Repository: NETMF/llilum Branch: dev Commit: 7ac7669fe205 Files: 3891 Total size: 46.4 MB Directory structure: gitextract_v7iyasqz/ ├── .gitattributes ├── .gitignore ├── BuildEnv.props ├── LICENSE ├── LlilumSDK/ │ ├── GenerateFrameworkList/ │ │ ├── App.config │ │ ├── GenerateFrameworkList.csproj │ │ ├── Program.cs │ │ └── Properties/ │ │ └── AssemblyInfo.cs │ ├── LlilumSDK/ │ │ ├── BoardConfigurations.wxs │ │ ├── Directories.wxs │ │ ├── HarvestDirectories.targets │ │ ├── LlilumSDK.wixproj │ │ ├── LlilumSDKLic.rtf │ │ ├── LlvmTools.wxs │ │ ├── MarkComponentsWin32.xslt │ │ ├── PreConditions.wxi │ │ ├── Product.wxs │ │ ├── ReferenceAssemblies.wxs │ │ └── ToolsBin.wxs │ ├── LlilumSDK.sln │ └── readme.md ├── LlvmApplication.props ├── README.md ├── SDKHelpers/ │ ├── RunLillium.cmd │ ├── output/ │ │ ├── CompileAndLink.bat │ │ ├── RunLLVM.bat │ │ └── makefile │ └── setenv.cmd ├── Samples/ │ ├── I2cTemperatureSensor/ │ │ ├── I2cTemperatureSensor/ │ │ │ ├── Managed/ │ │ │ │ ├── Managed.csproj │ │ │ │ ├── Program.cs │ │ │ │ ├── Properties/ │ │ │ │ │ └── AssemblyInfo.cs │ │ │ │ └── README.txt │ │ │ └── Native/ │ │ │ ├── Native.vcxproj │ │ │ ├── Source.cpp │ │ │ ├── mbed_simple_K64F.FrontEndConfig │ │ │ ├── mbed_simple_LPC1768.FrontEndConfig │ │ │ ├── mbed_simple_STM32L152.FrontEndConfig │ │ │ └── pch.h │ │ └── I2cTemperatureSensor.sln │ ├── README.txt │ └── SpiDisplay/ │ ├── SpiDisplay/ │ │ ├── Managed/ │ │ │ ├── Managed.csproj │ │ │ ├── Program.cs │ │ │ ├── Properties/ │ │ │ │ └── AssemblyInfo.cs │ │ │ └── README.txt │ │ └── Native/ │ │ ├── Native.vcxproj │ │ ├── Source.cpp │ │ ├── mbed_simple_K64F.FrontEndConfig │ │ ├── mbed_simple_LPC1768.FrontEndConfig │ │ ├── mbed_simple_STM32L152.FrontEndConfig │ │ └── pch.h │ └── SpiDisplay.sln ├── VisualStudio/ │ ├── LlilumApplicationType/ │ │ └── Llilum/ │ │ ├── 1.0/ │ │ │ ├── 1033/ │ │ │ │ ├── AndroidDebugger.xml │ │ │ │ ├── Llilum.xml │ │ │ │ ├── ar.xml │ │ │ │ ├── as.xml │ │ │ │ ├── clang.xml │ │ │ │ ├── clanglink.xml │ │ │ │ ├── general_android.xml │ │ │ │ ├── general_makefile_android.xml │ │ │ │ └── nmake_android.xml │ │ │ ├── Android.Common.props │ │ │ ├── Android.Common.targets │ │ │ ├── Android.Makefile.targets │ │ │ ├── Android.NDK.props │ │ │ ├── Android.STL.props │ │ │ ├── Android.Tools.props │ │ │ ├── Default.props │ │ │ └── Platforms/ │ │ │ ├── ARM/ │ │ │ │ ├── Platform.Default.props │ │ │ │ ├── Platform.props │ │ │ │ ├── Platform.targets │ │ │ │ └── PlatformToolsets/ │ │ │ │ └── Gcc/ │ │ │ │ ├── ImportAfter/ │ │ │ │ │ ├── armasm.props │ │ │ │ │ └── armasm.targets │ │ │ │ ├── Toolset.props │ │ │ │ └── Toolset.targets │ │ │ ├── Llilum_K64F.props │ │ │ ├── Llilum_LPC1768.props │ │ │ ├── Llilum_STM32F091.props │ │ │ ├── Llilum_STM32F401.props │ │ │ ├── Llilum_STM32F411.props │ │ │ ├── Llilum_STM32L152.props │ │ │ └── mbed-rtos.props │ │ └── Default.props │ └── LlilumProjectType/ │ ├── LlilumApplication/ │ │ ├── LlilumApplication.ProjectTemplate/ │ │ │ ├── LlilumApplication.ProjectTemplate.csproj │ │ │ ├── LlilumApplication.vstemplate │ │ │ ├── LlilumManaged/ │ │ │ │ ├── Managed.csproj │ │ │ │ ├── MyTemplate.vstemplate │ │ │ │ ├── Program.cs │ │ │ │ └── Properties/ │ │ │ │ └── AssemblyInfo.cs │ │ │ ├── LlilumNative/ │ │ │ │ ├── MyTemplate.vstemplate │ │ │ │ ├── Native.vcxproj │ │ │ │ ├── Source.cpp │ │ │ │ ├── mbed_simple_K64F.FrontEndConfig │ │ │ │ ├── mbed_simple_LPC1768.FrontEndConfig │ │ │ │ ├── mbed_simple_STM32F091.FrontEndConfig │ │ │ │ ├── mbed_simple_STM32F401.FrontEndConfig │ │ │ │ ├── mbed_simple_STM32F411.FrontEndConfig │ │ │ │ ├── mbed_simple_STM32L152.FrontEndConfig │ │ │ │ └── pch.h │ │ │ └── Properties/ │ │ │ └── AssemblyInfo.cs │ │ └── LlilumApplication.ProjectType/ │ │ ├── BuildSystem/ │ │ │ ├── DeployedBuildSystem/ │ │ │ │ ├── CustomProject.Default.props │ │ │ │ ├── CustomProject.props │ │ │ │ ├── CustomProject.targets │ │ │ │ └── CustomProjectCs.targets │ │ │ └── Rules/ │ │ │ ├── CustomPropertyPage.xaml │ │ │ ├── LlilumDebugger.xaml │ │ │ ├── ProjectItemsSchema.xaml │ │ │ └── debugger_general.xaml │ │ ├── Key.snk │ │ ├── LlilumApplication.ProjectType.csproj │ │ ├── LlilumDebuggerLaunchProvider.cs │ │ ├── LlilumDeployProvider.cs │ │ ├── LlilumHelpers.cs │ │ ├── MITLicense.txt │ │ ├── MyConfiguredProject.cs │ │ ├── MyUnconfiguredProject.cs │ │ ├── ProjectProperties.cs │ │ ├── Properties/ │ │ │ └── AssemblyInfo.cs │ │ ├── VSPackage.resx │ │ ├── VsPackage.cs │ │ ├── app.config │ │ ├── packages.config │ │ └── source.extension.vsixmanifest │ ├── LlilumApplication.sln │ ├── Microsoft.MIEngine.CoreRegisters.ARM/ │ │ ├── Converters/ │ │ │ ├── ExceptionNumberConverter.cs │ │ │ ├── IntAsBinaryStringConverter.cs │ │ │ └── IsNullValueConverter.cs │ │ ├── CoreRegistersWindow.cs │ │ ├── CoreRegistersWindowCommand.cs │ │ ├── CoreRegistersWindowControl.xaml │ │ ├── CoreRegistersWindowControl.xaml.cs │ │ ├── Key.snk │ │ ├── MIEngineResultsParsers.cs │ │ ├── MITLicense.txt │ │ ├── Microsoft.MIEngine.CoreRegisters.ARM.csproj │ │ ├── Properties/ │ │ │ └── AssemblyInfo.cs │ │ ├── VSPackage.resx │ │ ├── ViewModel/ │ │ │ ├── CoreRegisterViewModel.cs │ │ │ ├── CoreRegistersViewModel.cs │ │ │ └── XpsrRegisterDetailsViewModel.cs │ │ ├── VsPackage.cs │ │ ├── VsPackage.vsct │ │ ├── packages.config │ │ └── source.extension.vsixmanifest │ └── Microsoft.MIEngine.CoreRegisters.ARMTests/ │ ├── IntAsBinaryStringConverterTests.cs │ ├── MIEngineResultParsersTests.cs │ ├── Microsoft.MIEngine.CoreRegisters.ARMTests.csproj │ ├── Properties/ │ │ └── AssemblyInfo.cs │ └── packages.config ├── Zelig/ │ ├── BoardConfigurations/ │ │ ├── BoardConfigurations.sln │ │ ├── K64F/ │ │ │ ├── Board/ │ │ │ │ ├── HardwareModel/ │ │ │ │ │ ├── Board.cs │ │ │ │ │ ├── Device.cs │ │ │ │ │ ├── Drivers/ │ │ │ │ │ │ ├── ContextSwitchTimer.cs │ │ │ │ │ │ ├── InterruptController.cs │ │ │ │ │ │ └── SystemTimer.cs │ │ │ │ │ ├── GPIO.cs │ │ │ │ │ ├── HardwareProviders/ │ │ │ │ │ │ ├── GpioProvider.cs │ │ │ │ │ │ ├── I2cProvider.cs │ │ │ │ │ │ ├── NetworkInterfaceProvider.cs │ │ │ │ │ │ └── SpiProvider.cs │ │ │ │ │ ├── HardwareProvidersUwp/ │ │ │ │ │ │ ├── AdcProviderUwp.cs │ │ │ │ │ │ ├── I2cProviderUwp.cs │ │ │ │ │ │ ├── PwmProviderUwp.cs │ │ │ │ │ │ └── SpiProviderUwp.cs │ │ │ │ │ ├── NVIC.cs │ │ │ │ │ ├── Peripherals.cs │ │ │ │ │ └── Processor.cs │ │ │ │ ├── K64F.csproj │ │ │ │ ├── Properties/ │ │ │ │ │ └── AssemblyInfo.cs │ │ │ │ └── SystemServices/ │ │ │ │ ├── GarbageCollectionManager.cs │ │ │ │ ├── ThreadManager.cs │ │ │ │ └── TimerPool.cs │ │ │ └── Configuration/ │ │ │ ├── Configuration.cs │ │ │ ├── K64F.FrontEndConfig │ │ │ ├── K64FConfiguration.csproj │ │ │ └── Properties/ │ │ │ └── AssemblyInfo.cs │ │ ├── LPC1768/ │ │ │ ├── Board/ │ │ │ │ ├── HardwareModel/ │ │ │ │ │ ├── Board.cs │ │ │ │ │ ├── Device.cs │ │ │ │ │ ├── Drivers/ │ │ │ │ │ │ ├── ContextSwitchTimer.cs │ │ │ │ │ │ ├── InterruptController.cs │ │ │ │ │ │ └── SystemTimer.cs │ │ │ │ │ ├── GPIO.cs │ │ │ │ │ ├── HardwareProviders/ │ │ │ │ │ │ ├── GpioProvider.cs │ │ │ │ │ │ ├── I2cProvider.cs │ │ │ │ │ │ └── SpiProvider.cs │ │ │ │ │ ├── HardwareProvidersUwp/ │ │ │ │ │ │ ├── AdcProviderUwp.cs │ │ │ │ │ │ ├── I2cProviderUwp.cs │ │ │ │ │ │ ├── PwmProviderUwp.cs │ │ │ │ │ │ └── SpiProviderUwp.cs │ │ │ │ │ ├── NVIC.cs │ │ │ │ │ ├── Peripherals.cs │ │ │ │ │ └── Processor.cs │ │ │ │ ├── LPC1768.csproj │ │ │ │ ├── Properties/ │ │ │ │ │ └── AssemblyInfo.cs │ │ │ │ └── SystemServices/ │ │ │ │ ├── GarbageCollectionManager.cs │ │ │ │ ├── ThreadManager.cs │ │ │ │ └── TimerPool.cs │ │ │ └── Configuration/ │ │ │ ├── Configuration.cs │ │ │ ├── LPC1768.FrontEndConfig │ │ │ ├── LPC1768Configuration.csproj │ │ │ └── Properties/ │ │ │ └── AssemblyInfo.cs │ │ ├── STM32F091/ │ │ │ ├── Board/ │ │ │ │ ├── HardwareModel/ │ │ │ │ │ ├── Board.cs │ │ │ │ │ ├── Device.cs │ │ │ │ │ ├── Drivers/ │ │ │ │ │ │ ├── ContextSwitchTimer.cs │ │ │ │ │ │ ├── InterruptController.cs │ │ │ │ │ │ └── SystemTimer.cs │ │ │ │ │ ├── GPIO.cs │ │ │ │ │ ├── HardwareProviders/ │ │ │ │ │ │ ├── GpioProvider.cs │ │ │ │ │ │ ├── I2cProvider.cs │ │ │ │ │ │ └── SpiProvider.cs │ │ │ │ │ ├── HardwareProvidersUwp/ │ │ │ │ │ │ ├── AdcProviderUwp.cs │ │ │ │ │ │ ├── I2cProviderUwp.cs │ │ │ │ │ │ ├── PwmProviderUwp.cs │ │ │ │ │ │ └── SpiProviderUwp.cs │ │ │ │ │ ├── NVIC.cs │ │ │ │ │ ├── Peripherals.cs │ │ │ │ │ └── Processor.cs │ │ │ │ ├── Properties/ │ │ │ │ │ └── AssemblyInfo.cs │ │ │ │ ├── STM32F091.csproj │ │ │ │ └── SystemServices/ │ │ │ │ ├── GarbageCollectionManager.cs │ │ │ │ ├── ThreadManager.cs │ │ │ │ └── TimerPool.cs │ │ │ └── Configuration/ │ │ │ ├── Configuration.cs │ │ │ ├── Properties/ │ │ │ │ └── AssemblyInfo.cs │ │ │ ├── STM32F091.FrontEndConfig │ │ │ └── STM32F091Configuration.csproj │ │ ├── STM32F401/ │ │ │ ├── Board/ │ │ │ │ ├── HardwareModel/ │ │ │ │ │ ├── Board.cs │ │ │ │ │ ├── Device.cs │ │ │ │ │ ├── Drivers/ │ │ │ │ │ │ ├── ContextSwitchTimer.cs │ │ │ │ │ │ ├── InterruptController.cs │ │ │ │ │ │ └── SystemTimer.cs │ │ │ │ │ ├── GPIO.cs │ │ │ │ │ ├── HardwareProviders/ │ │ │ │ │ │ ├── GpioProvider.cs │ │ │ │ │ │ ├── I2cProvider.cs │ │ │ │ │ │ └── SpiProvider.cs │ │ │ │ │ ├── HardwareProvidersUwp/ │ │ │ │ │ │ ├── AdcProviderUwp.cs │ │ │ │ │ │ ├── I2cProviderUwp.cs │ │ │ │ │ │ ├── PwmProviderUwp.cs │ │ │ │ │ │ └── SpiProviderUwp.cs │ │ │ │ │ ├── NVIC.cs │ │ │ │ │ ├── Peripherals.cs │ │ │ │ │ └── Processor.cs │ │ │ │ ├── Properties/ │ │ │ │ │ └── AssemblyInfo.cs │ │ │ │ ├── STM32F401.csproj │ │ │ │ └── SystemServices/ │ │ │ │ ├── GarbageCollectionManager.cs │ │ │ │ ├── ThreadManager.cs │ │ │ │ └── TimerPool.cs │ │ │ └── Configuration/ │ │ │ ├── Configuration.cs │ │ │ ├── Properties/ │ │ │ │ └── AssemblyInfo.cs │ │ │ ├── STM32F401.FrontEndConfig │ │ │ └── STM32F401Configuration.csproj │ │ ├── STM32F411/ │ │ │ ├── Board/ │ │ │ │ ├── HardwareModel/ │ │ │ │ │ ├── Board.cs │ │ │ │ │ ├── Device.cs │ │ │ │ │ ├── Drivers/ │ │ │ │ │ │ ├── ContextSwitchTimer.cs │ │ │ │ │ │ ├── InterruptController.cs │ │ │ │ │ │ └── SystemTimer.cs │ │ │ │ │ ├── GPIO.cs │ │ │ │ │ ├── HardwareProviders/ │ │ │ │ │ │ ├── GpioProvider.cs │ │ │ │ │ │ ├── I2cProvider.cs │ │ │ │ │ │ └── SpiProvider.cs │ │ │ │ │ ├── HardwareProvidersUwp/ │ │ │ │ │ │ ├── AdcProviderUwp.cs │ │ │ │ │ │ ├── I2cProviderUwp.cs │ │ │ │ │ │ ├── PwmProviderUwp.cs │ │ │ │ │ │ └── SpiProviderUwp.cs │ │ │ │ │ ├── NVIC.cs │ │ │ │ │ ├── Peripherals.cs │ │ │ │ │ └── Processor.cs │ │ │ │ ├── Properties/ │ │ │ │ │ └── AssemblyInfo.cs │ │ │ │ ├── STM32F411.csproj │ │ │ │ └── SystemServices/ │ │ │ │ ├── GarbageCollectionManager.cs │ │ │ │ ├── ThreadManager.cs │ │ │ │ └── TimerPool.cs │ │ │ └── Configuration/ │ │ │ ├── Configuration.cs │ │ │ ├── Properties/ │ │ │ │ └── AssemblyInfo.cs │ │ │ ├── STM32F411.FrontEndConfig │ │ │ └── STM32F411Configuration.csproj │ │ ├── STM32L152/ │ │ │ ├── Board/ │ │ │ │ ├── HardwareModel/ │ │ │ │ │ ├── Board.cs │ │ │ │ │ ├── Device.cs │ │ │ │ │ ├── Drivers/ │ │ │ │ │ │ ├── ContextSwitchTimer.cs │ │ │ │ │ │ ├── InterruptController.cs │ │ │ │ │ │ └── SystemTimer.cs │ │ │ │ │ ├── GPIO.cs │ │ │ │ │ ├── HardwareProviders/ │ │ │ │ │ │ ├── GpioProvider.cs │ │ │ │ │ │ ├── I2cProvider.cs │ │ │ │ │ │ └── SpiProvider.cs │ │ │ │ │ ├── HardwareProvidersUwp/ │ │ │ │ │ │ ├── AdcProviderUwp.cs │ │ │ │ │ │ ├── I2cProviderUwp.cs │ │ │ │ │ │ ├── PwmProviderUwp.cs │ │ │ │ │ │ └── SpiProviderUwp.cs │ │ │ │ │ ├── NVIC.cs │ │ │ │ │ ├── Peripherals.cs │ │ │ │ │ └── Processor.cs │ │ │ │ ├── Properties/ │ │ │ │ │ └── AssemblyInfo.cs │ │ │ │ ├── STM32L152.csproj │ │ │ │ └── SystemServices/ │ │ │ │ ├── GarbageCollectionManager.cs │ │ │ │ ├── ThreadManager.cs │ │ │ │ └── TimerPool.cs │ │ │ └── Configuration/ │ │ │ ├── Configuration.cs │ │ │ ├── Properties/ │ │ │ │ └── AssemblyInfo.cs │ │ │ ├── STM32L152.FrontEndConfig │ │ │ └── STM32L152Configuration.csproj │ │ └── Win32/ │ │ └── Configuration/ │ │ ├── Configuration.cs │ │ ├── Properties/ │ │ │ └── AssemblyInfo.cs │ │ ├── Win32.FrontEndConfig │ │ └── Win32Configuration.csproj │ ├── LLVM2IR_results/ │ │ └── mbed/ │ │ ├── common_files/ │ │ │ └── temporary_helper.c │ │ ├── mbed_rtos/ │ │ │ ├── GpioInterrupts/ │ │ │ │ ├── Makefile │ │ │ │ ├── buildK64F.bat │ │ │ │ ├── buildLPC1768.bat │ │ │ │ └── main.cpp │ │ │ └── ReadMe.txt │ │ ├── simple/ │ │ │ ├── .gdbinit │ │ │ ├── DebugOptions.xml │ │ │ ├── build.bat │ │ │ ├── buildK64F.bat │ │ │ ├── buildLPC1768.bat │ │ │ ├── buildSTM32F091.bat │ │ │ ├── buildSTM32F401.bat │ │ │ ├── buildSTM32F411.bat │ │ │ ├── buildSTM32L152.bat │ │ │ ├── buildWin32.bat │ │ │ ├── buildmake.bat │ │ │ ├── debug.bat │ │ │ ├── debugK64F.bat │ │ │ ├── debugLPC1768.bat │ │ │ ├── debugSTM32F091.bat │ │ │ ├── debugSTM32F401.bat │ │ │ ├── debugSTM32F411.bat │ │ │ ├── debugSTM32L152.bat │ │ │ ├── deploy.bat │ │ │ ├── deployK64F.bat │ │ │ ├── deployLPC1768.bat │ │ │ ├── deploySTM32F091.bat │ │ │ ├── deploySTM32F401.bat │ │ │ ├── deploySTM32F411.bat │ │ │ ├── deploySTM32L152.bat │ │ │ ├── helpers.h │ │ │ └── makefile │ │ └── test/ │ │ ├── build.bat │ │ ├── buildK64F.bat │ │ ├── buildLPC1768.bat │ │ ├── debug.bat │ │ ├── debugK64F.bat │ │ ├── debugLPC1768.bat │ │ ├── deploy.bat │ │ ├── deployK64F.bat │ │ ├── deployLPC1768.bat │ │ └── makefile │ ├── Zelig/ │ │ ├── CompileTime/ │ │ │ ├── AnalysisTools/ │ │ │ │ ├── IRCompare/ │ │ │ │ │ ├── IRCompare.csproj │ │ │ │ │ ├── MainForm.Designer.cs │ │ │ │ │ ├── MainForm.cs │ │ │ │ │ ├── MainForm.resx │ │ │ │ │ ├── MethodViewer.Designer.cs │ │ │ │ │ ├── MethodViewer.cs │ │ │ │ │ ├── MethodViewer.resx │ │ │ │ │ ├── Program.cs │ │ │ │ │ ├── Properties/ │ │ │ │ │ │ ├── AssemblyInfo.cs │ │ │ │ │ │ ├── Resources.Designer.cs │ │ │ │ │ │ ├── Resources.resx │ │ │ │ │ │ ├── Settings.Designer.cs │ │ │ │ │ │ └── Settings.settings │ │ │ │ │ ├── RenderMethod.cs │ │ │ │ │ └── app.config │ │ │ │ ├── IRViewer/ │ │ │ │ │ ├── IRViewer.csproj │ │ │ │ │ ├── MainForm.Designer.cs │ │ │ │ │ ├── MainForm.cs │ │ │ │ │ ├── MainForm.resx │ │ │ │ │ ├── Parser.cs │ │ │ │ │ ├── Program.cs │ │ │ │ │ ├── Properties/ │ │ │ │ │ │ ├── AssemblyInfo.cs │ │ │ │ │ │ ├── Resources.Designer.cs │ │ │ │ │ │ ├── Resources.resx │ │ │ │ │ │ ├── Settings.Designer.cs │ │ │ │ │ │ └── Settings.settings │ │ │ │ │ └── SourceCodeTracker.cs │ │ │ │ └── InequalityGraphVisualization/ │ │ │ │ ├── GraphForm.Designer.cs │ │ │ │ ├── GraphForm.cs │ │ │ │ ├── GraphForm.resx │ │ │ │ ├── InequalityGraphVisualization.csproj │ │ │ │ ├── Properties/ │ │ │ │ │ └── AssemblyInfo.cs │ │ │ │ └── Viewer.cs │ │ │ ├── CodeGenerator/ │ │ │ │ ├── CodeGenerator.UnitTest/ │ │ │ │ │ ├── BaseTester.cs │ │ │ │ │ ├── Bench.cs │ │ │ │ │ ├── CodeGenerationTester.cs │ │ │ │ │ ├── CodeGenerator.UnitTest.csproj │ │ │ │ │ ├── GenericInstantiationClosureTester.cs │ │ │ │ │ ├── Properties/ │ │ │ │ │ │ └── AssemblyInfo.cs │ │ │ │ │ ├── SerializationSpeedTester.cs │ │ │ │ │ ├── TypeSystemPopulationTester.cs │ │ │ │ │ └── app.config │ │ │ │ ├── CodeTransformation/ │ │ │ │ │ ├── Abstractions/ │ │ │ │ │ │ ├── CallingConvention.cs │ │ │ │ │ │ ├── ExternalCallContext.cs │ │ │ │ │ │ ├── PlacementRequirements.cs │ │ │ │ │ │ ├── Platform.cs │ │ │ │ │ │ ├── RegisterClass.cs │ │ │ │ │ │ └── RegisterDescriptor.cs │ │ │ │ │ ├── Annotations/ │ │ │ │ │ │ ├── InliningPathAnnotation.cs │ │ │ │ │ │ ├── RegisterAllocationConstraintAnnotation.cs │ │ │ │ │ │ └── RegisterCouplingConstraintAnnotation.cs │ │ │ │ │ ├── BitFieldDefinition.cs │ │ │ │ │ ├── CodeTransformation.csproj │ │ │ │ │ ├── CompilationSteps/ │ │ │ │ │ │ ├── Attributes/ │ │ │ │ │ │ │ ├── AbstractHandlerAttribute.cs │ │ │ │ │ │ │ ├── CallClosureHandlerAttribute.cs │ │ │ │ │ │ │ ├── CallToWellKnownMethodHandlerAttribute.cs │ │ │ │ │ │ │ ├── CustomAttributeHandlerAttribute.cs │ │ │ │ │ │ │ ├── CustomAttributeNotificationAttribute.cs │ │ │ │ │ │ │ ├── MaximumOperatorLevelAfterPhaseExecutionAttribute.cs │ │ │ │ │ │ │ ├── NewEntityNotificationAttribute.cs │ │ │ │ │ │ │ ├── OperatorArgumentHandlerAttribute.cs │ │ │ │ │ │ │ ├── OperatorHandlerAttribute.cs │ │ │ │ │ │ │ ├── OptimizationHandlerAttribute.cs │ │ │ │ │ │ │ ├── PhaseDisabledAttribute.cs │ │ │ │ │ │ │ ├── PhaseFilterAttribute.cs │ │ │ │ │ │ │ ├── PhaseLimitAttribute.cs │ │ │ │ │ │ │ ├── PhaseOrderingAttribute.cs │ │ │ │ │ │ │ ├── PostFlowGraphHandlerAttribute.cs │ │ │ │ │ │ │ ├── PostPhaseHandlerAttribute.cs │ │ │ │ │ │ │ ├── PreFlowGraphHandlerAttribute.cs │ │ │ │ │ │ │ ├── PrePhaseHandlerAttribute.cs │ │ │ │ │ │ │ ├── WellKnownFieldHandlerAttribute.cs │ │ │ │ │ │ │ ├── WellKnownMethodHandlerAttribute.cs │ │ │ │ │ │ │ └── WellKnownTypeHandlerAttribute.cs │ │ │ │ │ │ ├── Controller.cs │ │ │ │ │ │ ├── Handlers/ │ │ │ │ │ │ │ ├── MethodTransformations.cs │ │ │ │ │ │ │ ├── OperatorHandlers_ConvertUnsupportedOperatorsToMethodCalls.cs │ │ │ │ │ │ │ ├── OperatorHandlers_ExpandAggregateTypes.cs │ │ │ │ │ │ │ ├── OperatorHandlers_FromImplicitToExplicitExceptions.cs │ │ │ │ │ │ │ ├── OperatorHandlers_HighLevel.cs │ │ │ │ │ │ │ ├── OperatorHandlers_HighLevelToMidLevel.cs │ │ │ │ │ │ │ ├── OperatorHandlers_MidLevelToLowLevel.cs │ │ │ │ │ │ │ ├── OperatorHandlers_ReferenceCountingGarbageCollection.cs │ │ │ │ │ │ │ ├── Optimizations.cs │ │ │ │ │ │ │ ├── ProtectRequiredEntities.cs │ │ │ │ │ │ │ ├── SoftwareFloatingPoint.cs │ │ │ │ │ │ │ ├── WellKnownFieldHandlers.cs │ │ │ │ │ │ │ └── WellKnownMethodHandlers.cs │ │ │ │ │ │ ├── PhaseDrivers/ │ │ │ │ │ │ │ ├── ApplyClassExtensions.cs │ │ │ │ │ │ │ ├── CallGraph.cs │ │ │ │ │ │ │ ├── CallsDatabase.cs │ │ │ │ │ │ │ ├── ComputeCallsClosure.cs │ │ │ │ │ │ │ ├── DelegationCache.cs │ │ │ │ │ │ │ ├── DetectFieldInvariants.cs │ │ │ │ │ │ │ ├── ImplementExternalMethods.cs │ │ │ │ │ │ │ ├── ImplementInternalMethods.cs │ │ │ │ │ │ │ ├── ImplementInternalMethods_Delegate.cs │ │ │ │ │ │ │ ├── ImplementInternalMethods_ExternalMethodStub.cs │ │ │ │ │ │ │ ├── ImplementInternalMethods_ObjectEquals.cs │ │ │ │ │ │ │ ├── ImplementInternalMethods_SingletonFactory.cs │ │ │ │ │ │ │ ├── OptimizationsPhaseExecution.cs │ │ │ │ │ │ │ ├── ParallelTransformationsHandler.cs │ │ │ │ │ │ │ ├── PhaseDriver.cs │ │ │ │ │ │ │ ├── PhaseExecution.cs │ │ │ │ │ │ │ └── SingleMethodPhaseExecution.cs │ │ │ │ │ │ └── Phases/ │ │ │ │ │ │ ├── AllocateRegisters.cs │ │ │ │ │ │ ├── ApplyClassExtensions.cs │ │ │ │ │ │ ├── ApplyConfigurationSettings.cs │ │ │ │ │ │ ├── CollectRegisterAllocationConstraints.cs │ │ │ │ │ │ ├── CompleteImplementationOfInternalMethods.cs │ │ │ │ │ │ ├── ComputeCallsClosure.cs │ │ │ │ │ │ ├── ConvertToSSA.cs │ │ │ │ │ │ ├── ConvertUnsupportedOperatorsToMethodCalls.cs │ │ │ │ │ │ ├── CrossReferenceTypeSystem.cs │ │ │ │ │ │ ├── DetectNonImplementedInternalCalls.cs │ │ │ │ │ │ ├── Done.cs │ │ │ │ │ │ ├── EstimateTypeSystemReduction.cs │ │ │ │ │ │ ├── ExpandAggregateTypes.cs │ │ │ │ │ │ ├── FromImplicitToExplicitExceptions.cs │ │ │ │ │ │ ├── FuseOperators.cs │ │ │ │ │ │ ├── GenerateImage.cs │ │ │ │ │ │ ├── HighLevelToMidLevelConversion.cs │ │ │ │ │ │ ├── HighLevelTransformations.cs │ │ │ │ │ │ ├── LayoutTypes.cs │ │ │ │ │ │ ├── MidLevelToLowLevelConversion.cs │ │ │ │ │ │ ├── Optimizations.cs │ │ │ │ │ │ ├── OrderStaticConstructors.cs │ │ │ │ │ │ ├── PrepareExternalMethods.cs │ │ │ │ │ │ ├── PrepareForRegisterAllocation.cs │ │ │ │ │ │ ├── PrepareImplementationOfInternalMethods.cs │ │ │ │ │ │ ├── PropagateCompilationConstraints.cs │ │ │ │ │ │ ├── ReduceNumberOfTemporaries.cs │ │ │ │ │ │ ├── ReduceTypeSystem.cs │ │ │ │ │ │ ├── ReferenceCountingGarbageCollection.cs │ │ │ │ │ │ ├── ResourceManagerOptimizations.cs │ │ │ │ │ │ ├── SplitComplexOperators.cs │ │ │ │ │ │ └── TransformFinallyBlocksIntoTryBlocks.cs │ │ │ │ │ ├── ControlFlowGraphState/ │ │ │ │ │ │ ├── ControlFlowGraphStateForCodeTransformation.cs │ │ │ │ │ │ ├── ControlFlowGraphStateForCodeTransformation_CompilationConstraintsLookup.cs │ │ │ │ │ │ ├── ControlFlowGraphStateForCodeTransformation_Dominance.cs │ │ │ │ │ │ ├── ControlFlowGraphStateForCodeTransformation_Liveness.cs │ │ │ │ │ │ ├── ControlFlowGraphStateForCodeTransformation_MapToMachine.cs │ │ │ │ │ │ ├── ControlFlowGraphStateForCodeTransformation_PostDominance.cs │ │ │ │ │ │ ├── ControlFlowGraphStateForCodeTransformation_PostOrderVisit.cs │ │ │ │ │ │ ├── ControlFlowGraphStateForCodeTransformation_PropertiesOfVariables.cs │ │ │ │ │ │ ├── ControlFlowGraphStateForCodeTransformation_ReachingDefinitions.cs │ │ │ │ │ │ ├── ControlFlowGraphStateForCodeTransformation_SpanningTree.cs │ │ │ │ │ │ ├── ControlFlowGraphStateForCodeTransformation_Trace.cs │ │ │ │ │ │ └── ControlFlowGraphStateForCodeTransformation_UseDefinitionChains.cs │ │ │ │ │ ├── DataFlow/ │ │ │ │ │ │ ├── ControlTree/ │ │ │ │ │ │ │ ├── Dominance.cs │ │ │ │ │ │ │ ├── GenericDepthFirst.cs │ │ │ │ │ │ │ ├── NaturalLoops.cs │ │ │ │ │ │ │ ├── PostDominance.cs │ │ │ │ │ │ │ ├── PostOrderVisit.cs │ │ │ │ │ │ │ └── SpanningTree.cs │ │ │ │ │ │ ├── LivenessAnalysis.cs │ │ │ │ │ │ └── ReachingDefinitions.cs │ │ │ │ │ ├── DataManager.cs │ │ │ │ │ ├── Expressions/ │ │ │ │ │ │ ├── ConditionCodeExpression.cs │ │ │ │ │ │ ├── LowLevelVariableExpression.cs │ │ │ │ │ │ ├── PhiVariableExpression.cs │ │ │ │ │ │ ├── PhysicalRegisterExpression.cs │ │ │ │ │ │ ├── PseudoRegisterExpression.cs │ │ │ │ │ │ ├── StackLocationExpression.cs │ │ │ │ │ │ └── TypedPhysicalRegisterExpression.cs │ │ │ │ │ ├── ExternalDataDescriptor.cs │ │ │ │ │ ├── ExternalMethodImporters/ │ │ │ │ │ │ ├── ArmElfContext.cs │ │ │ │ │ │ ├── ArmElfDataContext.cs │ │ │ │ │ │ └── ArmElfMethodContext.cs │ │ │ │ │ ├── ImageBuilders/ │ │ │ │ │ │ ├── CodeConstant.cs │ │ │ │ │ │ ├── CompilationState.cs │ │ │ │ │ │ ├── CompilationState_EmitCode.cs │ │ │ │ │ │ ├── CompilationState_Encoder.cs │ │ │ │ │ │ ├── CompilationState_ExceptionMap.cs │ │ │ │ │ │ ├── CompilationState_Scheduling.cs │ │ │ │ │ │ ├── Core.cs │ │ │ │ │ │ ├── ImageAnnotations/ │ │ │ │ │ │ │ ├── CodeRelocation.cs │ │ │ │ │ │ │ ├── DataRelocation.cs │ │ │ │ │ │ │ ├── ExternMethodCallRelocation.cs │ │ │ │ │ │ │ ├── ExternalDataRelocation.cs │ │ │ │ │ │ │ ├── GenericImageAnnotation.cs │ │ │ │ │ │ │ ├── ImageAnnotation.cs │ │ │ │ │ │ │ └── TrackVariableLifetime.cs │ │ │ │ │ │ └── SequentialRegion.cs │ │ │ │ │ ├── IntermediateRepresentationDumper.cs │ │ │ │ │ ├── LLVM/ │ │ │ │ │ │ ├── DebugInfoExtensions.cs │ │ │ │ │ │ ├── ITargetSectionOptions.cs │ │ │ │ │ │ ├── InliningPathAnnotationExtensions.cs │ │ │ │ │ │ ├── LLVMModuleManager.cs │ │ │ │ │ │ ├── LLVMModuleManager_Types.cs │ │ │ │ │ │ ├── SectionNameProvider.cs │ │ │ │ │ │ ├── TypeField.cs │ │ │ │ │ │ ├── ValueExtensions.cs │ │ │ │ │ │ ├── _BasicBlock.cs │ │ │ │ │ │ ├── _Function.cs │ │ │ │ │ │ ├── _Module.cs │ │ │ │ │ │ └── _Type.cs │ │ │ │ │ ├── Operators/ │ │ │ │ │ │ ├── BinaryOperatorWithCarryIn.cs │ │ │ │ │ │ ├── BinaryOperatorWithCarryInAndOut.cs │ │ │ │ │ │ ├── BinaryOperatorWithCarryOut.cs │ │ │ │ │ │ ├── BitTestOperator.cs │ │ │ │ │ │ ├── Calls/ │ │ │ │ │ │ │ ├── DirectSubroutineOperator.cs │ │ │ │ │ │ │ ├── IndirectSubroutineOperator.cs │ │ │ │ │ │ │ └── SubroutineOperator.cs │ │ │ │ │ │ ├── CompareOperator.cs │ │ │ │ │ │ ├── ConditionalCompareOperator.cs │ │ │ │ │ │ ├── Control/ │ │ │ │ │ │ │ └── ConditionCodeControlOperator.cs │ │ │ │ │ │ ├── InitialValueOperator.cs │ │ │ │ │ │ ├── LongCompareOperator.cs │ │ │ │ │ │ ├── NewConstraintOperator.cs │ │ │ │ │ │ ├── PhiOperator.cs │ │ │ │ │ │ ├── PiOperator.cs │ │ │ │ │ │ ├── SetIfConditionIsTrueOperator.cs │ │ │ │ │ │ └── UnaryOperatorWithCarryOut.cs │ │ │ │ │ ├── Properties/ │ │ │ │ │ │ └── AssemblyInfo.cs │ │ │ │ │ ├── SourceCodeTracker.cs │ │ │ │ │ ├── TransformationContextForCodeTransformation.cs │ │ │ │ │ ├── Transformations/ │ │ │ │ │ │ ├── CommonMethodRedundancyElimination.cs │ │ │ │ │ │ ├── ConstraintSystemCollector.cs │ │ │ │ │ │ ├── ConvertToLandingPads.cs │ │ │ │ │ │ ├── GlobalCopyPropagation.cs │ │ │ │ │ │ ├── GlobalRegisterAllocation.cs │ │ │ │ │ │ ├── InlineCall.cs │ │ │ │ │ │ ├── InlineScalars.cs │ │ │ │ │ │ ├── MergeExtendedBasicBlocks.cs │ │ │ │ │ │ ├── PerformClassExtension.cs │ │ │ │ │ │ ├── ReduceNumberOfTemporaries.cs │ │ │ │ │ │ ├── RemoveDeadCode.cs │ │ │ │ │ │ ├── RemoveSimpleIndirections.cs │ │ │ │ │ │ ├── SimplifyConditionCodeChecks.cs │ │ │ │ │ │ ├── SplitBasicBlocksAtExceptionSites.cs │ │ │ │ │ │ ├── StaticSingleAssignmentForm.cs │ │ │ │ │ │ ├── TransformFinallyBlocksIntoTryBlocks.cs │ │ │ │ │ │ └── TypeSystemIntrospection/ │ │ │ │ │ │ ├── CollectUsageContext.cs │ │ │ │ │ │ ├── LocateFieldsInCode.cs │ │ │ │ │ │ ├── LocateUsageInCode.cs │ │ │ │ │ │ ├── RemapTypeSystem.cs │ │ │ │ │ │ ├── ReverseIndexTypeSystem.cs │ │ │ │ │ │ ├── ScanCode.cs │ │ │ │ │ │ ├── ScanCodeWithCallback.cs │ │ │ │ │ │ └── ScanTypeSystem.cs │ │ │ │ │ ├── TypeSystemForCodeTransformation.cs │ │ │ │ │ ├── TypeSystemForCodeTransformation_Notifications.cs │ │ │ │ │ └── TypeSystemSerializer.cs │ │ │ │ ├── FrontEnd/ │ │ │ │ │ ├── Bench.cs │ │ │ │ │ ├── FrontEnd.csproj │ │ │ │ │ ├── Legacy/ │ │ │ │ │ │ ├── NohauLPC3180Loader.FrontEndConfig │ │ │ │ │ │ ├── VoxSoloFormFactorLoader.FrontEndConfig │ │ │ │ │ │ ├── VoxSolo_Bootstrap_FF.FrontEndConfig │ │ │ │ │ │ ├── VoxSolo_Bootstrap_NXP.FrontEndConfig │ │ │ │ │ │ ├── VoxSolo_Tester_FF.FrontEndConfig │ │ │ │ │ │ ├── VoxSolo_Tester_NXP.FrontEndConfig │ │ │ │ │ │ ├── VoxSolo_UnitTest_FF.FrontEndConfig │ │ │ │ │ │ ├── VoxSolo_UnitTest_NXP.FrontEndConfig │ │ │ │ │ │ ├── iMote2Loader.FrontEndConfig │ │ │ │ │ │ ├── iMoteQuickTest_Tester.FrontEndConfig │ │ │ │ │ │ ├── mscorlib_unittest_FF.FrontEndConfig │ │ │ │ │ │ ├── mscorlib_unittest_NXP.FrontEndConfig │ │ │ │ │ │ ├── mscorlib_unittest_PXA.FrontEndConfig │ │ │ │ │ │ ├── tester_FF.FrontEndConfig │ │ │ │ │ │ ├── tester_NXP.FrontEndConfig │ │ │ │ │ │ └── tester_PXA.FrontEndConfig │ │ │ │ │ ├── Properties/ │ │ │ │ │ │ └── AssemblyInfo.cs │ │ │ │ │ ├── Test/ │ │ │ │ │ │ ├── Dhrystone_perf_test.FrontEndConfig │ │ │ │ │ │ ├── ExternalLinking_Tester.FrontEndConfig │ │ │ │ │ │ ├── FileSystemSample.FrontEndConfig │ │ │ │ │ │ ├── FileSystem_Tester.FrontEndConfig │ │ │ │ │ │ ├── LLVM_test.FrontEndConfig │ │ │ │ │ │ ├── Whetstone_perf_test.FrontEndConfig │ │ │ │ │ │ ├── crypto_perf_test.FrontEndConfig │ │ │ │ │ │ ├── mbed_gpio_test.FrontEndConfig │ │ │ │ │ │ ├── mbed_serialport_test.FrontEndConfig │ │ │ │ │ │ └── test.FrontEndConfig │ │ │ │ │ ├── mbed_common.FrontEndConfig │ │ │ │ │ ├── mbed_common_K64F.FrontEndConfig │ │ │ │ │ ├── mbed_common_LPC1768.FrontEndConfig │ │ │ │ │ ├── mbed_simple_HTTP_K64F.FrontEndConfig │ │ │ │ │ ├── mbed_simple_K64F.FrontEndConfig │ │ │ │ │ ├── mbed_simple_LPC1768.FrontEndConfig │ │ │ │ │ ├── mbed_simple_LPC1768_Tester.FrontEndConfig │ │ │ │ │ ├── mbed_simple_NETMF_LPC1768.FrontEndConfig │ │ │ │ │ ├── mbed_simple_NET_K64F.FrontEndConfig │ │ │ │ │ ├── mbed_simple_NET_K64F_Tester.FrontEndConfig │ │ │ │ │ ├── mbed_simple_STM32F091.FrontEndConfig │ │ │ │ │ ├── mbed_simple_STM32F401.FrontEndConfig │ │ │ │ │ ├── mbed_simple_STM32F411.FrontEndConfig │ │ │ │ │ ├── mbed_simple_STM32L152.FrontEndConfig │ │ │ │ │ ├── mbed_simple_Win32.FrontEndConfig │ │ │ │ │ └── mbed_simple_Win32_Tester.FrontEndConfig │ │ │ │ └── IntermediateRepresentation/ │ │ │ │ ├── Annotations/ │ │ │ │ │ ├── Annotation.cs │ │ │ │ │ ├── ArrayLengthAnnotation.cs │ │ │ │ │ ├── BlockCopyPropagationAnnotation.cs │ │ │ │ │ ├── DontRemoveAnnotation.cs │ │ │ │ │ ├── ExternalCallArgumentAnnotation.cs │ │ │ │ │ ├── FixedLengthArrayAnnotation.cs │ │ │ │ │ ├── IInliningPathAnnotation.cs │ │ │ │ │ ├── InvalidationAnnotation.cs │ │ │ │ │ ├── MemoryMappedPeripheralAnnotation.cs │ │ │ │ │ ├── NotNullAnnotation.cs │ │ │ │ │ ├── PostInvalidationAnnotation.cs │ │ │ │ │ └── PreInvalidationAnnotation.cs │ │ │ │ ├── BasicBlocks/ │ │ │ │ │ ├── BasicBlock.cs │ │ │ │ │ ├── BasicBlockEdge.cs │ │ │ │ │ ├── BasicBlockEdgeClass.cs │ │ │ │ │ ├── Cloning/ │ │ │ │ │ │ ├── CloneForwardGraph.cs │ │ │ │ │ │ ├── CloneForwardGraphButLinkToExceptionHandlers.cs │ │ │ │ │ │ ├── CloneSingleBasicBlock.cs │ │ │ │ │ │ └── CloningContext.cs │ │ │ │ │ ├── CompilationConstraints.cs │ │ │ │ │ ├── ControlFlowGraphState.cs │ │ │ │ │ ├── EntryBasicBlock.cs │ │ │ │ │ ├── ExceptionClause.cs │ │ │ │ │ ├── ExceptionHandlerBasicBlock.cs │ │ │ │ │ ├── ExitBasicBlock.cs │ │ │ │ │ └── NormalBasicBlock.cs │ │ │ │ ├── ByteCode/ │ │ │ │ │ ├── ByteCodeBlock.cs │ │ │ │ │ ├── ByteCodeConverter.cs │ │ │ │ │ ├── ByteCodeConverter_Helpers.cs │ │ │ │ │ └── ByteCodeConverter_ProcessInstruction.cs │ │ │ │ ├── Expressions/ │ │ │ │ │ ├── ArgumentVariableExpression.cs │ │ │ │ │ ├── ConstantExpression.cs │ │ │ │ │ ├── ExceptionObjectVariableExpression.cs │ │ │ │ │ ├── Expression.cs │ │ │ │ │ ├── LocalVariableExpression.cs │ │ │ │ │ ├── TemporaryVariableExpression.cs │ │ │ │ │ └── VariableExpression.cs │ │ │ │ ├── IIntermediateRepresentationDumper.cs │ │ │ │ ├── IntermediateRepresentation.csproj │ │ │ │ ├── Operators/ │ │ │ │ │ ├── AbstractAssignmentOperator.cs │ │ │ │ │ ├── AbstractBinaryOperator.cs │ │ │ │ │ ├── AbstractUnaryOperator.cs │ │ │ │ │ ├── BinaryOperator.cs │ │ │ │ │ ├── Call/ │ │ │ │ │ │ ├── AddActivationRecordEventOperator.cs │ │ │ │ │ │ ├── CallOperator.cs │ │ │ │ │ │ ├── ExternalCallOperator.cs │ │ │ │ │ │ ├── IndirectCallOperator.cs │ │ │ │ │ │ ├── InstanceCallOperator.cs │ │ │ │ │ │ └── StaticCallOperator.cs │ │ │ │ │ ├── Checks/ │ │ │ │ │ │ ├── NullCheckOperator.cs │ │ │ │ │ │ ├── OutOfBoundCheckOperator.cs │ │ │ │ │ │ └── OverflowCheckOperator.cs │ │ │ │ │ ├── CompareAndSetOperator.cs │ │ │ │ │ ├── CompilationConstraintsOperator.cs │ │ │ │ │ ├── Control/ │ │ │ │ │ │ ├── BinaryConditionalControlOperator.cs │ │ │ │ │ │ ├── CompareConditionalControlOperator.cs │ │ │ │ │ │ ├── ConditionalControlOperator.cs │ │ │ │ │ │ ├── ControlOperator.cs │ │ │ │ │ │ ├── DeadControlOperator.cs │ │ │ │ │ │ ├── EndFinallyControlOperator.cs │ │ │ │ │ │ ├── LeaveControlOperator.cs │ │ │ │ │ │ ├── MultiWayConditionalControlOperator.cs │ │ │ │ │ │ ├── ResumeUnwindOperator.cs │ │ │ │ │ │ ├── RethrowControlOperator.cs │ │ │ │ │ │ ├── ReturnControlOperator.cs │ │ │ │ │ │ ├── ThrowControlOperator.cs │ │ │ │ │ │ └── UnconditionalControlOperator.cs │ │ │ │ │ ├── ConversionOperator.cs │ │ │ │ │ ├── ConvertOperator.cs │ │ │ │ │ ├── FetchExceptionOperator.cs │ │ │ │ │ ├── LandingPadOperator.cs │ │ │ │ │ ├── LongBinaryOperator.cs │ │ │ │ │ ├── Memory/ │ │ │ │ │ │ ├── AddressAssignmentOperator.cs │ │ │ │ │ │ ├── ArgListOperator.cs │ │ │ │ │ │ ├── ElementOperator.cs │ │ │ │ │ │ ├── FieldOperator.cs │ │ │ │ │ │ ├── IndirectOperator.cs │ │ │ │ │ │ ├── LoadAddressOperator.cs │ │ │ │ │ │ ├── LoadElementAddressOperator.cs │ │ │ │ │ │ ├── LoadElementOperator.cs │ │ │ │ │ │ ├── LoadFieldOperator.cs │ │ │ │ │ │ ├── LoadIndirectOperator.cs │ │ │ │ │ │ ├── LoadInstanceFieldAddressOperator.cs │ │ │ │ │ │ ├── LoadInstanceFieldOperator.cs │ │ │ │ │ │ ├── LoadStaticFieldAddressOperator.cs │ │ │ │ │ │ ├── LoadStaticFieldOperator.cs │ │ │ │ │ │ ├── StackAllocationOperator.cs │ │ │ │ │ │ ├── StoreElementOperator.cs │ │ │ │ │ │ ├── StoreFieldOperator.cs │ │ │ │ │ │ ├── StoreIndirectOperator.cs │ │ │ │ │ │ ├── StoreInstanceFieldOperator.cs │ │ │ │ │ │ └── StoreStaticFieldOperator.cs │ │ │ │ │ ├── NopOperator.cs │ │ │ │ │ ├── Object/ │ │ │ │ │ │ ├── ArrayAllocationOperator.cs │ │ │ │ │ │ ├── ArrayLengthOperator.cs │ │ │ │ │ │ ├── BoxOperator.cs │ │ │ │ │ │ ├── CastOperator.cs │ │ │ │ │ │ ├── IsInstanceOperator.cs │ │ │ │ │ │ ├── MethodRepresentationOperator.cs │ │ │ │ │ │ ├── ObjectAllocationOperator.cs │ │ │ │ │ │ └── UnboxOperator.cs │ │ │ │ │ ├── Operator.cs │ │ │ │ │ ├── PartialAssignmentOperator.cs │ │ │ │ │ ├── SignExtendOperator.cs │ │ │ │ │ ├── SingleAssignmentOperator.cs │ │ │ │ │ ├── TruncateOperator.cs │ │ │ │ │ ├── TypedReference/ │ │ │ │ │ │ ├── MkRefAnyOperator.cs │ │ │ │ │ │ ├── RefAnyTypeOperator.cs │ │ │ │ │ │ └── RefAnyValOperator.cs │ │ │ │ │ ├── UnaryOperator.cs │ │ │ │ │ └── ZeroExtendOperator.cs │ │ │ │ ├── Properties/ │ │ │ │ │ └── AssemblyInfo.cs │ │ │ │ ├── TransformationContextForIR.cs │ │ │ │ └── TypeSystemForIR.cs │ │ │ ├── Llvm.NET/ │ │ │ │ ├── LibLLVM/ │ │ │ │ │ ├── AnalysisBindings.cpp │ │ │ │ │ ├── AnalysisBindings.h │ │ │ │ │ ├── AttributeBindings.cpp │ │ │ │ │ ├── AttributeBindings.h │ │ │ │ │ ├── BuildLlvmWithVS.cmd │ │ │ │ │ ├── DIBuilderBindings.cpp │ │ │ │ │ ├── DIBuilderBindings.h │ │ │ │ │ ├── DITypeBindings.cpp │ │ │ │ │ ├── DITypeBindings.h │ │ │ │ │ ├── EXPORTS.DEF │ │ │ │ │ ├── IRBindings.cpp │ │ │ │ │ ├── IRBindings.h │ │ │ │ │ ├── InlinedExports.cpp │ │ │ │ │ ├── InlinedExports.h │ │ │ │ │ ├── InstrumentationBindings.cpp │ │ │ │ │ ├── InstrumentationBindings.h │ │ │ │ │ ├── LibLLVM.vcxproj │ │ │ │ │ ├── LibLLVM.vcxproj.filters │ │ │ │ │ ├── LlvmApplication.props │ │ │ │ │ ├── LlvmApplication.targets │ │ │ │ │ ├── LlvmDebugInfo.cpp │ │ │ │ │ ├── LlvmDebugInfo.h │ │ │ │ │ ├── ModuleBindings.cpp │ │ │ │ │ ├── ModuleBindings.h │ │ │ │ │ ├── Resource.rc │ │ │ │ │ ├── ValueBindings.cpp │ │ │ │ │ ├── ValueBindings.h │ │ │ │ │ ├── resource.h │ │ │ │ │ ├── stdafx.h │ │ │ │ │ └── targetver.h │ │ │ │ ├── Llvm.NET/ │ │ │ │ │ ├── ArgValidationExtensions.cs │ │ │ │ │ ├── Context.cs │ │ │ │ │ ├── ContextValidator.cs │ │ │ │ │ ├── DataLayout.cs │ │ │ │ │ ├── DebugInfo/ │ │ │ │ │ │ ├── DIBasicType.cs │ │ │ │ │ │ ├── DICompileUnit.cs │ │ │ │ │ │ ├── DICompositeType.cs │ │ │ │ │ │ ├── DIDerivedType.cs │ │ │ │ │ │ ├── DIEnumerator.cs │ │ │ │ │ │ ├── DIExpression.cs │ │ │ │ │ │ ├── DIFile.cs │ │ │ │ │ │ ├── DIGlobalVariable.cs │ │ │ │ │ │ ├── DIImportedEntity.cs │ │ │ │ │ │ ├── DILexicalBlock.cs │ │ │ │ │ │ ├── DILexicalBlockBase.cs │ │ │ │ │ │ ├── DILexicalBlockFile.cs │ │ │ │ │ │ ├── DILocalScope.cs │ │ │ │ │ │ ├── DILocalVariable.cs │ │ │ │ │ │ ├── DILocation.cs │ │ │ │ │ │ ├── DIModule.cs │ │ │ │ │ │ ├── DINamespace.cs │ │ │ │ │ │ ├── DINode.cs │ │ │ │ │ │ ├── DINodeArray.cs │ │ │ │ │ │ ├── DIObjCProperty.cs │ │ │ │ │ │ ├── DIScope.cs │ │ │ │ │ │ ├── DISubProgram.cs │ │ │ │ │ │ ├── DISubRange.cs │ │ │ │ │ │ ├── DISubroutineType.cs │ │ │ │ │ │ ├── DITemplateParameter.cs │ │ │ │ │ │ ├── DITemplateTypeParameter.cs │ │ │ │ │ │ ├── DITemplateValueParameter.cs │ │ │ │ │ │ ├── DIType.cs │ │ │ │ │ │ ├── DITypeArray.cs │ │ │ │ │ │ ├── DIVariable.cs │ │ │ │ │ │ ├── DebugArrayType.cs │ │ │ │ │ │ ├── DebugBasicType.cs │ │ │ │ │ │ ├── DebugFunctionType.cs │ │ │ │ │ │ ├── DebugInfoBuilder.cs │ │ │ │ │ │ ├── DebugMemberInfo.cs │ │ │ │ │ │ ├── DebugPointerType.cs │ │ │ │ │ │ ├── DebugStructType.cs │ │ │ │ │ │ ├── DebugType.cs │ │ │ │ │ │ ├── DwarfEnumerations.cs │ │ │ │ │ │ ├── GenericDINode.cs │ │ │ │ │ │ └── MDNodeOperandList.cs │ │ │ │ │ ├── Enumerations.cs │ │ │ │ │ ├── GlobalPassRegistry.cs │ │ │ │ │ ├── IExtensiblePropertyContainer.cs │ │ │ │ │ ├── Instructions/ │ │ │ │ │ │ ├── AddressSpaceCast.cs │ │ │ │ │ │ ├── Alloca.cs │ │ │ │ │ │ ├── AtomicCmpXchg.cs │ │ │ │ │ │ ├── AtomicRMW.cs │ │ │ │ │ │ ├── BinaryOperator.cs │ │ │ │ │ │ ├── BitCast.cs │ │ │ │ │ │ ├── Branch.cs │ │ │ │ │ │ ├── Call.cs │ │ │ │ │ │ ├── Cast.cs │ │ │ │ │ │ ├── CatchPad.cs │ │ │ │ │ │ ├── CatchReturn.cs │ │ │ │ │ │ ├── CatchSwitch.cs │ │ │ │ │ │ ├── CleanupPad.cs │ │ │ │ │ │ ├── CleanupReturn.cs │ │ │ │ │ │ ├── Cmp.cs │ │ │ │ │ │ ├── DebugDeclare.cs │ │ │ │ │ │ ├── DebugInfoIntrinsic.cs │ │ │ │ │ │ ├── ExtractElement.cs │ │ │ │ │ │ ├── ExtractValue.cs │ │ │ │ │ │ ├── FCmp.cs │ │ │ │ │ │ ├── FPExt.cs │ │ │ │ │ │ ├── FPToSI.cs │ │ │ │ │ │ ├── FPToUI.cs │ │ │ │ │ │ ├── FPTrunc.cs │ │ │ │ │ │ ├── Fence.cs │ │ │ │ │ │ ├── FuncletPad.cs │ │ │ │ │ │ ├── GetElementPtr.cs │ │ │ │ │ │ ├── IndirectBranch.cs │ │ │ │ │ │ ├── InsertElement.cs │ │ │ │ │ │ ├── InsertValue.cs │ │ │ │ │ │ ├── Instruction.cs │ │ │ │ │ │ ├── InstructionBuilder.cs │ │ │ │ │ │ ├── IntCmp.cs │ │ │ │ │ │ ├── IntToPointer.cs │ │ │ │ │ │ ├── Intrinsic.cs │ │ │ │ │ │ ├── Invoke.cs │ │ │ │ │ │ ├── LandingPad.cs │ │ │ │ │ │ ├── Load.cs │ │ │ │ │ │ ├── MemCpy.cs │ │ │ │ │ │ ├── MemIntrinsic.cs │ │ │ │ │ │ ├── MemMove.cs │ │ │ │ │ │ ├── MemSet.cs │ │ │ │ │ │ ├── PhiNode.cs │ │ │ │ │ │ ├── PointerToInt.cs │ │ │ │ │ │ ├── Resume.cs │ │ │ │ │ │ ├── Return.cs │ │ │ │ │ │ ├── SIToFP.cs │ │ │ │ │ │ ├── Select.cs │ │ │ │ │ │ ├── ShuffleVector.cs │ │ │ │ │ │ ├── SignExtend.cs │ │ │ │ │ │ ├── Store.cs │ │ │ │ │ │ ├── Switch.cs │ │ │ │ │ │ ├── Terminator.cs │ │ │ │ │ │ ├── Trunc.cs │ │ │ │ │ │ ├── UIToFP.cs │ │ │ │ │ │ ├── UnaryInstruction.cs │ │ │ │ │ │ ├── Unreachable.cs │ │ │ │ │ │ ├── UserOp1.cs │ │ │ │ │ │ ├── UserOp2.cs │ │ │ │ │ │ ├── VAArg.cs │ │ │ │ │ │ └── ZeroExtend.cs │ │ │ │ │ ├── InternalCodeGeneratorException.cs │ │ │ │ │ ├── LLVM/ │ │ │ │ │ │ ├── Generated.cs │ │ │ │ │ │ ├── GeneratedExtensions.cs │ │ │ │ │ │ ├── LLVMNative.cs │ │ │ │ │ │ └── LlvmHandles.cs │ │ │ │ │ ├── Llvm.NET.csproj │ │ │ │ │ ├── Llvm.NET.ruleset │ │ │ │ │ ├── MemoryBuffer.cs │ │ │ │ │ ├── Metadata/ │ │ │ │ │ │ ├── ConstantAsMetadata.cs │ │ │ │ │ │ ├── LocalAsMetadata.cs │ │ │ │ │ │ ├── MDNode.cs │ │ │ │ │ │ ├── MDOperand.cs │ │ │ │ │ │ ├── MDString.cs │ │ │ │ │ │ ├── MDTuple.cs │ │ │ │ │ │ ├── Metadata.cs │ │ │ │ │ │ ├── MetadataAsValue.cs │ │ │ │ │ │ ├── NamedMDNode.cs │ │ │ │ │ │ └── ValueAsMetadata.cs │ │ │ │ │ ├── Module.cs │ │ │ │ │ ├── NativeMethods.cs │ │ │ │ │ ├── PassManagerBuilder.cs │ │ │ │ │ ├── Properties/ │ │ │ │ │ │ └── AssemblyInfo.cs │ │ │ │ │ ├── ScalarEnumerable.cs │ │ │ │ │ ├── StaticState.cs │ │ │ │ │ ├── Target.cs │ │ │ │ │ ├── TargetMachine.cs │ │ │ │ │ ├── Types/ │ │ │ │ │ │ ├── ArrayType.cs │ │ │ │ │ │ ├── FunctionType.cs │ │ │ │ │ │ ├── ITypeRef.cs │ │ │ │ │ │ ├── PointerType.cs │ │ │ │ │ │ ├── SequenceType.cs │ │ │ │ │ │ ├── StructType.cs │ │ │ │ │ │ ├── TypeRef.cs │ │ │ │ │ │ └── VectorType.cs │ │ │ │ │ └── Values/ │ │ │ │ │ ├── Argument.cs │ │ │ │ │ ├── AttributeBuilder.cs │ │ │ │ │ ├── AttributeKindExtensions.cs │ │ │ │ │ ├── AttributeSet.cs │ │ │ │ │ ├── AttributeSetContainer.cs │ │ │ │ │ ├── AttributeValue.cs │ │ │ │ │ ├── BasicBlock.cs │ │ │ │ │ ├── BlockAddress.cs │ │ │ │ │ ├── ConstPointerNull.cs │ │ │ │ │ ├── Constant.cs │ │ │ │ │ ├── ConstantAggregateZero.cs │ │ │ │ │ ├── ConstantArray.cs │ │ │ │ │ ├── ConstantDataArray.cs │ │ │ │ │ ├── ConstantDataSequential.cs │ │ │ │ │ ├── ConstantDataVector.cs │ │ │ │ │ ├── ConstantExpression.cs │ │ │ │ │ ├── ConstantFP.cs │ │ │ │ │ ├── ConstantInt.cs │ │ │ │ │ ├── ConstantStruct.cs │ │ │ │ │ ├── ConstantTokenNone.cs │ │ │ │ │ ├── ConstantVector.cs │ │ │ │ │ ├── Function.cs │ │ │ │ │ ├── FunctionParameterList.cs │ │ │ │ │ ├── GlobalAlias.cs │ │ │ │ │ ├── GlobalObject.cs │ │ │ │ │ ├── GlobalValue.cs │ │ │ │ │ ├── GlobalVariable.cs │ │ │ │ │ ├── IAttributeSetContainer.cs │ │ │ │ │ ├── InlineAsm.cs │ │ │ │ │ ├── UndefValue.cs │ │ │ │ │ ├── Use.cs │ │ │ │ │ ├── User.cs │ │ │ │ │ ├── UserOperandList.cs │ │ │ │ │ └── Value.cs │ │ │ │ └── Llvm.NET.sln │ │ │ ├── MetaData/ │ │ │ │ ├── Importer/ │ │ │ │ │ ├── AbstractMetaDataException.cs │ │ │ │ │ ├── ArrayReader.cs │ │ │ │ │ ├── ArrayWriter.cs │ │ │ │ │ ├── EHClause.cs │ │ │ │ │ ├── IllegalMetaDataFormatException.cs │ │ │ │ │ ├── Importer.csproj │ │ │ │ │ ├── Instruction.cs │ │ │ │ │ ├── LogWriter.cs │ │ │ │ │ ├── MarshalSpec.cs │ │ │ │ │ ├── MetaData.cs │ │ │ │ │ ├── MetaDataAssembly.cs │ │ │ │ │ ├── MetaDataAssemblyRef.cs │ │ │ │ │ ├── MetaDataClassLayout.cs │ │ │ │ │ ├── MetaDataConstant.cs │ │ │ │ │ ├── MetaDataCustomAttribute.cs │ │ │ │ │ ├── MetaDataDeclSecurity.cs │ │ │ │ │ ├── MetaDataDumper.cs │ │ │ │ │ ├── MetaDataEvent.cs │ │ │ │ │ ├── MetaDataField.cs │ │ │ │ │ ├── MetaDataFieldLayout.cs │ │ │ │ │ ├── MetaDataFieldMarshal.cs │ │ │ │ │ ├── MetaDataFieldRVA.cs │ │ │ │ │ ├── MetaDataFile.cs │ │ │ │ │ ├── MetaDataGenericParam.cs │ │ │ │ │ ├── MetaDataImplMap.cs │ │ │ │ │ ├── MetaDataManifestResource.cs │ │ │ │ │ ├── MetaDataMemberRef.cs │ │ │ │ │ ├── MetaDataMethod.cs │ │ │ │ │ ├── MetaDataMethodImpl.cs │ │ │ │ │ ├── MetaDataMethodSemantics.cs │ │ │ │ │ ├── MetaDataMethodSpec.cs │ │ │ │ │ ├── MetaDataMethod_Code.cs │ │ │ │ │ ├── MetaDataModule.cs │ │ │ │ │ ├── MetaDataModuleRef.cs │ │ │ │ │ ├── MetaDataNormalizationContext.cs │ │ │ │ │ ├── MetaDataObject.cs │ │ │ │ │ ├── MetaDataParam.cs │ │ │ │ │ ├── MetaDataProperty.cs │ │ │ │ │ ├── MetaDataResolver.cs │ │ │ │ │ ├── MetaDataStandAloneSig.cs │ │ │ │ │ ├── MetaDataTypeDefinition.cs │ │ │ │ │ ├── MetaDataTypeReference.cs │ │ │ │ │ ├── MetaDataTypeSpec.cs │ │ │ │ │ ├── PDBInfo/ │ │ │ │ │ │ ├── BitSet.cs │ │ │ │ │ │ ├── CvInfo.cs │ │ │ │ │ │ ├── DataStream.cs │ │ │ │ │ │ ├── DbiHeader.cs │ │ │ │ │ │ ├── DbiModuleInfo.cs │ │ │ │ │ │ ├── DbiSecCon.cs │ │ │ │ │ │ ├── MsfDirectory.cs │ │ │ │ │ │ ├── PdbException.cs │ │ │ │ │ │ ├── PdbFile.cs │ │ │ │ │ │ ├── PdbFileHeader.cs │ │ │ │ │ │ ├── PdbFunction.cs │ │ │ │ │ │ ├── PdbLine.cs │ │ │ │ │ │ ├── PdbLines.cs │ │ │ │ │ │ ├── PdbReader.cs │ │ │ │ │ │ ├── PdbScope.cs │ │ │ │ │ │ ├── PdbSlot.cs │ │ │ │ │ │ ├── PdbSource.cs │ │ │ │ │ │ ├── PdbStream.cs │ │ │ │ │ │ └── PdbWriter.cs │ │ │ │ │ ├── PELoader.cs │ │ │ │ │ ├── Parser.cs │ │ │ │ │ ├── Properties/ │ │ │ │ │ │ └── AssemblyInfo.cs │ │ │ │ │ ├── Signature.cs │ │ │ │ │ ├── SignatureField.cs │ │ │ │ │ ├── SignatureLocalVar.cs │ │ │ │ │ ├── SignatureMethod.cs │ │ │ │ │ ├── SignatureMethodSpec.cs │ │ │ │ │ ├── SignatureProperty.cs │ │ │ │ │ ├── SignatureTypeSpec.cs │ │ │ │ │ ├── SilentCompilationAbortException.cs │ │ │ │ │ └── UnresolvedExternalReferenceException.cs │ │ │ │ ├── MetaData.UnitTest/ │ │ │ │ │ ├── Bench.cs │ │ │ │ │ ├── CompressionTester.cs │ │ │ │ │ ├── MetaData.UnitTest.csproj │ │ │ │ │ ├── MetaDataParserTester.cs │ │ │ │ │ ├── MetaDataResolverTester.cs │ │ │ │ │ ├── PDBFileTester.cs │ │ │ │ │ ├── PELoaderTester.cs │ │ │ │ │ └── Properties/ │ │ │ │ │ └── AssemblyInfo.cs │ │ │ │ └── Normalized/ │ │ │ │ ├── EHClause.cs │ │ │ │ ├── Instruction.cs │ │ │ │ ├── MarshalSpec.cs │ │ │ │ ├── MetaDataAssembly.cs │ │ │ │ ├── MetaDataBits.cs │ │ │ │ ├── MetaDataClassLayout.cs │ │ │ │ ├── MetaDataConstant.cs │ │ │ │ ├── MetaDataCustomAttribute.cs │ │ │ │ ├── MetaDataDeclSecurity.cs │ │ │ │ ├── MetaDataEvent.cs │ │ │ │ ├── MetaDataField.cs │ │ │ │ ├── MetaDataFieldAbstract.cs │ │ │ │ ├── MetaDataFieldLayout.cs │ │ │ │ ├── MetaDataFieldMarshal.cs │ │ │ │ ├── MetaDataFieldRVA.cs │ │ │ │ ├── MetaDataFieldWithContext.cs │ │ │ │ ├── MetaDataFile.cs │ │ │ │ ├── MetaDataGenericMethodParam.cs │ │ │ │ ├── MetaDataGenericParam.cs │ │ │ │ ├── MetaDataGenericTypeParam.cs │ │ │ │ ├── MetaDataImplMap.cs │ │ │ │ ├── MetaDataInterfaces.cs │ │ │ │ ├── MetaDataManifestResource.cs │ │ │ │ ├── MetaDataMethod.cs │ │ │ │ ├── MetaDataMethodAbstract.cs │ │ │ │ ├── MetaDataMethodBase.cs │ │ │ │ ├── MetaDataMethodGeneric.cs │ │ │ │ ├── MetaDataMethodGenericInstantiation.cs │ │ │ │ ├── MetaDataMethodImpl.cs │ │ │ │ ├── MetaDataMethodSemantics.cs │ │ │ │ ├── MetaDataMethodWithContext.cs │ │ │ │ ├── MetaDataModule.cs │ │ │ │ ├── MetaDataObject.cs │ │ │ │ ├── MetaDataParam.cs │ │ │ │ ├── MetaDataProperty.cs │ │ │ │ ├── MetaDataSignature.cs │ │ │ │ ├── MetaDataTypeDefinition.cs │ │ │ │ ├── MetaDataTypeDefinitionAbstract.cs │ │ │ │ ├── MetaDataTypeDefinitionArray.cs │ │ │ │ ├── MetaDataTypeDefinitionArrayMulti.cs │ │ │ │ ├── MetaDataTypeDefinitionArraySz.cs │ │ │ │ ├── MetaDataTypeDefinitionBase.cs │ │ │ │ ├── MetaDataTypeDefinitionByRef.cs │ │ │ │ ├── MetaDataTypeDefinitionDelayed.cs │ │ │ │ ├── MetaDataTypeDefinitionGeneric.cs │ │ │ │ ├── MetaDataTypeDefinitionGenericInstantiation.cs │ │ │ │ ├── MetaDataTypeDefinitionPartiallyDelayedMethodParameter.cs │ │ │ │ ├── MetaDataTypeDefinitionPartiallyDelayedTypeParameter.cs │ │ │ │ ├── MetaDataVersion.cs │ │ │ │ ├── Normalized.csproj │ │ │ │ ├── Properties/ │ │ │ │ │ └── AssemblyInfo.cs │ │ │ │ ├── SignatureField.cs │ │ │ │ ├── SignatureMethod.cs │ │ │ │ └── SignatureType.cs │ │ │ └── TargetModels/ │ │ │ ├── ArmProcessor/ │ │ │ │ ├── ARM/ │ │ │ │ │ ├── EncodingDefinition_ARM.cs │ │ │ │ │ └── EncodingDefinition_VFP_ARM.cs │ │ │ │ ├── ArmProcessor.csproj │ │ │ │ ├── CurrentInstructionSetEncoding.cs │ │ │ │ ├── EncodingDefinition.cs │ │ │ │ ├── EncodingDefinition_VFP.cs │ │ │ │ ├── InstructionSet.cs │ │ │ │ ├── InstructionSetVersion.cs │ │ │ │ ├── InstructionSet_VFP.cs │ │ │ │ └── Properties/ │ │ │ │ └── AssemblyInfo.cs │ │ │ ├── ProductConfiguration/ │ │ │ │ ├── Abstractions/ │ │ │ │ │ ├── ARM/ │ │ │ │ │ │ ├── ArchitectureVersions/ │ │ │ │ │ │ │ ├── ArmV4.cs │ │ │ │ │ │ │ ├── ArmV4_Optimizations.cs │ │ │ │ │ │ │ ├── ArmV5.cs │ │ │ │ │ │ │ ├── ArmV5_VFP.cs │ │ │ │ │ │ │ ├── ArmV5_VFP_CollectRegisterAllocationConstraints.cs │ │ │ │ │ │ │ └── ArmV5_VFP_Emulation.cs │ │ │ │ │ │ ├── ArmCallingConvention.cs │ │ │ │ │ │ ├── ArmPlatform.cs │ │ │ │ │ │ ├── ArmPlatform_CompilationState.cs │ │ │ │ │ │ ├── ArmPlatform_CompilationState_CodeMap.cs │ │ │ │ │ │ ├── ArmPlatform_CompilationState_EmitCode.cs │ │ │ │ │ │ ├── ArmPlatform_CompilationState_Encoder.cs │ │ │ │ │ │ ├── ArmPlatform_CompilationState_Encoder_VFP.cs │ │ │ │ │ │ ├── ArmPlatform_EmitPrologueEpilogue.cs │ │ │ │ │ │ ├── ArmPlatform_Handlers_ExpandAggregateTypes.cs.cs │ │ │ │ │ │ ├── ArmPlatform_Handlers_HighLevel.cs │ │ │ │ │ │ ├── ArmPlatform_OperatorConstraints.cs │ │ │ │ │ │ ├── ArmPlatform_Optimizations.cs │ │ │ │ │ │ ├── ArmPlatform_PrepareForRegisterAllocation.cs │ │ │ │ │ │ ├── ArmPlatform_RegisterAllocation.cs │ │ │ │ │ │ ├── ArmPlatform_SplitComplexOperators.cs │ │ │ │ │ │ ├── ImageAnnotations/ │ │ │ │ │ │ │ ├── ArmCodeRelocation_Branch.cs │ │ │ │ │ │ │ ├── ArmCodeRelocation_ExternMethod.cs │ │ │ │ │ │ │ ├── ArmCodeRelocation_FLD.cs │ │ │ │ │ │ │ ├── ArmCodeRelocation_LDR.cs │ │ │ │ │ │ │ └── ArmCodeRelocation_MOV.cs │ │ │ │ │ │ └── Operators/ │ │ │ │ │ │ ├── BinaryOperatorWithShift.cs │ │ │ │ │ │ ├── BreakpointOperator.cs │ │ │ │ │ │ ├── GetStatusRegisterOperator.cs │ │ │ │ │ │ ├── IndirectOperatorWithIndexUpdate.cs │ │ │ │ │ │ ├── LoadIndirectOperatorWithIndexUpdate.cs │ │ │ │ │ │ ├── MoveFloatingPointRegistersOperator.cs │ │ │ │ │ │ ├── MoveFromCoprocessor.cs │ │ │ │ │ │ ├── MoveIntegerRegistersOperator.cs │ │ │ │ │ │ ├── MoveStackPointerOperator.cs │ │ │ │ │ │ ├── MoveToCoprocessor.cs │ │ │ │ │ │ ├── SetStatusRegisterOperator.cs │ │ │ │ │ │ ├── StoreIndirectOperatorWithIndexUpdate.cs │ │ │ │ │ │ ├── VectorHack_Base.cs │ │ │ │ │ │ ├── VectorHack_Cleanup.cs │ │ │ │ │ │ ├── VectorHack_Finalize.cs │ │ │ │ │ │ ├── VectorHack_Initialize.cs │ │ │ │ │ │ ├── VectorHack_LoadData.cs │ │ │ │ │ │ ├── VectorHack_MultiplyAndAccumulate.cs │ │ │ │ │ │ └── VectorHack_Prepare.cs │ │ │ │ │ └── LLVMforZelig/ │ │ │ │ │ ├── LlvmForArmV6M.cs │ │ │ │ │ ├── LlvmForArmV7M.cs │ │ │ │ │ ├── LlvmForArmV7MCallingConvention.cs │ │ │ │ │ ├── LlvmForArmV7MCompilationState.cs │ │ │ │ │ ├── LlvmForArmV7MCompilationState_BasicBlocks.cs │ │ │ │ │ ├── LlvmForArmV7M_VFP.cs │ │ │ │ │ ├── LlvmForWin32.cs │ │ │ │ │ └── ValueCache.cs │ │ │ │ ├── Loaders.Designer.cs │ │ │ │ ├── Loaders.resx │ │ │ │ ├── Manager.cs │ │ │ │ ├── Models/ │ │ │ │ │ ├── Displays.cs │ │ │ │ │ ├── Engines.cs │ │ │ │ │ ├── LegacyProducts.cs │ │ │ │ │ ├── Memories.cs │ │ │ │ │ └── Processors.cs │ │ │ │ ├── NandFlashJTagLoaderCategory.cs │ │ │ │ ├── NorFlashJTagLoaderCategory.cs │ │ │ │ ├── ProductConfiguration.csproj │ │ │ │ ├── Properties/ │ │ │ │ │ └── AssemblyInfo.cs │ │ │ │ ├── RamJTagLoaderCategory.cs │ │ │ │ ├── Resources/ │ │ │ │ │ ├── Microsoft.NohauLPC3180Loader.hex │ │ │ │ │ ├── Microsoft.VoxSoloFormFactorLoader.hex │ │ │ │ │ └── Microsoft.iMote2Loader.hex │ │ │ │ └── XScaleNorFlashJTagLoaderCategory.cs │ │ │ └── Win32EmuProcessor/ │ │ │ ├── InstructionSetVersion.cs │ │ │ ├── Properties/ │ │ │ │ └── AssemblyInfo.cs │ │ │ └── Win32Processor.csproj │ │ ├── DebugTime/ │ │ │ ├── ArmProcessorEmulation/ │ │ │ │ ├── ArmProcessorEmulation.csproj │ │ │ │ ├── Forms/ │ │ │ │ │ ├── BaseDebuggerForm.Designer.cs │ │ │ │ │ ├── BaseDebuggerForm.cs │ │ │ │ │ ├── BaseDebuggerForm.resx │ │ │ │ │ └── HostingSite.cs │ │ │ │ ├── Hosting/ │ │ │ │ │ ├── AbstractEngine.cs │ │ │ │ │ ├── AbstractEngineException.cs │ │ │ │ │ ├── AbstractHardwarePlugIn.cs │ │ │ │ │ ├── AbstractHost.cs │ │ │ │ │ ├── AbstractPlugIn.cs │ │ │ │ │ ├── AbstractUIPlugIn.cs │ │ │ │ │ ├── BinaryBlob.cs │ │ │ │ │ ├── Breakpoint.cs │ │ │ │ │ ├── CodeCoverage.cs │ │ │ │ │ ├── DebugCommunicationChannel.cs │ │ │ │ │ ├── DeviceClockTicksTracking.cs │ │ │ │ │ ├── ExtraDeploymentSteps.cs │ │ │ │ │ ├── HalButtons.cs │ │ │ │ │ ├── HalEvents.cs │ │ │ │ │ ├── IAsynchronousSerialPort.cs │ │ │ │ │ ├── ISynchronousSerialInterfaceBus.cs │ │ │ │ │ ├── ISynchronousSerialInterfaceController.cs │ │ │ │ │ ├── Interop.cs │ │ │ │ │ ├── JTagConnector.cs │ │ │ │ │ ├── JTagCustomer.cs │ │ │ │ │ ├── MemoryProvider.cs │ │ │ │ │ ├── MonitorExecution.cs │ │ │ │ │ ├── OutputSink.cs │ │ │ │ │ ├── ProcessorControl.cs │ │ │ │ │ ├── ProcessorPerformance.cs │ │ │ │ │ ├── ProcessorStatus.cs │ │ │ │ │ ├── SED15E0Sink.cs │ │ │ │ │ ├── SimulatedDeviceClockTicksTracking.cs │ │ │ │ │ ├── SimulatorControl.cs │ │ │ │ │ └── TypeSystem.cs │ │ │ │ ├── Models/ │ │ │ │ │ ├── Chipset/ │ │ │ │ │ │ ├── MM9691LP.cs │ │ │ │ │ │ └── PXA27x.cs │ │ │ │ │ ├── Display/ │ │ │ │ │ │ └── SED15E0.cs │ │ │ │ │ ├── FlashMemory/ │ │ │ │ │ │ ├── S29WS064.cs │ │ │ │ │ │ └── S29WS128N.cs │ │ │ │ │ └── VoxSoloFormFactor/ │ │ │ │ │ └── Interops.cs │ │ │ │ ├── Properties/ │ │ │ │ │ └── AssemblyInfo.cs │ │ │ │ ├── SRecordParser.cs │ │ │ │ ├── Simulator.cs │ │ │ │ ├── SimulatorCore.cs │ │ │ │ └── SymDef.cs │ │ │ ├── Debugger/ │ │ │ │ ├── Debugger.csproj │ │ │ │ ├── Execution/ │ │ │ │ │ ├── DebugGarbageColllection.cs │ │ │ │ │ ├── ImageInformation.cs │ │ │ │ │ ├── InteropHelper.cs │ │ │ │ │ ├── MemoryDelta.cs │ │ │ │ │ ├── PerformanceCounter.cs │ │ │ │ │ ├── ProcessorHost.cs │ │ │ │ │ ├── Profiler.cs │ │ │ │ │ ├── RegisterContext.cs │ │ │ │ │ ├── Session.cs │ │ │ │ │ ├── StackFrame.cs │ │ │ │ │ ├── ThreadStatus.cs │ │ │ │ │ ├── ValueHandles/ │ │ │ │ │ │ ├── AbstractValueHandle.cs │ │ │ │ │ │ ├── BitFieldValueHandle.cs │ │ │ │ │ │ ├── CompoundValueHandle.cs │ │ │ │ │ │ ├── MemoryValueHandle.cs │ │ │ │ │ │ ├── RegisterValueHandle.cs │ │ │ │ │ │ └── SlicedValueHandle.cs │ │ │ │ │ └── WatchHelper.cs │ │ │ │ ├── Forms/ │ │ │ │ │ ├── DebuggerMainForm.Actions.cs │ │ │ │ │ ├── DebuggerMainForm.Designer.cs │ │ │ │ │ ├── DebuggerMainForm.Worker.cs │ │ │ │ │ ├── DebuggerMainForm.cs │ │ │ │ │ ├── DebuggerMainForm.resx │ │ │ │ │ ├── DisplayForm.Designer.cs │ │ │ │ │ ├── DisplayForm.cs │ │ │ │ │ ├── DisplayForm.resx │ │ │ │ │ ├── EnvironmentForm.Designer.cs │ │ │ │ │ ├── EnvironmentForm.cs │ │ │ │ │ ├── EnvironmentForm.resx │ │ │ │ │ ├── IMainForm.cs │ │ │ │ │ ├── InputForm.Designer.cs │ │ │ │ │ ├── InputForm.cs │ │ │ │ │ ├── InputForm.resx │ │ │ │ │ ├── OutputForm.Designer.cs │ │ │ │ │ ├── OutputForm.cs │ │ │ │ │ ├── OutputForm.resx │ │ │ │ │ ├── ProfilerMainForm.Designer.cs │ │ │ │ │ ├── ProfilerMainForm.cs │ │ │ │ │ ├── ProfilerMainForm.resx │ │ │ │ │ ├── SessionManager.Designer.cs │ │ │ │ │ ├── SessionManager.cs │ │ │ │ │ └── SessionManager.resx │ │ │ │ ├── Program.cs │ │ │ │ ├── Properties/ │ │ │ │ │ ├── AssemblyInfo.cs │ │ │ │ │ ├── Resources.Designer.cs │ │ │ │ │ ├── Resources.resx │ │ │ │ │ ├── Settings.Designer.cs │ │ │ │ │ └── Settings.settings │ │ │ │ ├── SoloDebugOverDccUI_HW.DebuggerConfig │ │ │ │ ├── SoloOverDccUI.DebuggerConfig │ │ │ │ ├── SoloOverDccUI_HW.DebuggerConfig │ │ │ │ ├── SoloOverSerialUI_HW.DebuggerConfig │ │ │ │ ├── SoloUI.DebuggerConfig │ │ │ │ ├── UserControls/ │ │ │ │ │ ├── BreakpointsView.Designer.cs │ │ │ │ │ ├── BreakpointsView.cs │ │ │ │ │ ├── BreakpointsView.resx │ │ │ │ │ ├── CodeView.Designer.cs │ │ │ │ │ ├── CodeView.Parsers.cs │ │ │ │ │ ├── CodeView.cs │ │ │ │ │ ├── CodeView.resx │ │ │ │ │ ├── LocalsView.Designer.cs │ │ │ │ │ ├── LocalsView.cs │ │ │ │ │ ├── LocalsView.resx │ │ │ │ │ ├── MemoryView.Designer.cs │ │ │ │ │ ├── MemoryView.cs │ │ │ │ │ ├── MemoryView.resx │ │ │ │ │ ├── RegistersView.Designer.cs │ │ │ │ │ ├── RegistersView.cs │ │ │ │ │ ├── RegistersView.resx │ │ │ │ │ ├── StackTraceView.Designer.cs │ │ │ │ │ ├── StackTraceView.cs │ │ │ │ │ ├── StackTraceView.resx │ │ │ │ │ ├── ThreadsView.Designer.cs │ │ │ │ │ ├── ThreadsView.cs │ │ │ │ │ ├── ThreadsView.resx │ │ │ │ │ ├── TreeBasedGridView.Designer.cs │ │ │ │ │ ├── TreeBasedGridView.cs │ │ │ │ │ └── TreeBasedGridView.resx │ │ │ │ ├── VisualTree/ │ │ │ │ │ ├── GraphicsContext.cs │ │ │ │ │ ├── VisualEffects/ │ │ │ │ │ │ ├── InlineDisassembly.cs │ │ │ │ │ │ ├── SourceCodeHighlight.cs │ │ │ │ │ │ └── VisualEffect.cs │ │ │ │ │ ├── VisualItems/ │ │ │ │ │ │ ├── AddressVisualItem.cs │ │ │ │ │ │ ├── BackgroundVisualItem.cs │ │ │ │ │ │ ├── BaseTextVisualItem.cs │ │ │ │ │ │ ├── ByteVisualItem.cs │ │ │ │ │ │ ├── CharsVisualItem.cs │ │ │ │ │ │ ├── ContainerVisualItem.cs │ │ │ │ │ │ ├── IconVisualItem.cs │ │ │ │ │ │ ├── ShortVisualItem.cs │ │ │ │ │ │ ├── TextVisualItem.cs │ │ │ │ │ │ ├── VisualItem.cs │ │ │ │ │ │ └── WordVisualItem.cs │ │ │ │ │ └── VisualTreeInfo.cs │ │ │ │ ├── app.config │ │ │ │ ├── test.DebuggerConfig │ │ │ │ └── test.ZeligDebugSession │ │ │ ├── Elf/ │ │ │ │ ├── ElfLib/ │ │ │ │ │ ├── DebugInfoEntry.cs │ │ │ │ │ ├── ElfObject.cs │ │ │ │ │ ├── ElfObject_Descriptors.cs │ │ │ │ │ ├── ElfObject_Factory.cs │ │ │ │ │ ├── ElfObject_FileUtil.cs │ │ │ │ │ ├── ElfObject_HelperTypes.cs │ │ │ │ │ ├── ElfSection.cs │ │ │ │ │ ├── ElfSegment.cs │ │ │ │ │ ├── Elflib.csproj │ │ │ │ │ ├── OutputFormatter.cs │ │ │ │ │ ├── Properties/ │ │ │ │ │ │ └── AssemblyInfo.cs │ │ │ │ │ ├── RelocationEntry.cs │ │ │ │ │ ├── RelocationSection.cs │ │ │ │ │ ├── SectionReference.cs │ │ │ │ │ ├── StringTable.cs │ │ │ │ │ ├── Symbol.cs │ │ │ │ │ └── SymbolTable.cs │ │ │ │ └── ReadElf/ │ │ │ │ ├── Program.cs │ │ │ │ ├── Properties/ │ │ │ │ │ └── AssemblyInfo.cs │ │ │ │ └── ReadElf.csproj │ │ │ └── Loader/ │ │ │ ├── Loader.Designer.cs │ │ │ ├── Loader.cs │ │ │ ├── Loader.csproj │ │ │ ├── Loader.resx │ │ │ ├── Program.cs │ │ │ └── Properties/ │ │ │ ├── AssemblyInfo.cs │ │ │ ├── Resources.Designer.cs │ │ │ ├── Resources.resx │ │ │ ├── Settings.Designer.cs │ │ │ └── Settings.settings │ │ ├── FileSystemTest/ │ │ │ ├── Directory/ │ │ │ │ ├── CreateDirectory.cs │ │ │ │ ├── DI_Constructor.cs │ │ │ │ ├── Delete.cs │ │ │ │ ├── DirectoryInfoTests.cs │ │ │ │ ├── DirectoryTests.cs │ │ │ │ ├── Exists.cs │ │ │ │ ├── GetDirectories.cs │ │ │ │ ├── GetFiles.cs │ │ │ │ ├── GetSetCurrentDirectory.cs │ │ │ │ └── Move.cs │ │ │ ├── File/ │ │ │ │ ├── Copy.cs │ │ │ │ ├── Create.cs │ │ │ │ ├── Delete.cs │ │ │ │ ├── Exists.cs │ │ │ │ ├── FileInfoTests.cs │ │ │ │ ├── FileTests.cs │ │ │ │ ├── GetSetAttributes.cs │ │ │ │ ├── OpenRead.cs │ │ │ │ ├── OpenWrite.cs │ │ │ │ ├── Open_FM.cs │ │ │ │ ├── Open_FM_FA.cs │ │ │ │ ├── Open_FM_FA_FS.cs │ │ │ │ └── ReadAllBytes.cs │ │ │ ├── FileStream/ │ │ │ │ ├── CanRead.cs │ │ │ │ ├── CanSeek.cs │ │ │ │ ├── CanWrite.cs │ │ │ │ ├── Constructors_FileAccess.cs │ │ │ │ ├── Constructors_FileMode.cs │ │ │ │ ├── Constructors_FileShare.cs │ │ │ │ ├── FileStreamHelper.cs │ │ │ │ ├── FileStreamTests.cs │ │ │ │ ├── Flush.cs │ │ │ │ ├── PropertyTests.cs │ │ │ │ ├── Read.cs │ │ │ │ ├── Seek.cs │ │ │ │ └── Write.cs │ │ │ ├── FileSystemTest.csproj │ │ │ ├── IOTestsHelper.cs │ │ │ ├── MemoryStream/ │ │ │ │ ├── CanRead.cs │ │ │ │ ├── CanSeek.cs │ │ │ │ ├── CanWrite.cs │ │ │ │ ├── Close.cs │ │ │ │ ├── Flush.cs │ │ │ │ ├── Length.cs │ │ │ │ ├── MemoryStreamHelper.cs │ │ │ │ ├── MemoryStream_Ctor.cs │ │ │ │ ├── Position.cs │ │ │ │ ├── Read.cs │ │ │ │ ├── ReadByte.cs │ │ │ │ ├── Seek.cs │ │ │ │ ├── SetLength.cs │ │ │ │ ├── ToArray.cs │ │ │ │ ├── Write.cs │ │ │ │ ├── WriteByte.cs │ │ │ │ └── WriteTo.cs │ │ │ ├── Path/ │ │ │ │ ├── ChangeExtension.cs │ │ │ │ ├── Combine.cs │ │ │ │ ├── GetDirectoryName.cs │ │ │ │ ├── GetExtension.cs │ │ │ │ ├── GetFileName.cs │ │ │ │ ├── GetFileNameWithoutExtension.cs │ │ │ │ ├── GetFullPath.cs │ │ │ │ ├── GetPathRoot.cs │ │ │ │ ├── HasExtension.cs │ │ │ │ ├── IsPathRooted.cs │ │ │ │ └── PathTests.cs │ │ │ ├── Program.cs │ │ │ ├── Properties/ │ │ │ │ └── AssemblyInfo.cs │ │ │ └── VolumeLabelTests.cs │ │ ├── RunTime/ │ │ │ ├── DeviceModels/ │ │ │ │ ├── CortexM0OnCMSIS-Core/ │ │ │ │ │ ├── CortexM0OnCMSIS-Core.csproj │ │ │ │ │ ├── HardwareModel/ │ │ │ │ │ │ ├── Board.cs │ │ │ │ │ │ ├── Device.cs │ │ │ │ │ │ ├── Drivers/ │ │ │ │ │ │ │ ├── ContextSwitchTimer.cs │ │ │ │ │ │ │ └── InterruptController.cs │ │ │ │ │ │ ├── HardwareProvider.cs │ │ │ │ │ │ ├── Memory.cs │ │ │ │ │ │ ├── Peripherals.cs │ │ │ │ │ │ ├── Processor.cs │ │ │ │ │ │ ├── SerialPortsManager.cs │ │ │ │ │ │ └── Storage.cs │ │ │ │ │ ├── Properties/ │ │ │ │ │ │ └── AssemblyInfo.cs │ │ │ │ │ └── SystemServices/ │ │ │ │ │ ├── GarbageCollectionManager.cs │ │ │ │ │ ├── MemoryManager.cs │ │ │ │ │ ├── ThreadManager.cs │ │ │ │ │ ├── TimerPool.cs │ │ │ │ │ └── TypeSystemManager.cs │ │ │ │ ├── CortexM0OnMBED/ │ │ │ │ │ ├── CortexM0OnMBED.csproj │ │ │ │ │ ├── HardwareModel/ │ │ │ │ │ │ ├── Board.cs │ │ │ │ │ │ ├── Device.cs │ │ │ │ │ │ ├── Drivers/ │ │ │ │ │ │ │ ├── AdcChannel.cs │ │ │ │ │ │ │ ├── GpioPin.cs │ │ │ │ │ │ │ ├── I2cChannel.cs │ │ │ │ │ │ │ ├── InterruptController.cs │ │ │ │ │ │ │ ├── PwmChannel.cs │ │ │ │ │ │ │ ├── SerialPortsManager.cs │ │ │ │ │ │ │ ├── SpiChannel.cs │ │ │ │ │ │ │ ├── StandardSerialPort.cs │ │ │ │ │ │ │ └── SystemTimer.cs │ │ │ │ │ │ ├── HardwareProvider.cs │ │ │ │ │ │ ├── HardwareProviders/ │ │ │ │ │ │ │ ├── AdcProvider.cs │ │ │ │ │ │ │ ├── GpioProvider.cs │ │ │ │ │ │ │ ├── I2cProvider.cs │ │ │ │ │ │ │ ├── PwmProvider.cs │ │ │ │ │ │ │ ├── SocketProvider.cs │ │ │ │ │ │ │ └── SpiProvider.cs │ │ │ │ │ │ ├── Memory.cs │ │ │ │ │ │ ├── Peripherals.cs │ │ │ │ │ │ ├── Processor.cs │ │ │ │ │ │ └── Storage.cs │ │ │ │ │ ├── Properties/ │ │ │ │ │ │ └── AssemblyInfo.cs │ │ │ │ │ └── SystemServices/ │ │ │ │ │ ├── GarbageCollectionManager.cs │ │ │ │ │ ├── MemoryManager.cs │ │ │ │ │ ├── SchedulerTimeImpl.cs │ │ │ │ │ ├── SchedulerTimeSpanImpl.cs │ │ │ │ │ ├── ThreadManager.cs │ │ │ │ │ ├── TimerPool.cs │ │ │ │ │ └── TypeSystemManager.cs │ │ │ │ ├── CortexM3OnCMSIS-Core/ │ │ │ │ │ ├── CortexM3OnCMSIS-Core.csproj │ │ │ │ │ ├── HardwareModel/ │ │ │ │ │ │ ├── Board.cs │ │ │ │ │ │ ├── Device.cs │ │ │ │ │ │ ├── Drivers/ │ │ │ │ │ │ │ ├── ContextSwitchTimer.cs │ │ │ │ │ │ │ └── InterruptController.cs │ │ │ │ │ │ ├── HardwareProvider.cs │ │ │ │ │ │ ├── Memory.cs │ │ │ │ │ │ ├── Peripherals.cs │ │ │ │ │ │ ├── Processor.cs │ │ │ │ │ │ ├── SerialPortsManager.cs │ │ │ │ │ │ └── Storage.cs │ │ │ │ │ ├── Properties/ │ │ │ │ │ │ └── AssemblyInfo.cs │ │ │ │ │ └── SystemServices/ │ │ │ │ │ ├── GarbageCollectionManager.cs │ │ │ │ │ ├── MemoryManager.cs │ │ │ │ │ ├── ThreadManager.cs │ │ │ │ │ ├── TimerPool.cs │ │ │ │ │ └── TypeSystemManager.cs │ │ │ │ ├── CortexM3OnMBED/ │ │ │ │ │ ├── CortexM3OnMBED.csproj │ │ │ │ │ ├── HardwareModel/ │ │ │ │ │ │ ├── Board.cs │ │ │ │ │ │ ├── Device.cs │ │ │ │ │ │ ├── Drivers/ │ │ │ │ │ │ │ ├── InterruptController.cs │ │ │ │ │ │ │ ├── SerialPortsManager.cs │ │ │ │ │ │ │ └── SystemTimer.cs │ │ │ │ │ │ ├── HardwareProvider.cs │ │ │ │ │ │ ├── HardwareProviders/ │ │ │ │ │ │ │ ├── AdcProvider.cs │ │ │ │ │ │ │ ├── GpioProvider.cs │ │ │ │ │ │ │ ├── I2cProvider.cs │ │ │ │ │ │ │ ├── NetworkInterfaceProvider.cs │ │ │ │ │ │ │ ├── PwmProvider.cs │ │ │ │ │ │ │ ├── SocketProvider.cs │ │ │ │ │ │ │ └── SpiProvider.cs │ │ │ │ │ │ ├── Memory.cs │ │ │ │ │ │ ├── Peripherals.cs │ │ │ │ │ │ ├── Processor.cs │ │ │ │ │ │ └── Storage.cs │ │ │ │ │ ├── Properties/ │ │ │ │ │ │ └── AssemblyInfo.cs │ │ │ │ │ └── SystemServices/ │ │ │ │ │ ├── GarbageCollectionManager.cs │ │ │ │ │ ├── MemoryManager.cs │ │ │ │ │ ├── ThreadManager.cs │ │ │ │ │ ├── TimerPool.cs │ │ │ │ │ └── TypeSystemManager.cs │ │ │ │ ├── CortexM4OnCMSIS-Core/ │ │ │ │ │ ├── CortexM4OnCMSIS-Core.csproj │ │ │ │ │ ├── HardwareModel/ │ │ │ │ │ │ ├── Board.cs │ │ │ │ │ │ ├── Device.cs │ │ │ │ │ │ ├── Drivers/ │ │ │ │ │ │ │ ├── ContextSwitchTimer.cs │ │ │ │ │ │ │ └── InterruptController.cs │ │ │ │ │ │ ├── HardwareProvider.cs │ │ │ │ │ │ ├── Memory.cs │ │ │ │ │ │ ├── Peripherals.cs │ │ │ │ │ │ ├── Processor.cs │ │ │ │ │ │ └── Storage.cs │ │ │ │ │ ├── Properties/ │ │ │ │ │ │ └── AssemblyInfo.cs │ │ │ │ │ └── SystemServices/ │ │ │ │ │ ├── GarbageCollectionManager.cs │ │ │ │ │ ├── MemoryManager.cs │ │ │ │ │ ├── ThreadManager.cs │ │ │ │ │ ├── TimerPool.cs │ │ │ │ │ └── TypeSystemManager.cs │ │ │ │ ├── CortexM4OnMBED/ │ │ │ │ │ ├── CortexM4OnMBED.csproj │ │ │ │ │ ├── HardwareModel/ │ │ │ │ │ │ ├── Board.cs │ │ │ │ │ │ ├── Device.cs │ │ │ │ │ │ ├── Drivers/ │ │ │ │ │ │ │ ├── InterruptController.cs │ │ │ │ │ │ │ └── SystemTimer.cs │ │ │ │ │ │ ├── HardwareProvider.cs │ │ │ │ │ │ ├── HardwareProviders/ │ │ │ │ │ │ │ ├── GpioProvider.cs │ │ │ │ │ │ │ ├── I2cProvider.cs │ │ │ │ │ │ │ └── SpiProvider.cs │ │ │ │ │ │ ├── Memory.cs │ │ │ │ │ │ ├── Peripherals.cs │ │ │ │ │ │ ├── Processor.cs │ │ │ │ │ │ ├── SpiProvider.cs │ │ │ │ │ │ └── Storage.cs │ │ │ │ │ ├── Properties/ │ │ │ │ │ │ └── AssemblyInfo.cs │ │ │ │ │ └── SystemServices/ │ │ │ │ │ ├── GarbageCollectionManager.cs │ │ │ │ │ ├── MemoryManager.cs │ │ │ │ │ ├── ThreadManager.cs │ │ │ │ │ ├── TimerPool.cs │ │ │ │ │ └── TypeSystemManager.cs │ │ │ │ ├── ExternalLinking_Tester/ │ │ │ │ │ ├── ExternalLinking_Tester.csproj │ │ │ │ │ ├── Program.cs │ │ │ │ │ └── Properties/ │ │ │ │ │ └── AssemblyInfo.cs │ │ │ │ ├── FileSystemSample/ │ │ │ │ │ ├── FileSystemSample.csproj │ │ │ │ │ ├── Program.cs │ │ │ │ │ └── Properties/ │ │ │ │ │ └── AssemblyInfo.cs │ │ │ │ ├── ModelForCortexM/ │ │ │ │ │ ├── HardwareModel/ │ │ │ │ │ │ ├── Board.cs │ │ │ │ │ │ ├── ChipSet/ │ │ │ │ │ │ │ └── StandardPeripherals/ │ │ │ │ │ │ │ ├── NVIC.cs │ │ │ │ │ │ │ └── SysTick.cs │ │ │ │ │ │ └── Drivers/ │ │ │ │ │ │ ├── ContextSwitchTimer.cs │ │ │ │ │ │ └── InterruptController.cs │ │ │ │ │ ├── ModelForCortexM.csproj │ │ │ │ │ ├── Properties/ │ │ │ │ │ │ └── AssemblyInfo.cs │ │ │ │ │ └── SystemServices/ │ │ │ │ │ └── ThreadManager.cs │ │ │ │ ├── ModelForCortexM0/ │ │ │ │ │ ├── HardwareModel/ │ │ │ │ │ │ ├── Board.cs │ │ │ │ │ │ ├── Drivers/ │ │ │ │ │ │ │ ├── ContextSwitchTimer.cs │ │ │ │ │ │ │ └── InterruptController.cs │ │ │ │ │ │ └── Processor.cs │ │ │ │ │ ├── ModelForCortexM0.csproj │ │ │ │ │ ├── Properties/ │ │ │ │ │ │ └── AssemblyInfo.cs │ │ │ │ │ └── SystemServices/ │ │ │ │ │ └── ThreadManager.cs │ │ │ │ ├── ModelForCortexM3/ │ │ │ │ │ ├── HardwareModel/ │ │ │ │ │ │ ├── Board.cs │ │ │ │ │ │ ├── Drivers/ │ │ │ │ │ │ │ ├── ContextSwitchTimer.cs │ │ │ │ │ │ │ └── InterruptController.cs │ │ │ │ │ │ └── Processor.cs │ │ │ │ │ ├── ModelForCortexM3.csproj │ │ │ │ │ ├── Properties/ │ │ │ │ │ │ └── AssemblyInfo.cs │ │ │ │ │ └── SystemServices/ │ │ │ │ │ └── ThreadManager.cs │ │ │ │ ├── ModelForCortexM4/ │ │ │ │ │ ├── HardwareModel/ │ │ │ │ │ │ ├── Board.cs │ │ │ │ │ │ ├── Drivers/ │ │ │ │ │ │ │ ├── ContextSwitchTimer.cs │ │ │ │ │ │ │ └── InterruptController.cs │ │ │ │ │ │ └── Processor.cs │ │ │ │ │ ├── ModelForCortexM4.csproj │ │ │ │ │ ├── Properties/ │ │ │ │ │ │ └── AssemblyInfo.cs │ │ │ │ │ └── SystemServices/ │ │ │ │ │ └── ThreadManager.cs │ │ │ │ ├── ModelForLPC3180/ │ │ │ │ │ ├── HardwareModel/ │ │ │ │ │ │ ├── ChipSet/ │ │ │ │ │ │ │ ├── LPC3180/ │ │ │ │ │ │ │ │ ├── GPDMA.cs │ │ │ │ │ │ │ │ ├── GPIO.cs │ │ │ │ │ │ │ │ ├── HighSpeedTimer.cs │ │ │ │ │ │ │ │ ├── INTC.cs │ │ │ │ │ │ │ │ ├── MilliSecondTimer.cs │ │ │ │ │ │ │ │ ├── MultiLevelNANDController.cs │ │ │ │ │ │ │ │ ├── SDRAMController.cs │ │ │ │ │ │ │ │ ├── StandardUART.cs │ │ │ │ │ │ │ │ └── SystemControl.cs │ │ │ │ │ │ │ └── LPC3180.cs │ │ │ │ │ │ ├── Drivers/ │ │ │ │ │ │ │ ├── InterruptController.cs │ │ │ │ │ │ │ ├── RealTimeClock.cs │ │ │ │ │ │ │ └── StandardSerialPort.cs │ │ │ │ │ │ └── Processor.cs │ │ │ │ │ ├── ModelForLPC3180.csproj │ │ │ │ │ ├── Properties/ │ │ │ │ │ │ └── AssemblyInfo.cs │ │ │ │ │ └── SystemServices/ │ │ │ │ │ ├── SchedulerTimeImpl.cs │ │ │ │ │ ├── SchedulerTimeSpanImpl.cs │ │ │ │ │ ├── SerialPortsManager.cs │ │ │ │ │ └── ThreadManager.cs │ │ │ │ ├── ModelForMM9691LP/ │ │ │ │ │ ├── HardwareModel/ │ │ │ │ │ │ ├── ChipSet/ │ │ │ │ │ │ │ └── MM9691LP/ │ │ │ │ │ │ │ ├── APC.cs │ │ │ │ │ │ │ ├── ARMTIMER0.cs │ │ │ │ │ │ │ ├── ARMTIMER1.cs │ │ │ │ │ │ │ ├── ARMTIMERx.cs │ │ │ │ │ │ │ ├── BUSWATCHER.cs │ │ │ │ │ │ │ ├── CMU.cs │ │ │ │ │ │ │ ├── DMAC.cs │ │ │ │ │ │ │ ├── EBIU.cs │ │ │ │ │ │ │ ├── EDMAIF.cs │ │ │ │ │ │ │ ├── FILTERARCTAN.cs │ │ │ │ │ │ │ ├── GPIO.cs │ │ │ │ │ │ │ ├── INTC.cs │ │ │ │ │ │ │ ├── MWSPI.cs │ │ │ │ │ │ │ ├── PCU.cs │ │ │ │ │ │ │ ├── REMAP_PAUSE.cs │ │ │ │ │ │ │ ├── RTC.cs │ │ │ │ │ │ │ ├── SECURITYKEY.cs │ │ │ │ │ │ │ ├── USART0.cs │ │ │ │ │ │ │ ├── USART1.cs │ │ │ │ │ │ │ ├── USARTx.cs │ │ │ │ │ │ │ ├── USB.cs │ │ │ │ │ │ │ ├── VITERBI.cs │ │ │ │ │ │ │ └── VTU32.cs │ │ │ │ │ │ ├── Drivers/ │ │ │ │ │ │ │ ├── InterruptController.cs │ │ │ │ │ │ │ ├── RealTimeClock.cs │ │ │ │ │ │ │ └── SerialPort.cs │ │ │ │ │ │ └── Processor.cs │ │ │ │ │ ├── ModelForMM9691LP.csproj │ │ │ │ │ ├── Properties/ │ │ │ │ │ │ └── AssemblyInfo.cs │ │ │ │ │ └── SystemServices/ │ │ │ │ │ ├── SchedulerTimeImpl.cs │ │ │ │ │ ├── SchedulerTimeSpanImpl.cs │ │ │ │ │ ├── SerialPortsManager.cs │ │ │ │ │ └── ThreadManager.cs │ │ │ │ ├── ModelForPXA27x/ │ │ │ │ │ ├── HardwareModel/ │ │ │ │ │ │ ├── ChipSet/ │ │ │ │ │ │ │ ├── PXA27x/ │ │ │ │ │ │ │ │ ├── ClockManager.cs │ │ │ │ │ │ │ │ ├── GPIO.cs │ │ │ │ │ │ │ │ ├── I2C.cs │ │ │ │ │ │ │ │ ├── InterruptController.cs │ │ │ │ │ │ │ │ ├── MemoryController.cs │ │ │ │ │ │ │ │ ├── OSTimers.cs │ │ │ │ │ │ │ │ ├── PowerManager.cs │ │ │ │ │ │ │ │ ├── SSP.cs │ │ │ │ │ │ │ │ ├── StackedFlashChip.cs │ │ │ │ │ │ │ │ └── UART.cs │ │ │ │ │ │ │ └── PXA27x.cs │ │ │ │ │ │ ├── Drivers/ │ │ │ │ │ │ │ ├── GPIO.cs │ │ │ │ │ │ │ ├── I2C.cs │ │ │ │ │ │ │ ├── InterruptController.cs │ │ │ │ │ │ │ ├── RealTimeClock.cs │ │ │ │ │ │ │ ├── SPI.cs │ │ │ │ │ │ │ └── SerialPort.cs │ │ │ │ │ │ └── Processor.cs │ │ │ │ │ ├── ModelForPXA27x.csproj │ │ │ │ │ ├── Properties/ │ │ │ │ │ │ └── AssemblyInfo.cs │ │ │ │ │ └── SystemServices/ │ │ │ │ │ ├── SchedulerTimeImpl.cs │ │ │ │ │ ├── SchedulerTimeSpanImpl.cs │ │ │ │ │ ├── SerialPortsManager.cs │ │ │ │ │ └── ThreadManager.cs │ │ │ │ ├── ModelForWin32/ │ │ │ │ │ ├── HardwareModel/ │ │ │ │ │ │ ├── Device.cs │ │ │ │ │ │ ├── HardwareProviders/ │ │ │ │ │ │ │ └── HardwareProvider.cs │ │ │ │ │ │ ├── InterruptsSafeHandle.cs │ │ │ │ │ │ ├── Memory.cs │ │ │ │ │ │ ├── Peripherals.cs │ │ │ │ │ │ ├── Processor.cs │ │ │ │ │ │ └── SerialPortsManager.cs │ │ │ │ │ ├── ModelForWin32.csproj │ │ │ │ │ ├── Properties/ │ │ │ │ │ │ └── AssemblyInfo.cs │ │ │ │ │ └── SystemServices/ │ │ │ │ │ ├── MemoryManager.cs │ │ │ │ │ ├── SchedulerTimeImpl.cs │ │ │ │ │ ├── SchedulerTimeSpanImpl.cs │ │ │ │ │ ├── ThreadManager.cs │ │ │ │ │ └── TypeSystemManager.cs │ │ │ │ ├── NohauLPC3180/ │ │ │ │ │ ├── AudioSamples.Designer.cs │ │ │ │ │ ├── AudioSamples.resx │ │ │ │ │ ├── HardwareModel/ │ │ │ │ │ │ ├── Device.cs │ │ │ │ │ │ ├── Drivers/ │ │ │ │ │ │ │ ├── InterruptController.cs │ │ │ │ │ │ │ └── RealTimeClock.cs │ │ │ │ │ │ ├── Memory.cs │ │ │ │ │ │ ├── Peripherals.cs │ │ │ │ │ │ ├── Processor.cs │ │ │ │ │ │ └── Storage.cs │ │ │ │ │ ├── NohauLPC3180.csproj │ │ │ │ │ ├── Properties/ │ │ │ │ │ │ └── AssemblyInfo.cs │ │ │ │ │ ├── Resources/ │ │ │ │ │ │ └── sample1.pcm │ │ │ │ │ └── SystemServices/ │ │ │ │ │ ├── GarbageCollectionManager.cs │ │ │ │ │ ├── MemoryManager.cs │ │ │ │ │ ├── SerialPortsManager.cs │ │ │ │ │ ├── ThreadManager.cs │ │ │ │ │ └── TypeSystemManager.cs │ │ │ │ ├── NohauLPC3180Loader/ │ │ │ │ │ ├── HardwareModel/ │ │ │ │ │ │ ├── Device.cs │ │ │ │ │ │ ├── Drivers/ │ │ │ │ │ │ │ ├── InterruptController.cs │ │ │ │ │ │ │ └── RealTimeClock.cs │ │ │ │ │ │ ├── Memory.cs │ │ │ │ │ │ ├── Peripherals.cs │ │ │ │ │ │ ├── Processor.cs │ │ │ │ │ │ └── Storage.cs │ │ │ │ │ ├── Loader.cs │ │ │ │ │ ├── NohauLPC3180Loader.csproj │ │ │ │ │ └── Properties/ │ │ │ │ │ └── AssemblyInfo.cs │ │ │ │ ├── NohauLPC3180Tester/ │ │ │ │ │ ├── NohauLPC3180Tester.csproj │ │ │ │ │ ├── Properties/ │ │ │ │ │ │ └── AssemblyInfo.cs │ │ │ │ │ └── Tester.cs │ │ │ │ ├── Perf/ │ │ │ │ │ ├── Dhrystone/ │ │ │ │ │ │ ├── DhrystoneTest.csproj │ │ │ │ │ │ ├── Properties/ │ │ │ │ │ │ │ └── AssemblyInfo.cs │ │ │ │ │ │ └── dhrystone.cs │ │ │ │ │ ├── Whetstone/ │ │ │ │ │ │ ├── Properties/ │ │ │ │ │ │ │ └── AssemblyInfo.cs │ │ │ │ │ │ ├── Whetstone.cs │ │ │ │ │ │ └── WhetstoneTest.csproj │ │ │ │ │ └── v8/ │ │ │ │ │ └── crypto/ │ │ │ │ │ └── CryptoTest/ │ │ │ │ │ ├── CryptoTest.csproj │ │ │ │ │ ├── Properties/ │ │ │ │ │ │ └── AssemblyInfo.cs │ │ │ │ │ └── crypto.cs │ │ │ │ ├── QuickTest/ │ │ │ │ │ ├── Program.cs │ │ │ │ │ ├── Properties/ │ │ │ │ │ │ └── AssemblyInfo.cs │ │ │ │ │ └── QuickTest.csproj │ │ │ │ ├── TestMethodGen/ │ │ │ │ │ ├── Program.cs │ │ │ │ │ ├── Properties/ │ │ │ │ │ │ └── AssemblyInfo.cs │ │ │ │ │ └── TestMethodGen.csproj │ │ │ │ ├── VoxSoloFormFactor/ │ │ │ │ │ ├── HardwareModel/ │ │ │ │ │ │ ├── Device.cs │ │ │ │ │ │ ├── Drivers/ │ │ │ │ │ │ │ ├── InterruptController.cs │ │ │ │ │ │ │ └── RealTimeClock.cs │ │ │ │ │ │ ├── Memory.cs │ │ │ │ │ │ ├── Peripherals.cs │ │ │ │ │ │ ├── Processor.cs │ │ │ │ │ │ └── Storage.cs │ │ │ │ │ ├── Properties/ │ │ │ │ │ │ └── AssemblyInfo.cs │ │ │ │ │ ├── SystemServices/ │ │ │ │ │ │ ├── GarbageCollectionManager.cs │ │ │ │ │ │ ├── MemoryManager.cs │ │ │ │ │ │ ├── SerialPortsManager.cs │ │ │ │ │ │ ├── ThreadManager.cs │ │ │ │ │ │ └── TypeSystemManager.cs │ │ │ │ │ └── VoxSoloFormFactor.csproj │ │ │ │ ├── VoxSoloFormFactorLoader/ │ │ │ │ │ ├── HardwareModel/ │ │ │ │ │ │ ├── Device.cs │ │ │ │ │ │ ├── Drivers/ │ │ │ │ │ │ │ ├── InterruptController.cs │ │ │ │ │ │ │ └── RealTimeClock.cs │ │ │ │ │ │ ├── Memory.cs │ │ │ │ │ │ ├── Peripherals.cs │ │ │ │ │ │ ├── Processor.cs │ │ │ │ │ │ └── Storage.cs │ │ │ │ │ ├── Loader.cs │ │ │ │ │ ├── Properties/ │ │ │ │ │ │ └── AssemblyInfo.cs │ │ │ │ │ └── VoxSoloFormFactorLoader.csproj │ │ │ │ ├── VoxSoloFormFactorTester/ │ │ │ │ │ ├── Properties/ │ │ │ │ │ │ └── AssemblyInfo.cs │ │ │ │ │ ├── Tester.cs │ │ │ │ │ └── VoxSoloFormFactorTester.csproj │ │ │ │ ├── iMote2/ │ │ │ │ │ ├── HardwareModel/ │ │ │ │ │ │ ├── Device.cs │ │ │ │ │ │ ├── Drivers/ │ │ │ │ │ │ │ ├── GPIO.cs │ │ │ │ │ │ │ ├── I2C.cs │ │ │ │ │ │ │ ├── InterruptController.cs │ │ │ │ │ │ │ ├── RealTimeClock.cs │ │ │ │ │ │ │ └── SPI.cs │ │ │ │ │ │ ├── Memory.cs │ │ │ │ │ │ ├── Peripherals.cs │ │ │ │ │ │ ├── Processor.cs │ │ │ │ │ │ └── Storage.cs │ │ │ │ │ ├── Properties/ │ │ │ │ │ │ └── AssemblyInfo.cs │ │ │ │ │ ├── SystemServices/ │ │ │ │ │ │ ├── GarbageCollectionManager.cs │ │ │ │ │ │ ├── MemoryManager.cs │ │ │ │ │ │ ├── SerialPortsManager.cs │ │ │ │ │ │ ├── ThreadManager.cs │ │ │ │ │ │ └── TypeSystemManager.cs │ │ │ │ │ └── iMote2.csproj │ │ │ │ ├── iMote2Loader/ │ │ │ │ │ ├── HardwareModel/ │ │ │ │ │ │ ├── Device.cs │ │ │ │ │ │ ├── Drivers/ │ │ │ │ │ │ │ ├── GPIO.cs │ │ │ │ │ │ │ ├── I2C.cs │ │ │ │ │ │ │ ├── InterruptController.cs │ │ │ │ │ │ │ ├── RealTimeClock.cs │ │ │ │ │ │ │ └── SPI.cs │ │ │ │ │ │ ├── Memory.cs │ │ │ │ │ │ ├── Peripherals.cs │ │ │ │ │ │ ├── Processor.cs │ │ │ │ │ │ └── Storage.cs │ │ │ │ │ ├── Loader.cs │ │ │ │ │ ├── Properties/ │ │ │ │ │ │ └── AssemblyInfo.cs │ │ │ │ │ └── iMote2Loader.csproj │ │ │ │ ├── iMote2Tester/ │ │ │ │ │ ├── Properties/ │ │ │ │ │ │ └── AssemblyInfo.cs │ │ │ │ │ ├── Tester.cs │ │ │ │ │ ├── UnitTests/ │ │ │ │ │ │ ├── I2C.Tests.cs │ │ │ │ │ │ ├── LED.Tests.cs │ │ │ │ │ │ ├── Serial.Tests.cs │ │ │ │ │ │ └── UnitTest.Interface.cs │ │ │ │ │ └── iMote2Tester.csproj │ │ │ │ ├── lwIP/ │ │ │ │ │ ├── Microsoft.Llilum.Lwip.csproj │ │ │ │ │ ├── NetworkInterface.cs │ │ │ │ │ └── Properties/ │ │ │ │ │ └── AssemblyInfo.cs │ │ │ │ └── mbed/ │ │ │ │ ├── Properties/ │ │ │ │ │ └── AssemblyInfo.cs │ │ │ │ ├── Threading.cs │ │ │ │ ├── Timer.cs │ │ │ │ ├── UsTicker.cs │ │ │ │ ├── Utilities.cs │ │ │ │ └── mbed.csproj │ │ │ ├── Framework/ │ │ │ │ ├── Llilum/ │ │ │ │ │ └── Devices/ │ │ │ │ │ ├── Adc/ │ │ │ │ │ │ ├── AdcChannel.cs │ │ │ │ │ │ ├── AdcChannelInfo.cs │ │ │ │ │ │ └── AdcPin.cs │ │ │ │ │ ├── Gpio/ │ │ │ │ │ │ └── GpioPin.cs │ │ │ │ │ ├── I2c/ │ │ │ │ │ │ ├── I2cChannel.cs │ │ │ │ │ │ ├── I2cChannelInfo.cs │ │ │ │ │ │ └── I2cDevice.cs │ │ │ │ │ ├── Microsoft.Llilum.Devices.csproj │ │ │ │ │ ├── Properties/ │ │ │ │ │ │ └── AssemblyInfo.cs │ │ │ │ │ ├── Pwm/ │ │ │ │ │ │ ├── PwmChannel.cs │ │ │ │ │ │ ├── PwmChannelInfo.cs │ │ │ │ │ │ └── PwmPin.cs │ │ │ │ │ └── Spi/ │ │ │ │ │ ├── SpiChannel.cs │ │ │ │ │ ├── SpiChannelInfo.cs │ │ │ │ │ └── SpiDevice.cs │ │ │ │ ├── System.Runtime.WindowsRuntime/ │ │ │ │ │ ├── Properties/ │ │ │ │ │ │ └── AssemblyInfo.cs │ │ │ │ │ ├── System.Runtime.WindowsRuntime.csproj │ │ │ │ │ └── WindowsRuntimeSystemExtensions.cs │ │ │ │ ├── System_Core/ │ │ │ │ │ ├── Properties/ │ │ │ │ │ │ └── AssemblyInfo.cs │ │ │ │ │ ├── System/ │ │ │ │ │ │ ├── FuncAndAction.cs │ │ │ │ │ │ └── Runtime/ │ │ │ │ │ │ └── CompilerServices/ │ │ │ │ │ │ └── Extension.cs │ │ │ │ │ └── system_core.csproj │ │ │ │ ├── Windows/ │ │ │ │ │ ├── Devices/ │ │ │ │ │ │ ├── Adc/ │ │ │ │ │ │ │ ├── AdcChannel.cs │ │ │ │ │ │ │ ├── AdcChannelMode.cs │ │ │ │ │ │ │ ├── AdcController.cs │ │ │ │ │ │ │ ├── IAdcControllerProvider.cs │ │ │ │ │ │ │ ├── IAdcProvider.cs │ │ │ │ │ │ │ └── ProviderAdcChannelMode.cs │ │ │ │ │ │ ├── Enumeration/ │ │ │ │ │ │ │ ├── DeviceInformation.cs │ │ │ │ │ │ │ └── DeviceInformationCollection.cs │ │ │ │ │ │ ├── Gpio/ │ │ │ │ │ │ │ ├── DefaultPinProvider.cs │ │ │ │ │ │ │ ├── GpioController.cs │ │ │ │ │ │ │ ├── GpioEnums.cs │ │ │ │ │ │ │ ├── GpioPin.cs │ │ │ │ │ │ │ ├── GpioPinProvider.cs │ │ │ │ │ │ │ └── GpioPinValueChangedEventArgs.cs │ │ │ │ │ │ ├── I2c/ │ │ │ │ │ │ │ ├── I2cConnectionSettings.cs │ │ │ │ │ │ │ ├── I2cDevice.cs │ │ │ │ │ │ │ └── I2cEnums.cs │ │ │ │ │ │ ├── Pwm/ │ │ │ │ │ │ │ ├── DefaultPwmControllerProvider.cs │ │ │ │ │ │ │ ├── IPwmControllerProvider.cs │ │ │ │ │ │ │ ├── IPwmProvider.cs │ │ │ │ │ │ │ ├── PwmController.cs │ │ │ │ │ │ │ ├── PwmEnums.cs │ │ │ │ │ │ │ └── PwmPin.cs │ │ │ │ │ │ ├── SerialCommunication/ │ │ │ │ │ │ │ ├── SerialCommunicationEnums.cs │ │ │ │ │ │ │ ├── SerialCommunicationEventArgs.cs │ │ │ │ │ │ │ ├── SerialCommunicationInputStream.cs │ │ │ │ │ │ │ ├── SerialCommunicationOutputStream.cs │ │ │ │ │ │ │ └── SerialDevice.cs │ │ │ │ │ │ └── Spi/ │ │ │ │ │ │ ├── SpiBusInfo.cs │ │ │ │ │ │ ├── SpiChannel.cs │ │ │ │ │ │ ├── SpiConnectionSettings.cs │ │ │ │ │ │ ├── SpiDevice.cs │ │ │ │ │ │ └── SpiEnums.cs │ │ │ │ │ ├── Foundation/ │ │ │ │ │ │ ├── Delegates.cs │ │ │ │ │ │ ├── Enums.cs │ │ │ │ │ │ ├── IAsyncAction.cs │ │ │ │ │ │ ├── IAsyncInfo.cs │ │ │ │ │ │ ├── IAsyncOperation.cs │ │ │ │ │ │ └── IAsyncOperationWithProgress.cs │ │ │ │ │ ├── Internal/ │ │ │ │ │ │ ├── AsyncActionFromTask.cs │ │ │ │ │ │ ├── AsyncOperationFromTask.cs │ │ │ │ │ │ ├── AsyncOperationWithProgressFromTask.cs │ │ │ │ │ │ ├── ByteBuffer.cs │ │ │ │ │ │ ├── SynchronousOperation.cs │ │ │ │ │ │ └── WindowsRuntimeSystemExtensions.cs │ │ │ │ │ ├── Properties/ │ │ │ │ │ │ └── AssemblyInfo.cs │ │ │ │ │ ├── Storage/ │ │ │ │ │ │ └── Streams/ │ │ │ │ │ │ ├── ByteOrder.cs │ │ │ │ │ │ ├── DataReader.cs │ │ │ │ │ │ ├── DataReaderLoadOperation.cs │ │ │ │ │ │ ├── DataWriter.cs │ │ │ │ │ │ ├── DataWriterStoreOperation.cs │ │ │ │ │ │ ├── IBuffer.cs │ │ │ │ │ │ ├── IInputStream.cs │ │ │ │ │ │ └── IOutputStream.cs │ │ │ │ │ ├── System/ │ │ │ │ │ │ └── Threading/ │ │ │ │ │ │ ├── ThreadPool.cs │ │ │ │ │ │ ├── ThreadPoolTimer.cs │ │ │ │ │ │ ├── ThreadingDelegates.cs │ │ │ │ │ │ └── ThreadingEnums.cs │ │ │ │ │ └── Windows.csproj │ │ │ │ ├── mscorlib/ │ │ │ │ │ ├── Properties/ │ │ │ │ │ │ └── AssemblyInfo.cs │ │ │ │ │ ├── System/ │ │ │ │ │ │ ├── Action.cs │ │ │ │ │ │ ├── Activator.cs │ │ │ │ │ │ ├── AggregateException.cs │ │ │ │ │ │ ├── ApplicationException.cs │ │ │ │ │ │ ├── ArgumentException.cs │ │ │ │ │ │ ├── ArgumentNullException.cs │ │ │ │ │ │ ├── ArgumentOutOfRangeException.cs │ │ │ │ │ │ ├── ArithmeticException.cs │ │ │ │ │ │ ├── Array.cs │ │ │ │ │ │ ├── ArrayTypeMismatchException.cs │ │ │ │ │ │ ├── AssemblyHandle.cs │ │ │ │ │ │ ├── AsyncCallback.cs │ │ │ │ │ │ ├── Attribute.cs │ │ │ │ │ │ ├── AttributeTargets.cs │ │ │ │ │ │ ├── AttributeUsageAttribute.cs │ │ │ │ │ │ ├── BCLDebug.cs │ │ │ │ │ │ ├── BitConverter.cs │ │ │ │ │ │ ├── Boolean.cs │ │ │ │ │ │ ├── Buffer.cs │ │ │ │ │ │ ├── Byte.cs │ │ │ │ │ │ ├── CLSCompliantAttribute.cs │ │ │ │ │ │ ├── Char.cs │ │ │ │ │ │ ├── CharEnumerator.cs │ │ │ │ │ │ ├── Collections/ │ │ │ │ │ │ │ ├── ArrayList.cs │ │ │ │ │ │ │ ├── BitArray.cs │ │ │ │ │ │ │ ├── Comparer.cs │ │ │ │ │ │ │ ├── DictionaryEntry.cs │ │ │ │ │ │ │ ├── Generic/ │ │ │ │ │ │ │ │ ├── ArraySortHelper.cs │ │ │ │ │ │ │ │ ├── Comparer.cs │ │ │ │ │ │ │ │ ├── Dictionary.cs │ │ │ │ │ │ │ │ ├── EqualityComparer.cs │ │ │ │ │ │ │ │ ├── ICollection.cs │ │ │ │ │ │ │ │ ├── IComparer.cs │ │ │ │ │ │ │ │ ├── IDictionary.cs │ │ │ │ │ │ │ │ ├── IEnumerable.cs │ │ │ │ │ │ │ │ ├── IEnumerator.cs │ │ │ │ │ │ │ │ ├── IEqualityComparer.cs │ │ │ │ │ │ │ │ ├── IList.cs │ │ │ │ │ │ │ │ ├── KeyNotFoundException.cs │ │ │ │ │ │ │ │ ├── KeyValuePair.cs │ │ │ │ │ │ │ │ └── List.cs │ │ │ │ │ │ │ ├── Hashtable.cs │ │ │ │ │ │ │ ├── ICollection.cs │ │ │ │ │ │ │ ├── IComparer.cs │ │ │ │ │ │ │ ├── IDictionary.cs │ │ │ │ │ │ │ ├── IDictionaryEnumerator.cs │ │ │ │ │ │ │ ├── IEnumerable.cs │ │ │ │ │ │ │ ├── IEnumerator.cs │ │ │ │ │ │ │ ├── IEqualityComparer.cs │ │ │ │ │ │ │ ├── IList.cs │ │ │ │ │ │ │ ├── KeyValuePairs.cs │ │ │ │ │ │ │ ├── ObjectModel/ │ │ │ │ │ │ │ │ ├── Collection.cs │ │ │ │ │ │ │ │ ├── KeyedCollection.cs │ │ │ │ │ │ │ │ └── ReadOnlyCollection.cs │ │ │ │ │ │ │ ├── Queue.cs │ │ │ │ │ │ │ ├── ReadOnlyCollectionBase.cs │ │ │ │ │ │ │ ├── SortedList.cs │ │ │ │ │ │ │ └── Stack.cs │ │ │ │ │ │ ├── Configuration/ │ │ │ │ │ │ │ └── Assemblies/ │ │ │ │ │ │ │ ├── AssemblyHashAlgorithm.cs │ │ │ │ │ │ │ └── AssemblyVersionCompatibility.cs │ │ │ │ │ │ ├── Console.cs │ │ │ │ │ │ ├── ConsoleColor.cs │ │ │ │ │ │ ├── Convert.cs │ │ │ │ │ │ ├── CurrentTimeZone.cs │ │ │ │ │ │ ├── DBNull.cs │ │ │ │ │ │ ├── DateTime.cs │ │ │ │ │ │ ├── DateTimeKind.cs │ │ │ │ │ │ ├── DayOfWeek.cs │ │ │ │ │ │ ├── Decimal.cs │ │ │ │ │ │ ├── Delegate.cs │ │ │ │ │ │ ├── Diagnostics/ │ │ │ │ │ │ │ ├── CodeAnalysis/ │ │ │ │ │ │ │ │ └── SuppressMessageAttribute.cs │ │ │ │ │ │ │ ├── ConditionalAttribute.cs │ │ │ │ │ │ │ ├── Contracts/ │ │ │ │ │ │ │ │ └── Contracts.cs │ │ │ │ │ │ │ ├── Debugger.cs │ │ │ │ │ │ │ ├── DebuggerAttributes.cs │ │ │ │ │ │ │ ├── StackFrame.cs │ │ │ │ │ │ │ └── StackTrace.cs │ │ │ │ │ │ ├── DivideByZeroException.cs │ │ │ │ │ │ ├── Double.cs │ │ │ │ │ │ ├── Empty.cs │ │ │ │ │ │ ├── Enum.cs │ │ │ │ │ │ ├── Environment.cs │ │ │ │ │ │ ├── EventArgs.cs │ │ │ │ │ │ ├── EventHandler.cs │ │ │ │ │ │ ├── Exception.cs │ │ │ │ │ │ ├── FlagsAttribute.cs │ │ │ │ │ │ ├── FormatException.cs │ │ │ │ │ │ ├── GC.cs │ │ │ │ │ │ ├── Globalization/ │ │ │ │ │ │ │ ├── BaseInfoTable.cs │ │ │ │ │ │ │ ├── Calendar.cs │ │ │ │ │ │ │ ├── CalendarAlgorithmType.cs │ │ │ │ │ │ │ ├── CalendarTable.cs │ │ │ │ │ │ │ ├── CalendarWeekRule.cs │ │ │ │ │ │ │ ├── CharUnicodeInfo.cs │ │ │ │ │ │ │ ├── CompareInfo.cs │ │ │ │ │ │ │ ├── CultureInfo.cs │ │ │ │ │ │ │ ├── CultureTableRecord.cs │ │ │ │ │ │ │ ├── DateTimeFormat.cs │ │ │ │ │ │ │ ├── DateTimeFormatInfo.cs │ │ │ │ │ │ │ ├── DateTimeParse.cs │ │ │ │ │ │ │ ├── DateTimeStyles.cs │ │ │ │ │ │ │ ├── DaylightTime.cs │ │ │ │ │ │ │ ├── DigitShapes.cs │ │ │ │ │ │ │ ├── GregorianCalendar.cs │ │ │ │ │ │ │ ├── GregorianCalendarTypes.cs │ │ │ │ │ │ │ ├── NumberFormatInfo.cs │ │ │ │ │ │ │ ├── NumberStyles.cs │ │ │ │ │ │ │ └── TextInfo.cs │ │ │ │ │ │ ├── Guid.cs │ │ │ │ │ │ ├── IAsyncResult.cs │ │ │ │ │ │ ├── ICloneable.cs │ │ │ │ │ │ ├── IComparable.cs │ │ │ │ │ │ ├── IConvertible.cs │ │ │ │ │ │ ├── ICustomFormatter.cs │ │ │ │ │ │ ├── IDisposable.cs │ │ │ │ │ │ ├── IEquatable.cs │ │ │ │ │ │ ├── IFormatProvider.cs │ │ │ │ │ │ ├── IFormattable.cs │ │ │ │ │ │ ├── IO/ │ │ │ │ │ │ │ ├── BinaryReader.cs │ │ │ │ │ │ │ ├── BinaryWriter.cs │ │ │ │ │ │ │ ├── Directory.cs │ │ │ │ │ │ │ ├── DirectoryInfo.cs │ │ │ │ │ │ │ ├── EndOfStreamException.cs │ │ │ │ │ │ │ ├── File.cs │ │ │ │ │ │ │ ├── FileAccess.cs │ │ │ │ │ │ │ ├── FileAttributes.cs │ │ │ │ │ │ │ ├── FileEnum.cs │ │ │ │ │ │ │ ├── FileInfo.cs │ │ │ │ │ │ │ ├── FileMode.cs │ │ │ │ │ │ │ ├── FileShare.cs │ │ │ │ │ │ │ ├── FileStream.cs │ │ │ │ │ │ │ ├── FileSystemInfo.cs │ │ │ │ │ │ │ ├── FileSystemManager.cs │ │ │ │ │ │ │ ├── IO.cs │ │ │ │ │ │ │ ├── IOException.cs │ │ │ │ │ │ │ ├── MediaManager.cs │ │ │ │ │ │ │ ├── MemoryStream.cs │ │ │ │ │ │ │ ├── Path.cs │ │ │ │ │ │ │ ├── SeekOrigin.cs │ │ │ │ │ │ │ ├── Stream.cs │ │ │ │ │ │ │ ├── StreamReader.cs │ │ │ │ │ │ │ ├── StreamWriter.cs │ │ │ │ │ │ │ ├── TextReader.cs │ │ │ │ │ │ │ ├── TextWriter.cs │ │ │ │ │ │ │ └── __Error.cs │ │ │ │ │ │ ├── IServiceObjectProvider.cs │ │ │ │ │ │ ├── IndexOutOfRangeException.cs │ │ │ │ │ │ ├── Int16.cs │ │ │ │ │ │ ├── Int32.cs │ │ │ │ │ │ ├── Int64.cs │ │ │ │ │ │ ├── IntPtr.cs │ │ │ │ │ │ ├── InvalidCastException.cs │ │ │ │ │ │ ├── InvalidOperationException.cs │ │ │ │ │ │ ├── InvalidProgramException.cs │ │ │ │ │ │ ├── MarshalByRefObject.cs │ │ │ │ │ │ ├── Math.cs │ │ │ │ │ │ ├── MidpointRounding.cs │ │ │ │ │ │ ├── MulticastDelegate.cs │ │ │ │ │ │ ├── MulticastNotSupportedException.cs │ │ │ │ │ │ ├── NonSerializedAttribute.cs │ │ │ │ │ │ ├── NotFiniteNumberException.cs │ │ │ │ │ │ ├── NotImplementedException.cs │ │ │ │ │ │ ├── NotSupportedException.cs │ │ │ │ │ │ ├── NullReferenceException.cs │ │ │ │ │ │ ├── Nullable.cs │ │ │ │ │ │ ├── Number.cs │ │ │ │ │ │ ├── Object.cs │ │ │ │ │ │ ├── ObjectDisposedException.cs │ │ │ │ │ │ ├── ObsoleteAttribute.cs │ │ │ │ │ │ ├── OperationCanceledException.cs │ │ │ │ │ │ ├── OutOfMemoryException.cs │ │ │ │ │ │ ├── OverflowException.cs │ │ │ │ │ │ ├── ParamArrayAttribute.cs │ │ │ │ │ │ ├── ParseNumbers.cs │ │ │ │ │ │ ├── Random.cs │ │ │ │ │ │ ├── RankException.cs │ │ │ │ │ │ ├── Reflection/ │ │ │ │ │ │ │ ├── Assembly.cs │ │ │ │ │ │ │ ├── AssemblyAttributes.cs │ │ │ │ │ │ │ ├── Binder.cs │ │ │ │ │ │ │ ├── BindingFlags.cs │ │ │ │ │ │ │ ├── CallingConventions.cs │ │ │ │ │ │ │ ├── ConstructorInfo.cs │ │ │ │ │ │ │ ├── DefaultMemberAttribute.cs │ │ │ │ │ │ │ ├── EventInfo.cs │ │ │ │ │ │ │ ├── FieldInfo.cs │ │ │ │ │ │ │ ├── ICustomAttributeProvider.cs │ │ │ │ │ │ │ ├── IReflect.cs │ │ │ │ │ │ │ ├── InterfaceMapping.cs │ │ │ │ │ │ │ ├── MemberInfo.cs │ │ │ │ │ │ │ ├── MemberTypes.cs │ │ │ │ │ │ │ ├── MethodAttributes.cs │ │ │ │ │ │ │ ├── MethodBase.cs │ │ │ │ │ │ │ ├── MethodImplAttributes.cs │ │ │ │ │ │ │ ├── MethodInfo.cs │ │ │ │ │ │ │ ├── Module.cs │ │ │ │ │ │ │ ├── ParameterAttributes.cs │ │ │ │ │ │ │ ├── ParameterInfo.cs │ │ │ │ │ │ │ ├── ParameterModifier.cs │ │ │ │ │ │ │ ├── PropertyInfo.cs │ │ │ │ │ │ │ ├── RuntimeConstructorInfo.cs │ │ │ │ │ │ │ ├── RuntimeEventInfo.cs │ │ │ │ │ │ │ ├── RuntimeFieldInfo.cs │ │ │ │ │ │ │ ├── RuntimeMethodInfo.cs │ │ │ │ │ │ │ ├── RuntimePropertyInfo.cs │ │ │ │ │ │ │ ├── TypeAttributes.cs │ │ │ │ │ │ │ └── TypeFilter.cs │ │ │ │ │ │ ├── Resources/ │ │ │ │ │ │ │ └── ResourceManager.cs │ │ │ │ │ │ ├── Runtime/ │ │ │ │ │ │ │ ├── CompilerServices/ │ │ │ │ │ │ │ │ ├── AsyncStateMachineAttribute.cs │ │ │ │ │ │ │ │ ├── AsyncTaskMethodBuilder.cs │ │ │ │ │ │ │ │ ├── CompilationRelaxations.cs │ │ │ │ │ │ │ │ ├── CompilerGeneratedAttribute.cs │ │ │ │ │ │ │ │ ├── DecimalConstantAttribute.cs │ │ │ │ │ │ │ │ ├── ExtensionAttribute.cs │ │ │ │ │ │ │ │ ├── IAsyncStateMachine.cs │ │ │ │ │ │ │ │ ├── INotifyCompletion.cs │ │ │ │ │ │ │ │ ├── IndexerNameAttribute.cs │ │ │ │ │ │ │ │ ├── InternalsVisibleToAttribute.cs │ │ │ │ │ │ │ │ ├── IsVolatile.cs │ │ │ │ │ │ │ │ ├── JitHelpers.cs │ │ │ │ │ │ │ │ ├── MethodImplAttribute.cs │ │ │ │ │ │ │ │ ├── RuntimeCompatibilityAttribute.cs │ │ │ │ │ │ │ │ ├── RuntimeHelpers.cs │ │ │ │ │ │ │ │ ├── SpecialNameAttribute.cs │ │ │ │ │ │ │ │ ├── StateMachineAttribute.cs │ │ │ │ │ │ │ │ ├── TaskAwaiter.cs │ │ │ │ │ │ │ │ ├── TypeForwardedFromAttribute.cs │ │ │ │ │ │ │ │ └── UnsafeValueTypeAttribute.cs │ │ │ │ │ │ │ ├── InteropServices/ │ │ │ │ │ │ │ │ ├── Attributes.cs │ │ │ │ │ │ │ │ ├── CallingConvention.cs │ │ │ │ │ │ │ │ ├── CharSet.cs │ │ │ │ │ │ │ │ ├── LayoutKind.cs │ │ │ │ │ │ │ │ └── Marshal.cs │ │ │ │ │ │ │ ├── Reliability/ │ │ │ │ │ │ │ │ ├── CriticalFinalizerObject.cs │ │ │ │ │ │ │ │ ├── PrePrepareMethodAttribute.cs │ │ │ │ │ │ │ │ └── ReliabilityContractAttribute.cs │ │ │ │ │ │ │ └── Serialization/ │ │ │ │ │ │ │ ├── SerializationAttributes.cs │ │ │ │ │ │ │ └── SerializationException.cs │ │ │ │ │ │ ├── RuntimeArgumentHandle.cs │ │ │ │ │ │ ├── RuntimeFieldHandle.cs │ │ │ │ │ │ ├── RuntimeMethodHandle.cs │ │ │ │ │ │ ├── RuntimeType.cs │ │ │ │ │ │ ├── RuntimeTypeHandle.cs │ │ │ │ │ │ ├── SByte.cs │ │ │ │ │ │ ├── Security/ │ │ │ │ │ │ │ ├── Attributes.cs │ │ │ │ │ │ │ ├── Cryptography/ │ │ │ │ │ │ │ │ └── X509Certificates/ │ │ │ │ │ │ │ │ └── X509Certificate.cs │ │ │ │ │ │ │ └── Permissions/ │ │ │ │ │ │ │ ├── HostProtectionPermission.cs │ │ │ │ │ │ │ ├── PermissionAttributes.cs │ │ │ │ │ │ │ ├── PermissionState.cs │ │ │ │ │ │ │ └── SecurityPermission.cs │ │ │ │ │ │ ├── SerializableAttribute.cs │ │ │ │ │ │ ├── Single.cs │ │ │ │ │ │ ├── StackOverflowException.cs │ │ │ │ │ │ ├── String.cs │ │ │ │ │ │ ├── StringComparer.cs │ │ │ │ │ │ ├── StringComparison.cs │ │ │ │ │ │ ├── SystemException.cs │ │ │ │ │ │ ├── TargetFrameworkAttribute.cs │ │ │ │ │ │ ├── Text/ │ │ │ │ │ │ │ ├── ASCIIEncoding.cs │ │ │ │ │ │ │ ├── Decoder.cs │ │ │ │ │ │ │ ├── DecoderBestFitFallback.cs │ │ │ │ │ │ │ ├── DecoderExceptionFallback.cs │ │ │ │ │ │ │ ├── DecoderFallback.cs │ │ │ │ │ │ │ ├── DecoderNLS.cs │ │ │ │ │ │ │ ├── DecoderReplacementFallback.cs │ │ │ │ │ │ │ ├── Encoder.cs │ │ │ │ │ │ │ ├── EncoderBestFitFallback.cs │ │ │ │ │ │ │ ├── EncoderExceptionFallback.cs │ │ │ │ │ │ │ ├── EncoderFallback.cs │ │ │ │ │ │ │ ├── EncoderNLS.cs │ │ │ │ │ │ │ ├── EncoderReplacementFallback.cs │ │ │ │ │ │ │ ├── Encoding.cs │ │ │ │ │ │ │ ├── StringBuilder.cs │ │ │ │ │ │ │ ├── UTF8Encoding.cs │ │ │ │ │ │ │ └── UnicodeEncoding.cs │ │ │ │ │ │ ├── ThreadStaticAttribute.cs │ │ │ │ │ │ ├── Threading/ │ │ │ │ │ │ │ ├── ApartmentState.cs │ │ │ │ │ │ │ ├── AutoResetEvent.cs │ │ │ │ │ │ │ ├── CancellationToken.cs │ │ │ │ │ │ │ ├── CancellationTokenRegistration.cs │ │ │ │ │ │ │ ├── CancellationTokenSource.cs │ │ │ │ │ │ │ ├── EventResetMode.cs │ │ │ │ │ │ │ ├── EventWaitHandle.cs │ │ │ │ │ │ │ ├── Interlocked.cs │ │ │ │ │ │ │ ├── ManualResetEvent.cs │ │ │ │ │ │ │ ├── Monitor.cs │ │ │ │ │ │ │ ├── Mutex.cs │ │ │ │ │ │ │ ├── ParameterizedThreadStart.cs │ │ │ │ │ │ │ ├── SpinWait.cs │ │ │ │ │ │ │ ├── Tasks/ │ │ │ │ │ │ │ │ ├── GenericTask.cs │ │ │ │ │ │ │ │ ├── Task.cs │ │ │ │ │ │ │ │ ├── TaskCanceledException.cs │ │ │ │ │ │ │ │ ├── TaskContinuation.cs │ │ │ │ │ │ │ │ └── TaskScheduler.cs │ │ │ │ │ │ │ ├── Thread.cs │ │ │ │ │ │ │ ├── ThreadAbortException.cs │ │ │ │ │ │ │ ├── ThreadPool.cs │ │ │ │ │ │ │ ├── ThreadPriority.cs │ │ │ │ │ │ │ ├── ThreadStart.cs │ │ │ │ │ │ │ ├── ThreadStartException.cs │ │ │ │ │ │ │ ├── ThreadState.cs │ │ │ │ │ │ │ ├── ThreadStateException.cs │ │ │ │ │ │ │ ├── Timeout.cs │ │ │ │ │ │ │ ├── Timer.cs │ │ │ │ │ │ │ ├── Volatile.cs │ │ │ │ │ │ │ └── WaitHandle.cs │ │ │ │ │ │ ├── ThrowHelper.cs │ │ │ │ │ │ ├── TimeSpan.cs │ │ │ │ │ │ ├── TimeZone.cs │ │ │ │ │ │ ├── TimeoutException.cs │ │ │ │ │ │ ├── Type.cs │ │ │ │ │ │ ├── TypeCode.cs │ │ │ │ │ │ ├── TypedReference.cs │ │ │ │ │ │ ├── UInt16.cs │ │ │ │ │ │ ├── UInt32.cs │ │ │ │ │ │ ├── UInt64.cs │ │ │ │ │ │ ├── UIntPtr.cs │ │ │ │ │ │ ├── UnSafeCharBuffer.cs │ │ │ │ │ │ ├── UnauthorizedAccessException.cs │ │ │ │ │ │ ├── ValueType.cs │ │ │ │ │ │ ├── Version.cs │ │ │ │ │ │ ├── Void.cs │ │ │ │ │ │ └── WeakReference.cs │ │ │ │ │ ├── ZeligHooks/ │ │ │ │ │ │ ├── TypeDependencyAttribute.cs │ │ │ │ │ │ ├── WellKnownFieldAttribute.cs │ │ │ │ │ │ ├── WellKnownMethodAttribute.cs │ │ │ │ │ │ └── WellKnownTypeAttribute.cs │ │ │ │ │ └── mscorlib.csproj │ │ │ │ ├── mscorlib_UnitTest/ │ │ │ │ │ ├── Files.Designer.cs │ │ │ │ │ ├── Files.resx │ │ │ │ │ ├── Program.cs │ │ │ │ │ ├── Properties/ │ │ │ │ │ │ └── AssemblyInfo.cs │ │ │ │ │ ├── Resources/ │ │ │ │ │ │ └── ZeligRefreshBinaryDrop.cmd │ │ │ │ │ ├── Test_OpenClasses.cs │ │ │ │ │ ├── Verify.cs │ │ │ │ │ └── mscorlib_UnitTest.csproj │ │ │ │ └── system/ │ │ │ │ ├── Properties/ │ │ │ │ │ └── AssemblyInfo.cs │ │ │ │ ├── System/ │ │ │ │ │ ├── CodeDOM/ │ │ │ │ │ │ └── Compiler/ │ │ │ │ │ │ └── GeneratedCodeAttribute.cs │ │ │ │ │ ├── Collections/ │ │ │ │ │ │ └── Generic/ │ │ │ │ │ │ ├── LinkedList.cs │ │ │ │ │ │ └── Queue.cs │ │ │ │ │ ├── ComponentModel/ │ │ │ │ │ │ ├── Component.cs │ │ │ │ │ │ ├── ComponentCollection.cs │ │ │ │ │ │ ├── EditorBrowsableAttribute.cs │ │ │ │ │ │ ├── EventHandlerList.cs │ │ │ │ │ │ ├── IComponent.cs │ │ │ │ │ │ ├── IContainer.cs │ │ │ │ │ │ └── ISite.cs │ │ │ │ │ ├── Diagnostics/ │ │ │ │ │ │ ├── Debug.cs │ │ │ │ │ │ ├── DefaultTraceListener.cs │ │ │ │ │ │ ├── Stopwatch.cs │ │ │ │ │ │ ├── Trace.cs │ │ │ │ │ │ ├── TraceEventCache.cs │ │ │ │ │ │ ├── TraceEventType.cs │ │ │ │ │ │ ├── TraceFilter.cs │ │ │ │ │ │ ├── TraceInternal.cs │ │ │ │ │ │ ├── TraceListener.cs │ │ │ │ │ │ ├── TraceListeners.cs │ │ │ │ │ │ └── TraceOption.cs │ │ │ │ │ ├── HTTP/ │ │ │ │ │ │ ├── System.Net.AuthenticationType.cs │ │ │ │ │ │ ├── System.Net.HttpListener.cs │ │ │ │ │ │ ├── System.Net.HttpListenerContext.cs │ │ │ │ │ │ ├── System.Net.HttpListenerRequest.cs │ │ │ │ │ │ ├── System.Net.HttpListenerResponse.cs │ │ │ │ │ │ ├── System.Net.HttpStatusCode.cs │ │ │ │ │ │ ├── System.Net.HttpVersion.cs │ │ │ │ │ │ ├── System.Net.HttpWebRequest.cs │ │ │ │ │ │ ├── System.Net.HttpWebResponse.cs │ │ │ │ │ │ ├── System.Net.IWebProxy.cs │ │ │ │ │ │ ├── System.Net.IWebRequestCreate.cs │ │ │ │ │ │ ├── System.Net.Internal.cs │ │ │ │ │ │ ├── System.Net.NetworkCredential.cs │ │ │ │ │ │ ├── System.Net.ProtocolViolationException.cs │ │ │ │ │ │ ├── System.Net.WebException.cs │ │ │ │ │ │ ├── System.Net.WebHeaders.cs │ │ │ │ │ │ ├── System.Net.WebProxy.cs │ │ │ │ │ │ ├── System.Net.WebRequest.cs │ │ │ │ │ │ ├── System.Net.WebResponse.cs │ │ │ │ │ │ ├── System.Net.WebStatus.cs │ │ │ │ │ │ ├── System.Net._HeaderInfo.cs │ │ │ │ │ │ ├── System.Net._HeaderInfoTable.cs │ │ │ │ │ │ ├── System.Net._HttpDateParse.cs │ │ │ │ │ │ ├── System.Net._InputNetworkStreamWrapper.cs │ │ │ │ │ │ ├── System.Net._OutputNetworkStreamWrapper.cs │ │ │ │ │ │ ├── System.Net._ValidationHelper.cs │ │ │ │ │ │ └── System.Uri.cs │ │ │ │ │ ├── IO/ │ │ │ │ │ │ └── Ports/ │ │ │ │ │ │ ├── Handshake.cs │ │ │ │ │ │ ├── InternalResources.cs │ │ │ │ │ │ ├── Parity.cs │ │ │ │ │ │ ├── SerialErrors.cs │ │ │ │ │ │ ├── SerialPinChanges.cs │ │ │ │ │ │ ├── SerialPort.cs │ │ │ │ │ │ ├── SerialReceived.cs │ │ │ │ │ │ ├── SerialStream.cs │ │ │ │ │ │ └── StopBits.cs │ │ │ │ │ └── Net/ │ │ │ │ │ ├── DNS.cs │ │ │ │ │ ├── EndPoint.cs │ │ │ │ │ ├── IPAddress.cs │ │ │ │ │ ├── IPEndPoint.cs │ │ │ │ │ ├── IPHostEntry.cs │ │ │ │ │ ├── Internal/ │ │ │ │ │ │ └── SocketNative.cs │ │ │ │ │ ├── SocketAddress.cs │ │ │ │ │ ├── SocketException.cs │ │ │ │ │ └── Sockets/ │ │ │ │ │ ├── AddressFamily.cs │ │ │ │ │ ├── NetworkStream.cs │ │ │ │ │ ├── ProtocolFamily.cs │ │ │ │ │ ├── ProtocolType.cs │ │ │ │ │ ├── SelectMode.cs │ │ │ │ │ ├── Socket.cs │ │ │ │ │ ├── SocketErrors.cs │ │ │ │ │ ├── SocketFlags.cs │ │ │ │ │ ├── SocketOptionLevel.cs │ │ │ │ │ ├── SocketOptionName.cs │ │ │ │ │ └── SocketType.cs │ │ │ │ └── system.csproj │ │ │ └── Zelig/ │ │ │ ├── Common/ │ │ │ │ ├── Attributes/ │ │ │ │ │ ├── CallQualifiers/ │ │ │ │ │ │ ├── ActivationRecordEvents.cs │ │ │ │ │ │ ├── BottomOfCallStackAttribute.cs │ │ │ │ │ │ ├── CanAllocateOnReturnAttribute.cs │ │ │ │ │ │ ├── CannotAllocateAttribute.cs │ │ │ │ │ │ ├── DebuggerHookHandlerAttribute.cs │ │ │ │ │ │ ├── DisableBoundsChecksAttribute.cs │ │ │ │ │ │ ├── DisableNullChecksAttribute.cs │ │ │ │ │ │ ├── ExportedMethodAttribute.cs │ │ │ │ │ │ ├── HardwareExceptionHandlerAttribute.cs │ │ │ │ │ │ ├── ImportedMethodReferenceAttribute.cs │ │ │ │ │ │ ├── InlineAttribute.cs │ │ │ │ │ │ ├── NoInlineAttribute.cs │ │ │ │ │ │ ├── NoReturnAttribute.cs │ │ │ │ │ │ ├── SaveFullProcessorContextAttribute.cs │ │ │ │ │ │ ├── StackAvailableOnReturnAttribute.cs │ │ │ │ │ │ └── StackNotAvailableAttribute.cs │ │ │ │ │ ├── CompileTimeOptions/ │ │ │ │ │ │ ├── AlignmentRequirementsAttribute.cs │ │ │ │ │ │ ├── ConfigurationOptionAttribute.cs │ │ │ │ │ │ ├── ForceDevirtualizationAttribute.cs │ │ │ │ │ │ ├── ImplicitInstanceAttribute.cs │ │ │ │ │ │ ├── MemoryRequirementsAttribute.cs │ │ │ │ │ │ ├── MemoryUsageAttribute.cs │ │ │ │ │ │ └── SingletonFactoryAttribute.cs │ │ │ │ │ ├── HardwareModeling/ │ │ │ │ │ │ ├── BitFieldPeripheralAttribute.cs │ │ │ │ │ │ ├── BitFieldRegisterAttribute.cs │ │ │ │ │ │ ├── BitFieldSplitRegisterAttribute.cs │ │ │ │ │ │ ├── MemoryMappedPeripheralAttribute.cs │ │ │ │ │ │ └── RegisterAttribute.cs │ │ │ │ │ ├── OpenClasses/ │ │ │ │ │ │ ├── AliasForBaseFieldAttribute.cs │ │ │ │ │ │ ├── AliasForBaseMethodAttribute.cs │ │ │ │ │ │ ├── AliasForSuperMethodAttribute.cs │ │ │ │ │ │ ├── AliasForTargetMethodAttribute.cs │ │ │ │ │ │ ├── CapabilitiesFilterAttribute.cs │ │ │ │ │ │ ├── DiscardTargetImplementationAttribute.cs │ │ │ │ │ │ ├── ExtendClassAttribute.cs │ │ │ │ │ │ ├── InjectAtEntryPointAttribute.cs │ │ │ │ │ │ ├── InjectAtExitPointAttribute.cs │ │ │ │ │ │ ├── MergeWithTargetImplementationAttribute.cs │ │ │ │ │ │ ├── ProductFilterAttribute.cs │ │ │ │ │ │ └── SingletonFactoryPlatformFilter.cs │ │ │ │ │ └── TypeSystem/ │ │ │ │ │ ├── AllowCompileTimeIntrospectionAttribute.cs │ │ │ │ │ ├── AssumeReferencedAttribute.cs │ │ │ │ │ ├── DisableAutomaticReferenceCountingAttribute.cs │ │ │ │ │ ├── DisableReferenceCountingAttribute.cs │ │ │ │ │ ├── GarbageCollectionExtensionAttribute.cs │ │ │ │ │ ├── GenerateUnsafeCastAttribute.cs │ │ │ │ │ ├── LinkToRuntimeTypeAttribute.cs │ │ │ │ │ ├── NoVTableAttribute.cs │ │ │ │ │ ├── SkipDuringGarbageCollectionAttribute.cs │ │ │ │ │ ├── TypeDependencyAttribute.cs │ │ │ │ │ ├── WellKnownFieldAttribute.cs │ │ │ │ │ ├── WellKnownMethodAttribute.cs │ │ │ │ │ ├── WellKnownTypeAttribute.cs │ │ │ │ │ └── WellKnownTypeLookupAttribute.cs │ │ │ │ ├── Collections/ │ │ │ │ │ ├── BitVector.cs │ │ │ │ │ ├── GrowOnlyHashTable.cs │ │ │ │ │ ├── GrowOnlyList.cs │ │ │ │ │ ├── GrowOnlySet.cs │ │ │ │ │ ├── HashHelpers.cs │ │ │ │ │ ├── ReferenceEqualityComparer.cs │ │ │ │ │ ├── UniqueList.cs │ │ │ │ │ └── WeakEqualityComparer.cs │ │ │ │ ├── Common.csproj │ │ │ │ ├── Configuration/ │ │ │ │ │ ├── Attributes/ │ │ │ │ │ │ ├── AbstractDefaultsAttribute.cs │ │ │ │ │ │ ├── AllowedOptionsAttribute.cs │ │ │ │ │ │ ├── DefaultsAttribute.cs │ │ │ │ │ │ ├── DependsOnAttribute.cs │ │ │ │ │ │ ├── DisplayNameAttribute.cs │ │ │ │ │ │ ├── EnumDefaultsAttribute.cs │ │ │ │ │ │ ├── HardwareModelAttribute.cs │ │ │ │ │ │ ├── LinkToConfigurationOptionAttribute.cs │ │ │ │ │ │ ├── MemorySectionAttribute.cs │ │ │ │ │ │ ├── MergeEnumDefaultsAttribute.cs │ │ │ │ │ │ ├── RequiresAttribute.cs │ │ │ │ │ │ └── ReserveBlockAttribute.cs │ │ │ │ │ ├── Categories/ │ │ │ │ │ │ ├── AbstractCategory.cs │ │ │ │ │ │ ├── BusAttachedCategory.cs │ │ │ │ │ │ ├── BusControllerCategory.cs │ │ │ │ │ │ ├── CacheControllerCategory.cs │ │ │ │ │ │ ├── CompilationSetupCategory.cs │ │ │ │ │ │ ├── DisplayCategory.cs │ │ │ │ │ │ ├── EngineCategory.cs │ │ │ │ │ │ ├── FlashMemoryCategory.cs │ │ │ │ │ │ ├── InteropCategory.cs │ │ │ │ │ │ ├── JtagLoaderCategory.cs │ │ │ │ │ │ ├── LoaderCompilationSetupCategory.cs │ │ │ │ │ │ ├── MemoryCategory.cs │ │ │ │ │ │ ├── MemoryMapCategory.cs │ │ │ │ │ │ ├── PeripheralCategory.cs │ │ │ │ │ │ ├── ProcessorCategory.cs │ │ │ │ │ │ ├── ProductCategory.cs │ │ │ │ │ │ └── RamMemoryCategory.cs │ │ │ │ │ ├── ImageSection.cs │ │ │ │ │ └── Interfaces/ │ │ │ │ │ └── IMemoryMapper.cs │ │ │ │ ├── Debugging/ │ │ │ │ │ ├── DebugInfo.cs │ │ │ │ │ └── MethodDebugInfo.cs │ │ │ │ ├── Exceptions/ │ │ │ │ │ ├── AssertionViolationException.cs │ │ │ │ │ ├── IncorrectEncodingException.cs │ │ │ │ │ ├── NotSupportedException.cs │ │ │ │ │ └── TypeConsistencyErrorException.cs │ │ │ │ ├── Helpers/ │ │ │ │ │ ├── AddressMath.cs │ │ │ │ │ ├── ArrayUtility.cs │ │ │ │ │ ├── CRC32.cs │ │ │ │ │ ├── Checks.cs │ │ │ │ │ ├── DataConversion.cs │ │ │ │ │ ├── HashTableFactory.cs │ │ │ │ │ ├── HashTableWithListFactory.cs │ │ │ │ │ ├── HashTableWithSetFactory.cs │ │ │ │ │ ├── ReflectionHelper.cs │ │ │ │ │ └── SetFactory.cs │ │ │ │ ├── PerformanceCounters/ │ │ │ │ │ ├── ContextualTiming.cs │ │ │ │ │ └── Timing.cs │ │ │ │ └── Properties/ │ │ │ │ └── AssemblyInfo.cs │ │ │ ├── CommonPC/ │ │ │ │ ├── CommonPC.csproj │ │ │ │ ├── Properties/ │ │ │ │ │ └── AssemblyInfo.cs │ │ │ │ └── XmlHelper.cs │ │ │ ├── Kernel/ │ │ │ │ ├── Bootstrap.cs │ │ │ │ ├── FrameworkOverrides/ │ │ │ │ │ ├── ActivatorImpl.cs │ │ │ │ │ ├── ArrayImpl.cs │ │ │ │ │ ├── BufferImpl.cs │ │ │ │ │ ├── ConsoleImpl.cs │ │ │ │ │ ├── CurrentSystemTimeZoneImpl.cs │ │ │ │ │ ├── DateTimeImpl.cs │ │ │ │ │ ├── DelegateImpl.cs │ │ │ │ │ ├── Diagnostics/ │ │ │ │ │ │ ├── DebuggerImpl.cs │ │ │ │ │ │ └── StopwatchImpl.cs │ │ │ │ │ ├── EnvironmentImpl.cs │ │ │ │ │ ├── GCImpl.cs │ │ │ │ │ ├── Globalization/ │ │ │ │ │ │ ├── CompareInfoImpl.cs │ │ │ │ │ │ └── TextInfoImpl.cs │ │ │ │ │ ├── MathImpl.cs │ │ │ │ │ ├── MulticastDelegateImpl.cs │ │ │ │ │ ├── NumberImpl.cs │ │ │ │ │ ├── ObjectImpl.cs │ │ │ │ │ ├── Reflection/ │ │ │ │ │ │ ├── MemberInfoImpl.cs │ │ │ │ │ │ ├── RuntimeFieldHandleImpl.cs │ │ │ │ │ │ ├── RuntimeMethodHandleImpl.cs │ │ │ │ │ │ └── RuntimeTypeHandleImpl.cs │ │ │ │ │ ├── Resources/ │ │ │ │ │ │ └── ResourceManagerImpl.cs │ │ │ │ │ ├── Runtime/ │ │ │ │ │ │ ├── CompilerServices/ │ │ │ │ │ │ │ ├── JitHelpersImpl.cs │ │ │ │ │ │ │ └── RuntimeHelpersImpl.cs │ │ │ │ │ │ └── InteropServices/ │ │ │ │ │ │ └── MarshalImpl.cs │ │ │ │ │ ├── RuntimeTypeImpl.cs │ │ │ │ │ ├── StringImpl.cs │ │ │ │ │ ├── Threading/ │ │ │ │ │ │ ├── EventWaitHandleImpl.cs │ │ │ │ │ │ ├── InterlockedImpl.cs │ │ │ │ │ │ ├── InterlockedImpl_ARMv6M.cs │ │ │ │ │ │ ├── MonitorImpl.cs │ │ │ │ │ │ ├── ThreadImpl.cs │ │ │ │ │ │ ├── ThreadPoolImpl.cs │ │ │ │ │ │ ├── TimerImpl.cs │ │ │ │ │ │ └── WaitHandleImpl.cs │ │ │ │ │ ├── TypeImpl.cs │ │ │ │ │ └── WeakReferenceImpl.cs │ │ │ │ ├── FrameworkOverrides_Llilum/ │ │ │ │ │ └── Devices/ │ │ │ │ │ ├── Adc/ │ │ │ │ │ │ ├── AdcPinImpl.cs │ │ │ │ │ │ └── AdcProvider.cs │ │ │ │ │ ├── Gpio/ │ │ │ │ │ │ ├── GpioPinImpl.cs │ │ │ │ │ │ └── GpioProvider.cs │ │ │ │ │ ├── I2c/ │ │ │ │ │ │ ├── I2cDeviceImpl.cs │ │ │ │ │ │ └── I2cProvider.cs │ │ │ │ │ ├── Pwm/ │ │ │ │ │ │ ├── PwmPinImpl.cs │ │ │ │ │ │ └── PwmProvider.cs │ │ │ │ │ └── Spi/ │ │ │ │ │ ├── SpiDeviceImpl.cs │ │ │ │ │ └── SpiProvider.cs │ │ │ │ ├── FrameworkOverrides_System/ │ │ │ │ │ ├── Diagnostics/ │ │ │ │ │ │ └── DefaultTraceListernerImpl.cs │ │ │ │ │ ├── IO/ │ │ │ │ │ │ ├── MediaManagerImpl.cs │ │ │ │ │ │ ├── NativeFileImpl.cs │ │ │ │ │ │ └── Ports/ │ │ │ │ │ │ ├── BaseSerialStream.cs │ │ │ │ │ │ ├── SerialPortImpl.cs │ │ │ │ │ │ └── SerialStreamImpl.cs │ │ │ │ │ └── Net/ │ │ │ │ │ ├── IPAddressImpl.cs │ │ │ │ │ ├── NetworkInterfaceProvider.cs │ │ │ │ │ ├── SocketNativeImpl.cs │ │ │ │ │ └── SocketProvider.cs │ │ │ │ ├── FrameworkOverrides_Windows/ │ │ │ │ │ └── Devices/ │ │ │ │ │ ├── Adc/ │ │ │ │ │ │ ├── AdcControllerImpl.cs │ │ │ │ │ │ └── AdcProviderUwp.cs │ │ │ │ │ ├── I2c/ │ │ │ │ │ │ ├── I2cDeviceImplUwp.cs │ │ │ │ │ │ └── I2cProviderUwp.cs │ │ │ │ │ ├── Pwm/ │ │ │ │ │ │ ├── PwmControllerImpl.cs │ │ │ │ │ │ └── PwmProviderUwp.cs │ │ │ │ │ └── Spi/ │ │ │ │ │ ├── SpiDeviceImplUwp.cs │ │ │ │ │ └── SpiProviderUwp.cs │ │ │ │ ├── GarbageCollectors/ │ │ │ │ │ ├── ConservativeMarkAndSweepCollector.cs │ │ │ │ │ ├── MarkAndSweepCollector.cs │ │ │ │ │ ├── PreciseMarkAndSweepCollector.cs │ │ │ │ │ └── ReferenceCountingCollector.cs │ │ │ │ ├── HardwareModel/ │ │ │ │ │ ├── Device.cs │ │ │ │ │ ├── HardwareProvider.cs │ │ │ │ │ ├── Memory.cs │ │ │ │ │ ├── Peripherals.cs │ │ │ │ │ ├── Processor.cs │ │ │ │ │ ├── Storage.cs │ │ │ │ │ └── TargetPlatform/ │ │ │ │ │ ├── ARMv4/ │ │ │ │ │ │ ├── Coprocessor14.cs │ │ │ │ │ │ ├── Coprocessor15.cs │ │ │ │ │ │ ├── InterruptsSafeHandleARMv4.cs │ │ │ │ │ │ ├── MMUv4.cs │ │ │ │ │ │ ├── ProcessorARMv4.cs │ │ │ │ │ │ └── ProcessorARMv4_ContextSwitch.cs │ │ │ │ │ ├── ARMv5/ │ │ │ │ │ │ ├── ProcessorARMv5.cs │ │ │ │ │ │ └── ProcessorARMv5_ContextSwitch.cs │ │ │ │ │ ├── ARMv5_VFP/ │ │ │ │ │ │ ├── BinaryOperations.cs │ │ │ │ │ │ ├── Convert.cs │ │ │ │ │ │ ├── ProcessorARMv5_VFP.cs │ │ │ │ │ │ └── ProcessorARMv5_VFP_ContextSwitch.cs │ │ │ │ │ ├── ARMv6/ │ │ │ │ │ │ ├── InterruptsSafeHandleARMv6M.cs │ │ │ │ │ │ ├── ProcessorARMv6M.cs │ │ │ │ │ │ ├── ProcessorARMv6MForLlvm.cs │ │ │ │ │ │ └── ProcessorARMv6MForLlvm_ContextSwitch.cs │ │ │ │ │ ├── ARMv7/ │ │ │ │ │ │ ├── InterruptsSafeHandleARMv7M.cs │ │ │ │ │ │ ├── ProcessorARMv7M.cs │ │ │ │ │ │ ├── ProcessorARMv7MForLlvm.cs │ │ │ │ │ │ └── ProcessorARMv7MForLlvm_ContextSwitch.cs │ │ │ │ │ ├── ARMv7_VFP/ │ │ │ │ │ │ ├── ProcessorARMv7MForLlvm_VFP.cs │ │ │ │ │ │ ├── ProcessorARMv7MForLlvm_VFP_ContextSwitch.cs │ │ │ │ │ │ └── ProcessorARMv7M_VFP.cs │ │ │ │ │ └── AbstractMethodWrapper.cs │ │ │ │ ├── Helpers/ │ │ │ │ │ ├── BinaryOperations.cs │ │ │ │ │ ├── CompareAndSet.cs │ │ │ │ │ ├── Convert.cs │ │ │ │ │ ├── DoubleImplementation.cs │ │ │ │ │ ├── FloatImplementation.cs │ │ │ │ │ └── UnaryOperations.cs │ │ │ │ ├── Kernel.csproj │ │ │ │ ├── ManagedHeap/ │ │ │ │ │ ├── BrickTable.cs │ │ │ │ │ ├── Finalizer.cs │ │ │ │ │ ├── GarbageCollectionExtensionHandler.cs │ │ │ │ │ ├── MemoryFreeBlock.cs │ │ │ │ │ ├── MemorySegment.cs │ │ │ │ │ ├── ObjectHeader.cs │ │ │ │ │ ├── ReleaseReferenceHelper.cs │ │ │ │ │ ├── SyncBlock.cs │ │ │ │ │ └── SyncBlockTable.cs │ │ │ │ ├── MemoryManagers/ │ │ │ │ │ └── LinearMemoryManager.cs │ │ │ │ ├── Properties/ │ │ │ │ │ └── AssemblyInfo.cs │ │ │ │ ├── SelfTest.cs │ │ │ │ ├── SmartHandles/ │ │ │ │ │ ├── CriticalSectionHolder.cs │ │ │ │ │ ├── InterruptState.cs │ │ │ │ │ ├── SwapCurrentThread.cs │ │ │ │ │ ├── SwapCurrentThreadUnderInterrupt.cs │ │ │ │ │ └── YieldLockHolder.cs │ │ │ │ ├── Support/ │ │ │ │ │ ├── BugCheck.cs │ │ │ │ │ ├── KernelCircularBuffer.cs │ │ │ │ │ ├── KernelList.cs │ │ │ │ │ ├── KernelNode.cs │ │ │ │ │ ├── KernelPerformanceCounter.cs │ │ │ │ │ └── LandingPadResult.cs │ │ │ │ ├── Synchronization/ │ │ │ │ │ ├── CriticalSection.cs │ │ │ │ │ ├── WaitableObject.cs │ │ │ │ │ ├── WaitingRecord.cs │ │ │ │ │ └── YieldLock.cs │ │ │ │ ├── SystemServices/ │ │ │ │ │ ├── Configuration.cs │ │ │ │ │ ├── GarbageCollectionManager.cs │ │ │ │ │ ├── MemoryManager.cs │ │ │ │ │ ├── SchedulerTime.cs │ │ │ │ │ ├── SchedulerTimeSpan.cs │ │ │ │ │ ├── SerialPortsManager.cs │ │ │ │ │ ├── Threading/ │ │ │ │ │ │ ├── ARMv5ThreadManager.cs │ │ │ │ │ │ ├── ARMv6ThreadManager.cs │ │ │ │ │ │ ├── ARMv7ThreadManager.cs │ │ │ │ │ │ └── ThreadManager.cs │ │ │ │ │ ├── TypeSystemManager.cs │ │ │ │ │ └── Unwind.cs │ │ │ │ └── TypeSystemManagers/ │ │ │ │ └── DefaultTypeSystemManager.cs │ │ │ ├── LlilumCMSIS-RTOS/ │ │ │ │ ├── API/ │ │ │ │ │ ├── CmsisObject.cs │ │ │ │ │ ├── CmsisRtos.cs │ │ │ │ │ ├── CmsisRtosMessageQueue.cs │ │ │ │ │ ├── CmsisRtosMutex.cs │ │ │ │ │ ├── CmsisRtosSemaphore.cs │ │ │ │ │ └── CmsisRtosThread.cs │ │ │ │ ├── LlilumCMSIS-RTOS.csproj │ │ │ │ ├── Properties/ │ │ │ │ │ └── AssemblyInfo.cs │ │ │ │ └── ReadMe.txt │ │ │ ├── LlilumOSAbstraction/ │ │ │ │ ├── API/ │ │ │ │ │ ├── IO/ │ │ │ │ │ │ ├── Adc.cs │ │ │ │ │ │ ├── Ethernet.cs │ │ │ │ │ │ ├── Gpio.cs │ │ │ │ │ │ ├── I2C.cs │ │ │ │ │ │ ├── Pwm.cs │ │ │ │ │ │ ├── SerialPort.cs │ │ │ │ │ │ ├── Socket.cs │ │ │ │ │ │ └── Spi.cs │ │ │ │ │ └── RuntimeMemory.cs │ │ │ │ ├── HAL/ │ │ │ │ │ ├── Clock.cs │ │ │ │ │ ├── Mutex.cs │ │ │ │ │ ├── Thread.cs │ │ │ │ │ └── Timer.cs │ │ │ │ ├── LlilumErrors.cs │ │ │ │ ├── LlilumOSAbstraction.csproj │ │ │ │ └── Native/ │ │ │ │ └── API/ │ │ │ │ └── RuntimeMemory.cs │ │ │ └── TypeSystem/ │ │ │ ├── AssemblyRepresentation.cs │ │ │ ├── BaseRepresentation.cs │ │ │ ├── CodeMap.cs │ │ │ ├── CodeMapDecoderCallback.cs │ │ │ ├── CodePointer.cs │ │ │ ├── ConversionContext.cs │ │ │ ├── CustomAttributeAssociationRepresentation.cs │ │ │ ├── CustomAttributeRepresentation.cs │ │ │ ├── Environment/ │ │ │ │ ├── IConfigurationProvider.cs │ │ │ │ └── IEnvironmentProvider.cs │ │ │ ├── EquivalenceSet.cs │ │ │ ├── ExceptionMap.cs │ │ │ ├── Fields/ │ │ │ │ ├── FieldRepresentation.cs │ │ │ │ ├── InstanceFieldRepresentation.cs │ │ │ │ └── StaticFieldRepresentation.cs │ │ │ ├── GCInfo.cs │ │ │ ├── GenericInstantiationClosure.cs │ │ │ ├── GenericParameterDefinition.cs │ │ │ ├── GlobalRoot.cs │ │ │ ├── InstantiationContext.cs │ │ │ ├── Methods/ │ │ │ │ ├── ConstructorMethodRepresentation.cs │ │ │ │ ├── FinalMethodRepresentation.cs │ │ │ │ ├── FinalizerMethodRepresentation.cs │ │ │ │ ├── InstanceMethodRepresentation.cs │ │ │ │ ├── MethodImplRepresentation.cs │ │ │ │ ├── MethodRepresentation.cs │ │ │ │ ├── NotVirtualMethodRepresentation.cs │ │ │ │ ├── RuntimeMethodRepresentation.cs │ │ │ │ ├── StaticConstructorMethodRepresentation.cs │ │ │ │ ├── StaticMethodRepresentation.cs │ │ │ │ └── VirtualMethodRepresentation.cs │ │ │ ├── Properties/ │ │ │ │ └── AssemblyInfo.cs │ │ │ ├── ResourceRepresentation.cs │ │ │ ├── StackEquivalentType.cs │ │ │ ├── TransformationContext.cs │ │ │ ├── TypeSystem.cs │ │ │ ├── TypeSystem.csproj │ │ │ ├── Types/ │ │ │ │ ├── AbstractReferenceTypeRepresentation.cs │ │ │ │ ├── ArrayReferenceTypeRepresentation.cs │ │ │ │ ├── BoxedValueTypeRepresentation.cs │ │ │ │ ├── ConcreteReferenceTypeRepresentation.cs │ │ │ │ ├── DelayedMethodParameterTypeRepresentation.cs │ │ │ │ ├── DelayedTypeParameterTypeRepresentation.cs │ │ │ │ ├── EnumerationTypeRepresentation.cs │ │ │ │ ├── InterfaceTypeRepresentation.cs │ │ │ │ ├── ManagedPointerTypeRepresentation.cs │ │ │ │ ├── MultiArrayReferenceTypeRepresentation.cs │ │ │ │ ├── PinnedPointerTypeRepresentation.cs │ │ │ │ ├── PointerTypeRepresentation.cs │ │ │ │ ├── ReferenceTypeRepresentation.cs │ │ │ │ ├── ScalarTypeRepresentation.cs │ │ │ │ ├── SzArrayReferenceTypeRepresentation.cs │ │ │ │ ├── TypeRepresentation.cs │ │ │ │ ├── UnmanagedPointerTypeRepresentation.cs │ │ │ │ └── ValueTypeRepresentation.cs │ │ │ ├── VTable.cs │ │ │ ├── WellKnownFields.cs │ │ │ ├── WellKnownMethods.cs │ │ │ └── WellKnownTypes.cs │ │ ├── Test/ │ │ │ ├── Common/ │ │ │ │ ├── Assert.cs │ │ │ │ ├── Console.cs │ │ │ │ ├── Properties/ │ │ │ │ │ └── AssemblyInfo.cs │ │ │ │ ├── SpotTestLog.cs │ │ │ │ ├── TestAttributes.cs │ │ │ │ ├── TestBase.cs │ │ │ │ ├── TestInterface.cs │ │ │ │ ├── TestResult.cs │ │ │ │ ├── Test_Common.csproj │ │ │ │ └── Utilities.cs │ │ │ ├── CompileTime/ │ │ │ │ ├── CompilerTests/ │ │ │ │ │ ├── CompilerTests.csproj │ │ │ │ │ ├── Properties/ │ │ │ │ │ │ └── AssemblyInfo.cs │ │ │ │ │ └── SimpleTests.cs │ │ │ │ └── GenericInstantiationClosure/ │ │ │ │ ├── Fail_Field/ │ │ │ │ │ └── test.cs │ │ │ │ ├── Fail_GenericMethod1/ │ │ │ │ │ └── test.cs │ │ │ │ ├── Fail_GenericMethod2/ │ │ │ │ │ └── test.cs │ │ │ │ ├── Fail_Inheritance/ │ │ │ │ │ └── test.cs │ │ │ │ ├── Fail_Method/ │ │ │ │ │ └── test.cs │ │ │ │ ├── Pass/ │ │ │ │ │ └── test.cs │ │ │ │ └── rebuildDir.cmd │ │ │ ├── Desktop/ │ │ │ │ └── Net/ │ │ │ │ ├── HttpTest/ │ │ │ │ │ ├── App.config │ │ │ │ │ ├── HttpTest.csproj │ │ │ │ │ ├── Program.cs │ │ │ │ │ └── Properties/ │ │ │ │ │ └── AssemblyInfo.cs │ │ │ │ └── NetworkTest/ │ │ │ │ ├── App.config │ │ │ │ ├── NetworkTest.csproj │ │ │ │ ├── Program.cs │ │ │ │ └── Properties/ │ │ │ │ └── AssemblyInfo.cs │ │ │ ├── HardwareTests/ │ │ │ │ ├── Gpio/ │ │ │ │ │ ├── GpioTest.csproj │ │ │ │ │ ├── Program.cs │ │ │ │ │ └── ReadMe.txt │ │ │ │ └── SerialPort/ │ │ │ │ ├── Program.cs │ │ │ │ ├── ReadMe.txt │ │ │ │ └── SerialPortTest.csproj │ │ │ ├── LlilumTests.sln │ │ │ ├── LlilumWin32/ │ │ │ │ ├── LlilumWin32.cpp │ │ │ │ ├── LlilumWin32.vcxproj │ │ │ │ ├── LlilumWin32.vcxproj.filters │ │ │ │ ├── ReadMe.txt │ │ │ │ ├── stdafx.cpp │ │ │ │ ├── stdafx.h │ │ │ │ └── targetver.h │ │ │ ├── LlilumWin32.sln │ │ │ ├── RunTime/ │ │ │ │ ├── NETMF/ │ │ │ │ │ ├── System/ │ │ │ │ │ │ ├── Http/ │ │ │ │ │ │ │ ├── AuthenticationTests.cs │ │ │ │ │ │ │ ├── Base64Tests.cs │ │ │ │ │ │ │ ├── FunctionalTests.cs │ │ │ │ │ │ │ ├── HttpKnownHeaderNamesTests.cs │ │ │ │ │ │ │ ├── HttpRequestHeaderTests.cs │ │ │ │ │ │ │ ├── HttpResponseHeaderTests.cs │ │ │ │ │ │ │ ├── HttpServer.cs │ │ │ │ │ │ │ ├── HttpStatusCodeTests.cs │ │ │ │ │ │ │ ├── HttpVersionTests.cs │ │ │ │ │ │ │ ├── HttpWebRequestTests.cs │ │ │ │ │ │ │ ├── HttpWebResponseTests.cs │ │ │ │ │ │ │ ├── Master.cs │ │ │ │ │ │ │ ├── ProtocolViolationExceptionTests.cs │ │ │ │ │ │ │ ├── TestServer.cs │ │ │ │ │ │ │ ├── UriTests.cs │ │ │ │ │ │ │ ├── WebExceptionTests.cs │ │ │ │ │ │ │ ├── WebHeaderCollectionTests.cs │ │ │ │ │ │ │ ├── WebProxyTests.cs │ │ │ │ │ │ │ ├── WebRequestTests.cs │ │ │ │ │ │ │ └── WebResponseTests.cs │ │ │ │ │ │ ├── IO/ │ │ │ │ │ │ │ └── MemoryStream/ │ │ │ │ │ │ │ ├── CanRead.cs │ │ │ │ │ │ │ ├── CanSeek.cs │ │ │ │ │ │ │ ├── CanWrite.cs │ │ │ │ │ │ │ ├── Close.cs │ │ │ │ │ │ │ ├── Flush.cs │ │ │ │ │ │ │ ├── Length.cs │ │ │ │ │ │ │ ├── MemoryStreamHelper.cs │ │ │ │ │ │ │ ├── MemoryStream_Ctor.cs │ │ │ │ │ │ │ ├── Position.cs │ │ │ │ │ │ │ ├── Read.cs │ │ │ │ │ │ │ ├── ReadByte.cs │ │ │ │ │ │ │ ├── Seek.cs │ │ │ │ │ │ │ ├── SetLength.cs │ │ │ │ │ │ │ ├── ToArray.cs │ │ │ │ │ │ │ ├── Write.cs │ │ │ │ │ │ │ ├── WriteByte.cs │ │ │ │ │ │ │ └── WriteTo.cs │ │ │ │ │ │ ├── Test_System.csproj │ │ │ │ │ │ ├── Text/ │ │ │ │ │ │ │ └── StringBuilder/ │ │ │ │ │ │ │ └── StringBuilderTests.cs │ │ │ │ │ │ ├── netTests/ │ │ │ │ │ │ │ └── NetTests.cs │ │ │ │ │ │ └── socketTests/ │ │ │ │ │ │ ├── SocketExceptionTests.cs │ │ │ │ │ │ ├── SocketPair.cs │ │ │ │ │ │ ├── SocketServer.cs │ │ │ │ │ │ ├── SocketTests.cs │ │ │ │ │ │ ├── SocketTools.cs │ │ │ │ │ │ ├── SocketsEnumsTests.cs │ │ │ │ │ │ └── StressTests.cs │ │ │ │ │ └── mscorlib/ │ │ │ │ │ ├── Properties/ │ │ │ │ │ │ └── AssemblyInfo.cs │ │ │ │ │ ├── Test_mscorlib.csproj │ │ │ │ │ ├── arrays/ │ │ │ │ │ │ ├── ArraysOtherTests.cs │ │ │ │ │ │ └── ArraysSimpleTests.cs │ │ │ │ │ ├── attributes/ │ │ │ │ │ │ ├── AttributesTests1.cs │ │ │ │ │ │ └── AttributesTests2.cs │ │ │ │ │ ├── basicconcepts/ │ │ │ │ │ │ └── BasicConceptTests.cs │ │ │ │ │ ├── bitconverter/ │ │ │ │ │ │ ├── BitConverterTests.cs │ │ │ │ │ │ ├── Helper.cs │ │ │ │ │ │ └── TestFailException.cs │ │ │ │ │ ├── classes/ │ │ │ │ │ │ ├── classes1/ │ │ │ │ │ │ │ ├── ConstTests.cs │ │ │ │ │ │ │ ├── ConstructorsTests.cs │ │ │ │ │ │ │ ├── DeclarationsTests.cs │ │ │ │ │ │ │ ├── DestructorsTests.cs │ │ │ │ │ │ │ ├── EventsTests.cs │ │ │ │ │ │ │ └── FieldsTests.cs │ │ │ │ │ │ ├── classes2/ │ │ │ │ │ │ │ ├── IndexersTests.cs │ │ │ │ │ │ │ ├── OperatorsTests.cs │ │ │ │ │ │ │ ├── PropertiesTests.cs │ │ │ │ │ │ │ └── Static_InstTests.cs │ │ │ │ │ │ └── classes3/ │ │ │ │ │ │ ├── MembersTests.cs │ │ │ │ │ │ └── MethodsTests.cs │ │ │ │ │ ├── collections/ │ │ │ │ │ │ ├── ArrayListTests.cs │ │ │ │ │ │ ├── HashtableTests.cs │ │ │ │ │ │ ├── QueueTests.cs │ │ │ │ │ │ ├── StackTests.cs │ │ │ │ │ │ └── TestObjects.cs │ │ │ │ │ ├── conversions/ │ │ │ │ │ │ ├── BoxingTests.cs │ │ │ │ │ │ ├── Convert.cs │ │ │ │ │ │ ├── ExprefTests.cs │ │ │ │ │ │ ├── ImpenumTests.cs │ │ │ │ │ │ ├── ImprefTests.cs │ │ │ │ │ │ ├── basic/ │ │ │ │ │ │ │ └── BasicTests.cs │ │ │ │ │ │ ├── basic2/ │ │ │ │ │ │ │ └── BasicTests2.cs │ │ │ │ │ │ ├── expenum/ │ │ │ │ │ │ │ ├── Expenum1Tests.cs │ │ │ │ │ │ │ └── Expenum2Tests.cs │ │ │ │ │ │ ├── expenum2/ │ │ │ │ │ │ │ └── Expenum3Tests.cs │ │ │ │ │ │ └── user/ │ │ │ │ │ │ ├── ClassClassTests.cs │ │ │ │ │ │ ├── ClassStructTests.cs │ │ │ │ │ │ ├── StructClassTests.cs │ │ │ │ │ │ ├── StructStructTests.cs │ │ │ │ │ │ └── selection/ │ │ │ │ │ │ └── BasicSelectionTests.cs │ │ │ │ │ ├── delegates/ │ │ │ │ │ │ └── DelegatesTests.cs │ │ │ │ │ ├── enums/ │ │ │ │ │ │ └── EnumTests.cs │ │ │ │ │ ├── exceptions/ │ │ │ │ │ │ └── CSharp/ │ │ │ │ │ │ └── ExceptionsTests.cs │ │ │ │ │ ├── expressions/ │ │ │ │ │ │ ├── expressions1/ │ │ │ │ │ │ │ ├── ArithmeticTests1.cs │ │ │ │ │ │ │ ├── ArithmeticTests2.cs │ │ │ │ │ │ │ └── OtherTests1.cs │ │ │ │ │ │ └── expressions2/ │ │ │ │ │ │ └── ExpressionsTests.cs │ │ │ │ │ ├── interfaces/ │ │ │ │ │ │ └── InterfaceTests.cs │ │ │ │ │ ├── lexical/ │ │ │ │ │ │ ├── LexicalTests1.cs │ │ │ │ │ │ └── LexicalTests2.cs │ │ │ │ │ ├── namespaces/ │ │ │ │ │ │ ├── NS_attribute_01.cs │ │ │ │ │ │ ├── NS_attribute_02.cs │ │ │ │ │ │ ├── NS_compunit_01A.cs │ │ │ │ │ │ ├── NS_compunit_01B.cs │ │ │ │ │ │ ├── NS_compunit_03A.cs │ │ │ │ │ │ ├── NS_compunit_03B.cs │ │ │ │ │ │ ├── NS_compunit_04A.cs │ │ │ │ │ │ ├── NS_compunit_04B.cs │ │ │ │ │ │ ├── NS_decl_14.cs │ │ │ │ │ │ ├── NS_decl_15.cs │ │ │ │ │ │ └── NamespacesTests.cs │ │ │ │ │ ├── statements/ │ │ │ │ │ │ └── StatementsTests.cs │ │ │ │ │ ├── structs/ │ │ │ │ │ │ └── StructsTests.cs │ │ │ │ │ ├── systemlib/ │ │ │ │ │ │ ├── systemlib1/ │ │ │ │ │ │ │ ├── Guid.cs │ │ │ │ │ │ │ ├── ParseTests.cs │ │ │ │ │ │ │ ├── SystemTimeSpanTests.cs │ │ │ │ │ │ │ └── SystemTimeZoneTests.cs │ │ │ │ │ │ └── systemlib2/ │ │ │ │ │ │ ├── InitLocalsTests.cs │ │ │ │ │ │ ├── MicrosoftSpotReflection.cs │ │ │ │ │ │ ├── SystemAppDomainTests.cs │ │ │ │ │ │ ├── SystemDateTimeTests.cs │ │ │ │ │ │ ├── SystemGCTests.cs │ │ │ │ │ │ ├── SystemMathTests.cs │ │ │ │ │ │ ├── SystemReflectionAssembly.cs │ │ │ │ │ │ ├── SystemReflectionMemberTests.cs │ │ │ │ │ │ ├── SystemReflectionTypeTests.cs │ │ │ │ │ │ ├── SystemStringTests.cs │ │ │ │ │ │ ├── SystemTypeTests.cs │ │ │ │ │ │ ├── SystemWeakReferenceTests.cs │ │ │ │ │ │ └── Utf8EncodingTests.cs │ │ │ │ │ ├── threads/ │ │ │ │ │ │ ├── threads1/ │ │ │ │ │ │ │ └── ThreadTests.cs │ │ │ │ │ │ ├── threads2/ │ │ │ │ │ │ │ ├── AutoResetEventTests.cs │ │ │ │ │ │ │ ├── InterlockedTests.cs │ │ │ │ │ │ │ ├── MonitorTests.cs │ │ │ │ │ │ │ ├── TimeoutTests.cs │ │ │ │ │ │ │ └── WaitHandleTests.cs │ │ │ │ │ │ └── threads3/ │ │ │ │ │ │ └── TimerTests.cs │ │ │ │ │ ├── types/ │ │ │ │ │ │ ├── ReferenceBoxingTests.cs │ │ │ │ │ │ ├── ValueArrayTests.cs │ │ │ │ │ │ ├── ValueDefault_ConstTests.cs │ │ │ │ │ │ ├── ValueFloatTests.cs │ │ │ │ │ │ ├── ValueIntegralTests.cs │ │ │ │ │ │ ├── ValueSimpleTests.cs │ │ │ │ │ │ └── ValueTests.cs │ │ │ │ │ └── variables/ │ │ │ │ │ ├── CategoriesTests.cs │ │ │ │ │ └── VariablesTests.cs │ │ │ │ └── mscorlib_UnitTest/ │ │ │ │ ├── Files.Designer.cs │ │ │ │ ├── Files.resx │ │ │ │ ├── Program.cs │ │ │ │ ├── Properties/ │ │ │ │ │ └── AssemblyInfo.cs │ │ │ │ ├── Resources/ │ │ │ │ │ └── ZeligRefreshBinaryDrop.cmd │ │ │ │ ├── Test_OpenClasses.cs │ │ │ │ ├── Verify.cs │ │ │ │ ├── app.config │ │ │ │ └── mscorlib_UnitTest.csproj │ │ │ ├── Runner/ │ │ │ │ ├── Properties/ │ │ │ │ │ └── AssemblyInfo.cs │ │ │ │ ├── TestRunner.cs │ │ │ │ └── TestRunner.csproj │ │ │ └── mbed/ │ │ │ ├── NativeHelpers/ │ │ │ │ ├── NativeHelpers.vcxproj │ │ │ │ └── NativeHelpers.vcxproj.filters │ │ │ ├── SimpleHttp/ │ │ │ │ ├── Program.cs │ │ │ │ ├── Properties/ │ │ │ │ │ └── AssemblyInfo.cs │ │ │ │ └── SimpleHttp.csproj │ │ │ ├── SimpleNet/ │ │ │ │ ├── Program.cs │ │ │ │ ├── Properties/ │ │ │ │ │ └── AssemblyInfo.cs │ │ │ │ └── SimpleNet.csproj │ │ │ ├── SimpleSDK/ │ │ │ │ ├── Managed/ │ │ │ │ │ ├── Program.cs │ │ │ │ │ ├── Properties/ │ │ │ │ │ │ └── AssemblyInfo.cs │ │ │ │ │ └── SimpleTestProgram.csproj │ │ │ │ └── Native/ │ │ │ │ ├── Native.vcxproj │ │ │ │ ├── helpers.h │ │ │ │ ├── mbed_simple_K64F.FrontEndConfig │ │ │ │ ├── mbed_simple_LPC1768.FrontEndConfig │ │ │ │ └── pch.h │ │ │ └── simple/ │ │ │ ├── LedToggler.cs │ │ │ ├── Program.cs │ │ │ ├── Program_Test__ADC.cs │ │ │ ├── Program_Test__GpioInterruptTestData.cs │ │ │ ├── Program_Test__GpioPerf.cs │ │ │ ├── Program_Test__I2C.cs │ │ │ ├── Program_Test__PWM.cs │ │ │ ├── Program_Test__SPI.cs │ │ │ ├── Program_Test__SpiLcd.cs │ │ │ ├── Program_Test__Win32.cs │ │ │ ├── Properties/ │ │ │ │ └── AssemblyInfo.cs │ │ │ ├── SpiLcdC12832.cs │ │ │ └── simple.csproj │ │ ├── Zelig.proj │ │ ├── Zelig.sln │ │ └── setenv.cmd │ ├── ZeligInterop/ │ │ └── Sample/ │ │ ├── ExternalLinking_tester/ │ │ │ ├── dotNetMF.proj │ │ │ ├── zelig_interop.cpp │ │ │ ├── zelig_interop.h │ │ │ └── zelig_interop2.cpp │ │ ├── FileSystemSampleLPC/ │ │ │ ├── BlockStorageFileSystem.cpp │ │ │ ├── BlockStorageFileSystem.h │ │ │ ├── LIB/ │ │ │ │ ├── FS_FAT.lib │ │ │ │ ├── Watchdog_pal_stubs.lib │ │ │ │ ├── blockstorage_pal.lib │ │ │ │ ├── cpu_power_stubs.lib │ │ │ │ ├── fs_pal.lib │ │ │ │ └── tinycrt_pal.lib │ │ │ ├── build.cmd │ │ │ └── dotnetmf.proj │ │ └── FileSystemTest/ │ │ ├── BlockStorageFileSystem.cpp │ │ ├── BlockStorageFileSystem.h │ │ ├── LIB/ │ │ │ ├── FS_FAT.lib │ │ │ ├── Watchdog_pal_stubs.lib │ │ │ ├── blockstorage_pal.lib │ │ │ ├── cpu_power_stubs.lib │ │ │ ├── fs_pal.lib │ │ │ └── tinycrt_pal.lib │ │ ├── build.cmd │ │ └── dotnetmf.proj │ ├── ext-tools/ │ │ └── binutils/ │ │ └── binutils.sln │ ├── lwip/ │ │ ├── lwip/ │ │ │ ├── include/ │ │ │ │ ├── ipv4/ │ │ │ │ │ └── lwip/ │ │ │ │ │ ├── autoip.h │ │ │ │ │ ├── icmp.h │ │ │ │ │ ├── igmp.h │ │ │ │ │ ├── inet.h │ │ │ │ │ ├── inet_chksum.h │ │ │ │ │ ├── ip.h │ │ │ │ │ ├── ip_addr.h │ │ │ │ │ └── ip_frag.h │ │ │ │ ├── lwip/ │ │ │ │ │ ├── api.h │ │ │ │ │ ├── api_msg.h │ │ │ │ │ ├── arch.h │ │ │ │ │ ├── debug.h │ │ │ │ │ ├── def.h │ │ │ │ │ ├── dhcp.h │ │ │ │ │ ├── dns.h │ │ │ │ │ ├── err.h │ │ │ │ │ ├── init.h │ │ │ │ │ ├── mem.h │ │ │ │ │ ├── memp.h │ │ │ │ │ ├── memp_std.h │ │ │ │ │ ├── netbuf.h │ │ │ │ │ ├── netdb.h │ │ │ │ │ ├── netif.h │ │ │ │ │ ├── netifapi.h │ │ │ │ │ ├── opt.h │ │ │ │ │ ├── pbuf.h │ │ │ │ │ ├── raw.h │ │ │ │ │ ├── sio.h │ │ │ │ │ ├── snmp.h │ │ │ │ │ ├── snmp_asn1.h │ │ │ │ │ ├── snmp_msg.h │ │ │ │ │ ├── snmp_structs.h │ │ │ │ │ ├── sockets.h │ │ │ │ │ ├── stats.h │ │ │ │ │ ├── sys.h │ │ │ │ │ ├── tcp.h │ │ │ │ │ ├── tcp_impl.h │ │ │ │ │ ├── tcpip.h │ │ │ │ │ ├── timers.h │ │ │ │ │ └── udp.h │ │ │ │ └── netif/ │ │ │ │ ├── etharp.h │ │ │ │ ├── ppp_oe.h │ │ │ │ └── slipif.h │ │ │ ├── lib/ │ │ │ │ ├── liblwIP.a │ │ │ │ ├── liblwIPc.a │ │ │ │ └── liblwIPd.a │ │ │ └── lwipopts.h │ │ ├── lwip-eth/ │ │ │ └── arch/ │ │ │ ├── TARGET_Freescale/ │ │ │ │ ├── k64f_emac_config.h │ │ │ │ └── lwipopts_conf.h │ │ │ ├── TARGET_NXP/ │ │ │ │ ├── lpc17_emac.c │ │ │ │ ├── lpc17xx_emac.h │ │ │ │ ├── lpc_emac_config.h │ │ │ │ ├── lpc_phy.h │ │ │ │ ├── lpc_phy_dp83848.c │ │ │ │ └── lwipopts_conf.h │ │ │ ├── TARGET_RZ_A1H/ │ │ │ │ ├── lwipopts_conf.h │ │ │ │ └── rza1_emac.c │ │ │ └── TARGET_STM/ │ │ │ ├── lwipopts_conf.h │ │ │ └── stm32f4_emac.c │ │ └── lwip-sys/ │ │ └── arch/ │ │ ├── cc.h │ │ ├── checksum.c │ │ ├── memcpy.c │ │ ├── perf.h │ │ ├── sys_arch.c │ │ └── sys_arch.h │ ├── mbed/ │ │ ├── AnalogIn.h │ │ ├── AnalogOut.h │ │ ├── BusIn.h │ │ ├── BusInOut.h │ │ ├── BusOut.h │ │ ├── CAN.h │ │ ├── CThunk.h │ │ ├── CallChain.h │ │ ├── CircularBuffer.h │ │ ├── DigitalIn.h │ │ ├── DigitalInOut.h │ │ ├── DigitalOut.h │ │ ├── DirHandle.h │ │ ├── Ethernet.h │ │ ├── EthernetInterface/ │ │ │ ├── EthernetInterface.cpp │ │ │ ├── EthernetInterface.h │ │ │ ├── README.txt │ │ │ └── eth_arch.h │ │ ├── FileBase.h │ │ ├── FileHandle.h │ │ ├── FileLike.h │ │ ├── FilePath.h │ │ ├── FileSystemLike.h │ │ ├── FunctionPointer.h │ │ ├── I2C.h │ │ ├── I2CSlave.h │ │ ├── InterruptIn.h │ │ ├── InterruptManager.h │ │ ├── LocalFileSystem.h │ │ ├── LowPowerTicker.h │ │ ├── LowPowerTimeout.h │ │ ├── LowPowerTimer.h │ │ ├── PortIn.h │ │ ├── PortInOut.h │ │ ├── PortOut.h │ │ ├── PwmOut.h │ │ ├── RawSerial.h │ │ ├── SPI.h │ │ ├── SPISlave.h │ │ ├── Serial.h │ │ ├── SerialBase.h │ │ ├── Stream.h │ │ ├── TARGET_K64F/ │ │ │ ├── MK64F12.h │ │ │ ├── TARGET_Freescale/ │ │ │ │ └── TARGET_KPSDK_MCUS/ │ │ │ │ ├── PeripheralPins.h │ │ │ │ ├── PortNames.h │ │ │ │ ├── TARGET_KPSDK_CODE/ │ │ │ │ │ ├── common/ │ │ │ │ │ │ └── phyksz8081/ │ │ │ │ │ │ └── fsl_phy_driver.h │ │ │ │ │ ├── drivers/ │ │ │ │ │ │ ├── clock/ │ │ │ │ │ │ │ └── fsl_clock_manager.h │ │ │ │ │ │ ├── enet/ │ │ │ │ │ │ │ ├── fsl_enet_driver.h │ │ │ │ │ │ │ └── fsl_enet_rtcs_adapter.h │ │ │ │ │ │ ├── interrupt/ │ │ │ │ │ │ │ ├── fsl_interrupt_features.h │ │ │ │ │ │ │ └── fsl_interrupt_manager.h │ │ │ │ │ │ └── pit/ │ │ │ │ │ │ ├── common/ │ │ │ │ │ │ │ └── fsl_pit_common.h │ │ │ │ │ │ └── fsl_pit_driver.h │ │ │ │ │ ├── hal/ │ │ │ │ │ │ ├── adc/ │ │ │ │ │ │ │ ├── fsl_adc_features.h │ │ │ │ │ │ │ └── fsl_adc_hal.h │ │ │ │ │ │ ├── can/ │ │ │ │ │ │ │ ├── fsl_flexcan_features.h │ │ │ │ │ │ │ └── fsl_flexcan_hal.h │ │ │ │ │ │ ├── dac/ │ │ │ │ │ │ │ ├── fsl_dac_features.h │ │ │ │ │ │ │ └── fsl_dac_hal.h │ │ │ │ │ │ ├── dmamux/ │ │ │ │ │ │ │ ├── fsl_dmamux_features.h │ │ │ │ │ │ │ └── fsl_dmamux_hal.h │ │ │ │ │ │ ├── dspi/ │ │ │ │ │ │ │ ├── fsl_dspi_features.h │ │ │ │ │ │ │ └── fsl_dspi_hal.h │ │ │ │ │ │ ├── edma/ │ │ │ │ │ │ │ ├── fsl_edma_features.h │ │ │ │ │ │ │ └── fsl_edma_hal.h │ │ │ │ │ │ ├── enet/ │ │ │ │ │ │ │ ├── fsl_enet_features.h │ │ │ │ │ │ │ └── fsl_enet_hal.h │ │ │ │ │ │ ├── flextimer/ │ │ │ │ │ │ │ ├── fsl_ftm_features.h │ │ │ │ │ │ │ └── fsl_ftm_hal.h │ │ │ │ │ │ ├── gpio/ │ │ │ │ │ │ │ ├── fsl_gpio_features.h │ │ │ │ │ │ │ └── fsl_gpio_hal.h │ │ │ │ │ │ ├── i2c/ │ │ │ │ │ │ │ ├── fsl_i2c_features.h │ │ │ │ │ │ │ └── fsl_i2c_hal.h │ │ │ │ │ │ ├── llwu/ │ │ │ │ │ │ │ ├── fsl_llwu_features.h │ │ │ │ │ │ │ └── fsl_llwu_hal.h │ │ │ │ │ │ ├── lptmr/ │ │ │ │ │ │ │ ├── fsl_lptmr_features.h │ │ │ │ │ │ │ └── fsl_lptmr_hal.h │ │ │ │ │ │ ├── lpuart/ │ │ │ │ │ │ │ ├── fsl_lpuart_features.h │ │ │ │ │ │ │ └── fsl_lpuart_hal.h │ │ │ │ │ │ ├── mcg/ │ │ │ │ │ │ │ ├── fsl_mcg_features.h │ │ │ │ │ │ │ ├── fsl_mcg_hal.h │ │ │ │ │ │ │ └── fsl_mcg_hal_modes.h │ │ │ │ │ │ ├── mpu/ │ │ │ │ │ │ │ ├── fsl_mpu_features.h │ │ │ │ │ │ │ └── fsl_mpu_hal.h │ │ │ │ │ │ ├── osc/ │ │ │ │ │ │ │ ├── fsl_osc_features.h │ │ │ │ │ │ │ └── fsl_osc_hal.h │ │ │ │ │ │ ├── pdb/ │ │ │ │ │ │ │ ├── fsl_pdb_features.h │ │ │ │ │ │ │ └── fsl_pdb_hal.h │ │ │ │ │ │ ├── pit/ │ │ │ │ │ │ │ ├── fsl_pit_features.h │ │ │ │ │ │ │ └── fsl_pit_hal.h │ │ │ │ │ │ ├── pmc/ │ │ │ │ │ │ │ ├── fsl_pmc_features.h │ │ │ │ │ │ │ └── fsl_pmc_hal.h │ │ │ │ │ │ ├── port/ │ │ │ │ │ │ │ ├── fsl_port_features.h │ │ │ │ │ │ │ └── fsl_port_hal.h │ │ │ │ │ │ ├── rcm/ │ │ │ │ │ │ │ ├── fsl_rcm_features.h │ │ │ │ │ │ │ └── fsl_rcm_hal.h │ │ │ │ │ │ ├── rtc/ │ │ │ │ │ │ │ ├── fsl_rtc_features.h │ │ │ │ │ │ │ └── fsl_rtc_hal.h │ │ │ │ │ │ ├── sai/ │ │ │ │ │ │ │ ├── fsl_sai_features.h │ │ │ │ │ │ │ └── fsl_sai_hal.h │ │ │ │ │ │ ├── sdhc/ │ │ │ │ │ │ │ ├── fsl_sdhc_features.h │ │ │ │ │ │ │ └── fsl_sdhc_hal.h │ │ │ │ │ │ ├── sim/ │ │ │ │ │ │ │ ├── fsl_sim_features.h │ │ │ │ │ │ │ └── fsl_sim_hal.h │ │ │ │ │ │ ├── smc/ │ │ │ │ │ │ │ ├── fsl_smc_features.h │ │ │ │ │ │ │ └── fsl_smc_hal.h │ │ │ │ │ │ ├── uart/ │ │ │ │ │ │ │ ├── fsl_uart_features.h │ │ │ │ │ │ │ └── fsl_uart_hal.h │ │ │ │ │ │ └── wdog/ │ │ │ │ │ │ ├── fsl_wdog_features.h │ │ │ │ │ │ └── fsl_wdog_hal.h │ │ │ │ │ └── utilities/ │ │ │ │ │ ├── fsl_misc_utilities.h │ │ │ │ │ ├── fsl_os_abstraction.h │ │ │ │ │ ├── fsl_os_abstraction_mbed.h │ │ │ │ │ └── sw_timer.h │ │ │ │ ├── TARGET_MCU_K64F/ │ │ │ │ │ ├── MK64F12/ │ │ │ │ │ │ ├── fsl_clock_K64F12.h │ │ │ │ │ │ └── fsl_sim_hal_K64F12.h │ │ │ │ │ ├── TARGET_FRDM/ │ │ │ │ │ │ ├── PeripheralNames.h │ │ │ │ │ │ ├── PinNames.h │ │ │ │ │ │ ├── crc.h │ │ │ │ │ │ └── device.h │ │ │ │ │ └── device/ │ │ │ │ │ ├── MK64F12/ │ │ │ │ │ │ └── fsl_bitaccess.h │ │ │ │ │ └── device/ │ │ │ │ │ ├── MK64F12/ │ │ │ │ │ │ ├── MK64F12.h │ │ │ │ │ │ ├── MK64F12_adc.h │ │ │ │ │ │ ├── MK64F12_aips.h │ │ │ │ │ │ ├── MK64F12_axbs.h │ │ │ │ │ │ ├── MK64F12_can.h │ │ │ │ │ │ ├── MK64F12_cau.h │ │ │ │ │ │ ├── MK64F12_cmp.h │ │ │ │ │ │ ├── MK64F12_cmt.h │ │ │ │ │ │ ├── MK64F12_crc.h │ │ │ │ │ │ ├── MK64F12_dac.h │ │ │ │ │ │ ├── MK64F12_dma.h │ │ │ │ │ │ ├── MK64F12_dmamux.h │ │ │ │ │ │ ├── MK64F12_enet.h │ │ │ │ │ │ ├── MK64F12_ewm.h │ │ │ │ │ │ ├── MK64F12_fb.h │ │ │ │ │ │ ├── MK64F12_fmc.h │ │ │ │ │ │ ├── MK64F12_ftfe.h │ │ │ │ │ │ ├── MK64F12_ftm.h │ │ │ │ │ │ ├── MK64F12_gpio.h │ │ │ │ │ │ ├── MK64F12_i2c.h │ │ │ │ │ │ ├── MK64F12_i2s.h │ │ │ │ │ │ ├── MK64F12_llwu.h │ │ │ │ │ │ ├── MK64F12_lptmr.h │ │ │ │ │ │ ├── MK64F12_mcg.h │ │ │ │ │ │ ├── MK64F12_mcm.h │ │ │ │ │ │ ├── MK64F12_mpu.h │ │ │ │ │ │ ├── MK64F12_nv.h │ │ │ │ │ │ ├── MK64F12_osc.h │ │ │ │ │ │ ├── MK64F12_pdb.h │ │ │ │ │ │ ├── MK64F12_pit.h │ │ │ │ │ │ ├── MK64F12_pmc.h │ │ │ │ │ │ ├── MK64F12_port.h │ │ │ │ │ │ ├── MK64F12_rcm.h │ │ │ │ │ │ ├── MK64F12_rfsys.h │ │ │ │ │ │ ├── MK64F12_rfvbat.h │ │ │ │ │ │ ├── MK64F12_rng.h │ │ │ │ │ │ ├── MK64F12_rtc.h │ │ │ │ │ │ ├── MK64F12_sdhc.h │ │ │ │ │ │ ├── MK64F12_sim.h │ │ │ │ │ │ ├── MK64F12_smc.h │ │ │ │ │ │ ├── MK64F12_spi.h │ │ │ │ │ │ ├── MK64F12_uart.h │ │ │ │ │ │ ├── MK64F12_usb.h │ │ │ │ │ │ ├── MK64F12_usbdcd.h │ │ │ │ │ │ ├── MK64F12_vref.h │ │ │ │ │ │ └── MK64F12_wdog.h │ │ │ │ │ └── fsl_device_registers.h │ │ │ │ ├── gpio_object.h │ │ │ │ └── objects.h │ │ │ ├── TOOLCHAIN_GCC_ARM/ │ │ │ │ ├── K64FN1M0xxx12.ld │ │ │ │ ├── board.o │ │ │ │ ├── cmsis_nvic.o │ │ │ │ ├── liblwIPeth.a │ │ │ │ ├── liblwipsysarch.a │ │ │ │ ├── libmbed.a │ │ │ │ ├── libmbedeth.a │ │ │ │ ├── mbed_overrides.o │ │ │ │ ├── retarget.o │ │ │ │ ├── startup_MK64F12.o │ │ │ │ └── system_MK64F12.o │ │ │ ├── cmsis.h │ │ │ ├── cmsis_nvic.h │ │ │ ├── core_ca9.h │ │ │ ├── core_caFunc.h │ │ │ ├── core_caInstr.h │ │ │ ├── core_ca_mmu.h │ │ │ ├── core_cm0.h │ │ │ ├── core_cm0plus.h │ │ │ ├── core_cm3.h │ │ │ ├── core_cm4.h │ │ │ ├── core_cm4_simd.h │ │ │ ├── core_cm7.h │ │ │ ├── core_cmFunc.h │ │ │ ├── core_cmInstr.h │ │ │ ├── core_cmSimd.h │ │ │ └── system_MK64F12.h │ │ ├── TARGET_LPC1768/ │ │ │ ├── LPC17xx.h │ │ │ ├── TARGET_NXP/ │ │ │ │ └── TARGET_LPC176X/ │ │ │ │ ├── PeripheralNames.h │ │ │ │ ├── PortNames.h │ │ │ │ ├── TARGET_MBED_LPC1768/ │ │ │ │ │ ├── PinNames.h │ │ │ │ │ ├── device.h │ │ │ │ │ └── reserved_pins.h │ │ │ │ ├── gpio_object.h │ │ │ │ └── objects.h │ │ │ ├── TOOLCHAIN_GCC_ARM/ │ │ │ │ ├── LPC1768.ld │ │ │ │ ├── board.o │ │ │ │ ├── cmsis_nvic.o │ │ │ │ ├── libmbed.a │ │ │ │ ├── libmbedeth.a │ │ │ │ ├── retarget.o │ │ │ │ ├── startup_LPC17xx.o │ │ │ │ └── system_LPC17xx.o │ │ │ ├── cmsis.h │ │ │ ├── cmsis_nvic.h │ │ │ ├── core_ca9.h │ │ │ ├── core_caFunc.h │ │ │ ├── core_caInstr.h │ │ │ ├── core_ca_mmu.h │ │ │ ├── core_cm0.h │ │ │ ├── core_cm0plus.h │ │ │ ├── core_cm3.h │ │ │ ├── core_cm4.h │ │ │ ├── core_cm4_simd.h │ │ │ ├── core_cm7.h │ │ │ ├── core_cmFunc.h │ │ │ ├── core_cmInstr.h │ │ │ ├── core_cmSimd.h │ │ │ └── system_LPC17xx.h │ │ ├── TARGET_NUCLEO_F091RC/ │ │ │ ├── TARGET_STM/ │ │ │ │ └── TARGET_STM32F0/ │ │ │ │ ├── PeripheralPins.h │ │ │ │ ├── TARGET_NUCLEO_F091RC/ │ │ │ │ │ ├── PeripheralNames.h │ │ │ │ │ ├── PinNames.h │ │ │ │ │ ├── PortNames.h │ │ │ │ │ ├── device.h │ │ │ │ │ └── objects.h │ │ │ │ └── gpio_object.h │ │ │ ├── TOOLCHAIN_GCC_ARM/ │ │ │ │ ├── STM32F091XC.ld │ │ │ │ ├── board.o │ │ │ │ ├── cmsis_nvic.o │ │ │ │ ├── hal_tick.o │ │ │ │ ├── libmbed.a │ │ │ │ ├── mbed_overrides.o │ │ │ │ ├── retarget.o │ │ │ │ ├── startup_stm32f091xc.o │ │ │ │ ├── stm32f0xx_hal.o │ │ │ │ ├── stm32f0xx_hal_adc.o │ │ │ │ ├── stm32f0xx_hal_adc_ex.o │ │ │ │ ├── stm32f0xx_hal_can.o │ │ │ │ ├── stm32f0xx_hal_cec.o │ │ │ │ ├── stm32f0xx_hal_comp.o │ │ │ │ ├── stm32f0xx_hal_cortex.o │ │ │ │ ├── stm32f0xx_hal_crc.o │ │ │ │ ├── stm32f0xx_hal_crc_ex.o │ │ │ │ ├── stm32f0xx_hal_dac.o │ │ │ │ ├── stm32f0xx_hal_dac_ex.o │ │ │ │ ├── stm32f0xx_hal_dma.o │ │ │ │ ├── stm32f0xx_hal_flash.o │ │ │ │ ├── stm32f0xx_hal_flash_ex.o │ │ │ │ ├── stm32f0xx_hal_gpio.o │ │ │ │ ├── stm32f0xx_hal_i2c.o │ │ │ │ ├── stm32f0xx_hal_i2c_ex.o │ │ │ │ ├── stm32f0xx_hal_i2s.o │ │ │ │ ├── stm32f0xx_hal_irda.o │ │ │ │ ├── stm32f0xx_hal_iwdg.o │ │ │ │ ├── stm32f0xx_hal_pcd.o │ │ │ │ ├── stm32f0xx_hal_pcd_ex.o │ │ │ │ ├── stm32f0xx_hal_pwr.o │ │ │ │ ├── stm32f0xx_hal_pwr_ex.o │ │ │ │ ├── stm32f0xx_hal_rcc.o │ │ │ │ ├── stm32f0xx_hal_rcc_ex.o │ │ │ │ ├── stm32f0xx_hal_rtc.o │ │ │ │ ├── stm32f0xx_hal_rtc_ex.o │ │ │ │ ├── stm32f0xx_hal_smartcard.o │ │ │ │ ├── stm32f0xx_hal_smartcard_ex.o │ │ │ │ ├── stm32f0xx_hal_smbus.o │ │ │ │ ├── stm32f0xx_hal_spi.o │ │ │ │ ├── stm32f0xx_hal_spi_ex.o │ │ │ │ ├── stm32f0xx_hal_tim.o │ │ │ │ ├── stm32f0xx_hal_tim_ex.o │ │ │ │ ├── stm32f0xx_hal_tsc.o │ │ │ │ ├── stm32f0xx_hal_uart.o │ │ │ │ ├── stm32f0xx_hal_uart_ex.o │ │ │ │ ├── stm32f0xx_hal_usart.o │ │ │ │ ├── stm32f0xx_hal_wwdg.o │ │ │ │ └── system_stm32f0xx.o │ │ │ ├── arm_common_tables.h │ │ │ ├── arm_const_structs.h │ │ │ ├── arm_math.h │ │ │ ├── cmsis.h │ │ │ ├── cmsis_nvic.h │ │ │ ├── core_ca9.h │ │ │ ├── core_caFunc.h │ │ │ ├── core_caInstr.h │ │ │ ├── core_ca_mmu.h │ │ │ ├── core_cm0.h │ │ │ ├── core_cm0plus.h │ │ │ ├── core_cm3.h │ │ │ ├── core_cm4.h │ │ │ ├── core_cm4_simd.h │ │ │ ├── core_cm7.h │ │ │ ├── core_cmFunc.h │ │ │ ├── core_cmInstr.h │ │ │ ├── core_cmSimd.h │ │ │ ├── core_sc000.h │ │ │ ├── core_sc300.h │ │ │ ├── hal_tick.h │ │ │ ├── stm32_hal_legacy.h │ │ │ ├── stm32f091xc.h │ │ │ ├── stm32f0xx.h │ │ │ ├── stm32f0xx_hal.h │ │ │ ├── stm32f0xx_hal_adc.h │ │ │ ├── stm32f0xx_hal_adc_ex.h │ │ │ ├── stm32f0xx_hal_can.h │ │ │ ├── stm32f0xx_hal_cec.h │ │ │ ├── stm32f0xx_hal_comp.h │ │ │ ├── stm32f0xx_hal_conf.h │ │ │ ├── stm32f0xx_hal_cortex.h │ │ │ ├── stm32f0xx_hal_crc.h │ │ │ ├── stm32f0xx_hal_crc_ex.h │ │ │ ├── stm32f0xx_hal_dac.h │ │ │ ├── stm32f0xx_hal_dac_ex.h │ │ │ ├── stm32f0xx_hal_def.h │ │ │ ├── stm32f0xx_hal_dma.h │ │ │ ├── stm32f0xx_hal_dma_ex.h │ │ │ ├── stm32f0xx_hal_flash.h │ │ │ ├── stm32f0xx_hal_flash_ex.h │ │ │ ├── stm32f0xx_hal_gpio.h │ │ │ ├── stm32f0xx_hal_gpio_ex.h │ │ │ ├── stm32f0xx_hal_i2c.h │ │ │ ├── stm32f0xx_hal_i2c_ex.h │ │ │ ├── stm32f0xx_hal_i2s.h │ │ │ ├── stm32f0xx_hal_irda.h │ │ │ ├── stm32f0xx_hal_irda_ex.h │ │ │ ├── stm32f0xx_hal_iwdg.h │ │ │ ├── stm32f0xx_hal_pcd.h │ │ │ ├── stm32f0xx_hal_pcd_ex.h │ │ │ ├── stm32f0xx_hal_pwr.h │ │ │ ├── stm32f0xx_hal_pwr_ex.h │ │ │ ├── stm32f0xx_hal_rcc.h │ │ │ ├── stm32f0xx_hal_rcc_ex.h │ │ │ ├── stm32f0xx_hal_rtc.h │ │ │ ├── stm32f0xx_hal_rtc_ex.h │ │ │ ├── stm32f0xx_hal_smartcard.h │ │ │ ├── stm32f0xx_hal_smartcard_ex.h │ │ │ ├── stm32f0xx_hal_smbus.h │ │ │ ├── stm32f0xx_hal_spi.h │ │ │ ├── stm32f0xx_hal_spi_ex.h │ │ │ ├── stm32f0xx_hal_tim.h │ │ │ ├── stm32f0xx_hal_tim_ex.h │ │ │ ├── stm32f0xx_hal_tsc.h │ │ │ ├── stm32f0xx_hal_uart.h │ │ │ ├── stm32f0xx_hal_uart_ex.h │ │ │ ├── stm32f0xx_hal_usart.h │ │ │ ├── stm32f0xx_hal_usart_ex.h │ │ │ ├── stm32f0xx_hal_wwdg.h │ │ │ └── system_stm32f0xx.h │ │ ├── TARGET_NUCLEO_F401RE/ │ │ │ ├── TARGET_STM/ │ │ │ │ └── TARGET_STM32F4/ │ │ │ │ ├── PeripheralPins.h │ │ │ │ ├── TARGET_NUCLEO_F401RE/ │ │ │ │ │ ├── PeripheralNames.h │ │ │ │ │ ├── PinNames.h │ │ │ │ │ ├── PortNames.h │ │ │ │ │ ├── device.h │ │ │ │ │ └── objects.h │ │ │ │ └── gpio_object.h │ │ │ ├── TOOLCHAIN_GCC_ARM/ │ │ │ │ ├── STM32F401XE.ld │ │ │ │ ├── board.o │ │ │ │ ├── cmsis_nvic.o │ │ │ │ ├── hal_tick.o │ │ │ │ ├── libmbed.a │ │ │ │ ├── mbed_overrides.o │ │ │ │ ├── retarget.o │ │ │ │ ├── startup_stm32f401xe.o │ │ │ │ ├── stm32f4xx_hal.o │ │ │ │ ├── stm32f4xx_hal_adc.o │ │ │ │ ├── stm32f4xx_hal_adc_ex.o │ │ │ │ ├── stm32f4xx_hal_can.o │ │ │ │ ├── stm32f4xx_hal_cec.o │ │ │ │ ├── stm32f4xx_hal_cortex.o │ │ │ │ ├── stm32f4xx_hal_crc.o │ │ │ │ ├── stm32f4xx_hal_cryp.o │ │ │ │ ├── stm32f4xx_hal_cryp_ex.o │ │ │ │ ├── stm32f4xx_hal_dac.o │ │ │ │ ├── stm32f4xx_hal_dac_ex.o │ │ │ │ ├── stm32f4xx_hal_dcmi.o │ │ │ │ ├── stm32f4xx_hal_dcmi_ex.o │ │ │ │ ├── stm32f4xx_hal_dma.o │ │ │ │ ├── stm32f4xx_hal_dma2d.o │ │ │ │ ├── stm32f4xx_hal_dma_ex.o │ │ │ │ ├── stm32f4xx_hal_dsi.o │ │ │ │ ├── stm32f4xx_hal_eth.o │ │ │ │ ├── stm32f4xx_hal_flash.o │ │ │ │ ├── stm32f4xx_hal_flash_ex.o │ │ │ │ ├── stm32f4xx_hal_flash_ramfunc.o │ │ │ │ ├── stm32f4xx_hal_fmpi2c.o │ │ │ │ ├── stm32f4xx_hal_fmpi2c_ex.o │ │ │ │ ├── stm32f4xx_hal_gpio.o │ │ │ │ ├── stm32f4xx_hal_hash.o │ │ │ │ ├── stm32f4xx_hal_hash_ex.o │ │ │ │ ├── stm32f4xx_hal_hcd.o │ │ │ │ ├── stm32f4xx_hal_i2c.o │ │ │ │ ├── stm32f4xx_hal_i2c_ex.o │ │ │ │ ├── stm32f4xx_hal_i2s.o │ │ │ │ ├── stm32f4xx_hal_i2s_ex.o │ │ │ │ ├── stm32f4xx_hal_irda.o │ │ │ │ ├── stm32f4xx_hal_iwdg.o │ │ │ │ ├── stm32f4xx_hal_lptim.o │ │ │ │ ├── stm32f4xx_hal_ltdc.o │ │ │ │ ├── stm32f4xx_hal_ltdc_ex.o │ │ │ │ ├── stm32f4xx_hal_msp_template.o │ │ │ │ ├── stm32f4xx_hal_nand.o │ │ │ │ ├── stm32f4xx_hal_nor.o │ │ │ │ ├── stm32f4xx_hal_pccard.o │ │ │ │ ├── stm32f4xx_hal_pcd.o │ │ │ │ ├── stm32f4xx_hal_pcd_ex.o │ │ │ │ ├── stm32f4xx_hal_pwr.o │ │ │ │ ├── stm32f4xx_hal_pwr_ex.o │ │ │ │ ├── stm32f4xx_hal_qspi.o │ │ │ │ ├── stm32f4xx_hal_rcc.o │ │ │ │ ├── stm32f4xx_hal_rcc_ex.o │ │ │ │ ├── stm32f4xx_hal_rng.o │ │ │ │ ├── stm32f4xx_hal_rtc.o │ │ │ │ ├── stm32f4xx_hal_rtc_ex.o │ │ │ │ ├── stm32f4xx_hal_sai.o │ │ │ │ ├── stm32f4xx_hal_sai_ex.o │ │ │ │ ├── stm32f4xx_hal_sd.o │ │ │ │ ├── stm32f4xx_hal_sdram.o │ │ │ │ ├── stm32f4xx_hal_smartcard.o │ │ │ │ ├── stm32f4xx_hal_spdifrx.o │ │ │ │ ├── stm32f4xx_hal_spi.o │ │ │ │ ├── stm32f4xx_hal_sram.o │ │ │ │ ├── stm32f4xx_hal_tim.o │ │ │ │ ├── stm32f4xx_hal_tim_ex.o │ │ │ │ ├── stm32f4xx_hal_uart.o │ │ │ │ ├── stm32f4xx_hal_usart.o │ │ │ │ ├── stm32f4xx_hal_wwdg.o │ │ │ │ ├── stm32f4xx_ll_fmc.o │ │ │ │ ├── stm32f4xx_ll_fsmc.o │ │ │ │ ├── stm32f4xx_ll_sdmmc.o │ │ │ │ ├── stm32f4xx_ll_usb.o │ │ │ │ └── system_stm32f4xx.o │ │ │ ├── arm_common_tables.h │ │ │ ├── arm_const_structs.h │ │ │ ├── arm_math.h │ │ │ ├── cmsis.h │ │ │ ├── cmsis_nvic.h │ │ │ ├── core_ca9.h │ │ │ ├── core_caFunc.h │ │ │ ├── core_caInstr.h │ │ │ ├── core_ca_mmu.h │ │ │ ├── core_cm0.h │ │ │ ├── core_cm0plus.h │ │ │ ├── core_cm3.h │ │ │ ├── core_cm4.h │ │ │ ├── core_cm4_simd.h │ │ │ ├── core_cm7.h │ │ │ ├── core_cmFunc.h │ │ │ ├── core_cmInstr.h │ │ │ ├── core_cmSimd.h │ │ │ ├── core_sc000.h │ │ │ ├── core_sc300.h │ │ │ ├── hal_tick.h │ │ │ ├── stm32_hal_legacy.h │ │ │ ├── stm32f401xe.h │ │ │ ├── stm32f4xx.h │ │ │ ├── stm32f4xx_hal.h │ │ │ ├── stm32f4xx_hal_adc.h │ │ │ ├── stm32f4xx_hal_adc_ex.h │ │ │ ├── stm32f4xx_hal_can.h │ │ │ ├── stm32f4xx_hal_cec.h │ │ │ ├── stm32f4xx_hal_conf.h │ │ │ ├── stm32f4xx_hal_conf_template.h │ │ │ ├── stm32f4xx_hal_cortex.h │ │ │ ├── stm32f4xx_hal_crc.h │ │ │ ├── stm32f4xx_hal_cryp.h │ │ │ ├── stm32f4xx_hal_cryp_ex.h │ │ │ ├── stm32f4xx_hal_dac.h │ │ │ ├── stm32f4xx_hal_dac_ex.h │ │ │ ├── stm32f4xx_hal_dcmi.h │ │ │ ├── stm32f4xx_hal_dcmi_ex.h │ │ │ ├── stm32f4xx_hal_def.h │ │ │ ├── stm32f4xx_hal_dma.h │ │ │ ├── stm32f4xx_hal_dma2d.h │ │ │ ├── stm32f4xx_hal_dma_ex.h │ │ │ ├── stm32f4xx_hal_dsi.h │ │ │ ├── stm32f4xx_hal_eth.h │ │ │ ├── stm32f4xx_hal_flash.h │ │ │ ├── stm32f4xx_hal_flash_ex.h │ │ │ ├── stm32f4xx_hal_flash_ramfunc.h │ │ │ ├── stm32f4xx_hal_fmpi2c.h │ │ │ ├── stm32f4xx_hal_fmpi2c_ex.h │ │ │ ├── stm32f4xx_hal_gpio.h │ │ │ ├── stm32f4xx_hal_gpio_ex.h │ │ │ ├── stm32f4xx_hal_hash.h │ │ │ ├── stm32f4xx_hal_hash_ex.h │ │ │ ├── stm32f4xx_hal_hcd.h │ │ │ ├── stm32f4xx_hal_i2c.h │ │ │ ├── stm32f4xx_hal_i2c_ex.h │ │ │ ├── stm32f4xx_hal_i2s.h │ │ │ ├── stm32f4xx_hal_i2s_ex.h │ │ │ ├── stm32f4xx_hal_irda.h │ │ │ ├── stm32f4xx_hal_iwdg.h │ │ │ ├── stm32f4xx_hal_lptim.h │ │ │ ├── stm32f4xx_hal_ltdc.h │ │ │ ├── stm32f4xx_hal_ltdc_ex.h │ │ │ ├── stm32f4xx_hal_nand.h │ │ │ ├── stm32f4xx_hal_nor.h │ │ │ ├── stm32f4xx_hal_pccard.h │ │ │ ├── stm32f4xx_hal_pcd.h │ │ │ ├── stm32f4xx_hal_pcd_ex.h │ │ │ ├── stm32f4xx_hal_pwr.h │ │ │ ├── stm32f4xx_hal_pwr_ex.h │ │ │ ├── stm32f4xx_hal_qspi.h │ │ │ ├── stm32f4xx_hal_rcc.h │ │ │ ├── stm32f4xx_hal_rcc_ex.h │ │ │ ├── stm32f4xx_hal_rng.h │ │ │ ├── stm32f4xx_hal_rtc.h │ │ │ ├── stm32f4xx_hal_rtc_ex.h │ │ │ ├── stm32f4xx_hal_sai.h │ │ │ ├── stm32f4xx_hal_sai_ex.h │ │ │ ├── stm32f4xx_hal_sd.h │ │ │ ├── stm32f4xx_hal_sdram.h │ │ │ ├── stm32f4xx_hal_smartcard.h │ │ │ ├── stm32f4xx_hal_spdifrx.h │ │ │ ├── stm32f4xx_hal_spi.h │ │ │ ├── stm32f4xx_hal_sram.h │ │ │ ├── stm32f4xx_hal_tim.h │ │ │ ├── stm32f4xx_hal_tim_ex.h │ │ │ ├── stm32f4xx_hal_uart.h │ │ │ ├── stm32f4xx_hal_usart.h │ │ │ ├── stm32f4xx_hal_wwdg.h │ │ │ ├── stm32f4xx_ll_fmc.h │ │ │ ├── stm32f4xx_ll_fsmc.h │ │ │ ├── stm32f4xx_ll_sdmmc.h │ │ │ ├── stm32f4xx_ll_usb.h │ │ │ └── system_stm32f4xx.h │ │ ├── TARGET_NUCLEO_F411RE/ │ │ │ ├── TARGET_STM/ │ │ │ │ └── TARGET_STM32F4/ │ │ │ │ ├── PeripheralPins.h │ │ │ │ ├── TARGET_NUCLEO_F411RE/ │ │ │ │ │ ├── PeripheralNames.h │ │ │ │ │ ├── PinNames.h │ │ │ │ │ ├── PortNames.h │ │ │ │ │ ├── device.h │ │ │ │ │ └── objects.h │ │ │ │ └── gpio_object.h │ │ │ ├── TOOLCHAIN_GCC_ARM/ │ │ │ │ ├── STM32F411XE.ld │ │ │ │ ├── board.o │ │ │ │ ├── cmsis_nvic.o │ │ │ │ ├── hal_tick.o │ │ │ │ ├── liblwipsysarch.a │ │ │ │ ├── libmbed.a │ │ │ │ ├── libmbedeth.a │ │ │ │ ├── mbed_overrides.o │ │ │ │ ├── retarget.o │ │ │ │ ├── startup_stm32f411xe.o │ │ │ │ ├── stm32f4xx_hal.o │ │ │ │ ├── stm32f4xx_hal_adc.o │ │ │ │ ├── stm32f4xx_hal_adc_ex.o │ │ │ │ ├── stm32f4xx_hal_can.o │ │ │ │ ├── stm32f4xx_hal_cec.o │ │ │ │ ├── stm32f4xx_hal_cortex.o │ │ │ │ ├── stm32f4xx_hal_crc.o │ │ │ │ ├── stm32f4xx_hal_cryp.o │ │ │ │ ├── stm32f4xx_hal_cryp_ex.o │ │ │ │ ├── stm32f4xx_hal_dac.o │ │ │ │ ├── stm32f4xx_hal_dac_ex.o │ │ │ │ ├── stm32f4xx_hal_dcmi.o │ │ │ │ ├── stm32f4xx_hal_dcmi_ex.o │ │ │ │ ├── stm32f4xx_hal_dma.o │ │ │ │ ├── stm32f4xx_hal_dma2d.o │ │ │ │ ├── stm32f4xx_hal_dma_ex.o │ │ │ │ ├── stm32f4xx_hal_dsi.o │ │ │ │ ├── stm32f4xx_hal_eth.o │ │ │ │ ├── stm32f4xx_hal_flash.o │ │ │ │ ├── stm32f4xx_hal_flash_ex.o │ │ │ │ ├── stm32f4xx_hal_flash_ramfunc.o │ │ │ │ ├── stm32f4xx_hal_fmpi2c.o │ │ │ │ ├── stm32f4xx_hal_fmpi2c_ex.o │ │ │ │ ├── stm32f4xx_hal_gpio.o │ │ │ │ ├── stm32f4xx_hal_hash.o │ │ │ │ ├── stm32f4xx_hal_hash_ex.o │ │ │ │ ├── stm32f4xx_hal_hcd.o │ │ │ │ ├── stm32f4xx_hal_i2c.o │ │ │ │ ├── stm32f4xx_hal_i2c_ex.o │ │ │ │ ├── stm32f4xx_hal_i2s.o │ │ │ │ ├── stm32f4xx_hal_i2s_ex.o │ │ │ │ ├── stm32f4xx_hal_irda.o │ │ │ │ ├── stm32f4xx_hal_iwdg.o │ │ │ │ ├── stm32f4xx_hal_lptim.o │ │ │ │ ├── stm32f4xx_hal_ltdc.o │ │ │ │ ├── stm32f4xx_hal_ltdc_ex.o │ │ │ │ ├── stm32f4xx_hal_msp_template.o │ │ │ │ ├── stm32f4xx_hal_nand.o │ │ │ │ ├── stm32f4xx_hal_nor.o │ │ │ │ ├── stm32f4xx_hal_pccard.o │ │ │ │ ├── stm32f4xx_hal_pcd.o │ │ │ │ ├── stm32f4xx_hal_pcd_ex.o │ │ │ │ ├── stm32f4xx_hal_pwr.o │ │ │ │ ├── stm32f4xx_hal_pwr_ex.o │ │ │ │ ├── stm32f4xx_hal_qspi.o │ │ │ │ ├── stm32f4xx_hal_rcc.o │ │ │ │ ├── stm32f4xx_hal_rcc_ex.o │ │ │ │ ├── stm32f4xx_hal_rng.o │ │ │ │ ├── stm32f4xx_hal_rtc.o │ │ │ │ ├── stm32f4xx_hal_rtc_ex.o │ │ │ │ ├── stm32f4xx_hal_sai.o │ │ │ │ ├── stm32f4xx_hal_sai_ex.o │ │ │ │ ├── stm32f4xx_hal_sd.o │ │ │ │ ├── stm32f4xx_hal_sdram.o │ │ │ │ ├── stm32f4xx_hal_smartcard.o │ │ │ │ ├── stm32f4xx_hal_spdifrx.o │ │ │ │ ├── stm32f4xx_hal_spi.o │ │ │ │ ├── stm32f4xx_hal_sram.o │ │ │ │ ├── stm32f4xx_hal_tim.o │ │ │ │ ├── stm32f4xx_hal_tim_ex.o │ │ │ │ ├── stm32f4xx_hal_uart.o │ │ │ │ ├── stm32f4xx_hal_usart.o │ │ │ │ ├── stm32f4xx_hal_wwdg.o │ │ │ │ ├── stm32f4xx_ll_fmc.o │ │ │ │ ├── stm32f4xx_ll_fsmc.o │ │ │ │ ├── stm32f4xx_ll_sdmmc.o │ │ │ │ ├── stm32f4xx_ll_usb.o │ │ │ │ └── system_stm32f4xx.o │ │ │ ├── arm_common_tables.h │ │ │ ├── arm_const_structs.h │ │ │ ├── arm_math.h │ │ │ ├── cmsis.h │ │ │ ├── cmsis_nvic.h │ │ │ ├── core_ca9.h │ │ │ ├── core_caFunc.h │ │ │ ├── core_caInstr.h │ │ │ ├── core_ca_mmu.h │ │ │ ├── core_cm0.h │ │ │ ├── core_cm0plus.h │ │ │ ├── core_cm3.h │ │ │ ├── core_cm4.h │ │ │ ├── core_cm4_simd.h │ │ │ ├── core_cm7.h │ │ │ ├── core_cmFunc.h │ │ │ ├── core_cmInstr.h │ │ │ ├── core_cmSimd.h │ │ │ ├── core_sc000.h │ │ │ ├── core_sc300.h │ │ │ ├── hal_tick.h │ │ │ ├── stm32_hal_legacy.h │ │ │ ├── stm32f411xe.h │ │ │ ├── stm32f4xx.h │ │ │ ├── stm32f4xx_hal.h │ │ │ ├── stm32f4xx_hal_adc.h │ │ │ ├── stm32f4xx_hal_adc_ex.h │ │ │ ├── stm32f4xx_hal_can.h │ │ │ ├── stm32f4xx_hal_cec.h │ │ │ ├── stm32f4xx_hal_conf.h │ │ │ ├── stm32f4xx_hal_conf_template.h │ │ │ ├── stm32f4xx_hal_cortex.h │ │ │ ├── stm32f4xx_hal_crc.h │ │ │ ├── stm32f4xx_hal_cryp.h │ │ │ ├── stm32f4xx_hal_cryp_ex.h │ │ │ ├── stm32f4xx_hal_dac.h │ │ │ ├── stm32f4xx_hal_dac_ex.h │ │ │ ├── stm32f4xx_hal_dcmi.h │ │ │ ├── stm32f4xx_hal_dcmi_ex.h │ │ │ ├── stm32f4xx_hal_def.h │ │ │ ├── stm32f4xx_hal_dma.h │ │ │ ├── stm32f4xx_hal_dma2d.h │ │ │ ├── stm32f4xx_hal_dma_ex.h │ │ │ ├── stm32f4xx_hal_dsi.h │ │ │ ├── stm32f4xx_hal_eth.h │ │ │ ├── stm32f4xx_hal_flash.h │ │ │ ├── stm32f4xx_hal_flash_ex.h │ │ │ ├── stm32f4xx_hal_flash_ramfunc.h │ │ │ ├── stm32f4xx_hal_fmpi2c.h │ │ │ ├── stm32f4xx_hal_fmpi2c_ex.h │ │ │ ├── stm32f4xx_hal_gpio.h │ │ │ ├── stm32f4xx_hal_gpio_ex.h │ │ │ ├── stm32f4xx_hal_hash.h │ │ │ ├── stm32f4xx_hal_hash_ex.h │ │ │ ├── stm32f4xx_hal_hcd.h │ │ │ ├── stm32f4xx_hal_i2c.h │ │ │ ├── stm32f4xx_hal_i2c_ex.h │ │ │ ├── stm32f4xx_hal_i2s.h │ │ │ ├── stm32f4xx_hal_i2s_ex.h │ │ │ ├── stm32f4xx_hal_irda.h │ │ │ ├── stm32f4xx_hal_iwdg.h │ │ │ ├── stm32f4xx_hal_lptim.h │ │ │ ├── stm32f4xx_hal_ltdc.h │ │ │ ├── stm32f4xx_hal_ltdc_ex.h │ │ │ ├── stm32f4xx_hal_nand.h │ │ │ ├── stm32f4xx_hal_nor.h │ │ │ ├── stm32f4xx_hal_pccard.h │ │ │ ├── stm32f4xx_hal_pcd.h │ │ │ ├── stm32f4xx_hal_pcd_ex.h │ │ │ ├── stm32f4xx_hal_pwr.h │ │ │ ├── stm32f4xx_hal_pwr_ex.h │ │ │ ├── stm32f4xx_hal_qspi.h │ │ │ ├── stm32f4xx_hal_rcc.h │ │ │ ├── stm32f4xx_hal_rcc_ex.h │ │ │ ├── stm32f4xx_hal_rng.h │ │ │ ├── stm32f4xx_hal_rtc.h │ │ │ ├── stm32f4xx_hal_rtc_ex.h │ │ │ ├── stm32f4xx_hal_sai.h │ │ │ ├── stm32f4xx_hal_sai_ex.h │ │ │ ├── stm32f4xx_hal_sd.h │ │ │ ├── stm32f4xx_hal_sdram.h │ │ │ ├── stm32f4xx_hal_smartcard.h │ │ │ ├── stm32f4xx_hal_spdifrx.h │ │ │ ├── stm32f4xx_hal_spi.h │ │ │ ├── stm32f4xx_hal_sram.h │ │ │ ├── stm32f4xx_hal_tim.h │ │ │ ├── stm32f4xx_hal_tim_ex.h │ │ │ ├── stm32f4xx_hal_uart.h │ │ │ ├── stm32f4xx_hal_usart.h │ │ │ ├── stm32f4xx_hal_wwdg.h │ │ │ ├── stm32f4xx_ll_fmc.h │ │ │ ├── stm32f4xx_ll_fsmc.h │ │ │ ├── stm32f4xx_ll_sdmmc.h │ │ │ ├── stm32f4xx_ll_usb.h │ │ │ └── system_stm32f4xx.h │ │ ├── TARGET_NUCLEO_L152RE/ │ │ │ ├── TARGET_STM/ │ │ │ │ └── TARGET_STM32L1/ │ │ │ │ ├── PeripheralPins.h │ │ │ │ ├── TARGET_NUCLEO_L152RE/ │ │ │ │ │ ├── PeripheralNames.h │ │ │ │ │ ├── PinNames.h │ │ │ │ │ ├── PortNames.h │ │ │ │ │ ├── device.h │ │ │ │ │ └── objects.h │ │ │ │ └── gpio_object.h │ │ │ ├── TOOLCHAIN_GCC_ARM/ │ │ │ │ ├── STM32L152XE.ld │ │ │ │ ├── board.o │ │ │ │ ├── cmsis_nvic.o │ │ │ │ ├── hal_tick.o │ │ │ │ ├── libmbed.a │ │ │ │ ├── libmbedeth.a │ │ │ │ ├── mbed_overrides.o │ │ │ │ ├── retarget.o │ │ │ │ ├── startup_stm32l152xe.o │ │ │ │ ├── stm32l1xx_hal.o │ │ │ │ ├── stm32l1xx_hal_adc.o │ │ │ │ ├── stm32l1xx_hal_adc_ex.o │ │ │ │ ├── stm32l1xx_hal_comp.o │ │ │ │ ├── stm32l1xx_hal_cortex.o │ │ │ │ ├── stm32l1xx_hal_crc.o │ │ │ │ ├── stm32l1xx_hal_cryp.o │ │ │ │ ├── stm32l1xx_hal_cryp_ex.o │ │ │ │ ├── stm32l1xx_hal_dac.o │ │ │ │ ├── stm32l1xx_hal_dac_ex.o │ │ │ │ ├── stm32l1xx_hal_dma.o │ │ │ │ ├── stm32l1xx_hal_flash.o │ │ │ │ ├── stm32l1xx_hal_flash_ex.o │ │ │ │ ├── stm32l1xx_hal_flash_ramfunc.o │ │ │ │ ├── stm32l1xx_hal_gpio.o │ │ │ │ ├── stm32l1xx_hal_i2c.o │ │ │ │ ├── stm32l1xx_hal_i2s.o │ │ │ │ ├── stm32l1xx_hal_irda.o │ │ │ │ ├── stm32l1xx_hal_iwdg.o │ │ │ │ ├── stm32l1xx_hal_lcd.o │ │ │ │ ├── stm32l1xx_hal_nor.o │ │ │ │ ├── stm32l1xx_hal_opamp.o │ │ │ │ ├── stm32l1xx_hal_opamp_ex.o │ │ │ │ ├── stm32l1xx_hal_pcd.o │ │ │ │ ├── stm32l1xx_hal_pcd_ex.o │ │ │ │ ├── stm32l1xx_hal_pwr.o │ │ │ │ ├── stm32l1xx_hal_pwr_ex.o │ │ │ │ ├── stm32l1xx_hal_rcc.o │ │ │ │ ├── stm32l1xx_hal_rcc_ex.o │ │ │ │ ├── stm32l1xx_hal_rtc.o │ │ │ │ ├── stm32l1xx_hal_rtc_ex.o │ │ │ │ ├── stm32l1xx_hal_sd.o │ │ │ │ ├── stm32l1xx_hal_smartcard.o │ │ │ │ ├── stm32l1xx_hal_spi.o │ │ │ │ ├── stm32l1xx_hal_spi_ex.o │ │ │ │ ├── stm32l1xx_hal_sram.o │ │ │ │ ├── stm32l1xx_hal_tim.o │ │ │ │ ├── stm32l1xx_hal_tim_ex.o │ │ │ │ ├── stm32l1xx_hal_uart.o │ │ │ │ ├── stm32l1xx_hal_usart.o │ │ │ │ ├── stm32l1xx_hal_wwdg.o │ │ │ │ ├── stm32l1xx_ll_fsmc.o │ │ │ │ ├── stm32l1xx_ll_sdmmc.o │ │ │ │ └── system_stm32l1xx.o │ │ │ ├── cmsis.h │ │ │ ├── cmsis_nvic.h │ │ │ ├── core_ca9.h │ │ │ ├── core_caFunc.h │ │ │ ├── core_caInstr.h │ │ │ ├── core_ca_mmu.h │ │ │ ├── core_cm0.h │ │ │ ├── core_cm0plus.h │ │ │ ├── core_cm3.h │ │ │ ├── core_cm4.h │ │ │ ├── core_cm4_simd.h │ │ │ ├── core_cm7.h │ │ │ ├── core_cmFunc.h │ │ │ ├── core_cmInstr.h │ │ │ ├── core_cmSimd.h │ │ │ ├── hal_tick.h │ │ │ ├── stm32l152xe.h │ │ │ ├── stm32l1xx.h │ │ │ ├── stm32l1xx_hal.h │ │ │ ├── stm32l1xx_hal_adc.h │ │ │ ├── stm32l1xx_hal_adc_ex.h │ │ │ ├── stm32l1xx_hal_comp.h │ │ │ ├── stm32l1xx_hal_comp_ex.h │ │ │ ├── stm32l1xx_hal_conf.h │ │ │ ├── stm32l1xx_hal_cortex.h │ │ │ ├── stm32l1xx_hal_crc.h │ │ │ ├── stm32l1xx_hal_cryp.h │ │ │ ├── stm32l1xx_hal_cryp_ex.h │ │ │ ├── stm32l1xx_hal_dac.h │ │ │ ├── stm32l1xx_hal_dac_ex.h │ │ │ ├── stm32l1xx_hal_def.h │ │ │ ├── stm32l1xx_hal_dma.h │ │ │ ├── stm32l1xx_hal_dma_ex.h │ │ │ ├── stm32l1xx_hal_flash.h │ │ │ ├── stm32l1xx_hal_flash_ex.h │ │ │ ├── stm32l1xx_hal_flash_ramfunc.h │ │ │ ├── stm32l1xx_hal_gpio.h │ │ │ ├── stm32l1xx_hal_gpio_ex.h │ │ │ ├── stm32l1xx_hal_i2c.h │ │ │ ├── stm32l1xx_hal_i2s.h │ │ │ ├── stm32l1xx_hal_irda.h │ │ │ ├── stm32l1xx_hal_iwdg.h │ │ │ ├── stm32l1xx_hal_lcd.h │ │ │ ├── stm32l1xx_hal_nor.h │ │ │ ├── stm32l1xx_hal_opamp.h │ │ │ ├── stm32l1xx_hal_opamp_ex.h │ │ │ ├── stm32l1xx_hal_pcd.h │ │ │ ├── stm32l1xx_hal_pcd_ex.h │ │ │ ├── stm32l1xx_hal_pwr.h │ │ │ ├── stm32l1xx_hal_pwr_ex.h │ │ │ ├── stm32l1xx_hal_rcc.h │ │ │ ├── stm32l1xx_hal_rcc_ex.h │ │ │ ├── stm32l1xx_hal_rtc.h │ │ │ ├── stm32l1xx_hal_rtc_ex.h │ │ │ ├── stm32l1xx_hal_sd.h │ │ │ ├── stm32l1xx_hal_smartcard.h │ │ │ ├── stm32l1xx_hal_spi.h │ │ │ ├── stm32l1xx_hal_spi_ex.h │ │ │ ├── stm32l1xx_hal_sram.h │ │ │ ├── stm32l1xx_hal_tim.h │ │ │ ├── stm32l1xx_hal_tim_ex.h │ │ │ ├── stm32l1xx_hal_uart.h │ │ │ ├── stm32l1xx_hal_usart.h │ │ │ ├── stm32l1xx_hal_wwdg.h │ │ │ ├── stm32l1xx_ll_fsmc.h │ │ │ ├── stm32l1xx_ll_sdmmc.h │ │ │ └── system_stm32l1xx.h │ │ ├── Ticker.h │ │ ├── Timeout.h │ │ ├── Timer.h │ │ ├── TimerEvent.h │ │ ├── Transaction.h │ │ ├── analogin_api.h │ │ ├── analogout_api.h │ │ ├── buffer.h │ │ ├── can_api.h │ │ ├── can_helper.h │ │ ├── dma_api.h │ │ ├── ethernet_api.h │ │ ├── gpio_api.h │ │ ├── gpio_irq_api.h │ │ ├── i2c_api.h │ │ ├── lp_ticker_api.h │ │ ├── mbed.h │ │ ├── mbed_assert.h │ │ ├── mbed_debug.h │ │ ├── mbed_error.h │ │ ├── mbed_interface.h │ │ ├── pinmap.h │ │ ├── platform.h │ │ ├── port_api.h │ │ ├── pwmout_api.h │ │ ├── rtc_api.h │ │ ├── rtc_time.h │ │ ├── semihost_api.h │ │ ├── serial_api.h │ │ ├── sleep_api.h │ │ ├── spi_api.h │ │ ├── ticker_api.h │ │ ├── toolchain.h │ │ ├── us_ticker_api.h │ │ └── wait_api.h │ ├── os_layer/ │ │ ├── ARMv7M/ │ │ │ └── Vectors/ │ │ │ ├── startup_LPC17xx.S │ │ │ ├── startup_MK64F12.S │ │ │ ├── startup_stm32f091xc.S │ │ │ ├── startup_stm32f401xe.S │ │ │ ├── startup_stm32f411xe.S │ │ │ └── startup_stm32l152xe.S │ │ ├── inc/ │ │ │ ├── api/ │ │ │ │ ├── io/ │ │ │ │ │ ├── llos_analog.h │ │ │ │ │ ├── llos_gpio.h │ │ │ │ │ ├── llos_i2c.h │ │ │ │ │ ├── llos_pwm.h │ │ │ │ │ ├── llos_serial.h │ │ │ │ │ └── llos_spi.h │ │ │ │ └── llos_memory.h │ │ │ ├── hal/ │ │ │ │ ├── llos_clock.h │ │ │ │ ├── llos_mutex.h │ │ │ │ ├── llos_system_timer.h │ │ │ │ └── llos_thread.h │ │ │ ├── llos_error.h │ │ │ ├── llos_platform.h │ │ │ ├── llos_types.h │ │ │ └── llos_unwind.h │ │ └── ports/ │ │ ├── mbed/ │ │ │ ├── MbedOSAbstraction.vcxproj │ │ │ ├── mbed_adc.cpp │ │ │ ├── mbed_asm.S │ │ │ ├── mbed_clock.cpp │ │ │ ├── mbed_core.cpp │ │ │ ├── mbed_debug.cpp │ │ │ ├── mbed_ethernet.cpp │ │ │ ├── mbed_gpio.cpp │ │ │ ├── mbed_helpers.h │ │ │ ├── mbed_i2c.cpp │ │ │ ├── mbed_mem.cpp │ │ │ ├── mbed_memory.cpp │ │ │ ├── mbed_nvic.cpp │ │ │ ├── mbed_overrides.cpp │ │ │ ├── mbed_pwm.cpp │ │ │ ├── mbed_serial.cpp │ │ │ ├── mbed_socket.cpp │ │ │ ├── mbed_spi.cpp │ │ │ ├── mbed_system_timer.cpp │ │ │ ├── mbed_systick.cpp │ │ │ ├── mbed_threading.cpp │ │ │ └── mbed_unwind.cpp │ │ └── win32/ │ │ └── Win32Abstraction/ │ │ ├── LlosClock.cpp │ │ ├── LlosDebug.cpp │ │ ├── LlosEntry.cpp │ │ ├── LlosGarbageCollection.cpp │ │ ├── LlosMemory.cpp │ │ ├── LlosMutex.cpp │ │ ├── LlosStubs.cpp │ │ ├── LlosThread.cpp │ │ ├── LlosTimer.cpp │ │ ├── LlosUnwind.cpp │ │ ├── LlosWin32.h │ │ ├── Win32Abstraction.vcxproj │ │ └── Win32Abstraction.vcxproj.filters │ ├── startVS.cmd │ └── tools/ │ └── readme.txt ├── docs/ │ └── CoAP/ │ └── readme.txt ├── llilum.vssettings ├── setenv.cmd └── setenv32.cmd ================================================ FILE CONTENTS ================================================ ================================================ FILE: .gitattributes ================================================ ############################################################################### # Set default behavior to automatically normalize line endings. ############################################################################### * text=binary ############################################################################### # Set default behavior for command prompt diff. # # This is need for earlier builds of msysgit that does not have it on by # default for csharp files. # Note: This is only used by command line ############################################################################### #*.cs diff=csharp ############################################################################### # Set the merge driver for project and solution files # # Merging from the command prompt will add diff markers to the files if there # are conflicts (Merging from VS is not affected by the settings below, in VS # the diff markers are never inserted). Diff markers may cause the following # file extensions to fail to load in VS. An alternative would be to treat # these files as binary and thus will always conflict and require user # intervention with every merge. To do so, just uncomment the entries below ############################################################################### #*.sln merge=binary #*.csproj merge=binary #*.vbproj merge=binary #*.vcxproj merge=binary #*.vcproj merge=binary #*.dbproj merge=binary #*.fsproj merge=binary #*.lsproj merge=binary #*.wixproj merge=binary #*.modelproj merge=binary #*.sqlproj merge=binary #*.wwaproj merge=binary ############################################################################### # behavior for image files # # image files are treated as binary by default. ############################################################################### #*.jpg binary #*.png binary #*.gif binary ############################################################################### # diff behavior for common document formats # # Convert binary document formats to text before diffing them. This feature # is only available from the command line. Turn it on by uncommenting the # entries below. ############################################################################### #*.doc diff=astextplain #*.DOC diff=astextplain #*.docx diff=astextplain #*.DOCX diff=astextplain #*.dot diff=astextplain #*.DOT diff=astextplain #*.pdf diff=astextplain #*.PDF diff=astextplain #*.rtf diff=astextplain #*.RTF diff=astextplain ================================================ FILE: .gitignore ================================================ ## LLVM and Zelig external/LLVM/ external/gcc4mbed/ zelig/LLVM2IR_results/mbed/simple/LPC1768/ zelig/LLVM2IR_results/mbed/simple/K64F/ zelig/LLVM2IR_results/mbed/simple/STM32L152/ zelig/LLVM2IR_results/mbed/simple/STM32F411/ zelig/LLVM2IR_results/mbed/simple/STM32F401/ zelig/LLVM2IR_results/mbed/simple/STM32F091/ zelig/LLVM2IR_results/mbed/simple/*.xml Zelig/LLVM2IR_results/mbed/test/LPC1768/ Zelig/LLVM2IR_results/mbed/test/K64F/ Zelig/LLVM2IR_results/mbed/mbed_rtos/GpioInterrupts/LPC1768/ Zelig/LLVM2IR_results/mbed/mbed_rtos/GpioInterrupts/K64F/ Zelig/mbed-rtos/ Zelig/mbed-rtos.lib *.IrTxtpost *.ZeligIR *.ZeligIR.xml *.ZeligIR_Post *.ZeligImage *.ElfDump *.ZeligCallsFromGraph *.ZeligCallsToGraph *.bc *.ll *.bc *_opt.o *.opendb ## OpenOCD Zelig/tools/openocd/* ## Ignore Visual Studio temporary files, build results, and ## files generated by popular Visual Studio add-ons. Zelig/zelig-pr.wiki/ # User-specific files *.cache *.FileListAbsolute.txt *.suo *.user *.userosscache *.sln.docstates *tmp_debug.bat # User-specific files (MonoDevelop/Xamarin Studio) *.userprefs # Build results [Dd]ebug/ [Dd]ebugPublic/ [Rr]elease/ [Rr]eleases/ x64/ x86/ build/ bld/ [Bb]in/ [Oo]bj/ *.bc *.ll # Visual Studo 2015 cache/options directory .vs/ # MSTest test Results [Tt]est[Rr]esult*/ [Bb]uild[Ll]og.* # NUNIT *.VisualState.xml TestResult.xml # Build Results of an ATL Project [Dd]ebugPS/ [Rr]eleasePS/ dlldata.c *.log *_i.c *_p.c *_i.h *.ilk *.meta *.obj *.pch *.pdb *.pgc *.pgd *.rsp *.sbr *.sbr *.tlb *.tli *.tlh *.tmp *.tmp_proj *.log *.vspscc *.vssscc .builds *.pidb *.svclog *.scc # Chutzpah Test files _Chutzpah* # Visual C++ cache files ipch/ *.aps *.ncb *.opensdf *.sdf *.cachefile # Visual Studio profiler *.psess *.vsp *.vspx # TFS 2012 Local Workspace $tf/ # Guidance Automation Toolkit *.gpState # ReSharper is a .NET coding add-in _ReSharper*/ *.[Rr]e[Ss]harper *.DotSettings.user # JustCode is a .NET coding addin-in .JustCode # TeamCity is a build add-in _TeamCity* # DotCover is a Code Coverage Tool *.dotCover # NCrunch _NCrunch_* .*crunch*.local.xml # MightyMoose *.mm.* AutoTest.Net/ # Web workbench (sass) .sass-cache/ # Installshield output folder [Ee]xpress/ # DocProject is a documentation generator add-in DocProject/buildhelp/ DocProject/Help/*.HxT DocProject/Help/*.HxC DocProject/Help/*.hhc DocProject/Help/*.hhk DocProject/Help/*.hhp DocProject/Help/Html2 DocProject/Help/html # Click-Once directory publish/ # Publish Web Output *.[Pp]ublish.xml *.azurePubxml # TODO: Comment the next line if you want to checkin your web deploy settings # but database connection strings (with potential passwords) will be unencrypted *.pubxml *.publishproj # NuGet Packages *.nupkg # The packages folder can be ignored because of Package Restore **/packages/* # except build/, which is used as an MSBuild target. !**/packages/build/ # Uncomment if necessary however generally it will be regenerated when needed #!**/packages/repositories.config # Windows Azure Build Output csx/ *.build.csdef # Windows Store app package directory AppPackages/ # Others *.[Cc]ache ClientBin/ [Ss]tyle[Cc]op.* ~$* *~ *.dbmdl *.dbproj.schemaview *.pfx *.publishsettings node_modules/ bower_components/ # RIA/Silverlight projects Generated_Code/ # Backup & report files from converting an old project file # to a newer Visual Studio version. Backup files are not needed, # because we have git ;-) _UpgradeReport_Files/ Backup*/ UpgradeLog*.XML UpgradeLog*.htm # SQL Server files *.mdf *.ldf #LightSwitch generated files GeneratedArtifacts/ _Pvt_Extensions/ ModelManifest.xml # ========================= # Windows detritus # ========================= # Windows image file caches Thumbs.db ehthumbs.db # Business Intelligence projects *.rdl.data *.bim.layout *.bim_*.settings # Microsoft Fakes FakesAssemblies/ # Node.js Tools for Visual Studio .ntvs_analysis.dat # Visual Studio 6 build log *.plg # Visual Studio 6 workspace options file *.opt *.tlog #Default build output location for CreateSDKDrop.bat /Scripts/SDKDrop Zelig/Zelig/CompileTime/Llvm.NET/LibLLVM/Win32/RelWithDebInfo/LibLLVM.3.6.1.dll Zelig/Zelig/CompileTime/Llvm.NET/LibLLVM/Win32/RelWithDebInfo/LibLLVM.3.6.1.exp Zelig/Zelig/CompileTime/Llvm.NET/LibLLVM/Win32/RelWithDebInfo/LibLLVM.3.6.1.iobj Zelig/Zelig/CompileTime/Llvm.NET/LibLLVM/Win32/RelWithDebInfo/LibLLVM.3.6.1.ipdb Zelig/Zelig/CompileTime/Llvm.NET/LibLLVM/Win32/RelWithDebInfo/LibLLVM.3.6.1.lib Zelig/Zelig/CompileTime/Llvm.NET/Win32/RelWithDebInfo/Llvm.NET.dll *.opendb /Zelig/Zelig/CompileTime/Llvm.NET/LibLLVM/generatedversioninfo.h /LlilumSDK/LlilumSDK/FrameworkList.xml Zelig/Zelig/Zelig.VC.db ================================================ FILE: BuildEnv.props ================================================ $([System.IO.Path]::GetFullPath('$(MSBuildThisFileDirectory)')) $(LLILUM_ROOT)Zelig\ 3.8.1 $([MSBuild]::GetRegistryValue(`HKEY_CURRENT_USER\Software\LLVM\$(LLVM_VERSION)\`, `SrcRoot`)) $([MSBuild]::GetRegistryValueFromView(`HKEY_LOCAL_MACHINE\Software\LLVM\$(LLVM_VERSION)\`, `SrcRoot`, null, RegistryView.Registry64, RegistryView.Registry32)) $(LLVM_SRCROOT_DIR)\ $(LLVM_SRCROOT_DIR) $(MSBuildThisFileDirectory)Zelig\ZeligBuild $(MSBuildThisFileDirectory)Zelig\Zelig $([MSBuild]::GetRegistryValueFromView(`HKEY_LOCAL_MACHINE\Software\GnuWin32\`, `InstallPath`, null, RegistryView.Registry32)) $(GnuWin32MakeInstallPath)\ ================================================ FILE: LICENSE ================================================ LLILUM Copyright (c) Microsoft Corporation All rights reserved. MIT License Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the ""Software""), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED *AS IS*, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. ================================================ FILE: LlilumSDK/GenerateFrameworkList/App.config ================================================  ================================================ FILE: LlilumSDK/GenerateFrameworkList/GenerateFrameworkList.csproj ================================================  Debug AnyCPU {2C5BD91F-C52C-4E90-A290-CB7F0B55FB27} Exe Properties GenerateFrameworkList GenerateFrameworkList $(LlilumBuildRoot)\Host\obj\$(MSBuildProjectName)\ v4.5.2 512 true AnyCPU true full false $(LlilumBuildRoot)\Host\bin\$(Configuration)\ DEBUG;TRACE prompt 4 AnyCPU pdbonly true $(LlilumBuildRoot)\Host\bin\$(Configuration)\ TRACE prompt 4 ================================================ FILE: LlilumSDK/GenerateFrameworkList/Program.cs ================================================ using System; using System.IO; using System.Text; using System.Linq; using System.Xml.Linq; using System.Reflection; namespace GenerateFrameworkList { /// Build utility to generate the .NET Multitargeting Frameworklist.xml file from the WIX source /// /// The FrameworkList.xml file contains information about a framework and it's assemblies for the /// multi-targeting support in Visuals Studio and MSBuild. In particular it contains details of the /// assemblies as 'File' elements. Given that the WIX source already lists all the files to go into /// the MSI this tool saves on duplication of data (and the potential for errors) by generating the /// FrameworkList.xml from the wix source itself, thus acurately reflecting what is actually installed. /// This is not doen as an MSBuild task due to the fact that it needs to load the assemblies via /// reflection to determine the values of various attributes for the 'generated 'File' elements. Assemblies /// loaded via reflection are never unloaded unless the AppDomain they are loaded into is unloaded. Also, /// MSBuild uses an optimization that leaves an instance of istelf running under the expectation that, /// during a build, it will be needed again, thus eliminating the need to reload and re-jit everything. /// This means that the MSBuild task would load the assemblies and then linger around after the build is /// finished holding on to an open file for the loaded assemblies, causing weird issues with "File in use" /// types of errors. While it is plausible to write an MSBuild task to run it's core functionality in an /// isolated AppDomain, doing this as a seperate exe is simpler and more obvious. /// /// class Program { const string LlilumFrameworkDisplayName = "Llilum 1.0"; const string LlilumRedistComponentId = "Microsoft-Llilum-CLRCoreComp-1.0"; const string WixNamespace = "http://schemas.microsoft.com/wix/2006/wi"; private readonly static XName WixComponentGroupElementName = XName.Get("ComponentGroup", WixNamespace); private readonly static XName WixFileElementName = XName.Get("File", WixNamespace); /// Entry point for the application /// Input command line args /// 0 on success non zero on error /// /// Commandline args: /// /// Wix SourceWix fragment source file describing the framework assemblies component /// InputPathPath to use when finding the assemblies referenced in the Wix Source /// OutputPathPath write the generated FrameworkList.xml file into /// /// static int Main(string[] args) { string inputXml; string outputPath; string inputPath; if (!ValidateArgs( args, out inputXml, out inputPath, out outputPath )) { return -1; } using (var strm = File.OpenText(inputXml)) { var fileListElement = new XElement("FileList" , new XAttribute("Name", LlilumFrameworkDisplayName) , new XAttribute("Redist", LlilumRedistComponentId) , new XAttribute("ToolsVersion", "4.0") ); var outputDoc = new XDocument(new XDeclaration("1.0", "utf-8", "yes"), fileListElement); var inputDoc = XDocument.Load(strm); // find the files elements in the component group containing all the reference assemblies // only use files with the KeyPath == 'yes" as the others are the PDBs. var assemblyFiles = from componentGroup in inputDoc.Descendants(WixComponentGroupElementName) where componentGroup.Attribute("Id")?.Value == "ReferenceAssembliesComponentGroup" from file in componentGroup.Descendants(WixFileElementName) where file.Attribute("KeyPath")?.Value == "yes" select Path.Combine(inputPath, file.Attribute("Name").Value); foreach (var assemblyFile in assemblyFiles) { try { var assembly = Assembly.ReflectionOnlyLoadFrom(assemblyFile); AssemblyName name = assembly.GetName(); fileListElement.Add(new XElement("File" , new XAttribute("AssemblyName", name.Name) , new XAttribute("Version", name.Version.ToString()) , new XAttribute("PublicKeyToken", FormatPublicKeyToken(name)) , new XAttribute("Culture", name.CultureName) , new XAttribute("ProcessorArchitecture", name.ProcessorArchitecture.ToString()) , new XAttribute("InGac", "false") ) ); } catch( BadImageFormatException ) { /*ignore unmanaged binaries */ } catch( FileLoadException ) { /*ignore unloadeable binaries */ } } outputDoc.Save(Path.Combine(outputPath, "FrameworkList.xml")); } return 0; } private static string FormatPublicKeyToken(AssemblyName name) { var token = name.GetPublicKeyToken(); if (token == null || token.Length == 0) return string.Empty; var bldr = new StringBuilder(token.Length * 2); for (int i = 0; i < token.Length; i++) bldr.AppendFormat("{0:x2}", token[i]); return bldr.ToString(); } private static bool ValidateArgs(string[] args, out string inputWixFragment, out string inputPath, out string outputPath ) { if ( args.Length != 3) { Console.WriteLine("Incorrect number of arguments provided"); inputWixFragment = null; inputPath = null; outputPath = null; return false; } inputWixFragment = FixQuotedArg(args[0]); inputPath = FixQuotedArg(args[1]); outputPath = FixQuotedArg(args[2]); if (string.IsNullOrWhiteSpace(inputWixFragment)) { Console.Error.WriteLine("Empty strings for InputWixFragment are not allowed"); return false; } if (!File.Exists(inputWixFragment)) { Console.Error.WriteLine("File '{0}' specified in InputWixFragment does not exist", inputWixFragment); return false; } if (string.IsNullOrWhiteSpace(inputPath)) { Console.Error.WriteLine("Empty strings for InputPath are not allowed"); return false; } if (!Directory.Exists(inputPath)) { Console.Error.WriteLine("Directory '{0}' specified for InputPath does not exist", inputPath); return false; } if (string.IsNullOrWhiteSpace(outputPath)) { Console.Error.WriteLine("Empty strings for OutputPath are not allowed"); return false; } if (!Directory.Exists(args[1])) { Console.Error.WriteLine("Directory '{0}' specified for OutputPath does not exist", outputPath); return false; } return true; } private static string FixQuotedArg(string arg) { // .NET arg parsing has an unfortunate side effect for paths containing a trailing seperator. // On Windows when the arg is quoted (e.g. "c:\path\sub path\" ) the trailing \" is treated // as an escaped " character and the \ is lost. This fixes that case if (arg[arg.Length - 1] == '"') return arg.Substring(0, arg.Length - 1); else return arg; } } } ================================================ FILE: LlilumSDK/GenerateFrameworkList/Properties/AssemblyInfo.cs ================================================ using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; // General Information about an assembly is controlled through the following // set of attributes. Change these attribute values to modify the information // associated with an assembly. [assembly: AssemblyTitle("GenerateFrameworkList")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("GenerateFrameworkList")] [assembly: AssemblyCopyright("Copyright © 2016")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible(false)] // The following GUID is for the ID of the typelib if this project is exposed to COM [assembly: Guid("2c5bd91f-c52c-4e90-a290-cb7f0b55fb27")] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Build and Revision Numbers // by using the '*' as shown below: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("1.0.0.0")] [assembly: AssemblyFileVersion("1.0.0.0")] ================================================ FILE: LlilumSDK/LlilumSDK/BoardConfigurations.wxs ================================================ ================================================ FILE: LlilumSDK/LlilumSDK/Directories.wxs ================================================ ================================================ FILE: LlilumSDK/LlilumSDK/HarvestDirectories.targets ================================================ true true NativeOsLayerComponentGroup wix.LlilumZeligOsLayerDir INSTALLDIR NativeMbedLibComponentGroup wix.LlilumZeligMbedDir INSTALLDIR NativeMbedRtosComponentGroup wix.LlilumZeligMbedRtosDir INSTALLDIR NativelWipComponentGroup wix.LlilumZeligLwipDir INSTALLDIR ThirdPartyToolsComponentGroup wix.LlilumZeligToolsDir INSTALLDIR ZeligTestComponentGroup wix.LlilumZeligZeligTestDir INSTALLDIR CpsProjectSystemComponentGroup wix.LlilumApplicationTypeDir CpsApplicationTypeFolder MarkComponentsWin32.xslt true ================================================ FILE: LlilumSDK/LlilumSDK/LlilumSDK.wixproj ================================================  Debug x64 3.10 3aeaaaeb-954f-43c1-9b4b-9d2e29dcd0d7 2.0 LlilumSDK Package $(LLILUM_ROOT) $(LlilumBuildRoot)\Host\obj\$(MSBuildProjectName)\ $(MSBuildExtensionsPath32)\Microsoft\WiX\v3.x\Wix.targets $(MSBuildExtensionsPath)\Microsoft\WiX\v3.x\Wix.targets LlilumRoot=$(LlilumRoot) $(WixVariables);CpsBuildSourceDir=$(LlilumRoot)\VisualStudio\LlilumApplicationType $(WixVariables);LlilumTargetBuildOutput=$(LlilumRoot)\Zelig\ZeligBuild\Target\bin\$(Configuration) $(WixVariables);LlilumHostBuildOutput=$(LlilumRoot)\Zelig\ZeligBuild\Host\bin\$(Configuration) $(WixVariables);LlilumLlvmBin=$(LLILUM_LLVM)\build\x64\Release\bin true true $(LlilumRoot)\Zelig\os_layer $(WixVariables);LlilumZeligOsLayerDir=$(LlilumZeligOsLayerDir) $(LlilumRoot)\Zelig\mbed $(WixVariables);LlilumZeligMbedDir=$(LlilumZeligMbedDir) $(LlilumRoot)\Zelig\mbed-rtos $(WixVariables);LlilumZeligMbedRtosDir=$(LlilumZeligMbedRtosDir) $(LlilumRoot)\Zelig\lwip $(WixVariables);LlilumZeligLwipDir=$(LlilumZeligLwipDir) $(LlilumRoot)\Zelig\tools $(WixVariables);LlilumZeligToolsDir=$(LlilumZeligToolsDir) $(LlilumRoot)\Zelig\Zelig\test $(WixVariables);LlilumZeligZeligTestDir=$(LlilumZeligZeligTestDir) $(LlilumRoot)\VisualStudio\LlilumApplicationType $(WixVariables);LlilumApplicationTypeDir=$(LlilumApplicationTypeDir) LlilumSDK Debug;RegAndFolderShortVersionString=v1.0 $(WixVariables);WixUILicenseRtf=$(MSBuildThisFileDirectory)\LlilumSDKLic.rtf $(LlilumBuildRoot)\Host\bin\$(Configuration)\ RegAndFolderShortVersionString=v1.0 $(WixVariables);WixUILicenseRtf=$(MSBuildThisFileDirectory)\LlilumSDKLic.rtf $(LlilumBuildRoot)\Host\bin\$(Configuration)\ GenerateFrameworkList {2c5bd91f-c52c-4e90-a290-cb7f0b55fb27} True True Binaries;Content;Satellites INSTALLFOLDER $(WixExtDir)\WixVSExtension.dll WixVSExtension $(WixExtDir)\WixUIExtension.dll WixUIExtension Always "$(LlilumBuildRoot)\Host\bin\$(Configuration)\GenerateFrameworkList" "$(ProjectDir)\ReferenceAssemblies.wxs" "$(LlilumRoot)\Zelig\ZeligBuild\Target\bin\$(Configuration)" "$(ProjectDir)" ================================================ FILE: LlilumSDK/LlilumSDK/LlilumSDKLic.rtf ================================================ {\rtf1\ansi\ansicpg1252\deff0\nouicompat{\fonttbl{\f0\fnil\fcharset0 Calibri;}{\f1\fnil\fcharset0 Consolas;}{\f2\fnil Consolas;}{\f3\fnil\fcharset2 Symbol;}} {\colortbl ;\red0\green0\blue0;\red255\green255\blue255;\red0\green0\blue255;} {\*\generator Riched20 10.0.10587}\viewkind4\uc1 \pard\sa200\sl240\slmult1\b\f0\fs44\lang9 Welcome to Llilum 1.0\par \b0\fs22 Llilum is goverend by the MIT License\par (see full text below)\par \b\fs28 Additional components:\b0\fs22\par Llilum incorporates the following additional\par components goverend by their own terms:\par \pard{\pntext\f3\'B7\tab}{\*\pn\pnlvlblt\pnf3\pnindent0{\pntxtb\'B7}}\fi-360\li360\sa200\sl240\slmult1 LLVM libraries and tools\par \pard\sa200\sl240\slmult1 University of Illinois Open Source License (See full text below)\par \pard{\pntext\f3\'B7\tab}{\*\pn\pnlvlblt\pnf3\pnindent0{\pntxtb\'B7}}\fi-360\li360\sa200\sl240\slmult1 ARM mBed Headers and libraries\par \pard\sa200\sl240\slmult1 Apache 2.0 (See reference below)\par \pard{\pntext\f3\'B7\tab}{\*\pn\pnlvlblt\pnf3\pnindent0{\pntxtb\'B7}}\fi-360\li360\sa200\sl240\slmult1 LWIP netowrking stack\par \pard\sa200\sl240\slmult1 Swedish Institute of Computer Science Lic. (See full bext below)\par \pard{\pntext\f3\'B7\tab}{\*\pn\pnlvlblt\pnf3\pnindent0{\pntxtb\'B7}}\fi-360\li360\sa200\sl240\slmult1 pyOCD mbed CMSIS-DAP Debugger\par \pard\sa200\sl240\slmult1 Apache 2.0 (See reference Below)\par \pard\sa200\sl240\slmult1\cf1\highlight2\f1\fs19\lang1033 ---------------------------------------\f2\lang9\par \b\fs32 The MIT License (MIT)\par \b0\fs19 Copyright (c) 2015 Microsoft\par \par Permission is hereby granted, free of charge, to any person obtaining a copy\f1\lang1033 \f2\lang9 of this software and associated documentation files (the "Software"), to\f1\lang1033 \f2\lang9 deal\f1\lang1033 \f2\lang9 in the Software without restriction, including without limitation the rights\f1\lang1033 \f2\lang9 to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\f1\lang1033 \f2\lang9 copies of the Software, and to permit persons to whom the Software is\f1\lang1033 \f2\lang9 furnished to do so, subject to the following \f1\lang1033 c\f2\lang9 onditions:\par The above copyright notice and this permission notice shall be included in\f1\lang1033 \f2\lang9 all copies or substantial portions of the\f1\lang1033 \f2\lang9 Software.\par THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\f1\lang1033 \f2\lang9 IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\f1\lang1033 \f2\lang9 FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\f1\lang1033 \f2\lang9 AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\f1\lang1033 \f2\lang9 LIABILITY, WHETHER IN AN ACTION OF\f1\lang1033 \f2\lang9 CONTRACT, TORT OR OTHERWISE, ARISING\f1\lang1033 \f2\lang9 FROM,\f1\lang1033 \f2\lang9 OUT OF OR IN CONNECTION WITH THE\f1\lang1033 \f2\lang9 SOFTWARE OR THE USE OR OTHER DEALINGS IN\f1\lang1033 \f2\lang9 THE SOFTWARE.\par \f1\lang1033 ---------------------------------------\cf0\highlight0\f0\fs22\lang9\par ==============================================================\par LLVM Release License\par ==============================================================\par University of Illinois/NCSA\par Open Source License\par Copyright (c) 2003-2015 University of Illinois at Urbana-Champaign.\par All rights reserved.\par \par Developed by:\par LLVM Team\par University of Illinois at Urbana-Champaign\par {{\field{\*\fldinst{HYPERLINK http://llvm.org }}{\fldrslt{http://llvm.org\ul0\cf0}}}}\f0\fs22\par \par Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal with 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:\par \pard{\pntext\f3\'B7\tab}{\*\pn\pnlvlblt\pnf3\pnindent0{\pntxtb\'B7}}\fi-360\li720\sa200\sl240\slmult1 Redistributions of source code must retain the above copyright notice,this list of conditions and the following disclaimers.\par {\pntext\f3\'B7\tab}Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimers in the documentation and/or other materials provided with the distribution.\par {\pntext\f3\'B7\tab}Neither the names of the LLVM Team, University of Illinois at Urbana-Champaign, nor the names of its contributors may be used to endorse or promote products derived from this Software without specific prior written permission.\par \pard\sa200\sl240\slmult1 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 CONTRIBUTORS 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 WITH THE SOFTWARE.\par ==============================================================\par Copyrights and Licenses for Third Party Software Distributed with LLVM:\par ==============================================================\par The LLVM software contains code written by third parties. Such software will have its own individual LICENSE.TXT file in the directory in which it appears. This file will describe the copyrights, license, and restrictions which apply to that code.\par The disclaimer of warranty in the University of Illinois Open Source License applies to all code in the LLVM Distribution, and nothing in any of the other licenses gives permission to use the names of the LLVM Team or the University of Illinois to endorse or promote products derived from this Software.\par The following pieces of software have additional or alternate copyrights, licenses, and/or restrictions:\par \ul Program Directory\par \ulnone Autoconf llvm/autoconf\par llvm/projects/ModuleMaker/autoconf\par Google Test llvm/utils/unittest/googletest\par OpenBSD regex llvm/lib/Support/\{reg*, COPYRIGHT.regex\}\par pyyaml tests llvm/test/YAMLParser/\{*.data, LICENSE.TXT\}\par ARM contributions llvm/lib/Target/ARM/LICENSE.TXT\par md5 contributions llvm/lib/Support/MD5.cpp llvm/include/llvm/Support/MD5.h\par \cf1\highlight2\f1\fs19\lang1033 ---------------------------------------\cf0\highlight0\f0\fs22\lang9\par LwIP License\par Copyright (c) 2001, 2002 Swedish Institute of Computer Science.\par All rights reserved. \par Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:\par 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. \par 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.\par 3. The name of the author may not be used to endorse or promote products derived from this software without specific prior written permission. \par THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\par \cf1\highlight2\f1\fs19\lang1033 ---------------------------------------\par mbed Microcontroller Library\par Copyright (c) 2006-2013 ARM Limited\par 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\par {\cf0{\field{\*\fldinst{HYPERLINK http://www.apache.org/licenses/LICENSE-2.0 }}{\fldrslt{http://www.apache.org/licenses/LICENSE-2.0\ul0\cf0}}}}\f1\fs19\par 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. \par ---------------------------------------\par mbed CMSIS-DAP debugger\par Copyright (c) 2015 ARM Limited\par 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\par {{\field{\*\fldinst{HYPERLINK http://www.apache.org/licenses/LICENSE-2.0 }}{\fldrslt{http://www.apache.org/licenses/LICENSE-2.0\ul0\cf0}}}}\f1\fs19\par 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.\cf0\highlight0\f0\fs22\lang9\par \cf1\highlight2\f1\fs19\lang1033 ---------------------------------------\par \cf0\highlight0\f0\fs22\lang9\par \par \par \par } ================================================ FILE: LlilumSDK/LlilumSDK/LlvmTools.wxs ================================================ ================================================ FILE: LlilumSDK/LlilumSDK/MarkComponentsWin32.xslt ================================================  no ================================================ FILE: LlilumSDK/LlilumSDK/PreConditions.wxi ================================================ Installed OR VS2015_COMMUNITY_EDITION_INSTALLED OR VS2015_PROFESSIONAL_EDITION_INSTALLED OR VS2015_PREMIUM_EDITION_INSTALLED OR VS2015_ENTERPRISE_EDITION_INSTALLED Installed OR VS2015_IDE_VCSHARP_PROJECTSYSTEM_INSTALLED Installed OR VS2015_IDE_VC_PROJECTSYSTEM_INSTALLED Installed OR VS2015_VC_CROSS_PLATFORM_MOBILE_TOOLS_INSTALLED Installed OR EMBEDDED_GCC_INSTALLED ================================================ FILE: LlilumSDK/LlilumSDK/Product.wxs ================================================ ================================================ FILE: LlilumSDK/LlilumSDK/ReferenceAssemblies.wxs ================================================ ================================================ FILE: LlilumSDK/LlilumSDK/ToolsBin.wxs ================================================  ================================================ FILE: LlilumSDK/LlilumSDK.sln ================================================  Microsoft Visual Studio Solution File, Format Version 12.00 # Visual Studio 14 VisualStudioVersion = 14.0.24720.0 MinimumVisualStudioVersion = 10.0.40219.1 Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "GenerateFrameworkList", "GenerateFrameworkList\GenerateFrameworkList.csproj", "{2C5BD91F-C52C-4E90-A290-CB7F0B55FB27}" EndProject Project("{930C7802-8A8C-48F9-8165-68863BCCD9DD}") = "LlilumSDK", "LlilumSDK\LlilumSDK.wixproj", "{3AEAAAEB-954F-43C1-9B4B-9D2E29DCD0D7}" EndProject Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "Solution Items", "Solution Items", "{88A50C99-9B62-4F44-B515-B0E15F80E9A7}" ProjectSection(SolutionItems) = preProject readme.md = readme.md EndProjectSection EndProject Global GlobalSection(SolutionConfigurationPlatforms) = preSolution Debug|Any CPU = Debug|Any CPU Debug|x64 = Debug|x64 Release|Any CPU = Release|Any CPU Release|x64 = Release|x64 EndGlobalSection GlobalSection(ProjectConfigurationPlatforms) = postSolution {2C5BD91F-C52C-4E90-A290-CB7F0B55FB27}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {2C5BD91F-C52C-4E90-A290-CB7F0B55FB27}.Debug|Any CPU.Build.0 = Debug|Any CPU {2C5BD91F-C52C-4E90-A290-CB7F0B55FB27}.Debug|x64.ActiveCfg = Debug|Any CPU {2C5BD91F-C52C-4E90-A290-CB7F0B55FB27}.Debug|x64.Build.0 = Debug|Any CPU {2C5BD91F-C52C-4E90-A290-CB7F0B55FB27}.Release|Any CPU.ActiveCfg = Release|Any CPU {2C5BD91F-C52C-4E90-A290-CB7F0B55FB27}.Release|Any CPU.Build.0 = Release|Any CPU {2C5BD91F-C52C-4E90-A290-CB7F0B55FB27}.Release|x64.ActiveCfg = Release|Any CPU {2C5BD91F-C52C-4E90-A290-CB7F0B55FB27}.Release|x64.Build.0 = Release|Any CPU {3AEAAAEB-954F-43C1-9B4B-9D2E29DCD0D7}.Debug|Any CPU.ActiveCfg = Debug|x64 {3AEAAAEB-954F-43C1-9B4B-9D2E29DCD0D7}.Debug|x64.ActiveCfg = Debug|x64 {3AEAAAEB-954F-43C1-9B4B-9D2E29DCD0D7}.Debug|x64.Build.0 = Debug|x64 {3AEAAAEB-954F-43C1-9B4B-9D2E29DCD0D7}.Release|Any CPU.ActiveCfg = Release|x64 {3AEAAAEB-954F-43C1-9B4B-9D2E29DCD0D7}.Release|x64.ActiveCfg = Release|x64 {3AEAAAEB-954F-43C1-9B4B-9D2E29DCD0D7}.Release|x64.Build.0 = Release|x64 EndGlobalSection GlobalSection(SolutionProperties) = preSolution HideSolutionNode = FALSE EndGlobalSection EndGlobal ================================================ FILE: LlilumSDK/readme.md ================================================ ### Llilum SDK Installer This folder contains the Solution for building the Llilum SDK MSI installer. ##### Prerequisites The installer is built using the [Windows Installer XML (Wix) v3.10.2](https://wix.codeplex.com/downloads/get/1540240) #### Building the Binaries that go into the SDK The SDK will incorporate the binareis built by other projects in the build. While it might make sense to define dependencies in the solution on those projects so that a single project builds everything - that doesn't really work for automated builds with digital signatures for a final production release. The binaries in the MSI must all get a proper digital signature and or strong name signed before they are bound into the MSI. After that the MSI is generated a signature is generated for the MSI itself. Thus keeping the MSI build isolated helps in managing the multi-stage process of creating a fully signed release build. The Following solutions and projects must be built to provide the input binaries for the SDK MSI: 1. Zelig.sln solution 2. BoardConfigurations.sln solution ###### Note: In the future the output of the board configurations solution will not go into the SDK itself, rather it will convert to a sample project that **uses** the SDK to create Board Support packages. This would include bundling the output of the build to a NUGET package to make adding a BSP to a project a simple act of adding a NUGET pacakge. This requires re-working the native project system to move the board selection and related properties out of the built in build infrastructure. We haven't quite made it that far so, for the short term the SDK includes the board configurations built in the Llilum core team. #### Building the MSI You need to install the Wix Toolset before you can build this solution. Once you have installed the Wix Toolset follow these simple steps: 1. Open the LlilumSDK.sln solution file 2. Select **Build | Build Solution** 3. The MSI will be gnerated into the ZeligBuild\Host\bin\$(Configuration) folder #### Using the SDK In order to use the SDK you must install the following: 1. The MSI 2. The VSIX package for the Llilum project system. 3. The ARM GCC compiler (Assuming you are targeting Cortex-M class devices) 4. Appropriate Debugger components (pyOCD, OpenOCD, mBed Serial Drivers, etc...) Once you have installed these you can open Visual Studio and create a new LlilumApplication and code away... ###### NOTE: The SDK and VSIX package are not bundled together to allow for faster and simpler updates as well as to keep the SDK from becoming bound to a specific version of Visual Studio. The release cadence of VS has increased dramatically and maintaining multiple variants of the SDK for each VS version is logistically challenging and distracting. At best we could add a bootstrapper executable that installed the MSI, then detected VS installations and downloaded the appropriate VSIX pacakges. That is a significant amount of work as the bootstrapper would require a fairly high degree of future proofing to ensure it could detect future Visual Studio installations, AND find an appropriate VSIX package to go with it. Ideally that would *not* require creating a new web service to provide information to the bootstrapper. (Although leveraging the public readable nature of Github over HTTPS, it could use a data file pushed on GitHub to pull down and use to extract information) None of that is particularly deeply thought out or considered for active development yet. ================================================ FILE: LlvmApplication.props ================================================ 3.8.1 $([MSBuild]::GetRegistryValue(`HKEY_CURRENT_USER\Software\LLVM\$(LLVM_VERSION)\`, `SrcRoot`)) $(LLVM_SRCROOT_DIR)\ $(LLVM_SRCROOT_DIR)Build\ $(LLVM_BUILD_DIR)\ $(LLVM_SRCROOT_DIR)Include $(LLVM_BUILD_DIR)$(Platform)\ $(LLVM_PLATFORM_DIR)$(Configuration)\ $(LLVM_PLATFORM_DIR)Include\ $(LLVM_CONFIG_DIR)bin\ $(LLVM_CONFIG_DIR)lib\ @(AllLlvmLibs) $(LLVM_CONFIG_INCLUDE);$(LLVM_INCLUDE);%(AdditionalIncludeDirectories) 4267;4244;4800;4291;4996 $(AllLlvmStaticLibs);$(AdditionalDependencies) ================================================ FILE: README.md ================================================ Welcome to LLILUM! ================== A development platform for IL based languages and UWP applications targeting Cortex-M processors. ## Why LLILUM Cortex-M processors are heavily resource constrained, and yet, because of their low power consumption and optimized interrupt dispatching, are arguably the most suitable solution for IoT applications. Existing development platfoms and tool chains that target this space are based on C/C++, and no native support for higher level languages and RAD environment exist that can take advantage of what a Cortex-M HW can offer. Previous efforts in this space include [.NET Micro Framework](https://github.com/NETMF/netmf-interpreter) and other Java solutions, which are sometimes too large in code size, too slow or too difficult to extend for mainstream adoption. LLILUM implements a scalable alternative to C/C++ that features comparable code size and speed, as well as easy extensibility from within the Visual Studio development tool chain. ## What is LLILUM LLILUM is an optimizing compiler tool chain based on the latest [CLI](http://www.ecma-international.org/publications/standards/Ecma-335.htm) standard and [LLVM](http://llvm.org/) version [3.8.1](http://llvm.org/releases/download.html#3.8.1). LLILUM relies on the compelling development experience of Visual Studio to transform source code into MSIL, and then into an intermediate represenation (IR) that is optmized for size and speed, taking into account the target platform constraints, such as memory layout, native ISA, calling convention, and, first and foremost, the application requirements. The method and type closure is optimized based on application usage of system facilities, and the type system is morphed to shrink into the smallest possible footprint. Debugging is carried out through Visual Studio and GDB. Standard features of CLI environments, e.g. type system (TS) introspection, garbage collection (GC) and a full featured multi-threaded execution engine (MTEE) are provided. # State of the Art LLILUM can generate runnable images for ARMv4 and ARMv5 ISA, with partial FP support. We could have extended the code generator to support ARMv7-M but we decided to leverage LLVM instead, hoping we can get a wider set of targets over time. The current incarnation of the system successfully uses LLVM to target: * Cortex-M0/3/4 ISA with * A fully functional Managed Type System and FP support * A reference counting collector * A conservative tracing collector (Bohem GC) * A fully multi-threaded execution environment compatible with Cortex-M architecture for `NVIC` and `SysTick` standard controllers * [lwIP](http://savannah.nongnu.org/projects/lwip/) TCP/IP stack * [CMSIS-RTOS](http://www.keil.com/pack/doc/cmsis/RTOS/html/index.html) porting layer for easy network stack porting * Visual Studio SDK with GDB debugging # Supported Hardware LLILUM supports a significant number of development boards from the [mBed](https://www.mbed.com/en/) ecosystem, and specifically: * [Freescale K64F-FRDM](https://developer.mbed.org/platforms/FRDM-K64F/) Cortex-M4 development board * [NXP LPC1768](https://developer.mbed.org/platforms/mbed-LPC1768/) Cortex-M3 development board * [STMicroelectronics STM32F091RC](https://developer.mbed.org/platforms/ST-Nucleo-F091RC/) Cortex-M0 development board * [STMicroelectronics STM32F401RE](https://developer.mbed.org/platforms/ST-Nucleo-F401RE/) Cortex-M3 development board * [STMicroelectronics STM32F411RE](https://developer.mbed.org/platforms/ST-Nucleo-F411RE/) Cortex-M4 development board * [STMicroelectronics STM32L152RE](https://developer.mbed.org/platforms/ST-Nucleo-L152RE/) Cortex-M3 development board # Supported Languages Currrent target language is C#; extensions to Python and possibly TypeScript are in the works. We are also targeting [UWP](https://msdn.microsoft.com/en-us/library/dn894631.aspx) app development, so that it will be possible to share code between a Windows 10 device app and a Cortex-M micro processor. Welcome to OneCore! # Further reading Please see the following documents in our wiki: Welcome to the _llilum_ wiki! 1. [Detailed system description](https://github.com/NETMF/llilum-pr/wiki/System) 1. [Build System](https://github.com/NETMF/llilum-pr/wiki/Building) 2. [Front End Configuration](https://github.com/NETMF/llilum-pr/wiki/LLILUM-Compiler-Frontend) 2. [Setup and build instruction](https://github.com/NETMF/llilum-pr/wiki/Setup) 3. [Build and run test demo](https://github.com/NETMF/llilum-pr/wiki/Demo) 4. [Performance considerations](https://github.com/NETMF/llilum-pr/wiki/Performance-Considerations) 5. [Next steps](https://github.com/NETMF/llilum-pr/wiki/Prototype-Roadmap) # Acknowledgments A big thanks to Miguel Perez Martinez for helping bringing up this proof of concepts with exceptional dedication, perseverance and competency. An even bigger thanks to D.M., who created the vast majority of this codebase single-handedly. ================================================ FILE: SDKHelpers/RunLillium.cmd ================================================ %LLILUM_ROOT%ZeligBuild\Host\bin\Debug\Microsoft.Zelig.Compiler.exe -cfg %LLILUM_ROOT%mbed_simple_LPC1768.FrontEndConfig .\ZeligBuild\Target\bin\Debug\Microsoft.Zelig.Test.mbed.Simple.exe -OutputName Microsoft.Zelig.Test.mbed.Simple -OutputDir output ================================================ FILE: SDKHelpers/output/CompileAndLink.bat ================================================ @echo off IF %1.==. ( ECHO No target passed in. Defaulting to LPC1768 set TARGET=LPC1768 ) ELSE ( ECHO Detected target: %1 set TARGET=%1 ) ECHO. ECHO Linking with mbed libs... make clean TARGET=%TARGET% make TARGET=%TARGET% GOTO :EXIT :EXIT ECHO. ECHO Completed ================================================ FILE: SDKHelpers/output/RunLLVM.bat ================================================ @echo off IF /i "%LLVM_BIN%"=="" ( ECHO LLVM_BIN is not defined. Please define LLVM_BIN to point to LLVM tools and binaries. GOTO :EXIT ) IF /i "%GCC_BIN%"=="" ( ECHO GCC_BIN is not defined. Please define GCC_BIN to point to LLVM tools and binaries. GOTO :EXIT ) ECHO Running LLVM Optimization Phases... ::%LLVM_BIN%\opt -O2 -adce -globaldce Microsoft.Zelig.Test.mbed.Simple.bc -o Microsoft.Zelig.Test.mbed.Simple_opt.bc ::%LLVM_BIN%\opt -O1 -globalopt -constmerge -adce -globaldce -time-passes Microsoft.Zelig.Test.mbed.Simple.bc -o Microsoft.Zelig.Test.mbed.Simple_opt.bc %LLVM_BIN%\opt -scalarrepl -targetlibinfo -verify -mem2reg -constmerge -adce -globaldce -time-passes Microsoft.Zelig.Test.mbed.Simple.bc -o Microsoft.Zelig.Test.mbed.Simple_opt.bc ::copy Microsoft.Zelig.Test.mbed.Simple.bc Microsoft.Zelig.Test.mbed.Simple_opt.bc ::%LLVM_BIN%\llvm-bcanalyzer Microsoft.Zelig.Test.mbed.Simple_opt.bc %LLVM_BIN%\llvm-dis Microsoft.Zelig.Test.mbed.Simple_opt.bc ECHO Compiling to ARM... %LLVM_BIN%\llc -code-model=small -data-sections -relocation-model=pic -march=thumb -mcpu=cortex-m3 -filetype=obj -mtriple=Thumb-NoSubArch-UnknownVendor-UnknownOS-GNUEABI-ELF -o=Microsoft.Zelig.Test.mbed.Simple_opt.o Microsoft.Zelig.Test.mbed.Simple_opt.bc ECHO Size Report... %GCC_BIN%\arm-none-eabi-size.exe Microsoft.Zelig.Test.mbed.Simple_opt.o :EXIT ECHO. ECHO Completed ================================================ FILE: SDKHelpers/output/makefile ================================================ # # Project-specific settings # VERBOSE=1 PROJECT = mbed_simple OBJECTS = .\Microsoft.Zelig.Test.mbed.Simple_opt.o $(TARGET)\temporary_helper.o # # Paths and includes # TODO: Make this algorithmic based on TARGET. # ifndef TARGET $(error TARGET is undefined. Pass in TARGET for desired board) endif ifeq ($(HARDFP),1) FLOAT_ABI = hard else FLOAT_ABI = softfp endif # Common settings GCC_BIN = ..\ARM_GCC\4.9\bin\\ MBED_ROOT = ..\mbed LIBRARIES = -lmbed LD_SYS_LIBS = -lstdc++ -lsupc++ -lm -lc -lgcc -lnosys # LPC1768 settings ifeq ($(TARGET),LPC1768) SYS_OBJECTS = $(MBED_ROOT)\TARGET_LPC1768\TOOLCHAIN_GCC_ARM\board.o $(MBED_ROOT)\TARGET_LPC1768\TOOLCHAIN_GCC_ARM\startup_LPC17xx.o $(MBED_ROOT)\TARGET_LPC1768\TOOLCHAIN_GCC_ARM\cmsis_nvic.o $(MBED_ROOT)\TARGET_LPC1768\TOOLCHAIN_GCC_ARM\retarget.o $(MBED_ROOT)\TARGET_LPC1768\TOOLCHAIN_GCC_ARM\system_LPC17xx.o INCLUDE_PATHS = -I. -I$(MBED_ROOT) -I$(MBED_ROOT)\TARGET_LPC1768 -I$(MBED_ROOT)\TARGET_LPC1768\TOOLCHAIN_GCC_ARM -I$(MBED_ROOT)\TARGET_LPC1768\TARGET_NXP -I$(MBED_ROOT)\TARGET_LPC1768\TARGET_NXP\TARGET_LPC176X -I$(MBED_ROOT)\TARGET_LPC1768\TARGET_NXP\TARGET_LPC176X\TARGET_MBED_LPC1768 LIBRARY_PATHS = -L$(MBED_ROOT)\TARGET_LPC1768\TOOLCHAIN_GCC_ARM LINKER_SCRIPT = $(MBED_ROOT)\TARGET_LPC1768\TOOLCHAIN_GCC_ARM\LPC1768.ld # Build flags CPU = -mcpu=cortex-m3 -mthumb CC_FLAGS = $(CPU) -c -g -fno-common -fmessage-length=0 -Wall -fno-exceptions -ffunction-sections -fdata-sections -fomit-frame-pointer -MMD -MP CC_SYMBOLS = -DTARGET_LPC1768 -DTARGET_M3 -DTARGET_CORTEX_M -DTARGET_NXP -DTARGET_LPC176X -DTARGET_MBED_LPC1768 -DTOOLCHAIN_GCC_ARM -DTOOLCHAIN_GCC -D__CORTEX_M3 -DARM_MATH_CM3 -DMBED_BUILD_TIMESTAMP=1435185689.48 -D__MBED__=1 LD_FLAGS = $(CPU) -Wl,--gc-sections --specs=nano.specs -u _printf_float -u _scanf_float -Wl,--wrap,main -Wl,-Map=$(TARGET)\$(PROJECT).map,--cref # K64F settings else ifeq ($(TARGET),K64F) SYS_OBJECTS = $(MBED_ROOT)/TARGET_K64F/TOOLCHAIN_GCC_ARM/mbed_overrides.o $(MBED_ROOT)/TARGET_K64F/TOOLCHAIN_GCC_ARM/system_MK64F12.o $(MBED_ROOT)/TARGET_K64F/TOOLCHAIN_GCC_ARM/startup_MK64F12.o $(MBED_ROOT)/TARGET_K64F/TOOLCHAIN_GCC_ARM/board.o $(MBED_ROOT)/TARGET_K64F/TOOLCHAIN_GCC_ARM/cmsis_nvic.o $(MBED_ROOT)/TARGET_K64F/TOOLCHAIN_GCC_ARM/retarget.o INCLUDE_PATHS = -I. -I$(MBED_ROOT) -I$(MBED_ROOT)/TARGET_K64F -I$(MBED_ROOT)/TARGET_K64F/TOOLCHAIN_GCC_ARM -I$(MBED_ROOT)/TARGET_K64F/TARGET_Freescale -I$(MBED_ROOT)/TARGET_K64F/TARGET_Freescale/TARGET_KPSDK_MCUS -I$(MBED_ROOT)/TARGET_K64F/TARGET_Freescale/TARGET_KPSDK_MCUS/TARGET_MCU_K64F -I$(MBED_ROOT)/TARGET_K64F/TARGET_Freescale/TARGET_KPSDK_MCUS/TARGET_MCU_K64F/MK64F12 -I$(MBED_ROOT)/TARGET_K64F/TARGET_Freescale/TARGET_KPSDK_MCUS/TARGET_MCU_K64F/device -I$(MBED_ROOT)/TARGET_K64F/TARGET_Freescale/TARGET_KPSDK_MCUS/TARGET_MCU_K64F/device/MK64F12 -I$(MBED_ROOT)/TARGET_K64F/TARGET_Freescale/TARGET_KPSDK_MCUS/TARGET_MCU_K64F/device/device -I$(MBED_ROOT)/TARGET_K64F/TARGET_Freescale/TARGET_KPSDK_MCUS/TARGET_MCU_K64F/device/device/MK64F12 -I$(MBED_ROOT)/TARGET_K64F/TARGET_Freescale/TARGET_KPSDK_MCUS/TARGET_MCU_K64F/TARGET_FRDM -I$(MBED_ROOT)/TARGET_K64F/TARGET_Freescale/TARGET_KPSDK_MCUS/TARGET_KPSDK_CODE -I$(MBED_ROOT)/TARGET_K64F/TARGET_Freescale/TARGET_KPSDK_MCUS/TARGET_KPSDK_CODE/common -I$(MBED_ROOT)/TARGET_K64F/TARGET_Freescale/TARGET_KPSDK_MCUS/TARGET_KPSDK_CODE/common/phyksz8081 -I$(MBED_ROOT)/TARGET_K64F/TARGET_Freescale/TARGET_KPSDK_MCUS/TARGET_KPSDK_CODE/hal -I$(MBED_ROOT)/TARGET_K64F/TARGET_Freescale/TARGET_KPSDK_MCUS/TARGET_KPSDK_CODE/hal/lptmr -I$(MBED_ROOT)/TARGET_K64F/TARGET_Freescale/TARGET_KPSDK_MCUS/TARGET_KPSDK_CODE/hal/dac -I$(MBED_ROOT)/TARGET_K64F/TARGET_Freescale/TARGET_KPSDK_MCUS/TARGET_KPSDK_CODE/hal/gpio -I$(MBED_ROOT)/TARGET_K64F/TARGET_Freescale/TARGET_KPSDK_MCUS/TARGET_KPSDK_CODE/hal/port -I$(MBED_ROOT)/TARGET_K64F/TARGET_Freescale/TARGET_KPSDK_MCUS/TARGET_KPSDK_CODE/hal/llwu -I$(MBED_ROOT)/TARGET_K64F/TARGET_Freescale/TARGET_KPSDK_MCUS/TARGET_KPSDK_CODE/hal/sim -I$(MBED_ROOT)/TARGET_K64F/TARGET_Freescale/TARGET_KPSDK_MCUS/TARGET_KPSDK_CODE/hal/rcm -I$(MBED_ROOT)/TARGET_K64F/TARGET_Freescale/TARGET_KPSDK_MCUS/TARGET_KPSDK_CODE/hal/sdhc -I$(MBED_ROOT)/TARGET_K64F/TARGET_Freescale/TARGET_KPSDK_MCUS/TARGET_KPSDK_CODE/hal/can -I$(MBED_ROOT)/TARGET_K64F/TARGET_Freescale/TARGET_KPSDK_MCUS/TARGET_KPSDK_CODE/hal/mpu -I$(MBED_ROOT)/TARGET_K64F/TARGET_Freescale/TARGET_KPSDK_MCUS/TARGET_KPSDK_CODE/hal/smc -I$(MBED_ROOT)/TARGET_K64F/TARGET_Freescale/TARGET_KPSDK_MCUS/TARGET_KPSDK_CODE/hal/osc -I$(MBED_ROOT)/TARGET_K64F/TARGET_Freescale/TARGET_KPSDK_MCUS/TARGET_KPSDK_CODE/hal/flextimer -I$(MBED_ROOT)/TARGET_K64F/TARGET_Freescale/TARGET_KPSDK_MCUS/TARGET_KPSDK_CODE/hal/pdb -I$(MBED_ROOT)/TARGET_K64F/TARGET_Freescale/TARGET_KPSDK_MCUS/TARGET_KPSDK_CODE/hal/enet -I$(MBED_ROOT)/TARGET_K64F/TARGET_Freescale/TARGET_KPSDK_MCUS/TARGET_KPSDK_CODE/hal/i2c -I$(MBED_ROOT)/TARGET_K64F/TARGET_Freescale/TARGET_KPSDK_MCUS/TARGET_KPSDK_CODE/hal/uart -I$(MBED_ROOT)/TARGET_K64F/TARGET_Freescale/TARGET_KPSDK_MCUS/TARGET_KPSDK_CODE/hal/dspi -I$(MBED_ROOT)/TARGET_K64F/TARGET_Freescale/TARGET_KPSDK_MCUS/TARGET_KPSDK_CODE/hal/pit -I$(MBED_ROOT)/TARGET_K64F/TARGET_Freescale/TARGET_KPSDK_MCUS/TARGET_KPSDK_CODE/hal/lpuart -I$(MBED_ROOT)/TARGET_K64F/TARGET_Freescale/TARGET_KPSDK_MCUS/TARGET_KPSDK_CODE/hal/sai -I$(MBED_ROOT)/TARGET_K64F/TARGET_Freescale/TARGET_KPSDK_MCUS/TARGET_KPSDK_CODE/hal/rtc -I$(MBED_ROOT)/TARGET_K64F/TARGET_Freescale/TARGET_KPSDK_MCUS/TARGET_KPSDK_CODE/hal/mcg -I$(MBED_ROOT)/TARGET_K64F/TARGET_Freescale/TARGET_KPSDK_MCUS/TARGET_KPSDK_CODE/hal/edma -I$(MBED_ROOT)/TARGET_K64F/TARGET_Freescale/TARGET_KPSDK_MCUS/TARGET_KPSDK_CODE/hal/pmc -I$(MBED_ROOT)/TARGET_K64F/TARGET_Freescale/TARGET_KPSDK_MCUS/TARGET_KPSDK_CODE/hal/adc -I$(MBED_ROOT)/TARGET_K64F/TARGET_Freescale/TARGET_KPSDK_MCUS/TARGET_KPSDK_CODE/hal/wdog -I$(MBED_ROOT)/TARGET_K64F/TARGET_Freescale/TARGET_KPSDK_MCUS/TARGET_KPSDK_CODE/hal/dmamux -I$(MBED_ROOT)/TARGET_K64F/TARGET_Freescale/TARGET_KPSDK_MCUS/TARGET_KPSDK_CODE/utilities -I$(MBED_ROOT)/TARGET_K64F/TARGET_Freescale/TARGET_KPSDK_MCUS/TARGET_KPSDK_CODE/drivers -I$(MBED_ROOT)/TARGET_K64F/TARGET_Freescale/TARGET_KPSDK_MCUS/TARGET_KPSDK_CODE/drivers/enet -I$(MBED_ROOT)/TARGET_K64F/TARGET_Freescale/TARGET_KPSDK_MCUS/TARGET_KPSDK_CODE/drivers/pit -I$(MBED_ROOT)/TARGET_K64F/TARGET_Freescale/TARGET_KPSDK_MCUS/TARGET_KPSDK_CODE/drivers/pit/common -I$(MBED_ROOT)/TARGET_K64F/TARGET_Freescale/TARGET_KPSDK_MCUS/TARGET_KPSDK_CODE/drivers/interrupt -I$(MBED_ROOT)/TARGET_K64F/TARGET_Freescale/TARGET_KPSDK_MCUS/TARGET_KPSDK_CODE/drivers/clock LIBRARY_PATHS = -L$(MBED_ROOT)/TARGET_K64F/TOOLCHAIN_GCC_ARM LINKER_SCRIPT = $(MBED_ROOT)/TARGET_K64F/TOOLCHAIN_GCC_ARM/K64FN1M0xxx12.ld # Build flags CPU = -mcpu=cortex-m4 -mthumb -mfpu=fpv4-sp-d16 -mfloat-abi=$(FLOAT_ABI) CC_FLAGS = $(CPU) -c -g -fno-common -fmessage-length=0 -Wall -fno-exceptions -ffunction-sections -fdata-sections -fomit-frame-pointer -MMD -MP CC_SYMBOLS = -DTARGET_K64F -DTARGET_M4 -DTARGET_CORTEX_M -DTARGET_Freescale -DTARGET_KPSDK_MCUS -DTARGET_KPSDK_CODE -DTARGET_MCU_K64F -DTARGET_FRDM -DTOOLCHAIN_GCC_ARM -DTOOLCHAIN_GCC -D__CORTEX_M4 -DARM_MATH_CM4 -D__FPU_PRESENT=1 -DMBED_BUILD_TIMESTAMP=1435855534.71 -D__MBED__=1 -DCPU_MK64FN1M0VMD12 -DFSL_RTOS_MBED -DTARGET_FF_ARDUINO LD_FLAGS = $(CPU) -Wl,--gc-sections --specs=nano.specs -u _printf_float -u _scanf_float -Wl,--wrap,main -Wl,-Map=$(TARGET)\$(PROJECT).map,--cref else $(error TARGET is not recognized. Please check the value passed in) endif DEPS = $(OBJECTS:.o=.d) # # Build tools # AS = "$(GCC_BIN)arm-none-eabi-as" CC = "$(GCC_BIN)arm-none-eabi-gcc" CPP = "$(GCC_BIN)arm-none-eabi-g++" LD = "$(GCC_BIN)arm-none-eabi-gcc" OBJCOPY = "$(GCC_BIN)arm-none-eabi-objcopy" OBJDUMP = "$(GCC_BIN)arm-none-eabi-objdump" SIZE = "$(GCC_BIN)arm-none-eabi-size" ifeq ($(DEBUG), 1) CC_FLAGS += -DDEBUG -O0 else CC_FLAGS += -DNDEBUG -Os endif # # Recipes # .PHONY: all clean lst size all: ${TARGET} $(TARGET)\$(PROJECT).bin $(TARGET)\$(PROJECT).hex $(TARGET)\$(PROJECT).lst $(TARGET)\$(PROJECT).disasm size # Conditionals (ifeq/ifneq) are bugged on Windows. Instead, we'll just ensure the directory exists and remove it unconditionally. clean: ${TARGET} @rmdir /q /s $(TARGET) # Ensures the target directory has been created. ${TARGET}: @mkdir $@ $(TARGET)\\%.o: %.s $(AS) $(CPU) -o $@ $< $(TARGET)\\%.o: %.c $(CC) $(CC_FLAGS) $(CC_SYMBOLS) -std=gnu99 $(INCLUDE_PATHS) -o $@ $< $(TARGET)\\%.o: %.cpp $(CPP) $(CC_FLAGS) $(CC_SYMBOLS) -std=gnu++98 -fno-rtti $(INCLUDE_PATHS) -o $@ $< $(TARGET)\$(PROJECT).elf: $(OBJECTS) $(SYS_OBJECTS) $(LD) $(LD_FLAGS) -T$(LINKER_SCRIPT) $(LIBRARY_PATHS) -o $@ $^ $(LIBRARIES) $(LD_SYS_LIBS) $(LIBRARIES) $(LD_SYS_LIBS) $(TARGET)\$(PROJECT).bin: $(TARGET)\$(PROJECT).elf $(OBJCOPY) -O binary $< $@ $(TARGET)\$(PROJECT).hex: $(TARGET)\$(PROJECT).elf @$(OBJCOPY) -O ihex $< $@ $(TARGET)\$(PROJECT).lst: $(TARGET)\$(PROJECT).elf @$(OBJDUMP) -Sdh $< > $@ $(TARGET)\$(PROJECT).disasm: $(TARGET)\$(PROJECT).elf @$(OBJDUMP) -D $< > $@ size: $(TARGET)\$(PROJECT).elf @echo Size report... $(SIZE) $< ================================================ FILE: SDKHelpers/setenv.cmd ================================================ @echo off set LLILUM_ROOT=%CD%\ echo Current dir is %LLILUM_ROOT% prompt $_$+---$G $P$_$+ $G$_Cmd$G :: :: Set LLVM environment variables. :: set LLVM_BIN=%LLILUM_ROOT%LLVM\Debug\bin\ set GCC_BIN=%LLILUM_ROOT%ARM_GCC\4.9\bin\ :: :: Add pyOCD and and make to path. :: set PATH=%LLILUM_ROOT%tools;%PATH% echo Welcome to LLILUM! echo --- NOTE --- echo See SDKDrop\tools\readme.txt for the PY_OCD download link ================================================ FILE: Samples/I2cTemperatureSensor/I2cTemperatureSensor/Managed/Managed.csproj ================================================  Debug AnyCPU {82477C67-5E33-437A-9AE5-33F9808CC9F3} Exe Properties Managed Llilum.Managed v4.5 512 publish\ true Disk false Foreground 7 Days false false true 0 1.0.0.%2a false false true AnyCPU true full false bin\Debug\ DEBUG;TRACE prompt 4 true AnyCPU pdbonly true bin\Release\ TRACE prompt 4 $(LLILUM_SDK)\ZeligBuild\Host\bin\$(Configuration)\Microsoft.Llilum.BoardConfigurations.K64F.dll $(LLILUM_SDK)\ZeligBuild\Host\bin\$(Configuration)\Microsoft.Llilum.BoardConfigurations.LPC1768.dll $(LLILUM_SDK)\ZeligBuild\Target\bin\$(Configuration)\K64F.dll $(LLILUM_SDK)\ZeligBuild\Target\bin\$(Configuration)\LPC1768.dll $(LLILUM_SDK)\ZeligBuild\Target\bin\$(Configuration)\Microsoft.Zelig.Support.mbed.dll $(LLILUM_SDK)\ZeligBuild\Target\bin\$(Configuration)\System.dll $(LLILUM_SDK)\ZeligBuild\Target\bin\$(Configuration)\Windows.dll False Microsoft .NET Framework 4.5 %28x86 and x64%29 true False .NET Framework 3.5 SP1 false ================================================ FILE: Samples/I2cTemperatureSensor/I2cTemperatureSensor/Managed/Program.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // namespace Managed { using Windows.Devices.Gpio; using Windows.Devices.I2c; using Windows.Devices.Enumeration; // This is our board-specific assembly using Microsoft.Llilum.LPC1768; class Program { // This array will only have byte 0x0 in it public static byte[] i2cReadWrite1 = new byte[] { 0x0 }; public static byte[] i2cReadWrite2 = new byte[] { 0x0, 0x0 }; // // Set temperature range in order to filter bad readings. // private const double c_MinimumTemperature = 10.0; private const double c_MaximumTemperature = 50.0; // These are the pins on the LPC1768 dev board static int[] pinNumbers = { (int)PinName.LED1, (int)PinName.LED2, (int)PinName.LED3, (int)PinName.LED4, }; /// /// Writes a command to the I2cDevice, then reads the result (temperature) and formats it /// /// /// Temperature reading public static double ReadTemp(I2cDevice device) { double temp; i2cReadWrite1[0] = 0x0; I2cTransferResult res = device.WriteReadPartial(i2cReadWrite1, i2cReadWrite2); if (res.Status == I2cTransferStatus.SlaveAddressNotAcknowledged) { // Note: if you are running this sample where temp is < 0 degrees, you should probably relocate // The board is not connected temp = -1; } else { temp = ((i2cReadWrite2[0] << 8) | i2cReadWrite2[1]) / 256.0; } return temp; } private static double GetAveragedTemperature(int samples, I2cDevice i2cDevice) { double avg = 0.0; for(int i=0; i c_MaximumTemperature) { tmp = ReadTemp( i2cDevice ); } avg += tmp; } avg /= samples; return avg; } static void Main() { var controller = GpioController.GetDefault(); var pins = new GpioPin[pinNumbers.Length]; const int c_SampleCount = 4; for (int i = 0; i < pinNumbers.Length; ++i) { GpioPin pin = controller.OpenPin(pinNumbers[i]); // Start with all LEDs off. pin.Write(GpioPinValue.Low); pin.SetDriveMode(GpioPinDriveMode.Output); pins[i] = pin; } // Keep the first pin on, unless we hit an error pins[0].Write(GpioPinValue.High); // Initialize the I2cDevice string i2cDeviceSelector = I2cDevice.GetDeviceSelector("I2C1"); var i2cAcqs = DeviceInformation.FindAllAsync(i2cDeviceSelector); string i2cBusId = i2cAcqs[0].Id; I2cDevice i2cDevice = I2cDevice.FromIdAsync(i2cBusId, new I2cConnectionSettings(slaveAddress: 0x90) { SharingMode = I2cSharingMode.Shared }); // // Get average starting temperature // double firstRead = GetAveragedTemperature(c_SampleCount, i2cDevice); const double scale = 0.5; while (true) { double tempDiff = GetAveragedTemperature(c_SampleCount, i2cDevice); tempDiff -= firstRead; pins[0].Write((tempDiff > 0 * scale) ? GpioPinValue.High : GpioPinValue.Low); pins[1].Write((tempDiff > 1 * scale) ? GpioPinValue.High : GpioPinValue.Low); pins[2].Write((tempDiff > 2 * scale) ? GpioPinValue.High : GpioPinValue.Low); pins[3].Write((tempDiff > 3 * scale) ? GpioPinValue.High : GpioPinValue.Low); } } } } ================================================ FILE: Samples/I2cTemperatureSensor/I2cTemperatureSensor/Managed/Properties/AssemblyInfo.cs ================================================ using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; // General Information about an assembly is controlled through the following // set of attributes. Change these attribute values to modify the information // associated with an assembly. [assembly: AssemblyTitle("Managed")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("Managed")] [assembly: AssemblyCopyright("Copyright © 2015")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible(false)] // The following GUID is for the ID of the typelib if this project is exposed to COM [assembly: Guid("982d03a1-c858-4b8f-8ff6-11e705f29a55")] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Build and Revision Numbers // by using the '*' as shown below: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("1.0.0.0")] [assembly: AssemblyFileVersion("1.0.0.0")] ================================================ FILE: Samples/I2cTemperatureSensor/I2cTemperatureSensor/Managed/README.txt ================================================ # # Using this sample # This sample is built on top of the mBed Application Board, and uses the on-board I2C temperature sensor. Based on the temperature reading, LEDs on the LPC1768 board light up (the warmer, the more LEDs light up). Users can make the temperature "change" by placing a finger on the temperature sensor. If no LEDs light up, change the values for TEMP0-3 to be tailored to the user's environment ================================================ FILE: Samples/I2cTemperatureSensor/I2cTemperatureSensor/Native/Native.vcxproj ================================================  Debug ARM Release ARM {2a3586b9-7f8b-4215-943f-d7ecc81dbd8f} Android Native 14.0 Llilum 1.0 $(LLILUM_GCC) Native LPC1768 $(MSBuildProjectDirectory)\mbed_simple_$(LlilumBoardName).FrontEndConfig $(LlilumSDK)source\ports\mbed\inc;$(LlilumSDK)source\inc;$(LlilumSDK)source\inc\api;$(LlilumSDK)source\inc\api\io;$(LlilumSDK)source\inc\hal $(LlilumClAdditionalOptionsLPC1768) $(LlilumClAdditionalIncludesLPC1768) $(LlilumClPreprocessorDefsLPC1768) $(LlilumLinkAdditionalDepsLPC1768) $(LlilumLinkAdditionalLibDirsLPC1768) $(LlilumLinkAdditionalOptionsLPC1768) $(LlilumLinkLibDepsLPC1768) $(LlilumTargetBoardArchitectureLPC1768) $(LlilumAsmAdditionalOptionsLPC1768) $(LlilumStackSizeLPC1768) $(LlilumHeapSizeLPC1768) $(LlilumClAdditionalOptionsK64F) $(LlilumClAdditionalIncludesK64F) $(LlilumClPreprocessorDefsK64F) $(LlilumLinkAdditionalDepsK64F) $(LlilumLinkAdditionalLibDirsK64F) $(LlilumLinkAdditionalOptionsK64F) $(LlilumLinkLibDepsK64F) $(LlilumTargetBoardArchitectureK64F) $(LlilumAsmAdditionalOptionsK64F) $(LlilumStackSizeK64F) $(LlilumHeapSizeK64F) $(LlilumClAdditionalOptionsSTM32L152) $(LlilumClAdditionalIncludesSTM32L152) $(LlilumClPreprocessorDefsSTM32L152) $(LlilumLinkAdditionalDepsSTM32L152) $(LlilumLinkAdditionalLibDirsSTM32L152) $(LlilumLinkAdditionalOptionsSTM32L152) $(LlilumLinkLibDepsSTM32L152) $(LlilumTargetBoardArchitectureSTM32L152) $(LlilumAsmAdditionalOptionsSTM32L152) $(LlilumStackSizeSTM32L152) $(LlilumHeapSizeSTM32L152) DynamicLibrary true $(LlilumTargetBoardArchitecture) DynamicLibrary $(LlilumTargetBoardArchitecture) system false $(LlilumOutputName) .elf $(LlilumGccBin);$(ExecutablePath) $(LlilumOutputName) .elf $(LlilumGccBin);$(ExecutablePath) Use pch.h $(LlilumClAdditionalOptions) %(AdditionalOptions) $(LlilumClAdditionalIncludes);%(AdditionalIncludeDirectories);$(NativeIncludes) $(LlilumClPreprocessorDefs);DEBUG;%(PreprocessorDefinitions);__DEFAULT_STACK_SIZE=$(LlilumStackSize);__HEAP_SIZE=$(LlilumHeapSize) $(LlilumAsmAdditionalOptions) %(LlilumClAdditionalOptions) -Wa,--defsym,__HEAP_SIZE=$(LlilumHeapSize) $(LlilumLinkAdditionalDeps) $(LlilumLinkAdditionalLibDirs) $(LlilumLinkAdditionalOptions) %(AdditionalOptions) $(LlilumLinkLibDeps) Use pch.h $(LlilumClAdditionalOptions) %(AdditionalOptions) $(LlilumClAdditionalIncludes);%(AdditionalIncludeDirectories);$(NativeIncludes) $(LlilumClPreprocessorDefs);%(PreprocessorDefinitions);__DEFAULT_STACK_SIZE=$(LlilumStackSize);__HEAP_SIZE=$(LlilumHeapSize) $(LlilumAsmAdditionalOptions) %(LlilumClAdditionalOptions) -Wa,--defsym,__HEAP_SIZE=$(LlilumHeapSize) $(LlilumLinkAdditionalDeps) $(LlilumLinkAdditionalLibDirs) $(LlilumLinkAdditionalOptions) %(AdditionalOptions) $(LlilumLinkLibDeps) {34eeeced-afb0-4717-8212-d7f6dc103896} true true true ================================================ FILE: Samples/I2cTemperatureSensor/I2cTemperatureSensor/Native/Source.cpp ================================================ extern "C" { // User's C interop code goes here // Dummy function used in Program.cs as an example int AddOneInterop(int input) { return input + 1; } } ================================================ FILE: Samples/I2cTemperatureSensor/I2cTemperatureSensor/Native/mbed_simple_K64F.FrontEndConfig ================================================ ### ### Location of the Zelig assemblies. ### #-HostAssemblyDir ..\..\..\..\ZeligBuild\Host\bin\Debug #-DeviceAssemblyDir ..\..\..\..\ZeligBuild\Target\bin\Debug -CompilationSetup Microsoft.Llilum.BoardConfigurations.K64FMBEDHostedCompilationSetup ### ### We need to include this assembly to get the right drivers. ### -Reference Microsoft.CortexM4OnMBED -Reference Microsoft.CortexM4OnCMSISCore -Reference Microsoft.DeviceModels.ModelForCortexM4 -Reference K64F ### ### Add compilation phases, in order ### #-CompilationPhaseDisabled ReduceNumberOfTemporaries #-CompilationPhaseDisabled TransformFinallyBlocksIntoTryBlocks #-CompilationPhaseDisabled ApplyClassExtensions #-CompilationPhaseDisabled PrepareImplementationOfInternalMethods #-CompilationPhaseDisabled CrossReferenceTypeSystem #-CompilationPhaseDisabled ApplyConfigurationSettings -CompilationPhaseDisabled ResourceManagerOptimizations #-CompilationPhaseDisabled HighLevelTransformations #-CompilationPhaseDisabled PropagateCompilationConstraints #-CompilationPhaseDisabled ComputeCallsClosure #-CompilationPhaseDisabled EstimateTypeSystemReduction #-CompilationPhaseDisabled CompleteImplementationOfInternalMethods #-CompilationPhaseDisabled ReduceTypeSystem -CompilationPhaseDisabled PrepareExternalMethods #-CompilationPhaseDisabled DetectNonImplementedInternalCalls #-CompilationPhaseDisabled OrderStaticConstructors #-CompilationPhaseDisabled LayoutTypes #-CompilationPhaseDisabled HighLevelToMidLevelConversion #-CompilationPhaseDisabled FromImplicitToExplicitExceptions #-CompilationPhaseDisabled ReferenceCountingGarbageCollection -CompilationPhaseDisabled MidLevelToLowLevelConversion -CompilationPhaseDisabled ConvertUnsupportedOperatorsToMethodCalls -CompilationPhaseDisabled ExpandAggregateTypes -CompilationPhaseDisabled SplitComplexOperators -CompilationPhaseDisabled FuseOperators #-CompilationPhaseDisabled Optimizations -CompilationPhaseDisabled ConvertToSSA -CompilationPhaseDisabled PrepareForRegisterAllocation -CompilationPhaseDisabled CollectRegisterAllocationConstraints -CompilationPhaseDisabled AllocateRegisters #-CompilationPhaseDisabled GenerateImage #-CompilationPhaseDisabled Done ### ### The program to compile. ### #..\..\..\..\ZeligBuild\Target\bin\Debug\Microsoft.Zelig.Test.mbed.Simple.exe ### ### Where to put the results. ### #-OutputName Microsoft.Zelig.Test.mbed.Simple #-OutputDir ..\..\..\..\LLVM2IR_results\mbed\simple #-DumpIR #-DumpIRpre #-DumpIRpost #-DumpIRXML -DumpLLVMIR #-ReloadState #-DumpLLVMIR_TextRepresentation -MaxProcs 8 ================================================ FILE: Samples/I2cTemperatureSensor/I2cTemperatureSensor/Native/mbed_simple_LPC1768.FrontEndConfig ================================================ ### ### Location of the Zelig assemblies. ### #-HostAssemblyDir ..\..\..\..\ZeligBuild\Host\bin\Debug #-DeviceAssemblyDir ..\..\..\..\ZeligBuild\Target\bin\Debug -CompilationSetup Microsoft.Llilum.BoardConfigurations.LPC1768MBEDHostedCompilationSetup ### ### We need to include this assembly to get the right drivers. ### -Reference Microsoft.CortexM3OnMBED -Reference Microsoft.CortexM3OnCMSISCore -Reference Microsoft.DeviceModels.ModelForCortexM3 -Reference LPC1768 ### ### Add compilation phases, in order ### #-CompilationPhaseDisabled ReduceNumberOfTemporaries #-CompilationPhaseDisabled TransformFinallyBlocksIntoTryBlocks #-CompilationPhaseDisabled ApplyClassExtensions #-CompilationPhaseDisabled PrepareImplementationOfInternalMethods #-CompilationPhaseDisabled CrossReferenceTypeSystem #-CompilationPhaseDisabled ApplyConfigurationSettings -CompilationPhaseDisabled ResourceManagerOptimizations #-CompilationPhaseDisabled HighLevelTransformations #-CompilationPhaseDisabled PropagateCompilationConstraints #-CompilationPhaseDisabled ComputeCallsClosure #-CompilationPhaseDisabled EstimateTypeSystemReduction #-CompilationPhaseDisabled CompleteImplementationOfInternalMethods #-CompilationPhaseDisabled ReduceTypeSystem -CompilationPhaseDisabled PrepareExternalMethods #-CompilationPhaseDisabled DetectNonImplementedInternalCalls #-CompilationPhaseDisabled OrderStaticConstructors #-CompilationPhaseDisabled LayoutTypes #-CompilationPhaseDisabled HighLevelToMidLevelConversion #-CompilationPhaseDisabled FromImplicitToExplicitExceptions #-CompilationPhaseDisabled ReferenceCountingGarbageCollection -CompilationPhaseDisabled MidLevelToLowLevelConversion -CompilationPhaseDisabled ConvertUnsupportedOperatorsToMethodCalls -CompilationPhaseDisabled ExpandAggregateTypes -CompilationPhaseDisabled SplitComplexOperators -CompilationPhaseDisabled FuseOperators #-CompilationPhaseDisabled Optimizations -CompilationPhaseDisabled ConvertToSSA -CompilationPhaseDisabled PrepareForRegisterAllocation -CompilationPhaseDisabled CollectRegisterAllocationConstraints -CompilationPhaseDisabled AllocateRegisters #-CompilationPhaseDisabled GenerateImage #-CompilationPhaseDisabled Done ### ### The program to compile. ### #..\..\..\..\ZeligBuild\Target\bin\Debug\Microsoft.Zelig.Test.mbed.Simple.exe ### ### Where to put the results. ### #-OutputName Microsoft.Zelig.Test.mbed.Simple #-OutputDir ..\..\..\..\LLVM2IR_results\mbed\simple #-DumpIR #-DumpIRpre #-DumpIRpost #-DumpIRXML -DumpLLVMIR #-ReloadState #-DumpLLVMIR_TextRepresentation -MaxProcs 8 ================================================ FILE: Samples/I2cTemperatureSensor/I2cTemperatureSensor/Native/mbed_simple_STM32L152.FrontEndConfig ================================================ ### ### Location of the Zelig assemblies. ### -HostAssemblyDir ..\..\..\..\ZeligBuild\Host\bin\Debug -DeviceAssemblyDir ..\..\..\..\ZeligBuild\Target\bin\Debug -CompilationSetupPath ..\..\..\..\ZeligBuild\Host\bin\Debug\Microsoft.Llilum.BoardConfigurations.STM32L152.dll -CompilationSetup Microsoft.Llilum.BoardConfigurations.STM32L152MBEDHostedCompilationSetup ### ### We need to include this assembly to get the right drivers. ### -Reference Microsoft.CortexM3OnMBED -Reference Microsoft.CortexM3OnCMSISCore -Reference Microsoft.DeviceModels.ModelForCortexM3 -Reference STM32L152 ### ### Add compilation phases, in order ### #-CompilationPhaseDisabled ReduceNumberOfTemporaries #-CompilationPhaseDisabled TransformFinallyBlocksIntoTryBlocks #-CompilationPhaseDisabled ApplyClassExtensions #-CompilationPhaseDisabled PrepareImplementationOfInternalMethods #-CompilationPhaseDisabled CrossReferenceTypeSystem #-CompilationPhaseDisabled ApplyConfigurationSettings -CompilationPhaseDisabled ResourceManagerOptimizations #-CompilationPhaseDisabled HighLevelTransformations #-CompilationPhaseDisabled PropagateCompilationConstraints #-CompilationPhaseDisabled ComputeCallsClosure #-CompilationPhaseDisabled EstimateTypeSystemReduction #-CompilationPhaseDisabled CompleteImplementationOfInternalMethods #-CompilationPhaseDisabled ReduceTypeSystem -CompilationPhaseDisabled PrepareExternalMethods #-CompilationPhaseDisabled DetectNonImplementedInternalCalls #-CompilationPhaseDisabled OrderStaticConstructors #-CompilationPhaseDisabled LayoutTypes #-CompilationPhaseDisabled HighLevelToMidLevelConversion #-CompilationPhaseDisabled FromImplicitToExplicitExceptions #-CompilationPhaseDisabled ReferenceCountingGarbageCollection -CompilationPhaseDisabled MidLevelToLowLevelConversion -CompilationPhaseDisabled ConvertUnsupportedOperatorsToMethodCalls -CompilationPhaseDisabled ExpandAggregateTypes -CompilationPhaseDisabled SplitComplexOperators -CompilationPhaseDisabled FuseOperators #-CompilationPhaseDisabled Optimizations -CompilationPhaseDisabled ConvertToSSA -CompilationPhaseDisabled PrepareForRegisterAllocation -CompilationPhaseDisabled CollectRegisterAllocationConstraints -CompilationPhaseDisabled AllocateRegisters #-CompilationPhaseDisabled GenerateImage #-CompilationPhaseDisabled Done ### ### The program to compile. ### ..\..\..\..\ZeligBuild\Target\bin\Debug\Microsoft.Zelig.Test.mbed.Simple.exe ### ### Where to put the results. ### -OutputName Microsoft.Zelig.Test.mbed.Simple -OutputDir ..\..\..\..\LLVM2IR_results\mbed\simple -DumpIR #-DumpIRpre #-DumpIRpost #-DumpIRXML -DumpLLVMIR #-ReloadState -DumpLLVMIR_TextRepresentation -MaxProcs 8 -NoSDK ================================================ FILE: Samples/I2cTemperatureSensor/I2cTemperatureSensor/Native/pch.h ================================================ ================================================ FILE: Samples/I2cTemperatureSensor/I2cTemperatureSensor.sln ================================================  Microsoft Visual Studio Solution File, Format Version 12.00 # Visual Studio 14 VisualStudioVersion = 14.0.23107.0 MinimumVisualStudioVersion = 10.0.40219.1 Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "Native", "I2cTemperatureSensor\Native\Native.vcxproj", "{2A3586B9-7F8B-4215-943F-D7ECC81DBD8F}" EndProject Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Managed", "I2cTemperatureSensor\Managed\Managed.csproj", "{82477C67-5E33-437A-9AE5-33F9808CC9F3}" EndProject Global GlobalSection(SolutionConfigurationPlatforms) = preSolution Debug|Any CPU = Debug|Any CPU Debug|ARM = Debug|ARM Release|Any CPU = Release|Any CPU Release|ARM = Release|ARM EndGlobalSection GlobalSection(ProjectConfigurationPlatforms) = postSolution {2A3586B9-7F8B-4215-943F-D7ECC81DBD8F}.Debug|Any CPU.ActiveCfg = Debug|ARM {2A3586B9-7F8B-4215-943F-D7ECC81DBD8F}.Debug|ARM.ActiveCfg = Debug|ARM {2A3586B9-7F8B-4215-943F-D7ECC81DBD8F}.Debug|ARM.Build.0 = Debug|ARM {2A3586B9-7F8B-4215-943F-D7ECC81DBD8F}.Debug|ARM.Deploy.0 = Debug|ARM {2A3586B9-7F8B-4215-943F-D7ECC81DBD8F}.Release|Any CPU.ActiveCfg = Release|ARM {2A3586B9-7F8B-4215-943F-D7ECC81DBD8F}.Release|ARM.ActiveCfg = Release|ARM {2A3586B9-7F8B-4215-943F-D7ECC81DBD8F}.Release|ARM.Build.0 = Release|ARM {2A3586B9-7F8B-4215-943F-D7ECC81DBD8F}.Release|ARM.Deploy.0 = Release|ARM {82477C67-5E33-437A-9AE5-33F9808CC9F3}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {82477C67-5E33-437A-9AE5-33F9808CC9F3}.Debug|Any CPU.Build.0 = Debug|Any CPU {82477C67-5E33-437A-9AE5-33F9808CC9F3}.Debug|ARM.ActiveCfg = Debug|Any CPU {82477C67-5E33-437A-9AE5-33F9808CC9F3}.Debug|ARM.Build.0 = Debug|Any CPU {82477C67-5E33-437A-9AE5-33F9808CC9F3}.Release|Any CPU.ActiveCfg = Release|Any CPU {82477C67-5E33-437A-9AE5-33F9808CC9F3}.Release|Any CPU.Build.0 = Release|Any CPU {82477C67-5E33-437A-9AE5-33F9808CC9F3}.Release|ARM.ActiveCfg = Release|Any CPU {82477C67-5E33-437A-9AE5-33F9808CC9F3}.Release|ARM.Build.0 = Release|Any CPU EndGlobalSection GlobalSection(SolutionProperties) = preSolution HideSolutionNode = FALSE EndGlobalSection EndGlobal ================================================ FILE: Samples/README.txt ================================================ Below is the list of samples in this directory. Each item lists the sample name, the MCU it is implemented for, and any other requirements for it to run correctly. Many of these rely on the mBed Application board, which can be found here: https://developer.mbed.org/cookbook/mbed-application-board Sample Name | MCU | Additional Requirements | Details ============================================================================================================================ Spi Display | LPC1768 | mBed Application Board | Modifying board config; SPI; ADC; managed driver I2c Temperature Sensor | LPC1768 | mBed Application Board | I2C; GPIO ================================================ FILE: Samples/SpiDisplay/SpiDisplay/Managed/Managed.csproj ================================================  Debug AnyCPU {2F9DF480-AFDB-482D-87BB-5CB82E03A43F} Exe Properties Managed Llilum.Managed v4.5 512 publish\ true Disk false Foreground 7 Days false false true 0 1.0.0.%2a false false true AnyCPU true full false bin\Debug\ DEBUG;TRACE prompt 4 true AnyCPU pdbonly true bin\Release\ TRACE prompt 4 $(LLILUM_SDK)\ZeligBuild\Target\bin\$(Configuration)\Microsoft.Zelig.Support.mbed.dll $(LLILUM_SDK)\ZeligBuild\Target\bin\$(Configuration)\LPC1768.dll $(LLILUM_SDK)\ZeligBuild\Target\bin\$(Configuration)\System.dll $(LLILUM_SDK)\ZeligBuild\Target\bin\$(Configuration)\Windows.dll $(LLILUM_SDK)\ZeligBuild\Host\bin\$(Configuration)\Microsoft.Llilum.BoardConfigurations.LPC1768.dll False Microsoft .NET Framework 4.5 %28x86 and x64%29 true False .NET Framework 3.5 SP1 false ================================================ FILE: Samples/SpiDisplay/SpiDisplay/Managed/Program.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // namespace Microsoft.Zelig.Test.mbed.Simple { using Windows.Devices.Adc; using Windows.Devices.Gpio; using Windows.Devices.Spi; using Windows.Devices.Enumeration; // This is our board-specific assembly using Llilum.LPC1768; /// /// This is a sample program to show the functionality of the SPI controller implementation. This demonstrates the power of /// writing managed drivers, and the ability to interact with C functions through managed code. This demo is intended to /// be run on a LPC1768 board on the mBed application board (https://developer.mbed.org/cookbook/mbed-application-board) /// unsafe class Program { static AdcChannel adcChannel; static SpiDevice spiDevice; static GpioPin _A0, _reset, _CS; // This is the figure we will be drawing static byte[] stickFigure = new byte[] {0x00, 0x00, 0xF0, 0x9C, 0x06, 0xC2, 0x93, 0x01, 0x01, 0x93, 0xC2, 0x06, 0x9C, 0xF0, 0x00, 0x00, 0x10, 0x10, 0x20, 0x23, 0x46, 0x44, 0x8C, 0xF9, 0xF9, 0x8C, 0x44, 0x46, 0x23, 0x20, 0x10, 0x10, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x80, 0x7F, 0x7F, 0x80, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x80, 0x60, 0x18, 0x06, 0x01, 0x00, 0x00, 0x01, 0x06, 0x18, 0x60, 0x80, 0x00, 0x00}; static byte[] writeHelper; static void Main() { var controller = GpioController.GetDefault(); // Used to pass data to SPI device writeHelper = new byte[1]; _A0 = controller.OpenPin((int)PinName.p8); _A0.SetDriveMode(GpioPinDriveMode.Output); _reset = controller.OpenPin((int)PinName.p6); // Start reset high _reset.Write(GpioPinValue.High); _reset.SetDriveMode(GpioPinDriveMode.Output); _CS = controller.OpenPin((int)PinName.p11); _CS.Write(GpioPinValue.High); _CS.SetDriveMode(GpioPinDriveMode.Output); // Analog pin init. This maps to LPC1768 p19 adcChannel = AdcController.GetDefaultAsync().OpenChannel(4); // Note: The LCD display uses a non-standard SPI configuration. This is why we // have added a copy of the LPC1768 project, and changed the configuration for SPI0! // Get the device selector by friendly name string deviceSelector = SpiDevice.GetDeviceSelector("SPI0WriteOnly"); var acqs = DeviceInformation.FindAllAsync(deviceSelector); string busId = acqs[0].Id; // Set up a non-default frequency and pins int chipSelect = unchecked((int)PinName.NC); SpiConnectionSettings settings = new SpiConnectionSettings(chipSelect) { ClockFrequency = 20000000, Mode = SpiMode.Mode3 }; // Get a reference to the SPI device spiDevice = SpiDevice.FromIdAsync(busId, settings); // Initialize the LCD display lcd_reset(); int width = 16; while (true) { int analogVal = (int)(adcChannel.ReadRatio() * 100); if (analogVal > 112) { analogVal = 112; } else if (analogVal < 0) { analogVal = 0; } copy_to_lcd(analogVal, analogVal + width); } } /// /// LCD Initializer /// private static void lcd_reset() { _A0.Write(GpioPinValue.Low); _CS.Write(GpioPinValue.High); _reset.Write(GpioPinValue.Low); for (int i = 0; i < 500; i++) { // Wait 50ms } // Try to force low... _reset.Write(GpioPinValue.High); for (int i = 0; i < 50; i++) { // Wait 5ms } wr_cmd(0xAE); // display off wr_cmd(0xA2); // bias voltage wr_cmd(0xA0); wr_cmd(0xC8); // column normal wr_cmd(0x22); // voltage resistor ratio wr_cmd(0x2F); // power on //wr_cmd(0xA4); // LCD display ram wr_cmd(0x40); // start line = 0 wr_cmd(0xAF); // display ON wr_cmd(0x81); // set contrast wr_cmd(0x17); // set contrast wr_cmd(0xA6); // display normal copy_to_lcd(-1, -1); } /// /// Write a single byte command to the LCD display /// /// private static void wr_cmd(byte a) { writeHelper[0] = a; _A0.Write(GpioPinValue.Low); _CS.Write(GpioPinValue.Low); spiDevice.Write(writeHelper); _CS.Write(GpioPinValue.High); } /// /// Write a single byte data to the LCD display /// /// private static void wr_dat(byte a) { writeHelper[0] = a; _A0.Write(GpioPinValue.High); _CS.Write(GpioPinValue.Low); spiDevice.Write(writeHelper); } /// /// Flush the LCD display. Draw a figure from startIndex to stopIndex. /// /// Begin drawing /// End drawing private static void copy_to_lcd(int startIndex, int stopIndex) { int i = 0; int j = 0; //page 0 wr_cmd(0x00); // set column low nibble 0 wr_cmd(0x10); // set column hi nibble 0 wr_cmd(0xB0); // set page address 0 _A0.Write(GpioPinValue.High); for (i = 0; i < 128; i++) { if (i >= startIndex && i < stopIndex) { wr_dat(stickFigure[j]); j++; } else { wr_dat(0x00); } } // page 1 wr_cmd(0x00); // set column low nibble 0 wr_cmd(0x10); // set column hi nibble 0 wr_cmd(0xB1); // set page address 1 _A0.Write(GpioPinValue.High); for (i = 0; i < 128; i++) { if (i >= startIndex && i < stopIndex) { wr_dat(stickFigure[j]); j++; } else { wr_dat(0x00); } } //page 2 wr_cmd(0x00); // set column low nibble 0 wr_cmd(0x10); // set column hi nibble 0 wr_cmd(0xB2); // set page address 2 _A0.Write(GpioPinValue.High); for (i = 0; i < 128; i++) { if (i >= startIndex && i < stopIndex) { wr_dat(stickFigure[j]); j++; } else { wr_dat(0x00); } } //page 3 wr_cmd(0x00); // set column low nibble 0 wr_cmd(0x10); // set column hi nibble 0 wr_cmd(0xB3); // set page address 3 _A0.Write(GpioPinValue.High); // Why is this here? //_CS.Write(GpioPinValue.Low); for (i = 0; i < 128; i++) { if (i >= startIndex && i < stopIndex) { wr_dat(stickFigure[j]); j++; } else { wr_dat(0x00); } } } } } ================================================ FILE: Samples/SpiDisplay/SpiDisplay/Managed/Properties/AssemblyInfo.cs ================================================ using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; // General Information about an assembly is controlled through the following // set of attributes. Change these attribute values to modify the information // associated with an assembly. [assembly: AssemblyTitle("Managed")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("Managed")] [assembly: AssemblyCopyright("Copyright © 2015")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible(false)] // The following GUID is for the ID of the typelib if this project is exposed to COM [assembly: Guid("66e1e899-ba49-4bf4-bb74-f9b3b74a87ec")] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Build and Revision Numbers // by using the '*' as shown below: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("1.0.0.0")] [assembly: AssemblyFileVersion("1.0.0.0")] ================================================ FILE: Samples/SpiDisplay/SpiDisplay/Managed/README.txt ================================================ # # Using a modified board configuration # The mbed Application Board has a SPI display connected to SPI0. The MISO and CS pins, however, are not connected as SPI pins; they are mapped to _reset and _A0, respectively. In order to ensure that the MISO and CS pins are not reserved by the SpiDevice, we must modify the board configuration assembly (LPC1768.dll) and create a new one (LPC1768ApplicationBoard.dll). Below are the steps for how we accomplished that goal: 1. Copy the LPC1768 project from Zelig\Runtime\DeviceModels\CortexM\Boards to the Solution Dir. 2. Add the copied project to the solution, rename it, and rename its assembly in AssemblyInfo.cs 3. Edit the project properties so that build output goes to SDKDrop\ZeligBuild\Target\bin\Debug\ 4. Resolve any reference issues, and ensure that all DLLs are in SDKDrop\ZeligBuild\Target\bin\Debug\ 5. Change the LPC1768 reference in the Managed project to LPC1768ApplicationBoard 6. Ensure that the managed projects build correctly 7. In mbed_simple_LPC1768.FrontEndConfig, change "-Reference LPC1768" to "-Reference LPC1768ApplicationBoard" 8. Rebuild the entire solution ================================================ FILE: Samples/SpiDisplay/SpiDisplay/Native/Native.vcxproj ================================================  Debug ARM Release ARM {d8dca8c9-9d56-4f97-b5fa-d26ed0944400} Android Native 14.0 Llilum 1.0 $(LLILUM_GCC) Native LPC1768 $(MSBuildProjectDirectory)\mbed_simple_$(LlilumBoardName).FrontEndConfig $(LlilumSDK)source\ports\mbed\inc;$(LlilumSDK)source\inc;$(LlilumSDK)source\inc\api;$(LlilumSDK)source\inc\api\io;$(LlilumSDK)source\inc\hal $(LlilumClAdditionalOptionsLPC1768) $(LlilumClAdditionalIncludesLPC1768) $(LlilumClPreprocessorDefsLPC1768) $(LlilumLinkAdditionalDepsLPC1768) $(LlilumLinkAdditionalLibDirsLPC1768) $(LlilumLinkAdditionalOptionsLPC1768) $(LlilumLinkLibDepsLPC1768) $(LlilumTargetBoardArchitectureLPC1768) $(LlilumAsmAdditionalOptionsLPC1768) $(LlilumStackSizeLPC1768) $(LlilumHeapSizeLPC1768) $(LlilumClAdditionalOptionsK64F) $(LlilumClAdditionalIncludesK64F) $(LlilumClPreprocessorDefsK64F) $(LlilumLinkAdditionalDepsK64F) $(LlilumLinkAdditionalLibDirsK64F) $(LlilumLinkAdditionalOptionsK64F) $(LlilumLinkLibDepsK64F) $(LlilumTargetBoardArchitectureK64F) $(LlilumAsmAdditionalOptionsK64F) $(LlilumStackSizeK64F) $(LlilumHeapSizeK64F) $(LlilumClAdditionalOptionsSTM32L152) $(LlilumClAdditionalIncludesSTM32L152) $(LlilumClPreprocessorDefsSTM32L152) $(LlilumLinkAdditionalDepsSTM32L152) $(LlilumLinkAdditionalLibDirsSTM32L152) $(LlilumLinkAdditionalOptionsSTM32L152) $(LlilumLinkLibDepsSTM32L152) $(LlilumTargetBoardArchitectureSTM32L152) $(LlilumAsmAdditionalOptionsSTM32L152) $(LlilumStackSizeSTM32L152) $(LlilumHeapSizeSTM32L152) DynamicLibrary true $(LlilumTargetBoardArchitecture) DynamicLibrary $(LlilumTargetBoardArchitecture) system false $(LlilumOutputName) .elf $(LlilumGccBin);$(ExecutablePath) $(LlilumOutputName) .elf $(LlilumGccBin);$(ExecutablePath) Use pch.h $(LlilumClAdditionalOptions) %(AdditionalOptions) $(LlilumClAdditionalIncludes);%(AdditionalIncludeDirectories);$(NativeIncludes) $(LlilumClPreprocessorDefs);DEBUG;%(PreprocessorDefinitions);__DEFAULT_STACK_SIZE=$(LlilumStackSize);__HEAP_SIZE=$(LlilumHeapSize) $(LlilumAsmAdditionalOptions) %(LlilumClAdditionalOptions) -Wa,--defsym,__HEAP_SIZE=$(LlilumHeapSize) $(LlilumLinkAdditionalDeps) $(LlilumLinkAdditionalLibDirs) $(LlilumLinkAdditionalOptions) %(AdditionalOptions) $(LlilumLinkLibDeps) Use pch.h $(LlilumClAdditionalOptions) %(AdditionalOptions) $(LlilumClAdditionalIncludes);%(AdditionalIncludeDirectories);$(NativeIncludes) $(LlilumClPreprocessorDefs);%(PreprocessorDefinitions);__DEFAULT_STACK_SIZE=$(LlilumStackSize);__HEAP_SIZE=$(LlilumHeapSize) $(LlilumAsmAdditionalOptions) %(LlilumClAdditionalOptions) -Wa,--defsym,__HEAP_SIZE=$(LlilumHeapSize) $(LlilumLinkAdditionalDeps) $(LlilumLinkAdditionalLibDirs) $(LlilumLinkAdditionalOptions) %(AdditionalOptions) $(LlilumLinkLibDeps) {b82b6a0e-fe0c-4ad7-bd33-525508a987b1} true true true ================================================ FILE: Samples/SpiDisplay/SpiDisplay/Native/Source.cpp ================================================ extern "C" { // User's C interop code goes here // Dummy function used in Program.cs as an example int AddOneInterop(int input) { return input + 1; } } ================================================ FILE: Samples/SpiDisplay/SpiDisplay/Native/mbed_simple_K64F.FrontEndConfig ================================================ ### ### Location of the Zelig assemblies. ### #-HostAssemblyDir ..\..\..\..\ZeligBuild\Host\bin\Debug #-DeviceAssemblyDir ..\..\..\..\ZeligBuild\Target\bin\Debug -CompilationSetup Microsoft.Llilum.BoardConfigurations.K64FMBEDHostedCompilationSetup ### ### We need to include this assembly to get the right drivers. ### -Reference Microsoft.CortexM4OnMBED -Reference Microsoft.CortexM4OnCMSISCore -Reference Microsoft.DeviceModels.ModelForCortexM4 -Reference K64F ### ### Add compilation phases, in order ### #-CompilationPhaseDisabled ReduceNumberOfTemporaries #-CompilationPhaseDisabled TransformFinallyBlocksIntoTryBlocks #-CompilationPhaseDisabled ApplyClassExtensions #-CompilationPhaseDisabled PrepareImplementationOfInternalMethods #-CompilationPhaseDisabled CrossReferenceTypeSystem #-CompilationPhaseDisabled ApplyConfigurationSettings -CompilationPhaseDisabled ResourceManagerOptimizations #-CompilationPhaseDisabled HighLevelTransformations #-CompilationPhaseDisabled PropagateCompilationConstraints #-CompilationPhaseDisabled ComputeCallsClosure #-CompilationPhaseDisabled EstimateTypeSystemReduction #-CompilationPhaseDisabled CompleteImplementationOfInternalMethods #-CompilationPhaseDisabled ReduceTypeSystem -CompilationPhaseDisabled PrepareExternalMethods #-CompilationPhaseDisabled DetectNonImplementedInternalCalls #-CompilationPhaseDisabled OrderStaticConstructors #-CompilationPhaseDisabled LayoutTypes #-CompilationPhaseDisabled HighLevelToMidLevelConversion #-CompilationPhaseDisabled FromImplicitToExplicitExceptions #-CompilationPhaseDisabled ReferenceCountingGarbageCollection -CompilationPhaseDisabled MidLevelToLowLevelConversion -CompilationPhaseDisabled ConvertUnsupportedOperatorsToMethodCalls -CompilationPhaseDisabled ExpandAggregateTypes -CompilationPhaseDisabled SplitComplexOperators -CompilationPhaseDisabled FuseOperators #-CompilationPhaseDisabled Optimizations -CompilationPhaseDisabled ConvertToSSA -CompilationPhaseDisabled PrepareForRegisterAllocation -CompilationPhaseDisabled CollectRegisterAllocationConstraints -CompilationPhaseDisabled AllocateRegisters #-CompilationPhaseDisabled GenerateImage #-CompilationPhaseDisabled Done ### ### The program to compile. ### #..\..\..\..\ZeligBuild\Target\bin\Debug\Microsoft.Zelig.Test.mbed.Simple.exe ### ### Where to put the results. ### #-OutputName Microsoft.Zelig.Test.mbed.Simple #-OutputDir ..\..\..\..\LLVM2IR_results\mbed\simple #-DumpIR #-DumpIRpre #-DumpIRpost #-DumpIRXML -DumpLLVMIR #-ReloadState #-DumpLLVMIR_TextRepresentation -MaxProcs 8 ================================================ FILE: Samples/SpiDisplay/SpiDisplay/Native/mbed_simple_LPC1768.FrontEndConfig ================================================ ### ### Location of the Zelig assemblies. ### #-HostAssemblyDir ..\..\..\..\ZeligBuild\Host\bin\Debug #-DeviceAssemblyDir ..\..\..\..\ZeligBuild\Target\bin\Debug -CompilationSetup Microsoft.Llilum.BoardConfigurations.LPC1768MBEDHostedCompilationSetup ### ### We need to include this assembly to get the right drivers. ### -Reference Microsoft.CortexM3OnMBED -Reference Microsoft.CortexM3OnCMSISCore -Reference Microsoft.DeviceModels.ModelForCortexM3 -Reference LPC1768 ### ### Add compilation phases, in order ### #-CompilationPhaseDisabled ReduceNumberOfTemporaries #-CompilationPhaseDisabled TransformFinallyBlocksIntoTryBlocks #-CompilationPhaseDisabled ApplyClassExtensions #-CompilationPhaseDisabled PrepareImplementationOfInternalMethods #-CompilationPhaseDisabled CrossReferenceTypeSystem #-CompilationPhaseDisabled ApplyConfigurationSettings -CompilationPhaseDisabled ResourceManagerOptimizations #-CompilationPhaseDisabled HighLevelTransformations #-CompilationPhaseDisabled PropagateCompilationConstraints #-CompilationPhaseDisabled ComputeCallsClosure #-CompilationPhaseDisabled EstimateTypeSystemReduction #-CompilationPhaseDisabled CompleteImplementationOfInternalMethods #-CompilationPhaseDisabled ReduceTypeSystem -CompilationPhaseDisabled PrepareExternalMethods #-CompilationPhaseDisabled DetectNonImplementedInternalCalls #-CompilationPhaseDisabled OrderStaticConstructors #-CompilationPhaseDisabled LayoutTypes #-CompilationPhaseDisabled HighLevelToMidLevelConversion #-CompilationPhaseDisabled FromImplicitToExplicitExceptions #-CompilationPhaseDisabled ReferenceCountingGarbageCollection -CompilationPhaseDisabled MidLevelToLowLevelConversion -CompilationPhaseDisabled ConvertUnsupportedOperatorsToMethodCalls -CompilationPhaseDisabled ExpandAggregateTypes -CompilationPhaseDisabled SplitComplexOperators -CompilationPhaseDisabled FuseOperators #-CompilationPhaseDisabled Optimizations -CompilationPhaseDisabled ConvertToSSA -CompilationPhaseDisabled PrepareForRegisterAllocation -CompilationPhaseDisabled CollectRegisterAllocationConstraints -CompilationPhaseDisabled AllocateRegisters #-CompilationPhaseDisabled GenerateImage #-CompilationPhaseDisabled Done ### ### The program to compile. ### #..\..\..\..\ZeligBuild\Target\bin\Debug\Microsoft.Zelig.Test.mbed.Simple.exe ### ### Where to put the results. ### #-OutputName Microsoft.Zelig.Test.mbed.Simple #-OutputDir ..\..\..\..\LLVM2IR_results\mbed\simple #-DumpIR #-DumpIRpre #-DumpIRpost #-DumpIRXML -DumpLLVMIR #-ReloadState #-DumpLLVMIR_TextRepresentation -MaxProcs 8 ================================================ FILE: Samples/SpiDisplay/SpiDisplay/Native/mbed_simple_STM32L152.FrontEndConfig ================================================ ### ### Location of the Zelig assemblies. ### -HostAssemblyDir ..\..\..\..\ZeligBuild\Host\bin\Debug -DeviceAssemblyDir ..\..\..\..\ZeligBuild\Target\bin\Debug -CompilationSetupPath ..\..\..\..\ZeligBuild\Host\bin\Debug\Microsoft.Llilum.BoardConfigurations.STM32L152.dll -CompilationSetup Microsoft.Llilum.BoardConfigurations.STM32L152MBEDHostedCompilationSetup ### ### We need to include this assembly to get the right drivers. ### -Reference Microsoft.CortexM3OnMBED -Reference Microsoft.CortexM3OnCMSISCore -Reference Microsoft.DeviceModels.ModelForCortexM3 -Reference STM32L152 ### ### Add compilation phases, in order ### #-CompilationPhaseDisabled ReduceNumberOfTemporaries #-CompilationPhaseDisabled TransformFinallyBlocksIntoTryBlocks #-CompilationPhaseDisabled ApplyClassExtensions #-CompilationPhaseDisabled PrepareImplementationOfInternalMethods #-CompilationPhaseDisabled CrossReferenceTypeSystem #-CompilationPhaseDisabled ApplyConfigurationSettings -CompilationPhaseDisabled ResourceManagerOptimizations #-CompilationPhaseDisabled HighLevelTransformations #-CompilationPhaseDisabled PropagateCompilationConstraints #-CompilationPhaseDisabled ComputeCallsClosure #-CompilationPhaseDisabled EstimateTypeSystemReduction #-CompilationPhaseDisabled CompleteImplementationOfInternalMethods #-CompilationPhaseDisabled ReduceTypeSystem -CompilationPhaseDisabled PrepareExternalMethods #-CompilationPhaseDisabled DetectNonImplementedInternalCalls #-CompilationPhaseDisabled OrderStaticConstructors #-CompilationPhaseDisabled LayoutTypes #-CompilationPhaseDisabled HighLevelToMidLevelConversion #-CompilationPhaseDisabled FromImplicitToExplicitExceptions #-CompilationPhaseDisabled ReferenceCountingGarbageCollection -CompilationPhaseDisabled MidLevelToLowLevelConversion -CompilationPhaseDisabled ConvertUnsupportedOperatorsToMethodCalls -CompilationPhaseDisabled ExpandAggregateTypes -CompilationPhaseDisabled SplitComplexOperators -CompilationPhaseDisabled FuseOperators #-CompilationPhaseDisabled Optimizations -CompilationPhaseDisabled ConvertToSSA -CompilationPhaseDisabled PrepareForRegisterAllocation -CompilationPhaseDisabled CollectRegisterAllocationConstraints -CompilationPhaseDisabled AllocateRegisters #-CompilationPhaseDisabled GenerateImage #-CompilationPhaseDisabled Done ### ### The program to compile. ### ..\..\..\..\ZeligBuild\Target\bin\Debug\Microsoft.Zelig.Test.mbed.Simple.exe ### ### Where to put the results. ### -OutputName Microsoft.Zelig.Test.mbed.Simple -OutputDir ..\..\..\..\LLVM2IR_results\mbed\simple -DumpIR #-DumpIRpre #-DumpIRpost #-DumpIRXML -DumpLLVMIR #-ReloadState -DumpLLVMIR_TextRepresentation -MaxProcs 8 -NoSDK ================================================ FILE: Samples/SpiDisplay/SpiDisplay/Native/pch.h ================================================ ================================================ FILE: Samples/SpiDisplay/SpiDisplay.sln ================================================  Microsoft Visual Studio Solution File, Format Version 12.00 # Visual Studio 14 VisualStudioVersion = 14.0.23107.0 MinimumVisualStudioVersion = 10.0.40219.1 Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "Native", "SpiDisplay\Native\Native.vcxproj", "{D8DCA8C9-9D56-4F97-B5FA-D26ED0944400}" EndProject Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Managed", "SpiDisplay\Managed\Managed.csproj", "{2F9DF480-AFDB-482D-87BB-5CB82E03A43F}" EndProject Global GlobalSection(SolutionConfigurationPlatforms) = preSolution Debug|Any CPU = Debug|Any CPU Debug|ARM = Debug|ARM Release|Any CPU = Release|Any CPU Release|ARM = Release|ARM EndGlobalSection GlobalSection(ProjectConfigurationPlatforms) = postSolution {D8DCA8C9-9D56-4F97-B5FA-D26ED0944400}.Debug|Any CPU.ActiveCfg = Debug|ARM {D8DCA8C9-9D56-4F97-B5FA-D26ED0944400}.Debug|ARM.ActiveCfg = Debug|ARM {D8DCA8C9-9D56-4F97-B5FA-D26ED0944400}.Debug|ARM.Build.0 = Debug|ARM {D8DCA8C9-9D56-4F97-B5FA-D26ED0944400}.Debug|ARM.Deploy.0 = Debug|ARM {D8DCA8C9-9D56-4F97-B5FA-D26ED0944400}.Release|Any CPU.ActiveCfg = Release|ARM {D8DCA8C9-9D56-4F97-B5FA-D26ED0944400}.Release|ARM.ActiveCfg = Release|ARM {D8DCA8C9-9D56-4F97-B5FA-D26ED0944400}.Release|ARM.Build.0 = Release|ARM {D8DCA8C9-9D56-4F97-B5FA-D26ED0944400}.Release|ARM.Deploy.0 = Release|ARM {2F9DF480-AFDB-482D-87BB-5CB82E03A43F}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {2F9DF480-AFDB-482D-87BB-5CB82E03A43F}.Debug|Any CPU.Build.0 = Debug|Any CPU {2F9DF480-AFDB-482D-87BB-5CB82E03A43F}.Debug|ARM.ActiveCfg = Debug|Any CPU {2F9DF480-AFDB-482D-87BB-5CB82E03A43F}.Debug|ARM.Build.0 = Debug|Any CPU {2F9DF480-AFDB-482D-87BB-5CB82E03A43F}.Release|Any CPU.ActiveCfg = Release|Any CPU {2F9DF480-AFDB-482D-87BB-5CB82E03A43F}.Release|Any CPU.Build.0 = Release|Any CPU {2F9DF480-AFDB-482D-87BB-5CB82E03A43F}.Release|ARM.ActiveCfg = Release|Any CPU {2F9DF480-AFDB-482D-87BB-5CB82E03A43F}.Release|ARM.Build.0 = Release|Any CPU EndGlobalSection GlobalSection(SolutionProperties) = preSolution HideSolutionNode = FALSE EndGlobalSection EndGlobal ================================================ FILE: VisualStudio/LlilumApplicationType/Llilum/1.0/1033/AndroidDebugger.xml ================================================  FEEA6E9D-77D8-423F-9EDE-3970CBB76125 0x400 AndroidDeviceID ================================================ FILE: VisualStudio/LlilumApplicationType/Llilum/1.0/1033/Llilum.xml ================================================ ================================================ FILE: VisualStudio/LlilumApplicationType/Llilum/1.0/1033/ar.xml ================================================  ================================================ FILE: VisualStudio/LlilumApplicationType/Llilum/1.0/1033/as.xml ================================================  ================================================ FILE: VisualStudio/LlilumApplicationType/Llilum/1.0/1033/clang.xml ================================================  ================================================ FILE: VisualStudio/LlilumApplicationType/Llilum/1.0/1033/clanglink.xml ================================================  ================================================ FILE: VisualStudio/LlilumApplicationType/Llilum/1.0/1033/general_android.xml ================================================  ================================================ FILE: VisualStudio/LlilumApplicationType/Llilum/1.0/1033/general_makefile_android.xml ================================================  ================================================ FILE: VisualStudio/LlilumApplicationType/Llilum/1.0/1033/nmake_android.xml ================================================ ================================================ FILE: VisualStudio/LlilumApplicationType/Llilum/1.0/Android.Common.props ================================================ x64 x86 Native32Bit true false $(IntermediateOutputPath) $(Platform)\$(Configuration)\ $(IntDir) $(SolutionDir)$(Platform)\$(Configuration)\ false false Unicode <_PlatformToolsetShortNameFor_Clang_3_4>$(TargetOsAndVersion) <_PlatformToolsetFriendlyNameFor_Clang_3_4 Condition="'$(_PlatformToolsetFriendlyNameFor_Clang_3_4)' == ''">Clang 3.4 <_PlatformToolsetShortNameFor_Gcc>$(TargetOsAndVersion) <_PlatformToolsetFriendlyNameFor_Gcc Condition="'$(_PlatformToolsetFriendlyNameFor_Gcc)' == ''">GCC $(MSBuildProjectName) *.bin;*.hex;*.lst;*.d;*.tlog;$(ExtensionsToDeleteOnClean) true true true "$(VS_NdkRoot)\ndk-build.cmd" "$(VS_NdkRoot)\ndk-build.cmd" -B "$(VS_NdkRoot)\ndk-build.cmd" clean true true .so library lib$(RootNamespace) true .a staticlibrary lib$(RootNamespace) VCInstallDir_is_not_defined WindowsSdkDir_is_not_defined <_CheckDev11ToolsInstalled>false Performing Custom Build Tools true false $(TLogLocation) true $(AcceptableNonZeroExitCodes) Performing Custom Build Step false true false true true EnableAllWarnings FullDebug None NDEBUG;%(PreprocessorDefinitions) Disabled MinSize $(IntDir) Disabled false gnu99 gnu++98 NotUsing $(IntDir)%(filename).o Default false false false true $(IntDir) CompileAsCpp true true true false false false false false false false true $(OutDir)$(TargetName)$(TargetExt) true false $(OutDir)$(TargetName)$(TargetExt) Replacement true --strip-unneeded $(StripOptions) false LlilumDebugger false false BreadthFirst {F8BBB05E-FBD0-4B36-8C17-0B3F79AD4F01} $(NMakeIncludeSearchPath);$(VS_NDKRoot)\platforms\$(AndroidAPILevel)\arch-$(Platform)\usr\include;$(VS_NDKRoot)\sources\android\ndk_helper;$(VS_NDKRoot)\sources\android\cpufeatures;$(VS_NDKRoot)\sources\android\native_app_glue;$(StlIncludeDirectories) ================================================ FILE: VisualStudio/LlilumApplicationType/Llilum/1.0/Android.Common.targets ================================================  %(Link.OutputFile) <_ApkRecipeFile>$(OutDir)$(TargetName)$(TargetExt).recipe Low $(ComputeCompileInputsTargets); FixupCLCompileOptions; %(ClCompile.ForcedIncludeFiles) false EnableAllWarnings CompileAsC CompileAsCpp %(ClCompile.PrecompiledHeaderOutputFileDirectory)\ $([System.IO.Path]::GetFileName('%(ClCompile.PrecompiledHeaderFile)')) %(ClCompile.PrecompiledHeaderFile);%(ClCompile.ForcedIncludeFiles) %(ClCompile.PrecompiledHeaderOutputFileDirectory)%(ClCompile.PrecompiledHeaderOutputFileName) %(ClCompile.PrecompiledHeaderOutputFileDirectory)%(ClCompile.PrecompiledHeaderOutputFileName).gch %(ClCompile.PrecompiledHeaderOutputFileDirectory)%(ClCompile.PrecompiledHeaderOutputFileName);%(ClCompile.ClangForcedIncludeFiles) -mcpu=$(ArmArchitecture) %(AdditionalOptions) $(VCToolArchitecture) true false -mcpu=$(ArmArchitecture) %(AdditionalOptions) -mthumb %(AdditionalOptions) $(VCToolArchitecture) $(IntDir.TrimEnd('\')) -CompilationSetupPath "$(LlilumBoardSupportPackage)" -CompilationSetupPath "$(LlilumSDK)CompilationSetup\Microsoft.Llilum.BoardConfigurations.$(LlilumBoardName).dll" $(AfterBuildLinkTargets);dotbin;dothex;dotlst;size $(BuildCompileTargets);ConvertManagedCode ComputeCLOutputFromManagedCode;$(ComputeLinkInputsTargets) ComputeCLOutputFromManagedCode;$(ComputeLibInputsTargets) $(ToolchainPrefix)ar.exe $(VCToolArchitecture) false <_ObjDirectories Condition="'@(Obj)'!=''">$([System.IO.Path]::GetDirectoryName('%(Obj.fullpath)')) o $(ConfigurationType) $(_ApkRecipeFile) $(_ApkRecipeFile) <_MSBuildProjectReferenceExistent Include="@(_MSBuildProjectReferenceExistent)"> Android $(BeforeBuildCompileTargets); _AssignProjectReferencesPlatformType; $(BuildLinkTargets); _CreateApkRecipeFile; _MarkLastSuccessfulDeployForCleanup; Project PropertySheet File;BrowseObject $(OutDir)\$([System.IO.Path]::GetFileNameWithoutExtension('$(PackagePath)')).lastsuccessfuldeploy ================================================ FILE: VisualStudio/LlilumApplicationType/Llilum/1.0/Android.Makefile.targets ================================================ <_MSBuildProjectReferenceExistent> Android o $(ConfigurationType) false $(OutDir)$(ProjectName).recipe Project PropertySheet File ================================================ FILE: VisualStudio/LlilumApplicationType/Llilum/1.0/Android.NDK.props ================================================ x86 i686-linux-android- arm-none-eabi arm-none-eabi- 4.9.3 $(ToolchainPrebuiltPath)\$(ToolchainName)\lib $(ToolchainPrefix)objcopy $(ToolchainPrefix)objdump $(ToolchainPrefix)size android-arm android-x86 gdbserver $(VS_NdkRoot)\prebuilt\$(GdbPrebuiltTag)\gdbserver\$(GdbServerName) ================================================ FILE: VisualStudio/LlilumApplicationType/Llilum/1.0/Android.STL.props ================================================ <_PropertySheetDisplayName>Use of STL $(VS_NdkRoot)\platforms\$(AndroidAPILevel)\arch-arm\usr\lib\libstdc++.a $(VS_NdkRoot)\platforms\$(AndroidAPILevel)\arch-x86\usr\lib\libstdc++.a stdc++ true $(VS_NdkRoot)\sources\cxx-stl\gabi++\libs\$(TargetArchAbi)\thumb $(VS_NdkRoot)\sources\cxx-stl\gabi++\libs\$(TargetArchAbi)\thumb $(VS_NdkRoot)\sources\cxx-stl\stlport\libs\$(TargetArchAbi)\thumb $(VS_NdkRoot)\sources\cxx-stl\stlport\libs\$(TargetArchAbi)\thumb $(VS_NdkRoot)\sources\cxx-stl\gnu-libstdc++\$(ToolchainVersion)\libs\$(TargetArchAbi)\thumb $(VS_NdkRoot)\sources\cxx-stl\gnu-libstdc++\$(ToolchainVersion)\libs\$(TargetArchAbi)\thumb $(VS_NdkRoot)\sources\cxx-stl\llvm-libc++\libs\$(TargetArchAbi)\thumb $(VS_NdkRoot)\sources\cxx-stl\llvm-libc++\libs\$(TargetArchAbi)\thumb $(UseOfStl) true $(VS_NdkRoot)\sources\cxx-stl\gabi++\libs\$(TargetArchAbi) $(VS_NdkRoot)\sources\cxx-stl\gabi++\libs\$(TargetArchAbi) $(VS_NdkRoot)\sources\cxx-stl\stlport\libs\$(TargetArchAbi) $(VS_NdkRoot)\sources\cxx-stl\stlport\libs\$(TargetArchAbi) $(VS_NdkRoot)\sources\cxx-stl\gnu-libstdc++\$(ToolchainVersion)\libs\$(TargetArchAbi) $(VS_NdkRoot)\sources\cxx-stl\gnu-libstdc++\$(ToolchainVersion)\libs\$(TargetArchAbi) $(VS_NdkRoot)\sources\cxx-stl\llvm-libc++\libs\$(TargetArchAbi) $(VS_NdkRoot)\sources\cxx-stl\llvm-libc++\libs\$(TargetArchAbi) $(UseOfStl) true $(StlLibraryPath)\lib$(StlLibraryName).a $(StlLibraryPath)\lib$(StlLibraryName).so $(VS_NdkRoot)\sources\cxx-stl\system\include $(VS_NdkRoot)\sources\cxx-stl\gabi++\include $(VS_NdkRoot)\sources\cxx-stl\stlport\stlport;$(VS_NdkRoot)sources\cxx-stl\gabi++\include $(VS_NdkRoot)\sources\cxx-stl\gnu-libstdc++\$(ToolchainVersion)\include;$(VS_NdkRoot)\sources\cxx-stl\gnu-libstdc++\$(ToolchainVersion)\libs\$(TargetArchAbi)\include;$(VS_NdkRoot)\sources\cxx-stl\gnu-libstdc++\$(ToolchainVersion)\include\backward $(VS_NdkRoot)\sources\cxx-stl\llvm-libc++\libcxx\include;$(VS_NdkRoot)\sources\cxx-stl\llvm-libc++abi\libcxxabi\include $(VS_NdkRoot)\sources\cxx-stl\llvm-libc++\libcxx\include;$(VS_NdkRoot)\sources\cxx-stl\gabi++\include c++11 false $(StlAdditionalDependencies) $(StlIncludeDirectories) ================================================ FILE: VisualStudio/LlilumApplicationType/Llilum/1.0/Android.Tools.props ================================================ $(Registry:HKEY_CURRENT_USER\SOFTWARE\Microsoft\VisualStudio\SecondaryInstaller\VC@AndroidHome) $(Registry:HKEY_CURRENT_USER\SOFTWARE\Microsoft\VisualStudio\SecondaryInstaller\VC@AntHome) $(Registry:HKEY_CURRENT_USER\SOFTWARE\Microsoft\VisualStudio\SecondaryInstaller\VC@JavaHome) $(Registry:HKEY_CURRENT_USER\SOFTWARE\Microsoft\VisualStudio\SecondaryInstaller\VC@NDKRoot) $(Registry:HKEY_LOCAL_MACHINE\SOFTWARE\Android SDK Tools@Path) $(Registry:HKEY_LOCAL_MACHINE\SOFTWARE\Wow6432Node\Android SDK Tools@Path) $(Registry:HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\VisualStudio\14.0\Setup\VS\SecondaryInstaller\Ant@ANT_HOME) $(Registry:HKEY_LOCAL_MACHINE\SOFTWARE\Wow6432Node\Microsoft\VisualStudio\14.0\Setup\VS\SecondaryInstaller\Ant@ANT_HOME) $(Registry:HKEY_LOCAL_MACHINE\SOFTWARE\JavaSoft\Java Development Kit\1.7\@JavaHome) $(Registry:HKEY_LOCAL_MACHINE\SOFTWARE\Wow6432Node\JavaSoft\Java Development Kit\1.7\@JavaHome) $(Registry:HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\VisualStudio\14.0\Setup\VS\SecondaryInstaller\AndroidNDK@NDK_HOME) $(Registry:HKEY_LOCAL_MACHINE\SOFTWARE\Wow6432Node\Microsoft\VisualStudio\14.0\Setup\VS\SecondaryInstaller\AndroidNDK@NDK_HOME) $(VS_NdkRoot)\Platforms $(VS_AndroidHome)\Platforms High 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 $(DefaultAndroidAPILevelNumber) $(AndroidAPILevelNumber).0 Cupcake 1.5 Donut 1.6 Eclair 2.0 Eclair 2.0.1 Eclair 2.1 Froyo 2.2.x Gingerbread 2.3 - 2.3.2 Gingerbread 2.3.3 - 2.3.7 Honeycomb 3.0 Honeycomb 3.1 Honeycomb 3.2.x Ice Cream Sandwich 4.0.1 - 4.0.2 Ice Cream Sandwich 4.0.3 - 4.0.4 Jelly Bean 4.1.x Jelly Bean 4.2.x Jelly Bean 4.3.x KitKat 4.4 - 4.4.4 Lollipop 5.0 - 5.0.2 ================================================ FILE: VisualStudio/LlilumApplicationType/Llilum/1.0/Default.props ================================================  $(VCTargetsPath)\Application Type\$(ApplicationType)\$(ApplicationTypeRevision)\ Gcc Gcc $(AndroidCommonTargetsPath)\Android.NDK.Props android-19 19 gnustl_static DynamicLibrary armv7-m armv6-m;armv7-ar;armv7e-m;armv7-m;cortex-m7;cortex-m3;cortex-m4 $(MSBuildExtensionsPath)\Microsoft.Cpp\v4.0\V140\Application Type\Llilum\1.0\ $(LLILUM_SDK) $(LLILUM_LLVM)build\x64\Debug\bin\ $(LlilumSDK)mbed\ LPC1768 TARGET_LPC1768 TARGET_NXP TOOLCHAIN_GCC_ARM TARGET_LPC176X TARGET_MBED_LPC1768 $(SolutionName) $(LLILUM_GCC)\bin\ $(OutDir)\$(LlilumOutputName).bin $(LlilumSDK)os_layer\ $(LlilumSDK)\bin\Microsoft.Zelig.Compiler.exe $(MSBuildProjectDirectory)\mbed_simple_$(LlilumBoardName).FrontEndConfig ================================================ FILE: VisualStudio/LlilumApplicationType/Llilum/1.0/Platforms/ARM/Platform.Default.props ================================================  ARM ARM ARM armeabi-v7a Thumb ================================================ FILE: VisualStudio/LlilumApplicationType/Llilum/1.0/Platforms/ARM/Platform.props ================================================  <_PlatformFolder>$(MSBuildThisFileDirectory) ================================================ FILE: VisualStudio/LlilumApplicationType/Llilum/1.0/Platforms/ARM/Platform.targets ================================================  ================================================ FILE: VisualStudio/LlilumApplicationType/Llilum/1.0/Platforms/ARM/PlatformToolsets/Gcc/ImportAfter/armasm.props ================================================ $(ToolchainPrefix)as $(IntDir)%(FileName).o --gen-debug -mcpu=cortex-m3 -mthumb false as [AllOptions] [AdditionalOptions] [Inputs] Assembling %(Identity)... ArmAssemble ================================================ FILE: VisualStudio/LlilumApplicationType/Llilum/1.0/Platforms/ARM/PlatformToolsets/Gcc/ImportAfter/armasm.targets ================================================ $(ComputeLinkInputsTargets); ComputeARMASMOutput; $(ComputeLibInputsTargets); ComputeARMASMOutput; false @(ArmAssemble, '|') ================================================ FILE: VisualStudio/LlilumApplicationType/Llilum/1.0/Platforms/ARM/PlatformToolsets/Gcc/Toolset.props ================================================  $(ToolchainPrefix)gcc.exe true false 4.9.3 $(ToolchainPrebuiltPath)\bin;$(LlilumLLVM);$(ExecutablePath) $(ToolchainPrebuiltPath)\$(ToolchainName)\include\c++\$(ToolchainVersion)\$(ToolchainName)\$(ArmArchitecture);$(ToolchainPrebuiltPath)\$(ToolchainName)\include\c++\$(ToolchainVersion)\$(ToolchainName);$(ToolchainPrebuiltPath)\$(ToolchainName)\include\c++\$(ToolchainVersion);$(ToolchainPrebuiltPath)\$(ToolchainName)\include;$(ToolchainPrebuiltPath)\lib\gcc\$(ToolchainName)\$(GccVersion)\include-fixed;$(ToolchainPrebuiltPath)\lib\gcc\$(ToolchainName)\$(GccVersion)\include $(ToolchainPrebuiltPath)\lib\gcc\$(ToolchainName)\$(GccVersion)\include;$(MSBuildToolsPath);$(MSBuildFrameworkToolsPath);$(MSBuild_ExecutablePath) $(StlIncludeDirectories);%(AdditionalIncludeDirectories) $(ThumbMode) false $(StlLibraryName);%(LibraryDependencies) $(ToolchainPrebuiltPath)\lib\gcc\$(ToolchainName)\$(GccVersion)\$(ArmArchitecture);$(StlLibraryPath);%(AdditionalLibraryDirectories) %(SharedLibrarySearchPath) ================================================ FILE: VisualStudio/LlilumApplicationType/Llilum/1.0/Platforms/ARM/PlatformToolsets/Gcc/Toolset.targets ================================================  false <_ApplicableDebuggers>Desktop ================================================ FILE: VisualStudio/LlilumApplicationType/Llilum/1.0/Platforms/Llilum_K64F.props ================================================  $(LlilumSDK)mbed\ TARGET_K64F TARGET_Freescale TOOLCHAIN_GCC_ARM TARGET_KPSDK_MCUS TARGET_MCU_K64F cortex-m4 $(LlilumTargetDirK64F)$(LlilumTargetBoardK64F)/$(LlilumTargetBrandK64F)/$(LlilumTargetClassK64F)/ $(LlilumSDK)lwip\lwip;$(LlilumSDK)lwip\lwip\include;$(LlilumSDK)lwip\lwip\include\ipv4;$(LlilumSDK)lwip\lwip\include\ipv4\lwip;$(LlilumSDK)lwip\lwip\include\lwip;$(LlilumSDK)lwip\lwip\include\netif;$(LlilumSDK)lwip\lwip\netif;$(LlilumSDK)lwip/lwip/netif/ppp;$(LlilumSDK)lwip/lwip/api;$(LlilumSDK)lwip/lwip/core;$(LlilumSDK)lwip/lwip/core/ipv4;$(LlilumSDK)lwip/lwip/core/snmp;$(LlilumSDK)lwip/lwip-eth;$(LlilumSDK)lwip/lwip-eth/arch;$(LlilumSDK)lwip/lwip-sys;$(LlilumSDK)lwip/lwip-sys/arch;$(LlilumSDK)/mbed-rtos/llos;$(LlilumSDK)mbed-rtos/llos/TARGET_CORTEX_M;$(LlilumSDK)lwip/lwip-eth/arch/TARGET_Freescale;$(LlilumSDK)mbed-rtos\rtx\TARGET_CORTEX_M -mcpu=$(LlilumTargetBoardArchitectureK64F) -mfloat-abi=softfp $(LlilumTargetDirK64F);$(LlilumTargetDirK64F)$(LlilumTargetBoardK64F);$(LlilumTargetDirK64F)$(LlilumTargetBoardK64F)/$(LlilumTargetToolchainK64F);$(LlilumTargetDirK64F)$(LlilumTargetBoardK64F)/$(LlilumTargetBrandK64F);$(LlilumTargetDirK64F)$(LlilumTargetBoardK64F)/$(LlilumTargetBrandK64F)/$(LlilumTargetClassK64F);$(LlilumTargetDirK64F)$(LlilumTargetBoardK64F)/$(LlilumTargetBrandK64F)/$(LlilumTargetClassK64F)/$(LlilumTargetBoardMbedK64F);$(LlilumSDK)ARM_GCC\arm-none-eabi\include;$(LlilumTargetDivergingDirectoryK64F)TARGET_MCU_K64F\device\device\MK64F12;$(LlilumTargetDivergingDirectoryK64F)TARGET_MCU_K64F\device\device;$(LlilumTargetDivergingDirectoryK64F)TARGET_MCU_K64F\device\MK64F12;$(LlilumTargetDivergingDirectoryK64F)TARGET_MCU_K64F\MK64F12;$(LlilumTargetDivergingDirectoryK64F)TARGET_MCU_K64F\TARGET_FRDM;$(LlilumTargetDivergingDirectoryK64F)TARGET_KPSDK_CODE\utilities;$(LlilumTargetDivergingDirectoryK64F)TARGET_KPSDK_CODE\hal\wdog;$(LlilumTargetDivergingDirectoryK64F)TARGET_KPSDK_CODE\hal\uart;$(LlilumTargetDivergingDirectoryK64F)TARGET_KPSDK_CODE\hal\smc;$(LlilumTargetDivergingDirectoryK64F)TARGET_KPSDK_CODE\hal\sim;$(LlilumTargetDivergingDirectoryK64F)TARGET_KPSDK_CODE\hal\sdhc;$(LlilumTargetDivergingDirectoryK64F)TARGET_KPSDK_CODE\hal\sai;$(LlilumTargetDivergingDirectoryK64F)TARGET_KPSDK_CODE\hal\rtc;$(LlilumTargetDivergingDirectoryK64F)TARGET_KPSDK_CODE\hal\rcm;$(LlilumTargetDivergingDirectoryK64F)TARGET_KPSDK_CODE\hal\port;$(LlilumTargetDivergingDirectoryK64F)TARGET_KPSDK_CODE\hal\pmc;$(LlilumTargetDivergingDirectoryK64F)TARGET_KPSDK_CODE\hal\pit;$(LlilumTargetDivergingDirectoryK64F)TARGET_KPSDK_CODE\hal\pdb;$(LlilumTargetDivergingDirectoryK64F)TARGET_KPSDK_CODE\hal\osc;$(LlilumTargetDivergingDirectoryK64F)TARGET_KPSDK_CODE\hal\mpu;$(LlilumTargetDivergingDirectoryK64F)TARGET_KPSDK_CODE\hal\mcg;$(LlilumTargetDivergingDirectoryK64F)TARGET_KPSDK_CODE\hal\lpuart;$(LlilumTargetDivergingDirectoryK64F)TARGET_KPSDK_CODE\hal\lptmr;$(LlilumTargetDivergingDirectoryK64F)TARGET_KPSDK_CODE\hal\llwu;$(LlilumTargetDivergingDirectoryK64F)TARGET_KPSDK_CODE\hal\i2c;$(LlilumTargetDivergingDirectoryK64F)TARGET_KPSDK_CODE\hal\gpio;$(LlilumTargetDivergingDirectoryK64F)TARGET_KPSDK_CODE\hal\flextimer;$(LlilumTargetDivergingDirectoryK64F)TARGET_KPSDK_CODE\hal\enet;$(LlilumTargetDivergingDirectoryK64F)TARGET_KPSDK_CODE\hal\edma;$(LlilumTargetDivergingDirectoryK64F)TARGET_KPSDK_CODE\hal\dspi;$(LlilumTargetDivergingDirectoryK64F)TARGET_KPSDK_CODE\hal\dmamux;$(LlilumTargetDivergingDirectoryK64F)TARGET_KPSDK_CODE\hal\dac;$(LlilumTargetDivergingDirectoryK64F)TARGET_KPSDK_CODE\hal\can;$(LlilumTargetDivergingDirectoryK64F)TARGET_KPSDK_CODE\hal\adc;$(LlilumTargetDivergingDirectoryK64F)TARGET_KPSDK_CODE\hal;$(LlilumTargetDivergingDirectoryK64F)TARGET_KPSDK_CODE\drivers\pit\common;$(LlilumTargetDivergingDirectoryK64F)TARGET_KPSDK_CODE\drivers\pit;$(LlilumTargetDivergingDirectoryK64F)TARGET_KPSDK_CODE\drivers\interrupt;$(LlilumTargetDivergingDirectoryK64F)TARGET_KPSDK_CODE\drivers\enet;$(LlilumTargetDivergingDirectoryK64F)TARGET_KPSDK_CODE\drivers\clock;$(LlilumTargetDivergingDirectoryK64F)TARGET_KPSDK_CODE\drivers;$(LlilumTargetDivergingDirectoryK64F)TARGET_KPSDK_CODE\common\phyksz8081;$(LlilumTargetDivergingDirectoryK64F)TARGET_KPSDK_CODE\common;$(LlilumTargetDivergingDirectoryK64F)TARGET_KPSDK_CODE;$(LlilumTargetDivergingDirectoryK64F)TARGET_MCU_K64F\device;$(LlilumTargetDirK64F)\EthernetInterface;$(LlilumLwipIncludeDirs) TARGET_K64F;TARGET_M4;TARGET_CORTEX_M;TARGET_Freescale;TARGET_KPSDK_MCUS;TARGET_KPSDK_CODE;TARGET_MCU_K64F;TARGET_FRDM;TOOLCHAIN_GCC_ARM;TOOLCHAIN_GCC;__CORTEX_M4;ARM_MATH_CM4;__FPU_PRESENT=1;MBED_BUILD_TIMESTAMP=1435855534.71;__MBED__=1;CPU_MK64FN1M0VMD12;FSL_RTOS_MBED;TARGET_FF_ARDUINO; $(LlilumTargetDirK64F)$(LlilumTargetBoardK64F)/$(LlilumTargetToolchainK64F)/board.o;$(LlilumTargetDirK64F)$(LlilumTargetBoardK64F)/$(LlilumTargetToolchainK64F)/cmsis_nvic.o;$(LlilumTargetDirK64F)$(LlilumTargetBoardK64F)/$(LlilumTargetToolchainK64F)/retarget.o;$(LlilumTargetDirK64F)$(LlilumTargetBoardK64F)/$(LlilumTargetToolchainK64F)/system_MK64F12.o $(LlilumTargetDirK64F)$(LlilumTargetBoardK64F)/$(LlilumTargetToolchainK64F);$(LlilumSDK)lwip\lwip\lib; -T"$(LlilumTargetDirK64F)$(LlilumTargetBoardK64F)/$(LlilumTargetToolchainK64F)/K64FN1M0xxx12.ld" -Wl,--gc-sections --specs=nano.specs -u _printf_float -u _scanf_float -Wl,--wrap,main lwipsysarch;mbedeth;lwIPeth;lwip;mbed;stdc++;supc++;m;c;gcc;nosys 0x800 0x10000 $(LlilumTargetDirK64F) $(LlilumTargetBoardK64F) $(LlilumTargetBrandK64F) $(LlilumTargetToolchainK64F) $(LlilumTargetClassK64F) $(LlilumTargetBoardMbedK64F) $(LlilumTargetBoardArchitectureK64F) $(LlilumTargetDivergingDirectoryK64F) $(LlilumLwipIncludeDirs) $(LlilumClAdditionalOptionsK64F) $(LlilumClAdditionalIncludesK64F) $(LlilumClPreprocessorDefsK64F) $(LlilumLinkAdditionalDepsK64F) $(LlilumLinkAdditionalLibDirsK64F) $(LlilumLinkAdditionalOptionsK64F) $(LlilumLinkLibDepsK64F) $(LlilumAsmAdditionalOptionsK64F) $(LlilumStackSizeK64F) $(LlilumHeapSizeK64F) ================================================ FILE: VisualStudio/LlilumApplicationType/Llilum/1.0/Platforms/Llilum_LPC1768.props ================================================  $(LlilumSDK)mbed\ TARGET_LPC1768 TARGET_NXP TOOLCHAIN_GCC_ARM TARGET_LPC176X TARGET_MBED_LPC1768 cortex-m3 $(LlilumTargetDirLPC1768)EthernetInterface;$(LlilumSDK)lwip\lwip;$(LlilumSDK)lwip\lwip\include;$(LlilumSDK)lwip\lwip\include\ipv4;$(LlilumSDK)lwip\lwip\include\ipv4\lwip;$(LlilumSDK)lwip\lwip\include\lwip;$(LlilumSDK)lwip\lwip\include\netif;$(LlilumSDK)lwip\lwip\netif;$(LlilumSDK)lwip/lwip/netif/ppp;$(LlilumSDK)lwip/lwip/api;$(LlilumSDK)lwip/lwip/core;$(LlilumSDK)lwip/lwip/core/ipv4;$(LlilumSDK)lwip/lwip/core/snmp;$(LlilumSDK)lwip/lwip-eth;$(LlilumSDK)lwip/lwip-eth/arch;$(LlilumSDK)lwip/lwip-sys;$(LlilumSDK)lwip/lwip-sys/arch;$(LlilumSDK)mbed-rtos/llos;$(LlilumSDK)mbed-rtos/llos/TARGET_CORTEX_M;$(LlilumSDK)lwip/lwip-eth/arch/TARGET_NXP -mcpu=$(LlilumTargetBoardArchitectureLPC1768) $(LlilumLwipIncludeDirs);$(LlilumTargetDirLPC1768);$(LlilumTargetDirLPC1768)$(LlilumTargetBoardLPC1768);$(LlilumTargetDirLPC1768)$(LlilumTargetBoardLPC1768)/$(LlilumTargetToolchainLPC1768);$(LlilumTargetDirLPC1768)$(LlilumTargetBoardLPC1768)/$(LlilumTargetBrandLPC1768);$(LlilumTargetDirLPC1768)$(LlilumTargetBoardLPC1768)/$(LlilumTargetBrandLPC1768)/$(LlilumTargetClassLPC1768);$(LlilumTargetDirLPC1768)$(LlilumTargetBoardLPC1768)/$(LlilumTargetBrandLPC1768)/$(LlilumTargetClassLPC1768)/$(LlilumTargetBoardMbedLPC1768);$(LlilumSDK)ARM_GCC\arm-none-eabi\include TARGET_LPC1768;TARGET_M3;TARGET_CORTEX_M;TARGET_NXP;TARGET_LPC176X;TARGET_MBED_LPC1768;TOOLCHAIN_GCC_ARM;TOOLCHAIN_GCC;__CORTEX_M3;ARM_MATH_CM3;MBED_BUILD_TIMESTAMP=1435688844.64;__MBED__=1 $(LlilumTargetDirLPC1768)$(LlilumTargetBoardLPC1768)/$(LlilumTargetToolchainLPC1768)/board.o;$(LlilumTargetDirLPC1768)$(LlilumTargetBoardLPC1768)/$(LlilumTargetToolchainLPC1768)/cmsis_nvic.o;$(LlilumTargetDirLPC1768)$(LlilumTargetBoardLPC1768)/$(LlilumTargetToolchainLPC1768)/retarget.o;$(LlilumTargetDirLPC1768)$(LlilumTargetBoardLPC1768)/$(LlilumTargetToolchainLPC1768)/system_LPC17xx.o $(LlilumTargetDirLPC1768)$(LlilumTargetBoardLPC1768)/$(LlilumTargetToolchainLPC1768) -T"$(LlilumTargetDirLPC1768)$(LlilumTargetBoardLPC1768)/$(LlilumTargetToolchainLPC1768)/LPC1768.ld" -Wl,--gc-sections --specs=nano.specs -u _printf_float -u _scanf_float -Wl,--wrap,main mbed;stdc++;supc++;m;c;gcc;nosys 0x800 0x6A00 0xC00 $(LlilumTargetDirLPC1768) $(LlilumTargetBoardLPC1768) $(LlilumTargetBrandLPC1768) $(LlilumTargetToolchainLPC1768) $(LlilumTargetClassLPC1768) $(LlilumTargetBoardMbedLPC1768) $(LlilumTargetBoardArchitectureLPC1768) $(LlilumLwipIncludeDirs) $(LlilumClAdditionalOptionsLPC1768) $(LlilumClAdditionalIncludesLPC1768) $(LlilumClPreprocessorDefsLPC1768) $(LlilumLinkAdditionalDepsLPC1768) $(LlilumLinkAdditionalLibDirsLPC1768) $(LlilumLinkAdditionalOptionsLPC1768) $(LlilumLinkLibDepsLPC1768) $(LlilumAsmAdditionalOptionsLPC1768) $(LlilumStackSizeLPC1768) $(LlilumHeapSizeLPC1768) ================================================ FILE: VisualStudio/LlilumApplicationType/Llilum/1.0/Platforms/Llilum_STM32F091.props ================================================  $(LlilumSDK)mbed\ TARGET_NUCLEO_F401RE TARGET_STM TOOLCHAIN_GCC_ARM TARGET_STM32F4 TARGET_NUCLEO_F401RE cortex-m4 $(LlilumTargetDirLPC1768)EthernetInterface;$(LlilumSDK)lwip\lwip;$(LlilumSDK)lwip\lwip\include;$(LlilumSDK)lwip\lwip\include\ipv4;$(LlilumSDK)lwip\lwip\include\ipv4\lwip;$(LlilumSDK)lwip\lwip\include\lwip;$(LlilumSDK)lwip\lwip\include\netif;$(LlilumSDK)lwip\lwip\netif;$(LlilumSDK)lwip/lwip/netif/ppp;$(LlilumSDK)lwip/lwip/api;$(LlilumSDK)lwip/lwip/core;$(LlilumSDK)lwip/lwip/core/ipv4;$(LlilumSDK)lwip/lwip/core/snmp;$(LlilumSDK)lwip/lwip-eth;$(LlilumSDK)lwip/lwip-eth/arch;$(LlilumSDK)lwip/lwip-sys;$(LlilumSDK)lwip/lwip-sys/arch;$(LlilumSDK)mbed-rtos/llos;$(LlilumSDK)mbed-rtos/llos/TARGET_CORTEX_M;$(LlilumSDK)lwip/lwip-eth/arch/TARGET_NXP stlink-v2-1.cfg st_nucleo_f4.cfg -mcpu=$(LlilumTargetBoardArchitectureSTM32F091) -mthumb -mfpu=fpv4-sp-d16 -mfloat-abi=softfp $(LlilumLwipIncludeDirs);$(LlilumTargetDirSTM32F091);$(LlilumTargetDirSTM32F091)$(LlilumTargetBoardSTM32F091);$(LlilumTargetDirSTM32F091)$(LlilumTargetBoardSTM32F091)/$(LlilumTargetToolchainSTM32F091);$(LlilumTargetDirSTM32F091)$(LlilumTargetBoardSTM32F091)/$(LlilumTargetBrandSTM32F091);$(LlilumTargetDirSTM32F091)$(LlilumTargetBoardSTM32F091)/$(LlilumTargetBrandSTM32F091)/$(LlilumTargetClassSTM32F091);$(LlilumTargetDirSTM32F091)$(LlilumTargetBoardSTM32F091)/$(LlilumTargetBrandSTM32F091)/$(LlilumTargetClassSTM32F091)/$(LlilumTargetBoardMbedSTM32F091); TARGET_FF_ARDUINO;TOOLCHAIN_GCC_ARM;TARGET_NUCLEO_F401RE;__CORTEX_M4;TARGET_CORTEX_M;__FPU_PRESENT=1;__MBED__=1;TARGET_M4;TARGET_FF_MORPHO;TARGET_STM;TARGET_STM32F4;TOOLCHAIN_GCC;TARGET_STM32F091RE;ARM_MATH_CM4;MBED_BUILD_TIMESTAMP=1450373147.1 $(LlilumTargetDirSTM32F091)$(LlilumTargetBoardSTM32F091)/$(LlilumTargetToolchainSTM32F091)/stm32f4xx_hal_flash_ramfunc.o;$(LlilumTargetDirSTM32F091)$(LlilumTargetBoardSTM32F091)/$(LlilumTargetToolchainSTM32F091)/board.o;$(LlilumTargetDirSTM32F091)$(LlilumTargetBoardSTM32F091)/$(LlilumTargetToolchainSTM32F091)/cmsis_nvic.o;$(LlilumTargetDirSTM32F091)$(LlilumTargetBoardSTM32F091)/$(LlilumTargetToolchainSTM32F091)/hal_tick.o;$(LlilumTargetDirSTM32F091)$(LlilumTargetBoardSTM32F091)/$(LlilumTargetToolchainSTM32F091)/mbed_overrides.o;$(LlilumTargetDirSTM32F091)$(LlilumTargetBoardSTM32F091)/$(LlilumTargetToolchainSTM32F091)/retarget.o ;$(LlilumTargetDirSTM32F091)$(LlilumTargetBoardSTM32F091)/$(LlilumTargetToolchainSTM32F091)/stm32f4xx_hal.o;$(LlilumTargetDirSTM32F091)$(LlilumTargetBoardSTM32F091)/$(LlilumTargetToolchainSTM32F091)/stm32f4xx_hal_adc.o;$(LlilumTargetDirSTM32F091)$(LlilumTargetBoardSTM32F091)/$(LlilumTargetToolchainSTM32F091)/stm32f4xx_hal_adc_ex.o;$(LlilumTargetDirSTM32F091)$(LlilumTargetBoardSTM32F091)/$(LlilumTargetToolchainSTM32F091)/stm32f4xx_hal_can.o;$(LlilumTargetDirSTM32F091)$(LlilumTargetBoardSTM32F091)/$(LlilumTargetToolchainSTM32F091)/stm32f4xx_hal_cec.o;$(LlilumTargetDirSTM32F091)$(LlilumTargetBoardSTM32F091)/$(LlilumTargetToolchainSTM32F091)/stm32f4xx_hal_cortex.o;$(LlilumTargetDirSTM32F091)$(LlilumTargetBoardSTM32F091)/$(LlilumTargetToolchainSTM32F091)/stm32f4xx_hal_crc.o;$(LlilumTargetDirSTM32F091)$(LlilumTargetBoardSTM32F091)/$(LlilumTargetToolchainSTM32F091)/stm32f4xx_hal_cryp.o;$(LlilumTargetDirSTM32F091)$(LlilumTargetBoardSTM32F091)/$(LlilumTargetToolchainSTM32F091)/stm32f4xx_hal_cryp_ex.o;$(LlilumTargetDirSTM32F091)$(LlilumTargetBoardSTM32F091)/$(LlilumTargetToolchainSTM32F091)/stm32f4xx_hal_dac.o;$(LlilumTargetDirSTM32F091)$(LlilumTargetBoardSTM32F091)/$(LlilumTargetToolchainSTM32F091)/stm32f4xx_hal_dac_ex.o;$(LlilumTargetDirSTM32F091)$(LlilumTargetBoardSTM32F091)/$(LlilumTargetToolchainSTM32F091)/stm32f4xx_hal_dcmi.o;$(LlilumTargetDirSTM32F091)$(LlilumTargetBoardSTM32F091)/$(LlilumTargetToolchainSTM32F091)/stm32f4xx_hal_dcmi_ex.o;$(LlilumTargetDirSTM32F091)$(LlilumTargetBoardSTM32F091)/$(LlilumTargetToolchainSTM32F091)/stm32f4xx_hal_dma.o;$(LlilumTargetDirSTM32F091)$(LlilumTargetBoardSTM32F091)/$(LlilumTargetToolchainSTM32F091)/stm32f4xx_hal_dma2d.o;$(LlilumTargetDirSTM32F091)$(LlilumTargetBoardSTM32F091)/$(LlilumTargetToolchainSTM32F091)/stm32f4xx_hal_dma_ex.o;$(LlilumTargetDirSTM32F091)$(LlilumTargetBoardSTM32F091)/$(LlilumTargetToolchainSTM32F091)/stm32f4xx_hal_dsi.o;$(LlilumTargetDirSTM32F091)$(LlilumTargetBoardSTM32F091)/$(LlilumTargetToolchainSTM32F091)/stm32f4xx_hal_eth.o;$(LlilumTargetDirSTM32F091)$(LlilumTargetBoardSTM32F091)/$(LlilumTargetToolchainSTM32F091)/stm32f4xx_hal_flash.o;$(LlilumTargetDirSTM32F091)$(LlilumTargetBoardSTM32F091)/$(LlilumTargetToolchainSTM32F091)/stm32f4xx_hal_flash_ex.o;$(LlilumTargetDirSTM32F091)$(LlilumTargetBoardSTM32F091)/$(LlilumTargetToolchainSTM32F091)/stm32f4xx_hal_fmpi2c_ex.o;$(LlilumTargetDirSTM32F091)$(LlilumTargetBoardSTM32F091)/$(LlilumTargetToolchainSTM32F091)/stm32f4xx_hal_fmpi2c.o;$(LlilumTargetDirSTM32F091)$(LlilumTargetBoardSTM32F091)/$(LlilumTargetToolchainSTM32F091)/stm32f4xx_hal_msp_template.o;$(LlilumTargetDirSTM32F091)$(LlilumTargetBoardSTM32F091)/$(LlilumTargetToolchainSTM32F091)/stm32f4xx_hal_gpio.o;$(LlilumTargetDirSTM32F091)$(LlilumTargetBoardSTM32F091)/$(LlilumTargetToolchainSTM32F091)/stm32f4xx_hal_hash.o;$(LlilumTargetDirSTM32F091)$(LlilumTargetBoardSTM32F091)/$(LlilumTargetToolchainSTM32F091)/stm32f4xx_hal_hash_ex.o;$(LlilumTargetDirSTM32F091)$(LlilumTargetBoardSTM32F091)/$(LlilumTargetToolchainSTM32F091)/stm32f4xx_hal_hcd.o;$(LlilumTargetDirSTM32F091)$(LlilumTargetBoardSTM32F091)/$(LlilumTargetToolchainSTM32F091)/stm32f4xx_hal_i2c.o;$(LlilumTargetDirSTM32F091)$(LlilumTargetBoardSTM32F091)/$(LlilumTargetToolchainSTM32F091)/stm32f4xx_hal_i2c_ex.o;$(LlilumTargetDirSTM32F091)$(LlilumTargetBoardSTM32F091)/$(LlilumTargetToolchainSTM32F091)/stm32f4xx_hal_i2s.o;$(LlilumTargetDirSTM32F091)$(LlilumTargetBoardSTM32F091)/$(LlilumTargetToolchainSTM32F091)/stm32f4xx_hal_i2s_ex.o;$(LlilumTargetDirSTM32F091)$(LlilumTargetBoardSTM32F091)/$(LlilumTargetToolchainSTM32F091)/stm32f4xx_hal_irda.o;$(LlilumTargetDirSTM32F091)$(LlilumTargetBoardSTM32F091)/$(LlilumTargetToolchainSTM32F091)/stm32f4xx_hal_iwdg.o;$(LlilumTargetDirSTM32F091)$(LlilumTargetBoardSTM32F091)/$(LlilumTargetToolchainSTM32F091)/stm32f4xx_hal_lptim.o;$(LlilumTargetDirSTM32F091)$(LlilumTargetBoardSTM32F091)/$(LlilumTargetToolchainSTM32F091)/stm32f4xx_hal_ltdc.o;$(LlilumTargetDirSTM32F091)$(LlilumTargetBoardSTM32F091)/$(LlilumTargetToolchainSTM32F091)/stm32f4xx_hal_ltdc_ex.o;$(LlilumTargetDirSTM32F091)$(LlilumTargetBoardSTM32F091)/$(LlilumTargetToolchainSTM32F091)/stm32f4xx_hal_smartcard.o;$(LlilumTargetDirSTM32F091)$(LlilumTargetBoardSTM32F091)/$(LlilumTargetToolchainSTM32F091)/stm32f4xx_hal_nand.o;$(LlilumTargetDirSTM32F091)$(LlilumTargetBoardSTM32F091)/$(LlilumTargetToolchainSTM32F091)/stm32f4xx_hal_nor.o;$(LlilumTargetDirSTM32F091)$(LlilumTargetBoardSTM32F091)/$(LlilumTargetToolchainSTM32F091)/stm32f4xx_hal_pccard.o;$(LlilumTargetDirSTM32F091)$(LlilumTargetBoardSTM32F091)/$(LlilumTargetToolchainSTM32F091)/stm32f4xx_hal_pcd.o;$(LlilumTargetDirSTM32F091)$(LlilumTargetBoardSTM32F091)/$(LlilumTargetToolchainSTM32F091)/stm32f4xx_hal_pcd_ex.o;$(LlilumTargetDirSTM32F091)$(LlilumTargetBoardSTM32F091)/$(LlilumTargetToolchainSTM32F091)/stm32f4xx_hal_pwr.o;$(LlilumTargetDirSTM32F091)$(LlilumTargetBoardSTM32F091)/$(LlilumTargetToolchainSTM32F091)/stm32f4xx_hal_pwr_ex.o;$(LlilumTargetDirSTM32F091)$(LlilumTargetBoardSTM32F091)/$(LlilumTargetToolchainSTM32F091)/stm32f4xx_hal_qspi.o;$(LlilumTargetDirSTM32F091)$(LlilumTargetBoardSTM32F091)/$(LlilumTargetToolchainSTM32F091)/stm32f4xx_hal_rcc.o;$(LlilumTargetDirSTM32F091)$(LlilumTargetBoardSTM32F091)/$(LlilumTargetToolchainSTM32F091)/stm32f4xx_hal_rcc_ex.o;$(LlilumTargetDirSTM32F091)$(LlilumTargetBoardSTM32F091)/$(LlilumTargetToolchainSTM32F091)/stm32f4xx_hal_rng.o;$(LlilumTargetDirSTM32F091)$(LlilumTargetBoardSTM32F091)/$(LlilumTargetToolchainSTM32F091)/stm32f4xx_hal_rtc.o;$(LlilumTargetDirSTM32F091)$(LlilumTargetBoardSTM32F091)/$(LlilumTargetToolchainSTM32F091)/stm32f4xx_hal_rtc_ex.o;$(LlilumTargetDirSTM32F091)$(LlilumTargetBoardSTM32F091)/$(LlilumTargetToolchainSTM32F091)/stm32f4xx_hal_sai.o;$(LlilumTargetDirSTM32F091)$(LlilumTargetBoardSTM32F091)/$(LlilumTargetToolchainSTM32F091)/stm32f4xx_hal_sai_ex.o;$(LlilumTargetDirSTM32F091)$(LlilumTargetBoardSTM32F091)/$(LlilumTargetToolchainSTM32F091)/stm32f4xx_hal_sd.o;$(LlilumTargetDirSTM32F091)$(LlilumTargetBoardSTM32F091)/$(LlilumTargetToolchainSTM32F091)/stm32f4xx_hal_sdram.o;$(LlilumTargetDirSTM32F091)$(LlilumTargetBoardSTM32F091)/$(LlilumTargetToolchainSTM32F091)/stm32f4xx_hal_spdifrx.o;$(LlilumTargetDirSTM32F091)$(LlilumTargetBoardSTM32F091)/$(LlilumTargetToolchainSTM32F091)/stm32f4xx_hal_spi.o;$(LlilumTargetDirSTM32F091)$(LlilumTargetBoardSTM32F091)/$(LlilumTargetToolchainSTM32F091)/stm32f4xx_hal_sram.o;$(LlilumTargetDirSTM32F091)$(LlilumTargetBoardSTM32F091)/$(LlilumTargetToolchainSTM32F091)/stm32f4xx_hal_tim.o;$(LlilumTargetDirSTM32F091)$(LlilumTargetBoardSTM32F091)/$(LlilumTargetToolchainSTM32F091)/stm32f4xx_hal_tim_ex.o;$(LlilumTargetDirSTM32F091)$(LlilumTargetBoardSTM32F091)/$(LlilumTargetToolchainSTM32F091)/stm32f4xx_hal_uart.o;$(LlilumTargetDirSTM32F091)$(LlilumTargetBoardSTM32F091)/$(LlilumTargetToolchainSTM32F091)/stm32f4xx_hal_usart.o;$(LlilumTargetDirSTM32F091)$(LlilumTargetBoardSTM32F091)/$(LlilumTargetToolchainSTM32F091)/stm32f4xx_hal_wwdg.o;$(LlilumTargetDirSTM32F091)$(LlilumTargetBoardSTM32F091)/$(LlilumTargetToolchainSTM32F091)/stm32f4xx_ll_fmc.o;$(LlilumTargetDirSTM32F091)$(LlilumTargetBoardSTM32F091)/$(LlilumTargetToolchainSTM32F091)/stm32f4xx_ll_fsmc.o;$(LlilumTargetDirSTM32F091)$(LlilumTargetBoardSTM32F091)/$(LlilumTargetToolchainSTM32F091)/stm32f4xx_ll_sdmmc.o;$(LlilumTargetDirSTM32F091)$(LlilumTargetBoardSTM32F091)/$(LlilumTargetToolchainSTM32F091)/stm32f4xx_ll_usb.o;$(LlilumTargetDirSTM32F091)$(LlilumTargetBoardSTM32F091)/$(LlilumTargetToolchainSTM32F091)/system_stm32f4xx.o $(LlilumTargetDirSTM32F091)$(LlilumTargetBoardSTM32F091)/$(LlilumTargetToolchainSTM32F091) -T"$(LlilumTargetDirSTM32F091)$(LlilumTargetBoardSTM32F091)/$(LlilumTargetToolchainSTM32F091)/STM32F091XE.ld" -Wl,--gc-sections --specs=nano.specs -u _printf_float -u _scanf_float -Wl,--wrap,main mbed;stdc++;supc++;m;c;gcc;nosys 0x800 0x6000 $(LlilumTargetDirSTM32F091) $(LlilumTargetBoardSTM32F091) $(LlilumTargetBrandSTM32F091) $(LlilumTargetToolchainSTM32F091) $(LlilumTargetClassSTM32F091) $(LlilumTargetBoardMbedSTM32F091) $(LlilumTargetBoardArchitectureSTM32F091) $(LlilumLwipIncludeDirs) $(LlilumClAdditionalOptionsSTM32F091) $(LlilumClAdditionalIncludesSTM32F091) $(LlilumClPreprocessorDefsSTM32F091) $(LlilumLinkAdditionalDepsSTM32F091) $(LlilumLinkAdditionalLibDirsSTM32F091) $(LlilumLinkAdditionalOptionsSTM32F091) $(LlilumLinkLibDepsSTM32F091) $(LlilumAsmAdditionalOptionsSTM32F091) $(LlilumStackSizeSTM32F091) $(LlilumHeapSizeSTM32F091) $(LlilumOpenOcdInterfaceCfgSTM32F091) $(LlilumOpenOcdBoardCfgSTM32F091) ================================================ FILE: VisualStudio/LlilumApplicationType/Llilum/1.0/Platforms/Llilum_STM32F401.props ================================================  $(LlilumSDK)mbed\ TARGET_NUCLEO_F401RE TARGET_STM TOOLCHAIN_GCC_ARM TARGET_STM32F4 TARGET_NUCLEO_F401RE cortex-m4 $(LlilumTargetDirLPC1768)EthernetInterface;$(LlilumSDK)lwip\lwip;$(LlilumSDK)lwip\lwip\include;$(LlilumSDK)lwip\lwip\include\ipv4;$(LlilumSDK)lwip\lwip\include\ipv4\lwip;$(LlilumSDK)lwip\lwip\include\lwip;$(LlilumSDK)lwip\lwip\include\netif;$(LlilumSDK)lwip\lwip\netif;$(LlilumSDK)lwip/lwip/netif/ppp;$(LlilumSDK)lwip/lwip/api;$(LlilumSDK)lwip/lwip/core;$(LlilumSDK)lwip/lwip/core/ipv4;$(LlilumSDK)lwip/lwip/core/snmp;$(LlilumSDK)lwip/lwip-eth;$(LlilumSDK)lwip/lwip-eth/arch;$(LlilumSDK)lwip/lwip-sys;$(LlilumSDK)lwip/lwip-sys/arch;$(LlilumSDK)mbed-rtos/llos;$(LlilumSDK)mbed-rtos/llos/TARGET_CORTEX_M;$(LlilumSDK)lwip/lwip-eth/arch/TARGET_NXP stlink-v2-1.cfg st_nucleo_f4.cfg -mcpu=$(LlilumTargetBoardArchitectureSTM32F401) -mthumb -mfpu=fpv4-sp-d16 -mfloat-abi=softfp $(LlilumLwipIncludeDirs);$(LlilumTargetDirSTM32F401);$(LlilumTargetDirSTM32F401)$(LlilumTargetBoardSTM32F401);$(LlilumTargetDirSTM32F401)$(LlilumTargetBoardSTM32F401)/$(LlilumTargetToolchainSTM32F401);$(LlilumTargetDirSTM32F401)$(LlilumTargetBoardSTM32F401)/$(LlilumTargetBrandSTM32F401);$(LlilumTargetDirSTM32F401)$(LlilumTargetBoardSTM32F401)/$(LlilumTargetBrandSTM32F401)/$(LlilumTargetClassSTM32F401);$(LlilumTargetDirSTM32F401)$(LlilumTargetBoardSTM32F401)/$(LlilumTargetBrandSTM32F401)/$(LlilumTargetClassSTM32F401)/$(LlilumTargetBoardMbedSTM32F401); TARGET_FF_ARDUINO;TOOLCHAIN_GCC_ARM;TARGET_NUCLEO_F401RE;__CORTEX_M4;TARGET_CORTEX_M;__FPU_PRESENT=1;__MBED__=1;TARGET_M4;TARGET_FF_MORPHO;TARGET_STM;TARGET_STM32F4;TOOLCHAIN_GCC;TARGET_STM32F401RE;ARM_MATH_CM4;MBED_BUILD_TIMESTAMP=1450373147.1 $(LlilumTargetDirSTM32F401)$(LlilumTargetBoardSTM32F401)/$(LlilumTargetToolchainSTM32F401)/stm32f4xx_hal_flash_ramfunc.o;$(LlilumTargetDirSTM32F401)$(LlilumTargetBoardSTM32F401)/$(LlilumTargetToolchainSTM32F401)/board.o;$(LlilumTargetDirSTM32F401)$(LlilumTargetBoardSTM32F401)/$(LlilumTargetToolchainSTM32F401)/cmsis_nvic.o;$(LlilumTargetDirSTM32F401)$(LlilumTargetBoardSTM32F401)/$(LlilumTargetToolchainSTM32F401)/hal_tick.o;$(LlilumTargetDirSTM32F401)$(LlilumTargetBoardSTM32F401)/$(LlilumTargetToolchainSTM32F401)/mbed_overrides.o;$(LlilumTargetDirSTM32F401)$(LlilumTargetBoardSTM32F401)/$(LlilumTargetToolchainSTM32F401)/retarget.o ;$(LlilumTargetDirSTM32F401)$(LlilumTargetBoardSTM32F401)/$(LlilumTargetToolchainSTM32F401)/stm32f4xx_hal.o;$(LlilumTargetDirSTM32F401)$(LlilumTargetBoardSTM32F401)/$(LlilumTargetToolchainSTM32F401)/stm32f4xx_hal_adc.o;$(LlilumTargetDirSTM32F401)$(LlilumTargetBoardSTM32F401)/$(LlilumTargetToolchainSTM32F401)/stm32f4xx_hal_adc_ex.o;$(LlilumTargetDirSTM32F401)$(LlilumTargetBoardSTM32F401)/$(LlilumTargetToolchainSTM32F401)/stm32f4xx_hal_can.o;$(LlilumTargetDirSTM32F401)$(LlilumTargetBoardSTM32F401)/$(LlilumTargetToolchainSTM32F401)/stm32f4xx_hal_cec.o;$(LlilumTargetDirSTM32F401)$(LlilumTargetBoardSTM32F401)/$(LlilumTargetToolchainSTM32F401)/stm32f4xx_hal_cortex.o;$(LlilumTargetDirSTM32F401)$(LlilumTargetBoardSTM32F401)/$(LlilumTargetToolchainSTM32F401)/stm32f4xx_hal_crc.o;$(LlilumTargetDirSTM32F401)$(LlilumTargetBoardSTM32F401)/$(LlilumTargetToolchainSTM32F401)/stm32f4xx_hal_cryp.o;$(LlilumTargetDirSTM32F401)$(LlilumTargetBoardSTM32F401)/$(LlilumTargetToolchainSTM32F401)/stm32f4xx_hal_cryp_ex.o;$(LlilumTargetDirSTM32F401)$(LlilumTargetBoardSTM32F401)/$(LlilumTargetToolchainSTM32F401)/stm32f4xx_hal_dac.o;$(LlilumTargetDirSTM32F401)$(LlilumTargetBoardSTM32F401)/$(LlilumTargetToolchainSTM32F401)/stm32f4xx_hal_dac_ex.o;$(LlilumTargetDirSTM32F401)$(LlilumTargetBoardSTM32F401)/$(LlilumTargetToolchainSTM32F401)/stm32f4xx_hal_dcmi.o;$(LlilumTargetDirSTM32F401)$(LlilumTargetBoardSTM32F401)/$(LlilumTargetToolchainSTM32F401)/stm32f4xx_hal_dcmi_ex.o;$(LlilumTargetDirSTM32F401)$(LlilumTargetBoardSTM32F401)/$(LlilumTargetToolchainSTM32F401)/stm32f4xx_hal_dma.o;$(LlilumTargetDirSTM32F401)$(LlilumTargetBoardSTM32F401)/$(LlilumTargetToolchainSTM32F401)/stm32f4xx_hal_dma2d.o;$(LlilumTargetDirSTM32F401)$(LlilumTargetBoardSTM32F401)/$(LlilumTargetToolchainSTM32F401)/stm32f4xx_hal_dma_ex.o;$(LlilumTargetDirSTM32F401)$(LlilumTargetBoardSTM32F401)/$(LlilumTargetToolchainSTM32F401)/stm32f4xx_hal_dsi.o;$(LlilumTargetDirSTM32F401)$(LlilumTargetBoardSTM32F401)/$(LlilumTargetToolchainSTM32F401)/stm32f4xx_hal_eth.o;$(LlilumTargetDirSTM32F401)$(LlilumTargetBoardSTM32F401)/$(LlilumTargetToolchainSTM32F401)/stm32f4xx_hal_flash.o;$(LlilumTargetDirSTM32F401)$(LlilumTargetBoardSTM32F401)/$(LlilumTargetToolchainSTM32F401)/stm32f4xx_hal_flash_ex.o;$(LlilumTargetDirSTM32F401)$(LlilumTargetBoardSTM32F401)/$(LlilumTargetToolchainSTM32F401)/stm32f4xx_hal_fmpi2c_ex.o;$(LlilumTargetDirSTM32F401)$(LlilumTargetBoardSTM32F401)/$(LlilumTargetToolchainSTM32F401)/stm32f4xx_hal_fmpi2c.o;$(LlilumTargetDirSTM32F401)$(LlilumTargetBoardSTM32F401)/$(LlilumTargetToolchainSTM32F401)/stm32f4xx_hal_msp_template.o;$(LlilumTargetDirSTM32F401)$(LlilumTargetBoardSTM32F401)/$(LlilumTargetToolchainSTM32F401)/stm32f4xx_hal_gpio.o;$(LlilumTargetDirSTM32F401)$(LlilumTargetBoardSTM32F401)/$(LlilumTargetToolchainSTM32F401)/stm32f4xx_hal_hash.o;$(LlilumTargetDirSTM32F401)$(LlilumTargetBoardSTM32F401)/$(LlilumTargetToolchainSTM32F401)/stm32f4xx_hal_hash_ex.o;$(LlilumTargetDirSTM32F401)$(LlilumTargetBoardSTM32F401)/$(LlilumTargetToolchainSTM32F401)/stm32f4xx_hal_hcd.o;$(LlilumTargetDirSTM32F401)$(LlilumTargetBoardSTM32F401)/$(LlilumTargetToolchainSTM32F401)/stm32f4xx_hal_i2c.o;$(LlilumTargetDirSTM32F401)$(LlilumTargetBoardSTM32F401)/$(LlilumTargetToolchainSTM32F401)/stm32f4xx_hal_i2c_ex.o;$(LlilumTargetDirSTM32F401)$(LlilumTargetBoardSTM32F401)/$(LlilumTargetToolchainSTM32F401)/stm32f4xx_hal_i2s.o;$(LlilumTargetDirSTM32F401)$(LlilumTargetBoardSTM32F401)/$(LlilumTargetToolchainSTM32F401)/stm32f4xx_hal_i2s_ex.o;$(LlilumTargetDirSTM32F401)$(LlilumTargetBoardSTM32F401)/$(LlilumTargetToolchainSTM32F401)/stm32f4xx_hal_irda.o;$(LlilumTargetDirSTM32F401)$(LlilumTargetBoardSTM32F401)/$(LlilumTargetToolchainSTM32F401)/stm32f4xx_hal_iwdg.o;$(LlilumTargetDirSTM32F401)$(LlilumTargetBoardSTM32F401)/$(LlilumTargetToolchainSTM32F401)/stm32f4xx_hal_lptim.o;$(LlilumTargetDirSTM32F401)$(LlilumTargetBoardSTM32F401)/$(LlilumTargetToolchainSTM32F401)/stm32f4xx_hal_ltdc.o;$(LlilumTargetDirSTM32F401)$(LlilumTargetBoardSTM32F401)/$(LlilumTargetToolchainSTM32F401)/stm32f4xx_hal_ltdc_ex.o;$(LlilumTargetDirSTM32F401)$(LlilumTargetBoardSTM32F401)/$(LlilumTargetToolchainSTM32F401)/stm32f4xx_hal_smartcard.o;$(LlilumTargetDirSTM32F401)$(LlilumTargetBoardSTM32F401)/$(LlilumTargetToolchainSTM32F401)/stm32f4xx_hal_nand.o;$(LlilumTargetDirSTM32F401)$(LlilumTargetBoardSTM32F401)/$(LlilumTargetToolchainSTM32F401)/stm32f4xx_hal_nor.o;$(LlilumTargetDirSTM32F401)$(LlilumTargetBoardSTM32F401)/$(LlilumTargetToolchainSTM32F401)/stm32f4xx_hal_pccard.o;$(LlilumTargetDirSTM32F401)$(LlilumTargetBoardSTM32F401)/$(LlilumTargetToolchainSTM32F401)/stm32f4xx_hal_pcd.o;$(LlilumTargetDirSTM32F401)$(LlilumTargetBoardSTM32F401)/$(LlilumTargetToolchainSTM32F401)/stm32f4xx_hal_pcd_ex.o;$(LlilumTargetDirSTM32F401)$(LlilumTargetBoardSTM32F401)/$(LlilumTargetToolchainSTM32F401)/stm32f4xx_hal_pwr.o;$(LlilumTargetDirSTM32F401)$(LlilumTargetBoardSTM32F401)/$(LlilumTargetToolchainSTM32F401)/stm32f4xx_hal_pwr_ex.o;$(LlilumTargetDirSTM32F401)$(LlilumTargetBoardSTM32F401)/$(LlilumTargetToolchainSTM32F401)/stm32f4xx_hal_qspi.o;$(LlilumTargetDirSTM32F401)$(LlilumTargetBoardSTM32F401)/$(LlilumTargetToolchainSTM32F401)/stm32f4xx_hal_rcc.o;$(LlilumTargetDirSTM32F401)$(LlilumTargetBoardSTM32F401)/$(LlilumTargetToolchainSTM32F401)/stm32f4xx_hal_rcc_ex.o;$(LlilumTargetDirSTM32F401)$(LlilumTargetBoardSTM32F401)/$(LlilumTargetToolchainSTM32F401)/stm32f4xx_hal_rng.o;$(LlilumTargetDirSTM32F401)$(LlilumTargetBoardSTM32F401)/$(LlilumTargetToolchainSTM32F401)/stm32f4xx_hal_rtc.o;$(LlilumTargetDirSTM32F401)$(LlilumTargetBoardSTM32F401)/$(LlilumTargetToolchainSTM32F401)/stm32f4xx_hal_rtc_ex.o;$(LlilumTargetDirSTM32F401)$(LlilumTargetBoardSTM32F401)/$(LlilumTargetToolchainSTM32F401)/stm32f4xx_hal_sai.o;$(LlilumTargetDirSTM32F401)$(LlilumTargetBoardSTM32F401)/$(LlilumTargetToolchainSTM32F401)/stm32f4xx_hal_sai_ex.o;$(LlilumTargetDirSTM32F401)$(LlilumTargetBoardSTM32F401)/$(LlilumTargetToolchainSTM32F401)/stm32f4xx_hal_sd.o;$(LlilumTargetDirSTM32F401)$(LlilumTargetBoardSTM32F401)/$(LlilumTargetToolchainSTM32F401)/stm32f4xx_hal_sdram.o;$(LlilumTargetDirSTM32F401)$(LlilumTargetBoardSTM32F401)/$(LlilumTargetToolchainSTM32F401)/stm32f4xx_hal_spdifrx.o;$(LlilumTargetDirSTM32F401)$(LlilumTargetBoardSTM32F401)/$(LlilumTargetToolchainSTM32F401)/stm32f4xx_hal_spi.o;$(LlilumTargetDirSTM32F401)$(LlilumTargetBoardSTM32F401)/$(LlilumTargetToolchainSTM32F401)/stm32f4xx_hal_sram.o;$(LlilumTargetDirSTM32F401)$(LlilumTargetBoardSTM32F401)/$(LlilumTargetToolchainSTM32F401)/stm32f4xx_hal_tim.o;$(LlilumTargetDirSTM32F401)$(LlilumTargetBoardSTM32F401)/$(LlilumTargetToolchainSTM32F401)/stm32f4xx_hal_tim_ex.o;$(LlilumTargetDirSTM32F401)$(LlilumTargetBoardSTM32F401)/$(LlilumTargetToolchainSTM32F401)/stm32f4xx_hal_uart.o;$(LlilumTargetDirSTM32F401)$(LlilumTargetBoardSTM32F401)/$(LlilumTargetToolchainSTM32F401)/stm32f4xx_hal_usart.o;$(LlilumTargetDirSTM32F401)$(LlilumTargetBoardSTM32F401)/$(LlilumTargetToolchainSTM32F401)/stm32f4xx_hal_wwdg.o;$(LlilumTargetDirSTM32F401)$(LlilumTargetBoardSTM32F401)/$(LlilumTargetToolchainSTM32F401)/stm32f4xx_ll_fmc.o;$(LlilumTargetDirSTM32F401)$(LlilumTargetBoardSTM32F401)/$(LlilumTargetToolchainSTM32F401)/stm32f4xx_ll_fsmc.o;$(LlilumTargetDirSTM32F401)$(LlilumTargetBoardSTM32F401)/$(LlilumTargetToolchainSTM32F401)/stm32f4xx_ll_sdmmc.o;$(LlilumTargetDirSTM32F401)$(LlilumTargetBoardSTM32F401)/$(LlilumTargetToolchainSTM32F401)/stm32f4xx_ll_usb.o;$(LlilumTargetDirSTM32F401)$(LlilumTargetBoardSTM32F401)/$(LlilumTargetToolchainSTM32F401)/system_stm32f4xx.o $(LlilumTargetDirSTM32F401)$(LlilumTargetBoardSTM32F401)/$(LlilumTargetToolchainSTM32F401) -T"$(LlilumTargetDirSTM32F401)$(LlilumTargetBoardSTM32F401)/$(LlilumTargetToolchainSTM32F401)/STM32F401XE.ld" -Wl,--gc-sections --specs=nano.specs -u _printf_float -u _scanf_float -Wl,--wrap,main mbed;stdc++;supc++;m;c;gcc;nosys 0x800 0x6000 $(LlilumTargetDirSTM32F401) $(LlilumTargetBoardSTM32F401) $(LlilumTargetBrandSTM32F401) $(LlilumTargetToolchainSTM32F401) $(LlilumTargetClassSTM32F401) $(LlilumTargetBoardMbedSTM32F401) $(LlilumTargetBoardArchitectureSTM32F401) $(LlilumLwipIncludeDirs) $(LlilumClAdditionalOptionsSTM32F401) $(LlilumClAdditionalIncludesSTM32F401) $(LlilumClPreprocessorDefsSTM32F401) $(LlilumLinkAdditionalDepsSTM32F401) $(LlilumLinkAdditionalLibDirsSTM32F401) $(LlilumLinkAdditionalOptionsSTM32F401) $(LlilumLinkLibDepsSTM32F401) $(LlilumAsmAdditionalOptionsSTM32F401) $(LlilumStackSizeSTM32F401) $(LlilumHeapSizeSTM32F401) $(LlilumOpenOcdInterfaceCfgSTM32F401) $(LlilumOpenOcdBoardCfgSTM32F401) ================================================ FILE: VisualStudio/LlilumApplicationType/Llilum/1.0/Platforms/Llilum_STM32F411.props ================================================  $(LlilumSDK)mbed\ TARGET_NUCLEO_F411RE TARGET_STM TOOLCHAIN_GCC_ARM TARGET_STM32F4 TARGET_NUCLEO_F411RE cortex-m4 $(LlilumTargetDirLPC1768)EthernetInterface;$(LlilumSDK)lwip\lwip;$(LlilumSDK)lwip\lwip\include;$(LlilumSDK)lwip\lwip\include\ipv4;$(LlilumSDK)lwip\lwip\include\ipv4\lwip;$(LlilumSDK)lwip\lwip\include\lwip;$(LlilumSDK)lwip\lwip\include\netif;$(LlilumSDK)lwip\lwip\netif;$(LlilumSDK)lwip/lwip/netif/ppp;$(LlilumSDK)lwip/lwip/api;$(LlilumSDK)lwip/lwip/core;$(LlilumSDK)lwip/lwip/core/ipv4;$(LlilumSDK)lwip/lwip/core/snmp;$(LlilumSDK)lwip/lwip-eth;$(LlilumSDK)lwip/lwip-eth/arch;$(LlilumSDK)lwip/lwip-sys;$(LlilumSDK)lwip/lwip-sys/arch;$(LlilumSDK)mbed-rtos/llos;$(LlilumSDK)mbed-rtos/llos/TARGET_CORTEX_M;$(LlilumSDK)lwip/lwip-eth/arch/TARGET_NXP stlink-v2-1.cfg st_nucleo_f4.cfg -mcpu=$(LlilumTargetBoardArchitectureSTM32F411) -mthumb -mfpu=fpv4-sp-d16 -mfloat-abi=softfp $(LlilumLwipIncludeDirs);$(LlilumTargetDirSTM32F411);$(LlilumTargetDirSTM32F411)$(LlilumTargetBoardSTM32F411);$(LlilumTargetDirSTM32F411)$(LlilumTargetBoardSTM32F411)/$(LlilumTargetToolchainSTM32F411);$(LlilumTargetDirSTM32F411)$(LlilumTargetBoardSTM32F411)/$(LlilumTargetBrandSTM32F411);$(LlilumTargetDirSTM32F411)$(LlilumTargetBoardSTM32F411)/$(LlilumTargetBrandSTM32F411)/$(LlilumTargetClassSTM32F411);$(LlilumTargetDirSTM32F411)$(LlilumTargetBoardSTM32F411)/$(LlilumTargetBrandSTM32F411)/$(LlilumTargetClassSTM32F411)/$(LlilumTargetBoardMbedSTM32F411); TARGET_FF_ARDUINO;TOOLCHAIN_GCC_ARM;TARGET_NUCLEO_F411RE;__CORTEX_M4;TARGET_CORTEX_M;__FPU_PRESENT=1;__MBED__=1;TARGET_M4;TARGET_FF_MORPHO;TARGET_STM;TARGET_STM32F4;TOOLCHAIN_GCC;TARGET_STM32F411RE;ARM_MATH_CM4;MBED_BUILD_TIMESTAMP=1450373147.1 $(LlilumTargetDirSTM32F411)$(LlilumTargetBoardSTM32F411)/$(LlilumTargetToolchainSTM32F411)/stm32f4xx_hal_flash_ramfunc.o;$(LlilumTargetDirSTM32F411)$(LlilumTargetBoardSTM32F411)/$(LlilumTargetToolchainSTM32F411)/board.o;$(LlilumTargetDirSTM32F411)$(LlilumTargetBoardSTM32F411)/$(LlilumTargetToolchainSTM32F411)/cmsis_nvic.o;$(LlilumTargetDirSTM32F411)$(LlilumTargetBoardSTM32F411)/$(LlilumTargetToolchainSTM32F411)/hal_tick.o;$(LlilumTargetDirSTM32F411)$(LlilumTargetBoardSTM32F411)/$(LlilumTargetToolchainSTM32F411)/mbed_overrides.o;$(LlilumTargetDirSTM32F411)$(LlilumTargetBoardSTM32F411)/$(LlilumTargetToolchainSTM32F411)/retarget.o ;$(LlilumTargetDirSTM32F411)$(LlilumTargetBoardSTM32F411)/$(LlilumTargetToolchainSTM32F411)/stm32f4xx_hal.o;$(LlilumTargetDirSTM32F411)$(LlilumTargetBoardSTM32F411)/$(LlilumTargetToolchainSTM32F411)/stm32f4xx_hal_adc.o;$(LlilumTargetDirSTM32F411)$(LlilumTargetBoardSTM32F411)/$(LlilumTargetToolchainSTM32F411)/stm32f4xx_hal_adc_ex.o;$(LlilumTargetDirSTM32F411)$(LlilumTargetBoardSTM32F411)/$(LlilumTargetToolchainSTM32F411)/stm32f4xx_hal_can.o;$(LlilumTargetDirSTM32F411)$(LlilumTargetBoardSTM32F411)/$(LlilumTargetToolchainSTM32F411)/stm32f4xx_hal_cec.o;$(LlilumTargetDirSTM32F411)$(LlilumTargetBoardSTM32F411)/$(LlilumTargetToolchainSTM32F411)/stm32f4xx_hal_cortex.o;$(LlilumTargetDirSTM32F411)$(LlilumTargetBoardSTM32F411)/$(LlilumTargetToolchainSTM32F411)/stm32f4xx_hal_crc.o;$(LlilumTargetDirSTM32F411)$(LlilumTargetBoardSTM32F411)/$(LlilumTargetToolchainSTM32F411)/stm32f4xx_hal_cryp.o;$(LlilumTargetDirSTM32F411)$(LlilumTargetBoardSTM32F411)/$(LlilumTargetToolchainSTM32F411)/stm32f4xx_hal_cryp_ex.o;$(LlilumTargetDirSTM32F411)$(LlilumTargetBoardSTM32F411)/$(LlilumTargetToolchainSTM32F411)/stm32f4xx_hal_dac.o;$(LlilumTargetDirSTM32F411)$(LlilumTargetBoardSTM32F411)/$(LlilumTargetToolchainSTM32F411)/stm32f4xx_hal_dac_ex.o;$(LlilumTargetDirSTM32F411)$(LlilumTargetBoardSTM32F411)/$(LlilumTargetToolchainSTM32F411)/stm32f4xx_hal_dcmi.o;$(LlilumTargetDirSTM32F411)$(LlilumTargetBoardSTM32F411)/$(LlilumTargetToolchainSTM32F411)/stm32f4xx_hal_dcmi_ex.o;$(LlilumTargetDirSTM32F411)$(LlilumTargetBoardSTM32F411)/$(LlilumTargetToolchainSTM32F411)/stm32f4xx_hal_dma.o;$(LlilumTargetDirSTM32F411)$(LlilumTargetBoardSTM32F411)/$(LlilumTargetToolchainSTM32F411)/stm32f4xx_hal_dma2d.o;$(LlilumTargetDirSTM32F411)$(LlilumTargetBoardSTM32F411)/$(LlilumTargetToolchainSTM32F411)/stm32f4xx_hal_dma_ex.o;$(LlilumTargetDirSTM32F411)$(LlilumTargetBoardSTM32F411)/$(LlilumTargetToolchainSTM32F411)/stm32f4xx_hal_dsi.o;$(LlilumTargetDirSTM32F411)$(LlilumTargetBoardSTM32F411)/$(LlilumTargetToolchainSTM32F411)/stm32f4xx_hal_eth.o;$(LlilumTargetDirSTM32F411)$(LlilumTargetBoardSTM32F411)/$(LlilumTargetToolchainSTM32F411)/stm32f4xx_hal_flash.o;$(LlilumTargetDirSTM32F411)$(LlilumTargetBoardSTM32F411)/$(LlilumTargetToolchainSTM32F411)/stm32f4xx_hal_flash_ex.o;$(LlilumTargetDirSTM32F411)$(LlilumTargetBoardSTM32F411)/$(LlilumTargetToolchainSTM32F411)/stm32f4xx_hal_fmpi2c_ex.o;$(LlilumTargetDirSTM32F411)$(LlilumTargetBoardSTM32F411)/$(LlilumTargetToolchainSTM32F411)/stm32f4xx_hal_fmpi2c.o;$(LlilumTargetDirSTM32F411)$(LlilumTargetBoardSTM32F411)/$(LlilumTargetToolchainSTM32F411)/stm32f4xx_hal_msp_template.o;$(LlilumTargetDirSTM32F411)$(LlilumTargetBoardSTM32F411)/$(LlilumTargetToolchainSTM32F411)/stm32f4xx_hal_gpio.o;$(LlilumTargetDirSTM32F411)$(LlilumTargetBoardSTM32F411)/$(LlilumTargetToolchainSTM32F411)/stm32f4xx_hal_hash.o;$(LlilumTargetDirSTM32F411)$(LlilumTargetBoardSTM32F411)/$(LlilumTargetToolchainSTM32F411)/stm32f4xx_hal_hash_ex.o;$(LlilumTargetDirSTM32F411)$(LlilumTargetBoardSTM32F411)/$(LlilumTargetToolchainSTM32F411)/stm32f4xx_hal_hcd.o;$(LlilumTargetDirSTM32F411)$(LlilumTargetBoardSTM32F411)/$(LlilumTargetToolchainSTM32F411)/stm32f4xx_hal_i2c.o;$(LlilumTargetDirSTM32F411)$(LlilumTargetBoardSTM32F411)/$(LlilumTargetToolchainSTM32F411)/stm32f4xx_hal_i2c_ex.o;$(LlilumTargetDirSTM32F411)$(LlilumTargetBoardSTM32F411)/$(LlilumTargetToolchainSTM32F411)/stm32f4xx_hal_i2s.o;$(LlilumTargetDirSTM32F411)$(LlilumTargetBoardSTM32F411)/$(LlilumTargetToolchainSTM32F411)/stm32f4xx_hal_i2s_ex.o;$(LlilumTargetDirSTM32F411)$(LlilumTargetBoardSTM32F411)/$(LlilumTargetToolchainSTM32F411)/stm32f4xx_hal_irda.o;$(LlilumTargetDirSTM32F411)$(LlilumTargetBoardSTM32F411)/$(LlilumTargetToolchainSTM32F411)/stm32f4xx_hal_iwdg.o;$(LlilumTargetDirSTM32F411)$(LlilumTargetBoardSTM32F411)/$(LlilumTargetToolchainSTM32F411)/stm32f4xx_hal_lptim.o;$(LlilumTargetDirSTM32F411)$(LlilumTargetBoardSTM32F411)/$(LlilumTargetToolchainSTM32F411)/stm32f4xx_hal_ltdc.o;$(LlilumTargetDirSTM32F411)$(LlilumTargetBoardSTM32F411)/$(LlilumTargetToolchainSTM32F411)/stm32f4xx_hal_ltdc_ex.o;$(LlilumTargetDirSTM32F411)$(LlilumTargetBoardSTM32F411)/$(LlilumTargetToolchainSTM32F411)/stm32f4xx_hal_smartcard.o;$(LlilumTargetDirSTM32F411)$(LlilumTargetBoardSTM32F411)/$(LlilumTargetToolchainSTM32F411)/stm32f4xx_hal_nand.o;$(LlilumTargetDirSTM32F411)$(LlilumTargetBoardSTM32F411)/$(LlilumTargetToolchainSTM32F411)/stm32f4xx_hal_nor.o;$(LlilumTargetDirSTM32F411)$(LlilumTargetBoardSTM32F411)/$(LlilumTargetToolchainSTM32F411)/stm32f4xx_hal_pccard.o;$(LlilumTargetDirSTM32F411)$(LlilumTargetBoardSTM32F411)/$(LlilumTargetToolchainSTM32F411)/stm32f4xx_hal_pcd.o;$(LlilumTargetDirSTM32F411)$(LlilumTargetBoardSTM32F411)/$(LlilumTargetToolchainSTM32F411)/stm32f4xx_hal_pcd_ex.o;$(LlilumTargetDirSTM32F411)$(LlilumTargetBoardSTM32F411)/$(LlilumTargetToolchainSTM32F411)/stm32f4xx_hal_pwr.o;$(LlilumTargetDirSTM32F411)$(LlilumTargetBoardSTM32F411)/$(LlilumTargetToolchainSTM32F411)/stm32f4xx_hal_pwr_ex.o;$(LlilumTargetDirSTM32F411)$(LlilumTargetBoardSTM32F411)/$(LlilumTargetToolchainSTM32F411)/stm32f4xx_hal_qspi.o;$(LlilumTargetDirSTM32F411)$(LlilumTargetBoardSTM32F411)/$(LlilumTargetToolchainSTM32F411)/stm32f4xx_hal_rcc.o;$(LlilumTargetDirSTM32F411)$(LlilumTargetBoardSTM32F411)/$(LlilumTargetToolchainSTM32F411)/stm32f4xx_hal_rcc_ex.o;$(LlilumTargetDirSTM32F411)$(LlilumTargetBoardSTM32F411)/$(LlilumTargetToolchainSTM32F411)/stm32f4xx_hal_rng.o;$(LlilumTargetDirSTM32F411)$(LlilumTargetBoardSTM32F411)/$(LlilumTargetToolchainSTM32F411)/stm32f4xx_hal_rtc.o;$(LlilumTargetDirSTM32F411)$(LlilumTargetBoardSTM32F411)/$(LlilumTargetToolchainSTM32F411)/stm32f4xx_hal_rtc_ex.o;$(LlilumTargetDirSTM32F411)$(LlilumTargetBoardSTM32F411)/$(LlilumTargetToolchainSTM32F411)/stm32f4xx_hal_sai.o;$(LlilumTargetDirSTM32F411)$(LlilumTargetBoardSTM32F411)/$(LlilumTargetToolchainSTM32F411)/stm32f4xx_hal_sai_ex.o;$(LlilumTargetDirSTM32F411)$(LlilumTargetBoardSTM32F411)/$(LlilumTargetToolchainSTM32F411)/stm32f4xx_hal_sd.o;$(LlilumTargetDirSTM32F411)$(LlilumTargetBoardSTM32F411)/$(LlilumTargetToolchainSTM32F411)/stm32f4xx_hal_sdram.o;$(LlilumTargetDirSTM32F411)$(LlilumTargetBoardSTM32F411)/$(LlilumTargetToolchainSTM32F411)/stm32f4xx_hal_spdifrx.o;$(LlilumTargetDirSTM32F411)$(LlilumTargetBoardSTM32F411)/$(LlilumTargetToolchainSTM32F411)/stm32f4xx_hal_spi.o;$(LlilumTargetDirSTM32F411)$(LlilumTargetBoardSTM32F411)/$(LlilumTargetToolchainSTM32F411)/stm32f4xx_hal_sram.o;$(LlilumTargetDirSTM32F411)$(LlilumTargetBoardSTM32F411)/$(LlilumTargetToolchainSTM32F411)/stm32f4xx_hal_tim.o;$(LlilumTargetDirSTM32F411)$(LlilumTargetBoardSTM32F411)/$(LlilumTargetToolchainSTM32F411)/stm32f4xx_hal_tim_ex.o;$(LlilumTargetDirSTM32F411)$(LlilumTargetBoardSTM32F411)/$(LlilumTargetToolchainSTM32F411)/stm32f4xx_hal_uart.o;$(LlilumTargetDirSTM32F411)$(LlilumTargetBoardSTM32F411)/$(LlilumTargetToolchainSTM32F411)/stm32f4xx_hal_usart.o;$(LlilumTargetDirSTM32F411)$(LlilumTargetBoardSTM32F411)/$(LlilumTargetToolchainSTM32F411)/stm32f4xx_hal_wwdg.o;$(LlilumTargetDirSTM32F411)$(LlilumTargetBoardSTM32F411)/$(LlilumTargetToolchainSTM32F411)/stm32f4xx_ll_fmc.o;$(LlilumTargetDirSTM32F411)$(LlilumTargetBoardSTM32F411)/$(LlilumTargetToolchainSTM32F411)/stm32f4xx_ll_fsmc.o;$(LlilumTargetDirSTM32F411)$(LlilumTargetBoardSTM32F411)/$(LlilumTargetToolchainSTM32F411)/stm32f4xx_ll_sdmmc.o;$(LlilumTargetDirSTM32F411)$(LlilumTargetBoardSTM32F411)/$(LlilumTargetToolchainSTM32F411)/stm32f4xx_ll_usb.o;$(LlilumTargetDirSTM32F411)$(LlilumTargetBoardSTM32F411)/$(LlilumTargetToolchainSTM32F411)/system_stm32f4xx.o $(LlilumTargetDirSTM32F411)$(LlilumTargetBoardSTM32F411)/$(LlilumTargetToolchainSTM32F411) -T"$(LlilumTargetDirSTM32F411)$(LlilumTargetBoardSTM32F411)/$(LlilumTargetToolchainSTM32F411)/STM32F411XE.ld" -Wl,--gc-sections --specs=nano.specs -u _printf_float -u _scanf_float -Wl,--wrap,main mbed;stdc++;supc++;m;c;gcc;nosys 0x800 0x6000 $(LlilumTargetDirSTM32F411) $(LlilumTargetBoardSTM32F411) $(LlilumTargetBrandSTM32F411) $(LlilumTargetToolchainSTM32F411) $(LlilumTargetClassSTM32F411) $(LlilumTargetBoardMbedSTM32F411) $(LlilumTargetBoardArchitectureSTM32F411) $(LlilumLwipIncludeDirs) $(LlilumClAdditionalOptionsSTM32F411) $(LlilumClAdditionalIncludesSTM32F411) $(LlilumClPreprocessorDefsSTM32F411) $(LlilumLinkAdditionalDepsSTM32F411) $(LlilumLinkAdditionalLibDirsSTM32F411) $(LlilumLinkAdditionalOptionsSTM32F411) $(LlilumLinkLibDepsSTM32F411) $(LlilumAsmAdditionalOptionsSTM32F411) $(LlilumStackSizeSTM32F411) $(LlilumHeapSizeSTM32F411) $(LlilumOpenOcdInterfaceCfgSTM32F411) $(LlilumOpenOcdBoardCfgSTM32F411) ================================================ FILE: VisualStudio/LlilumApplicationType/Llilum/1.0/Platforms/Llilum_STM32L152.props ================================================  $(LlilumSDK)mbed\ TARGET_NUCLEO_L152RE TARGET_STM TOOLCHAIN_GCC_ARM TARGET_STM32L1 TARGET_NUCLEO_L152RE cortex-m3 stlink-v2-1.cfg st_nucleo_l1.cfg -mcpu=$(LlilumTargetBoardArchitectureSTM32L152) -mthumb $(LlilumTargetDirSTM32L152);$(LlilumTargetDirSTM32L152)$(LlilumTargetBoardSTM32L152);$(LlilumTargetDirSTM32L152)$(LlilumTargetBoardSTM32L152)/$(LlilumTargetToolchainSTM32L152);$(LlilumTargetDirSTM32L152)$(LlilumTargetBoardSTM32L152)/$(LlilumTargetBrandSTM32L152);$(LlilumTargetDirSTM32L152)$(LlilumTargetBoardSTM32L152)/$(LlilumTargetBrandSTM32L152)/$(LlilumTargetClassSTM32L152);$(LlilumTargetDirSTM32L152)$(LlilumTargetBoardSTM32L152)/$(LlilumTargetBrandSTM32L152)/$(LlilumTargetClassSTM32L152)/$(LlilumTargetBoardMbedSTM32L152); MBED_BUILD_TIMESTAMP=1445629897.99;TARGET_FF_ARDUINO;TOOLCHAIN_GCC_ARM;TOOLCHAIN_GCC;TARGET_FF_MORPHO;TARGET_CORTEX_M;ARM_MATH_CM3;TARGET_STM32L1;TARGET_STM;__CORTEX_M3;TARGET_NUCLEO_L152RE;TARGET_M3;TARGET_STM32L152RE;__MBED__=1 $(LlilumTargetDirSTM32L152)$(LlilumTargetBoardSTM32L152)/$(LlilumTargetToolchainSTM32L152)/stm32l1xx_hal_flash_ramfunc.o;$(LlilumTargetDirSTM32L152)$(LlilumTargetBoardSTM32L152)/$(LlilumTargetToolchainSTM32L152)/board.o;$(LlilumTargetDirSTM32L152)$(LlilumTargetBoardSTM32L152)/$(LlilumTargetToolchainSTM32L152)/cmsis_nvic.o;$(LlilumTargetDirSTM32L152)$(LlilumTargetBoardSTM32L152)/$(LlilumTargetToolchainSTM32L152)/hal_tick.o;$(LlilumTargetDirSTM32L152)$(LlilumTargetBoardSTM32L152)/$(LlilumTargetToolchainSTM32L152)/mbed_overrides.o;$(LlilumTargetDirSTM32L152)$(LlilumTargetBoardSTM32L152)/$(LlilumTargetToolchainSTM32L152)/retarget.o;$(LlilumTargetDirSTM32L152)$(LlilumTargetBoardSTM32L152)/$(LlilumTargetToolchainSTM32L152)/stm32l1xx_hal.o;$(LlilumTargetDirSTM32L152)$(LlilumTargetBoardSTM32L152)/$(LlilumTargetToolchainSTM32L152)/stm32l1xx_hal_adc.o;$(LlilumTargetDirSTM32L152)$(LlilumTargetBoardSTM32L152)/$(LlilumTargetToolchainSTM32L152)/stm32l1xx_hal_adc_ex.o;$(LlilumTargetDirSTM32L152)$(LlilumTargetBoardSTM32L152)/$(LlilumTargetToolchainSTM32L152)/stm32l1xx_hal_comp.o;$(LlilumTargetDirSTM32L152)$(LlilumTargetBoardSTM32L152)/$(LlilumTargetToolchainSTM32L152)/stm32l1xx_hal_cortex.o;$(LlilumTargetDirSTM32L152)$(LlilumTargetBoardSTM32L152)/$(LlilumTargetToolchainSTM32L152)/stm32l1xx_hal_crc.o;$(LlilumTargetDirSTM32L152)$(LlilumTargetBoardSTM32L152)/$(LlilumTargetToolchainSTM32L152)/stm32l1xx_hal_cryp.o;$(LlilumTargetDirSTM32L152)$(LlilumTargetBoardSTM32L152)/$(LlilumTargetToolchainSTM32L152)/stm32l1xx_hal_cryp_ex.o;$(LlilumTargetDirSTM32L152)$(LlilumTargetBoardSTM32L152)/$(LlilumTargetToolchainSTM32L152)/stm32l1xx_hal_dac.o;$(LlilumTargetDirSTM32L152)$(LlilumTargetBoardSTM32L152)/$(LlilumTargetToolchainSTM32L152)/stm32l1xx_hal_dac_ex.o;$(LlilumTargetDirSTM32L152)$(LlilumTargetBoardSTM32L152)/$(LlilumTargetToolchainSTM32L152)/stm32l1xx_hal_dma.o;$(LlilumTargetDirSTM32L152)$(LlilumTargetBoardSTM32L152)/$(LlilumTargetToolchainSTM32L152)/stm32l1xx_hal_flash.o;$(LlilumTargetDirSTM32L152)$(LlilumTargetBoardSTM32L152)/$(LlilumTargetToolchainSTM32L152)/stm32l1xx_hal_flash_ex.o;$(LlilumTargetDirSTM32L152)$(LlilumTargetBoardSTM32L152)/$(LlilumTargetToolchainSTM32L152)/stm32l1xx_hal_smartcard.o;$(LlilumTargetDirSTM32L152)$(LlilumTargetBoardSTM32L152)/$(LlilumTargetToolchainSTM32L152)/stm32l1xx_hal_gpio.o;$(LlilumTargetDirSTM32L152)$(LlilumTargetBoardSTM32L152)/$(LlilumTargetToolchainSTM32L152)/stm32l1xx_hal_i2c.o;$(LlilumTargetDirSTM32L152)$(LlilumTargetBoardSTM32L152)/$(LlilumTargetToolchainSTM32L152)/stm32l1xx_hal_i2s.o;$(LlilumTargetDirSTM32L152)$(LlilumTargetBoardSTM32L152)/$(LlilumTargetToolchainSTM32L152)/stm32l1xx_hal_irda.o;$(LlilumTargetDirSTM32L152)$(LlilumTargetBoardSTM32L152)/$(LlilumTargetToolchainSTM32L152)/stm32l1xx_hal_iwdg.o;$(LlilumTargetDirSTM32L152)$(LlilumTargetBoardSTM32L152)/$(LlilumTargetToolchainSTM32L152)/stm32l1xx_hal_lcd.o;$(LlilumTargetDirSTM32L152)$(LlilumTargetBoardSTM32L152)/$(LlilumTargetToolchainSTM32L152)/stm32l1xx_hal_nor.o;$(LlilumTargetDirSTM32L152)$(LlilumTargetBoardSTM32L152)/$(LlilumTargetToolchainSTM32L152)/stm32l1xx_hal_opamp.o;$(LlilumTargetDirSTM32L152)$(LlilumTargetBoardSTM32L152)/$(LlilumTargetToolchainSTM32L152)/stm32l1xx_hal_opamp_ex.o;$(LlilumTargetDirSTM32L152)$(LlilumTargetBoardSTM32L152)/$(LlilumTargetToolchainSTM32L152)/stm32l1xx_hal_pcd.o;$(LlilumTargetDirSTM32L152)$(LlilumTargetBoardSTM32L152)/$(LlilumTargetToolchainSTM32L152)/stm32l1xx_hal_pcd_ex.o;$(LlilumTargetDirSTM32L152)$(LlilumTargetBoardSTM32L152)/$(LlilumTargetToolchainSTM32L152)/stm32l1xx_hal_pwr.o;$(LlilumTargetDirSTM32L152)$(LlilumTargetBoardSTM32L152)/$(LlilumTargetToolchainSTM32L152)/stm32l1xx_hal_pwr_ex.o;$(LlilumTargetDirSTM32L152)$(LlilumTargetBoardSTM32L152)/$(LlilumTargetToolchainSTM32L152)/stm32l1xx_hal_rcc.o;$(LlilumTargetDirSTM32L152)$(LlilumTargetBoardSTM32L152)/$(LlilumTargetToolchainSTM32L152)/stm32l1xx_hal_rcc_ex.o;$(LlilumTargetDirSTM32L152)$(LlilumTargetBoardSTM32L152)/$(LlilumTargetToolchainSTM32L152)/stm32l1xx_hal_rtc.o;$(LlilumTargetDirSTM32L152)$(LlilumTargetBoardSTM32L152)/$(LlilumTargetToolchainSTM32L152)/stm32l1xx_hal_rtc_ex.o;$(LlilumTargetDirSTM32L152)$(LlilumTargetBoardSTM32L152)/$(LlilumTargetToolchainSTM32L152)/stm32l1xx_hal_sd.o;$(LlilumTargetDirSTM32L152)$(LlilumTargetBoardSTM32L152)/$(LlilumTargetToolchainSTM32L152)/stm32l1xx_hal_spi.o;$(LlilumTargetDirSTM32L152)$(LlilumTargetBoardSTM32L152)/$(LlilumTargetToolchainSTM32L152)/stm32l1xx_hal_spi_ex.o;$(LlilumTargetDirSTM32L152)$(LlilumTargetBoardSTM32L152)/$(LlilumTargetToolchainSTM32L152)/stm32l1xx_hal_sram.o;$(LlilumTargetDirSTM32L152)$(LlilumTargetBoardSTM32L152)/$(LlilumTargetToolchainSTM32L152)/stm32l1xx_hal_tim.o;$(LlilumTargetDirSTM32L152)$(LlilumTargetBoardSTM32L152)/$(LlilumTargetToolchainSTM32L152)/stm32l1xx_hal_tim_ex.o;$(LlilumTargetDirSTM32L152)$(LlilumTargetBoardSTM32L152)/$(LlilumTargetToolchainSTM32L152)/stm32l1xx_hal_uart.o;$(LlilumTargetDirSTM32L152)$(LlilumTargetBoardSTM32L152)/$(LlilumTargetToolchainSTM32L152)/stm32l1xx_hal_usart.o;$(LlilumTargetDirSTM32L152)$(LlilumTargetBoardSTM32L152)/$(LlilumTargetToolchainSTM32L152)/stm32l1xx_hal_wwdg.o;$(LlilumTargetDirSTM32L152)$(LlilumTargetBoardSTM32L152)/$(LlilumTargetToolchainSTM32L152)/stm32l1xx_ll_fsmc.o;$(LlilumTargetDirSTM32L152)$(LlilumTargetBoardSTM32L152)/$(LlilumTargetToolchainSTM32L152)/stm32l1xx_ll_sdmmc.o;$(LlilumTargetDirSTM32L152)$(LlilumTargetBoardSTM32L152)/$(LlilumTargetToolchainSTM32L152)/system_stm32l1xx.o $(LlilumTargetDirSTM32L152)$(LlilumTargetBoardSTM32L152)/$(LlilumTargetToolchainSTM32L152) -T"$(LlilumTargetDirSTM32L152)$(LlilumTargetBoardSTM32L152)/$(LlilumTargetToolchainSTM32L152)/STM32L152XE.ld" -Wl,--gc-sections --specs=nano.specs -u _printf_float -u _scanf_float -Wl,--wrap,main mbed;stdc++;supc++;m;c;gcc;nosys 0x800 0x4000 $(LlilumTargetDirSTM32L152) $(LlilumTargetBoardSTM32L152) $(LlilumTargetBrandSTM32L152) $(LlilumTargetToolchainSTM32L152) $(LlilumTargetClassSTM32L152) $(LlilumTargetBoardMbedSTM32L152) $(LlilumTargetBoardArchitectureSTM32L152) $(LlilumClAdditionalOptionsSTM32L152) $(LlilumClAdditionalIncludesSTM32L152) $(LlilumClPreprocessorDefsSTM32L152) $(LlilumLinkAdditionalDepsSTM32L152) $(LlilumLinkAdditionalLibDirsSTM32L152) $(LlilumLinkAdditionalOptionsSTM32L152) $(LlilumLinkLibDepsSTM32L152) $(LlilumAsmAdditionalOptionsSTM32L152) $(LlilumStackSizeSTM32L152) $(LlilumHeapSizeSTM32L152) $(LlilumOpenOcdInterfaceCfgSTM32L152) $(LlilumOpenOcdBoardCfgSTM32L152) ================================================ FILE: VisualStudio/LlilumApplicationType/Llilum/1.0/Platforms/mbed-rtos.props ================================================  $(LlilumSDK)\mbed-rtos\rtx\TARGET_CORTEX_M;%(AdditionalIncludeDirectories) ================================================ FILE: VisualStudio/LlilumApplicationType/Llilum/Default.props ================================================  Android ARM 4.9 2015q1 $([MSBuild]::GetRegistryValueFromView('HKEY_LOCAL_MACHINE\SOFTWARE\ARM\GNU Tools for ARM Embedded Processors', 'InstallFolder', null, RegistryView.Registry64, RegistryView.Registry32)) $(MSBuildProgramFiles32)\GNU Tools ARM Embedded\$(LLilumGccVersion)\ $(LLILUM_GCC)\ $([MSBuild]::GetRegistryValueFromView('HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Llilum\v1.0', 'InstallDir', null, RegistryView.Registry64, RegistryView.Registry32)) $(LLILUM_SDK)\ ================================================ FILE: VisualStudio/LlilumProjectType/LlilumApplication/LlilumApplication.ProjectTemplate/LlilumApplication.ProjectTemplate.csproj ================================================  14.0 12.0 $(MSBuildExtensionsPath32)\Microsoft\VisualStudio\v$(VisualStudioVersion) SAK SAK SAK SAK 4.0 publish\ true Disk false Foreground 7 Days false false true 0 1.0.0.%2a false false true Debug AnyCPU 2.0 {82b43b9b-a64c-4715-b499-d71e9ca2bd60};{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC} {5747D247-5FCC-4151-942C-811603768ABE} Library Properties LlilumApplication LlilumApplication v4.5 false false false false false false false false false false true full false bin\Debug\ DEBUG;TRACE prompt 4 pdbonly true bin\Release\ TRACE prompt 4 Designer False Microsoft .NET Framework 4.5 %28x86 and x64%29 true False .NET Framework 3.5 SP1 false Designer ================================================ FILE: VisualStudio/LlilumProjectType/LlilumApplication/LlilumApplication.ProjectTemplate/LlilumApplication.vstemplate ================================================ Llilum Application Project A template for creating a Llilum Application project. LlilumApplication.ico LlilumApplication 4.5.2 1 {95af4530-3c8f-4126-a438-e2c18a6133f5} true LlilumApplication true LlilumNative\MyTemplate.vstemplate LlilumManaged\MyTemplate.vstemplate ================================================ FILE: VisualStudio/LlilumProjectType/LlilumApplication/LlilumApplication.ProjectTemplate/LlilumManaged/Managed.csproj ================================================  Debug AnyCPU {$guid1$} Exe Properties $safeprojectname$ Llilum.Managed v4.5 512 Llilum 1.0 AnyCPU true full false bin\Debug\ DEBUG;TRACE prompt 4 true AnyCPU pdbonly true bin\Release\ TRACE prompt 4 ================================================ FILE: VisualStudio/LlilumProjectType/LlilumApplication/LlilumApplication.ProjectTemplate/LlilumManaged/MyTemplate.vstemplate ================================================ LlilumManaged Managed code for a Llilum embedded project CSharp 1000 true LlilumManaged true Enabled true __TemplateIcon.ico __PreviewImage.ico Program.cs AssemblyInfo.cs ================================================ FILE: VisualStudio/LlilumProjectType/LlilumApplication/LlilumApplication.ProjectTemplate/LlilumManaged/Program.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // #define LPC1768 //#define K64F //#define STM32F411 //#define STM32F401 //#define STM32F091 namespace Managed { using System; using Windows.Devices.Gpio; using System.Runtime.InteropServices; using System.Threading; #if LPC1768 using Microsoft.Llilum.LPC1768; #elif K64F using Microsoft.Llilum.K64F; #elif STM32F411 using Microsoft.Llilum.STM32F411; #elif STM32F401 using Microsoft.Llilum.STM32F401; #elif STM32F091 using Microsoft.Llilum.STM32F091; #endif class Program { // Example of C interop functions [DllImport("C")] private static extern int AddOneInterop(int input); const float period = 0.75f; const float timePerMode = 4.0f; static int[] pinNumbers = { #if (LPC1768) (int)PinName.LED1, (int)PinName.LED4, #elif (K64F) (int)PinName.LED_BLUE, (int)PinName.LED_RED, #elif (STM32F411 || STM32F401 || STM32F091) (int)PinName.LED1, (int)PinName.LED1, #else #error No target board defined. #endif }; static void Main() { var controller = GpioController.GetDefault(); var threadToggledPin = controller.OpenPin(pinNumbers[0]); #if (STM32F411 || STM32F401 || STM32F091) var loopToggledPin = threadToggledPin; #else var loopToggledPin = controller.OpenPin(pinNumbers[1]); #endif threadToggledPin.SetDriveMode(GpioPinDriveMode.Output); loopToggledPin.SetDriveMode(GpioPinDriveMode.Output); int threadPinState = 1; int loopPinState = 1; // Toggling a pin with a thread var ev = new AutoResetEvent(false); var solitaryBlinker = new Thread(delegate () { while (true) { ev.WaitOne(1000, false); threadToggledPin.Write((GpioPinValue)threadPinState); // Using the C interop here threadPinState = AddOneInterop(threadPinState) % 2; } }); solitaryBlinker.Start(); // Toggling a pin in a loop long last = DateTime.Now.Ticks; while (true) { long now = DateTime.Now.Ticks; // Toggle every 500ms if (now > (last + 5000000)) { last = now; // Toggle the pin loopToggledPin.Write((GpioPinValue)loopPinState); // Using the C interop here loopPinState = AddOneInterop(loopPinState) % 2; } } } } } ================================================ FILE: VisualStudio/LlilumProjectType/LlilumApplication/LlilumApplication.ProjectTemplate/LlilumManaged/Properties/AssemblyInfo.cs ================================================ using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; // General Information about an assembly is controlled through the following // set of attributes. Change these attribute values to modify the information // associated with an assembly. [assembly: AssemblyTitle("$safeprojectname$")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("$safeprojectname$")] [assembly: AssemblyCopyright("Copyright © 2015")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible(false)] // The following GUID is for the ID of the typelib if this project is exposed to COM [assembly: Guid("$guid3$")] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Build and Revision Numbers // by using the '*' as shown below: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("1.0.0.0")] [assembly: AssemblyFileVersion("1.0.0.0")] ================================================ FILE: VisualStudio/LlilumProjectType/LlilumApplication/LlilumApplication.ProjectTemplate/LlilumNative/MyTemplate.vstemplate ================================================ LlilumNative Native code for a Llilum embedded project VC 1000 true LlilumNative true Enabled true __TemplateIcon.ico __PreviewImage.ico pch.h Source.cpp mbed_simple_K64F.FrontEndConfig mbed_simple_LPC1768.FrontEndConfig mbed_simple_STM32L152.FrontEndConfig mbed_simple_STM32F411.FrontEndConfig mbed_simple_STM32F401.FrontEndConfig mbed_simple_STM32F091.FrontEndConfig ================================================ FILE: VisualStudio/LlilumProjectType/LlilumApplication/LlilumApplication.ProjectTemplate/LlilumNative/Native.vcxproj ================================================  Debug ARM Release ARM {$guid2$} Android $safeprojectname$ 14.0 Llilum 1.0 $(LLILUM_GCC) Native LPC1768 $(MSBuildProjectDirectory)\mbed_simple_$(LlilumBoardName).FrontEndConfig $(LlilumSDK)os_layer\ports\mbed\inc;$(LlilumSDK)os_layer\inc;$(LlilumSDK)os_layer\inc\api;$(LlilumSDK)os_layer\inc\api\io;$(LlilumSDK)os_layer\inc\hal $(LlilumClAdditionalOptionsLPC1768) $(LlilumClAdditionalIncludesLPC1768) $(LlilumClPreprocessorDefsLPC1768) $(LlilumLinkAdditionalDepsLPC1768) $(LlilumLinkAdditionalLibDirsLPC1768) $(LlilumLinkAdditionalOptionsLPC1768) $(LlilumLinkLibDepsLPC1768) $(LlilumTargetBoardArchitectureLPC1768) $(LlilumAsmAdditionalOptionsLPC1768) $(LlilumStackSizeLPC1768) $(LlilumHeapSizeLPC1768) $(LlilumClAdditionalOptionsK64F) $(LlilumClAdditionalIncludesK64F) $(LlilumClPreprocessorDefsK64F) $(LlilumLinkAdditionalDepsK64F) $(LlilumLinkAdditionalLibDirsK64F) $(LlilumLinkAdditionalOptionsK64F) $(LlilumLinkLibDepsK64F) $(LlilumTargetBoardArchitectureK64F) $(LlilumAsmAdditionalOptionsK64F) $(LlilumStackSizeK64F) $(LlilumHeapSizeK64F) $(LlilumClAdditionalOptionsSTM32F091) $(LlilumClAdditionalIncludesSTM32F091) $(LlilumClPreprocessorDefsSTM32F091) $(LlilumLinkAdditionalDepsSTM32F091) $(LlilumLinkAdditionalLibDirsSTM32F091) $(LlilumLinkAdditionalOptionsSTM32F091) $(LlilumLinkLibDepsSTM32F091) $(LlilumTargetBoardArchitectureSTM32F091) $(LlilumAsmAdditionalOptionsSTM32F091) $(LlilumStackSizeSTM32F091) $(LlilumHeapSizeSTM32F091) $(LlilumOpenOcdInterfaceCfgSTM32F091) $(LlilumOpenOcdBoardCfgSTM32F091) $(LlilumClAdditionalOptionsSTM32L152) $(LlilumClAdditionalIncludesSTM32L152) $(LlilumClPreprocessorDefsSTM32L152) $(LlilumLinkAdditionalDepsSTM32L152) $(LlilumLinkAdditionalLibDirsSTM32L152) $(LlilumLinkAdditionalOptionsSTM32L152) $(LlilumLinkLibDepsSTM32L152) $(LlilumTargetBoardArchitectureSTM32L152) $(LlilumAsmAdditionalOptionsSTM32L152) $(LlilumStackSizeSTM32L152) $(LlilumHeapSizeSTM32L152) $(LlilumOpenOcdInterfaceCfgSTM32L152) $(LlilumOpenOcdBoardCfgSTM32L152) $(LlilumClAdditionalOptionsSTM32F411) $(LlilumClAdditionalIncludesSTM32F411) $(LlilumClPreprocessorDefsSTM32F411) $(LlilumLinkAdditionalDepsSTM32F411) $(LlilumLinkAdditionalLibDirsSTM32F411) $(LlilumLinkAdditionalOptionsSTM32F411) $(LlilumLinkLibDepsSTM32F411) $(LlilumTargetBoardArchitectureSTM32F411) $(LlilumAsmAdditionalOptionsSTM32F411) $(LlilumStackSizeSTM32F411) $(LlilumHeapSizeSTM32F411) $(LlilumOpenOcdInterfaceCfgSTM32F411) $(LlilumOpenOcdBoardCfgSTM32F411) $(LlilumClAdditionalOptionsSTM32F401) $(LlilumClAdditionalIncludesSTM32F401) $(LlilumClPreprocessorDefsSTM32F401) $(LlilumLinkAdditionalDepsSTM32F401) $(LlilumLinkAdditionalLibDirsSTM32F401) $(LlilumLinkAdditionalOptionsSTM32F401) $(LlilumLinkLibDepsSTM32F401) $(LlilumTargetBoardArchitectureSTM32F401) $(LlilumAsmAdditionalOptionsSTM32F401) $(LlilumStackSizeSTM32F401) $(LlilumHeapSizeSTM32F401) $(LlilumOpenOcdInterfaceCfgSTM32F401) $(LlilumOpenOcdBoardCfgSTM32F401) DynamicLibrary true $(LlilumTargetBoardArchitecture) DynamicLibrary $(LlilumTargetBoardArchitecture) system false $(LlilumOutputName) .elf $(LlilumGccBin);$(ExecutablePath) $(LlilumOutputName) .elf $(LlilumGccBin);$(ExecutablePath) Use pch.h $(LlilumClAdditionalOptions) %(AdditionalOptions) $(LlilumClAdditionalIncludes);%(AdditionalIncludeDirectories);$(NativeIncludes) $(LlilumClPreprocessorDefs);DEBUG;%(PreprocessorDefinitions);__DEFAULT_STACK_SIZE=$(LlilumStackSize);__HEAP_SIZE=$(LlilumHeapSize) $(LlilumAsmAdditionalOptions) %(LlilumClAdditionalOptions) -Wa,--defsym,__HEAP_SIZE=$(LlilumHeapSize) $(LlilumLinkAdditionalDeps) $(LlilumLinkAdditionalLibDirs) $(LlilumLinkAdditionalOptions) %(AdditionalOptions) $(LlilumLinkLibDeps) Use pch.h $(LlilumClAdditionalOptions) %(AdditionalOptions) $(LlilumClAdditionalIncludes);%(AdditionalIncludeDirectories);$(NativeIncludes) $(LlilumClPreprocessorDefs);%(PreprocessorDefinitions);__DEFAULT_STACK_SIZE=$(LlilumStackSize);__HEAP_SIZE=$(LlilumHeapSize) $(LlilumAsmAdditionalOptions) %(LlilumClAdditionalOptions) -Wa,--defsym,__HEAP_SIZE=$(LlilumHeapSize) $(LlilumLinkAdditionalDeps) $(LlilumLinkAdditionalLibDirs) $(LlilumLinkAdditionalOptions) %(AdditionalOptions) $(LlilumLinkLibDeps) {$guid1$} true true true true true ================================================ FILE: VisualStudio/LlilumProjectType/LlilumApplication/LlilumApplication.ProjectTemplate/LlilumNative/Source.cpp ================================================ extern "C" { // User's C interop code goes here // Dummy function used in Program.cs as an example int AddOneInterop(int input) { return input + 1; } } ================================================ FILE: VisualStudio/LlilumProjectType/LlilumApplication/LlilumApplication.ProjectTemplate/LlilumNative/mbed_simple_K64F.FrontEndConfig ================================================ ### ### NOTE: This file can be used in the SDK AS-IS, or remove all instances of #~# to use as manual input for the FrontEnd project ### ### ### Location of the Zelig assemblies. ### #~#-HostAssemblyDir ..\..\..\..\ZeligBuild\Host\bin\Debug #~#-DeviceAssemblyDir ..\..\..\..\ZeligBuild\Target\bin\Debug -Architecture cortex-m4 #~#-CompilationSetupPath ..\..\..\..\ZeligBuild\Host\bin\Debug\Microsoft.Llilum.BoardConfigurations.K64F.dll -CompilationSetup Microsoft.Llilum.BoardConfigurations.K64FMBEDHostedCompilationSetup ### ### We need to include this assembly to get the right drivers. ### -Reference Microsoft.CortexM4OnMBED -Reference Microsoft.CortexM4OnCMSISCore -Reference Microsoft.DeviceModels.ModelForCortexM4 -Reference K64F -Reference Microsoft.Zelig.LlilumCMSIS-RTOS ### ### Add compilation phases, in order ### #-CompilationPhaseDisabled ReduceNumberOfTemporaries #-CompilationPhaseDisabled TransformFinallyBlocksIntoTryBlocks #-CompilationPhaseDisabled ApplyClassExtensions #-CompilationPhaseDisabled PrepareImplementationOfInternalMethods #-CompilationPhaseDisabled CrossReferenceTypeSystem #-CompilationPhaseDisabled ApplyConfigurationSettings -CompilationPhaseDisabled ResourceManagerOptimizations #-CompilationPhaseDisabled HighLevelTransformations #-CompilationPhaseDisabled PropagateCompilationConstraints #-CompilationPhaseDisabled ComputeCallsClosure #-CompilationPhaseDisabled EstimateTypeSystemReduction #-CompilationPhaseDisabled CompleteImplementationOfInternalMethods #-CompilationPhaseDisabled ReduceTypeSystem -CompilationPhaseDisabled PrepareExternalMethods #-CompilationPhaseDisabled DetectNonImplementedInternalCalls #-CompilationPhaseDisabled OrderStaticConstructors #-CompilationPhaseDisabled LayoutTypes #-CompilationPhaseDisabled HighLevelToMidLevelConversion #-CompilationPhaseDisabled FromImplicitToExplicitExceptions #-CompilationPhaseDisabled ReferenceCountingGarbageCollection -CompilationPhaseDisabled MidLevelToLowLevelConversion -CompilationPhaseDisabled ConvertUnsupportedOperatorsToMethodCalls -CompilationPhaseDisabled ExpandAggregateTypes -CompilationPhaseDisabled SplitComplexOperators -CompilationPhaseDisabled FuseOperators #-CompilationPhaseDisabled Optimizations -CompilationPhaseDisabled ConvertToSSA -CompilationPhaseDisabled PrepareForRegisterAllocation -CompilationPhaseDisabled CollectRegisterAllocationConstraints -CompilationPhaseDisabled AllocateRegisters #-CompilationPhaseDisabled GenerateImage #-CompilationPhaseDisabled Done ### ### The program to compile. ### #~#..\..\..\..\ZeligBuild\Target\bin\Debug\Microsoft.Zelig.Test.mbed.Simple.exe ### ### Where to put the results. ### #~#-OutputName Microsoft.Zelig.Test.mbed.Simple #~#-OutputDir ..\..\..\..\LLVM2IR_results\mbed\simple ### ### Dumps and diagnostics ### #-DumpIRBeforePhase All #-DumpIR #-DumpIRpre #-DumpIRpost #-DumpIRXML #-DumpFlattenedCallGraph -DumpLLVMIR #-ReloadState #-DumpLLVMIR_TextRepresentation -MaxProcs 8 #~#-NoSDK -GenerateObj # examples of overriding opt.exe and llc arguments # the examples here are the same as the defaults but can be modified to suit a variety of test # scenarios and experimentations #-LlvmOptArgs "-verify-debug-info -verify-dom-info -verify-each -verify-loop-info -verify-regalloc -verify-region-info -march=thumb -mcpu=cortex-m3 -aa-eval -indvars -gvn -globaldce -adce -dce -tailcallopt -scalarrepl -mem2reg -ipconstprop -deadargelim -sccp -dce -ipsccp -dce -constmerge -scev-aa -targetlibinfo -irce -dse -dce -argpromotion -mem2reg -adce -mem2reg -globaldce -die -dce -dse" #-LlvmLlcArgs "-O2 -code-model=small -data-sections -relocation-model=pic -march=thumb -mcpu=cortex-m3 -filetype=obj -mtriple=thumbv7m-none-eabi" # While the compiler is pretty good at figuring out where the LLVM tools are from # current Environment variables or registry entires you can manually specify the # path to find the LLVM binaries. # note: Environment variabes (i.e %MY_VAR%) are supported and expanded as with all # options in the FrontendConfig files so you can specify a custom variable if needed #-LlvmBinPath c:\src\llvm\llvm-3.7.0.src\build\x64\Release\bin\ ================================================ FILE: VisualStudio/LlilumProjectType/LlilumApplication/LlilumApplication.ProjectTemplate/LlilumNative/mbed_simple_LPC1768.FrontEndConfig ================================================ ### ### NOTE: This file can be used in the SDK AS-IS, or remove all instances of #~# to use as manual input for the FrontEnd project ### ### ### Location of the Zelig assemblies. ### #~#-HostAssemblyDir ..\..\..\..\ZeligBuild\Host\bin\Debug #~#-DeviceAssemblyDir ..\..\..\..\ZeligBuild\Target\bin\Debug -Architecture cortex-m3 #~#-CompilationSetupPath ..\..\..\..\ZeligBuild\Host\bin\Debug\Microsoft.Llilum.BoardConfigurations.LPC1768.dll -CompilationSetup Microsoft.Llilum.BoardConfigurations.LPC1768MBEDHostedCompilationSetup ### ### We need to include this assembly to get the right drivers. ### -Reference Microsoft.CortexM3OnMBED -Reference Microsoft.CortexM3OnCMSISCore -Reference Microsoft.DeviceModels.ModelForCortexM3 -Reference LPC1768 ### ### Add compilation phases, in order ### #-CompilationPhaseDisabled ReduceNumberOfTemporaries #-CompilationPhaseDisabled TransformFinallyBlocksIntoTryBlocks #-CompilationPhaseDisabled ApplyClassExtensions #-CompilationPhaseDisabled PrepareImplementationOfInternalMethods #-CompilationPhaseDisabled CrossReferenceTypeSystem #-CompilationPhaseDisabled ApplyConfigurationSettings -CompilationPhaseDisabled ResourceManagerOptimizations #-CompilationPhaseDisabled HighLevelTransformations #-CompilationPhaseDisabled PropagateCompilationConstraints #-CompilationPhaseDisabled ComputeCallsClosure #-CompilationPhaseDisabled EstimateTypeSystemReduction #-CompilationPhaseDisabled CompleteImplementationOfInternalMethods #-CompilationPhaseDisabled ReduceTypeSystem -CompilationPhaseDisabled PrepareExternalMethods #-CompilationPhaseDisabled DetectNonImplementedInternalCalls #-CompilationPhaseDisabled OrderStaticConstructors #-CompilationPhaseDisabled LayoutTypes #-CompilationPhaseDisabled HighLevelToMidLevelConversion #-CompilationPhaseDisabled FromImplicitToExplicitExceptions #-CompilationPhaseDisabled ReferenceCountingGarbageCollection -CompilationPhaseDisabled MidLevelToLowLevelConversion -CompilationPhaseDisabled ConvertUnsupportedOperatorsToMethodCalls -CompilationPhaseDisabled ExpandAggregateTypes -CompilationPhaseDisabled SplitComplexOperators -CompilationPhaseDisabled FuseOperators #-CompilationPhaseDisabled Optimizations -CompilationPhaseDisabled ConvertToSSA -CompilationPhaseDisabled PrepareForRegisterAllocation -CompilationPhaseDisabled CollectRegisterAllocationConstraints -CompilationPhaseDisabled AllocateRegisters #-CompilationPhaseDisabled GenerateImage #-CompilationPhaseDisabled Done -CompilationOption System.String GarbageCollectionManager ConservativeMarkAndSweepCollector ### ### The program to compile. ### #~#..\..\..\..\ZeligBuild\Target\bin\Debug\Microsoft.Zelig.Test.mbed.Simple.exe ### ### Where to put the results. ### #~#-OutputName Microsoft.Zelig.Test.mbed.Simple #~#-OutputDir ..\..\..\..\LLVM2IR_results\mbed\simple ### ### Dumps and diagnostics ### #-DumpIRBeforePhase ReduceNumberOfTemporaries TransformFinallyBlocksIntoTryBlocks ApplyClassExtensions #-DumpIRBeforePhase All #-DumpIR #-DumpIRpre #-DumpIRpost #-DumpIRXML #-DumpFlattenedCallGraph -DumpLLVMIR #-ReloadState #-DumpLLVMIR_TextRepresentation -MaxProcs 8 #~#-NoSDK ### ### LLVM CodeGeneration ### -GenerateObj # examples of overriding opt.exe and llc arguments # the examples here are the same as the defaults but can be modified to suit a variety of test # scenarios and experimentations #-LlvmOptArgs "-verify-debug-info -verify-dom-info -verify-each -verify-loop-info -verify-regalloc -verify-region-info -march=thumb -mcpu=cortex-m3 -aa-eval -indvars -gvn -globaldce -adce -dce -tailcallopt -scalarrepl -mem2reg -ipconstprop -deadargelim -sccp -dce -ipsccp -dce -constmerge -scev-aa -targetlibinfo -irce -dse -dce -argpromotion -mem2reg -adce -mem2reg -globaldce -die -dce -dse" #-LlvmLlcArgs "-O2 -code-model=small -data-sections -relocation-model=pic -march=thumb -mcpu=cortex-m3 -filetype=obj -mtriple=thumbv7m-none-eabi" # While the compiler is pretty good at figuring out where the LLVM tools are from # current Environment variables or registry entires you can manually specify the # path to find the LLVM binaries. # note: Environment variabes (i.e %MY_VAR%) are supported and expanded as with all # options in the FrontendConfig files so you can specify a custom variable if needed #-LlvmBinPath \\netmfbld02\LLVM\3.7.0\build\Win32\Release\bin ================================================ FILE: VisualStudio/LlilumProjectType/LlilumApplication/LlilumApplication.ProjectTemplate/LlilumNative/mbed_simple_STM32F091.FrontEndConfig ================================================ ### ### NOTE: This file can be used in the SDK AS-IS, or remove all instances of #~# to use as manual input for the FrontEnd project ### ### ### Location of the Zelig assemblies. ### #~#-HostAssemblyDir ..\..\..\..\ZeligBuild\Host\bin\Debug #~#-DeviceAssemblyDir ..\..\..\..\ZeligBuild\Target\bin\Debug -Architecture cortex-m0 #~#-CompilationSetupPath ..\..\..\..\ZeligBuild\Host\bin\Debug\Microsoft.Llilum.BoardConfigurations.STM32F091.dll -CompilationSetup Microsoft.Llilum.BoardConfigurations.STM32F091MBEDHostedCompilationSetup ### ### We need to include this assembly to get the right drivers. ### -Reference Microsoft.CortexM0OnMBED -Reference Microsoft.CortexM0OnCMSISCore -Reference Microsoft.DeviceModels.ModelForCortexM0 -Reference STM32F091 ### ### Add compilation phases, in order ### #-CompilationPhaseDisabled ReduceNumberOfTemporaries #-CompilationPhaseDisabled TransformFinallyBlocksIntoTryBlocks #-CompilationPhaseDisabled ApplyClassExtensions #-CompilationPhaseDisabled PrepareImplementationOfInternalMethods #-CompilationPhaseDisabled CrossReferenceTypeSystem #-CompilationPhaseDisabled ApplyConfigurationSettings -CompilationPhaseDisabled ResourceManagerOptimizations #-CompilationPhaseDisabled HighLevelTransformations #-CompilationPhaseDisabled PropagateCompilationConstraints #-CompilationPhaseDisabled ComputeCallsClosure #-CompilationPhaseDisabled EstimateTypeSystemReduction #-CompilationPhaseDisabled CompleteImplementationOfInternalMethods #-CompilationPhaseDisabled ReduceTypeSystem -CompilationPhaseDisabled PrepareExternalMethods #-CompilationPhaseDisabled DetectNonImplementedInternalCalls #-CompilationPhaseDisabled OrderStaticConstructors #-CompilationPhaseDisabled LayoutTypes #-CompilationPhaseDisabled HighLevelToMidLevelConversion #-CompilationPhaseDisabled FromImplicitToExplicitExceptions #-CompilationPhaseDisabled ReferenceCountingGarbageCollection -CompilationPhaseDisabled MidLevelToLowLevelConversion -CompilationPhaseDisabled ConvertUnsupportedOperatorsToMethodCalls -CompilationPhaseDisabled ExpandAggregateTypes -CompilationPhaseDisabled SplitComplexOperators -CompilationPhaseDisabled FuseOperators #-CompilationPhaseDisabled Optimizations -CompilationPhaseDisabled ConvertToSSA -CompilationPhaseDisabled PrepareForRegisterAllocation -CompilationPhaseDisabled CollectRegisterAllocationConstraints -CompilationPhaseDisabled AllocateRegisters #-CompilationPhaseDisabled GenerateImage #-CompilationPhaseDisabled Done ### ### The program to compile. ### #~#..\..\..\..\ZeligBuild\Target\bin\Debug\Microsoft.Zelig.Test.mbed.Simple.exe ### ### Where to put the results. ### #~#-OutputName Microsoft.Zelig.Test.mbed.Simple #~#-OutputDir ..\..\..\..\LLVM2IR_results\mbed\simple ### ### Dumps and diagnostics ### #-DumpIRBeforePhase ReduceNumberOfTemporaries TransformFinallyBlocksIntoTryBlocks ApplyClassExtensions #-DumpIRBeforePhase All #-DumpIR #-DumpIRpre #-DumpIRpost #-DumpIRXML #-DumpFlattenedCallGraph -DumpLLVMIR #-ReloadState #-DumpLLVMIR_TextRepresentation -MaxProcs 8 #~#-NoSDK ### ### LLVM CodeGeneration ### -GenerateObj # examples of overriding opt.exe and llc arguments # the examples here are the same as the defaults but can be modified to suit a variety of test # scenarios and experimentations #-LlvmOptArgs "-verify-debug-info -verify-dom-info -verify-each -verify-loop-info -verify-regalloc -verify-region-info -march=thumb -mcpu=cortex-m3 -aa-eval -indvars -gvn -globaldce -adce -dce -tailcallopt -scalarrepl -mem2reg -ipconstprop -deadargelim -sccp -dce -ipsccp -dce -constmerge -scev-aa -targetlibinfo -irce -dse -dce -argpromotion -mem2reg -adce -mem2reg -globaldce -die -dce -dse" #-LlvmLlcArgs "-O2 -code-model=small -data-sections -relocation-model=pic -march=thumb -mcpu=cortex-m3 -filetype=obj -mtriple=thumbv7m-none-eabi" # While the compiler is pretty good at figuring out where the LLVM tools are from # current Environment variables or registry entires you can manually specify the # path to find the LLVM binaries. # note: Environment variabes (i.e %MY_VAR%) are supported and expanded as with all # options in the FrontendConfig files so you can specify a custom variable if needed #-LlvmBinPath c:\src\llvm\llvm-3.7.0.src\build\x64\Release\bin ================================================ FILE: VisualStudio/LlilumProjectType/LlilumApplication/LlilumApplication.ProjectTemplate/LlilumNative/mbed_simple_STM32F401.FrontEndConfig ================================================ ### ### NOTE: This file can be used in the SDK AS-IS, or remove all instances of #~# to use as manual input for the FrontEnd project ### ### ### Location of the Zelig assemblies. ### #~#-HostAssemblyDir ..\..\..\..\ZeligBuild\Host\bin\Debug #~#-DeviceAssemblyDir ..\..\..\..\ZeligBuild\Target\bin\Debug -Architecture cortex-m4 #~#-CompilationSetupPath ..\..\..\..\ZeligBuild\Host\bin\Debug\Microsoft.Llilum.BoardConfigurations.STM32F401.dll -CompilationSetup Microsoft.Llilum.BoardConfigurations.STM32F401MBEDHostedCompilationSetup ### ### We need to include this assembly to get the right drivers. ### -Reference Microsoft.CortexM4OnMBED -Reference Microsoft.CortexM4OnCMSISCore -Reference Microsoft.DeviceModels.ModelForCortexM4 -Reference STM32F401 ### ### Add compilation phases, in order ### #-CompilationPhaseDisabled ReduceNumberOfTemporaries #-CompilationPhaseDisabled TransformFinallyBlocksIntoTryBlocks #-CompilationPhaseDisabled ApplyClassExtensions #-CompilationPhaseDisabled PrepareImplementationOfInternalMethods #-CompilationPhaseDisabled CrossReferenceTypeSystem #-CompilationPhaseDisabled ApplyConfigurationSettings -CompilationPhaseDisabled ResourceManagerOptimizations #-CompilationPhaseDisabled HighLevelTransformations #-CompilationPhaseDisabled PropagateCompilationConstraints #-CompilationPhaseDisabled ComputeCallsClosure #-CompilationPhaseDisabled EstimateTypeSystemReduction #-CompilationPhaseDisabled CompleteImplementationOfInternalMethods #-CompilationPhaseDisabled ReduceTypeSystem -CompilationPhaseDisabled PrepareExternalMethods #-CompilationPhaseDisabled DetectNonImplementedInternalCalls #-CompilationPhaseDisabled OrderStaticConstructors #-CompilationPhaseDisabled LayoutTypes #-CompilationPhaseDisabled HighLevelToMidLevelConversion #-CompilationPhaseDisabled FromImplicitToExplicitExceptions #-CompilationPhaseDisabled ReferenceCountingGarbageCollection -CompilationPhaseDisabled MidLevelToLowLevelConversion -CompilationPhaseDisabled ConvertUnsupportedOperatorsToMethodCalls -CompilationPhaseDisabled ExpandAggregateTypes -CompilationPhaseDisabled SplitComplexOperators -CompilationPhaseDisabled FuseOperators #-CompilationPhaseDisabled Optimizations -CompilationPhaseDisabled ConvertToSSA -CompilationPhaseDisabled PrepareForRegisterAllocation -CompilationPhaseDisabled CollectRegisterAllocationConstraints -CompilationPhaseDisabled AllocateRegisters #-CompilationPhaseDisabled GenerateImage #-CompilationPhaseDisabled Done ### ### The program to compile. ### #~#..\..\..\..\ZeligBuild\Target\bin\Debug\Microsoft.Zelig.Test.mbed.Simple.exe ### ### Where to put the results. ### #~#-OutputName Microsoft.Zelig.Test.mbed.Simple #~#-OutputDir ..\..\..\..\LLVM2IR_results\mbed\simple #-DumpIR #-DumpIRpre #-DumpIRpost #-DumpIRXML #-DumpFlattenedCallGraph -DumpLLVMIR #-ReloadState #-DumpLLVMIR_TextRepresentation -MaxProcs 8 #~#-NoSDK -GenerateObj # examples of overriding opt.exe and llc arguments # the examples here are the same as the defaults but can be modified to suit a variety of test # scenarios and experimentations #-LlvmOptArgs "-verify-debug-info -verify-dom-info -verify-each -verify-loop-info -verify-regalloc -verify-region-info -march=thumb -mcpu=cortex-m3 -aa-eval -indvars -gvn -globaldce -adce -dce -tailcallopt -scalarrepl -mem2reg -ipconstprop -deadargelim -sccp -dce -ipsccp -dce -constmerge -scev-aa -targetlibinfo -irce -dse -dce -argpromotion -mem2reg -adce -mem2reg -globaldce -die -dce -dse" #-LlvmLlcArgs "-O2 -code-model=small -data-sections -relocation-model=pic -march=thumb -mcpu=cortex-m3 -filetype=obj -mtriple=thumbv7m-none-eabi" # While the compiler is pretty good at figuring out where the LLVM tools are from # current Environment variables or registry entires you can manually specify the # path to find the LLVM binaries. # note: Environment variabes (i.e %MY_VAR%) are supported and expanded as with all # options in the FrontendConfig files so you can specify a custom variable if needed #-LlvmBinPath \\netmfbld02\LLVM\3.7.0\build\Win32\Release\bin ================================================ FILE: VisualStudio/LlilumProjectType/LlilumApplication/LlilumApplication.ProjectTemplate/LlilumNative/mbed_simple_STM32F411.FrontEndConfig ================================================ ### ### NOTE: This file can be used in the SDK AS-IS, or remove all instances of #~# to use as manual input for the FrontEnd project ### ### ### Location of the Zelig assemblies. ### #~#-HostAssemblyDir ..\..\..\..\ZeligBuild\Host\bin\Debug #~#-DeviceAssemblyDir ..\..\..\..\ZeligBuild\Target\bin\Debug -Architecture cortex-m4 #~#-CompilationSetupPath ..\..\..\..\ZeligBuild\Host\bin\Debug\Microsoft.Llilum.BoardConfigurations.STM32F411.dll -CompilationSetup Microsoft.Llilum.BoardConfigurations.STM32F411MBEDHostedCompilationSetup ### ### We need to include this assembly to get the right drivers. ### -Reference Microsoft.CortexM4OnMBED -Reference Microsoft.CortexM4OnCMSISCore -Reference Microsoft.DeviceModels.ModelForCortexM4 -Reference STM32F411 ### ### Add compilation phases, in order ### #-CompilationPhaseDisabled ReduceNumberOfTemporaries #-CompilationPhaseDisabled TransformFinallyBlocksIntoTryBlocks #-CompilationPhaseDisabled ApplyClassExtensions #-CompilationPhaseDisabled PrepareImplementationOfInternalMethods #-CompilationPhaseDisabled CrossReferenceTypeSystem #-CompilationPhaseDisabled ApplyConfigurationSettings -CompilationPhaseDisabled ResourceManagerOptimizations #-CompilationPhaseDisabled HighLevelTransformations #-CompilationPhaseDisabled PropagateCompilationConstraints #-CompilationPhaseDisabled ComputeCallsClosure #-CompilationPhaseDisabled EstimateTypeSystemReduction #-CompilationPhaseDisabled CompleteImplementationOfInternalMethods #-CompilationPhaseDisabled ReduceTypeSystem -CompilationPhaseDisabled PrepareExternalMethods #-CompilationPhaseDisabled DetectNonImplementedInternalCalls #-CompilationPhaseDisabled OrderStaticConstructors #-CompilationPhaseDisabled LayoutTypes #-CompilationPhaseDisabled HighLevelToMidLevelConversion #-CompilationPhaseDisabled FromImplicitToExplicitExceptions #-CompilationPhaseDisabled ReferenceCountingGarbageCollection -CompilationPhaseDisabled MidLevelToLowLevelConversion -CompilationPhaseDisabled ConvertUnsupportedOperatorsToMethodCalls -CompilationPhaseDisabled ExpandAggregateTypes -CompilationPhaseDisabled SplitComplexOperators -CompilationPhaseDisabled FuseOperators #-CompilationPhaseDisabled Optimizations -CompilationPhaseDisabled ConvertToSSA -CompilationPhaseDisabled PrepareForRegisterAllocation -CompilationPhaseDisabled CollectRegisterAllocationConstraints -CompilationPhaseDisabled AllocateRegisters #-CompilationPhaseDisabled GenerateImage #-CompilationPhaseDisabled Done ### ### The program to compile. ### #~#..\..\..\..\ZeligBuild\Target\bin\Debug\Microsoft.Zelig.Test.mbed.Simple.exe ### ### Where to put the results. ### #~#-OutputName Microsoft.Zelig.Test.mbed.Simple #~#-OutputDir ..\..\..\..\LLVM2IR_results\mbed\simple ### ### Dumps and diagnostics ### #-DumpIRBeforePhase ReduceNumberOfTemporaries TransformFinallyBlocksIntoTryBlocks ApplyClassExtensions #-DumpIRBeforePhase All #-DumpIR #-DumpIRpre #-DumpIRpost #-DumpIRXML #-DumpFlattenedCallGraph -DumpLLVMIR #-ReloadState #-DumpLLVMIR_TextRepresentation -MaxProcs 8 #~#-NoSDK ### ### LLVM CodeGeneration ### -GenerateObj # examples of overriding opt.exe and llc arguments # the examples here are the same as the defaults but can be modified to suit a variety of test # scenarios and experimentations #-LlvmOptArgs "-verify-debug-info -verify-dom-info -verify-each -verify-loop-info -verify-regalloc -verify-region-info -march=thumb -mcpu=cortex-m3 -aa-eval -indvars -gvn -globaldce -adce -dce -tailcallopt -scalarrepl -mem2reg -ipconstprop -deadargelim -sccp -dce -ipsccp -dce -constmerge -scev-aa -targetlibinfo -irce -dse -dce -argpromotion -mem2reg -adce -mem2reg -globaldce -die -dce -dse" #-LlvmLlcArgs "-O2 -code-model=small -data-sections -relocation-model=pic -march=thumb -mcpu=cortex-m3 -filetype=obj -mtriple=thumbv7m-none-eabi" # While the compiler is pretty good at figuring out where the LLVM tools are from # current Environment variables or registry entires you can manually specify the # path to find the LLVM binaries. # note: Environment variabes (i.e %MY_VAR%) are supported and expanded as with all # options in the FrontendConfig files so you can specify a custom variable if needed #-LlvmBinPath \\netmfbld02\LLVM\3.7.0\build\Win32\Release\bin ================================================ FILE: VisualStudio/LlilumProjectType/LlilumApplication/LlilumApplication.ProjectTemplate/LlilumNative/mbed_simple_STM32L152.FrontEndConfig ================================================ ### ### NOTE: This file can be used in the SDK AS-IS, or remove all instances of #~# to use as manual input for the FrontEnd project ### ### ### Location of the Zelig assemblies. ### #~#-HostAssemblyDir ..\..\..\..\ZeligBuild\Host\bin\Debug #~#-DeviceAssemblyDir ..\..\..\..\ZeligBuild\Target\bin\Debug -Architecture cortex-m3 #~#-CompilationSetupPath ..\..\..\..\ZeligBuild\Host\bin\Debug\Microsoft.Llilum.BoardConfigurations.STM32L152.dll -CompilationSetup Microsoft.Llilum.BoardConfigurations.STM32L152MBEDHostedCompilationSetup ### ### We need to include this assembly to get the right drivers. ### -Reference Microsoft.CortexM3OnMBED -Reference Microsoft.CortexM3OnCMSISCore -Reference Microsoft.DeviceModels.ModelForCortexM3 -Reference STM32L152 ### ### Add compilation phases, in order ### #-CompilationPhaseDisabled ReduceNumberOfTemporaries #-CompilationPhaseDisabled TransformFinallyBlocksIntoTryBlocks #-CompilationPhaseDisabled ApplyClassExtensions #-CompilationPhaseDisabled PrepareImplementationOfInternalMethods #-CompilationPhaseDisabled CrossReferenceTypeSystem #-CompilationPhaseDisabled ApplyConfigurationSettings -CompilationPhaseDisabled ResourceManagerOptimizations #-CompilationPhaseDisabled HighLevelTransformations #-CompilationPhaseDisabled PropagateCompilationConstraints #-CompilationPhaseDisabled ComputeCallsClosure #-CompilationPhaseDisabled EstimateTypeSystemReduction #-CompilationPhaseDisabled CompleteImplementationOfInternalMethods #-CompilationPhaseDisabled ReduceTypeSystem -CompilationPhaseDisabled PrepareExternalMethods #-CompilationPhaseDisabled DetectNonImplementedInternalCalls #-CompilationPhaseDisabled OrderStaticConstructors #-CompilationPhaseDisabled LayoutTypes #-CompilationPhaseDisabled HighLevelToMidLevelConversion #-CompilationPhaseDisabled FromImplicitToExplicitExceptions #-CompilationPhaseDisabled ReferenceCountingGarbageCollection -CompilationPhaseDisabled MidLevelToLowLevelConversion -CompilationPhaseDisabled ConvertUnsupportedOperatorsToMethodCalls -CompilationPhaseDisabled ExpandAggregateTypes -CompilationPhaseDisabled SplitComplexOperators -CompilationPhaseDisabled FuseOperators #-CompilationPhaseDisabled Optimizations -CompilationPhaseDisabled ConvertToSSA -CompilationPhaseDisabled PrepareForRegisterAllocation -CompilationPhaseDisabled CollectRegisterAllocationConstraints -CompilationPhaseDisabled AllocateRegisters #-CompilationPhaseDisabled GenerateImage #-CompilationPhaseDisabled Done ### ### The program to compile. ### #~#..\..\..\..\ZeligBuild\Target\bin\Debug\Microsoft.Zelig.Test.mbed.Simple.exe ### ### Where to put the results. ### #~#-OutputName Microsoft.Zelig.Test.mbed.Simple #~#-OutputDir ..\..\..\..\LLVM2IR_results\mbed\simple ### ### Dumps and diagnostics ### #-DumpIRBeforePhase All -DumpIR #-DumpIRpre #-DumpIRpost #-DumpIRXML #-DumpFlattenedCallGraph -DumpLLVMIR #-ReloadState #-DumpLLVMIR_TextRepresentation -MaxProcs 8 #~#-NoSDK -GenerateObj # examples of overriding opt.exe and llc arguments # the examples here are the same as the defaults but can be modified to suit a variety of test # scenarios and experimentations #-LlvmOptArgs "-verify-debug-info -verify-dom-info -verify-each -verify-loop-info -verify-regalloc -verify-region-info -march=thumb -mcpu=cortex-m3 -aa-eval -indvars -gvn -globaldce -adce -dce -tailcallopt -scalarrepl -mem2reg -ipconstprop -deadargelim -sccp -dce -ipsccp -dce -constmerge -scev-aa -targetlibinfo -irce -dse -dce -argpromotion -mem2reg -adce -mem2reg -globaldce -die -dce -dse" #-LlvmLlcArgs "-O2 -code-model=small -data-sections -relocation-model=pic -march=thumb -mcpu=cortex-m3 -filetype=obj -mtriple=thumbv7m-none-eabi" # While the compiler is pretty good at figuring out where the LLVM tools are from # current Environment variables or registry entires you can manually specify the # path to find the LLVM binaries. # note: Environment variabes (i.e %MY_VAR%) are supported and expanded as with all # options in the FrontendConfig files so you can specify a custom variable if needed #-LlvmBinPath \\netmfbld02\LLVM\3.7.0\build\Win32\Release\bin ================================================ FILE: VisualStudio/LlilumProjectType/LlilumApplication/LlilumApplication.ProjectTemplate/LlilumNative/pch.h ================================================ ================================================ FILE: VisualStudio/LlilumProjectType/LlilumApplication/LlilumApplication.ProjectTemplate/Properties/AssemblyInfo.cs ================================================ using System.Reflection; using System.Runtime.CompilerServices; // // General Information about an assembly is controlled through the following // set of attributes. Change these attribute values to modify the information // associated with an assembly. // [assembly: AssemblyTitle("")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("")] [assembly: AssemblyCopyright("")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Revision and Build Numbers // by using the '*' as shown below: [assembly: AssemblyVersion("1.0.*")] ================================================ FILE: VisualStudio/LlilumProjectType/LlilumApplication/LlilumApplication.ProjectType/BuildSystem/DeployedBuildSystem/CustomProject.Default.props ================================================  $(MSBuildThisFileDirectory) Debug x86 7.0 v4.6 Client .NETFramework,Version=$(TargetFrameworkVersion) exe bin\$(Configuration)\ true LlilumDebugger TAB_SDK_ALL TAB_ASSEMBLY_ALL $(MSBuildProjectName) $(Name) $(Name) false true ================================================ FILE: VisualStudio/LlilumProjectType/LlilumApplication/LlilumApplication.ProjectType/BuildSystem/DeployedBuildSystem/CustomProject.props ================================================  $(LLILUM_SDK) $(LlilumSDK)LLVM\Debug\bin\ $(LlilumSDK)mbed\ LPC1768 TARGET_LPC1768 TARGET_NXP TOOLCHAIN_GCC_ARM TARGET_LPC176X TARGET_MBED_LPC1768 $(SolutionName) $(LlilumSDK)ARM_GCC\4.9\bin $(OutDir)\$(LlilumOutputName).bin $(LlilumSDK)\bin\Microsoft.Zelig.Compiler.exe $(MSBuildProjectDirectory)\mbed_simple_$(LlilumBoardName).FrontEndConfig $(LlilumSDK) $(LlilumLLVM) $(LlilumCompiler) $(LlilumConfig) $(LlilumTargetDir) $(LlilumTargetBoard) $(LlilumTargetBrand) $(LlilumTargetToolchain) $(LlilumTargetClass) $(LlilumTargetBoardMbed) $(LlilumOutputName) $(LlilumGccBin) $(LlilumOutputBin) ================================================ FILE: VisualStudio/LlilumProjectType/LlilumApplication/LlilumApplication.ProjectType/BuildSystem/DeployedBuildSystem/CustomProject.targets ================================================  Debug AnyCPU Release AnyCPU Project Project File Invisible File;BrowseObject ;BrowseObject ProjectSubscriptionService;BrowseObject BrowseObject Project ================================================ FILE: VisualStudio/LlilumProjectType/LlilumApplication/LlilumApplication.ProjectType/BuildSystem/DeployedBuildSystem/CustomProjectCs.targets ================================================  File BrowseObject Project ================================================ FILE: VisualStudio/LlilumProjectType/LlilumApplication/LlilumApplication.ProjectType/BuildSystem/Rules/CustomPropertyPage.xaml ================================================  ================================================ FILE: VisualStudio/LlilumProjectType/LlilumApplication/LlilumApplication.ProjectType/BuildSystem/Rules/LlilumDebugger.xaml ================================================  ================================================ FILE: VisualStudio/LlilumProjectType/LlilumApplication/LlilumApplication.ProjectType/BuildSystem/Rules/ProjectItemsSchema.xaml ================================================  ================================================ FILE: VisualStudio/LlilumProjectType/LlilumApplication/LlilumApplication.ProjectType/BuildSystem/Rules/debugger_general.xaml ================================================  ================================================ FILE: VisualStudio/LlilumProjectType/LlilumApplication/LlilumApplication.ProjectType/LlilumApplication.ProjectType.csproj ================================================  14.0 14.0 $(MSBuildExtensionsPath32)\Microsoft\VisualStudio\v$(VisualStudioVersion) Debug AnyCPU 8.0.30703 2.0 {82b43b9b-a64c-4715-b499-d71e9ca2bd60};{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC} {74611D01-A97F-438C-B687-448FEEDBE4FB} Library Properties LlilumApplication LlilumApplication v4.5.2 512 true Key.snk Program $(MSBuildProgramFiles32)\Microsoft Visual Studio 14.0\Common7\IDE\devenv.exe /rootSuffix Exp true full false bin\Debug\ DEBUG;TRACE prompt 4 x86 pdbonly true bin\Release\ TRACE prompt 4 True True C:\Program Files (x86)\Microsoft Visual Studio 14.0\Common7\IDE\CommonExtensions\Microsoft\MDD\Debugger\Microsoft.MIDebugEngine.dll ..\..\packages\Microsoft.VisualStudio.Composition.14.0.50715-pre\lib\net451\Microsoft.VisualStudio.Composition.dll True ..\..\packages\Microsoft.VisualStudio.Composition.14.0.50715-pre\lib\net451\Microsoft.VisualStudio.Composition.Configuration.dll True ..\..\packages\Microsoft.VisualStudio.ProjectSystem.14.0.50721-pre\lib\net451\Microsoft.VisualStudio.ProjectSystem.Interop.dll True ..\..\packages\Microsoft.VisualStudio.ProjectSystem.14.0.50721-pre\lib\net451\Microsoft.VisualStudio.ProjectSystem.Utilities.v14.0.dll True ..\..\packages\Microsoft.VisualStudio.ProjectSystem.14.0.50721-pre\lib\net451\Microsoft.VisualStudio.ProjectSystem.V14Only.dll True ..\..\packages\Microsoft.VisualStudio.ProjectSystem.14.0.50721-pre\lib\net451\Microsoft.VisualStudio.ProjectSystem.VS.V14Only.dll True True True True True True True ..\..\packages\Microsoft.VisualStudio.Threading.14.0.50702\lib\net45\Microsoft.VisualStudio.Threading.dll True ..\..\packages\System.Collections.Immutable.1.1.36\lib\portable-net45+win8+wp8+wpa81\System.Collections.Immutable.dll True ..\..\packages\Microsoft.Tpl.Dataflow.4.5.24\lib\portable-net45+win8+wpa81\System.Threading.Tasks.Dataflow.dll True {80F61FFD-C936-4528-BBC3-5DEE0782EBE5} Microsoft.MIEngine.CoreRegisters.ARM BuiltProjectOutputGroup%3bBuiltProjectOutputGroupDependencies%3bGetCopyToOutputDirectoryItems%3bSatelliteDllsProjectOutputGroup%3bPkgdefProjectOutputGroup%3b DebugSymbolsProjectOutputGroup%3b false {5747d247-5fcc-4151-942c-811603768abe} LlilumApplication.ProjectTemplate false TemplateProjectOutputGroup%3b ProjectTemplates Designer None Designer Designer MSBuild:Compile MSBuild:Compile Designer Always true This project references NuGet package(s) that are missing on this computer. Use NuGet Package Restore to download them. For more information, see http://go.microsoft.com/fwlink/?LinkID=322105. The missing file is {0}. ================================================ FILE: VisualStudio/LlilumProjectType/LlilumApplication/LlilumApplication.ProjectType/LlilumDebuggerLaunchProvider.cs ================================================ using System; using System.Collections.Generic; using System.ComponentModel.Composition; using System.Threading.Tasks; using Microsoft.VisualStudio.ProjectSystem; using Microsoft.VisualStudio.ProjectSystem.Debuggers; using Microsoft.VisualStudio.ProjectSystem.Utilities; using Microsoft.VisualStudio.ProjectSystem.Utilities.DebuggerProviders; using Microsoft.VisualStudio.ProjectSystem.VS.Debuggers; using System.Diagnostics; using System.IO; namespace LlilumApplication { [ExportDebugger(LlilumDebugger.SchemaName)] [AppliesTo(MyUnconfiguredProject.UniqueCapability)] public class LlilumDebuggerLaunchProvider : DebugLaunchProviderBase { private static readonly string DebuggerOptionsFormat = @""; private static readonly string DebuggerFileFormat = @"{0}\{1}.bat"; private static readonly string DebuggerScriptContentFormat = @"""{0}"" ""{1}"" {2} %*"; private static readonly string DebuggerLoadScriptContentFormat = @"""{0}"" ""{1}"" -ex ""load ""{1}"""" {2} %*"; // TODO: Specify the assembly full name here [ExportPropertyXamlRuleDefinition("LlilumApplication, Version=1.0.0.0, Culture=neutral, PublicKeyToken=9be6e469bc4921f1", "XamlRuleToCode:LlilumDebugger.xaml", "Project")] [AppliesTo(MyUnconfiguredProject.UniqueCapability)] private object DebuggerXaml { get { throw new NotImplementedException(); } } [ImportingConstructor] public LlilumDebuggerLaunchProvider(ConfiguredProject configuredProject) : base(configuredProject) { } /// /// Gets project properties that the debugger needs to launch. /// [Import] private ProjectProperties DebuggerProperties { get; set; } public override async Task CanLaunchAsync(DebugLaunchOptions launchOptions) { var properties = await this.DebuggerProperties.GetLlilumDebuggerPropertiesAsync(); string commandValue = await properties.LlilumDebuggerCommand.GetEvaluatedValueAtEndAsync(); return !string.IsNullOrEmpty(commandValue); } public string CreateDebuggerFileIfNoneExist(string workingDirectory, string executablePath, string gdbPath, string gdbArgs, string script) { string debuggerFile = string.Format(DebuggerFileFormat, workingDirectory, "tmp_debug"); if(!File.Exists(debuggerFile)) { using (System.IO.StreamWriter file = new System.IO.StreamWriter(debuggerFile)) { file.WriteLine(string.Format(script, gdbPath, executablePath, gdbArgs)); } } return debuggerFile; } public override async Task> QueryDebugTargetsAsync(DebugLaunchOptions launchOptions) { var settings = new DebugLaunchSettings(launchOptions); // The properties that are available via DebuggerProperties are determined by the property XAML files in your project. var debuggerProperties = await this.DebuggerProperties.GetLlilumDebuggerPropertiesAsync(); string dir = await debuggerProperties.LlilumDebuggerWorkingDirectory.GetEvaluatedValueAtEndAsync(); string executable = await debuggerProperties.LlilumDebuggerCommand.GetEvaluatedValueAtEndAsync(); string gdbPath = await debuggerProperties.LlilumGdbPath.GetEvaluatedValueAtEndAsync(); string gdbArgs = await debuggerProperties.LlilumGdbArgs.GetEvaluatedValueAtEndAsync(); var gdbServer = await debuggerProperties.LlilumGdbServerOption.GetEvaluatedValueAtEndAsync(); settings.CurrentDirectory = dir; settings.Executable = executable; // If we are going to deploy with GDB load command, create a script that will also load the elf file string debugScript = DebuggerScriptContentFormat; var deployTool = await debuggerProperties.LlilumDeployTool.GetEvaluatedValueAtEndAsync(); if (string.Compare(deployTool, "gdbloadcommand", true) == 0) { debugScript = DebuggerLoadScriptContentFormat; } // Create the temporary file for passing to the debug engine string debuggerFile = CreateDebuggerFileIfNoneExist(dir, executable, gdbPath, gdbArgs, debugScript); settings.Options = string.Format(DebuggerOptionsFormat, debuggerFile); settings.LaunchOperation = DebugLaunchOperation.CreateProcess; settings.LaunchDebugEngineGuid = new Guid(Microsoft.MIDebugEngine.EngineConstants.EngineId); // Launch py_ocd to communicate with GDB string gdbServerPath = string.Empty; string gdbServerArgs = string.Empty; if(gdbServer.Equals("pyocd")) { gdbServerPath = await debuggerProperties.LlilumPyOcdPath.GetEvaluatedValueAtEndAsync(); gdbServerArgs = await debuggerProperties.LlilumPyOcdArgs.GetEvaluatedValueAtEndAsync(); } else if (gdbServer.Equals("openocd")) { gdbServerPath = await debuggerProperties.LlilumOpenOcdPath.GetEvaluatedValueAtEndAsync(); gdbServerArgs = await debuggerProperties.LlilumOpenOcdArgs.GetEvaluatedValueAtEndAsync(); } if (!string.IsNullOrWhiteSpace(gdbServerPath)) { // Even though we did it in deploy, do it here just in case we go straight to debug await LlilumHelpers.TryKillPyocdAsync(); await LlilumHelpers.TryKillOpenOcdAsync(); ProcessStartInfo start = new ProcessStartInfo(); start.FileName = gdbServerPath; start.Arguments = gdbServerArgs; start.UseShellExecute = false; start.RedirectStandardOutput = true; Process gdbServerProcess = Process.Start(start); } return new IDebugLaunchSettings[] { settings }; } } } ================================================ FILE: VisualStudio/LlilumProjectType/LlilumApplication/LlilumApplication.ProjectType/LlilumDeployProvider.cs ================================================ using System; using System.ComponentModel.Composition; using System.Diagnostics; using System.IO; using System.Threading; using System.Threading.Tasks; using Microsoft.VisualStudio.ProjectSystem; using Microsoft.VisualStudio.ProjectSystem.Build; using Microsoft.VisualStudio.ProjectSystem.Utilities; namespace LlilumApplication { [Export(typeof(IDeployProvider))] [AppliesTo(MyUnconfiguredProject.UniqueCapability)] internal class LlilumDeployProvider : IDeployProvider { /// /// Provides access to the project's properties. /// [Import] private ProjectProperties Properties { get; set; } [Import] private IThreadHandling ThreadHandling { get; set; } private async Task RunDeployTool(CancellationToken cancellationToken, TextWriter outputPaneWriter, string deployToolPath, string deployToolArgs) { ProcessStartInfo start = new ProcessStartInfo(); start.FileName = deployToolPath; start.Arguments = deployToolArgs; start.UseShellExecute = false; start.RedirectStandardOutput = true; start.RedirectStandardError = true; start.CreateNoWindow = true; using (Process process = Process.Start(start)) using (StreamReader stdOut = process.StandardOutput) using (StreamReader stdErr = process.StandardError) { try { var stdoutTask = Task.Run(() => SendProcessOutputToPaneAsync(outputPaneWriter, stdOut, cancellationToken)); var stderrTask = Task.Run(() => SendProcessOutputToPaneAsync(outputPaneWriter, stdErr, cancellationToken)); await Task.WhenAll(stdoutTask, stderrTask); if (process.ExitCode != 0) throw new ApplicationException($"Flash tool failed with exit code {process.ExitCode}"); } catch (OperationCanceledException) { if (!process.HasExited) { process.CloseMainWindow(); } } } } public async Task DeployAsync( CancellationToken cancellationToken, TextWriter outputPaneWriter ) { // Kill all instances of PyOcd and OpenOcd because they affect the flash-tool and debugger await LlilumHelpers.TryKillPyocdAsync(); await LlilumHelpers.TryKillOpenOcdAsync(); var properties = await Properties.GetLlilumDebuggerPropertiesAsync(); var deployTool = await properties.LlilumDeployTool.GetEvaluatedValueAtEndAsync(); string deployToolPath = string.Empty; string binaryPath = string.Empty; if (string.Compare(deployTool, "pyocdflashtool", StringComparison.OrdinalIgnoreCase) == 0) { // Deploy with pyOCD Flash Tool deployToolPath = await properties.LlilumFlashToolPath.GetEvaluatedValueAtEndAsync(); deployToolPath = Path.GetFullPath(deployToolPath.Trim('"')); if (!File.Exists(deployToolPath)) { var msg = $"Flash programming tool not found: '{deployToolPath}'"; outputPaneWriter.Write(msg); throw new FileNotFoundException(msg); } } else if (string.Compare(deployTool, "stlinkutility", StringComparison.OrdinalIgnoreCase) == 0) { // Deploy with ST-Link Utility deployToolPath = await properties.LlilumSTLinkUtilityPath.GetEvaluatedValueAtEndAsync(); deployToolPath = Path.GetFullPath(deployToolPath.Trim('"')); if (!File.Exists(deployToolPath)) { var msg = $"STLink Utility not found: '{deployToolPath}'"; outputPaneWriter.Write(msg); throw new FileNotFoundException(msg); } } else if(string.Compare(deployTool, "copytodrive", StringComparison.OrdinalIgnoreCase) == 0) { // Deploy by copying to the drive. Do nothing } else { // Deploy with GDB command, or Do Not Deploy return; } binaryPath = await properties.LlilumOutputBin.GetEvaluatedValueAtEndAsync( ); binaryPath = Path.GetFullPath( binaryPath.Trim( '"' ) ); if( !File.Exists( binaryPath ) ) { var msg = $"Flash binary file not found: '{binaryPath}'"; outputPaneWriter.Write( msg ); throw new FileNotFoundException( msg ); } if (string.Compare(deployTool, "pyocdflashtool", StringComparison.OrdinalIgnoreCase) == 0) { // Deploy with pyOCD Flash Tool string flashToolArgs = await properties.LlilumFlashToolArgs.GetEvaluatedValueAtEndAsync(); flashToolArgs = $"{EnsureQuotedPathIfNeeded(binaryPath)} {flashToolArgs}"; await RunDeployTool(cancellationToken, outputPaneWriter, deployToolPath, flashToolArgs); } else if (string.Compare(deployTool, "stlinkutility", StringComparison.OrdinalIgnoreCase) == 0) { // Deploy with ST-Link Utility string stlinkConnectArgs = await properties.LlilumSTLinkUtilityConnectArgs.GetEvaluatedValueAtEndAsync(); string stlinkEraseArgs = await properties.LlilumSTLinkUtilityEraseArgs.GetEvaluatedValueAtEndAsync(); string stlinkProgramArgs = await properties.LlilumSTLinkUtilityProgramArgs.GetEvaluatedValueAtEndAsync(); string stlinkDeployArgs = stlinkConnectArgs + " " + stlinkEraseArgs + " " + stlinkProgramArgs; await RunDeployTool(cancellationToken, outputPaneWriter, deployToolPath, stlinkDeployArgs); } else if (string.Compare(deployTool, "copytodrive", StringComparison.OrdinalIgnoreCase) == 0) { // Copy to the specified drive string drive = await properties.LlilumDriveToCopyTo.GetEvaluatedValueAtEndAsync(); drive = drive.Trim(); if(string.IsNullOrWhiteSpace(drive)) { throw new ArgumentNullException("Drive not specified"); } // Get the properly formatted string for the drive letter DriveInfo driveInfo = new DriveInfo(drive); drive = driveInfo.RootDirectory.FullName; if (!Directory.Exists(drive)) { throw new DriveNotFoundException("The drive specified could not be located"); } string[] binaryPathArr = binaryPath.Split('\\'); string binaryName = binaryPathArr[binaryPathArr.Length - 1]; string destFile = System.IO.Path.Combine(drive, binaryName); // Allow the copy to fail, and throw an exception on its own File.Copy(binaryPath, destFile, true); } } // Crude but effective ensurance of quoted string when a path contains spaces // only runs once on deploy so not particularly perf critical private static string EnsureQuotedPathIfNeeded( string path ) { if( string.IsNullOrEmpty( path ) ) return path; if( path[ 0 ] == '"' && path[ path.Length - 1 ] == '"' ) return path; if( !path.Contains( " " ) ) return path; return $"\"{path}\""; } private async Task SendProcessOutputToPaneAsync( TextWriter outputPaneWriter, StreamReader strm, CancellationToken cancellationToken ) { while( !strm.EndOfStream && !cancellationToken.IsCancellationRequested ) { outputPaneWriter.Write( await strm.ReadLineAsync( ) ); } } public bool IsDeploySupported { get { return true; } } public void Commit() { } public void Rollback() { } } } ================================================ FILE: VisualStudio/LlilumProjectType/LlilumApplication/LlilumApplication.ProjectType/LlilumHelpers.cs ================================================  namespace LlilumApplication { using System.Diagnostics; using System.Threading.Tasks; public static class LlilumHelpers { public static Task TryKillPyocdAsync() { return Task.Run( ( ) => { foreach( var proc in Process.GetProcessesByName( "pyocd_win" ) ) { proc.Kill( ); proc.WaitForExit( ); } } ); } public static Task TryKillOpenOcdAsync() { return Task.Run(() => { foreach (var proc in Process.GetProcessesByName("openocd")) { proc.Kill(); proc.WaitForExit(); } }); } } } ================================================ FILE: VisualStudio/LlilumProjectType/LlilumApplication/LlilumApplication.ProjectType/MITLicense.txt ================================================ The MIT License (MIT) Copyright (c) 2015 Microsoft Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. ================================================ FILE: VisualStudio/LlilumProjectType/LlilumApplication/LlilumApplication.ProjectType/MyConfiguredProject.cs ================================================ /*************************************************************************** Copyright (c) Microsoft Corporation. All rights reserved. This code is licensed under the Visual Studio SDK license terms. THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT. ***************************************************************************/ namespace LlilumApplication { using System; using System.ComponentModel.Composition; using System.Diagnostics.CodeAnalysis; using System.Threading.Tasks; using System.Threading.Tasks.Dataflow; using Microsoft.VisualStudio.ProjectSystem; using Microsoft.VisualStudio.ProjectSystem.Designers; using Microsoft.VisualStudio.ProjectSystem.Utilities; using Microsoft.VisualStudio.Shell; using Microsoft.VisualStudio.Shell.Interop; using Task = System.Threading.Tasks.Task; [Export] [AppliesTo(MyUnconfiguredProject.UniqueCapability)] internal class MyConfiguredProject { [Import, SuppressMessage("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode", Justification = "MEF")] internal ConfiguredProject ConfiguredProject { get; private set; } [Import, SuppressMessage("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode", Justification = "MEF")] internal ProjectProperties Properties { get; private set; } } } ================================================ FILE: VisualStudio/LlilumProjectType/LlilumApplication/LlilumApplication.ProjectType/MyUnconfiguredProject.cs ================================================ /*************************************************************************** Copyright (c) Microsoft Corporation. All rights reserved. This code is licensed under the Visual Studio SDK license terms. THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT. ***************************************************************************/ namespace LlilumApplication { using System; using System.ComponentModel.Composition; using System.Diagnostics.CodeAnalysis; using System.Threading.Tasks; using System.Threading.Tasks.Dataflow; using Microsoft.VisualStudio.ProjectSystem; using Microsoft.VisualStudio.ProjectSystem.Designers; using Microsoft.VisualStudio.ProjectSystem.Utilities; using Microsoft.VisualStudio.Shell; using Microsoft.VisualStudio.Shell.Interop; using Task = System.Threading.Tasks.Task; [Export] [AppliesTo(MyUnconfiguredProject.UniqueCapability)] [ProjectTypeRegistration(VsPackage.ProjectTypeGuid, "Llilum Application", "#2", ProjectExtension, Language, resourcePackageGuid: VsPackage.PackageGuid, PossibleProjectExtensions = ProjectExtension, ProjectTemplatesDir = @"..\..\Templates\Projects\MyCustomProject")] [ProvideProjectItem(VsPackage.ProjectTypeGuid, "My Items", @"..\..\Templates\ProjectItems\MyCustomProject", 500)] internal class MyUnconfiguredProject { /// /// The file extension used by your project type. /// This does not include the leading period. /// internal const string ProjectExtension = "llilumproj"; /// /// A project capability that is present in your project type and none others. /// This is a convenient constant that may be used by your extensions so they /// only apply to instances of your project type. /// /// /// This value should be kept in sync with the capability as actually defined in your .targets. /// internal const string UniqueCapability = "LlilumApplication"; internal const string Language = "LlilumApplication"; [ImportingConstructor] public MyUnconfiguredProject(UnconfiguredProject unconfiguredProject) { this.ProjectHierarchies = new OrderPrecedenceImportCollection(projectCapabilityCheckProvider: unconfiguredProject); } [Import] internal UnconfiguredProject UnconfiguredProject { get; } [Import] internal IActiveConfiguredProjectSubscriptionService SubscriptionService { get; } [Import] internal IThreadHandling ThreadHandling { get; } [Import] internal ActiveConfiguredProject ActiveConfiguredProject { get; } [Import] internal ActiveConfiguredProject MyActiveConfiguredProject { get; } [ImportMany(ExportContractNames.VsTypes.IVsProject, typeof(IVsProject))] internal OrderPrecedenceImportCollection ProjectHierarchies { get; } internal IVsHierarchy ProjectHierarchy { get { return this.ProjectHierarchies.Single().Value; } } } } ================================================ FILE: VisualStudio/LlilumProjectType/LlilumApplication/LlilumApplication.ProjectType/ProjectProperties.cs ================================================ namespace LlilumApplication { using System; using System.Collections.Generic; using System.ComponentModel.Composition; using System.Linq; using System.Text; using System.Threading.Tasks; using Microsoft.VisualStudio.ProjectSystem; using Microsoft.VisualStudio.ProjectSystem.Properties; using Microsoft.VisualStudio.ProjectSystem.Utilities; [Export] [AppliesTo(MyUnconfiguredProject.UniqueCapability)] internal partial class ProjectProperties : StronglyTypedPropertyAccess { /// /// Initializes a new instance of the class. /// [ImportingConstructor] public ProjectProperties(ConfiguredProject configuredProject) : base(configuredProject) { } /// /// Initializes a new instance of the class. /// public ProjectProperties(ConfiguredProject configuredProject, string file, string itemType, string itemName) : base(configuredProject, file, itemType, itemName) { } /// /// Initializes a new instance of the class. /// public ProjectProperties(ConfiguredProject configuredProject, IProjectPropertiesContext projectPropertiesContext) : base(configuredProject, projectPropertiesContext) { } /// /// Initializes a new instance of the class. /// public ProjectProperties(ConfiguredProject configuredProject, UnconfiguredProject unconfiguredProject) : base(configuredProject, unconfiguredProject) { } } } ================================================ FILE: VisualStudio/LlilumProjectType/LlilumApplication/LlilumApplication.ProjectType/Properties/AssemblyInfo.cs ================================================ using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; [assembly: Microsoft.VisualStudio.Shell.ProvideCodeBase(CodeBase = @"$PackageFolder$\LlilumApplication.dll")] // General Information about an assembly is controlled through the following // set of attributes. Change these attribute values to modify the information // associated with an assembly. [assembly: AssemblyTitle("LlilumApplication.ProjectType")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("LlilumApplication.ProjectType")] [assembly: AssemblyCopyright("Copyright © 2015")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible(false)] // The following GUID is for the ID of the typelib if this project is exposed to COM [assembly: Guid("e80f771d-7f9a-45a7-8b48-9db1dbb196e9")] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Build and Revision Numbers // by using the '*' as shown below: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("1.0.0.0")] [assembly: AssemblyFileVersion("1.0.0.0")] ================================================ FILE: VisualStudio/LlilumProjectType/LlilumApplication/LlilumApplication.ProjectType/VSPackage.resx ================================================  text/microsoft-resx 2.0 System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 Llilum Application Llilum Application Project Files (*.llilumproj);*.llilumproj Llilum Application Items ================================================ FILE: VisualStudio/LlilumProjectType/LlilumApplication/LlilumApplication.ProjectType/VsPackage.cs ================================================ /*************************************************************************** Copyright (c) Microsoft Corporation. All rights reserved. This code is licensed under the Visual Studio SDK license terms. THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT. ***************************************************************************/ namespace LlilumApplication { using System; using System.ComponentModel; using System.Runtime.InteropServices; using Microsoft.VisualStudio.Shell; /// /// This class implements the package exposed by this assembly. /// /// /// This package is required if you want to define adds custom commands (ctmenu) /// or localized resources for the strings that appear in the New Project and Open Project dialogs. /// Creating project extensions or project types does not actually require a VSPackage. /// [PackageRegistration(UseManagedResourcesOnly = true)] [Description("A custom project type based on CPS")] [Guid(VsPackage.PackageGuid)] public sealed class VsPackage : Package { /// /// The GUID for this package. /// public const string PackageGuid = "77dca561-ba37-4520-91a2-3adcff025ac2"; /// /// The GUID for this project type. It is unique with the project file extension and /// appears under the VS registry hive's Projects key. /// public const string ProjectTypeGuid = "4e46a113-0369-413e-9b70-97a179ba0b8e"; /// /// The file extension of this project type. No preceding period. /// public const string ProjectExtension = "llilumproj"; /// /// The default namespace this project compiles with, so that manifest /// resource names can be calculated for embedded resources. /// internal const string DefaultNamespace = "LlilumApplication"; } } ================================================ FILE: VisualStudio/LlilumProjectType/LlilumApplication/LlilumApplication.ProjectType/app.config ================================================  ================================================ FILE: VisualStudio/LlilumProjectType/LlilumApplication/LlilumApplication.ProjectType/packages.config ================================================  ================================================ FILE: VisualStudio/LlilumProjectType/LlilumApplication/LlilumApplication.ProjectType/source.extension.vsixmanifest ================================================  Llilum Application VSIX A template for creating a Llilum Application project. https://github.com/NETMF/llilum MITLicense.txt ================================================ FILE: VisualStudio/LlilumProjectType/LlilumApplication.sln ================================================  Microsoft Visual Studio Solution File, Format Version 12.00 # Visual Studio 14 VisualStudioVersion = 14.0.23107.0 MinimumVisualStudioVersion = 10.0.40219.1 Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "LlilumApplication.ProjectType", "LlilumApplication\LlilumApplication.ProjectType\LlilumApplication.ProjectType.csproj", "{74611D01-A97F-438C-B687-448FEEDBE4FB}" EndProject Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "LlilumApplication.ProjectTemplate", "LlilumApplication\LlilumApplication.ProjectTemplate\LlilumApplication.ProjectTemplate.csproj", "{5747D247-5FCC-4151-942C-811603768ABE}" EndProject Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Microsoft.MIEngine.CoreRegisters.ARM", "Microsoft.MIEngine.CoreRegisters.ARM\Microsoft.MIEngine.CoreRegisters.ARM.csproj", "{80F61FFD-C936-4528-BBC3-5DEE0782EBE5}" EndProject Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Microsoft.MIEngine.CoreRegisters.ARMTests", "Microsoft.MIEngine.CoreRegisters.ARMTests\Microsoft.MIEngine.CoreRegisters.ARMTests.csproj", "{C37F80C6-2575-4CF8-999B-A38B1E8087AC}" EndProject Global GlobalSection(SolutionConfigurationPlatforms) = preSolution Debug|Any CPU = Debug|Any CPU Release|Any CPU = Release|Any CPU EndGlobalSection GlobalSection(ProjectConfigurationPlatforms) = postSolution {74611D01-A97F-438C-B687-448FEEDBE4FB}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {74611D01-A97F-438C-B687-448FEEDBE4FB}.Debug|Any CPU.Build.0 = Debug|Any CPU {74611D01-A97F-438C-B687-448FEEDBE4FB}.Release|Any CPU.ActiveCfg = Release|Any CPU {74611D01-A97F-438C-B687-448FEEDBE4FB}.Release|Any CPU.Build.0 = Release|Any CPU {5747D247-5FCC-4151-942C-811603768ABE}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {5747D247-5FCC-4151-942C-811603768ABE}.Debug|Any CPU.Build.0 = Debug|Any CPU {5747D247-5FCC-4151-942C-811603768ABE}.Release|Any CPU.ActiveCfg = Release|Any CPU {5747D247-5FCC-4151-942C-811603768ABE}.Release|Any CPU.Build.0 = Release|Any CPU {80F61FFD-C936-4528-BBC3-5DEE0782EBE5}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {80F61FFD-C936-4528-BBC3-5DEE0782EBE5}.Debug|Any CPU.Build.0 = Debug|Any CPU {80F61FFD-C936-4528-BBC3-5DEE0782EBE5}.Release|Any CPU.ActiveCfg = Release|Any CPU {80F61FFD-C936-4528-BBC3-5DEE0782EBE5}.Release|Any CPU.Build.0 = Release|Any CPU {C37F80C6-2575-4CF8-999B-A38B1E8087AC}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {C37F80C6-2575-4CF8-999B-A38B1E8087AC}.Debug|Any CPU.Build.0 = Debug|Any CPU {C37F80C6-2575-4CF8-999B-A38B1E8087AC}.Release|Any CPU.ActiveCfg = Release|Any CPU {C37F80C6-2575-4CF8-999B-A38B1E8087AC}.Release|Any CPU.Build.0 = Release|Any CPU EndGlobalSection GlobalSection(SolutionProperties) = preSolution HideSolutionNode = FALSE EndGlobalSection EndGlobal ================================================ FILE: VisualStudio/LlilumProjectType/Microsoft.MIEngine.CoreRegisters.ARM/Converters/ExceptionNumberConverter.cs ================================================ using System; using System.Collections.Generic; using System.Globalization; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Data; namespace Microsoft.MIEngine.CoreRegisters.ARM { public class ExceptionNumberConverter : IValueConverter { public object Convert( object value, Type targetType, object parameter, CultureInfo culture ) { if( targetType != typeof( string ) ) return null; var exceptionNum = ( int )value; switch( exceptionNum ) { case 0: return ""; case 1: return "Reset"; case 2: return "NMI"; case 3: return "HardFault"; case 4: return "MemManage"; case 5: return "BusFault"; case 6: return "UsageFault"; case 7: return "Reserved7"; case 8: return "Reserved8"; case 9: return "Reserved9"; case 10: return "Reserved10"; case 11: return "SvcCall"; case 12: return "DebugMonitor"; case 13: return "Reserved13"; case 14: return "PendSV"; case 15: return "SysTick"; default: // TODO: make this extensible so that the UI can show actual SOC interrupt source names return $"ExternalInt{exceptionNum - 16}"; } } public object ConvertBack( object value, Type targetType, object parameter, CultureInfo culture ) { throw new NotSupportedException( ); } } } ================================================ FILE: VisualStudio/LlilumProjectType/Microsoft.MIEngine.CoreRegisters.ARM/Converters/IntAsBinaryStringConverter.cs ================================================ using System; using System.Collections.Generic; using System.Globalization; using System.Text; using System.Windows.Data; namespace Microsoft.MIEngine.CoreRegisters.ARM { /// Value converter to convert an integer into a string of binary digits in groups of 4 digits separated by spaces public class IntAsBinaryStringConverter : IValueConverter { public object Convert( object value, Type targetType, object parameter, CultureInfo culture ) { var bldr = new StringBuilder(32 + 7);// 32 digits plus 7 spaces foreach( var c in GetBitChars( ( uint )value ) ) bldr.Append( c ); return bldr.ToString( ); } // xxxx_xxxx_xxxx_xxxx_xxxx_xxxx_xxxx_xxxx private IEnumerable GetBitChars( uint value ) { var binString = System.Convert.ToString( value, 2 ); int bitIndex = 0; for( var index = binString.Length - 32; index < binString.Length; ++index, ++bitIndex ) { if( InsertDelimiter( bitIndex ) ) yield return ' '; yield return index < 0 ? '0' : binString[ index ]; } } private static bool InsertDelimiter( int bitIndex ) { return bitIndex != 0 && ( bitIndex % 4 == 0 ) && bitIndex <= 32; } public object ConvertBack( object value, Type targetType, object parameter, CultureInfo culture ) { throw new NotSupportedException( ); } } } ================================================ FILE: VisualStudio/LlilumProjectType/Microsoft.MIEngine.CoreRegisters.ARM/Converters/IsNullValueConverter.cs ================================================ using System; using System.Collections.Generic; using System.Globalization; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Data; namespace Microsoft.MIEngine.CoreRegisters.ARM { public class IsNullConverter : IValueConverter { public object Convert( object value, Type targetType, object parameter, CultureInfo culture ) { return ( value == null ); } public object ConvertBack( object value, Type targetType, object parameter, CultureInfo culture ) { throw new NotSupportedException( ); } } } ================================================ FILE: VisualStudio/LlilumProjectType/Microsoft.MIEngine.CoreRegisters.ARM/CoreRegistersWindow.cs ================================================ // The MIT License( MIT) // // Copyright( c) 2015 Microsoft // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The 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. using Microsoft.VisualStudio.Shell; using Microsoft.VisualStudio.Shell.Interop; using System; using System.Diagnostics; using System.Diagnostics.CodeAnalysis; using System.Runtime.InteropServices; namespace Microsoft.MIEngine.CoreRegisters.ARM { /// /// This class implements the tool window exposed by this package and hosts a user control. /// /// /// In Visual Studio tool windows are composed of a frame (implemented by the shell) and a pane, /// usually implemented by the package implementer. /// /// This class derives from the ToolWindowPane class provided from the MPF in order to use its /// implementation of the IVsUIElementPane interface. /// /// [Guid( "43a63d28-8723-4b55-9671-93597c2e78e5" )] public class CoreRegistersWindow : ToolWindowPane { /// /// Initializes a new instance of the class. /// [SuppressMessage( "Warning", "VSSDK002", Justification = "Asserted via ThreadHelper.ThrowIfNotOnUIThread( )" )] public CoreRegistersWindow( IServiceProvider svcProvider ) : base( svcProvider ) { Caption = "CoreRegistersWindow"; ThreadHelper.ThrowIfNotOnUIThread( ); var debugger = ( IVsDebugger )GetService( typeof( SVsShellDebugger ) ); Debug.Assert( debugger != null ); // This is the user control hosted by the tool window; Note that, even if this class implements IDisposable, // we are not calling Dispose on this object. This is because ToolWindowPane calls Dispose on // the object returned by the Content property. Setting it on a private field and overriding the // Content property avoids the problem of calling a virtual in the constructor. ContentControl = new CoreRegistersWindowControl( new CoreRegistersViewModel( debugger ) ); } public override object Content { get { if( base.Content == null ) base.Content = ContentControl; return base.Content; } set { base.Content = value; } } private readonly CoreRegistersWindowControl ContentControl; } } ================================================ FILE: VisualStudio/LlilumProjectType/Microsoft.MIEngine.CoreRegisters.ARM/CoreRegistersWindowCommand.cs ================================================ // The MIT License( MIT) // // Copyright( c) 2015 Microsoft // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The 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. using System; using System.ComponentModel.Design; using System.Globalization; using Microsoft.VisualStudio.Shell; using Microsoft.VisualStudio.Shell.Interop; using Microsoft.VisualStudio; using System.Diagnostics.CodeAnalysis; namespace Microsoft.MIEngine.CoreRegisters.ARM { /// /// Command handler /// internal sealed class CoreRegistersWindowCommand { /// /// Command ID. /// public const int CommandId = 0x0100; /// /// Command menu group (command set GUID). /// public static readonly Guid CommandSet = new Guid( "8d5e2453-09b4-41bf-aa8d-7b6e1602a1c7" ); /// /// VS Package that provides this command, not null. /// private readonly Package package; private IVsMonitorSelection SelectionService; private uint DebuggingContextCookie; /// /// Initializes a new instance of the class. /// Adds our command handlers for menu (commands must exist in the command table file) /// /// Owner package, not null. [SuppressMessage( "Warning","VSSDK002", Justification = "Checked via ThreadHelper.ThrowIfNotOnUIThread()")] private CoreRegistersWindowCommand( Package package ) { if( package == null ) { throw new ArgumentNullException( nameof( package ) ); } this.package = package; ThreadHelper.ThrowIfNotOnUIThread( ); SelectionService = ( IVsMonitorSelection )Package.GetGlobalService( typeof( SVsShellMonitorSelection ) ); if( SelectionService == null ) return; OleMenuCommandService commandService = ServiceProvider.GetService( typeof( IMenuCommandService ) ) as OleMenuCommandService; if( commandService == null ) return; var menuCommandID = new CommandID( CommandSet, CommandId ); var menuItem = new OleMenuCommand( ShowToolWindow, menuCommandID ); commandService.AddCommand( menuItem ); menuItem.BeforeQueryStatus += MenuItem_BeforeQueryStatus; Guid tempGuid = VSConstants.UICONTEXT.Debugging_guid; ErrorHandler.ThrowOnFailure( SelectionService.GetCmdUIContextCookie( ref tempGuid, out DebuggingContextCookie ) ); } [SuppressMessage( "Warning", "VSSDK002", Justification = "UI thread callback, always on UI" )] private void MenuItem_BeforeQueryStatus( object sender, EventArgs e ) { var cmd = ( OleMenuCommand )sender; int active = 0; ErrorHandler.ThrowOnFailure( SelectionService.IsCmdUIContextActive( DebuggingContextCookie, out active ) ); cmd.Visible = active != 0; } /// /// Gets the instance of the command. /// public static CoreRegistersWindowCommand Instance { get; private set; } /// /// Gets the service provider from the owner package. /// private IServiceProvider ServiceProvider => package; /// /// Initializes the singleton instance of the command. /// /// Owner package, not null. public static void Initialize( Package package ) { Instance = new CoreRegistersWindowCommand( package ); } /// /// Shows the tool window when the menu item is clicked. /// /// The event sender. /// The event args. [SuppressMessage( "Warning", "VSSDK002", Justification = "UI thread callback, always on UI" )] private void ShowToolWindow( object sender, EventArgs e ) { // Get the instance number 0 of this tool window. This window is single instance so this instance // is actually the only one. // The last flag is set to true so that if the tool window does not exists it will be created. ToolWindowPane window = package.FindToolWindow( typeof( CoreRegistersWindow ), 0, true ); if( ( null == window ) || ( null == window.Frame ) ) { throw new NotSupportedException( "Cannot create tool window" ); } IVsWindowFrame windowFrame = ( IVsWindowFrame )window.Frame; ErrorHandler.ThrowOnFailure( windowFrame.Show( ) ); } } } ================================================ FILE: VisualStudio/LlilumProjectType/Microsoft.MIEngine.CoreRegisters.ARM/CoreRegistersWindowControl.xaml ================================================  ================================================ FILE: VisualStudio/LlilumProjectType/Microsoft.MIEngine.CoreRegisters.ARM/CoreRegistersWindowControl.xaml.cs ================================================ // The MIT License( MIT) // // Copyright( c) 2015 Microsoft // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The 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. using System.ComponentModel; using System.Windows; using System.Windows.Controls; using System.Windows.Data; namespace Microsoft.MIEngine.CoreRegisters.ARM { /// Interaction logic for CoreRegistersWindowControl. public partial class CoreRegistersWindowControl { /// Initializes a new instance of the class. internal CoreRegistersWindowControl( CoreRegistersViewModel context ) { DataContext = context; InitializeComponent( ); ICollectionView view = CollectionViewSource.GetDefaultView( RegistersView.ItemsSource ); view.GroupDescriptions.Add( new PropertyGroupDescription( "Group" ) ); } } public class RegisterDetailsTemplateSelector : DataTemplateSelector { public override DataTemplate SelectTemplate( object item, DependencyObject container ) { var element = container as FrameworkElement; var register = item as CoreRegisterViewModel; if( element == null || register == null ) return null; var templateName = register.Name == "xpsr" ? "XpsrRegisterDetailsViewModelTemplate" : "DefaultRegisterDetailsTemplate"; return element.FindResource( templateName ) as DataTemplate; } } } ================================================ FILE: VisualStudio/LlilumProjectType/Microsoft.MIEngine.CoreRegisters.ARM/MIEngineResultsParsers.cs ================================================ // The MIT License( MIT) // // Copyright( c) 2015 Microsoft // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The 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. using Sprache; using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Microsoft.VisualStudio.Threading; namespace Microsoft.MIEngine.Extensions { /// Represents a parsed registerId and value pair from the MI response public struct RegisterIdValuePair { public RegisterIdValuePair( int id, uint value ) { Id = id; Value = value; } public int Id { get; } public uint Value { get; } } /// Represents a parsed registerId and value pair from the MI response public struct RegisterIdNamePair { public RegisterIdNamePair( int id, string name ) { Id = id; Name = name; } public int Id { get; } public string Name { get; } } /// Represents the result status of a command response public enum ResultStatus { Done, Connected, Error, Exit } /// Base class for parsed engine results public class MIEngineResult { protected MIEngineResult( ResultStatus status ) { Status = status; } /// Status parsed from the response public ResultStatus Status { get; } } /// Result of parsing a '-data-list-register-values x' command public class RegisterValuesResult : MIEngineResult { internal RegisterValuesResult( ResultStatus status, IEnumerable registers ) : base( status ) { // NOTE: ToList() is run here to support Async scenarios by forcing // the list enumeration at the time this result is created instead // of some point later when the Registers property is read on some // other thread. Registers = registers.ToList( ).AsReadOnly( ); } public IReadOnlyList Registers { get; } public static Task ParseAsync( string resultTxt ) => MIEngineResultParsers.ParseRegisterValuesResultAsync( resultTxt ); public static string GetCommand( ) => GetCommand( new int[0] ); public static string GetCommand( IReadOnlyList registers ) { var regArg = string.Join( " ", registers.Select( ( i ) => i.ToString( ) ) ); return $"-data-list-register-values x {regArg}"; } } /// Parses the result of a '-data-list-changed-registers' command public class ChangedRegistersResult : MIEngineResult { internal ChangedRegistersResult( ResultStatus status, IEnumerable registers ) : base( status ) { // NOTE: ToList() is run here to support Async scenarios by forcing // the list enumeration at the time this result is created instead // of some point later when the Registers property is read on some // other thread. Registers = registers.ToList( ).AsReadOnly( ); } public IReadOnlyList Registers { get; } public static Task ParseAsync( string resultTxt ) => MIEngineResultParsers.ParseChangedRegistersResultAsync( resultTxt ); public const string Command = "-data-list-changed-registers"; } /// Parses the result of a '-data-list-register-names' command public class RegisterNamesResult : MIEngineResult { internal RegisterNamesResult( ResultStatus status, IEnumerable names ) : base( status ) { var regNames = from regId in names.Select( ( n, i ) => new RegisterIdNamePair( i, n ) ) where !string.IsNullOrEmpty( regId.Name ) select regId; // NOTE: ToList() is run here to support Async scenarios by forcing // the list enumeration at the time this result is created instead // of some point later when the Names property is read on some // other thread. Names = regNames.ToList( ).AsReadOnly( ); } public IReadOnlyList Names { get; } public static Task ParseAsync( string resultTxt ) => MIEngineResultParsers.ParseRegisterNamesResultAsync( resultTxt ); public const string Command = "-data-list-register-names"; } /// Internal parsers for parsing the textual results from commands sent via MIEngine /// /// The parsers are built using Parser Combinators built from the Sprache parser library (Nuget package - Apache Lic. ) /// The combinators help simplify the task of parsing the string results into a useable form at runtime whithout the /// need of complex Regular Expressions or a full blown ANTLR sylte parser. /// It is important to note that the format of the texual response from the MIEngine isn't the actual /// GDB Machine Interface (MI) form. The MIEngine will parse the actual MI result to present a human readable response, /// which is what these parsers take as input. This is due to the fact that the raw MI form is not exposed outside the /// MIEngine itself but the human readable for is thanks to the Debug.MIDebugExec command. /// public static class MIEngineResultParsers { public static async Task ParseRegisterValuesResultAsync( string resultTxt ) { await TaskScheduler.Default; return RegisterValuesResultParser.Parse( resultTxt ); } public static async Task ParseChangedRegistersResultAsync( string resultTxt ) { await TaskScheduler.Default; return ChangedRegistersResultParser.Parse( resultTxt ); } public static async Task ParseRegisterNamesResultAsync( string resultTxt ) { await TaskScheduler.Default; return RegisterNamesResultParser.Parse( resultTxt ); } #region Primitive Parser Combinators // parses a single hex digit private static readonly Parser HexDigit = Parse.Digit.Or( Parse.Chars( 'a', 'b', 'c', 'd', 'e', 'f', 'A', 'B', 'C', 'D', 'E', 'F' ) ); // parses a register name (doesn't currently allow underscores or dashes but that doesn't appear to be necessary...) private static readonly Parser> RegisterName = Parse.Identifier( Parse.Letter, Parse.LetterOrDigit ) .Optional( ) .Token(); // parses a decimal integer as an int private static readonly Parser DecimalInteger = ( from val in Parse.Digit.AtLeastOnce( ).Text( ).Token( ) select int.Parse( val ) ).Token( ); // parses a '0x' prefixed hexadecimal number as an unsigned 32 bit integer private static readonly Parser HexInteger = ( from prefix in Parse.String( "0x" ) from val in HexDigit.AtLeastOnce( ).Text( ).Token( ) select Convert.ToUInt32( val, 16 ) ).Token(); // parses double quoted text private static readonly Parser QuotedText = ( from open in Parse.Char( '"' ) from content in Parse.CharExcept( '"' ).Many( ).Text( ) from close in Parse.Char( '"' ) select content ).Token( ); // Factory method for building name=value pair parser combinators private static Parser> NameValuePair( string name, Parser valueParser ) { return ( from key in Parse.String( name ).Text( ).Token( ) from eq in Parse.Char( '=' ).Token( ) from value in valueParser select new KeyValuePair( key, value ) ).Token( ); } #endregion #region MIEngine result string parsers // parses an MI register id and value pair private static readonly Parser RegisterValue = from lbrace in Parse.Char( '{' ).Token( ) from num in NameValuePair( "number", DecimalInteger ) from comma in Parse.Char( ',' ).Token( ) from val in NameValuePair( "value", HexInteger ) from rbrace in Parse.Char( '}' ) select new RegisterIdValuePair( num.Value, val.Value ); // parses the MIEngine result line private static readonly Parser ResultClass = from label in Parse.String( "result-class:" ).Token( ) from kind in Parse.String( "done" ).Return( ResultStatus.Done ) .Or( Parse.String( "error" ).Return( ResultStatus.Error ) ) .Or( Parse.String( "exit" ).Return( ResultStatus.Exit ) ) .Or( Parse.String( "connected" ).Return( ResultStatus.Connected ) ) from trailing in Parse.WhiteSpace.Optional( ) from eol in Parse.LineEnd select kind; // parses the result string from a '-data-list-register-values x' command private static readonly Parser RegisterValuesResultParser = ( from kind in ResultClass from label in Parse.String( "register-values:" ).Token( ) from lbracket in Parse.Char( '[' ).Token( ) from registers in RegisterValue.DelimitedBy( Parse.Char( ',' ).Token( ) ) from rbracket in Parse.Char( ']' ).Token( ) select new RegisterValuesResult( kind, registers ) ).End( ); // parses the result string from a '-data-list-changed-registers' command private static readonly Parser ChangedRegistersResultParser = ( from kind in ResultClass from label in Parse.String( "changed-registers:" ).Token( ) from lbracket in Parse.Char( '[' ).Token( ) from registers in DecimalInteger.DelimitedBy( Parse.Char( ',' ).Token( ) ) from rbracket in Parse.Char( ']' ).Token( ) select new ChangedRegistersResult( kind, registers ) ).End( ); // parses the result string from a '-data-list-register-names' command private static readonly Parser RegisterNamesResultParser = ( from kind in ResultClass from label in Parse.String( "register-names:" ).Token( ) from lbracket in Parse.Char( '[' ).Token( ) from registers in RegisterName.DelimitedBy( Parse.Char( ',' ).Token( ) ) from rbracket in Parse.Char( ']' ).Token( ) select new RegisterNamesResult( kind, registers.Select( r=>r.IsEmpty ? string.Empty : r.Get() ) ) ).End( ); #endregion } } ================================================ FILE: VisualStudio/LlilumProjectType/Microsoft.MIEngine.CoreRegisters.ARM/MITLicense.txt ================================================ The MIT License (MIT) Copyright (c) 2015 Microsoft Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. ================================================ FILE: VisualStudio/LlilumProjectType/Microsoft.MIEngine.CoreRegisters.ARM/Microsoft.MIEngine.CoreRegisters.ARM.csproj ================================================  14.0 $(MSBuildExtensionsPath32)\Microsoft\VisualStudio\v$(VisualStudioVersion) true true Key.snk Debug AnyCPU 2.0 {82b43b9b-a64c-4715-b499-d71e9ca2bd60};{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC} {80F61FFD-C936-4528-BBC3-5DEE0782EBE5} Library Properties Microsoft.MIEngine.CoreRegisters.ARM Microsoft.MIEngine.CoreRegisters.ARM v4.5.2 true true true true true false true full false bin\Debug\ DEBUG;TRACE prompt 4 pdbonly true bin\Release\ TRACE prompt 4 CoreRegistersWindowControl.xaml Designer False False False False $(MSBuildProgramFiles32)\Microsoft Visual Studio 14.0\Common7\IDE\CommonExtensions\Microsoft\MDD\Debugger\Microsoft.MIDebugEngine.dll False ..\packages\Microsoft.VisualStudio.Imaging.14.0.23107\lib\net45\Microsoft.VisualStudio.Imaging.dll True ..\packages\Microsoft.VisualStudio.OLE.Interop.7.10.6070\lib\Microsoft.VisualStudio.OLE.Interop.dll True ..\packages\Microsoft.VisualStudio.Shell.14.0.14.0.23107\lib\Microsoft.VisualStudio.Shell.14.0.dll True ..\packages\Microsoft.VisualStudio.Shell.Immutable.10.0.10.0.30319\lib\net40\Microsoft.VisualStudio.Shell.Immutable.10.0.dll True ..\packages\Microsoft.VisualStudio.Shell.Immutable.11.0.11.0.50727\lib\net45\Microsoft.VisualStudio.Shell.Immutable.11.0.dll True ..\packages\Microsoft.VisualStudio.Shell.Immutable.12.0.12.0.21003\lib\net45\Microsoft.VisualStudio.Shell.Immutable.12.0.dll True ..\packages\Microsoft.VisualStudio.Shell.Immutable.14.0.14.0.23107\lib\net45\Microsoft.VisualStudio.Shell.Immutable.14.0.dll True ..\packages\Microsoft.VisualStudio.Shell.Interop.7.10.6071\lib\Microsoft.VisualStudio.Shell.Interop.dll True True ..\packages\Microsoft.VisualStudio.Shell.Interop.10.0.10.0.30319\lib\Microsoft.VisualStudio.Shell.Interop.10.0.dll True True ..\packages\Microsoft.VisualStudio.Shell.Interop.11.0.11.0.61030\lib\Microsoft.VisualStudio.Shell.Interop.11.0.dll True True ..\packages\Microsoft.VisualStudio.Shell.Interop.12.0.12.0.30110\lib\Microsoft.VisualStudio.Shell.Interop.12.0.dll True ..\packages\Microsoft.VisualStudio.Shell.Interop.8.0.8.0.50727\lib\Microsoft.VisualStudio.Shell.Interop.8.0.dll True ..\packages\Microsoft.VisualStudio.Shell.Interop.9.0.9.0.30729\lib\Microsoft.VisualStudio.Shell.Interop.9.0.dll True ..\packages\Microsoft.VisualStudio.TextManager.Interop.7.10.6070\lib\Microsoft.VisualStudio.TextManager.Interop.dll True ..\packages\Microsoft.VisualStudio.TextManager.Interop.8.0.8.0.50727\lib\Microsoft.VisualStudio.TextManager.Interop.8.0.dll True ..\packages\Microsoft.VisualStudio.Threading.14.0.50702\lib\net45\Microsoft.VisualStudio.Threading.dll True ..\packages\Microsoft.VisualStudio.Utilities.14.0.23107\lib\net45\Microsoft.VisualStudio.Utilities.dll True ..\packages\Microsoft.VisualStudio.Validation.14.0.50702\lib\net45\Microsoft.VisualStudio.Validation.dll True ..\packages\Sprache.JetBrains.2.0.0.44\lib\portable-net4+netcore45+win8+wp8+sl5+MonoAndroid1+MonoTouch1\Sprache.dll True False Menus.ctmenu VsPackage.cs true VSPackage MSBuild:Compile Designer This project references NuGet package(s) that are missing on this computer. Use NuGet Package Restore to download them. For more information, see http://go.microsoft.com/fwlink/?LinkID=322105. The missing file is {0}. ================================================ FILE: VisualStudio/LlilumProjectType/Microsoft.MIEngine.CoreRegisters.ARM/Properties/AssemblyInfo.cs ================================================ using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; // General Information about an assembly is controlled through the following // set of attributes. Change these attribute values to modify the information // associated with an assembly. [assembly: AssemblyTitle( "Microsoft.MIEngine.CoreRegisters.ARM" )] [assembly: AssemblyDescription( "" )] [assembly: AssemblyConfiguration( "" )] [assembly: AssemblyCompany( "" )] [assembly: AssemblyProduct( "Microsoft.MIEngine.CoreRegisters.ARM" )] [assembly: AssemblyCopyright( "" )] [assembly: AssemblyTrademark( "" )] [assembly: AssemblyCulture( "" )] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible( false )] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Build and Revision Numbers // by using the '*' as shown below: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion( "1.0.0.0" )] [assembly: AssemblyFileVersion( "1.0.0.0" )] [assembly: InternalsVisibleTo( "Microsoft.MIEngine.CoreRegisters.ARM.Tests, PublicKey=002400000480000094000000060200000024000052534131000400000100010021418abe4dcdc112c52bd042e37e668db02edd6db60b8ed26825578ea37f8d148084323543757f1986c94c852944e2a59ddf7455f7f32d70e41b999c729fab9d0410cecda09ccace57556f5390d0fda83f016b3a151d8101345d75f057af2dc2402c8fcbe94595461502f78983509a68337dc82529f769777c6d6527fb7190cb" )] [assembly: InternalsVisibleTo( "Microsoft.MIEngine.CoreRegisters.ARM.Explorables, PublicKey=002400000480000094000000060200000024000052534131000400000100010021418abe4dcdc112c52bd042e37e668db02edd6db60b8ed26825578ea37f8d148084323543757f1986c94c852944e2a59ddf7455f7f32d70e41b999c729fab9d0410cecda09ccace57556f5390d0fda83f016b3a151d8101345d75f057af2dc2402c8fcbe94595461502f78983509a68337dc82529f769777c6d6527fb7190cb" )] ================================================ FILE: VisualStudio/LlilumProjectType/Microsoft.MIEngine.CoreRegisters.ARM/VSPackage.resx ================================================  text/microsoft-resx 2.0 System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 Microsoft MIEngine extension for viewing ARM(R) Core registers This package privides visibility of Core CPU registers borken down to individual bit fields where appropriate Resources\VsPackage.ico;System.Drawing.Icon, System.Drawing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a ================================================ FILE: VisualStudio/LlilumProjectType/Microsoft.MIEngine.CoreRegisters.ARM/ViewModel/CoreRegisterViewModel.cs ================================================ // The MIT License( MIT) // // Copyright( c) 2015 Microsoft // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The 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. using System; using System.ComponentModel; namespace Microsoft.MIEngine.CoreRegisters.ARM { public class CoreRegisterViewModel : INotifyPropertyChanged { public CoreRegisterViewModel( string name, string group, int id ) : this( name, group, id, null ) { } public CoreRegisterViewModel( string name, string group, int id, Func detailFactory ) { Name = name; Group = group; Id = id; Value = 0; if( detailFactory != null ) Details = detailFactory( this ); } public event PropertyChangedEventHandler PropertyChanged = delegate {}; public string Name { get; } public uint Value { get { return Value_; } internal set { Value_ = value; PropertyChanged( this, ValueChangedEventArgs ); IsChanged = true; } } uint Value_; public object Details { get; } public string Group { get; } public int Id { get; } public bool IsChanged { get { return IsChanged_; } internal set { IsChanged_ = value; PropertyChanged( this, IsChangedEventArgs ); } } private bool IsChanged_; private static readonly PropertyChangedEventArgs IsChangedEventArgs = new PropertyChangedEventArgs( nameof( IsChanged ) ); private static readonly PropertyChangedEventArgs ValueChangedEventArgs = new PropertyChangedEventArgs( nameof( Value ) ); } } ================================================ FILE: VisualStudio/LlilumProjectType/Microsoft.MIEngine.CoreRegisters.ARM/ViewModel/CoreRegistersViewModel.cs ================================================ // The MIT License( MIT) // // Copyright( c) 2015 Microsoft // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The 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. using Microsoft.MIDebugEngine; using Microsoft.MIEngine.Extensions; using Microsoft.VisualStudio; using Microsoft.VisualStudio.Shell; using Microsoft.VisualStudio.Shell.Interop; using System; using System.Collections.Generic; using System.ComponentModel; using System.Diagnostics; using System.Diagnostics.CodeAnalysis; using System.Linq; using System.Threading.Tasks; using Task = System.Threading.Tasks.Task; namespace Microsoft.MIEngine.CoreRegisters.ARM { internal sealed class CoreRegistersViewModel : INotifyPropertyChanged , IVsDebuggerEvents , IDisposable { [SuppressMessage("Warning", "VSSDK002", Justification = "Asserted via ThreadHelper.ThrowIfNotOnUIThread( )")] internal CoreRegistersViewModel( IVsDebugger debugger ) { if( debugger == null ) throw new ArgumentNullException( nameof( debugger ) ); Registers = new List { new CoreRegisterViewModel("R0", "Core", 0) , new CoreRegisterViewModel("R1", "Core", 1) , new CoreRegisterViewModel("R2", "Core", 2) , new CoreRegisterViewModel("R3", "Core", 3) , new CoreRegisterViewModel("R4", "Core", 4) , new CoreRegisterViewModel("R5", "Core", 5) , new CoreRegisterViewModel("R6", "Core", 6) , new CoreRegisterViewModel("R7", "Core", 7) , new CoreRegisterViewModel("R8", "Core", 8) , new CoreRegisterViewModel("R9", "Core", 9) , new CoreRegisterViewModel("R10", "Core", 10) , new CoreRegisterViewModel("R11", "Core", 11) , new CoreRegisterViewModel("R12", "Core", 12) , new CoreRegisterViewModel("R13(SP)", "Core", 13) , new CoreRegisterViewModel("R14(LR)", "Core", 14) , new CoreRegisterViewModel("R15(PC)", "Core", 15) , new CoreRegisterViewModel("xpsr", "Core", 0x19, (r)=>new XpsrRegisterDetailsViewModel(r) ) , new CoreRegisterViewModel("msp", "Banked", 0x5B) , new CoreRegisterViewModel("psp", "Banked", 0x5C) , new CoreRegisterViewModel("primask", "System", 0x5D) , new CoreRegisterViewModel("control", "System", 0x5E) , new CoreRegisterViewModel("basepri", "System", 0x5F) , new CoreRegisterViewModel("faultmask", "System", 0x60) }; RegIdToViewModelMap = Registers.ToDictionary( vm => vm.Id ); ThreadHelper.ThrowIfNotOnUIThread( ); Debugger = debugger; Debugger.AdviseDebuggerEvents( this, out DebuggerEventsSinkCookie ); } public string DebugMode { get; private set; } public event PropertyChangedEventHandler PropertyChanged = delegate {}; public List Registers { get; } public void Dispose( ) { ThreadHelper.ThrowIfNotOnUIThread( ); Debugger.UnadviseDebuggerEvents( DebuggerEventsSinkCookie ); } int IVsDebuggerEvents.OnModeChange( DBGMODE dbgmodeNew ) { // Push actual handler activity to the UI thread, if not already there // Run Async is needed since this is an interface defined method that // isn't async aware. ThreadHelper.JoinableTaskFactory.RunAsync( async ()=> { await ThreadHelper.JoinableTaskFactory.SwitchToMainThreadAsync( ); DebugMode = dbgmodeNew.ToString( ); PropertyChanged( this, DebugModeChangedEventArgs ); if( dbgmodeNew != DBGMODE.DBGMODE_Break ) return; foreach( var knownReg in RegIdToViewModelMap.Values ) knownReg.IsChanged = false; var registers = await GetUpdatedRegistersAsync( ); foreach( var reg in registers ) RegIdToViewModelMap[ reg.Id ].Value = reg.Value; }); return VSConstants.S_OK; } internal async Task< IReadOnlyList > GetUpdatedRegistersAsync( ) { #if DEBUG await VerifyRegisterIds( ); #endif string cmdResult = await MIDebugCommandDispatcher.ExecuteCommand( ChangedRegistersResult.Command ); var regChangedResult = await ChangedRegistersResult.ParseAsync( cmdResult ); // if( regChangedResult.Status != ResultStatus.Done ) // TODO: How should errors be reported? // send a request for the values of the changed registers var cmd = RegisterValuesResult.GetCommand( regChangedResult.Registers ); cmdResult = await MIDebugCommandDispatcher.ExecuteCommand( cmd ); var regValues = await RegisterValuesResult.ParseAsync( cmdResult ); //if( regValues.Status != ResultStatus.Done ) // TODO: How should errors be reported? return regValues.Registers; } private readonly Dictionary RegIdToViewModelMap; private readonly IVsDebugger Debugger; private readonly uint DebuggerEventsSinkCookie; private static readonly PropertyChangedEventArgs DebugModeChangedEventArgs = new PropertyChangedEventArgs( nameof( DebugMode ) ); #if DEBUG // request all register names and ids, validate that all core registers // have a matching view model private async Task VerifyRegisterIds( ) { if( VerifiedRegisterIds ) return; string cmdResult = await MIDebugCommandDispatcher.ExecuteCommand( RegisterNamesResult.Command ); var result = await RegisterNamesResult.ParseAsync( cmdResult ); if( result.Status != ResultStatus.Done ) return; foreach( var regNameId in result.Names ) { Debug.Assert( RegIdToViewModelMap.ContainsKey( regNameId.Id ) ); } VerifiedRegisterIds = true; } bool VerifiedRegisterIds; #endif } } ================================================ FILE: VisualStudio/LlilumProjectType/Microsoft.MIEngine.CoreRegisters.ARM/ViewModel/XpsrRegisterDetailsViewModel.cs ================================================ using System.ComponentModel; namespace Microsoft.MIEngine.CoreRegisters.ARM { public class XpsrRegisterDetailsViewModel : INotifyPropertyChanged { public XpsrRegisterDetailsViewModel( CoreRegisterViewModel vm ) { Register = vm; PropertyChangedEventManager.AddHandler( vm, RegValueChanged, nameof( vm.Value ) ); } public event PropertyChangedEventHandler PropertyChanged = delegate { }; private void RegValueChanged( object sender, PropertyChangedEventArgs e ) { var val = Register.Value; N = ( val & NBitMask ) != 0; Z = ( val & ZBitMask ) != 0; C = ( val & CBitMask ) != 0; V = ( val & VBitMask ) != 0; Q = ( val & QBitMask ) != 0; ExceptionNum = ( int )( val & ExceptionMask ); PropertyChanged( this, AllPropertiesChangedEventArgs ); } public bool N { get; private set; } public bool Z { get; private set; } public bool C { get; private set; } public bool V { get; private set; } public bool Q { get; private set; } public int ExceptionNum { get; private set; } private readonly CoreRegisterViewModel Register; // see ARM-V7M Arch manual (B1.4.2) private const uint NBitMask = 1u << 31; private const uint ZBitMask = 1u << 30; private const uint CBitMask = 1u << 29; private const uint VBitMask = 1u << 28; private const uint QBitMask = 1u << 27; private const uint ExceptionMask = 0x1FF; private static readonly PropertyChangedEventArgs AllPropertiesChangedEventArgs = new PropertyChangedEventArgs( string.Empty ); } } ================================================ FILE: VisualStudio/LlilumProjectType/Microsoft.MIEngine.CoreRegisters.ARM/VsPackage.cs ================================================ // The MIT License( MIT) // // Copyright( c) 2015 Microsoft // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The 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. using Microsoft.VisualStudio.Shell; using System; using System.ComponentModel.Design; using System.Diagnostics.CodeAnalysis; using System.Runtime.InteropServices; namespace Microsoft.MIEngine.CoreRegisters.ARM { /// /// This is the class that implements the package exposed by this assembly. /// /// /// /// The minimum requirement for a class to be considered a valid package for Visual Studio /// is to implement the IVsPackage interface and register itself with the shell. /// This package uses the helper classes defined inside the Managed Package Framework (MPF) /// to do it: it derives from the Package class that provides the implementation of the /// IVsPackage interface and uses the registration attributes defined in the framework to /// register itself and its components with the shell. These attributes tell the pkgdef creation /// utility what data to put into .pkgdef file. /// /// /// To get loaded into VS, the package must be referred by <Asset Type="Microsoft.VisualStudio.VsPackage" ...> in .vsixmanifest file. /// /// [PackageRegistration( UseManagedResourcesOnly = true )] [InstalledProductRegistration( "#110", "#112", "1.0", IconResourceID = 400 )] // Info on this package for Help/About [Guid( PackageGuidString )] [ProvideMenuResource("Menus.ctmenu", 1)] [ProvideToolWindow(typeof(CoreRegistersWindow))] [SuppressMessage( "StyleCop.CSharp.DocumentationRules", "SA1650:ElementDocumentationMustBeSpelledCorrectly", Justification = "pkgdef, VS and vsixmanifest are valid VS terms" )] public sealed class VsPackage : Package { /// The GUID for this package. public const string PackageGuidString = "217e9e56-991f-400f-ad67-89ff15e0adee"; /// /// Initializes a new instance of the class. /// public VsPackage( ) { // Inside this method you can place any initialization code that does not require // any Visual Studio service because at this point the package object is created but // not sited yet inside Visual Studio environment. The place to do all the other // initialization is the Initialize method. } /// /// Initialization of the package; this method is called right after the package is sited, so this is the place /// where you can put all the initialization code that rely on services provided by VisualStudio. /// protected override void Initialize( ) { base.Initialize( ); IServiceContainer svcContainer = this; CoreRegistersWindowCommand.Initialize( this ); } // base implementation uses default constructor, need to override to make service provider available // to the tool window being created protected override WindowPane InstantiateToolWindow( Type toolWindowType ) { return ( WindowPane )Activator.CreateInstance( toolWindowType, ( IServiceProvider )this ); } } } ================================================ FILE: VisualStudio/LlilumProjectType/Microsoft.MIEngine.CoreRegisters.ARM/VsPackage.vsct ================================================  ================================================ FILE: VisualStudio/LlilumProjectType/Microsoft.MIEngine.CoreRegisters.ARM/packages.config ================================================  ================================================ FILE: VisualStudio/LlilumProjectType/Microsoft.MIEngine.CoreRegisters.ARM/source.extension.vsixmanifest ================================================  Microsoft.MIEngine.CoreRegisters.ARM Empty VSIX Project. ================================================ FILE: VisualStudio/LlilumProjectType/Microsoft.MIEngine.CoreRegisters.ARMTests/IntAsBinaryStringConverterTests.cs ================================================ using Microsoft.VisualStudio.TestTools.UnitTesting; using System; using System.Globalization; namespace Microsoft.MIEngine.CoreRegisters.ARM.Tests { [TestClass( )] public class IntAsBinaryStringConverterTests { [TestMethod( )] public void ConvertTest( ) { var converter = new IntAsBinaryStringConverter( ); var result = converter.Convert( 0x12345678U, typeof( string ), null, CultureInfo.InvariantCulture ); Assert.IsNotNull( result ); var resultString = result as string; Assert.IsNotNull( resultString ); Assert.AreEqual( "0001 0010 0011 0100 0101 0110 0111 1000", resultString ); } [TestMethod] [ExpectedException( typeof( NotSupportedException ) )] public void ConvertBackTest( ) { var converter = new IntAsBinaryStringConverter( ); converter.ConvertBack( "1111 0000 1111 0000 1111 0000 1111 0000", typeof( uint ), null, CultureInfo.InvariantCulture ); } } } ================================================ FILE: VisualStudio/LlilumProjectType/Microsoft.MIEngine.CoreRegisters.ARMTests/MIEngineResultParsersTests.cs ================================================ using System; using System.Collections.Generic; using Microsoft.VisualStudio.TestTools.UnitTesting; namespace Microsoft.MIEngine.Extensions.Tests { [TestClass] public class MIEngineResultParsersTests { const string ValidRegValueTestInput = "result-class: done\r\n" + "register-values: [{number=0, value=0x10006210},{number=1,value=0x0},{number=2,value=0x40000},{number=3,value=0xf014},{number=4,value=0x3f00f707},{number=5,value=0x1000335c},{number=6,value=0x0},{number=7,value=0x3fe00000},{number=8,value=0x10003330},{number=9,value=0x1},{number=10,value=0x0},{number=11,value=0x10001b9c},{number=12,value=0xf000},{number=13,value=0x10006180},{number=14,value=0x9357},{number=15,value=0x385c},{number=25,value=0x1000000},{number=91,value=0x10007fb0},{number=92,value=0x10006180},{number=93,value=0x0},{number=94,value=0x2},{number=95,value=0xf8},{number=96,value=0x0}]"; const string ValidRegisterNamesTestInput = "result-class: done\r\n" + "register-names: [r0,r1,r2,r3,r4,r5,r6,r7,r8,r9,r10,r11,r12,sp,lr,pc,,,,,,,,,,xpsr,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,msp,psp,primask,control,basepri,faultmask]"; const string ErrorMsgResultTestInput = "result-class: error\r\n" + "msg: -data-list-register-values: Usage: -data-list-register-values [--skip-unavailable] [...]"; const string IncompleteResult = "result-class: done\r\n"; static readonly RegisterIdNamePair[] Registers = { new RegisterIdNamePair( 0 , "r0" ), new RegisterIdNamePair( 1 , "r1"), new RegisterIdNamePair( 2 , "r2"), new RegisterIdNamePair( 3 , "r3"), new RegisterIdNamePair( 4 , "r4"), new RegisterIdNamePair( 5 , "r5"), new RegisterIdNamePair( 6 , "r6"), new RegisterIdNamePair( 7 , "r7"), new RegisterIdNamePair( 8 , "r8"), new RegisterIdNamePair( 9 , "r9"), new RegisterIdNamePair( 10, "r10"), new RegisterIdNamePair( 11, "r11"), new RegisterIdNamePair( 12, "r12"), new RegisterIdNamePair( 13, "sp"), new RegisterIdNamePair( 14, "lr"), new RegisterIdNamePair( 15, "pc"), new RegisterIdNamePair( 25, "xpsr"), new RegisterIdNamePair( 91, "msp"), new RegisterIdNamePair( 92, "psp"), new RegisterIdNamePair( 93, "primask"), new RegisterIdNamePair( 94, "control"), new RegisterIdNamePair( 95, "basepri"), new RegisterIdNamePair( 96, "faultmask") }; [ TestMethod ] public void ParseRegisterValuesResultAsyncTest( ) { var parsedResult = MIEngineResultParsers.ParseRegisterValuesResultAsync( ValidRegValueTestInput ).Result; Assert.IsNotNull( parsedResult ); Assert.AreEqual( ResultStatus.Done, parsedResult.Status ); Assert.AreEqual( 23, parsedResult.Registers.Count ); CheckRegisterValue( parsedResult.Registers[ 0 ], 0, 0x10006210); CheckRegisterValue( parsedResult.Registers[ 1 ], 1, 0x0); CheckRegisterValue( parsedResult.Registers[ 2 ], 2, 0x40000); CheckRegisterValue( parsedResult.Registers[ 3 ], 3, 0xf014); CheckRegisterValue( parsedResult.Registers[ 4 ], 4, 0x3f00f707); CheckRegisterValue( parsedResult.Registers[ 5 ], 5, 0x1000335c); CheckRegisterValue( parsedResult.Registers[ 6 ], 6, 0x0); CheckRegisterValue( parsedResult.Registers[ 7 ], 7, 0x3fe00000); CheckRegisterValue( parsedResult.Registers[ 8 ], 8, 0x10003330); CheckRegisterValue( parsedResult.Registers[ 9 ], 9, 0x1); CheckRegisterValue( parsedResult.Registers[ 10 ], 10, 0x0); CheckRegisterValue( parsedResult.Registers[ 11 ], 11, 0x10001b9c); CheckRegisterValue( parsedResult.Registers[ 12 ], 12, 0xf000); CheckRegisterValue( parsedResult.Registers[ 13 ], 13, 0x10006180); CheckRegisterValue( parsedResult.Registers[ 14 ], 14, 0x9357); CheckRegisterValue( parsedResult.Registers[ 15 ], 15, 0x385c); CheckRegisterValue( parsedResult.Registers[ 16 ], 25, 0x1000000); CheckRegisterValue( parsedResult.Registers[ 17 ], 91, 0x10007fb0); CheckRegisterValue( parsedResult.Registers[ 18 ], 92, 0x10006180); CheckRegisterValue( parsedResult.Registers[ 19 ], 93, 0x0); CheckRegisterValue( parsedResult.Registers[ 20 ], 94, 0x2); CheckRegisterValue( parsedResult.Registers[ 21 ], 95, 0xf8); CheckRegisterValue( parsedResult.Registers[ 22 ], 96, 0x0); } [TestMethod] public void ParseRegisterValuePartialInputTest( ) { bool exceptionOccurred = false; try { var parsedResult = MIEngineResultParsers.ParseRegisterValuesResultAsync( IncompleteResult ).Result; } catch(AggregateException ex) { Assert.IsInstanceOfType( ex.InnerException, typeof( Sprache.ParseException ) ); exceptionOccurred = true; } Assert.IsTrue( exceptionOccurred ); } private static void CheckRegisterValue( RegisterIdValuePair x, int expectedIndex, uint expectedValue ) { Assert.AreEqual( expectedIndex, x.Id ); Assert.AreEqual( expectedValue, x.Value ); } [TestMethod( )] public void ParseChangedRegistersResultAsyncTest( ) { Assert.Inconclusive( ); } [TestMethod( )] public void ParseRegisterNamesResultAsyncTest( ) { var parsedResult = MIEngineResultParsers.ParseRegisterNamesResultAsync( ValidRegisterNamesTestInput ).Result; Assert.IsNotNull( parsedResult ); Assert.AreEqual( ResultStatus.Done, parsedResult.Status ); Assert.AreEqual( Registers.Length, parsedResult.Names.Count ); for( int i = 0; i < Registers.Length; ++i ) { Assert.AreEqual( Registers[ i ].Id, parsedResult.Names[ i ].Id ); Assert.AreEqual( Registers[ i ].Name, parsedResult.Names[ i ].Name ); } } } } ================================================ FILE: VisualStudio/LlilumProjectType/Microsoft.MIEngine.CoreRegisters.ARMTests/Microsoft.MIEngine.CoreRegisters.ARMTests.csproj ================================================  Debug AnyCPU {C37F80C6-2575-4CF8-999B-A38B1E8087AC} Library Properties Microsoft.MIEngine.CoreRegisters.ARMTests Microsoft.MIEngine.CoreRegisters.ARMTests v4.5.2 512 {3AC096D0-A1C2-E12C-1390-A8335801FDAB};{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC} 10.0 $(MSBuildExtensionsPath32)\Microsoft\VisualStudio\v$(VisualStudioVersion) $(ProgramFiles)\Common Files\microsoft shared\VSTT\$(VisualStudioVersion)\UITestExtensionPackages False UnitTest true full false bin\Debug\ DEBUG;TRACE prompt 4 pdbonly true bin\Release\ TRACE prompt 4 ..\packages\Sprache.JetBrains.2.0.0.44\lib\portable-net4+netcore45+win8+wp8+sl5+MonoAndroid1+MonoTouch1\Sprache.dll True {80F61FFD-C936-4528-BBC3-5DEE0782EBE5} Microsoft.MIEngine.CoreRegisters.ARM False False False False ================================================ FILE: VisualStudio/LlilumProjectType/Microsoft.MIEngine.CoreRegisters.ARMTests/Properties/AssemblyInfo.cs ================================================ using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; // General Information about an assembly is controlled through the following // set of attributes. Change these attribute values to modify the information // associated with an assembly. [assembly: AssemblyTitle( "Microsoft.MIEngine.CoreRegisters.ARMTests" )] [assembly: AssemblyDescription( "" )] [assembly: AssemblyConfiguration( "" )] [assembly: AssemblyCompany( "" )] [assembly: AssemblyProduct( "Microsoft.MIEngine.CoreRegisters.ARMTests" )] [assembly: AssemblyCopyright( "Copyright © 2015" )] [assembly: AssemblyTrademark( "" )] [assembly: AssemblyCulture( "" )] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible( false )] // The following GUID is for the ID of the typelib if this project is exposed to COM [assembly: Guid( "c37f80c6-2575-4cf8-999b-a38b1e8087ac" )] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Build and Revision Numbers // by using the '*' as shown below: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion( "1.0.0.0" )] [assembly: AssemblyFileVersion( "1.0.0.0" )] ================================================ FILE: VisualStudio/LlilumProjectType/Microsoft.MIEngine.CoreRegisters.ARMTests/packages.config ================================================  ================================================ FILE: Zelig/BoardConfigurations/BoardConfigurations.sln ================================================  Microsoft Visual Studio Solution File, Format Version 12.00 # Visual Studio 14 VisualStudioVersion = 14.0.23107.0 MinimumVisualStudioVersion = 10.0.40219.1 Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "LPC1768Configuration", "LPC1768\Configuration\LPC1768Configuration.csproj", "{C17E59D0-2D64-4012-8A98-D184D0CF8A49}" EndProject Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "K64FConfiguration", "K64F\Configuration\K64FConfiguration.csproj", "{9863D039-AB21-4710-960E-7303919552C6}" EndProject Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "K64F", "K64F\Board\K64F.csproj", "{1705887B-E636-4FA3-AE40-2D431AF1511C}" EndProject Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "LPC1768", "LPC1768\Board\LPC1768.csproj", "{CEE4D575-4B4B-42B0-B2F1-CC7198CB7306}" EndProject Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "LPC1768", "LPC1768", "{5100FF29-2B10-4D43-822F-DEDE105433FC}" EndProject Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "K64F", "K64F", "{5C328A57-B790-4B02-A36C-4EDA8280BA51}" EndProject Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "STM32L152", "STM32L152", "{582F3F68-6C35-48E6-BC68-139AE9666F64}" EndProject Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "STM32L152", "STM32L152\Board\STM32L152.csproj", "{F0229144-F7C4-4456-8442-5E816C6E8FBC}" EndProject Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "STM32L152Configuration", "STM32L152\Configuration\STM32L152Configuration.csproj", "{F222E0D3-0FFF-41F4-91EE-400C4E4E043D}" EndProject Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "STM32F411", "STM32F411", "{3F416416-1AEE-4F13-B338-917087AF0C54}" EndProject Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "STM32F411", "STM32F411\Board\STM32F411.csproj", "{DD4371DE-85A8-49AA-B939-10E03B7ED3C9}" EndProject Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "STM32F411Configuration", "STM32F411\Configuration\STM32F411Configuration.csproj", "{9B0EDB62-1E62-492D-B807-A8501EEE8400}" EndProject Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "STM32F401", "STM32F401", "{BE299041-AFCA-44FE-8556-EEC89F85005F}" EndProject Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "STM32F401", "STM32F401\Board\STM32F401.csproj", "{6194144A-F8B1-4525-829F-061DF4A5645A}" EndProject Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "STM32F401Configuration", "STM32F401\Configuration\STM32F401Configuration.csproj", "{7F600371-17AB-41F2-96AB-39C8AA2389E1}" EndProject Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "STM32F091", "STM32F091", "{67586B48-76A8-4D65-A3AC-C89D7A8774E8}" EndProject Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "STM32F091", "STM32F091\Board\STM32F091.csproj", "{65E36DF8-5CB8-4582-851E-F5381AE4A1A7}" EndProject Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "STM32F091Configuration", "STM32F091\Configuration\STM32F091Configuration.csproj", "{C183991C-1F27-4665-A884-FD977D2AD359}" EndProject Global GlobalSection(SolutionConfigurationPlatforms) = preSolution Debug|Any CPU = Debug|Any CPU Release|Any CPU = Release|Any CPU EndGlobalSection GlobalSection(ProjectConfigurationPlatforms) = postSolution {C17E59D0-2D64-4012-8A98-D184D0CF8A49}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {C17E59D0-2D64-4012-8A98-D184D0CF8A49}.Debug|Any CPU.Build.0 = Debug|Any CPU {C17E59D0-2D64-4012-8A98-D184D0CF8A49}.Release|Any CPU.ActiveCfg = Release|Any CPU {C17E59D0-2D64-4012-8A98-D184D0CF8A49}.Release|Any CPU.Build.0 = Release|Any CPU {9863D039-AB21-4710-960E-7303919552C6}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {9863D039-AB21-4710-960E-7303919552C6}.Debug|Any CPU.Build.0 = Debug|Any CPU {9863D039-AB21-4710-960E-7303919552C6}.Release|Any CPU.ActiveCfg = Release|Any CPU {9863D039-AB21-4710-960E-7303919552C6}.Release|Any CPU.Build.0 = Release|Any CPU {1705887B-E636-4FA3-AE40-2D431AF1511C}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {1705887B-E636-4FA3-AE40-2D431AF1511C}.Debug|Any CPU.Build.0 = Debug|Any CPU {1705887B-E636-4FA3-AE40-2D431AF1511C}.Release|Any CPU.ActiveCfg = Release|Any CPU {1705887B-E636-4FA3-AE40-2D431AF1511C}.Release|Any CPU.Build.0 = Release|Any CPU {CEE4D575-4B4B-42B0-B2F1-CC7198CB7306}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {CEE4D575-4B4B-42B0-B2F1-CC7198CB7306}.Debug|Any CPU.Build.0 = Debug|Any CPU {CEE4D575-4B4B-42B0-B2F1-CC7198CB7306}.Release|Any CPU.ActiveCfg = Release|Any CPU {CEE4D575-4B4B-42B0-B2F1-CC7198CB7306}.Release|Any CPU.Build.0 = Release|Any CPU {F0229144-F7C4-4456-8442-5E816C6E8FBC}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {F0229144-F7C4-4456-8442-5E816C6E8FBC}.Debug|Any CPU.Build.0 = Debug|Any CPU {F0229144-F7C4-4456-8442-5E816C6E8FBC}.Release|Any CPU.ActiveCfg = Release|Any CPU {F0229144-F7C4-4456-8442-5E816C6E8FBC}.Release|Any CPU.Build.0 = Release|Any CPU {F222E0D3-0FFF-41F4-91EE-400C4E4E043D}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {F222E0D3-0FFF-41F4-91EE-400C4E4E043D}.Debug|Any CPU.Build.0 = Debug|Any CPU {F222E0D3-0FFF-41F4-91EE-400C4E4E043D}.Release|Any CPU.ActiveCfg = Release|Any CPU {F222E0D3-0FFF-41F4-91EE-400C4E4E043D}.Release|Any CPU.Build.0 = Release|Any CPU {DD4371DE-85A8-49AA-B939-10E03B7ED3C9}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {DD4371DE-85A8-49AA-B939-10E03B7ED3C9}.Debug|Any CPU.Build.0 = Debug|Any CPU {DD4371DE-85A8-49AA-B939-10E03B7ED3C9}.Release|Any CPU.ActiveCfg = Release|Any CPU {DD4371DE-85A8-49AA-B939-10E03B7ED3C9}.Release|Any CPU.Build.0 = Release|Any CPU {9B0EDB62-1E62-492D-B807-A8501EEE8400}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {9B0EDB62-1E62-492D-B807-A8501EEE8400}.Debug|Any CPU.Build.0 = Debug|Any CPU {9B0EDB62-1E62-492D-B807-A8501EEE8400}.Release|Any CPU.ActiveCfg = Release|Any CPU {9B0EDB62-1E62-492D-B807-A8501EEE8400}.Release|Any CPU.Build.0 = Release|Any CPU {6194144A-F8B1-4525-829F-061DF4A5645A}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {6194144A-F8B1-4525-829F-061DF4A5645A}.Debug|Any CPU.Build.0 = Debug|Any CPU {6194144A-F8B1-4525-829F-061DF4A5645A}.Release|Any CPU.ActiveCfg = Release|Any CPU {6194144A-F8B1-4525-829F-061DF4A5645A}.Release|Any CPU.Build.0 = Release|Any CPU {7F600371-17AB-41F2-96AB-39C8AA2389E1}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {7F600371-17AB-41F2-96AB-39C8AA2389E1}.Debug|Any CPU.Build.0 = Debug|Any CPU {7F600371-17AB-41F2-96AB-39C8AA2389E1}.Release|Any CPU.ActiveCfg = Release|Any CPU {7F600371-17AB-41F2-96AB-39C8AA2389E1}.Release|Any CPU.Build.0 = Release|Any CPU {65E36DF8-5CB8-4582-851E-F5381AE4A1A7}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {65E36DF8-5CB8-4582-851E-F5381AE4A1A7}.Debug|Any CPU.Build.0 = Debug|Any CPU {65E36DF8-5CB8-4582-851E-F5381AE4A1A7}.Release|Any CPU.ActiveCfg = Release|Any CPU {65E36DF8-5CB8-4582-851E-F5381AE4A1A7}.Release|Any CPU.Build.0 = Release|Any CPU {C183991C-1F27-4665-A884-FD977D2AD359}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {C183991C-1F27-4665-A884-FD977D2AD359}.Debug|Any CPU.Build.0 = Debug|Any CPU {C183991C-1F27-4665-A884-FD977D2AD359}.Release|Any CPU.ActiveCfg = Release|Any CPU {C183991C-1F27-4665-A884-FD977D2AD359}.Release|Any CPU.Build.0 = Release|Any CPU EndGlobalSection GlobalSection(SolutionProperties) = preSolution HideSolutionNode = FALSE EndGlobalSection GlobalSection(NestedProjects) = preSolution {C17E59D0-2D64-4012-8A98-D184D0CF8A49} = {5100FF29-2B10-4D43-822F-DEDE105433FC} {9863D039-AB21-4710-960E-7303919552C6} = {5C328A57-B790-4B02-A36C-4EDA8280BA51} {1705887B-E636-4FA3-AE40-2D431AF1511C} = {5C328A57-B790-4B02-A36C-4EDA8280BA51} {CEE4D575-4B4B-42B0-B2F1-CC7198CB7306} = {5100FF29-2B10-4D43-822F-DEDE105433FC} {F0229144-F7C4-4456-8442-5E816C6E8FBC} = {582F3F68-6C35-48E6-BC68-139AE9666F64} {F222E0D3-0FFF-41F4-91EE-400C4E4E043D} = {582F3F68-6C35-48E6-BC68-139AE9666F64} {DD4371DE-85A8-49AA-B939-10E03B7ED3C9} = {3F416416-1AEE-4F13-B338-917087AF0C54} {9B0EDB62-1E62-492D-B807-A8501EEE8400} = {3F416416-1AEE-4F13-B338-917087AF0C54} {6194144A-F8B1-4525-829F-061DF4A5645A} = {BE299041-AFCA-44FE-8556-EEC89F85005F} {7F600371-17AB-41F2-96AB-39C8AA2389E1} = {BE299041-AFCA-44FE-8556-EEC89F85005F} {65E36DF8-5CB8-4582-851E-F5381AE4A1A7} = {67586B48-76A8-4D65-A3AC-C89D7A8774E8} {C183991C-1F27-4665-A884-FD977D2AD359} = {67586B48-76A8-4D65-A3AC-C89D7A8774E8} EndGlobalSection EndGlobal ================================================ FILE: Zelig/BoardConfigurations/K64F/Board/HardwareModel/Board.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // namespace Microsoft.Llilum.K64F { using System; using Chipset = Microsoft.CortexM4OnMBED; using ChipsetAbstration = Microsoft.DeviceModels.Chipset.CortexM4; public sealed class Board : Chipset.Board { internal const int GPIO_PORT_SHIFT = 12; // // Serial Ports // private static readonly string[] m_serialPorts = { "UART0", "UART1", "UART3" }; public static readonly ChipsetAbstration.Board.SerialPortInfo UART0 = new ChipsetAbstration.Board.SerialPortInfo() { TxPin = (int)PinName.PTC14, RxPin = (int)PinName.PTC15, RtsPin = unchecked( (int)PinName.NC ), CtsPin = unchecked( (int)PinName.NC ), }; public static readonly ChipsetAbstration.Board.SerialPortInfo UART1 = new ChipsetAbstration.Board.SerialPortInfo() { TxPin = (int)PinName.USBTX, RxPin = (int)PinName.USBRX, RtsPin = unchecked( (int)PinName.NC ), CtsPin = unchecked( (int)PinName.NC ), }; public static readonly ChipsetAbstration.Board.SerialPortInfo UART3 = new ChipsetAbstration.Board.SerialPortInfo() { TxPin = (int)PinName.PTC17, RxPin = (int)PinName.PTC16, RtsPin = unchecked( (int)PinName.NC ), CtsPin = unchecked( (int)PinName.NC ), }; //--// private static readonly int[] s_ledPins = new int[] { (int)K64F.PinName.LED1, (int)K64F.PinName.LED2, (int)K64F.PinName.LED3, (int)K64F.PinName.LED4, }; private static readonly int[] s_pwmPins = new int[] { (int)K64F.PinName.D3, }; // // Gpio discovery // public override int PinCount { get { return 160; } } public override int PinToIndex( int pin ) { int port = pin >> Board.GPIO_PORT_SHIFT; int portIndex = pin & 0x000000FF; return ( port * 32 ) + portIndex; } public override int NCPin { get { return -1; } } public override int[] LedPins { get { return s_ledPins; } } public override int[] PwmPins { get { return s_pwmPins; } } // // Serial Port // public override string[] GetSerialPorts() { return m_serialPorts; } public override ChipsetAbstration.Board.SerialPortInfo GetSerialPortInfo(string portName) { switch (portName) { case "UART0": return UART0; case "UART1": return UART1; case "UART3": return UART3; default: return null; } } // // System timer // public override int GetSystemTimerIRQ( ) { return (int)IRQn.PIT3_IRQn; } public override int GetSerialPortIRQ(string portName) { switch (portName) { case "UART0": return (int)IRQn.UART0_RX_TX_IRQn; case "UART1": return (int)IRQn.UART1_RX_TX_IRQn; case "UART3": return (int)IRQn.UART3_RX_TX_IRQn; default: throw new NotSupportedException(); } } //////public override void RemapSerialPortInterrupts( ) //////{ ////// Processor.RemapInterrupt( IRQn.UART0_ERR_IRQn ); ////// Processor.RemapInterrupt( IRQn.UART0_ERR_IRQn ); ////// Processor.RemapInterrupt( IRQn.UART1_ERR_IRQn ); ////// Processor.RemapInterrupt( IRQn.UART1_ERR_IRQn ); ////// Processor.RemapInterrupt( IRQn.UART3_ERR_IRQn ); ////// Processor.RemapInterrupt( IRQn.UART3_ERR_IRQn ); //////} } } ================================================ FILE: Zelig/BoardConfigurations/K64F/Board/HardwareModel/Device.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // namespace Microsoft.Llilum.K64F { using RT = Microsoft.Zelig.Runtime; public sealed class Device : Microsoft.CortexM4OnMBED.Device { [RT.MemoryUsage(RT.MemoryUsage.Stack, ContentsUninitialized = true, AllocateFromHighAddress = true)] static readonly uint[] s_bootstrapStackK64F = new uint[ 1024 / sizeof( uint ) ]; // // Access Methods // public override uint[] BootstrapStack { get { return s_bootstrapStackK64F; } } } } ================================================ FILE: Zelig/BoardConfigurations/K64F/Board/HardwareModel/Drivers/ContextSwitchTimer.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // //#define TIMERS_SELF_TEST namespace Microsoft.Llilum.K64F.Drivers { using System.Runtime.CompilerServices; using RT = Microsoft.Zelig.Runtime; using Chipset = Microsoft.DeviceModels.Chipset.CortexM3.Drivers; public sealed class ContextSwitchTimer : Chipset.ContextSwitchTimer { protected override uint GetTicksForQuantumValue( uint ms ) { // K64F uses the Core clock (120Mhz) for SysTick return (uint)( RT.Configuration.CoreClockFrequency / 1000 ) * ms; } } } ================================================ FILE: Zelig/BoardConfigurations/K64F/Board/HardwareModel/Drivers/InterruptController.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // namespace Microsoft.Llilum.K64F.Drivers { using Chipset = Microsoft.CortexM4OnMBED.Drivers; public sealed class InterruptController : Chipset.InterruptController { } } ================================================ FILE: Zelig/BoardConfigurations/K64F/Board/HardwareModel/Drivers/SystemTimer.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // namespace Microsoft.Llilum.K64F.Drivers { using Chipset = Microsoft.CortexM4OnMBED.Drivers; public sealed class SystemTimer : Chipset.SystemTimer { } } ================================================ FILE: Zelig/BoardConfigurations/K64F/Board/HardwareModel/GPIO.cs ================================================ // // Copyright ((c) Microsoft Corporation. All rights reserved. // namespace Microsoft.Llilum.K64F { //--// public enum PinName : uint { // Commented out pins do not appear to be used on the board PTA0 = ((0 << Board.GPIO_PORT_SHIFT) | 0 ), PTA1 = ((0 << Board.GPIO_PORT_SHIFT) | 1 ), PTA2 = ((0 << Board.GPIO_PORT_SHIFT) | 2 ), PTA3 = ((0 << Board.GPIO_PORT_SHIFT) | 3 ), PTA4 = ((0 << Board.GPIO_PORT_SHIFT) | 4 ), PTA5 = ((0 << Board.GPIO_PORT_SHIFT) | 5 ), PTA6 = ((0 << Board.GPIO_PORT_SHIFT) | 6 ), PTA7 = ((0 << Board.GPIO_PORT_SHIFT) | 7 ), PTA8 = ((0 << Board.GPIO_PORT_SHIFT) | 8 ), PTA9 = ((0 << Board.GPIO_PORT_SHIFT) | 9 ), PTA10 = ((0 << Board.GPIO_PORT_SHIFT) | 10), PTA11 = ((0 << Board.GPIO_PORT_SHIFT) | 11), PTA12 = ((0 << Board.GPIO_PORT_SHIFT) | 12), PTA13 = ((0 << Board.GPIO_PORT_SHIFT) | 13), PTA14 = ((0 << Board.GPIO_PORT_SHIFT) | 14), PTA15 = ((0 << Board.GPIO_PORT_SHIFT) | 15), PTA16 = ((0 << Board.GPIO_PORT_SHIFT) | 16), PTA17 = ((0 << Board.GPIO_PORT_SHIFT) | 17), PTA18 = ((0 << Board.GPIO_PORT_SHIFT) | 18), PTA19 = ((0 << Board.GPIO_PORT_SHIFT) | 19), PTA20 = ((0 << Board.GPIO_PORT_SHIFT) | 20), PTA21 = ((0 << Board.GPIO_PORT_SHIFT) | 21), PTA22 = ((0 << Board.GPIO_PORT_SHIFT) | 22), PTA23 = ((0 << Board.GPIO_PORT_SHIFT) | 23), PTA24 = ((0 << Board.GPIO_PORT_SHIFT) | 24), PTA25 = ((0 << Board.GPIO_PORT_SHIFT) | 25), PTA26 = ((0 << Board.GPIO_PORT_SHIFT) | 26), PTA27 = ((0 << Board.GPIO_PORT_SHIFT) | 27), PTA28 = ((0 << Board.GPIO_PORT_SHIFT) | 28), PTA29 = ((0 << Board.GPIO_PORT_SHIFT) | 29), PTA30 = ((0 << Board.GPIO_PORT_SHIFT) | 30), PTA31 = ((0 << Board.GPIO_PORT_SHIFT) | 31), PTB0 = ((1 << Board.GPIO_PORT_SHIFT) | 0 ), PTB1 = ((1 << Board.GPIO_PORT_SHIFT) | 1 ), PTB2 = ((1 << Board.GPIO_PORT_SHIFT) | 2 ), PTB3 = ((1 << Board.GPIO_PORT_SHIFT) | 3 ), PTB4 = ((1 << Board.GPIO_PORT_SHIFT) | 4 ), PTB5 = ((1 << Board.GPIO_PORT_SHIFT) | 5 ), PTB6 = ((1 << Board.GPIO_PORT_SHIFT) | 6 ), PTB7 = ((1 << Board.GPIO_PORT_SHIFT) | 7 ), PTB8 = ((1 << Board.GPIO_PORT_SHIFT) | 8 ), PTB9 = ((1 << Board.GPIO_PORT_SHIFT) | 9 ), PTB10 = ((1 << Board.GPIO_PORT_SHIFT) | 10), PTB11 = ((1 << Board.GPIO_PORT_SHIFT) | 11), PTB12 = ((1 << Board.GPIO_PORT_SHIFT) | 12), PTB13 = ((1 << Board.GPIO_PORT_SHIFT) | 13), PTB14 = ((1 << Board.GPIO_PORT_SHIFT) | 14), PTB15 = ((1 << Board.GPIO_PORT_SHIFT) | 15), PTB16 = ((1 << Board.GPIO_PORT_SHIFT) | 16), PTB17 = ((1 << Board.GPIO_PORT_SHIFT) | 17), PTB18 = ((1 << Board.GPIO_PORT_SHIFT) | 18), PTB19 = ((1 << Board.GPIO_PORT_SHIFT) | 19), PTB20 = ((1 << Board.GPIO_PORT_SHIFT) | 20), PTB21 = ((1 << Board.GPIO_PORT_SHIFT) | 21), PTB22 = ((1 << Board.GPIO_PORT_SHIFT) | 22), PTB23 = ((1 << Board.GPIO_PORT_SHIFT) | 23), PTB24 = ((1 << Board.GPIO_PORT_SHIFT) | 24), PTB25 = ((1 << Board.GPIO_PORT_SHIFT) | 25), PTB26 = ((1 << Board.GPIO_PORT_SHIFT) | 26), PTB27 = ((1 << Board.GPIO_PORT_SHIFT) | 27), PTB28 = ((1 << Board.GPIO_PORT_SHIFT) | 28), PTB29 = ((1 << Board.GPIO_PORT_SHIFT) | 29), PTB30 = ((1 << Board.GPIO_PORT_SHIFT) | 30), PTB31 = ((1 << Board.GPIO_PORT_SHIFT) | 31), PTC0 = ((2 << Board.GPIO_PORT_SHIFT) | 0 ), PTC1 = ((2 << Board.GPIO_PORT_SHIFT) | 1 ), PTC2 = ((2 << Board.GPIO_PORT_SHIFT) | 2 ), PTC3 = ((2 << Board.GPIO_PORT_SHIFT) | 3 ), PTC4 = ((2 << Board.GPIO_PORT_SHIFT) | 4 ), PTC5 = ((2 << Board.GPIO_PORT_SHIFT) | 5 ), PTC6 = ((2 << Board.GPIO_PORT_SHIFT) | 6 ), PTC7 = ((2 << Board.GPIO_PORT_SHIFT) | 7 ), PTC8 = ((2 << Board.GPIO_PORT_SHIFT) | 8 ), PTC9 = ((2 << Board.GPIO_PORT_SHIFT) | 9 ), PTC10 = ((2 << Board.GPIO_PORT_SHIFT) | 10), PTC11 = ((2 << Board.GPIO_PORT_SHIFT) | 11), PTC12 = ((2 << Board.GPIO_PORT_SHIFT) | 12), PTC13 = ((2 << Board.GPIO_PORT_SHIFT) | 13), PTC14 = ((2 << Board.GPIO_PORT_SHIFT) | 14), PTC15 = ((2 << Board.GPIO_PORT_SHIFT) | 15), PTC16 = ((2 << Board.GPIO_PORT_SHIFT) | 16), PTC17 = ((2 << Board.GPIO_PORT_SHIFT) | 17), PTC18 = ((2 << Board.GPIO_PORT_SHIFT) | 18), PTC19 = ((2 << Board.GPIO_PORT_SHIFT) | 19), PTC20 = ((2 << Board.GPIO_PORT_SHIFT) | 20), PTC21 = ((2 << Board.GPIO_PORT_SHIFT) | 21), PTC22 = ((2 << Board.GPIO_PORT_SHIFT) | 22), PTC23 = ((2 << Board.GPIO_PORT_SHIFT) | 23), PTC24 = ((2 << Board.GPIO_PORT_SHIFT) | 24), PTC25 = ((2 << Board.GPIO_PORT_SHIFT) | 25), PTC26 = ((2 << Board.GPIO_PORT_SHIFT) | 26), PTC27 = ((2 << Board.GPIO_PORT_SHIFT) | 27), PTC28 = ((2 << Board.GPIO_PORT_SHIFT) | 28), PTC29 = ((2 << Board.GPIO_PORT_SHIFT) | 29), PTC30 = ((2 << Board.GPIO_PORT_SHIFT) | 30), PTC31 = ((2 << Board.GPIO_PORT_SHIFT) | 31), PTD0 = ((3 << Board.GPIO_PORT_SHIFT) | 0 ), PTD1 = ((3 << Board.GPIO_PORT_SHIFT) | 1 ), PTD2 = ((3 << Board.GPIO_PORT_SHIFT) | 2 ), PTD3 = ((3 << Board.GPIO_PORT_SHIFT) | 3 ), PTD4 = ((3 << Board.GPIO_PORT_SHIFT) | 4 ), PTD5 = ((3 << Board.GPIO_PORT_SHIFT) | 5 ), PTD6 = ((3 << Board.GPIO_PORT_SHIFT) | 6 ), PTD7 = ((3 << Board.GPIO_PORT_SHIFT) | 7 ), PTD8 = ((3 << Board.GPIO_PORT_SHIFT) | 8 ), PTD9 = ((3 << Board.GPIO_PORT_SHIFT) | 9 ), PTD10 = ((3 << Board.GPIO_PORT_SHIFT) | 10), PTD11 = ((3 << Board.GPIO_PORT_SHIFT) | 11), PTD12 = ((3 << Board.GPIO_PORT_SHIFT) | 12), PTD13 = ((3 << Board.GPIO_PORT_SHIFT) | 13), PTD14 = ((3 << Board.GPIO_PORT_SHIFT) | 14), PTD15 = ((3 << Board.GPIO_PORT_SHIFT) | 15), PTD16 = ((3 << Board.GPIO_PORT_SHIFT) | 16), PTD17 = ((3 << Board.GPIO_PORT_SHIFT) | 17), PTD18 = ((3 << Board.GPIO_PORT_SHIFT) | 18), PTD19 = ((3 << Board.GPIO_PORT_SHIFT) | 19), PTD20 = ((3 << Board.GPIO_PORT_SHIFT) | 20), PTD21 = ((3 << Board.GPIO_PORT_SHIFT) | 21), PTD22 = ((3 << Board.GPIO_PORT_SHIFT) | 22), PTD23 = ((3 << Board.GPIO_PORT_SHIFT) | 23), PTD24 = ((3 << Board.GPIO_PORT_SHIFT) | 24), PTD25 = ((3 << Board.GPIO_PORT_SHIFT) | 25), PTD26 = ((3 << Board.GPIO_PORT_SHIFT) | 26), PTD27 = ((3 << Board.GPIO_PORT_SHIFT) | 27), PTD28 = ((3 << Board.GPIO_PORT_SHIFT) | 28), PTD29 = ((3 << Board.GPIO_PORT_SHIFT) | 29), PTD30 = ((3 << Board.GPIO_PORT_SHIFT) | 30), PTD31 = ((3 << Board.GPIO_PORT_SHIFT) | 31), PTE0 = ((4 << Board.GPIO_PORT_SHIFT) | 0 ), PTE1 = ((4 << Board.GPIO_PORT_SHIFT) | 1 ), PTE2 = ((4 << Board.GPIO_PORT_SHIFT) | 2 ), PTE3 = ((4 << Board.GPIO_PORT_SHIFT) | 3 ), PTE4 = ((4 << Board.GPIO_PORT_SHIFT) | 4 ), PTE5 = ((4 << Board.GPIO_PORT_SHIFT) | 5 ), PTE6 = ((4 << Board.GPIO_PORT_SHIFT) | 6 ), PTE7 = ((4 << Board.GPIO_PORT_SHIFT) | 7 ), PTE8 = ((4 << Board.GPIO_PORT_SHIFT) | 8 ), PTE9 = ((4 << Board.GPIO_PORT_SHIFT) | 9 ), PTE10 = ((4 << Board.GPIO_PORT_SHIFT) | 10), PTE11 = ((4 << Board.GPIO_PORT_SHIFT) | 11), PTE12 = ((4 << Board.GPIO_PORT_SHIFT) | 12), PTE13 = ((4 << Board.GPIO_PORT_SHIFT) | 13), PTE14 = ((4 << Board.GPIO_PORT_SHIFT) | 14), PTE15 = ((4 << Board.GPIO_PORT_SHIFT) | 15), PTE16 = ((4 << Board.GPIO_PORT_SHIFT) | 16), PTE17 = ((4 << Board.GPIO_PORT_SHIFT) | 17), PTE18 = ((4 << Board.GPIO_PORT_SHIFT) | 18), PTE19 = ((4 << Board.GPIO_PORT_SHIFT) | 19), PTE20 = ((4 << Board.GPIO_PORT_SHIFT) | 20), PTE21 = ((4 << Board.GPIO_PORT_SHIFT) | 21), PTE22 = ((4 << Board.GPIO_PORT_SHIFT) | 22), PTE23 = ((4 << Board.GPIO_PORT_SHIFT) | 23), PTE24 = ((4 << Board.GPIO_PORT_SHIFT) | 24), PTE25 = ((4 << Board.GPIO_PORT_SHIFT) | 25), PTE26 = ((4 << Board.GPIO_PORT_SHIFT) | 26), PTE27 = ((4 << Board.GPIO_PORT_SHIFT) | 27), PTE28 = ((4 << Board.GPIO_PORT_SHIFT) | 28), PTE29 = ((4 << Board.GPIO_PORT_SHIFT) | 29), PTE30 = ((4 << Board.GPIO_PORT_SHIFT) | 30), PTE31 = ((4 << Board.GPIO_PORT_SHIFT) | 31), LED_RED = PTB22, LED_GREEN = PTE26, LED_BLUE = PTB21, // mbed original LED naming LED1 = LED_RED, LED2 = LED_GREEN, LED3 = LED_BLUE, LED4 = LED_RED, //Push buttons SW2 = PTC6, SW3 = PTA4, // USB Pins USBTX = PTB17, USBRX = PTB16, // Arduino Headers D0 = PTC16, D1 = PTC17, D2 = PTB9, D3 = PTA1, D4 = PTB23, D5 = PTA2, D6 = PTC2, D7 = PTC3, D8 = PTA0, D9 = PTC4, D10 = PTD0, D11 = PTD2, D12 = PTD3, D13 = PTD1, D14 = PTE25, D15 = PTE24, I2C_SCL = D15, I2C_SDA = D14, A0 = PTB2, A1 = PTB3, A2 = PTB10, A3 = PTB11, A4 = PTC11, A5 = PTC10, DAC0_OUT = 0xFEFE, /* DAC does not have Pin Name in RM */ // Not connected NC = 0xFFFFFFFF } } ================================================ FILE: Zelig/BoardConfigurations/K64F/Board/HardwareModel/HardwareProviders/GpioProvider.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // namespace Microsoft.Llilum.K64F.HardwareModel.HardwareProviders { using System; using Chipset = CortexM4OnMBED; public sealed class GpioProvider : Chipset.HardwareModel.GpioProvider { //////public override void RemapInterrupts() //////{ ////// Processor.RemapInterrupt( IRQn.PORTA_IRQn ); ////// Processor.RemapInterrupt( IRQn.PORTB_IRQn ); ////// Processor.RemapInterrupt( IRQn.PORTC_IRQn ); ////// Processor.RemapInterrupt( IRQn.PORTD_IRQn ); ////// Processor.RemapInterrupt( IRQn.PORTE_IRQn ); //////} public override int GetGpioPinIRQNumber(int pinNumber) { PinName pin = (PinName)pinNumber; if (PinName.PTA0 <= pin && pin < PinName.PTB0) { return (int)IRQn.PORTA_IRQn; } else if (PinName.PTB0 <= pin && pin < PinName.PTC0) { return (int)IRQn.PORTB_IRQn; } else if (PinName.PTC0 <= pin && pin < PinName.PTD0) { return (int)IRQn.PORTC_IRQn; } else if (PinName.PTD0 <= pin && pin < PinName.PTE0) { return (int)IRQn.PORTD_IRQn; } else if (PinName.PTE0 <= pin && pin <= PinName.PTE31) { return (int)IRQn.PORTB_IRQn; } throw new NotSupportedException(); } } } ================================================ FILE: Zelig/BoardConfigurations/K64F/Board/HardwareModel/HardwareProviders/I2cProvider.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // namespace Microsoft.Llilum.K64F { using Microsoft.Zelig.Runtime; using Chipset = Microsoft.CortexM4OnMBED; public sealed class I2cProvider : Chipset.HardwareModel.I2cProvider { public static readonly I2cChannelInfo I2C0 = new I2cChannelInfo() { SclPin = (int)PinName.I2C_SCL, SdaPin = (int)PinName.I2C_SDA, PortIndex = 0, }; public override I2cChannelInfo GetI2cChannelInfo(int id) { switch (id) { case 0: return I2C0; default: return null; } } } } ================================================ FILE: Zelig/BoardConfigurations/K64F/Board/HardwareModel/HardwareProviders/NetworkInterfaceProvider.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // namespace Microsoft.Llilum.K64F { using RT = Microsoft.Zelig.Runtime; using Chipset = Microsoft.CortexM3OnMBED.HardwareModel; public sealed class NetworkInterfaceProvider : Chipset.NetworkInterfaceProvider { public override void RemapInterrupts() { Processor.RemapInterrupt( IRQn.ENET_Receive_IRQn ); Processor.RemapInterrupt( IRQn.ENET_Transmit_IRQn ); } } } ================================================ FILE: Zelig/BoardConfigurations/K64F/Board/HardwareModel/HardwareProviders/SpiProvider.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // namespace Microsoft.Llilum.K64F { using System; using Microsoft.Zelig.Runtime; using Chipset = Microsoft.CortexM4OnMBED; using ChipsetAbstration = Microsoft.DeviceModels.Chipset.CortexM4; public sealed class SpiProvider : Chipset.HardwareModel.SpiProvider { public static readonly SpiChannelInfo SPI0 = new SpiChannelInfo() { Mosi = (int)PinName.PTD2, Miso = unchecked((int)PinName.NC), Sclk = (int)PinName.PTD1, DefaultChipSelect = unchecked((int)PinName.NC), SetupTime = 10, HoldTime = 10, ActiveLow = true, }; public static readonly SpiChannelInfo SPI1 = new SpiChannelInfo() { Mosi = (int)PinName.PTD6, Miso = (int)PinName.PTD7, Sclk = (int)PinName.PTD5, DefaultChipSelect = (int)PinName.PTD4, SetupTime = 10, HoldTime = 10, ActiveLow = true, }; public static readonly SpiChannelInfo SPI2 = new SpiChannelInfo() { Mosi = (int)PinName.PTE3, Miso = (int)PinName.PTE1, Sclk = (int)PinName.PTE2, DefaultChipSelect = (int)PinName.PTE4, SetupTime = 10, HoldTime = 10, ActiveLow = true, }; public override bool SpiBusySupported { get { return false; } } public override SpiChannelInfo GetSpiChannelInfo(int id) { switch (id) { case 0: return SPI0; case 1: return SPI1; case 2: return SPI2; default: return null; } } } } ================================================ FILE: Zelig/BoardConfigurations/K64F/Board/HardwareModel/HardwareProvidersUwp/AdcProviderUwp.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // namespace Microsoft.Llilum.K64F { using System; using RT = Microsoft.Zelig.Runtime; using Chipset = Microsoft.CortexM3OnMBED; using ChipsetAbstration = Microsoft.DeviceModels.Chipset.CortexM3; public sealed class AdcProviderUwp : RT.AdcProviderUwp { private static readonly RT.AdcChannelInfoUwp m_adcInfo = new RT.AdcChannelInfoUwp() { MaxValue = UInt16.MaxValue, MinValue = 0, ResolutionInBits = 16, AdcPinNumbers = new int[] { (int)PinName.A0, (int)PinName.A1, (int)PinName.A2, (int)PinName.A3, (int)PinName.A4, (int)PinName.A5 } }; public override RT.AdcChannelInfoUwp GetAdcChannelInfo() { return m_adcInfo; } } } ================================================ FILE: Zelig/BoardConfigurations/K64F/Board/HardwareModel/HardwareProvidersUwp/I2cProviderUwp.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // namespace Microsoft.Llilum.K64F { using System; using Microsoft.Zelig.Runtime; using Chipset = Microsoft.CortexM4OnMBED; using ChipsetAbstration = Microsoft.DeviceModels.Chipset.CortexM4; public sealed class I2cProviderUwp : Microsoft.Zelig.Runtime.I2cProviderUwp { private static string[] m_i2cChannels = { "I2C0" }; public override I2cChannelInfo GetI2cChannelInfo(string busId) { switch (busId) { case "I2C0": return I2cProvider.I2C0; default: return null; } } public override string[] GetI2cChannels() { return m_i2cChannels; } } } ================================================ FILE: Zelig/BoardConfigurations/K64F/Board/HardwareModel/HardwareProvidersUwp/PwmProviderUwp.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // namespace Microsoft.Llilum.K64F { using System; using Microsoft.Zelig.Runtime; using Chipset = Microsoft.CortexM3OnMBED; using ChipsetAbstration = Microsoft.DeviceModels.Chipset.CortexM3; public sealed class PwmProviderUwp : Microsoft.Zelig.Runtime.PwmProviderUwp { private static readonly PwmChannelInfoUwp m_pwmInfo = new PwmChannelInfoUwp() { MaxFrequency = 1000000, MinFrequency = 0, PwmPinNumbers = new int[] { (int)PinName.A4, (int)PinName.A5, (int)PinName.D3, (int)PinName.D4, (int)PinName.D5, (int)PinName.D6, (int)PinName.D7, (int)PinName.D8, (int)PinName.D9, (int)PinName.D10, (int)PinName.D11, (int)PinName.D12, (int)PinName.D13, } }; public override PwmChannelInfoUwp GetPwmChannelInfo() { return m_pwmInfo; } } } ================================================ FILE: Zelig/BoardConfigurations/K64F/Board/HardwareModel/HardwareProvidersUwp/SpiProviderUwp.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // namespace Microsoft.Llilum.K64F { using System; using Microsoft.Zelig.Runtime; using Chipset = Microsoft.CortexM4OnMBED; using ChipsetAbstration = Microsoft.DeviceModels.Chipset.CortexM3; public sealed class SpiProviderUwp : Microsoft.Zelig.Runtime.SpiProviderUwp { private static readonly string[] m_spiDevices = { "SPI0", "SPI1", "SPI2" }; public static readonly SpiChannelInfoUwp SPI0 = new SpiChannelInfoUwp() { ChipSelectLines = 1, MinFreq = 1000, MaxFreq = 30000000, Supports16 = true, ChannelInfoKernel = SpiProvider.SPI0, }; public static readonly SpiChannelInfoUwp SPI1 = new SpiChannelInfoUwp() { ChipSelectLines = 1, MinFreq = 1000, MaxFreq = 30000000, Supports16 = true, ChannelInfoKernel = SpiProvider.SPI1, }; public static readonly SpiChannelInfoUwp SPI2 = new SpiChannelInfoUwp() { ChipSelectLines = 1, MinFreq = 1000, MaxFreq = 30000000, Supports16 = true, ChannelInfoKernel = SpiProvider.SPI2, }; public override SpiChannelInfoUwp GetSpiChannelInfo(string busId) { switch (busId) { case "SPI0": return SPI0; case "SPI1": return SPI1; case "SPI2": return SPI2; default: return null; } } public override string[] GetSpiChannels() { return m_spiDevices; } } } ================================================ FILE: Zelig/BoardConfigurations/K64F/Board/HardwareModel/NVIC.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // namespace Microsoft.Llilum.K64F { enum IRQn { /* Core interrupts */ NonMaskableInt_IRQn = -14, /**< Non Maskable Interrupt */ HardFault_IRQn = -13, /**< Cortex-M4 SV Hard Fault Interrupt */ MemoryManagement_IRQn = -12, /**< Cortex-M4 Memory Management Interrupt */ BusFault_IRQn = -11, /**< Cortex-M4 Bus Fault Interrupt */ UsageFault_IRQn = -10, /**< Cortex-M4 Usage Fault Interrupt */ SVCall_IRQn = -5, /**< Cortex-M4 SV Call Interrupt */ DebugMonitor_IRQn = -4, /**< Cortex-M4 Debug Monitor Interrupt */ PendSV_IRQn = -2, /**< Cortex-M4 Pend SV Interrupt */ SysTick_IRQn = -1, /**< Cortex-M4 System Tick Interrupt */ /* Device specific interrupts */ DMA0_IRQn = 0, /**< DMA Channel 0 Transfer Complete */ DMA1_IRQn = 1, /**< DMA Channel 1 Transfer Complete */ DMA2_IRQn = 2, /**< DMA Channel 2 Transfer Complete */ DMA3_IRQn = 3, /**< DMA Channel 3 Transfer Complete */ DMA4_IRQn = 4, /**< DMA Channel 4 Transfer Complete */ DMA5_IRQn = 5, /**< DMA Channel 5 Transfer Complete */ DMA6_IRQn = 6, /**< DMA Channel 6 Transfer Complete */ DMA7_IRQn = 7, /**< DMA Channel 7 Transfer Complete */ DMA8_IRQn = 8, /**< DMA Channel 8 Transfer Complete */ DMA9_IRQn = 9, /**< DMA Channel 9 Transfer Complete */ DMA10_IRQn = 10, /**< DMA Channel 10 Transfer Complete */ DMA11_IRQn = 11, /**< DMA Channel 11 Transfer Complete */ DMA12_IRQn = 12, /**< DMA Channel 12 Transfer Complete */ DMA13_IRQn = 13, /**< DMA Channel 13 Transfer Complete */ DMA14_IRQn = 14, /**< DMA Channel 14 Transfer Complete */ DMA15_IRQn = 15, /**< DMA Channel 15 Transfer Complete */ DMA_Error_IRQn = 16, /**< DMA Error Interrupt */ MCM_IRQn = 17, /**< Normal Interrupt */ FTFE_IRQn = 18, /**< FTFE Command complete interrupt */ Read_Collision_IRQn = 19, /**< Read Collision Interrupt */ LVD_LVW_IRQn = 20, /**< Low Voltage Detect, Low Voltage Warning */ LLW_IRQn = 21, /**< Low Leakage Wakeup */ Watchdog_IRQn = 22, /**< WDOG Interrupt */ RNG_IRQn = 23, /**< RNG Interrupt */ I2C0_IRQn = 24, /**< I2C0 interrupt */ I2C1_IRQn = 25, /**< I2C1 interrupt */ SPI0_IRQn = 26, /**< SPI0 Interrupt */ SPI1_IRQn = 27, /**< SPI1 Interrupt */ I2S0_Tx_IRQn = 28, /**< I2S0 transmit interrupt */ I2S0_Rx_IRQn = 29, /**< I2S0 receive interrupt */ UART0_LON_IRQn = 30, /**< UART0 LON interrupt */ UART0_RX_TX_IRQn = 31, /**< UART0 Receive/Transmit interrupt */ UART0_ERR_IRQn = 32, /**< UART0 Error interrupt */ UART1_RX_TX_IRQn = 33, /**< UART1 Receive/Transmit interrupt */ UART1_ERR_IRQn = 34, /**< UART1 Error interrupt */ UART2_RX_TX_IRQn = 35, /**< UART2 Receive/Transmit interrupt */ UART2_ERR_IRQn = 36, /**< UART2 Error interrupt */ UART3_RX_TX_IRQn = 37, /**< UART3 Receive/Transmit interrupt */ UART3_ERR_IRQn = 38, /**< UART3 Error interrupt */ ADC0_IRQn = 39, /**< ADC0 interrupt */ CMP0_IRQn = 40, /**< CMP0 interrupt */ CMP1_IRQn = 41, /**< CMP1 interrupt */ FTM0_IRQn = 42, /**< FTM0 fault, overflow and channels interrupt */ FTM1_IRQn = 43, /**< FTM1 fault, overflow and channels interrupt */ FTM2_IRQn = 44, /**< FTM2 fault, overflow and channels interrupt */ CMT_IRQn = 45, /**< CMT interrupt */ RTC_IRQn = 46, /**< RTC interrupt */ RTC_Seconds_IRQn = 47, /**< RTC seconds interrupt */ PIT0_IRQn = 48, /**< PIT timer channel 0 interrupt */ PIT1_IRQn = 49, /**< PIT timer channel 1 interrupt */ PIT2_IRQn = 50, /**< PIT timer channel 2 interrupt */ PIT3_IRQn = 51, /**< PIT timer channel 3 interrupt */ PDB0_IRQn = 52, /**< PDB0 Interrupt */ USB0_IRQn = 53, /**< USB0 interrupt */ USBDCD_IRQn = 54, /**< USBDCD Interrupt */ Reserved71_IRQn = 55, /**< Reserved interrupt 71 */ DAC0_IRQn = 56, /**< DAC0 interrupt */ MCG_IRQn = 57, /**< MCG Interrupt */ LPTimer_IRQn = 58, /**< LPTimer interrupt */ PORTA_IRQn = 59, /**< Port A interrupt */ PORTB_IRQn = 60, /**< Port B interrupt */ PORTC_IRQn = 61, /**< Port C interrupt */ PORTD_IRQn = 62, /**< Port D interrupt */ PORTE_IRQn = 63, /**< Port E interrupt */ SWI_IRQn = 64, /**< Software interrupt */ SPI2_IRQn = 65, /**< SPI2 Interrupt */ UART4_RX_TX_IRQn = 66, /**< UART4 Receive/Transmit interrupt */ UART4_ERR_IRQn = 67, /**< UART4 Error interrupt */ UART5_RX_TX_IRQn = 68, /**< UART5 Receive/Transmit interrupt */ UART5_ERR_IRQn = 69, /**< UART5 Error interrupt */ CMP2_IRQn = 70, /**< CMP2 interrupt */ FTM3_IRQn = 71, /**< FTM3 fault, overflow and channels interrupt */ DAC1_IRQn = 72, /**< DAC1 interrupt */ ADC1_IRQn = 73, /**< ADC1 interrupt */ I2C2_IRQn = 74, /**< I2C2 interrupt */ CAN0_ORed_Message_buffer_IRQn = 75, /**< CAN0 OR'd message buffers interrupt */ CAN0_Bus_Off_IRQn = 76, /**< CAN0 bus off interrupt */ CAN0_Error_IRQn = 77, /**< CAN0 error interrupt */ CAN0_Tx_Warning_IRQn = 78, /**< CAN0 Tx warning interrupt */ CAN0_Rx_Warning_IRQn = 79, /**< CAN0 Rx warning interrupt */ CAN0_Wake_Up_IRQn = 80, /**< CAN0 wake up interrupt */ SDHC_IRQn = 81, /**< SDHC interrupt */ ENET_1588_Timer_IRQn = 82, /**< Ethernet MAC IEEE 1588 Timer Interrupt */ ENET_Transmit_IRQn = 83, /**< Ethernet MAC Transmit Interrupt */ ENET_Receive_IRQn = 84, /**< Ethernet MAC Receive Interrupt */ ENET_Error_IRQn = 85, /**< Ethernet MAC Error and miscelaneous Interrupt */ LAST = 86, } } ================================================ FILE: Zelig/BoardConfigurations/K64F/Board/HardwareModel/Peripherals.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // //#define ALLOW_PAUSE namespace Microsoft.Llilum.K64F { using RT = Microsoft.Zelig.Runtime; using Chipset = Microsoft.CortexM4OnMBED; using CMSIS = Microsoft.DeviceModels.Chipset.CortexM; public sealed class Peripherals : Chipset.Peripherals { public override void Initialize() { base.Initialize( ); // // Peripherals exceptions all have same priority // for(int i = 0; i < (int)IRQn.LAST; ++i) { CMSIS.NVIC.SetPriority( i , RT.TargetPlatform.ARMv7.ProcessorARMv7M.c_Priority__GenericPeripherals ); } } } } ================================================ FILE: Zelig/BoardConfigurations/K64F/Board/HardwareModel/Processor.cs ================================================ // // Copyright ((c) Microsoft Corporation. All rights reserved. // namespace Microsoft.Llilum.K64F { using System; using System.Runtime.InteropServices; using RT = Microsoft.Zelig.Runtime; using ARMv7 = Microsoft.Zelig.Runtime.TargetPlatform.ARMv7; using ChipsetModel = Microsoft.CortexM4OnMBED; [RT.ProductFilter( "Microsoft.Llilum.BoardConfigurations.K64FMBED" )] public sealed class Processor : Microsoft.CortexM4OnMBED.Processor { public new class Context : ChipsetModel.Processor.Context { public Context( RT.ThreadImpl owner ) : base( owner ) { } public override unsafe void SwitchTo( ) { // // BUGBUG: return to thread using VFP state as well // base.SwitchTo( ); } } internal static void RemapInterrupt( IRQn irqNumber ) { var processor = (Microsoft.Llilum.K64F.Processor)Processor.Instance; using(RT.SmartHandles.InterruptState.Disable( )) { switch(irqNumber) { //////// //////// UART //////// //////case IRQn.UART0_ERR_IRQn: ////// processor.RemapInterrupt( (IRQn_Type)IRQn.UART0_ERR_IRQn, Zelig_Exception_UART0_ERR_IRQHandler ); ////// break; //////case IRQn.UART0_RX_TX_IRQn: ////// processor.RemapInterrupt( (IRQn_Type)IRQn.UART0_RX_TX_IRQn, Zelig_Exception_UART0_RX_TX_IRQHandler ); ////// break; //////case IRQn.UART1_ERR_IRQn: ////// processor.RemapInterrupt( (IRQn_Type)IRQn.UART1_ERR_IRQn, Zelig_Exception_UART1_ERR_IRQHandler ); ////// break; //////case IRQn.UART1_RX_TX_IRQn: ////// processor.RemapInterrupt( (IRQn_Type)IRQn.UART1_RX_TX_IRQn, Zelig_Exception_UART1_RX_TX_IRQHandler ); ////// break; //////case IRQn.UART3_ERR_IRQn: ////// processor.RemapInterrupt( (IRQn_Type)IRQn.UART3_ERR_IRQn, Zelig_Exception_UART3_ERR_IRQHandler ); ////// break; //////case IRQn.UART3_RX_TX_IRQn: ////// processor.RemapInterrupt( (IRQn_Type)IRQn.UART3_RX_TX_IRQn, Zelig_Exception_UART3_RX_TX_IRQHandler ); ////// break; //////// //////// GPIO //////// //////case IRQn.PORTA_IRQn: ////// processor.RemapInterrupt( (IRQn_Type)IRQn.PORTA_IRQn, Zelig_Exception_PORTA_IRQHandler ); ////// break; //////case IRQn.PORTB_IRQn: ////// processor.RemapInterrupt( (IRQn_Type)IRQn.PORTB_IRQn, Zelig_Exception_PORTB_IRQHandler ); ////// break; //////case IRQn.PORTC_IRQn: ////// processor.RemapInterrupt( (IRQn_Type)IRQn.PORTC_IRQn, Zelig_Exception_PORTC_IRQHandler ); ////// break; //////case IRQn.PORTD_IRQn: ////// processor.RemapInterrupt( (IRQn_Type)IRQn.PORTD_IRQn, Zelig_Exception_PORTD_IRQHandler ); ////// break; //////case IRQn.PORTE_IRQn: ////// processor.RemapInterrupt( (IRQn_Type)IRQn.PORTE_IRQn, Zelig_Exception_PORTE_IRQHandler ); ////// break; // // Ethernet // case IRQn.ENET_Receive_IRQn: processor.RemapInterrupt( (IRQn_Type)IRQn.ENET_Receive_IRQn, Zelig_Exception_ENET_Receive_IRQHandler ); break; case IRQn.ENET_Transmit_IRQn: processor.RemapInterrupt( (IRQn_Type)IRQn.ENET_Transmit_IRQn, Zelig_Exception_ENET_Transmit_IRQHandler ); break; default: RT.BugCheck.Assert( false, Zelig.Runtime.BugCheck.StopCode.IncorrectArgument ); break; } } } //--// // // State // private static readonly Action s_ENET_Receive_IRQHandler; private static readonly Action s_ENET_Transmit_IRQHandler; //////private static readonly Action s_UART0_RX_TX_IRQHandler; //////private static readonly Action s_UART0_ERR_IRQHandler; //////private static readonly Action s_UART1_RX_TX_IRQHandler; //////private static readonly Action s_UART1_ERR_IRQHandler; //////private static readonly Action s_UART3_RX_TX_IRQHandler; //////private static readonly Action s_UART3_ERR_IRQHandler; //////private static readonly Action s_PORTA_IRQHandler; //////private static readonly Action s_PORTB_IRQHandler; //////private static readonly Action s_PORTC_IRQHandler; //////private static readonly Action s_PORTD_IRQHandler; //////private static readonly Action s_PORTE_IRQHandler; //--// // // Constructors // static Processor( ) { s_ENET_Transmit_IRQHandler = new Action( ENET_Transmit_IRQHandler_Wrapper ); s_ENET_Receive_IRQHandler = new Action( ENET_Receive_IRQHandler_Wrapper ); //////s_UART0_RX_TX_IRQHandler = new Action( UART0_RX_TX_IRQHandler ); //////s_UART0_ERR_IRQHandler = new Action( UART0_ERR_IRQHandler ); //////s_UART1_RX_TX_IRQHandler = new Action( UART1_RX_TX_IRQHandler ); //////s_UART1_ERR_IRQHandler = new Action( UART1_ERR_IRQHandler ); //////s_UART3_RX_TX_IRQHandler = new Action( UART3_RX_TX_IRQHandler ); //////s_UART3_ERR_IRQHandler = new Action( UART3_ERR_IRQHandler ); //////s_PORTA_IRQHandler = new Action( PORTA_IRQHandler ); //////s_PORTB_IRQHandler = new Action( PORTB_IRQHandler ); //////s_PORTC_IRQHandler = new Action( PORTC_IRQHandler ); //////s_PORTD_IRQHandler = new Action( PORTD_IRQHandler ); //////s_PORTE_IRQHandler = new Action( PORTE_IRQHandler ); } // // Helper methods // [RT.Inline] public override void InitializeProcessor( ) { base.InitializeProcessor( ); DisableMPU( ); } [RT.Inline] public override Microsoft.Zelig.Runtime.Processor.Context AllocateProcessorContext( RT.ThreadImpl owner ) { return new Context( owner ); } //--// private unsafe void DisableMPU( ) { CUSTOM_STUB_K64F_DisableMPU( ); } [DllImport( "C" )] private static extern void CUSTOM_STUB_K64F_DisableMPU( ); //--// //--// //--// #region Warapper for exception handlers // // UART // private static void UART0_RX_TX_IRQHandler_Wrapper( ) { UART0_RX_TX_IRQHandler( ); } private static void UART0_ERR_IRQHandler_Wrapper( ) { UART0_ERR_IRQHandler( ); } private static void UART1_RX_TX_IRQHandler_Wrapper( ) { UART1_RX_TX_IRQHandler( ); } private static void UART1_ERR_IRQHandler_Wrapper( ) { UART1_ERR_IRQHandler( ); } private static void UART3_RX_TX_IRQHandler_Wrapper( ) { UART3_RX_TX_IRQHandler( ); } private static void UART3_ERR_IRQHandler_Wrapper( ) { UART3_ERR_IRQHandler( ); } // // GPIO // private static void PORTA_IRQHandler_Wrapper( ) { PORTA_IRQHandler( ); } private static void PORTB_IRQHandler_Wrapper( ) { PORTB_IRQHandler( ); } private static void PORTC_IRQHandler_Wrapper( ) { PORTC_IRQHandler( ); } private static void PORTD_IRQHandler_Wrapper( ) { PORTD_IRQHandler( ); } private static void PORTE_IRQHandler_Wrapper( ) { PORTE_IRQHandler( ); } // // Ethernet // private static void ENET_Transmit_IRQHandler_Wrapper( ) { ENET_Transmit_IRQHandler( ); } private static void ENET_Receive_IRQHandler_Wrapper( ) { ENET_Receive_IRQHandler( ); } #endregion //--// //--// //--// #region Exported exception handlers // // Export all exception handler for native platform to call // //////[RT.HardwareExceptionHandler( RT.HardwareException.Interrupt )] //////[RT.ExportedMethod] //////private static void Zelig_Exception_DMA0_IRQHandler( ) //////{ ////// ARMv7.ProcessorARMv7M.ExclusiveAccessExceptionHandler( DMA0_IRQHandler ); //////} //////[RT.HardwareExceptionHandler( RT.HardwareException.Interrupt )] //////[RT.ExportedMethod] //////private static void Zelig_Exception_DMA1_IRQHandler( ) //////{ ////// ARMv7.ProcessorARMv7M.ExclusiveAccessExceptionHandler( DMA1_IRQHandler ); //////} //////[RT.HardwareExceptionHandler( RT.HardwareException.Interrupt )] //////[RT.ExportedMethod] //////private static void Zelig_Exception_DMA2_IRQHandler( ) //////{ ////// ARMv7.ProcessorARMv7M.ExclusiveAccessExceptionHandler( DMA2_IRQHandler ); //////} //////[RT.HardwareExceptionHandler( RT.HardwareException.Interrupt )] //////[RT.ExportedMethod] //////private static void Zelig_Exception_DMA3_IRQHandler( ) //////{ ////// ARMv7.ProcessorARMv7M.ExclusiveAccessExceptionHandler( DMA3_IRQHandler ); //////} //////[RT.HardwareExceptionHandler( RT.HardwareException.Interrupt )] //////[RT.ExportedMethod] //////private static void Zelig_Exception_DMA4_IRQHandler( ) //////{ ////// ARMv7.ProcessorARMv7M.ExclusiveAccessExceptionHandler( DMA4_IRQHandler ); //////} //////[RT.HardwareExceptionHandler( RT.HardwareException.Interrupt )] //////[RT.ExportedMethod] //////private static void Zelig_Exception_DMA5_IRQHandler( ) //////{ ////// ARMv7.ProcessorARMv7M.ExclusiveAccessExceptionHandler( DMA5_IRQHandler ); //////} //////[RT.HardwareExceptionHandler( RT.HardwareException.Interrupt )] //////[RT.ExportedMethod] //////private static void Zelig_Exception_DMA6_IRQHandler( ) //////{ ////// ARMv7.ProcessorARMv7M.ExclusiveAccessExceptionHandler( DMA6_IRQHandler ); //////} //////[RT.HardwareExceptionHandler( RT.HardwareException.Interrupt )] //////[RT.ExportedMethod] //////private static void Zelig_Exception_DMA7_IRQHandler( ) //////{ ////// ARMv7.ProcessorARMv7M.ExclusiveAccessExceptionHandler( DMA7_IRQHandler ); //////} //////[RT.HardwareExceptionHandler( RT.HardwareException.Interrupt )] //////[RT.ExportedMethod] //////private static void Zelig_Exception_DMA8_IRQHandler( ) //////{ ////// ARMv7.ProcessorARMv7M.ExclusiveAccessExceptionHandler( DMA8_IRQHandler ); //////} //////[RT.HardwareExceptionHandler( RT.HardwareException.Interrupt )] //////[RT.ExportedMethod] //////private static void Zelig_Exception_DMA9_IRQHandler( ) //////{ ////// ARMv7.ProcessorARMv7M.ExclusiveAccessExceptionHandler( DMA9_IRQHandler ); //////} //////[RT.HardwareExceptionHandler( RT.HardwareException.Interrupt )] //////[RT.ExportedMethod] //////private static void Zelig_Exception_DMA10_IRQHandler( ) //////{ ////// ARMv7.ProcessorARMv7M.ExclusiveAccessExceptionHandler( DMA10_IRQHandler ); //////} //////[RT.HardwareExceptionHandler( RT.HardwareException.Interrupt )] //////[RT.ExportedMethod] //////private static void Zelig_Exception_DMA11_IRQHandler( ) //////{ ////// ARMv7.ProcessorARMv7M.ExclusiveAccessExceptionHandler( DMA11_IRQHandler ); //////} //////[RT.HardwareExceptionHandler( RT.HardwareException.Interrupt )] //////[RT.ExportedMethod] //////private static void Zelig_Exception_DMA12_IRQHandler( ) //////{ ////// ARMv7.ProcessorARMv7M.ExclusiveAccessExceptionHandler( DMA12_IRQHandler ); //////} //////[RT.HardwareExceptionHandler( RT.HardwareException.Interrupt )] //////[RT.ExportedMethod] //////private static void Zelig_Exception_DMA13_IRQHandler( ) //////{ ////// ARMv7.ProcessorARMv7M.ExclusiveAccessExceptionHandler( DMA13_IRQHandler ); //////} //////[RT.HardwareExceptionHandler( RT.HardwareException.Interrupt )] //////[RT.ExportedMethod] //////private static void Zelig_Exception_DMA14_IRQHandler( ) //////{ ////// ARMv7.ProcessorARMv7M.ExclusiveAccessExceptionHandler( DMA14_IRQHandler ); //////} //////[RT.HardwareExceptionHandler( RT.HardwareException.Interrupt )] //////[RT.ExportedMethod] //////private static void Zelig_Exception_DMA15_IRQHandler( ) //////{ ////// ARMv7.ProcessorARMv7M.ExclusiveAccessExceptionHandler( DMA15_IRQHandler ); //////} //////[RT.HardwareExceptionHandler( RT.HardwareException.Interrupt )] //////[RT.ExportedMethod] //////private static void Zelig_Exception_DMA_Error_IRQHandler( ) //////{ ////// ARMv7.ProcessorARMv7M.ExclusiveAccessExceptionHandler( DMA_Error_IRQHandler ); //////} //////[RT.HardwareExceptionHandler( RT.HardwareException.Interrupt )] //////[RT.ExportedMethod] //////private static void Zelig_Exception_MCM_IRQHandler( ) //////{ ////// ARMv7.ProcessorARMv7M.ExclusiveAccessExceptionHandler( MCM_IRQHandler ); //////} //////[RT.HardwareExceptionHandler( RT.HardwareException.Interrupt )] //////[RT.ExportedMethod] //////private static void Zelig_Exception_FTFE_IRQHandler( ) //////{ ////// ARMv7.ProcessorARMv7M.ExclusiveAccessExceptionHandler( FTFE_IRQHandler ); //////} //////[RT.HardwareExceptionHandler( RT.HardwareException.Interrupt )] //////[RT.ExportedMethod] //////private static void Zelig_Exception_Read_Collision_IRQHandler( ) //////{ ////// ARMv7.ProcessorARMv7M.ExclusiveAccessExceptionHandler( Read_Collision_IRQHandler ); //////} //////[RT.HardwareExceptionHandler( RT.HardwareException.Interrupt )] //////[RT.ExportedMethod] //////private static void Zelig_Exception_LVD_LVW_IRQHandler( ) //////{ ////// ARMv7.ProcessorARMv7M.ExclusiveAccessExceptionHandler( LVD_LVW_IRQHandler ); //////} //////[RT.HardwareExceptionHandler( RT.HardwareException.Interrupt )] //////[RT.ExportedMethod] //////private static void Zelig_Exception_LLW_IRQHandler( ) //////{ ////// ARMv7.ProcessorARMv7M.ExclusiveAccessExceptionHandler( LLW_IRQHandler ); //////} //////[RT.HardwareExceptionHandler( RT.HardwareException.Interrupt )] //////[RT.ExportedMethod] //////private static void Zelig_Exception_Watchdog_IRQHandler( ) //////{ ////// ARMv7.ProcessorARMv7M.ExclusiveAccessExceptionHandler( Watchdog_IRQHandler ); //////} //////[RT.HardwareExceptionHandler( RT.HardwareException.Interrupt )] //////[RT.ExportedMethod] //////private static void Zelig_Exception_RNG_IRQHandler( ) //////{ ////// ARMv7.ProcessorARMv7M.ExclusiveAccessExceptionHandler( RNG_IRQHandler ); //////} //////[RT.HardwareExceptionHandler( RT.HardwareException.Interrupt )] //////[RT.ExportedMethod] //////private static void Zelig_Exception_I2C0_IRQHandler( ) //////{ ////// ARMv7.ProcessorARMv7M.ExclusiveAccessExceptionHandler( I2C0_IRQHandler ); //////} //////[RT.HardwareExceptionHandler( RT.HardwareException.Interrupt )] //////[RT.ExportedMethod] //////private static void Zelig_Exception_I2C1_IRQHandler( ) //////{ ////// ARMv7.ProcessorARMv7M.ExclusiveAccessExceptionHandler( I2C1_IRQHandler ); //////} //////[RT.HardwareExceptionHandler( RT.HardwareException.Interrupt )] //////[RT.ExportedMethod] //////private static void Zelig_Exception_SPI0_IRQHandler( ) //////{ ////// ARMv7.ProcessorARMv7M.ExclusiveAccessExceptionHandler( SPI0_IRQHandler ); //////} //////[RT.HardwareExceptionHandler( RT.HardwareException.Interrupt )] //////[RT.ExportedMethod] //////private static void Zelig_Exception_SPI1_IRQHandler( ) //////{ ////// ARMv7.ProcessorARMv7M.ExclusiveAccessExceptionHandler( SPI1_IRQHandler ); //////} //////[RT.HardwareExceptionHandler( RT.HardwareException.Interrupt )] //////[RT.ExportedMethod] //////private static void Zelig_Exception_I2S0_Tx_IRQHandler( ) //////{ ////// ARMv7.ProcessorARMv7M.ExclusiveAccessExceptionHandler( I2S0_Tx_IRQHandler ); //////} //////[RT.HardwareExceptionHandler( RT.HardwareException.Interrupt )] //////[RT.ExportedMethod] //////private static void Zelig_Exception_I2S0_Rx_IRQHandler( ) //////{ ////// ARMv7.ProcessorARMv7M.ExclusiveAccessExceptionHandler( I2S0_Rx_IRQHandler ); //////} //////[RT.HardwareExceptionHandler(RT.HardwareException.Interrupt)] //////[RT.ExportedMethod] //////private static void Zelig_Exception_UART0_LON_IRQHandler() //////{ ////// ARMv7.ProcessorARMv7M.ExclusiveAccessExceptionHandler(UART0_LON_IRQHandler); //////} //////[RT.HardwareExceptionHandler( RT.HardwareException.Interrupt )] //////[RT.ExportedMethod] //////private static void Zelig_Exception_UART0_RX_TX_IRQHandler( ) //////{ ////// ARMv7.ProcessorARMv7M.ExclusiveAccessExceptionHandler( s_UART0_RX_TX_IRQHandler ); //////} //////[RT.HardwareExceptionHandler( RT.HardwareException.Interrupt )] //////[RT.ExportedMethod] //////private static void Zelig_Exception_UART0_ERR_IRQHandler( ) //////{ ////// ARMv7.ProcessorARMv7M.ExclusiveAccessExceptionHandler( s_UART0_ERR_IRQHandler ); //////} //////[RT.HardwareExceptionHandler( RT.HardwareException.Interrupt )] //////[RT.ExportedMethod] //////private static void Zelig_Exception_UART1_RX_TX_IRQHandler( ) //////{ ////// ARMv7.ProcessorARMv7M.ExclusiveAccessExceptionHandler( s_UART1_RX_TX_IRQHandler ); //////} //////[RT.HardwareExceptionHandler( RT.HardwareException.Interrupt )] //////[RT.ExportedMethod] //////[RT.DisableNullChecks] //////private static void Zelig_Exception_UART1_ERR_IRQHandler( ) //////{ ////// ARMv7.ProcessorARMv7M.ExclusiveAccessExceptionHandler( s_UART1_ERR_IRQHandler ); //////} //////[RT.HardwareExceptionHandler(RT.HardwareException.Interrupt)] //////[RT.ExportedMethod] //////private static void Zelig_Exception_UART2_RX_TX_IRQHandler() //////{ ////// ARMv7.ProcessorARMv7M.ExclusiveAccessExceptionHandler(UART2_RX_TX_IRQHandler); //////} //////[RT.HardwareExceptionHandler(RT.HardwareException.Interrupt)] //////[RT.ExportedMethod] //////private static void Zelig_Exception_UART2_ERR_IRQHandler() //////{ ////// ARMv7.ProcessorARMv7M.ExclusiveAccessExceptionHandler(UART2_ERR_IRQHandler); //////} //////[RT.HardwareExceptionHandler( RT.HardwareException.Interrupt )] //////[RT.ExportedMethod] //////private static void Zelig_Exception_UART3_RX_TX_IRQHandler( ) //////{ ////// ARMv7.ProcessorARMv7M.ExclusiveAccessExceptionHandler( s_UART3_RX_TX_IRQHandler ); //////} //////[RT.HardwareExceptionHandler( RT.HardwareException.Interrupt )] //////[RT.ExportedMethod] //////private static void Zelig_Exception_UART3_ERR_IRQHandler( ) //////{ ////// ARMv7.ProcessorARMv7M.ExclusiveAccessExceptionHandler( s_UART3_ERR_IRQHandler ); //////} //////[RT.HardwareExceptionHandler( RT.HardwareException.Interrupt )] //////[RT.ExportedMethod] //////private static void Zelig_Exception_ADC0_IRQHandler( ) //////{ ////// ARMv7.ProcessorARMv7M.ExclusiveAccessExceptionHandler( ADC0_IRQHandler ); //////} //////[RT.HardwareExceptionHandler( RT.HardwareException.Interrupt )] //////[RT.ExportedMethod] //////private static void Zelig_Exception_CMP0_IRQHandler( ) //////{ ////// ARMv7.ProcessorARMv7M.ExclusiveAccessExceptionHandler( CMP0_IRQHandler ); //////} //////[RT.HardwareExceptionHandler( RT.HardwareException.Interrupt )] //////[RT.ExportedMethod] //////private static void Zelig_Exception_CMP1_IRQHandler( ) //////{ ////// ARMv7.ProcessorARMv7M.ExclusiveAccessExceptionHandler( CMP1_IRQHandler ); //////} //////[RT.HardwareExceptionHandler( RT.HardwareException.Interrupt )] //////[RT.ExportedMethod] //////private static void Zelig_Exception_FTM0_IRQHandler( ) //////{ ////// ARMv7.ProcessorARMv7M.ExclusiveAccessExceptionHandler( FTM0_IRQHandler ); //////} //////[RT.HardwareExceptionHandler( RT.HardwareException.Interrupt )] //////[RT.ExportedMethod] //////private static void Zelig_Exception_FTM1_IRQHandler( ) //////{ ////// ARMv7.ProcessorARMv7M.ExclusiveAccessExceptionHandler( FTM1_IRQHandler ); //////} //////[RT.HardwareExceptionHandler( RT.HardwareException.Interrupt )] //////[RT.ExportedMethod] //////private static void Zelig_Exception_FTM2_IRQHandler( ) //////{ ////// ARMv7.ProcessorARMv7M.ExclusiveAccessExceptionHandler( FTM2_IRQHandler ); //////} //////[RT.HardwareExceptionHandler( RT.HardwareException.Interrupt )] //////[RT.ExportedMethod] //////private static void Zelig_Exception_CMT_IRQHandler( ) //////{ ////// ARMv7.ProcessorARMv7M.ExclusiveAccessExceptionHandler( CMT_IRQHandler ); //////} //////[RT.HardwareExceptionHandler( RT.HardwareException.Interrupt )] //////[RT.ExportedMethod] //////private static void Zelig_Exception_RTC_IRQHandler( ) //////{ ////// ARMv7.ProcessorARMv7M.ExclusiveAccessExceptionHandler( RTC_IRQHandler ); //////} //////[RT.HardwareExceptionHandler( RT.HardwareException.Interrupt )] //////[RT.ExportedMethod] //////private static void Zelig_Exception_RTC_Seconds_IRQHandler( ) //////{ ////// ARMv7.ProcessorARMv7M.ExclusiveAccessExceptionHandler( RTC_Seconds_IRQHandler ); //////} //////[RT.HardwareExceptionHandler( RT.HardwareException.Interrupt )] //////[RT.ExportedMethod] //////private static void Zelig_Exception_PIT0_IRQHandler( ) //////{ ////// ARMv7.ProcessorARMv7M.ExclusiveAccessExceptionHandler( PIT0_IRQHandler ); //////} //////[RT.HardwareExceptionHandler( RT.HardwareException.Interrupt )] //////[RT.ExportedMethod] //////private static void Zelig_Exception_PIT1_IRQHandler( ) //////{ ////// ARMv7.ProcessorARMv7M.ExclusiveAccessExceptionHandler( PIT1_IRQHandler ); //////} //////[RT.HardwareExceptionHandler( RT.HardwareException.Interrupt )] //////[RT.ExportedMethod] //////private static void Zelig_Exception_PIT2_IRQHandler( ) //////{ ////// ARMv7.ProcessorARMv7M.ExclusiveAccessExceptionHandler( PIT2_IRQHandler ); //////} //////[RT.HardwareExceptionHandler(RT.HardwareException.Interrupt)] //////[RT.ExportedMethod] //////private static void Zelig_Exception_PIT3_IRQHandler() //////{ ////// ARMv7.ProcessorARMv7M.ExclusiveAccessExceptionHandler(PIT3_IRQHandler); //////} //////[RT.HardwareExceptionHandler( RT.HardwareException.Interrupt )] //////[RT.ExportedMethod] //////private static void Zelig_Exception_PDB0_IRQHandler( ) //////{ ////// ARMv7.ProcessorARMv7M.ExclusiveAccessExceptionHandler( PDB0_IRQHandler ); //////} //////[RT.HardwareExceptionHandler( RT.HardwareException.Interrupt )] //////[RT.ExportedMethod] //////private static void Zelig_Exception_USB0_IRQHandler( ) //////{ ////// ARMv7.ProcessorARMv7M.ExclusiveAccessExceptionHandler( USB0_IRQHandler ); //////} //////[RT.HardwareExceptionHandler( RT.HardwareException.Interrupt )] //////[RT.ExportedMethod] //////private static void Zelig_Exception_USBDCD_IRQHandler( ) //////{ ////// ARMv7.ProcessorARMv7M.ExclusiveAccessExceptionHandler( USBDCD_IRQHandler ); //////} //////[RT.HardwareExceptionHandler( RT.HardwareException.Interrupt )] //////[RT.ExportedMethod] //////private static void Zelig_Exception_Reserved71_IRQHandler( ) //////{ ////// ARMv7.ProcessorARMv7M.ExclusiveAccessExceptionHandler( Reserved71_IRQHandler ); //////} //////[RT.HardwareExceptionHandler( RT.HardwareException.Interrupt )] //////[RT.ExportedMethod] //////private static void Zelig_Exception_DAC0_IRQHandler( ) //////{ ////// ARMv7.ProcessorARMv7M.ExclusiveAccessExceptionHandler( DAC0_IRQHandler ); //////} //////[RT.HardwareExceptionHandler( RT.HardwareException.Interrupt )] //////[RT.ExportedMethod] //////private static void Zelig_Exception_MCG_IRQHandler( ) //////{ ////// ARMv7.ProcessorARMv7M.ExclusiveAccessExceptionHandler( MCG_IRQHandler ); //////} //////[RT.HardwareExceptionHandler( RT.HardwareException.Interrupt )] //////[RT.ExportedMethod] //////private static void Zelig_Exception_LPTimer_IRQHandler( ) //////{ ////// ARMv7.ProcessorARMv7M.ExclusiveAccessExceptionHandler( LPTimer_IRQHandler ); //////} //////[RT.HardwareExceptionHandler( RT.HardwareException.Interrupt )] //////[RT.ExportedMethod] //////private static void Zelig_Exception_PORTA_IRQHandler( ) //////{ ////// ARMv7.ProcessorARMv7M.ExclusiveAccessExceptionHandler( s_PORTA_IRQHandler ); //////} //////[RT.HardwareExceptionHandler( RT.HardwareException.Interrupt )] //////[RT.ExportedMethod] //////private static void Zelig_Exception_PORTB_IRQHandler( ) //////{ ////// ARMv7.ProcessorARMv7M.ExclusiveAccessExceptionHandler( s_PORTB_IRQHandler ); //////} //////[RT.HardwareExceptionHandler( RT.HardwareException.Interrupt )] //////[RT.ExportedMethod] //////private static void Zelig_Exception_PORTC_IRQHandler( ) //////{ ////// ARMv7.ProcessorARMv7M.ExclusiveAccessExceptionHandler( s_PORTC_IRQHandler ); //////} //////[RT.HardwareExceptionHandler( RT.HardwareException.Interrupt )] //////[RT.ExportedMethod] //////private static void Zelig_Exception_PORTD_IRQHandler( ) //////{ ////// ARMv7.ProcessorARMv7M.ExclusiveAccessExceptionHandler( s_PORTD_IRQHandler ); //////} //////[RT.HardwareExceptionHandler( RT.HardwareException.Interrupt )] //////[RT.ExportedMethod] //////private static void Zelig_Exception_PORTE_IRQHandler( ) //////{ ////// ARMv7.ProcessorARMv7M.ExclusiveAccessExceptionHandler( s_PORTE_IRQHandler ); //////} //////[RT.HardwareExceptionHandler( RT.HardwareException.Interrupt )] //////[RT.ExportedMethod] //////private static void Zelig_Exception_SWI_IRQHandler( ) //////{ ////// ARMv7.ProcessorARMv7M.ExclusiveAccessExceptionHandler( SWI_IRQHandler ); //////} //////[RT.HardwareExceptionHandler( RT.HardwareException.Interrupt )] //////[RT.ExportedMethod] //////private static void Zelig_Exception_SPI2_IRQHandler( ) //////{ ////// ARMv7.ProcessorARMv7M.ExclusiveAccessExceptionHandler( SPI2_IRQHandler ); //////} //////[RT.HardwareExceptionHandler( RT.HardwareException.Interrupt )] //////[RT.ExportedMethod] //////private static void Zelig_Exception_UART4_RX_TX_IRQHandler( ) //////{ ////// ARMv7.ProcessorARMv7M.ExclusiveAccessExceptionHandler( UART4_RX_TX_IRQHandler ); //////} //////[RT.HardwareExceptionHandler( RT.HardwareException.Interrupt )] //////[RT.ExportedMethod] //////private static void Zelig_Exception_UART4_ERR_IRQHandler( ) //////{ ////// ARMv7.ProcessorARMv7M.ExclusiveAccessExceptionHandler( UART4_ERR_IRQHandler ); //////} //////[RT.HardwareExceptionHandler( RT.HardwareException.Interrupt )] //////[RT.ExportedMethod] //////private static void Zelig_Exception_UART5_RX_TX_IRQHandler( ) //////{ ////// ARMv7.ProcessorARMv7M.ExclusiveAccessExceptionHandler( UART5_RX_TX_IRQHandler ); //////} //////[RT.HardwareExceptionHandler( RT.HardwareException.Interrupt )] //////[RT.ExportedMethod] //////private static void Zelig_Exception_UART5_ERR_IRQHandler( ) //////{ ////// ARMv7.ProcessorARMv7M.ExclusiveAccessExceptionHandler( UART5_ERR_IRQHandler ); //////} //////[RT.HardwareExceptionHandler( RT.HardwareException.Interrupt )] //////[RT.ExportedMethod] //////private static void Zelig_Exception_CMP2_IRQHandler( ) //////{ ////// ARMv7.ProcessorARMv7M.ExclusiveAccessExceptionHandler( CMP2_IRQHandler ); //////} //////[RT.HardwareExceptionHandler( RT.HardwareException.Interrupt )] //////[RT.ExportedMethod] //////private static void Zelig_Exception_FTM3_IRQHandler( ) //////{ ////// ARMv7.ProcessorARMv7M.ExclusiveAccessExceptionHandler( FTM3_IRQHandler ); //////} //////[RT.HardwareExceptionHandler( RT.HardwareException.Interrupt )] //////[RT.ExportedMethod] //////private static void Zelig_Exception_DAC1_IRQHandler( ) //////{ ////// ARMv7.ProcessorARMv7M.ExclusiveAccessExceptionHandler( DAC1_IRQHandler ); //////} //////[RT.HardwareExceptionHandler( RT.HardwareException.Interrupt )] //////[RT.ExportedMethod] //////private static void Zelig_Exception_ADC1_IRQHandler( ) //////{ ////// ARMv7.ProcessorARMv7M.ExclusiveAccessExceptionHandler( ADC1_IRQHandler ); //////} //////[RT.HardwareExceptionHandler( RT.HardwareException.Interrupt )] //////[RT.ExportedMethod] //////private static void Zelig_Exception_I2C2_IRQHandler( ) //////{ ////// ARMv7.ProcessorARMv7M.ExclusiveAccessExceptionHandler( I2C2_IRQHandler ); //////} //////[RT.HardwareExceptionHandler( RT.HardwareException.Interrupt )] //////[RT.ExportedMethod] //////private static void Zelig_Exception_CAN0_ORed_Message_buffer_IRQHandler( ) //////{ ////// ARMv7.ProcessorARMv7M.ExclusiveAccessExceptionHandler( CAN0_ORed_Message_buffer_IRQHandler ); //////} //////[RT.HardwareExceptionHandler( RT.HardwareException.Interrupt )] //////[RT.ExportedMethod] //////private static void Zelig_Exception_CAN0_Bus_Off_IRQHandler( ) //////{ ////// ARMv7.ProcessorARMv7M.ExclusiveAccessExceptionHandler( CAN0_Bus_Off_IRQHandler ); //////} //////[RT.HardwareExceptionHandler( RT.HardwareException.Interrupt )] //////[RT.ExportedMethod] //////private static void Zelig_Exception_CAN0_Error_IRQHandler( ) //////{ ////// ARMv7.ProcessorARMv7M.ExclusiveAccessExceptionHandler( CAN0_Error_IRQHandler ); //////} //////[RT.HardwareExceptionHandler( RT.HardwareException.Interrupt )] //////[RT.ExportedMethod] //////private static void Zelig_Exception_CAN0_Tx_Warning_IRQHandler( ) //////{ ////// ARMv7.ProcessorARMv7M.ExclusiveAccessExceptionHandler( CAN0_Tx_Warning_IRQHandler ); //////} //////[RT.HardwareExceptionHandler( RT.HardwareException.Interrupt )] //////[RT.ExportedMethod] //////private static void Zelig_Exception_CAN0_Rx_Warning_IRQHandler( ) //////{ ////// ARMv7.ProcessorARMv7M.ExclusiveAccessExceptionHandler( CAN0_Rx_Warning_IRQHandler ); //////} //////[RT.HardwareExceptionHandler( RT.HardwareException.Interrupt )] //////[RT.ExportedMethod] //////private static void Zelig_Exception_CAN0_Wake_Up_IRQHandler( ) //////{ ////// ARMv7.ProcessorARMv7M.ExclusiveAccessExceptionHandler( CAN0_Wake_Up_IRQHandler ); //////} //////[RT.HardwareExceptionHandler( RT.HardwareException.Interrupt )] //////[RT.ExportedMethod] //////private static void Zelig_Exception_SDHC_IRQHandler( ) //////{ ////// ARMv7.ProcessorARMv7M.ExclusiveAccessExceptionHandler( SDHC_IRQHandler ); //////} //[RT.HardwareExceptionHandler( RT.HardwareException.Interrupt )] //[RT.ExportedMethod] //private static void Zelig_Exception_ENET_1588_Timer_IRQHandler( ) //{ // //ARMv7.ProcessorARMv7M.ExclusiveAccessExceptionHandler( ENET_1588_Timer_IRQHandler ); // ENET_1588_Timer_IRQHandler( ); //} [RT.HardwareExceptionHandler( RT.HardwareException.Interrupt )] [RT.ExportedMethod] [RT.DisableNullChecks] private static void Zelig_Exception_ENET_Transmit_IRQHandler( ) { ARMv7.ProcessorARMv7MForLlvm.ExclusiveAccessExceptionHandler( s_ENET_Transmit_IRQHandler ); } [RT.HardwareExceptionHandler( RT.HardwareException.Interrupt )] [RT.ExportedMethod] [RT.DisableNullChecks] private static void Zelig_Exception_ENET_Receive_IRQHandler( ) { ARMv7.ProcessorARMv7MForLlvm.ExclusiveAccessExceptionHandler( s_ENET_Receive_IRQHandler ); } //[RT.HardwareExceptionHandler( RT.HardwareException.Interrupt )] //[RT.ExportedMethod] //private static void Zelig_Exception_ENET_Error_IRQHandler( ) //{ // //ARMv7.ProcessorARMv7M.ExclusiveAccessExceptionHandler( ENET_Error_IRQHandler ); // ENET_Error_IRQHandler( ); //} //[RT.HardwareExceptionHandler( RT.HardwareException.Interrupt )] //[RT.ExportedMethod] //private static void Zelig_Exception_DefaultISR( ) //{ // ARMv7.ProcessorARMv7M.ExclusiveAccessExceptionHandler( DefaultISR ); //} #endregion //--// //--// //--// #region Imported exception handlers // // Import all exception handler from native platform // [DllImport( "C" )] private static extern void NMI_Handler( ); [DllImport( "C" )] private static extern void HardFault_Handler( ); [DllImport( "C" )] private static extern void MemManage_Handler( ); [DllImport( "C" )] private static extern void BusFault_Handler( ); [DllImport( "C" )] private static extern void UsageFault_Handler( ); [DllImport( "C" )] private static extern void SVC_Handler( ); [DllImport( "C" )] private static extern void DebugMon_Handler( ); [DllImport( "C" )] private static extern void PendSV_Handler( ); [DllImport( "C" )] private static extern void SysTick_Handler( ); [DllImport( "C" )] private static extern void DMA0_IRQHandler( ); [DllImport( "C" )] private static extern void DMA1_IRQHandler( ); [DllImport( "C" )] private static extern void DMA2_IRQHandler( ); [DllImport( "C" )] private static extern void DMA3_IRQHandler( ); [DllImport( "C" )] private static extern void DMA4_IRQHandler( ); [DllImport( "C" )] private static extern void DMA5_IRQHandler( ); [DllImport( "C" )] private static extern void DMA6_IRQHandler( ); [DllImport( "C" )] private static extern void DMA7_IRQHandler( ); [DllImport( "C" )] private static extern void DMA8_IRQHandler( ); [DllImport( "C" )] private static extern void DMA9_IRQHandler( ); [DllImport( "C" )] private static extern void DMA10_IRQHandler( ); [DllImport( "C" )] private static extern void DMA11_IRQHandler( ); [DllImport( "C" )] private static extern void DMA12_IRQHandler( ); [DllImport( "C" )] private static extern void DMA13_IRQHandler( ); [DllImport( "C" )] private static extern void DMA14_IRQHandler( ); [DllImport( "C" )] private static extern void DMA15_IRQHandler( ); [DllImport( "C" )] private static extern void DMA_Error_IRQHandler( ); [DllImport( "C" )] private static extern void MCM_IRQHandler( ); [DllImport( "C" )] private static extern void FTFE_IRQHandler( ); [DllImport( "C" )] private static extern void Read_Collision_IRQHandler( ); [DllImport( "C" )] private static extern void LVD_LVW_IRQHandler( ); [DllImport( "C" )] private static extern void LLW_IRQHandler( ); [DllImport( "C" )] private static extern void Watchdog_IRQHandler( ); [DllImport( "C" )] private static extern void RNG_IRQHandler( ); [DllImport( "C" )] private static extern void I2C0_IRQHandler( ); [DllImport( "C" )] private static extern void I2C1_IRQHandler( ); [DllImport( "C" )] private static extern void SPI0_IRQHandler( ); [DllImport( "C" )] private static extern void SPI1_IRQHandler( ); [DllImport( "C" )] private static extern void I2S0_Tx_IRQHandler( ); [DllImport( "C" )] private static extern void I2S0_Rx_IRQHandler( ); [DllImport( "C" )] private static extern void UART0_LON_IRQHandler( ); [DllImport( "C" )] private static extern void UART0_RX_TX_IRQHandler( ); [DllImport( "C" )] private static extern void UART0_ERR_IRQHandler( ); [DllImport( "C" )] private static extern void UART1_RX_TX_IRQHandler( ); [DllImport( "C" )] private static extern void UART1_ERR_IRQHandler( ); [DllImport( "C" )] private static extern void UART2_RX_TX_IRQHandler( ); [DllImport( "C" )] private static extern void UART2_ERR_IRQHandler( ); [DllImport( "C" )] private static extern void UART3_RX_TX_IRQHandler( ); [DllImport( "C" )] private static extern void UART3_ERR_IRQHandler( ); [DllImport( "C" )] private static extern void ADC0_IRQHandler( ); [DllImport( "C" )] private static extern void CMP0_IRQHandler( ); [DllImport( "C" )] private static extern void CMP1_IRQHandler( ); [DllImport( "C" )] private static extern void FTM0_IRQHandler( ); [DllImport( "C" )] private static extern void FTM1_IRQHandler( ); [DllImport( "C" )] private static extern void FTM2_IRQHandler( ); [DllImport( "C" )] private static extern void CMT_IRQHandler( ); [DllImport( "C" )] private static extern void RTC_IRQHandler( ); [DllImport( "C" )] private static extern void RTC_Seconds_IRQHandler( ); [DllImport( "C" )] private static extern void PIT0_IRQHandler( ); [DllImport( "C" )] private static extern void PIT1_IRQHandler( ); [DllImport( "C" )] private static extern void PIT2_IRQHandler( ); [DllImport( "C" )] private static extern void PIT3_IRQHandler( ); [DllImport( "C" )] private static extern void PDB0_IRQHandler( ); [DllImport( "C" )] private static extern void USB0_IRQHandler( ); [DllImport( "C" )] private static extern void USBDCD_IRQHandler( ); [DllImport( "C" )] private static extern void Reserved71_IRQHandler( ); [DllImport( "C" )] private static extern void DAC0_IRQHandler( ); [DllImport( "C" )] private static extern void MCG_IRQHandler( ); [DllImport( "C" )] private static extern void LPTimer_IRQHandler( ); [DllImport( "C" )] private static extern void PORTA_IRQHandler( ); [DllImport( "C" )] private static extern void PORTB_IRQHandler( ); [DllImport( "C" )] private static extern void PORTC_IRQHandler( ); [DllImport( "C" )] private static extern void PORTD_IRQHandler( ); [DllImport( "C" )] private static extern void PORTE_IRQHandler( ); [DllImport( "C" )] private static extern void SWI_IRQHandler( ); [DllImport( "C" )] private static extern void SPI2_IRQHandler( ); [DllImport( "C" )] private static extern void UART4_RX_TX_IRQHandler( ); [DllImport( "C" )] private static extern void UART4_ERR_IRQHandler( ); [DllImport( "C" )] private static extern void UART5_RX_TX_IRQHandler( ); [DllImport( "C" )] private static extern void UART5_ERR_IRQHandler( ); [DllImport( "C" )] private static extern void CMP2_IRQHandler( ); [DllImport( "C" )] private static extern void FTM3_IRQHandler( ); [DllImport( "C" )] private static extern void DAC1_IRQHandler( ); [DllImport( "C" )] private static extern void ADC1_IRQHandler( ); [DllImport( "C" )] private static extern void I2C2_IRQHandler( ); [DllImport( "C" )] private static extern void CAN0_ORed_Message_buffer_IRQHandler( ); [DllImport( "C" )] private static extern void CAN0_Bus_Off_IRQHandler( ); [DllImport( "C" )] private static extern void CAN0_Error_IRQHandler( ); [DllImport( "C" )] private static extern void CAN0_Tx_Warning_IRQHandler( ); [DllImport( "C" )] private static extern void CAN0_Rx_Warning_IRQHandler( ); [DllImport( "C" )] private static extern void CAN0_Wake_Up_IRQHandler( ); [DllImport( "C" )] private static extern void SDHC_IRQHandler( ); [DllImport( "C" )] private static extern void ENET_1588_Timer_IRQHandler( ); [DllImport( "C" )] private static extern void ENET_Transmit_IRQHandler( ); [DllImport( "C" )] private static extern void ENET_Receive_IRQHandler( ); [DllImport( "C" )] private static extern void ENET_Error_IRQHandler( ); [DllImport( "C" )] private static extern void DefaultISR( ); #endregion } } ================================================ FILE: Zelig/BoardConfigurations/K64F/Board/K64F.csproj ================================================  Debug AnyCPU 9.0.21022 2.0 {1705887B-E636-4FA3-AE40-2D431AF1511C} Library Properties Microsoft.Llilum.K64F K64F v4.5 512 true $(LlilumBuildRoot)\Target\bin\$(Configuration)\ $(LlilumBuildRoot)\Target\bin\$(Configuration)\ $(LlilumBuildRoot)\Target\obj\$(MSBuildProjectName)\ $(LLILUM_SDK)\ZeligBuild\Target\bin\$(Configuration)\ $(LLILUM_SDK)\ZeligBuild\Target\bin\$(Configuration)\ $(LLILUM_SDK)\ZeligBuild\Target\obj\$(MSBuildProjectName)\ true full false DEBUG;TRACE prompt 4 true true true AllRules.ruleset AnyCPU false pdbonly true TRACE prompt 4 true true true AllRules.ruleset AnyCPU false {b8fe271a-cd41-435e-8766-4db7609c1007} CortexM0OnCMSIS-Core {89ebdbb0-c81f-4611-b719-b385df215f8d} CortexM0OnMBED {0b37e5ba-4839-4ec4-9e36-a96bcbea2400} CortexM3OnCMSIS-Core {c3bfafad-a6c6-471d-a059-b3cb7e57a4ab} ModelForCortexM0 {a30eb003-94f8-4a85-8da1-006f6810a7a4} ModelForCortexM3 {e4c618af-1785-472e-a070-8068e20582eb} ModelForCortexM {186f31a3-ef89-4a25-b2d5-20070606aa01} ProductConfiguration {0c522c6a-0f77-4af8-ad78-5b2415c98c51} CortexM3OnMBED {7fb3f581-742d-4e12-a36a-be172c574ab0} CortexM4OnCMSIS-Core {65c8eda6-ac24-4e18-a5b5-216e0f2c3906} CortexM4OnMBED {ca8a6d38-528b-4faa-89b6-8fa9178de55d} ModelForCortexM4 {186f31a3-ef89-4a25-b2d5-20070601aa01} CommonPC {186f31a3-ef89-4a25-b2d5-20061218aa01} Common {186f31a3-ef89-4a25-b2d5-20060509aa01} Kernel {20dc2cf5-8eed-4231-9743-6bab96be465c} LlilumOSAbstraction {186f31a3-ef89-4a25-b2d5-20060720aa01} TypeSystem {186F31A3-EF89-4A25-B2D5-20060501AA01} mscorlib False False $(LLILUM_SDK)\ZeligBuild\Target\bin\$(Configuration)\Microsoft.CortexM3OnCMSISCore.dll False $(LLILUM_SDK)\ZeligBuild\Target\bin\$(Configuration)\Microsoft.CortexM3OnMBED.dll False $(LLILUM_SDK)\ZeligBuild\Target\bin\$(Configuration)\Microsoft.DeviceModels.ModelForCortexM3.dll False $(LLILUM_SDK)\ZeligBuild\Target\bin\$(Configuration)\Microsoft.CortexM4OnCMSISCore.dll False $(LLILUM_SDK)\ZeligBuild\Target\bin\$(Configuration)\Microsoft.CortexM4OnMBED.dll False $(LLILUM_SDK)\ZeligBuild\Target\bin\$(Configuration)\Microsoft.DeviceModels.ModelForCortexM4.dll False $(LLILUM_SDK)\ZeligBuild\Target\bin\$(Configuration)\Microsoft.Zelig.LlilumOSAbstraction.dll False $(LLILUM_SDK)\ZeligBuild\Host\bin\$(Configuration)\Microsoft.Zelig.ProductConfiguration.dll False $(LLILUM_SDK)\ZeligBuild\Host\bin\$(Configuration)\Microsoft.Zelig.Runtime.dll False $(LLILUM_SDK)\ZeligBuild\Host\bin\$(Configuration)\Microsoft.Zelig.Runtime.Common.dll False $(LLILUM_SDK)\ZeligBuild\Host\bin\$(Configuration)\Microsoft.Zelig.Runtime.CommonPC.dll False $(LLILUM_SDK)\ZeligBuild\Host\bin\$(Configuration)\Microsoft.Zelig.Runtime.TypeSystem.dll $(LLILUM_SDK)\ZeligBuild\Target\bin\$(Configuration)\mscorlib.dll ================================================ FILE: Zelig/BoardConfigurations/K64F/Board/Properties/AssemblyInfo.cs ================================================ using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; // General Information about an assembly is controlled through the following // set of attributes. Change these attribute values to modify the information // associated with an assembly. [assembly: AssemblyTitle("K64F")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("K64F")] [assembly: AssemblyCopyright("Copyright © 2015")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible(false)] // The following GUID is for the ID of the typelib if this project is exposed to COM [assembly: Guid("1705887b-e636-4fa3-ae40-2d431af1511c")] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Build and Revision Numbers // by using the '*' as shown below: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("1.0.0.0")] [assembly: AssemblyFileVersion("1.0.0.0")] ================================================ FILE: Zelig/BoardConfigurations/K64F/Board/SystemServices/GarbageCollectionManager.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // namespace Microsoft.Llilum.K64F { using Chipset = Microsoft.CortexM4OnMBED; public sealed class GarbageCollectionManager : Chipset.GarbageCollectionManager { } } ================================================ FILE: Zelig/BoardConfigurations/K64F/Board/SystemServices/ThreadManager.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // namespace Microsoft.Llilum.K64F { using Chipset = Microsoft.CortexM4OnMBED; using LLOS = Zelig.LlilumOSAbstraction.API; public sealed class ThreadManager : Chipset.ThreadManager { private const int DefaultStackSizeK64F = 4 * 1024; //--// // // Helper Methods // public override int DefaultStackSize { get { uint stackSize = LLOS.RuntimeMemory.LLOS_MEMORY_GetDefaultManagedStackSize(); if(stackSize == 0) { return DefaultStackSizeK64F; } return (int)stackSize; } } } } ================================================ FILE: Zelig/BoardConfigurations/K64F/Board/SystemServices/TimerPool.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // namespace Microsoft.Llilum.K64F { using Chipset = Microsoft.CortexM4OnMBED; public sealed class TimerPool : Chipset.TimerPool { } } ================================================ FILE: Zelig/BoardConfigurations/K64F/Configuration/Configuration.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // namespace Microsoft.Llilum.BoardConfigurations { using Microsoft.Zelig.Runtime; using Microsoft.Zelig.Configuration.Environment; [DisplayName("K64F")] public sealed class K64FSoC : ProcessorCategory { [DependsOn(typeof(K64FSoC))] [DisplayName("Internal 256KB Static RAM")] [Defaults ( "BaseAddress" , 0x1FFF0000U )] [Defaults ( "SizeInBytes" , 256 * 1024 )] [Defaults ( "WordSize" , 32 )] [Defaults ( "WaitStates" , 0 )] [EnumDefaults( "Characteristics", MemoryAttributes.RAM | MemoryAttributes.RandomAccessMemory | MemoryAttributes.InternalMemory | MemoryAttributes.ConfiguredAtEntryPoint )] public sealed class InternalRAM256KB : RamMemoryCategory { } [DependsOn( typeof( K64FSoC ) )] [DisplayName( "Internal 512KB FLASH" )] [Defaults( "BaseAddress", 0x00000000 )] [Defaults( "SizeInBytes", 1024 * 1024 )] [Defaults( "WordSize" , 32 )] [Defaults( "WaitStates" , 0 )] [EnumDefaults( "Characteristics", MemoryAttributes.FLASH | MemoryAttributes.RandomAccessMemory | MemoryAttributes.InternalMemory | MemoryAttributes.ConfiguredAtEntryPoint )] public sealed class InternalFlash1024KB : FlashMemoryCategory { } } //--// //--// //--// [DisplayName( "Memory Map for K64F" )] public sealed class K64FMemoryMap : MemoryMapCategory { [MergeEnumDefaults( "Characteristics", MemoryAttributes.InternalMemory | MemoryAttributes.RandomAccessMemory | MemoryAttributes.ConfiguredAtEntryPoint )] [MemorySection( MemoryUsage.Stack | MemoryUsage.Heap | MemoryUsage.DataRW | MemoryUsage.Code )] [AllowedOptions( typeof( K64FSoC.InternalRAM256KB ) )] [Defaults( "BaseAddress", 0x1FFF0000U )] public RamMemoryCategory InternalRamChip; [MergeEnumDefaults( "Characteristics", MemoryAttributes.InternalMemory | MemoryAttributes.RandomAccessMemory | MemoryAttributes.ConfiguredAtEntryPoint | MemoryAttributes.LoadedAtEntrypoint )] [MemorySection( MemoryUsage.Bootstrap | MemoryUsage.Code | MemoryUsage.DataRO | MemoryUsage.VectorsTable | MemoryUsage.Relocation )] [AllowedOptions( typeof( K64FSoC.InternalFlash1024KB ) )] [Defaults( "BaseAddress", 0x00000000U )] public FlashMemoryCategory InternalFlashChip; } //--// //--// //--// [DisplayName("K64F MBED")] public sealed class K64F : ProductCategory { [AllowedOptions(typeof(K64FSoC))] [Defaults("CoreClockFrequency" , 120000000UL)] [Defaults("RealTimeClockFrequency", 1000000UL )] [Defaults("DefaultThreadPoolThreads", 3)] [Defaults("DefaultTimerPoolThreads" , 2)] public K64FSoC Processor; //--// [AllowedOptions( typeof( K64FSoC.InternalRAM256KB ) )] [Defaults( "BaseAddress", 0x1FFF0000U )] public RamMemoryCategory InternalRam; [AllowedOptions( typeof( K64FSoC.InternalFlash1024KB ) )] [Defaults( "BaseAddress", 0x00000000U )] public FlashMemoryCategory InternalFlashChip; } //--// //--// //--// [DisplayName("LLVM Compilation for K64F")] [Defaults( "Platform", typeof( Microsoft.Zelig.Configuration.Environment.Abstractions.Architectures.LlvmForArmV7M_VFP ) )] [Defaults( "CallingConvention", typeof( Microsoft.Zelig.Configuration.Environment.Abstractions.Architectures.LlvmForArmV7MCallingConvention ) )] [Defaults("Product", typeof(K64F))] [Defaults("MemoryMap", typeof(K64FMemoryMap))] public sealed class K64FMBEDCompilationSetup : CompilationSetupCategory { } } ================================================ FILE: Zelig/BoardConfigurations/K64F/Configuration/K64F.FrontEndConfig ================================================ ### ### NOTE: This file can be used in the SDK AS-IS, or remove all instances of #~# to use as manual input for the FrontEnd project ### ### ### Location of the Zelig assemblies. ### #~#-HostAssemblyDir ..\..\..\..\ZeligBuild\Host\bin\Debug #~#-DeviceAssemblyDir ..\..\..\..\ZeligBuild\Target\bin\Debug -Architecture cortex-m4 #~#-CompilationSetupPath ..\..\..\..\ZeligBuild\Host\bin\Debug\Microsoft.Llilum.BoardConfigurations.K64F.dll -CompilationSetup Microsoft.Llilum.BoardConfigurations.K64FMBEDCompilationSetup ### ### We need to include this assembly to get the right drivers. ### -Reference Microsoft.CortexM4OnMBED -Reference Microsoft.CortexM4OnCMSISCore -Reference Microsoft.DeviceModels.ModelForCortexM4 -Reference K64F -Reference Microsoft.Zelig.LlilumCMSIS-RTOS ### ### Add compilation phases, in order ### #-CompilationPhaseDisabled ReduceNumberOfTemporaries #-CompilationPhaseDisabled TransformFinallyBlocksIntoTryBlocks #-CompilationPhaseDisabled ApplyClassExtensions #-CompilationPhaseDisabled PrepareImplementationOfInternalMethods #-CompilationPhaseDisabled CrossReferenceTypeSystem #-CompilationPhaseDisabled ApplyConfigurationSettings -CompilationPhaseDisabled ResourceManagerOptimizations #-CompilationPhaseDisabled HighLevelTransformations #-CompilationPhaseDisabled PropagateCompilationConstraints #-CompilationPhaseDisabled ComputeCallsClosure #-CompilationPhaseDisabled EstimateTypeSystemReduction #-CompilationPhaseDisabled CompleteImplementationOfInternalMethods #-CompilationPhaseDisabled ReduceTypeSystem -CompilationPhaseDisabled PrepareExternalMethods #-CompilationPhaseDisabled DetectNonImplementedInternalCalls #-CompilationPhaseDisabled OrderStaticConstructors #-CompilationPhaseDisabled LayoutTypes #-CompilationPhaseDisabled HighLevelToMidLevelConversion #-CompilationPhaseDisabled FromImplicitToExplicitExceptions #-CompilationPhaseDisabled ReferenceCountingGarbageCollection -CompilationPhaseDisabled MidLevelToLowLevelConversion -CompilationPhaseDisabled ConvertUnsupportedOperatorsToMethodCalls -CompilationPhaseDisabled ExpandAggregateTypes -CompilationPhaseDisabled SplitComplexOperators -CompilationPhaseDisabled FuseOperators #-CompilationPhaseDisabled Optimizations -CompilationPhaseDisabled ConvertToSSA -CompilationPhaseDisabled PrepareForRegisterAllocation -CompilationPhaseDisabled CollectRegisterAllocationConstraints -CompilationPhaseDisabled AllocateRegisters #-CompilationPhaseDisabled GenerateImage #-CompilationPhaseDisabled Done ### ### The program to compile. ### #~#..\..\..\..\ZeligBuild\Target\bin\Debug\Microsoft.Zelig.Test.mbed.Simple.exe ### ### Where to put the results. ### #~#-OutputName Microsoft.Zelig.Test.mbed.Simple #~#-OutputDir ..\..\..\..\LLVM2IR_results\mbed\simple ### ### Dumps and diagnostics ### #-DumpIRBeforePhase All #-DumpIR #-DumpIRpre #-DumpIRpost #-DumpIRXML #-DumpFlattenedCallGraph -DumpLLVMIR #-ReloadState #-DumpLLVMIR_TextRepresentation -MaxProcs 8 #~#-NoSDK -GenerateObj # examples of overriding opt.exe and llc arguments # the examples here are the same as the defaults but can be modified to suit a variety of test # scenarios and experimentations #-LlvmOptArgs "-verify-debug-info -verify-dom-info -verify-each -verify-loop-info -verify-regalloc -verify-region-info -march=thumb -mcpu=cortex-m3 -aa-eval -indvars -gvn -globaldce -adce -dce -tailcallopt -scalarrepl -mem2reg -ipconstprop -deadargelim -sccp -dce -ipsccp -dce -constmerge -scev-aa -targetlibinfo -irce -dse -dce -argpromotion -mem2reg -adce -mem2reg -globaldce -die -dce -dse" #-LlvmLlcArgs "-O2 -code-model=small -data-sections -relocation-model=pic -march=thumb -mcpu=cortex-m3 -filetype=obj -mtriple=thumbv7m-none-eabi" # While the compiler is pretty good at figuring out where the LLVM tools are from # current Environment variables or registry entires you can manually specify the # path to find the LLVM binaries. # note: Environment variabes (i.e %MY_VAR%) are supported and expanded as with all # options in the FrontendConfig files so you can specify a custom variable if needed #-LlvmBinPath c:\src\llvm\llvm-3.7.0.src\build\x64\Release\bin\ ================================================ FILE: Zelig/BoardConfigurations/K64F/Configuration/K64FConfiguration.csproj ================================================  Debug AnyCPU {9863D039-AB21-4710-960E-7303919552C6} Library Properties Microsoft.Llilum.BoardConfigurations Microsoft.Llilum.BoardConfigurations.K64F v4.5 512 true true full false $(LlilumBuildRoot)\Host\bin\$(Configuration)\ DEBUG;TRACE prompt 4 pdbonly true $(LlilumBuildRoot)\Host\bin\$(Configuration)\ TRACE prompt 4 {186f31a3-ef89-4a25-b2d5-20070606aa01} ProductConfiguration {186f31a3-ef89-4a25-b2d5-20061218aa01} Common {186F31A3-EF89-4A25-B2D5-20060501AA01} mscorlib False {186F31A3-EF89-4A25-B2D5-20070702AA01} system False $(LLILUM_SDK)\ZeligBuild\Host\bin\Debug\Microsoft.Zelig.ProductConfiguration.dll $(LLILUM_SDK)\ZeligBuild\Host\bin\Debug\Microsoft.Zelig.Runtime.Common.dll $(LLILUM_SDK)\ZeligBuild\Target\bin\Debug\mscorlib.dll $(LLILUM_SDK)\ZeligBuild\Target\bin\Debug\system.dll ================================================ FILE: Zelig/BoardConfigurations/K64F/Configuration/Properties/AssemblyInfo.cs ================================================ using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; // General Information about an assembly is controlled through the following // set of attributes. Change these attribute values to modify the information // associated with an assembly. [assembly: AssemblyTitle("Microsoft.Llilum.BoardConfigurations.K64F")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("Microsoft.Llilum.BoardConfigurations.K64F")] [assembly: AssemblyCopyright("Copyright © 2015")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible(false)] // The following GUID is for the ID of the typelib if this project is exposed to COM [assembly: Guid("9863d039-ab21-4710-960e-7303919552c6")] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Build and Revision Numbers // by using the '*' as shown below: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("1.0.0.0")] [assembly: AssemblyFileVersion("1.0.0.0")] ================================================ FILE: Zelig/BoardConfigurations/LPC1768/Board/HardwareModel/Board.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // namespace Microsoft.Llilum.LPC1768 { using System; using Chipset = Microsoft.CortexM3OnMBED; using ChipsetAbstration = Microsoft.DeviceModels.Chipset.CortexM3; public sealed class Board : Chipset.Board { // // Serial Ports // private static readonly string[] m_serialPorts = { "UART0", "UART1" }; public static readonly ChipsetAbstration.Board.SerialPortInfo UART0 = new ChipsetAbstration.Board.SerialPortInfo() { TxPin = (int)PinName.USBTX, RxPin = (int)PinName.USBRX, RtsPin = unchecked( (int)PinName.NC ) , CtsPin = unchecked( (int)PinName.NC ) , }; public static readonly ChipsetAbstration.Board.SerialPortInfo UART1 = new ChipsetAbstration.Board.SerialPortInfo() { TxPin = (int)PinName.p13 , RxPin = (int)PinName.p14 , RtsPin = unchecked( (int)PinName.NC ), CtsPin = unchecked( (int)PinName.NC ), }; //--// private static readonly int[] s_ledPins = new int[] { (int)LPC1768.PinName.LED1, (int)LPC1768.PinName.LED2, (int)LPC1768.PinName.LED3, (int)LPC1768.PinName.LED4, }; private static readonly int[] s_pwmPins = new int[] { (int)LPC1768.PinName.p21, }; //--// // // Gpio discovery // public override int PinCount { get { return 40; } } public override int PinToIndex( int pin ) { return pin - (int)PinName.P0_0; } public override int NCPin { get { return -1; } } public override int[] LedPins { get { return s_ledPins; } } public override int[] PwmPins { get { return s_pwmPins; } } // // Serial Ports // public override string[] GetSerialPorts() { return m_serialPorts; } public override ChipsetAbstration.Board.SerialPortInfo GetSerialPortInfo(string portName) { switch (portName) { case "UART0": return UART0; case "UART1": return UART1; default: return null; } } public override int GetSerialPortIRQ(string portName) { switch (portName) { case "UART0": return (int)IRQn.UART0_IRQn; case "UART1": return (int)IRQn.UART1_IRQn; default: throw new NotSupportedException(); } } //////public override void RemapSerialPortInterrupts( ) //////{ ////// Processor.RemapInterrupt( IRQn.UART0_ERR_IRQn ); ////// Processor.RemapInterrupt( IRQn.UART0_ERR_IRQn ); ////// Processor.RemapInterrupt( IRQn.UART1_ERR_IRQn ); ////// Processor.RemapInterrupt( IRQn.UART1_ERR_IRQn ); ////// Processor.RemapInterrupt( IRQn.UART3_ERR_IRQn ); ////// Processor.RemapInterrupt( IRQn.UART3_ERR_IRQn ); //////} // // System timer // public override int GetSystemTimerIRQ( ) { return (int)IRQn.TIMER3_IRQn; } } } ================================================ FILE: Zelig/BoardConfigurations/LPC1768/Board/HardwareModel/Device.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // namespace Microsoft.Llilum.LPC1768 { using RT = Microsoft.Zelig.Runtime; public sealed class Device : Microsoft.CortexM3OnMBED.Device { // TODO: When the compiler optimizations are complete, revisit this stack size since it is likely // it could be reduced. [RT.MemoryUsage(RT.MemoryUsage.Stack, ContentsUninitialized = true, AllocateFromHighAddress = true)] static readonly uint[] s_bootstrapStackLPC1768 = new uint[ 512 / sizeof( uint ) ]; public override uint[] BootstrapStack { get { return s_bootstrapStackLPC1768; } } } } ================================================ FILE: Zelig/BoardConfigurations/LPC1768/Board/HardwareModel/Drivers/ContextSwitchTimer.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // //#define TIMERS_SELF_TEST namespace Microsoft.Llilum.LPC1768.Drivers { using Chipset = Microsoft.DeviceModels.Chipset.CortexM3.Drivers; public sealed class ContextSwitchTimer : Chipset.ContextSwitchTimer { } } ================================================ FILE: Zelig/BoardConfigurations/LPC1768/Board/HardwareModel/Drivers/InterruptController.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // namespace Microsoft.Llilum.LPC1768.Drivers { using Chipset = Microsoft.CortexM3OnMBED.Drivers; public sealed class InterruptController : Chipset.InterruptController { } } ================================================ FILE: Zelig/BoardConfigurations/LPC1768/Board/HardwareModel/Drivers/SystemTimer.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // namespace Microsoft.Llilum.LPC1768.Drivers { using Chipset = Microsoft.CortexM3OnMBED.Drivers; public sealed class SystemTimer : Chipset.SystemTimer { } } ================================================ FILE: Zelig/BoardConfigurations/LPC1768/Board/HardwareModel/GPIO.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // namespace Microsoft.Llilum.LPC1768 { //--// public enum PinName : uint { P0_0 = 0x2009C000, //LPC_GPIO_BASE P0_1, P0_2, P0_3, P0_4, P0_5, P0_6, P0_7, P0_8, P0_9, P0_10, P0_11, P0_12, P0_13, P0_14, P0_15, P0_16, P0_17, P0_18, P0_19, P0_20, P0_21, P0_22, P0_23, P0_24, P0_25, P0_26, P0_27, P0_28, P0_29, P0_30, P0_31, P1_0, P1_1, P1_2, P1_3, P1_4, P1_5, P1_6, P1_7, P1_8, P1_9, P1_10, P1_11, P1_12, P1_13, P1_14, P1_15, P1_16, P1_17, P1_18, P1_19, P1_20, P1_21, P1_22, P1_23, P1_24, P1_25, P1_26, P1_27, P1_28, P1_29, P1_30, P1_31, P2_0, P2_1, P2_2, P2_3, P2_4, P2_5, P2_6, P2_7, P2_8, P2_9, P2_10, P2_11, P2_12, P2_13, P2_14, P2_15, P2_16, P2_17, P2_18, P2_19, P2_20, P2_21, P2_22, P2_23, P2_24, P2_25, P2_26, P2_27, P2_28, P2_29, P2_30, P2_31, P3_0, P3_1, P3_2, P3_3, P3_4, P3_5, P3_6, P3_7, P3_8, P3_9, P3_10, P3_11, P3_12, P3_13, P3_14, P3_15, P3_16, P3_17, P3_18, P3_19, P3_20, P3_21, P3_22, P3_23, P3_24, P3_25, P3_26, P3_27, P3_28, P3_29, P3_30, P3_31, P4_0, P4_1, P4_2, P4_3, P4_4, P4_5, P4_6, P4_7, P4_8, P4_9, P4_10, P4_11, P4_12, P4_13, P4_14, P4_15, P4_16, P4_17, P4_18, P4_19, P4_20, P4_21, P4_22, P4_23, P4_24, P4_25, P4_26, P4_27, P4_28, P4_29, P4_30, P4_31, // mbed DIP Pin Names p5 = P0_9, p6 = P0_8, p7 = P0_7, p8 = P0_6, p9 = P0_0, p10 = P0_1, p11 = P0_18, p12 = P0_17, p13 = P0_15, p14 = P0_16, p15 = P0_23, p16 = P0_24, p17 = P0_25, p18 = P0_26, p19 = P1_30, p20 = P1_31, p21 = P2_5, p22 = P2_4, p23 = P2_3, p24 = P2_2, p25 = P2_1, p26 = P2_0, p27 = P0_11, p28 = P0_10, p29 = P0_5, p30 = P0_4, LED1 = P1_18, LED2 = P1_20, LED3 = P1_21, LED4 = P1_23, USBTX = P0_2, USBRX = P0_3, // Arch Pro Pin Names D0 = P4_29, D1 = P4_28, D2 = P0_4, D3 = P0_5, D4 = P2_2, D5 = P2_3, D6 = P2_4, D7 = P2_5, D8 = P0_0, D9 = P0_1, D10 = P0_6, D11 = P0_9, D12 = P0_8, D13 = P0_7, D14 = P0_27, D15 = P0_28, A0 = P0_23, A1 = P0_24, A2 = P0_25, A3 = P0_26, A4 = P1_30, A5 = P1_31, I2C_SCL = D15, I2C_SDA = D14, // Not connected NC = 0xFFFFFFFF } } ================================================ FILE: Zelig/BoardConfigurations/LPC1768/Board/HardwareModel/HardwareProviders/GpioProvider.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // namespace Microsoft.Llilum.LPC1768.HardwareModel.HardwareProviders { using Chipset = CortexM3OnMBED; public sealed class GpioProvider : Chipset.HardwareModel.GpioProvider { public override int GetGpioPinIRQNumber(int pinNumber) { // // All GPIO interrupts use EINT3 // return (int)IRQn.EINT3_IRQn; } } } ================================================ FILE: Zelig/BoardConfigurations/LPC1768/Board/HardwareModel/HardwareProviders/I2cProvider.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // namespace Microsoft.Llilum.LPC1768 { using System; using Microsoft.Zelig.Runtime; using Chipset = Microsoft.CortexM3OnMBED; using ChipsetAbstration = Microsoft.DeviceModels.Chipset.CortexM3; public sealed class I2cProvider : Chipset.HardwareModel.I2cProvider { public static readonly I2cChannelInfo I2C0 = new I2cChannelInfo() { SdaPin = (int)PinName.p9, SclPin = (int)PinName.p10, PortIndex = 0, }; public static readonly I2cChannelInfo I2C1 = new I2cChannelInfo() { SdaPin = (int)PinName.p28, SclPin = (int)PinName.p27, PortIndex = 1, }; public override I2cChannelInfo GetI2cChannelInfo(int id) { switch (id) { case 0: return I2C0; case 1: return I2C1; default: return null; } } } } ================================================ FILE: Zelig/BoardConfigurations/LPC1768/Board/HardwareModel/HardwareProviders/SpiProvider.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // namespace Microsoft.Llilum.LPC1768 { using System; using Microsoft.Zelig.Runtime; using Chipset = Microsoft.CortexM3OnMBED; using ChipsetAbstration = Microsoft.DeviceModels.Chipset.CortexM3; public sealed class SpiProvider : Chipset.HardwareModel.SpiProvider { public static readonly SpiChannelInfo SPI0 = new SpiChannelInfo() { Mosi = (int)PinName.p5, Miso = (int)PinName.p6, Sclk = (int)PinName.p7, DefaultChipSelect = (int)PinName.p8, SetupTime = 10, HoldTime = 10, ActiveLow = true, }; public static readonly SpiChannelInfo SPI1 = new SpiChannelInfo() { Mosi = (int)PinName.p11, Miso = (int)PinName.p12, Sclk = (int)PinName.p13, DefaultChipSelect = (int)PinName.p14, SetupTime = 10, HoldTime = 10, ActiveLow = true, }; public override bool SpiBusySupported { get { return true; } } public override SpiChannelInfo GetSpiChannelInfo(int id) { switch (id) { case 0: return SPI0; case 1: return SPI1; default: return null; } } } } ================================================ FILE: Zelig/BoardConfigurations/LPC1768/Board/HardwareModel/HardwareProvidersUwp/AdcProviderUwp.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // namespace Microsoft.Llilum.LPC1768 { using System; using Microsoft.Zelig.Runtime; using Chipset = Microsoft.CortexM3OnMBED; using ChipsetAbstration = Microsoft.DeviceModels.Chipset.CortexM3; public sealed class AdcProviderUwp : Microsoft.Zelig.Runtime.AdcProviderUwp { private static readonly AdcChannelInfoUwp m_adcInfo = new AdcChannelInfoUwp() { MaxValue = UInt16.MaxValue, MinValue = 0, ResolutionInBits = 16, AdcPinNumbers = new int[] {(int)PinName.A0, (int)PinName.A1, (int)PinName.A2, (int)PinName.A3, (int)PinName.A4, (int)PinName.A5 } }; public override AdcChannelInfoUwp GetAdcChannelInfo() { return m_adcInfo; } } } ================================================ FILE: Zelig/BoardConfigurations/LPC1768/Board/HardwareModel/HardwareProvidersUwp/I2cProviderUwp.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // namespace Microsoft.Llilum.LPC1768 { using System; using Microsoft.Zelig.Runtime; using Chipset = Microsoft.CortexM3OnMBED; using ChipsetAbstration = Microsoft.DeviceModels.Chipset.CortexM3; public sealed class I2cProviderUwp : Microsoft.Zelig.Runtime.I2cProviderUwp { private static string[] m_i2cChannels = { "I2C0", "I2C1" }; public override I2cChannelInfo GetI2cChannelInfo(string busId) { switch (busId) { case "I2C0": return I2cProvider.I2C0; case "I2C1": return I2cProvider.I2C1; default: return null; } } public override string[] GetI2cChannels() { return m_i2cChannels; } } } ================================================ FILE: Zelig/BoardConfigurations/LPC1768/Board/HardwareModel/HardwareProvidersUwp/PwmProviderUwp.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // namespace Microsoft.Llilum.LPC1768 { using System; using Microsoft.Zelig.Runtime; using Chipset = Microsoft.CortexM3OnMBED; using ChipsetAbstration = Microsoft.DeviceModels.Chipset.CortexM3; public sealed class PwmProviderUwp : Microsoft.Zelig.Runtime.PwmProviderUwp { private static readonly PwmChannelInfoUwp m_pwmInfo = new PwmChannelInfoUwp() { MaxFrequency = 1000000, MinFrequency = 0, PwmPinNumbers = new int[] { (int)PinName.p21, (int)PinName.p22, (int)PinName.p23, (int)PinName.p24, (int)PinName.p25, (int)PinName.p26, } }; public override PwmChannelInfoUwp GetPwmChannelInfo() { return m_pwmInfo; } } } ================================================ FILE: Zelig/BoardConfigurations/LPC1768/Board/HardwareModel/HardwareProvidersUwp/SpiProviderUwp.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // namespace Microsoft.Llilum.LPC1768 { using System; using Microsoft.Zelig.Runtime; using Chipset = Microsoft.CortexM3OnMBED; using ChipsetAbstration = Microsoft.DeviceModels.Chipset.CortexM3; public sealed class SpiProviderUwp : Microsoft.Zelig.Runtime.SpiProviderUwp { private static readonly string[] m_spiDevices = { "SPI0", "SPI1", "SPI0WriteOnly" }; public static readonly SpiChannelInfo SPI0WriteOnlyChannelInfo = new SpiChannelInfo() { Mosi = SpiProvider.SPI0.Mosi, Miso = unchecked((int)PinName.NC), Sclk = SpiProvider.SPI0.Sclk, DefaultChipSelect = SpiProvider.SPI0.DefaultChipSelect, SetupTime = SpiProvider.SPI0.SetupTime, HoldTime = SpiProvider.SPI0.HoldTime, ActiveLow = SpiProvider.SPI0.ActiveLow, }; public static readonly SpiChannelInfoUwp SPI0 = new SpiChannelInfoUwp() { ChipSelectLines = 1, MinFreq = 1000, MaxFreq = 30000000, Supports16 = true, ChannelInfoKernel = SpiProvider.SPI0, }; public static readonly SpiChannelInfoUwp SPI0WriteOnly = new SpiChannelInfoUwp() { ChipSelectLines = 1, MinFreq = 1000, MaxFreq = 30000000, Supports16 = true, ChannelInfoKernel = SPI0WriteOnlyChannelInfo, }; public static readonly SpiChannelInfoUwp SPI1 = new SpiChannelInfoUwp() { ChipSelectLines = 1, MinFreq = 1000, MaxFreq = 30000000, Supports16 = true, ChannelInfoKernel = SpiProvider.SPI1, }; public override SpiChannelInfoUwp GetSpiChannelInfo(string busId) { switch (busId) { case "SPI0": return SPI0; case "SPI1": return SPI1; case "SPI0WriteOnly": return SPI0WriteOnly; default: return null; } } public override string[] GetSpiChannels() { return m_spiDevices; } } } ================================================ FILE: Zelig/BoardConfigurations/LPC1768/Board/HardwareModel/NVIC.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // namespace Microsoft.Llilum.LPC1768 { enum IRQn { /****** Cortex-M3 Processor Exceptions Numbers ***************************************************/ NonMaskableInt_IRQn = -14, /*!< 2 Non Maskable Interrupt */ MemoryManagement_IRQn = -12, /*!< 4 Cortex-M3 Memory Management Interrupt */ BusFault_IRQn = -11, /*!< 5 Cortex-M3 Bus Fault Interrupt */ UsageFault_IRQn = -10, /*!< 6 Cortex-M3 Usage Fault Interrupt */ SVCall_IRQn = -5, /*!< 11 Cortex-M3 SV Call Interrupt */ DebugMonitor_IRQn = -4, /*!< 12 Cortex-M3 Debug Monitor Interrupt */ PendSV_IRQn = -2, /*!< 14 Cortex-M3 Pend SV Interrupt */ SysTick_IRQn = -1, /*!< 15 Cortex-M3 System Tick Interrupt */ /****** LPC17xx Specific Interrupt Numbers *******************************************************/ WDT_IRQn = 0, /*!< Watchdog Timer Interrupt */ TIMER0_IRQn = 1, /*!< Timer0 Interrupt */ TIMER1_IRQn = 2, /*!< Timer1 Interrupt */ TIMER2_IRQn = 3, /*!< Timer2 Interrupt */ TIMER3_IRQn = 4, /*!< Timer3 Interrupt */ UART0_IRQn = 5, /*!< UART0 Interrupt */ UART1_IRQn = 6, /*!< UART1 Interrupt */ UART2_IRQn = 7, /*!< UART2 Interrupt */ UART3_IRQn = 8, /*!< UART3 Interrupt */ PWM1_IRQn = 9, /*!< PWM1 Interrupt */ I2C0_IRQn = 10, /*!< I2C0 Interrupt */ I2C1_IRQn = 11, /*!< I2C1 Interrupt */ I2C2_IRQn = 12, /*!< I2C2 Interrupt */ SPI_IRQn = 13, /*!< SPI Interrupt */ SSP0_IRQn = 14, /*!< SSP0 Interrupt */ SSP1_IRQn = 15, /*!< SSP1 Interrupt */ PLL0_IRQn = 16, /*!< PLL0 Lock (Main PLL) Interrupt */ RTC_IRQn = 17, /*!< Real Time Clock Interrupt */ EINT0_IRQn = 18, /*!< External Interrupt 0 Interrupt */ EINT1_IRQn = 19, /*!< External Interrupt 1 Interrupt */ EINT2_IRQn = 20, /*!< External Interrupt 2 Interrupt */ EINT3_IRQn = 21, /*!< External Interrupt 3 Interrupt */ ADC_IRQn = 22, /*!< A/D Converter Interrupt */ BOD_IRQn = 23, /*!< Brown-Out Detect Interrupt */ USB_IRQn = 24, /*!< USB Interrupt */ CAN_IRQn = 25, /*!< CAN Interrupt */ DMA_IRQn = 26, /*!< General Purpose DMA Interrupt */ I2S_IRQn = 27, /*!< I2S Interrupt */ ENET_IRQn = 28, /*!< Ethernet Interrupt */ RIT_IRQn = 29, /*!< Repetitive Interrupt Timer Interrupt */ MCPWM_IRQn = 30, /*!< Motor Control PWM Interrupt */ QEI_IRQn = 31, /*!< Quadrature Encoder Interface Interrupt */ PLL1_IRQn = 32, /*!< PLL1 Lock (USB PLL) Interrupt */ USBActivity_IRQn = 33, /* USB Activity interrupt */ CANActivity_IRQn = 34, /* CAN Activity interrupt */ LAST = 35, } } ================================================ FILE: Zelig/BoardConfigurations/LPC1768/Board/HardwareModel/Peripherals.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // namespace Microsoft.Llilum.LPC1768 { using RT = Microsoft.Zelig.Runtime; using Chipset = Microsoft.CortexM3OnMBED; using CMSIS = Microsoft.DeviceModels.Chipset.CortexM; public sealed class Peripherals : Chipset.Peripherals { public override void Initialize() { base.Initialize( ); // // Peripherals exceptions all have same priority // for(int i = 0; i < (int)IRQn.LAST; ++i) { CMSIS.NVIC.SetPriority( i , RT.TargetPlatform.ARMv7.ProcessorARMv7M.c_Priority__GenericPeripherals ); } } } } ================================================ FILE: Zelig/BoardConfigurations/LPC1768/Board/HardwareModel/Processor.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // namespace Microsoft.Llilum.LPC1768 { using RT = Microsoft.Zelig.Runtime; using ChipsetModel = Microsoft.CortexM3OnMBED; [RT.ProductFilter("Microsoft.Llilum.BoardConfigurations.LPC1768")] public sealed class Processor : Microsoft.CortexM3OnMBED.Processor { public new class Context : ChipsetModel.Processor.Context { public Context(RT.ThreadImpl owner) : base(owner) { } } // // Helper methods // [RT.Inline] public override RT.Processor.Context AllocateProcessorContext(RT.ThreadImpl owner) { return new Context(owner); } } } ================================================ FILE: Zelig/BoardConfigurations/LPC1768/Board/LPC1768.csproj ================================================  Debug AnyCPU 9.0.21022 2.0 {CEE4D575-4B4B-42B0-B2F1-CC7198CB7306} Library Properties Microsoft.Llilum.LPC1768 LPC1768 v4.5 512 true $(LlilumBuildRoot)\Target\bin\$(Configuration)\ $(LlilumBuildRoot)\Target\bin\$(Configuration)\ $(LlilumBuildRoot)\Target\obj\$(MSBuildProjectName)\ $(LLILUM_SDK)\ZeligBuild\Target\bin\$(Configuration)\ $(LLILUM_SDK)\ZeligBuild\Target\bin\$(Configuration)\ $(LLILUM_SDK)\ZeligBuild\Target\obj\$(MSBuildProjectName)\ true full false DEBUG;TRACE prompt 4 true true true AllRules.ruleset AnyCPU false pdbonly true TRACE prompt 4 true true true AllRules.ruleset AnyCPU false {b8fe271a-cd41-435e-8766-4db7609c1007} CortexM0OnCMSIS-Core {89ebdbb0-c81f-4611-b719-b385df215f8d} CortexM0OnMBED {c3bfafad-a6c6-471d-a059-b3cb7e57a4ab} ModelForCortexM0 {a30eb003-94f8-4a85-8da1-006f6810a7a4} ModelForCortexM3 {e4c618af-1785-472e-a070-8068e20582eb} ModelForCortexM {186f31a3-ef89-4a25-b2d5-20070606aa01} ProductConfiguration {0b37e5ba-4839-4ec4-9e36-a96bcbea2400} CortexM3OnCMSIS-Core {0c522c6a-0f77-4af8-ad78-5b2415c98c51} CortexM3OnMBED {186f31a3-ef89-4a25-b2d5-20070601aa01} CommonPC {186f31a3-ef89-4a25-b2d5-20061218aa01} Common {186f31a3-ef89-4a25-b2d5-20060509aa01} Kernel {20dc2cf5-8eed-4231-9743-6bab96be465c} LlilumOSAbstraction {186f31a3-ef89-4a25-b2d5-20060720aa01} TypeSystem {186F31A3-EF89-4A25-B2D5-20060501AA01} mscorlib False False $(LLILUM_SDK)\ZeligBuild\Target\bin\$(Configuration)\Microsoft.CortexM3OnCMSISCore.dll False $(LLILUM_SDK)\ZeligBuild\Target\bin\$(Configuration)\Microsoft.CortexM3OnMBED.dll False $(LLILUM_SDK)\ZeligBuild\Target\bin\$(Configuration)\Microsoft.DeviceModels.ModelForCortexM3.dll False $(LLILUM_SDK)\ZeligBuild\Target\bin\$(Configuration)\Microsoft.Zelig.LlilumOSAbstraction.dll False $(LLILUM_SDK)\ZeligBuild\Host\bin\$(Configuration)\Microsoft.Zelig.ProductConfiguration.dll False $(LLILUM_SDK)\ZeligBuild\Host\bin\$(Configuration)\Microsoft.Zelig.Runtime.dll False $(LLILUM_SDK)\ZeligBuild\Host\bin\$(Configuration)\Microsoft.Zelig.Runtime.Common.dll False $(LLILUM_SDK)\ZeligBuild\Host\bin\$(Configuration)\Microsoft.Zelig.Runtime.CommonPC.dll False $(LLILUM_SDK)\ZeligBuild\Host\bin\$(Configuration)\Microsoft.Zelig.Runtime.TypeSystem.dll False $(LLILUM_SDK)\ZeligBuild\Host\bin\$(Configuration)\mscorlib.dll ================================================ FILE: Zelig/BoardConfigurations/LPC1768/Board/Properties/AssemblyInfo.cs ================================================ using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; // General Information about an assembly is controlled through the following // set of attributes. Change these attribute values to modify the information // associated with an assembly. [assembly: AssemblyTitle( "LPC1768" )] [assembly: AssemblyDescription( "" )] [assembly: AssemblyConfiguration( "" )] [assembly: AssemblyCompany( "Microsoft" )] [assembly: AssemblyProduct( "LPC1768" )] [assembly: AssemblyCopyright( "Copyright © Microsoft 2015" )] [assembly: AssemblyTrademark( "" )] [assembly: AssemblyCulture( "" )] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible( false )] // The following GUID is for the ID of the typelib if this project is exposed to COM //[assembly: Guid( "ffacd01c-fa64-4234-9058-1ad866f88c1a" )] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Build and Revision Numbers // by using the '*' as shown below: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion( "1.0.0.0" )] [assembly: AssemblyFileVersion( "1.0.0.0" )] ================================================ FILE: Zelig/BoardConfigurations/LPC1768/Board/SystemServices/GarbageCollectionManager.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // // The default GC scheme will be Conservative Mark and Sweep. // Only one of these should be enabled at a time #define MarkAndSweepGC namespace Microsoft.Llilum.LPC1768 { using Chipset = Microsoft.CortexM3OnMBED; #if ReferenceCountingGC public sealed class ReferenceCountingCollector : Microsoft.Zelig.Runtime.ReferenceCountingCollector { } #endif #if StrincReferenceCountingGC public sealed class StrictReferenceCountingCollector : Microsoft.Zelig.Runtime.StrictReferenceCountingCollector { } #endif #if MarkAndSweepGC public sealed class ConservativeMarkAndSweepCollector : Microsoft.Zelig.Runtime.ConservativeMarkAndSweepCollector { } #endif } ================================================ FILE: Zelig/BoardConfigurations/LPC1768/Board/SystemServices/ThreadManager.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // namespace Microsoft.Llilum.LPC1768 { using ChipsetModel = Microsoft.CortexM3OnMBED; using LLOS = Zelig.LlilumOSAbstraction.API; public sealed class ThreadManager : ChipsetModel.ThreadManager { private const int DefaultStackSizeLPC1768 = 2 * 1024; //--// // // Helper Methods // public override int DefaultStackSize { get { uint stackSize = LLOS.RuntimeMemory.LLOS_MEMORY_GetDefaultManagedStackSize(); if(stackSize == 0) { return DefaultStackSizeLPC1768; } return (int)stackSize; } } } } ================================================ FILE: Zelig/BoardConfigurations/LPC1768/Board/SystemServices/TimerPool.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // namespace Microsoft.Llilum.LPC1768 { using Chipset = Microsoft.CortexM0OnMBED; public sealed class TimerPool : Chipset.TimerPool { } } ================================================ FILE: Zelig/BoardConfigurations/LPC1768/Configuration/Configuration.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // namespace Microsoft.Llilum.BoardConfigurations { using Microsoft.Zelig.Runtime; using Microsoft.Zelig.Configuration.Environment; [DisplayName("LPC1768")] public sealed class LPC1768SoC : ProcessorCategory { [DependsOn(typeof(LPC1768SoC))] [DisplayName("Internal 32KB Static RAM")] [Defaults ( "BaseAddress" , 0x10000000 )] [Defaults ( "SizeInBytes" , 32 * 1024 )] [Defaults ( "WordSize" , 32 )] [Defaults ( "WaitStates" , 0 )] [EnumDefaults( "Characteristics", MemoryAttributes.RAM | MemoryAttributes.RandomAccessMemory | MemoryAttributes.InternalMemory | MemoryAttributes.ConfiguredAtEntryPoint )] public sealed class InternalRAM32KB : RamMemoryCategory { } [DependsOn( typeof( LPC1768SoC ) )] [DisplayName( "Internal 512KB FLASH" )] [Defaults( "BaseAddress", 0x00000000 )] [Defaults( "SizeInBytes", 512 * 1024 )] [Defaults( "WordSize" , 32 )] [Defaults( "WaitStates" , 0 )] [EnumDefaults( "Characteristics", MemoryAttributes.FLASH | MemoryAttributes.RandomAccessMemory | MemoryAttributes.InternalMemory | MemoryAttributes.ConfiguredAtEntryPoint )] public sealed class InternalFlash512KB : FlashMemoryCategory { } } //--// //--// //--// [DisplayName( "Memory Map for LPC1768" )] public sealed class LPC1768MemoryMap : MemoryMapCategory { [MergeEnumDefaults( "Characteristics", MemoryAttributes.InternalMemory | MemoryAttributes.RandomAccessMemory | MemoryAttributes.ConfiguredAtEntryPoint )] [MemorySection( MemoryUsage.Stack | MemoryUsage.Heap | MemoryUsage.DataRW | MemoryUsage.Code )] [AllowedOptions( typeof( LPC1768SoC.InternalRAM32KB ) )] [Defaults( "BaseAddress", 0x10000000U )] public RamMemoryCategory InternalRamChip; [MergeEnumDefaults( "Characteristics", MemoryAttributes.InternalMemory | MemoryAttributes.RandomAccessMemory | MemoryAttributes.ConfiguredAtEntryPoint | MemoryAttributes.LoadedAtEntrypoint )] [MemorySection( MemoryUsage.Bootstrap | MemoryUsage.Code | MemoryUsage.DataRO | MemoryUsage.VectorsTable | MemoryUsage.Relocation )] [AllowedOptions( typeof( LPC1768SoC.InternalFlash512KB ) )] [Defaults( "BaseAddress", 0x00000000U )] public FlashMemoryCategory InternalFlashChip; } //--// //--// //--// [DisplayName("LPC1768 MBED")] public sealed class LPC1768 : ProductCategory { [AllowedOptions(typeof(LPC1768SoC))] [Defaults("CoreClockFrequency" , 96000000UL)] [Defaults("RealTimeClockFrequency" , 1000000UL )] [Defaults("DefaultThreadPoolThreads", 2)] [Defaults("DefaultTimerPoolThreads" , 1)] public LPC1768SoC Processor; //--// [AllowedOptions( typeof( LPC1768SoC.InternalRAM32KB ) )] [Defaults( "BaseAddress", 0x10000000U )] public RamMemoryCategory InternalRam; [AllowedOptions( typeof( LPC1768SoC.InternalFlash512KB ) )] [Defaults( "BaseAddress", 0x00000000U )] public FlashMemoryCategory InternalFlashChip; } //--// //--// //--// [DisplayName("LLVM Compilation for LPC1768")] [Defaults("Platform", typeof(Microsoft.Zelig.Configuration.Environment.Abstractions.Architectures.LlvmForArmV7M))] [Defaults("CallingConvention", typeof(Microsoft.Zelig.Configuration.Environment.Abstractions.Architectures.LlvmForArmV7MCallingConvention))] [Defaults("Product", typeof(LPC1768))] [Defaults("MemoryMap", typeof(LPC1768MemoryMap))] public sealed class LPC1768MBEDCompilationSetup : CompilationSetupCategory { } } ================================================ FILE: Zelig/BoardConfigurations/LPC1768/Configuration/LPC1768.FrontEndConfig ================================================ ### ### NOTE: This file can be used in the SDK AS-IS, or remove all instances of #~# to use as manual input for the FrontEnd project ### ### ### Location of the Zelig assemblies. ### #~#-HostAssemblyDir ..\..\..\..\ZeligBuild\Host\bin\Debug #~#-DeviceAssemblyDir ..\..\..\..\ZeligBuild\Target\bin\Debug -Architecture cortex-m3 #~#-CompilationSetupPath ..\..\..\..\ZeligBuild\Host\bin\Debug\Microsoft.Llilum.BoardConfigurations.LPC1768.dll -CompilationSetup Microsoft.Llilum.BoardConfigurations.LPC1768MBEDCompilationSetup ### ### We need to include this assembly to get the right drivers. ### -Reference Microsoft.CortexM3OnMBED -Reference Microsoft.CortexM3OnCMSISCore -Reference Microsoft.DeviceModels.ModelForCortexM3 -Reference LPC1768 ### ### Add compilation phases, in order ### #-CompilationPhaseDisabled ReduceNumberOfTemporaries #-CompilationPhaseDisabled TransformFinallyBlocksIntoTryBlocks #-CompilationPhaseDisabled ApplyClassExtensions #-CompilationPhaseDisabled PrepareImplementationOfInternalMethods #-CompilationPhaseDisabled CrossReferenceTypeSystem #-CompilationPhaseDisabled ApplyConfigurationSettings -CompilationPhaseDisabled ResourceManagerOptimizations #-CompilationPhaseDisabled HighLevelTransformations #-CompilationPhaseDisabled PropagateCompilationConstraints #-CompilationPhaseDisabled ComputeCallsClosure #-CompilationPhaseDisabled EstimateTypeSystemReduction #-CompilationPhaseDisabled CompleteImplementationOfInternalMethods #-CompilationPhaseDisabled ReduceTypeSystem -CompilationPhaseDisabled PrepareExternalMethods #-CompilationPhaseDisabled DetectNonImplementedInternalCalls #-CompilationPhaseDisabled OrderStaticConstructors #-CompilationPhaseDisabled LayoutTypes #-CompilationPhaseDisabled HighLevelToMidLevelConversion #-CompilationPhaseDisabled FromImplicitToExplicitExceptions #-CompilationPhaseDisabled ReferenceCountingGarbageCollection -CompilationPhaseDisabled MidLevelToLowLevelConversion -CompilationPhaseDisabled ConvertUnsupportedOperatorsToMethodCalls -CompilationPhaseDisabled ExpandAggregateTypes -CompilationPhaseDisabled SplitComplexOperators -CompilationPhaseDisabled FuseOperators #-CompilationPhaseDisabled Optimizations -CompilationPhaseDisabled ConvertToSSA -CompilationPhaseDisabled PrepareForRegisterAllocation -CompilationPhaseDisabled CollectRegisterAllocationConstraints -CompilationPhaseDisabled AllocateRegisters #-CompilationPhaseDisabled GenerateImage #-CompilationPhaseDisabled Done -CompilationOption System.String GarbageCollectionManager ConservativeMarkAndSweepCollector ### ### The program to compile. ### #~#..\..\..\..\ZeligBuild\Target\bin\Debug\Microsoft.Zelig.Test.mbed.Simple.exe ### ### Where to put the results. ### #~#-OutputName Microsoft.Zelig.Test.mbed.Simple #~#-OutputDir ..\..\..\..\LLVM2IR_results\mbed\simple ### ### Dumps and diagnostics ### #-DumpIRBeforePhase ReduceNumberOfTemporaries TransformFinallyBlocksIntoTryBlocks ApplyClassExtensions #-DumpIRBeforePhase All #-DumpIR #-DumpIRpre #-DumpIRpost #-DumpIRXML #-DumpFlattenedCallGraph -DumpLLVMIR #-ReloadState #-DumpLLVMIR_TextRepresentation -MaxProcs 8 #~#-NoSDK ### ### LLVM CodeGeneration ### -GenerateObj # examples of overriding opt.exe and llc arguments # the examples here are the same as the defaults but can be modified to suit a variety of test # scenarios and experimentations #-LlvmOptArgs "-verify-debug-info -verify-dom-info -verify-each -verify-loop-info -verify-regalloc -verify-region-info -march=thumb -mcpu=cortex-m3 -aa-eval -indvars -gvn -globaldce -adce -dce -tailcallopt -scalarrepl -mem2reg -ipconstprop -deadargelim -sccp -dce -ipsccp -dce -constmerge -scev-aa -targetlibinfo -irce -dse -dce -argpromotion -mem2reg -adce -mem2reg -globaldce -die -dce -dse" #-LlvmLlcArgs "-O2 -code-model=small -data-sections -relocation-model=pic -march=thumb -mcpu=cortex-m3 -filetype=obj -mtriple=thumbv7m-none-eabi" # While the compiler is pretty good at figuring out where the LLVM tools are from # current Environment variables or registry entires you can manually specify the # path to find the LLVM binaries. # note: Environment variabes (i.e %MY_VAR%) are supported and expanded as with all # options in the FrontendConfig files so you can specify a custom variable if needed #-LlvmBinPath \\netmfbld02\LLVM\3.7.0\build\Win32\Release\bin ================================================ FILE: Zelig/BoardConfigurations/LPC1768/Configuration/LPC1768Configuration.csproj ================================================  Debug AnyCPU {C17E59D0-2D64-4012-8A98-D184D0CF8A49} Library Properties Microsoft.Llilum.BoardConfigurations Microsoft.Llilum.BoardConfigurations.LPC1768 v4.5 512 true true full false $(LlilumBuildRoot)\Host\bin\Debug\ DEBUG;TRACE prompt 4 pdbonly true $(LlilumBuildRoot)\Host\bin\Release\ TRACE prompt 4 {186f31a3-ef89-4a25-b2d5-20070606aa01} ProductConfiguration {186f31a3-ef89-4a25-b2d5-20061218aa01} Common {186F31A3-EF89-4A25-B2D5-20060501AA01} mscorlib False $(LLILUM_SDK)\ZeligBuild\Host\bin\Debug\Microsoft.Zelig.ProductConfiguration.dll $(LLILUM_SDK)\ZeligBuild\Host\bin\Debug\Microsoft.Zelig.Runtime.Common.dll $(LLILUM_SDK)\ZeligBuild\Target\bin\Debug\mscorlib.dll ================================================ FILE: Zelig/BoardConfigurations/LPC1768/Configuration/Properties/AssemblyInfo.cs ================================================ using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; // General Information about an assembly is controlled through the following // set of attributes. Change these attribute values to modify the information // associated with an assembly. [assembly: AssemblyTitle("Microsoft.Llilum.BoardConfigurations.LPC1768")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("Microsoft.Llilum.BoardConfigurations.LPC1768")] [assembly: AssemblyCopyright("Copyright © 2015")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible(false)] // The following GUID is for the ID of the typelib if this project is exposed to COM [assembly: Guid("c17e59d0-2d64-4012-8a98-d184d0cf8a49")] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Build and Revision Numbers // by using the '*' as shown below: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("1.0.0.0")] [assembly: AssemblyFileVersion("1.0.0.0")] ================================================ FILE: Zelig/BoardConfigurations/STM32F091/Board/HardwareModel/Board.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // namespace Microsoft.Llilum.STM32F091 { using System; using Chipset = Microsoft.CortexM0OnMBED; using ChipsetAbstration = Microsoft.DeviceModels.Chipset.CortexM0; public sealed class Board : Chipset.Board { internal const int GPIO_PORT_SHIFT = 12; // // Serial Ports // // NOTICE: Names are 1-indexed as per STM Board Description private static readonly string[] m_serialPorts = { "UART2", "UART3" }; public static readonly ChipsetAbstration.Board.SerialPortInfo UART2 = new ChipsetAbstration.Board.SerialPortInfo() { TxPin = (int)PinName.PA_14, RxPin = (int)PinName.PA_15, RtsPin = unchecked( (int)PinName.NC ), CtsPin = unchecked( (int)PinName.NC ), }; public static readonly ChipsetAbstration.Board.SerialPortInfo UART3 = new ChipsetAbstration.Board.SerialPortInfo() { TxPin = (int)PinName.PB_11, RxPin = (int)PinName.PC_4 , RtsPin = unchecked( (int)PinName.NC ), CtsPin = unchecked( (int)PinName.NC ), }; //--// private static readonly int[] s_ledPins = new int[] { (int)STM32F091.PinName.LED1, }; private static readonly int[] s_pwmPins = new int[] { (int)STM32F091.PinName.PB_0, }; // // Gpio discovery // public override int PinCount { get { return 51; } } public override int PinToIndex( int pin ) { return pin; } public override int NCPin { get { return -1; } } public override int[] LedPins { get { return s_ledPins; } } public override int[] PwmPins { get { return s_pwmPins; } } // // Serial Port // public override string[] GetSerialPorts() { return m_serialPorts; } public override ChipsetAbstration.Board.SerialPortInfo GetSerialPortInfo(string portName) { switch (portName) { case "UART2": return UART2; case "UART3": return UART3; default: return null; } } // // System timer // public override int GetSystemTimerIRQ( ) { return (int)IRQn.TIM2_IRQn; } public override int GetSerialPortIRQ(string portName) { switch (portName) { case "UART2": return (int)IRQn.USART2_IRQn; case "UART3": return (int)IRQn.USART3_8_IRQn; default: throw new NotSupportedException(); } } } } ================================================ FILE: Zelig/BoardConfigurations/STM32F091/Board/HardwareModel/Device.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // namespace Microsoft.Llilum.STM32F091 { using RT = Microsoft.Zelig.Runtime; using LLOS = Zelig.LlilumOSAbstraction.API; public sealed class Device : Microsoft.CortexM0OnMBED.Device { [RT.MemoryUsage(RT.MemoryUsage.Stack, ContentsUninitialized = true, AllocateFromHighAddress = true)] static readonly uint[] s_bootstrapStackSTM32F091 = new uint[ 1024 / sizeof( uint ) ]; // // Access Methods // public override uint[] BootstrapStack { get { return s_bootstrapStackSTM32F091; } } } } ================================================ FILE: Zelig/BoardConfigurations/STM32F091/Board/HardwareModel/Drivers/ContextSwitchTimer.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // //#define TIMERS_SELF_TEST namespace Microsoft.Llilum.STM32F091.Drivers { using System.Runtime.CompilerServices; using RT = Microsoft.Zelig.Runtime; using Chipset = Microsoft.DeviceModels.Chipset.CortexM0.Drivers; public sealed class ContextSwitchTimer : Chipset.ContextSwitchTimer { protected override uint GetTicksForQuantumValue( uint ms ) { // STM32F411 uses the Core clock (100Mhz) for SysTick return (uint)( RT.Configuration.CoreClockFrequency / 1000 ) * ms; } } } ================================================ FILE: Zelig/BoardConfigurations/STM32F091/Board/HardwareModel/Drivers/InterruptController.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // namespace Microsoft.Llilum.STM32F091.Drivers { using Chipset = Microsoft.CortexM0OnMBED.Drivers; public sealed class InterruptController : Chipset.InterruptController { } } ================================================ FILE: Zelig/BoardConfigurations/STM32F091/Board/HardwareModel/Drivers/SystemTimer.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // namespace Microsoft.Llilum.STM32F091.Drivers { using Chipset = Microsoft.CortexM0OnMBED.Drivers; public sealed class SystemTimer : Chipset.SystemTimer { } } ================================================ FILE: Zelig/BoardConfigurations/STM32F091/Board/HardwareModel/GPIO.cs ================================================ // // Copyright ((c) Microsoft Corporation. All rights reserved. // namespace Microsoft.Llilum.STM32F091 { //--// public enum PinName : uint { PA_0 = 0x00, PA_1 = 0x01, PA_2 = 0x02, PA_3 = 0x03, PA_4 = 0x04, PA_5 = 0x05, PA_6 = 0x06, PA_7 = 0x07, PA_8 = 0x08, PA_9 = 0x09, PA_10 = 0x0A, PA_11 = 0x0B, PA_12 = 0x0C, PA_13 = 0x0D, PA_14 = 0x0E, PA_15 = 0x0F, PB_0 = 0x10, PB_1 = 0x11, PB_2 = 0x12, PB_3 = 0x13, PB_4 = 0x14, PB_5 = 0x15, PB_6 = 0x16, PB_7 = 0x17, PB_8 = 0x18, PB_9 = 0x19, PB_10 = 0x1A, PB_11 = 0x1B, PB_12 = 0x1C, PB_13 = 0x1D, PB_14 = 0x1E, PB_15 = 0x1F, PC_0 = 0x20, PC_1 = 0x21, PC_2 = 0x22, PC_3 = 0x23, PC_4 = 0x24, PC_5 = 0x25, PC_6 = 0x26, PC_7 = 0x27, PC_8 = 0x28, PC_9 = 0x29, PC_10 = 0x2A, PC_11 = 0x2B, PC_12 = 0x2C, PC_13 = 0x2D, PC_14 = 0x2E, PC_15 = 0x2F, PD_2 = 0x32, PF_0 = 0x50, PF_1 = 0x51, PF_11 = 0x5B, // Arduino connector namings A0 = PA_0, A1 = PA_1, A2 = PA_4, A3 = PB_0, A4 = PC_1, A5 = PC_0, D0 = PA_3, D1 = PA_2, D2 = PA_10, D3 = PB_3, D4 = PB_5, D5 = PB_4, D6 = PB_10, D7 = PA_8, D8 = PA_9, D9 = PC_7, D10 = PB_6, D11 = PA_7, D12 = PA_6, D13 = PA_5, D14 = PB_9, D15 = PB_8, // Generic signals namings LED1 = PA_5, LED2 = PA_5, LED3 = PA_5, LED4 = PA_5, USER_BUTTON = PC_13, SERIAL_TX = PA_2, SERIAL_RX = PA_3, USBTX = PA_2, USBRX = PA_3, I2C_SCL = PB_8, I2C_SDA = PB_9, SPI_MOSI = PA_7, SPI_MISO = PA_6, SPI_SCK = PA_5, SPI_CS = PB_6, PWM_OUT = PB_4, // Not connected NC = unchecked(0xFFFFFFFF) } } ================================================ FILE: Zelig/BoardConfigurations/STM32F091/Board/HardwareModel/HardwareProviders/GpioProvider.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // namespace Microsoft.Llilum.STM32F091.HardwareModel.HardwareProviders { using System; using Chipset = CortexM0OnMBED; public sealed class GpioProvider : Chipset.HardwareModel.GpioProvider { public override int GetGpioPinIRQNumber(int pinNumber) { int pinIndex = pinNumber & 0xF; switch (pinIndex) { case 0: case 1: return (int)IRQn.EXTI0_1_IRQn; case 2: case 3: return (int)IRQn.EXTI2_3_IRQn; case 4: case 5: case 6: case 7: case 8: case 9: case 10: case 11: case 12: case 13: case 14: case 15: return (int)IRQn.EXTI4_15_IRQn; default: throw new NotImplementedException(); } } } } ================================================ FILE: Zelig/BoardConfigurations/STM32F091/Board/HardwareModel/HardwareProviders/I2cProvider.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // namespace Microsoft.Llilum.STM32F091 { using System; using Microsoft.Zelig.Runtime; using Chipset = Microsoft.CortexM0OnMBED; using ChipsetAbstration = Microsoft.DeviceModels.Chipset.CortexM0; public sealed class I2cProvider : Chipset.HardwareModel.I2cProvider { public static readonly I2cChannelInfo I2C0 = new I2cChannelInfo() { SclPin = (int)PinName.I2C_SCL, SdaPin = (int)PinName.I2C_SDA, PortIndex = 0, }; public override I2cChannelInfo GetI2cChannelInfo(int id) { switch (id) { case 0: return I2C0; default: return null; } } } } ================================================ FILE: Zelig/BoardConfigurations/STM32F091/Board/HardwareModel/HardwareProviders/SpiProvider.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // namespace Microsoft.Llilum.STM32F091 { using System; using Microsoft.Zelig.Runtime; using Chipset = Microsoft.CortexM0OnMBED; using ChipsetAbstration = Microsoft.DeviceModels.Chipset.CortexM0; public sealed class SpiProvider : Chipset.HardwareModel.SpiProvider { public static readonly SpiChannelInfo SPI0 = new SpiChannelInfo() { Mosi = (int)PinName.PA_7, Miso = (int)PinName.PA_6, Sclk = (int)PinName.PA_5, DefaultChipSelect = unchecked((int)PinName.NC), SetupTime = 10, HoldTime = 10, ActiveLow = true, }; public static readonly SpiChannelInfo SPI1 = new SpiChannelInfo() { Mosi = (int)PinName.PB_15, Miso = (int)PinName.PB_14, Sclk = (int)PinName.PB_13, DefaultChipSelect = unchecked((int)PinName.NC), SetupTime = 10, HoldTime = 10, ActiveLow = true, }; public override bool SpiBusySupported { get { return false; } } public override SpiChannelInfo GetSpiChannelInfo(int id) { switch (id) { case 0: return SPI0; case 1: return SPI1; default: return null; } } } } ================================================ FILE: Zelig/BoardConfigurations/STM32F091/Board/HardwareModel/HardwareProvidersUwp/AdcProviderUwp.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // namespace Microsoft.Llilum.STM32F091 { using System; using RT = Microsoft.Zelig.Runtime; using Chipset = Microsoft.CortexM0OnMBED; using ChipsetAbstration = Microsoft.DeviceModels.Chipset.CortexM0; public sealed class AdcProviderUwp : RT.AdcProviderUwp { private static readonly RT.AdcChannelInfoUwp m_adcInfo = new RT.AdcChannelInfoUwp() { MaxValue = UInt16.MaxValue, MinValue = 0, ResolutionInBits = 16, AdcPinNumbers = new int[] { (int)PinName.PB_1, (int)PinName.PC_2, (int)PinName.PC_3, (int)PinName.PC_4, (int)PinName.PC_5 } }; public override RT.AdcChannelInfoUwp GetAdcChannelInfo() { return m_adcInfo; } } } ================================================ FILE: Zelig/BoardConfigurations/STM32F091/Board/HardwareModel/HardwareProvidersUwp/I2cProviderUwp.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // namespace Microsoft.Llilum.STM32F091 { using System; using Microsoft.Zelig.Runtime; using Chipset = Microsoft.CortexM0OnMBED; using ChipsetAbstration = Microsoft.DeviceModels.Chipset.CortexM0; public sealed class I2cProviderUwp : Microsoft.Zelig.Runtime.I2cProviderUwp { private static string[] m_i2cChannels = { "I2C0" }; public override I2cChannelInfo GetI2cChannelInfo(string busId) { switch (busId) { case "I2C0": return I2cProvider.I2C0; default: return null; } } public override string[] GetI2cChannels() { return m_i2cChannels; } } } ================================================ FILE: Zelig/BoardConfigurations/STM32F091/Board/HardwareModel/HardwareProvidersUwp/PwmProviderUwp.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // namespace Microsoft.Llilum.STM32F091 { using System; using Microsoft.Zelig.Runtime; using Chipset = Microsoft.CortexM0OnMBED; using ChipsetAbstration = Microsoft.DeviceModels.Chipset.CortexM0; public sealed class PwmProviderUwp : Microsoft.Zelig.Runtime.PwmProviderUwp { private static readonly PwmChannelInfoUwp m_pwmInfo = new PwmChannelInfoUwp() { MaxFrequency = 1000000, MinFrequency = 0, PwmPinNumbers = new int[] { (int)PinName.PWM_OUT, } }; public override PwmChannelInfoUwp GetPwmChannelInfo() { return m_pwmInfo; } } } ================================================ FILE: Zelig/BoardConfigurations/STM32F091/Board/HardwareModel/HardwareProvidersUwp/SpiProviderUwp.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // namespace Microsoft.Llilum.STM32F091 { using System; using Microsoft.Zelig.Runtime; using Chipset = Microsoft.CortexM0OnMBED; using ChipsetAbstration = Microsoft.DeviceModels.Chipset.CortexM0; public sealed class SpiProviderUwp : Microsoft.Zelig.Runtime.SpiProviderUwp { // NOTICE: Names are 1-indexed as per STM Board Description private static readonly string[] m_spiDevices = { "SPI1", "SPI2" }; public static readonly SpiChannelInfoUwp SPI0 = new SpiChannelInfoUwp() { ChipSelectLines = 1, MinFreq = 1000, MaxFreq = 30000000, Supports16 = true, ChannelInfoKernel = SpiProvider.SPI0, }; public static readonly SpiChannelInfoUwp SPI1 = new SpiChannelInfoUwp() { ChipSelectLines = 1, MinFreq = 1000, MaxFreq = 30000000, Supports16 = true, ChannelInfoKernel = SpiProvider.SPI1, }; public override SpiChannelInfoUwp GetSpiChannelInfo(string busId) { switch (busId) { case "SPI1": return SPI0; case "SPI2": return SPI1; default: return null; } } public override string[] GetSpiChannels() { return m_spiDevices; } } } ================================================ FILE: Zelig/BoardConfigurations/STM32F091/Board/HardwareModel/NVIC.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // namespace Microsoft.Llilum.STM32F091 { enum IRQn { /****** Cortex-M0 Processor Exceptions Numbers **************************************************************/ NonMaskableInt_IRQn = -14, /*!< 2 Non Maskable Interrupt */ HardFault_IRQn = -13, /*!< 3 Cortex-M0 Hard Fault Interrupt */ SVC_IRQn = -5, /*!< 11 Cortex-M0 SV Call Interrupt */ PendSV_IRQn = -2, /*!< 14 Cortex-M0 Pend SV Interrupt */ SysTick_IRQn = -1, /*!< 15 Cortex-M0 System Tick Interrupt */ /****** STM32F091xC specific Interrupt Numbers **************************************************/ WWDG_IRQn = 0, /*!< Window WatchDog Interrupt */ PVD_VDDIO2_IRQn = 1, /*!< PVD & VDDIO2 Interrupts through EXTI Lines 16 and 31 */ RTC_IRQn = 2, /*!< RTC Interrupt through EXTI Lines 17, 19 and 20 */ FLASH_IRQn = 3, /*!< FLASH global Interrupt */ RCC_CRS_IRQn = 4, /*!< RCC & CRS global Interrupts */ EXTI0_1_IRQn = 5, /*!< EXTI Line 0 and 1 Interrupts */ EXTI2_3_IRQn = 6, /*!< EXTI Line 2 and 3 Interrupts */ EXTI4_15_IRQn = 7, /*!< EXTI Line 4 to 15 Interrupts */ TSC_IRQn = 8, /*!< Touch Sensing Controller Interrupts */ DMA1_Ch1_IRQn = 9, /*!< DMA1 Channel 1 Interrupt */ DMA1_Ch2_3_DMA2_Ch1_2_IRQn = 10, /*!< DMA1 Channel 2 and 3 & DMA2 Channel 1 and 2 Interrupts */ DMA1_Ch4_7_DMA2_Ch3_5_IRQn = 11, /*!< DMA1 Channel 4 to 7 & DMA2 Channel 3 to 5 Interrupts */ ADC1_COMP_IRQn = 12, /*!< ADC, COMP1 and COMP2 Interrupts (EXTI Lines 21 and 22) */ TIM1_BRK_UP_TRG_COM_IRQn = 13, /*!< TIM1 Break, Update, Trigger and Commutation Interrupts */ TIM1_CC_IRQn = 14, /*!< TIM1 Capture Compare Interrupt */ TIM2_IRQn = 15, /*!< TIM2 global Interrupt */ TIM3_IRQn = 16, /*!< TIM3 global Interrupt */ TIM6_DAC_IRQn = 17, /*!< TIM6 global and DAC channel underrun error Interrupts */ TIM7_IRQn = 18, /*!< TIM7 global Interrupt */ TIM14_IRQn = 19, /*!< TIM14 global Interrupt */ TIM15_IRQn = 20, /*!< TIM15 global Interrupt */ TIM16_IRQn = 21, /*!< TIM16 global Interrupt */ TIM17_IRQn = 22, /*!< TIM17 global Interrupt */ I2C1_IRQn = 23, /*!< I2C1 Event Interrupt & EXTI Line23 Interrupt (I2C1 wakeup) */ I2C2_IRQn = 24, /*!< I2C2 Event Interrupt */ SPI1_IRQn = 25, /*!< SPI1 global Interrupt */ SPI2_IRQn = 26, /*!< SPI2 global Interrupt */ USART1_IRQn = 27, /*!< USART1 global Interrupt & EXTI Line25 Interrupt (USART1 wakeup) */ USART2_IRQn = 28, /*!< USART2 global Interrupt & EXTI Line26 Interrupt (USART2 wakeup) */ USART3_8_IRQn = 29, /*!< USART3 to USART8 global Interrupts */ CEC_CAN_IRQn = 30, /*!< CEC and CAN global Interrupts & EXTI Line27 Interrupt */ LAST = 31, } } ================================================ FILE: Zelig/BoardConfigurations/STM32F091/Board/HardwareModel/Peripherals.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // //#define ALLOW_PAUSE namespace Microsoft.Llilum.STM32F091 { using RT = Microsoft.Zelig.Runtime; using Chipset = Microsoft.CortexM0OnMBED; using CMSIS = Microsoft.DeviceModels.Chipset.CortexM; public sealed class Peripherals : Chipset.Peripherals { public override void Initialize() { base.Initialize( ); // // Peripherals exceptions all have same priority // for(int i = 0; i < (int)IRQn.LAST; ++i) { CMSIS.NVIC.SetPriority( i , RT.TargetPlatform.ARMv7.ProcessorARMv7M.c_Priority__GenericPeripherals ); } } } } ================================================ FILE: Zelig/BoardConfigurations/STM32F091/Board/HardwareModel/Processor.cs ================================================ // // Copyright ((c) Microsoft Corporation. All rights reserved. // namespace Microsoft.Llilum.STM32F091 { using System.Runtime.InteropServices; using RT = Microsoft.Zelig.Runtime; using ChipsetModel = Microsoft.CortexM0OnMBED; [RT.ProductFilter("Microsoft.Llilum.BoardConfigurations.STM32F091")] public sealed class Processor : Microsoft.CortexM0OnMBED.Processor { public new class Context : ChipsetModel.Processor.Context { public Context(RT.ThreadImpl owner) : base(owner) { } public override unsafe void SwitchTo( ) { base.SwitchTo( ); } } // // Helper methods // [RT.Inline] public override void InitializeProcessor() { base.InitializeProcessor( ); } [RT.Inline] public override Microsoft.Zelig.Runtime.Processor.Context AllocateProcessorContext(RT.ThreadImpl owner) { return new Context(owner); } } } ================================================ FILE: Zelig/BoardConfigurations/STM32F091/Board/Properties/AssemblyInfo.cs ================================================ using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; // General Information about an assembly is controlled through the following // set of attributes. Change these attribute values to modify the information // associated with an assembly. [assembly: AssemblyTitle("STM32F091")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("STM32F091")] [assembly: AssemblyCopyright("Copyright © 2016")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible(false)] // The following GUID is for the ID of the typelib if this project is exposed to COM [assembly: Guid("6194144a-f8b1-4525-829f-061df4a5645a")] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Build and Revision Numbers // by using the '*' as shown below: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("1.0.0.0")] [assembly: AssemblyFileVersion("1.0.0.0")] ================================================ FILE: Zelig/BoardConfigurations/STM32F091/Board/STM32F091.csproj ================================================  Debug AnyCPU {65E36DF8-5CB8-4582-851E-F5381AE4A1A7} Library Properties Microsoft.Llilum.STM32F091 STM32F091 v4.5 512 true $(LlilumBuildRoot)\Target\bin\$(Configuration)\ $(LlilumBuildRoot)\Target\bin\$(Configuration)\ $(LlilumBuildRoot)\Target\obj\$(MSBuildProjectName)\ $(LLILUM_SDK)\ZeligBuild\Target\bin\$(Configuration)\ $(LLILUM_SDK)\ZeligBuild\Target\bin\$(Configuration)\ $(LLILUM_SDK)\ZeligBuild\Target\obj\$(MSBuildProjectName)\ true full false DEBUG;TRACE prompt 4 true true true AllRules.ruleset AnyCPU false pdbonly true TRACE prompt 4 true true true AllRules.ruleset AnyCPU false {B8FE271A-CD41-435E-8766-4DB7609C1007} CortexM0OnCMSIS-Core {89EBDBB0-C81F-4611-B719-B385DF215F8D} CortexM0OnMBED {C3BFAFAD-A6C6-471D-A059-B3CB7E57A4AB} ModelForCortexM0 {e4c618af-1785-472e-a070-8068e20582eb} ModelForCortexM {186f31a3-ef89-4a25-b2d5-20070606aa01} ProductConfiguration {186f31a3-ef89-4a25-b2d5-20070601aa01} CommonPC {186f31a3-ef89-4a25-b2d5-20061218aa01} Common {186f31a3-ef89-4a25-b2d5-20060509aa01} Kernel {20dc2cf5-8eed-4231-9743-6bab96be465c} LlilumOSAbstraction {186f31a3-ef89-4a25-b2d5-20060720aa01} TypeSystem {186F31A3-EF89-4A25-B2D5-20060501AA01} mscorlib False False $(LLILUM_SDK)\ZeligBuild\Target\bin\$(Configuration)\Microsoft.CortexM3OnCMSISCore.dll False $(LLILUM_SDK)\ZeligBuild\Target\bin\$(Configuration)\Microsoft.CortexM3OnMBED.dll False $(LLILUM_SDK)\ZeligBuild\Target\bin\$(Configuration)\Microsoft.DeviceModels.ModelForCortexM3.dll False $(LLILUM_SDK)\ZeligBuild\Target\bin\$(Configuration)\Microsoft.CortexM4OnCMSISCore.dll False $(LLILUM_SDK)\ZeligBuild\Target\bin\$(Configuration)\Microsoft.CortexM4OnMBED.dll False $(LLILUM_SDK)\ZeligBuild\Target\bin\$(Configuration)\Microsoft.DeviceModels.ModelForCortexM4.dll False $(LLILUM_SDK)\ZeligBuild\Target\bin\$(Configuration)\Microsoft.Zelig.LlilumOSAbstraction.dll False $(LLILUM_SDK)\ZeligBuild\Host\bin\$(Configuration)\Microsoft.Zelig.ProductConfiguration.dll False $(LLILUM_SDK)\ZeligBuild\Host\bin\$(Configuration)\Microsoft.Zelig.Runtime.dll False $(LLILUM_SDK)\ZeligBuild\Host\bin\$(Configuration)\Microsoft.Zelig.Runtime.Common.dll False $(LLILUM_SDK)\ZeligBuild\Host\bin\$(Configuration)\Microsoft.Zelig.Runtime.CommonPC.dll False $(LLILUM_SDK)\ZeligBuild\Host\bin\$(Configuration)\Microsoft.Zelig.Runtime.TypeSystem.dll $(LLILUM_SDK)\ZeligBuild\Target\bin\$(Configuration)\mscorlib.dll ================================================ FILE: Zelig/BoardConfigurations/STM32F091/Board/SystemServices/GarbageCollectionManager.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // namespace Microsoft.Llilum.STM32F091 { using Chipset = Microsoft.CortexM0OnMBED; public sealed class GarbageCollectionManager : Chipset.GarbageCollectionManager { } } ================================================ FILE: Zelig/BoardConfigurations/STM32F091/Board/SystemServices/ThreadManager.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // namespace Microsoft.Llilum.STM32F091 { using Chipset = Microsoft.CortexM0OnMBED; using LLOS = Zelig.LlilumOSAbstraction.API; public sealed class ThreadManager : Chipset.ThreadManager { private const int DefaultStackSizeSTM32F091 = 2 * 1024; //--// // // Helper Methods // public override int DefaultStackSize { get { uint stackSize = LLOS.RuntimeMemory.LLOS_MEMORY_GetDefaultManagedStackSize(); if(stackSize == 0) { return DefaultStackSizeSTM32F091; } return (int)stackSize; } } } } ================================================ FILE: Zelig/BoardConfigurations/STM32F091/Board/SystemServices/TimerPool.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // namespace Microsoft.Llilum.STM32F091 { using Chipset = Microsoft.CortexM0OnMBED; public sealed class TimerPool : Chipset.TimerPool { } } ================================================ FILE: Zelig/BoardConfigurations/STM32F091/Configuration/Configuration.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // namespace Microsoft.Llilum.BoardConfigurations { using Microsoft.Zelig.Runtime; using Microsoft.Zelig.Configuration.Environment; [DisplayName("STM32F091")] public sealed class STM32F091SoC : ProcessorCategory { [DependsOn(typeof(STM32F091SoC))] [DisplayName("Internal 32KB Static RAM")] [Defaults("BaseAddress", 0x20000000U)] [Defaults("SizeInBytes", 32 * 1024)] [Defaults("WordSize", 32)] [Defaults("WaitStates", 0)] [EnumDefaults("Characteristics", MemoryAttributes.RAM | MemoryAttributes.RandomAccessMemory | MemoryAttributes.InternalMemory | MemoryAttributes.ConfiguredAtEntryPoint)] public sealed class InternalRAM32KB : RamMemoryCategory { } [DependsOn(typeof(STM32F091SoC))] [DisplayName("Internal 256KB FLASH")] [Defaults("BaseAddress", 0x08000000U)] [Defaults("SizeInBytes", 256 * 1024)] [Defaults("WordSize", 32)] [Defaults("WaitStates", 0)] [EnumDefaults("Characteristics", MemoryAttributes.FLASH | MemoryAttributes.RandomAccessMemory | MemoryAttributes.InternalMemory | MemoryAttributes.ConfiguredAtEntryPoint)] public sealed class InternalFlash256KB : FlashMemoryCategory { } } //--// //--// //--// [DisplayName("Memory Map for STM32F091")] public sealed class STM32F091MemoryMap : MemoryMapCategory { [MergeEnumDefaults("Characteristics", MemoryAttributes.InternalMemory | MemoryAttributes.RandomAccessMemory | MemoryAttributes.ConfiguredAtEntryPoint)] [MemorySection(MemoryUsage.Stack | MemoryUsage.Heap | MemoryUsage.DataRW | MemoryUsage.Code)] [AllowedOptions(typeof(STM32F091SoC.InternalRAM32KB))] [Defaults("BaseAddress", 0x20000000U)] public RamMemoryCategory InternalRamChip; [MergeEnumDefaults("Characteristics", MemoryAttributes.InternalMemory | MemoryAttributes.RandomAccessMemory | MemoryAttributes.ConfiguredAtEntryPoint | MemoryAttributes.LoadedAtEntrypoint)] [MemorySection(MemoryUsage.Bootstrap | MemoryUsage.Code | MemoryUsage.DataRO | MemoryUsage.VectorsTable | MemoryUsage.Relocation)] [AllowedOptions(typeof(STM32F091SoC.InternalFlash256KB))] [Defaults("BaseAddress", 0x08000000U)] public FlashMemoryCategory InternalFlashChip; } //--// //--// //--// [DisplayName("STM32F091 MBED")] public sealed class STM32F091 : ProductCategory { [AllowedOptions(typeof(STM32F091SoC))] [Defaults("CoreClockFrequency", 48000000UL)] [Defaults("RealTimeClockFrequency", 1000000UL)] [Defaults("DefaultThreadPoolThreads", 1)] [Defaults("DefaultTimerPoolThreads", 1)] public STM32F091SoC Processor; //--// [AllowedOptions(typeof(STM32F091SoC.InternalRAM32KB))] [Defaults("BaseAddress", 0x20000000U)] public RamMemoryCategory InternalRam; [AllowedOptions(typeof(STM32F091SoC.InternalFlash256KB))] [Defaults("BaseAddress", 0x08000000U)] public FlashMemoryCategory InternalFlashChip; } //--// //--// //--// [DisplayName("LLVM Compilation for STM32F091")] [Defaults("Platform", typeof(Microsoft.Zelig.Configuration.Environment.Abstractions.Architectures.LlvmForArmV6M))] [Defaults("CallingConvention", typeof(Microsoft.Zelig.Configuration.Environment.Abstractions.Architectures.LlvmForArmV7MCallingConvention))] [Defaults("Product", typeof(STM32F091))] [Defaults("MemoryMap", typeof(STM32F091MemoryMap))] public sealed class STM32F091MBEDCompilationSetup : CompilationSetupCategory { } } ================================================ FILE: Zelig/BoardConfigurations/STM32F091/Configuration/Properties/AssemblyInfo.cs ================================================ using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; // General Information about an assembly is controlled through the following // set of attributes. Change these attribute values to modify the information // associated with an assembly. [assembly: AssemblyTitle("Microsoft.Llilum.BoardConfigurations.STM32F091")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("Microsoft.Llilum.BoardConfigurations.STM32F091")] [assembly: AssemblyCopyright("Copyright © 2016")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible(false)] // The following GUID is for the ID of the typelib if this project is exposed to COM [assembly: Guid("DA8F4085-A48D-4B75-ACF7-4735279B4D96")] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Build and Revision Numbers // by using the '*' as shown below: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("1.0.0.0")] [assembly: AssemblyFileVersion("1.0.0.0")] ================================================ FILE: Zelig/BoardConfigurations/STM32F091/Configuration/STM32F091.FrontEndConfig ================================================ ### ### NOTE: This file can be used in the SDK AS-IS, or remove all instances of #~# to use as manual input for the FrontEnd project ### ### ### Location of the Zelig assemblies. ### #~#-HostAssemblyDir ..\..\..\..\ZeligBuild\Host\bin\Debug #~#-DeviceAssemblyDir ..\..\..\..\ZeligBuild\Target\bin\Debug -Architecture cortex-m0 #~#-CompilationSetupPath ..\..\..\..\ZeligBuild\Host\bin\Debug\Microsoft.Llilum.BoardConfigurations.STM32F091.dll -CompilationSetup Microsoft.Llilum.BoardConfigurations.STM32F091MBEDCompilationSetup ### ### We need to include this assembly to get the right drivers. ### -Reference Microsoft.CortexM0OnMBED -Reference Microsoft.CortexM0OnCMSISCore -Reference Microsoft.DeviceModels.ModelForCortexM0 -Reference STM32F091 ### ### Add compilation phases, in order ### #-CompilationPhaseDisabled ReduceNumberOfTemporaries #-CompilationPhaseDisabled TransformFinallyBlocksIntoTryBlocks #-CompilationPhaseDisabled ApplyClassExtensions #-CompilationPhaseDisabled PrepareImplementationOfInternalMethods #-CompilationPhaseDisabled CrossReferenceTypeSystem #-CompilationPhaseDisabled ApplyConfigurationSettings -CompilationPhaseDisabled ResourceManagerOptimizations #-CompilationPhaseDisabled HighLevelTransformations #-CompilationPhaseDisabled PropagateCompilationConstraints #-CompilationPhaseDisabled ComputeCallsClosure #-CompilationPhaseDisabled EstimateTypeSystemReduction #-CompilationPhaseDisabled CompleteImplementationOfInternalMethods #-CompilationPhaseDisabled ReduceTypeSystem -CompilationPhaseDisabled PrepareExternalMethods #-CompilationPhaseDisabled DetectNonImplementedInternalCalls #-CompilationPhaseDisabled OrderStaticConstructors #-CompilationPhaseDisabled LayoutTypes #-CompilationPhaseDisabled HighLevelToMidLevelConversion #-CompilationPhaseDisabled FromImplicitToExplicitExceptions #-CompilationPhaseDisabled ReferenceCountingGarbageCollection -CompilationPhaseDisabled MidLevelToLowLevelConversion -CompilationPhaseDisabled ConvertUnsupportedOperatorsToMethodCalls -CompilationPhaseDisabled ExpandAggregateTypes -CompilationPhaseDisabled SplitComplexOperators -CompilationPhaseDisabled FuseOperators #-CompilationPhaseDisabled Optimizations -CompilationPhaseDisabled ConvertToSSA -CompilationPhaseDisabled PrepareForRegisterAllocation -CompilationPhaseDisabled CollectRegisterAllocationConstraints -CompilationPhaseDisabled AllocateRegisters #-CompilationPhaseDisabled GenerateImage #-CompilationPhaseDisabled Done ### ### The program to compile. ### #~#..\..\..\..\ZeligBuild\Target\bin\Debug\Microsoft.Zelig.Test.mbed.Simple.exe ### ### Where to put the results. ### #~#-OutputName Microsoft.Zelig.Test.mbed.Simple #~#-OutputDir ..\..\..\..\LLVM2IR_results\mbed\simple ### ### Dumps and diagnostics ### #-DumpIRBeforePhase ReduceNumberOfTemporaries TransformFinallyBlocksIntoTryBlocks ApplyClassExtensions #-DumpIRBeforePhase All #-DumpIR #-DumpIRpre #-DumpIRpost #-DumpIRXML #-DumpFlattenedCallGraph -DumpLLVMIR #-ReloadState #-DumpLLVMIR_TextRepresentation -MaxProcs 8 #~#-NoSDK ### ### LLVM CodeGeneration ### -GenerateObj # examples of overriding opt.exe and llc arguments # the examples here are the same as the defaults but can be modified to suit a variety of test # scenarios and experimentations #-LlvmOptArgs "-verify-debug-info -verify-dom-info -verify-each -verify-loop-info -verify-regalloc -verify-region-info -march=thumb -mcpu=cortex-m3 -aa-eval -indvars -gvn -globaldce -adce -dce -tailcallopt -scalarrepl -mem2reg -ipconstprop -deadargelim -sccp -dce -ipsccp -dce -constmerge -scev-aa -targetlibinfo -irce -dse -dce -argpromotion -mem2reg -adce -mem2reg -globaldce -die -dce -dse" #-LlvmLlcArgs "-O2 -code-model=small -data-sections -relocation-model=pic -march=thumb -mcpu=cortex-m3 -filetype=obj -mtriple=thumbv7m-none-eabi" # While the compiler is pretty good at figuring out where the LLVM tools are from # current Environment variables or registry entires you can manually specify the # path to find the LLVM binaries. # note: Environment variabes (i.e %MY_VAR%) are supported and expanded as with all # options in the FrontendConfig files so you can specify a custom variable if needed #-LlvmBinPath c:\src\llvm\llvm-3.7.0.src\build\x64\Release\bin ================================================ FILE: Zelig/BoardConfigurations/STM32F091/Configuration/STM32F091Configuration.csproj ================================================  Debug AnyCPU {C183991C-1F27-4665-A884-FD977D2AD359} Library Properties Microsoft.Llilum.BoardConfigurations Microsoft.Llilum.BoardConfigurations.STM32F091 v4.5 512 true true full false $(LlilumBuildRoot)\Host\bin\$(Configuration)\ DEBUG;TRACE prompt 4 pdbonly true $(LlilumBuildRoot)\Host\bin\$(Configuration)\ TRACE prompt 4 {186f31a3-ef89-4a25-b2d5-20070606aa01} ProductConfiguration {186f31a3-ef89-4a25-b2d5-20061218aa01} Common {186F31A3-EF89-4A25-B2D5-20060501AA01} mscorlib False $(LLILUM_SDK)\ZeligBuild\Host\bin\Debug\Microsoft.Zelig.ProductConfiguration.dll $(LLILUM_SDK)\ZeligBuild\Host\bin\Debug\Microsoft.Zelig.Runtime.Common.dll $(LLILUM_SDK)\ZeligBuild\Target\bin\Debug\mscorlib.dll ================================================ FILE: Zelig/BoardConfigurations/STM32F401/Board/HardwareModel/Board.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // namespace Microsoft.Llilum.STM32F401 { using System; using Chipset = Microsoft.CortexM4OnMBED; using ChipsetAbstration = Microsoft.DeviceModels.Chipset.CortexM4; public sealed class Board : Chipset.Board { internal const int GPIO_PORT_SHIFT = 12; // // Serial Ports // // NOTICE: Names are 1-indexed as per STM Board Description private static readonly string[] m_serialPorts = { "UART1", "UART2", "UART6" }; public static readonly ChipsetAbstration.Board.SerialPortInfo UART1 = new ChipsetAbstration.Board.SerialPortInfo() { TxPin = (int)PinName.PA_9, RxPin = (int)PinName.PA_10, RtsPin = unchecked((int)PinName.NC), CtsPin = unchecked((int)PinName.NC) }; public static readonly ChipsetAbstration.Board.SerialPortInfo UART2 = new ChipsetAbstration.Board.SerialPortInfo() { TxPin = (int)PinName.USBTX, RxPin = (int)PinName.USBRX, RtsPin = unchecked((int)PinName.NC), CtsPin = unchecked((int)PinName.NC) }; public static readonly ChipsetAbstration.Board.SerialPortInfo UART6 = new ChipsetAbstration.Board.SerialPortInfo() { TxPin = (int)PinName.PA_11, RxPin = (int)PinName.PA_12, RtsPin = unchecked((int)PinName.NC), CtsPin = unchecked((int)PinName.NC) }; //--// private static readonly int[] s_ledPins = new int[] { (int)STM32F401.PinName.LED1, }; private static readonly int[] s_pwmPins = new int[] { (int)STM32F401.PinName.D3, }; // // Gpio discovery // public override int PinCount { get { return 48; } } public override int PinToIndex( int pin ) { return pin; } public override int NCPin { get { return -1; } } public override int[] LedPins { get { return s_ledPins; } } public override int[] PwmPins { get { return s_pwmPins; } } // // Serial Port // public override string[] GetSerialPorts() { return m_serialPorts; } public override ChipsetAbstration.Board.SerialPortInfo GetSerialPortInfo(string portName) { switch (portName) { case "UART1": return UART1; case "UART2": return UART2; case "UART6": return UART6; default: return null; } } // // System timer // public override int GetSystemTimerIRQ( ) { return (int)IRQn.TIM2_IRQn; } public override int GetSerialPortIRQ(string portName) { switch (portName) { case "UART1": return (int)IRQn.USART1_IRQn; case "UART2": return (int)IRQn.USART2_IRQn; case "UART6": return (int)IRQn.USART6_IRQn; default: throw new NotSupportedException(); } } } } ================================================ FILE: Zelig/BoardConfigurations/STM32F401/Board/HardwareModel/Device.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // namespace Microsoft.Llilum.STM32F401 { using RT = Microsoft.Zelig.Runtime; using LLOS = Zelig.LlilumOSAbstraction.API; public sealed class Device : Microsoft.CortexM4OnMBED.Device { [RT.MemoryUsage(RT.MemoryUsage.Stack, ContentsUninitialized = true, AllocateFromHighAddress = true)] static readonly uint[] s_bootstrapStackSTM32F401 = new uint[ 1024 / sizeof( uint ) ]; // // Access Methods // public override uint[] BootstrapStack { get { return s_bootstrapStackSTM32F401; } } } } ================================================ FILE: Zelig/BoardConfigurations/STM32F401/Board/HardwareModel/Drivers/ContextSwitchTimer.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // //#define TIMERS_SELF_TEST namespace Microsoft.Llilum.STM32F401.Drivers { using System.Runtime.CompilerServices; using RT = Microsoft.Zelig.Runtime; using Chipset = Microsoft.DeviceModels.Chipset.CortexM4.Drivers; public sealed class ContextSwitchTimer : Chipset.ContextSwitchTimer { protected override uint GetTicksForQuantumValue( uint ms ) { // STM32F411 uses the Core clock (100Mhz) for SysTick return (uint)( RT.Configuration.CoreClockFrequency / 1000 ) * ms; } } } ================================================ FILE: Zelig/BoardConfigurations/STM32F401/Board/HardwareModel/Drivers/InterruptController.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // namespace Microsoft.Llilum.STM32F401.Drivers { using Chipset = Microsoft.CortexM4OnMBED.Drivers; public sealed class InterruptController : Chipset.InterruptController { } } ================================================ FILE: Zelig/BoardConfigurations/STM32F401/Board/HardwareModel/Drivers/SystemTimer.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // namespace Microsoft.Llilum.STM32F401.Drivers { using Chipset = Microsoft.CortexM4OnMBED.Drivers; public sealed class SystemTimer : Chipset.SystemTimer { } } ================================================ FILE: Zelig/BoardConfigurations/STM32F401/Board/HardwareModel/GPIO.cs ================================================ // // Copyright ((c) Microsoft Corporation. All rights reserved. // namespace Microsoft.Llilum.STM32F401 { //--// public enum PinName : uint { PA_0 = 0x00, PA_1 = 0x01, PA_2 = 0x02, PA_3 = 0x03, PA_4 = 0x04, PA_5 = 0x05, PA_6 = 0x06, PA_7 = 0x07, PA_8 = 0x08, PA_9 = 0x09, PA_10 = 0x0A, PA_11 = 0x0B, PA_12 = 0x0C, PA_13 = 0x0D, PA_14 = 0x0E, PA_15 = 0x0F, PB_0 = 0x10, PB_1 = 0x11, PB_2 = 0x12, PB_3 = 0x13, PB_4 = 0x14, PB_5 = 0x15, PB_6 = 0x16, PB_7 = 0x17, PB_8 = 0x18, PB_9 = 0x19, PB_10 = 0x1A, PB_12 = 0x1C, PB_13 = 0x1D, PB_14 = 0x1E, PB_15 = 0x1F, PC_0 = 0x20, PC_1 = 0x21, PC_2 = 0x22, PC_3 = 0x23, PC_4 = 0x24, PC_5 = 0x25, PC_6 = 0x26, PC_7 = 0x27, PC_8 = 0x28, PC_9 = 0x29, PC_10 = 0x2A, PC_11 = 0x2B, PC_12 = 0x2C, PC_13 = 0x2D, PC_14 = 0x2E, PC_15 = 0x2F, // Unsure what these are. Modify PinToIndex to accomodate for these if needed PD_2 = 0x32, PH_0 = 0x70, PH_1 = 0x71, // Arduino connector namings A0 = PA_0, A1 = PA_1, A2 = PA_4, A3 = PB_0, A4 = PC_1, A5 = PC_0, D0 = PA_3, D1 = PA_2, D2 = PA_10, D3 = PB_3, D4 = PB_5, D5 = PB_4, D6 = PB_10, D7 = PA_8, D8 = PA_9, D9 = PC_7, D10 = PB_6, D11 = PA_7, D12 = PA_6, D13 = PA_5, D14 = PB_9, D15 = PB_8, // Generic signals namings LED1 = PA_5, LED2 = PA_5, LED3 = PA_5, LED4 = PA_5, USER_BUTTON = PC_13, SERIAL_TX = PA_2, SERIAL_RX = PA_3, USBTX = PA_2, USBRX = PA_3, I2C_SCL = PB_8, I2C_SDA = PB_9, SPI_MOSI = PA_7, SPI_MISO = PA_6, SPI_SCK = PA_5, SPI_CS = PB_6, PWM_OUT = PB_3, // Not connected NC = unchecked(0xFFFFFFFF), } } ================================================ FILE: Zelig/BoardConfigurations/STM32F401/Board/HardwareModel/HardwareProviders/GpioProvider.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // namespace Microsoft.Llilum.STM32F401.HardwareModel.HardwareProviders { using System; using Chipset = CortexM4OnMBED; public sealed class GpioProvider : Chipset.HardwareModel.GpioProvider { public override int GetGpioPinIRQNumber(int pinNumber) { int pinIndex = pinNumber & 0xF; switch (pinIndex) { case 0: return (int)IRQn.EXTI0_IRQn; case 1: return (int)IRQn.EXTI1_IRQn; case 2: return (int)IRQn.EXTI2_IRQn; case 3: return (int)IRQn.EXTI3_IRQn; case 4: return (int)IRQn.EXTI4_IRQn; case 5: case 6: case 7: case 8: case 9: return (int)IRQn.EXTI9_5_IRQn; case 10: case 11: case 12: case 13: case 14: case 15: return (int)IRQn.EXTI15_10_IRQn; default: throw new NotImplementedException(); } } } } ================================================ FILE: Zelig/BoardConfigurations/STM32F401/Board/HardwareModel/HardwareProviders/I2cProvider.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // namespace Microsoft.Llilum.STM32F401 { using System; using Microsoft.Zelig.Runtime; using Chipset = Microsoft.CortexM4OnMBED; using ChipsetAbstration = Microsoft.DeviceModels.Chipset.CortexM4; public sealed class I2cProvider : Chipset.HardwareModel.I2cProvider { public static readonly I2cChannelInfo I2C0 = new I2cChannelInfo() { SclPin = (int)PinName.I2C_SCL, SdaPin = (int)PinName.I2C_SDA, PortIndex = 0, }; public override I2cChannelInfo GetI2cChannelInfo(int id) { switch (id) { case 0: return I2C0; default: return null; } } } } ================================================ FILE: Zelig/BoardConfigurations/STM32F401/Board/HardwareModel/HardwareProviders/SpiProvider.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // namespace Microsoft.Llilum.STM32F401 { using System; using Microsoft.Zelig.Runtime; using Chipset = Microsoft.CortexM4OnMBED; using ChipsetAbstration = Microsoft.DeviceModels.Chipset.CortexM4; public sealed class SpiProvider : Chipset.HardwareModel.SpiProvider { public static readonly SpiChannelInfo SPI0 = new SpiChannelInfo() { Mosi = (int)PinName.PA_7, Miso = (int)PinName.PA_6, Sclk = (int)PinName.PA_5, DefaultChipSelect = unchecked((int)PinName.NC), SetupTime = 10, HoldTime = 10, ActiveLow = true, }; public static readonly SpiChannelInfo SPI1 = new SpiChannelInfo() { Mosi = (int)PinName.PB_15, Miso = (int)PinName.PB_14, Sclk = (int)PinName.PB_13, DefaultChipSelect = unchecked((int)PinName.NC), SetupTime = 10, HoldTime = 10, ActiveLow = true, }; public static readonly SpiChannelInfo SPI2 = new SpiChannelInfo() { Mosi = (int)PinName.PC_12, Miso = (int)PinName.PC_11, Sclk = (int)PinName.PC_10, DefaultChipSelect = unchecked((int)PinName.NC), SetupTime = 10, HoldTime = 10, ActiveLow = true, }; public override bool SpiBusySupported { get { return false; } } public override SpiChannelInfo GetSpiChannelInfo(int id) { switch (id) { case 0: return SPI0; case 1: return SPI1; case 2: return SPI2; default: return null; } } } } ================================================ FILE: Zelig/BoardConfigurations/STM32F401/Board/HardwareModel/HardwareProvidersUwp/AdcProviderUwp.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // namespace Microsoft.Llilum.STM32F401 { using System; using RT = Microsoft.Zelig.Runtime; using Chipset = Microsoft.CortexM4OnMBED; using ChipsetAbstration = Microsoft.DeviceModels.Chipset.CortexM4; public sealed class AdcProviderUwp : RT.AdcProviderUwp { private static readonly RT.AdcChannelInfoUwp m_adcInfo = new RT.AdcChannelInfoUwp() { MaxValue = UInt16.MaxValue, MinValue = 0, ResolutionInBits = 16, AdcPinNumbers = new int[] { (int)PinName.A0, (int)PinName.A1, (int)PinName.A2, (int)PinName.A3, (int)PinName.A4, (int)PinName.A5 } }; public override RT.AdcChannelInfoUwp GetAdcChannelInfo() { return m_adcInfo; } } } ================================================ FILE: Zelig/BoardConfigurations/STM32F401/Board/HardwareModel/HardwareProvidersUwp/I2cProviderUwp.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // namespace Microsoft.Llilum.STM32F401 { using System; using Microsoft.Zelig.Runtime; using Chipset = Microsoft.CortexM4OnMBED; using ChipsetAbstration = Microsoft.DeviceModels.Chipset.CortexM4; public sealed class I2cProviderUwp : Microsoft.Zelig.Runtime.I2cProviderUwp { private static string[] m_i2cChannels = { "I2C0" }; public override I2cChannelInfo GetI2cChannelInfo(string busId) { switch (busId) { case "I2C0": return I2cProvider.I2C0; default: return null; } } public override string[] GetI2cChannels() { return m_i2cChannels; } } } ================================================ FILE: Zelig/BoardConfigurations/STM32F401/Board/HardwareModel/HardwareProvidersUwp/PwmProviderUwp.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // namespace Microsoft.Llilum.STM32F401 { using System; using Microsoft.Zelig.Runtime; using Chipset = Microsoft.CortexM4OnMBED; using ChipsetAbstration = Microsoft.DeviceModels.Chipset.CortexM4; public sealed class PwmProviderUwp : Microsoft.Zelig.Runtime.PwmProviderUwp { private static readonly PwmChannelInfoUwp m_pwmInfo = new PwmChannelInfoUwp() { MaxFrequency = 1000000, MinFrequency = 0, PwmPinNumbers = new int[] { (int)PinName.A0, (int)PinName.A1, (int)PinName.A3, (int)PinName.D0, (int)PinName.D1, (int)PinName.D2, (int)PinName.D3, (int)PinName.D4, (int)PinName.D5, (int)PinName.D6, (int)PinName.D7, (int)PinName.D8, (int)PinName.D9, (int)PinName.D10, (int)PinName.D11, (int)PinName.D12, (int)PinName.D13, (int)PinName.D14, (int)PinName.D15, } }; public override PwmChannelInfoUwp GetPwmChannelInfo() { return m_pwmInfo; } } } ================================================ FILE: Zelig/BoardConfigurations/STM32F401/Board/HardwareModel/HardwareProvidersUwp/SpiProviderUwp.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // namespace Microsoft.Llilum.STM32F401 { using System; using Microsoft.Zelig.Runtime; using Chipset = Microsoft.CortexM4OnMBED; using ChipsetAbstration = Microsoft.DeviceModels.Chipset.CortexM4; public sealed class SpiProviderUwp : Microsoft.Zelig.Runtime.SpiProviderUwp { // NOTICE: Names are 1-indexed as per STM Board Description private static readonly string[] m_spiDevices = { "SPI1", "SPI2", "SPI3" }; public static readonly SpiChannelInfoUwp SPI0 = new SpiChannelInfoUwp() { ChipSelectLines = 1, MinFreq = 1000, MaxFreq = 30000000, Supports16 = true, ChannelInfoKernel = SpiProvider.SPI0, }; public static readonly SpiChannelInfoUwp SPI1 = new SpiChannelInfoUwp() { ChipSelectLines = 1, MinFreq = 1000, MaxFreq = 30000000, Supports16 = true, ChannelInfoKernel = SpiProvider.SPI1, }; public static readonly SpiChannelInfoUwp SPI2 = new SpiChannelInfoUwp() { ChipSelectLines = 1, MinFreq = 1000, MaxFreq = 30000000, Supports16 = true, ChannelInfoKernel = SpiProvider.SPI2, }; public override SpiChannelInfoUwp GetSpiChannelInfo(string busId) { switch (busId) { case "SPI1": return SPI0; case "SPI2": return SPI1; case "SPI3": return SPI2; default: return null; } } public override string[] GetSpiChannels() { return m_spiDevices; } } } ================================================ FILE: Zelig/BoardConfigurations/STM32F401/Board/HardwareModel/NVIC.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // namespace Microsoft.Llilum.STM32F401 { enum IRQn { /****** Cortex-M4 Processor Exceptions Numbers ****************************************************************/ NonMaskableInt_IRQn = -14, /*!< 2 Non Maskable Interrupt */ MemoryManagement_IRQn = -12, /*!< 4 Cortex-M4 Memory Management Interrupt */ BusFault_IRQn = -11, /*!< 5 Cortex-M4 Bus Fault Interrupt */ UsageFault_IRQn = -10, /*!< 6 Cortex-M4 Usage Fault Interrupt */ SVCall_IRQn = -5, /*!< 11 Cortex-M4 SV Call Interrupt */ DebugMonitor_IRQn = -4, /*!< 12 Cortex-M4 Debug Monitor Interrupt */ PendSV_IRQn = -2, /*!< 14 Cortex-M4 Pend SV Interrupt */ SysTick_IRQn = -1, /*!< 15 Cortex-M4 System Tick Interrupt */ /****** STM32 specific Interrupt Numbers **********************************************************************/ WWDG_IRQn = 0, /*!< Window WatchDog Interrupt */ PVD_IRQn = 1, /*!< PVD through EXTI Line detection Interrupt */ TAMP_STAMP_IRQn = 2, /*!< Tamper and TimeStamp interrupts through the EXTI line */ RTC_WKUP_IRQn = 3, /*!< RTC Wakeup interrupt through the EXTI line */ FLASH_IRQn = 4, /*!< FLASH global Interrupt */ RCC_IRQn = 5, /*!< RCC global Interrupt */ EXTI0_IRQn = 6, /*!< EXTI Line0 Interrupt */ EXTI1_IRQn = 7, /*!< EXTI Line1 Interrupt */ EXTI2_IRQn = 8, /*!< EXTI Line2 Interrupt */ EXTI3_IRQn = 9, /*!< EXTI Line3 Interrupt */ EXTI4_IRQn = 10, /*!< EXTI Line4 Interrupt */ DMA1_Stream0_IRQn = 11, /*!< DMA1 Stream 0 global Interrupt */ DMA1_Stream1_IRQn = 12, /*!< DMA1 Stream 1 global Interrupt */ DMA1_Stream2_IRQn = 13, /*!< DMA1 Stream 2 global Interrupt */ DMA1_Stream3_IRQn = 14, /*!< DMA1 Stream 3 global Interrupt */ DMA1_Stream4_IRQn = 15, /*!< DMA1 Stream 4 global Interrupt */ DMA1_Stream5_IRQn = 16, /*!< DMA1 Stream 5 global Interrupt */ DMA1_Stream6_IRQn = 17, /*!< DMA1 Stream 6 global Interrupt */ ADC_IRQn = 18, /*!< ADC1, ADC2 and ADC3 global Interrupts */ EXTI9_5_IRQn = 23, /*!< External Line[9:5] Interrupts */ TIM1_BRK_TIM9_IRQn = 24, /*!< TIM1 Break interrupt and TIM9 global interrupt */ TIM1_UP_TIM10_IRQn = 25, /*!< TIM1 Update Interrupt and TIM10 global interrupt */ TIM1_TRG_COM_TIM11_IRQn = 26, /*!< TIM1 Trigger and Commutation Interrupt and TIM11 global interrupt */ TIM1_CC_IRQn = 27, /*!< TIM1 Capture Compare Interrupt */ TIM2_IRQn = 28, /*!< TIM2 global Interrupt */ TIM3_IRQn = 29, /*!< TIM3 global Interrupt */ TIM4_IRQn = 30, /*!< TIM4 global Interrupt */ I2C1_EV_IRQn = 31, /*!< I2C1 Event Interrupt */ I2C1_ER_IRQn = 32, /*!< I2C1 Error Interrupt */ I2C2_EV_IRQn = 33, /*!< I2C2 Event Interrupt */ I2C2_ER_IRQn = 34, /*!< I2C2 Error Interrupt */ SPI1_IRQn = 35, /*!< SPI1 global Interrupt */ SPI2_IRQn = 36, /*!< SPI2 global Interrupt */ USART1_IRQn = 37, /*!< USART1 global Interrupt */ USART2_IRQn = 38, /*!< USART2 global Interrupt */ EXTI15_10_IRQn = 40, /*!< External Line[15:10] Interrupts */ RTC_Alarm_IRQn = 41, /*!< RTC Alarm (A and B) through EXTI Line Interrupt */ OTG_FS_WKUP_IRQn = 42, /*!< USB OTG FS Wakeup through EXTI line interrupt */ DMA1_Stream7_IRQn = 47, /*!< DMA1 Stream7 Interrupt */ SDIO_IRQn = 49, /*!< SDIO global Interrupt */ TIM5_IRQn = 50, /*!< TIM5 global Interrupt */ SPI3_IRQn = 51, /*!< SPI3 global Interrupt */ DMA2_Stream0_IRQn = 56, /*!< DMA2 Stream 0 global Interrupt */ DMA2_Stream1_IRQn = 57, /*!< DMA2 Stream 1 global Interrupt */ DMA2_Stream2_IRQn = 58, /*!< DMA2 Stream 2 global Interrupt */ DMA2_Stream3_IRQn = 59, /*!< DMA2 Stream 3 global Interrupt */ DMA2_Stream4_IRQn = 60, /*!< DMA2 Stream 4 global Interrupt */ OTG_FS_IRQn = 67, /*!< USB OTG FS global Interrupt */ DMA2_Stream5_IRQn = 68, /*!< DMA2 Stream 5 global interrupt */ DMA2_Stream6_IRQn = 69, /*!< DMA2 Stream 6 global interrupt */ DMA2_Stream7_IRQn = 70, /*!< DMA2 Stream 7 global interrupt */ USART6_IRQn = 71, /*!< USART6 global interrupt */ I2C3_EV_IRQn = 72, /*!< I2C3 event interrupt */ I2C3_ER_IRQn = 73, /*!< I2C3 error interrupt */ FPU_IRQn = 81, /*!< FPU global interrupt */ SPI4_IRQn = 84, /*!< SPI4 global Interrupt */ LAST = 85, } } ================================================ FILE: Zelig/BoardConfigurations/STM32F401/Board/HardwareModel/Peripherals.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // //#define ALLOW_PAUSE namespace Microsoft.Llilum.STM32F401 { using RT = Microsoft.Zelig.Runtime; using Chipset = Microsoft.CortexM3OnMBED; using CMSIS = Microsoft.DeviceModels.Chipset.CortexM; public sealed class Peripherals : Chipset.Peripherals { public override void Initialize() { base.Initialize( ); // // Peripherals exceptions all have same priority // for(int i = 0; i < (int)IRQn.LAST; ++i) { CMSIS.NVIC.SetPriority( i , RT.TargetPlatform.ARMv7.ProcessorARMv7M.c_Priority__GenericPeripherals ); } } } } ================================================ FILE: Zelig/BoardConfigurations/STM32F401/Board/HardwareModel/Processor.cs ================================================ // // Copyright ((c) Microsoft Corporation. All rights reserved. // namespace Microsoft.Llilum.STM32F401 { using System.Runtime.InteropServices; using RT = Microsoft.Zelig.Runtime; using ChipsetModel = Microsoft.CortexM4OnMBED; [RT.ProductFilter("Microsoft.Llilum.BoardConfigurations.STM32F411")] public sealed class Processor : Microsoft.CortexM4OnMBED.Processor { public new class Context : ChipsetModel.Processor.Context { public Context(RT.ThreadImpl owner) : base(owner) { } public override unsafe void SwitchTo( ) { // // BUGBUG: return to thread using VFP state as well // base.SwitchTo( ); } } // // Helper methods // [RT.Inline] public override void InitializeProcessor() { base.InitializeProcessor( ); DisableMPU( ); } [RT.Inline] public override Microsoft.Zelig.Runtime.Processor.Context AllocateProcessorContext(RT.ThreadImpl owner) { return new Context(owner); } //--// private unsafe void DisableMPU() { CUSTOM_STUB_STM32F4xx_DisableMPU( ); } [DllImport( "C" )] private static extern void CUSTOM_STUB_STM32F4xx_DisableMPU( ); } } ================================================ FILE: Zelig/BoardConfigurations/STM32F401/Board/Properties/AssemblyInfo.cs ================================================ using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; // General Information about an assembly is controlled through the following // set of attributes. Change these attribute values to modify the information // associated with an assembly. [assembly: AssemblyTitle("STM32F401")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("STM32F401")] [assembly: AssemblyCopyright("Copyright © 2016")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible(false)] // The following GUID is for the ID of the typelib if this project is exposed to COM [assembly: Guid("6194144a-f8b1-4525-829f-061df4a5645a")] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Build and Revision Numbers // by using the '*' as shown below: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("1.0.0.0")] [assembly: AssemblyFileVersion("1.0.0.0")] ================================================ FILE: Zelig/BoardConfigurations/STM32F401/Board/STM32F401.csproj ================================================  Debug AnyCPU {6194144A-F8B1-4525-829F-061DF4A5645A} Library Properties Microsoft.Llilum.STM32F401 STM32F401 v4.5 512 true $(LlilumBuildRoot)\Target\bin\$(Configuration)\ $(LlilumBuildRoot)\Target\bin\$(Configuration)\ $(LlilumBuildRoot)\Target\obj\$(MSBuildProjectName)\ $(LLILUM_SDK)\ZeligBuild\Target\bin\$(Configuration)\ $(LLILUM_SDK)\ZeligBuild\Target\bin\$(Configuration)\ $(LLILUM_SDK)\ZeligBuild\Target\obj\$(MSBuildProjectName)\ true full false DEBUG;TRACE prompt 4 true true true AllRules.ruleset AnyCPU false pdbonly true TRACE prompt 4 true true true AllRules.ruleset AnyCPU false {B8FE271A-CD41-435E-8766-4DB7609C1007} CortexM0OnCMSIS-Core {89EBDBB0-C81F-4611-B719-B385DF215F8D} CortexM0OnMBED {C3BFAFAD-A6C6-471D-A059-B3CB7E57A4AB} ModelForCortexM0 {e4c618af-1785-472e-a070-8068e20582eb} ModelForCortexM {186f31a3-ef89-4a25-b2d5-20070606aa01} ProductConfiguration {0b37e5ba-4839-4ec4-9e36-a96bcbea2400} CortexM3OnCMSIS-Core {0c522c6a-0f77-4af8-ad78-5b2415c98c51} CortexM3OnMBED {7fb3f581-742d-4e12-a36a-be172c574ab0} CortexM4OnCMSIS-Core {65c8eda6-ac24-4e18-a5b5-216e0f2c3906} CortexM4OnMBED {a30eb003-94f8-4a85-8da1-006f6810a7a4} ModelForCortexM3 {ca8a6d38-528b-4faa-89b6-8fa9178de55d} ModelForCortexM4 {186f31a3-ef89-4a25-b2d5-20070601aa01} CommonPC {186f31a3-ef89-4a25-b2d5-20061218aa01} Common {186f31a3-ef89-4a25-b2d5-20060509aa01} Kernel {20dc2cf5-8eed-4231-9743-6bab96be465c} LlilumOSAbstraction {186f31a3-ef89-4a25-b2d5-20060720aa01} TypeSystem {186F31A3-EF89-4A25-B2D5-20060501AA01} mscorlib False False $(LLILUM_SDK)\ZeligBuild\Target\bin\$(Configuration)\Microsoft.CortexM3OnCMSISCore.dll False $(LLILUM_SDK)\ZeligBuild\Target\bin\$(Configuration)\Microsoft.CortexM3OnMBED.dll False $(LLILUM_SDK)\ZeligBuild\Target\bin\$(Configuration)\Microsoft.DeviceModels.ModelForCortexM3.dll False $(LLILUM_SDK)\ZeligBuild\Target\bin\$(Configuration)\Microsoft.CortexM4OnCMSISCore.dll False $(LLILUM_SDK)\ZeligBuild\Target\bin\$(Configuration)\Microsoft.CortexM4OnMBED.dll False $(LLILUM_SDK)\ZeligBuild\Target\bin\$(Configuration)\Microsoft.DeviceModels.ModelForCortexM4.dll False $(LLILUM_SDK)\ZeligBuild\Target\bin\$(Configuration)\Microsoft.Zelig.LlilumOSAbstraction.dll False $(LLILUM_SDK)\ZeligBuild\Host\bin\$(Configuration)\Microsoft.Zelig.ProductConfiguration.dll False $(LLILUM_SDK)\ZeligBuild\Host\bin\$(Configuration)\Microsoft.Zelig.Runtime.dll False $(LLILUM_SDK)\ZeligBuild\Host\bin\$(Configuration)\Microsoft.Zelig.Runtime.Common.dll False $(LLILUM_SDK)\ZeligBuild\Host\bin\$(Configuration)\Microsoft.Zelig.Runtime.CommonPC.dll False $(LLILUM_SDK)\ZeligBuild\Host\bin\$(Configuration)\Microsoft.Zelig.Runtime.TypeSystem.dll $(LLILUM_SDK)\ZeligBuild\Target\bin\$(Configuration)\mscorlib.dll ================================================ FILE: Zelig/BoardConfigurations/STM32F401/Board/SystemServices/GarbageCollectionManager.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // namespace Microsoft.Llilum.STM32F401 { using Chipset = Microsoft.CortexM4OnMBED; public sealed class GarbageCollectionManager : Chipset.GarbageCollectionManager { } } ================================================ FILE: Zelig/BoardConfigurations/STM32F401/Board/SystemServices/ThreadManager.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // namespace Microsoft.Llilum.STM32F401 { using Chipset = Microsoft.CortexM4OnMBED; using LLOS = Zelig.LlilumOSAbstraction.API; public sealed class ThreadManager : Chipset.ThreadManager { private const int DefaultStackSizeSTM32F411 = 4 * 1024; //--// // // Helper Methods // public override int DefaultStackSize { get { uint stackSize = LLOS.RuntimeMemory.LLOS_MEMORY_GetDefaultManagedStackSize(); if(stackSize == 0) { return DefaultStackSizeSTM32F411; } return (int)stackSize; } } } } ================================================ FILE: Zelig/BoardConfigurations/STM32F401/Board/SystemServices/TimerPool.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // namespace Microsoft.Llilum.STM32F401 { using Chipset = Microsoft.CortexM4OnMBED; public sealed class TimerPool : Chipset.TimerPool { } } ================================================ FILE: Zelig/BoardConfigurations/STM32F401/Configuration/Configuration.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // namespace Microsoft.Llilum.BoardConfigurations { using Microsoft.Zelig.Runtime; using Microsoft.Zelig.Configuration.Environment; [DisplayName("STM32F401")] public sealed class STM32F401SoC : ProcessorCategory { [DependsOn(typeof(STM32F401SoC))] [DisplayName("Internal 96KB Static RAM")] [Defaults("BaseAddress", 0x20000000U)] [Defaults("SizeInBytes", 96 * 1024)] [Defaults("WordSize", 32)] [Defaults("WaitStates", 0)] [EnumDefaults("Characteristics", MemoryAttributes.RAM | MemoryAttributes.RandomAccessMemory | MemoryAttributes.InternalMemory | MemoryAttributes.ConfiguredAtEntryPoint)] public sealed class InternalRAM96KB : RamMemoryCategory { } [DependsOn(typeof(STM32F401SoC))] [DisplayName("Internal 512KB FLASH")] [Defaults("BaseAddress", 0x08000000U)] [Defaults("SizeInBytes", 512 * 1024)] [Defaults("WordSize", 32)] [Defaults("WaitStates", 0)] [EnumDefaults("Characteristics", MemoryAttributes.FLASH | MemoryAttributes.RandomAccessMemory | MemoryAttributes.InternalMemory | MemoryAttributes.ConfiguredAtEntryPoint)] public sealed class InternalFlash512KB : FlashMemoryCategory { } } //--// //--// //--// [DisplayName("Memory Map for STM32F401")] public sealed class STM32F401MemoryMap : MemoryMapCategory { [MergeEnumDefaults("Characteristics", MemoryAttributes.InternalMemory | MemoryAttributes.RandomAccessMemory | MemoryAttributes.ConfiguredAtEntryPoint)] [MemorySection(MemoryUsage.Stack | MemoryUsage.Heap | MemoryUsage.DataRW | MemoryUsage.Code)] [AllowedOptions(typeof(STM32F401SoC.InternalRAM96KB))] [Defaults("BaseAddress", 0x20000000U)] public RamMemoryCategory InternalRamChip; [MergeEnumDefaults("Characteristics", MemoryAttributes.InternalMemory | MemoryAttributes.RandomAccessMemory | MemoryAttributes.ConfiguredAtEntryPoint | MemoryAttributes.LoadedAtEntrypoint)] [MemorySection(MemoryUsage.Bootstrap | MemoryUsage.Code | MemoryUsage.DataRO | MemoryUsage.VectorsTable | MemoryUsage.Relocation)] [AllowedOptions(typeof(STM32F401SoC.InternalFlash512KB))] [Defaults("BaseAddress", 0x08000000U)] public FlashMemoryCategory InternalFlashChip; } //--// //--// //--// [DisplayName("STM32F401 MBED")] public sealed class STM32F401 : ProductCategory { [AllowedOptions(typeof(STM32F401SoC))] [Defaults("CoreClockFrequency", 84000000UL)] [Defaults("RealTimeClockFrequency", 1000000UL)] [Defaults("DefaultThreadPoolThreads", 2)] [Defaults("DefaultTimerPoolThreads", 2)] public STM32F401SoC Processor; //--// [AllowedOptions(typeof(STM32F401SoC.InternalRAM96KB))] [Defaults("BaseAddress", 0x20000000U)] public RamMemoryCategory InternalRam; [AllowedOptions(typeof(STM32F401SoC.InternalFlash512KB))] [Defaults("BaseAddress", 0x08000000U)] public FlashMemoryCategory InternalFlashChip; } //--// //--// //--// [DisplayName("LLVM Compilation for STM32F401")] [Defaults("Platform", typeof(Microsoft.Zelig.Configuration.Environment.Abstractions.Architectures.LlvmForArmV7M_VFP))] [Defaults("CallingConvention", typeof(Microsoft.Zelig.Configuration.Environment.Abstractions.Architectures.LlvmForArmV7MCallingConvention))] [Defaults("Product", typeof(STM32F401))] [Defaults("MemoryMap", typeof(STM32F401MemoryMap))] public sealed class STM32F401MBEDCompilationSetup : CompilationSetupCategory { } } ================================================ FILE: Zelig/BoardConfigurations/STM32F401/Configuration/Properties/AssemblyInfo.cs ================================================ using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; // General Information about an assembly is controlled through the following // set of attributes. Change these attribute values to modify the information // associated with an assembly. [assembly: AssemblyTitle("Microsoft.Llilum.BoardConfigurations.STM32L152")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("Microsoft.Llilum.BoardConfigurations.STM32L152")] [assembly: AssemblyCopyright("Copyright © 2016")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible(false)] // The following GUID is for the ID of the typelib if this project is exposed to COM [assembly: Guid("7f600371-17ab-41f2-96ab-39c8aa2389e1")] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Build and Revision Numbers // by using the '*' as shown below: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("1.0.0.0")] [assembly: AssemblyFileVersion("1.0.0.0")] ================================================ FILE: Zelig/BoardConfigurations/STM32F401/Configuration/STM32F401.FrontEndConfig ================================================ ### ### NOTE: This file can be used in the SDK AS-IS, or remove all instances of #~# to use as manual input for the FrontEnd project ### ### ### Location of the Zelig assemblies. ### #~#-HostAssemblyDir ..\..\..\..\ZeligBuild\Host\bin\Debug #~#-DeviceAssemblyDir ..\..\..\..\ZeligBuild\Target\bin\Debug -Architecture cortex-m4 #~#-CompilationSetupPath ..\..\..\..\ZeligBuild\Host\bin\Debug\Microsoft.Llilum.BoardConfigurations.STM32F401.dll -CompilationSetup Microsoft.Llilum.BoardConfigurations.STM32F401MBEDCompilationSetup ### ### We need to include this assembly to get the right drivers. ### -Reference Microsoft.CortexM4OnMBED -Reference Microsoft.CortexM4OnCMSISCore -Reference Microsoft.DeviceModels.ModelForCortexM4 -Reference STM32F401 ### ### Add compilation phases, in order ### #-CompilationPhaseDisabled ReduceNumberOfTemporaries #-CompilationPhaseDisabled TransformFinallyBlocksIntoTryBlocks #-CompilationPhaseDisabled ApplyClassExtensions #-CompilationPhaseDisabled PrepareImplementationOfInternalMethods #-CompilationPhaseDisabled CrossReferenceTypeSystem #-CompilationPhaseDisabled ApplyConfigurationSettings -CompilationPhaseDisabled ResourceManagerOptimizations #-CompilationPhaseDisabled HighLevelTransformations #-CompilationPhaseDisabled PropagateCompilationConstraints #-CompilationPhaseDisabled ComputeCallsClosure #-CompilationPhaseDisabled EstimateTypeSystemReduction #-CompilationPhaseDisabled CompleteImplementationOfInternalMethods #-CompilationPhaseDisabled ReduceTypeSystem -CompilationPhaseDisabled PrepareExternalMethods #-CompilationPhaseDisabled DetectNonImplementedInternalCalls #-CompilationPhaseDisabled OrderStaticConstructors #-CompilationPhaseDisabled LayoutTypes #-CompilationPhaseDisabled HighLevelToMidLevelConversion #-CompilationPhaseDisabled FromImplicitToExplicitExceptions #-CompilationPhaseDisabled ReferenceCountingGarbageCollection -CompilationPhaseDisabled MidLevelToLowLevelConversion -CompilationPhaseDisabled ConvertUnsupportedOperatorsToMethodCalls -CompilationPhaseDisabled ExpandAggregateTypes -CompilationPhaseDisabled SplitComplexOperators -CompilationPhaseDisabled FuseOperators #-CompilationPhaseDisabled Optimizations -CompilationPhaseDisabled ConvertToSSA -CompilationPhaseDisabled PrepareForRegisterAllocation -CompilationPhaseDisabled CollectRegisterAllocationConstraints -CompilationPhaseDisabled AllocateRegisters #-CompilationPhaseDisabled GenerateImage #-CompilationPhaseDisabled Done ### ### The program to compile. ### #~#..\..\..\..\ZeligBuild\Target\bin\Debug\Microsoft.Zelig.Test.mbed.Simple.exe ### ### Where to put the results. ### #~#-OutputName Microsoft.Zelig.Test.mbed.Simple #~#-OutputDir ..\..\..\..\LLVM2IR_results\mbed\simple #-DumpIR #-DumpIRpre #-DumpIRpost #-DumpIRXML #-DumpFlattenedCallGraph -DumpLLVMIR #-ReloadState #-DumpLLVMIR_TextRepresentation -MaxProcs 8 #~#-NoSDK -GenerateObj # examples of overriding opt.exe and llc arguments # the examples here are the same as the defaults but can be modified to suit a variety of test # scenarios and experimentations #-LlvmOptArgs "-verify-debug-info -verify-dom-info -verify-each -verify-loop-info -verify-regalloc -verify-region-info -march=thumb -mcpu=cortex-m3 -aa-eval -indvars -gvn -globaldce -adce -dce -tailcallopt -scalarrepl -mem2reg -ipconstprop -deadargelim -sccp -dce -ipsccp -dce -constmerge -scev-aa -targetlibinfo -irce -dse -dce -argpromotion -mem2reg -adce -mem2reg -globaldce -die -dce -dse" #-LlvmLlcArgs "-O2 -code-model=small -data-sections -relocation-model=pic -march=thumb -mcpu=cortex-m3 -filetype=obj -mtriple=thumbv7m-none-eabi" # While the compiler is pretty good at figuring out where the LLVM tools are from # current Environment variables or registry entires you can manually specify the # path to find the LLVM binaries. # note: Environment variabes (i.e %MY_VAR%) are supported and expanded as with all # options in the FrontendConfig files so you can specify a custom variable if needed #-LlvmBinPath \\netmfbld02\LLVM\3.7.0\build\Win32\Release\bin ================================================ FILE: Zelig/BoardConfigurations/STM32F401/Configuration/STM32F401Configuration.csproj ================================================  Debug AnyCPU {7F600371-17AB-41F2-96AB-39C8AA2389E1} Library Properties Microsoft.Llilum.BoardConfigurations Microsoft.Llilum.BoardConfigurations.STM32F401 v4.5 512 true true full false $(LlilumBuildRoot)\Host\bin\$(Configuration)\ DEBUG;TRACE prompt 4 pdbonly true $(LlilumBuildRoot)\Host\bin\$(Configuration)\ TRACE prompt 4 {186f31a3-ef89-4a25-b2d5-20070606aa01} ProductConfiguration {186f31a3-ef89-4a25-b2d5-20061218aa01} Common {186F31A3-EF89-4A25-B2D5-20060501AA01} mscorlib False $(LLILUM_SDK)\ZeligBuild\Host\bin\Debug\Microsoft.Zelig.ProductConfiguration.dll $(LLILUM_SDK)\ZeligBuild\Host\bin\Debug\Microsoft.Zelig.Runtime.Common.dll $(LLILUM_SDK)\ZeligBuild\Target\bin\Debug\mscorlib.dll ================================================ FILE: Zelig/BoardConfigurations/STM32F411/Board/HardwareModel/Board.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // namespace Microsoft.Llilum.STM32F411 { using System; using Chipset = Microsoft.CortexM4OnMBED; using ChipsetAbstration = Microsoft.DeviceModels.Chipset.CortexM4; public sealed class Board : Chipset.Board { internal const int GPIO_PORT_SHIFT = 12; // // Serial Ports // // NOTICE: Names are 1-indexed as per STM Board Description private static readonly string[] m_serialPorts = { "UART1", "UART2", "UART6" }; public static readonly ChipsetAbstration.Board.SerialPortInfo UART1 = new ChipsetAbstration.Board.SerialPortInfo() { TxPin = (int)PinName.PA_9 , RxPin = (int)PinName.PA_10, RtsPin = unchecked( (int)PinName.NC ), CtsPin = unchecked( (int)PinName.NC ), }; public static readonly ChipsetAbstration.Board.SerialPortInfo UART2 = new ChipsetAbstration.Board.SerialPortInfo() { TxPin = (int)PinName.USBTX, RxPin = (int)PinName.USBRX, RtsPin = unchecked( (int)PinName.NC ), CtsPin = unchecked( (int)PinName.NC ), }; public static readonly ChipsetAbstration.Board.SerialPortInfo UART6 = new ChipsetAbstration.Board.SerialPortInfo() { TxPin = (int)PinName.PA_11, RxPin = (int)PinName.PA_12, RtsPin = unchecked( (int)PinName.NC ), CtsPin = unchecked( (int)PinName.NC ), }; //--// private static readonly int[] s_ledPins = new int[] { (int)STM32F411.PinName.LED1, }; private static readonly int[] s_pwmPins = new int[] { (int)STM32F411.PinName.D3, }; // // Gpio discovery // public override int PinCount { get { return 48; } } public override int PinToIndex( int pin ) { return pin; } public override int NCPin { get { return -1; } } public override int[] LedPins { get { return s_ledPins; } } public override int[] PwmPins { get { return s_pwmPins; } } // // Serial Port // public override string[] GetSerialPorts() { return m_serialPorts; } public override ChipsetAbstration.Board.SerialPortInfo GetSerialPortInfo(string portName) { switch (portName) { case "UART1": return UART1; case "UART2": return UART2; case "UART6": return UART6; default: return null; } } // // System timer // public override int GetSystemTimerIRQ( ) { return (int)IRQn.TIM2_IRQn; } public override int GetSerialPortIRQ(string portName) { switch (portName) { case "UART1": return (int)IRQn.USART1_IRQn; case "UART2": return (int)IRQn.USART2_IRQn; case "UART6": return (int)IRQn.USART6_IRQn; default: throw new NotSupportedException(); } } } } ================================================ FILE: Zelig/BoardConfigurations/STM32F411/Board/HardwareModel/Device.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // namespace Microsoft.Llilum.STM32F411 { using RT = Microsoft.Zelig.Runtime; using LLOS = Zelig.LlilumOSAbstraction.API; public sealed class Device : Microsoft.CortexM4OnMBED.Device { [RT.MemoryUsage(RT.MemoryUsage.Stack, ContentsUninitialized = true, AllocateFromHighAddress = true)] static readonly uint[] s_bootstrapStackSTM32F411 = new uint[ 1024 / sizeof( uint ) ]; // // Access Methods // public override uint[] BootstrapStack { get { return s_bootstrapStackSTM32F411; } } } } ================================================ FILE: Zelig/BoardConfigurations/STM32F411/Board/HardwareModel/Drivers/ContextSwitchTimer.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // //#define TIMERS_SELF_TEST namespace Microsoft.Llilum.STM32F411.Drivers { using System.Runtime.CompilerServices; using RT = Microsoft.Zelig.Runtime; using Chipset = Microsoft.DeviceModels.Chipset.CortexM4.Drivers; public sealed class ContextSwitchTimer : Chipset.ContextSwitchTimer { protected override uint GetTicksForQuantumValue( uint ms ) { // STM32F411 uses the Core clock (100Mhz) for SysTick return (uint)( RT.Configuration.CoreClockFrequency / 1000 ) * ms; } } } ================================================ FILE: Zelig/BoardConfigurations/STM32F411/Board/HardwareModel/Drivers/InterruptController.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // namespace Microsoft.Llilum.STM32F411.Drivers { using Chipset = Microsoft.CortexM4OnMBED.Drivers; public sealed class InterruptController : Chipset.InterruptController { } } ================================================ FILE: Zelig/BoardConfigurations/STM32F411/Board/HardwareModel/Drivers/SystemTimer.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // namespace Microsoft.Llilum.STM32F411.Drivers { using Chipset = Microsoft.CortexM4OnMBED.Drivers; public sealed class SystemTimer : Chipset.SystemTimer { } } ================================================ FILE: Zelig/BoardConfigurations/STM32F411/Board/HardwareModel/GPIO.cs ================================================ // // Copyright ((c) Microsoft Corporation. All rights reserved. // namespace Microsoft.Llilum.STM32F411 { //--// public enum PinName : uint { PA_0 = 0x00, PA_1 = 0x01, PA_2 = 0x02, PA_3 = 0x03, PA_4 = 0x04, PA_5 = 0x05, PA_6 = 0x06, PA_7 = 0x07, PA_8 = 0x08, PA_9 = 0x09, PA_10 = 0x0A, PA_11 = 0x0B, PA_12 = 0x0C, PA_13 = 0x0D, PA_14 = 0x0E, PA_15 = 0x0F, PB_0 = 0x10, PB_1 = 0x11, PB_2 = 0x12, PB_3 = 0x13, PB_4 = 0x14, PB_5 = 0x15, PB_6 = 0x16, PB_7 = 0x17, PB_8 = 0x18, PB_9 = 0x19, PB_10 = 0x1A, PB_12 = 0x1C, PB_13 = 0x1D, PB_14 = 0x1E, PB_15 = 0x1F, PC_0 = 0x20, PC_1 = 0x21, PC_2 = 0x22, PC_3 = 0x23, PC_4 = 0x24, PC_5 = 0x25, PC_6 = 0x26, PC_7 = 0x27, PC_8 = 0x28, PC_9 = 0x29, PC_10 = 0x2A, PC_11 = 0x2B, PC_12 = 0x2C, PC_13 = 0x2D, PC_14 = 0x2E, PC_15 = 0x2F, // Unsure what these are. Modify PinToIndex to accomodate for these if needed PD_2 = 0x32, PH_0 = 0x70, PH_1 = 0x71, // Arduino connector namings A0 = PA_0, A1 = PA_1, A2 = PA_4, A3 = PB_0, A4 = PC_1, A5 = PC_0, D0 = PA_3, D1 = PA_2, D2 = PA_10, D3 = PB_3, D4 = PB_5, D5 = PB_4, D6 = PB_10, D7 = PA_8, D8 = PA_9, D9 = PC_7, D10 = PB_6, D11 = PA_7, D12 = PA_6, D13 = PA_5, D14 = PB_9, D15 = PB_8, // Generic signals namings LED1 = PA_5, LED2 = PA_5, LED3 = PA_5, LED4 = PA_5, USER_BUTTON = PC_13, SERIAL_TX = PA_2, SERIAL_RX = PA_3, USBTX = PA_2, USBRX = PA_3, I2C_SCL = PB_8, I2C_SDA = PB_9, SPI_MOSI = PA_7, SPI_MISO = PA_6, SPI_SCK = PA_5, SPI_CS = PB_6, PWM_OUT = PB_3, // Not connected NC = unchecked(0xFFFFFFFF), } } ================================================ FILE: Zelig/BoardConfigurations/STM32F411/Board/HardwareModel/HardwareProviders/GpioProvider.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // namespace Microsoft.Llilum.STM32F411.HardwareModel.HardwareProviders { using System; using Chipset = CortexM4OnMBED; public sealed class GpioProvider : Chipset.HardwareModel.GpioProvider { public override int GetGpioPinIRQNumber(int pinNumber) { int pinIndex = pinNumber & 0xF; switch (pinIndex) { case 0: return (int)IRQn.EXTI0_IRQn; case 1: return (int)IRQn.EXTI1_IRQn; case 2: return (int)IRQn.EXTI2_IRQn; case 3: return (int)IRQn.EXTI3_IRQn; case 4: return (int)IRQn.EXTI4_IRQn; case 5: case 6: case 7: case 8: case 9: return (int)IRQn.EXTI9_5_IRQn; case 10: case 11: case 12: case 13: case 14: case 15: return (int)IRQn.EXTI15_10_IRQn; default: throw new NotImplementedException(); } } } } ================================================ FILE: Zelig/BoardConfigurations/STM32F411/Board/HardwareModel/HardwareProviders/I2cProvider.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // namespace Microsoft.Llilum.STM32F411 { using System; using Microsoft.Zelig.Runtime; using Chipset = Microsoft.CortexM4OnMBED; using ChipsetAbstration = Microsoft.DeviceModels.Chipset.CortexM4; public sealed class I2cProvider : Chipset.HardwareModel.I2cProvider { public static readonly I2cChannelInfo I2C0 = new I2cChannelInfo() { SclPin = (int)PinName.I2C_SCL, SdaPin = (int)PinName.I2C_SDA, PortIndex = 0, }; public override I2cChannelInfo GetI2cChannelInfo(int id) { switch (id) { case 0: return I2C0; default: return null; } } } } ================================================ FILE: Zelig/BoardConfigurations/STM32F411/Board/HardwareModel/HardwareProviders/SpiProvider.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // namespace Microsoft.Llilum.STM32F411 { using System; using Microsoft.Zelig.Runtime; using Chipset = Microsoft.CortexM4OnMBED; using ChipsetAbstration = Microsoft.DeviceModels.Chipset.CortexM4; public sealed class SpiProvider : Chipset.HardwareModel.SpiProvider { public static readonly SpiChannelInfo SPI0 = new SpiChannelInfo() { Mosi = (int)PinName.PA_7, Miso = (int)PinName.PA_6, Sclk = (int)PinName.PA_5, DefaultChipSelect = unchecked((int)PinName.NC), SetupTime = 10, HoldTime = 10, ActiveLow = true, }; public static readonly SpiChannelInfo SPI1 = new SpiChannelInfo() { Mosi = (int)PinName.PB_15, Miso = (int)PinName.PB_14, Sclk = (int)PinName.PB_13, DefaultChipSelect = unchecked((int)PinName.NC), SetupTime = 10, HoldTime = 10, ActiveLow = true, }; public static readonly SpiChannelInfo SPI2 = new SpiChannelInfo() { Mosi = (int)PinName.PC_12, Miso = (int)PinName.PC_11, Sclk = (int)PinName.PC_10, DefaultChipSelect = unchecked((int)PinName.NC), SetupTime = 10, HoldTime = 10, ActiveLow = true, }; public override bool SpiBusySupported { get { return false; } } public override SpiChannelInfo GetSpiChannelInfo(int id) { switch (id) { case 0: return SPI0; case 1: return SPI1; case 2: return SPI2; default: return null; } } } } ================================================ FILE: Zelig/BoardConfigurations/STM32F411/Board/HardwareModel/HardwareProvidersUwp/AdcProviderUwp.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // namespace Microsoft.Llilum.STM32F411 { using System; using RT = Microsoft.Zelig.Runtime; using Chipset = Microsoft.CortexM4OnMBED; using ChipsetAbstration = Microsoft.DeviceModels.Chipset.CortexM4; public sealed class AdcProviderUwp : RT.AdcProviderUwp { private static readonly RT.AdcChannelInfoUwp m_adcInfo = new RT.AdcChannelInfoUwp() { MaxValue = UInt16.MaxValue, MinValue = 0, ResolutionInBits = 16, AdcPinNumbers = new int[] { (int)PinName.A0, (int)PinName.A1, (int)PinName.A2, (int)PinName.A3, (int)PinName.A4, (int)PinName.A5 } }; public override RT.AdcChannelInfoUwp GetAdcChannelInfo() { return m_adcInfo; } } } ================================================ FILE: Zelig/BoardConfigurations/STM32F411/Board/HardwareModel/HardwareProvidersUwp/I2cProviderUwp.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // namespace Microsoft.Llilum.STM32F411 { using System; using Microsoft.Zelig.Runtime; using Chipset = Microsoft.CortexM4OnMBED; using ChipsetAbstration = Microsoft.DeviceModels.Chipset.CortexM4; public sealed class I2cProviderUwp : Microsoft.Zelig.Runtime.I2cProviderUwp { private static string[] m_i2cChannels = { "I2C0" }; public override I2cChannelInfo GetI2cChannelInfo(string busId) { switch (busId) { case "I2C0": return I2cProvider.I2C0; default: return null; } } public override string[] GetI2cChannels() { return m_i2cChannels; } } } ================================================ FILE: Zelig/BoardConfigurations/STM32F411/Board/HardwareModel/HardwareProvidersUwp/PwmProviderUwp.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // namespace Microsoft.Llilum.STM32F411 { using System; using Microsoft.Zelig.Runtime; using Chipset = Microsoft.CortexM4OnMBED; using ChipsetAbstration = Microsoft.DeviceModels.Chipset.CortexM4; public sealed class PwmProviderUwp : Microsoft.Zelig.Runtime.PwmProviderUwp { private static readonly PwmChannelInfoUwp m_pwmInfo = new PwmChannelInfoUwp() { MaxFrequency = 1000000, MinFrequency = 0, PwmPinNumbers = new int[] { (int)PinName.A0, (int)PinName.A1, (int)PinName.A3, (int)PinName.D0, (int)PinName.D1, (int)PinName.D2, (int)PinName.D3, (int)PinName.D4, (int)PinName.D5, (int)PinName.D6, (int)PinName.D7, (int)PinName.D8, (int)PinName.D9, (int)PinName.D10, (int)PinName.D11, (int)PinName.D12, (int)PinName.D13, (int)PinName.D14, (int)PinName.D15, } }; public override PwmChannelInfoUwp GetPwmChannelInfo() { return m_pwmInfo; } } } ================================================ FILE: Zelig/BoardConfigurations/STM32F411/Board/HardwareModel/HardwareProvidersUwp/SpiProviderUwp.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // namespace Microsoft.Llilum.STM32F411 { using System; using Microsoft.Zelig.Runtime; using Chipset = Microsoft.CortexM4OnMBED; using ChipsetAbstration = Microsoft.DeviceModels.Chipset.CortexM4; public sealed class SpiProviderUwp : Microsoft.Zelig.Runtime.SpiProviderUwp { // NOTICE: Names are 1-indexed as per STM Board Description private static readonly string[] m_spiDevices = { "SPI1", "SPI2", "SPI3" }; public static readonly SpiChannelInfoUwp SPI0 = new SpiChannelInfoUwp() { ChipSelectLines = 1, MinFreq = 1000, MaxFreq = 30000000, Supports16 = true, ChannelInfoKernel = SpiProvider.SPI0, }; public static readonly SpiChannelInfoUwp SPI1 = new SpiChannelInfoUwp() { ChipSelectLines = 1, MinFreq = 1000, MaxFreq = 30000000, Supports16 = true, ChannelInfoKernel = SpiProvider.SPI1, }; public static readonly SpiChannelInfoUwp SPI2 = new SpiChannelInfoUwp() { ChipSelectLines = 1, MinFreq = 1000, MaxFreq = 30000000, Supports16 = true, ChannelInfoKernel = SpiProvider.SPI2, }; public override SpiChannelInfoUwp GetSpiChannelInfo(string busId) { switch (busId) { case "SPI1": return SPI0; case "SPI2": return SPI1; case "SPI3": return SPI2; default: return null; } } public override string[] GetSpiChannels() { return m_spiDevices; } } } ================================================ FILE: Zelig/BoardConfigurations/STM32F411/Board/HardwareModel/NVIC.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // namespace Microsoft.Llilum.STM32F411 { enum IRQn { /****** Cortex-M4 Processor Exceptions Numbers ****************************************************************/ NonMaskableInt_IRQn = -14, /*!< 2 Non Maskable Interrupt */ MemoryManagement_IRQn = -12, /*!< 4 Cortex-M4 Memory Management Interrupt */ BusFault_IRQn = -11, /*!< 5 Cortex-M4 Bus Fault Interrupt */ UsageFault_IRQn = -10, /*!< 6 Cortex-M4 Usage Fault Interrupt */ SVCall_IRQn = -5, /*!< 11 Cortex-M4 SV Call Interrupt */ DebugMonitor_IRQn = -4, /*!< 12 Cortex-M4 Debug Monitor Interrupt */ PendSV_IRQn = -2, /*!< 14 Cortex-M4 Pend SV Interrupt */ SysTick_IRQn = -1, /*!< 15 Cortex-M4 System Tick Interrupt */ /****** STM32 specific Interrupt Numbers **********************************************************************/ WWDG_IRQn = 0, /*!< Window WatchDog Interrupt */ PVD_IRQn = 1, /*!< PVD through EXTI Line detection Interrupt */ TAMP_STAMP_IRQn = 2, /*!< Tamper and TimeStamp interrupts through the EXTI line */ RTC_WKUP_IRQn = 3, /*!< RTC Wakeup interrupt through the EXTI line */ FLASH_IRQn = 4, /*!< FLASH global Interrupt */ RCC_IRQn = 5, /*!< RCC global Interrupt */ EXTI0_IRQn = 6, /*!< EXTI Line0 Interrupt */ EXTI1_IRQn = 7, /*!< EXTI Line1 Interrupt */ EXTI2_IRQn = 8, /*!< EXTI Line2 Interrupt */ EXTI3_IRQn = 9, /*!< EXTI Line3 Interrupt */ EXTI4_IRQn = 10, /*!< EXTI Line4 Interrupt */ DMA1_Stream0_IRQn = 11, /*!< DMA1 Stream 0 global Interrupt */ DMA1_Stream1_IRQn = 12, /*!< DMA1 Stream 1 global Interrupt */ DMA1_Stream2_IRQn = 13, /*!< DMA1 Stream 2 global Interrupt */ DMA1_Stream3_IRQn = 14, /*!< DMA1 Stream 3 global Interrupt */ DMA1_Stream4_IRQn = 15, /*!< DMA1 Stream 4 global Interrupt */ DMA1_Stream5_IRQn = 16, /*!< DMA1 Stream 5 global Interrupt */ DMA1_Stream6_IRQn = 17, /*!< DMA1 Stream 6 global Interrupt */ ADC_IRQn = 18, /*!< ADC1, ADC2 and ADC3 global Interrupts */ EXTI9_5_IRQn = 23, /*!< External Line[9:5] Interrupts */ TIM1_BRK_TIM9_IRQn = 24, /*!< TIM1 Break interrupt and TIM9 global interrupt */ TIM1_UP_TIM10_IRQn = 25, /*!< TIM1 Update Interrupt and TIM10 global interrupt */ TIM1_TRG_COM_TIM11_IRQn = 26, /*!< TIM1 Trigger and Commutation Interrupt and TIM11 global interrupt */ TIM1_CC_IRQn = 27, /*!< TIM1 Capture Compare Interrupt */ TIM2_IRQn = 28, /*!< TIM2 global Interrupt */ TIM3_IRQn = 29, /*!< TIM3 global Interrupt */ TIM4_IRQn = 30, /*!< TIM4 global Interrupt */ I2C1_EV_IRQn = 31, /*!< I2C1 Event Interrupt */ I2C1_ER_IRQn = 32, /*!< I2C1 Error Interrupt */ I2C2_EV_IRQn = 33, /*!< I2C2 Event Interrupt */ I2C2_ER_IRQn = 34, /*!< I2C2 Error Interrupt */ SPI1_IRQn = 35, /*!< SPI1 global Interrupt */ SPI2_IRQn = 36, /*!< SPI2 global Interrupt */ USART1_IRQn = 37, /*!< USART1 global Interrupt */ USART2_IRQn = 38, /*!< USART2 global Interrupt */ EXTI15_10_IRQn = 40, /*!< External Line[15:10] Interrupts */ RTC_Alarm_IRQn = 41, /*!< RTC Alarm (A and B) through EXTI Line Interrupt */ OTG_FS_WKUP_IRQn = 42, /*!< USB OTG FS Wakeup through EXTI line interrupt */ DMA1_Stream7_IRQn = 47, /*!< DMA1 Stream7 Interrupt */ SDIO_IRQn = 49, /*!< SDIO global Interrupt */ TIM5_IRQn = 50, /*!< TIM5 global Interrupt */ SPI3_IRQn = 51, /*!< SPI3 global Interrupt */ DMA2_Stream0_IRQn = 56, /*!< DMA2 Stream 0 global Interrupt */ DMA2_Stream1_IRQn = 57, /*!< DMA2 Stream 1 global Interrupt */ DMA2_Stream2_IRQn = 58, /*!< DMA2 Stream 2 global Interrupt */ DMA2_Stream3_IRQn = 59, /*!< DMA2 Stream 3 global Interrupt */ DMA2_Stream4_IRQn = 60, /*!< DMA2 Stream 4 global Interrupt */ OTG_FS_IRQn = 67, /*!< USB OTG FS global Interrupt */ DMA2_Stream5_IRQn = 68, /*!< DMA2 Stream 5 global interrupt */ DMA2_Stream6_IRQn = 69, /*!< DMA2 Stream 6 global interrupt */ DMA2_Stream7_IRQn = 70, /*!< DMA2 Stream 7 global interrupt */ USART6_IRQn = 71, /*!< USART6 global interrupt */ I2C3_EV_IRQn = 72, /*!< I2C3 event interrupt */ I2C3_ER_IRQn = 73, /*!< I2C3 error interrupt */ FPU_IRQn = 81, /*!< FPU global interrupt */ SPI4_IRQn = 84, /*!< SPI4 global Interrupt */ SPI5_IRQn = 85, /*!< SPI5 global Interrupt */ LAST = 86, } } ================================================ FILE: Zelig/BoardConfigurations/STM32F411/Board/HardwareModel/Peripherals.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // //#define ALLOW_PAUSE namespace Microsoft.Llilum.STM32F411 { using RT = Microsoft.Zelig.Runtime; using Chipset = Microsoft.CortexM3OnMBED; using CMSIS = Microsoft.DeviceModels.Chipset.CortexM; public sealed class Peripherals : Chipset.Peripherals { public override void Initialize() { base.Initialize( ); // // Peripherals exceptions all have same priority // for(int i = 0; i < (int)IRQn.LAST; ++i) { CMSIS.NVIC.SetPriority( i , RT.TargetPlatform.ARMv7.ProcessorARMv7M.c_Priority__GenericPeripherals ); } } } } ================================================ FILE: Zelig/BoardConfigurations/STM32F411/Board/HardwareModel/Processor.cs ================================================ // // Copyright ((c) Microsoft Corporation. All rights reserved. // namespace Microsoft.Llilum.STM32F411 { using System.Runtime.InteropServices; using RT = Microsoft.Zelig.Runtime; using ChipsetModel = Microsoft.CortexM4OnMBED; [RT.ProductFilter("Microsoft.Llilum.BoardConfigurations.STM32F411")] public sealed class Processor : Microsoft.CortexM4OnMBED.Processor { public new class Context : ChipsetModel.Processor.Context { public Context(RT.ThreadImpl owner) : base(owner) { } public override unsafe void SwitchTo( ) { // // BUGBUG: return to thread using VFP state as well // base.SwitchTo( ); } } // // Helper methods // [RT.Inline] public override void InitializeProcessor() { base.InitializeProcessor( ); DisableMPU( ); } [RT.Inline] public override Microsoft.Zelig.Runtime.Processor.Context AllocateProcessorContext(RT.ThreadImpl owner) { return new Context(owner); } //--// private unsafe void DisableMPU() { CUSTOM_STUB_STM32F4xx_DisableMPU( ); } [DllImport( "C" )] private static extern void CUSTOM_STUB_STM32F4xx_DisableMPU( ); } } ================================================ FILE: Zelig/BoardConfigurations/STM32F411/Board/Properties/AssemblyInfo.cs ================================================ using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; // General Information about an assembly is controlled through the following // set of attributes. Change these attribute values to modify the information // associated with an assembly. [assembly: AssemblyTitle("STM32F411")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("STM32F411")] [assembly: AssemblyCopyright("Copyright © 2015")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible(false)] // The following GUID is for the ID of the typelib if this project is exposed to COM [assembly: Guid("dd4371de-85a8-49aa-b939-10e03b7ed3c9")] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Build and Revision Numbers // by using the '*' as shown below: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("1.0.0.0")] [assembly: AssemblyFileVersion("1.0.0.0")] ================================================ FILE: Zelig/BoardConfigurations/STM32F411/Board/STM32F411.csproj ================================================  Debug AnyCPU {DD4371DE-85A8-49AA-B939-10E03B7ED3C9} Library Properties Microsoft.Llilum.STMF411 STM32F411 v4.5 512 true $(LlilumBuildRoot)\Target\bin\$(Configuration)\ $(LlilumBuildRoot)\Target\bin\$(Configuration)\ $(LlilumBuildRoot)\Target\obj\$(MSBuildProjectName)\ $(LLILUM_SDK)\ZeligBuild\Target\bin\$(Configuration)\ $(LLILUM_SDK)\ZeligBuild\Target\bin\$(Configuration)\ $(LLILUM_SDK)\ZeligBuild\Target\obj\$(MSBuildProjectName)\ true full false DEBUG;TRACE prompt 4 true true true AllRules.ruleset AnyCPU false pdbonly true TRACE prompt 4 true true true AllRules.ruleset AnyCPU false {186f31a3-ef89-4a25-b2d5-20070606aa01} ProductConfiguration {b8fe271a-cd41-435e-8766-4db7609c1007} CortexM0OnCMSIS-Core {89ebdbb0-c81f-4611-b719-b385df215f8d} CortexM0OnMBED {0b37e5ba-4839-4ec4-9e36-a96bcbea2400} CortexM3OnCMSIS-Core {0c522c6a-0f77-4af8-ad78-5b2415c98c51} CortexM3OnMBED {7fb3f581-742d-4e12-a36a-be172c574ab0} CortexM4OnCMSIS-Core {65c8eda6-ac24-4e18-a5b5-216e0f2c3906} CortexM4OnMBED {c3bfafad-a6c6-471d-a059-b3cb7e57a4ab} ModelForCortexM0 {a30eb003-94f8-4a85-8da1-006f6810a7a4} ModelForCortexM3 {ca8a6d38-528b-4faa-89b6-8fa9178de55d} ModelForCortexM4 {e4c618af-1785-472e-a070-8068e20582eb} ModelForCortexM {186f31a3-ef89-4a25-b2d5-20070601aa01} CommonPC {186f31a3-ef89-4a25-b2d5-20061218aa01} Common {186f31a3-ef89-4a25-b2d5-20060509aa01} Kernel {20dc2cf5-8eed-4231-9743-6bab96be465c} LlilumOSAbstraction {186f31a3-ef89-4a25-b2d5-20060720aa01} TypeSystem {186F31A3-EF89-4A25-B2D5-20060501AA01} mscorlib False False $(LLILUM_SDK)\ZeligBuild\Target\bin\$(Configuration)\Microsoft.DeviceModels.ModelForCortexM.dll False $(LLILUM_SDK)\ZeligBuild\Target\bin\$(Configuration)\Microsoft.DeviceModels.ModelForCortexM0.dll False $(LLILUM_SDK)\ZeligBuild\Target\bin\$(Configuration)\Microsoft.CortexM0OnCMSISCore.dll False $(LLILUM_SDK)\ZeligBuild\Target\bin\$(Configuration)\Microsoft.CortexM0OnMBED.dll False $(LLILUM_SDK)\ZeligBuild\Target\bin\$(Configuration)\Microsoft.CortexM3OnCMSISCore.dll False $(LLILUM_SDK)\ZeligBuild\Target\bin\$(Configuration)\Microsoft.CortexM3OnMBED.dll False $(LLILUM_SDK)\ZeligBuild\Target\bin\$(Configuration)\Microsoft.DeviceModels.ModelForCortexM3.dll False $(LLILUM_SDK)\ZeligBuild\Target\bin\$(Configuration)\Microsoft.CortexM4OnCMSISCore.dll False $(LLILUM_SDK)\ZeligBuild\Target\bin\$(Configuration)\Microsoft.CortexM4OnMBED.dll False $(LLILUM_SDK)\ZeligBuild\Target\bin\$(Configuration)\Microsoft.DeviceModels.ModelForCortexM4.dll False $(LLILUM_SDK)\ZeligBuild\Target\bin\$(Configuration)\Microsoft.Zelig.LlilumOSAbstraction.dll False $(LLILUM_SDK)\ZeligBuild\Host\bin\$(Configuration)\Microsoft.Zelig.ProductConfiguration.dll False $(LLILUM_SDK)\ZeligBuild\Host\bin\$(Configuration)\Microsoft.Zelig.Runtime.dll False $(LLILUM_SDK)\ZeligBuild\Host\bin\$(Configuration)\Microsoft.Zelig.Runtime.Common.dll False $(LLILUM_SDK)\ZeligBuild\Host\bin\$(Configuration)\Microsoft.Zelig.Runtime.CommonPC.dll False $(LLILUM_SDK)\ZeligBuild\Host\bin\$(Configuration)\Microsoft.Zelig.Runtime.TypeSystem.dll $(LLILUM_SDK)\ZeligBuild\Target\bin\$(Configuration)\mscorlib.dll ================================================ FILE: Zelig/BoardConfigurations/STM32F411/Board/SystemServices/GarbageCollectionManager.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // namespace Microsoft.Llilum.STM32F411 { using Chipset = Microsoft.CortexM4OnMBED; public sealed class GarbageCollectionManager : Chipset.GarbageCollectionManager { } } ================================================ FILE: Zelig/BoardConfigurations/STM32F411/Board/SystemServices/ThreadManager.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // namespace Microsoft.Llilum.STM32F411 { using Chipset = Microsoft.CortexM4OnMBED; using LLOS = Zelig.LlilumOSAbstraction.API; public sealed class ThreadManager : Chipset.ThreadManager { private const int DefaultStackSizeSTM32F411 = 4 * 1024; //--// // // Helper Methods // public override int DefaultStackSize { get { uint stackSize = LLOS.RuntimeMemory.LLOS_MEMORY_GetDefaultManagedStackSize(); if(stackSize == 0) { return DefaultStackSizeSTM32F411; } return (int)stackSize; } } } } ================================================ FILE: Zelig/BoardConfigurations/STM32F411/Board/SystemServices/TimerPool.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // namespace Microsoft.Llilum.STM32F411 { using Chipset = Microsoft.CortexM4OnMBED; public sealed class TimerPool : Chipset.TimerPool { } } ================================================ FILE: Zelig/BoardConfigurations/STM32F411/Configuration/Configuration.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // namespace Microsoft.Llilum.BoardConfigurations { using Microsoft.Zelig.Runtime; using Microsoft.Zelig.Configuration.Environment; [DisplayName("STM32F411")] public sealed class STM32F411SoC : ProcessorCategory { [DependsOn(typeof(STM32F411SoC))] [DisplayName("Internal 128KB Static RAM")] [Defaults("BaseAddress", 0x20000000U)] [Defaults("SizeInBytes", 128 * 1024)] [Defaults("WordSize", 32)] [Defaults("WaitStates", 0)] [EnumDefaults("Characteristics", MemoryAttributes.RAM | MemoryAttributes.RandomAccessMemory | MemoryAttributes.InternalMemory | MemoryAttributes.ConfiguredAtEntryPoint)] public sealed class InternalRAM128KB : RamMemoryCategory { } [DependsOn(typeof(STM32F411SoC))] [DisplayName("Internal 512KB FLASH")] [Defaults("BaseAddress", 0x08000000U)] [Defaults("SizeInBytes", 512 * 1024)] [Defaults("WordSize", 32)] [Defaults("WaitStates", 0)] [EnumDefaults("Characteristics", MemoryAttributes.FLASH | MemoryAttributes.RandomAccessMemory | MemoryAttributes.InternalMemory | MemoryAttributes.ConfiguredAtEntryPoint)] public sealed class InternalFlash512KB : FlashMemoryCategory { } } //--// //--// //--// [DisplayName("Memory Map for STM32F411")] public sealed class STM32F411MemoryMap : MemoryMapCategory { [MergeEnumDefaults("Characteristics", MemoryAttributes.InternalMemory | MemoryAttributes.RandomAccessMemory | MemoryAttributes.ConfiguredAtEntryPoint)] [MemorySection(MemoryUsage.Stack | MemoryUsage.Heap | MemoryUsage.DataRW | MemoryUsage.Code)] [AllowedOptions(typeof(STM32F411SoC.InternalRAM128KB))] [Defaults("BaseAddress", 0x20000000U)] public RamMemoryCategory InternalRamChip; [MergeEnumDefaults("Characteristics", MemoryAttributes.InternalMemory | MemoryAttributes.RandomAccessMemory | MemoryAttributes.ConfiguredAtEntryPoint | MemoryAttributes.LoadedAtEntrypoint)] [MemorySection(MemoryUsage.Bootstrap | MemoryUsage.Code | MemoryUsage.DataRO | MemoryUsage.VectorsTable | MemoryUsage.Relocation)] [AllowedOptions(typeof(STM32F411SoC.InternalFlash512KB))] [Defaults("BaseAddress", 0x08000000U)] public FlashMemoryCategory InternalFlashChip; } //--// //--// //--// [DisplayName("STM32F411 MBED")] public sealed class STM32F411 : ProductCategory { [AllowedOptions(typeof(STM32F411SoC))] [Defaults("CoreClockFrequency" , 100000000UL)] [Defaults("RealTimeClockFrequency" , 1000000UL)] [Defaults("DefaultThreadPoolThreads", 2)] [Defaults("DefaultTimerPoolThreads" , 2)] public STM32F411SoC Processor; //--// [AllowedOptions(typeof(STM32F411SoC.InternalRAM128KB))] [Defaults("BaseAddress", 0x20000000U)] public RamMemoryCategory InternalRam; [AllowedOptions(typeof(STM32F411SoC.InternalFlash512KB))] [Defaults("BaseAddress", 0x08000000U)] public FlashMemoryCategory InternalFlashChip; } //--// //--// //--// [DisplayName("LLVM Compilation for STM32F411")] [Defaults("Platform", typeof(Microsoft.Zelig.Configuration.Environment.Abstractions.Architectures.LlvmForArmV7M_VFP))] [Defaults("CallingConvention", typeof(Microsoft.Zelig.Configuration.Environment.Abstractions.Architectures.LlvmForArmV7MCallingConvention))] [Defaults("Product", typeof(STM32F411))] [Defaults("MemoryMap", typeof(STM32F411MemoryMap))] public sealed class STM32F411MBEDCompilationSetup : CompilationSetupCategory { } } ================================================ FILE: Zelig/BoardConfigurations/STM32F411/Configuration/Properties/AssemblyInfo.cs ================================================ using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; // General Information about an assembly is controlled through the following // set of attributes. Change these attribute values to modify the information // associated with an assembly. [assembly: AssemblyTitle("Microsoft.Llilum.BoardConfigurations.STM32L152")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("Microsoft.Llilum.BoardConfigurations.STM32L152")] [assembly: AssemblyCopyright("Copyright © 2015")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible(false)] // The following GUID is for the ID of the typelib if this project is exposed to COM [assembly: Guid("9b0edb62-1e62-492d-b807-a8501eee8400")] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Build and Revision Numbers // by using the '*' as shown below: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("1.0.0.0")] [assembly: AssemblyFileVersion("1.0.0.0")] ================================================ FILE: Zelig/BoardConfigurations/STM32F411/Configuration/STM32F411.FrontEndConfig ================================================ ### ### NOTE: This file can be used in the SDK AS-IS, or remove all instances of #~# to use as manual input for the FrontEnd project ### ### ### Location of the Zelig assemblies. ### #~#-HostAssemblyDir ..\..\..\..\ZeligBuild\Host\bin\Debug #~#-DeviceAssemblyDir ..\..\..\..\ZeligBuild\Target\bin\Debug -Architecture cortex-m4 #~#-CompilationSetupPath ..\..\..\..\ZeligBuild\Host\bin\Debug\Microsoft.Llilum.BoardConfigurations.STM32F411.dll -CompilationSetup Microsoft.Llilum.BoardConfigurations.STM32F411MBEDCompilationSetup ### ### We need to include this assembly to get the right drivers. ### -Reference Microsoft.CortexM4OnMBED -Reference Microsoft.CortexM4OnCMSISCore -Reference Microsoft.DeviceModels.ModelForCortexM4 -Reference STM32F411 ### ### Add compilation phases, in order ### #-CompilationPhaseDisabled ReduceNumberOfTemporaries #-CompilationPhaseDisabled TransformFinallyBlocksIntoTryBlocks #-CompilationPhaseDisabled ApplyClassExtensions #-CompilationPhaseDisabled PrepareImplementationOfInternalMethods #-CompilationPhaseDisabled CrossReferenceTypeSystem #-CompilationPhaseDisabled ApplyConfigurationSettings -CompilationPhaseDisabled ResourceManagerOptimizations #-CompilationPhaseDisabled HighLevelTransformations #-CompilationPhaseDisabled PropagateCompilationConstraints #-CompilationPhaseDisabled ComputeCallsClosure #-CompilationPhaseDisabled EstimateTypeSystemReduction #-CompilationPhaseDisabled CompleteImplementationOfInternalMethods #-CompilationPhaseDisabled ReduceTypeSystem -CompilationPhaseDisabled PrepareExternalMethods #-CompilationPhaseDisabled DetectNonImplementedInternalCalls #-CompilationPhaseDisabled OrderStaticConstructors #-CompilationPhaseDisabled LayoutTypes #-CompilationPhaseDisabled HighLevelToMidLevelConversion #-CompilationPhaseDisabled FromImplicitToExplicitExceptions #-CompilationPhaseDisabled ReferenceCountingGarbageCollection -CompilationPhaseDisabled MidLevelToLowLevelConversion -CompilationPhaseDisabled ConvertUnsupportedOperatorsToMethodCalls -CompilationPhaseDisabled ExpandAggregateTypes -CompilationPhaseDisabled SplitComplexOperators -CompilationPhaseDisabled FuseOperators #-CompilationPhaseDisabled Optimizations -CompilationPhaseDisabled ConvertToSSA -CompilationPhaseDisabled PrepareForRegisterAllocation -CompilationPhaseDisabled CollectRegisterAllocationConstraints -CompilationPhaseDisabled AllocateRegisters #-CompilationPhaseDisabled GenerateImage #-CompilationPhaseDisabled Done ### ### The program to compile. ### #~#..\..\..\..\ZeligBuild\Target\bin\Debug\Microsoft.Zelig.Test.mbed.Simple.exe ### ### Where to put the results. ### #~#-OutputName Microsoft.Zelig.Test.mbed.Simple #~#-OutputDir ..\..\..\..\LLVM2IR_results\mbed\simple ### ### Dumps and diagnostics ### #-DumpIRBeforePhase ReduceNumberOfTemporaries TransformFinallyBlocksIntoTryBlocks ApplyClassExtensions #-DumpIRBeforePhase All #-DumpIR #-DumpIRpre #-DumpIRpost #-DumpIRXML #-DumpFlattenedCallGraph -DumpLLVMIR #-ReloadState #-DumpLLVMIR_TextRepresentation -MaxProcs 8 #~#-NoSDK ### ### LLVM CodeGeneration ### -GenerateObj # examples of overriding opt.exe and llc arguments # the examples here are the same as the defaults but can be modified to suit a variety of test # scenarios and experimentations #-LlvmOptArgs "-verify-debug-info -verify-dom-info -verify-each -verify-loop-info -verify-regalloc -verify-region-info -march=thumb -mcpu=cortex-m3 -aa-eval -indvars -gvn -globaldce -adce -dce -tailcallopt -scalarrepl -mem2reg -ipconstprop -deadargelim -sccp -dce -ipsccp -dce -constmerge -scev-aa -targetlibinfo -irce -dse -dce -argpromotion -mem2reg -adce -mem2reg -globaldce -die -dce -dse" #-LlvmLlcArgs "-O2 -code-model=small -data-sections -relocation-model=pic -march=thumb -mcpu=cortex-m3 -filetype=obj -mtriple=thumbv7m-none-eabi" # While the compiler is pretty good at figuring out where the LLVM tools are from # current Environment variables or registry entires you can manually specify the # path to find the LLVM binaries. # note: Environment variabes (i.e %MY_VAR%) are supported and expanded as with all # options in the FrontendConfig files so you can specify a custom variable if needed #-LlvmBinPath \\netmfbld02\LLVM\3.7.0\build\Win32\Release\bin ================================================ FILE: Zelig/BoardConfigurations/STM32F411/Configuration/STM32F411Configuration.csproj ================================================  Debug AnyCPU {9B0EDB62-1E62-492D-B807-A8501EEE8400} Library Properties Microsoft.Llilum.BoardConfigurations Microsoft.Llilum.BoardConfigurations.STM32F411 v4.5 512 true true full false $(LlilumBuildRoot)\Host\bin\$(Configuration)\ DEBUG;TRACE prompt 4 pdbonly true $(LlilumBuildRoot)\Host\bin\$(Configuration)\ TRACE prompt 4 {186f31a3-ef89-4a25-b2d5-20070606aa01} ProductConfiguration {186f31a3-ef89-4a25-b2d5-20061218aa01} Common {186F31A3-EF89-4A25-B2D5-20060501AA01} mscorlib False $(LLILUM_SDK)\ZeligBuild\Host\bin\Debug\Microsoft.Zelig.ProductConfiguration.dll $(LLILUM_SDK)\ZeligBuild\Host\bin\Debug\Microsoft.Zelig.Runtime.Common.dll $(LLILUM_SDK)\ZeligBuild\Target\bin\Debug\mscorlib.dll ================================================ FILE: Zelig/BoardConfigurations/STM32L152/Board/HardwareModel/Board.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // namespace Microsoft.Llilum.STM32L152 { using System; using Chipset = Microsoft.CortexM3OnMBED; using ChipsetAbstration = Microsoft.DeviceModels.Chipset.CortexM3; public sealed class Board : Chipset.Board { // // Serial Ports // private static readonly string[] m_serialPorts = { "UART2", "UART3", "UART4", "UART5" }; public static readonly ChipsetAbstration.Board.SerialPortInfo UART2 = new ChipsetAbstration.Board.SerialPortInfo() { TxPin = (int)PinName.USBTX, RxPin = (int)PinName.USBRX, RtsPin = unchecked( (int)PinName.NC ), CtsPin = unchecked( (int)PinName.NC ), }; public static readonly ChipsetAbstration.Board.SerialPortInfo UART3 = new ChipsetAbstration.Board.SerialPortInfo() { TxPin = (int)PinName.PB_10, RxPin = (int)PinName.PB_11, RtsPin = unchecked( (int)PinName.NC ), CtsPin = unchecked( (int)PinName.NC ), }; public static readonly ChipsetAbstration.Board.SerialPortInfo UART4 = new ChipsetAbstration.Board.SerialPortInfo() { TxPin = (int)PinName.PC_10, RxPin = (int)PinName.PC_11, RtsPin = unchecked( (int)PinName.NC ), CtsPin = unchecked( (int)PinName.NC ), }; public static readonly ChipsetAbstration.Board.SerialPortInfo UART5 = new ChipsetAbstration.Board.SerialPortInfo() { TxPin = (int)PinName.PC_12, RxPin = (int)PinName.PD_2 , RtsPin = unchecked( (int)PinName.NC ), CtsPin = unchecked( (int)PinName.NC ), }; //--// private static readonly int[] s_ledPins = new int[] { (int)STM32L152.PinName.LED1, }; private static readonly int[] s_pwmPins = new int[] { (int)STM32L152.PinName.D3, }; // // Gpio discovery // public override int PinCount { get { return 64; } } public override int PinToIndex( int pin ) { return pin; } public override int NCPin { get { return -1; } } public override int[] LedPins { get { return s_ledPins; } } public override int[] PwmPins { get { return s_pwmPins; } } // // Serial Ports // public override string[] GetSerialPorts() { return m_serialPorts; } public override ChipsetAbstration.Board.SerialPortInfo GetSerialPortInfo(string portName) { switch (portName) { case "UART2": return UART2; case "UART3": return UART3; case "UART4": return UART4; case "UART5": return UART5; default: return null; } } public override int GetSerialPortIRQ(string portName) { switch (portName) { case "UART2": return (int)IRQn.USART2_IRQn; case "UART3": return (int)IRQn.USART3_IRQn; case "UART4": return (int)IRQn.UART4_IRQn; case "UART5": return (int)IRQn.UART5_IRQn; default: throw new NotSupportedException(); } } // // System timer // public override int GetSystemTimerIRQ( ) { return (int)IRQn.TIM5_IRQn; } } } ================================================ FILE: Zelig/BoardConfigurations/STM32L152/Board/HardwareModel/Device.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // namespace Microsoft.Llilum.STM32L152 { using Chipset = Microsoft.CortexM3OnMBED; public sealed class Device : Chipset.Device { } } ================================================ FILE: Zelig/BoardConfigurations/STM32L152/Board/HardwareModel/Drivers/ContextSwitchTimer.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // //#define TIMERS_SELF_TEST namespace Microsoft.Llilum.STM32L152.Drivers { using Chipset = Microsoft.DeviceModels.Chipset.CortexM3.Drivers; public sealed class ContextSwitchTimer : Chipset.ContextSwitchTimer { } } ================================================ FILE: Zelig/BoardConfigurations/STM32L152/Board/HardwareModel/Drivers/InterruptController.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // namespace Microsoft.Llilum.STM32L152.Drivers { using Chipset = Microsoft.CortexM3OnMBED.Drivers; public sealed class InterruptController : Chipset.InterruptController { } } ================================================ FILE: Zelig/BoardConfigurations/STM32L152/Board/HardwareModel/Drivers/SystemTimer.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // namespace Microsoft.Llilum.STM32L152.Drivers { using Chipset = Microsoft.CortexM3OnMBED.Drivers; public sealed class SystemTimer : Chipset.SystemTimer { } } ================================================ FILE: Zelig/BoardConfigurations/STM32L152/Board/HardwareModel/GPIO.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // namespace Microsoft.Llilum.STM32L152 { //--// public enum PinDirection { PIN_INPUT, PIN_OUTPUT } public enum PinMode { PullUp = 0, PullDown = 3, PullNone = 2, Repeater = 1, OpenDrain = 4, PullDefault = PullDown } public enum PinName : uint { PA_0 = 0x00, PA_1 = 0x01, PA_2 = 0x02, PA_3 = 0x03, PA_4 = 0x04, PA_5 = 0x05, PA_6 = 0x06, PA_7 = 0x07, PA_8 = 0x08, PA_9 = 0x09, PA_10 = 0x0A, PA_11 = 0x0B, PA_12 = 0x0C, PA_13 = 0x0D, PA_14 = 0x0E, PA_15 = 0x0F, PB_0 = 0x10, PB_1 = 0x11, PB_2 = 0x12, PB_3 = 0x13, PB_4 = 0x14, PB_5 = 0x15, PB_6 = 0x16, PB_7 = 0x17, PB_8 = 0x18, PB_9 = 0x19, PB_10 = 0x1A, PB_11 = 0x1B, PB_12 = 0x1C, PB_13 = 0x1D, PB_14 = 0x1E, PB_15 = 0x1F, PC_0 = 0x20, PC_1 = 0x21, PC_2 = 0x22, PC_3 = 0x23, PC_4 = 0x24, PC_5 = 0x25, PC_6 = 0x26, PC_7 = 0x27, PC_8 = 0x28, PC_9 = 0x29, PC_10 = 0x2A, PC_11 = 0x2B, PC_12 = 0x2C, PC_13 = 0x2D, PC_14 = 0x2E, PC_15 = 0x2F, PD_2 = 0x32, PH_0 = 0x70, PH_1 = 0x71, // Arduino connector namings A0 = PA_0, A1 = PA_1, A2 = PA_4, A3 = PB_0, A4 = PC_1, A5 = PC_0, D0 = PA_3, D1 = PA_2, D2 = PA_10, D3 = PB_3, D4 = PB_5, D5 = PB_4, D6 = PB_10, D7 = PA_8, D8 = PA_9, D9 = PC_7, D10 = PB_6, D11 = PA_7, D12 = PA_6, D13 = PA_5, D14 = PB_9, D15 = PB_8, // Generic signals namings LED1 = PA_5, LED2 = PA_5, LED3 = PA_5, LED4 = PA_5, USER_BUTTON = PC_13, SERIAL_TX = PA_2, SERIAL_RX = PA_3, USBTX = PA_2, USBRX = PA_3, I2C_SCL = PB_8, I2C_SDA = PB_9, SPI_MOSI = PA_7, SPI_MISO = PA_6, SPI_SCK = PA_5, SPI_CS = PB_6, PWM_OUT = PB_3, // Not connected NC = 0xFFFFFFFF, } } ================================================ FILE: Zelig/BoardConfigurations/STM32L152/Board/HardwareModel/HardwareProviders/GpioProvider.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // namespace Microsoft.Llilum.STM32L152.HardwareModel.HardwareProviders { using Chipset = CortexM3OnMBED; public sealed class GpioProvider : Chipset.HardwareModel.GpioProvider { public override int GetGpioPinIRQNumber(int pinNumber) { int pinIndex = pinNumber % 16; switch (pinIndex) { case 0: return (int)IRQn.EXTI0_IRQn; case 1: return (int)IRQn.EXTI1_IRQn; case 2: return (int)IRQn.EXTI2_IRQn; case 3: return (int)IRQn.EXTI3_IRQn; case 4: return (int)IRQn.EXTI4_IRQn; case 5: case 6: case 7: case 8: case 9: return (int)IRQn.EXTI9_5_IRQn; case 10: case 11: case 12: case 13: case 14: case 15: return (int)IRQn.EXTI15_10_IRQn; default: throw new System.InvalidOperationException(); } } } } ================================================ FILE: Zelig/BoardConfigurations/STM32L152/Board/HardwareModel/HardwareProviders/I2cProvider.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // namespace Microsoft.Llilum.STM32L152 { using System; using Microsoft.Zelig.Runtime; using Chipset = Microsoft.CortexM3OnMBED; using ChipsetAbstration = Microsoft.DeviceModels.Chipset.CortexM3; public sealed class I2cProvider : Chipset.HardwareModel.I2cProvider { public static readonly I2cChannelInfo I2C0 = new I2cChannelInfo() { SdaPin = (int)PinName.PB_9, SclPin = (int)PinName.PB_8, PortIndex = 0, }; public static readonly I2cChannelInfo I2C1 = new I2cChannelInfo() { SdaPin = (int)PinName.PB_10, SclPin = (int)PinName.PB_6, PortIndex = 1, }; public override I2cChannelInfo GetI2cChannelInfo(int id) { switch (id) { case 0: return I2C0; case 1: return I2C1; default: return null; } } } } ================================================ FILE: Zelig/BoardConfigurations/STM32L152/Board/HardwareModel/HardwareProviders/SpiProvider.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // namespace Microsoft.Llilum.STM32L152 { using System; using Microsoft.Zelig.Runtime; using Chipset = Microsoft.CortexM3OnMBED; using ChipsetAbstration = Microsoft.DeviceModels.Chipset.CortexM3; public sealed class SpiProvider : Chipset.HardwareModel.SpiProvider { public static readonly SpiChannelInfo SPI0 = new SpiChannelInfo() { Mosi = (int)PinName.PA_7, Miso = (int)PinName.PA_6, Sclk = (int)PinName.PA_5, DefaultChipSelect = unchecked((int)PinName.NC), SetupTime = 0, HoldTime = 0, ActiveLow = true, }; public static readonly SpiChannelInfo SPI1 = new SpiChannelInfo() { Mosi = (int)PinName.PB_5, Miso = (int)PinName.PB_4, Sclk = (int)PinName.PB_3, DefaultChipSelect = unchecked((int)PinName.NC), SetupTime = 10, HoldTime = 10, ActiveLow = true, }; public override bool SpiBusySupported { get { return true; } } public override SpiChannelInfo GetSpiChannelInfo(int id) { switch (id) { case 0: return SPI0; case 1: return SPI1; default: return null; } } } } ================================================ FILE: Zelig/BoardConfigurations/STM32L152/Board/HardwareModel/HardwareProvidersUwp/AdcProviderUwp.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // namespace Microsoft.Llilum.STM32L152 { using System; using Microsoft.Zelig.Runtime; using Chipset = Microsoft.CortexM3OnMBED; using ChipsetAbstration = Microsoft.DeviceModels.Chipset.CortexM3; public sealed class AdcProviderUwp : Microsoft.Zelig.Runtime.AdcProviderUwp { private static readonly AdcChannelInfoUwp m_adcInfo = new AdcChannelInfoUwp() { MaxValue = UInt16.MaxValue, MinValue = 0, ResolutionInBits = 16, AdcPinNumbers = new int[] {(int)PinName.A0, (int)PinName.A1, (int)PinName.A2, (int)PinName.A3, (int)PinName.A4, (int)PinName.A5 } }; public override AdcChannelInfoUwp GetAdcChannelInfo() { return m_adcInfo; } } } ================================================ FILE: Zelig/BoardConfigurations/STM32L152/Board/HardwareModel/HardwareProvidersUwp/I2cProviderUwp.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // namespace Microsoft.Llilum.STM32L152 { using System; using Microsoft.Zelig.Runtime; using Chipset = Microsoft.CortexM3OnMBED; using ChipsetAbstration = Microsoft.DeviceModels.Chipset.CortexM3; public sealed class I2cProviderUwp : Microsoft.Zelig.Runtime.I2cProviderUwp { private static string[] m_i2cChannels = { "I2C0", "I2C1" }; public override I2cChannelInfo GetI2cChannelInfo(string busId) { switch (busId) { case "I2C0": return I2cProvider.I2C0; case "I2C1": return I2cProvider.I2C1; default: return null; } } public override string[] GetI2cChannels() { return m_i2cChannels; } } } ================================================ FILE: Zelig/BoardConfigurations/STM32L152/Board/HardwareModel/HardwareProvidersUwp/PwmProviderUwp.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // namespace Microsoft.Llilum.STM32L152 { using System; using Microsoft.Zelig.Runtime; using Chipset = Microsoft.CortexM3OnMBED; using ChipsetAbstration = Microsoft.DeviceModels.Chipset.CortexM3; public sealed class PwmProviderUwp : Microsoft.Zelig.Runtime.PwmProviderUwp { private static readonly PwmChannelInfoUwp m_pwmInfo = new PwmChannelInfoUwp() { MaxFrequency = 1000000, MinFrequency = 0, PwmPinNumbers = new int[] { (int)PinName.D0, (int)PinName.D1, (int)PinName.D3, (int)PinName.D4, (int)PinName.D5, (int)PinName.D6, (int)PinName.D9, (int)PinName.D10, (int)PinName.D11, (int)PinName.D12, (int)PinName.D13, } }; public override PwmChannelInfoUwp GetPwmChannelInfo() { return m_pwmInfo; } } } ================================================ FILE: Zelig/BoardConfigurations/STM32L152/Board/HardwareModel/HardwareProvidersUwp/SpiProviderUwp.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // namespace Microsoft.Llilum.STM32L152 { using System; using Microsoft.Zelig.Runtime; using Chipset = Microsoft.CortexM3OnMBED; using ChipsetAbstration = Microsoft.DeviceModels.Chipset.CortexM3; public sealed class SpiProviderUwp : Microsoft.Zelig.Runtime.SpiProviderUwp { private static readonly string[] m_spiDevices = { "SPI0", "SPI1" }; public static readonly SpiChannelInfoUwp SPI0 = new SpiChannelInfoUwp() { ChipSelectLines = 1, MinFreq = 1000, MaxFreq = 30000000, Supports16 = true, ChannelInfoKernel = SpiProvider.SPI0, }; public static readonly SpiChannelInfoUwp SPI1 = new SpiChannelInfoUwp() { ChipSelectLines = 1, MinFreq = 1000, MaxFreq = 30000000, Supports16 = true, ChannelInfoKernel = SpiProvider.SPI1, }; public override SpiChannelInfoUwp GetSpiChannelInfo(string busId) { switch (busId) { case "SPI0": return SPI0; case "SPI1": return SPI1; default: return null; } } public override string[] GetSpiChannels() { return m_spiDevices; } } } ================================================ FILE: Zelig/BoardConfigurations/STM32L152/Board/HardwareModel/NVIC.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // namespace Microsoft.Llilum.STM32L152 { enum IRQn { /****** Cortex-M3 Processor Exceptions Numbers ******************************************************/ NonMaskableInt_IRQn = -14, /*!< 2 Non Maskable Interrupt */ MemoryManagement_IRQn = -12, /*!< 4 Cortex-M3 Memory Management Interrupt */ BusFault_IRQn = -11, /*!< 5 Cortex-M3 Bus Fault Interrupt */ UsageFault_IRQn = -10, /*!< 6 Cortex-M3 Usage Fault Interrupt */ SVC_IRQn = -5, /*!< 11 Cortex-M3 SV Call Interrupt */ DebugMonitor_IRQn = -4, /*!< 12 Cortex-M3 Debug Monitor Interrupt */ PendSV_IRQn = -2, /*!< 14 Cortex-M3 Pend SV Interrupt */ SysTick_IRQn = -1, /*!< 15 Cortex-M3 System Tick Interrupt */ /****** STM32L specific Interrupt Numbers ***********************************************************/ WWDG_IRQn = 0, /*!< Window WatchDog Interrupt */ PVD_IRQn = 1, /*!< PVD through EXTI Line detection Interrupt */ TAMPER_STAMP_IRQn = 2, /*!< Tamper and TimeStamp interrupts through the EXTI line */ RTC_WKUP_IRQn = 3, /*!< RTC Wakeup Timer through EXTI Line Interrupt */ FLASH_IRQn = 4, /*!< FLASH global Interrupt */ RCC_IRQn = 5, /*!< RCC global Interrupt */ EXTI0_IRQn = 6, /*!< EXTI Line0 Interrupt */ EXTI1_IRQn = 7, /*!< EXTI Line1 Interrupt */ EXTI2_IRQn = 8, /*!< EXTI Line2 Interrupt */ EXTI3_IRQn = 9, /*!< EXTI Line3 Interrupt */ EXTI4_IRQn = 10, /*!< EXTI Line4 Interrupt */ DMA1_Channel1_IRQn = 11, /*!< DMA1 Channel 1 global Interrupt */ DMA1_Channel2_IRQn = 12, /*!< DMA1 Channel 2 global Interrupt */ DMA1_Channel3_IRQn = 13, /*!< DMA1 Channel 3 global Interrupt */ DMA1_Channel4_IRQn = 14, /*!< DMA1 Channel 4 global Interrupt */ DMA1_Channel5_IRQn = 15, /*!< DMA1 Channel 5 global Interrupt */ DMA1_Channel6_IRQn = 16, /*!< DMA1 Channel 6 global Interrupt */ DMA1_Channel7_IRQn = 17, /*!< DMA1 Channel 7 global Interrupt */ ADC1_IRQn = 18, /*!< ADC1 global Interrupt */ USB_HP_IRQn = 19, /*!< USB High Priority Interrupt */ USB_LP_IRQn = 20, /*!< USB Low Priority Interrupt */ DAC_IRQn = 21, /*!< DAC Interrupt */ COMP_IRQn = 22, /*!< Comparator through EXTI Line Interrupt */ EXTI9_5_IRQn = 23, /*!< External Line[9:5] Interrupts */ LCD_IRQn = 24, /*!< LCD Interrupt */ TIM9_IRQn = 25, /*!< TIM9 global Interrupt */ TIM10_IRQn = 26, /*!< TIM10 global Interrupt */ TIM11_IRQn = 27, /*!< TIM11 global Interrupt */ TIM2_IRQn = 28, /*!< TIM2 global Interrupt */ TIM3_IRQn = 29, /*!< TIM3 global Interrupt */ TIM4_IRQn = 30, /*!< TIM4 global Interrupt */ I2C1_EV_IRQn = 31, /*!< I2C1 Event Interrupt */ I2C1_ER_IRQn = 32, /*!< I2C1 Error Interrupt */ I2C2_EV_IRQn = 33, /*!< I2C2 Event Interrupt */ I2C2_ER_IRQn = 34, /*!< I2C2 Error Interrupt */ SPI1_IRQn = 35, /*!< SPI1 global Interrupt */ SPI2_IRQn = 36, /*!< SPI2 global Interrupt */ USART1_IRQn = 37, /*!< USART1 global Interrupt */ USART2_IRQn = 38, /*!< USART2 global Interrupt */ USART3_IRQn = 39, /*!< USART3 global Interrupt */ EXTI15_10_IRQn = 40, /*!< External Line[15:10] Interrupts */ RTC_Alarm_IRQn = 41, /*!< RTC Alarm through EXTI Line Interrupt */ USB_FS_WKUP_IRQn = 42, /*!< USB FS WakeUp from suspend through EXTI Line Interrupt */ TIM6_IRQn = 43, /*!< TIM6 global Interrupt */ TIM7_IRQn = 44, /*!< TIM7 global Interrupt */ TIM5_IRQn = 46, /*!< TIM5 global Interrupt */ SPI3_IRQn = 47, /*!< SPI3 global Interrupt */ UART4_IRQn = 48, /*!< UART4 global Interrupt */ UART5_IRQn = 49, /*!< UART5 global Interrupt */ DMA2_Channel1_IRQn = 50, /*!< DMA2 Channel 1 global Interrupt */ DMA2_Channel2_IRQn = 51, /*!< DMA2 Channel 2 global Interrupt */ DMA2_Channel3_IRQn = 52, /*!< DMA2 Channel 3 global Interrupt */ DMA2_Channel4_IRQn = 53, /*!< DMA2 Channel 4 global Interrupt */ DMA2_Channel5_IRQn = 54, /*!< DMA2 Channel 5 global Interrupt */ COMP_ACQ_IRQn = 56, /*!< Comparator Channel Acquisition global Interrupt */ LAST = 57, } } ================================================ FILE: Zelig/BoardConfigurations/STM32L152/Board/HardwareModel/Peripherals.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // //#define ALLOW_PAUSE namespace Microsoft.Llilum.STM32L152 { using RT = Microsoft.Zelig.Runtime; using Chipset = Microsoft.CortexM3OnMBED; using CMSIS = Microsoft.DeviceModels.Chipset.CortexM; public sealed class Peripherals : Chipset.Peripherals { public override void Initialize() { base.Initialize( ); // // Peripherals exceptions all have same priority // for(int i = 0; i < (int)IRQn.LAST; ++i) { CMSIS.NVIC.SetPriority( i , RT.TargetPlatform.ARMv7.ProcessorARMv7M.c_Priority__GenericPeripherals ); } } } } ================================================ FILE: Zelig/BoardConfigurations/STM32L152/Board/HardwareModel/Processor.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // namespace Microsoft.Llilum.STM32L152 { using RT = Microsoft.Zelig.Runtime; using ChipsetModel = Microsoft.CortexM3OnMBED; public sealed class Processor : Microsoft.CortexM3OnMBED.Processor { [RT.ProductFilter("Microsoft.Llilum.BoardConfigurations.STM32L152")] public new class Context : ChipsetModel.Processor.Context { public Context(RT.ThreadImpl owner) : base(owner) { } } // // Helper methods // [RT.Inline] public override RT.Processor.Context AllocateProcessorContext(RT.ThreadImpl owner) { return new Context(owner); } } } ================================================ FILE: Zelig/BoardConfigurations/STM32L152/Board/Properties/AssemblyInfo.cs ================================================ using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; // General Information about an assembly is controlled through the following // set of attributes. Change these attribute values to modify the information // associated with an assembly. [assembly: AssemblyTitle("STM32L152")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("STM32L152")] [assembly: AssemblyCopyright("Copyright © 2015")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible(false)] // The following GUID is for the ID of the typelib if this project is exposed to COM [assembly: Guid("f0229144-f7c4-4456-8442-5e816c6e8fbc")] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Build and Revision Numbers // by using the '*' as shown below: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("1.0.0.0")] [assembly: AssemblyFileVersion("1.0.0.0")] ================================================ FILE: Zelig/BoardConfigurations/STM32L152/Board/STM32L152.csproj ================================================  Debug AnyCPU {F0229144-F7C4-4456-8442-5E816C6E8FBC} Library Properties Microsoft.Llilum.STM32L152 STM32L152 v4.5 512 true $(LlilumBuildRoot)\Target\bin\$(Configuration)\ $(LlilumBuildRoot)\Target\bin\$(Configuration)\ $(LlilumBuildRoot)\Target\obj\$(MSBuildProjectName)\ $(LLILUM_SDK)\ZeligBuild\Target\bin\$(Configuration)\ $(LLILUM_SDK)\ZeligBuild\Target\bin\$(Configuration)\ $(LLILUM_SDK)\ZeligBuild\Target\obj\$(MSBuildProjectName)\ true full false DEBUG;TRACE prompt 4 true true true AllRules.ruleset AnyCPU false pdbonly true TRACE prompt 4 true true true AllRules.ruleset AnyCPU false {186f31a3-ef89-4a25-b2d5-20070606aa01} ProductConfiguration {b8fe271a-cd41-435e-8766-4db7609c1007} CortexM0OnCMSIS-Core {89ebdbb0-c81f-4611-b719-b385df215f8d} CortexM0OnMBED {0b37e5ba-4839-4ec4-9e36-a96bcbea2400} CortexM3OnCMSIS-Core {0c522c6a-0f77-4af8-ad78-5b2415c98c51} CortexM3OnMBED {c3bfafad-a6c6-471d-a059-b3cb7e57a4ab} ModelForCortexM0 {a30eb003-94f8-4a85-8da1-006f6810a7a4} ModelForCortexM3 {e4c618af-1785-472e-a070-8068e20582eb} ModelForCortexM {186f31a3-ef89-4a25-b2d5-20070601aa01} CommonPC {186f31a3-ef89-4a25-b2d5-20061218aa01} Common {186f31a3-ef89-4a25-b2d5-20060509aa01} Kernel {20dc2cf5-8eed-4231-9743-6bab96be465c} LlilumOSAbstraction {186f31a3-ef89-4a25-b2d5-20060720aa01} TypeSystem {186F31A3-EF89-4A25-B2D5-20060501AA01} mscorlib False False $(LLILUM_SDK)\ZeligBuild\Target\bin\$(Configuration)\Microsoft.DeviceModels.ModelForCortexM.dll False $(LLILUM_SDK)\ZeligBuild\Target\bin\$(Configuration)\Microsoft.DeviceModels.ModelForCortexM0.dll False $(LLILUM_SDK)\ZeligBuild\Target\bin\$(Configuration)\Microsoft.CortexM0OnCMSISCore.dll False $(LLILUM_SDK)\ZeligBuild\Target\bin\$(Configuration)\Microsoft.CortexM0OnMBED.dll False $(LLILUM_SDK)\ZeligBuild\Target\bin\$(Configuration)\Microsoft.CortexM3OnCMSISCore.dll False $(LLILUM_SDK)\ZeligBuild\Target\bin\$(Configuration)\Microsoft.CortexM3OnMBED.dll False $(LLILUM_SDK)\ZeligBuild\Target\bin\$(Configuration)\Microsoft.DeviceModels.ModelForCortexM3.dll False $(LLILUM_SDK)\ZeligBuild\Target\bin\$(Configuration)\Microsoft.Zelig.LlilumOSAbstraction.dll False $(LLILUM_SDK)\ZeligBuild\Host\bin\$(Configuration)\Microsoft.Zelig.ProductConfiguration.dll False $(LLILUM_SDK)\ZeligBuild\Host\bin\$(Configuration)\Microsoft.Zelig.Runtime.dll False $(LLILUM_SDK)\ZeligBuild\Host\bin\$(Configuration)\Microsoft.Zelig.Runtime.Common.dll False $(LLILUM_SDK)\ZeligBuild\Host\bin\$(Configuration)\Microsoft.Zelig.Runtime.CommonPC.dll False $(LLILUM_SDK)\ZeligBuild\Host\bin\$(Configuration)\Microsoft.Zelig.Runtime.TypeSystem.dll $(LLILUM_SDK)\ZeligBuild\Target\bin\$(Configuration)\mscorlib.dll ================================================ FILE: Zelig/BoardConfigurations/STM32L152/Board/SystemServices/GarbageCollectionManager.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // namespace Microsoft.Llilum.STM32L152 { using Chipset = Microsoft.CortexM3OnMBED; public sealed class GarbageCollectionManager : Chipset.GarbageCollectionManager { } } ================================================ FILE: Zelig/BoardConfigurations/STM32L152/Board/SystemServices/ThreadManager.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // namespace Microsoft.Llilum.STM32L152 { using RT = Microsoft.Zelig.Runtime; using Chipset = Microsoft.CortexM3OnMBED; public sealed class ThreadManager : Chipset.ThreadManager { private const int DefaultStackSizeSTM32L152 = (4 * 512) / sizeof( uint ); //--// // // Helper Methods // public override int DefaultStackSize { get { return DefaultStackSizeSTM32L152; } } } } ================================================ FILE: Zelig/BoardConfigurations/STM32L152/Board/SystemServices/TimerPool.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // namespace Microsoft.Llilum.STM32L152 { using Chipset = Microsoft.CortexM3OnMBED; public sealed class TimerPool : Chipset.TimerPool { } } ================================================ FILE: Zelig/BoardConfigurations/STM32L152/Configuration/Configuration.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // namespace Microsoft.Llilum.BoardConfigurations { using Microsoft.Zelig.Runtime; using Microsoft.Zelig.Configuration.Environment; [DisplayName("STM32L152")] public sealed class STM32L152SoC : ProcessorCategory { [DependsOn(typeof(STM32L152SoC))] [DisplayName("Internal 80KB Static RAM")] [Defaults("BaseAddress", 0x20000000)] [Defaults("SizeInBytes", 80 * 1024)] [Defaults("WordSize", 32)] [Defaults("WaitStates", 0)] [EnumDefaults("Characteristics", MemoryAttributes.RAM | MemoryAttributes.RandomAccessMemory | MemoryAttributes.InternalMemory | MemoryAttributes.ConfiguredAtEntryPoint)] public sealed class InternalRAM80KB : RamMemoryCategory { } [DependsOn(typeof(STM32L152SoC))] [DisplayName("Internal 512KB FLASH")] [Defaults("BaseAddress", 0x00000000)] [Defaults("SizeInBytes", 512 * 1024)] [Defaults("WordSize", 32)] [Defaults("WaitStates", 0)] [EnumDefaults("Characteristics", MemoryAttributes.FLASH | MemoryAttributes.RandomAccessMemory | MemoryAttributes.InternalMemory | MemoryAttributes.ConfiguredAtEntryPoint)] public sealed class InternalFlash512KB : FlashMemoryCategory { } } //--// //--// //--// [DisplayName("Memory Map for STM32L152")] public sealed class STM32L152MemoryMap : MemoryMapCategory { [MergeEnumDefaults("Characteristics", MemoryAttributes.InternalMemory | MemoryAttributes.RandomAccessMemory | MemoryAttributes.ConfiguredAtEntryPoint)] [MemorySection(MemoryUsage.Stack | MemoryUsage.Heap | MemoryUsage.DataRW | MemoryUsage.Code)] [AllowedOptions(typeof(STM32L152SoC.InternalRAM80KB))] [Defaults("BaseAddress", 0x20000000U)] public RamMemoryCategory InternalRamChip; [MergeEnumDefaults("Characteristics", MemoryAttributes.InternalMemory | MemoryAttributes.RandomAccessMemory | MemoryAttributes.ConfiguredAtEntryPoint | MemoryAttributes.LoadedAtEntrypoint)] [MemorySection(MemoryUsage.Bootstrap | MemoryUsage.Code | MemoryUsage.DataRO | MemoryUsage.VectorsTable | MemoryUsage.Relocation)] [AllowedOptions(typeof(STM32L152SoC.InternalFlash512KB))] [Defaults("BaseAddress", 0x00000000U)] public FlashMemoryCategory InternalFlashChip; } //--// //--// //--// [DisplayName("STM32L152 MBED")] public sealed class STM32L152 : ProductCategory { [AllowedOptions(typeof(STM32L152SoC))] [Defaults("CoreClockFrequency", 32000000UL)] [Defaults("RealTimeClockFrequency", 1000000UL)] public STM32L152SoC Processor; //--// [AllowedOptions(typeof(STM32L152SoC.InternalRAM80KB))] [Defaults("BaseAddress", 0x20000000U)] public RamMemoryCategory InternalRam; [AllowedOptions(typeof(STM32L152SoC.InternalFlash512KB))] [Defaults("BaseAddress", 0x00000000U)] public FlashMemoryCategory InternalFlashChip; } //--// //--// //--// [DisplayName("LLVM Compilation for STM32L152")] [Defaults("Platform", typeof(Microsoft.Zelig.Configuration.Environment.Abstractions.Architectures.LlvmForArmV7M))] [Defaults("CallingConvention", typeof(Microsoft.Zelig.Configuration.Environment.Abstractions.Architectures.LlvmForArmV7MCallingConvention))] [Defaults("Product", typeof(STM32L152))] [Defaults("MemoryMap", typeof(STM32L152MemoryMap))] public sealed class STM32L152MBEDCompilationSetup : CompilationSetupCategory { } } ================================================ FILE: Zelig/BoardConfigurations/STM32L152/Configuration/Properties/AssemblyInfo.cs ================================================ using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; // General Information about an assembly is controlled through the following // set of attributes. Change these attribute values to modify the information // associated with an assembly. [assembly: AssemblyTitle("Microsoft.Llilum.BoardConfigurations.STM32L152")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("Microsoft.Llilum.BoardConfigurations.STM32L152")] [assembly: AssemblyCopyright("Copyright © 2015")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible(false)] // The following GUID is for the ID of the typelib if this project is exposed to COM [assembly: Guid("f222e0d3-0fff-41f4-91ee-400c4e4e043d")] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Build and Revision Numbers // by using the '*' as shown below: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("1.0.0.0")] [assembly: AssemblyFileVersion("1.0.0.0")] ================================================ FILE: Zelig/BoardConfigurations/STM32L152/Configuration/STM32L152.FrontEndConfig ================================================ ### ### NOTE: This file can be used in the SDK AS-IS, or remove all instances of #~# to use as manual input for the FrontEnd project ### ### ### Location of the Zelig assemblies. ### #~#-HostAssemblyDir ..\..\..\..\ZeligBuild\Host\bin\Debug #~#-DeviceAssemblyDir ..\..\..\..\ZeligBuild\Target\bin\Debug -Architecture cortex-m3 #~#-CompilationSetupPath ..\..\..\..\ZeligBuild\Host\bin\Debug\Microsoft.Llilum.BoardConfigurations.STM32L152.dll -CompilationSetup Microsoft.Llilum.BoardConfigurations.STM32L152MBEDCompilationSetup ### ### We need to include this assembly to get the right drivers. ### -Reference Microsoft.CortexM3OnMBED -Reference Microsoft.CortexM3OnCMSISCore -Reference Microsoft.DeviceModels.ModelForCortexM3 -Reference STM32L152 ### ### Add compilation phases, in order ### #-CompilationPhaseDisabled ReduceNumberOfTemporaries #-CompilationPhaseDisabled TransformFinallyBlocksIntoTryBlocks #-CompilationPhaseDisabled ApplyClassExtensions #-CompilationPhaseDisabled PrepareImplementationOfInternalMethods #-CompilationPhaseDisabled CrossReferenceTypeSystem #-CompilationPhaseDisabled ApplyConfigurationSettings -CompilationPhaseDisabled ResourceManagerOptimizations #-CompilationPhaseDisabled HighLevelTransformations #-CompilationPhaseDisabled PropagateCompilationConstraints #-CompilationPhaseDisabled ComputeCallsClosure #-CompilationPhaseDisabled EstimateTypeSystemReduction #-CompilationPhaseDisabled CompleteImplementationOfInternalMethods #-CompilationPhaseDisabled ReduceTypeSystem -CompilationPhaseDisabled PrepareExternalMethods #-CompilationPhaseDisabled DetectNonImplementedInternalCalls #-CompilationPhaseDisabled OrderStaticConstructors #-CompilationPhaseDisabled LayoutTypes #-CompilationPhaseDisabled HighLevelToMidLevelConversion #-CompilationPhaseDisabled FromImplicitToExplicitExceptions #-CompilationPhaseDisabled ReferenceCountingGarbageCollection -CompilationPhaseDisabled MidLevelToLowLevelConversion -CompilationPhaseDisabled ConvertUnsupportedOperatorsToMethodCalls -CompilationPhaseDisabled ExpandAggregateTypes -CompilationPhaseDisabled SplitComplexOperators -CompilationPhaseDisabled FuseOperators #-CompilationPhaseDisabled Optimizations -CompilationPhaseDisabled ConvertToSSA -CompilationPhaseDisabled PrepareForRegisterAllocation -CompilationPhaseDisabled CollectRegisterAllocationConstraints -CompilationPhaseDisabled AllocateRegisters #-CompilationPhaseDisabled GenerateImage #-CompilationPhaseDisabled Done ### ### The program to compile. ### #~#..\..\..\..\ZeligBuild\Target\bin\Debug\Microsoft.Zelig.Test.mbed.Simple.exe ### ### Where to put the results. ### #~#-OutputName Microsoft.Zelig.Test.mbed.Simple #~#-OutputDir ..\..\..\..\LLVM2IR_results\mbed\simple ### ### Dumps and diagnostics ### #-DumpIRBeforePhase All -DumpIR #-DumpIRpre #-DumpIRpost #-DumpIRXML #-DumpFlattenedCallGraph -DumpLLVMIR #-ReloadState #-DumpLLVMIR_TextRepresentation -MaxProcs 8 #~#-NoSDK -GenerateObj # examples of overriding opt.exe and llc arguments # the examples here are the same as the defaults but can be modified to suit a variety of test # scenarios and experimentations #-LlvmOptArgs "-verify-debug-info -verify-dom-info -verify-each -verify-loop-info -verify-regalloc -verify-region-info -march=thumb -mcpu=cortex-m3 -aa-eval -indvars -gvn -globaldce -adce -dce -tailcallopt -scalarrepl -mem2reg -ipconstprop -deadargelim -sccp -dce -ipsccp -dce -constmerge -scev-aa -targetlibinfo -irce -dse -dce -argpromotion -mem2reg -adce -mem2reg -globaldce -die -dce -dse" #-LlvmLlcArgs "-O2 -code-model=small -data-sections -relocation-model=pic -march=thumb -mcpu=cortex-m3 -filetype=obj -mtriple=thumbv7m-none-eabi" # While the compiler is pretty good at figuring out where the LLVM tools are from # current Environment variables or registry entires you can manually specify the # path to find the LLVM binaries. # note: Environment variabes (i.e %MY_VAR%) are supported and expanded as with all # options in the FrontendConfig files so you can specify a custom variable if needed #-LlvmBinPath \\netmfbld02\LLVM\3.7.0\build\Win32\Release\bin ================================================ FILE: Zelig/BoardConfigurations/STM32L152/Configuration/STM32L152Configuration.csproj ================================================  Debug AnyCPU {F222E0D3-0FFF-41F4-91EE-400C4E4E043D} Library Properties Microsoft.Llilum.BoardConfigurations Microsoft.Llilum.BoardConfigurations.STM32L152 v4.5 512 true true full false $(LlilumBuildRoot)\Host\bin\$(Configuration)\ DEBUG;TRACE prompt 4 pdbonly true $(LlilumBuildRoot)\Host\bin\$(Configuration)\ TRACE prompt 4 {186f31a3-ef89-4a25-b2d5-20070606aa01} ProductConfiguration {186f31a3-ef89-4a25-b2d5-20061218aa01} Common {186F31A3-EF89-4A25-B2D5-20060501AA01} mscorlib False $(LLILUM_SDK)\ZeligBuild\Host\bin\Debug\Microsoft.Zelig.ProductConfiguration.dll $(LLILUM_SDK)\ZeligBuild\Host\bin\Debug\Microsoft.Zelig.Runtime.Common.dll $(LLILUM_SDK)\ZeligBuild\Target\bin\Debug\mscorlib.dll ================================================ FILE: Zelig/BoardConfigurations/Win32/Configuration/Configuration.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // namespace Microsoft.Llilum.BoardConfigurations { using Microsoft.Zelig.Configuration.Environment; [DisplayName("Win32Product")] public sealed class Win32Product : ProductCategory { [Defaults("CoreClockFrequency", 1000UL)] [Defaults("RealTimeClockFrequency", 1000UL)] [Defaults("DefaultThreadPoolThreads", 10)] [Defaults("DefaultTimerPoolThreads" , 10)] public ProcessorCategory Processor; } [DisplayName("Memory Map for Win32")] public sealed class Win32CoreMemoryMap : MemoryMapCategory { } [DisplayName("LLVM Compilation for Win32")] [Defaults("Platform", typeof(Microsoft.Zelig.Configuration.Environment.Abstractions.Architectures.LlvmForWin32))] [Defaults("CallingConvention", typeof(Microsoft.Zelig.Configuration.Environment.Abstractions.Architectures.LlvmForArmV7MCallingConvention))] [Defaults("Product", typeof(Win32Product))] [Defaults("MemoryMap", typeof(Win32CoreMemoryMap))] public sealed class Win32CompilationSetup : CompilationSetupCategory { } } ================================================ FILE: Zelig/BoardConfigurations/Win32/Configuration/Properties/AssemblyInfo.cs ================================================ using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; // General Information about an assembly is controlled through the following // set of attributes. Change these attribute values to modify the information // associated with an assembly. [assembly: AssemblyTitle("Microsoft.Llilum.BoardConfigurations.K26")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("Microsoft.Llilum.BoardConfigurations.K26")] [assembly: AssemblyCopyright("Copyright © 2015")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible(false)] // The following GUID is for the ID of the typelib if this project is exposed to COM [assembly: Guid("63BB92A6-10A4-42A2-BB1F-FC645ECAC716")] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Build and Revision Numbers // by using the '*' as shown below: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("1.0.0.0")] [assembly: AssemblyFileVersion("1.0.0.0")] ================================================ FILE: Zelig/BoardConfigurations/Win32/Configuration/Win32.FrontEndConfig ================================================ ### ### README: This file can be used in the SDK AS-IS, or remove all instances of #~# to use with the FrontEnd project ### ### ### Location of the Zelig assemblies. ### #~#-HostAssemblyDir ..\..\..\..\ZeligBuild\Host\bin\Debug #~#-DeviceAssemblyDir ..\..\..\..\ZeligBuild\Target\bin\Debug #~#-CompilationSetupPath ..\..\..\..\ZeligBuild\Host\bin\Debug\Microsoft.Llilum.BoardConfigurations.K26.dll -CompilationSetup Microsoft.Llilum.BoardConfigurations.K26CompilationSetup ### ### We need to include this assembly to get the right drivers. ### -Reference Microsoft.DeviceModels.ModelForWin32 -Reference Win32 ### ### Add compilation phases, in order ### #-CompilationPhaseDisabled ReduceNumberOfTemporaries #-CompilationPhaseDisabled TransformFinallyBlocksIntoTryBlocks #-CompilationPhaseDisabled ApplyClassExtensions #-CompilationPhaseDisabled PrepareImplementationOfInternalMethods #-CompilationPhaseDisabled CrossReferenceTypeSystem #-CompilationPhaseDisabled ApplyConfigurationSettings -CompilationPhaseDisabled ResourceManagerOptimizations #-CompilationPhaseDisabled HighLevelTransformations #-CompilationPhaseDisabled PropagateCompilationConstraints #-CompilationPhaseDisabled ComputeCallsClosure #-CompilationPhaseDisabled EstimateTypeSystemReduction #-CompilationPhaseDisabled CompleteImplementationOfInternalMethods #-CompilationPhaseDisabled ReduceTypeSystem -CompilationPhaseDisabled PrepareExternalMethods #-CompilationPhaseDisabled DetectNonImplementedInternalCalls #-CompilationPhaseDisabled OrderStaticConstructors #-CompilationPhaseDisabled LayoutTypes #-CompilationPhaseDisabled HighLevelToMidLevelConversion #-CompilationPhaseDisabled FromImplicitToExplicitExceptions #-CompilationPhaseDisabled ReferenceCountingGarbageCollection -CompilationPhaseDisabled MidLevelToLowLevelConversion -CompilationPhaseDisabled ConvertUnsupportedOperatorsToMethodCalls -CompilationPhaseDisabled ExpandAggregateTypes -CompilationPhaseDisabled SplitComplexOperators -CompilationPhaseDisabled FuseOperators #-CompilationPhaseDisabled Optimizations -CompilationPhaseDisabled ConvertToSSA -CompilationPhaseDisabled PrepareForRegisterAllocation -CompilationPhaseDisabled CollectRegisterAllocationConstraints -CompilationPhaseDisabled AllocateRegisters #-CompilationPhaseDisabled GenerateImage #-CompilationPhaseDisabled Done ### ### The program to compile. ### #~#..\..\..\..\ZeligBuild\Target\bin\Debug\Microsoft.Zelig.Test.mbed.Simple.exe ### ### Where to put the results. ### #~#-OutputName Microsoft.Zelig.Test.mbed.Simple #~#-OutputDir ..\..\..\..\LLVM2IR_results\mbed\simple #-DumpIR #-DumpIRpre #-DumpIRpost #-DumpIRXML -DumpLLVMIR #-ReloadState #-DumpLLVMIR_TextRepresentation -MaxProcs 8 #-NoSDK #-GenerateObj #-LlvmOptArgs "-verify-debug-info -verify-dom-info -verify-each -verify-loop-info -verify-regalloc -verify-region-info -march=thumb -mcpu=cortex-m3 -aa-eval -indvars -gvn -globaldce -adce -dce -tailcallopt -scalarrepl -mem2reg -ipconstprop -deadargelim -sccp -dce -ipsccp -dce -constmerge -scev-aa -targetlibinfo -irce -dse -dce -argpromotion -mem2reg -adce -mem2reg -globaldce -die -dce -dse" #-LlvmLlcArgs "-O2 -code-model=small -data-sections -relocation-model=pic -march=thumb -mcpu=cortex-m3 -filetype=obj -mtriple=thumbv7m-none-eabi" ================================================ FILE: Zelig/BoardConfigurations/Win32/Configuration/Win32Configuration.csproj ================================================  Debug AnyCPU {F84C2434-C768-4295-955B-E032E3A18FC3} Library Properties Microsoft.Llilum.BoardConfigurations Microsoft.Llilum.BoardConfigurations.Win32 v4.5 512 true true full false $(LlilumBuildRoot)\Host\bin\$(Configuration)\ DEBUG;TRACE prompt 4 pdbonly true $(LlilumBuildRoot)\Host\bin\$(Configuration)\ TRACE prompt 4 {186f31a3-ef89-4a25-b2d5-20070606aa01} ProductConfiguration {186f31a3-ef89-4a25-b2d5-20061218aa01} Common {186F31A3-EF89-4A25-B2D5-20060501AA01} mscorlib False $(LLILUM_SDK)\ZeligBuild\Host\bin\Debug\Microsoft.Zelig.ProductConfiguration.dll $(LLILUM_SDK)\ZeligBuild\Host\bin\Debug\Microsoft.Zelig.Runtime.Common.dll $(LLILUM_SDK)\ZeligBuild\Target\bin\Debug\mscorlib.dll ================================================ FILE: Zelig/LLVM2IR_results/mbed/common_files/temporary_helper.c ================================================ #include "gpio_api.h" #include void tmp_gpio_write(gpio_t *obj, int value) { gpio_write(obj,value); } int tmp_gpio_read(gpio_t *obj) { return gpio_read(obj); } void tmp_gpio_alloc(gpio_t **obj) { *obj=calloc(sizeof(gpio_t),1); } ================================================ FILE: Zelig/LLVM2IR_results/mbed/mbed_rtos/GpioInterrupts/Makefile ================================================ # This file was automagically generated by mbed.org. For more information, # see http://mbed.org/handbook/Exporting-to-GCC-ARM-Embedded VERBOSE=1 ifndef GCC_BIN $(error GCC_BIN is undefined. Define GCC_BIN to point to arm-none-eabi-xxx tools) endif # Common settings PROJECT = GpioInterrupt MBED_ROOT = $(LLILUM_ROOT)Zelig\mbed MBED_RTOS_ROOT = $(LLILUM_ROOT)Zelig\mbed-rtos SOURCE_ROOT = $(LLILUM_ROOT)Zelig\LLVM2IR_results\mbed\mbed_rtos\GpioInterrupts LIBRARIES = -lmbed LD_SYS_LIBS = -lstdc++ -lsupc++ -lm -lc -lgcc -lnosys ifeq ($(TARGET),) $(error TARGET is undefined. Pass in TARGET for desired board) endif ifeq ($(TARGET),LPC1768) OBJECTS = $(MBED_RTOS_ROOT)\rtx\TARGET_CORTEX_M\TARGET_M3\TOOLCHAIN_GCC\HAL_CM3.o $(MBED_RTOS_ROOT)\rtx\TARGET_CORTEX_M\TARGET_M3\TOOLCHAIN_GCC\SVC_Table.o $(MBED_RTOS_ROOT)\rtx\TARGET_CORTEX_M\HAL_CM.o $(MBED_RTOS_ROOT)\rtx\TARGET_CORTEX_M\RTX_Conf_CM.o $(MBED_RTOS_ROOT)\rtx\TARGET_CORTEX_M\rt_CMSIS.o $(MBED_RTOS_ROOT)\rtx\TARGET_CORTEX_M\rt_Event.o $(MBED_RTOS_ROOT)\rtx\TARGET_CORTEX_M\rt_List.o $(MBED_RTOS_ROOT)\rtx\TARGET_CORTEX_M\rt_Mailbox.o $(MBED_RTOS_ROOT)\rtx\TARGET_CORTEX_M\rt_MemBox.o $(MBED_RTOS_ROOT)\rtx\TARGET_CORTEX_M\rt_Mutex.o $(MBED_RTOS_ROOT)\rtx\TARGET_CORTEX_M\rt_Robin.o $(MBED_RTOS_ROOT)\rtx\TARGET_CORTEX_M\rt_Semaphore.o $(MBED_RTOS_ROOT)\rtx\TARGET_CORTEX_M\rt_System.o $(MBED_RTOS_ROOT)\rtx\TARGET_CORTEX_M\rt_Task.o $(MBED_RTOS_ROOT)\rtx\TARGET_CORTEX_M\rt_Time.o $(TARGET)\main.o $(MBED_RTOS_ROOT)\rtos\Mutex.o $(MBED_RTOS_ROOT)\rtos\RtosTimer.o $(MBED_RTOS_ROOT)\rtos\Semaphore.o $(MBED_RTOS_ROOT)\rtos\Thread.o SYS_OBJECTS = $(MBED_ROOT)\TARGET_LPC1768\TOOLCHAIN_GCC_ARM\board.o $(MBED_ROOT)\TARGET_LPC1768\TOOLCHAIN_GCC_ARM\cmsis_nvic.o $(MBED_ROOT)\TARGET_LPC1768\TOOLCHAIN_GCC_ARM\retarget.o $(MBED_ROOT)\TARGET_LPC1768\TOOLCHAIN_GCC_ARM\startup_LPC17xx.o $(MBED_ROOT)\TARGET_LPC1768\TOOLCHAIN_GCC_ARM\system_LPC17xx.o INCLUDE_PATHS = -I. -I$(MBED_ROOT) -I$(MBED_RTOS_ROOT) -I$(MBED_RTOS_ROOT)\rtos -I$(MBED_RTOS_ROOT)\rtx -I$(MBED_RTOS_ROOT)\rtx\TARGET_CORTEX_M -I$(MBED_RTOS_ROOT)\rtx\TARGET_CORTEX_M\TARGET_M3 -I$(MBED_RTOS_ROOT)\rtx\TARGET_CORTEX_M\TARGET_M3\TOOLCHAIN_GCC -I$(SOURCE_ROOT) -I$(MBED_ROOT)\TARGET_LPC1768 -I$(MBED_ROOT)\TARGET_LPC1768\TARGET_NXP -I$(MBED_ROOT)\TARGET_LPC1768\TARGET_NXP\TARGET_LPC176X -I$(MBED_ROOT)\TARGET_LPC1768\TARGET_NXP\TARGET_LPC176X\TARGET_MBED_LPC1768 -I$(MBED_ROOT)\TARGET_LPC1768\TOOLCHAIN_GCC_ARM LIBRARY_PATHS = -L$(MBED_ROOT)\TARGET_LPC1768\TOOLCHAIN_GCC_ARM LINKER_SCRIPT = $(MBED_ROOT)\TARGET_LPC1768\TOOLCHAIN_GCC_ARM\LPC1768.ld CPU = -mcpu=cortex-m3 -mthumb CC_FLAGS = $(CPU) -c -g -fno-common -fmessage-length=0 -Wall -Wextra -fno-exceptions -ffunction-sections -fdata-sections -fomit-frame-pointer -MMD -MP CC_SYMBOLS = -DTOOLCHAIN_GCC_ARM -DTOOLCHAIN_GCC -DARM_MATH_CM3 -DMBED_BUILD_TIMESTAMP=1446568245.6 -DTARGET_CORTEX_M -DTARGET_LPC176X -DTARGET_NXP -DTARGET_MBED_LPC1768 -DTARGET_LPC1768 -D__CORTEX_M3 -DTARGET_M3 -D__MBED__=1 LD_FLAGS = $(CPU) -Wl,--gc-sections --specs=nano.specs -u _printf_float -u _scanf_float -Wl,--wrap,main -Wl,-Map=${TARGET}\$(PROJECT).map,--cref else ifeq ($(TARGET),K64F) OBJECTS = $(MBED_RTOS_ROOT)\rtx\TARGET_CORTEX_M\TARGET_M4\TOOLCHAIN_GCC\HAL_CM4.o $(MBED_RTOS_ROOT)\rtx\TARGET_CORTEX_M\TARGET_M4\TOOLCHAIN_GCC\SVC_Table.o $(MBED_RTOS_ROOT)\rtx\TARGET_CORTEX_M\HAL_CM.o $(MBED_RTOS_ROOT)\rtx\TARGET_CORTEX_M\RTX_Conf_CM.o $(MBED_RTOS_ROOT)\rtx\TARGET_CORTEX_M\rt_CMSIS.o $(MBED_RTOS_ROOT)\rtx\TARGET_CORTEX_M\rt_Event.o $(MBED_RTOS_ROOT)\rtx\TARGET_CORTEX_M\rt_List.o $(MBED_RTOS_ROOT)\rtx\TARGET_CORTEX_M\rt_Mailbox.o $(MBED_RTOS_ROOT)\rtx\TARGET_CORTEX_M\rt_MemBox.o $(MBED_RTOS_ROOT)\rtx\TARGET_CORTEX_M\rt_Mutex.o $(MBED_RTOS_ROOT)\rtx\TARGET_CORTEX_M\rt_Robin.o $(MBED_RTOS_ROOT)\rtx\TARGET_CORTEX_M\rt_Semaphore.o $(MBED_RTOS_ROOT)\rtx\TARGET_CORTEX_M\rt_System.o $(MBED_RTOS_ROOT)\rtx\TARGET_CORTEX_M\rt_Task.o $(MBED_RTOS_ROOT)\rtx\TARGET_CORTEX_M\rt_Time.o $(TARGET)\main.o $(MBED_RTOS_ROOT)\rtos\Mutex.o $(MBED_RTOS_ROOT)\rtos\RtosTimer.o $(MBED_RTOS_ROOT)\rtos\Semaphore.o $(MBED_RTOS_ROOT)\rtos\Thread.o SYS_OBJECTS = $(MBED_ROOT)\TARGET_K64F\TOOLCHAIN_GCC_ARM\board.o $(MBED_ROOT)\TARGET_K64F\TOOLCHAIN_GCC_ARM\cmsis_nvic.o $(MBED_ROOT)\TARGET_K64F\TOOLCHAIN_GCC_ARM\mbed_overrides.o $(MBED_ROOT)\TARGET_K64F\TOOLCHAIN_GCC_ARM\retarget.o $(MBED_ROOT)\TARGET_K64F\TOOLCHAIN_GCC_ARM\startup_MK64F12.o $(MBED_ROOT)\TARGET_K64F\TOOLCHAIN_GCC_ARM\system_MK64F12.o INCLUDE_PATHS = -I. -I$(MBED_ROOT) -I$(MBED_RTOS_ROOT) -I$(MBED_RTOS_ROOT)\rtos -I$(MBED_RTOS_ROOT)\rtx -I$(MBED_RTOS_ROOT)\rtx\TARGET_CORTEX_M -I$(MBED_RTOS_ROOT)\rtx\TARGET_CORTEX_M\TARGET_M4 -I$(MBED_RTOS_ROOT)\rtx\TARGET_CORTEX_M\TARGET_M4\TOOLCHAIN_GCC -I$(SOURCE_ROOT) -I$(MBED_ROOT)\TARGET_K64F -I$(MBED_ROOT)\TARGET_K64F\TARGET_Freescale -I$(MBED_ROOT)\TARGET_K64F\TARGET_Freescale\TARGET_KPSDK_MCUS -I$(MBED_ROOT)\TARGET_K64F\TARGET_Freescale\TARGET_KPSDK_MCUS\TARGET_KPSDK_CODE -I$(MBED_ROOT)\TARGET_K64F\TARGET_Freescale\TARGET_KPSDK_MCUS\TARGET_KPSDK_CODE\common -I$(MBED_ROOT)\TARGET_K64F\TARGET_Freescale\TARGET_KPSDK_MCUS\TARGET_KPSDK_CODE\common\phyksz8081 -I$(MBED_ROOT)\TARGET_K64F\TARGET_Freescale\TARGET_KPSDK_MCUS\TARGET_KPSDK_CODE\drivers -I$(MBED_ROOT)\TARGET_K64F\TARGET_Freescale\TARGET_KPSDK_MCUS\TARGET_KPSDK_CODE\drivers\clock -I$(MBED_ROOT)\TARGET_K64F\TARGET_Freescale\TARGET_KPSDK_MCUS\TARGET_KPSDK_CODE\drivers\enet -I$(MBED_ROOT)\TARGET_K64F\TARGET_Freescale\TARGET_KPSDK_MCUS\TARGET_KPSDK_CODE\drivers\interrupt -I$(MBED_ROOT)\TARGET_K64F\TARGET_Freescale\TARGET_KPSDK_MCUS\TARGET_KPSDK_CODE\drivers\pit -I$(MBED_ROOT)\TARGET_K64F\TARGET_Freescale\TARGET_KPSDK_MCUS\TARGET_KPSDK_CODE\drivers\pit\common -I$(MBED_ROOT)\TARGET_K64F\TARGET_Freescale\TARGET_KPSDK_MCUS\TARGET_KPSDK_CODE\hal -I$(MBED_ROOT)\TARGET_K64F\TARGET_Freescale\TARGET_KPSDK_MCUS\TARGET_KPSDK_CODE\hal\adc -I$(MBED_ROOT)\TARGET_K64F\TARGET_Freescale\TARGET_KPSDK_MCUS\TARGET_KPSDK_CODE\hal\can -I$(MBED_ROOT)\TARGET_K64F\TARGET_Freescale\TARGET_KPSDK_MCUS\TARGET_KPSDK_CODE\hal\dac -I$(MBED_ROOT)\TARGET_K64F\TARGET_Freescale\TARGET_KPSDK_MCUS\TARGET_KPSDK_CODE\hal\dmamux -I$(MBED_ROOT)\TARGET_K64F\TARGET_Freescale\TARGET_KPSDK_MCUS\TARGET_KPSDK_CODE\hal\dspi -I$(MBED_ROOT)\TARGET_K64F\TARGET_Freescale\TARGET_KPSDK_MCUS\TARGET_KPSDK_CODE\hal\edma -I$(MBED_ROOT)\TARGET_K64F\TARGET_Freescale\TARGET_KPSDK_MCUS\TARGET_KPSDK_CODE\hal\enet -I$(MBED_ROOT)\TARGET_K64F\TARGET_Freescale\TARGET_KPSDK_MCUS\TARGET_KPSDK_CODE\hal\flextimer -I$(MBED_ROOT)\TARGET_K64F\TARGET_Freescale\TARGET_KPSDK_MCUS\TARGET_KPSDK_CODE\hal\gpio -I$(MBED_ROOT)\TARGET_K64F\TARGET_Freescale\TARGET_KPSDK_MCUS\TARGET_KPSDK_CODE\hal\i2c -I$(MBED_ROOT)\TARGET_K64F\TARGET_Freescale\TARGET_KPSDK_MCUS\TARGET_KPSDK_CODE\hal\llwu -I$(MBED_ROOT)\TARGET_K64F\TARGET_Freescale\TARGET_KPSDK_MCUS\TARGET_KPSDK_CODE\hal\lptmr -I$(MBED_ROOT)\TARGET_K64F\TARGET_Freescale\TARGET_KPSDK_MCUS\TARGET_KPSDK_CODE\hal\lpuart -I$(MBED_ROOT)\TARGET_K64F\TARGET_Freescale\TARGET_KPSDK_MCUS\TARGET_KPSDK_CODE\hal\mcg -I$(MBED_ROOT)\TARGET_K64F\TARGET_Freescale\TARGET_KPSDK_MCUS\TARGET_KPSDK_CODE\hal\mpu -I$(MBED_ROOT)\TARGET_K64F\TARGET_Freescale\TARGET_KPSDK_MCUS\TARGET_KPSDK_CODE\hal\osc -I$(MBED_ROOT)\TARGET_K64F\TARGET_Freescale\TARGET_KPSDK_MCUS\TARGET_KPSDK_CODE\hal\pdb -I$(MBED_ROOT)\TARGET_K64F\TARGET_Freescale\TARGET_KPSDK_MCUS\TARGET_KPSDK_CODE\hal\pit -I$(MBED_ROOT)\TARGET_K64F\TARGET_Freescale\TARGET_KPSDK_MCUS\TARGET_KPSDK_CODE\hal\pmc -I$(MBED_ROOT)\TARGET_K64F\TARGET_Freescale\TARGET_KPSDK_MCUS\TARGET_KPSDK_CODE\hal\port -I$(MBED_ROOT)\TARGET_K64F\TARGET_Freescale\TARGET_KPSDK_MCUS\TARGET_KPSDK_CODE\hal\rcm -I$(MBED_ROOT)\TARGET_K64F\TARGET_Freescale\TARGET_KPSDK_MCUS\TARGET_KPSDK_CODE\hal\rtc -I$(MBED_ROOT)\TARGET_K64F\TARGET_Freescale\TARGET_KPSDK_MCUS\TARGET_KPSDK_CODE\hal\sai -I$(MBED_ROOT)\TARGET_K64F\TARGET_Freescale\TARGET_KPSDK_MCUS\TARGET_KPSDK_CODE\hal\sdhc -I$(MBED_ROOT)\TARGET_K64F\TARGET_Freescale\TARGET_KPSDK_MCUS\TARGET_KPSDK_CODE\hal\sim -I$(MBED_ROOT)\TARGET_K64F\TARGET_Freescale\TARGET_KPSDK_MCUS\TARGET_KPSDK_CODE\hal\smc -I$(MBED_ROOT)\TARGET_K64F\TARGET_Freescale\TARGET_KPSDK_MCUS\TARGET_KPSDK_CODE\hal\uart -I$(MBED_ROOT)\TARGET_K64F\TARGET_Freescale\TARGET_KPSDK_MCUS\TARGET_KPSDK_CODE\hal\wdog -I$(MBED_ROOT)\TARGET_K64F\TARGET_Freescale\TARGET_KPSDK_MCUS\TARGET_KPSDK_CODE\utilities -I$(MBED_ROOT)\TARGET_K64F\TARGET_Freescale\TARGET_KPSDK_MCUS\TARGET_MCU_K64F -I$(MBED_ROOT)\TARGET_K64F\TARGET_Freescale\TARGET_KPSDK_MCUS\TARGET_MCU_K64F\MK64F12 -I$(MBED_ROOT)\TARGET_K64F\TARGET_Freescale\TARGET_KPSDK_MCUS\TARGET_MCU_K64F\TARGET_FRDM -I$(MBED_ROOT)\TARGET_K64F\TARGET_Freescale\TARGET_KPSDK_MCUS\TARGET_MCU_K64F\device -I$(MBED_ROOT)\TARGET_K64F\TARGET_Freescale\TARGET_KPSDK_MCUS\TARGET_MCU_K64F\device\MK64F12 -I$(MBED_ROOT)\TARGET_K64F\TARGET_Freescale\TARGET_KPSDK_MCUS\TARGET_MCU_K64F\device\device -I$(MBED_ROOT)\TARGET_K64F\TARGET_Freescale\TARGET_KPSDK_MCUS\TARGET_MCU_K64F\device\device\MK64F12 -I$(MBED_ROOT)\TARGET_K64F\TOOLCHAIN_GCC_ARM LIBRARY_PATHS = -L$(MBED_ROOT)\TARGET_K64F\TOOLCHAIN_GCC_ARM LINKER_SCRIPT = $(MBED_ROOT)\TARGET_K64F\TOOLCHAIN_GCC_ARM\K64FN1M0xxx12.ld ifeq ($(HARDFP),1) FLOAT_ABI = hard else FLOAT_ABI = softfp endif CPU = -mcpu=cortex-m4 -mthumb -mfpu=fpv4-sp-d16 -mfloat-abi=$(FLOAT_ABI) CC_FLAGS = $(CPU) -c -g -fno-common -fmessage-length=0 -Wall -Wextra -fno-exceptions -ffunction-sections -fdata-sections -fomit-frame-pointer -MMD -MP CC_SYMBOLS = -DTARGET_KPSDK_MCUS -DTARGET_FF_ARDUINO -DTOOLCHAIN_GCC_ARM -DTOOLCHAIN_GCC -DCPU_MK64FN1M0VMD12 -DTARGET_FRDM -DTARGET_CORTEX_M -DMBED_BUILD_TIMESTAMP=1446571491.65 -D__FPU_PRESENT=1 -DTARGET_KPSDK_CODE -DTARGET_M4 -D__MBED__=1 -DTARGET_K64F -DTARGET_Freescale -D__CORTEX_M4 -DFSL_RTOS_MBED -DTARGET_MCU_K64F -DARM_MATH_CM4 LD_FLAGS = $(CPU) -Wl,--gc-sections --specs=nano.specs -u _printf_float -u _scanf_float -Wl,--wrap,main -Wl,-Map=${TARGET}\$(PROJECT).map,--cref else $(error TARGET is not recognized. Please check the value passed in) endif DEPS = $(OBJECTS:.o=.d) ############################################################################### AS = $(GCC_BIN)arm-none-eabi-as CC = $(GCC_BIN)arm-none-eabi-gcc CPP = $(GCC_BIN)arm-none-eabi-g++ LD = $(GCC_BIN)arm-none-eabi-gcc OBJCOPY = $(GCC_BIN)arm-none-eabi-objcopy OBJDUMP = $(GCC_BIN)arm-none-eabi-objdump SIZE = $(GCC_BIN)arm-none-eabi-size ifeq ($(DEBUG), 1) CC_FLAGS += -DDEBUG -O0 else CC_FLAGS += -DNDEBUG -Os endif .PHONY: all clean lst size all: ${TARGET} ${TARGET}\$(PROJECT).bin ${TARGET}\$(PROJECT).hex $(TARGET)\$(PROJECT).lst $(TARGET)\$(PROJECT).disasm size clean: ${TARGET} @rmdir /q /s $(TARGET) # Ensures the target directory has been created. ${TARGET}: @mkdir $@ $(TARGET)\\%.o : %.asm $(AS) $(CPU) $(AS_FLAGS) -o $@ $< $(TARGET)\\%.o : %.S $(AS) $(CPU) $(AS_FLAGS) -o $@ $< $(TARGET)\\%.o : %.s $(AS) $(CPU) $(AS_FLAGS) -o $@ $< $(TARGET)\\%.o : %.c $(CC) $(CC_FLAGS) $(CC_SYMBOLS) -std=gnu99 $(INCLUDE_PATHS) -o $@ $< $(TARGET)\\%.o : $(SOURCE_ROOT)\%.cpp $(CPP) $(CC_FLAGS) $(CC_SYMBOLS) -std=gnu++98 -fno-rtti $(INCLUDE_PATHS) -o $@ $< $(TARGET)\$(PROJECT).elf: $(OBJECTS) $(SYS_OBJECTS) $(LD) $(LD_FLAGS) -T$(LINKER_SCRIPT) $(LIBRARY_PATHS) -o $@ $^ $(LIBRARIES) $(LD_SYS_LIBS) $(LIBRARIES) $(LD_SYS_LIBS) $(TARGET)\$(PROJECT).bin: $(TARGET)\$(PROJECT).elf $(OBJCOPY) -O binary $< $@ $(TARGET)\$(PROJECT).hex: $(TARGET)\$(PROJECT).elf @$(OBJCOPY) -O ihex $< $@ $(TARGET)\$(PROJECT).lst: $(TARGET)\$(PROJECT).elf @$(OBJDUMP) -Sdh $< > $@ $(TARGET)\$(PROJECT).disasm: $(TARGET)\$(PROJECT).elf @$(OBJDUMP) -D $< > $@ size: $(TARGET)\$(PROJECT).elf @echo Size report... $(SIZE) $< #DEPS = $(OBJECTS:.o=.d) $(SYS_OBJECTS:.o=.d) #-include $(DEPS) ================================================ FILE: Zelig/LLVM2IR_results/mbed/mbed_rtos/GpioInterrupts/buildK64F.bat ================================================ @echo off make TARGET=K64F %* EXIT /b ================================================ FILE: Zelig/LLVM2IR_results/mbed/mbed_rtos/GpioInterrupts/buildLPC1768.bat ================================================ @echo off make TARGET=LPC1768 %* EXIT /b ================================================ FILE: Zelig/LLVM2IR_results/mbed/mbed_rtos/GpioInterrupts/main.cpp ================================================ #include "mbed.h" #include "rtos.h" #include "Thread.h" // // To test hardware generated interrupt handling comment out this #define and connect a function generator to the input pin // (LPC1768: p9, K64F: PTC7). Also place a oscilloscope probe on the monitor pin (LPC1768: p11, K64F: PTC0). // #define TEST_SOFTWARE_INTERRUPTS 1 #if TARGET_LPC1768 #if TEST_SOFTWARE_INTERRUPTS DigitalOut pinOut(P0_1); #endif InterruptIn pinIn(P0_0); DigitalOut pinMonitor(P0_18); #elif TARGET_K64F #if TEST_SOFTWARE_INTERRUPTS DigitalOut pinOut(PTC5); #endif InterruptIn pinIn(PTC7); DigitalOut pinMonitor(PTC0); #else !Error No target defined. #endif const int SIGNAL_MAIN_THREAD = 0x4321; const int SIGNAL_DISPATCH_THREAD = 0x1234; const int SIGNAL_WAIT_FOREVER = 0x1000; struct Dispatcher; Mutex dispatcher_lock; Mutex gpio_lock; Dispatcher *s_pDispatcherInst = NULL; Queue gpio_interrupt_queue; Thread *p_main_thread = NULL; Thread *p_dispatcher_thread = NULL; #if !TEST_SOFTWARE_INTERRUPTS int g_monitor_value = 1; #endif void main_thread_proc(void const *args); void dispatcher_thread_proc(void const *args); typedef void (*PIN_CHANGED_HANDLER)(int edge); void handle_event(int event) { #if TEST_SOFTWARE_INTERRUPTS pinMonitor = 0; p_main_thread->signal_set(SIGNAL_MAIN_THREAD); #else pinMonitor = g_monitor_value; g_monitor_value = !g_monitor_value; #endif } struct Dispatcher { static Mutex m_lock; PIN_CHANGED_HANDLER m_callback; void RegisterForCallback( PIN_CHANGED_HANDLER callback ) { m_callback = callback; } PIN_CHANGED_HANDLER GetCallback() { return m_callback; } static Dispatcher *GetInstance() { if( s_pDispatcherInst == NULL ) { dispatcher_lock.lock(); if( s_pDispatcherInst == NULL ) { s_pDispatcherInst = new Dispatcher(); } dispatcher_lock.unlock(); } return s_pDispatcherInst; } static void dispatcher_thread_proc(void const *args) { while(p_main_thread == NULL) { wait(1.0); } p_main_thread->signal_set(SIGNAL_MAIN_THREAD); while (true) { Thread::signal_wait(SIGNAL_DISPATCH_THREAD); gpio_lock.lock(); osEvent evt = gpio_interrupt_queue.get(); gpio_lock.unlock(); Dispatcher *pInst = Dispatcher::GetInstance(); PIN_CHANGED_HANDLER callback = pInst->GetCallback(); if( callback != NULL) { callback((int)evt.value.p); } } } }; void OnRise(void) { int evt = pinIn; gpio_lock.lock(); gpio_interrupt_queue.put((int*)evt); gpio_lock.unlock(); p_dispatcher_thread->signal_set(SIGNAL_DISPATCH_THREAD); } void main_thread_proc(void const *args) { Thread::signal_wait(SIGNAL_MAIN_THREAD); pinMonitor = 0; #if TEST_SOFTWARE_INTERRUPTS pinOut = 0; #else pinIn.fall( &OnRise ); #endif pinIn.rise( &OnRise ); while(1) { #if TEST_SOFTWARE_INTERRUPTS pinMonitor = 1; pinOut = 1; #endif Thread::signal_wait(SIGNAL_MAIN_THREAD); #if TEST_SOFTWARE_INTERRUPTS pinOut = 0; wait(2.0); #endif } } int main() { Dispatcher *pDisp = Dispatcher::GetInstance(); pDisp->RegisterForCallback( handle_event ); Thread dispatcher_thread(Dispatcher::dispatcher_thread_proc); Thread main_thread(main_thread_proc); p_dispatcher_thread = &dispatcher_thread; p_main_thread = &main_thread; Thread::signal_wait(SIGNAL_WAIT_FOREVER); } ================================================ FILE: Zelig/LLVM2IR_results/mbed/mbed_rtos/ReadMe.txt ================================================ The applications under this directory require the mbed-rtos directories that can be found at https://developer.mbed.org/users/mbed_official/code/mbed-rtos/. The following subdirectories of mbed-rtos are required: * rtos * rtx\TARGET_CORTEX_M * rtx\TARGET_CORTEX_M\TARGET_M3\... * rtx\TARGET_CORTEX_M\TARGET_M4\... The mbed-rtos directory must be placed in the directory $(LLILUM_ROOT)\Zelig\ as a peer directory to $(LLILUM_ROOT)\Zelig\mbed. ================================================ FILE: Zelig/LLVM2IR_results/mbed/simple/.gdbinit ================================================ define hook-quit set confirm off end set listsize 10 set filename-display basename set target-charset ASCII set output-radix 16 set print address off set print pretty on set print symbol off set print symbol-filename off set pagination off set disassemble-next-line on br DebugLogPrint commands silent printf "DebugLog: %s\n", message cont end ================================================ FILE: Zelig/LLVM2IR_results/mbed/simple/DebugOptions.xml ================================================ ================================================ FILE: Zelig/LLVM2IR_results/mbed/simple/build.bat ================================================ @echo off setlocal enableDelayedExpansion @REM - Set this ENVIRONMENT Variable to override default optimization level for testing IF NOT DEFINED LLILUM_OPT_LEVEL SET LLILUM_OPT_LEVEL=2 @REM with the Llilum compiler now running opt and LLC internally the default here @REM is not to run either one unless explicitly enabled by the user. This essentially @REM boils down to run the size app to show obj file size info and then running make @REM to build the native code components and link the final image. IF NOT DEFINED LLILUM_SKIP_OPT SET LLILUM_SKIP_OPT=1 IF NOT DEFINED LLILUM_SKIP_LLC SET LLILUM_SKIP_LLC=1 IF NOT DEFINED LLILUM_DEBUG SET LLILUM_DEBUG=1 IF NOT DEFINED LLILUM_SKIP_CLEANCLEAN SET LLILUM_SKIP_CLEANCLEAN=1 @REM lwIP stack has binaries for release, checked and debug. Checked is a release build @REM of lwIP (-Os -DNDEBUG) with LWIP_DEBUG defined and all debug switches for modules turned on. @REM Flag for release binaries is LLILUM_LWIP_DEBUG=0, debug binaries is 1, and checked is 2. IF NOT DEFINED LLILUM_LWIP_DEBUG SET LLILUM_LWIP_DEBUG=0 @REM SET incremental build as default, and correct as needed SET LLILUM_CLEANCLEAN=0 SET LLILUM_DUMPS=0 IF "%2"=="/clean" ( SET LLILUM_CLEANCLEAN=1 ) IF "%2"=="/dumps" ( SET LLILUM_DUMPS=1 ) IF "%3"=="/dumps" ( SET LLILUM_DUMPS=1 ) IF "%LLILUM_SKIP_CLEANCLEAN%" == "0" ( SET LLILUM_CLEANCLEAN=1 ) IF "%LLILUM_CLEANCLEAN%" == "0" ( ECHO Incremental build for c/cpp/asm sources... ECHO Use 'SET LLILUM_SKIP_CLEANCLEAN=' or 'SET LLILUM_SKIP_CLEANCLEAN=0' to perform a full build, ECHO or call the build batch file with '/bc' as last argument ) IF /i "%LLVM_BIN%"=="" ( ECHO LLVM_BIN is not defined. Please define LLVM_BIN to point to LLVM tools and binaries. GOTO :EXIT ) IF /i "%GCC_BIN%"=="" ( ECHO GCC_BIN is not defined. Please define GCC_BIN to point to LLVM tools and binaries. GOTO :EXIT ) IF %1.==. ( ECHO No target passed in. Defaulting to LPC1768 SET TARGET=LPC1768 SET LLILUM_TARGET_CPU=cortex-m3 SET LLILUM_TARGET_TRIPLE=Thumb-NoSubArch-UnknownVendor-UnknownOS-GNUEABI-ELF SET LLILUM_TARGET_ARCH=thumb SET SIZE_OF_HEAP=0x6000 SET LWIP_USE=0 ) ELSE ( ECHO Detected target: %1 SET TARGET=%1 IF "%1"=="K64F" ( SET SIZE_OF_HEAP=0x10000 SET LLILUM_TARGET_CPU=cortex-m3 SET LLILUM_TARGET_TRIPLE=Thumb-NoSubArch-UnknownVendor-UnknownOS-GNUEABI-ELF SET LLILUM_TARGET_ARCH=thumb SET LWIP_USE=1 ) ELSE IF "%1"=="LPC1768" ( SET SIZE_OF_HEAP=0x6000 SET LLILUM_TARGET_CPU=cortex-m3 SET LLILUM_TARGET_TRIPLE=Thumb-NoSubArch-UnknownVendor-UnknownOS-GNUEABI-ELF SET LLILUM_TARGET_ARCH=thumb SET LWIP_USE=0 ) ELSE IF "%1"=="STM32F091" ( SET SIZE_OF_HEAP=0x6000 SET LLILUM_TARGET_CPU=cortex-m0 SET LLILUM_TARGET_TRIPLE=Thumb-NoSubArch-UnknownVendor-UnknownOS-GNUEABI-ELF SET LWIP_USE=0 ) ELSE IF "%1"=="STM32F411" ( SET SIZE_OF_HEAP=0x10000 SET LLILUM_TARGET_CPU=cortex-m4 SET LLILUM_TARGET_TRIPLE=Thumb-NoSubArch-UnknownVendor-UnknownOS-GNUEABI-ELF SET LLILUM_TARGET_ARCH=thumb SET LWIP_USE=0 ) ELSE IF "%1"=="STM32F401" ( SET SIZE_OF_HEAP=0x10000 SET LLILUM_TARGET_CPU=cortex-m4 SET LLILUM_TARGET_TRIPLE=Thumb-NoSubArch-UnknownVendor-UnknownOS-GNUEABI-ELF SET LLILUM_TARGET_ARCH=thumb SET LWIP_USE=0 ) ELSE IF "%1"=="STM32L152" ( SET SIZE_OF_HEAP=0x10000 SET LLILUM_TARGET_CPU=cortex-m3 SET LLILUM_TARGET_TRIPLE=Thumb-NoSubArch-UnknownVendor-UnknownOS-GNUEABI-ELF SET LLILUM_TARGET_ARCH=thumb SET LWIP_USE=0 ) ELSE IF "%1"=="WIN32" ( SET SIZE_OF_HEAP=0x10000 SET LLILUM_TARGET_CPU=x86-64 SET LLILUM_TARGET_TRIPLE=x86_64-pc-windows-msvc SET LLILUM_TARGET_ARCH=x86 SET LLILUM_TARGET_EXTRA=-function-sections -dwarf-version=3 SET LLILUM_SKIP_LLC=0 SET LWIP_USE=0 ) ELSE ( SET SIZE_OF_HEAP=0x6000 SET LLILUM_TARGET_CPU=cortex-m3 SET LLILUM_TARGET_TRIPLE=Thumb-NoSubArch-UnknownVendor-UnknownOS-GNUEABI-ELF SET LLILUM_TARGET_ARCH=thumb SET LWIP_USE=0 ) ) SET ARCH_AND_CPU=-march=%LLILUM_TARGET_ARCH% -mcpu=%LLILUM_TARGET_CPU% SET OPT_STEPS__VERIFY=-verify-debug-info -verify-dom-info -verify-each -verify-loop-info -verify-regalloc -verify-region-info SET OPT_STEPS__OPTIMIZE=-march=%LLILUM_TARGET_ARCH% -mcpu=%LLILUM_TARGET_CPU% -mem2reg -instcombine -scev-aa -indvars -gvn -globaldce -adce -dce -tailcallopt -instcombine -memcpyopt -scalarrepl -ipconstprop -deadargelim -sccp -dce -die -ipsccp -dce -die -instcombine -constmerge -scev-aa -targetlibinfo -irce -dse -dce -instcombine -argpromotion -adce -instcombine -memcpyopt -globaldce -die -dce -dse -loop-deletion -indvars -loop-simplify -licm -indvars -loop-reduce -mem2reg -time-passes SET OPT_STEPS__BUILDS_DATA_STRUCTURES=-domfrontier -domtree -intervals -globals-aa -memdep -dce -die -domfrontier -domtree -intervals -globals-aa -memdep SET OPT_STEPS__SIMPLIFY_GLOBALS=-strip-dead-prototypes -globalopt -globaldce -gvn -prune-eh -reassociate -constmerge -ipconstprop -reassociate -constmerge -constprop -constmerge -sccp -constmerge -deadargelim -ipsccp -irce %OPT_STEPS__BUILDS_DATA_STRUCTURES% SET OPT_STEPS__DEAD_CODE_OBVIOUS=-dse -die %OPT_STEPS__BUILDS_DATA_STRUCTURES% REM SET OPT_STEPS__INLINE=-always-inline -inline %OPT_STEPS__BUILDS_DATA_STRUCTURES% REM SET OPT_STEPS__INLINE=-always-inline %OPT_STEPS__BUILDS_DATA_STRUCTURES% REM SET OPT_STEPS__MERGE_FUNCTIONS=-mergefunc -mergereturn %OPT_STEPS__BUILDS_DATA_STRUCTURES% SET OPT_STEPS__SIMPLIFY_FUNCTIONS=-simplifycfg %OPT_STEPS__BUILDS_DATA_STRUCTURES% REM SET OPT_STEPS__SIMPLIFY_SINK=-sink %OPT_STEPS__BUILDS_DATA_STRUCTURES% SET OPT_STEPS__SIMPLIFY_TAIL_CALL=-tailcallopt %OPT_STEPS__BUILDS_DATA_STRUCTURES% SET OPT_STEPS__SIMPLIFY_INSTRUCTIONS=-instcombine -sroa -memcpyopt -irce -scalarrepl -scalarrepl-ssa %OPT_STEPS__BUILDS_DATA_STRUCTURES% SET OPT_STEPS__DEAD_CODE_AGGRESSIVE=-adce -bdce %OPT_STEPS__BUILDS_DATA_STRUCTURES% REM SET OPT_STEPS__LOOPS=-loop-deletion -indvars -loop-simplify -licm -indvars -loop-reduce %OPT_STEPS__BUILDS_DATA_STRUCTURES% SET OPT_STEPS__MEM2REG=-mem2reg %OPT_STEPS__BUILDS_DATA_STRUCTURES% @REM - To skip optimizations for testing you can SET this ENVIRONMENT variable, otherwise the optimization will run as normal IF "%LLILUM_SKIP_OPT%" == "0" ( ECHO Running LLVM Optimization passes... "%LLVM_BIN%\llvm-dis" %TARGET%\Microsoft.Zelig.Test.mbed.Simple.bc @REM -"%LLVM_BIN%\opt" -O2 -adce -globaldce %TARGET%\Microsoft.Zelig.Test.mbed.Simple.bc -o %TARGET%\Microsoft.Zelig.Test.mbed.Simple_opt_2.bc @REM -"%LLVM_BIN%\opt" -O1 -globalopt -constmerge -adce -globaldce -time-passes %TARGET%\Microsoft.Zelig.Test.mbed.Simple.bc -o %TARGET%\Microsoft.Zelig.Test.mbed.Simple_opt_2.bc ECHO Verify... "%LLVM_BIN%\opt" %OPT_STEPS__VERIFY% %TARGET%\Microsoft.Zelig.Test.mbed.Simple.bc -o %TARGET%\Microsoft.Zelig.Test.mbed.Simple_verify.bc ECHO Optimize... ECHO Generating LLVM IR source file... "%LLVM_BIN%\opt" %OPT_STEPS__OPTIMIZE% %TARGET%\Microsoft.Zelig.Test.mbed.Simple.bc -o %TARGET%\Microsoft.Zelig.Test.mbed.Simple_opt_2.bc REM "%LLVM_BIN%\opt" %ARCH_AND_CPU% %OPT_STEPS__DEAD_CODE_OBVIOUS% %OPT_STEPS__SIMPLIFY_GLOBALS% %OPT_STEPS__INLINE% %OPT_STEPS__MERGE_FUNCTIONS% %OPT_STEPS__INLINE% %OPT_STEPS__SIMPLIFY_FUNCTIONS% %OPT_STEPS__SIMPLIFY_SINK% %OPT_STEPS__SIMPLIFY_TAIL_CALL% %OPT_STEPS__SIMPLIFY_INSTRUCTIONS% %OPT_STEPS__LOOPS% %OPT_STEPS__MEM2REG% -time-passes %TARGET%\Microsoft.Zelig.Test.mbed.Simple.bc -o %TARGET%\Microsoft.Zelig.Test.mbed.Simple_opt_0.bc REM "%LLVM_BIN%\opt" %ARCH_AND_CPU% %OPT_STEPS__DEAD_CODE_OBVIOUS% %OPT_STEPS__SIMPLIFY_GLOBALS% %OPT_STEPS__INLINE% %OPT_STEPS__MERGE_FUNCTIONS% %OPT_STEPS__INLINE% %OPT_STEPS__SIMPLIFY_FUNCTIONS% %OPT_STEPS__SIMPLIFY_SINK% %OPT_STEPS__SIMPLIFY_TAIL_CALL% %OPT_STEPS__SIMPLIFY_INSTRUCTIONS% %OPT_STEPS__LOOPS% %OPT_STEPS__MEM2REG% -time-passes %TARGET%\Microsoft.Zelig.Test.mbed.Simple_opt_0.bc -o %TARGET%\Microsoft.Zelig.Test.mbed.Simple_opt_1.bc REM "%LLVM_BIN%\opt" %ARCH_AND_CPU% %OPT_STEPS__DEAD_CODE_OBVIOUS% %OPT_STEPS__SIMPLIFY_GLOBALS% %OPT_STEPS__INLINE% %OPT_STEPS__MERGE_FUNCTIONS% %OPT_STEPS__INLINE% %OPT_STEPS__SIMPLIFY_FUNCTIONS% %OPT_STEPS__SIMPLIFY_SINK% %OPT_STEPS__SIMPLIFY_TAIL_CALL% %OPT_STEPS__SIMPLIFY_INSTRUCTIONS% %OPT_STEPS__LOOPS% %OPT_STEPS__MEM2REG% -time-passes %TARGET%\Microsoft.Zelig.Test.mbed.Simple_opt_1.bc -o %TARGET%\Microsoft.Zelig.Test.mbed.Simple_opt_2.bc REM "%LLVM_BIN%\llvm-dis" %TARGET%\Microsoft.Zelig.Test.mbed.Simple_opt_0.bc REM "%LLVM_BIN%\llvm-dis" %TARGET%\Microsoft.Zelig.Test.mbed.Simple_opt_1.bc "%LLVM_BIN%\llvm-dis" %TARGET%\Microsoft.Zelig.Test.mbed.Simple_opt_2.bc @echo off ) ELSE ( ECHO Skipping optimization passes... COPY %TARGET%\Microsoft.Zelig.Test.mbed.Simple.bc %TARGET%\Microsoft.Zelig.Test.mbed.Simple_opt_2.bc 1>NUL ) @REM -"%LLVM_BIN%\llvm-bcanalyzer" %TARGET%\Microsoft.Zelig.Test.mbed.Simple_opt.bc IF "%LLILUM_SKIP_LLC%" == "0" ( ECHO Generating LLVM IR source file... ECHO Compiling to %LLILUM_TARGET_ARCH% ^(optimization level %LLILUM_OPT_LEVEL%^)... "%LLVM_BIN%\llc" -O%LLILUM_OPT_LEVEL% %LLILUM_TARGET_EXTRA% -code-model=small -data-sections -relocation-model=pic -march=%LLILUM_TARGET_ARCH% -mcpu=%LLILUM_TARGET_CPU% -mtriple=%LLILUM_TARGET_TRIPLE% -filetype=obj -o=%TARGET%\Microsoft.Zelig.Test.mbed.Simple_opt.o %TARGET%\Microsoft.Zelig.Test.mbed.Simple_opt_2.bc if %ERRORLEVEL% LSS 0 ( @ECHO ERRORLEVEL=%ERRORLEVEL% goto :EXIT ) ) ELSE ( ECHO skipping LLC compilation... ) IF "%1"=="WIN32" ( GOTO :EXIT ) ECHO Size Report... "%GCC_BIN%\arm-none-eabi-size.exe" %TARGET%\Microsoft.Zelig.Test.mbed.Simple_opt.o ECHO. ECHO Compiling and linking with mbed libs... IF "%LLILUM_CLEANCLEAN%" == "1" ( ECHO Cleaning target '%TARGET%' for intermediate and final artifacts... make cleanclean TARGET=%TARGET% ) ELSE ( ECHO Cleaning target '%TARGET%' for final artifacts only... make clean TARGET=%TARGET% ) make all TARGET=%TARGET% HEAP_SIZE=%SIZE_OF_HEAP% STACK_SIZE=%SIZE_OF_STACK% USE_LWIP=%LWIP_USE% DEBUG=%LLILUM_DEBUG% LWIP_DEBUG=%LLILUM_LWIP_DEBUG% ECHO. ECHO Target '%TARGET%' build is complete. ECHO. IF "%LLILUM_DUMPS%" == "1" ( ECHO Creating .lst and .disas files... make dumps TARGET=%TARGET% HEAP_SIZE=%SIZE_OF_HEAP% STACK_SIZE=%SIZE_OF_STACK% USE_LWIP=%LWIP_USE% ECHO done! ) GOTO :EXIT :EXIT ECHO. ================================================ FILE: Zelig/LLVM2IR_results/mbed/simple/buildK64F.bat ================================================ @echo off "%dp~0%build.bat" K64F %* EXIT /b ================================================ FILE: Zelig/LLVM2IR_results/mbed/simple/buildLPC1768.bat ================================================ @echo off "%dp~0%build.bat" LPC1768 %* EXIT /b ================================================ FILE: Zelig/LLVM2IR_results/mbed/simple/buildSTM32F091.bat ================================================ @echo off "%dp~0%build.bat" STM32F091 %* EXIT /b ================================================ FILE: Zelig/LLVM2IR_results/mbed/simple/buildSTM32F401.bat ================================================ @echo off "%dp~0%build.bat" STM32F401 %* EXIT /b ================================================ FILE: Zelig/LLVM2IR_results/mbed/simple/buildSTM32F411.bat ================================================ @echo off "%dp~0%build.bat" STM32F411 %* EXIT /b ================================================ FILE: Zelig/LLVM2IR_results/mbed/simple/buildSTM32L152.bat ================================================ @echo off "%dp~0%build.bat" STM32L152 %* EXIT /b ================================================ FILE: Zelig/LLVM2IR_results/mbed/simple/buildWin32.bat ================================================ @echo off "%dp~0%build.bat" WIN32 EXIT /b ================================================ FILE: Zelig/LLVM2IR_results/mbed/simple/buildmake.bat ================================================ @echo off IF %1.==. ( ECHO No target passed in. Defaulting to LPC1768 set TARGET=LPC1768 set SIZE_OF_HEAP=0x6000 ) ELSE ( ECHO Detected target: %1 set TARGET=%1 IF "%1"=="K64F" ( set SIZE_OF_HEAP=0x10000 ) ELSE ( set SIZE_OF_HEAP=0x6000 ) ) ::make clean TARGET=%TARGET% make DEBUG=1 TARGET=%TARGET% HEAP_SIZE=%SIZE_OF_HEAP% ================================================ FILE: Zelig/LLVM2IR_results/mbed/simple/debug.bat ================================================ @echo off IF /i "%GCC_BIN%"=="" ( ECHO GCC_BIN is not defined. Please define GCC_BIN to point to LLVM tools and binaries. GOTO :EXIT ) ECHO. ECHO Trying to start pyOCD for Windows kill pyocd_win.exe START /I pyocd_win.exe PAUSE ECHO. ECHO Trying to attach to remote target on port 3333 "%GCC_BIN%arm-none-eabi-gdb.exe" %* exit /b ================================================ FILE: Zelig/LLVM2IR_results/mbed/simple/debugK64F.bat ================================================ @echo off "%dp~0%debug.bat" K64F\mbed_simple.elf %* -ex "target remote :3333" -ex "monitor halt reset" -ex "ni" exit /b ================================================ FILE: Zelig/LLVM2IR_results/mbed/simple/debugLPC1768.bat ================================================ @echo off "%dp~0%debug.bat" LPC1768\mbed_simple.elf %* -ex "target remote :3333" -ex "monitor halt reset" -ex "ni" exit /b ================================================ FILE: Zelig/LLVM2IR_results/mbed/simple/debugSTM32F091.bat ================================================ @echo off IF /i "%GCC_BIN%"=="" ( ECHO GCC_BIN is not defined. Please define GCC_BIN to point to LLVM tools and binaries. GOTO :EXIT ) IF /i "%LLILUM_OPENOCD_SCRIPTS%"=="" ( ECHO Path to OpenOCD scripts is not defined. Please run setenv or set LLILUM_OPENOCD_SCRIPTS to point to the correct directory. GOTO :EXIT ) ECHO. ECHO Trying to start OpenOCD for Windows kill openocd.exe START /I openocd.exe -f %LLILUM_OPENOCD_SCRIPTS%interface\stlink-v2-1.cfg -f %LLILUM_OPENOCD_SCRIPTS%board\st_nucleo_f0.cfg PAUSE ECHO. ECHO Trying to attach to remote target on port 3333 "%GCC_BIN%arm-none-eabi-gdb.exe" STM32F091\mbed_simple.elf %* -ex "target remote :3333" -ex "monitor halt reset" -ex "ni" exit /b ================================================ FILE: Zelig/LLVM2IR_results/mbed/simple/debugSTM32F401.bat ================================================ @echo off IF /i "%GCC_BIN%"=="" ( ECHO GCC_BIN is not defined. Please define GCC_BIN to point to LLVM tools and binaries. GOTO :EXIT ) IF /i "%LLILUM_OPENOCD_SCRIPTS%"=="" ( ECHO Path to OpenOCD scripts is not defined. Please run setenv or set LLILUM_OPENOCD_SCRIPTS to point to the correct directory. GOTO :EXIT ) ECHO. ECHO Trying to start OpenOCD for Windows kill openocd.exe START /I openocd.exe -f %LLILUM_OPENOCD_SCRIPTS%interface\stlink-v2-1.cfg -f %LLILUM_OPENOCD_SCRIPTS%board\st_nucleo_f4.cfg PAUSE ECHO. ECHO Trying to attach to remote target on port 3333 "%GCC_BIN%arm-none-eabi-gdb.exe" STM32F401\mbed_simple.elf %* -ex "target remote :3333" -ex "monitor halt reset" -ex "ni" exit /b ================================================ FILE: Zelig/LLVM2IR_results/mbed/simple/debugSTM32F411.bat ================================================ @echo off IF /i "%GCC_BIN%"=="" ( ECHO GCC_BIN is not defined. Please define GCC_BIN to point to LLVM tools and binaries. GOTO :EXIT ) IF /i "%LLILUM_OPENOCD_SCRIPTS%"=="" ( ECHO Path to OpenOCD scripts is not defined. Please run setenv or set LLILUM_OPENOCD_SCRIPTS to point to the correct directory. GOTO :EXIT ) ECHO. ECHO Trying to start OpenOCD for Windows kill openocd.exe START /I openocd.exe -f %LLILUM_OPENOCD_SCRIPTS%interface\stlink-v2-1.cfg -f %LLILUM_OPENOCD_SCRIPTS%board\st_nucleo_f4.cfg PAUSE ECHO. ECHO Trying to attach to remote target on port 3333 "%GCC_BIN%arm-none-eabi-gdb.exe" STM32F411\mbed_simple.elf %* -ex "target remote :3333" -ex "monitor halt reset" -ex "ni" exit /b ================================================ FILE: Zelig/LLVM2IR_results/mbed/simple/debugSTM32L152.bat ================================================ @echo off IF /i "%GCC_BIN%"=="" ( ECHO GCC_BIN is not defined. Please define GCC_BIN to point to LLVM tools and binaries. GOTO :EXIT ) IF /i "%LLILUM_OPENOCD_SCRIPTS%"=="" ( ECHO Path to OpenOCD scripts is not defined. Please run setenv or set LLILUM_OPENOCD_SCRIPTS to point to the correct directory. GOTO :EXIT ) ECHO. ECHO Trying to start OpenOCD for Windows kill openocd.exe START /I openocd.exe -f %LLILUM_OPENOCD_SCRIPTS%interface\stlink-v2-1.cfg -f %LLILUM_OPENOCD_SCRIPTS%board\st_nucleo_l1.cfg PAUSE "%GCC_BIN%arm-none-eabi-gdb.exe" STM32L152\mbed_simple.elf %* -ex "target remote :3333" -ex "monitor halt reset" -ex "ni" exit /b ================================================ FILE: Zelig/LLVM2IR_results/mbed/simple/deploy.bat ================================================ @ECHO OFF setlocal enabledelayedexpansion IF %1.==. ( ECHO No target passed in. Defaulting to LPC1768 set TARGET=LPC1768 ) ELSE ( ECHO Detected target: %1 set TARGET=%1 ) SET DEPLOY_DRIVE=e: IF "%2" NEQ "" ( set DEPLOY_DRIVE=%2 ) ELSE IF EXIST "d:\MBED.HTM" ( set DEPLOY_DRIVE=d: ) ELSE IF EXIST "e:\MBED.HTM" ( set DEPLOY_DRIVE=e: ) ELSE IF EXIST "f:\MBED.HTM" ( set DEPLOY_DRIVE=f: ) ELSE IF EXIST "g:\MBED.HTM" ( set DEPLOY_DRIVE=g: ) ELSE IF EXIST "h:\MBED.HTM" ( set DEPLOY_DRIVE=h: ) IF NOT EXIST %DEPLOY_DRIVE%\ ( @ECHO. @ECHO Error: device drive not found! @ECHO. GOTO :USAGE ) @ECHO Deleting old image (%DEPLOY_DRIVE%\*.bin) ... del %DEPLOY_DRIVE%\*.bin @ECHO Installing new image (%TARGET%\mbed_simple.bin) to %DEPLOY_DRIVE%\... copy %TARGET%\mbed_simple.bin %DEPLOY_DRIVE%\. @ECHO Complete! GOTO :EOF :USAGE @ECHO Usage: deploy.bat [DeployDeviceDrive] @ECHO e.g. 'deploy.bat e:' @ECHO. ================================================ FILE: Zelig/LLVM2IR_results/mbed/simple/deployK64F.bat ================================================ deploy.bat K64F ================================================ FILE: Zelig/LLVM2IR_results/mbed/simple/deployLPC1768.bat ================================================ deploy.bat LPC1768 ================================================ FILE: Zelig/LLVM2IR_results/mbed/simple/deploySTM32F091.bat ================================================ deploy.bat STM32F091 ================================================ FILE: Zelig/LLVM2IR_results/mbed/simple/deploySTM32F401.bat ================================================ deploy.bat STM32F401 ================================================ FILE: Zelig/LLVM2IR_results/mbed/simple/deploySTM32F411.bat ================================================ deploy.bat STM32F411 ================================================ FILE: Zelig/LLVM2IR_results/mbed/simple/deploySTM32L152.bat ================================================ deploy.bat STM32L152 ================================================ FILE: Zelig/LLVM2IR_results/mbed/simple/helpers.h ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // #include "gpio_api.h" #ifdef TARGET_LPC1768 #include "core_cm3.h" #elif TARGET_K64F #include "core_cm4.h" #else #error Undefined plaform #endif #include "spi_api.h" #include "i2c_api.h" #include "core_cmFunc.h" #include #include #include "us_ticker_api.h" // // Platform dependent configurations // #ifdef TARGET_LPC1768 #include "system_LPC17xx.h" #elif TARGET_K64F #include "system_MK64F12.h" #else #error Undefined plaform #endif ================================================ FILE: Zelig/LLVM2IR_results/mbed/simple/makefile ================================================ # # Project-specific settings # VERBOSE=1 PROJECT = mbed_simple COMPILE_SYS_ARCH = 1 ifdef USE_LLILUM_OS_ABSTRACTION_STATIC_OBJECT ifeq ($(DEBUG), 1) OBJECTS = $(TARGET)\Microsoft.Zelig.Test.mbed.Simple_opt.o \ $(LLILUM_ROOT)\Zelig\ZeligBuild\Target\bin\mbedOsAbstraction\Debug\mbedOSAbstraction_$(TARGET).a else OBJECTS = $(TARGET)\Microsoft.Zelig.Test.mbed.Simple_opt.o \ $(LLILUM_ROOT)\Zelig\ZeligBuild\Target\bin\mbedOsAbstraction\Release\mbedOSAbstraction_$(TARGET).a endif else OBJECTS += \ $(TARGET)\Microsoft.Zelig.Test.mbed.Simple_opt.o \ $(TARGET)\mbed_adc.o \ $(TARGET)\mbed_asm.o \ $(TARGET)\mbed_clock.o \ $(TARGET)\mbed_core.o \ $(TARGET)\mbed_debug.o \ $(TARGET)\mbed_gpio.o \ $(TARGET)\mbed_i2c.o \ $(TARGET)\mbed_mem.o \ $(TARGET)\mbed_memory.o \ $(TARGET)\mbed_NVIC.o \ $(TARGET)\mbed_overrides.o \ $(TARGET)\mbed_pwm.o \ $(TARGET)\mbed_serial.o \ $(TARGET)\mbed_spi.o \ $(TARGET)\mbed_system_timer.o \ $(TARGET)\mbed_SysTick.o \ $(TARGET)\mbed_threading.o \ $(TARGET)\mbed_unwind.o \ endif # # Paths and includes # TODO: Make this algorithmic based on TARGET. # ifndef GCC_BIN $(error GCC_BIN is undefined. Define GCC_BIN to point to arm-none-eabi-xxx tools) endif ifndef TARGET $(error TARGET is undefined. Pass in TARGET for desired board) endif ifeq ($(HARDFP),1) FLOAT_ABI = hard else FLOAT_ABI = softfp endif ################### # General section # ################### # Common settings MBED_LIBS = $(LLILUM_ROOT)Zelig MBED_ROOT = $(LLILUM_ROOT)Zelig\mbed SOURCE_ROOT = $(LLILUM_ROOT)Zelig\Zelig\Test\mbed\SimpleSDK\Native LIBRARIES += -lmbed LD_SYS_LIBS = -lstdc++ -lsupc++ -lm -lc -lgcc -lnosys INCLUDE_PATHS = -I. -I$(MBED_ROOT) -I$(LLILUM_ROOT)Zelig\os_layer\inc -I$(LLILUM_ROOT)Zelig\os_layer\inc\api -I$(LLILUM_ROOT)Zelig\os_layer\inc\api\io -I$(LLILUM_ROOT)Zelig\os_layer\inc\hal # # LWIP Compilation and Libraries # ifeq ($(USE_LWIP), 1) # Define lwIP debug flags to build sys_arch libs for both checked and debug builds ifeq ($(LWIP_DEBUG), 1) CC_FLAGS += -DLWIP_DEBUG LIBRARIES += -llwIPd else ifeq ($(LWIP_DEBUG), 2) CC_FLAGS += -DLWIP_DEBUG LIBRARIES += -llwIPc else LIBRARIES += -llwIP endif # Adaptation layer ifeq ($(COMPILE_SYS_ARCH),1) # Used when compiling these objects for the lwipsysarch lib OBJECTS += $(TARGET)\checksum.o $(TARGET)\memcpy.o $(TARGET)\sys_arch.o else # Comment out when compiling this lib LIBRARIES += -llwipsysarch endif OBJECTS += \ $(TARGET)\mbed_ethernet.o \ $(TARGET)\mbed_socket.o \ ifeq ($(TARGET),K64F) # Ethernet controller # NOTE: mbed lib is in the back. Order matters, and it needs to be referenced after the lwip libs LIBRARIES += -lmbedeth -llwIPeth -lmbed endif LIBRARY_PATHS += -L$(MBED_LIBS)/lwip/lwip/lib INCLUDE_PATHS += -I$(MBED_ROOT)/EthernetInterface -I$(MBED_LIBS)\lwip\lwip -I$(MBED_LIBS)\lwip\lwip\include -I$(MBED_LIBS)\lwip\lwip\include\ipv4 -I$(MBED_LIBS)\lwip\lwip\include\ipv4\lwip -I$(MBED_LIBS)\lwip\lwip\include\lwip -I$(MBED_LIBS)\lwip\lwip\include\netif -I$(MBED_LIBS)\lwip\lwip\netif -I$(MBED_LIBS)\lwip/lwip/netif/ppp -I$(MBED_LIBS)\lwip/lwip/api -I$(MBED_LIBS)\lwip/lwip/core -I$(MBED_LIBS)\lwip/lwip/core/ipv4 -I$(MBED_LIBS)\lwip/lwip/core/snmp -I$(MBED_LIBS)\lwip/lwip-eth -I$(MBED_LIBS)\lwip/lwip-eth/arch -I$(MBED_LIBS)\lwip/lwip-sys -I$(MBED_LIBS)\lwip/lwip-sys/arch -I$(MBED_LIBS)\lwip/mbed-rtos/rtos -I$(MBED_LIBS)\lwip/mbed-rtos/llos -I$(MBED_LIBS)/mbed-rtos/llos/TARGET_CORTEX_M endif ########################## # Board specific section # ########################## # # LPC1768 settings # ifeq ($(TARGET),LPC1768) ifeq ($(HEAP_SIZE),) AS_FLAGS += --defsym __HEAP_SIZE=0x6000 CC_FLAGS += -D__HEAP_SIZE=0x6000 else AS_FLAGS += --defsym __HEAP_SIZE=$(HEAP_SIZE) CC_FLAGS += -D__HEAP_SIZE=$(HEAP_SIZE) endif # # Override defautl stack size for LPC1768 where teh total available RAM is only 32KB # ifeq ($(DEBUG), 1) CC_FLAGS += -D__DEFAULT_STACK_SIZE=0x800 endif OBJECTS += $(TARGET)\startup_LPC17xx.o SYS_OBJECTS = $(MBED_ROOT)\TARGET_LPC1768\TOOLCHAIN_GCC_ARM\board.o $(MBED_ROOT)\TARGET_LPC1768\TOOLCHAIN_GCC_ARM\cmsis_nvic.o $(MBED_ROOT)\TARGET_LPC1768\TOOLCHAIN_GCC_ARM\retarget.o $(MBED_ROOT)\TARGET_LPC1768\TOOLCHAIN_GCC_ARM\system_LPC17xx.o INCLUDE_PATHS += -I$(MBED_ROOT)\TARGET_LPC1768 -I$(MBED_ROOT)\TARGET_LPC1768\TOOLCHAIN_GCC_ARM -I$(MBED_ROOT)\TARGET_LPC1768\TARGET_NXP -I$(MBED_ROOT)\TARGET_LPC1768\TARGET_NXP\TARGET_LPC176X -I$(MBED_ROOT)\TARGET_LPC1768\TARGET_NXP\TARGET_LPC176X\TARGET_MBED_LPC1768 LIBRARY_PATHS += -L$(MBED_ROOT)\TARGET_LPC1768\TOOLCHAIN_GCC_ARM LINKER_SCRIPT = $(MBED_ROOT)\TARGET_LPC1768\TOOLCHAIN_GCC_ARM\LPC1768.ld # This is not ready for LPC1768 yet ifeq ($(USE_LWIP), 1) INCLUDE_PATHS += -I$(MBED_LIBS)/lwip/lwip-eth/arch/TARGET_NXP endif # Build flags CPU = -mcpu=cortex-m3 -mthumb CC_FLAGS += $(CPU) -c -g3 -gdwarf-4 -fvar-tracking-assignments -fno-common -fmessage-length=0 -Wall -fexceptions -ffunction-sections -fdata-sections -fomit-frame-pointer -MMD -MP CC_SYMBOLS = -DTARGET_LPC1768 -DTARGET_M3 -DTARGET_CORTEX_M -DTARGET_NXP -DTARGET_LPC176X -DTARGET_MBED_LPC1768 -DTOOLCHAIN_GCC_ARM -DTOOLCHAIN_GCC -D__CORTEX_M3 -DARM_MATH_CM3 -DMBED_BUILD_TIMESTAMP=1435185689.48 -D__MBED__=1 LD_FLAGS = $(CPU) -Wl,--gc-sections --specs=nano.specs -u _printf_float -u _scanf_float -Wl,--wrap,main -Wl,-Map=$(TARGET)\$(PROJECT).map,--cref # # K64F settings # else ifeq ($(TARGET),K64F) ifeq ($(HEAP_SIZE),) AS_FLAGS += --defsym __HEAP_SIZE=0x10000 CC_FLAGS += -D__HEAP_SIZE=0x10000 else AS_FLAGS += --defsym __HEAP_SIZE=$(HEAP_SIZE) CC_FLAGS += -D__HEAP_SIZE=$(HEAP_SIZE) endif OBJECTS += $(TARGET)\startup_MK64F12.o SYS_OBJECTS = $(MBED_ROOT)/TARGET_K64F/TOOLCHAIN_GCC_ARM/system_MK64F12.o $(MBED_ROOT)/TARGET_K64F/TOOLCHAIN_GCC_ARM/board.o $(MBED_ROOT)/TARGET_K64F/TOOLCHAIN_GCC_ARM/cmsis_nvic.o $(MBED_ROOT)/TARGET_K64F/TOOLCHAIN_GCC_ARM/retarget.o INCLUDE_PATHS += -I$(MBED_ROOT)/TARGET_K64F -I$(MBED_ROOT)/TARGET_K64F/TOOLCHAIN_GCC_ARM -I$(MBED_ROOT)/TARGET_K64F/TARGET_Freescale -I$(MBED_ROOT)/TARGET_K64F/TARGET_Freescale/TARGET_KPSDK_MCUS -I$(MBED_ROOT)/TARGET_K64F/TARGET_Freescale/TARGET_KPSDK_MCUS/TARGET_MCU_K64F -I$(MBED_ROOT)/TARGET_K64F/TARGET_Freescale/TARGET_KPSDK_MCUS/TARGET_MCU_K64F/MK64F12 -I$(MBED_ROOT)/TARGET_K64F/TARGET_Freescale/TARGET_KPSDK_MCUS/TARGET_MCU_K64F/device -I$(MBED_ROOT)/TARGET_K64F/TARGET_Freescale/TARGET_KPSDK_MCUS/TARGET_MCU_K64F/device/MK64F12 -I$(MBED_ROOT)/TARGET_K64F/TARGET_Freescale/TARGET_KPSDK_MCUS/TARGET_MCU_K64F/device/device -I$(MBED_ROOT)/TARGET_K64F/TARGET_Freescale/TARGET_KPSDK_MCUS/TARGET_MCU_K64F/device/device/MK64F12 -I$(MBED_ROOT)/TARGET_K64F/TARGET_Freescale/TARGET_KPSDK_MCUS/TARGET_MCU_K64F/TARGET_FRDM -I$(MBED_ROOT)/TARGET_K64F/TARGET_Freescale/TARGET_KPSDK_MCUS/TARGET_KPSDK_CODE -I$(MBED_ROOT)/TARGET_K64F/TARGET_Freescale/TARGET_KPSDK_MCUS/TARGET_KPSDK_CODE/common -I$(MBED_ROOT)/TARGET_K64F/TARGET_Freescale/TARGET_KPSDK_MCUS/TARGET_KPSDK_CODE/common/phyksz8081 -I$(MBED_ROOT)/TARGET_K64F/TARGET_Freescale/TARGET_KPSDK_MCUS/TARGET_KPSDK_CODE/hal -I$(MBED_ROOT)/TARGET_K64F/TARGET_Freescale/TARGET_KPSDK_MCUS/TARGET_KPSDK_CODE/hal/lptmr -I$(MBED_ROOT)/TARGET_K64F/TARGET_Freescale/TARGET_KPSDK_MCUS/TARGET_KPSDK_CODE/hal/dac -I$(MBED_ROOT)/TARGET_K64F/TARGET_Freescale/TARGET_KPSDK_MCUS/TARGET_KPSDK_CODE/hal/gpio -I$(MBED_ROOT)/TARGET_K64F/TARGET_Freescale/TARGET_KPSDK_MCUS/TARGET_KPSDK_CODE/hal/port -I$(MBED_ROOT)/TARGET_K64F/TARGET_Freescale/TARGET_KPSDK_MCUS/TARGET_KPSDK_CODE/hal/llwu -I$(MBED_ROOT)/TARGET_K64F/TARGET_Freescale/TARGET_KPSDK_MCUS/TARGET_KPSDK_CODE/hal/sim -I$(MBED_ROOT)/TARGET_K64F/TARGET_Freescale/TARGET_KPSDK_MCUS/TARGET_KPSDK_CODE/hal/rcm -I$(MBED_ROOT)/TARGET_K64F/TARGET_Freescale/TARGET_KPSDK_MCUS/TARGET_KPSDK_CODE/hal/sdhc -I$(MBED_ROOT)/TARGET_K64F/TARGET_Freescale/TARGET_KPSDK_MCUS/TARGET_KPSDK_CODE/hal/can -I$(MBED_ROOT)/TARGET_K64F/TARGET_Freescale/TARGET_KPSDK_MCUS/TARGET_KPSDK_CODE/hal/mpu -I$(MBED_ROOT)/TARGET_K64F/TARGET_Freescale/TARGET_KPSDK_MCUS/TARGET_KPSDK_CODE/hal/smc -I$(MBED_ROOT)/TARGET_K64F/TARGET_Freescale/TARGET_KPSDK_MCUS/TARGET_KPSDK_CODE/hal/osc -I$(MBED_ROOT)/TARGET_K64F/TARGET_Freescale/TARGET_KPSDK_MCUS/TARGET_KPSDK_CODE/hal/flextimer -I$(MBED_ROOT)/TARGET_K64F/TARGET_Freescale/TARGET_KPSDK_MCUS/TARGET_KPSDK_CODE/hal/pdb -I$(MBED_ROOT)/TARGET_K64F/TARGET_Freescale/TARGET_KPSDK_MCUS/TARGET_KPSDK_CODE/hal/enet -I$(MBED_ROOT)/TARGET_K64F/TARGET_Freescale/TARGET_KPSDK_MCUS/TARGET_KPSDK_CODE/hal/i2c -I$(MBED_ROOT)/TARGET_K64F/TARGET_Freescale/TARGET_KPSDK_MCUS/TARGET_KPSDK_CODE/hal/uart -I$(MBED_ROOT)/TARGET_K64F/TARGET_Freescale/TARGET_KPSDK_MCUS/TARGET_KPSDK_CODE/hal/dspi -I$(MBED_ROOT)/TARGET_K64F/TARGET_Freescale/TARGET_KPSDK_MCUS/TARGET_KPSDK_CODE/hal/pit -I$(MBED_ROOT)/TARGET_K64F/TARGET_Freescale/TARGET_KPSDK_MCUS/TARGET_KPSDK_CODE/hal/lpuart -I$(MBED_ROOT)/TARGET_K64F/TARGET_Freescale/TARGET_KPSDK_MCUS/TARGET_KPSDK_CODE/hal/sai -I$(MBED_ROOT)/TARGET_K64F/TARGET_Freescale/TARGET_KPSDK_MCUS/TARGET_KPSDK_CODE/hal/rtc -I$(MBED_ROOT)/TARGET_K64F/TARGET_Freescale/TARGET_KPSDK_MCUS/TARGET_KPSDK_CODE/hal/mcg -I$(MBED_ROOT)/TARGET_K64F/TARGET_Freescale/TARGET_KPSDK_MCUS/TARGET_KPSDK_CODE/hal/edma -I$(MBED_ROOT)/TARGET_K64F/TARGET_Freescale/TARGET_KPSDK_MCUS/TARGET_KPSDK_CODE/hal/pmc -I$(MBED_ROOT)/TARGET_K64F/TARGET_Freescale/TARGET_KPSDK_MCUS/TARGET_KPSDK_CODE/hal/adc -I$(MBED_ROOT)/TARGET_K64F/TARGET_Freescale/TARGET_KPSDK_MCUS/TARGET_KPSDK_CODE/hal/wdog -I$(MBED_ROOT)/TARGET_K64F/TARGET_Freescale/TARGET_KPSDK_MCUS/TARGET_KPSDK_CODE/hal/dmamux -I$(MBED_ROOT)/TARGET_K64F/TARGET_Freescale/TARGET_KPSDK_MCUS/TARGET_KPSDK_CODE/utilities -I$(MBED_ROOT)/TARGET_K64F/TARGET_Freescale/TARGET_KPSDK_MCUS/TARGET_KPSDK_CODE/drivers -I$(MBED_ROOT)/TARGET_K64F/TARGET_Freescale/TARGET_KPSDK_MCUS/TARGET_KPSDK_CODE/drivers/enet -I$(MBED_ROOT)/TARGET_K64F/TARGET_Freescale/TARGET_KPSDK_MCUS/TARGET_KPSDK_CODE/drivers/pit -I$(MBED_ROOT)/TARGET_K64F/TARGET_Freescale/TARGET_KPSDK_MCUS/TARGET_KPSDK_CODE/drivers/pit/common -I$(MBED_ROOT)/TARGET_K64F/TARGET_Freescale/TARGET_KPSDK_MCUS/TARGET_KPSDK_CODE/drivers/interrupt -I$(MBED_ROOT)/TARGET_K64F/TARGET_Freescale/TARGET_KPSDK_MCUS/TARGET_KPSDK_CODE/drivers/clock LIBRARY_PATHS += -L$(MBED_ROOT)/TARGET_K64F/TOOLCHAIN_GCC_ARM LINKER_SCRIPT = $(MBED_ROOT)/TARGET_K64F/TOOLCHAIN_GCC_ARM/K64FN1M0xxx12.ld ifeq ($(USE_LWIP), 1) INCLUDE_PATHS += -I$(MBED_LIBS)/lwip/lwip-eth/arch/TARGET_Freescale endif # Build flags CPU = -mcpu=cortex-m4 -mthumb -mfpu=fpv4-sp-d16 -mfloat-abi=$(FLOAT_ABI) CC_FLAGS += $(CPU) -c -g3 -gdwarf-4 -fvar-tracking-assignments -fno-common -fmessage-length=0 -Wall -fexceptions -ffunction-sections -fdata-sections -fomit-frame-pointer -MMD -MP CC_SYMBOLS = -DTARGET_K64F -DTARGET_M4 -DTARGET_CORTEX_M -DTARGET_Freescale -DTARGET_KPSDK_MCUS -DTARGET_KPSDK_CODE -DTARGET_MCU_K64F -DTARGET_FRDM -DTOOLCHAIN_GCC_ARM -DTOOLCHAIN_GCC -D__CORTEX_M4 -DARM_MATH_CM4 -D__FPU_PRESENT=1 -DMBED_BUILD_TIMESTAMP=1435855534.71 -D__MBED__=1 -DCPU_MK64FN1M0VMD12 -DFSL_RTOS_MBED -DTARGET_FF_ARDUINO LD_FLAGS = $(CPU) -Wl,--gc-sections --specs=nano.specs -u _printf_float -u _scanf_float -Wl,--wrap,main -Wl,-Map=$(TARGET)\$(PROJECT).map,--cref # # STM32L152 # else ifeq ($(TARGET),STM32L152) ifeq ($(HEAP_SIZE),) AS_FLAGS += --defsym __HEAP_SIZE=0x4000 else AS_FLAGS += --defsym __HEAP_SIZE=$(HEAP_SIZE) CC_FLAGS += -D__HEAP_SIZE=$(HEAP_SIZE) endif OBJECTS += $(TARGET)\startup_stm32l152xe.o SYS_OBJECTS = $(MBED_ROOT)/TARGET_NUCLEO_L152RE/TOOLCHAIN_GCC_ARM/stm32l1xx_hal_flash_ramfunc.o $(MBED_ROOT)/TARGET_NUCLEO_L152RE/TOOLCHAIN_GCC_ARM/board.o $(MBED_ROOT)/TARGET_NUCLEO_L152RE/TOOLCHAIN_GCC_ARM/cmsis_nvic.o $(MBED_ROOT)/TARGET_NUCLEO_L152RE/TOOLCHAIN_GCC_ARM/hal_tick.o $(MBED_ROOT)/TARGET_NUCLEO_L152RE/TOOLCHAIN_GCC_ARM/mbed_overrides.o $(MBED_ROOT)/TARGET_NUCLEO_L152RE/TOOLCHAIN_GCC_ARM/retarget.o $(MBED_ROOT)/TARGET_NUCLEO_L152RE/TOOLCHAIN_GCC_ARM/stm32l1xx_hal.o $(MBED_ROOT)/TARGET_NUCLEO_L152RE/TOOLCHAIN_GCC_ARM/stm32l1xx_hal_adc.o $(MBED_ROOT)/TARGET_NUCLEO_L152RE/TOOLCHAIN_GCC_ARM/stm32l1xx_hal_adc_ex.o $(MBED_ROOT)/TARGET_NUCLEO_L152RE/TOOLCHAIN_GCC_ARM/stm32l1xx_hal_comp.o $(MBED_ROOT)/TARGET_NUCLEO_L152RE/TOOLCHAIN_GCC_ARM/stm32l1xx_hal_cortex.o $(MBED_ROOT)/TARGET_NUCLEO_L152RE/TOOLCHAIN_GCC_ARM/stm32l1xx_hal_crc.o $(MBED_ROOT)/TARGET_NUCLEO_L152RE/TOOLCHAIN_GCC_ARM/stm32l1xx_hal_cryp.o $(MBED_ROOT)/TARGET_NUCLEO_L152RE/TOOLCHAIN_GCC_ARM/stm32l1xx_hal_cryp_ex.o $(MBED_ROOT)/TARGET_NUCLEO_L152RE/TOOLCHAIN_GCC_ARM/stm32l1xx_hal_dac.o $(MBED_ROOT)/TARGET_NUCLEO_L152RE/TOOLCHAIN_GCC_ARM/stm32l1xx_hal_dac_ex.o $(MBED_ROOT)/TARGET_NUCLEO_L152RE/TOOLCHAIN_GCC_ARM/stm32l1xx_hal_dma.o $(MBED_ROOT)/TARGET_NUCLEO_L152RE/TOOLCHAIN_GCC_ARM/stm32l1xx_hal_flash.o $(MBED_ROOT)/TARGET_NUCLEO_L152RE/TOOLCHAIN_GCC_ARM/stm32l1xx_hal_flash_ex.o $(MBED_ROOT)/TARGET_NUCLEO_L152RE/TOOLCHAIN_GCC_ARM/stm32l1xx_hal_smartcard.o $(MBED_ROOT)/TARGET_NUCLEO_L152RE/TOOLCHAIN_GCC_ARM/stm32l1xx_hal_gpio.o $(MBED_ROOT)/TARGET_NUCLEO_L152RE/TOOLCHAIN_GCC_ARM/stm32l1xx_hal_i2c.o $(MBED_ROOT)/TARGET_NUCLEO_L152RE/TOOLCHAIN_GCC_ARM/stm32l1xx_hal_i2s.o $(MBED_ROOT)/TARGET_NUCLEO_L152RE/TOOLCHAIN_GCC_ARM/stm32l1xx_hal_irda.o $(MBED_ROOT)/TARGET_NUCLEO_L152RE/TOOLCHAIN_GCC_ARM/stm32l1xx_hal_iwdg.o $(MBED_ROOT)/TARGET_NUCLEO_L152RE/TOOLCHAIN_GCC_ARM/stm32l1xx_hal_lcd.o $(MBED_ROOT)/TARGET_NUCLEO_L152RE/TOOLCHAIN_GCC_ARM/stm32l1xx_hal_nor.o $(MBED_ROOT)/TARGET_NUCLEO_L152RE/TOOLCHAIN_GCC_ARM/stm32l1xx_hal_opamp.o $(MBED_ROOT)/TARGET_NUCLEO_L152RE/TOOLCHAIN_GCC_ARM/stm32l1xx_hal_opamp_ex.o $(MBED_ROOT)/TARGET_NUCLEO_L152RE/TOOLCHAIN_GCC_ARM/stm32l1xx_hal_pcd.o $(MBED_ROOT)/TARGET_NUCLEO_L152RE/TOOLCHAIN_GCC_ARM/stm32l1xx_hal_pcd_ex.o $(MBED_ROOT)/TARGET_NUCLEO_L152RE/TOOLCHAIN_GCC_ARM/stm32l1xx_hal_pwr.o $(MBED_ROOT)/TARGET_NUCLEO_L152RE/TOOLCHAIN_GCC_ARM/stm32l1xx_hal_pwr_ex.o $(MBED_ROOT)/TARGET_NUCLEO_L152RE/TOOLCHAIN_GCC_ARM/stm32l1xx_hal_rcc.o $(MBED_ROOT)/TARGET_NUCLEO_L152RE/TOOLCHAIN_GCC_ARM/stm32l1xx_hal_rcc_ex.o $(MBED_ROOT)/TARGET_NUCLEO_L152RE/TOOLCHAIN_GCC_ARM/stm32l1xx_hal_rtc.o $(MBED_ROOT)/TARGET_NUCLEO_L152RE/TOOLCHAIN_GCC_ARM/stm32l1xx_hal_rtc_ex.o $(MBED_ROOT)/TARGET_NUCLEO_L152RE/TOOLCHAIN_GCC_ARM/stm32l1xx_hal_sd.o $(MBED_ROOT)/TARGET_NUCLEO_L152RE/TOOLCHAIN_GCC_ARM/stm32l1xx_hal_spi.o $(MBED_ROOT)/TARGET_NUCLEO_L152RE/TOOLCHAIN_GCC_ARM/stm32l1xx_hal_spi_ex.o $(MBED_ROOT)/TARGET_NUCLEO_L152RE/TOOLCHAIN_GCC_ARM/stm32l1xx_hal_sram.o $(MBED_ROOT)/TARGET_NUCLEO_L152RE/TOOLCHAIN_GCC_ARM/stm32l1xx_hal_tim.o $(MBED_ROOT)/TARGET_NUCLEO_L152RE/TOOLCHAIN_GCC_ARM/stm32l1xx_hal_tim_ex.o $(MBED_ROOT)/TARGET_NUCLEO_L152RE/TOOLCHAIN_GCC_ARM/stm32l1xx_hal_uart.o $(MBED_ROOT)/TARGET_NUCLEO_L152RE/TOOLCHAIN_GCC_ARM/stm32l1xx_hal_usart.o $(MBED_ROOT)/TARGET_NUCLEO_L152RE/TOOLCHAIN_GCC_ARM/stm32l1xx_hal_wwdg.o $(MBED_ROOT)/TARGET_NUCLEO_L152RE/TOOLCHAIN_GCC_ARM/stm32l1xx_ll_fsmc.o $(MBED_ROOT)/TARGET_NUCLEO_L152RE/TOOLCHAIN_GCC_ARM/stm32l1xx_ll_sdmmc.o $(MBED_ROOT)/TARGET_NUCLEO_L152RE/TOOLCHAIN_GCC_ARM/system_stm32l1xx.o INCLUDE_PATHS += -I$(MBED_ROOT)/TARGET_NUCLEO_L152RE -I$(MBED_ROOT)/TARGET_NUCLEO_L152RE/TARGET_STM -I$(MBED_ROOT)/TARGET_NUCLEO_L152RE/TARGET_STM/TARGET_STM32L1 -I$(MBED_ROOT)/TARGET_NUCLEO_L152RE/TARGET_STM/TARGET_STM32L1/TARGET_NUCLEO_L152RE -I$(MBED_ROOT)/TARGET_NUCLEO_L152RE/TOOLCHAIN_GCC_ARM LIBRARY_PATHS += -L$(MBED_ROOT)/TARGET_NUCLEO_L152RE/TOOLCHAIN_GCC_ARM LINKER_SCRIPT = $(MBED_ROOT)\TARGET_NUCLEO_L152RE\TOOLCHAIN_GCC_ARM\STM32L152XE.ld ifeq ($(USE_LWIP), 1) INCLUDE_PATHS += -I$(MBED_LIBS)/lwip/lwip-eth/arch/TARGET_STM endif # Build flags CPU = -mcpu=cortex-m3 -mthumb CC_FLAGS += $(CPU) -c -g -fno-common -fmessage-length=0 -Wall -Wextra -fexceptions -ffunction-sections -fdata-sections -fomit-frame-pointer -MMD -MP CC_SYMBOLS = -DMBED_BUILD_TIMESTAMP=1445629897.99 -DTARGET_FF_ARDUINO -DTOOLCHAIN_GCC_ARM -DTOOLCHAIN_GCC -DTARGET_FF_MORPHO -DTARGET_CORTEX_M -DARM_MATH_CM3 -DTARGET_STM32L1 -DTARGET_STM -D__CORTEX_M3 -DTARGET_NUCLEO_L152RE -DTARGET_M3 -DTARGET_STM32L152RE -D__MBED__=1 LD_FLAGS = $(CPU) -Wl,--gc-sections --specs=nano.specs -u _printf_float -u _scanf_float -Wl,--wrap,main -Wl,-Map=$(TARGET)\$(PROJECT).map,--cref # # STM32F411 # else ifeq ($(TARGET),STM32F411) ifeq ($(HEAP_SIZE),) AS_FLAGS += --defsym __HEAP_SIZE=0x10000 CC_FLAGS += -D__HEAP_SIZE=0x10000 else AS_FLAGS += --defsym __HEAP_SIZE=$(HEAP_SIZE) CC_FLAGS += -D__HEAP_SIZE=$(HEAP_SIZE) endif OBJECTS += $(TARGET)\startup_stm32f411xe.o SYS_OBJECTS = $(MBED_ROOT)/TARGET_NUCLEO_F411RE/TOOLCHAIN_GCC_ARM/stm32f4xx_hal_flash_ramfunc.o $(MBED_ROOT)/TARGET_NUCLEO_F411RE/TOOLCHAIN_GCC_ARM/board.o $(MBED_ROOT)/TARGET_NUCLEO_F411RE/TOOLCHAIN_GCC_ARM/cmsis_nvic.o $(MBED_ROOT)/TARGET_NUCLEO_F411RE/TOOLCHAIN_GCC_ARM/hal_tick.o $(MBED_ROOT)/TARGET_NUCLEO_F411RE/TOOLCHAIN_GCC_ARM/mbed_overrides.o $(MBED_ROOT)/TARGET_NUCLEO_F411RE/TOOLCHAIN_GCC_ARM/retarget.o $(MBED_ROOT)/TARGET_NUCLEO_F411RE/TOOLCHAIN_GCC_ARM/stm32f4xx_hal.o $(MBED_ROOT)/TARGET_NUCLEO_F411RE/TOOLCHAIN_GCC_ARM/stm32f4xx_hal_adc.o $(MBED_ROOT)/TARGET_NUCLEO_F411RE/TOOLCHAIN_GCC_ARM/stm32f4xx_hal_adc_ex.o $(MBED_ROOT)/TARGET_NUCLEO_F411RE/TOOLCHAIN_GCC_ARM/stm32f4xx_hal_can.o $(MBED_ROOT)/TARGET_NUCLEO_F411RE/TOOLCHAIN_GCC_ARM/stm32f4xx_hal_cec.o $(MBED_ROOT)/TARGET_NUCLEO_F411RE/TOOLCHAIN_GCC_ARM/stm32f4xx_hal_cortex.o $(MBED_ROOT)/TARGET_NUCLEO_F411RE/TOOLCHAIN_GCC_ARM/stm32f4xx_hal_crc.o $(MBED_ROOT)/TARGET_NUCLEO_F411RE/TOOLCHAIN_GCC_ARM/stm32f4xx_hal_cryp.o $(MBED_ROOT)/TARGET_NUCLEO_F411RE/TOOLCHAIN_GCC_ARM/stm32f4xx_hal_cryp_ex.o $(MBED_ROOT)/TARGET_NUCLEO_F411RE/TOOLCHAIN_GCC_ARM/stm32f4xx_hal_dac.o $(MBED_ROOT)/TARGET_NUCLEO_F411RE/TOOLCHAIN_GCC_ARM/stm32f4xx_hal_dac_ex.o $(MBED_ROOT)/TARGET_NUCLEO_F411RE/TOOLCHAIN_GCC_ARM/stm32f4xx_hal_dcmi.o $(MBED_ROOT)/TARGET_NUCLEO_F411RE/TOOLCHAIN_GCC_ARM/stm32f4xx_hal_dcmi_ex.o $(MBED_ROOT)/TARGET_NUCLEO_F411RE/TOOLCHAIN_GCC_ARM/stm32f4xx_hal_dma.o $(MBED_ROOT)/TARGET_NUCLEO_F411RE/TOOLCHAIN_GCC_ARM/stm32f4xx_hal_dma2d.o $(MBED_ROOT)/TARGET_NUCLEO_F411RE/TOOLCHAIN_GCC_ARM/stm32f4xx_hal_dma_ex.o $(MBED_ROOT)/TARGET_NUCLEO_F411RE/TOOLCHAIN_GCC_ARM/stm32f4xx_hal_dsi.o $(MBED_ROOT)/TARGET_NUCLEO_F411RE/TOOLCHAIN_GCC_ARM/stm32f4xx_hal_eth.o $(MBED_ROOT)/TARGET_NUCLEO_F411RE/TOOLCHAIN_GCC_ARM/stm32f4xx_hal_flash.o $(MBED_ROOT)/TARGET_NUCLEO_F411RE/TOOLCHAIN_GCC_ARM/stm32f4xx_hal_flash_ex.o $(MBED_ROOT)/TARGET_NUCLEO_F411RE/TOOLCHAIN_GCC_ARM/stm32f4xx_hal_fmpi2c_ex.o $(MBED_ROOT)/TARGET_NUCLEO_F411RE/TOOLCHAIN_GCC_ARM/stm32f4xx_hal_fmpi2c.o $(MBED_ROOT)/TARGET_NUCLEO_F411RE/TOOLCHAIN_GCC_ARM/stm32f4xx_hal_msp_template.o $(MBED_ROOT)/TARGET_NUCLEO_F411RE/TOOLCHAIN_GCC_ARM/stm32f4xx_hal_gpio.o $(MBED_ROOT)/TARGET_NUCLEO_F411RE/TOOLCHAIN_GCC_ARM/stm32f4xx_hal_hash.o $(MBED_ROOT)/TARGET_NUCLEO_F411RE/TOOLCHAIN_GCC_ARM/stm32f4xx_hal_hash_ex.o $(MBED_ROOT)/TARGET_NUCLEO_F411RE/TOOLCHAIN_GCC_ARM/stm32f4xx_hal_hcd.o $(MBED_ROOT)/TARGET_NUCLEO_F411RE/TOOLCHAIN_GCC_ARM/stm32f4xx_hal_i2c.o $(MBED_ROOT)/TARGET_NUCLEO_F411RE/TOOLCHAIN_GCC_ARM/stm32f4xx_hal_i2c_ex.o $(MBED_ROOT)/TARGET_NUCLEO_F411RE/TOOLCHAIN_GCC_ARM/stm32f4xx_hal_i2s.o $(MBED_ROOT)/TARGET_NUCLEO_F411RE/TOOLCHAIN_GCC_ARM/stm32f4xx_hal_i2s_ex.o $(MBED_ROOT)/TARGET_NUCLEO_F411RE/TOOLCHAIN_GCC_ARM/stm32f4xx_hal_irda.o $(MBED_ROOT)/TARGET_NUCLEO_F411RE/TOOLCHAIN_GCC_ARM/stm32f4xx_hal_iwdg.o $(MBED_ROOT)/TARGET_NUCLEO_F411RE/TOOLCHAIN_GCC_ARM/stm32f4xx_hal_lptim.o $(MBED_ROOT)/TARGET_NUCLEO_F411RE/TOOLCHAIN_GCC_ARM/stm32f4xx_hal_ltdc.o $(MBED_ROOT)/TARGET_NUCLEO_F411RE/TOOLCHAIN_GCC_ARM/stm32f4xx_hal_ltdc_ex.o $(MBED_ROOT)/TARGET_NUCLEO_F411RE/TOOLCHAIN_GCC_ARM/stm32f4xx_hal_smartcard.o $(MBED_ROOT)/TARGET_NUCLEO_F411RE/TOOLCHAIN_GCC_ARM/stm32f4xx_hal_nand.o $(MBED_ROOT)/TARGET_NUCLEO_F411RE/TOOLCHAIN_GCC_ARM/stm32f4xx_hal_nor.o $(MBED_ROOT)/TARGET_NUCLEO_F411RE/TOOLCHAIN_GCC_ARM/stm32f4xx_hal_pccard.o $(MBED_ROOT)/TARGET_NUCLEO_F411RE/TOOLCHAIN_GCC_ARM/stm32f4xx_hal_pcd.o $(MBED_ROOT)/TARGET_NUCLEO_F411RE/TOOLCHAIN_GCC_ARM/stm32f4xx_hal_pcd_ex.o $(MBED_ROOT)/TARGET_NUCLEO_F411RE/TOOLCHAIN_GCC_ARM/stm32f4xx_hal_pwr.o $(MBED_ROOT)/TARGET_NUCLEO_F411RE/TOOLCHAIN_GCC_ARM/stm32f4xx_hal_pwr_ex.o $(MBED_ROOT)/TARGET_NUCLEO_F411RE/TOOLCHAIN_GCC_ARM/stm32f4xx_hal_qspi.o $(MBED_ROOT)/TARGET_NUCLEO_F411RE/TOOLCHAIN_GCC_ARM/stm32f4xx_hal_rcc.o $(MBED_ROOT)/TARGET_NUCLEO_F411RE/TOOLCHAIN_GCC_ARM/stm32f4xx_hal_rcc_ex.o $(MBED_ROOT)/TARGET_NUCLEO_F411RE/TOOLCHAIN_GCC_ARM/stm32f4xx_hal_rng.o $(MBED_ROOT)/TARGET_NUCLEO_F411RE/TOOLCHAIN_GCC_ARM/stm32f4xx_hal_rtc.o $(MBED_ROOT)/TARGET_NUCLEO_F411RE/TOOLCHAIN_GCC_ARM/stm32f4xx_hal_rtc_ex.o $(MBED_ROOT)/TARGET_NUCLEO_F411RE/TOOLCHAIN_GCC_ARM/stm32f4xx_hal_sai.o $(MBED_ROOT)/TARGET_NUCLEO_F411RE/TOOLCHAIN_GCC_ARM/stm32f4xx_hal_sai_ex.o $(MBED_ROOT)/TARGET_NUCLEO_F411RE/TOOLCHAIN_GCC_ARM/stm32f4xx_hal_sd.o $(MBED_ROOT)/TARGET_NUCLEO_F411RE/TOOLCHAIN_GCC_ARM/stm32f4xx_hal_sdram.o $(MBED_ROOT)/TARGET_NUCLEO_F411RE/TOOLCHAIN_GCC_ARM/stm32f4xx_hal_spdifrx.o $(MBED_ROOT)/TARGET_NUCLEO_F411RE/TOOLCHAIN_GCC_ARM/stm32f4xx_hal_spi.o $(MBED_ROOT)/TARGET_NUCLEO_F411RE/TOOLCHAIN_GCC_ARM/stm32f4xx_hal_sram.o $(MBED_ROOT)/TARGET_NUCLEO_F411RE/TOOLCHAIN_GCC_ARM/stm32f4xx_hal_tim.o $(MBED_ROOT)/TARGET_NUCLEO_F411RE/TOOLCHAIN_GCC_ARM/stm32f4xx_hal_tim_ex.o $(MBED_ROOT)/TARGET_NUCLEO_F411RE/TOOLCHAIN_GCC_ARM/stm32f4xx_hal_uart.o $(MBED_ROOT)/TARGET_NUCLEO_F411RE/TOOLCHAIN_GCC_ARM/stm32f4xx_hal_usart.o $(MBED_ROOT)/TARGET_NUCLEO_F411RE/TOOLCHAIN_GCC_ARM/stm32f4xx_hal_wwdg.o $(MBED_ROOT)/TARGET_NUCLEO_F411RE/TOOLCHAIN_GCC_ARM/stm32f4xx_ll_fmc.o $(MBED_ROOT)/TARGET_NUCLEO_F411RE/TOOLCHAIN_GCC_ARM/stm32f4xx_ll_fsmc.o $(MBED_ROOT)/TARGET_NUCLEO_F411RE/TOOLCHAIN_GCC_ARM/stm32f4xx_ll_sdmmc.o $(MBED_ROOT)/TARGET_NUCLEO_F411RE/TOOLCHAIN_GCC_ARM/stm32f4xx_ll_usb.o $(MBED_ROOT)/TARGET_NUCLEO_F411RE/TOOLCHAIN_GCC_ARM/system_stm32f4xx.o INCLUDE_PATHS += -I$(MBED_ROOT)/TARGET_NUCLEO_F411RE -I$(MBED_ROOT)/TARGET_NUCLEO_F411RE/TARGET_STM -I$(MBED_ROOT)/TARGET_NUCLEO_F411RE/TARGET_STM/TARGET_STM32F4 -I$(MBED_ROOT)/TARGET_NUCLEO_F411RE/TARGET_STM/TARGET_STM32F4/TARGET_NUCLEO_F411RE -I$(MBED_ROOT)/TARGET_NUCLEO_F411RE/TOOLCHAIN_GCC_ARM LIBRARY_PATHS += -L$(MBED_ROOT)/TARGET_NUCLEO_F411RE/TOOLCHAIN_GCC_ARM LINKER_SCRIPT = $(MBED_ROOT)/TARGET_NUCLEO_F411RE/TOOLCHAIN_GCC_ARM/STM32F411XE.ld ifeq ($(USE_LWIP), 1) INCLUDE_PATHS += -I$(MBED_LIBS)/lwip/lwip-eth/arch/TARGET_STM endif CPU = -mcpu=cortex-m4 -mthumb -mfpu=fpv4-sp-d16 -mfloat-abi=$(FLOAT_ABI) CC_FLAGS += $(CPU) -c -g -fno-common -fmessage-length=0 -Wall -Wextra -fexceptions -ffunction-sections -fdata-sections -fomit-frame-pointer -MMD -MP CC_SYMBOLS = -DTARGET_FF_ARDUINO -DTOOLCHAIN_GCC_ARM -DTARGET_NUCLEO_F411RE -D__CORTEX_M4 -DTARGET_CORTEX_M -D__FPU_PRESENT=1 -D__MBED__=1 -DTARGET_M4 -DTARGET_FF_MORPHO -DTARGET_STM -DTARGET_STM32F4 -DTOOLCHAIN_GCC -DTARGET_STM32F411RE -DARM_MATH_CM4 -DMBED_BUILD_TIMESTAMP=1450373147.1 LD_FLAGS = $(CPU) -Wl,--gc-sections --specs=nano.specs -u _printf_float -u _scanf_float -Wl,--wrap,main -Wl,-Map=$(TARGET)\$(PROJECT).map,--cref # # STM32F401 # else ifeq ($(TARGET),STM32F401) ifeq ($(HEAP_SIZE),) AS_FLAGS += --defsym __HEAP_SIZE=0x10000 CC_FLAGS += -D__HEAP_SIZE=0x6000 else AS_FLAGS += --defsym __HEAP_SIZE=$(HEAP_SIZE) CC_FLAGS += -D__HEAP_SIZE=$(HEAP_SIZE) endif OBJECTS += $(TARGET)\startup_stm32f401xe.o SYS_OBJECTS = $(MBED_ROOT)/TARGET_NUCLEO_F401RE/TOOLCHAIN_GCC_ARM/stm32f4xx_hal_flash_ramfunc.o $(MBED_ROOT)/TARGET_NUCLEO_F401RE/TOOLCHAIN_GCC_ARM/board.o $(MBED_ROOT)/TARGET_NUCLEO_F401RE/TOOLCHAIN_GCC_ARM/cmsis_nvic.o $(MBED_ROOT)/TARGET_NUCLEO_F401RE/TOOLCHAIN_GCC_ARM/hal_tick.o $(MBED_ROOT)/TARGET_NUCLEO_F401RE/TOOLCHAIN_GCC_ARM/mbed_overrides.o $(MBED_ROOT)/TARGET_NUCLEO_F401RE/TOOLCHAIN_GCC_ARM/retarget.o $(MBED_ROOT)/TARGET_NUCLEO_F401RE/TOOLCHAIN_GCC_ARM/stm32f4xx_hal.o $(MBED_ROOT)/TARGET_NUCLEO_F401RE/TOOLCHAIN_GCC_ARM/stm32f4xx_hal_adc.o $(MBED_ROOT)/TARGET_NUCLEO_F401RE/TOOLCHAIN_GCC_ARM/stm32f4xx_hal_adc_ex.o $(MBED_ROOT)/TARGET_NUCLEO_F401RE/TOOLCHAIN_GCC_ARM/stm32f4xx_hal_can.o $(MBED_ROOT)/TARGET_NUCLEO_F401RE/TOOLCHAIN_GCC_ARM/stm32f4xx_hal_cec.o $(MBED_ROOT)/TARGET_NUCLEO_F401RE/TOOLCHAIN_GCC_ARM/stm32f4xx_hal_cortex.o $(MBED_ROOT)/TARGET_NUCLEO_F401RE/TOOLCHAIN_GCC_ARM/stm32f4xx_hal_crc.o $(MBED_ROOT)/TARGET_NUCLEO_F401RE/TOOLCHAIN_GCC_ARM/stm32f4xx_hal_cryp.o $(MBED_ROOT)/TARGET_NUCLEO_F401RE/TOOLCHAIN_GCC_ARM/stm32f4xx_hal_cryp_ex.o $(MBED_ROOT)/TARGET_NUCLEO_F401RE/TOOLCHAIN_GCC_ARM/stm32f4xx_hal_dac.o $(MBED_ROOT)/TARGET_NUCLEO_F401RE/TOOLCHAIN_GCC_ARM/stm32f4xx_hal_dac_ex.o $(MBED_ROOT)/TARGET_NUCLEO_F401RE/TOOLCHAIN_GCC_ARM/stm32f4xx_hal_dcmi.o $(MBED_ROOT)/TARGET_NUCLEO_F401RE/TOOLCHAIN_GCC_ARM/stm32f4xx_hal_dcmi_ex.o $(MBED_ROOT)/TARGET_NUCLEO_F401RE/TOOLCHAIN_GCC_ARM/stm32f4xx_hal_dma.o $(MBED_ROOT)/TARGET_NUCLEO_F401RE/TOOLCHAIN_GCC_ARM/stm32f4xx_hal_dma2d.o $(MBED_ROOT)/TARGET_NUCLEO_F401RE/TOOLCHAIN_GCC_ARM/stm32f4xx_hal_dma_ex.o $(MBED_ROOT)/TARGET_NUCLEO_F401RE/TOOLCHAIN_GCC_ARM/stm32f4xx_hal_dsi.o $(MBED_ROOT)/TARGET_NUCLEO_F401RE/TOOLCHAIN_GCC_ARM/stm32f4xx_hal_eth.o $(MBED_ROOT)/TARGET_NUCLEO_F401RE/TOOLCHAIN_GCC_ARM/stm32f4xx_hal_flash.o $(MBED_ROOT)/TARGET_NUCLEO_F401RE/TOOLCHAIN_GCC_ARM/stm32f4xx_hal_flash_ex.o $(MBED_ROOT)/TARGET_NUCLEO_F401RE/TOOLCHAIN_GCC_ARM/stm32f4xx_hal_fmpi2c_ex.o $(MBED_ROOT)/TARGET_NUCLEO_F401RE/TOOLCHAIN_GCC_ARM/stm32f4xx_hal_fmpi2c.o $(MBED_ROOT)/TARGET_NUCLEO_F401RE/TOOLCHAIN_GCC_ARM/stm32f4xx_hal_msp_template.o $(MBED_ROOT)/TARGET_NUCLEO_F401RE/TOOLCHAIN_GCC_ARM/stm32f4xx_hal_gpio.o $(MBED_ROOT)/TARGET_NUCLEO_F401RE/TOOLCHAIN_GCC_ARM/stm32f4xx_hal_hash.o $(MBED_ROOT)/TARGET_NUCLEO_F401RE/TOOLCHAIN_GCC_ARM/stm32f4xx_hal_hash_ex.o $(MBED_ROOT)/TARGET_NUCLEO_F401RE/TOOLCHAIN_GCC_ARM/stm32f4xx_hal_hcd.o $(MBED_ROOT)/TARGET_NUCLEO_F401RE/TOOLCHAIN_GCC_ARM/stm32f4xx_hal_i2c.o $(MBED_ROOT)/TARGET_NUCLEO_F401RE/TOOLCHAIN_GCC_ARM/stm32f4xx_hal_i2c_ex.o $(MBED_ROOT)/TARGET_NUCLEO_F401RE/TOOLCHAIN_GCC_ARM/stm32f4xx_hal_i2s.o $(MBED_ROOT)/TARGET_NUCLEO_F401RE/TOOLCHAIN_GCC_ARM/stm32f4xx_hal_i2s_ex.o $(MBED_ROOT)/TARGET_NUCLEO_F401RE/TOOLCHAIN_GCC_ARM/stm32f4xx_hal_irda.o $(MBED_ROOT)/TARGET_NUCLEO_F401RE/TOOLCHAIN_GCC_ARM/stm32f4xx_hal_iwdg.o $(MBED_ROOT)/TARGET_NUCLEO_F401RE/TOOLCHAIN_GCC_ARM/stm32f4xx_hal_lptim.o $(MBED_ROOT)/TARGET_NUCLEO_F401RE/TOOLCHAIN_GCC_ARM/stm32f4xx_hal_ltdc.o $(MBED_ROOT)/TARGET_NUCLEO_F401RE/TOOLCHAIN_GCC_ARM/stm32f4xx_hal_ltdc_ex.o $(MBED_ROOT)/TARGET_NUCLEO_F401RE/TOOLCHAIN_GCC_ARM/stm32f4xx_hal_smartcard.o $(MBED_ROOT)/TARGET_NUCLEO_F401RE/TOOLCHAIN_GCC_ARM/stm32f4xx_hal_nand.o $(MBED_ROOT)/TARGET_NUCLEO_F401RE/TOOLCHAIN_GCC_ARM/stm32f4xx_hal_nor.o $(MBED_ROOT)/TARGET_NUCLEO_F401RE/TOOLCHAIN_GCC_ARM/stm32f4xx_hal_pccard.o $(MBED_ROOT)/TARGET_NUCLEO_F401RE/TOOLCHAIN_GCC_ARM/stm32f4xx_hal_pcd.o $(MBED_ROOT)/TARGET_NUCLEO_F401RE/TOOLCHAIN_GCC_ARM/stm32f4xx_hal_pcd_ex.o $(MBED_ROOT)/TARGET_NUCLEO_F401RE/TOOLCHAIN_GCC_ARM/stm32f4xx_hal_pwr.o $(MBED_ROOT)/TARGET_NUCLEO_F401RE/TOOLCHAIN_GCC_ARM/stm32f4xx_hal_pwr_ex.o $(MBED_ROOT)/TARGET_NUCLEO_F401RE/TOOLCHAIN_GCC_ARM/stm32f4xx_hal_qspi.o $(MBED_ROOT)/TARGET_NUCLEO_F401RE/TOOLCHAIN_GCC_ARM/stm32f4xx_hal_rcc.o $(MBED_ROOT)/TARGET_NUCLEO_F401RE/TOOLCHAIN_GCC_ARM/stm32f4xx_hal_rcc_ex.o $(MBED_ROOT)/TARGET_NUCLEO_F401RE/TOOLCHAIN_GCC_ARM/stm32f4xx_hal_rng.o $(MBED_ROOT)/TARGET_NUCLEO_F401RE/TOOLCHAIN_GCC_ARM/stm32f4xx_hal_rtc.o $(MBED_ROOT)/TARGET_NUCLEO_F401RE/TOOLCHAIN_GCC_ARM/stm32f4xx_hal_rtc_ex.o $(MBED_ROOT)/TARGET_NUCLEO_F401RE/TOOLCHAIN_GCC_ARM/stm32f4xx_hal_sai.o $(MBED_ROOT)/TARGET_NUCLEO_F401RE/TOOLCHAIN_GCC_ARM/stm32f4xx_hal_sai_ex.o $(MBED_ROOT)/TARGET_NUCLEO_F401RE/TOOLCHAIN_GCC_ARM/stm32f4xx_hal_sd.o $(MBED_ROOT)/TARGET_NUCLEO_F401RE/TOOLCHAIN_GCC_ARM/stm32f4xx_hal_sdram.o $(MBED_ROOT)/TARGET_NUCLEO_F401RE/TOOLCHAIN_GCC_ARM/stm32f4xx_hal_spdifrx.o $(MBED_ROOT)/TARGET_NUCLEO_F401RE/TOOLCHAIN_GCC_ARM/stm32f4xx_hal_spi.o $(MBED_ROOT)/TARGET_NUCLEO_F401RE/TOOLCHAIN_GCC_ARM/stm32f4xx_hal_sram.o $(MBED_ROOT)/TARGET_NUCLEO_F401RE/TOOLCHAIN_GCC_ARM/stm32f4xx_hal_tim.o $(MBED_ROOT)/TARGET_NUCLEO_F401RE/TOOLCHAIN_GCC_ARM/stm32f4xx_hal_tim_ex.o $(MBED_ROOT)/TARGET_NUCLEO_F401RE/TOOLCHAIN_GCC_ARM/stm32f4xx_hal_uart.o $(MBED_ROOT)/TARGET_NUCLEO_F401RE/TOOLCHAIN_GCC_ARM/stm32f4xx_hal_usart.o $(MBED_ROOT)/TARGET_NUCLEO_F401RE/TOOLCHAIN_GCC_ARM/stm32f4xx_hal_wwdg.o $(MBED_ROOT)/TARGET_NUCLEO_F401RE/TOOLCHAIN_GCC_ARM/stm32f4xx_ll_fmc.o $(MBED_ROOT)/TARGET_NUCLEO_F401RE/TOOLCHAIN_GCC_ARM/stm32f4xx_ll_fsmc.o $(MBED_ROOT)/TARGET_NUCLEO_F401RE/TOOLCHAIN_GCC_ARM/stm32f4xx_ll_sdmmc.o $(MBED_ROOT)/TARGET_NUCLEO_F401RE/TOOLCHAIN_GCC_ARM/stm32f4xx_ll_usb.o $(MBED_ROOT)/TARGET_NUCLEO_F401RE/TOOLCHAIN_GCC_ARM/system_stm32f4xx.o INCLUDE_PATHS += -I$(MBED_ROOT)/TARGET_NUCLEO_F401RE -I$(MBED_ROOT)/TARGET_NUCLEO_F401RE/TARGET_STM -I$(MBED_ROOT)/TARGET_NUCLEO_F401RE/TARGET_STM/TARGET_STM32F4 -I$(MBED_ROOT)/TARGET_NUCLEO_F401RE/TARGET_STM/TARGET_STM32F4/TARGET_NUCLEO_F401RE -I$(MBED_ROOT)/TARGET_NUCLEO_F401RE/TOOLCHAIN_GCC_ARM LIBRARY_PATHS += -L$(MBED_ROOT)/TARGET_NUCLEO_F401RE/TOOLCHAIN_GCC_ARM LINKER_SCRIPT = $(MBED_ROOT)/TARGET_NUCLEO_F401RE/TOOLCHAIN_GCC_ARM/STM32F401XE.ld ifeq ($(USE_LWIP), 1) INCLUDE_PATHS += -I$(MBED_LIBS)/lwip/lwip-eth/arch/TARGET_STM endif CPU = -mcpu=cortex-m4 -mthumb -mfpu=fpv4-sp-d16 -mfloat-abi=$(FLOAT_ABI) CC_FLAGS += $(CPU) -c -g -fno-common -fmessage-length=0 -Wall -Wextra -fexceptions -ffunction-sections -fdata-sections -fomit-frame-pointer -MMD -MP CC_SYMBOLS = -DTARGET_FF_ARDUINO -DTOOLCHAIN_GCC_ARM -DTARGET_NUCLEO_F401RE -D__CORTEX_M4 -DTARGET_CORTEX_M -D__FPU_PRESENT=1 -D__MBED__=1 -DTARGET_M4 -DTARGET_FF_MORPHO -DTARGET_STM -DTARGET_STM32F4 -DTOOLCHAIN_GCC -DTARGET_STM32F401RE -DARM_MATH_CM4 -DMBED_BUILD_TIMESTAMP=1450373147.1 LD_FLAGS = $(CPU) -Wl,--gc-sections --specs=nano.specs -u _printf_float -u _scanf_float -Wl,--wrap,main -Wl,-Map=$(TARGET)\$(PROJECT).map,--cref # # STM32F091 # else ifeq ($(TARGET),STM32F091) ifeq ($(HEAP_SIZE),) AS_FLAGS += --defsym __HEAP_SIZE=0x6000 CC_FLAGS += -D__HEAP_SIZE=0x6000 else AS_FLAGS += --defsym __HEAP_SIZE=$(HEAP_SIZE) CC_FLAGS += -D__HEAP_SIZE=$(HEAP_SIZE) endif OBJECTS += $(TARGET)\startup_stm32f091xc.o SYS_OBJECTS = $(MBED_ROOT)/TARGET_NUCLEO_F091RC/TOOLCHAIN_GCC_ARM/stm32f0xx_hal_smartcard.o $(MBED_ROOT)/TARGET_NUCLEO_F091RC/TOOLCHAIN_GCC_ARM/board.o $(MBED_ROOT)/TARGET_NUCLEO_F091RC/TOOLCHAIN_GCC_ARM/cmsis_nvic.o $(MBED_ROOT)/TARGET_NUCLEO_F091RC/TOOLCHAIN_GCC_ARM/hal_tick.o $(MBED_ROOT)/TARGET_NUCLEO_F091RC/TOOLCHAIN_GCC_ARM/mbed_overrides.o $(MBED_ROOT)/TARGET_NUCLEO_F091RC/TOOLCHAIN_GCC_ARM/retarget.o $(MBED_ROOT)/TARGET_NUCLEO_F091RC/TOOLCHAIN_GCC_ARM/stm32f0xx_hal.o $(MBED_ROOT)/TARGET_NUCLEO_F091RC/TOOLCHAIN_GCC_ARM/stm32f0xx_hal_adc.o $(MBED_ROOT)/TARGET_NUCLEO_F091RC/TOOLCHAIN_GCC_ARM/stm32f0xx_hal_adc_ex.o $(MBED_ROOT)/TARGET_NUCLEO_F091RC/TOOLCHAIN_GCC_ARM/stm32f0xx_hal_can.o $(MBED_ROOT)/TARGET_NUCLEO_F091RC/TOOLCHAIN_GCC_ARM/stm32f0xx_hal_cec.o $(MBED_ROOT)/TARGET_NUCLEO_F091RC/TOOLCHAIN_GCC_ARM/stm32f0xx_hal_comp.o $(MBED_ROOT)/TARGET_NUCLEO_F091RC/TOOLCHAIN_GCC_ARM/stm32f0xx_hal_cortex.o $(MBED_ROOT)/TARGET_NUCLEO_F091RC/TOOLCHAIN_GCC_ARM/stm32f0xx_hal_crc.o $(MBED_ROOT)/TARGET_NUCLEO_F091RC/TOOLCHAIN_GCC_ARM/stm32f0xx_hal_crc_ex.o $(MBED_ROOT)/TARGET_NUCLEO_F091RC/TOOLCHAIN_GCC_ARM/stm32f0xx_hal_dac.o $(MBED_ROOT)/TARGET_NUCLEO_F091RC/TOOLCHAIN_GCC_ARM/stm32f0xx_hal_dac_ex.o $(MBED_ROOT)/TARGET_NUCLEO_F091RC/TOOLCHAIN_GCC_ARM/stm32f0xx_hal_dma.o $(MBED_ROOT)/TARGET_NUCLEO_F091RC/TOOLCHAIN_GCC_ARM/stm32f0xx_hal_flash.o $(MBED_ROOT)/TARGET_NUCLEO_F091RC/TOOLCHAIN_GCC_ARM/stm32f0xx_hal_flash_ex.o $(MBED_ROOT)/TARGET_NUCLEO_F091RC/TOOLCHAIN_GCC_ARM/stm32f0xx_hal_gpio.o $(MBED_ROOT)/TARGET_NUCLEO_F091RC/TOOLCHAIN_GCC_ARM/stm32f0xx_hal_i2c.o $(MBED_ROOT)/TARGET_NUCLEO_F091RC/TOOLCHAIN_GCC_ARM/stm32f0xx_hal_i2c_ex.o $(MBED_ROOT)/TARGET_NUCLEO_F091RC/TOOLCHAIN_GCC_ARM/stm32f0xx_hal_i2s.o $(MBED_ROOT)/TARGET_NUCLEO_F091RC/TOOLCHAIN_GCC_ARM/stm32f0xx_hal_irda.o $(MBED_ROOT)/TARGET_NUCLEO_F091RC/TOOLCHAIN_GCC_ARM/stm32f0xx_hal_iwdg.o $(MBED_ROOT)/TARGET_NUCLEO_F091RC/TOOLCHAIN_GCC_ARM/stm32f0xx_hal_pcd.o $(MBED_ROOT)/TARGET_NUCLEO_F091RC/TOOLCHAIN_GCC_ARM/stm32f0xx_hal_pcd_ex.o $(MBED_ROOT)/TARGET_NUCLEO_F091RC/TOOLCHAIN_GCC_ARM/stm32f0xx_hal_pwr.o $(MBED_ROOT)/TARGET_NUCLEO_F091RC/TOOLCHAIN_GCC_ARM/stm32f0xx_hal_pwr_ex.o $(MBED_ROOT)/TARGET_NUCLEO_F091RC/TOOLCHAIN_GCC_ARM/stm32f0xx_hal_rcc.o $(MBED_ROOT)/TARGET_NUCLEO_F091RC/TOOLCHAIN_GCC_ARM/stm32f0xx_hal_rcc_ex.o $(MBED_ROOT)/TARGET_NUCLEO_F091RC/TOOLCHAIN_GCC_ARM/stm32f0xx_hal_rtc.o $(MBED_ROOT)/TARGET_NUCLEO_F091RC/TOOLCHAIN_GCC_ARM/stm32f0xx_hal_rtc_ex.o $(MBED_ROOT)/TARGET_NUCLEO_F091RC/TOOLCHAIN_GCC_ARM/stm32f0xx_hal_smartcard_ex.o $(MBED_ROOT)/TARGET_NUCLEO_F091RC/TOOLCHAIN_GCC_ARM/stm32f0xx_hal_smbus.o $(MBED_ROOT)/TARGET_NUCLEO_F091RC/TOOLCHAIN_GCC_ARM/stm32f0xx_hal_spi.o $(MBED_ROOT)/TARGET_NUCLEO_F091RC/TOOLCHAIN_GCC_ARM/stm32f0xx_hal_spi_ex.o $(MBED_ROOT)/TARGET_NUCLEO_F091RC/TOOLCHAIN_GCC_ARM/stm32f0xx_hal_tim.o $(MBED_ROOT)/TARGET_NUCLEO_F091RC/TOOLCHAIN_GCC_ARM/stm32f0xx_hal_tim_ex.o $(MBED_ROOT)/TARGET_NUCLEO_F091RC/TOOLCHAIN_GCC_ARM/stm32f0xx_hal_tsc.o $(MBED_ROOT)/TARGET_NUCLEO_F091RC/TOOLCHAIN_GCC_ARM/stm32f0xx_hal_uart.o $(MBED_ROOT)/TARGET_NUCLEO_F091RC/TOOLCHAIN_GCC_ARM/stm32f0xx_hal_uart_ex.o $(MBED_ROOT)/TARGET_NUCLEO_F091RC/TOOLCHAIN_GCC_ARM/stm32f0xx_hal_usart.o $(MBED_ROOT)/TARGET_NUCLEO_F091RC/TOOLCHAIN_GCC_ARM/stm32f0xx_hal_wwdg.o $(MBED_ROOT)/TARGET_NUCLEO_F091RC/TOOLCHAIN_GCC_ARM/system_stm32f0xx.o INCLUDE_PATHS += -I$(MBED_ROOT)/TARGET_NUCLEO_F091RC -I$(MBED_ROOT)/TARGET_NUCLEO_F091RC/TARGET_STM -I$(MBED_ROOT)/TARGET_NUCLEO_F091RC/TARGET_STM/TARGET_STM32F0 -I$(MBED_ROOT)/TARGET_NUCLEO_F091RC/TARGET_STM/TARGET_STM32F0/TARGET_NUCLEO_F091RC -I$(MBED_ROOT)/TARGET_NUCLEO_F091RC/TOOLCHAIN_GCC_ARM LIBRARY_PATHS += -L$(MBED_ROOT)/TARGET_NUCLEO_F091RC/TOOLCHAIN_GCC_ARM LINKER_SCRIPT = $(MBED_ROOT)/TARGET_NUCLEO_F091RC/TOOLCHAIN_GCC_ARM/STM32F091XC.ld CPU = -mcpu=cortex-m0 -mthumb CC_FLAGS += $(CPU) -c -g -fno-common -fmessage-length=0 -Wall -Wextra -fexceptions -ffunction-sections -fdata-sections -fomit-frame-pointer -MMD -MP CC_SYMBOLS = -D__CORTEX_M0 -DMBED_BUILD_TIMESTAMP=1452888922.57 -DTARGET_FF_ARDUINO -DTOOLCHAIN_GCC_ARM -DTOOLCHAIN_GCC -DTARGET_FF_MORPHO -DTARGET_CORTEX_M -DARM_MATH_CM0 -DTARGET_STM -DTARGET_STM32F0 -DTARGET_M0 -DTARGET_NUCLEO_F091RC -DTARGET_STM32F091RC -D__MBED__=1 LD_FLAGS = $(CPU) -Wl,--gc-sections --specs=nano.specs -Wl,--wrap,main -Wl,-Map=$(TARGET)\$(PROJECT).map,--cref else $(error TARGET is not recognized. Please check the value passed in) endif DEPS = $(OBJECTS:.o=.d) ############### # Build tools # ############### AS = "$(GCC_BIN)arm-none-eabi-as" CC = "$(GCC_BIN)arm-none-eabi-gcc" CPP = "$(GCC_BIN)arm-none-eabi-g++" LD = "$(GCC_BIN)arm-none-eabi-gcc" OBJCOPY = "$(GCC_BIN)arm-none-eabi-objcopy" OBJDUMP = "$(GCC_BIN)arm-none-eabi-objdump" SIZE = "$(GCC_BIN)arm-none-eabi-size" ifeq ($(DEBUG), 1) CC_FLAGS += -DDEBUG -Og else CC_FLAGS += -DNDEBUG -Os endif ########### # Recipes # ########### .PHONY: all clean lst size all: ${TARGET} $(TARGET)\$(PROJECT).bin $(TARGET)\$(PROJECT).hex size dumps: ${TARGET} $(TARGET)\$(PROJECT).lst $(TARGET)\$(PROJECT).disasm # Conditionals (ifeq/ifneq) are bugged on Windows. Instead, we'll just ensure the directory exists and remove it unconditionally. cleanclean: ${TARGET} @del /q /f /s $(TARGET)\mbed*.o @del /q /f /s $(TARGET)\mbed*.d @del /q /f /s $(TARGET)\$(PROJECT).elf @del /q /f /s $(TARGET)\$(PROJECT).bin @del /q /f /s $(TARGET)\$(PROJECT).hex @del /q /f /s $(TARGET)\$(PROJECT).disasm @del /q /f /s $(TARGET)\$(PROJECT).lst @del /q /f /s $(TARGET)\$(PROJECT).map # Conditionals (ifeq/ifneq) are bugged on Windows. Instead, we'll just ensure the directory exists and remove it unconditionally. clean: ${TARGET} @del /q /f /s $(TARGET)\$(PROJECT).elf @del /q /f /s $(TARGET)\$(PROJECT).bin @del /q /f /s $(TARGET)\$(PROJECT).hex @del /q /f /s $(TARGET)\$(PROJECT).disasm @del /q /f /s $(TARGET)\$(PROJECT).lst @del /q /f /s $(TARGET)\$(PROJECT).map # Ensures the target directory has been created. ${TARGET}: @mkdir $@ $(TARGET)\\%.o: $(LLILUM_ROOT)\Zelig\os_layer\ARMv7M\Vectors\%.S $(AS) $(CPU) $(AS_FLAGS) -o $@ $< $(TARGET)\\%.o: $(LLILUM_ROOT)\Zelig\os_layer\ARMv7M\Vectors\%.s $(AS) $(CPU) $(AS_FLAGS) -o $@ $< $(TARGET)\\%.o: $(LLILUM_ROOT)\Zelig\os_layer\ports\mbed\%.S $(AS) $(CPU) $(AS_FLAGS) -o $@ $< $(TARGET)\\%.o: $(LLILUM_ROOT)\Zelig\lwip\lwip-sys\arch\%.c $(CC) $(CC_FLAGS) $(CC_SYMBOLS) -std=gnu99 $(INCLUDE_PATHS) -o $@ $< $(TARGET)\\%.o: %.c $(CC) $(CC_FLAGS) $(CC_SYMBOLS) -std=gnu99 $(INCLUDE_PATHS) -o $@ $< $(TARGET)\\%.o: $(SOURCE_ROOT)\%.cpp $(CPP) $(CC_FLAGS) $(CC_SYMBOLS) -std=gnu++98 -fno-rtti $(INCLUDE_PATHS) -o $@ $< $(TARGET)\\%.o: $(LLILUM_ROOT)\Zelig\os_layer\ports\mbed\%.cpp $(CPP) $(CC_FLAGS) $(CC_SYMBOLS) -std=gnu++98 -fno-rtti $(INCLUDE_PATHS) -o $@ $< $(TARGET)\$(PROJECT).elf: $(OBJECTS) $(SYS_OBJECTS) $(LD) $(LD_FLAGS) -T$(LINKER_SCRIPT) $(LIBRARY_PATHS) -o $@ $^ $(LIBRARIES) $(LD_SYS_LIBS) $(TARGET)\$(PROJECT).bin: $(TARGET)\$(PROJECT).elf $(OBJCOPY) -O binary $< $@ $(TARGET)\$(PROJECT).hex: $(TARGET)\$(PROJECT).elf @$(OBJCOPY) -O ihex $< $@ $(TARGET)\$(PROJECT).lst: $(TARGET)\$(PROJECT).elf @$(OBJDUMP) -Sdh $< > $@ $(TARGET)\$(PROJECT).disasm: $(TARGET)\$(PROJECT).elf @$(OBJDUMP) -D $< > $@ size: $(TARGET)\$(PROJECT).elf @echo Size report... $(SIZE) $< ================================================ FILE: Zelig/LLVM2IR_results/mbed/test/build.bat ================================================ @echo off setlocal enableDelayedExpansion IF %1.==. ( ECHO. ECHO Error no test name given. e.g. Build.bat GpioTest LPC1768 GOTO :EOF ) IF NOT EXIST "Microsoft.Zelig.Test.%1.ll" ( ECHO. ECHO Error invalid test name given: %1. Microsoft.Zelig.Test.%1.ll was not found! GOTO :EOF ) @REM - set this ENVIRONMENT Variable to override default optimization level for testing IF NOT DEFINED LLILUM_OPT_LEVEL SET LLILUM_OPT_LEVEL=2 IF /i "%LLVM_BIN%"=="" ( ECHO LLVM_BIN is not defined. Please define LLVM_BIN to point to LLVM tools and binaries. GOTO :EXIT ) IF /i "%GCC_BIN%"=="" ( ECHO GCC_BIN is not defined. Please define GCC_BIN to point to LLVM tools and binaries. GOTO :EXIT ) IF %2.==. ( ECHO No target passed in. Defaulting to LPC1768 set TARGET=LPC1768 set SIZE_OF_HEAP=0x6A00 ) ELSE ( ECHO Detected target: %2 set TARGET=%2 IF "%2"=="K64F" ( set SIZE_OF_HEAP=0x40000 ) ELSE ( set SIZE_OF_HEAP=0x6A00 ) ) @REM - To skip optimizations for testing you can set this ENVIRONMENT variable, otherwise the optimization will run as normal IF NOT DEFINED LLILUM_SKIP_OPT ( ECHO Running LLVM Optimization Phases... @REM -"%LLVM_BIN%\opt" -O2 -adce -globaldce Microsoft.Zelig.Test.%1.bc -o Microsoft.Zelig.Test.%1_opt.bc @REM -"%LLVM_BIN%\opt" -O1 -globalopt -constmerge -adce -globaldce -time-passes Microsoft.Zelig.Test.%1.bc -o Microsoft.Zelig.Test.%1_opt.bc "%LLVM_BIN%\opt" -verify-debug-info -verify-dom-info -verify-each -verify-loop-info -verify-regalloc -verify-region-info Microsoft.Zelig.Test.%1.bc -o Microsoft.Zelig.Test.%1_verify.bc "%LLVM_BIN%\opt" -march=thumb -mcpu=cortex-m3 -aa-eval -indvars -gvn -globaldce -adce -dce -tailcallopt -scalarrepl -mem2reg -ipconstprop -deadargelim -sccp -dce -ipsccp -dce -constmerge -scev-aa -targetlibinfo -irce -dse -dce -argpromotion -mem2reg -adce -mem2reg -globaldce -die -dce -dse -time-passes Microsoft.Zelig.Test.%1.bc -o Microsoft.Zelig.Test.%1_opt.bc ) else ( Echo Skipping optimization passes... copy Microsoft.Zelig.Test.%1.bc Microsoft.Zelig.Test.%1_opt.bc ) @REM -"%LLVM_BIN%\llvm-bcanalyzer" Microsoft.Zelig.Test.%1_opt.bc ECHO Cenerating LLVM IR source file... "%LLVM_BIN%\llvm-dis" Microsoft.Zelig.Test.%1_opt.bc ECHO Compiling to ARM... "%LLVM_BIN%\llc" -O%LLILUM_OPT_LEVEL% -code-model=small -data-sections -relocation-model=pic -march=thumb -mcpu=cortex-m3 -filetype=obj -mtriple=Thumb-NoSubArch-UnknownVendor-UnknownOS-GNUEABI-ELF -o=Microsoft.Zelig.Test.%1_opt.o Microsoft.Zelig.Test.%1_opt.bc if %ERRORLEVEL% LSS 0 ( @echo ERRORLEVEL=%ERRORLEVEL% goto :EXIT ) ECHO Size Report... "%GCC_BIN%\arm-none-eabi-size.exe" Microsoft.Zelig.Test.%1_opt.o ECHO. ECHO Linking with mbed libs... make clean TARGET=%TARGET% PROJECT=%1 make DEBUG=1 TARGET=%TARGET% HEAP_SIZE=%SIZE_OF_HEAP% PROJECT=%1 GOTO :EXIT :EXIT ECHO. ECHO Completed ================================================ FILE: Zelig/LLVM2IR_results/mbed/test/buildK64F.bat ================================================ @echo off IF %1.==. ( ECHO Error no test name given. e.g. BuildK64F.bat GpioTest GOTO :EOF ) "%dp~0%build.bat" %1 K64F EXIT /b ================================================ FILE: Zelig/LLVM2IR_results/mbed/test/buildLPC1768.bat ================================================ @echo off IF %1.==. ( ECHO Error no test name given. e.g. BuildK64F.bat GpioTest GOTO :EOF ) "%dp~0%build.bat" %1 LPC1768 EXIT /b ================================================ FILE: Zelig/LLVM2IR_results/mbed/test/debug.bat ================================================ @echo off IF /i "%GCC_BIN%"=="" ( ECHO GCC_BIN is not defined. Please define GCC_BIN to point to LLVM tools and binaries. GOTO :EXIT ) ECHO. ECHO Trying to start pyOCD for Windows START /I pyocd_win.exe PAUSE ECHO. ECHO Trying to attach to remote target on port 3333 "%GCC_BIN%arm-none-eabi-gdb.exe" %* exit /b ================================================ FILE: Zelig/LLVM2IR_results/mbed/test/debugK64F.bat ================================================ @echo off "%dp~0%debug.bat" K64F\*.elf %* -ex "target remote :3333" -ex "monitor halt reset" -ex "ni" exit /b ================================================ FILE: Zelig/LLVM2IR_results/mbed/test/debugLPC1768.bat ================================================ @echo off "%dp~0%debug.bat" LPC1768\*.elf %* -ex "target remote :3333" -ex "monitor halt reset" -ex "ni" exit /b ================================================ FILE: Zelig/LLVM2IR_results/mbed/test/deploy.bat ================================================ @ECHO OFF setlocal enabledelayedexpansion IF %1.==. ( ECHO No target passed in. Defaulting to LPC1768 set TARGET=LPC1768 ) ELSE ( ECHO Detected target: %1 set TARGET=%1 ) SET DEPLOY_DRIVE=e: IF "%2" NEQ "" ( set DEPLOY_DRIVE=%2 ) ELSE IF EXIST "e:\MBED.HTM" ( set DEPLOY_DRIVE=e: ) ELSE IF EXIST "f:\MBED.HTM" ( set DEPLOY_DRIVE=f: ) ELSE IF EXIST "g:\MBED.HTM" ( set DEPLOY_DRIVE=g: ) ELSE IF EXIST "h:\MBED.HTM" ( set DEPLOY_DRIVE=h: ) IF NOT EXIST %DEPLOY_DRIVE%\ ( @ECHO. @ECHO Error: device drive not found! @ECHO. GOTO :USAGE ) @ECHO Deleting old image (%DEPLOY_DRIVE%\*.bin) ... del %DEPLOY_DRIVE%\*.bin @ECHO Installing new image (%TARGET%\*.bin) to %DEPLOY_DRIVE%\... copy %TARGET%\*.bin %DEPLOY_DRIVE%\. @ECHO Complete! GOTO :EOF :USAGE @ECHO Usage: deploy.bat [DeployDeviceDrive] @ECHO e.g. 'deploy.bat e:' @ECHO. ================================================ FILE: Zelig/LLVM2IR_results/mbed/test/deployK64F.bat ================================================ deploy.bat K64F ================================================ FILE: Zelig/LLVM2IR_results/mbed/test/deployLPC1768.bat ================================================ deploy.bat LPC1768 ================================================ FILE: Zelig/LLVM2IR_results/mbed/test/makefile ================================================ # # Project-specific settings # VERBOSE=1 ifndef PROJECT $(error PROJECT is not defined. Define PROJECT to the target test.) endif # # TODO: Move InteropExports_* to common directory. # OBJECTS = .\Microsoft.Zelig.Test.$(PROJECT)_opt.o \ $(TARGET)\mbed_adc.o \ $(TARGET)\mbed_asm.o \ $(TARGET)\mbed_clock.o \ $(TARGET)\mbed_core.o \ $(TARGET)\mbed_debug.o \ $(TARGET)\mbed_gpio.o \ $(TARGET)\mbed_i2c.o \ $(TARGET)\mbed_mem.o \ $(TARGET)\mbed_memory.o \ $(TARGET)\mbed_NVIC.o \ $(TARGET)\mbed_pwm.o \ $(TARGET)\mbed_serial.o \ $(TARGET)\mbed_spi.o \ $(TARGET)\mbed_system_timer.o \ $(TARGET)\mbed_SysTick.o \ $(TARGET)\mbed_threading.o \ # # Paths and includes # TODO: Make this algorithmic based on TARGET. # ifndef GCC_BIN $(error GCC_BIN is undefined. Define GCC_BIN to point to arm-none-eabi-xxx tools) endif ifndef TARGET $(error TARGET is undefined. Pass in TARGET for desired board) endif ifeq ($(HARDFP),1) FLOAT_ABI = hard else FLOAT_ABI = softfp endif # Common settings MBED_ROOT = $(LLILUM_ROOT)Zelig\mbed SOURCE_ROOT = $(LLILUM_ROOT)Zelig\LLVM2IR_results\mbed\test LIBRARIES = -lmbed LD_SYS_LIBS = -lstdc++ -lsupc++ -lm -lc -lgcc -lnosys INCLUDE_PATHS = -I. -I$(MBED_ROOT) -I$(LLILUM_ROOT)Zelig\os_layer\inc -I$(LLILUM_ROOT)Zelig\os_layer\inc\api -I$(LLILUM_ROOT)Zelig\os_layer\inc\api\io -I$(LLILUM_ROOT)Zelig\os_layer\inc\hal # LPC1768 settings ifeq ($(TARGET),LPC1768) ifeq ($(HEAP_SIZE),) AS_FLAGS += --defsym __HEAP_SIZE=0x4000 CC_FLAGS += -D__HEAP_SIZE=0x4000 else AS_FLAGS += --defsym __HEAP_SIZE=$(HEAP_SIZE) CC_FLAGS += -D__HEAP_SIZE=$(HEAP_SIZE) endif OBJECTS += $(TARGET)\startup_LPC17xx.o SYS_OBJECTS = $(MBED_ROOT)\TARGET_LPC1768\TOOLCHAIN_GCC_ARM\board.o $(MBED_ROOT)\TARGET_LPC1768\TOOLCHAIN_GCC_ARM\cmsis_nvic.o $(MBED_ROOT)\TARGET_LPC1768\TOOLCHAIN_GCC_ARM\retarget.o $(MBED_ROOT)\TARGET_LPC1768\TOOLCHAIN_GCC_ARM\system_LPC17xx.o INCLUDE_PATHS += -I$(MBED_ROOT)\TARGET_LPC1768 -I$(MBED_ROOT)\TARGET_LPC1768\TOOLCHAIN_GCC_ARM -I$(MBED_ROOT)\TARGET_LPC1768\TARGET_NXP -I$(MBED_ROOT)\TARGET_LPC1768\TARGET_NXP\TARGET_LPC176X -I$(MBED_ROOT)\TARGET_LPC1768\TARGET_NXP\TARGET_LPC176X\TARGET_MBED_LPC1768 LIBRARY_PATHS = -L$(MBED_ROOT)\TARGET_LPC1768\TOOLCHAIN_GCC_ARM LINKER_SCRIPT = $(MBED_ROOT)\TARGET_LPC1768\TOOLCHAIN_GCC_ARM\LPC1768.ld # Build flags CPU = -mcpu=cortex-m3 -mthumb CC_FLAGS += $(CPU) -c -g3 -gdwarf-4 -fvar-tracking-assignments -fno-common -fmessage-length=0 -Wall -fno-exceptions -ffunction-sections -fdata-sections -fomit-frame-pointer -MMD -MP CC_SYMBOLS = -DTARGET_LPC1768 -DTARGET_M3 -DTARGET_CORTEX_M -DTARGET_NXP -DTARGET_LPC176X -DTARGET_MBED_LPC1768 -DTOOLCHAIN_GCC_ARM -DTOOLCHAIN_GCC -D__CORTEX_M3 -DARM_MATH_CM3 -DMBED_BUILD_TIMESTAMP=1435185689.48 -D__MBED__=1 LD_FLAGS = $(CPU) -Wl,--gc-sections --specs=nano.specs -u _printf_float -u _scanf_float -Wl,--wrap,main -Wl,-Map=$(TARGET)\$(PROJECT).map,--cref # K64F settings else ifeq ($(TARGET),K64F) ifeq ($(HEAP_SIZE),) AS_FLAGS += --defsym __HEAP_SIZE=0x10000 CC_FLAGS += -D__HEAP_SIZE=0x10000 else AS_FLAGS += --defsym __HEAP_SIZE=$(HEAP_SIZE) CC_FLAGS += -D__HEAP_SIZE=$(HEAP_SIZE) endif OBJECTS += $(TARGET)\startup_MK64F12.o # SYS_OBJECTS = $(MBED_ROOT)/TARGET_K64F/TOOLCHAIN_GCC_ARM/mbed_overrides.o $(MBED_ROOT)/TARGET_K64F/TOOLCHAIN_GCC_ARM/system_MK64F12.o $(MBED_ROOT)/TARGET_K64F/TOOLCHAIN_GCC_ARM/board.o $(MBED_ROOT)/TARGET_K64F/TOOLCHAIN_GCC_ARM/cmsis_nvic.o $(MBED_ROOT)/TARGET_K64F/TOOLCHAIN_GCC_ARM/retarget.o SYS_OBJECTS = $(MBED_ROOT)/TARGET_K64F/TOOLCHAIN_GCC_ARM/system_MK64F12.o $(MBED_ROOT)/TARGET_K64F/TOOLCHAIN_GCC_ARM/board.o $(MBED_ROOT)/TARGET_K64F/TOOLCHAIN_GCC_ARM/cmsis_nvic.o $(MBED_ROOT)/TARGET_K64F/TOOLCHAIN_GCC_ARM/retarget.o INCLUDE_PATHS += -I$(MBED_ROOT)/TARGET_K64F -I$(MBED_ROOT)/TARGET_K64F/TOOLCHAIN_GCC_ARM -I$(MBED_ROOT)/TARGET_K64F/TARGET_Freescale -I$(MBED_ROOT)/TARGET_K64F/TARGET_Freescale/TARGET_KPSDK_MCUS -I$(MBED_ROOT)/TARGET_K64F/TARGET_Freescale/TARGET_KPSDK_MCUS/TARGET_MCU_K64F -I$(MBED_ROOT)/TARGET_K64F/TARGET_Freescale/TARGET_KPSDK_MCUS/TARGET_MCU_K64F/MK64F12 -I$(MBED_ROOT)/TARGET_K64F/TARGET_Freescale/TARGET_KPSDK_MCUS/TARGET_MCU_K64F/device -I$(MBED_ROOT)/TARGET_K64F/TARGET_Freescale/TARGET_KPSDK_MCUS/TARGET_MCU_K64F/device/MK64F12 -I$(MBED_ROOT)/TARGET_K64F/TARGET_Freescale/TARGET_KPSDK_MCUS/TARGET_MCU_K64F/device/device -I$(MBED_ROOT)/TARGET_K64F/TARGET_Freescale/TARGET_KPSDK_MCUS/TARGET_MCU_K64F/device/device/MK64F12 -I$(MBED_ROOT)/TARGET_K64F/TARGET_Freescale/TARGET_KPSDK_MCUS/TARGET_MCU_K64F/TARGET_FRDM -I$(MBED_ROOT)/TARGET_K64F/TARGET_Freescale/TARGET_KPSDK_MCUS/TARGET_KPSDK_CODE -I$(MBED_ROOT)/TARGET_K64F/TARGET_Freescale/TARGET_KPSDK_MCUS/TARGET_KPSDK_CODE/common -I$(MBED_ROOT)/TARGET_K64F/TARGET_Freescale/TARGET_KPSDK_MCUS/TARGET_KPSDK_CODE/common/phyksz8081 -I$(MBED_ROOT)/TARGET_K64F/TARGET_Freescale/TARGET_KPSDK_MCUS/TARGET_KPSDK_CODE/hal -I$(MBED_ROOT)/TARGET_K64F/TARGET_Freescale/TARGET_KPSDK_MCUS/TARGET_KPSDK_CODE/hal/lptmr -I$(MBED_ROOT)/TARGET_K64F/TARGET_Freescale/TARGET_KPSDK_MCUS/TARGET_KPSDK_CODE/hal/dac -I$(MBED_ROOT)/TARGET_K64F/TARGET_Freescale/TARGET_KPSDK_MCUS/TARGET_KPSDK_CODE/hal/gpio -I$(MBED_ROOT)/TARGET_K64F/TARGET_Freescale/TARGET_KPSDK_MCUS/TARGET_KPSDK_CODE/hal/port -I$(MBED_ROOT)/TARGET_K64F/TARGET_Freescale/TARGET_KPSDK_MCUS/TARGET_KPSDK_CODE/hal/llwu -I$(MBED_ROOT)/TARGET_K64F/TARGET_Freescale/TARGET_KPSDK_MCUS/TARGET_KPSDK_CODE/hal/sim -I$(MBED_ROOT)/TARGET_K64F/TARGET_Freescale/TARGET_KPSDK_MCUS/TARGET_KPSDK_CODE/hal/rcm -I$(MBED_ROOT)/TARGET_K64F/TARGET_Freescale/TARGET_KPSDK_MCUS/TARGET_KPSDK_CODE/hal/sdhc -I$(MBED_ROOT)/TARGET_K64F/TARGET_Freescale/TARGET_KPSDK_MCUS/TARGET_KPSDK_CODE/hal/can -I$(MBED_ROOT)/TARGET_K64F/TARGET_Freescale/TARGET_KPSDK_MCUS/TARGET_KPSDK_CODE/hal/mpu -I$(MBED_ROOT)/TARGET_K64F/TARGET_Freescale/TARGET_KPSDK_MCUS/TARGET_KPSDK_CODE/hal/smc -I$(MBED_ROOT)/TARGET_K64F/TARGET_Freescale/TARGET_KPSDK_MCUS/TARGET_KPSDK_CODE/hal/osc -I$(MBED_ROOT)/TARGET_K64F/TARGET_Freescale/TARGET_KPSDK_MCUS/TARGET_KPSDK_CODE/hal/flextimer -I$(MBED_ROOT)/TARGET_K64F/TARGET_Freescale/TARGET_KPSDK_MCUS/TARGET_KPSDK_CODE/hal/pdb -I$(MBED_ROOT)/TARGET_K64F/TARGET_Freescale/TARGET_KPSDK_MCUS/TARGET_KPSDK_CODE/hal/enet -I$(MBED_ROOT)/TARGET_K64F/TARGET_Freescale/TARGET_KPSDK_MCUS/TARGET_KPSDK_CODE/hal/i2c -I$(MBED_ROOT)/TARGET_K64F/TARGET_Freescale/TARGET_KPSDK_MCUS/TARGET_KPSDK_CODE/hal/uart -I$(MBED_ROOT)/TARGET_K64F/TARGET_Freescale/TARGET_KPSDK_MCUS/TARGET_KPSDK_CODE/hal/dspi -I$(MBED_ROOT)/TARGET_K64F/TARGET_Freescale/TARGET_KPSDK_MCUS/TARGET_KPSDK_CODE/hal/pit -I$(MBED_ROOT)/TARGET_K64F/TARGET_Freescale/TARGET_KPSDK_MCUS/TARGET_KPSDK_CODE/hal/lpuart -I$(MBED_ROOT)/TARGET_K64F/TARGET_Freescale/TARGET_KPSDK_MCUS/TARGET_KPSDK_CODE/hal/sai -I$(MBED_ROOT)/TARGET_K64F/TARGET_Freescale/TARGET_KPSDK_MCUS/TARGET_KPSDK_CODE/hal/rtc -I$(MBED_ROOT)/TARGET_K64F/TARGET_Freescale/TARGET_KPSDK_MCUS/TARGET_KPSDK_CODE/hal/mcg -I$(MBED_ROOT)/TARGET_K64F/TARGET_Freescale/TARGET_KPSDK_MCUS/TARGET_KPSDK_CODE/hal/edma -I$(MBED_ROOT)/TARGET_K64F/TARGET_Freescale/TARGET_KPSDK_MCUS/TARGET_KPSDK_CODE/hal/pmc -I$(MBED_ROOT)/TARGET_K64F/TARGET_Freescale/TARGET_KPSDK_MCUS/TARGET_KPSDK_CODE/hal/adc -I$(MBED_ROOT)/TARGET_K64F/TARGET_Freescale/TARGET_KPSDK_MCUS/TARGET_KPSDK_CODE/hal/wdog -I$(MBED_ROOT)/TARGET_K64F/TARGET_Freescale/TARGET_KPSDK_MCUS/TARGET_KPSDK_CODE/hal/dmamux -I$(MBED_ROOT)/TARGET_K64F/TARGET_Freescale/TARGET_KPSDK_MCUS/TARGET_KPSDK_CODE/utilities -I$(MBED_ROOT)/TARGET_K64F/TARGET_Freescale/TARGET_KPSDK_MCUS/TARGET_KPSDK_CODE/drivers -I$(MBED_ROOT)/TARGET_K64F/TARGET_Freescale/TARGET_KPSDK_MCUS/TARGET_KPSDK_CODE/drivers/enet -I$(MBED_ROOT)/TARGET_K64F/TARGET_Freescale/TARGET_KPSDK_MCUS/TARGET_KPSDK_CODE/drivers/pit -I$(MBED_ROOT)/TARGET_K64F/TARGET_Freescale/TARGET_KPSDK_MCUS/TARGET_KPSDK_CODE/drivers/pit/common -I$(MBED_ROOT)/TARGET_K64F/TARGET_Freescale/TARGET_KPSDK_MCUS/TARGET_KPSDK_CODE/drivers/interrupt -I$(MBED_ROOT)/TARGET_K64F/TARGET_Freescale/TARGET_KPSDK_MCUS/TARGET_KPSDK_CODE/drivers/clock LIBRARY_PATHS = -L$(MBED_ROOT)/TARGET_K64F/TOOLCHAIN_GCC_ARM LINKER_SCRIPT = $(MBED_ROOT)/TARGET_K64F/TOOLCHAIN_GCC_ARM/K64FN1M0xxx12.ld # Build flags CPU = -mcpu=cortex-m4 -mthumb -mfpu=fpv4-sp-d16 -mfloat-abi=$(FLOAT_ABI) CC_FLAGS += $(CPU) -c -g3 -gdwarf-4 -fvar-tracking-assignments -fno-common -fmessage-length=0 -Wall -fno-exceptions -ffunction-sections -fdata-sections -fomit-frame-pointer -MMD -MP CC_SYMBOLS = -DTARGET_K64F -DTARGET_M4 -DTARGET_CORTEX_M -DTARGET_Freescale -DTARGET_KPSDK_MCUS -DTARGET_KPSDK_CODE -DTARGET_MCU_K64F -DTARGET_FRDM -DTOOLCHAIN_GCC_ARM -DTOOLCHAIN_GCC -D__CORTEX_M4 -DARM_MATH_CM4 -D__FPU_PRESENT=1 -DMBED_BUILD_TIMESTAMP=1435855534.71 -D__MBED__=1 -DCPU_MK64FN1M0VMD12 -DFSL_RTOS_MBED -DTARGET_FF_ARDUINO LD_FLAGS = $(CPU) -Wl,--gc-sections --specs=nano.specs -u _printf_float -u _scanf_float -Wl,--wrap,main -Wl,-Map=$(TARGET)\$(PROJECT).map,--cref # STM32L152 else ifeq ($(TARGET),STM32L152) ifeq ($(HEAP_SIZE),) AS_FLAGS += --defsym __HEAP_SIZE=0x4000 CC_FLAGS += -D__HEAP_SIZE=0x4000 else AS_FLAGS += --defsym __HEAP_SIZE=$(HEAP_SIZE) CC_FLAGS += -D__HEAP_SIZE=$(HEAP_SIZE) endif OBJECTS += $(TARGET)\startup_stm32l152xe.o SYS_OBJECTS = $(MBED_ROOT)/TARGET_NUCLEO_L152RE/TOOLCHAIN_GCC_ARM/stm32l1xx_hal_flash_ramfunc.o $(MBED_ROOT)/TARGET_NUCLEO_L152RE/TOOLCHAIN_GCC_ARM/board.o $(MBED_ROOT)/TARGET_NUCLEO_L152RE/TOOLCHAIN_GCC_ARM/cmsis_nvic.o $(MBED_ROOT)/TARGET_NUCLEO_L152RE/TOOLCHAIN_GCC_ARM/hal_tick.o $(MBED_ROOT)/TARGET_NUCLEO_L152RE/TOOLCHAIN_GCC_ARM/mbed_overrides.o $(MBED_ROOT)/TARGET_NUCLEO_L152RE/TOOLCHAIN_GCC_ARM/retarget.o $(MBED_ROOT)/TARGET_NUCLEO_L152RE/TOOLCHAIN_GCC_ARM/stm32l1xx_hal.o $(MBED_ROOT)/TARGET_NUCLEO_L152RE/TOOLCHAIN_GCC_ARM/stm32l1xx_hal_adc.o $(MBED_ROOT)/TARGET_NUCLEO_L152RE/TOOLCHAIN_GCC_ARM/stm32l1xx_hal_adc_ex.o $(MBED_ROOT)/TARGET_NUCLEO_L152RE/TOOLCHAIN_GCC_ARM/stm32l1xx_hal_comp.o $(MBED_ROOT)/TARGET_NUCLEO_L152RE/TOOLCHAIN_GCC_ARM/stm32l1xx_hal_cortex.o $(MBED_ROOT)/TARGET_NUCLEO_L152RE/TOOLCHAIN_GCC_ARM/stm32l1xx_hal_crc.o $(MBED_ROOT)/TARGET_NUCLEO_L152RE/TOOLCHAIN_GCC_ARM/stm32l1xx_hal_cryp.o $(MBED_ROOT)/TARGET_NUCLEO_L152RE/TOOLCHAIN_GCC_ARM/stm32l1xx_hal_cryp_ex.o $(MBED_ROOT)/TARGET_NUCLEO_L152RE/TOOLCHAIN_GCC_ARM/stm32l1xx_hal_dac.o $(MBED_ROOT)/TARGET_NUCLEO_L152RE/TOOLCHAIN_GCC_ARM/stm32l1xx_hal_dac_ex.o $(MBED_ROOT)/TARGET_NUCLEO_L152RE/TOOLCHAIN_GCC_ARM/stm32l1xx_hal_dma.o $(MBED_ROOT)/TARGET_NUCLEO_L152RE/TOOLCHAIN_GCC_ARM/stm32l1xx_hal_flash.o $(MBED_ROOT)/TARGET_NUCLEO_L152RE/TOOLCHAIN_GCC_ARM/stm32l1xx_hal_flash_ex.o $(MBED_ROOT)/TARGET_NUCLEO_L152RE/TOOLCHAIN_GCC_ARM/stm32l1xx_hal_smartcard.o $(MBED_ROOT)/TARGET_NUCLEO_L152RE/TOOLCHAIN_GCC_ARM/stm32l1xx_hal_gpio.o $(MBED_ROOT)/TARGET_NUCLEO_L152RE/TOOLCHAIN_GCC_ARM/stm32l1xx_hal_i2c.o $(MBED_ROOT)/TARGET_NUCLEO_L152RE/TOOLCHAIN_GCC_ARM/stm32l1xx_hal_i2s.o $(MBED_ROOT)/TARGET_NUCLEO_L152RE/TOOLCHAIN_GCC_ARM/stm32l1xx_hal_irda.o $(MBED_ROOT)/TARGET_NUCLEO_L152RE/TOOLCHAIN_GCC_ARM/stm32l1xx_hal_iwdg.o $(MBED_ROOT)/TARGET_NUCLEO_L152RE/TOOLCHAIN_GCC_ARM/stm32l1xx_hal_lcd.o $(MBED_ROOT)/TARGET_NUCLEO_L152RE/TOOLCHAIN_GCC_ARM/stm32l1xx_hal_nor.o $(MBED_ROOT)/TARGET_NUCLEO_L152RE/TOOLCHAIN_GCC_ARM/stm32l1xx_hal_opamp.o $(MBED_ROOT)/TARGET_NUCLEO_L152RE/TOOLCHAIN_GCC_ARM/stm32l1xx_hal_opamp_ex.o $(MBED_ROOT)/TARGET_NUCLEO_L152RE/TOOLCHAIN_GCC_ARM/stm32l1xx_hal_pcd.o $(MBED_ROOT)/TARGET_NUCLEO_L152RE/TOOLCHAIN_GCC_ARM/stm32l1xx_hal_pcd_ex.o $(MBED_ROOT)/TARGET_NUCLEO_L152RE/TOOLCHAIN_GCC_ARM/stm32l1xx_hal_pwr.o $(MBED_ROOT)/TARGET_NUCLEO_L152RE/TOOLCHAIN_GCC_ARM/stm32l1xx_hal_pwr_ex.o $(MBED_ROOT)/TARGET_NUCLEO_L152RE/TOOLCHAIN_GCC_ARM/stm32l1xx_hal_rcc.o $(MBED_ROOT)/TARGET_NUCLEO_L152RE/TOOLCHAIN_GCC_ARM/stm32l1xx_hal_rcc_ex.o $(MBED_ROOT)/TARGET_NUCLEO_L152RE/TOOLCHAIN_GCC_ARM/stm32l1xx_hal_rtc.o $(MBED_ROOT)/TARGET_NUCLEO_L152RE/TOOLCHAIN_GCC_ARM/stm32l1xx_hal_rtc_ex.o $(MBED_ROOT)/TARGET_NUCLEO_L152RE/TOOLCHAIN_GCC_ARM/stm32l1xx_hal_sd.o $(MBED_ROOT)/TARGET_NUCLEO_L152RE/TOOLCHAIN_GCC_ARM/stm32l1xx_hal_spi.o $(MBED_ROOT)/TARGET_NUCLEO_L152RE/TOOLCHAIN_GCC_ARM/stm32l1xx_hal_spi_ex.o $(MBED_ROOT)/TARGET_NUCLEO_L152RE/TOOLCHAIN_GCC_ARM/stm32l1xx_hal_sram.o $(MBED_ROOT)/TARGET_NUCLEO_L152RE/TOOLCHAIN_GCC_ARM/stm32l1xx_hal_tim.o $(MBED_ROOT)/TARGET_NUCLEO_L152RE/TOOLCHAIN_GCC_ARM/stm32l1xx_hal_tim_ex.o $(MBED_ROOT)/TARGET_NUCLEO_L152RE/TOOLCHAIN_GCC_ARM/stm32l1xx_hal_uart.o $(MBED_ROOT)/TARGET_NUCLEO_L152RE/TOOLCHAIN_GCC_ARM/stm32l1xx_hal_usart.o $(MBED_ROOT)/TARGET_NUCLEO_L152RE/TOOLCHAIN_GCC_ARM/stm32l1xx_hal_wwdg.o $(MBED_ROOT)/TARGET_NUCLEO_L152RE/TOOLCHAIN_GCC_ARM/stm32l1xx_ll_fsmc.o $(MBED_ROOT)/TARGET_NUCLEO_L152RE/TOOLCHAIN_GCC_ARM/stm32l1xx_ll_sdmmc.o $(MBED_ROOT)/TARGET_NUCLEO_L152RE/TOOLCHAIN_GCC_ARM/system_stm32l1xx.o INCLUDE_PATHS += -I$(MBED_ROOT)/TARGET_NUCLEO_L152RE -I$(MBED_ROOT)/TARGET_NUCLEO_L152RE/TARGET_STM -I$(MBED_ROOT)/TARGET_NUCLEO_L152RE/TARGET_STM/TARGET_STM32L1 -I$(MBED_ROOT)/TARGET_NUCLEO_L152RE/TARGET_STM/TARGET_STM32L1/TARGET_NUCLEO_L152RE -I$(MBED_ROOT)/TARGET_NUCLEO_L152RE/TOOLCHAIN_GCC_ARM LIBRARY_PATHS = -L$(MBED_ROOT)/TARGET_NUCLEO_L152RE/TOOLCHAIN_GCC_ARM LINKER_SCRIPT = $(MBED_ROOT)\TARGET_NUCLEO_L152RE\TOOLCHAIN_GCC_ARM\STM32L152XE.ld # Build flags CPU = -mcpu=cortex-m3 -mthumb CC_FLAGS += $(CPU) -c -g -fno-common -fmessage-length=0 -Wall -Wextra -fno-exceptions -ffunction-sections -fdata-sections -fomit-frame-pointer -MMD -MP CC_SYMBOLS = -DMBED_BUILD_TIMESTAMP=1445629897.99 -DTARGET_FF_ARDUINO -DTOOLCHAIN_GCC_ARM -DTOOLCHAIN_GCC -DTARGET_FF_MORPHO -DTARGET_CORTEX_M -DARM_MATH_CM3 -DTARGET_STM32L1 -DTARGET_STM -D__CORTEX_M3 -DTARGET_NUCLEO_L152RE -DTARGET_M3 -DTARGET_STM32L152RE -D__MBED__=1 LD_FLAGS = $(CPU) -Wl,--gc-sections --specs=nano.specs -u _printf_float -u _scanf_float -Wl,--wrap,main -Wl,-Map=$(PROJECT).map,--cref else $(error TARGET is not recognized. Please check the value passed in) endif DEPS = $(OBJECTS:.o=.d) # # Build tools # AS = "$(GCC_BIN)arm-none-eabi-as" CC = "$(GCC_BIN)arm-none-eabi-gcc" CPP = "$(GCC_BIN)arm-none-eabi-g++" LD = "$(GCC_BIN)arm-none-eabi-gcc" OBJCOPY = "$(GCC_BIN)arm-none-eabi-objcopy" OBJDUMP = "$(GCC_BIN)arm-none-eabi-objdump" SIZE = "$(GCC_BIN)arm-none-eabi-size" ifeq ($(DEBUG), 1) CC_FLAGS += -DDEBUG -O0 else CC_FLAGS += -DNDEBUG -Os endif # # Recipes # .PHONY: all clean lst size all: ${TARGET} $(TARGET)\$(PROJECT).bin $(TARGET)\$(PROJECT).hex $(TARGET)\$(PROJECT).lst $(TARGET)\$(PROJECT).disasm size # Conditionals (ifeq/ifneq) are bugged on Windows. Instead, we'll just ensure the directory exists and remove it unconditionally. clean: ${TARGET} @rmdir /q /s $(TARGET) # Ensures the target directory has been created. ${TARGET}: @mkdir $@ $(TARGET)\\%.o: $(LLILUM_ROOT)\Zelig\os_layer\ARMv7M\Vectors\%.S $(AS) $(CPU) $(AS_FLAGS) -o $@ $< $(TARGET)\\%.o: $(LLILUM_ROOT)\Zelig\os_layer\ARMv7M\Vectors\%.s $(AS) $(CPU) $(AS_FLAGS) -o $@ $< $(TARGET)\\%.o: $(LLILUM_ROOT)\Zelig\os_layer\ports\mbed\%.S $(AS) $(CPU) $(AS_FLAGS) -o $@ $< $(TARGET)\\%.o: %.c $(CC) $(CC_FLAGS) $(CC_SYMBOLS) -std=gnu99 $(INCLUDE_PATHS) -o $@ $< $(TARGET)\\%.o: $(SOURCE_ROOT)\%.cpp $(CPP) $(CC_FLAGS) $(CC_SYMBOLS) -std=gnu++98 -fno-rtti $(INCLUDE_PATHS) -o $@ $< $(TARGET)\\%.o: $(LLILUM_ROOT)\Zelig\os_layer\ports\mbed\%.cpp $(CPP) $(CC_FLAGS) $(CC_SYMBOLS) -std=gnu++98 -fno-rtti $(INCLUDE_PATHS) -o $@ $< $(TARGET)\$(PROJECT).elf: $(OBJECTS) $(SYS_OBJECTS) $(LD) $(LD_FLAGS) -T$(LINKER_SCRIPT) $(LIBRARY_PATHS) -o $@ $^ $(LIBRARIES) $(LD_SYS_LIBS) $(LIBRARIES) $(LD_SYS_LIBS) $(TARGET)\$(PROJECT).bin: $(TARGET)\$(PROJECT).elf $(OBJCOPY) -O binary $< $@ $(TARGET)\$(PROJECT).hex: $(TARGET)\$(PROJECT).elf @$(OBJCOPY) -O ihex $< $@ $(TARGET)\$(PROJECT).lst: $(TARGET)\$(PROJECT).elf @$(OBJDUMP) -Sdh $< > $@ $(TARGET)\$(PROJECT).disasm: $(TARGET)\$(PROJECT).elf @$(OBJDUMP) -D $< > $@ size: $(TARGET)\$(PROJECT).elf @echo Size report... $(SIZE) $< ================================================ FILE: Zelig/Zelig/CompileTime/AnalysisTools/IRCompare/IRCompare.csproj ================================================  Debug AnyCPU 9.0.21022 2.0 {186F31A3-EF89-4A25-B2D5-20070211AA01} WinExe Properties Microsoft.Zelig.Tools.IRCompare Microsoft.Zelig.Tools.IRCompare $(LlilumBuildRoot)\Host\obj\$(MSBuildProjectName)\ v4.5 true full false $(LlilumBuildRoot)\Host\bin\$(Configuration)\ DEBUG;TRACE prompt 4 AllRules.ruleset AnyCPU false pdbonly true $(LlilumBuildRoot)\Host\bin\$(Configuration)\ TRACE prompt 4 AllRules.ruleset AnyCPU false $(LlilumBuildRoot)\Host\bin\$(Configuration)\ TRACE;DEBUG AnyCPU false false 3.5 Form MainForm.cs Form MethodViewer.cs Designer MainForm.cs Designer MethodViewer.cs ResXFileCodeGenerator Resources.Designer.cs Designer True Resources.resx True SettingsSingleFileGenerator Settings.Designer.cs True Settings.settings True {186F31A3-EF89-4A25-B2D5-20070222AA01} CodeTransformation False {186F31A3-EF89-4A25-B2D5-20060603AA01} IntermediateRepresentation False {186F31A3-EF89-4A25-B2D5-20061218AA01} Common False {186F31A3-EF89-4A25-B2D5-20060720AA01} TypeSystem False ================================================ FILE: Zelig/Zelig/CompileTime/AnalysisTools/IRCompare/MainForm.Designer.cs ================================================ namespace Microsoft.Zelig.Tools.IRCompare { partial class MainForm { /// /// Required designer variable. /// private System.ComponentModel.IContainer components = null; /// /// Clean up any resources being used. /// /// true if managed resources should be disposed; otherwise, false. protected override void Dispose( bool disposing ) { if(disposing && (components != null)) { components.Dispose(); } base.Dispose( disposing ); } #region Windows Form Designer generated code /// /// Required method for Designer support - do not modify /// the contents of this method with the code editor. /// private void InitializeComponent() { this.menuStrip1 = new System.Windows.Forms.MenuStrip(); this.fileToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem(); this.openToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem(); this.openFileDialog1 = new System.Windows.Forms.OpenFileDialog(); this.groupBoxMethods = new System.Windows.Forms.GroupBox(); this.listBoxMethods = new System.Windows.Forms.ListBox(); this.textBoxFilter = new System.Windows.Forms.TextBox(); this.label1 = new System.Windows.Forms.Label(); this.menuStrip1.SuspendLayout(); this.groupBoxMethods.SuspendLayout(); this.SuspendLayout(); // // menuStrip1 // this.menuStrip1.Items.AddRange(new System.Windows.Forms.ToolStripItem[] { this.fileToolStripMenuItem}); this.menuStrip1.Location = new System.Drawing.Point(0, 0); this.menuStrip1.Name = "menuStrip1"; this.menuStrip1.Size = new System.Drawing.Size(577, 24); this.menuStrip1.TabIndex = 0; this.menuStrip1.Text = "menuStrip1"; // // fileToolStripMenuItem // this.fileToolStripMenuItem.DropDownItems.AddRange(new System.Windows.Forms.ToolStripItem[] { this.openToolStripMenuItem}); this.fileToolStripMenuItem.Name = "fileToolStripMenuItem"; this.fileToolStripMenuItem.Size = new System.Drawing.Size(37, 20); this.fileToolStripMenuItem.Text = "&File"; // // openToolStripMenuItem // this.openToolStripMenuItem.Name = "openToolStripMenuItem"; this.openToolStripMenuItem.ShortcutKeys = ((System.Windows.Forms.Keys)((System.Windows.Forms.Keys.Control | System.Windows.Forms.Keys.O))); this.openToolStripMenuItem.Size = new System.Drawing.Size(155, 22); this.openToolStripMenuItem.Text = "&Open..."; this.openToolStripMenuItem.Click += new System.EventHandler(this.openToolStripMenuItem_Click); // // openFileDialog1 // this.openFileDialog1.Filter = "Zelig Image|*.ZeligImage"; this.openFileDialog1.Title = "Open Zelig Image"; // // groupBoxMethods // this.groupBoxMethods.Anchor = ((System.Windows.Forms.AnchorStyles)((((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Bottom) | System.Windows.Forms.AnchorStyles.Left) | System.Windows.Forms.AnchorStyles.Right))); this.groupBoxMethods.Controls.Add(this.listBoxMethods); this.groupBoxMethods.Location = new System.Drawing.Point(12, 68); this.groupBoxMethods.Name = "groupBoxMethods"; this.groupBoxMethods.Size = new System.Drawing.Size(553, 186); this.groupBoxMethods.TabIndex = 1; this.groupBoxMethods.TabStop = false; this.groupBoxMethods.Text = "Methods"; // // listBoxMethods // this.listBoxMethods.Dock = System.Windows.Forms.DockStyle.Fill; this.listBoxMethods.FormattingEnabled = true; this.listBoxMethods.Location = new System.Drawing.Point(3, 16); this.listBoxMethods.Name = "listBoxMethods"; this.listBoxMethods.Size = new System.Drawing.Size(547, 160); this.listBoxMethods.TabIndex = 0; this.listBoxMethods.DoubleClick += new System.EventHandler(this.listBoxMethods_DoubleClick); // // textBoxFilter // this.textBoxFilter.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Left) | System.Windows.Forms.AnchorStyles.Right))); this.textBoxFilter.Location = new System.Drawing.Point(49, 42); this.textBoxFilter.Name = "textBoxFilter"; this.textBoxFilter.Size = new System.Drawing.Size(513, 20); this.textBoxFilter.TabIndex = 2; this.textBoxFilter.TextChanged += new System.EventHandler(this.textBoxFilter_TextChanged); // // label1 // this.label1.AutoSize = true; this.label1.Location = new System.Drawing.Point(15, 48); this.label1.Name = "label1"; this.label1.Size = new System.Drawing.Size(32, 13); this.label1.TabIndex = 3; this.label1.Text = "Filter:"; // // MainForm // this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F); this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font; this.ClientSize = new System.Drawing.Size(577, 266); this.Controls.Add(this.label1); this.Controls.Add(this.textBoxFilter); this.Controls.Add(this.groupBoxMethods); this.Controls.Add(this.menuStrip1); this.MainMenuStrip = this.menuStrip1; this.Name = "MainForm"; this.Text = "IR Compare"; this.menuStrip1.ResumeLayout(false); this.menuStrip1.PerformLayout(); this.groupBoxMethods.ResumeLayout(false); this.ResumeLayout(false); this.PerformLayout(); } #endregion private System.Windows.Forms.MenuStrip menuStrip1; private System.Windows.Forms.ToolStripMenuItem fileToolStripMenuItem; private System.Windows.Forms.ToolStripMenuItem openToolStripMenuItem; private System.Windows.Forms.OpenFileDialog openFileDialog1; private System.Windows.Forms.GroupBox groupBoxMethods; private System.Windows.Forms.ListBox listBoxMethods; private System.Windows.Forms.TextBox textBoxFilter; private System.Windows.Forms.Label label1; } } ================================================ FILE: Zelig/Zelig/CompileTime/AnalysisTools/IRCompare/MainForm.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // namespace Microsoft.Zelig.Tools.IRCompare { using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Text; using System.Windows.Forms; using IR = Microsoft.Zelig.CodeGeneration.IR; using TS = Microsoft.Zelig.Runtime.TypeSystem; using System.IO; ////using ARM = Microsoft.Zelig.Emulation.ArmProcessor; public partial class MainForm : Form { // // State // Dictionary< string, TS.MethodRepresentation > m_lookupMethod; IR.TypeSystemForCodeTransformation m_typeSystem; RenderMethod m_renderer; string m_IRName; // // Constructor Methods // public MainForm() { InitializeComponent(); m_renderer = new RenderMethod(); } //--/ private object CreateInstanceForType( Type t ) { if(t == typeof(IR.TypeSystemForCodeTransformation)) { return new IR.TypeSystemForCodeTransformation( null ); } return null; } //--// private void openToolStripMenuItem_Click( object sender , EventArgs e ) { if(openFileDialog1.ShowDialog() == DialogResult.OK) { try { m_IRName = Path.GetFileNameWithoutExtension( openFileDialog1.FileName ); int idx = m_IRName.LastIndexOf( '.' ); if(idx >= 0) { m_IRName = m_IRName.Substring( idx + 1, m_IRName.Length - idx - 1 ); } this.Text = "IR Compare - " + m_IRName; using(System.IO.FileStream stream = new System.IO.FileStream( openFileDialog1.FileName, System.IO.FileMode.Open )) { m_typeSystem = IR.TypeSystemSerializer.Deserialize( stream, CreateInstanceForType, null, 0 ); m_lookupMethod = new Dictionary< string, TS.MethodRepresentation >(); m_typeSystem.EnumerateMethods( delegate( TS.MethodRepresentation md ) { m_lookupMethod[md.ToShortString()] = md; } ); } UpdateListBox(); } catch { } } } private void textBoxFilter_TextChanged( object sender , EventArgs e ) { UpdateListBox(); } private void UpdateListBox() { if(m_lookupMethod != null) { string filter = textBoxFilter.Text.ToLower(); List< string > lst = new List(); foreach(string id in m_lookupMethod.Keys) { if(string.IsNullOrEmpty( filter ) || id.ToLower().Contains( filter )) { lst.Add( id ); } } lst.Sort(); ListBox.ObjectCollection col = listBoxMethods.Items; listBoxMethods.SuspendLayout(); col.Clear(); col.AddRange( lst.ToArray() ); listBoxMethods.ResumeLayout(); } } private void listBoxMethods_DoubleClick( object sender , EventArgs e ) { if(m_lookupMethod != null && listBoxMethods.SelectedItem != null) { TS.MethodRepresentation method = m_lookupMethod[ (string)listBoxMethods.SelectedItem ]; MethodViewer mv = new MethodViewer( m_lookupMethod, method, m_renderer, m_IRName ); mv.Show(); } } } } ================================================ FILE: Zelig/Zelig/CompileTime/AnalysisTools/IRCompare/MainForm.resx ================================================ text/microsoft-resx 2.0 System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 17, 17 126, 17 ================================================ FILE: Zelig/Zelig/CompileTime/AnalysisTools/IRCompare/MethodViewer.Designer.cs ================================================ namespace Microsoft.Zelig.Tools.IRCompare { partial class MethodViewer { /// /// Required designer variable. /// private System.ComponentModel.IContainer components = null; /// /// Clean up any resources being used. /// /// true if managed resources should be disposed; otherwise, false. protected override void Dispose( bool disposing ) { if(disposing && (components != null)) { components.Dispose(); } base.Dispose( disposing ); } #region Windows Form Designer generated code /// /// Required method for Designer support - do not modify /// the contents of this method with the code editor. /// private void InitializeComponent() { this.textBox1 = new System.Windows.Forms.TextBox(); this.splitContainer1 = new System.Windows.Forms.SplitContainer(); this.tabControl1 = new System.Windows.Forms.TabControl(); this.tabPageVariables = new System.Windows.Forms.TabPage(); this.listViewVariables = new System.Windows.Forms.ListView(); this.columnHeader1 = new System.Windows.Forms.ColumnHeader(); this.columnHeader2 = new System.Windows.Forms.ColumnHeader(); this.tabPageBasicBlock = new System.Windows.Forms.TabPage(); this.listBoxBasicBlock = new System.Windows.Forms.ListBox(); this.checkBoxExpandBasicBlocks = new System.Windows.Forms.CheckBox(); this.richTextBox1 = new System.Windows.Forms.RichTextBox(); this.splitContainer1.Panel1.SuspendLayout(); this.splitContainer1.Panel2.SuspendLayout(); this.splitContainer1.SuspendLayout(); this.tabControl1.SuspendLayout(); this.tabPageVariables.SuspendLayout(); this.tabPageBasicBlock.SuspendLayout(); this.SuspendLayout(); // // textBox1 // this.textBox1.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Left) | System.Windows.Forms.AnchorStyles.Right))); this.textBox1.Location = new System.Drawing.Point( 148, 10 ); this.textBox1.Name = "textBox1"; this.textBox1.ReadOnly = true; this.textBox1.Size = new System.Drawing.Size( 716, 20 ); this.textBox1.TabIndex = 1; // // splitContainer1 // this.splitContainer1.Anchor = ((System.Windows.Forms.AnchorStyles)((((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Bottom) | System.Windows.Forms.AnchorStyles.Left) | System.Windows.Forms.AnchorStyles.Right))); this.splitContainer1.Location = new System.Drawing.Point( 12, 39 ); this.splitContainer1.Name = "splitContainer1"; // // splitContainer1.Panel1 // this.splitContainer1.Panel1.Controls.Add( this.richTextBox1 ); // // splitContainer1.Panel2 // this.splitContainer1.Panel2.Controls.Add( this.tabControl1 ); this.splitContainer1.Size = new System.Drawing.Size( 856, 373 ); this.splitContainer1.SplitterDistance = 301; this.splitContainer1.TabIndex = 2; // // tabControl1 // this.tabControl1.Controls.Add( this.tabPageVariables ); this.tabControl1.Controls.Add( this.tabPageBasicBlock ); this.tabControl1.Dock = System.Windows.Forms.DockStyle.Fill; this.tabControl1.Location = new System.Drawing.Point( 0, 0 ); this.tabControl1.Name = "tabControl1"; this.tabControl1.SelectedIndex = 0; this.tabControl1.Size = new System.Drawing.Size( 551, 373 ); this.tabControl1.TabIndex = 1; // // tabPageVariables // this.tabPageVariables.Controls.Add( this.listViewVariables ); this.tabPageVariables.Location = new System.Drawing.Point( 4, 22 ); this.tabPageVariables.Name = "tabPageVariables"; this.tabPageVariables.Padding = new System.Windows.Forms.Padding( 3 ); this.tabPageVariables.Size = new System.Drawing.Size( 543, 347 ); this.tabPageVariables.TabIndex = 1; this.tabPageVariables.Text = "Variables"; this.tabPageVariables.UseVisualStyleBackColor = true; // // listViewVariables // this.listViewVariables.Columns.AddRange( new System.Windows.Forms.ColumnHeader[] { this.columnHeader1, this.columnHeader2} ); this.listViewVariables.Dock = System.Windows.Forms.DockStyle.Fill; this.listViewVariables.Location = new System.Drawing.Point( 3, 3 ); this.listViewVariables.Name = "listViewVariables"; this.listViewVariables.Size = new System.Drawing.Size( 537, 341 ); this.listViewVariables.TabIndex = 0; this.listViewVariables.UseCompatibleStateImageBehavior = false; this.listViewVariables.View = System.Windows.Forms.View.Details; // // columnHeader1 // this.columnHeader1.Text = "Name"; // // columnHeader2 // this.columnHeader2.Text = "Type"; this.columnHeader2.Width = 266; // // tabPageBasicBlock // this.tabPageBasicBlock.Controls.Add( this.listBoxBasicBlock ); this.tabPageBasicBlock.Location = new System.Drawing.Point( 4, 22 ); this.tabPageBasicBlock.Name = "tabPageBasicBlock"; this.tabPageBasicBlock.Padding = new System.Windows.Forms.Padding( 3 ); this.tabPageBasicBlock.Size = new System.Drawing.Size( 543, 347 ); this.tabPageBasicBlock.TabIndex = 0; this.tabPageBasicBlock.Text = "Basic Block"; this.tabPageBasicBlock.UseVisualStyleBackColor = true; // // listBoxBasicBlock // this.listBoxBasicBlock.Dock = System.Windows.Forms.DockStyle.Fill; this.listBoxBasicBlock.FormattingEnabled = true; this.listBoxBasicBlock.HorizontalScrollbar = true; this.listBoxBasicBlock.IntegralHeight = false; this.listBoxBasicBlock.Location = new System.Drawing.Point( 3, 3 ); this.listBoxBasicBlock.Name = "listBoxBasicBlock"; this.listBoxBasicBlock.Size = new System.Drawing.Size( 537, 341 ); this.listBoxBasicBlock.TabIndex = 0; // // checkBoxExpandBasicBlocks // this.checkBoxExpandBasicBlocks.AutoSize = true; this.checkBoxExpandBasicBlocks.Location = new System.Drawing.Point( 12, 12 ); this.checkBoxExpandBasicBlocks.Name = "checkBoxExpandBasicBlocks"; this.checkBoxExpandBasicBlocks.Size = new System.Drawing.Size( 126, 17 ); this.checkBoxExpandBasicBlocks.TabIndex = 3; this.checkBoxExpandBasicBlocks.Text = "Expand Basic Blocks"; this.checkBoxExpandBasicBlocks.UseVisualStyleBackColor = true; this.checkBoxExpandBasicBlocks.CheckedChanged += new System.EventHandler( this.checkBoxExpandBasicBlocks_CheckedChanged ); // // richTextBox1 // this.richTextBox1.Dock = System.Windows.Forms.DockStyle.Fill; this.richTextBox1.Location = new System.Drawing.Point( 0, 0 ); this.richTextBox1.Name = "richTextBox1"; this.richTextBox1.Size = new System.Drawing.Size( 301, 373 ); this.richTextBox1.TabIndex = 0; this.richTextBox1.Text = ""; // // MethodViewer // this.AutoScaleDimensions = new System.Drawing.SizeF( 6F, 13F ); this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font; this.ClientSize = new System.Drawing.Size( 880, 424 ); this.Controls.Add( this.checkBoxExpandBasicBlocks ); this.Controls.Add( this.splitContainer1 ); this.Controls.Add( this.textBox1 ); this.Name = "MethodViewer"; this.Text = "Method Viewer"; this.Load += new System.EventHandler( this.MethodViewer_Load ); this.splitContainer1.Panel1.ResumeLayout( false ); this.splitContainer1.Panel2.ResumeLayout( false ); this.splitContainer1.ResumeLayout( false ); this.tabControl1.ResumeLayout( false ); this.tabPageVariables.ResumeLayout( false ); this.tabPageBasicBlock.ResumeLayout( false ); this.ResumeLayout( false ); this.PerformLayout(); } #endregion private System.Windows.Forms.TextBox textBox1; private System.Windows.Forms.SplitContainer splitContainer1; private System.Windows.Forms.TabControl tabControl1; private System.Windows.Forms.TabPage tabPageBasicBlock; private System.Windows.Forms.TabPage tabPageVariables; private System.Windows.Forms.ListBox listBoxBasicBlock; private System.Windows.Forms.ListView listViewVariables; private System.Windows.Forms.ColumnHeader columnHeader1; private System.Windows.Forms.ColumnHeader columnHeader2; private System.Windows.Forms.CheckBox checkBoxExpandBasicBlocks; private System.Windows.Forms.RichTextBox richTextBox1; } } ================================================ FILE: Zelig/Zelig/CompileTime/AnalysisTools/IRCompare/MethodViewer.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // namespace Microsoft.Zelig.Tools.IRCompare { using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Text; using System.Windows.Forms; using IR = Microsoft.Zelig.CodeGeneration.IR; using TS = Microsoft.Zelig.Runtime.TypeSystem; ////using ARM = Microsoft.Zelig.Emulation.ArmProcessor; public partial class MethodViewer : Form { // // State // Dictionary< string, TS.MethodRepresentation > m_lookupMethod; TS.MethodRepresentation m_method; RenderMethod m_renderer; List< RenderMethod.OutputLine > m_text; string m_irName; bool m_fExpandBasicBlocks; IR.BasicBlock m_selectedBasicBlock; // // Constructor Methods // public MethodViewer( Dictionary< string, TS.MethodRepresentation > lookupMethod , TS.MethodRepresentation method , RenderMethod renderer , string irName ) { m_lookupMethod = lookupMethod; m_method = method; m_renderer = renderer; m_irName = irName; m_fExpandBasicBlocks = false; InitializeComponent(); } private void UpdateDisplay() { textBox1.Text = m_method.Name; Text = "MethodViewer - " + m_method.Name + " - IR: " + m_irName; //--// ListVariables(); m_text = m_renderer.DumpMethod( m_method ); string[] lines = new string[m_text.Count]; for(int i = 0; i < m_text.Count; i++) { lines[i] = m_text[i].Text; } richTextBox1.Lines = lines; SelectBasicBlock( null ); } //--// private void ListVariables() { ListView.ListViewItemCollection col = listViewVariables.Items; listViewVariables.SuspendLayout(); col.Clear(); IR.ControlFlowGraphStateForCodeTransformation cfg = IR.TypeSystemForCodeTransformation.GetCodeForMethod( m_method ); if(cfg != null) { foreach(IR.VariableExpression var in cfg.DataFlow_SpanningTree_Variables) { string name; if(var.DebugName != null) { name = var.DebugName.Name; } else { name = var.ToString(); } ListViewItem lvi = new ListViewItem( name ); lvi.SubItems.Add( var.Type.ToString() ); col.Add( lvi ); } } listViewVariables.ResumeLayout(); tabControl1.SelectedTab = tabPageVariables; } //--//--// private void SelectBasicBlock( IR.BasicBlock bb ) { ListBox.ObjectCollection col = listBoxBasicBlock.Items; listBoxBasicBlock.SuspendLayout(); col.Clear(); m_selectedBasicBlock = bb; if(bb != null) { foreach(IR.Operator op in bb.Operators) { col.Add( op ); } } listBoxBasicBlock.ResumeLayout(); tabControl1.SelectedTab = tabPageBasicBlock; } //--//--// private void MethodViewer_Load( object sender , EventArgs e ) { UpdateDisplay(); } private void listBoxBasicBlock_DoubleClick( object sender , EventArgs e ) { if(m_selectedBasicBlock != null) { int i = listBoxBasicBlock.SelectedIndex; if(i >= 0 && i < m_selectedBasicBlock.Operators.Length) { IR.Operator op = m_selectedBasicBlock.Operators[i]; if(op is IR.CallOperator) { m_method = ((IR.CallOperator)op).TargetMethod; UpdateDisplay(); } } } } private void checkBoxExpandBasicBlocks_CheckedChanged( object sender , EventArgs e ) { m_fExpandBasicBlocks = checkBoxExpandBasicBlocks.Checked; } } } ================================================ FILE: Zelig/Zelig/CompileTime/AnalysisTools/IRCompare/MethodViewer.resx ================================================ text/microsoft-resx 2.0 System.Resources.ResXResourceReader, System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 System.Resources.ResXResourceWriter, System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 ================================================ FILE: Zelig/Zelig/CompileTime/AnalysisTools/IRCompare/Program.cs ================================================ using System; using System.Collections.Generic; using System.Windows.Forms; namespace Microsoft.Zelig.Tools.IRCompare { static class Program { /// /// The main entry point for the application. /// [STAThread] static void Main() { Application.EnableVisualStyles(); Application.SetCompatibleTextRenderingDefault( false ); Application.Run( new MainForm() ); } } } ================================================ FILE: Zelig/Zelig/CompileTime/AnalysisTools/IRCompare/Properties/AssemblyInfo.cs ================================================ using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; // General Information about an assembly is controlled through the following // set of attributes. Change these attribute values to modify the information // associated with an assembly. [assembly: AssemblyTitle( "IRCompare" )] [assembly: AssemblyDescription( "" )] [assembly: AssemblyConfiguration( "" )] [assembly: AssemblyCompany( "Microsoft" )] [assembly: AssemblyProduct( "IRCompare" )] [assembly: AssemblyCopyright( "Copyright © Microsoft 2006" )] [assembly: AssemblyTrademark( "" )] [assembly: AssemblyCulture( "" )] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible( false )] //// The following GUID is for the ID of the typelib if this project is exposed to COM //[assembly: Guid( "fafaa296-9d0d-42fa-b922-8fb69f2544b2" )] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // [assembly: AssemblyVersion( "1.0.0.0" )] [assembly: AssemblyFileVersion( "1.0.0.0" )] ================================================ FILE: Zelig/Zelig/CompileTime/AnalysisTools/IRCompare/Properties/Resources.Designer.cs ================================================ //------------------------------------------------------------------------------ // // This code was generated by a tool. // Runtime Version:4.0.30319.34209 // // Changes to this file may cause incorrect behavior and will be lost if // the code is regenerated. // //------------------------------------------------------------------------------ namespace Microsoft.Zelig.Tools.IRCompare.Properties { using System; /// /// A strongly-typed resource class, for looking up localized strings, etc. /// // This class was auto-generated by the StronglyTypedResourceBuilder // class via a tool like ResGen or Visual Studio. // To add or remove a member, edit your .ResX file then rerun ResGen // with the /str option, or rebuild your VS project. [global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Resources.Tools.StronglyTypedResourceBuilder", "4.0.0.0")] [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] [global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()] internal class Resources { private static global::System.Resources.ResourceManager resourceMan; private static global::System.Globalization.CultureInfo resourceCulture; [global::System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")] internal Resources() { } /// /// Returns the cached ResourceManager instance used by this class. /// [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)] internal static global::System.Resources.ResourceManager ResourceManager { get { if (object.ReferenceEquals(resourceMan, null)) { global::System.Resources.ResourceManager temp = new global::System.Resources.ResourceManager("Microsoft.Zelig.Tools.IRCompare.Properties.Resources", typeof(Resources).Assembly); resourceMan = temp; } return resourceMan; } } /// /// Overrides the current thread's CurrentUICulture property for all /// resource lookups using this strongly typed resource class. /// [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)] internal static global::System.Globalization.CultureInfo Culture { get { return resourceCulture; } set { resourceCulture = value; } } } } ================================================ FILE: Zelig/Zelig/CompileTime/AnalysisTools/IRCompare/Properties/Resources.resx ================================================  text/microsoft-resx 2.0 System.Resources.ResXResourceReader, System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 System.Resources.ResXResourceWriter, System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 ================================================ FILE: Zelig/Zelig/CompileTime/AnalysisTools/IRCompare/Properties/Settings.Designer.cs ================================================ //------------------------------------------------------------------------------ // // This code was generated by a tool. // Runtime Version:4.0.30319.34209 // // Changes to this file may cause incorrect behavior and will be lost if // the code is regenerated. // //------------------------------------------------------------------------------ namespace Microsoft.Zelig.Tools.IRCompare.Properties { [global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()] [global::System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.VisualStudio.Editors.SettingsDesigner.SettingsSingleFileGenerator", "12.0.0.0")] internal sealed partial class Settings : global::System.Configuration.ApplicationSettingsBase { private static Settings defaultInstance = ((Settings)(global::System.Configuration.ApplicationSettingsBase.Synchronized(new Settings()))); public static Settings Default { get { return defaultInstance; } } } } ================================================ FILE: Zelig/Zelig/CompileTime/AnalysisTools/IRCompare/Properties/Settings.settings ================================================  ================================================ FILE: Zelig/Zelig/CompileTime/AnalysisTools/IRCompare/RenderMethod.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // namespace Microsoft.Zelig.Tools.IRCompare { using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Text; using System.Windows.Forms; using IR = Microsoft.Zelig.CodeGeneration.IR; using TS = Microsoft.Zelig.Runtime.TypeSystem; ////using ARM = Microsoft.Zelig.Emulation.ArmProcessor; public class RenderMethod : IR.BaseIntermediateRepresentationDumper { public class OutputLine { public string Text; public IR.Operator Operator; } // // State // IR.Operator m_currentOperator; StringBuilder m_writer; List< OutputLine > m_output; int m_indent; bool m_fIndented; // // Constructor Methods // public RenderMethod() { m_writer = new StringBuilder(); } //--// private void AddLine() { OutputLine ol = new OutputLine(); ol.Text = m_writer.ToString(); ol.Operator = m_currentOperator; m_output.Add( ol ); m_writer.Length = 0; } public void WriteLine() { WriteIndentation(); AddLine(); m_fIndented = false; } public void WriteLine( string s ) { WriteIndentation(); m_writer.Append( s ); AddLine(); m_fIndented = false; } public void WriteLine( string s , object arg1 ) { WriteIndentedLine( s, arg1 ); } public void WriteLine( string s , object arg1 , object arg2 ) { WriteIndentedLine( s, arg1, arg2 ); } public void WriteLine( string s , object arg1 , object arg2 , object arg3 ) { WriteIndentedLine( s, arg1, arg2, arg3 ); } public void WriteLine( string s , params object[] args ) { WriteIndentedLine( s, args ); } //--// public List< OutputLine > DumpMethod( TS.MethodRepresentation md ) { m_output = new List< OutputLine >(); DumpGraph( IR.TypeSystemForCodeTransformation.GetCodeForMethod( md ) ); return m_output; } public override void DumpGraph( IR.ControlFlowGraphState cfg ) { IR.ControlFlowGraphStateForCodeTransformation cfg2 = (IR.ControlFlowGraphStateForCodeTransformation)cfg; base.DumpGraph( cfg2 ); //--// if(m_sortedVariables.Length > 0) { m_indent += 3; foreach(IR.VariableExpression ex in m_sortedVariables) { WriteLine( "{0} {1} as {2}", m_useChains[ex.SpanningTreeIndex].Length > 0 ? " var" : "unused var", ex, ex.Type ); } m_indent -= 3; WriteLine(); } foreach(IR.BasicBlock bb in m_basicBlocks) { ProcessBasicBlock( bb ); } } private void ProcessBasicBlock( IR.BasicBlock bb ) { m_indent += 1; string label = CreateLabel( bb ); if(label != null) { WriteLine( "{0}: [Index:{1}] [Annotation:{2}]", label, bb.SpanningTreeIndex, bb.Annotation ); } m_indent += 4; if(bb is IR.ExceptionHandlerBasicBlock) { IR.ExceptionHandlerBasicBlock ehBB = (IR.ExceptionHandlerBasicBlock)bb; foreach(IR.ExceptionClause eh in ehBB.HandlerFor) { WriteLine( ".handler for {0}", eh ); } } foreach(IR.ExceptionHandlerBasicBlock bbEh in bb.ProtectedBy) { foreach(IR.ExceptionClause eh in bbEh.HandlerFor) { WriteLine( ".protected by {0} at {1}", eh, CreateLabel( bbEh ) ); } } foreach(IR.BasicBlockEdge edge in bb.Predecessors) { WriteLine( ".edge {0} from {1}", edge.EdgeClass, CreateLabel( edge.Predecessor ) ); } foreach(IR.BasicBlockEdge edge in bb.Successors) { WriteLine( ".edge {0} to {1}", edge.EdgeClass, CreateLabel( edge.Successor ) ); } GrowOnlySet< IR.Expression > used = SetFactory.NewWithReferenceEquality< IR.Expression >(); foreach(IR.Operator op in bb.Operators) { foreach(IR.Expression ex in op.Arguments) { used.Insert( ex ); } } foreach(IR.Expression ex in used) { bool fGot = false; foreach(int opIndex in m_reachingDefinitions[bb.Operators[0].SpanningTreeIndex]) { if(m_operators[opIndex].IsSourceOfExpression( ex )) { if(fGot == false) { WriteIndented( ".reaching {0} <=", ex ); fGot = true; } else { WriteIndented( "," ); } WriteIndented( " Op_{0}", opIndex ); } } if(fGot) { WriteLine(); } } //--// foreach(IR.Operator op in bb.Operators) { DumpOperator( op ); } m_indent -= 4; m_indent -= 1; WriteLine(); } private void DumpOperator( IR.Operator op ) { m_currentOperator = op; string s = op.FormatOutput( this ); foreach(string s2 in s.Split( '\n' )) { WriteLine( "Op_{0,-4}: {1}", op.SpanningTreeIndex, s2 ); } m_currentOperator = null; } //--// private void WriteIndented( string s , params object[] args ) { WriteIndentation(); m_writer.Append( FormatOutputInternal( s, args ) ); } private void WriteIndentedLine( string s , params object[] args ) { WriteIndentation(); m_writer.Append( FormatOutputInternal( s, args ) ); AddLine(); m_fIndented = false; } private void WriteIndentation() { if(m_fIndented == false) { m_fIndented = true; for(int i = 0; i < m_indent; i++) { m_writer.Append( " " ); } } } } } ================================================ FILE: Zelig/Zelig/CompileTime/AnalysisTools/IRCompare/app.config ================================================ ================================================ FILE: Zelig/Zelig/CompileTime/AnalysisTools/IRViewer/IRViewer.csproj ================================================  Debug AnyCPU 9.0.21022 2.0 {186F31A3-EF89-4A25-B2D5-20060721AA01} WinExe Properties Microsoft.Zelig.Tools.IRViewer Microsoft.Zelig.Tools.IRViewer $(LlilumBuildRoot)\Host\obj\$(MSBuildProjectName)\ v4.5 true full false $(LlilumBuildRoot)\Host\bin\$(Configuration)\ DEBUG;TRACE prompt 4 AllRules.ruleset AnyCPU false pdbonly true $(LlilumBuildRoot)\Host\bin\$(Configuration)\ TRACE prompt 4 AllRules.ruleset AnyCPU false $(LlilumBuildRoot)\Host\bin\$(Configuration)\ AnyCPU TRACE;DEBUG false false ..\..\..\External\Binaries\GLEE\Debug\Microsoft.GLEE.dll ..\..\..\External\Binaries\GLEE\Debug\Microsoft.GLEE.Drawing.dll ..\..\..\External\Binaries\GLEE\Debug\Microsoft.GLEE.GraphViewerGDI.dll 3.5 Form MainForm.cs Designer MainForm.cs ResXFileCodeGenerator Resources.Designer.cs Designer True Resources.resx True SettingsSingleFileGenerator Settings.Designer.cs True Settings.settings True {186F31A3-EF89-4A25-B2D5-20061218AA01} Common ================================================ FILE: Zelig/Zelig/CompileTime/AnalysisTools/IRViewer/MainForm.Designer.cs ================================================ namespace Microsoft.Zelig.Tools.IRViewer { partial class MainForm { /// /// Required designer variable. /// private System.ComponentModel.IContainer components = null; /// /// Clean up any resources being used. /// /// true if managed resources should be disposed; otherwise, false. protected override void Dispose( bool disposing ) { if(disposing && (components != null)) { components.Dispose(); } base.Dispose( disposing ); } #region Windows Form Designer generated code /// /// Required method for Designer support - do not modify /// the contents of this method with the code editor. /// private void InitializeComponent() { this.components = new System.ComponentModel.Container(); this.openFileDialog1 = new System.Windows.Forms.OpenFileDialog(); this.gViewer1 = new Microsoft.Glee.GraphViewerGdi.GViewer(); this.textBoxFilter = new System.Windows.Forms.TextBox(); this.splitContainer = new System.Windows.Forms.SplitContainer(); this.checkBoxShowLineNumbers = new System.Windows.Forms.CheckBox(); this.checkBoxExpandBasicBlocks = new System.Windows.Forms.CheckBox(); this.listViewVariables = new System.Windows.Forms.ListView(); this.columnHeaderVariableName = ((System.Windows.Forms.ColumnHeader)(new System.Windows.Forms.ColumnHeader())); this.columnHeaderVariableType = ((System.Windows.Forms.ColumnHeader)(new System.Windows.Forms.ColumnHeader())); this.listViewBasicBlock = new System.Windows.Forms.ListView(); this.columnHeaderOperatorIndex = ((System.Windows.Forms.ColumnHeader)(new System.Windows.Forms.ColumnHeader())); this.columnHeaderOperatorType = ((System.Windows.Forms.ColumnHeader)(new System.Windows.Forms.ColumnHeader())); this.columnHeaderOperatorValue = ((System.Windows.Forms.ColumnHeader)(new System.Windows.Forms.ColumnHeader())); this.richTextBoxCode = new System.Windows.Forms.RichTextBox(); this.buttonLaunchCode = new System.Windows.Forms.Button(); this.textBoxCodeFileName = new System.Windows.Forms.TextBox(); this.listBoxMethods = new System.Windows.Forms.ListBox(); this.buttonBack = new System.Windows.Forms.Button(); this.contextMenuStripBackStack = new System.Windows.Forms.ContextMenuStrip(this.components); this.buttonBackStackDropdown = new System.Windows.Forms.Button(); ((System.ComponentModel.ISupportInitialize)(this.splitContainer)).BeginInit(); this.splitContainer.Panel1.SuspendLayout(); this.splitContainer.Panel2.SuspendLayout(); this.splitContainer.SuspendLayout(); this.SuspendLayout(); // // openFileDialog1 // this.openFileDialog1.Filter = "IR XML Dump|*.xml"; this.openFileDialog1.Title = "Open IR XML Dump"; // // gViewer1 // this.gViewer1.AsyncLayout = false; this.gViewer1.AutoScroll = true; this.gViewer1.BackwardEnabled = false; this.gViewer1.Dock = System.Windows.Forms.DockStyle.Top; this.gViewer1.EditObjects = false; this.gViewer1.ForwardEnabled = false; this.gViewer1.Graph = null; this.gViewer1.Location = new System.Drawing.Point(0, 0); this.gViewer1.MouseHitDistance = 0.05D; this.gViewer1.Name = "gViewer1"; this.gViewer1.NavigationVisible = true; this.gViewer1.PanButtonPressed = false; this.gViewer1.SaveButtonVisible = true; this.gViewer1.Size = new System.Drawing.Size(301, 562); this.gViewer1.TabIndex = 0; this.gViewer1.ZoomF = 1D; this.gViewer1.ZoomFraction = 0.5D; this.gViewer1.ZoomWindowThreshold = 0.05D; this.gViewer1.SelectionChanged += new System.EventHandler(this.gViewer1_SelectionChanged); this.gViewer1.MouseClick += new System.Windows.Forms.MouseEventHandler(this.gViewer1_MouseClick); // // textBoxFilter // this.textBoxFilter.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Left) | System.Windows.Forms.AnchorStyles.Right))); this.textBoxFilter.Location = new System.Drawing.Point(67, 10); this.textBoxFilter.Name = "textBoxFilter"; this.textBoxFilter.Size = new System.Drawing.Size(801, 20); this.textBoxFilter.TabIndex = 1; this.textBoxFilter.Click += new System.EventHandler(this.textBoxFilter_Click); this.textBoxFilter.TextChanged += new System.EventHandler(this.textBoxFilter_TextChanged); // // splitContainer // this.splitContainer.Anchor = ((System.Windows.Forms.AnchorStyles)((((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Bottom) | System.Windows.Forms.AnchorStyles.Left) | System.Windows.Forms.AnchorStyles.Right))); this.splitContainer.Location = new System.Drawing.Point(12, 39); this.splitContainer.Name = "splitContainer"; // // splitContainer.Panel1 // this.splitContainer.Panel1.Controls.Add(this.checkBoxShowLineNumbers); this.splitContainer.Panel1.Controls.Add(this.gViewer1); this.splitContainer.Panel1.Controls.Add(this.checkBoxExpandBasicBlocks); // // splitContainer.Panel2 // this.splitContainer.Panel2.Controls.Add(this.listViewVariables); this.splitContainer.Panel2.Controls.Add(this.listViewBasicBlock); this.splitContainer.Panel2.Controls.Add(this.richTextBoxCode); this.splitContainer.Panel2.Controls.Add(this.buttonLaunchCode); this.splitContainer.Panel2.Controls.Add(this.textBoxCodeFileName); this.splitContainer.Size = new System.Drawing.Size(856, 588); this.splitContainer.SplitterDistance = 301; this.splitContainer.TabIndex = 2; // // checkBoxShowLineNumbers // this.checkBoxShowLineNumbers.AutoSize = true; this.checkBoxShowLineNumbers.Checked = true; this.checkBoxShowLineNumbers.CheckState = System.Windows.Forms.CheckState.Checked; this.checkBoxShowLineNumbers.Location = new System.Drawing.Point(136, 568); this.checkBoxShowLineNumbers.Name = "checkBoxShowLineNumbers"; this.checkBoxShowLineNumbers.Size = new System.Drawing.Size(121, 17); this.checkBoxShowLineNumbers.TabIndex = 4; this.checkBoxShowLineNumbers.Text = "Show Line Numbers"; this.checkBoxShowLineNumbers.UseVisualStyleBackColor = true; this.checkBoxShowLineNumbers.CheckedChanged += new System.EventHandler(this.checkBoxShowLineNumbers_CheckedChanged); // // checkBoxExpandBasicBlocks // this.checkBoxExpandBasicBlocks.AutoSize = true; this.checkBoxExpandBasicBlocks.Location = new System.Drawing.Point(3, 568); this.checkBoxExpandBasicBlocks.Name = "checkBoxExpandBasicBlocks"; this.checkBoxExpandBasicBlocks.Size = new System.Drawing.Size(126, 17); this.checkBoxExpandBasicBlocks.TabIndex = 3; this.checkBoxExpandBasicBlocks.Text = "Expand Basic Blocks"; this.checkBoxExpandBasicBlocks.UseVisualStyleBackColor = true; this.checkBoxExpandBasicBlocks.CheckedChanged += new System.EventHandler(this.checkBoxExpandBasicBlocks_CheckedChanged); // // listViewVariables // this.listViewVariables.Columns.AddRange(new System.Windows.Forms.ColumnHeader[] { this.columnHeaderVariableName, this.columnHeaderVariableType}); this.listViewVariables.Dock = System.Windows.Forms.DockStyle.Top; this.listViewVariables.FullRowSelect = true; this.listViewVariables.HeaderStyle = System.Windows.Forms.ColumnHeaderStyle.Nonclickable; this.listViewVariables.HideSelection = false; this.listViewVariables.Location = new System.Drawing.Point(0, 0); this.listViewVariables.Name = "listViewVariables"; this.listViewVariables.Size = new System.Drawing.Size(551, 150); this.listViewVariables.TabIndex = 0; this.listViewVariables.UseCompatibleStateImageBehavior = false; this.listViewVariables.View = System.Windows.Forms.View.Details; // // columnHeaderVariableName // this.columnHeaderVariableName.Text = "Name"; this.columnHeaderVariableName.Width = 200; // // columnHeaderVariableType // this.columnHeaderVariableType.Text = "Type"; this.columnHeaderVariableType.Width = 340; // // listViewBasicBlock // this.listViewBasicBlock.Columns.AddRange(new System.Windows.Forms.ColumnHeader[] { this.columnHeaderOperatorIndex, this.columnHeaderOperatorType, this.columnHeaderOperatorValue}); this.listViewBasicBlock.FullRowSelect = true; this.listViewBasicBlock.HeaderStyle = System.Windows.Forms.ColumnHeaderStyle.Nonclickable; this.listViewBasicBlock.HideSelection = false; this.listViewBasicBlock.Location = new System.Drawing.Point(0, 153); this.listViewBasicBlock.MultiSelect = false; this.listViewBasicBlock.Name = "listViewBasicBlock"; this.listViewBasicBlock.ShowGroups = false; this.listViewBasicBlock.Size = new System.Drawing.Size(551, 200); this.listViewBasicBlock.TabIndex = 2; this.listViewBasicBlock.UseCompatibleStateImageBehavior = false; this.listViewBasicBlock.View = System.Windows.Forms.View.Details; this.listViewBasicBlock.Click += new System.EventHandler(this.listViewBasicBlock_Click); this.listViewBasicBlock.DoubleClick += new System.EventHandler(this.listViewBasicBlock_DoubleClick); // // columnHeaderOperatorIndex // this.columnHeaderOperatorIndex.Text = "#"; this.columnHeaderOperatorIndex.Width = 20; // // columnHeaderOperatorType // this.columnHeaderOperatorType.Text = "Operator"; this.columnHeaderOperatorType.Width = 150; // // columnHeaderOperatorValue // this.columnHeaderOperatorValue.Text = "Value"; this.columnHeaderOperatorValue.Width = 200; // // richTextBoxCode // this.richTextBoxCode.BackColor = System.Drawing.SystemColors.Window; this.richTextBoxCode.BorderStyle = System.Windows.Forms.BorderStyle.FixedSingle; this.richTextBoxCode.Dock = System.Windows.Forms.DockStyle.Bottom; this.richTextBoxCode.Font = new System.Drawing.Font("Consolas", 9.75F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.richTextBoxCode.Location = new System.Drawing.Point(0, 379); this.richTextBoxCode.Name = "richTextBoxCode"; this.richTextBoxCode.ReadOnly = true; this.richTextBoxCode.Size = new System.Drawing.Size(551, 209); this.richTextBoxCode.TabIndex = 1; this.richTextBoxCode.Text = ""; this.richTextBoxCode.WordWrap = false; // // buttonLaunchCode // this.buttonLaunchCode.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Right))); this.buttonLaunchCode.Enabled = false; this.buttonLaunchCode.Location = new System.Drawing.Point(517, 356); this.buttonLaunchCode.Name = "buttonLaunchCode"; this.buttonLaunchCode.Size = new System.Drawing.Size(34, 20); this.buttonLaunchCode.TabIndex = 1; this.buttonLaunchCode.Text = ">>"; this.buttonLaunchCode.UseVisualStyleBackColor = true; this.buttonLaunchCode.Click += new System.EventHandler(this.buttonLaunchCode_Click); // // textBoxCodeFileName // this.textBoxCodeFileName.Location = new System.Drawing.Point(0, 356); this.textBoxCodeFileName.Name = "textBoxCodeFileName"; this.textBoxCodeFileName.ReadOnly = true; this.textBoxCodeFileName.Size = new System.Drawing.Size(514, 20); this.textBoxCodeFileName.TabIndex = 0; // // listBoxMethods // this.listBoxMethods.FormattingEnabled = true; this.listBoxMethods.Location = new System.Drawing.Point(67, 31); this.listBoxMethods.Name = "listBoxMethods"; this.listBoxMethods.Size = new System.Drawing.Size(801, 212); this.listBoxMethods.TabIndex = 0; this.listBoxMethods.Click += new System.EventHandler(this.listBoxMethods_Click); // // buttonBack // this.buttonBack.Enabled = false; this.buttonBack.Font = new System.Drawing.Font("Wingdings 3", 12F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(2))); this.buttonBack.Location = new System.Drawing.Point(12, 8); this.buttonBack.Name = "buttonBack"; this.buttonBack.Size = new System.Drawing.Size(36, 24); this.buttonBack.TabIndex = 3; this.buttonBack.Text = "f"; this.buttonBack.UseVisualStyleBackColor = true; this.buttonBack.Click += new System.EventHandler(this.buttonBack_Click); // // contextMenuStripBackStack // this.contextMenuStripBackStack.Name = "contextMenuStripBackStack"; this.contextMenuStripBackStack.Size = new System.Drawing.Size(61, 4); // // buttonBackStackDropdown // this.buttonBackStackDropdown.Enabled = false; this.buttonBackStackDropdown.Font = new System.Drawing.Font("Wingdings 3", 6F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(2))); this.buttonBackStackDropdown.ForeColor = System.Drawing.SystemColors.ControlDarkDark; this.buttonBackStackDropdown.Location = new System.Drawing.Point(47, 8); this.buttonBackStackDropdown.Name = "buttonBackStackDropdown"; this.buttonBackStackDropdown.Size = new System.Drawing.Size(18, 24); this.buttonBackStackDropdown.TabIndex = 5; this.buttonBackStackDropdown.Text = "q"; this.buttonBackStackDropdown.UseVisualStyleBackColor = true; this.buttonBackStackDropdown.Click += new System.EventHandler(this.buttonBackStackDropdown_Click); // // MainForm // this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F); this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font; this.ClientSize = new System.Drawing.Size(880, 639); this.Controls.Add(this.buttonBackStackDropdown); this.Controls.Add(this.buttonBack); this.Controls.Add(this.listBoxMethods); this.Controls.Add(this.splitContainer); this.Controls.Add(this.textBoxFilter); this.MinimumSize = new System.Drawing.Size(896, 463); this.Name = "MainForm"; this.Text = "IR Viewer"; this.Load += new System.EventHandler(this.MainForm_Load); this.Resize += new System.EventHandler(this.MainForm_Resize); this.splitContainer.Panel1.ResumeLayout(false); this.splitContainer.Panel1.PerformLayout(); this.splitContainer.Panel2.ResumeLayout(false); this.splitContainer.Panel2.PerformLayout(); ((System.ComponentModel.ISupportInitialize)(this.splitContainer)).EndInit(); this.splitContainer.ResumeLayout(false); this.ResumeLayout(false); this.PerformLayout(); } #endregion private System.Windows.Forms.OpenFileDialog openFileDialog1; private Microsoft.Glee.GraphViewerGdi.GViewer gViewer1; private System.Windows.Forms.TextBox textBoxFilter; private System.Windows.Forms.SplitContainer splitContainer; private System.Windows.Forms.ListView listViewVariables; private System.Windows.Forms.ColumnHeader columnHeaderVariableName; private System.Windows.Forms.ColumnHeader columnHeaderVariableType; private System.Windows.Forms.CheckBox checkBoxExpandBasicBlocks; private System.Windows.Forms.RichTextBox richTextBoxCode; private System.Windows.Forms.TextBox textBoxCodeFileName; private System.Windows.Forms.Button buttonLaunchCode; private System.Windows.Forms.ListView listViewBasicBlock; private System.Windows.Forms.ColumnHeader columnHeaderOperatorIndex; private System.Windows.Forms.ColumnHeader columnHeaderOperatorValue; private System.Windows.Forms.ColumnHeader columnHeaderOperatorType; private System.Windows.Forms.ListBox listBoxMethods; private System.Windows.Forms.CheckBox checkBoxShowLineNumbers; private System.Windows.Forms.Button buttonBack; private System.Windows.Forms.ContextMenuStrip contextMenuStripBackStack; private System.Windows.Forms.Button buttonBackStackDropdown; } } ================================================ FILE: Zelig/Zelig/CompileTime/AnalysisTools/IRViewer/MainForm.cs ================================================ using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Text; using System.Windows.Forms; using System.IO; using System.Diagnostics; namespace Microsoft.Zelig.Tools.IRViewer { public partial class MainForm : Form { // // State // Dictionary m_lookupMethod; Method m_method; ListViewItem m_selectedOpLVI; string m_phaseName; bool m_fExpandBasicBlocks; object m_highlightedObjectAttr; object m_highlightedObject; Glee.Drawing.NodeAttr m_selectedNodeAttr; Glee.Drawing.Node m_selectedNode; BasicBlock m_selectedBasicBlock; SourceCodeTracker m_sourceCodeTracker; struct BackStackState { public BackStackState(Method method, BasicBlock basicBlock, Operator op) { this.Method = method; this.BasicBlock = basicBlock; this.Operator = op; } public Method Method { get; } public BasicBlock BasicBlock { get; } public Operator Operator { get; } } Stack m_backStack; // // Constructor Methods // public MainForm() { m_sourceCodeTracker = new SourceCodeTracker(); m_backStack = new Stack(); m_fExpandBasicBlocks = false; InitializeComponent(); UpdateListBox(); } private void MainForm_Load(object sender, EventArgs e) { bool loadSucceeded = false; if (openFileDialog1.ShowDialog() == DialogResult.OK) { try { System.Xml.XmlDocument doc = new System.Xml.XmlDocument(); doc.Load(openFileDialog1.FileName); var phaseName = Path.GetFileNameWithoutExtension(openFileDialog1.FileName); int idx = phaseName.LastIndexOf('.'); if (idx >= 0) { phaseName = phaseName.Substring(idx + 1, phaseName.Length - idx - 1); } this.Text = "IRViewer - " + phaseName; foreach (System.Xml.XmlNode methods in doc.SelectNodes("Methods")) { Parser parser = new Parser(methods); m_lookupMethod = parser.Methods; m_phaseName = phaseName; SelectMethod(null); UpdateListBox(); textBoxFilter.Select(); loadSucceeded = true; break; } } catch { } } if (!loadSucceeded) { Close(); } } private void SelectMethod(Method method) { if (method == null) { Text = $"IRViewer - { m_phaseName }"; m_method = method; } else { Text = $"IRViewer - { method.Name } - { m_phaseName }"; if (m_method != null && m_method != method) { var previousOp = (m_selectedOpLVI != null) ? m_selectedBasicBlock.Operators[m_selectedOpLVI.Index] : null; m_backStack.Push(new BackStackState(m_method, m_selectedBasicBlock, previousOp)); buttonBack.Enabled = true; buttonBackStackDropdown.Enabled = true; } textBoxFilter.Text = method.Name; listBoxMethods.Visible = false; m_method = method; CreateGraph(); ListVariables(); } SelectBasicBlock(null); } //--// private void CreateGraph() { Microsoft.Glee.Drawing.Graph g = new Microsoft.Glee.Drawing.Graph(string.Format("Method for {0}", m_method.Name)); g.GraphAttr.NodeAttr.Padding = 3; foreach (BasicBlockEdge edge in m_method.BasicBlockEdges) { Microsoft.Glee.Drawing.Edge edgeG = g.AddEdge(edge.From.Id, edge.To.Id) as Microsoft.Glee.Drawing.Edge; Microsoft.Glee.Drawing.EdgeAttr attr = edgeG.Attr; attr.Label = edge.Kind; attr.Fontsize -= 4; } foreach (BasicBlock bb in m_method.BasicBlocks) { Microsoft.Glee.Drawing.Node node = CreateNode(g, bb, m_fExpandBasicBlocks); } gViewer1.Graph = g; m_selectedNode = null; m_selectedNodeAttr = null; m_highlightedObject = null; m_highlightedObjectAttr = null; } private static Microsoft.Glee.Drawing.Node CreateNode(Microsoft.Glee.Drawing.Graph graph, BasicBlock bb, bool fExpandBasicBlocks) { Microsoft.Glee.Drawing.Node node = graph.AddNode(bb.Id) as Microsoft.Glee.Drawing.Node; Microsoft.Glee.Drawing.NodeAttr attr = node.Attr; if (bb.Type == "EntryBasicBlock") { attr.Shape = Microsoft.Glee.Drawing.Shape.Box; attr.Fillcolor = Microsoft.Glee.Drawing.Color.Green; } else if (bb.Type == "ExitBasicBlock") { attr.Shape = Microsoft.Glee.Drawing.Shape.Box; attr.Fillcolor = Microsoft.Glee.Drawing.Color.Red; } else if (bb.Type == "ExceptionHandlerBasicBlock") { attr.Shape = Microsoft.Glee.Drawing.Shape.Box; attr.Fillcolor = Microsoft.Glee.Drawing.Color.Purple; } else { attr.Shape = Microsoft.Glee.Drawing.Shape.Box; } if (fExpandBasicBlocks) { StringBuilder sb = new StringBuilder(); sb.AppendFormat("{0}:", bb.Id); sb.AppendLine(); foreach (Operator op in bb.Operators) { sb.AppendLine(op.Value); } node.Attr.Label = sb.ToString(); } else { attr.Label = bb.Id + " - " + bb.Index; } return node; } //--// private void ListVariables() { ListView.ListViewItemCollection col = listViewVariables.Items; listViewVariables.SuspendLayout(); col.Clear(); foreach (Variable var in m_method.Variables) { ListViewItem lvi = new ListViewItem(var.Name); lvi.SubItems.Add(var.Type); col.Add(lvi); } listViewVariables.AutoResizeColumns(ColumnHeaderAutoResizeStyle.ColumnContent); listViewVariables.ResumeLayout(); } //--//--// private void SelectBasicBlock(BasicBlock bb) { ListView.ListViewItemCollection col = listViewBasicBlock.Items; listViewBasicBlock.SuspendLayout(); col.Clear(); m_selectedOpLVI = null; m_selectedBasicBlock = bb; if (bb != null) { foreach (Operator op in bb.Operators) { ListViewItem lvi = new ListViewItem(op.Index.ToString()); lvi.SubItems.Add(op.Type); lvi.SubItems.Add(op.Value); col.Add(lvi); } } if (listViewBasicBlock.Items.Count > 0) { listViewBasicBlock.AutoResizeColumns(ColumnHeaderAutoResizeStyle.ColumnContent); } listViewBasicBlock.ResumeLayout(); if (listViewBasicBlock.Items.Count > 0) { listViewBasicBlock.Items[0].Selected = true; listViewBasicBlock.Select(); } UpdateCodePane(); } //--//--// private void gViewer1_SelectionChanged(object sender, EventArgs e) { if (m_highlightedObject != null) { if (m_highlightedObject is Microsoft.Glee.Drawing.Edge) { Microsoft.Glee.Drawing.Edge edge = (Microsoft.Glee.Drawing.Edge)m_highlightedObject; edge.Attr = m_highlightedObjectAttr as Microsoft.Glee.Drawing.EdgeAttr; } else if (m_highlightedObject is Microsoft.Glee.Drawing.Node) { Microsoft.Glee.Drawing.Node node = (Microsoft.Glee.Drawing.Node)m_highlightedObject; node.Attr = m_highlightedObjectAttr as Microsoft.Glee.Drawing.NodeAttr; } m_highlightedObject = null; m_highlightedObjectAttr = null; } if (gViewer1.SelectedObject != null) { m_highlightedObject = gViewer1.SelectedObject; if (m_highlightedObject is Microsoft.Glee.Drawing.Edge) { Microsoft.Glee.Drawing.Edge edge = (Microsoft.Glee.Drawing.Edge)m_highlightedObject; m_highlightedObjectAttr = edge.Attr.Clone(); edge.Attr.Color = Microsoft.Glee.Drawing.Color.Magenta; edge.Attr.Fontcolor = Microsoft.Glee.Drawing.Color.Magenta; } else if (m_highlightedObject is Microsoft.Glee.Drawing.Node) { Microsoft.Glee.Drawing.Node node = (Microsoft.Glee.Drawing.Node)m_highlightedObject; m_highlightedObjectAttr = node.Attr.Clone(); node.Attr.Color = Microsoft.Glee.Drawing.Color.Magenta; node.Attr.Fontcolor = Microsoft.Glee.Drawing.Color.Magenta; } } gViewer1.Invalidate(); } private void gViewer1_MouseClick(object sender, MouseEventArgs e) { // Do nothing if we didn't click on a node or click on the same node if (m_highlightedObject is Microsoft.Glee.Drawing.Node && m_highlightedObject != m_selectedNode) { if (m_selectedNode != null) { m_selectedNode.Attr = m_selectedNodeAttr; m_selectedNode = null; m_selectedNodeAttr = null; } Microsoft.Glee.Drawing.Node node = (Microsoft.Glee.Drawing.Node)m_highlightedObject; foreach (BasicBlock bb in m_method.BasicBlocks) { if (bb.Id == node.Id) { SelectBasicBlock(bb); m_selectedNode = node; // Save the original / untempered style so when we can go back to it when the node is unselected m_selectedNodeAttr = ((Microsoft.Glee.Drawing.NodeAttr)m_highlightedObjectAttr).Clone(); // Apply the selected style to both the node and the saved styled from highlight so when // mouse moves away, the node remain selected ((Microsoft.Glee.Drawing.NodeAttr)m_highlightedObjectAttr).Fillcolor = Microsoft.Glee.Drawing.Color.Goldenrod; node.Attr.Fillcolor = Microsoft.Glee.Drawing.Color.Goldenrod; break; } } gViewer1.Invalidate(); } } private void listViewBasicBlock_DoubleClick(object sender, EventArgs e) { if (m_selectedBasicBlock != null && listViewBasicBlock.SelectedIndices.Count > 0) { int i = listViewBasicBlock.SelectedIndices[0]; if (i >= 0 && i < m_selectedBasicBlock.Operators.Count) { Operator op = m_selectedBasicBlock.Operators[i]; if (op.Call != null) { Method method; if (m_lookupMethod.TryGetValue(op.Call, out method)) { SelectMethod(method); } } } } } private void checkBoxExpandBasicBlocks_CheckedChanged(object sender, EventArgs e) { m_fExpandBasicBlocks = checkBoxExpandBasicBlocks.Checked; SelectBasicBlock(null); CreateGraph(); } private void listViewBasicBlock_Click(object sender, EventArgs e) { UpdateCodePane(); } private void UpdateCodePane(bool force = false) { if (listViewBasicBlock.SelectedIndices.Count == 0) { ClearCodePane(); } else { // Remove selection highlight on the list view item if (m_selectedOpLVI != null) { m_selectedOpLVI.BackColor = listViewBasicBlock.BackColor; m_selectedOpLVI.ForeColor = listViewBasicBlock.ForeColor; } var selectedOpLVI = listViewBasicBlock.SelectedItems[0]; var op = m_selectedBasicBlock.Operators[selectedOpLVI.Index]; var sourceCode = m_sourceCodeTracker.GetSourceCode(op?.Debug?.File); if (sourceCode != null) { bool showLineNumbers = checkBoxShowLineNumbers.Checked; int lineNumberPadding = showLineNumbers ? sourceCode.Count.ToString().Length + 2 : 0; // +2 for ": " var previousOp = (m_selectedOpLVI != null) ? m_selectedBasicBlock.Operators[m_selectedOpLVI.Index] : null; if (force || sourceCode.File != previousOp?.Debug?.File) { richTextBoxCode.Clear(); // Add the lines to the rich text box if (showLineNumbers) { for (int i = 1; i <= sourceCode.Count; i++) { string lineNumberText = i.ToString(); richTextBoxCode.AppendText($"{new string(' ', lineNumberPadding - 2 - lineNumberText.Length)}{lineNumberText}: {sourceCode[i]}\r\n"); } } else { for (int i = 1; i <= sourceCode.Count; i++) { richTextBoxCode.AppendText($"{sourceCode[i]}\r\n"); } } textBoxCodeFileName.Text = op.Debug.File; buttonLaunchCode.Enabled = true; } else if (previousOp != op) { // Remove previous highlighting richTextBoxCode.SelectionStart = richTextBoxCode.GetFirstCharIndexFromLine(previousOp.Debug.BeginLine - 1); richTextBoxCode.SelectionLength = richTextBoxCode.GetFirstCharIndexFromLine(previousOp.Debug.EndLine - 1) + richTextBoxCode.Lines[previousOp.Debug.EndLine - 1].Length - richTextBoxCode.SelectionStart; richTextBoxCode.SelectionBackColor = richTextBoxCode.BackColor; } if (force || previousOp != op) { // Highlight the relevant lines int beginLineCharIndex = richTextBoxCode.GetFirstCharIndexFromLine(op.Debug.BeginLine - 1); int endLineCharIndex = richTextBoxCode.GetFirstCharIndexFromLine(op.Debug.EndLine - 1); richTextBoxCode.SelectionStart = beginLineCharIndex; richTextBoxCode.SelectionLength = endLineCharIndex + richTextBoxCode.Lines[op.Debug.EndLine - 1].Length - richTextBoxCode.SelectionStart; richTextBoxCode.SelectionBackColor = Color.PaleGoldenrod; // Highlight the relevant columns richTextBoxCode.SelectionStart = beginLineCharIndex + lineNumberPadding + op.Debug.BeginColumn - 1; richTextBoxCode.SelectionLength = endLineCharIndex + lineNumberPadding + op.Debug.EndColumn - richTextBoxCode.SelectionStart; richTextBoxCode.SelectionBackColor = Color.Goldenrod; } // Scroll to a few lines before the start int scrollLineTarget = op.Debug.BeginLine - 4; if (scrollLineTarget < 0) { scrollLineTarget = 0; } richTextBoxCode.SelectionStart = richTextBoxCode.GetFirstCharIndexFromLine(scrollLineTarget); richTextBoxCode.SelectionLength = 0; richTextBoxCode.ScrollToCaret(); } else { textBoxCodeFileName.Clear(); richTextBoxCode.Clear(); richTextBoxCode.AppendText("//\r\n// No corresponding source code\r\n//\r\n"); buttonLaunchCode.Enabled = false; } // Override the selected LVI with the highlight color so it remain "highlighted" when losing focus. selectedOpLVI.BackColor = SystemColors.Highlight; selectedOpLVI.ForeColor = SystemColors.HighlightText; m_selectedOpLVI = selectedOpLVI; } } private void ClearCodePane() { richTextBoxCode.Clear(); textBoxCodeFileName.Clear(); buttonLaunchCode.Enabled = false; m_selectedOpLVI = null; } private void MainForm_Resize(object sender, EventArgs e) { const int margin = 3; listViewBasicBlock.Height = splitContainer.Panel2.Height - listViewVariables.Height - richTextBoxCode.Height - buttonLaunchCode.Height - margin * 3; listViewBasicBlock.Width = splitContainer.Panel2.Width; textBoxCodeFileName.Top = listViewBasicBlock.Bottom + margin; textBoxCodeFileName.Width = splitContainer.Panel2.Width - buttonLaunchCode.Width - margin; buttonLaunchCode.Top = listViewBasicBlock.Bottom + margin; buttonLaunchCode.Left = textBoxCodeFileName.Right + margin; gViewer1.Height = splitContainer.Panel1.Height - checkBoxExpandBasicBlocks.Height - margin; checkBoxExpandBasicBlocks.Top = gViewer1.Bottom + margin; checkBoxShowLineNumbers.Top = gViewer1.Bottom + margin; listBoxMethods.Width = textBoxFilter.Width; } private void buttonLaunchCode_Click(object sender, EventArgs e) { try { Process.Start(textBoxCodeFileName.Text); } catch { // ignored } } private void textBoxFilter_TextChanged(object sender, EventArgs e) { UpdateListBox(); } private void UpdateListBox() { if (m_lookupMethod != null) { string filter = textBoxFilter.Text.ToLower(); List lst = new List(); foreach (string id in m_lookupMethod.Keys) { if (string.IsNullOrEmpty(filter) || id.ToLower().Contains(filter)) { lst.Add(id); } } lst.Sort(); ListBox.ObjectCollection col = listBoxMethods.Items; listBoxMethods.SuspendLayout(); col.Clear(); col.AddRange(lst.ToArray()); listBoxMethods.ResumeLayout(); listBoxMethods.Visible = listBoxMethods.Items.Count > 0; } } private void listBoxMethods_Click(object sender, EventArgs e) { if (m_lookupMethod != null) { if (listBoxMethods.SelectedItem != null) { SelectMethod(m_lookupMethod[(string)listBoxMethods.SelectedItem]); } } } private void textBoxFilter_Click(object sender, EventArgs e) { textBoxFilter.SelectAll(); listBoxMethods.Visible = listBoxMethods.Items.Count > 0; if (listBoxMethods.Visible) { listBoxMethods.SelectedIndex = -1; } } private void checkBoxShowLineNumbers_CheckedChanged(object sender, EventArgs e) { UpdateCodePane(/*force*/true); } private void buttonBack_Click(object sender, EventArgs e) { if (m_backStack.Count > 0) { GoBack(m_backStack.Pop()); } } private void buttonBackStackDropdown_Click(object sender, EventArgs e) { if (m_backStack.Count > 0) { contextMenuStripBackStack.Items.Clear(); foreach (var item in m_backStack) { contextMenuStripBackStack.Items.Add(item.Method.Name, null, new EventHandler(delegate (object o, EventArgs a) { BackStackState state; do { state = m_backStack.Pop(); } while (!state.Equals(item)); GoBack(state); })); } contextMenuStripBackStack.Show(buttonBack, new Point(0, buttonBack.Height)); } } private void GoBack(BackStackState state) { // Select the method m_method = state.Method; textBoxFilter.Text = m_method.Name; listBoxMethods.Visible = false; CreateGraph(); ListVariables(); // Select the basic block SelectBasicBlock(state.BasicBlock); if (state.BasicBlock != null) { // Select the node in graph var node = gViewer1.Graph.FindNode(state.BasicBlock.Id); if (node != null) { m_selectedNode = node; m_selectedNodeAttr = node.Attr.Clone(); node.Attr.Fillcolor = Microsoft.Glee.Drawing.Color.Goldenrod; gViewer1.Invalidate(); } // Select the operation var lvi = listViewBasicBlock.FindItemWithText(state.Operator.Index.ToString(), /*includesSubItem*/false, /*startIndex*/0, /*prefixSearch*/false); if (lvi != null) { lvi.Selected = true; listViewBasicBlock.Select(); UpdateCodePane(); } } if (m_backStack.Count == 0) { buttonBack.Enabled = false; buttonBackStackDropdown.Enabled = false; } } } } ================================================ FILE: Zelig/Zelig/CompileTime/AnalysisTools/IRViewer/MainForm.resx ================================================ text/microsoft-resx 2.0 System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 126, 17 266, 17 ================================================ FILE: Zelig/Zelig/CompileTime/AnalysisTools/IRViewer/Parser.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // namespace Microsoft.Zelig.Tools.IRViewer { using System; using System.Collections.Generic; using System.Text; using System.Xml; public class Method { // // State // public string Name; public List< Variable > Variables = new List< Variable >(); public List< BasicBlock > BasicBlocks = new List< BasicBlock >(); public List< BasicBlockEdge > BasicBlockEdges = new List< BasicBlockEdge >(); } public class Variable { // // State // public string Name; public string Type; } public class BasicBlock { // // State // public string Id; public string Index; public string Type; public List< Operator > Operators = new List< Operator >(); public List< ReachingDefinition > ReachingDefinitions = new List< ReachingDefinition >(); public List< HandlerFor > Handlers = new List< HandlerFor >(); } public class ReachingDefinition { // // State // public string Variable; public List< Operator > Definitions = new List< Operator >(); } public class HandlerFor { // // State // public string Eh; } public class Operator { // // State // public int Index; public string Type; public string Value; public string Call; public Debug Debug; } public class Debug { // // State // public string File; public int BeginLine; public int BeginColumn; public int EndLine; public int EndColumn; } public class BasicBlockEdge { // // State // public BasicBlock From; public BasicBlock To; public string Kind; } public class Parser { // // State // private Dictionary< string, Method > m_methods = new Dictionary< string, Method >(); // // Constructor Methods // public Parser( XmlNode node ) { foreach(XmlNode subnode in node.SelectNodes( "Method" )) { Method res = ParseMethod( subnode ); m_methods[ res.Name ] = res; } } public Dictionary< string, Method > Methods { get { return m_methods; } } //--// private Method ParseMethod( XmlNode node ) { Method res = new Method(); res.Name = GetAttribute( node, "Name" ); foreach(XmlNode subnode in node.SelectNodes( "Variable" )) { res.Variables.Add( ParseVariable( subnode ) ); } Dictionary< string, BasicBlock > lookupBasicBlock = new Dictionary< string, BasicBlock >(); Dictionary< string, XmlNode > lookupNode = new Dictionary< string, XmlNode >(); Dictionary< int , Operator > lookupOperator = new Dictionary< int , Operator >(); foreach(XmlNode subnode in node.SelectNodes( "BasicBlock" )) { res.BasicBlocks.Add( ParseBasicBlock( subnode, lookupBasicBlock, lookupNode, lookupOperator ) ); } foreach(string id in lookupNode.Keys) { BasicBlock bb = lookupBasicBlock[ id ]; XmlNode subnode = lookupNode [ id ]; ParseBasicBlock( subnode, res, bb, lookupBasicBlock, lookupOperator ); } return res; } private Variable ParseVariable( XmlNode node ) { Variable res = new Variable(); res.Name = GetAttribute( node, "Name" ); res.Type = GetAttribute( node, "Type" ); return res; } private BasicBlock ParseBasicBlock( XmlNode node , Dictionary< string, BasicBlock > lookupBasicBlock , Dictionary< string, XmlNode > lookupNode , Dictionary< int , Operator > lookupOperator ) { BasicBlock res = new BasicBlock(); res.Id = GetAttribute( node, "Id" ); res.Index = GetAttribute( node, "Index" ); res.Type = GetAttribute( node, "Type" ); lookupBasicBlock[ res.Id ] = res; lookupNode [ res.Id ] = node; foreach(XmlNode subnode in node.SelectNodes( "Operator" )) { res.Operators.Add( ParseOperator( subnode, lookupOperator ) ); } return res; } private Operator ParseOperator( XmlNode node , Dictionary< int, Operator > lookupOperator ) { Operator res = new Operator(); res.Index = int.Parse( GetAttribute( node, "Index" ) ); res.Call = GetAttribute( node, "Call" ); res.Type = GetAttribute(node, "Type"); res.Value = node.InnerText; XmlNode subnode = node.SelectSingleNode( "Debug" ); if(subnode != null) { res.Debug = ParseDebug( subnode ); } lookupOperator[ res.Index ] = res; return res; } private Debug ParseDebug( XmlNode node ) { Debug res = new Debug(); res.File = GetAttribute( node, "File" ); res.BeginLine = int.Parse( GetAttribute( node, "BeginLine" ) ); res.BeginColumn = int.Parse( GetAttribute( node, "BeginColumn" ) ); res.EndLine = int.Parse( GetAttribute( node, "EndLine" ) ); res.EndColumn = int.Parse( GetAttribute( node, "EndColumn" ) ); return res; } private void ParseBasicBlock( XmlNode node , Method method , BasicBlock bb , Dictionary< string, BasicBlock > lookupBasicBlock , Dictionary< int, Operator > lookupOperator ) { foreach(XmlNode subnode in node.SelectNodes( "ReachingDefinition" )) { bb.ReachingDefinitions.Add( ParseReachingDefinition( subnode, lookupOperator ) ); } foreach(XmlNode subnode in node.SelectNodes( "HandlerFor" )) { bb.Handlers.Add( ParseHandler( subnode ) ); } foreach(XmlNode subnode in node.SelectNodes( "Edge" )) { method.BasicBlockEdges.Add( ParseBasicBlockEdge( subnode, lookupBasicBlock ) ); } } private ReachingDefinition ParseReachingDefinition( XmlNode node , Dictionary< int, Operator > lookupOperator ) { ReachingDefinition res = new ReachingDefinition(); res.Variable = GetAttribute( node, "Variable" ); foreach(XmlNode subnode in node.SelectNodes( "Definition" )) { res.Definitions.Add( lookupOperator[ int.Parse( GetAttribute( subnode, "Index" ) ) ] ); } return res; } private HandlerFor ParseHandler( XmlNode node ) { HandlerFor res = new HandlerFor(); res.Eh = GetAttribute( node, "Type" ); return res; } private BasicBlockEdge ParseBasicBlockEdge( XmlNode node , Dictionary< string, BasicBlock > lookupBasicBlock ) { BasicBlockEdge res = new BasicBlockEdge(); res.From = lookupBasicBlock[ GetAttribute( node, "From" ) ]; res.To = lookupBasicBlock[ GetAttribute( node, "To" ) ]; res.Kind = GetAttribute( node, "Kind" ) ; return res; } //--// private static string GetAttribute( XmlNode node , string name ) { XmlAttribute attrib = node.Attributes.GetNamedItem( name ) as XmlAttribute ; if(attrib != null) { return attrib.Value; } return null; } } } ================================================ FILE: Zelig/Zelig/CompileTime/AnalysisTools/IRViewer/Program.cs ================================================ using System; using System.Collections.Generic; using System.Windows.Forms; namespace Microsoft.Zelig.Tools.IRViewer { static class Program { /// /// The main entry point for the application. /// [STAThread] static void Main() { Application.EnableVisualStyles(); Application.SetCompatibleTextRenderingDefault( false ); Application.Run( new MainForm() ); } } } ================================================ FILE: Zelig/Zelig/CompileTime/AnalysisTools/IRViewer/Properties/AssemblyInfo.cs ================================================ using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; // General Information about an assembly is controlled through the following // set of attributes. Change these attribute values to modify the information // associated with an assembly. [assembly: AssemblyTitle( "IRViewer" )] [assembly: AssemblyDescription( "" )] [assembly: AssemblyConfiguration( "" )] [assembly: AssemblyCompany( "Microsoft" )] [assembly: AssemblyProduct( "IRViewer" )] [assembly: AssemblyCopyright( "Copyright © Microsoft 2006" )] [assembly: AssemblyTrademark( "" )] [assembly: AssemblyCulture( "" )] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible( false )] //// The following GUID is for the ID of the typelib if this project is exposed to COM //[assembly: Guid( "fafaa296-9d0d-42fa-b922-8fb69f2544b2" )] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // [assembly: AssemblyVersion( "1.0.0.0" )] [assembly: AssemblyFileVersion( "1.0.0.0" )] ================================================ FILE: Zelig/Zelig/CompileTime/AnalysisTools/IRViewer/Properties/Resources.Designer.cs ================================================ //------------------------------------------------------------------------------ // // This code was generated by a tool. // Runtime Version:4.0.30319.34209 // // Changes to this file may cause incorrect behavior and will be lost if // the code is regenerated. // //------------------------------------------------------------------------------ namespace Microsoft.Zelig.Tools.IRViewer.Properties { using System; /// /// A strongly-typed resource class, for looking up localized strings, etc. /// // This class was auto-generated by the StronglyTypedResourceBuilder // class via a tool like ResGen or Visual Studio. // To add or remove a member, edit your .ResX file then rerun ResGen // with the /str option, or rebuild your VS project. [global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Resources.Tools.StronglyTypedResourceBuilder", "4.0.0.0")] [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] [global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()] internal class Resources { private static global::System.Resources.ResourceManager resourceMan; private static global::System.Globalization.CultureInfo resourceCulture; [global::System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")] internal Resources() { } /// /// Returns the cached ResourceManager instance used by this class. /// [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)] internal static global::System.Resources.ResourceManager ResourceManager { get { if (object.ReferenceEquals(resourceMan, null)) { global::System.Resources.ResourceManager temp = new global::System.Resources.ResourceManager("Microsoft.Zelig.Tools.IRViewer.Properties.Resources", typeof(Resources).Assembly); resourceMan = temp; } return resourceMan; } } /// /// Overrides the current thread's CurrentUICulture property for all /// resource lookups using this strongly typed resource class. /// [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)] internal static global::System.Globalization.CultureInfo Culture { get { return resourceCulture; } set { resourceCulture = value; } } } } ================================================ FILE: Zelig/Zelig/CompileTime/AnalysisTools/IRViewer/Properties/Resources.resx ================================================  text/microsoft-resx 2.0 System.Resources.ResXResourceReader, System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 System.Resources.ResXResourceWriter, System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 ================================================ FILE: Zelig/Zelig/CompileTime/AnalysisTools/IRViewer/Properties/Settings.Designer.cs ================================================ //------------------------------------------------------------------------------ // // This code was generated by a tool. // Runtime Version:4.0.30319.34209 // // Changes to this file may cause incorrect behavior and will be lost if // the code is regenerated. // //------------------------------------------------------------------------------ namespace Microsoft.Zelig.Tools.IRViewer.Properties { [global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()] [global::System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.VisualStudio.Editors.SettingsDesigner.SettingsSingleFileGenerator", "12.0.0.0")] internal sealed partial class Settings : global::System.Configuration.ApplicationSettingsBase { private static Settings defaultInstance = ((Settings)(global::System.Configuration.ApplicationSettingsBase.Synchronized(new Settings()))); public static Settings Default { get { return defaultInstance; } } } } ================================================ FILE: Zelig/Zelig/CompileTime/AnalysisTools/IRViewer/Properties/Settings.settings ================================================  ================================================ FILE: Zelig/Zelig/CompileTime/AnalysisTools/IRViewer/SourceCodeTracker.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // namespace Microsoft.Zelig.Tools.IRViewer { using System; using System.Collections.Generic; public sealed class SourceCodeTracker { public sealed class SourceCode { readonly List _lines; public SourceCode(string file) { File = file; _lines = new List(); using (var stream = new System.IO.StreamReader(file)) { string line; while ((line = stream.ReadLine()) != null) { _lines.Add(line); } } } public string File { get; } public int Count => _lines.Count; public string this[int line] { get { if (line >= 1 && line <= _lines.Count) { return _lines[line - 1]; } return string.Empty; } } } GrowOnlyHashTable _lookupSourceCode; public SourceCodeTracker() { _lookupSourceCode = HashTableFactory.New(); } public SourceCode GetSourceCode(string file) { SourceCode sc = null; if (_lookupSourceCode.TryGetValue(file, out sc)) { return sc; } if (System.IO.File.Exists(file)) { try { sc = new SourceCode(file); } catch { // ignored } } _lookupSourceCode[file] = sc; return sc; } } } ================================================ FILE: Zelig/Zelig/CompileTime/AnalysisTools/InequalityGraphVisualization/GraphForm.Designer.cs ================================================ namespace Microsoft.Zelig.Tools.InequalityGraphVisualization { partial class GraphForm { /// /// Required designer variable. /// private System.ComponentModel.IContainer components = null; /// /// Clean up any resources being used. /// /// true if managed resources should be disposed; otherwise, false. protected override void Dispose( bool disposing ) { if(disposing && (components != null)) { components.Dispose(); } base.Dispose( disposing ); } #region Windows Form Designer generated code /// /// Required method for Designer support - do not modify /// the contents of this method with the code editor. /// private void InitializeComponent() { this.splitContainer1 = new System.Windows.Forms.SplitContainer(); this.gViewer1 = new Microsoft.Glee.GraphViewerGdi.GViewer(); this.richTextBox1 = new System.Windows.Forms.RichTextBox(); this.splitContainer2 = new System.Windows.Forms.SplitContainer(); this.hScrollBar1 = new System.Windows.Forms.HScrollBar(); this.textBox1 = new System.Windows.Forms.TextBox(); this.splitContainer1.Panel1.SuspendLayout(); this.splitContainer1.Panel2.SuspendLayout(); this.splitContainer1.SuspendLayout(); this.splitContainer2.Panel1.SuspendLayout(); this.splitContainer2.Panel2.SuspendLayout(); this.splitContainer2.SuspendLayout(); this.SuspendLayout(); // // splitContainer1 // this.splitContainer1.Dock = System.Windows.Forms.DockStyle.Fill; this.splitContainer1.Location = new System.Drawing.Point( 0, 0 ); this.splitContainer1.Name = "splitContainer1"; this.splitContainer1.Orientation = System.Windows.Forms.Orientation.Horizontal; // // splitContainer1.Panel1 // this.splitContainer1.Panel1.Controls.Add( this.splitContainer2 ); // // splitContainer1.Panel2 // this.splitContainer1.Panel2.Controls.Add( this.richTextBox1 ); this.splitContainer1.Size = new System.Drawing.Size( 1171, 738 ); this.splitContainer1.SplitterDistance = 634; this.splitContainer1.TabIndex = 0; // // gViewer1 // this.gViewer1.AsyncLayout = false; this.gViewer1.AutoScroll = true; this.gViewer1.BackwardEnabled = false; this.gViewer1.Dock = System.Windows.Forms.DockStyle.Fill; this.gViewer1.EditObjects = false; this.gViewer1.ForwardEnabled = false; this.gViewer1.Graph = null; this.gViewer1.Location = new System.Drawing.Point( 0, 0 ); this.gViewer1.MouseHitDistance = 0.05; this.gViewer1.Name = "gViewer1"; this.gViewer1.NavigationVisible = true; this.gViewer1.PanButtonPressed = false; this.gViewer1.SaveButtonVisible = false; this.gViewer1.Size = new System.Drawing.Size( 1171, 593 ); this.gViewer1.TabIndex = 1; this.gViewer1.ZoomF = 1; this.gViewer1.ZoomFraction = 0.5; this.gViewer1.ZoomWindowThreshold = 0.05; this.gViewer1.SelectionChanged += new System.EventHandler( this.gViewer1_SelectionChanged ); this.gViewer1.MouseClick += new System.Windows.Forms.MouseEventHandler( this.gViewer1_MouseClick ); // // richTextBox1 // this.richTextBox1.Dock = System.Windows.Forms.DockStyle.Fill; this.richTextBox1.Location = new System.Drawing.Point( 0, 0 ); this.richTextBox1.Name = "richTextBox1"; this.richTextBox1.Size = new System.Drawing.Size( 1171, 100 ); this.richTextBox1.TabIndex = 0; this.richTextBox1.Text = ""; // // splitContainer2 // this.splitContainer2.Dock = System.Windows.Forms.DockStyle.Fill; this.splitContainer2.Location = new System.Drawing.Point( 0, 0 ); this.splitContainer2.Name = "splitContainer2"; this.splitContainer2.Orientation = System.Windows.Forms.Orientation.Horizontal; // // splitContainer2.Panel1 // this.splitContainer2.Panel1.Controls.Add( this.textBox1 ); this.splitContainer2.Panel1.Controls.Add( this.hScrollBar1 ); // // splitContainer2.Panel2 // this.splitContainer2.Panel2.Controls.Add( this.gViewer1 ); this.splitContainer2.Size = new System.Drawing.Size( 1171, 634 ); this.splitContainer2.SplitterDistance = 40; this.splitContainer2.SplitterWidth = 1; this.splitContainer2.TabIndex = 2; // // hScrollBar1 // this.hScrollBar1.Location = new System.Drawing.Point( 9, 9 ); this.hScrollBar1.Name = "hScrollBar1"; this.hScrollBar1.Size = new System.Drawing.Size( 235, 20 ); this.hScrollBar1.TabIndex = 0; this.hScrollBar1.ValueChanged += new System.EventHandler( this.hScrollBar1_ValueChanged ); // // textBox1 // this.textBox1.Location = new System.Drawing.Point( 248, 9 ); this.textBox1.Name = "textBox1"; this.textBox1.ReadOnly = true; this.textBox1.Size = new System.Drawing.Size( 911, 20 ); this.textBox1.TabIndex = 1; // // GraphForm // this.AutoScaleDimensions = new System.Drawing.SizeF( 6F, 13F ); this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font; this.ClientSize = new System.Drawing.Size( 1171, 738 ); this.Controls.Add( this.splitContainer1 ); this.Name = "GraphForm"; this.Text = "Inequality Graph Viewer"; this.Load += new System.EventHandler( this.GraphForm_Load ); this.splitContainer1.Panel1.ResumeLayout( false ); this.splitContainer1.Panel2.ResumeLayout( false ); this.splitContainer1.ResumeLayout( false ); this.splitContainer2.Panel1.ResumeLayout( false ); this.splitContainer2.Panel1.PerformLayout(); this.splitContainer2.Panel2.ResumeLayout( false ); this.splitContainer2.ResumeLayout( false ); this.ResumeLayout( false ); } #endregion private System.Windows.Forms.SplitContainer splitContainer1; private Microsoft.Glee.GraphViewerGdi.GViewer gViewer1; private System.Windows.Forms.RichTextBox richTextBox1; private System.Windows.Forms.SplitContainer splitContainer2; private System.Windows.Forms.TextBox textBox1; private System.Windows.Forms.HScrollBar hScrollBar1; } } ================================================ FILE: Zelig/Zelig/CompileTime/AnalysisTools/InequalityGraphVisualization/GraphForm.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // namespace Microsoft.Zelig.Tools.InequalityGraphVisualization { using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Text; using System.Windows.Forms; using Microsoft.Zelig.CodeGeneration.IR; using Microsoft.Zelig.CodeGeneration.IR.Transformations; public partial class GraphForm : Form { // // State // ConstraintSystemCollector.GraphState m_gs; GrowOnlyHashTable< object, string > m_ids = HashTableFactory.New< object, string >(); object m_selectedObjectAttr; object m_selectedObject; // // Constructor Methods // public GraphForm( ConstraintSystemCollector.GraphState gs ) { m_gs = gs; InitializeComponent(); } // // Helper Methods // private void CreateGraph() { Microsoft.Glee.Drawing.Graph g = new Microsoft.Glee.Drawing.Graph( "None" ); g.GraphAttr.NodeAttr.Padding = 3; foreach(object obj in m_gs.Vertices.Keys) { if(m_gs.WasReached( obj )) { Microsoft.Glee.Drawing.Node node = CreateNode( g, obj ); } } foreach(ConstraintSystemCollector.ConstraintInstance ci in m_gs.Constraints) { if(m_gs.WasReached( ci.Destination ) && m_gs.WasReached( ci.Source ) ) { Microsoft.Glee.Drawing.Edge edgeG = CreateEdge( g, ci ); } } gViewer1.Graph = g; if(m_gs.ProofTests != null) { hScrollBar1.Minimum = 0; hScrollBar1.Maximum = m_gs.ProofTests.Count - 1 + hScrollBar1.LargeChange; } } private Microsoft.Glee.Drawing.Edge CreateEdge( Microsoft.Glee.Drawing.Graph graph , ConstraintSystemCollector.ConstraintInstance ci ) { Microsoft.Glee.Drawing.Edge edge = graph.AddEdge( GetId( ci.Source ), GetId( ci.Destination ) ) as Microsoft.Glee.Drawing.Edge; Microsoft.Glee.Drawing.EdgeAttr attr = edge.Attr; edge.UserData = ci; attr.ArrowHeadAtTarget = Microsoft.Glee.Drawing.ArrowStyle.Normal; attr.Label = ci.Weight.ToString(); //// attr.Fontsize -= 4; return edge; } private Microsoft.Glee.Drawing.Node CreateNode( Microsoft.Glee.Drawing.Graph graph , object obj ) { Microsoft.Glee.Drawing.Node node = graph.AddNode( GetId( obj ) ) as Microsoft.Glee.Drawing.Node; Microsoft.Glee.Drawing.NodeAttr attr = node.Attr; attr.Label = GetLabel( obj ); Operator op = m_gs.Vertices[obj]; if(op is PhiOperator) { attr.Shape = Microsoft.Glee.Drawing.Shape.Diamond; } else if(op is PiOperator) { attr.Shape = Microsoft.Glee.Drawing.Shape.DoubleCircle; } node.UserData = obj; return node; } private Microsoft.Glee.Drawing.Node GetNode( object obj ) { string id = GetId( obj ); return gViewer1.Graph.FindNode( id ); } private void SetColor( object obj , Microsoft.Glee.Drawing.Color color ) { SetColorForNode( GetNode( obj ), color ); } private void SetColorForNode( Microsoft.Glee.Drawing.Node node , Microsoft.Glee.Drawing.Color color ) { Microsoft.Glee.Drawing.NodeAttr nodeAttr = node.Attr; nodeAttr.Color = color; nodeAttr.Fontcolor = color; nodeAttr.Fillcolor = Microsoft.Glee.Drawing.Color.White; } private string GetId( object obj ) { string id; if(m_ids.TryGetValue( obj, out id ) == false) { id = string.Format( "Id{0}", m_ids.Count ); m_ids[obj] = id; } return id; } private string GetLabel( object obj ) { string res; if(m_gs.Labels.TryGetValue( obj, out res ) == false) { res = obj.ToString(); } return res; } //--// private void ClearText() { richTextBox1.Clear(); } private void AppendText( string fmt , params object[] args ) { richTextBox1.AppendText( string.Format( fmt, args ) ); richTextBox1.AppendText( "\n" ); } // // Event Methods // private void GraphForm_Load( object sender , EventArgs e ) { CreateGraph(); } private void gViewer1_SelectionChanged( object sender , EventArgs e ) { if(m_selectedObject != null) { if(m_selectedObject is Microsoft.Glee.Drawing.Edge) { Microsoft.Glee.Drawing.Edge edge = (Microsoft.Glee.Drawing.Edge)m_selectedObject; edge.Attr = m_selectedObjectAttr as Microsoft.Glee.Drawing.EdgeAttr; } else if(m_selectedObject is Microsoft.Glee.Drawing.Node) { Microsoft.Glee.Drawing.Node node = (Microsoft.Glee.Drawing.Node)m_selectedObject; node.Attr = m_selectedObjectAttr as Microsoft.Glee.Drawing.NodeAttr; } m_selectedObject = null; m_selectedObjectAttr = null; } if(gViewer1.SelectedObject == null) { //// label1.Text = "No object under the mouse"; //// this.gViewer.SetToolTip( toolTip1, "" ); } else { m_selectedObject = gViewer1.SelectedObject; if(m_selectedObject is Microsoft.Glee.Drawing.Edge) { Microsoft.Glee.Drawing.Edge edge = (Microsoft.Glee.Drawing.Edge)m_selectedObject; m_selectedObjectAttr = edge.Attr.Clone(); edge.Attr.Color = Microsoft.Glee.Drawing.Color.Magenta; edge.Attr.Fontcolor = Microsoft.Glee.Drawing.Color.Magenta; //// //here you can use e.Attr.Id or e.UserData to get back to you data //// this.gViewer.SetToolTip( this.toolTip1, String.Format( "edge from {0} {1}", edge.Source, edge.Target ) ); } else if(m_selectedObject is Microsoft.Glee.Drawing.Node) { Microsoft.Glee.Drawing.Node node = (Microsoft.Glee.Drawing.Node)m_selectedObject; m_selectedObjectAttr = node.Attr.Clone(); node.Attr.Color = Microsoft.Glee.Drawing.Color.Magenta; node.Attr.Fontcolor = Microsoft.Glee.Drawing.Color.Magenta; //// //here you can use e.Attr.Id to get back to your data //// this.gViewer.SetToolTip( toolTip1, String.Format( "node {0}", (selectedObject as Node).Attr.Label ) ); } } gViewer1.Invalidate(); } private void gViewer1_MouseClick( object sender , MouseEventArgs e ) { ClearText(); richTextBox1.Clear(); if(gViewer1.SelectedObject is Microsoft.Glee.Drawing.Edge) { Microsoft.Glee.Drawing.Edge edge = (Microsoft.Glee.Drawing.Edge)gViewer1.SelectedObject; ConstraintSystemCollector.ConstraintInstance ci = (ConstraintSystemCollector.ConstraintInstance)edge.UserData; AppendText( "Constraint: {0} - {1} <= {2}", GetLabel( ci.Destination ), GetLabel( ci.Source ), ci.Weight ); } if(gViewer1.SelectedObject is Microsoft.Glee.Drawing.Node) { Microsoft.Glee.Drawing.Node node = (Microsoft.Glee.Drawing.Node)gViewer1.SelectedObject; object obj = node.UserData; if(obj is ConstraintSystemCollector.ArrayLengthHolder) { ConstraintSystemCollector.ArrayLengthHolder hld = (ConstraintSystemCollector.ArrayLengthHolder)obj; obj = hld.Array; } AppendText( "Symbol: {0} = {1}", GetLabel( obj ), obj ); Operator op; if(m_gs.Vertices.TryGetValue( obj, out op ) && op != null) { AppendText( "Definition: {0} is Op_{1} : {2}", GetLabel( obj ), op.SpanningTreeIndex, op.ToPrettyString() ); Operator opStart = op; Operator opStop = op; for(int i = 0; i < 3; i++) { Operator op2 = opStart.GetPreviousOperator(); if(op2 == null) { break; } opStart = op2; } for(int i = 0; i < 3; i++) { Operator op2 = opStop.GetNextOperator(); if(op2 == null) { break; } opStop = op2; } Operator[] ops = op.BasicBlock.Operators; int start = ArrayUtility.FindInNotNullArray( ops, opStart ); int stop = ArrayUtility.FindInNotNullArray( ops, opStop ); AppendText( "----" ); while(start <= stop) { Operator op2 = ops[start++]; AppendText( "Op_{0}: {1}", op2.SpanningTreeIndex, op2.ToPrettyString() ); } } } } private void hScrollBar1_ValueChanged( object sender , EventArgs e ) { if(m_gs.ProofTests != null) { Stack< ConstraintSystemCollector.ConstraintInstance > stack = new Stack< ConstraintSystemCollector.ConstraintInstance >(); System.Text.StringBuilder sb = new StringBuilder(); string dir = (m_gs.Flavor == ConstraintSystemCollector.Kind.LessThanOrEqual) ? "<=" : ">="; for(int i = 0; i < hScrollBar1.Value; i++) { object val = m_gs.ProofTests[i]; if(val is ConstraintSystemCollector.ConstraintInstance) { var ci = val as ConstraintSystemCollector.ConstraintInstance; stack.Push( ci ); SetColor( ci.Source , Microsoft.Glee.Drawing.Color.Blue ); SetColor( ci.Destination, Microsoft.Glee.Drawing.Color.Brown ); sb.AppendFormat( "Checking: ## {0} {1} ## - ## {2} {3} ## {4} {5}\n", GetLabel( ci.Destination ), ci.Destination, GetLabel( ci.Source ), ci.Source, m_gs.Flavor == ConstraintSystemCollector.Kind.LessThanOrEqual ? "<=" : ">=", ci.Weight ); } else if(val is ConstraintSystemCollector.Lattice) { var res = (ConstraintSystemCollector.Lattice)val; if(stack.Count > 0) { var ci = stack.Pop(); switch(res) { case ConstraintSystemCollector.Lattice.True: SetColor( ci.Destination, Microsoft.Glee.Drawing.Color.Green ); break; case ConstraintSystemCollector.Lattice.Reduced: SetColor( ci.Destination, Microsoft.Glee.Drawing.Color.Orange ); break; case ConstraintSystemCollector.Lattice.False: SetColor( ci.Destination, Microsoft.Glee.Drawing.Color.Red ); break; } sb.AppendFormat( "Result: ## {0} {1} ## - ## {2} {3} ## {4} {5} ==> {6}\n", GetLabel( ci.Destination ), ci.Destination, GetLabel( ci.Source ), ci.Source, dir, ci.Weight, res ); } } else { foreach(Microsoft.Glee.Drawing.Node node in gViewer1.Graph.NodeMap.Values) { SetColorForNode( node, Microsoft.Glee.Drawing.Color.Black ); } sb.Length = 0; } } var ciArray = stack.ToArray(); for(int i = ciArray.Length; --i >= 0;) { var ci = ciArray[i]; var node = GetNode( ci.Destination ); if(i == 0) { node.Attr.Fillcolor = Microsoft.Glee.Drawing.Color.LightGreen; textBox1.Text = string.Format( "Step: {0}, trying to prove {1} {2} {3} {4}", hScrollBar1.Value, GetLabel( ci.Destination ), GetLabel( ci.Source ), dir, ci.Weight ); } else { node.Attr.Fillcolor = Microsoft.Glee.Drawing.Color.LightGray; } } richTextBox1.Clear(); richTextBox1.AppendText( sb.ToString() ); richTextBox1.ScrollToCaret(); gViewer1.Refresh(); } } } } ================================================ FILE: Zelig/Zelig/CompileTime/AnalysisTools/InequalityGraphVisualization/GraphForm.resx ================================================ text/microsoft-resx 2.0 System.Resources.ResXResourceReader, System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 System.Resources.ResXResourceWriter, System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 True ================================================ FILE: Zelig/Zelig/CompileTime/AnalysisTools/InequalityGraphVisualization/InequalityGraphVisualization.csproj ================================================  Debug AnyCPU 9.0.21022 2.0 {96BF0234-1D60-4401-A6B9-99839187234E} Library Properties Microsoft.Zelig.Tools.InequalityGraphVisualization Microsoft.Zelig.Tools.InequalityGraphVisualization v4.5 512 $(LlilumBuildRoot)\Host\obj\$(MSBuildProjectName)\ true full false $(LlilumBuildRoot)\Host\bin\$(Configuration)\ DEBUG;TRACE prompt 4 AllRules.ruleset AnyCPU false pdbonly true $(LlilumBuildRoot)\Host\bin\$(Configuration)\ TRACE prompt 4 AllRules.ruleset AnyCPU false $(LlilumBuildRoot)\Host\bin\$(Configuration)\ TRACE;DEBUG AnyCPU false false False ..\..\..\External\Binaries\GLEE\Debug\Microsoft.GLEE.dll False ..\..\..\External\Binaries\GLEE\Debug\Microsoft.GLEE.Drawing.dll False ..\..\..\External\Binaries\GLEE\Debug\Microsoft.GLEE.GraphViewerGDI.dll 3.5 Form GraphForm.cs GraphForm.cs Designer {186F31A3-EF89-4A25-B2D5-20061218AA01} Common False {186F31A3-EF89-4A25-B2D5-20060720AA01} TypeSystem False {186F31A3-EF89-4A25-B2D5-20070222AA01} CodeTransformation False {186F31A3-EF89-4A25-B2D5-20060603AA01} IntermediateRepresentation False ================================================ FILE: Zelig/Zelig/CompileTime/AnalysisTools/InequalityGraphVisualization/Properties/AssemblyInfo.cs ================================================ using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; // General Information about an assembly is controlled through the following // set of attributes. Change these attribute values to modify the information // associated with an assembly. [assembly: AssemblyTitle( "Microsoft.Zelig.Tools.InequalityGraphVisualization" )] [assembly: AssemblyDescription( "" )] [assembly: AssemblyConfiguration( "" )] [assembly: AssemblyCompany( "Microsoft" )] [assembly: AssemblyProduct( "InequalityGraphVisualization" )] [assembly: AssemblyCopyright( "Copyright © Microsoft 2007" )] [assembly: AssemblyTrademark( "" )] [assembly: AssemblyCulture( "" )] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible( false )] // The following GUID is for the ID of the typelib if this project is exposed to COM [assembly: Guid( "f330d684-c05e-4db4-b064-fd3156fa8e7c" )] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Build and Revision Numbers // by using the '*' as shown below: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion( "1.0.0.0" )] [assembly: AssemblyFileVersion( "1.0.0.0" )] ================================================ FILE: Zelig/Zelig/CompileTime/AnalysisTools/InequalityGraphVisualization/Viewer.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // namespace Microsoft.Zelig.Tools.InequalityGraphVisualization { using System; using System.Threading; using System.Collections.Generic; using System.Windows.Forms; using Microsoft.Zelig.CodeGeneration.IR; using Microsoft.Zelig.CodeGeneration.IR.Transformations; public class Viewer { // // State // static bool s_Initialized; // // Helper Methods // [STAThread] public static void Show( ConstraintSystemCollector.GraphState gs ) { if(!s_Initialized) { s_Initialized = true; Application.EnableVisualStyles(); Application.SetCompatibleTextRenderingDefault( false ); } Application.Run( new GraphForm( gs ) ); } } } ================================================ FILE: Zelig/Zelig/CompileTime/CodeGenerator/CodeGenerator.UnitTest/BaseTester.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // #define LIVE //#define REDIRECT_OUTPUT //#define DUMP_SINGLE_METHOD //#define USE_IMOTE_PLATFORM namespace Microsoft.Zelig.CodeGeneration.UnitTest { using System; using System.Collections.Generic; using System.Text; using System.IO; using Microsoft.Zelig.MetaData; using Importer = Microsoft.Zelig.MetaData.Importer; using Normalized = Microsoft.Zelig.MetaData.Normalized; using IR = Microsoft.Zelig.CodeGeneration.IR; using RT = Microsoft.Zelig.Runtime; using TS = Microsoft.Zelig.Runtime.TypeSystem; #if REDIRECT_OUTPUT internal class RedirectOutput : IDisposable { System.IO.TextWriter m_orig; System.IO.TextWriter m_writer; internal RedirectOutput( string file ) { m_orig = Console.Out; m_writer = new System.IO.StreamWriter( file, false, System.Text.Encoding.ASCII ); Console.SetOut( m_writer ); } public void Dispose() { Console.SetOut( m_orig ); m_writer.Close(); } } #else internal class RedirectOutput : IDisposable { internal RedirectOutput( string file ) { } public void Dispose() { } } #endif public abstract class BaseTester : TS.IEnvironmentProvider { public class TypeSystemForUnitTest : IR.TypeSystemForCodeTransformation { // // State // BaseTester m_owner; // // Constructor Methods // public TypeSystemForUnitTest( BaseTester owner , TS.IEnvironmentProvider env ) : base( env ) { m_owner = owner; } // // Helper Methods // protected override void NotifyCompilationPhase( IR.CompilationSteps.PhaseDriver phase ) { m_owner.NotifyCompilationPhase( phase ); } } #if LIVE protected static string BuildRoot = Expand( @"%DEPOTROOT%\ZeligBuild" ); #else protected static string BuildRoot = Expand( @"%DEPOTROOT%\ZeligBuild.Reference" ); #endif #if DEBUG #if DEBUG_INSTRUMENTATION protected static string BuildFlavor = "Instrumentation"; #else protected static string BuildFlavor = "Debug"; #endif #else protected static string BuildFlavor = "Release"; #endif // // State // protected List m_searchOrder; protected string m_baseFile; protected IR.CompilationSteps.DelegationCache m_delegationCache; protected MetaDataResolver m_resolver; protected TypeSystemForUnitTest m_typeSystem; protected IR.CompilationSteps.Controller m_controller; protected IMetaDataResolverHelper m_metaDataResolverHelper; protected ISymbolResolverHelper m_symbolHelper; private PerformanceCounters.Timing m_timing; // // Constructor Methods // protected BaseTester() { m_timing.Start(); } //--// protected string GetTime() { return string.Format( "{0,13:F6}", (float)PerformanceCounters.Timing.ToMicroSeconds( m_timing.Sample() ) / (1000 * 1000) ); } protected void Initialize() { m_searchOrder = new List(); m_resolver = new Zelig.MetaData.MetaDataResolver( m_metaDataResolverHelper ); AddSearchDirectory( BuildRoot + @"\Target\bin\" + BuildFlavor ); AddSearchDirectory( BuildRoot + @"\Host\bin\" + BuildFlavor ); // // We need this assembly, for all the extra stuff about open classes. // LoadAndResolve( BuildRoot + @"\Host\bin\" + BuildFlavor + @"\Microsoft.Zelig.Runtime.dll" ); } protected void CreateTypeSystem() { m_typeSystem = new TypeSystemForUnitTest( this, this ); m_delegationCache = new IR.CompilationSteps.DelegationCache( m_typeSystem ); m_typeSystem.InitializeForCompilation(); //--// var pa = new Microsoft.Zelig.Configuration.Environment.Abstractions.Architectures.ArmV4( m_typeSystem, null ); m_typeSystem.PlatformAbstraction = pa; uint RamSize = 768 * 1024; uint StartOfRam = 0x00000000; uint EndOfRam = StartOfRam + RamSize; #if USE_IMOTE_PLATFORM uint SDRAMSize = 32 * 1024 * 1024; uint StartOfSDRAM = 0xA0000000; uint EndOfSDRAM = StartOfSDRAM + SDRAMSize; uint StartOfFlash = 0x02000000; uint FlashSize = 32 * 1024 * 1024; #else uint StartOfFlash = 0x90000000; uint FlashSize = 8 * 1024 * 1024; #endif uint EndOfFlash = StartOfFlash + FlashSize; uint FlashEntryPoint = StartOfFlash; UIntPtr ptrRamStart = new UIntPtr( StartOfRam ); UIntPtr ptrRamEnd = new UIntPtr( EndOfRam ); #if USE_IMOTE_PLATFORM UIntPtr ptrSDRAMStart = new UIntPtr( StartOfSDRAM ); UIntPtr ptrSDRAMEnd = new UIntPtr( EndOfSDRAM ); #endif UIntPtr ptrFlashStart = new UIntPtr( StartOfFlash ); UIntPtr ptrFlashEnd = new UIntPtr( EndOfFlash ); UIntPtr ptrFlashEntryPoint = new UIntPtr( FlashEntryPoint ); RT.MemoryUsage codeDataRO = RT.MemoryUsage.Code | RT.MemoryUsage.DataRO | RT.MemoryUsage.Bootstrap; RT.MemoryUsage anything = RT.MemoryUsage.Code | RT.MemoryUsage.DataRO | RT.MemoryUsage.DataRW | RT.MemoryUsage.VectorsTable; pa.AddMemoryBlock( new RT.Memory.Range( ptrRamStart , ptrRamEnd , null, RT.MemoryAttributes.RAM , anything , null ) ); pa.AddMemoryBlock( new RT.Memory.Range( ptrFlashEntryPoint, ptrFlashEnd, null, RT.MemoryAttributes.FLASH | RT.MemoryAttributes.ConfiguredAtEntryPoint, codeDataRO | RT.MemoryUsage.Relocation, null ) ); #if USE_IMOTE_PLATFORM pa.AddMemoryBlock( new RT.Memory.Range( ptrSDRAMStart , ptrSDRAMEnd, null, RT.MemoryAttributes.RAM , anything , null ) ); #endif //--// var cc = new Microsoft.Zelig.Configuration.Environment.Abstractions.ArmCallingConvention( m_typeSystem ); m_typeSystem.CallingConvention = cc; } protected void AddSearchDirectory( string dir ) { dir = Expand( dir ); if(m_searchOrder.Contains( dir ) == false) { m_searchOrder.Add( dir ); } } protected void ConvertAllTypes() { foreach(Normalized.MetaDataAssembly asml in m_resolver.NormalizedAssemblies) { m_typeSystem.ImportAssembly( asml ); } } protected void ResolveAll() { m_typeSystem.ResolveAll(); } protected void ExecuteSteps() { m_controller = new IR.CompilationSteps.Controller( m_typeSystem ); m_controller.ExecuteSteps(); } protected void ConvertToIR() { Console.WriteLine( "{0}: ConvertToIR", GetTime() ); CreateTypeSystem(); ConvertAllTypes(); Console.WriteLine( "{0}: Done", GetTime() ); Console.WriteLine( "{0}: ResolveAll", GetTime() ); ResolveAll(); Console.WriteLine( "{0}: Done", GetTime() ); } protected virtual void NotifyCompilationPhase( IR.CompilationSteps.PhaseDriver phase ) { } //--// object TS.IEnvironmentProvider.GetService( Type t ) { if(t == typeof(Normalized.IMetaDataBootstrap)) { return m_resolver; } if(t == typeof(IR.CompilationSteps.DelegationCache)) { return m_delegationCache; } return null; } //--// protected static string Expand( string file ) { return Environment.ExpandEnvironmentVariables( file ); } protected void LoadAndResolve( string file ) { if(m_baseFile == null) { m_baseFile = file; m_searchOrder.Insert( 0, System.IO.Path.GetDirectoryName( file ) ); } Importer.MetaData md = LoadAssembly( file ); m_resolver.Add( md ); m_resolver.ResolveAll(); } private Importer.MetaData LoadAssembly( string file ) { byte[] image = System.IO.File.ReadAllBytes( file ); Importer.PELoader pe = new Importer.PELoader( file, image ); Importer.MetaData md = Importer.MetaData.loadMetaData( file, m_symbolHelper, pe, Importer.MetaDataLoaderFlags.LoadCode | Importer.MetaDataLoaderFlags.LoadDebugInfo ); return md; } //--// protected Importer.PdbInfo.PdbFile InnerResolveAssemblySymbols( string file ) { try { file = System.IO.Path.GetDirectoryName( file ) + @"\" + System.IO.Path.GetFileNameWithoutExtension( file ) + ".pdb"; if(System.IO.File.Exists( file )) { byte[] image = System.IO.File.ReadAllBytes( file ); Importer.PdbInfo.PdbFile pdbFile = new Importer.PdbInfo.PdbFile( new Importer.ArrayReader( image ) ); return pdbFile; } } catch { } return null; } protected Importer.MetaData InnerResolveAssemblyReference( string name , MetaDataVersion ver ) { Importer.MetaData md; foreach(string dir in m_searchOrder) { md = CheckAndLoad( dir, name, ver ); if(md != null) { return md; } } return null; } //--// protected Importer.MetaData CheckAndLoad( string dir , string name ) { string file = dir + @"\" + name + ".dll"; if(System.IO.File.Exists( file )) { try { return LoadAssembly( file ); } catch { } } return null; } protected Importer.MetaData CheckAndLoad( string dir , string name , MetaDataVersion ver ) { Importer.MetaData md = CheckAndLoad( dir, name ); if(md != null) { if(md.Assembly.Name == name && md.Assembly.Version.IsCompatible( ver, false )) { return md; } } return null; } //--//--// protected void SaveIrToDisk( string file , IR.TypeSystemForCodeTransformation typeSystem ) { using(System.IO.FileStream stream = new System.IO.FileStream( file, FileMode.Create )) { IR.TypeSystemSerializer.Serialize( stream, typeSystem ); } } protected IR.TypeSystemForCodeTransformation LoadIrFromDisk( string file , IR.TypeSystemSerializer.CreateInstance callback ) { using(System.IO.FileStream stream = new System.IO.FileStream( file, FileMode.Open )) { return IR.TypeSystemSerializer.Deserialize( stream, callback, null, 0 ); } } //--// protected void DumpIRAsText( string file ) { using(IR.TextIntermediateRepresentationDumper ird = new IR.TextIntermediateRepresentationDumper( file )) { foreach(TS.TypeRepresentation td in m_typeSystem.Types) { #if !DUMP_SINGLE_METHOD ird.WriteLine( "###############################################################################" ); ird.WriteLine(); ird.WriteLine( "Type: {0} [Size={1}]", td, td.ValidLayout ? td.Size : uint.MaxValue ); if(td.Extends != null) { ird.WriteLine( " Extends: {0}", td.Extends ); } foreach(TS.TypeRepresentation itf in td.Interfaces) { ird.WriteLine( " Interface: {0}", itf ); } foreach(TS.FieldRepresentation fd in td.Fields) { ird.WriteLine( " Field: {0} [Offset={1}]", fd, fd.ValidLayout ? fd.Offset : -1 ); } ird.WriteLine(); #endif foreach(TS.MethodRepresentation md in td.Methods) { IR.ControlFlowGraphState cfg = IR.TypeSystemForCodeTransformation.GetCodeForMethod( md ); if(cfg != null) { #if DUMP_SINGLE_METHOD //if(cfg.Method.ToString() != "") { continue; } #endif ird.WriteLine( " Method {0}", md ); ird.WriteLine( ); cfg.Dump( ird ); } #if !DUMP_SINGLE_METHOD else { ird.WriteLine( " NoCodeMethod {0}", md ); } ird.WriteLine(); #endif } } } } protected void DumpIRAsText( string file , IEnumerable< TS.MethodRepresentation > enumerable ) { using(IR.TextIntermediateRepresentationDumper ird = new IR.TextIntermediateRepresentationDumper( file )) { foreach(TS.MethodRepresentation md in ird.Sort( enumerable )) { IR.ControlFlowGraphState cfg = IR.TypeSystemForCodeTransformation.GetCodeForMethod( md ); if(cfg != null) { ird.WriteLine( "Method {0}", md ); ird.WriteLine( ); cfg.Dump( ird ); } else { ird.WriteLine( "NoCodeMethod {0}", md ); } ird.WriteLine(); } } } protected void DumpIRAsXML( string file , IEnumerable< TS.MethodRepresentation > enumerable ) { System.Xml.XmlDocument doc = new System.Xml.XmlDocument(); System.Xml.XmlNode node = XmlHelper.AddElement( doc, "Methods" ); IR.XmlIntermediateRepresentationDumper ird = new IR.XmlIntermediateRepresentationDumper( doc, node ); foreach(TS.MethodRepresentation md in ird.Sort( enumerable )) { IR.ControlFlowGraphState cfg = IR.TypeSystemForCodeTransformation.GetCodeForMethod( md ); if(cfg != null) { cfg.Dump( ird ); } } doc.Save( file ); } } } ================================================ FILE: Zelig/Zelig/CompileTime/CodeGenerator/CodeGenerator.UnitTest/Bench.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // namespace Microsoft.Zelig.CodeGeneration.UnitTest { using System; using System.Collections.Generic; using System.Text; using Microsoft.Zelig.MetaData; class Bench { public static void Main( string[] args ) { if(args != null) { foreach(string arg in args) { switch(arg) { case "TypeSystemPopulationTester": TypeSystemPopulationTester.Run( args ); break; case "GenericInstantiationClosureTester": GenericInstantiationClosureTester.Run( args ); break; case "CodeGenerationTester": CodeGenerationTester.Run( args ); break; case "SerializationSpeedTester": SerializationSpeedTester.Run( args ); break; } } } } } } ================================================ FILE: Zelig/Zelig/CompileTime/CodeGenerator/CodeGenerator.UnitTest/CodeGenerationTester.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // //#define DEBUG_DUMP_ALL_PHASES_AFTER_TYPE_SYSTEM_REDUCTION //#define DEBUG_DUMP_ALL_PHASES #define DEBUG_DUMP_XML //#define REPORT_OPERATORS_AT_EACH_PHASE //#define CLONE_STATE //#define USE_IMOTE_PLATFORM namespace Microsoft.Zelig.CodeGeneration.UnitTest { using System; using System.Collections.Generic; using System.Text; using System.IO; using Microsoft.Zelig.MetaData; using Importer = Microsoft.Zelig.MetaData.Importer; using Normalized = Microsoft.Zelig.MetaData.Normalized; using IR = Microsoft.Zelig.CodeGeneration.IR; using TS = Microsoft.Zelig.Runtime.TypeSystem; using ARM = Microsoft.Zelig.Emulation.ArmProcessor; class CodeGenerationTester : BaseTester, Microsoft.Zelig.MetaData.IMetaDataResolverHelper, Microsoft.Zelig.MetaData.ISymbolResolverHelper { // // State // private string m_filePrefix; private bool m_fDumpIRToFile; private int m_dumpCount; // // Constructor Methods // private CodeGenerationTester() { m_symbolHelper = this; m_metaDataResolverHelper = this; Initialize(); } public static void Run( string[] args ) { string[] files = { #if USE_IMOTE_PLATFORM BuildRoot + @"\Target\bin\" + BuildFlavor + @"\Microsoft.iMote2.dll", BuildRoot + @"\Target\bin\" + BuildFlavor + @"\Microsoft.DeviceModels.ModelForPXA27x.dll", BuildRoot + @"\Target\bin\" + BuildFlavor + @"\QuickTest.exe", #else BuildRoot + @"\Target\bin\" + BuildFlavor + @"\mscorlib_unittest.exe", BuildRoot + @"\Target\bin\" + BuildFlavor + @"\Microsoft.VoxSoloFormFactor.dll", #endif }; CodeGenerationTester pThis = new CodeGenerationTester(); pThis.Run( files, true, true ); Console.WriteLine( "Execution time: {0}", pThis.GetTime() ); } private void Run( string[] files , bool fDumpIRToFile , bool fSerialize ) { string root = Expand( @"%DEPOTROOT%\ZeligUnitTestResults\" ); string file2 = Path.GetFileNameWithoutExtension( files[0] ); string filePrefix = root + file2; m_filePrefix = filePrefix; m_fDumpIRToFile = fDumpIRToFile; foreach(string file in files) { LoadAndResolve( file ); } ConvertToIR(); #if CLONE_STATE Console.WriteLine( "{0}: Cloning State", GetTime() ); byte[] buf; using(RedirectOutput ro = new RedirectOutput( filePrefix + ".serializer.txt" )) { buf = IR.TypeSystemSerializer.Serialize( m_typeSystem ); } TypeSystemForUnitTest typeSystem2; using(RedirectOutput ro = new RedirectOutput( filePrefix + ".deserializer.txt" )) { typeSystem2 = (TypeSystemForUnitTest)IR.TypeSystemSerializer.Deserialize( new System.IO.MemoryStream( buf ), CreateInstanceForType ); } TypeSystemForUnitTest typeSystem3 = m_typeSystem; m_typeSystem = typeSystem2; Console.WriteLine( "{0}: Done", GetTime() ); #endif Console.WriteLine( "{0}: ExecuteSteps", GetTime() ); ExecuteSteps(); Console.WriteLine( "{0}: Done", GetTime() ); //--// if(fSerialize) { Console.WriteLine( "{0}: Type System Serialization Test...", GetTime() ); System.IO.MemoryStream stream = new System.IO.MemoryStream(); using(RedirectOutput ro = new RedirectOutput( filePrefix + ".serializer.txt" )) { IR.TypeSystemSerializer.Serialize( stream, m_typeSystem ); } stream.Seek( 0, SeekOrigin.Begin ); TypeSystemForUnitTest deserializedTypeSystem; using(RedirectOutput ro = new RedirectOutput( filePrefix + ".deserializer.txt" )) { deserializedTypeSystem = (TypeSystemForUnitTest)IR.TypeSystemSerializer.Deserialize( stream, CreateInstanceForType, null, 0 ); } System.IO.MemoryStream stream2 = new System.IO.MemoryStream(); using(RedirectOutput ro = new RedirectOutput( filePrefix + ".reserializer.txt" )) { IR.TypeSystemSerializer.Serialize( stream2, deserializedTypeSystem ); } if(ArrayUtility.ArrayEquals( stream.ToArray(), stream2.ToArray() )) { Console.WriteLine( "{0}: Type System Serialization PASS", GetTime() ); } else { Console.WriteLine( "{0}: Type System Serialization FAIL", GetTime() ); } } } //--// Importer.PdbInfo.PdbFile ISymbolResolverHelper.ResolveAssemblySymbols( string file ) { return InnerResolveAssemblySymbols( file ); } Importer.MetaData IMetaDataResolverHelper.ResolveAssemblyReference( string name , MetaDataVersion ver ) { // // Force use of our version of mscorlib. // if(name == "mscorlib" || name == "system") { return CheckAndLoad( BuildRoot + @"\Target\bin\" + BuildFlavor, name ); } return InnerResolveAssemblyReference( name, ver ); } //--// private object CreateInstanceForType( Type t ) { if(t == typeof(IR.TypeSystemForCodeTransformation)) { return new TypeSystemForUnitTest( this, null ); } return null; } private void DumpPerformanceCounters( string filePrefix ) { if(PerformanceCounters.ContextualTiming.IsEnabled()) { Console.WriteLine( "{0}: Dumping Performance Counters", GetTime() ); using(System.IO.StreamWriter output = new System.IO.StreamWriter( filePrefix + "_timing.type.txt", false, System.Text.Encoding.ASCII )) { PerformanceCounters.ContextualTiming.DumpAllByType( output ); } using(System.IO.StreamWriter output = new System.IO.StreamWriter( filePrefix + "_timing.reason.txt", false, System.Text.Encoding.ASCII )) { PerformanceCounters.ContextualTiming.DumpAllByReason( output ); } Console.WriteLine( "{0}: Done", GetTime() ); } } //--// protected override void NotifyCompilationPhase( IR.CompilationSteps.PhaseDriver phase ) { if(!m_fDumpIRToFile) return; bool fDumpIR = false; bool fDumpTXT = false; #if DEBUG_DUMP_XML bool fDumpXML = true; #else bool fDumpXML = false; #endif bool fDumpOps = false; bool fDumpASM = false; bool fDumpIMG = false; ++m_dumpCount; Console.WriteLine( "{0}: Phase: {1}", GetTime(), phase ); #if REPORT_OPERATORS_AT_EACH_PHASE fDumpOps = true; #endif //// if(phase >= IR.CompilationSteps.Phase.ConvertToSSA) //// { //// fDumpTXT = true; //// } if(phase is IR.CompilationSteps.Phases.GenerateImage) { DumpPerformanceCounters( m_filePrefix ); fDumpTXT = true; } else if(phase is IR.CompilationSteps.Phases.Done) { fDumpIMG = true; fDumpASM = true; fDumpTXT = true; fDumpIR = true; m_typeSystem.DropCompileTimeObjects(); // Get the smallest dump. } //--// #if DEBUG_DUMP_ALL_PHASES fDumpTXT = true; #endif #if DEBUG_DUMP_ALL_PHASES_AFTER_TYPE_SYSTEM_REDUCTION if(IR.CompilationSteps.PhaseDriver.CompareOrder( phase, typeof(IR.CompilationSteps.Phases.ReduceTypeSystem) ) > 0) { fDumpTXT = true; } #endif //--// //// if(phase is IR.CompilationSteps.Phases.LayoutTypes) //// { //// fDumpOps = true; //// } //// else if(phase is IR.CompilationSteps.Phases.GenerateImage || //// phase is IR.CompilationSteps.Phases.Done ) //// { //// fDumpOps = true; //// } if(fDumpOps) { ReportOperators( phase ); } if(fDumpIR || fDumpTXT || fDumpXML) { string file = string.Format( "{0}.{1:X2}.{2}.{3}.", m_filePrefix, m_dumpCount, phase.PhaseIndex, phase ); Console.WriteLine( "{0}: Dump {1}", GetTime(), file ); if(fDumpIR ) SaveIrToDisk( file + "ZeligImage", m_typeSystem ); if(fDumpTXT) DumpIRAsText( file + "ZeligIR" ); if(fDumpXML) DumpIRAsXML ( file + "xml" , GetAllMethods() ); if(fDumpASM) { m_typeSystem.DisassembleImage( file + "asmdir" ); } if(fDumpIMG) { using(FileStream stream = new FileStream( file + "hex", FileMode.Create )) { foreach(var section in m_typeSystem.Image) { ARM.SRecordParser.Encode( stream, section.Payload, section.Address ); } } } Console.WriteLine( "{0}: Done", GetTime() ); } } private void ReportOperators( IR.CompilationSteps.PhaseDriver phase ) { GrowOnlySet< Type > types = SetFactory.NewWithReferenceEquality< Type >(); m_typeSystem.EnumerateFlowGraphs( delegate( IR.ControlFlowGraphStateForCodeTransformation cfg ) { foreach(IR.Operator op in cfg.DataFlow_SpanningTree_Operators) { types.Insert( op.GetType() ); } } ); Console.WriteLine( "Operators at phase {0}", phase ); foreach(Type t in types) { Console.WriteLine( " {0}", t.Name ); } } //--// private List< TS.MethodRepresentation > GetAllMethods() { List< TS.MethodRepresentation > lst = new List< TS.MethodRepresentation >(); m_typeSystem.EnumerateMethods( delegate( TS.MethodRepresentation md ) { lst.Add( md ); } ); return lst; } private List< TS.MethodRepresentation > GetAllReferencedMethods() { List< TS.MethodRepresentation > lst = new List< TS.MethodRepresentation >(); foreach(TS.MethodRepresentation md in m_controller.EntitiesReferencedByMethods.Keys) { lst.Add( md ); } return lst; } } } ================================================ FILE: Zelig/Zelig/CompileTime/CodeGenerator/CodeGenerator.UnitTest/CodeGenerator.UnitTest.csproj ================================================  Debug AnyCPU 9.0.21022 2.0 {186F31A3-EF89-4A25-B2D5-20060606AA01} Exe Properties Microsoft.Zelig.CodeGeneration.UnitTest Microsoft.Zelig.CodeGeneration.UnitTest $(LlilumBuildRoot)\Host\obj\$(MSBuildProjectName)\ v4.5 true full false $(LlilumBuildRoot)\Host\bin\$(Configuration)\ DEBUG;TRACE prompt 4 false true AllRules.ruleset AnyCPU false pdbonly true $(LlilumBuildRoot)\Host\bin\$(Configuration)\ TRACE prompt 4 false true AllRules.ruleset AnyCPU false $(LlilumBuildRoot)\Host\bin\$(Configuration)\ TRACE;DEBUG;DEBUG_DUMP_ALL_PHASES;REPORT_OPERATORS_AT_EACH_PHASE;DEBUG_DUMP_XML;DEBUG_INSTRUMENTATION true AnyCPU false 3.5 {186F31A3-EF89-4A25-B2D5-20060704AA01} ArmProcessorEmulation False {186F31A3-EF89-4A25-B2D5-20070601AA01} CommonPC False {186F31A3-EF89-4A25-B2D5-20060509AA01} Kernel False {186F31A3-EF89-4A25-B2D5-20060404AA01} Importer False {186F31A3-EF89-4A25-B2D5-20060510AA01} Normalized False {186F31A3-EF89-4A25-B2D5-20061218AA01} Common False {186F31A3-EF89-4A25-B2D5-20060720AA01} TypeSystem False {186F31A3-EF89-4A25-B2D5-20070606AA01} ProductConfiguration False {186F31A3-EF89-4A25-B2D5-20070222AA01} CodeTransformation False {186F31A3-EF89-4A25-B2D5-20060603AA01} IntermediateRepresentation False ================================================ FILE: Zelig/Zelig/CompileTime/CodeGenerator/CodeGenerator.UnitTest/GenericInstantiationClosureTester.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // namespace Microsoft.Zelig.CodeGeneration.UnitTest { using System; using System.Collections.Generic; using System.Text; using System.IO; using Microsoft.Zelig.MetaData; using Importer = Microsoft.Zelig.MetaData.Importer; using Normalized = Microsoft.Zelig.MetaData.Normalized; using IR = Microsoft.Zelig.CodeGeneration.IR; using TS = Microsoft.Zelig.Runtime.TypeSystem; class GenericInstantiationClosureTester : BaseTester, Microsoft.Zelig.MetaData.IMetaDataResolverHelper { // // Constructor Methods // private GenericInstantiationClosureTester() { m_metaDataResolverHelper = this; Initialize(); //AddSearchDirectory( @"%WINDIR%\Microsoft.NET\Framework\v1.1.4322" ); //AddSearchDirectory( @"%WINDIR%\Microsoft.NET\Framework\v2.0.50727" ); } public static void Run( string[] args ) { Run( @"%DEPOTROOT%\Zelig\Test\GenericInstantiationClosure\Pass\Pass.exe" , true ); Run( @"%DEPOTROOT%\Zelig\Test\GenericInstantiationClosure\Fail_Field\Fail_Field.exe" , false ); Run( @"%DEPOTROOT%\Zelig\Test\GenericInstantiationClosure\Fail_GenericMethod1\Fail_GenericMethod1.exe", false ); Run( @"%DEPOTROOT%\Zelig\Test\GenericInstantiationClosure\Fail_GenericMethod2\Fail_GenericMethod2.exe", false ); Run( @"%DEPOTROOT%\Zelig\Test\GenericInstantiationClosure\Fail_Inheritance\Fail_Inheritance.exe" , false ); Run( @"%DEPOTROOT%\Zelig\Test\GenericInstantiationClosure\Fail_Method\Fail_Method.exe" , false ); } private static void Run( string file , bool fShouldPass ) { Exception result = null; try { GenericInstantiationClosureTester pThis; pThis = new GenericInstantiationClosureTester(); pThis.LoadAndResolve( Expand( file ) ); pThis.ConvertToIR(); } catch(Exception e) { result = e; } if((result == null) == fShouldPass) { Console.WriteLine( "Passed test for '{0}'", file ); } else { Console.WriteLine( "Failed test for '{0}'", file ); Console.WriteLine( " {0}" , result ); } } //--// Importer.MetaData IMetaDataResolverHelper.ResolveAssemblyReference( string name , MetaDataVersion ver ) { return InnerResolveAssemblyReference( name, ver ); } } } ================================================ FILE: Zelig/Zelig/CompileTime/CodeGenerator/CodeGenerator.UnitTest/Properties/AssemblyInfo.cs ================================================ using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; // General Information about an assembly is controlled through the following // set of attributes. Change these attribute values to modify the information // associated with an assembly. [assembly: AssemblyTitle( "Microsoft.Zelig.CodeGeneration.UnitTest" )] [assembly: AssemblyDescription( "" )] [assembly: AssemblyConfiguration( "" )] [assembly: AssemblyCompany( "Microsoft" )] [assembly: AssemblyProduct( "Microsoft.Zelig.CodeGeneration.UnitTest" )] [assembly: AssemblyCopyright( "Copyright © Microsoft 2006" )] [assembly: AssemblyTrademark( "" )] [assembly: AssemblyCulture( "" )] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible( false )] //// The following GUID is for the ID of the typelib if this project is exposed to COM //[assembly: Guid( "012e8fb6-008e-45a0-ba5d-64b07a84aa95" )] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Revision and Build Numbers // by using the '*' as shown below: [assembly: AssemblyVersion( "1.0.0.0" )] [assembly: AssemblyFileVersion( "1.0.0.0" )] ================================================ FILE: Zelig/Zelig/CompileTime/CodeGenerator/CodeGenerator.UnitTest/SerializationSpeedTester.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // namespace Microsoft.Zelig.CodeGeneration.UnitTest { using System; using System.Collections.Generic; using IR = Microsoft.Zelig.CodeGeneration.IR; using RT = Microsoft.Zelig.Runtime; using TS = Microsoft.Zelig.Runtime.TypeSystem; class SerializationSpeedTester { private class TypeSystemForExecution : IR.TypeSystemForCodeTransformation { internal TypeSystemForExecution() : base( null ) { } } public static void Run( string[] args ) { //// string file = @"S:\enlistments\VOX\main\ZeligUnitTestResults\Microsoft.NohauLPC3180Loader.ZeligImage"; //// string file = @"S:\enlistments\VOX\main\ZeligUnitTestResults\mscorlib_UnitTest_FF.ZeligImage"; string file = @"S:\enlistments\VOX\main\ZeligUnitTestResults\soloTest_NXP.ZeligImage"; IR.TypeSystemForCodeTransformation ts; System.Diagnostics.Stopwatch st = new System.Diagnostics.Stopwatch(); st.Start(); using(System.IO.Stream serializedStream = new System.IO.FileStream( file, System.IO.FileMode.Open )) { IR.TypeSystemSerializer.CreateInstance dlgCreateInstance = delegate( Type t ) { if(t == typeof(IR.TypeSystemForCodeTransformation)) { return new TypeSystemForExecution(); } return null; }; IR.TypeSystemSerializer.ProgressCallback dlgProgress = delegate( long pos, long total ) { }; ts = (IR.TypeSystemForCodeTransformation)IR.TypeSystemSerializer.Deserialize( serializedStream, dlgCreateInstance, dlgProgress, 10000 ); } st.Stop(); long val1 = st.ElapsedMilliseconds; st.Reset(); } } } ================================================ FILE: Zelig/Zelig/CompileTime/CodeGenerator/CodeGenerator.UnitTest/TypeSystemPopulationTester.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // namespace Microsoft.Zelig.CodeGeneration.UnitTest { using System; using System.Collections.Generic; using System.Text; using System.IO; using Microsoft.Zelig.MetaData; using Importer = Microsoft.Zelig.MetaData.Importer; using Normalized = Microsoft.Zelig.MetaData.Normalized; using IR = Microsoft.Zelig.CodeGeneration.IR; using TS = Microsoft.Zelig.Runtime.TypeSystem; using ARM = Microsoft.Zelig.Emulation.ArmProcessor; class TypeSystemPopulationTester : BaseTester, Microsoft.Zelig.MetaData.IMetaDataResolverHelper, Microsoft.Zelig.MetaData.ISymbolResolverHelper { // // Constructor Methods // private TypeSystemPopulationTester() { m_symbolHelper = this; m_metaDataResolverHelper = this; Initialize(); //AddSearchDirectory( @"%WINDIR%\Microsoft.NET\Framework\v1.1.4322" ); //AddSearchDirectory( @"%WINDIR%\Microsoft.NET\Framework\v2.0.50727" ); } public static void Run( string[] args ) { DateTime start = DateTime.Now; Run( BuildRoot + @"\Target\bin\" + BuildFlavor + @"\mscorlib_unittest.exe" , true ); //Run( BuildRoot + @"\Host\bin\" + BuildFlavor + @"\Microsoft.Zelig.MetaData.UnitTest.exe", false ); //Run( BuildRoot + @"\Host\bin\" + BuildFlavor + @"\Microsoft.Zelig.MetaData.UnitTest.exe", false ); DateTime stop = DateTime.Now; Console.WriteLine( "Execution time: {0}", (stop - start) ); } private static void Run( string file , bool fDumpTypeSystem ) { TypeSystemPopulationTester pThis; pThis = new TypeSystemPopulationTester(); pThis.LoadAndResolve( file ); pThis.ConvertToIR(); string root = Expand( @"%DEPOTROOT%\ZeligUnitTestResults\" ); string file2 = Path.GetFileNameWithoutExtension( file ); string filePrefix = root + file2; if(fDumpTypeSystem) { using(System.IO.TextWriter writer = new System.IO.StreamWriter( filePrefix + ".TypeSystemDump.IrTxt", false, System.Text.Encoding.ASCII )) { foreach(TS.TypeRepresentation td in pThis.m_typeSystem.Types) { writer.WriteLine( "Type: {0}", td ); foreach(TS.TypeRepresentation itf in td.Interfaces) { writer.WriteLine( " Interface: {0}", itf ); } foreach(TS.FieldRepresentation fd in td.Fields) { writer.WriteLine( " Field: {0}", fd ); } foreach(TS.MethodRepresentation md in td.Methods) { writer.WriteLine( " Method: {0}", md ); } writer.WriteLine(); } } } //--// System.IO.MemoryStream msSerialized = new System.IO.MemoryStream(); using(RedirectOutput ro = new RedirectOutput( filePrefix + ".serializer.txt" )) { IR.TypeSystemSerializer.Serialize( msSerialized, pThis.m_typeSystem ); } System.IO.MemoryStream ms = new System.IO.MemoryStream(); System.IO.Compression.GZipStream gzip = new System.IO.Compression.GZipStream( ms, System.IO.Compression.CompressionMode.Compress ); byte[] buf = msSerialized.ToArray(); gzip.Write( buf, 0, buf.Length ); gzip.Flush(); byte[] bufCompressed = ms.ToArray(); TypeSystemForUnitTest typeSystem2; using(RedirectOutput ro = new RedirectOutput( filePrefix + ".deserializer.txt" )) { typeSystem2 = (TypeSystemForUnitTest)IR.TypeSystemSerializer.Deserialize( new System.IO.MemoryStream( buf ), pThis.CreateInstanceForType, null, 0 ); } System.IO.MemoryStream msSerialized2 = new System.IO.MemoryStream(); using(RedirectOutput ro = new RedirectOutput( filePrefix + ".reserializer.txt" )) { IR.TypeSystemSerializer.Serialize( msSerialized2, typeSystem2 ); } byte[] buf2 = msSerialized2.ToArray(); if(ArrayUtility.ArrayEquals( buf, buf2 )) { Console.WriteLine( "{0}: Type System Serialization PASS" , DateTime.Now ); Console.WriteLine( "{0}: Serialized size = {1}, compressed size = {2}", DateTime.Now, buf.Length, bufCompressed.Length ); } else { Console.WriteLine( "{0}: Type System Serialization FAIL", DateTime.Now ); } } private object CreateInstanceForType( Type t ) { if(t == typeof(IR.TypeSystemForCodeTransformation)) { return new TypeSystemForUnitTest( this, null ); } return null; } //--// Importer.PdbInfo.PdbFile ISymbolResolverHelper.ResolveAssemblySymbols( string file ) { return InnerResolveAssemblySymbols( file ); } Importer.MetaData IMetaDataResolverHelper.ResolveAssemblyReference( string name , MetaDataVersion ver ) { return InnerResolveAssemblyReference( name, ver ); } } } ================================================ FILE: Zelig/Zelig/CompileTime/CodeGenerator/CodeGenerator.UnitTest/app.config ================================================ ================================================ FILE: Zelig/Zelig/CompileTime/CodeGenerator/CodeTransformation/Abstractions/CallingConvention.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // namespace Microsoft.Zelig.CodeGeneration.IR.Abstractions { using System; using System.Collections.Generic; using Microsoft.Zelig.MetaData; using Microsoft.Zelig.MetaData.Normalized; using Microsoft.Zelig.Runtime.TypeSystem; public abstract class CallingConvention : ITransformationContextTarget { public enum Direction { Caller, Callee, } public abstract class CallState : ITransformationContextTarget { // // State // private Direction m_direction; // // Constructor Methods // protected CallState() // Default constructor required by TypeSystemSerializer. { } protected CallState( Direction direction ) { m_direction = direction; } // // Helper Methods // public abstract RegisterDescriptor GetNextRegister( Platform platform , TypeRepresentation sourceTd , TypeRepresentation fragmentTd , ControlFlowGraphStateForCodeTransformation.KindOfFragment kind ); public abstract int GetNextIndex( Platform platform , TypeRepresentation sourceTd , TypeRepresentation fragmentTd , ControlFlowGraphStateForCodeTransformation.KindOfFragment kind ); public abstract bool CanMapToRegister( Platform platform , TypeRepresentation td ); public abstract bool CanMapResultToRegister( Platform platform , TypeRepresentation td ); public virtual void ApplyTransformation( TransformationContext context ) { TransformationContextForCodeTransformation context2 = (TransformationContextForCodeTransformation)context; context2.Push( this ); context2.Transform( ref m_direction ); context2.Pop(); } // // Access Methods // public Direction Direction { get { return m_direction; } } } // // State // protected TypeSystemForCodeTransformation m_typeSystem; // // Constructor Methods // protected CallingConvention() // Default constructor required by TypeSystemSerializer. { } protected CallingConvention( TypeSystemForCodeTransformation typeSystem ) { m_typeSystem = typeSystem; } // // Helper Methods // public virtual void ApplyTransformation( TransformationContext context ) { TransformationContextForCodeTransformation context2 = (TransformationContextForCodeTransformation)context; context2.Push( this ); context2.Transform( ref m_typeSystem ); context2.Pop(); } //--// public abstract void RegisterForNotifications( TypeSystemForCodeTransformation ts , CompilationSteps.DelegationCache cache ); public virtual void ExpandCallsClosure( CompilationSteps.ComputeCallsClosure computeCallsClosure ) { } //--// public Expression[] AssignArgument( ControlFlowGraphStateForCodeTransformation cfg , Operator insertionOp , Expression ex , Abstractions.CallingConvention.CallState callState ) { return AssignArgument( cfg, insertionOp, ex, ex.Type, callState ); } public Expression[] AssignReturnValue( ControlFlowGraphStateForCodeTransformation cfg , Operator insertionOp , VariableExpression exReturnValue , Abstractions.CallingConvention.CallState callState ) { if(exReturnValue != null) { return AssignReturnValue( cfg, insertionOp, exReturnValue, exReturnValue.Type, callState ); } else { return null; } } //--// public abstract CallState CreateCallState( Direction direction ); public abstract Expression[] AssignArgument( ControlFlowGraphStateForCodeTransformation cfg , Operator insertionOp , Expression ex , TypeRepresentation td , Abstractions.CallingConvention.CallState callState ); public abstract Expression[] AssignReturnValue( ControlFlowGraphStateForCodeTransformation cfg , Operator insertionOp , VariableExpression exReturnValue , TypeRepresentation tdReturnValue , Abstractions.CallingConvention.CallState callState ); public abstract VariableExpression[] CollectExpressionsToInvalidate( ControlFlowGraphStateForCodeTransformation cfg , CallOperator op , Expression[] resFragments ); public abstract bool ShouldSaveRegister( RegisterDescriptor regDesc ); //--// protected static VariableExpression[] MergeFragments( VariableExpression[] exDstArray , Expression[] exSrcArray ) { if(exSrcArray != null) { foreach(Expression exSrc in exSrcArray) { VariableExpression var = exSrc as VariableExpression; if(var != null) { exDstArray = AddUniqueToFragment( exDstArray, var ); } } } return exDstArray; } protected static VariableExpression[] AddUniqueToFragment( VariableExpression[] array , VariableExpression var ) { for(int i = array.Length; --i >= 0; ) { if(array[i].IsTheSamePhysicalEntity( var )) { return array; } } return ArrayUtility.AppendToNotNullArray( array, var ); } protected static VariableExpression[] CollectAddressTakenExpressionsToInvalidate( ControlFlowGraphStateForCodeTransformation cfg , VariableExpression[] res , Operator context ) { VariableExpression[] variables = cfg.DataFlow_SpanningTree_Variables; VariableExpression.Property[] varProps = cfg.DataFlow_PropertiesOfVariables; for(int varIdx = 0; varIdx < variables.Length; varIdx++) { if((varProps[varIdx] & VariableExpression.Property.AddressTaken) != 0) { VariableExpression var = variables[varIdx]; Expression[] fragments = cfg.GetFragmentsForExpression( var ); if(fragments != null) { res = MergeFragments( res, fragments ); } else { res = AddUniqueToFragment( res, var ); } } } return res; } } } ================================================ FILE: Zelig/Zelig/CompileTime/CodeGenerator/CodeTransformation/Abstractions/ExternalCallContext.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // namespace Microsoft.Zelig.CodeGeneration.IR.Abstractions { using System; using Microsoft.Zelig.Runtime; using Microsoft.Zelig.CodeGeneration.IR.ExternalMethodImporters; using Microsoft.Zelig.TargetModel.ArmProcessor; public class ExternalCallContext { public static void Initialize(TypeSystemForCodeTransformation typeSystem) { if (typeSystem.PlatformAbstraction.CodeGenerator == InstructionSetVersion.CodeGenerator_Zelig) { ArmElfExternalCallContext.Initialize(typeSystem); } else { throw new ArgumentException("Unknown platform"); } } public static void Reset() { ArmElfExternalCallContext.Reset(); } public static void ResetExternalCalls() { ArmElfExternalCallContext.ResetExternCalls(); } public static ExternalCallOperator.IExternalCallContext[] Create( ImportedMethodReferenceAttribute.InteropFileType fileType, string filePath, string methodName, BasicBlock owner ) { switch(fileType) { case ImportedMethodReferenceAttribute.InteropFileType.ArmELF: return ArmElfExternalCallContext.Load( filePath, methodName, owner ); } throw new NotImplementedException(); } } } ================================================ FILE: Zelig/Zelig/CompileTime/CodeGenerator/CodeTransformation/Abstractions/PlacementRequirements.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // namespace Microsoft.Zelig.CodeGeneration.IR.Abstractions { using System; using System.Collections.Generic; using Microsoft.Zelig.MetaData; using Microsoft.Zelig.MetaData.Normalized; using Microsoft.Zelig.Runtime.TypeSystem; public class PlacementRequirements { // // State // private bool m_fContentsUninitialized; private bool m_fAllocateFromHighAddress; private uint m_alignment; private int m_alignmentOffset; private string[] m_sections; private Runtime.MemoryUsage[] m_usages; private Runtime.MemoryAttributes[] m_memoryKinds; // // Constructor Methods // public PlacementRequirements( uint alignment , int alignmentOffset ) { m_alignment = alignment; m_alignmentOffset = alignmentOffset; } // // Helper Methods // public void ApplyTransformation( TransformationContextForCodeTransformation context ) { context.Push( this ); context.Transform( ref m_fContentsUninitialized ); context.Transform( ref m_fAllocateFromHighAddress ); context.Transform( ref m_alignment ); context.Transform( ref m_alignmentOffset ); context.Transform( ref m_sections ); context.Transform( ref m_usages ); context.Transform( ref m_memoryKinds ); context.Pop(); } public PlacementRequirements Clone() { PlacementRequirements pr = new PlacementRequirements( m_alignment, m_alignmentOffset ); pr.m_sections = m_sections; pr.m_usages = m_usages; pr.m_memoryKinds = m_memoryKinds; return pr; } public void AddConstraint( string section ) { if(section != null) { m_sections = ArrayUtility.AddUniqueToArray( m_sections, section ); } } public void AddConstraint( Runtime.MemoryUsage usage ) { m_usages = ArrayUtility.AppendToArray( m_usages, usage ); } public void AddConstraint( Runtime.MemoryAttributes memoryKind ) { m_memoryKinds = ArrayUtility.AppendToArray( m_memoryKinds, memoryKind ); } //--// public bool IsCompatible( PlacementRequirements pr ) { if(pr != null) { if(Object.ReferenceEquals( this, pr )) { return true; } if( this.m_alignment == pr.m_alignment && this.m_alignmentOffset == pr.m_alignmentOffset && ArrayUtility.SameContents( this.m_sections , pr.m_sections ) && ArrayUtility.SameContents( this.m_usages , pr.m_usages ) && ArrayUtility.SameContents( this.m_memoryKinds , pr.m_memoryKinds ) ) { return true; } } return false; } public bool IsCompatible( string sectionName , Runtime.MemoryAttributes memoryKind , Runtime.MemoryUsage memoryUsage ) { if(m_sections != null) { bool fGot = false; foreach(string name in m_sections) { if(sectionName == name) { fGot = true; break; } } if(fGot == false) { return false; } } if(m_usages != null) { bool fGot = false; foreach(Runtime.MemoryUsage usage in m_usages) { if((memoryUsage & usage) == usage) { fGot = true; break; } } if(fGot == false) { return false; } } if(m_memoryKinds != null) { bool fGot = false; foreach(Runtime.MemoryAttributes kind in m_memoryKinds) { if((memoryKind & kind) == kind) { fGot = true; break; } } if(fGot == false) { return false; } } return true; } // // Access Methods // public uint Alignment { get { return m_alignment; } set { m_alignment = value; } } public int AlignmentOffset { get { return m_alignmentOffset; } set { m_alignmentOffset = value; } } public string[] Sections { get { return m_sections; } } public Runtime.MemoryUsage[] Usages { get { return m_usages; } } public Runtime.MemoryAttributes[] MemoryKinds { get { return m_memoryKinds; } } public bool ContentsUninitialized { get { return m_fContentsUninitialized; } set { m_fContentsUninitialized = value; } } public bool AllocateFromHighAddress { get { return m_fAllocateFromHighAddress; } set { m_fAllocateFromHighAddress = value; } } } } ================================================ FILE: Zelig/Zelig/CompileTime/CodeGenerator/CodeTransformation/Abstractions/Platform.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // namespace Microsoft.Zelig.CodeGeneration.IR.Abstractions { using System; using System.Collections.Generic; using Microsoft.Zelig.MetaData; using Microsoft.Zelig.MetaData.Normalized; using Microsoft.Zelig.Runtime.TypeSystem; using Microsoft.Zelig.TargetModel.ArmProcessor; public abstract class Platform : ITransformationContextTarget, Operator.IOperatorLevelHelper { // // State // protected TypeSystemForCodeTransformation m_typeSystem; // // Constructor Methods // protected Platform() // Default constructor required by TypeSystemSerializer. { } protected Platform( TypeSystemForCodeTransformation typeSystem ) { m_typeSystem = typeSystem; } // // Helper Methods // public virtual void ApplyTransformation( TransformationContext context ) { TransformationContextForCodeTransformation context2 = (TransformationContextForCodeTransformation)context; context2.Push( this ); context2.Transform( ref m_typeSystem ); context2.Pop(); } //--// public abstract void RegisterForNotifications( TypeSystemForCodeTransformation ts , CompilationSteps.DelegationCache cache ); public abstract TypeRepresentation GetRuntimeType( TypeSystemForCodeTransformation ts , Abstractions.RegisterDescriptor regDesc ); public virtual void ExpandCallsClosure( CompilationSteps.ComputeCallsClosure computeCallsClosure ) { foreach(var regDesc in this.GetRegisters()) { computeCallsClosure.Expand( GetRuntimeType( computeCallsClosure.TypeSystem, regDesc ) ); } } //--// public abstract bool CanUseMultipleConditionCodes { get; } public abstract int EstimatedCostOfLoadOperation { get; } public abstract int EstimatedCostOfStoreOperation { get; } public abstract uint MemoryAlignment { get; } public abstract void GetListOfMemoryBlocks( List< Runtime.Memory.Range > list ); public abstract PlacementRequirements GetMemoryRequirements( object obj ); public abstract IR.ImageBuilders.CompilationState CreateCompilationState( IR.ImageBuilders.Core core , ControlFlowGraphStateForCodeTransformation cfg ); //--// public abstract string CodeGenerator { get; } public abstract uint PlatformFamily { get; } public abstract uint PlatformVersion { get; } public abstract uint PlatformVFP { get; } public abstract bool PlatformBigEndian { get; } public abstract InstructionSet GetInstructionSetProvider(); public abstract RegisterDescriptor[] GetRegisters(); public abstract RegisterDescriptor GetRegisterForEncoding( uint regNum ); public abstract RegisterDescriptor GetScratchRegister(); public abstract void ComputeNumberOfFragmentsForExpression( TypeRepresentation sourceTd , ControlFlowGraphStateForCodeTransformation.KindOfFragment kind , out uint sourceFragments , out bool fDirect ); public abstract bool CanFitInRegister( TypeRepresentation td ); //--// public abstract TypeRepresentation GetMethodWrapperType(); public abstract bool HasRegisterContextArgument( MethodRepresentation md ); public abstract void ComputeSetOfRegistersToSave( Abstractions.CallingConvention cc , ControlFlowGraphStateForCodeTransformation cfg , BitVector modifiedRegisters , out BitVector registersToSave , out Runtime.HardwareException he ); //--// bool Operator.IOperatorLevelHelper.FitsInPhysicalRegister( TypeRepresentation td ) { return CanFitTypeInPhysicalRegister( td ); } protected abstract bool CanFitTypeInPhysicalRegister( TypeRepresentation td ); //--// public abstract bool CanPropagateCopy( SingleAssignmentOperator opSrc , Operator opDst , int exIndexInDst , VariableExpression[] variables , BitVector[] variableUses , BitVector[] variableDefinitions , Operator[] operators ); //--// public static void SetConstraintOnResultsBasedOnType( CompilationSteps.PhaseExecution.NotificationContext nc , VariableExpression[] results ) { for(int i = 0; i < results.Length; i++) { SetConstraintOnLhsBasedOnType( nc, results, i ); } } public static void SetConstraintOnLhsBasedOnType( CompilationSteps.PhaseExecution.NotificationContext nc , VariableExpression[] lhs , int varIndex ) { SetConstraintBasedOnType( nc, lhs[varIndex], varIndex, true ); } public static void SetConstraintOnArgumentsBasedOnType( CompilationSteps.PhaseExecution.NotificationContext nc , Expression[] arguments ) { for(int i = 0; i < arguments.Length; i++) { SetConstraintOnRhsBasedOnType( nc, arguments, i ); } } public static void SetConstraintOnRhsBasedOnType( CompilationSteps.PhaseExecution.NotificationContext nc , Expression[] rhs , int varIndex ) { SetConstraintBasedOnType( nc, rhs[varIndex], varIndex, false ); } public static void SetConstraintBasedOnType( CompilationSteps.PhaseExecution.NotificationContext nc , Expression ex , int varIndex , bool fIsResult ) { if(ex != null) { TypeRepresentation td = ex.Type; if(td.IsFloatingPoint) { if(td.SizeOfHoldingVariableInWords == 1) { SetConstraint( nc, varIndex, fIsResult, RegisterClass.SinglePrecision ); } else { SetConstraint( nc, varIndex, fIsResult, RegisterClass.DoublePrecision ); } } else if(td is PointerTypeRepresentation) { SetConstraint( nc, varIndex, fIsResult, RegisterClass.Address ); } else { SetConstraint( nc, varIndex, fIsResult, RegisterClass.Integer ); } } } public static void SetConstraintOnLHS( CompilationSteps.PhaseExecution.NotificationContext nc , int varIndex , RegisterClass constraint ) { SetConstraint( nc, varIndex, true, constraint ); } public static void SetConstraintOnRHS( CompilationSteps.PhaseExecution.NotificationContext nc , int varIndex , RegisterClass constraint ) { SetConstraint( nc, varIndex, false, constraint ); } public static void SetConstraint( CompilationSteps.PhaseExecution.NotificationContext nc , int varIndex , bool fIsResult , RegisterClass constraint ) { nc.CurrentOperator.AddAnnotation( RegisterAllocationConstraintAnnotation.Create( nc.TypeSystem, varIndex, fIsResult, constraint ) ); } //--// public static bool MoveToPseudoRegisterIfConstant( ControlFlowGraphStateForCodeTransformation cfg , Operator op , Expression ex ) { if(ex is ConstantExpression) { MoveToPseudoRegister( cfg, op, ex ); return true; } return false; } public static VariableExpression MoveToPseudoRegister( ControlFlowGraphStateForCodeTransformation cfg , Operator op , Expression ex ) { VariableExpression exReg = cfg.AllocatePseudoRegister( ex.Type ); op.AddOperatorBefore( SingleAssignmentOperator.New( op.DebugInfo, exReg, ex ) ); op.SubstituteUsage( ex, exReg ); return exReg; } public static PseudoRegisterExpression AllocatePseudoRegisterIfNeeded( ControlFlowGraphStateForCodeTransformation cfg , Expression ex ) { var var = ex as VariableExpression; if(var != null) { var exStack = var.AliasedVariable as StackLocationExpression; if(exStack != null) { return cfg.AllocatePseudoRegister( exStack.Type, exStack.DebugName ); } } return null; } public static PseudoRegisterExpression AllocatePseudoRegisterIfNeeded( ControlFlowGraphStateForCodeTransformation cfg , Expression ex , bool fConstantOk ) { var res = AllocatePseudoRegisterIfNeeded( cfg, ex ); if(res == null) { if(fConstantOk == false && ex is ConstantExpression) { res = cfg.AllocatePseudoRegister( ex.Type ); } } return res; } } } ================================================ FILE: Zelig/Zelig/CompileTime/CodeGenerator/CodeTransformation/Abstractions/RegisterClass.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // namespace Microsoft.Zelig.CodeGeneration.IR.Abstractions { using System; using System.Collections.Generic; using Microsoft.Zelig.MetaData; using Microsoft.Zelig.MetaData.Normalized; using Microsoft.Zelig.Runtime.TypeSystem; [Flags] public enum RegisterClass : uint { None = 0x00000000, Address = 0x00000001, System = 0x00000002, Integer = 0x00000004, SinglePrecision = 0x00000008, DoublePrecision = 0x00000010, DoublePrecision_Low = 0x00000020, DoublePrecision_High = 0x00000040, StatusRegister = 0x04000000, LinkAddress = 0x08000000, StackPointer = 0x10000000, ProgramCounter = 0x20000000, AvailableForAllocation = 0x40000000, Special = 0x80000000, } } ================================================ FILE: Zelig/Zelig/CompileTime/CodeGenerator/CodeTransformation/Abstractions/RegisterDescriptor.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // namespace Microsoft.Zelig.CodeGeneration.IR.Abstractions { using System; using System.Collections.Generic; using Microsoft.Zelig.MetaData; using Microsoft.Zelig.MetaData.Normalized; using Microsoft.Zelig.Runtime.TypeSystem; public class RegisterDescriptor { public static readonly RegisterDescriptor[] SharedEmptyArray = new RegisterDescriptor[0]; public enum Pair { Int_Int = 0, Int_FP = 1, Int_Sys = 2, FP_Int = 3, FP_FP = 4, FP_Sys = 5, Sys_Int = 6, Sys_FP = 7, Sys_Sys = 8, } // // State // int m_index; string m_mnemonic; uint m_encoding; uint m_physicalStorageOffset; uint m_physicalStorageSize; RegisterDescriptor[] m_interfersWith; RegisterClass m_physicalClass; RegisterClass m_storageCapabilities; RegisterClass m_computeCapabilities; // // Constructor Methods // private RegisterDescriptor( List< RegisterDescriptor > lst , string mnemonic , uint encoding , uint physicalStorageOffset , uint physicalStorageSize ) { m_index = lst.Count; m_mnemonic = mnemonic; m_physicalStorageOffset = physicalStorageOffset; m_physicalStorageSize = physicalStorageSize; m_encoding = encoding; m_interfersWith = SharedEmptyArray; lst.Add( this ); } // // Helper Methods // public void ApplyTransformation( TransformationContextForCodeTransformation context ) { context.Push( this ); context.Transform( ref m_index ); context.Transform( ref m_mnemonic ); context.Transform( ref m_encoding ); context.Transform( ref m_physicalStorageOffset ); context.Transform( ref m_physicalStorageSize ); context.Transform( ref m_interfersWith ); context.Transform( ref m_physicalClass ); context.Transform( ref m_storageCapabilities ); context.Transform( ref m_computeCapabilities ); context.Pop(); } //--// public static RegisterDescriptor ExtractFromExpression( Expression ex ) { var var = ex as VariableExpression; if(var != null) { var reg = var.AliasedVariable as PhysicalRegisterExpression; if(reg != null) { return reg.RegisterDescriptor; } } return null; } public static Pair GetPairState( RegisterDescriptor lhs , RegisterDescriptor rhs ) { if(lhs.InIntegerRegisterFile) { if(rhs.InIntegerRegisterFile) { return Pair.Int_Int; } if(rhs.IsSystemRegister) { return Pair.Int_Sys; } return Pair.Int_FP; } else if(lhs.InFloatingPointRegisterFile) { if(rhs.InIntegerRegisterFile) { return Pair.FP_Int; } if(rhs.IsSystemRegister) { return Pair.FP_Sys; } return Pair.FP_FP; } else { if(rhs.InIntegerRegisterFile) { return Pair.Sys_Int; } if(rhs.IsSystemRegister) { return Pair.Sys_Sys; } return Pair.Sys_FP; } } public static RegisterDescriptor CreateTemplateFor32bitSystemRegister( List< RegisterDescriptor > lst , string mnemonic , uint encoding , uint physicalStorageOffset , Abstractions.RegisterClass physicalClass ) { RegisterDescriptor reg = new RegisterDescriptor( lst, mnemonic, encoding, physicalStorageOffset, 1 ); physicalClass |= RegisterClass.System; reg.m_physicalClass = physicalClass; reg.m_storageCapabilities = RegisterClass.None; reg.m_computeCapabilities = RegisterClass.None; return reg; } public static RegisterDescriptor CreateTemplateFor32bitIntegerRegister( List< RegisterDescriptor > lst , string mnemonic , uint encoding , uint physicalStorageOffset , Abstractions.RegisterClass physicalClass ) { RegisterDescriptor reg = new RegisterDescriptor( lst, mnemonic, encoding, physicalStorageOffset, 1 ); physicalClass |= RegisterClass.Integer; reg.m_physicalClass = physicalClass; reg.m_storageCapabilities = RegisterClass.Integer | RegisterClass.Address | RegisterClass.SinglePrecision | RegisterClass.DoublePrecision_Low | RegisterClass.DoublePrecision_High ; reg.m_computeCapabilities = RegisterClass.Integer | RegisterClass.Address ; return reg; } public static RegisterDescriptor CreateTemplateFor32bitFloatingPointRegister( List< RegisterDescriptor > lst , string mnemonic , uint encoding , uint physicalStorageOffset , Abstractions.RegisterClass physicalClass , bool lowPart ) { RegisterDescriptor reg = new RegisterDescriptor( lst, mnemonic, encoding, physicalStorageOffset, 1 ); physicalClass |= RegisterClass.SinglePrecision; reg.m_physicalClass = physicalClass; reg.m_storageCapabilities = RegisterClass.Integer | RegisterClass.SinglePrecision | (lowPart ? RegisterClass.DoublePrecision_Low : RegisterClass.DoublePrecision_High); reg.m_computeCapabilities = RegisterClass.SinglePrecision; return reg; } public static RegisterDescriptor CreateTemplateFor64bitFloatingPointRegister( List< RegisterDescriptor > lst , string mnemonic , uint encoding , uint physicalStorageOffset , Abstractions.RegisterClass physicalClass ) { RegisterDescriptor reg = new RegisterDescriptor( lst, mnemonic, encoding, physicalStorageOffset, 2 ); physicalClass |= RegisterClass.DoublePrecision; reg.m_physicalClass = physicalClass; reg.m_storageCapabilities = RegisterClass.DoublePrecision; reg.m_computeCapabilities = RegisterClass.DoublePrecision; return reg; } public void AddInterference( RegisterDescriptor reg ) { m_interfersWith = ArrayUtility.AddUniqueToNotNullArray( m_interfersWith, reg ); } public object ValueFromBytes( uint[] data ) { if(this.InIntegerRegisterFile) { switch(m_physicalStorageSize) { case 1: return data[0]; case 2: return ((ulong)data[1] << 32) | (ulong)data[0]; default: return null; } } else if(this.InFloatingPointRegisterFile) { if(this.IsDoublePrecision) { return DataConversion.GetDoubleFromBytes( ((ulong)data[1] << 32) | (ulong)data[0] ); } else { return DataConversion.GetFloatFromBytes( data[0] ); } } else { return data[0]; } } public uint[] BytesFromValue( object value ) { uint[] res = new uint[m_physicalStorageSize]; if(this.InIntegerRegisterFile) { switch(m_physicalStorageSize) { case 1: res[0] = (uint)value; break; case 2: ulong val = (ulong)value; res[0] = (uint) val ; res[1] = (uint)(val >> 32); break; default: return null; } } else if(this.InFloatingPointRegisterFile) { if(this.IsDoublePrecision) { ulong val = DataConversion.GetDoubleAsBytes( (double)value ); res[0] = (uint) val ; res[1] = (uint)(val >> 32); } else { uint val = DataConversion.GetFloatAsBytes( (float)value ); res[0] = val; } } else { res[0] = (uint)value; } return res; } // // Access Methods // public int Index { get { return m_index; } } public string Mnemonic { get { return m_mnemonic; } } public RegisterClass PhysicalClass { get { return m_physicalClass; } } public uint Encoding { get { return m_encoding; } } public uint PhysicalStorageOffset { get { return m_physicalStorageOffset; } } public uint PhysicalStorageSize { get { return m_physicalStorageSize; } } public RegisterDescriptor[] InterfersWith { get { return m_interfersWith; } } public RegisterClass StorageCapabilities { get { return m_storageCapabilities; } } public RegisterClass ComputeCapabilities { get { return m_computeCapabilities; } } public bool InIntegerRegisterFile { get { return (this.PhysicalClass & RegisterClass.Integer) != 0; } } public bool InFloatingPointRegisterFile { get { return (this.PhysicalClass & (RegisterClass.SinglePrecision | RegisterClass.DoublePrecision)) != 0; } } public bool IsDoublePrecision { get { return (this.PhysicalClass & RegisterClass.DoublePrecision) != 0; } } public bool IsSystemRegister { get { return (this.PhysicalClass & RegisterClass.System) != 0; } } public bool IsSpecial { get { return (this.PhysicalClass & RegisterClass.Special) != 0; } } public bool IsLinkAddress { get { return (this.PhysicalClass & RegisterClass.LinkAddress) != 0; } } public bool CanAllocate { get { return (this.PhysicalClass & RegisterClass.AvailableForAllocation) != 0; } } // // Debug Methods // public override String ToString() { return string.Format( "RegisterDescriptor( {0} )", this.Mnemonic ); } } } ================================================ FILE: Zelig/Zelig/CompileTime/CodeGenerator/CodeTransformation/Annotations/InliningPathAnnotation.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // namespace Microsoft.Zelig.CodeGeneration.IR { using Debugging; using Microsoft.Zelig.Runtime.TypeSystem; using System; using System.Diagnostics; public sealed class InliningPathAnnotation : Annotation , IInliningPathAnnotation { // // State // // this is the original path used in the inlining heuristics unmodified for compatibility private MethodRepresentation[] m_path; // This contains the locations where the operator that this annotation is attached to was inlined into private DebugInfo[] m_InlinedAt; // // Constructor Methods // private InliningPathAnnotation( MethodRepresentation[] path, DebugInfo[] inlinedAt ) { Debug.Assert(path.Length == inlinedAt.Length); Debug.Assert(path.Length != 0); m_path = path; m_InlinedAt = inlinedAt; } public static InliningPathAnnotation Create( TypeSystemForIR ts , InliningPathAnnotation anOuter , MethodRepresentation md , DebugInfo debugInfo, InliningPathAnnotation anInner ) { Debug.Assert(anOuter == null || anOuter.DebugInfoPath.Length == anOuter.Path.Length); Debug.Assert(anInner == null || anInner.DebugInfoPath.Length == anInner.Path.Length); var pathOuter = anOuter != null ? anOuter.m_path : MethodRepresentation.SharedEmptyArray; var pathInner = anInner != null ? anInner.Path : MethodRepresentation.SharedEmptyArray; var path = ArrayUtility.AppendToNotNullArray( pathOuter, md ); path = ArrayUtility.AppendNotNullArrayToNotNullArray( path, pathInner ); // if the operator or varialbe didn't have debug info, then use the method itself if (debugInfo == null) debugInfo = md.DebugInfo; var debugInfoOuter = anOuter?.m_InlinedAt ?? DebugInfo.SharedEmptyArray; var debugInfoInner = anInner?.m_InlinedAt ?? DebugInfo.SharedEmptyArray; var debugInfoPath = ArrayUtility.AppendToNotNullArray( debugInfoOuter, debugInfo ); debugInfoPath = ArrayUtility.AppendNotNullArrayToNotNullArray( debugInfoPath, debugInfoInner ); return (InliningPathAnnotation)MakeUnique( ts, new InliningPathAnnotation( path, debugInfoPath ) ); } // // Equality Methods // public override bool Equals( Object obj ) { if(obj is InliningPathAnnotation) { InliningPathAnnotation other = (InliningPathAnnotation)obj; return ArrayUtility.ArrayEqualsNotNull( this.m_path, other.m_path, 0 ); } return false; } public override int GetHashCode() { if(m_path.Length > 0) { return m_path[0].GetHashCode(); } return 0; } // // Helper Methods // public override Annotation Clone( CloningContext context ) { MethodRepresentation[] path = context.ConvertMethods( m_path ); if(Object.ReferenceEquals( path, m_path )) { return this; // Nothing to change. } return RegisterAndCloneState( context, MakeUnique( context.TypeSystem, new InliningPathAnnotation( path, m_InlinedAt ) ) ); } //--// public override void ApplyTransformation( TransformationContextForIR context ) { context.Push( this ); base.ApplyTransformation( context ); object origin = context.GetTransformInitiator(); if(origin is CompilationSteps.ComputeCallsClosure.Context) { // // Don't propagate the path, it might include methods that don't exist anymore. // } else if (context is TypeSystemForCodeTransformation.FlagProhibitedUses) { TypeSystemForCodeTransformation ts = (TypeSystemForCodeTransformation)context.GetTypeSystem(); for (int i = m_path.Length; --i >= 0;) { MethodRepresentation md = m_path[i]; if (ts.ReachabilitySet.IsProhibited(md)) { m_path = ArrayUtility.RemoveAtPositionFromNotNullArray(m_path, i); // REVIEW: // Consider implications of not removing the entry, but instead // setting the scope to null, this would keep the Source and line debug // info so the debug info code gneration could treat this like a // pre-processor macro substitution instead of an inlined call to // a function that doesn't exist anymore. m_InlinedAt = ArrayUtility.RemoveAtPositionFromNotNullArray(m_InlinedAt, i); IsSquashed = true; } } } else { context.Transform( ref m_path ); // TODO: Handle m_DebugInfo - there is no Transform method for DebugInfo[] so this info isn't serialized, etc... } context.Pop(); //Debug.Assert(m_path.Length == m_InlinedAt.Length); //Debug.Assert(m_path.Length != 0 || IsSquashed); } //--// // // Access Methods // public bool IsSquashed { get; private set; } /// Method path for an inlined operator /// /// The last entry in the array contains the original source method for the operator this annotation is attached to. /// public MethodRepresentation[] Path => m_path; /// Retrieves the source location information for the inlining chain /// /// It is possible for entries in this array to be null if there was no debug information /// for the call site the method is inlined into. /// It is worth noting that the debug info path does not "line up" with the /// array, it is in fact off by one index. This is due to the fact that the operator that this /// annotation applies to has its own DebugInfo indicating its source location. Thus, the last /// entry in DebugInfoPath contains the source location where the operator was inlined *into*. /// public Debugging.DebugInfo[] DebugInfoPath => m_InlinedAt; //--// // // Debug Methods // public override string FormatOutput( IIntermediateRepresentationDumper dumper ) { System.Text.StringBuilder sb = new System.Text.StringBuilder(); sb.Append( "" ); sb.Append(""); return sb.ToString(); } } } ================================================ FILE: Zelig/Zelig/CompileTime/CodeGenerator/CodeTransformation/Annotations/RegisterAllocationConstraintAnnotation.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // namespace Microsoft.Zelig.CodeGeneration.IR { using System; using System.Collections.Generic; using Microsoft.Zelig.Runtime.TypeSystem; public sealed class RegisterAllocationConstraintAnnotation : Annotation { // // State // private int m_varIndex; private bool m_fIsResult; private Abstractions.RegisterClass m_constraint; // // Constructor Methods // private RegisterAllocationConstraintAnnotation( int index , bool fIsResult , Abstractions.RegisterClass constraint ) { m_varIndex = index; m_fIsResult = fIsResult; m_constraint = constraint; } public static RegisterAllocationConstraintAnnotation Create( TypeSystemForIR ts , int index , bool fIsResult , Abstractions.RegisterClass constraint ) { return (RegisterAllocationConstraintAnnotation)MakeUnique( ts, new RegisterAllocationConstraintAnnotation( index, fIsResult, constraint ) ); } // // Equality Methods // public override bool Equals( Object obj ) { if(obj is RegisterAllocationConstraintAnnotation) { RegisterAllocationConstraintAnnotation other = (RegisterAllocationConstraintAnnotation)obj; if(m_varIndex == other.m_varIndex && m_fIsResult == other.m_fIsResult && m_constraint == other.m_constraint ) { return true; } } return false; } public override int GetHashCode() { return 0x0F88DAC4 ^ m_varIndex; } // // Helper Methods // public override Annotation Clone( CloningContext context ) { return this; // Nothing to change. } //--// public override void ApplyTransformation( TransformationContextForIR context ) { var context2 = (TransformationContextForCodeTransformation)context; context2.Push( this ); base.ApplyTransformation( context2 ); context2.Transform( ref m_varIndex ); context2.Transform( ref m_fIsResult ); context2.Transform( ref m_constraint ); context2.Pop(); } //--// public static bool ShouldLhsBeMovedToPseudoRegister( Operator op , int index ) { if(VariableExpression.ExtractAliased( op.Results[index] ) is StackLocationExpression) { foreach(var an in op.FilterAnnotations< RegisterAllocationConstraintAnnotation >()) { if(an.IsResult == true && an.VarIndex == index) { if((an.Constraint & ~Abstractions.RegisterClass.Address) != Abstractions.RegisterClass.None) { return true; } } } } return false; } public static bool ShouldRhsBeMovedToPseudoRegister( Operator op , int index ) { if(VariableExpression.ExtractAliased( op.Arguments[index] ) is StackLocationExpression) { foreach(var an in op.FilterAnnotations< RegisterAllocationConstraintAnnotation >()) { if(an.IsResult == false && an.VarIndex == index) { if((an.Constraint & ~Abstractions.RegisterClass.Address) != Abstractions.RegisterClass.None) { return true; } } } } return false; } //--// public static Abstractions.RegisterClass ComputeConstraintsForLHS( Operator op , VariableExpression ex ) { Abstractions.RegisterClass constraint = Abstractions.RegisterClass.None; if(op != null) { foreach(var an in op.FilterAnnotations< RegisterAllocationConstraintAnnotation >()) { if(an.IsResult == true && op.Results[an.VarIndex] == ex) { constraint |= an.Constraint; } } } return constraint; } public static Abstractions.RegisterClass ComputeConstraintsForRHS( Operator op , Expression ex ) { Abstractions.RegisterClass constraint = Abstractions.RegisterClass.None; if(op != null) { foreach(var an in op.FilterAnnotations< RegisterAllocationConstraintAnnotation >()) { if(an.IsResult == false && op.Arguments[an.VarIndex] == ex) { constraint |= an.Constraint; } } } return constraint; } public static Abstractions.RegisterClass ComputeConstraintsForLHS( Operator op , int lhsIndex ) { Abstractions.RegisterClass constraint = Abstractions.RegisterClass.None; if(op != null) { foreach(var an in op.FilterAnnotations< RegisterAllocationConstraintAnnotation >()) { if(an.IsResult == true && an.VarIndex == lhsIndex) { constraint |= an.Constraint; } } } return constraint; } public static Abstractions.RegisterClass ComputeConstraintsForRHS( Operator op , int rhsIndex ) { Abstractions.RegisterClass constraint = Abstractions.RegisterClass.None; if(op != null) { foreach(var an in op.FilterAnnotations< RegisterAllocationConstraintAnnotation >()) { if(an.IsResult == false && an.VarIndex == rhsIndex) { constraint |= an.Constraint; } } } return constraint; } //--// // // Access Methods // public int VarIndex { get { return m_varIndex; } } public bool IsResult { get { return m_fIsResult; } } public Abstractions.RegisterClass Constraint { get { return m_constraint; } } //--// // // Debug Methods // public override string FormatOutput( IIntermediateRepresentationDumper dumper ) { return dumper.FormatOutput( "", m_fIsResult ? "LHS" : "RHS", m_varIndex , m_constraint ); } } } ================================================ FILE: Zelig/Zelig/CompileTime/CodeGenerator/CodeTransformation/Annotations/RegisterCouplingConstraintAnnotation.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // namespace Microsoft.Zelig.CodeGeneration.IR { using System; using System.Collections.Generic; using Microsoft.Zelig.Runtime.TypeSystem; public sealed class RegisterCouplingConstraintAnnotation : Annotation { // // State // private int m_varIndex1; private bool m_fIsResult1; private int m_varIndex2; private bool m_fIsResult2; // // Constructor Methods // private RegisterCouplingConstraintAnnotation( int index1 , bool fIsResult1 , int index2 , bool fIsResult2 ) { m_varIndex1 = index1; m_fIsResult1 = fIsResult1; m_varIndex2 = index2; m_fIsResult2 = fIsResult2; } public static RegisterCouplingConstraintAnnotation Create( TypeSystemForIR ts , int index1 , bool fIsResult1 , int index2 , bool fIsResult2 ) { return (RegisterCouplingConstraintAnnotation)MakeUnique( ts, new RegisterCouplingConstraintAnnotation( index1, fIsResult1, index2, fIsResult2 ) ); } // // Equality Methods // public override bool Equals( Object obj ) { if(obj is RegisterCouplingConstraintAnnotation) { var other = (RegisterCouplingConstraintAnnotation)obj; if(m_varIndex1 == other.m_varIndex1 && m_fIsResult1 == other.m_fIsResult1 && m_varIndex2 == other.m_varIndex2 && m_fIsResult2 == other.m_fIsResult2 ) { return true; } } return false; } public override int GetHashCode() { return 0x0E47C2CA ^ m_varIndex1 ^ (m_varIndex2 << 10); } // // Helper Methods // public override Annotation Clone( CloningContext context ) { return this; // Nothing to change. } //--// public override void ApplyTransformation( TransformationContextForIR context ) { var context2 = (TransformationContextForCodeTransformation)context; context2.Push( this ); base.ApplyTransformation( context2 ); context2.Transform( ref m_varIndex1 ); context2.Transform( ref m_fIsResult1 ); context2.Transform( ref m_varIndex2 ); context2.Transform( ref m_fIsResult2 ); context2.Pop(); } //--// public void ExtractTargets( Operator op , out VariableExpression var1 , out VariableExpression var2 ) { var1 = m_fIsResult1 ? op.Results[m_varIndex1] : (op.Arguments[m_varIndex1] as VariableExpression); var2 = m_fIsResult2 ? op.Results[m_varIndex2] : (op.Arguments[m_varIndex2] as VariableExpression); } public VariableExpression FindCoupledExpression( Operator op , VariableExpression ex ) { VariableExpression var1; VariableExpression var2; ExtractTargets( op, out var1, out var2 ); if(var1 == ex) return var2; if(var2 == ex) return var1; return null; } //--// // // Access Methods // public int VarIndex1 { get { return m_varIndex1; } } public bool IsResult1 { get { return m_fIsResult1; } } public int VarIndex2 { get { return m_varIndex2; } } public bool IsResult2 { get { return m_fIsResult2; } } //--// // // Debug Methods // public override string FormatOutput( IIntermediateRepresentationDumper dumper ) { return dumper.FormatOutput( " {2}({3})>", m_fIsResult1 ? "LHS" : "RHS", m_varIndex1, m_fIsResult2 ? "LHS" : "RHS", m_varIndex2 ); } } } ================================================ FILE: Zelig/Zelig/CompileTime/CodeGenerator/CodeTransformation/BitFieldDefinition.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // namespace Microsoft.Zelig.CodeGeneration.IR { using System; using System.Collections.Generic; using System.Runtime.CompilerServices; using Microsoft.Zelig.MetaData; using Microsoft.Zelig.MetaData.Normalized; using Microsoft.Zelig.Runtime.TypeSystem; [AllowCompileTimeIntrospection] public sealed class BitFieldDefinition { [AllowCompileTimeIntrospection] public sealed class Section { // // State // public uint Position; public uint Size; public uint Offset; public Runtime.BitFieldModifier Modifiers; public uint ReadsAs; public uint WritesAs; } // // State // public static readonly Section[] SharedEmptyArray = new Section[0]; private Section[] m_sections = SharedEmptyArray; // // Helper Methods // public void AddSection( Section sec ) { int i = m_sections.Length; while(i > 0) { var sec2 = m_sections[i-1]; if(sec2.Offset < sec.Offset) { break; } i--; } m_sections = ArrayUtility.InsertAtPositionOfNotNullArray( m_sections, i, sec ); } // // Access Methods // public Section[] Sections { get { return m_sections; } } public uint TotalSize { get { uint size = 0; foreach(var sec in m_sections) { size += sec.Size; } return size; } } } } ================================================ FILE: Zelig/Zelig/CompileTime/CodeGenerator/CodeTransformation/CodeTransformation.csproj ================================================  Debug AnyCPU 9.0.21022 2.0 {186F31A3-EF89-4A25-B2D5-20070222AA01} Library Properties Microsoft.Zelig.CodeGeneration.IR Microsoft.Zelig.CodeGeneration.CodeTransformation $(LlilumBuildRoot)\Host\obj\$(MSBuildProjectName)\ v4.5 true full false $(LlilumBuildRoot)\Host\bin\$(Configuration)\ DEBUG;TRACE prompt 4 true AllRules.ruleset AnyCPU false pdbonly true $(LlilumBuildRoot)\Host\bin\$(Configuration)\ TRACE prompt 4 true AllRules.ruleset AnyCPU false $(LlilumBuildRoot)\Host\bin\$(Configuration)\ TRACE;DEBUG;DUMP_CONSTRAINTSYSTEM;TRACE_EVERY_SINGLE_IR_CHANGE;TRACE_EVERY_IR_CHANGE true AnyCPU false {186F31A3-EF89-4A25-B2D5-20070601AA01} CommonPC False {186F31A3-EF89-4A25-B2D5-20060510AA01} Normalized False {186F31A3-EF89-4A25-B2D5-20061218AA01} Common False {186F31A3-EF89-4A25-B2D5-20060509AA01} Kernel False {186F31A3-EF89-4A25-B2D5-20060720AA01} TypeSystem False {186F31A3-EF89-4A25-B2D5-20070519AA01} ArmProcessor False {46478CA2-8163-47A0-8C65-3ACFC21CE57F} Win32Processor False {186F31A3-EF89-4A25-B2D5-20060603AA01} IntermediateRepresentation False {0162c8ce-6641-4922-8664-f8a44356fbf7} Llvm.NET {186f31a3-ef89-4a25-b2d5-20060404aa01} Importer {37193a86-ba04-4a3e-9df8-656df455e952} Elflib False ..\..\..\External\Binaries\CSharpParser\Debug\CSharpParser.dll 3.5 ================================================ FILE: Zelig/Zelig/CompileTime/CodeGenerator/CodeTransformation/CompilationSteps/Attributes/AbstractHandlerAttribute.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // namespace Microsoft.Zelig.CodeGeneration.IR.CompilationSteps { using System; [AttributeUsage(AttributeTargets.Method)] public abstract class AbstractHandlerAttribute : Attribute { // // State // // // Constructor Methods // } } ================================================ FILE: Zelig/Zelig/CompileTime/CodeGenerator/CodeTransformation/CompilationSteps/Attributes/CallClosureHandlerAttribute.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // namespace Microsoft.Zelig.CodeGeneration.IR.CompilationSteps { using System; [AttributeUsage(AttributeTargets.Method, AllowMultiple=true)] public sealed class CallClosureHandlerAttribute : AbstractHandlerAttribute { // // State // public Type Target; // // Constructor Methods // public CallClosureHandlerAttribute( Type target ) { this.Target = target; } } } ================================================ FILE: Zelig/Zelig/CompileTime/CodeGenerator/CodeTransformation/CompilationSteps/Attributes/CallToWellKnownMethodHandlerAttribute.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // namespace Microsoft.Zelig.CodeGeneration.IR.CompilationSteps { using System; [AttributeUsage(AttributeTargets.Method, AllowMultiple=true)] public sealed class CallToWellKnownMethodHandlerAttribute : AbstractHandlerAttribute { // // State // public string Target; // // Constructor Methods // public CallToWellKnownMethodHandlerAttribute( string target ) { this.Target = target; } } } ================================================ FILE: Zelig/Zelig/CompileTime/CodeGenerator/CodeTransformation/CompilationSteps/Attributes/CustomAttributeHandlerAttribute.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // namespace Microsoft.Zelig.CodeGeneration.IR.CompilationSteps { using System; [AttributeUsage(AttributeTargets.Method)] public sealed class CustomAttributeHandlerAttribute : AbstractHandlerAttribute { // // State // public string FieldName; // // Constructor Methods // public CustomAttributeHandlerAttribute( string fieldName ) { this.FieldName = fieldName; } } } ================================================ FILE: Zelig/Zelig/CompileTime/CodeGenerator/CodeTransformation/CompilationSteps/Attributes/CustomAttributeNotificationAttribute.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // namespace Microsoft.Zelig.CodeGeneration.IR.CompilationSteps { using System; [AttributeUsage(AttributeTargets.Method,AllowMultiple=true)] public sealed class CustomAttributeNotificationAttribute : Attribute { // // State // public string Target; // // Constructor Methods // public CustomAttributeNotificationAttribute( string target ) { this.Target = target; } } } ================================================ FILE: Zelig/Zelig/CompileTime/CodeGenerator/CodeTransformation/CompilationSteps/Attributes/MaximumOperatorLevelAfterPhaseExecutionAttribute.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // namespace Microsoft.Zelig.CodeGeneration.IR.CompilationSteps { using System; // // After running phase X, all the operators should be at most at level Y. // [AttributeUsage(AttributeTargets.Field, AllowMultiple=false)] public sealed class MaximumOperatorLevelAfterPhaseExecutionAttribute : Attribute { // // State // public readonly Operator.OperatorLevel Level; // // Constructor Methods // public MaximumOperatorLevelAfterPhaseExecutionAttribute( Operator.OperatorLevel level ) { this.Level = level; } } } ================================================ FILE: Zelig/Zelig/CompileTime/CodeGenerator/CodeTransformation/CompilationSteps/Attributes/NewEntityNotificationAttribute.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // namespace Microsoft.Zelig.CodeGeneration.IR.CompilationSteps { using System; [AttributeUsage(AttributeTargets.Method,AllowMultiple=false)] public sealed class NewEntityNotificationAttribute : Attribute { } } ================================================ FILE: Zelig/Zelig/CompileTime/CodeGenerator/CodeTransformation/CompilationSteps/Attributes/OperatorArgumentHandlerAttribute.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // namespace Microsoft.Zelig.CodeGeneration.IR.CompilationSteps { using System; [AttributeUsage(AttributeTargets.Method)] public sealed class OperatorArgumentHandlerAttribute : AbstractHandlerAttribute { // // State // public Type Target; // // Constructor Methods // public OperatorArgumentHandlerAttribute( Type target ) { this.Target = target; } } } ================================================ FILE: Zelig/Zelig/CompileTime/CodeGenerator/CodeTransformation/CompilationSteps/Attributes/OperatorHandlerAttribute.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // namespace Microsoft.Zelig.CodeGeneration.IR.CompilationSteps { using System; [AttributeUsage(AttributeTargets.Method, AllowMultiple=true)] public sealed class OperatorHandlerAttribute : AbstractHandlerAttribute { // // State // public Type Target; // // Constructor Methods // public OperatorHandlerAttribute( Type target ) { this.Target = target; } } } ================================================ FILE: Zelig/Zelig/CompileTime/CodeGenerator/CodeTransformation/CompilationSteps/Attributes/OptimizationHandlerAttribute.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // namespace Microsoft.Zelig.CodeGeneration.IR.CompilationSteps { using System; // // Methods with this attribute get a chance to look at the ControlFlowGraphState during optimization phases. // [AttributeUsage(AttributeTargets.Method)] public sealed class OptimizationHandlerAttribute : AbstractHandlerAttribute { // // State // public bool RunOnce; public bool RunInExtendedSSAForm; public bool RunInSSAForm; public bool RunInNormalForm; public string RunBefore; public string RunAfter; internal OptimizationHandlerAttribute caToRunBeforeThis; internal OptimizationHandlerAttribute caToRunAfterThis; // // Constructor Methods // } } ================================================ FILE: Zelig/Zelig/CompileTime/CodeGenerator/CodeTransformation/CompilationSteps/Attributes/PhaseDisabledAttribute.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // namespace Microsoft.Zelig.CodeGeneration.IR.CompilationSteps { using System; // // After running phase X, all the operators should be at most at level Y. // [AttributeUsage(AttributeTargets.Class, AllowMultiple=false)] public sealed class PhaseDisabledAttribute : Attribute { // // State // // none // // Constructor Methods // public PhaseDisabledAttribute() { } } } ================================================ FILE: Zelig/Zelig/CompileTime/CodeGenerator/CodeTransformation/CompilationSteps/Attributes/PhaseFilterAttribute.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // namespace Microsoft.Zelig.CodeGeneration.IR.CompilationSteps { using System; [AttributeUsage(AttributeTargets.Method, AllowMultiple=true)] public sealed class PhaseFilterAttribute : Attribute { // // State // public readonly Type Target; // // Constructor Methods // public PhaseFilterAttribute( Type target ) { this.Target = target; } } } ================================================ FILE: Zelig/Zelig/CompileTime/CodeGenerator/CodeTransformation/CompilationSteps/Attributes/PhaseLimitAttribute.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // namespace Microsoft.Zelig.CodeGeneration.IR.CompilationSteps { using System; // // After running phase X, all the operators should be at most at level Y. // [AttributeUsage(AttributeTargets.Class, AllowMultiple=false)] public sealed class PhaseLimitAttribute : Attribute { // // State // public readonly Operator.OperatorLevel Level; // // Constructor Methods // public PhaseLimitAttribute( Operator.OperatorLevel level ) { this.Level = level; } } } ================================================ FILE: Zelig/Zelig/CompileTime/CodeGenerator/CodeTransformation/CompilationSteps/Attributes/PhaseOrderingAttribute.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // namespace Microsoft.Zelig.CodeGeneration.IR.CompilationSteps { using System; // // Allows to position phase X in relation to other phases. // [AttributeUsage(AttributeTargets.Class, AllowMultiple=false, Inherited=true)] public sealed class PhaseOrderingAttribute : Attribute { // // State // public Type ExecuteBefore; public Type ExecuteAfter; public bool IsPipelineBlock; } } ================================================ FILE: Zelig/Zelig/CompileTime/CodeGenerator/CodeTransformation/CompilationSteps/Attributes/PostFlowGraphHandlerAttribute.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // namespace Microsoft.Zelig.CodeGeneration.IR.CompilationSteps { using System; // // Methods with this attribute get a chance to look at the ControlFlowGraphState after everyone else. // [AttributeUsage(AttributeTargets.Method)] public sealed class PostFlowGraphHandlerAttribute : AbstractHandlerAttribute { // // State // // // Constructor Methods // } } ================================================ FILE: Zelig/Zelig/CompileTime/CodeGenerator/CodeTransformation/CompilationSteps/Attributes/PostPhaseHandlerAttribute.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // namespace Microsoft.Zelig.CodeGeneration.IR.CompilationSteps { using System; // // Methods with this attribute get a chance to look at the type system after a phase has executed. // [AttributeUsage(AttributeTargets.Method)] public sealed class PostPhaseHandlerAttribute : AbstractHandlerAttribute { // // State // // // Constructor Methods // } } ================================================ FILE: Zelig/Zelig/CompileTime/CodeGenerator/CodeTransformation/CompilationSteps/Attributes/PreFlowGraphHandlerAttribute.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // namespace Microsoft.Zelig.CodeGeneration.IR.CompilationSteps { using System; // // Methods with this attribute get a chance to look at the ControlFlowGraphState before everyone else. // [AttributeUsage(AttributeTargets.Method)] public sealed class PreFlowGraphHandlerAttribute : AbstractHandlerAttribute { // // State // // // Constructor Methods // } } ================================================ FILE: Zelig/Zelig/CompileTime/CodeGenerator/CodeTransformation/CompilationSteps/Attributes/PrePhaseHandlerAttribute.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // namespace Microsoft.Zelig.CodeGeneration.IR.CompilationSteps { using System; // // Methods with this attribute get a chance to look at the type system before a phase has executed. // [AttributeUsage(AttributeTargets.Method)] public sealed class PrePhaseHandlerAttribute : AbstractHandlerAttribute { // // State // // // Constructor Methods // } } ================================================ FILE: Zelig/Zelig/CompileTime/CodeGenerator/CodeTransformation/CompilationSteps/Attributes/WellKnownFieldHandlerAttribute.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // namespace Microsoft.Zelig.CodeGeneration.IR.CompilationSteps { using System; [AttributeUsage(AttributeTargets.Method)] public sealed class WellKnownFieldHandlerAttribute : AbstractHandlerAttribute { // // State // public string Target; // // Constructor Methods // public WellKnownFieldHandlerAttribute( string target ) { this.Target = target; } } } ================================================ FILE: Zelig/Zelig/CompileTime/CodeGenerator/CodeTransformation/CompilationSteps/Attributes/WellKnownMethodHandlerAttribute.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // namespace Microsoft.Zelig.CodeGeneration.IR.CompilationSteps { using System; [AttributeUsage(AttributeTargets.Method, AllowMultiple=true)] public sealed class WellKnownMethodHandlerAttribute : AbstractHandlerAttribute { // // State // public string Target; // // Constructor Methods // public WellKnownMethodHandlerAttribute( string target ) { this.Target = target; } } } ================================================ FILE: Zelig/Zelig/CompileTime/CodeGenerator/CodeTransformation/CompilationSteps/Attributes/WellKnownTypeHandlerAttribute.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // namespace Microsoft.Zelig.CodeGeneration.IR.CompilationSteps { using System; [AttributeUsage(AttributeTargets.Method)] public sealed class WellKnownTypeHandlerAttribute : AbstractHandlerAttribute { // // State // public string Target; // // Constructor Methods // public WellKnownTypeHandlerAttribute( string target ) { this.Target = target; } } } ================================================ FILE: Zelig/Zelig/CompileTime/CodeGenerator/CodeTransformation/CompilationSteps/Controller.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // //#define COLLECT_PERFORMANCE_DATA_FOR_CONTROLLER namespace Microsoft.Zelig.CodeGeneration.IR.CompilationSteps { using System; using System.Collections.Generic; using Microsoft.Zelig.Runtime.TypeSystem; public sealed class Controller { // // State // private readonly TypeSystemForCodeTransformation m_typeSystem; private readonly CallsDataBase m_callsDatabase; private readonly LinkedList< PhaseDriver > m_phases; private PhaseDriver m_currentPhase; // // Constructor Methods // public Controller( TypeSystemForCodeTransformation typeSystem, List phases ) { m_typeSystem = typeSystem; m_callsDatabase = new CallsDataBase( ); m_phases = new LinkedList( ); //--// var lst = new List( ); CreatePhaseDrivers( lst, phases ); var orderingForward = HashTableFactory.NewWithReferenceEquality>( ); var orderingBackward = HashTableFactory.NewWithReferenceEquality>( ); CollectPhaseOrderingConstraints( lst, orderingForward, orderingBackward ); ValidateConstraints( lst, orderingForward ); SortPhaseDrivers( lst, orderingBackward ); DumpPhaseOrdering( ); } public Controller( TypeSystemForCodeTransformation typeSystem ) : this( typeSystem, null ) { } // // Helper Methods // private void CreatePhaseDrivers( List lst, List userDisabledPhases ) { var assembly = System.Reflection.Assembly.GetCallingAssembly(); foreach(Type t in assembly.GetTypes()) { if(t.IsAbstract == false && t.IsSubclassOf( typeof(PhaseDriver) )) { bool fDisabled = false; // check if this phase appears in the list crafted by the user if( userDisabledPhases != null && userDisabledPhases.Count > 0 ) { foreach( var p in userDisabledPhases ) { if(t.Name == p) { fDisabled = true; break; } } } // check if phase has been disabled through attribute if( !fDisabled ) { // check that this phase is not disabled // disabled phases cannot run var e = t.CustomAttributes.GetEnumerator( ); while( e.MoveNext( ) ) { if( e.Current.AttributeType == typeof( PhaseDisabledAttribute ) ) { fDisabled = true; break; } } } var phase = (PhaseDriver)Activator.CreateInstance(t, this); phase.Disabled = fDisabled; lst.Add(phase); } } } private static void CollectPhaseOrderingConstraints( List < PhaseDriver > lst , GrowOnlyHashTable< PhaseDriver, List< PhaseDriver > > orderingForward , GrowOnlyHashTable< PhaseDriver, List< PhaseDriver > > orderingBackward ) { foreach(var phase in lst) { var phaseAfter = FindPhaseByType( lst, phase.ExecuteAfter ); if(phaseAfter != null) { HashTableWithListFactory.AddUnique( orderingForward , phaseAfter, phase ); HashTableWithListFactory.AddUnique( orderingBackward, phase , phaseAfter ); } var phaseBefore = FindPhaseByType( lst, phase.ExecuteBefore ); if(phaseBefore != null) { HashTableWithListFactory.AddUnique( orderingForward , phase , phaseBefore ); HashTableWithListFactory.AddUnique( orderingBackward, phaseBefore, phase ); } } } private static void ValidateConstraints( List < PhaseDriver > lst , GrowOnlyHashTable< PhaseDriver, List< PhaseDriver > > orderingForward ) { var set = SetFactory.NewWithReferenceEquality< PhaseDriver >(); foreach(var phase in lst) { set.Clear(); if(FindOrderingLoop( orderingForward, set, phase, phase )) { throw TypeConsistencyErrorException.Create( "Found loop in phase ordering constraints" ); } } } private static bool FindOrderingLoop( GrowOnlyHashTable< PhaseDriver, List< PhaseDriver > > ordering , GrowOnlySet < PhaseDriver > set , PhaseDriver phaseStart , PhaseDriver phase ) { set.Insert( phase ); List< PhaseDriver > lst; if(ordering.TryGetValue( phase, out lst )) { foreach(var phaseNext in lst) { if(phaseNext == phaseStart) { return true; } if(FindOrderingLoop( ordering, set, phaseStart, phaseNext )) { return true; } } } return false; } private void SortPhaseDrivers( List < PhaseDriver > lst , GrowOnlyHashTable< PhaseDriver, List< PhaseDriver > > orderingBackward ) { // // Keep looking for a phase that doesn't have any pending predecessors. // This is guaranteed to make progress, since we have already proved there are no loops. // while(lst.Count > 0) { foreach(var phase in lst) { List< PhaseDriver > lstPredecessors; bool fAdd = true; if(orderingBackward.TryGetValue( phase, out lstPredecessors )) { foreach(var phasePredecessor in lstPredecessors) { if(phasePredecessor.m_node == null) { // // Predecessor not inserted, can't add to the list. // fAdd = false; break; } } } if(fAdd) { phase.m_node = m_phases.AddLast( phase ); lst.Remove( phase ); break; } } } } private void DumpPhaseOrdering() { Console.WriteLine(""); Console.WriteLine("Phase Ordering:"); foreach(var phase in m_phases) { if (phase.Disabled) { var color = Console.ForegroundColor; Console.ForegroundColor = ConsoleColor.Yellow; Console.WriteLine(" {0}: {1} (Disabled)", phase.PhaseIndex, phase); Console.ForegroundColor = color; } else { Console.WriteLine(" {0}: {1}", phase.PhaseIndex, phase); } } Console.WriteLine( "" ); Console.WriteLine( "" ); } //--// public void ExecuteSteps( bool fGenerateImageOnly = false ) { Console.WriteLine( "Compiling..." ); Console.WriteLine( "" ); // // 1) Expand the Call Closure to include all the overrides of virtual methods. // Question: should we wait until we know all the types used by the application? // // 2) For all the ForceDevirtualization types, find the implementation. Virtual calls should be changed to normal calls. // Question: should we use a ClassExtension-like mechanism? Not for now. // // 3) ImplicitInstance == you cannot create objects for this type. For now, it's not-implemented! // // 4) ForceDevirtualization = there should be only one subclass used by the application // => keep track of referenced types, marking some types as unavailable. For now, we could simplify and abort on multiple sub-classes. // RegisterPhases(); m_currentPhase = m_phases.First.Value; while(m_currentPhase != null) { if(fGenerateImageOnly && ((m_currentPhase is Phases.GenerateImage) == false)) { m_currentPhase = m_currentPhase.NextPhase; continue; } if(m_currentPhase.Disabled) { var color = Console.ForegroundColor; Console.ForegroundColor = ConsoleColor.Yellow; Console.WriteLine( "Skipping phase: {0}", m_currentPhase ); Console.ForegroundColor = color; m_currentPhase = m_currentPhase.NextPhase; continue; } using(new Transformations.ExecutionTiming( m_currentPhase.ToString() )) { m_typeSystem.NotifyCompilationPhaseInner( m_currentPhase ); #if COLLECT_PERFORMANCE_DATA_FOR_CONTROLLER PerformanceCounters.ContextualTiming timing = new PerformanceCounters.ContextualTiming(); timing.Start( this, string.Format( "Phase__{0}", m_currentPhase ) ); #endif var nextPhase = m_currentPhase.Execute(); #if COLLECT_PERFORMANCE_DATA_FOR_CONTROLLER timing.Stop(); #endif if(nextPhase != null) { foreach(var phase in m_phases) { phase.ValidatePhaseMovement( m_currentPhase, nextPhase ); } } m_currentPhase = nextPhase; } } } private void RegisterPhases() { var cache = m_typeSystem.GetEnvironmentService< IR.CompilationSteps.DelegationCache >(); cache.Register( new Handlers.MethodTransformations() ); cache.Register( new Handlers.ProtectRequiredEntities() ); cache.Register( new Handlers.WellKnownFieldHandlers() ); cache.Register( new Handlers.WellKnownMethodHandlers() ); cache.Register( new Handlers.OperatorHandlers_HighLevel() ); cache.Register( new Handlers.OperatorHandlers_HighLevelToMidLevel() ); cache.Register( new Handlers.OperatorHandlers_FromImplicitToExplicitExceptions() ); cache.Register( new Handlers.OperatorHandlers_ReferenceCountingGarbageCollection() ); cache.Register( new Handlers.OperatorHandlers_ConvertUnsupportedOperatorsToMethodCalls() ); cache.Register( new Handlers.OperatorHandlers_ExpandAggregateTypes() ); cache.Register( new Handlers.OperatorHandlers_MidLevelToLowLevel() ); cache.Register( new Handlers.Optimizations() ); m_typeSystem.PlatformAbstraction.RegisterForNotifications( m_typeSystem, cache ); m_typeSystem.CallingConvention .RegisterForNotifications( m_typeSystem, cache ); } //--// internal T FindPhase< T >() where T : PhaseDriver { return (T)FindPhaseByType( typeof(T) ); } internal PhaseDriver FindPhaseByType( Type type ) { return FindPhaseByType( m_phases, type ); } private static PhaseDriver FindPhaseByType( IEnumerable< PhaseDriver > lst , Type type ) { if(type != null) { foreach(var phase in lst) { if(phase.GetType() == type) { return phase; } } } return null; } //--// // // Access Methods // internal TypeSystemForCodeTransformation TypeSystem { get { return m_typeSystem; } } internal CallsDataBase CallsDatabase { get { return m_callsDatabase; } } public GrowOnlyHashTable< MethodRepresentation, GrowOnlySet< object > > EntitiesReferencedByMethods { get { CHECKS.ASSERT( m_currentPhase.PhaseIndex > FindPhase< Phases.ComputeCallsClosure >().PhaseIndex, "Cannot access EntitiesReferencedByMethods property at phase {0}!", m_currentPhase ); var phase = this.FindPhase< Phases.ComputeCallsClosure >(); return phase.EntitiesReferencedByMethods; } } } } ================================================ FILE: Zelig/Zelig/CompileTime/CodeGenerator/CodeTransformation/CompilationSteps/Handlers/MethodTransformations.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // namespace Microsoft.Zelig.CodeGeneration.IR.CompilationSteps.Handlers { using System; using System.Collections.Generic; using Microsoft.Zelig.Runtime.TypeSystem; public class MethodTransformations { //--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--// //--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--// //--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--// [CompilationSteps.PhaseFilter( typeof(Phases.HighLevelTransformations ) )] [CompilationSteps.PhaseFilter( typeof(Phases.HighLevelToMidLevelConversion) )] [CompilationSteps.PhaseFilter( typeof(Phases.MidLevelToLowLevelConversion ) )] [CompilationSteps.PhaseFilter( typeof(Phases.ExpandAggregateTypes ) )] [CompilationSteps.PhaseFilter( typeof(Phases.ReferenceCountingGarbageCollection) )] [CompilationSteps.PostFlowGraphHandler()] private static void ProcessFlowGraphAfterTransformations( PhaseExecution.NotificationContext nc ) { ControlFlowGraphStateForCodeTransformation cfg = nc.CurrentCFG; if(cfg != null) { if(Transformations.CommonMethodRedundancyElimination.Execute( cfg )) { nc.StopScan(); return; } cfg.DropDeadVariables(); } } //--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--// //--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--// //--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--// [CompilationSteps.PreFlowGraphHandler()] private void InjectPrologueAndEpilogue( PhaseExecution.NotificationContext nc ) { var inlineOptions = nc.TypeSystem.GetEnvironmentService( ); if( inlineOptions != null && !inlineOptions.InjectPrologAndEpilog ) return; if(nc.Phase.ComparePositionTo< Phases.HighLevelTransformations >() >= 0 && nc.Phase.ComparePositionTo< Phases.ReduceTypeSystem >() < 0 ) { ControlFlowGraphStateForCodeTransformation cfg = nc.CurrentCFG; if(cfg != null && cfg.SetProperty( "MethodWrappersAdded" ) == false) { var wkm = nc.TypeSystem.WellKnownMethods; { var prologueStart = cfg.GetInjectionPoint( BasicBlock.Qualifier.PrologueStart ); var prologueEnd = cfg.GetInjectionPoint( BasicBlock.Qualifier.PrologueEnd ); AddCallToWrapper( nc, prologueStart, prologueEnd, wkm.Microsoft_Zelig_Runtime_AbstractMethodWrapper_Prologue, wkm.Microsoft_Zelig_Runtime_AbstractMethodWrapper_Prologue2 ); } { var epilogueStart = cfg.GetInjectionPoint( BasicBlock.Qualifier.EpilogueStart ); var epilogueEnd = cfg.GetInjectionPoint( BasicBlock.Qualifier.EpilogueEnd ); AddCallToWrapper( nc, epilogueStart, epilogueEnd, wkm.Microsoft_Zelig_Runtime_AbstractMethodWrapper_Epilogue, wkm.Microsoft_Zelig_Runtime_AbstractMethodWrapper_Epilogue2 ); } nc.StartScan(); } } } private static void AddCallToWrapper( PhaseExecution.NotificationContext nc , BasicBlock targetStart , BasicBlock targetEnd , MethodRepresentation mdNormal , MethodRepresentation mdException ) { if(targetStart != null) { var cfg = nc.CurrentCFG; var ts = nc.TypeSystem; var md = cfg.Method; var attribs = md.ExpandedBuildTimeFlags; var he = ts.ExtractHardwareExceptionSettingsForMethod( md ); var tdHelper = ts.PlatformAbstraction.GetMethodWrapperType(); var exHelper = ts.GenerateConstantForSingleton( tdHelper, DataManager.Attributes.Constant | DataManager.Attributes.SuitableForConstantPropagation ); Expression[] rhsHelper; MethodRepresentation mdHelper; if(ts.PlatformAbstraction.HasRegisterContextArgument( md )) { attribs |= MethodRepresentation.BuildTimeAttributes.SaveFullProcessorContext; } if(he == Runtime.HardwareException.None) { rhsHelper = ts.CreateConstantsFromObjects( exHelper, md.OwnerType.FullName, md.ToShortString(), attribs ); mdHelper = mdNormal; } else { rhsHelper = ts.CreateConstantsFromObjects( exHelper, md.OwnerType.FullName, md.ToShortString(), attribs, he ); mdHelper = mdException; } CallOperator callHelper; MethodRepresentation mdHelperDirect = mdHelper.FindVirtualTarget( tdHelper ); if(mdHelperDirect != null) { callHelper = InstanceCallOperator.New( null, CallOperator.CallKind.Overridden, mdHelperDirect, rhsHelper, false ); } else { callHelper = InstanceCallOperator.New( null, CallOperator.CallKind.Virtual, mdHelper, rhsHelper, false ); } targetStart.AddOperator( callHelper ); } } //--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--// //--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--// //--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--// [CompilationSteps.PhaseFilter( typeof(Phases.ExpandAggregateTypes) )] [CompilationSteps.PreFlowGraphHandler()] private static void ProcessFlowGraphBeforeExpandAggregateTypes( PhaseExecution.NotificationContext nc ) { ControlFlowGraphStateForCodeTransformation cfg = nc.CurrentCFG; if(cfg != null) { cfg.MapVariables(); } } //--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--// //--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--// //--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--// [CompilationSteps.PhaseFilter( typeof(Phases.ConvertToSSA) )] [CompilationSteps.PreFlowGraphHandler()] private static void ConvertToSSA( PhaseExecution.NotificationContext nc ) { ControlFlowGraphStateForCodeTransformation cfg = nc.CurrentCFG; if(cfg != null) { if(Transformations.StaticSingleAssignmentForm.ConvertInto( cfg )) { nc.MarkAsModified(); } } } //--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--// //--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--// //--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--// /// /// Coerce constant call arguments to their target type. This saves having to inject a cast at translation time. /// /// Context for this transformation. [CompilationSteps.OperatorHandler(typeof(CallOperator))] private void CoerceConstantParameters( PhaseExecution.NotificationContext nc ) { CallOperator call = nc.GetOperatorAndThrowIfNotCall(); TypeRepresentation[] argTypes = call.TargetMethod.ThisPlusArguments; Expression[] arguments = call.Arguments; bool isIndirect = call is IndirectCallOperator; // We always skip the 'this' pointer, so start at 1. for( int i = 1 ; i < argTypes.Length; ++i ) { CoerceConstantParameter(ref arguments[isIndirect ? (i + 1) : i], argTypes[i]); } } private static void CoerceConstantParameter( ref Expression argExpr, TypeRepresentation targetType ) { var constExpr = argExpr as ConstantExpression; if( constExpr == null ) { return; } if ( targetType != argExpr.Type ) { // This works for all scalar numeric types, including enums. ulong valueAsUInt64; if( constExpr.GetAsRawUlong( out valueAsUInt64 ) ) { object value = ConstantExpression.ConvertToType( targetType, valueAsUInt64 ); argExpr = new ConstantExpression( targetType, value ); } } } //--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--// //--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--// //--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--// [CompilationSteps.OperatorHandler( typeof(CallOperator) )] private static void AttemptDevirtualization( PhaseExecution.NotificationContext nc ) { if(AttemptDevirtualization( nc.TypeSystem, nc.GetOperatorAndThrowIfNotCall() )) { nc.MarkAsModified(); } } //--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--// //--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--// //--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--// public static bool AttemptDevirtualization( TypeSystemForCodeTransformation typeSystem , CallOperator call ) { MethodRepresentation md = call.TargetMethod; if(call.CallType == CallOperator.CallKind.Virtual) { if(!(md is VirtualMethodRepresentation) || md is FinalMethodRepresentation ) { CallOperator callNew = InstanceCallOperator.New( call.DebugInfo, CallOperator.CallKind.Overridden, md, call.Results, call.Arguments, true ); call.SubstituteWithOperator( callNew, Operator.SubstitutionFlags.CopyAnnotations ); return true; } else { TypeRepresentation tdTarget = null; { TypeRepresentation tdForcedDevirtualization; if(typeSystem.ForcedDevirtualizations.TryGetValue( md.OwnerType, out tdForcedDevirtualization )) { tdTarget = tdForcedDevirtualization; } } if(tdTarget == null) { Expression exThis = call.FirstArgument; TypeRepresentation tdThis = exThis.Type.UnderlyingType; if(tdThis is ValueTypeRepresentation || (tdThis.Flags & TypeRepresentation.Attributes.Sealed) != 0) { tdTarget = tdThis; } else if(tdThis.IsSubClassOf( md.OwnerType, null )) { MethodRepresentation md2 = md.FindVirtualTarget( tdThis ); if((md2.Flags & MethodRepresentation.Attributes.Final) != 0) { tdTarget = tdThis; } } if(tdTarget == null) { // // BUGBUG: This is valid only if we are in bounded application mode!!! // tdTarget = typeSystem.FindSingleConcreteImplementation( tdThis ); } } if(tdTarget != null) { MethodRepresentation md2 = md.FindVirtualTarget( tdTarget ); CallOperator callNew = InstanceCallOperator.New( call.DebugInfo, CallOperator.CallKind.Overridden, md2, call.Results, call.Arguments, true ); call.SubstituteWithOperator( callNew, Operator.SubstitutionFlags.CopyAnnotations ); return true; } } } return false; } //--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--// //--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--// //--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--// [CompilationSteps.PhaseFilter( typeof( Phases.ReferenceCountingGarbageCollection ) )] [CompilationSteps.PreFlowGraphHandler( )] private static void InjectReferenceCountingSetupAndCleanup( PhaseExecution.NotificationContext nc ) { ControlFlowGraphStateForCodeTransformation cfg = nc.CurrentCFG; if(cfg != null && cfg.SetProperty( "ReferenceCountingAdded" ) == false) { var ts = nc.TypeSystem; if(!ts.ShouldExcludeMethodFromReferenceCounting( cfg.Method )) { bool modified = false; var phase = (Phases.ReferenceCountingGarbageCollection)nc.Phase; var wkm = ts.WellKnownMethods; var defChains = cfg.DataFlow_DefinitionChains; var useChains = cfg.DataFlow_UseChains; var variables = cfg.DataFlow_SpanningTree_Variables; var arguments = cfg.Arguments; GrowOnlySet needRelease = SetFactory.New( ); var prologueStart = cfg.GetInjectionPoint( BasicBlock.Qualifier.PrologueStart ); var epilogueStart = cfg.GetInjectionPoint( BasicBlock.Qualifier.EpilogueStart ); cfg.ResetCacheCheckpoint( ); var mdAddRef = wkm.ObjectHeader_AddReference; var mdRelease = wkm.ObjectHeader_ReleaseReference; var returnVariable = FindReturnVariable( cfg, defChains, useChains ); foreach(var arg in arguments) { var skipReferenceCounting = true; // Skip over the first argument (this pointer) // and arguments that aren't being used (as indicated by an invalid spanning tree index) // and arguments that are not the right types if(arg.Number != 0 && arg.SpanningTreeIndex >= 0 && ts.IsReferenceCountingType( arg.Type )) { var defChain = defChains[ arg.SpanningTreeIndex ]; CHECKS.ASSERT( defChain.Length > 0 && defChain[ 0 ] is InitialValueOperator, "Argument {0} does not have an InitialValueOperator", arg); // Looking at the definition chain, we only want to AddRef/Release arguments that are modified // within the method, so we can manage the lifetime of the new value accordingly. If the argument is // never modified, then the caller would hold a reference to guarantee its lifetime for the // duration of the method call. if(defChain.Length > 1) { var rhsAddref = ts.AddTypePointerToArgumentsOfStaticMethod( mdAddRef, arg ); var callAddref = StaticCallOperator.New( null, CallOperator.CallKind.Direct, mdAddRef, rhsAddref ); prologueStart.AddOperator( callAddref ); phase.IncrementInjectionCount( mdAddRef ); modified = true; // Do not release the return variable because we need to pass the // ref count back to the caller on return. if(arg != returnVariable) { needRelease.Insert( arg ); } skipReferenceCounting = false; } } if(skipReferenceCounting) { arg.SkipReferenceCounting = true; } } var skippables = FindSkippableVariables( cfg, variables, defChains, useChains ); foreach(var variable in variables) { if(skippables[ variable.SpanningTreeIndex ]) { variable.SkipReferenceCounting = true; } else if (!(variable is ArgumentVariableExpression)) { var nullExpression = new ConstantExpression( variable.Type, null ); var op = SingleAssignmentOperator.New( null, variable, nullExpression ); prologueStart.AddOperator( op ); modified = true; phase.AddToModifiedOperator( op ); // Do not release the return variable because we need to pass the // ref count back to the caller on return. if(variable != returnVariable) { needRelease.Insert( variable ); } } } if(epilogueStart != null) { foreach(var variable in needRelease) { var rhsRelease = ts.AddTypePointerToArgumentsOfStaticMethod( mdRelease, variable ); var callRelease = StaticCallOperator.New( null, CallOperator.CallKind.Direct, mdRelease, rhsRelease ); epilogueStart.AddOperator( callRelease ); phase.IncrementInjectionCount( mdRelease ); modified = true; } // A ref counting return variable should carry a ref count to pass on to the caller, // so if we skip reference counting on the variable, we'd need to take a ref count // prior to returning. if( returnVariable != null && returnVariable.SkipReferenceCounting && ts.IsReferenceCountingType( returnVariable.Type )) { var rhsAddRef = ts.AddTypePointerToArgumentsOfStaticMethod( mdAddRef, returnVariable ); var callAddRef = StaticCallOperator.New( null, CallOperator.CallKind.Direct, mdAddRef, rhsAddRef ); epilogueStart.AddOperator( callAddRef ); phase.IncrementInjectionCount( mdAddRef ); modified = true; } } if(modified) { nc.StartScan( ); } cfg.AssertNoCacheRefreshSinceCheckpoint( ); } } } private static VariableExpression FindReturnVariable( ControlFlowGraphStateForCodeTransformation cfg, Operator[][] defChains, Operator[][] useChains ) { var ts = cfg.TypeSystem; // Find the return variable, if any. var returnOperator = (ReturnControlOperator)cfg.ExitBasicBlock?.FlowControl; var returnVariable = returnOperator?.Arguments.Length > 0 ? returnOperator.FirstArgument as VariableExpression : null; if(returnVariable != null && ts.IsReferenceCountingType( returnVariable.Type )) { var returnVarSubstitute = FindReturnVariableSubstitute( defChains, useChains, returnVariable ); if(returnVarSubstitute != null) { returnVariable.SkipReferenceCounting = true; returnVariable = returnVarSubstitute; } } return returnVariable; } // If we can find the following pattern: // tmp = local; // ... <== additional code OK, as long as local is not changed // return tmp; // then we can avoid calling AddReference on tmp and ReleaseReference on local. // Instead, just hand off the existing ref count on local on return. private static VariableExpression FindReturnVariableSubstitute( Operator[][] defChains, Operator[][] useChains, VariableExpression returnVariable ) { // Find the pattern var assignOp = ControlFlowGraphState.CheckSingleDefinition( defChains, returnVariable ) as SingleAssignmentOperator; var returnOp = ControlFlowGraphState.CheckSingleUse ( useChains, returnVariable ) as ReturnControlOperator; if(assignOp == null || returnOp == null) { return null; } var returnVarCandidate = assignOp.FirstArgument as VariableExpression; if(returnVarCandidate == null) { return null; } // If we ever take the address of the expression, assume it can be modified. foreach(Operator op in useChains[ returnVarCandidate.SpanningTreeIndex ]) { if(op is AddressAssignmentOperator) { return null; } } // Gather information about where the substitute is being defined / written var substituteDefChain = defChains[ returnVarCandidate.SpanningTreeIndex ]; var substituteDefBasicBlocks = SetFactory.New( ); foreach(Operator defOp in substituteDefChain) { substituteDefBasicBlocks.Insert( defOp.BasicBlock ); } // Starting with the basic block that the "tmp = local" assignment took place, // find out if local is being redefined in this basic block. var currentBasicBlock = assignOp.BasicBlock; if(substituteDefBasicBlocks.Contains( currentBasicBlock )) { // If true, we're OK as long as those definitions happen after the assign operator. var currentBlockDefs = new List( substituteDefChain ).FindAll( defOp => defOp.BasicBlock == currentBasicBlock ); if(currentBlockDefs.TrueForAll( defOp => defOp.GetBasicBlockIndex( ) < assignOp.GetBasicBlockIndex( ) )) { // Move on to the next basic block, as long as there's no branches var flowCtrl = currentBasicBlock.FlowControl as UnconditionalControlOperator; if(flowCtrl != null) { currentBasicBlock = flowCtrl.TargetBranch; } else { return null; } } else { return null; } } // Go through the rest of the basic blocks to make sure local is not redefined, // and the control flow is linear. while(currentBasicBlock != returnOp.BasicBlock) { if(!substituteDefBasicBlocks.Contains( currentBasicBlock )) { // Move on to the next basic block, as long as there's no branches var flowCtrl = currentBasicBlock.FlowControl as UnconditionalControlOperator; if(flowCtrl != null) { currentBasicBlock = flowCtrl.TargetBranch; } else { return null; } } else { return null; } } return returnVarCandidate; } private static BitVector FindSkippableVariables( ControlFlowGraphStateForCodeTransformation cfg, VariableExpression[] variables, Operator[][] defChains, Operator[][] useChains ) { var skippables = new BitVector( variables.Length ); // In strict mode, we assume any object can be accessed by multiple threads at the same time // so we need to take a local reference to all field / element / indirect load. var allowLoads = cfg.TypeSystem.ReferenceCountingGarbageCollectionStatus != TypeSystemForCodeTransformation.ReferenceCountingStatus.EnabledStrict; // In this initial pass, we go through each of the variable and mark off the variables that // are already marked skippable and of the wrong types, as well as calling the IsVariableSkippable // helper with the incomplete skippables information. foreach(var variable in variables) { int i = variable.SpanningTreeIndex; if( !cfg.TypeSystem.IsReferenceCountingType( variable.Type ) || variable.SkipReferenceCounting || IsVariableSkippable( defChains[ i ], useChains[ i ], skippables, allowLoads )) { skippables[ i ] = true; } } // We will repeatedly call IsVariableSkippable helper on all variables with the most up-to-date // skippables information until it stops changing. This will help us get the case where a variable // is assigned from a previously marked skippable variable. bool done; do { done = true; foreach(var variable in variables) { int i = variable.SpanningTreeIndex; if(!skippables[ i ]) { if (IsVariableSkippable( defChains[ i ], useChains[ i ], skippables, allowLoads )) { skippables[ i ] = true; done = false; } } } } while(!done); return skippables; } private static bool IsVariableSkippable( Operator[] defChain, Operator[] useChain, BitVector skippables, bool allowLoads ) { // A variable is skippable only if all its definitions match the criteria. foreach(var defOp in defChain) { if(defOp is CallOperator) { // A ref count is always passed by return, so can't skip. return false; } else if (defOp is SingleAssignmentOperator) { var assignOp = (SingleAssignmentOperator)defOp; var source = assignOp.FirstArgument; // Single assignment is OK if we're assigning from a constant or another skippable // variable. if( source is ConstantExpression || ( source is VariableExpression && skippables[ source.SpanningTreeIndex ] )) { continue; } return false; } else if(defOp is LoadInstanceFieldOperator || defOp is LoadElementOperator || defOp is LoadIndirectOperator) { if(allowLoads) { // Special case for volatile fields -- we need to properly ref count them to ensure // correctness. if(defOp is LoadInstanceFieldOperator) { var fieldOp = (LoadInstanceFieldOperator)defOp; if(( fieldOp.Field.Flags & FieldRepresentation.Attributes.IsVolatile ) != 0) { return false; } } continue; } else { return false; } } else if (defOp is InitialValueOperator) { // First assignment of an argument -- we're OK since the caller will always have a ref count continue; } else { CHECKS.ASSERT( false, "Unexpected definition operators: %s", defOp ); } } // In addition, if the variable's address is taken, we have to assume that it can be use // elsewhere where it might be addref / released, so we cannot skip it. foreach(var useOp in useChain) { if(useOp is AddressAssignmentOperator) { return false; } } return true; } } } ================================================ FILE: Zelig/Zelig/CompileTime/CodeGenerator/CodeTransformation/CompilationSteps/Handlers/OperatorHandlers_ConvertUnsupportedOperatorsToMethodCalls.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // namespace Microsoft.Zelig.CodeGeneration.IR.CompilationSteps.Handlers { using System; using System.Collections.Generic; using Microsoft.Zelig.Runtime.TypeSystem; public class OperatorHandlers_ConvertUnsupportedOperatorsToMethodCalls { //--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--// //--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--// //--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--// [CompilationSteps.PhaseFilter( typeof(Phases.ConvertUnsupportedOperatorsToMethodCalls) )] [CompilationSteps.OperatorHandler( typeof(BinaryOperator) )] private static void Handle_BinaryOperator( PhaseExecution.NotificationContext nc ) { BinaryOperator op = (BinaryOperator)nc.CurrentOperator; ControlFlowGraphStateForCodeTransformation cfg = nc.CurrentCFG; TypeSystemForCodeTransformation ts = nc.TypeSystem; WellKnownMethods wkm = ts.WellKnownMethods; VariableExpression exRes = op.FirstResult; Expression exSrc1 = op.FirstArgument; Expression exSrc2 = op.SecondArgument; TypeRepresentation tdRes = exRes .Type; TypeRepresentation tdSrc1 = exSrc1.Type; TypeRepresentation tdSrc2 = exSrc2.Type; uint sizeRes = tdRes .SizeOfHoldingVariableInWords; uint sizeSrc1 = tdSrc1.SizeOfHoldingVariableInWords; uint sizeSrc2 = tdSrc2.SizeOfHoldingVariableInWords; bool fSigned = op.Signed; if(sizeSrc1 != sizeSrc2) { switch(op.Alu) { case BinaryOperator.ALU.SHL: case BinaryOperator.ALU.SHR: CHECKS.ASSERT( sizeSrc2 == 1, "Incompatible input for {0}", op ); break; default: throw TypeConsistencyErrorException.Create( "Unsupported inputs for binary operator: {0}", op ); } } if(sizeSrc1 != sizeRes) { if(op.Alu != BinaryOperator.ALU.MUL) { throw TypeConsistencyErrorException.Create( "Unsupported inputs for binary operator: {0}", op ); } } if((tdSrc1.IsNumeric == false || tdSrc1.IsInteger) && (tdSrc2.IsNumeric == false || tdSrc2.IsInteger) ) { if(sizeSrc1 == 1) { switch(op.Alu) { case BinaryOperator.ALU.DIV: case BinaryOperator.ALU.REM: { MethodRepresentation md; if(fSigned) { switch(op.Alu) { case BinaryOperator.ALU.DIV: md = wkm.Helpers_BinaryOperations_IntDiv; break; case BinaryOperator.ALU.REM: md = wkm.Helpers_BinaryOperations_IntRem; break; default: throw TypeConsistencyErrorException.Create( "Unsupported inputs for binary operator: {0}", op ); } } else { switch(op.Alu) { case BinaryOperator.ALU.DIV: md = wkm.Helpers_BinaryOperations_UintDiv; break; case BinaryOperator.ALU.REM: md = wkm.Helpers_BinaryOperations_UintRem; break; default: throw TypeConsistencyErrorException.Create( "Unsupported inputs for binary operator: {0}", op ); } } ts.SubstituteWithCallToHelper( md, op ); nc.MarkAsModified(); } break; } } else if(sizeSrc1 == 2) { switch(op.Alu) { case BinaryOperator.ALU.MUL: case BinaryOperator.ALU.DIV: case BinaryOperator.ALU.REM: { MethodRepresentation md; if(fSigned) { switch(op.Alu) { case BinaryOperator.ALU.MUL: md = wkm.Helpers_BinaryOperations_LongMul; break; case BinaryOperator.ALU.DIV: md = wkm.Helpers_BinaryOperations_LongDiv; break; case BinaryOperator.ALU.REM: md = wkm.Helpers_BinaryOperations_LongRem; break; default: throw TypeConsistencyErrorException.Create( "Unsupported inputs for binary operator: {0}", op ); } } else { switch(op.Alu) { case BinaryOperator.ALU.MUL: md = wkm.Helpers_BinaryOperations_UlongMul; break; case BinaryOperator.ALU.DIV: md = wkm.Helpers_BinaryOperations_UlongDiv; break; case BinaryOperator.ALU.REM: md = wkm.Helpers_BinaryOperations_UlongRem; break; default: throw TypeConsistencyErrorException.Create( "Unsupported inputs for binary operator: {0}", op ); } } ts.SubstituteWithCallToHelper( md, op ); nc.MarkAsModified(); } break; case BinaryOperator.ALU.SHL: case BinaryOperator.ALU.SHR: { ConstantExpression exShift = exSrc2 as ConstantExpression; // // Conversion from 64 to 32 bits? Or from 32 to 64 bits? // if(exShift != null && exShift.Value is int && (int)exShift.Value == 32) { // // This will be expanded later. // } else { MethodRepresentation md; if(fSigned) { switch(op.Alu) { case BinaryOperator.ALU.SHL: md = wkm.Helpers_BinaryOperations_LongShl; break; case BinaryOperator.ALU.SHR: md = wkm.Helpers_BinaryOperations_LongShr; break; default: throw TypeConsistencyErrorException.Create( "Unsupported inputs for binary operator: {0}", op ); } } else { switch(op.Alu) { case BinaryOperator.ALU.SHL: md = wkm.Helpers_BinaryOperations_UlongShl; break; case BinaryOperator.ALU.SHR: md = wkm.Helpers_BinaryOperations_UlongShr; break; default: throw TypeConsistencyErrorException.Create( "Unsupported inputs for binary operator: {0}", op ); } } ts.SubstituteWithCallToHelper( md, op ); nc.MarkAsModified(); } } break; } } } } } } ================================================ FILE: Zelig/Zelig/CompileTime/CodeGenerator/CodeTransformation/CompilationSteps/Handlers/OperatorHandlers_ExpandAggregateTypes.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // namespace Microsoft.Zelig.CodeGeneration.IR.CompilationSteps.Handlers { using System; using System.Collections.Generic; using Microsoft.Zelig.Runtime.TypeSystem; public class OperatorHandlers_ExpandAggregateTypes { //--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--// //--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--// //--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--// [CompilationSteps.PhaseFilter( typeof(Phases.ExpandAggregateTypes) )] [CompilationSteps.OperatorHandler( typeof(InitialValueOperator) )] private static void Handle_InitialValueOperator( PhaseExecution.NotificationContext nc ) { InitialValueOperator op = (InitialValueOperator)nc.CurrentOperator; TypeSystemForCodeTransformation ts = nc.TypeSystem; if(ts.OperatorAlreadyInScalarForm( op ) == false) { ControlFlowGraphStateForCodeTransformation cfg = nc.CurrentCFG; Debugging.DebugInfo debugInfo = op.DebugInfo; VariableExpression exDst = op.FirstResult; Expression[] dstFragments = cfg.GetFragmentsForExpression( exDst ); foreach(Expression dstFragment in dstFragments) { InitialValueOperator opNew = InitialValueOperator.New( debugInfo, (VariableExpression)dstFragment ); opNew.CopyAnnotations( op ); op.AddOperatorBefore( opNew ); } op.Delete(); nc.MarkAsModified(); } } //--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--// //--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--// //--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--// [CompilationSteps.PhaseFilter( typeof(Phases.ExpandAggregateTypes) )] [CompilationSteps.OperatorHandler( typeof(SingleAssignmentOperator) )] private static void Handle_AssignmentOperator( PhaseExecution.NotificationContext nc ) { SingleAssignmentOperator op = (SingleAssignmentOperator)nc.CurrentOperator; TypeSystemForCodeTransformation ts = nc.TypeSystem; if(ts.OperatorAlreadyInScalarForm( op ) == false) { ControlFlowGraphStateForCodeTransformation cfg = nc.CurrentCFG; BasicBlock current = op.BasicBlock; Debugging.DebugInfo debugInfo = op.DebugInfo; Expression exSrc = op.FirstArgument; VariableExpression exDst = op.FirstResult; Expression[] srcFragments = cfg.GetFragmentsForExpression( exSrc ); Expression[] dstFragments = cfg.GetFragmentsForExpression( exDst ); uint srcSize = (uint)srcFragments.Length; uint dstSize = (uint)dstFragments.Length; if(srcSize != dstSize) { if(srcSize == 1) { for(uint offset = 0; offset < dstSize; offset++) { PartialAssignmentOperator opNew = PartialAssignmentOperator.New( debugInfo, (VariableExpression)dstFragments[offset], 0, srcFragments[0], offset ); opNew.CopyAnnotations( op ); op.AddOperatorBefore( opNew ); } op.Delete(); } else if(dstSize == 1) { for(uint offset = 0; offset < srcSize; offset++) { PartialAssignmentOperator opNew = PartialAssignmentOperator.New( debugInfo, (VariableExpression)srcFragments[0], offset, dstFragments[offset], 0 ); opNew.CopyAnnotations( op ); op.AddOperatorBefore( opNew ); } op.Delete(); } else { throw TypeConsistencyErrorException.Create( "Unexpected kind of assignment: {0}", op ); } } else { CHECKS.ASSERT( exSrc.Type.SizeOfHoldingVariableInWords == exDst.Type.SizeOfHoldingVariableInWords, "Assignments between elements of different sizes not supported at IR level: {0} <= {1}", exSrc, exDst ); if(srcSize == 1) { SingleAssignmentOperator opNew = SingleAssignmentOperator.New( debugInfo, (VariableExpression)dstFragments[0], srcFragments[0] ); op.SubstituteWithOperator( opNew, Operator.SubstitutionFlags.CopyAnnotations ); } else { for(int offset = 0; offset < srcSize; offset++) { SingleAssignmentOperator opNew = SingleAssignmentOperator.New( debugInfo, (VariableExpression)dstFragments[offset], srcFragments[offset] ); opNew.CopyAnnotations( op ); op.AddOperatorBefore( opNew ); } op.Delete(); } } nc.MarkAsModified(); } } //--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--// //--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--// //--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--// [CompilationSteps.PhaseFilter( typeof(Phases.ExpandAggregateTypes) )] [CompilationSteps.OperatorHandler( typeof(AddressAssignmentOperator) )] private static void Handle_AddressAssignmentOperator( PhaseExecution.NotificationContext nc ) { AddressAssignmentOperator op = (AddressAssignmentOperator)nc.CurrentOperator; TypeSystemForCodeTransformation ts = nc.TypeSystem; if(ts.OperatorAlreadyInScalarForm( op ) == false) { ControlFlowGraphStateForCodeTransformation cfg = nc.CurrentCFG; BasicBlock current = op.BasicBlock; Debugging.DebugInfo debugInfo = op.DebugInfo; Expression exSrc = op.FirstArgument; VariableExpression exDst = op.FirstResult; Expression[] srcFragments = cfg.GetFragmentsForExpression( exSrc ); Expression[] dstFragments = cfg.GetFragmentsForExpression( exDst ); CHECKS.ASSERT( exDst.Type.SizeOfHoldingVariableInWords == 1, "Pointer {0} is wider than a word", exDst ); CHECKS.ASSERT( srcFragments[0] is StackLocationExpression , "Cannot take address of {0}, expecting a stack location", srcFragments[0] ); AddressAssignmentOperator opNew = AddressAssignmentOperator.New( debugInfo, (VariableExpression)dstFragments[0], srcFragments[0] ); op.SubstituteWithOperator( opNew, Operator.SubstitutionFlags.CopyAnnotations ); opNew.AddAnnotation( NotNullAnnotation.Create( ts ) ); nc.MarkAsModified(); } } //--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--// //--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--// //--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--// [CompilationSteps.PhaseFilter( typeof(Phases.ExpandAggregateTypes) )] [CompilationSteps.OperatorHandler( typeof(CompareConditionalControlOperator) )] private static void Handle_CompareConditionalControlOperator( PhaseExecution.NotificationContext nc ) { CompareConditionalControlOperator op = (CompareConditionalControlOperator)nc.CurrentOperator; //--// ControlFlowGraphStateForCodeTransformation cfg = nc.CurrentCFG; Debugging.DebugInfo debugInfo = op.DebugInfo; Expression exSrc1 = op.FirstArgument; Expression exSrc2 = op.SecondArgument; Expression[] src1Fragments = cfg.GetFragmentsForExpression( exSrc1 ); Expression[] src2Fragments = cfg.GetFragmentsForExpression( exSrc2 ); TypeRepresentation tdSrc1 = exSrc1.Type; TypeRepresentation tdSrc2 = exSrc2.Type; uint sizeSrc1 = tdSrc1.SizeOfHoldingVariableInWords; uint sizeSrc2 = tdSrc2.SizeOfHoldingVariableInWords; bool fSigned = op.Signed; CHECKS.ASSERT( sizeSrc1 == sizeSrc2, "Cannot compare entities of different size: {0} <=> {1}", exSrc1, exSrc2 ); //--// ConditionCodeExpression.Comparison condition; switch(op.Condition) { case CompareAndSetOperator.ActionCondition.EQ: condition = ConditionCodeExpression.Comparison.Equal; break; case CompareAndSetOperator.ActionCondition.GE: if(fSigned) { condition = ConditionCodeExpression.Comparison.SignedGreaterThanOrEqual; } else { condition = ConditionCodeExpression.Comparison.UnsignedHigherThanOrSame; } break; case CompareAndSetOperator.ActionCondition.GT: if(fSigned) { condition = ConditionCodeExpression.Comparison.SignedGreaterThan; } else { condition = ConditionCodeExpression.Comparison.UnsignedHigherThan; } break; case CompareAndSetOperator.ActionCondition.LE: if(fSigned) { condition = ConditionCodeExpression.Comparison.SignedLessThanOrEqual; } else { condition = ConditionCodeExpression.Comparison.UnsignedLowerThanOrSame; } break; case CompareAndSetOperator.ActionCondition.LT: if(fSigned) { condition = ConditionCodeExpression.Comparison.SignedLessThan; } else { condition = ConditionCodeExpression.Comparison.UnsignedLowerThan; } break; case CompareAndSetOperator.ActionCondition.NE: condition = ConditionCodeExpression.Comparison.NotEqual; break; default: throw TypeConsistencyErrorException.Create( "Unexpected value {0} in {1}", op.Condition, op ); } //--// if(exSrc1 is ConstantExpression) { // // Swap the left and right operands and change the direction of disequality conditions. // Expression[] tmp; tmp = src1Fragments; src1Fragments = src2Fragments; src2Fragments = tmp; switch(condition) { case ConditionCodeExpression.Comparison.Equal : /* Keep the same */ break; case ConditionCodeExpression.Comparison.NotEqual : /* Keep the same */ break; case ConditionCodeExpression.Comparison.UnsignedHigherThanOrSame : condition = ConditionCodeExpression.Comparison.UnsignedLowerThanOrSame ; break; case ConditionCodeExpression.Comparison.UnsignedLowerThan : condition = ConditionCodeExpression.Comparison.UnsignedHigherThan ; break; case ConditionCodeExpression.Comparison.UnsignedHigherThan : condition = ConditionCodeExpression.Comparison.UnsignedLowerThan ; break; case ConditionCodeExpression.Comparison.UnsignedLowerThanOrSame : condition = ConditionCodeExpression.Comparison.UnsignedHigherThanOrSame; break; case ConditionCodeExpression.Comparison.SignedGreaterThanOrEqual : condition = ConditionCodeExpression.Comparison.SignedLessThanOrEqual ; break; case ConditionCodeExpression.Comparison.SignedLessThan : condition = ConditionCodeExpression.Comparison.SignedGreaterThan ; break; case ConditionCodeExpression.Comparison.SignedGreaterThan : condition = ConditionCodeExpression.Comparison.SignedLessThan ; break; case ConditionCodeExpression.Comparison.SignedLessThanOrEqual : condition = ConditionCodeExpression.Comparison.SignedGreaterThanOrEqual; break; default: throw TypeConsistencyErrorException.Create( "Unsupported compare operation: {0}", op ); } } if(tdSrc1.IsFloatingPoint && tdSrc2.IsFloatingPoint ) { CHECKS.ASSERT( src1Fragments.Length == 1, "Expecting left argument in a single floating point register: {0}" , op ); CHECKS.ASSERT( src2Fragments.Length == 1, "Expecting right argument in a single floating point register: {0}", op ); ConditionCodeExpression cc = cfg.AllocateConditionCode(); op.AddOperatorBefore( CompareOperator.New( debugInfo, cc, src1Fragments[0], src2Fragments[0] ) ); //--// ConditionCodeConditionalControlOperator opNew = ConditionCodeConditionalControlOperator.New( debugInfo, condition, cc, op.TargetBranchNotTaken, op.TargetBranchTaken ); op.SubstituteWithOperator( opNew, Operator.SubstitutionFlags.Default ); } else if((tdSrc1.IsNumeric == false || tdSrc1.IsInteger) && (tdSrc2.IsNumeric == false || tdSrc2.IsInteger) ) { ConditionCodeExpression cc = cfg.AllocateConditionCode(); if(sizeSrc1 == 1) { op.AddOperatorBefore( CompareOperator.New( debugInfo, cc, src1Fragments[0], src2Fragments[0] ) ); //--// ConditionCodeConditionalControlOperator opNew = ConditionCodeConditionalControlOperator.New( debugInfo, condition, cc, op.TargetBranchNotTaken, op.TargetBranchTaken ); op.SubstituteWithOperator( opNew, Operator.SubstitutionFlags.Default ); } else if(sizeSrc1 == 2) { op.AddOperatorBefore( LongCompareOperator.New( debugInfo, cc, src1Fragments[0], src1Fragments[1], src2Fragments[0], src2Fragments[1] ) ); //--// ConditionCodeConditionalControlOperator opNew = ConditionCodeConditionalControlOperator.New( debugInfo, condition, cc, op.TargetBranchNotTaken, op.TargetBranchTaken ); op.SubstituteWithOperator( opNew, Operator.SubstitutionFlags.Default ); } else { throw TypeConsistencyErrorException.Create( "Unsupported compare operation larger than 64 bits: {0}", op ); } } else { throw TypeConsistencyErrorException.Create( "Unsupported mixed-mode compare operation: {0}", op ); } nc.MarkAsModified(); } //--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--// //--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--// //--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--// [CompilationSteps.PhaseFilter( typeof(Phases.ExpandAggregateTypes) )] [CompilationSteps.OperatorHandler( typeof(CompareAndSetOperator) )] private static void Handle_CompareAndSetOperator( PhaseExecution.NotificationContext nc ) { CompareAndSetOperator op = (CompareAndSetOperator)nc.CurrentOperator; //--// ControlFlowGraphStateForCodeTransformation cfg = nc.CurrentCFG; TypeSystemForCodeTransformation ts = nc.TypeSystem; BasicBlock current = op.BasicBlock; Debugging.DebugInfo debugInfo = op.DebugInfo; VariableExpression exRes = op.FirstResult; Expression exSrc1 = op.FirstArgument; Expression exSrc2 = op.SecondArgument; Expression[] resFragments = cfg.GetFragmentsForExpression( exRes ); Expression[] src1Fragments = cfg.GetFragmentsForExpression( exSrc1 ); Expression[] src2Fragments = cfg.GetFragmentsForExpression( exSrc2 ); TypeRepresentation tdSrc1 = exSrc1.Type; TypeRepresentation tdSrc2 = exSrc2.Type; uint sizeSrc1 = tdSrc1.SizeOfHoldingVariableInWords; uint sizeSrc2 = tdSrc2.SizeOfHoldingVariableInWords; bool fSigned = op.Signed; CHECKS.ASSERT( resFragments.Length == 1, "The lvalue of CompareAndSetOperator should be a 32bit word: {0}", op ); CHECKS.ASSERT( sizeSrc1 == sizeSrc2, "Cannot compare entities of different size: {0} <=> {1}", exSrc1, exSrc2 ); //--// ConditionCodeExpression.Comparison condition; switch(op.Condition) { case CompareAndSetOperator.ActionCondition.EQ: condition = ConditionCodeExpression.Comparison.Equal; break; case CompareAndSetOperator.ActionCondition.GE: if(fSigned) { condition = ConditionCodeExpression.Comparison.SignedGreaterThanOrEqual; } else { condition = ConditionCodeExpression.Comparison.UnsignedHigherThanOrSame; } break; case CompareAndSetOperator.ActionCondition.GT: if(fSigned) { condition = ConditionCodeExpression.Comparison.SignedGreaterThan; } else { condition = ConditionCodeExpression.Comparison.UnsignedHigherThan; } break; case CompareAndSetOperator.ActionCondition.LE: if(fSigned) { condition = ConditionCodeExpression.Comparison.SignedLessThanOrEqual; } else { condition = ConditionCodeExpression.Comparison.UnsignedLowerThanOrSame; } break; case CompareAndSetOperator.ActionCondition.LT: if(fSigned) { condition = ConditionCodeExpression.Comparison.SignedLessThan; } else { condition = ConditionCodeExpression.Comparison.UnsignedLowerThan; } break; case CompareAndSetOperator.ActionCondition.NE: condition = ConditionCodeExpression.Comparison.NotEqual; break; default: throw TypeConsistencyErrorException.Create( "Unexpected value {0} in {1}", op.Condition, op ); } //--// if(exSrc1 is ConstantExpression) { // // Swap the left and right operands and change the direction of disequality conditions. // Expression[] tmp; tmp = src1Fragments; src1Fragments = src2Fragments; src2Fragments = tmp; switch(condition) { case ConditionCodeExpression.Comparison.Equal : /* Keep the same */ break; case ConditionCodeExpression.Comparison.NotEqual : /* Keep the same */ break; case ConditionCodeExpression.Comparison.UnsignedHigherThanOrSame : condition = ConditionCodeExpression.Comparison.UnsignedLowerThanOrSame ; break; case ConditionCodeExpression.Comparison.UnsignedLowerThan : condition = ConditionCodeExpression.Comparison.UnsignedHigherThan ; break; case ConditionCodeExpression.Comparison.UnsignedHigherThan : condition = ConditionCodeExpression.Comparison.UnsignedLowerThan ; break; case ConditionCodeExpression.Comparison.UnsignedLowerThanOrSame : condition = ConditionCodeExpression.Comparison.UnsignedHigherThanOrSame; break; case ConditionCodeExpression.Comparison.SignedGreaterThanOrEqual : condition = ConditionCodeExpression.Comparison.SignedLessThanOrEqual ; break; case ConditionCodeExpression.Comparison.SignedLessThan : condition = ConditionCodeExpression.Comparison.SignedGreaterThan ; break; case ConditionCodeExpression.Comparison.SignedGreaterThan : condition = ConditionCodeExpression.Comparison.SignedLessThan ; break; case ConditionCodeExpression.Comparison.SignedLessThanOrEqual : condition = ConditionCodeExpression.Comparison.SignedGreaterThanOrEqual; break; default: throw TypeConsistencyErrorException.Create( "Unsupported compare operation: {0}", op ); } } if(tdSrc1.IsFloatingPoint && tdSrc2.IsFloatingPoint ) { CHECKS.ASSERT( src1Fragments.Length == 1, "Expecting left argument in a single floating point register: {0}" , op ); CHECKS.ASSERT( src2Fragments.Length == 1, "Expecting right argument in a single floating point register: {0}", op ); ConditionCodeExpression cc = cfg.AllocateConditionCode(); op.AddOperatorBefore( CompareOperator.New( debugInfo, cc, src1Fragments[0], src2Fragments[0] ) ); //--// SetIfConditionIsTrueOperator opNew = SetIfConditionIsTrueOperator.New( debugInfo, condition, (VariableExpression)resFragments[0], cc ); op.SubstituteWithOperator( opNew, Operator.SubstitutionFlags.Default ); } else if((tdSrc1.IsNumeric == false || tdSrc1.IsInteger) && (tdSrc2.IsNumeric == false || tdSrc2.IsInteger) ) { ConditionCodeExpression cc = cfg.AllocateConditionCode(); if(sizeSrc1 == 1) { op.AddOperatorBefore( CompareOperator.New( debugInfo, cc, src1Fragments[0], src2Fragments[0] ) ); //--// SetIfConditionIsTrueOperator opNew = SetIfConditionIsTrueOperator.New( debugInfo, condition, (VariableExpression)resFragments[0], cc ); op.SubstituteWithOperator( opNew, Operator.SubstitutionFlags.Default ); } else if(sizeSrc1 == 2) { op.AddOperatorBefore( LongCompareOperator.New( debugInfo, cc, src1Fragments[0], src1Fragments[1], src2Fragments[0], src2Fragments[1] ) ); //--// SetIfConditionIsTrueOperator opNew = SetIfConditionIsTrueOperator.New( debugInfo, condition, (VariableExpression)resFragments[0], cc ); op.SubstituteWithOperator( opNew, Operator.SubstitutionFlags.Default ); } else { throw TypeConsistencyErrorException.Create( "Unsupported compare operation larger than 64 bits: {0}", op ); } } else { throw TypeConsistencyErrorException.Create( "Unsupported mixed-mode compare operation: {0}", op ); } nc.MarkAsModified(); } //--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--// //--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--// //--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--// [CompilationSteps.PhaseFilter( typeof(Phases.ExpandAggregateTypes) )] [CompilationSteps.OperatorHandler( typeof(AbstractBinaryOperator) )] private static void Handle_BinaryOperator( PhaseExecution.NotificationContext nc ) { var op = (AbstractBinaryOperator)nc.CurrentOperator; TypeSystemForCodeTransformation ts = nc.TypeSystem; if(ts.OperatorAlreadyInScalarForm( op ) == false) { ControlFlowGraphStateForCodeTransformation cfg = nc.CurrentCFG; BasicBlock current = op.BasicBlock; Debugging.DebugInfo debugInfo = op.DebugInfo; VariableExpression exRes = op.FirstResult; Expression exSrc1 = op.FirstArgument; Expression exSrc2 = op.SecondArgument; Expression[] resFragments = cfg.GetFragmentsForExpression( exRes ); Expression[] src1Fragments = cfg.GetFragmentsForExpression( exSrc1 ); Expression[] src2Fragments = cfg.GetFragmentsForExpression( exSrc2 ); TypeRepresentation tdRes = exRes .Type; TypeRepresentation tdSrc1 = exSrc1.Type; TypeRepresentation tdSrc2 = exSrc2.Type; uint sizeRes = tdRes .SizeOfHoldingVariableInWords; uint sizeSrc1 = tdSrc1.SizeOfHoldingVariableInWords; uint sizeSrc2 = tdSrc2.SizeOfHoldingVariableInWords; bool fSigned = op.Signed; var alu = op.Alu; if(sizeSrc1 != sizeSrc2) { switch(op.Alu) { case BinaryOperator.ALU.SHL: case BinaryOperator.ALU.SHR: CHECKS.ASSERT( sizeSrc2 == 1, "Incompatible input for {0}", op ); break; default: throw TypeConsistencyErrorException.Create( "Unsupported inputs for binary operator: {0}", op ); } } if(sizeSrc1 != sizeRes) { if(alu != BinaryOperator.ALU.MUL) { throw TypeConsistencyErrorException.Create( "Unsupported inputs for binary operator: {0}", op ); } } if(tdSrc1.IsFloatingPoint && tdSrc2.IsFloatingPoint ) { CHECKS.ASSERT( resFragments .Length == 1, "Expecting result in a single floating point register: {0}" , op ); CHECKS.ASSERT( src1Fragments.Length == 1, "Expecting left argument in a single floating point register: {0}" , op ); CHECKS.ASSERT( src2Fragments.Length == 1, "Expecting right argument in a single floating point register: {0}", op ); VariableExpression newRes = (VariableExpression)resFragments [0]; Expression newSrc1 = src1Fragments[0]; Expression newSrc2 = src2Fragments[0]; AbstractBinaryOperator opNew; if (op is BinaryOperator ) { opNew = BinaryOperator .New( debugInfo, alu, fSigned, false, newRes, newSrc1, newSrc2 ); } else if(op is BinaryOperatorWithCarryIn ) { opNew = BinaryOperatorWithCarryIn .New( debugInfo, alu, fSigned, false, newRes, newSrc1, newSrc2, (VariableExpression)op.ThirdArgument ); } else if(op is BinaryOperatorWithCarryInAndOut) { opNew = BinaryOperatorWithCarryInAndOut.New( debugInfo, alu, fSigned, false, newRes, op.SecondResult, newSrc1, newSrc2, (VariableExpression)op.ThirdArgument ); } else if(op is BinaryOperatorWithCarryOut ) { opNew = BinaryOperatorWithCarryOut .New( debugInfo, alu, fSigned, false, newRes, op.SecondResult, newSrc1, newSrc2 ); } else { throw TypeConsistencyErrorException.Create( "Unsupported inputs for binary operator: {0}", op ); } op.SubstituteWithOperator( opNew, Operator.SubstitutionFlags.CopyAnnotations ); } else if((tdSrc1.IsNumeric == false || tdSrc1.IsInteger) && (tdSrc2.IsNumeric == false || tdSrc2.IsInteger) ) { if(sizeSrc1 == 1) { switch(alu) { case BinaryOperator.ALU.DIV: case BinaryOperator.ALU.REM: { // // These should have been removed by a previous phase. // throw TypeConsistencyErrorException.Create( "Unexpected operator: {0}", op ); } default: if(sizeRes == 1) { VariableExpression newRes = (VariableExpression)resFragments [0]; Expression newSrc1 = src1Fragments[0]; Expression newSrc2 = src2Fragments[0]; AbstractBinaryOperator opNew; if (op is BinaryOperator ) { opNew = BinaryOperator .New( debugInfo, alu, fSigned, false, newRes, newSrc1, newSrc2 ); } else if(op is BinaryOperatorWithCarryIn ) { opNew = BinaryOperatorWithCarryIn .New( debugInfo, alu, fSigned, false, newRes, newSrc1, newSrc2, (VariableExpression)op.ThirdArgument ); } else if(op is BinaryOperatorWithCarryInAndOut) { opNew = BinaryOperatorWithCarryInAndOut.New( debugInfo, alu, fSigned, false, newRes, op.SecondResult, newSrc1, newSrc2, (VariableExpression)op.ThirdArgument ); } else if(op is BinaryOperatorWithCarryOut ) { opNew = BinaryOperatorWithCarryOut .New( debugInfo, alu, fSigned, false, newRes, op.SecondResult, newSrc1, newSrc2 ); } else { throw TypeConsistencyErrorException.Create( "Unsupported inputs for binary operator: {0}", op ); } op.SubstituteWithOperator( opNew, Operator.SubstitutionFlags.CopyAnnotations ); } else if(sizeRes == 2) { VariableExpression newResLo = (VariableExpression)resFragments [0]; VariableExpression newResHi = (VariableExpression)resFragments [1]; Expression newSrc1 = src1Fragments[0]; Expression newSrc2 = src2Fragments[0]; if(op is BinaryOperator) { var opNew = LongBinaryOperator.New( debugInfo, alu, fSigned, false, newResLo, newResHi, newSrc1, newSrc2 ); op.SubstituteWithOperator( opNew, Operator.SubstitutionFlags.CopyAnnotations ); } else { throw TypeConsistencyErrorException.Create( "Unsupported inputs for binary operator: {0}", op ); } } else { throw TypeConsistencyErrorException.Create( "Unexpected operator: {0}", op ); } break; } } else if(sizeSrc1 == 2) { switch(alu) { case BinaryOperator.ALU.ADD: case BinaryOperator.ALU.SUB: if(op is BinaryOperator) { ConditionCodeExpression cc = cfg.AllocateConditionCode(); var opLow = BinaryOperatorWithCarryOut.New( debugInfo, alu, fSigned, false, (VariableExpression)resFragments[0], cc, src1Fragments[0], src2Fragments[0] ); op.AddOperatorBefore( opLow ); var opHigh = BinaryOperatorWithCarryIn.New( debugInfo, alu, fSigned, false, (VariableExpression)resFragments[1], src1Fragments[1], src2Fragments[1], cc ); op.AddOperatorBefore( opHigh ); } else { throw TypeConsistencyErrorException.Create( "Unsupported inputs for binary operator: {0}", op ); } break; case BinaryOperator.ALU.MUL: case BinaryOperator.ALU.DIV: case BinaryOperator.ALU.REM: { // // These should have been removed by a previous phase. // throw TypeConsistencyErrorException.Create( "Unexpected operator: {0}", op ); } case BinaryOperator.ALU.AND: case BinaryOperator.ALU.OR : case BinaryOperator.ALU.XOR: if(op is BinaryOperator) { BinaryOperator opLow = BinaryOperator.New( debugInfo, alu, fSigned, false, (VariableExpression)resFragments[0], src1Fragments[0], src2Fragments[0] ); op.AddOperatorBefore( opLow ); BinaryOperator opHigh = BinaryOperator.New( debugInfo, alu, fSigned, false, (VariableExpression)resFragments[1], src1Fragments[1], src2Fragments[1] ); op.AddOperatorBefore( opHigh ); } else { throw TypeConsistencyErrorException.Create( "Unsupported inputs for binary operator: {0}", op ); } break; case BinaryOperator.ALU.SHL: case BinaryOperator.ALU.SHR: if(op is BinaryOperator) { ConstantExpression exShift = src2Fragments[0] as ConstantExpression; // // Conversion from 64 to 32 bits? Or from 32 to 64 bits? // if(exShift != null && exShift.Value is int && (int)exShift.Value == 32) { Operator opLow; Operator opHigh; switch(alu) { case BinaryOperator.ALU.SHL: // // Assign low part of Left to high part of Res, clear low part of Res. // opLow = SingleAssignmentOperator.New( debugInfo, (VariableExpression)resFragments[0], ts.CreateConstant( (int)0 ) ); opHigh = SingleAssignmentOperator.New( debugInfo, (VariableExpression)resFragments[1], src1Fragments[0] ); break; case BinaryOperator.ALU.SHR: if(fSigned) { // // Assign high part of Left to low part of Res, sign extend high part of Res. // opLow = SingleAssignmentOperator.New( debugInfo, (VariableExpression)resFragments[0], src1Fragments[1] ); opHigh = BinaryOperator .New( debugInfo, BinaryOperator.ALU.SHR, true, false, (VariableExpression)resFragments[1], src1Fragments[1], ts.CreateConstant( (int)31 ) ); } else { // // Assign high part of Left to low part of Res, clear high part of Res. // opLow = SingleAssignmentOperator.New( debugInfo, (VariableExpression)resFragments[0], src1Fragments[1] ); opHigh = SingleAssignmentOperator.New( debugInfo, (VariableExpression)resFragments[1], ts.CreateConstant( (int)0 ) ); } break; default: throw TypeConsistencyErrorException.Create( "Unsupported inputs for binary operator: {0}", op ); } op.AddOperatorBefore ( opLow ); op.SubstituteWithOperator( opHigh, Operator.SubstitutionFlags.Default ); } else { // // These should have been removed by a previous phase. // throw TypeConsistencyErrorException.Create( "Unexpected operator: {0}", op ); } } else { throw TypeConsistencyErrorException.Create( "Unsupported inputs for binary operator: {0}", op ); } break; default: throw TypeConsistencyErrorException.Create( "Unsupported inputs for binary operator: {0}", op ); } op.Delete(); } else { throw TypeConsistencyErrorException.Create( "Unsupported inputs for binary operator: {0}", op ); } } else { throw TypeConsistencyErrorException.Create( "Unsupported inputs for binary operator: {0}", op ); } nc.MarkAsModified(); } } //--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--// //--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--// //--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--// [CompilationSteps.PhaseFilter( typeof(Phases.ExpandAggregateTypes) )] [CompilationSteps.OperatorHandler( typeof(AbstractUnaryOperator) )] private static void Handle_UnaryOperator( PhaseExecution.NotificationContext nc ) { var op = (AbstractUnaryOperator)nc.CurrentOperator; var ts = nc.TypeSystem; if(ts.OperatorAlreadyInScalarForm( op ) == false) { ControlFlowGraphStateForCodeTransformation cfg = nc.CurrentCFG; Debugging.DebugInfo debugInfo = op.DebugInfo; VariableExpression exRes = op.FirstResult; Expression exSrc = op.FirstArgument; Expression[] resFragments = cfg.GetFragmentsForExpression( exRes ); Expression[] srcFragments = cfg.GetFragmentsForExpression( exSrc ); TypeRepresentation tdSrc = exSrc.Type; uint sizeSrc = tdSrc.SizeOfHoldingVariableInWords; bool fSigned = op.Signed; var alu = op.Alu; if(tdSrc.IsFloatingPoint) { if(op is UnaryOperator) { } else { throw TypeConsistencyErrorException.Create( "Unsupported inputs for unary operator: {0}", op ); } CHECKS.ASSERT( resFragments.Length == 1, "Expecting result in a single floating point register: {0}" , op ); CHECKS.ASSERT( srcFragments.Length == 1, "Expecting left argument in a single floating point register: {0}" , op ); VariableExpression newRes = (VariableExpression)resFragments[0]; Expression newSrc = srcFragments[0]; UnaryOperator opNew = UnaryOperator.New( debugInfo, alu, fSigned, false, newRes, newSrc ); op.SubstituteWithOperator( opNew, Operator.SubstitutionFlags.Default ); } else if(tdSrc.IsNumeric == false || tdSrc.IsInteger) { if(sizeSrc == 1) { VariableExpression newRes = (VariableExpression)resFragments[0]; Expression newSrc = srcFragments[0]; AbstractUnaryOperator opNew; if (op is UnaryOperator ) { opNew = UnaryOperator .New( debugInfo, alu, fSigned, false, newRes, newSrc ); } else if(op is UnaryOperatorWithCarryOut) { opNew = UnaryOperatorWithCarryOut.New( debugInfo, alu, fSigned, false, newRes, op.SecondResult, newSrc ); } else { throw TypeConsistencyErrorException.Create( "Unsupported inputs for unary operator: {0}", op ); } op.SubstituteWithOperator( opNew, Operator.SubstitutionFlags.Default ); } else if(sizeSrc == 2) { switch(alu) { case UnaryOperator.ALU.NEG: if(op is UnaryOperator) { ConditionCodeExpression cc = cfg.AllocateConditionCode(); var opLow = BinaryOperatorWithCarryOut.New( debugInfo, BinaryOperator.ALU.SUB, fSigned, false, (VariableExpression)resFragments[0], cc, ts.CreateConstant( (int)0 ), srcFragments[0] ); op.AddOperatorBefore( opLow ); var opHigh = BinaryOperatorWithCarryIn.New( debugInfo, BinaryOperator.ALU.SUB, fSigned, false, (VariableExpression)resFragments[1], ts.CreateConstant( (int)0 ), srcFragments[1], cc ); op.AddOperatorBefore( opHigh ); } else { throw TypeConsistencyErrorException.Create( "Unsupported inputs for unary operator: {0}", op ); } break; case UnaryOperator.ALU.NOT: if(op is UnaryOperator) { UnaryOperator opLow = UnaryOperator.New( debugInfo, alu, fSigned, false, (VariableExpression)resFragments[0], srcFragments[0] ); op.AddOperatorBefore( opLow ); UnaryOperator opHigh = UnaryOperator.New( debugInfo, alu, fSigned, false, (VariableExpression)resFragments[1], srcFragments[1] ); op.AddOperatorBefore( opHigh ); } else { throw TypeConsistencyErrorException.Create( "Unsupported inputs for unary operator: {0}", op ); } break; default: throw TypeConsistencyErrorException.Create( "Unsupported inputs for binary operator: {0}", op ); } op.Delete(); } else { throw TypeConsistencyErrorException.Create( "Unsupported inputs for unary operator: {0}", op ); } } else { throw TypeConsistencyErrorException.Create( "Unsupported inputs for unary operator: {0}", op ); } nc.MarkAsModified(); } } //--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--// //--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--// //--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--// [CompilationSteps.PhaseFilter( typeof(Phases.ExpandAggregateTypes) )] [CompilationSteps.OperatorHandler( typeof(ConvertOperator) )] private static void Handle_ConvertOperator( PhaseExecution.NotificationContext nc ) { ConvertOperator op = (ConvertOperator)nc.CurrentOperator; TypeSystemForCodeTransformation ts = nc.TypeSystem; if(ts.OperatorAlreadyInScalarForm( op ) == false) { ControlFlowGraphStateForCodeTransformation cfg = nc.CurrentCFG; BasicBlock current = op.BasicBlock; Debugging.DebugInfo debugInfo = op.DebugInfo; VariableExpression exRes = op.FirstResult; Expression exSrc = op.FirstArgument; Expression[] resFragments = cfg.GetFragmentsForExpression( exRes ); Expression[] srcFragments = cfg.GetFragmentsForExpression( exSrc ); CHECKS.ASSERT( resFragments.Length == 1, "Expecting result of conversion to fit in one register: {0}" , op ); CHECKS.ASSERT( srcFragments.Length == 1, "Expecting argument of conversion to fit in one register: {0}", op ); VariableExpression newRes = (VariableExpression)resFragments[0]; Expression newSrc = srcFragments[0]; ConvertOperator opNew = ConvertOperator.New( debugInfo, op.InputKind, op.OutputKind, op.CheckOverflow, newRes, newSrc ); op.SubstituteWithOperator( opNew, Operator.SubstitutionFlags.CopyAnnotations ); nc.MarkAsModified(); } } //--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--// //--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--// //--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--// [CompilationSteps.PhaseFilter( typeof(Phases.ExpandAggregateTypes) )] [CompilationSteps.OperatorHandler( typeof(SignExtendOperator) )] private static void Handle_SignExtendOperator( PhaseExecution.NotificationContext nc ) { SignExtendOperator op = (SignExtendOperator)nc.CurrentOperator; TypeSystemForCodeTransformation ts = nc.TypeSystem; if(ts.OperatorAlreadyInScalarForm( op ) == false) { ControlFlowGraphStateForCodeTransformation cfg = nc.CurrentCFG; BasicBlock current = op.BasicBlock; Debugging.DebugInfo debugInfo = op.DebugInfo; VariableExpression exRes = op.FirstResult; Expression exSrc = op.FirstArgument; Expression[] resFragments = cfg.GetFragmentsForExpression( exRes ); Expression[] srcFragments = cfg.GetFragmentsForExpression( exSrc ); uint sizeRes = exRes.Type.SizeOfHoldingVariableInWords; uint sizeSrc = exSrc.Type.SizeOfHoldingVariableInWords; if(sizeRes == 1 && sizeSrc == 1) { VariableExpression newRes = (VariableExpression)resFragments[0]; Expression newSrc = srcFragments[0]; SignExtendOperator opNew = SignExtendOperator.New( debugInfo, op.SignificantSize, false, newRes, newSrc ); op.SubstituteWithOperator( opNew, Operator.SubstitutionFlags.CopyAnnotations ); } else if(sizeRes == 2 && sizeSrc == 1) { VariableExpression newResLo = (VariableExpression)resFragments[0]; VariableExpression newResHi = (VariableExpression)resFragments[1]; Expression newSrc = srcFragments[0]; if(op.SignificantSize < 4) { op.AddOperatorBefore( SignExtendOperator.New( debugInfo, op.SignificantSize, false, newResLo, newSrc ) ); } else { op.AddOperatorBefore( SingleAssignmentOperator.New( debugInfo, newResLo, newSrc ) ); } // // Copy the sign bit through the high word. // BinaryOperator opNew = BinaryOperator.New( debugInfo, BinaryOperator.ALU.SHR, true, false, newResHi, newResLo, ts.CreateConstant( 31 ) ); op.SubstituteWithOperator( opNew, Operator.SubstitutionFlags.Default ); } else { throw TypeConsistencyErrorException.Create( "Unsupported inputs for sign extension: {0}", op ); } nc.MarkAsModified(); } } //--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--// //--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--// //--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--// [CompilationSteps.PhaseFilter( typeof(Phases.ExpandAggregateTypes) )] [CompilationSteps.OperatorHandler( typeof(ZeroExtendOperator) )] private static void Handle_ZeroExtendOperator( PhaseExecution.NotificationContext nc ) { ZeroExtendOperator op = (ZeroExtendOperator)nc.CurrentOperator; TypeSystemForCodeTransformation ts = nc.TypeSystem; if(ts.OperatorAlreadyInScalarForm( op ) == false) { ControlFlowGraphStateForCodeTransformation cfg = nc.CurrentCFG; BasicBlock current = op.BasicBlock; Debugging.DebugInfo debugInfo = op.DebugInfo; VariableExpression exRes = op.FirstResult; Expression exSrc = op.FirstArgument; Expression[] resFragments = cfg.GetFragmentsForExpression( exRes ); Expression[] srcFragments = cfg.GetFragmentsForExpression( exSrc ); uint sizeRes = exRes.Type.SizeOfHoldingVariableInWords; uint sizeSrc = exSrc.Type.SizeOfHoldingVariableInWords; if(sizeRes == 1 && sizeSrc == 1) { VariableExpression newRes = (VariableExpression)resFragments[0]; Expression newSrc = srcFragments[0]; ZeroExtendOperator opNew = ZeroExtendOperator.New( debugInfo, op.SignificantSize, false, newRes, newSrc ); op.SubstituteWithOperator( opNew, Operator.SubstitutionFlags.Default ); } else if(sizeRes == 2 && sizeSrc == 1) { VariableExpression newResLo = (VariableExpression)resFragments[0]; VariableExpression newResHi = (VariableExpression)resFragments[1]; Expression newSrc = srcFragments[0]; if(op.SignificantSize < 4) { op.AddOperatorBefore( ZeroExtendOperator.New( debugInfo, op.SignificantSize, false, newResLo, newSrc ) ); } else { op.AddOperatorBefore( SingleAssignmentOperator.New( debugInfo, newResLo, newSrc ) ); } // // Clear high word. // var opNew = SingleAssignmentOperator.New( debugInfo, newResHi, ts.CreateConstant( newResHi.Type, 0 ) ); op.SubstituteWithOperator( opNew, Operator.SubstitutionFlags.Default ); } else { throw TypeConsistencyErrorException.Create( "Unsupported inputs for sign extension: {0}", op ); } nc.MarkAsModified(); } } //--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--// //--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--// //--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--// [CompilationSteps.PhaseFilter( typeof(Phases.ExpandAggregateTypes) )] [CompilationSteps.OperatorHandler( typeof(TruncateOperator) )] private static void Handle_TruncateOperator( PhaseExecution.NotificationContext nc ) { TruncateOperator op = (TruncateOperator)nc.CurrentOperator; TypeSystemForCodeTransformation ts = nc.TypeSystem; if(ts.OperatorAlreadyInScalarForm( op ) == false) { ControlFlowGraphStateForCodeTransformation cfg = nc.CurrentCFG; BasicBlock current = op.BasicBlock; Debugging.DebugInfo debugInfo = op.DebugInfo; VariableExpression exRes = op.FirstResult; Expression exSrc = op.FirstArgument; Expression[] resFragments = cfg.GetFragmentsForExpression( exRes ); Expression[] srcFragments = cfg.GetFragmentsForExpression( exSrc ); uint sizeRes = exRes.Type.SizeOfHoldingVariableInWords; uint sizeSrc = exSrc.Type.SizeOfHoldingVariableInWords; if(sizeRes == 1 && sizeSrc == 1) { VariableExpression newRes = (VariableExpression)resFragments[0]; Expression newSrc = srcFragments[0]; TruncateOperator opNew = TruncateOperator.New( debugInfo, op.SignificantSize, false, newRes, newSrc ); op.SubstituteWithOperator( opNew, Operator.SubstitutionFlags.Default ); } else if(sizeRes == 1 && sizeSrc == 2) { VariableExpression newRes = (VariableExpression)resFragments[0]; Expression newSrcLo = srcFragments[0]; Expression newSrcHi = srcFragments[1]; Operator opNew; if(op.SignificantSize < 4) { opNew = TruncateOperator.New( debugInfo, op.SignificantSize, false, newRes, newSrcLo ); } else if(op.SignificantSize == 4) { opNew = SingleAssignmentOperator.New( debugInfo, newRes, newSrcLo ); } else { throw TypeConsistencyErrorException.Create( "Unsupported inputs for truncation: {0}", op ); } op.SubstituteWithOperator( opNew, Operator.SubstitutionFlags.Default ); } else { throw TypeConsistencyErrorException.Create( "Unsupported inputs for truncation: {0}", op ); } nc.MarkAsModified(); } } //--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--// //--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--// //--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--// [CompilationSteps.PhaseFilter( typeof(Phases.ExpandAggregateTypes) )] [CompilationSteps.OperatorHandler( typeof(LoadIndirectOperator) )] private static void Handle_LoadIndirectOperator( PhaseExecution.NotificationContext nc ) { LoadIndirectOperator op = (LoadIndirectOperator)nc.CurrentOperator; TypeSystemForCodeTransformation ts = nc.TypeSystem; if(ts.OperatorAlreadyInScalarForm( op ) == false) { ControlFlowGraphStateForCodeTransformation cfg = nc.CurrentCFG; Debugging.DebugInfo debugInfo = op.DebugInfo; Expression exSrc = op.FirstArgument; VariableExpression exDst = op.FirstResult; TypeRepresentation tdLoad = op.Type; FieldRepresentation[] accessPath = op.AccessPath; Expression[] srcFragments = cfg.GetFragmentsForExpression( exSrc ); Expression[] dstFragments = cfg.GetFragmentsForExpression( exDst ); int sizeDst = dstFragments.Length; bool fIsVolatile = op.MayMutateExistingStorage; for(int offset = 0; offset < sizeDst; offset++) { VariableExpression exDstFragment = (VariableExpression)dstFragments[offset]; Expression exSrcFragment = srcFragments[ 0]; TypeRepresentation tdDstFragment = exDstFragment.Type; TypeRepresentation td; if(sizeDst > 1) { td = tdDstFragment; } else if(tdDstFragment == tdLoad) { td = tdDstFragment; } else if(tdDstFragment.SizeOfHoldingVariable <= tdLoad.SizeOfHoldingVariable) { td = tdDstFragment; } else { td = tdLoad; } var fd = tdLoad.FindFieldAtOffset( offset * sizeof(uint) ); FieldRepresentation[] newAccessPath; if(fd != null && fd.FieldType == td) { newAccessPath = ArrayUtility.AppendToArray( accessPath, fd ); } else { newAccessPath = accessPath; } LoadIndirectOperator opNew = LoadIndirectOperator.New( debugInfo, td, exDstFragment, exSrcFragment, newAccessPath, op.Offset + offset * sizeof(uint), fIsVolatile, false ); opNew.CopyAnnotations( op ); op.AddOperatorBefore( opNew ); } op.Delete(); nc.MarkAsModified(); } } //--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--// //--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--// //--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--// [CompilationSteps.PhaseFilter( typeof(Phases.ExpandAggregateTypes) )] [CompilationSteps.OperatorHandler( typeof(StoreIndirectOperator) )] private static void Handle_StoreIndirectOperator( PhaseExecution.NotificationContext nc ) { StoreIndirectOperator op = (StoreIndirectOperator)nc.CurrentOperator; TypeSystemForCodeTransformation ts = nc.TypeSystem; if(ts.OperatorAlreadyInScalarForm( op ) == false) { ControlFlowGraphStateForCodeTransformation cfg = nc.CurrentCFG; BasicBlock current = op.BasicBlock; Debugging.DebugInfo debugInfo = op.DebugInfo; Expression exSrc = op.SecondArgument; Expression exDst = op.FirstArgument; Expression[] srcFragments = cfg.GetFragmentsForExpression( exSrc ); Expression[] dstFragments = cfg.GetFragmentsForExpression( exDst ); int sizeSrc = srcFragments.Length; for(int offset = 0; offset < sizeSrc; offset++) { Expression exSrcFragment = srcFragments[offset]; Expression exDstFragment = dstFragments[ 0]; TypeRepresentation td = sizeSrc > 1 ? exSrcFragment.Type : op.Type; StoreIndirectOperator opNew = StoreIndirectOperator.New( debugInfo, td, exDstFragment, exSrcFragment, op.AccessPath, op.Offset + offset * sizeof(uint), false ); opNew.CopyAnnotations( op ); op.AddOperatorBefore( opNew ); } op.Delete(); nc.MarkAsModified(); } } //--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--// //--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--// //--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--// [CompilationSteps.PhaseFilter( typeof(Phases.ExpandAggregateTypes) )] [CompilationSteps.OperatorHandler( typeof(BinaryConditionalControlOperator) )] private static void Handle_BinaryConditionalControlOperator( PhaseExecution.NotificationContext nc ) { BinaryConditionalControlOperator op = (BinaryConditionalControlOperator)nc.CurrentOperator; //--// TypeSystemForCodeTransformation ts = nc.TypeSystem; ControlFlowGraphStateForCodeTransformation cfg = nc.CurrentCFG; Debugging.DebugInfo debugInfo = op.DebugInfo; Expression exSrc = op.FirstArgument; Expression[] srcFragments = cfg.GetFragmentsForExpression( exSrc ); TypeRepresentation tdSrc = exSrc.Type; uint sizeSrc = tdSrc.SizeOfHoldingVariableInWords; //--// ConditionCodeExpression cc = cfg.AllocateConditionCode(); if(tdSrc.IsFloatingPoint) { throw TypeConsistencyErrorException.Create( "Unsupported inputs for compare: {0}", op ); } else if(tdSrc.IsNumeric == false || tdSrc.IsInteger) { if(sizeSrc == 1) { op.AddOperatorBefore( CompareOperator.New( debugInfo, cc, srcFragments[0], ts.CreateConstant( 0 ) ) ); } else if(sizeSrc == 2) { VariableExpression tmpFragment = cfg.AllocatePseudoRegister( srcFragments[0].Type ); var opLow = BinaryOperatorWithCarryOut.New( debugInfo, BinaryOperator.ALU.OR, false, false, tmpFragment, cc, srcFragments[0], srcFragments[1] ); op.AddOperatorBefore( opLow ); } else { throw TypeConsistencyErrorException.Create( "Unsupported inputs for compare: {0}", op ); } } else { throw TypeConsistencyErrorException.Create( "Unsupported inputs for compare: {0}", op ); } ConditionCodeConditionalControlOperator opNew = ConditionCodeConditionalControlOperator.New( debugInfo, ConditionCodeExpression.Comparison.NotEqual, cc, op.TargetBranchNotTaken, op.TargetBranchTaken ); op.SubstituteWithOperator( opNew, Operator.SubstitutionFlags.Default ); nc.MarkAsModified(); } //--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--// //--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--// //--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--// [CompilationSteps.PhaseFilter( typeof(Phases.ExpandAggregateTypes) )] [CompilationSteps.OperatorHandler( typeof(MultiWayConditionalControlOperator) )] private static void Handle_MultiWayConditionalControlOperator( PhaseExecution.NotificationContext nc ) { MultiWayConditionalControlOperator op = (MultiWayConditionalControlOperator)nc.CurrentOperator; TypeSystemForCodeTransformation ts = nc.TypeSystem; if(ts.OperatorAlreadyInScalarForm( op ) == false) { ControlFlowGraphStateForCodeTransformation cfg = nc.CurrentCFG; Debugging.DebugInfo debugInfo = op.DebugInfo; Expression exSrc = op.FirstArgument; Expression[] srcFragments = cfg.GetFragmentsForExpression( exSrc ); uint sizeSrc = exSrc.Type.SizeOfHoldingVariableInWords; //--// if(sizeSrc == 1) { Expression newSrc = srcFragments[0]; MultiWayConditionalControlOperator opNew = MultiWayConditionalControlOperator.New( debugInfo, newSrc, op.TargetBranchNotTaken, op.Targets ); op.SubstituteWithOperator( opNew, Operator.SubstitutionFlags.CopyAnnotations ); nc.MarkAsModified(); } else { throw TypeConsistencyErrorException.Create( "Multi-way branches only support 32bit inputs: {0}", op ); } } } //--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--// //--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--// //--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--// [CompilationSteps.PhaseFilter( typeof(Phases.ExpandAggregateTypes) )] [CompilationSteps.OperatorHandler( typeof(ReturnControlOperator) )] private static void Handle_ReturnControlOperator( PhaseExecution.NotificationContext nc ) { ReturnControlOperator op = (ReturnControlOperator)nc.CurrentOperator; TypeSystemForCodeTransformation ts = nc.TypeSystem; if(ts.OperatorAlreadyInScalarForm( op ) == false) { ControlFlowGraphStateForCodeTransformation cfg = nc.CurrentCFG; // // No need to do anything special here. // The code for mapping arguments to words also maps the return value to a set of fragments. // As a consequence, the assignments to the return value are already directed to the right spot. // ReturnControlOperator opNew = ReturnControlOperator.New( cfg.GetFragmentsForExpression( cfg.ReturnValue ) ); op.SubstituteWithOperator( opNew, Operator.SubstitutionFlags.Default ); nc.MarkAsModified(); } } //--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--// //--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--// //--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--// [CompilationSteps.PhaseFilter( typeof(Phases.ExpandAggregateTypes) )] [CompilationSteps.OperatorHandler( typeof(CallOperator) )] private static void Handle_CallOperator( PhaseExecution.NotificationContext nc ) { CallOperator op = (CallOperator)nc.CurrentOperator; TypeSystemForCodeTransformation ts = nc.TypeSystem; ControlFlowGraphStateForCodeTransformation cfg = nc.CurrentCFG; Abstractions.CallingConvention cc = ts.CallingConvention; Abstractions.CallingConvention.CallState callState = cc.CreateCallState( Abstractions.CallingConvention.Direction.Caller ); BasicBlock current = op.BasicBlock; Debugging.DebugInfo debugInfo = op.DebugInfo; VariableExpression returnValue = op.Results.Length == 1 ? op.FirstResult : null; Expression[] resSrcFragments = cc.AssignReturnValue( cfg, op, returnValue, callState ); Expression[][] srcFragments = cfg.GetFragmentsForExpressionArray( op.Arguments ); int offset = op is IndirectCallOperator ? 1 : 0; SingleAssignmentOperator opReg = null; Expression[] rhs = Expression.SharedEmptyArray; bool fIsImportedMethod = op is StaticCallOperator && 0 != ( ( (StaticCallOperator)op ).TargetMethod.BuildTimeFlags & MethodRepresentation.BuildTimeAttributes.Imported ); for(int arg = 0; arg + offset < srcFragments.Length; arg++) { Expression[] argFragments = srcFragments[arg+offset]; Expression dst = op.Arguments[arg+offset]; /// /// For external calls, we do not want the first argument to be the 'this' pointer. /// if(arg == 0 && fIsImportedMethod) { continue; } Expression[] dstFragments = cc.AssignArgument( cfg, op, dst, callState ); int requiredWords = argFragments.Length; if(arg == 0 && op is StaticCallOperator) { // // Don't bother loading the 'this' pointer for static methods. // continue; } for(int wordOffset = 0; wordOffset < requiredWords; wordOffset++) { Expression argEx = argFragments[wordOffset]; VariableExpression dstEx = (VariableExpression)dstFragments[wordOffset]; SingleAssignmentOperator opNew = SingleAssignmentOperator.New( debugInfo, dstEx, argEx ); if(fIsImportedMethod) { opNew.AddAnnotation( ExternalCallArgumentAnnotation.Create(ts) ); } rhs = ArrayUtility.AppendToNotNullArray( rhs, (Expression)dstEx ); // // Well, we want to assign first the values that get passed on the stack, then the ones that get passed in registers. // The idea is that, if the result of a previous call is used for a stack value, we could pick it up directly from the volatile registers. // Operator opTarget = op; if(dstEx is PhysicalRegisterExpression) { if(opReg == null) { opReg = opNew; } } else if(opReg != null) { opTarget = opReg; } opTarget.AddOperatorBefore( opNew ); } } SubroutineOperator newCall; if(op is IndirectCallOperator) { newCall = IndirectSubroutineOperator.New( debugInfo, op.TargetMethod, srcFragments[0][0], rhs ); } else { newCall = DirectSubroutineOperator.New( debugInfo, op.TargetMethod, rhs ); } Annotation[] annotations = op.Annotations; foreach(Annotation an in annotations) { if(an is NotNullAnnotation || an is FixedLengthArrayAnnotation ) { } else { newCall.AddAnnotation( an ); } } op.SubstituteWithOperator( newCall, Operator.SubstitutionFlags.Default ); if(resSrcFragments != null) { Expression[] resDstFragments = cfg.GetFragmentsForExpression( returnValue ); for(int wordOffset = 0; wordOffset < resDstFragments.Length; wordOffset++) { var opNew = SingleAssignmentOperator.New( debugInfo, (VariableExpression)resDstFragments[wordOffset], resSrcFragments[wordOffset] ); foreach(Annotation an in annotations) { if(an is NotNullAnnotation || an is FixedLengthArrayAnnotation ) { opNew.AddAnnotation( an ); } } newCall.AddOperatorAfter( opNew ); } } if(newCall.GetNextOperator() is DeadControlOperator) { // // No need to add side effects after a dead call. // } else { foreach(VariableExpression exToInvalidate in cc.CollectExpressionsToInvalidate( cfg, op, resSrcFragments )) { newCall.AddAnnotation( PostInvalidationAnnotation.Create( ts, exToInvalidate ) ); } } nc.MarkAsModified(); } } } ================================================ FILE: Zelig/Zelig/CompileTime/CodeGenerator/CodeTransformation/CompilationSteps/Handlers/OperatorHandlers_FromImplicitToExplicitExceptions.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // //#define ENABLE_OVERFLOW_CHECKS namespace Microsoft.Zelig.CodeGeneration.IR.CompilationSteps.Handlers { using System; using System.Collections.Generic; using Microsoft.Zelig.Runtime.TypeSystem; public class OperatorHandlers_FromImplicitToExplicitExceptions { #if ENABLE_OVERFLOW_CHECKS [CompilationSteps.PhaseFilter( typeof(Phases.FromImplicitToExplicitExceptions) )] [CompilationSteps.OperatorHandler( typeof(BinaryOperator) )] #endif // ENABLE_OVERFLOW_CHECKS private static void Handle_BinaryOperator( PhaseExecution.NotificationContext nc ) { BinaryOperator op = (BinaryOperator)nc.CurrentOperator; if(op.CheckOverflow) { var overflowFlag = CreateOverflowCheck(nc, op); var opNew = BinaryOperatorWithCarryOut.New( op.DebugInfo, op.Alu, op.Signed, false, op.FirstResult, overflowFlag, op.FirstArgument, op.SecondArgument); op.SubstituteWithOperator( opNew, Operator.SubstitutionFlags.CopyAnnotations ); } } //--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--// //--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--// //--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--// #if ENABLE_OVERFLOW_CHECKS [CompilationSteps.PhaseFilter( typeof(Phases.FromImplicitToExplicitExceptions) )] [CompilationSteps.OperatorHandler( typeof(UnaryOperator) )] #endif // ENABLE_OVERFLOW_CHECKS private static void Handle_UnaryOperator( PhaseExecution.NotificationContext nc ) { UnaryOperator op = (UnaryOperator)nc.CurrentOperator; if(op.CheckOverflow) { var overflowFlag = CreateOverflowCheck(nc, op); var opNew = UnaryOperatorWithCarryOut.New( op.DebugInfo, op.Alu, op.Signed, false, op.FirstResult, overflowFlag, op.FirstArgument); op.SubstituteWithOperator( opNew, Operator.SubstitutionFlags.CopyAnnotations ); } } //--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--// //--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--// //--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--// [CompilationSteps.PhaseFilter( typeof(Phases.FromImplicitToExplicitExceptions) )] [CompilationSteps.OperatorHandler( typeof(SignExtendOperator) )] private static void Handle_SignExtendOperator( PhaseExecution.NotificationContext nc ) { SignExtendOperator op = (SignExtendOperator)nc.CurrentOperator; VariableExpression lhs = op.FirstResult; Expression rhs = op.FirstArgument; var di = op.DebugInfo; if(lhs.Type.Size == rhs.Type.Size && lhs.Type.Size == op.SignificantSize) { var opNew = SingleAssignmentOperator.New( di, lhs, rhs ); op.SubstituteWithOperator( opNew, Operator.SubstitutionFlags.CopyAnnotations ); nc.MarkAsModified(); } else if(op.CheckOverflow) { var opNew = SignExtendOperator.New( di, op.SignificantSize, false, lhs, rhs ); op.SubstituteWithOperator( opNew, Operator.SubstitutionFlags.CopyAnnotations ); VerifyNoLossOfPrecision( nc, opNew, lhs, rhs ); } } //--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--// //--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--// //--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--// [CompilationSteps.PhaseFilter( typeof(Phases.FromImplicitToExplicitExceptions) )] [CompilationSteps.OperatorHandler( typeof(ZeroExtendOperator) )] private static void Handle_ZeroExtendOperator( PhaseExecution.NotificationContext nc ) { ZeroExtendOperator op = (ZeroExtendOperator)nc.CurrentOperator; VariableExpression lhs = op.FirstResult; Expression rhs = op.FirstArgument; if(lhs.Type.Size == rhs.Type.Size && lhs.Type.Size == op.SignificantSize) { var opNew = SingleAssignmentOperator.New( op.DebugInfo, lhs, rhs ); op.SubstituteWithOperator( opNew, Operator.SubstitutionFlags.CopyAnnotations ); nc.MarkAsModified(); } else if(op.CheckOverflow) { var opNew = ZeroExtendOperator.New( op.DebugInfo, op.SignificantSize, false, lhs, rhs ); op.SubstituteWithOperator( opNew, Operator.SubstitutionFlags.CopyAnnotations ); VerifyNoLossOfPrecision( nc, opNew, lhs, rhs ); } } //--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--// //--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--// //--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--// [CompilationSteps.PhaseFilter( typeof(Phases.FromImplicitToExplicitExceptions) )] [CompilationSteps.OperatorHandler( typeof(TruncateOperator) )] private static void Handle_TruncateOperator( PhaseExecution.NotificationContext nc ) { TruncateOperator op = (TruncateOperator)nc.CurrentOperator; VariableExpression lhs = op.FirstResult; Expression rhs = op.FirstArgument; if(lhs.Type.Size == rhs.Type.Size && lhs.Type.Size == op.SignificantSize) { var opNew = SingleAssignmentOperator.New( op.DebugInfo, lhs, rhs ); op.SubstituteWithOperator( opNew, Operator.SubstitutionFlags.CopyAnnotations ); nc.MarkAsModified(); } else if(op.CheckOverflow) { TruncateOperator opNew = TruncateOperator.New( op.DebugInfo, op.SignificantSize, false, lhs, rhs ); op.SubstituteWithOperator( opNew, Operator.SubstitutionFlags.CopyAnnotations ); VerifyNoLossOfPrecision( nc, opNew, lhs, rhs ); } } //--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--// //--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--// //--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--// [CompilationSteps.PhaseFilter( typeof(Phases.FromImplicitToExplicitExceptions) )] [CompilationSteps.OperatorHandler( typeof(NullCheckOperator) )] private static void Handle_NullCheckOperator( PhaseExecution.NotificationContext nc ) { Operator op = nc.CurrentOperator; CompilationConstraints[] ccArray = nc.CurrentCFG.CompilationConstraintsAtOperator( op ); Expression addr = op.FirstArgument; if(addr == nc.CurrentCFG.Arguments[0]) { // We know the 'this' pointer is non-null since the caller will check before calling. op.Delete(); } else if(addr.Type is ManagedPointerTypeRepresentation || addr.Type is UnmanagedPointerTypeRepresentation) { // Managed pointers are guaranteed non-null by construction, while unmanaged pointers // can only be used in an unsafe context and therefore should never be checked. op.Delete(); } else if(ControlFlowGraphState.HasCompilationConstraint( ccArray, CompilationConstraints.NullChecks_OFF ) || ControlFlowGraphState.HasCompilationConstraint( ccArray, CompilationConstraints.NullChecks_OFF_DEEP ) ) { op.Delete(); } else { Debugging.DebugInfo debugInfo = op.DebugInfo; BasicBlock current = op.BasicBlock; BasicBlock continueBB; BasicBlock throwBB; SplitAndCall( nc, op, true, nc.TypeSystem.WellKnownMethods.ThreadImpl_ThrowNullException, out continueBB, out throwBB ); //--// current.AddOperator( BinaryConditionalControlOperator.New( debugInfo, addr, throwBB, continueBB ) ); } nc.MarkAsModified(); } //--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--// //--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--// //--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--// [CompilationSteps.PhaseFilter( typeof(Phases.FromImplicitToExplicitExceptions) )] [CompilationSteps.OperatorHandler( typeof(OutOfBoundCheckOperator) )] private static void Handle_OutOfBoundCheckOperator( PhaseExecution.NotificationContext nc ) { Operator op = nc.CurrentOperator; CompilationConstraints[] ccArray = nc.CurrentCFG.CompilationConstraintsAtOperator( op ); if(ControlFlowGraphState.HasCompilationConstraint( ccArray, CompilationConstraints.BoundsChecks_OFF ) || ControlFlowGraphState.HasCompilationConstraint( ccArray, CompilationConstraints.BoundsChecks_OFF_DEEP ) ) { op.Delete(); } else { TypeSystemForCodeTransformation ts = nc.TypeSystem; WellKnownTypes wkt = ts.WellKnownTypes; WellKnownFields wkf = ts.WellKnownFields; WellKnownMethods wkm = ts.WellKnownMethods; Debugging.DebugInfo debugInfo = op.DebugInfo; Expression exAddress = op.FirstArgument; Expression exIndex = op.SecondArgument; BasicBlock currentBB = op.BasicBlock; BasicBlock continueBB; BasicBlock throwBB; SplitAndCall( nc, op, true, wkm.ThreadImpl_ThrowIndexOutOfRangeException, out continueBB, out throwBB ); //--// ControlFlowGraphStateForCodeTransformation cfg = nc.CurrentCFG; TemporaryVariableExpression exLength = cfg.AllocateTemporary( wkt.System_UInt32, null ); currentBB.AddOperator( LoadInstanceFieldOperator .New( debugInfo, wkf.ArrayImpl_m_numElements, exLength, exAddress, false ) ); currentBB.AddOperator( CompareConditionalControlOperator.New( debugInfo, CompareAndSetOperator.ActionCondition.LT, false, exIndex, exLength, throwBB, continueBB ) ); } nc.MarkAsModified(); } //--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--// //--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--// //--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--// private static VariableExpression CreateOverflowCheck(PhaseExecution.NotificationContext nc, Operator op) { TypeRepresentation boolType = nc.TypeSystem.WellKnownTypes.System_Boolean; TemporaryVariableExpression overflowFlag = nc.CurrentCFG.AllocateTemporary(boolType, null); BasicBlock continueBB; BasicBlock throwBB; MethodRepresentation throwOverflow = nc.TypeSystem.WellKnownMethods.ThreadImpl_ThrowOverflowException; SplitAndCall(nc, op, true, throwOverflow, out continueBB, out throwBB); op.AddOperatorAfter(BinaryConditionalControlOperator.New(op.DebugInfo, overflowFlag, continueBB, throwBB)); nc.MarkAsModified(); return overflowFlag; } private static void SplitAndCall( PhaseExecution.NotificationContext nc , Operator op , bool fRemoveOperator , MethodRepresentation md , out BasicBlock continueBB , out BasicBlock throwBB ) { Debugging.DebugInfo debugInfo = op.DebugInfo; BasicBlock current = op.BasicBlock; BasicBlock[] basicBlocks = nc.CurrentCFG.DataFlow_SpanningTree_BasicBlocks; throwBB = null; // Try to find an existing throw block for the same exception. foreach(BasicBlock block in basicBlocks) { var callOp = block.FirstOperator as StaticCallOperator; if( (callOp != null) && (callOp.TargetMethod == md) && ArrayUtility.ArrayEqualsNotNull( block.ProtectedBy, current.ProtectedBy, 0 )) { throwBB = block; break; } } continueBB = current.SplitAtOperator( op, fRemoveOperator, false ); // We didn't find an existing throw block, so create a new one. if(throwBB == null) { Expression[] rhs = nc.TypeSystem.AddTypePointerToArgumentsOfStaticMethod( md ); throwBB = NormalBasicBlock.CreateWithSameProtection( current ); throwBB.AddOperator( StaticCallOperator .New( debugInfo, CallOperator.CallKind.Direct, md, rhs ) ); throwBB.AddOperator( DeadControlOperator.New( debugInfo ) ); } nc.MarkAsModified(); } private static void VerifyNoLossOfPrecision( PhaseExecution.NotificationContext nc , Operator op , VariableExpression lhs , Expression rhs ) { var cfg = nc.CurrentCFG; var lhsExt = cfg.AllocateTemporary( rhs.Type, null ); Operator opNew; if(lhs.Type.IsSigned) { opNew = SignExtendOperator.New( op.DebugInfo, lhs.Type.Size, false, lhsExt, lhs ); } else { opNew = ZeroExtendOperator.New( op.DebugInfo, lhs.Type.Size, false, lhsExt, lhs ); } op.AddOperatorAfter( opNew ); //--// BasicBlock continueBB; BasicBlock throwBB; SplitAndCall( nc, opNew.GetNextOperator(), false, nc.TypeSystem.WellKnownMethods.ThreadImpl_ThrowOverflowException, out continueBB, out throwBB ); //--// opNew.BasicBlock.AddOperator( CompareConditionalControlOperator.New( op.DebugInfo, CompareAndSetOperator.ActionCondition.NE, false, lhsExt, rhs, continueBB, throwBB ) ); nc.MarkAsModified(); } } } ================================================ FILE: Zelig/Zelig/CompileTime/CodeGenerator/CodeTransformation/CompilationSteps/Handlers/OperatorHandlers_HighLevel.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // namespace Microsoft.Zelig.CodeGeneration.IR.CompilationSteps.Handlers { using System; using System.Collections.Generic; using Microsoft.Zelig.Runtime.TypeSystem; public class OperatorHandlers_HighLevel { [CompilationSteps.PhaseFilter( typeof(Phases.HighLevelTransformations) )] [CompilationSteps.OperatorHandler( typeof(ObjectAllocationOperator) )] private static void Handle_ObjectAllocationOperator( PhaseExecution.NotificationContext nc ) { ObjectAllocationOperator op = (ObjectAllocationOperator)nc.CurrentOperator; TypeSystemForCodeTransformation ts = nc.TypeSystem; WellKnownMethods wkm = ts.WellKnownMethods; MethodRepresentation mdAllocateObject = wkm.TypeSystemManager_AllocateObject; MethodRepresentation md = op.Method; TypeRepresentation td = op.Type; CallOperator call; Expression[] rhs; Expression exStringLen = null; // // Is this a special object? // for(var td2 = td; td2 != null; td2 = td2.Extends) { if(ts.GarbageCollectionExtensions.ContainsKey( td2 )) { mdAllocateObject = wkm.TypeSystemManager_AllocateObjectWithExtensions; break; } } if(md != null) { if(md == wkm.StringImpl_ctor_char_int) { exStringLen = op.SecondArgument; } else if(md == wkm.StringImpl_ctor_charArray) { TemporaryVariableExpression tmp = nc.CurrentCFG.AllocateTemporary( ts.WellKnownTypes.System_Int32, null ); op.AddOperatorBefore( ArrayLengthOperator.New( op.DebugInfo, tmp, op.FirstArgument ) ); exStringLen = tmp; } else if(md == wkm.StringImpl_ctor_charArray_int_int) { exStringLen = op.ThirdArgument; } } // // Special case to allocate strings built out of characters. // if(exStringLen != null) { if(ts.IsReferenceCountingType( ts.WellKnownTypes.System_String ) && !ts.ShouldExcludeMethodFromReferenceCounting( nc.CurrentMethod )) { mdAllocateObject = wkm.StringImpl_FastAllocateReferenceCountingString; } else { mdAllocateObject = wkm.StringImpl_FastAllocateString; } rhs = ts.AddTypePointerToArgumentsOfStaticMethod( mdAllocateObject, exStringLen ); call = StaticCallOperator.New( op.DebugInfo, CallOperator.CallKind.Direct, mdAllocateObject, op.Results, rhs ); op.SubstituteWithOperator( call, Operator.SubstitutionFlags.CopyAnnotations ); call.AddAnnotation( NotNullAnnotation.Create( ts ) ); } else { if( ts.IsReferenceCountingGarbageCollectionEnabled && md != wkm.TypeSystemManager_AllocateObjectWithExtensions && ts.IsReferenceCountingType( td ) && !ts.ShouldExcludeMethodFromReferenceCounting( nc.CurrentMethod )) { mdAllocateObject = wkm.TypeSystemManager_AllocateReferenceCountingObject; } TemporaryVariableExpression typeSystemManagerEx = FetchTypeSystemManager( nc, op ); rhs = new Expression[] { typeSystemManagerEx, ts.GetVTable( op.Type ) }; call = InstanceCallOperator.New( op.DebugInfo, CallOperator.CallKind.Virtual, mdAllocateObject, op.Results, rhs, true ); op.SubstituteWithOperator( call, Operator.SubstitutionFlags.CopyAnnotations ); call.AddAnnotation( NotNullAnnotation.Create( ts ) ); var mdFinalizer = td.FindDestructor(); if(mdFinalizer != null && mdFinalizer.OwnerType != ts.WellKnownTypes.System_Object) { var mdHelper = wkm.Finalizer_Allocate; var rhsHelper = ts.AddTypePointerToArgumentsOfStaticMethod( mdHelper, call.FirstResult ); var callHelper = StaticCallOperator.New( call.DebugInfo, CallOperator.CallKind.Direct, mdHelper, rhsHelper ); call.AddOperatorAfter( callHelper ); } } nc.MarkAsModified(); } //--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--// //--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--// //--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--// [CompilationSteps.PhaseFilter( typeof(Phases.HighLevelTransformations) )] [CompilationSteps.OperatorHandler( typeof(ArrayAllocationOperator) )] private static void Handle_ArrayAllocationOperator( PhaseExecution.NotificationContext nc ) { ArrayAllocationOperator op = (ArrayAllocationOperator)nc.CurrentOperator; TypeSystemForCodeTransformation ts = nc.TypeSystem; TemporaryVariableExpression typeSystemManagerEx = FetchTypeSystemManager( nc, op ); MethodRepresentation mdAllocateArray = ts.WellKnownMethods.TypeSystemManager_AllocateArray; CallOperator call; Expression[] rhs; Expression exLen = op.FirstArgument; if( ts.IsReferenceCountingGarbageCollectionEnabled && ts.IsReferenceCountingType( ts.WellKnownTypes.System_Array ) && !ts.ShouldExcludeMethodFromReferenceCounting( nc.CurrentMethod )) { mdAllocateArray = ts.WellKnownMethods.TypeSystemManager_AllocateReferenceCountingArray; } rhs = new Expression[] { typeSystemManagerEx, ts.GetVTable( op.Type ), exLen }; call = InstanceCallOperator.New( op.DebugInfo, CallOperator.CallKind.Virtual, mdAllocateArray, op.Results, rhs, true ); op.SubstituteWithOperator( call, Operator.SubstitutionFlags.CopyAnnotations ); call.AddAnnotation( NotNullAnnotation.Create( ts ) ); ConstantExpression exLenConst = exLen as ConstantExpression; if(exLenConst != null && exLenConst.IsValueInteger) { ulong val; exLenConst.GetAsRawUlong( out val ); call.AddAnnotation( FixedLengthArrayAnnotation.Create( ts, (int)val ) ); } nc.MarkAsModified(); } [CompilationSteps.PhaseFilter( typeof(Phases.HighLevelTransformations) )] [CompilationSteps.OperatorHandler( typeof(ArrayLengthOperator) )] private static void Handle_ArrayLengthOperator( PhaseExecution.NotificationContext nc ) { ArrayLengthOperator op = (ArrayLengthOperator)nc.CurrentOperator; TypeSystemForCodeTransformation typeSystem = nc.TypeSystem; InstanceCallOperator opNew = InstanceCallOperator.New( op.DebugInfo, CallOperator.CallKind.Direct, typeSystem.WellKnownMethods.ArrayImpl_get_Length, op.Results, new Expression[] { op.FirstArgument }, true ); op.SubstituteWithOperator( opNew, Operator.SubstitutionFlags.Default ); nc.MarkAsModified(); } //--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--// //--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--// //--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--// [CompilationSteps.PhaseFilter( typeof(Phases.HighLevelTransformations) )] [CompilationSteps.OperatorHandler( typeof(ThrowControlOperator) )] private static void Handle_ThrowControlOperator( PhaseExecution.NotificationContext nc ) { ThrowControlOperator op = (ThrowControlOperator)nc.CurrentOperator; TypeSystemForCodeTransformation typeSystem = nc.TypeSystem; TemporaryVariableExpression typeSystemManagerEx = FetchTypeSystemManager( nc, op ); MethodRepresentation mdThrow = typeSystem.WellKnownMethods.TypeSystemManager_Throw; Debugging.DebugInfo debugInfo = op.DebugInfo; CallOperator call; Expression[] rhs; rhs = new Expression[] { typeSystemManagerEx, op.FirstArgument }; call = InstanceCallOperator.New( debugInfo, CallOperator.CallKind.Virtual, mdThrow, rhs, true ); call.CopyAnnotations( op ); op.AddOperatorBefore( call ); op.SubstituteWithOperator( DeadControlOperator.New( debugInfo ), Operator.SubstitutionFlags.Default ); nc.MarkAsModified(); } [CompilationSteps.PhaseFilter( typeof(Phases.HighLevelTransformations) )] [CompilationSteps.OperatorHandler( typeof(RethrowControlOperator) )] private static void Handle_RethrowControlOperator( PhaseExecution.NotificationContext nc ) { RethrowControlOperator op = (RethrowControlOperator)nc.CurrentOperator; TypeSystemForCodeTransformation typeSystem = nc.TypeSystem; TemporaryVariableExpression typeSystemManagerEx = FetchTypeSystemManager( nc, op ); MethodRepresentation mdRethrow = typeSystem.WellKnownMethods.TypeSystemManager_Rethrow; Debugging.DebugInfo debugInfo = op.DebugInfo; CallOperator call; Expression[] rhs; rhs = new Expression[] { typeSystemManagerEx }; call = InstanceCallOperator.New( debugInfo, CallOperator.CallKind.Virtual, mdRethrow, rhs, true ); call.CopyAnnotations( op ); op.AddOperatorBefore( call ); op.SubstituteWithOperator( DeadControlOperator.New( debugInfo ), Operator.SubstitutionFlags.Default ); nc.MarkAsModified(); } [CompilationSteps.PhaseFilter( typeof(Phases.HighLevelTransformations) )] [CompilationSteps.OperatorHandler( typeof(FetchExceptionOperator) )] private static void Handle_FetchExceptionOperator( PhaseExecution.NotificationContext nc ) { FetchExceptionOperator op = (FetchExceptionOperator)nc.CurrentOperator; TypeSystemForCodeTransformation typeSystem = nc.TypeSystem; MethodRepresentation md = typeSystem.WellKnownMethods.ThreadImpl_GetCurrentException; CallOperator call; Expression[] rhs; rhs = typeSystem.AddTypePointerToArgumentsOfStaticMethod( md ); call = StaticCallOperator.New( op.DebugInfo, CallOperator.CallKind.Direct, md, op.Results, rhs ); op.SubstituteWithOperator( call, Operator.SubstitutionFlags.Default ); nc.MarkAsModified(); } //--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--// //--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--// //--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--// [CompilationSteps.PhaseFilter( typeof(Phases.HighLevelTransformations) )] [CompilationSteps.OperatorHandler( typeof(CastOperator) )] private static void Handle_CastOperator( PhaseExecution.NotificationContext nc ) { WellKnownMethods wkm = nc.TypeSystem.WellKnownMethods; CastOperator op = (CastOperator)nc.CurrentOperator; Handle_GenericCastOperator( nc, op.Type, wkm.TypeSystemManager_CastToSealedType, wkm.TypeSystemManager_CastToType, wkm.TypeSystemManager_CastToInterface ); } [CompilationSteps.PhaseFilter( typeof(Phases.HighLevelTransformations) )] [CompilationSteps.OperatorHandler( typeof(IsInstanceOperator) )] private static void Handle_IsInstanceOperator( PhaseExecution.NotificationContext nc ) { WellKnownMethods wkm = nc.TypeSystem.WellKnownMethods; IsInstanceOperator op = (IsInstanceOperator)nc.CurrentOperator; Handle_GenericCastOperator( nc, op.Type, wkm.TypeSystemManager_CastToSealedTypeNoThrow, wkm.TypeSystemManager_CastToTypeNoThrow, wkm.TypeSystemManager_CastToInterfaceNoThrow ); } private static void Handle_GenericCastOperator( PhaseExecution.NotificationContext nc , TypeRepresentation target , MethodRepresentation mdSealedType , MethodRepresentation mdType , MethodRepresentation mdInterface ) { TypeSystemForCodeTransformation typeSystem = nc.TypeSystem; Operator op = nc.CurrentOperator; Expression src = op.FirstArgument; if(target.CanBeAssignedFrom( src.Type, null )) { var opNew = SingleAssignmentOperator.New( op.DebugInfo, op.FirstResult, src ); op.SubstituteWithOperator( opNew, Operator.SubstitutionFlags.Default ); } else { MethodRepresentation md; Expression[] rhs; CallOperator call; if(target is InterfaceTypeRepresentation) { md = mdInterface; } else if(target is ArrayReferenceTypeRepresentation) { md = mdType; } else { TypeRepresentation targetSealed; if(typeSystem.IsSealedType( target, out targetSealed )) { target = targetSealed; md = mdSealedType; } else { md = mdType; } } rhs = typeSystem.AddTypePointerToArgumentsOfStaticMethod( md, src, typeSystem.GetVTable( target ) ); call = StaticCallOperator.New( op.DebugInfo, CallOperator.CallKind.Direct, md, op.Results, rhs ); op.SubstituteWithOperator( call, Operator.SubstitutionFlags.Default ); } nc.MarkAsModified(); } //--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--// //--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--// //--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--// [CompilationSteps.PhaseFilter( typeof(Phases.HighLevelTransformations) )] [CompilationSteps.OperatorHandler( typeof(LoadStaticFieldAddressOperator) )] private static void Handle_LoadStaticFieldAddressOperator( PhaseExecution.NotificationContext nc ) { LoadStaticFieldAddressOperator op = (LoadStaticFieldAddressOperator)nc.CurrentOperator; TypeSystemForCodeTransformation ts = nc.TypeSystem; Expression exRoot = ts.GenerateRootAccessor( op ); InstanceFieldRepresentation fd = ts.AddStaticFieldToGlobalRoot( (StaticFieldRepresentation)op.Field ); // // 'exRoot' will never be null, so we don't need to add null checks. // LoadInstanceFieldAddressOperator opNew = LoadInstanceFieldAddressOperator.New( op.DebugInfo, fd, op.FirstResult, exRoot, false ); opNew.AddAnnotation( NotNullAnnotation.Create( ts ) ); op.SubstituteWithOperator( opNew, Operator.SubstitutionFlags.Default ); nc.MarkAsModified(); } [CompilationSteps.PhaseFilter( typeof(Phases.HighLevelTransformations) )] [CompilationSteps.OperatorHandler( typeof(LoadStaticFieldOperator) )] private static void Handle_LoadStaticFieldOperator( PhaseExecution.NotificationContext nc ) { LoadStaticFieldOperator op = (LoadStaticFieldOperator)nc.CurrentOperator; TypeSystemForCodeTransformation typeSystem = nc.TypeSystem; Expression exRoot = typeSystem.GenerateRootAccessor( op ); InstanceFieldRepresentation fd = typeSystem.AddStaticFieldToGlobalRoot( (StaticFieldRepresentation)op.Field ); // // 'exRoot' will never be null, so we don't need to check for it. // LoadInstanceFieldOperator opNew = LoadInstanceFieldOperator.New( op.DebugInfo, fd, op.FirstResult, exRoot, false ); op.SubstituteWithOperator( opNew, Operator.SubstitutionFlags.Default ); nc.MarkAsModified(); } [CompilationSteps.PhaseFilter( typeof(Phases.HighLevelTransformations) )] [CompilationSteps.OperatorHandler( typeof(StoreStaticFieldOperator) )] private static void Handle_StoreStaticFieldOperator( PhaseExecution.NotificationContext nc ) { StoreStaticFieldOperator op = (StoreStaticFieldOperator)nc.CurrentOperator; TypeSystemForCodeTransformation typeSystem = nc.TypeSystem; Expression exRoot = typeSystem.GenerateRootAccessor( op ); InstanceFieldRepresentation fd = typeSystem.AddStaticFieldToGlobalRoot( (StaticFieldRepresentation)op.Field ); // // 'exRoot' will never be null, so we don't need to check for it. // StoreInstanceFieldOperator opNew = StoreInstanceFieldOperator.New( op.DebugInfo, fd, exRoot, op.FirstArgument, false ); op.SubstituteWithOperator( opNew, Operator.SubstitutionFlags.Default ); nc.MarkAsModified(); } //--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--// //--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--// //--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--// [CompilationSteps.PhaseFilter( typeof(Phases.HighLevelTransformations) )] [CompilationSteps.OperatorHandler( typeof(MkRefAnyOperator) )] private static void Handle_MkRefAnyOperator( PhaseExecution.NotificationContext nc ) { MkRefAnyOperator op = (MkRefAnyOperator)nc.CurrentOperator; VariableExpression lhs = op.FirstResult; TypeRepresentation target = lhs.Type; FieldRepresentation fdValue = target.FindField( "Value" ); FieldRepresentation fdType = target.FindField( "Type" ); op.AddOperatorBefore ( StoreInstanceFieldOperator.New( op.DebugInfo, fdValue, lhs, op.FirstArgument , true ) ); op.SubstituteWithOperator( StoreInstanceFieldOperator.New( op.DebugInfo, fdType , lhs, nc.TypeSystem.GetVTable( op.Type ), true ), Operator.SubstitutionFlags.Default ); nc.MarkAsModified(); } [CompilationSteps.PhaseFilter( typeof(Phases.HighLevelTransformations) )] [CompilationSteps.OperatorHandler( typeof(RefAnyValOperator) )] private static void Handle_RefAnyValOperator( PhaseExecution.NotificationContext nc ) { RefAnyValOperator op = (RefAnyValOperator)nc.CurrentOperator; TypeRepresentation target = op.FirstArgument.Type; FieldRepresentation fdValue = target.FindField( "Value" ); // // TODO: Check that target.Type and op.Type are the same. // LoadInstanceFieldOperator opNew = LoadInstanceFieldOperator.New( op.DebugInfo, fdValue, op.FirstResult, op.FirstArgument, true ); op.SubstituteWithOperator( opNew, Operator.SubstitutionFlags.Default ); nc.MarkAsModified(); } [CompilationSteps.PhaseFilter( typeof(Phases.HighLevelTransformations) )] [CompilationSteps.OperatorHandler( typeof(RefAnyTypeOperator) )] private static void Handle_RefAnyTypeOperator( PhaseExecution.NotificationContext nc ) { RefAnyTypeOperator op = (RefAnyTypeOperator)nc.CurrentOperator; TypeRepresentation target = op.FirstArgument.Type; FieldRepresentation fdType = target.FindField( "Type" ); LoadInstanceFieldOperator opNew = LoadInstanceFieldOperator.New( op.DebugInfo, fdType, op.FirstResult, op.FirstArgument, true ); op.SubstituteWithOperator( opNew, Operator.SubstitutionFlags.Default ); nc.MarkAsModified(); } //--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--// //--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--// //--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--// [CompilationSteps.PhaseFilter( typeof(Phases.HighLevelTransformations) )] [CompilationSteps.OperatorHandler( typeof(BoxOperator) )] private static void Handle_BoxOperator( PhaseExecution.NotificationContext nc ) { BoxOperator op = (BoxOperator)nc.CurrentOperator; var lhs = op.FirstResult; // // Try to detect the pattern of many methods in generic types: // // private int FindEntry( TKey key ) // { // if(key == null) // { // // 'null' is always a reference and if TKey is a value type, the compiler has to generate a boxing operation. // But boxed values are also non-null, so we can delete the boxing and substitute a constant for the outcome of the compare. // { var cfg = nc.CurrentCFG; var use = cfg.FindSingleUse( lhs ); if(use != null) { bool fNullOnRight; if(use.IsBinaryOperationAgainstZeroValue( out fNullOnRight ) == lhs) { if(use is CompareAndSetOperator) { var use2 = (CompareAndSetOperator)use; bool fSubstitute = false; int val = 0; switch(use2.Condition) { case CompareAndSetOperator.ActionCondition.EQ: fSubstitute = true; val = 0; break; case CompareAndSetOperator.ActionCondition.NE: fSubstitute = true; val = 1; break; } if(fSubstitute) { op.Delete(); use2.SubstituteWithOperator( SingleAssignmentOperator.New( use2.DebugInfo, use2.FirstResult, cfg.TypeSystem.CreateConstant( val ) ), Operator.SubstitutionFlags.Default ); nc.StopScan(); return; } } if(use is CompareConditionalControlOperator) { var use2 = (CompareConditionalControlOperator)use; bool fSubstitute = false; BasicBlock target = null; switch(use2.Condition) { case CompareAndSetOperator.ActionCondition.EQ: fSubstitute = true; target = use2.TargetBranchNotTaken; break; case CompareAndSetOperator.ActionCondition.NE: fSubstitute = true; target = use2.TargetBranchTaken; break; } if(fSubstitute) { op.Delete(); use2.SubstituteWithOperator( UnconditionalControlOperator.New( use2.DebugInfo, target ), Operator.SubstitutionFlags.Default ); nc.StopScan(); return; } } } } } op.AddOperatorBefore(ObjectAllocationOperator.New(op.DebugInfo, op.Type.UnderlyingType, lhs)); // Store requires a boxed type, but this argument may have been retyped. Retype it if necessary. VariableExpression boxedValue = lhs; if (boxedValue.Type != op.Type) { boxedValue = nc.AllocateTemporary(op.Type); op.AddOperatorBefore(SingleAssignmentOperator.New(op.DebugInfo, boxedValue, lhs)); } var storeOp = StoreInstanceFieldOperator.New(op.DebugInfo, op.Type.Fields[0], boxedValue, op.FirstArgument, false); op.SubstituteWithOperator(storeOp, Operator.SubstitutionFlags.Default); nc.MarkAsModified(); } [CompilationSteps.PhaseFilter( typeof(Phases.HighLevelTransformations) )] [CompilationSteps.OperatorHandler( typeof(UnboxOperator) )] private static void Handle_UnboxOperator( PhaseExecution.NotificationContext nc ) { UnboxOperator op = (UnboxOperator)nc.CurrentOperator; // Load requires a boxed type, but this argument may have been retyped. Retype it if necessary. Expression boxedValue = op.FirstArgument; if (boxedValue.Type != op.Type) { VariableExpression newValue = nc.AllocateTemporary(op.Type); op.AddOperatorBefore(SingleAssignmentOperator.New(op.DebugInfo, newValue, op.FirstArgument)); boxedValue = newValue; } var loadOp = LoadInstanceFieldAddressOperator.New( op.DebugInfo, op.Type.Fields[0], op.FirstResult, boxedValue, fNullCheck: true); op.SubstituteWithOperator(loadOp, Operator.SubstitutionFlags.Default); nc.MarkAsModified(); } //--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--// //--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--// //--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--// [CompilationSteps.PhaseFilter( typeof(Phases.HighLevelTransformations) )] [CompilationSteps.OperatorHandler( typeof(BinaryOperator) )] private static void Handle_RemoveTypeConversions( PhaseExecution.NotificationContext nc ) { BinaryOperator op = (BinaryOperator)nc.CurrentOperator; ControlFlowGraphStateForCodeTransformation cfg = nc.CurrentCFG; VariableExpression exLhs = op.FirstResult; ConstantExpression exConstLeft = op.FirstArgument as ConstantExpression; ConstantExpression exConstRight = op.SecondArgument as ConstantExpression; ConversionOperator use = IsArgumentAsTypeConversion( cfg, exLhs , false ); ConversionOperator defLeft = IsArgumentAsTypeConversion( cfg, op.FirstArgument , true ); ConversionOperator defRight = IsArgumentAsTypeConversion( cfg, op.SecondArgument, true ); if(defLeft != null && defRight != null) { Expression leftPre = defLeft .FirstArgument; Expression leftPost = defLeft .FirstResult; Expression rightPre = defRight.FirstArgument; Expression rightPost = defRight.FirstResult; uint leftPreSize = leftPre .Type.UnderlyingType.Size; uint leftPostSize = leftPost .Type.UnderlyingType.Size; uint rightPreSize = rightPre .Type.UnderlyingType.Size; uint rightPostSize = rightPost.Type.UnderlyingType.Size; if(leftPreSize == leftPostSize && defLeft .SignificantSize == leftPostSize && rightPreSize == rightPostSize && defRight.SignificantSize == rightPostSize ) { // // The extend ops are no-ops, most likely due to the requirement of loading an int/long into the evaluation stack. // // Shortcut the binary operator to use the pre-extension values. // ShortcutBinaryOperation( nc, op, op.Signed, exLhs, leftPre, rightPre ); return; } if(leftPreSize == 4 && leftPostSize == 8 && rightPreSize == 4 && rightPostSize == 8 ) { // // This is a 32 -> 64 bit extension. Can we remove the 64 bit operation? // if(use != null && use.SignificantSize == 4) { // // It's a 32->64->32 sequence of operations. // if(op.CheckOverflow == false) { switch(op.Alu) { case BinaryOperator.ALU.ADD: case BinaryOperator.ALU.SUB: case BinaryOperator.ALU.MUL: case BinaryOperator.ALU.AND: case BinaryOperator.ALU.OR : ShortcutBinaryOperation( nc, op, use.FirstResult.Type.IsSigned, use.FirstResult, leftPre, rightPre ); use.Delete(); nc.StopScan(); return; } } } else { // // It's a 32x32->64 sequence of operations. // if(op.CheckOverflow == false) { switch(op.Alu) { case BinaryOperator.ALU.MUL: ShortcutBinaryOperation( nc, op, exLhs.Type.IsSigned, exLhs, leftPre, rightPre ); return; } } } } } if(defLeft != null && exConstRight != null) { Expression leftPre = defLeft.FirstArgument; Expression leftPost = defLeft.FirstResult; uint leftPreSize = leftPre .Type.UnderlyingType.Size; uint leftPostSize = leftPost .Type.UnderlyingType.Size; uint rightSize = exConstRight.Type.UnderlyingType.Size; if(leftPreSize == leftPostSize && defLeft.SignificantSize == leftPostSize) { // // The extend ops are no-ops, most likely due to the requirement of loading an int/long into the evaluation stack. // // Shortcut the binary operator to use the pre-extension values. // ShortcutBinaryOperation( nc, op, op.Signed, exLhs, leftPre, exConstRight ); return; } if(leftPreSize == 4 && leftPostSize == 8 && rightSize == 8) { ulong val; if(exConstRight.GetAsRawUlong( out val )) { ConstantExpression exConstRightShort = nc.TypeSystem.CreateConstant( leftPre.Type, ConstantExpression.ConvertToType( leftPre.Type, val ) ); // // This is a 32 -> 64 bit extension. Can we remove the 64 bit operation? // if(use != null && use.SignificantSize == 4) { // // It's a 32->64->32 sequence of operations. // if(op.CheckOverflow == false) { switch(op.Alu) { case BinaryOperator.ALU.ADD: case BinaryOperator.ALU.SUB: case BinaryOperator.ALU.MUL: case BinaryOperator.ALU.AND: case BinaryOperator.ALU.OR : ShortcutBinaryOperation( nc, op, use.FirstResult.Type.IsSigned, use.FirstResult, leftPre, exConstRightShort ); use.Delete(); nc.StopScan(); return; } } } else { ulong valPost; exConstRightShort.GetAsRawUlong( out valPost ); if(valPost == val) { // // It's a 32x32->64 sequence of operations. // if(op.CheckOverflow == false) { switch(op.Alu) { case BinaryOperator.ALU.MUL: ShortcutBinaryOperation( nc, op, exLhs.Type.IsSigned, exLhs, leftPre, exConstRightShort ); return; } } } } } } } if(exConstLeft != null && defRight != null) { Expression rightPre = defRight.FirstArgument; Expression rightPost = defRight.FirstResult; uint rightPreSize = rightPre .Type.UnderlyingType.Size; uint rightPostSize = rightPost .Type.UnderlyingType.Size; uint leftSize = exConstLeft.Type.UnderlyingType.Size; if(rightPreSize == rightPostSize && defRight.SignificantSize == rightPostSize) { // // The extend ops are no-ops, most likely due to the requirement of loading an int/long into the evaluation stack. // // Shortcut the binary operator to use the pre-extension values. // ShortcutBinaryOperation( nc, op, op.Signed, exLhs, exConstLeft, rightPre ); return; } if(rightPreSize == 4 && rightPostSize == 8 && leftSize == 8) { ulong val; if(exConstRight.GetAsRawUlong( out val )) { ConstantExpression exConstLeftShort = nc.TypeSystem.CreateConstant( rightPre.Type, ConstantExpression.ConvertToType( rightPre.Type, val ) ); // // This is a 32 -> 64 bit extension. Can we remove the 64 bit operation? // if(use != null && use.SignificantSize == 4) { // // It's a 32->64->32 sequence of operations. // if(op.CheckOverflow == false) { switch(op.Alu) { case BinaryOperator.ALU.ADD: case BinaryOperator.ALU.SUB: case BinaryOperator.ALU.MUL: case BinaryOperator.ALU.AND: case BinaryOperator.ALU.OR : ShortcutBinaryOperation( nc, op, use.FirstResult.Type.IsSigned, use.FirstResult, exConstLeftShort, rightPre ); use.Delete(); nc.StopScan(); return; } } } else { ulong valPost; exConstLeftShort.GetAsRawUlong( out valPost ); if(valPost == val) { // // It's a 32x32->64 sequence of operations. // if(op.CheckOverflow == false) { switch(op.Alu) { case BinaryOperator.ALU.MUL: ShortcutBinaryOperation( nc, op, exLhs.Type.IsSigned, exLhs, exConstLeftShort, rightPre ); return; } } } } } } } } private static ConversionOperator IsArgumentAsTypeConversion( ControlFlowGraphStateForCodeTransformation cfg , Expression ex , bool fGetDefinition ) { if(ex is VariableExpression) { Operator[][] useChains = cfg.DataFlow_UseChains; Operator[][] defChains = cfg.DataFlow_DefinitionChains; int idx = ex.SpanningTreeIndex; Operator[] uses = useChains[idx]; Operator[] defs = defChains[idx]; if(uses.Length == 1 && defs.Length == 1 ) { Operator res = fGetDefinition ? defs[0] : uses[0]; return res as ConversionOperator; } } return null; } private static void ShortcutBinaryOperation( PhaseExecution.NotificationContext nc , BinaryOperator op , bool fSigned , VariableExpression lhs , Expression left , Expression right ) { BinaryOperator opNew = BinaryOperator.New( op.DebugInfo, op.Alu, fSigned, op.CheckOverflow, lhs, left, right ); op.SubstituteWithOperator( opNew, Operator.SubstitutionFlags.CopyAnnotations ); nc.MarkAsModified(); } //--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--// //--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--// //--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--// private static TemporaryVariableExpression FetchTypeSystemManager( PhaseExecution.NotificationContext nc , Operator op ) { TypeSystemForCodeTransformation typeSystem = nc.TypeSystem; MethodRepresentation mdTypeSystemManager = typeSystem.WellKnownMethods.TypeSystemManager_get_Instance; TemporaryVariableExpression typeSystemManagerEx = nc.AllocateTemporary( mdTypeSystemManager.ReturnType ); CallOperator call; Expression[] rhs; rhs = typeSystem.AddTypePointerToArgumentsOfStaticMethod( mdTypeSystemManager ); call = StaticCallOperator.New( op.DebugInfo, CallOperator.CallKind.Direct, mdTypeSystemManager, VariableExpression.ToArray( typeSystemManagerEx ), rhs ); op.AddOperatorBefore( call ); nc.MarkAsModified(); return typeSystemManagerEx; } } } ================================================ FILE: Zelig/Zelig/CompileTime/CodeGenerator/CodeTransformation/CompilationSteps/Handlers/OperatorHandlers_HighLevelToMidLevel.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // namespace Microsoft.Zelig.CodeGeneration.IR.CompilationSteps.Handlers { using System; using System.Collections.Generic; using Microsoft.Zelig.Runtime.TypeSystem; public class OperatorHandlers_HighLevelToMidLevel { //--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--// //--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--// //--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--// [CompilationSteps.PhaseFilter( typeof(Phases.HighLevelToMidLevelConversion) )] [CompilationSteps.OperatorHandler( typeof(LeaveControlOperator) )] private static void Handle_LeaveControlOperator( PhaseExecution.NotificationContext nc ) { LeaveControlOperator op = (LeaveControlOperator)nc.CurrentOperator; UnconditionalControlOperator opNew = UnconditionalControlOperator.New( op.DebugInfo, op.TargetBranch ); op.SubstituteWithOperator( opNew, Operator.SubstitutionFlags.Default ); nc.MarkAsModified(); } //--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--// //--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--// //--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--// private static VariableExpression LoadVirtualMethodPointer( PhaseExecution.NotificationContext nc, InstanceCallOperator call, Expression target, MethodRepresentation method) { TypeSystemForCodeTransformation typeSystem = nc.TypeSystem; Debugging.DebugInfo debugInfo = call.DebugInfo; TemporaryVariableExpression methodPointer; if ( method.OwnerType is InterfaceTypeRepresentation ) { // Load MethodPointers for interface. MethodRepresentation mdVTableGetInterface = typeSystem.WellKnownMethods.VTable_GetInterface; TemporaryVariableExpression methodPointers = nc.AllocateTemporary( mdVTableGetInterface.ReturnType ); Expression[] rhs = typeSystem.AddTypePointerToArgumentsOfStaticMethod( mdVTableGetInterface, target, typeSystem.GetVTable( method.OwnerType ) ); CallOperator newCall = StaticCallOperator.New( debugInfo, CallOperator.CallKind.Direct, mdVTableGetInterface, VariableExpression.ToArray( methodPointers ), rhs ); call.AddOperatorBefore( newCall ); // Load the code pointer from the list. No null or range check, we know both will always pass. int idx = method.FindInterfaceTableIndex(); methodPointer = nc.AllocateTemporary( methodPointers.Type.ContainedType ); call.AddOperatorBefore( LoadElementOperator.New( debugInfo, methodPointer, methodPointers, typeSystem.CreateConstant( idx ), null, false ) ); } else { // Load the target object's VTable. MethodRepresentation mdVTableGet = typeSystem.WellKnownMethods.VTable_Get; TemporaryVariableExpression tmpVTable = nc.AllocateTemporary( mdVTableGet.OwnerType ); Expression[] rhs = typeSystem.AddTypePointerToArgumentsOfStaticMethod( mdVTableGet, target ); CallOperator newCall = StaticCallOperator.New( debugInfo, CallOperator.CallKind.Direct, mdVTableGet, VariableExpression.ToArray( tmpVTable ), rhs ); call.AddOperatorBefore( newCall ); // Get method code pointers. The VTable can never be null here, so don't add null-checks. FieldRepresentation fdMethodPointers = typeSystem.WellKnownFields.VTable_MethodPointers; TemporaryVariableExpression methodPointers = nc.AllocateTemporary( fdMethodPointers.FieldType ); call.AddOperatorBefore( LoadInstanceFieldOperator.New( debugInfo, fdMethodPointers, methodPointers, tmpVTable, false ) ); // Load the code pointer from the list. No null or range check, we know both will always pass. int index = method.FindVirtualTableIndex(); methodPointer = nc.AllocateTemporary( methodPointers.Type.ContainedType ); call.AddOperatorBefore( LoadElementOperator.New( debugInfo, methodPointer, methodPointers, typeSystem.CreateConstant( index ), null, false ) ); } return methodPointer; } //--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--// //--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--// //--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--// [CompilationSteps.PhaseFilter( typeof(Phases.HighLevelToMidLevelConversion) )] [CompilationSteps.OperatorHandler( typeof(InstanceCallOperator) )] private static void Handle_Convert_VirtualCallOperator( PhaseExecution.NotificationContext nc ) { InstanceCallOperator op = (InstanceCallOperator)nc.CurrentOperator; TypeSystemForCodeTransformation typeSystem = nc.TypeSystem; if(op.CallType == CallOperator.CallKind.Virtual) { if(MethodTransformations.AttemptDevirtualization( typeSystem, op )) { nc.MarkAsModified(); return; } VariableExpression methodPointer = LoadVirtualMethodPointer( nc, op, op.FirstArgument, op.TargetMethod ); Expression[] rhs = ArrayUtility.InsertAtHeadOfNotNullArray( op.Arguments, methodPointer ); CallOperator call = IndirectCallOperator.New( op.DebugInfo, op.TargetMethod, op.Results, rhs, true, false ); op.SubstituteWithOperator( call, Operator.SubstitutionFlags.CopyAnnotations ); nc.MarkAsModified(); } } //--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--// //--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--// //--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--// [CompilationSteps.PhaseFilter( typeof(Phases.HighLevelToMidLevelConversion) )] [CompilationSteps.OperatorHandler( typeof(MethodRepresentationOperator) )] private static void Handle_Convert_DelegateCreation( PhaseExecution.NotificationContext nc ) { ControlFlowGraphStateForCodeTransformation cfg = nc.CurrentCFG; MethodRepresentationOperator op = (MethodRepresentationOperator)nc.CurrentOperator; MethodRepresentation mdDelegate = op.Method; VariableExpression mdPtr = op.FirstResult; Operator def = cfg.FindSingleDefinition( mdPtr ); InstanceCallOperator call = cfg.FindSingleUse ( mdPtr ) as InstanceCallOperator; if(def != null && call != null) { TypeSystemForCodeTransformation typeSystem = nc.TypeSystem; WellKnownMethods wkm = typeSystem.WellKnownMethods; Debugging.DebugInfo debugInfo = call.DebugInfo; Expression dlg = call.FirstArgument; Expression target = call.SecondArgument; Expression exCode; CallOperator newCall; Expression[] rhs; if(op.Arguments.Length == 0) { // // Direct method. // CodePointer cp = typeSystem.CreateCodePointer( mdDelegate ); WellKnownTypes wkt = typeSystem.WellKnownTypes; exCode = typeSystem.CreateConstant( wkt.Microsoft_Zelig_Runtime_TypeSystem_CodePointer, cp ); } else { // // Virtual method. // Expression source = op.FirstArgument; if(source != target) { throw TypeConsistencyErrorException.Create( "Cannot create an instance delegate on '{0}' when the method comes from '{1}'", target, source ); } exCode = LoadVirtualMethodPointer( nc, call, target, mdDelegate ); } foreach( MethodRepresentation mdParent in call.TargetMethod.OwnerType.Extends.Methods ) { if( mdParent is ConstructorMethodRepresentation ) { rhs = new Expression[ ] { dlg, target, exCode }; newCall = InstanceCallOperator.New( debugInfo, CallOperator.CallKind.Direct, mdParent, call.Results, rhs, true ); call.SubstituteWithOperator( newCall, Operator.SubstitutionFlags.CopyAnnotations ); // // Make sure we get rid of the LDFTN/LDVIRTFTN operators. // op.Delete( ); nc.StopScan( ); return; } } } throw TypeConsistencyErrorException.Create( "Unsupported delegate creation at {0}", op ); } //--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--// //--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--// //--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--// [CompilationSteps.PhaseFilter( typeof(Phases.HighLevelToMidLevelConversion) )] [CompilationSteps.OperatorHandler( typeof(FieldOperator) )] private static void Handle_FieldOperator( PhaseExecution.NotificationContext nc ) { TypeSystemForCodeTransformation ts = nc.TypeSystem; FieldOperator op = (FieldOperator)nc.CurrentOperator; ControlFlowGraphStateForCodeTransformation cfg = nc.CurrentCFG; Debugging.DebugInfo debugInfo = op.DebugInfo; FieldRepresentation fd = op.Field; { CustomAttributeRepresentation caFd; if(ts.RegisterAttributes.TryGetValue( fd, out caFd )) { TypeRepresentation tdField = fd.FieldType; if(tdField is ScalarTypeRepresentation) { // // Scalar fields are handled normally. // } else if(ts.MemoryMappedBitFieldPeripherals.ContainsKey( tdField )) { // // Bitfields are handled normally. // } else { TypeRepresentation tdTarget; if(tdField is ArrayReferenceTypeRepresentation) { tdTarget = tdField.ContainedType; } else { tdTarget = tdField; } if(ts.MemoryMappedPeripherals.ContainsKey( tdTarget ) == false) { if(tdTarget is ScalarTypeRepresentation) { // // Accept memory-mapped arrays of scalar types. // } else if(ts.MemoryMappedBitFieldPeripherals.ContainsKey( tdTarget )) { // // Arrays of bitfields are handled normally. // } else { throw TypeConsistencyErrorException.Create( "Cannot use type '{0}' for Register field '{1}'", tdField.FullNameWithAbbreviation, fd.ToShortString() ); } } Operator opNew; uint offset = (uint)caFd.GetNamedArg( "Offset" ); if(op is LoadInstanceFieldAddressOperator) { throw TypeConsistencyErrorException.Create( "Cannot take the address of section '{0}' of memory-mapped peripheral '{1}'", fd.Name, fd.OwnerType.FullNameWithAbbreviation ); } else if(op is LoadInstanceFieldOperator) { opNew = BinaryOperator.New( debugInfo, BinaryOperator.ALU.ADD, false, false, op.FirstResult, op.FirstArgument, nc.TypeSystem.CreateConstant( offset ) ); opNew.AddAnnotation( NotNullAnnotation .Create( ts ) ); opNew.AddAnnotation( MemoryMappedPeripheralAnnotation.Create( ts, caFd ) ); } else if(op is StoreInstanceFieldOperator) { throw TypeConsistencyErrorException.Create( "Cannot update reference to section '{0}' of memory-mapped peripheral '{1}'", fd.Name, fd.OwnerType.FullNameWithAbbreviation ); } else { throw TypeConsistencyErrorException.Create( "Unexpected operator {0} at phase {1}", op, nc.Phase ); } CHECKS.ASSERT( opNew.MayThrow == false, "Failed to lower call operator {0}", op ); op.SubstituteWithOperator( opNew, Operator.SubstitutionFlags.CopyAnnotations ); nc.MarkAsModified(); return; } } } { BitFieldDefinition bfDef; if(ts.BitFieldRegisterAttributes.TryGetValue( fd, out bfDef )) { if((fd.FieldType is ScalarTypeRepresentation) == false) { throw TypeConsistencyErrorException.Create( "Unexpected operator {0} at phase {1}", op, nc.Phase ); } bool fLoad; if(op is LoadInstanceFieldAddressOperator) { throw TypeConsistencyErrorException.Create( "Cannot take the address of section '{0}' of memory-mapped peripheral '{1}'", fd.Name, fd.OwnerType.FullNameWithAbbreviation ); } else if(op is LoadInstanceFieldOperator) { fLoad = true; } else if(op is StoreInstanceFieldOperator) { fLoad = false; } else { throw TypeConsistencyErrorException.Create( "Unexpected operator {0} at phase {1}", op, nc.Phase ); } //--// bool fSigned = fd.FieldType.IsSigned; TypeRepresentation td = fd.OwnerType; CustomAttributeRepresentation caTd = ts.MemoryMappedBitFieldPeripherals[td]; TypeRepresentation tdPhysical = caTd.GetNamedArg< TypeRepresentation >( "PhysicalType" ); VariableExpression tmp = nc.CurrentCFG.AllocateTemporary( tdPhysical, null ); Operator opNew; op.AddOperatorBefore( LoadIndirectOperator.New( debugInfo, tdPhysical, tmp, op.FirstArgument, null, fd.Offset, true, false ) ); if(bfDef.Sections.Length == 1) { var sec = bfDef.Sections[0]; uint position = sec.Position; uint size = sec.Size; Runtime.BitFieldModifier modifiers = sec.Modifiers; //--// uint mask = (1u << (int)size) - 1u; uint maskShifted = mask << (int)position; if(fLoad) { if(position == 0 && fSigned == false) { // // TODO: Add ability to verify with Platform Abstraction if it's possible to encode the constant in a single instruction. // opNew = BinaryOperator.New( debugInfo, BinaryOperator.ALU.AND, false, false, op.FirstResult, tmp, ts.CreateConstant( mask ) ); } else { // // We need to load the physical register, and extract the bitfield, which we achieve with a left/right shift pair. // VariableExpression tmp2 = nc.CurrentCFG.AllocateTemporary( tdPhysical, null ); op.AddOperatorBefore( BinaryOperator.New( debugInfo, BinaryOperator.ALU.SHL, false , false, tmp2 , tmp , ts.CreateConstant( 32 - (position + size) ) ) ); opNew = BinaryOperator.New( debugInfo, BinaryOperator.ALU.SHR, fSigned, false, op.FirstResult, tmp2, ts.CreateConstant( 32 - size ) ); } } else { if(size == 1 && op.SecondArgument is ConstantExpression) { // // Setting/clearing a single bit. No need to perform complex masking. // ConstantExpression ex = (ConstantExpression)op.SecondArgument; ulong val; if(ex.GetAsUnsignedInteger( out val ) == false) { throw TypeConsistencyErrorException.Create( "Expecting a numeric constant, got '{0}'", ex ); } VariableExpression tmp2 = nc.CurrentCFG.AllocateTemporary( tdPhysical, null ); if((val & 1) != 0) { ConstantExpression exMask = ts.CreateConstant( maskShifted ); op.AddOperatorBefore( BinaryOperator.New( debugInfo, BinaryOperator.ALU.OR, false, false, tmp2, tmp, exMask ) ); } else { ConstantExpression exMaskNot = ts.CreateConstant( ~maskShifted ); op.AddOperatorBefore( BinaryOperator.New( debugInfo, BinaryOperator.ALU.AND, false, false, tmp2, tmp, exMaskNot ) ); } opNew = StoreIndirectOperator.New( debugInfo, td, op.FirstArgument, tmp2, null, fd.Offset, false ); } else { // // We need to load the physical register, shift it and mask it, then mask and merge with the new value, and finally write it back. // VariableExpression tmp2 = nc.CurrentCFG.AllocateTemporary( tdPhysical, null ); VariableExpression tmp3 = nc.CurrentCFG.AllocateTemporary( tdPhysical, null ); VariableExpression tmp4 = nc.CurrentCFG.AllocateTemporary( tdPhysical, null ); VariableExpression tmp5 = nc.CurrentCFG.AllocateTemporary( tdPhysical, null ); ConstantExpression exMask = ts.CreateConstant( maskShifted ); ConstantExpression exMaskNot = ts.CreateConstant( ~maskShifted ); op.AddOperatorBefore( BinaryOperator.New( debugInfo, BinaryOperator.ALU.SHL, false, false, tmp2, op.SecondArgument, ts.CreateConstant( position ) ) ); op.AddOperatorBefore( BinaryOperator.New( debugInfo, BinaryOperator.ALU.AND, false, false, tmp3, tmp2 , exMask ) ); op.AddOperatorBefore( BinaryOperator.New( debugInfo, BinaryOperator.ALU.AND, false, false, tmp4, tmp , exMaskNot ) ); op.AddOperatorBefore( BinaryOperator.New( debugInfo, BinaryOperator.ALU.OR , false, false, tmp5, tmp3 , tmp4 ) ); opNew = StoreIndirectOperator.New( debugInfo, td, op.FirstArgument, tmp5, null, fd.Offset, false ); } } } else { uint totalSize = bfDef.TotalSize; VariableExpression lastVar = null; foreach(var sec in bfDef.Sections) { uint position = sec.Position; uint size = sec.Size; uint offset = sec.Offset; Runtime.BitFieldModifier modifiers = sec.Modifiers; //--// uint mask = (1u << (int)size) - 1u; uint maskShifted = mask << (int)position; VariableExpression newVar = nc.CurrentCFG.AllocateTemporary( tdPhysical, null ); if(fLoad) { bool fLastSection = (offset + size == totalSize); bool fSigned2 = fSigned && fLastSection; VariableExpression newVarUnshifted = nc.CurrentCFG.AllocateTemporary( tdPhysical, null ); if(position == 0 && fSigned2 == false) { // // TODO: Add ability to verify with Platform Abstraction if it's possible to encode the constant in a single instruction. // op.AddOperatorBefore( BinaryOperator.New( debugInfo, BinaryOperator.ALU.AND, false, false, newVarUnshifted, tmp, ts.CreateConstant( mask ) ) ); } else { // // We need to load the physical register, and extract the bitfield, which we achieve with a left/right shift pair. // VariableExpression tmp2 = nc.CurrentCFG.AllocateTemporary( tdPhysical, null ); op.AddOperatorBefore( BinaryOperator.New( debugInfo, BinaryOperator.ALU.SHL, false , false, tmp2 , tmp , ts.CreateConstant( 32 - (position + size) ) ) ); op.AddOperatorBefore( BinaryOperator.New( debugInfo, BinaryOperator.ALU.SHR, fSigned2, false, newVarUnshifted, tmp2, ts.CreateConstant( 32 - size ) ) ); } op.AddOperatorBefore( BinaryOperator.New( debugInfo, BinaryOperator.ALU.SHL, false, false, newVar, newVarUnshifted, ts.CreateConstant( offset ) ) ); if(lastVar != null) { VariableExpression mergeVar = nc.CurrentCFG.AllocateTemporary( tdPhysical, null ); op.AddOperatorBefore( BinaryOperator.New( debugInfo, BinaryOperator.ALU.OR, false, false, mergeVar, lastVar, newVar ) ); lastVar = mergeVar; } else { lastVar = newVar; } } else { if(size == 1 && op.SecondArgument is ConstantExpression) { // // Setting/clearing a single bit. No need to perform complex masking. // ConstantExpression ex = (ConstantExpression)op.SecondArgument; ulong val; if(ex.GetAsUnsignedInteger( out val ) == false) { throw TypeConsistencyErrorException.Create( "Expecting a numeric constant, got '{0}'", ex ); } if((val & (1u << (int)offset)) != 0) { ConstantExpression exMask = ts.CreateConstant( maskShifted ); op.AddOperatorBefore( BinaryOperator.New( debugInfo, BinaryOperator.ALU.OR, false, false, newVar, tmp, exMask ) ); } else { ConstantExpression exMaskNot = ts.CreateConstant( ~maskShifted ); op.AddOperatorBefore( BinaryOperator.New( debugInfo, BinaryOperator.ALU.AND, false, false, newVar, tmp, exMaskNot ) ); } } else { // // We need to load the physical register, shift it and mask it, then mask and merge with the new value, and finally write it back. // VariableExpression tmp2 = nc.CurrentCFG.AllocateTemporary( tdPhysical, null ); VariableExpression tmp3 = nc.CurrentCFG.AllocateTemporary( tdPhysical, null ); VariableExpression tmp4 = nc.CurrentCFG.AllocateTemporary( tdPhysical, null ); ConstantExpression exMask = ts.CreateConstant( maskShifted ); ConstantExpression exMaskNot = ts.CreateConstant( ~maskShifted ); if(position > offset) { op.AddOperatorBefore( BinaryOperator.New( debugInfo, BinaryOperator.ALU.SHL, false, false, tmp2, op.SecondArgument, ts.CreateConstant( position - offset ) ) ); } else { op.AddOperatorBefore( BinaryOperator.New( debugInfo, BinaryOperator.ALU.SHR, false, false, tmp2, op.SecondArgument, ts.CreateConstant( offset - position ) ) ); } op.AddOperatorBefore( BinaryOperator.New( debugInfo, BinaryOperator.ALU.AND, false, false, tmp3 , tmp2, exMask ) ); op.AddOperatorBefore( BinaryOperator.New( debugInfo, BinaryOperator.ALU.AND, false, false, tmp4 , tmp , exMaskNot ) ); op.AddOperatorBefore( BinaryOperator.New( debugInfo, BinaryOperator.ALU.OR , false, false, newVar, tmp3, tmp4 ) ); } lastVar = newVar; tmp = lastVar; } } if(fLoad) { opNew = SingleAssignmentOperator.New( debugInfo, op.FirstResult, lastVar ); } else { opNew = StoreIndirectOperator.New( debugInfo, td, op.FirstArgument, lastVar, null, fd.Offset, false ); } } CHECKS.ASSERT( opNew.MayThrow == false, "Failed to lower call operator {0}", op ); op.SubstituteWithOperator( opNew, Operator.SubstitutionFlags.CopyAnnotations ); nc.MarkAsModified(); return; } } if(op.MayThrow) { FieldOperator opNew; op.AddOperatorBefore( NullCheckOperator.New( debugInfo, op.FirstArgument ) ); if(op is LoadInstanceFieldAddressOperator) { opNew = LoadInstanceFieldAddressOperator.New( debugInfo, fd, op.FirstResult, op.FirstArgument, false ); opNew.AddAnnotation( NotNullAnnotation.Create( ts ) ); } else if(op is LoadInstanceFieldOperator) { opNew = LoadInstanceFieldOperator.New( debugInfo, fd, op.FirstResult, op.FirstArgument, false ); } else if(op is StoreInstanceFieldOperator) { opNew = StoreInstanceFieldOperator.New( debugInfo, fd, op.FirstArgument, op.SecondArgument, false ); } else { throw TypeConsistencyErrorException.Create( "Unexpected operator {0} at phase {1}", op, nc.Phase ); } CHECKS.ASSERT( opNew.MayThrow == false, "Failed to lower call operator {0}", op ); op.SubstituteWithOperator( opNew, Operator.SubstitutionFlags.CopyAnnotations ); op = opNew; nc.MarkAsModified(); } if(op is LoadInstanceFieldOperator) { if((fd.Flags & FieldRepresentation.Attributes.NeverNull) != 0) { if(op.AddAnnotation( NotNullAnnotation.Create( ts ) )) { nc.MarkAsModified(); } } if((fd.Flags & FieldRepresentation.Attributes.HasFixedSize) != 0) { if(op.AddAnnotation( FixedLengthArrayAnnotation.Create( ts, fd.FixedSize ) )) { nc.MarkAsModified(); } } } } //--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--// //--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--// //--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--// [CompilationSteps.PhaseFilter( typeof(Phases.HighLevelToMidLevelConversion) )] [CompilationSteps.OperatorHandler( typeof(ElementOperator) )] private static void Handle_ElementOperator( PhaseExecution.NotificationContext nc ) { TypeSystemForCodeTransformation ts = nc.TypeSystem; ElementOperator op = (ElementOperator)nc.CurrentOperator; Debugging.DebugInfo debugInfo = op.DebugInfo; Expression exArray = op.FirstArgument; TypeRepresentation tdElement = exArray.Type.ContainedType; MemoryMappedPeripheralAnnotation anMemoryMapped = null; if(exArray is VariableExpression) { foreach(Operator arrayDef in nc.CurrentCFG.DataFlow_DefinitionChains[exArray.SpanningTreeIndex]) { MemoryMappedPeripheralAnnotation an = arrayDef.GetAnnotation< MemoryMappedPeripheralAnnotation >(); if(an != null) { if(tdElement is ScalarTypeRepresentation) { anMemoryMapped = an; break; } if(ts.MemoryMappedBitFieldPeripherals.ContainsKey( tdElement )) { anMemoryMapped = an; break; } //--// CustomAttributeRepresentation ca; if(ts.MemoryMappedPeripherals.TryGetValue( tdElement, out ca )) { uint size = (uint)ca.GetNamedArg( "Length" ); if(op is LoadElementAddressOperator) { throw TypeConsistencyErrorException.Create( "Cannot take the address of an array of memory-mapped sections '{0}'", tdElement.FullNameWithAbbreviation ); } else if(op is LoadElementOperator) { TemporaryVariableExpression tmpOffset = nc.AllocateTemporary( nc.TypeSystem.WellKnownTypes.System_UInt32 ); Operator opNew; opNew = BinaryOperator.New( debugInfo, BinaryOperator.ALU.MUL, false, false, tmpOffset, op.SecondArgument, nc.TypeSystem.CreateConstant( size ) ); op.AddOperatorBefore( opNew ); opNew = BinaryOperator.New( debugInfo, BinaryOperator.ALU.ADD, false, false, op.FirstResult, exArray, tmpOffset ); opNew.AddAnnotation( NotNullAnnotation .Create( ts ) ); opNew.AddAnnotation( MemoryMappedPeripheralAnnotation.Create( ts, ca ) ); CHECKS.ASSERT( opNew.MayThrow == false, "Failed to lower call operator {0}", op ); op.SubstituteWithOperator( opNew, Operator.SubstitutionFlags.CopyAnnotations ); nc.MarkAsModified(); return; } else if(op is StoreElementOperator) { throw TypeConsistencyErrorException.Create( "Cannot update reference to an array of memory-mapped sections '{0}'", tdElement.FullNameWithAbbreviation ); } else { throw TypeConsistencyErrorException.Create( "Unexpected operator {0} at phase {1}", op, nc.Phase ); } } } } } if(op.MayThrow) { ElementOperator opNew; if(anMemoryMapped == null) { op.AddOperatorBefore( NullCheckOperator .New( debugInfo, op.FirstArgument ) ); op.AddOperatorBefore( OutOfBoundCheckOperator.New( debugInfo, op.FirstArgument, op.SecondArgument ) ); } if(op is LoadElementAddressOperator) { opNew = LoadElementAddressOperator.New( debugInfo, op.FirstResult, op.FirstArgument, op.SecondArgument, op.AccessPath, false ); opNew.AddAnnotation( NotNullAnnotation.Create( ts ) ); } else if(op is LoadElementOperator) { opNew = LoadElementOperator.New( debugInfo, op.FirstResult, op.FirstArgument, op.SecondArgument, op.AccessPath, false ); } else if(op is StoreElementOperator) { opNew = StoreElementOperator.New( debugInfo, op.FirstArgument, op.SecondArgument, op.ThirdArgument, op.AccessPath, false ); } else { throw TypeConsistencyErrorException.Create( "Unexpected operator {0} at phase {1}", op, nc.Phase ); } if(anMemoryMapped != null) { opNew.AddAnnotation( anMemoryMapped ); } CHECKS.ASSERT( opNew.MayThrow == false, "Failed to lower call operator {0}", op ); op.SubstituteWithOperator( opNew, Operator.SubstitutionFlags.CopyAnnotations ); nc.MarkAsModified(); } } //--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--// //--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--// //--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--// [CompilationSteps.PhaseFilter( typeof(Phases.HighLevelToMidLevelConversion) )] [CompilationSteps.OperatorHandler( typeof(IndirectOperator) )] private static void Handle_IndirectOperator( PhaseExecution.NotificationContext nc ) { IndirectOperator op = (IndirectOperator)nc.CurrentOperator; if(op.MayThrow) { Debugging.DebugInfo debugInfo = op.DebugInfo; bool fIsVolatile = op.MayMutateExistingStorage; Operator opNew; op.AddOperatorBefore( NullCheckOperator.New( debugInfo, op.FirstArgument ) ); if(op is LoadIndirectOperator) { opNew = LoadIndirectOperator.New( debugInfo, op.Type, op.FirstResult, op.FirstArgument, op.AccessPath, op.Offset, fIsVolatile, false ); } else if(op is StoreIndirectOperator) { opNew = StoreIndirectOperator.New( debugInfo, op.Type, op.FirstArgument, op.SecondArgument, op.AccessPath, op.Offset, false ); } else { throw TypeConsistencyErrorException.Create( "Unexpected operator {0} at phase {1}", op, nc.Phase ); } CHECKS.ASSERT( opNew.MayThrow == false, "Failed to lower call operator {0}", op ); op.SubstituteWithOperator( opNew, Operator.SubstitutionFlags.CopyAnnotations ); nc.MarkAsModified(); } } //--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--// //--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--// //--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--// [CompilationSteps.PhaseFilter( typeof(Phases.HighLevelToMidLevelConversion) )] [CompilationSteps.OperatorHandler( typeof(CallOperator) )] private static void Handle_CallOperator( PhaseExecution.NotificationContext nc ) { CallOperator op = (CallOperator)nc.CurrentOperator; if(nc.TypeSystem.GetLevel( op )> Operator.OperatorLevel.ConcreteTypes_NoExceptions) { Debugging.DebugInfo debugInfo = op.DebugInfo; CallOperator opNew; if(op is InstanceCallOperator) { op.AddOperatorBefore( NullCheckOperator.New( debugInfo, op.FirstArgument ) ); opNew = InstanceCallOperator.New( debugInfo, op.CallType, op.TargetMethod, op.Results, op.Arguments, false ); } else if(op is IndirectCallOperator) { op.AddOperatorBefore( NullCheckOperator.New( debugInfo, op.FirstArgument ) ); if(op.TargetMethod is InstanceMethodRepresentation) { op.AddOperatorBefore( NullCheckOperator.New( debugInfo, op.SecondArgument ) ); } bool isInstanceCall = ((IndirectCallOperator)op).IsInstanceCall; opNew = IndirectCallOperator.New(debugInfo, op.TargetMethod, op.Results, op.Arguments, isInstanceCall, false); } else { throw TypeConsistencyErrorException.Create( "Unexpected operator {0} at phase {1}", op, nc.Phase ); } CHECKS.ASSERT( nc.TypeSystem.GetLevel( opNew )<= Operator.OperatorLevel.ConcreteTypes_NoExceptions, "Failed to lower call operator {0}", op ); op.SubstituteWithOperator( opNew, Operator.SubstitutionFlags.CopyAnnotations ); nc.MarkAsModified(); } } } } ================================================ FILE: Zelig/Zelig/CompileTime/CodeGenerator/CodeTransformation/CompilationSteps/Handlers/OperatorHandlers_MidLevelToLowLevel.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // namespace Microsoft.Zelig.CodeGeneration.IR.CompilationSteps.Handlers { using System; using System.Collections.Generic; using Microsoft.Zelig.Runtime.TypeSystem; public class OperatorHandlers_MidLevelToLowLevel { [CompilationSteps.PhaseFilter( typeof(Phases.MidLevelToLowLevelConversion) )] [CompilationSteps.OperatorHandler( typeof(FieldOperator) )] private static void Handle_FieldOperator( PhaseExecution.NotificationContext nc ) { FieldOperator op = (FieldOperator)nc.CurrentOperator; FieldRepresentation fd = op.Field; Debugging.DebugInfo debugInfo = op.DebugInfo; bool fIsVolatile = (fd.Flags & FieldRepresentation.Attributes.IsVolatile) != 0; Operator opNew; CHECKS.ASSERT( op.MayThrow == false, "Unexpected throwing operator: {0}", op ); if(op is LoadInstanceFieldAddressOperator) { opNew = BinaryOperator.New( debugInfo, BinaryOperator.ALU.ADD, false, false, op.FirstResult, op.FirstArgument, nc.TypeSystem.CreateConstant( fd.Offset ) ); } else if(op is LoadInstanceFieldOperator) { opNew = LoadIndirectOperator.New( debugInfo, fd.FieldType, op.FirstResult, op.FirstArgument, new FieldRepresentation[] { fd }, fd.Offset, fIsVolatile, false ); } else if(op is StoreInstanceFieldOperator) { opNew = StoreIndirectOperator.New( debugInfo, fd.FieldType, op.FirstArgument, op.SecondArgument, new FieldRepresentation[] { fd }, fd.Offset, false ); } else { throw TypeConsistencyErrorException.Create( "Unexpected operator {0} at phase {1}", op, nc.Phase ); } op.SubstituteWithOperator( opNew, Operator.SubstitutionFlags.CopyAnnotations ); nc.MarkAsModified(); } //--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--// //--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--// //--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--// [CompilationSteps.PhaseFilter( typeof(Phases.MidLevelToLowLevelConversion) )] [CompilationSteps.OperatorHandler( typeof(ElementOperator) )] private static void Handle_ElementOperator( PhaseExecution.NotificationContext nc ) { ElementOperator op = (ElementOperator)nc.CurrentOperator; Debugging.DebugInfo debugInfo = op.DebugInfo; Expression exArray = op.FirstArgument; Expression exIndex = op.SecondArgument; TypeRepresentation tdArray = exArray.Type; TypeRepresentation tdElement = tdArray.ContainedType; TypeRepresentation tdElementPtr = nc.TypeSystem.GetManagedPointerToType( tdElement ); TemporaryVariableExpression tmpPtr = nc.CurrentCFG.AllocateTemporary( tdElementPtr , null ); TemporaryVariableExpression tmpOffset = nc.CurrentCFG.AllocateTemporary( nc.TypeSystem.WellKnownTypes.System_Int32, null ); Operator opNew; // // Get a pointer to the first element. // if(op.HasAnnotation< MemoryMappedPeripheralAnnotation >()) { // // A memory-mapped array doesn't have any length field. // opNew = SingleAssignmentOperator.New( debugInfo, tmpPtr, exArray ); } else { // // Skip the length field. // opNew = BinaryOperator.New( debugInfo, BinaryOperator.ALU.ADD, false, false, tmpPtr, exArray, nc.TypeSystem.CreateConstant( tdArray.VirtualTable.BaseSize ) ); } opNew.AddAnnotation( NotNullAnnotation.Create( nc.TypeSystem ) ); op.AddOperatorBefore( opNew ); // // Compute byte-offset within the array. // op.AddOperatorBefore( BinaryOperator.New( debugInfo, BinaryOperator.ALU.MUL, false, false, tmpOffset, exIndex, nc.TypeSystem.CreateConstant( tdArray.VirtualTable.ElementSize ) ) ); // // Compute the address of the element to access. // op.AddOperatorBefore( BinaryOperator.New( debugInfo, BinaryOperator.ALU.ADD, false, false, tmpPtr, tmpPtr, tmpOffset ) ); if(op is LoadElementAddressOperator) { opNew = SingleAssignmentOperator.New( debugInfo, op.FirstResult, tmpPtr ); } else if(op is LoadElementOperator) { opNew = LoadIndirectOperator.New( debugInfo, tdElement, op.FirstResult, tmpPtr, op.AccessPath, 0, false, false ); } else if(op is StoreElementOperator) { opNew = StoreIndirectOperator.New( debugInfo, tdElement, tmpPtr, op.ThirdArgument, op.AccessPath, 0, false ); } else { throw TypeConsistencyErrorException.Create( "Unexpected operator {0} at phase {1}", op, nc.Phase ); } op.SubstituteWithOperator( opNew, Operator.SubstitutionFlags.CopyAnnotations ); nc.MarkAsModified(); } } } ================================================ FILE: Zelig/Zelig/CompileTime/CodeGenerator/CodeTransformation/CompilationSteps/Handlers/OperatorHandlers_ReferenceCountingGarbageCollection.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // namespace Microsoft.Zelig.CodeGeneration.IR.CompilationSteps.Handlers { using Microsoft.Zelig.CodeGeneration.IR.CompilationSteps.Phases; using Runtime.TypeSystem; using System; public class OperatorHandlers_ReferenceCountingGarbageCollection { [CompilationSteps.PhaseFilter( typeof( Phases.ReferenceCountingGarbageCollection ) )] [CompilationSteps.OperatorHandler( typeof( SingleAssignmentOperator ) )] [CompilationSteps.OperatorHandler( typeof( CallOperator ) )] [CompilationSteps.OperatorHandler( typeof( StoreInstanceFieldOperator ) )] [CompilationSteps.OperatorHandler( typeof( LoadInstanceFieldOperator ) )] [CompilationSteps.OperatorHandler( typeof( StoreElementOperator ) )] [CompilationSteps.OperatorHandler( typeof( LoadElementOperator ) )] [CompilationSteps.OperatorHandler( typeof( StoreIndirectOperator ) )] [CompilationSteps.OperatorHandler( typeof( LoadIndirectOperator ) )] private static void Handle_AssignmentOperators( PhaseExecution.NotificationContext nc ) { var op = nc.CurrentOperator; var ts = nc.TypeSystem; var phase = (ReferenceCountingGarbageCollection)nc.Phase; if(!ts.ShouldExcludeMethodFromReferenceCounting( op.BasicBlock.Owner.Method ) && !phase.IsOperatorModified( op )) { if(op is SingleAssignmentOperator) { Handle_SingleAssignmentOperator( nc ); } else if(op is CallOperator) { Handle_CallOperator( nc ); } else if(op is StoreInstanceFieldOperator) { Handle_StoreInstanceFieldOperator( nc ); } else if(op is LoadInstanceFieldOperator) { Handle_LoadInstanceFieldOperator( nc ); } else if(op is StoreElementOperator) { Handle_StoreElementOperator( nc ); } else if(op is LoadElementOperator) { Handle_LoadElementOperator( nc ); } else if(op is StoreIndirectOperator) { Handle_StoreIndirectOperator( nc ); } else if(op is LoadIndirectOperator) { Handle_LoadIndirectOperator( nc ); } phase.AddToModifiedOperator( op ); } } private enum RefCountType { None = 0, RefCounted, Pointer, Skipped, } private static RefCountType GetRefCountType( PhaseExecution.NotificationContext nc, Expression exp ) { var variable = exp as VariableExpression; if(variable != null) { var refCountType = GetRefCountType( nc, variable.Type ); if (refCountType == RefCountType.RefCounted && variable.SkipReferenceCounting) { return RefCountType.Skipped; } return refCountType; } return RefCountType.None; } private static RefCountType GetRefCountType( PhaseExecution.NotificationContext nc, TypeRepresentation type ) { var rctype = RefCountType.None; var ts = nc.TypeSystem; if(ts.IsReferenceCountingType( type )) { rctype = RefCountType.RefCounted; } else if(type == ts.WellKnownTypes.System_UIntPtr || type == ts.WellKnownTypes.System_IntPtr) { rctype = RefCountType.Pointer; } return rctype; } private static void InsertAddRefBefore( PhaseExecution.NotificationContext nc, Expression argument ) { InsertMethodHelper( nc, nc.TypeSystem.WellKnownMethods.ObjectHeader_AddReference, argument, insertBefore: true ); } private static void InsertAddRefAfter( PhaseExecution.NotificationContext nc, Expression argument ) { InsertMethodHelper( nc, nc.TypeSystem.WellKnownMethods.ObjectHeader_AddReference, argument, insertBefore: false ); } private static void InsertReleaseBefore( PhaseExecution.NotificationContext nc, Expression argument ) { InsertMethodHelper( nc, nc.TypeSystem.WellKnownMethods.ObjectHeader_ReleaseReference, argument, insertBefore: true ); } private static void InsertMethodHelper( PhaseExecution.NotificationContext nc, Runtime.TypeSystem.MethodRepresentation md, Expression argument, bool insertBefore ) { var op = nc.CurrentOperator; var ts = nc.TypeSystem; var rhs = ts.AddTypePointerToArgumentsOfStaticMethod( md, argument ); var call = StaticCallOperator.New( op.DebugInfo, CallOperator.CallKind.Direct, md, rhs ); if(insertBefore) { op.AddOperatorBefore( call ); } else { op.AddOperatorAfter( call ); } var phase = (Phases.ReferenceCountingGarbageCollection)nc.Phase; phase.AddToModifiedOperator( call ); phase.IncrementInjectionCount( md ); nc.MarkAsModified( ); } private static void Handle_SingleAssignmentOperator( PhaseExecution.NotificationContext nc ) { // Syntax: FirstResult = FirstArgument var op = (SingleAssignmentOperator)nc.CurrentOperator; var lhsRefCountType = GetRefCountType( nc, op.FirstResult ); var rhsRefCountType = GetRefCountType( nc, op.FirstArgument ); if(lhsRefCountType == RefCountType.RefCounted) { // Need to addref the RHS if both LHS and RHS are ref-counted. // Note, we also need to do this if LHS is refcounted and RHS is refcounted but skipped // so we don't mess up the ref count of the LHS. // Also note, this means that we won't addref when we assign ref-counted object to // non-refcounted objects or IntPtr / UIntptr (effectively treating them as weak reference) if( rhsRefCountType == RefCountType.RefCounted || rhsRefCountType == RefCountType.Skipped) { InsertAddRefBefore( nc, op.FirstArgument ); } // If LHS has a ref-counted type, we should always call Release (it'll just be no-op if the // actual object is not) InsertReleaseBefore( nc, op.FirstResult ); // We are assigning a weak pointer (IntPtr / UIntPtr) to a ref-counted type. We need to // assume a reference since it's now assigned to a proper object. if(rhsRefCountType == RefCountType.Pointer) { InsertAddRefAfter( nc, op.FirstResult ); } } } private static void Handle_CallOperator( PhaseExecution.NotificationContext nc ) { // Syntax: FirstResult = TargetMethod() var op = (CallOperator)nc.CurrentOperator; var lhsRefCountType = ( op.Results.Length > 0 ) ? GetRefCountType( nc, op.FirstResult.Type ) : RefCountType.None; if(lhsRefCountType == RefCountType.RefCounted) { InsertReleaseBefore( nc, op.FirstResult ); } } private static void Handle_StoreInstanceFieldOperator( PhaseExecution.NotificationContext nc ) { // Syntax: FirstArgument.Field = SecondArgument Handle_StoreOperators( nc : nc, lhsType : ( (StoreFieldOperator)nc.CurrentOperator ).Field.FieldType, loadLhsAddr: ( op, tempVar ) => LoadInstanceFieldAddressOperator.New( op.DebugInfo, ( (FieldOperator)op ).Field, tempVar, op.FirstArgument, fNullCheck: false ), rhs : nc.CurrentOperator.SecondArgument ); } private static void Handle_LoadInstanceFieldOperator( PhaseExecution.NotificationContext nc ) { // Syntax: FirstResult = FirstArgument.Field Handle_LoadOperators( nc : nc, lhs : nc.CurrentOperator.FirstResult, rhsType : ( (LoadFieldOperator)nc.CurrentOperator ).Field.FieldType, loadRhsAddr: ( op, tempVar ) => LoadInstanceFieldAddressOperator.New( op.DebugInfo, ( (FieldOperator)op ).Field, tempVar, op.FirstArgument, fNullCheck: false ) ); } private static void Handle_StoreElementOperator( PhaseExecution.NotificationContext nc ) { // Syntax: FirstArgument[SecondArgument] = ThirdArgument Handle_StoreOperators( nc : nc, lhsType : nc.CurrentOperator.FirstArgument.Type.ContainedType, loadLhsAddr: ( op, tempVar ) => LoadElementAddressOperator.New( op.DebugInfo, tempVar, op.FirstArgument, op.SecondArgument, ( (ElementOperator)op ).AccessPath, fNullCheck: false ), rhs : nc.CurrentOperator.ThirdArgument ); } private static void Handle_LoadElementOperator( PhaseExecution.NotificationContext nc ) { // Syntax: FirstResult = FirstArgument[SecondArgument] Handle_LoadOperators( nc : nc, lhs : nc.CurrentOperator.FirstResult, rhsType : nc.CurrentOperator.FirstArgument.Type.ContainedType, loadRhsAddr: ( op, tempVar ) => LoadElementAddressOperator.New( op.DebugInfo, tempVar, op.FirstArgument, op.SecondArgument, ( (ElementOperator)op ).AccessPath, fNullCheck: false ) ); } private static void Handle_StoreIndirectOperator( PhaseExecution.NotificationContext nc ) { // Syntax: FirstArgument[Offset] = SecondArgument Handle_StoreOperators( nc : nc, lhsType : nc.CurrentOperator.FirstArgument.Type.ContainedType, loadLhsAddr: delegate( Operator op, TemporaryVariableExpression tempVar ) { CHECKS.ASSERT( ( (IndirectOperator)op ).Offset == 0, "No support for non-zero offset" ); return SingleAssignmentOperator.New( op.DebugInfo, tempVar, op.FirstArgument ); }, rhs : nc.CurrentOperator.SecondArgument ); } private static void Handle_LoadIndirectOperator( PhaseExecution.NotificationContext nc ) { // Syntax: FirstResult = FirstArgument[Offset] Handle_LoadOperators( nc : nc, lhs : nc.CurrentOperator.FirstResult, rhsType : nc.CurrentOperator.FirstArgument.Type.ContainedType, loadRhsAddr: delegate ( Operator op, TemporaryVariableExpression tempVar ) { CHECKS.ASSERT( ( (IndirectOperator)op ).Offset == 0, "No support for non-zero offset" ); return SingleAssignmentOperator.New( op.DebugInfo, tempVar, op.FirstArgument ); } ); } private static void Handle_StoreOperators( PhaseExecution.NotificationContext nc, TypeRepresentation lhsType, Func loadLhsAddr, Expression rhs ) { var op = nc.CurrentOperator; var lhsRefCountType = GetRefCountType( nc, lhsType ); if(lhsRefCountType == RefCountType.RefCounted) { var tempAddr = nc.CurrentCFG.AllocateTemporary( nc.TypeSystem.GetManagedPointerToType( nc.TypeSystem.WellKnownTypes.System_Object ), null ); Operator loadAddrOp = loadLhsAddr( op, tempAddr ); op.AddOperatorBefore( loadAddrOp ); var swap = nc.TypeSystem.WellKnownMethods.ReferenceCountingCollector_Swap; var swapRHS = nc.TypeSystem.AddTypePointerToArgumentsOfStaticMethod( swap, tempAddr, rhs ); var swapCall = StaticCallOperator.New( op.DebugInfo, CallOperator.CallKind.Direct, swap, VariableExpression.SharedEmptyArray, swapRHS ); op.SubstituteWithOperator( swapCall, Operator.SubstitutionFlags.Default ); var phase = (ReferenceCountingGarbageCollection)nc.Phase; phase.AddToModifiedOperator( swapCall ); phase.IncrementInjectionCount( swap ); } } private static void Handle_LoadOperators( PhaseExecution.NotificationContext nc, VariableExpression lhs, TypeRepresentation rhsType, Func loadRhsAddr ) { var op = nc.CurrentOperator; var lhsRefCountType = GetRefCountType( nc, lhs ); var rhsRefCountType = GetRefCountType( nc, rhsType ); // Note that we are calling Release() first then AddRef() here. This is OK because the field // will always hold a valid reference, so the first Release() can never cause the ref count to // bounce zero. // If LHS has a ref-counted type, we should always call Release (it'll just be no-op if the // actual object is not) if(lhsRefCountType == RefCountType.RefCounted) { InsertReleaseBefore( nc, lhs ); // Need to Addref the RHS if it's a ref-counted type. if(rhsRefCountType == RefCountType.RefCounted) { // Create a temporary variable to store the address of the field object var tempAddr = nc.CurrentCFG.AllocateTemporary( nc.TypeSystem.GetManagedPointerToType( nc.TypeSystem.WellKnownTypes.System_Object ), null ); var loadAddrOp = loadRhsAddr(op, tempAddr); op.AddOperatorBefore( loadAddrOp ); var loadAndAddRef = nc.TypeSystem.WellKnownMethods.ReferenceCountingCollector_LoadAndAddReference; var loadAndAddRefRHS = nc.TypeSystem.AddTypePointerToArgumentsOfStaticMethod( loadAndAddRef, tempAddr ); var loadAndAddRefCall = StaticCallOperator.New( op.DebugInfo, CallOperator.CallKind.Direct, loadAndAddRef, new VariableExpression[] { lhs }, loadAndAddRefRHS ); op.SubstituteWithOperator( loadAndAddRefCall, Operator.SubstitutionFlags.Default ); var phase = (ReferenceCountingGarbageCollection)nc.Phase; phase.AddToModifiedOperator( loadAndAddRefCall ); phase.IncrementInjectionCount( loadAndAddRef ); } } } [CompilationSteps.PhaseFilter( typeof( Phases.ReferenceCountingGarbageCollection ) )] [CompilationSteps.OperatorHandler( typeof( StaticCallOperator ) )] private static void Handle_RedundantRefCountingCalls( PhaseExecution.NotificationContext nc ) { var op = (StaticCallOperator)nc.CurrentOperator; var ts = nc.TypeSystem; var wkm = ts.WellKnownMethods; var md = op.TargetMethod; // Remove redundant AddReference(null) and ReleaseReference(null) if(md == wkm.ObjectHeader_AddReference || md == wkm.ObjectHeader_ReleaseReference) { var arg = op.SecondArgument as ConstantExpression; if(arg != null && arg.Value == null) { op.Delete( ); ( (ReferenceCountingGarbageCollection)nc.Phase ).DecrementInjectionCount( md ); nc.MarkAsModified( ); } } } [CompilationSteps.PhaseFilter( typeof( Phases.ReferenceCountingGarbageCollection ) )] [CompilationSteps.OperatorHandler( typeof( StaticCallOperator ) )] private static void Handle_ReplaceFastAllocateString( PhaseExecution.NotificationContext nc ) { var op = (StaticCallOperator)nc.CurrentOperator; var ts = nc.TypeSystem; var wkm = ts.WellKnownMethods; var allocString = wkm.StringImpl_FastAllocateString; if(allocString != null && op.TargetMethod == allocString) { var allocStrCall = StaticCallOperator.New( op.DebugInfo, CallOperator.CallKind.Direct, wkm.StringImpl_FastAllocateReferenceCountingString, op.Results, op.Arguments ); op.SubstituteWithOperator( allocStrCall, Operator.SubstitutionFlags.Default ); var phase = (ReferenceCountingGarbageCollection)nc.Phase; if(phase.IsOperatorModified( op )) { phase.AddToModifiedOperator( allocStrCall ); } nc.MarkAsModified( ); } } [CompilationSteps.PhaseFilter( typeof( Phases.ReferenceCountingGarbageCollection ) )] [CompilationSteps.OperatorHandler( typeof( StaticCallOperator ) )] private static void Handle_ReplaceInternalInterlockedMethods( PhaseExecution.NotificationContext nc ) { // Various Interlocked methods like Exchange and CompareExchange are being replaced by // LLVM atomic instruction, and as such, they do not properly account for reference counting // This handler will wrap the calls with the proper reference counting methods (as implemented // in InterlockedImpl.ReferenceCounting* methods) var op = (StaticCallOperator)nc.CurrentOperator; var ts = nc.TypeSystem; var wkm = ts.WellKnownMethods; var internalExchange = wkm.InterlockedImpl_InternalExchange_Template; var internalCompareExchange = wkm.InterlockedImpl_InternalCompareExchange_Template; var refCountExchange = wkm.ReferenceCountingCollector_ReferenceCountingExchange; var refCountCompareExchange = wkm.ReferenceCountingCollector_ReferenceCountingCompareExchange; var md = op.TargetMethod; var owner = op.BasicBlock.Owner.Method; // Do not replace the call in ReferenceCountingExchange or ReferenceCountingCompareExchange if(owner == refCountExchange || owner == refCountCompareExchange) { return; } if(md.IsGenericInstantiation && (md.GenericTemplate == internalExchange || md.GenericTemplate == internalCompareExchange)) { var isCompareExchange = md.GenericTemplate == internalCompareExchange; // Generate the unsafe cast from T& to object& var tempPtr = nc.CurrentCFG.AllocateTemporary( nc.TypeSystem.GetManagedPointerToType( nc.TypeSystem.WellKnownTypes.System_Object ), null ); var unsafeCastOp = SingleAssignmentOperator.New( op.DebugInfo, tempPtr, op.SecondArgument ); op.AddOperatorBefore( unsafeCastOp ); // Replace the T& with the new temporary Expression[] args = (Expression[])op.Arguments.Clone( ); args[ 1 ] = tempPtr; var call = StaticCallOperator.New( op.DebugInfo, CallOperator.CallKind.Direct, isCompareExchange ? refCountCompareExchange : refCountExchange, op.Results, args ); op.SubstituteWithOperator( call, Operator.SubstitutionFlags.Default ); var phase = (ReferenceCountingGarbageCollection)nc.Phase; if(phase.IsOperatorModified( op )) { phase.AddToModifiedOperator( call ); } nc.MarkAsModified( ); } } } } ================================================ FILE: Zelig/Zelig/CompileTime/CodeGenerator/CodeTransformation/CompilationSteps/Handlers/Optimizations.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // //#define DUMP_CONSTRAINTSYSTEM // LLVM translation doesn't yet recognize SSA format, and will not produce correct code. // TODO: Remove this tag when that issue has been resolved. //#define ALLOW_SSA_FORM // Enable optimizations that only work for direct ARM translation (non-LLVM legacy path). // TODO: Remove this tag when comparison is no longer needed. //#define ENABLE_LOW_LEVEL_OPTIMIZATIONS // Enable more advanced optimizations which look for non-equivalent comparisons. This appears to be // overly aggressive when not in SSA form, resulting in incorrect code. // TODO: Remove this tag when this issue is resolved. //#define ENABLE_ADVANCED_COMPARES namespace Microsoft.Zelig.CodeGeneration.IR.CompilationSteps.Handlers { using System; using System.Collections.Generic; using Microsoft.Zelig.Runtime.TypeSystem; public class Optimizations { //--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--// //--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--// //--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--// #if ALLOW_SSA_FORM [CompilationSteps.OptimizationHandler(RunOnce = true, RunInExtendedSSAForm = true)] #else // ALLOW_SSA_FORM [CompilationSteps.OptimizationHandler(RunOnce = true)] #endif // ALLOW_SSA_FORM private static void RemoveRedundantChecks( PhaseExecution.NotificationContext nc ) { ControlFlowGraphStateForCodeTransformation cfg = nc.CurrentCFG; while(true) { GrowOnlyHashTable< VariableExpression, Operator > defLookup = cfg.DataFlow_SingleDefinitionLookup; if(PropagateFixedArrayLength( cfg, defLookup ) || RemoveRedundantChecks( cfg, defLookup ) ) { Transformations.RemoveDeadCode.Execute( cfg, false ); continue; } break; } } //--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--// private static bool PropagateFixedArrayLength( ControlFlowGraphStateForCodeTransformation cfg , GrowOnlyHashTable< VariableExpression, Operator > defLookup ) { bool fRunSimplify = false; #if ENABLE_LOW_LEVEL_OPTIMIZATIONS foreach(var op in cfg.FilterOperators< LoadIndirectOperator >()) #else // ENABLE_LOW_LEVEL_OPTIMIZATIONS foreach(var op in cfg.FilterOperators< LoadInstanceFieldOperator >()) #endif // ENABLE_LOW_LEVEL_OPTIMIZATIONS { if(op.HasAnnotation< ArrayLengthAnnotation >()) { FixedLengthArrayAnnotation an = FindFixedLengthArrayAnnotation( defLookup, op.FirstArgument ); if(an != null) { var var = op.FirstResult; var opNew = SingleAssignmentOperator.New( op.DebugInfo, var, cfg.TypeSystem.CreateConstant( (uint)an.ArrayLength ) ); op.SubstituteWithOperator( opNew, Operator.SubstitutionFlags.Default ); defLookup[var] = op; fRunSimplify = true; } } } return fRunSimplify; } private static FixedLengthArrayAnnotation FindFixedLengthArrayAnnotation( GrowOnlyHashTable< VariableExpression, Operator > defLookup , Expression ex ) { return FindFixedLengthArrayAnnotation( defLookup, SetFactory.NewWithReferenceEquality< VariableExpression >(), ex ); } private static FixedLengthArrayAnnotation FindFixedLengthArrayAnnotation( GrowOnlyHashTable< VariableExpression, Operator > defLookup , GrowOnlySet< VariableExpression > history , Expression ex ) { var array = ex as VariableExpression; if(array == null || history.Insert( array )) { // // Detected loop, bail out. // return null; } //--// Operator arrayDef; if(defLookup.TryGetValue( array, out arrayDef )) { var an = arrayDef.GetAnnotation< FixedLengthArrayAnnotation >(); if(an != null) { return an; } if(arrayDef is PhiOperator) { foreach(Expression rhs in arrayDef.Arguments) { FixedLengthArrayAnnotation an2 = FindFixedLengthArrayAnnotation( defLookup, history, rhs ); if(an2 == null) { return null; } if(an == null) { an = an2; } else if(an.ArrayLength != an2.ArrayLength) { return null; } } return an; } if(arrayDef is SingleAssignmentOperator || arrayDef is PiOperator ) { return FindFixedLengthArrayAnnotation( defLookup, history, arrayDef.FirstArgument ); } } return null; } //--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--// private static bool RemoveRedundantChecks( ControlFlowGraphStateForCodeTransformation cfg, GrowOnlyHashTable< VariableExpression, Operator > defLookup ) { var useChains = cfg.DataFlow_UseChains; bool fRunSimplify = false; cfg.ResetCacheCheckpoint( ); foreach(var controlOp in cfg.FilterOperators< BinaryConditionalControlOperator >()) { BasicBlock takenBranch = TryGetUnconditionalBranchTarget( controlOp, defLookup, useChains ); if(takenBranch != null) { UnconditionalControlOperator opNewCtrl = UnconditionalControlOperator.New( controlOp.DebugInfo, takenBranch ); controlOp.SubstituteWithOperator( opNewCtrl, Operator.SubstitutionFlags.Default ); fRunSimplify = true; } } // If modified, we need to refresh useChains in case variables were changed. If we don't do this, FilterOperators // below will refresh the operators, and SpanningTreeIndex and other info between variables and our stale useChains // may be mismatched. if(fRunSimplify) { cfg.AssertNoCacheRefreshSinceCheckpoint( ); useChains = cfg.DataFlow_UseChains; cfg.ResetCacheCheckpoint( ); } var cscUpperBound = new Transformations.ConstraintSystemCollector( cfg, Transformations.ConstraintSystemCollector.Kind.LessThanOrEqual ); var cscLowerBound = new Transformations.ConstraintSystemCollector( cfg, Transformations.ConstraintSystemCollector.Kind.GreaterThanOrEqual ); foreach(var controlOp in cfg.FilterOperators< CompareConditionalControlOperator >()) { BasicBlock takenBranch = TryGetUnconditionalBranchTarget( cscUpperBound, cscLowerBound, controlOp, defLookup, useChains ); if(takenBranch != null) { UnconditionalControlOperator opNewCtrl = UnconditionalControlOperator.New( controlOp.DebugInfo, takenBranch ); controlOp.SubstituteWithOperator( opNewCtrl, Operator.SubstitutionFlags.Default ); fRunSimplify = true; } } #if ENABLE_LOW_LEVEL_OPTIMIZATIONS foreach(var controlOp in cfg.FilterOperators< ConditionCodeConditionalControlOperator >()) { bool fNotEqual; switch(controlOp.Condition) { case ConditionCodeExpression.Comparison.NotEqual: fNotEqual = true; break; case ConditionCodeExpression.Comparison.Equal: fNotEqual = false; break; default: continue; } var opCmp = ControlFlowGraphState.CheckSingleDefinition( defLookup, controlOp.FirstArgument ) as CompareOperator; if(opCmp != null) { bool fNullOnRight; Expression ex = opCmp.IsBinaryOperationAgainstZeroValue( out fNullOnRight ); if(ex != null) { if(ProveNonZero( defLookup, ex ) == ProveResult.True) { UnconditionalControlOperator opNewCtrl = UnconditionalControlOperator.New( controlOp.DebugInfo, fNotEqual ? controlOp.TargetBranchTaken : controlOp.TargetBranchNotTaken ); controlOp.SubstituteWithOperator( opNewCtrl, Operator.SubstitutionFlags.Default ); fRunSimplify = true; } } } } foreach (var controlOp in cfg.FilterOperators< ConditionCodeConditionalControlOperator >()) { var opCmp = ControlFlowGraphState.CheckSingleDefinition( defLookup, controlOp.FirstArgument ) as CompareOperator; if(opCmp != null) { ProveResult result = ProveComparison( cscUpperBound, cscLowerBound, opCmp.FirstArgument, opCmp.SecondArgument, controlOp.Condition ); if(result != ProveResult.Unknown) { BasicBlock takenBranch = (result == ProveResult.AlwaysTrue) ? controlOp.TargetBranchTaken : controlOp.TargetBranchNotTaken; UnconditionalControlOperator opNewCtrl = UnconditionalControlOperator.New( controlOp.DebugInfo, takenBranch ); controlOp.SubstituteWithOperator( opNewCtrl, Operator.SubstitutionFlags.Default ); fRunSimplify = true; } } } #endif // ENABLE_LOW_LEVEL_OPTIMIZATIONS cfg.AssertNoCacheRefreshSinceCheckpoint( ); return fRunSimplify; } bool SomeProperty { get; set; } private static BasicBlock TryGetUnconditionalBranchTarget( BinaryConditionalControlOperator controlOp, GrowOnlyHashTable defLookup, Operator[][] useChains) { // Replace binary branches with unconditional ones when both targets are the same block. if (controlOp.TargetBranchTaken == controlOp.TargetBranchNotTaken) { return controlOp.TargetBranchTaken; } switch (ProveNonZero(controlOp.FirstArgument, defLookup, useChains)) { case ProveResult.AlwaysTrue: return controlOp.TargetBranchTaken; case ProveResult.NeverTrue: return controlOp.TargetBranchNotTaken; } return null; } private static BasicBlock TryGetUnconditionalBranchTarget( Transformations.ConstraintSystemCollector cscUpperBound, Transformations.ConstraintSystemCollector cscLowerBound, CompareConditionalControlOperator controlOp, GrowOnlyHashTable defLookup, Operator[][] useChains) { // Replace binary branches with unconditional ones when both targets are the same block. if (controlOp.TargetBranchTaken == controlOp.TargetBranchNotTaken) { return controlOp.TargetBranchTaken; } ProveResult result = ProveResult.Unknown; switch (controlOp.Condition) { case CompareAndSetOperator.ActionCondition.EQ: case CompareAndSetOperator.ActionCondition.NE: bool fNullOnRight; Expression expr = controlOp.IsBinaryOperationAgainstZeroValue(out fNullOnRight); if (expr == null) { break; } result = ProveNonZero(expr, defLookup, useChains); if (result == ProveResult.Unknown) { break; } // Invert the result for (expr == 0) if (controlOp.Condition == CompareAndSetOperator.ActionCondition.EQ) { if (result == ProveResult.AlwaysTrue) { result = ProveResult.NeverTrue; } else { result = ProveResult.AlwaysTrue; } } break; #if ENABLE_ADVANCED_COMPARES case CompareAndSetOperator.ActionCondition.LT: result = ProveLessThanOrEqual(cscUpperBound, cscLowerBound, controlOp.FirstArgument, controlOp.SecondArgument, weight: -1); break; case CompareAndSetOperator.ActionCondition.LE: result = ProveLessThanOrEqual(cscUpperBound, cscLowerBound, controlOp.FirstArgument, controlOp.SecondArgument, weight: 0); break; case CompareAndSetOperator.ActionCondition.GT: result = ProveLessThanOrEqual(cscUpperBound, cscLowerBound, controlOp.SecondArgument, controlOp.FirstArgument, weight: -1); break; case CompareAndSetOperator.ActionCondition.GE: result = ProveLessThanOrEqual(cscUpperBound, cscLowerBound, controlOp.SecondArgument, controlOp.FirstArgument, weight: 0); break; #endif // ENABLE_ADVANCED_COMPARES } switch (result) { case ProveResult.AlwaysTrue: return controlOp.TargetBranchTaken; case ProveResult.NeverTrue: return controlOp.TargetBranchNotTaken; default: return null; } } private enum ProveResult { Unknown = 0, AlwaysTrue, NeverTrue, } private static ProveResult ProveNonZero( Expression ex, GrowOnlyHashTable< VariableExpression, Operator > defLookup, Operator[][] useChains ) { return ProveNonZero( ex, defLookup, useChains, SetFactory.NewWithReferenceEquality< VariableExpression >() ); } private static ProveResult ProveNonZero( Expression ex, GrowOnlyHashTable< VariableExpression, Operator > defLookup, Operator[][] useChains, GrowOnlySet< VariableExpression > history ) { var exConst = ex as ConstantExpression; if (exConst != null) { if(exConst.IsEqualToZero()) { return ProveResult.NeverTrue; } return ProveResult.AlwaysTrue; } var exVar = ex as VariableExpression; // If we detected a loop, the value may change between iterations. if(exVar == null || history.Insert( exVar )) { return ProveResult.Unknown; } //--// Operator def; if(defLookup.TryGetValue( exVar, out def )) { // If we ever take the address of the expression, assume it can be modified. foreach (Operator op in useChains[exVar.SpanningTreeIndex]) { if (op is AddressAssignmentOperator) { return ProveResult.Unknown; } } if (def.HasAnnotation< NotNullAnnotation >()) { return ProveResult.AlwaysTrue; } // Phi: If all predecessors are provably the same result, then so is the operator's result. if(def is PhiOperator) { bool isFirstResult = true; ProveResult result = ProveResult.Unknown; foreach(Expression rhs in def.Arguments) { ProveResult curResult = ProveNonZero( rhs, defLookup, useChains, history ); if(isFirstResult) { isFirstResult = false; result = curResult; } else if(curResult != result) { // We got two different results from different blocks. return ProveResult.Unknown; } } return result; } // Assignment is transitive, so look up the source value. if(def is SingleAssignmentOperator) { return ProveNonZero( def.FirstArgument, defLookup, useChains, history ); } #if FUTURE // This block isn't strictly correct and assumes low-level knowledge. We should revisit it. if(def is BinaryOperator) { var binOp = (BinaryOperator)def; ConstantExpression exConst; bool fConstOnRight; var varSrc = binOp.IsBinaryOperationAgainstConstant( out exConst, out fConstOnRight ); if(varSrc != null) { // // Only apply the optimization to pointer-like variables. // if(varSrc.CanPointToMemory || exVar.CanPointToMemory) { switch(binOp.Alu) { case BinaryOperator.ALU.ADD: case BinaryOperator.ALU.SUB: // // Adding/removing a constant from a non-null value doesn't change its nullness. // return ProveNonZero( defLookup, history, varSrc ); case BinaryOperator.ALU.OR: // // OR'ing with a non-zero constant ensures the results are not null. // if(!exConst.IsEqualToZero()) { return ProveResult.AlwaysTrue; } break; } } } return ProveResult.Unknown; } #endif // FUTURE if(def is PiOperator) { var piOp = (PiOperator)def; ex = def.FirstArgument; if((piOp.LeftExpression == ex && piOp.RightExpression.IsEqualToZero()) || (piOp.RightExpression == ex && piOp.LeftExpression .IsEqualToZero()) ) { switch(piOp.RelationOperator) { case PiOperator.Relation.Equal: return ProveResult.NeverTrue; case PiOperator.Relation.NotEqual: return ProveResult.AlwaysTrue; } } return ProveNonZero( ex, defLookup, useChains, history ); } } return ProveResult.Unknown; } #if ENABLE_LOW_LEVEL_OPTIMIZATIONS private static ProveResult ProveComparison( Transformations.ConstraintSystemCollector cscUpperBound, Transformations.ConstraintSystemCollector cscLowerBound, Expression exLeft, Expression exRight, ConditionCodeExpression.Comparison condition) { switch(condition) { case ConditionCodeExpression.Comparison.UnsignedLowerThan: case ConditionCodeExpression.Comparison.SignedLessThan: return ProveLessThanOrEqual( cscUpperBound, cscLowerBound, exLeft, exRight, -1 ); case ConditionCodeExpression.Comparison.UnsignedLowerThanOrSame: case ConditionCodeExpression.Comparison.SignedLessThanOrEqual: return ProveLessThanOrEqual( cscUpperBound, cscLowerBound, exLeft, exRight, 0 ); case ConditionCodeExpression.Comparison.UnsignedHigherThan: case ConditionCodeExpression.Comparison.SignedGreaterThan: return ProveLessThanOrEqual( cscUpperBound, cscLowerBound, exRight, exLeft, -1 ); case ConditionCodeExpression.Comparison.UnsignedHigherThanOrSame: case ConditionCodeExpression.Comparison.SignedGreaterThanOrEqual: return ProveLessThanOrEqual( cscUpperBound, cscLowerBound, exRight, exLeft, 0 ); } return ProveResult.Unknown; } #endif // ENABLE_LOW_LEVEL_OPTIMIZATIONS private static ProveResult ProveLessThanOrEqual( Transformations.ConstraintSystemCollector cscUpperBound, Transformations.ConstraintSystemCollector cscLowerBound, Expression exLeft, Expression exRight, double weight) { if(exLeft is VariableExpression) { if(cscUpperBound.Prove( exLeft, exRight, weight )) { return ProveResult.AlwaysTrue; } } if(exRight is VariableExpression) { if(cscLowerBound.Prove( exRight, exLeft, -weight )) { return ProveResult.AlwaysTrue; } } return ProveResult.Unknown; } //--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--// //--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--// //--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--// #if ENABLE_LOW_LEVEL_OPTIMIZATIONS [CompilationSteps.OptimizationHandler(RunOnce=true, RunInSSAForm=true)] private static void ConvertLongCompareToNormalCompare( PhaseExecution.NotificationContext nc ) { ControlFlowGraphStateForCodeTransformation cfg = nc.CurrentCFG; Operator[][] useChains = cfg.DataFlow_UseChains; foreach(var opLong in cfg.FilterOperators< LongCompareOperator >()) { Debugging.DebugInfo debugInfo = opLong.DebugInfo; VariableExpression lhs = opLong.FirstResult; Expression[] rhs = opLong.Arguments; Operator[] uses = useChains[lhs.SpanningTreeIndex]; bool fOk = false; switch(uses.Length) { case 0: fOk = true; break; case 1: { bool fNullOnRight; Operator use = uses[0]; Expression[] target = opLong.IsCompareToNull( out fNullOnRight ); ConditionCodeExpression.Comparison cond = ConditionCodeExpression.Comparison.NotValid; if(use is ConditionalCompareOperator) { var ccOp = (ConditionalCompareOperator)use; cond = ccOp.Condition; } else if(use is ConditionCodeConditionalControlOperator) { var ccOp = (ConditionCodeConditionalControlOperator)use; cond = ccOp.Condition; } else if(use is SetIfConditionIsTrueOperator) { var setOp = (SetIfConditionIsTrueOperator)use; cond = setOp.Condition; } if(cond != ConditionCodeExpression.Comparison.NotValid) { ConditionCodeExpression.Comparison condOrig = cond; Expression rhsLeftLo = rhs[0]; Expression rhsLeftHi = rhs[1]; Expression rhsRightLo = rhs[2]; Expression rhsRightHi = rhs[3]; if(target != null) { if(!fNullOnRight) { rhsLeftLo = rhs[2]; rhsLeftHi = rhs[3]; rhsRightLo = rhs[0]; rhsRightHi = rhs[1]; cond = ConditionCodeExpression.NegateCondition( cond ); } // // We are comparing against zero. // // Can we use a single instruction to perform the comparison? // // For Zero/NonZero, we just OR together the two halves, and set the condition code. // // For Negative/PositiveOrZero, we just need to look at the high part. // // For unsigned: // >= is always true. // < is always false. // <= is like Equal. // > is like NotEqual. // // // For signed: // >= is like PositiveOrZero. // < is like Negative. // <= requires full comparison. // > requires full comparison. // switch(cond) { case ConditionCodeExpression.Comparison.Equal : case ConditionCodeExpression.Comparison.NotEqual: { VariableExpression tmp = cfg.AllocatePseudoRegister( rhsLeftLo.Type ); var op2 = BinaryOperatorWithCarryOut.New( debugInfo, BinaryOperator.ALU.OR, false, false, tmp, lhs, rhsLeftLo, rhsLeftHi ); opLong.SubstituteWithOperator( op2, Operator.SubstitutionFlags.Default ); } fOk = true; break; case ConditionCodeExpression.Comparison.Negative : case ConditionCodeExpression.Comparison.PositiveOrZero : { CompareOperator op2 = CompareOperator.New( debugInfo, lhs, rhsLeftHi, nc.TypeSystem.CreateConstant( rhsLeftHi.Type, 0 ) ); opLong.AddOperatorBefore( op2 ); opLong.Delete(); } fOk = true; break; //--// case ConditionCodeExpression.Comparison.UnsignedLowerThanOrSame: cond = ConditionCodeExpression.Comparison.Equal; goto case ConditionCodeExpression.Comparison.Equal; case ConditionCodeExpression.Comparison.UnsignedHigherThan: cond = ConditionCodeExpression.Comparison.NotEqual; goto case ConditionCodeExpression.Comparison.NotEqual; case ConditionCodeExpression.Comparison.UnsignedHigherThanOrSame: // Always true. goto case ConditionCodeExpression.Comparison.PositiveOrZero; case ConditionCodeExpression.Comparison.UnsignedLowerThan: // Always false. goto case ConditionCodeExpression.Comparison.PositiveOrZero; //--// case ConditionCodeExpression.Comparison.SignedGreaterThanOrEqual: cond = ConditionCodeExpression.Comparison.PositiveOrZero; goto case ConditionCodeExpression.Comparison.PositiveOrZero; case ConditionCodeExpression.Comparison.SignedLessThan: cond = ConditionCodeExpression.Comparison.Negative; goto case ConditionCodeExpression.Comparison.Negative; case ConditionCodeExpression.Comparison.SignedGreaterThan: case ConditionCodeExpression.Comparison.SignedLessThanOrEqual: // // We have to use the full 64bit comparison. // break; } } if(fOk == false) { // // We are comparing two variables. // // For Zero/NonZero and all the unsigned comparisons, // first compare the high parts and then compare the low ones, if the high parts are equal. // // For signed: // >= do a subtraction and set the result if SignedGreaterThanOrEqual. // < do a subtraction and set the result if SignedLessThan. // <= is like >= with the arguments swapped. // > is like < with the arguments swapped. // switch(cond) { case ConditionCodeExpression.Comparison.Equal : case ConditionCodeExpression.Comparison.NotEqual : case ConditionCodeExpression.Comparison.UnsignedHigherThanOrSame: case ConditionCodeExpression.Comparison.UnsignedLowerThan : case ConditionCodeExpression.Comparison.UnsignedHigherThan : case ConditionCodeExpression.Comparison.UnsignedLowerThanOrSame : { CompareOperator opHigh = CompareOperator.New( debugInfo, lhs, rhsLeftHi, rhsRightHi ); opLong.AddOperatorBefore( opHigh ); ConditionalCompareOperator opLow = ConditionalCompareOperator.New( debugInfo, ConditionCodeExpression.Comparison.Equal, lhs, rhsLeftLo, rhsRightLo, lhs ); opLong.AddOperatorBefore( opLow ); opLong.Delete(); } fOk = true; break; case ConditionCodeExpression.Comparison.SignedGreaterThanOrEqual: { VariableExpression tmpLo = cfg.AllocatePseudoRegister( rhsLeftLo.Type ); VariableExpression tmpHi = cfg.AllocatePseudoRegister( rhsLeftHi.Type ); var opLow = BinaryOperatorWithCarryOut.New( debugInfo, BinaryOperator.ALU.SUB, true, false, tmpLo, lhs, rhsLeftLo, rhsRightLo ); opLong.AddOperatorBefore( opLow ); var opHigh = BinaryOperatorWithCarryInAndOut.New( debugInfo, BinaryOperator.ALU.SUB, true, false, tmpHi, lhs, rhsLeftHi, rhsRightHi, lhs ); opLong.AddOperatorBefore( opHigh ); opLong.Delete(); cond = ConditionCodeExpression.Comparison.SignedGreaterThanOrEqual; } fOk = true; break; case ConditionCodeExpression.Comparison.SignedLessThan: { VariableExpression tmpLo = cfg.AllocatePseudoRegister( rhsLeftLo.Type ); VariableExpression tmpHi = cfg.AllocatePseudoRegister( rhsLeftHi.Type ); var opLow = BinaryOperatorWithCarryOut.New( debugInfo, BinaryOperator.ALU.SUB, true, false, tmpLo, lhs, rhsLeftLo, rhsRightLo ); opLong.AddOperatorBefore( opLow ); var opHigh = BinaryOperatorWithCarryInAndOut.New( debugInfo, BinaryOperator.ALU.SUB, true, false, tmpHi, lhs, rhsLeftHi, rhsRightHi, lhs ); opLong.AddOperatorBefore( opHigh ); opLong.Delete(); cond = ConditionCodeExpression.Comparison.SignedLessThan; } fOk = true; break; case ConditionCodeExpression.Comparison.SignedGreaterThan: { Expression tmpLo; Expression tmpHi; tmpLo = rhsLeftLo ; tmpHi = rhsLeftHi ; rhsLeftLo = rhsRightLo; rhsLeftHi = rhsRightHi; rhsRightLo = tmpLo ; rhsRightHi = tmpHi ; goto case ConditionCodeExpression.Comparison.SignedLessThan; } case ConditionCodeExpression.Comparison.SignedLessThanOrEqual: { Expression tmpLo; Expression tmpHi; tmpLo = rhsLeftLo ; tmpHi = rhsLeftHi ; rhsLeftLo = rhsRightLo; rhsLeftHi = rhsRightHi; rhsRightLo = tmpLo ; rhsRightHi = tmpHi ; goto case ConditionCodeExpression.Comparison.SignedGreaterThanOrEqual; } } } if(condOrig != cond) { if(use is ConditionalCompareOperator) { var ccOp = (ConditionalCompareOperator)use; ccOp.Condition = cond; } else if(use is ConditionCodeConditionalControlOperator) { var ccOp = (ConditionCodeConditionalControlOperator)use; ccOp.Condition = cond; } else if(use is SetIfConditionIsTrueOperator) { var setOp = (SetIfConditionIsTrueOperator)use; setOp.Condition = cond; } } } } break; default: throw TypeConsistencyErrorException.Create( "Unexpected form of '{0}' with multiple uses for the condition code", opLong ); } if(fOk == false) { throw TypeConsistencyErrorException.Create( "Unexpected form of '{0}'", opLong ); } } } #endif // ENABLE_LOW_LEVEL_OPTIMIZATIONS #if ALLOW_SSA_FORM [CompilationSteps.OptimizationHandler(RunOnce = true, RunInSSAForm = true)] #else // ALLOW_SSA_FORM [CompilationSteps.OptimizationHandler(RunOnce = true)] #endif // ALLOW_SSA_FORM private static void ReduceComparisons(PhaseExecution.NotificationContext nc) { ControlFlowGraphStateForCodeTransformation cfg = nc.CurrentCFG; Operator[][] defChains = cfg.DataFlow_DefinitionChains; Operator[][] useChains = cfg.DataFlow_UseChains; // Replace split compare + branch operators with CompareConditionalControlOperator. foreach (var branchOp in cfg.FilterOperators()) { var comparand = branchOp.FirstArgument as VariableExpression; if (comparand == null) { continue; } var compareOp = ControlFlowGraphState.CheckSingleDefinition(defChains, comparand) as CompareAndSetOperator; if (compareOp == null) { continue; } var conditionalOp = CompareConditionalControlOperator.New( branchOp.DebugInfo, compareOp.Condition, compareOp.Signed, compareOp.FirstArgument, compareOp.SecondArgument, branchOp.TargetBranchNotTaken, branchOp.TargetBranchTaken); branchOp.SubstituteWithOperator(conditionalOp, Operator.SubstitutionFlags.Default); nc.MarkAsModified(); } } //--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--// //--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--// //--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--// #if ALLOW_SSA_FORM [CompilationSteps.OptimizationHandler(RunOnce = true, RunInSSAForm = true)] #else // ALLOW_SSA_FORM [CompilationSteps.OptimizationHandler(RunOnce = true)] #endif // ALLOW_SSA_FORM private static void RemoveRedundantConversions( PhaseExecution.NotificationContext nc ) { ControlFlowGraphStateForCodeTransformation cfg = nc.CurrentCFG; Operator[][] defChains = cfg.DataFlow_DefinitionChains; Operator[][] useChains = cfg.DataFlow_UseChains; cfg.ResetCacheCheckpoint( ); foreach(var opConv in cfg.FilterOperators< ConversionOperator >()) { var lhs = opConv.FirstResult; var rhs = opConv.FirstArgument; if(rhs is VariableExpression) { var def = ControlFlowGraphState.CheckSingleDefinition( defChains, (VariableExpression)rhs ); bool fSubstitute = false; var defLoad = def as LoadIndirectOperator; if(defLoad != null) { TypeRepresentation tdSrc = defLoad.Type; if(tdSrc.SizeOfHoldingVariable == opConv.SignificantSize) { if((opConv is ZeroExtendOperator && tdSrc.IsSigned == false) || (opConv is SignExtendOperator && tdSrc.IsSigned == true ) ) { fSubstitute = true; } } } else if(def is BinaryOperator) { var defBinOp = (BinaryOperator)def; switch(defBinOp.Alu) { case BinaryOperator.ALU.AND: defBinOp.EnsureConstantToTheRight(); var ex = defBinOp.SecondArgument as ConstantExpression; ulong val; if(ex != null && ex.GetAsUnsignedInteger( out val ) && val != 0) { int msb = BitVector.GetPositionOfLastBitSet( val ); uint max = opConv.SignificantSize * 8; // // Masking by a constant smaller than the destination size. // if((opConv is ZeroExtendOperator && (msb < max )) || (opConv is SignExtendOperator && (msb < max - 1)) ) { fSubstitute = true; } } break; } } if(fSubstitute) { foreach(Operator use in useChains[lhs.SpanningTreeIndex]) { use.SubstituteUsage( lhs, rhs ); } } } foreach(Operator use in useChains[lhs.SpanningTreeIndex]) { var useStore = use as StoreIndirectOperator; if(useStore != null) { if(opConv.SignificantSize >= useStore.Type.SizeOfHoldingVariable) { use.SubstituteUsage( lhs, rhs ); } } } } cfg.AssertNoCacheRefreshSinceCheckpoint( ); } #if ENABLE_LOW_LEVEL_OPTIMIZATIONS //--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--// //--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--// //--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--// [CompilationSteps.OptimizationHandler(RunOnce = false, RunInSSAForm = true)] private static void ConstantMemoryDereference( PhaseExecution.NotificationContext nc ) { ControlFlowGraphStateForCodeTransformation cfg = nc.CurrentCFG; TypeSystemForCodeTransformation ts = nc.TypeSystem; foreach(var opLoad in cfg.FilterOperators< LoadIndirectOperator >()) { var debugInfo = opLoad.DebugInfo; var lhs = opLoad.FirstResult; var rhs = opLoad.FirstArgument as ConstantExpression; if(rhs != null) { var dd = rhs.Value as DataManager.DataDescriptor; if(dd != null) { var val2 = dd.GetDataAtOffset( opLoad.AccessPath, 0, opLoad.Offset ); var ddVal = val2 as DataManager.DataDescriptor; if(ddVal != null && ddVal.CanPropagate) { opLoad.SubstituteWithOperator( SingleAssignmentOperator.New( debugInfo, lhs, ts.CreateConstant( lhs.Type, val2 ) ), Operator.SubstitutionFlags.Default ); continue; } } } } } #endif // ENABLE_LOW_LEVEL_OPTIMIZATIONS } } ================================================ FILE: Zelig/Zelig/CompileTime/CodeGenerator/CodeTransformation/CompilationSteps/Handlers/ProtectRequiredEntities.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // namespace Microsoft.Zelig.CodeGeneration.IR.CompilationSteps.Handlers { using System; using System.Collections.Generic; using Microsoft.Zelig.Runtime.TypeSystem; public class ProtectRequiredEntities { [CompilationSteps.CallClosureHandler( typeof(InstanceCallOperator) )] private static void Protect_MethodPointers( ComputeCallsClosure.Context host , Operator target ) { InstanceCallOperator call = (InstanceCallOperator)target; if(call.CallType == CallOperator.CallKind.Virtual) { Keep_VTablesGetter ( host ); Keep_VTables ( host ); Keep_MethodPointers( host ); } if(call.TargetMethod is InstanceMethodRepresentation) { Keep_NullCheck( host ); } if(call.TargetMethod.OwnerType is InterfaceTypeRepresentation) { Keep_InterfaceMap( host ); } } [CompilationSteps.CallClosureHandler( typeof(FieldOperator))] private static void Protect_FieldOperator( ComputeCallsClosure.Context host , Operator target ) { Keep_NullCheck( host ); } [CompilationSteps.CallClosureHandler( typeof(ElementOperator) )] private static void Protect_ElementOperator( ComputeCallsClosure.Context host , Operator target ) { Keep_NullCheck ( host ); Keep_BoundCheck( host ); Keep_ArraySize ( host ); } [CompilationSteps.CallClosureHandler( typeof(BinaryOperator) )] [CompilationSteps.CallClosureHandler( typeof(SignExtendOperator) )] [CompilationSteps.CallClosureHandler( typeof(TruncateOperator) )] [CompilationSteps.CallClosureHandler( typeof(UnaryOperator) )] [CompilationSteps.CallClosureHandler( typeof(ZeroExtendOperator) )] private static void Protect_OverflowOperators( ComputeCallsClosure.Context host , Operator target ) { Keep_OverflowCheck( host ); } [CompilationSteps.CallClosureHandler( typeof(BinaryOperator) )] private static void Protect_BinaryOperator( ComputeCallsClosure.Context host , Operator target ) { BinaryOperator op = (BinaryOperator)target; TypeRepresentation td = op.FirstArgument.Type; TypeSystemForCodeTransformation ts = host.TypeSystem; WellKnownTypes wkt = ts.WellKnownTypes; WellKnownMethods wkm = ts.WellKnownMethods; if(td == wkt.System_Int32 || td == wkt.System_UInt32 ) { if(op.Signed) { switch(op.Alu) { case BinaryOperator.ALU.DIV: host.CoverObject( wkm.Helpers_BinaryOperations_IntDiv ); break; case BinaryOperator.ALU.REM: host.CoverObject( wkm.Helpers_BinaryOperations_IntRem ); break; } } else { switch(op.Alu) { case BinaryOperator.ALU.DIV: host.CoverObject( wkm.Helpers_BinaryOperations_UintDiv ); break; case BinaryOperator.ALU.REM: host.CoverObject( wkm.Helpers_BinaryOperations_UintRem ); break; } } } else if(td == wkt.System_Int64 || td == wkt.System_UInt64 ) { if(op.Signed) { switch(op.Alu) { case BinaryOperator.ALU.MUL: host.CoverObject( wkm.Helpers_BinaryOperations_LongMul ); break; case BinaryOperator.ALU.DIV: host.CoverObject( wkm.Helpers_BinaryOperations_LongDiv ); break; case BinaryOperator.ALU.REM: host.CoverObject( wkm.Helpers_BinaryOperations_LongRem ); break; case BinaryOperator.ALU.SHL: host.CoverObject( wkm.Helpers_BinaryOperations_LongShl ); break; case BinaryOperator.ALU.SHR: host.CoverObject( wkm.Helpers_BinaryOperations_LongShr ); break; } } else { switch(op.Alu) { case BinaryOperator.ALU.MUL: host.CoverObject( wkm.Helpers_BinaryOperations_UlongMul ); break; case BinaryOperator.ALU.DIV: host.CoverObject( wkm.Helpers_BinaryOperations_UlongDiv ); break; case BinaryOperator.ALU.REM: host.CoverObject( wkm.Helpers_BinaryOperations_UlongRem ); break; case BinaryOperator.ALU.SHL: host.CoverObject( wkm.Helpers_BinaryOperations_UlongShl ); break; case BinaryOperator.ALU.SHR: host.CoverObject( wkm.Helpers_BinaryOperations_UlongShr ); break; } } } } [CompilationSteps.CallClosureHandler(typeof(CallOperator))] private static void Protect_ExceptionOperators(ComputeCallsClosure.Context host, Operator target) { // Don't cover unprotected calls. if (target.BasicBlock.ProtectedBy.Length == 0) { return; } TypeRepresentation resultType = host.TypeSystem.WellKnownTypes.Microsoft_Zelig_Runtime_LandingPadResult; host.CoverObject(resultType); foreach (var field in resultType.Fields) { host.CoverObject(field); } } //--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--// //--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--// //--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--// private static void Keep_VTablesGetter( ComputeCallsClosure.Context host ) { host.CoverObject( host.TypeSystem.WellKnownMethods.VTable_Get ); } private static void Keep_VTables( ComputeCallsClosure.Context host ) { host.CoverObject( host.TypeSystem.WellKnownFields.ObjectHeader_VirtualTable ); } private static void Keep_MethodPointers( ComputeCallsClosure.Context host ) { host.CoverObject( host.TypeSystem.WellKnownFields.VTable_MethodPointers ); host.CoverObject( host.TypeSystem.WellKnownFields.CodePointer_Target ); } private static void Keep_InterfaceMap( ComputeCallsClosure.Context host ) { host.CoverObject( host.TypeSystem.WellKnownMethods.VTable_GetInterface ); } private static void Keep_ArraySize( ComputeCallsClosure.Context host ) { host.CoverObject( host.TypeSystem.WellKnownFields.ArrayImpl_m_numElements ); } private static void Keep_NullCheck( ComputeCallsClosure.Context host ) { host.CoverObject( host.TypeSystem.WellKnownMethods.ThreadImpl_ThrowNullException ); } private static void Keep_BoundCheck( ComputeCallsClosure.Context host ) { host.CoverObject( host.TypeSystem.WellKnownMethods.ThreadImpl_ThrowIndexOutOfRangeException ); } private static void Keep_OverflowCheck( ComputeCallsClosure.Context host ) { host.CoverObject( host.TypeSystem.WellKnownMethods.ThreadImpl_ThrowOverflowException ); } } } ================================================ FILE: Zelig/Zelig/CompileTime/CodeGenerator/CodeTransformation/CompilationSteps/Handlers/SoftwareFloatingPoint.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // namespace Microsoft.Zelig.CodeGeneration.IR.CompilationSteps.Handlers { using System; using System.Collections.Generic; using Microsoft.Zelig.Runtime.TypeSystem; public class SoftwareFloatingPoint { const string c_CompareAndSet_FloatEqual = "SoftFP_CompareAndSet_FloatEqual"; const string c_CompareAndSet_FloatGreaterOrEqual = "SoftFP_CompareAndSet_FloatGreaterOrEqual"; const string c_CompareAndSet_FloatGreater = "SoftFP_CompareAndSet_FloatGreater"; const string c_CompareAndSet_FloatLessOrEqual = "SoftFP_CompareAndSet_FloatLessOrEqual"; const string c_CompareAndSet_FloatLess = "SoftFP_CompareAndSet_FloatLess"; const string c_CompareAndSet_FloatNotEqual = "SoftFP_CompareAndSet_FloatNotEqual"; const string c_CompareAndSet_DoubleEqual = "SoftFP_CompareAndSet_DoubleEqual"; const string c_CompareAndSet_DoubleGreaterOrEqual = "SoftFP_CompareAndSet_DoubleGreaterOrEqual"; const string c_CompareAndSet_DoubleGreater = "SoftFP_CompareAndSet_DoubleGreater"; const string c_CompareAndSet_DoubleLessOrEqual = "SoftFP_CompareAndSet_DoubleLessOrEqual"; const string c_CompareAndSet_DoubleLess = "SoftFP_CompareAndSet_DoubleLess"; const string c_CompareAndSet_DoubleNotEqual = "SoftFP_CompareAndSet_DoubleNotEqual"; //--// const string c_BinaryOperations_FloatAdd = "SoftFP_BinaryOperations_FloatAdd"; const string c_BinaryOperations_FloatSub = "SoftFP_BinaryOperations_FloatSub"; const string c_BinaryOperations_FloatMul = "SoftFP_BinaryOperations_FloatMul"; const string c_BinaryOperations_FloatDiv = "SoftFP_BinaryOperations_FloatDiv"; const string c_BinaryOperations_FloatRem = "SoftFP_BinaryOperations_FloatRem"; const string c_BinaryOperations_DoubleAdd = "SoftFP_BinaryOperations_DoubleAdd"; const string c_BinaryOperations_DoubleSub = "SoftFP_BinaryOperations_DoubleSub"; const string c_BinaryOperations_DoubleMul = "SoftFP_BinaryOperations_DoubleMul"; const string c_BinaryOperations_DoubleDiv = "SoftFP_BinaryOperations_DoubleDiv"; const string c_BinaryOperations_DoubleRem = "SoftFP_BinaryOperations_DoubleRem"; //--// const string c_UnaryOperations_FloatNeg = "SoftFP_UnaryOperations_FloatNeg"; const string c_UnaryOperations_FloatFinite = "SoftFP_UnaryOperations_FloatFinite"; const string c_UnaryOperations_DoubleNeg = "SoftFP_UnaryOperations_DoubleNeg"; const string c_UnaryOperations_DoubleFinite = "SoftFP_UnaryOperations_DoubleFinite"; //--// const string c_Convert_IntToFloat = "SoftFP_Convert_IntToFloat"; const string c_Convert_LongToFloat = "SoftFP_Convert_LongToFloat"; const string c_Convert_UnsignedIntToFloat = "SoftFP_Convert_UnsignedIntToFloat"; const string c_Convert_UnsignedLongToFloat = "SoftFP_Convert_UnsignedLongToFloat"; const string c_Convert_DoubleToFloat = "SoftFP_Convert_DoubleToFloat"; const string c_Convert_IntToDouble = "SoftFP_Convert_IntToDouble"; const string c_Convert_LongToDouble = "SoftFP_Convert_LongToDouble"; const string c_Convert_UnsignedIntToDouble = "SoftFP_Convert_UnsignedIntToDouble"; const string c_Convert_UnsignedLongToDouble = "SoftFP_Convert_UnsignedLongToDouble"; const string c_Convert_FloatToDouble = "SoftFP_Convert_FloatToDouble"; const string c_Convert_FloatToInt = "SoftFP_Convert_FloatToInt"; const string c_Convert_FloatToUnsignedInt = "SoftFP_Convert_FloatToUnsignedInt"; const string c_Convert_DoubleToInt = "SoftFP_Convert_DoubleToInt"; const string c_Convert_DoubleToUnsignedInt = "SoftFP_Convert_DoubleToUnsignedInt"; const string c_Convert_FloatToLong = "SoftFP_Convert_FloatToLong"; const string c_Convert_FloatToUnsignedLong = "SoftFP_Convert_FloatToUnsignedLong"; const string c_Convert_DoubleToLong = "SoftFP_Convert_DoubleToLong"; const string c_Convert_DoubleToUnsignedLong = "SoftFP_Convert_DoubleToUnsignedLong"; //--// [CompilationSteps.CallClosureHandler( typeof(CompareConditionalControlOperator) )] private static void Protect_CompareConditionalControlOperator( ComputeCallsClosure.Context host , Operator target ) { CompareConditionalControlOperator op = (CompareConditionalControlOperator)target; Protect_CommonFloatingPointCompare( host, op, op.Condition ); } [CompilationSteps.CallClosureHandler( typeof(CompareAndSetOperator) )] private static void Protect_CompareAndSetOperators( ComputeCallsClosure.Context host , Operator target ) { CompareAndSetOperator op = (CompareAndSetOperator)target; Protect_CommonFloatingPointCompare( host, op, op.Condition ); } private static void Protect_CommonFloatingPointCompare( ComputeCallsClosure.Context host , Operator target , CompareAndSetOperator.ActionCondition condition ) { TypeRepresentation td = target.FirstArgument.Type; TypeSystemForCodeTransformation ts = host.TypeSystem; WellKnownTypes wkt = ts.WellKnownTypes; string name = null; if(td == wkt.System_Single) { switch(condition) { case CompareAndSetOperator.ActionCondition.EQ: name = c_CompareAndSet_FloatEqual ; break; case CompareAndSetOperator.ActionCondition.GE: name = c_CompareAndSet_FloatGreaterOrEqual; break; case CompareAndSetOperator.ActionCondition.GT: name = c_CompareAndSet_FloatGreater ; break; case CompareAndSetOperator.ActionCondition.LE: name = c_CompareAndSet_FloatLessOrEqual ; break; case CompareAndSetOperator.ActionCondition.LT: name = c_CompareAndSet_FloatLess ; break; case CompareAndSetOperator.ActionCondition.NE: name = c_CompareAndSet_FloatNotEqual ; break; } } else if(td == wkt.System_Double) { switch(condition) { case CompareAndSetOperator.ActionCondition.EQ: name = c_CompareAndSet_DoubleEqual ; break; case CompareAndSetOperator.ActionCondition.GE: name = c_CompareAndSet_DoubleGreaterOrEqual; break; case CompareAndSetOperator.ActionCondition.GT: name = c_CompareAndSet_DoubleGreater ; break; case CompareAndSetOperator.ActionCondition.LE: name = c_CompareAndSet_DoubleLessOrEqual ; break; case CompareAndSetOperator.ActionCondition.LT: name = c_CompareAndSet_DoubleLess ; break; case CompareAndSetOperator.ActionCondition.NE: name = c_CompareAndSet_DoubleNotEqual ; break; } } if(name != null) { host.CoverObject( ts.GetWellKnownMethod( name ) ); } } [CompilationSteps.CallClosureHandler( typeof(BinaryOperator) )] private static void Protect_BinaryOperator( ComputeCallsClosure.Context host , Operator target ) { BinaryOperator op = (BinaryOperator)target; TypeRepresentation td = op.FirstArgument.Type; TypeSystemForCodeTransformation ts = host.TypeSystem; WellKnownTypes wkt = ts.WellKnownTypes; string name = null; if(td == wkt.System_Single) { switch(op.Alu) { case BinaryOperator.ALU.ADD: name = c_BinaryOperations_FloatAdd; break; case BinaryOperator.ALU.SUB: name = c_BinaryOperations_FloatSub; break; case BinaryOperator.ALU.MUL: name = c_BinaryOperations_FloatMul; break; case BinaryOperator.ALU.DIV: name = c_BinaryOperations_FloatDiv; break; case BinaryOperator.ALU.REM: name = c_BinaryOperations_FloatRem; break; } } else if(td == wkt.System_Double) { switch(op.Alu) { case BinaryOperator.ALU.ADD: name = c_BinaryOperations_DoubleAdd; break; case BinaryOperator.ALU.SUB: name = c_BinaryOperations_DoubleSub; break; case BinaryOperator.ALU.MUL: name = c_BinaryOperations_DoubleMul; break; case BinaryOperator.ALU.DIV: name = c_BinaryOperations_DoubleDiv; break; case BinaryOperator.ALU.REM: name = c_BinaryOperations_DoubleRem; break; } } if(name != null) { host.CoverObject( ts.GetWellKnownMethod( name ) ); } } [CompilationSteps.CallClosureHandler( typeof(UnaryOperator) )] private static void Protect_UnaryOperator( ComputeCallsClosure.Context host , Operator target ) { UnaryOperator op = (UnaryOperator)target; TypeRepresentation td = op.FirstArgument.Type; TypeSystemForCodeTransformation ts = host.TypeSystem; WellKnownTypes wkt = ts.WellKnownTypes; string name = null; if(td == wkt.System_Single) { switch(op.Alu) { case UnaryOperator.ALU.NEG : name = c_UnaryOperations_FloatNeg ; break; case UnaryOperator.ALU.FINITE: name = c_UnaryOperations_FloatFinite; break; } } else if(td == wkt.System_Double) { switch(op.Alu) { case UnaryOperator.ALU.NEG : name = c_UnaryOperations_DoubleNeg ; break; case UnaryOperator.ALU.FINITE: name = c_UnaryOperations_DoubleFinite; break; } } if(name != null) { host.CoverObject( ts.GetWellKnownMethod( name ) ); } } [CompilationSteps.CallClosureHandler( typeof(ConvertOperator) )] private static void Protect_ConvertOperator( ComputeCallsClosure.Context host , Operator target ) { ConvertOperator op = (ConvertOperator)target; TypeSystemForCodeTransformation ts = host.TypeSystem; TypeRepresentation.BuiltInTypes kindInput = op.InputKind; TypeRepresentation.BuiltInTypes kindOutput = op.OutputKind; string name = null; switch(kindOutput) { case TypeRepresentation.BuiltInTypes.R4: switch(kindInput) { case TypeRepresentation.BuiltInTypes.I4: name = c_Convert_IntToFloat ; break; case TypeRepresentation.BuiltInTypes.U4: name = c_Convert_UnsignedIntToFloat ; break; case TypeRepresentation.BuiltInTypes.I8: name = c_Convert_LongToFloat ; break; case TypeRepresentation.BuiltInTypes.U8: name = c_Convert_UnsignedLongToFloat; break; case TypeRepresentation.BuiltInTypes.R8: name = c_Convert_DoubleToFloat ; break; } break; case TypeRepresentation.BuiltInTypes.R8: switch(kindInput) { case TypeRepresentation.BuiltInTypes.I4: name = c_Convert_IntToDouble ; break; case TypeRepresentation.BuiltInTypes.U4: name = c_Convert_UnsignedIntToDouble ; break; case TypeRepresentation.BuiltInTypes.I8: name = c_Convert_LongToDouble ; break; case TypeRepresentation.BuiltInTypes.U8: name = c_Convert_UnsignedLongToDouble; break; case TypeRepresentation.BuiltInTypes.R4: name = c_Convert_FloatToDouble ; break; } break; case TypeRepresentation.BuiltInTypes.I4: switch(kindInput) { case TypeRepresentation.BuiltInTypes.R4: name = c_Convert_FloatToInt ; break; case TypeRepresentation.BuiltInTypes.R8: name = c_Convert_DoubleToInt; break; } break; case TypeRepresentation.BuiltInTypes.U4: switch(kindInput) { case TypeRepresentation.BuiltInTypes.R4: name = c_Convert_FloatToUnsignedInt ; break; case TypeRepresentation.BuiltInTypes.R8: name = c_Convert_DoubleToUnsignedInt; break; } break; case TypeRepresentation.BuiltInTypes.I8: switch(kindInput) { case TypeRepresentation.BuiltInTypes.R4: name = c_Convert_FloatToLong ; break; case TypeRepresentation.BuiltInTypes.R8: name = c_Convert_DoubleToLong; break; } break; case TypeRepresentation.BuiltInTypes.U8: switch(kindInput) { case TypeRepresentation.BuiltInTypes.R4: name = c_Convert_FloatToUnsignedLong ; break; case TypeRepresentation.BuiltInTypes.R8: name = c_Convert_DoubleToUnsignedLong; break; } break; } if(name != null) { host.CoverObject( ts.GetWellKnownMethod( name ) ); } } //--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--// //--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--// //--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--// [CompilationSteps.PhaseFilter( typeof(Phases.ConvertUnsupportedOperatorsToMethodCalls) )] [CompilationSteps.OperatorHandler( typeof(CompareConditionalControlOperator) )] private static void Handle_CompareConditionalControlOperator( PhaseExecution.NotificationContext nc ) { CompareConditionalControlOperator op = (CompareConditionalControlOperator)nc.CurrentOperator; if(op.FirstArgument.Type.IsFloatingPoint) { ControlFlowGraphStateForCodeTransformation cfg = nc.CurrentCFG; TypeSystemForCodeTransformation ts = nc.TypeSystem; TemporaryVariableExpression tmp = cfg.AllocateTemporary( ts.WellKnownTypes.System_Boolean, null ); CompareAndSetOperator opCmp = CompareAndSetOperator.New( op.DebugInfo, op.Condition, op.Signed, tmp, op.FirstArgument, op.SecondArgument ); op.AddOperatorBefore( opCmp ); BinaryConditionalControlOperator opCtrl = BinaryConditionalControlOperator.New( op.DebugInfo, tmp, op.TargetBranchNotTaken, op.TargetBranchTaken ); op.SubstituteWithOperator( opCtrl, Operator.SubstitutionFlags.Default ); nc.MarkAsModified(); } } //--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--// //--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--// //--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--// [CompilationSteps.PhaseFilter( typeof(Phases.ConvertUnsupportedOperatorsToMethodCalls) )] [CompilationSteps.OperatorHandler( typeof(CompareAndSetOperator) )] private static void Handle_CompareAndSetOperator( PhaseExecution.NotificationContext nc ) { CompareAndSetOperator op = (CompareAndSetOperator)nc.CurrentOperator; Expression exSrc1 = op.FirstArgument; Expression exSrc2 = op.SecondArgument; TypeRepresentation tdSrc1 = exSrc1.Type; TypeRepresentation tdSrc2 = exSrc2.Type; if(tdSrc1.IsFloatingPoint && tdSrc2.IsFloatingPoint ) { ControlFlowGraphStateForCodeTransformation cfg = nc.CurrentCFG; TypeSystemForCodeTransformation ts = nc.TypeSystem; uint sizeSrc1 = tdSrc1.SizeOfHoldingVariableInWords; uint sizeSrc2 = tdSrc2.SizeOfHoldingVariableInWords; string name; CHECKS.ASSERT( sizeSrc1 == sizeSrc2, "Cannot compare entities of different size: {0} <=> {1}", exSrc1, exSrc2 ); if(sizeSrc1 == 1) { switch(op.Condition) { case CompareAndSetOperator.ActionCondition.EQ: name = c_CompareAndSet_FloatEqual ; break; case CompareAndSetOperator.ActionCondition.GE: name = c_CompareAndSet_FloatGreaterOrEqual; break; case CompareAndSetOperator.ActionCondition.GT: name = c_CompareAndSet_FloatGreater ; break; case CompareAndSetOperator.ActionCondition.LE: name = c_CompareAndSet_FloatLessOrEqual ; break; case CompareAndSetOperator.ActionCondition.LT: name = c_CompareAndSet_FloatLess ; break; case CompareAndSetOperator.ActionCondition.NE: name = c_CompareAndSet_FloatNotEqual ; break; default: throw TypeConsistencyErrorException.Create( "Unexpected value {0} in {1}", op.Condition, op ); } } else if(sizeSrc1 == 2) { switch(op.Condition) { case CompareAndSetOperator.ActionCondition.EQ: name = c_CompareAndSet_DoubleEqual ; break; case CompareAndSetOperator.ActionCondition.GE: name = c_CompareAndSet_DoubleGreaterOrEqual; break; case CompareAndSetOperator.ActionCondition.GT: name = c_CompareAndSet_DoubleGreater ; break; case CompareAndSetOperator.ActionCondition.LE: name = c_CompareAndSet_DoubleLessOrEqual ; break; case CompareAndSetOperator.ActionCondition.LT: name = c_CompareAndSet_DoubleLess ; break; case CompareAndSetOperator.ActionCondition.NE: name = c_CompareAndSet_DoubleNotEqual ; break; default: throw TypeConsistencyErrorException.Create( "Unexpected value {0} in {1}", op.Condition, op ); } } else { throw TypeConsistencyErrorException.Create( "Unsupported compare operation larger than 64 bits: {0}", op ); } ts.SubstituteWithCallToHelper( name, op ); nc.MarkAsModified(); } } //--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--// //--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--// //--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--// [CompilationSteps.PhaseFilter( typeof(Phases.ConvertUnsupportedOperatorsToMethodCalls) )] [CompilationSteps.OperatorHandler( typeof(BinaryOperator) )] private static void Handle_BinaryOperator( PhaseExecution.NotificationContext nc ) { BinaryOperator op = (BinaryOperator)nc.CurrentOperator; Expression exSrc1 = op.FirstArgument; Expression exSrc2 = op.SecondArgument; TypeRepresentation tdSrc1 = exSrc1.Type; TypeRepresentation tdSrc2 = exSrc2.Type; if(tdSrc1.IsFloatingPoint && tdSrc2.IsFloatingPoint ) { ControlFlowGraphStateForCodeTransformation cfg = nc.CurrentCFG; TypeSystemForCodeTransformation ts = nc.TypeSystem; VariableExpression exRes = op.FirstResult; TypeRepresentation tdRes = exRes .Type; uint sizeRes = tdRes .SizeOfHoldingVariableInWords; uint sizeSrc1 = tdSrc1.SizeOfHoldingVariableInWords; uint sizeSrc2 = tdSrc2.SizeOfHoldingVariableInWords; string name; CHECKS.ASSERT( sizeSrc1 == sizeSrc2, "Cannot compare entities of different size: {0} <=> {1}", exSrc1, exSrc2 ); if(sizeSrc1 == 1) { switch(op.Alu) { case BinaryOperator.ALU.ADD: name = c_BinaryOperations_FloatAdd; break; case BinaryOperator.ALU.SUB: name = c_BinaryOperations_FloatSub; break; case BinaryOperator.ALU.MUL: name = c_BinaryOperations_FloatMul; break; case BinaryOperator.ALU.DIV: name = c_BinaryOperations_FloatDiv; break; case BinaryOperator.ALU.REM: name = c_BinaryOperations_FloatRem; break; default: throw TypeConsistencyErrorException.Create( "Unsupported inputs for binary operator: {0}", op ); } } else if(sizeSrc1 == 2) { switch(op.Alu) { case BinaryOperator.ALU.ADD: name = c_BinaryOperations_DoubleAdd; break; case BinaryOperator.ALU.SUB: name = c_BinaryOperations_DoubleSub; break; case BinaryOperator.ALU.MUL: name = c_BinaryOperations_DoubleMul; break; case BinaryOperator.ALU.DIV: name = c_BinaryOperations_DoubleDiv; break; case BinaryOperator.ALU.REM: name = c_BinaryOperations_DoubleRem; break; default: throw TypeConsistencyErrorException.Create( "Unsupported inputs for binary operator: {0}", op ); } } else { throw TypeConsistencyErrorException.Create( "Unsupported inputs for binary operator: {0}", op ); } ts.SubstituteWithCallToHelper( name, op ); nc.MarkAsModified(); } } //--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--// //--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--// //--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--// [CompilationSteps.PhaseFilter( typeof(Phases.ConvertUnsupportedOperatorsToMethodCalls) )] [CompilationSteps.OperatorHandler( typeof(UnaryOperator) )] private static void Handle_UnaryOperator( PhaseExecution.NotificationContext nc ) { UnaryOperator op = (UnaryOperator)nc.CurrentOperator; Expression exSrc = op.FirstArgument; TypeRepresentation tdSrc = exSrc.Type; if(tdSrc.IsFloatingPoint) { ControlFlowGraphStateForCodeTransformation cfg = nc.CurrentCFG; TypeSystemForCodeTransformation ts = nc.TypeSystem; uint sizeSrc = tdSrc.SizeOfHoldingVariableInWords; string name; if(sizeSrc == 1) { switch(op.Alu) { case UnaryOperator.ALU.NEG : name = c_UnaryOperations_FloatNeg ; break; case UnaryOperator.ALU.FINITE: name = c_UnaryOperations_FloatFinite; break; default: throw TypeConsistencyErrorException.Create( "Unsupported inputs for unary operator: {0}", op ); } } else if(sizeSrc == 2) { switch(op.Alu) { case UnaryOperator.ALU.NEG : name = c_UnaryOperations_DoubleNeg ; break; case UnaryOperator.ALU.FINITE: name = c_UnaryOperations_DoubleFinite; break; default: throw TypeConsistencyErrorException.Create( "Unsupported inputs for unary operator: {0}", op ); } } else { throw TypeConsistencyErrorException.Create( "Unsupported inputs for unary operator: {0}", op ); } ts.SubstituteWithCallToHelper( name, op ); nc.MarkAsModified(); } } //--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--// //--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--// //--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--// [CompilationSteps.PhaseFilter( typeof(Phases.ConvertUnsupportedOperatorsToMethodCalls) )] [CompilationSteps.OperatorHandler( typeof(BinaryConditionalControlOperator) )] private static void Handle_BinaryConditionalControlOperator( PhaseExecution.NotificationContext nc ) { BinaryConditionalControlOperator op = (BinaryConditionalControlOperator)nc.CurrentOperator; Expression exSrc = op.FirstArgument; TypeRepresentation tdSrc = exSrc.Type; //--// if(tdSrc.IsFloatingPoint) { TypeSystemForCodeTransformation ts = nc.TypeSystem; ControlFlowGraphStateForCodeTransformation cfg = nc.CurrentCFG; Debugging.DebugInfo debugInfo = op.DebugInfo; uint sizeSrc = tdSrc.SizeOfHoldingVariableInWords; string name; object val; if(sizeSrc == 1) { name = c_CompareAndSet_FloatEqual; val = (float)0; } else if(sizeSrc == 2) { name = c_CompareAndSet_DoubleEqual; val = (double)0; } else { throw TypeConsistencyErrorException.Create( "Unsupported inputs for compare: {0}", op ); } MethodRepresentation md = ts.GetWellKnownMethod( name ); VariableExpression tmpFragment = cfg.AllocatePseudoRegister( ts.WellKnownTypes.System_Boolean ); Expression[] rhs = ts.AddTypePointerToArgumentsOfStaticMethod( md, op.FirstArgument, ts.CreateConstant( md.OwnerType, val ) ); StaticCallOperator opCall = StaticCallOperator.New( op.DebugInfo, CallOperator.CallKind.Direct, md, VariableExpression.ToArray( tmpFragment ), rhs ); op.AddOperatorBefore( opCall ); //--// var cc = cfg.AllocateConditionCode(); op.AddOperatorBefore( CompareOperator.New( debugInfo, cc, tmpFragment, ts.CreateConstant( 0 ) ) ); ConditionCodeConditionalControlOperator opNew = ConditionCodeConditionalControlOperator.New( debugInfo, ConditionCodeExpression.Comparison.NotEqual, cc, op.TargetBranchNotTaken, op.TargetBranchTaken ); op.SubstituteWithOperator( opNew, Operator.SubstitutionFlags.Default ); nc.MarkAsModified(); } } //--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--// //--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--// //--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--// [CompilationSteps.PhaseFilter( typeof(Phases.FromImplicitToExplicitExceptions) )] [CompilationSteps.OperatorHandler( typeof(ConvertOperator) )] private static void Handle_ConvertOperator_Exceptions( PhaseExecution.NotificationContext nc ) { ConvertOperator op = (ConvertOperator)nc.CurrentOperator; VariableExpression lhs = op.FirstResult; Expression rhs = op.FirstArgument; if(op.CheckOverflow) { ConvertOperator opNew = ConvertOperator.New( op.DebugInfo, op.InputKind, op.OutputKind, false, lhs, rhs ); op.SubstituteWithOperator( opNew, Operator.SubstitutionFlags.CopyAnnotations ); // // BUGBUG: We are dropping the overflow check!! // //// CreateOverflowCheck( nc, op, opNew ); nc.MarkAsModified(); } } //--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--// //--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--// //--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--// [CompilationSteps.PhaseFilter( typeof(Phases.ConvertUnsupportedOperatorsToMethodCalls) )] [CompilationSteps.OperatorHandler( typeof(ConvertOperator) )] private static void Handle_ConvertOperator( PhaseExecution.NotificationContext nc ) { ConvertOperator op = (ConvertOperator)nc.CurrentOperator; TypeSystemForCodeTransformation ts = nc.TypeSystem; TypeRepresentation.BuiltInTypes kindInput = op.InputKind; TypeRepresentation.BuiltInTypes kindOutput = op.OutputKind; string name = null; switch(kindOutput) { case TypeRepresentation.BuiltInTypes.R4: switch(kindInput) { case TypeRepresentation.BuiltInTypes.I4: name = c_Convert_IntToFloat ; break; case TypeRepresentation.BuiltInTypes.U4: name = c_Convert_UnsignedIntToFloat ; break; case TypeRepresentation.BuiltInTypes.I8: name = c_Convert_LongToFloat ; break; case TypeRepresentation.BuiltInTypes.U8: name = c_Convert_UnsignedLongToFloat; break; case TypeRepresentation.BuiltInTypes.R8: name = c_Convert_DoubleToFloat ; break; } break; case TypeRepresentation.BuiltInTypes.R8: switch(kindInput) { case TypeRepresentation.BuiltInTypes.I4: name = c_Convert_IntToDouble ; break; case TypeRepresentation.BuiltInTypes.U4: name = c_Convert_UnsignedIntToDouble ; break; case TypeRepresentation.BuiltInTypes.I8: name = c_Convert_LongToDouble ; break; case TypeRepresentation.BuiltInTypes.U8: name = c_Convert_UnsignedLongToDouble; break; case TypeRepresentation.BuiltInTypes.R4: name = c_Convert_FloatToDouble ; break; } break; case TypeRepresentation.BuiltInTypes.I4: switch(kindInput) { case TypeRepresentation.BuiltInTypes.R4: name = c_Convert_FloatToInt ; break; case TypeRepresentation.BuiltInTypes.R8: name = c_Convert_DoubleToInt; break; } break; case TypeRepresentation.BuiltInTypes.U4: switch(kindInput) { case TypeRepresentation.BuiltInTypes.R4: name = c_Convert_FloatToUnsignedInt ; break; case TypeRepresentation.BuiltInTypes.R8: name = c_Convert_DoubleToUnsignedInt; break; } break; case TypeRepresentation.BuiltInTypes.I8: switch(kindInput) { case TypeRepresentation.BuiltInTypes.R4: name = c_Convert_FloatToLong ; break; case TypeRepresentation.BuiltInTypes.R8: name = c_Convert_DoubleToLong; break; } break; case TypeRepresentation.BuiltInTypes.U8: switch(kindInput) { case TypeRepresentation.BuiltInTypes.R4: name = c_Convert_FloatToUnsignedLong ; break; case TypeRepresentation.BuiltInTypes.R8: name = c_Convert_DoubleToUnsignedLong; break; } break; } if(name != null) { MethodRepresentation md = ts.GetWellKnownMethod( name ); Expression[] rhs = ts.AddTypePointerToArgumentsOfStaticMethod( md, op.FirstArgument, ts.CreateConstant( ts.WellKnownTypes.System_Boolean, op.CheckOverflow ) ); StaticCallOperator opCall = StaticCallOperator.New( op.DebugInfo, CallOperator.CallKind.Direct, md, op.Results, rhs ); op.SubstituteWithOperator( opCall, Operator.SubstitutionFlags.Default ); nc.MarkAsModified(); } } } } ================================================ FILE: Zelig/Zelig/CompileTime/CodeGenerator/CodeTransformation/CompilationSteps/Handlers/WellKnownFieldHandlers.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // namespace Microsoft.Zelig.CodeGeneration.IR.CompilationSteps.Handlers { using System; using System.Collections.Generic; using Microsoft.Zelig.Runtime.TypeSystem; public class WellKnownFieldHandlers { [CompilationSteps.PhaseFilter( typeof(Phases.HighLevelTransformations) )] [CompilationSteps.PostPhaseHandler] private static void Handle_ResourceManagerImpl_s_resources( PhaseDriver host , TypeSystemForCodeTransformation typeSystem ) { // // Only generate the table if the corresponding field is referenced by the application. // We can detect that by checking the "ImplementedBy" property of a static field: // it will be valid if there's an operator involving the field. // var fd = (StaticFieldRepresentation)typeSystem.WellKnownFields.ResourceManagerImpl_s_resources; if(fd != null) { InstanceFieldRepresentation fdReal = fd.ImplementedBy; if(fdReal != null) { DataManager.ObjectDescriptor od = typeSystem.GetGlobalRoot(); if(od.Get( fdReal ) == null) // Create only once. { od.ConvertAndSet( fdReal, DataManager.Attributes.Constant | DataManager.Attributes.SuitableForConstantPropagation, null, typeSystem.Resources.ToArray() ); } } } } [CompilationSteps.PhaseFilter( typeof(Phases.ReduceTypeSystem) )] [CompilationSteps.PostPhaseHandler] private static void Handle_GarbageCollectionManager_m_extensionTargets( PhaseDriver host , TypeSystemForCodeTransformation typeSystem ) { // // Only generate the table if the corresponding field is referenced by the application. // We can detect that by checking the "ImplementedBy" property of a static field: // it will be valid if there's an operator involving the field. // var fd = (InstanceFieldRepresentation)typeSystem.WellKnownFields.GarbageCollectionManager_m_extensionTargets; if(fd != null) { TypeRepresentation td = fd.OwnerType; TypeRepresentation tdNew; if(typeSystem.ForcedDevirtualizations.TryGetValue( td, out tdNew ) == false) { throw TypeConsistencyErrorException.Create( "Cannot devirtualize type '{0}'", td ); } var od = typeSystem.GenerateSingleton( tdNew, DataManager.Attributes.Constant | DataManager.Attributes.SuitableForConstantPropagation ); if(od.Get( fd ) == null) { var extensions = typeSystem.GarbageCollectionExtensions; var vTables = new VTable[extensions.Count]; int pos = 0; foreach(var tdSrc in extensions.Keys) { vTables[pos++] = tdSrc.VirtualTable; } od.ConvertAndSet( fd, DataManager.Attributes.Constant, null, vTables ); } } } [CompilationSteps.PhaseFilter( typeof(Phases.ReduceTypeSystem) )] [CompilationSteps.PostPhaseHandler] private static void Handle_GarbageCollectionManager_m_extensionHandlers( PhaseDriver host , TypeSystemForCodeTransformation typeSystem ) { // // Only generate the table if the corresponding field is referenced by the application. // We can detect that by checking the "ImplementedBy" property of a static field: // it will be valid if there's an operator involving the field. // var fd = (InstanceFieldRepresentation)typeSystem.WellKnownFields.GarbageCollectionManager_m_extensionHandlers; if(fd != null) { TypeRepresentation td = fd.OwnerType; TypeRepresentation tdNew; if(typeSystem.ForcedDevirtualizations.TryGetValue( td, out tdNew ) == false) { throw TypeConsistencyErrorException.Create( "Cannot devirtualize type '{0}'", td ); } var od = typeSystem.GenerateSingleton( tdNew, DataManager.Attributes.Constant | DataManager.Attributes.SuitableForConstantPropagation ); if(od.Get( fd ) == null) { var extensions = typeSystem.GarbageCollectionExtensions; var handlers = typeSystem.DataManagerInstance.BuildArrayDescriptor( (ArrayReferenceTypeRepresentation)fd.FieldType, DataManager.Attributes.Mutable, null, null, extensions.Count ); int pos = 0; foreach(var tdSrc in extensions.Keys) { handlers.Set( pos++, typeSystem.DataManagerInstance.BuildObjectDescriptor( extensions[tdSrc], DataManager.Attributes.Mutable, null ) ); } od.Set( fd, handlers ); } } } [CompilationSteps.PhaseFilter( typeof(Phases.HighLevelTransformations) )] [CompilationSteps.WellKnownFieldHandler( "Memory_m_availableMemory" )] private static void Handle_Memory_m_availableMemory( PhaseExecution.NotificationContext nc ) { Operator op = nc.CurrentOperator; InstanceFieldRepresentation fd = (InstanceFieldRepresentation)nc.Value; TypeRepresentation td = fd.OwnerType; TypeRepresentation tdNew; if(nc.TypeSystem.ForcedDevirtualizations.TryGetValue( td, out tdNew ) == false) { throw TypeConsistencyErrorException.Create( "Cannot devirtualize type '{0}'", td ); } DataManager.ObjectDescriptor od = nc.TypeSystem.GenerateSingleton( tdNew, DataManager.Attributes.Constant | DataManager.Attributes.SuitableForConstantPropagation ); if(od.Get( fd ) == null) { // // This will be updated later in the compilation process, see Core.CreateAvailableMemoryTables() // od.ConvertAndSet( fd, DataManager.Attributes.Constant, null, new Runtime.Memory.Range[0] ); } // // This is never null. // if(op.HasAnnotation< NotNullAnnotation >() == false) { op.AddAnnotation( NotNullAnnotation.Create( nc.TypeSystem ) ); } } [CompilationSteps.PhaseFilter( typeof(Phases.HighLevelTransformations ) )] [CompilationSteps.PhaseFilter( typeof(Phases.FromImplicitToExplicitExceptions) )] [CompilationSteps.WellKnownFieldHandler( "ArrayImpl_m_numElements" )] private static void Handle_ArrayImpl_m_numElements( PhaseExecution.NotificationContext nc ) { Operator op = nc.CurrentOperator; if(op is LoadInstanceFieldOperator) { if(op.HasAnnotation< ArrayLengthAnnotation >() == false) { op.AddAnnotation( ArrayLengthAnnotation.Create( nc.TypeSystem ) ); } } } } } ================================================ FILE: Zelig/Zelig/CompileTime/CodeGenerator/CodeTransformation/CompilationSteps/Handlers/WellKnownMethodHandlers.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // // Enable this macro to shift object pointers from the beginning of the header to the beginning of the payload. #define CANONICAL_OBJECT_POINTERS namespace Microsoft.Zelig.CodeGeneration.IR.CompilationSteps.Handlers { using System; using System.Collections.Generic; using Microsoft.Zelig.Runtime.TypeSystem; public class WellKnownMethodHandlers { [CompilationSteps.PhaseFilter( typeof(Phases.HighLevelTransformations) )] [CompilationSteps.CallToWellKnownMethodHandler( "Configuration_ExecuteApplication" )] private static void Handle_Configuration_ExecuteApplication( PhaseExecution.NotificationContext nc ) { CallOperator op = nc.GetOperatorAndThrowIfNotCall(); TypeSystemForCodeTransformation ts = nc.TypeSystem; MethodRepresentation md = op.TargetMethod; MethodRepresentation mdApp = ts.ApplicationEntryPoint; if(md.MatchSignature( mdApp, null )) { op.TargetMethod = mdApp; nc.MarkAsModified(); return; } if(mdApp.ThisPlusArguments.Length == 2) { TypeRepresentation tdArg = mdApp.ThisPlusArguments[1]; if(tdArg is ArrayReferenceTypeRepresentation) { if(tdArg.ContainedType == ts.WellKnownTypes.System_String) { Expression[] rhs = ts.AddTypePointerToArgumentsOfStaticMethod( mdApp, ts.CreateNullPointer( mdApp.ThisPlusArguments[1] ) ); CallOperator callNew = StaticCallOperator.New( op.DebugInfo, CallOperator.CallKind.Direct, mdApp, rhs ); op.SubstituteWithOperator( callNew, Operator.SubstitutionFlags.Default ); nc.MarkAsModified(); return; } } } throw TypeConsistencyErrorException.Create( "Cannot use '{0}' as an application entry point, incompatible signature", md ); } //--//--//--//--//--//--//--//--//--//--//--//--//--//--// [CompilationSteps.PhaseFilter( typeof(Phases.HighLevelTransformations) )] [CompilationSteps.CallToWellKnownMethodHandler( "RuntimeHelpers_InitializeArray" )] private static void Handle_RuntimeHelpers_InitializeArray( PhaseExecution.NotificationContext nc ) { CallOperator op = nc.GetOperatorAndThrowIfNotCall(); ConstantExpression exConst = op.ThirdArgument as ConstantExpression; if(exConst != null) { DataManager.ObjectDescriptor odHandle = (DataManager.ObjectDescriptor)exConst.Value; DataManager.ObjectDescriptor odField = (DataManager.ObjectDescriptor)odHandle.Get( (InstanceFieldRepresentation)nc.TypeSystem.WellKnownFields.RuntimeFieldHandleImpl_m_value ); FieldRepresentation fd = (FieldRepresentation)odField.Source; TypeSystemForCodeTransformation ts = nc.TypeSystem; // // Get the field, extract the default value, convert it to an array of the right type, then copy the array. // ArrayReferenceTypeRepresentation td = (ArrayReferenceTypeRepresentation)op.SecondArgument.Type; ScalarTypeRepresentation tdElement = td.ContainedType as ScalarTypeRepresentation; if(tdElement != null) { byte[] rawData = ts.GetDefaultValue( fd ); Type t = tdElement.ConvertToRuntimeType(); Array srcData = Array.CreateInstance( t, rawData.Length / tdElement.Size ); MethodRepresentation md = ts.WellKnownMethods.RuntimeHelpers_InitializeArray2; Buffer.BlockCopy( rawData, 0, srcData, 0, rawData.Length ); Expression[] rhs = new Expression[] { op.FirstArgument, op.SecondArgument, ts.GenerateConstantArrayAccessor( op, td, srcData, null ) }; CallOperator callNew = StaticCallOperator.New( op.DebugInfo, CallOperator.CallKind.Direct, md, rhs ); op.SubstituteWithOperator( callNew, Operator.SubstitutionFlags.Default ); nc.MarkAsModified(); return; } } throw TypeConsistencyErrorException.Create( "Unsupported array initializer in {0}", op ); } //--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--// //--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--// //--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--// [CompilationSteps.PhaseFilter( typeof(Phases.HighLevelTransformations) )] [CompilationSteps.CallToWellKnownMethodHandler( "MarshalImpl_SizeOf__Type" )] private static void Handle_MarshalImpl_SizeOf__Type( PhaseExecution.NotificationContext nc ) { CallOperator op = nc.GetOperatorAndThrowIfNotCall(); TypeSystemForCodeTransformation ts = nc.TypeSystem; ControlFlowGraphStateForCodeTransformation cfg = nc.CurrentCFG; while(true) { SingleAssignmentOperator opDef; VTable vTable = InferVirtualTableFromConstantTypeParameter( ts, cfg, op.SecondArgument, out opDef ); if(vTable == null) { break; } var opNew = SingleAssignmentOperator.New( op.DebugInfo, op.FirstResult, ts.CreateConstantForTypeSize( vTable.TypeInfo ) ); if(cfg.FindSingleUse( opDef.FirstResult ) == op) { opDef.Delete(); } op.SubstituteWithOperator( opNew, Operator.SubstitutionFlags.Default ); nc.StopScan(); return; } } //--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--// //--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--// //--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--// [CompilationSteps.PhaseFilter( typeof(Phases.HighLevelTransformations) )] [CompilationSteps.CallToWellKnownMethodHandler( "RuntimeHelpers_get_OffsetToStringData" )] private static void Handle_RuntimeHelpers_get_OffsetToStringData( PhaseExecution.NotificationContext nc ) { CallOperator op = nc.GetOperatorAndThrowIfNotCall(); TypeSystemForCodeTransformation ts = nc.TypeSystem; // Return an adjusted offset, accounting for the header size. ConstantExpression offset = ts.CreateConstantForFieldOffset( ts.WellKnownFields.StringImpl_FirstChar ); #if CANONICAL_OBJECT_POINTERS var opNew = SingleAssignmentOperator.New( op.DebugInfo, op.FirstResult, offset ); #else // CANONICAL_OBJECT_POINTERS ConstantExpression headerSize = ts.CreateConstantForTypeSize( ts.WellKnownTypes.Microsoft_Zelig_Runtime_ObjectHeader ); var opNew = BinaryOperator.New( op.DebugInfo, BinaryOperator.ALU.ADD, false, false, op.FirstResult, offset, headerSize ); #endif // CANONICAL_OBJECT_POINTERS op.SubstituteWithOperator( opNew, Operator.SubstitutionFlags.Default ); nc.MarkAsModified(); } //--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--// //--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--// //--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--// [CompilationSteps.PhaseFilter( typeof(Phases.HighLevelTransformations) )] [CompilationSteps.CallToWellKnownMethodHandler( "Object_NullCheck" )] private static void Handle_Object_NullCheck( PhaseExecution.NotificationContext nc ) { CallOperator op = nc.GetOperatorAndThrowIfNotCall(); TypeSystemForCodeTransformation ts = nc.TypeSystem; NullCheckOperator opNew = NullCheckOperator.New( op.DebugInfo, op.SecondArgument ); op.SubstituteWithOperator( opNew, Operator.SubstitutionFlags.Default ); nc.MarkAsModified(); } //--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--// //--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--// //--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--// [CompilationSteps.CallToWellKnownMethodHandler( "Microsoft_Zelig_Runtime_AbstractMethodWrapper_AddActivationRecordEvent" )] private static void Handle_Microsoft_Zelig_Runtime_AbstractMethodWrapper_AddActivationRecordEvent( PhaseExecution.NotificationContext nc ) { CallOperator op = nc.GetOperatorAndThrowIfNotCall(); TypeSystemForCodeTransformation ts = nc.TypeSystem; if(nc.IsParameterConstant( op, 1 )) { int ev = nc.ExtractConstantIntParameter( op, 1 ); var opNew = AddActivationRecordEventOperator.New( op.DebugInfo, (Runtime.ActivationRecordEvents)ev ); op.SubstituteWithOperator( opNew, Operator.SubstitutionFlags.Default ); nc.MarkAsModified(); } } //--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--// //--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--// //--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--// [CompilationSteps.PhaseFilter( typeof(Phases.HighLevelTransformations) )] [CompilationSteps.CustomAttributeHandler( "Microsoft_Zelig_Runtime_TypeSystem_GenerateUnsafeCastAttribute" )] private static void Handle_GenerateUnsafeCast( PhaseExecution.NotificationContext nc , CustomAttributeRepresentation ca ) { CallOperator op = nc.GetOperatorAndThrowIfNotCall(); int offset; if(op.TargetMethod is StaticMethodRepresentation) { offset = 1; } else { offset = 0; } if(op.Arguments.Length != offset + 1) { throw TypeConsistencyErrorException.Create( "GenerateUnsafeCastAttribute use incompatible with signature for method '{0}'", op.TargetMethod ); } var opNew = SingleAssignmentOperator.New( op.DebugInfo, op.FirstResult, op.Arguments[offset] ); op.SubstituteWithOperator( opNew, Operator.SubstitutionFlags.Default ); nc.MarkAsModified(); } //--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--// //--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--// //--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--// [CompilationSteps.PhaseFilter( typeof(Phases.ApplyConfigurationSettings) )] [CompilationSteps.CustomAttributeHandler( "Microsoft_Zelig_Runtime_ConfigurationOptionAttribute" )] private static void Handle_ConfigurationOption( PhaseExecution.NotificationContext nc , CustomAttributeRepresentation ca ) { var cfgProv = nc.TypeSystem.GetEnvironmentService< IConfigurationProvider >(); var op = nc.CurrentOperator; if(cfgProv != null) { string name = (string)ca.FixedArgsValues[0]; object val; if(cfgProv.GetValue( name, out val )) { ConstantExpression ex = nc.TypeSystem.CreateConstantFromObject( val ); if(op is CallOperator) { op.SubstituteWithOperator( SingleAssignmentOperator.New( op.DebugInfo, op.FirstResult, ex ), Operator.SubstitutionFlags.Default ); nc.MarkAsModified(); return; } if(op is LoadFieldOperator) { op.SubstituteWithOperator( SingleAssignmentOperator.New( op.DebugInfo, op.FirstResult, ex ), Operator.SubstitutionFlags.Default ); nc.MarkAsModified(); return; } } } var call = op as CallOperator; if(call != null) { nc.Phase.CallsDataBase.QueueForForcedInlining( call ); } } //--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--// //--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--// //--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--// [CompilationSteps.PhaseFilter( typeof(Phases.HighLevelToMidLevelConversion) )] [CompilationSteps.CallToWellKnownMethodHandler( "TypeSystemManager_CastToType" )] [CompilationSteps.CallToWellKnownMethodHandler( "TypeSystemManager_CastToTypeNoThrow" )] [CompilationSteps.CallToWellKnownMethodHandler( "TypeSystemManager_CastToSealedType" )] [CompilationSteps.CallToWellKnownMethodHandler( "TypeSystemManager_CastToSealedTypeNoThrow" )] private static void Handle_CastToType( PhaseExecution.NotificationContext nc ) { CallOperator call = nc.GetOperatorAndThrowIfNotCall(); Expression exSrc = call.SecondArgument; ConstantExpression exVTable = call.ThirdArgument as ConstantExpression; if(exVTable != null) { DataManager.ObjectDescriptor od = (DataManager.ObjectDescriptor)exVTable.Value; VTable vtable = (VTable )od.Source; TypeRepresentation tdTarget = vtable.TypeInfo; TypeRepresentation tdSource = exSrc.Type; TypeRepresentation tdSource2 = nc.TypeSystem.FindSingleConcreteImplementation( tdSource ); if(tdSource2 != null && tdTarget.CanBeAssignedFrom( tdSource2, null )) { var opNew = SingleAssignmentOperator.New( call.DebugInfo, call.FirstResult, exSrc ); call.SubstituteWithOperator( opNew, Operator.SubstitutionFlags.Default ); nc.MarkAsModified(); } } } //--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--// //--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--// //--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--// [CompilationSteps.PhaseFilter( typeof(Phases.HighLevelTransformations) )] [CompilationSteps.CallToWellKnownMethodHandler( "TypeImpl_GetTypeFromHandle" )] private static void Handle_TypeImpl_GetTypeFromHandle( PhaseExecution.NotificationContext nc ) { CallOperator op = nc.GetOperatorAndThrowIfNotCall(); TypeSystemForCodeTransformation ts = nc.TypeSystem; ControlFlowGraphStateForCodeTransformation cfg = nc.CurrentCFG; ConstantExpression exTd = op.SecondArgument as ConstantExpression; if(exTd == null) { return; } DataManager.ObjectDescriptor odRuntimeTypeHandle = exTd.Value as DataManager.ObjectDescriptor; if(odRuntimeTypeHandle == null) { return; } DataManager.ObjectDescriptor odVTable = odRuntimeTypeHandle.Get( (InstanceFieldRepresentation)ts.WellKnownFields.RuntimeTypeHandleImpl_m_value ) as DataManager.ObjectDescriptor; if(odVTable == null) { return; } op.SubstituteWithOperator( SingleAssignmentOperator.New( op.DebugInfo, op.FirstResult, ts.CreateConstantForType( (VTable)odVTable.Source ) ), Operator.SubstitutionFlags.Default ); nc.MarkAsModified(); } //--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--// //--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--// //--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--// [CompilationSteps.PhaseFilter( typeof(Phases.HighLevelTransformations) )] [CompilationSteps.CallToWellKnownMethodHandler( "ActivatorImpl_CreateInstanceInner" )] private static void Handle_ActivatorImpl_CreateInstanceInner( PhaseExecution.NotificationContext nc ) { CallOperator op = nc.GetOperatorAndThrowIfNotCall(); TypeSystemForCodeTransformation ts = nc.TypeSystem; ControlFlowGraphStateForCodeTransformation cfg = nc.CurrentCFG; // // We need to substitute the sequence: // // opDef : $Temp_1[0](System.Type) = callStatic StaticMethodRepresentation(System.Type System.Type::GetTypeFromHandle(System.RuntimeTypeHandle))( , $Const(System.RuntimeTypeHandle $Object(System.RuntimeTypeHandle)) ) // op : $Temp_2[1](object) = callStatic StaticMethodRepresentation(object System.Activator::CreateInstanceInner(System.Type))( , $Temp_1[0](System.Type) ) // opUse : (T) = $Temp_2[1](object) cast as T // // with the sequence: // // (T) = new T; // call (T)T() // while(true) { SingleAssignmentOperator opDef; VTable vTable = InferVirtualTableFromConstantTypeParameter( ts, cfg, op.SecondArgument, out opDef ); if(vTable == null) { break; } TypeRepresentation tdTarget = vTable.TypeInfo; CastOperator opUse = cfg.FindSingleUse( op.FirstResult ) as CastOperator; if(opUse == null) { break; } VariableExpression varTarget = opUse.FirstResult; if(varTarget.Type.CanBeAssignedFrom( tdTarget, null ) == false) { break; } ConstructorMethodRepresentation mdTarget = tdTarget.FindDefaultConstructor(); if(mdTarget == null) { break; } op.AddOperatorBefore( ObjectAllocationOperator.New( op.DebugInfo, tdTarget, varTarget ) ); op.AddOperatorBefore( InstanceCallOperator .New( op.DebugInfo, CallOperator.CallKind.Direct, mdTarget, new Expression[] { varTarget }, false) ); if(cfg.FindSingleUse( opDef.FirstResult ) == op) { opDef.Delete(); } op .Delete(); opUse.Delete(); nc.StopScan(); return; } throw TypeConsistencyErrorException.Create( "INTERNAL ERROR: Unrecognized use of {0}", op.TargetMethod ); } //--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--// //--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--// //--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--// public static VTable InferVirtualTableFromConstantTypeParameter( TypeSystemForCodeTransformation ts , ControlFlowGraphStateForCodeTransformation cfg , Expression ex , out SingleAssignmentOperator opDef ) { opDef = cfg.FindSingleDefinition( ex ) as SingleAssignmentOperator; if(opDef == null) { return null; } var exType = opDef.FirstArgument as ConstantExpression; if(exType == null) { return null; } var dt = exType.Value as TypeSystemForCodeTransformation.DelayedType; if(dt != null) { return dt.VTable; } return null; } } } ================================================ FILE: Zelig/Zelig/CompileTime/CodeGenerator/CodeTransformation/CompilationSteps/PhaseDrivers/ApplyClassExtensions.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // namespace Microsoft.Zelig.CodeGeneration.IR.CompilationSteps { using System; using System.Collections.Generic; using Microsoft.Zelig.Runtime.TypeSystem; internal sealed class ApplyClassExtensions : Transformations.ScanTypeSystem { // // State // private Transformations.ReverseIndexTypeSystem m_reverseIndex; private List< Transformations.PerformClassExtension.Duplicate > m_duplicates; private bool m_fChanged; // // Constructor Methods // internal ApplyClassExtensions( TypeSystemForCodeTransformation typeSystem ) : base( typeSystem, typeof(ApplyClassExtensions) ) { m_fChanged = false; } // // Helper Methods // internal static bool Hack_MirrorGenericInstantiations( TypeSystemForCodeTransformation typeSystem ) { bool fChanged = false; typeSystem.BuildGenericInstantiationTables(); foreach(TypeRepresentation td in typeSystem.Types.ToArray()) { CustomAttributeRepresentation ca = td.FindCustomAttribute( typeSystem.WellKnownTypes.Microsoft_Zelig_Runtime_ExtendClassAttribute ); if(ca != null) { object objTarget = ca.FixedArgsValues[0]; TypeRepresentation tdTarget = objTarget as TypeRepresentation; object obj = ca.GetNamedArg( "PlatformVersionFilter" ); if(obj != null) { uint filter = (uint)obj; if(( filter & typeSystem.PlatformAbstraction.PlatformVersion ) != typeSystem.PlatformAbstraction.PlatformVersion) { // This type is not an allowed extension for the current platform continue; } } if(tdTarget == null) { tdTarget = typeSystem.GetWellKnownTypeNoThrow( objTarget as string ); } if(tdTarget == null) { throw TypeConsistencyErrorException.Create( "Missing target class to extend: {0}", objTarget ); } if(td.IsOpenType == false && tdTarget.IsOpenType) { tdTarget = typeSystem.CreateInstantiationOfGenericTemplate( tdTarget, td.GenericParameters ); } if(tdTarget.IsOpenType) { List< TypeRepresentation > lstTdTarget; if(typeSystem.GenericTypeInstantiations.TryGetValue( tdTarget, out lstTdTarget )) { List< TypeRepresentation > lstTd; typeSystem.GenericTypeInstantiations.TryGetValue( td, out lstTd ); foreach(var td2 in lstTdTarget) { var tdNew = typeSystem.CreateInstantiationOfGenericTemplate( td, td2.GenericParameters ); if(td != tdNew && (lstTd == null || lstTd.Contains( tdNew ) == false)) { fChanged = true; } } } } else { fChanged |= Hack_ProcessType( typeSystem, td, tdTarget ); } } } return fChanged; } private static bool Hack_ProcessType( TypeSystemForCodeTransformation typeSystem , TypeRepresentation td , TypeRepresentation tdTarget ) { bool fChanged = false; var ht = IR.Transformations.PerformClassExtension.Hack_GetSubstitutionTable( typeSystem, td, tdTarget ); foreach(var mdOverriding in ht.Keys) { if(mdOverriding.IsOpenMethod) { var mdOverridden = ht[mdOverriding]; List< MethodRepresentation > lstMdOverridden; if(typeSystem.GenericMethodInstantiations.TryGetValue( mdOverridden, out lstMdOverridden )) { List< MethodRepresentation > lstMdOverriding; typeSystem.GenericMethodInstantiations.TryGetValue( mdOverriding, out lstMdOverriding ); foreach(var md in lstMdOverridden) { if(md.IsOpenMethod == false) { var mdNew = typeSystem.CreateInstantiationOfGenericTemplate( mdOverriding, md.GenericParameters ); if(lstMdOverriding == null || lstMdOverriding.Contains( mdNew ) == false) { fChanged = true; } } } } } } return fChanged; } //--// internal void Run() { m_reverseIndex = new Transformations.ReverseIndexTypeSystem( m_typeSystem ); m_duplicates = new List< Transformations.PerformClassExtension.Duplicate >(); // // We need to deal with Generic Types and Methods. // // For generic types, we need to ensure we have as many specialization of the overridding type as those of the overridden one. // // For generic methods, we need to ensure that the overriding generic method is instantiated as many times as the overridden one. // // // To speed up the processing of mapping from the overridding entities to the overridden ones, // we build a reverse index of the whole type system. // using(new Transformations.ExecutionTiming( "ReverseIndexTypeSystem" )) { m_reverseIndex.ProcessTypeSystem(); } // // Process types that are generic parameters types first // var genericParametersTypes = new List(); foreach(TypeRepresentation td in m_typeSystem.Types) { foreach(var parameter in td.GenericParameters) { if(parameter is DelayedMethodParameterTypeRepresentation || parameter is DelayedTypeParameterTypeRepresentation) { continue; } genericParametersTypes.Add( parameter ); } } foreach(TypeRepresentation td in genericParametersTypes) { ProcessType( td ); } // // Process all other types // foreach(TypeRepresentation td in m_typeSystem.Types.ToArray()) { ProcessType( td ); } if(m_fChanged) { if(m_duplicates.Count > 0) { Transformations.PerformClassExtension pfe = new Transformations.PerformClassExtension( m_typeSystem, m_reverseIndex, m_duplicates ); pfe.ProcessDuplicates(); } // // We need to rebuild all the hash tables. // TypeSystemForCodeTransformation typeSystem = m_typeSystem; Transform( ref typeSystem ); typeSystem.RefreshHashCodesAfterTypeSystemRemapping(); } } //--// protected override bool ShouldRefreshHashCodes() { return true; } //--// private void ProcessType( TypeRepresentation td ) { if(m_typeSystem.ReachabilitySet.IsProhibited( td ) == false) { CustomAttributeRepresentation ca = td.FindCustomAttribute( m_typeSystem.WellKnownTypes.Microsoft_Zelig_Runtime_ExtendClassAttribute ); if(ca != null) { object objTarget = ca.FixedArgsValues[0]; TypeRepresentation tdTarget = objTarget as TypeRepresentation; bool fNoConstructors = false; object obj; obj = ca.GetNamedArg( "PlatformVersionFilter" ); if(obj != null) { uint filter = (uint)obj; if((filter & m_typeSystem.PlatformAbstraction.PlatformVersion) != m_typeSystem.PlatformAbstraction.PlatformVersion) { // This type is not an allowed extension for the current platform return; } } if(tdTarget == null) { tdTarget = m_typeSystem.GetWellKnownTypeNoThrow( objTarget as string ); } if(tdTarget == null) { throw TypeConsistencyErrorException.Create( "Missing target class to extend: {0}", objTarget ); } if(td.IsOpenType == false && tdTarget.IsOpenType) { List< TypeRepresentation > lstTdTarget; if(m_typeSystem.GenericTypeInstantiations.TryGetValue( tdTarget, out lstTdTarget ) == false) { throw TypeConsistencyErrorException.Create( "Found mismatch between instantiation of class extension and target class: {0} not compatible with {1}", td, tdTarget ); } tdTarget = null; foreach(var tdTarget2 in lstTdTarget) { if(tdTarget2.IsOpenType == false && ArrayUtility.ArrayEqualsNotNull( td.GenericParameters, tdTarget2.GenericParameters, 0 )) { tdTarget = tdTarget2; } } if(tdTarget == null) { throw TypeConsistencyErrorException.Create( "Missing target class to extend: {0}", objTarget ); } } obj = ca.GetNamedArg( "NoConstructors" ); if(obj != null) { fNoConstructors = (bool)obj; } obj = ca.GetNamedArg( "ProcessAfter" ); if(obj != null) { TypeRepresentation tdPre = (TypeRepresentation)obj; if(tdPre.HasCustomAttribute( m_typeSystem.WellKnownTypes.Microsoft_Zelig_Runtime_ExtendClassAttribute )) { ProcessType( tdPre ); } } TypeRepresentation tdExtends = td.Extends; if(tdExtends != null) { ProcessType( tdExtends ); } // // HACK: Generic type extension is handled at the end of meta data import. // if(td.IsOpenType || tdTarget.IsOpenType) { return; } using(new Transformations.ExecutionTiming( "PerformClassExtension from {0} to {1}", td, tdTarget )) { var pfe = new Transformations.PerformClassExtension( m_typeSystem, m_reverseIndex, m_duplicates, td, tdTarget, fNoConstructors ); pfe.Execute(); } m_fChanged = true; } } } } } ================================================ FILE: Zelig/Zelig/CompileTime/CodeGenerator/CodeTransformation/CompilationSteps/PhaseDrivers/CallGraph.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // namespace Microsoft.Zelig.CodeGeneration.IR.CompilationSteps { using System; using System.Collections.Generic; using System.Runtime.CompilerServices; using Microsoft.Zelig.Runtime.TypeSystem; public sealed class CallGraph { public delegate bool ShouldIncludeInClosureDelegate( MethodRepresentation md ); // // State // private TypeSystemForCodeTransformation m_typeSystem; private GrowOnlyHashTable< MethodRepresentation, List< MethodRepresentation > > m_methods; private GrowOnlyHashTable< MethodRepresentation, List< MethodRepresentation > > m_methodsThatRequireStaticConstructors; private GrowOnlySet < MethodRepresentation > m_methodsUsedInDelegates; // // Constructor Methods // public CallGraph( TypeSystemForCodeTransformation typeSystem ) { m_typeSystem = typeSystem; m_methods = HashTableFactory.NewWithReferenceEquality< MethodRepresentation, List< MethodRepresentation > >(); m_methodsThatRequireStaticConstructors = HashTableFactory.NewWithReferenceEquality< MethodRepresentation, List< MethodRepresentation > >(); m_methodsUsedInDelegates = SetFactory .NewWithReferenceEquality< MethodRepresentation >(); //--// typeSystem.EnumerateFlowGraphs( delegate ( ControlFlowGraphStateForCodeTransformation cfg ) { var tdCodePointer = m_typeSystem.WellKnownTypes.Microsoft_Zelig_Runtime_TypeSystem_CodePointer; foreach(Operator op in cfg.DataFlow_SpanningTree_Operators) { MethodRepresentationOperator opMd = op as MethodRepresentationOperator; if(opMd != null) { m_methodsUsedInDelegates.Insert( opMd.Method ); } FieldOperator opFd = op as FieldOperator; if(opFd != null) { FieldRepresentation fd = opFd.Field; InstanceFieldRepresentation fdI = fd as InstanceFieldRepresentation; if(fdI != null) { fd = fdI.ImplementationOf; } if(fd is StaticFieldRepresentation) { MethodRepresentation mdCCtor = fd.OwnerType.FindDefaultStaticConstructor(); if(mdCCtor != null) { MethodRepresentation mdFrom = cfg.Method; if(mdFrom != mdCCtor) { HashTableWithListFactory.AddUnique( m_methodsThatRequireStaticConstructors, mdFrom, mdCCtor ); } } } } foreach(var ex in op.Arguments) { var exConst = ex as ConstantExpression; if(exConst != null && exConst.Type == tdCodePointer) { var od = (DataManager.ObjectDescriptor)exConst.Value; if(od != null) { var cp = (CodePointer)od.Source; var md = m_typeSystem.DataManagerInstance.GetCodePointerFromUniqueID( cp.Target ) as MethodRepresentation; if(md != null) { m_methodsUsedInDelegates.Insert( md ); } } } } } } ); typeSystem.EnumerateMethods( delegate ( MethodRepresentation md ) { Analyze( md ); } ); } // // Helper Methods // public GrowOnlySet< MethodRepresentation > ComputeClosure( MethodRepresentation md , ShouldIncludeInClosureDelegate dlg ) { GrowOnlySet< MethodRepresentation > set = SetFactory.NewWithReferenceEquality< MethodRepresentation >(); set.Insert( md ); ExpandClosure( set, md, dlg ); return set; } private void ExpandClosure( GrowOnlySet< MethodRepresentation > set , MethodRepresentation md , ShouldIncludeInClosureDelegate dlg ) { ExpandClosure( set, md, dlg, m_methods ); ExpandClosure( set, md, dlg, m_methodsThatRequireStaticConstructors ); } private void ExpandClosure( GrowOnlySet< MethodRepresentation > set , MethodRepresentation md , ShouldIncludeInClosureDelegate dlg , GrowOnlyHashTable< MethodRepresentation, List< MethodRepresentation > > ht ) { List< MethodRepresentation > lst; if(ht.TryGetValue( md, out lst )) { foreach(MethodRepresentation mdNext in lst) { if(set.Insert( mdNext ) == false) { if(dlg != null && dlg( mdNext ) == false) { continue; } ExpandClosure( set, mdNext, dlg ); } } } } //--// private void Analyze( MethodRepresentation mdFrom ) { List< MethodRepresentation > lst; if(HashTableWithListFactory.Create( m_methods, mdFrom, out lst )) { // // Already analyzed. // return; } ControlFlowGraphStateForCodeTransformation cfgFrom = TypeSystemForCodeTransformation.GetCodeForMethod( mdFrom ); if(cfgFrom != null) { foreach(var call in cfgFrom.FilterOperators< CallOperator >()) { MethodRepresentation mdTo = call.TargetMethod; switch(call.CallType) { case CallOperator.CallKind.Direct: case CallOperator.CallKind.Overridden: case CallOperator.CallKind.OverriddenNoCheck: AddEdge( mdFrom, mdTo ); break; case CallOperator.CallKind.Virtual: case CallOperator.CallKind.Indirect: AddVirtualEdge( mdFrom, (VirtualMethodRepresentation)mdTo ); break; default: throw TypeConsistencyErrorException.Create( "Unsupported call '{0}' found in '{1}'", call, cfgFrom ); } TypeRepresentation td = mdTo.OwnerType; if(td.IsAbstract == false && td.IsSubClassOf( m_typeSystem.WellKnownTypes.System_Delegate, null )) { switch(mdTo.Name) { case "Invoke": foreach(MethodRepresentation mdDlg in m_methodsUsedInDelegates) { if(mdDlg.MatchSignature( mdTo, null )) { AddEdge( mdFrom, mdDlg ); } } break; } } } } } private void AddVirtualEdge( MethodRepresentation mdFrom , VirtualMethodRepresentation mdTo ) { // // Include all the overrides for this method in all the subclasses already reached by the closure computation. // int index = mdTo.FindVirtualTableIndex(); TypeRepresentation td = mdTo.OwnerType; AddOverrides( mdFrom, td, index ); //--// // // The method belongs to an interface, we have to include all the implementations in all the touched types. // if(td is InterfaceTypeRepresentation) { InterfaceTypeRepresentation itf = (InterfaceTypeRepresentation)td; int itfIndex = mdTo.FindInterfaceTableIndex(); foreach(TypeRepresentation td2 in m_typeSystem.InterfaceImplementors[itf]) { MethodRepresentation mdOverride = td2.FindInterfaceTable( itf )[itfIndex]; AddEdge( mdFrom, mdOverride ); } } } private void AddOverrides( MethodRepresentation mdFrom , TypeRepresentation td , int index ) { List< TypeRepresentation > lst; if(m_typeSystem.DirectDescendant.TryGetValue( td, out lst )) { foreach(TypeRepresentation td2 in lst) { AddEdge( mdFrom, td2.MethodTable[index] ); AddOverrides( mdFrom, td2, index ); } } } private void AddEdge( MethodRepresentation from , MethodRepresentation to ) { HashTableWithListFactory.AddUnique( m_methods, from, to ); Analyze( to ); } // // Access Methods // public GrowOnlyHashTable< MethodRepresentation, List< MethodRepresentation > > Methods { get { return m_methods; } } public GrowOnlyHashTable< MethodRepresentation, List< MethodRepresentation > > MethodsThatRequireStaticConstructors { get { return m_methodsThatRequireStaticConstructors; } } } } ================================================ FILE: Zelig/Zelig/CompileTime/CodeGenerator/CodeTransformation/CompilationSteps/PhaseDrivers/CallsDatabase.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // namespace Microsoft.Zelig.CodeGeneration.IR.CompilationSteps { using System; using System.Collections.Generic; using System.Runtime.CompilerServices; using Microsoft.Zelig.Runtime.TypeSystem; public interface IInlineOptions { bool HonorInlineAttribute { get; } bool EnableAutoInlining { get; } bool InjectPrologAndEpilog { get; } } public sealed class CallsDataBase { internal class Entry { // // State // int m_version; ControlFlowGraphStateForCodeTransformation m_cfg; ControlFlowGraphStateForCodeTransformation m_clonedCFG; List< CallOperator > m_callsFromThisMethod; List< CallOperator > m_callsToThisMethod; IInlineOptions m_InlineOptions; // // Constructor Methods // internal Entry( ControlFlowGraphStateForCodeTransformation cfg ) { m_cfg = cfg; m_version = -1; m_callsFromThisMethod = new List< CallOperator >(); m_callsToThisMethod = new List< CallOperator >(); m_InlineOptions = cfg.TypeSystem.GetEnvironmentService( ); } // // Helper Methods // internal void Reset() { m_callsFromThisMethod.Clear(); m_callsToThisMethod .Clear(); } internal void AddCallFromThisMethod( CallOperator call ) { lock(this) { m_callsFromThisMethod.Add( call ); } } internal void AddCallToThisMethod( CallOperator call ) { lock(this) { m_callsToThisMethod.Add( call ); } } internal void AnalyzeInlining() { if(m_version != m_cfg.Version) { m_version = m_cfg.Version; bool fInline = false; MethodRepresentation md = m_cfg.Method; if(md.HasBuildTimeFlag( MethodRepresentation.BuildTimeAttributes.NoInline )) { fInline = false; } else if(md.HasBuildTimeFlag( MethodRepresentation.BuildTimeAttributes.Inline )) { if( m_InlineOptions == null || m_InlineOptions.HonorInlineAttribute ) fInline = true; } else if( m_InlineOptions == null || m_InlineOptions.EnableAutoInlining ) { bool fCallToConstructor = false; int iCall = 0; int iGetter = 0; int iSetter = 0; int iOther = 0; var set = SetFactory.NewWithReferenceEquality< BasicBlock >(); var queue = new Queue < BasicBlock >(); var bbStart = m_cfg.NormalizedEntryBasicBlock; var bbEnd = m_cfg.NormalizedExitBasicBlock; set .Insert ( bbStart ); queue.Enqueue( bbStart ); while(queue.Count > 0) { var bb = queue.Dequeue(); foreach(var edge in bb.Successors) { var bbNext = edge.Successor; if(bbNext != bbEnd && set.Insert( bbNext ) == false) { queue.Enqueue( bbNext ); } } foreach(Operator op in bb.Operators) { if(op is CallOperator) { CallOperator call = (CallOperator)op; if(call.TargetMethod is ConstructorMethodRepresentation) { fCallToConstructor = true; } else { iCall++; } } else if(op is LoadFieldOperator) { iGetter++; } else if(op is StoreFieldOperator) { iSetter++; } else if(op is NopOperator || op is UnconditionalControlOperator || op is AbstractAssignmentOperator || op is ReturnControlOperator ) { // Ignore them. } else { iOther++; } } } if(!fCallToConstructor && iGetter == 0 && iSetter == 0 && iOther == 0) { fInline = true; // Noop method. } else if(fCallToConstructor && iGetter == 0 && iSetter == 0 && iOther == 0) { fInline = true; // Empty constructor. } else if(!fCallToConstructor && iGetter == 1 && iSetter == 0 && iOther < 2) { fInline = true; // Simple getter. } else if(!fCallToConstructor && iGetter == 0 && iSetter == 1 && iOther == 0) { fInline = true; // Simple setter. } else if(!fCallToConstructor && iGetter == 0 && iSetter == 0 && iCall == 0 && iOther < 4) { fInline = true; // Simple method with no calls. } else { fInline = false; } } if( fInline) { m_clonedCFG = m_cfg.Clone( null ); } else { m_clonedCFG = null; } } } internal void EnsureCloned() { if(m_clonedCFG == null) { m_clonedCFG = m_cfg.Clone( null ); } } internal void QueueInlining( GrowOnlySet< ControlFlowGraphStateForCodeTransformation > touched , GrowOnlyHashTable< ControlFlowGraphStateForCodeTransformation, List< CallOperator > > workList ) { if(m_clonedCFG != null) { for(int pos = m_callsToThisMethod.Count; --pos >= 0; ) { bool fRemove = false; CallOperator call = m_callsToThisMethod[pos]; while(true) { BasicBlock bb = call.BasicBlock; if(bb == null) { // // Dead operator, just remove it. // fRemove = true; break; } var cfg = (ControlFlowGraphStateForCodeTransformation)bb.Owner; if(cfg == m_cfg) { // // Can't self-inline. // break; } // // Detect inlining loops and stop them. // var an = call.GetAnnotation< InliningPathAnnotation >(); if(an != null) { if(ArrayUtility.FindInNotNullArray( an.Path, m_clonedCFG.Method ) >= 0) { break; } } var callType = call.CallType; if(callType == CallOperator.CallKind.Virtual || callType == CallOperator.CallKind.Indirect ) { break; } var cfgInlineSite = (ControlFlowGraphStateForCodeTransformation)call.BasicBlock.Owner; touched.Insert( cfgInlineSite ); HashTableWithListFactory.AddUnique( workList, cfgInlineSite, call ); fRemove = true; break; } if(fRemove) { m_callsToThisMethod.RemoveAt( pos ); } } } } // // Access Methods // internal ControlFlowGraphStateForCodeTransformation Cfg { get { return m_cfg; } } internal ControlFlowGraphStateForCodeTransformation ClonedCfg { get { return m_clonedCFG; } } internal List< CallOperator > CallFromThisMethod { get { return m_callsFromThisMethod; } } internal List< CallOperator > CallToThisMethod { get { return m_callsToThisMethod; } } } // // State // private GrowOnlyHashTable< ControlFlowGraphStateForCodeTransformation, Entry > m_entries; private GrowOnlySet < CallOperator > m_forcedInlines; // // Constructor Methods // public CallsDataBase() { m_entries = HashTableFactory.NewWithReferenceEquality< ControlFlowGraphStateForCodeTransformation, Entry >(); m_forcedInlines = SetFactory .NewWithReferenceEquality< CallOperator >(); } // // Helper Methods // public void RegisterCallSite( CallOperator call ) { var cfgFrom = (ControlFlowGraphStateForCodeTransformation) call.BasicBlock.Owner; var cfgTo = TypeSystemForCodeTransformation.GetCodeForMethod( call.TargetMethod ); Entry enFrom = GetEntry( cfgFrom, true ); enFrom.AddCallFromThisMethod( call ); if(cfgTo != null) { Entry enTo = GetEntry( cfgTo, true ); enTo.AddCallToThisMethod( call ); } } public void QueueForForcedInlining( CallOperator call ) { lock(TypeSystemForCodeTransformation.Lock) // It's called from multiple threads during parallel phase executions. { m_forcedInlines.Insert( call ); } } public void ClearCallSites() { m_entries.Clear(); } public void ResetCallSites() { foreach(Entry en in m_entries.Values) { en.Reset(); } } public List< CallOperator > CallsToMethod( MethodRepresentation md ) { var cfg = TypeSystemForCodeTransformation.GetCodeForMethod( md ); Entry en = GetEntry( cfg, false ); return (en != null) ? en.CallToThisMethod : null; } public List< CallOperator > CallsFromMethod( MethodRepresentation md ) { var cfg = TypeSystemForCodeTransformation.GetCodeForMethod( md ); Entry en = GetEntry( cfg, false ); return (en != null) ? en.CallFromThisMethod : null; } //--// public CallsDataBase Analyze( TypeSystemForCodeTransformation typeSystem ) { ResetCallSites(); ParallelTransformationsHandler.EnumerateFlowGraphs( typeSystem, delegate( ControlFlowGraphStateForCodeTransformation cfg ) { foreach(var call in cfg.FilterOperators< CallOperator >()) { RegisterCallSite( call ); } } ); return this; } public void AnalyzeForInlining() { foreach(Entry en in m_entries.Values) { en.AnalyzeInlining(); } } public GrowOnlySet< ControlFlowGraphStateForCodeTransformation > ExecuteInlining( TypeSystemForCodeTransformation typeSystem ) { var workList = HashTableFactory.NewWithReferenceEquality< ControlFlowGraphStateForCodeTransformation, List< CallOperator > >(); var touched = SetFactory .NewWithReferenceEquality< ControlFlowGraphStateForCodeTransformation >(); var touched2 = touched.CloneSettings(); while(true) { workList.Clear(); touched2.Clear(); foreach(Entry en in m_entries.Values) { en.QueueInlining( touched2, workList ); } foreach(CallOperator call in m_forcedInlines) { if(!call.IsDetached) { var cfgInlineSite = (ControlFlowGraphStateForCodeTransformation)call.BasicBlock.Owner; var cfgTarget = TypeSystemForCodeTransformation.GetCodeForMethod( call.TargetMethod ); touched2.Insert( cfgInlineSite ); var en = GetEntry( cfgTarget, true ); en.EnsureCloned(); HashTableWithListFactory.AddUnique( workList, cfgInlineSite, call ); } } if(workList.Count == 0) { break; } //--// var lockList = HashTableFactory.NewWithReferenceEquality< ControlFlowGraphStateForCodeTransformation, IDisposable >(); foreach(var cfg in workList.Keys) { foreach(var call in workList[cfg]) { var cfgTarget = TypeSystemForCodeTransformation.GetCodeForMethod( call.TargetMethod ); Entry en; m_entries.TryGetValue( cfgTarget, out en ); var cfgCloned = en.ClonedCfg; if(lockList.ContainsKey( cfgCloned ) == false) { var bbEntry = cfgCloned.NormalizedEntryBasicBlock; var bbExit = cfgCloned.NormalizedExitBasicBlock; lockList[cfgTarget] = cfgCloned.LockFlowInformation(); } } } ParallelTransformationsHandler.EnumerateFlowGraphs( typeSystem, delegate( ControlFlowGraphStateForCodeTransformation cfg ) { List< CallOperator > calls; bool fGot = false; if(workList.TryGetValue( cfg, out calls )) { foreach(var call in calls) { var cfgTarget = TypeSystemForCodeTransformation.GetCodeForMethod( call.TargetMethod ); Entry en; m_entries.TryGetValue( cfgTarget, out en ); cfg.TraceToFile( "InlineCall" ); using(ControlFlowGraphState.AddExceptionToThreadMethodLock( call.TargetMethod )) { Transformations.InlineCall.Execute( call, en.ClonedCfg, null ); } cfg.TraceToFile( "InlineCall-Post" ); fGot = true; } if(fGot) { Transformations.CommonMethodRedundancyElimination.Execute( cfg ); cfg.DropDeadVariables(); } } } ); foreach(var disp in lockList.Values) { disp.Dispose(); } touched.Merge( touched2 ); } return touched; } //--// Entry GetEntry( ControlFlowGraphStateForCodeTransformation cfg , bool fAllocate ) { lock(TypeSystemForCodeTransformation.Lock) // It's called from multiple threads during parallel phase executions. { Entry entry; if(m_entries.TryGetValue( cfg, out entry ) == false && fAllocate) { entry = new Entry( cfg ); m_entries[cfg] = entry; } return entry; } } } } ================================================ FILE: Zelig/Zelig/CompileTime/CodeGenerator/CodeTransformation/CompilationSteps/PhaseDrivers/ComputeCallsClosure.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // //#define COMPUTECALLSCLOSURE_FORCE_SINGLE_THREADED namespace Microsoft.Zelig.CodeGeneration.IR.CompilationSteps { using System; using System.Collections.Generic; using Microsoft.Zelig.Runtime.TypeSystem; public interface ICallClosureComputationTarget { void ExpandClosure( ComputeCallsClosure.Context host ); } public sealed class ComputeCallsClosure { public delegate void Notification( Context host, Operator op ); public class Context { // // State // private readonly ComputeCallsClosure m_owner; private readonly TypeSystem.Reachability m_reachabilitySet; // // Constructor Methods // internal Context( ComputeCallsClosure owner , TypeSystem.Reachability reachabilitySet ) { m_owner = owner; m_reachabilitySet = reachabilitySet; } // // Helper Methods // internal void ProcessMethod( MethodRepresentation md ) { CoverObject( md ); ControlFlowGraphStateForCodeTransformation cfg = TypeSystemForCodeTransformation.GetCodeForMethod( md ); if(cfg != null) { Transformations.ScanCodeWithCallback.Execute( m_owner.m_typeSystem, this, cfg, delegate( Operator op, object target ) { if(target != null) { MethodRepresentation mdTarget = target as MethodRepresentation; if(mdTarget != null) { m_owner.QueueMethodForProcessing( mdTarget ); } CoverObject( target ); if(target is Operator) { Operator opTarget = (Operator)target; Type type = opTarget.GetType(); while(type != null) { List< Notification > lst; if(m_owner.m_delegation.TryGetValue( type, out lst )) { foreach(Notification dlg in lst) { dlg( this, opTarget ); } } type = type.BaseType; } CallOperator call = opTarget as CallOperator; if(call != null) { m_owner.m_callsDatabase.RegisterCallSite( call ); } var tdCodePointer = m_owner.m_typeSystem.WellKnownTypes.Microsoft_Zelig_Runtime_TypeSystem_CodePointer; foreach(var ex in opTarget.Arguments) { var exConst = ex as ConstantExpression; if(exConst != null && exConst.Type == tdCodePointer) { var od = (DataManager.ObjectDescriptor)exConst.Value; if(od != null) { var cp = (CodePointer)od.Source; var mdDelegate = m_owner.m_typeSystem.DataManagerInstance.GetCodePointerFromUniqueID( cp.Target ); CoverObject( mdDelegate ); } } } } } return Transformations.ScanCodeWithCallback.CallbackResult.Proceed; } ); } } public void CoverObject( object obj ) { if(obj == null) return; if(obj is MethodRepresentation) { CoverMethod( (MethodRepresentation)obj ); } else if(obj is FieldRepresentation) { CoverField( (FieldRepresentation)obj ); } else if(obj is TypeRepresentation) { CoverType( (TypeRepresentation)obj ); } else if(obj is AssemblyRepresentation) { CoverAssembly( (AssemblyRepresentation)obj ); } else if(obj is CustomAttributeRepresentation) { CoverCustomAttribute( (CustomAttributeRepresentation)obj ); } else if(obj is CustomAttributeAssociationRepresentation) { CoverCustomAttributeAssociation( (CustomAttributeAssociationRepresentation)obj ); } else if(obj is ICallClosureComputationTarget) { ICallClosureComputationTarget itf = (ICallClosureComputationTarget)obj; itf.ExpandClosure( this ); } else { m_reachabilitySet.ExpandPending( obj ); } } private void CoverReflectionType( object obj ) { TypeRepresentation td = m_owner.m_typeSystem.TryGetTypeRepresentationFromType( obj.GetType() ); if(td != null) { CoverType( td ); } } private void CoverAssembly( AssemblyRepresentation asml ) { m_reachabilitySet.ExpandPending( asml ); } private void CoverType( TypeRepresentation td ) { while(td != null) { if(m_reachabilitySet.ExpandPending( td )) { break; } CoverReflectionType( td ); CoverAssembly( td.Owner ); CoverType( td.Extends ); CoverType( td.EnclosingClass ); // // If a generic type, include the context. // TypeRepresentation.GenericContext gc = td.Generic; if(gc != null) { CoverType( gc.Template ); foreach(TypeRepresentation td2 in gc.Parameters) { CoverType( td2 ); } GenericParameterDefinition[] parametersDefinition = gc.ParametersDefinition; if(parametersDefinition != null) { for(int i = 0; i < parametersDefinition.Length; i++) { foreach(TypeRepresentation constraint in parametersDefinition[i].Constraints) { CoverType( constraint ); } } } } // // These are weird objects, because they actually contain a use of themselves in their definition. // We want to keep the fields alive, so that the size computation doesn't generate the wrong values. // if(td is ScalarTypeRepresentation) { foreach(FieldRepresentation fd in td.Fields) { if(fd is InstanceFieldRepresentation) { CoverField( fd ); } } } if(td is ArrayReferenceTypeRepresentation) { // // Keep alive also the managed pointer to the elements of the array, it will be used later. // CoverType( m_owner.m_typeSystem.GetManagedPointerToType( td.ContainedType ) ); } // // For a non-pointer type, keep alive any associated pointer type. // if(!(td is PointerTypeRepresentation)) { foreach(TypeRepresentation td2 in m_owner.m_typeSystem.Types) { PointerTypeRepresentation ptr = td2 as PointerTypeRepresentation; if(ptr != null && ptr.ContainedType == td) { CoverType( ptr ); } } } // // Look for all the fields, if they have an "AssumeReferenced" attribute, force them to be included. // { TypeRepresentation tdAttrib = m_owner.m_typeSystem.WellKnownTypes.Microsoft_Zelig_Runtime_TypeSystem_AssumeReferencedAttribute; foreach(FieldRepresentation fd in td.Fields) { if(fd.HasCustomAttribute( tdAttrib )) { CoverField( fd ); } } } // // Look for all the methods that are marked as exception handlers and include them. // { var heh = m_owner.m_typeSystem.HardwareExceptionHandlers; foreach(MethodRepresentation md in td.Methods) { CustomAttributeRepresentation ca; if(heh.TryGetValue( md, out ca )) { CoverMethod ( md ); CoverCustomAttribute( ca ); } } } // // Look for all the methods that are marked as debugger handlers and include them. // { var dhh = m_owner.m_typeSystem.DebuggerHookHandlers; foreach(MethodRepresentation md in td.Methods) { CustomAttributeRepresentation ca; if(dhh.TryGetValue( md, out ca )) { CoverMethod ( md ); CoverCustomAttribute( ca ); } } } td = td.ContainedType; } } private void CoverField( FieldRepresentation fd ) { if(fd == null) return; if(m_reachabilitySet.ExpandPending( fd )) { return; } CoverReflectionType( fd ); CoverType( fd.OwnerType ); CoverType( fd.FieldType ); if(fd is StaticFieldRepresentation) { StaticFieldRepresentation fdS = (StaticFieldRepresentation)fd; CoverField( fdS.ImplementedBy ); CoverStaticConstructor( fdS ); } if(fd is InstanceFieldRepresentation) { InstanceFieldRepresentation fdI = (InstanceFieldRepresentation)fd; CoverField( fdI.ImplementationOf ); CoverStaticConstructor( fdI.ImplementationOf ); } } private void CoverStaticConstructor( StaticFieldRepresentation fd ) { if(fd == null) return; StaticConstructorMethodRepresentation md = fd.OwnerType.FindDefaultStaticConstructor(); if(md != null) { CoverMethod( md ); CoverMethod( m_owner.m_typeSystem.WellKnownMethods.TypeSystemManager_InvokeStaticConstructors ); } } private void CoverMethod( MethodRepresentation md ) { if(md == null) return; if(m_reachabilitySet.ExpandPending( md )) { return; } CoverReflectionType( md ); m_owner.QueueMethodForProcessing( md ); // // If a generic method, include the context. // MethodRepresentation.GenericContext gc = md.Generic; if(gc != null) { CoverMethod( gc.Template ); foreach(TypeRepresentation td in gc.Parameters) { CoverType( td ); } GenericParameterDefinition[] parametersDefinition = gc.ParametersDefinition; if(parametersDefinition != null) { for(int i = 0; i < parametersDefinition.Length; i++) { foreach(TypeRepresentation constraint in parametersDefinition[i].Constraints) { CoverType( constraint ); } } } } CoverType( md.OwnerType ); CoverType( md.ReturnType ); foreach(TypeRepresentation td in md.ThisPlusArguments) { CoverType( td ); } /// /// For imported methods we need to make sure that any passed structures are preserved. /// The type system reduction phase will attempt to remove member fields if they are /// not used or covered here which will leave them with a different signature/size than /// the native imported method is expecting. /// if(0 != ( md.BuildTimeFlags & MethodRepresentation.BuildTimeAttributes.Imported )) { foreach(CustomAttributeAssociationRepresentation caa in md.CustomAttributes) { CoverCustomAttributeAssociation( caa ); } HashSet importTypes = new HashSet(); foreach(TypeRepresentation tr in md.ThisPlusArguments) { // Make imported structures do not lose members during type system reduction if( tr.BuiltInType == TypeRepresentation.BuiltInTypes.BYREF && tr.UnderlyingType.BuiltInType == TypeRepresentation.BuiltInTypes.VALUETYPE ) { CoverImportedDataType( tr.UnderlyingType, importTypes ); } // also check for arrays of structs else if( tr.BuiltInType == TypeRepresentation.BuiltInTypes.ARRAY && tr.ContainedType.BuiltInType == TypeRepresentation.BuiltInTypes.VALUETYPE ) { CoverImportedDataType( tr.ContainedType, importTypes ); } } } } /// /// Cover all fields from an imported structure so that its size/signature remains consistent. /// /// /// private void CoverImportedDataType( TypeRepresentation tr, HashSet coveredTypes ) { if(coveredTypes.Contains( tr )) return; coveredTypes.Add( tr ); CoverType( tr ); foreach(FieldRepresentation fr in tr.Fields) { CoverField( fr ); CoverImportedDataType( fr.FieldType, coveredTypes ); } } private void CoverCustomAttribute( CustomAttributeRepresentation ca ) { if(ca == null) return; if(m_reachabilitySet.ExpandPending( ca )) { return; } CoverReflectionType( ca ); CoverMethod( ca.Constructor ); } private void CoverCustomAttributeAssociation( CustomAttributeAssociationRepresentation caa ) { if(caa == null) return; if(m_reachabilitySet.ExpandPending( caa )) { return; } CoverReflectionType( caa ); CoverObject( caa.Target ); CoverObject( caa.CustomAttribute ); } //--// internal void IncludeGeneric( object obj ) { CHECKS.ASSERT( m_owner.m_typeSystem.IsUseProhibited( obj ) == false, "Found use of '{0}' after the entity was marked illegal to use", obj ); if(obj is TypeRepresentation) { Include( (TypeRepresentation)obj ); } else if(obj is TypeRepresentation.GenericContext) { Include( (TypeRepresentation.GenericContext)obj ); } else if(obj is FieldRepresentation) { Include( (FieldRepresentation)obj ); } else if(obj is MethodRepresentation) { Include( (MethodRepresentation)obj ); } else if(obj is MethodRepresentation.GenericContext) { Include( (MethodRepresentation.GenericContext)obj ); } else if(obj is CustomAttributeRepresentation) { Include( (CustomAttributeRepresentation)obj ); } else if(obj is VTable) { Include( (VTable)obj ); } else if(obj is DataManager.DataDescriptor) { Include( (DataManager.DataDescriptor)obj ); } } private void Include( TypeRepresentation td ) { CHECKS.ASSERT( m_owner.m_typeSystem.IsUseProhibited( td ) == false, "Found use of '{0}' after the entity was marked illegal to use", td ); CoverType( td ); //--// TypeRepresentation tdSystem_Attribute = m_owner.m_typeSystem.WellKnownTypes.System_Attribute; if(tdSystem_Attribute != null && tdSystem_Attribute.IsSuperClassOf( td, null )) { // // If we touch an attribute, make sure all the constructor methods used by actual instances are touched. // m_owner.m_typeSystem.EnumerateCustomAttributes( delegate( CustomAttributeAssociationRepresentation caa ) { CustomAttributeRepresentation ca = caa.CustomAttribute; MethodRepresentation mdCa = ca .Constructor; if(mdCa.OwnerType == td) { // // BUGBUG: The named arguments are not included! // if(m_reachabilitySet.Contains( mdCa ) == false) { CoverMethod( mdCa ); } } } ); } //--// // // Include all the concrete subclasses, because we need at least one implementation. // if(td.HasBuildTimeFlag( TypeRepresentation.BuildTimeAttributes.ForceDevirtualization )) { var list = m_owner.m_typeSystem.CollectConcreteImplementations(td); foreach (var td2 in list) { CoverType(td2); } } //--// // // Since call closure has reached a new type, make sure that all the overrides to already touched virtual methods are included. // foreach(MethodRepresentation md in td.Methods) { if(md is VirtualMethodRepresentation && md.IsOpenMethod == false && td.IsOpenType == false && m_reachabilitySet.Contains( md ) == false) { int index = md.FindVirtualTableIndex(); if(index == -1) { continue; } MethodRepresentation mdRoot = md; TypeRepresentation tdRoot = td; while((mdRoot.Flags & MethodRepresentation.Attributes.NewSlot) == 0) { tdRoot = tdRoot.Extends; if(tdRoot == null) break; mdRoot = tdRoot.MethodTable[index]; if(m_reachabilitySet.Contains( mdRoot )) { CoverMethod( md ); break; } } } } // // Also, include the methods associated with already touched interfaces. // foreach(TypeRepresentation.InterfaceMap map in td.InterfaceMaps) { if(m_reachabilitySet.Contains( map.Interface )) { MethodRepresentation[] mdOverride = map.Methods; MethodRepresentation[] mdDeclaration = map.Interface.FindInterfaceTable( map.Interface ); for(int i = 0; i < mdDeclaration.Length; i++) { if(m_reachabilitySet.Contains( mdDeclaration[i] )) { if(m_reachabilitySet.Contains( mdOverride[i] ) == false) { CoverMethod( mdOverride[i] ); } } } } } } private void Include( TypeRepresentation.GenericContext ctx ) { if(ctx.Template != null) { Include( ctx.Template ); } foreach(TypeRepresentation td in ctx.Parameters) { Include( td ); } if(ctx.ParametersDefinition != null) { foreach(GenericParameterDefinition def in ctx.ParametersDefinition) { foreach(TypeRepresentation td in def.Constraints) { Include( td ); } } } } private void Include( FieldRepresentation fd ) { CHECKS.ASSERT( m_reachabilitySet.Contains( fd.OwnerType ), "ComputeCallsClosure.GlobalReachabilitySet does not contain '{0}', although it should", fd.OwnerType ); CoverField( fd ); } private void Include( MethodRepresentation md ) { CHECKS.ASSERT( m_owner.m_typeSystem.IsUseProhibited( md ) == false, "Found use of '{0}' after the entity was marked illegal to use", md ); CHECKS.ASSERT( m_owner.m_pendingHistory.Contains( md ), "ComputeCallsClosure.EntitiesReferencedByMethod does not contain '{0}', although it should", md ); CHECKS.ASSERT( m_reachabilitySet.Contains( md.OwnerType ), "ComputeCallsClosure.GlobalReachabilitySet does not contain '{0}', although it should", md.OwnerType ); CoverMethod( md ); if(md is VirtualMethodRepresentation && !(md is FinalMethodRepresentation)) { // // Include all the overrides for this method in all the subclasses already reached by the closure computation. // int index = md.FindVirtualTableIndex(); TypeRepresentation td = md.OwnerType; List< TypeRepresentation > lst; if(m_owner.m_typeSystem.DirectDescendant.TryGetValue( td, out lst )) { foreach(TypeRepresentation td2 in lst) { MethodRepresentation md2 = td2.MethodTable[index]; if(m_reachabilitySet.Contains( md2.OwnerType )) { CoverMethod( md2 ); } } } // // A virtual method defines a slot when it's first introduced. // Make sure all the methods from this one up to the root of the override tree are included. // MethodRepresentation mdRoot = md; while((mdRoot.Flags & MethodRepresentation.Attributes.NewSlot) == 0) { td = td.Extends; if(td == null) break; mdRoot = td.MethodTable[index]; if(m_reachabilitySet.Contains( mdRoot ) == false) { CoverMethod( mdRoot ); } } //--// // // The method belongs to an interface, we have to include all the implementations in all the touched types. // if(td is InterfaceTypeRepresentation) { InterfaceTypeRepresentation itf = (InterfaceTypeRepresentation)td; int itfIndex = md.FindInterfaceTableIndex(); foreach(TypeRepresentation td2 in m_owner.m_typeSystem.InterfaceImplementors[itf]) { if(m_reachabilitySet.Contains( td2 )) { MethodRepresentation mdOverride = td2.FindInterfaceTable( itf )[itfIndex]; if(m_reachabilitySet.Contains( mdOverride ) == false) { CoverMethod( mdOverride ); } } } } } } private void Include( MethodRepresentation.GenericContext ctx ) { Include( ctx.Template ); foreach(TypeRepresentation td in ctx.Parameters) { Include( td ); } if(ctx.ParametersDefinition != null) { foreach(GenericParameterDefinition def in ctx.ParametersDefinition) { foreach(TypeRepresentation td in def.Constraints) { Include( td ); } } } } private void Include( CustomAttributeRepresentation ca ) { CHECKS.ASSERT( m_owner.m_typeSystem.IsUseProhibited( ca ) == false, "Found use of '{0}' after the entity was marked illegal to use", ca ); CoverCustomAttribute( ca ); } private void Include( VTable vTable ) { Include( vTable.TypeInfo ); } private void Include( DataManager.DataDescriptor dd ) { lock(m_owner.m_delayedExpansion) { m_owner.m_delayedExpansion.Insert( dd ); } } internal bool Contains( object obj ) { return m_reachabilitySet.Contains( obj ); } //--// // // Access Methods // public TypeSystemForCodeTransformation TypeSystem { get { return m_owner.m_typeSystem; } } internal TypeSystem.Reachability ReachabilitySet { get { return m_reachabilitySet; } } } // // State // private readonly TypeSystemForCodeTransformation m_typeSystem; private readonly CallsDataBase m_callsDatabase; private readonly PhaseDriver m_phase; private readonly GrowOnlyHashTable< Type, List< Notification > > m_delegation; private readonly GrowOnlySet < DataManager.DataDescriptor > m_delayedExpansion; private readonly GrowOnlySet < MethodRepresentation > m_pendingHistory; private readonly Queue < MethodRepresentation > m_pending; private readonly Context m_globalContext; private readonly GrowOnlyHashTable< MethodRepresentation, GrowOnlySet< object > > m_entitiesReferencedByMethods; // // Constructor Methods // public ComputeCallsClosure( TypeSystemForCodeTransformation typeSystem , DelegationCache cache , CallsDataBase callsDatabase , PhaseDriver phase , bool fCollectPerMethodInfo ) { m_typeSystem = typeSystem; m_callsDatabase = callsDatabase; m_phase = phase; m_delegation = HashTableFactory.New < Type, List< Notification > >(); m_delayedExpansion = SetFactory .NewWithReferenceEquality< DataManager.DataDescriptor >(); m_pendingHistory = SetFactory .NewWithReferenceEquality< MethodRepresentation >(); m_pending = new Queue < MethodRepresentation >(); m_globalContext = new Context( this, typeSystem.ReachabilitySet ); if(fCollectPerMethodInfo) { m_entitiesReferencedByMethods = HashTableFactory.NewWithReferenceEquality< MethodRepresentation, GrowOnlySet< object > >(); } typeSystem.ReachabilitySet.RestartComputation(); cache.HookNotifications( typeSystem, this, phase ); } // // Helper Methods // public void Execute( MethodRepresentation mdStart ) { if(m_globalContext.Contains( mdStart ) == false) { QueueMethodForProcessing( mdStart ); ProcessInner(); } } public void Expand( object val ) { m_globalContext.CoverObject( val ); ProcessInner(); } public void ExpandContents< TKey, TValue >( GrowOnlyHashTable< TKey, TValue > ht ) { foreach(TKey key in ht.Keys) { Expand( key ); Expand( ht[key] ); } } public void ExpandValueIfKeyIsReachable< TKey, TValue >( GrowOnlyHashTable< TKey, TValue > ht ) { foreach(TKey key in ht.Keys) { if(m_globalContext.Contains( key )) { Expand( ht[key] ); } } } //--// private void QueueMethodForProcessing( MethodRepresentation md ) { lock(m_pendingHistory) { if(m_pendingHistory.Insert( md ) == true) { return; } } lock(m_pending) { m_pending.Enqueue( md ); } } private void ProcessInner() { while(IsThereWorkToDo()) { ProcessMethods(); ProcessDataDescriptors(); } } private bool IsThereWorkToDo() { if(m_pending.Count > 0) { return true; } if(m_globalContext.ReachabilitySet.HasPendingItems()) { return true; } return false; } private void Analyze( MethodRepresentation md ) { m_globalContext.ProcessMethod( md ); if(m_entitiesReferencedByMethods != null) { GrowOnlySet< object > entitiesReferencedByMethod; lock(m_entitiesReferencedByMethods) { if(m_entitiesReferencedByMethods.ContainsKey( md )) return; entitiesReferencedByMethod = SetFactory.NewWithWeakEquality< object >(); m_entitiesReferencedByMethods[md] = entitiesReferencedByMethod; } var currentMethodReachabilitySet = TypeSystemForCodeTransformation.Reachability.CreateForUpdate( entitiesReferencedByMethod ); Context ctx = new Context( this, currentMethodReachabilitySet ); ctx.ProcessMethod( md ); } } private void ProcessMethods() { using(ParallelTransformationsHandler handler = new ParallelTransformationsHandler( Analyze )) { while(true) { DrainIncrementalSet(); if(m_pending.Count == 0) { break; } var methods = m_pending.ToArray(); m_pending.Clear(); #if COMPUTECALLSCLOSURE_FORCE_SINGLE_THREADED foreach(var md in methods) { Analyze( md ); } #else foreach(var md in methods) { handler.Queue( md ); } handler.Synchronize(); #endif } } } private void DrainIncrementalSet() { while(true) { object[] set = m_globalContext.ReachabilitySet.ApplyPendingSet( true ); if(set == null) { break; } foreach(object obj in set) { m_globalContext.IncludeGeneric( obj ); } } } private void ProcessDataDescriptors() { TypeSystem.Reachability reachability = m_globalContext.ReachabilitySet.CloneForIncrementalUpdate(); foreach(DataManager.DataDescriptor dd in m_delayedExpansion) { if(reachability.Contains( dd )) { dd.IncludeExtraTypes( reachability, m_phase ); } } object[] set = reachability.ApplyPendingSet( false ); if(set != null) { foreach(object obj in set) { m_globalContext.CoverObject( obj ); } } } //--// public void RegisterForNotification( Type type , Notification notification ) { HashTableWithListFactory.AddUnique( m_delegation, type, notification ); } //--// // // Access Methods // public TypeSystemForCodeTransformation TypeSystem { get { return m_typeSystem; } } public GrowOnlyHashTable< MethodRepresentation, GrowOnlySet< object > > EntitiesReferencedByMethods { get { return m_entitiesReferencedByMethods; } } } } ================================================ FILE: Zelig/Zelig/CompileTime/CodeGenerator/CodeTransformation/CompilationSteps/PhaseDrivers/DelegationCache.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // namespace Microsoft.Zelig.CodeGeneration.IR.CompilationSteps { using System; using System.Collections.Generic; using Microsoft.Zelig.Runtime.TypeSystem; public sealed class DelegationCache { class Entry { // // State // System.Reflection.MethodInfo m_source; Delegate m_dlg; AbstractHandlerAttribute m_context; PhaseFilterAttribute[] m_phaseFilters; // // Constructor Methods // internal Entry( System.Reflection.MethodInfo source , Delegate dlg , AbstractHandlerAttribute context ) { m_source = source; m_dlg = dlg; m_context = context; m_phaseFilters = ReflectionHelper.GetAttributes< PhaseFilterAttribute >( source, false ); } // // Helper Methods // internal bool ShouldProcess( PhaseDriver phase , int pass ) { if(pass == 0) { foreach(PhaseFilterAttribute pf in m_phaseFilters) { if(pf.Target == phase.GetType()) { return true; } } } else { if(m_phaseFilters.Length == 0) { // // No filter => always on. But process after any entry that has a filter. // return true; } } return false; } // // Access Methods // internal System.Reflection.MethodInfo Source { get { return m_source; } } internal PhaseDriver.Notification DelegateForPhase { get { return (PhaseDriver.Notification)m_dlg; } } internal PhaseExecution.NotificationOfTransformation DelegateForPhaseExecution { get { return (PhaseExecution.NotificationOfTransformation)m_dlg; } } internal PhaseExecution.NotificationOfTransformationForAttribute DelegateForPhaseExecutionForAttribute { get { return (PhaseExecution.NotificationOfTransformationForAttribute)m_dlg; } } internal ComputeCallsClosure.Notification DelegateForCallClosure { get { return (ComputeCallsClosure.Notification)m_dlg; } } internal AbstractHandlerAttribute Context { get { return m_context; } } } // // State // private readonly TypeSystemForCodeTransformation m_typeSystem; private List< Entry > m_entries; // // Constructor Methods // public DelegationCache( TypeSystemForCodeTransformation typeSystem ) { m_typeSystem = typeSystem; m_entries = new List< Entry >(); } // // Helper Methods // public void Register( object instance ) { Type t = instance.GetType(); while(t != null) { foreach(var mi in t.GetMethods( System.Reflection.BindingFlags.Static | System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.Public | System.Reflection.BindingFlags.NonPublic )) { HookCustomAttributeNotifications( mi, instance ); HookNewEntityNotifications ( mi, instance ); CreateHandlers ( mi, instance ); } var cfgProv = m_typeSystem.GetEnvironmentService< IConfigurationProvider >(); if(cfgProv != null) { foreach(var mi in ReflectionHelper.GetAllFields( t )) { foreach(var attr in ReflectionHelper.GetAttributes< Runtime.ConfigurationOptionAttribute >( mi, false )) { object val; if(cfgProv.GetValue( attr.Name, out val )) { if(mi.IsStatic) { mi.SetValue( null, val ); } else { mi.SetValue( instance, val ); } } } } } t = t.BaseType; } } private void CreateHandlers( System.Reflection.MethodInfo mi , object instance ) { foreach(AbstractHandlerAttribute attrib in ReflectionHelper.GetAttributes< AbstractHandlerAttribute >( mi, false )) { try { Type type; if(attrib is CallClosureHandlerAttribute) { type = typeof(ComputeCallsClosure.Notification); } else if(attrib is PrePhaseHandlerAttribute || attrib is PostPhaseHandlerAttribute ) { type = typeof(PhaseDriver.Notification); } else if(attrib is CustomAttributeHandlerAttribute) { type = typeof(PhaseExecution.NotificationOfTransformationForAttribute); } else { type = typeof(PhaseExecution.NotificationOfTransformation); } Entry en = new Entry( mi, CreateNotification( type, mi, instance ), attrib ); m_entries.Add( en ); } catch(Exception ex) { throw TypeConsistencyErrorException.Create( "Got the following error while trying to create a notification handler for {0}:\n{1}", attrib, ex.ToString() ); } } } private void HookNewEntityNotifications( System.Reflection.MethodInfo mi , object instance ) { if(ReflectionHelper.HasAttribute< CompilationSteps.NewEntityNotificationAttribute >( mi, false )) { System.Reflection.ParameterInfo[] parameters = mi.GetParameters(); if(parameters != null && parameters.Length == 1) { Type paramEntity = parameters[0].ParameterType; if(paramEntity == typeof(TypeRepresentation)) { var dlg = (TypeSystem.NotificationOfNewType)CreateNotification( typeof(TypeSystem.NotificationOfNewType), mi, instance ); m_typeSystem.RegisterForNewType( dlg ); return; } if(paramEntity == typeof(FieldRepresentation)) { var dlg = (TypeSystem.NotificationOfNewField)CreateNotification( typeof(TypeSystem.NotificationOfNewField), mi, instance ); m_typeSystem.RegisterForNewField( dlg ); return; } if(paramEntity == typeof(MethodRepresentation)) { var dlg = (TypeSystem.NotificationOfNewMethod)CreateNotification( typeof(TypeSystem.NotificationOfNewMethod), mi, instance ); m_typeSystem.RegisterForNewMethod( dlg ); return; } } throw TypeConsistencyErrorException.Create( "Method '{0}' cannot be used for new entity notification", mi ); } } //--// private void HookCustomAttributeNotifications( System.Reflection.MethodInfo mi , object instance ) { foreach(var attrib in ReflectionHelper.GetAttributes< CompilationSteps.CustomAttributeNotificationAttribute >( mi, false )) { TypeRepresentation td = m_typeSystem.GetWellKnownTypeNoThrow( attrib.Target ); if(td == null) { throw TypeConsistencyErrorException.Create( "Failed to create custom attribute notification because type '{0}' is not well-known", attrib.Target ); } System.Reflection.ParameterInfo[] parameters = mi.GetParameters(); if(parameters != null && parameters.Length >= 3) { Type paramTypeKeep = parameters[0].ParameterType; Type paramTypeCa = parameters[1].ParameterType; Type paramTypeOwner = parameters[2].ParameterType; if(paramTypeKeep.IsByRef && paramTypeKeep.GetElementType() == typeof(bool) && paramTypeCa == typeof(CustomAttributeRepresentation) ) { if(paramTypeOwner == typeof(BaseRepresentation) && parameters.Length == 3) { var dlg = (TypeSystem.NotificationOfAttributeOnGeneric)CreateNotification( typeof(TypeSystem.NotificationOfAttributeOnGeneric), mi, instance ); m_typeSystem.RegisterForNotificationOfAttributeOnGeneric( td, dlg ); continue; } if(paramTypeOwner == typeof(TypeRepresentation) && parameters.Length == 3) { var dlg = (TypeSystem.NotificationOfAttributeOnType)CreateNotification( typeof(TypeSystem.NotificationOfAttributeOnType), mi, instance ); m_typeSystem.RegisterForNotificationOfAttributeOnType( td, dlg ); continue; } if(paramTypeOwner == typeof(FieldRepresentation) && parameters.Length == 3) { var dlg = (TypeSystem.NotificationOfAttributeOnField)CreateNotification( typeof(TypeSystem.NotificationOfAttributeOnField), mi, instance ); m_typeSystem.RegisterForNotificationOfAttributeOnField( td, dlg ); continue; } if(paramTypeOwner == typeof(MethodRepresentation)) { if(parameters.Length == 3) { var dlg = (TypeSystem.NotificationOfAttributeOnMethod)CreateNotification( typeof(TypeSystem.NotificationOfAttributeOnMethod), mi, instance ); m_typeSystem.RegisterForNotificationOfAttributeOnMethod( td, dlg ); continue; } if(parameters.Length == 4 && parameters[3].ParameterType == typeof(int)) { var dlg = (TypeSystem.NotificationOfAttributeOnParam)CreateNotification( typeof(TypeSystem.NotificationOfAttributeOnParam), mi, instance ); m_typeSystem.RegisterForNotificationOfAttributeOnParam( td, dlg ); continue; } } } } throw TypeConsistencyErrorException.Create( "Method '{0}' cannot be used for custom attribute notification", mi ); } } //--// public void HookNotifications( TypeSystemForCodeTransformation typeSystem , PhaseDriver phase ) { for(int pass = 0; pass < 2; pass++) { foreach(Entry en in m_entries) { if(en.ShouldProcess( phase, pass )) { if(en.Context is PrePhaseHandlerAttribute) { phase.RegisterForNotification( en.DelegateForPhase, true ); } if(en.Context is PostPhaseHandlerAttribute) { phase.RegisterForNotification( en.DelegateForPhase, false ); } } } } } public void HookNotifications( TypeSystemForCodeTransformation typeSystem , PhaseExecution pe , PhaseDriver phase ) { for(int pass = 0; pass < 2; pass++) { foreach(Entry en in m_entries) { if(en.ShouldProcess( phase, pass )) { if(en.Context is OptimizationHandlerAttribute) { OptimizationHandlerAttribute ca = (OptimizationHandlerAttribute)en.Context; pe.RegisterForNotificationOfOptimization( ca, en.DelegateForPhaseExecution ); } if(en.Context is PreFlowGraphHandlerAttribute) { pe.RegisterForNotificationOfFlowGraph( en.DelegateForPhaseExecution, true ); } if(en.Context is PostFlowGraphHandlerAttribute) { pe.RegisterForNotificationOfFlowGraph( en.DelegateForPhaseExecution, false ); } if(en.Context is OperatorHandlerAttribute) { OperatorHandlerAttribute ca = (OperatorHandlerAttribute)en.Context; pe.RegisterForNotificationOfOperatorsByType( ca.Target, en.DelegateForPhaseExecution ); } if(en.Context is OperatorArgumentHandlerAttribute) { OperatorArgumentHandlerAttribute ca = (OperatorArgumentHandlerAttribute)en.Context; pe.RegisterForNotificationOfOperatorByTypeOfArguments( ca.Target, en.DelegateForPhaseExecution ); } if(en.Context is WellKnownTypeHandlerAttribute) { WellKnownTypeHandlerAttribute ca = (WellKnownTypeHandlerAttribute)en.Context; pe.RegisterForNotificationOfOperatorByEntities( typeSystem.GetWellKnownTypeNoThrow( ca.Target ), en.DelegateForPhaseExecution ); } if(en.Context is WellKnownFieldHandlerAttribute) { WellKnownFieldHandlerAttribute ca = (WellKnownFieldHandlerAttribute)en.Context; pe.RegisterForNotificationOfOperatorByEntities( typeSystem.GetWellKnownFieldNoThrow( ca.Target ), en.DelegateForPhaseExecution ); } if(en.Context is WellKnownMethodHandlerAttribute) { WellKnownMethodHandlerAttribute ca = (WellKnownMethodHandlerAttribute)en.Context; pe.RegisterForNotificationOfOperatorByEntities( typeSystem.GetWellKnownMethodNoThrow( ca.Target ), en.DelegateForPhaseExecution ); } if(en.Context is CallToWellKnownMethodHandlerAttribute) { CallToWellKnownMethodHandlerAttribute ca = (CallToWellKnownMethodHandlerAttribute)en.Context; pe.RegisterForNotificationOfCallOperatorByEntities( typeSystem.GetWellKnownMethodNoThrow( ca.Target ), en.DelegateForPhaseExecution ); } if(en.Context is CustomAttributeHandlerAttribute) { CustomAttributeHandlerAttribute ca = (CustomAttributeHandlerAttribute)en.Context; TypeRepresentation targetType = typeSystem.GetWellKnownTypeNoThrow( ca.FieldName ); if(targetType != null) { var dlg = en.DelegateForPhaseExecutionForAttribute; typeSystem.EnumerateCustomAttributes( delegate( CustomAttributeAssociationRepresentation caa ) { if(caa.CustomAttribute.Constructor.OwnerType == targetType) { BaseRepresentation bdTarget = caa.Target; if(bdTarget != null) { pe.RegisterForNotificationOfOperatorByEntities( bdTarget, nc => dlg( nc, caa.CustomAttribute ) ); } } } ); } } } } } } internal void HookNotifications( TypeSystemForCodeTransformation typeSystem , ComputeCallsClosure cc , PhaseDriver phase ) { for(int pass = 0; pass < 2; pass++) { foreach(Entry en in m_entries) { if(en.ShouldProcess( phase, pass )) { if(en.Context is CallClosureHandlerAttribute) { CallClosureHandlerAttribute ca = (CallClosureHandlerAttribute)en.Context; cc.RegisterForNotification( ca.Target, en.DelegateForCallClosure ); } } } } } //--// private static Delegate CreateNotification( Type type , System.Reflection.MethodInfo mi , object instance ) { try { if(mi.IsStatic) { return Delegate.CreateDelegate( type, mi, true ); } else { return Delegate.CreateDelegate( type, instance, mi, true ); } } catch(Exception ex) { throw TypeConsistencyErrorException.Create( "Got the following error while trying to create a notification handler for {0}:\n{1}", mi, ex.ToString() ); } } } } ================================================ FILE: Zelig/Zelig/CompileTime/CodeGenerator/CodeTransformation/CompilationSteps/PhaseDrivers/DetectFieldInvariants.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // namespace Microsoft.Zelig.CodeGeneration.IR.CompilationSteps { using System; using System.Collections.Generic; using Microsoft.Zelig.Runtime.TypeSystem; internal static class DetectFieldInvariants { // // Helper Methods // internal static void Execute( TypeSystemForCodeTransformation typeSystem ) { Transformations.LocateFieldsInCode lfic = new Transformations.LocateFieldsInCode( typeSystem ); lfic.Run(); foreach(FieldRepresentation fd in lfic.FieldReferences.Keys) { GrowOnlySet< Operator > set = lfic.FieldReferences[fd]; StoreFieldOperator opStore = null; bool fCandidate = true; foreach(Operator op in set) { if(op is StoreFieldOperator) { if(opStore != null) { // // More than one store, let's give up. // // TODO: what if all the stores have the same shape? // fCandidate = false; break; } opStore = (StoreFieldOperator)op; } else if(op is LoadAddressOperator) { // // Address taken, not interesting. // fCandidate = false; break; } } if(fCandidate && opStore != null) { fd.Flags |= FieldRepresentation.Attributes.HasSingleAssignment; ControlFlowGraphStateForCodeTransformation cfg = (ControlFlowGraphStateForCodeTransformation)opStore.BasicBlock.Owner; MethodRepresentation md = cfg.Method; if(fd.OwnerType != md.OwnerType) { continue; } if(md is ConstructorMethodRepresentation || md is StaticConstructorMethodRepresentation ) { Expression[] rhs = opStore.Arguments; Expression val = rhs[rhs.Length - 1]; TypeRepresentation fdType = fd.FieldType; if(val is ConstantExpression) { ConstantExpression exVal = (ConstantExpression)val; if(fdType is ReferenceTypeRepresentation) { if(exVal.Value != null) { fd.Flags |= FieldRepresentation.Attributes.NeverNull; } if(fdType is ArrayReferenceTypeRepresentation) { Array array = exVal.Value as Array; if(array != null) { fd.FixedSize = array.Length; } } } } else { Operator singleDef = ControlFlowGraphState.CheckSingleDefinition( cfg.DataFlow_DefinitionChains, (VariableExpression)val ); if(singleDef != null) { if(fdType is ArrayReferenceTypeRepresentation) { ArrayReferenceTypeRepresentation fdTypeArray = (ArrayReferenceTypeRepresentation)fdType; ArrayAllocationOperator opAlloc = singleDef as ArrayAllocationOperator; if(opAlloc != null) { fd.Flags |= FieldRepresentation.Attributes.NeverNull; ConstantExpression exSize = opAlloc.FirstArgument as ConstantExpression; long iSize; if(exSize != null && exSize.GetAsSignedInteger( out iSize )) { int size = (int)iSize; fd.FixedSize = size; if(fd is StaticFieldRepresentation) { // // This is an array assigned to a static field and never changed. // // Convert it into a static array, remove the array allocation and the static field assignment. // InstanceFieldRepresentation fdInstance = typeSystem.AddStaticFieldToGlobalRoot( (StaticFieldRepresentation)fd ); DataManager.ObjectDescriptor odRoot = typeSystem.GenerateGlobalRoot(); var wkt = typeSystem.WellKnownTypes; TypeRepresentation tdElement = fdTypeArray.ContainedType; Type tElement = typeSystem.TryGetTypeFromTypeRepresentation( tdElement ); Array array = null; if(tElement != null) { array = Array.CreateInstance( tElement, size ); } DataManager.Attributes flags = DataManager.Attributes.SuitableForConstantPropagation; if(size == 0) { flags |= DataManager.Attributes.Constant; } else { flags |= DataManager.Attributes.Mutable; } Abstractions.PlacementRequirements pr = typeSystem.GetPlacementRequirements( fd ); // // For a non-zero array, make sure it's allocated in a writable data section. // if(size != 0) { if(pr == null) { pr = new Abstractions.PlacementRequirements( sizeof(uint), 0 ); } pr.AddConstraint( Runtime.MemoryUsage.DataRW ); } DataManager.ArrayDescriptor ad = typeSystem.DataManagerInstance.BuildArrayDescriptor( fdTypeArray, flags, pr, array, size ); odRoot.Set( fdInstance, ad ); // // Remove the store and change the allocation with a load. // opAlloc.SubstituteWithOperator( LoadStaticFieldOperator.New( opAlloc.DebugInfo, fd, opAlloc.FirstResult ), Operator.SubstitutionFlags.Default ); opStore.Delete(); } } } } else if(fdType is ReferenceTypeRepresentation) { ObjectAllocationOperator opAlloc = singleDef as ObjectAllocationOperator; if(opAlloc != null) { fd.Flags |= FieldRepresentation.Attributes.NeverNull; } } } } } } } } } } ================================================ FILE: Zelig/Zelig/CompileTime/CodeGenerator/CodeTransformation/CompilationSteps/PhaseDrivers/ImplementExternalMethods.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // namespace Microsoft.Zelig.CodeGeneration.IR.CompilationSteps { using System; using System.Collections.Generic; using Microsoft.Zelig.Runtime.TypeSystem; using Microsoft.Zelig.Runtime; using Microsoft.Zelig.CodeGeneration.IR.Abstractions; using System.IO; public sealed class ImplementExternalMethods { // // State // private TypeSystemForCodeTransformation m_typeSystem; // // Constructor Methods // public ImplementExternalMethods( TypeSystemForCodeTransformation typeSystem ) { m_typeSystem = typeSystem; } public static void ResetExternalDataDescriptors() { ExternalCallContext.Reset( ); } // // Helper Methods // public void Prepare() { ExternalCallContext.Initialize( m_typeSystem ); ExternalCallContext.ResetExternalCalls(); List importedMethods = new List(); foreach(TypeRepresentation td in m_typeSystem.Types) { // // Implement code for external "C/ASM" calls that have been marked as imported references // foreach(MethodRepresentation md in td.Methods) { if(( md.BuildTimeFlags & MethodRepresentation.BuildTimeAttributes.Exported ) != 0) { m_typeSystem.ExportedMethods.Add( md ); } else if(( md.BuildTimeFlags & MethodRepresentation.BuildTimeAttributes.Imported ) != 0) { importedMethods.Add( md ); } } } foreach(MethodRepresentation md in importedMethods) { ImplementExternalMethodStub( md, this.m_typeSystem ); } } // // Helper Methods // private void ImplementExternalMethodStub( MethodRepresentation md, TypeSystemForCodeTransformation typeSys ) { ControlFlowGraphStateForCodeTransformation cfg = TypeSystemForCodeTransformation.GetCodeForMethod( md ); if(cfg == null) { cfg = (ControlFlowGraphStateForCodeTransformation)m_typeSystem.CreateControlFlowGraphState( md ); } if( cfg.Method.CustomAttributes.Length > 0) { var bb = cfg.FirstBasicBlock; CustomAttributeRepresentation ca = md.CustomAttributes[0].CustomAttribute; string filePath = ca.FixedArgsValues[1] as string; string methodName = ca.FixedArgsValues.Length >= 3 ? ca.FixedArgsValues[2] as string : md.Name; filePath = Environment.ExpandEnvironmentVariables( filePath ); ImportedMethodReferenceAttribute.InteropFileType fileType = (ImportedMethodReferenceAttribute.InteropFileType)ca.FixedArgsValues[0]; if(!Path.IsPathRooted( filePath )) { string tmp = Path.Combine( Directory.GetCurrentDirectory(), filePath ); if(File.Exists( tmp )) { filePath = tmp; } else { foreach(string p in typeSys.NativeImportDirectories) { tmp = Path.Combine( p, filePath ); if(File.Exists( tmp )) { filePath = tmp; break; } } } } if(!typeSys.NativeImportLibraries.Contains( filePath.ToLower() )) { typeSys.NativeImportLibraries.Add( filePath.ToLower() ); } ExternalCallOperator.IExternalCallContext[] ctxs = ExternalCallContext.Create( fileType, filePath, methodName, bb ); int len = ctxs.Length; for(int i = 0; i < len; i++) { ExternalCallOperator op = ExternalCallOperator.New( ctxs[i] ); bb.AddOperator( op ); op.Context.Owner = op; } md.RemoveCustomAttribute( ca ); } } } } ================================================ FILE: Zelig/Zelig/CompileTime/CodeGenerator/CodeTransformation/CompilationSteps/PhaseDrivers/ImplementInternalMethods.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // namespace Microsoft.Zelig.CodeGeneration.IR.CompilationSteps { using System; using System.Collections.Generic; using Microsoft.Zelig.Runtime.TypeSystem; public sealed partial class ImplementInternalMethods { internal delegate bool Callback( MethodRepresentation md ); // // State // private TypeSystemForCodeTransformation m_typeSystem; private GrowOnlyHashTable< MethodRepresentation, Callback > m_pending; // // Constructor Methods // public ImplementInternalMethods( TypeSystemForCodeTransformation typeSystem ) { m_typeSystem = typeSystem; m_pending = HashTableFactory.NewWithReferenceEquality< MethodRepresentation, Callback >(); } // // Helper Methods // public void Prepare() { WellKnownTypes wkt = m_typeSystem.WellKnownTypes; WellKnownMethods wkm = m_typeSystem.WellKnownMethods; TypeRepresentation tdMulticastDelegate = wkt.System_MulticastDelegate; MethodRepresentation mdObject_Equals = wkm.Object_Equals; Callback dlgImplementObjectEquals = ImplementObjectEquals; foreach(TypeRepresentation td in m_typeSystem.Types) { // // For all the user-defined value types, provide a system-generated implementation of Object.Equals and Obect.GetHashCode. // if(td is ValueTypeRepresentation && !(td is ScalarTypeRepresentation) && td.IsAbstract == false) { if(td.IsOpenType == false && td.FindMatch( mdObject_Equals, null ) == null) { MethodRepresentation md = td.CreateOverride( m_typeSystem, (VirtualMethodRepresentation)mdObject_Equals ); m_pending[md] = dlgImplementObjectEquals; } } // // Implement code for delegates. // if(td.IsSubClassOf( tdMulticastDelegate, null ) && wkm.MulticastDelegateImpl_MulticastDelegateImpl != null) { foreach(MethodRepresentation md in td.Methods) { ImplementDelegateMethods( md ); } } // // Implement code for the compiler-generated methods on arrays. // if(td is ArrayReferenceTypeRepresentation) { var tdHelper = FindArrayHelper( td ); foreach(MethodRepresentation md in td.Methods) { if(md is RuntimeMethodRepresentation) { if(TypeSystemForCodeTransformation.GetCodeForMethod( md ) == null) { var cfg = (ControlFlowGraphStateForCodeTransformation)m_typeSystem.CreateControlFlowGraphState( md ); if(tdHelper != null) { LinkArrayImplementation( cfg, tdHelper ); } else { ProvideThrowingStubImplementation( cfg ); } } } } } //LON: 2/16/09 // // Implement code for external "C/ASM" calls that have been marked as imported references // foreach(MethodRepresentation md in td.Methods) { if ((md.BuildTimeFlags & MethodRepresentation.BuildTimeAttributes.Imported) != 0) { ImplementExternalMethodStub( md, this.m_typeSystem ); } } } // // Implement code for singleton factories. // foreach(MethodRepresentation md in m_typeSystem.SingletonFactories.Keys) { ImplementSingletonFactory( md, m_typeSystem.SingletonFactories[md] ); } } private TypeRepresentation FindArrayHelper( TypeRepresentation td ) { List< TypeRepresentation > lst; if(m_typeSystem.GenericTypeInstantiations.TryGetValue( m_typeSystem.WellKnownTypes.Microsoft_Zelig_Runtime_SZArrayHelper, out lst )) { foreach(var tdHelper in lst) { if(tdHelper.GenericParameters[0] == td.ContainedType) { return tdHelper; } } } return null; } private void LinkArrayImplementation( ControlFlowGraphStateForCodeTransformation cfg , TypeRepresentation tdHelper ) { MethodRepresentation md = cfg.Method; TypeRepresentation[] thisPlusArguments = md.ThisPlusArguments; thisPlusArguments = ArrayUtility.InsertAtHeadOfNotNullArray( thisPlusArguments, tdHelper ); foreach(var mdHelper in tdHelper.Methods) { if(mdHelper.MatchNameAndSignature( md.Name, md.ReturnType, thisPlusArguments, null )) { var bb = cfg.CreateFirstNormalBasicBlock(); var rhs = m_typeSystem.AddTypePointerToArgumentsOfStaticMethod( mdHelper, cfg.Arguments ); bb.AddOperator( StaticCallOperator.New( null, CallOperator.CallKind.Direct, mdHelper, VariableExpression.ToArray( cfg.ReturnValue ), rhs ) ); cfg.AddReturnOperator(); return; } } // // No implementation found, fallback to throwing behavior. // ProvideThrowingStubImplementation( cfg ); } private void ProvideThrowingStubImplementation( ControlFlowGraphStateForCodeTransformation cfg ) { var bb = cfg.CreateFirstNormalBasicBlock(); MethodRepresentation mdThrow = m_typeSystem.WellKnownMethods.ThreadImpl_ThrowNotImplementedException; Expression[] rhs = m_typeSystem.AddTypePointerToArgumentsOfStaticMethod( mdThrow ); bb.AddOperator( StaticCallOperator.New( null, CallOperator.CallKind.Direct, mdThrow, rhs ) ); cfg.ExitBasicBlock.FlowControl = DeadControlOperator.New( null ); } public bool Complete() { MethodRepresentation[] mdArray = m_pending.KeysToArray(); Callback[] dlgArray = m_pending.ValuesToArray(); bool fRes = true; m_pending.Clear(); for(int i = 0; i < mdArray.Length; i++) { MethodRepresentation md = mdArray[i]; if(m_typeSystem.EstimatedReachabilitySet.IsProhibited( md ) == false) { fRes &= dlgArray[i]( mdArray[i] ); } } return fRes; } } } ================================================ FILE: Zelig/Zelig/CompileTime/CodeGenerator/CodeTransformation/CompilationSteps/PhaseDrivers/ImplementInternalMethods_Delegate.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // namespace Microsoft.Zelig.CodeGeneration.IR.CompilationSteps { using System; using System.Collections.Generic; using Microsoft.Zelig.Runtime.TypeSystem; public sealed partial class ImplementInternalMethods { // // Helper Methods // private void ImplementDelegateMethods( MethodRepresentation md ) { if(TypeSystemForCodeTransformation.GetCodeForMethod( md ) == null) { ControlFlowGraphStateForCodeTransformation cfg = (ControlFlowGraphStateForCodeTransformation)m_typeSystem.CreateControlFlowGraphState( md ); WellKnownTypes wkt = m_typeSystem.WellKnownTypes; WellKnownMethods wkm = m_typeSystem.WellKnownMethods; WellKnownFields wkf = m_typeSystem.WellKnownFields; if(md is ConstructorMethodRepresentation) { var bb = cfg.CreateFirstNormalBasicBlock(); md.BuildTimeFlags &= ~MethodRepresentation.BuildTimeAttributes.Inline; md.BuildTimeFlags |= MethodRepresentation.BuildTimeAttributes.NoInline; // // Create proper flow control for exit basic block. // cfg.AddReturnOperator(); // // Call the base method. // MethodRepresentation mdParent = wkm.MulticastDelegateImpl_MulticastDelegateImpl; Expression[] rhs = new Expression[cfg.Arguments.Length]; for(int i = 0; i < cfg.Arguments.Length; i++) { rhs[i] = cfg.Arguments[i]; } // Wrap the IntPtr param in a CodePointer struct and call the parent constructor. rhs[2] = cfg.AllocateLocal( wkt.Microsoft_Zelig_Runtime_TypeSystem_CodePointer, null ); bb.AddOperator( StoreInstanceFieldOperator.New( null, wkf.CodePointer_Target, rhs[2], cfg.Arguments[2], false ) ); bb.AddOperator( InstanceCallOperator.New( null, CallOperator.CallKind.Overridden, mdParent, rhs, true ) ); } else if(md.Name == "Invoke") { var bb = cfg.CreateFirstNormalBasicBlock(); BasicBlock bbExit; Expression[] rhs; VariableExpression exReturnValue; // // Create proper flow control for exit basic block. // ReturnControlOperator opRet; if(cfg.ReturnValue != null) { opRet = ReturnControlOperator.New( cfg.ReturnValue ); //--// exReturnValue = cfg.AllocateLocal( cfg.ReturnValue.Type, null ); Operator op = cfg.GenerateVariableInitialization( null, exReturnValue ); cfg.GetInjectionPoint( BasicBlock.Qualifier.PrologueEnd ).AddOperator( op ); //--// bbExit = cfg.CreateLastNormalBasicBlock(); bbExit.AddOperator( SingleAssignmentOperator.New( null, cfg.ReturnValue, exReturnValue ) ); } else { opRet = ReturnControlOperator.New(); //--// exReturnValue = null; //--// bbExit = cfg.NormalizedExitBasicBlock; } cfg.ExitBasicBlock.AddOperator( opRet ); // // This is the code we need to implement: // // DelegateImpl[] invocationList = m_invocationList; // // if(invocationList == null) // { // res = Invoke( ... ); // } // else // { // int len = invocationList.Length; // // for(int i = 0; i < len; i++) // { // res = invocationList[i].Invoke( ... ); // } // } // // FieldRepresentation fdInvocationList = wkf.MulticastDelegateImpl_m_invocationList; FieldRepresentation fdTarget = wkf.DelegateImpl_m_target; FieldRepresentation fdCodePtr = wkf.DelegateImpl_m_codePtr; VariableExpression exInvocationList = cfg.AllocateTemporary( fdInvocationList.FieldType , null ); VariableExpression exInvocation = cfg.AllocateTemporary( fdInvocationList.FieldType.ContainedType, null ); VariableExpression exTarget = cfg.AllocateTemporary( fdTarget .FieldType , null ); VariableExpression exCodePtr = cfg.AllocateTemporary( fdCodePtr .FieldType , null ); VariableExpression exLen = cfg.AllocateTemporary( wkt.System_Int32 , null ); VariableExpression exPos = cfg.AllocateTemporary( wkt.System_Int32 , null ); VariableExpression exThis = cfg.Arguments[0]; //--// // // DelegateImpl[] invocationList = m_invocationList; // // if(invocationList == null) // { // // } // else // { // // } // NormalBasicBlock bbNull = new NormalBasicBlock( cfg ); NormalBasicBlock bbNotNull = new NormalBasicBlock( cfg ); bb.AddOperator( LoadInstanceFieldOperator.New( null, fdInvocationList, exInvocationList, exThis, true ) ); bb.FlowControl = BinaryConditionalControlOperator.New( null, exInvocationList, bbNull, bbNotNull ); //--// // // // // { // object target = m_target; // CodePtr codePtr = m_codePtr; // // if (target != null) // = IndirectCall(target, ); // else // = IndirectCall(); // } // NormalBasicBlock bbInstance = new NormalBasicBlock(cfg); NormalBasicBlock bbStatic = new NormalBasicBlock(cfg); bbNull.AddOperator(LoadInstanceFieldOperator.New(null, fdTarget, exTarget, exThis, true)); bbNull.AddOperator(LoadInstanceFieldOperator.New(null, fdCodePtr, exCodePtr, exThis, true)); bbNull.FlowControl = BinaryConditionalControlOperator.New(null, exTarget, bbStatic, bbInstance); rhs = new Expression[cfg.Arguments.Length + 1]; rhs[0] = exCodePtr; rhs[1] = exTarget; for(int i = 1; i < cfg.Arguments.Length; i++) { rhs[i+1] = cfg.Arguments[i]; } bbInstance.AddOperator(IndirectCallOperator.New(null, md, VariableExpression.ToArray(exReturnValue), rhs, true, false)); bbInstance.AddOperator(UnconditionalControlOperator.New(null, bbExit)); bbStatic.AddOperator(IndirectCallOperator.New(null, md, VariableExpression.ToArray(exReturnValue), rhs, false, false)); bbStatic.AddOperator(UnconditionalControlOperator.New(null, bbExit)); // // // // { // int len = invocationList.Length; // // for(int pos = 0; pos < len; pos++) // { // DelegateImpl invocation = invocationList[i]; // // res = invocation.Invoke( ... ); // } // } NormalBasicBlock bbNotNullCheck = new NormalBasicBlock(cfg); NormalBasicBlock bbNotNullInner = new NormalBasicBlock(cfg); NormalBasicBlock bbNotNullInstance = new NormalBasicBlock(cfg); NormalBasicBlock bbNotNullStatic = new NormalBasicBlock(cfg); NormalBasicBlock bbNotNullPost = new NormalBasicBlock(cfg); bbNotNull.AddOperator(ArrayLengthOperator.New(null, exLen, exInvocationList)); bbNotNull.AddOperator(SingleAssignmentOperator.New(null, exPos, m_typeSystem.CreateConstant(0))); bbNotNull.AddOperator(UnconditionalControlOperator.New(null, bbNotNullCheck)); bbNotNullCheck.AddOperator(CompareConditionalControlOperator.New(null, CompareAndSetOperator.ActionCondition.LT, true, exPos, exLen, bbExit, bbNotNullInner)); bbNotNullInner.AddOperator(LoadElementOperator.New(null, exInvocation, exInvocationList, exPos, null, true)); bbNotNullInner.AddOperator(LoadInstanceFieldOperator.New(null, fdTarget, exTarget, exInvocation, true)); bbNotNullInner.AddOperator(LoadInstanceFieldOperator.New(null, fdCodePtr, exCodePtr, exInvocation, true)); rhs = new Expression[cfg.Arguments.Length + 1]; rhs[0] = exCodePtr; rhs[1] = exTarget; for (int i = 1; i < cfg.Arguments.Length; i++) { rhs[i+1] = cfg.Arguments[i]; } bbNotNullInner.FlowControl = BinaryConditionalControlOperator.New(null, exTarget, bbNotNullStatic, bbNotNullInstance); bbNotNullInstance.AddOperator(IndirectCallOperator.New(null, md, VariableExpression.ToArray(exReturnValue), rhs, true, false)); bbNotNullInstance.AddOperator(UnconditionalControlOperator.New(null, bbNotNullPost)); bbNotNullStatic.AddOperator(IndirectCallOperator.New(null, md, VariableExpression.ToArray(exReturnValue), rhs, false, false)); bbNotNullStatic.AddOperator(UnconditionalControlOperator.New(null, bbNotNullPost)); bbNotNullPost.AddOperator(BinaryOperator.New(null, BinaryOperator.ALU.ADD, true, false, exPos, exPos, m_typeSystem.CreateConstant(1))); bbNotNullPost.AddOperator(UnconditionalControlOperator.New(null, bbNotNullCheck)); } else { var bb = cfg.CreateFirstNormalBasicBlock(); MethodRepresentation mdThrow = wkm.ThreadImpl_ThrowNotImplementedException; Expression[] rhs = m_typeSystem.AddTypePointerToArgumentsOfStaticMethod( mdThrow ); bb.AddOperator( StaticCallOperator.New( null, CallOperator.CallKind.Direct, mdThrow, rhs ) ); cfg.ExitBasicBlock.AddOperator( DeadControlOperator.New( null ) ); } } } } } ================================================ FILE: Zelig/Zelig/CompileTime/CodeGenerator/CodeTransformation/CompilationSteps/PhaseDrivers/ImplementInternalMethods_ExternalMethodStub.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // namespace Microsoft.Zelig.CodeGeneration.IR.CompilationSteps { using System; using System.Collections.Generic; using Microsoft.Zelig.Runtime.TypeSystem; using Microsoft.Zelig.Runtime; using Microsoft.Zelig.CodeGeneration.IR.Abstractions; public sealed partial class ImplementInternalMethods { // // Helper Methods // public static void InitializeExternalReferences() { ExternalCallContext.Reset(); } private void ImplementExternalMethodStub( MethodRepresentation md, TypeSystemForCodeTransformation typeSys ) { if (TypeSystemForCodeTransformation.GetCodeForMethod(md) == null) { ControlFlowGraphStateForCodeTransformation cfg = (ControlFlowGraphStateForCodeTransformation)m_typeSystem.CreateControlFlowGraphState( md ); var bb = cfg.CreateFirstNormalBasicBlock(); /// /// Leave an empty implemenation that will be filled only after the ComputeCallClosure phase is over. That way /// we do not add imported code that will not be used. /// // // Create proper flow control for exit basic block. // cfg.AddReturnOperator(); } } } } ================================================ FILE: Zelig/Zelig/CompileTime/CodeGenerator/CodeTransformation/CompilationSteps/PhaseDrivers/ImplementInternalMethods_ObjectEquals.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // namespace Microsoft.Zelig.CodeGeneration.IR.CompilationSteps { using System; using System.Collections.Generic; using Microsoft.Zelig.Runtime.TypeSystem; public sealed partial class ImplementInternalMethods { // // Helper Methods // private bool ImplementObjectEquals( MethodRepresentation md ) { if(TypeSystemForCodeTransformation.GetCodeForMethod( md ) == null) { ControlFlowGraphStateForCodeTransformation cfg = (ControlFlowGraphStateForCodeTransformation)m_typeSystem.CreateControlFlowGraphState( md ); var bb = cfg.CreateFirstNormalBasicBlock(); var bbExit = cfg.NormalizedExitBasicBlock; NormalBasicBlock bbTRUE = new NormalBasicBlock( cfg ); NormalBasicBlock bbFALSE = new NormalBasicBlock( cfg ); NormalBasicBlock bbNext; VariableExpression variable_return = cfg.ReturnValue; VariableExpression pThis = cfg.Arguments[0]; VariableExpression obj = cfg.Arguments[1]; TemporaryVariableExpression other; // // Create proper flow control for exit basic block. // cfg.AddReturnOperator(); // // Create TRUE branch. // bbTRUE.AddOperator( SingleAssignmentOperator .New( null, variable_return, m_typeSystem.CreateConstant( md.ReturnType, 1 ) ) ); bbTRUE.AddOperator( UnconditionalControlOperator.New( null, bbExit ) ); // // Create FALSE branch. // bbFALSE.AddOperator( SingleAssignmentOperator .New( null, variable_return, m_typeSystem.CreateConstant( md.ReturnType, 0 ) ) ); bbFALSE.AddOperator( UnconditionalControlOperator.New( null, bbExit ) ); //// ;;;91 if(!(obj is T)) //// ;;;91 ^ //// Op_4 : $other = Arg_1(obj) isinst BoxedValueTypeRepresentation(T) //// Op_6 : if $other != ZERO then goto $Next else goto $Label_FALSE //// bbNext = new NormalBasicBlock( cfg ); other = cfg.AllocateTemporary( pThis.Type, null ); bb.AddOperator( IsInstanceOperator.New( null, pThis.Type, other, obj ) ); bb.FlowControl = BinaryConditionalControlOperator.New( null, other, bbFALSE, bbNext ); bb = bbNext; foreach(FieldRepresentation fd in md.OwnerType.Fields) { if(fd is InstanceFieldRepresentation) { TypeRepresentation fdType = fd.FieldType; bbNext = new NormalBasicBlock( cfg ); if(fdType is ScalarTypeRepresentation || fdType is ReferenceTypeRepresentation || fdType is PointerTypeRepresentation ) { //// $pThisField <= [Arg_0(this), InstanceFieldRepresentation(fd)] //// $otherField <= [$other, InstanceFieldRepresentation(fd)] //// if $pThisField EQ.unsigned $otherField then goto $Label_FALSE else goto $Next TemporaryVariableExpression pThisField = cfg.AllocateTemporary( fdType, null ); TemporaryVariableExpression otherField = cfg.AllocateTemporary( fdType, null ); bb.AddOperator( LoadInstanceFieldOperator.New( null, fd, pThisField, pThis, true ) ); bb.AddOperator( LoadInstanceFieldOperator.New( null, fd, otherField, other, true ) ); bb.AddOperator( CompareConditionalControlOperator.New( null, CompareAndSetOperator.ActionCondition.EQ, false, pThisField, otherField, bbFALSE, bbNext ) ); } //// else if(fdType is ValueTypeRepresentation) //// { //// ManagedPointerTypeRepresentation fdTypeAddr = m_typeSystem.GetManagedPointerToType( fdType ); //// TemporaryVariableExpression tmp = cfg.AllocateTemporary( m_typeSystem.WellKnownTypes.System_Int32 ); //// TemporaryVariableExpression pThisFieldAddr = cfg.AllocateTemporary( fdTypeAddr ); //// TemporaryVariableExpression otherFieldAddr = cfg.AllocateTemporary( fdTypeAddr ); //// //// bb.AddOperator( LoadInstanceFieldAddressOperator.New( null, fd, pThisFieldAddr, pThis ) ); //// bb.AddOperator( LoadInstanceFieldAddressOperator.New( null, fd, otherFieldAddr, other ) ); //// //// bb.AddOperator( InstanceCallOperator.New( null, CallOperator.CallKind.Virtual, m_typeSystem.WellKnownMethods.Object_Equals, tmp, new Expression[] { pThisFieldAddr, otherFieldAddr } ) ); //// bb.AddOperator( BinaryConditionalControlOperator.New( null, tmp, bbFALSE, bbNext ) ); //// } else { bb.AddOperator( UnconditionalControlOperator.New( null, bbNext ) ); //throw TypeConsistencyErrorException.Create( "Don't know how to generate comparison code for field {0}", fd ); } bb = bbNext; } } bb.AddOperator( UnconditionalControlOperator.New( null, bbTRUE ) ); return false; } return true; } } } ================================================ FILE: Zelig/Zelig/CompileTime/CodeGenerator/CodeTransformation/CompilationSteps/PhaseDrivers/ImplementInternalMethods_SingletonFactory.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // namespace Microsoft.Zelig.CodeGeneration.IR.CompilationSteps { using System; using System.Collections.Generic; using Microsoft.Zelig.Runtime.TypeSystem; public sealed partial class ImplementInternalMethods { // // Helper Methods // private void ImplementSingletonFactory( MethodRepresentation md , CustomAttributeRepresentation ca ) { if(TypeSystemForCodeTransformation.GetCodeForMethod( md ) == null) { ControlFlowGraphStateForCodeTransformation cfg = (ControlFlowGraphStateForCodeTransformation)m_typeSystem.CreateControlFlowGraphState( md ); VariableExpression dst = cfg.ReturnValue; TypeRepresentation target = dst.Type; if((target.Flags & TypeRepresentation.Attributes.Sealed) == 0) { TypeRepresentation targetDirect; if(m_typeSystem.ForcedDevirtualizations.TryGetValue( target, out targetDirect )) { target = targetDirect; } else { // // BUGBUG: This is valid only if we are in bounded application mode!!! // List< TypeRepresentation > lst = m_typeSystem.CollectConcreteImplementations( target ); switch(lst.Count) { case 0: throw TypeConsistencyErrorException.Create( "Found singleton factory that refers to a type with no concrete subclasses: {0}", target.FullName ); case 1: target = lst[ 0 ]; break; default: // // if we have more than one // var mostDerived = new TypeSystemForCodeTransformation.LinearHierarchyBuilder( lst, m_typeSystem ).Build(); if( mostDerived != null ) { target = lst[ 0 ]; break; } throw TypeConsistencyErrorException.Create( "Found singleton factory that refers to a type with multiple concrete subclasses: {0}", target.FullName ); } } } //--// // // Prepare method body // var bb = cfg.CreateFirstNormalBasicBlock(); md.BuildTimeFlags &= ~MethodRepresentation.BuildTimeAttributes.NoInline; md.BuildTimeFlags |= MethodRepresentation.BuildTimeAttributes.Inline; // // Create proper flow control for exit basic block. // cfg.AddReturnOperator(); //--// DataManager.Attributes attrib; if(ca.HasNamedArg( "ReadOnly" )) { attrib = DataManager.Attributes.Constant; } else { attrib = DataManager.Attributes.Mutable; } attrib |= DataManager.Attributes.SuitableForConstantPropagation; //--// CustomAttributeRepresentation caMemoryMapped; Expression ex; Annotation an = null; if(m_typeSystem.MemoryMappedPeripherals.TryGetValue( target, out caMemoryMapped )) { object baseObj = caMemoryMapped.GetNamedArg( "Base" ); if(baseObj == null) { throw TypeConsistencyErrorException.Create( "Found MemoryMappedPeripheral with singleton factory and no Base address: {0}", target.FullName ); } uint baseAddress = (uint)baseObj; ex = m_typeSystem.CreateConstant( target, baseAddress ); an = MemoryMappedPeripheralAnnotation.Create( m_typeSystem, caMemoryMapped ); } else { ex = m_typeSystem.GenerateConstantForSingleton( target, attrib ); } var opNew = SingleAssignmentOperator.New( null, dst, ex ); opNew.AddAnnotation( NotNullAnnotation.Create( m_typeSystem ) ); if(an != null) { opNew.AddAnnotation( an ); } bb.AddOperator( opNew ); } } } } ================================================ FILE: Zelig/Zelig/CompileTime/CodeGenerator/CodeTransformation/CompilationSteps/PhaseDrivers/OptimizationsPhaseExecution.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // #define OPTIMIZATION_REPORT_SLOW_METHODS namespace Microsoft.Zelig.CodeGeneration.IR.CompilationSteps { using System; using System.Collections.Generic; using Microsoft.Zelig.Runtime.TypeSystem; public sealed class OptimizationsPhaseExecution : SingleMethodPhaseExecution { class State { // // State // private GrowOnlySet< OptimizationHandlerAttribute > m_dontExecute; //--// internal bool CanExecute( OptimizationHandlerAttribute ca ) { if(m_dontExecute != null) { if(m_dontExecute.Contains( ca )) { return false; } } return true; } internal void SetAsDontExecute( OptimizationHandlerAttribute ca ) { if(m_dontExecute == null) { m_dontExecute = SetFactory.NewWithReferenceEquality< OptimizationHandlerAttribute >(); } m_dontExecute.Insert( ca ); } } // // State // private GrowOnlyHashTable< MethodRepresentation, State > m_methods; private OptimizationHandlerAttribute[] m_order; // // Constructor Methods // public OptimizationsPhaseExecution( TypeSystemForCodeTransformation typeSystem , DelegationCache cache , CallsDataBase callsDatabase , PhaseDriver phase ) : base( typeSystem, cache, callsDatabase, phase ) { m_methods = HashTableFactory.NewWithReferenceEquality< MethodRepresentation, State >(); m_order = new OptimizationHandlerAttribute[0]; //--// CompileOrder(); } // // Helper Methods // public override void Analyze( MethodRepresentation md ) { ControlFlowGraphStateForCodeTransformation cfg = TypeSystemForCodeTransformation.GetCodeForMethod( md ); if(cfg != null) { State state; if(m_methods.TryGetValue( md, out state ) == false) { state = new State(); m_methods[md] = state; } NotificationContext nc = new NotificationContext( this ); nc.CurrentMethod = md; nc.CurrentCFG = cfg; #if OPTIMIZATION_REPORT_SLOW_METHODS System.Diagnostics.Stopwatch sw = new System.Diagnostics.Stopwatch(); sw.Start(); int iterations = 0; int iterations_SSA_In = 0; int iterations_SSA_Out = 0; int iterations_SSA_Undo = 0; #endif while(true) { #if OPTIMIZATION_REPORT_SLOW_METHODS iterations++; #endif nc.StartScan(); foreach(OptimizationHandlerAttribute ca in m_order) { if(state.CanExecute( ca )) { if(ca.RunInExtendedSSAForm) { #if OPTIMIZATION_REPORT_SLOW_METHODS iterations_SSA_In++; #endif Transformations.StaticSingleAssignmentForm.InsertPiOperators( cfg ); Transformations.StaticSingleAssignmentForm.ConvertInto( cfg ); } else if(ca.RunInSSAForm) { #if OPTIMIZATION_REPORT_SLOW_METHODS iterations_SSA_In++; #endif Transformations.StaticSingleAssignmentForm.RemovePiOperators( cfg ); Transformations.StaticSingleAssignmentForm.ConvertInto( cfg ); } else if(ca.RunInNormalForm) { #if OPTIMIZATION_REPORT_SLOW_METHODS iterations_SSA_Out++; #endif Transformations.StaticSingleAssignmentForm.ConvertOut( cfg, true ); } Transformations.RemoveDeadCode.Execute( cfg, false ); NotificationOfTransformation dlg = m_delegationForOptimization[ca]; cfg.TraceToFile( "Optimization-Pre - " + dlg.Method ); dlg( nc ); cfg.TraceToFile( "Optimization-Post" ); if(Transformations.StaticSingleAssignmentForm.ShouldTransformInto( cfg )) { #if OPTIMIZATION_REPORT_SLOW_METHODS iterations_SSA_Undo++; #endif // // Since the graph is no longer in SSA form, it's best to properly convert it out. // Transformations.StaticSingleAssignmentForm.ConvertOut( cfg, true ); } if(ca.RunOnce) { state.SetAsDontExecute( ca ); } if(nc.CanContinue == false) break; } } if(nc.CanContinue) { break; } } #if OPTIMIZATION_REPORT_SLOW_METHODS sw.Stop(); if(sw.ElapsedMilliseconds >= 1500) { Console.WriteLine( "NOTICE: Optimizations for method '{0}' took {1} milliseconds and {2} iterations! [{3} variables and {4} operators]", cfg.Method.ToShortString(), sw.ElapsedMilliseconds, iterations, cfg.DataFlow_SpanningTree_Variables.Length, cfg.DataFlow_SpanningTree_Operators.Length ); Console.WriteLine( "NOTICE: SSA In = {0}, SSA Out = {1}, SSA Undo = {2}", iterations_SSA_In, iterations_SSA_Out, iterations_SSA_Undo ); Console.WriteLine(); } #endif } } //--// private void CompileOrder() { foreach(OptimizationHandlerAttribute ca in m_delegationForOptimization.Keys) { if(ca.RunBefore != null) { OptimizationHandlerAttribute ca2 = FindTarget( ca, ca.RunBefore ); if(ca2 == null) { throw TypeConsistencyErrorException.Create( "Cannot find optimization '{0}', needed for proper sequencing of {1}", ca.RunBefore, m_delegationForOptimization[ca].Method ); } ca.caToRunAfterThis = ca2; } if(ca.RunAfter != null) { OptimizationHandlerAttribute ca2 = FindTarget( ca, ca.RunAfter ); if(ca2 == null) { throw TypeConsistencyErrorException.Create( "Cannot find optimization '{0}', needed for proper sequencing of {1}", ca.RunAfter, m_delegationForOptimization[ca].Method ); } ca.caToRunBeforeThis = ca2; } } foreach(OptimizationHandlerAttribute ca in m_delegationForOptimization.Keys) { if(ArrayUtility.FindReferenceInNotNullArray( m_order, ca ) < 0) { if(ca.caToRunBeforeThis != null) { if(ArrayUtility.FindReferenceInNotNullArray( m_order, ca.caToRunBeforeThis ) < 0) { m_order = ArrayUtility.AppendToNotNullArray( m_order, ca.caToRunBeforeThis ); } } if(ca.caToRunAfterThis != null) { int pos = ArrayUtility.FindReferenceInNotNullArray( m_order, ca.caToRunAfterThis ); if(pos >= 0) { m_order = ArrayUtility.InsertAtPositionOfNotNullArray( m_order, pos, ca ); continue; } } m_order = ArrayUtility.AppendToNotNullArray( m_order, ca ); } } // // Ensure we have the correct ordering. // for(int pos = 0; pos < m_order.Length; pos++) { OptimizationHandlerAttribute ca = m_order[pos]; if(ca.caToRunAfterThis != null && ArrayUtility.FindReferenceInNotNullArray( m_order, ca.caToRunAfterThis ) < pos) { throw TypeConsistencyErrorException.Create( "Cannot find scheduling to put {0} after {1}", m_delegationForOptimization[ca].Method, m_delegationForOptimization[ca.caToRunAfterThis].Method ); } if(ca.caToRunBeforeThis != null && ArrayUtility.FindReferenceInNotNullArray( m_order, ca.caToRunBeforeThis ) > pos) { throw TypeConsistencyErrorException.Create( "Cannot find scheduling to put {0} before {1}", m_delegationForOptimization[ca].Method, m_delegationForOptimization[ca.caToRunBeforeThis].Method ); } } } private OptimizationHandlerAttribute FindTarget( OptimizationHandlerAttribute caSource , string id ) { int pos = id.IndexOf( '.' ); string nameType; string nameMethod; if(pos < 0) { nameType = m_delegationForOptimization[caSource].Method.DeclaringType.Name; nameMethod = id; } else { nameType = id.Substring( 0, pos ); nameMethod = id.Substring( pos+1 ); } foreach(OptimizationHandlerAttribute ca in m_delegationForOptimization.Keys) { if(ca != caSource) { NotificationOfTransformation dlg = m_delegationForOptimization[ca]; System.Reflection.MethodInfo mi = dlg.Method; if(nameMethod == mi. Name && nameType == mi.DeclaringType.Name ) { return ca; } } } return null; } //--// // // Access Methods // } } ================================================ FILE: Zelig/Zelig/CompileTime/CodeGenerator/CodeTransformation/CompilationSteps/PhaseDrivers/ParallelTransformationsHandler.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // #define USE_THREAD_POOL namespace Microsoft.Zelig.CodeGeneration.IR.CompilationSteps { using System; using System.Collections.Generic; using Microsoft.Zelig.Runtime.TypeSystem; using System.Threading; public class ParallelTransformationsHandler : IDisposable { public delegate void NotificationCallback( Operation phase, MethodRepresentation md, ref object state ); public enum Operation { Initialize, Execute, Shutdown, } internal class Worker { // // State // private ParallelTransformationsHandler m_owner; private volatile MethodRepresentation m_md; private List< Exception > m_errors; private object m_state; #if !USE_THREAD_POOL private System.Threading.Thread m_thread; #endif private System.Threading.AutoResetEvent m_waitForRequest; // // Constructor Methods // internal Worker( ParallelTransformationsHandler owner ) { m_owner = owner; m_errors = new List< Exception >(); m_state = null; #if !USE_THREAD_POOL m_thread = new System.Threading.Thread( Execute ); #endif m_waitForRequest = new System.Threading.AutoResetEvent( false ); //--// #if USE_THREAD_POOL ThreadPool.QueueUserWorkItem( Execute ); #else m_thread.Priority = System.Threading.ThreadPriority.BelowNormal; m_thread.IsBackground = true; m_thread.Start(); #endif } // // Helper Methods // internal void Post( MethodRepresentation md ) { m_md = md; m_waitForRequest.Set(); } internal void Stop() { m_md = null; m_waitForRequest.Set(); #if !USE_THREAD_POOL m_thread.Join(); #endif if(m_errors.Count > 0) { throw new Exception( "Delivering exception from worker thread", m_errors[0] ); } } //--// private void Execute(object state) { lock(m_owner.m_availableWorkers) { Notify( Operation.Initialize, null ); } while(true) { lock(m_owner.m_availableWorkers) { m_owner.m_availableWorkers.Enqueue( this ); } m_owner.m_availableSemaphore.Release(); m_waitForRequest.WaitOne(); MethodRepresentation md = m_md; if(md == null) { break; } try { using(ControlFlowGraphState.LockThreadToMethod( md )) { Notify( Operation.Execute, md ); if(m_owner.m_mdCallback != null) { m_owner.m_mdCallback( md ); } if(m_owner.m_cfgCallback != null) { ControlFlowGraphStateForCodeTransformation cfg = TypeSystemForCodeTransformation.GetCodeForMethod( md ); if(cfg != null) { m_owner.m_cfgCallback( cfg ); } } } } catch(Exception ex) { m_errors.Add( ex ); } } lock(m_owner.m_availableWorkers) { Notify( Operation.Shutdown, null ); } } private void Notify( Operation phase , MethodRepresentation md ) { if(m_owner.m_notificationCallback != null) { m_owner.m_notificationCallback( phase, md, ref m_state ); } } } // // State // static int s_maximumNumberOfProcessorsToUse = int.MaxValue; //--// MethodEnumerationCallback m_mdCallback; ControlFlowGraphEnumerationCallback m_cfgCallback; NotificationCallback m_notificationCallback; int m_procs; Worker[] m_workers; System.Threading.Semaphore m_availableSemaphore; Queue< Worker > m_availableWorkers; // // Constructor Methods // public ParallelTransformationsHandler( MethodEnumerationCallback callback ) : this( callback, null, null ) { } public ParallelTransformationsHandler( ControlFlowGraphEnumerationCallback callback ) : this( null, callback, null ) { } public ParallelTransformationsHandler( MethodEnumerationCallback mdCallback , ControlFlowGraphEnumerationCallback cfgCallback , NotificationCallback notificationCallback ) { int procs = (int)BitVector.CountBits( (uint)(System.Diagnostics.Process.GetCurrentProcess().ProcessorAffinity.ToInt32()) ) + 1; if(procs > s_maximumNumberOfProcessorsToUse) procs = s_maximumNumberOfProcessorsToUse; if(procs < 1 ) procs = 1; //--// m_mdCallback = mdCallback; m_cfgCallback = cfgCallback; m_notificationCallback = notificationCallback; m_procs = procs; m_workers = new Worker[procs]; m_availableSemaphore = new System.Threading.Semaphore( 0, (int)procs ); m_availableWorkers = new Queue< Worker >(); for(int idx = 0; idx < procs; idx++) { m_workers[idx] = new Worker( this ); } } // // Helper Methods // public void Queue( MethodRepresentation md ) { CHECKS.ASSERT( md != null, "Expecting method argument" ); m_availableSemaphore.WaitOne(); Worker worker; lock(m_availableWorkers) { worker = m_availableWorkers.Dequeue(); } worker.Post( md ); } public void Synchronize() { for(int idx = 0; idx < m_procs; idx++) { m_availableSemaphore.WaitOne(); } m_availableSemaphore.Release( m_procs ); } public void Shutdown() { for(int idx = 0; idx < m_procs; idx++) { m_availableSemaphore.WaitOne(); Worker worker; lock(m_availableWorkers) { worker = m_availableWorkers.Dequeue(); } worker.Stop(); } } //--// void IDisposable.Dispose() { Shutdown(); } //--// public static void EnumerateMethods( TypeSystemForCodeTransformation typeSystem , NotificationCallback callback ) { using(ParallelTransformationsHandler handler = new ParallelTransformationsHandler( null, null, callback )) { typeSystem.EnumerateMethods( handler.EnumerationCallback ); } } public static void EnumerateMethods( TypeSystemForCodeTransformation typeSystem , MethodEnumerationCallback callback ) { using(ParallelTransformationsHandler handler = new ParallelTransformationsHandler( callback )) { typeSystem.EnumerateMethods( handler.EnumerationCallback ); } } public static void EnumerateFlowGraphs( TypeSystemForCodeTransformation typeSystem , ControlFlowGraphEnumerationCallback callback ) { using(ParallelTransformationsHandler handler = new ParallelTransformationsHandler( callback )) { typeSystem.EnumerateMethods( handler.EnumerationCallback ); } } //--// private void EnumerationCallback( MethodRepresentation md ) { this.Queue( md ); } // // Access Methods // public static int MaximumNumberOfProcessorsToUse { get { return s_maximumNumberOfProcessorsToUse; } set { s_maximumNumberOfProcessorsToUse = value; } } } } ================================================ FILE: Zelig/Zelig/CompileTime/CodeGenerator/CodeTransformation/CompilationSteps/PhaseDrivers/PhaseDriver.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // namespace Microsoft.Zelig.CodeGeneration.IR.CompilationSteps { using System; using System.Collections.Generic; using Microsoft.Zelig.Runtime.TypeSystem; public abstract class PhaseDriver { public delegate void Notification( PhaseDriver host, TypeSystemForCodeTransformation typeSystem ); // // State // internal LinkedListNode< PhaseDriver > m_node; protected Controller m_context; protected Notification m_delegationForPhase_Before; protected Notification m_delegationForPhase_After; // // Constructor Methods // protected PhaseDriver( Controller context ) { m_context = context; } public bool Disabled { get; set; } // // Helper Methods // public static int CompareOrder( PhaseDriver phase , Type type ) { if(phase == null) { return -1; } var phaseTarget = phase.FindPhaseByType( type ); if(phaseTarget == null) { return 1; } return phase.PhaseIndex.CompareTo( phaseTarget.PhaseIndex ); } public int ComparePositionTo() where T : PhaseDriver { PhaseDriver target = FindPhase(); return this.PhaseIndex.CompareTo( target.PhaseIndex ); } public T FindPhase< T >() where T : PhaseDriver { return (T)FindPhaseByType( typeof(T) ); } public PhaseDriver FindPhaseByType( Type type ) { if(m_node != null) { foreach(var phase in m_node.List) { if(phase.GetType() == type) { return phase; } } } return null; } //--// public void RegisterForNotification( Notification target , bool fFirst ) { if(fFirst) { m_delegationForPhase_Before += target; } else { m_delegationForPhase_After += target; } } //--// public PhaseDriver Execute() { ControlFlowGraphStateForCodeTransformation.SetPhaseForTrace( this ); this.DelegationCache.HookNotifications( this.TypeSystem, this ); { var dlg = m_delegationForPhase_Before; if(dlg != null) { m_delegationForPhase_Before = null; dlg( this, this.TypeSystem ); } } var res = Run(); { var dlg = m_delegationForPhase_After; if(dlg != null) { m_delegationForPhase_After = null; dlg( this, this.TypeSystem ); } } return res; } public abstract PhaseDriver Run(); //--// protected void ValidateAbstractionLevel( Operator.OperatorLevel maxLevel ) { var phase = this; while(phase != null) { var attrib = ReflectionHelper.GetAttribute< PhaseLimitAttribute >( phase, true ); if(attrib != null && attrib.Level < maxLevel) { // LT72: mask inconsistencies to cope with missign optimizations // throw TypeConsistencyErrorException.Create("Found operator at level {0} when limit was {1}", maxLevel, attrib.Level); // LT72: log instead of throwing exception Console.WriteLine(String.Format("Found operator at level {0} when limit was {1}", maxLevel, attrib.Level)); Console.WriteLine(); } phase = phase.PreviousPhase; } } public virtual void ValidatePhaseMovement( PhaseDriver prevPhase , PhaseDriver nextPhase ) { var attrib = ReflectionHelper.GetAttribute< PhaseOrderingAttribute >( this, true ); if(attrib != null) { if(attrib.IsPipelineBlock && prevPhase.PhaseIndex > this.PhaseIndex) { if(nextPhase.PhaseIndex < this.PhaseIndex) { throw TypeConsistencyErrorException.Create( "Detected attempt to move past a pipeline block: {0} < {1}", nextPhase.GetType().FullName, this.GetType().FullName ); } } } } internal Operator.OperatorLevel ValidateOperatorLevels( ControlFlowGraphStateForCodeTransformation cfg ) { Operator.OperatorLevel limit = this.MaximumAllowedLevel; Operator.OperatorLevel max = Operator.OperatorLevel.Lowest; var ts = this.TypeSystem; foreach(Operator op in cfg.DataFlow_SpanningTree_Operators) { Operator.OperatorLevel level = ts.GetLevel( op ); if(max < level) { max = level; } if(level > limit) { // LT72: mask inconsistencies to cope with missign optimizations // throw TypeConsistencyErrorException.Create( "Found operator at level {0} when limit was {1}: {2}", level, limit, op ); // LT72: log instead of throwing exception Console.WriteLine(String.Format("Found operator at level {0} when limit was {1}: {2}", level, limit, op)); Console.WriteLine(); } } return max; } //--// protected void PerformSequentialExecutionOfPhase( bool fInline , bool fExcludeGenericEntities ) { var rpe = new SingleMethodPhaseExecution( this.TypeSystem, this.DelegationCache, this.CallsDataBase, this ); if(fInline) { this.CallsDataBase.ResetCallSites(); } this.TypeSystem.EnumerateMethods( delegate( MethodRepresentation md ) { if(fExcludeGenericEntities) { if(md.IsOpenMethod || md.OwnerType.IsOpenType) { return; } } rpe.Analyze( md ); } ); if(fInline) { while(true) { this.CallsDataBase.AnalyzeForInlining(); GrowOnlySet< ControlFlowGraphStateForCodeTransformation > touched = this.CallsDataBase.ExecuteInlining( this.TypeSystem ); if(touched.Count == 0) { break; } foreach(ControlFlowGraphStateForCodeTransformation cfg in touched) { rpe.Analyze( cfg.Method ); } } } ValidateAbstractionLevel( rpe.MaxAbstractionLevelEncountered ); } protected void PerformParallelExecutionOfPhase( bool fInline , bool fExcludeGenericEntities ) { var maxLevel = Operator.OperatorLevel.Lowest; if(fInline) { this.CallsDataBase.ResetCallSites(); } ParallelTransformationsHandler.EnumerateMethods( this.TypeSystem, delegate( ParallelTransformationsHandler.Operation phase, MethodRepresentation md, ref object state ) { var rpe = (SingleMethodPhaseExecution)state; switch(phase) { case ParallelTransformationsHandler.Operation.Initialize: state = new SingleMethodPhaseExecution( this.TypeSystem, this.DelegationCache, this.CallsDataBase, this ); break; case ParallelTransformationsHandler.Operation.Execute: if(fExcludeGenericEntities) { if(md.IsOpenMethod || md.OwnerType.IsOpenType) { break; } } rpe.Analyze( md ); break; case ParallelTransformationsHandler.Operation.Shutdown: if(maxLevel < rpe.MaxAbstractionLevelEncountered) { maxLevel = rpe.MaxAbstractionLevelEncountered; } break; } } ); if(fInline) { while(true) { this.CallsDataBase.AnalyzeForInlining(); var touched = this.CallsDataBase.ExecuteInlining( this.TypeSystem ); if(touched.Count == 0) { break; } ParallelTransformationsHandler.EnumerateMethods( this.TypeSystem, delegate( ParallelTransformationsHandler.Operation phase, MethodRepresentation md, ref object state ) { var rpe = (SingleMethodPhaseExecution)state; switch(phase) { case ParallelTransformationsHandler.Operation.Initialize: state = new SingleMethodPhaseExecution( this.TypeSystem, this.DelegationCache, this.CallsDataBase, this ); break; case ParallelTransformationsHandler.Operation.Execute: var cfg = TypeSystemForCodeTransformation.GetCodeForMethod( md ); if(cfg != null && touched.Contains( cfg )) { rpe.Analyze( md ); } break; case ParallelTransformationsHandler.Operation.Shutdown: if(maxLevel < rpe.MaxAbstractionLevelEncountered) { maxLevel = rpe.MaxAbstractionLevelEncountered; } break; } } ); } } ValidateAbstractionLevel( maxLevel ); } // // Debug Methods // public override string ToString() { return this.GetType().Name; } // // Access Methods // public int PhaseIndex { get { int index = 0; for(var phase = this; phase.PreviousPhase != null; phase = phase.PreviousPhase) { index++; } return index; } } public PhaseDriver PreviousPhase { get { if(m_node != null) { var prev = m_node.Previous; if(prev != null) { return prev.Value; } } return null; } } public PhaseDriver NextPhase { get { if(m_node != null) { var next = m_node.Next; if(next != null) { return next.Value; } } return null; } } public Type ExecuteBefore { get { var attrib = ReflectionHelper.GetAttribute< PhaseOrderingAttribute >( this, true ); return attrib != null ? attrib.ExecuteBefore : null; } } public Type ExecuteAfter { get { var attrib = ReflectionHelper.GetAttribute< PhaseOrderingAttribute >( this, true ); return attrib != null ? attrib.ExecuteAfter : null; } } protected TypeSystemForCodeTransformation TypeSystem { get { return m_context.TypeSystem; } } public CallsDataBase CallsDataBase { get { return m_context.CallsDatabase; } } protected DelegationCache DelegationCache { get { return this.TypeSystem.GetEnvironmentService< DelegationCache >(); } } protected Operator.OperatorLevel MaximumAllowedLevel { get { var attrib = ReflectionHelper.GetAttribute< PhaseLimitAttribute >( this, true ); if(attrib != null) { return attrib.Level; } var prev = this.PreviousPhase; if(prev != null) { return prev.MaximumAllowedLevel; } return Operator.OperatorLevel.Highest; } } } } ================================================ FILE: Zelig/Zelig/CompileTime/CodeGenerator/CodeTransformation/CompilationSteps/PhaseDrivers/PhaseExecution.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // #define REPORT_SLOW_METHODS namespace Microsoft.Zelig.CodeGeneration.IR.CompilationSteps { using System; using System.Collections.Generic; using Microsoft.Zelig.Runtime.TypeSystem; public abstract class PhaseExecution { public delegate void NotificationOfTransformation ( NotificationContext nc ); public delegate void NotificationOfTransformationForAttribute( NotificationContext nc, CustomAttributeRepresentation ca ); //--// public class NotificationContext { [Flags] enum NotificationStatus { Active = 0x00000000, Skip = 0x00000001, // Don't invoke any other delegate for this operator. Stop = 0x00000002, // Don't invoke any delegates at all. Modified = 0x00000004, // The CFG has been touched. } // // State // private readonly PhaseExecution m_owner; private NotificationStatus m_status; public MethodRepresentation CurrentMethod; public ControlFlowGraphStateForCodeTransformation CurrentCFG; public Operator CurrentOperator; public object Value; // // Constructor Methods // internal NotificationContext( PhaseExecution owner ) { m_owner = owner; } // // Helper methods // internal void StartScan() { m_status = NotificationStatus.Active; } internal void ClearSkip() { m_status &= ~NotificationStatus.Skip; } public void StopScan() { m_status = NotificationStatus.Stop; } public void MarkAsModified() { m_status |= NotificationStatus.Skip | NotificationStatus.Modified; } //--// public void SetMaxAbstractionLevelEncountered( Operator.OperatorLevel level ) { if(m_owner.m_maxAbstractionLevelEncountered < level) { m_owner.m_maxAbstractionLevelEncountered = level; } } public CallOperator GetOperatorAndThrowIfNotCall() { CallOperator op = this.CurrentOperator as CallOperator; if(op == null) { throw TypeConsistencyErrorException.Create( "'{0}' cannot be used with {1}, it's a restricted method", this.Value, this.CurrentOperator ); } return op; } public TemporaryVariableExpression AllocateTemporary( TypeRepresentation td ) { return this.CurrentCFG.AllocateTemporary( td, null ); } //--// public bool IsParameterConstant( CallOperator op , int index ) { var ex = op.Arguments[index]; var exConst = ex as ConstantExpression; return (exConst != null); } public uint ExtractConstantUIntParameter( CallOperator op , int index ) { var ex = op.Arguments[index]; var exConst = ex as ConstantExpression; if(exConst != null) { ulong val; if(exConst.GetAsUnsignedInteger( out val )) { return (uint)val; } } throw TypeConsistencyErrorException.Create( "Expecting integer constant for {0}-th parameter in call to {1}, got {2}", index + 1, op.TargetMethod.ToShortString(), ex ); } public int ExtractConstantIntParameter( CallOperator op , int index ) { var ex = op.Arguments[index]; var exConst = ex as ConstantExpression; if(exConst != null) { long val; if(exConst.GetAsSignedInteger( out val )) { return (int)val; } } throw TypeConsistencyErrorException.Create( "Expecting integer constant for {0}-th parameter in call to {1}, got {2}", index + 1, op.TargetMethod.ToShortString(), ex ); } public bool ExtractConstantBoolParameter( CallOperator op , int index ) { var ex = op.Arguments[index]; var exConst = ex as ConstantExpression; if(exConst != null) { ulong val; if(exConst.GetAsUnsignedInteger( out val )) { return val != 0; } } throw TypeConsistencyErrorException.Create( "Expecting boolean constant for {0}-th parameter in call to {1}, got {2}", index + 1, op.TargetMethod.ToShortString(), ex ); } public PhysicalRegisterExpression GetVariableForRegisterEncoding( uint encoding ) { return GetVariableForRegisterEncoding( this.TypeSystem.WellKnownTypes.System_UIntPtr, encoding ); } public PhysicalRegisterExpression GetVariableForRegisterEncoding( TypeRepresentation td , uint encoding ) { return this.CurrentCFG.AllocateTypedPhysicalRegister( td, this.TypeSystem.PlatformAbstraction.GetRegisterForEncoding( encoding ), null, null, 0 ); } //--// // // Access methods // public TypeSystemForCodeTransformation TypeSystem { get { return m_owner.m_typeSystem; } } public PhaseDriver Phase { get { return m_owner.m_phase; } } public bool CanContinue { get { return m_status == NotificationStatus.Active; } } public bool ShouldSkip { get { return (m_status & NotificationStatus.Skip) != 0; } } public bool ShouldStop { get { return (m_status & NotificationStatus.Stop) != 0; } } public bool WasModified { get { return (m_status & NotificationStatus.Modified) != 0; } } } protected class NotificationIssuer { List< NotificationOfTransformation > m_list; internal NotificationIssuer() { m_list = new List< NotificationOfTransformation >(); } internal void Add( NotificationOfTransformation dlg ) { if(m_list.Contains( dlg ) == false) { m_list.Add( dlg ); } } internal bool Invoke( NotificationContext nc ) { if(nc.ShouldSkip) return false; foreach(NotificationOfTransformation dlg in m_list) { if(nc.CurrentCFG != null) { nc.CurrentCFG.TraceToFile( dlg ); } dlg( nc ); if(nc.ShouldSkip) return false; if(nc.ShouldStop) return false; } return true; } } // // State // protected TypeSystemForCodeTransformation m_typeSystem; protected DelegationCache m_cache; protected CallsDataBase m_callsDatabase; protected PhaseDriver m_phase; protected Operator.OperatorLevel m_maxAbstractionLevelEncountered; private NotificationIssuer m_delegationForFlowGraph_Before; private NotificationIssuer m_delegationForFlowGraph_After; private GrowOnlyHashTable< BaseRepresentation , NotificationIssuer > m_delegationForEntities; private GrowOnlyHashTable< MethodRepresentation , NotificationIssuer > m_delegationForCallEntities; private GrowOnlyHashTable< Type , NotificationIssuer > m_delegationForOperators; private GrowOnlyHashTable< Type , NotificationIssuer > m_delegationForArguments; protected GrowOnlyHashTable< OptimizationHandlerAttribute, NotificationOfTransformation > m_delegationForOptimization; private GrowOnlySet < Operator > m_operatorNotificationHistory; // // Constructor Methods // public PhaseExecution( TypeSystemForCodeTransformation typeSystem , DelegationCache cache , CallsDataBase callsDatabase , PhaseDriver phase ) { m_typeSystem = typeSystem; m_cache = cache; m_callsDatabase = callsDatabase; m_phase = phase; m_maxAbstractionLevelEncountered = Operator.OperatorLevel.Lowest; m_delegationForFlowGraph_Before = new NotificationIssuer(); m_delegationForFlowGraph_After = new NotificationIssuer(); m_delegationForEntities = HashTableFactory.NewWithReferenceEquality< BaseRepresentation , NotificationIssuer >(); m_delegationForCallEntities = HashTableFactory.NewWithReferenceEquality< MethodRepresentation , NotificationIssuer >(); m_delegationForOperators = HashTableFactory.NewWithReferenceEquality< Type , NotificationIssuer >(); m_delegationForArguments = HashTableFactory.NewWithReferenceEquality< Type , NotificationIssuer >(); m_delegationForOptimization = HashTableFactory.NewWithReferenceEquality< OptimizationHandlerAttribute, NotificationOfTransformation >(); m_operatorNotificationHistory = SetFactory .NewWithReferenceEquality< Operator >(); //--// cache.HookNotifications( typeSystem, this, phase ); } // // Helper Methods // protected void AnalyzeMethod( MethodRepresentation md ) { NotificationContext nc = new NotificationContext( this ); nc.CurrentMethod = md; nc.CurrentCFG = TypeSystemForCodeTransformation.GetCodeForMethod( md ); #if REPORT_SLOW_METHODS System.Diagnostics.Stopwatch sw = new System.Diagnostics.Stopwatch(); sw.Start(); int iterations = 0; #endif using(new PerformanceCounters.ContextualTiming( nc.CurrentCFG, "AnalyzeMethod" )) { while(true) { #if REPORT_SLOW_METHODS iterations++; #endif if(BeginScan ( nc ) && ConvertMethod( nc ) && EndScan ( nc ) ) { break; } } } #if REPORT_SLOW_METHODS sw.Stop(); if(sw.ElapsedMilliseconds >= 1500) { int variablesCount = (nc.CurrentCFG != null ? nc.CurrentCFG.DataFlow_SpanningTree_Variables.Length : 0); int operatorsCount = (nc.CurrentCFG != null ? nc.CurrentCFG.DataFlow_SpanningTree_Operators.Length : 0); Console.WriteLine( "NOTICE: Processing for method '{0}' took {1} milliseconds and {2} iterations! [{3} variables and {4} operators]", nc.CurrentMethod.ToShortString(), sw.ElapsedMilliseconds, iterations, variablesCount, operatorsCount ); Console.WriteLine(); } #endif } protected virtual bool BeginScan( NotificationContext nc ) { m_operatorNotificationHistory.Clear(); nc.StartScan(); return m_delegationForFlowGraph_Before.Invoke( nc ); } protected virtual bool ConvertMethod( NotificationContext nc ) { if(nc.CurrentCFG == null) { // // Nothing to do. // return true; } // // Shortcut the processing of the method, in case we don't need to track too many details. // { bool fGotEntities = (m_delegationForEntities .Count != 0 || m_delegationForCallEntities.Count != 0); bool fGotOperators = (m_delegationForOperators.Count != 0); bool fGotArguments = (m_delegationForArguments.Count != 0); if(fGotEntities == false && fGotArguments == false ) { if(fGotOperators) { foreach(Operator op in nc.CurrentCFG.DataFlow_SpanningTree_Operators) { nc.CurrentOperator = op; nc.Value = op; nc.ClearSkip(); if(m_operatorNotificationHistory.Insert( op ) == false) { InvokeByType( m_delegationForOperators, op, nc ); } if(nc.ShouldStop) return false; if(nc.ShouldSkip) continue; CallOperator call = op as CallOperator; if(call != null) { m_callsDatabase.RegisterCallSite( call ); } } if(nc.WasModified) return false; } return true; } } bool fContinue = Transformations.ScanCodeWithCallback.Execute( m_typeSystem, this, nc.CurrentCFG, delegate( Operator op, object target ) { nc.CurrentOperator = op; nc.Value = target; nc.ClearSkip(); while(true) { BaseRepresentation br = target as BaseRepresentation; if(br != null) { NotificationIssuer ni; if(m_delegationForEntities.TryGetValue( br, out ni )) { if(!ni.Invoke( nc )) break; } MethodRepresentation md = br as MethodRepresentation; CallOperator opCall = op as CallOperator; if(md != null && opCall != null && opCall.TargetMethod == md) { if(m_delegationForCallEntities.TryGetValue( md, out ni )) { if(!ni.Invoke( nc )) break; } } } if(target != null) { if(!InvokeByType( m_delegationForArguments, target, nc )) break; } if(op != null && m_operatorNotificationHistory.Insert( op ) == false) { if(!InvokeByType( m_delegationForOperators, op, nc )) break; } break; } if(nc.ShouldStop) return Transformations.ScanCodeWithCallback.CallbackResult.Stop; if(nc.ShouldSkip) return Transformations.ScanCodeWithCallback.CallbackResult.SkipToNextOperator; CallOperator call = target as CallOperator; if(call != null) { m_callsDatabase.RegisterCallSite( call ); } return Transformations.ScanCodeWithCallback.CallbackResult.Proceed; } ); if(fContinue) { fContinue = (nc.WasModified == false); } return fContinue; } protected virtual bool EndScan( NotificationContext nc ) { if(!m_delegationForFlowGraph_After.Invoke( nc )) { return false; } if(!nc.CanContinue) { return false; } ControlFlowGraphStateForCodeTransformation cfg = nc.CurrentCFG; if(cfg != null) { nc.SetMaxAbstractionLevelEncountered( nc.Phase.ValidateOperatorLevels( cfg ) ); } return true; } //--// public void RegisterForNotificationOfOptimization( OptimizationHandlerAttribute ca , NotificationOfTransformation target ) { m_delegationForOptimization[ca] = target; } public void RegisterForNotificationOfFlowGraph( NotificationOfTransformation target , bool fFirst ) { if(fFirst) { m_delegationForFlowGraph_Before.Add( target ); } else { m_delegationForFlowGraph_After.Add( target ); } } public void RegisterForNotificationOfOperatorsByType( Type cls , NotificationOfTransformation target ) { RegisterForNotification( m_delegationForOperators, cls, target ); } public void RegisterForNotificationOfOperatorByTypeOfArguments( Type cls , NotificationOfTransformation target ) { RegisterForNotification( m_delegationForArguments, cls, target ); } public void RegisterForNotificationOfOperatorByEntities( BaseRepresentation br , NotificationOfTransformation target ) { if(br != null) { RegisterForNotification( m_delegationForEntities, br, target ); } } public void RegisterForNotificationOfCallOperatorByEntities( MethodRepresentation md , NotificationOfTransformation target ) { if(md != null) { RegisterForNotification( m_delegationForCallEntities, md, target ); } } //--// private void RegisterForNotification( GrowOnlyHashTable< T, NotificationIssuer > ht , T key , NotificationOfTransformation target ) where T : class { NotificationIssuer res; if(ht.TryGetValue( key, out res ) == false) { res = new NotificationIssuer(); ht[key] = res; } res.Add( target ); } //--// private bool InvokeByType( GrowOnlyHashTable< Type, NotificationIssuer > ht , object target , NotificationContext nc ) { Type type = target.GetType(); while(type != null) { NotificationIssuer ni; if(ht.TryGetValue( type, out ni )) { if(!ni.Invoke( nc )) return false; } type = type.BaseType; } return true; } //--// // // Access Methods // public Operator.OperatorLevel MaxAbstractionLevelEncountered { get { return m_maxAbstractionLevelEncountered; } } } } ================================================ FILE: Zelig/Zelig/CompileTime/CodeGenerator/CodeTransformation/CompilationSteps/PhaseDrivers/SingleMethodPhaseExecution.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // namespace Microsoft.Zelig.CodeGeneration.IR.CompilationSteps { using System; using System.Collections.Generic; using Microsoft.Zelig.Runtime.TypeSystem; public class SingleMethodPhaseExecution : PhaseExecution { // // State // MethodRepresentation m_currentMethod; // // Constructor Methods // public SingleMethodPhaseExecution( TypeSystemForCodeTransformation typeSystem , DelegationCache cache , CallsDataBase callsDatabase , PhaseDriver phase ) : base( typeSystem, cache, callsDatabase, phase ) { } // // Helper Methods // public virtual void Analyze( MethodRepresentation md ) { m_currentMethod = md; AnalyzeMethod( md ); } } } ================================================ FILE: Zelig/Zelig/CompileTime/CodeGenerator/CodeTransformation/CompilationSteps/Phases/AllocateRegisters.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // namespace Microsoft.Zelig.CodeGeneration.IR.CompilationSteps.Phases { using System; using System.Collections.Generic; using Microsoft.Zelig.Runtime.TypeSystem; //[PhaseDisabled()] [PhaseOrdering( ExecuteAfter=typeof(CollectRegisterAllocationConstraints), IsPipelineBlock=true )] [PhaseLimit( Operator.OperatorLevel.StackLocations )] public sealed class AllocateRegisters : PhaseDriver { // // Constructor Methods // public AllocateRegisters( Controller context ) : base ( context ) { } // // Helper Methods // public override PhaseDriver Run() { //// GrowOnlySet< Type > set = SetFactory.New< Type >(); ParallelTransformationsHandler.EnumerateFlowGraphs( this.TypeSystem, delegate( ControlFlowGraphStateForCodeTransformation cfg ) { Transformations.GlobalRegisterAllocation.Execute( cfg ); cfg.DropDeadVariables(); //// lock(set) //// { //// foreach(IR.Operator op in cfg.SpanningTreeOperators) //// { //// set.Insert( op.GetType() ); //// } //// } } ); //// foreach(Type t in set) //// { //// Console.WriteLine( "{0}", t.FullName ); //// } return this.NextPhase; } } } ================================================ FILE: Zelig/Zelig/CompileTime/CodeGenerator/CodeTransformation/CompilationSteps/Phases/ApplyClassExtensions.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // namespace Microsoft.Zelig.CodeGeneration.IR.CompilationSteps.Phases { using System; using System.Collections.Generic; using Microsoft.Zelig.Runtime.TypeSystem; [PhaseOrdering( ExecuteAfter=typeof(TransformFinallyBlocksIntoTryBlocks) )] public sealed class ApplyClassExtensions : PhaseDriver { // // Constructor Methods // public ApplyClassExtensions( Controller context ) : base ( context ) { } // // Helper Methods // public override PhaseDriver Run() { var ace = new CompilationSteps.ApplyClassExtensions( this.TypeSystem ); ace.Run(); return this.NextPhase; } } } ================================================ FILE: Zelig/Zelig/CompileTime/CodeGenerator/CodeTransformation/CompilationSteps/Phases/ApplyConfigurationSettings.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // namespace Microsoft.Zelig.CodeGeneration.IR.CompilationSteps.Phases { using System; using System.Collections.Generic; using Microsoft.Zelig.Runtime.TypeSystem; [PhaseOrdering( ExecuteAfter=typeof(CrossReferenceTypeSystem) )] public sealed class ApplyConfigurationSettings : PhaseDriver { // // Constructor Methods // public ApplyConfigurationSettings( Controller context ) : base ( context ) { } // // Helper Methods // public override PhaseDriver Run() { PerformParallelExecutionOfPhase( false, false ); this.CallsDataBase.ExecuteInlining( this.TypeSystem ); ApplyGarbageCollectorConfiguration(); return this.NextPhase; } private void ApplyGarbageCollectorConfiguration() { var wkt = TypeSystem.WellKnownTypes; var gcImpls = TypeSystem.CollectConcreteImplementations(wkt.Microsoft_Zelig_Runtime_GarbageCollectionManager); CHECKS.ASSERT(gcImpls.Count == 1, "There can only be 1 active garbage collection manager"); var gcImpl = gcImpls[0]; Console.WriteLine("Garbage collector selected: {0}", gcImpl.FullName); // Since ReferenceCountingCollector is done by code injection during compile time // (and the ReferenceCountingCollector class itself is only a dummy class with // empty implementations), we need to detect its selection here and enable the // code path for code injection here for the later phases. if (gcImpl.IsSubClassOf(wkt.Microsoft_Zelig_Runtime_ReferenceCountingCollector, null)) { TypeSystem.ReferenceCountingGarbageCollectionStatus = TypeSystemForCodeTransformation.ReferenceCountingStatus.Enabled; } else if (gcImpl.IsSubClassOf(wkt.Microsoft_Zelig_Runtime_StrictReferenceCountingCollector, null)) { TypeSystem.ReferenceCountingGarbageCollectionStatus = TypeSystemForCodeTransformation.ReferenceCountingStatus.EnabledStrict; } } } } ================================================ FILE: Zelig/Zelig/CompileTime/CodeGenerator/CodeTransformation/CompilationSteps/Phases/CollectRegisterAllocationConstraints.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // namespace Microsoft.Zelig.CodeGeneration.IR.CompilationSteps.Phases { using System; using System.Collections.Generic; using Microsoft.Zelig.Runtime.TypeSystem; //[PhaseDisabled()] [PhaseOrdering( ExecuteAfter=typeof(PrepareForRegisterAllocation) )] public sealed class CollectRegisterAllocationConstraints : PhaseDriver { // // Constructor Methods // public CollectRegisterAllocationConstraints( Controller context ) : base ( context ) { } // // Helper Methods // public override PhaseDriver Run() { PerformParallelExecutionOfPhase( false, true ); return this.NextPhase; } } } ================================================ FILE: Zelig/Zelig/CompileTime/CodeGenerator/CodeTransformation/CompilationSteps/Phases/CompleteImplementationOfInternalMethods.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // namespace Microsoft.Zelig.CodeGeneration.IR.CompilationSteps.Phases { using System; using System.Collections.Generic; using Microsoft.Zelig.Runtime.TypeSystem; //[PhaseDisabled()] [PhaseOrdering( ExecuteAfter=typeof(EstimateTypeSystemReduction) )] public sealed class CompleteImplementationOfInternalMethods : PhaseDriver { // // Constructor Methods // public CompleteImplementationOfInternalMethods( Controller context ) : base ( context ) { } // // Helper Methods // public override PhaseDriver Run() { var phaseStart = FindPhase< PrepareImplementationOfInternalMethods >(); if(phaseStart.m_state.Complete() == false) { this.TypeSystem.BuildCrossReference(); return FindPhase< HighLevelTransformations >(); } return this.NextPhase; } } } ================================================ FILE: Zelig/Zelig/CompileTime/CodeGenerator/CodeTransformation/CompilationSteps/Phases/ComputeCallsClosure.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // //#define DEBUG_INCLUDE_ALL_METHODS namespace Microsoft.Zelig.CodeGeneration.IR.CompilationSteps.Phases { using System; using Microsoft.Zelig.Runtime.TypeSystem; [PhaseOrdering( ExecuteAfter = typeof( PropagateCompilationConstraints ) )] public sealed class ComputeCallsClosure : PhaseDriver { // // State // private CompilationSteps.ComputeCallsClosure m_state; // // Constructor Methods // public ComputeCallsClosure( Controller context ) : base( context ) { } // // Helper Methods // public override PhaseDriver Run( ) { this.CallsDataBase.ResetCallSites( ); m_state = new CompilationSteps.ComputeCallsClosure( this.TypeSystem, this.DelegationCache, this.CallsDataBase, this, false ); if( this.TypeSystem.PlatformAbstraction.CodeGenerator == TargetModel.ArmProcessor.InstructionSetVersion.CodeGenerator_LLVM ) { //MethodRepresentation mainThread = null; //this.TypeSystem.EnumerateMethods( delegate( MethodRepresentation md ) //{ // if( md.Name.Equals( "MainThread" ) && md.OwnerType.Equals( this.TypeSystem.WellKnownMethods ) ) // { // mainThread = md; // } //} ); //if( mainThread != null) //{ // m_state.Execute( mainThread ); //} //else //{ // CHECKS.ASSERT( false, "No Thread Manager or no MainThread method found!!" ); //} m_state.Execute( this.TypeSystem.GetWellKnownMethod( "Bootstrap_Initialization" ) ); } else { #if DEBUG_INCLUDE_ALL_METHODS this.TypeSystem.EnumerateMethods( delegate( MethodRepresentation md ) { m_state.Execute( md ); } ); #else m_state.Execute( this.TypeSystem.GetHandler( Runtime.HardwareException.Reset ) ); #endif } if (this.TypeSystem.IsReferenceCountingGarbageCollectionEnabled) { // Keep the reference counting methods around so they stay alive when we inject // auto reference counting code in the ReferenceCountingGarbageCollection phase var wkm = this.TypeSystem.WellKnownMethods; m_state.Execute( wkm.ObjectHeader_AddReference ); m_state.Execute( wkm.ObjectHeader_ReleaseReference ); m_state.Execute( wkm.ThreadImpl_AllocateReleaseReferenceHelper ); m_state.Execute( wkm.ReferenceCountingCollector_Swap ); m_state.Execute( wkm.ReferenceCountingCollector_LoadAndAddReference ); m_state.Execute( wkm.ReferenceCountingCollector_ReferenceCountingExchange ); m_state.Execute( wkm.ReferenceCountingCollector_ReferenceCountingCompareExchange ); m_state.Execute( wkm.StringImpl_FastAllocateReferenceCountingString ); m_state.Execute( wkm.Bootstrap_ReferenceCountingInitialization ); m_state.Execute( wkm.ThreadManager_CleanupBootstrapThread ); } this.TypeSystem.ExpandCallsClosure( m_state ); var touched = this.CallsDataBase.ExecuteInlining( this.TypeSystem ); if( touched.Count > 0 ) { return this; } return this.NextPhase; } // // Access Methods // public GrowOnlyHashTable> EntitiesReferencedByMethods { get { return m_state.EntitiesReferencedByMethods; } } } } ================================================ FILE: Zelig/Zelig/CompileTime/CodeGenerator/CodeTransformation/CompilationSteps/Phases/ConvertToSSA.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // namespace Microsoft.Zelig.CodeGeneration.IR.CompilationSteps.Phases { using System; using System.Collections.Generic; using Microsoft.Zelig.Runtime.TypeSystem; //[PhaseDisabled()] [PhaseOrdering( ExecuteAfter=typeof(Optimizations) )] public sealed class ConvertToSSA : PhaseDriver { // // Constructor Methods // public ConvertToSSA( Controller context ) : base ( context ) { } // // Helper Methods // public override PhaseDriver Run() { PerformParallelExecutionOfPhase( false, true ); return this.NextPhase; } } } ================================================ FILE: Zelig/Zelig/CompileTime/CodeGenerator/CodeTransformation/CompilationSteps/Phases/ConvertUnsupportedOperatorsToMethodCalls.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // namespace Microsoft.Zelig.CodeGeneration.IR.CompilationSteps.Phases { using System; using System.Collections.Generic; using Microsoft.Zelig.Runtime.TypeSystem; //[PhaseDisabled()] [PhaseOrdering( ExecuteAfter=typeof(MidLevelToLowLevelConversion) )] public sealed class ConvertUnsupportedOperatorsToMethodCalls : PhaseDriver { // // Constructor Methods // public ConvertUnsupportedOperatorsToMethodCalls( Controller context ) : base ( context ) { } // // Helper Methods // public override PhaseDriver Run() { PerformParallelExecutionOfPhase( true, true ); return this.NextPhase; } } } ================================================ FILE: Zelig/Zelig/CompileTime/CodeGenerator/CodeTransformation/CompilationSteps/Phases/CrossReferenceTypeSystem.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // namespace Microsoft.Zelig.CodeGeneration.IR.CompilationSteps.Phases { using System; using System.Collections.Generic; using Microsoft.Zelig.Runtime.TypeSystem; [PhaseOrdering( ExecuteAfter=typeof(PrepareImplementationOfInternalMethods) )] public sealed class CrossReferenceTypeSystem : PhaseDriver { // // Constructor Methods // public CrossReferenceTypeSystem( Controller context ) : base ( context ) { } // // Helper Methods // public override PhaseDriver Run() { this.TypeSystem.BuildCrossReference(); return this.NextPhase; } } } ================================================ FILE: Zelig/Zelig/CompileTime/CodeGenerator/CodeTransformation/CompilationSteps/Phases/DetectNonImplementedInternalCalls.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // //#define DEBUG_MISSING_METHODS_CALLERS //#define STOP_ON_POSITIVE_DETECTION namespace Microsoft.Zelig.CodeGeneration.IR.CompilationSteps.Phases { using System; using System.Collections.Generic; using Microsoft.Zelig.Runtime.TypeSystem; [PhaseOrdering( ExecuteAfter=typeof(ReduceTypeSystem) )] public sealed class DetectNonImplementedInternalCalls : PhaseDriver { // // Constructor Methods // public DetectNonImplementedInternalCalls( Controller context ) : base ( context ) { } // // Helper Methods // public override PhaseDriver Run() { #if DEBUG_MISSING_METHODS_CALLERS var missingMethods = new List< MethodRepresentation >(); foreach(TypeRepresentation td in this.TypeSystem.Types) { if(td.IsOpenType == false) { foreach(MethodRepresentation md in td.Methods) { if((md.Flags & MethodRepresentation.Attributes.Abstract) != 0) continue; if(md.IsOpenMethod == false && TypeSystemForCodeTransformation.GetCodeForMethod( md ) == null) { missingMethods.Add( md ); } } } } #endif #if STOP_ON_POSITIVE_DETECTION if(missingMethods.Count > 0) { DumpMissingMethods( missingMethods ); throw TypeConsistencyErrorException.Create( "ERROR: found methods without an implementation" ); } #endif return this.NextPhase; } private void DumpMissingMethods( List< MethodRepresentation > lst ) { var reverseIndex = new Transformations.ReverseIndexTypeSystem( this.TypeSystem ); reverseIndex.ProcessTypeSystem(); foreach(MethodRepresentation md in lst) { Console.WriteLine( "WARNING: missing implementation for {0}", md.ToShortString() ); #if DEBUG_MISSING_METHODS_CALLERS var set = SetFactory.New< MethodRepresentation >(); DumpCallers( reverseIndex, set, md, 0, 2 ); #endif Console.WriteLine(); } } private static void DumpCallers( Transformations.ReverseIndexTypeSystem reverseIndex , GrowOnlySet< MethodRepresentation > history , MethodRepresentation md , int depth , int maxDepth ) { if(history.Insert( md ) == true) { return; } GrowOnlySet< MethodRepresentation > set = GetCallers( reverseIndex, md ); foreach(MethodRepresentation caller in set) { if(history.Contains( caller ) == false) { Console.WriteLine( " {0}called from {1}", new string( ' ', depth * 3 ), caller.ToShortString() ); if(depth < maxDepth) { DumpCallers( reverseIndex, history, caller, depth + 1, maxDepth ); } } } } private static GrowOnlySet< MethodRepresentation > GetCallers( Transformations.ReverseIndexTypeSystem reverseIndex , MethodRepresentation md ) { GrowOnlySet< MethodRepresentation > res = SetFactory.NewWithReferenceEquality< MethodRepresentation >(); GrowOnlySet< object > set = reverseIndex[md]; if(set != null) { foreach(object obj in set) { CallOperator op = obj as CallOperator; if(op != null && op.TargetMethod == md) { MethodRepresentation caller = op.BasicBlock.Owner.Method; res.Insert( caller ); } } } if(md is VirtualMethodRepresentation && md.VTableLayoutFlags == MethodRepresentation.Attributes.ReuseSlot) { TypeRepresentation td = md.OwnerType; string name = md.Name; while((td = td.Extends) != null) { foreach(MethodRepresentation md2 in td.Methods) { if(td.GetDeclarationOfMethodImpl( md2 ) != null) { continue; // Skip any method with an explicit MethodImpl. } if(md2.MatchNameAndSignature( name, md, null )) { res.Merge( GetCallers( reverseIndex, md2 ) ); break; } } } } return res; } } } ================================================ FILE: Zelig/Zelig/CompileTime/CodeGenerator/CodeTransformation/CompilationSteps/Phases/Done.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // namespace Microsoft.Zelig.CodeGeneration.IR.CompilationSteps.Phases { using System; using System.Collections.Generic; using Microsoft.Zelig.Runtime.TypeSystem; [PhaseOrdering( ExecuteAfter=typeof(GenerateImage) )] public sealed class Done : PhaseDriver { // // Constructor Methods // public Done( Controller context ) : base ( context ) { } // // Helper Methods // public override PhaseDriver Run() { return this.NextPhase; } } } ================================================ FILE: Zelig/Zelig/CompileTime/CodeGenerator/CodeTransformation/CompilationSteps/Phases/EstimateTypeSystemReduction.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // namespace Microsoft.Zelig.CodeGeneration.IR.CompilationSteps.Phases { using System; using System.Collections.Generic; using Microsoft.Zelig.Runtime.TypeSystem; [PhaseOrdering( ExecuteAfter=typeof(ComputeCallsClosure))] public sealed class EstimateTypeSystemReduction : PhaseDriver { // // Constructor Methods // public EstimateTypeSystemReduction( Controller context ) : base ( context ) { } // // Helper Methods // public override PhaseDriver Run() { this.TypeSystem.EstimateReduction(); return this.NextPhase; } } } ================================================ FILE: Zelig/Zelig/CompileTime/CodeGenerator/CodeTransformation/CompilationSteps/Phases/ExpandAggregateTypes.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // namespace Microsoft.Zelig.CodeGeneration.IR.CompilationSteps.Phases { using System; using System.Collections.Generic; using Microsoft.Zelig.Runtime.TypeSystem; //[PhaseDisabled()] [PhaseOrdering( ExecuteAfter=typeof(ConvertUnsupportedOperatorsToMethodCalls), IsPipelineBlock=true )] [PhaseLimit( Operator.OperatorLevel.ScalarValues )] public sealed class ExpandAggregateTypes : PhaseDriver { // // Constructor Methods // public ExpandAggregateTypes( Controller context ) : base ( context ) { } // // Helper Methods // public override PhaseDriver Run() { PerformParallelExecutionOfPhase( false, true ); return this.NextPhase; } } } ================================================ FILE: Zelig/Zelig/CompileTime/CodeGenerator/CodeTransformation/CompilationSteps/Phases/FromImplicitToExplicitExceptions.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // // This macro enables transformation from exception blocks to landing pad form. #define ENABLE_LANDING_PADS namespace Microsoft.Zelig.CodeGeneration.IR.CompilationSteps.Phases { using System; using System.Collections.Generic; using Microsoft.Zelig.Runtime.TypeSystem; [PhaseOrdering( ExecuteAfter = typeof( HighLevelToMidLevelConversion ) )] public sealed class FromImplicitToExplicitExceptions : PhaseDriver { // // Constructor Methods // public FromImplicitToExplicitExceptions( Controller context ) : base ( context ) { } // // Helper Methods // public override PhaseDriver Run() { #if ENABLE_LANDING_PADS ParallelTransformationsHandler.EnumerateFlowGraphs( this.TypeSystem, delegate (ControlFlowGraphStateForCodeTransformation cfg) { Transformations.ConvertToLandingPads.Execute(cfg); }); #endif // ENABLE_LANDING_PADS PerformParallelExecutionOfPhase( true, false ); return this.NextPhase; } } } ================================================ FILE: Zelig/Zelig/CompileTime/CodeGenerator/CodeTransformation/CompilationSteps/Phases/FuseOperators.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // namespace Microsoft.Zelig.CodeGeneration.IR.CompilationSteps.Phases { using System; using System.Collections.Generic; using Microsoft.Zelig.Runtime.TypeSystem; //[PhaseDisabled()] [PhaseOrdering( ExecuteAfter=typeof(SplitComplexOperators) )] public sealed class FuseOperators : PhaseDriver { // // Constructor Methods // public FuseOperators( Controller context ) : base ( context ) { } // // Helper Methods // public override PhaseDriver Run() { PerformParallelExecutionOfPhase( false, true ); return this.NextPhase; } } } ================================================ FILE: Zelig/Zelig/CompileTime/CodeGenerator/CodeTransformation/CompilationSteps/Phases/GenerateImage.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // // Enable this macro to run LLVM-specific transforms prior to generating the image. #define LLVM namespace Microsoft.Zelig.CodeGeneration.IR.CompilationSteps.Phases { using System; using System.Collections.Generic; using Microsoft.Zelig.Runtime.TypeSystem; [PhaseOrdering( ExecuteAfter=typeof(AllocateRegisters) )] public sealed class GenerateImage : PhaseDriver { // // Constructor Methods // public GenerateImage( Controller context ) : base ( context ) { } // // Helper Methods // public override PhaseDriver Run() { #if LLVM ParallelTransformationsHandler.EnumerateFlowGraphs( this.TypeSystem, delegate( ControlFlowGraphStateForCodeTransformation cfg ) { Transformations.MergeExtendedBasicBlocks.Execute( cfg, preserveInjectionSites: false ); } ); #endif // LLVM this.TypeSystem.GenerateImage( this ); return this.NextPhase; } } } ================================================ FILE: Zelig/Zelig/CompileTime/CodeGenerator/CodeTransformation/CompilationSteps/Phases/HighLevelToMidLevelConversion.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // namespace Microsoft.Zelig.CodeGeneration.IR.CompilationSteps.Phases { using System; using System.Collections.Generic; using Microsoft.Zelig.Runtime.TypeSystem; //[PhaseDisabled()] [PhaseOrdering( ExecuteAfter = typeof( LayoutTypes ) )] public sealed class HighLevelToMidLevelConversion : PhaseDriver { // // Constructor Methods // public HighLevelToMidLevelConversion( Controller context ) : base ( context ) { } // // Helper Methods // public override PhaseDriver Run() { PerformParallelExecutionOfPhase( true, false ); return this.NextPhase; } } } ================================================ FILE: Zelig/Zelig/CompileTime/CodeGenerator/CodeTransformation/CompilationSteps/Phases/HighLevelTransformations.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // namespace Microsoft.Zelig.CodeGeneration.IR.CompilationSteps.Phases { using System; using System.Collections.Generic; using Microsoft.Zelig.Runtime.TypeSystem; [PhaseOrdering( ExecuteAfter = typeof(ApplyConfigurationSettings))] public sealed class HighLevelTransformations : PhaseDriver { // // Constructor Methods // public HighLevelTransformations( Controller context ) : base ( context ) { } // // Helper Methods // public override PhaseDriver Run() { PerformParallelExecutionOfPhase( false, false ); return this.NextPhase; } } } ================================================ FILE: Zelig/Zelig/CompileTime/CodeGenerator/CodeTransformation/CompilationSteps/Phases/LayoutTypes.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // namespace Microsoft.Zelig.CodeGeneration.IR.CompilationSteps.Phases { using System; using System.Collections.Generic; using Microsoft.Zelig.Runtime.TypeSystem; //[PhaseDisabled()] [PhaseOrdering( ExecuteAfter = typeof( OrderStaticConstructors ), IsPipelineBlock = true )] [PhaseLimit( Operator.OperatorLevel.ConcreteTypes )] public sealed class LayoutTypes : PhaseDriver { // // Constructor Methods // public LayoutTypes( Controller context ) : base ( context ) { } // // Helper Methods // public override PhaseDriver Run() { this.TypeSystem.LayoutTypes( this.TypeSystem.PlatformAbstraction.MemoryAlignment ); this.TypeSystem.DataManagerInstance.RefreshValues( this ); this.TypeSystem.FlattenCallsDatabase( this.CallsDataBase.Analyze( this.TypeSystem ), fCallsTo: true ); this.TypeSystem.FlattenCallsDatabase( this.CallsDataBase.Analyze( this.TypeSystem ), fCallsTo: false ); return this.NextPhase; } public override void ValidatePhaseMovement( PhaseDriver prevPhase , PhaseDriver nextPhase ) { base.ValidatePhaseMovement( prevPhase, nextPhase ); if(nextPhase.PhaseIndex < this.PhaseIndex) { this.TypeSystem.InvalidateLayout(); } } } } ================================================ FILE: Zelig/Zelig/CompileTime/CodeGenerator/CodeTransformation/CompilationSteps/Phases/MidLevelToLowLevelConversion.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // namespace Microsoft.Zelig.CodeGeneration.IR.CompilationSteps.Phases { using System; using System.Collections.Generic; using Microsoft.Zelig.Runtime.TypeSystem; [PhaseOrdering( ExecuteAfter=typeof( ReferenceCountingGarbageCollection ) )] [PhaseLimit( Operator.OperatorLevel.ConcreteTypes_NoExceptions )] public sealed class MidLevelToLowLevelConversion : PhaseDriver { // // Constructor Methods // public MidLevelToLowLevelConversion( Controller context ) : base ( context ) { } // // Helper Methods // public override PhaseDriver Run() { PerformParallelExecutionOfPhase( true, true ); return this.NextPhase; } } } ================================================ FILE: Zelig/Zelig/CompileTime/CodeGenerator/CodeTransformation/CompilationSteps/Phases/Optimizations.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // namespace Microsoft.Zelig.CodeGeneration.IR.CompilationSteps.Phases { using System; using System.Collections.Generic; using Microsoft.Zelig.Runtime.TypeSystem; //[PhaseDisabled()] [PhaseOrdering( ExecuteAfter=typeof(FuseOperators) )] public sealed class Optimizations : PhaseDriver { // // Constructor Methods // public Optimizations( Controller context ) : base ( context ) { } // // Helper Methods // public override PhaseDriver Run() { var maxLevel = Operator.OperatorLevel.Lowest; ParallelTransformationsHandler.EnumerateMethods( this.TypeSystem, delegate( ParallelTransformationsHandler.Operation phase, MethodRepresentation md, ref object state ) { var rpe = (OptimizationsPhaseExecution)state; switch(phase) { case ParallelTransformationsHandler.Operation.Initialize: state = new OptimizationsPhaseExecution( this.TypeSystem, this.DelegationCache, this.CallsDataBase, this ); break; case ParallelTransformationsHandler.Operation.Execute: if(md.IsOpenMethod == false && md.OwnerType.IsOpenType == false) { rpe.Analyze( md ); } break; case ParallelTransformationsHandler.Operation.Shutdown: if(maxLevel < rpe.MaxAbstractionLevelEncountered) { maxLevel = rpe.MaxAbstractionLevelEncountered; } break; } } ); ValidateAbstractionLevel( maxLevel ); return this.NextPhase; } } } ================================================ FILE: Zelig/Zelig/CompileTime/CodeGenerator/CodeTransformation/CompilationSteps/Phases/OrderStaticConstructors.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // namespace Microsoft.Zelig.CodeGeneration.IR.CompilationSteps.Phases { using System; using System.Collections.Generic; using Microsoft.Zelig.Runtime.TypeSystem; //[PhaseDisabled()] [PhaseOrdering( ExecuteAfter = typeof( DetectNonImplementedInternalCalls ) )] public sealed class OrderStaticConstructors : PhaseDriver { // // Constructor Methods // public OrderStaticConstructors( Controller context ) : base ( context ) { } // // Helper Methods // public override PhaseDriver Run() { var mdTarget = this.TypeSystem.WellKnownMethods.TypeSystemManager_InvokeStaticConstructors; if(mdTarget != null) { // // 1) Build the call graph for the whole system. // var callGraph = new CallGraph( this.TypeSystem ); // // 2) Walk through the methods that use field that require static constructors, collecting the cctors. // var constructors = HashTableFactory.NewWithReferenceEquality< MethodRepresentation, GrowOnlySet< MethodRepresentation > >(); foreach(var lst in callGraph.MethodsThatRequireStaticConstructors.Values) { foreach(var md in lst) { if(constructors.ContainsKey( md ) == false) { // // 3) Create the call closure for each cctor, stopping at other static cctors. // GrowOnlySet< MethodRepresentation > setClosure = callGraph.ComputeClosure( md, FilterClosure ); // // 4) Build a map from each static constructor to all the ones it depends on. // GrowOnlySet< MethodRepresentation > set = SetFactory.NewWithReferenceEquality< MethodRepresentation >();; foreach(MethodRepresentation mdInClosure in setClosure) { if(mdInClosure != md) { if(mdInClosure is StaticConstructorMethodRepresentation) { set.Insert( mdInClosure ); } } } constructors[md] = set; } } } // // 5) Create an ordered list of static constructors to invoke, breaking loops if needed. // var invocationOrder = new List< MethodRepresentation >(); var processed = SetFactory.NewWithReferenceEquality< MethodRepresentation >(); // // 6) Iterate until all the static constructors have been ordered. // while(processed.Count < constructors.Count) { bool fStuckInLoop = true; foreach(var md in constructors.Keys) { if(processed.Contains( md ) == false) { bool fAdd = true; foreach(var mdDepends in constructors[md]) { if(processed.Contains( mdDepends ) == false) { fAdd = false; break; } } if(fAdd) { invocationOrder.Add ( md ); processed .Insert( md ); fStuckInLoop = false; } } } if(fStuckInLoop) { // // Just pick one to break the loop. // MethodRepresentation mdBest = null; Console.WriteLine( "WARNING: Detected loop between static constructors:" ); foreach(var md in constructors.Keys) { if(processed.Contains( md ) == false) { Console.WriteLine( " {0}", md.OwnerType.FullNameWithAbbreviation ); if(mdBest == null) { mdBest = md; } else if(constructors[md].Count < constructors[mdBest].Count) { mdBest = md; } } } CHECKS.ASSERT( mdBest != null, "Cannot be stuck in loop between static constructors when no items in the loop" ); invocationOrder.Add ( mdBest ); processed .Insert( mdBest ); } } // // 7) Inject calls to static constructors into target method. // var cfg = TypeSystemForCodeTransformation.GetCodeForMethod( mdTarget ); var bb = cfg.NormalizedEntryBasicBlock; foreach(var md in invocationOrder) { var rhs = this.TypeSystem.AddTypePointerToArgumentsOfStaticMethod( md ); var call = StaticCallOperator.New( null, CallOperator.CallKind.Direct, md, rhs ); bb.AddOperator( call ); } } return this.NextPhase; } private bool FilterClosure( MethodRepresentation mdNext ) { if(mdNext is StaticConstructorMethodRepresentation) { return false; } var wkm = this.TypeSystem.WellKnownMethods; if(SameMethodOrOverride( mdNext, wkm.TypeSystemManager_AllocateObject ) || SameMethodOrOverride( mdNext, wkm.TypeSystemManager_AllocateArray ) || SameMethodOrOverride( mdNext, wkm.TypeSystemManager_AllocateArrayNoClear ) || SameMethodOrOverride( mdNext, wkm.TypeSystemManager_AllocateString ) ) { // // These methods are already working by the time we get to class constructors, so let's stop the closure here. // return false; } if (SameMethodOrOverride(mdNext, wkm.TypeSystemManager_Throw) || SameMethodOrOverride(mdNext, wkm.TypeSystemManager_Rethrow)) { // // If a class constructor throws an exception, bad things are going to happen, so no need to expand the closure any further. // return false; } return true; } private static bool SameMethodOrOverride( MethodRepresentation md , MethodRepresentation mdTarget ) { if(md == mdTarget) { return true; } if(md is VirtualMethodRepresentation && mdTarget is VirtualMethodRepresentation ) { if(md.OwnerType.IsSubClassOf( mdTarget.OwnerType, null )) { int index = md .FindVirtualTableIndex(); int indexTarget = mdTarget.FindVirtualTableIndex(); if(index == indexTarget) { return true; } } } return false; } } } ================================================ FILE: Zelig/Zelig/CompileTime/CodeGenerator/CodeTransformation/CompilationSteps/Phases/PrepareExternalMethods.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // namespace Microsoft.Zelig.CodeGeneration.IR.CompilationSteps.Phases { using System; using System.Collections.Generic; using Microsoft.Zelig.Runtime.TypeSystem; //[PhaseDisabled()] [PhaseOrdering( ExecuteAfter = typeof(ReduceTypeSystem), ExecuteBefore = typeof( DetectNonImplementedInternalCalls ) )] public sealed class PrepareExternalMethods : PhaseDriver { // // State // internal ImplementExternalMethods m_state; // // Constructor Methods // public PrepareExternalMethods( Controller context ) : base( context ) { ExternalCallOperator.NativeImportDirectories = context.TypeSystem.NativeImportDirectories; ExternalCallOperator.NativeImportLibraries = context.TypeSystem.NativeImportLibraries; m_state = new ImplementExternalMethods( this.TypeSystem ); } // // Helper Methods // public override PhaseDriver Run() { //this.TypeSystem.BuildCrossReference(); m_state.Prepare(); //DetectFieldInvariants.Execute( this.TypeSystem ); return this.NextPhase; } } } ================================================ FILE: Zelig/Zelig/CompileTime/CodeGenerator/CodeTransformation/CompilationSteps/Phases/PrepareForRegisterAllocation.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // namespace Microsoft.Zelig.CodeGeneration.IR.CompilationSteps.Phases { using System; using System.Collections.Generic; using Microsoft.Zelig.Runtime.TypeSystem; //[PhaseDisabled()] [PhaseOrdering( ExecuteAfter=typeof(ConvertToSSA) )] public sealed class PrepareForRegisterAllocation : PhaseDriver { // // Constructor Methods // public PrepareForRegisterAllocation( Controller context ) : base ( context ) { } // // Helper Methods // public override PhaseDriver Run() { PerformParallelExecutionOfPhase( false, true ); return this.NextPhase; } } } ================================================ FILE: Zelig/Zelig/CompileTime/CodeGenerator/CodeTransformation/CompilationSteps/Phases/PrepareImplementationOfInternalMethods.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // namespace Microsoft.Zelig.CodeGeneration.IR.CompilationSteps.Phases { using System; using System.Collections.Generic; using Microsoft.Zelig.Runtime.TypeSystem; //[PhaseDisabled()] [PhaseOrdering( ExecuteAfter=typeof(ApplyClassExtensions) )] public sealed class PrepareImplementationOfInternalMethods : PhaseDriver { // // State // internal ImplementInternalMethods m_state; // // Constructor Methods // public PrepareImplementationOfInternalMethods( Controller context ) : base ( context ) { m_state = new ImplementInternalMethods( this.TypeSystem ); } // // Helper Methods // public override PhaseDriver Run() { this.TypeSystem.BuildCrossReference(); m_state.Prepare(); DetectFieldInvariants.Execute( this.TypeSystem ); return this.NextPhase; } } } ================================================ FILE: Zelig/Zelig/CompileTime/CodeGenerator/CodeTransformation/CompilationSteps/Phases/PropagateCompilationConstraints.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // namespace Microsoft.Zelig.CodeGeneration.IR.CompilationSteps.Phases { using System; using System.Collections.Generic; using Microsoft.Zelig.Runtime.TypeSystem; [PhaseOrdering( ExecuteAfter=typeof(HighLevelTransformations) )] public sealed class PropagateCompilationConstraints : PhaseDriver { // // Constructor Methods // public PropagateCompilationConstraints( Controller context ) : base ( context ) { } // // Helper Methods // public override PhaseDriver Run() { var callsToInline = new Queue< CallOperator >(); ParallelTransformationsHandler.EnumerateFlowGraphs( this.TypeSystem, delegate( ControlFlowGraphStateForCodeTransformation cfg ) { if(cfg.Method.IsOpenMethod == false) { EnforceCompilationConstraints( callsToInline, cfg ); } } ); while(callsToInline.Count > 0) { CallOperator op = callsToInline.Dequeue(); var cfg = (ControlFlowGraphStateForCodeTransformation)op.BasicBlock.Owner; cfg.TraceToFile( "InlineCall" ); var fSuccess = Transformations.InlineCall.Execute( op, null ); cfg.TraceToFile( "InlineCall-Post" ); if(fSuccess) { EnforceCompilationConstraints( callsToInline, cfg ); } else { // // Inling can fail if the target method doesn't have an implementation. // For now, just proceed, it will be caught at a later stage. // //CHECKS.ASSERT( false, "Unexpected failure to force inlining" ); } } return this.NextPhase; } private static void EnforceCompilationConstraints( Queue< CallOperator > callsToInline , ControlFlowGraphStateForCodeTransformation cfg ) { var toBeInlined = new List< CallOperator >(); cfg.EnforceCompilationConstraints( toBeInlined ); if(toBeInlined.Count > 0) { lock(callsToInline) { foreach(CallOperator op in toBeInlined) { callsToInline.Enqueue( op ); } } } } } } ================================================ FILE: Zelig/Zelig/CompileTime/CodeGenerator/CodeTransformation/CompilationSteps/Phases/ReduceNumberOfTemporaries.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // namespace Microsoft.Zelig.CodeGeneration.IR.CompilationSteps.Phases { using System; using System.Collections.Generic; using Microsoft.Zelig.Runtime.TypeSystem; public sealed class ReduceNumberOfTemporaries : PhaseDriver { // // Constructor Methods // public ReduceNumberOfTemporaries( Controller context ) : base ( context ) { } // // Helper Methods // public override PhaseDriver Run() { ParallelTransformationsHandler.EnumerateFlowGraphs( this.TypeSystem, delegate( ControlFlowGraphStateForCodeTransformation cfg ) { Transformations.ReduceNumberOfTemporaries.Execute( cfg ); } ); return this.NextPhase; } } } ================================================ FILE: Zelig/Zelig/CompileTime/CodeGenerator/CodeTransformation/CompilationSteps/Phases/ReduceTypeSystem.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // namespace Microsoft.Zelig.CodeGeneration.IR.CompilationSteps.Phases { using System; using System.Collections.Generic; using Microsoft.Zelig.Runtime.TypeSystem; [PhaseOrdering( ExecuteAfter=typeof(CompleteImplementationOfInternalMethods), IsPipelineBlock=true )] [PhaseLimit( Operator.OperatorLevel.ObjectOriented )] public sealed class ReduceTypeSystem : PhaseDriver { private TypeSystem m_typeSystem; // // Constructor Methods // public ReduceTypeSystem( Controller context ) : base ( context ) { m_typeSystem = context.TypeSystem; } // // Helper Methods // public override PhaseDriver Run() { // // Flush the call graph, because it could contain reduced methods. // this.CallsDataBase.ClearCallSites(); this.TypeSystem.PerformReduction(); this.TypeSystem.BuildCrossReference(); return this.NextPhase; } } } ================================================ FILE: Zelig/Zelig/CompileTime/CodeGenerator/CodeTransformation/CompilationSteps/Phases/ReferenceCountingGarbageCollection.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // using Microsoft.Zelig.Runtime.TypeSystem; using System; namespace Microsoft.Zelig.CodeGeneration.IR.CompilationSteps.Phases { [PhaseOrdering( ExecuteAfter = typeof( FromImplicitToExplicitExceptions ) )] public sealed class ReferenceCountingGarbageCollection : PhaseDriver { private GrowOnlySet m_modifiedOperators; private GrowOnlyHashTable m_stats; // // Constructor Methods // public ReferenceCountingGarbageCollection( Controller context ) : base( context ) { m_modifiedOperators = SetFactory.New( ); m_stats = HashTableFactory.New( ); } public bool IsOperatorModified( Operator op ) { lock (m_modifiedOperators) { return m_modifiedOperators.Contains( op ); } } public void AddToModifiedOperator( Operator op ) { lock (m_modifiedOperators) { m_modifiedOperators.Insert( op ); } } public void IncrementInjectionCount( MethodRepresentation md ) { lock (m_stats) { if(m_stats.ContainsKey( md )) { m_stats.Update( md, m_stats.GetValue( md ) + 1 ); } else { m_stats.Add( md, 1 ); } } } public void DecrementInjectionCount( MethodRepresentation md ) { lock (m_stats) { CHECKS.ASSERT( m_stats.ContainsKey( md ), "DecrementInjectionCount error" ); m_stats.Update( md, m_stats.GetValue( md ) - 1 ); } } // // Helper Methods // public override PhaseDriver Run( ) { if(this.TypeSystem.IsReferenceCountingGarbageCollectionEnabled) { // 1. Inject reference counting specific setup / helpers InjectReferenceCountingHelpers( ); // 2. Inject calls to AddReference and ReleaseReference for operators that copy references // 3. Inject calls to ReleaseReference at the end of each function to for each local / temp variables. PerformParallelExecutionOfPhase( true, false ); // 4. Reduce number of temporaries again to clean up the injected code ParallelTransformationsHandler.EnumerateFlowGraphs( this.TypeSystem, delegate ( ControlFlowGraphStateForCodeTransformation cfg ) { Transformations.ReduceNumberOfTemporaries.Execute( cfg ); } ); // 5: Dump out the counts of each injection for informational purpose DumpInjectionStats( ); } return this.NextPhase; } private void DumpInjectionStats() { Console.WriteLine( ); Console.WriteLine( " Reference Counting GC Code Injection Stats" ); Console.WriteLine( " ================================================" ); int total = 0; foreach(var md in m_stats.Keys) { var count = m_stats.GetValue( md ); Console.WriteLine( " {0,-20} :{1, 6}", md.Name, count ); total += count; } Console.WriteLine( " ------------------------------------------------" ); Console.WriteLine( " {0,-20} :{1, 6}", "Total", total ); Console.WriteLine( " ================================================" ); Console.WriteLine( ); } private struct Injection { public String method; public Func arguments; public String target; public BasicBlock.Qualifier injectionPoint; } private void InjectReferenceCountingHelpers( ) { Injection[] injections = new Injection[] { new Injection { method = "ThreadImpl_AllocateReleaseReferenceHelper", arguments = cfg => new Expression[] { cfg.Arguments[ 0 ] }, target = "ThreadImpl_ctor", injectionPoint = BasicBlock.Qualifier.EntryInjectionStart }, new Injection { method = "Bootstrap_ReferenceCountingInitialization", arguments = cfg => Expression.SharedEmptyArray, target = "Bootstrap_HeapInitialization", injectionPoint = BasicBlock.Qualifier.ExitInjectionStart }, new Injection { method = "ThreadManager_CleanupBootstrapThread", arguments = cfg => Expression.SharedEmptyArray, target = "ThreadManager_CleanupBootstrapThreadIfNeeded", injectionPoint = BasicBlock.Qualifier.EntryInjectionStart }, }; var ts = this.TypeSystem; foreach (var injection in injections) { var target = ts.GetWellKnownMethod( injection.target ); var cfg = TypeSystemForCodeTransformation.GetCodeForMethod( target ); var injectionPoint = cfg.GetInjectionPoint( injection.injectionPoint ); var method = ts.GetWellKnownMethod( injection.method ); var arguments = injection.arguments( cfg ); Operator call; if (method is StaticMethodRepresentation) { var rhs = ts.AddTypePointerToArgumentsOfStaticMethod( method, arguments ); call = StaticCallOperator.New( null, CallOperator.CallKind.Direct, method, rhs ); } else { call = InstanceCallOperator.New( null, CallOperator.CallKind.Direct, method, arguments, false ); } injectionPoint.AddOperator( call ); } } } } ================================================ FILE: Zelig/Zelig/CompileTime/CodeGenerator/CodeTransformation/CompilationSteps/Phases/ResourceManagerOptimizations.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // namespace Microsoft.Zelig.CodeGeneration.IR.CompilationSteps.Phases { using System; using System.Collections.Generic; using Microsoft.Zelig.Runtime.TypeSystem; //[PhaseDisabled()] [PhaseOrdering( ExecuteAfter=typeof(ApplyConfigurationSettings), ExecuteBefore=typeof(HighLevelTransformations) )] public sealed class ResourceManagerOptimizations : PhaseDriver { // // State // GrowOnlyHashTable< StaticMethodRepresentation, string > m_lookup; // // Constructor Methods // public ResourceManagerOptimizations( Controller context ) : base ( context ) { } // // Helper Methods // public override PhaseDriver Run() { this.CallsDataBase.Analyze( this.TypeSystem ); m_lookup = HashTableFactory.New< StaticMethodRepresentation, string >(); Handle_ResourceManagerImpl_GetObject1( "ResourceManagerImpl_GetObject1" ); Handle_ResourceManagerImpl_GetObject1( "ResourceManagerImpl_GetString1" ); Handle_ResourceManagerImpl_GetObject2( "ResourceManagerImpl_GetObject2" ); Handle_ResourceManagerImpl_GetObject2( "ResourceManagerImpl_GetString2" ); return this.NextPhase; } //--// // // The VS Designer generates this code pattern for resources: // // /// // /// Returns the cached ResourceManager instance used by this class. // /// // [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)] // internal static global::System.Resources.ResourceManager ResourceManager { // get { // if (object.ReferenceEquals(resourceMan, null)) { // global::System.Resources.ResourceManager temp = new global::System.Resources.ResourceManager( , typeof(Files).Assembly); // resourceMan = temp; // } // return resourceMan; // } // } // // /// // /// Overrides the current thread's CurrentUICulture property for all // /// resource lookups using this strongly typed resource class. // /// // [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)] // internal static global::System.Globalization.CultureInfo Culture { // get { // return resourceCulture; // } // set { // resourceCulture = value; // } // } // // internal static { // get { // object obj = ResourceManager.GetObject( , resourceCulture); // return ()(obj)); // } // } // // For an application that doesn't need to support runtime localization (aka: if resourceCulture is never assigned), // we could detect this code pattern and substitute the runtime calls with a compile-time assignment. // private void Handle_ResourceManagerImpl_GetObject1( string name ) { var md = this.TypeSystem.GetWellKnownMethodNoThrow( name ); if(md != null) { foreach(var op in this.CallsDataBase.CallsToMethod( md )) { if(op.BasicBlock == null) { // // Deleted call. // continue; } ConstantExpression exRes = GetActualResource( op, 1, 1 ); if(exRes != null) { Operator opResourceManager = op.GetPreviousOperator(); opResourceManager.Delete(); SubstituteGetObjectWithAssignment( op, exRes ); } } } } private void Handle_ResourceManagerImpl_GetObject2( string name ) { var md = this.TypeSystem.GetWellKnownMethodNoThrow( name ); if(md != null) { foreach(var op in this.CallsDataBase.CallsToMethod( md )) { ConstantExpression exRes = GetActualResource( op, 1, 2 ); if(exRes != null) { Operator opCultureInfo = op.GetPreviousOperator(); Operator opResourceManager = opCultureInfo.GetPreviousOperator(); opCultureInfo.Delete(); opResourceManager.Delete(); SubstituteGetObjectWithAssignment( op, exRes ); } } } } private static void SubstituteGetObjectWithAssignment( CallOperator op , ConstantExpression exRes ) { var ex = op.FirstResult; if(ex.Type.CanBeAssignedFrom( exRes.Type, null ) == false) { throw TypeConsistencyErrorException.Create( "Incompatible resource type found at {0}: {1} != {2}", op.BasicBlock.ToShortString(), ex.Type, exRes.Type ); } MethodRepresentation md = op.BasicBlock.Owner.Method; op.SubstituteWithOperator( SingleAssignmentOperator.New( op.DebugInfo, ex, exRes ), Operator.SubstitutionFlags.Default ); md.BuildTimeFlags |= MethodRepresentation.BuildTimeAttributes.Inline; md.BuildTimeFlags &= ~MethodRepresentation.BuildTimeAttributes.NoInline; } private ConstantExpression GetActualResource( CallOperator op , int resourceNameOffset , int resourceIdOffset ) { string resourceName = GetResourceName( op, resourceNameOffset ); if(resourceName != null) { StaticMethodRepresentation md = FindCallToResourceManager( op, resourceIdOffset, op.BasicBlock.Owner.Method.OwnerType ); if(md != null) { string resourceId = ExtractResourceIdentifier( md ); object res = FindResource( resourceId, resourceName ); if(res != null) { return this.TypeSystem.CreateConstantFromObject( res ); } } } return null; } private string GetResourceName( CallOperator op , int index ) { if(op.Arguments.Length > index && op.Arguments[index].Type == this.TypeSystem.WellKnownTypes.System_String) { var ex = op.Arguments[index] as ConstantExpression; if(ex != null) { var od = (DataManager.ObjectDescriptor)ex.Value; return (string)od.Source; } } return null; } private object FindResource( string resourceId , string resourceName ) { foreach(var res in this.TypeSystem.Resources) { if(res.Name == resourceId) { foreach(var pair in res.Values) { if(pair.Key == resourceName) { return pair.Value; } } } } return null; } private static StaticMethodRepresentation FindCallToResourceManager( Operator op , int offset , TypeRepresentation context ) { while(op != null && offset-- > 0) { op = op.GetPreviousOperator(); } var call = op as CallOperator; if(call != null && call.Results.Length == 1 && call.FirstResult is TemporaryVariableExpression) { var md = call.TargetMethod as StaticMethodRepresentation; if(md != null && md.Name == "get_ResourceManager" && md.OwnerType == context) { return md; } } return null; } private string ExtractResourceIdentifier( StaticMethodRepresentation md ) { string res; if(m_lookup.TryGetValue( md, out res ) == false) { var cfg = TypeSystemForCodeTransformation.GetCodeForMethod( md ); if(cfg != null) { var wkt = this.TypeSystem.WellKnownTypes; var td = wkt.System_Resources_ResourceManager; foreach(var call in cfg.FilterOperators< CallOperator >()) { var ctor = call.TargetMethod as ConstructorMethodRepresentation; if(ctor != null && ctor.OwnerType == td) { if(call.Arguments.Length == 3 && call.SecondArgument.Type == wkt.System_String) { var ex = call.SecondArgument as ConstantExpression; if(ex != null) { var od = (DataManager.ObjectDescriptor)ex.Value; res = (string)od.Source; m_lookup[md] = res; break; } } } } } } return res; } } } ================================================ FILE: Zelig/Zelig/CompileTime/CodeGenerator/CodeTransformation/CompilationSteps/Phases/SplitComplexOperators.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // namespace Microsoft.Zelig.CodeGeneration.IR.CompilationSteps.Phases { using System; using System.Collections.Generic; using Microsoft.Zelig.Runtime.TypeSystem; //[PhaseDisabled()] [PhaseOrdering( ExecuteAfter=typeof(ExpandAggregateTypes) )] public sealed class SplitComplexOperators : PhaseDriver { // // Constructor Methods // public SplitComplexOperators( Controller context ) : base ( context ) { } // // Helper Methods // public override PhaseDriver Run() { PerformParallelExecutionOfPhase( false, true ); return this.NextPhase; } } } ================================================ FILE: Zelig/Zelig/CompileTime/CodeGenerator/CodeTransformation/CompilationSteps/Phases/TransformFinallyBlocksIntoTryBlocks.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // namespace Microsoft.Zelig.CodeGeneration.IR.CompilationSteps.Phases { using System; using System.Collections.Generic; using Microsoft.Zelig.Runtime.TypeSystem; [PhaseOrdering( ExecuteAfter=typeof(ReduceNumberOfTemporaries) )] public sealed class TransformFinallyBlocksIntoTryBlocks : PhaseDriver { // // Constructor Methods // public TransformFinallyBlocksIntoTryBlocks( Controller context ) : base ( context ) { } // // Helper Methods // public override PhaseDriver Run() { ParallelTransformationsHandler.EnumerateFlowGraphs( this.TypeSystem, delegate( ControlFlowGraphStateForCodeTransformation cfg ) { Transformations.TransformFinallyBlocksIntoTryBlocks.Execute( cfg ); Transformations.MergeExtendedBasicBlocks.Execute( cfg, preserveInjectionSites: true ); } ); return this.NextPhase; } } } ================================================ FILE: Zelig/Zelig/CompileTime/CodeGenerator/CodeTransformation/ControlFlowGraphState/ControlFlowGraphStateForCodeTransformation.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // namespace Microsoft.Zelig.CodeGeneration.IR { using System; using System.Collections.Generic; using Microsoft.Zelig.Runtime.TypeSystem; public partial class ControlFlowGraphStateForCodeTransformation : ControlFlowGraphState { // // State // private TypeSystemForCodeTransformation m_typeSystem; private GrowOnlyHashTable< Expression, Expression[] > m_lookupFragments; private GrowOnlyHashTable< string , object > m_propertyBag; // // Constructor Methods // public ControlFlowGraphStateForCodeTransformation() // Default constructor required by TypeSystemSerializer. { AllocateState(); } public ControlFlowGraphStateForCodeTransformation( TypeSystemForCodeTransformation typeSystem , MethodRepresentation md ) : base( md ) { m_typeSystem = typeSystem; AllocateState(); } protected ControlFlowGraphStateForCodeTransformation( ControlFlowGraphState source ) : base( source ) { ControlFlowGraphStateForCodeTransformation source2 = (ControlFlowGraphStateForCodeTransformation)source; m_typeSystem = source2.m_typeSystem; AllocateState(); } private void AllocateState() { m_lookupFragments = HashTableFactory.NewWithReferenceEquality< Expression, Expression[] >(); m_propertyBag = HashTableFactory.New < string, object >(); } //--// public ControlFlowGraphStateForCodeTransformation Clone( InstantiationContext ic ) { ControlFlowGraphStateForCodeTransformation clonedCFG = new ControlFlowGraphStateForCodeTransformation( this ); CloningContext context = new CloneForwardGraph( this, clonedCFG, ic ); clonedCFG.CloneVariables( context, this ); context.Clone( m_entryBasicBlock ); return clonedCFG; } //--// protected override void CloneVariables( CloningContext context , ControlFlowGraphState source ) { ControlFlowGraphStateForCodeTransformation source2 = (ControlFlowGraphStateForCodeTransformation)source; base.CloneVariables( context, source2 ); foreach(VariableExpression var in source2.DataFlow_SpanningTree_Variables) { CloneVariable( context, source2, var ); } } private VariableExpression CloneVariable( CloningContext context , ControlFlowGraphStateForCodeTransformation source , VariableExpression var ) { VariableExpression newVar = context.LookupRegistered( var ); if(newVar == null) { TypeRepresentation td = var.Type; VariableExpression.DebugInfo debugInfo = var.DebugName; VariableExpression sourceVar = null; uint sourceOffset = 0; if(var is LowLevelVariableExpression) { LowLevelVariableExpression low = (LowLevelVariableExpression)var; if(low.SourceVariable != null) { sourceVar = CloneVariable( context, source, low.SourceVariable ); sourceOffset = low.SourceOffset; } } if(var is LocalVariableExpression) { LocalVariableExpression loc = (LocalVariableExpression)var; newVar = AllocateLocal( td, debugInfo ); } else if(var is TemporaryVariableExpression) { newVar = AllocateTemporary( td, debugInfo ); } else if(var is ExceptionObjectVariableExpression) { newVar = AllocateExceptionObjectVariable( td ); } else if(var is PhiVariableExpression) { PhiVariableExpression phiVar = (PhiVariableExpression)var; VariableExpression newTarget = CloneVariable( context, source, phiVar.Target ); newVar = AllocatePhiVariable( newTarget ); } else if(var is PseudoRegisterExpression) { newVar = AllocatePseudoRegister( td, debugInfo, sourceVar, sourceOffset ); } else if(var is TypedPhysicalRegisterExpression) { TypedPhysicalRegisterExpression reg = (TypedPhysicalRegisterExpression)var; newVar = AllocateTypedPhysicalRegister( td, reg.RegisterDescriptor, debugInfo, reg.SourceVariable, reg.SourceOffset ); } else if(var is PhysicalRegisterExpression) { PhysicalRegisterExpression reg = (PhysicalRegisterExpression)var; newVar = AllocatePhysicalRegister( reg.RegisterDescriptor ); } else if(var is StackLocationExpression) { StackLocationExpression stack = (StackLocationExpression)var; newVar = AllocateStackLocation( td, debugInfo, stack.Number, stack.StackPlacement, sourceVar, sourceOffset ); } else if(var is ConditionCodeExpression) { newVar = AllocateConditionCode(); } else { throw TypeConsistencyErrorException.Create( "Unexpected expression '{0}' during cloning of '{1}'", var, source ); } newVar.SkipReferenceCounting = var.SkipReferenceCounting; context.Register( var, newVar ); } return newVar; } //--// internal VariableExpression[] AllocateVariables( TypeRepresentation[] localVars , string[] localVarNames ) { if(m_md.ReturnType != m_typeSystem.WellKnownTypes.System_Void) { m_returnValue = AllocateTemporary( m_md.ReturnType, null ); } //--// TypeRepresentation[] args = m_md.ThisPlusArguments; int argsNum = args.Length; m_arguments = new VariableExpression[argsNum]; for(int i = 0; i < argsNum; i++) { VariableExpression.DebugInfo debugInfo; string[] names = m_md.ArgumentNames; if(names != null) { debugInfo = new VariableExpression.DebugInfo( m_md, names[i], i, false ); } else { debugInfo = null; } m_arguments[i] = new ArgumentVariableExpression( args[i], debugInfo, i ); // // We want to have each argument variable assigned to on entry to the method, // so we create an ArgumentValueOperator (see GenerateVariableInitialization) // Operator op = GenerateVariableInitialization( null, m_arguments[i] ); this.EntryBasicBlock.AddOperator( op ); } //--// VariableExpression[] locals; if(localVars == null) { locals = VariableExpression.SharedEmptyArray; } else { int varsNum = localVars.Length; locals = new VariableExpression[varsNum]; var bb = this.GetInjectionPoint( BasicBlock.Qualifier.PrologueEnd ); for(int i = 0; i < varsNum; i++) { VariableExpression.DebugInfo debugInfo; if(localVarNames != null) { debugInfo = new VariableExpression.DebugInfo( m_md, localVarNames[i], i, true ); } else { debugInfo = null; } locals[i] = AllocateLocal( localVars[i], debugInfo ); Operator op = GenerateVariableInitialization( null, locals[i] ); bb.AddOperator( op ); } } return locals; } //--// // // Helper Methods // public PhiVariableExpression AllocatePhiVariable( VariableExpression target ) { PhiVariableExpression newPhi = new PhiVariableExpression( target ); TrackVariable( newPhi ); return newPhi; } public PseudoRegisterExpression AllocatePseudoRegister( TypeRepresentation td ) { return AllocatePseudoRegister( td, null, null, 0 ); } public PseudoRegisterExpression AllocatePseudoRegister( TypeRepresentation td , VariableExpression.DebugInfo debugInfo ) { return AllocatePseudoRegister( td, debugInfo, null, 0 ); } internal PseudoRegisterExpression AllocatePseudoRegister( TypeRepresentation td , VariableExpression.DebugInfo debugInfo , VariableExpression sourceVar , uint sourceOffset ) { CHECKS.ASSERT( m_typeSystem.PlatformAbstraction.CanFitInRegister( td ), "Type '{0}' is too large to fit in a pseudo register", td ); PseudoRegisterExpression newPseudo = new PseudoRegisterExpression( td, debugInfo, sourceVar, sourceOffset ); TrackVariable( newPseudo ); return newPseudo; } public PhysicalRegisterExpression AllocatePhysicalRegister( Abstractions.RegisterDescriptor regDesc ) { for(int pos = m_variablesCount; --pos >= 0; ) { PhysicalRegisterExpression reg = m_variables[pos] as PhysicalRegisterExpression; if(reg != null && !(reg is TypedPhysicalRegisterExpression) && reg.Number == regDesc.Index) { return reg; } } TypeRepresentation td = m_typeSystem.PlatformAbstraction.GetRuntimeType( m_typeSystem, regDesc ); PhysicalRegisterExpression newReg = new PhysicalRegisterExpression( td, regDesc, null, null, 0 ); TrackVariable( newReg ); return newReg; } public TypedPhysicalRegisterExpression AllocateTypedPhysicalRegister( TypeRepresentation td , Abstractions.RegisterDescriptor regDesc , VariableExpression.DebugInfo debugInfo , VariableExpression sourceVar , uint sourceOffset ) { TypedPhysicalRegisterExpression newReg = new TypedPhysicalRegisterExpression( td, regDesc, debugInfo, sourceVar, sourceOffset ); TrackVariable( newReg ); return newReg; } internal StackLocationExpression AllocateLocalStackLocation( TypeRepresentation td , VariableExpression.DebugInfo debugInfo , VariableExpression sourceVar , uint sourceOffset ) { int wordOffset = 0; for(int pos = m_variablesCount; --pos >= 0; ) { StackLocationExpression stack = m_variables[pos] as StackLocationExpression; if(stack != null && stack.StackPlacement == StackLocationExpression.Placement.Local) { if(wordOffset <= stack.Number) { wordOffset = stack.Number + 1; } } } return AllocateStackLocation( td, debugInfo, wordOffset, StackLocationExpression.Placement.Local, sourceVar, sourceOffset ); } internal StackLocationExpression AllocateStackLocation( TypeRepresentation td , VariableExpression.DebugInfo debugInfo , int wordOffset , StackLocationExpression.Placement placement , VariableExpression sourceVar , uint sourceOffset ) { StackLocationExpression newStack = new StackLocationExpression( td, debugInfo, wordOffset, placement, sourceVar, sourceOffset ); TrackVariable( newStack ); return newStack; } public ConditionCodeExpression AllocateConditionCode() { if(m_typeSystem.PlatformAbstraction.CanUseMultipleConditionCodes == false) { for(int pos = m_variablesCount; --pos >= 0; ) { var cc = m_variables[pos] as ConditionCodeExpression; if(cc != null) { return cc; } } } //--// var newCC = new ConditionCodeExpression( m_typeSystem.WellKnownTypes.System_UInt32, null, 0 ); TrackVariable( newCC ); return newCC; } public void ApplyTransformation( TransformationContextForCodeTransformation context ) { context.Push( this ); InnerApplyTransformation( context ); context.Transform( ref m_typeSystem ); context.Transform( ref m_lookupFragments ); context.Transform( ref m_propertyBag ); ApplyTransformation_MapToMachine( context ); context.Pop(); } //--// public override Operator GenerateVariableInitialization( Debugging.DebugInfo debugInfo , Expression var , TypeRepresentation td , bool fThroughPointer ) { Expression ex; if(var is ArgumentVariableExpression) { // // We want to have each argument variable assigned to on entry to the method, so we create an InvalidateExpressionOperator. // return InitialValueOperator.New( debugInfo, (VariableExpression)var ); } if(td is ReferenceTypeRepresentation || td is PointerTypeRepresentation ) { ex = m_typeSystem.CreateNullPointer( td ); } else { if(td is EnumerationTypeRepresentation) { td = td.UnderlyingType; } if(td is ScalarTypeRepresentation) { object val; switch(td.BuiltInType) { case TypeRepresentation.BuiltInTypes.BOOLEAN: val = (System.Boolean)false; break; case TypeRepresentation.BuiltInTypes.CHAR : val = (System.Char ) 0; break; case TypeRepresentation.BuiltInTypes.I1 : val = (System.SByte ) 0; break; case TypeRepresentation.BuiltInTypes.U1 : val = (System.Byte ) 0; break; case TypeRepresentation.BuiltInTypes.I2 : val = (System.Int16 ) 0; break; case TypeRepresentation.BuiltInTypes.U2 : val = (System.UInt16 ) 0; break; case TypeRepresentation.BuiltInTypes.I4 : val = (System.Int32 ) 0; break; case TypeRepresentation.BuiltInTypes.U4 : val = (System.UInt32 ) 0; break; case TypeRepresentation.BuiltInTypes.I8 : val = (System.Int64 ) 0; break; case TypeRepresentation.BuiltInTypes.U8 : val = (System.UInt64 ) 0; break; case TypeRepresentation.BuiltInTypes.R4 : val = (System.Single ) 0; break; case TypeRepresentation.BuiltInTypes.R8 : val = (System.Double ) 0; break; case TypeRepresentation.BuiltInTypes.I : val = (System.IntPtr ) 0; break; case TypeRepresentation.BuiltInTypes.U : val = (System.UIntPtr) 0; break; default: throw IncorrectEncodingException.Create( "Unexpected type {0} for {1}", td.BuiltInType, var ); } ex = m_typeSystem.CreateConstant( td, val ); } else { // // TODO: expose a hook to allow arbitrary variable initialization policies. // CustomAttributeRepresentation ca; if(m_typeSystem.MemoryMappedBitFieldPeripherals.TryGetValue( td, out ca )) { return GenerateVariableInitialization( debugInfo, var, ca.GetNamedArg< TypeRepresentation >( "PhysicalType" ), fThroughPointer ); } ex = m_typeSystem.CreateConstant( td, null ); } } if(fThroughPointer) { return StoreIndirectOperator.New( debugInfo, td, var, ex, null, 0, true ); } else { return SingleAssignmentOperator.New( debugInfo, (VariableExpression)var, ex ); } } public void DropDeadVariables() { m_variables = this.DataFlow_SpanningTree_Variables; m_variablesCount = m_variables.Length; } public VariableExpression[] SortVariables() { VariableExpression[] variables = ArrayUtility.CopyNotNullArray( this.DataFlow_SpanningTree_Variables ); Array.Sort( variables, VariableExpression.GetSorter() ); return variables; } public override void RenumberVariables() { base.RenumberVariables(); GrowOnlyHashTable < VariableExpression, int > phiVersions = null; int numPhi = 0; int numPseudo = 0; int numCC = 0; for(int pos = m_variablesCount; --pos >= 0; ) { VariableExpression var = m_variables[pos] as VariableExpression; if(var is PhiVariableExpression) { PhiVariableExpression varPhi = (PhiVariableExpression)var; int version; if(phiVersions == null) { phiVersions = HashTableFactory.NewWithReferenceEquality< VariableExpression, int >(); } int maxVersion; if(phiVersions.TryGetValue( varPhi.Target, out maxVersion )) { version = maxVersion + 1; } else { version = 1; } varPhi.Version = version; phiVersions[varPhi.Target] = version; var.Number = numPhi++; } else if(var is PseudoRegisterExpression) { var.Number = numPseudo++; } else if(var is StackLocationExpression) { } else if(var is ConditionCodeExpression) { var.Number = numCC++; } } } //--// public override BasicBlock GetInjectionPoint( BasicBlock.Qualifier qualifier ) { foreach(BasicBlock bb in this.DataFlow_SpanningTree_BasicBlocks) { if(bb.Annotation == qualifier) { return bb; } } bool fAddAfter; switch(qualifier) { case BasicBlock.Qualifier.Entry: return this.EntryBasicBlock; case BasicBlock.Qualifier.PrologueStart: case BasicBlock.Qualifier.PrologueEnd: case BasicBlock.Qualifier.EntryInjectionStart: case BasicBlock.Qualifier.EntryInjectionEnd: fAddAfter = true; break; case BasicBlock.Qualifier.ExitInjectionStart: case BasicBlock.Qualifier.ExitInjectionEnd: case BasicBlock.Qualifier.EpilogueStart: case BasicBlock.Qualifier.EpilogueEnd: fAddAfter = false; break; case BasicBlock.Qualifier.Exit: return this.ExitBasicBlock; default: return null; } BasicBlock res; if(fAddAfter) { var targetBB = GetInjectionPoint( qualifier - 1 ); CHECKS.ASSERT( targetBB.Successors.Length == 1, "Internal failure: entry basic block has more than one successor in '{0}'", this ); res = targetBB.InsertNewSuccessor( targetBB.FirstSuccessor ); } else { var targetBB = GetInjectionPoint( qualifier + 1 ); if(targetBB == null) { return null; } res = targetBB.InsertNewPredecessor(); } res.Annotation = qualifier; return res; } //--// public bool HasProperty( string key ) { return m_propertyBag.ContainsKey( key ); } public object GetPropertyValue( string key ) { object res; m_propertyBag.TryGetValue( key, out res ); return res; } public bool SetPropertyValue( string key , object value ) { return m_propertyBag.Update( key, value ); } public bool SetProperty( string key ) { return SetPropertyValue( key, null ); } //--// // // Access Methods // public override TypeSystemForIR TypeSystemForIR { get { return m_typeSystem; } } public TypeSystemForCodeTransformation TypeSystem { get { return m_typeSystem; } } } } ================================================ FILE: Zelig/Zelig/CompileTime/CodeGenerator/CodeTransformation/ControlFlowGraphState/ControlFlowGraphStateForCodeTransformation_CompilationConstraintsLookup.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // namespace Microsoft.Zelig.CodeGeneration.IR { using System; using System.Collections.Generic; using Microsoft.Zelig.Runtime.TypeSystem; public partial class ControlFlowGraphStateForCodeTransformation { struct MergeHelper { // // State // CompilationConstraints[] m_array1; CompilationConstraints[] m_array2; CompilationConstraints[] m_arrayRes; // // Helper Methods // internal void Init( CompilationConstraints[] array1 , CompilationConstraints[] array2 ) { m_array1 = array1; m_array2 = array2; m_arrayRes = SharedEmptyCompilationConstraintsArray; } internal void Apply( params CompilationConstraints[] ccFilter ) { foreach(CompilationConstraints cc in ccFilter) { if(HasCompilationConstraint( m_array1, cc ) || HasCompilationConstraint( m_array2, cc ) ) { m_arrayRes = AddCompilationConstraint( m_arrayRes, cc ); return; } } } // // Access Methods // internal CompilationConstraints[] Result { get { return m_arrayRes; } } } struct ConvertHelper { // // State // private CompilationConstraints[] m_ccPre; private CompilationConstraints[] m_ccPost; internal CompilationConstraints[] m_ccResult; // // Helper Methods // internal void Init( CompilationConstraints[] ccPre , CompilationConstraints[] ccPost ) { m_ccPre = ccPre; m_ccPost = ccPost; m_ccResult = ControlFlowGraphState.SharedEmptyCompilationConstraintsArray; } internal void Apply( params CompilationConstraints[] ccFilter ) { foreach(CompilationConstraints cc in ccFilter) { if(HasCompilationConstraint( m_ccPost, cc )) { m_ccResult = AddCompilationConstraint( m_ccResult, cc ); return; } } foreach(CompilationConstraints cc in ccFilter) { if(HasCompilationConstraint( m_ccPre, cc )) { m_ccResult = AddCompilationConstraint( m_ccResult, cc ); return; } } } } struct DeltaHelper { // // State // private CompilationConstraints[] m_ccPre; private CompilationConstraints[] m_ccPost; internal CompilationConstraints[] m_ccSet; internal CompilationConstraints[] m_ccReset; internal bool m_fNotEmpty; // // Helper Methods // internal void Init( CompilationConstraints[] ccPre , CompilationConstraints[] ccPost ) { m_ccPre = ccPre; m_ccPost = ccPost; m_ccSet = ControlFlowGraphState.SharedEmptyCompilationConstraintsArray; m_ccReset = ControlFlowGraphState.SharedEmptyCompilationConstraintsArray; m_fNotEmpty = false; } internal void Apply( params CompilationConstraints[] ccFilter ) { CompilationConstraints ccPre; CompilationConstraints ccPost; bool fGotPre = HasAnyCompilationConstraint( m_ccPre , out ccPre , ccFilter ); bool fGotPost = HasAnyCompilationConstraint( m_ccPost, out ccPost, ccFilter ); if(fGotPre && fGotPost) { if(ccPre == ccPost) { return; } } if(fGotPre) { m_ccReset = ControlFlowGraphState.AddCompilationConstraint( m_ccReset, ccPre ); m_fNotEmpty = true; } if(fGotPost) { m_ccSet = ControlFlowGraphState.AddCompilationConstraint( m_ccSet, ccPost ); m_fNotEmpty = true; } } static bool Find( CompilationConstraints[] ccTarget , CompilationConstraints[] ccFilter , out CompilationConstraints match ) { foreach(CompilationConstraints cc in ccFilter) { if(HasCompilationConstraint( ccTarget, cc )) { match = cc; return true; } } match = default(CompilationConstraints); return false; } } //--// // // State // // // Constructor Methods // // // Helper Methods // public bool EnforceCompilationConstraints( List< CallOperator > toBeInlined ) { GrowOnlyHashTable< BasicBlock, CompilationConstraints[] > ht = HashTableFactory.NewWithReferenceEquality< BasicBlock, CompilationConstraints[] >(); return PropagateCompilationConstraints( ht, this.EntryBasicBlock, this.CompilationConstraintsArray, toBeInlined ); } public GrowOnlyHashTable< BasicBlock, CompilationConstraints[] > PropagateCompilationConstraints( CompilationConstraints[] ccStart ) { GrowOnlyHashTable< BasicBlock, CompilationConstraints[] > ht = HashTableFactory.NewWithReferenceEquality< BasicBlock, CompilationConstraints[] >(); if(PropagateCompilationConstraints( ht, this.EntryBasicBlock, ccStart, null )) { return ht; } return null; } private static bool PropagateCompilationConstraints( GrowOnlyHashTable< BasicBlock, CompilationConstraints[] > ht , BasicBlock bb , CompilationConstraints[] ccArray , List< CallOperator > toBeInlined ) { CompilationConstraints[] ccArrayOld; if(ht.TryGetValue( bb, out ccArrayOld )) { if(SameCompilationConstraints( ccArrayOld, ccArray )) { return true; } //--// MergeHelper helper = new MergeHelper(); helper.Init( ccArray, ccArrayOld ); helper.Apply( CompilationConstraints.Allocations_OFF , CompilationConstraints.Allocations_ON ); helper.Apply( CompilationConstraints.StackAccess_OFF , CompilationConstraints.StackAccess_ON ); helper.Apply( CompilationConstraints.BoundsChecks_OFF_DEEP , CompilationConstraints.BoundsChecks_OFF , CompilationConstraints.BoundsChecks_ON ); helper.Apply( CompilationConstraints.NullChecks_OFF_DEEP , CompilationConstraints.NullChecks_OFF , CompilationConstraints.NullChecks_ON ); ccArray = helper.Result; } ht[bb] = ccArray; ccArray = PropagateCompilationConstraintsThroughOperators( bb, ccArray, null, toBeInlined ); if(ccArray == null) { return false; } foreach(BasicBlockEdge edge in bb.Successors) { if(!PropagateCompilationConstraints( ht, edge.Successor, ccArray, toBeInlined )) { return false; } } return true; } private static CompilationConstraints[] PropagateCompilationConstraintsThroughOperators( BasicBlock bb , CompilationConstraints[] ccArray , Operator opStopAt , List< CallOperator > toBeInlined ) { foreach(Operator op in bb.Operators) { if(op == opStopAt) { break; } if(op is CallOperator) { CallOperator call = (CallOperator)op; if(toBeInlined != null) { if(HasCompilationConstraint( ccArray, CompilationConstraints.StackAccess_OFF )) { if(call.CallType == CallOperator.CallKind.Virtual) { throw TypeConsistencyErrorException.Create( "Found a virtual method call '{0}' in a StackNotAvailable context: '{1}'", call.TargetMethod, bb.Owner.Method ); } if(call.TargetMethod.HasBuildTimeFlag( MethodRepresentation.BuildTimeAttributes.NoInline )) { // // TODO: Should we ignore the attribute?? // } else { toBeInlined.Add( call ); return null; } } if(HasCompilationConstraint( ccArray, CompilationConstraints.Allocations_OFF )) { // // TODO: This cannot be properly processed here, we'd need to have fully expanded the callee to analyze it properly... // } } if(call.TargetMethod.HasBuildTimeFlag( MethodRepresentation.BuildTimeAttributes.CanAllocateOnReturn )) { ccArray = RemoveCompilationConstraint( ccArray, CompilationConstraints.Allocations_OFF ); ccArray = AddCompilationConstraint ( ccArray, CompilationConstraints.Allocations_ON ); } } else { if(toBeInlined != null) { if(op.MayAllocateStorage && HasCompilationConstraint( ccArray, CompilationConstraints.Allocations_OFF )) { throw TypeConsistencyErrorException.Create( "Allocating operator '{0}' found in a CannotAllocate context: '{1}'", op, bb.Owner.Method ); } } } if(op is CompilationConstraintsOperator) { CompilationConstraintsOperator ccOp = (CompilationConstraintsOperator)op; ccArray = ccOp.TransformCompilationConstraints( ccArray ); } } return ccArray; } //--// public static CompilationConstraints[] ComposeCompilationConstraints( CompilationConstraints[] ccPre , CompilationConstraints[] ccPost ) { ConvertHelper cnvHelper = new ConvertHelper(); cnvHelper.Init( ccPre, ccPost ); cnvHelper.Apply( CompilationConstraints.Allocations_OFF , CompilationConstraints.Allocations_ON ); cnvHelper.Apply( CompilationConstraints.StackAccess_OFF , CompilationConstraints.StackAccess_ON ); cnvHelper.Apply( CompilationConstraints.BoundsChecks_OFF_DEEP , CompilationConstraints.BoundsChecks_OFF , CompilationConstraints.BoundsChecks_ON ); cnvHelper.Apply( CompilationConstraints.NullChecks_OFF_DEEP , CompilationConstraints.NullChecks_OFF , CompilationConstraints.NullChecks_ON ); return cnvHelper.m_ccResult; } public static bool ComputeDeltaBetweenCompilationConstraints( CompilationConstraints[] ccPre , CompilationConstraints[] ccPost , out CompilationConstraints[] ccSet , out CompilationConstraints[] ccReset ) { DeltaHelper dltHelper = new DeltaHelper(); dltHelper.Init( ccPre, ccPost ); dltHelper.Apply( CompilationConstraints.Allocations_OFF , CompilationConstraints.Allocations_ON ); dltHelper.Apply( CompilationConstraints.StackAccess_OFF , CompilationConstraints.StackAccess_ON ); dltHelper.Apply( CompilationConstraints.BoundsChecks_OFF_DEEP , CompilationConstraints.BoundsChecks_OFF , CompilationConstraints.BoundsChecks_ON ); dltHelper.Apply( CompilationConstraints.NullChecks_OFF_DEEP , CompilationConstraints.NullChecks_OFF , CompilationConstraints.NullChecks_ON ); ccSet = dltHelper.m_ccSet; ccReset = dltHelper.m_ccReset; return dltHelper.m_fNotEmpty; } //--// public CompilationConstraints[] CompilationConstraintsAtBasicBlockEntry( BasicBlock bb ) { GrowOnlyHashTable< BasicBlock, CompilationConstraints[] > ht = PropagateCompilationConstraints( this.CompilationConstraintsArray ); if(ht == null) { throw TypeConsistencyErrorException.Create( "Cannot propagate compilation constraints in {0}", this ); } return CompilationConstraintsAtBasicBlockEntry( ht, bb ); } public static CompilationConstraints[] CompilationConstraintsAtBasicBlockEntry( GrowOnlyHashTable< BasicBlock, CompilationConstraints[] > ht , BasicBlock bb ) { CompilationConstraints[] res; if(ht.TryGetValue( bb, out res ) == false) { res = ControlFlowGraphState.SharedEmptyCompilationConstraintsArray; } return res; } public static CompilationConstraints[] CompilationConstraintsAtBasicBlockExit( GrowOnlyHashTable< BasicBlock, CompilationConstraints[] > ht , BasicBlock bb ) { CompilationConstraints[] res = CompilationConstraintsAtBasicBlockEntry( ht, bb ); res = PropagateCompilationConstraintsThroughOperators( bb, res, null, null ); if(res == null) { throw TypeConsistencyErrorException.Create( "Cannot propagate compilation constraints in {0} to basic block {1}", bb.Owner, bb ); } return res; } public CompilationConstraints[] CompilationConstraintsAtOperator( Operator op ) { CompilationConstraints[] res = CompilationConstraintsAtBasicBlockEntry( op.BasicBlock ); res = PropagateCompilationConstraintsThroughOperators( op.BasicBlock, res, op, null ); if(res == null) { throw TypeConsistencyErrorException.Create( "Cannot propagate compilation constraints in {0} to operator {1}", this, op ); } return res; } } } ================================================ FILE: Zelig/Zelig/CompileTime/CodeGenerator/CodeTransformation/ControlFlowGraphState/ControlFlowGraphStateForCodeTransformation_Dominance.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // namespace Microsoft.Zelig.CodeGeneration.IR { using System; using System.Collections.Generic; using Microsoft.Zelig.Runtime.TypeSystem; public partial class ControlFlowGraphStateForCodeTransformation { class CacheInfo_Dominance : CachedInfo { // // State // internal DataFlow.ControlTree.Dominance m_dominance; // // Helper Methods // protected override void Update() { ControlFlowGraphStateForCodeTransformation cfg = (ControlFlowGraphStateForCodeTransformation)m_owner; using(new PerformanceCounters.ContextualTiming( cfg, "Dominance" )) { m_dominance = new DataFlow.ControlTree.Dominance( cfg ); } } } // // Helper Methods // public IDisposable LockDominance() { var ci = GetCachedInfo< CacheInfo_Dominance >(); ci.Lock(); return ci; } // // Access Methods // [System.Diagnostics.DebuggerBrowsable( System.Diagnostics.DebuggerBrowsableState.Never )] public BasicBlock[] DataFlow_ImmediateDominators { get { var ci = GetCachedInfo< CacheInfo_Dominance >(); return ci.m_dominance.GetImmediateDominators(); } } [System.Diagnostics.DebuggerBrowsable( System.Diagnostics.DebuggerBrowsableState.Never )] public BitVector[] DataFlow_Dominance { get { var ci = GetCachedInfo< CacheInfo_Dominance >(); return ci.m_dominance.GetDominance(); } } [System.Diagnostics.DebuggerBrowsable( System.Diagnostics.DebuggerBrowsableState.Never )] public BitVector[] DataFlow_DominanceFrontier { get { var ci = GetCachedInfo< CacheInfo_Dominance >(); return ci.m_dominance.GetDominanceFrontier(); } } } } ================================================ FILE: Zelig/Zelig/CompileTime/CodeGenerator/CodeTransformation/ControlFlowGraphState/ControlFlowGraphStateForCodeTransformation_Liveness.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // namespace Microsoft.Zelig.CodeGeneration.IR { using System; using System.Collections.Generic; using Microsoft.Zelig.Runtime.TypeSystem; public partial class ControlFlowGraphStateForCodeTransformation { class CacheInfo_Liveness : CachedInfo { // // State // internal DataFlow.LivenessAnalysis m_liveness; // // Helper Methods // protected override void Update() { ControlFlowGraphStateForCodeTransformation cfg = (ControlFlowGraphStateForCodeTransformation)m_owner; using(new PerformanceCounters.ContextualTiming( cfg, "Liveness" )) { m_liveness = DataFlow.LivenessAnalysis.Compute( cfg, false ); } } } // // Helper Methods // public IDisposable LockLiveness() { var ci = GetCachedInfo< CacheInfo_Liveness >(); ci.Lock(); return ci; } // // Access Methods // [System.Diagnostics.DebuggerBrowsable( System.Diagnostics.DebuggerBrowsableState.Never )] public BitVector[] DataFlow_LivenessAtBasicBlockEntry // It's indexed as [][] { get { var ci = GetCachedInfo< CacheInfo_Liveness >(); return ci.m_liveness.LivenessAtBasicBlockEntry; } } [System.Diagnostics.DebuggerBrowsable( System.Diagnostics.DebuggerBrowsableState.Never )] public BitVector[] DataFlow_LivenessAtBasicBlockExit // It's indexed as [][] { get { var ci = GetCachedInfo< CacheInfo_Liveness >(); return ci.m_liveness.LivenessAtBasicBlockExit; } } [System.Diagnostics.DebuggerBrowsable( System.Diagnostics.DebuggerBrowsableState.Never )] public BitVector[] DataFlow_LivenessAtOperator // It's indexed as [][] { get { var ci = GetCachedInfo< CacheInfo_Liveness >(); return ci.m_liveness.LivenessAtOperator; } } [System.Diagnostics.DebuggerBrowsable( System.Diagnostics.DebuggerBrowsableState.Never )] public BitVector[] DataFlow_VariableLivenessMap // It's indexed as [][] { get { var ci = GetCachedInfo< CacheInfo_Liveness >(); return ci.m_liveness.VariableLivenessMap; } } } } ================================================ FILE: Zelig/Zelig/CompileTime/CodeGenerator/CodeTransformation/ControlFlowGraphState/ControlFlowGraphStateForCodeTransformation_MapToMachine.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // namespace Microsoft.Zelig.CodeGeneration.IR { using System; using System.Collections.Generic; using Microsoft.Zelig.Runtime.TypeSystem; public partial class ControlFlowGraphStateForCodeTransformation { const string MappedToMachine = "VariablesMappedToMachine"; public class ValueFragment : ITransformationContextTarget { // // State // private object m_target; private uint m_offset; // // Constructor Methods // internal ValueFragment( object target , uint offset ) { m_target = target; m_offset = offset; } // // Helper Methods // void ITransformationContextTarget.ApplyTransformation( TransformationContext context ) { context.Push( this ); context.Transform( ref m_target ); context.Transform( ref m_offset ); context.Pop(); } //--// // // Access Methods // public uint Value { get { return DataConversion.GetFragmentOfNumber( m_target, (int)m_offset ); } } // // Debug Methods // public override string ToString() { return string.Format( "", m_offset, m_target ); } } // // State // private Abstractions.CallingConvention.CallState m_callState; // // Constructor Methods // //--// // // Helper Methods // private void ApplyTransformation_MapToMachine( TransformationContextForCodeTransformation context ) { context.TransformGeneric( ref m_callState ); } //--//--//--//--//--//--//--// internal void MapVariables() { if(SetProperty( MappedToMachine ) == false) { m_callState = m_typeSystem.CallingConvention.CreateCallState( Abstractions.CallingConvention.Direction.Callee ); Operator insertionOp = this.GetInjectionPoint( BasicBlock.Qualifier.PrologueEnd ).FirstOperator; MapIncomingArgumentsBasedOnCallingConvention( insertionOp ); MapTheRestOfTheVariables ( insertionOp ); RemoveOldArgumentValueOperators ( this.EntryBasicBlock ); AddInvalidateOperatorsToExceptionHandlers(); } } //--//--//--//--//--//--//--// private void MapIncomingArgumentsBasedOnCallingConvention( Operator insertionOp ) { Abstractions.CallingConvention cc = m_typeSystem.CallingConvention; Expression[] fragments = cc.AssignReturnValue( this, insertionOp, m_returnValue, m_callState ); if(fragments != null) { SetFragmentsForExpression( m_returnValue, fragments ); } /// /// Do not add 'this' pointer as part of the incoming arguments for exported methods /// bool fAddCurrentArg = 0 == (this.Method.BuildTimeFlags & MethodRepresentation.BuildTimeAttributes.Exported); foreach(VariableExpression exArg in m_arguments) { if(fAddCurrentArg) { SetFragmentsForExpression( exArg, cc.AssignArgument( this, insertionOp, exArg, m_callState ) ); } fAddCurrentArg = true; } } private void MapTheRestOfTheVariables( Operator insertingOp ) { VariableExpression [] vars = this.DataFlow_SpanningTree_Variables; VariableExpression.Property[] varProps = this.DataFlow_PropertiesOfVariables; for(int i = 0; i < vars.Length; i++) { VariableExpression var = vars[i]; if(m_typeSystem.GetLevel( var ) <= Operator.OperatorLevel.ScalarValues) { // // Only high-level expressions need to be mapped. // continue; } Expression[] fragments = GetFragmentsForExpression( var ); Expression[] fragmentsNew; // // Any variable that is bigger than 64 bits or whose address is taken must be allocated on the stack. // if((varProps[i] & VariableExpression.Property.AddressTaken) != 0 || var.Type.SizeOfHoldingVariableInWords > 2) { bool fAllocate; if(fragments == null) { fAllocate = true; } else { fAllocate = false; foreach(Expression fragment in fragments) { if(!(fragment is StackLocationExpression)) { fAllocate = true; break; } } } if(fAllocate) { fragmentsNew = MapExpressionToFragments( null, var.DebugName, var, m_callState, KindOfFragment.AllocateStackLocalLocation ); } else { fragmentsNew = null; } } else if(fragments == null) { fragmentsNew = MapExpressionToFragments( null, var.DebugName, var, m_callState, KindOfFragment.AllocatePseudoRegister ); } else { fragmentsNew = null; } if(fragmentsNew != null) { SetFragmentsForExpression( var, fragmentsNew ); if(fragments != null) { CHECKS.ASSERT( fragments.Length == fragmentsNew.Length, "Cannot copy between different-sized expressions" ); // // Insert assignment ops for all the variables that have been reassigned. // for(int fragIdx = 0; fragIdx < fragments.Length; fragIdx++) { Expression src = fragments [fragIdx]; Expression dst = fragmentsNew[fragIdx]; if(src != dst) { insertingOp.AddOperatorBefore( SingleAssignmentOperator.New( null, (VariableExpression)dst, src ) ); } } } } } } private void RemoveOldArgumentValueOperators( BasicBlock bb ) { // // Arguments are passed through an invalidation operator, so that they appear always assigned to. // We need to remove these operators, since now we have equivalent ones for the fragments. // foreach(Operator op in bb.Operators) { if(op is InitialValueOperator) { if(ArrayUtility.FindReferenceInNotNullArray( m_arguments, op.FirstResult ) >= 0) { op.Delete(); } } } } private void AddInvalidateOperatorsToExceptionHandlers() { foreach(BasicBlock bb in m_basicBlocks) { if(bb is ExceptionHandlerBasicBlock) { var op = NopOperator.New( null ); bb.FirstOperator.AddOperatorBefore( op ); foreach(VariableExpression exToInvalidate in m_typeSystem.CallingConvention.CollectExpressionsToInvalidate( this, null, null )) { op.AddAnnotation( PostInvalidationAnnotation.Create( m_typeSystem, exToInvalidate ) ); } } } } //--//--//--//--//--//--//--// public enum KindOfFragment { CopyIncomingArgumentFromPhysicalToPseudoRegister, CopyIncomingArgumentFromStackToPseudoRegister , AllocatePhysicalRegisterForArgument , AllocatePhysicalRegisterForReturnValue , AllocatePseudoRegister , AllocateStackInLocation , AllocateStackLocalLocation , AllocateStackOutLocation , } public Expression[] MapExpressionToFragments( Operator insertionOp , VariableExpression.DebugInfo debugInfo , VariableExpression sourceVar , Abstractions.CallingConvention.CallState callState , KindOfFragment kind ) { return MapExpressionToFragments( insertionOp, debugInfo, sourceVar, sourceVar.Type, callState, kind ); } public Expression[] MapExpressionToFragments( Operator insertionOp , VariableExpression.DebugInfo debugInfo , VariableExpression sourceVar , TypeRepresentation sourceTd , Abstractions.CallingConvention.CallState callState , KindOfFragment kind ) { uint sourceFragments; bool fDirect; m_typeSystem.PlatformAbstraction.ComputeNumberOfFragmentsForExpression( sourceTd, kind, out sourceFragments, out fDirect ); Expression[] res = new Expression[sourceFragments]; TypeRepresentation genericTd = m_typeSystem.WellKnownTypes.System_UInt32; Abstractions.Platform pa = m_typeSystem.PlatformAbstraction; for(uint offset = 0; offset < sourceFragments; offset++) { uint sourceOffset = offset * sizeof(uint); TypeRepresentation fragmentTd; Expression exFragment; if(fDirect) { fragmentTd = sourceTd; } else if(sourceTd is ScalarTypeRepresentation && sourceFragments == 1) { fragmentTd = sourceTd; } else { fragmentTd = genericTd; InstanceFieldRepresentation fd = sourceTd.FindFieldAtOffset( (int)sourceOffset ); if(fd != null) { TypeRepresentation fieldTd = fd.FieldType; if(fieldTd.SizeOfHoldingVariable == genericTd.SizeOfHoldingVariable) { fragmentTd = fieldTd; } } } switch(kind) { case KindOfFragment.CopyIncomingArgumentFromPhysicalToPseudoRegister: { exFragment = AllocatePseudoRegister( fragmentTd, debugInfo, sourceVar, sourceOffset ); // // Invalidate the physical register and then copy it to pseudo one. // TypedPhysicalRegisterExpression exReg = AllocateTypedPhysicalRegister( fragmentTd, callState.GetNextRegister( pa, sourceTd, fragmentTd, kind ), debugInfo, sourceVar, sourceOffset ); var opNew = SingleAssignmentOperator.New( insertionOp.DebugInfo, (VariableExpression)exFragment, exReg ); insertionOp.AddOperatorBefore( opNew ); // // Don't copy propagate the input registers. // opNew.AddAnnotation( BlockCopyPropagationAnnotation.Create( this.TypeSystem, 0, false, false ) ); // // This pointer is always not null. // if(this.Method is InstanceMethodRepresentation && sourceVar == this.Arguments[0]) { opNew.AddAnnotation( NotNullAnnotation.Create( this.TypeSystem ) ); } var opTarget = GetTarget( insertionOp ); opTarget.AddOperatorBefore( InitialValueOperator.New( insertionOp.DebugInfo, exReg ) ); } break; case KindOfFragment.CopyIncomingArgumentFromStackToPseudoRegister: { exFragment = AllocatePseudoRegister( fragmentTd, debugInfo, sourceVar, sourceOffset ); StackLocationExpression exStack = AllocateStackLocation( fragmentTd, debugInfo, callState.GetNextIndex( pa, sourceTd, fragmentTd, kind ), StackLocationExpression.Placement.In, sourceVar, sourceOffset ); insertionOp.AddOperatorBefore( SingleAssignmentOperator.New( insertionOp.DebugInfo, (VariableExpression)exFragment, exStack ) ); Operator opTarget = GetTarget( insertionOp ); opTarget.AddOperatorBefore( InitialValueOperator.New( insertionOp.DebugInfo, exStack ) ); } break; case KindOfFragment.AllocatePhysicalRegisterForArgument: case KindOfFragment.AllocatePhysicalRegisterForReturnValue: exFragment = AllocateTypedPhysicalRegister( fragmentTd, callState.GetNextRegister( pa, sourceTd, fragmentTd, kind ), debugInfo, sourceVar, sourceOffset ); break; case KindOfFragment.AllocatePseudoRegister: exFragment = AllocatePseudoRegister( fragmentTd, debugInfo, sourceVar, sourceOffset ); break; case KindOfFragment.AllocateStackInLocation: case KindOfFragment.AllocateStackLocalLocation: case KindOfFragment.AllocateStackOutLocation: { StackLocationExpression.Placement stackPlacement; if (kind == KindOfFragment.AllocateStackInLocation ) stackPlacement = StackLocationExpression.Placement.In; else if(kind == KindOfFragment.AllocateStackLocalLocation) stackPlacement = StackLocationExpression.Placement.Local; else stackPlacement = StackLocationExpression.Placement.Out; StackLocationExpression exStack = AllocateStackLocation( fragmentTd, debugInfo, callState.GetNextIndex( pa, sourceTd, fragmentTd, kind ), stackPlacement, sourceVar, sourceOffset ); if(kind == KindOfFragment.AllocateStackInLocation) { Operator opTarget = GetTarget( insertionOp ); opTarget.AddOperatorBefore( InitialValueOperator.New( insertionOp.DebugInfo, exStack ) ); } exFragment = exStack; } break; default: exFragment = null; break; } res[offset] = exFragment; } return res; } private static Operator GetTarget( Operator op ) { return op.BasicBlock.Owner.EntryBasicBlock.GetFirstDifferentOperator( typeof(InitialValueOperator) ); } //--// public Expression[][] GetFragmentsForExpressionArray( Expression[] exArray ) { var res = new Expression[exArray.Length][]; for(int i = 0; i < exArray.Length; i++) { res[i] = GetFragmentsForExpression( exArray[i] ); } return res; } public Expression[] GetFragmentsForExpression( Expression ex ) { Expression[] res; if(m_lookupFragments.TryGetValue( ex, out res ) == false) { if(ex is LowLevelVariableExpression) { res = new Expression[] { ex }; SetFragmentsForExpression( ex, res ); } else if(ex is ConstantExpression) { ConstantExpression exConst = (ConstantExpression)ex; TypeRepresentation td = exConst.Type; object val = exConst.Value; uint sourceFragments; bool fDirect; m_typeSystem.PlatformAbstraction.ComputeNumberOfFragmentsForExpression( td, KindOfFragment.AllocatePseudoRegister, out sourceFragments, out fDirect ); res = new Expression[sourceFragments]; if(sourceFragments == 1 && m_typeSystem.GetLevel( exConst ) <= Operator.OperatorLevel.ScalarValues) { res[0] = exConst; } else { TypeRepresentation genericTd = m_typeSystem.WellKnownTypes.System_UInt32; for(uint offset = 0; offset < sourceFragments; offset++) { uint byteOffset = offset * sizeof(uint); InstanceFieldRepresentation fd = td.FindFieldAtOffset( (int)byteOffset ); TypeRepresentation fragmentTd = genericTd; if(fd != null) { TypeRepresentation fieldTd = fd.FieldType; if(fieldTd.SizeOfHoldingVariable == fragmentTd.SizeOfHoldingVariable) { fragmentTd = fieldTd; } } object valFrag; ulong valInt; if(exConst.IsValueInteger && exConst.GetAsRawUlong( out valInt )) { CHECKS.ASSERT( exConst.SizeOfValue == sourceFragments * sizeof(uint), "Mismatch between type and value of ConstantExpression: {0} <=> {1}", exConst.Type, exConst.Value ); if(offset == 0) { fragmentTd = m_typeSystem.WellKnownTypes.System_UInt32; valFrag = (uint)valInt; } else { if(exConst.IsValueSigned) { fragmentTd = m_typeSystem.WellKnownTypes.System_Int32; valFrag = (int)(valInt >> 32); } else { fragmentTd = m_typeSystem.WellKnownTypes.System_UInt32; valFrag = (uint)(valInt >> 32); } } } else { valFrag = new ValueFragment( val, offset ); } res[offset] = new ConstantExpression( fragmentTd, valFrag ); } } SetFragmentsForExpression( exConst, res ); } } return res; } internal void SetFragmentsForExpression( Expression ex , Expression[] fragments ) { m_lookupFragments[ex] = fragments; } //--// // // Access Methods // public bool IsMappedToMachine { get { return HasProperty( MappedToMachine ); } } //--// // // Debug Methods // } } ================================================ FILE: Zelig/Zelig/CompileTime/CodeGenerator/CodeTransformation/ControlFlowGraphState/ControlFlowGraphStateForCodeTransformation_PostDominance.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // namespace Microsoft.Zelig.CodeGeneration.IR { using System; using System.Collections.Generic; using Microsoft.Zelig.Runtime.TypeSystem; public partial class ControlFlowGraphStateForCodeTransformation { class CacheInfo_PostDominance : CachedInfo { // // State // internal DataFlow.ControlTree.PostDominance m_postDominance; // // Helper Methods // protected override void Update() { ControlFlowGraphStateForCodeTransformation cfg = (ControlFlowGraphStateForCodeTransformation)m_owner; using(new PerformanceCounters.ContextualTiming( cfg, "PostDominance" )) { m_postDominance = new DataFlow.ControlTree.PostDominance( cfg ); } } } // // Helper Methods // public IDisposable LockPostDominance() { var ci = GetCachedInfo< CacheInfo_PostDominance >(); ci.Lock(); return ci; } // // Access Methods // [System.Diagnostics.DebuggerBrowsable( System.Diagnostics.DebuggerBrowsableState.Never )] public BitVector[] DataFlow_PostDominance { get { var ci = GetCachedInfo< CacheInfo_PostDominance >(); return ci.m_postDominance.GetPostDominance(); } } [System.Diagnostics.DebuggerBrowsable( System.Diagnostics.DebuggerBrowsableState.Never )] public BasicBlock[] DataFlow_ImmediatePostDominators { get { var ci = GetCachedInfo< CacheInfo_PostDominance >(); return ci.m_postDominance.GetImmediatePostDominators(); } } } } ================================================ FILE: Zelig/Zelig/CompileTime/CodeGenerator/CodeTransformation/ControlFlowGraphState/ControlFlowGraphStateForCodeTransformation_PostOrderVisit.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // namespace Microsoft.Zelig.CodeGeneration.IR { using System; using System.Collections.Generic; using Microsoft.Zelig.Runtime.TypeSystem; public partial class ControlFlowGraphStateForCodeTransformation { class CacheInfo_PostOrderVisit : CachedInfo { // // State // internal BasicBlock[] m_basicBlocks; // // Helper Methods // protected override void Update() { ControlFlowGraphStateForCodeTransformation cfg = (ControlFlowGraphStateForCodeTransformation)m_owner; using(new PerformanceCounters.ContextualTiming( cfg, "PostOrderVisit" )) { cfg.UpdateFlowInformation(); DataFlow.ControlTree.PostOrderVisit.Compute( cfg.m_entryBasicBlock, out m_basicBlocks ); } } } // // Helper Methods // public IDisposable LockPostOrderVisit() { var ci = GetCachedInfo< CacheInfo_PostOrderVisit >(); ci.Lock(); return ci; } // // Access Methods // [System.Diagnostics.DebuggerBrowsable( System.Diagnostics.DebuggerBrowsableState.Never )] public BasicBlock[] DataFlow_PostOrderVisit { get { var ci = GetCachedInfo< CacheInfo_PostOrderVisit >(); return ci.m_basicBlocks; } } } } ================================================ FILE: Zelig/Zelig/CompileTime/CodeGenerator/CodeTransformation/ControlFlowGraphState/ControlFlowGraphStateForCodeTransformation_PropertiesOfVariables.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // namespace Microsoft.Zelig.CodeGeneration.IR { using System; using System.Collections.Generic; using Microsoft.Zelig.Runtime.TypeSystem; public partial class ControlFlowGraphStateForCodeTransformation { class CacheInfo_PropertiesOfVariables : CachedInfo { // // State // internal VariableExpression.Property[] m_propertiesOfVariables; // // Helper Methods // protected override void Update() { ControlFlowGraphStateForCodeTransformation cfg = (ControlFlowGraphStateForCodeTransformation)m_owner; using(new PerformanceCounters.ContextualTiming( cfg, "PropertiesOfVariables" )) { Operator [] operators = cfg.DataFlow_SpanningTree_Operators; VariableExpression [] variables = cfg.DataFlow_SpanningTree_Variables; VariableExpression.Property[] properties = new VariableExpression.Property[variables.Length]; foreach(VariableExpression var in variables) { if(var.AliasedVariable is PhysicalRegisterExpression) { properties[var.SpanningTreeIndex] |= VariableExpression.Property.PhysicalRegister; } } foreach(Operator op in operators) { if(op is AddressAssignmentOperator) { ExpandAddressTakenThroughFragments( cfg, variables, properties, op.FirstArgument ); } } m_propertiesOfVariables = properties; } } private static void ExpandAddressTakenThroughFragments( ControlFlowGraphStateForCodeTransformation cfg , VariableExpression[] variables , VariableExpression.Property[] properties , Expression ex ) { if(ex is VariableExpression) { CHECKS.ASSERT( ex.SpanningTreeIndex != -1, "Encountered variable not belonging to the spanning tree: {0}", ex ); if((properties[ex.SpanningTreeIndex] & VariableExpression.Property.AddressTaken) == 0) { properties[ex.SpanningTreeIndex] |= VariableExpression.Property.AddressTaken; // // Expand from fragment to original variable. // Expression[] fragments; if(ex is LowLevelVariableExpression) { LowLevelVariableExpression exLow = (LowLevelVariableExpression)ex; fragments = cfg.GetFragmentsForExpression( exLow.SourceVariable ); } else { fragments = cfg.GetFragmentsForExpression( ex ); } if(fragments != null) { // // Expand to all the fragments. // foreach(Expression var in fragments) { ExpandAddressTakenThroughFragments( cfg, variables, properties, var ); } } } } } } // // Helper Methods // public IDisposable LockPropertiesOfVariables() { var ci = GetCachedInfo< CacheInfo_PropertiesOfVariables >(); ci.Lock(); return ci; } // // Access Methods // [System.Diagnostics.DebuggerBrowsable( System.Diagnostics.DebuggerBrowsableState.Never )] public VariableExpression.Property[] DataFlow_PropertiesOfVariables { get { var ci = GetCachedInfo< CacheInfo_PropertiesOfVariables >(); return ci.m_propertiesOfVariables; } } // // Debug Methods // public override string ToPrettyString( Operator op ) { return PrettyDumper.Dump( op ); } } } ================================================ FILE: Zelig/Zelig/CompileTime/CodeGenerator/CodeTransformation/ControlFlowGraphState/ControlFlowGraphStateForCodeTransformation_ReachingDefinitions.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // namespace Microsoft.Zelig.CodeGeneration.IR { using System; using System.Collections.Generic; using Microsoft.Zelig.Runtime.TypeSystem; public partial class ControlFlowGraphStateForCodeTransformation { class CacheInfo_ReachingDefinitions : CachedInfo { // // State // internal BitVector[] m_reachingDefinitions; // // Helper Methods // protected override void Update() { ControlFlowGraphStateForCodeTransformation cfg = (ControlFlowGraphStateForCodeTransformation)m_owner; using(new PerformanceCounters.ContextualTiming( cfg, "ReachingDefinitions" )) { DataFlow.ReachingDefinitions.Compute( cfg.DataFlow_SpanningTree_BasicBlocks, cfg.DataFlow_SpanningTree_Operators, true, out m_reachingDefinitions ); } } } // // Helper Methods // public IDisposable LockReachingDefinitions() { var ci = GetCachedInfo< CacheInfo_ReachingDefinitions >(); ci.Lock(); return ci; } // // Access Methods // [System.Diagnostics.DebuggerBrowsable( System.Diagnostics.DebuggerBrowsableState.Never )] public BitVector[] DataFlow_ReachingDefinitions { get { var ci = GetCachedInfo< CacheInfo_ReachingDefinitions >(); return ci.m_reachingDefinitions; } } } } ================================================ FILE: Zelig/Zelig/CompileTime/CodeGenerator/CodeTransformation/ControlFlowGraphState/ControlFlowGraphStateForCodeTransformation_SpanningTree.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // namespace Microsoft.Zelig.CodeGeneration.IR { using System; using System.Collections.Generic; using Microsoft.Zelig.Runtime.TypeSystem; public partial class ControlFlowGraphStateForCodeTransformation { class CacheInfo_SpanningTree : CachedInfo { // // State // internal BasicBlock[] m_basicBlocks; internal BasicBlock[] m_ancestors; internal Operator[] m_operators; internal VariableExpression[] m_variables; internal VariableExpression[][] m_variablesByStorage; internal VariableExpression[][] m_variablesByAggregate; // // Helper Methods // protected override void Update() { ControlFlowGraphStateForCodeTransformation cfg = (ControlFlowGraphStateForCodeTransformation)m_owner; using(new PerformanceCounters.ContextualTiming( cfg, "SpanningTree" )) { while(true) { cfg.UpdateFlowInformation(); foreach(BasicBlock bb in cfg.m_basicBlocks) { bb.SpanningTreeIndex = -1; } if(m_variables != null) { foreach(VariableExpression var in m_variables) { var.SpanningTreeIndex = -1; } } //--// m_ancestors = null; m_variablesByStorage = null; m_variablesByAggregate = null; DataFlow.ControlTree.SpanningTree.Compute( cfg, out m_basicBlocks, out m_operators, out m_variables ); #if DEBUG foreach(Operator op in m_operators) { CHECKS.ASSERT( op.BasicBlock.Owner == cfg, "Operator {0} does not belong to {1}", op, cfg.m_md ); } #endif //--// // // If any basic block got removed from the flow graph, it will become unreachable. // Detect that and recompute the flow information. // bool fUpdateFlowInformation = false; foreach(Operator op in m_operators) { PhiOperator phiOp = op as PhiOperator; if(phiOp != null) { fUpdateFlowInformation |= phiOp.AdjustLinkage(); } } foreach(BasicBlock bb in cfg.m_basicBlocks) { if(bb.SpanningTreeIndex == -1) { CHECKS.ASSERT( ArrayUtility.FindReferenceInNotNullArray( m_basicBlocks, bb ) == -1, "{0} belongs in the spanning tree for {1} without an index", bb, cfg ); bb.Delete(); fUpdateFlowInformation = true; } } cfg.m_basicBlocks = m_basicBlocks; if(!fUpdateFlowInformation) break; } } } } // // Constructor Methods // //--// // // Helper Methods // private static VariableExpression[][] BuildStorageTable( VariableExpression[] variables ) { int varNum = variables.Length; VariableExpression[][] variablesByStorage = new VariableExpression[varNum][]; for(int varIdx = 0; varIdx < varNum; varIdx++) { if(variablesByStorage[varIdx] == null) { VariableExpression var = variables[varIdx]; if(var.AliasedVariable is LowLevelVariableExpression) { VariableExpression[] array = VariableExpression.SharedEmptyArray; // // We only need to scan forward. // If we got here, it was because we didn't encounter an equivalent storage before this point. // for(int varIdx2 = varIdx; varIdx2 < varNum; varIdx2++) { VariableExpression var2 = variables[varIdx2]; if(var2 != null && var.IsTheSamePhysicalEntity( var2 )) { array = ArrayUtility.AppendToNotNullArray( array, var2 ); } } // // Propagate the table to all the variables mapped to the same storage. // foreach(VariableExpression var3 in array) { variablesByStorage[var3.SpanningTreeIndex] = array; } } else { variablesByStorage[varIdx] = new VariableExpression[] { var }; } } } return variablesByStorage; } private static VariableExpression[][] BuildAggregationTable( VariableExpression[] variables ) { int varNum = variables.Length; VariableExpression[][] variablesByAggregate = new VariableExpression[varNum][]; for(int varIdx = 0; varIdx < varNum; varIdx++) { if(variablesByAggregate[varIdx] == null) { VariableExpression var = variables[varIdx]; VariableExpression[] array = VariableExpression.SharedEmptyArray; // // We only need to scan forward. // If we got here, it was because we didn't encounter an equivalent storage before this point. // for(int varIdx2 = varIdx; varIdx2 < varNum; varIdx2++) { VariableExpression var2 = variables[varIdx2]; if(var2 != null && var.IsTheSameAggregate( var2 )) { array = ArrayUtility.AppendToNotNullArray( array, var2 ); } } // // Propagate the table to all the variables mapped to the same storage. // foreach(VariableExpression var3 in array) { variablesByAggregate[var3.SpanningTreeIndex] = array; } } } return variablesByAggregate; } //--// public IDisposable LockSpanningTree() { var ci = GetCachedInfo< CacheInfo_SpanningTree >(); ci.Lock(); return ci; } //--// public OperatorEnumeratorProvider< T > FilterOperators< T >() where T : Operator { return new OperatorEnumeratorProvider< T >( this.DataFlow_SpanningTree_Operators ); } public struct OperatorEnumeratorProvider< T > where T : Operator { // // State // private readonly Operator[] m_values; // // Constructor Methods // internal OperatorEnumeratorProvider( Operator[] values ) { m_values = values; } // // Helper Methods // public OperatorEnumerator< T > GetEnumerator() { return new OperatorEnumerator< T >( m_values ); } } public struct OperatorEnumerator< T > where T : Operator { // // State // private readonly Operator[] m_values; private T m_current; private int m_index; // // Constructor Methods // internal OperatorEnumerator( Operator[] values ) { m_values = values; m_current = null; m_index = 0; } // // Helper Methods // public void Dispose() { } public bool MoveNext() { while(m_index < m_values.Length) { T res = m_values[m_index++] as T; if(res != null) { if(res.BasicBlock != null) // Skip deleted operators. { m_current = res; return true; } } } m_current = null; return false; } public T Current { get { return m_current; } } } // // Access Methods // [System.Diagnostics.DebuggerBrowsable( System.Diagnostics.DebuggerBrowsableState.Never )] public BasicBlock[] DataFlow_SpanningTree_BasicBlocks { get { var ci = GetCachedInfo< CacheInfo_SpanningTree >(); return ci.m_basicBlocks; } } [System.Diagnostics.DebuggerBrowsable( System.Diagnostics.DebuggerBrowsableState.Never )] public BasicBlock[] DataFlow_SpanningTree_Ancestors { get { var ci = GetCachedInfo< CacheInfo_SpanningTree >(); if(ci.m_ancestors == null) { ci.m_ancestors = DataFlow.ControlTree.SpanningTree.ComputeAncestors( ci.m_basicBlocks ); } return ci.m_ancestors; } } [System.Diagnostics.DebuggerBrowsable( System.Diagnostics.DebuggerBrowsableState.Never )] public Operator[] DataFlow_SpanningTree_Operators { get { var ci = GetCachedInfo< CacheInfo_SpanningTree >(); return ci.m_operators; } } [System.Diagnostics.DebuggerBrowsable( System.Diagnostics.DebuggerBrowsableState.Never )] public VariableExpression[] DataFlow_SpanningTree_Variables { get { var ci = GetCachedInfo< CacheInfo_SpanningTree >(); return ci.m_variables; } } [System.Diagnostics.DebuggerBrowsable( System.Diagnostics.DebuggerBrowsableState.Never )] public VariableExpression[][] DataFlow_SpanningTree_VariablesByStorage // It's indexed as VariableExpression[][] { get { var ci = GetCachedInfo< CacheInfo_SpanningTree >(); if(ci.m_variablesByStorage == null) { ci.m_variablesByStorage = BuildStorageTable( ci.m_variables ); } return ci.m_variablesByStorage; } } [System.Diagnostics.DebuggerBrowsable( System.Diagnostics.DebuggerBrowsableState.Never )] public VariableExpression[][] DataFlow_SpanningTree_VariablesByAggregate // It's indexed as VariableExpression[][] { get { var ci = GetCachedInfo< CacheInfo_SpanningTree >(); if(ci.m_variablesByAggregate == null) { ci.m_variablesByAggregate = BuildAggregationTable( ci.m_variables ); } return ci.m_variablesByAggregate; } } } } ================================================ FILE: Zelig/Zelig/CompileTime/CodeGenerator/CodeTransformation/ControlFlowGraphState/ControlFlowGraphStateForCodeTransformation_Trace.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // //#define TRACE_EVERY_IR_CHANGE //#define TRACE_EVERY_SINGLE_IR_CHANGE namespace Microsoft.Zelig.CodeGeneration.IR { using System; using System.Collections.Generic; using Microsoft.Zelig.Runtime.TypeSystem; public partial class ControlFlowGraphStateForCodeTransformation : ControlFlowGraphState { // // Debug Methods // public void Dump() { using(var ird = new IR.TextIntermediateRepresentationDumper()) { ird.WriteLine( "#################################################################################" ); ird.WriteLine( "#################################################################################" ); ird.WriteLine( "#################################################################################" ); this.Dump( ird ); } } public void DumpToFile( string file ) { using(var ird = new IR.TextIntermediateRepresentationDumper( file )) { ird.WriteLine( "Method: {0}", this.m_md ); ird.WriteLine( ); this.Dump( ird ); } } public void DumpToStream( System.IO.StreamWriter output ) { using(var ird = new IR.TextIntermediateRepresentationDumper( output )) { ird.WriteLine( "Method: {0}", this.m_md ); ird.WriteLine( ); this.Dump( ird ); ird.WriteLine(); } } #if TRACE_EVERY_IR_CHANGE static int s_count; static int s_dumpCount; static int s_lastCount; static string s_lastNote = "InitialState"; static byte[] s_lastDump; static string s_directory; static string s_phase = "InitialPhase"; static int s_phase_count; internal static void SetPhaseForTrace( CompilationSteps.PhaseDriver driver ) { s_phase = string.Format( "{0:X4}_{1}", ++s_phase_count, driver.GetType().Name ); } internal void TraceToFile( Delegate dlg ) { TraceToFile( dlg.Method.Name ); } internal void TraceToFile( string note ) { const string constText = //// "FlowGraph(int[] Microsoft.NohauLPC3180Loader.Loader::TestArrayBoundChecks(int[],int,int))"; //// "FlowGraph(void Microsoft.Zelig.Runtime.MemorySegment::Initialize())"; //// "FlowGraph(void System.Array::Copy(System.Array,System.Array,int))"; //// "FlowGraph(void Microsoft.Zelig.Runtime.MarkAndSweepCollector::InitializeGarbageCollectionManager())"; //// "FlowGraph(int Microsoft.Zelig.Runtime.Helpers.BinaryOperations::IntDiv(int,int))"; //// "FlowGraph(int[] Microsoft.NohauLPC3180Loader.Loader::TestArrayBoundChecks(int[],int,int))"; //// "FlowGraph(uint Microsoft.NohauLPC3180Loader.Loader::Sqrt(uint))"; //// "FlowGraph(void System.Collections.Generic.ArraySortHelper`1::QuickSort(int[],object[],int,int,System.Collections.Generic.IComparer`1))"; //// "FlowGraph(void mscorlib_UnitTest.Program::TestBitField())"; //// "FlowGraph(void mscorlib_UnitTest.Program::Main())"; //// "FlowGraph(string System.Number::ToStringFormat(string,System.Globalization.NumberFormatInfo))"; //// "FlowGraph(void Microsoft.Zelig.Runtime.ThreadManager::AddThread(System.Threading.Thread))"; //// "FlowGraph(bool Microsoft.Zelig.Runtime.TargetPlatform.ARMv4.ProcessorARMv4.Context::Unwind())"; "FlowGraph(void Microsoft.Zelig.Runtime.Bootstrap::EntryPoint())"; if(this.ToString() != constText) { return; } s_count++; //// if(s_count >= 0x1C1) //// { //// } var memStream = new System.IO.MemoryStream(); var writer = new System.IO.StreamWriter( memStream ); using(var ird = new TextIntermediateRepresentationDumper( writer )) { ird.DumpGraph( this ); } writer.Flush(); byte[] dump = memStream.ToArray(); #if !TRACE_EVERY_SINGLE_IR_CHANGE if(ArrayUtility.ByteArrayEquals( dump, s_lastDump ) == false) #endif { string filePrefix = Environment.ExpandEnvironmentVariables( @"%DEPOTROOT%\ZeligUnitTestResults\Trace" ); if(s_directory == null) { s_directory = string.Format( "{0}_{1:yyyy-MM-dd--HH-mm-ss}", filePrefix, DateTime.Now ); } #if TRACE_EVERY_SINGLE_IR_CHANGE string file = string.Format( @"{0}\{1}\{2:X4}__{3:X4}_{4}", s_directory, s_phase, s_dumpCount++, s_count, note ); #else string file = string.Format( @"{0}\{1}\{2:X4}__{3:X4}_{4}", s_directory, s_phase, s_dumpCount++, s_lastCount, s_lastNote ); #endif file = file.Replace( ' ', '_' ); file = file.Replace( '<', '_' ); file = file.Replace( '>', '_' ); //// if(note.StartsWith( "ConvertInto-" )) //// { //// TraceAsXml( file ); //// //// TraceAsIR( file ); //// } System.IO.Directory.CreateDirectory( System.IO.Path.GetDirectoryName( file ) ); using(System.IO.FileStream fileStream = new System.IO.FileStream( file + ".txt", System.IO.FileMode.Create, System.IO.FileAccess.Write ) ) { fileStream.Write( dump, 0, dump.Length ); } s_lastDump = dump; } s_lastCount = s_count; s_lastNote = note; } private void TraceAsXml( string file ) { var doc = new System.Xml.XmlDocument(); var node = XmlHelper.AddElement( doc, "Methods" ); var ird = new IR.XmlIntermediateRepresentationDumper( doc, node ); this.Dump( ird ); doc.Save( file + ".xml" ); } private void TraceAsIR( string file ) { using(var stream = new System.IO.FileStream( file + ".ZeligImage", System.IO.FileMode.Create )) { IR.TypeSystemSerializer.Serialize( stream, this.TypeSystem ); } } #else internal static void SetPhaseForTrace( CompilationSteps.PhaseDriver driver ) { } internal void TraceToFile( Delegate dlg ) { } internal void TraceToFile( string note ) { } #endif } } ================================================ FILE: Zelig/Zelig/CompileTime/CodeGenerator/CodeTransformation/ControlFlowGraphState/ControlFlowGraphStateForCodeTransformation_UseDefinitionChains.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // namespace Microsoft.Zelig.CodeGeneration.IR { using System; using System.Collections.Generic; using Microsoft.Zelig.Runtime.TypeSystem; public partial class ControlFlowGraphStateForCodeTransformation { class CacheInfo_UseDefinitionChains : CachedInfo { // // State // internal Operator[] m_operators; internal BitVector[] m_uses; internal BitVector[] m_definitions; internal Operator[][] m_usesAsOperatorSet; internal Operator[][] m_definitionsAsOperatorSet; // // Helper Methods // protected override void Update() { ControlFlowGraphStateForCodeTransformation cfg = (ControlFlowGraphStateForCodeTransformation)m_owner; using(new PerformanceCounters.ContextualTiming( cfg, "UseDefinitionChains" )) { VariableExpression[] variables = cfg.DataFlow_SpanningTree_Variables; m_operators = cfg.DataFlow_SpanningTree_Operators; m_usesAsOperatorSet = null; m_definitionsAsOperatorSet = null; m_uses = BitVector.AllocateBitVectors( variables.Length, m_operators.Length ); m_definitions = BitVector.AllocateBitVectors( variables.Length, m_operators.Length ); for(int i = 0; i < m_operators.Length; i++) { Operator op = m_operators[i]; foreach(var an in op.FilterAnnotations< InvalidationAnnotation >()) { m_definitions[an.Target.SpanningTreeIndex].Set( i ); } foreach(var ex in op.Results) { m_definitions[ex.SpanningTreeIndex].Set( i ); } foreach(var ex in op.Arguments) { if(ex is VariableExpression) { m_uses[ex.SpanningTreeIndex].Set( i ); } } } } } } // // Helper Methods // public Operator FindSingleDefinition( Expression ex ) { if(ex is VariableExpression) { Operator[] defChain = this.DataFlow_DefinitionChains[ex.SpanningTreeIndex]; if(defChain.Length == 1) { return defChain[0]; } } return null; } public Operator FindSingleUse( Expression ex ) { if(ex is VariableExpression) { Operator[] useChain = this.DataFlow_UseChains[ex.SpanningTreeIndex]; if(useChain.Length == 1) { return useChain[0]; } } return null; } public static Operator FindOrigin( Expression ex , Operator[][] defChains , BitVector visited ) { visited.ClearAll(); while(true) { var res = ex as VariableExpression; if(res != null) { Operator singleDef = CheckSingleDefinition( defChains, res ); if(singleDef != null) { if(singleDef is AbstractAssignmentOperator && singleDef.Arguments.Length == 1) { if(visited.Set( singleDef.SpanningTreeIndex ) == false) { // // Detected loop. // return null; } ex = singleDef.FirstArgument; continue; } return singleDef; } } return null; } } //--// private static Operator[][] CreateFinalArrays( BitVector[] bits , Operator[] operators ) { int len = bits.Length; Operator[][] res = new Operator[len][]; for(int i = 0; i < len; i++) { int num = bits[i].Cardinality; if(num == 0) { res[i] = Operator.SharedEmptyArray; } else { Operator[] res2 = new Operator[num]; res[i] = res2; int j = 0; foreach(int pos in bits[i]) { res2[j++] = operators[pos]; } } } return res; } //--// public IDisposable LockUseDefinitionChains() { var ci = GetCachedInfo< CacheInfo_UseDefinitionChains >(); ci.Lock(); return ci; } // // Access Methods // [System.Diagnostics.DebuggerBrowsable( System.Diagnostics.DebuggerBrowsableState.Never )] public BitVector[] DataFlow_BitVectorsForUseChains // It's indexed as Operator[][] { get { var ci = GetCachedInfo< CacheInfo_UseDefinitionChains >(); return ci.m_uses; } } [System.Diagnostics.DebuggerBrowsable( System.Diagnostics.DebuggerBrowsableState.Never )] public BitVector[] DataFlow_BitVectorsForDefinitionChains // It's indexed as Operator[][] { get { var ci = GetCachedInfo< CacheInfo_UseDefinitionChains >(); return ci.m_definitions; } } [System.Diagnostics.DebuggerBrowsable( System.Diagnostics.DebuggerBrowsableState.Never )] public Operator[][] DataFlow_UseChains // It's indexed as Operator[][] { get { var ci = GetCachedInfo< CacheInfo_UseDefinitionChains >(); if(ci.m_usesAsOperatorSet == null) { ci.m_usesAsOperatorSet = CreateFinalArrays( ci.m_uses, ci.m_operators ); } return ci.m_usesAsOperatorSet; } } [System.Diagnostics.DebuggerBrowsable( System.Diagnostics.DebuggerBrowsableState.Never )] public Operator[][] DataFlow_DefinitionChains // It's indexed as Operator[][] { get { var ci = GetCachedInfo< CacheInfo_UseDefinitionChains >(); if(ci.m_definitionsAsOperatorSet == null) { ci.m_definitionsAsOperatorSet = CreateFinalArrays( ci.m_definitions, ci.m_operators ); } return ci.m_definitionsAsOperatorSet; } } //--// [System.Diagnostics.DebuggerBrowsable( System.Diagnostics.DebuggerBrowsableState.Never )] public GrowOnlyHashTable< VariableExpression, Operator[] > DataFlow_UseChainsLookup { get { GrowOnlyHashTable< VariableExpression, Operator[] > useChainsLookup = HashTableFactory.NewWithReferenceEquality< VariableExpression, Operator[] >(); Operator[][] useChains = this.DataFlow_UseChains; foreach(VariableExpression var in this.DataFlow_SpanningTree_Variables) { useChainsLookup[var] = useChains[var.SpanningTreeIndex]; } return useChainsLookup; } } [System.Diagnostics.DebuggerBrowsable( System.Diagnostics.DebuggerBrowsableState.Never )] public GrowOnlyHashTable< VariableExpression, Operator > DataFlow_SingleDefinitionLookup { get { GrowOnlyHashTable< VariableExpression, Operator > defLookup = HashTableFactory.NewWithReferenceEquality< VariableExpression, Operator >(); Operator[][] defChains = this.DataFlow_DefinitionChains; foreach(VariableExpression var in this.DataFlow_SpanningTree_Variables) { Operator[] defs = defChains[var.SpanningTreeIndex]; if(defs.Length == 1) { defLookup[var] = defs[0]; } } return defLookup; } } } } ================================================ FILE: Zelig/Zelig/CompileTime/CodeGenerator/CodeTransformation/DataFlow/ControlTree/Dominance.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // namespace Microsoft.Zelig.CodeGeneration.IR.DataFlow.ControlTree { using System; using System.Collections.Generic; public class Dominance { // // State // BasicBlock[] m_basicBlocksSpanningTree; BasicBlock[] m_basicBlocksPostOrder; int[] m_spanningTreeToPostOrder; BasicBlock[] m_immediateDominanceSpanningTree; BasicBlock[] m_immediateDominancePostOrder; // // Constructor Methods // public Dominance( ControlFlowGraphStateForCodeTransformation cfg ) { m_basicBlocksSpanningTree = cfg.DataFlow_SpanningTree_BasicBlocks; m_basicBlocksPostOrder = cfg.DataFlow_PostOrderVisit; CHECKS.ASSERT( m_basicBlocksSpanningTree.Length == m_basicBlocksPostOrder.Length, "Mismatch between size of SpanningTree and size of PostOrderVisit for {0}", cfg ); int num = m_basicBlocksPostOrder.Length; m_spanningTreeToPostOrder = new int[num]; for(int pos = 0; pos < num; pos++) { BasicBlock bb = m_basicBlocksPostOrder[pos]; m_spanningTreeToPostOrder[bb.SpanningTreeIndex] = pos; } } // // Helper Methods // private void ComputeDominators() { // // This is an implementation of the algorithm in "A Simple, Fast Dominance Algorithm", by Keith D. Cooper, Timothy J. Harvey, and Ken Kennedy. // // "for all nodes, b /* initialize the dominators array */ // doms[b] = Undefined // doms[start_node] = start_node // Changed = true // while (Changed) // Changed = false // for all nodes, b, in reverse postorder (except start node) // new_idom = first (processed) predecessor of b /* (pick one) */ // for all other predecessors, p, of b // if doms[p] != Undefined /* i.e., if doms[p] already calculated */ // new_idom = intersect(p, new_idom) // if doms[b] != new_idom // doms[b] = new_idom // Changed = true // // function intersect(b1, b2) returns node // finger1 = b1 // finger2 = b2 // while (finger1 != finger2) // while (finger1 < finger2) // finger1 = doms[finger1] // while (finger2 < finger1) // finger2 = doms[finger2] // return finger1" // int num = m_basicBlocksPostOrder.Length; m_immediateDominancePostOrder = new BasicBlock[num]; BasicBlock startNode = m_basicBlocksSpanningTree[0]; SetIDom( startNode, startNode ); while(true) { bool fChanged = false; for(int pos = num - 1; --pos >= 0;) { BasicBlock nodeB = m_basicBlocksPostOrder[pos]; CHECKS.ASSERT( !(nodeB is EntryBasicBlock) , "Start node should not be processed by ImmediateDominance algorithm" ); CHECKS.ASSERT( nodeB.Predecessors.Length > 0, "Node 'b' should have a predecessor: {0}", nodeB ); BasicBlock first = null; foreach(BasicBlockEdge edge in nodeB.Predecessors) { BasicBlock bb = edge.Predecessor; if(GetIDom( bb ) != null) { first = bb; break; } } CHECKS.ASSERT( first != null, "Cannot find first (processed) predecessor of 'b'" ); BasicBlock new_idom = first; foreach(BasicBlockEdge edge in nodeB.Predecessors) { BasicBlock nodeP = edge.Predecessor; if(nodeP != first) { if(GetIDom( nodeP ) != null) { new_idom = Intersect( nodeP, new_idom ); } } } if(GetIDom( nodeB ) != new_idom) { SetIDom( nodeB, new_idom ); fChanged = true; } } if(!fChanged) break; } //--// // // Finally, convert to an array in spanning-tree order. // m_immediateDominanceSpanningTree = new BasicBlock[num]; for(int pos = 0; pos < num; pos++) { m_immediateDominanceSpanningTree[pos] = GetIDom( m_basicBlocksSpanningTree[pos] ); } } private BasicBlock Intersect( BasicBlock b1 , BasicBlock b2 ) { int finger1 = GetPostOrderIndex( b1 ); int finger2 = GetPostOrderIndex( b2 ); while(finger1 != finger2) { while(finger1 < finger2) { b1 = m_immediateDominancePostOrder[ finger1 ]; finger1 = GetPostOrderIndex( b1 ); } while(finger2 < finger1) { b2 = m_immediateDominancePostOrder[ finger2 ]; finger2 = GetPostOrderIndex( b2 ); } } return b1; } //--// private int GetPostOrderIndex( BasicBlock bb ) { return m_spanningTreeToPostOrder[ bb.SpanningTreeIndex ]; } private void SetIDom( BasicBlock bb , BasicBlock bb2 ) { m_immediateDominancePostOrder[ GetPostOrderIndex( bb ) ] = bb2; } private BasicBlock GetIDom( BasicBlock bb ) { return m_immediateDominancePostOrder[ GetPostOrderIndex( bb ) ]; } // // Access Methods // public BasicBlock[] GetImmediateDominators() { if(m_immediateDominanceSpanningTree == null) { ComputeDominators(); } return m_immediateDominanceSpanningTree; } public BitVector[] GetDominance() { BasicBlock[] idom = GetImmediateDominators(); int num = idom.Length; BitVector[] res = BitVector.AllocateBitVectors( num, num ); for(int pos = 0; pos < num; pos++) { BasicBlock bb = m_basicBlocksSpanningTree[pos]; BitVector vec = res[pos]; while(true) { int idx = bb.SpanningTreeIndex; vec.Set( idx ); BasicBlock next = idom[idx]; if(next == bb) { break; } bb = next; } } return res; } public BitVector[] GetDominanceFrontier() { // // This is an implementation of the algorithm in "A Simple, Fast Dominance Algorithm", by Keith D. Cooper, Timothy J. Harvey, and Ken Kennedy. // // "for all nodes, b // if the number of predecessors of b >= 2 // for all predecessors, p, of b // runner = p // while runner != doms[b] // add b to runners dominance frontier set // runner = doms[runner]" // BasicBlock[] idom = GetImmediateDominators(); int num = idom.Length; BitVector[] res = BitVector.AllocateBitVectors( num, num ); for(int nodeBidx = 0; nodeBidx < num; nodeBidx++) { BasicBlock nodeB = m_basicBlocksSpanningTree[nodeBidx]; if(nodeB.Predecessors.Length >= 2) { foreach(BasicBlockEdge edge in nodeB.Predecessors) { BasicBlock nodeP = edge.Predecessor; BasicBlock runner = nodeP; while(runner != idom[nodeBidx]) { int idx = runner.SpanningTreeIndex; res[idx].Set( nodeBidx ); runner = idom[idx]; } } } } return res; } } } ================================================ FILE: Zelig/Zelig/CompileTime/CodeGenerator/CodeTransformation/DataFlow/ControlTree/GenericDepthFirst.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // namespace Microsoft.Zelig.CodeGeneration.IR.DataFlow.ControlTree { using System; public abstract class GenericDepthFirst { // // State // GrowOnlySet< BasicBlock > m_visited; // // Constructor Methods // protected GenericDepthFirst() { m_visited = SetFactory.NewWithReferenceEquality< BasicBlock >(); } protected void Visit( BasicBlock bb ) { ProcessBefore( bb ); m_visited.Insert( bb ); for(int pass = 0; pass < 2; pass++) { foreach(BasicBlockEdge edge in bb.Successors) { BasicBlock bbSucc = edge.Successor; // // On the first pass, follow only non-dead branches. // // Dead branches are almost always exception-throwing branches, // following them after the other branches ensures that they don't show up in TreeEdges. // if((pass == 0) == (bbSucc.FlowControl is DeadControlOperator)) { continue; } if(m_visited.Contains( bbSucc ) == false) { ProcessEdgeBefore( edge ); Visit( bbSucc ); ProcessEdgeAfter( edge ); } else { ProcessEdgeNotTaken( edge ); } } } ProcessAfter( bb ); } //--// protected virtual void ProcessBefore( BasicBlock bb ) { } protected virtual void ProcessAfter( BasicBlock bb ) { } //--// protected virtual void ProcessEdgeBefore( BasicBlockEdge edge ) { } protected virtual void ProcessEdgeAfter( BasicBlockEdge edge ) { } protected virtual void ProcessEdgeNotTaken( BasicBlockEdge edge ) { } } } ================================================ FILE: Zelig/Zelig/CompileTime/CodeGenerator/CodeTransformation/DataFlow/ControlTree/NaturalLoops.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // namespace Microsoft.Zelig.CodeGeneration.IR.DataFlow.ControlTree { using System; using System.Collections.Generic; public class NaturalLoops : IDisposable { public class Entry { public static Entry[] SharedEmptyArray = new Entry[0]; // // State // internal int m_depth; internal int m_headIdx; internal BitVector m_basicBlocks; internal BitVector m_exitPoints; // // Constructor Methods // internal Entry( BasicBlock bbHead , BasicBlock bb , int bbNum ) { m_headIdx = bbHead.SpanningTreeIndex; m_basicBlocks = new BitVector( bbNum ); m_exitPoints = new BitVector( bbNum ); m_basicBlocks.Set( bb.SpanningTreeIndex ); ExpandInner( bbHead, bb ); } // // Helper Methods // private void ExpandInner( BasicBlock bbHead , BasicBlock bb ) { if(bbHead != bb) { foreach(BasicBlockEdge edge in bb.Predecessors) { BasicBlock bbPred = edge.Predecessor; int bbPredIdx = bbPred.SpanningTreeIndex; if(m_basicBlocks.Set( bbPredIdx )) { ExpandInner( bbHead, bbPred ); } } } } // // Access Methods // public int Depth { get { return m_depth; } } public int IndexOfHead { get { return m_headIdx; } } public BitVector BasicBlocks { get { return m_basicBlocks; } } public BitVector ExitPoints { get { return m_exitPoints; } } } // // State // private readonly IDisposable m_cfgLock; private readonly BasicBlock[] m_basicBlocks; private readonly BitVector[] m_dominance; private List< Entry > m_loops; private Entry[][] m_loopsLookup; // // Constructor Methods // private NaturalLoops( ControlFlowGraphStateForCodeTransformation cfg ) { m_cfgLock = cfg.GroupLock( cfg.LockSpanningTree() , cfg.LockDominance () ); m_basicBlocks = cfg.DataFlow_SpanningTree_BasicBlocks; m_dominance = cfg.DataFlow_Dominance; } // // Helper Methods // public static NaturalLoops Execute( ControlFlowGraphStateForCodeTransformation cfg ) { NaturalLoops nl = new NaturalLoops( cfg ); nl.Compute(); return nl; } public void Dispose() { m_cfgLock.Dispose(); } private void Compute() { int bbNum = m_basicBlocks.Length; m_loops = new List< Entry >( bbNum ); m_loopsLookup = new Entry[bbNum][]; for(int i = 0; i < bbNum; i++) { m_loopsLookup[i] = Entry.SharedEmptyArray; } foreach(BasicBlock bb in m_basicBlocks) { int bbIdx = bb.SpanningTreeIndex; foreach(BasicBlockEdge edge in bb.Successors) { BasicBlock bbHead = edge.Successor; int bbHeadIdx = bbHead.SpanningTreeIndex; if(m_dominance[bbIdx][bbHeadIdx]) { // // Found a back edge bb->bbHead. // bool fNew = true; foreach(var loop in m_loopsLookup[bbHeadIdx]) { if(loop.m_headIdx == bbHeadIdx && loop.m_basicBlocks[bbIdx]) { fNew = false; break; } } if(fNew) { Entry loopNew = new Entry( bbHead, bb, bbNum ); foreach(Entry loop in m_loops) { if(loop.m_basicBlocks == loopNew.m_basicBlocks) { loopNew = null; break; } } if(loopNew != null) { m_loops.Add( loopNew ); foreach(int idx in loopNew.m_basicBlocks) { m_loopsLookup[idx] = ArrayUtility.AppendToNotNullArray( m_loopsLookup[idx], loopNew ); } } } } } } foreach(var loop in m_loops) { loop.m_depth = m_loopsLookup[loop.m_headIdx].Length; foreach(var idx in loop.m_basicBlocks) { foreach(var bbEdge in m_basicBlocks[idx].Successors) { var bbNext = bbEdge.Successor; if(bbNext is ExceptionHandlerBasicBlock) { // Skip these blocks, they are not normal edges. } else { if(loop.m_basicBlocks[bbNext.SpanningTreeIndex] == false) { // // The successor is not part of the same loop, this is the definition of an exit point. // loop.m_exitPoints.Set( idx ); } } } } } } //--// public int GetDepthOfBasicBlock( BasicBlock bb ) { int depth = 0; foreach(var en in m_loopsLookup[bb.SpanningTreeIndex]) { depth = Math.Max( depth, en.Depth ); } return depth; } // // Access Methods // public List< Entry > Loops { get { return m_loops; } } public Entry[][] LoopsLookup { get { return m_loopsLookup; } } } } ================================================ FILE: Zelig/Zelig/CompileTime/CodeGenerator/CodeTransformation/DataFlow/ControlTree/PostDominance.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // namespace Microsoft.Zelig.CodeGeneration.IR.DataFlow.ControlTree { using System; using System.Collections.Generic; // // TODO: There's a problem with this algorithm and exceptions. // // Basically, every exception handler that does not return execution to the method is an exit block. // So they must be treated as if they are actual exit blocks. // public class PostDominance { // // State // BasicBlock[] m_basicBlocks; BitVector[] m_postDominance; BasicBlock[] m_immediatePostDominators; // // Constructor Methods // public PostDominance( ControlFlowGraphStateForCodeTransformation cfg ) { m_basicBlocks = cfg.DataFlow_SpanningTree_BasicBlocks; } // // Helper Methods // private void ComputePostDominators() { int len = m_basicBlocks.Length; BitVector t = new BitVector( len ); m_postDominance = new BitVector[len]; for(int i = 0; i < len; i++) { BitVector bv = new BitVector( len ); if(m_basicBlocks[i].Successors.Length == 0) { // // A basic block with no successors is postdominated just by itself. // bv.Set( i ); } else { bv.SetRange( 0, len ); } m_postDominance[i] = bv; } while(true) { bool fChange = false; for(int i = 0; i < len; i++) { BasicBlockEdge[] edges = m_basicBlocks[i].Successors; if(edges.Length != 0) { t.SetRange( 0, len ); foreach(BasicBlockEdge edge in edges) { t.AndInPlace( m_postDominance[edge.Successor.SpanningTreeIndex] ); } t.Set( i ); if(t != m_postDominance[i]) { fChange = true; m_postDominance[i].Assign( t ); } } } if(!fChange) break; } } private void ComputeImmediatePostDominators() { int len = m_basicBlocks.Length; BitVector[] tmp = BitVector.AllocateBitVectors( len, len ); for(int n = 0; n < len; n++) { // Tmp(n) := PostDomin(n) - {n} tmp[n].Assign( m_postDominance[n] ); tmp[n].Clear ( n ); } for(int n = 0; n < len; n++) // Walk the basic blocks in pre-order. { // for each n in N do BitVector tmpN = tmp[n]; for(int s = 0; s < len; s++) { if(tmpN[s]) { // for each s in Tmp(n) do BitVector tmpS = tmp[s]; for(int t = 0; t < len; t++) { if(t != s && tmpN[t]) { // for each t in Tmp(n) - {s} do if(tmpS[t]) { // if t in Tmp(s) then Tmp(n) -= {t} tmpN.Clear( t ); } } } } } } m_immediatePostDominators = new BasicBlock[len]; for(int n = 0; n < len; n++) { bool fGot = false; foreach(int idom in tmp[n]) { CHECKS.ASSERT( fGot == false, "Internal failure, found more than one immediate post dominators" ); m_immediatePostDominators[n] = m_basicBlocks[idom]; fGot = true; } } } // // Access Methods // public BitVector[] GetPostDominance() { if(m_postDominance == null) { ComputePostDominators(); } return m_postDominance; } public BasicBlock[] GetImmediatePostDominators() { if(m_immediatePostDominators == null) { ComputeImmediatePostDominators(); } return m_immediatePostDominators; } } } ================================================ FILE: Zelig/Zelig/CompileTime/CodeGenerator/CodeTransformation/DataFlow/ControlTree/PostOrderVisit.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // namespace Microsoft.Zelig.CodeGeneration.IR.DataFlow.ControlTree { using System; using System.Collections.Generic; public class PostOrderVisit : GenericDepthFirst { // // State // List< BasicBlock > m_basicBlocks; // // Constructor Methods // private PostOrderVisit() { m_basicBlocks = new List< BasicBlock >(); } public static void Compute( EntryBasicBlock entry , out BasicBlock[] basicBlocks ) { PostOrderVisit tree = new PostOrderVisit(); tree.Visit( entry ); basicBlocks = tree.m_basicBlocks.ToArray(); } //--// protected override void ProcessAfter( BasicBlock bb ) { m_basicBlocks.Add( bb ); } } } ================================================ FILE: Zelig/Zelig/CompileTime/CodeGenerator/CodeTransformation/DataFlow/ControlTree/SpanningTree.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // namespace Microsoft.Zelig.CodeGeneration.IR.DataFlow.ControlTree { using System; using System.Collections.Generic; public class SpanningTree : GenericDepthFirst { // // State // ControlFlowGraphStateForCodeTransformation m_cfg; List< BasicBlock > m_basicBlocks; List< Operator > m_operators; List< VariableExpression > m_variables; // // Constructor Methods // private SpanningTree( ControlFlowGraphStateForCodeTransformation cfg ) { m_cfg = cfg; m_basicBlocks = new List< BasicBlock >(); m_operators = new List< Operator >(); m_variables = new List< VariableExpression >(); Visit( cfg.EntryBasicBlock ); } public static void Compute( ControlFlowGraphStateForCodeTransformation cfg , out BasicBlock[] basicBlocks , out Operator[] operators , out VariableExpression[] variables ) { SpanningTree tree = new SpanningTree( cfg ); basicBlocks = tree.m_basicBlocks.ToArray(); operators = tree.m_operators .ToArray(); variables = tree.m_variables .ToArray(); } //--// public static BasicBlock[] ComputeAncestors( BasicBlock[] basicBlocks ) { int bbCount = basicBlocks.Length; BasicBlock[] ancestors = new BasicBlock[bbCount]; for(int i = 0; i < bbCount; i++) { BasicBlock bb = basicBlocks[i]; foreach(BasicBlockEdge edge in bb.Predecessors) { if(edge.EdgeClass == BasicBlockEdgeClass.TreeEdge) { ancestors[i] = edge.Predecessor; } } } return ancestors; } //--// protected override void ProcessBefore( BasicBlock bb ) { bb.SpanningTreeIndex = m_basicBlocks.Count; m_basicBlocks.Add( bb ); foreach(Operator op in bb.Operators) { op.SpanningTreeIndex = m_operators.Count; m_operators.Add( op ); foreach(var an in op.FilterAnnotations< InvalidationAnnotation >()) { AddExpression( an.Target ); } foreach(var ex in op.Results) { AddExpression( ex ); } foreach(var ex in op.Arguments) { AddExpression( ex ); } } } private void AddExpression( Expression ex ) { if(ex is VariableExpression) { AddVariable( (VariableExpression)ex ); } } private void AddVariable( VariableExpression var ) { if(var.SpanningTreeIndex < 0) { var.SpanningTreeIndex = m_variables.Count; m_variables.Add( var ); // // If this is a fragment, we need to add all the other fragments to the spanning tree. // Expression[] fragments = m_cfg.GetFragmentsForExpression( var ); LowLevelVariableExpression lowVar = var as LowLevelVariableExpression; if(lowVar != null) { VariableExpression sourceVar = lowVar.SourceVariable; if(sourceVar != null) { fragments = m_cfg.GetFragmentsForExpression( sourceVar ); CHECKS.ASSERT( fragments != null, "Found an orphan fragment: {0} not part of {1}", lowVar, sourceVar ); } } if(fragments != null) { foreach(Expression exFragment in fragments) { AddVariable( (VariableExpression)exFragment ); } } // // Also add any aliased variable. // AddVariable( var.AliasedVariable ); } } //--// protected override void ProcessEdgeBefore( BasicBlockEdge edge ) { edge.EdgeClass = BasicBlockEdgeClass.TreeEdge; } protected override void ProcessEdgeNotTaken( BasicBlockEdge edge ) { BasicBlock predecessor = edge.Predecessor; BasicBlock successor = edge.Successor; if(predecessor.SpanningTreeIndex < successor.SpanningTreeIndex) { if(IsAncestor( predecessor, successor )) { edge.EdgeClass = BasicBlockEdgeClass.ForwardEdge; } else { edge.EdgeClass = BasicBlockEdgeClass.CrossEdge; } } else { if(IsAncestor( successor, predecessor )) { edge.EdgeClass = BasicBlockEdgeClass.BackEdge; } else { edge.EdgeClass = BasicBlockEdgeClass.CrossEdge; } } } //--// public static bool IsAncestor( BasicBlock node , BasicBlock child ) { while(child != null) { if(node == child) { return true; } BasicBlock nodeNext = null; foreach(BasicBlockEdge edge in child.Predecessors) { if(edge.EdgeClass == BasicBlockEdgeClass.TreeEdge) { nodeNext = edge.Predecessor; break; } } CHECKS.ASSERT( nodeNext != null || child.Predecessors.Length == 0, "Child not a member of a spanning tree" ); child = nodeNext; } return false; } } } ================================================ FILE: Zelig/Zelig/CompileTime/CodeGenerator/CodeTransformation/DataFlow/LivenessAnalysis.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // namespace Microsoft.Zelig.CodeGeneration.IR.DataFlow { using System; using System.Collections.Generic; using Microsoft.Zelig.Runtime.TypeSystem; // // This class computes, for each program point or basic block, the set of variables that are alive. // public class LivenessAnalysis { // // State // private readonly BasicBlock[] m_basicBlocks; private readonly Operator[] m_operators; private readonly VariableExpression[] m_variables; private readonly VariableExpression[][] m_variablesByStorage; private readonly VariableExpression[][] m_variablesByAggregate; private readonly int m_bbNum; private readonly int m_varNum; private BitVector[] m_state_LVinAtOperator; // Variables live at the beginning of an operator. private readonly BitVector[] m_state_LVin; // Variables live at the beginning of a basic block. private readonly BitVector[] m_state_LVout; // Variables live at the end of a basic block. private readonly BitVector[] m_state_DEF; // Variables defined in a basic block, BEFORE any use. private readonly BitVector[] m_state_USE; // Variables used in a basic block BEFORE any definition. private bool m_foundPhiOperators; private BitVector[] m_variableLivenessMap; // For each variable, the set of operators it's alive for. // // Constructor Methods // private LivenessAnalysis( ControlFlowGraphStateForCodeTransformation cfg , bool fExpandLivenessToAggregates ) { m_basicBlocks = cfg.DataFlow_SpanningTree_BasicBlocks; m_operators = cfg.DataFlow_SpanningTree_Operators; m_variables = cfg.DataFlow_SpanningTree_Variables; m_variablesByStorage = cfg.DataFlow_SpanningTree_VariablesByStorage; m_bbNum = m_basicBlocks.Length; m_varNum = m_variables.Length; m_state_LVin = BitVector.AllocateBitVectors( m_bbNum, m_varNum ); m_state_LVout = BitVector.AllocateBitVectors( m_bbNum, m_varNum ); m_state_DEF = BitVector.AllocateBitVectors( m_bbNum, m_varNum ); m_state_USE = BitVector.AllocateBitVectors( m_bbNum, m_varNum ); if(fExpandLivenessToAggregates) { m_variablesByAggregate = cfg.DataFlow_SpanningTree_VariablesByAggregate; } } public static LivenessAnalysis Compute( ControlFlowGraphStateForCodeTransformation cfg , bool fExpandLivenessToAggregates ) { using(cfg.LockSpanningTree()) { LivenessAnalysis liveness = new LivenessAnalysis( cfg, fExpandLivenessToAggregates ); liveness.Compute(); return liveness; } } //--// private void Compute() { ComputeEquationParameters(); SolveEquations(); } //--// private void ComputeEquationParameters() { for(int i = 0; i < m_bbNum; i++) { BasicBlock bb = m_basicBlocks[i]; BitVector def = m_state_DEF [i]; BitVector use = m_state_USE [i]; Operator[] ops = bb.Operators; for(int pos = ops.Length; --pos >= 0;) { VariableExpression var; Operator op = ops[pos]; foreach(var an in op.FilterAnnotations< PostInvalidationAnnotation >()) { if(m_variablesByAggregate != null) { if(ShouldSkip( an )) { continue; } } int idx = an.Target.SpanningTreeIndex; // // We actually use multiple instances of physical registers and stack locations, each one with a different type. // But whenever we encounter one, we need to toggle all of them. // foreach(VariableExpression var2 in m_variablesByStorage[idx]) { int idx2 = var2.SpanningTreeIndex; use.Clear( idx2 ); def.Set ( idx2 ); } } foreach(var lhs in op.Results) { int idx = lhs.SpanningTreeIndex; // // We actually use multiple instances of physical registers and stack locations, each one with a different type. // But whenever we encounter one, we need to toggle all of them. // foreach(VariableExpression var2 in m_variablesByStorage[idx]) { int idx2 = var2.SpanningTreeIndex; use.Clear( idx2 ); def.Set ( idx2 ); } } if(op is PhiOperator) { // // Do not include the contributions from Phi operators! // Their semantic is different from that of a normal operator, it's flow-sensitive, // the use of an Rvalue is conditional to the path the execution took to reach the point. // // Their contribution will be handled later. // m_foundPhiOperators = true; } else { foreach(Expression ex in op.Arguments) { var = ex as VariableExpression; if(var != null) { int idx = var.SpanningTreeIndex; def.Clear( idx ); use.Set ( idx ); } } if(m_variablesByAggregate != null) { if(op is AddressAssignmentOperator) { var rhs = op.FirstArgument as VariableExpression; if(rhs != null) { foreach(var rhsAggregate in m_variablesByAggregate[rhs.SpanningTreeIndex]) { int idx = rhsAggregate.SpanningTreeIndex; def.Clear( idx ); use.Set ( idx ); } } } } } foreach(var an in op.FilterAnnotations< PreInvalidationAnnotation >()) { if(m_variablesByAggregate != null) { if(ShouldSkip( an )) { continue; } } int idx = an.Target.SpanningTreeIndex; // // We actually use multiple instances of physical registers and stack locations, each one with a different type. // But whenever we encounter one, we need to toggle all of them. // foreach(VariableExpression var2 in m_variablesByStorage[idx]) { int idx2 = var2.SpanningTreeIndex; use.Clear( idx2 ); def.Set ( idx2 ); } } } } } private void SolveEquations() { BitVector tmp = new BitVector( m_varNum ); while(true) { bool fDone = true; if(m_foundPhiOperators) { // // We need to modify LVout to include the contribution of phi variables, which is flow-sensitive. // for(int i = 0; i < m_bbNum; i++) { BasicBlock bb = m_basicBlocks[i]; BitVector LVout = m_state_LVout[i]; foreach(BasicBlockEdge edge in bb.Successors) { foreach(Operator op in edge.Successor.Operators) { PhiOperator opPhi = op as PhiOperator; if(opPhi != null) { Expression[] rhs = opPhi.Arguments; BasicBlock[] origins = opPhi.Origins; for(int pos = 0; pos < rhs.Length; pos++) { if(origins[pos] == bb) { LVout.Set( rhs[pos].SpanningTreeIndex ); } } } } } } } // // LVin = (LVout - DEF) Or USE // for(int i = 0; i < m_bbNum; i++) { tmp.Difference( m_state_LVout[i], m_state_DEF[i] ); tmp.OrInPlace( m_state_USE[i] ); BitVector LVin = m_state_LVin[i]; if(LVin != tmp) { LVin.Assign( tmp ); fDone = false; } } if(fDone) { break; } // // LVout = Or { LVin() } // for(int i = 0; i < m_bbNum; i++) { BitVector b = m_state_LVout[i]; b.ClearAll(); foreach(BasicBlockEdge edge in m_basicBlocks[i].Successors) { b.OrInPlace( m_state_LVin[ edge.Successor.SpanningTreeIndex ] ); } } } } //--// private BitVector[] ConvertToOperatorGranularity() { int numOp = m_operators.Length; BitVector[] res = new BitVector[numOp]; for(int i = 0; i < m_bbNum; i++) { BitVector live = m_state_LVout[i].Clone(); BasicBlock bb = m_basicBlocks[i]; Operator[] ops = bb.Operators; for(int pos = ops.Length; --pos >= 0;) { Operator op = ops[pos]; foreach(var an in op.FilterAnnotations< PostInvalidationAnnotation >()) { if(m_variablesByAggregate != null) { if(ShouldSkip( an )) { continue; } } live.Clear( an.Target.SpanningTreeIndex ); } foreach(var lhs in op.Results) { live.Clear( lhs.SpanningTreeIndex ); } if(op is PhiOperator) { // // It would be an error to mark the inputs of a phi operator as alive. // The semantic of the phi operator is that "only one of the input is valid at each invocation". // We already take care of the contribution of phi operators in the computation of LVout. // } else { foreach(Expression ex in op.Arguments) { var var = ex as VariableExpression; if(var != null) { live.Set( var.SpanningTreeIndex ); } } if(m_variablesByAggregate != null) { if(op is AddressAssignmentOperator) { var rhs = op.FirstArgument as VariableExpression; if(rhs != null) { foreach(var rhsAggregate in m_variablesByAggregate[rhs.SpanningTreeIndex]) { live.Set( rhsAggregate.SpanningTreeIndex ); } } } } } foreach(var an in op.FilterAnnotations< PreInvalidationAnnotation >()) { if(m_variablesByAggregate != null) { if(ShouldSkip( an )) { continue; } } live.Clear( an.Target.SpanningTreeIndex ); } res[op.SpanningTreeIndex] = live.Clone(); } } return res; } private BitVector[] ConvertToVariableGranularity() { int numOp = m_operators.Length; BitVector[] res = BitVector.AllocateBitVectors( m_varNum, numOp ); int[] variableStateOrigin = new int[m_varNum]; for(int i = 0; i < m_bbNum; i++) { BitVector live = m_state_LVout[i].Clone(); BasicBlock bb = m_basicBlocks[i]; Operator[] ops = bb.Operators; int opsNum = ops.Length; int opEntryIdx = ops[0].SpanningTreeIndex; int opEndIdx = opEntryIdx + opsNum; // // For each basic block, we initialize the state of each variable liveness based on the "LVout" values. // // Then, for each change of a variable, we set or clear the whole range since the last update. // This should touch way less bits than computing the liveness at the operator granularity // and then pivoting it to variable granularity. // for(int varIdx = m_varNum; --varIdx >= 0;) { variableStateOrigin[varIdx] = opEndIdx; } for(int pos = opsNum; --pos >= 0;) { Operator op = ops[pos]; int opIdx = op.SpanningTreeIndex; foreach(var an in op.FilterAnnotations< PostInvalidationAnnotation >()) { if(m_variablesByAggregate != null) { if(ShouldSkip( an )) { continue; } } int varIdx = an.Target.SpanningTreeIndex; if(live.Clear( varIdx )) // State change, propagate the previous state up to this point. { int opStartIdx = opIdx + 1; res[varIdx].SetRange( opStartIdx, variableStateOrigin[varIdx] - opStartIdx ); variableStateOrigin[varIdx] = opStartIdx; } } foreach(var lhs in op.Results) { int varIdx = lhs.SpanningTreeIndex; if(live.Clear( varIdx )) // State change, propagate the previous state up to this point. { int opStartIdx = opIdx + 1; res[varIdx].SetRange( opStartIdx, variableStateOrigin[varIdx] - opStartIdx ); variableStateOrigin[varIdx] = opStartIdx; } } if(op is PhiOperator) { // // It would be an error to mark the inputs of a phi operator as alive. // The semantic of the phi operator is that "only one of the input is valid at each invocation". // We already take care of the contribution of phi operators in the computation of LVout. // } else { foreach(Expression ex in op.Arguments) { var var = ex as VariableExpression; if(var != null) { int varIdx = var.SpanningTreeIndex; if(live.Set( varIdx )) // State change, propagate the previous state up to this point. { int opStartIdx = opIdx + 1; // No need to clear the range, it's already cleared. variableStateOrigin[varIdx] = opStartIdx; } } } if(m_variablesByAggregate != null) { if(op is AddressAssignmentOperator) { var rhs = op.FirstArgument as VariableExpression; if(rhs != null) { foreach(var rhsAggregate in m_variablesByAggregate[rhs.SpanningTreeIndex]) { var varIdx = rhsAggregate.SpanningTreeIndex; if(live.Set( varIdx )) // State change, propagate the previous state up to this point. { int opStartIdx = opIdx + 1; // No need to clear the range, it's already cleared. variableStateOrigin[varIdx] = opStartIdx; } } } } } } foreach(var an in op.FilterAnnotations< PreInvalidationAnnotation >()) { if(m_variablesByAggregate != null) { if(ShouldSkip( an )) { continue; } } int varIdx = an.Target.SpanningTreeIndex; if(live.Clear( varIdx )) // State change, propagate the previous state up to this point. { int opStartIdx = opIdx + 1; res[varIdx].SetRange( opStartIdx, variableStateOrigin[varIdx] - opStartIdx ); variableStateOrigin[varIdx] = opStartIdx; } } } // // Finally, if the current state is "live", propagate through the entry of the basic block. // for(int varIdx = m_varNum; --varIdx >= 0;) { if(live[varIdx]) { res[varIdx].SetRange( opEntryIdx, variableStateOrigin[varIdx] - opEntryIdx ); } } } return res; } private static bool ShouldSkip( InvalidationAnnotation an ) { var stackVar = an.Target.AliasedVariable as StackLocationExpression; if(stackVar != null) { switch(stackVar.StackPlacement) { case StackLocationExpression.Placement.In : case StackLocationExpression.Placement.Local: return true; } } return false; } //--// // // Access Methods // public BasicBlock[] BasicBlocks { get { return m_basicBlocks; } } public Operator[] Operators { get { return m_operators; } } public VariableExpression[] Variables { get { return m_variables; } } public BitVector[] LivenessAtBasicBlockEntry // It's indexed as [][] { get { return m_state_LVin; } } public BitVector[] LivenessAtBasicBlockExit // It's indexed as [][] { get { return m_state_LVout; } } public BitVector[] LivenessAtOperator // It's indexed as [][] { get { if(m_state_LVinAtOperator == null) { m_state_LVinAtOperator = ConvertToOperatorGranularity(); } return m_state_LVinAtOperator; } } public BitVector[] VariableLivenessMap // It's indexed as [][] { get { if(m_variableLivenessMap == null) { m_variableLivenessMap = ConvertToVariableGranularity();; } return m_variableLivenessMap; } } } } ================================================ FILE: Zelig/Zelig/CompileTime/CodeGenerator/CodeTransformation/DataFlow/ReachingDefinitions.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // namespace Microsoft.Zelig.CodeGeneration.IR.DataFlow { using System; using System.Collections.Generic; using Microsoft.Zelig.Runtime.TypeSystem; // // WARNING!!! WARNING!!! WARNING!!! WARNING!!! WARNING!!! WARNING!!! WARNING!!! WARNING!!! // WARNING!!! WARNING!!! WARNING!!! WARNING!!! WARNING!!! WARNING!!! WARNING!!! WARNING!!! // // This algorithm is currently broken, due to the removal of UsedBy and DefinedBy properties from the Expression class. // // WARNING!!! WARNING!!! WARNING!!! WARNING!!! WARNING!!! WARNING!!! WARNING!!! WARNING!!! // WARNING!!! WARNING!!! WARNING!!! WARNING!!! WARNING!!! WARNING!!! WARNING!!! WARNING!!! // // // This class computes, for each program point, the set of definitions that reach it. // // Here "definition" means "lvalue assignment". // // There are some type of variable assignment that are not tracked. // For example, when a variable is passed as an out/ref parameter to a method. // it's a possible assignment, but it cannot be tracked, due to chosen representation (one bit per program point). // public class ReachingDefinitions { // // State // BasicBlock[] m_basicBlocks; Operator[] m_definitions; BitVector[] m_state_RCHin; // Definitions reaching the beginning of a basic block. BitVector[] m_state_RCHout; // Definitions reaching the end of a basic block. BitVector[] m_state_PRSV; // Definitions preserved by a basic block. BitVector[] m_state_GEN; // Definitions generated by a basic block. // // Constructor Methods // private ReachingDefinitions( BasicBlock[] basicBlocks , Operator[] definitions ) { m_basicBlocks = basicBlocks; m_definitions = definitions; } public static void Compute( BasicBlock[] basicBlocks , Operator[] definitions , bool fComputeAtOperatorGranularity , out BitVector[] rch ) { ReachingDefinitions reachdef = new ReachingDefinitions( basicBlocks, definitions ); reachdef.Compute(); if(fComputeAtOperatorGranularity) { rch = reachdef.ConvertToOperatorGranularity(); } else { rch = reachdef.m_state_RCHin; } } //--// private void Compute() { int numBB = m_basicBlocks.Length; m_state_RCHin = AllocateBitVectors( numBB ); m_state_RCHout = AllocateBitVectors( numBB ); m_state_PRSV = AllocateBitVectors( numBB ); m_state_GEN = AllocateBitVectors( numBB ); ComputeEquationParameters(); SolveEquations(); } private BitVector[] ConvertToOperatorGranularity() { GrowOnlySet< Operator > setPossibleDefinitions = SetFactory.NewWithReferenceEquality< Operator >(); GrowOnlySet< Operator > setVisited = SetFactory.NewWithReferenceEquality< Operator >(); int numBB = m_basicBlocks.Length; int numOp = m_definitions.Length; BitVector[] res = AllocateBitVectors( numOp ); BitVector prsv = new BitVector( numOp ); BitVector gen = new BitVector( numOp ); for(int i = 0; i < numBB; i++) { BitVector rch = m_state_RCHin[i]; foreach(Operator op in m_basicBlocks[i].Operators) { prsv.SetRange( 0, numOp ); gen .ClearAll(); ComputeStateUpdateForOperator( op, prsv, gen, setPossibleDefinitions, setVisited ); BitVector rchOp = res[ op.SpanningTreeIndex ]; rchOp.Assign( rch ); rch.AndInPlace( prsv ); rch.OrInPlace ( gen ); } } return res; } //--// private BitVector[] AllocateBitVectors( int size ) { return BitVector.AllocateBitVectors( size, m_definitions.Length ); } private void ComputeEquationParameters() { GrowOnlySet< Operator > setPossibleDefinitions = SetFactory.NewWithReferenceEquality< Operator >(); GrowOnlySet< Operator > setVisited = SetFactory.NewWithReferenceEquality< Operator >(); int numBB = m_basicBlocks.Length; int numOp = m_definitions.Length; for(int i = 0; i < numBB; i++) { BitVector prsv = m_state_PRSV[i]; BitVector gen = m_state_GEN [i]; prsv.SetRange( 0, numOp ); gen .ClearAll(); foreach(Operator op in m_basicBlocks[i].Operators) { ComputeStateUpdateForOperator( op, prsv, gen, setPossibleDefinitions, setVisited ); } } } private void ComputeStateUpdateForOperator( Operator op , BitVector prsv , BitVector gen , GrowOnlySet setPossibleDefinitions , GrowOnlySet setVisited ) { // // We should consider all the side effects of an operator. // // For example: // // - indirect load/store can affect a variable. // - method call could affect all fields, arrays. // - out/ref parameters could affect all fields, arrays, local variables, arguments, etc. // if(op.MayWriteThroughPointerOperands) { if(op is CallOperator) { foreach(Expression ex2 in op.Arguments) { if(ex2.Type is ManagedPointerTypeRepresentation) { InvalidatePointer( ex2, setPossibleDefinitions, setVisited, prsv, gen ); } } } else if(op is StoreIndirectOperator || op is StoreInstanceFieldOperator) { InvalidatePointer( op.FirstArgument, setPossibleDefinitions, setVisited, prsv, gen ); } else { throw new NotImplementedException(); } } foreach(var ex in op.Results) { InvalidateExpression( prsv, gen, ex ); gen.Set( op.SpanningTreeIndex ); } } private void InvalidatePointer( Expression ex , GrowOnlySet setPossibleDefinitions , GrowOnlySet setVisited , BitVector prsv , BitVector gen ) { setPossibleDefinitions.Clear(); setVisited .Clear(); //ex.CollectPossibleDefinitionSites( setPossibleDefinitions, setVisited ); foreach(Operator op in setPossibleDefinitions) { if(prsv.IsEmpty) { // // Nothing preserved, no more changes possible. // break; } if(op is AddressAssignmentOperator) { InvalidateExpression( prsv, gen, op.FirstArgument ); } else if(op is StackAllocationOperator) { } else if(op is CallOperator) { } else if(op is LoadIndirectOperator) { } else if(op is SingleAssignmentOperator || op is PiOperator || op is UnboxOperator ) { Expression src = op.FirstArgument; if(src.Type is PointerTypeRepresentation) { GrowOnlySet< Operator > setPossibleDefinitions2 = SetFactory.NewWithReferenceEquality< Operator >(); GrowOnlySet< Operator > setVisited2 = SetFactory.NewWithReferenceEquality< Operator >(); InvalidatePointer( src, setPossibleDefinitions2, setVisited2, prsv, gen ); } } else if(op is BinaryOperator || op is SignExtendOperator || op is ZeroExtendOperator || op is TruncateOperator ) { // // This means there's some pointer arithmetic. // As a consequence, we don't know the exact origin of the pointer. // prsv.ClearAll(); gen .ClearAll(); } else if(op is LoadElementAddressOperator) { // // Although all accesses to arrays could be affected, // we are only interested in the effects on expressions (locals, arguments, and temporaries). // } else if(op is LoadElementOperator || op is LoadFieldOperator ) { // // Pointers stored in an object cannot point to locals or arguments, only to the heap. // } else if(op is LoadAddressOperator) { // // Although all accesses to the field could be affected, // we are only interested in the effects on expressions (locals, arguments, and temporaries). // } else { throw new NotImplementedException(); } } } private void InvalidateExpression( BitVector prsv , BitVector gen , Expression ex ) { int numOp = m_definitions.Length; for(int i = 0; i < numOp; i++) { Operator op = m_definitions[i]; foreach(var lhs in op.Results) { if(lhs == ex) { prsv.Clear( i ); gen .Clear( i ); break; } } } } //// private void InvalidateFieldAccesses( BitVector prsv , //// FieldVariableExpression field ) //// { //// int numOp = m_definitions.Length; //// //// for(int i = 0; i < numOp; i++) //// { //// Operator op = m_definitions[i]; //// //// foreach(Expression ex in op.Rhs) //// { //// if(ex is FieldVariableExpression) //// { //// FieldVariableExpression field2 = (FieldVariableExpression)ex; //// //// if(field2.Field == field.Field) //// { //// prsv.Clear( i ); //// break; //// } //// } //// } //// } //// } private void SolveEquations() { BitVector tmp = new BitVector(); int numBB = m_basicBlocks.Length; while(true) { bool fDone = true; // // RCHout = (RCHin And PRSV) Or GEN // for(int i = 0; i < numBB; i++) { tmp.Assign( m_state_RCHin[i] ); tmp.AndInPlace( m_state_PRSV[i] ); tmp.OrInPlace( m_state_GEN[i] ); if(m_state_RCHout[i] != tmp) { m_state_RCHout[i].Assign( tmp ); fDone = false; } } if(fDone) { break; } // // RCHin = Or { RCHout() } // for(int i = 0; i < numBB; i++) { BitVector b = m_state_RCHin[i]; b.ClearAll(); foreach(BasicBlockEdge edge in m_basicBlocks[i].Predecessors) { b.OrInPlace( m_state_RCHout[ edge.Predecessor.SpanningTreeIndex ] ); } } } } } } ================================================ FILE: Zelig/Zelig/CompileTime/CodeGenerator/CodeTransformation/DataManager.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // #if DEBUG #define TRACK_DATADESCRIPTOR_IDENTITY #else //#define TRACK_DATADESCRIPTOR_IDENTITY #endif namespace Microsoft.Zelig.CodeGeneration.IR { using System; using System.Collections.Generic; using System.Runtime.CompilerServices; using Microsoft.Zelig.Runtime.TypeSystem; public class DataManager { [Flags] public enum Attributes { Constant = 0x00000000, Mutable = 0x00000001, SuitableForConstantPropagation = 0x00000002, } public abstract class DataDescriptor { // // State // #if TRACK_DATADESCRIPTOR_IDENTITY protected static int s_identity; #endif public int m_identity; //--// protected DataManager m_owner; protected TypeRepresentation m_context; protected Attributes m_flags; protected Abstractions.PlacementRequirements m_placementRequirements; protected DataDescriptor m_nestingDd; protected InstanceFieldRepresentation m_nestingFd; protected int m_nestingPos; // // Constructor Methods // protected DataDescriptor() // Default constructor required by TypeSystemSerializer. { } protected DataDescriptor( DataManager owner , TypeRepresentation context , Attributes flags , Abstractions.PlacementRequirements pr ) { #if TRACK_DATADESCRIPTOR_IDENTITY m_identity = s_identity++; #endif m_owner = owner; m_context = context; m_flags = flags; m_placementRequirements = pr; } // // Helper Methods // internal void SetNesting( DataDescriptor nestingDd , InstanceFieldRepresentation nestingFd , int nestingPos ) { m_nestingDd = nestingDd; m_nestingFd = nestingFd; m_nestingPos = nestingPos; } protected void ApplyTransformationInner( TransformationContextForCodeTransformation context ) { context.Transform ( ref m_owner ); context.Transform ( ref m_context ); context.Transform ( ref m_flags ); context.Transform ( ref m_placementRequirements ); context.TransformGeneric( ref m_nestingDd ); context.Transform ( ref m_nestingFd ); context.Transform ( ref m_nestingPos ); } //--// internal virtual void IncludeExtraTypes( TypeSystem.Reachability reachability , CompilationSteps.PhaseDriver phase ) { RefreshValues( phase ); reachability.ExpandPending( m_context ); if(m_context is ReferenceTypeRepresentation) { object valVt = m_owner.GetObjectDescriptor( m_context.VirtualTable ); reachability.ExpandPending( valVt ); } } internal abstract void Reduce( GrowOnlySet< DataDescriptor > visited , TypeSystem.Reachability reachability , bool fApply ); internal abstract void RefreshValues( CompilationSteps.PhaseDriver phase ); internal abstract void Write( ImageBuilders.SequentialRegion region ); public abstract object GetDataAtOffset( FieldRepresentation[] accessPath , int accessPathIndex , int offset ); //--// protected void WriteHeader( ImageBuilders.SequentialRegion region , TypeRepresentation context ) { if(context is ValueTypeRepresentation) { // // Value types don't have headers. // return; } WellKnownTypes wkt = m_owner.m_typeSystem.WellKnownTypes; TypeRepresentation tdHeader = wkt.Microsoft_Zelig_Runtime_ObjectHeader; if(tdHeader != null) { WellKnownFields wkf = m_owner.m_typeSystem.WellKnownFields; ImageBuilders.SequentialRegion.Section sec = region.GetSectionOfFixedSize( tdHeader.Size ); FieldRepresentation fd; region.PointerOffset = region.Position; fd = wkf.ObjectHeader_VirtualTable; if(fd != null) { DataManager.DataDescriptor vTable = (DataManager.DataDescriptor)m_owner.GetObjectDescriptor( context.VirtualTable ); sec.Offset = (uint)fd.Offset; sec.AddImageAnnotation( fd.FieldType.SizeOfHoldingVariable, fd ); sec.WritePointerToDataDescriptor( vTable ); } fd = wkf.ObjectHeader_MultiUseWord; if(fd != null) { sec.Offset = (uint)fd.Offset; sec.AddImageAnnotation( fd.FieldType.SizeOfHoldingVariable, fd ); Runtime.ObjectHeader.GarbageCollectorFlags flags; if(this.IsMutable) { flags = Runtime.ObjectHeader.GarbageCollectorFlags.UnreclaimableObject; } else { flags = Runtime.ObjectHeader.GarbageCollectorFlags.ReadOnlyObject; } sec.Write( (uint)flags ); } } } // // Access Methods // public TypeRepresentation Context { get { return m_context; } } public DataManager Owner { get { return m_owner; } } public bool IsMutable { get { return (m_flags & Attributes.Mutable) != 0; } } public bool CanPropagate { get { return (m_flags & Attributes.SuitableForConstantPropagation) != 0; } } public DataDescriptor Nesting { get { return m_nestingDd; } } public InstanceFieldRepresentation NestingField { get { return m_nestingFd; } } public int NestingIndex { get { return m_nestingPos; } } public Abstractions.PlacementRequirements PlacementRequirements { get { return m_placementRequirements; } set { m_placementRequirements = value; } } // // Debug Methods // public override string ToString() { return ToString( false ); } internal string ToStringVerbose() { return ToString( true ); } protected abstract string ToString( bool fVerbose ); } //--//--//--//--//--//--//--//--//--// public class ObjectDescriptor : DataDescriptor { // // State // private object m_source; private GrowOnlyHashTable< InstanceFieldRepresentation, object > m_values; // // Constructor Methods // private ObjectDescriptor() // Default constructor required by TypeSystemSerializer. { m_values = HashTableFactory.New< InstanceFieldRepresentation, object >(); } internal ObjectDescriptor( DataManager owner , TypeRepresentation context , Attributes flags , Abstractions.PlacementRequirements pr , object source ) : base( owner, context, flags, pr ) { m_source = source; m_values = HashTableFactory.New< InstanceFieldRepresentation, object >(); } // // Helper Methods // public void ApplyTransformation( TransformationContextForCodeTransformation context ) { context.Push( this ); ApplyTransformationInner( context ); context.Transform( ref m_source ); context.Transform( ref m_values ); context.Pop(); } //--// internal override void IncludeExtraTypes( TypeSystem.Reachability reachability , CompilationSteps.PhaseDriver phase ) { base.IncludeExtraTypes( reachability, phase ); if(m_source != null) { reachability.ExpandPending( m_source ); } foreach(InstanceFieldRepresentation fd in m_values.Keys) { object val = m_values[fd]; if(val != null && reachability.Contains( fd )) { if(val is DataDescriptor) { reachability.ExpandPending( val ); } } } } internal override void Reduce( GrowOnlySet< DataDescriptor > visited , TypeSystem.Reachability reachability , bool fApply ) { if(visited.Insert( this ) == false) { CHECKS.ASSERT( reachability.Contains( m_context ), "The type of {0} is not included in the globalReachabilitySet: {1}", this, m_context ); GrowOnlyHashTable< InstanceFieldRepresentation, object > valuesNew = m_values.CloneSettings(); foreach(InstanceFieldRepresentation fd in m_values.Keys) { if(reachability.Contains( fd )) { object val = m_values[fd]; if(val == null || reachability.IsProhibited( val ) == false) { valuesNew[fd] = val; if(val is DataDescriptor) { DataDescriptor dd = (DataDescriptor)val; dd.Reduce( visited, reachability, fApply ); } } } } if(fApply) { m_values = valuesNew; } } } //--// internal void UpdateSource( object source , CompilationSteps.PhaseDriver phase ) { m_source = source; RefreshValues( phase ); } internal override void RefreshValues( CompilationSteps.PhaseDriver phase ) { if(m_source != null) { const System.Reflection.BindingFlags bindingFlags = System.Reflection.BindingFlags.DeclaredOnly | System.Reflection.BindingFlags.Public | System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.Instance; Type typeSrc = m_source.GetType(); TypeRepresentation typeDst = m_context; TypeSystemForCodeTransformation typeSystem = m_owner.m_typeSystem; WellKnownTypes wkt = typeSystem.WellKnownTypes; WellKnownFields wkf = typeSystem.WellKnownFields; FieldRepresentation fdStringImpl_FirstChar = wkf.StringImpl_FirstChar; FieldRepresentation fdVTable_Type = wkf.VTable_Type; GrowOnlyHashTable< InstanceFieldRepresentation, object > values = m_values; m_values = values.CloneSettingsAndSize(); while(typeDst != null) { foreach(FieldRepresentation fdIn in typeDst.Fields) { InstanceFieldRepresentation fd = fdIn as InstanceFieldRepresentation; if(fd != null) { object valOld; values.TryGetValue( fd, out valOld ); if(fd == fdStringImpl_FirstChar) { // // Special case for strings: store the whole content as an array of chars. // Set( fd, ((string)m_source).ToCharArray() ); } else if(fd == wkf.StringImpl_ArrayLength) { Set(fd, ((string)m_source).ToCharArray().Length); } else if(fd == wkf.StringImpl_StringLength) { Set(fd, ((string)m_source).Length); } else if(fd == fdVTable_Type) { // // Special case for virtual tables: create a TypeImpl on the fly. // if(valOld == null) { TypeRepresentation valTd = wkt.Microsoft_Zelig_Runtime_RuntimeTypeImpl; if(valTd != null) { ObjectDescriptor od = m_owner.BuildObjectDescriptor( valTd, Attributes.Constant | Attributes.SuitableForConstantPropagation, null ); InstanceFieldRepresentation fdTarget = (InstanceFieldRepresentation)wkf.RuntimeTypeImpl_m_handle; VTable vTable = (VTable)m_source; ObjectDescriptor odSub = typeSystem.CreateDescriptorForRuntimeHandle( vTable.TypeInfo ); odSub.SetNesting( od, fdTarget, -1 ); odSub.RefreshValues( phase ); od.Set( fdTarget, odSub ); valOld = od; } } Set( fd, valOld ); } else { System.Reflection.FieldInfo fi = typeSrc.GetField( fd.Name, bindingFlags ); if(fi != null) { object val = fi.GetValue( m_source ); ObjectDescriptor oldOD = valOld as ObjectDescriptor; if(fi.FieldType.IsValueType && oldOD != null) { oldOD.UpdateSource( val, phase ); Set( fd, oldOD ); } else { Set( fd, m_owner.ConvertToObjectDescriptor( fd.FieldType, m_flags, m_placementRequirements, val, this, fd, -1, phase ) ); } } else { throw TypeConsistencyErrorException.Create( "Cannot create ObjectDescriptor, field '{0}' is missing in source object", fd ); } } } } typeSrc = typeSrc.BaseType; typeDst = typeDst.Extends; } } } //--// internal override void Write( ImageBuilders.SequentialRegion region ) { WriteHeader( region, m_context ); string text = m_source as string; int arrayLength = text != null ? (text.Length+1) : 0; VTable vtable = m_context.VirtualTable; ImageBuilders.SequentialRegion.Section sec = region.GetSectionOfFixedSize( vtable.BaseSize + vtable.ElementSize * (uint)arrayLength ); WriteFields( sec, vtable ); } internal void WriteFields( ImageBuilders.SequentialRegion.Section sec , VTable vtable ) { WellKnownFields wkf = m_owner.m_typeSystem.WellKnownFields; FieldRepresentation fdFirstChar = wkf.StringImpl_FirstChar; FieldRepresentation fdCodePointer_Target = wkf.CodePointer_Target; foreach(InstanceFieldRepresentation fd in m_values.Keys) { object val = m_values[fd]; sec.Offset = (uint)fd.Offset; sec.AddImageAnnotation( fd.FieldType.SizeOfHoldingVariable, fd ); if(fd == fdFirstChar) { // // Special case for strings: store the whole content as an array of chars. // sec.Write( (char[])val ); } else if(fd == fdCodePointer_Target) { // // Special case for code pointers: substitute with actual code pointers. // IntPtr id = (IntPtr)val; object ptr = m_owner.GetCodePointerFromUniqueID( id ); if(ptr is MethodRepresentation) { MethodRepresentation md = (MethodRepresentation)ptr; ControlFlowGraphStateForCodeTransformation cfg = TypeSystemForCodeTransformation.GetCodeForMethod( md ); if(cfg == null) { sec.WriteNullPointer(); } else { sec.WritePointerToBasicBlock( cfg.EntryBasicBlock ); } } else if(ptr is ExceptionHandlerBasicBlock) { ExceptionHandlerBasicBlock ehBB = (ExceptionHandlerBasicBlock)ptr; sec.WritePointerToBasicBlock( ehBB ); } else { sec.Write( id ); } } else if(val == null) { sec.WriteNullPointer(); } else if(val is DataDescriptor) { DataDescriptor dd = (DataDescriptor)val; if(dd.Nesting != null) { ObjectDescriptor od = (ObjectDescriptor)dd; od.WriteFields( sec.GetSubSection( dd.Context.Size ), dd.Context.VirtualTable ); } else { sec.WritePointerToDataDescriptor( dd ); } } else if(fd.FieldType is ScalarTypeRepresentation) { if(sec.WriteGeneric( val ) == false) { throw TypeConsistencyErrorException.Create( "Can't write scalar value {0}", val ); } } else { throw TypeConsistencyErrorException.Create( "Don't know how to write {0}", val ); } } } //--// public override object GetDataAtOffset( FieldRepresentation[] accessPath , int accessPathIndex , int offset ) { if(!this.CanPropagate) { return null; } lock(TypeSystemForCodeTransformation.Lock) { if(accessPath != null && accessPathIndex < accessPath.Length) { var fd = (InstanceFieldRepresentation)accessPath[accessPathIndex++]; object val; if(m_values.TryGetValue( fd, out val ) == false) { return null; } offset -= fd.Offset; if(accessPathIndex == accessPath.Length) { return val; } var dd = val as DataDescriptor; if(dd == null) { return null; } return dd.GetDataAtOffset( accessPath, accessPathIndex, offset ); } foreach(InstanceFieldRepresentation fd in m_values.Keys) { if(fd.Offset == offset) { return m_values[fd]; } } return null; } } //--// public void ConvertAndSet( InstanceFieldRepresentation fd , Attributes flags , Abstractions.PlacementRequirements pr , object val ) { lock(TypeSystemForCodeTransformation.Lock) { Set( fd, m_owner.ConvertToObjectDescriptor( fd.FieldType, flags, pr, val ) ); } } public void Set( InstanceFieldRepresentation fd , object val ) { lock(TypeSystemForCodeTransformation.Lock) { m_values[fd] = val; } } public object Get( InstanceFieldRepresentation fd ) { lock(TypeSystemForCodeTransformation.Lock) { object res; m_values.TryGetValue( fd, out res ); return res; } } public bool Has( InstanceFieldRepresentation fd ) { lock(TypeSystemForCodeTransformation.Lock) { return m_values.ContainsKey( fd ); } } //--// // // Access Methods // public object Source { get { return m_source; } } public GrowOnlyHashTable< InstanceFieldRepresentation, object > Values { get { return m_values; } } // // Debug Methods // protected override string ToString( bool fVerbose ) { System.Text.StringBuilder sb = new System.Text.StringBuilder(); sb.AppendFormat( "$Object({0}", m_context.FullName ); if(m_source != null) { sb.AppendFormat( " => {0}", m_source ); } if(fVerbose) { bool fFirst = true; foreach(InstanceFieldRepresentation fd in m_values.Keys) { object val = m_values[fd]; if(val != null) { if(fFirst) { sb.Append( " -> " ); fFirst = false; } else { sb.Append( ", " ); } if(val is DataDescriptor) { DataDescriptor dd = (DataDescriptor)val; val = dd.Context; } sb.AppendFormat( "{0}::{1} = {2}", fd.OwnerType.FullNameWithAbbreviation, fd.Name, val ); } } } sb.Append( ")" ); if(m_nestingDd != null) { sb.AppendFormat( " => {0}", fVerbose ? m_nestingDd.ToStringVerbose() : m_nestingDd.ToString() ); } return sb.ToString(); } } //--//--//--//--//--//--//--//--//--// public class ArrayDescriptor : DataDescriptor { // // State // private Array m_source; private int m_length; private object[] m_values; // // Constructor Methods // internal ArrayDescriptor( DataManager owner , ArrayReferenceTypeRepresentation context , Attributes flags , Abstractions.PlacementRequirements pr , Array source , int len ) : base( owner, context, flags, pr ) { m_source = source; m_length = len; if(source == null || source.GetType().GetElementType().IsPrimitive == false) { m_values = new object[len]; } } // // Helper Methods // public void ApplyTransformation( TransformationContextForCodeTransformation context ) { context.Push( this ); ApplyTransformationInner( context ); context.TransformGeneric( ref m_source ); context.Transform ( ref m_values ); context.Pop(); } //--// internal override void IncludeExtraTypes( TypeSystem.Reachability reachability , CompilationSteps.PhaseDriver phase ) { base.IncludeExtraTypes( reachability, phase ); if(m_values != null) { foreach(object obj in m_values) { if(obj is DataDescriptor) { DataDescriptor dd = (DataDescriptor)obj; if(reachability.Contains( dd.Context )) { reachability.ExpandPending( obj ); } } } } } internal override void Reduce( GrowOnlySet< DataDescriptor > visited , TypeSystem.Reachability reachability , bool fApply ) { if(visited.Insert( this ) == false) { CHECKS.ASSERT( reachability.Contains( m_context ), "The type of {0} is not included in the globalReachabilitySet: {1}", this, m_context ); if(m_values != null) { foreach(object val in m_values) { if(val is DataDescriptor) { DataDescriptor dd = (DataDescriptor)val; dd.Reduce( visited, reachability, fApply ); } } } } } //--// internal override void RefreshValues( CompilationSteps.PhaseDriver phase ) { if(m_source != null && m_values != null) { TypeRepresentation typeDst = m_context.UnderlyingType.ContainedType; for(int i = 0; i < m_length; i++) { object val = m_source.GetValue( i ); ObjectDescriptor oldOD = Get( i ) as ObjectDescriptor; if(typeDst is ValueTypeRepresentation && oldOD != null) { oldOD.UpdateSource( val, phase ); } else { Set( i, m_owner.ConvertToObjectDescriptor( typeDst, m_flags, m_placementRequirements, val, this, null, i, phase ) ); } } } } //--// internal override void Write( ImageBuilders.SequentialRegion region ) { WriteHeader( region, m_context ); uint arrayLength = (uint)m_length; VTable vtable = m_context.VirtualTable; ImageBuilders.SequentialRegion.Section sec = region.GetSectionOfFixedSize( vtable.BaseSize + vtable.ElementSize * arrayLength ); FieldRepresentation fd = m_owner.m_typeSystem.WellKnownFields.ArrayImpl_m_numElements; if(fd != null) { sec.Offset = (uint)fd.Offset; sec.AddImageAnnotation( fd.FieldType.SizeOfHoldingVariable, fd ); sec.Write( arrayLength ); } if(region.PlacementRequirements.ContentsUninitialized) { region.PayloadCutoff = sec.Position; } else { // // Special case for common scalar arrays. // if(m_values == null) { if(m_source is byte[]) { sec.Write( (byte[])m_source ); return; } if(m_source is char[]) { sec.Write( (char[])m_source ); return; } if(m_source is int[]) { sec.Write( (int[])m_source ); return; } if(m_source is uint[]) { sec.Write( (uint[])m_source ); return; } } for(uint i = 0; i < arrayLength; i++) { object val = GetDirect( (int)i ); sec.Offset = vtable.BaseSize + vtable.ElementSize * i; if(val == null) { sec.WriteNullPointer(); } else if(val is DataDescriptor) { DataDescriptor dd = (DataDescriptor)val; if(dd.Nesting != null) { ObjectDescriptor od = (ObjectDescriptor)dd; od.WriteFields( sec.GetSubSection( vtable.ElementSize ), dd.Context.VirtualTable ); } else { sec.WritePointerToDataDescriptor( dd ); } } else if(m_context.ContainedType is ScalarTypeRepresentation) { if(sec.WriteGeneric( val ) == false) { throw TypeConsistencyErrorException.Create( "Can't write scalar value {0}", val ); } } else { throw TypeConsistencyErrorException.Create( "Don't know how to write {0}", val ); } } } } //--// public override object GetDataAtOffset( FieldRepresentation[] accessPath , int accessPathIndex , int offset ) { if(!this.CanPropagate) { return null; } lock(TypeSystemForCodeTransformation.Lock) { uint arrayLength = (uint)m_length; if(offset == 0) { return arrayLength; } else { VTable vtable = m_context.VirtualTable; offset -= (int)vtable.BaseSize; offset /= (int)vtable.ElementSize; if(offset >= 0 && offset < m_length) { return GetDirect( offset ); } return null; } } } //--// public void Set( int pos , object val ) { lock(TypeSystemForCodeTransformation.Lock) { m_values[pos] = val; } } public object Get( int pos ) { lock(TypeSystemForCodeTransformation.Lock) { return GetDirect( pos ); } } private object GetDirect( int pos ) { return m_values != null ? m_values[pos] : m_source.GetValue( pos ); } //--// // // Access Methods // public Array Source { get { return m_source; } } //ZELIG2LLVM: Added Length public getter public int Length { get { return m_length; } } public object[] Values { get { return m_values; } } //--// // // Debug Methods // protected override string ToString( bool fVerbose ) { System.Text.StringBuilder sb = new System.Text.StringBuilder(); sb.AppendFormat( "$Array({0}", m_context.FullName ); if(m_source != null) { sb.AppendFormat( " => {0}", m_source ); } if(fVerbose) { sb.Append( " -> [" ); for(int i = 0; i < m_length; i++) { object val = GetDirect( i ); if(val != null) { if(i != 0) { sb.Append( ", " ); } if(val is DataDescriptor) { DataDescriptor dd = (DataDescriptor)val; val = dd.Context; } sb.AppendFormat( "{0} = {1}", i, val ); } } sb.Append( "]" ); } sb.Append( ")" ); if(m_nestingDd != null) { sb.AppendFormat( " => {0}", fVerbose ? m_nestingDd.ToStringVerbose() : m_nestingDd.ToString() ); } return sb.ToString(); } } //--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--// // // State // TypeSystemForCodeTransformation m_typeSystem; GrowOnlyHashTable< object, DataDescriptor > m_data; GrowOnlyHashTable< object, int > m_codePointers; GrowOnlyHashTable< int , object > m_codePointersReverse; // Not persisted, rebuilt if needed. int m_nextCodePointerId; // // Constructor Methods // private DataManager() // Default constructor required by TypeSystemSerializer. { m_data = HashTableFactory.NewWithWeakEquality < object, DataDescriptor >(); m_codePointers = HashTableFactory.NewWithReferenceEquality< object, int >(); } internal DataManager( TypeSystemForCodeTransformation typeSystem ) : this() { m_typeSystem = typeSystem; } // // Helper Methods // public void ApplyTransformation( TransformationContextForCodeTransformation context ) { context.Push( this ); context.Transform( ref m_typeSystem ); context.Transform( ref m_data ); context.Transform( ref m_codePointers ); context.Transform( ref m_nextCodePointerId ); context.Pop(); } //--// internal void Reduce( TypeSystem.Reachability reachability , bool fApply ) { GrowOnlyHashTable< object, DataDescriptor > dataNew = m_data.CloneSettings(); GrowOnlySet< DataDescriptor > visited = SetFactory.NewWithReferenceEquality< DataDescriptor >(); foreach(object obj in m_data.Keys) { DataDescriptor dd = m_data[obj]; if(reachability.IsProhibited( obj ) == false) { if(reachability.Contains( dd )) { dd.Reduce( visited, reachability, fApply ); dataNew[obj] = dd; dd = null; } } if(dd != null) { CHECKS.ASSERT( reachability.Contains( dd ) == false, "{0} cannot belong both to globalReachabilitySet and useProhibited", dd ); reachability.ExpandProhibition( dd ); } } if(fApply) { m_data = dataNew; } //--// if(fApply) { GrowOnlyHashTable< object, int > codePointers = m_codePointers.CloneSettings(); foreach(object obj in m_codePointers.Keys) { if(reachability.IsProhibited( obj ) == false) { codePointers[obj] = m_codePointers[obj]; } } m_codePointers = codePointers; m_codePointersReverse = null; } } //--// public object GetObjectDescriptor( object obj ) { if(obj == null) { return null; } else if(obj is DataDescriptor) { return (DataDescriptor)obj; } else if(obj.GetType().IsPrimitive) { return obj; } else if(obj is Enum) { return obj; } else { lock(TypeSystemForCodeTransformation.Lock) // It's called from multiple threads during parallel phase executions. { DataDescriptor res; if(m_data.TryGetValue( obj, out res )) { return res; } } return null; } } internal object ConvertToObjectDescriptor( object value , out TypeRepresentation tdTarget ) { tdTarget = m_typeSystem.GetTypeRepresentationFromObject( value ); return ConvertToObjectDescriptor( tdTarget, DataManager.Attributes.Constant | DataManager.Attributes.SuitableForConstantPropagation, null, value ); } internal object ConvertToObjectDescriptor( TypeRepresentation td , Attributes flags , Abstractions.PlacementRequirements pr , object obj ) { return ConvertToObjectDescriptor( td, flags, pr, obj, null, null, 0, null ); } private object ConvertToObjectDescriptor( TypeRepresentation td , Attributes flags , Abstractions.PlacementRequirements pr , object obj , DataDescriptor nestingDd , InstanceFieldRepresentation nestingFd , int nestingPos , CompilationSteps.PhaseDriver phase ) { if(obj == null) { return null; } else if(obj is DataDescriptor) { return (DataDescriptor)obj; } else if(obj.GetType().IsPrimitive) { return obj; } else if(obj is Enum) { return obj; } else { TypeRepresentation tdObj = m_typeSystem.GetTypeRepresentationFromType( obj.GetType() ); if(td.CanBeAssignedFrom( tdObj, null ) == false) { throw TypeConsistencyErrorException.Create( "Cannot create a DataDescriptor of type {0} with a value of type {1}", td, tdObj ); } lock(TypeSystemForCodeTransformation.Lock) // It's called from multiple threads during parallel phase executions. { DataDescriptor res; if(obj is ValueType || m_data.TryGetValue( obj, out res ) == false) { if(nestingFd != null) { bool fSkip = false; WellKnownFields wkf = m_typeSystem.WellKnownFields; if(CompilationSteps.PhaseDriver.CompareOrder( phase, typeof(CompilationSteps.Phases.ReduceTypeSystem) ) <= 0) { if(nestingFd == wkf.TypeRepresentation_MethodTable || nestingFd == wkf.TypeRepresentation_InterfaceMethodTables || nestingFd == wkf.VTable_MethodPointers || nestingFd == wkf.VTable_InterfaceMap ) { fSkip = true; } } // Note that we only want to skip GCInfo before the LayoutTypes phase, but not in LayoutType phase, // so GCInfo will be corrected during the call to RefreshValues as part of the LayoutTypes phase. if (CompilationSteps.PhaseDriver.CompareOrder( phase, typeof(CompilationSteps.Phases.LayoutTypes) ) < 0) { if(nestingFd == wkf.VTable_GCInfo) { fSkip = true; } } if(fSkip) { // // Don't generate a DataDescriptor for these items, they will be regenerated later. // return null; } } if(obj is Array) { Array array = (Array)obj; res = new ArrayDescriptor( this, (ArrayReferenceTypeRepresentation)tdObj, flags, pr, array, array.Length ); } else { res = new ObjectDescriptor( this, tdObj, flags, pr, obj ); } if(obj is ValueType) { res.SetNesting( nestingDd, nestingFd, nestingPos ); res.RefreshValues( phase ); } else { m_data[obj] = res; } InstantiateVTable( res ); } return res; } } } //--// private object ConvertVirtualTable( VTable vTable ) { TypeRepresentation tdVT = m_typeSystem.GetTypeRepresentationFromObject( vTable ); return ConvertToObjectDescriptor( tdVT, DataManager.Attributes.Constant | DataManager.Attributes.SuitableForConstantPropagation, null, vTable ); } private void InstantiateVTable( DataDescriptor dd ) { TypeRepresentation td = dd.Context; if(td is ReferenceTypeRepresentation) { VTable vt = td.VirtualTable; if(vt != null) { ConvertVirtualTable( vt ); } } } internal ObjectDescriptor BuildObjectDescriptor( TypeRepresentation td , DataManager.Attributes flags , Abstractions.PlacementRequirements pr ) { CHECKS.ASSERT( !(td is ArrayReferenceTypeRepresentation ), "Expecting an object, got an array: {0}", td ); CHECKS.ASSERT( !(td is AbstractReferenceTypeRepresentation), "Cannot instantiate abstract type: {0}", td ); lock(TypeSystemForCodeTransformation.Lock) // It's called from multiple threads during parallel phase executions. { ObjectDescriptor od = new ObjectDescriptor( this, td, flags, pr, null ); m_data[od] = od; InstantiateVTable( od ); return od; } } internal ArrayDescriptor BuildArrayDescriptor( ArrayReferenceTypeRepresentation td , DataManager.Attributes flags , Abstractions.PlacementRequirements pr , Array array , int len ) { CHECKS.ASSERT( (td is ArrayReferenceTypeRepresentation), "Expecting an array, got an object: {0}", td ); ArrayDescriptor ad; lock(TypeSystemForCodeTransformation.Lock) // It's called from multiple threads during parallel phase executions. { ad = new ArrayDescriptor( this, td, flags, pr, array, len ); m_data[ad] = ad; InstantiateVTable( ad ); } if(array == null) { var tdElement = td.ContainedType; if(tdElement is ValueTypeRepresentation) { if(!(tdElement is ScalarTypeRepresentation)) { for(int pos = 0; pos < len; pos++) { var od = BuildObjectDescriptor( tdElement, flags, pr ); od.SetNesting( ad, null, pos ); ad.Set( pos, od ); } } } } return ad; } //--// internal CodePointer CreateCodePointer( object obj ) { CodePointer res; int id; lock(TypeSystemForCodeTransformation.Lock) // It's called from multiple threads during parallel phase executions. { if(m_codePointers.TryGetValue( obj, out id ) == false) { id = m_nextCodePointerId++; // // To distinguish between real method pointers and placeholders, // we use a non-word-aligned value, which is illegal for real methods. // id = (id * 2 + 1); m_codePointers[obj] = id; if(m_codePointersReverse != null) { m_codePointersReverse[id] = obj; } } } // // To distinguish between real method pointers and placeholders, // we use a non-word-aligned value, which is illegal for real methods. // res.Target = new IntPtr( id ); return res; } internal object GetCodePointerFromUniqueID( IntPtr val ) { int id = val.ToInt32(); if((id & 1) != 0) { lock(TypeSystemForCodeTransformation.Lock) // It's called from multiple threads during parallel phase executions. { if(m_codePointersReverse == null) { m_codePointersReverse = HashTableFactory.New< int, object >(); object[] keys = m_codePointers.KeysToArray (); int[] values = m_codePointers.ValuesToArray(); for(int i = 0; i < keys.Length; i++) { m_codePointersReverse[ values[i] ] = keys[i]; } } object obj; if(m_codePointersReverse.TryGetValue( id, out obj )) { return obj; } } } return null; } internal void RefreshValues( CompilationSteps.PhaseDriver phase ) { GrowOnlyHashTable< object, DataDescriptor > dataIncr = m_data.CloneSettings(); // // Because the process of population can create new DataDescriptors, we need to keep iterating. // while(true) { object[] keys = m_data.KeysToArray(); bool fDone = true; foreach(object obj in keys) { DataDescriptor dd = m_data[obj]; if(dataIncr.Update( obj, dd ) == false) { dd.RefreshValues( phase ); fDone = false; } } if(fDone) break; } } } } ================================================ FILE: Zelig/Zelig/CompileTime/CodeGenerator/CodeTransformation/Expressions/ConditionCodeExpression.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // namespace Microsoft.Zelig.CodeGeneration.IR { using System; using System.Collections.Generic; using Microsoft.Zelig.Runtime.TypeSystem; public sealed class ConditionCodeExpression : LowLevelVariableExpression { public enum Comparison : byte { Equal , NotEqual , Negative , PositiveOrZero , Overflow , NoOverflow , UnsignedHigherThanOrSame, UnsignedLowerThan , UnsignedHigherThan , UnsignedLowerThanOrSame , SignedGreaterThanOrEqual, SignedLessThan , SignedGreaterThan , SignedLessThanOrEqual , Always , NotValid , } internal class ConstantResult : ConstantExpression.DelayedValue, ITransformationContextTarget { // // State // object m_left; object m_right; // // Constructor Methods // internal ConstantResult( object left , object right ) { m_left = left; m_right = right; } //--// // // MetaDataEquality Methods // public override bool Equals( object obj ) { if(obj is ConstantResult) { ConstantResult other = (ConstantResult)obj; if(m_left == other.m_left && m_right == other.m_right ) { return true; } } return false; } public override int GetHashCode() { return m_left.GetHashCode(); } // // Helper Methods // //--// void ITransformationContextTarget.ApplyTransformation( TransformationContext context ) { context.Push( this ); context.TransformGeneric( ref m_left ); context.TransformGeneric( ref m_right ); context.Pop(); } //--// // // Access Methods // public override bool CanEvaluate { get { return false; } } public override object Value { get { return null; } } public object LeftValue { get { return m_left; } } public object RightValue { get { return m_right; } } //--// // // Debug Methods // public override string ToString() { return string.Format( "", m_left, m_right ); } } //--// // // Constructor Methods // internal ConditionCodeExpression( TypeRepresentation type , VariableExpression sourceVar , uint sourceOffset ) : base( type, null, sourceVar, sourceOffset ) { } //--// // // Helper Methods // public override Expression Clone( CloningContext context ) { ControlFlowGraphStateForCodeTransformation cfg = (ControlFlowGraphStateForCodeTransformation)context.ControlFlowGraphDestination; return RegisterAndCloneState( context, cfg.AllocateConditionCode() ); } //--// public override Operator.OperatorLevel GetLevel( Operator.IOperatorLevelHelper helper ) { return Operator.OperatorLevel.Registers; } public override int GetVariableKind() { return c_VariableKind_Condition; } //--// public static Comparison NegateCondition( Comparison cond ) { switch(cond) { case Comparison.Equal : cond = Comparison.NotEqual ; break; case Comparison.NotEqual : cond = Comparison.Equal ; break; case Comparison.Negative : cond = Comparison.PositiveOrZero ; break; case Comparison.PositiveOrZero : cond = Comparison.Negative ; break; case Comparison.Overflow : cond = Comparison.NoOverflow ; break; case Comparison.NoOverflow : cond = Comparison.Overflow ; break; case Comparison.UnsignedHigherThanOrSame: cond = Comparison.UnsignedLowerThan ; break; case Comparison.UnsignedLowerThan : cond = Comparison.UnsignedHigherThanOrSame; break; case Comparison.UnsignedHigherThan : cond = Comparison.UnsignedLowerThanOrSame ; break; case Comparison.UnsignedLowerThanOrSame : cond = Comparison.UnsignedHigherThan ; break; case Comparison.SignedGreaterThanOrEqual: cond = Comparison.SignedLessThan ; break; case Comparison.SignedLessThan : cond = Comparison.SignedGreaterThanOrEqual; break; case Comparison.SignedGreaterThan : cond = Comparison.SignedLessThanOrEqual ; break; case Comparison.SignedLessThanOrEqual : cond = Comparison.SignedGreaterThan ; break; } return cond; } //--// // // Access Methods // public override CanBeNull CanBeNull { get { return CanBeNull.Unknown; } } public override bool CanTakeAddress { get { return false; } } //--// // // Debug Methods // public override void InnerToString( System.Text.StringBuilder sb ) { sb.Append( "$CC_" ); base.InnerToString( sb ); } } } ================================================ FILE: Zelig/Zelig/CompileTime/CodeGenerator/CodeTransformation/Expressions/LowLevelVariableExpression.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // namespace Microsoft.Zelig.CodeGeneration.IR { using System; using System.Collections.Generic; using Microsoft.Zelig.Runtime.TypeSystem; public abstract class LowLevelVariableExpression : VariableExpression { protected const int c_VariableKind_Pseudo = 4; protected const int c_VariableKind_Physical = 5; protected const int c_VariableKind_Condition = 6; protected const int c_VariableKind_StackLocation = 7; // 7-9, depending on the placement. // // State // protected VariableExpression m_sourceVar; protected uint m_sourceOffset; // // Constructor Methods // protected LowLevelVariableExpression( TypeRepresentation type , DebugInfo debugInfo , VariableExpression sourceVar , uint sourceOffset ) : base( type, debugInfo ) { m_sourceVar = sourceVar; m_sourceOffset = sourceOffset; } //--// // // Helper Methods // protected override void CloneState( CloningContext context , Expression clone ) { LowLevelVariableExpression clone2 = (LowLevelVariableExpression)clone; clone2.m_sourceVar = (VariableExpression)context.Clone( m_sourceVar ); base.CloneState( context, clone ); } //--// public override void ApplyTransformation( TransformationContextForIR context ) { context.Push( this ); base.ApplyTransformation( context ); context.Transform( ref m_sourceVar ); context.Transform( ref m_sourceOffset ); context.Pop(); } //--// // // Access Methods // public VariableExpression SourceVariable { get { return m_sourceVar; } } public uint SourceOffset { get { return m_sourceOffset; } } public VariableExpression AggregateVariable { get { return m_sourceVar != null ? m_sourceVar : this; } } //--// // // Debug Methods // protected void AppendOffsetInfo( System.Text.StringBuilder sb ) { if(m_sourceVar != null) { sb.Append( "<<" ); m_sourceVar.InnerToString( sb ); if(m_sourceOffset != 0 || m_sourceVar.Type.Size != this.Type.Size) { sb.AppendFormat( " at offset {0}", m_sourceOffset ); } sb.Append( ">>" ); } } } } ================================================ FILE: Zelig/Zelig/CompileTime/CodeGenerator/CodeTransformation/Expressions/PhiVariableExpression.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // namespace Microsoft.Zelig.CodeGeneration.IR { using System; using System.Collections.Generic; using Microsoft.Zelig.Runtime.TypeSystem; public sealed class PhiVariableExpression : VariableExpression { public static new readonly PhiVariableExpression[] SharedEmptyArray = new PhiVariableExpression[0]; // // State // private VariableExpression m_target; private int m_version; // // Constructor Methods // internal PhiVariableExpression( VariableExpression target ) : base( target.Type, target.DebugName ) { m_target = target; m_version = -1; } // // Equality Methods // public override bool IsTheSamePhysicalEntity( Expression ex ) { if(base.IsTheSamePhysicalEntity( ex )) { return true; } return m_target.IsTheSamePhysicalEntity( ex ); } public override bool IsTheSameAggregate( Expression ex ) { if(base.IsTheSameAggregate( ex )) { return true; } return m_target.IsTheSameAggregate( ex ); } //--// // // Helper Methods // public override Expression Clone( CloningContext context ) { ControlFlowGraphStateForCodeTransformation cfg = (ControlFlowGraphStateForCodeTransformation)context.ControlFlowGraphDestination; return RegisterAndCloneState( context, cfg.AllocatePhiVariable( null ) ); } protected override void CloneState( CloningContext context , Expression clone ) { PhiVariableExpression clone2 = (PhiVariableExpression)clone; clone2.m_target = (PhiVariableExpression)context.Clone( m_target ); base.CloneState( context, clone ); } //--// public override void ApplyTransformation( TransformationContextForIR context ) { context.Push( this ); base.ApplyTransformation( context ); context.Transform( ref m_target ); context.Pop(); } //--// public override Operator.OperatorLevel GetLevel( Operator.IOperatorLevelHelper helper ) { return m_target.GetLevel( helper ); } public override int GetVariableKind() { // // Just a heuristic to cluster together phi variables, no guarantee it's going to achieve the goal. // return 100 + (1024 * 1024) * m_target.GetVariableKind() + m_target.Number; } //--// // // Access Methods // public VariableExpression Target { get { return m_target; } } public int Version { get { return m_version; } internal set { m_version = value; } } public override CanBeNull CanBeNull { get { return m_target.CanBeNull; } } public override bool CanTakeAddress { get { return m_target.CanTakeAddress; } } public override VariableExpression AliasedVariable { get { return m_target; } } //--// // // Debug Methods // public override void InnerToString( System.Text.StringBuilder sb ) { sb.AppendFormat( "Phi'{0}", m_version ); AppendIdentity( sb ); sb.Append( "<" ); m_target.InnerToString( sb ); sb.Append( ">" ); } } } ================================================ FILE: Zelig/Zelig/CompileTime/CodeGenerator/CodeTransformation/Expressions/PhysicalRegisterExpression.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // namespace Microsoft.Zelig.CodeGeneration.IR { using System; using System.Collections.Generic; using Microsoft.Zelig.Runtime.TypeSystem; public class PhysicalRegisterExpression : LowLevelVariableExpression { // // State // protected Abstractions.RegisterDescriptor m_regDesc; // // Constructor Methods // internal PhysicalRegisterExpression( TypeRepresentation type , Abstractions.RegisterDescriptor regDesc , VariableExpression.DebugInfo debugInfo , VariableExpression sourceVar , uint sourceOffset ) : base( type, debugInfo, sourceVar, sourceOffset ) { m_number = regDesc.Index; m_regDesc = regDesc; } // // Equality Methods // public override bool IsTheSamePhysicalEntity( Expression ex ) { if(base.IsTheSamePhysicalEntity( ex )) { return true; } PhysicalRegisterExpression reg = Extract( ex ); if(reg != null) { if(this.RegisterDescriptor == reg.RegisterDescriptor) { // // Different variables, but they are both assigned to the same physical register. // return true; } } return false; } public override bool IsTheSameAggregate( Expression ex ) { if(base.IsTheSameAggregate( ex )) { return true; } PhysicalRegisterExpression reg = Extract( ex ); if(reg != null) { if(this.RegisterDescriptor == reg.RegisterDescriptor) { // // Different variables, but they are both assigned to the same physical register. // return true; } // // Are they connected by interference? // foreach(var interference in this.RegisterDescriptor.InterfersWith) { if(interference == reg.RegisterDescriptor) { return true; } } foreach(var interference in reg.RegisterDescriptor.InterfersWith) { if(interference == this.RegisterDescriptor) { return true; } } } return false; } public static PhysicalRegisterExpression Extract( Expression ex ) { VariableExpression var = ex as VariableExpression; if(var != null) { return var.AliasedVariable as PhysicalRegisterExpression; } return null; } //--// // // Helper Methods // public override Expression Clone( CloningContext context ) { ControlFlowGraphStateForCodeTransformation cfg = (ControlFlowGraphStateForCodeTransformation)context.ControlFlowGraphDestination; return RegisterAndCloneState( context, cfg.AllocatePhysicalRegister( m_regDesc ) ); } //--// public override void ApplyTransformation( TransformationContextForIR context ) { TransformationContextForCodeTransformation context2 = (TransformationContextForCodeTransformation)context; context2.Push( this ); base.ApplyTransformation( context2 ); context2.Transform( ref m_regDesc ); context2.Pop(); } //--// public override Operator.OperatorLevel GetLevel( Operator.IOperatorLevelHelper helper ) { return Operator.OperatorLevel.Registers; } public override int GetVariableKind() { return c_VariableKind_Physical; } //--// // // Access Methods // public override CanBeNull CanBeNull { get { return CanBeNull.Unknown; } } public override bool CanTakeAddress { get { return false; } } public Abstractions.RegisterDescriptor RegisterDescriptor { get { return m_regDesc; } } //--// // // Debug Methods // public override void InnerToString( System.Text.StringBuilder sb ) { sb.AppendFormat( "$PhyReg__{0}__", m_regDesc.Mnemonic ); base.InnerToString( sb ); AppendOffsetInfo( sb ); } } } ================================================ FILE: Zelig/Zelig/CompileTime/CodeGenerator/CodeTransformation/Expressions/PseudoRegisterExpression.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // namespace Microsoft.Zelig.CodeGeneration.IR { using System; using System.Collections.Generic; using Microsoft.Zelig.Runtime.TypeSystem; public sealed class PseudoRegisterExpression : LowLevelVariableExpression { // // Constructor Methods // internal PseudoRegisterExpression( TypeRepresentation type , DebugInfo debugInfo , VariableExpression sourceVar , uint sourceOffset ) : base( type, debugInfo, sourceVar, sourceOffset ) { } //--// // // Helper Methods // public override Expression Clone( CloningContext context ) { ControlFlowGraphStateForCodeTransformation cfg = (ControlFlowGraphStateForCodeTransformation)context.ControlFlowGraphDestination; TypeRepresentation td = context.ConvertType( m_type ); VariableExpression sourceVar = (VariableExpression)context.Clone( m_sourceVar ); return RegisterAndCloneState( context, cfg.AllocatePseudoRegister( td, m_debugInfo, sourceVar, m_sourceOffset ) ); } //--// public override Operator.OperatorLevel GetLevel( Operator.IOperatorLevelHelper helper ) { return Operator.OperatorLevel.ScalarValues; // Could go to either register or stack. } public override int GetVariableKind() { return c_VariableKind_Pseudo; } //--// // // Access Methods // public override CanBeNull CanBeNull { get { return CanBeNull.Unknown; } } public override bool CanTakeAddress { get { return false; } } //--// // // Debug Methods // public override void InnerToString( System.Text.StringBuilder sb ) { sb.Append( "$PseudoReg_" ); base.InnerToString( sb ); AppendOffsetInfo( sb ); } } } ================================================ FILE: Zelig/Zelig/CompileTime/CodeGenerator/CodeTransformation/Expressions/StackLocationExpression.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // namespace Microsoft.Zelig.CodeGeneration.IR { using System; using System.Collections.Generic; using Microsoft.Zelig.Runtime.TypeSystem; public sealed class StackLocationExpression : LowLevelVariableExpression { public enum Placement { In , Local, Out , } //--// // // State // private Placement m_placement; private uint m_allocationOffset; // // Constructor Methods // internal StackLocationExpression( TypeRepresentation type , VariableExpression.DebugInfo debugInfo , int number , Placement placement , VariableExpression sourceVar , uint sourceOffset ) : base( type, debugInfo, sourceVar, sourceOffset ) { m_number = number; m_placement = placement; m_allocationOffset = uint.MaxValue; } // // Equality Methods // public override bool IsTheSamePhysicalEntity( Expression ex ) { if(base.IsTheSamePhysicalEntity( ex )) { return true; } VariableExpression var = ex as VariableExpression; if(var != null) { StackLocationExpression stack = var.AliasedVariable as StackLocationExpression; if(stack != null) { if(this.m_number == stack.m_number && this.m_placement == stack.m_placement ) { // // Different variables, but they are both assigned to the same stack location. // return true; } } } return false; } public override bool IsTheSameAggregate( Expression ex ) { if(base.IsTheSameAggregate( ex )) { return true; } if(this.SourceVariable != null) { VariableExpression var = ex as VariableExpression; if(var != null) { StackLocationExpression stack = var.AliasedVariable as StackLocationExpression; if(stack != null) { if(this.SourceVariable == stack.SourceVariable) { // // Different variables, but they are both assigned to the same stack location. // return true; } } } } return false; } //--// // // Helper Methods // public override Expression Clone( CloningContext context ) { ControlFlowGraphStateForCodeTransformation cfg = (ControlFlowGraphStateForCodeTransformation)context.ControlFlowGraphDestination; TypeRepresentation td = context.ConvertType( m_type ); VariableExpression sourceVar = (VariableExpression)context.Clone( m_sourceVar ); return RegisterAndCloneState( context, cfg.AllocateStackLocation( td, m_debugInfo, m_number, m_placement, sourceVar, m_sourceOffset ) ); } //--// public override void ApplyTransformation( TransformationContextForIR context ) { TransformationContextForCodeTransformation context2 = (TransformationContextForCodeTransformation)context; context2.Push( this ); base.ApplyTransformation( context2 ); context2.Transform( ref m_placement ); context2.Transform( ref m_allocationOffset ); context2.Pop(); } //--// public override Operator.OperatorLevel GetLevel( Operator.IOperatorLevelHelper helper ) { return Operator.OperatorLevel.StackLocations; } public override int GetVariableKind() { return c_VariableKind_StackLocation + (int)m_placement; } //--// // // Access Methods // public Placement StackPlacement { get { return m_placement; } } public uint AllocationOffset { get { return m_allocationOffset; } set { m_allocationOffset = value; } } // // Debug Methods // public override void InnerToString( System.Text.StringBuilder sb ) { sb.AppendFormat( "$Stack{0}_", this.StackPlacement ); base.InnerToString( sb ); if(m_allocationOffset != uint.MaxValue) { sb.AppendFormat( "[0x{0:X8}]", m_allocationOffset ); } AppendOffsetInfo( sb ); } } } ================================================ FILE: Zelig/Zelig/CompileTime/CodeGenerator/CodeTransformation/Expressions/TypedPhysicalRegisterExpression.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // namespace Microsoft.Zelig.CodeGeneration.IR { using System; using System.Collections.Generic; using Microsoft.Zelig.Runtime.TypeSystem; public sealed class TypedPhysicalRegisterExpression : PhysicalRegisterExpression { // // Constructor Methods // internal TypedPhysicalRegisterExpression( TypeRepresentation type , Abstractions.RegisterDescriptor regDesc , VariableExpression.DebugInfo debugInfo , VariableExpression sourceVar , uint sourceOffset ) : base( type, regDesc, debugInfo, sourceVar, sourceOffset ) { } //--// // // Helper Methods // public override Expression Clone( CloningContext context ) { ControlFlowGraphStateForCodeTransformation cfg = (ControlFlowGraphStateForCodeTransformation)context.ControlFlowGraphDestination; TypeRepresentation td = context.ConvertType( m_type ); VariableExpression sourceVar = (VariableExpression)context.Clone( m_sourceVar ); return RegisterAndCloneState( context, cfg.AllocateTypedPhysicalRegister( td, m_regDesc, m_debugInfo, sourceVar, m_sourceOffset ) ); } //--// public override int GetVariableKind() { return c_VariableKind_Physical; } //--// // // Access Methods // public override CanBeNull CanBeNull { get { return CanBeNull.Unknown; } } //--// // // Debug Methods // } } ================================================ FILE: Zelig/Zelig/CompileTime/CodeGenerator/CodeTransformation/ExternalDataDescriptor.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // namespace Microsoft.Zelig.CodeGeneration.IR { using System; using System.Collections.Generic; using System.Runtime.CompilerServices; using Microsoft.Zelig.Runtime.TypeSystem; public class ExternalDataDescriptor : DataManager.DataDescriptor { public interface IExternalDataContext { byte[] RawData { get; } void WriteData( ImageBuilders.SequentialRegion region ); object DataSection { get; } } private IExternalDataContext m_externContext; internal ExternalDataDescriptor() { } public ExternalDataDescriptor( DataManager owner , IExternalDataContext context , DataManager.Attributes flags , Abstractions.PlacementRequirements pr ) : base( owner, null, flags, pr ) { m_externContext = context; } public IExternalDataContext ExternContext { get { return m_externContext; } } public override object GetDataAtOffset( Runtime.TypeSystem.FieldRepresentation[] accessPath, int accessPathIndex, int offset ) { throw new NotImplementedException(); } internal override void IncludeExtraTypes( Runtime.TypeSystem.TypeSystem.Reachability reachability, CompilationSteps.PhaseDriver phase ) { throw new NotImplementedException(); } internal override void Reduce( GrowOnlySet visited, Runtime.TypeSystem.TypeSystem.Reachability reachability, bool fApply ) { } internal override void RefreshValues( CompilationSteps.PhaseDriver phase ) { } internal override void Write( ImageBuilders.SequentialRegion region ) { m_externContext.WriteData( region ); } protected override string ToString( bool fVerbose ) { return "ExternalDataDescriptor"; } } } ================================================ FILE: Zelig/Zelig/CompileTime/CodeGenerator/CodeTransformation/ExternalMethodImporters/ArmElfContext.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // namespace Microsoft.Zelig.CodeGeneration.IR.ExternalMethodImporters { using System; using System.Collections.Generic; using System.Linq; using System.Text; using Microsoft.Zelig.Elf; using Microsoft.Zelig.CodeGeneration.IR.ImageBuilders; using Microsoft.Zelig.Runtime.TypeSystem; using System.IO; public abstract class ArmElfContext { protected class ArmElfGlobalContext { private ArmElfGlobalContext() { m_symToCallContext = new Dictionary(); m_fileNameToElfObject = new Dictionary(); m_methodToArmElfSection = new Dictionary(); /// /// There can be more than one method (or alias) per ArmElfExternalCallContext with its /// own offset, therefore the following two items can not be combined without creating /// yet another class /// m_methodToElfSectionOffset = new Dictionary(); m_methodToExternalCallCtx = new Dictionary(); /// /// There can be more than one data symbol (or alias) per ArmElfExternalCallContext with /// its own offset, therefore the following two items can not be combined without creating /// yet another class /// m_symbolToGlobalDataOffset = new Dictionary(); m_symbolToGlobalDataCtx = new Dictionary(); m_symbolToArmElfFile = new Dictionary(); m_elfSectionToSeqRegion = new Dictionary(); m_methodNameToMethodDef = new Dictionary(); } public static ArmElfGlobalContext Instance { get { if(s_instance == null) { lock(s_lock) { if(s_instance == null) { s_instance = new ArmElfGlobalContext(); } } } return s_instance; } } public void ResetExternalCalls() { m_symToCallContext.Clear(); } public void ResetState() { m_methodToElfSectionOffset.Clear(); m_symbolToGlobalDataCtx.Clear(); m_symbolToGlobalDataOffset.Clear(); m_methodNameToMethodDef.Clear(); m_elfSectionToSeqRegion.Clear(); } public bool HasExternalMethodContext( string symName ) { return m_symToCallContext.ContainsKey( symName ); } public bool IsManagedCodeSymbol( string symName ) { return m_methodNameToMethodDef.ContainsKey( symName ); } public void RegisterExternalMethodContext( string symName, ArmElfExternalCallContext ctx ) { m_symToCallContext[symName] = ctx; } public object GetCodeForMethod( string methodName, out uint methodOffset ) { methodOffset = 0; if(m_symToCallContext.ContainsKey( methodName )) { ArmElfExternalCallContext ctx = m_symToCallContext[methodName]; if(ctx.ElfSection.Aliases.ContainsKey( methodName )) { methodOffset = ctx.ElfSection.Aliases[methodName]; } return m_symToCallContext[methodName].Owner; } if(m_methodNameToMethodDef.ContainsKey( methodName )) { return m_methodNameToMethodDef[methodName].Code; } return null; } public ExternalDataDescriptor.IExternalDataContext GetExternalDataContext( string symName, SectionReference.SymbolReference symRef, uint opcode, out uint dataOffset ) { ExternalDataDescriptor.IExternalDataContext retVal = null; dataOffset = 0; if(m_elfSectionToSeqRegion.ContainsKey( symRef.Owner.Section )) { Symbol sym = symRef.RelocationRef.ReferencedSymbol; bool hasOffset = false; dataOffset = opcode; foreach(string key in symRef.Owner.Section.Aliases.Keys) { if(key == symName) { dataOffset += symRef.Owner.Section.Aliases[key]; hasOffset = true; break; } } if(!hasOffset) { dataOffset += sym.SymbolDef.st_value; } ExternalDataDescriptor edd = m_elfSectionToSeqRegion[symRef.Owner.Section].Context as ExternalDataDescriptor; retVal = edd.ExternContext; m_symbolToGlobalDataCtx[symName] = retVal as ArmElfExternalDataContext; m_symbolToGlobalDataOffset[symName] = dataOffset; } else if(m_symbolToGlobalDataCtx.ContainsKey( symName )) { dataOffset = m_symbolToGlobalDataOffset[symName]; retVal = m_symbolToGlobalDataCtx[symName]; symRef.Owner.Section = (ElfSection)retVal.DataSection; } return retVal; } public void AddGlobalDataSections( ElfSection[] dataSections, ImageBuilders.Core coreBuilder, ArmElfExternalCallContext owner ) // SequentialRegion region ) { foreach(ElfSection dataSec in dataSections) { if(!m_elfSectionToSeqRegion.ContainsKey( dataSec )) { m_elfSectionToSeqRegion[dataSec] = coreBuilder.AddExternalData( new ArmElfExternalDataContext( dataSec, owner ), dataSec.Header.sh_size ); } } } public bool IsSymbolPlaced( string symbolName, ElfSection section ) { if(m_methodToExternalCallCtx.ContainsKey( symbolName )) return true; if(m_methodNameToMethodDef.ContainsKey( symbolName )) return true; if(m_symbolToGlobalDataCtx.ContainsKey( symbolName )) { ArmElfExternalDataContext ctx = m_symbolToGlobalDataCtx[symbolName]; if(ctx.Section == section) { return true; } } return false; } public void RegisterMethodCall( string methodName, uint sectionOffset, SectionReference sectionRef, ArmElfExternalCallContext ctx ) { m_methodToElfSectionOffset[methodName] = sectionOffset; m_methodToExternalCallCtx[methodName] = ctx; foreach(string alias in sectionRef.Section.Aliases.Keys) { m_methodToElfSectionOffset[alias] = sectionOffset + sectionRef.Section.Aliases[alias]; m_methodToExternalCallCtx[alias] = ctx; } } public ElfSection ParseElfFileForSymbol( string symName, string filePath ) { ElfSection retVal = null; ElfObject[] objs = null; if(m_methodToArmElfSection.ContainsKey( symName )) { return m_methodToArmElfSection[symName]; } string key = Path.GetFullPath( filePath ).ToLower(); if(GlobalContext.m_fileNameToElfObject.ContainsKey( key )) { objs = GlobalContext.m_fileNameToElfObject[key]; } else { objs = ElfObject.FileUtil.Parse( filePath ); GlobalContext.m_fileNameToElfObject[key] = objs; } foreach(ElfObject obj in objs) { foreach(ElfSection sec in obj.Sections) { string name = sec.Name; // Remove this check when the elf parser does a better job distinguishing between sections if(!name.StartsWith( ".rel" ) && !name.StartsWith( ".debug" )) { if(!m_symbolToArmElfFile.ContainsKey( name )) { m_symbolToArmElfFile[name] = filePath.ToLower(); } foreach(string alias in sec.Aliases.Keys) { if(!m_symbolToArmElfFile.ContainsKey( alias )) { m_symbolToArmElfFile[alias] = filePath.ToLower(); } } // add all sections so that we can just do a lookup next time around if(retVal == null) { if(0 == name.CompareTo( symName ) || sec.Aliases.ContainsKey( symName )) { retVal = sec; } } } } } return retVal; } public ElfSection FindExternSymbol( string symName ) { ElfSection retVal = null; if(m_methodNameToMethodDef.ContainsKey( symName )) { return null; } if(m_methodToArmElfSection.ContainsKey( symName )) { return m_methodToArmElfSection[symName]; } if(m_symbolToArmElfFile.ContainsKey( symName )) { retVal = ParseElfFileForSymbol( symName, m_symbolToArmElfFile[symName] ); if(retVal == null) { m_symbolToArmElfFile.Remove( symName ); } } if(retVal == null) { foreach(string file in ExternalCallOperator.NativeImportLibraries) { if(m_symbolToArmElfFile.ContainsValue( file.ToLower() )) continue; string val = file.ToLower(); retVal = ParseElfFileForSymbol( symName, file.ToLower() ); if(retVal != null) break; } } if(retVal == null) { foreach(string dir in ExternalCallOperator.NativeImportDirectories) { if(!Directory.Exists( dir )) continue; foreach(string file in Directory.GetFiles( dir )) { if(m_symbolToArmElfFile.ContainsValue( file.ToLower() )) continue; retVal = ParseElfFileForSymbol( symName, file ); if(retVal != null) break; } if(retVal != null) break; } } if(retVal != null) { m_methodToArmElfSection[symName] = retVal; } return retVal; } public void IntializeExportMethods( TypeSystemForIR typeSystemForIR ) { if(m_methodNameToMethodDef.Count == 0) { List exportedMethods = typeSystemForIR.ExportedMethods; foreach(MethodRepresentation md in exportedMethods) { m_methodNameToMethodDef[md.Name] = md; } } } //--// private Dictionary m_symToCallContext; private Dictionary m_fileNameToElfObject; private Dictionary m_methodToArmElfSection; private Dictionary m_methodToElfSectionOffset; private Dictionary m_methodToExternalCallCtx; private Dictionary m_symbolToGlobalDataOffset; private Dictionary m_symbolToGlobalDataCtx; private Dictionary m_symbolToArmElfFile; private Dictionary m_elfSectionToSeqRegion; private Dictionary m_methodNameToMethodDef; private static object s_lock = new object(); private static ArmElfGlobalContext s_instance; } protected static ArmElfGlobalContext GlobalContext { get { return ArmElfGlobalContext.Instance; } } } } ================================================ FILE: Zelig/Zelig/CompileTime/CodeGenerator/CodeTransformation/ExternalMethodImporters/ArmElfDataContext.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // namespace Microsoft.Zelig.CodeGeneration.IR.ExternalMethodImporters { using System; using System.Collections.Generic; using System.Linq; using System.Text; using Microsoft.Zelig.Elf; using Microsoft.Zelig.CodeGeneration.IR.ImageBuilders; using Microsoft.Zelig.Runtime.TypeSystem; public class ArmElfExternalDataContext : ArmElfContext, ExternalDataDescriptor.IExternalDataContext { ElfSection m_dataSec; ArmElfExternalCallContext m_owner; public ArmElfExternalDataContext( ElfSection dataSec, ArmElfExternalCallContext owner ) { m_dataSec = dataSec; m_owner = owner; } public byte[] RawData { get { return m_dataSec.Raw; } } public object DataSection { get { return m_dataSec; } } internal ElfSection Section { get { return m_dataSec; } } public void WriteData( ImageBuilders.SequentialRegion region ) { uint len = (uint)m_dataSec.Raw.Length; ImageBuilders.SequentialRegion.Section sec = region.GetSectionOfFixedSize( len ); uint offset = region.PointerOffset; sec.Write( m_dataSec.Raw ); foreach(SectionReference sr in m_dataSec.References) { foreach(SectionReference.SymbolReference symRef in sr.CallOffsets) { uint callOffset = symRef.Offset; SymbolType st = symRef.RelocationRef.ReferencedSymbol.Type; SymbolBinding sb = symRef.RelocationRef.ReferencedSymbol.Binding; string symName = symRef.RelocationRef.ReferencedSymbol.Name; uint opcode = BitConverter.ToUInt32( m_dataSec.Raw, (int)symRef.Offset ); if(st == SymbolType.STT_FUNC || st == SymbolType.STT_NOTYPE) { uint dataOffset; object target = ArmElfExternalCallContext.GetCodeForMethod( symName, out dataOffset ); if(target != null) { new ExternalPointerRelocation( region, offset + callOffset, dataOffset, target ); } else { Console.WriteLine( "UNABLE TO FIND EXTERNAL REFERENCE " + symName ); } } else if(st == SymbolType.STT_OBJECT || st == SymbolType.STT_SECTION) { uint dataOffset; ExternalDataDescriptor.IExternalDataContext ctx = GlobalContext.GetExternalDataContext( symName, symRef, opcode, out dataOffset ); if(ctx != null) { new ExternalPointerRelocation( region, offset + callOffset, dataOffset, ctx ); } else { Console.WriteLine( "ERROR: Unable to find symbol: " + symName ); } } else { Console.WriteLine( "ERROR: UNKNOWN DATA REFERENCE TYPE: " + st.ToString() ); } } } } } } ================================================ FILE: Zelig/Zelig/CompileTime/CodeGenerator/CodeTransformation/ExternalMethodImporters/ArmElfMethodContext.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // namespace Microsoft.Zelig.CodeGeneration.IR.ExternalMethodImporters { using System; using System.Collections.Generic; using Microsoft.Zelig.Elf; using Microsoft.Zelig.CodeGeneration.IR.ImageBuilders; using Microsoft.Zelig.CodeGeneration.IR.Abstractions; using System.IO; using Microsoft.Zelig.TargetModel.ArmProcessor; /// /// /// public class ArmElfExternalCallContext : ArmElfContext, ExternalCallOperator.IExternalCallContext { private static InstructionSet s_iset; //--// private readonly string m_methodName; private readonly string m_filePath; private Operator m_owner; private readonly ElfSection m_elfSection; private Debugging.DebugInfo m_dbgInfo; private uint m_offset; public Operator Owner { get { return m_owner; } set { m_owner = value; } } internal ElfSection ElfSection { get { return m_elfSection; } } public uint OperatorOffset { get { return m_offset; } } public static void Initialize(TypeSystemForCodeTransformation typeSystem) { s_iset = typeSystem.PlatformAbstraction.GetInstructionSetProvider(); ElfObject.SystemArchitecture arch = ElfObject.SystemArchitecture.ArmV5; ElfObject.FloatingPointUnit fpu = ElfObject.FloatingPointUnit.None; ElfObject.Endian endian = ElfObject.Endian.Little; switch(typeSystem.PlatformAbstraction.PlatformVersion) { case InstructionSetVersion.Platform_Version__ARMv4: arch = ElfObject.SystemArchitecture.ArmV4; break; case InstructionSetVersion.Platform_Version__ARMv5: arch = ElfObject.SystemArchitecture.ArmV5; break; case InstructionSetVersion.Platform_Version__ARMv6M: arch = ElfObject.SystemArchitecture.Thumb1; break; case InstructionSetVersion.Platform_Version__ARMv7M: arch = ElfObject.SystemArchitecture.Thumb2; break; default: throw new ArgumentException("Unknown or unsupported platform version"); } switch(typeSystem.PlatformAbstraction.PlatformVFP) { case InstructionSetVersion.Platform_VFP__NoVFP: fpu = ElfObject.FloatingPointUnit.None; break; case InstructionSetVersion.Platform_VFP__SoftVFP: fpu = ElfObject.FloatingPointUnit.SoftVFP; break; case InstructionSetVersion.Platform_VFP__HardVFP: fpu = ElfObject.FloatingPointUnit.VFP; break; default: throw new ArgumentException("Unknown or unsupported FP mode"); } if(typeSystem.PlatformAbstraction.PlatformBigEndian) { endian = ElfObject.Endian.Big; } ElfObject.FileUtil.DeviceConfiguration = new ElfObject.RvctDeviceType( arch, fpu, endian ); GlobalContext.ResetState(); } public static void Reset() { GlobalContext.ResetState(); } public static void ResetExternCalls() { GlobalContext.ResetExternalCalls(); } private ArmElfExternalCallContext( string methodName, ElfSection section ) { m_methodName = methodName; m_filePath = section.Parent.FileName; m_owner = null; m_elfSection = section; } public static object GetCodeForMethod( string methodName, out uint methodOffset ) { return GlobalContext.GetCodeForMethod( methodName, out methodOffset ); } private static ElfSection FindElfSection( string filePath, string symName ) { ElfSection elfSection = GlobalContext.ParseElfFileForSymbol( symName, filePath ); if(elfSection == null) { elfSection = GlobalContext.FindExternSymbol( symName ); } return elfSection; } public static ArmElfExternalCallContext[] Load( string filePath, string methodName, BasicBlock owner ) { ArmElfExternalCallContext item = null; Queue queue = new Queue(); List lst = new List(); HashSet dataSymLookup = new HashSet(); ElfSection section; GlobalContext.IntializeExportMethods( owner.Owner.TypeSystemForIR ); string path = Path.GetFullPath( filePath ).ToLower(); section = FindElfSection( path, methodName ); if(section != null) { lst.Add( item = new ArmElfExternalCallContext( methodName, section ) ); GlobalContext.RegisterExternalMethodContext( section.Name, item ); foreach(string alias in item.m_elfSection.Aliases.Keys) { GlobalContext.RegisterExternalMethodContext( alias, item ); } Console.WriteLine( "{0,-30}: {1}", Path.GetFileName(section.Parent.FileName), methodName ); queue.Enqueue( item ); while(queue.Count > 0) { item = queue.Dequeue(); foreach(SectionReference sr in item.m_elfSection.References) { string symName = sr.SectionName; if(!GlobalContext.HasExternalMethodContext( symName ) && !GlobalContext.IsManagedCodeSymbol( symName ) && !dataSymLookup.Contains( symName )) { section = FindElfSection( sr.Section.Parent.FileName, symName ); if(section == null) continue; ArmElfExternalCallContext tmp = new ArmElfExternalCallContext( symName, section ); if(!tmp.m_elfSection.IsDataSection) { lst.Add( tmp ); } queue.Enqueue( tmp ); if(!tmp.m_elfSection.IsDataSection) { GlobalContext.RegisterExternalMethodContext( tmp.m_elfSection.Name, tmp ); foreach(string alias in tmp.m_elfSection.Aliases.Keys) { GlobalContext.RegisterExternalMethodContext( alias, tmp ); } Console.WriteLine( "{0,-30}: {1}", Path.GetFileName(section.Parent.FileName), symName ); } else { dataSymLookup.Add( tmp.m_methodName ); } } } } } return lst.ToArray(); } public Debugging.DebugInfo DebugInfo { get { if(m_dbgInfo == null) { if(m_elfSection.DebugEntries.Count > 0) { DebugInfoEntry die = m_elfSection.DebugEntries[0]; if(die.m_lines.Count > 0) { DebugLineEntry dle = die.m_lines[0]; if(dle.m_files.Count > 0) { object arg; int startLine = 1; int startCol = 1; if(dle.m_opcode.Count >= 3) { // opcode 2 is the start line arg = dle.m_opcode[2].Arg; if(arg is uint) { startLine = (int)(uint)arg; } else if(arg is int) { startLine = (int)arg; } // opcode 1 is the start column arg = dle.m_opcode[1].Arg; if(arg is uint) { startCol = (int)(uint)arg; } else if(arg is int) { startCol = (int)arg; } } else { // TODO: find a way to include macros with no line number opcodes return null; } string file = dle.m_files[0].m_name; if(dle.m_includeDirs.Count > 0) { if(!File.Exists( file )) { foreach(string dir in dle.m_includeDirs) { if(File.Exists( dir + file )) { file = dir + file; break; } } } } m_dbgInfo = new Debugging.DebugInfo( file, m_elfSection.Name, startLine, startCol, startLine + 1, startCol + 1 ); } } } } return m_dbgInfo; } } public void UpdateRelocation( object relocation ) { ImageBuilders.CodeRelocation reloc = (ImageBuilders.CodeRelocation)relocation; m_elfSection.AddressInMemory = reloc.InsertionAddress; } public void AddExternalData( ImageBuilders.Core coreBuilder, ElfSection[] dataSections ) { GlobalContext.AddGlobalDataSections( dataSections, coreBuilder, this ); } public void AddExternalData( ImageBuilders.Core coreBuilder, SectionReference sr ) { if(sr == null) return; if(!string.IsNullOrEmpty( sr.Section.Name )) { AddExternalData( coreBuilder, sr.Section.Parent.DataEntries ); } else { ElfSection ownerSection = GlobalContext.FindExternSymbol( sr.SectionName ); if(ownerSection != null) { AddExternalData( coreBuilder, ownerSection.Parent.DataEntries ); sr.Section = ownerSection; } } } public bool PerformCodeLinkage( object region, object section, object core ) { try { ImageBuilders.Core coreBuilder = core as ImageBuilders.Core; SequentialRegion sqr = (SequentialRegion)region; SequentialRegion.Section sec = (SequentialRegion.Section)section; Dictionary sectionPlacementMap = new Dictionary(); GlobalContext.IntializeExportMethods( m_owner.BasicBlock.Owner.TypeSystemForIR ); AddExternalData( coreBuilder, m_elfSection.Parent.DataEntries ); sec.AlignToWord(); m_offset = sec.Offset; sec.Write( m_elfSection.Raw ); sec.AlignToWord(); sectionPlacementMap[m_elfSection] = 0; foreach(SectionReference sr in m_elfSection.References) { AddExternalData( coreBuilder, sr ); ParseReferences( sqr, m_offset, sr, sectionPlacementMap ); } } catch { Console.WriteLine( "ERROR" ); return false; } return true; } private void ParseReferences( SequentialRegion sqr, uint sectionBaseAddr, SectionReference sr, Dictionary secPlacementMap ) { foreach(SectionReference.SymbolReference symRef in sr.CallOffsets) { uint callOffset = symRef.Offset; uint op = BitConverter.ToUInt32( m_elfSection.Raw, (int)callOffset ); InstructionSet.Opcode opcode = s_iset.Decode( op ); RelocationEntry reloc = symRef.RelocationRef; Symbol sym = reloc.ReferencedSymbol; SymbolType st = sym.Type; SymbolBinding sb = sym.Binding; string symName = sym.Name; callOffset += sectionBaseAddr; if(st == SymbolType.STT_FUNC || st == SymbolType.STT_NOTYPE) { if(opcode is InstructionSet.Opcode_Branch) { uint methodOffset; object target = GlobalContext.GetCodeForMethod( symName, out methodOffset ); if(target != null) { switch(reloc.Type) { case RelocationType.R_ARM_JUMP24: case RelocationType.R_ARM_CALL: new ExternMethodCallRelocation( sqr, callOffset, UpdateExternalMethodCall, methodOffset, target, EncodingDefinition.c_PC_offset ); break; default: Console.WriteLine( "NOT IMPLEMENTED: relocation type: " + reloc.Type.ToString() ); throw new InvalidOperationException( "ERROR: Unhandled relocation type: " + reloc.Type.ToString() ); } } else { Console.WriteLine( "UNABLE TO FIND EXTERNAL CALL REFERENCE " + symName ); } } else if(opcode is InstructionSet.Opcode_DataProcessing_2) { uint dataOffset = 0; object ctx = GlobalContext.GetExternalDataContext( symName, symRef, op, out dataOffset ); if(ctx == null) { ctx = GlobalContext.GetCodeForMethod( symName, out dataOffset ); } if(ctx != null) { switch(reloc.Type) { case RelocationType.R_ARM_ABS32: new ExternalPointerRelocation( sqr, callOffset, dataOffset, ctx ); break; default: Console.WriteLine( "NOT IMPLEMENTED: relocation type: " + reloc.Type.ToString() ); throw new InvalidOperationException( "ERROR: Unhandled relocation type: " + reloc.Type.ToString() ); } } else { Console.WriteLine( "UNABLE TO FIND EXTERNAL DATA REFERENCE " + symName ); } } else { Console.WriteLine( "NOT IMPLEMENTED: " + opcode.ToString() ); } } else if(st == SymbolType.STT_SECTION || st == SymbolType.STT_OBJECT) { uint dataOffset; ExternalDataDescriptor.IExternalDataContext ctx = GlobalContext.GetExternalDataContext( symName, symRef, op, out dataOffset ); if(ctx != null) { switch(reloc.Type) { case RelocationType.R_ARM_ABS32: new ExternalPointerRelocation( sqr, callOffset, dataOffset, ctx ); break; default: Console.WriteLine( "NOT IMPLEMENTED: relocation type: " + reloc.Type.ToString() ); throw new InvalidOperationException( "ERROR: Unhandled relocation type: " + reloc.Type.ToString() ); } } else { Console.WriteLine( "ERROR: Unable to find symbol: " + symName ); } } else { Console.WriteLine( "NOT IMPLEMENTED: " + st.ToString() ); } } } private uint UpdateExternalMethodCall( uint opcode, uint callerAddress, uint calleeAddress ) { InstructionSet.Opcode op = s_iset.Decode( opcode ); if(op is InstructionSet.Opcode_Branch) { InstructionSet.Opcode_Branch branch = (InstructionSet.Opcode_Branch)op; branch.Prepare( branch.ConditionCodes, (int)calleeAddress - EncodingDefinition.c_PC_offset - (int)callerAddress, branch.IsLink ); return branch.Encode(); } else { Console.WriteLine( "ERROR: UNEXPECTED OPCODE!!!!" ); } return opcode; } } } ================================================ FILE: Zelig/Zelig/CompileTime/CodeGenerator/CodeTransformation/ImageBuilders/CodeConstant.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // namespace Microsoft.Zelig.CodeGeneration.IR.ImageBuilders { using System; using System.Collections.Generic; using Microsoft.Zelig.Runtime.TypeSystem; using Microsoft.Zelig.TargetModel.ArmProcessor; public class CodeConstant { public static readonly CodeConstant[] SharedEmptyArray = new CodeConstant[0]; // // State // ImageAnnotation m_source; object m_target; SequentialRegion m_region; // // Constructor Methods // internal CodeConstant( object target ) { m_target = target; } // // Helper Methods // public void ApplyTransformation( TransformationContextForCodeTransformation context ) { context.Push( this ); context.Transform( ref m_source ); context.Transform( ref m_target ); context.Transform( ref m_region ); context.Pop(); } // // Access Methods // public ImageAnnotation Source { get { return m_source; } set { m_source = value; } } public object Target { get { return m_target; } } public SequentialRegion Region { get { return m_region; } set { m_region = value; } } // // Debug Methods // public override string ToString() { return string.Format( "Pointer to {0}", m_target ); } } } ================================================ FILE: Zelig/Zelig/CompileTime/CodeGenerator/CodeTransformation/ImageBuilders/CompilationState.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // namespace Microsoft.Zelig.CodeGeneration.IR.ImageBuilders { using System; using System.Collections.Generic; using Microsoft.Zelig.Runtime.TypeSystem; using Microsoft.Zelig.TargetModel.ArmProcessor; public abstract partial class CompilationState : IDisposable { protected class StateForLocalStackAssignment { // // State // internal StackLocationExpression m_var; internal BitVector m_liveness = new BitVector(); internal BitVector m_interferesWith = new BitVector(); internal BitVector m_sharesSourceVariableWith = new BitVector(); internal BitVector m_sharesOffsetOfSourceVariableWith = new BitVector(); internal uint m_offset; // // Constructor Methods // internal StateForLocalStackAssignment( StackLocationExpression var ) { m_var = var; m_offset = uint.MaxValue; } // // Helper Methods // internal void SetLiveness( BitVector[] livenessMap , BitVector[] defVectors , VariableExpression.Property[] properties , Operator[] operators ) { int varIdx = m_var.SpanningTreeIndex; // // TODO: Once we have proper pointer analysis, we could weaken the check. // For now, we just don't want to have this variable aliased. // if((properties[varIdx] & VariableExpression.Property.AddressTaken) != 0) { m_liveness.SetRange( 0, operators.Length ); } else { m_liveness.OrInPlace( livenessMap[varIdx] ); // // We also include all the operators that follow a definition of the stack location, // because a dead assignment won't appear in the liveness map but it does change the state of the stack. // foreach(int defIdx in defVectors[varIdx]) { m_liveness.Set( defIdx + 1 ); } } } //--// internal static void Correlate( List< StateForLocalStackAssignment > states ) { for(int stateIdx = 0; stateIdx < states.Count; stateIdx++) { StateForLocalStackAssignment state = states[stateIdx]; VariableExpression srcVar = state.m_var.SourceVariable; uint srcOffset = state.m_var.SourceOffset; state.m_sharesSourceVariableWith .Set( stateIdx ); state.m_sharesOffsetOfSourceVariableWith.Set( stateIdx ); for(int stateIdx2 = stateIdx + 1; stateIdx2 < states.Count; stateIdx2++) { StateForLocalStackAssignment state2 = states[stateIdx2]; VariableExpression srcVar2 = state2.m_var.SourceVariable; uint srcOffset2 = state2.m_var.SourceOffset; if(state.m_liveness.IsIntersectionEmpty( state2.m_liveness ) == false) { state .m_interferesWith.Set( stateIdx2 ); state2.m_interferesWith.Set( stateIdx ); } if(srcVar == srcVar2) { state .m_sharesSourceVariableWith.Set( stateIdx2 ); state2.m_sharesSourceVariableWith.Set( stateIdx ); if(srcOffset == srcOffset2) { state .m_sharesOffsetOfSourceVariableWith.Set( stateIdx2 ); state2.m_sharesOffsetOfSourceVariableWith.Set( stateIdx ); } } } } } public static uint ComputeLayout( List< StateForLocalStackAssignment > states ) { BitVector[] offsetsUsage = BitVector.SharedEmptyArray; for(int stateIdx = 0; stateIdx < states.Count; stateIdx++) { StateForLocalStackAssignment state = states[stateIdx]; if(state.m_offset == uint.MaxValue) { VariableExpression srcVar = state.m_var.AggregateVariable; uint size = srcVar.Type.SizeOfHoldingVariableInWords; BitVector liveness; if(size == 1) { CHECKS.ASSERT( state.m_var.SourceOffset == 0, "Mismatch between SourceOffset and Size of object" ); // // Simple case, we don't have to worry about keeping the various fields in the same order. // liveness = state.m_liveness; if(liveness.Cardinality > 0) { uint offset = 0; while(IsOffsetAvailable( ref offsetsUsage, liveness, offset, 1 ) == false) { offset++; } MarkOffsetAsUsed( offsetsUsage, liveness, offset, 1 ); state.m_var.AllocationOffset = offset * sizeof(uint); state.m_offset = offset; } else { state.m_var.Number = int.MaxValue; state.m_offset = uint.MaxValue - 1; } } else { // // Complex case, we have to ensure that the various fields are kept in the same order. // // // Compute the liveness for the whole object. // liveness = new BitVector(); foreach(int stateIdx2 in state.m_sharesSourceVariableWith) { StateForLocalStackAssignment state2 = states[stateIdx2]; liveness.OrInPlace( state2.m_liveness ); } if(liveness.Cardinality > 0) { uint offset = 0; while(IsOffsetAvailable( ref offsetsUsage, liveness, offset, size ) == false) { offset++; } MarkOffsetAsUsed( offsetsUsage, liveness, offset, size ); foreach(int stateIdx2 in state.m_sharesSourceVariableWith) { StateForLocalStackAssignment state2 = states[stateIdx2]; // // If there are multiple variables mapping to the same field, their liveness should be disjoined. // foreach(int stateIdx3 in state2.m_interferesWith) { if(state2.m_sharesOffsetOfSourceVariableWith[ stateIdx3 ]) { throw TypeConsistencyErrorException.Create( "Unsupported scenario: multiple variables mapping to the same field of the same stack variable are alive at the same time: {0} {1}", state2.m_var, states[stateIdx3].m_var ); } } state2.m_var.AllocationOffset = offset * sizeof(uint) + state2.m_var.SourceOffset; state2.m_offset = offset; } } else { foreach(int stateIdx2 in state.m_sharesSourceVariableWith) { StateForLocalStackAssignment state2 = states[stateIdx2]; state2.m_var.Number = int.MaxValue; state2.m_offset = uint.MaxValue - 1; } } } } } return (uint)offsetsUsage.Length; } //--// private static bool IsOffsetAvailable( ref BitVector[] offsetsUsage , BitVector liveness , uint offset , uint size ) { while(size > 0) { offsetsUsage = ArrayUtility.EnsureSizeOfNotNullArray( offsetsUsage, (int)(offset + 1) ); BitVector vec = offsetsUsage[offset]; if(vec != null && vec.IsIntersectionEmpty( liveness ) == false) { return false; } offset++; size--; } return true; } private static void MarkOffsetAsUsed( BitVector[] offsetsUsage , BitVector liveness , uint offset , uint size ) { while(size > 0) { BitVector vec = offsetsUsage[offset]; if(vec == null) { offsetsUsage[offset] = liveness.Clone(); } else { vec.OrInPlace( liveness ); } offset++; size--; } } } // // State // protected Core m_owner; protected ControlFlowGraphStateForCodeTransformation m_cfg; protected List< SequentialRegion > m_associatedRegions; protected SequentialRegion[] m_basicBlockToRegions; // // Cached values, not persisted. // private IDisposable m_cfgLock; protected BasicBlock[] m_basicBlocks; protected BasicBlock[] m_immediateDominators; protected Operator[] m_operators; protected VariableExpression[] m_variables; protected BitVector[] m_livenessAtBasicBlockEntry; // It's indexed as [][] protected BitVector[] m_livenessAtBasicBlockExit; // It's indexed as [][] protected BitVector[] m_livenessAtOperator; // It's indexed as [][] protected DataFlow.ControlTree.NaturalLoops m_naturalLoops; private List< Slot > m_topLevelSlots; private AtomicSlot[] m_schedulingLookup; private AtomicSlot[] m_schedulingLoopExits; private BitVector m_vecColdCode; private BitVector m_vecZeroLengthCandidates; private BitVector m_vecReachableFromColdCode; private BitVector m_vecReachableFromEntry; // // Constructor Methods // protected CompilationState() // Default constructor required by TypeSystemSerializer. { m_associatedRegions = new List< SequentialRegion >(); } protected CompilationState( Core owner , ControlFlowGraphStateForCodeTransformation cfg ) : this() { m_owner = owner; m_cfg = cfg; } // // Helper Methods // public virtual void ApplyTransformation( TransformationContextForCodeTransformation context ) { context.Push( this ); context.TransformGeneric( ref m_owner ); context.TransformGeneric( ref m_cfg ); context.Transform ( ref m_associatedRegions ); context.Transform ( ref m_basicBlockToRegions ); context.Pop(); } //--// internal protected int CompareSchedulingWeights( BasicBlock left , BasicBlock right ) { var slotLeft = GetSchedulingSlot( left ); var slotRight = GetSchedulingSlot( right ); return slotLeft.Weight.CompareTo( slotRight.Weight ); } internal protected bool AreBasicBlocksAdjacent( BasicBlock pre , BasicBlock post ) { var slotPre = GetSchedulingSlot( pre ); var slotPost = GetSchedulingSlot( post ); if(IsZeroLengthCandidate( pre )) { return slotPre.SchedulingIndex == slotPost.SchedulingIndex; } return slotPre.SchedulingIndex + 1 == slotPost.SchedulingIndex; } //--// internal void CompileMethod() { PrepareDataStructures(); AssignStackLocations( ); AllocateBasicBlockRegions( ); CollectSchedulingPreferences( ); PropagateColdCodeHints( ); AllocateSchedulingSlots( ); OrderBasicBlocks( ); AssignSchedulingIndex( ); EmitCodeForBasicBlocks(); } //--// protected virtual void PrepareDataStructures() { m_cfgLock = m_cfg.GroupLock( m_cfg.LockSpanningTree() , m_cfg.LockDominance () , m_cfg.LockLiveness () ); m_basicBlocks = m_cfg.DataFlow_SpanningTree_BasicBlocks; m_immediateDominators = m_cfg.DataFlow_ImmediateDominators; m_operators = m_cfg.DataFlow_SpanningTree_Operators; m_variables = m_cfg.DataFlow_SpanningTree_Variables; // // We need to build a slightly different liveness information: Stack Locations should be tracked as aggregates and not invalidated by method calls. // var liveness = DataFlow.LivenessAnalysis.Compute( m_cfg, true ); m_livenessAtBasicBlockEntry = liveness.LivenessAtBasicBlockEntry; m_livenessAtBasicBlockExit = liveness.LivenessAtBasicBlockExit; m_livenessAtOperator = liveness.LivenessAtOperator; //// if(m_cfg.ToString() == sDebugTarget) //// { //// } m_naturalLoops = DataFlow.ControlTree.NaturalLoops.Execute( m_cfg ); //--// int bbNum = m_basicBlocks.Length; m_basicBlockToRegions = new SequentialRegion[bbNum]; m_topLevelSlots = new List< Slot >(); m_schedulingLookup = new AtomicSlot[bbNum]; m_vecColdCode = new BitVector( bbNum ); m_vecZeroLengthCandidates = new BitVector( bbNum ); m_vecReachableFromColdCode = new BitVector( bbNum ); m_vecReachableFromEntry = new BitVector( bbNum ); //--// // // Sort loops from the deep to the shallow. // m_naturalLoops.Loops.Sort( (x, y) => y.Depth.CompareTo( x.Depth ) ); } private void AllocateBasicBlockRegions() { foreach(BasicBlock bb in m_basicBlocks) { SequentialRegion reg = new SequentialRegion( m_owner, bb, m_owner.TypeSystem.PlatformAbstraction.GetMemoryRequirements( bb ) ); m_basicBlockToRegions[bb.SpanningTreeIndex] = reg; TrackRegion( reg ); } } //--// private void PropagateColdCodeHints() { // // Try to maximize the number of basic blocks that are cold, making sure that a block becomes cold if it's dominated by a cold block. // foreach(BasicBlock bb in m_basicBlocks) { if(bb is EntryBasicBlock) { PropagateReachableFromEntry( bb.SpanningTreeIndex ); } if(IsColdCode( bb )) { PropagateReachableFromColdCode( bb.SpanningTreeIndex ); } } } private void PropagateReachableFromEntry( int bbIdx ) { if(m_vecReachableFromEntry.Set( bbIdx )) { foreach(BasicBlockEdge edge in m_basicBlocks[bbIdx].Successors) { BasicBlock bbNext = edge.Successor; if(IsColdCode( bbNext )) { continue; } PropagateReachableFromEntry( bbNext.SpanningTreeIndex ); } } } private void PropagateReachableFromColdCode( int bbIdx ) { if(m_vecReachableFromColdCode.Set( bbIdx )) { foreach(BasicBlockEdge edge in m_basicBlocks[bbIdx].Successors) { BasicBlock bbNext = edge.Successor; int bbNextIdx = bbNext.SpanningTreeIndex; PropagateReachableFromColdCode( bbNextIdx ); } } } //--// public void Dispose() { if(m_cfgLock != null) { if(m_naturalLoops != null) { m_naturalLoops.Dispose(); m_naturalLoops = null; } m_cfgLock.Dispose(); m_cfgLock = null; } } public void ReleaseAllLocks() { if(m_cfgLock != null) { m_cfgLock.Dispose(); m_cfgLock = null; } } //--// private void AssignStackLocations() { if(m_cfg.Method.HasBuildTimeFlag( MethodRepresentation.BuildTimeAttributes.StackNotAvailable ) == false) { VariableExpression.Property[] properties = m_cfg.DataFlow_PropertiesOfVariables; BitVector[] livenessMap = m_cfg.DataFlow_VariableLivenessMap; // It's indexed as [][] BitVector[] defVectors = m_cfg.DataFlow_BitVectorsForDefinitionChains; int varsNum = m_variables.Length; List< StateForLocalStackAssignment > states = new List< StateForLocalStackAssignment >(); for(int varIdx = 0; varIdx < varsNum; varIdx++) { VariableExpression var = m_variables[varIdx]; PhysicalRegisterExpression regVar = var as PhysicalRegisterExpression; if(regVar != null) { AssignStackLocations_RecordRegister( regVar ); } StackLocationExpression stackVar = var as StackLocationExpression; if(stackVar != null) { if(stackVar.StackPlacement == StackLocationExpression.Placement.Local) { StateForLocalStackAssignment state = new StateForLocalStackAssignment( stackVar ); // // Try to minimize the amount of stack required, using the lifetime information // to carve a slice of the stack just for the amount of time we need to keep the object around. // state.SetLiveness( livenessMap, defVectors, properties, m_operators ); states.Add( state ); } else if(stackVar.StackPlacement == StackLocationExpression.Placement.Out) { AssignStackLocations_RecordStackOut( stackVar ); } } } StateForLocalStackAssignment.Correlate( states ); AssignStackLocations_RecordStackLocal( states ); //--// AssignStackLocations_Finalize(); } } protected abstract void AssignStackLocations_RecordRegister( PhysicalRegisterExpression regVar ); protected abstract void AssignStackLocations_RecordStackOut( StackLocationExpression stackVar ); protected abstract void AssignStackLocations_RecordStackLocal( List< StateForLocalStackAssignment > states ); protected abstract void AssignStackLocations_Finalize(); //--// protected abstract void FixupEmptyRegion( SequentialRegion reg ); //--// public abstract bool CreateCodeMaps(); //--// internal void TrackRegion( SequentialRegion reg ) { m_associatedRegions.Add( reg ); } //--// protected SequentialRegion[] GetSortedCodeRegions() { SequentialRegion[] regArray = ArrayUtility.CopyNotNullArray( m_basicBlockToRegions ); Core.SortRegions( regArray ); return regArray; } // // Access Methods // public Core Owner { get { return m_owner; } } public SequentialRegion[] BasicBlockRegions { get { return m_basicBlockToRegions; } } internal List< SequentialRegion > AssociatedRegions { get { return m_associatedRegions; } } } } ================================================ FILE: Zelig/Zelig/CompileTime/CodeGenerator/CodeTransformation/ImageBuilders/CompilationState_EmitCode.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // namespace Microsoft.Zelig.CodeGeneration.IR.ImageBuilders { using System; using System.Collections.Generic; using Microsoft.Zelig.TargetModel.ArmProcessor; public partial class CompilationState { // // State // // // Constructor Methods // // // Helper Methods // private void EmitCodeForBasicBlocks() { var isProcessed = new BitVector( m_basicBlocks.Length ); var pending = new Stack( m_basicBlocks.Length ); foreach(BasicBlock block in m_basicBlocks) { pending.Push( block ); } // Emit blocks in dominance order. while(pending.Count > 0) { BasicBlock block = pending.Pop(); // Skip dead and already-processed blocks. if((block.SpanningTreeIndex == -1) || isProcessed[block.SpanningTreeIndex]) { continue; } // If the block's immediate dominator hasn't been processed, process it first. BasicBlock idom = m_immediateDominators[block.SpanningTreeIndex]; if((idom != block) && !isProcessed[idom.SpanningTreeIndex]) { pending.Push( block ); pending.Push( idom ); continue; } EmitCodeForBasicBlock(block); isProcessed[block.SpanningTreeIndex] = true; } FlushUnfinishedBlocks(); } public virtual void EmitCodeForBasicBlock( BasicBlock bb ) { m_activeCodeRegion = GetRegion( bb ); m_activeCodeSection = m_activeCodeRegion.GetSectionOfVariableSize( sizeof(uint) ); m_activeHardwareException = m_owner.TypeSystem.ExtractHardwareExceptionSettingsForMethod( bb.Owner.Method ); //--// TypeSystemForCodeTransformation ts = m_cfg.TypeSystem; Abstractions.Platform pa = ts.PlatformAbstraction; Abstractions.CallingConvention cc = ts.CallingConvention; // // We want to track the exact liveness state of all the variables. // // To do that, we first emit tracking info for all the variables alive on entry to a basic block. // BitVector aliveHistory = m_livenessAtBasicBlockEntry[bb.SpanningTreeIndex].Clone(); for(int idx = 0; idx < m_variables.Length; idx++) { if(aliveHistory[idx] == true) { TrackVariable( m_variables[idx], true ); } } m_fStopProcessingOperatorsForCurrentBasicBlock = false; foreach(Operator op in bb.Operators) { // // See which pointers are generated or killed. // UpdateLivenessInfo( aliveHistory, m_livenessAtOperator[op.SpanningTreeIndex] ); //--// if(EmitCodeForBasicBlock_ShouldSkip( op )) { continue; } EmitCodeForBasicBlock_EmitOperator( op ); if(m_fStopProcessingOperatorsForCurrentBasicBlock) { break; } } EmitCodeForBasicBlock_FlushOperators(); UpdateLivenessInfo( aliveHistory, m_livenessAtBasicBlockExit[bb.SpanningTreeIndex] ); //--// m_activeCodeRegion = null; m_activeCodeSection = null; } public virtual void FlushUnfinishedBlocks( ) { } protected virtual bool EmitCodeForBasicBlock_ShouldSkip( Operator op ) { // // Skip any meta-operators. // if(op.IsMetaOperator && !(op is InitialValueOperator)) { return true; } return false; } protected abstract uint EmitCodeForBasicBlock_EstimateMinimumSize( Operator op ); protected abstract void EmitCodeForBasicBlock_EmitOperator( Operator op ); protected abstract void EmitCodeForBasicBlock_FlushOperators(); //--// private void UpdateLivenessInfo( BitVector aliveHistory , BitVector alive ) { aliveHistory.XorInPlace( alive ); // // Now 'aliveHistory' contains the set of variables that changed liveness status. // // We do two passes, first track the variables that went dead, then the ones that became alive. // The reason for this is that multiple variables map to the same physical register, // it's normal for a register to die and be born on the same instruction. // The end result should be a register that is still alive. // We'll compress the table later, when we switch from variables to actual storage places. // foreach(int idx in aliveHistory) { if(alive[idx] == false) { TrackVariable( m_variables[idx], false ); } } foreach(int idx in aliveHistory) { if(alive[idx] == true) { TrackVariable( m_variables[idx], true ); } } aliveHistory.Assign( alive ); } } } ================================================ FILE: Zelig/Zelig/CompileTime/CodeGenerator/CodeTransformation/ImageBuilders/CompilationState_Encoder.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // namespace Microsoft.Zelig.CodeGeneration.IR.ImageBuilders { using System; using System.Collections.Generic; using Microsoft.Zelig.Runtime.TypeSystem; using Microsoft.Zelig.TargetModel.ArmProcessor; public partial class CompilationState { // // State // protected SequentialRegion m_activeCodeRegion; protected SequentialRegion.Section m_activeCodeSection; protected Runtime.HardwareException m_activeHardwareException; protected bool m_fStopProcessingOperatorsForCurrentBasicBlock; private readonly Queue< Operator > m_contextOperators = new Queue< Operator >(); // // Helper Methods // public ImageAnnotation AddNewImageAnnotation( object val ) { return AddNewImageAnnotation( 0, val ); } public ImageAnnotation AddNewImageAnnotation( uint size , object val ) { return m_activeCodeSection.AddImageAnnotation( size, val ); } protected void AddOperatorContext( Operator op ) { m_contextOperators.Enqueue( op ); } protected void FlushOperatorContext() { while(m_contextOperators.Count > 0) { AddNewImageAnnotation( m_contextOperators.Dequeue() ); } } protected static object NormalizeValue( object o ) { if(o is ConstantExpression) { ConstantExpression ex = (ConstantExpression)o; o = ex.Value; ControlFlowGraphStateForCodeTransformation.ValueFragment frag; frag = o as ControlFlowGraphStateForCodeTransformation.ValueFragment; if(frag != null) { o = frag.Value; } } return o; } protected static bool GetValue( object o , out int val ) { o = NormalizeValue( o ); if(o == null) { val = 0; } else if(o is UIntPtr) { val = (int)((UIntPtr)o).ToUInt32(); } else if(o is IntPtr) { val = ((IntPtr)o).ToInt32(); } else if(o is int) { val = (int)o; } else if(o is uint) { val = (int)(uint)o; } else if(o is short) { val = (int)(short)o; } else if(o is ushort) { val = (int)(uint)(ushort)o; } else if(o is sbyte) { val = (int)(sbyte)o; } else if(o is byte) { val = (int)(uint)(byte)o; } else if(o is bool) { val = (bool)o ? 1 : 0; } else { val = 0; return false; } return true; } //--// protected void RecordAdjacencyNeed( Operator opSource , BasicBlock bbTarget ) { m_owner.RecordAdjacencyNeed( opSource, bbTarget ); } protected Core.BranchEncodingLevel GetEncodingLevelForBranch( Operator opSource , BasicBlock bb , bool fConditional ) { return m_owner.GetEncodingLevelForBranch( opSource, bb, fConditional ); } protected Core.ConstantAddressEncodingLevel GetEncodingLevelForConstant( Operator opSource ) { return m_owner.GetEncodingLevelForConstant( opSource ); } //--// protected ImageAnnotation TrackVariable( VariableExpression var , bool fAlive ) { List< ImageAnnotation > annotationList = m_activeCodeSection.Context.AnnotationList; for(int idx = annotationList.Count; --idx >= 0; ) { TrackVariableLifetime tvl = annotationList[idx] as TrackVariableLifetime; if(tvl != null && tvl.Target == var) { if(tvl.IsAlive == fAlive) { // // No change in liveness, keep going. // return tvl; } break; } } return new TrackVariableLifetime( m_activeCodeSection.Context, m_activeCodeSection.Offset, var, fAlive ); } //--// // // Debug Methods // public Exception NotImplemented() { using(System.IO.StreamWriter output = new System.IO.StreamWriter( "CompilationException.txt", false, System.Text.Encoding.ASCII )) { m_cfg.DumpToStream( output ); DumpOpcodes( output ); } return new NotImplementedException(); } protected abstract void DumpOpcodes( System.IO.TextWriter textWriter ); } } ================================================ FILE: Zelig/Zelig/CompileTime/CodeGenerator/CodeTransformation/ImageBuilders/CompilationState_ExceptionMap.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // namespace Microsoft.Zelig.CodeGeneration.IR.ImageBuilders { using System; using System.Collections.Generic; using Microsoft.Zelig.Runtime.TypeSystem; using Microsoft.Zelig.TargetModel.ArmProcessor; public partial class CompilationState { class ExceptionMapBuilder { // // State // ExceptionMap m_exceptionMap; SequentialRegion m_firstRegion; SequentialRegion m_lastRegion; ExceptionMap.Range m_currentRange; // // Constructor Methods // internal ExceptionMapBuilder( ExceptionMap em ) { m_exceptionMap = em; } // // Helper Methods // internal void Compress( DataManager dm , SequentialRegion reg ) { BasicBlock bb = (BasicBlock)reg.Context; ExceptionMap.Range range = m_currentRange; range.Handlers = ExceptionMap.Handler.SharedEmptyArray; foreach(ExceptionHandlerBasicBlock ehBB in bb.ProtectedBy) { foreach(ExceptionClause ec in ehBB.HandlerFor) { ExceptionMap.Handler hnd = new ExceptionMap.Handler(); TypeRepresentation td = ec.ClassObject; bool fAdd = true; hnd.HandlerCode = dm.CreateCodePointer( ehBB ); if(td != null) { hnd.Filter = td.VirtualTable; } uint handlerAddress = reg.Owner.Resolve( ehBB ); for(int i = 0; i < range.Handlers.Length; i++) { VTable filter = range.Handlers[i].Filter; if(filter == null) { // // There's already a catch-all, no need to extend the set of handlers. // fAdd = false; break; } if(filter.TypeInfo.IsSuperClassOf( td, null )) { // // There's already a less-specific catch, no need to extend the set of handlers. // fAdd = false; break; } // // Same handlers? Then this could be a less-specific catch, update the handler. // object ehBB2 = dm.GetCodePointerFromUniqueID( range.Handlers[i].HandlerCode.Target ); uint handlerAddress2 = reg.Owner.Resolve( ehBB2 ); if(handlerAddress == handlerAddress2) { range.Handlers[i].Filter = hnd.Filter; fAdd = false; break; } } if(fAdd) { hnd.HandlerCode = dm.CreateCodePointer( ehBB ); range.Handlers = ArrayUtility.AppendToNotNullArray( range.Handlers, hnd ); } } } if(m_currentRange.SameContents( ref range ) == false) { Emit(); } else if(m_lastRegion != null) { uint startAddress = reg .BaseAddress.ToUInt32(); uint endAddress = m_lastRegion.EndAddress .ToUInt32(); if(endAddress != startAddress) { CHECKS.ASSERT( endAddress < startAddress, "Incorrect ordering of regions: {0} <=> {1}", reg, m_lastRegion ); Emit(); } } m_currentRange = range; if(m_firstRegion == null) { m_firstRegion = reg; m_currentRange.Start = reg.BaseAddress; } m_lastRegion = reg; } internal void Emit() { if(m_firstRegion != null) { if(m_currentRange.Handlers.Length > 0) { m_currentRange.End = m_lastRegion.EndAddress; if(m_currentRange.Start != m_currentRange.End) { // // Only emit non-empty ranges that have handlers. // m_exceptionMap.Ranges = ArrayUtility.AppendToNotNullArray( m_exceptionMap.Ranges, m_currentRange ); } } m_firstRegion = null; m_lastRegion = null; } } } // // State // // // Constructor Methods // // // Helper Methods // internal bool CreateExceptionHandlingTables() { SequentialRegion[] regions = GetSortedCodeRegions(); //--// ExceptionMap em = new ExceptionMap(); em.Ranges = ExceptionMap.Range.SharedEmptyArray; DataManager dm = m_cfg.TypeSystem.DataManagerInstance; ExceptionMapBuilder emb = new ExceptionMapBuilder( em ); foreach(SequentialRegion reg in regions) { emb.Compress( dm, reg ); } emb.Emit(); //--// if(em.Ranges.Length == 0) { em = null; } ExceptionMap emOld = m_cfg.Method.CodeMap.ExceptionMap; bool fModified = ExceptionMap.SameContents( em, emOld ) == false; if(fModified) { m_cfg.Method.CodeMap.ExceptionMap = em; } return fModified; } } } ================================================ FILE: Zelig/Zelig/CompileTime/CodeGenerator/CodeTransformation/ImageBuilders/CompilationState_Scheduling.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // //#define DEBUG_BASICBLOCK_SCHEDULING namespace Microsoft.Zelig.CodeGeneration.IR.ImageBuilders { using System; using System.Collections.Generic; using Microsoft.Zelig.Runtime.TypeSystem; using Microsoft.Zelig.TargetModel.ArmProcessor; public partial class CompilationState { #if DEBUG_BASICBLOCK_SCHEDULING const string sDebugTarget = "FlowGraph(void Microsoft.Zelig.Runtime.Bootstrap::EntryPoint())"; //// "FlowGraph(int Microsoft.Zelig.Runtime.Processor::Delay(int))"; //// "FlowGraph(void Microsoft.Zelig.Runtime.Memory::Dirty(System.UIntPtr,System.UIntPtr))"; //// "FlowGraph(void Microsoft.Zelig.Runtime.TargetPlatform.ARMv4.ProcessorARMv4::VectorsTable())"; //// "FlowGraph(void Microsoft.Zelig.Runtime.TargetPlatform.ARMv4.ProcessorARMv4WithContextSwitch::LongJump(Microsoft.Zelig.Runtime.TargetPlatform.ARMv4.ProcessorARMv4WithContextSwitch.Context.RegistersOnStack&))"; //// "FlowGraph(void Microsoft.Zelig.Runtime.MarkAndSweepCollector::Sweep())"; #endif [Flags] enum SlotEdgeFlavor { Inbound = 0x00000001, Outbound = 0x00000002, SourceIsInternal = 0x00000004, DestinationIsInternal = 0x00000008, } class SlotEdge { // // State // internal readonly AtomicSlot m_source; internal readonly AtomicSlot m_destination; internal readonly SlotEdgeFlavor m_flavor; // // Constructor Methods // internal SlotEdge( AtomicSlot source , AtomicSlot destination , SlotEdgeFlavor flavor ) { m_source = source; m_destination = destination; m_flavor = flavor; } // // AccessMethods // internal bool IsInbound { get { return (m_flavor & SlotEdgeFlavor.Inbound) != 0; } } internal bool IsOutbound { get { return (m_flavor & SlotEdgeFlavor.Outbound) != 0; } } internal bool IsBoundary { get { return (m_flavor & (SlotEdgeFlavor.SourceIsInternal | SlotEdgeFlavor.DestinationIsInternal)) == 0; } } } abstract class Slot { // // State // protected readonly CompilationState m_owner; private readonly List< SlotEdge > m_edges; private CompoundSlot m_superSlot; protected int m_weight; private int m_schedulingIndex; // // Constructor Methods // protected Slot( CompilationState owner ) { m_owner = owner; m_edges = new List< SlotEdge >(); m_schedulingIndex = -1; owner.RegisterTopLevel( this ); } // // Helper Methods // protected static void AddConnection( SlotEdge edge ) { AddConnection( edge.m_source, edge.m_destination ); } protected static void AddConnection( AtomicSlot source , AtomicSlot destination ) { if(destination.Target is ExceptionHandlerBasicBlock) { // For scheduling purposes, only include edges to normal basic blocks. } else { Slot topLevelSrc = source .TopLevel; Slot topLevelDst = destination.TopLevel; if(topLevelSrc == topLevelDst) { // Don't include internal connections. return; } topLevelSrc.AddOutboundConnection( source, destination ); topLevelDst.AddInboundConnection ( source, destination ); } } private void AddInboundConnection( AtomicSlot source , AtomicSlot destination ) { CHECKS.ASSERT( this == destination.TopLevel, "Not an inbound connection" ); if(FindEdge( source, destination ) == null) { SlotEdgeFlavor flavor = SlotEdgeFlavor.Inbound; if(source != source.TopLevel.LastSubSlot) { flavor |= SlotEdgeFlavor.SourceIsInternal; } if(destination != this.FirstSubSlot) { flavor |= SlotEdgeFlavor.DestinationIsInternal; } m_edges.Add( new SlotEdge( source, destination, flavor ) ); } } private void AddOutboundConnection( AtomicSlot source , AtomicSlot destination ) { CHECKS.ASSERT( this == source.TopLevel, "Not an outbound connection" ); if(FindEdge( source, destination ) == null) { SlotEdgeFlavor flavor = SlotEdgeFlavor.Outbound; if(source != this.LastSubSlot) { flavor |= SlotEdgeFlavor.SourceIsInternal; } if(destination != destination.TopLevel.FirstSubSlot) { flavor |= SlotEdgeFlavor.DestinationIsInternal; } m_edges.Add( new SlotEdge( source, destination, flavor ) ); } } internal SlotEdge FindEdge( AtomicSlot source , AtomicSlot destination ) { foreach(var edge in m_edges) { if(edge.m_source == source && edge.m_destination == destination ) { return edge; } } return null; } internal bool HasBinaryInput( out SlotEdge edge1 , out SlotEdge edge2 , bool fColdCode ) { edge1 = null; edge2 = null; int count = 0; foreach(var edge in m_edges) { if(edge.IsInbound) { if(edge.m_source.IsColdCode != fColdCode) { continue; } switch(count++) { case 0: edge1 = edge; break; case 1: edge2 = edge; break; } } } return count == 2; } internal bool HasBinaryOutput( out SlotEdge edge1 , out SlotEdge edge2 , bool fColdCode ) { edge1 = null; edge2 = null; int count = 0; foreach(var edge in m_edges) { if(edge.IsOutbound) { if(edge.m_destination.IsColdCode != fColdCode) { continue; } switch(count++) { case 0: edge1 = edge; break; case 1: edge2 = edge; break; } } } return count == 2; } //--// internal abstract IEnumerable< AtomicSlot > Enumerate(); //--// internal CompoundSlot Merge( Slot slot ) { #if DEBUG_BASICBLOCK_SCHEDULING if(m_owner.m_cfg.ToString() == sDebugTarget) { Console.WriteLine( "#####################################" ); Console.WriteLine( "Left : {0}", this ); Console.WriteLine( "Right: {0}", slot ); Console.WriteLine( "<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<" ); Console.WriteLine( "{0}", new System.Diagnostics.StackTrace() ); Console.WriteLine( ">>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>" ); } #endif return new CompoundSlot( m_owner, this, slot ); } internal bool IsInSet( GrowOnlySet< Slot > slots ) { if(slots == null) { return true; } Slot slot = this; while(slot != null) { if(slots.Contains( slot )) { return true; } slot = slot.SuperSlot; } return false; } internal GrowOnlySet< Slot > InboundEdges( bool fBoundaryEdgesOnly ) { GrowOnlySet< Slot > set = SetFactory.NewWithReferenceEquality< Slot >(); foreach(var edge in m_edges) { if(edge.IsInbound) { if(fBoundaryEdgesOnly && edge.IsBoundary == false) { continue; } set.Insert( edge.m_source ); } } return set; } internal GrowOnlySet< Slot > OutboundEdges( bool fBoundaryEdgesOnly ) { GrowOnlySet< Slot > set = SetFactory.NewWithReferenceEquality< Slot >(); foreach(var edge in m_edges) { if(edge.IsOutbound) { if(fBoundaryEdgesOnly && edge.IsBoundary == false) { continue; } set.Insert( edge.m_destination ); } } return set; } internal Slot FindSingleInboundEdge( GrowOnlySet< Slot > slots , bool fSameColdness , bool fBoundaryEdgesOnly ) { Slot res = null; foreach(var edge in m_edges) { if(edge.IsInbound) { Slot slot = edge.m_source; if(fSameColdness && this.IsColdCode != slot.IsColdCode) { continue; } if(slot.IsInSet( slots )) { if(res != null) { return null; } if(fBoundaryEdgesOnly && edge.IsBoundary == false) { return null; } res = slot; } } } return res; } internal Slot FindSingleOutboundEdge( GrowOnlySet slots , bool fSameColdness , bool fBoundaryEdgesOnly ) { Slot res = null; foreach(var edge in m_edges) { if(edge.IsOutbound) { Slot slot = edge.m_destination; if(fSameColdness && this.IsColdCode != slot.IsColdCode) { continue; } if(slot.IsInSet( slots )) { if(fBoundaryEdgesOnly && edge.IsBoundary == false) { return null; } if(res != null) { return null; } res = slot; } } } if(fBoundaryEdgesOnly && res != null) { res = res.TopLevel; } return res; } //--// // // Access Methods // internal List< SlotEdge > Edges { get { return m_edges; } } internal int Weight { get { return m_weight; } } internal int SchedulingIndex { get { return m_schedulingIndex; } set { m_schedulingIndex = value; } } internal bool IsTopLevel { get { return this == this.TopLevel; } } internal bool IsColdCode { get { return m_owner.IsTransitivelyColdCode( this.FirstSubSlot.Target ); } } internal Slot TopLevel { get { return m_superSlot != null ? m_superSlot.TopLevel : this; } } internal CompoundSlot SuperSlot { get { return m_superSlot; } set { m_superSlot = value; if(m_superSlot == null) { m_owner.RegisterTopLevel( this ); } else { m_owner.UnregisterTopLevel( this ); } } } internal abstract AtomicSlot FirstSubSlot { get; } internal abstract AtomicSlot LastSubSlot { get; } // // Debug Methods // public override string ToString() { System.Text.StringBuilder sb = new System.Text.StringBuilder(); sb.AppendFormat( "Slots:" ); sb.AppendLine(); foreach(var slot in this.Enumerate()) { foreach(var sub in slot.ToString().Split( Environment.NewLine.ToCharArray(), StringSplitOptions.RemoveEmptyEntries )) { sb.AppendFormat( " >> {0}{1}", sub, Environment.NewLine ); } sb.AppendLine(); } return sb.ToString(); } } class CompoundSlot : Slot { // // State // private readonly Slot m_left; private readonly Slot m_right; // // Constructor Methods // internal CompoundSlot( CompilationState owner , Slot left , Slot right ) : base( owner ) { CHECKS.ASSERT( left .SuperSlot == null, "Cannot merge slot twice: {0}", left ); CHECKS.ASSERT( right.SuperSlot == null, "Cannot merge slot twice: {0}", right ); m_left = left; m_right = right; //--// //// Console.WriteLine( "<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<" ); //// Console.WriteLine( "Left {0}" , left ); //// Console.WriteLine( "----------------------------------------" ); //// Console.WriteLine( "Right {0}", right ); // // Redistribute the slots. // m_left .SuperSlot = this; m_right.SuperSlot = this; m_weight = Math.Max( m_left.Weight, m_right.Weight ); // // Merge the slot edges. // CopyConnections( left .Edges ); CopyConnections( right.Edges ); //// Console.WriteLine( "########################################" ); //// Console.WriteLine( "Result {0}", res ); //// Console.WriteLine( ">>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>" ); } // // Helper Methods // private static void CopyConnections( List< SlotEdge > list ) { foreach(var edge in list) { AddConnection( edge ); } } internal override IEnumerable< AtomicSlot > Enumerate() { foreach(var slot in m_left.Enumerate()) { yield return slot; } foreach(var slot in m_right.Enumerate()) { yield return slot; } } // // Access Methods // internal override AtomicSlot FirstSubSlot { get { return m_left.FirstSubSlot; } } internal override AtomicSlot LastSubSlot { get { return m_right.LastSubSlot; } } } class AtomicSlot : Slot { internal static readonly AtomicSlot[] SharedEmptyArray = new AtomicSlot[0]; // // State // private readonly BitVector m_zeroLengthPredecessors; private readonly int m_targetIdx; // // Constructor Methods // internal AtomicSlot( CompilationState owner , int targetIdx , int weight ) : base( owner ) { m_zeroLengthPredecessors = new BitVector(); m_targetIdx = targetIdx; m_weight = weight; } // // Helper Methods // internal void AddInboundConnection( AtomicSlot source ) { AddConnection( source, this ); } internal void AddOutboundConnection( AtomicSlot destination ) { AddConnection( this, destination ); } internal override IEnumerable< AtomicSlot > Enumerate() { yield return this; } // // Access Methods // internal BitVector ZeroLengthPredecessors { get { return m_zeroLengthPredecessors; } } internal override AtomicSlot FirstSubSlot { get { return this; } } internal override AtomicSlot LastSubSlot { get { return this; } } internal int TargetIndex { get { return m_targetIdx; } } internal BasicBlock Target { get { return m_owner.m_basicBlocks[m_targetIdx]; } } // // Debug Methods // public override string ToString() { System.Text.StringBuilder sb = new System.Text.StringBuilder(); sb.AppendFormat( "<<<<<<<<<" ); sb.AppendLine(); foreach(var bbIdx in m_zeroLengthPredecessors) { sb.AppendFormat( "PreTarget: {0}", m_owner.m_basicBlocks[bbIdx] ); sb.AppendLine(); } sb.AppendFormat( "Target: {0}", this.Target ); sb.AppendLine(); sb.AppendFormat( "Weight: {0}", m_weight ); sb.AppendLine(); sb.AppendFormat( ">>>>>>>>>" ); return sb.ToString(); } } // // State // // // Constructor Methods // // // Helper Methods // private void CollectSchedulingPreferences() { #if DEBUG_BASICBLOCK_SCHEDULING if(m_cfg.ToString() == sDebugTarget) { } #endif foreach(var bb in m_basicBlocks) { // // Mark exception entry code as cold. // if(bb is ExceptionHandlerBasicBlock) { SetColdCode( bb ); } if(bb.FlowControl is DeadControlOperator) { SetColdCode( bb ); } //--// uint size = 0; foreach(Operator op in bb.Operators) { size += EmitCodeForBasicBlock_EstimateMinimumSize( op ); var call = op as SubroutineOperator; if(call != null && call.TargetMethod.HasBuildTimeFlag( MethodRepresentation.BuildTimeAttributes.NoReturn )) { SetColdCode( bb ); } } if(size == 0) { SetZeroLengthCandidate( bb ); } } } //--// private void AllocateSchedulingSlots() { #if DEBUG_BASICBLOCK_SCHEDULING if(m_cfg.ToString() == sDebugTarget) { } #endif foreach(var bb in m_basicBlocks) { var slot = GetSchedulingSlot( bb ); foreach(var edge in bb.Predecessors) { var bbPrev = edge.Predecessor; if(bbPrev.ShouldIncludeInScheduling( bb )) { var slotPrev = GetSchedulingSlot( bbPrev ); slot.AddInboundConnection( slotPrev ); } } foreach(var edge in bb.Successors) { var bbNext = edge.Successor; if(bb.ShouldIncludeInScheduling( bbNext )) { var slotNext = GetSchedulingSlot( bbNext ); slot.AddOutboundConnection( slotNext ); } } } AllocateArrayOfLoopExitSlots(); } private void AllocateArrayOfLoopExitSlots() { BitVector candidates = new BitVector(); foreach(var entry in m_naturalLoops.Loops) { candidates.OrInPlace( entry.m_exitPoints ); } m_schedulingLoopExits = new AtomicSlot[candidates.Cardinality]; int idxLoop = 0; foreach(var idx in candidates) { m_schedulingLoopExits[idxLoop++] = m_schedulingLookup[idx]; } } //--// private void OrderBasicBlocks() { #if DEBUG_BASICBLOCK_SCHEDULING if(m_cfg.ToString() == sDebugTarget) { } #endif while(true) { if(CoalesceSlots( ToSet( m_topLevelSlots ) )) { continue; } if(OrderBasicBlocksInLoops()) { continue; } if(OrderBasicBlocksInSet( ToSet( m_topLevelSlots ) )) { continue; } break; } #if DEBUG_BASICBLOCK_SCHEDULING if(m_cfg.ToString() == sDebugTarget) { } #endif } private bool OrderBasicBlocksInLoops() { foreach(var entry in m_naturalLoops.Loops) { if(OrderBasicBlocksInLoop( entry )) { return true; } } return false; } private bool OrderBasicBlocksInLoop( IR.DataFlow.ControlTree.NaturalLoops.Entry entry ) { if(OrderBasicBlocksInLoop( entry, false )) { return true; } if(OrderBasicBlocksInLoop( entry, true )) { return true; } return false; } private bool OrderBasicBlocksInLoop( IR.DataFlow.ControlTree.NaturalLoops.Entry entry , bool fColdCode ) { GrowOnlySet< Slot > slots = SetFactory.NewWithReferenceEquality< Slot >(); foreach(var idx in entry.BasicBlocks) { var slot = m_schedulingLookup[idx]; if(slot.IsColdCode != fColdCode) { continue; } slots.Insert( slot.TopLevel ); } return OrderBasicBlocksInSet( slots ); } //--//--// private bool OrderBasicBlocksInSet( GrowOnlySet< Slot > slots ) { if(slots.Count <= 1) { return false; } if(DetectCodePattern_LoopExit( slots )) { return true; } if(DetectCodePattern_IfBlock( slots )) { return true; } if(CoalesceSlots( slots )) { return true; } return false; } //--// private bool DetectCodePattern_LoopExit( GrowOnlySet< Slot > slots ) { if(DetectCodePattern_LoopExit( slots, true )) { return true; } if(DetectCodePattern_LoopExit( slots, false )) { return true; } return false; } private bool DetectCodePattern_LoopExit( GrowOnlySet< Slot > slots , bool fColdCode ) { foreach(var slot in SortByWeight( slots, true )) { if(slot.IsColdCode != fColdCode) { continue; } var lastSlot = slot.LastSubSlot; foreach(var loop in m_naturalLoops.Loops) { if(loop.ExitPoints[lastSlot.TargetIndex]) { foreach(var slotPre in Filter( slot.InboundEdges( false ), slots, fColdCode )) { slotPre.Merge( slot ); return true; } } } } return false; } //--// private bool DetectCodePattern_IfBlock( GrowOnlySet< Slot > slots ) { if(DetectCodePattern_IfBlock( slots, false )) { return true; } if(DetectCodePattern_IfBlock( slots, true )) { return true; } return false; } private bool DetectCodePattern_IfBlock( GrowOnlySet< Slot > slots , bool fColdCode ) { foreach(var slot in SortByWeight( slots, true )) { if(slot.IsColdCode != fColdCode) { continue; } SlotEdge edgeIf1; SlotEdge edgeIf2; if(slot.HasBinaryOutput( out edgeIf1, out edgeIf2, fColdCode )) { Slot dst1 = edgeIf1.m_destination.TopLevel; Slot dst2 = edgeIf2.m_destination.TopLevel; if(TryToLinearizeIF( slot, dst1, dst2, fColdCode )) { return true; } if(TryToLinearizeIF( slot, dst2, dst1, fColdCode )) { return true; } if(TryToLinearizeIFTHENELSE( slots, slot, dst1, dst2, fColdCode )) { return true; } } } return false; } private bool TryToLinearizeIF( Slot slotA , Slot slotB , Slot slotC , bool fColdCode ) { SlotEdge edge1; SlotEdge edge2; if(slotC.HasBinaryInput( out edge1, out edge2, fColdCode )) { if(edge1.m_source.TopLevel == slotA && edge2.m_source.TopLevel == slotB) { slotA.Merge( slotB ); return true; } } return false; } private bool TryToLinearizeIFTHENELSE( GrowOnlySet< Slot > slots , Slot slotIf , Slot slotThen , Slot slotElse , bool fColdCode ) { Slot slotThenOut = slotThen.FindSingleOutboundEdge( slots, true, false ); Slot slotElseOut = slotElse.FindSingleOutboundEdge( slots, true, false ); if(slotThenOut != null && slotElseOut != null) { slotThenOut = slotThenOut.TopLevel; slotElseOut = slotElseOut.TopLevel; if(slotThenOut == slotElseOut) { // // BUGBUG: Select which way to merge the if/then/else block: if/then/else or if/else/then?? // slotIf.Merge( slotThen ); return true; } } return false; } //--//--// private bool CoalesceSlots( GrowOnlySet< Slot > slots ) { foreach(var slot in slots) { var slotNext = slot.FindSingleOutboundEdge( slots, true, true ); if(slotNext != null && slotNext.FindSingleInboundEdge( slots, true, true ) == slot) { // // Only merge slots with the same "coldness" flavor. // if(slot.IsColdCode == slotNext.IsColdCode) { slot.Merge( slotNext ); return true; } } } return false; } //--//--// private void AssignSchedulingIndex() { #if DEBUG_BASICBLOCK_SCHEDULING if(m_cfg.ToString() == sDebugTarget) { Console.WriteLine( "Start Scheduling for {0}:", m_cfg ); Console.WriteLine(); foreach(var slotTopLevel in m_topLevelSlots) { Console.WriteLine( "#######" ); Console.WriteLine( "{0}", slotTopLevel ); } Console.WriteLine( "-------------------" ); } #endif int index = 0; index = AssignSchedulingIndex( index, false ); index = AssignSchedulingIndex( index, true ); #if DEBUG_BASICBLOCK_SCHEDULING if(m_cfg.ToString() == sDebugTarget) { Console.WriteLine( "Completed Scheduling for {0}:", m_cfg ); Console.WriteLine(); Slot[] slots = ArrayUtility.CopyNotNullArray( m_topLevelSlots.ToArray() ); Array.Sort( slots, (x, y) => x.FirstSubSlot.SchedulingIndex.CompareTo( y.FirstSubSlot.SchedulingIndex ) ); foreach(var slotTopLevel in slots) { Console.WriteLine( "#######" ); Console.WriteLine( "{0}", slotTopLevel ); } Console.WriteLine( "-------------------" ); } #endif } private int AssignSchedulingIndex( int index , bool fColdCode ) { #if DEBUG_BASICBLOCK_SCHEDULING if(m_cfg.ToString() == sDebugTarget) { } #endif GrowOnlySet< Slot > visited = SetFactory.NewWithReferenceEquality< Slot>(); foreach(var slot in m_schedulingLookup) { index = AssignSchedulingIndex( index, fColdCode, slot, visited ); } return index; } private int AssignSchedulingIndex( int index , bool fColdCode , Slot slot , GrowOnlySet< Slot > visited ) { var slotTopLevel = slot.TopLevel; if(fColdCode == slotTopLevel.IsColdCode) { bool fSchedule = true; foreach(var edge in slotTopLevel.Edges) { if(edge.IsInbound) { if(visited.Contains( edge.m_source.TopLevel ) == false) { fSchedule = false; } } } // // Only assign a scheduling number after all the inbound edges have been visited. // if(fSchedule) { foreach(var slotSub in slotTopLevel.Enumerate()) { if(slotSub.SchedulingIndex < 0) { slotSub.SchedulingIndex = index++; } } } } if(visited.Insert( slotTopLevel ) == false) { foreach(var edge in slotTopLevel.Edges) { if(edge.IsOutbound) { index = AssignSchedulingIndex( index, fColdCode, edge.m_destination, visited ); } } } return index; } //--// public void SetZeroLengthCandidate( BasicBlock bb ) { CHECKS.ASSERT( m_cfg == bb.Owner, "'{0}' does not belong to '{1}'", bb, m_cfg ); m_vecZeroLengthCandidates.Set( bb.SpanningTreeIndex ); } public bool IsZeroLengthCandidate( BasicBlock bb ) { CHECKS.ASSERT( m_cfg == bb.Owner, "'{0}' does not belong to '{1}'", bb, m_cfg ); return m_vecZeroLengthCandidates[bb.SpanningTreeIndex]; } public void SetColdCode( BasicBlock bb ) { CHECKS.ASSERT( m_cfg == bb.Owner, "'{0}' does not belong to '{1}'", bb, m_cfg ); m_vecColdCode.Set( bb.SpanningTreeIndex ); } public bool IsColdCode( BasicBlock bb ) { CHECKS.ASSERT( m_cfg == bb.Owner, "'{0}' does not belong to '{1}'", bb, m_cfg ); return m_vecColdCode[bb.SpanningTreeIndex]; } public bool IsReachableFromColdCode( BasicBlock bb ) { CHECKS.ASSERT( m_cfg == bb.Owner, "'{0}' does not belong to '{1}'", bb, m_cfg ); return m_vecReachableFromColdCode[bb.SpanningTreeIndex]; } public bool IsReachableFromEntry( BasicBlock bb ) { CHECKS.ASSERT( m_cfg == bb.Owner, "'{0}' does not belong to '{1}'", bb, m_cfg ); return m_vecReachableFromEntry[bb.SpanningTreeIndex]; } public bool IsTransitivelyColdCode( BasicBlock bb ) { CHECKS.ASSERT( m_cfg == bb.Owner, "'{0}' does not belong to '{1}'", bb, m_cfg ); return IsReachableFromColdCode( bb ) && !IsReachableFromEntry( bb ); } public int SchedulingIndex( BasicBlock bb ) { CHECKS.ASSERT( m_cfg == bb.Owner, "'{0}' does not belong to '{1}'", bb, m_cfg ); return GetSchedulingSlot( bb ).SchedulingIndex; } public SequentialRegion GetRegion( BasicBlock bb ) { CHECKS.ASSERT( m_cfg == bb.Owner, "'{0}' does not belong to '{1}'", bb, m_cfg ); return m_basicBlockToRegions[bb.SpanningTreeIndex]; } //--// private AtomicSlot GetSchedulingSlot( BasicBlock bb ) { int bbIdx = bb.SpanningTreeIndex; AtomicSlot slot = m_schedulingLookup[bbIdx]; if(slot == null) { if(m_vecZeroLengthCandidates[bbIdx]) { foreach(var edge in bb.Successors) { var bbNext = edge.Successor; if(bbNext is ExceptionHandlerBasicBlock) { // Only consider normal basic blocks. } else { slot = GetSchedulingSlot( bbNext ); slot.ZeroLengthPredecessors.Set( bbIdx ); break; } } } if(slot == null) { // // Bias the slot based on hot/cold split. // int weight = IsTransitivelyColdCode( bb ) ? -1000000 : 1000000; // // The ordering algorithm is based on dominance, so it works backwards. // Adding the spanning tree index position skews the weights in the right way (exit before entry). // weight += bbIdx; // // Finally multiply the loop depth position by the size of the spanning tree, to avoid interfering with the previous point. // weight += m_basicBlocks.Length * (int)Math.Pow( 8, m_naturalLoops.GetDepthOfBasicBlock( bb ) ); slot = new AtomicSlot( this, bbIdx, weight ); } m_schedulingLookup[bb.SpanningTreeIndex] = slot; } return slot; } private void RegisterTopLevel( Slot slot ) { m_topLevelSlots.Add( slot ); } private void UnregisterTopLevel( Slot slot ) { m_topLevelSlots.Remove( slot ); } //--// private List< Slot > ToList( IEnumerable< Slot > collection ) { List< Slot > lst = new List< Slot >(); foreach(var slot in collection) { lst.Add( slot ); } return lst; } private GrowOnlySet< Slot > ToSet( IEnumerable< Slot > collection ) { GrowOnlySet< Slot > set = SetFactory.NewWithReferenceEquality< Slot >(); foreach(var slot in collection) { set.Insert( slot ); } return set; } private IEnumerable< Slot > Filter( GrowOnlySet< Slot > set , GrowOnlySet< Slot > slots , bool fColdCode ) { return Filter( set.ToArray(), slots, fColdCode ); } private IEnumerable< Slot > Filter( IEnumerable< Slot > collection , GrowOnlySet< Slot > slots , bool fColdCode ) { foreach(var slot in collection) { if(slot.IsColdCode == fColdCode) { if(slot.IsInSet( slots )) { yield return slot.TopLevel; } } } } private IEnumerable< Slot > SortByWeight( GrowOnlySet< Slot > set , bool fUp ) { return SortByWeight( set.ToArray(), fUp ); } private IEnumerable< Slot > SortByWeight( IEnumerable< Slot > collection , bool fUp ) { List< Slot > lst = ToList( collection ); if(fUp) { lst.Sort( (x, y) => x.Weight.CompareTo( y.Weight ) ); } else { lst.Sort( (x, y) => y.Weight.CompareTo( x.Weight ) ); } return lst; } private IEnumerable< Slot > EnumerateLoopExits() { return m_schedulingLoopExits; } //--// internal void AssignAbsoluteAddresses( bool fIncludeColdCode ) { AtomicSlot[] slots = ArrayUtility.CopyNotNullArray( m_schedulingLookup ); Array.Sort( slots, (x, y) => x.SchedulingIndex.CompareTo( y.SchedulingIndex ) ); #if DEBUG_BASICBLOCK_SCHEDULING if(m_cfg.ToString() == sDebugTarget) { } #endif foreach(var slot in slots) { SequentialRegion reg = GetRegion( slot.Target ); if(reg.IsBaseAddressAssigned == false) { if(fIncludeColdCode || !IsTransitivelyColdCode( slot.Target )) { if(reg.Size == 0) { // // We cannot have a zero-length slot, because it will be aliased to random places. // This can cause malfunctions during stack walking, // because the stack unwinder will think it landed in a different method. // We need to add a bit of garbage to make the stack crawler happy. // FixupEmptyRegion( reg ); } reg.AssignAbsoluteAddress(); foreach(var bbIdx2 in slot.ZeroLengthPredecessors) { SequentialRegion reg2 = m_basicBlockToRegions[bbIdx2]; if(reg2.IsBaseAddressAssigned == false) { reg2.BaseAddress = reg.BaseAddress; } } m_owner.PushRegionConstantsToPendingList( reg ); } } } } } } ================================================ FILE: Zelig/Zelig/CompileTime/CodeGenerator/CodeTransformation/ImageBuilders/Core.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // #define ARMv7M_BUILD__LLVM_IR_ONLY namespace Microsoft.Zelig.CodeGeneration.IR.ImageBuilders { using System; using System.Collections.Generic; using Microsoft.Zelig.Runtime.TypeSystem; using Microsoft.Zelig.TargetModel.ArmProcessor; using Microsoft.Zelig.CodeGeneration.IR.CompilationSteps; public sealed class Core { public delegate bool SequentialRegionEnumerationCallback( SequentialRegion reg ); public delegate bool ImageAnnotationEnumerationCallback( ImageAnnotation an ); //--// public enum BranchEncodingLevel { // // Don't emit any branch, the source and destination are adjacent. // Skip, // // Single-opcode encoding for branch. // // Example: // // BR #rel-address // ShortBranch, // // Single-opcode indirect jump. // // Example: // // LDR PC, [PC,#const] // NearRelativeLoad, // // Multi-opcode indirect jump. // // Example: // // MOV R12, #const1 // OR R12, #const2 // ... // LDR PC, [PC,R12] // FarRelativeLoad, //--// Max = FarRelativeLoad, } public enum ConstantAddressEncodingLevel { // // The constant is encoded in the opcode. // // Example: // // MOV ,#const // Immediate, // // The constant is encoded in the opcode. // // Example: // // MOV ,#const1 // OR ,,#const2 // SmallLoad, // // Single-opcode indirect jump. // // Example: // // LDR , [PC,#const] // NearRelativeLoad, // // Multi-opcode indirect load. // // Example: // // MOV R12, #const1 // OR R12, #const2 // ... // LDR , [PC,R12] // FarRelativeLoad16Bit, FarRelativeLoad24Bit, FarRelativeLoad32Bit, //--// Max = FarRelativeLoad32Bit, } //--// class MemoryRange { // // State // List< byte[] > m_chunks; // // Constructor Methods // internal MemoryRange( ) { m_chunks = new List( ); } internal MemoryRange( byte[] chunk ) : this( ) { Append( chunk ); } // // Helper Methods // internal void Rewind( int length ) { for( int pos = m_chunks.Count; --pos >= 0; ) { byte[] chunk = m_chunks[ pos ]; int chunkLen = chunk.Length; if( chunkLen <= length ) { m_chunks.RemoveAt( pos ); length -= chunkLen; if( length <= 0 ) { break; } } else { m_chunks[ pos ] = ArrayUtility.ExtractSliceFromNotNullArray( chunk, 0, chunkLen - length ); break; } } } internal void Append( byte[] chunk ) { m_chunks.Add( chunk ); } internal bool Match( int offset, byte[] payload, int payloadOffset, int length ) { int offsetEnd = offset + length; int chunkStart = 0; foreach( byte[] chunk in m_chunks ) { int chunkLen = chunk.Length; int chunkEnd = chunkStart + chunkLen; int matchStart = Math.Max( chunkStart, offset ); int matchEnd = Math.Min( chunkEnd, offsetEnd ); // // Is there any overlap? // if( matchStart < matchEnd ) { if( ArrayUtility.ByteArrayEquals( chunk, matchStart - chunkStart, payload, payloadOffset + ( matchStart - offset ), matchEnd - matchStart ) == false ) { return false; } } chunkStart += chunkLen; } return true; } internal byte[] ToArray( ) { int size = 0; foreach( byte[] chunk in m_chunks ) { size += chunk.Length; } byte[] res = new byte[ size ]; int offset = 0; foreach( byte[] chunk in m_chunks ) { Array.Copy( chunk, 0, res, offset, chunk.Length ); offset += chunk.Length; } return res; } } class SortedLinkerHeap { internal class HeapRange { // // State // internal UIntPtr Start; internal UIntPtr End; internal string SectionName; internal Runtime.MemoryAttributes Attributes; internal Runtime.MemoryUsage Usage; internal Type ExtensionHandler; // // Constructor Methods // internal HeapRange( UIntPtr start, UIntPtr end, string sectionName, Runtime.MemoryAttributes attributes, Runtime.MemoryUsage usage, Type extensionHandler ) { this.Start = start; this.End = end; this.SectionName = sectionName; this.Attributes = attributes; this.Usage = usage; this.ExtensionHandler = extensionHandler; } // // Helper Methods // internal HeapRange Clone( ) { return new HeapRange( this.Start, this.End, this.SectionName, this.Attributes, this.Usage, this.ExtensionHandler ); } internal HeapRange SliceAsAllocated( UIntPtr ptrStart, UIntPtr ptrEnd ) { return new HeapRange( ptrStart, ptrEnd, this.SectionName, this.Attributes | Runtime.MemoryAttributes.Allocated, this.Usage, this.ExtensionHandler ); } internal HeapRange SliceAsNotAllocated( UIntPtr ptrStart, UIntPtr ptrEnd ) { return new HeapRange( ptrStart, ptrEnd, this.SectionName, this.Attributes & ~Runtime.MemoryAttributes.Allocated, this.Usage, this.ExtensionHandler ); } internal Runtime.Memory.Range ToMemoryRange( ) { return new Runtime.Memory.Range( this.Start, this.End, this.SectionName, this.Attributes, this.Usage, this.ExtensionHandler ); } internal static HeapRange FromMemoryRange( Runtime.Memory.Range rng ) { return new HeapRange( rng.Start, rng.End, rng.SectionName, rng.Attributes & ~Runtime.MemoryAttributes.Allocated, rng.Usage, rng.ExtensionHandler ); } } // // State // internal List< HeapRange > m_heap; // // Constructor Methods // internal SortedLinkerHeap( List memoryBlocks ) { m_heap = new List( ); ImportBlocks( memoryBlocks ); } internal SortedLinkerHeap( SortedLinkerHeap other ) { m_heap = new List( ); foreach( HeapRange rng in other.m_heap ) { m_heap.Add( rng.Clone( ) ); } } // // Helper Methods // internal List Commit( ) { List< Runtime.Memory.Range > lst = new List( ); foreach( HeapRange heapRng in m_heap ) { lst.Add( heapRng.ToMemoryRange( ) ); } return lst; } internal void RebuildFromRegions( List memoryBlocks, SequentialRegion[] regions ) { m_heap.Clear( ); ImportBlocks( memoryBlocks ); //--// SequentialRegion firstRegion = null; SequentialRegion lastRegion = null; foreach( SequentialRegion reg in regions ) { if( firstRegion == null ) { firstRegion = reg; } else if( AddressMath.IsGreaterThanOrEqual( lastRegion.EndAddress, reg.BaseAddress ) == false ) { FixupSpan( firstRegion.BaseAddress, lastRegion.EndAddress ); firstRegion = reg; } lastRegion = reg; } if( firstRegion != null ) { FixupSpan( firstRegion.BaseAddress, lastRegion.EndAddress ); } } private void FixupSpan( UIntPtr regStart, UIntPtr regEnd ) { for( int pos = 0; pos < m_heap.Count; pos++ ) { HeapRange rng = m_heap[ pos ]; Runtime.MemoryAttributes rngKind = rng.Attributes; if( ( rngKind & Runtime.MemoryAttributes.Allocated ) == 0 ) { UIntPtr ptrStart = AddressMath.Max( rng.Start, regStart ); UIntPtr ptrEnd = AddressMath.Min( rng.End, regEnd ); if( AddressMath.IsLessThan( ptrStart, ptrEnd ) ) { ExtractChunk( pos, rng, ptrStart, ptrEnd ); // // Restart the loop, in case the region spans multiple free heap clusters. // pos = -1; continue; } } } } internal bool Allocate( uint size, uint offset, Abstractions.PlacementRequirements pr, out UIntPtr address ) { for( int pos = 0; pos < m_heap.Count; pos++ ) { HeapRange rng = m_heap[ pos ]; if( ( rng.Attributes & Runtime.MemoryAttributes.Allocated ) == 0 ) { if(pr.IsCompatible( rng.SectionName, rng.Attributes, rng.Usage ) ) { // // Chunk is free and compatible. // uint offsetForAlignment = ( uint )( offset + pr.AlignmentOffset ); uint sizeForAlignment = size - offsetForAlignment; UIntPtr ptrStart; UIntPtr ptrEnd; if( pr.AllocateFromHighAddress ) { ptrStart = AddressMath.Decrement( rng.End, sizeForAlignment ); ptrStart = AddressMath.AlignToBoundary( ptrStart, pr.Alignment ); ptrEnd = AddressMath.Increment( ptrStart, sizeForAlignment ); // // AlignToBoundary might move the block past the end of the range, try to adjust for this. // if( AddressMath.IsGreaterThan( ptrEnd, rng.End ) ) { ptrStart = AddressMath.Decrement( ptrStart, pr.Alignment ); ptrEnd = AddressMath.Decrement( ptrEnd, pr.Alignment ); } } else { ptrStart = AddressMath.Increment( rng.Start, offsetForAlignment ); ptrStart = AddressMath.AlignToBoundary( ptrStart, pr.Alignment ); ptrEnd = AddressMath.Increment( ptrStart, sizeForAlignment ); } if( AddressMath.IsGreaterThanOrEqual( ptrStart, rng.Start ) && AddressMath.IsLessThanOrEqual( ptrEnd, rng.End ) ) { // // Found a fit. Update the heap state. // address = AddressMath.Decrement( ptrStart, offsetForAlignment ); ExtractChunk( pos, rng, address, ptrEnd ); return true; } } } } address = new UIntPtr( ); return false; } //--// private void ImportBlocks( List memoryBlocks ) { foreach( var rng in memoryBlocks ) { HeapRange heapRange = HeapRange.FromMemoryRange( rng ); int pos = 0; while( pos < m_heap.Count ) { HeapRange heapRange2 = m_heap[ pos ]; if( AddressMath.IsLessThan( heapRange.Start, heapRange2.Start ) ) { break; } pos++; } m_heap.Insert( pos, heapRange ); } } private void ExtractChunk( int pos, HeapRange rng, UIntPtr ptrStart, UIntPtr ptrEnd ) { CHECKS.ASSERT( AddressMath.IsLessThanOrEqual( rng.Start, ptrStart ), "The start of the target range [{0:X8}-{1:X8}] does not belong to the chunk [{2:X8}-{3:X8}]", ptrStart.ToUInt32( ), ptrEnd.ToUInt32( ), rng.Start.ToUInt32( ), rng.End.ToUInt32( ) ); CHECKS.ASSERT( AddressMath.IsGreaterThanOrEqual( rng.End, ptrEnd ), "The end of the target range [{0:X8}-{1:X8}] does not belong to the chunk [{2:X8}-{3:X8}]", ptrStart.ToUInt32( ), ptrEnd.ToUInt32( ), rng.Start.ToUInt32( ), rng.End.ToUInt32( ) ); HeapRange rngPrev = CanMergeWithPrevious( pos, rng ); HeapRange rngNext = CanMergeWithNext( pos, rng ); bool fFlushToBottom = ( ptrStart == rng.Start ); bool fFlushToTop = ( ptrEnd == rng.End ); if( fFlushToBottom && fFlushToTop ) { // // Convert the whole chunk to allocated. // rng.Attributes |= Runtime.MemoryAttributes.Allocated; if( rngNext != null ) { rng.End = rngNext.End; m_heap.RemoveAt( pos + 1 ); } if( rngPrev != null ) { rngPrev.End = rng.End; m_heap.RemoveAt( pos ); } } else if( fFlushToBottom ) { if( rngPrev != null ) { // // Update the boundary between allocated/unallocated chunks. // rngPrev.End = ptrEnd; rng.Start = ptrEnd; } else { HeapRange newAllocatedRng = rng.SliceAsAllocated( ptrStart, ptrEnd ); m_heap.Insert( pos, newAllocatedRng ); rng.Start = ptrEnd; } } else if( fFlushToTop ) { if( rngNext != null ) { // // Update the boundary between unallocated/allocated chunks. // rngNext.Start = ptrStart; rng.End = ptrStart; } else { HeapRange newAllocatedRng = rng.SliceAsAllocated( ptrStart, ptrEnd ); m_heap.Insert( pos + 1, newAllocatedRng ); rng.End = ptrStart; } } else { HeapRange newAllocatedRng = rng.SliceAsAllocated( ptrStart, ptrEnd ); HeapRange newUnallocatedRng = rng.SliceAsNotAllocated( ptrEnd, rng.End ); m_heap.Insert( pos + 1, newAllocatedRng ); m_heap.Insert( pos + 2, newUnallocatedRng ); rng.End = ptrStart; } } private HeapRange CanMergeWithPrevious( int pos, HeapRange rng ) { if( pos > 0 ) { HeapRange rngPrev = m_heap[ pos - 1 ]; if( rngPrev.End == rng.Start && rngPrev.SectionName == rng.SectionName && rngPrev.Attributes == ( rng.Attributes | Runtime.MemoryAttributes.Allocated ) && rngPrev.Usage == rng.Usage ) { return rngPrev; } } return null; } private HeapRange CanMergeWithNext( int pos, HeapRange rng ) { if( pos + 1 < m_heap.Count ) { HeapRange rngNext = m_heap[ pos + 1 ]; if( rngNext.Start == rng.End && rngNext.SectionName == rng.SectionName && rngNext.Attributes == ( rng.Attributes | Runtime.MemoryAttributes.Allocated ) && rngNext.Usage == rng.Usage ) { return rngNext; } } return null; } } //--// // // State // private TypeSystemForCodeTransformation m_typeSystem; private List < Runtime.Memory.Range > m_memoryBlocks; private List < Runtime.Memory.Range > m_availableMemory; private SortedLinkerHeap m_sortedLinkerHeapForCode; private SortedLinkerHeap m_sortedLinkerHeap; private GrowOnlyHashTable< ControlFlowGraphStateForCodeTransformation , CompilationState > m_methodCompilationState; private GrowOnlyHashTable< object , List< CodeConstant > > m_codeConstants; private GrowOnlyHashTable< DataManager.DataDescriptor , SequentialRegion > m_dataDescriptors; private GrowOnlyHashTable m_externalDataRegions; private CodeMap.ReverseIndex[] m_reverseCodeMapIndex; private SourceCodeTracker m_sourceCodeTracker; // // These fields are not persisted. // private GrowOnlyHashTable< Operator , BranchEncodingLevel > m_relocationConstraintsForUnconditionalBranches; private GrowOnlyHashTable< Operator , BranchEncodingLevel > m_relocationConstraintsForConditionalBranches; private GrowOnlyHashTable< Operator , ConstantAddressEncodingLevel > m_relocationConstraintsForConstants; private Queue < CompilationState > m_pendingCode; private Queue < DataManager.DataDescriptor > m_pendingDataDescriptors; private Queue < DataManager.DataDescriptor > m_pendingExternalDataDescriptors; private GrowOnlyHashTable< Operator , List< BasicBlock > > m_adjacencyNeeds; private GrowOnlyHashTable< SequentialRegion , List< CodeConstant > > m_regionToCodeConstants; private List < CodeConstant > m_pendingConstants; private InstructionSet m_encoder; // // Constructor Methods // private Core( ) // Default constructor required by TypeSystemSerializer. { m_memoryBlocks = new List( ); m_availableMemory = new List( ); m_methodCompilationState = HashTableFactory.NewWithReferenceEquality( ); m_codeConstants = HashTableFactory.New>( ); m_dataDescriptors = HashTableFactory.NewWithReferenceEquality( ); m_externalDataRegions = HashTableFactory.New( ); m_sourceCodeTracker = new SourceCodeTracker( ); m_relocationConstraintsForUnconditionalBranches = HashTableFactory.NewWithReferenceEquality( ); m_relocationConstraintsForConditionalBranches = HashTableFactory.NewWithReferenceEquality( ); m_relocationConstraintsForConstants = HashTableFactory.NewWithReferenceEquality( ); m_pendingCode = new Queue( ); m_pendingDataDescriptors = new Queue( ); m_pendingExternalDataDescriptors = new Queue( ); m_adjacencyNeeds = HashTableFactory.NewWithReferenceEquality>( ); m_regionToCodeConstants = HashTableFactory.NewWithReferenceEquality>( ); m_pendingConstants = new List( ); } internal Core( TypeSystemForCodeTransformation typeSystem ) : this( ) { m_typeSystem = typeSystem; SourceCodeTracker sct = typeSystem.GetSourceCodeTracker( ); if( sct != null ) { m_sourceCodeTracker.Merge( sct ); } } // // Helper Methods // public void ApplyTransformation( TransformationContextForCodeTransformation context ) { CHECKS.ASSERT( m_pendingCode .Count == 0, "Cannot apply transformation to ImageBuilder while there are pending compilations" ); CHECKS.ASSERT( m_pendingDataDescriptors.Count == 0, "Cannot apply transformation to ImageBuilder while there are pending compilations" ); context.Push( this ); context.Transform ( ref m_typeSystem ); context.Transform ( ref m_memoryBlocks ); context.Transform ( ref m_availableMemory ); context.Transform ( ref m_methodCompilationState ); context.Transform ( ref m_codeConstants ); context.Transform ( ref m_dataDescriptors ); context.Transform ( ref m_externalDataRegions ); context.TransformGeneric( ref m_sourceCodeTracker ); context.TransformGeneric( ref m_reverseCodeMapIndex ); context.Pop( ); } //--// internal void DropCompileTimeObjects( ) { foreach( var reg in this.SortedRegions ) { var lst = reg.AnnotationList; for( int i = 0; i < lst.Count; i++ ) { var an = lst[ i ]; if( an.IsCompileTimeAnnotation ) { lst.RemoveAt( i-- ); } } } } //--// public InstructionSet GetInstructionSetProvider( ) { if( m_encoder == null ) { m_encoder = m_typeSystem.PlatformAbstraction.GetInstructionSetProvider( ); } return m_encoder; } //--// public CompilationState TryToGetCompilationState( BasicBlock bb ) { return TryToGetCompilationState( ( ControlFlowGraphStateForCodeTransformation )bb.Owner ); } public CompilationState GetCompilationState( BasicBlock bb ) { return GetCompilationState( ( ControlFlowGraphStateForCodeTransformation )bb.Owner ); } //--// public CompilationState TryToGetCompilationState( ControlFlowGraphStateForCodeTransformation cfg ) { CompilationState res; m_methodCompilationState.TryGetValue( cfg, out res ); return res; } public CompilationState GetCompilationState( ControlFlowGraphStateForCodeTransformation cfg ) { CompilationState res = TryToGetCompilationState( cfg ); if( res == null ) { throw TypeConsistencyErrorException.Create( "Unexpected reference to method '{0}'", cfg.Method.ToShortString( ) ); } return res; } //--// public SequentialRegion AddObject( DataManager.DataDescriptor dd ) { SequentialRegion reg; if( m_dataDescriptors.TryGetValue( dd, out reg ) == false ) { reg = new SequentialRegion( this, dd, m_typeSystem.PlatformAbstraction.GetMemoryRequirements( dd ) ); m_dataDescriptors[ dd ] = reg; m_pendingDataDescriptors.Enqueue( dd ); } return reg; } public SequentialRegion AddExternalData( ExternalDataDescriptor.IExternalDataContext ctx, uint size ) { SequentialRegion reg; if( m_externalDataRegions.TryGetValue( ctx, out reg ) == false ) { ExternalDataDescriptor edd = new ExternalDataDescriptor( m_typeSystem.DataManagerInstance, ctx, DataManager.Attributes.Mutable, null ); reg = new SequentialRegion( this, edd, m_typeSystem.PlatformAbstraction.GetMemoryRequirements( edd ) ); m_externalDataRegions[ ctx ] = reg; m_pendingExternalDataDescriptors.Enqueue( edd ); } return reg; } //--// internal bool ProcessPending( ) { bool fNoNewMethod = true; while( true ) { if( m_pendingCode.Count > 0 ) { CompilationState cs = m_pendingCode.Dequeue( ); cs.CompileMethod( ); fNoNewMethod = false; continue; } if( m_pendingDataDescriptors.Count > 0 ) { DataManager.DataDescriptor dd = m_pendingDataDescriptors.Dequeue( ); #if ARMv7M_BUILD__LLVM_IR_ONLY if( TypeSystem.PlatformAbstraction.CodeGenerator != InstructionSetVersion.CodeGenerator_LLVM ) #endif { dd.Write( m_dataDescriptors[ dd ] ); } continue; } if( m_pendingExternalDataDescriptors.Count > 0 ) { ExternalDataDescriptor dd = ( ExternalDataDescriptor )m_pendingExternalDataDescriptors.Dequeue( ); #if ARMv7M_BUILD__LLVM_IR_ONLY if( TypeSystem.PlatformAbstraction.CodeGenerator != InstructionSetVersion.CodeGenerator_LLVM ) #endif { dd.Write( m_externalDataRegions[ dd.ExternContext ] ); } continue; } break; } return fNoNewMethod; } //--// internal void RestartCompilation( ) { foreach( var cs in m_methodCompilationState.Values ) { cs.Dispose( ); } //--// // reset the import data sections ImplementExternalMethods.ResetExternalDataDescriptors( ); m_methodCompilationState.Clear( ); m_codeConstants.Clear( ); m_dataDescriptors.Clear( ); m_externalDataRegions.Clear( ); m_pendingCode.Clear( ); m_pendingDataDescriptors.Clear( ); m_pendingExternalDataDescriptors.Clear( ); m_adjacencyNeeds.Clear( ); m_regionToCodeConstants.Clear( ); m_pendingConstants.Clear( ); m_sortedLinkerHeapForCode = new SortedLinkerHeap( m_memoryBlocks ); //--// m_sortedLinkerHeap = m_sortedLinkerHeapForCode; } public void CompileBasicBlock( BasicBlock bb ) { CompileMethod( ( ControlFlowGraphStateForCodeTransformation )bb.Owner ); } public void CompileMethod( ControlFlowGraphStateForCodeTransformation cfg ) { if( cfg != null && m_methodCompilationState.ContainsKey( cfg ) == false ) { CompilationState cs = m_typeSystem.PlatformAbstraction.CreateCompilationState( this, cfg ); m_methodCompilationState[ cfg ] = cs; m_pendingCode.Enqueue( cs ); } } public CodeConstant CompileCodeConstant( object entity, SequentialRegion regCode ) { CodeConstant cc = new CodeConstant( entity ); SequentialRegion reg = new SequentialRegion( this, cc, regCode.PlacementRequirements ); if( entity is DataManager.DataDescriptor ) { DataManager.DataDescriptor dd = ( DataManager.DataDescriptor )entity; if( dd.Context is ValueTypeRepresentation ) { #if ARMv7M_BUILD__LLVM_IR_ONLY if( TypeSystem.PlatformAbstraction.CodeGenerator != InstructionSetVersion.CodeGenerator_LLVM ) #endif { dd.Write( reg ); } } else { SequentialRegion.Section sec = reg.GetSectionOfVariableSize( sizeof( uint ) ); sec.WritePointerToDataDescriptor( dd ); } } else if( entity is BasicBlock ) { BasicBlock bb = ( BasicBlock )entity; SequentialRegion.Section sec = reg.GetSectionOfVariableSize( sizeof( uint ) ); sec.WritePointerToBasicBlock( bb ); } else { SequentialRegion.Section sec = reg.GetSectionOfVariableSize( sizeof( uint ) ); if( sec.WriteGeneric( entity ) == false ) { throw TypeConsistencyErrorException.Create( "Unexpected value for code constant: {0}", entity ); } } cc.Region = reg; HashTableWithListFactory.AddUnique( m_regionToCodeConstants, regCode, cc ); CompilationState cs = GetCompilationState( ( BasicBlock )regCode.Context ); cs.TrackRegion( reg ); return cc; } public void RecordAdjacencyNeed( Operator op, BasicBlock bbTarget ) { HashTableWithListFactory.AddUnique( m_adjacencyNeeds, op, bbTarget ); } //--// internal bool AssignAbsoluteAddressesToCode( ) { // // We want to deal only with code at this phase. // The data descriptors will be recreated back later. // m_dataDescriptors.Clear( ); //--// // // First of all, assign an absolute address to some hardware handler, so they are placed at the beginning of image. // bool fDone = true; fDone &= AssignAbsoluteAddresses( GetHandler( Runtime.HardwareException.VectorTable ), true ); fDone &= AssignAbsoluteAddresses( GetHandler( Runtime.HardwareException.Bootstrap ), false ); //--// // // Assign an address to the "hot" code first. // foreach( ControlFlowGraphStateForCodeTransformation cfg in m_methodCompilationState.Keys ) { fDone &= AssignAbsoluteAddresses( cfg, false ); } // // Then to "cold" code. // foreach( ControlFlowGraphStateForCodeTransformation cfg in m_methodCompilationState.Keys ) { fDone &= AssignAbsoluteAddresses( cfg, true ); } //--// EnsureNoUnassignedRegions( ); fDone &= VerifyAdjacencyNeeds( ); return fDone; } private bool AssignAbsoluteAddresses( ControlFlowGraphStateForCodeTransformation cfg, bool fIncludeColdCode ) { if(cfg != null) { CompilationState cs = GetCompilationState( cfg.EntryBasicBlock ); cs.AssignAbsoluteAddresses( fIncludeColdCode ); return FlushConstants( ); } return true; } internal void RewindToDataDescriptorsPhase( ) { m_sortedLinkerHeap = new SortedLinkerHeap( m_sortedLinkerHeapForCode ); m_dataDescriptors.Clear( ); } internal bool ImportDataDescriptors( ) { GrowOnlySet< DataManager.DataDescriptor > dataDescriptors = SetFactory.NewWithReferenceEquality( ); EnumerateImageAnnotations( delegate( ImageAnnotation an ) { if( an.Target is DataManager.DataDescriptor ) { DataManager.DataDescriptor dd = ( DataManager.DataDescriptor )an.Target; dataDescriptors.Insert( dd ); } return true; } ); foreach( DataManager.DataDescriptor dd in dataDescriptors ) { AddObject( dd ); } ExternalDataDescriptor.IExternalDataContext[] edcs = m_externalDataRegions.KeysToArray( ); m_externalDataRegions.Clear( ); foreach( ExternalDataDescriptor.IExternalDataContext edc in edcs ) { AddExternalData( edc, ( uint )edc.RawData.Length ); } return ProcessPending( ); } internal void AssignAbsoluteAddressesToDataDescriptors( ) { foreach( DataManager.DataDescriptor dd in m_dataDescriptors.Keys ) { m_dataDescriptors[ dd ].AssignAbsoluteAddress( ); } foreach( ExternalDataDescriptor.IExternalDataContext dd in m_externalDataRegions.Keys ) { m_externalDataRegions[ dd ].AssignAbsoluteAddress( ); } //--// EnsureNoUnassignedRegions( ); } [System.Diagnostics.Conditional( "DEBUG" )] private void EnsureNoUnassignedRegions( ) { EnumerateRegions( delegate( SequentialRegion reg ) { CHECKS.ASSERT( reg.IsBaseAddressAssigned || reg.Context is ExternalDataDescriptor, "Found region not assigned an address: {0}", reg ); return true; } ); } //--// private ControlFlowGraphStateForCodeTransformation GetHandler( Runtime.HardwareException he ) { MethodRepresentation md = m_typeSystem.TryGetHandler( he ); if( md != null ) { return TypeSystemForCodeTransformation.GetCodeForMethod( md ); } return null; } //--// internal void PushRegionConstantsToPendingList( SequentialRegion reg ) { List< CodeConstant > lst; if( m_regionToCodeConstants.TryGetValue( reg, out lst ) ) { foreach( CodeConstant ccToAssign in lst ) { if( FindDuplicateForConstant( ccToAssign ) == false ) { m_pendingConstants.Add( ccToAssign ); } } } } private bool FindDuplicateForConstant( CodeConstant ccToAssign ) { SequentialRegion ccRegToAssign = ccToAssign.Region; ImageAnnotation anToAssign = ccToAssign.Source; List< CodeConstant > lstAssigned; if( m_codeConstants.TryGetValue( ccToAssign.Target, out lstAssigned ) ) { foreach( CodeConstant cc in lstAssigned ) { SequentialRegion ccReg = cc.Region; if( ccReg.PlacementRequirements.IsCompatible( ccRegToAssign.PlacementRequirements ) ) { if( anToAssign.CanRelocateToAddress( anToAssign.InsertionAddress, ccReg.ExternalAddress ) ) { ccRegToAssign.BaseAddress = ccReg.BaseAddress; lstAssigned.Add( ccToAssign ); return true; } } } } return false; } private bool FlushConstants( ) { bool fDone = true; foreach( CodeConstant ccToAssign in m_pendingConstants ) { if( FindDuplicateForConstant( ccToAssign ) == false ) { SequentialRegion regToAssign = ccToAssign.Region; ImageAnnotation anToAssign = ccToAssign.Source; regToAssign.AssignAbsoluteAddress( ); if( anToAssign.ApplyRelocation( ) ) { HashTableWithListFactory.AddUnique( m_codeConstants, ccToAssign.Target, ccToAssign ); } else { fDone = false; } } } m_pendingConstants.Clear( ); return fDone; } private bool VerifyAdjacencyNeeds( ) { bool fDone = true; foreach( Operator op in m_adjacencyNeeds.Keys ) { var regSource = GetAssociatedRegion( op.BasicBlock ); var endAddress = regSource.EndAddress; foreach( BasicBlock bb in m_adjacencyNeeds[ op ] ) { var regTarget = GetAssociatedRegion( bb ); if( endAddress != regTarget.BaseAddress ) { IncreaseEncodingLevelForBranch( op, bb, false ); fDone = false; break; } } } return fDone; } //--// internal bool ApplyRelocation( ) { bool fRes = true; EnumerateRegions( delegate( SequentialRegion reg ) { fRes &= reg.ApplyRelocation( ); return true; } ); return fRes; } internal bool CreateCodeMaps( ) { bool fModified = false; foreach( CompilationState cs in m_methodCompilationState.Values ) { fModified |= cs.CreateCodeMaps( ); } if( fModified == false ) { BuildReverseCodeMapIndex( ); // // Only generate the lookup index if the corresponding field is referenced by the application. // FieldRepresentation fd = m_typeSystem.WellKnownFields.CodeMap_LookupAddress; if( fd != null ) { InstanceFieldRepresentation fd2 = m_typeSystem.GetEntityFromGlobalRoot( fd ); if( fd2 != null ) { DataManager.ObjectDescriptor gr = m_typeSystem.GenerateGlobalRoot( ); DataManager.ArrayDescriptor ad = ( DataManager.ArrayDescriptor )gr.Get( fd2 ); CodeMap.ReverseIndex[] arrayOld = ad != null ? ( CodeMap.ReverseIndex[] )ad.Source : null; CodeMap.ReverseIndex[] arrayNew = m_reverseCodeMapIndex; if( CodeMap.ReverseIndex.SameArrayContents( arrayOld, arrayNew ) == false ) { gr.ConvertAndSet( fd2, DataManager.Attributes.Constant, null, arrayNew ); fModified = true; } } } } return fModified == false; } internal bool CreateExceptionHandlingTables( ) { bool fModified = false; foreach( CompilationState cs in m_methodCompilationState.Values ) { fModified |= cs.CreateExceptionHandlingTables( ); } return fModified == false; } internal bool CreateAvailableMemoryTables( ) { bool fModified = false; // // BUGBUG #89: the m_forcedDevirtalizations member in TypeSystem currently does not serialization process!!! // if(m_typeSystem.ForcedDevirtualizations != null) { // // Only generate the lookup index if the corresponding field is referenced by the application. // InstanceFieldRepresentation fd = ( InstanceFieldRepresentation )m_typeSystem.WellKnownFields.Memory_m_availableMemory; if(fd != null) { TypeRepresentation td = fd.OwnerType; TypeRepresentation tdNew; if(m_typeSystem.ForcedDevirtualizations.TryGetValue( td, out tdNew ) == false) { throw TypeConsistencyErrorException.Create( "Cannot devirtualize type '{0}'", td ); } DataManager.ObjectDescriptor od = m_typeSystem.GenerateSingleton( tdNew, DataManager.Attributes.Constant | DataManager.Attributes.SuitableForConstantPropagation ); DataManager.ArrayDescriptor ad = ( DataManager.ArrayDescriptor )od.Get( fd ); Runtime.Memory.Range[] arrayOld = ad != null ? ( Runtime.Memory.Range[] )ad.Source : null; Runtime.Memory.Range[] arrayNew = m_availableMemory.ToArray( ); Array.Sort( arrayNew, ( left, right ) => AddressMath.Compare( left.Start, right.Start ) ); if(Runtime.Memory.Range.ArrayEquals( arrayOld, arrayNew ) == false) { od.ConvertAndSet( fd, DataManager.Attributes.Constant, null, arrayNew ); fModified = true; } } } return fModified == false; } internal bool CreateImageRelocationData( ) { bool fModified = false; // // Only generate the lookup index if the corresponding field is referenced by the application. // InstanceFieldRepresentation fd = ( InstanceFieldRepresentation )m_typeSystem.WellKnownFields.Memory_m_relocationInfo; if( fd != null ) { TypeRepresentation td = fd.OwnerType; TypeRepresentation tdNew; if( m_typeSystem.ForcedDevirtualizations.TryGetValue( td, out tdNew ) == false ) { throw TypeConsistencyErrorException.Create( "Cannot devirtualize type '{0}'", td ); } DataManager.ObjectDescriptor od = m_typeSystem.GenerateSingleton( tdNew, DataManager.Attributes.Constant | DataManager.Attributes.SuitableForConstantPropagation ); DataManager.ArrayDescriptor ad = ( DataManager.ArrayDescriptor )od.Get( fd ); Runtime.Memory.RelocationInfo[] arrayOld = ad != null ? ( Runtime.Memory.RelocationInfo[] )ad.Source : null; Runtime.Memory.RelocationInfo[] arrayNew = BuildImageRelocationData( ); if( Runtime.Memory.RelocationInfo.ArrayEquals( arrayOld, arrayNew ) == false ) { Abstractions.PlacementRequirements pr = new Abstractions.PlacementRequirements( sizeof( uint ), 0 ); pr.AddConstraint( Runtime.MemoryUsage.Bootstrap ); od.PlacementRequirements = pr; od.ConvertAndSet( fd, DataManager.Attributes.Constant, pr, arrayNew ); InstanceFieldRepresentation fd2 = ( InstanceFieldRepresentation )m_typeSystem.WellKnownFields.RelocationInfo_m_data; if( fd2 != null ) { DataManager.ArrayDescriptor adSub = ( DataManager.ArrayDescriptor )od.Get( fd ); adSub.RefreshValues( null ); pr = new Abstractions.PlacementRequirements( sizeof( uint ), 0 ); pr.AddConstraint( Runtime.MemoryUsage.Relocation ); for( int i = 0; i < arrayNew.Length; i++ ) { DataManager.ObjectDescriptor odSub = ( DataManager.ObjectDescriptor )adSub.Get( i ); odSub.RefreshValues( null ); DataManager.ArrayDescriptor adSub2 = ( DataManager.ArrayDescriptor )odSub.Get( fd2 ); if( adSub2 != null ) { adSub2.PlacementRequirements = pr; } } } fModified = true; } } return fModified == false; } internal void CommitMemoryMap( ) { m_availableMemory = m_sortedLinkerHeap.Commit( ); } internal void CacheSourceCore( ) { EnumerateImageAnnotations( delegate( ImageAnnotation an ) { Operator op = an.Target as IR.Operator; if( op != null ) { Debugging.DebugInfo di = op.DebugInfo; if( di != null ) { SourceCodeTracker.SourceCode sc = m_sourceCodeTracker.GetSourceCode( di.SrcFileName ); if( sc != null ) { sc.UsingCachedValues = true; } } } return true; } ); } //--// private void BuildReverseCodeMapIndex( ) { List< CodeMap.ReverseIndex > lst = new List( ); UIntPtr lastAddress = new UIntPtr( ); CodeMap lastCodeMap = null; foreach( SequentialRegion reg in this.SortedRegions ) { BasicBlock bb = reg.Context as BasicBlock; if( bb != null ) { CodeMap codeMap = bb.Owner.Method.CodeMap; if( codeMap != lastCodeMap ) { CodeMap.ReverseIndex idx; idx.Address = reg.BaseAddress; idx.Code = codeMap; lst.Add( idx ); lastCodeMap = codeMap; } lastAddress = reg.EndAddress; } } if( lastCodeMap != null ) { CodeMap.ReverseIndex idx; idx.Address = lastAddress; idx.Code = null; lst.Add( idx ); } //--// m_reverseCodeMapIndex = lst.ToArray( ); } private Runtime.Memory.RelocationInfo[] BuildImageRelocationData( ) { List< Runtime.Memory.RelocationInfo > lst = new List( ); UIntPtr baseAddress = new UIntPtr( ); UIntPtr lastAddress = new UIntPtr( ); MemoryRange buffer = null; foreach( SequentialRegion reg in this.SortedRegions ) { if( ShouldRelocate( reg.BaseAddress.ToUInt32( ) ) ) { if( buffer != null ) { int distance = AddressMath.Distance( lastAddress, reg.BaseAddress ); if( distance > 0 ) { AddRelocation( lst, baseAddress, buffer ); buffer = null; } else if( distance < 0 ) { // // Overlap, rewind the buffer. // buffer.Rewind( -distance ); lastAddress = reg.BaseAddress; } } if( buffer == null ) { baseAddress = reg.BaseAddress; buffer = new MemoryRange( ); } lastAddress = reg.PayloadEndAddress; buffer.Append( reg.ToArray( ) ); } } if( buffer != null ) { AddRelocation( lst, baseAddress, buffer ); } return lst.ToArray( ); } private static void AddRelocation( List lst, UIntPtr baseAddress, MemoryRange buffer ) { byte[] data8 = buffer.ToArray( ); uint[] data32 = new uint[ ( data8.Length + sizeof( uint ) - 1 ) / sizeof( uint ) ]; Buffer.BlockCopy( data8, 0, data32, 0, data8.Length ); int size = data32.Length; int pos = 0; int posStart = 0; while( true ) { while( pos < size ) { if( data32[ pos ] == 0 ) { break; } pos++; } int posZero = pos; while( posZero < size ) { if( data32[ posZero ] != 0 ) { break; } posZero++; } if( posZero < size && posZero - pos < 4 ) { // // Run of zeros is too short, look for the next one. // pos = posZero; continue; } if( posStart != pos ) { lst.Add( new Runtime.Memory.RelocationInfo( AddressMath.Increment( baseAddress, ( uint )posStart * sizeof( uint ) ), data32, posStart, pos - posStart ) ); posStart = pos; } if( posStart != posZero ) { lst.Add( new Runtime.Memory.RelocationInfo( AddressMath.Increment( baseAddress, ( uint )posStart * sizeof( uint ) ), ( uint )( posZero - posStart ) ) ); pos = posZero; posStart = posZero; } if( posStart == size ) { break; } } } //--// public List CollectImage( ) { List< Configuration.Environment.ImageSection > lst = new List( ); SequentialRegion[] regArray = this.SortedRegions; Runtime.Memory.Range currentBlock = null; MemoryRange currentRange = null; uint currentRangeAddress = 0; uint currentRangeAddressEnd = 0; Abstractions.Platform pa = m_typeSystem.PlatformAbstraction; for( int idx = 0; idx < regArray.Length; idx++ ) { SequentialRegion reg = regArray[ idx ]; if( reg.Size > 0 ) { byte[] payload = reg.ToArray( ); uint executeAddress = reg.BaseAddress.ToUInt32( ); Runtime.Memory.Range rng = FindMemoryBlock( executeAddress ); uint physicalAddress = executeAddress; uint physicalAddressEnd; if( rng.ExtensionHandler != null ) { object hnd = Activator.CreateInstance( rng.ExtensionHandler ); if( hnd is Configuration.Environment.IMemoryMapper ) { Configuration.Environment.IMemoryMapper itf = ( Configuration.Environment.IMemoryMapper )hnd; physicalAddress = itf.GetUncacheableAddress( physicalAddress ); } } physicalAddressEnd = physicalAddress + ( uint )payload.Length; if( rng != null ) { bool fMerge = false; bool fAppend = true; // If no current range or disjoint ranges, append new one. if( currentBlock != null && currentBlock.Equals( rng ) ) { CHECKS.ASSERT( currentRangeAddress <= physicalAddress, "Internal failure: regions not sorted out of SortedRegion: {0:X8} preceeds {1:X8}", currentRangeAddress, physicalAddress ); int gap = ( int )( physicalAddress - currentRangeAddressEnd ); if( gap == 0 ) // Adjacent? { // // Concatenate. // fMerge = true; } else if( gap < 0 ) // Overlapped? { int gapEnd = ( int )( physicalAddressEnd - currentRangeAddressEnd ); int offset = ( int )( physicalAddress - currentRangeAddress ); if( gapEnd <= 0 ) // Fully contained? { // // Verify the payload matches. // if( currentRange.Match( offset, payload, 0, payload.Length ) == false ) { throw TypeConsistencyErrorException.Create( "Inconsistency image: overlapping regions have different payloads" ); } fAppend = false; } else // Then partially contained. { // // Verify the overlapping payload matches and merge the rest. // if( currentRange.Match( offset, payload, 0, payload.Length - gapEnd ) == false ) { throw TypeConsistencyErrorException.Create( "Inconsistency image: overlapping regions have different payloads" ); } payload = ArrayUtility.ExtractSliceFromNotNullArray( payload, payload.Length - gapEnd, gapEnd ); fMerge = true; } } } if( fAppend ) { if( fMerge ) { currentRange.Append( payload ); currentRangeAddressEnd += ( uint )payload.Length; } else { AppendToImageIfNeeded( lst, currentBlock, currentRange, currentRangeAddress ); currentBlock = rng; currentRange = new MemoryRange( payload ); currentRangeAddress = physicalAddress; currentRangeAddressEnd = physicalAddressEnd; } } } } } AppendToImageIfNeeded( lst, currentBlock, currentRange, currentRangeAddress ); return lst; } private void AppendToImageIfNeeded( List lst, Runtime.Memory.Range currentBlock, MemoryRange currentRange, uint currentRangeAddress ) { if( currentBlock != null ) { lst.Add( new Configuration.Environment.ImageSection( currentRangeAddress, currentRange.ToArray( ), currentBlock.SectionName, currentBlock.Attributes, currentBlock.Usage ) ); } } //--// internal Runtime.Memory.Range FindMemoryBlock( uint address ) { for( int i = 0; i < m_memoryBlocks.Count; i++ ) { Runtime.Memory.Range mr = m_memoryBlocks[ i ]; if( mr.Contains( address ) ) { return mr; } } return null; } internal bool ShouldRelocate( uint address ) { for( int i = 0; i < m_memoryBlocks.Count; i++ ) { Runtime.Memory.Range mr = m_memoryBlocks[ i ]; if( mr.Contains( address ) ) { if( ( mr.Usage & Runtime.MemoryUsage.Relocation ) != 0 || ( mr.Attributes & Runtime.MemoryAttributes.LoadedAtEntrypoint ) != 0 ) { return false; } else { return true; } } } return false; } internal bool ReserveRangeOfMemory( uint size, uint offset, Abstractions.PlacementRequirements pr, out UIntPtr address ) { return m_sortedLinkerHeap.Allocate( size, offset, pr, out address ); } //--// public BranchEncodingLevel GetEncodingLevelForBranch( Operator op, BasicBlock bb, bool fConditional ) { var ht = fConditional ? m_relocationConstraintsForConditionalBranches : m_relocationConstraintsForUnconditionalBranches; BranchEncodingLevel val; if( ht.TryGetValue( op, out val ) == false ) { val = fConditional ? BranchEncodingLevel.ShortBranch : BranchEncodingLevel.Skip; } // // Branch to self? Don't remove. // if( op.BasicBlock == bb ) { if( val == BranchEncodingLevel.Skip ) val++; } return val; } public void IncreaseEncodingLevelForBranch( Operator op, BasicBlock bb, bool fConditional ) { IncreaseEncodingLevelForBranch( op, bb, fConditional, BranchEncodingLevel.Skip ); } public void IncreaseEncodingLevelForBranch( Operator op, BasicBlock bb, bool fConditional, BranchEncodingLevel minLevel ) { BranchEncodingLevel val = GetEncodingLevelForBranch( op, bb, fConditional ); if( val < minLevel ) { val = minLevel; } if( val != BranchEncodingLevel.Max ) { val++; } var ht = fConditional ? m_relocationConstraintsForConditionalBranches : m_relocationConstraintsForUnconditionalBranches; ht[ op ] = val; } //--// public ConstantAddressEncodingLevel GetEncodingLevelForConstant( Operator op ) { ConstantAddressEncodingLevel val; if( m_relocationConstraintsForConstants.TryGetValue( op, out val ) == false ) { val = ConstantAddressEncodingLevel.Immediate; } return val; } public void IncreaseEncodingLevelForConstant( Operator op ) { IncreaseEncodingLevelForConstant( op, ConstantAddressEncodingLevel.Immediate ); } public void IncreaseEncodingLevelForConstant( Operator op, ConstantAddressEncodingLevel minLevel ) { ConstantAddressEncodingLevel val = GetEncodingLevelForConstant( op ); if( val < minLevel ) { val = minLevel; } if( val != ConstantAddressEncodingLevel.Max ) val++; m_relocationConstraintsForConstants[ op ] = val; } //--// public uint Resolve( object marker ) { SequentialRegion reg = GenericGetAssociatedRegion( marker ); if( reg == null ) { throw TypeConsistencyErrorException.Create( "Cannot resolve relocation information for {0}", marker ); } return reg.ExternalAddress; } private SequentialRegion GenericGetAssociatedRegion( object marker ) { SequentialRegion reg; if( marker is CodePointer ) { CodePointer cp = ( CodePointer )marker; marker = m_typeSystem.DataManagerInstance.GetCodePointerFromUniqueID( cp.Target ); } if( marker is SequentialRegion ) { reg = ( SequentialRegion )marker; } else if( marker is ControlFlowGraphStateForCodeTransformation ) { reg = GetAssociatedRegion( ( ControlFlowGraphStateForCodeTransformation )marker ); } else if( marker is BasicBlock ) { reg = GetAssociatedRegion( ( BasicBlock )marker ); } else if( marker is DataManager.DataDescriptor ) { reg = GetAssociatedRegion( ( DataManager.DataDescriptor )marker ); } else if( marker is ExternalDataDescriptor.IExternalDataContext ) { reg = GetAssociatedRegion( ( ExternalDataDescriptor.IExternalDataContext )marker ); } else if( marker is Operator ) { reg = GetAssociatedRegion( ( ( Operator )marker ).BasicBlock ); } else if( marker is CodeConstant ) { CodeConstant cc = ( CodeConstant )marker; reg = cc.Region; } else { reg = null; } return reg; } public SequentialRegion GetAssociatedRegion( ControlFlowGraphStateForCodeTransformation cfg ) { return GetAssociatedRegion( cfg.EntryBasicBlock ); } public SequentialRegion GetAssociatedRegion( BasicBlock bb ) { CompilationState cs = TryToGetCompilationState( bb ); return cs != null ? cs.GetRegion( bb ) : null; } public SequentialRegion GetAssociatedRegion( DataManager.DataDescriptor dd ) { SequentialRegion reg; m_dataDescriptors.TryGetValue( dd, out reg ); return reg; } public SequentialRegion GetAssociatedRegion( ExternalDataDescriptor.IExternalDataContext edc ) { SequentialRegion reg; m_externalDataRegions.TryGetValue( edc, out reg ); return reg; } public SequentialRegion GetAssociatedRegion( ConstantExpression ex ) { return GenericGetAssociatedRegion( ex.Value ); } public List GetAssociatedRegions( ControlFlowGraphStateForCodeTransformation cfg, bool fIncludeConstants ) { List< SequentialRegion > lst = new List( ); CompilationState cs = TryToGetCompilationState( cfg ); if( cs != null ) { foreach( SequentialRegion reg in cs.AssociatedRegions ) { if( reg.Context is CodeConstant ) { if( fIncludeConstants == false ) { continue; } } lst.Add( reg ); } } return lst; } //--// public static SequentialRegion[] SortRegions( List lst ) { SequentialRegion[] regArray = lst.ToArray( ); SortRegions( regArray ); return regArray; } public static void SortRegions( SequentialRegion[] regArray ) { Array.Sort( regArray, delegate( SequentialRegion left, SequentialRegion right ) { int res = left.ExternalAddress.CompareTo( right.ExternalAddress ); if( res != 0 ) { return res; } res = left.EndAddress.ToUInt32( ).CompareTo( right.EndAddress.ToUInt32( ) ); if( res != 0 ) { return res; } BasicBlock bbLeft = left.Context as BasicBlock; BasicBlock bbRight = right.Context as BasicBlock; if( bbLeft != null && bbRight != null ) { res = bbLeft.SpanningTreeIndex.CompareTo( bbRight.SpanningTreeIndex ); if( res != 0 ) { return res; } } return 0; } ); } public static SequentialRegion ResolveAddressToRegion( SequentialRegion[] regArray, uint address ) { int low = 0; int high = regArray.Length - 1; while( low <= high ) { int mid = ( high + low ) / 2; SequentialRegion reg = regArray[ mid ]; if( address < reg.BaseAddress.ToUInt32( ) ) { high = mid - 1; } else if( address >= reg.EndAddress.ToUInt32( ) ) { low = mid + 1; } else { return reg; } } return null; } //--// public bool EnumerateRegions( SequentialRegionEnumerationCallback callback ) { foreach( CompilationState cs in m_methodCompilationState.Values ) { foreach( var reg in cs.BasicBlockRegions ) { if( callback( reg ) == false ) { return false; } } } foreach( object obj in m_codeConstants.Keys ) { foreach( CodeConstant cc in m_codeConstants[ obj ] ) { if( callback( cc.Region ) == false ) { return false; } } } foreach( SequentialRegion reg in m_dataDescriptors.Values ) { if( callback( reg ) == false ) { return false; } } foreach( SequentialRegion reg in m_externalDataRegions.Values ) { if( callback( reg ) == false ) { return false; } } return true; } public bool EnumerateImageAnnotations( ImageAnnotationEnumerationCallback callback ) { return EnumerateRegions( delegate( SequentialRegion reg ) { foreach( ImageAnnotation an in reg.AnnotationList ) { if( callback( an ) == false ) { return false; } } return true; } ); } //--// // // Access Methods // public TypeSystemForCodeTransformation TypeSystem { get { return m_typeSystem; } } public SequentialRegion Bootstrap { get { ControlFlowGraphStateForCodeTransformation cfg = TypeSystemForCodeTransformation.GetCodeForMethod( m_typeSystem.GetHandler( Runtime.HardwareException.Reset ) ); //// ControlFlowGraphStateForCodeTransformation cfg = TypeSystemForCodeTransformation.GetCodeForMethod( m_typeSystem.GetHandler( Runtime.HardwareException.Bootstrap ) ); return GetAssociatedRegion( cfg ); } } public List MemoryBlocks { get { return m_memoryBlocks; } } public List AvailableMemory { get { return m_availableMemory; } } public SourceCodeTracker SourceCodeTracker { get { return m_sourceCodeTracker; } } public CodeMap.ReverseIndex[] ReverseCodeMapIndex { get { return m_reverseCodeMapIndex; } } //--// public SequentialRegion[] SortedRegions { get { List< SequentialRegion > res = new List( ); EnumerateRegions( delegate( SequentialRegion reg ) { res.Add( reg ); return true; } ); SequentialRegion[] regArray = res.ToArray( ); SortRegions( regArray ); return regArray; } } // // Debug Methods // class Statistics { internal string m_text; internal int m_size; internal int m_count; } class CatalogItem { // // State // object m_context; int m_hashCode; int m_subIndex; string m_filePrefix; string m_fileSuffix; System.IO.StreamWriter m_stream; // // Constructor Methods // private CatalogItem( ) { } // // Helper Methods // internal static void Flush( GrowOnlyHashTable> catalog ) { GrowOnlySet< object > set = SetFactory.NewWithReferenceEquality( ); foreach( var lst in catalog.Values ) { foreach( CatalogItem item in lst ) { set.Insert( item.m_stream ); } } foreach( System.IO.StreamWriter stream in set ) { stream.Flush( ); stream.Close( ); } } internal static System.IO.StreamWriter GenerateStream( GrowOnlyHashTable> catalog, string baseDirectory, string filePrefix, string fileSuffix, object context, int hashCode ) { CatalogItem newItem = new CatalogItem( ); newItem.m_context = context; newItem.m_hashCode = hashCode; newItem.m_filePrefix = filePrefix; newItem.m_fileSuffix = fileSuffix; //--// List< CatalogItem > lst = HashTableWithListFactory.Create( catalog, hashCode ); foreach( CatalogItem item in lst ) { if( item.m_filePrefix == filePrefix && item.m_fileSuffix == fileSuffix && item.m_context.ToString( ) == context.ToString( ) ) { newItem.m_stream = item.m_stream; newItem.m_subIndex = item.m_subIndex; break; } newItem.m_subIndex = Math.Max( newItem.m_subIndex, item.m_subIndex + 1 ); } lst.Add( newItem ); //--// if( newItem.m_stream == null ) { newItem.m_stream = new System.IO.StreamWriter( System.IO.Path.Combine( baseDirectory, newItem.FileName ), false, System.Text.Encoding.ASCII ); } else { newItem.m_stream.WriteLine( ); newItem.m_stream.WriteLine( "############################################################" ); newItem.m_stream.WriteLine( ); } return newItem.m_stream; } // // Debug Methods // internal string FileName { get { string fmt = ( m_subIndex == 0 ) ? "{0}{1:X8}{3}" : "{0}{1:X8}_{2}{3}"; return string.Format( fmt, m_filePrefix, m_hashCode, m_subIndex, m_fileSuffix ); } } public override string ToString( ) { return string.Format( "{0} => {1}", m_context, this.FileName ); } } public void Disassemble( string baseDirectory ) { GrowOnlyHashTable< int, List< CatalogItem > > catalog = HashTableFactory.New>( ); if( System.IO.Directory.Exists( baseDirectory ) ) { System.IO.Directory.Delete( baseDirectory, true ); } System.IO.Directory.CreateDirectory( baseDirectory ); //--// Disassemble_Code( baseDirectory, catalog ); Disassemble_Data( baseDirectory, catalog ); Disassemble_Stats( baseDirectory, catalog ); CatalogItem.Flush( catalog ); //--// using( System.IO.StreamWriter textWriter = new System.IO.StreamWriter( System.IO.Path.Combine( baseDirectory, "__Index.txt" ), false, System.Text.Encoding.ASCII ) ) { List< string > output = new List( ); foreach( List< CatalogItem > lst in catalog.Values ) { foreach( CatalogItem item in lst ) { output.Add( item.ToString( ) ); } } output.Sort( ); foreach( var text in output ) { textWriter.WriteLine( text ); } } } private void Disassemble_Code( string baseDirectory, GrowOnlyHashTable> catalog ) { foreach( ControlFlowGraphStateForCodeTransformation cfg in m_methodCompilationState.Keys ) { CompilationState cs = m_methodCompilationState[ cfg ]; MethodRepresentation md = cfg.Method; CodeMap cm = md.CodeMap; string name = md.ToShortString( ); System.IO.StreamWriter textWriter = CatalogItem.GenerateStream( catalog, baseDirectory, "Code_", ".asm", cfg, name.GetHashCode( ) ); textWriter.WriteLine( "{0}", name ); if( cm != null ) { textWriter.WriteLine( ); textWriter.WriteLine( " CodeMap:" ); textWriter.WriteLine( ); foreach( CodeMap.Range rng in cm.Ranges ) { bool fFirst = true; foreach( string txt in rng.ToString( ).Split( new string[] { Environment.NewLine }, StringSplitOptions.RemoveEmptyEntries ) ) { if( fFirst ) { fFirst = false; textWriter.WriteLine( " {0}", txt ); } else { textWriter.WriteLine( " {0}", txt ); } } textWriter.WriteLine( ); } ExceptionMap em = cm.ExceptionMap; if( em != null ) { textWriter.WriteLine( ); textWriter.WriteLine( " ExceptionMap:" ); textWriter.WriteLine( ); foreach( ExceptionMap.Range rng in em.Ranges ) { ExceptionMap.Handler[] handlers = rng.Handlers; textWriter.WriteLine( " Range[0x{0:X8}-0x{1:X8} {2} Entries]", rng.Start.ToUInt32( ), rng.End.ToUInt32( ), handlers != null ? handlers.Length : 0 ); if( handlers != null ) { for( int pos = 0; pos < handlers.Length; pos++ ) { ExceptionMap.Handler hnd = handlers[ pos ]; VTable vt = hnd.Filter; uint address = Resolve( hnd.HandlerCode ); textWriter.WriteLine( " Handler 0x{0:X8} for {1}", address, vt != null ? vt.TypeInfo.FullNameWithAbbreviation : "" ); } } textWriter.WriteLine( ); } } } foreach( SequentialRegion reg in Core.SortRegions( cs.AssociatedRegions ) ) { reg.Dump( textWriter ); } } } private void Disassemble_Data( string baseDirectory, GrowOnlyHashTable> catalog ) { foreach( DataManager.DataDescriptor dd in m_dataDescriptors.Keys ) { SequentialRegion reg = m_dataDescriptors[ dd ]; string name = dd.ToString( ); System.IO.StreamWriter textWriter = CatalogItem.GenerateStream( catalog, baseDirectory, "Data_", ".asm", dd, name.GetHashCode( ) ); textWriter.WriteLine( "{0}", name ); textWriter.WriteLine( ); reg.Dump( textWriter ); } } private void Disassemble_Stats( string baseDirectory, GrowOnlyHashTable> catalog ) { GrowOnlyHashTable< string, Statistics > statistics = HashTableFactory.New( ); foreach( SequentialRegion reg in this.SortedRegions ) { object context = reg.Context; string text; Statistics stat; if( context is BasicBlock ) { BasicBlock bb2 = ( BasicBlock )context; text = "Code for " + bb2.Owner.Method.ToShortString( ); } else { text = context.ToString( ); } if( statistics.TryGetValue( text, out stat ) == false ) { stat = new Statistics( ); stat.m_text = text; statistics[ text ] = stat; } stat.m_size += ( int )reg.Size; ; stat.m_count += 1; } //--// using( System.IO.StreamWriter textWriter = new System.IO.StreamWriter( System.IO.Path.Combine( baseDirectory, "Summary.txt" ), false, System.Text.Encoding.ASCII ) ) { Statistics[] stats = statistics.ValuesToArray( ); Array.Sort( stats, delegate( Statistics left, Statistics right ) { int res = right.m_size.CompareTo( left.m_size ); if( res == 0 ) { res = left.m_text.CompareTo( right.m_text ); } return res; } ); foreach( Statistics stat in stats ) { textWriter.WriteLine( "{0,8} byte(s) for {1,4} entries of type {2}", stat.m_size, stat.m_count, stat.m_text ); } } } //--// public void DisassembleInOneFile( string fileName ) { using( System.IO.StreamWriter textWriter = new System.IO.StreamWriter( fileName, false, System.Text.Encoding.ASCII, 1024 * 1024 ) ) { GrowOnlyHashTable< string, Statistics > statistics = HashTableFactory.New( ); foreach( SequentialRegion reg in this.SortedRegions ) { object context = reg.Context; { string text; Statistics stat; if( context is BasicBlock ) { BasicBlock bb2 = ( BasicBlock )context; text = "Code for " + bb2.Owner.Method.ToShortString( ); } else { text = context.ToString( ); } if( reg.PlacementRequirements.Alignment > 0x100 ) { text += "[TLB]"; } if( reg.PlacementRequirements.Usages != null && reg.PlacementRequirements.Usages.Length > 0 && reg.PlacementRequirements.Usages[ 0 ] == Runtime.MemoryUsage.Relocation ) { text += "[Relocation]"; } if( statistics.TryGetValue( text, out stat ) == false ) { stat = new Statistics( ); stat.m_text = text; statistics[ text ] = stat; } stat.m_size += ( int )reg.Size; ; stat.m_count += 1; } //--// EntryBasicBlock bb = context as EntryBasicBlock; if( bb != null ) { MethodRepresentation md = bb.Owner.Method; CodeMap cm = md.CodeMap; if( cm != null ) { textWriter.WriteLine( ); textWriter.WriteLine( " CodeMap for {0}", md.ToShortString( ) ); textWriter.WriteLine( ); foreach( CodeMap.Range rng in cm.Ranges ) { bool fFirst = true; foreach( string txt in rng.ToString( ).Split( new string[] { Environment.NewLine }, StringSplitOptions.RemoveEmptyEntries ) ) { if( fFirst ) { fFirst = false; textWriter.WriteLine( " {0}", txt ); } else { textWriter.WriteLine( " {0}", txt ); } } textWriter.WriteLine( ); } ExceptionMap em = cm.ExceptionMap; if( em != null ) { textWriter.WriteLine( ); textWriter.WriteLine( " ExceptionMap for {0}", md.ToShortString( ) ); textWriter.WriteLine( ); foreach( ExceptionMap.Range rng in em.Ranges ) { ExceptionMap.Handler[] handlers = rng.Handlers; textWriter.WriteLine( " Range[0x{0:X8}-0x{1:X8} {2} Entries]", rng.Start.ToUInt32( ), rng.End.ToUInt32( ), handlers != null ? handlers.Length : 0 ); if( handlers != null ) { for( int pos = 0; pos < handlers.Length; pos++ ) { ExceptionMap.Handler hnd = handlers[ pos ]; VTable vt = hnd.Filter; uint address = Resolve( hnd.HandlerCode ); textWriter.WriteLine( " Handler 0x{0:X8} for {1}", address, vt != null ? vt.TypeInfo.FullNameWithAbbreviation : "" ); } } textWriter.WriteLine( ); } } } } reg.Dump( textWriter ); } //--// textWriter.WriteLine( ); textWriter.WriteLine( " Summary:" ); textWriter.WriteLine( ); Statistics[] stats = statistics.ValuesToArray( ); Array.Sort( stats, delegate( Statistics left, Statistics right ) { int res = right.m_size.CompareTo( left.m_size ); if( res == 0 ) { res = left.m_text.CompareTo( right.m_text ); } return res; } ); foreach( Statistics stat in stats ) { textWriter.WriteLine( " {0,8} for {1,4} entries of type {2}", stat.m_size, stat.m_count, stat.m_text ); } textWriter.WriteLine( ); } } } } ================================================ FILE: Zelig/Zelig/CompileTime/CodeGenerator/CodeTransformation/ImageBuilders/ImageAnnotations/CodeRelocation.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // namespace Microsoft.Zelig.CodeGeneration.IR.ImageBuilders { using System; using System.Collections.Generic; using Microsoft.Zelig.Runtime.TypeSystem; using Microsoft.Zelig.TargetModel.ArmProcessor; public abstract class CodeRelocation : ImageAnnotation { // // State // protected CompilationState m_cs; protected Operator m_origin; protected int m_skew; // // Constructor Methods // protected CodeRelocation() // Default constructor required by TypeSystemSerializer. { } protected CodeRelocation( SequentialRegion region , uint offset , uint size , object target , CompilationState cs , Operator origin , int skew ) : base( region, offset, size, target ) { m_cs = cs; m_origin = origin; m_skew = skew; } // // Helper Methods // public override void ApplyTransformation( TransformationContextForCodeTransformation context ) { context.Push( this ); base.ApplyTransformation( context ); context.Transform( ref m_cs ); context.Transform( ref m_origin ); context.Transform( ref m_skew ); context.Pop(); } //--// public override bool IsCompileTimeAnnotation { get { return true; } } public override bool ApplyRelocation() { uint dstAddress = m_region.Owner.Resolve ( m_target ); uint srcAddress = m_region.GetAbsoluteAddress( m_offset ); if(CanRelocateToAddress( srcAddress, dstAddress )) { if(ApplyRelocation( srcAddress, dstAddress )) { return true; } } NotifyFailedRelocation(); return false; } protected abstract bool ApplyRelocation( uint srcAddress , uint dstAddress ); protected abstract void NotifyFailedRelocation(); //--// protected Exception NotImplemented() { return m_cs.NotImplemented(); } // // Access Methods // public Operator Origin { get { return m_origin; } } public int Skew { get { return m_skew; } } } } ================================================ FILE: Zelig/Zelig/CompileTime/CodeGenerator/CodeTransformation/ImageBuilders/ImageAnnotations/DataRelocation.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // namespace Microsoft.Zelig.CodeGeneration.IR.ImageBuilders { using System; using System.Collections.Generic; using Microsoft.Zelig.Runtime.TypeSystem; using Microsoft.Zelig.TargetModel.ArmProcessor; public sealed class DataRelocation : ImageAnnotation { // // State // // // Constructor Methods // private DataRelocation() // Default constructor required by TypeSystemSerializer. { } public DataRelocation( SequentialRegion region , uint offset , object target ) : base( region, offset, sizeof(uint), target ) { } // // Helper Methods // //--// public override bool IsCompileTimeAnnotation { get { return true; } } public override void GetAllowedRelocationRange( out int lowerBound , out int upperBound ) { lowerBound = int.MinValue; upperBound = int.MaxValue; } public override bool ApplyRelocation() { uint val = m_region.Owner.Resolve( m_target ); m_region.Write( m_offset, val ); return true; } } } ================================================ FILE: Zelig/Zelig/CompileTime/CodeGenerator/CodeTransformation/ImageBuilders/ImageAnnotations/ExternMethodCallRelocation.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // namespace Microsoft.Zelig.CodeGeneration.IR.ImageBuilders { using System; using System.Collections.Generic; using Microsoft.Zelig.Runtime.TypeSystem; using Microsoft.Zelig.TargetModel.ArmProcessor; public sealed class ExternMethodCallRelocation : ImageAnnotation { public delegate uint UpdateExternalMethodCall( uint opcode, uint callerAddress, uint calleeAddress ); // // State // private UpdateExternalMethodCall m_callback; private uint m_methodOffset; private int m_skew; // // Constructor Methods // private ExternMethodCallRelocation() // Default constructor required by TypeSystemSerializer. { } public ExternMethodCallRelocation( SequentialRegion region, uint offset, UpdateExternalMethodCall callback, uint methodOffset, object target, int skew) : base( region, offset, sizeof( uint ), target ) { m_callback = callback; m_methodOffset = methodOffset; m_skew = skew; } // // Helper Methods // //--// public override bool IsCompileTimeAnnotation { get { return true; } } public override void GetAllowedRelocationRange( out int lowerBound, out int upperBound ) { lowerBound = m_skew + ( int.MinValue >> 8 ) * sizeof( uint ); upperBound = m_skew + ( int.MaxValue >> 8 ) * sizeof( uint ); } public override bool ApplyRelocation() { uint methodAddr = m_region.Owner.Resolve( m_target ) + m_methodOffset; uint srcAddress = m_region.GetAbsoluteAddress( m_offset ); if(m_target is ExternalCallOperator) { methodAddr += ( (ExternalCallOperator)m_target ).Context.OperatorOffset; } if(this.CanRelocateToAddress( srcAddress, methodAddr )) { m_region.Write( m_offset, m_callback( m_region.ReadUInt( m_offset ), srcAddress, methodAddr) ); return true; } return false; } } } ================================================ FILE: Zelig/Zelig/CompileTime/CodeGenerator/CodeTransformation/ImageBuilders/ImageAnnotations/ExternalDataRelocation.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // namespace Microsoft.Zelig.CodeGeneration.IR.ImageBuilders { using System; using System.Collections.Generic; using Microsoft.Zelig.Runtime.TypeSystem; using Microsoft.Zelig.TargetModel.ArmProcessor; public sealed class ExternalPointerRelocation : ImageAnnotation { // // State // private uint m_externalDataOffset; // // Constructor Methods // private ExternalPointerRelocation() // Default constructor required by TypeSystemSerializer. { } public ExternalPointerRelocation( SequentialRegion region, uint offset, uint externalDataOffset, object target ) : base( region, offset, sizeof( uint ), target ) { m_externalDataOffset = externalDataOffset; } // // Helper Methods // //--// public override bool IsCompileTimeAnnotation { get { return true; } } public override void GetAllowedRelocationRange( out int lowerBound, out int upperBound ) { lowerBound = int.MinValue; upperBound = int.MaxValue; } public override void ApplyTransformation( TransformationContextForCodeTransformation context ) { context.Push( this ); m_target = null; base.ApplyTransformation( context ); context.Transform( ref m_externalDataOffset ); context.Pop(); } public override bool ApplyRelocation() { uint val = m_region.Owner.Resolve( m_target ); if(m_target is ExternalCallOperator) { val = (uint)(val + ( (ExternalCallOperator)m_target ).Context.OperatorOffset); } else { val += m_externalDataOffset; } m_region.Write( m_offset, val ); return true; } } } ================================================ FILE: Zelig/Zelig/CompileTime/CodeGenerator/CodeTransformation/ImageBuilders/ImageAnnotations/GenericImageAnnotation.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // namespace Microsoft.Zelig.CodeGeneration.IR.ImageBuilders { using System; using System.Collections.Generic; using Microsoft.Zelig.Runtime.TypeSystem; using Microsoft.Zelig.TargetModel.ArmProcessor; public sealed class GenericImageAnnotation : ImageAnnotation { // // State // // // Constructor Methods // private GenericImageAnnotation() // Default constructor required by TypeSystemSerializer. { } public GenericImageAnnotation( SequentialRegion region , uint offset , uint size , object target ) : base( region, offset, size, target ) { } // // Helper Methods // //--// public override bool IsCompileTimeAnnotation { get { return false; } } public override void GetAllowedRelocationRange( out int lowerBound , out int upperBound ) { lowerBound = int.MinValue; upperBound = int.MaxValue; } public override bool ApplyRelocation() { return true; } } } ================================================ FILE: Zelig/Zelig/CompileTime/CodeGenerator/CodeTransformation/ImageBuilders/ImageAnnotations/ImageAnnotation.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // namespace Microsoft.Zelig.CodeGeneration.IR.ImageBuilders { using System; using System.Collections.Generic; using Microsoft.Zelig.Runtime.TypeSystem; using Microsoft.Zelig.TargetModel.ArmProcessor; public abstract class ImageAnnotation { // // State // protected SequentialRegion m_region; protected uint m_offset; protected uint m_size; protected object m_target; // // Constructor Methods // protected ImageAnnotation() // Default constructor required by TypeSystemSerializer. { } protected ImageAnnotation( SequentialRegion region , uint offset , uint size , object target ) { m_region = region; m_offset = offset; m_size = size; m_target = target; m_region.AddImageAnnotation( this ); } // // Helper Methods // public virtual void ApplyTransformation( TransformationContextForCodeTransformation context ) { context.Push( this ); context.Transform( ref m_region ); context.Transform( ref m_offset ); context.Transform( ref m_size ); context.Transform( ref m_target ); context.Pop(); } //--// public bool CanRelocateToAddress( uint srcAddress , uint dstAddress ) { int diff = (int)(dstAddress - srcAddress); int lowerBound; int upperBound; this.GetAllowedRelocationRange( out lowerBound, out upperBound ); return (lowerBound <= diff && diff <= upperBound); } public abstract void GetAllowedRelocationRange( out int lowerBound , out int upperBound ); public abstract bool ApplyRelocation(); public abstract bool IsCompileTimeAnnotation { get; } // // Access Methods // public SequentialRegion Region { get { return m_region; } } public uint InsertionAddress { get { return m_region.BaseAddress.ToUInt32() + m_offset; } } public uint Offset { get { return m_offset; } set { m_offset = value; } } public uint Size { get { return m_size; } } public object Target { get { return m_target; } } // // Debug Methods // public override string ToString() { return string.Format( "{0} at {1}", this.GetType(), m_offset ); } public bool IsScalar { get { if(m_target is BasicBlock || m_target is SequentialRegion || m_target is FieldRepresentation ) { return false; } else { return true; } } } internal virtual void Dump( System.IO.TextWriter textWriter ) { if(m_target is BasicBlock) { BasicBlock bb = (BasicBlock)m_target; textWriter.Write( "{0} of '{1}'", m_region.Dumper.CreateLabel( bb ), bb.Owner.Method.ToShortString() ); } else if(m_target is SequentialRegion) { SequentialRegion regTarget = (SequentialRegion)m_target; textWriter.Write( "{0}", regTarget.Context ); } else if(m_target is FieldRepresentation) { FieldRepresentation fd = (FieldRepresentation)m_target; textWriter.Write( "{0}", fd.ToShortString() ); } else { textWriter.Write( "{0}", m_target ); } } } } ================================================ FILE: Zelig/Zelig/CompileTime/CodeGenerator/CodeTransformation/ImageBuilders/ImageAnnotations/TrackVariableLifetime.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // namespace Microsoft.Zelig.CodeGeneration.IR.ImageBuilders { using System; using System.Collections.Generic; using Microsoft.Zelig.Runtime.TypeSystem; using Microsoft.Zelig.TargetModel.ArmProcessor; public sealed class TrackVariableLifetime : ImageAnnotation { // // State // bool m_fAlive; // // Constructor Methods // private TrackVariableLifetime() // Default constructor required by TypeSystemSerializer. { } public TrackVariableLifetime( SequentialRegion region , uint offset , VariableExpression target , bool fAlive ) : base( region, offset, sizeof(uint), target ) { m_fAlive = fAlive; } // // Helper Methods // public override void ApplyTransformation( TransformationContextForCodeTransformation context ) { context.Push( this ); base.ApplyTransformation( context ); context.Transform( ref m_fAlive ); context.Pop(); } //--// public override bool IsCompileTimeAnnotation { get { return false; } } public override void GetAllowedRelocationRange( out int lowerBound , out int upperBound ) { lowerBound = int.MinValue; upperBound = int.MaxValue; } public override bool ApplyRelocation() { return true; } //--// public static bool ShouldTrackAsAPointer( VariableExpression var ) { if(var is PhysicalRegisterExpression || var is StackLocationExpression ) { TypeRepresentation td = var.Type; if(td is ReferenceTypeRepresentation || td is PointerTypeRepresentation ) { return true; } if(td is ScalarTypeRepresentation) { ScalarTypeRepresentation tdS = (ScalarTypeRepresentation)td; switch(tdS.BuiltInType) { case TypeRepresentation.BuiltInTypes.I: case TypeRepresentation.BuiltInTypes.U: return true; // We track IntPtr and UIntPtr quantities as potentially pinned pointers. } } } return false; } // // Access Methods // public bool IsAlive { get { return m_fAlive; } } // // Debug Methods // internal override void Dump( System.IO.TextWriter textWriter ) { VariableExpression var = (VariableExpression)this.Target; textWriter.Write( "{0} {1}", m_fAlive ? "ALIVE" : "DEAD ", var ); } } } ================================================ FILE: Zelig/Zelig/CompileTime/CodeGenerator/CodeTransformation/ImageBuilders/SequentialRegion.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // namespace Microsoft.Zelig.CodeGeneration.IR.ImageBuilders { using System; using System.Collections.Generic; using Microsoft.Zelig.TargetModel.ArmProcessor; public class SequentialRegion { public class Section { // // State // private SequentialRegion m_context; private uint m_start; private uint m_end; private uint m_offset; // // Constructor Methods // internal Section( SequentialRegion context , uint start ) { m_context = context; m_start = start; m_end = uint.MaxValue; m_offset = 0; } internal Section( SequentialRegion context , uint start , uint size ) { m_context = context; m_start = start; m_end = start + size; m_offset = 0; } // // Helper Methods // public Section GetSubSection( uint size ) { uint start = m_start + m_offset; m_offset += size; CheckPosition(); return new Section( m_context, start, size ); } public void AlignGeneric( uint alignment ) { uint off = m_offset % alignment; if(off != 0) { m_offset += alignment - off; CheckPosition(); } } public void AlignToHalfWord() { m_offset = (m_offset + 1u) & ~1u; CheckPosition(); } public void AlignToWord() { m_offset = (m_offset + 3u) & ~3u; CheckPosition(); } public void Skip( uint size ) { m_offset += size; CheckPosition(); } //--// public void Write( byte val ) { uint pos = Expand( sizeof(byte) ); m_context.Write( pos, val ); } public void Write( ushort val ) { uint pos = Expand( sizeof(ushort) ); m_context.Write( pos, val ); } public void Write( uint val ) { uint pos = Expand( sizeof(uint) ); m_context.Write( pos, val ); } public void WriteNullPointer() { Expand( sizeof(uint) ); } public ImageAnnotation WritePointerToDataDescriptor( DataManager.DataDescriptor dd ) { CHECKS.ASSERT( dd != null, "Cannot write null pointer" ); uint pos = Expand( sizeof(uint) ); var reloc = new DataRelocation( m_context, pos, dd ); m_context.m_owner.AddObject( dd ); return reloc; } public ImageAnnotation WritePointerToBasicBlock( BasicBlock bb ) { CHECKS.ASSERT( bb != null, "Cannot write null pointer" ); uint pos = Expand( sizeof(uint) ); var reloc = new DataRelocation( m_context, pos, bb ); m_context.m_owner.CompileBasicBlock( bb ); return reloc; } //--// public void Write( bool val ) { Write( val ? (byte)1 : (byte)0 ); } public void Write( ulong val ) { uint pos = Expand( sizeof(ulong) ); m_context.Write( pos , (uint)(val ) ); m_context.Write( pos + sizeof(uint), (uint)(val >> 32) ); } public void Write( sbyte val ) { uint pos = Expand( sizeof(sbyte) ); m_context.Write( pos, (byte)val ); } public void Write( short val ) { uint pos = Expand( sizeof(short) ); m_context.Write( pos, (ushort)val ); } public void Write( int val ) { uint pos = Expand( sizeof(int) ); m_context.Write( pos, (uint)val ); } public void Write( long val ) { uint pos = Expand( sizeof(long) ); m_context.Write( pos , (uint)(val ) ); m_context.Write( pos + sizeof(uint), (uint)(val >> 32) ); } public void Write( char val ) { uint pos = Expand( sizeof(char) ); m_context.Write( pos, (ushort)val ); } public void Write( float val ) { uint pos = Expand( sizeof(float) ); m_context.Write( pos, DataConversion.GetFloatAsBytes( val ) ); } public void Write( double val ) { uint pos = Expand( sizeof(double) ); ulong val2 = DataConversion.GetDoubleAsBytes( val ); m_context.Write( pos , (uint)(val2 ) ); m_context.Write( pos + sizeof(uint), (uint)(val2 >> 32) ); } public void Write( UIntPtr val ) { uint pos = Expand( sizeof(uint) ); m_context.Write( pos, val.ToUInt32() ); } public void Write( IntPtr val ) { uint pos = Expand( sizeof(uint) ); m_context.Write( pos, (uint)val.ToInt32() ); } //--// public void Write( byte[] valArray ) { uint pos = Expand( (uint)(valArray.Length * sizeof(byte)) ); m_context.Write( pos, valArray ); } public void Write( char[] valArray ) { uint pos = Expand( (uint)(valArray.Length * sizeof(char)) ); m_context.Write( pos, valArray ); } public void Write( int[] valArray ) { uint pos = Expand( (uint)(valArray.Length * sizeof(int)) ); m_context.Write( pos, valArray ); } public void Write( uint[] valArray ) { uint pos = Expand( (uint)(valArray.Length * sizeof(uint)) ); m_context.Write( pos, valArray ); } //--// public bool WriteGeneric( object val ) { if(val != null) { Type t = val.GetType(); if(t.IsEnum) { t = Enum.GetUnderlyingType( t ); } if(t == typeof(bool )) { Write( (bool )val ); return true; } if(t == typeof(byte )) { Write( (byte )val ); return true; } if(t == typeof(ushort )) { Write( (ushort )val ); return true; } if(t == typeof(uint )) { Write( (uint )val ); return true; } if(t == typeof(ulong )) { Write( (ulong )val ); return true; } if(t == typeof(sbyte )) { Write( (sbyte )val ); return true; } if(t == typeof(short )) { Write( (short )val ); return true; } if(t == typeof(int )) { Write( (int )val ); return true; } if(t == typeof(long )) { Write( (long )val ); return true; } if(t == typeof(char )) { Write( (char )val ); return true; } if(t == typeof(float )) { Write( (float )val ); return true; } if(t == typeof(double )) { Write( (double )val ); return true; } if(t == typeof(UIntPtr)) { Write( (UIntPtr)val ); return true; } if(t == typeof(IntPtr )) { Write( (IntPtr )val ); return true; } if(t == typeof(byte[] )) { Write( (byte[] )val ); return true; } if(t == typeof(char[] )) { Write( (char[] )val ); return true; } if(t == typeof(int [] )) { Write( (int [] )val ); return true; } if(t == typeof(uint[] )) { Write( (uint[] )val ); return true; } } return false; } //--// public ImageAnnotation AddImageAnnotation( uint size , object val ) { return new GenericImageAnnotation( m_context, m_start + m_offset, size, val ); } //--// private void CheckPosition() { if(m_end == uint.MaxValue) { m_context.EnsureSize( m_start + m_offset ); } else if(m_offset > this.Size) { throw new IndexOutOfRangeException(); } } private uint ExpandAndAnnotate( uint size , object val ) { if(val != null) { AddImageAnnotation( size, val ); } return Expand( size ); } private uint Expand( uint size ) { uint pos = m_start + m_offset; m_offset += size; CheckPosition(); return pos; } // // Access Methods // public SequentialRegion Context { get { return m_context; } } public uint Position { get { return m_start + m_offset; } } public uint Offset { get { return m_offset; } set { m_offset = value; CheckPosition(); } } public uint Size { get { return m_end - m_start; } } } //--// const uint AddressNotAssigned = 0xFFFFFFFFu; // // State // private Core m_owner; private object m_context; private Abstractions.PlacementRequirements m_placementRequirements; private UIntPtr m_baseAddress; private uint m_pointerOffset; private uint m_position; private uint m_size; private byte[] m_payload; private uint m_payloadCutoff; private List< ImageAnnotation > m_annotationList; private PrettyDumper m_dumper; // // Constructor Methods // private SequentialRegion() // Default constructor required by TypeSystemSerializer. { m_annotationList = new List< ImageAnnotation >(); } internal SequentialRegion( Core owner , object context , Abstractions.PlacementRequirements pr ) : this() { m_owner = owner; m_context = context; m_placementRequirements = pr; m_pointerOffset = 0; m_position = 0; m_size = 0; m_payloadCutoff = uint.MaxValue; m_payload = null; InvalidateBaseAddress(); } // // Helper Methods // public void ApplyTransformation( TransformationContextForCodeTransformation context ) { context.Push( this ); context.Transform( ref m_owner ); context.Transform( ref m_context ); context.Transform( ref m_placementRequirements ); context.Transform( ref m_baseAddress ); context.Transform( ref m_pointerOffset ); context.Transform( ref m_position ); context.Transform( ref m_size ); context.Transform( ref m_payloadCutoff ); context.Transform( ref m_payload ); context.Transform( ref m_annotationList ); context.Pop(); } //--// public void InvalidateBaseAddress() { m_baseAddress = new UIntPtr( AddressNotAssigned ); } public void Clear() { m_pointerOffset = 0; m_position = 0; m_size = 0; m_payload = null; m_annotationList.Clear(); } //--// public uint AdjustSizeForAlignment( uint size ) { return AddressMath.AlignToBoundary( size, m_owner.TypeSystem.PlatformAbstraction.MemoryAlignment ); } public uint GetAbsoluteAddress( uint offset ) { return this.ExternalAddress + offset; } public Section GetSectionOfVariableSize( uint alignment ) { Section sec = new Section( this, m_position ); return sec; } public Section GetSectionOfFixedSize( uint size ) { size = AdjustSizeForAlignment( size ); Section sec = new Section( this, m_position, size ); Skip( size ); return sec; } public void Skip( uint size ) { m_position += size; EnsureSize( m_position ); } //--// public byte ReadByte( uint offset ) { return m_payload[offset]; } public ushort ReadUShort( uint offset ) { return (ushort)(((uint)m_payload[offset ] ) | ((uint)m_payload[offset+1] << 8) ); } public uint ReadUInt( uint offset ) { return (((uint)m_payload[offset ] ) | ((uint)m_payload[offset+1] << 8) | ((uint)m_payload[offset+2] << 16) | ((uint)m_payload[offset+3] << 24) ); } //--// public void Write( uint offset , byte val ) { m_payload[offset] = val; } public void Write( uint offset , ushort val ) { m_payload[offset ] = (byte)(val ); m_payload[offset+1] = (byte)(val >> 8); } public void Write( uint offset , uint val ) { m_payload[offset ] = (byte)(val ); m_payload[offset+1] = (byte)(val >> 8); m_payload[offset+2] = (byte)(val >> 16); m_payload[offset+3] = (byte)(val >> 24); } //--// public void Write( uint offset , byte[] valArray ) { Buffer.BlockCopy( valArray, 0, m_payload, (int)offset, valArray.Length ); } public void Write( uint offset , char[] valArray ) { Buffer.BlockCopy( valArray, 0, m_payload, (int)offset, valArray.Length * sizeof(char) ); } public void Write( uint offset , int[] valArray ) { Buffer.BlockCopy( valArray, 0, m_payload, (int)offset, valArray.Length * sizeof(int) ); } public void Write( uint offset , uint[] valArray ) { Buffer.BlockCopy( valArray, 0, m_payload, (int)offset, valArray.Length * sizeof(uint) ); } //--// public void Remove( uint offset , uint len ) { if(offset < m_size) { uint end = offset + len; if(end < m_size) { Array.Copy( m_payload, end, m_payload, offset, m_size - end ); m_size -= len; } else { m_size = offset; } // // Adjust relocation info. // foreach(ImageAnnotation an in m_annotationList) { if(an.Offset >= offset) { if(an.Offset >= end) { an.Offset -= len; } else { an.Offset = offset; } } } } } //--// internal void AddImageAnnotation( ImageAnnotation an ) { // // Insert the annotation in 'Offset' order. // int pos = m_annotationList.Count; while(--pos >= 0) { ImageAnnotation anOld = m_annotationList[pos]; if(anOld.Offset <= an.Offset) { break; } } m_annotationList.Insert( pos + 1, an ); } //--// internal void AssignAbsoluteAddress() { if(this.IsBaseAddressAssigned == false) { UIntPtr address; if(m_owner.ReserveRangeOfMemory( m_size, m_pointerOffset, m_placementRequirements, out address ) == false) { throw TypeConsistencyErrorException.Create( "Cannot allocate memory for data: {0}", m_context ); } this.BaseAddress = address; } } internal bool ApplyRelocation() { bool fRes = true; foreach(ImageAnnotation an in m_annotationList) { fRes &= an.ApplyRelocation(); } return fRes; } //--// public static int ComputeSize( object val ) { if(val is bool ) return sizeof(bool ); if(val is byte ) return sizeof(byte ); if(val is ushort) return sizeof(ushort); if(val is uint ) return sizeof(uint ); if(val is ulong ) return sizeof(ulong ); if(val is sbyte ) return sizeof(sbyte ); if(val is short ) return sizeof(short ); if(val is int ) return sizeof(int ); if(val is long ) return sizeof(long ); if(val is char ) return sizeof(char ); if(val is float ) return sizeof(float ); if(val is double) return sizeof(double); return -1; } //--// void EnsureSize( uint size ) { if(m_payload == null) { m_payload = new byte[128]; } if(m_size < size) { uint newSize = Math.Max( m_size + 128, size + 64 ); m_payload = ArrayUtility.EnsureSizeOfNotNullArray( m_payload, (int)newSize ); } m_size = size; } //--// public byte[] ToArray() { if(m_payload == null) { return new byte[0]; } return ArrayUtility.ExtractSliceFromNotNullArray( m_payload, 0, (int)this.PayloadCutoff ); } //--// // // Access Methods // public Core Owner { get { return m_owner; } } public object Context { get { return m_context; } } public Abstractions.PlacementRequirements PlacementRequirements { get { return m_placementRequirements; } } public UIntPtr BaseAddress { get { return m_baseAddress; } set { m_baseAddress = value; } } public UIntPtr EndAddress { get { return new UIntPtr( m_baseAddress.ToUInt32() + m_size ); } } public UIntPtr PayloadEndAddress { get { return new UIntPtr( m_baseAddress.ToUInt32() + this.PayloadCutoff ); } } public uint PointerOffset { get { return m_pointerOffset; } set { m_pointerOffset = value; } } public uint PayloadCutoff { get { return Math.Min( m_size, m_payloadCutoff ); } set { m_payloadCutoff = value; } } public uint ExternalAddress { get { CHECKS.ASSERT( this.IsBaseAddressAssigned, "Cannot access ExternalAddress before it's been assigned to {0}", this ); return m_baseAddress.ToUInt32() + m_pointerOffset; } } //--// public uint Position { get { return m_position; } set { if(value > m_size) { throw new IndexOutOfRangeException(); } m_position = value; } } public uint Size { get { return m_size; } } public bool IsBaseAddressAssigned { get { return m_baseAddress.ToUInt32() != AddressNotAssigned; } } public List< ImageAnnotation > AnnotationList { get { return m_annotationList; } } // // Debug Methods // internal IIntermediateRepresentationDumper Dumper { get { if(m_dumper == null) { m_dumper = new PrettyDumper(); } return m_dumper; } } private static string s_indent1 = new string( ' ', 12 ); private static string s_indent2 = new string( ' ', 13 ); private void DumpActivationRecordEvents( System.IO.TextWriter textWriter , uint offset ) { bool fGot = false; foreach(ImageAnnotation an in m_annotationList) { if(an.Offset == offset) { if(an.Target is Runtime.ActivationRecordEvents) { if(fGot == false) { fGot = true; textWriter.WriteLine( "{0};;;;;;;;;;", s_indent1 ); } textWriter.Write( "{0};;;;;;;;;;{1}ACTIVATION RECORD >>>> ", s_indent1, s_indent2 ); an.Dump( textWriter ); textWriter.WriteLine(); } } } if(fGot) { textWriter.WriteLine( "{0};;;;;;;;;;", s_indent1 ); } } private void DumpPointers( System.IO.TextWriter textWriter , uint offset ) { bool fGot = false; foreach(ImageAnnotation an in m_annotationList) { if(an.Offset == offset) { if(an is TrackVariableLifetime) { TrackVariableLifetime tvl = (TrackVariableLifetime)an; if(offset == 0 && tvl.IsAlive == false) { // // Don't dump dead variables at the entrance of the basic block. // continue; } if(fGot == false) { fGot = true; textWriter.WriteLine( "{0};;;;;;;;;;", s_indent1 ); } textWriter.Write( "{0};;;;;;;;;;{1}VAR >>>> ", s_indent1, s_indent2 ); an.Dump( textWriter ); textWriter.WriteLine(); } } } if(fGot) { textWriter.WriteLine( "{0};;;;;;;;;;", s_indent1 ); } } private void DumpOperators( System.IO.TextWriter textWriter , uint offset ) { foreach(ImageAnnotation an in m_annotationList) { if(an.Offset == offset) { Operator op = an.Target as Operator; if(op != null) { bool fGot = false; m_owner.SourceCodeTracker.Print( op.DebugInfo, delegate ( string format, object[] args ) { textWriter.Write( "{0};;;;;;;;;;{1}", s_indent1, s_indent2 ); textWriter.WriteLine( format, args ); fGot = true; } ); if(fGot) { textWriter.WriteLine( "{0};;;;;;;;;;", s_indent1 ); } textWriter.WriteLine( "{0};;;;;;;;;;{1}IR >>>> {2}", s_indent1, s_indent2, op.FormatOutput( this.Dumper ) ); textWriter.WriteLine( "{0};;;;;;;;;;", s_indent1 ); } } } } private void DumpOther( System.IO.TextWriter textWriter , uint offset ) { bool fFirst = true; foreach(ImageAnnotation an in m_annotationList) { if(an.Offset == offset) { if(an is TrackVariableLifetime) { continue; } if(an.IsScalar) { continue; } if(an.Target is Operator) { continue; } if(fFirst) { fFirst = false; textWriter.Write( " ;;; " ); } else { textWriter.Write( ", " ); } an.Dump( textWriter ); } } } public void Dump( System.IO.TextWriter textWriter ) { if(m_context is BasicBlock) { BasicBlock bb = (BasicBlock)m_context; textWriter.WriteLine( " Opcodes for {0} for {1} [{2}]", this.Dumper.CreateLabel( bb ), bb.Owner, bb.Annotation ); InstructionSet encoder = this.Owner.GetInstructionSetProvider(); uint address = this.IsBaseAddressAssigned ? this.BaseAddress.ToUInt32() : 0; m_owner.SourceCodeTracker.ResetContext(); m_owner.SourceCodeTracker.ExtraLinesToOutput = 3; for(uint offset = 0; offset < m_size; offset += sizeof(uint)) { uint target; bool targetIsCode; uint opcode = ReadUInt( offset ); string res = encoder.DecodeAndPrint( address + offset, opcode, out target, out targetIsCode ); // // Dump activation record events. // DumpActivationRecordEvents( textWriter, offset ); // // Dump liveness status of variables. // DumpPointers( textWriter, offset ); // // Dump IR operators associated with the instruction. // DumpOperators( textWriter, offset ); // // Dump ARM opcode. // textWriter.Write( "{0}0x{1:X8}: {2:X8} {3}", s_indent1, address + offset, opcode, res ); // // Dump all the other annotations. // DumpOther( textWriter, offset ); textWriter.WriteLine(); } DumpActivationRecordEvents( textWriter, m_size ); DumpPointers( textWriter, m_size ); textWriter.WriteLine(); } else { if(m_size > 0) { textWriter.WriteLine( " Data for {0}", m_context ); uint address = this.IsBaseAddressAssigned ? this.BaseAddress.ToUInt32() : 0; uint pos = 0; bool fNewLine = false; for(uint offset = 0; offset < this.PayloadCutoff; offset++) { ImageAnnotation gotAnnotation = null; foreach(ImageAnnotation an in m_annotationList) { if(an.Offset == offset) { gotAnnotation = an; break; } } if(gotAnnotation != null && pos != 0) { fNewLine = true; } if(fNewLine) { fNewLine = false; pos = 0; textWriter.WriteLine(); } textWriter.Write( pos == 0 ? " 0x{0:X8}: " : ", " , address + offset ); if(gotAnnotation == null) { textWriter.Write( "0x{0:X2}", ReadByte( offset ) ); pos++; if(pos >= 32) { fNewLine = true; } } else { switch(gotAnnotation.Size) { case 1: textWriter.Write( "0x{0:X2}", ReadByte( offset ) ); break; case 2: textWriter.Write( "0x{0:X4}", ReadUShort( offset ) ); offset += 2 - 1; break; default: case 4: textWriter.Write( "0x{0:X8}", ReadUInt( offset ) ); offset += 4 - 1; break; case 8: textWriter.Write( "0x{0:X8}{1:X8}", ReadUInt( offset + 4 ), ReadUInt( offset ) ); offset += 8 - 1; break; } bool fFirst = true; foreach(ImageAnnotation an in m_annotationList) { if(an.Offset == gotAnnotation.Offset) { if(an.IsScalar == false || an.Target is char) { if(fFirst) { fFirst = false; textWriter.Write( " ;;; " ); } else { textWriter.Write( ", " ); } an.Dump( textWriter ); } } } fNewLine = true; } } if(fNewLine || pos > 0) { textWriter.WriteLine(); } if(this.PayloadCutoff < this.Size) { textWriter.WriteLine( " 0x{0:X8}: " , address + this.PayloadCutoff, this.Size - this.PayloadCutoff ); } textWriter.WriteLine(); } } } // // Debug Methods // public override string ToString() { if(this.IsBaseAddressAssigned) { return string.Format( "Region at 0x{0:X8} for {1}", this.ExternalAddress, m_context ); } else { return string.Format( "Region for {0}", m_context ); } } } } ================================================ FILE: Zelig/Zelig/CompileTime/CodeGenerator/CodeTransformation/IntermediateRepresentationDumper.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // //#define DUMP_ALIVE_INFO namespace Microsoft.Zelig.CodeGeneration.IR { using System; using System.Collections.Generic; using Microsoft.Zelig.Runtime.TypeSystem; // // Debug classes // public abstract class BaseIntermediateRepresentationDumper : IIntermediateRepresentationDumper { // // State // private GrowOnlyHashTable< Expression, string > m_lookupName; private GrowOnlyHashTable< BasicBlock, string > m_lookupLabel; //--// protected BasicBlock[] m_basicBlocks; protected BasicBlock[] m_ancestors; protected Operator[] m_operators; protected VariableExpression[] m_variables; protected VariableExpression[] m_sortedVariables; protected Operator[][] m_useChains; protected BitVector[] m_reachingDefinitions; #if DUMP_ALIVE_INFO protected BitVector[] m_liveness; #endif // // Constructor Methods // protected BaseIntermediateRepresentationDumper() { m_lookupName = HashTableFactory.NewWithReferenceEquality< Expression, string >(); m_lookupLabel = HashTableFactory.NewWithReferenceEquality< BasicBlock, string >(); } //--// public MethodRepresentation[] Sort( IEnumerable< MethodRepresentation > enumerable ) { GrowOnlyHashTable< MethodRepresentation, string > htNames = HashTableFactory.NewWithReferenceEquality< MethodRepresentation, string >(); foreach(MethodRepresentation md in enumerable) { htNames[md] = md.ToShortString(); } MethodRepresentation[] res = new MethodRepresentation[htNames.Count]; int pos = 0; foreach(MethodRepresentation md in htNames.Keys) { res[pos++] = md; } Array.Sort( res, delegate( MethodRepresentation left, MethodRepresentation right ) { return String.Compare( htNames[left], htNames[right] ); } ); return res; } public string FormatOutput( string s , object arg1 ) { return FormatOutputInternal( s, arg1 ); } public string FormatOutput( string s , object arg1 , object arg2 ) { return FormatOutputInternal( s, arg1, arg2 ); } public string FormatOutput( string s , object arg1 , object arg2 , object arg3 ) { return FormatOutputInternal( s, arg1, arg2, arg3 ); } public string FormatOutput( string s , params object[] args ) { return FormatOutputInternal( s, args ); } //--// public virtual void DumpGraph( ControlFlowGraphState cfg ) { ControlFlowGraphStateForCodeTransformation cfg2 = (ControlFlowGraphStateForCodeTransformation)cfg; m_lookupName .Clear(); m_lookupLabel.Clear(); //--// m_basicBlocks = cfg2.DataFlow_SpanningTree_BasicBlocks; m_ancestors = cfg2.DataFlow_SpanningTree_Ancestors; m_operators = cfg2.DataFlow_SpanningTree_Operators; m_variables = cfg2.DataFlow_SpanningTree_Variables; m_useChains = cfg2.DataFlow_UseChains; m_reachingDefinitions = cfg2.DataFlow_ReachingDefinitions; #if DUMP_ALIVE_INFO m_liveness = cfg2.LivenessAtOperator; // It's indexed as [][] #endif cfg2.RenumberVariables(); m_sortedVariables = cfg2.SortVariables(); } public string CreateName( Expression ex ) { string res; if(m_lookupName.TryGetValue( ex, out res ) == false) { res = ex.ToString(); m_lookupName[ex] = res; } return res; } public string CreateLabel( BasicBlock bb ) { string res; if(m_lookupLabel.TryGetValue( bb, out res ) == false) { res = bb.ToShortString(); m_lookupLabel[bb] = res; } return res; } //--// protected string FormatOutputInternal( string s , params object[] args ) { for(int i = 0; i < args.Length; i++) { object o = args[i]; if(o is Expression) { Expression ex = (Expression)o; args[i] = CreateName( ex ); } if(o is BasicBlock) { BasicBlock bb = (BasicBlock)o; args[i] = CreateLabel( bb ); } } return string.Format( s, args ); } } //--// public class TextIntermediateRepresentationDumper : BaseIntermediateRepresentationDumper, IDisposable { // // State // System.IO.TextWriter m_writer; bool m_closeWriter; int m_indent; bool m_fIndented; SourceCodeTracker m_sourceCodeTracker; // // Constructor Methods // public TextIntermediateRepresentationDumper() { m_writer = Console.Out; m_closeWriter = false; Init(); } public TextIntermediateRepresentationDumper( string file ) { m_writer = new System.IO.StreamWriter( file, false, System.Text.Encoding.ASCII, 1024 * 1024 ); m_closeWriter = true; Init(); } public TextIntermediateRepresentationDumper( System.IO.StreamWriter writer ) { m_writer = writer; m_closeWriter = false; Init(); } private void Init() { m_sourceCodeTracker = new SourceCodeTracker(); } //--// public void WriteLine() { WriteIndentation(); m_writer.WriteLine(); m_fIndented = false; } public void WriteLine( string s ) { WriteIndentation(); m_writer.WriteLine( s ); m_fIndented = false; } public void WriteLine( string s , object arg1 ) { WriteIndentedLine( s, arg1 ); } public void WriteLine( string s , object arg1 , object arg2 ) { WriteIndentedLine( s, arg1, arg2 ); } public void WriteLine( string s , object arg1 , object arg2 , object arg3 ) { WriteIndentedLine( s, arg1, arg2, arg3 ); } public void WriteLine( string s , params object[] args ) { WriteIndentedLine( s, args ); } //--// public override void DumpGraph( ControlFlowGraphState cfg ) { ControlFlowGraphStateForCodeTransformation cfg2 = (ControlFlowGraphStateForCodeTransformation)cfg; base.DumpGraph( cfg2 ); m_sourceCodeTracker.ExtraLinesToOutput = 3; //--// if(m_sortedVariables.Length > 0) { m_indent += 3; foreach(VariableExpression ex in m_sortedVariables) { WriteLine( "{0} {1} as {2}", m_useChains[ex.SpanningTreeIndex].Length > 0 ? " var" : "unused var", ex, ex.Type ); } m_indent -= 3; WriteLine(); } foreach(BasicBlock bb in m_basicBlocks) { ProcessBasicBlock( bb ); } } private void ProcessBasicBlock( BasicBlock bb ) { m_indent += 1; string label = CreateLabel( bb ); if(label != null) { WriteLine( "{0}: [Index:{1}] [Annotation:{2}]", label, bb.SpanningTreeIndex, bb.Annotation ); } // // Print context for every basic block, even if they are consecutive. // m_sourceCodeTracker.ResetContext(); m_indent += 2; if(bb is ExceptionHandlerBasicBlock) { ExceptionHandlerBasicBlock ehBB = (ExceptionHandlerBasicBlock)bb; foreach(ExceptionClause eh in ehBB.HandlerFor) { WriteLine( ".handler for {0}", eh ); } } foreach(ExceptionHandlerBasicBlock bbEh in bb.ProtectedBy) { foreach(ExceptionClause eh in bbEh.HandlerFor) { WriteLine( ".protected by {0} at {1}", eh, CreateLabel( bbEh ) ); } } foreach(BasicBlockEdge edge in bb.Predecessors) { WriteLine( ".edge {0} from {1}", edge.EdgeClass, CreateLabel( edge.Predecessor ) ); } foreach(BasicBlockEdge edge in bb.Successors) { WriteLine( ".edge {0} to {1}", edge.EdgeClass, CreateLabel( edge.Successor ) ); } GrowOnlySet< Expression > used = SetFactory.NewWithReferenceEquality< Expression >(); foreach(Operator op in bb.Operators) { foreach(Expression ex in op.Arguments) { used.Insert( ex ); } } foreach(Expression ex in used) { bool fGot = false; foreach(int opIndex in m_reachingDefinitions[bb.Operators[0].SpanningTreeIndex]) { if(m_operators[opIndex].IsSourceOfExpression( ex )) { if(fGot == false) { WriteIndented( ".reaching {0} <=", ex ); fGot = true; } else { WriteIndented( "," ); } WriteIndented( " Op_{0}", opIndex ); } } if(fGot) { WriteLine(); } } //--// foreach(Operator op in bb.Operators) { DumpOperator( op ); } m_indent -= 2; m_indent -= 1; WriteLine(); } private void DumpOperator( Operator op ) { DumpSourceCode( op.DebugInfo ); #if DUMP_ALIVE_INFO if(op.IsSideEffect == false) { BitVector vec = m_liveness[op.SpanningTreeIndex]; if(vec.Cardinality != 0) { WriteLine(); foreach(int idx in vec) { VariableExpression ex = m_variables[idx]; WriteIndentedLine( ".alive {0}", ex ); } } } #endif string s = op.FormatOutput( this ); foreach(string s2 in s.Split( '\n' )) { WriteLine("Op_{0,-3} {1,-35}: {2}", op.SpanningTreeIndex, op.GetType().Name, s2); } foreach(Annotation an in op.Annotations) { WriteLine( " {0}", an.FormatOutput( this ) ); } } private void DumpSourceCode( Debugging.DebugInfo dbg ) { m_sourceCodeTracker.Print( dbg, delegate ( string format, object[] args ) { m_writer.Write ( ";;;" ); m_writer.WriteLine( format, args ); } ); } //--// private void WriteIndented( string s , params object[] args ) { WriteIndentation(); m_writer.Write( FormatOutputInternal( s, args ) ); } private void WriteIndentedLine( string s , params object[] args ) { WriteIndentation(); m_writer.WriteLine( FormatOutputInternal( s, args ) ); m_fIndented = false; } private void WriteIndentation() { if(m_fIndented == false) { m_fIndented = true; for(int i = 0; i < m_indent; i++) { m_writer.Write( " " ); } } } #region IDisposable Members public void Dispose() { if(m_closeWriter) { m_writer.Flush(); m_writer.Dispose(); m_writer = null; m_closeWriter = false; } } #endregion } //--// public class XmlIntermediateRepresentationDumper : BaseIntermediateRepresentationDumper { // // State // System.Xml.XmlDocument m_doc; System.Xml.XmlNode m_root; // // Constructor Methods // public XmlIntermediateRepresentationDumper( System.Xml.XmlDocument doc , System.Xml.XmlNode root ) { m_doc = doc; m_root = root; } //--// public override void DumpGraph( ControlFlowGraphState cfg ) { ControlFlowGraphStateForCodeTransformation cfg2 = (ControlFlowGraphStateForCodeTransformation)cfg; base.DumpGraph( cfg2 ); //--// System.Xml.XmlNode node = XmlHelper.AddElement( m_root, "Method" ); XmlHelper.AddAttribute( node, "Name", cfg.Method.ToString() ); foreach(VariableExpression ex in cfg2.DataFlow_SpanningTree_Variables) { DumpVariable( node, ex ); } foreach(BasicBlock bb in m_basicBlocks) { ProcessBasicBlock( node, bb ); } } private void DumpVariable( System.Xml.XmlNode node , VariableExpression ex ) { System.Xml.XmlNode subnode = XmlHelper.AddElement( node, "Variable" ); XmlHelper.AddAttribute( subnode, "Name", CreateName( ex ) ); XmlHelper.AddAttribute( subnode, "Type", ex.Type.ToString() ); } private void ProcessBasicBlock( System.Xml.XmlNode node , BasicBlock bb ) { System.Xml.XmlNode subnode = XmlHelper.AddElement( node, "BasicBlock" ); XmlHelper.AddAttribute( subnode, "Id" , CreateLabel( bb ) ); XmlHelper.AddAttribute( subnode, "Index", bb.SpanningTreeIndex.ToString() ); XmlHelper.AddAttribute( subnode, "Type" , bb.GetType().Name ); foreach(BasicBlockEdge edge in bb.Successors) { DumpEdge( subnode, edge ); } //--// GrowOnlySet< Expression > used = SetFactory.NewWithReferenceEquality< Expression >(); foreach(Operator op in bb.Operators) { foreach(Expression ex in op.Arguments) { used.Insert( ex ); } } foreach(Expression ex in used) { System.Xml.XmlNode reachingNode = null; foreach(int opIndex in m_reachingDefinitions[bb.Operators[0].SpanningTreeIndex]) { if(m_operators[opIndex].IsSourceOfExpression( ex )) { if(reachingNode == null) { reachingNode = XmlHelper.AddElement( subnode, "ReachingDefinition" ); XmlHelper.AddAttribute( reachingNode, "Variable", CreateName( ex ) ); } System.Xml.XmlNode opNode = XmlHelper.AddElement( reachingNode, "Definition" ); XmlHelper.AddAttribute( opNode, "Index", opIndex.ToString() ); } } } if(bb is ExceptionHandlerBasicBlock) { ExceptionHandlerBasicBlock ehBB = (ExceptionHandlerBasicBlock)bb; foreach(ExceptionClause eh in ehBB.HandlerFor) { System.Xml.XmlNode exNode = XmlHelper.AddElement( subnode, "HandlerFor" ); XmlHelper.AddAttribute( exNode, "Type", eh.ToString() ); } } //--// foreach(Operator op in bb.Operators) { DumpOperator( subnode, op ); } } private void DumpOperator( System.Xml.XmlNode node , Operator op ) { string s = op.FormatOutput( this ); foreach(string s2 in s.Split( '\n' )) { System.Xml.XmlNode subnode = XmlHelper.AddElement( node, "Operator" ); XmlHelper.AddAttribute( subnode, "Index", op.SpanningTreeIndex.ToString() ); XmlHelper.AddAttribute(subnode, "Type", op.GetType().Name); if(op is CallOperator) { CallOperator op2 = (CallOperator)op; XmlHelper.AddAttribute( subnode, "Call", op2.TargetMethod.ToString() ); } DumpDebug( subnode, op.DebugInfo ); subnode.AppendChild( m_doc.CreateTextNode( s2 ) ); } } private void DumpDebug( System.Xml.XmlNode node , Debugging.DebugInfo dbg ) { if(dbg != null) { System.Xml.XmlNode subnode = XmlHelper.AddElement( node, "Debug" ); XmlHelper.AddAttribute( subnode, "File" , dbg.SrcFileName ); XmlHelper.AddAttribute( subnode, "MethodName" , dbg.MethodName ); XmlHelper.AddAttribute( subnode, "BeginLine" , dbg.BeginLineNumber.ToString() ); XmlHelper.AddAttribute( subnode, "BeginColumn", dbg.BeginColumn .ToString() ); XmlHelper.AddAttribute( subnode, "EndLine" , dbg.EndLineNumber .ToString() ); XmlHelper.AddAttribute( subnode, "EndColumn" , dbg.EndColumn .ToString() ); } } private void DumpEdge( System.Xml.XmlNode node , BasicBlockEdge edge ) { System.Xml.XmlNode subnode = XmlHelper.AddElement( node, "Edge" ); XmlHelper.AddAttribute( subnode, "From", CreateLabel( edge.Predecessor ) ); XmlHelper.AddAttribute( subnode, "To" , CreateLabel( edge.Successor ) ); XmlHelper.AddAttribute( subnode, "Kind", edge.EdgeClass.ToString() ); } } //--// public class PrettyDumper : BaseIntermediateRepresentationDumper { // // State // // // Constructor Methods // public PrettyDumper() { } //--// public override void DumpGraph( ControlFlowGraphState cfg ) { } internal static string Dump( Operator op ) { PrettyDumper dumper = new PrettyDumper(); return op.FormatOutput( dumper ); } } } ================================================ FILE: Zelig/Zelig/CompileTime/CodeGenerator/CodeTransformation/LLVM/DebugInfoExtensions.cs ================================================ using Llvm.NET.DebugInfo; using Microsoft.Zelig.Debugging; using Microsoft.Zelig.Runtime.TypeSystem; using System.Diagnostics; namespace Microsoft.Zelig.LLVM { internal static class DebugInfoExtensions { /// Converts between Zelig IR and LLVM debug location information /// Zelig IR debug information may be null if no info is available /// Module that owns the resulting location /// Source location this location is inlined into (may be null if not inlined) /// New DILocation for the given IR location internal static DILocation AsDILocation( this DebugInfo debugInfo, _Module module, DILocation inlinedAt ) { if (debugInfo == null) return null; var md = debugInfo.Scope as MethodRepresentation; Debug.Assert(md != null); var scope = module.Manager.GetScopeFor(md); #if DEBUG string irSrcPath = System.IO.Path.GetFullPath(debugInfo.SrcFileName); string llscopePath = System.IO.Path.GetFullPath(scope.File.Path); Debug.Assert( irSrcPath == llscopePath); #endif return new DILocation(scope.Context, (uint)debugInfo.BeginLineNumber, (uint)debugInfo.BeginColumn, scope, inlinedAt); } internal static DILocation AsDILocation(this DebugInfo debugInfo, _Module module) { return AsDILocation(debugInfo, module, null); } } } ================================================ FILE: Zelig/Zelig/CompileTime/CodeGenerator/CodeTransformation/LLVM/ITargetSectionOptions.cs ================================================ namespace Microsoft.Zelig.LLVM { /// Provides options for generating target data sections /// /// This interface is implemented on a component provided by the application hosting /// the Llilum compilation engine. Typically the host's command line options object /// would implement this interface to provide settings parse from the command line. /// public interface ITargetSectionOptions { /// Gets a flag to indicate if section names for blobal data should include the type name /// If this flag is then the LLVM code generation phase will output /// all global data into sections with a name that includes the full type of the data. This is useful /// for diagnostics and understanding memory usage. Though it can have an adverse impact on the overall /// data size. Since sections have a platform, target and toolchain minimum alignment if there are a /// large number of types (and therefore sections) it is possible the alignment requirements for them /// could actually increase the size of the image. Thus this is considered a diagnostic option rather /// than a default setting. /// If this is then the global data is placed into sections that include /// the Llilum name to help identify Llilum specific data. (i.e. for ARM Cortex-M processors readonly /// data would go to .rodata.llilum and writeable data to .data.llilum) /// bool GenerateDataSectionPerType { get; } } } ================================================ FILE: Zelig/Zelig/CompileTime/CodeGenerator/CodeTransformation/LLVM/InliningPathAnnotationExtensions.cs ================================================ #define DUMP_INLINING_PATH_DETAILS using Llvm.NET; using Llvm.NET.DebugInfo; using Microsoft.Zelig.CodeGeneration.IR; using Microsoft.Zelig.Debugging; using System; using System.CodeDom.Compiler; using System.Diagnostics; using System.IO; namespace Microsoft.Zelig.LLVM { internal static class InlinedPathDetailsExtensions { #if DUMP_INLINING_PATH_DETAILS static Lazy InliningLog = new Lazy( ()=> new IndentedTextWriter(new StreamWriter("InlinePath.log")) , false ); #endif [Conditional("DUMP_INLINING_PATH_DETAILS")] private static void Log( DILocation location ) { if (location == null) return; InliningLog.Value.WriteLine("Location: {0}", location ); InliningLog.Value.Write("Scope: {0}", location.Scope); if( location.InlinedAt != null ) { ++InliningLog.Value.Indent; InliningLog.Value.WriteLine(); Log(location.InlinedAt); --InliningLog.Value.Indent; } InliningLog.Value.WriteLine(); InliningLog.Value.Flush(); } /// Generates a DILocation with a full scope chain for inlined locations from an InliningPathAnnotation /// Annotation to get the full path information from /// Module to use for resolving Zelig IR class instanes to their corresponding LLVM instances /// LLVM function for the outermost scope /// Zelig IR Debug info for the innermost source location /// with full chained scoping (e.g. InlinedAt is set for full scope chain) for inlined functions /// /// LLVM Locations require full tracking from the innermost location to the outer most, however the Zelig IR /// doesn't store the innermost source location, nor the outermost function /// scope. Thus an InliningPathAnnotation on its own is insufficient to construct the LLVM debug information. /// This method takes care of that by using the additional parameters to complete the information. /// internal static DILocation GetDebugLocationFor( this IInliningPathAnnotation pathDetails, _Module module, _Function outerScope, DebugInfo innermostDebugInfo ) { if (pathDetails == null) { throw new ArgumentNullException(nameof(pathDetails)); } // if elements of the inline path are removed (e.g. the path is squashed) // then scopes may be off and can't be handle by this code yet. (This can // occur for extension methods that were inlined into something) Conceptually // extension methods are more like a pre-processor macro insertion than // inlining but this code doesn't have enough information to make a decision // on that here.So, for the moment, this just treats it as not inlined. if ( pathDetails.IsSquashed ) { return module.Manager.GetDebugInfoFor(outerScope.Method)?.AsDILocation( module ); } //construct inlining scope and info array with full path //starting from outermost scope and moving inward. This //completes the full chain and "re-aligns" the scope and //location arrays to have a 1:1 relationship var inlineLocations = ScalarEnumerable.Combine( pathDetails.DebugInfoPath, innermostDebugInfo); // walk the scope and location collection from outermost to innermost to // construct proper LLVM chain. The resulting location is for the innermost // location with the "InlinedAt" property referring to the next outer // scope, and so on all the way up to the final outer most scope DILocation location = null; foreach(var debugInfo in inlineLocations ) { location = debugInfo.AsDILocation(module, location); } Log(location); return location; } } } ================================================ FILE: Zelig/Zelig/CompileTime/CodeGenerator/CodeTransformation/LLVM/LLVMModuleManager.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // // Enable this macro to shift object pointers from the beginning of the header to the beginning of the payload. #define CANONICAL_OBJECT_POINTERS namespace Microsoft.Zelig.LLVM { using System; using System.Collections.Generic; using System.Text; using System.Text.RegularExpressions; using System.IO; using Importer = Microsoft.Zelig.MetaData.Importer; using Normalized = Microsoft.Zelig.MetaData.Normalized; using IR = Microsoft.Zelig.CodeGeneration.IR; using TS = Microsoft.Zelig.Runtime.TypeSystem; using Llvm.NET.Values; using System.Diagnostics; using Llvm.NET.DebugInfo; public partial class LLVMModuleManager { private ISectionNameProvider m_SectionNameProvider; private readonly Debugging.DebugInfo m_dummyDebugInfo; private _Module m_module; private readonly string m_imageName; private readonly IR.TypeSystemForCodeTransformation m_typeSystem; private GrowOnlyHashTable m_typeRepresentationsToType; private GrowOnlyHashTable m_debugInfoForMethods; private GrowOnlyHashTable m_globalInitializedValues; private bool m_typeSystemAlreadyConverted; private bool m_turnOffCompilationAndValidation; //TypeSystem might not be completely initialized at this point. public LLVMModuleManager( IR.TypeSystemForCodeTransformation typeSystem, string imageName ) { m_imageName = imageName; m_typeSystem = typeSystem; m_debugInfoForMethods = HashTableFactory.New( ); m_typeRepresentationsToType = HashTableFactory.New( ); m_globalInitializedValues = HashTableFactory.New(); m_typeSystemAlreadyConverted = false; m_turnOffCompilationAndValidation = false; m_module = new _Module( m_imageName, m_typeSystem ); m_dummyDebugInfo = new Debugging.DebugInfo( m_imageName, 0, 0, 0, 0 ); // Initialize to safe default value, will be changed later before the manager is used m_SectionNameProvider = new EmptySectionNameProvider( m_typeSystem ); } public ISectionNameProvider SectionNameProvider { get { return m_SectionNameProvider; } set { m_SectionNameProvider = value; } } public void Compile() { CompleteMissingDataDescriptors(); // // Synthesize the code for all exported methods as a simple C-style function using the name // of the method without full qualification // foreach(TS.MethodRepresentation md in m_typeSystem.ExportedMethods) { _Function handler = GetOrInsertFunction( md ); m_module.CreateAlias(handler.LlvmFunction, md.Name); } if(!m_turnOffCompilationAndValidation) { TS.MethodRepresentation bootstrapResetMR = m_typeSystem.GetWellKnownMethod( "Bootstrap_Initialization" ); _Function bootstrapReset = GetOrInsertFunction( bootstrapResetMR ); if(m_typeSystem.PlatformAbstraction.PlatformFamily == TargetModel.Win32.InstructionSetVersion.Platform_Family__Win32 ) { m_module.CreateAlias(bootstrapReset.LlvmFunction, "LLILUM_main"); } else { m_module.CreateAlias(bootstrapReset.LlvmFunction, "main"); } m_module.Compile(); } } public void DumpToFile( string filename, OutputFormat format ) { m_module.DumpToFile( filename, format ); } public void TurnOffCompilationAndValidation( ) { m_turnOffCompilationAndValidation = true; } public DISubProgram GetScopeFor( TS.MethodRepresentation md ) { return GetOrInsertFunction(md)?.LlvmFunction?.DISubProgram; } public _Function GetOrInsertFunction( TS.MethodRepresentation md ) { _Function function = m_module.GetOrInsertFunction( md ); function.LlvmFunction.Section = m_SectionNameProvider.GetSectionNameFor( md ); return function; } public static string GetFullMethodName( TS.MethodRepresentation method ) { if( method.Flags.HasFlag( TS.MethodRepresentation.Attributes.PinvokeImpl ) ) { return method.Name; } return $"{method.OwnerType.FullName}::{method.Name}#{method.Identity}"; } private void CompleteMissingDataDescriptors( ) { bool stillMissing = true; while( stillMissing ) { stillMissing = false; foreach( var dd in m_globalInitializedValues.Keys ) { // Force creation of any missing global data descriptor by accessing its value. if( m_globalInitializedValues[ dd ].IsAnUninitializedGlobal( ) ) { stillMissing = true; GlobalValueFromDataDescriptor( dd, setInitializer: true ); break; } } } m_module.FinalizeGlobals(); } private Constant GetUCVStruct( _Type type, bool anon, params Constant[ ] vals ) { var fields = new List( ); foreach( var val in vals ) { fields.Add( val ); } return m_module.GetUCVStruct( type, fields, anon ); } private object GetDirectFromArrayDescriptor( IR.DataManager.ArrayDescriptor ad, uint pos ) { return ad.Values != null ? ad.Values[ pos ] : ad.Source.GetValue( pos ); } private Constant GetUCVArray( IR.DataManager.ArrayDescriptor ad ) { uint arrayLength = ( uint )( ( ad.Values == null ) ? ad.Source.Length : ad.Values.Length ); var fields = new List( ); TS.TypeRepresentation elTR = ( ( TS.ArrayReferenceTypeRepresentation )ad.Context ).ContainedType; // // Special case for common scalar arrays. // if( ad.Values == null ) { for( uint i = 0; i < arrayLength; i++ ) { object fdVal = GetDirectFromArrayDescriptor( ad, i ); fields.Add( GetScalarTypeUCV( elTR, fdVal ) ); } } else { for( uint i = 0; i < arrayLength; i++ ) { object val = GetDirectFromArrayDescriptor( ad, i ); if( val == null ) { fields.Add(m_module.GetNullValue(GetOrInsertType(elTR))); } else if( val is IR.DataManager.DataDescriptor ) { IR.DataManager.DataDescriptor valDD = ( IR.DataManager.DataDescriptor )val; if( valDD.Nesting != null ) { fields.Add( UCVFromDataDescriptor( valDD ) ); } else { fields.Add(GlobalValueFromDataDescriptor(valDD, false)); } } else if( ad.Context.ContainedType is TS.ScalarTypeRepresentation ) { fields.Add( GetScalarTypeUCV( elTR, val ) ); } else { throw TypeConsistencyErrorException.Create( "Don't know how to write {0}", val ); } } } return m_module.GetUCVArray( GetOrInsertType( elTR ), fields ); } private Constant GetScalarTypeUCV( TS.TypeRepresentation tr, object value ) { _Type type = GetOrInsertType( tr ); return m_module.GetUCVScalar( type, value ); } private bool TypeChangesAfterCreation( IR.DataManager.DataDescriptor dd ) { return dd is IR.DataManager.ArrayDescriptor || dd.Context == m_typeSystem.WellKnownTypes.System_String; } public Constant GlobalValueFromDataDescriptor(IR.DataManager.DataDescriptor dd, bool setInitializer) { // If the type changes after creation it's a string or array type, so force initialization. if (TypeChangesAfterCreation(dd)) { setInitializer = true; } Constant global; if (m_globalInitializedValues.TryGetValue(dd, out global)) { // If we already have an initialized global, or an uninitialized one that we're still not initializing, // return the cached one. Uninitialized globals will be replaced below. if (!global.IsAnUninitializedGlobal() || !setInitializer) { return global; } } if (setInitializer) { // Get the object header if this type needs one. Constant header = null; #if CANONICAL_OBJECT_POINTERS if (!(dd.Context is TS.ValueTypeRepresentation)) { header = GetUCVObjectHeader(dd); } #endif // CANONICAL_OBJECT_POINTERS _Type type = GetOrInsertInlineType(dd.Context); Constant value = UCVFromDataDescriptor(dd); string name = type.Name; string sectionName = m_SectionNameProvider.GetSectionNameFor(dd); // Rename vtable constants so they can be easily read in the output. // FUTURE: This should probably be set more generally at a higher level, likely in DataManager. if (dd.Context == m_typeSystem.WellKnownTypes.Microsoft_Zelig_Runtime_TypeSystem_VTable) { var objDescriptor = (IR.DataManager.ObjectDescriptor)dd; var vtable = objDescriptor.Source as TS.VTable; string sourceName = vtable?.TypeInfo?.FullName; if (sourceName != null) { name = sourceName + ".VTable"; } } global = m_module.GetGlobalFromUCV(type, header, value, !dd.IsMutable, name, sectionName); } else { global = m_module.GetUninitializedGlobal(GetOrInsertInlineType(dd.Context)); } // If we had an uninitialized placeholder, replace it with the new copy. Constant cachedGlobal; if (m_globalInitializedValues.TryGetValue(dd, out cachedGlobal)) { cachedGlobal.MergeToAndRemove(global); } m_globalInitializedValues[dd] = global; return global; } private Constant GetUCVObjectHeader( IR.DataManager.DataDescriptor dd ) { TS.WellKnownFields wkf = m_typeSystem.WellKnownFields; TS.WellKnownTypes wkt = m_typeSystem.WellKnownTypes; var fields = new List( ); Runtime.ObjectHeader.GarbageCollectorFlags flags; if( dd.IsMutable ) { flags = Runtime.ObjectHeader.GarbageCollectorFlags.UnreclaimableObject; } else { flags = Runtime.ObjectHeader.GarbageCollectorFlags.ReadOnlyObject; } var descriptor = (IR.DataManager.DataDescriptor)dd.Owner.GetObjectDescriptor(dd.Context.VirtualTable); Constant virtualTable = GlobalValueFromDataDescriptor(descriptor, false); fields.Add(GetScalarTypeUCV(wkf.ObjectHeader_MultiUseWord.FieldType, (ulong)flags)); fields.Add(virtualTable); _Type headerType = GetOrInsertType( wkt.Microsoft_Zelig_Runtime_ObjectHeader ); return m_module.GetUCVStruct( headerType.UnderlyingType, fields, false ); } private Constant UCVFromDataDescriptor(IR.DataManager.DataDescriptor dd) { return UCVFromDataDescriptor(dd, dd.Context); } private Constant UCVFromDataDescriptor( IR.DataManager.DataDescriptor dd, TS.TypeRepresentation currentType) { TS.WellKnownFields wkf = m_typeSystem.WellKnownFields; TS.WellKnownTypes wkt = m_typeSystem.WellKnownTypes; TS.WellKnownMethods wkm = m_typeSystem.WellKnownMethods; if( dd is IR.DataManager.ObjectDescriptor ) { IR.DataManager.ObjectDescriptor od = ( IR.DataManager.ObjectDescriptor )dd; var fields = new List( ); #if CANONICAL_OBJECT_POINTERS // Recursively add parent class fields for reference types. if( !( currentType is TS.ValueTypeRepresentation ) && ( currentType != wkt.System_Object ) ) #else // CANONICAL_OBJECT_POINTERS // Special case: System.Object always gets an object header. if( currentType == wkt.System_Object ) { Constant ucv = GetUCVObjectHeader( dd ); _Type objectType = GetOrInsertType( wkt.System_Object ); return GetUCVStruct( objectType.UnderlyingType, false, ucv ); } if( !( currentType is TS.ValueTypeRepresentation ) ) #endif // CANONICAL_OBJECT_POINTERS { fields.Add( UCVFromDataDescriptor( dd, currentType.Extends ) ); } for( uint i = 0; i < currentType.Size - ( currentType.Extends == null ? 0 : currentType.Extends.Size ); i++ ) { var fd = currentType.FindFieldAtOffset( ( int )( i + ( currentType.Extends == null ? 0 : currentType.Extends.Size ) ) ); if( fd != null ) { i += fd.FieldType.SizeOfHoldingVariable - 1; if( !od.Values.ContainsKey( fd ) ) { fields.Add(m_module.GetNullValue(GetOrInsertType(fd.FieldType))); continue; } var fdVal = od.Values[ fd ]; if( fd == wkf.CodePointer_Target ) { // // Special case for code pointers: substitute with actual code pointers. // IntPtr id = ( IntPtr )fdVal; object ptr = od.Owner.GetCodePointerFromUniqueID( id ); if( ptr is TS.MethodRepresentation ) { TS.MethodRepresentation md = ( TS.MethodRepresentation )ptr; Constant ucv = GetOrInsertFunction(md).LlvmFunction; ucv = GetUCVStruct( GetOrInsertType( fd.FieldType ), false, ucv ); fields.Add( ucv ); } else if( ptr is IR.ExceptionHandlerBasicBlock ) { IR.ExceptionHandlerBasicBlock ehBB = ( IR.ExceptionHandlerBasicBlock )ptr; // // temporary place-holder // Constant ucv = GetOrInsertFunction(wkm.TypeSystemManager_Throw).LlvmFunction; ucv = GetUCVStruct( GetOrInsertType( fd.FieldType ), false, ucv ); fields.Add( ucv ); } else { throw new Exception( "I'm not sure what kind of code pointer is this:" + ptr ); } } else if( fdVal == null ) { fields.Add(m_module.GetNullValue(GetOrInsertType(fd.FieldType))); } else if( fdVal is IR.DataManager.DataDescriptor ) { IR.DataManager.DataDescriptor valDD = ( IR.DataManager.DataDescriptor )fdVal; if( valDD.Nesting != null ) { fields.Add( UCVFromDataDescriptor( valDD ) ); } else { fields.Add(GlobalValueFromDataDescriptor(valDD, false)); } } else if( fd.FieldType is TS.ScalarTypeRepresentation ) { fields.Add( GetScalarTypeUCV( fd.FieldType, fdVal ) ); } else { throw TypeConsistencyErrorException.Create( "Don't know how to write {0}", fdVal ); } } else { fields.Add( GetScalarTypeUCV( wkt.System_Byte, 0xAB ) ); } } if( currentType == wkt.System_String ) { var chars = new List( ); foreach( char c in ( ( string )od.Source ).ToCharArray( ) ) { chars.Add( GetScalarTypeUCV( wkf.StringImpl_FirstChar.FieldType, c ) ); } fields.Add( m_module.GetUCVArray( GetOrInsertType( wkf.StringImpl_FirstChar.FieldType ), chars ) ); } return m_module.GetUCVStruct( GetOrInsertInlineType( currentType ), fields, currentType == wkt.System_String ); } else if( dd is IR.DataManager.ArrayDescriptor ) { IR.DataManager.ArrayDescriptor ad = ( IR.DataManager.ArrayDescriptor )dd; int length = ad.Source?.Length ?? ad.Length; #if CANONICAL_OBJECT_POINTERS Constant obj = GetUCVStruct( GetOrInsertInlineType( wkt.System_Object ), false ); #else // CANONICAL_OBJECT_POINTERS Constant header = GetUCVObjectHeader( dd ); Constant obj = GetUCVStruct( GetOrInsertInlineType( wkt.System_Object ), false, header ); #endif // CANONICAL_OBJECT_POINTERS Constant arrayLength = GetScalarTypeUCV( wkf.ArrayImpl_m_numElements.FieldType, length ); Constant arrayFields = GetUCVStruct( GetOrInsertInlineType( wkt.System_Array ), false, obj, arrayLength ); return GetUCVStruct( GetOrInsertInlineType( dd.Context ), true, arrayFields, GetUCVArray( ad ) ); } else { throw new System.InvalidOperationException( "DataDescriptor type not supported:" + dd ); } } public _Module Module { get { return m_module; } } public GrowOnlyHashTable DebugInfoForMethods { get { return m_debugInfoForMethods; } } } } ================================================ FILE: Zelig/Zelig/CompileTime/CodeGenerator/CodeTransformation/LLVM/LLVMModuleManager_Types.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // // Enable this macro to shift object pointers from the beginning of the header to the beginning of the payload. #define CANONICAL_OBJECT_POINTERS using System.Collections.ObjectModel; using Microsoft.Zelig.Debugging; namespace Microsoft.Zelig.LLVM { using System; using System.Diagnostics; using System.Collections.Generic; using IR = Microsoft.Zelig.CodeGeneration.IR; using TS = Microsoft.Zelig.Runtime.TypeSystem; using System.Linq; public partial class LLVMModuleManager { public void ConvertTypeLayoutsToLLVM( ) { // LT72NOTE: are we thread safe?? if( !m_typeSystemAlreadyConverted ) { foreach( TS.TypeRepresentation type in m_typeSystem.Types ) { GetOrInsertType( type ); } m_typeSystemAlreadyConverted = true; } } public LLVM._Type GetOrInsertInlineType( TS.TypeRepresentation tr ) { _Type type = GetOrInsertType( tr ); if( type.IsPointer && ( type.UnderlyingType != null ) && !type.UnderlyingType.IsValueType ) { type = type.UnderlyingType; } return type; } public LLVM._Type GetOrInsertType( TS.TypeRepresentation tr ) { TS.WellKnownFields wkf = m_typeSystem.WellKnownFields; TS.WellKnownTypes wkt = m_typeSystem.WellKnownTypes; // // Open and Delayed types do not participate in layout // if( tr.IsOpenType || tr.IsDelayedType ) { return null; } // // Delayed types do not participate in layout // if( tr is TS.DelayedMethodParameterTypeRepresentation || tr is TS.DelayedTypeParameterTypeRepresentation ) { return null; } if( tr is TS.PointerTypeRepresentation ) { TS.TypeRepresentation underlying = tr.UnderlyingType; if( underlying is TS.DelayedMethodParameterTypeRepresentation || underlying is TS.DelayedTypeParameterTypeRepresentation ) { return null; } } if( tr is TS.ArrayReferenceTypeRepresentation ) { TS.TypeRepresentation contained = tr.ContainedType; if( contained is TS.DelayedMethodParameterTypeRepresentation || contained is TS.DelayedTypeParameterTypeRepresentation ) { return null; } } if( !tr.ValidLayout ) { // only unresolved generics get here return null; } if( tr is TS.PinnedPointerTypeRepresentation || tr is TS.EnumerationTypeRepresentation ) { tr = tr.UnderlyingType; } // Try to get the cached type before we create a new one. _Type cachedType; if( m_typeRepresentationsToType.TryGetValue( tr, out cachedType ) ) { return cachedType; } // Remap scalar basic types to native types. if( tr == wkt.System_Boolean || tr == wkt.System_Char || tr == wkt.System_SByte || tr == wkt.System_Byte || tr == wkt.System_Int16 || tr == wkt.System_UInt16 || tr == wkt.System_Int32 || tr == wkt.System_UInt32 || tr == wkt.System_Int64 || tr == wkt.System_UInt64 || tr == wkt.System_Single || tr == wkt.System_Double || tr == wkt.System_IntPtr || tr == wkt.System_UIntPtr || tr == wkt.System_Void ) { _Type type = m_module.GetOrInsertType( tr ); m_typeRepresentationsToType[ tr ] = type; return type; } string typeName = tr.FullName; if( tr is TS.PointerTypeRepresentation ) { if( tr.UnderlyingType == wkt.System_Void ) { // Special case: we remap void* to an IntPtr to allow LLVM to function. return GetOrInsertType( wkt.System_IntPtr ); } _Type underlyingType = GetOrInsertType( tr.UnderlyingType ); m_typeRepresentationsToType[ tr ] = m_module.GetOrInsertPointerType( ( TS.PointerTypeRepresentation )tr, underlyingType ); return m_typeRepresentationsToType[ tr ]; } // All other types _Type llvmType = m_module.GetOrInsertType( tr ); // Ensure that we always return the correct type for storage. If this is a value type, then we're done. // Otherwise, return the type as a pointer. if( llvmType.IsValueType ) { m_typeRepresentationsToType[ tr ] = llvmType; } else { m_typeRepresentationsToType[ tr ] = m_module.GetOrInsertPointerType( llvmType ); } #if !CANONICAL_OBJECT_POINTERS // Special case: System.Object always gets an ObjectHeader. if( tr == wkt.System_Object ) { _Type headerType = GetOrInsertType( wkt.Microsoft_Zelig_Runtime_ObjectHeader ); llvmType.AddField( 0, headerType.UnderlyingType, ".header" ); } #endif // !CANONICAL_OBJECT_POINTERS // Inline the parent class for object types. We will represent unboxed Value types as flat, c++ style, types // because they are 'inlined' in the object layout and their fields offset are based on such layout. We also // exempt ObjectHeader as a special case, since it can't inherit anything. if( ( tr.Extends != null ) && ( tr.Extends != wkt.System_ValueType ) && ( tr.Extends != wkt.System_Enum ) && ( tr != wkt.Microsoft_Zelig_Runtime_ObjectHeader ) ) { _Type parentType = GetOrInsertType( tr.Extends ); llvmType.AddField( 0, parentType.UnderlyingType, ".extends" ); } // Boxed types extend ValueType or Enum (ECMA-335 I.8.2.4), but should be treated as reference types. if( tr is TS.BoxedValueTypeRepresentation ) { _Type objectType = GetOrInsertType( wkt.System_Object ); _Type underlyingType = GetOrInsertType( tr.UnderlyingType ); llvmType.UnderlyingType = underlyingType; llvmType.IsBoxed = true; llvmType.AddField( 0, objectType.UnderlyingType, ".extends" ); } foreach( var field in tr.Fields ) { // static fields are not part of object layout if( field is TS.StaticFieldRepresentation ) { continue; } if( !field.ValidLayout ) { continue; } // Strings are implemented inside the type if( field == wkf.StringImpl_FirstChar ) { _Type arrayType = m_module.GetOrInsertZeroSizedArray( GetOrInsertType( wkt.System_Char ) ); llvmType.AddField( ( uint )field.Offset, arrayType, field.Name ); continue; } llvmType.AddField( ( uint )field.Offset, GetOrInsertType( field.FieldType ), field.Name ); } if( tr is TS.ArrayReferenceTypeRepresentation ) { _Type arrayType = m_module.GetOrInsertZeroSizedArray( GetOrInsertType( tr.ContainedType ) ); llvmType.AddField( wkt.System_Array.Size, arrayType, "array_data" ); } llvmType.SetupFields( ); return m_typeRepresentationsToType[ tr ]; } public _Type GetOrInsertType( TS.MethodRepresentation mr ) { var args = new List<_Type>( ); foreach( var param in mr.ThisPlusArguments ) { args.Add( GetOrInsertType( param ) ); } if( mr is TS.StaticMethodRepresentation ) args.RemoveAt( 0 ); _Type retType = GetOrInsertType( mr.ReturnType ); if( retType == null ) { retType = m_module.GetVoidType( ); } string sigName; if( mr.Flags.HasFlag( TS.MethodRepresentation.Attributes.PinvokeImpl ) ) sigName = mr.Name; else sigName = mr.ToSignatureString( ); return m_module.GetOrInsertFunctionType( sigName, retType, args ); } public DebugInfo GetDebugInfoFor( TS.MethodRepresentation method ) { if( method.DebugInfo == null ) { var cfg = IR.TypeSystemForCodeTransformation.GetCodeForMethod( method ); if( cfg == null ) return m_dummyDebugInfo; method.DebugInfo = ( from op in cfg.DataFlow_SpanningTree_Operators where op.DebugInfo != null select op.DebugInfo ).FirstOrDefault( ); if( method.DebugInfo == null ) method.DebugInfo = m_dummyDebugInfo; } return method.DebugInfo; } } } ================================================ FILE: Zelig/Zelig/CompileTime/CodeGenerator/CodeTransformation/LLVM/SectionNameProvider.cs ================================================ using Llvm.NET; using Microsoft.Zelig.CodeGeneration.IR; using Microsoft.Zelig.Runtime.TypeSystem; namespace Microsoft.Zelig.LLVM { /// Interface for an object file section name provider /// /// This interface is used to allow toolchain and ABI specific implementations of section names /// whithout causing a lot hard coding or conditional coding to handle variations. Once we get /// to where Llilum supports multiple target platforms/ABIs there can be multiple implementations /// of this interface keyed by the LLVM Target "triple" for the target. /// public interface ISectionNameProvider { /// LLVM target triple this provider applies to string TargetTriple { get; } /// Gets the section name for a given /// Descriptor for the global data to get a section name for /// Section name the data should go into string GetSectionNameFor( DataManager.DataDescriptor dd ); /// Gets the section name for a given /// Method to get the section name for /// Name for the section the method should go into string GetSectionNameFor( MethodRepresentation md ); } /// Section name provider for unknown or underspecified target public class EmptySectionNameProvider : ISectionNameProvider { /// Constructs a new provider /// Type system information to use when looking up well known types /// /// The parameter is used to construct a section name suffix for /// some special types (i.e. VTable, String ). /// public EmptySectionNameProvider(TypeSystem typeSystem) { } /// public string TargetTriple => Target.UnknownEabiTriple; /// public string GetSectionNameFor(MethodRepresentation md) { return string.Empty; } /// public string GetSectionNameFor(DataManager.DataDescriptor dd) { return string.Empty; } } /// Section name provider for unknown or underspecified target public class Win32SectionNameProvider : ISectionNameProvider { /// Constructs a new provider /// Type system information to use when looking up well known types /// /// The parameter is used to construct a section name suffix for /// some special types (i.e. VTable, String ). /// public Win32SectionNameProvider(TypeSystem typeSystem) { } /// public string TargetTriple => Target.Win32EabiTriple; /// public string GetSectionNameFor(MethodRepresentation md) { return string.Empty; } /// public string GetSectionNameFor(DataManager.DataDescriptor dd) { return string.Empty; } } /// Section name provider for the ARMv7m Thumb2 EABI target public class Thumb2EabiSectionNameProvider : ISectionNameProvider { /// Constructs a new provider /// Type system information to use when looking up well known types /// /// The parameter is used to construct a section name suffix for /// some special types (i.e. VTable, String ). /// public Thumb2EabiSectionNameProvider( TypeSystem typeSystem ) { m_TypeSystem = typeSystem; } /// public string TargetTriple => Target.ThumbV7mEabiTriple; /// public string GetSectionNameFor( MethodRepresentation md ) { // TODO: Check method representation for custom attributes etc... // to get any special section names for this method. For now, // hardcode all to a custom text section as Llilum doesn't currently // have an attribute dedicated to specifying a section. return LlilumTextSectionName; } /// public string GetSectionNameFor( DataManager.DataDescriptor dd ) { var section = dd.IsMutable ? LlilumRWDataSectionName : LlilumRODataSectionName; return $"{section}{GetSectionSuffixForType( dd.Context )}"; } /// Computes a section name suffix for /// type to get the suffix for /// suffix for the type or if no special suffix required private string GetSectionSuffixForType( TypeRepresentation type ) { if( type == m_TypeSystem.WellKnownTypes.Microsoft_Zelig_Runtime_TypeSystem_VTable ) { return LlilumVTableSectionNameSuffix; } else if( type == m_TypeSystem.WellKnownTypes.System_String ) { return LlilumStringSectionNameSuffix; } // [Lather, rinse, repeat for any additional special type section naming...] else { var options = m_TypeSystem.GetEnvironmentService( ); if( options != null && options.GenerateDataSectionPerType ) { // use full type name for all other types of data // Replace any [] in the name with _SZARRAY to prevent issues with invalid section names return "." + type.FullName.Replace( "[]", "_SZARRAY" ); } else { return string.Empty; } } } private readonly TypeSystem m_TypeSystem; private const string LlilumTextSectionName = ".text.llilum"; private const string LlilumRWDataSectionName = ".data.llilum"; private const string LlilumRODataSectionName = ".rodata.llilum"; private const string LlilumVTableSectionNameSuffix = ".VTable"; private const string LlilumStringSectionNameSuffix = ".String"; } } ================================================ FILE: Zelig/Zelig/CompileTime/CodeGenerator/CodeTransformation/LLVM/TypeField.cs ================================================ using Llvm.NET; namespace Microsoft.Zelig.LLVM { internal class TypeField { internal TypeField( string name, _Type memberType, uint offset ) { Name = name; MemberType = memberType; Offset = offset; } internal string Name { get; set; } internal _Type MemberType { get; set; } internal uint Offset { get; set; } internal uint FinalIdx { get; set; } } } ================================================ FILE: Zelig/Zelig/CompileTime/CodeGenerator/CodeTransformation/LLVM/ValueExtensions.cs ================================================ using System; using Llvm.NET.Values; using Llvm.NET.Types; namespace Microsoft.Zelig.LLVM { public static class ValueExtensions { private static readonly string TypeName = "Type"; public static void SetDebugType(this Value value, _Type type) { value.AddExtendedPropertyValue(TypeName, type); } public static _Type GetDebugType(this Value value) { _Type type; if (!value.TryGetExtendedPropertyValue(TypeName, out type)) { return null; } return type; } public static _Type GetUnderlyingType(this Value value) { return value.GetDebugType().UnderlyingType; } public static bool IsAnUninitializedGlobal(this Value value) { var gv = value as GlobalVariable; if (gv == null) { return false; } return gv.Initializer == null; } public static void SetGlobalInitializer(this Value value, Constant constVal) { var gv = value as GlobalVariable; if (gv != null) { gv.Initializer = constVal; } } public static void MergeToAndRemove(this Value value, Value targetVal) { GlobalVariable gv = value as GlobalVariable; if (gv != null) { gv.ReplaceAllUsesWith(targetVal); gv.RemoveFromParent(); } } } } ================================================ FILE: Zelig/Zelig/CompileTime/CodeGenerator/CodeTransformation/LLVM/_BasicBlock.cs ================================================ using Llvm.NET; using Llvm.NET.DebugInfo; using Llvm.NET.Instructions; using Llvm.NET.Types; using Llvm.NET.Values; using Microsoft.Zelig.CodeGeneration.IR; using Microsoft.Zelig.Debugging; using Microsoft.Zelig.Runtime.TypeSystem; using System; using System.Collections.Generic; using System.Diagnostics; using System.Linq; using BasicBlock = Llvm.NET.Values.BasicBlock; namespace Microsoft.Zelig.LLVM { public class _BasicBlock { internal _BasicBlock( _Function owner, BasicBlock block ) { Owner = owner; LlvmBasicBlock = block; IrBuilder = new InstructionBuilder( block ); } public _Module Module => Owner.Module; public _Function Owner { get; } public string Name { get { return LlvmBasicBlock.Name; } } public void InsertASMString( string ASM ) { #if DUMP_INLINED_COMMENTS_AS_ASM_CALLS // unported C++ code InlineAsm not yet supported in Llvm.NET (and not really needed here anyway) string strASM = (const char*)( Marshal::StringToHGlobalAnsi( ASM ) ).ToPointer( ); std::vector FuncTy_3_args; FunctionType* FuncTy_3 = FunctionType::get( llvm::Type::getVoidTy( owner._pimpl.GetLLVMObject( ).getContext( ) ), FuncTy_3_args, false ); auto asmFunc = InlineAsm::get( FuncTy_3, strASM, "", true ); bldr.Call( asmFunc ); #endif } public void SetDebugInfo( LLVMModuleManager manager, MethodRepresentation method, Operator op ) { var func = manager.GetOrInsertFunction( method ); Debug.Assert( Owner == func ); if( op != null ) { SetDebugInfo( op.DebugInfo ); } else { SetDebugInfo( method.DebugInfo ?? manager.GetDebugInfoFor( method ) ); } } private void SetDebugInfo( DebugInfo debugInfo ) { if( debugInfo == null ) return; // don't allow inlined code to change the file scope of the location // - that either requires a new DILexicalFileBlock (i.e. preprocessor // macro expansion) or it requires the location to include the InlinedAt // location scoping. In order to build the InlinedAt we'd need the // DISubProgram corresponding to the method the operator is inlined // from, which the Zelig inlining doesn't currently provide - all we get // is the source and line data. string curPath = Owner.LlvmFunction.DISubProgram.File?.Path ?? string.Empty; if( 0 != string.Compare( debugInfo.SrcFileName, curPath, StringComparison.OrdinalIgnoreCase ) ) return; CurDILocation = new DILocation( LlvmBasicBlock.Context , ( uint )( debugInfo?.BeginLineNumber ?? 0 ) , ( uint )( debugInfo?.BeginColumn ?? 0 ) , Owner.LlvmFunction.DISubProgram ); } /// /// Ensure that at least default debug info has been set for this block. If debug info has already been created, /// this is a no-op. /// /// Owner of the LLVM module. /// Representation of the method in which this block is defined. public void EnsureDebugInfo( LLVMModuleManager manager, MethodRepresentation method ) { if( CurDILocation == null ) { SetDebugInfo( manager, method, null ); } Debug.Assert( CurDILocation != null ); Debug.Assert( CurDISubProgram != null ); } public Value GetMethodArgument(int index, _Type type) { var llvmFunc = Owner.LlvmFunction; Value value = llvmFunc.Parameters[index]; value.SetDebugType(type); return value; } public Value InsertAlloca(string name, _Type type) { Value value = IrBuilder.Alloca(type.DebugType); value.RegisterName(name); value.SetDebugType(Module.GetOrInsertPointerType(type)); return value; } public Value InsertLoad(Value value) { Value resultValue = IrBuilder.Load(value); resultValue.SetDebugLocation(CurDILocation); resultValue.SetDebugType(value.GetUnderlyingType()); return resultValue; } public void InsertStore(Value src, Value dst) { var ptrType = dst.NativeType as IPointerType; if (src.NativeType != ptrType.ElementType) { Console.WriteLine("For \"Ptr must be a pointer to Val type!\" Assert."); Console.WriteLine("getOperand(0).getType()"); Console.WriteLine(src.NativeType ); Console.WriteLine(""); Console.WriteLine("cast(getOperand(1).getType()).getElementType()"); Console.WriteLine(ptrType.ElementType); Console.WriteLine(""); throw new NotSupportedException(); } IrBuilder.Store(src, dst); } public Value LoadIndirect(Value val, _Type loadedType) { _Type pointerType = Module.GetOrInsertPointerType(loadedType); Value resultVal = IrBuilder.BitCast(val, pointerType.DebugType); resultVal.SetDebugLocation(CurDILocation); resultVal.SetDebugType(pointerType); return resultVal; } public void InsertMemCpy(Value dst, Value src, Value size, bool overlapping) { if (overlapping) { IrBuilder.MemMove(Module.LlvmModule, dst, src, size, 0, false); } else { IrBuilder.MemCpy(Module.LlvmModule, dst, src, size, 0, false); } } public void InsertMemSet(Value dst, Value value, Value size) { IrBuilder.MemSet(Module.LlvmModule, dst, value, size, 0, false); } enum BinaryOperator { ADD = 0, SUB = 1, MUL = 2, DIV = 3, REM = 4, AND = 5, OR = 6, XOR = 7, SHL = 8, SHR = 9, }; public Value InsertBinaryOp( int op, Value left, Value right, bool isSigned ) { var binOp = (BinaryOperator)op; var bldr = IrBuilder; Value retVal; if (left.NativeType.IsInteger && right.NativeType.IsInteger) { switch (binOp) { case BinaryOperator.ADD: retVal = bldr.Add(left, right); break; case BinaryOperator.SUB: retVal = bldr.Sub(left, right); break; case BinaryOperator.MUL: retVal = bldr.Mul(left, right); break; case BinaryOperator.DIV: if (isSigned) retVal = bldr.SDiv(left, right); else retVal = bldr.UDiv(left, right); break; case BinaryOperator.REM: if (isSigned) retVal = bldr.SRem(left, right); else retVal = bldr.URem(left, right); break; case BinaryOperator.AND: retVal = bldr.And(left, right); break; case BinaryOperator.OR: retVal = bldr.Or(left, right); break; case BinaryOperator.XOR: retVal = bldr.Xor(left, right); break; case BinaryOperator.SHL: retVal = bldr.ShiftLeft(left, right); break; case BinaryOperator.SHR: if (isSigned) { retVal = bldr.ArithmeticShiftRight(left, right); } else { retVal = bldr.LogicalShiftRight(left, right); } break; default: throw new NotSupportedException($"Parameters combination not supported for Binary Operator: {binOp}"); } } else if (left.NativeType.IsFloatingPoint && right.NativeType.IsFloatingPoint) { switch (binOp) { case BinaryOperator.ADD: retVal = bldr.FAdd(left, right); break; case BinaryOperator.SUB: retVal = bldr.FSub(left, right); break; case BinaryOperator.MUL: retVal = bldr.FMul(left, right); break; case BinaryOperator.DIV: retVal = bldr.FDiv(left, right); break; case BinaryOperator.REM: retVal = bldr.FRem(left, right); break; default: throw new NotSupportedException($"Parameters combination not supported for Binary Operator: {binOp}"); } } else { throw new NotSupportedException($"Parameters combination not supported for Binary Operator: {binOp}"); } retVal.SetDebugLocation(CurDILocation); retVal.SetDebugType(left.GetDebugType()); return retVal; } enum UnaryOperator { NEG = 0, NOT = 1, FINITE = 2, }; public Value InsertUnaryOp( int op, Value val, bool isSigned ) { var unOp = (UnaryOperator)op; Debug.Assert(val.NativeType.IsInteger || val.NativeType.IsFloatingPoint); Value retVal = val; switch( unOp ) { case UnaryOperator.NEG: if (val.NativeType.IsInteger) { retVal = IrBuilder.Neg( retVal ); } else { retVal = IrBuilder.FNeg( retVal ); } break; case UnaryOperator.NOT: retVal = IrBuilder.Not( retVal ); break; } retVal.SetDebugLocation(CurDILocation); retVal.SetDebugType(val.GetDebugType()); return retVal; } const int SignedBase = 10; const int FloatBase = SignedBase + 10; static readonly Dictionary PredicateMap = new Dictionary( ) { [ 0 ] = Predicate.Equal, //llvm::CmpInst::ICMP_EQ; [ 1 ] = Predicate.UnsignedGreaterOrEqual, //llvm::CmpInst::ICMP_UGE; [ 2 ] = Predicate.UnsignedGreater, //llvm::CmpInst::ICMP_UGT; [ 3 ] = Predicate.UnsignedLessOrEqual, //llvm::CmpInst::ICMP_ULE; [ 4 ] = Predicate.UnsignedLess, //llvm::CmpInst::ICMP_ULT; [ 5 ] = Predicate.NotEqual, //llvm::CmpInst::ICMP_NE; [ SignedBase + 0 ] = Predicate.Equal, //llvm::CmpInst::ICMP_EQ; [ SignedBase + 1 ] = Predicate.SignedGreaterOrEqual, //llvm::CmpInst::ICMP_SGE; [ SignedBase + 2 ] = Predicate.SignedGreater, //llvm::CmpInst::ICMP_SGT; [ SignedBase + 3 ] = Predicate.SignedLessOrEqual, //llvm::CmpInst::ICMP_SLE; [ SignedBase + 4 ] = Predicate.SignedLess, //llvm::CmpInst::ICMP_SLT; [ SignedBase + 5 ] = Predicate.NotEqual, //llvm::CmpInst::ICMP_NE; [ FloatBase + 0 ] = Predicate.OrderedAndEqual, //llvm::CmpInst::FCMP_OEQ; [ FloatBase + 1 ] = Predicate.OrderedAndGreaterThanOrEqual, //llvm::CmpInst::FCMP_OGE; [ FloatBase + 2 ] = Predicate.OrderedAndGreaterThan, //llvm::CmpInst::FCMP_OGT; [ FloatBase + 3 ] = Predicate.OrderedAndLessThanOrEqual, //llvm::CmpInst::FCMP_OLE; [ FloatBase + 4 ] = Predicate.OrderedAndLessThan, //llvm::CmpInst::FCMP_OLT; [ FloatBase + 5 ] = Predicate.OrderedAndNotEqual //llvm::CmpInst::FCMP_ONE; }; public Value InsertCmp( int predicate, bool isSigned, Value valA, Value valB ) { _Type booleanImpl = Module.GetNativeBoolType(); if( (valA.NativeType.IsInteger && valB.NativeType.IsInteger) || (valA.NativeType.IsPointer && valB.NativeType.IsPointer) ) { Predicate p = PredicateMap[ predicate + ( isSigned ? SignedBase : 0 ) ]; var cmp = IrBuilder.Compare((IntPredicate)p, valA, valB); cmp.SetDebugLocation(CurDILocation); cmp.SetDebugType(booleanImpl); return cmp; } if( valA.NativeType.IsFloatingPoint && valB.NativeType.IsFloatingPoint ) { Predicate p = PredicateMap[ predicate + FloatBase ]; var cmp = IrBuilder.Compare((RealPredicate)p, valA, valB); cmp.SetDebugLocation(CurDILocation); cmp.SetDebugType(booleanImpl); return cmp; } Console.WriteLine( "valA:" ); Console.WriteLine( valA.ToString( ) ); Console.WriteLine( "valB:" ); Console.WriteLine( valB.ToString( ) ); throw new NotSupportedException( "Parameter combination not supported for CMP Operator." ); } public Value InsertZExt( Value val, _Type ty, int significantBits ) { Value retVal = val; // TODO: Remove this workaround once issue #123 has been resolved. if (significantBits != val.GetDebugType().SizeInBits) { retVal = IrBuilder.TruncOrBitCast( val, Module.LlvmModule.Context.GetIntType( ( uint )significantBits ) ) .SetDebugLocation( CurDILocation ); } retVal = IrBuilder.ZeroExtendOrBitCast(retVal, ty.DebugType); retVal.SetDebugLocation(CurDILocation); retVal.SetDebugType(ty); return retVal; } public Value InsertSExt( Value val, _Type ty, int significantBits ) { Value retVal = val; // TODO: Remove this workaround once issue #123 has been resolved. if (significantBits != val.GetDebugType().SizeInBits) { retVal = IrBuilder.TruncOrBitCast(val, Module.LlvmModule.Context.GetIntType((uint)significantBits)) .SetDebugLocation(CurDILocation); } retVal = IrBuilder.SignExtendOrBitCast(retVal, ty.DebugType); retVal.SetDebugLocation(CurDILocation); retVal.SetDebugType(ty); return retVal; } public Value InsertTrunc(Value val, _Type type, int significantBits) { // TODO: Remove this workaround once issue #123 has been resolved. if (significantBits < type.SizeInBits) { return InsertZExt(val, type, significantBits); } Value retVal = IrBuilder.TruncOrBitCast(val, type.DebugType); retVal.SetDebugLocation(CurDILocation); retVal.SetDebugType(type); return retVal; } public Value InsertBitCast(Value val, _Type type) { var bitCast = IrBuilder.BitCast(val, type.DebugType); bitCast.SetDebugLocation(CurDILocation); bitCast.SetDebugType(type); return bitCast; } public Value InsertPointerToInt(Value val, _Type intType) { Value llvmVal = IrBuilder.PointerToInt(val, intType.DebugType); llvmVal.SetDebugLocation(CurDILocation); llvmVal.SetDebugType(intType); return llvmVal; } public Value InsertIntToPointer(Value val, _Type pointerType) { Value llvmVal = IrBuilder.IntToPointer(val, (IPointerType)pointerType.DebugType); llvmVal.SetDebugLocation(CurDILocation); llvmVal.SetDebugType(pointerType); return llvmVal; } public Value InsertIntToFP(Value val, _Type type) { Value result; if (val.GetDebugType().IsSigned) { result = IrBuilder.SIToFPCast(val, type.DebugType); } else { result = IrBuilder.UIToFPCast(val, type.DebugType); } result.SetDebugLocation(CurDILocation); result.SetDebugType(type); return result; } public Value InsertFPExt(Value val, _Type type) { var value = IrBuilder.FPExt(val, type.DebugType); value.SetDebugLocation(CurDILocation); value.SetDebugType(type); return value; } public Value InsertFPTrunc(Value val, _Type type) { var value = IrBuilder.FPTrunc(val, type.DebugType); value.SetDebugLocation(CurDILocation); value.SetDebugType(type); return value; } public Value InsertFPToInt(Value val, _Type intType) { Value result; if (val.GetDebugType().IsSigned) { result = IrBuilder.FPToSICast(val, intType.DebugType); } else { result = IrBuilder.FPToUICast(val, intType.DebugType); } result.SetDebugLocation(CurDILocation); result.SetDebugType(intType); return result; } public void InsertUnreachable() { IrBuilder.Unreachable().SetDebugLocation(CurDILocation); } public void InsertUnconditionalBranch(_BasicBlock bb) { IrBuilder.Branch(bb.LlvmBasicBlock) .SetDebugLocation(CurDILocation); } public void InsertConditionalBranch(Value cond, _BasicBlock trueBB, _BasicBlock falseBB) { IrBuilder.Branch(cond, trueBB.LlvmBasicBlock, falseBB.LlvmBasicBlock) .SetDebugLocation(CurDILocation); } public void InsertSwitchAndCases(Value cond, _BasicBlock defaultBB, List casesValues, List<_BasicBlock> casesBBs) { Debug.Assert(cond.NativeType.IsInteger); Value val = cond; // force all values to uint32 so they match the case table for LLVM // CLI spec (ECMA-335 III.3.66) requires an int32 operand that is // treated as unsigned. LLVM requires that the table entries and the // conditional value are of the same type. So zero extend the value // if it is smaller than an i32. if (val.NativeType.IntegerBitWidth < 32) { val = IrBuilder.ZeroExtend(val, Owner.Module.LlvmContext.Int32Type); } var si = IrBuilder.Switch(val, defaultBB.LlvmBasicBlock, (uint)casesBBs.Count) .SetDebugLocation(CurDILocation); for (int i = 0; i < casesBBs.Count; ++i) { si.AddCase(Module.LlvmModule.Context.CreateConstant(casesValues[i]), casesBBs[i].LlvmBasicBlock); } } public Value InsertCall(Value func, _Type returnType, List args, bool isIndirect) { if (isIndirect) { func = CastFunctionPointer(func, returnType, args); } Value retVal = IrBuilder.Call(func, args); retVal.SetDebugLocation(CurDILocation); retVal.SetDebugType(returnType); return retVal; } public Value InsertInvoke( Value func, _Type returnType, List args, bool isIndirect, _BasicBlock nextBlock, _BasicBlock catchBlock) { if (isIndirect) { func = CastFunctionPointer(func, returnType, args); } Value retVal = IrBuilder.Invoke(func, args, nextBlock.LlvmBasicBlock, catchBlock.LlvmBasicBlock); retVal.SetDebugLocation(CurDILocation); retVal.SetDebugType(returnType); return retVal; } private Value CastFunctionPointer(Value pointer, _Type returnType, List args) { // Manufacture a function prototype. var paramTypes = args.Select((Value value) => { return value.NativeType; }); ITypeRef llvmFuncType = Module.LlvmContext.GetFunctionType(returnType.DebugType.NativeType, paramTypes); ITypeRef funcPointerType = llvmFuncType.CreatePointerType(); // Bitcast the given pointer to the prototype we just created. Value extracted = IrBuilder.ExtractValue(pointer, 0) .SetDebugLocation(CurDILocation); return IrBuilder.BitCast(extracted, funcPointerType) .SetDebugLocation(CurDILocation); } static _Type SetValuesForByteOffsetAccess( _Type ty, List values, int offset, out string fieldName ) { for( int i = 0; i < ty.Fields.Count; ++i ) { TypeField thisField = ty.Fields[ i ]; // The first field of a reference type is always a super-class, except for the root System.Object. bool fieldIsParent = ( i == 0 && !ty.IsValueType && ty != _Type.GetOrInsertTypeImpl( ty.Module, ty.Module.TypeSystem.WellKnownTypes.Microsoft_Zelig_Runtime_ObjectHeader ) ); int thisFieldSize = thisField.MemberType.SizeInBits / 8; int curOffset = ( int )thisField.Offset; int nextOffset = curOffset + thisFieldSize; // If the next field is beyond our desired offset, inspect the current field. As offset may index into // a nested field, we must recursively inspect each nested field until we find an exact match. if ( nextOffset > offset ) { values.Add( thisField.FinalIdx ); fieldName = thisField.Name; // If the current offset isn't an exact match, it must be an offset within a nested field. We also // force inspection of parent classes even on an exact match. if ( fieldIsParent || ( curOffset != offset ) ) { return SetValuesForByteOffsetAccess( thisField.MemberType, values, offset - curOffset, out fieldName ); } return thisField.MemberType; } } throw new NotSupportedException( "Invalid offset for field access." ); } public Value GetFieldAddress( Value objAddress, int offset, _Type fieldType ) { Context ctx = Module.LlvmModule.Context; Debug.Assert(objAddress.GetDebugType().IsPointer, "Cannot get field address from a loaded value type."); _Type underlyingType = objAddress.GetUnderlyingType(); List valuesForGep = new List(); // Add an initial 0 value to index into the address. valuesForGep.Add( ctx.CreateConstant( 0 ) ); string fieldName = string.Empty; // Special case: For boxed types, index into the wrapped value type. if ( ( underlyingType != null ) && underlyingType.IsBoxed ) { fieldName = underlyingType.Fields[1].Name; underlyingType = underlyingType.UnderlyingType; valuesForGep.Add(ctx.CreateConstant(1)); } // Don't index into the type's fields if we want the outer struct. This is always true for primitive values, // and usually true for boxed values. if (underlyingType.IsPrimitiveType || (underlyingType == fieldType)) { Debug.Assert( offset == 0, "Primitive and boxed types can only have one member, and it must be at offset zero." ); } else { List values = new List(); underlyingType = SetValuesForByteOffsetAccess( underlyingType, values, offset, out fieldName ); for( int i = 0; i < values.Count; ++i ) { valuesForGep.Add( ctx.CreateConstant( values[ i ] ) ); } } // Special case: No-op trivial GEP instructions, and just return the original address. if( valuesForGep.Count == 1 ) { return objAddress; } var gep = IrBuilder.GetElementPtr(objAddress, valuesForGep) .RegisterName($"{objAddress.Name}.{fieldName}") .SetDebugLocation(CurDILocation); _Type pointerType = Module.GetOrInsertPointerType( underlyingType ); gep.SetDebugType(pointerType); return gep; } public Value IndexLLVMArray(Value obj, Value idx, _Type elementType) { Value[] idxs = { Module.LlvmModule.Context.CreateConstant(0), idx }; Value retVal = IrBuilder.GetElementPtr(obj, idxs) .SetDebugLocation(CurDILocation); _Type pointerType = Module.GetOrInsertPointerType(elementType); retVal.SetDebugType(pointerType); return retVal; } public void InsertRet(Value val) { if (val == null) { IrBuilder.Return() .SetDebugLocation(CurDILocation); } else { IrBuilder.Return(val) .SetDebugLocation(CurDILocation); } } public Value InsertAtomicXchg(Value ptr, Value val) => InsertAtomicBinaryOp(IrBuilder.AtomicXchg, ptr, val); public Value InsertAtomicAdd(Value ptr, Value val) => InsertAtomicBinaryOp(IrBuilder.AtomicAdd, ptr, val); public Value InsertAtomicSub(Value ptr, Value val) => InsertAtomicBinaryOp(IrBuilder.AtomicSub, ptr, val); public Value InsertAtomicAnd(Value ptr, Value val) => InsertAtomicBinaryOp(IrBuilder.AtomicAnd, ptr, val); public Value InsertAtomicNand(Value ptr, Value val) => InsertAtomicBinaryOp(IrBuilder.AtomicNand, ptr, val); public Value InsertAtomicOr(Value ptr, Value val) => InsertAtomicBinaryOp(IrBuilder.AtomicOr, ptr, val); public Value InsertAtomicXor(Value ptr, Value val) => InsertAtomicBinaryOp(IrBuilder.AtomicXor, ptr, val); public Value InsertAtomicMax(Value ptr, Value val) => InsertAtomicBinaryOp(IrBuilder.AtomicMax, ptr, val); public Value InsertAtomicMin(Value ptr, Value val) => InsertAtomicBinaryOp(IrBuilder.AtomicMin, ptr, val); public Value InsertAtomicUMax(Value ptr, Value val) => InsertAtomicBinaryOp(IrBuilder.AtomicUMax, ptr, val); public Value InsertAtomicUMin(Value ptr, Value val) => InsertAtomicBinaryOp(IrBuilder.AtomicUMin, ptr, val); private Value InsertAtomicBinaryOp(Func fn, Value ptr, Value val) { // LLVM atomicRMW returns the old value at ptr Value retVal = fn(ptr, val); retVal.SetDebugLocation(CurDILocation); retVal.SetDebugType(val.GetDebugType()); return retVal; } public Value InsertAtomicCmpXchg(Value ptr, Value cmp, Value val) { // LLVM cmpxchg instruction returns { ty, i1 } for { oldValue, isSuccess } var retVal = IrBuilder.AtomicCmpXchg(ptr, cmp, val); // And we only want the old value var oldVal = IrBuilder.ExtractValue(retVal, 0); oldVal.SetDebugLocation(CurDILocation); oldVal.SetDebugType(val.GetDebugType()); return oldVal; } public LandingPad InsertLandingPad(_Type resultType, Value[] vtables, bool cleanup) { LandingPad landingPad = IrBuilder.LandingPad(resultType.DebugType); landingPad.SetCleanup(cleanup); foreach (Value vtable in vtables) { landingPad.AddClause(vtable); } landingPad.SetDebugType(resultType); return landingPad; } public void InsertResume(Value exception) { IrBuilder.Resume(exception); } public void SetVariableName(Value value, VariableExpression expression) { string name = expression.DebugName?.Name; if (!string.IsNullOrWhiteSpace(name)) { value.RegisterName(name); } } internal InstructionBuilder IrBuilder { get; } internal BasicBlock LlvmBasicBlock { get; } internal DISubProgram CurDISubProgram => CurDILocation?.Scope as DISubProgram; internal DILocation CurDILocation; } } ================================================ FILE: Zelig/Zelig/CompileTime/CodeGenerator/CodeTransformation/LLVM/_Function.cs ================================================ using Llvm.NET; using Llvm.NET.DebugInfo; using Llvm.NET.Values; using System; using System.Diagnostics; using Llvm.NET.Types; using IR = Microsoft.Zelig.CodeGeneration.IR; using TS = Microsoft.Zelig.Runtime.TypeSystem; namespace Microsoft.Zelig.LLVM { /// Subset of AttributeKind values which apply specifically to functions. public enum FunctionAttribute : uint { AlwaysInline = AttributeKind.AlwaysInline, Builtin = AttributeKind.Builtin, Cold = AttributeKind.Cold, Convergent = AttributeKind.Convergent, InlineHint = AttributeKind.InlineHint, JumpTable = AttributeKind.JumpTable, MinSize = AttributeKind.MinSize, Naked = AttributeKind.Naked, NoBuiltin = AttributeKind.NoBuiltin, NoDuplicate = AttributeKind.NoDuplicate, NoImplicitFloat = AttributeKind.NoImplicitFloat, NoInline = AttributeKind.NoInline, NonLazyBind = AttributeKind.NonLazyBind, NoRedZone = AttributeKind.NoRedZone, NoReturn = AttributeKind.NoReturn, NoUnwind = AttributeKind.NoUnwind, OptimizeForSize = AttributeKind.OptimizeForSize, OptimizeNone = AttributeKind.OptimizeNone, ReadNone = AttributeKind.ReadNone, ReadOnly = AttributeKind.ReadOnly, ArgMemOnly = AttributeKind.ArgMemOnly, ReturnsTwice = AttributeKind.ReturnsTwice, StackAlignment = AttributeKind.StackAlignment, StackProtect = AttributeKind.StackProtect, StackProtectReq = AttributeKind.StackProtectReq, StackProtectStrong = AttributeKind.StackProtectStrong, SafeStack = AttributeKind.SafeStack, SanitizeAddress = AttributeKind.SanitizeAddress, SanitizeThread = AttributeKind.SanitizeThread, SanitizeMemory = AttributeKind.SanitizeMemory, UnwindTable = AttributeKind.UWTable, } // REVIEW: // Given that this has no data members beyond those from the base class // this class probably ought to be a static class with extensions methods // on the Llvm.NET.Values.Function class. public class _Function { internal _Function(_Module module, TS.MethodRepresentation method) { Module = module; Method = method; LlvmValue = CreateLLvmFunctionWithDebugInfo(module, method); LlvmValue.SetDebugType(module.Manager.GetOrInsertType(method)); var function = ( Function )LlvmValue; if( function.BasicBlocks.Count == 0 ) function.Linkage( Linkage.ExternalWeak ); if (method.HasBuildTimeFlag(TS.MethodRepresentation.BuildTimeAttributes.Inline)) { AddAttribute(FunctionAttribute.AlwaysInline); } if (method.HasBuildTimeFlag(TS.MethodRepresentation.BuildTimeAttributes.NoInline)) { AddAttribute(FunctionAttribute.NoInline); } if (method.HasBuildTimeFlag(TS.MethodRepresentation.BuildTimeAttributes.BottomOfCallStack)) { AddAttribute(FunctionAttribute.Naked); } if (method.HasBuildTimeFlag(TS.MethodRepresentation.BuildTimeAttributes.NoReturn)) { AddAttribute(FunctionAttribute.NoReturn); } // Try to find an explicit stack alignment attribute and apply it if it exists. TS.WellKnownTypes wkt = module.TypeSystem.WellKnownTypes; TS.CustomAttributeRepresentation alignAttr = method.FindCustomAttribute(wkt.Microsoft_Zelig_Runtime_AlignmentRequirementsAttribute); if (alignAttr != null) { AddAttribute(FunctionAttribute.StackAlignment, (uint)alignAttr.FixedArgsValues[0]); } } public TS.MethodRepresentation Method { get; } // In LLVM, the context owns the value. However, a _Module here is a container for the // context, a NativeModule, and a DiBuilder with assorted other state info. public _Module Module { get; } public Function LlvmFunction => (Function)LlvmValue; private Value LlvmValue { get; } public void AddAttribute(FunctionAttribute kind) { LlvmFunction.AddAttributes((AttributeKind)kind); } public void AddAttribute(FunctionAttribute kind, ulong value) { LlvmFunction.AddAttributes(new AttributeValue((AttributeKind)kind, value)); } public void RemoveAttribute(FunctionAttribute kind) { LlvmFunction.RemoveAttribute((AttributeKind)kind); } public _BasicBlock GetOrInsertBasicBlock(string blockName) { return new _BasicBlock(this, LlvmFunction.FindOrCreateNamedBlock(blockName)); } public Value GetLocalStackValue( TS.MethodRepresentation method, _BasicBlock block, IR.VariableExpression val, LLVMModuleManager manager) { block.EnsureDebugInfo( manager, method ); bool hasDebugName = !string.IsNullOrWhiteSpace( val.DebugName?.Name ); Value retVal = block.InsertAlloca( hasDebugName ? val.DebugName.Name : val.ToString( ), manager.GetOrInsertType( val.Type ) ); // If the local had a valid symbolic name in the source code, generate debug info for it. if( !hasDebugName ) { return retVal; } DILocalVariable localSym; _Type valType = manager.GetOrInsertType( val.Type ); var argExpression = val as IR.ArgumentVariableExpression; if( argExpression != null ) { // Adjust index since IR form keeps slot = 0 as the "this" param for static methods it just sets that to // null. LLVM doesn't have any notion of that and only has a slot for an actual arg. var index = checked( ( ushort )argExpression.Number ); if( method is TS.StaticMethodRepresentation ) { index--; } localSym = Module.DIBuilder.CreateArgument( block.CurDISubProgram , val.DebugName.Name , block.CurDILocation.Scope.File , block.CurDILocation.Line , valType.DIType , true , DebugInfoFlags.None , checked( (ushort)(index + 1) ) // LLVM debug arg index is one based ); } else { localSym = Module.DIBuilder.CreateLocalVariable( block.CurDISubProgram , val.DebugName.Name , block.CurDILocation.Scope.File , block.CurDILocation.Line , valType.DIType , true , DebugInfoFlags.None ); } // For reference types passed as a pointer, tell debugger to deref the pointer. DIExpression expr = Module.DIBuilder.CreateExpression( ); if( !retVal.GetDebugType().IsValueType ) { expr = Module.DIBuilder.CreateExpression( ExpressionOp.deref ); } Module.DIBuilder.InsertDeclare( retVal, localSym, expr, block.CurDILocation, block.LlvmBasicBlock ); return retVal; } public void SetExternalLinkage() { LlvmFunction.Linkage = Linkage.External; } public void SetInternalLinkage() { LlvmFunction.Linkage = Linkage.Internal; } private static Function CreateLLvmFunctionWithDebugInfo( _Module module, TS.MethodRepresentation method ) { string mangledName = LLVMModuleManager.GetFullMethodName( method ); _Type functionType = module.Manager.GetOrInsertType( method ); Debugging.DebugInfo loc = module.Manager.GetDebugInfoFor( method ); Debug.Assert( loc != null ); var containingType = module.GetOrInsertType( method.OwnerType ); // Create the DISupprogram info var retVal = module.LlvmModule.CreateFunction( containingType?.DIType ?? ( DIScope )module.DICompileUnit , method.Name , mangledName , module.GetOrCreateDIFile( loc.SrcFileName ) , ( uint )loc.BeginLineNumber , (DebugFunctionType)functionType.DebugType , true , true , ( uint )loc.EndLineNumber , DebugInfoFlags.None // TODO: Map Zelig accesibility info etc... to flags , false ); bool isStatic = method is TS.StaticMethodRepresentation; // "this" is always at index 0, for static functions the name for "this" is null int paramBase = isStatic ? 1 : 0; string[] argumentNames = null; if(method.ArgumentNames == null) { argumentNames = new string[ method.ThisPlusArguments.Length ]; if(method is TS.InstanceMethodRepresentation) { argumentNames[ 0 ] = "this"; } else { throw TypeConsistencyErrorException.Create( "Generic method {0} has not been instantiated correctly", method.FullyQualifiedName ); } } else { argumentNames = method.ArgumentNames; } Debug.Assert( retVal != null && argumentNames.Length - paramBase == retVal.Parameters.Count ); for( int i = paramBase; i < argumentNames.Length; ++i ) { string name = argumentNames[ i ]; if( string.IsNullOrWhiteSpace( name ) ) name = $"$ARG{i}"; // adjust the index for the native type since there's not assumption that [0]=="this" retVal.Parameters[ i - paramBase ].Name = name; } return retVal; } } } ================================================ FILE: Zelig/Zelig/CompileTime/CodeGenerator/CodeTransformation/LLVM/_Module.cs ================================================ using System; using System.Linq; using System.Collections.Generic; using System.Diagnostics; using Llvm.NET.Values; using Llvm.NET; using Llvm.NET.Types; using Llvm.NET.DebugInfo; using Microsoft.Zelig.CodeGeneration.IR; using Microsoft.Zelig.Runtime.TypeSystem; using Microsoft.Zelig.Debugging; using ConstantExpression = Llvm.NET.Values.ConstantExpression; namespace Microsoft.Zelig.LLVM { public enum OutputFormat { BitCodeBinary, BitCodeSource, TargetObjectFile, TargetAsmSource } public class _Module { public _Module( string assemblyName, TypeSystemForCodeTransformation typeSystem ) { StaticState.RegisterAll( ); // REVIEW: Need to deal with how LLVM thinks about threads and context // and figure out how to map it to how Zelig system uses threads... // for now assuming the LLVM code gen is done on a single thread // and ignoring the issue of disposing the Context. var context = new Context( ); // TODO: Get target triple from command line instead of hard coding it here. var target = Target.FromTriple( Target.ThumbV7mEabiTriple ); TargetMachine = target.CreateTargetMachine( context , Target.ThumbV7mEabiTriple , string.Empty // CPU , string.Empty // features , CodeGenOpt.None // hard code no optimizations for easier debugging for now... , Reloc.Static , CodeModel.Default ); // REVIEW: What happens when we start interacting with assemblies written in other languages? // At the moment this is setting the entire module to CSharp. LlvmModule = new NativeModule( assemblyName, context, SourceLanguage.CSharp, "out.bc", "ZeligIR2LLVMIR", false, "", 0 ) { TargetTriple = TargetMachine.Triple, Layout = TargetMachine.TargetData }; LlvmModule.AddModuleFlag( ModuleFlagBehavior.Override, NativeModule.DebugVersionValue, NativeModule.DebugMetadataVersion ); TypeSystem = typeSystem; } internal LLVMModuleManager Manager => TypeSystem.Module; internal TypeSystemForCodeTransformation TypeSystem { get; } public _Type GetOrInsertType( TypeRepresentation tr ) { return _Type.GetOrInsertTypeImpl( this, tr ); } public _Type GetOrInsertFunctionType( string name, _Type returnType, List<_Type> argTypes ) { var llvmArgs = argTypes.Select( t => t.DebugType ); var funcType = LlvmModule.Context.CreateFunctionType( LlvmModule.DIBuilder , returnType.DebugType , llvmArgs ); _Type timpl = _Type.GetOrInsertTypeImpl( this, name, 0, true, funcType ); return timpl; } public _Type GetOrInsertPointerType( PointerTypeRepresentation tr, _Type underlyingType ) { Debug.Assert( !underlyingType.DebugType.IsVoid ); var ptrType = new DebugPointerType( underlyingType.DebugType, LlvmModule ); var retVal = _Type.GetOrInsertTypeImpl( this, tr, ptrType ); retVal.UnderlyingType = underlyingType; return retVal; } // REVIEW: Figure out if we can remove this, it's one of the reasons we have to keep using strings as the key for cacheing public _Type GetOrInsertPointerType( _Type underlyingType ) { Debug.Assert( !underlyingType.DebugType.IsVoid ); var ptrType = new DebugPointerType( underlyingType.DebugType, LlvmModule ); var sizeAndAlign = PointerSize; var retVal = _Type.GetOrInsertTypeImpl( this, underlyingType.Name + "*", ( int )sizeAndAlign, true, ptrType ); retVal.UnderlyingType = underlyingType; return retVal; } public _Type GetOrInsertZeroSizedArray( _Type type ) { var arrayType = new DebugArrayType( type.DebugType, LlvmModule, 0 ); var retVal = _Type.GetOrInsertTypeImpl( this, $"MemoryArray of {type.Name}", type.SizeInBits, true, arrayType ); return retVal; } public _Type GetType( TypeRepresentation tr ) => _Type.GetOrInsertTypeImpl( this, tr ); public _Type GetVoidType( ) => GetType( TypeSystem.WellKnownTypes.System_Void ); public _Type GetNativeBoolType() { var boolType = new DebugBasicType(LlvmModule.Context.GetIntType(1), LlvmModule, "bool", DiTypeKind.Boolean); return _Type.GetOrInsertTypeImpl(this, "bool", 1, true, boolType); } internal DINamespace GetOrCreateDINamespace( TypeRepresentation tr ) { return GetOrCreateDINamespace( tr.Namespace ); } // Get a debug namespace descriptor from a Fully Qualified Name (FQN) for a namespace // the FQNS name uses the standard .NET dotted form (parent.nested1.nested2[...]) private DINamespace GetOrCreateDINamespace( string fullName ) { // "global" namespace is null if( string.IsNullOrWhiteSpace( fullName ) ) return null; // try the cached mapping first DINamespace retVal; if( m_DiNamespaces.TryGetValue( fullName, out retVal ) ) return retVal; // find last "." in the name to get the most nested name var parentLen = fullName.LastIndexOf( '.' ); if( parentLen < 0 ) parentLen = fullName.Length; var parentNamespaceName = parentLen == fullName.Length ? null : fullName.Substring( 0, parentLen ); // take everything up to, but not including the last '.' var namespaceName = parentNamespaceName == null ? fullName : fullName.Substring( parentLen + 1 ); // take everything after the last '.' in the name var parent = GetOrCreateDINamespace( parentNamespaceName ); retVal = DIBuilder.CreateNamespace( parent, namespaceName, null, 0 ); m_DiNamespaces.Add( fullName, retVal ); return retVal; } // produces an iterator of all the Fully Qualified Names (FQN) for a given namespace starting with the root name and ending with the given FQN itself IEnumerable GetQualifiedNamespaceNames( string fullName ) { if( string.IsNullOrWhiteSpace( fullName ) ) { yield return null; yield break; } for( int pos = fullName.IndexOf( '.' ); pos > 0 && pos < fullName.Length - 1; pos = fullName.IndexOf( '.', pos + 1 ) ) { // produce name up to but not including the next '.' delimiter yield return fullName.Substring( 0, pos ); } yield return fullName; } public Constant GetScalarConstant(_Type type, object value) { Constant ucv = GetUCVScalar(type, value); ucv.SetDebugType(type); return ucv; } public Constant GetNullValue(_Type type) { Constant ucv = type.DebugType.GetNullValue(); ucv.SetDebugType(type); return ucv; } public _Function GetOrInsertFunction( MethodRepresentation method ) { _Function retVal; if( m_FunctionMap.TryGetValue( method.Identity, out retVal ) ) return retVal; retVal = new _Function( this, method ); m_FunctionMap.Add( method.Identity, retVal ); return retVal; } public Constant GetUCVStruct( _Type structType, List structMembers, bool anon ) { // Special case: Primitive types aren't wrapped in structs, so return the wrapped value directly. if ( structType.IsPrimitiveType ) { return structMembers[0]; } List fields = new List( ); var llvmStructType = ( IStructType )structType.DebugType; if( structMembers != null ) { foreach( Constant ucv in structMembers ) { var curVal = ucv; var curType = llvmStructType.Members[ fields.Count ]; // Special case: Constant objects containing arrays may not strictly match the target pointer type, // as the variable type always has zero elements. In these cases, we need to bitcast the pointer. if( curType.IsPointer && ( curVal.NativeType != curType ) ) { curVal = ConstantExpression.BitCast( curVal, curType ); } fields.Add( curVal ); } } Constant retVal; if( anon ) { retVal = LlvmModule.Context.CreateConstantStruct( true, fields ); } else { retVal = LlvmModule.Context.CreateNamedConstantStruct( llvmStructType, fields ); } return retVal; } public Constant GetUCVArray( _Type arrayMemberType, List arrayMembers ) { var members = new List( ); ITypeRef curType = arrayMemberType.DebugType; if( arrayMembers != null ) { foreach( Constant ucv in arrayMembers ) { Constant curVal = ucv; if( curType.IsPointer && curVal.NativeType != curType ) { curVal = ConstantExpression.BitCast( curVal, curType ); } members.Add( curVal ); } } return ConstantArray.From( curType, members ); } public Constant GetUCVScalar( _Type type, object value ) { if( type.IsInteger ) { // Note: This does not cover enums. ulong intValue = ( value is ulong ) ? (ulong)value : (ulong)Convert.ToInt64( value ); return LlvmModule.Context.CreateConstant( type.DebugType, intValue, type.IsSigned ); } else if( type.IsFloat ) { return LlvmModule.Context.CreateConstant( (float)value ); } else if( type.IsDouble ) { return LlvmModule.Context.CreateConstant( (double)value ); } else if( type.TypeRepresentation == TypeSystem.WellKnownTypes.System_IntPtr ) { Constant ucv = LlvmModule.Context.CreateConstant( (uint)type.SizeInBits, (ulong)value, true ); return ConstantExpression.IntToPtrExpression( ucv, type.DebugType ); } else if( type.TypeRepresentation == TypeSystem.WellKnownTypes.System_UIntPtr ) { Constant ucv = LlvmModule.Context.CreateConstant( (uint)type.SizeInBits, value is ulong ? (ulong)value : ((UIntPtr)value).ToUInt64(), false ); return ConstantExpression.IntToPtrExpression( ucv, type.DebugType ); } throw new InvalidCastException( "Cannot create a scalar constant of non-scalar type." ); } public Constant GetUCVZeroInitialized( _Type type ) { return type.DebugType.GetNullValue( ); } public Constant GetUninitializedGlobal(_Type type) { var gv = LlvmModule.AddGlobal(type.DebugType, string.Empty); gv.IsConstant = false; gv.Linkage = Linkage.Internal; // This returns the equivalent of a "this" pointer for the object. gv.SetDebugType(GetOrInsertPointerType(type)); return gv; } public Constant GetGlobalFromUCV( _Type type, Constant header, Constant ucv, bool isConstant, string name, string sectionName) { string uniqueName = $"{name}_{GetMonotonicUniqueId()}"; // Wrap the value with a header if one is provided. if (header != null) { ucv = LlvmModule.Context.CreateConstantStruct(true, header, ucv); } GlobalVariable global = LlvmModule.AddGlobal(ucv.NativeType, uniqueName); global.IsConstant = isConstant; global.Linkage = Linkage.Internal; global.Initializer = ucv; global.Section = sectionName; // For real constant data mark it as unnammed_addr to allow the backend to coalesce identical content. // (e.g. if three globals are declared of the same type with the same constant data initializer, then // only one copy is really required in the final image generated by the linker. global.UnnamedAddress = isConstant; // Return a pointer to the beginning of the unwrapped payload. Constant result = global; if (header != null) { // Ensure the header portion of the global is marked as used. m_usedGlobals.Add(global); Constant[] indices = { LlvmModule.Context.CreateConstant(0), LlvmModule.Context.CreateConstant(1), }; result = ConstantExpression.GetElementPtr(result, indices); } // This returns the equivalent of a "this" pointer for the object. result.SetDebugType(GetOrInsertPointerType(type)); return result; } public void FinalizeGlobals() { // Add all marked globals to a keep-alive data structure that LLVM recognizes. if (m_usedGlobals.Count != 0) { _Type pointerType = GetOrInsertType(TypeSystem.WellKnownTypes.System_IntPtr); var globalPointers = new List(m_usedGlobals.Count); foreach (var global in m_usedGlobals) { Constant pointer = ConstantExpression.BitCast(global, pointerType.DebugType); globalPointers.Add(pointer); } // Note: The following global and section names are prescribed by LLVM and must not change. Constant ucv = GetUCVArray(pointerType, globalPointers); var llvmUsed = LlvmModule.AddGlobal(ucv.NativeType, false, Linkage.Append, ucv, "llvm.used"); llvmUsed.Section = "llvm.metadata"; } } public void CreateAlias(Value value, string name) { var gv = value as GlobalObject; if (gv != null) { var alias = LlvmModule.AddAlias(gv, name); alias.Linkage = Linkage.External; } else { Console.Error.WriteLine("Warning: Ignoring alias \"{0}\" because aliasee is not global.", name); } } public bool Compile( ) { DIBuilder.Finish( ); // performing a verify pass here is just a waste of time... // Emiting the bit code file will perform a verify //string msg; //if( !LlvmModule.Verify( out msg ) ) //{ // // TODO: we need a better error handling strategy than this! // Console.Error.WriteLine( msg ); // throw new NotSupportedException( $"LLVM module verification failed:\n{msg}" ); //} return true; } public bool DumpToFile( string fileName, OutputFormat format ) { DIBuilder.Finish( ); try { switch( format ) { case OutputFormat.BitCodeBinary: LlvmModule.WriteToFile( fileName ); return true; case OutputFormat.BitCodeSource: System.IO.File.WriteAllText( fileName, LlvmModule.AsString( ) ); return true; case OutputFormat.TargetObjectFile: TargetMachine.EmitToFile( LlvmModule, fileName, CodeGenFileType.ObjectFile ); return true; case OutputFormat.TargetAsmSource: TargetMachine.EmitToFile( LlvmModule, fileName, CodeGenFileType.AssemblySource ); return true; default: return false; } } catch( System.IO.IOException ex ) { Console.Error.WriteLine( ex.ToString( ) ); return false; } } // REVIEW: This can be generalized to creating any function by prototype. public Function GetPersonalityFunction(string functionName) { Function function = LlvmModule.GetFunction(functionName); if (function == null) { _Type intType = _Type.GetOrInsertTypeImpl(this, TypeSystem.WellKnownTypes.System_Int32); function = LlvmModule.CreateFunction(functionName, true, intType.DebugType); } return function; } internal uint NativeIntSize => LlvmModule.Layout.IntPtrType( ).IntegerBitWidth; internal uint PointerSize => LlvmModule.Layout.IntPtrType( ).IntegerBitWidth; internal Context LlvmContext => LlvmModule.Context; internal DebugInfoBuilder DIBuilder => LlvmModule.DIBuilder; internal DICompileUnit DICompileUnit => LlvmModule.DICompileUnit; internal NativeModule LlvmModule { get; } internal TargetMachine TargetMachine { get; } internal DIFile GetOrCreateDIFile( string fn ) { if( string.IsNullOrWhiteSpace( fn ) ) return null; DIFile retVal; if( m_DiFiles.TryGetValue( fn, out retVal ) ) return retVal; retVal = DIBuilder.CreateFile( fn ); m_DiFiles.Add( fn, retVal ); return retVal; } private Function CreateLLvmFunctionWithDebugInfo( MethodRepresentation method ) { string mangledName = LLVMModuleManager.GetFullMethodName( method ); _Type functionType = Manager.GetOrInsertType( method ); DebugInfo loc = method.DebugInfo ?? Manager.GetDebugInfoFor( method ); Debug.Assert( loc != null ); // Create the DISupprogram info var retVal = LlvmModule.CreateFunction( DICompileUnit , method.Name , mangledName , GetOrCreateDIFile( loc.SrcFileName ) , ( uint )loc.BeginLineNumber , ( DebugFunctionType )functionType.DebugType , true , true , ( uint )loc.EndLineNumber , DebugInfoFlags.None // TODO: Map Zelig accesibility info etc... to flags , false ); return retVal; } private readonly Dictionary m_DiFiles = new Dictionary( ); private readonly Dictionary m_FunctionMap = new Dictionary( ); private readonly Dictionary m_DiNamespaces = new Dictionary( ); private readonly List m_usedGlobals = new List(); static int GetMonotonicUniqueId( ) { return ( int )System.Threading.Interlocked.Increment( ref globalsCounter ); } static Int64 globalsCounter; } } ================================================ FILE: Zelig/Zelig/CompileTime/CodeGenerator/CodeTransformation/LLVM/_Type.cs ================================================ using System; using System.Collections.Generic; using System.Diagnostics; using System.Text; using Llvm.NET; using Llvm.NET.DebugInfo; using Llvm.NET.Types; using Microsoft.Zelig.Runtime.TypeSystem; namespace Microsoft.Zelig.LLVM { public class _Type { private static readonly Dictionary< string, _Type > TypeImplMap = new Dictionary< string, _Type >( ); private NativeModule LlvmModule => Module.LlvmModule; internal List< DebugMemberInfo > DiFields = new List< DebugMemberInfo >( ); internal _Type( _Module owner, string name, int sizeInBits, bool isValueType, IDebugType typeRef ) { Debug.Assert( typeRef != null ); Module = owner; SizeInBits = sizeInBits; IsValueType = isValueType; DebugType = typeRef; Name = name; } public _Type( _Module owner, TypeRepresentation tr, IDebugType typeRef ) { TypeRepresentation = tr; Module = owner; SizeInBits = (int)tr.Size * 8; IsValueType = tr is ValueTypeRepresentation; Name = tr.FullName; DebugType = typeRef; } public _Type( _Module owner, TypeRepresentation tr ) { TypeRepresentation = tr; Module = owner; SizeInBits = ( int )tr.Size * 8; IsValueType = tr is ValueTypeRepresentation; Name = tr.FullName; Debug.Assert( LlvmModule.GetTypeByName( Name ) == null, "Trying to override _Type" ); DINamespace diNamespace = Module.GetOrCreateDINamespace( tr ); IDebugType baseType; // Basic types need to use DebugBasicType since the LLVM primitive types are all uniqued // and some of them would end up overlapping (i.e. System.UInt16 and Char are both i16 to // LLVM but need distinct DIBasicType instances to describe them for the debugger) switch( Name ) { case "System.Void": // DIType == null means void baseType = Llvm.NET.DebugInfo.DebugType.Create( LlvmModule.Context.VoidType, ( DIType )null ); DebugType = CreateBasicTypeDef( baseType, tr.Name, diNamespace ); break; case "System.Char": baseType = new DebugBasicType( LlvmModule.Context.GetIntType( ( uint )SizeInBits ), LlvmModule, tr.FullName, DiTypeKind.UTF ); DebugType = CreateBasicTypeDef( baseType, tr.Name, diNamespace ); IsPrimitiveType = true; break; case "System.Boolean": baseType = new DebugBasicType( LlvmModule.Context.GetIntType( ( uint )SizeInBits ), LlvmModule, tr.FullName, DiTypeKind.Boolean ); DebugType = CreateBasicTypeDef( baseType, tr.Name, diNamespace ); IsPrimitiveType = true; break; case "System.SByte": case "System.Int16": case "System.Int32": case "System.Int64": baseType = new DebugBasicType( LlvmModule.Context.GetIntType( ( uint )SizeInBits ), LlvmModule, tr.FullName, DiTypeKind.Signed ); DebugType = CreateBasicTypeDef( baseType, tr.Name, diNamespace ); IsPrimitiveType = true; IsSigned = true; break; case "System.Byte": case "System.UInt16": case "System.UInt32": case "System.UInt64": baseType = new DebugBasicType( LlvmModule.Context.GetIntType( ( uint )SizeInBits ), LlvmModule, tr.FullName, DiTypeKind.Unsigned ); DebugType = CreateBasicTypeDef( baseType, tr.Name, diNamespace ); IsPrimitiveType = true; break; case "System.Single": baseType = new DebugBasicType( LlvmModule.Context.FloatType, LlvmModule, tr.FullName, DiTypeKind.Float ); DebugType = CreateBasicTypeDef( baseType, tr.Name, diNamespace ); IsPrimitiveType = true; break; case "System.Double": baseType = new DebugBasicType( LlvmModule.Context.DoubleType, LlvmModule, tr.FullName, DiTypeKind.Float ); DebugType = CreateBasicTypeDef( baseType, tr.Name, diNamespace ); IsPrimitiveType = true; break; case "System.IntPtr": case "System.UIntPtr": // While this is generally void* in C#, LLVM doesn't have a void pointer type. // To help keep the debug views more readable, this creates a typedef for the // pointer, since pointer types don't have names var basePtrType = new DebugPointerType( LlvmModule.Context.Int8Type, LlvmModule, null ); var typeDef = LlvmModule.DIBuilder.CreateTypedef( basePtrType, tr.Name, null, 0, diNamespace ); DebugType = new DebugPointerType( basePtrType.NativeType, typeDef ); IsPrimitiveType = true; break; default: // All other types are created as structures with the Debug type as a temporary. // Creation of concrete DIType is deferred until SetupFields when full field // layout information is known. DebugType = new DebugStructType( LlvmModule, tr.FullName, (DIScope)diNamespace ?? LlvmModule.DICompileUnit, tr.FullName ); break; } } internal TypeRepresentation TypeRepresentation { get; } public bool IsDouble => DebugType.IsDouble; public bool IsFloat => DebugType.IsFloat; public bool IsFloatingPoint => DebugType.IsFloatingPoint; public bool IsInteger => DebugType.IsInteger; public bool IsPointer => DebugType.IsPointer; public bool IsStruct => DebugType.IsStruct; public bool IsValueType { get; } public bool IsBoxed { get; set; } public bool IsPrimitiveType { get; } public bool IsSigned { get; } internal _Module Module { get; } internal DIType DIType => DebugType.DIType; internal List< TypeField > Fields { get; } = new List< TypeField >( ); public IDebugType DebugType { get; } public int SizeInBits { get; } public string Name { get; } public _Type UnderlyingType { get; internal set; } // This overload is used for synthetic types such as function signatures, memory arrays, pointers and boxed value types // that don't have a corresponding TypeRepresentation internal static _Type GetOrInsertTypeImpl( _Module owner, string name, int sizeInBits, bool isValueType, IDebugType ty ) { _Type retVal; if( TypeImplMap.TryGetValue( name, out retVal ) ) return retVal; retVal = new _Type( owner, name, sizeInBits, isValueType, ty ); TypeImplMap.Add( name, retVal ); return retVal; } internal static _Type GetOrInsertTypeImpl( _Module owner, TypeRepresentation tr, IDebugType ty ) { _Type retVal; if( TypeImplMap.TryGetValue( tr.FullName, out retVal ) ) return retVal; retVal = new _Type( owner, tr, ty ); TypeImplMap.Add( tr.FullName, retVal ); return retVal; } internal static _Type GetOrInsertTypeImpl( _Module owner, TypeRepresentation tr ) { _Type retVal; if( TypeImplMap.TryGetValue( tr.FullName, out retVal ) ) return retVal; retVal = new _Type( owner, tr ); TypeImplMap.Add( tr.FullName, retVal ); return retVal; } public void AddField( uint offset, _Type type, string name ) { TypeField field = new TypeField( name, type, offset ); // Add the field in offset order, by moving all other pointer to fields // Not the most efficient approach for C# but mirrors the original C++ code Fields.Add( default(TypeField) ); // increase count by one var i = 0; for( i = Fields.Count - 1; i > 0; --i ) { if( Fields[ i - 1 ].Offset <= field.Offset ) break; Fields[ i ] = Fields[ i - 1 ]; } Fields[ i ] = field; } private void AddTypeToStruct( TypeField field, ICollection< ITypeRef > llvmFields, ref uint offset ) { field.FinalIdx = ( uint ) llvmFields.Count; llvmFields.Add( field.MemberType.DebugType ); offset += ( uint ) field.MemberType.SizeInBits / 8; } public void SetupFields( ) { var structType = DebugType as DebugStructType; if( structType == null ) return; var llvmFields = new List< ITypeRef >( ); var idx = 0; uint offset = 0; while( offset < SizeInBits/8 ) { if( ( idx < Fields.Count ) && ( Fields[ idx ].Offset == offset ) ) { AddTypeToStruct( Fields[ idx ], llvmFields, ref offset ); AddDiField( Fields[ idx ], idx, offset, flags: 0 ); ++idx; } else { // Add explicit padding if necessary. // TODO: Clean this up with a single byte array [ n x i8 ] llvmFields.Add( GetOrInsertTypeImpl( Module, Module.TypeSystem.WellKnownTypes.System_Byte ).DebugType ); ++offset; } } // Add in any remaining fields beyond the expected structure size. These should generally be zero-sized, // such as System.Object and the elements trailing strings/arrays. for( ; idx < Fields.Count; ++idx ) { // NOTE: order of calls matters here as offset is a ref param and updated in the call to AddTypeToStruct. AddDiField( Fields[ idx ], idx, offset, flags: 0 ); AddTypeToStruct( Fields[ idx ], llvmFields, ref offset ); } // BUGBUG: We don't yet handle explicit struct layout with overlapping fields. structType.SetBody( true, LlvmModule, LlvmModule.DICompileUnit, null, 0, 0, llvmFields, DiFields, (uint)SizeInBits, 0 ); } private void AddDiField( TypeField field, int index, uint offset, DebugInfoFlags flags ) { var structType = DebugType as IStructType; Debug.Assert( structType != null ); Debug.Assert( field.MemberType.DIType != null ); var memberDiType = field.MemberType.DebugType; // TODO: since Zelig takes explicit control of layout the alignment needs to come from Zelig somewhere... var debugMemberInfo = new DebugMemberInfo { Name = field.Name , DebugType = memberDiType , Index = (uint)index , DebugInfoFlags = flags , ExplicitLayout = new DebugMemberLayout( ( uint )field.MemberType.SizeInBits, 0 /* ???? */, offset * 8UL) /* todo: file, line... (Zelig IL parsing doesn't seem to capture source locations for fields)*/ }; DiFields.Add( debugMemberInfo ); } private IDebugType CreateBasicTypeDef( IDebugType baseType, string name, DINamespace ns ) { //baseType = Llvm.NET.DebugInfo.DebugType.Create( LlvmModule.Context.VoidType, ( DIType )null ); var typeDef = LlvmModule.DIBuilder.CreateTypedef( baseType.DIType, name, null, 0, ns ); return Llvm.NET.DebugInfo.DebugType.Create( baseType.NativeType, typeDef ); } } } ================================================ FILE: Zelig/Zelig/CompileTime/CodeGenerator/CodeTransformation/Operators/BinaryOperatorWithCarryIn.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // namespace Microsoft.Zelig.CodeGeneration.IR { using System; using System.Collections.Generic; using Microsoft.Zelig.Runtime.TypeSystem; public sealed class BinaryOperatorWithCarryIn : AbstractBinaryOperator { // // Constructor Methods // private BinaryOperatorWithCarryIn( Debugging.DebugInfo debugInfo , OperatorCapabilities capabilities , OperatorLevel level , ALU alu , bool fSigned , bool fOverflow ) : base( debugInfo, capabilities, level, alu, fSigned, fOverflow ) { } //--// public static BinaryOperatorWithCarryIn New( Debugging.DebugInfo debugInfo , ALU alu , bool fSigned , bool fOverflow , VariableExpression lhs , Expression rhsLeft , Expression rhsRight , VariableExpression rhsCC ) { CHECKS.ASSERT( rhsCC.AliasedVariable is ConditionCodeExpression, "rhsCC parameter has to alias a condition code" ); OperatorCapabilities capabilities = OperatorCapabilities.DoesNotMutateExistingStorage | OperatorCapabilities.DoesNotAllocateStorage | OperatorCapabilities.DoesNotReadExistingMutableStorage | OperatorCapabilities.DoesNotReadThroughPointerOperands | OperatorCapabilities.DoesNotWriteThroughPointerOperands | OperatorCapabilities.DoesNotCapturePointerOperands ; switch(alu) { case ALU.ADD: case ALU.MUL: case ALU.AND: case ALU.OR: case ALU.XOR: capabilities |= OperatorCapabilities.IsCommutative; break; default: capabilities |= OperatorCapabilities.IsNonCommutative; break; } if(fOverflow) capabilities |= OperatorCapabilities.MayThrow; else capabilities |= OperatorCapabilities.DoesNotThrow; OperatorLevel level = fOverflow ? OperatorLevel.ConcreteTypes : OperatorLevel.Lowest; var res = new BinaryOperatorWithCarryIn( debugInfo, capabilities, level, alu, fSigned, fOverflow ); res.SetLhs( lhs ); res.SetRhs( rhsLeft, rhsRight, rhsCC ); return res; } //--// // // Helper Methods // public override Operator Clone( CloningContext context ) { return RegisterAndCloneState( context, new BinaryOperatorWithCarryIn( m_debugInfo, m_capabilities, m_level, m_alu, m_fSigned, m_fOverflow ) ); } //--// // // Access Methods // //--// // // Debug Methods // public override void InnerToString( System.Text.StringBuilder sb ) { sb.Append( "BinaryOperatorWithCarryIn(" ); base.InnerToString( sb ); sb.Append( ")" ); } public override string FormatOutput( IIntermediateRepresentationDumper dumper ) { return dumper.FormatOutput( "{0} = {1} {2} {3} <= {4}", this.FirstResult, this.FirstArgument, m_alu, this.SecondArgument, this.ThirdArgument ); } } } ================================================ FILE: Zelig/Zelig/CompileTime/CodeGenerator/CodeTransformation/Operators/BinaryOperatorWithCarryInAndOut.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // namespace Microsoft.Zelig.CodeGeneration.IR { using System; using System.Collections.Generic; using Microsoft.Zelig.Runtime.TypeSystem; public sealed class BinaryOperatorWithCarryOut : AbstractBinaryOperator { // // Constructor Methods // private BinaryOperatorWithCarryOut( Debugging.DebugInfo debugInfo , OperatorCapabilities capabilities , OperatorLevel level , ALU alu , bool fSigned , bool fOverflow ) : base( debugInfo, capabilities, level, alu, fSigned, fOverflow ) { } //--// public static BinaryOperatorWithCarryOut New( Debugging.DebugInfo debugInfo , ALU alu , bool fSigned , bool fOverflow , VariableExpression lhs , VariableExpression cc , Expression rhsLeft , Expression rhsRight ) { CHECKS.ASSERT( cc.AliasedVariable is ConditionCodeExpression, "Invalid type for condition code: {0}", cc ); OperatorCapabilities capabilities = OperatorCapabilities.DoesNotMutateExistingStorage | OperatorCapabilities.DoesNotAllocateStorage | OperatorCapabilities.DoesNotReadExistingMutableStorage | OperatorCapabilities.DoesNotReadThroughPointerOperands | OperatorCapabilities.DoesNotWriteThroughPointerOperands | OperatorCapabilities.DoesNotCapturePointerOperands ; switch(alu) { case ALU.ADD: case ALU.MUL: case ALU.AND: case ALU.OR: case ALU.XOR: capabilities |= OperatorCapabilities.IsCommutative; break; default: capabilities |= OperatorCapabilities.IsNonCommutative; break; } if(fOverflow) capabilities |= OperatorCapabilities.MayThrow; else capabilities |= OperatorCapabilities.DoesNotThrow; OperatorLevel level = fOverflow ? OperatorLevel.ConcreteTypes : OperatorLevel.Lowest; var res = new BinaryOperatorWithCarryOut( debugInfo, capabilities, level, alu, fSigned, fOverflow ); res.SetLhs( lhs , cc ); res.SetRhs( rhsLeft, rhsRight ); return res; } //--// // // Helper Methods // public override Operator Clone( CloningContext context ) { return RegisterAndCloneState( context, new BinaryOperatorWithCarryOut( m_debugInfo, m_capabilities, m_level, m_alu, m_fSigned, m_fOverflow ) ); } //--// // // Access Methods // //--// // // Debug Methods // public override void InnerToString( System.Text.StringBuilder sb ) { sb.Append( "BinaryOperatorWithCarryOut(" ); base.InnerToString( sb ); sb.Append( ")" ); } public override string FormatOutput( IIntermediateRepresentationDumper dumper ) { return dumper.FormatOutput( "{0}, {1} = {2} {3} {4}{5}", this.FirstResult, this.SecondResult, this.FirstArgument, m_alu, this.SecondArgument, this.MayThrow ? " MayThrow" : "" ); } } } ================================================ FILE: Zelig/Zelig/CompileTime/CodeGenerator/CodeTransformation/Operators/BinaryOperatorWithCarryOut.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // namespace Microsoft.Zelig.CodeGeneration.IR { using System; using System.Collections.Generic; using Microsoft.Zelig.Runtime.TypeSystem; public sealed class BinaryOperatorWithCarryInAndOut : AbstractBinaryOperator { // // Constructor Methods // private BinaryOperatorWithCarryInAndOut( Debugging.DebugInfo debugInfo , OperatorCapabilities capabilities , OperatorLevel level , ALU alu , bool fSigned , bool fOverflow ) : base( debugInfo, capabilities, level, alu, fSigned, fOverflow ) { } //--// public static BinaryOperatorWithCarryInAndOut New( Debugging.DebugInfo debugInfo , ALU alu , bool fSigned , bool fOverflow , VariableExpression lhs , VariableExpression lhsCC , Expression rhsLeft , Expression rhsRight , VariableExpression rhsCC ) { CHECKS.ASSERT( lhsCC.AliasedVariable is ConditionCodeExpression, "Invalid type for condition code: {0}", lhsCC ); CHECKS.ASSERT( rhsCC.AliasedVariable is ConditionCodeExpression, "Invalid type for condition code: {0}", rhsCC ); OperatorCapabilities capabilities = OperatorCapabilities.DoesNotMutateExistingStorage | OperatorCapabilities.DoesNotAllocateStorage | OperatorCapabilities.DoesNotReadExistingMutableStorage | OperatorCapabilities.DoesNotReadThroughPointerOperands | OperatorCapabilities.DoesNotWriteThroughPointerOperands | OperatorCapabilities.DoesNotCapturePointerOperands ; switch(alu) { case ALU.ADD: case ALU.MUL: case ALU.AND: case ALU.OR: case ALU.XOR: capabilities |= OperatorCapabilities.IsCommutative; break; default: capabilities |= OperatorCapabilities.IsNonCommutative; break; } if(fOverflow) capabilities |= OperatorCapabilities.MayThrow; else capabilities |= OperatorCapabilities.DoesNotThrow; OperatorLevel level = fOverflow ? OperatorLevel.ConcreteTypes : OperatorLevel.Lowest; var res = new BinaryOperatorWithCarryInAndOut( debugInfo, capabilities, level, alu, fSigned, fOverflow ); res.SetLhs( lhs , lhsCC ); res.SetRhs( rhsLeft, rhsRight, rhsCC ); return res; } //--// // // Helper Methods // public override Operator Clone( CloningContext context ) { return RegisterAndCloneState( context, new BinaryOperatorWithCarryInAndOut( m_debugInfo, m_capabilities, m_level, m_alu, m_fSigned, m_fOverflow ) ); } //--// // // Access Methods // //--// // // Debug Methods // public override void InnerToString( System.Text.StringBuilder sb ) { sb.Append( "BinaryOperatorWithCarryInAndOut(" ); base.InnerToString( sb ); sb.Append( ")" ); } public override string FormatOutput( IIntermediateRepresentationDumper dumper ) { return dumper.FormatOutput( "{0}, {1} = {2} {3} {4} <= {5}{6}", this.FirstResult, this.SecondResult, this.FirstArgument, m_alu, this.SecondArgument, this.ThirdArgument, this.MayThrow ? " MayThrow" : "" ); } } } ================================================ FILE: Zelig/Zelig/CompileTime/CodeGenerator/CodeTransformation/Operators/BitTestOperator.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // namespace Microsoft.Zelig.CodeGeneration.IR { using System; using System.Collections.Generic; using Microsoft.Zelig.Runtime.TypeSystem; public sealed class BitTestOperator : Operator { private const OperatorCapabilities cCapabilities = OperatorCapabilities.IsCommutative | OperatorCapabilities.DoesNotMutateExistingStorage | OperatorCapabilities.DoesNotAllocateStorage | OperatorCapabilities.DoesNotReadExistingMutableStorage | OperatorCapabilities.DoesNotThrow | OperatorCapabilities.DoesNotReadThroughPointerOperands | OperatorCapabilities.DoesNotWriteThroughPointerOperands | OperatorCapabilities.DoesNotCapturePointerOperands ; // // State // // // Constructor Methods // private BitTestOperator( Debugging.DebugInfo debugInfo ) : base( debugInfo, cCapabilities, OperatorLevel.Lowest ) { } //--// public static BitTestOperator New( Debugging.DebugInfo debugInfo , VariableExpression lhs , Expression rhsLeft , Expression rhsRight ) { CHECKS.ASSERT( lhs.AliasedVariable is ConditionCodeExpression, "Expecting a ConditionCodeExpression for the 'lhs' parameter, got '{0}'", lhs ); BitTestOperator res = new BitTestOperator( debugInfo ); res.SetLhs( lhs ); res.SetRhs( rhsLeft, rhsRight ); return res; } //--// // // Helper Methods // public override Operator Clone( CloningContext context ) { return RegisterAndCloneState( context, new BitTestOperator( m_debugInfo ) ); } //--// // // Access Methods // //--// // // Debug Methods // public override void InnerToString( System.Text.StringBuilder sb ) { sb.Append( "BitTestOperator(" ); base.InnerToString( sb ); sb.Append( ")" ); } public override string FormatOutput( IIntermediateRepresentationDumper dumper ) { return dumper.FormatOutput( "{0} = bittest {1} <-> {2}", this.FirstResult, this.FirstArgument, this.SecondArgument ); } } } ================================================ FILE: Zelig/Zelig/CompileTime/CodeGenerator/CodeTransformation/Operators/Calls/DirectSubroutineOperator.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // namespace Microsoft.Zelig.CodeGeneration.IR { using System; using System.Collections.Generic; using Microsoft.Zelig.Runtime.TypeSystem; public sealed class DirectSubroutineOperator : SubroutineOperator { private const OperatorCapabilities cCapabilities = OperatorCapabilities.IsNonCommutative | OperatorCapabilities.DoesNotMutateExistingStorage | OperatorCapabilities.DoesNotAllocateStorage | // It only allocates in the stack space. OperatorCapabilities.DoesNotReadExistingMutableStorage | OperatorCapabilities.DoesNotThrow | OperatorCapabilities.DoesNotReadThroughPointerOperands | OperatorCapabilities.DoesNotWriteThroughPointerOperands | OperatorCapabilities.DoesNotCapturePointerOperands ; // // Constructor Methods // private DirectSubroutineOperator( Debugging.DebugInfo debugInfo , MethodRepresentation md ) : base( debugInfo, cCapabilities, md ) { } //--// public static DirectSubroutineOperator New( Debugging.DebugInfo debugInfo , MethodRepresentation md , Expression[] rhs ) { DirectSubroutineOperator res = new DirectSubroutineOperator( debugInfo, md ); res.SetRhsArray( rhs ); return res; } //--// // // Helper Methods // public override Operator Clone( CloningContext context ) { MethodRepresentation md = context.ConvertMethod( m_md ); return RegisterAndCloneState( context, new DirectSubroutineOperator( m_debugInfo, md ) ); } //--// // // Access Methods // //--// // // Debug Methods // public override void InnerToString( System.Text.StringBuilder sb ) { sb.Append( "DirectSubroutineOperator(" ); base.InnerToString( sb ); sb.Append( ")" ); } public override string FormatOutput( IIntermediateRepresentationDumper dumper ) { System.Text.StringBuilder sb = new System.Text.StringBuilder(); if(this.Arguments.Length > 0) { sb.Append( " " ); for(int i = 0; i < this.Arguments.Length; i++) { if(i != 0) sb.Append( ", " ); this.Arguments[i].InnerToString( sb ); } sb.Append( " " ); } return dumper.FormatOutput( "directSubCall {0}({1})", this.TargetMethod, sb.ToString() ); } } } ================================================ FILE: Zelig/Zelig/CompileTime/CodeGenerator/CodeTransformation/Operators/Calls/IndirectSubroutineOperator.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // namespace Microsoft.Zelig.CodeGeneration.IR { using System; using System.Collections.Generic; using Microsoft.Zelig.Runtime.TypeSystem; public sealed class IndirectSubroutineOperator : SubroutineOperator { private const OperatorCapabilities cCapabilities = OperatorCapabilities.IsNonCommutative | OperatorCapabilities.DoesNotMutateExistingStorage | OperatorCapabilities.DoesNotAllocateStorage | // It only allocates in the stack space. OperatorCapabilities.DoesNotReadExistingMutableStorage | OperatorCapabilities.DoesNotThrow | OperatorCapabilities.DoesNotReadThroughPointerOperands | OperatorCapabilities.DoesNotWriteThroughPointerOperands | OperatorCapabilities.DoesNotCapturePointerOperands ; // // Constructor Methods // private IndirectSubroutineOperator( Debugging.DebugInfo debugInfo , MethodRepresentation md ) : base( debugInfo, cCapabilities, md ) { } //--// public static IndirectSubroutineOperator New( Debugging.DebugInfo debugInfo , MethodRepresentation md , Expression exPointer , Expression[] rhs ) { IndirectSubroutineOperator res = new IndirectSubroutineOperator( debugInfo, md ); if(rhs.Length > 0) { res.SetRhsArray( ArrayUtility.InsertAtHeadOfNotNullArray( rhs, exPointer ) ); } else { res.SetRhs( exPointer ); } return res; } //--// // // Helper Methods // public override Operator Clone( CloningContext context ) { MethodRepresentation md = context.ConvertMethod( m_md ); return RegisterAndCloneState( context, new IndirectSubroutineOperator( m_debugInfo, md ) ); } //--// // // Access Methods // //--// // // Debug Methods // public override void InnerToString( System.Text.StringBuilder sb ) { sb.Append( "IndirectSubroutineOperator(" ); base.InnerToString( sb ); sb.Append( ")" ); } public override string FormatOutput( IIntermediateRepresentationDumper dumper ) { System.Text.StringBuilder sb = new System.Text.StringBuilder(); this.FirstArgument.InnerToString( sb ); if(this.Arguments.Length > 1) { sb.Append( " => " ); for(int i = 1; i < this.Arguments.Length; i++) { if(i != 1) sb.Append( ", " ); this.Arguments[i].InnerToString( sb ); } } return dumper.FormatOutput( "indirectSubCall {0}( {1} )", this.TargetMethod, sb.ToString() ); } } } ================================================ FILE: Zelig/Zelig/CompileTime/CodeGenerator/CodeTransformation/Operators/Calls/SubroutineOperator.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // namespace Microsoft.Zelig.CodeGeneration.IR { using System; using System.Collections.Generic; using Microsoft.Zelig.Runtime.TypeSystem; public abstract class SubroutineOperator : Operator { // // State // protected MethodRepresentation m_md; // // Constructor Methods // protected SubroutineOperator( Debugging.DebugInfo debugInfo , OperatorCapabilities capabilities , MethodRepresentation md ) : base( debugInfo, capabilities, OperatorLevel.Lowest ) { m_md = md; } //--// // // Helper Methods // public override void ApplyTransformation( TransformationContextForIR context ) { context.Push( this ); base.ApplyTransformation( context ); context.Transform( ref m_md ); context.Pop(); } //--// public override bool CanPropagateCopy( Expression exOld , Expression exNew ) { // // The Rvalues are used to keep alive actual method arguments, so we cannot change them!! // return false; } //--// // // Access Methods // public MethodRepresentation TargetMethod { get { return m_md; } } //--// // // Debug Methods // public override void InnerToString( System.Text.StringBuilder sb ) { base.InnerToString( sb ); sb.AppendFormat( " {0}", m_md ); } } } ================================================ FILE: Zelig/Zelig/CompileTime/CodeGenerator/CodeTransformation/Operators/CompareOperator.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // namespace Microsoft.Zelig.CodeGeneration.IR { using System; using System.Collections.Generic; using Microsoft.Zelig.Runtime.TypeSystem; public sealed class CompareOperator : Operator { private const OperatorCapabilities cCapabilities = OperatorCapabilities.IsNonCommutative | OperatorCapabilities.DoesNotMutateExistingStorage | OperatorCapabilities.DoesNotAllocateStorage | OperatorCapabilities.DoesNotReadExistingMutableStorage | OperatorCapabilities.DoesNotThrow | OperatorCapabilities.DoesNotReadThroughPointerOperands | OperatorCapabilities.DoesNotWriteThroughPointerOperands | OperatorCapabilities.DoesNotCapturePointerOperands ; // // State // // // Constructor Methods // private CompareOperator( Debugging.DebugInfo debugInfo ) : base( debugInfo, cCapabilities, OperatorLevel.Lowest ) { } //--// public static CompareOperator New( Debugging.DebugInfo debugInfo , VariableExpression lhs , Expression rhsLeft , Expression rhsRight ) { CHECKS.ASSERT( lhs.AliasedVariable is ConditionCodeExpression, "Expecting a ConditionCodeExpression for the 'lhs' parameter, got '{0}'", lhs ); CompareOperator res = new CompareOperator( debugInfo ); res.SetLhs( lhs ); res.SetRhs( rhsLeft, rhsRight ); return res; } //--// // // Helper Methods // public override Operator Clone( CloningContext context ) { return RegisterAndCloneState( context, new CompareOperator( m_debugInfo ) ); } //--// public override ConstantExpression CanEvaluate( Operator[][] defChains , Operator[][] useChains , VariableExpression.Property[] properties ) { var exL = FindConstantOrigin( this.FirstArgument , defChains, useChains, properties ); var exR = FindConstantOrigin( this.SecondArgument, defChains, useChains, properties ); if(exL != null && exR != null) { object objL; object objR; if(exL.IsValueInteger && exR.IsValueInteger) { ulong valL; ulong valR; exL.GetAsRawUlong( out valL ); exR.GetAsRawUlong( out valR ); objL = valL; objR = valR; } else if(exL.IsValueFloatingPoint && exR.IsValueFloatingPoint) { double valL; double valR; exL.GetFloatingPoint( out valL ); exR.GetFloatingPoint( out valR ); objL = valL; objR = valR; } else { return null; } return new ConstantExpression( this.FirstResult.Type, new ConditionCodeExpression.ConstantResult( objL, objR ) ); } return null; } //--// // // Access Methods // //--// // // Debug Methods // public override void InnerToString( System.Text.StringBuilder sb ) { sb.Append( "CompareOperator(" ); base.InnerToString( sb ); sb.Append( ")" ); } public override string FormatOutput( IIntermediateRepresentationDumper dumper ) { return dumper.FormatOutput( "{0} = compare {1} <-> {2}", this.FirstResult, this.FirstArgument, this.SecondArgument ); } } } ================================================ FILE: Zelig/Zelig/CompileTime/CodeGenerator/CodeTransformation/Operators/ConditionalCompareOperator.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // namespace Microsoft.Zelig.CodeGeneration.IR { using System; using System.Collections.Generic; using Microsoft.Zelig.Runtime.TypeSystem; public sealed class ConditionalCompareOperator : Operator { private const OperatorCapabilities cCapabilities = OperatorCapabilities.IsNonCommutative | OperatorCapabilities.DoesNotMutateExistingStorage | OperatorCapabilities.DoesNotAllocateStorage | OperatorCapabilities.DoesNotReadExistingMutableStorage | OperatorCapabilities.DoesNotThrow | OperatorCapabilities.DoesNotReadThroughPointerOperands | OperatorCapabilities.DoesNotWriteThroughPointerOperands | OperatorCapabilities.DoesNotCapturePointerOperands ; // // State // private ConditionCodeExpression.Comparison m_condition; // // Constructor Methods // private ConditionalCompareOperator( Debugging.DebugInfo debugInfo , ConditionCodeExpression.Comparison condition ) : base( debugInfo, cCapabilities, OperatorLevel.Lowest ) { m_condition = condition; } //--// public static ConditionalCompareOperator New( Debugging.DebugInfo debugInfo , ConditionCodeExpression.Comparison condition , VariableExpression lhs , Expression rhsLeft , Expression rhsRight , VariableExpression rhsCC ) { CHECKS.ASSERT( lhs .AliasedVariable is ConditionCodeExpression, "Expecting a ConditionCodeExpression for the 'lhs' parameter, got '{0}'" , lhs ); CHECKS.ASSERT( rhsCC.AliasedVariable is ConditionCodeExpression, "Expecting a ConditionCodeExpression for the 'rhsCC' parameter, got '{0}'", rhsCC ); ConditionalCompareOperator res = new ConditionalCompareOperator( debugInfo, condition ); res.SetLhs( lhs ); res.SetRhs( rhsLeft, rhsRight, rhsCC ); return res; } //--// // // Helper Methods // public override Operator Clone( CloningContext context ) { return RegisterAndCloneState( context, new ConditionalCompareOperator( m_debugInfo, m_condition ) ); } //--// public override void ApplyTransformation( TransformationContextForIR context ) { TransformationContextForCodeTransformation context2 = (TransformationContextForCodeTransformation)context; context2.Push( this ); base.ApplyTransformation( context2 ); context2.Transform( ref m_condition ); context2.Pop(); } //--// // // Access Methods // public ConditionCodeExpression.Comparison Condition { get { return m_condition; } set { m_condition = value; } } //--// // // Debug Methods // public override void InnerToString( System.Text.StringBuilder sb ) { sb.Append( "ConditionalCompareOperator(" ); base.InnerToString( sb ); sb.Append( ")" ); } public override string FormatOutput( IIntermediateRepresentationDumper dumper ) { return dumper.FormatOutput( "{0} = compare {1} <-> {2} if {3} is {4}", this.FirstResult, this.FirstArgument, this.SecondArgument, this.ThirdArgument, m_condition ); } } } ================================================ FILE: Zelig/Zelig/CompileTime/CodeGenerator/CodeTransformation/Operators/Control/ConditionCodeControlOperator.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // namespace Microsoft.Zelig.CodeGeneration.IR { using System; using System.Collections.Generic; using Microsoft.Zelig.Runtime.TypeSystem; public sealed class ConditionCodeConditionalControlOperator : ConditionalControlOperator { // // State // private BasicBlock m_targetBranchTaken; private ConditionCodeExpression.Comparison m_condition; // // Constructor Methods // private ConditionCodeConditionalControlOperator( Debugging.DebugInfo debugInfo , OperatorCapabilities capabilities , ConditionCodeExpression.Comparison condition ) : base( debugInfo, capabilities, OperatorLevel.Lowest ) { m_condition = condition; } //--// public static ConditionCodeConditionalControlOperator New( Debugging.DebugInfo debugInfo , ConditionCodeExpression.Comparison condition , VariableExpression rhs , BasicBlock targetFalse , BasicBlock targetTrue ) { CHECKS.ASSERT( rhs.AliasedVariable is ConditionCodeExpression, "We need a condition code as input: {0}", rhs ); OperatorCapabilities capabilities = OperatorCapabilities.IsNonCommutative | OperatorCapabilities.DoesNotMutateExistingStorage | OperatorCapabilities.DoesNotAllocateStorage | OperatorCapabilities.DoesNotReadExistingMutableStorage | OperatorCapabilities.DoesNotThrow | OperatorCapabilities.DoesNotReadThroughPointerOperands | OperatorCapabilities.DoesNotWriteThroughPointerOperands | OperatorCapabilities.DoesNotCapturePointerOperands ; ConditionCodeConditionalControlOperator res = new ConditionCodeConditionalControlOperator( debugInfo, capabilities, condition ); res.SetRhs( rhs ); res.m_targetBranchNotTaken = targetFalse; res.m_targetBranchTaken = targetTrue; return res; } //--// // // Helper Methods // public override Operator Clone( CloningContext context ) { return RegisterAndCloneState( context, new ConditionCodeConditionalControlOperator( m_debugInfo, m_capabilities, m_condition ) ); } protected override void CloneState( CloningContext context , Operator clone ) { ConditionCodeConditionalControlOperator clone2 = (ConditionCodeConditionalControlOperator)clone; clone2.m_targetBranchTaken = context.Clone( m_targetBranchTaken ); base.CloneState( context, clone ); } //--// public override void ApplyTransformation( TransformationContextForIR context ) { TransformationContextForCodeTransformation context2 = (TransformationContextForCodeTransformation)context; context2.Push( this ); base.ApplyTransformation( context2 ); context2.Transform( ref m_targetBranchTaken ); context2.Transform( ref m_condition ); context2.Pop(); } //--// protected override void UpdateSuccessorInformation() { base.UpdateSuccessorInformation(); m_basicBlock.LinkToNormalBasicBlock( m_targetBranchTaken ); } //--// public override bool SubstituteTarget( BasicBlock oldBB , BasicBlock newBB ) { bool fChanged = base.SubstituteTarget( oldBB, newBB ); if(m_targetBranchTaken == oldBB) { m_targetBranchTaken = newBB; BumpVersion(); fChanged = true; } return fChanged; } //--// public override bool Simplify( Operator[][] defChains , Operator[][] useChains , VariableExpression.Property[] properties ) { if(base.Simplify( defChains, useChains, properties )) { return true; } var exConst = FindConstantOrigin( this.FirstArgument, defChains, useChains, properties ); if(exConst != null) { ConditionCodeExpression.ConstantResult cr = exConst.Value as ConditionCodeExpression.ConstantResult; if(cr != null) { object left = cr.LeftValue; object right = cr.RightValue; bool fTaken; if(left is ulong && right is ulong) { ulong valL = (ulong)left; ulong valR = (ulong)right; switch(m_condition) { case ConditionCodeExpression.Comparison.Equal : fTaken = valL == valR; break; case ConditionCodeExpression.Comparison.NotEqual : fTaken = valL != valR; break; case ConditionCodeExpression.Comparison.UnsignedHigherThanOrSame: fTaken = valL >= valR; break; case ConditionCodeExpression.Comparison.UnsignedLowerThan : fTaken = valL < valR; break; case ConditionCodeExpression.Comparison.UnsignedHigherThan : fTaken = valL > valR; break; case ConditionCodeExpression.Comparison.UnsignedLowerThanOrSame : fTaken = valL <= valR; break; case ConditionCodeExpression.Comparison.SignedGreaterThanOrEqual: fTaken = (long)valL >= (long)valR; break; case ConditionCodeExpression.Comparison.SignedLessThan : fTaken = (long)valL < (long)valR; break; case ConditionCodeExpression.Comparison.SignedGreaterThan : fTaken = (long)valL > (long)valR; break; case ConditionCodeExpression.Comparison.SignedLessThanOrEqual : fTaken = (long)valL <= (long)valR; break; default: throw TypeConsistencyErrorException.Create( "Unexpected input to {0}", this ); } } else if(left is double && right is double) { double valL = (double)left; double valR = (double)right; switch(m_condition) { case ConditionCodeExpression.Comparison.Equal : fTaken = valL == valR; break; case ConditionCodeExpression.Comparison.NotEqual : fTaken = valL != valR; break; //// case ConditionCodeExpression.Comparison.UnsignedHigherThanOrSame: fTaken = valL >= valR; break; //// case ConditionCodeExpression.Comparison.UnsignedLowerThan : fTaken = valL < valR; break; //// case ConditionCodeExpression.Comparison.UnsignedHigherThan : fTaken = valL > valR; break; //// case ConditionCodeExpression.Comparison.UnsignedLowerThanOrSame : fTaken = valL <= valR; break; case ConditionCodeExpression.Comparison.SignedGreaterThanOrEqual: fTaken = valL >= valR; break; case ConditionCodeExpression.Comparison.SignedLessThan : fTaken = valL < valR; break; case ConditionCodeExpression.Comparison.SignedGreaterThan : fTaken = valL > valR; break; case ConditionCodeExpression.Comparison.SignedLessThanOrEqual : fTaken = valL <= valR; break; default: throw TypeConsistencyErrorException.Create( "Unexpected input to {0}", this ); } } else { throw TypeConsistencyErrorException.Create( "Unexpected input to {0}", this ); } UnconditionalControlOperator opNew = UnconditionalControlOperator.New( this.DebugInfo, fTaken ? m_targetBranchTaken : m_targetBranchNotTaken ); this.SubstituteWithOperator( opNew, Operator.SubstitutionFlags.CopyAnnotations ); return true; } throw TypeConsistencyErrorException.Create( "Unexpected input to {0}", this ); } return false; } //--// // // Access Methods // public BasicBlock TargetBranchTaken { get { return m_targetBranchTaken; } } public ConditionCodeExpression.Comparison Condition { get { return m_condition; } set { m_condition = value; } } //--// // // Debug Methods // public override void InnerToString( System.Text.StringBuilder sb ) { sb.Append( "ConditionCodeConditionalControlOperator(" ); base.InnerToString( sb ); sb.AppendFormat( " Taken: {0}", m_targetBranchTaken.SpanningTreeIndex ); sb.Append( ")" ); } public override string FormatOutput( IIntermediateRepresentationDumper dumper ) { return dumper.FormatOutput( "if {0} is {1} then goto {2} else goto {3}", this.FirstArgument, m_condition, m_targetBranchTaken, m_targetBranchNotTaken ); } } } ================================================ FILE: Zelig/Zelig/CompileTime/CodeGenerator/CodeTransformation/Operators/InitialValueOperator.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // namespace Microsoft.Zelig.CodeGeneration.IR { using System; using System.Collections.Generic; using Microsoft.Zelig.Runtime.TypeSystem; public sealed class InitialValueOperator : Operator { private const OperatorCapabilities cCapabilities = OperatorCapabilities.IsNonCommutative | OperatorCapabilities.DoesNotMutateExistingStorage | OperatorCapabilities.DoesNotAllocateStorage | OperatorCapabilities.DoesNotReadExistingMutableStorage | OperatorCapabilities.DoesNotThrow | OperatorCapabilities.DoesNotReadThroughPointerOperands | OperatorCapabilities.DoesNotWriteThroughPointerOperands | OperatorCapabilities.DoesNotCapturePointerOperands | OperatorCapabilities.IsMetaOperator ; // // State // // // Constructor Methods // private InitialValueOperator( Debugging.DebugInfo debugInfo ) : base( debugInfo, cCapabilities, OperatorLevel.Lowest ) { } //--// public static InitialValueOperator New( Debugging.DebugInfo debugInfo , VariableExpression ex ) { InitialValueOperator res = new InitialValueOperator( debugInfo ); res.SetLhs( ex ); return res; } //--// // // Helper Methods // public override Operator Clone( CloningContext context ) { return RegisterAndCloneState( context, new InitialValueOperator( m_debugInfo ) ); } //--// // // Access Methods // //--// // // Debug Methods // public override void InnerToString( System.Text.StringBuilder sb ) { sb.Append( "InitialValueOperator(" ); base.InnerToString( sb ); sb.Append( ")" ); } public override string FormatOutput( IIntermediateRepresentationDumper dumper ) { return dumper.FormatOutput( "{0} = ", this.FirstResult ); } } } ================================================ FILE: Zelig/Zelig/CompileTime/CodeGenerator/CodeTransformation/Operators/LongCompareOperator.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // namespace Microsoft.Zelig.CodeGeneration.IR { using System; using System.Collections.Generic; using Microsoft.Zelig.Runtime.TypeSystem; public sealed class LongCompareOperator : Operator { private const OperatorCapabilities cCapabilities = OperatorCapabilities.IsNonCommutative | OperatorCapabilities.DoesNotMutateExistingStorage | OperatorCapabilities.DoesNotAllocateStorage | OperatorCapabilities.DoesNotReadExistingMutableStorage | OperatorCapabilities.DoesNotThrow | OperatorCapabilities.DoesNotReadThroughPointerOperands | OperatorCapabilities.DoesNotWriteThroughPointerOperands | OperatorCapabilities.DoesNotCapturePointerOperands ; // // State // // // Constructor Methods // private LongCompareOperator( Debugging.DebugInfo debugInfo ) : base( debugInfo, cCapabilities, OperatorLevel.Lowest ) { } //--// public static LongCompareOperator New( Debugging.DebugInfo debugInfo , VariableExpression lhs , Expression rhsLeftLo , Expression rhsLeftHi , Expression rhsRightLo , Expression rhsRightHi ) { CHECKS.ASSERT( lhs.AliasedVariable is ConditionCodeExpression, "Invalid type for condition code: {0}", lhs ); var res = new LongCompareOperator( debugInfo ); res.SetLhs ( lhs ); res.SetRhsArray( rhsLeftLo, rhsLeftHi, rhsRightLo, rhsRightHi ); return res; } //--// // // Helper Methods // public override Operator Clone( CloningContext context ) { return RegisterAndCloneState( context, new LongCompareOperator( m_debugInfo ) ); } //--// public override ConstantExpression CanEvaluate( Operator[][] defChains , Operator[][] useChains , VariableExpression.Property[] properties ) { var exLlo = FindConstantOrigin( this.FirstArgument , defChains, useChains, properties ); var exLhi = FindConstantOrigin( this.SecondArgument, defChains, useChains, properties ); var exRlo = FindConstantOrigin( this.ThirdArgument , defChains, useChains, properties ); var exRhi = FindConstantOrigin( this.FourthArgument, defChains, useChains, properties ); if(exLlo != null && exLhi != null && exRlo != null && exRhi != null) { object objL; object objR; if(exLlo.IsValueInteger && exLhi.IsValueInteger && exRlo.IsValueInteger && exRhi.IsValueInteger) { ulong valLlo; ulong valLhi; ulong valRlo; ulong valRhi; exLlo.GetAsRawUlong( out valLlo ); exLhi.GetAsRawUlong( out valLhi ); exRlo.GetAsRawUlong( out valRlo ); exRhi.GetAsRawUlong( out valRhi ); objL = valLlo | (valLhi << 32); objR = valRlo | (valRhi << 32); } else { return null; } return new ConstantExpression( this.FirstResult.Type, new ConditionCodeExpression.ConstantResult( objL, objR ) ); } return null; } internal Expression[] IsCompareToNull( out bool fNullOnRight ) { if(this.FirstArgument .IsEqualToZero() && this.SecondArgument.IsEqualToZero() ) { fNullOnRight = false; return new Expression[] { this.ThirdArgument, this.FourthArgument }; } if(this.ThirdArgument .IsEqualToZero() && this.FourthArgument.IsEqualToZero() ) { fNullOnRight = true; return new Expression[] { this.FirstArgument, this.SecondArgument }; } fNullOnRight = false; return null; } //--// // // Access Methods // //--// // // Debug Methods // public override void InnerToString( System.Text.StringBuilder sb ) { sb.Append( "LongCompareOperator(" ); base.InnerToString( sb ); sb.Append( ")" ); } public override string FormatOutput( IIntermediateRepresentationDumper dumper ) { return dumper.FormatOutput( "{0} = longcompare {1}:{2} <-> {3}:{4}", this.FirstResult, this.FirstArgument, this.SecondArgument, this.ThirdArgument, this.FourthArgument ); } } } ================================================ FILE: Zelig/Zelig/CompileTime/CodeGenerator/CodeTransformation/Operators/NewConstraintOperator.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // namespace Microsoft.Zelig.CodeGeneration.IR { using System; using System.Collections.Generic; using Microsoft.Zelig.Runtime.TypeSystem; public sealed class NewConstraintOperator : Operator { private const OperatorCapabilities cCapabilities = OperatorCapabilities.IsNonCommutative | OperatorCapabilities.DoesNotMutateExistingStorage | OperatorCapabilities.DoesNotAllocateStorage | OperatorCapabilities.DoesNotReadExistingMutableStorage | OperatorCapabilities.DoesNotThrow | OperatorCapabilities.DoesNotReadThroughPointerOperands | OperatorCapabilities.DoesNotWriteThroughPointerOperands | OperatorCapabilities.DoesNotCapturePointerOperands ; // // Constructor Methods // private NewConstraintOperator( Debugging.DebugInfo debugInfo ) : base( debugInfo, cCapabilities, Operator.OperatorLevel.Lowest ) { } //--// public static NewConstraintOperator New( Debugging.DebugInfo debugInfo , VariableExpression lhs , Expression rhs ) { NewConstraintOperator res = new NewConstraintOperator( debugInfo ); res.SetLhs( lhs ); res.SetRhs( rhs ); return res; } //--// // // Helper Methods // public override Operator Clone( CloningContext context ) { return RegisterAndCloneState( context, new NewConstraintOperator( m_debugInfo ) ); } //--// // // Access Methods // //--// // // Debug Methods // public override void InnerToString( System.Text.StringBuilder sb ) { sb.Append( "NewConstraintOperator(" ); base.InnerToString( sb ); sb.Append( ")" ); } public override string FormatOutput( IIntermediateRepresentationDumper dumper ) { return dumper.FormatOutput( "{0} = NewConstraint< {1} >", this.FirstResult, this.FirstArgument ); } } } ================================================ FILE: Zelig/Zelig/CompileTime/CodeGenerator/CodeTransformation/Operators/PhiOperator.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // namespace Microsoft.Zelig.CodeGeneration.IR { using System; using System.Collections.Generic; using Microsoft.Zelig.Runtime.TypeSystem; public sealed class PhiOperator : Operator { private const OperatorCapabilities cCapabilities = OperatorCapabilities.IsNonCommutative | OperatorCapabilities.DoesNotMutateExistingStorage | OperatorCapabilities.DoesNotAllocateStorage | OperatorCapabilities.DoesNotReadExistingMutableStorage | OperatorCapabilities.DoesNotThrow | OperatorCapabilities.DoesNotReadThroughPointerOperands | OperatorCapabilities.DoesNotWriteThroughPointerOperands | OperatorCapabilities.DoesNotCapturePointerOperands ; // // State // private BasicBlock[] m_origins; // // Constructor Methods // private PhiOperator( Debugging.DebugInfo debugInfo ) : base( debugInfo, cCapabilities, OperatorLevel.Lowest ) { m_origins = BasicBlock.SharedEmptyArray; } //--// public static PhiOperator New( Debugging.DebugInfo debugInfo , VariableExpression ex ) { PhiOperator res = new PhiOperator( debugInfo ); res.SetLhs( ex ); return res; } //--// // // Helper Methods // public override Operator Clone( CloningContext context ) { return RegisterAndCloneState( context, new PhiOperator( m_debugInfo ) ); } protected override void CloneState( CloningContext context , Operator clone ) { PhiOperator clone2 = (PhiOperator)clone; clone2.m_origins = context.Clone( m_origins ); base.CloneState( context, clone ); } //--// public override void ApplyTransformation( TransformationContextForIR context ) { context.Push( this ); base.ApplyTransformation( context ); context.Transform( ref m_origins ); context.Pop(); } //--// public override void NotifyMerge( BasicBlock entryBB , BasicBlock exitBB ) { CHECKS.ASSERT( entryBB != exitBB, "Cannot merge basic block with itself" ); // // If we have a contribution from 'exitBB', it will dominate any contribution from 'entryBB'. // Remove those contributions. // if(ArrayUtility.FindReferenceInNotNullArray( m_origins, exitBB ) >= 0) { int pos; while((pos = ArrayUtility.FindReferenceInNotNullArray( m_origins, entryBB )) >= 0) { this.Arguments = ArrayUtility.RemoveAtPositionFromNotNullArray( this.Arguments, pos ); this.Origins = ArrayUtility.RemoveAtPositionFromNotNullArray( this.Origins , pos ); } } } public override void NotifyNewPredecessor( BasicBlock oldBB , BasicBlock newBB ) { CHECKS.ASSERT( oldBB != newBB, "Cannot change a predecessor with itself" ); int pos; while((pos = ArrayUtility.FindReferenceInNotNullArray( m_origins, oldBB )) >= 0) { m_origins[pos] = newBB; } } //--// public override bool CanPropagateCopy( Expression exOld , Expression exNew ) { // // The Rvalues are used to keep a reference to the previous definitions of a variable, // so we cannot change them!! // return false; } //--// internal void AddEffect( VariableExpression input , BasicBlock source ) { CHECKS.ASSERT( ArrayUtility.FindReferenceInNotNullArray( m_origins, source ) < 0, "SSA effect added more than once from the same BasicBlock: {0} from {1}", input, source ); this.Arguments = ArrayUtility.AppendToNotNullArray( this.Arguments, (Expression)input ); this.Origins = ArrayUtility.AppendToNotNullArray( this.Origins , source ); } internal void RemoveEffect( BasicBlock source ) { int pos = ArrayUtility.FindReferenceInNotNullArray( m_origins, source ); if(pos >= 0) { this.Arguments = ArrayUtility.RemoveAtPositionFromNotNullArray( this.Arguments, pos ); this.Origins = ArrayUtility.RemoveAtPositionFromNotNullArray( this.Origins , pos ); } } internal bool AdjustLinkage() { bool fModified = false; foreach(BasicBlock origin in m_origins) { if(origin.SpanningTreeIndex < 0) { RemoveEffect( origin ); fModified = true; } } return fModified; } internal void SubstituteOrigin( BasicBlock oldSource , BasicBlock newSource ) { BasicBlock[] origins = m_origins; for(int pos = origins.Length; --pos >=0; ) { if(origins[pos] == oldSource) { if(m_origins == origins) { origins = ArrayUtility.CopyNotNullArray( m_origins ); } origins[pos] = newSource; } } if(m_origins != origins) { BumpVersion(); m_origins = origins; } } //--// // // Access Methods // public BasicBlock[] Origins { get { return m_origins; } private set { m_origins = value; } } //--// // // Debug Methods // public override void InnerToString( System.Text.StringBuilder sb ) { sb.Append( "PhiOperator(" ); base.InnerToString( sb ); sb.Append( ")" ); } public override string FormatOutput( IIntermediateRepresentationDumper dumper ) { System.Text.StringBuilder sb = new System.Text.StringBuilder(); bool fFirst = true; for(int pos = 0; pos < this.Arguments.Length; pos++) { Expression ex = this.Arguments[pos]; BasicBlock src = this.Origins [pos]; string fmt; if(fFirst) { fFirst = false; fmt = "{0} from {1}"; } else { fmt = ", {0} from {1}"; } sb.Append( dumper.FormatOutput( fmt, ex, src ) ); } return dumper.FormatOutput( "{0} = phi( {1} )", this.FirstResult, sb.ToString() ); } } } ================================================ FILE: Zelig/Zelig/CompileTime/CodeGenerator/CodeTransformation/Operators/PiOperator.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // namespace Microsoft.Zelig.CodeGeneration.IR { using System; using System.Collections.Generic; using Microsoft.Zelig.Runtime.TypeSystem; public sealed class PiOperator : Operator { public enum Relation { Invalid , Equal , NotEqual , UnsignedHigherThanOrSame, UnsignedLowerThan , UnsignedHigherThan , UnsignedLowerThanOrSame , SignedGreaterThanOrEqual, SignedLessThan , SignedGreaterThan , SignedLessThanOrEqual , } private const OperatorCapabilities cCapabilities = OperatorCapabilities.IsNonCommutative | OperatorCapabilities.DoesNotMutateExistingStorage | OperatorCapabilities.DoesNotAllocateStorage | OperatorCapabilities.DoesNotReadExistingMutableStorage | OperatorCapabilities.DoesNotThrow | OperatorCapabilities.DoesNotReadThroughPointerOperands | OperatorCapabilities.DoesNotWriteThroughPointerOperands | OperatorCapabilities.DoesNotCapturePointerOperands ; // // State // private Relation m_relation; // // Constructor Methods // private PiOperator( Debugging.DebugInfo debugInfo , Relation cmpRelation ) : base( debugInfo, cCapabilities, OperatorLevel.Lowest ) { m_relation = cmpRelation; } //--// public static PiOperator New( Debugging.DebugInfo debugInfo , VariableExpression lhs , VariableExpression rhs , Expression cmpLeft , Expression cmpRight , Relation cmpRelation ) { PiOperator res = new PiOperator( debugInfo, cmpRelation ); res.SetLhs( lhs ); res.SetRhs( rhs, cmpLeft, cmpRight ); return res; } //--// // // Helper Methods // public override Operator Clone( CloningContext context ) { return RegisterAndCloneState( context, new PiOperator( m_debugInfo, m_relation ) ); } //--// public override void ApplyTransformation( TransformationContextForIR context ) { TransformationContextForCodeTransformation context2 = (TransformationContextForCodeTransformation)context; context2.Push( this ); base.ApplyTransformation( context2 ); context2.Transform( ref m_relation ); context2.Pop(); } //--// public override bool CanPropagateCopy( Expression exOld , Expression exNew ) { // // We create Pi operators to say that input and output have some differences, so don't copy propagate or we'll lose that bit of knowledge! // return false; } //--// public static Relation ConvertRelation( ConditionCodeExpression.Comparison comparison ) { switch(comparison) { case ConditionCodeExpression.Comparison.Equal : return Relation.Equal ; case ConditionCodeExpression.Comparison.NotEqual : return Relation.NotEqual ; case ConditionCodeExpression.Comparison.UnsignedHigherThanOrSame: return Relation.UnsignedHigherThanOrSame; case ConditionCodeExpression.Comparison.UnsignedLowerThan : return Relation.UnsignedLowerThan ; case ConditionCodeExpression.Comparison.UnsignedHigherThan : return Relation.UnsignedHigherThan ; case ConditionCodeExpression.Comparison.UnsignedLowerThanOrSame : return Relation.UnsignedLowerThanOrSame ; case ConditionCodeExpression.Comparison.SignedGreaterThanOrEqual: return Relation.SignedGreaterThanOrEqual; case ConditionCodeExpression.Comparison.SignedLessThan : return Relation.SignedLessThan ; case ConditionCodeExpression.Comparison.SignedGreaterThan : return Relation.SignedGreaterThan ; case ConditionCodeExpression.Comparison.SignedLessThanOrEqual : return Relation.SignedLessThanOrEqual ; } return Relation.Invalid; } public static Relation NegateRelation( Relation relation ) { switch(relation) { case Relation.Equal : return Relation.NotEqual ; case Relation.NotEqual : return Relation.Equal ; case Relation.UnsignedHigherThanOrSame: return Relation.UnsignedLowerThan ; case Relation.UnsignedLowerThan : return Relation.UnsignedHigherThanOrSame; case Relation.UnsignedHigherThan : return Relation.UnsignedLowerThanOrSame ; case Relation.UnsignedLowerThanOrSame : return Relation.UnsignedHigherThan ; case Relation.SignedGreaterThanOrEqual: return Relation.SignedLessThan ; case Relation.SignedLessThan : return Relation.SignedGreaterThanOrEqual; case Relation.SignedGreaterThan : return Relation.SignedLessThanOrEqual ; case Relation.SignedLessThanOrEqual : return Relation.SignedGreaterThan ; } return Relation.Invalid; } public static bool SameAnnotation( PiOperator pi1 , PiOperator pi2 ) { if(pi1.LeftExpression == pi2.LeftExpression && pi1.RightExpression == pi2.RightExpression && pi1.RelationOperator == pi2.RelationOperator ) { return true; } return false; } //--// // // Access Methods // public Expression LeftExpression { get { return this.SecondArgument; } } public Expression RightExpression { get { return this.ThirdArgument; } } public Relation RelationOperator { get { return m_relation; } } //--// public override bool ShouldNotBeRemoved { [System.Diagnostics.DebuggerHidden] get { VariableExpression left = this.LeftExpression as VariableExpression; VariableExpression right = this.RightExpression as VariableExpression; VariableExpression src = this.FirstArgument as VariableExpression; // // If it's a relation between two variables, we should keep it. // If it's a ralation between a variable and a constant, we can remove it. // return (src == left && right != null) || (src == right && left != null); } } //--// // // Debug Methods // public override void InnerToString( System.Text.StringBuilder sb ) { sb.Append( "PiOperator(" ); base.InnerToString( sb ); sb.Append( ")" ); } public override string FormatOutput( IIntermediateRepresentationDumper dumper ) { return dumper.FormatOutput( "{0} = pi( {1} ) [{2} {3} {4}]", this.FirstResult, this.FirstArgument, this.LeftExpression, m_relation, this.RightExpression ); } } } ================================================ FILE: Zelig/Zelig/CompileTime/CodeGenerator/CodeTransformation/Operators/SetIfConditionIsTrueOperator.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // namespace Microsoft.Zelig.CodeGeneration.IR { using System; using System.Collections.Generic; using Microsoft.Zelig.Runtime.TypeSystem; public sealed class SetIfConditionIsTrueOperator : Operator { private const OperatorCapabilities cCapabilities = OperatorCapabilities.IsNonCommutative | OperatorCapabilities.DoesNotMutateExistingStorage | OperatorCapabilities.DoesNotAllocateStorage | OperatorCapabilities.DoesNotReadExistingMutableStorage | OperatorCapabilities.DoesNotThrow | OperatorCapabilities.DoesNotReadThroughPointerOperands | OperatorCapabilities.DoesNotWriteThroughPointerOperands | OperatorCapabilities.DoesNotCapturePointerOperands ; // // State // private ConditionCodeExpression.Comparison m_condition; // // Constructor Methods // private SetIfConditionIsTrueOperator( Debugging.DebugInfo debugInfo , ConditionCodeExpression.Comparison condition ) : base( debugInfo, cCapabilities, OperatorLevel.Lowest ) { m_condition = condition; } //--// public static SetIfConditionIsTrueOperator New( Debugging.DebugInfo debugInfo , ConditionCodeExpression.Comparison condition , VariableExpression lhs , VariableExpression rhs ) { CHECKS.ASSERT( rhs.AliasedVariable is ConditionCodeExpression, "Invalid type for condition code: {0}", rhs ); var res = new SetIfConditionIsTrueOperator( debugInfo, condition ); res.SetLhs( lhs ); res.SetRhs( rhs ); return res; } //--// // // Helper Methods // public override Operator Clone( CloningContext context ) { return RegisterAndCloneState( context, new SetIfConditionIsTrueOperator( m_debugInfo, m_condition ) ); } //--// public override void ApplyTransformation( TransformationContextForIR context ) { TransformationContextForCodeTransformation context2 = (TransformationContextForCodeTransformation)context; context2.Push( this ); base.ApplyTransformation( context2 ); context2.Transform( ref m_condition ); context2.Pop(); } //--// public override bool Simplify( Operator[][] defChains , Operator[][] useChains , VariableExpression.Property[] properties ) { if(base.Simplify( defChains, useChains, properties )) { return true; } var exConst = FindConstantOrigin( this.FirstArgument, defChains, useChains, properties ); if(exConst != null) { ConditionCodeExpression.ConstantResult cr = exConst.Value as ConditionCodeExpression.ConstantResult; if(cr != null) { object left = cr.LeftValue; object right = cr.RightValue; bool fSet; if(left is ulong && right is ulong) { ulong valL = (ulong)left; ulong valR = (ulong)right; switch(m_condition) { case ConditionCodeExpression.Comparison.Equal : fSet = valL == valR; break; case ConditionCodeExpression.Comparison.NotEqual : fSet = valL != valR; break; case ConditionCodeExpression.Comparison.UnsignedHigherThanOrSame: fSet = valL >= valR; break; case ConditionCodeExpression.Comparison.UnsignedLowerThan : fSet = valL < valR; break; case ConditionCodeExpression.Comparison.UnsignedHigherThan : fSet = valL > valR; break; case ConditionCodeExpression.Comparison.UnsignedLowerThanOrSame : fSet = valL <= valR; break; case ConditionCodeExpression.Comparison.SignedGreaterThanOrEqual: fSet = (long)valL >= (long)valR; break; case ConditionCodeExpression.Comparison.SignedLessThan : fSet = (long)valL < (long)valR; break; case ConditionCodeExpression.Comparison.SignedGreaterThan : fSet = (long)valL > (long)valR; break; case ConditionCodeExpression.Comparison.SignedLessThanOrEqual : fSet = (long)valL <= (long)valR; break; default: throw TypeConsistencyErrorException.Create( "Unexpected input to {0}", this ); } } else if(left is double && right is double) { double valL = (double)left; double valR = (double)right; switch(m_condition) { case ConditionCodeExpression.Comparison.Equal : fSet = valL == valR; break; case ConditionCodeExpression.Comparison.NotEqual : fSet = valL != valR; break; //// case ConditionCodeExpression.Comparison.UnsignedHigherThanOrSame: fSet = valL >= valR; break; //// case ConditionCodeExpression.Comparison.UnsignedLowerThan : fSet = valL < valR; break; //// case ConditionCodeExpression.Comparison.UnsignedHigherThan : fSet = valL > valR; break; //// case ConditionCodeExpression.Comparison.UnsignedLowerThanOrSame : fSet = valL <= valR; break; case ConditionCodeExpression.Comparison.SignedGreaterThanOrEqual: fSet = valL >= valR; break; case ConditionCodeExpression.Comparison.SignedLessThan : fSet = valL < valR; break; case ConditionCodeExpression.Comparison.SignedGreaterThan : fSet = valL > valR; break; case ConditionCodeExpression.Comparison.SignedLessThanOrEqual : fSet = valL <= valR; break; default: throw TypeConsistencyErrorException.Create( "Unexpected input to {0}", this ); } } else { throw TypeConsistencyErrorException.Create( "Unexpected input to {0}", this ); } var opNew = SingleAssignmentOperator.New( this.DebugInfo, this.FirstResult, m_basicBlock.Owner.TypeSystemForIR.CreateConstant( fSet ? 1 : 0 ) ); this.SubstituteWithOperator( opNew, Operator.SubstitutionFlags.CopyAnnotations ); return true; } throw TypeConsistencyErrorException.Create( "Unexpected input to {0}", this ); } return false; } //--// // // Access Methods // public ConditionCodeExpression.Comparison Condition { get { return m_condition; } set { m_condition = value; } } //--// // // Debug Methods // public override void InnerToString( System.Text.StringBuilder sb ) { sb.Append( "SetIfConditionIsTrueOperator(" ); base.InnerToString( sb ); sb.AppendFormat( " Cond: {0}", m_condition ); sb.Append( ")" ); } public override string FormatOutput( IIntermediateRepresentationDumper dumper ) { return dumper.FormatOutput( "{0} = set if {1} is {2}", this.FirstResult, this.FirstArgument, m_condition ); } } } ================================================ FILE: Zelig/Zelig/CompileTime/CodeGenerator/CodeTransformation/Operators/UnaryOperatorWithCarryOut.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // namespace Microsoft.Zelig.CodeGeneration.IR { using System; using System.Collections.Generic; using Microsoft.Zelig.Runtime.TypeSystem; public sealed class UnaryOperatorWithCarryOut : AbstractUnaryOperator { // // Constructor Methods // private UnaryOperatorWithCarryOut( Debugging.DebugInfo debugInfo , OperatorCapabilities capabilities , OperatorLevel level , ALU alu , bool fSigned , bool fOverflow ) : base( debugInfo, capabilities, level, alu, fSigned, fOverflow ) { } //--// public static UnaryOperatorWithCarryOut New( Debugging.DebugInfo debugInfo , ALU alu , bool fSigned , bool fOverflow , VariableExpression lhs , VariableExpression cc , Expression rhs ) { CHECKS.ASSERT( cc.AliasedVariable is ConditionCodeExpression, "Invalid type for condition code: {0}", cc ); OperatorCapabilities capabilities = OperatorCapabilities.IsNonCommutative | OperatorCapabilities.DoesNotMutateExistingStorage | OperatorCapabilities.DoesNotAllocateStorage | OperatorCapabilities.DoesNotReadExistingMutableStorage | OperatorCapabilities.DoesNotReadThroughPointerOperands | OperatorCapabilities.DoesNotWriteThroughPointerOperands | OperatorCapabilities.DoesNotCapturePointerOperands ; if(fOverflow) capabilities |= OperatorCapabilities.MayThrow; else capabilities |= OperatorCapabilities.DoesNotThrow; OperatorLevel level = fOverflow ? OperatorLevel.ConcreteTypes : OperatorLevel.Lowest; var res = new UnaryOperatorWithCarryOut( debugInfo, capabilities, level, alu, fSigned, fOverflow ); res.SetLhs( lhs, cc ); res.SetRhs( rhs ); return res; } //--// // // Helper Methods // public override Operator Clone( CloningContext context ) { return RegisterAndCloneState( context, new UnaryOperatorWithCarryOut( m_debugInfo, m_capabilities, m_level, m_alu, m_fSigned, m_fOverflow ) ); } //--// // // Access Methods // //--// // // Debug Methods // public override void InnerToString( System.Text.StringBuilder sb ) { sb.Append( "UnaryOperatorWithCarry(" ); base.InnerToString( sb ); sb.Append( ")" ); } public override string FormatOutput( IIntermediateRepresentationDumper dumper ) { return dumper.FormatOutput( "{0}, {1} = {2} {3}{4}", this.FirstResult, this.SecondResult, m_alu, this.FirstArgument, this.MayThrow ? " MayThrow" : "" ); } } } ================================================ FILE: Zelig/Zelig/CompileTime/CodeGenerator/CodeTransformation/Properties/AssemblyInfo.cs ================================================ using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; // General Information about an assembly is controlled through the following // set of attributes. Change these attribute values to modify the information // associated with an assembly. [assembly: AssemblyTitle( "Microsoft.Zelig.CodeGeneration.CodeTransformation" )] [assembly: AssemblyDescription( "" )] [assembly: AssemblyConfiguration( "" )] [assembly: AssemblyCompany( "Microsoft" )] [assembly: AssemblyProduct( "Microsoft.Zelig.CodeGeneration.CodeTransformation" )] [assembly: AssemblyCopyright( "Copyright © Microsoft 2007" )] [assembly: AssemblyTrademark( "" )] [assembly: AssemblyCulture( "" )] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible( false )] //// The following GUID is for the ID of the typelib if this project is exposed to COM //[assembly: Guid( "57de0ebe-e971-4cb9-8985-5f6b66934a91" )] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Revision and Build Numbers // by using the '*' as shown below: [assembly: AssemblyVersion( "1.0.0.0" )] [assembly: AssemblyFileVersion( "1.0.0.0" )] ================================================ FILE: Zelig/Zelig/CompileTime/CodeGenerator/CodeTransformation/SourceCodeTracker.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // namespace Microsoft.Zelig.CodeGeneration.IR { using System; using System.Collections.Generic; using Microsoft.Zelig.Runtime.TypeSystem; public sealed class SourceCodeTracker : ITransformationContextTarget { public sealed class SourceCode : ITransformationContextTarget { // // State // string m_file; List< string > m_lines; Microsoft.CSharp.Token[] m_tokens; bool m_fCached; // // Constructor Methods // public SourceCode( string file ) { m_file = file; m_lines = new List(); using(System.IO.StreamReader stream = new System.IO.StreamReader( file )) { string line; while((line = stream.ReadLine()) != null) { m_lines.Add( line ); } } } // // Helper Methods // void ITransformationContextTarget.ApplyTransformation( TransformationContext context ) { context.Push( this ); context.Transform( ref m_file ); context.Transform( ref m_lines ); context.Transform( ref m_fCached ); context.Pop(); } public string[] ToArray() { return m_lines.ToArray(); } // // Access Methods // public string File { get { return m_file; } } public bool UsingCachedValues { get { return m_fCached; } set { m_fCached = value; } } public int Count { get { return m_lines.Count; } } public string this[int line] { get { if(line >= 1 && line <= m_lines.Count) { return m_lines[line-1]; } return string.Empty; } } public Microsoft.CSharp.Token[] Tokens { get { if(m_tokens == null) { Microsoft.CSharp.NameTable nameTable = new Microsoft.CSharp.NameTable(); Microsoft.CSharp.LineMap lineMap = new Microsoft.CSharp.LineMap( m_file ); Microsoft.CSharp.FileLexer lexer = new Microsoft.CSharp.FileLexer( nameTable ); string newLine = Environment.NewLine; int newLineLen = newLine.Length; int len = 0; for(int line = 0; line < m_lines.Count; line++) { len += m_lines[line].Length + newLineLen; } System.Text.StringBuilder buffer = new System.Text.StringBuilder( len ); for(int line = 0; line < m_lines.Count; line++) { buffer.Append( m_lines[line] ); buffer.Append( newLine ); } m_tokens = lexer.Lex( buffer.ToString().ToCharArray(), new System.Collections.Hashtable(), lineMap, true ); } return m_tokens; } } } public delegate void EmitLine( string format, params object[] args ); // // State // GrowOnlyHashTable< string, SourceCode > m_lookupSourceCode; SourceCode m_lastSc; Debugging.DebugInfo m_lastDebugInfo; int m_extraLinesToOutput; // // Constructor Methods // public SourceCodeTracker() { m_lookupSourceCode = HashTableFactory.New< string, SourceCode >(); } //--// // // Helper Methods // void ITransformationContextTarget.ApplyTransformation( TransformationContext context ) { TransformationContextForCodeTransformation context2 = (TransformationContextForCodeTransformation)context; context2.Push( this ); context2.Transform( ref m_lookupSourceCode ); context2.Pop(); } public void Merge( SourceCodeTracker sct ) { m_lookupSourceCode.Merge( sct.m_lookupSourceCode ); } public void ResetContext() { m_lastDebugInfo = null; } public void Print( Debugging.DebugInfo dbg , EmitLine callback ) { if(dbg != null) { SourceCode sc = GetSourceCode( dbg.SrcFileName ); if(sc != null) { if(sc != m_lastSc) { callback( "=== {0} ====", dbg.SrcFileName ); m_lastSc = sc; m_lastDebugInfo = null; } if(m_lastDebugInfo != dbg) { int lineNo = dbg.BeginLineNumber; for(int offset = lineNo - m_extraLinesToOutput; offset <= dbg.EndLineNumber; offset++) { string line = sc[offset]; if(line != null) { callback( "{0} {1}", offset, line ); if(offset == lineNo) { callback( "{0} {1}^", offset, new string( ' ', dbg.BeginColumn-1 ) ); } } } m_lastDebugInfo = dbg; m_extraLinesToOutput = 0; } } } } public SourceCode GetSourceCode( string file ) { SourceCode sc; if(m_lookupSourceCode.TryGetValue( file, out sc )) { return sc; } try { if(System.IO.File.Exists( file )) { sc = new SourceCode( file ); } else { sc = null; } } catch { sc = null; } m_lookupSourceCode[file] = sc; return sc; } // // Access Methods // public int ExtraLinesToOutput { set { m_extraLinesToOutput = value; } } } } ================================================ FILE: Zelig/Zelig/CompileTime/CodeGenerator/CodeTransformation/TransformationContextForCodeTransformation.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // //TODO: Figure out why USE_EMIT is not working //#define TRANSFORMATIONCONTEXT__USE_EMIT //#define TRANSFORMATIONCONTEXT_SHOWALLMETHODSTODEBUGGER namespace Microsoft.Zelig.CodeGeneration.IR { using System; using System.Collections.Generic; #if TRANSFORMATIONCONTEXT__USE_EMIT using System.Reflection; using System.Reflection.Emit; #endif using Microsoft.Zelig.Runtime.TypeSystem; public abstract class TransformationContextForCodeTransformation : TransformationContextForIR { // // State // #if !TRANSFORMATIONCONTEXT__USE_EMIT private GrowOnlyHashTable< Type, System.Reflection.MethodInfo > m_handlers; #endif // // Helper Methods // public abstract void Transform( ref TypeSystemForCodeTransformation typeSystem ); public abstract void Transform( ref StackLocationExpression.Placement val ); public abstract void Transform( ref ConditionCodeExpression.Comparison val ); public abstract void Transform( ref PiOperator.Relation val ); public abstract void Transform( ref DataManager dataManager ); public abstract void Transform( ref DataManager.Attributes val ); public abstract void Transform( ref DataManager.ObjectDescriptor od ); public abstract void Transform( ref DataManager.ArrayDescriptor ad ); public abstract void Transform( ref ImageBuilders.Core imageBuilder ); public abstract void Transform( ref ImageBuilders.CompilationState cs ); public abstract void Transform( ref ImageBuilders.SequentialRegion reg ); public abstract void Transform( ref ImageBuilders.ImageAnnotation an ); public abstract void Transform( ref ImageBuilders.CodeConstant cc ); public abstract void Transform( ref ImageBuilders.SequentialRegion[] regArray ); public abstract void Transform( ref List< ImageBuilders.SequentialRegion > regLst ); public abstract void Transform( ref List< ImageBuilders.ImageAnnotation > anLst ); public abstract void Transform( ref List< ImageBuilders.CodeConstant > ccLst ); public abstract void Transform( ref List< Runtime.Memory.Range > mrLst ); public abstract void Transform( ref Runtime.MemoryAttributes val ); public abstract void Transform( ref Runtime.MemoryAttributes[] maArray ); public abstract void Transform( ref Runtime.MemoryUsage val ); public abstract void Transform( ref Runtime.MemoryUsage[] muArray ); public abstract void Transform( ref Abstractions.PlacementRequirements pr ); public abstract void Transform( ref Abstractions.RegisterDescriptor regDesc ); public abstract void Transform( ref Abstractions.RegisterDescriptor[] regDescArray ); public abstract void Transform( ref Abstractions.RegisterClass val ); public abstract void Transform( ref Abstractions.CallingConvention.Direction val ); //--// public void Transform( ref GrowOnlyHashTable< string, object > ht ) { TransformContents( ht ); } public void Transform( ref GrowOnlyHashTable< Expression, Expression[] > ht ) { TransformContents( ht ); } public void Transform( ref GrowOnlyHashTable< object, ConstantExpression > ht ) { TransformContents( ht ); } public void Transform( ref GrowOnlyHashTable< TypeRepresentation, GrowOnlyHashTable< object, ConstantExpression > > ht ) { TransformContents( ht ); } public void Transform( ref GrowOnlyHashTable< TypeRepresentation, List< ConstantExpression > > ht ) { TransformContents( ht ); } public void Transform( ref GrowOnlyHashTable< BaseRepresentation, InstanceFieldRepresentation > ht ) { TransformContents( ht ); } public void Transform( ref GrowOnlyHashTable< TypeRepresentation, CustomAttributeRepresentation > ht ) { TransformContents( ht ); } public void Transform( ref GrowOnlyHashTable< FieldRepresentation, CustomAttributeRepresentation > ht ) { TransformContents( ht ); } public void Transform( ref GrowOnlyHashTable< MethodRepresentation, CustomAttributeRepresentation > ht ) { TransformContents( ht ); } public void Transform( ref GrowOnlyHashTable< TypeRepresentation, TypeRepresentation > ht ) { TransformContents( ht ); } public void Transform( ref GrowOnlyHashTable< object, DataManager.DataDescriptor > ht ) { TransformContents( ht ); } public void Transform( ref GrowOnlyHashTable< ControlFlowGraphStateForCodeTransformation, ImageBuilders.CompilationState > ht ) { TransformContents( ht ); } public void Transform( ref GrowOnlyHashTable< object, List< ImageBuilders.CodeConstant > > ht ) { TransformContents( ht ); } public void Transform( ref GrowOnlyHashTable ht ) { TransformContents( ht ); } public void Transform( ref GrowOnlyHashTable ht ) { TransformContents( ht ); } public void Transform( ref GrowOnlyHashTable< BaseRepresentation, Abstractions.PlacementRequirements > ht ) { TransformContents( ht ); } public void Transform( ref GrowOnlyHashTable< object, int > ht ) { TransformValueTypeContents( ht ); } public void Transform( ref GrowOnlyHashTable< MethodRepresentation, List > ht ) { TransformContents( ht ); } public void Transform( ref GrowOnlyHashTable< string, SourceCodeTracker.SourceCode > ht ) { TransformContents( ht ); } public void Transform( ref GrowOnlyHashTable< FieldRepresentation, BitFieldDefinition > ht ) { TransformContents( ht ); } //--// #if !TRANSFORMATIONCONTEXT_SHOWALLMETHODSTODEBUGGER [System.Diagnostics.DebuggerHidden] #endif protected override object TransformGenericReference( object obj ) { if(obj is TypeSystemForCodeTransformation) { TypeSystemForCodeTransformation target = (TypeSystemForCodeTransformation)obj; Transform( ref target ); return target; } return base.TransformGenericReference( obj ); } //--// protected override DynamicTransform BuildDynamicTransform() { if(m_dynamicTransform == null) { #if TRANSFORMATIONCONTEXT__USE_EMIT GrowOnlyHashTable< Type, System.Reflection.MethodInfo > ht = GetMethodInfoTable(); List< Type > lst = new List< Type >(); TreeNode tnClassType = new TreeNode( typeof(object ) ); TreeNode tnValueType = new TreeNode( typeof(ValueType) ); foreach(var t in ht.Keys) { TreeNode node = new TreeNode( t ); node.m_method = ht[t]; if(t.IsValueType) { tnValueType.Insert( node ); } else { tnClassType.Insert( node ); } } tnClassType.Normalize(); tnValueType.Normalize(); //--// DynamicMethod methodBuilder = new DynamicMethod( "TransformDecoder", typeof(object), new Type[] { typeof(TransformationContext), typeof(object), typeof(Type) }, true ); ILGenerator il = methodBuilder.GetILGenerator( 256 ); //// il.EmitWriteLine( "Starting check:" ); if(tnValueType.GetNumberOfTerminalNodes() > 0) { tnValueType.Emit( il, true ); } if(tnClassType.GetNumberOfTerminalNodes() > 0) { tnClassType.Emit( il, false ); } m_dynamicTransform = (DynamicTransform)methodBuilder.CreateDelegate( typeof(DynamicTransform) ); #else m_dynamicTransform = TransformThroughInvoke; #endif } return m_dynamicTransform; } //--// #if TRANSFORMATIONCONTEXT__USE_EMIT class TreeNode { // // State // internal Type m_type; internal System.Reflection.MethodInfo m_method; internal List< TreeNode > m_children = new List< TreeNode >(); // // Constructor Methods // internal TreeNode( Type t ) { m_type = t; } // // Helper Methods // internal bool IsSubclassOf( TreeNode node ) { return m_type.IsSubclassOf( node.m_type ); } internal void Insert( TreeNode newNode ) { // // First, relocate all the node that are subclasses of the new node under it. // for(int i = 0; i < m_children.Count; i++) { var child = m_children[i]; if(child.IsSubclassOf( newNode )) { newNode.m_children.Add( child ); m_children.RemoveAt( i-- ); return; } } // // Then, add the node here. // m_children.Add( newNode ); } internal void Normalize() { for(int i = 0; i < m_children.Count; i++) { var child = m_children[i]; var parent = child.m_type.BaseType; if(parent != null && parent != m_type) { foreach(var child2 in m_children) { if(child2.m_type == parent) { child2.m_children.Add( child ); m_children.RemoveAt( i-- ); child = null; break; } } if(child != null) { TreeNode sub = new TreeNode( parent ); m_children[i] = sub; sub.m_children.Add( child ); } } } } internal int GetNumberOfTerminalNodes() { int num = m_method != null ? 1 : 0; foreach(var child in m_children) { num += child.GetNumberOfTerminalNodes(); } return num; } internal delegate Type GetTypeFromHandleDlg( RuntimeTypeHandle handle ); internal void Emit( ILGenerator il , bool fPerformCheck ) { if(fPerformCheck) { if(m_children.Count == 1) { m_children[0].Emit( il, true ); return; } } Label label = il.DefineLabel(); if(fPerformCheck) { //// il.EmitWriteLine( "Checking for: " + m_type.FullName ); if(m_type.IsArray || m_type == typeof(Array)) { GetTypeFromHandleDlg dlg = Type.GetTypeFromHandle; il.Emit( OpCodes.Ldtoken, m_type ); il.Emit( OpCodes.Call, dlg.Method ); il.Emit( OpCodes.Ldarg_2 ); il.Emit( OpCodes.Bne_Un, label ); } else { il.Emit( OpCodes.Ldarg_1 ); il.Emit( OpCodes.Isinst , m_type ); il.Emit( OpCodes.Brfalse, label ); } } foreach(var child in m_children) { child.Emit( il, true ); } if(m_method != null) { System.Reflection.ParameterInfo[] parameters = m_method.GetParameters(); System.Reflection.ParameterInfo paramInfo = parameters[0]; Type paramType = paramInfo.ParameterType; Type elementType = paramType.GetElementType(); LocalBuilder objectRef = il.DeclareLocal( elementType ); il.Emit( OpCodes.Ldarg_1 ); il.Emit( OpCodes.Unbox_Any, elementType ); il.Emit( OpCodes.Stloc, objectRef ); if(m_method.IsStatic == false) { il.Emit( OpCodes.Ldarg_0 ); il.Emit( OpCodes.Castclass, m_method.DeclaringType ); } il.Emit( OpCodes.Ldloca, objectRef ); il.EmitCall( OpCodes.Callvirt, m_method, null ); il.Emit( OpCodes.Ldloc, objectRef ); if(elementType.IsValueType) { il.Emit( OpCodes.Box, elementType ); } } else { //il.EmitWriteLine( "No method for: " + m_type.FullName ); // // In case of failure to find a target transform, return the transform context, so the caller will know nothing got selected. // il.Emit( OpCodes.Ldarg_0 ); } il.Emit( OpCodes.Ret ); if(fPerformCheck) { il.MarkLabel( label ); //// il.EmitWriteLine( "Check failed" ); } } } #else private static object TransformThroughInvoke( TransformationContext context , object obj , Type t ) { TransformationContextForCodeTransformation pThis = (TransformationContextForCodeTransformation)context; System.Reflection.MethodInfo mi; mi = pThis.GetAssociatedTransform( obj, true ); if(mi != null) { return pThis.CallTransformMethod( mi, obj ); } if(obj is Array) { Array array = (Array)obj; pThis.TransformArray( ref array ); return array; } mi = pThis.GetAssociatedTransform( obj, false ); if(mi != null) { return pThis.CallTransformMethod( mi, obj ); } return context; } #if !TRANSFORMATIONCONTEXT_SHOWALLMETHODSTODEBUGGER [System.Diagnostics.DebuggerHidden] #endif protected System.Reflection.MethodInfo GetAssociatedTransform( object obj , bool fExact ) { if(m_handlers == null) { m_handlers = GetMethodInfoTable(); } System.Reflection.MethodInfo res; Type src = obj != null ? obj.GetType() : typeof(object); while(src != null) { if(m_handlers.TryGetValue( src, out res )) { return res; } if(fExact) break; src = src.BaseType; } return null; } #if !TRANSFORMATIONCONTEXT_SHOWALLMETHODSTODEBUGGER [System.Diagnostics.DebuggerHidden] #endif protected object CallTransformMethod( System.Reflection.MethodInfo mi , object obj ) { object[] parameters = new object[] { obj }; mi.Invoke( this, parameters ); return parameters[0]; } #endif } } ================================================ FILE: Zelig/Zelig/CompileTime/CodeGenerator/CodeTransformation/Transformations/CommonMethodRedundancyElimination.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // namespace Microsoft.Zelig.CodeGeneration.IR.Transformations { using System; using System.Collections.Generic; using Microsoft.Zelig.Runtime.TypeSystem; public static class CommonMethodRedundancyElimination { // // Helper Methods // public static bool Execute( ControlFlowGraphStateForCodeTransformation cfg ) { bool fModified = false; if(Transformations.MergeExtendedBasicBlocks.Execute( cfg, preserveInjectionSites: true )) { fModified = true; } if(Transformations.RemoveDeadCode.Execute( cfg, false )) { fModified = true; } if(Transformations.GlobalCopyPropagation.Execute( cfg )) { fModified = true; } if(Transformations.InlineScalars.Execute( cfg )) { fModified = true; } if(Transformations.RemoveSimpleIndirections.Execute( cfg )) { fModified = true; } if(Transformations.RemoveDeadCode.Execute( cfg, false )) { fModified = true; } return fModified; } } } ================================================ FILE: Zelig/Zelig/CompileTime/CodeGenerator/CodeTransformation/Transformations/ConstraintSystemCollector.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // //#define DUMP_CONSTRAINTSYSTEM namespace Microsoft.Zelig.CodeGeneration.IR.Transformations { using System; using System.Collections.Generic; using Microsoft.Zelig.Runtime.TypeSystem; public class ConstraintSystemCollector { public class GraphState { public Kind Flavor; public GrowOnlySet < ConstraintInstance > Constraints; public GrowOnlyHashTable< object , Operator > Vertices; public GrowOnlyHashTable< object , GrowOnlySet< object > > IdentitySets; public GrowOnlyHashTable< object , double > ConstantsSet; public GrowOnlyHashTable< object , string > Labels; public List < object > ProofTests; // // Helper Methods // public bool WasReached( object obj ) { if(this.ProofTests == null) { return true; } foreach(object step in this.ProofTests) { ConstraintInstance ci = step as ConstraintInstance; if(ci != null) { if(ci.Destination == obj || ci.Source == obj) { return true; } } } return false; } } public interface IVisualizer { void DisplayGraph( GraphState gs ); } //--// public enum Kind { LessThanOrEqual , GreaterThanOrEqual, } public class ArrayLengthHolder { // // State // public readonly Expression Array; // // Constructor Methods // public ArrayLengthHolder( Expression array ) { this.Array = array; } // // Equality Methods // public override bool Equals( Object obj ) { if(obj is ArrayLengthHolder) { ArrayLengthHolder other = (ArrayLengthHolder)obj; if(this.Array == other.Array) { return true; } } return false; } public override int GetHashCode() { return this.Array.GetHashCode(); } } public class ConstraintInstance { // // State // public readonly object Destination; public readonly object Source; public readonly double Weight; // // Constructor Methods // public ConstraintInstance( object destination , object source , double weight ) { this.Destination = destination; this.Source = source; this.Weight = weight; } // // Equality Methods // public override bool Equals( Object obj ) { if(obj is ConstraintInstance) { ConstraintInstance other = (ConstraintInstance)obj; if(this.Destination.Equals( other.Destination ) && this.Source .Equals( other.Source ) && this.Weight == other.Weight ) { return true; } } return false; } public override int GetHashCode() { return this.Destination.GetHashCode(); } } public enum Lattice { False , Reduced, True , } private enum NormalizedValue { Invalid, Int , Long , Float , Double , } private class ConstraintState { // // State // internal object m_destination; internal object m_source; internal GrowOnlyHashTable< double, Lattice > m_history; // // Constructor Methods // internal ConstraintState() { } internal ConstraintState( object destination , object source ) { m_destination = destination; m_source = source; m_history = HashTableFactory.New< double, Lattice >(); } // // Equality Methods // public override bool Equals( Object obj ) { if(obj is ConstraintState) { ConstraintState other = (ConstraintState)obj; if(m_destination.Equals( other.m_destination ) && m_source .Equals( other.m_source ) ) { return true; } } return false; } public override int GetHashCode() { return m_destination.GetHashCode(); } } // // State // private readonly ControlFlowGraphStateForCodeTransformation m_cfg; private readonly Kind m_kind; private readonly GrowOnlySet < ConstraintInstance > m_set; private readonly GrowOnlyHashTable< object , Operator > m_vertices; private readonly GrowOnlySet < ArrayLengthHolder > m_arrays; private readonly GrowOnlyHashTable< object , List < ConstraintInstance > > m_incomingEdges; private readonly GrowOnlyHashTable< VariableExpression, GrowOnlySet< object > > m_assignments; // Multiple sources to one destination. private readonly GrowOnlyHashTable< object , GrowOnlySet< object > > m_identitySets; private readonly GrowOnlyHashTable< object , double > m_constantsSet; private readonly GrowOnlySet < ConstraintState > m_proveState; private readonly GrowOnlyHashTable< object, object > m_proveActive; private readonly GrowOnlySet < object > m_proveAttempts; private readonly ConstraintState m_proveLookupHelper; #if DUMP_CONSTRAINTSYSTEM List < object > m_debug_testHistory; GrowOnlyHashTable< object , string > m_debug_labels; GrowOnlyHashTable< VariableExpression, List< VariableExpression > > m_debug_baseVariables; List < ConstantExpression > m_debug_constants; int m_debug_indent; #endif // // Constructor Methods // public ConstraintSystemCollector( ControlFlowGraphStateForCodeTransformation cfg , Kind kind ) { m_cfg = cfg; m_kind = kind; m_set = SetFactory .New< ConstraintInstance >(); m_vertices = HashTableFactory.New< object , Operator >(); m_arrays = SetFactory .New< ArrayLengthHolder >(); m_incomingEdges = HashTableFactory.New< object , List < ConstraintInstance > >(); m_assignments = HashTableFactory.New< VariableExpression, GrowOnlySet< object > >(); m_identitySets = HashTableFactory.New< object , GrowOnlySet< object > >(); m_constantsSet = HashTableFactory.New< object , double >(); //--// m_proveState = SetFactory .New< ConstraintState >(); m_proveActive = HashTableFactory.New< object, object >(); m_proveAttempts = SetFactory .New< object >(); m_proveLookupHelper = new ConstraintState(); //--// Collect(); } // // Helper Methods // public bool Prove( Expression exDestination , Expression exSource , double weight ) { if(m_vertices.ContainsKey( exDestination ) && m_vertices.ContainsKey( exSource ) ) { Debug_Print( "#############################################################" ); m_proveAttempts.Clear(); Debug_ResetReachability(); if(ProveInternal( exDestination, exSource, weight ) != Lattice.False) { Debug_Flush(); Debug_Print( "SUCCESS!" ); //this.ShowGraph(); return true; } } Debug_Print( "FAILED!" ); //this.ShowGraph(); return false; } private Lattice ProveInternal( Expression exDestination , object source , double weight ) { if(m_proveAttempts.Insert( source ) == false) { Debug_Print( "########" ); Debug_PrintContext( exDestination, source, weight, "Round {0}, proving: ", m_proveAttempts.Count ); m_proveState .Clear(); m_proveActive.Clear(); Debug_RecordReachabilityMarker(); if(source is VariableExpression) { // // The algorithm doesn't work reliably with variables as the target of the proof. // // Of course it would be nice to be able to extend the algorithm to variable vs variable cases, // but we need to prove if that is even theorically possible... // } else { Lattice res = ProveInternalDirect( exDestination, source, weight ); if(res != Lattice.False) { return res; } } if(source is ArrayLengthHolder) { ArrayLengthHolder hld = (ArrayLengthHolder)source; VariableExpression array = hld.Array as VariableExpression; GrowOnlySet< object > set; if(array != null && m_identitySets.TryGetValue( array, out set )) { foreach(object altSource in set) { foreach(object vertex in m_vertices.Keys) { ArrayLengthHolder hld2 = vertex as ArrayLengthHolder; if(hld2 != null && hld != hld2 && hld2.Array == altSource) { Lattice res = ProveInternal( exDestination, hld2, weight ); if(res != Lattice.False) { return res; } } } } } } Operator opSource = GetDefinition( source ); if(opSource is LoadIndirectOperator && opSource.HasAnnotation< ArrayLengthAnnotation >()) { object altSource = opSource.FirstArgument; foreach(object vertex in m_vertices.Keys) { ArrayLengthHolder hld = vertex as ArrayLengthHolder; if(hld != null && hld.Array == altSource) { Lattice res = ProveInternal( exDestination, hld, weight ); if(res != Lattice.False) { return res; } } } } else if(opSource is SingleAssignmentOperator || opSource is PiOperator ) { return ProveInternalIfVertex( exDestination, opSource.FirstArgument, weight ); } else if(opSource is PhiOperator) { Lattice res = Lattice.True; foreach(Expression altSource in opSource.Arguments) { Lattice resSub = ProveInternalIfVertex( exDestination, altSource, weight ); if(res > resSub) res = resSub; } return res; } } return Lattice.False; } private Lattice ProveInternalIfVertex( Expression exDestination , object source , double weight ) { if(m_vertices.ContainsKey( source ) == false) { return Lattice.False; } return ProveInternal( exDestination, source, weight ); } //--// private Lattice ProveInternalDirect( object destination , object source , double weight ) { Debug_RecordReachabilityStepIn( destination, source, weight ); Debug_PrintFullContext( destination, source, weight, ">> Checking: {0}", IsMaxVertex( destination ) ? "MAX" : "MIN" ); double valDestination; double valSource; if(m_constantsSet.TryGetValue( destination, out valDestination ) && m_constantsSet.TryGetValue( source , out valSource ) ) { Lattice res2 = IsComparisonAlwaysTrue( valDestination, valSource, weight ) ? Lattice.True : Lattice.False; Debug_Print( string.Format( " << {0} : Constant comparison.", res2 ) ); return UpdateHistory( res2, destination, source, weight ); } ConstraintState cs = ExtractState( destination, source ); GrowOnlyHashTable< double, Lattice > history = cs.m_history; // // Check for: same or stronger difference already proven. // foreach(double oldWeight in history.Keys) { if(IsLessThanOrEqual( oldWeight, weight )) { if(history[oldWeight] == Lattice.True) { Debug_Print( "<< True : Same or stronger difference already proven." ); return UpdateHistory( Lattice.True, destination, source, weight ); } } } // // Check for: same or weaker difference already disproved. // foreach(double oldWeight in history.Keys) { if(IsGreaterThanOrEqual( oldWeight, weight )) { if(history[oldWeight] == Lattice.False) { Debug_Print( "<< False : Same or weaker difference already disproved." ); return UpdateHistory( Lattice.False, destination, source, weight ); } } } // // Check for: "source" on a cycle that was reduced for same or stronger difference. // foreach(double oldWeight in history.Keys) { if(IsLessThanOrEqual( oldWeight, weight )) { if(history[oldWeight] == Lattice.Reduced) { Debug_Print( "<< Reduced : source on a cycle that was reduced for same or stronger difference." ); return UpdateHistory( Lattice.Reduced, destination, source, weight ); } } } // // Check for: traversal reached the source vertex, success if "source - destination (== 0) <= weight". // if(source == destination) { if(IsGreaterThanOrEqual( weight, 0 )) { Debug_Print( "<< True : Traversal reached the source vertex with lower weight." ); return UpdateHistory( Lattice.True, destination, source, weight ); } else { Debug_Print( "<< False : Traversal reached the source vertex with higher weight." ); return UpdateHistory( Lattice.False, destination, source, weight ); } } object previousWeight; if(m_proveActive.TryGetValue( destination, out previousWeight ) && previousWeight is double) { // // Found cycle. // if(IsLessThan( weight, (double)previousWeight )) { // // weight < oldWeight, it's an amplifying cycle. // Debug_Print( "<< False : Amplifying cycle." ); return UpdateHistory( Lattice.False, destination, source, weight ); } else { // // Harmless cycle. // Debug_Print( "<< Reduced : Harmless cycle." ); return UpdateHistory( Lattice.Reduced, destination, source, weight ); } } List< ConstraintInstance > lst; if(m_incomingEdges.TryGetValue( destination, out lst ) == false) { Debug_Print( "<< False: No incoming edges found." ); return UpdateHistory( Lattice.False, destination, source, weight ); } //--// m_proveActive[destination] = weight; bool fUseMeet = IsMaxVertex( destination ); Lattice res = fUseMeet ? Lattice.True : Lattice.False; foreach(ConstraintInstance ci in lst) { Lattice val = ProveInternalDirect( ci.Source, source, weight - ci.Weight ); if(fUseMeet) { if(res > val) res = val; } else { if(res < val) res = val; } Debug_PrintContext( destination, source, weight, " Step: {0} for ", res ); } m_proveActive[destination] = null; //--// Debug_PrintContext( destination, source, weight, "<< Update: {0} for ", res ); return UpdateHistory( res, destination, source, weight ); } private bool IsLessThan( double left , double right ) { if(m_kind == Kind.LessThanOrEqual) { return (left < right); } else { return (left > right); } } private bool IsLessThanOrEqual( double left , double right ) { if(m_kind == Kind.LessThanOrEqual) { return (left <= right); } else { return (left >= right); } } private bool IsGreaterThanOrEqual( double left , double right ) { if(m_kind == Kind.LessThanOrEqual) { return (left >= right); } else { return (left <= right); } } private bool IsComparisonAlwaysTrue( double valDestination , double valSource , double weight ) { if(m_kind == Kind.LessThanOrEqual) { return (valDestination - valSource <= weight); } else { return (valDestination - valSource >= weight); } } private Operator GetDefinition( object obj ) { Operator op; m_vertices.TryGetValue( obj, out op ); return op; } private bool IsMaxVertex( object obj ) { return GetDefinition( obj ) is PhiOperator; } private Lattice UpdateHistory( Lattice res , object destination , object source , double weight ) { Debug_RecordReachabilityStepOut( res ); ConstraintState cs = ExtractState( destination, source ); GrowOnlyHashTable< double, Lattice > history = cs.m_history; history[weight] = res; return res; } private ConstraintState ExtractState( object destination , object source ) { ConstraintState cs; m_proveLookupHelper.m_destination = destination; m_proveLookupHelper.m_source = source; if(m_proveState.Contains( m_proveLookupHelper, out cs ) == false) { cs = new ConstraintState( destination, source ); m_proveState.Insert( cs ); } return cs; } //--// private void Collect() { CollectAssignments(); ComputeEquivalenceSet(); GrowOnlySet< PiOperator > set = CollectPiOperators(); CollectConstraints( set ); //AddConstraintsBetweenConstants(); } private GrowOnlySet< PiOperator > CollectPiOperators() { GrowOnlySet< PiOperator > set = SetFactory.New< PiOperator >(); foreach(var piOp in m_cfg.FilterOperators< PiOperator >()) { set.Insert( piOp ); } return set; } private void CollectAssignments() { foreach(Operator op in m_cfg.DataFlow_SpanningTree_Operators) { if(op is SingleAssignmentOperator) { RecordAssignement( op.FirstResult, op.FirstArgument ); } else if(op is PhiOperator) { foreach(Expression ex in op.Arguments) { RecordAssignement( op.FirstResult, ex ); } } else if(op is PiOperator) { RecordAssignement( op.FirstResult, op.FirstArgument ); } else if(op is LoadIndirectOperator && op.HasAnnotation< ArrayLengthAnnotation >()) { ArrayLengthHolder hld = m_arrays.MakeUnique( new ArrayLengthHolder( op.FirstArgument ) ); RecordAssignement( op.FirstResult, hld ); } } } private void CollectConstraints( GrowOnlySet< PiOperator > set ) { foreach(Operator op in m_cfg.DataFlow_SpanningTree_Operators) { if(op is SingleAssignmentOperator) { RecordConstraint( op.FirstResult, op.FirstArgument, 0 ); RecordDefinition( op ); } else if(op is PhiOperator) { foreach(Expression ex in op.Arguments) { RecordConstraint( op.FirstResult, ex, 0 ); } RecordDefinition( op ); } else if(op is PiOperator) { RecordConstraint( op.FirstResult, op.FirstArgument, 0 ); PiOperator piOp = (PiOperator)op; Expression exLeft; Expression exRight; long val; if(IsCompatible( set, piOp, out exLeft, out exRight, out val )) { RecordConstraint( exLeft, exRight, val ); } RecordDefinition( op ); } else if(op is BinaryOperator) { BinaryOperator op2 = (BinaryOperator)op; op2.EnsureConstantToTheRight(); Expression exLeft = op2.FirstArgument; Expression exRight = op2.SecondArgument; if(!(exLeft is ConstantExpression) && (exRight is ConstantExpression) ) { ConstantExpression exConst = (ConstantExpression)exRight; bool fOk; bool fNegate; switch(op2.Alu) { case BinaryOperator.ALU.ADD: fOk = true; fNegate = false; break; case BinaryOperator.ALU.SUB: fOk = true; fNegate = true; break; default: fOk = false; fNegate = false; break; } if(fOk) { if(exConst.IsValueFloatingPoint) { double value; if(exConst.GetFloatingPoint( out value )) { if(fNegate) { value = -value; } RecordConstraint( op.FirstResult, exLeft, value ); RecordDefinition( op ); } } else if(exConst.IsValueInteger) { long value; if(exConst.GetAsSignedInteger( out value )) { if(fNegate) { value = -value; } RecordConstraint( op.FirstResult, exLeft, value ); RecordDefinition( op ); } } } } } else if(op is LoadIndirectOperator && op.HasAnnotation< ArrayLengthAnnotation >()) { ArrayLengthHolder hld = m_arrays.MakeUnique( new ArrayLengthHolder( op.FirstArgument ) ); RecordConstraint( op.FirstResult, hld, 0 ); RecordDefinition( op ); } } } private void RecordDefinition( Operator op ) { foreach(var ex in op.Results) { m_vertices[ex] = op; } } private void AddConstraintsBetweenConstants() { foreach(ConstraintInstance ci in m_set.ToArray()) // Get a copy of the contents, since we're going to modify the hash table. { object destination = ci.Destination; object source = ci.Source; if(m_constantsSet.ContainsKey( source )) { double oldValue = m_constantsSet[source]; foreach(object constObj in m_constantsSet.Keys) { if(source != constObj) { double newValue = m_constantsSet[constObj]; double diff = newValue - oldValue; RecordConstraint( ci.Destination, constObj, ci.Weight - diff ); } } } if(m_constantsSet.ContainsKey( destination )) { double oldValue = m_constantsSet[destination]; foreach(object constObj in m_constantsSet.Keys) { if(destination != constObj) { double newValue = m_constantsSet[constObj]; double diff = newValue - oldValue; RecordConstraint( constObj, source, ci.Weight + diff ); } } } } } private void ComputeEquivalenceSet() { GrowOnlySet< object > roots = SetFactory.New< object >(); GrowOnlySet< object > history = SetFactory.New< object >(); foreach(VariableExpression var in m_assignments.Keys) { roots.Clear(); foreach(object src in m_assignments[var]) { history.Clear(); FindRoots( roots, history, src ); } if(roots.Count == 1) { foreach(object src in m_assignments[var]) { MergeEquivalenceSets( var, src ); } } } } private void FindRoots( GrowOnlySet< object > roots , GrowOnlySet< object > history , object obj ) { if(history.Insert( obj ) == false) { GrowOnlySet< object > set; if(obj is VariableExpression && m_assignments.TryGetValue( (VariableExpression)obj, out set )) { foreach(object next in set) { FindRoots( roots, history, next ); } } else { roots.Insert( obj ); } } } private void MergeEquivalenceSets( object obj1 , object obj2 ) { GrowOnlySet< object > set1 = HashTableWithSetFactory.Create( m_identitySets, obj1 ); GrowOnlySet< object > set2 = HashTableWithSetFactory.Create( m_identitySets, obj2 ); GrowOnlySet< object > setM = set1.CloneSettings(); setM.Merge ( set1 ); setM.Merge ( set2 ); setM.Insert( obj1 ); setM.Insert( obj2 ); foreach(object obj in setM) { m_identitySets[obj] = setM; } } //--// private void RecordAssignement( VariableExpression varDst , object source ) { HashTableWithSetFactory.Add( m_assignments, varDst, source ); } private bool IsCompatible( GrowOnlySet< PiOperator > set , PiOperator op , out Expression exLeft , out Expression exRight , out long val ) { Expression left = null; Expression right = null; long res = 0; switch(m_kind) { case Kind.LessThanOrEqual: switch(op.RelationOperator) { case PiOperator.Relation.Equal : case PiOperator.Relation.SignedLessThanOrEqual : case PiOperator.Relation.UnsignedLowerThanOrSame: left = op.LeftExpression; right = op.RightExpression; res = 0; break; case PiOperator.Relation.UnsignedHigherThanOrSame: case PiOperator.Relation.SignedGreaterThanOrEqual: left = op.RightExpression; right = op.LeftExpression; res = 0; break; case PiOperator.Relation.UnsignedLowerThan: case PiOperator.Relation.SignedLessThan : left = op.LeftExpression; right = op.RightExpression; res = -1; break; case PiOperator.Relation.UnsignedHigherThan: case PiOperator.Relation.SignedGreaterThan : left = op.RightExpression; right = op.LeftExpression; res = -1; break; } break; case Kind.GreaterThanOrEqual: switch(op.RelationOperator) { case PiOperator.Relation.Equal : case PiOperator.Relation.SignedLessThanOrEqual : case PiOperator.Relation.UnsignedLowerThanOrSame: left = op.RightExpression; right = op.LeftExpression; res = 0; break; case PiOperator.Relation.UnsignedHigherThanOrSame: case PiOperator.Relation.SignedGreaterThanOrEqual: left = op.LeftExpression; right = op.RightExpression; res = 0; break; case PiOperator.Relation.UnsignedLowerThan: case PiOperator.Relation.SignedLessThan : left = op.RightExpression; right = op.LeftExpression; res = -1; break; case PiOperator.Relation.UnsignedHigherThan: case PiOperator.Relation.SignedGreaterThan : left = op.LeftExpression; right = op.RightExpression; res = -1; break; } break; } exLeft = FindDestination( set, op, left ); exRight = FindDestination( set, op, right ); val = res; return exLeft is VariableExpression; } private Expression FindDestination( GrowOnlySet< PiOperator > set , PiOperator op , Expression ex ) { if(ex is VariableExpression) { foreach(PiOperator pi in set) { if(PiOperator.SameAnnotation( op, pi )) { if(pi.FirstArgument == ex) { return pi.FirstResult; } } } } return ex; } private void RecordConstraint( object exLeft , object exRight , double val ) { ConstraintInstance ci = new ConstraintInstance( exLeft, exRight, val ); if(m_set.Insert( ci ) == false) { HashTableWithListFactory.AddUnique( m_incomingEdges, exLeft, ci ); RecordVertex( exLeft ); RecordVertex( exRight ); } } private void RecordVertex( object obj ) { if(m_vertices.ContainsKey( obj ) == false) { m_vertices[obj] = null; if(obj is ConstantExpression) { ConstantExpression exConst = (ConstantExpression)obj; if(exConst.IsValueInteger) { if(exConst.IsValueSigned) { long val; exConst.GetAsSignedInteger( out val ); m_constantsSet[obj] = (double)val; } else { ulong val; exConst.GetAsUnsignedInteger( out val ); m_constantsSet[obj] = (double)val; } } else if(exConst.IsValueFloatingPoint) { double val; exConst.GetFloatingPoint( out val ); m_constantsSet[obj] = val; } } } } // // Access Methods // public Kind SystemKind { get { return m_kind; } } // // Debug Methods // [System.Diagnostics.Conditional( "DUMP_CONSTRAINTSYSTEM" )] private void Debug_Flush() { #if DUMP_CONSTRAINTSYSTEM Console.Out.Flush(); #endif } [System.Diagnostics.Conditional( "DUMP_CONSTRAINTSYSTEM" )] private void Debug_Print( char prefix , string fmt , params object[] args ) { #if DUMP_CONSTRAINTSYSTEM Console.Write ( new String( prefix, m_debug_indent + 1 ) ); Console.Write ( " " ); Console.WriteLine( fmt, args ); #endif } [System.Diagnostics.Conditional( "DUMP_CONSTRAINTSYSTEM" )] private void Debug_Print( string fmt , params object[] args ) { #if DUMP_CONSTRAINTSYSTEM Debug_Print( (char)('0' + (m_debug_indent % 10)), fmt, args ); #endif } [System.Diagnostics.Conditional( "DUMP_CONSTRAINTSYSTEM" )] private void Debug_PrintContext( object destination , object source , double weight , string fmt , params object[] args ) { #if DUMP_CONSTRAINTSYSTEM Debug_Print( "{0,-20} {1} - {2} {3} {4}", string.Format( fmt, args ), GenerateLabel( destination ), GenerateLabel( source ), m_kind == Kind.LessThanOrEqual ? "<=" : ">=", weight ); #endif } [System.Diagnostics.Conditional( "DUMP_CONSTRAINTSYSTEM" )] private void Debug_PrintFullContext( object destination , object source , double weight , string fmt , params object[] args ) { #if DUMP_CONSTRAINTSYSTEM Debug_Print( "{0,-20} {1} - {2} {3} {4}", string.Format( fmt, args ), GenerateLabel( destination ), GenerateLabel( source ), m_kind == Kind.LessThanOrEqual ? "<=" : ">=", weight ); Debug_Association( destination ); Debug_Association( source ); #endif } #if DUMP_CONSTRAINTSYSTEM private void Debug_Association( object obj ) { string label = GenerateLabel( obj ); Operator op = GetDefinition( obj ); if(op != null) { obj = op.ToPrettyString(); } else if(obj is ArrayLengthHolder) { ArrayLengthHolder hld = (ArrayLengthHolder)obj; obj = hld.Array; } Debug_Print( "{0,-20} {1} is {2}", "", label, obj ); } #endif //--// [System.Diagnostics.Conditional( "DUMP_CONSTRAINTSYSTEM" )] public void ShowGraph() { #if DUMP_CONSTRAINTSYSTEM IVisualizer itf = m_cfg.TypeSystem.GetEnvironmentService< IVisualizer >(); if(itf != null) { GenerateLabels(); GraphState gs = new GraphState(); gs.Flavor = m_kind;; gs.Constraints = m_set; gs.Vertices = m_vertices; gs.IdentitySets = m_identitySets; gs.ConstantsSet = m_constantsSet; gs.Labels = m_debug_labels; gs.ProofTests = m_debug_testHistory; itf.DisplayGraph( gs ); } #endif } [System.Diagnostics.Conditional( "DUMP_CONSTRAINTSYSTEM" )] public void Dump() { #if DUMP_CONSTRAINTSYSTEM SortedList< string, object > sortedList = new SortedList< string, object >(); System.Text.StringBuilder sb = new System.Text.StringBuilder(); GenerateLabels(); Console.WriteLine( "#############################################################################" ); Console.WriteLine( "Nodes:" ); foreach(object obj in m_debug_labels.Keys) { sortedList.Add( m_debug_labels[obj], obj ); } foreach(KeyValuePair< string, object > pair in sortedList) { Console.WriteLine( " {0} => {1}", pair.Key, pair.Value ); } Console.WriteLine(); sortedList.Clear(); Console.WriteLine( "Edges:" ); foreach(ConstraintInstance ci in m_set) { sortedList.Add( string.Format( "{0} - {1} {2} {3}", GenerateLabel( ci.Destination ), GenerateLabel( ci.Source ), m_kind == Kind.LessThanOrEqual ? "<=" : ">=", ci.Weight ), null ); } foreach(KeyValuePair< string, object > pair in sortedList) { Console.WriteLine( "{0}", pair.Key ); } Console.WriteLine(); sortedList.Clear(); Console.WriteLine( "Identity Sets:" ); foreach(object obj in m_identitySets.Keys) { sb.Length = 0; sb.AppendFormat( "{0} === ", GenerateLabel( obj ) ); foreach(object obj2 in m_identitySets[obj]) { sb.AppendFormat( "{0} ", GenerateLabel( obj2 ) ); } sortedList.Add( sb.ToString(), null ); } foreach(KeyValuePair< string, object > pair in sortedList) { Console.WriteLine( "{0}", pair.Key ); } Console.WriteLine(); #endif } [System.Diagnostics.Conditional( "DUMP_CONSTRAINTSYSTEM" )] private void Debug_RecordReachabilityMarker() { #if DUMP_CONSTRAINTSYSTEM if(m_debug_testHistory == null) { m_debug_testHistory = new List< object >(); } m_debug_testHistory.Add( "Reset" ); #endif } [System.Diagnostics.Conditional( "DUMP_CONSTRAINTSYSTEM" )] private void Debug_RecordReachabilityStepIn( object destination , object source , double weight ) { #if DUMP_CONSTRAINTSYSTEM m_debug_indent++; m_debug_testHistory.Add( new ConstraintInstance( destination, source, weight ) ); #endif } [System.Diagnostics.Conditional( "DUMP_CONSTRAINTSYSTEM" )] private void Debug_RecordReachabilityStepOut( Lattice res ) { #if DUMP_CONSTRAINTSYSTEM m_debug_indent--; m_debug_testHistory.Add( res ); #endif } [System.Diagnostics.Conditional( "DUMP_CONSTRAINTSYSTEM" )] private void Debug_ResetReachability() { #if DUMP_CONSTRAINTSYSTEM m_debug_testHistory = null; #endif } //--// #if DUMP_CONSTRAINTSYSTEM private void GenerateLabels() { if(m_debug_labels == null) { m_debug_labels = HashTableFactory.New< object , string >(); m_debug_baseVariables = HashTableFactory.New< VariableExpression, List< VariableExpression > >(); m_debug_constants = new List < ConstantExpression >(); foreach(ConstraintInstance ci in m_set) { GenerateLabel( ci.Destination ); GenerateLabel( ci.Source ); } } } private string GenerateLabel( object obj ) { GenerateLabels(); string text; if(m_debug_labels.TryGetValue( obj, out text ) == false) { if(obj is VariableExpression) { VariableExpression var = (VariableExpression)obj; VariableExpression baseVar = var.AliasedVariable; int num = 0; int ver = -1; foreach(VariableExpression oldBaseVar in m_debug_baseVariables.Keys) { if(oldBaseVar == baseVar) { List< VariableExpression > lst = m_debug_baseVariables[oldBaseVar]; for(int i = 0; i < lst.Count; i++) { if(lst[i] == var) { ver = i + 1; break; } } ver = lst.Count + 1; lst.Add( var ); break; } num++; } if(ver == -1) { HashTableWithListFactory.Add( m_debug_baseVariables, baseVar, var ); ver = 1; } text = string.Format( "V{0}_{1}", num, ver ); } else if(obj is ConstantExpression) { ConstantExpression val = (ConstantExpression)obj; int num = -1; for(int i = 0; i < m_debug_constants.Count; i++) { if(m_debug_constants[i] == val) { num = i; break; } } if(num == -1) { num = m_debug_constants.Count; m_debug_constants.Add( val ); } if(val.IsValueFloatingPoint || val.IsValueInteger) { text = string.Format( "C{0}({1})", num, val.Value ); } else { text = string.Format( "C{0}", num ); } } else if(obj is ArrayLengthHolder) { ArrayLengthHolder hld = (ArrayLengthHolder)obj; text = string.Format( "", GenerateLabel( hld.Array ) ); } else { text = obj.ToString(); } m_debug_labels[obj] = text; } return text; } #endif } } ================================================ FILE: Zelig/Zelig/CompileTime/CodeGenerator/CodeTransformation/Transformations/ConvertToLandingPads.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // namespace Microsoft.Zelig.CodeGeneration.IR.Transformations { using System; using System.Collections.Generic; using Microsoft.Zelig.Runtime.TypeSystem; public static class ConvertToLandingPads { class ExceptionRegion { public ExceptionRegion(ExceptionHandlerBasicBlock[] protectedBy, ExceptionHandlerBasicBlock landingPad) { ProtectedBy = protectedBy; LandingPad = landingPad; } public ExceptionHandlerBasicBlock[] ProtectedBy { get; } public ExceptionHandlerBasicBlock LandingPad { get; } }; public static void Execute(ControlFlowGraphStateForCodeTransformation cfg) { WellKnownTypes wkt = cfg.TypeSystem.WellKnownTypes; var handledRegions = new List(); foreach (BasicBlock block in cfg.DataFlow_SpanningTree_BasicBlocks) { // Skip blocks that aren't protected. if (block.ProtectedBy.Length == 0) { continue; } ExceptionRegion handledRegion = null; foreach (var region in handledRegions) { if (ArrayUtility.ArrayEqualsNotNull(block.ProtectedBy, region.ProtectedBy, 0)) { handledRegion = region; break; } } // If we haven't handled this region, create a new landing pad block for it. if (handledRegion == null) { var handledTypes = new Expression[block.ProtectedBy.Length]; var handlerBlocks = new BasicBlock[block.ProtectedBy.Length]; // TODO: Assert that all ProtectedBy blocks have the same protection. for (int i = 0; i < block.ProtectedBy.Length; ++i) { ExceptionHandlerBasicBlock handler = block.ProtectedBy[i]; // All class types for a given handler are required to be the same. We can // therefore inspect only the first one. TypeRepresentation clauseType = handler.HandlerFor[0].ClassObject; // Finally blocks are handled as special clauses with a null vtable. This is // distinct from a catch-all clause, which has an Object vtable. Expression virtualTable; if (clauseType == null) { virtualTable = cfg.TypeSystem.CreateNullPointer(wkt.Microsoft_Zelig_Runtime_TypeSystem_VTable); } else { virtualTable = cfg.TypeSystem.CreateConstantFromObject(clauseType.VirtualTable); } // We set the handler's successor here because we don't want to jump into an // exception handling block with normal flow control. Instead, we'll replace // all exception header blocks for this protected region with a single new // header containing only a landing pad. handledTypes[i] = virtualTable; handlerBlocks[i] = handler.FirstSuccessor; } // Expected form for landing pads: The pad entry serves as the exception "header" // block, and contains only the landing pad instruction itself. This serves as a // single entry point for all handled exception types. The landing pad operator // must be the first operator reached when an exception is thrown. // // Upon entering the landing pad, we select a block based on the result of the // personality function. The handler blocks are ordered and the selector will be // an index into the list of handlers. If the selector doesn't match any block, // we resume unwinding the stack and leave the exception unhandled. TypeRepresentation resultType = wkt.Microsoft_Zelig_Runtime_LandingPadResult; VariableExpression result = cfg.AllocateTemporary(resultType, null); VariableExpression exception = cfg.AllocateTemporary(resultType.Fields[0].FieldType, null); VariableExpression selector = cfg.AllocateTemporary(resultType.Fields[1].FieldType, null); var padEntry = new ExceptionHandlerBasicBlock(cfg); var padBody = NormalBasicBlock.CreateWithSameProtection(handlerBlocks[0]); var resumeBlock = NormalBasicBlock.CreateWithSameProtection(handlerBlocks[0]); // Landing pad entry var landingPadOp = LandingPadOperator.New(null, result, handledTypes, false); landingPadOp.AddAnnotation(DontRemoveAnnotation.Create(cfg.TypeSystemForIR)); padEntry.AddOperator(landingPadOp); padEntry.FlowControl = UnconditionalControlOperator.New(null, padBody); // Landing pad body var handlersWithCleanup = ArrayUtility.InsertAtHeadOfNotNullArray(handlerBlocks, resumeBlock); padBody.AddOperator(LoadInstanceFieldOperator.New(null, resultType.Fields[1], selector, result, false)); padBody.FlowControl = MultiWayConditionalControlOperator.New(null, selector, resumeBlock, handlersWithCleanup); // Resume block resumeBlock.AddOperator(LoadInstanceFieldOperator.New(null, resultType.Fields[0], exception, result, false)); resumeBlock.FlowControl = ResumeUnwindOperator.New(null, exception); handledRegion = new ExceptionRegion(block.ProtectedBy, padEntry); handledRegions.Add(handledRegion); } // Replace the handler for the current block with the landing pad. block.ClearProtectedBy(); block.SetProtectedBy(handledRegion.LandingPad); } } } } ================================================ FILE: Zelig/Zelig/CompileTime/CodeGenerator/CodeTransformation/Transformations/GlobalCopyPropagation.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // namespace Microsoft.Zelig.CodeGeneration.IR.Transformations { using System; using System.Collections.Generic; using Microsoft.Zelig.Runtime.TypeSystem; // // This class computes, for each program point, the set of identity assignments that reach it. // public class GlobalCopyPropagation : IDisposable { internal class SubstitutionScoreBoard { // // State // internal readonly Operator m_op; internal readonly int m_idxDst; internal readonly Expression m_exSrc; // // Constructor Methods // internal SubstitutionScoreBoard( Operator op , int idxDst , Expression exSrc ) { m_op = op; m_idxDst = idxDst; m_exSrc = exSrc; } } // // State // private readonly ControlFlowGraphStateForCodeTransformation m_cfg; private readonly IDisposable m_cfgLock; private readonly BasicBlock[] m_basicBlocks; // All the basic blocks, in spanning tree order. private readonly Operator[] m_operators; // All the operators, in spanning tree order. private readonly VariableExpression[] m_variables; // All the variables, in spanning tree order. private readonly VariableExpression[][] m_variablesByStorage; // Lookup for multi-mapped variables. private readonly VariableExpression.Property[] m_varProps; private readonly int m_bbNum; private readonly int m_opsNum; private readonly int m_varNum; private readonly BitVector[] m_variableUses; // For each variable (spanning tree index), which operators use it. private readonly BitVector[] m_variableDefinitions; // For each variable (spanning tree index), which operators define it. private BitVector[] m_operatorKillPre; // For each operator (spanning tree index), which variable assignments it kills BEFORE its execution. private BitVector[] m_operatorKillPost; // For each operator (spanning tree index), which variable assignments it kills AFTER its execution. private BitVector[] m_operatorCopy; // For each operator (spanning tree index), which variable assignments are available. private BitVector[] m_CPin; private BitVector[] m_CPout; private BitVector[] m_KILL; // For each basic block (spanning tree index), which variable assignments it kills. private BitVector[] m_COPY; // For each basic block (spanning tree index), which variable assignments are available at the exit. // // Constructor Methods // private GlobalCopyPropagation( ControlFlowGraphStateForCodeTransformation cfg ) { m_cfg = cfg; m_cfgLock = cfg.GroupLock( cfg.LockSpanningTree () , cfg.LockPropertiesOfVariables() , cfg.LockUseDefinitionChains () ); m_basicBlocks = cfg.DataFlow_SpanningTree_BasicBlocks; m_operators = cfg.DataFlow_SpanningTree_Operators; m_variables = cfg.DataFlow_SpanningTree_Variables; m_variablesByStorage = cfg.DataFlow_SpanningTree_VariablesByStorage; m_varProps = cfg.DataFlow_PropertiesOfVariables; m_bbNum = m_basicBlocks.Length; m_opsNum = m_operators.Length; m_varNum = m_variables.Length; m_variableUses = cfg.DataFlow_BitVectorsForUseChains; m_variableDefinitions = cfg.DataFlow_BitVectorsForDefinitionChains; //--// ComputeEquationParameters(); SolveEquations(); PropagateSolutions(); } // // Helper Methods // public static bool Execute( ControlFlowGraphStateForCodeTransformation cfg ) { cfg.TraceToFile( "GlobalCopyPropagation" ); using(new PerformanceCounters.ContextualTiming( cfg, "GlobalCopyPropagation" )) { using(GlobalCopyPropagation gcp = new GlobalCopyPropagation( cfg )) { return gcp.Apply(); } } } public void Dispose() { m_cfgLock.Dispose(); } private bool Apply() { TypeSystemForCodeTransformation ts = m_cfg.TypeSystem; Abstractions.Platform pa = ts.PlatformAbstraction; Operator[] operators = m_operators; BitVector[] availableCopies = m_operatorCopy; BitVector unavailableOperators = new BitVector( operators.Length ); List< SubstitutionScoreBoard > workList = null; int opsNum = operators.Length; for(int opIdx = 0; opIdx < opsNum; opIdx++) { Operator op = operators[opIdx]; foreach(int opSrcIdx in availableCopies[opIdx]) { // // Ignore operators that have been modified in this round. // if(unavailableOperators[opSrcIdx]) { continue; } SingleAssignmentOperator opSrc = operators[opSrcIdx] as SingleAssignmentOperator; Expression exSrc = opSrc.FirstArgument; TypeRepresentation tdSrc = exSrc.Type; bool fSkip = false; foreach(Annotation an in opSrc.Annotations) { if(an is NotNullAnnotation) { if(exSrc is ConstantExpression) { // // A constant is never null, so it's OK to ignore the annotation. // continue; } } // // Don't propagate copies if they carry annotations, they would be lost. // fSkip = true; break; } if(fSkip) { continue; } //--// for(int rhsIndex = 0; rhsIndex < op.Arguments.Length; rhsIndex++) { Expression exDst = op.Arguments[rhsIndex]; if(exDst == opSrc.FirstResult && exDst != exSrc && op.CanPropagateCopy( exDst, exSrc ) && pa.CanPropagateCopy( opSrc, op, rhsIndex, m_variables, m_variableUses, m_variableDefinitions, operators ) ) { bool fCopy = false; if(ts.GetLevel( exSrc ) == Operator.OperatorLevel.StackLocations) { // Don't propagate from stack locations to anywhere else, it's inefficient. } else if(ts.GetLevel( exDst ) <= Operator.OperatorLevel.ScalarValues && ts.GetLevel( exSrc ) <= Operator.OperatorLevel.ScalarValues ) { fCopy = true; } else { TypeRepresentation tdDst = exDst.Type; if(ShouldSubstitute( tdDst, tdSrc )) { // // Rhs and Candidate copy are compatible. // fCopy = true; } else if(exSrc is ConstantExpression) { if(tdDst is ReferenceTypeRepresentation || tdDst is PointerTypeRepresentation || tdDst.StackEquivalentType == StackEquivalentType.NativeInt ) { // // We can always assign a constant to a reference, a pointer type, or a native int. // fCopy = true; } else if(tdSrc is ScalarTypeRepresentation && tdDst is ScalarTypeRepresentation ) { // // Convert constant to the target type. // var exConst = (ConstantExpression)exSrc; ulong rawValue; if(exConst.GetAsRawUlong( out rawValue )) { var obj = ConstantExpression.ConvertToType( tdDst, rawValue ); exSrc = m_cfg.TypeSystem.CreateConstant( tdDst, obj ); fCopy = true; } } } if(fCopy == false) { if(op is SingleAssignmentOperator) { VariableExpression lhs = op.FirstResult; if(ShouldSubstitute( lhs.Type, tdSrc )) { // // Lhs and Candidate copy are compatible, through assignment operator. // fCopy = true; } } } } if(fCopy) { foreach(var an in op.FilterAnnotations< BlockCopyPropagationAnnotation >()) { if(an.IsResult == false && an.Index == rhsIndex) { fCopy = false; break; } } } if(fCopy) { if(workList == null) { workList = new List< SubstitutionScoreBoard >(); } workList.Add( new SubstitutionScoreBoard( op, rhsIndex, exSrc ) ); unavailableOperators.Set( opIdx ); } } } } } if(workList == null) { return false; } foreach(SubstitutionScoreBoard sb in workList) { sb.m_op.SubstituteUsage( sb.m_idxDst, sb.m_exSrc ); } return true; } private void ComputeEquationParameters() { // // Compute the KILL and COPY values for each operator. // m_operatorKillPre = BitVector.AllocateBitVectors( m_opsNum, m_opsNum ); m_operatorKillPost = BitVector.AllocateBitVectors( m_opsNum, m_opsNum ); m_operatorCopy = BitVector.AllocateBitVectors( m_opsNum, m_opsNum ); for(int opIdx = 0; opIdx < m_opsNum; opIdx++) { Operator op = m_operators [opIdx]; BitVector opKillPre = m_operatorKillPre [opIdx]; BitVector opKillPost = m_operatorKillPost[opIdx]; BitVector opCopy = m_operatorCopy [opIdx]; foreach(var an in op.FilterAnnotations< PreInvalidationAnnotation >()) { KillAllReferences( opKillPre, an.Target ); } if(op is ReturnControlOperator) { // // We don't want to change the expression associated with the return control operator, // because it's associated with the m_returnValue field on the ControlFlowGraphState object, // and m_returnValue is associated with registers or stack locations during Phase.ExpandAggregateTypes. // foreach(var ex in op.Arguments) { var ex2 = ex as VariableExpression; if(ex2 != null) { KillAllReferences( opKillPre, ex2 ); } } } if(op.MayWriteThroughPointerOperands) { for(int varIdx = 0; varIdx < m_varNum; varIdx++) { if((m_varProps[varIdx] & VariableExpression.Property.AddressTaken) != 0) { KillAllReferences( opKillPost, m_variables[varIdx] ); } } } foreach(var lhs in op.Results) { KillAllReferences( opKillPost, lhs ); } foreach(var an in op.FilterAnnotations< PostInvalidationAnnotation >()) { KillAllReferences( opKillPost, an.Target ); } if(op is SingleAssignmentOperator) { bool fCopy = true; if(op.FirstResult.AliasedVariable is LowLevelVariableExpression && op.FirstArgument is ConstantExpression ) { // // Don't propagate constant if the target is a low-level variable. // fCopy = false; } if(fCopy) { if(op.FirstResult.Type.IsFloatingPoint != op.FirstArgument.Type.IsFloatingPoint) { // // Don't mix floating-point and integer numbers. // fCopy = false; } } if(fCopy) { foreach(var an in op.FilterAnnotations< BlockCopyPropagationAnnotation >()) { if(an.IsResult && an.Index == 0) { fCopy = false; break; } } } if(fCopy) { opCopy.Set( op.SpanningTreeIndex ); } } } // // Compute the KILL and COPY values for each basic block. // m_KILL = BitVector.AllocateBitVectors( m_bbNum, m_opsNum ); m_COPY = BitVector.AllocateBitVectors( m_bbNum, m_opsNum ); for(int bbIdx = 0; bbIdx < m_bbNum; bbIdx++) { BasicBlock bb = m_basicBlocks[bbIdx]; BitVector bbKill = m_KILL [bbIdx]; BitVector bbCopy = m_COPY [bbIdx]; int pos = bb.Operators[0].SpanningTreeIndex; int len = bb.Operators.Length; while(--len >= 0) { bbKill.OrInPlace ( m_operatorKillPre[pos] ); bbCopy.DifferenceInPlace( m_operatorKillPre[pos] ); bbKill.OrInPlace ( m_operatorKillPost[pos] ); bbCopy.DifferenceInPlace( m_operatorKillPost[pos] ); bbCopy.OrInPlace ( m_operatorCopy[pos] ); bbKill.DifferenceInPlace( m_operatorCopy[pos] ); pos++; } } } private void SolveEquations() { // // Prepare initial state for Data Flow computation. // m_CPin = BitVector.AllocateBitVectors( m_bbNum, m_opsNum ); m_CPout = BitVector.AllocateBitVectors( m_bbNum, m_opsNum ); BitVector CopyTotal = new BitVector( m_opsNum ); for(int bbIdx = 0; bbIdx < m_bbNum; bbIdx++) { CopyTotal.OrInPlace( m_COPY[bbIdx] ); } for(int bbIdx = 0; bbIdx < m_bbNum; bbIdx++) { if(m_basicBlocks[bbIdx] is EntryBasicBlock) { } else { m_CPin[bbIdx].Assign( CopyTotal ); } } // // Solve the Data Flow equations. // BitVector tmp = new BitVector( m_opsNum ); while(true) { bool fDone = true; // // CPout = (CPin - Kill) Or Copy // for(int bbIdx = 0; bbIdx < m_bbNum; bbIdx++) { tmp.Difference( m_CPin[bbIdx], m_KILL[bbIdx] ); tmp.OrInPlace( m_COPY[bbIdx] ); if(m_CPout[bbIdx] != tmp) { m_CPout[bbIdx].Assign( tmp ); fDone = false; } } if(fDone) { break; } // // CPin = And { CPout() } // for(int bbIdx = 0; bbIdx < m_bbNum; bbIdx++) { BitVector b = m_CPin[bbIdx]; bool fFirst = true; foreach(BasicBlockEdge edge in m_basicBlocks[bbIdx].Predecessors) { BitVector CPpred = m_CPout[ edge.Predecessor.SpanningTreeIndex ]; if(fFirst) { fFirst = false; b.Assign( CPpred ); } else { b.AndInPlace( CPpred ); } } if(fFirst) { b.ClearAll(); } } } } private void PropagateSolutions() { // // Apply the solution to all the operators. // BitVector tmp = new BitVector( m_opsNum ); BitVector tmp2 = new BitVector( m_opsNum ); for(int bbIdx = 0; bbIdx < m_bbNum; bbIdx++) { tmp.Assign( m_CPin[bbIdx] ); BasicBlock bb = m_basicBlocks[bbIdx]; int pos = bb.Operators[0].SpanningTreeIndex; int len = bb.Operators.Length; while(--len >= 0) { tmp2.Assign( m_operatorCopy[pos] ); tmp.DifferenceInPlace( m_operatorKillPre[pos] ); m_operatorCopy[pos].Assign( tmp ); tmp.DifferenceInPlace( m_operatorKillPost[pos] ); tmp.OrInPlace ( tmp2 ); pos++; } } } //--// private void KillAllReferences( BitVector opKill , VariableExpression var ) { int varIdx = var.SpanningTreeIndex; // // We actually use multiple instances of physical registers and stack locations, each one with a different type. // But whenever we encounter one, we need to kill all of them. // foreach(VariableExpression var2 in m_variablesByStorage[varIdx]) { int varIdx2 = var2.SpanningTreeIndex; opKill.OrInPlace( m_variableDefinitions[varIdx2] ); opKill.OrInPlace( m_variableUses [varIdx2] ); } } private bool ShouldSubstitute( TypeRepresentation tdDst , TypeRepresentation tdSrc ) { if(tdDst.CanBeAssignedFrom( tdSrc, null )) { if(tdDst is PointerTypeRepresentation) { tdDst = tdDst.UnderlyingType; if(tdDst == m_cfg.TypeSystem.WellKnownTypes.System_Void) { // // It's always OK to substitute a 'void*' with something more specific. // return true; } if(tdSrc is PointerTypeRepresentation) { tdSrc = tdSrc.UnderlyingType; // // Only substitute the pointer if the source is more specific. // return ShouldSubstitute( tdDst, tdSrc ); } else { // // If the source is not a pointer, don't make the substitution. // return false; } } return true; } return false; } // // Access Methods // public BasicBlock[] BasicBlocks { get { return m_basicBlocks; } } public Operator[] Operators { get { return m_operators; } } public VariableExpression[] Variables { get { return m_variables; } } public BitVector[] VariableUses { get { return m_variableUses; } } public BitVector[] VariableDefinitions { get { return m_variableDefinitions; } } public BitVector[] AvailableCopyAssignments { get { return m_operatorCopy; } } } } ================================================ FILE: Zelig/Zelig/CompileTime/CodeGenerator/CodeTransformation/Transformations/GlobalRegisterAllocation.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // #define REGISTERALLOCATOR_SPILL_ONLY_ONE_VARIABLE #define REGISTERALLOCATOR_REPORT_SLOW_METHODS namespace Microsoft.Zelig.CodeGeneration.IR.Transformations { using System; using System.Collections.Generic; using Microsoft.Zelig.Runtime.TypeSystem; // // This class converts PseudoRegisters into PhysicalRegisters or moves the variables to stack locations. // public class GlobalRegisterAllocation { internal enum WebFlavor { Must , Should, May , } internal class WebPair { // // State // internal InterferenceNode m_node1; internal InterferenceNode m_node2; internal WebFlavor m_flavor; // // Constructor Methods // internal WebPair( InterferenceNode node1 , InterferenceNode node2 , WebFlavor flavor ) { m_node1 = node1; m_node2 = node2; m_flavor = flavor; } // // Helper methods // internal void MaximizeFlavor( WebFlavor flavor ) { if(m_flavor > flavor) { m_flavor = flavor; } } internal bool IsMatch( InterferenceNode node ) { return m_node1 == node || m_node2 == node; } internal int SpillCost() { return m_node1.m_spillCost + m_node2.m_spillCost; } internal void Remove() { m_node1.m_coalesceWeb.Remove( this ); m_node2.m_coalesceWeb.Remove( this ); } // // Debug Methods // public override string ToString() { return string.Format( "{0} <-> {1} as {2}", m_node1.m_source, m_node2.m_source, m_flavor ); } } internal class InterferenceNode { // // State // internal int m_index; internal VariableExpression m_source; internal Operator m_definition; // We are in SSA form, at most there's one definition. internal Operator[] m_uses; internal BitVector m_compatibleRegs; internal List< WebPair > m_coalesceWeb; internal PhysicalRegisterExpression m_fixed; internal PhysicalRegisterExpression m_assigned; internal int m_candidateColor; internal BitVector m_edges; internal BitVector m_liveness; internal int m_livenessLow; internal int m_livenessHigh; internal int m_degree; internal InterferenceNode m_previousStackElement; internal int m_spillCost; internal bool m_spillCandidate; internal bool m_spillWouldCreateNewWebs; // // Constructor Methods // internal InterferenceNode() // Used as an End-Of-Stack sentinel. { } internal InterferenceNode( int index , VariableExpression source , Operator definition , Operator[] uses , BitVector[] livenessMap ) { m_index = index; m_source = source; m_definition = definition; m_uses = uses; m_compatibleRegs = new BitVector(); m_coalesceWeb = new List< WebPair >(); m_liveness = livenessMap[source.SpanningTreeIndex].Clone(); // // This takes care of registers used in calling convention. // m_fixed = source.AliasedVariable as PhysicalRegisterExpression; m_assigned = m_fixed; } // // Helper methods // internal Abstractions.RegisterClass ComputeConstraintsForLHS() { return RegisterAllocationConstraintAnnotation.ComputeConstraintsForLHS( m_definition, m_source ); } internal Abstractions.RegisterClass ComputeConstraintsForRHS() { Abstractions.RegisterClass constraint = Abstractions.RegisterClass.None; foreach(Operator use in m_uses) { constraint |= RegisterAllocationConstraintAnnotation.ComputeConstraintsForRHS( use, m_source ); } return constraint; } internal void SubstituteDefinition( GlobalRegisterAllocation owner ) { owner.SubstituteDefinition( m_definition, m_source, false ); } internal void SubstituteUsage( GlobalRegisterAllocation owner ) { foreach(Operator use in m_uses) { owner.SubstituteUsage( use, m_source, false ); } } //--// internal WebPair FindPair( InterferenceNode node ) { foreach(var pair in m_coalesceWeb) { if(pair.IsMatch( this ) && pair.IsMatch( node )) { return pair; } } return null; } //--// internal void ResetCandidate() { if(m_assigned != null) { m_candidateColor = m_assigned.RegisterDescriptor.Index; } else { m_candidateColor = -1; } } internal void UpdateAdjacencies( InterferenceNode[] interferenceGraph ) { foreach(int idxEdge in m_edges) { InterferenceNode nodeEdge = interferenceGraph[idxEdge]; nodeEdge.m_degree--; } } internal void Push( InterferenceNode[] interferenceGraph , ref InterferenceNode lastStackElement , bool spillCandidate ) { m_spillCandidate = spillCandidate; m_previousStackElement = lastStackElement; lastStackElement = this; UpdateAdjacencies( interferenceGraph ); } internal bool HasLowerRelativeCost( InterferenceNode otherNode ) { int relCostThis = this .m_spillCost * otherNode.m_edges.Cardinality; int relCostOther = otherNode.m_spillCost * this .m_edges.Cardinality; return relCostThis < relCostOther; } internal bool LivenessOverlapsWith( InterferenceNode otherNode ) { if(this .m_livenessHigh < otherNode.m_livenessLow || otherNode.m_livenessHigh < this .m_livenessLow ) { // // Disjoint live ranges for sure. // return false; } return this.m_liveness.IsIntersectionEmpty( otherNode.m_liveness ) == false; } // // Debug Methods // public override string ToString() { System.Text.StringBuilder sb = new System.Text.StringBuilder(); sb.AppendFormat( "N.{0} {1}", m_index, m_source ); if(m_edges != null) { sb.AppendFormat( " => Edges {0}", m_edges ); } if(m_coalesceWeb.Count > 0) { sb.Append( " => Web [" ); foreach(var pair in m_coalesceWeb) { sb.AppendFormat( " {0} ", pair ); } sb.Append( "]" ); } if(m_fixed != null) { sb.AppendFormat( " => Fixed as {0}", m_fixed ); } if(m_assigned != null) { sb.AppendFormat( " => Assigned to {0}", m_assigned ); } if(m_candidateColor >= 0) { sb.AppendFormat( " => Candidate for {0}", m_candidateColor ); } return sb.ToString(); } } // // State // private readonly ControlFlowGraphStateForCodeTransformation m_cfg; private readonly Abstractions.RegisterDescriptor[] m_registers; private readonly InterferenceNode m_stackSentinel; private GrowOnlySet< VariableExpression > m_spillHistory; private Operator[][] m_defChains; private Operator[][] m_useChains; private int m_interferenceGraphSize; private InterferenceNode[] m_interferenceGraph; private InterferenceNode[] m_interferenceGraphLookup; private DataFlow.ControlTree.NaturalLoops m_naturalLoops; // // Constructor Methods // public GlobalRegisterAllocation( ControlFlowGraphStateForCodeTransformation cfg ) { m_cfg = cfg; //--// // // Get list of possible register candidates. // m_registers = cfg.TypeSystem.PlatformAbstraction.GetRegisters(); //--// m_stackSentinel = new InterferenceNode(); } // // Helper Methods // public static void Execute( ControlFlowGraphStateForCodeTransformation cfg ) { using(new PerformanceCounters.ContextualTiming( cfg, "GlobalRegisterAllocation" )) { GlobalRegisterAllocation gra = new GlobalRegisterAllocation( cfg ); gra.PerformAllocation(); } } private void PerformAllocation() { #if REGISTERALLOCATOR_REPORT_SLOW_METHODS System.Diagnostics.Stopwatch sw = new System.Diagnostics.Stopwatch(); sw.Start(); int iterations = 0; #endif //--// while(true) { #if REGISTERALLOCATOR_REPORT_SLOW_METHODS iterations++; #endif DisposeSpillCosts(); //--// m_cfg.TraceToFile( "RegisterAllocation-Loop" ); CHECKS.ASSERT( Transformations.StaticSingleAssignmentForm.ShouldTransformInto( m_cfg ) == false, "Control Flow Graph no longer in SSA form" ); // // 1) Ensure all the operators with register constraints have pseudo registers as parameters, not stack locations. // Operator[] operators = m_cfg.DataFlow_SpanningTree_Operators; bool fGot = false; int opLen = operators.Length; //foreach(Operator op in operators) for(int idxOp = 0; idxOp < opLen; idxOp++) { Operator op = operators[idxOp]; int opResLen = op.Results.Length; for(int idx = 0; idx < opResLen; idx++) { if(RegisterAllocationConstraintAnnotation.ShouldLhsBeMovedToPseudoRegister( op, idx )) { SubstituteDefinition( op, op.Results[idx], false ); fGot = true; } } opResLen = op.Arguments.Length; for(int idx = 0; idx < opResLen; idx++) { if(RegisterAllocationConstraintAnnotation.ShouldRhsBeMovedToPseudoRegister( op, idx )) { SubstituteUsage( op, (VariableExpression)op.Arguments[idx], false ); fGot = true; } } // // If an operator has some coupling constraints, we create temporary variables for the expressions involved in the constraint. // This relies some of the pressure from the graph coloring algorithm, since these constraints add 'MUST' web edges. // foreach(var an in op.FilterAnnotations< RegisterCouplingConstraintAnnotation >()) { if(an.IsResult1) { var ex = op.Results[an.VarIndex1]; if(!(ex is PseudoRegisterExpression)) { SubstituteDefinition( op, ex, true ); fGot = true; } } else { var ex = (VariableExpression)op.Arguments[an.VarIndex1]; if(!(ex is PseudoRegisterExpression)) { SubstituteUsage( op, ex, true ); fGot = true; } } if(an.IsResult2) { var ex = op.Results[an.VarIndex2]; if(!(ex is PseudoRegisterExpression)) { SubstituteDefinition( op, ex, true ); fGot = true; } } else { var ex = (VariableExpression)op.Arguments[an.VarIndex2]; if(!(ex is PseudoRegisterExpression)) { SubstituteUsage( op, ex, true ); fGot = true; } } } } if(fGot) { continue; } // // 1b) Create Use chains and liveness analysis. // VariableExpression[] variables = m_cfg.DataFlow_SpanningTree_Variables; BitVector[] livenessMap = m_cfg.DataFlow_VariableLivenessMap; // It's indexed as Operator[][] // // 2) Build interference graph. Any variables that have overlapping liveness are set to interfere. // using(new PerformanceCounters.ContextualTiming( m_cfg, "BuildInterferenceGraph" )) { m_interferenceGraphSize = 0; m_interferenceGraph = new InterferenceNode[variables.Length]; m_interferenceGraphLookup = new InterferenceNode[variables.Length]; m_defChains = m_cfg.DataFlow_DefinitionChains; m_useChains = m_cfg.DataFlow_UseChains; bool fRestart = false; int varLen = variables.Length; //foreach(VariableExpression var in variables) for(int idxVar = 0; idxVar < varLen; idxVar++) { VariableExpression var = variables[idxVar]; Operator[] defChain = m_defChains[var.SpanningTreeIndex]; CHECKS.ASSERT( defChain.Length <= 1, "Not in SSA form!" ); VariableExpression varAliased = var.AliasedVariable; bool fInclude = false; if(varAliased is PhysicalRegisterExpression) { fInclude = true; } else if(varAliased is PseudoRegisterExpression) { // // Some variables are not actually defined, because: // 1) they are just aliases for low-level expressions, // 2) they are passed as inputs. // if(defChain.Length == 1 || ((PseudoRegisterExpression)varAliased).SourceVariable.Type.FullName.Equals( "Microsoft.Zelig.Runtime.TypeSystem.CodePointer" )) { fInclude = true; } else { CHECKS.ASSERT( m_useChains[var.SpanningTreeIndex].Length == 0, "Cannot have a use of an undefined non-argument variable." ); } } if(fInclude) { InterferenceNode node = new InterferenceNode( m_interferenceGraphSize, var, defChain.Length == 1 ? defChain[0] : null, m_useChains[var.SpanningTreeIndex], livenessMap ); //--// Abstractions.RegisterClass constraintLHS = node.ComputeConstraintsForLHS(); Abstractions.RegisterClass constraintRHS = node.ComputeConstraintsForRHS(); Abstractions.RegisterClass constraint = constraintLHS | constraintRHS; bool fGotLHS = false; int regLen = m_registers.Length; //foreach(Abstractions.RegisterDescriptor regDesc in m_registers) for(int idxReg = 0; idxReg < regLen; idxReg++) { Abstractions.RegisterDescriptor regDesc = m_registers[idxReg]; if(regDesc.CanAllocate && regDesc.PhysicalStorageSize == node.m_source.Type.SizeOfHoldingVariableInWords) { if((regDesc.ComputeCapabilities & constraintLHS) == constraintLHS) { fGotLHS = true; } if((regDesc.ComputeCapabilities & constraint) == constraint) { node.m_compatibleRegs.Set( regDesc.Index ); } } } // // If no compatible registers, we need to reassign. // if(node.m_compatibleRegs.Cardinality == 0) { fRestart = true; } // // If the variable is already assigned to a physical register, // it has to be either a compatible register or a register that cannot be allocated (special usage registers). // if(node.m_fixed != null) { int idx = node.m_fixed.Number; if(m_registers[idx].CanAllocate) { if(node.m_compatibleRegs[idx] == false) { fRestart = true; } } } if(fRestart) { if(fGotLHS == false) { node.SubstituteDefinition( this ); } else { node.SubstituteUsage( this ); } break; } m_interferenceGraph[m_interferenceGraphSize++] = node; m_interferenceGraphLookup[var.SpanningTreeIndex] = node; } } if(fRestart) { continue; } //--// if(m_interferenceGraphSize != 0) { for(int idx = 0; idx < m_interferenceGraphSize; idx++) { InterferenceNode node = m_interferenceGraph[idx]; node.m_edges = new BitVector( m_interferenceGraphSize ); } //--// // // The data from the liveness analysis doesn't work directly for building the interference graph, // because if a register is invalidated as part of the calling convention but not used in the method, // it won't be marked as alive by the liveness analysis (correctly, since it's not used), // although it should be added to the interference set so that we don't assign scratch registers across method calls. // // Same thing for all the variables that are defined but not used, because their definition leads to a side-effect. // BitVector done = new BitVector(); BitVector tmp = new BitVector( opLen ); for(int idx = 0; idx < opLen; idx++) { Operator op = operators[idx]; foreach(var an in op.FilterAnnotations< PreInvalidationAnnotation >()) { var reg = an.Target.AliasedVariable as PhysicalRegisterExpression; if(reg != null && done[reg.Number] == false) { done[reg.Number] = true; tmp.ClearAll(); for(int idx2 = idx; idx2 < opLen; idx2++) { foreach(var an2 in operators[idx2].FilterAnnotations< InvalidationAnnotation >()) { var reg2 = an2.Target.AliasedVariable as PhysicalRegisterExpression; if(reg2 != null) { if(reg2.Number == reg.Number) { tmp.Set( idx2 ); } } } } for(int idx2 = 0; idx2 < m_interferenceGraphSize; idx2++) { InterferenceNode node = m_interferenceGraph[idx2]; if(node.m_fixed == reg) { node.m_liveness.OrInPlace( tmp ); } } } } int resLen = op.Results.Length; //foreach(var lhs in op.Results) for(int lIdx = 0; lIdx < resLen; lIdx++) { var lhs = op.Results[lIdx]; int lhsIdx = lhs.SpanningTreeIndex; if(m_useChains[lhsIdx].Length == 0) { InterferenceNode node = m_interferenceGraphLookup[lhsIdx]; if(node != null) { node.m_liveness.Set( idx ); } } } foreach(var an in op.FilterAnnotations< PostInvalidationAnnotation >()) { var reg = an.Target.AliasedVariable as PhysicalRegisterExpression; if(reg != null && done[reg.Number] == false) { done[reg.Number] = true; tmp.ClearAll(); for(int idx2 = idx; idx2 < opLen; idx2++) { foreach(var an2 in operators[idx2].FilterAnnotations< InvalidationAnnotation >()) { var reg2 = an2.Target.AliasedVariable as PhysicalRegisterExpression; if(reg2 != null) { if(reg2.Number == reg.Number) { tmp.Set( idx2 ); } } } } for(int idx2 = 0; idx2 < m_interferenceGraphSize; idx2++) { InterferenceNode node = m_interferenceGraph[idx2]; if(node.m_fixed == reg) { node.m_liveness.OrInPlace( tmp ); } } } } } for(int idx = 0; idx < m_interferenceGraphSize; idx++) { InterferenceNode node = m_interferenceGraph[idx]; node.m_liveness.GetRange( out node.m_livenessLow, out node.m_livenessHigh ); } } } if(m_interferenceGraphSize == 0) { // // Nothing to do, probably because there's nothing to compute in this method... // break; } //--// // // 3) Create adjacency information for all the pseudo registers and physical registers. // using(new PerformanceCounters.ContextualTiming( m_cfg, "ComputeAdjacencyMatrix" )) { for(int idx = 0; idx < m_interferenceGraphSize; idx++) { InterferenceNode node = m_interferenceGraph[idx]; for(int idx2 = idx + 1; idx2 < m_interferenceGraphSize; idx2++) { InterferenceNode node2 = m_interferenceGraph[idx2]; if(node.LivenessOverlapsWith( node2 )) { // // The two nodes interfere, so create an edge between them. // node .m_edges.Set( node2.m_index ); node2.m_edges.Set( node .m_index ); } } node.m_degree = node.m_edges.Cardinality; } } // // 4) Is the graph N-colorable? If not, select a candidate for spilling, update the interference graph and repeat. // // Look for any node interfering with less than N other nodes. // Remove it from the graph, put it on a stack, update the edges of the other nodes. // Repeat until no more such nodes are left in the graph. // If at the end the graph has no nodes, it's colorable. // InterferenceNode lastStackElement = m_stackSentinel; for(int nodesToPush = m_interferenceGraphSize; nodesToPush > 0; ) { bool fSpilled = false; for(int idx = 0; idx < m_interferenceGraphSize; idx++) { InterferenceNode node = m_interferenceGraph[idx]; if(node.m_previousStackElement == null) { if(node.m_degree < node.m_compatibleRegs.Cardinality) { node.Push( m_interferenceGraph, ref lastStackElement, false ); fSpilled = true; nodesToPush--; } } } if(fSpilled == false) { // // Coulnd't find any node with degree < N. // Select a node with the lowest spill cost, push it as a candidate and continue. // InterferenceNode nodeToSpill = SelectNodeToSpillOptimistically(); nodeToSpill.Push( m_interferenceGraph, ref lastStackElement, true ); nodesToPush--; } } if(ColorGraph( lastStackElement )) { // // 5) Assign pseudo registers to physical registers. // // // We have a coloring. Substitute registers for candidate variables. // foreach(Operator op in m_cfg.DataFlow_SpanningTree_Operators) { ConvertToPhysicalRegisters( op ); } break; } else { // // Failed to color, spill all interfering nodes, selecting the least expensive ones. // SpillVariables(); } } DisposeSpillCosts(); m_cfg.TraceToFile( "RegisterAllocation-Done" ); while(Transformations.CommonMethodRedundancyElimination.Execute( m_cfg )) { } Transformations.StaticSingleAssignmentForm.ConvertOut( m_cfg, false ); m_cfg.TraceToFile( "RegisterAllocation-Post" ); // // Remove temporary copy propagation blocks. // int stoLen = m_cfg.DataFlow_SpanningTree_Operators.Length; //foreach(Operator op in m_cfg.DataFlow_SpanningTree_Operators) for(int idxSto = 0; idxSto < stoLen; idxSto++) { Operator op = m_cfg.DataFlow_SpanningTree_Operators[idxSto]; foreach(var an in op.FilterAnnotations< BlockCopyPropagationAnnotation >()) { if(an.IsTemporary) { op.RemoveAnnotation( an ); } } } #if REGISTERALLOCATOR_REPORT_SLOW_METHODS sw.Stop(); int totalSeconds = (int)(sw.ElapsedMilliseconds / 1000); if(totalSeconds >= 2) { Console.WriteLine( "NOTICE: Register allocation for method '{0}' took {1} seconds and {2} iterations! [{3} variables and {4} operators]", m_cfg.Method.ToShortString(), totalSeconds, iterations, m_cfg.DataFlow_SpanningTree_Variables.Length, m_cfg.DataFlow_SpanningTree_Operators.Length ); Console.WriteLine( "NOTICE: Interference graph for method '{0}' has {1} nodes!" , m_cfg.Method.ToShortString(), m_interferenceGraphSize ); Console.WriteLine(); } #endif } //--// private int EstimateCostOfOperator( Operator op ) { if(op == null) { return 0; } int depth = m_naturalLoops.GetDepthOfBasicBlock( op.BasicBlock ); return (int)Math.Pow( 8, depth ); } private void DisposeSpillCosts() { if(m_naturalLoops != null) { m_naturalLoops.Dispose(); m_naturalLoops = null; } } private void ComputeSpillCosts() { if(m_naturalLoops == null) { m_naturalLoops = DataFlow.ControlTree.NaturalLoops.Execute( m_cfg ); //--// Abstractions.Platform pa = m_cfg.TypeSystem.PlatformAbstraction; int cost_definition = pa.EstimatedCostOfStoreOperation; int cost_use = pa.EstimatedCostOfLoadOperation; using(new PerformanceCounters.ContextualTiming( m_cfg, "ComputeSpillCosts" )) { for(int idx = 0; idx < m_interferenceGraphSize; idx++) { InterferenceNode node = m_interferenceGraph[idx]; int cost = 0; foreach(Operator def in m_defChains[node.m_source.SpanningTreeIndex]) { cost += cost_definition * EstimateCostOfOperator( def ); } foreach(Operator use in m_useChains[node.m_source.SpanningTreeIndex]) { cost += cost_use * EstimateCostOfOperator( use ); } node.m_spillCost = cost; //--// // // It makes sense to consider the node as a spill candidate // only if removing it would improve the chances of coloring the graph. // BitVector postLiveness = new BitVector(); if(node.m_definition != null) { postLiveness.Set( node.m_definition.SpanningTreeIndex ); } foreach(Operator use in node.m_uses) { postLiveness.Set( use.SpanningTreeIndex ); } node.m_spillWouldCreateNewWebs = false; if(node.m_fixed == null) { foreach(int idxEdge in node.m_edges) { InterferenceNode otherNode = m_interferenceGraph[idxEdge]; if(postLiveness.IsIntersectionEmpty( otherNode.m_liveness )) { node.m_spillWouldCreateNewWebs = true; break; } } } } } } } private InterferenceNode SelectNodeToSpillOptimistically() { ComputeSpillCosts(); InterferenceNode lastNode = null; InterferenceNode firstPhysical = null; for(int idx = 0; idx < m_interferenceGraphSize; idx++) { InterferenceNode node = m_interferenceGraph[idx]; // // Only look for nodes not in the stack yet. // if(node.m_previousStackElement == null) { if(node.m_fixed != null) { // // Just remember the first node associated with a physical register, but don't include them in the estimation. // if(firstPhysical == null) { firstPhysical = node; } } else { if(lastNode == null || node.HasLowerRelativeCost( lastNode )) { lastNode = node; } } } } if(lastNode == null) { // // We didn't find a node with a pseudo register, but we need to push something, so we push a physical register. // lastNode = firstPhysical; } CHECKS.ASSERT( lastNode != null, "Cannot find a candidate for spilling, even if the graph is not colorable" ); return lastNode; } //--// private void SpillVariables() { ComputeSpillCosts(); if(m_spillHistory == null) { m_spillHistory = SetFactory.NewWithReferenceEquality< VariableExpression >(); } InterferenceNode[] candidates = new InterferenceNode[m_interferenceGraphSize]; for(int idx = 0; idx < m_interferenceGraphSize; idx++) { InterferenceNode node = m_interferenceGraph[idx]; if(node.m_fixed != null) { continue; } if(m_spillHistory.Contains( node.m_source )) { continue; } if(node.m_edges.Cardinality < node.m_compatibleRegs.Cardinality && node.m_candidateColor >= 0) { // // This node can be colored for sure, because it interferes with less nodes than available registers. // continue; } candidates[idx] = node; } int iSpilled = 0; while(true) { InterferenceNode nodeToSpill = SelectNodeToSpill( candidates ); if(nodeToSpill == null) { break; } iSpilled++; SpillVariable( candidates, nodeToSpill ); #if REGISTERALLOCATOR_SPILL_ONLY_ONE_VARIABLE break; #endif } if(iSpilled == 0) { throw TypeConsistencyErrorException.Create( "Failed to find a pseudo register to spill in {0}", m_cfg ); } } private void SpillVariable( InterferenceNode[] candidates , InterferenceNode node ) { Operator opDef = node.m_definition; VariableExpression var = node.m_source; PseudoRegisterExpression source = (PseudoRegisterExpression)var.AliasedVariable; StackLocationExpression stackVar = null; ConstantExpression constVar = null; Expression targetVar; //--// m_spillHistory.Insert( var ); // // Remove this node and all the nodes it interferes with from the set of variables viable for spilling. // candidates[node.m_index] = null; foreach(int idxEdge in node.m_edges) { InterferenceNode otherNode = m_interferenceGraph[idxEdge]; candidates[otherNode.m_index] = null; } //--// // // Is this an assignment from an already spilled variables? // If so, we don't need to create a new variable. // if(opDef is SingleAssignmentOperator) { var rhs = opDef.FirstArgument; stackVar = rhs as StackLocationExpression; constVar = rhs as ConstantExpression; if(stackVar != null) { if(m_spillHistory.Contains( stackVar ) == false) { stackVar = null; } } } if(constVar != null) { // // No need to spill, it's a constant. // opDef.Delete(); targetVar = constVar; } else if(stackVar == null) { // // Don't associate the spill variable with the source variable, it would create a wrong alias for aggregate types. // stackVar = m_cfg.AllocateLocalStackLocation( source.Type, source.DebugName, null, 0 ); if(opDef is SingleAssignmentOperator || opDef is PhiOperator ) { opDef.SubstituteDefinition( var, stackVar ); } else { opDef.AddOperatorAfter( SingleAssignmentOperator.New( opDef.DebugInfo, stackVar, var ) ); } m_spillHistory.Insert( stackVar ); targetVar = stackVar; } else { opDef.Delete(); targetVar = stackVar; } //--// foreach(Operator opUse in m_useChains[var.SpanningTreeIndex]) { if(opUse is SingleAssignmentOperator || opUse is PhiOperator ) { // // No need to create a pseudo register and then assign it to the left side. Just substitute the usage. // opUse.SubstituteUsage( var, targetVar ); } else { PseudoRegisterExpression tmp = m_cfg.AllocatePseudoRegister( source.Type, source.DebugName, source.SourceVariable, source.SourceOffset ); opUse.AddOperatorBefore( SingleAssignmentOperator.New( opUse.DebugInfo, tmp, targetVar ) ); opUse.SubstituteUsage( var, tmp ); m_spillHistory.Insert( tmp ); } } } private InterferenceNode SelectNodeToSpill( InterferenceNode[] candidates ) { InterferenceNode lastNode; lastNode = SelectNodeToSpill( candidates, true , true , false ); if(lastNode != null) return lastNode; lastNode = SelectNodeToSpill( candidates, true , false, true ); if(lastNode != null) return lastNode; lastNode = SelectNodeToSpill( candidates, true , false, false ); if(lastNode != null) return lastNode; lastNode = SelectNodeToSpill( candidates, false, true , false ); if(lastNode != null) return lastNode; lastNode = SelectNodeToSpill( candidates, false, false, true ); if(lastNode != null) return lastNode; lastNode = SelectNodeToSpill( candidates, false, false, false ); return lastNode; } private InterferenceNode SelectNodeToSpill( InterferenceNode[] candidates , bool fOnlyConsiderNewWebs , bool fOnlyConsiderSpillCandidates , bool fOnlyConsiderFailures ) { InterferenceNode lastNode = null; for(int idx = 0; idx < candidates.Length; idx++) { InterferenceNode node = candidates[idx]; if(node == null) { continue; } // // Only look at the nodes that, if spilled, would create a new web? // if(fOnlyConsiderNewWebs && node.m_spillWouldCreateNewWebs == false) { continue; } // // Only look at the nodes that have been optimistically pushed on the stack? // if(fOnlyConsiderSpillCandidates && node.m_spillCandidate == false) { continue; } // // Only look at the nodes that failed to be assigned a color? // if(fOnlyConsiderFailures && node.m_candidateColor >= 0) { continue; } if(lastNode == null || node.HasLowerRelativeCost( lastNode )) { lastNode = node; } } return lastNode; } //--// private void ConvertToPhysicalRegisters( Operator op ) { foreach(var lhs in op.Results) { var node = GetInterferenceNode( lhs ); if(node != null) { if(lhs != node.m_assigned) { op.SubstituteDefinition( lhs, node.m_assigned ); } } } foreach(var rhs in op.Arguments) { var node = GetInterferenceNode( rhs ); if(node != null) { if(rhs != node.m_assigned) { op.SubstituteUsage( rhs, node.m_assigned ); } } } } private InterferenceNode GetInterferenceNode( Expression ex ) { if(ex is VariableExpression) { return m_interferenceGraphLookup[ex.SpanningTreeIndex]; } return null; } //--// private void SubstituteDefinition( Operator op , VariableExpression var , bool fBlockCopyPropagation ) { LowLevelVariableExpression source = var as LowLevelVariableExpression; PseudoRegisterExpression tmp = m_cfg.AllocatePseudoRegister( var.Type, var.DebugName, source != null ? source.SourceVariable : null, source != null ? source.SourceOffset : 0 ); op.SubstituteDefinition( var, tmp ); var opNew = SingleAssignmentOperator.New( op.DebugInfo, var, tmp ); if(fBlockCopyPropagation) { opNew.AddAnnotation( BlockCopyPropagationAnnotation.Create( m_cfg.TypeSystem, 0, false, true ) ); } op.AddOperatorAfter( opNew ); } private void SubstituteUsage( Operator op , VariableExpression var , bool fBlockCopyPropagation ) { LowLevelVariableExpression source = var as LowLevelVariableExpression; var sourceVariable = source != null ? source.SourceVariable : null; var sourceOffset = source != null ? source.SourceOffset : 0; if(op is PhiOperator) { PhiOperator opPhi = (PhiOperator)op; var rhs = opPhi.Arguments; var origins = opPhi.Origins; for(int i = 0; i < rhs.Length; i++) { if(rhs[i] == var) { PseudoRegisterExpression tmp = m_cfg.AllocatePseudoRegister( var.Type, var.DebugName, sourceVariable, sourceOffset ); var opNew = SingleAssignmentOperator.New( op.DebugInfo, tmp, var ); if(fBlockCopyPropagation) { opNew.AddAnnotation( BlockCopyPropagationAnnotation.Create( m_cfg.TypeSystem, 0, true, true ) ); } origins[i].AddOperator( opNew ); op.SubstituteUsage( i, tmp ); } } } else { PseudoRegisterExpression tmp = m_cfg.AllocatePseudoRegister( var.Type, var.DebugName, sourceVariable, sourceOffset ); var opNew = SingleAssignmentOperator.New( op.DebugInfo, tmp, var ); if(fBlockCopyPropagation) { opNew.AddAnnotation( BlockCopyPropagationAnnotation.Create( m_cfg.TypeSystem, 0, true, true ) ); } op.AddOperatorBefore( opNew ); op.SubstituteUsage( var, tmp ); } } //--// private bool ColorGraph( InterferenceNode root ) { using(new PerformanceCounters.ContextualTiming( m_cfg, "ColorGraph" )) { InterferenceNode node; bool fFound; // // Prep candidate coloring. // for(node = root; node != m_stackSentinel; node = node.m_previousStackElement) { node.ResetCandidate(); } // // If we cannot find a coloring without the constraints of the coalescing web, we should give up immediately. // fFound = FindColorCandidates( root ); if(fFound) { // // Build the coalesce web. // for(node = root; node != m_stackSentinel; node = node.m_previousStackElement) { node.m_coalesceWeb.Clear(); } for(node = root; node != m_stackSentinel; node = node.m_previousStackElement) { Operator op = node.m_definition; if(op is SingleAssignmentOperator || op is PiOperator ) { MergeCoalesceCandidates( node, op.FirstArgument, WebFlavor.Should ); } if(op is PhiOperator) { foreach(Expression ex in op.Arguments) { MergeCoalesceCandidates( node, ex, WebFlavor.Should ); } } foreach(Operator opUse in node.m_uses) { if(opUse is AbstractAssignmentOperator) { MergeCoalesceCandidates( node, opUse.FirstResult, WebFlavor.Should ); if(opUse is PhiOperator) { foreach(Expression ex in opUse.Arguments) { MergeCoalesceCandidates( node, ex, WebFlavor.Should ); } } } } if(op != null) { foreach(var an in op.FilterAnnotations< RegisterCouplingConstraintAnnotation >()) { var coupledSource = an.FindCoupledExpression( node.m_definition, node.m_source ); if(coupledSource != null) { MergeCoalesceCandidates( node, coupledSource, WebFlavor.Must ); } } } } while(true) { // // Reset colors. // for(node = root; node != m_stackSentinel; node = node.m_previousStackElement) { node.ResetCandidate(); } fFound = FindColorCandidates( root ); if(fFound) { // // Because of the aggressive use of coalesce webs, we might generate an incorrect coloring. // If so, revert the work and try again. // for(node = root; node != m_stackSentinel; node = node.m_previousStackElement) { if(node.m_assigned == null) { foreach(int idxEdge in node.m_edges) { InterferenceNode nodeEdge = m_interferenceGraph[idxEdge]; if(nodeEdge.m_candidateColor == node.m_candidateColor) { nodeEdge.ResetCandidate(); node .ResetCandidate(); fFound = false; } } } } } if(fFound) { AllocateRegisters( root ); break; } // // Remove one node from a coalesce web, retry. // ComputeSpillCosts(); BitVector web = new BitVector(); WebPair bestVictim = null; bestVictim = SelectWebToBreak( root, bestVictim, web, true , true ); bestVictim = SelectWebToBreak( root, bestVictim, web, true , false ); bestVictim = SelectWebToBreak( root, bestVictim, web, false, true ); bestVictim = SelectWebToBreak( root, bestVictim, web, false, false ); CHECKS.ASSERT( bestVictim != null, "Cannot find victim for removal from coalesce web" ); bestVictim.Remove(); } } return fFound; } } private WebPair SelectWebToBreak( InterferenceNode root , WebPair bestVictim , BitVector web , bool fIncludeFailuresOnly , bool fSkipPhysicalWebs ) { if(bestVictim != null) { // // Exit as soon as we find a victim. // return bestVictim; } for(var node = root; node != m_stackSentinel; node = node.m_previousStackElement) { // // On the first pass, skip nodes that have been successfully colored. // if(fIncludeFailuresOnly && node.m_candidateColor >= 0) { continue; } if(node.m_coalesceWeb.Count > 0) { web.ClearAll(); ComputeCoalesceSet( node, web ); bool fSkip = false; if(fSkipPhysicalWebs) { foreach(int idx in web) { InterferenceNode candidate = m_interferenceGraph[idx]; if(candidate.m_fixed != null) { fSkip = true; break; } } } if(fSkip) { continue; } //--// // // Try to find a victim to remove from the web based on its location, // giving higher score to variables from outside loops. // foreach(int idx in web) { InterferenceNode candidate = m_interferenceGraph[idx]; foreach(var pair in candidate.m_coalesceWeb) { if(pair.m_flavor != WebFlavor.Must) { if(bestVictim == null || bestVictim.SpillCost() > pair.SpillCost()) { bestVictim = pair; } } } } } } return bestVictim; } private bool FindColorCandidates( InterferenceNode root ) { var web = new BitVector(); bool fFound = true; for(InterferenceNode node = root; node != m_stackSentinel; node = node.m_previousStackElement) { if(node.m_candidateColor < 0) { BitVector availableRegs = node.m_compatibleRegs.Clone(); web.ClearAll(); ComputeCoalesceSet( node, web ); foreach(int idx in web) { if(UpdateAvailableRegisters( availableRegs, m_interferenceGraph[idx] ) == false) { break; } } bool fGot = false; foreach(int idx in web) { InterferenceNode coalesceNode = m_interferenceGraph[idx]; if(coalesceNode.m_candidateColor >= 0) { // // Assign the same color to all the nodes in the coalesce web, otherwise fail. // if(availableRegs[coalesceNode.m_candidateColor]) { node.m_candidateColor = coalesceNode.m_candidateColor; } fGot = true; break; } } if(fGot == false) { Abstractions.RegisterClass regClass; var td = node.m_source.Type; // // Make sure we select a register that is compatible with the type of variable. // if(td.IsNumeric) { switch(td.BuiltInType) { case TypeRepresentation.BuiltInTypes.R4: regClass = Abstractions.RegisterClass.SinglePrecision; break; case TypeRepresentation.BuiltInTypes.R8: regClass = Abstractions.RegisterClass.DoublePrecision; break; default: regClass = Abstractions.RegisterClass.Integer; break; } } else { regClass = Abstractions.RegisterClass.Address; } foreach(int regIdx in availableRegs) { if((m_registers[regIdx].StorageCapabilities & regClass) == regClass) { node.m_candidateColor = regIdx; break; } } } if(node.m_candidateColor < 0) { fFound = false; } else { foreach(int idx in web) { InterferenceNode coalesceNode = m_interferenceGraph[idx]; if(coalesceNode.m_candidateColor < 0) { if(coalesceNode.m_compatibleRegs[node.m_candidateColor]) { coalesceNode.m_candidateColor = node.m_candidateColor; } } } } } } return fFound; } private void AllocateRegisters( InterferenceNode node ) { for(; node != m_stackSentinel; node = node.m_previousStackElement) { if(node.m_assigned == null) { LowLevelVariableExpression source = (LowLevelVariableExpression)node.m_source.AliasedVariable; node.m_assigned = m_cfg.AllocateTypedPhysicalRegister( source.Type, m_registers[node.m_candidateColor], source.DebugName, source.SourceVariable, source.SourceOffset ); } } } private void ComputeCoalesceSet( InterferenceNode node , BitVector coalesceSet ) { if(coalesceSet.Set( node.m_index )) { var web = node.m_coalesceWeb; if(web != null) { foreach(var pair in web) { ComputeCoalesceSet( pair.m_node1, coalesceSet ); ComputeCoalesceSet( pair.m_node2, coalesceSet ); } } } } private void MergeCoalesceCandidates( InterferenceNode node , Expression ex , WebFlavor webFlavor ) { InterferenceNode nodeSrc = GetInterferenceNode( ex ); if(nodeSrc != null && nodeSrc != node && nodeSrc.m_assigned == null && nodeSrc.LivenessOverlapsWith( node ) == false) { WebPair oldPair = node.FindPair( nodeSrc ); if(oldPair != null) { oldPair.MaximizeFlavor( webFlavor ); } else { var vec = new BitVector(); var vecSrc = new BitVector(); ComputeCoalesceSet( node , vec ); ComputeCoalesceSet( nodeSrc, vecSrc ); if(DoesItInterfereWithCoalesceWeb( node , vecSrc ) || DoesItInterfereWithCoalesceWeb( nodeSrc, vec ) ) { return; } var pair = new WebPair( node, nodeSrc, webFlavor ); node .m_coalesceWeb.Add( pair ); nodeSrc.m_coalesceWeb.Add( pair ); } } } private bool DoesItInterfereWithCoalesceWeb( InterferenceNode node , BitVector vec ) { foreach(int idx in vec) { InterferenceNode other = m_interferenceGraph[idx]; if(other.LivenessOverlapsWith( node )) { return true; } } return false; } private bool UpdateAvailableRegisters( BitVector availableRegs , InterferenceNode node ) { foreach(int idxEdge in node.m_edges) { InterferenceNode nodeEdge = m_interferenceGraph[idxEdge]; int candidateIdx = nodeEdge.m_candidateColor; if(candidateIdx >= 0) { availableRegs.Clear( candidateIdx ); Abstractions.RegisterDescriptor regDesc = m_registers[candidateIdx]; foreach(Abstractions.RegisterDescriptor regDescInterfere in regDesc.InterfersWith) { availableRegs.Clear( regDescInterfere.Index ); } if(availableRegs.Cardinality == 0) { return false; } } } return true; } // // Access Methods // } } ================================================ FILE: Zelig/Zelig/CompileTime/CodeGenerator/CodeTransformation/Transformations/InlineCall.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // namespace Microsoft.Zelig.CodeGeneration.IR.Transformations { using System; using System.Collections.Generic; using Microsoft.Zelig.Runtime.TypeSystem; public sealed class InlineCall { public delegate void Notify( object from, object to ); sealed class CloningContextForInlining : CloningContext { // // State // Notify m_callback; GrowOnlySet< CallOperator > m_inlinedCalls; GrowOnlySet< BasicBlock > m_inlinedBasicBlocks; // // Constructor Methods // internal CloningContextForInlining( ControlFlowGraphState cfgSource , ControlFlowGraphState cfgDestination , Notify callback ) : base( cfgSource, cfgDestination, null ) { m_callback = callback; m_inlinedCalls = SetFactory.NewWithReferenceEquality< CallOperator >(); m_inlinedBasicBlocks = SetFactory.NewWithReferenceEquality< BasicBlock >(); } // // Helper Methods // protected override void RegisterInner( object from , object to ) { base.RegisterInner( from, to ); var call = to as CallOperator; if(call != null) { m_inlinedCalls.Insert( call ); } var bb = to as BasicBlock; if(bb != null) { m_inlinedBasicBlocks.Insert( bb ); } if(m_callback != null) { m_callback( from, to ); } } //--// internal void ApplyProtection( ExceptionHandlerBasicBlock[] protectedBy ) { if(protectedBy.Length > 0) { foreach(object to in m_cloned.Values) { BasicBlock bb = to as BasicBlock; if(bb != null && bb.Owner == m_cfgDestination) { foreach(ExceptionHandlerBasicBlock eh in protectedBy) { bb.SetProtectedBy( eh ); } } } } } internal void UpdateInliningPath( InliningPathAnnotation anOuter ) { MethodRepresentation md = m_cfgSource.Method; foreach(CallOperator call in m_inlinedCalls) { var anInner = call.GetAnnotation< InliningPathAnnotation >(); var anNew = InliningPathAnnotation.Create( this.TypeSystem, anOuter, md, call.DebugInfo, anInner ); call.RemoveAnnotation( anInner ); call.AddAnnotation ( anNew ); } } internal void ResetBasicBlockAnnotations() { foreach(var bb in m_inlinedBasicBlocks) { bb.Annotation = BasicBlock.Qualifier.Normal; } } } // // State // ControlFlowGraphStateForCodeTransformation m_cfg; // // Constructor Methods // private InlineCall( ControlFlowGraphStateForCodeTransformation cfg ) { m_cfg = cfg; } //--// // // Helper Methods // public static bool Execute( CallOperator call , Notify callback ) { BasicBlock entryBasicBlock; BasicBlock exitBasicBlock; return Execute( call, callback, out entryBasicBlock, out exitBasicBlock ); } public static bool Execute( CallOperator call , ControlFlowGraphStateForCodeTransformation cfgTarget , Notify callback ) { BasicBlock entryBasicBlock; BasicBlock exitBasicBlock; return Execute( call, cfgTarget, callback, out entryBasicBlock, out exitBasicBlock ); } public static bool Execute( CallOperator call , Notify callback , out BasicBlock entryBasicBlock , out BasicBlock exitBasicBlock ) { return Execute( call, TypeSystemForCodeTransformation.GetCodeForMethod( call.TargetMethod ), callback, out entryBasicBlock, out exitBasicBlock ); } public static bool Execute( CallOperator call , ControlFlowGraphStateForCodeTransformation cfgTarget , Notify callback , out BasicBlock entryBasicBlock , out BasicBlock exitBasicBlock ) { if(cfgTarget != null) { using(new PerformanceCounters.ContextualTiming( call.BasicBlock.Owner, "InlineCall" )) { ControlFlowGraphStateForCodeTransformation cfg = (ControlFlowGraphStateForCodeTransformation)call.BasicBlock.Owner; InlineCall ctx = new InlineCall( cfg ); entryBasicBlock = call.BasicBlock; exitBasicBlock = ctx.ExecuteInner( call, cfgTarget, callback ); } return true; } entryBasicBlock = null; exitBasicBlock = null; return false; } private BasicBlock ExecuteInner( CallOperator call , ControlFlowGraphStateForCodeTransformation otherCFG , Notify callback ) { BasicBlock current = call.BasicBlock; VariableExpression[] lhs = call.Results; Expression[] rhs = call.Arguments; BasicBlock otherEntry = otherCFG.NormalizedEntryBasicBlock; BasicBlock otherExit = otherCFG.NormalizedExitBasicBlock; CloningContextForInlining context = new CloningContextForInlining( otherCFG, m_cfg, callback ); // // Enumerate all the variables in the target method, create a proper copy (either a local or a temporary variable). // foreach(VariableExpression var in otherCFG.DataFlow_SpanningTree_Variables) { CloneVariable( context, otherCFG, call, rhs, var, false ); } // // Link lhs with return variable. // if(lhs.Length > 0 && otherCFG.ExitBasicBlock != null) { var ret = (ReturnControlOperator)otherCFG.ExitBasicBlock.FlowControl; CHECKS.ASSERT( lhs.Length == ret.Arguments.Length, "Mismatch between return value variable and function result at {0}", call ); for(int i = 0; i < lhs.Length; i++) { context.Register( ret.Arguments[i], lhs[i] ); } } //////////////////////////////////////////////////////////////////////////////// // // We need to merge the CompilationConstraints (CC) of the caller and the callee. // // 1) ccCall tracks the CC at the method call sitre. // // 2) If NullChecks and BoundChecks were disabled for the current method, // we need to re-enable them for the span of the inlined method. // // => ccCall becomes ccCallEntry. // // Compute the delta and emit a CompilationConstraintsOperator if there are any differences. // // // 3) Get the CC at the entry of the target method => ccEntry // The default is for not having any CC unless otherwise specified. // But if ccCallEntry has some CC, we want to make it explicit on ccEntry as well. // This makes it easier to compute the delta between ccCallEntry and ccEntry. // // Compute the delta and emit a CompilationConstraintsOperator if there are any differences. // // // 4) Inline the method and propagate the CC through it => ccExit // // 5) We want to restore the initial state, so we compare "ccExit -> ccCall". // This also reverts back the changes made at 2) // // Compute the delta and emit a CompilationConstraintsOperator if there are any differences. // // 6) If the target method had BuildTimeFlags to change CC, apply them to the current method => ccCall -> ccCallExit. // // Compute the delta and emit a CompilationConstraintsOperator if there are any differences. // //////////////////////////////////////////////////////////////////////////////// CompilationConstraints[] ccEntry = otherCFG.CompilationConstraintsArray; CompilationConstraints[] ccCall = m_cfg .CompilationConstraintsAtOperator( call ); CompilationConstraints[] ccSet; CompilationConstraints[] ccReset; // // It's important that 'newEntry' and 'newExit' are created AFTER we compute the set of compilation constraints for the current method, otherwise they will be reclaimed!! // NormalBasicBlock newEntry = NormalBasicBlock.CreateWithSameProtection( current ); NormalBasicBlock newExit = null; // // Link exit basic block with a new basic block, which will be used to copy back an eventual return value. // if(otherExit != null) { newExit = NormalBasicBlock.CreateWithSameProtection( current ); context.Register( otherExit, newExit ); } //--// CompilationConstraints[] ccCallEntry = ccCall; ccCallEntry = ControlFlowGraphState.RemoveCompilationConstraint( ccCallEntry, CompilationConstraints.NullChecks_OFF ); ccCallEntry = ControlFlowGraphState.RemoveCompilationConstraint( ccCallEntry, CompilationConstraints.BoundsChecks_OFF ); if(ControlFlowGraphStateForCodeTransformation.ComputeDeltaBetweenCompilationConstraints( ccCall, ccCallEntry, out ccSet, out ccReset )) { newEntry.AddOperator( CompilationConstraintsOperator.New( call.DebugInfo, ccSet, ccReset ) ); } //--// ccEntry = ControlFlowGraphStateForCodeTransformation.ComposeCompilationConstraints( ccCallEntry, ccEntry ); if(ControlFlowGraphStateForCodeTransformation.ComputeDeltaBetweenCompilationConstraints( ccCallEntry, ccEntry, out ccSet, out ccReset )) { newEntry.AddOperator( CompilationConstraintsOperator.New( call.DebugInfo, ccSet, ccReset ) ); } if(newExit != null) { GrowOnlyHashTable< BasicBlock, CompilationConstraints[] > ht = otherCFG.PropagateCompilationConstraints( ccEntry ); CompilationConstraints[] ccExit = ControlFlowGraphStateForCodeTransformation.CompilationConstraintsAtBasicBlockExit( ht, otherExit ); if(ControlFlowGraphStateForCodeTransformation.ComputeDeltaBetweenCompilationConstraints( ccExit, ccCall, out ccSet, out ccReset )) { newExit.AddOperator( CompilationConstraintsOperator.New( call.DebugInfo, ccSet, ccReset ) ); } //--// MethodRepresentation.BuildTimeAttributes bta = call.TargetMethod.BuildTimeFlags; CompilationConstraints[] ccCallExit = ccCall; if((bta & MethodRepresentation.BuildTimeAttributes.CanAllocateOnReturn) != 0) { if(ControlFlowGraphState.HasCompilationConstraint( ccCallExit, CompilationConstraints.Allocations_OFF )) { ccCallExit = ControlFlowGraphState.RemoveCompilationConstraint( ccCallExit, CompilationConstraints.Allocations_OFF ); ccCallExit = ControlFlowGraphState.AddCompilationConstraint ( ccCallExit, CompilationConstraints.Allocations_ON ); } } if((bta & MethodRepresentation.BuildTimeAttributes.StackAvailableOnReturn) != 0) { if(ControlFlowGraphState.HasCompilationConstraint( ccCallExit, CompilationConstraints.StackAccess_OFF )) { ccCallExit = ControlFlowGraphState.RemoveCompilationConstraint( ccCallExit, CompilationConstraints.StackAccess_OFF ); ccCallExit = ControlFlowGraphState.AddCompilationConstraint ( ccCallExit, CompilationConstraints.StackAccess_ON ); } } if(ControlFlowGraphStateForCodeTransformation.ComputeDeltaBetweenCompilationConstraints( ccCall, ccCallExit, out ccSet, out ccReset )) { newExit.AddOperator( CompilationConstraintsOperator.New( call.DebugInfo, ccSet, ccReset ) ); } } // // Now clone all the basic blocks and link them. // BasicBlock bbCloned = context.Clone( otherEntry ); newEntry.AddOperator( UnconditionalControlOperator.New( null, bbCloned ) ); context.ApplyProtection( current.ProtectedBy ); context.UpdateInliningPath( call.GetAnnotation< InliningPathAnnotation >() ); context.ResetBasicBlockAnnotations(); // // Insert a nop operator before the call, so we can keep track of the call site in the debugger. // if(call.DebugInfo != null) { call.AddOperatorBefore( NopOperator.New( call.DebugInfo ) ); } return call.SubstituteWithSubGraph( newEntry, newExit ); } private VariableExpression CloneVariable( CloningContext context , ControlFlowGraphStateForCodeTransformation otherCFG , CallOperator call , Expression[] rhs , VariableExpression var , bool fAllocateOnly ) { VariableExpression newVar = context.LookupRegistered( var ); if(newVar != null) { return newVar; } bool fCopy = false; bool fInit = false; if(var is ArgumentVariableExpression) { newVar = m_cfg.AllocateLocal( var.Type, var.DebugName ); fCopy = true; } else if(var is LocalVariableExpression) { LocalVariableExpression loc = (LocalVariableExpression)var; newVar = m_cfg.AllocateLocal( loc.Type, loc.DebugName ); fInit = true; } else if(var is PhysicalRegisterExpression) { PhysicalRegisterExpression reg = (PhysicalRegisterExpression)var; newVar = m_cfg.AllocatePhysicalRegister( reg.RegisterDescriptor ); } else if(var is TemporaryVariableExpression) { newVar = m_cfg.AllocateTemporary( var.Type, var.DebugName ); } else if(var is PhiVariableExpression) { PhiVariableExpression phiVar = (PhiVariableExpression)var; VariableExpression target = phiVar.Target; VariableExpression newTarget; if(ArrayUtility.FindReferenceInNotNullArray( otherCFG.DataFlow_SpanningTree_Variables, target ) >= 0) { // // Variable is used, create normally. // newTarget = CloneVariable( context, otherCFG, call, rhs, target, false ); } else { // // Variable is for reference only, don't create any code for it. // newTarget = CloneVariable( context, otherCFG, call, rhs, target, true ); } newVar = m_cfg.AllocatePhiVariable( newTarget ); } else if (var is ExceptionObjectVariableExpression) { newVar = m_cfg.AllocateExceptionObjectVariable(var.Type); } else { throw TypeConsistencyErrorException.Create( "Unexpected expression '{0}' in expanding call to '{1}'", var, call.TargetMethod ); } if(fAllocateOnly == false) { if(fCopy) { // // Assign parameters to the temporary variables acting as arguments for the inlined method. // call.AddOperatorBefore( SingleAssignmentOperator.New( null, newVar, rhs[var.Number] ) ); } if(fInit) { // // Initialize local variables. // call.AddOperatorBefore( m_cfg.GenerateVariableInitialization( null, newVar ) ); } } newVar.SkipReferenceCounting = var.SkipReferenceCounting; context.Register( var, newVar ); return newVar; } } } ================================================ FILE: Zelig/Zelig/CompileTime/CodeGenerator/CodeTransformation/Transformations/InlineScalars.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // namespace Microsoft.Zelig.CodeGeneration.IR.Transformations { using System; using System.Diagnostics; using Microsoft.Zelig.Runtime.TypeSystem; /// /// Inline common scalar operations and lower the imported wrapping struct to something better resembling native /// types. This entire set of optimizations assumes that all scalar types are created and owned by the runtime. If /// we ever open up the possibility of user-created scalars, some of the assumptions here may be invalidated. /// public static class InlineScalars { // // Helper Methods // public static bool Execute(ControlFlowGraphStateForCodeTransformation cfg) { cfg.TraceToFile("InlineScalars"); using (new PerformanceCounters.ContextualTiming(cfg, "InlineScalars")) { bool fModified = false; fModified |= InlineScalarConstructors(cfg); fModified |= InlineScalarEquality(cfg); fModified |= RemoveScalarFieldLoads(cfg); if (fModified) { cfg.UpdateFlowInformation(); RemoveUnnecessaryAddressLoads(cfg); cfg.DropDeadVariables(); } return fModified; } } private static bool InlineScalarConstructors(ControlFlowGraphStateForCodeTransformation cfg) { Operator[][] defChains = cfg.DataFlow_DefinitionChains; bool fModified = false; cfg.ResetCacheCheckpoint(); // Search for the following pattern: // ScalarType::.ctor(&local, value) // Replace with: // local = value foreach (var callOp in cfg.FilterOperators()) { var targetMethod = callOp.TargetMethod as ConstructorMethodRepresentation; var thisType = callOp.TargetMethod.OwnerType as ScalarTypeRepresentation; if ((targetMethod == null) || (thisType == null)) { continue; } Debug.Assert(callOp.Arguments.Length == 2, "Scalar constructors should always have exactly two arguments: 'this' and the value to initialize with."); // Skip inlining if the source value can't be safely cast to the constructing type. if (!thisType.CanBeAssignedFrom(targetMethod.ThisPlusArguments[1], null)) { continue; } // We can only replace constructors on values that exist on the stack. If thisPtr is an argument // or field, we should be assigning rather than constructing the value. var thisPtr = (VariableExpression)callOp.FirstArgument; var addressOp = (AddressAssignmentOperator)ControlFlowGraphState.CheckSingleDefinition(defChains, thisPtr); Expression initValue = callOp.SecondArgument; var constructing = (VariableExpression)addressOp.FirstArgument; var assignOp = SingleAssignmentOperator.New(callOp.DebugInfo, constructing, initValue); callOp.SubstituteWithOperator(assignOp, Operator.SubstitutionFlags.Default); fModified = true; } cfg.AssertNoCacheRefreshSinceCheckpoint(); return fModified; } private static bool InlineScalarEquality(ControlFlowGraphStateForCodeTransformation cfg) { Operator[][] defChains = cfg.DataFlow_DefinitionChains; bool fModified = false; cfg.ResetCacheCheckpoint(); // Patterns: // - Replace (scalar.Equals(scalar)) with (scalar == scalar) // - Replace (op_Equality(scalar, scalar)) with (scalar == scalar) // - Replace (op_Inequality(scalar, scalar)) with (scalar != scalar) foreach (var callOp in cfg.FilterOperators()) { var targetMethod = callOp.TargetMethod; var thisType = targetMethod.OwnerType as ScalarTypeRepresentation; if ((targetMethod == null) || (thisType == null)) { continue; } bool isStatic = targetMethod is StaticMethodRepresentation; CompareAndSetOperator.ActionCondition condition; switch (targetMethod.Name) { case "op_Equality": case "Equals": condition = CompareAndSetOperator.ActionCondition.EQ; break; case "op_Inequality": condition = CompareAndSetOperator.ActionCondition.NE; break; default: // Not an equality operator. continue; } Expression left; Expression right; if (isStatic) { Debug.Assert(callOp.Arguments.Length == 3, "Static equality operators should always have exactly three arguments: null 'this', value, and the value to compare to."); left = callOp.Arguments[1]; right = callOp.Arguments[2]; } else { Debug.Assert(callOp.Arguments.Length == 2, "Instance equality operators should always have exactly two arguments: 'this' and the value to compare to."); right = callOp.Arguments[1]; if (!(right.Type is ScalarTypeRepresentation)) { // Comparand is not a scalar, so skip inlining. continue; } var thisPtr = (VariableExpression)callOp.FirstArgument; left = LoadScalarAddress(cfg, defChains, thisPtr, callOp, true); } var compOperator = CompareAndSetOperator.New(callOp.DebugInfo, condition, false, callOp.FirstResult, left, right); callOp.SubstituteWithOperator(compOperator, Operator.SubstitutionFlags.Default); fModified = true; } cfg.AssertNoCacheRefreshSinceCheckpoint(); return fModified; } private static bool RemoveScalarFieldLoads(ControlFlowGraphStateForCodeTransformation cfg) { Operator[][] useChains = cfg.DataFlow_UseChains; Operator[][] defChains = cfg.DataFlow_DefinitionChains; bool fModified = false; cfg.ResetCacheCheckpoint(); // Pattern: Replace (scalarPtr->m_value) with (*scalarPtr) foreach (var loadFieldOp in cfg.FilterOperators()) { if (!(loadFieldOp.Field.OwnerType is ScalarTypeRepresentation)) { continue; } var thisPtr = (VariableExpression)loadFieldOp.FirstArgument; Expression loadedValue = LoadScalarAddress(cfg, defChains, thisPtr, loadFieldOp, loadFieldOp.MayThrow); VariableExpression field = loadFieldOp.FirstResult; foreach (Operator useOp in useChains[field.SpanningTreeIndex]) { useOp.SubstituteUsage(field, loadedValue); } loadFieldOp.SubstituteWithOperator(NopOperator.New(loadFieldOp.DebugInfo), Operator.SubstitutionFlags.Default); fModified = true; } // If modified, we need to refresh useChains in case variables were changed. If we don't do this, FilterOperators // below will refresh the operators, and SpanningTreeIndex and other info between variables and our stale useChains // may be mismatched. if (fModified) { cfg.AssertNoCacheRefreshSinceCheckpoint(); useChains = cfg.DataFlow_UseChains; cfg.ResetCacheCheckpoint(); } // Pattern: Replace (&scalarPtr->m_value) with (scalarPtr) foreach (var loadFieldOp in cfg.FilterOperators()) { if (!(loadFieldOp.Field.OwnerType is ScalarTypeRepresentation)) { continue; } VariableExpression fieldPtr = loadFieldOp.FirstResult; foreach (Operator useOp in useChains[fieldPtr.SpanningTreeIndex]) { useOp.SubstituteUsage(fieldPtr, loadFieldOp.FirstArgument); } loadFieldOp.SubstituteWithOperator(NopOperator.New(loadFieldOp.DebugInfo), Operator.SubstitutionFlags.Default); fModified = true; } cfg.AssertNoCacheRefreshSinceCheckpoint(); return fModified; } private static Expression LoadScalarAddress( ControlFlowGraphStateForCodeTransformation cfg, Operator[][] defChains, VariableExpression pointer, Operator usingOp, bool checkForNull) { // Special case: If the pointer is an address assignment operator with a single definition, we can recover // the original expression without creating a new temporary and load operation. if (!(pointer is ArgumentVariableExpression)) { var defOp = ControlFlowGraphState.CheckSingleDefinition(defChains, pointer); Debug.Assert(defOp != null, "Could not find source of scalar address."); if (defOp is AddressAssignmentOperator) { return defOp.FirstArgument; } } TypeRepresentation loadedType = pointer.Type.UnderlyingType; var loadedValue = cfg.AllocateTemporary(loadedType, null); var loadOp = LoadIndirectOperator.New(usingOp.DebugInfo, loadedType, loadedValue, pointer, null, 0, false, checkForNull); usingOp.AddOperatorBefore(loadOp); return loadedValue; } private static bool RemoveUnnecessaryAddressLoads(ControlFlowGraphStateForCodeTransformation cfg) { Operator[][] useChains = cfg.DataFlow_UseChains; cfg.ResetCacheCheckpoint(); bool fModified = false; // Search for the following pattern where LoadIndirect is the only use of address: // address = (expr) // local = LoadIndirect(address) // Replace with: // expr // Pattern: Replace (*&expr) with (expr) foreach (var addressOp in cfg.FilterOperators()) { // Remove orphan address loads. if (useChains[addressOp.FirstResult.SpanningTreeIndex].Length == 0) { addressOp.Delete(); fModified = true; continue; } var loadOp = ControlFlowGraphState.CheckSingleUse(useChains, addressOp.FirstResult) as LoadIndirectOperator; if (loadOp != null) { Expression loaded = addressOp.FirstArgument; foreach (Operator useOp in useChains[loadOp.FirstResult.SpanningTreeIndex]) { // Skip this substitution if the use is in an operator we just removed. if (useOp.BasicBlock != null) { useOp.SubstituteUsage(loadOp.FirstResult, loaded); } } // Delete instead of replacing with NOP. We don't want to save the debug info. addressOp.Delete(); loadOp.Delete(); fModified = true; } } // If modified, we need to refresh useChains in case variables were changed. If we don't do this, FilterOperators // below will refresh the operators, and SpanningTreeIndex and other info between variables and our stale useChains // may be mismatched if (fModified) { cfg.AssertNoCacheRefreshSinceCheckpoint(); useChains = cfg.DataFlow_UseChains; cfg.ResetCacheCheckpoint(); } // Pattern: Replace (*&obj.Field) with (obj.Field) foreach (var addressOp in cfg.FilterOperators()) { var loadOp = ControlFlowGraphState.CheckSingleUse(useChains, addressOp.FirstResult) as LoadIndirectOperator; if (loadOp != null) { LoadFieldOperator newLoadOp; if (addressOp is LoadInstanceFieldAddressOperator) { newLoadOp = LoadInstanceFieldOperator.New( loadOp.DebugInfo, addressOp.Field, loadOp.FirstResult, addressOp.FirstArgument, loadOp.MayThrow); } else { newLoadOp = LoadStaticFieldOperator.New(loadOp.DebugInfo, addressOp.Field, loadOp.FirstResult); } addressOp.Delete(); loadOp.SubstituteWithOperator(newLoadOp, Operator.SubstitutionFlags.Default); fModified = true; } } // If modified, we need to refresh useChains in case variables were changed. If we don't do this, FilterOperators // below will refresh the operators, and SpanningTreeIndex and other info between variables and our stale useChains // may be mismatched if (fModified) { cfg.AssertNoCacheRefreshSinceCheckpoint(); useChains = cfg.DataFlow_UseChains; cfg.ResetCacheCheckpoint(); } // Pattern: Replace (*&array[index]) with (array[index]) foreach (var addressOp in cfg.FilterOperators()) { var loadOp = ControlFlowGraphState.CheckSingleUse(useChains, addressOp.FirstResult) as LoadIndirectOperator; if (loadOp != null) { var newLoadOp = LoadElementOperator.New( loadOp.DebugInfo, loadOp.FirstResult, addressOp.FirstArgument, addressOp.SecondArgument, addressOp.AccessPath, loadOp.MayThrow); addressOp.Delete(); loadOp.SubstituteWithOperator(newLoadOp, Operator.SubstitutionFlags.Default); fModified = true; } } cfg.AssertNoCacheRefreshSinceCheckpoint(); return fModified; } } } ================================================ FILE: Zelig/Zelig/CompileTime/CodeGenerator/CodeTransformation/Transformations/MergeExtendedBasicBlocks.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // namespace Microsoft.Zelig.CodeGeneration.IR.Transformations { using System; using System.Diagnostics; using Microsoft.Zelig.Runtime.TypeSystem; public static class MergeExtendedBasicBlocks { // // Helper Methods // public static bool Execute( ControlFlowGraphStateForCodeTransformation cfg, bool preserveInjectionSites ) { cfg.TraceToFile( "MergeExtendedBasicBlocks" ); using(new PerformanceCounters.ContextualTiming( cfg, "MergeExtendedBasicBlocks" )) { bool fModified = false; bool fDone = false; while(!fDone) { BasicBlock[] basicBlocks = cfg.DataFlow_SpanningTree_BasicBlocks; fDone = true; foreach(BasicBlock bb in basicBlocks) { if(!(bb is NormalBasicBlock)) { continue; } UnconditionalControlOperator ctrl = bb.FlowControl as UnconditionalControlOperator; if(ctrl == null) { continue; } BasicBlock bbNext = ctrl.TargetBranch; // Most transforms depend on finding a block with a specific annotation to inject operators // into. We need to avoid removing the last block of a given annotation unless the caller is // looking for an aggressive merge. if(preserveInjectionSites && (bbNext.Annotation != bb.Annotation)) { continue; } if(TryMergeWithSuccessor( bb, bbNext )) { fModified = true; fDone = false; // When eliminating a successor, we need to reflow the graph; restart the loop. break; } if(ReplaceBlockIfEmpty( bb, bbNext )) { fModified = true; fDone = false; } } } return fModified; } } private static bool TryMergeWithSuccessor(BasicBlock block, BasicBlock successor) { // If the successor is special or this block isn't its only predecessor, we have to keep them separate. if (!(successor is NormalBasicBlock) || (successor.Predecessors.Length != 1)) { return false; } Debug.Assert(successor.Predecessors[0].Predecessor == block, "A block's sole successor must have the block as a predecessor."); // If the exception handling for these two blocks is different, they can't be merged. if (!ArrayUtility.ArrayEqualsNotNull(block.ProtectedBy, successor.ProtectedBy, 0)) { return false; } // It's too complicated to remove a basic block if the successor contains phi operators. foreach (Operator op in successor.Operators) { if (op is PhiOperator || op is PiOperator) { return false; } } block.Merge(successor); return true; } private static bool ReplaceBlockIfEmpty(BasicBlock block, BasicBlock successor) { // If the block isn't empty, or it loops back to itself, skip it. if ((block.Operators.Length != 1) || (block == successor)) { return false; } // It's too complicated to remove a basic block if the successor contains phi operators. foreach (Operator op in successor.Operators) { if (op is PhiOperator) { return false; } } bool modified = false; foreach (BasicBlockEdge edge in block.Predecessors) { BasicBlock predecessor = edge.Predecessor; // If this predecessor isn't a special block and it's under the same exception // handling scope, retarget its flow control to the successor. if ((predecessor is NormalBasicBlock) && ArrayUtility.ArrayEqualsNotNull(block.ProtectedBy, predecessor.ProtectedBy, 0) && predecessor.FlowControl.SubstituteTarget(block, successor)) { modified = true; } } return modified; } } } ================================================ FILE: Zelig/Zelig/CompileTime/CodeGenerator/CodeTransformation/Transformations/PerformClassExtension.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // //#define TRACK_TIMING //#define TRACK_TIMING_LEVEL2 //#define TRACK_TIMING_LEVEL3 //#define TRACK_TIMING_LEVEL4 namespace Microsoft.Zelig.CodeGeneration.IR.Transformations { using System; using System.Collections.Generic; using Microsoft.Zelig.Runtime.TypeSystem; #if TRACK_TIMING internal class ExecutionTiming : IDisposable { [ThreadStatic] static int s_nesting; string m_text; PerformanceCounters.Timing m_counter; internal ExecutionTiming( string text , params object[] args ) { m_text = string.Format( text, args ); s_nesting++; m_counter.Start(); } public void Dispose() { m_counter.Stop( true ); Console.WriteLine( "Execution time {0,8}usec : {1}{2}", m_counter.TotalInclusiveMicroSeconds, new string( ' ', (--s_nesting) * 3 ), m_text ); } } #else internal class ExecutionTiming : IDisposable { internal ExecutionTiming( string text , params object[] args ) { } public void Dispose() { } } #endif //--// internal class PerformClassExtension : ScanTypeSystem { internal struct Duplicate { // // State // internal object From; internal object To; // // Constructor Methods // internal Duplicate( object from, object to ) { this.From = from; this.To = to; } } // // State // ReverseIndexTypeSystem m_reverseIndex; GrowOnlySet< object > m_newObjectsForReverseIndex; List< Duplicate > m_duplicates; TypeRepresentation m_overridingTD; TypeRepresentation m_overriddenTD; bool m_fNoConstructors; bool m_fSameExtends; GrowOnlyHashTable< object, object > m_remapAliases; LocateUsageInCode m_inlineCandidates; GrowOnlyHashTable< MethodRepresentation, MethodRepresentation > m_substitutionTable; object m_activeContext; object m_replaceFrom; object m_replaceTo; // // Constructor Methods // internal PerformClassExtension( TypeSystemForCodeTransformation typeSystem , ReverseIndexTypeSystem reverseIndex , List< Duplicate > duplicates ) : base( typeSystem, typeof(PerformClassExtension) ) { m_reverseIndex = reverseIndex; m_duplicates = duplicates; //--// m_newObjectsForReverseIndex = SetFactory.New< object >(); m_remapAliases = HashTableFactory.New< object, object >(); m_inlineCandidates = new LocateUsageInCode( typeSystem ); m_substitutionTable = HashTableFactory.New< MethodRepresentation, MethodRepresentation >(); } internal PerformClassExtension( TypeSystemForCodeTransformation typeSystem , ReverseIndexTypeSystem reverseIndex , List< Duplicate > duplicates , TypeRepresentation overridingTD , TypeRepresentation overriddenTD , bool fNoConstructors ) : this( typeSystem, reverseIndex, duplicates ) { m_overridingTD = overridingTD; m_overriddenTD = overriddenTD; m_fNoConstructors = fNoConstructors; //--// m_fSameExtends = (overridingTD.Extends == overriddenTD.Extends); // // Either the two classes have the same super-class, or the overridding one derives from Object. // if(!m_fSameExtends) { if(overridingTD.Extends != typeSystem.WellKnownTypes.System_Object) { throw TypeConsistencyErrorException.Create( "Cannot extend '{0}' with '{1}', their superclasses are incompatible", overriddenTD, overridingTD ); } } } //--// // // Helper Methods // internal static GrowOnlyHashTable< MethodRepresentation, MethodRepresentation > Hack_GetSubstitutionTable( TypeSystemForCodeTransformation typeSystem , TypeRepresentation overridingTD , TypeRepresentation overriddenTD ) { var pce = new PerformClassExtension( typeSystem, null, null ); pce.m_overridingTD = overridingTD; pce.m_overriddenTD = overriddenTD; EquivalenceSet set = new EquivalenceSet( delegate( BaseRepresentation context1, BaseRepresentation br1 , BaseRepresentation context2, BaseRepresentation br2 ) { DelayedMethodParameterTypeRepresentation td1 = context1 as DelayedMethodParameterTypeRepresentation; DelayedMethodParameterTypeRepresentation td2 = context2 as DelayedMethodParameterTypeRepresentation; if(td1 != null && td2 != null) { MethodRepresentation md1 = br1 as MethodRepresentation; MethodRepresentation md2 = br2 as MethodRepresentation; if(md1 != null && md2 != null) { if(md1.IsOpenMethod && md2.IsOpenMethod) { if(md1.GenericParametersDefinition[td1.ParameterNumber].IsCompatible( ref md2.GenericParametersDefinition[td2.ParameterNumber] )) { return true; } } } } return false; } ); set.AddEquivalencePair( overridingTD, overriddenTD ); foreach(MethodRepresentation md in pce.m_overridingTD.Methods) { pce.m_substitutionTable[md] = pce.FindTargetMethod( md, set ); } return pce.m_substitutionTable; } //--// internal void Execute() { #if GENERICS_DEBUG if(m_overridingTD.ToString() == "AbstractReferenceTypeRepresentation(Microsoft.Zelig.Runtime.InterlockedImpl)") { } #endif // // 1) We need to deal with Generic Types and Methods. // // For generic types, we need to ensure we have as many specialization of the overridding type as those of the overridden one. // // For generic methods, we need to ensure that the overriding generic method is instantiated as many times as the overridden one. // #if TRACK_TIMING_LEVEL2 using(new ExecutionTiming( "InstantiateGenericTypesAndMethods for {0}", m_overridingTD )) #endif //// HACK: We performed the instantiation at metadata import time. //// { //// InstantiateGenericTypesAndMethods(); //// } // // 2) Go through all the whole type system and replace references from overridingTD to overriddenTD. // #if TRACK_TIMING_LEVEL2 using(new ExecutionTiming( "PrepareFieldAliasing for {0}", m_overridingTD )) #endif { PrepareFieldAliasing(); } #if TRACK_TIMING_LEVEL2 using(new ExecutionTiming( "PrepareMethodAliasing for {0}", m_overridingTD )) #endif { PrepareMethodAliasing(); } #if TRACK_TIMING_LEVEL2 using(new ExecutionTiming( "RemapTypesFromOverridingToOverridden for {0}", m_overridingTD )) #endif { RemapTypesFromOverridingToOverridden(); } #if TRACK_TIMING_LEVEL2 using(new ExecutionTiming( "ProcessMethodAliasing for {0}", m_overridingTD )) #endif { ProcessMethodAliasing(); } // // 3) Move fields and methods from overriding type to overridden one: // a) fields should not collide, // GrowOnlyHashTable< object, object > remap = HashTableFactory.New< object, object >(); #if TRACK_TIMING_LEVEL2 using(new ExecutionTiming( "MoveFields for {0}", m_overridingTD )) #endif { MoveFields( remap ); } #if TRACK_TIMING_LEVEL2 using(new ExecutionTiming( "MoveMethods for {0}", m_overridingTD )) #endif { MoveMethods( remap ); } #if TRACK_TIMING_LEVEL2 using(new ExecutionTiming( "ProcessTypeSystem for {0}", m_overridingTD )) #endif { ProcessRemaps( remap ); } FlushNewObjects(); } //--// private void InstantiateGenericTypesAndMethods() { GrowOnlyHashTable< MethodRepresentation, List< MethodRepresentation > > ht = null; if(m_overridingTD.IsOpenType || m_overridingTD.Generic != null || m_overriddenTD.IsOpenType || m_overriddenTD.Generic != null ) { throw TypeConsistencyErrorException.Create( "Class Extension for generic types not supported yet: '{0}' => '{1}'", m_overridingTD, m_overriddenTD ); } foreach(MethodRepresentation md in m_overridingTD.Methods) { if(md.IsOpenMethod) { EquivalenceSet set = new EquivalenceSet( delegate( BaseRepresentation context1, BaseRepresentation br1 , BaseRepresentation context2, BaseRepresentation br2 ) { DelayedMethodParameterTypeRepresentation td1 = context1 as DelayedMethodParameterTypeRepresentation; DelayedMethodParameterTypeRepresentation td2 = context2 as DelayedMethodParameterTypeRepresentation; if(td1 != null && td2 != null) { MethodRepresentation md1 = br1 as MethodRepresentation; MethodRepresentation md2 = br2 as MethodRepresentation; if(md1 != null && md2 != null) { if(md1.IsOpenMethod && md2.IsOpenMethod) { if(md1.GenericParametersDefinition[td1.ParameterNumber].IsCompatible( ref md2.GenericParametersDefinition[td2.ParameterNumber] )) { return true; } } } } return false; } ); set.AddEquivalencePair( m_overridingTD, m_overriddenTD ); MethodRepresentation overriddenMD = FindTargetMethod( md, set ); if(overriddenMD != null) { if(ht == null) { m_typeSystem.BuildHierarchyTables(); ht = m_typeSystem.GenericMethodInstantiations; } if(ht.ContainsKey( overriddenMD )) { foreach(MethodRepresentation overriddenInstantiationMD in ht[overriddenMD]) { if(m_overridingTD.FindMatch( overriddenInstantiationMD, set ) == null) { InstantiationContext ic; MethodRepresentation instantiatedMD = m_typeSystem.InstantiateMethod( md, null, overriddenInstantiationMD.GenericParameters, out ic ); ControlFlowGraphStateForCodeTransformation cfg = TypeSystemForCodeTransformation.GetCodeForMethod( md ); if(cfg != null) { instantiatedMD.Code = cfg.Clone( ic ); } } } } } } } } private void PrepareFieldAliasing() { // // AliasForBaseField should only act as a placeholder for a field on the target class. // foreach(FieldRepresentation fd in m_overridingTD.Fields) { FieldRepresentation aliasedFD; aliasedFD = FindAliasedField( m_typeSystem.WellKnownTypes.Microsoft_Zelig_Runtime_AliasForBaseFieldAttribute, fd, m_overriddenTD ); if(aliasedFD != null) { foreach(CustomAttributeAssociationRepresentation caa in fd.CustomAttributes) { aliasedFD.CopyCustomAttribute( caa ); } m_remapAliases[fd] = aliasedFD; m_overridingTD.RemoveField( fd ); m_typeSystem.ProhibitUse( fd ); continue; } } } private static FieldRepresentation FindAliasedField( TypeRepresentation customAttribute , FieldRepresentation fd , TypeRepresentation targetType ) { CustomAttributeRepresentation ca = fd.FindCustomAttribute( customAttribute ); if(ca != null) { fd.RemoveCustomAttribute( ca ); string targetField; if(ca.FixedArgsValues.Length == 0) { targetField = fd.Name; } else { targetField = (string)ca.FixedArgsValues[0]; } FieldRepresentation aliasedFD = targetType.FindField( targetField ); if(aliasedFD == null) { throw TypeConsistencyErrorException.Create( "Field '{0}' is aliased to non-existing or incompatible field {1}", fd, targetField ); } return aliasedFD; } return null; } //--// private void PrepareMethodAliasing() { // // AliasForBaseMethod should only act as a placeholder for a call to another method. // AliasForSuperMethod should only act as a placeholder for a call to another method. // Both should not be invoked from any other class other than this one. // Implementation should be empty. // foreach(MethodRepresentation md in m_overridingTD.Methods) { MethodRepresentation aliasedMD; aliasedMD = FindAliasedMethod( m_typeSystem.WellKnownTypes.Microsoft_Zelig_Runtime_AliasForBaseMethodAttribute, md, m_overriddenTD ); if(aliasedMD != null) { // // Any call to this method should be inlined, if the target method is going to be overridden. // m_inlineCandidates.AddLookup( md ); m_remapAliases[md] = aliasedMD; m_overridingTD.RemoveMethod( md ); m_typeSystem.ProhibitUse( md ); continue; } aliasedMD = FindAliasedMethod( m_typeSystem.WellKnownTypes.Microsoft_Zelig_Runtime_AliasForSuperMethodAttribute, md, m_overriddenTD.Extends ); if(aliasedMD != null) { m_remapAliases[md] = aliasedMD; m_overridingTD.RemoveMethod( md ); m_typeSystem.ProhibitUse( md ); continue; } } } private static MethodRepresentation FindAliasedMethod( TypeRepresentation customAttribute , MethodRepresentation md , TypeRepresentation targetType ) { CustomAttributeRepresentation ca = md.FindCustomAttribute( customAttribute ); if(ca != null) { string targetMethod = (string)ca.FixedArgsValues[0]; MethodRepresentation aliasedMD = targetType.FindMatch( targetMethod, md, null ); if(aliasedMD == null) { throw TypeConsistencyErrorException.Create( "Method '{0}' is aliased to non-existing or incompatible method {1}", md, targetMethod ); } if(TypeSystemForCodeTransformation.GetCodeForMethod( md ) != null) { throw TypeConsistencyErrorException.Create( "Method '{0}' cannot be an alias for a base method and have an implementation", md ); } if(md.MemberAccess != MethodRepresentation.Attributes.Private && !(md is VirtualMethodRepresentation)) { throw TypeConsistencyErrorException.Create( "Alias Method '{0}' has to be marked 'private'", md ); } return aliasedMD; } return null; } //--// private void RemapTypesFromOverridingToOverridden() { // // Remove the type from the list and process it unconditionally. // m_typeSystem.Types.Remove( m_overridingTD ); ProcessRemap( m_overridingTD , m_overriddenTD ); ProcessRemap( m_overridingTD.VirtualTable, m_overriddenTD.VirtualTable ); //--// m_remapAliases .RefreshHashCodes(); m_inlineCandidates.RefreshHashCodes(); } //--// private void ProcessMethodAliasing() { foreach(MethodRepresentation md in m_overridingTD.Methods) { m_substitutionTable[md] = FindTargetMethod( md, null ); } // // If any of the overriding methods has a call to one of the aliased method, the calls have to be inlined. // if(m_inlineCandidates.Entries.Count > 0) { m_inlineCandidates.ProcessType( m_overridingTD ); foreach(List< Operator > lst in m_inlineCandidates.Entries.Values) { foreach(Operator op in lst) { CallOperator call = (CallOperator)op; if(call != null) { MethodRepresentation md = call.TargetMethod; MethodRepresentation mdRemapped = (MethodRepresentation)m_remapAliases[md]; // // If the aliased method is going to be overridden, we need to inline it. // if(m_substitutionTable.ContainsValue( mdRemapped )) { call.TargetMethod = mdRemapped; Transformations.InlineCall.Execute( call, NotifyNewObjects ); } } } } } ProcessRemaps( m_remapAliases ); } private MethodRepresentation FindTargetMethod( MethodRepresentation md , EquivalenceSet set ) { string targetMethod; CustomAttributeRepresentation ca = md.FindCustomAttribute( m_typeSystem.WellKnownTypes.Microsoft_Zelig_Runtime_AliasForTargetMethodAttribute ); if(ca != null) { targetMethod = (string)ca.FixedArgsValues[0]; } else { targetMethod = md.Name; } MethodRepresentation overriddenMD; if(md.HasCustomAttribute( m_typeSystem.WellKnownTypes.Microsoft_Zelig_Runtime_InjectAtEntryPointAttribute )) { TypeRepresentation[] tdThisPlusArguments = md.ThisPlusArguments; if(md.ReturnType != m_typeSystem.WellKnownTypes.System_Void) { throw TypeConsistencyErrorException.Create( "Method '{0}' cannot have a return value because it's marked as InjectAtEntryPoint", md ); } overriddenMD = null; foreach(MethodRepresentation md2 in m_overriddenTD.Methods) { if(md2.Name == targetMethod) { // // Don't compare the first argument, a method signature does not include any 'this' pointer. // if(BaseRepresentation.ArrayEqualsThroughEquivalence( tdThisPlusArguments, md2.ThisPlusArguments, 1, -1, set )) { overriddenMD = md2; break; } } } if(overriddenMD == null) { throw TypeConsistencyErrorException.Create( "Type '{0}' doesn't have a method compatible for injection of '{0}'", m_overriddenTD.FullNameWithAbbreviation, md.ToShortString() ); } } else if(md.HasCustomAttribute( m_typeSystem.WellKnownTypes.Microsoft_Zelig_Runtime_InjectAtExitPointAttribute )) { TypeRepresentation[] tdThisPlusArguments = md.ThisPlusArguments; int numThisPlusArguments = tdThisPlusArguments.Length; overriddenMD = null; foreach(MethodRepresentation md2 in m_overriddenTD.Methods) { if(md2.Name == targetMethod) { TypeRepresentation[] td2ThisPlusArguments = md2.ThisPlusArguments; int num2ThisPlusArguments = td2ThisPlusArguments.Length; if(BaseRepresentation.EqualsThroughEquivalence( md.ReturnType, md2.ReturnType, set )) { // // There' an extra parameter in the overriding method, for the result value. // if(numThisPlusArguments == num2ThisPlusArguments + 1) { // // Make sure the extra parameter is compatible with the return type. // if(BaseRepresentation.EqualsThroughEquivalence( tdThisPlusArguments[numThisPlusArguments-1], md2.ReturnType, set )) { // // Don't compare the first argument, a method signature does not include any 'this' pointer. // if(BaseRepresentation.ArrayEqualsThroughEquivalence( tdThisPlusArguments, td2ThisPlusArguments, 1, num2ThisPlusArguments - 1, set )) { overriddenMD = md2; break; } } } } } } if(overriddenMD == null) { throw TypeConsistencyErrorException.Create( "Type '{0}' doesn't have a method compatible for injection of '{0}'", m_overriddenTD.FullNameWithAbbreviation, md.ToShortString() ); } } else { overriddenMD = m_overriddenTD.FindMatch( targetMethod, md, set ); } if(ca != null) { if(overriddenMD == null) { throw TypeConsistencyErrorException.Create( "Method '{0}' is aliased to non-existing method {1}", md, targetMethod ); } } else { if(overriddenMD != null) { if((overriddenMD is ConstructorMethodRepresentation) != (md is ConstructorMethodRepresentation)) { throw TypeConsistencyErrorException.Create( "Method '{0}' cannot override incompatible method '{1}'", md, overriddenMD ); } } } return overriddenMD; } //--// private void MoveFields( GrowOnlyHashTable< object, object > remap ) { foreach(FieldRepresentation overridingFD in m_overridingTD.Fields) { m_overriddenTD.AddField( overridingFD ); } } //--// private void MoveMethods( GrowOnlyHashTable< object, object > remap ) { ConstructorMethodRepresentation overiddenDefaultConstructor = m_overriddenTD.FindDefaultConstructor(); foreach(MethodRepresentation overridingMD in m_substitutionTable.Keys) { CHECKS.ASSERT(overridingMD.OwnerType == m_overriddenTD, "Remapping from {0} to {1} failed on method {2}", m_overridingTD, m_overriddenTD, overridingMD ); MethodRepresentation overriddenMD = m_substitutionTable[overridingMD]; ControlFlowGraphStateForCodeTransformation overridingCFG = TypeSystemForCodeTransformation.GetCodeForMethod( overridingMD ); ControlFlowGraphStateForCodeTransformation overriddenCFG = overriddenMD != null ? TypeSystemForCodeTransformation.GetCodeForMethod( overriddenMD ) : null; bool fAddToOverridden = false; bool fSubstituteToOverridden = false; bool fRemoveOverriding = false; bool fMigrateMethodImpl = false; if(overridingMD is ConstructorMethodRepresentation || overridingMD is StaticConstructorMethodRepresentation ) { bool fDiscard = overridingMD.HasCustomAttribute( m_typeSystem.WellKnownTypes.Microsoft_Zelig_Runtime_DiscardTargetImplementationAttribute ); bool fMerge = overridingMD.HasCustomAttribute( m_typeSystem.WellKnownTypes.Microsoft_Zelig_Runtime_MergeWithTargetImplementationAttribute ); if(overridingCFG == null && fMerge) { throw TypeConsistencyErrorException.Create( "Constructor method '{0}' cannot be an internal call and be decorated with the MergeWithTargetImplementation attribute", overridingMD ); } if(overridingMD is ConstructorMethodRepresentation) { if(m_fNoConstructors) continue; if(!fDiscard && !fMerge) { throw TypeConsistencyErrorException.Create( "Constructor method '{0}' should be decorated with DiscardTargetImplementation or MergeWithTargetImplementation", overridingMD ); } //// //// When extending a type, constructors have to be merged, and the first thing to check is whether or not oldTD and newTD share the same super class: //// //// 1) Same Extends? //// Yes) //// 2) New Constructor? //// Yes) //// Just add newMD to the list of methods on oldTD. //// DONE) //// //// No) //// [Either Merge or Discard should be set at this point] //// Check Merge and Discard flags (for merge, only same super class calls are allowed, single operator, just forward arguments). //// Substitute oldMD for newMD. //// DONE) //// //// No) //// [In this case, newTD should extend System.Object, nothing else is allowed.] //// 3) New Constructor? //// Yes) //// 4) Does oldTD have a default constructor? //// Yes) //// Remove call to newTD super constructor, inline in its place the default constructor. //// Substitute oldMD for newMD. //// DONE) //// //// No) //// Just add newMD to the list of methods on oldTD. //// DONE) //// //// No) //// [Either Merge or Discard should be set at this point] //// //// 5) Is Merge? //// Yes) //// Remove call to newTD super constructor, inline in its place the old constructor. //// Substitute oldMD for newMD. //// DONE) //// //// No) [Then it's Discard] //// Unless base() in oldMD is a call to the default constructor, fail. //// Change call to object() with oldTD.super() //// Substitute oldMD for newMD. //// DONE) //// if(m_fSameExtends) // 1) { if(overriddenMD == null) // 2) { if(fMerge) { if(overiddenDefaultConstructor == null) { throw TypeConsistencyErrorException.Create( "Overriding constructor '{0}' cannot be merged, neither a matching nor a default constructor could be found", overridingMD ); } CallOperator oldCall = FindSuperConstructorCall( overridingCFG ); CallOperator newCall = InstanceCallOperator.New( oldCall.DebugInfo, oldCall.CallType, overiddenDefaultConstructor, new Expression[] { oldCall.FirstArgument }, true ); NotifyNewObjects( null, newCall ); oldCall.AddOperatorAfter( newCall ); overridingCFG.TraceToFile( "InlineCall" ); Transformations.InlineCall.Execute( newCall, NotifyNewObjects ); overridingCFG.TraceToFile( "InlineCall-Post" ); // // Now we are left with two calls to the base constructor, we have to remove the second one. // bool fGotGoodOne = false; foreach(Operator op in oldCall.BasicBlock.Operators) { CallOperator call = op as CallOperator; if(call != null && call.TargetMethod is ConstructorMethodRepresentation) { if(fGotGoodOne == false) { fGotGoodOne = true; } else { call.Delete(); break; } } } } fAddToOverridden = true; } else { if(fMerge) { // TODO: Check that the prologues of the two methods are the same. // // Create a proper invocation list. // VariableExpression[] args = overridingCFG.Arguments; Expression[] rhs = new Expression[args.Length]; for(int i = 0; i < args.Length; i++) { rhs[i] = args[i]; } // // Substitute old call to overridden constructor, then inline the whole thing. // CallOperator oldCall = FindSuperConstructorCall( overridingCFG ); CallOperator newCall = InstanceCallOperator.New( oldCall.DebugInfo, oldCall.CallType, overriddenMD, rhs, true ); NotifyNewObjects( null, newCall ); oldCall.SubstituteWithOperator( newCall, Operator.SubstitutionFlags.CopyAnnotations ); overridingCFG.TraceToFile( "InlineCall" ); Transformations.InlineCall.Execute( newCall, NotifyNewObjects ); overridingCFG.TraceToFile( "InlineCall-Post" ); } fSubstituteToOverridden = true; } } else // Different super class { if(overriddenMD == null) // 3) { if(overiddenDefaultConstructor != null) // 4) { CallOperator call = FindSuperConstructorCall( overridingCFG ); call.TargetMethod = overiddenDefaultConstructor; overridingCFG.TraceToFile( "InlineCall" ); Transformations.InlineCall.Execute( call, NotifyNewObjects ); overridingCFG.TraceToFile( "InlineCall-Post" ); } fAddToOverridden = true; } else { if(fMerge) // 5) { // TODO: Check that the prologues of the two methods are the same. CallOperator oldCall = FindSuperConstructorCall( overridingCFG ); CallOperator newCall = InstanceCallOperator.New( oldCall.DebugInfo, oldCall.CallType, overriddenMD, oldCall.Arguments, true ); NotifyNewObjects( null, newCall ); oldCall.SubstituteWithOperator( newCall, Operator.SubstitutionFlags.CopyAnnotations ); overridingCFG.TraceToFile( "InlineCall" ); Transformations.InlineCall.Execute( newCall, NotifyNewObjects ); overridingCFG.TraceToFile( "InlineCall-Post" ); } fSubstituteToOverridden = true; } } } else { if(overriddenMD == null) { fAddToOverridden = true; } else { // // Inline the other static constructor. // Expression[] rhs = new Expression[] { overriddenCFG.Arguments[0] }; CallOperator call = InstanceCallOperator.New( null, CallOperator.CallKind.Direct, overriddenMD, rhs, true ); NotifyNewObjects( null, call ); BasicBlock bb = overridingCFG.NormalizedEntryBasicBlock; bb.FirstOperator.AddOperatorBefore( call ); overridingCFG.TraceToFile( "InlineCall" ); Transformations.InlineCall.Execute( call, NotifyNewObjects ); overridingCFG.TraceToFile( "InlineCall-Post" ); //--// fSubstituteToOverridden = true; } } } else { // // Non-constructor case. // bool fInsertPre = overridingMD.HasCustomAttribute( m_typeSystem.WellKnownTypes.Microsoft_Zelig_Runtime_InjectAtEntryPointAttribute ); bool fInsertPost = overridingMD.HasCustomAttribute( m_typeSystem.WellKnownTypes.Microsoft_Zelig_Runtime_InjectAtExitPointAttribute ); if(fInsertPre && fInsertPost) { throw TypeConsistencyErrorException.Create( "Method '{0}' cannot be decorated with both InjectAtEntryPoint and InjectAtExitPoint", overridingMD ); } if(fInsertPre || fInsertPost) { if(overriddenMD == null) { throw TypeConsistencyErrorException.Create( "Method '{0}' cannot be injected into target because target is missing", overridingMD ); } if(overriddenCFG == null) { throw TypeConsistencyErrorException.Create( "Method '{0}' cannot be injected into target because target doesn't have an implementation", overridingMD ); } } if(fInsertPre) { BasicBlock injectBasicBlock = overriddenCFG.GetInjectionPoint( BasicBlock.Qualifier.EntryInjectionEnd ); // // Create a proper invocation list. // VariableExpression[] args = overriddenCFG.Arguments; Expression[] rhs = new Expression[args.Length]; for(int i = 0; i < args.Length; i++) { rhs[i] = args[i]; } CallOperator newCall = InstanceCallOperator.New( null, CallOperator.CallKind.Direct, overridingMD, rhs, true ); NotifyNewObjects( null, newCall ); injectBasicBlock.AddOperator( newCall ); overriddenCFG.TraceToFile( "InjectCall" ); Transformations.InlineCall.Execute( newCall, NotifyNewObjects ); overriddenCFG.TraceToFile( "InjectCall-Post" ); fRemoveOverriding = true; } else if(fInsertPost) { BasicBlock injectBasicBlock = overriddenCFG.GetInjectionPoint( BasicBlock.Qualifier.ExitInjectionStart ); // // Create a proper invocation list. // VariableExpression[] args = overriddenCFG.Arguments; Expression[] rhs = new Expression[args.Length + 1]; for(int i = 0; i < args.Length; i++) { rhs[i] = args[i]; } rhs[args.Length] = overriddenCFG.ReturnValue; CallOperator newCall = InstanceCallOperator.New( null, CallOperator.CallKind.Direct, overridingMD, VariableExpression.ToArray( overriddenCFG.ReturnValue ), rhs, true ); NotifyNewObjects( null, newCall ); injectBasicBlock.AddOperator( newCall ); overriddenCFG.TraceToFile( "InjectCall" ); Transformations.InlineCall.Execute( newCall, NotifyNewObjects ); overriddenCFG.TraceToFile( "InjectCall-Post" ); fRemoveOverriding = true; } else { // // The default case is very simple, either add or substitute. // if(overriddenMD == null) { fAddToOverridden = true; } else { fSubstituteToOverridden = true; } } } if(fAddToOverridden) { m_overriddenTD.AddMethod( overridingMD ); fMigrateMethodImpl = true; } if(fSubstituteToOverridden) { m_overriddenTD.Substituite( overriddenMD, overridingMD ); remap[overriddenMD] = overridingMD; fMigrateMethodImpl = true; } if(fRemoveOverriding) { m_overridingTD.RemoveMethod( overridingMD ); remap[overridingMD] = overriddenMD; } if(fMigrateMethodImpl) { MigrateMethodImpl( m_overriddenTD, m_overridingTD, overridingMD ); } } } //--// private void NotifyNewObjects( object from, object to ) { m_newObjectsForReverseIndex.Insert( to ); } private static CallOperator FindSuperConstructorCall( ControlFlowGraphStateForCodeTransformation cfg ) { var bb = cfg.NormalizedEntryBasicBlock; while(true) { Operator[] ops = bb.Operators; CallOperator call = ops[0] as CallOperator; if(call != null && call.TargetMethod is ConstructorMethodRepresentation) { return call; } var ctrl = bb.FlowControl as UnconditionalControlOperator; if(ctrl == null) { break; } bb = ctrl.TargetBranch; } throw TypeConsistencyErrorException.Create( "Cannot find call to constructor in '{0}'", cfg.Method ); } private static void MigrateMethodImpl( TypeRepresentation overriddenTD , TypeRepresentation overridingTD , MethodRepresentation overridingMD ) { foreach(MethodImplRepresentation mi in overridingTD.MethodImpls) { if(mi.Body == overridingMD) { overriddenTD.AddMethodImpl( new MethodImplRepresentation( overridingMD, mi.Declaration ) ); } } } //--// internal void ProcessDuplicates() { while(m_duplicates.Count > 0) { Duplicate[] duplicates = m_duplicates.ToArray(); m_duplicates.Clear(); foreach(Duplicate duplicate in duplicates) { object from = duplicate.From; object to = duplicate.To; if(m_typeSystem.ReachabilitySet.IsProhibited( from ) == false && m_typeSystem.ReachabilitySet.IsProhibited( to ) == false ) { if(Object.Equals( from, to )) { // // Types are kept in a list, which doesn't shrink when we process remaps. // We'll have to manually force an update. // if(from is TypeRepresentation) { var tdFrom = (TypeRepresentation)from; m_typeSystem.RemoveDuplicateType( tdFrom ); } // // Fields are kept in an array, which doesn't shrink when we process remaps. // We'll have to manually force an update. // if(from is FieldRepresentation) { var fdFrom = (FieldRepresentation)from; var fdTo = (FieldRepresentation)to; var td = fdFrom.OwnerType; if(ArrayUtility.FindReferenceInNotNullArray( td.Fields, fdFrom ) >= 0 && ArrayUtility.FindReferenceInNotNullArray( td.Fields, fdTo ) >= 0) { td.RemoveField( fdFrom ); } } // // Methods are kept in an array, which doesn't shrink when we process remaps. // We'll have to manually force an update. // if(from is MethodRepresentation) { var mdFrom = (MethodRepresentation)from; var mdTo = (MethodRepresentation)to; var td = mdFrom.OwnerType; if(ArrayUtility.FindReferenceInNotNullArray( td.Methods, mdFrom ) >= 0 && ArrayUtility.FindReferenceInNotNullArray( td.Methods, mdTo ) >= 0) { td.RemoveMethod( mdFrom ); } } ProcessRemap( from, to ); } } } } } private void ProcessRemaps( GrowOnlyHashTable< object, object > remap ) { object[] keys = remap.KeysToArray(); object[] values = remap.ValuesToArray(); for(int i = 0; i < keys.Length; i++) { #if TRACK_TIMING_LEVEL3 using(new ExecutionTiming( "Remap from {0} to {1} : {2}", keys[i], values[i], m_newObjectsForReverseIndex.Count )) #endif { ProcessRemap( keys[i], values[i] ); } } } private void ProcessRemap( object from , object to ) { m_replaceFrom = from; m_replaceTo = to; object[] arrayFrom = null; object[] arrayTo = null; if(m_reverseIndex.CanBeTracked( from ) == false) { throw TypeConsistencyErrorException.Create( "Got unexpected source object to remap: {0}", from ); } if(m_reverseIndex.CanBeTracked( to ) == false) { throw TypeConsistencyErrorException.Create( "Got unexpected destination object to remap: {0}", to ); } //// List< object[] > pre = null; //// //// { //// pre = CollectUsageContext.Execute( m_typeSystem, from ); //// } FlushNewObjects(); GrowOnlySet< object > setFrom = m_reverseIndex[from]; if(setFrom != null) { foreach(object context in setFrom) { m_activeContext = context; this.Reset(); object obj = context; Transform( ref obj ); } GrowOnlySet< object > setTo = m_reverseIndex[to]; if(setTo != null) { arrayFrom = setFrom.ToArray(); arrayTo = setTo.ToArray(); } m_reverseIndex.Merge( from, to ); } m_typeSystem.ProhibitUse( from ); //// if(pre != null) //// { //// List< object[] > post = CollectUsageContext.Execute( m_typeSystem, from ); //// } if(arrayTo != null) { GrowOnlySet< object > set = SetFactory.New< object >(); foreach(object obj in arrayTo) { CheckForDuplicates( obj, set ); } foreach(object obj in arrayFrom) { CheckForDuplicates( obj, set ); } } } private void FlushNewObjects() { if(m_newObjectsForReverseIndex.Count > 0) { foreach(object obj in m_newObjectsForReverseIndex) { #if TRACK_TIMING_LEVEL4 using(new ExecutionTiming( "Update for {0}", obj )) #endif { m_reverseIndex.Update( obj ); } } m_newObjectsForReverseIndex.Clear(); } } private void CheckForDuplicates( object obj , GrowOnlySet< object > set ) { object objOld; if(set.Contains( obj, out objOld ) == true) { if(Object.ReferenceEquals( obj, objOld ) == false) { m_duplicates.Add( new Duplicate( obj, objOld ) ); } } else { set.Insert( obj ); } } //--// protected override object ShouldSubstitute( object target , out SubstitutionAction result ) { object context = this.TopContext(); if(context == null) { result = SubstitutionAction.Unknown; return null; } if(Object.ReferenceEquals( context, m_activeContext )) { if(Object.ReferenceEquals( m_replaceFrom, target )) { result = SubstitutionAction.Substitute; return m_replaceTo; } else { result = SubstitutionAction.Unknown; return null; } } result = SubstitutionAction.Keep; return null; } } } ================================================ FILE: Zelig/Zelig/CompileTime/CodeGenerator/CodeTransformation/Transformations/ReduceNumberOfTemporaries.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // namespace Microsoft.Zelig.CodeGeneration.IR.Transformations { using System; using System.Diagnostics; using System.Collections.Generic; using Microsoft.Zelig.Runtime.TypeSystem; public class ReduceNumberOfTemporaries { // // State // private readonly ControlFlowGraphStateForCodeTransformation m_cfg; private VariableExpression[] m_variables; private VariableExpression.Property[] m_varProps; private Operator[] m_operators; private Operator[][] m_useChains; // Operator[][] private Operator[][] m_defChains; // Operator[][] // // Constructor Methods // private ReduceNumberOfTemporaries( ControlFlowGraphStateForCodeTransformation cfg ) { m_cfg = cfg; } // // Helper Methods // public static void Execute( ControlFlowGraphStateForCodeTransformation cfg ) { cfg.TraceToFile( "ReduceNumberOfTemporaries" ); using(new PerformanceCounters.ContextualTiming( cfg, "ReduceNumberOfTemporaries" )) { ReduceNumberOfTemporaries pThis = new ReduceNumberOfTemporaries( cfg ); while(pThis.ExecuteSteps() == true) { Transformations.RemoveDeadCode.Execute( cfg, true ); } } } private bool ExecuteSteps() { using(m_cfg.GroupLock( m_cfg.LockSpanningTree () , m_cfg.LockPropertiesOfVariables() , m_cfg.LockUseDefinitionChains () )) { m_variables = m_cfg.DataFlow_SpanningTree_Variables; m_operators = m_cfg.DataFlow_SpanningTree_Operators; m_useChains = m_cfg.DataFlow_UseChains; m_defChains = m_cfg.DataFlow_DefinitionChains; m_varProps = m_cfg.DataFlow_PropertiesOfVariables; if(PropagateTemporaries ()) return true; if(StrengthReduceForConditionalControlOperators()) return true; if(PropagateConstantToChecks ()) return true; return false; } } //--// private bool PropagateTemporaries() { bool fChanged = false; foreach (VariableExpression var in m_variables) { int idx = var.SpanningTreeIndex; // Only process temporary variables with a single definition. if (!(var is TemporaryVariableExpression) || (m_defChains[idx].Length != 1)) { continue; } Operator opDef = m_defChains[idx][0]; Operator[] opUses = m_useChains[idx]; // Skip variables with multiple uses. if (opUses.Length != 1) { continue; } Operator opUse = opUses[0]; // Skip variables that are defined and used across basic block boundaries. if (opUse.BasicBlock != opDef.BasicBlock) { continue; } int start = opDef.SpanningTreeIndex; int end = opUse.SpanningTreeIndex; Debug.Assert(start < end, "Variable used before being defined."); VariableExpression exDef = opDef.FirstResult; if (opDef is SingleAssignmentOperator) { // // Detect pattern: // // $Temp = // : $Temp // // Convert into: // // : // Expression exDefSrc = opDef.FirstArgument; if (!IsRedefinedInRange(exDefSrc, start, end) && opUse.CanPropagateCopy(exDef, exDefSrc) && exDef.Type.CanBeAssignedFrom(exDefSrc.Type, null)) { opUse.SubstituteUsage(exDef, exDefSrc); fChanged = true; } } else if (opDef is ZeroExtendOperator && opUse is BinaryConditionalControlOperator) { // // Detect pattern: // // $TempA = zeroextend bool from 8 bits // if $TempA != ZERO then goto BasicBlock(T) else goto BasicBlock(F) // // Convert into: // // if != ZERO then goto BasicBlock(T) else goto BasicBlock(F) // Expression exDefSrc = opDef.FirstArgument; if (!IsRedefinedInRange(exDefSrc, start, end)) { opDef.Delete(); opUse.SubstituteUsage(exDef, exDefSrc); fChanged = true; } } else if (opDef is CompareAndSetOperator && opUse is CompareAndSetOperator) { // // Detect pattern: // // $TempA = // $TempB = $TempA EQ.signed $Const(int 0) // // Convert into: // // $TempB = ! // CompareAndSetOperator opCmpDef = (CompareAndSetOperator)opDef; CompareAndSetOperator opCmpUse = (CompareAndSetOperator)opUse; if (opCmpUse.Condition == CompareAndSetOperator.ActionCondition.EQ) { opCmpUse.EnsureConstantToTheRight(); ConstantExpression exRight = opCmpUse.SecondArgument as ConstantExpression; if (exRight != null && exRight.IsEqualToZero()) { CompareAndSetOperator opNew = CompareAndSetOperator.New( opCmpDef.DebugInfo, opCmpDef.InvertedCondition, opCmpDef.Signed, opCmpUse.FirstResult, opCmpDef.FirstArgument, opCmpDef.SecondArgument); opUse.SubstituteWithOperator(opNew, Operator.SubstitutionFlags.Default); opDef.Delete(); fChanged = true; } } } } return fChanged; } private bool IsRedefinedInRange( Expression ex , int start , int end ) { VariableExpression var = ex as VariableExpression; if(var != null) { bool fAddressTaken = (m_varProps[ex.SpanningTreeIndex] & VariableExpression.Property.AddressTaken) != 0; for(int i = start + 1; i < end; i++) { Operator op = m_operators[i]; if(ArrayUtility.FindInNotNullArray( op.Results, var ) >= 0) { return true; } if(op.MayWriteThroughPointerOperands && fAddressTaken) { return true; } } } return false; } //--// private bool StrengthReduceForConditionalControlOperators() { bool fChanged = false; foreach(Operator op in m_operators) { BinaryConditionalControlOperator opCtrl = op as BinaryConditionalControlOperator; if(opCtrl != null) { Operator opPrev = opCtrl.GetPreviousOperator(); if(opPrev is SingleAssignmentOperator) { // // Detect pattern: // // = // if != ZERO then goto BasicBlock(T) else goto BasicBlock(T) // // Convert into: // // = // if != ZERO then goto BasicBlock(T) else goto BasicBlock(T) // VariableExpression exSrc = opPrev.FirstResult; Expression exDst = opCtrl.FirstArgument; if(exSrc == exDst) { opCtrl.SubstituteUsage( exDst, opPrev.FirstArgument ); fChanged = true; } } else if(opPrev is CompareAndSetOperator) { // // Detect pattern: // // = // if != ZERO then goto BasicBlock(T) else goto BasicBlock(T) // // Convert into: // // = // if then goto BasicBlock(T) else goto BasicBlock(T) // CompareAndSetOperator opPrevCmp = (CompareAndSetOperator)opPrev; VariableExpression exSrc = opPrevCmp.FirstResult; Expression exDst = opCtrl.FirstArgument; if(exSrc == exDst) { CompareConditionalControlOperator ctrl = CompareConditionalControlOperator.New( opPrevCmp.DebugInfo, opPrevCmp.Condition, opPrevCmp.Signed, opPrevCmp.FirstArgument, opPrevCmp.SecondArgument, opCtrl.TargetBranchNotTaken, opCtrl.TargetBranchTaken ); opCtrl.SubstituteWithOperator( ctrl, Operator.SubstitutionFlags.Default ); fChanged = true; } } } } return fChanged; } //--// private bool PropagateConstantToChecks() { bool fChanged = false; // // If a variable is only used in a BinaryConditionalControlOperator, // try to replicate the check close to all the definitions of the variable. // Some definitions could be constants and the checks will straighten out. // foreach(VariableExpression var in m_variables) { BinaryConditionalControlOperator op = ControlFlowGraphState.CheckSingleUse( m_useChains, var ) as BinaryConditionalControlOperator; if(op != null) { foreach(Operator def in m_defChains[var.SpanningTreeIndex]) { if(CanPropagate( def, op )) { ControlOperator opCtrl = null; if(def is SingleAssignmentOperator) { ConstantExpression exConst = def.FirstArgument as ConstantExpression; if(exConst != null && exConst.IsValueInteger) { opCtrl = UnconditionalControlOperator.New( op.DebugInfo, exConst.IsEqualToZero() ? op.TargetBranchNotTaken : op.TargetBranchTaken ); } } if(opCtrl == null) { opCtrl = BinaryConditionalControlOperator.New( op.DebugInfo, op.FirstArgument, op.TargetBranchNotTaken, op.TargetBranchTaken ); } def.BasicBlock.FlowControl.SubstituteWithOperator( opCtrl, Operator.SubstitutionFlags.Default ); fChanged = true; } } } } return fChanged; } private static bool CanPropagate( Operator def , BinaryConditionalControlOperator op ) { var defBB = def.BasicBlock; var opBB = op .BasicBlock; if(defBB == opBB) { return false; } if(!(defBB is NormalBasicBlock) || !(opBB is NormalBasicBlock) ) { return false; } def = def.GetNextOperator(); // // Make sure all the operators between 'def' and 'op' are either Nops or unconditional branches. // while(def != null) { if(def == op) { return true; } if(def is NopOperator) { def = def.GetNextOperator(); continue; } UnconditionalControlOperator ctrl = def as UnconditionalControlOperator; if(ctrl != null) { def = ctrl.TargetBranch.Operators[0]; continue; } break; } return false; } } } ================================================ FILE: Zelig/Zelig/CompileTime/CodeGenerator/CodeTransformation/Transformations/RemoveDeadCode.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // namespace Microsoft.Zelig.CodeGeneration.IR.Transformations { using System; using System.Collections.Generic; using Microsoft.Zelig.Runtime.TypeSystem; public static class RemoveDeadCode { // // Helper Methods // public static bool Execute( ControlFlowGraphStateForCodeTransformation cfg , bool fLookForDeadAssignments ) { cfg.TraceToFile( "RemoveDeadCode" ); using(new PerformanceCounters.ContextualTiming( cfg, "RemoveDeadCode" )) { bool fModified = false; while(true) { VariableExpression[] vars = cfg.DataFlow_SpanningTree_Variables; VariableExpression.Property[] varProp = cfg.DataFlow_PropertiesOfVariables; Operator[] operators = cfg.DataFlow_SpanningTree_Operators; Operator[][] defChains = cfg.DataFlow_DefinitionChains; Operator[][] useChains = cfg.DataFlow_UseChains; Abstractions.Platform pa = cfg.TypeSystem.PlatformAbstraction; Abstractions.RegisterDescriptor[] registers = pa.GetRegisters(); bool[] unneededVars = new bool[vars.Length]; bool fDone = true; for(int i = 0; i < vars.Length; i++) { VariableExpression.Property prop = varProp[i]; if((prop & VariableExpression.Property.PhysicalRegister) != 0) { PhysicalRegisterExpression reg = (PhysicalRegisterExpression)vars[i].AliasedVariable; if(registers[ reg.Number ].IsSpecial) { continue; } } { VariableExpression var = vars[i]; bool fKeep = false; if(ShouldKeep( cfg, var, defChains, useChains )) { fKeep = true; } else if(var.AliasedVariable is StackLocationExpression) { // // Check if the variable is a fragment of an aggregate type, keep it around if any of the fragments are used. // StackLocationExpression stackVar = (StackLocationExpression)var.AliasedVariable; foreach(VariableExpression var2 in vars) { StackLocationExpression stackVar2 = var2.AliasedVariable as StackLocationExpression; if(stackVar2 != null && stackVar.SourceVariable == stackVar2.SourceVariable) { if(useChains[var2.SpanningTreeIndex].Length > 0) { fKeep = true; break; } } } } if(fKeep == false) { CHECKS.ASSERT( (prop & VariableExpression.Property.AddressTaken) == 0, "Variable {0} cannot be unused and its address taken", vars[i] ); unneededVars[i] = true; } } } // // Only remove an operator if ALL the results are dead. // foreach(var op in operators) { if(op.HasAnnotation< DontRemoveAnnotation >() == false) { bool fDelete = false; foreach(var lhs in op.Results) { if(unneededVars[lhs.SpanningTreeIndex]) { fDelete = true; } else { fDelete = false; break; } } if(fDelete) { op.Delete(); fDone = false; } } } // // Refresh the u/d chains. // if(fDone == false) { varProp = cfg.DataFlow_PropertiesOfVariables; operators = cfg.DataFlow_SpanningTree_Operators; defChains = cfg.DataFlow_DefinitionChains; useChains = cfg.DataFlow_UseChains; } // // Get rid of all the operators that do nothing, evaluate constant operations, etc. // BitVector[] livenessMap = fLookForDeadAssignments ? cfg.DataFlow_LivenessAtOperator : null; // It's indexed as [][] foreach(Operator op in operators) { if(op.PerformsNoActions) { op.Delete(); fDone = false; continue; } op.EnsureConstantToTheRight(); if(op.Simplify( defChains, useChains, varProp )) { fDone = false; continue; } if(fLookForDeadAssignments) { // // All the variables have to be initialized with their default values, // but most of the times these assignments are overwritten by other assignments. // Look for these pattern and remove the duplicate code. // if(op is SingleAssignmentOperator && op.HasAnnotation< InvalidationAnnotation >() == false) { int idxVar = op.FirstResult.SpanningTreeIndex; if((varProp[idxVar] & VariableExpression.Property.AddressTaken) == 0) { int idxOp = op.SpanningTreeIndex; if(livenessMap[idxOp+1][idxVar] == false) { // // The variable is dead at the next operator, thus it's a useless assignment. // op.Delete(); fDone = false; continue; } } } } } if(fDone) { break; } fModified = true; } return fModified; } } private static bool ShouldKeep( ControlFlowGraphStateForCodeTransformation cfg , VariableExpression var , Operator[][] defChains , Operator[][] useChains ) { if(ShouldKeep( var, defChains, useChains )) { return true; } Expression[] fragments = cfg.GetFragmentsForExpression( var ); if(fragments != null) { foreach(Expression ex in fragments) { if(ShouldKeep( ex, defChains, useChains )) { return true; } } } return false; } private static bool ShouldKeep( Expression var , Operator[][] defChains , Operator[][] useChains ) { if(useChains[var.SpanningTreeIndex].Length > 0) { return true; } foreach(Operator op in defChains[var.SpanningTreeIndex]) { if(op.ShouldNotBeRemoved || op.MayMutateExistingStorage || op.MayThrow ) { return true; } foreach(var an in op.FilterAnnotations< InvalidationAnnotation >()) { if(useChains[an.Target.SpanningTreeIndex].Length > 0) { return true; } } } return false; } } } ================================================ FILE: Zelig/Zelig/CompileTime/CodeGenerator/CodeTransformation/Transformations/RemoveSimpleIndirections.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // namespace Microsoft.Zelig.CodeGeneration.IR.Transformations { using System; using System.Collections.Generic; using Microsoft.Zelig.Runtime.TypeSystem; public static class RemoveSimpleIndirections { // // Helper Methods // public static bool Execute( ControlFlowGraphStateForCodeTransformation cfg ) { cfg.TraceToFile( "RemoveSimpleIndirections" ); using(new PerformanceCounters.ContextualTiming( cfg, "RemoveSimpleIndirections" )) { Operator[][] defChains = cfg.DataFlow_DefinitionChains; Operator[][] useChains = cfg.DataFlow_UseChains; bool fModified = false; foreach(var opDef in cfg.FilterOperators< AddressAssignmentOperator >()) { VariableExpression src = opDef.FirstArgument as VariableExpression; VariableExpression ptr = opDef.FirstResult; if(src != null && ControlFlowGraphState.CheckSingleDefinition( defChains, ptr ) != null) { // // Digest local indirections. // foreach(Operator opUse in useChains[ptr.SpanningTreeIndex]) { IndirectOperator opUseInd = opUse as IndirectOperator; if(opUseInd != null && opUseInd.Offset == 0) { if(opUseInd is StoreIndirectOperator) { if(CanReplace( opUseInd, opUseInd.FirstArgument, ptr, (VariableExpression)src, opUseInd.SecondArgument )) { Operator op = SingleAssignmentOperator.New( opUseInd.DebugInfo, (VariableExpression)src, opUseInd.SecondArgument ); opUseInd.SubstituteWithOperator( op, Operator.SubstitutionFlags.Default ); fModified = true; } } else if(opUseInd is LoadIndirectOperator) { if(CanReplace( opUseInd, opUseInd.FirstArgument, ptr, opUseInd.FirstResult, src )) { Operator op = SingleAssignmentOperator.New( opUseInd.DebugInfo, opUseInd.FirstResult, src ); opUseInd.SubstituteWithOperator( op, Operator.SubstitutionFlags.Default ); fModified = true; } } } } } } return fModified; } } private static bool CanReplace( IndirectOperator op , Expression ptrUse , Expression ptrSrc , Expression target , Expression origin ) { FieldRepresentation[] fdPath = op.AccessPath; if(fdPath != null) { TypeRepresentation tdTarget = target.Type; TypeRepresentation tdOrigin = origin.Type; if(tdTarget.ValidLayout && tdOrigin.ValidLayout ) { if(tdTarget.SizeOfHoldingVariable == tdOrigin.SizeOfHoldingVariable) { return true; } } return false; } else { return ptrUse == ptrSrc; } } } } ================================================ FILE: Zelig/Zelig/CompileTime/CodeGenerator/CodeTransformation/Transformations/SimplifyConditionCodeChecks.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // namespace Microsoft.Zelig.CodeGeneration.IR.Transformations { using System; using System.Collections.Generic; using Microsoft.Zelig.Runtime.TypeSystem; public class SimplifyConditionCodeChecks { // // State // private readonly ControlFlowGraphStateForCodeTransformation m_cfg; private readonly BasicBlock[] m_basicBlocks; // All the basic blocks, in spanning tree order. private readonly Operator[] m_operators; // All the operators, in spanning tree order. private readonly VariableExpression[] m_variables; // All the variables, in spanning tree order. private readonly int m_bbNum; private readonly int m_opsNum; private readonly int m_varNum; private readonly Operator[][] m_variableUses; // It's indexed as Operator[][] private readonly Operator[][] m_variableDefinitions; // It's indexed as Operator[][] private readonly Operator[] m_covered; // All the operators reached during processing, in spanning tree order. // // Constructor Methods // private SimplifyConditionCodeChecks( ControlFlowGraphStateForCodeTransformation cfg ) { m_cfg = cfg; m_basicBlocks = cfg.DataFlow_SpanningTree_BasicBlocks; m_operators = cfg.DataFlow_SpanningTree_Operators; m_variables = cfg.DataFlow_SpanningTree_Variables; m_bbNum = m_basicBlocks.Length; m_opsNum = m_operators.Length; m_varNum = m_variables.Length; m_variableUses = cfg.DataFlow_UseChains; m_variableDefinitions = cfg.DataFlow_DefinitionChains; m_covered = new Operator[m_operators.Length]; } // // Helper Methods // public static bool Execute( ControlFlowGraphStateForCodeTransformation cfg ) { cfg.TraceToFile( "SimplifyConditionCodeChecks" ); using(new PerformanceCounters.ContextualTiming( cfg, "SimplifyConditionCodeChecks" )) { SimplifyConditionCodeChecks sccc = new SimplifyConditionCodeChecks( cfg ); return sccc.Apply(); } } public bool Apply() { bool fModified = false; for(int opIdx = 0; opIdx < m_opsNum; opIdx++) { // // We are looking for patterns that can be compressed. // // For example: // // = set if $CC is || = address of // [ ] = zeroextend [] ] // $CC = compare <-> $Const(int 0) // if $CC is then goto $Label_3 else goto $Label_2 // // If $CC is defined only there, we can change $CC with $CC, after we adjust the condition. // ConditionCodeConditionalControlOperator opY = m_operators[opIdx] as ConditionCodeConditionalControlOperator; if(opY != null) { Operator def = GetSingleDef( opY.FirstArgument ); fModified |= ProcessSingleDefinition( opY, def, false, 64 ); } } return fModified; } private bool ProcessSingleDefinition( ConditionCodeConditionalControlOperator opY , Operator def , bool fNegate , uint validBits ) { if(def == null) { return false; } if(m_covered[def.SpanningTreeIndex] != null) { // // Break loops. // return false; } bool fModified = false; int idx = def.SpanningTreeIndex; m_covered[idx] = def; if(def is SingleAssignmentOperator) { fModified = ProcessSingleAssignmentOperator( opY, (SingleAssignmentOperator)def, fNegate, validBits ); } else if(def is ZeroExtendOperator) { fModified = ProcessZeroExtendOperator( opY, (ZeroExtendOperator)def, fNegate, validBits ); } else if(def is PhiOperator) { fModified = ProcessPhiOperator( opY, (PhiOperator)def, fNegate, validBits ); } else if(def is CompareOperator) { fModified = ProcessCompareOperator( opY, (CompareOperator)def, fNegate, validBits ); } else if(def is LongCompareOperator) { fModified = ProcessLongCompareOperator( opY, (LongCompareOperator)def, fNegate, validBits ); } else if(def is SetIfConditionIsTrueOperator) { fModified = ProcessSetIfConditionIsTrueOperator( opY, (SetIfConditionIsTrueOperator)def, fNegate, validBits ); } else if(def is AddressAssignmentOperator) { fModified = ProcessAddressAssignmentOperator( opY, (AddressAssignmentOperator)def, fNegate, validBits ); } m_covered[idx] = null; return fModified; } private bool ProcessSingleAssignmentOperator( ConditionCodeConditionalControlOperator opY , SingleAssignmentOperator assignDef , bool fNegate , uint validBits ) { Expression assignSrc = assignDef.FirstArgument; if(assignSrc is ConstantExpression) { ConstantExpression exConst = (ConstantExpression)assignSrc; if(exConst.IsValueInteger || exConst.IsValueFloatingPoint ) { bool fSubstitute = false; bool fTaken = false; bool fZero = exConst.IsEqualToZero(); switch(opY.Condition) { case ConditionCodeExpression.Comparison.Equal: fSubstitute = true; fTaken = fZero == fNegate; break; case ConditionCodeExpression.Comparison.NotEqual: fSubstitute = true; fTaken = fZero != fNegate; break; } if(fSubstitute) { UnconditionalControlOperator opNew; BasicBlock branch; if(fTaken) { branch = opY.TargetBranchTaken; } else { branch = opY.TargetBranchNotTaken; } opNew = UnconditionalControlOperator.New( opY.DebugInfo, branch ); opY.SubstituteWithOperator( opNew, Operator.SubstitutionFlags.Default ); return true; } } return false; } else { Operator def = GetSingleDef( assignSrc ); return ProcessSingleDefinition( opY, def, fNegate, validBits ); } } private bool ProcessZeroExtendOperator( ConditionCodeConditionalControlOperator opY , ZeroExtendOperator extendDef , bool fNegate , uint validBits ) { Expression extendSrc = extendDef.FirstArgument; Operator def = GetSingleDef( extendSrc ); return ProcessSingleDefinition( opY, def, fNegate, extendDef.SignificantSize ); } private bool ProcessPhiOperator( ConditionCodeConditionalControlOperator opY , PhiOperator phiDef , bool fNegate , uint validBits ) { Expression[] rhs = phiDef.Arguments; BasicBlock[] origins = phiDef.Origins; for(int idx = 0; idx < rhs.Length; idx++) { VariableExpression var = (VariableExpression)rhs[idx]; Operator varDef = GetSingleDef( var ); if(varDef is SingleAssignmentOperator) { ConstantExpression exConst = varDef.FirstArgument as ConstantExpression; if(exConst != null) { bool fSourceIsZero = exConst.IsEqualToZero(); bool fSubstitute = false; bool fCompareToZero = false; switch(opY.Condition) { case ConditionCodeExpression.Comparison.Equal: fSubstitute = true; fCompareToZero = fNegate; break; case ConditionCodeExpression.Comparison.NotEqual: fSubstitute = true; fCompareToZero = !fNegate; break; } if(fSubstitute) { UnconditionalControlOperator ctrl = varDef.BasicBlock.FlowControl as UnconditionalControlOperator; if(ctrl != null) { // // For now, we only handle the case of a single phi operator per basic block. // foreach(Operator op in phiDef.BasicBlock.Operators) { PhiOperator phiOp = op as PhiOperator; if(phiOp != null && phiOp != phiDef) { fSubstitute = false; } } if(fSubstitute) { // // We detect that one branch coming in into the conditional is always zero or false. // // We'd like to short-circuit the origin of the conditional input to its destination, // but we have to make sure that all the results in the trace to the conditional // are dead after the conditional. // Operator start = m_operators[varDef.SpanningTreeIndex+1]; bool fContinue = true; while(fContinue) { ControlOperator endCtrl = start.BasicBlock.FlowControl; int idxStart = start .SpanningTreeIndex; int idxEnd = endCtrl.SpanningTreeIndex; while(idxStart < idxEnd) { Operator op = m_covered[idxStart]; if(op == null || op.Results.Length == 0 || m_variableUses[op.FirstResult.SpanningTreeIndex].Length != 1 ) { // // There's an operator that was not involved in the computation of the conditional, // or its result are used also outside the conditional, // we cannot prove that the short-circuit is safe. // fContinue = false; fSubstitute = false; break; } idxStart++; if(idxStart == opY.SpanningTreeIndex) { fContinue = false; break; } } if(fContinue) { UnconditionalControlOperator endCtrl2 = endCtrl as UnconditionalControlOperator; if(endCtrl2 == null) { // // Multiple destinations, we cannot prove that the short-circuit is safe. // fContinue = false; fSubstitute = false; break; } start = endCtrl2.TargetBranch.Operators[0]; } } } if(fSubstitute) { BasicBlock branch; if(fSourceIsZero == fCompareToZero) { branch = opY.TargetBranchTaken; } else { branch = opY.TargetBranchNotTaken; } phiDef.RemoveEffect( ctrl.BasicBlock ); ctrl.SubstituteWithOperator( UnconditionalControlOperator.New( ctrl.DebugInfo, branch ), Operator.SubstitutionFlags.Default ); } } } } } } if(phiDef.Arguments.Length == 1) { SingleAssignmentOperator opNew = SingleAssignmentOperator.New( phiDef.DebugInfo, phiDef.FirstResult, phiDef.FirstArgument ); var opTarget = phiDef.BasicBlock.GetFirstDifferentOperator( typeof( PhiOperator ) ); opTarget.AddOperatorBefore( opNew ); phiDef.Delete(); return true; } return false; } private bool ProcessCompareOperator( ConditionCodeConditionalControlOperator opY , CompareOperator cmpDef , bool fNegate , uint validBits ) { bool fNullOnRight; Expression target = cmpDef.IsBinaryOperationAgainstZeroValue( out fNullOnRight ); if(target is ConstantExpression) { bool fSubstitute = false; bool fTaken = false; bool fZero = target.IsEqualToZero(); switch(opY.Condition) { case ConditionCodeExpression.Comparison.Equal: fSubstitute = true; fTaken = fZero != fNegate; break; case ConditionCodeExpression.Comparison.NotEqual: fSubstitute = true; fTaken = fZero == fNegate; break; } if(fSubstitute) { UnconditionalControlOperator opNew; BasicBlock branch; if(fTaken) { branch = opY.TargetBranchTaken; } else { branch = opY.TargetBranchNotTaken; } opNew = UnconditionalControlOperator.New( opY.DebugInfo, branch ); opY.SubstituteWithOperator( opNew, Operator.SubstitutionFlags.Default ); return true; } } /* // TODO: revisit this later and perform this optimzation only when appropriate (when only one conditional is used per block // and the target for the conditional is in the same block). // // This does not always work. If there are multiple conditionals initialized before they are referenced, then only the last // conditional value will be used. In this case we need to store the conditional value in a register. else if(target is VariableExpression) { Operator targetDef = GetSingleDef( (VariableExpression)target ); return ProcessSingleDefinition( opY, targetDef, !fNegate, target.Type.Size ); } */ return false; } private bool ProcessLongCompareOperator( ConditionCodeConditionalControlOperator opY , LongCompareOperator cmpDef , bool fNegate , uint validBits ) { bool fNullOnRight; Expression[] target = cmpDef.IsCompareToNull( out fNullOnRight ); if(target != null) { if(target[0] is ConstantExpression && target[1] is ConstantExpression ) { bool fSubstitute = false; bool fTaken = false; bool fZero = target[0].IsEqualToZero() && target[1].IsEqualToZero(); switch(opY.Condition) { case ConditionCodeExpression.Comparison.Equal: fSubstitute = true; fTaken = fZero != fNegate; break; case ConditionCodeExpression.Comparison.NotEqual: fSubstitute = true; fTaken = fZero == fNegate; break; } if(fSubstitute) { UnconditionalControlOperator opNew; BasicBlock branch; if(fTaken) { branch = opY.TargetBranchTaken; } else { branch = opY.TargetBranchNotTaken; } opNew = UnconditionalControlOperator.New( opY.DebugInfo, branch ); opY.SubstituteWithOperator( opNew, Operator.SubstitutionFlags.Default ); return true; } } else if(target[0] is VariableExpression && target[1] is VariableExpression) { // // TODO: Not sure how to propagate through two variables at the same time... // //// Operator targetDefLo = GetSingleDef( (VariableExpression)target[0] ); //// Operator targetDefHi = GetSingleDef( (VariableExpression)target[1] ); //// //// return ProcessSingleDefinition( opY, targetDef, !fNegate, target.Type.Size ); } } return false; } private bool ProcessSetIfConditionIsTrueOperator( ConditionCodeConditionalControlOperator opY , SetIfConditionIsTrueOperator setOp , bool fNegate , uint validBits ) { bool fSubstitute = false; bool fTaken = false; switch(opY.Condition) { case ConditionCodeExpression.Comparison.Equal: fSubstitute = true; fTaken = !fNegate; break; case ConditionCodeExpression.Comparison.NotEqual: fSubstitute = true; fTaken = fNegate; break; } if(fSubstitute) { ConditionCodeConditionalControlOperator opNew; BasicBlock branchTaken; BasicBlock branchNotTaken; if(fTaken) { branchTaken = opY.TargetBranchTaken; branchNotTaken = opY.TargetBranchNotTaken; } else { branchTaken = opY.TargetBranchNotTaken; branchNotTaken = opY.TargetBranchTaken; } opNew = ConditionCodeConditionalControlOperator.New( opY.DebugInfo, setOp.Condition, (VariableExpression)setOp.FirstArgument, branchNotTaken, branchTaken ); opY.SubstituteWithOperator( opNew, Operator.SubstitutionFlags.Default ); return true; } return false; } private bool ProcessAddressAssignmentOperator( ConditionCodeConditionalControlOperator opY , AddressAssignmentOperator addrDef , bool fNegate , uint validBits ) { // // So can never be zero. // bool fSubstitute = false; bool fTaken = false; switch(opY.Condition) { case ConditionCodeExpression.Comparison.Equal: fSubstitute = true; fTaken = !fNegate; break; case ConditionCodeExpression.Comparison.NotEqual: fSubstitute = true; fTaken = fNegate; break; } if(fSubstitute) { UnconditionalControlOperator opNew; BasicBlock branch; if(fTaken) { branch = opY.TargetBranchTaken; } else { branch = opY.TargetBranchNotTaken; } opNew = UnconditionalControlOperator.New( opY.DebugInfo, branch ); opY.SubstituteWithOperator( opNew, Operator.SubstitutionFlags.Default ); return true; } return false; } private Operator GetSingleDef( Expression ex ) { if(ex is VariableExpression) { Operator def = ControlFlowGraphState.CheckSingleDefinition( m_variableDefinitions, (VariableExpression)ex ); if(def != null) { // // Is it still in the graph? // if(def.BasicBlock != null) { return def; } } } return null; } } } ================================================ FILE: Zelig/Zelig/CompileTime/CodeGenerator/CodeTransformation/Transformations/SplitBasicBlocksAtExceptionSites.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // namespace Microsoft.Zelig.CodeGeneration.IR.Transformations { using System; using System.Collections.Generic; using Microsoft.Zelig.Runtime.TypeSystem; public static class SplitBasicBlocksAtExceptionSites { // // Helper Methods // public static bool Execute( ControlFlowGraphStateForCodeTransformation cfg ) { cfg.TraceToFile( "SplitBasicBlocksAtExceptionSites" ); using(new PerformanceCounters.ContextualTiming( cfg, "SplitBasicBlocksAtExceptionSites" )) { Queue< BasicBlock > pending = new Queue< BasicBlock >(); bool fModified = false; foreach(BasicBlock bb in cfg.DataFlow_SpanningTree_BasicBlocks) { pending.Enqueue( bb ); } while(pending.Count > 0) { BasicBlock bb = pending.Dequeue(); if(bb.ProtectedBy.Length > 0) { bool fFirst = true; foreach(Operator op in bb.Operators) { if(fFirst) { fFirst = false; } else if(op.MayThrow) { if(op is ThrowControlOperator || op is RethrowControlOperator || op is EndFinallyControlOperator ) { // Nothing to do, these operators throw an exception, they don't cause an exception. } else { BasicBlock split = op.BasicBlock.SplitAtOperator( op, false, true ); pending.Enqueue( split ); fModified = true; break; } } } } } // Another precondition for converting to SSA is that we cannot put a phi operator on an exception basic block. // This means that exception basic blocks should be immediately dominated by the block they protect. // // => only one basic block can be protected by an exception handler. // // Let's split them up! // // Note: LLVM allows phi operators in exception handling blocks, so we exclude this step. if (cfg.TypeSystem.PlatformAbstraction.CodeGenerator != TargetModel.ArmProcessor.InstructionSetVersion.CodeGenerator_LLVM) { while (true) { bool fDone = true; foreach (BasicBlock bb in cfg.DataFlow_SpanningTree_BasicBlocks) { ExceptionHandlerBasicBlock ehBB = bb as ExceptionHandlerBasicBlock; if (ehBB != null && ehBB.Predecessors.Length > 1) { CHECKS.ASSERT(ehBB.Successors.Length - ehBB.ProtectedBy.Length == 1, "Unexpected exception basic block with more than one successor: {0}", ehBB); BasicBlock bbNext = ehBB.FirstSuccessor; foreach (BasicBlockEdge edge in ehBB.Predecessors) { ExceptionHandlerBasicBlock ehBBNew = (ExceptionHandlerBasicBlock)CloneSingleBasicBlock.Execute(ehBB); edge.Predecessor.SubstituteProtectedBy(ehBB, ehBBNew); } fDone = false; break; } } if (fDone) { break; } } } return fModified; } } } } ================================================ FILE: Zelig/Zelig/CompileTime/CodeGenerator/CodeTransformation/Transformations/StaticSingleAssignmentForm.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // namespace Microsoft.Zelig.CodeGeneration.IR.Transformations { using System; using System.Collections.Generic; using Microsoft.Zelig.Runtime.TypeSystem; public static class StaticSingleAssignmentForm { // // State // // // Constructor Methods // // // Helper Methods // public static bool ShouldTransformInto( ControlFlowGraphStateForCodeTransformation cfg ) { return ComputeCandidatesForTransformIntoSSA( cfg ) != null; } //--// public static void RemovePiOperators( ControlFlowGraphStateForCodeTransformation cfg ) { cfg.TraceToFile( "RemovePiOperators-Pre" ); foreach(var op in cfg.FilterOperators< PiOperator >()) { var opNew = SingleAssignmentOperator.New( op.DebugInfo, op.FirstResult, op.FirstArgument ); op.SubstituteWithOperator( opNew, Operator.SubstitutionFlags.Default ); } cfg.TraceToFile( "RemovePiOperators-Post" ); } public static void InsertPiOperators( ControlFlowGraphStateForCodeTransformation cfg ) { cfg.TraceToFile( "InsertPiOperators-Pre" ); TypeSystemForCodeTransformation ts = cfg.TypeSystem; foreach(var op in cfg.FilterOperators< ConditionCodeConditionalControlOperator >()) { InsertPiOperators( ts, op ); } cfg.TraceToFile( "InsertPiOperators-Post" ); } private static void InsertPiOperators( TypeSystemForCodeTransformation ts , ConditionCodeConditionalControlOperator flowOp ) { PiOperator.Relation relation = PiOperator.ConvertRelation( flowOp.Condition ); if(relation != PiOperator.Relation.Invalid) { CompareOperator cmpOp = flowOp.GetPreviousOperator() as CompareOperator; if(cmpOp != null && cmpOp.FirstResult == flowOp.FirstArgument) { Expression exLeft = cmpOp.FirstArgument; Expression exRight = cmpOp.SecondArgument; // // Generate the constraints for the "comparison is true" branch. // AddPiOperator( flowOp, flowOp.TargetBranchTaken, exLeft , exLeft, exRight, relation ); AddPiOperator( flowOp, flowOp.TargetBranchTaken, exRight, exLeft, exRight, relation ); // // Generate the constraints for the "comparison is false" branch. // relation = PiOperator.NegateRelation( relation ); AddPiOperator( flowOp, flowOp.TargetBranchNotTaken, exLeft , exLeft, exRight, relation ); AddPiOperator( flowOp, flowOp.TargetBranchNotTaken, exRight, exLeft, exRight, relation ); } } } private static void AddPiOperator( Operator opSrc , BasicBlock bbDst , Expression ex , Expression cmpLeft , Expression cmpRight , PiOperator.Relation cmpRelation ) { VariableExpression var = ex as VariableExpression; if(var != null) { // // Make sure that we put the Pi operator in a basic block immediately dominated by the location of the comparison. // if(bbDst.Predecessors.Length > 1) { bbDst = opSrc.BasicBlock.InsertNewSuccessor( bbDst ); } var opDst = FirstOperatorAfterPiOperators( bbDst, var ); if(opDst != null) { PiOperator opNew = PiOperator.New( opSrc.DebugInfo, var, var, cmpLeft, cmpRight, cmpRelation ); opDst.AddOperatorBefore( opNew ); } } } private static Operator FirstOperatorAfterPiOperators( BasicBlock bb , VariableExpression var ) { foreach(Operator op in bb.Operators) { if(var == null) { return op; } var pi = op as PiOperator; if(pi == null) { return op; } if(pi.FirstArgument == var) { var = null; // Return the next operator. } } throw TypeConsistencyErrorException.Create( "Cannot find non-PI operator in {0}", bb ); } //--// private static bool[] ComputeCandidatesForTransformIntoSSA( ControlFlowGraphStateForCodeTransformation cfg ) { using(new PerformanceCounters.ContextualTiming( cfg, "ComputeCandidatesForTransformIntoSSA" )) { Operator[][] defChains = cfg.DataFlow_DefinitionChains; BitVector[] liveness = cfg.DataFlow_LivenessAtBasicBlockEntry; int varNum = defChains.Length; // // Are we already in SSA form? // // We need to convert into SSA form only if: // 1) A variable is defined twice or more. // 2) A variable is defined once and it's an argument. // bool[] candidate = new bool[varNum]; bool fShouldProcess = false; for(int varIdx = 0; varIdx < varNum; varIdx++) { Operator[] defs = defChains[varIdx]; if(defs.Length > 1) { candidate[varIdx] = true; fShouldProcess = true; } } return fShouldProcess ? candidate : null; } } public static bool ConvertInto( ControlFlowGraphStateForCodeTransformation cfg ) { using(new PerformanceCounters.ContextualTiming( cfg, "ConvertIntoSSA" )) { cfg.TraceToFile( "ConvertInto-Pre" ); // // To properly capture the dependencies between variables and exception handlers, // we need to create a basic block boundary at each exception site. // SplitBasicBlocksAtExceptionSites.Execute( cfg ); using(cfg.GroupLock( cfg.LockSpanningTree () , cfg.LockUseDefinitionChains() , cfg.LockLiveness () )) { bool[] candidate = ComputeCandidatesForTransformIntoSSA( cfg ); if(candidate == null) { return false; } cfg.TraceToFile( "ConvertInto-Entry" ); using(cfg.LockDominance()) { VariableExpression[] variables = cfg.DataFlow_SpanningTree_Variables; Operator[][] defChains = cfg.DataFlow_DefinitionChains; BitVector[] liveness = cfg.DataFlow_LivenessAtBasicBlockEntry; int varNum = variables.Length; GrowOnlySet< Operator > newPhis = SetFactory.NewWithReferenceEquality< Operator >(); // // Compute Iterated Dominance Frontier for each variable assigned. // BasicBlock[] basicBlocks = cfg.DataFlow_SpanningTree_BasicBlocks; BasicBlock[] immediateDominators = cfg.DataFlow_ImmediateDominators; BitVector[] dominanceFrontier = cfg.DataFlow_DominanceFrontier; int bbNum = basicBlocks.Length; Operator[] phiInsertionOps = new Operator[bbNum]; // // Insert Phi-operators. // BitVector vec = new BitVector( bbNum ); BitVector vecDF_N = new BitVector( bbNum ); BitVector vecDF_Nplus1 = new BitVector( bbNum ); for(int varIdx = 0; varIdx < varNum; varIdx++) { if(candidate[varIdx]) { VariableExpression var = variables[varIdx]; Operator[] defs = defChains[varIdx]; vec.ClearAll(); // // Build S // foreach(Operator op in defs) { vec.Set( op.BasicBlock.SpanningTreeIndex ); } if(vec.Cardinality > 1) { // // Compute DF^1(S) // vecDF_N.ClearAll(); foreach(int bbIdx in vec) { vecDF_N.OrInPlace( dominanceFrontier[bbIdx] ); } // // Build DF+(S), by computing DF^(N+1)(S) = DF(S union DF^N(S)). // while(true) { vecDF_Nplus1.ClearAll(); // // DF(S) // foreach(int bbIdx in vec) { vecDF_Nplus1.OrInPlace( dominanceFrontier[bbIdx] ); } // // DF(DF^N(S)) // foreach(int bbIdx in vecDF_N) { vecDF_Nplus1.OrInPlace( dominanceFrontier[bbIdx] ); } if(vecDF_Nplus1 == vecDF_N) { break; } vecDF_N.Assign( vecDF_Nplus1 ); } // // For each node in DF+(S), where is live at entry, add a phi operator. // foreach(int bbIdx in vecDF_N) { if(liveness[bbIdx][varIdx]) { PhiOperator phiOp = PhiOperator.New( null, var ); newPhis.Insert( phiOp ); var phiInsertionOp = phiInsertionOps[bbIdx]; if(phiInsertionOp == null) { phiInsertionOp = basicBlocks[bbIdx].GetFirstDifferentOperator( typeof(PhiOperator) ); phiInsertionOps[bbIdx] = phiInsertionOp; } phiInsertionOp.AddOperatorBefore( phiOp ); } } } } } // // Rename variables. // using(new PerformanceCounters.ContextualTiming( cfg, "ProcessInDominatorTreeOrder" )) { ProcessInDominatorTreeOrder( cfg, basicBlocks, immediateDominators, variables, candidate, newPhis ); } } } #if DEBUG foreach(Operator[] defChainPost in cfg.DataFlow_DefinitionChains) { CHECKS.ASSERT( defChainPost.Length <= 1, "Found a variable still defined multiple times after SSA conversion" ); } #endif cfg.TraceToFile( "ConvertInto-Post" ); PurgeUselessPhiOperators( cfg ); cfg.TraceToFile( "ConvertInto-PostPurge" ); while(Transformations.SimplifyConditionCodeChecks.Execute( cfg )) { Transformations.RemoveDeadCode.Execute( cfg, false ); } while(Transformations.CommonMethodRedundancyElimination.Execute( cfg )) { } cfg.DropDeadVariables(); cfg.TraceToFile( "ConvertInto-Done" ); return true; } } private static void PurgeUselessPhiOperators( ControlFlowGraphStateForCodeTransformation cfg ) { Operator[] operators = cfg.DataFlow_SpanningTree_Operators; VariableExpression[] variables = cfg.DataFlow_SpanningTree_Variables; VariableExpression[] variablesMap = new VariableExpression[variables.Length]; bool fLoop = true; bool fGot = false; // // In 'variablesMap', collect all the variables that are assigned through an identity phi operator. // while(fLoop) { fLoop = false; foreach(Operator op in operators) { if(op is PhiOperator) { VariableExpression lhs = op.FirstResult; if(variablesMap[lhs.SpanningTreeIndex] == null) { VariableExpression var = null; foreach(Expression ex in op.Arguments) { VariableExpression rhs = ex as VariableExpression; if(rhs != null) { VariableExpression rhsMapped = variablesMap[rhs.SpanningTreeIndex]; if(rhsMapped != null) { rhs = rhsMapped; } if(var == null) { var = rhs; } else if(var != rhs) { var = null; break; } } } if(var != null) { // // If other variables were mapped to 'lhs', update the mapping. // for(int varIdx = variablesMap.Length; --varIdx >= 0;) { if(variablesMap[varIdx] == lhs) { variablesMap[varIdx] = var; } } variablesMap[lhs.SpanningTreeIndex] = var; fLoop = true; fGot = true; } } } } } if(fGot) { // // We found some nilpotent phi operators, let's get rid of them. // This reduces the number of variables we need to track. // foreach(Operator op in operators) { if(op is PhiOperator) { VariableExpression lhs = op.FirstResult; if(lhs != null && variablesMap[lhs.SpanningTreeIndex] != null) { op.Delete(); } else { foreach(Expression ex in op.Arguments) { var rhs = ex as VariableExpression; if(rhs != null) { VariableExpression rhsMapped = variablesMap[rhs.SpanningTreeIndex]; if(rhsMapped != null) { op.SubstituteUsage( rhs, rhsMapped ); } } } } } } } } //--// internal class BasicBlockState { // // State // internal BasicBlock m_bb; internal BasicBlockEdge[] m_successors; internal PhiVariableExpression[] m_stackAtExit; // // Constructor Methods // internal BasicBlockState( BasicBlock bb ) { m_bb = bb; m_successors = bb.Successors; } } private static void ProcessInDominatorTreeOrder( ControlFlowGraphStateForCodeTransformation cfg , BasicBlock[] basicBlocks , BasicBlock[] immediateDominators , VariableExpression[] variables , bool[] candidate , GrowOnlySet< Operator > newPhis ) { int bbNum = basicBlocks.Length; int varNum = variables .Length; BasicBlockState[] bbStates = new BasicBlockState[bbNum]; Stack< BasicBlockState > pending = new Stack< BasicBlockState >( bbNum + 2 ); PhiVariableExpression[] stack = new PhiVariableExpression[varNum]; int [] renameHistory = new int [varNum]; int renameHistoryKey = 1; // // Process from the end of the spanning tree, so that the entry basic block will be at the top of the stack. // for(int idx = bbNum; --idx >= 0; ) { BasicBlockState bbs = new BasicBlockState( basicBlocks[idx] ); bbStates[idx] = bbs; pending.Push( bbs ); } // // Walk through the basic blocks, in dominator order, and update all the variables with corresponding phi versions. // while(pending.Count > 0) { BasicBlockState bbs = pending.Pop(); BasicBlock bb = bbs.m_bb; int idx = bb.SpanningTreeIndex; if(bbs.m_stackAtExit != null) { // // Already processed. // continue; } PhiVariableExpression[] localStack; BasicBlockState bbsIDOM = bbStates[immediateDominators[idx].SpanningTreeIndex] ; if(bbsIDOM == bbs) { // // This is an entry node, so we should use the initial state of the variable stack. // localStack = ArrayUtility.CopyNotNullArray( stack ); } else if(bbsIDOM.m_stackAtExit != null) { // // Use the state of the variable stack at the exit of the dominator basic block as our input. // localStack = ArrayUtility.CopyNotNullArray( bbsIDOM.m_stackAtExit ); } else { // // Process the immediate dominator before the current basic block. // pending.Push( bbs ); pending.Push( bbsIDOM ); continue; } // // Rename all the variables. // var entryStack = ArrayUtility.CopyNotNullArray( localStack ); foreach(Operator op in bb.Operators) { foreach(var an in op.FilterAnnotations< PreInvalidationAnnotation>()) { CreateNewVariable( cfg, variables, localStack, candidate, renameHistory, renameHistoryKey, an.Target ); } renameHistoryKey++; foreach(var an in op.FilterAnnotations< PreInvalidationAnnotation>()) { SubstituteDefinition( localStack, candidate, op, an ); } //--// SubstituteUsage( localStack, entryStack, candidate, op ); //--// foreach(var an in op.FilterAnnotations< PostInvalidationAnnotation>()) { CreateNewVariable( cfg, variables, localStack, candidate, renameHistory, renameHistoryKey, an.Target ); } renameHistoryKey++; foreach(var an in op.FilterAnnotations< PostInvalidationAnnotation>()) { SubstituteDefinition( localStack, candidate, op, an ); } //--// foreach(var lhs in op.Results) { CreateNewVariable( cfg, variables, localStack, candidate, renameHistory, renameHistoryKey, lhs ); } renameHistoryKey++; SubstituteDefinition( localStack, candidate, op ); } bbs.m_stackAtExit = localStack; // // Queue successors for processing. // foreach(BasicBlockEdge edge in bbs.m_successors) { BasicBlockState bbsNext = bbStates[edge.Successor.SpanningTreeIndex]; if(bbsNext.m_stackAtExit == null) { pending.Push( bbsNext ); } } } // // Now that all the variables have been updated, we can fill the phi operators. // foreach(BasicBlockState bbs in bbStates) { foreach(BasicBlockEdge edge in bbs.m_successors) { BasicBlock bbNext = edge.Successor; foreach(Operator op in bbNext.Operators) { PhiOperator phiOp = op as PhiOperator; if(phiOp != null && newPhis.Contains( phiOp )) { PhiVariableExpression phiVar = (PhiVariableExpression)phiOp.FirstResult; VariableExpression var = phiVar.Target; VariableExpression input = bbs.m_stackAtExit[var.SpanningTreeIndex]; /// /// TODO: Verify that this is the correct thing to do. For exception handlers /// the variables of the outer scope are set to NULL for the current bbs.m_stackAtExit /// This code gets the variable in the target basic blocks m_stackAtExit /// if(input == null) { input = bbStates[bbNext.SpanningTreeIndex].m_stackAtExit[var.SpanningTreeIndex]; } CHECKS.ASSERT( input != null, "Inputs to the phi operator have to be defined in method '{0}':\r\n {1}", op.BasicBlock.Owner.Method.ToShortString(), phiOp ); phiOp.AddEffect( input, bbs.m_bb ); } } } } } private static void CreateNewVariable( ControlFlowGraphStateForCodeTransformation cfg , VariableExpression[] variables , PhiVariableExpression[] localStack , bool[] candidate , int[] renameHistory , int renameHistoryKey , VariableExpression lhs ) { int varIdx = lhs.SpanningTreeIndex; if(candidate[varIdx] && renameHistory[varIdx] != renameHistoryKey) { PhiVariableExpression phiVar = cfg.AllocatePhiVariable( lhs ); localStack [varIdx] = phiVar; renameHistory[varIdx] = renameHistoryKey; PhysicalRegisterExpression reg = lhs.AliasedVariable as PhysicalRegisterExpression; if(reg != null) { // // Create a new phi variables for all the various typed versions of this physical register. // foreach(VariableExpression reg2 in variables) { int regIdx = reg2.SpanningTreeIndex; if(localStack[regIdx] == null && renameHistory[regIdx] != renameHistoryKey && reg.IsTheSamePhysicalEntity( reg2.AliasedVariable )) { localStack [regIdx] = cfg.AllocatePhiVariable( reg2 ); renameHistory[regIdx] = renameHistoryKey; } } } } } private static void SubstituteDefinition( PhiVariableExpression[] localStack , bool[] candidate , Operator op , InvalidationAnnotation an ) { var lhs = an.Target; int varIdx = lhs.SpanningTreeIndex; if(candidate[varIdx]) { var newVar = localStack[varIdx]; InvalidationAnnotation anNew; if(an is PreInvalidationAnnotation) { anNew = PreInvalidationAnnotation.Create( null, newVar ); } else { anNew = PostInvalidationAnnotation.Create( null, newVar ); } op.SubstituteAnnotation( an, anNew ); } } private static void SubstituteDefinition( PhiVariableExpression[] localStack , bool[] candidate , Operator op ) { foreach(var lhs in op.Results) { int varIdx = lhs.SpanningTreeIndex; if(candidate[varIdx]) { op.SubstituteDefinition( lhs, localStack[varIdx] ); } } } private static void SubstituteUsage( PhiVariableExpression[] localStack , PhiVariableExpression[] entryStack , bool[] candidate , Operator op ) { foreach(Expression rhs in op.Arguments) { VariableExpression var = rhs as VariableExpression; if(var != null) { int varIdx = var.SpanningTreeIndex; if(candidate[varIdx]) { // // If a variable is an argument, it won't be defined on any path from entry, // so its lot in localStack will be empty. It's OK, just use the original value. // PhiVariableExpression phiVar; // // Phi and Pi operators are parallel operators. // That's equivalent to using the state of the variables at the entry of the basic block. // if(op is PhiOperator || op is PiOperator ) { phiVar = entryStack[varIdx]; } else { phiVar = localStack[varIdx]; } CHECKS.ASSERT( phiVar != null, "Found use of phi-candidate variable that is not reachable by any of its definitions: {0}", op ); op.SubstituteUsage( var, phiVar ); } } } } //--//--//--//--//--//--//--//--//--//--// public static bool ConvertOut( ControlFlowGraphStateForCodeTransformation cfg , bool fAllowPseudoReg ) { using(new PerformanceCounters.ContextualTiming( cfg, "ConvertOutSSA" )) { bool fShouldProcess = false; // // First of all, are we still in SSA form? // Look for any PhiOperators or PhiVariable. // foreach(Operator op in cfg.DataFlow_SpanningTree_Operators) { if(op is PhiOperator || op is PiOperator ) { fShouldProcess = true; break; } } if(fShouldProcess == false) { foreach(VariableExpression var in cfg.DataFlow_SpanningTree_Variables) { if(var is PhiVariableExpression) { fShouldProcess = true; break; } } } if(fShouldProcess) { cfg.TraceToFile( "ConvertOut-Pre" ); RemovePiOperators ( cfg ); ConvertPhiOperatorsIntoCopies ( cfg ); ConvertPhiVariablesIntoNormalVariables( cfg, fAllowPseudoReg ); cfg.TraceToFile( "ConvertOut-Post" ); while(Transformations.CommonMethodRedundancyElimination.Execute( cfg )) { } cfg.DropDeadVariables(); cfg.TraceToFile( "ConvertOut-Done" ); } return fShouldProcess; } } //--// internal class InsertionState { // // State // internal BasicBlock m_basicBlockSource; internal BasicBlock m_basicBlockTarget; internal BasicBlock m_basicBlockInserted; internal List< SingleAssignmentOperator > m_assignments; // // Constructor Methods // internal InsertionState( BasicBlock bbSource , BasicBlock bbTarget ) { m_basicBlockSource = bbSource; m_basicBlockTarget = bbTarget; m_assignments = new List< SingleAssignmentOperator >(); } internal void AllocateBasicBlock() { m_basicBlockInserted = m_basicBlockSource.InsertNewSuccessor( m_basicBlockTarget ); } internal void Add( Microsoft.Zelig.Debugging.DebugInfo debugInfo , VariableExpression targetVar , Expression sourceEx ) { m_assignments.Add( SingleAssignmentOperator.New( debugInfo, targetVar, sourceEx ) ); } internal void ScheduleCopies( ControlFlowGraphStateForCodeTransformation cfg ) { // // First, get rid of non-interfering copies. // while(true) { InsertNonInterferingCopies(); bool fDone = true; for(int pos = 0; pos < m_assignments.Count; pos++) { SingleAssignmentOperator op = m_assignments[pos]; if(op != null) { // // At this point, only items in a cyclic graph are left. // // To break the loop, we have to: // 1) create a temporary, // 2) copy the source value into it, // 3) remove the original copy from the set, // 4) schedule all the other copies, // 5) insert back the assignment to the original destination, now from the temporary. // VariableExpression destinationVar = op.FirstResult; VariableExpression sourceVar = (VariableExpression)op.FirstArgument; VariableExpression tmp = AllocateTemporary( cfg, sourceVar.AliasedVariable ); m_basicBlockInserted.AddOperator( SingleAssignmentOperator.New( op.DebugInfo, tmp, sourceVar ) ); m_assignments[pos] = null; InsertNonInterferingCopies(); CHECKS.ASSERT( IsUsedByAnotherCopy( op, destinationVar ) == false, "Oops" ); m_assignments[pos] = SingleAssignmentOperator.New( op.DebugInfo, destinationVar, tmp ); fDone = false; // One less candidate, try looping again. break; } } if(fDone) { break; } } } //--// private VariableExpression AllocateTemporary( ControlFlowGraphStateForCodeTransformation cfg , VariableExpression var ) { if(var is PhysicalRegisterExpression) { PhysicalRegisterExpression regVar = (PhysicalRegisterExpression)var; Abstractions.RegisterDescriptor regDesc = cfg.TypeSystem.PlatformAbstraction.GetScratchRegister(); var = cfg.AllocateTypedPhysicalRegister( regVar.Type, regDesc, regVar.DebugName, regVar.SourceVariable, regVar.SourceOffset ); } return cfg.AllocatePhiVariable( var ); } private void InsertNonInterferingCopies() { while(true) { bool fDone = true; for(int pos = 0; pos < m_assignments.Count; pos++) { SingleAssignmentOperator op = m_assignments[pos]; if(op != null) { if(IsUsedByAnotherCopy( op, op.FirstResult ) == false) { m_basicBlockInserted.AddOperator( op ); m_assignments[pos] = null; fDone = false; // One less candidate, try looping again. } } } if(fDone) { break; } } } private bool IsUsedByAnotherCopy( SingleAssignmentOperator opSrc , VariableExpression var ) { for(int pos = 0; pos < m_assignments.Count; pos++) { var op = m_assignments[pos]; if(op != null && op != opSrc) // Skip source operator. { if(var.IsTheSamePhysicalEntity( op.FirstArgument )) { return true; } } } return false; } } private static void ConvertPhiOperatorsIntoCopies( ControlFlowGraphStateForCodeTransformation cfg ) { List< InsertionState > insertionPoints = new List< InsertionState >(); // // Build the table with all the copy operations that have to be scheduled. // foreach(var phiOp in cfg.FilterOperators< PhiOperator >()) { Expression[] rhs = phiOp.Arguments; BasicBlock[] origins = phiOp.Origins; BasicBlock target = phiOp.BasicBlock; VariableExpression targetVar = phiOp.FirstResult; for(int pos = 0; pos < origins.Length; pos++) { Expression sourceEx = rhs [pos]; BasicBlock source = origins[pos]; InsertionState insertionPoint = null; foreach(InsertionState insertionPoint2 in insertionPoints) { if(insertionPoint2.m_basicBlockSource == source && insertionPoint2.m_basicBlockTarget == target ) { insertionPoint = insertionPoint2; break; } } if(insertionPoint == null) { insertionPoint = new InsertionState( source, target ); insertionPoints.Add( insertionPoint ); } insertionPoint.Add( phiOp.DebugInfo, targetVar, sourceEx ); } phiOp.Delete(); } // // Create a new basic block and redirect the source to it. // foreach(InsertionState insertionPoint in insertionPoints) { insertionPoint.AllocateBasicBlock(); } foreach(InsertionState insertionPoint in insertionPoints) { insertionPoint.ScheduleCopies( cfg ); } } //--// internal class VariableState { // // State // internal int m_index; internal VariableExpression.Property m_properties; internal PhiVariableExpression[] m_phiVariables; internal VariableExpression m_mappedTo; internal Operator[] m_definitions; internal BitVector m_livenessMap; // // Constructor Methods // internal VariableState( int index ) { m_index = index; m_phiVariables = PhiVariableExpression.SharedEmptyArray; } internal static VariableState Create( GrowOnlyHashTable< VariableExpression, VariableState > lookup , VariableExpression var ) { VariableState res; if(lookup.TryGetValue( var, out res ) == false) { res = new VariableState( var.SpanningTreeIndex ); lookup[var] = res; } return res; } internal bool IsThereInterference( GrowOnlyHashTable< VariableExpression, VariableState > lookup , BitVector tmp , PhiVariableExpression phiTarget , PhiVariableExpression[] phis ) { // // We have to find out if there's any overlap in the liveness of different phi variables. // If there isn't, we can directly convert them back to registers. // Otherwise we need to add extra assignments. // foreach(PhiVariableExpression phi in phis) { if(phi != phiTarget) { tmp.And( m_livenessMap, lookup[phi].m_livenessMap ); if(tmp.Cardinality != 0) { return true; } } } return false; } } private static void ConvertPhiVariablesIntoNormalVariables( ControlFlowGraphStateForCodeTransformation cfg , bool fAllowPseudoReg ) { VariableExpression[] variables = cfg.DataFlow_SpanningTree_Variables; VariableExpression.Property[] varProps = cfg.DataFlow_PropertiesOfVariables; Operator[][] defChains = cfg.DataFlow_DefinitionChains; BitVector[] variableLivenessMap = cfg.DataFlow_VariableLivenessMap; GrowOnlyHashTable< VariableExpression, VariableState > lookup = HashTableFactory.NewWithReferenceEquality< VariableExpression, VariableState >(); // // Collect all redefinitions of variables. // foreach(VariableExpression var in variables) { VariableState vs; PhiVariableExpression phiVar = var as PhiVariableExpression; if(phiVar != null) { vs = VariableState.Create( lookup, phiVar.AliasedVariable ); vs.m_phiVariables = ArrayUtility.AppendToNotNullArray( vs.m_phiVariables, phiVar ); } //--// vs = VariableState.Create( lookup, var ); int idx = var.SpanningTreeIndex; vs.m_properties = varProps [idx]; vs.m_livenessMap = variableLivenessMap[idx]; vs.m_definitions = defChains [idx]; } // // Keep track of all the substitutions. // // Then go through the Subroutines and Invalidate operators and // update the values back to PhysicalRegister and StackLocations. // If needed, add assignment operators in front of subroutine calls. // foreach(VariableExpression var in lookup.Keys) { VariableState vs = lookup[var]; PhiVariableExpression[] phis = vs.m_phiVariables; if(phis.Length == 1) { // // Simple case, only one definition, substitute back for the original variable. // lookup[ phis[0] ].m_mappedTo = var; } else { VariableExpression.DebugInfo debugInfo = var.AliasedVariable.DebugName; BitVector tmp = new BitVector(); foreach(PhiVariableExpression phi in phis) { VariableState vsPhi = lookup[phi]; VariableExpression newVar = null; if(var is PhysicalRegisterExpression) { // // We have to find out if there's any overlap in the liveness of different phi variables. // If there isn't, we can directly convert them back to registers. // Otherwise we need to add extra assignments. // if(vsPhi.IsThereInterference( lookup, tmp, phi, phis ) == false) { newVar = var; } else if(vsPhi.m_definitions.Length == 1 && vsPhi.m_definitions[0] is InitialValueOperator) { // // This is an argument. Keep it as is. // newVar = var; } else { // // There's some aliasing problem with this register. // Create a new temporary, add an assignment at the original definition site and propagate that value. // if(fAllowPseudoReg) { newVar = cfg.AllocatePseudoRegister( var.Type, debugInfo ); } else { newVar = var; } } } else if(var is ConditionCodeExpression) { CHECKS.ASSERT( (vsPhi.m_properties & VariableExpression.Property.AddressTaken) == 0, "Cannot take address of condition code: {0}", phi ); // // We have to find out if there's any overlap in the liveness of different phi variables. // If there isn't, we can directly convert them back to registers. // Otherwise we need to add extra assignments. // if(vsPhi.IsThereInterference( lookup, tmp, phi, phis ) == false) { newVar = var; } else if(vsPhi.m_definitions.Length == 1 && vsPhi.m_definitions[0] is InitialValueOperator) { // // This is an argument. Keep it as is. // newVar = var; } else { // // There's some aliasing problem with this register. // Create a new temporary, add an assignment at the original definition site and propagate that value. // if(fAllowPseudoReg) { newVar = cfg.AllocatePseudoRegister( var.Type, debugInfo ); } else { newVar = var; } } } else if(var is StackLocationExpression) { StackLocationExpression stack = (StackLocationExpression)var; if(vsPhi.IsThereInterference( lookup, tmp, phi, phis ) == false) { newVar = var; } else if(vsPhi.m_definitions.Length == 1 && vsPhi.m_definitions[0] is InitialValueOperator) { // // This is an argument. Keep it as is. // newVar = var; } else { // // There's some aliasing problem with this stack location. // Create a new temporary, add an assignment at the original definition site and propagate that value. // if((vsPhi.m_properties & VariableExpression.Property.AddressTaken) != 0) { newVar = cfg.AllocateLocalStackLocation( stack.Type, debugInfo, stack.SourceVariable, stack.SourceOffset ); } else { if(fAllowPseudoReg) { newVar = cfg.AllocatePseudoRegister( stack.Type, debugInfo, stack.SourceVariable, stack.SourceOffset ); } else { newVar = var; } } } } else if(var is PseudoRegisterExpression) { PseudoRegisterExpression pseudo = (PseudoRegisterExpression)var; if((vsPhi.m_properties & VariableExpression.Property.AddressTaken) != 0) { newVar = cfg.AllocateLocalStackLocation( pseudo.Type, debugInfo, pseudo.SourceVariable, pseudo.SourceOffset ); } else { if(fAllowPseudoReg) { newVar = cfg.AllocatePseudoRegister( pseudo.Type, debugInfo, pseudo.SourceVariable, pseudo.SourceOffset ); } else { throw TypeConsistencyErrorException.Create( "Expecting a physical expression instead of {0}", var ); } } } else { // // WARNING: Convert to or from SSA before mapping to machine words is untested... // if(var is TemporaryVariableExpression) { newVar = cfg.AllocateTemporary( var.Type, debugInfo ); } else { newVar = cfg.AllocateLocal( var.Type, debugInfo ); } } vsPhi.m_mappedTo = newVar; } } } foreach(Operator op in cfg.DataFlow_SpanningTree_Operators) { SubstitutePhiVariables( op, lookup ); } } private static void SubstitutePhiVariables( Operator op , GrowOnlyHashTable< VariableExpression, VariableState > lookup ) { bool fCall = (op is SubroutineOperator); foreach(var an in op.FilterAnnotations< PreInvalidationAnnotation >()) { var var = an.Target; var newVar = FindSubstituteForPhiVariable( lookup, var ); if(newVar != null) { VariableExpression origVar = var.AliasedVariable; newVar = AdjustForCallingConvention( origVar, newVar ); if(newVar != origVar) { op.AddOperatorBefore( SingleAssignmentOperator.New( op.DebugInfo, origVar, newVar ) ); } var anNew = PreInvalidationAnnotation.Create( null, origVar ); op.SubstituteAnnotation( an, anNew ); } } foreach(Expression ex in op.Arguments) { var var = ex as VariableExpression; if(var != null) { var newVar = FindSubstituteForPhiVariable( lookup, var ); if(newVar != null) { if(fCall) { VariableExpression origVar = var.AliasedVariable; newVar = AdjustForCallingConvention( origVar, newVar ); if(newVar != origVar) { op.AddOperatorBefore( SingleAssignmentOperator.New( op.DebugInfo, origVar, newVar ) ); } op.SubstituteUsage( var, origVar ); } else { op.SubstituteUsage( var, newVar ); } } } } foreach(var an in op.FilterAnnotations< PostInvalidationAnnotation >()) { var var = an.Target; var newVar = FindSubstituteForPhiVariable( lookup, var ); if(newVar != null) { VariableExpression origVar = var.AliasedVariable; newVar = AdjustForCallingConvention( origVar, newVar ); if(newVar != origVar) { op.AddOperatorAfter( SingleAssignmentOperator.New( op.DebugInfo, newVar, origVar ) ); } var anNew = PostInvalidationAnnotation.Create( null, origVar ); op.SubstituteAnnotation( an, anNew ); } } foreach(var var in op.Results) { var newVar = FindSubstituteForPhiVariable( lookup, var ); if(newVar != null) { op.SubstituteDefinition( var, newVar ); } } } private static VariableExpression FindSubstituteForPhiVariable( GrowOnlyHashTable< VariableExpression, VariableState > lookup , VariableExpression var ) { VariableState vs; if(lookup.TryGetValue( var, out vs )) { return vs.m_mappedTo; } return null; } private static VariableExpression AdjustForCallingConvention( VariableExpression origVar , VariableExpression newVar ) { if(origVar is PhysicalRegisterExpression) { return origVar; } else if(origVar is ConditionCodeExpression) { return origVar; } else if(origVar is StackLocationExpression) { StackLocationExpression stack = (StackLocationExpression)origVar; if(stack.StackPlacement == StackLocationExpression.Placement.Out) { return stack; } } return newVar; } // // Access Methods // } } ================================================ FILE: Zelig/Zelig/CompileTime/CodeGenerator/CodeTransformation/Transformations/TransformFinallyBlocksIntoTryBlocks.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // //#define DEBUG_REMOVEUNNECESSARYTEMPORARIES namespace Microsoft.Zelig.CodeGeneration.IR.Transformations { using System; using System.Collections.Generic; using Microsoft.Zelig.Runtime.TypeSystem; public static class TransformFinallyBlocksIntoTryBlocks { struct FinallyRange { public ExceptionHandlerBasicBlock Entry; public BasicBlock Exit; public override bool Equals(Object obj) { return (obj is FinallyRange) && (this == (FinallyRange)obj); } public override int GetHashCode() { return Entry.GetHashCode() ^ Exit.GetHashCode(); } public static bool operator ==(FinallyRange x, FinallyRange y) { return (x.Entry == y.Entry) && (x.Entry == y.Entry); } public static bool operator !=(FinallyRange x, FinallyRange y) { return !(x == y); } }; public static void Execute(ControlFlowGraphStateForCodeTransformation cfg) { // This maps finally block ranges to the entry block of their cloned 'normal' region. var clonedRanges = HashTableFactory.New(); while (true) { cfg.TraceToFile( "TransformFinallyBlocksIntoTryBlocks" ); bool fDone = true; foreach (BasicBlock block in cfg.DataFlow_SpanningTree_BasicBlocks) { if (RemoveFinally(cfg, block, clonedRanges)) { fDone = false; break; } } if(fDone) { CHECKS.ASSERT( FindOperation( cfg.DataFlow_SpanningTree_Operators, typeof(EndFinallyControlOperator) ) == null, "Internal error: failed to remove 'endfinally' operators in {0}.", cfg.Method ); break; } } } private static bool RemoveFinally( ControlFlowGraphStateForCodeTransformation cfg, BasicBlock block, GrowOnlyHashTable clonedRanges) { ExceptionHandlerBasicBlock ehBB = block as ExceptionHandlerBasicBlock; if (ehBB == null) { return false; } foreach(ExceptionClause ec in ehBB.HandlerFor) { if(ec.Flags == ExceptionClause.ExceptionFlag.Finally) { GrowOnlySet setVisited = SetFactory.NewWithReferenceEquality(); // // Collect all the basic blocks that are part of the handler. // CollectFinallyHandler(ehBB, setVisited); // // First, see if there's any nested finally clause. If so, bail out. // foreach (BasicBlock bbSub in setVisited) { if (bbSub != ehBB) { if (RemoveFinally(cfg, bbSub, clonedRanges)) { return true; } } } GrowOnlySet setLeave = SetFactory.NewWithReferenceEquality(); GrowOnlySet setFinally = SetFactory.NewWithReferenceEquality(); // // Find all the leave operators in the basic blocks protected by this finally handler. // FindAllLeaveOperators(ehBB, setLeave); // // For each of them: // // 1) Clone the finally handler(s) protecting the leaving block. // 2) Convert the leave to a branch to the cloned handler. // 3) Change endfinally to a leave to the same original target. // foreach (LeaveControlOperator leave in setLeave) { CloningContext context = new CloneForwardGraphButLinkToExceptionHandlers(cfg, cfg, null); var finallyHandlers = new Stack(); FinallyRange currentRange = new FinallyRange{ Entry = null, Exit = leave.TargetBranch }; // Unwind all finally blocks that either ehBB itself or protected by it. These are always in // order from innermost to outermost; we can just chain them together until we hit ehBB. foreach (var handler in leave.BasicBlock.ProtectedBy) { foreach (var clause in handler.HandlerFor) { if ((clause.Flags & ExceptionClause.ExceptionFlag.Finally) != 0) { // Set the range's entry block to the first one we encounter. if (currentRange.Entry == null) { currentRange.Entry = handler; } finallyHandlers.Push(handler); break; } } if (handler == ehBB) { break; } } // If we already cloned this range of finally blocks, just reuse the existing entry block. BasicBlock nextBlock; if (!clonedRanges.TryGetValue(currentRange, out nextBlock)) { nextBlock = leave.TargetBranch; // Clone each handler block in reverse order. while (finallyHandlers.Count != 0) { BasicBlock handler = finallyHandlers.Pop(); BasicBlock clonedBlock = context.Clone(handler.FirstSuccessor); setFinally.Clear(); FindAllFinallyOperators(clonedBlock, setFinally); SubstituteFinallyForBranch(setFinally, nextBlock); nextBlock = clonedBlock; } clonedRanges[currentRange] = nextBlock; } var leaveBranch = UnconditionalControlOperator.New(leave.DebugInfo, nextBlock); leave.SubstituteWithOperator(leaveBranch, Operator.SubstitutionFlags.Default); } // To finish, all the endfinally operators should be converted to simple rethrow. setFinally.Clear(); FindAllFinallyOperators(ehBB, setFinally); SubstituteFinallyForRethrow(setFinally); // Convert the finally exception clauses to catch all ones. ExceptionClause ecNew = new ExceptionClause(ExceptionClause.ExceptionFlag.None, null); ehBB.SubstituteHandlerFor(ec, ecNew); return true; } } return false; } private static Operator FindOperation( Operator[] ops , Type match ) { foreach(Operator op in ops) { if(op.GetType() == match) { return op; } } return null; } private static void CollectFinallyHandler( BasicBlock bb , GrowOnlySet< BasicBlock > setVisited ) { setVisited.Insert( bb ); foreach(BasicBlockEdge edge in bb.Successors) { BasicBlock succ = edge.Successor; if(succ is ExceptionHandlerBasicBlock) { // // Don't follow exceptional edges. // } else if(setVisited.Contains( succ ) == false) { CollectFinallyHandler( succ, setVisited ); } } } private static void FindAllLeaveOperators( BasicBlock bb , GrowOnlySet setLeave ) { foreach(BasicBlockEdge edge in bb.Predecessors) { BasicBlock pred = edge.Predecessor; LeaveControlOperator ctrl = pred.FlowControl as LeaveControlOperator; if(ctrl != null) { // // Only consider operators leaving the area protected by the handler. // if(pred .IsProtectedBy( bb ) == true && ctrl.TargetBranch.IsProtectedBy( bb ) == false ) { setLeave.Insert( ctrl ); } } } } private static void FindAllFinallyOperators( BasicBlock bb , GrowOnlySet setFinally ) { GrowOnlySet< BasicBlock > setVisited = SetFactory.NewWithReferenceEquality< BasicBlock >(); CollectFinallyHandler( bb, setVisited ); foreach(BasicBlock bb2 in setVisited) { ControlOperator ctrl = bb2.FlowControl; if(ctrl is EndFinallyControlOperator) { setFinally.Insert( ctrl ); } } } private static void SubstituteFinallyForBranch(GrowOnlySet setFinally, BasicBlock target) { foreach (ControlOperator op in setFinally) { var opNew = UnconditionalControlOperator.New(op.DebugInfo, target); op.SubstituteWithOperator(opNew, Operator.SubstitutionFlags.Default); } } private static void SubstituteFinallyForRethrow( GrowOnlySet setFinally ) { foreach(ControlOperator op in setFinally) { RethrowControlOperator opNew = RethrowControlOperator.New( op.DebugInfo ); op.SubstituteWithOperator( opNew, Operator.SubstitutionFlags.Default ); } } } } ================================================ FILE: Zelig/Zelig/CompileTime/CodeGenerator/CodeTransformation/Transformations/TypeSystemIntrospection/CollectUsageContext.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // namespace Microsoft.Zelig.CodeGeneration.IR.Transformations { using System; using System.Collections.Generic; using Microsoft.Zelig.Runtime.TypeSystem; internal sealed class CollectUsageContext : ScanTypeSystem { // // State // object m_target; List< object[] > m_occurences; // // Constructor Methods // private CollectUsageContext( TypeSystemForCodeTransformation typeSystem , object target ) : base( typeSystem, typeof(CollectUsageContext) ) { m_target = target; m_occurences = new List< object[] >(); } //--// // // Helper Methods // internal static List< object[] > Execute( TypeSystemForCodeTransformation typeSystem , object target ) { CollectUsageContext pThis = new CollectUsageContext( typeSystem, target ); pThis.ProcessTypeSystem(); return pThis.m_occurences; } //--// protected override object ShouldSubstitute( object target , out SubstitutionAction result ) { if(target == m_target) { m_occurences.Add( this.FullContext ); } result = SubstitutionAction.Unknown; return null; } } } ================================================ FILE: Zelig/Zelig/CompileTime/CodeGenerator/CodeTransformation/Transformations/TypeSystemIntrospection/LocateFieldsInCode.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // namespace Microsoft.Zelig.CodeGeneration.IR.Transformations { using System; using System.Collections.Generic; using Microsoft.Zelig.Runtime.TypeSystem; internal sealed class LocateFieldsInCode { // // State // private TypeSystemForCodeTransformation m_typeSystem; private Transformations.ReverseIndexTypeSystem m_reverseIndex; private GrowOnlyHashTable< FieldRepresentation, GrowOnlySet< Operator > > m_fieldReferences; // // Constructor Methods // internal LocateFieldsInCode( TypeSystemForCodeTransformation typeSystem ) { m_typeSystem = typeSystem; } // // Helper Methods // internal void Run() { m_reverseIndex = new Transformations.ReverseIndexTypeSystem( m_typeSystem ); m_fieldReferences = HashTableFactory.NewWithReferenceEquality< FieldRepresentation, GrowOnlySet< Operator > >(); using(new Transformations.ExecutionTiming( "ReverseIndexTypeSystem" )) { m_reverseIndex.ProcessTypeSystem(); } m_typeSystem.EnumerateFields( delegate( FieldRepresentation fd ) { GrowOnlySet< object > set = m_reverseIndex[fd]; if(set != null) { foreach(object obj in set) { Operator op = obj as Operator; if(op != null) { HashTableWithSetFactory.AddWithReferenceEquality( m_fieldReferences, fd, op ); } } } } ); } //--// // // Access Methods // internal GrowOnlyHashTable< FieldRepresentation, GrowOnlySet< Operator > > FieldReferences { get { return m_fieldReferences; } } } } ================================================ FILE: Zelig/Zelig/CompileTime/CodeGenerator/CodeTransformation/Transformations/TypeSystemIntrospection/LocateUsageInCode.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // namespace Microsoft.Zelig.CodeGeneration.IR.Transformations { using System; using System.Collections.Generic; using Microsoft.Zelig.Runtime.TypeSystem; internal sealed class LocateUsageInCode : ScanCode { // // Constructor Methods // internal LocateUsageInCode( TypeSystemForCodeTransformation typeSystem ) : base( typeSystem, typeof(LocateUsageInCode) ) { } // // Helper Methods // internal void AddLookup( object src ) { CreateEntry( src ); } //--// protected override bool PerformAction( Operator op , object target ) { if(op != null) { List< Operator > lst = this[target]; if(lst != null) { RecordOccurence( lst, op ); } } return true; } } } ================================================ FILE: Zelig/Zelig/CompileTime/CodeGenerator/CodeTransformation/Transformations/TypeSystemIntrospection/RemapTypeSystem.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // namespace Microsoft.Zelig.CodeGeneration.IR.Transformations { using System; using System.Collections.Generic; using Microsoft.Zelig.Runtime.TypeSystem; internal sealed class RemapTypeSystem : ScanTypeSystem { // // State // GrowOnlyHashTable< object, object > m_remap; // // Constructor Methods // internal RemapTypeSystem( TypeSystemForCodeTransformation typeSystem ) : base( typeSystem, typeof(RemapTypeSystem) ) { m_remap = HashTableFactory.NewWithReferenceEquality< object, object >(); } internal override void RefreshHashCodes() { base.RefreshHashCodes(); m_remap.RefreshHashCodes(); } internal int NumberOfRemapRecords { get { return m_remap.Count; } } internal object this[ object key ] { get { if(key != null) { object substitute; if(m_remap.TryGetValue( key, out substitute )) { key = substitute; } } return key; } set { m_remap[key] = value; } } //--// protected override object ShouldSubstitute( object target , out SubstitutionAction result ) { object substitute; if(m_remap.TryGetValue( target, out substitute )) { if(substitute == null) { throw TypeConsistencyErrorException.Create( "Found unexpected reference to {0}", target ); } result = SubstitutionAction.Substitute; return substitute; } else { result = SubstitutionAction.Unknown; return null; } } //--// // // Access Methods // internal GrowOnlyHashTable< object, object > RemapTable { get { return m_remap; } } } } ================================================ FILE: Zelig/Zelig/CompileTime/CodeGenerator/CodeTransformation/Transformations/TypeSystemIntrospection/ReverseIndexTypeSystem.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // namespace Microsoft.Zelig.CodeGeneration.IR.Transformations { using System; using System.Collections.Generic; using Microsoft.Zelig.Runtime.TypeSystem; internal sealed class ReverseIndexTypeSystem : ScanTypeSystem { // // State // GrowOnlyHashTable< object, GrowOnlySet< object > > m_lookup; bool m_fPendingRefreshHashCodes; // // Constructor Methods // internal ReverseIndexTypeSystem( TypeSystemForCodeTransformation typeSystem ) : base( typeSystem, typeof(ReverseIndexTypeSystem) ) { m_lookup = HashTableFactory.NewWithWeakEquality< object, GrowOnlySet< object > >(); } //--// // // Helper Methods // internal override void RefreshHashCodes() { // // The ReverseIndex is extensively used during Class Extension, and thus this method is called many times. // Recomputing the hash codes for millions of objects is too expensive, so we keep track that a refresh is needed. // When we hit Update later, we refresh the hash codes of the base class before performing the scan. // m_fPendingRefreshHashCodes = true; m_lookup.RefreshHashCodes(); } internal override void ProcessTypeSystem() { m_lookup.Clear(); base.ProcessTypeSystem(); } internal void Update( object obj ) { if(m_fPendingRefreshHashCodes) { m_fPendingRefreshHashCodes = false; base.RefreshHashCodes(); } this.TransformGenericReference( obj ); } internal int NumberOfRemapRecords { get { return m_lookup.Count; } } internal GrowOnlySet< object > this[ object key ] { get { GrowOnlySet< object > val; if(m_lookup.TryGetValue( key, out val )) { return val; } return null; } } internal void Merge( object from , object to ) { this.RefreshHashCodes(); GrowOnlySet< object > setFrom = m_lookup[from]; GrowOnlySet< object > setTo = m_lookup[to]; if(setFrom != null) { if(setTo != null) { setTo.RefreshHashCodes(); setTo.Merge( setFrom ); } else { setFrom.RefreshHashCodes(); m_lookup[to] = setFrom; } m_lookup[from] = null; } } //--// protected override object ShouldSubstitute( object target , out SubstitutionAction result ) { object context = this.TopContext(); if(context != null) { if(CanBeTracked( target )) { GrowOnlySet< object > set; if(m_lookup.TryGetValue( target, out set ) == false || set == null) { set = SetFactory.NewWithReferenceEquality< object >(); m_lookup[target] = set; } set.Insert( context ); } } result = SubstitutionAction.Unknown; return null; } //--// internal bool CanBeTracked( object obj ) { if(obj is BaseRepresentation || obj is MethodImplRepresentation || obj is CustomAttributeAssociationRepresentation || obj is CustomAttributeRepresentation || obj is Annotation || obj is VTable ) { return true; } return false; } // // Access Methods // internal GrowOnlyHashTable< object, GrowOnlySet< object > > ReverseIndexTable { get { return m_lookup; } } } } ================================================ FILE: Zelig/Zelig/CompileTime/CodeGenerator/CodeTransformation/Transformations/TypeSystemIntrospection/ScanCode.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // namespace Microsoft.Zelig.CodeGeneration.IR.Transformations { using System; using System.Collections.Generic; using Microsoft.Zelig.Runtime.TypeSystem; internal abstract class ScanCode : ScanTypeSystem { // // State // protected GrowOnlyHashTable< object, List< Operator > > m_entries; bool m_fStop; // // Constructor Methods // protected ScanCode( TypeSystemForCodeTransformation typeSystem , object scanOriginator ) : base( typeSystem, scanOriginator ) { m_entries = HashTableFactory.NewWithReferenceEquality< object, List< Operator > >(); } // // Helper Methods // internal override void RefreshHashCodes() { base.RefreshHashCodes(); m_entries.RefreshHashCodes(); } //--// internal bool ProcessType( TypeRepresentation td ) { foreach(MethodRepresentation md in td.Methods) { if(!ProcessMethod( md )) return false; } return true; } internal bool ProcessMethod( MethodRepresentation md ) { return ProcessMethod( TypeSystemForCodeTransformation.GetCodeForMethod( md ) ); } internal bool ProcessMethod( ControlFlowGraphState cfg ) { Transform( ref cfg ); return m_fStop == false; } //--// protected List< Operator > CreateEntry( object key ) { return HashTableWithListFactory.Create( m_entries, key ); } protected void RecordOccurence( List< Operator > lst , Operator op ) { if(lst.IndexOf( op ) < 0) { lst.Add( op ); } } protected abstract bool PerformAction( Operator op , object target ); protected override object ShouldSubstitute( object target , out SubstitutionAction result ) { if(m_fStop) { result = SubstitutionAction.Keep; return null; } Operator op = (Operator)FindContext( typeof(Operator) ); if(!PerformAction( op, target )) { m_fStop = true; result = SubstitutionAction.Keep; return null; } if(target is TypeSystem || target is CustomAttributeAssociationRepresentation || target is CustomAttributeRepresentation || target is BaseRepresentation || target is DataManager.DataDescriptor ) { // // Don't follow type system entities or data, we just want to stay within the code. // result = SubstitutionAction.Keep; } else { result = SubstitutionAction.Unknown; } return null; } // // Access Methods // internal List< Operator > this[object index] { get { if(index != null) { List< Operator > lst; if(m_entries.TryGetValue( index, out lst )) { return lst; } } return null; } } internal GrowOnlyHashTable< object, List< Operator > > Entries { get { return m_entries; } } } } ================================================ FILE: Zelig/Zelig/CompileTime/CodeGenerator/CodeTransformation/Transformations/TypeSystemIntrospection/ScanCodeWithCallback.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // namespace Microsoft.Zelig.CodeGeneration.IR.Transformations { using System; using System.Collections.Generic; using Microsoft.Zelig.Runtime.TypeSystem; internal sealed class ScanCodeWithCallback : ScanCode { internal enum CallbackResult { Proceed , SkipToNextOperator, Stop , } internal delegate CallbackResult Callback( Operator op, object target ); // // State // private Callback m_callback; private Operator m_operatorToSkip; // // Constructor Methods // private ScanCodeWithCallback( TypeSystemForCodeTransformation typeSystem , object scanOriginator , Callback callback ) : base( typeSystem, scanOriginator ) { m_callback = callback; } // // Helper Methods // internal static bool Execute( TypeSystemForCodeTransformation typeSystem , object scanOriginator , ControlFlowGraphState cfg , Callback callback ) { ScanCodeWithCallback csc = new ScanCodeWithCallback( typeSystem, scanOriginator, callback ); return csc.ProcessMethod( cfg ); } //--// public override void Push( object ctx ) { base.Push( ctx ); } public override void Pop() { object obj = TopContext(); base.Pop(); if(m_operatorToSkip != null && obj == m_operatorToSkip) { if(TopContext() != obj) // Deal with recursion. { m_operatorToSkip = null; } } } protected override bool PerformAction( Operator op , object target ) { if(m_operatorToSkip != null && op == m_operatorToSkip) { return true; } CallbackResult result = m_callback( op, target ); if(result == CallbackResult.SkipToNextOperator && m_operatorToSkip == null) { m_operatorToSkip = op; } return (result != CallbackResult.Stop); } } } ================================================ FILE: Zelig/Zelig/CompileTime/CodeGenerator/CodeTransformation/Transformations/TypeSystemIntrospection/ScanTypeSystem.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // #define TRANSFORMATIONCONTEXT_SHOWALLMETHODSTODEBUGGER namespace Microsoft.Zelig.CodeGeneration.IR.Transformations { using System; using System.Collections.Generic; using Microsoft.Zelig.Runtime.TypeSystem; internal abstract class ScanTypeSystem : TransformationContextForCodeTransformation { protected enum SubstitutionAction { Unknown , Substitute, Keep , } // // State // private static GrowOnlyHashTable< Type, System.Reflection.MethodInfo > s_handlers; private static DynamicTransform s_dynamicTransform; protected TypeSystemForCodeTransformation m_typeSystem; protected object m_scanOriginator; private GrowOnlySet< object > m_visited; private object m_pending; // Transform( ref object ) has to go through Visit twice. Keep track of it. private object[] m_contextStack; private int m_contextStackSize; // // Constructor Methods // protected ScanTypeSystem( TypeSystemForCodeTransformation typeSystem , object scanOriginator ) { m_typeSystem = typeSystem; m_scanOriginator = scanOriginator; m_visited = SetFactory.NewWithReferenceEquality< object >(); m_contextStack = new object[16]; m_contextStackSize = 0; } #if TRANSFORMATIONCONTEXT__USE_EMIT public override bool IsReader { get { return false; } } #endif // // Helper Methods // internal virtual void RefreshHashCodes() { m_visited.RefreshHashCodes(); } internal virtual void ProcessTypeSystem() { this.Transform( ref m_typeSystem ); } internal void Reset() { m_visited.Clear(); m_pending = null; } //--// protected override void ClearPending() { m_pending = null; } protected virtual object ShouldSubstitute( object target , out SubstitutionAction result ) { result = SubstitutionAction.Unknown; return null; } #if !TRANSFORMATIONCONTEXT_SHOWALLMETHODSTODEBUGGER [System.Diagnostics.DebuggerHidden] #endif private SubstitutionAction Visit( ref T target ) where T : class { return Visit( ref target, false ); } #if !TRANSFORMATIONCONTEXT_SHOWALLMETHODSTODEBUGGER [System.Diagnostics.DebuggerHidden] #endif private SubstitutionAction Visit( ref T target , bool fSkipRecursiveCheck ) where T : class { if(m_pending != null) { CHECKS.ASSERT( m_pending == (object)target, "Internal error, ScanTypeSystem was expecting {0}, got {1}", m_pending, target ); m_pending = null; return SubstitutionAction.Unknown; } if(target == null) { return SubstitutionAction.Keep; } SubstitutionAction res; object substitute = ShouldSubstitute( target, out res ); if(res == SubstitutionAction.Substitute) { target = (T)substitute; } else if(res == SubstitutionAction.Unknown) { // // 'target' is passed by reference, so ShouldSubstitute could change it. // So, even if we checked for null in the step above, we have to check for null again. // if(target == null) { res = SubstitutionAction.Keep; } if(!fSkipRecursiveCheck && m_visited.Insert( target )) { res = SubstitutionAction.Keep; } } return res; } //--// #if !TRANSFORMATIONCONTEXT_SHOWALLMETHODSTODEBUGGER [System.Diagnostics.DebuggerHidden] #endif private void ReplaceUnique( ref T target ) where T : BaseRepresentation { if(Visit( ref target ) == SubstitutionAction.Unknown) { target.ApplyTransformation( this ); } } #if !TRANSFORMATIONCONTEXT_SHOWALLMETHODSTODEBUGGER [System.Diagnostics.DebuggerHidden] #endif private void ReplaceUnique( ref T[] target ) where T : BaseRepresentation { if(Visit( ref target ) == SubstitutionAction.Unknown) { for(int i = 0; i < target.Length; i++) { ReplaceUnique( ref target[i] ); } } } private void ReplaceUnique( ref List target ) where T : BaseRepresentation { if(Visit( ref target ) == SubstitutionAction.Unknown) { for(int i = 0; i < target.Count; i++) { T tmp = target[i]; ReplaceUnique( ref tmp ); target[i] = tmp; } } } //--//--//--//--//--//--//--//--//--//--//--//--// // // TransformationContext // protected override bool ShouldTransform( object target ) { SubstitutionAction res; ShouldSubstitute( target, out res ); return res != SubstitutionAction.Keep; } public override void MarkAsVisited( object obj ) { m_visited.Insert( obj ); } public override void Push( object ctx ) { if(m_contextStackSize >= m_contextStack.Length) { m_contextStack = ArrayUtility.IncreaseSizeOfNotNullArray( m_contextStack, 16 ); } m_contextStack[m_contextStackSize++] = ctx; } public override void Pop() { m_contextStack[--m_contextStackSize] = null; if(m_contextStackSize == 0) { RunDelayedUpdates(); } } public override object TopContext() { if(m_contextStackSize > 0) { return m_contextStack[m_contextStackSize-1]; } return null; } public override object FindContext( Type ctx ) { for(int i = m_contextStackSize; --i >= 0; ) { object o = m_contextStack[i]; if(ctx.IsInstanceOfType( o )) { return o; } } return null; } public override object GetTransformInitiator() { return m_scanOriginator; } public override TypeSystem GetTypeSystem() { return m_typeSystem; } //--// public override void Transform( ref ITransformationContextTarget itf ) { if(Visit( ref itf ) == SubstitutionAction.Unknown) { itf.ApplyTransformation( this ); } } //--// public override void Transform( ref bool val ) { ClearPending(); } public override void Transform( ref char val ) { ClearPending(); } public override void Transform( ref sbyte val ) { ClearPending(); } public override void Transform( ref byte val ) { ClearPending(); } public override void Transform( ref short val ) { ClearPending(); } public override void Transform( ref ushort val ) { ClearPending(); } public override void Transform( ref int val ) { ClearPending(); } public override void Transform( ref uint val ) { ClearPending(); } public override void Transform( ref long val ) { ClearPending(); } public override void Transform( ref ulong val ) { ClearPending(); } public override void Transform( ref float val ) { ClearPending(); } public override void Transform( ref double val ) { ClearPending(); } public override void Transform( ref IntPtr val ) { ClearPending(); } public override void Transform( ref UIntPtr val ) { ClearPending(); } public override void Transform( ref string val ) { ClearPending(); } #if !TRANSFORMATIONCONTEXT_SHOWALLMETHODSTODEBUGGER [System.Diagnostics.DebuggerHidden] #endif public override void Transform( ref object val ) { if(Visit( ref val ) == SubstitutionAction.Unknown) { m_pending = val; val = TransformGenericReference( val ); } } public override void Transform( ref Type val ) { ClearPending(); } //--// public override void Transform( ref bool[] valArray ) { ClearPending(); } public override void Transform( ref char[] valArray ) { ClearPending(); } public override void Transform( ref sbyte[] valArray ) { ClearPending(); } public override void Transform( ref byte[] valArray ) { ClearPending(); } public override void Transform( ref short[] valArray ) { ClearPending(); } public override void Transform( ref ushort[] valArray ) { ClearPending(); } public override void Transform( ref int[] valArray ) { ClearPending(); } public override void Transform( ref uint[] valArray ) { ClearPending(); } public override void Transform( ref long[] valArray ) { ClearPending(); } public override void Transform( ref ulong[] valArray ) { ClearPending(); } public override void Transform( ref float[] valArray ) { ClearPending(); } public override void Transform( ref double[] valArray ) { ClearPending(); } public override void Transform( ref IntPtr[] valArray ) { ClearPending(); } public override void Transform( ref UIntPtr[] valArray ) { ClearPending(); } public override void Transform( ref string[] valArray ) { ClearPending(); } public override void Transform( ref object[] objArray ) { if(Visit( ref objArray ) == SubstitutionAction.Unknown) { var array = objArray; // Get a local copy, because the original could change, due to the 'ref' argument. for(int i = 0; i < array.Length; i++) { Transform( ref array[i] ); } } } //--// public override void Transform( ref List< string > strLst ) { if(Visit( ref strLst ) == SubstitutionAction.Unknown) { List< string > lst = strLst; for(int i = 0; i < lst.Count; i++) { string str = lst[i]; Transform( ref str ); lst[i] = str; } } } //--// public override void Transform( ref Debugging.DebugInfo debugInfo ) { ClearPending(); } //--// public override void Transform( ref WellKnownTypes wkt ) { if(Visit( ref wkt ) == SubstitutionAction.Unknown) { wkt.ApplyTransformation( this ); } } public override void Transform( ref WellKnownMethods wkm ) { if(Visit( ref wkm ) == SubstitutionAction.Unknown) { wkm.ApplyTransformation( this ); } } public override void Transform( ref WellKnownFields wkf ) { if(Visit( ref wkf ) == SubstitutionAction.Unknown) { wkf.ApplyTransformation( this ); } } //--// public override void Transform( ref AssemblyRepresentation asml ) { ClearPending(); } public override void Transform( ref List< AssemblyRepresentation > asmlLst ) { ClearPending(); } public override void Transform( ref AssemblyRepresentation.VersionData ver ) { ClearPending(); } public override void Transform( ref AssemblyRepresentation.VersionData.AssemblyFlags val ) { ClearPending(); } //--// public override void Transform( ref BaseRepresentation bd ) { ReplaceUnique( ref bd ); } //--// public override void Transform( ref TypeRepresentation td ) { ReplaceUnique( ref td ); } public override void Transform( ref ValueTypeRepresentation td ) { ReplaceUnique( ref td ); } public override void Transform( ref ArrayReferenceTypeRepresentation td ) { ReplaceUnique( ref td ); } public override void Transform( ref InterfaceTypeRepresentation itf ) { ReplaceUnique( ref itf ); } public override void Transform( ref TypeRepresentation[] tdArray ) { ReplaceUnique( ref tdArray ); } public override void Transform( ref InterfaceTypeRepresentation[] itfArray ) { ReplaceUnique( ref itfArray ); } public override void Transform( ref List< TypeRepresentation > tdLst ) { if(Visit( ref tdLst ) == SubstitutionAction.Unknown) { List< TypeRepresentation > lst = tdLst; for(int i = 0; i < lst.Count; i++) { TypeRepresentation td = lst[i]; Transform( ref td ); lst[i] = td; } } } //--// public override void Transform( ref FieldRepresentation fd ) { ReplaceUnique( ref fd ); } public override void Transform( ref InstanceFieldRepresentation fd ) { ReplaceUnique( ref fd ); } public override void Transform( ref StaticFieldRepresentation fd ) { ReplaceUnique( ref fd ); } public override void Transform( ref FieldRepresentation[] fdArray ) { ReplaceUnique( ref fdArray ); } public override void Transform( ref InstanceFieldRepresentation[] fdArray ) { ReplaceUnique( ref fdArray ); } //--// public override void Transform( ref MethodRepresentation md ) { ReplaceUnique( ref md ); } public override void Transform( ref MethodRepresentation[] mdArray ) { ReplaceUnique( ref mdArray ); } public override void Transform( ref List resLst ) { if(Visit( ref resLst ) == SubstitutionAction.Unknown) { List lst = resLst; for(int i = 0; i < lst.Count; i++) { MethodRepresentation res = lst[i]; Transform( ref res ); lst[i] = res; } } } public override void Transform( ref MethodImplRepresentation mi ) { if(Visit( ref mi ) == SubstitutionAction.Unknown) { mi.ApplyTransformation( this ); } } public override void Transform( ref MethodImplRepresentation[] miArray ) { if(Visit( ref miArray ) == SubstitutionAction.Unknown) { var array = miArray; // Get a local copy, because the original could change, due to the 'ref' argument. for(int i = 0; i < array.Length; i++) { Transform( ref array[i] ); } } } //--// public override void Transform( ref GenericParameterDefinition param ) { ClearPending(); Transform( ref param.Constraints ); } public override void Transform( ref GenericParameterDefinition[] paramArray ) { if(Visit( ref paramArray ) == SubstitutionAction.Unknown) { var array = paramArray; // Get a local copy, because the original could change, due to the 'ref' argument. for(int i = 0; i < array.Length; i++) { Transform( ref array[i] ); } } } //--// public override void Transform( ref CustomAttributeRepresentation ca ) { if(Visit( ref ca ) == SubstitutionAction.Unknown) { ca.ApplyTransformation( this ); } } public override void Transform( ref CustomAttributeRepresentation[] caArray ) { if(Visit( ref caArray ) == SubstitutionAction.Unknown) { var array = caArray; // Get a local copy, because the original could change, due to the 'ref' argument. for(int i = 0; i < array.Length; i++) { Transform( ref array[i] ); } } } //--// public override void Transform( ref CustomAttributeAssociationRepresentation caa ) { if(Visit( ref caa ) == SubstitutionAction.Unknown) { caa.ApplyTransformation( this ); } } public override void Transform( ref CustomAttributeAssociationRepresentation[] caaArray ) { if(Visit( ref caaArray ) == SubstitutionAction.Unknown) { var array = caaArray; // Get a local copy, because the original could change, due to the 'ref' argument. for(int i = 0; i < array.Length; i++) { Transform( ref array[i] ); } } } //--// public override void Transform( ref ResourceRepresentation res ) { if(Visit( ref res ) == SubstitutionAction.Unknown) { res.ApplyTransformation( this ); } } public override void Transform( ref List< ResourceRepresentation > resLst ) { if(Visit( ref resLst ) == SubstitutionAction.Unknown) { List< ResourceRepresentation > lst = resLst; for(int i = 0; i < lst.Count; i++) { ResourceRepresentation res = lst[i]; Transform( ref res ); lst[i] = res; } } } public override void Transform( ref ResourceRepresentation.Attributes val ) { ClearPending(); } public override void Transform( ref ResourceRepresentation.Pair[] pairArray ) { if(Visit( ref pairArray ) == SubstitutionAction.Unknown) { var array = pairArray; // Get a local copy, because the original could change, due to the 'ref' argument. for(int i = 0; i < array.Length; i++) { TransformGeneric( ref array[i] ); } } } //--// public override void Transform( ref VTable vTable ) { if(Visit( ref vTable ) == SubstitutionAction.Unknown) { vTable.ApplyTransformation( this ); } } public override void Transform( ref VTable.InterfaceMap iMap ) { ClearPending(); Transform( ref iMap.Interface ); Transform( ref iMap.MethodPointers ); } public override void Transform( ref GCInfo gi ) { ClearPending(); } public override void Transform( ref GCInfo.Kind giKind ) { ClearPending(); } public override void Transform( ref GCInfo.Pointer giPtr ) { ClearPending(); } public override void Transform( ref GCInfo.Pointer[] giPtrArray ) { ClearPending(); } public override void Transform( ref CodePointer cp ) { ClearPending(); } public override void Transform( ref CodePointer[] cpArray ) { ClearPending(); } //--// public override void Transform( ref TypeRepresentation.BuiltInTypes val ) { ClearPending(); } public override void Transform( ref TypeRepresentation.Attributes val ) { ClearPending(); } public override void Transform( ref TypeRepresentation.BuildTimeAttributes val ) { ClearPending(); } public override void Transform( ref TypeRepresentation.GenericContext gc ) { if(Visit( ref gc ) == SubstitutionAction.Unknown) { gc.ApplyTransformation( this ); } } public override void Transform( ref TypeRepresentation.InterfaceMap map ) { ClearPending(); Transform( ref map.Interface ); Transform( ref map.Methods ); } //--// public override void Transform( ref FieldRepresentation.Attributes val ) { ClearPending(); } public override void Transform( ref GenericParameterDefinition.Attributes val ) { ClearPending(); } public override void Transform( ref MethodRepresentation.Attributes val ) { ClearPending(); } public override void Transform( ref MethodRepresentation.BuildTimeAttributes val ) { ClearPending(); } public override void Transform( ref MethodRepresentation.GenericContext gc ) { if(Visit( ref gc ) == SubstitutionAction.Unknown) { gc.ApplyTransformation( this ); } } public override void Transform( ref MultiArrayReferenceTypeRepresentation.Dimension dim ) { ClearPending(); } public override void Transform( ref MultiArrayReferenceTypeRepresentation.Dimension[] dimArray ) { ClearPending(); } public override void Transform( ref Runtime.ActivationRecordEvents val ) { ClearPending(); } //--// // // TransformationContextForIR // public override void Transform( ref ControlFlowGraphState cfg ) { if(Visit( ref cfg ) == SubstitutionAction.Unknown) { ControlFlowGraphStateForCodeTransformation cfg2 = (ControlFlowGraphStateForCodeTransformation)cfg; cfg2.ApplyTransformation( this ); } } //--// public override void Transform( ref Operator op ) { if(Visit( ref op ) == SubstitutionAction.Unknown) { op.ApplyTransformation( this ); } } public override void Transform( ref Operator[] opArray ) { if(Visit( ref opArray, true ) == SubstitutionAction.Unknown) { var array = opArray; // Get a local copy, because the original could change, due to the 'ref' argument. for(int i = 0; i < array.Length; i++) { Transform( ref array[i] ); } } } public override void Transform( ref Annotation an ) { if(Visit( ref an ) == SubstitutionAction.Unknown) { an.ApplyTransformation( this ); } } public override void Transform( ref Annotation[] anArray ) { if(Visit( ref anArray, true ) == SubstitutionAction.Unknown) { var array = anArray; // Get a local copy, because the original could change, due to the 'ref' argument. for(int i = 0; i < array.Length; i++) { Transform( ref array[i] ); } } } //--// public override void Transform( ref Expression ex ) { if(Visit( ref ex ) == SubstitutionAction.Unknown) { ex.ApplyTransformation( this ); } } public override void Transform( ref ConstantExpression ex ) { if(Visit( ref ex ) == SubstitutionAction.Unknown) { ex.ApplyTransformation( this ); } } public override void Transform( ref VariableExpression ex ) { if(Visit( ref ex ) == SubstitutionAction.Unknown) { ex.ApplyTransformation( this ); } } public override void Transform( ref VariableExpression.DebugInfo val ) { if(Visit( ref val ) == SubstitutionAction.Unknown) { val.ApplyTransformation( this ); } } //--// public override void Transform( ref Expression[] exArray ) { if(Visit( ref exArray, true ) == SubstitutionAction.Unknown) { var array = exArray; // Get a local copy, because the original could change, due to the 'ref' argument. for(int i = 0; i < array.Length; i++) { Transform( ref array[i] ); } } } public override void Transform( ref VariableExpression[] exArray ) { if(Visit( ref exArray, true ) == SubstitutionAction.Unknown) { var array = exArray; // Get a local copy, because the original could change, due to the 'ref' argument. for(int i = 0; i < array.Length; i++) { Transform( ref array[i] ); } } } public override void Transform( ref List< ConstantExpression > exLst ) { if(Visit( ref exLst ) == SubstitutionAction.Unknown) { List< ConstantExpression > lst = exLst; for(int i = 0; i < lst.Count; i++) { ConstantExpression ex = lst[i]; Transform( ref ex ); lst[i] = ex; } } } //--// public override void Transform( ref BasicBlock bb ) { if(Visit( ref bb ) == SubstitutionAction.Unknown) { bb.ApplyTransformation( this ); } } public override void Transform( ref EntryBasicBlock bb ) { if(Visit( ref bb ) == SubstitutionAction.Unknown) { bb.ApplyTransformation( this ); } } public override void Transform( ref ExitBasicBlock bb ) { if(Visit( ref bb ) == SubstitutionAction.Unknown) { bb.ApplyTransformation( this ); } } public override void Transform( ref ExceptionHandlerBasicBlock bb ) { if(Visit( ref bb ) == SubstitutionAction.Unknown) { bb.ApplyTransformation( this ); } } public override void Transform( ref BasicBlock[] bbArray ) { if(Visit( ref bbArray ) == SubstitutionAction.Unknown) { var array = bbArray; // Get a local copy, because the original could change, due to the 'ref' argument. for(int i = 0; i < array.Length; i++) { Transform( ref array[i] ); } } } public override void Transform( ref ExceptionHandlerBasicBlock[] bbArray ) { if(Visit( ref bbArray ) == SubstitutionAction.Unknown) { var array = bbArray; // Get a local copy, because the original could change, due to the 'ref' argument. for(int i = 0; i < array.Length; i++) { Transform( ref array[i] ); } } } public override void Transform( ref BasicBlock.Qualifier val ) { ClearPending(); } //--// public override void Transform( ref ExceptionClause ec ) { if(Visit( ref ec ) == SubstitutionAction.Unknown) { ec.ApplyTransformation( this ); } } public override void Transform( ref ExceptionClause[] ecArray ) { if(Visit( ref ecArray ) == SubstitutionAction.Unknown) { var array = ecArray; // Get a local copy, because the original could change, due to the 'ref' argument. for(int i = 0; i < array.Length; i++) { Transform( ref array[i] ); } } } public override void Transform( ref ExceptionClause.ExceptionFlag val ) { ClearPending(); } //--// public override void Transform( ref CompilationConstraints val ) { ClearPending(); } public override void Transform( ref CompilationConstraints[] ccArray ) { if(Visit( ref ccArray ) == SubstitutionAction.Unknown) { var array = ccArray; // Get a local copy, because the original could change, due to the 'ref' argument. for(int i = 0; i < array.Length; i++) { Transform( ref array[i] ); } } } public override void Transform( ref Operator.OperatorCapabilities val ) { ClearPending(); } public override void Transform( ref Operator.OperatorLevel val ) { ClearPending(); } public override void Transform( ref BinaryOperator.ALU val ) { ClearPending(); } public override void Transform( ref UnaryOperator.ALU val ) { ClearPending(); } public override void Transform( ref CallOperator.CallKind val ) { ClearPending(); } public override void Transform( ref CompareAndSetOperator.ActionCondition val ) { ClearPending(); } //--// // // TransformationContextForCodeTransformation // public override void Transform( ref TypeSystemForCodeTransformation typeSystem ) { if(Visit( ref typeSystem ) == SubstitutionAction.Unknown) { typeSystem.ApplyTransformation( this ); } } //--// public override void Transform( ref StackLocationExpression.Placement val ) { ClearPending(); } public override void Transform( ref ConditionCodeExpression.Comparison val ) { ClearPending(); } public override void Transform( ref PiOperator.Relation val ) { ClearPending(); } //--// public override void Transform( ref DataManager dataManager ) { if(Visit( ref dataManager ) == SubstitutionAction.Unknown) { dataManager.ApplyTransformation( this ); } } public override void Transform( ref DataManager.Attributes val ) { ClearPending(); } public override void Transform( ref DataManager.ObjectDescriptor od ) { if(Visit( ref od ) == SubstitutionAction.Unknown) { od.ApplyTransformation( this ); } } public override void Transform( ref DataManager.ArrayDescriptor ad ) { if(Visit( ref ad ) == SubstitutionAction.Unknown) { ad.ApplyTransformation( this ); } } //--// public override void Transform( ref ImageBuilders.Core imageBuilder ) { if(Visit( ref imageBuilder ) == SubstitutionAction.Unknown) { imageBuilder.ApplyTransformation( this ); } } public override void Transform( ref ImageBuilders.CompilationState cs ) { if(Visit( ref cs ) == SubstitutionAction.Unknown) { cs.ApplyTransformation( this ); } } public override void Transform( ref ImageBuilders.SequentialRegion reg ) { if(Visit( ref reg ) == SubstitutionAction.Unknown) { reg.ApplyTransformation( this ); } } public override void Transform( ref ImageBuilders.ImageAnnotation an ) { if(Visit( ref an ) == SubstitutionAction.Unknown) { an.ApplyTransformation( this ); } } public override void Transform( ref ImageBuilders.CodeConstant cc ) { if(Visit( ref cc ) == SubstitutionAction.Unknown) { cc.ApplyTransformation( this ); } } public override void Transform( ref ImageBuilders.SequentialRegion[] regArray ) { if(Visit( ref regArray ) == SubstitutionAction.Unknown) { var array = regArray; // Get a local copy, because the original could change, due to the 'ref' argument. for(int i = 0; i < array.Length; i++) { Transform( ref array[i] ); } } } public override void Transform( ref List< ImageBuilders.SequentialRegion > regLst ) { if(Visit( ref regLst ) == SubstitutionAction.Unknown) { List< ImageBuilders.SequentialRegion > lst = regLst; for(int i = 0; i < lst.Count; i++) { ImageBuilders.SequentialRegion reg = lst[i]; Transform( ref reg ); lst[i] = reg; } } } public override void Transform( ref List< ImageBuilders.ImageAnnotation > anLst ) { if(Visit( ref anLst ) == SubstitutionAction.Unknown) { List< ImageBuilders.ImageAnnotation > lst = anLst; for(int i = 0; i < lst.Count; i++) { ImageBuilders.ImageAnnotation an = lst[i]; Transform( ref an ); lst[i] = an; } } } public override void Transform( ref List< ImageBuilders.CodeConstant > ccLst ) { if(Visit( ref ccLst ) == SubstitutionAction.Unknown) { List< ImageBuilders.CodeConstant > lst = ccLst; for(int i = 0; i < lst.Count; i++) { ImageBuilders.CodeConstant cc = lst[i]; Transform( ref cc ); lst[i] = cc; } } } public override void Transform( ref List< Runtime.Memory.Range > mrLst ) { if(Visit( ref mrLst ) == SubstitutionAction.Unknown) { List< Runtime.Memory.Range > lst = mrLst; for(int i = 0; i < lst.Count; i++) { Runtime.Memory.Range mr = lst[i]; TransformGeneric( ref mr ); lst[i] = mr; } } } public override void Transform( ref Runtime.MemoryAttributes val ) { ClearPending(); } public override void Transform( ref Runtime.MemoryAttributes[] maArray ) { if(Visit( ref maArray ) == SubstitutionAction.Unknown) { var array = maArray; // Get a local copy, because the original could change, due to the 'ref' argument. for(int i = 0; i < array.Length; i++) { Transform( ref array[i] ); } } } public override void Transform( ref Runtime.MemoryUsage val ) { ClearPending(); } public override void Transform( ref Runtime.MemoryUsage[] muArray ) { if(Visit( ref muArray ) == SubstitutionAction.Unknown) { var array = muArray; // Get a local copy, because the original could change, due to the 'ref' argument. for(int i = 0; i < array.Length; i++) { Transform( ref array[i] ); } } } public override void Transform( ref Abstractions.PlacementRequirements pr ) { if(Visit( ref pr ) == SubstitutionAction.Unknown) { pr.ApplyTransformation( this ); } } public override void Transform( ref Abstractions.RegisterDescriptor regDesc ) { if(Visit( ref regDesc ) == SubstitutionAction.Unknown) { regDesc.ApplyTransformation( this ); } } public override void Transform( ref Abstractions.RegisterDescriptor[] regDescArray ) { if(Visit( ref regDescArray ) == SubstitutionAction.Unknown) { var array = regDescArray; // Get a local copy, because the original could change, due to the 'ref' argument. for(int i = 0; i < array.Length; i++) { Transform( ref array[i] ); } } } public override void Transform( ref Abstractions.RegisterClass val ) { ClearPending(); } public override void Transform( ref Abstractions.CallingConvention.Direction val ) { ClearPending(); } //--// protected override void TransformArray( ref Array arrayIn ) { if(Visit( ref arrayIn ) == SubstitutionAction.Unknown) { var array = arrayIn; // Get a local copy, because the original could change, due to the 'ref' argument. for(int i = 0; i < array.Length; i++) { object obj = array.GetValue( i ); object obj2 = obj; if(obj != null) { Type elemType = obj.GetType(); if(elemType.IsValueType || elemType == typeof(string)) break; } Transform( ref obj2 ); if(Object.ReferenceEquals( obj, obj2 ) == false) { array.SetValue( obj2, i ); } } } } //--// protected override GrowOnlyHashTable< Type, System.Reflection.MethodInfo > GetMethodInfoTable() { if(s_handlers == null) { s_handlers = BuildMethodInfoTable(); } return s_handlers; } protected override DynamicTransform GetDynamicTransform() { if(s_dynamicTransform == null) { s_dynamicTransform = BuildDynamicTransform(); } return s_dynamicTransform; } protected override object TransformThroughReflection( object obj ) { if(Visit( ref obj ) == SubstitutionAction.Unknown) { TransformFields( obj, obj.GetType() ); } return obj; } //--// // // Access Methods // internal GrowOnlySet< object > Visited { get { return m_visited; } } protected object[] FullContext { get { object[] res = new object[m_contextStackSize]; for(int idxFwd = 0, idxBck = m_contextStackSize; --idxBck >= 0; idxFwd++) { res[idxFwd] = m_contextStack[idxBck]; } return res; } } //--// // // Debug Methods // internal string GetContextDump() { System.Text.StringBuilder sb = new System.Text.StringBuilder(); for(int i = 0; i < m_contextStackSize; i++) { if(i != 0) { sb.Append( " => " ); } sb.Append( m_contextStack[i] ); } return sb.ToString(); } } } ================================================ FILE: Zelig/Zelig/CompileTime/CodeGenerator/CodeTransformation/TypeSystemForCodeTransformation.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // #if DEBUG #define VERIFY_REDUCTION #endif //#define VERIFY_REDUCTION #define DEBUG_IMAGEBUILDER_PERF #define ARMv7M_BUILD__LLVM_IR_ONLY namespace Microsoft.Zelig.CodeGeneration.IR { using System; using System.Collections.Generic; using System.Runtime.CompilerServices; using Microsoft.Zelig.MetaData; using Microsoft.Zelig.MetaData.Normalized; using Microsoft.Zelig.Runtime.TypeSystem; using Microsoft.Zelig.LLVM; public delegate void ControlFlowGraphEnumerationCallback( ControlFlowGraphStateForCodeTransformation cfg ); public partial class TypeSystemForCodeTransformation : TypeSystemForIR { internal sealed class FlagProhibitedUses : Transformations.ScanTypeSystem { // // State // // // Constructor Methods // internal FlagProhibitedUses( TypeSystemForCodeTransformation typeSystem ) : base( typeSystem, typeof( FlagProhibitedUses ) ) { } //--// protected override object ShouldSubstitute( object target, out SubstitutionAction result ) { if(target == m_typeSystem.ReachabilitySet.ProhibitedSet) { result = SubstitutionAction.Keep; } else { if(m_typeSystem.ReachabilitySet.IsProhibited( target )) { throw TypeConsistencyErrorException.Create( "Found unexpected reference to {0} from {1}", target, GetContextDump( ) ); } result = SubstitutionAction.Unknown; } return null; } } public class DelayedType : ConstantExpression.DelayedValue, ITransformationContextTarget, CompilationSteps.ICallClosureComputationTarget { // // State // TypeSystemForCodeTransformation m_owner; VTable m_vTable; // // Constructor Methods // internal DelayedType( TypeSystemForCodeTransformation owner, VTable vTable ) { m_owner = owner; m_vTable = vTable; } //--// // // MetaDataEquality Methods // public override bool Equals( object obj ) { if(obj is DelayedType) { var other = ( DelayedType )obj; if(m_vTable == other.m_vTable) { return true; } } return false; } public override int GetHashCode( ) { return m_vTable.GetHashCode( ); } // // Helper Methods // //--// void ITransformationContextTarget.ApplyTransformation( TransformationContext context ) { var context2 = ( TransformationContextForCodeTransformation )context; context2.Push( this ); context2.Transform( ref m_owner ); context2.Transform( ref m_vTable ); context2.Pop( ); } void CompilationSteps.ICallClosureComputationTarget.ExpandClosure( CompilationSteps.ComputeCallsClosure.Context context ) { context.CoverObject( m_vTable ); } //--// private DataManager.ObjectDescriptor TryToGetValue( ) { TypeRepresentation td; var odVTable = m_owner.DataManagerInstance.ConvertToObjectDescriptor( m_vTable, out td ) as DataManager.ObjectDescriptor; if(odVTable != null) { return odVTable.Get( (InstanceFieldRepresentation)m_owner.WellKnownFields.VTable_Type ) as DataManager.ObjectDescriptor; } return null; } // // Access Methods // public override bool CanEvaluate { get { return TryToGetValue( ) != null; } } public override object Value { get { return TryToGetValue( ); } } public VTable VTable { get { return m_vTable; } } //--// // // Debug Methods // public override string ToString( ) { return string.Format( "", m_vTable ); } } public class DelayedSize : ConstantExpression.DelayedValue, ITransformationContextTarget, CompilationSteps.ICallClosureComputationTarget { // // State // TypeRepresentation m_td; // // Constructor Methods // internal DelayedSize( TypeRepresentation td ) { m_td = td; } //--// // // MetaDataEquality Methods // public override bool Equals( object obj ) { if(obj is DelayedSize) { var other = ( DelayedSize )obj; if(m_td == other.m_td) { return true; } } return false; } public override int GetHashCode( ) { return m_td.GetHashCode( ); } // // Helper Methods // //--// void ITransformationContextTarget.ApplyTransformation( TransformationContext context ) { context.Push( this ); context.Transform( ref m_td ); context.Pop( ); } void CompilationSteps.ICallClosureComputationTarget.ExpandClosure( CompilationSteps.ComputeCallsClosure.Context context ) { context.CoverObject( m_td ); } //--// // // Access Methods // public override bool CanEvaluate { get { return m_td.ValidLayout; } } public override object Value { get { return m_td.Size; } } public TypeRepresentation Type { get { return m_td; } } //--// // // Debug Methods // public override string ToString( ) { return string.Format( "", m_td ); } } public class DelayedOffset : ConstantExpression.DelayedValue, ITransformationContextTarget, CompilationSteps.ICallClosureComputationTarget { // // State // FieldRepresentation m_fd; // // Constructor Methods // internal DelayedOffset( FieldRepresentation fd ) { m_fd = fd; } //--// // // MetaDataEquality Methods // public override bool Equals( object obj ) { if(obj is DelayedOffset) { var other = ( DelayedOffset )obj; if(m_fd == other.m_fd) { return true; } } return false; } public override int GetHashCode( ) { return m_fd.GetHashCode( ); } // // Helper Methods // //--// void ITransformationContextTarget.ApplyTransformation( TransformationContext context ) { context.Push( this ); context.Transform( ref m_fd ); context.Pop( ); } void CompilationSteps.ICallClosureComputationTarget.ExpandClosure( CompilationSteps.ComputeCallsClosure.Context context ) { context.CoverObject( m_fd ); } //--// // // Access Methods // public override bool CanEvaluate { get { return m_fd.ValidLayout; } } public override object Value { get { return m_fd.Offset; } } public FieldRepresentation Field { get { return m_fd; } } //--// // // Debug Methods // public override string ToString( ) { return string.Format( "", m_fd ); } } public class LinearHierarchyBuilder { List m_lst; TypeSystemForCodeTransformation m_typeSystem; public LinearHierarchyBuilder( List lst, TypeSystemForCodeTransformation typeSystem ) { m_lst = lst; m_typeSystem = typeSystem; m_lst.RemoveAll( tr => { CustomAttributeRepresentation sfpf = tr.FindCustomAttribute( typeSystem.WellKnownTypes.Microsoft_Zelig_Runtime_SingletonFactoryPlatformFilterAttribute ); if(sfpf != null) { object obj = sfpf.GetNamedArg( "PlatformVersionFilter" ); if(obj != null) { uint filter = (uint)obj; if((filter & typeSystem.PlatformAbstraction.PlatformVersion) != typeSystem.PlatformAbstraction.PlatformVersion) { // This type is not an allowed extension for the current platform return true; } } } CustomAttributeRepresentation pf = tr.FindCustomAttribute( typeSystem.WellKnownTypes.Microsoft_Zelig_Runtime_ProductFilterAttribute ); if(pf != null) { object obj = pf.GetNamedArg( "ProductFilter" ); if(obj != null) { string product = (string)obj; if(product != typeSystem.Product.FullName) { // This type is not an allowed extension for the current platform return true; } } } return false; } ); } public TypeRepresentation Build( ) { var hierarchy = new LinkedList< TypeRepresentation >(); // // There can be only one sealed type in a linear hierachy // foreach(TypeRepresentation target in m_lst) { TypeRepresentation type; if(m_typeSystem.IsSealedType( target, out type )) { if(hierarchy.Count > 0) { return null; } hierarchy.AddFirst( new LinkedListNode( type ) ); } } // // initialize the hierarchy with the last item in the input list // if(hierarchy.Count == 0) { TypeRepresentation last = m_lst[ m_lst.Count - 1 ]; hierarchy.AddFirst( last ); m_lst.Remove( last ); } // // Scan the input list and find the father of the last item in the hierarchy and the son of the first item. // At every step we need to always grow the hierarchy of at least one item, or else we are looking at a // disjoint inheritance line or a tree // int previousCount; do { previousCount = hierarchy.Count; TypeRepresentation first = hierarchy.First.Value; TypeRepresentation last = hierarchy.Last .Value; foreach(TypeRepresentation item in m_lst) { if(last.Extends == item) { hierarchy.AddLast( item ); last = item; } else if(item.Extends == first) { hierarchy.AddFirst( item ); first = item; } } } while(previousCount < hierarchy.Count); // // if we used all objects in the input list, then we have a linear hierarchy // if(m_lst.Count == hierarchy.Count) { return hierarchy.First.Value; } return null; } } public class MethodCall { private readonly MethodRepresentation m_target; private readonly int m_level; //--// public MethodCall( MethodRepresentation target, int level ) { m_target = target; m_level = level; } public MethodRepresentation Target { get { return m_target; } } public int Level { get { return m_level; } } public override string ToString( ) { return String.Format( "[{0}]:{1}", m_level, m_target.ToShortStringNoReturnValue() ); } } //--// // // State // public static readonly object Lock = new Object( ); private Type m_activeProduct; private Abstractions.Platform m_activePlatform; private Abstractions.CallingConvention m_activeCallingConvention; private PendingAnalysisQueue< ByteCodeConverter > m_pendingByteCodeAnalysis; private Reachability m_reachabilityEstimated; private Reachability m_reachability; private ImageBuilders.Core m_imageBuilder; private DataManager m_dataManager; private GrowOnlyHashTable < TypeRepresentation , GrowOnlyHashTable< object, ConstantExpression > > m_uniqueConstants; private GrowOnlyHashTable < BaseRepresentation , InstanceFieldRepresentation > m_globalRootMap; private ConstantExpression m_globalRoot; private GrowOnlyHashTable < Type , TypeRepresentation > m_lookupType; private GrowOnlyHashTable < Type , string > m_lookupTypeLinkedToRuntime; private GrowOnlySet < Annotation > m_uniqueAnnotations; private GrowOnlyHashTable < BaseRepresentation , Abstractions.PlacementRequirements > m_placementRequirements; private GrowOnlyHashTable < MethodRepresentation, CustomAttributeRepresentation > m_hardwareExceptionHandlers; private GrowOnlyHashTable < MethodRepresentation, CustomAttributeRepresentation > m_debuggerHookHandlers; private GrowOnlyHashTable < MethodRepresentation, CustomAttributeRepresentation > m_singletonFactories; private GrowOnlyHashTable < TypeRepresentation , TypeRepresentation > m_singletonFactoriesFallback; private GrowOnlyHashTable < TypeRepresentation , TypeRepresentation > m_garbageCollectionExtensions; private GrowOnlySet < FieldRepresentation > m_garbageCollectionExclusions; private GrowOnlySet < TypeRepresentation > m_referenceCountingExcludedTypes; private GrowOnlyHashTable < string , List< MethodRepresentation > > m_automaticReferenceCountingExclusions; private GrowOnlyHashTable < TypeRepresentation , CustomAttributeRepresentation > m_memoryMappedPeripherals; private GrowOnlyHashTable < FieldRepresentation , CustomAttributeRepresentation > m_registerAttributes; private GrowOnlyHashTable < TypeRepresentation , CustomAttributeRepresentation > m_memoryMappedBitFieldPeripherals; private GrowOnlyHashTable < FieldRepresentation , BitFieldDefinition > m_bitFieldRegisterAttributes; //--// private GrowOnlyHashTable < TypeRepresentation , List< TypeRepresentation > > m_directDescendants; private GrowOnlyHashTable < TypeRepresentation , List< TypeRepresentation > > m_concreteImplementations; private GrowOnlyHashTable < TypeRepresentation , List< TypeRepresentation > > m_nestedClasses; private GrowOnlyHashTable < TypeRepresentation , List< TypeRepresentation > > m_interfaceImplementors; private GrowOnlyHashTable < TypeRepresentation , List< TypeRepresentation > > m_genericTypeInstantiations; private GrowOnlyHashTable < MethodRepresentation, List< MethodRepresentation > > m_genericMethodInstantiations; private GrowOnlyHashTable < TypeRepresentation , TypeRepresentation > m_forcedDevirtualizations; private GrowOnlySet < TypeRepresentation > m_implicitInstances; private GrowOnlyHashTable < MethodRepresentation, List< MethodCall > > m_callersToMethod; private GrowOnlyHashTable < MethodRepresentation, List< MethodCall > > m_callsFromMethod; private List < string > m_nativeImportDirectories; private List < string > m_nativeImportLibraries; //Miguel: Field added to keep LLVM info through the whole process private LLVMModuleManager m_module; //--// // // Constructor Methods // public TypeSystemForCodeTransformation( IEnvironmentProvider env ) : base( env ) { m_dataManager = new DataManager( this ); m_reachability = new Reachability( ); m_uniqueConstants = HashTableFactory.NewWithReferenceEquality>( ); m_globalRootMap = HashTableFactory.NewWithReferenceEquality( ); m_lookupType = HashTableFactory.NewWithReferenceEquality( ); m_lookupTypeLinkedToRuntime = HashTableFactory.NewWithReferenceEquality( ); m_uniqueAnnotations = SetFactory.New( ); m_placementRequirements = HashTableFactory.New( ); m_hardwareExceptionHandlers = HashTableFactory.New( ); m_debuggerHookHandlers = HashTableFactory.New( ); m_singletonFactories = HashTableFactory.New( ); m_singletonFactoriesFallback = HashTableFactory.New( ); m_garbageCollectionExtensions = HashTableFactory.New( ); m_garbageCollectionExclusions = SetFactory.New( ); m_referenceCountingExcludedTypes = SetFactory.New( ); m_automaticReferenceCountingExclusions = HashTableFactory.New>( ); m_memoryMappedPeripherals = HashTableFactory.New( ); m_registerAttributes = HashTableFactory.New( ); m_memoryMappedBitFieldPeripherals = HashTableFactory.New( ); m_bitFieldRegisterAttributes = HashTableFactory.New( ); m_callersToMethod = HashTableFactory.NewWithReferenceEquality>( ); m_callsFromMethod = HashTableFactory.NewWithReferenceEquality>( ); m_nativeImportDirectories = new List( ); m_nativeImportLibraries = new List( ); m_module = new LLVMModuleManager( this, "" ); //--// foreach( System.Reflection.FieldInfo fi in ReflectionHelper.GetAllPublicInstanceFields( typeof( WellKnownTypes ) ) ) { var attrib = ReflectionHelper.GetAttribute( fi, false ); if( attrib != null ) { m_lookupTypeLinkedToRuntime[ attrib.Target ] = fi.Name; } } } // // Helper Methods // protected override void InitializeForMetaDataImport( ) { base.InitializeForMetaDataImport( ); m_pendingByteCodeAnalysis = new PendingAnalysisQueue( ); } protected override void RegisterMetaDataNotifications( ) { base.RegisterMetaDataNotifications( ); //--// WellKnownTypes wkt = this.WellKnownTypes; RegisterForTypeLayoutDelegation( wkt.System_String, delegate( TypeRepresentation td, GrowOnlySet history ) { // // Strings are a bit strange: their base size is not the same of the size of all their fields... // td.Size = 2 * sizeof( uint ); td.VirtualTable.ElementSize = sizeof( char ); WellKnownFields wkf = this.WellKnownFields; wkf.StringImpl_ArrayLength.Offset = 0 * sizeof( uint ); wkf.StringImpl_StringLength.Offset = 1 * sizeof( uint ); wkf.StringImpl_FirstChar.Offset = 2 * sizeof( uint ); return true; } ); RegisterForTypeLayoutDelegation( wkt.Microsoft_Zelig_Runtime_TypeSystem_GlobalRoot, delegate( TypeRepresentation td, GrowOnlySet history ) { Array.Sort( td.Fields, ( a, b ) => a.Name.CompareTo( b.Name ) ); return false; } ); //--// var cache = GetEnvironmentService( ); cache.Register( this ); } protected override void CleanupAfterMetaDataImport( ) { base.CleanupAfterMetaDataImport( ); m_pendingByteCodeAnalysis = null; } //--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--// internal void NotifyCompilationPhaseInner( CompilationSteps.PhaseDriver phase ) { NotifyCompilationPhase( phase ); } protected virtual void NotifyCompilationPhase( CompilationSteps.PhaseDriver phase ) { } public virtual SourceCodeTracker GetSourceCodeTracker( ) { return null; } //--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--// public override void ResolveAll( ) { while( true ) { base.ResolveAll( ); if( m_pendingByteCodeAnalysis.Dispatch( ) ) { continue; } // // HACK: try to mirror generic instantiations between class extensions and their targets... // if( IR.CompilationSteps.ApplyClassExtensions.Hack_MirrorGenericInstantiations( this ) ) { continue; } break; } CheckWellKnownMethods( ); CheckWellKnownFields( ); CleanupAfterMetaDataImport( ); } [System.Diagnostics.Conditional( "DEBUG" )] [System.Diagnostics.Conditional( "CHECKS_ASSERT" )] private void CheckWellKnownMethods( ) { WellKnownMethods target = this.WellKnownMethods; foreach( System.Reflection.FieldInfo fi in ReflectionHelper.GetAllPublicInstanceFields( target.GetType( ) ) ) { if( fi.GetValue( target ) == null ) { throw TypeConsistencyErrorException.Create( "Cannot find method to associate with 'WellKnownMethods.{0}'", fi.Name ); } } } [System.Diagnostics.Conditional( "DEBUG" )] [System.Diagnostics.Conditional( "CHECKS_ASSERT" )] private void CheckWellKnownFields( ) { WellKnownFields target = this.WellKnownFields; foreach( System.Reflection.FieldInfo fi in ReflectionHelper.GetAllPublicInstanceFields( target.GetType( ) ) ) { if( fi.GetValue( target ) == null ) { throw TypeConsistencyErrorException.Create( "Cannot find field to associate with 'WellKnownFields.{0}'", fi.Name ); } } } //--//--// protected override void PerformDelayedMethodAnalysis( MethodRepresentation target, ref ConversionContext context ) { base.PerformDelayedMethodAnalysis( target, ref context ); MetaDataMethodBase metadata = GetAssociatedMetaData( target ); if( metadata.Instructions != null ) { ConvertByteCodeToIR( target, context, metadata.Locals, metadata.DebugInformation ); } } //--// private void ConvertByteCodeToIR( MethodRepresentation md, ConversionContext context, SignatureType[] locals, Debugging.MethodDebugInfo debugInfo ) { if( md.Code == null ) { var converter = new ByteCodeConverter( this, ref context, md, locals, debugInfo ); converter.ExpandByteCodeArguments( ); this.QueueDelayedByteCodeAnalysis( converter, ref context ); } } //--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--// internal void QueueDelayedByteCodeAnalysis( ByteCodeConverter converter, ref ConversionContext context ) { m_pendingByteCodeAnalysis.Schedule( converter, ref context, delegate( ByteCodeConverter target, ref ConversionContext ctx ) { target.PerformDelayedByteCodeAnalysis( ); } ); } //--// public void EnumerateFlowGraphs( ControlFlowGraphEnumerationCallback callback ) { foreach( TypeRepresentation td in this.Types ) { foreach( MethodRepresentation md in td.Methods ) { var cfg = TypeSystemForCodeTransformation.GetCodeForMethod( md ); if( cfg != null ) { callback( cfg ); } } } } public void BuildCrossReference( ) { BuildMethodAndInterfaceMaps( ); BuildGenericInstantiationTables( ); BuildHierarchyTables( ); } public void BuildMethodAndInterfaceMaps( ) { foreach( TypeRepresentation td in this.Types ) { td.ClearMethodTableAndInterfaceMaps( this ); } foreach( TypeRepresentation td in this.Types ) { td.BuildMethodTableAndInterfaceMaps( this ); } } public void BuildGenericInstantiationTables( ) { m_genericTypeInstantiations = HashTableFactory.NewWithReferenceEquality>( ); m_genericMethodInstantiations = HashTableFactory.NewWithReferenceEquality>( ); foreach( TypeRepresentation td in this.Types ) { TypeRepresentation tdTemplate = td.GenericTemplate; if( tdTemplate != null ) { HashTableWithListFactory.AddUnique( m_genericTypeInstantiations, tdTemplate, td ); } foreach( MethodRepresentation md in td.Methods ) { MethodRepresentation mdTemplate = md.GenericTemplate; if( mdTemplate != null ) { HashTableWithListFactory.AddUnique( m_genericMethodInstantiations, mdTemplate, md ); } } } } public void BuildHierarchyTables( ) { m_directDescendants = HashTableFactory.NewWithReferenceEquality>( ); m_concreteImplementations = HashTableFactory.NewWithReferenceEquality>( ); m_interfaceImplementors = HashTableFactory.NewWithReferenceEquality>( ); m_nestedClasses = HashTableFactory.NewWithReferenceEquality>( ); m_forcedDevirtualizations = HashTableFactory.NewWithReferenceEquality( ); m_implicitInstances = SetFactory.NewWithReferenceEquality( ); // // BUGBUG: Generic method instantiations are not captured under the Types hierarchy, they are kind of free-floating methods... // foreach( TypeRepresentation td in this.Types ) { TypeRepresentation td2; td2 = td.Extends; if( td2 != null ) { HashTableWithListFactory.AddUnique( m_directDescendants, td2, td ); } if( td.IsAbstract == false ) { HashTableWithListFactory.AddUnique( m_concreteImplementations, td, td ); while( td2 != null ) { HashTableWithListFactory.AddUnique( m_concreteImplementations, td2, td ); td2 = td2.Extends; } } td2 = td.EnclosingClass; if( td2 != null ) { HashTableWithListFactory.AddUnique( m_nestedClasses, td2, td ); } if( td is InterfaceTypeRepresentation ) { HashTableWithListFactory.Create( m_interfaceImplementors, td ); } else { AddInterfaces( td, td.Interfaces ); } } foreach( TypeRepresentation td in this.Types ) { if( td.HasBuildTimeFlag( TypeRepresentation.BuildTimeAttributes.ForceDevirtualization ) ) { var lst = CollectConcreteImplementations( td ); switch( lst.Count ) { case 0: throw TypeConsistencyErrorException.Create( "'{0}' is marked as ForcedInstantiation, but no candidate was found", td ); case 1: m_forcedDevirtualizations[ td ] = lst[ 0 ]; break; default: // // if we have more than one // var mostDerived = new LinearHierarchyBuilder( lst, this ).Build(); if( mostDerived != null ) { m_forcedDevirtualizations[ td ] = mostDerived; break; } var sb = new System.Text.StringBuilder( ); bool fFirst = true; foreach( var tdCandidate in lst ) { if( fFirst ) { fFirst = false; } else { sb.AppendFormat( ", " ); } sb.AppendFormat( "{0}", tdCandidate.FullNameWithAbbreviation ); } throw TypeConsistencyErrorException.Create( "'{0}' is marked as ForcedInstantiation, but found multiple candidates: {1}", td, sb ); } } if( td.HasBuildTimeFlag( TypeRepresentation.BuildTimeAttributes.ImplicitInstance ) ) { m_implicitInstances.Insert( td ); } } } private void AddInterfaces( TypeRepresentation td, InterfaceTypeRepresentation[] itfArray ) { foreach( var itf in itfArray ) { HashTableWithListFactory.AddUnique( m_interfaceImplementors, itf, td ); AddInterfaces( td, itf.Interfaces ); } } public TypeRepresentation FindSingleConcreteImplementation( TypeRepresentation td ) { List< TypeRepresentation > lst = CollectConcreteImplementations( td ); if( lst.Count == 1 ) { return lst[ 0 ]; } return null; } public List CollectConcreteImplementations( TypeRepresentation td ) { var lst = new List( ); CollectConcreteImplementations( td, lst ); // // If there was a fallback, then there will be at list one item in the list. // if(lst.Count >= 1) { TypeRepresentation tdFallback; // // If there is more than one item, try and remove the fallback. // if(lst.Count > 1) { if(m_singletonFactoriesFallback.TryGetValue( td, out tdFallback )) { lst.Remove( tdFallback ); } } // Check with the configuration provider that any choice specified using // -CompilationOption is enforcable. Match the whole hyerarchy. var cfgProv = GetEnvironmentService( ); object match; if(cfgProv.GetValue( td.Name, out match ) && match is string) { string target = (string)match; var newList = new List( ); foreach(var tdCandidate in lst) { var source = tdCandidate; while(source != null) { if(source.Name == target) { newList.Add( tdCandidate ); break; } source = source.Extends; } } if(newList.Count == 0) { throw TypeConsistencyErrorException.Create( "Type {0} mandated by explicit configration option {1) could not be found", target, td.Name ); } lst = newList; } } return lst; } private void CollectConcreteImplementations( TypeRepresentation td, List lst ) { List< TypeRepresentation > tdLst; if( td.IsAbstract == false ) { lst.Add( td ); } if( m_directDescendants.TryGetValue( td, out tdLst ) ) { foreach( TypeRepresentation tdSub in tdLst ) { CollectConcreteImplementations( tdSub, lst ); } } } //--// internal void ExpandCallsClosure( CompilationSteps.ComputeCallsClosure computeCallsClosure ) { ExpandCallsClosure_GlobalRoot ( computeCallsClosure ); ExpandCallsClosure_PlacementRequirements( computeCallsClosure ); ExpandCallsClosure_HardwareExceptions ( computeCallsClosure ); ExpandCallsClosure_HardwareModel ( computeCallsClosure ); ExpandCallsClosure_GarbageCollection ( computeCallsClosure ); ExpandCallsClosure_ExportedMethods ( computeCallsClosure ); m_activeCallingConvention.ExpandCallsClosure( computeCallsClosure ); m_activePlatform .ExpandCallsClosure( computeCallsClosure ); } private void ExpandCallsClosure_GlobalRoot( CompilationSteps.ComputeCallsClosure computeCallsClosure ) { computeCallsClosure.Expand( m_globalRoot ); computeCallsClosure.Expand( m_globalRoot.Type ); computeCallsClosure.Expand( m_globalRoot.Value ); computeCallsClosure.ExpandValueIfKeyIsReachable( m_globalRootMap ); } private void ExpandCallsClosure_PlacementRequirements( CompilationSteps.ComputeCallsClosure computeCallsClosure ) { computeCallsClosure.ExpandValueIfKeyIsReachable( m_placementRequirements ); } private void ExpandCallsClosure_HardwareExceptions( CompilationSteps.ComputeCallsClosure computeCallsClosure ) { computeCallsClosure.Expand( TryGetHandler( Runtime.HardwareException.Reset ) ); } private void ExpandCallsClosure_ExportedMethods( CompilationSteps.ComputeCallsClosure computeCallsClosure ) { this.EnumerateMethods( delegate( MethodRepresentation md ) { if(md.HasBuildTimeFlag( MethodRepresentation.BuildTimeAttributes.Exported )) { computeCallsClosure.Expand( md ); } } ); } private void ExpandCallsClosure_HardwareModel( CompilationSteps.ComputeCallsClosure computeCallsClosure ) { computeCallsClosure.ExpandValueIfKeyIsReachable( m_memoryMappedPeripherals ); computeCallsClosure.ExpandValueIfKeyIsReachable( m_registerAttributes ); computeCallsClosure.ExpandValueIfKeyIsReachable( m_memoryMappedBitFieldPeripherals ); computeCallsClosure.ExpandValueIfKeyIsReachable( m_bitFieldRegisterAttributes ); } private void ExpandCallsClosure_GarbageCollection( CompilationSteps.ComputeCallsClosure computeCallsClosure ) { computeCallsClosure.ExpandValueIfKeyIsReachable( m_garbageCollectionExtensions ); } //--// public override void RefreshHashCodesAfterTypeSystemRemapping( ) { base.RefreshHashCodesAfterTypeSystemRemapping( ); Annotation[] array = m_uniqueAnnotations.ToArray( ); m_uniqueAnnotations.Clear( ); foreach( var an in array ) { if( IsUseProhibited( an ) == false ) { m_uniqueAnnotations.Insert( an ); } } } internal bool IsUseProhibited( object obj ) { return m_reachability.IsProhibited( obj ); } internal void ProhibitUse( object obj ) { m_reachability.ExpandProhibition( obj ); } internal void EstimateReduction( ) { m_reachabilityEstimated = m_reachability.CloneForProhibitionEstimation( ); Reduce( m_reachabilityEstimated, false ); } internal void PerformReduction( ) { m_reachabilityEstimated = null; Reduce( m_reachability, true ); } protected override void Reduce( TypeSystem.Reachability reachability, bool fApply ) { base.Reduce( reachability, fApply ); //--// m_dataManager.Reduce( reachability, fApply ); //--// var uniqueConstants = m_uniqueConstants.CloneSettings( ); foreach( TypeRepresentation td in m_uniqueConstants.Keys ) { if( reachability.Contains( td ) ) { var ht = HashTableFactory.New( ); var htOld = m_uniqueConstants[ td ]; foreach( object obj in htOld.Keys ) { var ex = htOld[ obj ]; if( reachability.Contains( ex ) ) { object val = ex.Value; if( val != null && reachability.Contains( val ) == false ) { if( reachability.IsProhibited( val ) ) { continue; } if( val is DataManager.DataDescriptor ) { continue; } } ht[ obj ] = ex; } } if( ht.Count > 0 ) { uniqueConstants[ td ] = ht; } } } if( fApply ) { m_uniqueConstants = uniqueConstants; } //--// ReduceHashTable( ref m_globalRootMap, reachability, true, true, fApply ); ReduceHashTable( ref m_lookupType, reachability, false, true, fApply ); ReduceSet( ref m_uniqueAnnotations, reachability, fApply ); ReduceHashTable( ref m_placementRequirements, reachability, true, false, fApply ); ReduceHashTable( ref m_hardwareExceptionHandlers, reachability, true, false, fApply ); ReduceHashTable( ref m_debuggerHookHandlers, reachability, true, false, fApply ); ReduceHashTable( ref m_singletonFactories, reachability, true, true, fApply ); ReduceHashTable( ref m_singletonFactoriesFallback, reachability, true, true, fApply ); ReduceHashTable( ref m_garbageCollectionExtensions, reachability, true, false, fApply ); ReduceSet( ref m_garbageCollectionExclusions, reachability, fApply ); ReduceHashTable( ref m_memoryMappedPeripherals, reachability, true, false, fApply ); ReduceHashTable( ref m_registerAttributes, reachability, true, false, fApply ); ReduceHashTable( ref m_memoryMappedBitFieldPeripherals, reachability, true, false, fApply ); ReduceHashTable( ref m_bitFieldRegisterAttributes, reachability, true, false, fApply ); //--// if( reachability.Contains( m_globalRoot.Type ) == false ) { reachability.ExpandProhibition( m_globalRoot ); if( fApply ) { m_globalRoot = null; } } //--// if( fApply ) { #if VERIFY_REDUCTION foreach( Object obj in reachability.IncludedSet ) { CHECKS.ASSERT( reachability.IsProhibited( obj ) == false, "Mutual exclusion violation for {0}", obj ); } foreach( Object obj in reachability.ProhibitedSet ) { CHECKS.ASSERT( reachability.Contains( obj ) == false, "Mutual exclusion violation for {0}", obj ); } #endif var flagProhibitedUses = new FlagProhibitedUses( this ); flagProhibitedUses.ProcessTypeSystem( ); } } //--// internal void FlattenCallsDatabase( CompilationSteps.CallsDataBase callsDb, bool fCallsTo ) { CompilationSteps.ParallelTransformationsHandler.EnumerateMethods( this, target => { var analysis = new Queue(); var analyzed = SetFactory.NewWithReferenceEquality(); var call = new MethodCall( target, 0 ); analysis.Enqueue( call ); List lst = null; if(fCallsTo) { lock (m_callersToMethod) { HashTableWithListFactory.Create( m_callersToMethod, call.Target ); lst = m_callersToMethod[ call.Target ]; } } else { lock (m_callsFromMethod) { HashTableWithListFactory.Create( m_callsFromMethod, call.Target ); lst = m_callsFromMethod[ call.Target ]; } } while(analysis.Count > 0) { var current = analysis.Dequeue(); var calls = fCallsTo ? callsDb.CallsToMethod( current.Target ) : callsDb.CallsFromMethod( current.Target ) ; if(calls != null) { foreach(var opCall in calls) { var method = fCallsTo ? opCall.BasicBlock.Owner.Method : opCall.TargetMethod; if(analyzed.Contains( method )) { continue; } var call1 = new MethodCall( method, current.Level + 1 ); analysis.Enqueue( call1 ); analyzed.Insert( method ); lst.Add( call1 ); } } } } ); } //--// public override void ApplyTransformation( TransformationContext contextIn ) { var context = ( TransformationContextForCodeTransformation )contextIn; context.Push( this ); base.ApplyTransformation( contextIn ); context.TransformGeneric( ref m_activePlatform ); context.TransformGeneric( ref m_activeCallingConvention ); context.Transform( ref m_reachability ); context.Transform( ref m_imageBuilder ); context.Transform( ref m_dataManager ); context.Transform( ref m_uniqueConstants ); context.Transform( ref m_globalRootMap ); context.Transform( ref m_globalRoot ); context.Transform( ref m_placementRequirements ); context.Transform( ref m_hardwareExceptionHandlers ); context.Transform( ref m_debuggerHookHandlers ); context.Transform( ref m_singletonFactories ); context.Transform( ref m_singletonFactoriesFallback ); context.Transform( ref m_garbageCollectionExtensions ); context.Transform( ref m_garbageCollectionExclusions ); context.Transform( ref m_memoryMappedPeripherals ); context.Transform( ref m_registerAttributes ); context.Transform( ref m_memoryMappedBitFieldPeripherals ); context.Transform( ref m_bitFieldRegisterAttributes ); context.Pop( ); } //--// public Operator.OperatorLevel GetLevel( Operator op ) { return op.GetLevel( m_activePlatform ); } public Operator.OperatorLevel GetLevel( Expression ex ) { return ex.GetLevel( m_activePlatform ); } public bool ExpressionAlreadyInScalarForm( Expression ex ) { return ( ex == null || GetLevel( ex ) <= Operator.OperatorLevel.ScalarValues ); } public bool OperatorAlreadyInScalarForm( Operator op ) { foreach( var exLhs in op.Results ) { if( ExpressionAlreadyInScalarForm( exLhs ) == false ) { return false; } } foreach( var exRhs in op.Arguments ) { if( ExpressionAlreadyInScalarForm( exRhs ) == false ) { return false; } } return true; } // // Access Methods // public Type Product { get { return m_activeProduct; } set { if( m_activeProduct != null ) { throw TypeConsistencyErrorException.Create( "Cannot change Product after it's been set" ); } m_activeProduct = value; } } public Abstractions.Platform PlatformAbstraction { get { return m_activePlatform; } set { if( m_activePlatform != null ) { throw TypeConsistencyErrorException.Create( "Cannot change PlatformAbstraction after it's been set" ); } m_activePlatform = value; } } public Abstractions.CallingConvention CallingConvention { get { return m_activeCallingConvention; } set { if( m_activeCallingConvention != null ) { throw TypeConsistencyErrorException.Create( "Cannot change CallingConvention after it's been set" ); } m_activeCallingConvention = value; } } public Reachability EstimatedReachabilitySet { get { return m_reachabilityEstimated; } } public Reachability ReachabilitySet { get { return m_reachability; } } public ImageBuilders.Core ImageBuilder { get { return m_imageBuilder; } } public DataManager DataManagerInstance { get { return m_dataManager; } } public ConstantExpression GlobalRoot { get { return m_globalRoot; } } //--// public GrowOnlyHashTable PlacementRequirements { get { return m_placementRequirements; } } public GrowOnlyHashTable HardwareExceptionHandlers { get { return m_hardwareExceptionHandlers; } } public GrowOnlyHashTable DebuggerHookHandlers { get { return m_debuggerHookHandlers; } } public GrowOnlyHashTable SingletonFactories { get { return m_singletonFactories; } } public GrowOnlyHashTable SingletonFactoriesFallback { get { return m_singletonFactoriesFallback; } } public GrowOnlyHashTable MemoryMappedPeripherals { get { return m_memoryMappedPeripherals; } } public GrowOnlyHashTable RegisterAttributes { get { return m_registerAttributes; } } public GrowOnlyHashTable MemoryMappedBitFieldPeripherals { get { return m_memoryMappedBitFieldPeripherals; } } public GrowOnlyHashTable BitFieldRegisterAttributes { get { return m_bitFieldRegisterAttributes; } } public GrowOnlyHashTable> FlattenedCallsDataBase_CallsTo { get { return m_callersToMethod; } } public GrowOnlyHashTable> FlattenedCallsDataBase_CallsFrom { get { return m_callsFromMethod; ; } } //--// public GrowOnlyHashTable GarbageCollectionExtensions { get { return m_garbageCollectionExtensions; } } public GrowOnlySet GarbageCollectionExclusions { get { return m_garbageCollectionExclusions; } } [Flags] public enum ReferenceCountingStatus { Disabled = 0, Enabled = 0x1, Strict = 0x2, EnabledStrict = Enabled | Strict, } public ReferenceCountingStatus ReferenceCountingGarbageCollectionStatus { get; set; } public bool IsReferenceCountingGarbageCollectionEnabled { get { var status = this.ReferenceCountingGarbageCollectionStatus; return (status & ReferenceCountingStatus.Enabled) == ReferenceCountingStatus.Enabled; } } public bool IsReferenceCountingType( TypeRepresentation td ) { if(!this.IsReferenceCountingGarbageCollectionEnabled || td == null || !( td is ReferenceTypeRepresentation ) || td.IsOpenType || td.IsDelayedType) { return false; } // If type T is excluded, then all its derived classes would be as well. while(td != null) { if(m_referenceCountingExcludedTypes.Contains( td ) || m_implicitInstances.Contains( td )) { return false; } td = td.Extends; } return true; } public bool ShouldExcludeMethodFromReferenceCounting( MethodRepresentation md ) { if(md.IsGenericInstantiation) { md = md.GenericTemplate; } var methodsList = m_automaticReferenceCountingExclusions.GetValue( md.Name ); if(methodsList != null) { var matches = methodsList.FindAll( method => method.MatchSignature( md, null ) ); foreach(var match in matches) { if(match == md || match.OwnerType.IsSuperClassOf( md.OwnerType, null )) { // Match if it's in the list or it overrides a method in the list. return true; } } } return false; } //--// public List NativeImportDirectories { get { return m_nativeImportDirectories; } set { m_nativeImportDirectories = value; } } public List NativeImportLibraries { get { return m_nativeImportLibraries; } set { m_nativeImportLibraries = value; } } public GrowOnlyHashTable> DirectDescendant { get { return m_directDescendants; } } public GrowOnlyHashTable> NestedClasses { get { return m_nestedClasses; } } public GrowOnlyHashTable> InterfaceImplementors { get { return m_interfaceImplementors; } } public GrowOnlyHashTable> GenericTypeInstantiations { get { return m_genericTypeInstantiations; } } public GrowOnlyHashTable> GenericMethodInstantiations { get { return m_genericMethodInstantiations; } } public GrowOnlyHashTable ForcedDevirtualizations { get { return m_forcedDevirtualizations; } } public GrowOnlySet ImplicitInstances { get { return m_implicitInstances; } } //--// public List Image { get { if( m_imageBuilder != null ) { return m_imageBuilder.CollectImage( ); } return null; } } public LLVMModuleManager Module { get { return m_module; } } //--// public bool IsSealedType( TypeRepresentation target, out TypeRepresentation targetSealed ) { if( ( target.Flags & TypeRepresentation.Attributes.Sealed ) != 0 ) { targetSealed = target; return true; } // // BUGBUG: This can be used only for bounded applications. // if( m_concreteImplementations != null ) { List< TypeRepresentation > tdLst; if( m_concreteImplementations.TryGetValue( target, out tdLst ) ) { if( tdLst.Count == 1 ) { targetSealed = tdLst[ 0 ]; return true; } } } targetSealed = null; return false; } //--// public override ControlFlowGraphState CreateControlFlowGraphState( MethodRepresentation md, TypeRepresentation[] localVars, string[] localVarNames, out VariableExpression[] arguments, out VariableExpression[] locals ) { var cfg = new ControlFlowGraphStateForCodeTransformation( this, md ); // // Create entry and exit basic blocks. // { var entryBasicBlock = new EntryBasicBlock( cfg ); var exitBasicBlock = new ExitBasicBlock( cfg ); entryBasicBlock.AddOperator( UnconditionalControlOperator.New( null, exitBasicBlock ) ); } locals = cfg.AllocateVariables( localVars, localVarNames ); arguments = cfg.Arguments; //--// md.Code = cfg; return cfg; } public override ConstantExpression CreateNullPointer( TypeRepresentation td ) { if( td is ValueTypeRepresentation ) { td = GetManagedPointerToType( ( ValueTypeRepresentation )td ); } return CreateConstant( td, null ); } public override ConstantExpression CreateConstant( TypeRepresentation td, object value ) { var dd = value as DataManager.DataDescriptor; if( dd != null ) { CHECKS.ASSERT( td == dd.Context, "Mismatch between formal and actual type: {0} != {1}", td, dd ); td = dd.Context; } GrowOnlyHashTable< object, ConstantExpression > ht; lock( m_uniqueConstants ) { if( m_uniqueConstants.TryGetValue( td, out ht ) == false ) { ht = HashTableFactory.New( ); m_uniqueConstants[ td ] = ht; } } lock( ht ) { ConstantExpression res; if( ht.TryGetValue( value, out res ) ) { return res; } } var valueOrig = value; if( dd != null ) { value = dd; } else if( value != null ) { if( td is ScalarTypeRepresentation ) { // // These are stored as boxed values. // } else if( value is ConstantExpression.DelayedValue ) { // // These are stored as delayed values. // } else { var flags = DataManager.Attributes.Constant | DataManager.Attributes.SuitableForConstantPropagation; value = m_dataManager.ConvertToObjectDescriptor( td, flags, null, value ); } } var resNew = new ConstantExpression( td, value ); lock( ht ) { ht[ valueOrig ] = resNew; } return resNew; } public override ConstantExpression CreateConstant( int value ) { return CreateConstant( this.WellKnownTypes.System_Int32, value ); } public override ConstantExpression CreateConstant( uint value ) { return CreateConstant( this.WellKnownTypes.System_UInt32, value ); } public override ConstantExpression CreateConstantFromObject( object value ) { TypeRepresentation tdTarget; object od = m_dataManager.ConvertToObjectDescriptor( value, out tdTarget ); return CreateConstant( tdTarget, od ); } public override Expression[] CreateConstantsFromObjects( params object[] array ) { var res = new Expression[ array.Length ]; for( int i = 0; i < res.Length; i++ ) { var value = array[ i ]; if( value is Expression ) { res[ i ] = ( Expression )value; } else if( value == null ) { res[ i ] = CreateNullPointer( this.WellKnownTypes.System_Object ); } else { res[ i ] = CreateConstantFromObject( value ); } } return res; } public override ConstantExpression CreateConstantForType( VTable vTable ) { var val = new DelayedType( this, vTable ); if( val.CanEvaluate ) { return CreateConstantFromObject( val.Value ); } else { return CreateConstant( this.WellKnownTypes.System_RuntimeType, val ); } } public override ConstantExpression CreateConstantForTypeSize( TypeRepresentation td ) { object val; if( td.ValidLayout ) { val = td.Size; } else { val = new DelayedSize( td ); } return CreateConstant( this.WellKnownTypes.System_UInt32, val ); } public override ConstantExpression CreateConstantForFieldOffset( FieldRepresentation fd ) { object val; if( fd.ValidLayout ) { val = fd.Offset; } else { val = new DelayedOffset( fd ); } return CreateConstant( this.WellKnownTypes.System_UInt32, val ); } public override Expression CreateRuntimeHandle( object o ) { DataManager.ObjectDescriptor od = CreateDescriptorForRuntimeHandle( o ); return CreateConstant( od.Context, od ); } public DataManager.ObjectDescriptor CreateDescriptorForRuntimeHandle( object o ) { WellKnownTypes wkt = this.WellKnownTypes; WellKnownFields wkf = this.WellKnownFields; // // We have to create an instance of RuntimeHandle, and we have to set its m_value field to the proper input. // However, we will be called *before* open class definitions have been applied. // This is the reason why we declare a type and use the field from a different class. // if( o is TypeRepresentation ) { var td = ( TypeRepresentation )o; return CreateRuntimeHandleDescriptor( wkt.System_RuntimeTypeHandle, wkf.RuntimeTypeHandleImpl_m_value, td.VirtualTable ); } if( o is FieldRepresentation ) { var fd = ( FieldRepresentation )o; return CreateRuntimeHandleDescriptor( wkt.System_RuntimeFieldHandle, wkf.RuntimeFieldHandleImpl_m_value, fd ); } if( o is MethodRepresentation ) { var md = ( MethodRepresentation )o; return CreateRuntimeHandleDescriptor( wkt.System_RuntimeMethodHandle, wkf.RuntimeMethodHandleImpl_m_value, md ); } throw TypeConsistencyErrorException.Create( "Unexpected input for runtime handle creation: {0}", o ); } private DataManager.ObjectDescriptor CreateRuntimeHandleDescriptor( TypeRepresentation td, FieldRepresentation fd, object val ) { DataManager.ObjectDescriptor od = m_dataManager.BuildObjectDescriptor( td, DataManager.Attributes.Constant | DataManager.Attributes.SuitableForConstantPropagation, null ); od.ConvertAndSet( ( InstanceFieldRepresentation )fd, DataManager.Attributes.Constant | DataManager.Attributes.SuitableForConstantPropagation, null, val ); return od; } //--// public override Annotation CreateUniqueAnnotation( Annotation an ) { Annotation oldAn; if( m_uniqueAnnotations.Contains( an, out oldAn ) ) { return oldAn; } lock( TypeSystemForCodeTransformation.Lock ) { if( m_uniqueAnnotations.Contains( an, out oldAn ) ) { return oldAn; } m_uniqueAnnotations.Insert( an ); return an; } } //--// public Abstractions.PlacementRequirements GetPlacementRequirements( BaseRepresentation owner ) { Abstractions.PlacementRequirements pr; m_placementRequirements.TryGetValue( owner, out pr ); return pr; } public Abstractions.PlacementRequirements CreatePlacementRequirements( BaseRepresentation owner ) { Abstractions.PlacementRequirements pr = GetPlacementRequirements( owner ); if( pr == null ) { pr = new Abstractions.PlacementRequirements( sizeof( uint ), 0 ); m_placementRequirements[ owner ] = pr; } return pr; } //--// public override Expression[] AddTypePointerToArgumentsOfStaticMethod( MethodRepresentation md, params Expression[] rhs ) { return ArrayUtility.InsertAtHeadOfNotNullArray( rhs, CreateNullPointer( md.ThisPlusArguments[ 0 ] ) ); } public void SubstituteWithCallToHelper( string name, Operator op ) { SubstituteWithCallToHelper( GetWellKnownMethod( name ), op ); } public void SubstituteWithCallToHelper( MethodRepresentation md, Operator op ) { Expression[] rhs = AddTypePointerToArgumentsOfStaticMethod( md, op.Arguments ); StaticCallOperator opCall = StaticCallOperator.New( op.DebugInfo, CallOperator.CallKind.Direct, md, op.Results, rhs ); op.SubstituteWithOperator( opCall, Operator.SubstitutionFlags.Default ); } //--// public Runtime.HardwareException ExtractHardwareExceptionSettingsForMethod( MethodRepresentation md ) { CustomAttributeRepresentation ca; if( m_hardwareExceptionHandlers.TryGetValue( md, out ca ) ) { return ( Runtime.HardwareException )ca.FixedArgsValues[ 0 ]; } return Runtime.HardwareException.None; } public MethodRepresentation GetHandler( Runtime.HardwareException he ) { MethodRepresentation md = TryGetHandler( he ); if( md != null ) { return md; } throw TypeConsistencyErrorException.Create( "Cannot find handler for {0}", he ); } public MethodRepresentation TryGetHandler( Runtime.HardwareException he ) { foreach( MethodRepresentation md in m_hardwareExceptionHandlers.Keys ) { CustomAttributeRepresentation ca = m_hardwareExceptionHandlers[ md ]; if( ( Runtime.HardwareException )ca.FixedArgsValues[ 0 ] == he ) { return md; } } return null; } //--// public Runtime.DebuggerHook ExtractDebuggerHookSettingsForMethod( MethodRepresentation md ) { CustomAttributeRepresentation ca; if( m_debuggerHookHandlers.TryGetValue( md, out ca ) ) { return ( Runtime.DebuggerHook )ca.FixedArgsValues[ 0 ]; } return Runtime.DebuggerHook.None; } public MethodRepresentation GetHandler( Runtime.DebuggerHook dh ) { MethodRepresentation md = TryGetHandler( dh ); if( md != null ) { return md; } throw TypeConsistencyErrorException.Create( "Cannot find handler for {0}", dh ); } public MethodRepresentation TryGetHandler( Runtime.DebuggerHook dh ) { foreach( MethodRepresentation md in m_debuggerHookHandlers.Keys ) { CustomAttributeRepresentation ca = m_debuggerHookHandlers[ md ]; if( ( Runtime.DebuggerHook )ca.FixedArgsValues[ 0 ] == dh ) { return md; } } return null; } //--// public static ControlFlowGraphStateForCodeTransformation GetCodeForMethod( MethodRepresentation md ) { return ( ControlFlowGraphStateForCodeTransformation )md.Code; } //--// public TypeRepresentation GetTypeRepresentationFromObject( object obj ) { return GetTypeRepresentationFromType( obj.GetType( ) ); } public TypeRepresentation GetTypeRepresentationFromType( Type t ) { if( t == null ) { return null; } TypeRepresentation td = TryGetTypeRepresentationFromType( t ); if( td != null ) { return td; } throw TypeConsistencyErrorException.Create( "Cannot lookup a TypeRepresentation for {0}", t ); } public TypeRepresentation TryGetTypeRepresentationFromType( Type t ) { lock( TypeSystemForCodeTransformation.Lock ) { TypeRepresentation res; if( m_lookupType.TryGetValue( t, out res ) ) { return res; } if( t.IsArray ) { var tdElement = TryGetTypeRepresentationFromType( t.GetElementType( ) ); if( tdElement == null ) { return null; } foreach( TypeRepresentation td in this.Types ) { if( td is ArrayReferenceTypeRepresentation ) { var tdArray = ( ArrayReferenceTypeRepresentation )td; if( tdArray.ContainedType == tdElement ) { int rank = t.GetArrayRank( ); if( tdArray is SzArrayReferenceTypeRepresentation ) { if( rank == 1 ) { m_lookupType[ t ] = td; return td; } } else { var tdArray2 = ( MultiArrayReferenceTypeRepresentation )tdArray; if( tdArray2.Rank == rank ) { m_lookupType[ t ] = td; return td; } } } } } } else { string wellKnownName; if( m_lookupTypeLinkedToRuntime.TryGetValue( t, out wellKnownName ) ) { return GetWellKnownType( wellKnownName ); } //--// string name = t.Name; string asmlName = t.Assembly.GetName( ).Name; if( t.IsNested ) { TypeRepresentation tdEnclosing = TryGetTypeRepresentationFromType( t.DeclaringType ); if( tdEnclosing == null ) { return null; } foreach( TypeRepresentation td in this.Types ) { if( td.Name == name && td.EnclosingClass == tdEnclosing ) { if( td.Owner.Name == asmlName ) { m_lookupType[ t ] = td; return td; } } } } else { string nameSpace = t.Namespace; foreach( TypeRepresentation td in this.Types ) { if( td.Name == name && td.Namespace == nameSpace ) { if( td.Owner.Name == asmlName ) { m_lookupType[ t ] = td; return td; } } } } } return null; } } public Type TryGetTypeFromTypeRepresentation( TypeRepresentation td ) { var wkt = this.WellKnownTypes; foreach( System.Reflection.FieldInfo fi in ReflectionHelper.GetAllPublicInstanceFields( wkt.GetType( ) ) ) { var obj = fi.GetValue( wkt ) as TypeRepresentation; if( obj == td ) { var attrib = ReflectionHelper.GetAttribute( fi, false ); if( attrib != null ) { return attrib.Target; } } } return null; } //--// public Expression GetVTable( TypeRepresentation td ) { TypeRepresentation tdVal = this.WellKnownTypes.Microsoft_Zelig_Runtime_TypeSystem_VTable; // Remap boxed type virtual tables to their underlying type's. if (td is BoxedValueTypeRepresentation) { td = td.UnderlyingType; } DataManager.Attributes attributes = DataManager.Attributes.Constant | DataManager.Attributes.SuitableForConstantPropagation; return CreateConstant( tdVal, m_dataManager.ConvertToObjectDescriptor( tdVal, attributes, null, td.VirtualTable ) ); } public Expression GetTypeRepresentation( TypeRepresentation target ) { TypeRepresentation tdTarget; object od = m_dataManager.ConvertToObjectDescriptor( target, out tdTarget ); return CreateConstant( tdTarget, od ); } //--// internal DataManager.ObjectDescriptor GetGlobalRoot( ) { return ( DataManager.ObjectDescriptor )m_globalRoot.Value; } internal DataManager.ObjectDescriptor GenerateGlobalRoot( ) { lock( TypeSystemForCodeTransformation.Lock ) { if( m_globalRoot == null ) { DataManager.ObjectDescriptor od = m_dataManager.BuildObjectDescriptor( this.WellKnownTypes.Microsoft_Zelig_Runtime_TypeSystem_GlobalRoot, DataManager.Attributes.Mutable | DataManager.Attributes.SuitableForConstantPropagation, null ); m_globalRoot = CreateConstant( this.WellKnownTypes.Microsoft_Zelig_Runtime_TypeSystem_GlobalRoot, od ); } } return GetGlobalRoot( ); } internal Expression GenerateConstantForSingleton( TypeRepresentation td, DataManager.Attributes flags ) { DataManager.ObjectDescriptor od = GenerateSingleton( td, flags ); return CreateConstant( od.Context, od ); } internal DataManager.ObjectDescriptor GenerateSingleton( TypeRepresentation td, DataManager.Attributes flags ) { InstanceFieldRepresentation res; return GenerateSingleton( td, flags, out res ); } internal DataManager.ObjectDescriptor GenerateSingleton( TypeRepresentation td, DataManager.Attributes flags, out InstanceFieldRepresentation res ) { lock( TypeSystemForCodeTransformation.Lock ) { DataManager.ObjectDescriptor odRoot = GenerateGlobalRoot( ); // // Special case for the GlobalRoot instance itself. // if( td == odRoot.Context ) { res = null; return odRoot; } if( m_globalRootMap.TryGetValue( td, out res ) == false ) { TypeRepresentation tdRoot = odRoot.Context; string fieldName = string.Format( "Singleton_{0}_{1:X8}", td.FullNameWithAbbreviation, td.ToString( ).GetHashCode( ) ); res = new InstanceFieldRepresentation( tdRoot, fieldName, td ); m_globalRootMap[ td ] = res; tdRoot.AddField( res ); odRoot.Set( res, m_dataManager.BuildObjectDescriptor( td, flags, null ) ); } return ( DataManager.ObjectDescriptor )odRoot.Get( res ); } } public DataManager.ObjectDescriptor GetSingleton( TypeRepresentation td ) { if( td != null ) { lock( TypeSystemForCodeTransformation.Lock ) { InstanceFieldRepresentation res; if( m_globalRoot != null && m_globalRootMap.TryGetValue( td, out res ) ) { DataManager.ObjectDescriptor odRoot = GetGlobalRoot( ); return ( DataManager.ObjectDescriptor )odRoot.Get( res ); } } } return null; } public TypeRepresentation FindActualSingleton( TypeRepresentation td ) { if( td != null ) { lock( TypeSystemForCodeTransformation.Lock ) { foreach( TypeRepresentation td2 in m_globalRootMap.Keys ) { if( td == td2 || td.IsSuperClassOf( td2, null ) ) { return td2; } } } } return null; } //--// public ConstantExpression GenerateRootAccessor( Operator site ) { GenerateGlobalRoot( ); return m_globalRoot; } public Expression GenerateSingletonAccessor( Operator site, TypeRepresentation td, DataManager.Attributes flags, bool fNeverNull ) { lock( TypeSystemForCodeTransformation.Lock ) { InstanceFieldRepresentation res; ConstantExpression exRoot = GenerateRootAccessor( site ); DataManager.ObjectDescriptor od = GenerateSingleton( td, flags, out res ); TemporaryVariableExpression tmp = site.BasicBlock.Owner.AllocateTemporary( td, null ); if( res != null ) { // // 'exRoot' will never be null, so we don't need to check for it. // LoadInstanceFieldOperator opNew = LoadInstanceFieldOperator.New( site.DebugInfo, res, tmp, exRoot, false ); if( fNeverNull ) { opNew.AddAnnotation( NotNullAnnotation.Create( this ) ); } site.AddOperatorBefore( opNew ); } else { var opNew = SingleAssignmentOperator.New( site.DebugInfo, tmp, exRoot ); opNew.AddAnnotation( NotNullAnnotation.Create( this ) ); } return tmp; } } public InstanceFieldRepresentation AddStaticFieldToGlobalRoot( StaticFieldRepresentation fd ) { lock( TypeSystemForCodeTransformation.Lock ) { DataManager.ObjectDescriptor odRoot = GenerateGlobalRoot( ); InstanceFieldRepresentation res; if( m_globalRootMap.TryGetValue( fd, out res ) == false ) { TypeRepresentation tdRoot = this.WellKnownTypes.Microsoft_Zelig_Runtime_TypeSystem_GlobalRoot; string fieldName = string.Format( "StaticField_{0}_{1}_{2:X8}", fd.OwnerType.FullNameWithAbbreviation, fd.Name, fd.ToString( ).GetHashCode( ) ); res = new InstanceFieldRepresentation( tdRoot, fieldName, fd.FieldType ); res.LinkAsImplementationOf( fd ); tdRoot.AddField( res ); m_globalRootMap[ fd ] = res; // // For static fields that are value types, we need to create a nested ObjectDescriptor. // TypeRepresentation fdType = res.FieldType; if( fdType is ValueTypeRepresentation ) { DataManager.ObjectDescriptor od = m_dataManager.BuildObjectDescriptor( fdType, DataManager.Attributes.Mutable, null ); od.SetNesting( odRoot, res, -1 ); odRoot.Set( res, od ); } } return res; } } public InstanceFieldRepresentation GetEntityFromGlobalRoot( BaseRepresentation bd ) { lock( TypeSystemForCodeTransformation.Lock ) { InstanceFieldRepresentation res; m_globalRootMap.TryGetValue( bd, out res ); return res; } } public Expression GenerateConstantArrayAccessor( Operator site, ArrayReferenceTypeRepresentation td, Array array, Abstractions.PlacementRequirements pr ) { return CreateConstant( td, m_dataManager.ConvertToObjectDescriptor( td, DataManager.Attributes.Constant | DataManager.Attributes.SuitableForConstantPropagation, pr, array ) ); } //--// public override CodePointer CreateCodePointer( MethodRepresentation md ) { return m_dataManager.CreateCodePointer( md ); } public override bool IncludeInGCInfo( InstanceFieldRepresentation fd ) { return m_garbageCollectionExclusions.Contains( fd ) == false; } //--// #if DEBUG_IMAGEBUILDER_PERF PerformanceCounters.Timing m_timing; private void Debug_TimestampedWriteLine( string format, params object[] args ) { Console.Write( "{0,13:F6}: ", ( float )PerformanceCounters.Timing.ToMicroSeconds( m_timing.Sample( ) ) / ( 1000 * 1000 ) ); Console.WriteLine( format, args ); } #endif public void GenerateImage( CompilationSteps.PhaseDriver phase ) { m_imageBuilder = new ImageBuilders.Core( this ); this.PlatformAbstraction.GetListOfMemoryBlocks( m_imageBuilder.MemoryBlocks ); bool fRecompile = true; bool fDone = false; #if DEBUG_IMAGEBUILDER_PERF int round = 0; m_timing.Start( ); Debug_TimestampedWriteLine( "START ##########################################################################" ); #endif while( !fDone ) { #if DEBUG_IMAGEBUILDER_PERF Debug_TimestampedWriteLine( "Round: {0}", ++round ); #endif fDone = true; if( fRecompile ) { fRecompile = false; #if DEBUG_IMAGEBUILDER_PERF Debug_TimestampedWriteLine( "Emitting..." ); #endif m_imageBuilder.RestartCompilation( ); foreach( MethodRepresentation md in this.HardwareExceptionHandlers.Keys ) { var cfg = TypeSystemForCodeTransformation.GetCodeForMethod( md ); m_imageBuilder.CompileMethod( cfg ); } foreach( MethodRepresentation md in this.DebuggerHookHandlers.Keys ) { var cfg = TypeSystemForCodeTransformation.GetCodeForMethod( md ); m_imageBuilder.CompileMethod( cfg ); } foreach( MethodRepresentation md in this.ExportedMethods ) { var cfg = TypeSystemForCodeTransformation.GetCodeForMethod( md ); m_imageBuilder.CompileMethod( cfg ); } // // Include all methods for LLVM flow only // if(PlatformAbstraction.CodeGenerator == TargetModel.ArmProcessor.InstructionSetVersion.CodeGenerator_LLVM) { foreach(var td in this.Types) { foreach(var md in td.Methods) { // // Do not include exported methods, exceptions and debugger hooks twice // if(this.HardwareExceptionHandlers.ContainsKey( md ) || this.DebuggerHookHandlers .ContainsKey( md ) || this.ExportedMethods .Contains ( md ) ) { continue; } var cfg = TypeSystemForCodeTransformation.GetCodeForMethod( md ); m_imageBuilder.CompileMethod( cfg ); } } } m_imageBuilder.ProcessPending( ); #if DEBUG_IMAGEBUILDER_PERF Debug_TimestampedWriteLine( "Done emitting" ); #endif } //--// #if ARMv7M_BUILD__LLVM_IR_ONLY if( PlatformAbstraction.CodeGenerator != TargetModel.ArmProcessor.InstructionSetVersion.CodeGenerator_LLVM ) #endif { if(m_imageBuilder.AssignAbsoluteAddressesToCode( ) == false) { #if DEBUG_IMAGEBUILDER_PERF Debug_TimestampedWriteLine( "Failed AssignAbsoluteAddressesToCode" ); #endif fRecompile = true; fDone = false; continue; } } //--// m_dataManager.RefreshValues( phase ); m_imageBuilder.RewindToDataDescriptorsPhase( ); if( m_imageBuilder.ImportDataDescriptors( ) == false ) { #if DEBUG_IMAGEBUILDER_PERF Debug_TimestampedWriteLine( "Failed ImportDataDescriptors" ); #endif fRecompile = true; fDone = false; continue; } #if ARMv7M_BUILD__LLVM_IR_ONLY if( PlatformAbstraction.CodeGenerator != TargetModel.ArmProcessor.InstructionSetVersion.CodeGenerator_LLVM ) #endif { m_imageBuilder.AssignAbsoluteAddressesToDataDescriptors( ); } m_imageBuilder.CommitMemoryMap( ); //--// #if ARMv7M_BUILD__LLVM_IR_ONLY if( PlatformAbstraction.CodeGenerator != TargetModel.ArmProcessor.InstructionSetVersion.CodeGenerator_LLVM ) #endif { if(m_imageBuilder.ApplyRelocation( ) == false) { #if DEBUG_IMAGEBUILDER_PERF Debug_TimestampedWriteLine( "Failed ApplyRelocation" ); #endif fRecompile = true; fDone = false; continue; } } #if ARMv7M_BUILD__LLVM_IR_ONLY if( PlatformAbstraction.CodeGenerator != TargetModel.ArmProcessor.InstructionSetVersion.CodeGenerator_LLVM ) #endif { if(m_imageBuilder.CreateCodeMaps( ) == false) { #if DEBUG_IMAGEBUILDER_PERF Debug_TimestampedWriteLine( "Failed CreateCodeMaps" ); #endif fDone = false; } } #if ARMv7M_BUILD__LLVM_IR_ONLY if( PlatformAbstraction.CodeGenerator != TargetModel.ArmProcessor.InstructionSetVersion.CodeGenerator_LLVM ) #endif { if(m_imageBuilder.CreateExceptionHandlingTables( ) == false) { #if DEBUG_IMAGEBUILDER_PERF Debug_TimestampedWriteLine( "Failed CreateExceptionHandlingTables" ); #endif fDone = false; } } #if ARMv7M_BUILD__LLVM_IR_ONLY if( PlatformAbstraction.CodeGenerator != TargetModel.ArmProcessor.InstructionSetVersion.CodeGenerator_LLVM ) #endif { if(m_imageBuilder.CreateAvailableMemoryTables( ) == false) { #if DEBUG_IMAGEBUILDER_PERF Debug_TimestampedWriteLine( "Failed CreateAvailableMemoryTables" ); #endif fDone = false; } } #if ARMv7M_BUILD__LLVM_IR_ONLY if( PlatformAbstraction.CodeGenerator != TargetModel.ArmProcessor.InstructionSetVersion.CodeGenerator_LLVM ) #endif { if(m_imageBuilder.CreateImageRelocationData( ) == false) { #if DEBUG_IMAGEBUILDER_PERF Debug_TimestampedWriteLine( "Failed CreateImageRelocationData" ); #endif fDone = false; } } } #if DEBUG_IMAGEBUILDER_PERF Debug_TimestampedWriteLine( "Done" ); #endif if( PlatformAbstraction.CodeGenerator == TargetModel.ArmProcessor.InstructionSetVersion.CodeGenerator_LLVM ) { Module.Compile( ); } m_imageBuilder.CacheSourceCore( ); } public void DropCompileTimeObjects( ) { this.ReachabilitySet.ProhibitedSet.Clear( ); #if ARMv7M_BUILD__LLVM_IR_ONLY if( PlatformAbstraction.CodeGenerator != TargetModel.ArmProcessor.InstructionSetVersion.CodeGenerator_LLVM ) #endif { if(m_imageBuilder != null) { m_imageBuilder.DropCompileTimeObjects( ); } } } // // Debug Methods // static System.IO.StreamWriter s_dump; [MethodImplAttribute( MethodImplOptions.Synchronized )] protected override void InnerReport( string format, params object[] args ) { if( s_dump == null ) { string file = string.Format( "typesystem_{0:yyyy-MM-dd--HH-mm-ss}.txt", DateTime.Now ); s_dump = new System.IO.StreamWriter( new System.IO.FileStream( file, System.IO.FileMode.Create ) ); } s_dump.WriteLine( format, args ); s_dump.Flush( ); } public void DisassembleImage( string baseDirectory ) { m_imageBuilder.Disassemble( baseDirectory ); } public void DisassembleImageInOneFile( string fileName ) { m_imageBuilder.DisassembleInOneFile( fileName ); } } } ================================================ FILE: Zelig/Zelig/CompileTime/CodeGenerator/CodeTransformation/TypeSystemForCodeTransformation_Notifications.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // namespace Microsoft.Zelig.CodeGeneration.IR { using System; using System.Collections.Generic; using System.Runtime.CompilerServices; using Microsoft.Zelig.MetaData; using Microsoft.Zelig.MetaData.Normalized; using Microsoft.Zelig.Runtime.TypeSystem; public partial class TypeSystemForCodeTransformation { [Runtime.ConfigurationOption( "ExcludeDebuggerHooks" )] public bool ExcludeDebuggerHooks; //--// [CompilationSteps.NewEntityNotification] private void Notify_NewBoxedType( TypeRepresentation td ) { // // Make sure that there's a boxed representation for each value type. // if(td is ValueTypeRepresentation) { CreateBoxedValueType( td ); } } [CompilationSteps.NewEntityNotification] private void Notify_CheckArrays( TypeRepresentation td ) { if(td is SzArrayReferenceTypeRepresentation) { var elementType = td.ContainedType; // // For a non-generic array, we need to instantiate also the helper class. // It will provide the implementation for the runtime methods. // if(elementType.IsOpenType == false) { CreateInstantiationOfGenericTemplate( this.WellKnownTypes.Microsoft_Zelig_Runtime_SZArrayHelper, elementType ); } } } [CompilationSteps.NewEntityNotification] private void Notify_CheckForComparerInstantiation( MethodRepresentation md ) { if(md.Name == "CreateComparer") { var td = md.OwnerType; if(td.IsGenericInstantiation) { if(td.GenericTemplate == this.WellKnownTypes.System_Collections_Generic_Comparer_of_T) { var tdParam = td.GenericParameters[0]; //// private static Comparer CreateComparer() //// { //// Type t = typeof( T ); //// //// // If T implements IComparable return a GenericComparer //// if(typeof( IComparable ).IsAssignableFrom( t )) //// { //// //return (Comparer)Activator.CreateInstance(typeof(GenericComparer<>).MakeGenericType(t)); //// return (Comparer)(typeof( GenericComparer ).TypeHandle.CreateInstanceForAnotherGenericParameter( t )); //// } //// //// // If T is a Nullable where U implements IComparable return a NullableComparer //// if(t.IsGenericType && t.GetGenericTypeDefinition() == typeof( Nullable<> )) //// { //// Type u = t.GetGenericArguments()[0]; //// if(typeof( IComparable<> ).MakeGenericType( u ).IsAssignableFrom( u )) //// { //// //return (Comparer)Activator.CreateInstance(typeof(NullableComparer<>).MakeGenericType(u)); //// return (Comparer)(typeof( NullableComparer ).TypeHandle.CreateInstanceForAnotherGenericParameter( u )); //// } //// } //// //// // Otherwise return an ObjectComparer //// return new ObjectComparer(); //// } if(tdParam.FindInstantiationOfGenericInterface( (InterfaceTypeRepresentation)this.WellKnownTypes.System_IComparable_of_T, tdParam ) != null) { var newTd = CreateInstantiationOfGenericTemplate( this.WellKnownTypes.System_Collections_Generic_GenericComparer_of_T, tdParam ); CreateComparerHelper( md, newTd ); } if(tdParam.GenericTemplate == this.WellKnownTypes.System_Nullable_of_T) { var tdParam2 = tdParam.GenericParameters[0]; if(td.FindInstantiationOfGenericInterface( (InterfaceTypeRepresentation)this.WellKnownTypes.System_IComparable_of_T, tdParam2 ) != null) { var newTd = CreateInstantiationOfGenericTemplate( this.WellKnownTypes.System_Collections_Generic_NullableComparer_of_T, tdParam2 ); CreateComparerHelper( md, newTd ); return; } } { var newTd = CreateInstantiationOfGenericTemplate( this.WellKnownTypes.System_Collections_Generic_ObjectComparer_of_T, tdParam ); CreateComparerHelper( md, newTd ); return; } } } } } [CompilationSteps.NewEntityNotification] private void Notify_CheckForEqualityComparerInstantiation( MethodRepresentation md ) { if(md.Name == "CreateComparer") { var td = md.OwnerType; if(td.IsGenericInstantiation) { if(td.GenericTemplate == this.WellKnownTypes.System_Collections_Generic_EqualityComparer_of_T) { var tdParam = td.GenericParameters[0]; //// private static EqualityComparer CreateComparer() //// { //// Type t = typeof( T ); //// //// // Specialize type byte for performance reasons //// if(t == typeof( byte )) //// { //// return (EqualityComparer)(object)(new ByteEqualityComparer()); //// } //// //// // If T implements IEquatable return a GenericEqualityComparer //// if(typeof( IEquatable ).IsAssignableFrom( t )) //// { //// //return (EqualityComparer)Activator.CreateInstance(typeof(GenericEqualityComparer<>).MakeGenericType(t)); //// return (EqualityComparer)(typeof( GenericEqualityComparer ).TypeHandle.CreateInstanceForAnotherGenericParameter( t )); //// } //// //// // If T is a Nullable where U implements IEquatable return a NullableEqualityComparer //// if(t.IsGenericType && t.GetGenericTypeDefinition() == typeof( Nullable<> )) //// { //// Type u = t.GetGenericArguments()[0]; //// if(typeof( IEquatable<> ).MakeGenericType( u ).IsAssignableFrom( u )) //// { //// //return (EqualityComparer)Activator.CreateInstance(typeof(NullableEqualityComparer<>).MakeGenericType(u)); //// return (EqualityComparer)(typeof( NullableEqualityComparer ).TypeHandle.CreateInstanceForAnotherGenericParameter( u )); //// } //// } //// //// // Otherwise return an ObjectEqualityComparer //// return new ObjectEqualityComparer(); //// } if(tdParam.FindInstantiationOfGenericInterface( (InterfaceTypeRepresentation)this.WellKnownTypes.System_IEquatable_of_T, tdParam ) != null) { var newTd = CreateInstantiationOfGenericTemplate( this.WellKnownTypes.System_Collections_Generic_GenericEqualityComparer_of_T, tdParam ); CreateComparerHelper( md, newTd ); return; } if(tdParam.Extends == this.WellKnownTypes.System_Enum) { TypeRepresentation tdTemplate = null; if( tdParam.UnderlyingType == this.WellKnownTypes.System_SByte || tdParam.UnderlyingType == this.WellKnownTypes.System_Byte ) { tdTemplate = this.WellKnownTypes.System_Collections_Generic_EqualityComparer_of_Enum_sbyte; } else if(tdParam.UnderlyingType == this.WellKnownTypes.System_Int16 || tdParam.UnderlyingType == this.WellKnownTypes.System_UInt16 ) { tdTemplate = this.WellKnownTypes.System_Collections_Generic_EqualityComparer_of_Enum_short; } else if(tdParam.UnderlyingType == this.WellKnownTypes.System_Int32 || tdParam.UnderlyingType == this.WellKnownTypes.System_UInt32 ) { tdTemplate = this.WellKnownTypes.System_Collections_Generic_EqualityComparer_of_Enum; } else if(tdParam.UnderlyingType == this.WellKnownTypes.System_Int64 || tdParam.UnderlyingType == this.WellKnownTypes.System_UInt64 ) { tdTemplate = this.WellKnownTypes.System_Collections_Generic_EqualityComparer_of_Enum_long; } else { throw TypeConsistencyErrorException.Create( "Enum {0} is not backed by a known underlying type", td ); } var newTd = CreateInstantiationOfGenericTemplate( tdTemplate, tdParam ); CreateComparerHelper( md, newTd ); return; } if(tdParam.GenericTemplate == this.WellKnownTypes.System_Nullable_of_T) { var tdParam2 = tdParam.GenericParameters[0]; if(td.FindInstantiationOfGenericInterface( (InterfaceTypeRepresentation)this.WellKnownTypes.System_IEquatable_of_T, tdParam2 ) != null) { var newTd = CreateInstantiationOfGenericTemplate( this.WellKnownTypes.System_Collections_Generic_NullableEqualityComparer_of_T, tdParam2 ); CreateComparerHelper( md, newTd ); return; } } { var newTd = CreateInstantiationOfGenericTemplate( this.WellKnownTypes.System_Collections_Generic_ObjectEqualityComparer_of_T, tdParam ); CreateComparerHelper( md, newTd ); return; } } } } } private void CreateComparerHelper( MethodRepresentation md , TypeRepresentation newTd ) { var cfg = (ControlFlowGraphStateForCodeTransformation)this.CreateControlFlowGraphState( md ); var bb = cfg.CreateFirstNormalBasicBlock(); // // Allocate helper. // bb.AddOperator( ObjectAllocationOperator.New( null, newTd, cfg.ReturnValue ) ); cfg.AddReturnOperator(); } //--//--// //// [CompilationSteps.CustomAttributeNotification( "Microsoft_Zelig_Internals_TypeDependencyAttribute" )] //// [CompilationSteps.CustomAttributeNotification( "Microsoft_Zelig_Runtime_TypeSystem_TypeDependencyAttribute" )] //// private void Notify_TypeDependencyAttribute( ref bool fKeep , //// CustomAttributeRepresentation ca , //// TypeRepresentation owner ) //// { //// } [CompilationSteps.CustomAttributeNotification( "Microsoft_Zelig_Internals_WellKnownFieldAttribute" )] [CompilationSteps.CustomAttributeNotification( "Microsoft_Zelig_Runtime_TypeSystem_WellKnownFieldAttribute" )] private void Notify_WellKnownFieldAttribute( ref bool fKeep , CustomAttributeRepresentation ca , FieldRepresentation owner ) { fKeep = false; // // Filter methods that belong to types that do not belong to the platform compiled // CustomAttributeRepresentation sfpf = owner.OwnerType.FindCustomAttribute( this.WellKnownTypes.Microsoft_Zelig_Runtime_ExtendClassAttribute ); if(sfpf != null) { object obj = sfpf.GetNamedArg( "PlatformVersionFilter" ); if(obj != null) { uint filter = (uint)obj; if((filter & this.PlatformAbstraction.PlatformVersion) != this.PlatformAbstraction.PlatformVersion) { // This type is not an allowed extension for the current platform return; } } } string fieldName = (string)ca.FixedArgsValues[0]; FieldRepresentation fdOld = this.GetWellKnownFieldNoThrow( fieldName ); if(fdOld != null && fdOld != owner) { throw TypeConsistencyErrorException.Create( "Found the well-known field '{0}' defined more than once: {1} and {2}", fieldName, fdOld, owner ); } this.SetWellKnownField( fieldName, owner ); } [CompilationSteps.CustomAttributeNotification( "Microsoft_Zelig_Internals_WellKnownMethodAttribute" )] [CompilationSteps.CustomAttributeNotification( "Microsoft_Zelig_Runtime_TypeSystem_WellKnownMethodAttribute" )] private void Notify_WellKnownMethodAttribute( ref bool fKeep , CustomAttributeRepresentation ca , MethodRepresentation owner ) { fKeep = false; if(owner.IsGenericInstantiation) { owner = owner.GenericTemplate; } // // Filter methods that belong to types that do not belong to the platform compiled // CustomAttributeRepresentation sfpf = owner.OwnerType.FindCustomAttribute( this.WellKnownTypes.Microsoft_Zelig_Runtime_ExtendClassAttribute ); if(sfpf != null) { object obj = sfpf.GetNamedArg( "PlatformVersionFilter" ); if(obj != null) { uint filter = (uint)obj; if((filter & this.PlatformAbstraction.PlatformVersion) != this.PlatformAbstraction.PlatformVersion) { // This type is not an allowed extension for the current platform return; } } } string methodName = (string)ca.FixedArgsValues[0]; MethodRepresentation mdOld = this.GetWellKnownMethodNoThrow( methodName ); if(mdOld != null && mdOld != owner) { throw TypeConsistencyErrorException.Create( "Found the well-known method '{0}' defined more than once: {1} and {2}", methodName, mdOld, owner ); } this.SetWellKnownMethod( methodName, owner ); } //--// [CompilationSteps.CustomAttributeNotification( "Microsoft_Zelig_Runtime_ForceDevirtualizationAttribute" )] private void Notify_ForceDevirtualizationAttribute( ref bool fKeep , CustomAttributeRepresentation ca , TypeRepresentation owner ) { fKeep = false; owner.BuildTimeFlags |= TypeRepresentation.BuildTimeAttributes.ForceDevirtualization; } [CompilationSteps.CustomAttributeNotification( "Microsoft_Zelig_Runtime_ImplicitInstanceAttribute" )] private void Notify_ImplicitInstanceAttribute( ref bool fKeep , CustomAttributeRepresentation ca , TypeRepresentation owner ) { fKeep = false; owner.BuildTimeFlags |= TypeRepresentation.BuildTimeAttributes.ImplicitInstance; } [CompilationSteps.CustomAttributeNotification( "System_FlagsAttribute" )] private void Notify_FlagsAttribute( ref bool fKeep , CustomAttributeRepresentation ca , TypeRepresentation owner ) { fKeep = false; owner.BuildTimeFlags |= TypeRepresentation.BuildTimeAttributes.FlagsAttribute; } [CompilationSteps.CustomAttributeNotification( "Microsoft_Zelig_Runtime_InlineAttribute" )] private void Notify_InlineAttribute( ref bool fKeep , CustomAttributeRepresentation ca , MethodRepresentation owner ) { fKeep = false; owner.BuildTimeFlags |= MethodRepresentation.BuildTimeAttributes.Inline; owner.BuildTimeFlags &= ~MethodRepresentation.BuildTimeAttributes.NoInline; } [CompilationSteps.CustomAttributeNotification( "Microsoft_Zelig_Runtime_NoInlineAttribute" )] private void Notify_NoInlineAttribute( ref bool fKeep , CustomAttributeRepresentation ca , MethodRepresentation owner ) { fKeep = false; owner.BuildTimeFlags |= MethodRepresentation.BuildTimeAttributes.NoInline; owner.BuildTimeFlags &= ~MethodRepresentation.BuildTimeAttributes.Inline; } [CompilationSteps.CustomAttributeNotification( "Microsoft_Zelig_Runtime_BottomOfCallStackAttribute" )] private void Notify_BottomOfCallStackAttribute( ref bool fKeep , CustomAttributeRepresentation ca , MethodRepresentation owner ) { fKeep = false; owner.BuildTimeFlags |= MethodRepresentation.BuildTimeAttributes.BottomOfCallStack; } [CompilationSteps.CustomAttributeNotification( "Microsoft_Zelig_Runtime_SaveFullProcessorContextAttribute" )] private void Notify_SaveFullProcessorContextAttribute( ref bool fKeep , CustomAttributeRepresentation ca , MethodRepresentation owner ) { fKeep = false; owner.BuildTimeFlags |= MethodRepresentation.BuildTimeAttributes.SaveFullProcessorContext; } [CompilationSteps.CustomAttributeNotification( "Microsoft_Zelig_Runtime_NoReturnAttribute" )] private void Notify_NoReturnAttribute( ref bool fKeep , CustomAttributeRepresentation ca , MethodRepresentation owner ) { fKeep = false; owner.BuildTimeFlags |= MethodRepresentation.BuildTimeAttributes.NoReturn; } [CompilationSteps.CustomAttributeNotification( "Microsoft_Zelig_Runtime_CannotAllocateAttribute" )] private void Notify_CannotAllocateAttribute( ref bool fKeep , CustomAttributeRepresentation ca , MethodRepresentation owner ) { fKeep = false; owner.BuildTimeFlags |= MethodRepresentation.BuildTimeAttributes.CannotAllocate; } [CompilationSteps.CustomAttributeNotification( "Microsoft_Zelig_Runtime_CanAllocateOnReturnAttribute" )] private void Notify_CanAllocateOnReturnAttribute( ref bool fKeep , CustomAttributeRepresentation ca , MethodRepresentation owner ) { fKeep = false; owner.BuildTimeFlags |= MethodRepresentation.BuildTimeAttributes.CanAllocateOnReturn; } [CompilationSteps.CustomAttributeNotification( "Microsoft_Zelig_Runtime_StackNotAvailableAttribute" )] private void Notify_StackNotAvailableAttribute( ref bool fKeep , CustomAttributeRepresentation ca , MethodRepresentation owner ) { fKeep = false; owner.BuildTimeFlags |= MethodRepresentation.BuildTimeAttributes.StackNotAvailable; } [CompilationSteps.CustomAttributeNotification( "Microsoft_Zelig_Runtime_StackAvailableOnReturnAttribute" )] private void Notify_StackAvailableOnReturnAttribute( ref bool fKeep , CustomAttributeRepresentation ca , MethodRepresentation owner ) { fKeep = false; owner.BuildTimeFlags |= MethodRepresentation.BuildTimeAttributes.StackAvailableOnReturn; } [CompilationSteps.CustomAttributeNotification( "Microsoft_Zelig_Runtime_DisableBoundsChecksAttribute" )] private void Notify_DisableBoundsChecksAttribute( ref bool fKeep , CustomAttributeRepresentation ca , MethodRepresentation owner ) { fKeep = false; if(ca.GetNamedArg( "ApplyRecursively" ) != null) { owner.BuildTimeFlags |= MethodRepresentation.BuildTimeAttributes.DisableDeepBoundsChecks; } else { owner.BuildTimeFlags |= MethodRepresentation.BuildTimeAttributes.DisableBoundsChecks; } } [CompilationSteps.CustomAttributeNotification( "Microsoft_Zelig_Runtime_DisableNullChecksAttribute" )] private void Notify_DisableNullChecksAttribute( ref bool fKeep , CustomAttributeRepresentation ca , MethodRepresentation owner ) { fKeep = false; if(ca.GetNamedArg( "ApplyRecursively" ) != null) { owner.BuildTimeFlags |= MethodRepresentation.BuildTimeAttributes.DisableDeepNullChecks; } else { owner.BuildTimeFlags |= MethodRepresentation.BuildTimeAttributes.DisableNullChecks; } } //LON: 2/16/09 [CompilationSteps.CustomAttributeNotification( "Microsoft_Zelig_Runtime_ImportedMethodReferenceAttribute" )] private void Notify_ImportedMethodReferenceAttribute( ref bool fKeep , CustomAttributeRepresentation ca , MethodRepresentation owner ) { fKeep = true; owner.BuildTimeFlags |= MethodRepresentation.BuildTimeAttributes.Imported; // for now disable inlining of these methods owner.BuildTimeFlags |= MethodRepresentation.BuildTimeAttributes.NoInline; owner.BuildTimeFlags &= ~MethodRepresentation.BuildTimeAttributes.Inline; } //LON: 2/16/09 [CompilationSteps.CustomAttributeNotification( "Microsoft_Zelig_Runtime_ExportedMethodAttribute" )] private void Notify_ExportedMethodAttribute( ref bool fKeep , CustomAttributeRepresentation ca , MethodRepresentation owner ) { fKeep = false; owner.BuildTimeFlags |= MethodRepresentation.BuildTimeAttributes.Exported; // for now disable inlining of these methods owner.BuildTimeFlags |= MethodRepresentation.BuildTimeAttributes.NoInline; owner.BuildTimeFlags &= ~MethodRepresentation.BuildTimeAttributes.Inline; if(this.PlatformAbstraction.PlatformVersion == TargetModel.ArmProcessor.InstructionSetVersion.Platform_Version__ARMv7M || this.PlatformAbstraction.PlatformVersion == TargetModel.ArmProcessor.InstructionSetVersion.Platform_Version__ARMv6M || this.PlatformAbstraction.PlatformVersion == TargetModel.Win32.InstructionSetVersion.Platform_Version__x86 ) { CustomAttributeRepresentation cf = owner.FindCustomAttribute( this.WellKnownTypes.Microsoft_Zelig_Runtime_CapabilitiesFilterAttribute ); if(cf != null) { object obj = cf.GetNamedArg( "RequiredCapabilities" ); if(obj != null) { uint capabilities = (uint)obj; uint reqFamily = capabilities & TargetModel.ArmProcessor.InstructionSetVersion.Platform_Family__Mask; uint reqVFP = capabilities & TargetModel.ArmProcessor.InstructionSetVersion.Platform_VFP__Mask; uint reqPlatformVersion = capabilities & TargetModel.ArmProcessor.InstructionSetVersion.Platform_Version__Mask; if(reqFamily != 0 && reqFamily != this.PlatformAbstraction.PlatformFamily) { // This method does not conform to the capabilities of the platform we are compiling return; } else if(reqVFP != 0 && reqVFP != this.PlatformAbstraction.PlatformVFP) { // This method does not conform to the capabilities of the platform we are compiling return; } else if(reqPlatformVersion != 0 && reqPlatformVersion != this.PlatformAbstraction.PlatformVersion) { // This method does not conform to the capabilities of the platform we are compiling return; } } } ExportedMethods.Add(owner); } } //--// [CompilationSteps.CustomAttributeNotification( "Microsoft_Zelig_Runtime_TypeSystem_GarbageCollectionExtensionAttribute" )] private void Notify_GarbageCollectionExtensionAttribute( ref bool fKeep , CustomAttributeRepresentation ca , TypeRepresentation owner ) { var td = (TypeRepresentation)ca.FixedArgsValues[0]; m_garbageCollectionExtensions.Add( td, owner ); } [CompilationSteps.CustomAttributeNotification( "Microsoft_Zelig_Runtime_TypeSystem_SkipDuringGarbageCollectionAttribute" )] private void Notify_SkipDuringGarbageCollectionAttribute( ref bool fKeep , CustomAttributeRepresentation ca , FieldRepresentation owner ) { m_garbageCollectionExclusions.Insert( owner ); } [CompilationSteps.CustomAttributeNotification( "Microsoft_Zelig_Runtime_TypeSystem_DisableReferenceCountingAttribute" )] private void Notify_EnableReferenceCountingAttribute( ref bool fKeep, CustomAttributeRepresentation ca, TypeRepresentation owner ) { m_referenceCountingExcludedTypes.Insert( owner ); } [CompilationSteps.CustomAttributeNotification( "Microsoft_Zelig_Runtime_TypeSystem_DisableAutomaticReferenceCountingAttribute" )] private void Notify_DisableAutomaticReferenceCountingAttribute( ref bool fKeep, CustomAttributeRepresentation ca, BaseRepresentation owner ) { if(owner is MethodRepresentation) { AddAutomaticReferenceCountingExclusion( (MethodRepresentation)owner ); } else if(owner is TypeRepresentation) { var tr = (TypeRepresentation)owner; foreach(var mr in tr.Methods) { AddAutomaticReferenceCountingExclusion( mr ); } } } private void AddAutomaticReferenceCountingExclusion( MethodRepresentation md ) { if(md.IsGenericInstantiation) { md = md.GenericTemplate; } var methodsList = m_automaticReferenceCountingExclusions.GetValue( md.Name ); if(methodsList == null) { methodsList = new List( ); m_automaticReferenceCountingExclusions.Add( md.Name, methodsList ); } if(!methodsList.Contains( md )) { methodsList.Add( md ); } } //--// [CompilationSteps.CustomAttributeNotification( "Microsoft_Zelig_Runtime_AlignmentRequirementsAttribute" )] private void Notify_AlignmentRequirementsAttribute( ref bool fKeep , CustomAttributeRepresentation ca , BaseRepresentation owner ) { Abstractions.PlacementRequirements pr = CreatePlacementRequirements( owner ); pr.Alignment = (uint)ca.FixedArgsValues[0]; pr.AlignmentOffset = (int )ca.FixedArgsValues[1]; } [CompilationSteps.CustomAttributeNotification( "Microsoft_Zelig_Runtime_MemoryRequirementsAttribute" )] private void Notify_MemoryRequirementsAttribute( ref bool fKeep , CustomAttributeRepresentation ca , BaseRepresentation owner ) { Abstractions.PlacementRequirements pr = CreatePlacementRequirements( owner ); pr.AddConstraint( (Runtime.MemoryAttributes)ca.FixedArgsValues[0] ); } [CompilationSteps.CustomAttributeNotification( "Microsoft_Zelig_Runtime_MemoryUsageAttribute" )] private void Notify_MemoryUsageAttribute( ref bool fKeep , CustomAttributeRepresentation ca , BaseRepresentation owner ) { Abstractions.PlacementRequirements pr = CreatePlacementRequirements( owner ); pr.AddConstraint( (Runtime.MemoryUsage)ca.FixedArgsValues[0] ); pr.AddConstraint( ca.GetNamedArg( "SectionName", null ) ); pr.ContentsUninitialized = ca.GetNamedArg( "ContentsUninitialized" , false ); pr.AllocateFromHighAddress = ca.GetNamedArg( "AllocateFromHighAddress", false ); } //--// [CompilationSteps.CustomAttributeNotification( "Microsoft_Zelig_Runtime_HardwareExceptionHandlerAttribute" )] private void Notify_HardwareExceptionHandlerAttribute( ref bool fKeep , CustomAttributeRepresentation ca , MethodRepresentation owner ) { m_hardwareExceptionHandlers[ owner ] = ca; } [CompilationSteps.CustomAttributeNotification( "Microsoft_Zelig_Runtime_DebuggerHookHandlerAttribute" )] private void Notify_DebuggerHookHandlerAttribute( ref bool fKeep , CustomAttributeRepresentation ca , MethodRepresentation owner ) { if(this.ExcludeDebuggerHooks == false) { m_debuggerHookHandlers[owner] = ca; } } [CompilationSteps.CustomAttributeNotification( "Microsoft_Zelig_Runtime_SingletonFactoryAttribute" )] private void Notify_SingletonFactoryAttribute( ref bool fKeep , CustomAttributeRepresentation ca , MethodRepresentation owner ) { m_singletonFactories[ owner ] = ca; var tdFallback = ca.GetNamedArg( "Fallback" ) as TypeRepresentation; if(tdFallback != null) { m_singletonFactoriesFallback[owner.OwnerType] = tdFallback; } } //--// [CompilationSteps.CustomAttributeNotification( "Microsoft_Zelig_Runtime_TypeSystem_NoVTableAttribute" )] private void Notify_NoVTableAttribute( ref bool fKeep , CustomAttributeRepresentation ca , TypeRepresentation owner ) { owner.BuildTimeFlags |= TypeRepresentation.BuildTimeAttributes.NoVTable; } //--//--// [CompilationSteps.CustomAttributeNotification( "Microsoft_Zelig_Runtime_MemoryMappedPeripheralAttribute" )] private void Notify_MemoryMappedPeripheralAttribute( ref bool fKeep , CustomAttributeRepresentation ca , TypeRepresentation owner ) { m_memoryMappedPeripherals[ owner ] = ca; RegisterAsMemoryMappedPeripheral( owner ); if(owner is ConcreteReferenceTypeRepresentation) { CheckRequiredFieldForMemoryMappedPeripheralAttribute( owner, "Base" ); CheckRequiredFieldForMemoryMappedPeripheralAttribute( owner, "Length" ); } } [CompilationSteps.CustomAttributeNotification( "Microsoft_Zelig_Runtime_RegisterAttribute" )] private void Notify_RegisterAttribute( ref bool fKeep , CustomAttributeRepresentation ca , FieldRepresentation owner ) { CheckRequiredField( ca, owner, "Offset" ); m_registerAttributes[ owner ] = ca; RegisterAsMemoryMappedPeripheral( owner.OwnerType ); } private void RegisterAsMemoryMappedPeripheral( TypeRepresentation td ) { for(var td2 = td; td2 != null && td2 != this.WellKnownTypes.System_Object; td2 = td2.Extends) { if(m_memoryMappedPeripherals.ContainsKey( td2 ) == false) { if(td == td2) { throw TypeConsistencyErrorException.Create( "'{0}' is not marked as a memory-mapped class", td.FullName ); } else { throw TypeConsistencyErrorException.Create( "Cannot have memory-mapped class derive from a non-memory-mapped one: '{0}' => '{1}'", td.FullName, td2.FullName ); } } } td.BuildTimeFlags |= TypeRepresentation.BuildTimeAttributes.NoVTable; RegisterForTypeLayoutDelegation( td, Notify_LayoutMemoryMappedPeripheral ); } //--// private bool Notify_LayoutMemoryMappedPeripheral( TypeRepresentation td , GrowOnlySet< TypeRepresentation > history ) { uint maxSize = 0; { TypeRepresentation tdSize = td; while(tdSize != null) { CustomAttributeRepresentation ca; if(m_memoryMappedPeripherals.TryGetValue( tdSize, out ca )) { object sizeObj = ca.GetNamedArg( "Length" ); if(sizeObj != null) { maxSize = (uint)sizeObj; break; } } tdSize = tdSize.Extends; } } foreach(FieldRepresentation fd in td.Fields) { if(fd is InstanceFieldRepresentation) { CustomAttributeRepresentation caFd; if(m_registerAttributes.TryGetValue( fd, out caFd ) == false) { throw TypeConsistencyErrorException.Create( "Cannot have non-register field '{0}' in memory-mapped class '{1}'", fd.Name, td.FullNameWithAbbreviation ); } var tdField = fd.FieldType; EnsureTypeLayout( tdField, history, this.PlatformAbstraction.MemoryAlignment ); fd.Offset = (int)(uint)caFd.GetNamedArg( "Offset" ); maxSize = Math.Max( (uint)(fd.Offset + tdField.SizeOfHoldingVariable), maxSize ); } } td.Size = maxSize; return true; } //--//--// [CompilationSteps.CustomAttributeNotification( "Microsoft_Zelig_Runtime_BitFieldPeripheralAttribute" )] private void Notify_BitFieldPeripheralAttribute( ref bool fKeep , CustomAttributeRepresentation ca , TypeRepresentation owner ) { CheckRequiredField( ca, owner, "PhysicalType" ); owner.BuildTimeFlags |= TypeRepresentation.BuildTimeAttributes.NoVTable; m_memoryMappedBitFieldPeripherals[ owner ] = ca; RegisterForTypeLayoutDelegation( owner, Layout_LayoutMemoryMappedBitFieldPeripheral ); } [CompilationSteps.CustomAttributeNotification( "Microsoft_Zelig_Runtime_BitFieldRegisterAttribute" )] private void Notify_BitFieldRegisterAttribute( ref bool fKeep , CustomAttributeRepresentation ca , FieldRepresentation owner ) { var sec = CreateSectionOfBitFieldDefinition( ca, owner ); HandleBitFieldRegisterAttributeCommon( ref fKeep, ca, owner, sec ); } [CompilationSteps.CustomAttributeNotification( "Microsoft_Zelig_Runtime_BitFieldSplitRegisterAttribute" )] private void Notify_BitFieldSplitRegisterAttribute( ref bool fKeep , CustomAttributeRepresentation ca , FieldRepresentation owner ) { var sec = CreateSectionOfBitFieldDefinition( ca, owner ); if(ca.TryToGetNamedArg( "Offset", out sec.Offset ) == false) { FailedRequiredField( ca, owner, "Offset" ); } HandleBitFieldRegisterAttributeCommon( ref fKeep, ca, owner, sec ); } private BitFieldDefinition.Section CreateSectionOfBitFieldDefinition( CustomAttributeRepresentation ca , FieldRepresentation owner ) { BitFieldDefinition.Section sec = new BitFieldDefinition.Section(); if(ca.TryToGetNamedArg( "Position", out sec.Position ) == false) { FailedRequiredField( ca, owner, "Position" ); } if(ca.TryToGetNamedArg( "Size", out sec.Size ) == false) { if(owner.FieldType != this.WellKnownTypes.System_Boolean) { FailedRequiredField( ca, owner, "Size" ); } sec.Size = 1; } ca.TryToGetNamedArg( "Modifiers", out sec.Modifiers ); ca.TryToGetNamedArg( "ReadAs" , out sec.ReadsAs ); ca.TryToGetNamedArg( "WriteAs" , out sec.WritesAs ); return sec; } private void HandleBitFieldRegisterAttributeCommon( ref bool fKeep , CustomAttributeRepresentation ca , FieldRepresentation owner , BitFieldDefinition.Section sec ) { fKeep = false; if(m_memoryMappedBitFieldPeripherals.ContainsKey( owner.OwnerType ) == false) { throw TypeConsistencyErrorException.Create( "Containing type '{0}' of bitfield register '{1}' must be a bitfield peripheral", owner.OwnerType.FullName, owner ); } BitFieldDefinition bfDef; if(m_bitFieldRegisterAttributes.TryGetValue( owner, out bfDef ) == false) { bfDef = new BitFieldDefinition(); m_bitFieldRegisterAttributes[ owner ] = bfDef; } bfDef.AddSection( sec ); } //--// private bool Layout_LayoutMemoryMappedBitFieldPeripheral( TypeRepresentation td , GrowOnlySet< TypeRepresentation > history ) { CustomAttributeRepresentation ca = m_memoryMappedBitFieldPeripherals[td]; TypeRepresentation tdPhysical = ca.GetNamedArg< TypeRepresentation >( "PhysicalType" ); EnsureTypeLayout( tdPhysical, history, this.PlatformAbstraction.MemoryAlignment ); td.Size = tdPhysical.Size; foreach(FieldRepresentation fd in td.Fields) { if(fd is StaticFieldRepresentation) { throw TypeConsistencyErrorException.Create( "Cannot have static field '{0}' in memory-mapped bitfield class '{1}'", fd.Name, td.FullNameWithAbbreviation ); } if(m_bitFieldRegisterAttributes.ContainsKey( fd ) == false) { throw TypeConsistencyErrorException.Create( "Cannot have non-bitfield register field '{0}' in memory-mapped bitfield class '{1}'", fd.Name, td.FullNameWithAbbreviation ); } fd.Offset = 0; } return true; } //--//--// private void CheckRequiredFieldForMemoryMappedPeripheralAttribute( TypeRepresentation target , string name ) { for(TypeRepresentation td = target; td != null; td = td.Extends) { CustomAttributeRepresentation ca; if(m_memoryMappedPeripherals.TryGetValue( td, out ca )) { if(ca.HasNamedArg( name )) { return; } } } throw TypeConsistencyErrorException.Create( "Cannot find required '{0}' field for attribute MemoryMappedPeripheralAttribute on the hierarchy for {2}", name, target ); } private static void CheckRequiredField( CustomAttributeRepresentation ca , object owner , string name ) { if(ca.HasNamedArg( name ) == false) { FailedRequiredField( ca, owner, name ); } } private static void FailedRequiredField( CustomAttributeRepresentation ca , object owner , string name ) { throw TypeConsistencyErrorException.Create( "Missing required '{0}' field for attribute '{1}' on '{2}'", name, ca.Constructor.OwnerType.FullName, owner ); } } } ================================================ FILE: Zelig/Zelig/CompileTime/CodeGenerator/CodeTransformation/TypeSystemSerializer.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // #define READER__USE_EMIT //#define DEBUG_PERSISTENCE //#define DEBUG_PERSISTENCE__COUNT_INSTANCES namespace Microsoft.Zelig.CodeGeneration.IR { using System; using System.Collections.Generic; using System.Reflection; #if READER__USE_EMIT using System.Reflection.Emit; #endif using Microsoft.Zelig.Runtime.TypeSystem; using Microsoft.Zelig.Elf; using Microsoft.Zelig.CodeGeneration.IR.ExternalMethodImporters; public static class TypeSystemSerializer { public delegate object CreateInstance( Type t ); public delegate void ProgressCallback( long pos, long total ); enum RecordType : byte { Null , Index , Class , ClassNoDef , Array , TypeUse , TypeDefinition, } const string VersionId = "v1.0.0.0, 20081009"; //--// public static TransformationContextForCodeTransformation GetSerializationContext( System.IO.Stream stream ) { return new Writer( stream ); } public static TransformationContextForCodeTransformation GetDeserializationContext( System.IO.Stream stream , CreateInstance callback , ProgressCallback feedback , int feedbackQuantum ) { return new Reader( stream, callback, feedback, feedbackQuantum ); } //--// public static void Serialize( System.IO.Stream stream , TypeSystemForCodeTransformation typeSystem ) { using(TransformationContextForCodeTransformation ctx = GetSerializationContext( stream )) { ctx.Transform( ref typeSystem ); } } public static TypeSystemForCodeTransformation Deserialize( System.IO.Stream stream , CreateInstance callback , ProgressCallback feedback , int feedbackQuantum ) { TransformationContextForCodeTransformation ctx = GetDeserializationContext( stream, callback, feedback, feedbackQuantum ); TypeSystemForCodeTransformation typeSystem = null; ctx.Transform( ref typeSystem ); return typeSystem; } //--// // // PersistenceContextForSerialization // internal class Writer : TransformationContextForCodeTransformation { // // State // static GrowOnlyHashTable< Type, System.Reflection.MethodInfo > s_handlers; static DynamicTransform s_dynamicTransform; System.IO.Stream m_payload; System.IO.BinaryWriter m_writer; object m_pending; // Transform( ref object ) has to go through Visit twice. Keep track of it. GrowOnlyHashTable< object, int > m_objectToIndex = HashTableFactory.NewWithReferenceEquality< object, int >(); GrowOnlyHashTable< Type , int > m_typeToIndex = HashTableFactory.NewWithReferenceEquality< Type , int >(); GrowOnlyHashTable< string, int > m_stringToIndex = HashTableFactory.New < string, int >(); #if DEBUG_PERSISTENCE__COUNT_INSTANCES GrowOnlyHashTable< Type , int > m_countTypes = HashTableFactory.NewWithReferenceEquality< Type , int >(); #endif // // Constructor Methods // internal Writer( System.IO.Stream payload ) { m_payload = payload; m_writer = new System.IO.BinaryWriter( m_payload, System.Text.Encoding.UTF8 ); m_writer.Write( VersionId ); } // // Helper Methods // public override void Dispose() { Flush(); } internal void Flush() { #if DEBUG_PERSISTENCE__COUNT_INSTANCES Type[] keys = m_countTypes.KeysToArray(); Array.Sort( keys, delegate( Type t1, Type t2 ) { return - m_countTypes[t1].CompareTo( m_countTypes[t2] ); } ); foreach(Type t in keys) { Console.WriteLine( "{0,-100} : {1}", t, m_countTypes[t] ); } #endif m_writer.Flush(); } //--// private bool FindObject( object obj , out int idx ) { if(m_objectToIndex.TryGetValue( obj, out idx )) { return true; } if(obj is string) { if(m_stringToIndex.TryGetValue( (string)obj, out idx )) { return true; } } return false; } private void NewObject( object obj ) { if(obj is ValueType) { return; } #if DEBUG_PERSISTENCE Console.WriteLine( "NewObject {0} {1}", obj.GetType(), m_objectToIndex.Count, obj ); #endif //// if(m_objectToIndex.Count == ) //// { //// } #if DEBUG_PERSISTENCE__COUNT_INSTANCES { int count; if(m_countTypes.TryGetValue( obj.GetType(), out count ) == false) { count = 0; } m_countTypes[ obj.GetType() ] = count + 1; } #endif int idx = m_objectToIndex.Count; m_objectToIndex[obj] = idx; if(obj is string) { m_stringToIndex[(string)obj] = idx; } } private void NewType( Type type ) { m_typeToIndex[type] = m_typeToIndex.Count; } //--// private void EmitRecordType( RecordType rt ) { m_writer.Write( (byte)rt ); } private void EmitRecordType( RecordType rt , int idx ) { m_writer.Write( (byte)rt ); m_writer.Write( idx ); } private bool HasPending( object target ) { if(m_pending != null) { CHECKS.ASSERT( m_pending == target, "Internal error, ScanTypeSystem was expecting {0}, got {1}", m_pending, target ); m_pending = null; return true; } return false; } protected override void ClearPending() { m_pending = null; } //--// private bool EmitArraySignature( T[] array ) { return EmitSignature( array, typeof(T[]) ); } private bool EmitSignature( T obj ) where T : class { return EmitSignature( obj, typeof(T) ); } private bool EmitSignature( object obj , Type typeExpected ) { return EmitSignature( obj, obj != null ? obj.GetType() : null, typeExpected ); } private bool EmitSignature( object obj , Type typeForSerialization , Type typeExpected ) { if(HasPending( obj )) { return true; } if(obj == null) { #if DEBUG_PERSISTENCE Console.WriteLine( "RecordType.Null" ); #endif EmitRecordType( RecordType.Null ); return false; } int idx; if(FindObject( obj, out idx )) { EmitRecordType( RecordType.Index, idx ); #if DEBUG_PERSISTENCE Console.WriteLine( "RecordType.Index {0} {1}", idx, m_writer.BaseStream.Position ); #endif return false; } EncodeTypeDefinition( typeForSerialization, typeExpected ); NewObject( obj ); if( obj is string) { m_writer.Write( (string)obj ); } else if(obj is bool ) { m_writer.Write( (bool )obj ); } else if(obj is byte ) { m_writer.Write( (byte )obj ); } else if(obj is sbyte ) { m_writer.Write( (sbyte )obj ); } else if(obj is char ) { m_writer.Write( (char )obj ); } else if(obj is short ) { m_writer.Write( (short )obj ); } else if(obj is ushort) { m_writer.Write( (ushort)obj ); } else if(obj is int ) { m_writer.Write( (int )obj ); } else if(obj is uint ) { m_writer.Write( (uint )obj ); } else if(obj is long ) { m_writer.Write( (long )obj ); } else if(obj is ulong ) { m_writer.Write( (ulong )obj ); } else if(obj is float ) { m_writer.Write( (float )obj ); } else if(obj is double) { m_writer.Write( (double)obj ); } else if(obj is Type) { EncodeTypeDefinition( (Type)obj, null ); } else if(obj is Array) { Array array = (Array)obj; m_writer.Write( (int)array.Length ); #if DEBUG_PERSISTENCE Console.WriteLine( "array.Length {0}", array.Length ); #endif return array.Length > 0; } else { return true; } return false; } //--// private int EmitListSize( List lst ) { bool fContinue = EmitSignature( lst ); if(fContinue) { int count = lst.Count; m_writer.Write( count ); #if DEBUG_PERSISTENCE Console.WriteLine( "list.Count {0}", count ); #endif return count; } return -1; } //--// private void EncodeTypeDefinition( Type type , Type typeTarget ) { int idx; if(type == typeTarget) { #if DEBUG_PERSISTENCE Console.WriteLine( "RecordType.ClassNoDef {0}", type ); #endif EmitRecordType( RecordType.ClassNoDef ); } else if(m_typeToIndex.TryGetValue( type, out idx )) { #if DEBUG_PERSISTENCE Console.WriteLine( "RecordType.TypeUse {0}", idx ); #endif EmitRecordType( RecordType.TypeUse, idx ); } else { #if DEBUG_PERSISTENCE Console.WriteLine( "RecordType.TypeDefinition {0}", m_typeToIndex.Count ); #endif EmitRecordType( RecordType.TypeDefinition ); if(type.IsArray) { #if DEBUG_PERSISTENCE Console.WriteLine( "RecordType.Array" ); #endif EmitRecordType( RecordType.Array ); EncodeTypeDefinition( type.GetElementType(), null ); } else { #if DEBUG_PERSISTENCE Console.WriteLine( "RecordType.Class" ); #endif EmitRecordType( RecordType.Class ); if(type.IsGenericType) { Type templateType = type.GetGenericTypeDefinition(); Type[] argsType = type.GetGenericArguments(); m_writer.Write( templateType.AssemblyQualifiedName ); m_writer.Write( argsType.Length ); foreach(Type argType in argsType) { EncodeTypeDefinition( argType, null ); } #if DEBUG_PERSISTENCE Console.WriteLine( "TypeName '{0}' : {1}", type.AssemblyQualifiedName, argsType.Length ); #endif } else { #if DEBUG_PERSISTENCE Console.WriteLine( "TypeName '{0}'", type.AssemblyQualifiedName ); #endif m_writer.Write( type.AssemblyQualifiedName ); } } NewType( type ); } } //--// // // PersistenceContext // protected override bool ShouldTransform( object target ) { return true; } public override void MarkAsVisited( object obj ) { } public override void Push( object ctx ) { } public override void Pop() { } public override object TopContext() { return null; } public override object FindContext( Type ctx ) { return null; } public override object GetTransformInitiator() { return null; } public override TypeSystem GetTypeSystem() { return null; } //--// public override void Transform( ref ITransformationContextTarget itf ) { if(EmitSignature( itf )) { itf.ApplyTransformation( this ); } } //--// public override void Transform( ref bool val ) { ClearPending(); m_writer.Write( val ); } public override void Transform( ref char val ) { ClearPending(); m_writer.Write( val ); } public override void Transform( ref sbyte val ) { ClearPending(); m_writer.Write( val ); } public override void Transform( ref byte val ) { ClearPending(); m_writer.Write( val ); } public override void Transform( ref short val ) { ClearPending(); m_writer.Write( val ); } public override void Transform( ref ushort val ) { ClearPending(); m_writer.Write( val ); } public override void Transform( ref int val ) { ClearPending(); m_writer.Write( val ); } public override void Transform( ref uint val ) { ClearPending(); m_writer.Write( val ); } public override void Transform( ref long val ) { ClearPending(); m_writer.Write( val ); } public override void Transform( ref ulong val ) { ClearPending(); m_writer.Write( val ); } public override void Transform( ref float val ) { ClearPending(); m_writer.Write( val ); } public override void Transform( ref double val ) { ClearPending(); m_writer.Write( val ); } public override void Transform( ref IntPtr val ) { ClearPending(); m_writer.Write( val.ToInt32() ); } public override void Transform( ref UIntPtr val ) { ClearPending(); m_writer.Write( val.ToUInt32() ); } public override void Transform( ref string val ) { if(EmitSignature( val )) { ; // Nothing else to do. } } public override void Transform( ref object val ) { if(EmitSignature( val, null )) { if(val is ExternalDataDescriptor) { } else if(val is ArmElfExternalDataContext) { } else { m_pending = val; val = TransformGenericReference( val ); } } } public override void Transform( ref Type val ) { if(EmitSignature( val, null )) { ; // Nothing else to do. } } //--// public override void Transform( ref bool[] valArray ) { if(EmitArraySignature( valArray )) { for(int i = 0; i < valArray.Length; i++) { m_writer.Write( valArray[i] ); } } } public override void Transform( ref char[] valArray ) { if(EmitArraySignature( valArray )) { for(int i = 0; i < valArray.Length; i++) { m_writer.Write( valArray[i] ); } } } public override void Transform( ref sbyte[] valArray ) { if(EmitArraySignature( valArray )) { for(int i = 0; i < valArray.Length; i++) { m_writer.Write( valArray[i] ); } } } public override void Transform( ref byte[] valArray ) { if(EmitArraySignature( valArray )) { m_writer.Write( valArray, 0, valArray.Length ); } } public override void Transform( ref short[] valArray ) { if(EmitArraySignature( valArray )) { for(int i = 0; i < valArray.Length; i++) { m_writer.Write( valArray[i] ); } } } public override void Transform( ref ushort[] valArray ) { if(EmitArraySignature( valArray )) { for(int i = 0; i < valArray.Length; i++) { m_writer.Write( valArray[i] ); } } } public override void Transform( ref int[] valArray ) { if(EmitArraySignature( valArray )) { for(int i = 0; i < valArray.Length; i++) { m_writer.Write( valArray[i] ); } } } public override void Transform( ref uint[] valArray ) { if(EmitArraySignature( valArray )) { for(int i = 0; i < valArray.Length; i++) { m_writer.Write( valArray[i] ); } } } public override void Transform( ref long[] valArray ) { if(EmitArraySignature( valArray )) { for(int i = 0; i < valArray.Length; i++) { m_writer.Write( valArray[i] ); } } } public override void Transform( ref ulong[] valArray ) { if(EmitArraySignature( valArray )) { for(int i = 0; i < valArray.Length; i++) { m_writer.Write( valArray[i] ); } } } public override void Transform( ref float[] valArray ) { if(EmitArraySignature( valArray )) { for(int i = 0; i < valArray.Length; i++) { m_writer.Write( valArray[i] ); } } } public override void Transform( ref double[] valArray ) { if(EmitArraySignature( valArray )) { for(int i = 0; i < valArray.Length; i++) { m_writer.Write( valArray[i] ); } } } public override void Transform( ref IntPtr[] valArray ) { if(EmitArraySignature( valArray )) { for(int i = 0; i < valArray.Length; i++) { m_writer.Write( valArray[i].ToInt32() ); } } } public override void Transform( ref UIntPtr[] valArray ) { if(EmitArraySignature( valArray )) { for(int i = 0; i < valArray.Length; i++) { m_writer.Write( valArray[i].ToUInt32() ); } } } public override void Transform( ref string[] valArray ) { if(EmitArraySignature( valArray )) { var array = valArray; // Get a local copy, because the original could change, due to the 'ref' argument. for(int i = 0; i < array.Length; i++) { Transform( ref array[i] ); } } } public override void Transform( ref object[] objArray ) { if(EmitArraySignature( objArray )) { var array = objArray; // Get a local copy, because the original could change, due to the 'ref' argument. for(int i = 0; i < array.Length; i++) { Transform( ref array[i] ); } } } //--// public override void Transform( ref List< string > strLst ) { int count = EmitListSize( strLst ); var lst = strLst; // Get a local copy, because the original could change, due to the 'ref' argument. for(int i = 0; i < count; i++) { string str = lst[i]; Transform( ref str ); } } //--// public override void Transform( ref Debugging.DebugInfo debugInfo ) { if(EmitSignature( debugInfo )) { Transform( ref debugInfo.SrcFileName ); Transform( ref debugInfo.MethodName ); Transform( ref debugInfo.BeginLineNumber ); Transform( ref debugInfo.BeginColumn ); Transform( ref debugInfo.EndLineNumber ); Transform( ref debugInfo.EndColumn ); } } //--// public override void Transform( ref WellKnownTypes wkt ) { if(EmitSignature( wkt )) { wkt.ApplyTransformation( this ); } } public override void Transform( ref WellKnownMethods wkm ) { if(EmitSignature( wkm )) { wkm.ApplyTransformation( this ); } } public override void Transform( ref WellKnownFields wkf ) { if(EmitSignature( wkf )) { wkf.ApplyTransformation( this ); } } //--// public override void Transform( ref AssemblyRepresentation asml ) { if(EmitSignature( asml )) { asml.ApplyTransformation( this ); } } public override void Transform( ref List< AssemblyRepresentation > asmlLst ) { int count = EmitListSize( asmlLst ); var lst = asmlLst; // Get a local copy, because the original could change, due to the 'ref' argument. for(int i = 0; i < count; i++) { AssemblyRepresentation asml = lst[i]; Transform( ref asml ); } } public override void Transform( ref AssemblyRepresentation.VersionData ver ) { ClearPending(); ver.ApplyTransformation( this ); } public override void Transform( ref AssemblyRepresentation.VersionData.AssemblyFlags val ) { ClearPending(); m_writer.Write( (int)val ); } //--// public override void Transform( ref BaseRepresentation bd ) { if(EmitSignature( bd )) { bd.ApplyTransformation( this ); } } //--// public override void Transform( ref TypeRepresentation td ) { if(EmitSignature( td )) { td.ApplyTransformation( this ); } } public override void Transform( ref ValueTypeRepresentation td ) { if(EmitSignature( td )) { td.ApplyTransformation( this ); } } public override void Transform( ref ArrayReferenceTypeRepresentation td ) { if(EmitSignature( td )) { td.ApplyTransformation( this ); } } public override void Transform( ref InterfaceTypeRepresentation itf ) { if(EmitSignature( itf )) { itf.ApplyTransformation( this ); } } public override void Transform( ref TypeRepresentation[] tdArray ) { if(EmitArraySignature( tdArray )) { var array = tdArray; // Get a local copy, because the original could change, due to the 'ref' argument. for(int i = 0; i < array.Length; i++) { Transform( ref array[i] ); } } } public override void Transform( ref InterfaceTypeRepresentation[] itfArray ) { if(EmitArraySignature( itfArray )) { var array = itfArray; // Get a local copy, because the original could change, due to the 'ref' argument. for(int i = 0; i < array.Length; i++) { Transform( ref array[i] ); } } } public override void Transform( ref List< TypeRepresentation > tdLst ) { int count = EmitListSize( tdLst ); var lst = tdLst; // Get a local copy, because the original could change, due to the 'ref' argument. for(int i = 0; i < count; i++) { TypeRepresentation td = lst[i]; Transform( ref td ); } } public override void Transform( ref FieldRepresentation fd ) { if(EmitSignature( fd )) { fd.ApplyTransformation( this ); } } public override void Transform( ref InstanceFieldRepresentation fd ) { if(EmitSignature( fd )) { fd.ApplyTransformation( this ); } } public override void Transform( ref StaticFieldRepresentation fd ) { if(EmitSignature( fd )) { fd.ApplyTransformation( this ); } } public override void Transform( ref FieldRepresentation[] fdArray ) { if(EmitArraySignature( fdArray )) { var array = fdArray; // Get a local copy, because the original could change, due to the 'ref' argument. for(int i = 0; i < array.Length; i++) { Transform( ref array[i] ); } } } public override void Transform( ref InstanceFieldRepresentation[] fdArray ) { if(EmitArraySignature( fdArray )) { var array = fdArray; // Get a local copy, because the original could change, due to the 'ref' argument. for(int i = 0; i < array.Length; i++) { Transform( ref array[i] ); } } } public override void Transform( ref MethodRepresentation md ) { if(EmitSignature( md )) { md.ApplyTransformation( this ); } } public override void Transform( ref MethodRepresentation[] mdArray ) { if(EmitArraySignature( mdArray )) { var array = mdArray; // Get a local copy, because the original could change, due to the 'ref' argument. for(int i = 0; i < array.Length; i++) { Transform( ref array[i] ); } } } public override void Transform( ref List resLst ) { int count = EmitListSize( resLst ); var lst = resLst; // Get a local copy, because the original could change, due to the 'ref' argument. for(int i = 0; i < count; i++) { MethodRepresentation res = lst[i]; Transform( ref res ); } } public override void Transform( ref MethodImplRepresentation mi ) { if(EmitSignature( mi )) { mi.ApplyTransformation( this ); } } public override void Transform( ref MethodImplRepresentation[] miArray ) { if(EmitArraySignature( miArray )) { var array = miArray; // Get a local copy, because the original could change, due to the 'ref' argument. for(int i = 0; i < array.Length; i++) { Transform( ref array[i] ); } } } public override void Transform( ref GenericParameterDefinition param ) { ClearPending(); param.ApplyTransformation( this ); } public override void Transform( ref GenericParameterDefinition[] paramArray ) { if(EmitArraySignature( paramArray )) { var array = paramArray; // Get a local copy, because the original could change, due to the 'ref' argument. for(int i = 0; i < array.Length; i++) { Transform( ref array[i] ); } } } //--// public override void Transform( ref CustomAttributeRepresentation ca ) { if(EmitSignature( ca )) { ca.ApplyTransformation( this ); } } public override void Transform( ref CustomAttributeRepresentation[] caArray ) { if(EmitArraySignature( caArray )) { var array = caArray; // Get a local copy, because the original could change, due to the 'ref' argument. for(int i = 0; i < array.Length; i++) { Transform( ref array[i] ); } } } //--// public override void Transform( ref CustomAttributeAssociationRepresentation caa ) { if(EmitSignature( caa )) { caa.ApplyTransformation( this ); } } public override void Transform( ref CustomAttributeAssociationRepresentation[] caaArray ) { if(EmitArraySignature( caaArray )) { var array = caaArray; // Get a local copy, because the original could change, due to the 'ref' argument. for(int i = 0; i < array.Length; i++) { Transform( ref array[i] ); } } } //--// public override void Transform( ref ResourceRepresentation res ) { if(EmitSignature( res )) { res.ApplyTransformation( this ); } } public override void Transform( ref List< ResourceRepresentation > resLst ) { int count = EmitListSize( resLst ); var lst = resLst; // Get a local copy, because the original could change, due to the 'ref' argument. for(int i = 0; i < count; i++) { ResourceRepresentation res = lst[i]; Transform( ref res ); } } public override void Transform( ref ResourceRepresentation.Attributes val ) { ClearPending(); m_writer.Write( (int)val ); } public override void Transform( ref ResourceRepresentation.Pair[] pairArray ) { if(EmitArraySignature( pairArray )) { var array = pairArray; // Get a local copy, because the original could change, due to the 'ref' argument. for(int i = 0; i < array.Length; i++) { TransformGeneric( ref array[i] ); } } } //--// public override void Transform( ref VTable vTable ) { if(EmitSignature( vTable )) { vTable.ApplyTransformation( this ); } } public override void Transform( ref VTable.InterfaceMap iMap ) { ClearPending(); Transform( ref iMap.Interface ); Transform( ref iMap.MethodPointers ); } public override void Transform( ref GCInfo gi ) { ClearPending(); Transform( ref gi.Pointers ); } public override void Transform( ref GCInfo.Kind giKind ) { ClearPending(); m_writer.Write( (short)giKind ); } public override void Transform( ref GCInfo.Pointer giPtr ) { ClearPending(); Transform( ref giPtr.Kind ); Transform( ref giPtr.OffsetInWords ); } public override void Transform( ref GCInfo.Pointer[] giPtrArray ) { if(EmitArraySignature( giPtrArray )) { var array = giPtrArray; // Get a local copy, because the original could change, due to the 'ref' argument. for(int i = 0; i < array.Length; i++) { Transform( ref array[i] ); } } } public override void Transform( ref CodePointer cp ) { ClearPending(); Transform( ref cp.Target ); } public override void Transform( ref CodePointer[] cpArray ) { if(EmitArraySignature( cpArray )) { var array = cpArray; // Get a local copy, because the original could change, due to the 'ref' argument. for(int i = 0; i < array.Length; i++) { Transform( ref array[i].Target ); } } } //--// public override void Transform( ref TypeRepresentation.BuiltInTypes val ) { ClearPending(); m_writer.Write( (byte)val ); } public override void Transform( ref TypeRepresentation.Attributes val ) { ClearPending(); m_writer.Write( (int)val ); } public override void Transform( ref TypeRepresentation.BuildTimeAttributes val ) { ClearPending(); m_writer.Write( (int)val ); } public override void Transform( ref TypeRepresentation.GenericContext gc ) { if(EmitSignature( gc )) { gc.ApplyTransformation( this ); } } public override void Transform( ref TypeRepresentation.InterfaceMap map ) { ClearPending(); Transform( ref map.Interface ); Transform( ref map.Methods ); } //--// public override void Transform( ref FieldRepresentation.Attributes val ) { ClearPending(); m_writer.Write( (int)val ); } public override void Transform( ref GenericParameterDefinition.Attributes val ) { ClearPending(); m_writer.Write( (ushort)val ); } public override void Transform( ref MethodRepresentation.Attributes val ) { ClearPending(); m_writer.Write( (ushort)val ); } public override void Transform( ref MethodRepresentation.BuildTimeAttributes val ) { ClearPending(); m_writer.Write( (uint)val ); } public override void Transform( ref MethodRepresentation.GenericContext gc ) { if(EmitSignature( gc )) { gc.ApplyTransformation( this ); } } public override void Transform( ref MultiArrayReferenceTypeRepresentation.Dimension dim ) { ClearPending(); m_writer.Write( dim.m_lowerBound ); m_writer.Write( dim.m_upperBound ); } public override void Transform( ref MultiArrayReferenceTypeRepresentation.Dimension[] dimArray ) { if(EmitArraySignature( dimArray )) { var array = dimArray; // Get a local copy, because the original could change, due to the 'ref' argument. for(int i = 0; i < array.Length; i++) { Transform( ref array[i] ); } } } public override void Transform( ref Runtime.ActivationRecordEvents val ) { ClearPending(); m_writer.Write( (int)val ); } // // PersistenceContextForIR // public override void Transform( ref ControlFlowGraphState cfg ) { if(EmitSignature( cfg )) { ControlFlowGraphStateForCodeTransformation cfg2 = (ControlFlowGraphStateForCodeTransformation)cfg; cfg2.ApplyTransformation( this ); } } //--// public override void Transform( ref Operator op ) { if(EmitSignature( op )) { op.ApplyTransformation( this ); } } public override void Transform( ref Operator[] opArray ) { if(EmitArraySignature( opArray )) { var array = opArray; // Get a local copy, because the original could change, due to the 'ref' argument. for(int i = 0; i < array.Length; i++) { Transform( ref array[i] ); } } } public override void Transform( ref Annotation an ) { if(EmitSignature( an )) { an.ApplyTransformation( this ); } } public override void Transform( ref Annotation[] anArray ) { if(EmitArraySignature( anArray )) { var array = anArray; // Get a local copy, because the original could change, due to the 'ref' argument. for(int i = 0; i < array.Length; i++) { Transform( ref array[i] ); } } } //--// public override void Transform( ref Expression ex ) { if(EmitSignature( ex )) { ex.ApplyTransformation( this ); } } public override void Transform( ref ConstantExpression ex ) { if(EmitSignature( ex )) { ex.ApplyTransformation( this ); } } public override void Transform( ref VariableExpression ex ) { if(EmitSignature( ex )) { ex.ApplyTransformation( this ); } } public override void Transform( ref VariableExpression.DebugInfo val ) { if(EmitSignature( val )) { val.ApplyTransformation( this ); } } //--// public override void Transform( ref Expression[] exArray ) { if(EmitArraySignature( exArray )) { var array = exArray; // Get a local copy, because the original could change, due to the 'ref' argument. for(int i = 0; i < array.Length; i++) { Transform( ref array[i] ); } } } public override void Transform( ref VariableExpression[] exArray ) { if(EmitArraySignature( exArray )) { var array = exArray; // Get a local copy, because the original could change, due to the 'ref' argument. for(int i = 0; i < array.Length; i++) { Transform( ref array[i] ); } } } public override void Transform( ref List< ConstantExpression > exLst ) { int count = EmitListSize( exLst ); var lst = exLst; // Get a local copy, because the original could change, due to the 'ref' argument. for(int i = 0; i < count; i++) { ConstantExpression ex = lst[i]; Transform( ref ex ); } } //--// public override void Transform( ref BasicBlock bb ) { if(EmitSignature( bb )) { bb.ApplyTransformation( this ); } } public override void Transform( ref EntryBasicBlock bb ) { if(EmitSignature( bb )) { bb.ApplyTransformation( this ); } } public override void Transform( ref ExitBasicBlock bb ) { if(EmitSignature( bb )) { bb.ApplyTransformation( this ); } } public override void Transform( ref ExceptionHandlerBasicBlock bb ) { if(EmitSignature( bb )) { bb.ApplyTransformation( this ); } } public override void Transform( ref BasicBlock[] bbArray ) { if(EmitArraySignature( bbArray )) { var array = bbArray; // Get a local copy, because the original could change, due to the 'ref' argument. for(int i = 0; i < array.Length; i++) { Transform( ref array[i] ); } } } public override void Transform( ref ExceptionHandlerBasicBlock[] bbArray ) { if(EmitArraySignature( bbArray )) { var array = bbArray; // Get a local copy, because the original could change, due to the 'ref' argument. for(int i = 0; i < array.Length; i++) { Transform( ref array[i] ); } } } public override void Transform( ref BasicBlock.Qualifier val ) { ClearPending(); m_writer.Write( (int)val ); } //--// public override void Transform( ref ExceptionClause ec ) { if(EmitSignature( ec )) { ec.ApplyTransformation( this ); } } public override void Transform( ref ExceptionClause[] ecArray ) { if(EmitArraySignature( ecArray )) { var array = ecArray; // Get a local copy, because the original could change, due to the 'ref' argument. for(int i = 0; i < array.Length; i++) { Transform( ref array[i] ); } } } public override void Transform( ref ExceptionClause.ExceptionFlag val ) { ClearPending(); m_writer.Write( (int)val ); } //--// public override void Transform( ref CompilationConstraints val ) { ClearPending(); m_writer.Write( (int)val ); } public override void Transform( ref CompilationConstraints[] ccArray ) { if(EmitArraySignature( ccArray )) { var array = ccArray; // Get a local copy, because the original could change, due to the 'ref' argument. for(int i = 0; i < array.Length; i++) { Transform( ref array[i] ); } } } public override void Transform( ref Operator.OperatorCapabilities val ) { ClearPending(); m_writer.Write( (int)val ); } public override void Transform( ref Operator.OperatorLevel val ) { ClearPending(); m_writer.Write( (int)val ); } public override void Transform( ref BinaryOperator.ALU val ) { ClearPending(); m_writer.Write( (int)val ); } public override void Transform( ref UnaryOperator.ALU val ) { ClearPending(); m_writer.Write( (int)val ); } public override void Transform( ref CallOperator.CallKind val ) { ClearPending(); m_writer.Write( (int)val ); } public override void Transform( ref CompareAndSetOperator.ActionCondition val ) { ClearPending(); m_writer.Write( (int)val ); } // // TransformationContextForCodeTransformation // public override void Transform( ref TypeSystemForCodeTransformation typeSystem ) { // // Special handling for the root of the type system: // don't use the actual type for the signature, // just emit the signature for the abstract type. // if(EmitSignature( typeSystem, typeof(TypeSystemForCodeTransformation), typeof(TypeSystemForCodeTransformation) )) { typeSystem.ApplyTransformation( this ); } } //--// public override void Transform( ref StackLocationExpression.Placement val ) { ClearPending(); m_writer.Write( (int)val ); } public override void Transform( ref ConditionCodeExpression.Comparison val ) { ClearPending(); m_writer.Write( (byte)val ); } public override void Transform( ref PiOperator.Relation val ) { ClearPending(); m_writer.Write( (int)val ); } //--// public override void Transform( ref DataManager dataManager ) { if(EmitSignature( dataManager )) { dataManager.ApplyTransformation( this ); } } public override void Transform( ref DataManager.Attributes val ) { ClearPending(); m_writer.Write( (int)val ); } public override void Transform( ref DataManager.ObjectDescriptor od ) { if(EmitSignature( od )) { od.ApplyTransformation( this ); } } public override void Transform( ref DataManager.ArrayDescriptor ad ) { if(EmitSignature( ad )) { ad.ApplyTransformation( this ); } } //--// public override void Transform( ref ImageBuilders.Core imageBuilder ) { if(EmitSignature( imageBuilder )) { imageBuilder.ApplyTransformation( this ); } } public override void Transform( ref ImageBuilders.CompilationState cs ) { if(EmitSignature( cs )) { cs.ApplyTransformation( this ); } } public override void Transform( ref ImageBuilders.SequentialRegion reg ) { if(EmitSignature( reg )) { reg.ApplyTransformation( this ); } } public override void Transform( ref ImageBuilders.ImageAnnotation an ) { if(EmitSignature( an )) { an.ApplyTransformation( this ); } } public override void Transform( ref ImageBuilders.CodeConstant cc ) { if(EmitSignature( cc )) { cc.ApplyTransformation( this ); } } public override void Transform( ref ImageBuilders.SequentialRegion[] regArray ) { if(EmitArraySignature( regArray )) { var array = regArray; // Get a local copy, because the original could change, due to the 'ref' argument. for(int i = 0; i < array.Length; i++) { Transform( ref array[i] ); } } } public override void Transform( ref List< ImageBuilders.SequentialRegion > regLst ) { int count = EmitListSize( regLst ); var lst = regLst; // Get a local copy, because the original could change, due to the 'ref' argument. for(int i = 0; i < count; i++) { ImageBuilders.SequentialRegion reg = lst[i]; Transform( ref reg ); } } public override void Transform( ref List< ImageBuilders.ImageAnnotation > anLst ) { int count = EmitListSize( anLst ); var lst = anLst; // Get a local copy, because the original could change, due to the 'ref' argument. for(int i = 0; i < count; i++) { ImageBuilders.ImageAnnotation an = lst[i]; Transform( ref an ); } } public override void Transform( ref List< ImageBuilders.CodeConstant > ccLst ) { int count = EmitListSize( ccLst ); var lst = ccLst; // Get a local copy, because the original could change, due to the 'ref' argument. for(int i = 0; i < count; i++) { ImageBuilders.CodeConstant cc = lst[i]; Transform( ref cc ); } } public override void Transform( ref List< Runtime.Memory.Range > mrLst ) { int count = EmitListSize( mrLst ); var lst = mrLst; // Get a local copy, because the original could change, due to the 'ref' argument. for(int i = 0; i < count; i++) { Runtime.Memory.Range mr = lst[i]; TransformGeneric( ref mr ); } } public override void Transform( ref Runtime.MemoryAttributes val ) { ClearPending(); m_writer.Write( (uint)val ); } public override void Transform( ref Runtime.MemoryAttributes[] maArray ) { if(EmitArraySignature( maArray )) { var array = maArray; // Get a local copy, because the original could change, due to the 'ref' argument. for(int i = 0; i < array.Length; i++) { Transform( ref array[i] ); } } } public override void Transform( ref Runtime.MemoryUsage val ) { ClearPending(); m_writer.Write( (uint)val ); } public override void Transform( ref Runtime.MemoryUsage[] muArray ) { if(EmitArraySignature( muArray )) { var array = muArray; // Get a local copy, because the original could change, due to the 'ref' argument. for(int i = 0; i < array.Length; i++) { Transform( ref array[i] ); } } } public override void Transform( ref Abstractions.PlacementRequirements pr ) { if(EmitSignature( pr )) { pr.ApplyTransformation( this ); } } public override void Transform( ref Abstractions.RegisterDescriptor regDesc ) { if(EmitSignature( regDesc )) { regDesc.ApplyTransformation( this ); } } public override void Transform( ref Abstractions.RegisterDescriptor[] regDescArray ) { if(EmitArraySignature( regDescArray )) { var array = regDescArray; // Get a local copy, because the original could change, due to the 'ref' argument. for(int i = 0; i < array.Length; i++) { Transform( ref array[i] ); } } } public override void Transform( ref Abstractions.RegisterClass val ) { ClearPending(); m_writer.Write( (uint)val ); } public override void Transform( ref Abstractions.CallingConvention.Direction val ) { ClearPending(); m_writer.Write( (uint)val ); } //--// protected override void TransformArray( ref Array arrayIn ) { if(EmitSignature( arrayIn )) { var array = arrayIn; // Get a local copy, because the original could change, due to the 'ref' argument. for(int i = 0; i < array.Length; i++) { object obj = array.GetValue( i ); Transform( ref obj ); } } } //--// protected override GrowOnlyHashTable< Type, System.Reflection.MethodInfo > GetMethodInfoTable() { if(s_handlers == null) { s_handlers = BuildMethodInfoTable(); } return s_handlers; } protected override DynamicTransform GetDynamicTransform() { if(s_dynamicTransform == null) { s_dynamicTransform = BuildDynamicTransform(); } return s_dynamicTransform; } protected override object TransformThroughReflection( object obj ) { if(EmitSignature( obj, null )) { TransformFields( obj, obj.GetType() ); } return obj; } #if TRANSFORMATIONCONTEXT__USE_EMIT public override bool IsReader { get { return false; } } #endif } //--// // // PersistenceContextForDeserialization // internal class Reader : TransformationContextForCodeTransformation { delegate object DynamicNewObj(); class SparseList { // // State // const int c_ChunkSize = 1024; List< object[] > m_list; object[] m_current; int m_pos; // // Constructor Methods // internal SparseList() { m_list = new List< object[] >(); } // // Helper Methods // internal void Add( object obj ) { if(m_current == null) { m_current = new object[c_ChunkSize]; m_list.Add( m_current ); } m_current[m_pos++] = obj; if(m_pos == c_ChunkSize) { m_current = null; m_pos = 0; } } // // Access Methods // internal int Count { get { int res = m_list.Count * c_ChunkSize; if(m_current != null) { res -= c_ChunkSize; res += m_pos; } return res; } } internal object this[int index] { get { object[] chunk = m_list[ index / c_ChunkSize ]; return chunk[index % c_ChunkSize]; } } } // // State // static GrowOnlyHashTable< Type, System.Reflection.MethodInfo > s_handlers; static DynamicTransform s_dynamicTransform; System.IO.BinaryReader m_reader; object m_pending; // Transform( ref object ) has to go through Visit twice. Keep track of it. SparseList m_indexToObject = new SparseList (); List< Type > m_indexToType = new List< Type >(); CreateInstance m_callback; ProgressCallback m_feedback; int m_feedbackQuantum; int m_feedbackCount; int m_contextStackSize; GrowOnlyHashTable< Type, DynamicNewObj > m_constructors; // // Constructor Methods // internal Reader( System.IO.Stream stream , CreateInstance callback , ProgressCallback feedback , int feedbackQuantum ) { m_reader = new System.IO.BinaryReader( stream, System.Text.Encoding.UTF8 ); m_callback = callback; m_feedback = feedback; m_feedbackQuantum = feedbackQuantum; string version = m_reader.ReadString(); if(version != VersionId) { throw new NotSupportedException( string.Format( "Expecting file version {0}, got {1}", VersionId, version ) ); } } //--// private void NewObject( object obj ) { if(obj is ValueType) { return; } #if DEBUG_PERSISTENCE Console.WriteLine( "NewObject {0} {1}", obj.GetType(), m_indexToObject.Count ); #endif //// if(m_indexToObject.Count == ) //// { //// } m_indexToObject.Add( obj ); } private void NewType( Type type ) { m_indexToType.Add( type ); } //--// private RecordType ReadRecordType() { return (RecordType)m_reader.ReadByte(); } protected override void ClearPending() { m_pending = null; } //--// private bool GetSignature( ref T obj ) where T : class { object res = null; bool fGot = GetSignature( ref res, typeof(T) ); obj = (T)res; return fGot; } private bool GetSignature( ref object obj , Type typeExpected ) { if(m_pending != null) { obj = m_pending; m_pending = null; return true; } if(m_feedback != null) { m_feedbackCount++; if(m_feedbackCount >= m_feedbackQuantum) { m_feedbackCount = 0; m_feedback( m_reader.BaseStream.Position, m_reader.BaseStream.Length ); } } RecordType rt = ReadRecordType(); if(rt == RecordType.Null) { #if DEBUG_PERSISTENCE Console.WriteLine( "RecordType.Null" ); #endif obj = null; return false; } else if(rt == RecordType.Index) { int idx = m_reader.ReadInt32(); #if DEBUG_PERSISTENCE Console.WriteLine( "RecordType.Index {0} {1}", idx, m_reader.BaseStream.Position ); #endif obj = m_indexToObject[ idx ]; return false; } Type t = DecodeTypeDefinition( rt, typeExpected ); if(t.IsArray) { if(t.GetArrayRank() != 1) { throw TypeConsistencyErrorException.Create( "Multi-dimension arrays not supported during type system serialization: {0}", t ); } Type elementType = t.GetElementType(); int len = m_reader.ReadInt32(); Array array = Array.CreateInstance( elementType, len ); NewObject( array ); #if DEBUG_PERSISTENCE Console.WriteLine( "array.Length {0}", len ); #endif obj = array; return array.Length > 0; } if( t == typeof(string)) { obj = m_reader.ReadString (); } else if(t == typeof(bool )) { obj = m_reader.ReadBoolean(); } else if(t == typeof(byte )) { obj = m_reader.ReadByte (); } else if(t == typeof(sbyte )) { obj = m_reader.ReadSByte (); } else if(t == typeof(char )) { obj = m_reader.ReadChar (); } else if(t == typeof(short )) { obj = m_reader.ReadInt16 (); } else if(t == typeof(ushort)) { obj = m_reader.ReadUInt16 (); } else if(t == typeof(int )) { obj = m_reader.ReadInt32 (); } else if(t == typeof(uint )) { obj = m_reader.ReadUInt32 (); } else if(t == typeof(long )) { obj = m_reader.ReadInt64 (); } else if(t == typeof(ulong )) { obj = m_reader.ReadUInt64 (); } else if(t == typeof(float )) { obj = m_reader.ReadSingle (); } else if(t == typeof(double)) { obj = m_reader.ReadDouble (); } else if(t.IsSubclassOf( typeof(Type) )) { obj = DecodeTypeDefinition( ReadRecordType(), null ); } else { obj = m_callback != null ? m_callback( t ) : null; if(obj == null) { if(m_constructors == null) { m_constructors = HashTableFactory.NewWithReferenceEquality< Type, DynamicNewObj >(); } DynamicNewObj dlg; if(m_constructors.TryGetValue( t, out dlg ) == false) { dlg = BuildDynamicNewObj( t ); m_constructors[t] = dlg; } obj = dlg(); } NewObject( obj ); return true; } NewObject( obj ); return false; } #if READER__USE_EMIT delegate object GetUninitializedObjectDelegate( Type type ); delegate Type GetTypeFromHandleDelegate( RuntimeTypeHandle handle ); #endif private DynamicNewObj BuildDynamicNewObj( Type t ) { const BindingFlags flags = BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.Public; Type tObj = t; Type[] tParam = new Type[0]; ConstructorInfo ci = null; while(tObj != null) { ci = tObj.GetConstructor( flags, null, tParam, null ); if(ci != null) { break; } tObj = tObj.BaseType; } #if READER__USE_EMIT DynamicMethod methodBuilder = new DynamicMethod( "", typeof(object), null, true ); ILGenerator il = methodBuilder.GetILGenerator( 256 ); if(t.IsValueType) { LocalBuilder objectRef = il.DeclareLocal( t ); il.Emit( OpCodes.Ldloca , objectRef ); il.Emit( OpCodes.Initobj, t ); il.Emit( OpCodes.Ldloc , objectRef ); il.Emit( OpCodes.Box , t ); } else { if(ci != null) { if(ci.DeclaringType == t) { il.Emit( OpCodes.Newobj, ci ); } else { return delegate() { object obj = System.Runtime.Serialization.FormatterServices.GetUninitializedObject( t ); ci.Invoke( obj, null ); return obj; }; } //// //// GetUninitializedObjectDelegate dlgGetUninitializedObject = System.Runtime.Serialization.FormatterServices.GetUninitializedObject; //// GetTypeFromHandleDelegate dlgGetTypeFromHandle = Type.GetTypeFromHandle; //// //// LocalBuilder objectRef = il.DeclareLocal( t ); //// //// il.Emit( OpCodes.Ldtoken , t ); //// il.Emit( OpCodes.Call , dlgGetTypeFromHandle .Method ); //// il.Emit( OpCodes.Call , dlgGetUninitializedObject.Method ); //// il.Emit( OpCodes.Castclass, t ); //// //// il.Emit( OpCodes.Stloc, objectRef ); //// //// if(ci != null) //// { //// il.Emit( OpCodes.Ldloc , objectRef ); //// il.Emit( OpCodes.Callvirt, ci ); << This causes a verification exception. //// } //// //// il.Emit( OpCodes.Ldloc, objectRef ); } else { GetUninitializedObjectDelegate dlgGetUninitializedObject = System.Runtime.Serialization.FormatterServices.GetUninitializedObject; GetTypeFromHandleDelegate dlgGetTypeFromHandle = Type.GetTypeFromHandle; il.Emit( OpCodes.Ldtoken, t ); il.Emit( OpCodes.Call , dlgGetTypeFromHandle .Method ); il.Emit( OpCodes.Call , dlgGetUninitializedObject.Method ); } } il.Emit( OpCodes.Ret ); return (DynamicNewObj)methodBuilder.CreateDelegate( typeof(DynamicNewObj) ); #else if(ci == null) { return delegate() { return System.Runtime.Serialization.FormatterServices.GetUninitializedObject( t ); }; } else { return delegate() { object obj = System.Runtime.Serialization.FormatterServices.GetUninitializedObject( t ); ci.Invoke( obj, null ); return obj; }; } #endif } //--// private int GetListSize( ref List lst ) { object res = null; bool fContinue = GetSignature( ref res, typeof(List< T >) ); lst = (List< T >)res; if(fContinue) { int count = m_reader.ReadInt32(); #if DEBUG_PERSISTENCE Console.WriteLine( "list.Count {0}", count ); #endif return count; } else { return -1; } } //--// private Type DecodeTypeDefinition( RecordType rt , Type targetType ) { if(rt == RecordType.ClassNoDef) { #if DEBUG_PERSISTENCE Console.WriteLine( "RecordType.ClassNoDef {0}", targetType ); #endif return targetType; } else if(rt == RecordType.TypeUse) { int idx = m_reader.ReadInt32(); #if DEBUG_PERSISTENCE Console.WriteLine( "RecordType.TypeUse {0}", idx ); #endif return m_indexToType[ idx ]; } else if(rt == RecordType.TypeDefinition) { #if DEBUG_PERSISTENCE Console.WriteLine( "RecordType.TypeDefinition {0}", m_indexToType.Count ); #endif Type t; rt = ReadRecordType(); if(rt == RecordType.Array) { #if DEBUG_PERSISTENCE Console.WriteLine( "RecordType.Array" ); #endif Type elementType = DecodeTypeDefinition( ReadRecordType(), null ); t = elementType.MakeArrayType(); } else if(rt == RecordType.Class) { #if DEBUG_PERSISTENCE Console.WriteLine( "RecordType.Class" ); #endif string assemblyQualifiedName = m_reader.ReadString(); t = Type.GetType( assemblyQualifiedName ); if(t.IsGenericType) { int argNum = m_reader.ReadInt32(); Type[] argsType = new Type[argNum]; for(int i = 0; i < argNum; i++) { argsType[i] = DecodeTypeDefinition( ReadRecordType(), null ); } t = t.MakeGenericType( argsType ); #if DEBUG_PERSISTENCE Console.WriteLine( "TypeName '{0}' : {1}", t.AssemblyQualifiedName, argNum ); #endif } else { #if DEBUG_PERSISTENCE Console.WriteLine( "TypeName '{0}'", assemblyQualifiedName ); #endif } } else { throw TypeConsistencyErrorException.Create( "Unrecognized token '{0}' received during type system deserialization", rt ); } NewType( t ); return t; } else { throw TypeConsistencyErrorException.Create( "Unrecognized token '{0}' received during type system deserialization", rt ); } } //--// // // TransformationContext // protected override bool ShouldTransform( object target ) { return true; } public override void MarkAsVisited( object obj ) { } public override void Push( object ctx ) { m_contextStackSize++; } public override void Pop() { CHECKS.ASSERT( m_contextStackSize > 0, "Unbalanced push/pop pair" ); if(--m_contextStackSize == 0) { RunDelayedUpdates(); } } public override object TopContext() { return null; } public override object FindContext( Type ctx ) { return null; } public override object GetTransformInitiator() { return null; } public override TypeSystem GetTypeSystem() { return null; } //--// public override void Transform( ref ITransformationContextTarget itf ) { if(GetSignature( ref itf )) { itf.ApplyTransformation( this ); } } //--// public override void Transform( ref bool val ) { ClearPending(); val = m_reader.ReadBoolean(); } public override void Transform( ref char val ) { ClearPending(); val = m_reader.ReadChar(); } public override void Transform( ref sbyte val ) { ClearPending(); val = m_reader.ReadSByte(); } public override void Transform( ref byte val ) { ClearPending(); val = m_reader.ReadByte(); } public override void Transform( ref short val ) { ClearPending(); val = m_reader.ReadInt16(); } public override void Transform( ref ushort val ) { ClearPending(); val = m_reader.ReadUInt16(); } public override void Transform( ref int val ) { ClearPending(); val = m_reader.ReadInt32(); } public override void Transform( ref uint val ) { ClearPending(); val = m_reader.ReadUInt32(); } public override void Transform( ref long val ) { ClearPending(); val = m_reader.ReadInt64(); } public override void Transform( ref ulong val ) { ClearPending(); val = m_reader.ReadUInt64(); } public override void Transform( ref float val ) { ClearPending(); val = m_reader.ReadSingle(); } public override void Transform( ref double val ) { ClearPending(); val = m_reader.ReadDouble(); } public override void Transform( ref IntPtr val ) { ClearPending(); val = new IntPtr( m_reader.ReadInt32() ); } public override void Transform( ref UIntPtr val ) { ClearPending(); val = new UIntPtr( m_reader.ReadUInt32() ); } public override void Transform( ref string val ) { if(GetSignature( ref val )) { ; // Nothing else to do. } } public override void Transform( ref object val ) { if(GetSignature( ref val, null )) { if(val is ExternalDataDescriptor) { val = new ExternalDataDescriptor(); } else if(val is ArmElfExternalDataContext) { val = new ArmElfExternalDataContext(null, null); } else { m_pending = val; val = TransformGenericReference( val ); } } } public override void Transform( ref Type val ) { if(GetSignature( ref val )) { ; // Nothing else to do. } } //--// public override void Transform( ref bool[] valArray ) { if(GetSignature( ref valArray )) { for(int i = 0; i < valArray.Length; i++) { valArray[i] = m_reader.ReadBoolean(); } } } public override void Transform( ref char[] valArray ) { if(GetSignature( ref valArray )) { for(int i = 0; i < valArray.Length; i++) { valArray[i] = m_reader.ReadChar(); } } } public override void Transform( ref sbyte[] valArray ) { if(GetSignature( ref valArray )) { for(int i = 0; i < valArray.Length; i++) { valArray[i] = m_reader.ReadSByte(); } } } public override void Transform( ref byte[] valArray ) { if(GetSignature( ref valArray )) { m_reader.Read( valArray, 0, valArray.Length ); } } public override void Transform( ref short[] valArray ) { if(GetSignature( ref valArray )) { for(int i = 0; i < valArray.Length; i++) { valArray[i] = m_reader.ReadInt16(); } } } public override void Transform( ref ushort[] valArray ) { if(GetSignature( ref valArray )) { for(int i = 0; i < valArray.Length; i++) { valArray[i] = m_reader.ReadUInt16(); } } } public override void Transform( ref int[] valArray ) { if(GetSignature( ref valArray )) { for(int i = 0; i < valArray.Length; i++) { valArray[i] = m_reader.ReadInt32(); } } } public override void Transform( ref uint[] valArray ) { if(GetSignature( ref valArray )) { for(int i = 0; i < valArray.Length; i++) { valArray[i] = m_reader.ReadUInt32(); } } } public override void Transform( ref long[] valArray ) { if(GetSignature( ref valArray )) { for(int i = 0; i < valArray.Length; i++) { valArray[i] = m_reader.ReadInt64(); } } } public override void Transform( ref ulong[] valArray ) { if(GetSignature( ref valArray )) { for(int i = 0; i < valArray.Length; i++) { valArray[i] = m_reader.ReadUInt64(); } } } public override void Transform( ref float[] valArray ) { if(GetSignature( ref valArray )) { for(int i = 0; i < valArray.Length; i++) { valArray[i] = m_reader.ReadSingle(); } } } public override void Transform( ref double[] valArray ) { if(GetSignature( ref valArray )) { for(int i = 0; i < valArray.Length; i++) { valArray[i] = m_reader.ReadDouble(); } } } public override void Transform( ref IntPtr[] valArray ) { if(GetSignature( ref valArray )) { for(int i = 0; i < valArray.Length; i++) { valArray[i] = new IntPtr( m_reader.ReadInt32() ); } } } public override void Transform( ref UIntPtr[] valArray ) { if(GetSignature( ref valArray )) { for(int i = 0; i < valArray.Length; i++) { valArray[i] = new UIntPtr( m_reader.ReadUInt32() ); } } } public override void Transform( ref string[] valArray ) { if(GetSignature( ref valArray )) { var array = valArray; // Get a local copy, because the original could change, due to the 'ref' argument. for(int i = 0; i < array.Length; i++) { Transform( ref array[i] ); } } } public override void Transform( ref object[] objArray ) { if(GetSignature( ref objArray )) { var array = objArray; // Get a local copy, because the original could change, due to the 'ref' argument. for(int i = 0; i < array.Length; i++) { Transform( ref array[i] ); } } } //--// public override void Transform( ref List< string > strLst ) { int count = GetListSize( ref strLst ); var lst = strLst; // Get a local copy, because the original could change, due to the 'ref' argument. for(int i = 0; i < count; i++) { string str = null; Transform( ref str ); lst.Add( str ); } } //--// public override void Transform( ref Debugging.DebugInfo debugInfo ) { if(GetSignature( ref debugInfo )) { Transform( ref debugInfo.SrcFileName ); Transform( ref debugInfo.MethodName ); Transform( ref debugInfo.BeginLineNumber ); Transform( ref debugInfo.BeginColumn ); Transform( ref debugInfo.EndLineNumber ); Transform( ref debugInfo.EndColumn ); } } //--// public override void Transform( ref WellKnownTypes wkt ) { if(GetSignature( ref wkt )) { wkt.ApplyTransformation( this ); } } public override void Transform( ref WellKnownMethods wkm ) { if(GetSignature( ref wkm )) { wkm.ApplyTransformation( this ); } } public override void Transform( ref WellKnownFields wkf ) { if(GetSignature( ref wkf )) { wkf.ApplyTransformation( this ); } } //--// public override void Transform( ref AssemblyRepresentation asml ) { if(GetSignature( ref asml )) { asml.ApplyTransformation( this ); } } public override void Transform( ref List< AssemblyRepresentation > asmlLst ) { int count = GetListSize( ref asmlLst ); var lst = asmlLst; // Get a local copy, because the original could change, due to the 'ref' argument. for(int i = 0; i < count; i++) { AssemblyRepresentation asml = null; Transform( ref asml ); lst.Add( asml ); } } public override void Transform( ref AssemblyRepresentation.VersionData ver ) { ClearPending(); ver.ApplyTransformation( this ); } public override void Transform( ref AssemblyRepresentation.VersionData.AssemblyFlags val ) { ClearPending(); val = (AssemblyRepresentation.VersionData.AssemblyFlags)m_reader.ReadInt32(); } //--// public override void Transform( ref BaseRepresentation bd ) { if(GetSignature( ref bd )) { bd.ApplyTransformation( this ); } } //--// public override void Transform( ref TypeRepresentation td ) { if(GetSignature( ref td )) { td.ApplyTransformation( this ); } } public override void Transform( ref ValueTypeRepresentation td ) { if(GetSignature( ref td )) { td.ApplyTransformation( this ); } } public override void Transform( ref ArrayReferenceTypeRepresentation td ) { if(GetSignature( ref td )) { td.ApplyTransformation( this ); } } public override void Transform( ref InterfaceTypeRepresentation itf ) { if(GetSignature( ref itf )) { itf.ApplyTransformation( this ); } } public override void Transform( ref TypeRepresentation[] tdArray ) { if(GetSignature( ref tdArray )) { var array = tdArray; // Get a local copy, because the original could change, due to the 'ref' argument. for(int i = 0; i < array.Length; i++) { Transform( ref array[i] ); } } } public override void Transform( ref InterfaceTypeRepresentation[] itfArray ) { if(GetSignature( ref itfArray )) { var array = itfArray; // Get a local copy, because the original could change, due to the 'ref' argument. for(int i = 0; i < array.Length; i++) { Transform( ref array[i] ); } } } public override void Transform( ref List< TypeRepresentation > tdLst ) { int count = GetListSize( ref tdLst ); var lst = tdLst; // Get a local copy, because the original could change, due to the 'ref' argument. for(int i = 0; i < count; i++) { TypeRepresentation td = null; Transform( ref td ); lst.Add( td ); } } public override void Transform( ref FieldRepresentation fd ) { if(GetSignature( ref fd )) { fd.ApplyTransformation( this ); } } public override void Transform( ref InstanceFieldRepresentation fd ) { if(GetSignature( ref fd )) { fd.ApplyTransformation( this ); } } public override void Transform( ref StaticFieldRepresentation fd ) { if(GetSignature( ref fd )) { fd.ApplyTransformation( this ); } } public override void Transform( ref FieldRepresentation[] fdArray ) { if(GetSignature( ref fdArray )) { var array = fdArray; // Get a local copy, because the original could change, due to the 'ref' argument. for(int i = 0; i < array.Length; i++) { Transform( ref array[i] ); } } } public override void Transform( ref InstanceFieldRepresentation[] fdArray ) { if(GetSignature( ref fdArray )) { var array = fdArray; // Get a local copy, because the original could change, due to the 'ref' argument. for(int i = 0; i < array.Length; i++) { Transform( ref array[i] ); } } } public override void Transform( ref MethodRepresentation md ) { if(GetSignature( ref md )) { md.ApplyTransformation( this ); } } public override void Transform( ref MethodRepresentation[] mdArray ) { if(GetSignature( ref mdArray )) { var array = mdArray; // Get a local copy, because the original could change, due to the 'ref' argument. for(int i = 0; i < array.Length; i++) { Transform( ref array[i] ); } } } public override void Transform( ref List resLst ) { int count = GetListSize( ref resLst ); var lst = resLst; // Get a local copy, because the original could change, due to the 'ref' argument. for(int i = 0; i < count; i++) { MethodRepresentation res = null; Transform( ref res ); lst.Add( res ); } } public override void Transform( ref MethodImplRepresentation mi ) { if(GetSignature( ref mi )) { mi.ApplyTransformation( this ); } } public override void Transform( ref MethodImplRepresentation[] miArray ) { if(GetSignature( ref miArray )) { var array = miArray; // Get a local copy, because the original could change, due to the 'ref' argument. for(int i = 0; i < array.Length; i++) { Transform( ref array[i] ); } } } public override void Transform( ref GenericParameterDefinition param ) { ClearPending(); param.ApplyTransformation( this ); } public override void Transform( ref GenericParameterDefinition[] paramArray ) { if(GetSignature( ref paramArray )) { var array = paramArray; // Get a local copy, because the original could change, due to the 'ref' argument. for(int i = 0; i < array.Length; i++) { Transform( ref array[i] ); } } } //--// public override void Transform( ref CustomAttributeRepresentation ca ) { if(GetSignature( ref ca )) { ca.ApplyTransformation( this ); } } public override void Transform( ref CustomAttributeRepresentation[] caArray ) { if(GetSignature( ref caArray )) { var array = caArray; // Get a local copy, because the original could change, due to the 'ref' argument. for(int i = 0; i < array.Length; i++) { Transform( ref array[i] ); } } } //--// public override void Transform( ref CustomAttributeAssociationRepresentation caa ) { if(GetSignature( ref caa )) { caa.ApplyTransformation( this ); } } public override void Transform( ref CustomAttributeAssociationRepresentation[] caaArray ) { if(GetSignature( ref caaArray )) { var array = caaArray; // Get a local copy, because the original could change, due to the 'ref' argument. for(int i = 0; i < array.Length; i++) { Transform( ref array[i] ); } } } //--// public override void Transform( ref ResourceRepresentation res ) { if(GetSignature( ref res )) { res.ApplyTransformation( this ); } } public override void Transform( ref List< ResourceRepresentation > resLst ) { int count = GetListSize( ref resLst ); var lst = resLst; // Get a local copy, because the original could change, due to the 'ref' argument. for(int i = 0; i < count; i++) { ResourceRepresentation res = null; Transform( ref res ); lst.Add( res ); } } public override void Transform( ref ResourceRepresentation.Attributes val ) { ClearPending(); val = (ResourceRepresentation.Attributes)m_reader.ReadInt32(); } public override void Transform( ref ResourceRepresentation.Pair[] pairArray ) { if(GetSignature( ref pairArray )) { var array = pairArray; // Get a local copy, because the original could change, due to the 'ref' argument. for(int i = 0; i < array.Length; i++) { TransformGeneric( ref array[i] ); } } } //--// public override void Transform( ref VTable vTable ) { if(GetSignature( ref vTable )) { vTable.ApplyTransformation( this ); } } public override void Transform( ref VTable.InterfaceMap iMap ) { ClearPending(); Transform( ref iMap.Interface ); Transform( ref iMap.MethodPointers ); } public override void Transform( ref GCInfo gi ) { ClearPending(); Transform( ref gi.Pointers ); } public override void Transform( ref GCInfo.Kind giKind ) { ClearPending(); giKind = (GCInfo.Kind)m_reader.ReadInt16(); } public override void Transform( ref GCInfo.Pointer giPtr ) { ClearPending(); Transform( ref giPtr.Kind ); Transform( ref giPtr.OffsetInWords ); } public override void Transform( ref GCInfo.Pointer[] giPtrArray ) { if(GetSignature( ref giPtrArray )) { var array = giPtrArray; // Get a local copy, because the original could change, due to the 'ref' argument. for(int i = 0; i < array.Length; i++) { Transform( ref array[i] ); } } } public override void Transform( ref CodePointer cp ) { ClearPending(); Transform( ref cp.Target ); } public override void Transform( ref CodePointer[] cpArray ) { if(GetSignature( ref cpArray )) { var array = cpArray; // Get a local copy, because the original could change, due to the 'ref' argument. for(int i = 0; i < array.Length; i++) { Transform( ref array[i].Target ); } } } //--// public override void Transform( ref TypeRepresentation.BuiltInTypes val ) { ClearPending(); val = (TypeRepresentation.BuiltInTypes)m_reader.ReadByte(); } public override void Transform( ref TypeRepresentation.Attributes val ) { ClearPending(); val = (TypeRepresentation.Attributes)m_reader.ReadInt32(); } public override void Transform( ref TypeRepresentation.BuildTimeAttributes val ) { ClearPending(); val = (TypeRepresentation.BuildTimeAttributes)m_reader.ReadInt32(); } public override void Transform( ref TypeRepresentation.GenericContext gc ) { if(GetSignature( ref gc )) { gc.ApplyTransformation( this ); } } public override void Transform( ref TypeRepresentation.InterfaceMap map ) { ClearPending(); Transform( ref map.Interface ); Transform( ref map.Methods ); } //--// public override void Transform( ref FieldRepresentation.Attributes val ) { ClearPending(); val = (FieldRepresentation.Attributes)m_reader.ReadInt32(); } public override void Transform( ref GenericParameterDefinition.Attributes val ) { ClearPending(); val = (GenericParameterDefinition.Attributes)m_reader.ReadUInt16(); } public override void Transform( ref MethodRepresentation.Attributes val ) { ClearPending(); val = (MethodRepresentation.Attributes)m_reader.ReadUInt16(); } public override void Transform( ref MethodRepresentation.BuildTimeAttributes val ) { ClearPending(); val = (MethodRepresentation.BuildTimeAttributes)m_reader.ReadUInt32(); } public override void Transform( ref MethodRepresentation.GenericContext gc ) { if(GetSignature( ref gc )) { gc.ApplyTransformation( this ); } } public override void Transform( ref MultiArrayReferenceTypeRepresentation.Dimension dim ) { ClearPending(); dim.m_lowerBound = m_reader.ReadUInt32(); dim.m_upperBound = m_reader.ReadUInt32(); } public override void Transform( ref MultiArrayReferenceTypeRepresentation.Dimension[] dimArray ) { if(GetSignature( ref dimArray )) { var array = dimArray; // Get a local copy, because the original could change, due to the 'ref' argument. for(int i = 0; i < array.Length; i++) { Transform( ref array[i] ); } } } public override void Transform( ref Runtime.ActivationRecordEvents val ) { ClearPending(); val = (Runtime.ActivationRecordEvents)m_reader.ReadUInt32(); } // // TransformationContextForIR // public override void Transform( ref ControlFlowGraphState cfg ) { if(GetSignature( ref cfg )) { ControlFlowGraphStateForCodeTransformation cfg2 = (ControlFlowGraphStateForCodeTransformation)cfg; cfg2.ApplyTransformation( this ); } } //--// public override void Transform( ref Operator op ) { if(GetSignature( ref op )) { op.ApplyTransformation( this ); } } public override void Transform( ref Operator[] opArray ) { if(GetSignature( ref opArray )) { var array = opArray; // Get a local copy, because the original could change, due to the 'ref' argument. for(int i = 0; i < array.Length; i++) { Transform( ref array[i] ); } } } public override void Transform( ref Annotation an ) { if(GetSignature( ref an )) { an.ApplyTransformation( this ); } } public override void Transform( ref Annotation[] anArray ) { if(GetSignature( ref anArray )) { var array = anArray; // Get a local copy, because the original could change, due to the 'ref' argument. for(int i = 0; i < array.Length; i++) { Transform( ref array[i] ); } } } //--// public override void Transform( ref Expression ex ) { if(GetSignature( ref ex )) { ex.ApplyTransformation( this ); } } public override void Transform( ref ConstantExpression ex ) { if(GetSignature( ref ex )) { ex.ApplyTransformation( this ); } } public override void Transform( ref VariableExpression ex ) { if(GetSignature( ref ex )) { ex.ApplyTransformation( this ); } } public override void Transform( ref VariableExpression.DebugInfo val ) { if(GetSignature( ref val )) { val.ApplyTransformation( this ); } } //--// public override void Transform( ref Expression[] exArray ) { if(GetSignature( ref exArray )) { var array = exArray; // Get a local copy, because the original could change, due to the 'ref' argument. for(int i = 0; i < array.Length; i++) { Transform( ref array[i] ); } } } public override void Transform( ref VariableExpression[] exArray ) { if(GetSignature( ref exArray )) { var array = exArray; // Get a local copy, because the original could change, due to the 'ref' argument. for(int i = 0; i < array.Length; i++) { Transform( ref array[i] ); } } } public override void Transform( ref List< ConstantExpression > exLst ) { int count = GetListSize( ref exLst ); var lst = exLst; // Get a local copy, because the original could change, due to the 'ref' argument. for(int i = 0; i < count; i++) { ConstantExpression ex = null; Transform( ref ex ); lst.Add( ex ); } } //--// public override void Transform( ref BasicBlock bb ) { if(GetSignature( ref bb )) { bb.ApplyTransformation( this ); } } public override void Transform( ref EntryBasicBlock bb ) { if(GetSignature( ref bb )) { bb.ApplyTransformation( this ); } } public override void Transform( ref ExitBasicBlock bb ) { if(GetSignature( ref bb )) { bb.ApplyTransformation( this ); } } public override void Transform( ref ExceptionHandlerBasicBlock bb ) { if(GetSignature( ref bb )) { bb.ApplyTransformation( this ); } } public override void Transform( ref BasicBlock[] bbArray ) { if(GetSignature( ref bbArray )) { var array = bbArray; // Get a local copy, because the original could change, due to the 'ref' argument. for(int i = 0; i < array.Length; i++) { Transform( ref array[i] ); } } } public override void Transform( ref ExceptionHandlerBasicBlock[] bbArray ) { if(GetSignature( ref bbArray )) { var array = bbArray; // Get a local copy, because the original could change, due to the 'ref' argument. for(int i = 0; i < array.Length; i++) { Transform( ref array[i] ); } } } public override void Transform( ref BasicBlock.Qualifier val ) { ClearPending(); val = (BasicBlock.Qualifier)m_reader.ReadInt32(); } //--// public override void Transform( ref ExceptionClause ec ) { if(GetSignature( ref ec )) { ec.ApplyTransformation( this ); } } public override void Transform( ref ExceptionClause[] ecArray ) { if(GetSignature( ref ecArray )) { var array = ecArray; // Get a local copy, because the original could change, due to the 'ref' argument. for(int i = 0; i < array.Length; i++) { Transform( ref array[i] ); } } } public override void Transform( ref ExceptionClause.ExceptionFlag val ) { ClearPending(); val = (ExceptionClause.ExceptionFlag)m_reader.ReadInt32(); } //--// public override void Transform( ref CompilationConstraints val ) { ClearPending(); val = (CompilationConstraints)m_reader.ReadInt32(); } public override void Transform( ref CompilationConstraints[] ccArray ) { if(GetSignature( ref ccArray )) { var array = ccArray; // Get a local copy, because the original could change, due to the 'ref' argument. for(int i = 0; i < array.Length; i++) { Transform( ref array[i] ); } } } public override void Transform( ref Operator.OperatorCapabilities val ) { ClearPending(); val = (Operator.OperatorCapabilities)m_reader.ReadInt32(); } public override void Transform( ref Operator.OperatorLevel val ) { ClearPending(); val = (Operator.OperatorLevel)m_reader.ReadInt32(); } public override void Transform( ref BinaryOperator.ALU val ) { ClearPending(); val = (BinaryOperator.ALU)m_reader.ReadInt32(); } public override void Transform( ref UnaryOperator.ALU val ) { ClearPending(); val = (UnaryOperator.ALU)m_reader.ReadInt32(); } public override void Transform( ref CallOperator.CallKind val ) { ClearPending(); val = (CallOperator.CallKind)m_reader.ReadInt32(); } public override void Transform( ref CompareAndSetOperator.ActionCondition val ) { ClearPending(); val = (CompareAndSetOperator.ActionCondition)m_reader.ReadInt32(); } // // TransformationContextForCodeGeneration // public override void Transform( ref TypeSystemForCodeTransformation typeSystem ) { if(GetSignature( ref typeSystem )) { typeSystem.ApplyTransformation( this ); } } //--// public override void Transform( ref StackLocationExpression.Placement val ) { ClearPending(); val = (StackLocationExpression.Placement)m_reader.ReadInt32(); } public override void Transform( ref ConditionCodeExpression.Comparison val ) { ClearPending(); val = (ConditionCodeExpression.Comparison)m_reader.ReadByte(); } public override void Transform( ref PiOperator.Relation val ) { ClearPending(); val = (PiOperator.Relation)m_reader.ReadInt32(); } //--// public override void Transform( ref DataManager dataManager ) { if(GetSignature( ref dataManager )) { dataManager.ApplyTransformation( this ); } } public override void Transform( ref DataManager.Attributes val ) { ClearPending(); val = (DataManager.Attributes)m_reader.ReadInt32(); } public override void Transform( ref DataManager.ObjectDescriptor od ) { if(GetSignature( ref od )) { od.ApplyTransformation( this ); } } public override void Transform( ref DataManager.ArrayDescriptor ad ) { if(GetSignature( ref ad )) { ad.ApplyTransformation( this ); } } //--// public override void Transform( ref ImageBuilders.Core imageBuilder ) { if(GetSignature( ref imageBuilder )) { imageBuilder.ApplyTransformation( this ); } } public override void Transform( ref ImageBuilders.CompilationState cs ) { if(GetSignature( ref cs )) { cs.ApplyTransformation( this ); } } public override void Transform( ref ImageBuilders.SequentialRegion reg ) { if(GetSignature( ref reg )) { reg.ApplyTransformation( this ); } } public override void Transform( ref ImageBuilders.ImageAnnotation an ) { if(GetSignature( ref an )) { an.ApplyTransformation( this ); } } public override void Transform( ref ImageBuilders.CodeConstant cc ) { if(GetSignature( ref cc )) { cc.ApplyTransformation( this ); } } public override void Transform( ref ImageBuilders.SequentialRegion[] regArray ) { if(GetSignature( ref regArray )) { var array = regArray; // Get a local copy, because the original could change, due to the 'ref' argument. for(int i = 0; i < array.Length; i++) { Transform( ref array[i] ); } } } public override void Transform( ref List< ImageBuilders.SequentialRegion > regLst ) { int count = GetListSize( ref regLst ); var lst = regLst; // Get a local copy, because the original could change, due to the 'ref' argument. for(int i = 0; i < count; i++) { ImageBuilders.SequentialRegion reg = null; Transform( ref reg ); lst.Add( reg ); } } public override void Transform( ref List< ImageBuilders.ImageAnnotation > anLst ) { int count = GetListSize( ref anLst ); var lst = anLst; // Get a local copy, because the original could change, due to the 'ref' argument. for(int i = 0; i < count; i++) { ImageBuilders.ImageAnnotation an = null; Transform( ref an ); lst.Add( an ); } } public override void Transform( ref List< ImageBuilders.CodeConstant > ccLst ) { int count = GetListSize( ref ccLst ); var lst = ccLst; // Get a local copy, because the original could change, due to the 'ref' argument. for(int i = 0; i < count; i++) { ImageBuilders.CodeConstant cc = null; Transform( ref cc ); lst.Add( cc ); } } public override void Transform( ref List< Runtime.Memory.Range > mrLst ) { int count = GetListSize( ref mrLst ); var lst = mrLst; // Get a local copy, because the original could change, due to the 'ref' argument. for(int i = 0; i < count; i++) { Runtime.Memory.Range mr = null; TransformGeneric( ref mr ); lst.Add( mr ); } } public override void Transform( ref Runtime.MemoryAttributes val ) { ClearPending(); val = (Runtime.MemoryAttributes)m_reader.ReadUInt32(); } public override void Transform( ref Runtime.MemoryAttributes[] maArray ) { if(GetSignature( ref maArray )) { var array = maArray; // Get a local copy, because the original could change, due to the 'ref' argument. for(int i = 0; i < array.Length; i++) { Transform( ref array[i] ); } } } public override void Transform( ref Runtime.MemoryUsage val ) { ClearPending(); val = (Runtime.MemoryUsage)m_reader.ReadUInt32(); } public override void Transform( ref Runtime.MemoryUsage[] muArray ) { if(GetSignature( ref muArray )) { var array = muArray; // Get a local copy, because the original could change, due to the 'ref' argument. for(int i = 0; i < array.Length; i++) { Transform( ref array[i] ); } } } public override void Transform( ref Abstractions.PlacementRequirements pr ) { if(GetSignature( ref pr )) { pr.ApplyTransformation( this ); } } public override void Transform( ref Abstractions.RegisterDescriptor regDesc ) { if(GetSignature( ref regDesc )) { regDesc.ApplyTransformation( this ); } } public override void Transform( ref Abstractions.RegisterDescriptor[] regDescArray ) { if(GetSignature( ref regDescArray )) { var array = regDescArray; // Get a local copy, because the original could change, due to the 'ref' argument. for(int i = 0; i < array.Length; i++) { Transform( ref array[i] ); } } } public override void Transform( ref Abstractions.RegisterClass val ) { ClearPending(); val = (Abstractions.RegisterClass)m_reader.ReadUInt32(); } public override void Transform( ref Abstractions.CallingConvention.Direction val ) { ClearPending(); val = (Abstractions.CallingConvention.Direction)m_reader.ReadUInt32(); } //--// protected override void TransformArray( ref Array arrayIn ) { if(GetSignature( ref arrayIn )) { var array = arrayIn; // Get a local copy, because the original could change, due to the 'ref' argument. for(int i = 0; i < array.Length; i++) { object obj = null; Transform( ref obj ); array.SetValue( obj, i ); } } } //--// protected override GrowOnlyHashTable< Type, System.Reflection.MethodInfo > GetMethodInfoTable() { if(s_handlers == null) { s_handlers = BuildMethodInfoTable(); } return s_handlers; } protected override DynamicTransform GetDynamicTransform() { if(s_dynamicTransform == null) { s_dynamicTransform = BuildDynamicTransform(); } return s_dynamicTransform; } protected override object TransformThroughReflection( object obj ) { if(GetSignature( ref obj, null )) { TransformFields( obj, obj.GetType() ); } return obj; } #if TRANSFORMATIONCONTEXT__USE_EMIT public override bool IsReader { get { return true; } } #endif } } } ================================================ FILE: Zelig/Zelig/CompileTime/CodeGenerator/FrontEnd/Bench.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // //#define DEBUG_SAVE_STATE //#define DEBUG_RELOAD_STATE namespace Microsoft.Zelig.FrontEnd { using System; using System.Collections.Generic; using System.Diagnostics; using System.IO; using System.Linq; using System.Text; using Win32; using Importer = Microsoft.Zelig.MetaData.Importer; using Normalized = Microsoft.Zelig.MetaData.Normalized; using IR = Microsoft.Zelig.CodeGeneration.IR; using TS = Microsoft.Zelig.Runtime.TypeSystem; using Cfg = Microsoft.Zelig.Configuration.Environment; using ARM = Microsoft.Zelig.Emulation.ArmProcessor; using ELF = Microsoft.Zelig.Elf; using LLVM; using CodeGeneration.IR.CompilationSteps; class Bench : TS.IEnvironmentProvider, TS.IConfigurationProvider, MetaData.IMetaDataResolverHelper, MetaData.ISymbolResolverHelper, IR.Transformations.ConstraintSystemCollector.IVisualizer { const string c_ZeligSourceCode = "/ZeligSourceCode"; public class RawImage { public string SectionName; public uint RangeStart; public uint RangeEnd; } public class TypeSystemForFrontEnd : IR.TypeSystemForCodeTransformation { readonly Bench m_owner; public TypeSystemForFrontEnd( Bench owner, TS.IEnvironmentProvider env ) : base( env ) { m_owner = owner; } //--// protected override void NotifyCompilationPhase( IR.CompilationSteps.PhaseDriver phase ) { m_owner.NotifyCompilationPhase( phase ); } public override IR.SourceCodeTracker GetSourceCodeTracker( ) { return m_owner.m_sourceCodeTracker; } } internal class LlvmCodeGenOptions : IR.CompilationSteps.IInlineOptions , ITargetSectionOptions { internal LlvmCodeGenOptions( ) { EnableAutoInlining = true; HonorInlineAttribute = true; InjectPrologAndEpilog = true; } public bool EnableAutoInlining { get; internal set; } public bool HonorInlineAttribute { get; internal set; } public bool InjectPrologAndEpilog { get; internal set; } public bool GenerateDataSectionPerType { get; internal set; } } // // State // const string SymbolSuffix = ".pdb"; const string SourceCodeDatabaseSuffix = ".srcdb"; // Environment variables that may refer to the LLVM tools location static readonly string[] LlvmBinPathEnvVarNames = { "LLILUM_LLVM", "LLVM_BIN" }; // Supported architectures const string c_CortexM0 = "cortex-m0"; const string c_CortexM3 = "cortex-m3"; const string c_CortexM4 = "cortex-m4"; const string c_CortexM7 = "cortex-m7"; const string c_x86_64 = "x86-64"; // These are the default arguments to LLC.EXE if not specified in the command line arguments const string DefaultLlcArgs_common = "-O2 -code-model=small -data-sections -filetype=obj"; const string DefaultLlcArgs_target_m0 = "-march=thumb -mcpu=cortex-m0 -mtriple=thumbv6m-none-eabi"; const string DefaultLlcArgs_target_m3 = "-march=thumb -mcpu=cortex-m3 -mtriple=thumbv7m-none-eabi"; //const string DefaultLlcArgs_target_m4 = "-march=thumb -mcpu=cortex-m4 -mtriple=thumbv7m-none-eabi"; https://github.com/NETMF/llilum/issues/136 const string DefaultLlcArgs_target_m4 = "-march=thumb -mcpu=cortex-m3 -mtriple=thumbv7m-none-eabi"; const string DefaultLlcArgs_target_m7 = "-march=thumb -mcpu=cortex-m7 -mtriple=thumbv7m-none-eabi"; const string DefaultLlcArgs_target_x86 = "-march=x86 -mcpu=x86-64 -mtriple=x86_64-pc-windows-msvc -function-sections -dwarf-version=3"; const string DefaultLlcArgs_target_df = DefaultLlcArgs_target_m3; const string DefaultLlcArgs_reloc = "-relocation-model=pic"; //--// const string DefaultOptExeArgs_common = "-verify-debug-info -verify-dom-info -verify-each -verify-loop-info -verify-regalloc -verify-region-info -aa-eval -indvars -gvn -globaldce -adce -dce -tailcallopt -scalarrepl -mem2reg -ipconstprop -deadargelim -sccp -dce -ipsccp -dce -constmerge -scev-aa -targetlibinfo -irce -dse -dce -argpromotion -mem2reg -adce -mem2reg -globaldce -die -dce -dse"; const string DefaultOptArgs_target_m0 = "-march=thumb -mcpu=cortex-m0"; const string DefaultOptArgs_target_m3 = "-march=thumb -mcpu=cortex-m3"; //const string DefaultOptArgs_target_m4 = "-march=thumb -mcpu=cortex-m4"; https://github.com/NETMF/llilum/issues/136 const string DefaultOptArgs_target_m4 = "-march=thumb -mcpu=cortex-m3"; const string DefaultOptArgs_target_m7 = "-march=thumb -mcpu=cortex-m7"; const string DefaultOptArgs_target_x86 = "-march=x86 -mcpu=x86-64"; const string DefaultOptArgs_target_df = DefaultOptArgs_target_m3; const string LlvmRegSoftwareBinPath = @"SOFTWARE\LLVM\3.8.0"; //--// // // Bench is a root object in the system. This makes it easier to put any object in the watch window from the global hierarchy. // private static Bench s_pThis; private string m_outputName; private string m_outputDir; private string m_targetFile; private string m_entryPointName; private bool m_fReloadState; private bool m_fDumpIL; private bool m_fDumpIRpre; private bool m_fDumpIRpost; private bool m_fDumpIR; private bool m_fDumpFlattenedCallGraph; private bool m_fDumpIRXMLpre; private bool m_fDumpIRXMLpost; private bool m_fDumpIRXML; private bool m_fDumpIRBeforeEachPhase; private bool m_fDumpCFG; private bool m_fDumpLLVMIR; private bool m_fSkipLlvmOptExe; private bool m_fGenerateObj; private bool m_fDumpLLVMIR_TextRepresentation; private bool m_fDumpASM; private bool m_fDumpASMDIR; private bool m_fDumpHEX; private bool m_fSkipReadOnly; private uint m_nativeIntSize; private List< RawImage > m_dumpRawImage; private int m_phaseExecutionCounter; private string m_libraryLocation_HostBuild; private string m_libraryLocation_TargetBuild; private string m_compilationSetupBinaryPath; private string m_LlvmBinPath; private string m_LlvmOptArgs; private string m_LlvmLlcArgs; private HashSet< string > m_phasesForDiagnosticDumps; private List< string > m_references; private List< string > m_searchOrder; private List< string > m_importDirectories; private List< string > m_importLibraries; private LlvmCodeGenOptions m_LlvmCodeGenOptions; private IR.CompilationSteps.DelegationCache m_delegationCache; private MetaData.MetaDataResolver m_resolver; private TypeSystemForFrontEnd m_typeSystem; private IR.CompilationSteps.Controller m_controller; private Cfg.CompilationSetupCategory m_compilationSetup; private GrowOnlyHashTable< string, object > m_configurationOptions; private List m_disabledPhases; private Cfg.ProductCategory m_product; private Cfg.MemoryMapCategory m_memoryMap; private IR.SourceCodeTracker m_sourceCodeTracker; // // This parameter overrides any infereces from compilation setup // (e.g.: -CompilationSetup Microsoft.Llilum.BoardConfigurations.LPC1768MBEDCompilationSetup) // There is no reason for the compilation setup not to express all needed switches // private string m_architecture; //--// private Cfg.Manager m_configurationManager; private PerformanceCounters.Timing m_timing; private long m_lastTiming; // // Constructor Methods // private Bench( ) { m_timing.Start( ); #if DEBUG #if DEBUG_INSTRUMENTATION Environment.SetEnvironmentVariable( "Flavor", "Instrumentation" ); #else Environment.SetEnvironmentVariable( "Flavor", "Debug" ); #endif #else Environment.SetEnvironmentVariable( "Flavor", "Release" ); #endif //--// m_outputDir = "."; m_nativeIntSize = 32; m_phaseExecutionCounter = 0; m_dumpRawImage = new List( ); m_phasesForDiagnosticDumps = new HashSet( ); m_references = new List( ); m_searchOrder = new List( ); m_importDirectories = new List( ); m_importLibraries = new List( ); m_resolver = new Zelig.MetaData.MetaDataResolver( this ); m_configurationOptions = HashTableFactory.New( ); m_disabledPhases = new List( ); m_sourceCodeTracker = new IR.SourceCodeTracker( ); m_LlvmCodeGenOptions = new LlvmCodeGenOptions( ); } //--// private string GetTime( ) { long newTiming = m_timing.Sample( ); long diffTiming = newTiming - m_lastTiming; m_lastTiming = newTiming; return string.Format( "{0,10:F3} [{1,8:F3}]", ( float )PerformanceCounters.Timing.ToMicroSeconds( newTiming ) / ( 1000 * 1000 ), ( float )PerformanceCounters.Timing.ToMicroSeconds( diffTiming ) / ( 1000 * 1000 ) ); } //--// private string AddSearchDirectory( string dir ) { if( m_searchOrder.Contains( dir ) == false ) { m_searchOrder.Add( dir ); } return dir; } void NotifyCompilationPhase( IR.CompilationSteps.PhaseDriver phase ) { m_phaseExecutionCounter++; int types = 0; int fields = 0; int methods = 0; m_typeSystem.GetTypeSystemStatistics( ref types, ref fields, ref methods ); ConsoleColor color = Console.ForegroundColor; Console.Write( "{0}: Phase: {1,-50} ", GetTime( ), phase ); Console.ForegroundColor = ConsoleColor.Green; Console.WriteLine( "[types: {0,5}, fields: {1,6}, methods: {2,6}]", types, fields, methods ); Console.ForegroundColor = color; #if DEBUG_SAVE_STATE if(phase == Microsoft.Zelig.CodeGeneration.IR.CompilationSteps.Phase.GenerateImage) { SaveIrToDisk( "temp.ZeligImage", m_typeSystem ); } #endif if(m_fDumpIRBeforeEachPhase) { var currentPhase = phase.ToString( ); if(m_phasesForDiagnosticDumps.Contains( "All" ) || m_phasesForDiagnosticDumps.Contains( currentPhase )) { string path = Path.Combine( m_outputDir, "phases" ); if(Directory.Exists( path ) == false) { Directory.CreateDirectory( path ); } string filePrefix = Path.Combine( path, m_phaseExecutionCounter.ToString() + "_" + m_outputName ); DumpIRAsText( filePrefix + "." + currentPhase + ".ZeligIR" ); DumpIRAsXML ( filePrefix + "." + currentPhase + ".ZeligIR.xml" ); } } } //--// private static string RemoveFileExtension( string file ) { return System.IO.Path.GetDirectoryName( file ) + @"\" + System.IO.Path.GetFileNameWithoutExtension( file ); } private static string Expand( string file ) { return Environment.ExpandEnvironmentVariables( file ); } private Importer.MetaData LoadAssembly( string file ) { byte[] image = System.IO.File.ReadAllBytes( file ); Importer.PELoader pe = new Importer.PELoader( file, image ); Importer.MetaData md = Importer.MetaData.loadMetaData( file, this, pe, Importer.MetaDataLoaderFlags.LoadCode | Importer.MetaDataLoaderFlags.LoadDebugInfo ); return md; } //--// object TS.IEnvironmentProvider.GetService( Type t ) { if( t == typeof( Normalized.IMetaDataBootstrap ) ) { return m_resolver; } if( t == typeof( TS.IConfigurationProvider ) ) { return this; } if( t == typeof( IR.CompilationSteps.DelegationCache ) ) { return m_delegationCache; } if( t == typeof( IR.CompilationSteps.IInlineOptions ) ) { return m_LlvmCodeGenOptions; } if( t == typeof( ITargetSectionOptions ) ) { return m_LlvmCodeGenOptions; } return null; } //--// bool TS.IConfigurationProvider.GetValue( string optionName, out object val ) { return m_configurationOptions.TryGetValue( optionName, out val ); } //--// void IR.Transformations.ConstraintSystemCollector.IVisualizer.DisplayGraph( IR.Transformations.ConstraintSystemCollector.GraphState gs ) { Microsoft.Zelig.Tools.InequalityGraphVisualization.Viewer.Show( gs ); } //--// Importer.PdbInfo.PdbFile MetaData.ISymbolResolverHelper.ResolveAssemblySymbols( string file ) { try { string root = RemoveFileExtension( file ); string symbolFile = root + SymbolSuffix; string sourceFile = root + SourceCodeDatabaseSuffix; FileInfo symbolInfo = new FileInfo( symbolFile ); if( symbolInfo.Exists ) { byte[] image = System.IO.File.ReadAllBytes( symbolFile ); Importer.PdbInfo.PdbFile pdbFile = new Importer.PdbInfo.PdbFile( new Importer.ArrayReader( image ) ); Importer.PdbInfo.DataStream streamSrc = pdbFile.GetStream( c_ZeligSourceCode ); if( streamSrc != null ) { try { IR.SourceCodeTracker sct = new IR.SourceCodeTracker( ); using( var stream = new MemoryStream( streamSrc.Payload ) ) { using( var ctx = IR.TypeSystemSerializer.GetDeserializationContext( stream, null, null, 0 ) ) { ctx.TransformGeneric( ref sct ); } } m_sourceCodeTracker.Merge( sct ); } catch { } } return pdbFile; } } catch { } return null; } Importer.MetaData MetaData.IMetaDataResolverHelper.ResolveAssemblyReference( string name, MetaData.MetaDataVersion ver ) { // // Force use of our version of mscorlib. // if( name == "mscorlib" ) { return CheckAndLoad( m_libraryLocation_TargetBuild, name ); } Importer.MetaData md; foreach( string dir in m_searchOrder ) { md = CheckAndLoad( dir, name, ver ); if( md != null ) { return md; } } return null; } //--// private Importer.MetaData CheckAndLoad( string dir, string name ) { string file = Path.Combine( dir, name + ".dll" ); if( System.IO.File.Exists( file ) ) { try { return LoadAssembly( file ); } catch { } } return null; } private Importer.MetaData CheckAndLoad( string dir, string name, MetaData.MetaDataVersion ver ) { Importer.MetaData md = CheckAndLoad( dir, name ); if( md != null ) { if( md.Assembly.Name == name ) { if( ver == null || md.Assembly.Version.IsCompatible( ver, false ) ) { return md; } } } return null; } //--// private void EmbedSourceCodeAll( string sDirectory ) { DirectoryInfo dir = new DirectoryInfo( sDirectory ); if( dir.Exists == false ) { Console.WriteLine( "Cannot find directory '{0}'", sDirectory ); } else { foreach( FileInfo file in dir.GetFiles( ) ) { if( string.Compare( file.Extension, SymbolSuffix, true ) == 0 ) { try { EmbedSourceCode( file.FullName ); } catch { } } } } } private void EmbedSourceCode( string file ) { try { var fi = new System.IO.FileInfo( file ); if( fi.Exists == false ) { Console.WriteLine( "Cannot find file '{0}'", file ); } else if( m_fSkipReadOnly && fi.IsReadOnly ) { Console.WriteLine( "Skipping read-only file '{0}'", file ); } else { IR.SourceCodeTracker sct = new IR.SourceCodeTracker( ); byte[] image = System.IO.File.ReadAllBytes( file ); Importer.PdbInfo.PdbFile pdbFile = new Importer.PdbInfo.PdbFile( new Importer.ArrayReader( image ) ); foreach( var pdbFunc in pdbFile.Functions ) { foreach( var pdbLine in pdbFunc.LineBlocks ) { IR.SourceCodeTracker.SourceCode sc = sct.GetSourceCode( pdbLine.File.Name ); if( sc != null ) { sc.UsingCachedValues = true; } } } { MemoryStream output = new MemoryStream( ); using( IR.TransformationContextForCodeTransformation ctx = IR.TypeSystemSerializer.GetSerializationContext( output ) ) { ctx.TransformGeneric( ref sct ); } Importer.PdbInfo.DataStream stream = pdbFile.CreateNewStream( c_ZeligSourceCode ); stream.Payload = output.ToArray( ); } System.IO.File.WriteAllBytes( file, pdbFile.Emit( ) ); Console.WriteLine( "Embedded source code in '{0}'", file ); } } catch( Importer.PdbInfo.PdbException ) { Console.WriteLine( "Skipping '{0}', unrecognized PDB format", file ); } } //--//--// private void SaveIrToDisk( string file, IR.TypeSystemForCodeTransformation typeSystem ) { using( System.IO.FileStream stream = new System.IO.FileStream( file, FileMode.Create, FileAccess.Write, FileShare.None, 1024 * 1024 ) ) { IR.TypeSystemSerializer.Serialize( stream, typeSystem ); } } private IR.TypeSystemForCodeTransformation LoadIrFromDisk( string file, IR.TypeSystemSerializer.CreateInstance callback ) { using( System.IO.FileStream stream = new System.IO.FileStream( file, FileMode.Open ) ) { return IR.TypeSystemSerializer.Deserialize( stream, callback, null, 0 ); } } private object CreateInstanceForType( Type t ) { if( t == typeof( IR.TypeSystemForCodeTransformation ) ) { return new TypeSystemForFrontEnd( this, this ); } return null; } //--// private void DumpIRAsText( string file ) { using( var ird = new IR.TextIntermediateRepresentationDumper( file ) ) { var types = m_typeSystem.Types.ToArray( ); Array.Sort( types, ( x, y ) => x.ToString( ).CompareTo( y.ToString( ) ) ); foreach( var td in types ) { ird.WriteLine( "###############################################################################" ); ird.WriteLine( ); ird.WriteLine( "Type: {0} [Size={1}]", td, td.ValidLayout ? td.Size : uint.MaxValue ); if( td.Extends != null ) { ird.WriteLine( " Extends: {0}", td.Extends ); } foreach( var itf in td.Interfaces ) { ird.WriteLine( " Interface: {0}", itf ); } foreach( var fd in td.Fields ) { ird.WriteLine( " Field: {0} [Offset={1}]", fd, fd.ValidLayout ? fd.Offset : -1 ); } ird.WriteLine( ); var methods = ArrayUtility.CopyNotNullArray( td.Methods ); Array.Sort( methods, ( x, y ) => x.ToShortString( ).CompareTo( y.ToShortString( ) ) ); foreach( var md in methods ) { IR.ControlFlowGraphState cfg = IR.TypeSystemForCodeTransformation.GetCodeForMethod( md ); if( cfg != null ) { ird.WriteLine( " Method {0}", md ); ird.WriteLine( ); cfg.Dump( ird ); } else { ird.WriteLine( " NoCodeMethod {0}", md ); } ird.WriteLine( ); } } } } private void DumpCallGraph( string file, bool fCallsTo ) { using( var sr = new StreamWriter( file ) ) { sr.WriteLine( "Call Graph for all surviving methods" ); sr.WriteLine( "=========================================================" ); sr.WriteLine( $"Listing all calls {{0}} a method", fCallsTo ? "to" : "from" ); sr.WriteLine( "=========================================================" ); sr.WriteLine( ); sr.WriteLine( ); var callsDb = fCallsTo ? m_typeSystem.FlattenedCallsDataBase_CallsTo : m_typeSystem.FlattenedCallsDataBase_CallsFrom; foreach(var method in callsDb.Keys) { sr.WriteLine( $"Method: {method.ToShortString()}" ); sr.WriteLine( ); var calls = callsDb[ method ]; if(calls != null && calls.Count > 0) { calls.Sort( (x, y) => { return x.Target.FullyQualifiedName.CompareTo( y.Target.FullyQualifiedName ); } ); foreach(var call in calls) { sr.WriteLine( $" {{0}} {call.ToString( )}", fCallsTo ? "<==" : "==>" ); } } else { sr.WriteLine( " <== no callers ==>" ); } sr.WriteLine( "=========================================================" ); sr.WriteLine( ); } } } private void DumpIRAsXML(string file) { // Collect all methods into a list var allMethods = new List(); m_typeSystem.EnumerateMethods(method => allMethods.Add(method)); // Initialize the XML IRDumper var doc = new System.Xml.XmlDocument(); var node = XmlHelper.AddElement(doc, "Methods"); var irDumper = new IR.XmlIntermediateRepresentationDumper(doc, node); // Dump each method alphabetically foreach (var method in irDumper.Sort(allMethods)) { IR.TypeSystemForCodeTransformation.GetCodeForMethod(method)?.Dump(irDumper); } doc.Save(file); } //--// private void InitializeConfigurationManager( ) { if( m_configurationManager == null ) { m_configurationManager = new Cfg.Manager( ); m_configurationManager.AddAllAssemblies( m_compilationSetupBinaryPath ); m_configurationManager.ComputeAllPossibleValuesForFields( ); } } private void SearchConfigurationOptions( Cfg.AbstractCategory category ) { foreach( var valueCtx in category.SearchValuesWithAttributes( typeof( Cfg.LinkToConfigurationOptionAttribute ) ) ) { var attrib = valueCtx.GetAttribute( ); m_configurationOptions[ attrib.Name ] = valueCtx.Value; } } private IEnumerable GetConfigurationOptions( ) where T : Cfg.AbstractCategory { InitializeConfigurationManager( ); foreach( Cfg.AbstractCategory value in m_configurationManager.AllValues ) { if( value is T ) { value.ApplyDefaultValues( ); yield return ( T )value; } } } private T GetConfigurationOption( Type target ) where T : Cfg.AbstractCategory { foreach( var option in GetConfigurationOptions( ) ) { if( option.GetType( ) == target ) { return option; } } return null; } private static string[] RecombineArgs( string[] args ) { List arguments = new List(args.Length); for(int i = 0; i < args.Length; ++i) { // An argument like "C:\my directory\with\a\space" will be split as // "C:\my" and "irectory\with\a\space" acrosss two entries in args. // We need to re-combine those entries. // It is important to note that this is a fairly simplistic approach // to quoted string args. In particular there is no support for any // sort of escaped quotes for quoted strings within an argument etc... // We must find a matching pair of double quotes. // if they are on the same arg, then move on. if( args[ i ].StartsWith( "\"" ) && !args[ i ].EndsWith("\"") ) { //start building the complete string var quotedString = new StringBuilder( ); for( ; i < args.Length; ++i ) { if( quotedString.Length > 0 ) quotedString.Append( ' ' ); quotedString.Append( args[ i ] ); if( args[ i ].EndsWith( "\"" ) ) { arguments.Add( quotedString.ToString( ) ); break; } } // if we are at the last entry in args already, then // we have an unmatched quote we may be able to recover from // so ignore it and hope for the best if( i >= args.Length ) { arguments.Add( quotedString.ToString( ) ); } } else arguments.Add( args[i] ); } return arguments.ToArray( ); } private bool Parse( string[] args, ref bool fNoSDK) { if( args == null ) return false; for( int i = 0; i < args.Length; i++ ) { string arg = args[ i ]; if( arg == string.Empty ) { continue; } if( arg.StartsWith( "/" ) || arg.StartsWith( "-" ) ) { string option = arg.Substring( 1 ); if( IsMatch( option, "Cfg" ) ) { string file; if( !GetArgument( arg, args, ref i, out file, true ) ) { return false; } using( System.IO.StreamReader stream = new System.IO.StreamReader( file ) ) { string line; while( ( line = stream.ReadLine( ) ) != null ) { if( line.StartsWith( "#" ) ) { continue; } var arguments = line.Split( new char[ ] { ' ', '\t' }, StringSplitOptions.RemoveEmptyEntries ); string[ ] recombinedArgs = RecombineArgs( arguments ); if( recombinedArgs == null ) { Console.WriteLine( String.Format( "Arguments at line '{0}' could not be recombined", line ) ); return false; } if( Parse( recombinedArgs, ref fNoSDK ) == false ) { return false; } } } } else if( IsMatch( option, "NoSDK" ) ) { fNoSDK = true; } else if( IsMatch( option, "DumpIL" ) ) { m_fDumpIL = true; } else if( IsMatch( option, "ReloadState" ) ) { m_fReloadState = true; } else if( IsMatch( option, "DumpIRpre" ) ) { m_fDumpIRpre = true; } else if( IsMatch( option, "DumpIRpost" ) ) { m_fDumpIRpost = true; } else if( IsMatch( option, "DumpIR" ) ) { m_fDumpIR = true; } else if( IsMatch( option, "DumpFlattenedCallGraph" ) ) { m_fDumpFlattenedCallGraph = true; } else if( IsMatch( option, "DumpIRXMLpre" ) ) { m_fDumpIRXMLpre = true; } else if( IsMatch( option, "DumpIRXMLpost" ) ) { m_fDumpIRXMLpost = true; } else if( IsMatch( option, "DumpIRBeforePhase" ) ) { m_fDumpIRBeforeEachPhase = true; string phase; bool fFoundOne = false; while( GetArgument( arg, args, ref i, out phase, false, false ) ) { m_phasesForDiagnosticDumps.Add( phase ); fFoundOne = true; } if( fFoundOne == false ) { return false; } } else if( IsMatch( option, "DumpIRXML" ) ) { m_fDumpIRXML = true; } else if( IsMatch( option, "DumpLLVMIR" ) ) { m_fDumpLLVMIR = true; } else if( IsMatch( option, "SkipLlvmOpt" ) ) { m_fSkipLlvmOptExe = true; } else if( IsMatch( option, "GenerateObj" ) ) { m_fDumpLLVMIR = true; m_fGenerateObj = true; } else if( IsMatch( option, "DumpLLVMIR_TextRepresentation" ) ) { m_fDumpLLVMIR_TextRepresentation = true; } else if( IsMatch( option, "DumpCFG" ) ) { m_fDumpCFG = true; } else if( IsMatch( option, "DumpASM" ) ) { m_fDumpASM = true; } else if( IsMatch( option, "DumpASMDIR" ) ) { m_fDumpASMDIR = true; } else if( IsMatch( option, "DumpHEX" ) ) { m_fDumpHEX = true; } else if( IsMatch( option, "DumpRAW" ) ) { string section; uint rangeStart; uint rangeEnd; if( !GetArgument( arg, args, ref i, out section, false ) || !GetArgument( arg, args, ref i, out rangeStart, true ) || !GetArgument( arg, args, ref i, out rangeEnd, true ) ) { return false; } m_dumpRawImage.Add( new RawImage { SectionName = section, RangeStart = rangeStart, RangeEnd = rangeEnd } ); } else if( IsMatch( option, "HostAssemblyDir" ) ) { string dir; if( !GetArgument( arg, args, ref i, out dir, true ) ) { return false; } m_libraryLocation_HostBuild = AddSearchDirectory( dir ); } else if( IsMatch( option, "DeviceAssemblyDir" ) ) { string dir; if( !GetArgument( arg, args, ref i, out dir, true ) ) { return false; } m_libraryLocation_TargetBuild = AddSearchDirectory( dir ); } else if( IsMatch( option, "ImportDirectory" ) ) { string dir; if( !GetArgument( arg, args, ref i, out dir, true ) ) { return false; } dir = dir.ToLower( ); if( !m_importDirectories.Contains( dir ) ) { m_importDirectories.Add( dir ); } } else if( IsMatch( option, "ImportLibrary" ) ) { string file; if( !GetArgument( arg, args, ref i, out file, true ) ) { return false; } file = file.ToLower( ); if( !m_importLibraries.Contains( file ) ) { m_importLibraries.Add( file ); } } else if( IsMatch( option, "MaxProcs" ) ) { uint iMaxProcs; if( !GetArgument( arg, args, ref i, out iMaxProcs, false ) ) { return false; } IR.CompilationSteps.ParallelTransformationsHandler.MaximumNumberOfProcessorsToUse = ( int )iMaxProcs; } else if( IsMatch( option, "OutputName" ) ) { string name; if( !GetArgument( arg, args, ref i, out name, false ) ) { return false; } m_outputName = name; } else if( IsMatch( option, "NativeIntSize" ) ) { string name; if( !GetArgument( arg, args, ref i, out name, false ) ) { return false; } if( !UInt32.TryParse( name, out m_nativeIntSize ) ) return false; } else if( IsMatch( option, "OutputDir" ) ) { string dir; if( !GetArgument( arg, args, ref i, out dir, true ) ) { return false; } m_outputDir = dir; } else if( IsMatch( option, "Reference" ) ) { string reference; if( !GetArgument( arg, args, ref i, out reference, false ) ) { return false; } m_references.Add( reference ); } else if( IsMatch( option, "CompilationSetupPath" ) ) { string compilationBinary; if( !GetArgument( arg, args, ref i, out compilationBinary, true ) ) { return false; } m_compilationSetupBinaryPath = compilationBinary; } else if( IsMatch( option, "LlvmBinPath" ) ) { string toolsPath; if( !GetArgument( arg, args, ref i, out toolsPath, true ) ) { return false; } m_LlvmBinPath = toolsPath; } else if( IsMatch( option, "LlvmOptArgs" ) ) { string optArgs; if( !GetArgument( arg, args, ref i, out optArgs, false ) ) { return false; } m_LlvmOptArgs = optArgs.Trim( '"' ); } else if( IsMatch( option, "LlvmLlcArgs" ) ) { string llcArgs; if( !GetArgument( arg, args, ref i, out llcArgs, false ) ) { return false; } m_LlvmLlcArgs = llcArgs.Trim( '"' ); } else if( IsMatch( option, "CompilationSetup" ) ) { string compilationSetup; if( !GetArgument( arg, args, ref i, out compilationSetup, false ) ) { return false; } m_compilationSetup = null; foreach( var setup in GetConfigurationOptions( ) ) { if( setup.GetType( ).FullName == compilationSetup ) { m_compilationSetup = setup; break; } } if( m_compilationSetup == null ) { Console.WriteLine( "Cannot find definition for compilation setup '{0}'", compilationSetup ); return false; } SearchConfigurationOptions( m_compilationSetup ); m_product = GetConfigurationOption( m_compilationSetup.Product ); if( m_product == null ) { Console.Error.WriteLine( "Cannot compile without a product definition!" ); return false; } SearchConfigurationOptions( m_product ); m_memoryMap = GetConfigurationOption( m_compilationSetup.MemoryMap ); if( m_memoryMap == null ) { Console.Error.WriteLine( "Cannot compile without a memory map!" ); return false; } SearchConfigurationOptions( m_memoryMap ); } else if( IsMatch( option, "CompilationOption" ) ) { string type; string name; string value; if( !GetArgument( arg, args, ref i, out type, false ) || !GetArgument( arg, args, ref i, out name, false ) || !GetArgument( arg, args, ref i, out value, false ) ) { return false; } Type t = Type.GetType( type ); if( t == null ) { Console.Error.WriteLine( "Cannot find type '{0}'", type ); return false; } try { object res; if(t == typeof( String )) { res = value; } else { res = t.InvokeMember( "Parse", System.Reflection.BindingFlags.InvokeMethod | System.Reflection.BindingFlags.Static | System.Reflection.BindingFlags.Public, null, null, new object[] { value } ); } m_configurationOptions[ name ] = res; } catch( Exception ex ) { Console.Error.WriteLine( "Cannot parse value '{0}': {1}", value, ex ); return false; } } else if( IsMatch( option, "CompilationPhaseDisabled" ) ) { string phase; if( !GetArgument( arg, args, ref i, out phase, false ) ) { return false; } m_disabledPhases.Add( phase.Trim( ) ); } else if( IsMatch( option, "Include" ) ) { string dir; if( !GetArgument( arg, args, ref i, out dir, true ) ) { return false; } AddSearchDirectory( dir ); } else if( IsMatch( option, "SkipReadOnly" ) ) { m_fSkipReadOnly = true; } else if( IsMatch( option, "EmbedSourceCode" ) ) { string sFile; if( !GetArgument( arg, args, ref i, out sFile, true ) ) { return false; } EmbedSourceCode( sFile ); return false; } else if( IsMatch( option, "EmbedSourceCodeAll" ) ) { string sDir; if( !GetArgument( arg, args, ref i, out sDir, true ) ) { return false; } EmbedSourceCodeAll( sDir ); return false; } else if( IsMatch( option, "EntryPoint" ) ) { string sEP; if( !GetArgument( arg, args, ref i, out sEP, true ) ) { return false; } m_entryPointName = sEP; } else if( IsMatch( option, "Debug" ) ) { m_fSkipLlvmOptExe = true; m_LlvmCodeGenOptions.EnableAutoInlining = false; m_LlvmCodeGenOptions.HonorInlineAttribute = false; m_LlvmCodeGenOptions.InjectPrologAndEpilog = false; } else if( IsMatch( option, "Architecture" ) ) { string arch; if( !GetArgument( arg, args, ref i, out arch, true ) ) { return false; } ValidateArchitecture( arch ); m_architecture = arch; } else if( IsMatch( option, "DisableAutoInlining" ) ) { m_LlvmCodeGenOptions.EnableAutoInlining = false; } else if( IsMatch( option, "IgnoreInlineAttributes" ) ) { m_LlvmCodeGenOptions.HonorInlineAttribute = false; } else if( IsMatch( option, "DisablePrologEpilogInjection" ) ) { m_LlvmCodeGenOptions.InjectPrologAndEpilog = false; } else if( IsMatch( option, "GenerateDataSectionPerType" ) ) { m_LlvmCodeGenOptions.GenerateDataSectionPerType = true; } else { Console.WriteLine( "Unrecognized option: {0}", option ); return false; } } else { arg = Expand( arg ); if( File.Exists( arg ) == false ) { Console.WriteLine( "Cannot find '{0}'", arg ); return false; } if( m_targetFile != null ) { Console.WriteLine( "ERROR: Only one target file per compilation." ); } m_targetFile = arg; m_searchOrder.Insert( 0, System.IO.Path.GetDirectoryName( arg ) ); } } return true; } private void ValidateArchitecture( string arch ) { switch(arch) { case c_CortexM0: case c_CortexM3: case c_CortexM4: case c_CortexM7: case c_x86_64: break; default: throw new NotSupportedException( "The only architectures currently supported are x86-64 and Cortex-M, for M0[+], M3, M4 and M7 variants" ); } } private static bool IsMatch( string arg, string cmd ) { return String.Compare( arg, cmd, StringComparison.OrdinalIgnoreCase ) == 0; } private static bool GetArgument( string arg, string[] args, ref int i, out string value, bool fExpand, bool fErrorOnParse = true ) { if( i + 1 < args.Length ) { i++; value = args[ i ]; if( fExpand ) { value = Expand( value ); } return true; } if(fErrorOnParse) { Console.WriteLine( "Option '{0}' needs an argument", arg ); } value = null; return false; } private static bool GetArgument( string arg, string[] args, ref int i, out uint value, bool fCanBeHex ) { string str; if( GetArgument( arg, args, ref i, out str, false ) ) { if( uint.TryParse( str, out value ) ) { return true; } if( fCanBeHex ) { if( str.StartsWith( "0x" ) && uint.TryParse( str.Substring( 2 ), System.Globalization.NumberStyles.AllowHexSpecifier, null, out value ) ) { return true; } } Console.WriteLine( "Option '{0}' needs a numeric argument, got '{1}'", arg, str ); } value = 0; return false; } //--// private bool ValidateOptions( ) { if( !ValidateLlvmToolsPath( ) ) return false; /* if( m_compilationSetup == null ) { Console.Error.WriteLine( "Cannot compile without a compilation setup!" ); return false; }*/ return true; } // Verify the LLVM tools path // if the path isn't set from command line options try to figure it out // using the following (in order): // 1) The path this program is executing from (Standard end user install scenario) // 2) LlvmBinPathEnvVarNames environment variables for curent process // 3) LlvmBinPathEnvVarNames environment variable/registry for curent user // 4) LlvmBinPathEnvVarNames environment variable/registry for curent machine // 5) HKCU\\@ToolsBin // 6) HKLM\\@ToolsBin // 7) HKCU\\@SrcRoot + "build\Win32\Release\bin" // 8) HKCU\\@SrcRoot + "build\x64\Release\bin" // 9) HKLM\\@SrcRoot + "build\Win32\Release\bin" // 10) HKLM\\@SrcRoot + "build\x64\Release\bin" // 11) Scan all paths in the processes PATH environment variable for the // first one containing opt.exe, llc.exe and llvm-dis.exe // // If none of the above yields a path that contains the required apps then fail the validation // // NOTE: this will update m_LlvmBinPath to the resolved path if one was found. // If the path to the LLVM tools isn't already in the PATH environment var // it is added to the PATH for this process. private bool ValidateLlvmToolsPath( ) { // if the tools aren't needed, based on options, no point verifying anything else if(m_fSkipLlvmOptExe && !m_fGenerateObj) return true; // cover the expected production scenario first if (string.IsNullOrWhiteSpace( m_LlvmBinPath )) { var thisAssembly = System.Reflection.Assembly.GetExecutingAssembly(); var localPath = Path.GetDirectoryName(thisAssembly.Location); if(PathHasLlvmTools(localPath)) m_LlvmBinPath = localPath; } // cover the most common internal development scenarios if (string.IsNullOrWhiteSpace( m_LlvmBinPath )) { m_LlvmBinPath = FindLLvmToolsPathOrSubPathFromEnvVars( EnvironmentVariableTarget.Process , EnvironmentVariableTarget.User , EnvironmentVariableTarget.Machine ); } if(string.IsNullOrWhiteSpace( m_LlvmBinPath )) { m_LlvmBinPath = GetRegValueString( RegistryHive.CurrentUser, LlvmRegSoftwareBinPath, "ToolsBin" ); } if(string.IsNullOrWhiteSpace( m_LlvmBinPath )) { m_LlvmBinPath = GetRegValueString( RegistryHive.LocalMachine, LlvmRegSoftwareBinPath, "ToolsBin" ); } if(string.IsNullOrWhiteSpace( m_LlvmBinPath )) { var srcRootDir = GetRegValueString( RegistryHive.CurrentUser, LlvmRegSoftwareBinPath, "SrcRoot" ); if(!string.IsNullOrWhiteSpace( srcRootDir )) { m_LlvmBinPath = Path.Combine( srcRootDir, "build", "Win32", "Release", "bin" ); if(string.IsNullOrWhiteSpace( m_LlvmBinPath ) && Environment.Is64BitOperatingSystem) { m_LlvmBinPath = m_LlvmBinPath = Path.Combine( srcRootDir, "build", "x64", "Release", "bin" ); } } } if(string.IsNullOrWhiteSpace( m_LlvmBinPath )) { var srcRootDir = GetRegValueString( RegistryHive.LocalMachine, LlvmRegSoftwareBinPath, "SrcRoot" ); if(!string.IsNullOrWhiteSpace( srcRootDir )) { m_LlvmBinPath = Path.Combine( srcRootDir, "build", "Win32", "Release", "bin" ); if(string.IsNullOrWhiteSpace( m_LlvmBinPath ) && Environment.Is64BitOperatingSystem) { m_LlvmBinPath = m_LlvmBinPath = Path.Combine( srcRootDir, "build", "x64", "Release", "bin" ); } } } // try scanning the PATH environment var to see if the tools are already in the PATH var envPathToLlvmTools = FindLlvmToolsInPath( ); if(string.IsNullOrWhiteSpace( m_LlvmBinPath ) && !string.IsNullOrWhiteSpace( envPathToLlvmTools )) { m_LlvmBinPath = envPathToLlvmTools; } if(string.IsNullOrWhiteSpace( m_LlvmBinPath )) { var color = Console.ForegroundColor; Console.ForegroundColor = ConsoleColor.Red; Console.Error.WriteLine( "ERROR: LLVM Tools location not specified and could not be determined" ); Console.ForegroundColor = color; return false; } if(!PathHasLlvmTools( m_LlvmBinPath )) { var color = Console.ForegroundColor; Console.ForegroundColor = ConsoleColor.Red; Console.Error.WriteLine( "ERROR: LLVM Tools not found in path '{0}'", m_LlvmBinPath ); Console.ForegroundColor = color; return false; } // if the llvm tools path isn't already in the PATH environment variable, add it so the tools are found when launched if( string.IsNullOrWhiteSpace( envPathToLlvmTools ) ) { Environment.SetEnvironmentVariable( "PATH", $"{Environment.GetEnvironmentVariable( "PATH" )};{m_LlvmBinPath}" ); } return true; } private static string FindLLvmToolsPathOrSubPathFromEnvVars( params EnvironmentVariableTarget[] targets ) { foreach( var target in targets ) { foreach( var envVar in LlvmBinPathEnvVarNames ) { var envPath = Environment.GetEnvironmentVariable( envVar, target ); if( string.IsNullOrEmpty( envPath ) ) continue; if( PathHasLlvmTools( envPath ) ) { return envPath; } // if the path points to the LLVM build source root then the actual // binaries are in a platform sepcific sub folder, try Win32 first. var envSubPath = Path.Combine( envPath, "build", "Win32", "Release", "bin" ); if( PathHasLlvmTools( envSubPath ) ) { return envSubPath; } envSubPath = Path.Combine( envPath, "build", "x64", "Release", "bin" ); if( PathHasLlvmTools( envPath ) ) { return envPath; } } } return null; } private string FindLlvmToolsInPath( ) { var envPathVar = Environment.ExpandEnvironmentVariables( "PATH" ); var envPaths = envPathVar.Split( ';' ); return ( from path in envPaths where PathHasLlvmTools( path ) select path ).FirstOrDefault( ); } static bool PathHasLlvmTools( string path ) { return File.Exists( Path.Combine( path, "opt.exe" ) ) && File.Exists( Path.Combine( path, "llc.exe" ) ) && File.Exists( Path.Combine( path, "llvm-dis.exe" ) ); } private string GetRegValueString( RegistryHive hive, string subkey, string valueName, string defaultValue = null, RegistryView view = RegistryView.Default ) { using( var hkRoot = RegistryKey.OpenBaseKey( hive, view ) ) using( var key = hkRoot.OpenSubKey( subkey ) ) { if( key == null ) return null; return ( string )key.GetValue( valueName ); } } private void Compile( ) { // // Store build artifacts on a per-product basis // m_outputDir = Path.Combine( m_outputDir, ExtractProductName( m_compilationSetup.Product ) ); if( m_outputName == null ) { m_outputName = Path.GetFileNameWithoutExtension( m_targetFile ); } string filePrefix = Path.Combine( m_outputDir, m_outputName ); /*FileStream fs = new FileStream( filePrefix + "_cout.txt", FileMode.Create ); StreamWriter sw = new StreamWriter( fs ); Console.SetOut( sw );*/ //--// // // We need this assembly, for all the extra stuff about open classes. // if( m_fReloadState == false ) { MetaData.IMetaDataResolverHelper resolver = this; Importer.MetaData md; md = resolver.ResolveAssemblyReference( "Microsoft.Zelig.Runtime", null ); m_resolver.Add( md ); m_resolver.ResolveAll( ); md = resolver.ResolveAssemblyReference( "mscorlib", null ); m_resolver.Add( md ); m_resolver.ResolveAll( ); //--// md = LoadAssembly( m_targetFile ); m_resolver.Add( md ); m_resolver.ResolveAll( ); //--// foreach( string reference in m_references ) { md = resolver.ResolveAssemblyReference( reference, null ); m_resolver.Add( md ); m_resolver.ResolveAll( ); } } //--// #if DEBUG_RELOAD_STATE m_typeSystem = (TypeSystemForFrontEnd)LoadIrFromDisk( "temp.ZeligImage", CreateInstanceForType ); m_typeSystem.GenerateImage( Microsoft.Zelig.CodeGeneration.IR.CompilationSteps.Phase.GenerateImage ); m_controller = new IR.CompilationSteps.Controller( m_typeSystem ); if(m_fDumpIL) { } if(m_fDumpIRpre) { } #else if( m_fReloadState == false ) { m_typeSystem = new TypeSystemForFrontEnd( this, this ); m_delegationCache = new IR.CompilationSteps.DelegationCache( m_typeSystem ); m_typeSystem.InitializeForCompilation( ); //--// var pa = ( IR.Abstractions.Platform )Activator.CreateInstance( m_compilationSetup.Platform, m_typeSystem, m_memoryMap ); m_typeSystem.PlatformAbstraction = pa; //--// var cc = ( IR.Abstractions.CallingConvention )Activator.CreateInstance( m_compilationSetup.CallingConvention, m_typeSystem ); m_typeSystem.CallingConvention = cc; //--// m_typeSystem.Product = m_product.GetType(); //--// Console.WriteLine( "{0}: ConvertToIR", GetTime( ) ); foreach( Normalized.MetaDataAssembly asml in m_resolver.NormalizedAssemblies ) { m_typeSystem.ImportAssembly( asml ); } Console.WriteLine( "{0}: Done", GetTime( ) ); //--// Console.WriteLine( "{0}: ResolveAll", GetTime( ) ); m_typeSystem.ResolveAll( ); Console.WriteLine( "{0}: Done", GetTime( ) ); //--// Directory.CreateDirectory( Path.GetDirectoryName( filePrefix ) ); if( m_fDumpIL ) { DirectoryInfo di = Directory.CreateDirectory( filePrefix ); string oldCD = Environment.CurrentDirectory; Environment.CurrentDirectory = di.FullName; foreach( Normalized.MetaDataAssembly asmlNormalized in m_resolver.NormalizedAssemblies ) { using( MetaData.MetaDataDumper writer = new MetaData.MetaDataDumper( asmlNormalized.Name, asmlNormalized.Version ) ) { writer.Process( asmlNormalized, true ); } } Environment.CurrentDirectory = oldCD; } if( m_fDumpCFG ) { DirectoryInfo di = Directory.CreateDirectory( filePrefix + "CFG" ); string oldCD = Environment.CurrentDirectory; Environment.CurrentDirectory = di.FullName; foreach( var t in m_typeSystem.Types ) { foreach( var method in t.Methods ) { IR.ControlFlowGraphStateForCodeTransformation cfg = IR.TypeSystemForCodeTransformation.GetCodeForMethod( method ); if( cfg != null ) { cfg.DumpToFile( method.Identity.ToString( ) + ".txt" ); } } } Environment.CurrentDirectory = oldCD; } if( m_fDumpIRpre ) { using( System.IO.TextWriter writer = new System.IO.StreamWriter( filePrefix + ".TypeSystemDump.IrTxtpre", false, System.Text.Encoding.ASCII ) ) { writer.WriteLine( "======================" ); writer.WriteLine( "==== Types table ====" ); writer.WriteLine( "======================" ); foreach( TS.TypeRepresentation td in m_typeSystem.Types ) { writer.WriteLine( "Type : {0}", td ); writer.WriteLine( "Assembly: {0}", td.Owner.Name ); writer.WriteLine( "Version : {0}", td.Owner.Version ); } writer.WriteLine( "" ); writer.WriteLine( "" ); writer.WriteLine( "" ); writer.WriteLine( "======================" ); writer.WriteLine( "==== Type Details ====" ); writer.WriteLine( "======================" ); foreach( TS.TypeRepresentation td in m_typeSystem.Types ) { writer.WriteLine( "Type: {0}", td ); foreach( TS.TypeRepresentation itf in td.Interfaces ) { writer.WriteLine( " Interface: {0}", itf ); } foreach( TS.FieldRepresentation fd in td.Fields ) { writer.WriteLine( " Field: {0}", fd ); } foreach( TS.MethodRepresentation md in td.Methods ) { writer.WriteLine( " Method: {0}", md ); } writer.WriteLine( ); } } DumpIRAsText( filePrefix + ".ZeligIR_Pre" ); } if (m_fDumpIRXMLpre) { DumpIRAsXML(filePrefix + ".ZeligIR_Pre.xml"); } //--// m_typeSystem.NativeImportDirectories = m_importDirectories; m_typeSystem.NativeImportLibraries = m_importLibraries; Console.WriteLine( "{0}: ExecuteSteps", GetTime( ) ); m_controller = new IR.CompilationSteps.Controller( m_typeSystem, m_disabledPhases ); m_controller.ExecuteSteps( ); if( m_fDumpIRpost ) { using( System.IO.TextWriter writer = new System.IO.StreamWriter( filePrefix + ".TypeSystemDump.IrTxtpost", false, System.Text.Encoding.ASCII ) ) { writer.WriteLine( "======================" ); writer.WriteLine( "==== Types table ====" ); writer.WriteLine( "======================" ); foreach( TS.TypeRepresentation td in m_typeSystem.Types ) { writer.WriteLine( "Type : {0}", td ); writer.WriteLine( "Assembly: {0}", td.Owner.Name ); writer.WriteLine( "Version : {0}", td.Owner.Version ); } writer.WriteLine( "" ); writer.WriteLine( "" ); writer.WriteLine( "" ); writer.WriteLine( "======================" ); writer.WriteLine( "==== Type Details ====" ); writer.WriteLine( "======================" ); foreach( TS.TypeRepresentation td in m_typeSystem.Types ) { writer.WriteLine( "Type : {0}", td ); foreach( TS.TypeRepresentation itf in td.Interfaces ) { writer.WriteLine( " Interface: {0}", itf ); } foreach( TS.FieldRepresentation fd in td.Fields ) { writer.WriteLine( " Field: {0}", fd ); } foreach( TS.MethodRepresentation md in td.Methods ) { writer.WriteLine( " Method: {0}", md ); } writer.WriteLine( ); } } DumpIRAsText( filePrefix + ".ZeligIR_Post" ); } if (m_fDumpIRXMLpost) { DumpIRAsXML(filePrefix + ".ZeligIR_Post.xml"); } SaveIrToDisk( "temp.ZeligImage", m_typeSystem ); } else { m_typeSystem = ( TypeSystemForFrontEnd )LoadIrFromDisk( "temp.ZeligImage", CreateInstanceForType ); m_delegationCache = new IR.CompilationSteps.DelegationCache( m_typeSystem ); //--// Console.WriteLine( "{0}: ExecuteSteps", GetTime( ) ); m_controller = new IR.CompilationSteps.Controller( m_typeSystem ); m_controller.ExecuteSteps( true ); } Console.WriteLine( "{0}: Done", GetTime( ) ); Console.Out.Flush( ); #endif if( PerformanceCounters.ContextualTiming.IsEnabled( ) ) { Console.WriteLine( "{0}: Dumping Performance Counters", GetTime( ) ); using( System.IO.StreamWriter output = new System.IO.StreamWriter( filePrefix + "_timing.type.txt", false, System.Text.Encoding.ASCII ) ) { PerformanceCounters.ContextualTiming.DumpAllByType( output ); } using( System.IO.StreamWriter output = new System.IO.StreamWriter( filePrefix + "_timing.reason.txt", false, System.Text.Encoding.ASCII ) ) { PerformanceCounters.ContextualTiming.DumpAllByReason( output ); } Console.WriteLine( "{0}: Done", GetTime( ) ); } // // We don't need to serialized the prohibited set. // Console.WriteLine( "{0}: Saving Results for {1}", GetTime( ), filePrefix ); m_typeSystem.DropCompileTimeObjects( ); { Console.WriteLine( "{0}: Image...", GetTime( ) ); SaveIrToDisk( filePrefix + ".ZeligImage", m_typeSystem ); Console.WriteLine( "{0}: Image done", GetTime( ) ); } if( m_fDumpIR ) { Console.WriteLine( "{0}: IR dump...", GetTime( ) ); DumpIRAsText( filePrefix + ".ZeligIR" ); Console.WriteLine( "{0}: IR dump done", GetTime( ) ); } if( m_fDumpFlattenedCallGraph ) { Console.WriteLine( "{0}: Flattened call graph dump...", GetTime( ) ); DumpCallGraph( filePrefix + ".ZeligCallsToGraph" , fCallsTo: true ); DumpCallGraph( filePrefix + ".ZeligCallsFromGraph", fCallsTo: false ); Console.WriteLine( "{0}: call graph dump done", GetTime( ) ); } if (m_fDumpIRXML) { Console.WriteLine("{0}: IR dump (XML)...", GetTime()); DumpIRAsXML(filePrefix + ".ZeligIR.xml"); Console.WriteLine("{0}: IR dump (XML) done", GetTime()); } if( m_fDumpASMDIR ) { Console.WriteLine( "{0}: ASMDIR dump...", GetTime( ) ); m_typeSystem.DisassembleImage( filePrefix + ".asmdir" ); Console.WriteLine( "{0}: ASMDIR dump done", GetTime( ) ); } if( m_fDumpASM ) { Console.WriteLine( "{0}: ASM dump...", GetTime( ) ); m_typeSystem.DisassembleImageInOneFile( filePrefix + ".asm" ); Console.WriteLine( "{0}: ASM dump done", GetTime( ) ); } if( m_fDumpHEX ) { Console.WriteLine( "{0}: HEX file...", GetTime( ) ); using( FileStream stream = new FileStream( filePrefix + ".hex", FileMode.Create ) ) { foreach( var section in m_typeSystem.Image ) { ARM.SRecordParser.Encode( stream, section.Payload, section.Address ); } TS.MethodRepresentation mdEntrypoint = m_typeSystem.TryGetHandler( Microsoft.Zelig.Runtime.HardwareException.Reset ); if( mdEntrypoint != null ) { IR.ControlFlowGraphStateForCodeTransformation cfg = IR.TypeSystemForCodeTransformation.GetCodeForMethod( mdEntrypoint ); if( cfg != null ) { IR.ImageBuilders.SequentialRegion reg = m_typeSystem.ImageBuilder.GetAssociatedRegion( cfg ); if( reg != null ) { ARM.SRecordParser.EncodeEntrypoint( stream, reg.BaseAddress.ToUInt32( ) ); } } } } Console.WriteLine( "{0}: HEX file done", GetTime( ) ); } if( m_fDumpLLVMIR_TextRepresentation ) { Console.WriteLine( "Writing LLVM IR text representation" ); m_typeSystem.Module.DumpToFile( filePrefix + ".ll", LLVM.OutputFormat.BitCodeSource ); } if( m_fDumpLLVMIR ) { Console.WriteLine( "Writing LLVM Bitcode representation" ); m_typeSystem.Module.DumpToFile( filePrefix + ".bc", LLVM.OutputFormat.BitCodeBinary ); } if( m_fDumpLLVMIR && !m_fSkipLlvmOptExe ) { var optSwitches = BuildOptArchitectureArgs( ); Console.WriteLine( "Optimizing LLVM Bitcode representation" ); var args = string.Format( "{0} {1} -o {2}" , m_LlvmOptArgs ?? optSwitches, filePrefix + ".bc" , filePrefix + "_opt.bc" ); ShellExec( "opt.exe", args ); ShellExec( "llvm-dis.exe", filePrefix + "_opt.bc" ); } else if( m_fGenerateObj ) { if(File.Exists(filePrefix + "_opt.bc")) { File.Delete(filePrefix + "_opt.bc"); } if(File.Exists(filePrefix + ".bc")) { File.Copy(filePrefix + ".bc", filePrefix + "_opt.bc"); } } if( m_fGenerateObj ) { var objFile = filePrefix + "_opt.o"; var llcSwitches = BuildLlcArchitectureArgs(); Console.WriteLine( "Compiling LLVM Bitcode" ); var args = string.Format( "{0} -o={1} {2}" , m_LlvmLlcArgs ?? llcSwitches, objFile , filePrefix + "_opt.bc" ); ShellExec( "llc.exe", args ); if(m_architecture != c_x86_64) { DumpElfInformation(objFile, filePrefix); } } foreach( var raw in m_dumpRawImage ) { var mem = new MemoryStream( ); foreach( var section in m_typeSystem.Image ) { uint sectionStart = section.Address; uint sectionEnd = sectionStart + ( uint )section.Payload.Length; uint sectionStart2 = Math.Max( sectionStart, raw.RangeStart ); uint sectionEnd2 = Math.Min( sectionEnd, raw.RangeEnd ); if( sectionStart2 < sectionEnd2 ) { uint offset = sectionStart2 - raw.RangeStart; mem.SetLength( offset ); mem.Seek( offset, SeekOrigin.Begin ); mem.Write( section.Payload, 0, section.Payload.Length ); } } if( mem.Length > 0 ) { Console.WriteLine( "{0}: RAW file...", GetTime( ) ); using( FileStream stream = new FileStream( filePrefix + "." + raw.SectionName + ".bin", FileMode.Create ) ) { var buf = mem.ToArray( ); stream.Write( buf, 0, buf.Length ); } Console.WriteLine( "{0}: RAW file done", GetTime( ) ); } } Console.WriteLine( "{0}: Done", GetTime( ) ); } private string ExtractProductName( Type product ) { var name = product.ToString(); return name.LastIndexOf( '.' ) != -1 ? name.Substring( name.LastIndexOf( '.' ) + 1 ) : name; } private object BuildLlcArchitectureArgs( ) { return ConcatArgs( DefaultLlcArgs_common, GetLlcSwitchesForTargetArchitecture( ), DefaultLlcArgs_reloc ); } private string BuildOptArchitectureArgs( ) { return ConcatArgs( DefaultOptExeArgs_common, GetOptSwitchesForTargetArchitecture() ); } private string GetOptSwitchesForTargetArchitecture( ) { switch(m_architecture) { case c_CortexM0: return DefaultOptArgs_target_m0; case c_CortexM3: return DefaultOptArgs_target_m3; case c_CortexM4: return DefaultOptArgs_target_m4; case c_CortexM7: return DefaultOptArgs_target_m7; case c_x86_64: return DefaultOptArgs_target_x86; default: return DefaultOptArgs_target_df; } } private string GetLlcSwitchesForTargetArchitecture( ) { switch(m_architecture) { case c_CortexM0: return DefaultLlcArgs_target_m0; case c_CortexM3: return DefaultLlcArgs_target_m3; case c_CortexM4: return DefaultLlcArgs_target_m4; case c_CortexM7: return DefaultLlcArgs_target_m7; case c_x86_64: return DefaultLlcArgs_target_x86; default: return DefaultLlcArgs_target_df; } } private string ConcatArgs( params string[] args ) { var sb = new StringBuilder(); for(int i = 0; i < args.Length; ++i) { sb.Append( args[i] ); if(i < args.Length - 1) { sb.Append( " " ); } } return sb.ToString( ); } private int ShellExec( string exe, string args ) { var startInfo = new ProcessStartInfo( exe, args ) { CreateNoWindow = true , UseShellExecute = false , RedirectStandardError = true , RedirectStandardOutput = true }; // for reasons unknown launching a process via ProcessStart doesn't actually inherit the // STDOUT and STDERR so this has to capture the output from poth and then send it to the // console explicitly or the output from the process will just end up in the bit pool at // the bottom of the computer's chasis. var proc = new Process( ) { StartInfo = startInfo }; proc.ErrorDataReceived += ( s, e ) => { if( e.Data != null ) Console.Error.WriteLine( e.Data ); }; proc.OutputDataReceived += ( s, e ) => { if( e.Data != null ) Console.WriteLine( e.Data ); }; proc.Start( ); proc.BeginOutputReadLine( ); proc.BeginErrorReadLine( ); proc.WaitForExit( ); return proc.ExitCode; } private void DumpElfInformation( string objFile, string filePrefix ) { var objElfObjs = ELF.ElfObject.FileUtil.Parse( objFile ); using(var sr = new System.IO.StreamWriter( filePrefix + "_opt.ElfDump" )) { foreach(var obj in objElfObjs) { sr.WriteLine( ELF.OutputFormatter.PrintElfHeader( obj.Header ) ); sr.WriteLine( ELF.OutputFormatter.PrintSectionHeaders( obj.Sections ) ); sr.WriteLine( ELF.OutputFormatter.PrintAllSizes( ELF.OutputFormatter.ComputeAllSizes( obj.SymbolTable ) ) ); var llilumTypes = new Dictionary(); var lillumMethods = new List(); var otherFunctions = new List(); uint totalSize = ELF.OutputFormatter.ComputeAllSizesMethodByMethod( obj.SymbolTable, llilumTypes, lillumMethods, otherFunctions ); sr.WriteLine( ELF.OutputFormatter.PrintTotalSizeMethodByMethod( totalSize ) ); sr.WriteLine( ); sr.WriteLine( ); sr.WriteLine( ELF.OutputFormatter.PrintAllTypesSizes ( llilumTypes , otherFunctions ) ); sr.WriteLine( ELF.OutputFormatter.PrintAllMethodsSizes( lillumMethods, otherFunctions, bySizeOrder: false ) ); sr.WriteLine( ELF.OutputFormatter.PrintAllMethodsSizes( lillumMethods, otherFunctions, bySizeOrder: true ) ); sr.WriteLine( "################################################" ); sr.WriteLine( "########### CROSS CHECK INFORMATION ############" ); sr.WriteLine( "################################################" ); sr.WriteLine( ); sr.WriteLine( ); sr.WriteLine( "============================================================================================" ); sr.WriteLine( " All types in llilum type system before LLVM code gen" ); sr.WriteLine( ); sr.WriteLine( " Total types: " + m_typeSystem.Types.Count ); sr.WriteLine( ); var allTypes = new List(); var allMethods = new List(); foreach(var tr in m_typeSystem.Types) { if(m_typeSystem.ShouldIncludeInCodeGenStats( tr )) { allTypes.Add( tr ); foreach(var mr in tr.Methods) { allMethods.Add( mr ); } } } foreach(var t in allTypes) { sr.WriteLine( t.FullName ); } sr.WriteLine( ); sr.WriteLine( ); sr.WriteLine( "============================================================================================" ); sr.WriteLine( " All methods in llilum type system before LLVM code gen" ); sr.WriteLine( ); sr.WriteLine( " Total methods: " + allMethods.Count ); sr.WriteLine( ); foreach(var mr in allMethods) { sr.WriteLine( mr.ToShortStringNoReturnValue( ) ); } //--o--//--o--//--o--//--o--//--o--//--o--//--o--//--o--//--o--//--o--//--o--// // // String table // List stringTable = new List(); var raw = obj.SymbolTable.StringTable; int index = 0; do { var s = raw.GetString( (uint)index ); if(string.IsNullOrEmpty( s )) { index++; continue; } stringTable.Add( s ); index += s.Length; // GetString will stop at the null separator } while(index < raw.Header.sh_size); sr.WriteLine( ); sr.WriteLine( ); sr.WriteLine( "============================================================================================" ); sr.WriteLine( " Strings table" ); sr.WriteLine( ); sr.WriteLine( "Total strings: " + stringTable.Count ); sr.WriteLine( ); for(int i = 0; i < stringTable.Count; i++) { sr.WriteLine( "{0:D6}: '{1}'", i, stringTable[i] ); } //--o--//--o--//--o--//--o--//--o--//--o--//--o--//--o--//--o--//--o--//--o--// // // Symbol table // var symbols = obj.SymbolTable.Symbols; sr.WriteLine( ); sr.WriteLine( ); sr.WriteLine( "============================================================================================" ); sr.WriteLine( " Symbols" ); sr.WriteLine( ); sr.WriteLine( "Total symbols: " + symbols.Length ); sr.WriteLine( ); for(int i = 0; i < symbols.Length; i++) { var symbol = symbols[ i ]; sr.WriteLine( "{0:D6}: Name: '{1}'\r\nSize: {2}\r\nType: {3}\r\nReferencedSection: '{4}'\r\nBinding: {5}\r\nVisibility: {6}\r\n", i, symbol.Name, symbol.SymbolDef.st_size, symbol.Type, symbol.ReferencedSection?.Name, symbol.Binding, symbol.Visibility ); } // // Done // sr.WriteLine( ); sr.WriteLine( ); sr.WriteLine( ); sr.WriteLine( " Elf Object dump completed for {0}", obj.FileName ); sr.WriteLine( "============================================================================================" ); sr.WriteLine( ); sr.WriteLine( ); sr.WriteLine( ); } } } internal static bool RunBench(string[] args) { bool fNoSDK = false; Bench bench = new Bench(); Bench.s_pThis = bench; // path with space need to be re-assembled string[] recombinedArgs = RecombineArgs(args); if(recombinedArgs != null && bench.Parse( recombinedArgs, ref fNoSDK )) { if(bench.ValidateOptions( )) { bench.Compile(); } } return fNoSDK; } public static int Main( string[] args ) { int retVal = 0; System.Threading.Thread th = new System.Threading.Thread( ()=> { bool fNoSDK = false; try { fNoSDK = RunBench(args); } catch( Importer.SilentCompilationAbortException ) { retVal = -1; } catch( Exception ex ) { Console.Error.WriteLine( "Caught exception: {0}", ex ); retVal = ex.HResult > unchecked((int)0x80000000u) ? ex.HResult : -1; } finally { if( System.Diagnostics.Debugger.IsAttached && fNoSDK == true) { Console.WriteLine( "Press to exit" ); Console.ReadLine( ); } } }, 1024*1024*1024 ); th.Start( ); th.Join( ); return retVal; } } } ================================================ FILE: Zelig/Zelig/CompileTime/CodeGenerator/FrontEnd/FrontEnd.csproj ================================================  Debug AnyCPU 9.0.21022 2.0 {186F31A3-EF89-4A25-B2D5-20070605AA02} Exe Properties Microsoft.Zelig.FrontEnd Microsoft.Zelig.Compiler $(LlilumBuildRoot)\Host\obj\$(MSBuildProjectName)\ v4.5 true full false $(LlilumBuildRoot)\Host\bin\$(Configuration)\ DEBUG;TRACE prompt 4 false true AllRules.ruleset AnyCPU false pdbonly true $(LlilumBuildRoot)\Host\bin\$(Configuration)\ TRACE prompt 4 false true AllRules.ruleset AnyCPU false $(LlilumBuildRoot)\Host\bin\$(Configuration)\ TRACE;DEBUG;DEBUG_INSTRUMENTATION AnyCPU true false 3.5 {186F31A3-EF89-4A25-B2D5-20060704AA01} ArmProcessorEmulation False {186F31A3-EF89-4A25-B2D5-20070601AA01} CommonPC False {186F31A3-EF89-4A25-B2D5-20060509AA01} Kernel False {96BF0234-1D60-4401-A6B9-99839187234E} InequalityGraphVisualization False {186F31A3-EF89-4A25-B2D5-20060404AA01} Importer False {186F31A3-EF89-4A25-B2D5-20060510AA01} Normalized False {186F31A3-EF89-4A25-B2D5-20061218AA01} Common False {186F31A3-EF89-4A25-B2D5-20060720AA01} TypeSystem False {186F31A3-EF89-4A25-B2D5-20070606AA01} ProductConfiguration False {186F31A3-EF89-4A25-B2D5-20070222AA01} CodeTransformation False {186F31A3-EF89-4A25-B2D5-20060603AA01} IntermediateRepresentation False {37193a86-ba04-4a3e-9df8-656df455e952} Elflib Always Always ================================================ FILE: Zelig/Zelig/CompileTime/CodeGenerator/FrontEnd/Legacy/NohauLPC3180Loader.FrontEndConfig ================================================ ### ### Location of the Zelig assemblies. ### -HostAssemblyDir %DEPOTROOT%\ZeligBuild\Host\bin\Debug -DeviceAssemblyDir %DEPOTROOT%\ZeligBuild\Target\bin\Debug -CompilationSetup Microsoft.Zelig.Configuration.Environment.NohauLPC3180LoaderCompilationSetup ### ### We need to include this assembly to get the right drivers. ### ### ### The program to compile. ### %DEPOTROOT%\ZeligBuild\Target\bin\Debug\Microsoft.NohauLPC3180Loader.exe ### ### Where to put the results. ### -OutputDir %DEPOTROOT%\ZeligUnitTestResults -DumpHEX -DumpIR -DumpASM ================================================ FILE: Zelig/Zelig/CompileTime/CodeGenerator/FrontEnd/Legacy/VoxSoloFormFactorLoader.FrontEndConfig ================================================ ### ### Location of the Zelig assemblies. ### -HostAssemblyDir %DEPOTROOT%\ZeligBuild\Host\bin\Debug -DeviceAssemblyDir %DEPOTROOT%\ZeligBuild\Target\bin\Debug -CompilationSetup Microsoft.Zelig.Configuration.Environment.VoxSoloFormFactorLoaderCompilationSetup #-CompilationOption System.Boolean Test true ### ### We need to include this assembly to get the right drivers. ### ### ### The program to compile. ### %DEPOTROOT%\ZeligBuild\Target\bin\Debug\Microsoft.VoxSoloFormFactorLoader.exe ### ### Where to put the results. ### -OutputDir %DEPOTROOT%\ZeligUnitTestResults -DumpHEX -DumpIR -DumpASM ================================================ FILE: Zelig/Zelig/CompileTime/CodeGenerator/FrontEnd/Legacy/VoxSolo_Bootstrap_FF.FrontEndConfig ================================================ ### ### Location of the Zelig assemblies. ### -HostAssemblyDir %DEPOTROOT%\ZeligBuild\Host\bin\Debug -DeviceAssemblyDir %DEPOTROOT%\ZeligBuild\Target\bin\Debug -CompilationSetup Microsoft.Zelig.Configuration.Environment.VoxSoloFormFactorCompilationSetup ### ### We need to include this assembly to get the right drivers. ### -Reference Microsoft.VoxSoloFormFactor ### ### The program to compile. ### -Include %DEPOTROOT%\SoloBuild\bin\Debug ###-IncludeSource %DEPOTROOT%\Zelig\BinaryDrop\Target\Debug %DEPOTROOT%\SoloBuild\bin\Debug\Microsoft.Vox.Solo.CPU.Ollie.Bootstrap.exe ### ### Where to put the results. ### -OutputName soloTest_FF -OutputDir %DEPOTROOT%\ZeligUnitTestResults -DumpIR -DumpASM ================================================ FILE: Zelig/Zelig/CompileTime/CodeGenerator/FrontEnd/Legacy/VoxSolo_Bootstrap_NXP.FrontEndConfig ================================================ ### ### Location of the Zelig assemblies. ### -HostAssemblyDir %DEPOTROOT%\ZeligBuild\Host\bin\Debug -DeviceAssemblyDir %DEPOTROOT%\ZeligBuild\Target\bin\Debug -CompilationSetup Microsoft.Zelig.Configuration.Environment.NohauLPC3180CompilationSetup ### ### We need to include this assembly to get the right drivers. ### -Reference Microsoft.NohauLPC3180 ### ### The program to compile. ### -Include %DEPOTROOT%\SoloBuild\bin\Debug %DEPOTROOT%\SoloBuild\bin\Debug\Microsoft.Vox.Solo.CPU.LPC3180.Bootstrap.exe ### ### Where to put the results. ### -OutputName soloTest_NXP -OutputDir %DEPOTROOT%\ZeligUnitTestResults -DumpASMDIR #-DumpASM -DumpIR ================================================ FILE: Zelig/Zelig/CompileTime/CodeGenerator/FrontEnd/Legacy/VoxSolo_Tester_FF.FrontEndConfig ================================================ ### ### Location of the Zelig assemblies. ### -HostAssemblyDir %DEPOTROOT%\ZeligBuild\Host\bin\Debug -DeviceAssemblyDir %DEPOTROOT%\ZeligBuild\Target\bin\Debug -CompilationSetup Microsoft.Zelig.Configuration.Environment.VoxSoloFormFactorCompilationSetup ### ### We need to include this assembly to get the right drivers. ### -Reference Microsoft.VoxSoloFormFactor ### ### The program to compile. ### %DEPOTROOT%\ZeligBuild\Target\bin\Debug\Microsoft.VoxSoloFormFactorTester.exe ### ### Where to put the results. ### -OutputName soloTester_FF -OutputDir %DEPOTROOT%\ZeligUnitTestResults -DumpIR -DumpASM ================================================ FILE: Zelig/Zelig/CompileTime/CodeGenerator/FrontEnd/Legacy/VoxSolo_Tester_NXP.FrontEndConfig ================================================ ### ### Location of the Zelig assemblies. ### -HostAssemblyDir %DEPOTROOT%\ZeligBuild\Host\bin\Debug -DeviceAssemblyDir %DEPOTROOT%\ZeligBuild\Target\bin\Debug -CompilationSetup Microsoft.Zelig.Configuration.Environment.NohauLPC3180CompilationSetup ### ### We need to include this assembly to get the right drivers. ### -Reference Microsoft.NohauLPC3180 ### ### The program to compile. ### %DEPOTROOT%\ZeligBuild\Target\bin\Debug\Microsoft.NohauLPC3180Tester.exe ### ### Where to put the results. ### -OutputName soloTester_NXP -OutputDir %DEPOTROOT%\ZeligUnitTestResults -DumpIR -DumpASM ================================================ FILE: Zelig/Zelig/CompileTime/CodeGenerator/FrontEnd/Legacy/VoxSolo_UnitTest_FF.FrontEndConfig ================================================ ### ### Location of the Zelig assemblies. ### -HostAssemblyDir %DEPOTROOT%\ZeligBuild\Host\bin\Debug -DeviceAssemblyDir %DEPOTROOT%\ZeligBuild\Target\bin\Debug -CompilationSetup Microsoft.Zelig.Configuration.Environment.VoxSoloFormFactorCompilationSetup ### ### We need to include this assembly to get the right drivers. ### -Reference Microsoft.VoxSoloFormFactor ### ### The program to compile. ### -Include %DEPOTROOT%\SoloBuild\bin\Debug %DEPOTROOT%\SoloBuild\bin\Debug\Microsoft.Vox.Solo.CPU.Ollie.UnitTest.exe ### ### Where to put the results. ### -OutputName soloTest_FF -OutputDir %DEPOTROOT%\ZeligUnitTestResults -DumpIR -DumpASM ================================================ FILE: Zelig/Zelig/CompileTime/CodeGenerator/FrontEnd/Legacy/VoxSolo_UnitTest_NXP.FrontEndConfig ================================================ ### ### Location of the Zelig assemblies. ### -HostAssemblyDir %DEPOTROOT%\ZeligBuild\Host\bin\Debug -DeviceAssemblyDir %DEPOTROOT%\ZeligBuild\Target\bin\Debug -CompilationSetup Microsoft.Zelig.Configuration.Environment.NohauLPC3180CompilationSetup ### ### We need to include this assembly to get the right drivers. ### -Reference Microsoft.NohauLPC3180 ### ### The program to compile. ### -Include %DEPOTROOT%\SoloBuild\bin\Debug %DEPOTROOT%\SoloBuild\bin\Debug\Microsoft.Vox.Solo.CPU.LPC3180.UnitTest.exe ### ### Where to put the results. ### -OutputName soloTest_NXP -OutputDir %DEPOTROOT%\ZeligUnitTestResults -DumpIR -DumpASM ================================================ FILE: Zelig/Zelig/CompileTime/CodeGenerator/FrontEnd/Legacy/iMote2Loader.FrontEndConfig ================================================ ### ### Location of the Zelig assemblies. ### -HostAssemblyDir %DEPOTROOT%\ZeligBuild\Host\bin\Debug -DeviceAssemblyDir %DEPOTROOT%\ZeligBuild\Target\bin\Debug -CompilationSetup Microsoft.Zelig.Configuration.Environment.iMote2LoaderCompilationSetup ### ### We need to include this assembly to get the right drivers. ### ### ### The program to compile. ### %DEPOTROOT%\ZeligBuild\Target\bin\Debug\Microsoft.iMote2Loader.exe ### ### Where to put the results. ### -OutputDir %DEPOTROOT%\ZeligUnitTestResults -DumpHEX -DumpIR -DumpASM ================================================ FILE: Zelig/Zelig/CompileTime/CodeGenerator/FrontEnd/Legacy/iMoteQuickTest_Tester.FrontEndConfig ================================================ ### ### Location of the Zelig assemblies. ### -HostAssemblyDir %DEPOTROOT%\ZeligBuild\Host\bin\%flavor% -DeviceAssemblyDir %DEPOTROOT%\ZeligBuild\Target\bin\%flavor% ###-CompilationSetup Microsoft.Zelig.Configuration.Environment.VoxSoloFormFactorCompilationSetup ###-CompilationSetup Microsoft.Zelig.Configuration.Environment.NohauLPC3180CompilationSetup -CompilationSetup Microsoft.Zelig.Configuration.Environment.iMote2CompilationSetup ### ### We need to include this assembly to get the right drivers. ### ###-Reference Microsoft.VoxSoloFormFactor ###-Reference Microsoft.NohauLPC3180 -Reference Microsoft.iMote2 ###-ImportDirectory %DEPOTROOT%\ZeligInterop\Sample\FileSystemTest\LIB\ ###-ImportDirectory %DEPOTROOT%\..\client_v4_2_dev\tools\ads_v4_0\Lib\armlib\ ###-ImportDirectory %DEPOTROOT%\..\client_v4_2_dev\tools\ads_v4_0\Lib\cpplib\ ### ### The program to compile. ### %DEPOTROOT%\ZeligBuild\Target\bin\%flavor%\QuickTest.exe ### ### Where to put the results. ### -OutputName QuickTest_Tester -OutputDir %DEPOTROOT%\ZeligUnitTestResults #-DumpIR #-DumpASM ================================================ FILE: Zelig/Zelig/CompileTime/CodeGenerator/FrontEnd/Legacy/mscorlib_unittest_FF.FrontEndConfig ================================================ ### ### Location of the Zelig assemblies. ### -HostAssemblyDir %DEPOTROOT%\ZeligBuild\Host\bin\Debug -DeviceAssemblyDir %DEPOTROOT%\ZeligBuild\Target\bin\Debug -CompilationSetup Microsoft.Zelig.Configuration.Environment.VoxSoloFormFactorCompilationSetup -CompilationOption System.Boolean GarbageCollectionManager__ValidateHeap true ### ### We need to include this assembly to get the right drivers. ### -Reference Microsoft.VoxSoloFormFactor ### ### The program to compile. ### %DEPOTROOT%\ZeligBuild\Target\bin\Debug\mscorlib_UnitTest.exe ### ### Where to put the results. ### -OutputName mscorlib_UnitTest_FF -OutputDir %DEPOTROOT%\ZeligUnitTestResults -DumpIR -DumpASM ================================================ FILE: Zelig/Zelig/CompileTime/CodeGenerator/FrontEnd/Legacy/mscorlib_unittest_NXP.FrontEndConfig ================================================ ### ### Location of the Zelig assemblies. ### -HostAssemblyDir %DEPOTROOT%\ZeligBuild\Host\bin\Debug -DeviceAssemblyDir %DEPOTROOT%\ZeligBuild\Target\bin\Debug -CompilationSetup Microsoft.Zelig.Configuration.Environment.NohauLPC3180CompilationSetup ### ### We need to include this assembly to get the right drivers. ### -Reference Microsoft.NohauLPC3180 ### ### The program to compile. ### %DEPOTROOT%\ZeligBuild\Target\bin\Debug\mscorlib_UnitTest.exe ### ### Where to put the results. ### -OutputName mscorlib_UnitTest_NXP -OutputDir %DEPOTROOT%\ZeligUnitTestResults -DumpIR -DumpASM ================================================ FILE: Zelig/Zelig/CompileTime/CodeGenerator/FrontEnd/Legacy/mscorlib_unittest_PXA.FrontEndConfig ================================================ ### ### Location of the Zelig assemblies. ### -HostAssemblyDir %DEPOTROOT%\ZeligBuild\Host\bin\%flavor% -DeviceAssemblyDir %DEPOTROOT%\ZeligBuild\Target\bin\%flavor% -CompilationSetup Microsoft.Zelig.Configuration.Environment.iMote2CompilationSetup ### ### We need to include this assembly to get the right drivers. ### -Reference Microsoft.iMote2 ### ### The program to compile. ### %DEPOTROOT%\ZeligBuild\Target\bin\%flavor%\mscorlib_UnitTest.exe ### ### Where to put the results. ### -OutputName mscorlib_UnitTest_PXA -OutputDir %DEPOTROOT%\ZeligUnitTestResults -DumpIR -DumpASM ================================================ FILE: Zelig/Zelig/CompileTime/CodeGenerator/FrontEnd/Legacy/tester_FF.FrontEndConfig ================================================ ### ### Location of the Zelig assemblies. ### -HostAssemblyDir %DEPOTROOT%\ZeligBuild\Host\bin\Debug -DeviceAssemblyDir %DEPOTROOT%\ZeligBuild\Target\bin\Debug -CompilationSetup Microsoft.Zelig.Configuration.Environment.VoxSoloFormFactorCompilationSetup ### ### We need to include this assembly to get the right drivers. ### -Reference Microsoft.VoxSoloFormFactor ### ### The program to compile. ### %DEPOTROOT%\ZeligBuild\Target\bin\Debug\Microsoft.VoxSoloFormFactorTester.exe ### ### Where to put the results. ### -OutputName tester_FF -OutputDir %DEPOTROOT%\ZeligUnitTestResults -DumpIR -DumpASM ================================================ FILE: Zelig/Zelig/CompileTime/CodeGenerator/FrontEnd/Legacy/tester_NXP.FrontEndConfig ================================================ ### ### Location of the Zelig assemblies. ### -HostAssemblyDir %DEPOTROOT%\ZeligBuild\Host\bin\Debug -DeviceAssemblyDir %DEPOTROOT%\ZeligBuild\Target\bin\Debug -CompilationSetup Microsoft.Zelig.Configuration.Environment.NohauLPC3180CompilationSetup ### ### We need to include this assembly to get the right drivers. ### -Reference Microsoft.NohauLPC3180 ### ### The program to compile. ### %DEPOTROOT%\ZeligBuild\Target\bin\Debug\Microsoft.NohauLPC3180Tester.exe ### ### Where to put the results. ### -OutputName tester_NXP -OutputDir %DEPOTROOT%\ZeligUnitTestResults -DumpIR -DumpASM ================================================ FILE: Zelig/Zelig/CompileTime/CodeGenerator/FrontEnd/Legacy/tester_PXA.FrontEndConfig ================================================ ### ### Location of the Zelig assemblies. ### -HostAssemblyDir %DEPOTROOT%\ZeligBuild\Host\bin\Debug -DeviceAssemblyDir %DEPOTROOT%\ZeligBuild\Target\bin\Debug -CompilationSetup Microsoft.Zelig.Configuration.Environment.iMote2CompilationSetup ### ### We need to include this assembly to get the right drivers. ### -Reference Microsoft.iMote2 ### ### The program to compile. ### %DEPOTROOT%\ZeligBuild\Target\bin\Debug\Microsoft.iMote2Tester.exe ### ### Where to put the results. ### -OutputName tester_PXA -OutputDir %DEPOTROOT%\ZeligUnitTestResults -DumpIR -DumpASM ================================================ FILE: Zelig/Zelig/CompileTime/CodeGenerator/FrontEnd/Properties/AssemblyInfo.cs ================================================ using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; // General Information about an assembly is controlled through the following // set of attributes. Change these attribute values to modify the information // associated with an assembly. [assembly: AssemblyTitle( "Zelig Compiler" )] [assembly: AssemblyDescription( "" )] [assembly: AssemblyConfiguration( "" )] [assembly: AssemblyCompany( "Microsoft" )] [assembly: AssemblyProduct( "Microsoft.Zelig.Compiler" )] [assembly: AssemblyCopyright( "Copyright © Microsoft 2007" )] [assembly: AssemblyTrademark( "" )] [assembly: AssemblyCulture( "" )] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible( false )] //// The following GUID is for the ID of the typelib if this project is exposed to COM //[assembly: Guid( "012e8fb6-008e-45a0-ba5d-64b07a84aa95" )] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Revision and Build Numbers // by using the '*' as shown below: [assembly: AssemblyVersion( "1.0.0.0" )] [assembly: AssemblyFileVersion( "1.0.0.0" )] [assembly: InternalsVisibleTo("Microsoft.Zelig.Compiler.Tests")] ================================================ FILE: Zelig/Zelig/CompileTime/CodeGenerator/FrontEnd/Test/Dhrystone_perf_test.FrontEndConfig ================================================ ### ### Location of the Zelig assemblies. ### -HostAssemblyDir %DEPOTROOT%\ZeligBuild\Host\bin\%flavor% -DeviceAssemblyDir %DEPOTROOT%\ZeligBuild\Target\bin\%flavor% ###-CompilationSetup Microsoft.Zelig.Configuration.Environment.VoxSoloFormFactorCompilationSetup -CompilationSetup Microsoft.Zelig.Configuration.Environment.NohauLPC3180CompilationSetup ###-CompilationSetup Microsoft.Zelig.Configuration.Environment.iMote2CompilationSetup ### ### We need to include this assembly to get the right drivers. ### ###-Reference Microsoft.VoxSoloFormFactor -Reference Microsoft.NohauLPC3180 ###-Reference Microsoft.iMote2 ###-ImportDirectory %DEPOTROOT%\ZeligInterop\Sample\FileSystemTest\LIB\ ###-ImportDirectory %DEPOTROOT%\..\client_v4_2_dev\tools\ads_v4_0\Lib\armlib\ ###-ImportDirectory %DEPOTROOT%\..\client_v4_2_dev\tools\ads_v4_0\Lib\cpplib\ ### ### The program to compile. ### %DEPOTROOT%\ZeligBuild\Target\bin\%flavor%\DhrystoneTest.exe ### ### Where to put the results. ### -OutputName Dhrystone_perf_test -OutputDir %DEPOTROOT%\ZeligUnitTestResults -DumpIR -DumpASM ================================================ FILE: Zelig/Zelig/CompileTime/CodeGenerator/FrontEnd/Test/ExternalLinking_Tester.FrontEndConfig ================================================ ### ### Location of the Zelig assemblies. ### -HostAssemblyDir %DEPOTROOT%\ZeligBuild\Host\bin\%flavor% -DeviceAssemblyDir %DEPOTROOT%\ZeligBuild\Target\bin\%flavor% ###-CompilationSetup Microsoft.Zelig.Configuration.Environment.VoxSoloFormFactorCompilationSetup -CompilationSetup Microsoft.Zelig.Configuration.Environment.NohauLPC3180CompilationSetup ###-CompilationSetup Microsoft.Zelig.Configuration.Environment.iMote2CompilationSetup ### ### We need to include this assembly to get the right drivers. ### ###-Reference Microsoft.VoxSoloFormFactor -Reference Microsoft.NohauLPC3180 ###-Reference Microsoft.iMote2 ### ### Include directories for inter-op libraries ### -ImportDirectory %DEPOTROOT%\ZeligInterop\Sample\ExternalLinking_tester\LIB\ -ImportDirectory %DEPOTROOT%\..\client_v4_2_dev\tools\ads_v4_0\Lib\armlib\ -ImportDirectory %DEPOTROOT%\..\client_v4_2_dev\tools\ads_v4_0\Lib\cpplib\ ### ### The program to compile. ### %DEPOTROOT%\ZeligBuild\Target\bin\%flavor%\ExternalLinking_Tester.exe ### ### Where to put the results. ### -OutputName ExternalLinking_Tester -OutputDir %DEPOTROOT%\ZeligUnitTestResults -DumpIR -DumpASM ================================================ FILE: Zelig/Zelig/CompileTime/CodeGenerator/FrontEnd/Test/FileSystemSample.FrontEndConfig ================================================ ### ### Location of the Zelig assemblies. ### -HostAssemblyDir %DEPOTROOT%\ZeligBuild\Host\bin\%flavor% -DeviceAssemblyDir %DEPOTROOT%\ZeligBuild\Target\bin\%flavor% ###-CompilationSetup Microsoft.Zelig.Configuration.Environment.VoxSoloFormFactorCompilationSetup -CompilationSetup Microsoft.Zelig.Configuration.Environment.NohauLPC3180CompilationSetup ###-CompilationSetup Microsoft.Zelig.Configuration.Environment.iMote2CompilationSetup ### ### We need to include this assembly to get the right drivers. ### ###-Reference Microsoft.VoxSoloFormFactor -Reference Microsoft.NohauLPC3180 ###-Reference Microsoft.iMote2 ### ### Include directories for inter-op libraries ### -ImportDirectory %DEPOTROOT%\ZeligInterop\Sample\FileSystemSampleLPC\LIB\ -ImportDirectory %DEPOTROOT%\..\client_v4_2_dev\tools\ads_v4_0\Lib\armlib\ -ImportDirectory %DEPOTROOT%\..\client_v4_2_dev\tools\ads_v4_0\Lib\cpplib\ ### ### The program to compile. ### %DEPOTROOT%\ZeligBuild\Target\bin\%flavor%\FileSystemSample.exe ### ### Where to put the results. ### -OutputName FileSystemSample -OutputDir %DEPOTROOT%\ZeligUnitTestResults -DumpIR -DumpASM ================================================ FILE: Zelig/Zelig/CompileTime/CodeGenerator/FrontEnd/Test/FileSystem_Tester.FrontEndConfig ================================================ ### ### Location of the Zelig assemblies. ### -HostAssemblyDir %DEPOTROOT%\ZeligBuild\Host\bin\Debug -DeviceAssemblyDir %DEPOTROOT%\ZeligBuild\Target\bin\Debug ###-CompilationSetup Microsoft.Zelig.Configuration.Environment.VoxSoloFormFactorCompilationSetup ###-CompilationSetup Microsoft.Zelig.Configuration.Environment.NohauLPC3180CompilationSetup -CompilationSetup Microsoft.Zelig.Configuration.Environment.iMote2CompilationSetup ### ### We need to include this assembly to get the right drivers. ### ###-Reference Microsoft.VoxSoloFormFactor ###-Reference Microsoft.NohauLPC3180 -Reference Microsoft.iMote2 ### ### Include directories for inter-op libraries ### -ImportDirectory %DEPOTROOT%\ZeligInterop\Sample\FileSystemTest\LIB\ -ImportDirectory %DEPOTROOT%\..\client_v4_2_dev\tools\ads_v4_0\Lib\armlib\ -ImportDirectory %DEPOTROOT%\..\client_v4_2_dev\tools\ads_v4_0\Lib\cpplib\ ### ### The program to compile. ### %DEPOTROOT%\ZeligBuild\Target\bin\Debug\FileSystemTest.exe ### ### Where to put the results. ### -OutputName FileSystem_Tester -OutputDir %DEPOTROOT%\ZeligUnitTestResults #-DumpIR #-DumpASM ================================================ FILE: Zelig/Zelig/CompileTime/CodeGenerator/FrontEnd/Test/LLVM_test.FrontEndConfig ================================================ ### ### Location of the Zelig assemblies. ### -HostAssemblyDir %DEPOTROOT%\ZeligBuild\Host\bin\%flavor% -DeviceAssemblyDir %DEPOTROOT%\ZeligBuild\Target\bin\%flavor% ###-CompilationSetup Microsoft.Zelig.Configuration.Environment.VoxSoloFormFactorCompilationSetup ###-CompilationSetup Microsoft.Zelig.Configuration.Environment.NohauLPC3180CompilationSetup -CompilationSetup Microsoft.Zelig.Configuration.Environment.iMote2CompilationSetup ### ### We need to include this assembly to get the right drivers. ### ###-Reference Microsoft.VoxSoloFormFactor ###-Reference Microsoft.NohauLPC3180 ###-Reference Microsoft.iMote2 ###-ImportDirectory %ZELIGROOT%\ZeligInterop\Sample\FileSystemTest\LIB\ ###-ImportDirectory %ZELIGROOT%\..\client_v4_2_dev\tools\ads_v4_0\Lib\armlib\ ###-ImportDirectory %ZELIGROOT%\..\client_v4_2_dev\tools\ads_v4_0\Lib\cpplib\ ### ### The program to compile. ### %DEPOTROOT%\ZeligBuild\Target\bin\%flavor%\TestPayload__CLR1_1__VanillaSingleClass.exe ###%ZELIGROOT%\prototypes\CS\DistanceMeasurement\bin\Debug\DistanceMeasurement.dll ### ### Where to put the results. ### -OutputName Whetstone_perf_test -OutputDir %ZELIGROOT%\UnitTestResults ###-DumpIRpre ###-DumpIR ###-DumpIL -DumpLLVMIR ###-DumpCFG #-DumpASM ================================================ FILE: Zelig/Zelig/CompileTime/CodeGenerator/FrontEnd/Test/Whetstone_perf_test.FrontEndConfig ================================================ ### ### Location of the Zelig assemblies. ### -HostAssemblyDir %DEPOTROOT%\ZeligBuild\Host\bin\%flavor% -DeviceAssemblyDir %DEPOTROOT%\ZeligBuild\Target\bin\%flavor% ###-CompilationSetup Microsoft.Zelig.Configuration.Environment.VoxSoloFormFactorCompilationSetup ###-CompilationSetup Microsoft.Zelig.Configuration.Environment.NohauLPC3180CompilationSetup -CompilationSetup Microsoft.Zelig.Configuration.Environment.iMote2CompilationSetup ### ### We need to include this assembly to get the right drivers. ### ###-Reference Microsoft.VoxSoloFormFactor ###-Reference Microsoft.NohauLPC3180 -Reference Microsoft.iMote2 ###-ImportDirectory %DEPOTROOT%\ZeligInterop\Sample\FileSystemTest\LIB\ ###-ImportDirectory %DEPOTROOT%\..\client_v4_2_dev\tools\ads_v4_0\Lib\armlib\ ###-ImportDirectory %DEPOTROOT%\..\client_v4_2_dev\tools\ads_v4_0\Lib\cpplib\ ### ### The program to compile. ### %DEPOTROOT%\ZeligBuild\Target\bin\%flavor%\WhetstoneTest.exe ### ### Where to put the results. ### -OutputName Whetstone_perf_test -OutputDir %DEPOTROOT%\ZeligUnitTestResults -DumpIR -DumpIL -DumpASM ================================================ FILE: Zelig/Zelig/CompileTime/CodeGenerator/FrontEnd/Test/crypto_perf_test.FrontEndConfig ================================================ ### ### Location of the Zelig assemblies. ### -HostAssemblyDir %DEPOTROOT%\ZeligBuild\Host\bin\%flavor% -DeviceAssemblyDir %DEPOTROOT%\ZeligBuild\Target\bin\%flavor% ###-CompilationSetup Microsoft.Zelig.Configuration.Environment.VoxSoloFormFactorCompilationSetup -CompilationSetup Microsoft.Zelig.Configuration.Environment.NohauLPC3180CompilationSetup ###-CompilationSetup Microsoft.Zelig.Configuration.Environment.iMote2CompilationSetup ### ### We need to include this assembly to get the right drivers. ### ###-Reference Microsoft.VoxSoloFormFactor ###-Reference Microsoft.NohauLPC3180 -Reference Microsoft.iMote2 ###-ImportDirectory %DEPOTROOT%\ZeligInterop\Sample\FileSystemTest\LIB\ ###-ImportDirectory %DEPOTROOT%\..\client_v4_2_dev\tools\ads_v4_0\Lib\armlib\ ###-ImportDirectory %DEPOTROOT%\..\client_v4_2_dev\tools\ads_v4_0\Lib\cpplib\ ### ### The program to compile. ### %DEPOTROOT%\ZeligBuild\Target\bin\%flavor%\CryptoTest.exe ### ### Where to put the results. ### -OutputName Crypto_perf_test -OutputDir %DEPOTROOT%\ZeligUnitTestResults -DumpIR -DumpASM ================================================ FILE: Zelig/Zelig/CompileTime/CodeGenerator/FrontEnd/Test/mbed_gpio_test.FrontEndConfig ================================================ ### ### The program to compile. ### ..\..\..\..\ZeligBuild\Target\bin\Debug\Microsoft.Zelig.Test.GpioTest.exe ### ### Where to put the results. ### -OutputName Microsoft.Zelig.Test.GpioTest -OutputDir ..\..\..\..\LLVM2IR_results\mbed\test ================================================ FILE: Zelig/Zelig/CompileTime/CodeGenerator/FrontEnd/Test/mbed_serialport_test.FrontEndConfig ================================================ ### ### The program to compile. ### ..\..\..\..\ZeligBuild\Target\bin\Debug\Microsoft.Zelig.Test.SerialPortTest.exe ### ### Where to put the results. ### -OutputName Microsoft.Zelig.Test.SerialPortTest -OutputDir ..\..\..\..\LLVM2IR_results\mbed\test ================================================ FILE: Zelig/Zelig/CompileTime/CodeGenerator/FrontEnd/Test/test.FrontEndConfig ================================================ ### ### ### #-MaxProcs 1 -cfg %DEPOTROOT%\Zelig\CompileTime\CodeGenerator\FrontEnd\mscorlib_unittest_FF.FrontEndConfig #-cfg %DEPOTROOT%\Zelig\CompileTime\CodeGenerator\FrontEnd\mscorlib_unittest_NXP.FrontEndConfig #-cfg %DEPOTROOT%\Zelig\CompileTime\CodeGenerator\FrontEnd\mscorlib_unittest_PXA.FrontEndConfig #-cfg %DEPOTROOT%\Zelig\CompileTime\CodeGenerator\FrontEnd\tester_FF.FrontEndConfig #-cfg %DEPOTROOT%\Zelig\CompileTime\CodeGenerator\FrontEnd\tester_NXP.FrontEndConfig #-cfg %DEPOTROOT%\Zelig\CompileTime\CodeGenerator\FrontEnd\tester_PXA.FrontEndConfig #-DumpIL #-DumpIRpre #-cfg %DEPOTROOT%\Zelig\CompileTime\CodeGenerator\FrontEnd\VoxSoloFormFactorLoader.FrontEndConfig #-cfg %DEPOTROOT%\Zelig\CompileTime\CodeGenerator\FrontEnd\NohauLPC3180Loader.FrontEndConfig #-cfg %DEPOTROOT%\Zelig\CompileTime\CodeGenerator\FrontEnd\iMote2Loader.FrontEndConfig #-cfg %DEPOTROOT%\Zelig\CompileTime\CodeGenerator\FrontEnd\VoxSoloTest.FrontEndConfig #-cfg %DEPOTROOT%\Zelig\CompileTime\CodeGenerator\FrontEnd\VoxSolo_UnitTest_FF.FrontEndConfig #-cfg %DEPOTROOT%\Zelig\CompileTime\CodeGenerator\FrontEnd\VoxSolo_Bootstrap_FF.FrontEndConfig #-cfg %DEPOTROOT%\Zelig\CompileTime\CodeGenerator\FrontEnd\VoxSolo_Tester_FF.FrontEndConfig #-cfg %DEPOTROOT%\Zelig\CompileTime\CodeGenerator\FrontEnd\VoxSolo_UnitTest_NXP.FrontEndConfig #-cfg %DEPOTROOT%\Zelig\CompileTime\CodeGenerator\FrontEnd\VoxSolo_Bootstrap_NXP.FrontEndConfig #-cfg %DEPOTROOT%\Zelig\CompileTime\CodeGenerator\FrontEnd\VoxSolo_Tester_NXP.FrontEndConfig #-embedSourceCode %DEPOTROOT%\ZeligBuild\Target\bin\Debug\mscorlib_UnitTest.pdb #-embedSourceCodeAll %DEPOTROOT%\ZeligBuild\Target\bin\Debug #-cfg %DEPOTROOT%\Zelig\Test\CCR\ccr_FF.FrontEndConfig #-cfg %DEPOTROOT%\Zelig\Test\CCR\ccr_NXP.FrontEndConfig #-cfg %DEPOTROOT%\Zelig\Test\CCR\ccr_PXA.FrontEndConfig ################################## # Tests for deployment # #-embedSourceCodeAll %ZELIGROOT%\BinaryDrop\Host #-embedSourceCodeAll %ZELIGROOT%\BinaryDrop\Target #-cfg %ZELIGROOT%\ConfigurationFiles\sample.FrontEndConfig #-cfg %ZELIGROOT%\ConfigurationFiles\ccr.FrontEndConfig -dumpRaw FLASH 0x10000000 0x10800000 -dumpRaw RAM 0x08000000 0x08010000 ================================================ FILE: Zelig/Zelig/CompileTime/CodeGenerator/FrontEnd/mbed_common.FrontEndConfig ================================================ ### ### Location of the Zelig assemblies. ### -HostAssemblyDir ..\..\..\..\ZeligBuild\Host\bin\Debug -DeviceAssemblyDir ..\..\..\..\ZeligBuild\Target\bin\Debug ### ### Add compilation phases, in order ### #-CompilationPhaseDisabled ReduceNumberOfTemporaries #-CompilationPhaseDisabled TransformFinallyBlocksIntoTryBlocks #-CompilationPhaseDisabled ApplyClassExtensions #-CompilationPhaseDisabled PrepareImplementationOfInternalMethods #-CompilationPhaseDisabled CrossReferenceTypeSystem #-CompilationPhaseDisabled ApplyConfigurationSettings -CompilationPhaseDisabled ResourceManagerOptimizations #-CompilationPhaseDisabled HighLevelTransformations #-CompilationPhaseDisabled PropagateCompilationConstraints #-CompilationPhaseDisabled ComputeCallsClosure #-CompilationPhaseDisabled EstimateTypeSystemReduction #-CompilationPhaseDisabled CompleteImplementationOfInternalMethods #-CompilationPhaseDisabled ReduceTypeSystem -CompilationPhaseDisabled PrepareExternalMethods #-CompilationPhaseDisabled DetectNonImplementedInternalCalls #-CompilationPhaseDisabled OrderStaticConstructors #-CompilationPhaseDisabled LayoutTypes #-CompilationPhaseDisabled HighLevelToMidLevelConversion #-CompilationPhaseDisabled FromImplicitToExplicitExceptions #-CompilationPhaseDisabled ReferenceCountingGarbageCollection -CompilationPhaseDisabled MidLevelToLowLevelConversion -CompilationPhaseDisabled ConvertUnsupportedOperatorsToMethodCalls -CompilationPhaseDisabled ExpandAggregateTypes -CompilationPhaseDisabled SplitComplexOperators -CompilationPhaseDisabled FuseOperators #-CompilationPhaseDisabled Optimizations -CompilationPhaseDisabled ConvertToSSA -CompilationPhaseDisabled PrepareForRegisterAllocation -CompilationPhaseDisabled CollectRegisterAllocationConstraints -CompilationPhaseDisabled AllocateRegisters #-CompilationPhaseDisabled GenerateImage #-CompilationPhaseDisabled Done -DumpIR #-DumpIRpre #-DumpIRpost #-DumpIRXML -DumpLLVMIR #-ReloadState -DumpLLVMIR_TextRepresentation -MaxProcs 8 -NoSDK -GenerateObj ================================================ FILE: Zelig/Zelig/CompileTime/CodeGenerator/FrontEnd/mbed_common_K64F.FrontEndConfig ================================================ ### ### We need to include this assembly to get the right drivers. ### -Reference Microsoft.CortexM4OnMBED -Reference Microsoft.CortexM4OnCMSISCore -Reference Microsoft.DeviceModels.ModelForCortexM4 -Reference K64F -CompilationSetupPath ..\..\..\..\ZeligBuild\Host\bin\Debug\Microsoft.Llilum.BoardConfigurations.K64F.dll -CompilationSetup Microsoft.Llilum.BoardConfigurations.K64FMBEDCompilationSetup -GenerateObj ================================================ FILE: Zelig/Zelig/CompileTime/CodeGenerator/FrontEnd/mbed_common_LPC1768.FrontEndConfig ================================================ ### ### We need to include this assembly to get the right drivers. ### -Reference Microsoft.CortexM3OnMBED -Reference Microsoft.CortexM3OnCMSISCore -Reference Microsoft.DeviceModels.ModelForCortexM3 -Reference LPC1768 -CompilationSetupPath ..\..\..\..\ZeligBuild\Host\bin\Debug\Microsoft.Llilum.BoardConfigurations.LPC1768.dll -CompilationSetup Microsoft.Llilum.BoardConfigurations.LPC1768MBEDCompilationSetup -GenerateObj ================================================ FILE: Zelig/Zelig/CompileTime/CodeGenerator/FrontEnd/mbed_simple_HTTP_K64F.FrontEndConfig ================================================ ### ### Location of the Zelig assemblies. ### -HostAssemblyDir ..\..\..\..\ZeligBuild\Host\bin\Debug -DeviceAssemblyDir ..\..\..\..\ZeligBuild\Target\bin\Debug -CompilationSetupPath ..\..\..\..\ZeligBuild\Host\bin\Debug\Microsoft.Llilum.BoardConfigurations.K64F.dll -CompilationSetup Microsoft.Llilum.BoardConfigurations.K64FMBEDCompilationSetup ### ### We need to include this assembly to get the right drivers. ### -Reference Microsoft.CortexM4OnMBED -Reference Microsoft.CortexM4OnCMSISCore -Reference Microsoft.DeviceModels.ModelForCortexM4 -Reference K64F -Reference Microsoft.Zelig.LlilumCMSIS-RTOS ### ### Add compilation phases, in order ### #-CompilationPhaseDisabled ReduceNumberOfTemporaries #-CompilationPhaseDisabled TransformFinallyBlocksIntoTryBlocks #-CompilationPhaseDisabled ApplyClassExtensions #-CompilationPhaseDisabled PrepareImplementationOfInternalMethods #-CompilationPhaseDisabled CrossReferenceTypeSystem #-CompilationPhaseDisabled ApplyConfigurationSettings -CompilationPhaseDisabled ResourceManagerOptimizations #-CompilationPhaseDisabled HighLevelTransformations #-CompilationPhaseDisabled PropagateCompilationConstraints #-CompilationPhaseDisabled ComputeCallsClosure #-CompilationPhaseDisabled EstimateTypeSystemReduction #-CompilationPhaseDisabled CompleteImplementationOfInternalMethods #-CompilationPhaseDisabled ReduceTypeSystem -CompilationPhaseDisabled PrepareExternalMethods #-CompilationPhaseDisabled DetectNonImplementedInternalCalls #-CompilationPhaseDisabled OrderStaticConstructors #-CompilationPhaseDisabled LayoutTypes #-CompilationPhaseDisabled HighLevelToMidLevelConversion #-CompilationPhaseDisabled FromImplicitToExplicitExceptions #-CompilationPhaseDisabled ReferenceCountingGarbageCollection -CompilationPhaseDisabled MidLevelToLowLevelConversion -CompilationPhaseDisabled ConvertUnsupportedOperatorsToMethodCalls -CompilationPhaseDisabled ExpandAggregateTypes -CompilationPhaseDisabled SplitComplexOperators -CompilationPhaseDisabled FuseOperators #-CompilationPhaseDisabled Optimizations -CompilationPhaseDisabled ConvertToSSA -CompilationPhaseDisabled PrepareForRegisterAllocation -CompilationPhaseDisabled CollectRegisterAllocationConstraints -CompilationPhaseDisabled AllocateRegisters #-CompilationPhaseDisabled GenerateImage #-CompilationPhaseDisabled Done ### ### The program to compile. ### ..\..\..\..\ZeligBuild\Target\bin\Debug\Microsoft.Zelig.Test.mbed.Simple.HTTP.exe ### ### Where to put the results. ### -OutputName Microsoft.Zelig.Test.mbed.Simple -OutputDir ..\..\..\..\LLVM2IR_results\mbed\simple ### ### Dumps and diagnostics ### #-DumpIRBeforePhase All #-DumpIR #-DumpIRpre #-DumpIRpost #-DumpIRXML #-DumpFlattenedCallGraph -DumpLLVMIR #-ReloadState #-DumpLLVMIR_TextRepresentation -MaxProcs 8 -NoSDK -GenerateObj # examples of overriding opt.exe and llc arguments # the examples here are the same as the defaults but can be modified to suit a variety of test # scenarios and experimentations #-LlvmOptArgs "-verify-debug-info -verify-dom-info -verify-each -verify-loop-info -verify-regalloc -verify-region-info -march=thumb -mcpu=cortex-m3 -aa-eval -indvars -gvn -globaldce -adce -dce -tailcallopt -scalarrepl -mem2reg -ipconstprop -deadargelim -sccp -dce -ipsccp -dce -constmerge -scev-aa -targetlibinfo -irce -dse -dce -argpromotion -mem2reg -adce -mem2reg -globaldce -die -dce -dse" #-LlvmLlcArgs "-O2 -code-model=small -data-sections -relocation-model=pic -march=thumb -mcpu=cortex-m3 -filetype=obj -mtriple=thumbv7m-none-eabi" # While the compiler is pretty good at figuring out where the LLVM tools are from # current Environment variables or registry entires you can manually specify the # path to find the LLVM binaries. # note: Environment variabes (i.e %MY_VAR%) are supported and expanded as with all # options in the FrontendConfig files so you can specify a custom variable if needed #-LlvmBinPath \\netmfbld02\LLVM\3.7.0\build\Win32\Release\bin ================================================ FILE: Zelig/Zelig/CompileTime/CodeGenerator/FrontEnd/mbed_simple_K64F.FrontEndConfig ================================================ ### ### Location of the Zelig assemblies. ### -HostAssemblyDir ..\..\..\..\ZeligBuild\Host\bin\Debug -DeviceAssemblyDir ..\..\..\..\ZeligBuild\Target\bin\Debug -Architecture cortex-m4 -CompilationSetupPath ..\..\..\..\ZeligBuild\Host\bin\Debug\Microsoft.Llilum.BoardConfigurations.K64F.dll -CompilationSetup Microsoft.Llilum.BoardConfigurations.K64FMBEDCompilationSetup ### ### We need to include this assembly to get the right drivers. ### -Reference Microsoft.CortexM4OnMBED -Reference Microsoft.CortexM4OnCMSISCore -Reference Microsoft.DeviceModels.ModelForCortexM4 -Reference K64F -Reference Microsoft.Zelig.LlilumCMSIS-RTOS ### ### Add compilation phases, in order ### #-CompilationPhaseDisabled ReduceNumberOfTemporaries #-CompilationPhaseDisabled TransformFinallyBlocksIntoTryBlocks #-CompilationPhaseDisabled ApplyClassExtensions #-CompilationPhaseDisabled PrepareImplementationOfInternalMethods #-CompilationPhaseDisabled CrossReferenceTypeSystem #-CompilationPhaseDisabled ApplyConfigurationSettings -CompilationPhaseDisabled ResourceManagerOptimizations #-CompilationPhaseDisabled HighLevelTransformations #-CompilationPhaseDisabled PropagateCompilationConstraints #-CompilationPhaseDisabled ComputeCallsClosure #-CompilationPhaseDisabled EstimateTypeSystemReduction #-CompilationPhaseDisabled CompleteImplementationOfInternalMethods #-CompilationPhaseDisabled ReduceTypeSystem -CompilationPhaseDisabled PrepareExternalMethods #-CompilationPhaseDisabled DetectNonImplementedInternalCalls #-CompilationPhaseDisabled OrderStaticConstructors #-CompilationPhaseDisabled LayoutTypes #-CompilationPhaseDisabled HighLevelToMidLevelConversion #-CompilationPhaseDisabled FromImplicitToExplicitExceptions #-CompilationPhaseDisabled ReferenceCountingGarbageCollection -CompilationPhaseDisabled MidLevelToLowLevelConversion -CompilationPhaseDisabled ConvertUnsupportedOperatorsToMethodCalls -CompilationPhaseDisabled ExpandAggregateTypes -CompilationPhaseDisabled SplitComplexOperators -CompilationPhaseDisabled FuseOperators #-CompilationPhaseDisabled Optimizations -CompilationPhaseDisabled ConvertToSSA -CompilationPhaseDisabled PrepareForRegisterAllocation -CompilationPhaseDisabled CollectRegisterAllocationConstraints -CompilationPhaseDisabled AllocateRegisters #-CompilationPhaseDisabled GenerateImage #-CompilationPhaseDisabled Done -CompilationOption System.String TimerPool UnboundedAsynchTimerPool ### ### The program to compile. ### ..\..\..\..\ZeligBuild\Target\bin\Debug\Microsoft.Zelig.Test.mbed.Simple.exe ### ### Where to put the results. ### -OutputName Microsoft.Zelig.Test.mbed.Simple -OutputDir ..\..\..\..\LLVM2IR_results\mbed\simple ### ### Dumps and diagnostics ### #-DumpIRBeforePhase All #-DumpIR #-DumpIRpre #-DumpIRpost #-DumpIRXML #-DumpFlattenedCallGraph -DumpLLVMIR #-ReloadState #-DumpLLVMIR_TextRepresentation -MaxProcs 8 -NoSDK -GenerateObj # examples of overriding opt.exe and llc arguments # the examples here are the same as the defaults but can be modified to suit a variety of test # scenarios and experimentations #-LlvmOptArgs "-verify-debug-info -verify-dom-info -verify-each -verify-loop-info -verify-regalloc -verify-region-info -march=thumb -mcpu=cortex-m3 -aa-eval -indvars -gvn -globaldce -adce -dce -tailcallopt -scalarrepl -mem2reg -ipconstprop -deadargelim -sccp -dce -ipsccp -dce -constmerge -scev-aa -targetlibinfo -irce -dse -dce -argpromotion -mem2reg -adce -mem2reg -globaldce -die -dce -dse" #-LlvmLlcArgs "-O2 -code-model=small -data-sections -relocation-model=pic -march=thumb -mcpu=cortex-m3 -filetype=obj -mtriple=thumbv7m-none-eabi" # While the compiler is pretty good at figuring out where the LLVM tools are from # current Environment variables or registry entires you can manually specify the # path to find the LLVM binaries. # note: Environment variabes (i.e %MY_VAR%) are supported and expanded as with all # options in the FrontendConfig files so you can specify a custom variable if needed #-LlvmBinPath c:\src\llvm\llvm-3.7.0.src\build\x64\Release\bin\ ================================================ FILE: Zelig/Zelig/CompileTime/CodeGenerator/FrontEnd/mbed_simple_LPC1768.FrontEndConfig ================================================ ### ### Location of the Zelig assemblies. ### -HostAssemblyDir ..\..\..\..\ZeligBuild\Host\bin\Debug -DeviceAssemblyDir ..\..\..\..\ZeligBuild\Target\bin\Debug -Architecture cortex-m3 -CompilationSetupPath ..\..\..\..\ZeligBuild\Host\bin\Debug\Microsoft.Llilum.BoardConfigurations.LPC1768.dll -CompilationSetup Microsoft.Llilum.BoardConfigurations.LPC1768MBEDCompilationSetup ### ### We need to include this assembly to get the right drivers. ### -Reference Microsoft.CortexM3OnMBED -Reference Microsoft.CortexM3OnCMSISCore -Reference Microsoft.DeviceModels.ModelForCortexM3 -Reference LPC1768 ### ### Add compilation phases, in order ### #-CompilationPhaseDisabled ReduceNumberOfTemporaries #-CompilationPhaseDisabled TransformFinallyBlocksIntoTryBlocks #-CompilationPhaseDisabled ApplyClassExtensions #-CompilationPhaseDisabled PrepareImplementationOfInternalMethods #-CompilationPhaseDisabled CrossReferenceTypeSystem #-CompilationPhaseDisabled ApplyConfigurationSettings -CompilationPhaseDisabled ResourceManagerOptimizations #-CompilationPhaseDisabled HighLevelTransformations #-CompilationPhaseDisabled PropagateCompilationConstraints #-CompilationPhaseDisabled ComputeCallsClosure #-CompilationPhaseDisabled EstimateTypeSystemReduction #-CompilationPhaseDisabled CompleteImplementationOfInternalMethods #-CompilationPhaseDisabled ReduceTypeSystem -CompilationPhaseDisabled PrepareExternalMethods #-CompilationPhaseDisabled DetectNonImplementedInternalCalls #-CompilationPhaseDisabled OrderStaticConstructors #-CompilationPhaseDisabled LayoutTypes #-CompilationPhaseDisabled HighLevelToMidLevelConversion #-CompilationPhaseDisabled FromImplicitToExplicitExceptions #-CompilationPhaseDisabled ReferenceCountingGarbageCollection -CompilationPhaseDisabled MidLevelToLowLevelConversion -CompilationPhaseDisabled ConvertUnsupportedOperatorsToMethodCalls -CompilationPhaseDisabled ExpandAggregateTypes -CompilationPhaseDisabled SplitComplexOperators -CompilationPhaseDisabled FuseOperators #-CompilationPhaseDisabled Optimizations -CompilationPhaseDisabled ConvertToSSA -CompilationPhaseDisabled PrepareForRegisterAllocation -CompilationPhaseDisabled CollectRegisterAllocationConstraints -CompilationPhaseDisabled AllocateRegisters #-CompilationPhaseDisabled GenerateImage #-CompilationPhaseDisabled Done -CompilationOption System.String GarbageCollectionManager ConservativeMarkAndSweepCollector -CompilationOption System.String TimerPool SyncDispatcherTimerPool ### ### The program to compile. ### ..\..\..\..\ZeligBuild\Target\bin\Debug\Microsoft.Zelig.Test.mbed.Simple.exe ### ### Where to put the results. ### -OutputName Microsoft.Zelig.Test.mbed.Simple -OutputDir ..\..\..\..\LLVM2IR_results\mbed\simple ### ### Dumps and diagnostics ### #-DumpIRBeforePhase ReduceNumberOfTemporaries TransformFinallyBlocksIntoTryBlocks ApplyClassExtensions #-DumpIRBeforePhase All -DumpIR #-DumpIRpre #-DumpIRpost #-DumpIRXML #-DumpFlattenedCallGraph -DumpLLVMIR #-ReloadState -DumpLLVMIR_TextRepresentation -MaxProcs 8 -NoSDK ### ### LLVM CodeGeneration ### -GenerateObj # examples of overriding opt.exe and llc arguments # the examples here are the same as the defaults but can be modified to suit a variety of test # scenarios and experimentations #-LlvmOptArgs "-verify-debug-info -verify-dom-info -verify-each -verify-loop-info -verify-regalloc -verify-region-info -march=thumb -mcpu=cortex-m3 -aa-eval -indvars -gvn -globaldce -adce -dce -tailcallopt -scalarrepl -mem2reg -ipconstprop -deadargelim -sccp -dce -ipsccp -dce -constmerge -scev-aa -targetlibinfo -irce -dse -dce -argpromotion -mem2reg -adce -mem2reg -globaldce -die -dce -dse" #-LlvmLlcArgs "-O2 -code-model=small -data-sections -relocation-model=pic -march=thumb -mcpu=cortex-m3 -filetype=obj -mtriple=thumbv7m-none-eabi" # While the compiler is pretty good at figuring out where the LLVM tools are from # current Environment variables or registry entires you can manually specify the # path to find the LLVM binaries. # note: Environment variabes (i.e %MY_VAR%) are supported and expanded as with all # options in the FrontendConfig files so you can specify a custom variable if needed #-LlvmBinPath \\netmfbld02\LLVM\3.7.0\build\Win32\Release\bin ================================================ FILE: Zelig/Zelig/CompileTime/CodeGenerator/FrontEnd/mbed_simple_LPC1768_Tester.FrontEndConfig ================================================ ### ### Location of the Zelig assemblies. ### -HostAssemblyDir ..\..\..\..\ZeligBuild\Host\bin\Debug -DeviceAssemblyDir ..\..\..\..\ZeligBuild\Target\bin\Debug -Architecture cortex-m3 -CompilationSetupPath ..\..\..\..\ZeligBuild\Host\bin\Debug\Microsoft.Llilum.BoardConfigurations.LPC1768.dll -CompilationSetup Microsoft.Llilum.BoardConfigurations.LPC1768MBEDCompilationSetup ### ### We need to include this assembly to get the right drivers. ### -Reference Microsoft.CortexM3OnMBED -Reference Microsoft.CortexM3OnCMSISCore -Reference Microsoft.DeviceModels.ModelForCortexM3 -Reference LPC1768 ### ### Add compilation phases, in order ### #-CompilationPhaseDisabled ReduceNumberOfTemporaries #-CompilationPhaseDisabled TransformFinallyBlocksIntoTryBlocks #-CompilationPhaseDisabled ApplyClassExtensions #-CompilationPhaseDisabled PrepareImplementationOfInternalMethods #-CompilationPhaseDisabled CrossReferenceTypeSystem #-CompilationPhaseDisabled ApplyConfigurationSettings -CompilationPhaseDisabled ResourceManagerOptimizations #-CompilationPhaseDisabled HighLevelTransformations #-CompilationPhaseDisabled PropagateCompilationConstraints #-CompilationPhaseDisabled ComputeCallsClosure #-CompilationPhaseDisabled EstimateTypeSystemReduction #-CompilationPhaseDisabled CompleteImplementationOfInternalMethods #-CompilationPhaseDisabled ReduceTypeSystem -CompilationPhaseDisabled PrepareExternalMethods #-CompilationPhaseDisabled DetectNonImplementedInternalCalls #-CompilationPhaseDisabled OrderStaticConstructors #-CompilationPhaseDisabled LayoutTypes #-CompilationPhaseDisabled HighLevelToMidLevelConversion #-CompilationPhaseDisabled FromImplicitToExplicitExceptions #-CompilationPhaseDisabled ReferenceCountingGarbageCollection -CompilationPhaseDisabled MidLevelToLowLevelConversion -CompilationPhaseDisabled ConvertUnsupportedOperatorsToMethodCalls -CompilationPhaseDisabled ExpandAggregateTypes -CompilationPhaseDisabled SplitComplexOperators -CompilationPhaseDisabled FuseOperators #-CompilationPhaseDisabled Optimizations -CompilationPhaseDisabled ConvertToSSA -CompilationPhaseDisabled PrepareForRegisterAllocation -CompilationPhaseDisabled CollectRegisterAllocationConstraints -CompilationPhaseDisabled AllocateRegisters #-CompilationPhaseDisabled GenerateImage #-CompilationPhaseDisabled Done -CompilationOption System.String GarbageCollectionManager ConservativeMarkAndSweepCollector ### ### The program to compile. ### ..\..\..\..\ZeligBuild\Target\bin\Debug\Microsoft.Zelig.Test.TestRunner.exe ### ### Where to put the results. ### -OutputName Microsoft.Zelig.Test.mbed.Simple -OutputDir ..\..\..\..\LLVM2IR_results\mbed\simple ### ### Dumps and diagnostics ### #-DumpIRBeforePhase All -DumpIR #-DumpIRpre #-DumpIRpost #-DumpIRXML #-DumpFlattenedCallGraph -DumpLLVMIR #-ReloadState -DumpLLVMIR_TextRepresentation -MaxProcs 8 -NoSDK -GenerateObj # examples of overriding opt.exe and llc arguments # the examples here are the same as the defaults but can be modified to suit a variety of test # scenarios and experimentations #-LlvmOptArgs "-verify-debug-info -verify-dom-info -verify-each -verify-loop-info -verify-regalloc -verify-region-info -march=thumb -mcpu=cortex-m3 -aa-eval -indvars -gvn -globaldce -adce -dce -tailcallopt -scalarrepl -mem2reg -ipconstprop -deadargelim -sccp -dce -ipsccp -dce -constmerge -scev-aa -targetlibinfo -irce -dse -dce -argpromotion -mem2reg -adce -mem2reg -globaldce -die -dce -dse" #-LlvmLlcArgs "-O2 -code-model=small -data-sections -relocation-model=pic -march=thumb -mcpu=cortex-m3 -filetype=obj -mtriple=thumbv7m-none-eabi" # While the compiler is pretty good at figuring out where the LLVM tools are from # current Environment variables or registry entires you can manually specify the # path to find the LLVM binaries. # note: Environment variabes (i.e %MY_VAR%) are supported and expanded as with all # options in the FrontendConfig files so you can specify a custom variable if needed #-LlvmBinPath \\netmfbld02\LLVM\3.7.0\build\Win32\Release\bin ================================================ FILE: Zelig/Zelig/CompileTime/CodeGenerator/FrontEnd/mbed_simple_NETMF_LPC1768.FrontEndConfig ================================================ ### ### Location of the Zelig assemblies. ### -HostAssemblyDir ..\..\..\..\ZeligBuild\Host\bin\Debug -DeviceAssemblyDir ..\..\..\..\ZeligBuild\Target\bin\Debug -Architecture cortex-m3 -CompilationSetupPath ..\..\..\..\ZeligBuild\Host\bin\Debug\Microsoft.Llilum.BoardConfigurations.LPC1768.dll -CompilationSetup Microsoft.Llilum.BoardConfigurations.LPC1768MBEDCompilationSetup ### ### We need to include this assembly to get the right drivers. ### -Reference Microsoft.CortexM3OnMBED -Reference Microsoft.CortexM3OnCMSISCore -Reference Microsoft.DeviceModels.ModelForCortexM3 -Reference LPC1768 ### ### Add compilation phases, in order ### #-CompilationPhaseDisabled ReduceNumberOfTemporaries #-CompilationPhaseDisabled TransformFinallyBlocksIntoTryBlocks #-CompilationPhaseDisabled ApplyClassExtensions #-CompilationPhaseDisabled PrepareImplementationOfInternalMethods #-CompilationPhaseDisabled CrossReferenceTypeSystem #-CompilationPhaseDisabled ApplyConfigurationSettings -CompilationPhaseDisabled ResourceManagerOptimizations #-CompilationPhaseDisabled HighLevelTransformations #-CompilationPhaseDisabled PropagateCompilationConstraints #-CompilationPhaseDisabled ComputeCallsClosure #-CompilationPhaseDisabled EstimateTypeSystemReduction #-CompilationPhaseDisabled CompleteImplementationOfInternalMethods #-CompilationPhaseDisabled ReduceTypeSystem -CompilationPhaseDisabled PrepareExternalMethods #-CompilationPhaseDisabled DetectNonImplementedInternalCalls #-CompilationPhaseDisabled OrderStaticConstructors #-CompilationPhaseDisabled LayoutTypes #-CompilationPhaseDisabled HighLevelToMidLevelConversion #-CompilationPhaseDisabled FromImplicitToExplicitExceptions #-CompilationPhaseDisabled ReferenceCountingGarbageCollection -CompilationPhaseDisabled MidLevelToLowLevelConversion -CompilationPhaseDisabled ConvertUnsupportedOperatorsToMethodCalls -CompilationPhaseDisabled ExpandAggregateTypes -CompilationPhaseDisabled SplitComplexOperators -CompilationPhaseDisabled FuseOperators #-CompilationPhaseDisabled Optimizations -CompilationPhaseDisabled ConvertToSSA -CompilationPhaseDisabled PrepareForRegisterAllocation -CompilationPhaseDisabled CollectRegisterAllocationConstraints -CompilationPhaseDisabled AllocateRegisters #-CompilationPhaseDisabled GenerateImage #-CompilationPhaseDisabled Done -CompilationOption System.String GarbageCollectionManager ConservativeMarkAndSweepCollector ### ### The program to compile. ### ..\..\..\..\ZeligBuild\Target\bin\Debug\Microsoft.Zelig.Test.mbed.SimpleNetMF.exe ### ### Where to put the results. ### -OutputName Microsoft.Zelig.Test.mbed.Simple -OutputDir ..\..\..\..\LLVM2IR_results\mbed\simple ### ### Dumps and diagnostics ### #-DumpIRBeforePhase ReduceNumberOfTemporaries TransformFinallyBlocksIntoTryBlocks ApplyClassExtensions #-DumpIRBeforePhase All -DumpIR #-DumpIRpre #-DumpIRpost #-DumpIRXML #-DumpFlattenedCallGraph -DumpLLVMIR #-ReloadState -DumpLLVMIR_TextRepresentation -MaxProcs 8 -NoSDK ### ### LLVM CodeGeneration ### -GenerateObj # examples of overriding opt.exe and llc arguments # the examples here are the same as the defaults but can be modified to suit a variety of test # scenarios and experimentations #-LlvmOptArgs "-verify-debug-info -verify-dom-info -verify-each -verify-loop-info -verify-regalloc -verify-region-info -march=thumb -mcpu=cortex-m3 -aa-eval -indvars -gvn -globaldce -adce -dce -tailcallopt -scalarrepl -mem2reg -ipconstprop -deadargelim -sccp -dce -ipsccp -dce -constmerge -scev-aa -targetlibinfo -irce -dse -dce -argpromotion -mem2reg -adce -mem2reg -globaldce -die -dce -dse" #-LlvmLlcArgs "-O2 -code-model=small -data-sections -relocation-model=pic -march=thumb -mcpu=cortex-m3 -filetype=obj -mtriple=thumbv7m-none-eabi" # While the compiler is pretty good at figuring out where the LLVM tools are from # current Environment variables or registry entires you can manually specify the # path to find the LLVM binaries. # note: Environment variabes (i.e %MY_VAR%) are supported and expanded as with all # options in the FrontendConfig files so you can specify a custom variable if needed #-LlvmBinPath \\netmfbld02\LLVM\3.7.0\build\Win32\Release\bin ================================================ FILE: Zelig/Zelig/CompileTime/CodeGenerator/FrontEnd/mbed_simple_NET_K64F.FrontEndConfig ================================================ ### ### Location of the Zelig assemblies. ### -HostAssemblyDir ..\..\..\..\ZeligBuild\Host\bin\Debug -DeviceAssemblyDir ..\..\..\..\ZeligBuild\Target\bin\Debug -Architecture cortex-m4 -CompilationSetupPath ..\..\..\..\ZeligBuild\Host\bin\Debug\Microsoft.Llilum.BoardConfigurations.K64F.dll -CompilationSetup Microsoft.Llilum.BoardConfigurations.K64FMBEDCompilationSetup ### ### We need to include this assembly to get the right drivers. ### -Reference Microsoft.CortexM4OnMBED -Reference Microsoft.CortexM4OnCMSISCore -Reference Microsoft.DeviceModels.ModelForCortexM4 -Reference K64F -Reference Microsoft.Zelig.LlilumCMSIS-RTOS ### ### Add compilation phases, in order ### #-CompilationPhaseDisabled ReduceNumberOfTemporaries #-CompilationPhaseDisabled TransformFinallyBlocksIntoTryBlocks #-CompilationPhaseDisabled ApplyClassExtensions #-CompilationPhaseDisabled PrepareImplementationOfInternalMethods #-CompilationPhaseDisabled CrossReferenceTypeSystem #-CompilationPhaseDisabled ApplyConfigurationSettings -CompilationPhaseDisabled ResourceManagerOptimizations #-CompilationPhaseDisabled HighLevelTransformations #-CompilationPhaseDisabled PropagateCompilationConstraints #-CompilationPhaseDisabled ComputeCallsClosure #-CompilationPhaseDisabled EstimateTypeSystemReduction #-CompilationPhaseDisabled CompleteImplementationOfInternalMethods #-CompilationPhaseDisabled ReduceTypeSystem -CompilationPhaseDisabled PrepareExternalMethods #-CompilationPhaseDisabled DetectNonImplementedInternalCalls #-CompilationPhaseDisabled OrderStaticConstructors #-CompilationPhaseDisabled LayoutTypes #-CompilationPhaseDisabled HighLevelToMidLevelConversion #-CompilationPhaseDisabled FromImplicitToExplicitExceptions #-CompilationPhaseDisabled ReferenceCountingGarbageCollection -CompilationPhaseDisabled MidLevelToLowLevelConversion -CompilationPhaseDisabled ConvertUnsupportedOperatorsToMethodCalls -CompilationPhaseDisabled ExpandAggregateTypes -CompilationPhaseDisabled SplitComplexOperators -CompilationPhaseDisabled FuseOperators #-CompilationPhaseDisabled Optimizations -CompilationPhaseDisabled ConvertToSSA -CompilationPhaseDisabled PrepareForRegisterAllocation -CompilationPhaseDisabled CollectRegisterAllocationConstraints -CompilationPhaseDisabled AllocateRegisters #-CompilationPhaseDisabled GenerateImage #-CompilationPhaseDisabled Done ### ### The program to compile. ### ..\..\..\..\ZeligBuild\Target\bin\Debug\Microsoft.Zelig.Test.mbed.Simple.NET.exe ### ### Where to put the results. ### -OutputName Microsoft.Zelig.Test.mbed.Simple -OutputDir ..\..\..\..\LLVM2IR_results\mbed\simple ### ### Dumps and diagnostics ### #-DumpIRBeforePhase All -DumpIR #-DumpIRpre #-DumpIRpost #-DumpIRXML #-DumpFlattenedCallGraph -DumpLLVMIR #-ReloadState #-DumpLLVMIR_TextRepresentation -MaxProcs 8 -NoSDK -GenerateObj # examples of overriding opt.exe and llc arguments # the examples here are the same as the defaults but can be modified to suit a variety of test # scenarios and experimentations #-LlvmOptArgs "-verify-debug-info -verify-dom-info -verify-each -verify-loop-info -verify-regalloc -verify-region-info -march=thumb -mcpu=cortex-m3 -aa-eval -indvars -gvn -globaldce -adce -dce -tailcallopt -scalarrepl -mem2reg -ipconstprop -deadargelim -sccp -dce -ipsccp -dce -constmerge -scev-aa -targetlibinfo -irce -dse -dce -argpromotion -mem2reg -adce -mem2reg -globaldce -die -dce -dse" #-LlvmLlcArgs "-O2 -code-model=small -data-sections -relocation-model=pic -march=thumb -mcpu=cortex-m3 -filetype=obj -mtriple=thumbv7m-none-eabi" # While the compiler is pretty good at figuring out where the LLVM tools are from # current Environment variables or registry entires you can manually specify the # path to find the LLVM binaries. # note: Environment variabes (i.e %MY_VAR%) are supported and expanded as with all # options in the FrontendConfig files so you can specify a custom variable if needed #-LlvmBinPath c:\src\llvm\llvm-3.7.0.src\build\x64\Release\bin ================================================ FILE: Zelig/Zelig/CompileTime/CodeGenerator/FrontEnd/mbed_simple_NET_K64F_Tester.FrontEndConfig ================================================ ### ### Location of the Zelig assemblies. ### -HostAssemblyDir ..\..\..\..\ZeligBuild\Host\bin\Debug -DeviceAssemblyDir ..\..\..\..\ZeligBuild\Target\bin\Debug -Architecture cortex-m4 -CompilationSetupPath ..\..\..\..\ZeligBuild\Host\bin\Debug\Microsoft.Llilum.BoardConfigurations.K64F.dll -CompilationSetup Microsoft.Llilum.BoardConfigurations.K64FMBEDCompilationSetup ### ### We need to include this assembly to get the right drivers. ### -Reference Microsoft.CortexM4OnMBED -Reference Microsoft.CortexM4OnCMSISCore -Reference Microsoft.DeviceModels.ModelForCortexM4 -Reference K64F -Reference Microsoft.Zelig.LlilumCMSIS-RTOS ### ### Add compilation phases, in order ### #-CompilationPhaseDisabled ReduceNumberOfTemporaries #-CompilationPhaseDisabled TransformFinallyBlocksIntoTryBlocks #-CompilationPhaseDisabled ApplyClassExtensions #-CompilationPhaseDisabled PrepareImplementationOfInternalMethods #-CompilationPhaseDisabled CrossReferenceTypeSystem #-CompilationPhaseDisabled ApplyConfigurationSettings -CompilationPhaseDisabled ResourceManagerOptimizations #-CompilationPhaseDisabled HighLevelTransformations #-CompilationPhaseDisabled PropagateCompilationConstraints #-CompilationPhaseDisabled ComputeCallsClosure #-CompilationPhaseDisabled EstimateTypeSystemReduction #-CompilationPhaseDisabled CompleteImplementationOfInternalMethods #-CompilationPhaseDisabled ReduceTypeSystem -CompilationPhaseDisabled PrepareExternalMethods #-CompilationPhaseDisabled DetectNonImplementedInternalCalls #-CompilationPhaseDisabled OrderStaticConstructors #-CompilationPhaseDisabled LayoutTypes #-CompilationPhaseDisabled HighLevelToMidLevelConversion #-CompilationPhaseDisabled FromImplicitToExplicitExceptions #-CompilationPhaseDisabled ReferenceCountingGarbageCollection -CompilationPhaseDisabled MidLevelToLowLevelConversion -CompilationPhaseDisabled ConvertUnsupportedOperatorsToMethodCalls -CompilationPhaseDisabled ExpandAggregateTypes -CompilationPhaseDisabled SplitComplexOperators -CompilationPhaseDisabled FuseOperators #-CompilationPhaseDisabled Optimizations -CompilationPhaseDisabled ConvertToSSA -CompilationPhaseDisabled PrepareForRegisterAllocation -CompilationPhaseDisabled CollectRegisterAllocationConstraints -CompilationPhaseDisabled AllocateRegisters #-CompilationPhaseDisabled GenerateImage #-CompilationPhaseDisabled Done ### ### The program to compile. ### ..\..\..\..\ZeligBuild\Target\bin\Debug\Microsoft.Zelig.Test.TestRunner.exe ### ### Where to put the results. ### -OutputName Microsoft.Zelig.Test.mbed.Simple -OutputDir ..\..\..\..\LLVM2IR_results\mbed\simple ### ### Dumps and diagnostics ### #-DumpIRBeforePhase All #-DumpIR #-DumpIRpre #-DumpIRpost #-DumpIRXML #-DumpFlattenedCallGraph -DumpLLVMIR #-ReloadState #-DumpLLVMIR_TextRepresentation -MaxProcs 8 -NoSDK -GenerateObj # examples of overriding opt.exe and llc arguments # the examples here are the same as the defaults but can be modified to suit a variety of test # scenarios and experimentations #-LlvmOptArgs "-verify-debug-info -verify-dom-info -verify-each -verify-loop-info -verify-regalloc -verify-region-info -march=thumb -mcpu=cortex-m3 -aa-eval -indvars -gvn -globaldce -adce -dce -tailcallopt -scalarrepl -mem2reg -ipconstprop -deadargelim -sccp -dce -ipsccp -dce -constmerge -scev-aa -targetlibinfo -irce -dse -dce -argpromotion -mem2reg -adce -mem2reg -globaldce -die -dce -dse" #-LlvmLlcArgs "-O2 -code-model=small -data-sections -relocation-model=pic -march=thumb -mcpu=cortex-m3 -filetype=obj -mtriple=thumbv7m-none-eabi" # While the compiler is pretty good at figuring out where the LLVM tools are from # current Environment variables or registry entires you can manually specify the # path to find the LLVM binaries. # note: Environment variabes (i.e %MY_VAR%) are supported and expanded as with all # options in the FrontendConfig files so you can specify a custom variable if needed #-LlvmBinPath c:\src\llvm\llvm-3.7.0.src\build\x64\Release\bin ================================================ FILE: Zelig/Zelig/CompileTime/CodeGenerator/FrontEnd/mbed_simple_STM32F091.FrontEndConfig ================================================ ### ### README: This file can be used in the SDK AS-IS, or remove all instances of to use with the FrontEnd project ### ### ### Location of the Zelig assemblies. ### -HostAssemblyDir ..\..\..\..\ZeligBuild\Host\bin\Debug -DeviceAssemblyDir ..\..\..\..\ZeligBuild\Target\bin\Debug -Architecture cortex-m0 -CompilationSetupPath ..\..\..\..\ZeligBuild\Host\bin\Debug\Microsoft.Llilum.BoardConfigurations.STM32F091.dll -CompilationSetup Microsoft.Llilum.BoardConfigurations.STM32F091MBEDCompilationSetup ### ### We need to include this assembly to get the right drivers. ### -Reference Microsoft.CortexM0OnMBED -Reference Microsoft.CortexM0OnCMSISCore -Reference Microsoft.DeviceModels.ModelForCortexM0 -Reference STM32F091 ### ### Add compilation phases, in order ### #-CompilationPhaseDisabled ReduceNumberOfTemporaries #-CompilationPhaseDisabled TransformFinallyBlocksIntoTryBlocks #-CompilationPhaseDisabled ApplyClassExtensions #-CompilationPhaseDisabled PrepareImplementationOfInternalMethods #-CompilationPhaseDisabled CrossReferenceTypeSystem #-CompilationPhaseDisabled ApplyConfigurationSettings -CompilationPhaseDisabled ResourceManagerOptimizations #-CompilationPhaseDisabled HighLevelTransformations #-CompilationPhaseDisabled PropagateCompilationConstraints #-CompilationPhaseDisabled ComputeCallsClosure #-CompilationPhaseDisabled EstimateTypeSystemReduction #-CompilationPhaseDisabled CompleteImplementationOfInternalMethods #-CompilationPhaseDisabled ReduceTypeSystem -CompilationPhaseDisabled PrepareExternalMethods #-CompilationPhaseDisabled DetectNonImplementedInternalCalls #-CompilationPhaseDisabled OrderStaticConstructors #-CompilationPhaseDisabled LayoutTypes #-CompilationPhaseDisabled HighLevelToMidLevelConversion #-CompilationPhaseDisabled FromImplicitToExplicitExceptions #-CompilationPhaseDisabled ReferenceCountingGarbageCollection -CompilationPhaseDisabled MidLevelToLowLevelConversion -CompilationPhaseDisabled ConvertUnsupportedOperatorsToMethodCalls -CompilationPhaseDisabled ExpandAggregateTypes -CompilationPhaseDisabled SplitComplexOperators -CompilationPhaseDisabled FuseOperators #-CompilationPhaseDisabled Optimizations -CompilationPhaseDisabled ConvertToSSA -CompilationPhaseDisabled PrepareForRegisterAllocation -CompilationPhaseDisabled CollectRegisterAllocationConstraints -CompilationPhaseDisabled AllocateRegisters #-CompilationPhaseDisabled GenerateImage #-CompilationPhaseDisabled Done ### ### The program to compile. ### ..\..\..\..\ZeligBuild\Target\bin\Debug\Microsoft.Zelig.Test.mbed.Simple.exe ### ### Where to put the results. ### -OutputName Microsoft.Zelig.Test.mbed.Simple -OutputDir ..\..\..\..\LLVM2IR_results\mbed\simple ### ### Dumps and diagnostics ### #-DumpIRBeforePhase ReduceNumberOfTemporaries TransformFinallyBlocksIntoTryBlocks ApplyClassExtensions #-DumpIRBeforePhase All -DumpIR #-DumpIRpre #-DumpIRpost #-DumpIRXML #-DumpFlattenedCallGraph -DumpLLVMIR #-ReloadState -DumpLLVMIR_TextRepresentation -MaxProcs 8 -NoSDK ### ### LLVM CodeGeneration ### -GenerateObj # examples of overriding opt.exe and llc arguments # the examples here are the same as the defaults but can be modified to suit a variety of test # scenarios and experimentations #-LlvmOptArgs "-verify-debug-info -verify-dom-info -verify-each -verify-loop-info -verify-regalloc -verify-region-info -march=thumb -mcpu=cortex-m3 -aa-eval -indvars -gvn -globaldce -adce -dce -tailcallopt -scalarrepl -mem2reg -ipconstprop -deadargelim -sccp -dce -ipsccp -dce -constmerge -scev-aa -targetlibinfo -irce -dse -dce -argpromotion -mem2reg -adce -mem2reg -globaldce -die -dce -dse" #-LlvmLlcArgs "-O2 -code-model=small -data-sections -relocation-model=pic -march=thumb -mcpu=cortex-m3 -filetype=obj -mtriple=thumbv7m-none-eabi" # While the compiler is pretty good at figuring out where the LLVM tools are from # current Environment variables or registry entires you can manually specify the # path to find the LLVM binaries. # note: Environment variabes (i.e %MY_VAR%) are supported and expanded as with all # options in the FrontendConfig files so you can specify a custom variable if needed #-LlvmBinPath c:\src\llvm\llvm-3.7.0.src\build\x64\Release\bin ================================================ FILE: Zelig/Zelig/CompileTime/CodeGenerator/FrontEnd/mbed_simple_STM32F401.FrontEndConfig ================================================ ### ### README: This file can be used in the SDK AS-IS, or remove all instances of to use with the FrontEnd project ### ### ### Location of the Zelig assemblies. ### -HostAssemblyDir ..\..\..\..\ZeligBuild\Host\bin\Debug -DeviceAssemblyDir ..\..\..\..\ZeligBuild\Target\bin\Debug -Architecture cortex-m4 -CompilationSetupPath ..\..\..\..\ZeligBuild\Host\bin\Debug\Microsoft.Llilum.BoardConfigurations.STM32F401.dll -CompilationSetup Microsoft.Llilum.BoardConfigurations.STM32F401MBEDCompilationSetup ### ### We need to include this assembly to get the right drivers. ### -Reference Microsoft.CortexM4OnMBED -Reference Microsoft.CortexM4OnCMSISCore -Reference Microsoft.DeviceModels.ModelForCortexM4 -Reference STM32F401 ### ### Add compilation phases, in order ### #-CompilationPhaseDisabled ReduceNumberOfTemporaries #-CompilationPhaseDisabled TransformFinallyBlocksIntoTryBlocks #-CompilationPhaseDisabled ApplyClassExtensions #-CompilationPhaseDisabled PrepareImplementationOfInternalMethods #-CompilationPhaseDisabled CrossReferenceTypeSystem #-CompilationPhaseDisabled ApplyConfigurationSettings -CompilationPhaseDisabled ResourceManagerOptimizations #-CompilationPhaseDisabled HighLevelTransformations #-CompilationPhaseDisabled PropagateCompilationConstraints #-CompilationPhaseDisabled ComputeCallsClosure #-CompilationPhaseDisabled EstimateTypeSystemReduction #-CompilationPhaseDisabled CompleteImplementationOfInternalMethods #-CompilationPhaseDisabled ReduceTypeSystem -CompilationPhaseDisabled PrepareExternalMethods #-CompilationPhaseDisabled DetectNonImplementedInternalCalls #-CompilationPhaseDisabled OrderStaticConstructors #-CompilationPhaseDisabled LayoutTypes #-CompilationPhaseDisabled HighLevelToMidLevelConversion #-CompilationPhaseDisabled FromImplicitToExplicitExceptions #-CompilationPhaseDisabled ReferenceCountingGarbageCollection -CompilationPhaseDisabled MidLevelToLowLevelConversion -CompilationPhaseDisabled ConvertUnsupportedOperatorsToMethodCalls -CompilationPhaseDisabled ExpandAggregateTypes -CompilationPhaseDisabled SplitComplexOperators -CompilationPhaseDisabled FuseOperators #-CompilationPhaseDisabled Optimizations -CompilationPhaseDisabled ConvertToSSA -CompilationPhaseDisabled PrepareForRegisterAllocation -CompilationPhaseDisabled CollectRegisterAllocationConstraints -CompilationPhaseDisabled AllocateRegisters #-CompilationPhaseDisabled GenerateImage #-CompilationPhaseDisabled Done ### ### The program to compile. ### ..\..\..\..\ZeligBuild\Target\bin\Debug\Microsoft.Zelig.Test.mbed.Simple.exe ### ### Where to put the results. ### -OutputName Microsoft.Zelig.Test.mbed.Simple -OutputDir ..\..\..\..\LLVM2IR_results\mbed\simple #-DumpIR #-DumpIRpre #-DumpIRpost #-DumpIRXML #-DumpFlattenedCallGraph -DumpLLVMIR #-ReloadState #-DumpLLVMIR_TextRepresentation -MaxProcs 8 -NoSDK -GenerateObj # examples of overriding opt.exe and llc arguments # the examples here are the same as the defaults but can be modified to suit a variety of test # scenarios and experimentations #-LlvmOptArgs "-verify-debug-info -verify-dom-info -verify-each -verify-loop-info -verify-regalloc -verify-region-info -march=thumb -mcpu=cortex-m3 -aa-eval -indvars -gvn -globaldce -adce -dce -tailcallopt -scalarrepl -mem2reg -ipconstprop -deadargelim -sccp -dce -ipsccp -dce -constmerge -scev-aa -targetlibinfo -irce -dse -dce -argpromotion -mem2reg -adce -mem2reg -globaldce -die -dce -dse" #-LlvmLlcArgs "-O2 -code-model=small -data-sections -relocation-model=pic -march=thumb -mcpu=cortex-m3 -filetype=obj -mtriple=thumbv7m-none-eabi" # While the compiler is pretty good at figuring out where the LLVM tools are from # current Environment variables or registry entires you can manually specify the # path to find the LLVM binaries. # note: Environment variabes (i.e %MY_VAR%) are supported and expanded as with all # options in the FrontendConfig files so you can specify a custom variable if needed #-LlvmBinPath \\netmfbld02\LLVM\3.7.0\build\Win32\Release\bin ================================================ FILE: Zelig/Zelig/CompileTime/CodeGenerator/FrontEnd/mbed_simple_STM32F411.FrontEndConfig ================================================ ### ### README: This file can be used in the SDK AS-IS, or remove all instances of to use with the FrontEnd project ### ### ### Location of the Zelig assemblies. ### -HostAssemblyDir ..\..\..\..\ZeligBuild\Host\bin\Debug -DeviceAssemblyDir ..\..\..\..\ZeligBuild\Target\bin\Debug -Architecture cortex-m4 -CompilationSetupPath ..\..\..\..\ZeligBuild\Host\bin\Debug\Microsoft.Llilum.BoardConfigurations.STM32F411.dll -CompilationSetup Microsoft.Llilum.BoardConfigurations.STM32F411MBEDCompilationSetup ### ### We need to include this assembly to get the right drivers. ### -Reference Microsoft.CortexM4OnMBED -Reference Microsoft.CortexM4OnCMSISCore -Reference Microsoft.DeviceModels.ModelForCortexM4 -Reference STM32F411 ### ### Add compilation phases, in order ### #-CompilationPhaseDisabled ReduceNumberOfTemporaries #-CompilationPhaseDisabled TransformFinallyBlocksIntoTryBlocks #-CompilationPhaseDisabled ApplyClassExtensions #-CompilationPhaseDisabled PrepareImplementationOfInternalMethods #-CompilationPhaseDisabled CrossReferenceTypeSystem #-CompilationPhaseDisabled ApplyConfigurationSettings -CompilationPhaseDisabled ResourceManagerOptimizations #-CompilationPhaseDisabled HighLevelTransformations #-CompilationPhaseDisabled PropagateCompilationConstraints #-CompilationPhaseDisabled ComputeCallsClosure #-CompilationPhaseDisabled EstimateTypeSystemReduction #-CompilationPhaseDisabled CompleteImplementationOfInternalMethods #-CompilationPhaseDisabled ReduceTypeSystem -CompilationPhaseDisabled PrepareExternalMethods #-CompilationPhaseDisabled DetectNonImplementedInternalCalls #-CompilationPhaseDisabled OrderStaticConstructors #-CompilationPhaseDisabled LayoutTypes #-CompilationPhaseDisabled HighLevelToMidLevelConversion #-CompilationPhaseDisabled FromImplicitToExplicitExceptions #-CompilationPhaseDisabled ReferenceCountingGarbageCollection -CompilationPhaseDisabled MidLevelToLowLevelConversion -CompilationPhaseDisabled ConvertUnsupportedOperatorsToMethodCalls -CompilationPhaseDisabled ExpandAggregateTypes -CompilationPhaseDisabled SplitComplexOperators -CompilationPhaseDisabled FuseOperators #-CompilationPhaseDisabled Optimizations -CompilationPhaseDisabled ConvertToSSA -CompilationPhaseDisabled PrepareForRegisterAllocation -CompilationPhaseDisabled CollectRegisterAllocationConstraints -CompilationPhaseDisabled AllocateRegisters #-CompilationPhaseDisabled GenerateImage #-CompilationPhaseDisabled Done ### ### The program to compile. ### ..\..\..\..\ZeligBuild\Target\bin\Debug\Microsoft.Zelig.Test.mbed.Simple.exe ### ### Where to put the results. ### -OutputName Microsoft.Zelig.Test.mbed.Simple -OutputDir ..\..\..\..\LLVM2IR_results\mbed\simple ### ### Dumps and diagnostics ### #-DumpIRBeforePhase ReduceNumberOfTemporaries TransformFinallyBlocksIntoTryBlocks ApplyClassExtensions #-DumpIRBeforePhase All -DumpIR #-DumpIRpre #-DumpIRpost #-DumpIRXML #-DumpFlattenedCallGraph -DumpLLVMIR #-ReloadState -DumpLLVMIR_TextRepresentation -MaxProcs 8 -NoSDK ### ### LLVM CodeGeneration ### -GenerateObj # examples of overriding opt.exe and llc arguments # the examples here are the same as the defaults but can be modified to suit a variety of test # scenarios and experimentations #-LlvmOptArgs "-verify-debug-info -verify-dom-info -verify-each -verify-loop-info -verify-regalloc -verify-region-info -march=thumb -mcpu=cortex-m3 -aa-eval -indvars -gvn -globaldce -adce -dce -tailcallopt -scalarrepl -mem2reg -ipconstprop -deadargelim -sccp -dce -ipsccp -dce -constmerge -scev-aa -targetlibinfo -irce -dse -dce -argpromotion -mem2reg -adce -mem2reg -globaldce -die -dce -dse" #-LlvmLlcArgs "-O2 -code-model=small -data-sections -relocation-model=pic -march=thumb -mcpu=cortex-m3 -filetype=obj -mtriple=thumbv7m-none-eabi" # While the compiler is pretty good at figuring out where the LLVM tools are from # current Environment variables or registry entires you can manually specify the # path to find the LLVM binaries. # note: Environment variabes (i.e %MY_VAR%) are supported and expanded as with all # options in the FrontendConfig files so you can specify a custom variable if needed #-LlvmBinPath \\netmfbld02\LLVM\3.7.0\build\Win32\Release\bin ================================================ FILE: Zelig/Zelig/CompileTime/CodeGenerator/FrontEnd/mbed_simple_STM32L152.FrontEndConfig ================================================ ### ### Location of the Zelig assemblies. ### -HostAssemblyDir ..\..\..\..\ZeligBuild\Host\bin\Debug -DeviceAssemblyDir ..\..\..\..\ZeligBuild\Target\bin\Debug -Architecture cortex-m3 -CompilationSetupPath ..\..\..\..\ZeligBuild\Host\bin\Debug\Microsoft.Llilum.BoardConfigurations.STM32L152.dll -CompilationSetup Microsoft.Llilum.BoardConfigurations.STM32L152MBEDCompilationSetup ### ### We need to include this assembly to get the right drivers. ### -Reference Microsoft.CortexM3OnMBED -Reference Microsoft.CortexM3OnCMSISCore -Reference Microsoft.DeviceModels.ModelForCortexM3 -Reference STM32L152 ### ### Add compilation phases, in order ### #-CompilationPhaseDisabled ReduceNumberOfTemporaries #-CompilationPhaseDisabled TransformFinallyBlocksIntoTryBlocks #-CompilationPhaseDisabled ApplyClassExtensions #-CompilationPhaseDisabled PrepareImplementationOfInternalMethods #-CompilationPhaseDisabled CrossReferenceTypeSystem #-CompilationPhaseDisabled ApplyConfigurationSettings -CompilationPhaseDisabled ResourceManagerOptimizations #-CompilationPhaseDisabled HighLevelTransformations #-CompilationPhaseDisabled PropagateCompilationConstraints #-CompilationPhaseDisabled ComputeCallsClosure #-CompilationPhaseDisabled EstimateTypeSystemReduction #-CompilationPhaseDisabled CompleteImplementationOfInternalMethods #-CompilationPhaseDisabled ReduceTypeSystem -CompilationPhaseDisabled PrepareExternalMethods #-CompilationPhaseDisabled DetectNonImplementedInternalCalls #-CompilationPhaseDisabled OrderStaticConstructors #-CompilationPhaseDisabled LayoutTypes #-CompilationPhaseDisabled HighLevelToMidLevelConversion #-CompilationPhaseDisabled FromImplicitToExplicitExceptions #-CompilationPhaseDisabled ReferenceCountingGarbageCollection -CompilationPhaseDisabled MidLevelToLowLevelConversion -CompilationPhaseDisabled ConvertUnsupportedOperatorsToMethodCalls -CompilationPhaseDisabled ExpandAggregateTypes -CompilationPhaseDisabled SplitComplexOperators -CompilationPhaseDisabled FuseOperators #-CompilationPhaseDisabled Optimizations -CompilationPhaseDisabled ConvertToSSA -CompilationPhaseDisabled PrepareForRegisterAllocation -CompilationPhaseDisabled CollectRegisterAllocationConstraints -CompilationPhaseDisabled AllocateRegisters #-CompilationPhaseDisabled GenerateImage #-CompilationPhaseDisabled Done ### ### The program to compile. ### ..\..\..\..\ZeligBuild\Target\bin\Debug\Microsoft.Zelig.Test.mbed.Simple.exe ### ### Where to put the results. ### -OutputName Microsoft.Zelig.Test.mbed.Simple -OutputDir ..\..\..\..\LLVM2IR_results\mbed\simple ### ### Dumps and diagnostics ### #-DumpIRBeforePhase All -DumpIR #-DumpIRpre #-DumpIRpost #-DumpIRXML #-DumpFlattenedCallGraph -DumpLLVMIR #-ReloadState -DumpLLVMIR_TextRepresentation -MaxProcs 8 -NoSDK -GenerateObj # examples of overriding opt.exe and llc arguments # the examples here are the same as the defaults but can be modified to suit a variety of test # scenarios and experimentations #-LlvmOptArgs "-verify-debug-info -verify-dom-info -verify-each -verify-loop-info -verify-regalloc -verify-region-info -march=thumb -mcpu=cortex-m3 -aa-eval -indvars -gvn -globaldce -adce -dce -tailcallopt -scalarrepl -mem2reg -ipconstprop -deadargelim -sccp -dce -ipsccp -dce -constmerge -scev-aa -targetlibinfo -irce -dse -dce -argpromotion -mem2reg -adce -mem2reg -globaldce -die -dce -dse" #-LlvmLlcArgs "-O2 -code-model=small -data-sections -relocation-model=pic -march=thumb -mcpu=cortex-m3 -filetype=obj -mtriple=thumbv7m-none-eabi" # While the compiler is pretty good at figuring out where the LLVM tools are from # current Environment variables or registry entires you can manually specify the # path to find the LLVM binaries. # note: Environment variabes (i.e %MY_VAR%) are supported and expanded as with all # options in the FrontendConfig files so you can specify a custom variable if needed #-LlvmBinPath \\netmfbld02\LLVM\3.7.0\build\Win32\Release\bin ================================================ FILE: Zelig/Zelig/CompileTime/CodeGenerator/FrontEnd/mbed_simple_Win32.FrontEndConfig ================================================ ### ### Location of the Zelig assemblies. ### -HostAssemblyDir ..\..\..\..\ZeligBuild\Host\bin\Debug -DeviceAssemblyDir ..\..\..\..\ZeligBuild\Target\bin\Debug -Architecture x86-64 -CompilationSetupPath ..\..\..\..\ZeligBuild\Host\bin\Debug\Microsoft.Llilum.BoardConfigurations.Win32.dll -CompilationSetup Microsoft.Llilum.BoardConfigurations.Win32CompilationSetup ### ### We need to include this assembly to get the right drivers. ### -Reference Microsoft.DeviceModels.ModelForWin32 -Reference Win32 ### ### Add compilation phases, in order ### #-CompilationPhaseDisabled ReduceNumberOfTemporaries #-CompilationPhaseDisabled TransformFinallyBlocksIntoTryBlocks #-CompilationPhaseDisabled ApplyClassExtensions #-CompilationPhaseDisabled PrepareImplementationOfInternalMethods #-CompilationPhaseDisabled CrossReferenceTypeSystem #-CompilationPhaseDisabled ApplyConfigurationSettings -CompilationPhaseDisabled ResourceManagerOptimizations #-CompilationPhaseDisabled HighLevelTransformations #-CompilationPhaseDisabled PropagateCompilationConstraints #-CompilationPhaseDisabled ComputeCallsClosure #-CompilationPhaseDisabled EstimateTypeSystemReduction #-CompilationPhaseDisabled CompleteImplementationOfInternalMethods #-CompilationPhaseDisabled ReduceTypeSystem -CompilationPhaseDisabled PrepareExternalMethods #-CompilationPhaseDisabled DetectNonImplementedInternalCalls #-CompilationPhaseDisabled OrderStaticConstructors #-CompilationPhaseDisabled LayoutTypes #-CompilationPhaseDisabled HighLevelToMidLevelConversion #-CompilationPhaseDisabled FromImplicitToExplicitExceptions #-CompilationPhaseDisabled ReferenceCountingGarbageCollection -CompilationPhaseDisabled MidLevelToLowLevelConversion -CompilationPhaseDisabled ConvertUnsupportedOperatorsToMethodCalls -CompilationPhaseDisabled ExpandAggregateTypes -CompilationPhaseDisabled SplitComplexOperators -CompilationPhaseDisabled FuseOperators #-CompilationPhaseDisabled Optimizations -CompilationPhaseDisabled ConvertToSSA -CompilationPhaseDisabled PrepareForRegisterAllocation -CompilationPhaseDisabled CollectRegisterAllocationConstraints -CompilationPhaseDisabled AllocateRegisters #-CompilationPhaseDisabled GenerateImage #-CompilationPhaseDisabled Done ### ### The program to compile. ### ..\..\..\..\ZeligBuild\Target\bin\Debug\Microsoft.Zelig.Test.mbed.Simple.exe ### ### Where to put the results. ### -OutputName Microsoft.Zelig.Test.mbed.Simple -OutputDir ..\..\..\..\LLVM2IR_results\mbed\simple -DumpIR #-DumpIRpre #-DumpIRpost #-DumpIRXML -DumpLLVMIR #-ReloadState -DumpLLVMIR_TextRepresentation -MaxProcs 8 -NoSDK #-Debug -GenerateObj #-LlvmOptArgs "-verify-debug-info -verify-dom-info -verify-each -verify-loop-info -verify-regalloc -verify-region-info -march=thumb -mcpu=cortex-m3 -aa-eval -indvars -gvn -globaldce -adce -dce -tailcallopt -scalarrepl -mem2reg -ipconstprop -deadargelim -sccp -dce -ipsccp -dce -constmerge -scev-aa -targetlibinfo -irce -dse -dce -argpromotion -mem2reg -adce -mem2reg -globaldce -die -dce -dse" #-LlvmLlcArgs "-O2 -code-model=small -data-sections -relocation-model=pic -march=thumb -mcpu=cortex-m3 -filetype=obj -mtriple=thumbv7m-none-eabi" ================================================ FILE: Zelig/Zelig/CompileTime/CodeGenerator/FrontEnd/mbed_simple_Win32_Tester.FrontEndConfig ================================================ ### ### Location of the Zelig assemblies. ### -HostAssemblyDir ..\..\..\..\ZeligBuild\Host\bin\Debug -DeviceAssemblyDir ..\..\..\..\ZeligBuild\Target\bin\Debug -Architecture x86-64 -CompilationSetupPath ..\..\..\..\ZeligBuild\Host\bin\Debug\Microsoft.Llilum.BoardConfigurations.Win32.dll -CompilationSetup Microsoft.Llilum.BoardConfigurations.Win32CompilationSetup ### ### We need to include this assembly to get the right drivers. ### -Reference Microsoft.DeviceModels.ModelForWin32 -Reference Win32 ### ### Add compilation phases, in order ### #-CompilationPhaseDisabled ReduceNumberOfTemporaries #-CompilationPhaseDisabled TransformFinallyBlocksIntoTryBlocks #-CompilationPhaseDisabled ApplyClassExtensions #-CompilationPhaseDisabled PrepareImplementationOfInternalMethods #-CompilationPhaseDisabled CrossReferenceTypeSystem #-CompilationPhaseDisabled ApplyConfigurationSettings -CompilationPhaseDisabled ResourceManagerOptimizations #-CompilationPhaseDisabled HighLevelTransformations #-CompilationPhaseDisabled PropagateCompilationConstraints #-CompilationPhaseDisabled ComputeCallsClosure #-CompilationPhaseDisabled EstimateTypeSystemReduction #-CompilationPhaseDisabled CompleteImplementationOfInternalMethods #-CompilationPhaseDisabled ReduceTypeSystem -CompilationPhaseDisabled PrepareExternalMethods #-CompilationPhaseDisabled DetectNonImplementedInternalCalls #-CompilationPhaseDisabled OrderStaticConstructors #-CompilationPhaseDisabled LayoutTypes #-CompilationPhaseDisabled HighLevelToMidLevelConversion #-CompilationPhaseDisabled FromImplicitToExplicitExceptions #-CompilationPhaseDisabled ReferenceCountingGarbageCollection -CompilationPhaseDisabled MidLevelToLowLevelConversion -CompilationPhaseDisabled ConvertUnsupportedOperatorsToMethodCalls -CompilationPhaseDisabled ExpandAggregateTypes -CompilationPhaseDisabled SplitComplexOperators -CompilationPhaseDisabled FuseOperators #-CompilationPhaseDisabled Optimizations -CompilationPhaseDisabled ConvertToSSA -CompilationPhaseDisabled PrepareForRegisterAllocation -CompilationPhaseDisabled CollectRegisterAllocationConstraints -CompilationPhaseDisabled AllocateRegisters #-CompilationPhaseDisabled GenerateImage #-CompilationPhaseDisabled Done ### ### The program to compile. ### ..\..\..\..\ZeligBuild\Target\bin\Debug\Microsoft.Zelig.Test.TestRunner.exe ### ### Where to put the results. ### -OutputName Microsoft.Zelig.Test.mbed.Simple -OutputDir ..\..\..\..\LLVM2IR_results\mbed\simple ### ### Dumps and diagnostics ### #-DumpIRBeforePhase All -DumpIR #-DumpIRpre #-DumpIRpost #-DumpIRXML #-DumpFlattenedCallGraph -DumpLLVMIR #-ReloadState -DumpLLVMIR_TextRepresentation -MaxProcs 8 -NoSDK -Debug -GenerateObj #-LlvmOptArgs "-verify-debug-info -verify-dom-info -verify-each -verify-loop-info -verify-regalloc -verify-region-info -march=thumb -mcpu=cortex-m3 -aa-eval -indvars -gvn -globaldce -adce -dce -tailcallopt -scalarrepl -mem2reg -ipconstprop -deadargelim -sccp -dce -ipsccp -dce -constmerge -scev-aa -targetlibinfo -irce -dse -dce -argpromotion -mem2reg -adce -mem2reg -globaldce -die -dce -dse" #-LlvmLlcArgs "-O2 -code-model=small -data-sections -relocation-model=pic -march=thumb -mcpu=cortex-m3 -filetype=obj -mtriple=thumbv7m-none-eabi" ================================================ FILE: Zelig/Zelig/CompileTime/CodeGenerator/IntermediateRepresentation/Annotations/Annotation.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // #if DEBUG #define TRACK_ANNOTATION_IDENTITY #else //#define TRACK_ANNOTATION_IDENTITY #endif namespace Microsoft.Zelig.CodeGeneration.IR { using System; using System.Collections.Generic; using Microsoft.Zelig.Runtime.TypeSystem; public abstract class Annotation { public static readonly Annotation[] SharedEmptyArray = new Annotation[0]; // // State // #if TRACK_ANNOTATION_IDENTITY protected static int s_identity; #endif public int m_identity; //--// // // Constructor Methods // protected Annotation() // Default constructor required by TypeSystemSerializer. { #if TRACK_ANNOTATION_IDENTITY m_identity = s_identity++; #endif } //--// // // Helper Methods // public abstract Annotation Clone( CloningContext context ); protected Annotation RegisterAndCloneState( CloningContext context , Annotation clone ) { context.Register( this, clone ); CloneState( context, clone ); return clone; } protected virtual void CloneState( CloningContext context , Annotation clone ) { } //--// public virtual void ApplyTransformation( TransformationContextForIR context ) { } public virtual Operator.OperatorLevel GetLevel( Operator.IOperatorLevelHelper helper ) { return Operator.OperatorLevel.Lowest; } //--// protected static Annotation MakeUnique( TypeSystemForIR ts , Annotation an ) { return ts != null ? ts.CreateUniqueAnnotation( an ) : an; } //--// // // Access Methods // //--// // // Debug Methods // public abstract string FormatOutput( IIntermediateRepresentationDumper dumper ); } } ================================================ FILE: Zelig/Zelig/CompileTime/CodeGenerator/IntermediateRepresentation/Annotations/ArrayLengthAnnotation.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // namespace Microsoft.Zelig.CodeGeneration.IR { using System; using System.Collections.Generic; using Microsoft.Zelig.Runtime.TypeSystem; public sealed class ArrayLengthAnnotation : Annotation { // // Constructor Methods // private ArrayLengthAnnotation() { } public static ArrayLengthAnnotation Create( TypeSystemForIR ts ) { return (ArrayLengthAnnotation)MakeUnique( ts, new ArrayLengthAnnotation() ); } // // Equality Methods // public override bool Equals( Object obj ) { if(obj is ArrayLengthAnnotation) { return true; } return false; } public override int GetHashCode() { return base.GetHashCode(); } // // Helper Methods // public override Annotation Clone( CloningContext context ) { return this; // Nothing to change. } //--// // // Access Methods // //--// // // Debug Methods // public override string FormatOutput( IIntermediateRepresentationDumper dumper ) { return ""; } } } ================================================ FILE: Zelig/Zelig/CompileTime/CodeGenerator/IntermediateRepresentation/Annotations/BlockCopyPropagationAnnotation.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // namespace Microsoft.Zelig.CodeGeneration.IR { using System; using System.Collections.Generic; using Microsoft.Zelig.Runtime.TypeSystem; public sealed class BlockCopyPropagationAnnotation : Annotation { // // State // private int m_index; private bool m_fIsResult; private bool m_fIsTemporary; // // Constructor Methods // private BlockCopyPropagationAnnotation( int index , bool fIsResult , bool fIsTemporary ) { m_index = index; m_fIsResult = fIsResult; m_fIsTemporary = fIsTemporary; } public static BlockCopyPropagationAnnotation Create( TypeSystemForIR ts , int index , bool fIsResult , bool fIsTemporary ) { return (BlockCopyPropagationAnnotation)MakeUnique( ts, new BlockCopyPropagationAnnotation( index, fIsResult, fIsTemporary ) ); } // // Equality Methods // public override bool Equals( Object obj ) { if(obj is BlockCopyPropagationAnnotation) { var other = (BlockCopyPropagationAnnotation)obj; if(m_index == other.m_index && m_fIsResult == other.m_fIsResult && m_fIsTemporary == other.m_fIsTemporary ) { return true; } } return false; } public override int GetHashCode() { return 0x7D112541 ^ m_index; } // // Helper Methods // public override Annotation Clone( CloningContext context ) { return this; // Nothing to change. } //--// public override void ApplyTransformation( TransformationContextForIR context ) { context.Push( this ); base.ApplyTransformation( context ); context.Transform( ref m_index ); context.Transform( ref m_fIsResult ); context.Transform( ref m_fIsTemporary ); context.Pop(); } //--// // // Access Methods // public int Index { get { return m_index; } } public bool IsResult { get { return m_fIsResult; } } public bool IsTemporary { get { return m_fIsTemporary; } } //--// // // Debug Methods // public override string FormatOutput( IIntermediateRepresentationDumper dumper ) { return dumper.FormatOutput( "", m_fIsResult ? "LHS" : "RHS", m_index, m_fIsTemporary ? " Temporary" : "" ); } } } ================================================ FILE: Zelig/Zelig/CompileTime/CodeGenerator/IntermediateRepresentation/Annotations/DontRemoveAnnotation.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // namespace Microsoft.Zelig.CodeGeneration.IR { using System; using System.Collections.Generic; using Microsoft.Zelig.Runtime.TypeSystem; public sealed class DontRemoveAnnotation : Annotation { // // Constructor Methods // private DontRemoveAnnotation() { } public static DontRemoveAnnotation Create( TypeSystemForIR ts ) { return (DontRemoveAnnotation)MakeUnique( ts, new DontRemoveAnnotation() ); } // // Equality Methods // public override bool Equals( Object obj ) { if(obj is DontRemoveAnnotation) { return true; } return false; } public override int GetHashCode() { return base.GetHashCode(); } // // Helper Methods // public override Annotation Clone( CloningContext context ) { return this; // Nothing to change. } //--// // // Access Methods // //--// // // Debug Methods // public override string FormatOutput( IIntermediateRepresentationDumper dumper ) { return ""; } } } ================================================ FILE: Zelig/Zelig/CompileTime/CodeGenerator/IntermediateRepresentation/Annotations/ExternalCallArgumentAnnotation.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // namespace Microsoft.Zelig.CodeGeneration.IR { using System; using System.Collections.Generic; using Microsoft.Zelig.Runtime.TypeSystem; public sealed class ExternalCallArgumentAnnotation : Annotation { // // Constructor Methods // private ExternalCallArgumentAnnotation() { } public static ExternalCallArgumentAnnotation Create( TypeSystemForIR ts ) { return (ExternalCallArgumentAnnotation)MakeUnique( ts, new ExternalCallArgumentAnnotation() ); } // // Equality Methods // public override bool Equals( Object obj ) { if(obj is ExternalCallArgumentAnnotation) { return true; } return false; } public override int GetHashCode() { return base.GetHashCode(); } // // Helper Methods // public override Annotation Clone( CloningContext context ) { return this; // Nothing to change. } //--// // // Access Methods // //--// // // Debug Methods // public override string FormatOutput( IIntermediateRepresentationDumper dumper ) { return ""; } } } ================================================ FILE: Zelig/Zelig/CompileTime/CodeGenerator/IntermediateRepresentation/Annotations/FixedLengthArrayAnnotation.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // namespace Microsoft.Zelig.CodeGeneration.IR { using System; using System.Collections.Generic; using Microsoft.Zelig.Runtime.TypeSystem; public sealed class FixedLengthArrayAnnotation : Annotation { // // State // private int m_length; // // Constructor Methods // private FixedLengthArrayAnnotation( int length ) { m_length = length; } public static FixedLengthArrayAnnotation Create( TypeSystemForIR ts , int length ) { return (FixedLengthArrayAnnotation)MakeUnique( ts, new FixedLengthArrayAnnotation( length ) ); } // // Equality Methods // public override bool Equals( Object obj ) { if(obj is FixedLengthArrayAnnotation) { FixedLengthArrayAnnotation other = (FixedLengthArrayAnnotation)obj; return m_length == other.m_length; } return false; } public override int GetHashCode() { return 0x4FF536EC ^ m_length; } // // Helper Methods // public override Annotation Clone( CloningContext context ) { return this; // Nothing to change. } //--// public override void ApplyTransformation( TransformationContextForIR context ) { context.Push( this ); base.ApplyTransformation( context ); context.Transform( ref m_length ); context.Pop(); } //--// // // Access Methods // public int ArrayLength { get { return m_length; } } //--// // // Debug Methods // public override string FormatOutput( IIntermediateRepresentationDumper dumper ) { return dumper.FormatOutput( "", m_length ); } } } ================================================ FILE: Zelig/Zelig/CompileTime/CodeGenerator/IntermediateRepresentation/Annotations/IInliningPathAnnotation.cs ================================================ using Microsoft.Zelig.Debugging; using Microsoft.Zelig.Runtime.TypeSystem; namespace Microsoft.Zelig.CodeGeneration.IR { /// This interface is used to provide inlined details information for a /// /// This is done as an interface to break circular dependency between the IntermediateRepresentation /// and CodeTransformation assemblies. It is expected, though technically not required, that this /// interface is implemented on Microsoft.Zelig.CodeGeneration.IR.InliningPathAnnotation to allow /// tracking where a variable/argument was inlined from and into. /// public interface IInliningPathAnnotation { /// Applies transformations for the inlined path information /// Transformation context void ApplyTransformation(TransformationContextForIR context); /// Method path for an inlined operator /// /// The last entry in the list contains the original source method for the operator this annotation is attached to. /// It is important to note that for compatability reasons this is an array, however callers should consider /// the contents as readonly and not modify the structure or undefined behavior will result /// MethodRepresentation[] Path { get; } /// Retrieves the source location information for the inlining chain /// /// It is possible for entries in this list to be null if there was no debug information /// for the call site the method is inlined into. /// It is worth noting that the debug info path does not "line up" with the /// array, it is in fact off by one index. This is due to the fact that the operator that this /// annotation applies to has its own DebugInfo indicating its source location. Thus, the last /// entry in DebugInfoPath contains the source location where the functions entry block was inlined *into*. /// It is important to note that for compatability reasons this is an array, however callers should consider /// the contents as readonly and not modify the structure or undefined behavior will result /// DebugInfo[] DebugInfoPath { get; } // temp: flag to indicate if the path has had elements removed due to reachability checks bool IsSquashed { get; } } } ================================================ FILE: Zelig/Zelig/CompileTime/CodeGenerator/IntermediateRepresentation/Annotations/InvalidationAnnotation.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // namespace Microsoft.Zelig.CodeGeneration.IR { using System; using System.Collections.Generic; using Microsoft.Zelig.Runtime.TypeSystem; public abstract class InvalidationAnnotation : Annotation { // // State // private VariableExpression m_target; // // Constructor Methods // protected InvalidationAnnotation( VariableExpression target ) { m_target = target; } // // Equality Methods // public override bool Equals( Object obj ) { var other = obj as InvalidationAnnotation; if(other != null) { return m_target == other.m_target; } return false; } public override int GetHashCode() { return m_target.Type.GetHashCode(); } // // Helper Methods // public override void ApplyTransformation( TransformationContextForIR context ) { context.Push( this ); base.ApplyTransformation( context ); context.Transform( ref m_target ); context.Pop(); } //--// // // Access Methods // public VariableExpression Target { get { return m_target; } } //--// // // Debug Methods // } } ================================================ FILE: Zelig/Zelig/CompileTime/CodeGenerator/IntermediateRepresentation/Annotations/MemoryMappedPeripheralAnnotation.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // namespace Microsoft.Zelig.CodeGeneration.IR { using System; using System.Collections.Generic; using Microsoft.Zelig.Runtime.TypeSystem; public sealed class MemoryMappedPeripheralAnnotation : Annotation { // // State // private CustomAttributeRepresentation m_ca; // // Constructor Methods // private MemoryMappedPeripheralAnnotation( CustomAttributeRepresentation ca ) { m_ca = ca; } public static MemoryMappedPeripheralAnnotation Create( TypeSystemForIR ts , CustomAttributeRepresentation ca ) { return (MemoryMappedPeripheralAnnotation)MakeUnique( ts, new MemoryMappedPeripheralAnnotation( ca ) ); } // // Equality Methods // public override bool Equals( Object obj ) { if(obj is MemoryMappedPeripheralAnnotation) { MemoryMappedPeripheralAnnotation other = (MemoryMappedPeripheralAnnotation)obj; return m_ca == other.m_ca; } return false; } public override int GetHashCode() { return m_ca.GetHashCode(); } // // Helper Methods // public override Annotation Clone( CloningContext context ) { return this; // Nothing to change. } //--// public override void ApplyTransformation( TransformationContextForIR context ) { context.Push( this ); base.ApplyTransformation( context ); context.Transform( ref m_ca ); context.Pop(); } //--// // // Access Methods // public CustomAttributeRepresentation Target { get { return m_ca; } } //--// // // Debug Methods // public override string FormatOutput( IIntermediateRepresentationDumper dumper ) { return dumper.FormatOutput( "", m_ca ); } } } ================================================ FILE: Zelig/Zelig/CompileTime/CodeGenerator/IntermediateRepresentation/Annotations/NotNullAnnotation.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // namespace Microsoft.Zelig.CodeGeneration.IR { using System; using System.Collections.Generic; using Microsoft.Zelig.Runtime.TypeSystem; public sealed class NotNullAnnotation : Annotation { // // Constructor Methods // private NotNullAnnotation() { } public static NotNullAnnotation Create( TypeSystemForIR ts ) { return (NotNullAnnotation)MakeUnique( ts, new NotNullAnnotation() ); } // // Equality Methods // public override bool Equals( Object obj ) { if(obj is NotNullAnnotation) { return true; } return false; } public override int GetHashCode() { return base.GetHashCode(); } // // Helper Methods // public override Annotation Clone( CloningContext context ) { return this; // Nothing to change. } //--// // // Access Methods // //--// // // Debug Methods // public override string FormatOutput( IIntermediateRepresentationDumper dumper ) { return ""; } } } ================================================ FILE: Zelig/Zelig/CompileTime/CodeGenerator/IntermediateRepresentation/Annotations/PostInvalidationAnnotation.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // namespace Microsoft.Zelig.CodeGeneration.IR { using System; using System.Collections.Generic; using Microsoft.Zelig.Runtime.TypeSystem; public sealed class PostInvalidationAnnotation : InvalidationAnnotation { // // State // // // Constructor Methods // private PostInvalidationAnnotation( VariableExpression target ) : base( target ) { } public static PostInvalidationAnnotation Create( TypeSystemForIR ts , VariableExpression target ) { return (PostInvalidationAnnotation)MakeUnique( ts, new PostInvalidationAnnotation( target ) ); } // // Equality Methods // public override bool Equals( Object obj ) { var other = obj as PostInvalidationAnnotation; if(other != null) { return base.Equals( obj ); } return false; } public override int GetHashCode() { return base.GetHashCode(); } // // Helper Methods // public override Annotation Clone( CloningContext context ) { var target = (VariableExpression)context.Clone( this.Target ); return RegisterAndCloneState( context, MakeUnique( context.TypeSystem, new PostInvalidationAnnotation( target ) ) ); } //--// // // Access Methods // //--// // // Debug Methods // public override string FormatOutput( IIntermediateRepresentationDumper dumper ) { return dumper.FormatOutput( "", this.Target ); } } } ================================================ FILE: Zelig/Zelig/CompileTime/CodeGenerator/IntermediateRepresentation/Annotations/PreInvalidationAnnotation.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // namespace Microsoft.Zelig.CodeGeneration.IR { using System; using System.Collections.Generic; using Microsoft.Zelig.Runtime.TypeSystem; public sealed class PreInvalidationAnnotation : InvalidationAnnotation { // // State // // // Constructor Methods // private PreInvalidationAnnotation( VariableExpression target ) : base( target ) { } public static PreInvalidationAnnotation Create( TypeSystemForIR ts , VariableExpression target ) { return (PreInvalidationAnnotation)MakeUnique( ts, new PreInvalidationAnnotation( target ) ); } // // Equality Methods // public override bool Equals( Object obj ) { var other = obj as PreInvalidationAnnotation; if(other != null) { return base.Equals( obj ); } return false; } public override int GetHashCode() { return base.GetHashCode(); } // // Helper Methods // public override Annotation Clone( CloningContext context ) { var target = (VariableExpression)context.Clone( this.Target ); return RegisterAndCloneState( context, MakeUnique( context.TypeSystem, new PreInvalidationAnnotation( target ) ) ); } //--// // // Access Methods // //--// // // Debug Methods // public override string FormatOutput( IIntermediateRepresentationDumper dumper ) { return dumper.FormatOutput( "", this.Target ); } } } ================================================ FILE: Zelig/Zelig/CompileTime/CodeGenerator/IntermediateRepresentation/BasicBlocks/BasicBlock.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // #if DEBUG #define TRACK_BASICBLOCK_IDENTITY #else //#define TRACK_BASICBLOCK_IDENTITY #endif namespace Microsoft.Zelig.CodeGeneration.IR { using System; using System.Collections.Generic; using Microsoft.Zelig.Runtime.TypeSystem; public abstract class BasicBlock { public static readonly BasicBlock[] SharedEmptyArray = new BasicBlock[0]; public enum Qualifier { Entry , PrologueStart , PrologueEnd , EntryInjectionStart, EntryInjectionEnd , Normal , Exception , ExitInjectionStart , ExitInjectionEnd , EpilogueStart , EpilogueEnd , Exit , } // // State // #if TRACK_BASICBLOCK_IDENTITY protected static int s_identity; #endif public int m_identity; //--// protected ControlFlowGraphState m_owner; protected int m_index; protected Operator[] m_operators; protected ExceptionHandlerBasicBlock[] m_protectedBy; protected Qualifier m_qualifier; // // Created through ResetFlowInformation/UpdateFlowInformation // protected BasicBlockEdge[] m_predecessors; protected BasicBlockEdge[] m_successors; // // Constructor Methods // protected BasicBlock() // Default constructor required by TypeSystemSerializer. { #if TRACK_BASICBLOCK_IDENTITY m_identity = s_identity++; #endif m_index = -1; } protected BasicBlock( ControlFlowGraphState owner ) : this() { m_owner = owner; m_operators = Operator .SharedEmptyArray; m_protectedBy = ExceptionHandlerBasicBlock.SharedEmptyArray; m_qualifier = Qualifier.Normal; m_predecessors = BasicBlockEdge .SharedEmptyArray; m_successors = BasicBlockEdge .SharedEmptyArray; owner.Register( this ); } //--// // // Helper Methods // public abstract BasicBlock Clone( CloningContext context ); public BasicBlock RegisterAndCloneState( CloningContext context , BasicBlock clone ) { context.Register( this, clone ); CloneState( context, clone ); return clone; } public virtual void CloneState( CloningContext context , BasicBlock clone ) { clone.m_qualifier = m_qualifier; clone.m_operators = context.Clone( m_operators ); clone.m_protectedBy = context.Clone( m_protectedBy ); } //--// internal void BumpVersion() { m_owner.BumpVersion(); } internal void ResetFlowInformation() { m_predecessors = BasicBlockEdge.SharedEmptyArray; m_successors = BasicBlockEdge.SharedEmptyArray; } internal void UpdateFlowInformation() { // // NOTICE! // // It's important that we link first the normal edges and then the exception ones. // This way, when we build the spanning tree, it's guaranteed that the tree edges go // through the normal execution path and not through the exceptional one. // ControlOperator ctrl = this.FlowControl; if(ctrl != null) { ctrl.UpdateSuccessorInformationInner(); } foreach(BasicBlock protectedBy in m_protectedBy) { this.LinkToExceptionBasicBlock( protectedBy ); } } //--//--// public void LinkToNormalBasicBlock( BasicBlock successor ) { CHECKS.ASSERT( successor is ExceptionHandlerBasicBlock == false, "Cannot link from flow control to an exception basic block: {0} => {1}", this, successor ); LinkToInner( successor ); } public void LinkToExceptionBasicBlock( BasicBlock successor ) { CHECKS.ASSERT( successor is ExceptionHandlerBasicBlock == true, "Cannot use a normal basic block for exception handling: {0} => {1}", this, successor ); LinkToInner( successor ); } private void LinkToInner( BasicBlock successor ) { foreach(BasicBlockEdge edge in this.m_successors) { CHECKS.ASSERT( edge.Predecessor == this, "Found inconsistency in basic block linkage" ); if(edge.Successor == successor) { CHECKS.ASSERT( ArrayUtility.FindReferenceInNotNullArray( successor.m_predecessors, edge ) >= 0, "Found inconsistency in basic block linkage" ); return; } } BasicBlockEdge newEdge = new BasicBlockEdge( this, successor ); successor.m_predecessors = ArrayUtility.AppendToNotNullArray( successor.m_predecessors, newEdge ); this .m_successors = ArrayUtility.AppendToNotNullArray( this .m_successors , newEdge ); } public void Delete() { m_owner.Deregister( this ); m_owner = null; } public BasicBlock InsertNewSuccessor( BasicBlock oldBB ) { return InsertNewSuccessor( oldBB, new NormalBasicBlock( m_owner ) ); } public BasicBlock InsertNewSuccessor( BasicBlock oldBB , BasicBlock newBB ) { this.FlowControl.SubstituteTarget( oldBB, newBB ); newBB.AddOperator( UnconditionalControlOperator.New( null, oldBB ) ); newBB.NotifyNewPredecessor( this ); return newBB; } public BasicBlock InsertNewPredecessor() { return InsertNewPredecessor( new NormalBasicBlock( m_owner ) ); } public BasicBlock InsertNewPredecessor( BasicBlock newBB ) { BasicBlockEdge[] edges = this.Predecessors; newBB.AddOperator( UnconditionalControlOperator.New( null, this ) ); foreach(BasicBlockEdge edge in edges) { edge.Predecessor.FlowControl.SubstituteTarget( this, newBB ); } newBB.NotifyNewPredecessor( this ); return newBB; } //--// private void NotifyMerge( BasicBlock entryBB ) { foreach(BasicBlockEdge edge in this.Successors) { BasicBlock succ = edge.Successor; foreach(Operator op in succ.Operators) { op.NotifyMerge( entryBB, this ); } } } private void NotifyNewPredecessor( BasicBlock oldBB ) { foreach(BasicBlockEdge edge in this.Successors) { BasicBlock succ = edge.Successor; foreach(Operator op in succ.Operators) { op.NotifyNewPredecessor( oldBB, this ); } } } //--// public BasicBlockEdge FindForwardEdge( BasicBlock successor ) { foreach(BasicBlockEdge edge in m_successors) { if(edge.Successor == successor) { return edge; } } return null; } public BasicBlockEdge FindBackwardEdge( BasicBlock predecessor ) { foreach(BasicBlockEdge edge in m_predecessors) { if(edge.Predecessor == predecessor) { return edge; } } return null; } public bool IsProtectedBy( BasicBlock handler ) { foreach(BasicBlock bb in m_protectedBy) { if(bb == handler) { return true; } } return false; } public bool ShouldIncludeInScheduling( BasicBlock bbNext ) { var ctrl = this.FlowControl; return ctrl != null ? ctrl.ShouldIncludeInScheduling( bbNext ) : false; } //--// public void SetProtectedBy( ExceptionHandlerBasicBlock bb ) { BumpVersion(); m_protectedBy = ArrayUtility.AddUniqueToNotNullArray( m_protectedBy, bb ); } public bool SubstituteProtectedBy( ExceptionHandlerBasicBlock oldBB , ExceptionHandlerBasicBlock newBB ) { int pos = ArrayUtility.FindInNotNullArray( m_protectedBy, oldBB ); if(pos >= 0) { m_protectedBy = ArrayUtility.ReplaceAtPositionOfNotNullArray( m_protectedBy, pos, newBB ); BumpVersion(); return true; } return false; } public void ClearProtectedBy() { if (m_protectedBy.Length != 0) { m_protectedBy = ExceptionHandlerBasicBlock.SharedEmptyArray; BumpVersion(); } } //--// public bool IsDominatedBy( BasicBlock bbTarget , BitVector[] dominance ) { return dominance[this.SpanningTreeIndex][bbTarget.SpanningTreeIndex]; } public Operator GetOperator( Type target ) { foreach(Operator op in m_operators) { if(target.IsInstanceOfType( op )) { return op; } } return null; } public Operator GetFirstDifferentOperator( Type target ) { foreach(Operator op in m_operators) { if(target.IsInstanceOfType( op ) == false) { return op; } } return null; } public void AddOperator( Operator oper ) { CHECKS.ASSERT( !(oper is ControlOperator) || this.FlowControl == null, "Cannot add two control operators to a basic block" ); CHECKS.ASSERT( oper.BasicBlock == null , "Adding operator already part of another code sequence" ); CHECKS.ASSERT( oper.GetBasicBlockIndex() < 0 , "Adding operator already present in code sequence" ); BumpVersion(); oper.BasicBlock = this; int pos = m_operators.Length; if(oper is ControlOperator) { // // Make sure the ControlOperator is always the last one in the basic block. // } else if(pos > 0) { Operator ctrl = m_operators[pos-1]; if(ctrl is ControlOperator) { // // Insert before the control operator. // pos -= 1; } } m_operators = ArrayUtility.InsertAtPositionOfNotNullArray( m_operators, pos, oper ); } internal void AddAsFirstOperator( Operator oper ) { AddOperatorBefore( oper, m_operators[0] ); } internal void AddOperatorBefore( Operator oper , Operator operTarget ) { CHECKS.ASSERT( oper != null , "Missing source operator" ); CHECKS.ASSERT( operTarget != null , "Missing target operator" ); CHECKS.ASSERT( oper is ControlOperator == false , "Control operator can only be added at the end of a basic block" ); CHECKS.ASSERT( oper .BasicBlock == null , "Adding operator already part of another code sequence" ); CHECKS.ASSERT( operTarget.BasicBlock == this , "Target operator does not belong to this basic block" ); CHECKS.ASSERT( operTarget.GetBasicBlockIndex() >= 0, "Target operator does not belong to this basic block" ); CHECKS.ASSERT( oper .GetBasicBlockIndex() < 0, "Adding operator already present in code sequence" ); BumpVersion(); oper.BasicBlock = this; int pos = operTarget.GetBasicBlockIndex(); m_operators = ArrayUtility.InsertAtPositionOfNotNullArray( m_operators, pos, oper ); } internal void AddOperatorAfter( Operator operTarget , Operator oper ) { CHECKS.ASSERT( operTarget != null , "Missing target operator" ); CHECKS.ASSERT( operTarget is ControlOperator == false, "Target operator cannot be a control operator" ); AddOperatorBefore( oper, operTarget.GetNextOperator() ); } internal void RemoveOperator( Operator oper ) { CHECKS.ASSERT( oper.BasicBlock == this , "Removing operator part of another code sequence" ); CHECKS.ASSERT( oper.GetBasicBlockIndex() >= 0, "Removing operator not part of current basic block" ); BumpVersion(); int pos = oper.GetBasicBlockIndex(); m_operators = ArrayUtility.RemoveAtPositionFromNotNullArray( m_operators, pos ); oper.BasicBlock = null; } internal void SubstituteOperator( Operator opOld , Operator opNew , Operator.SubstitutionFlags flags ) { CHECKS.ASSERT( opOld.BasicBlock == this , "Target operator does not belong to this basic block" ); CHECKS.ASSERT( opNew.BasicBlock == null , "Substituting operator already part of another code sequence" ); CHECKS.ASSERT( (opOld is ControlOperator) == (opNew is ControlOperator), "Change substitute between incompatible operators ({0} <=> {1})", opOld, opNew ); BumpVersion(); if((flags & Operator.SubstitutionFlags.CopyAnnotations) != 0) { opNew.CopyAnnotations( opOld ); } int pos = opOld.GetBasicBlockIndex(); m_operators = ArrayUtility.ReplaceAtPositionOfNotNullArray( m_operators, pos, opNew ); opOld.BasicBlock = null; opNew.BasicBlock = this; } public void Merge( BasicBlock bbNext ) { CHECKS.ASSERT( this.Owner == bbNext.Owner, "Cannot merge basic blocks from different flow graphs!" ); ControlOperator ctrl = this.FlowControl; CHECKS.ASSERT( ctrl is UnconditionalControlOperator && ((UnconditionalControlOperator)ctrl).TargetBranch == bbNext && bbNext.Predecessors.Length == 1 , "Cannot merge two non-consecutive basic blocks" ); bbNext.NotifyMerge( this ); ctrl.Delete(); m_operators = ArrayUtility.AppendNotNullArrayToNotNullArray( m_operators, bbNext.Operators ); foreach(Operator op in bbNext.Operators) { op.BasicBlock = this; } this.NotifyNewPredecessor( bbNext ); } public NormalBasicBlock SplitAtOperator( Operator oper , bool fRemoveOperator , bool fAddFlowControl ) { CHECKS.ASSERT( this is NormalBasicBlock , "Cannot split non-normal basic block" ); CHECKS.ASSERT( !(oper is ControlOperator), "Cannot split on control operator" ); CHECKS.ASSERT( oper.BasicBlock == this , "Target operator does not belong to this basic block" ); BumpVersion(); // // Create new basic block, copying the exception handler sets. // NormalBasicBlock bb = NormalBasicBlock.CreateWithSameProtection( this ); switch(this.Annotation) { case Qualifier.EntryInjectionEnd: this.Annotation = BasicBlock.Qualifier.Normal; bb .Annotation = BasicBlock.Qualifier.EntryInjectionEnd; break; case Qualifier.ExitInjectionEnd: this.Annotation = BasicBlock.Qualifier.Normal; bb .Annotation = BasicBlock.Qualifier.ExitInjectionEnd; break; } // // Redistribute operators, redirect post ones to the new basic block, add branch from pre ones. // int pos = oper.GetBasicBlockIndex(); int pos2; if(fRemoveOperator) { Operator next = oper.GetNextOperator(); if(next != null) { pos2 = next.GetBasicBlockIndex(); } else { pos2 = m_operators.Length; } } else { pos2 = pos; } Operator[] preOps = ArrayUtility.ExtractSliceFromNotNullArray( m_operators, 0 , pos ); Operator[] postOps = ArrayUtility.ExtractSliceFromNotNullArray( m_operators, pos2, m_operators.Length - pos2 ); this.m_operators = preOps; bb .m_operators = postOps; foreach(Operator op in postOps) { op.Retarget( bb ); } if(fAddFlowControl) { AddOperator( UnconditionalControlOperator.New( null, bb ) ); } if(fRemoveOperator) { oper.ClearState(); } bb.NotifyNewPredecessor( this ); return bb; } //--// // // Example: // // bb.PerformActionOnValues( delegate( Expression ex ) // { // TemporaryVariableExpression var = ex as TemporaryVariableExpression; // // if(var != null) // { // SetTemporary( var ); // } // } ); // public void PerformActionOnValues( Action< Expression > action ) { foreach(var op in m_operators) { foreach(var ex in op.Results) { if(ex != null) { action( ex ); } } foreach(var ex in op.Arguments) { if(ex != null) { action( ex ); } } } } //--// public virtual void ApplyTransformation( TransformationContextForIR context ) { context.Push( this ); context.Transform( ref m_owner ); context.Transform( ref m_index ); context.Transform( ref m_operators ); context.Transform( ref m_protectedBy ); context.Transform( ref m_qualifier ); context.Pop(); } //--// // // Access Methods // public ControlFlowGraphState Owner { get { return m_owner; } } public int SpanningTreeIndex { get { return m_index; } set { m_index = value; } } public Operator[] Operators { get { return m_operators; } } [System.Diagnostics.DebuggerBrowsable( System.Diagnostics.DebuggerBrowsableState.Never )] public BasicBlockEdge[] Predecessors { get { m_owner.UpdateFlowInformation(); return m_predecessors; } } [System.Diagnostics.DebuggerBrowsable( System.Diagnostics.DebuggerBrowsableState.Never )] public BasicBlockEdge[] Successors { get { m_owner.UpdateFlowInformation(); return m_successors; } } public ExceptionHandlerBasicBlock[] ProtectedBy { get { return m_protectedBy; } } public Qualifier Annotation { get { return m_qualifier; } set { m_qualifier = value; } } public ControlOperator FlowControl { get { int len = m_operators.Length; if(len > 0) { Operator op = m_operators[len-1]; if(op is ControlOperator) { return (ControlOperator)op; } } return null; } set { BumpVersion(); value.BasicBlock = this; int len = m_operators.Length; if(len > 0) { Operator op = m_operators[len-1]; if(op is ControlOperator) { // // Update existing control operator. // m_operators[len-1] = value; return; } } m_operators = ArrayUtility.AppendToNotNullArray( m_operators, (Operator)value ); } } public BasicBlock FirstPredecessor { get { return this.Predecessors[0].Predecessor; } } public BasicBlock FirstSuccessor { get { return this.Successors[0].Successor; } } public Operator FirstOperator { get { return m_operators[0]; } } public Operator LastOperator { get { return m_operators[m_operators.Length - 1]; } } //--// // // Debug Methods // public override string ToString() { string fmt = (m_owner == null) ? "{0}" : "{0} of {1}"; return string.Format( fmt, this.ToShortString(), m_owner ); } public abstract string ToShortString(); //--// protected string ToShortStringInner( string prefix ) { return string.Format( "{0}({1})", prefix, m_index ); } } } ================================================ FILE: Zelig/Zelig/CompileTime/CodeGenerator/IntermediateRepresentation/BasicBlocks/BasicBlockEdge.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // namespace Microsoft.Zelig.CodeGeneration.IR { using System; public sealed class BasicBlockEdge { public static readonly BasicBlockEdge[] SharedEmptyArray = new BasicBlockEdge[0]; // // State // private readonly BasicBlock m_predecessor; private readonly BasicBlock m_successor; private BasicBlockEdgeClass m_edgeClass; // // Constructor Methods // internal BasicBlockEdge( BasicBlock predecessor , BasicBlock successor ) { m_predecessor = predecessor; m_successor = successor; m_edgeClass = BasicBlockEdgeClass.Unknown; } //--// // // Helper Methods // //--// // // Access Methods // public BasicBlock Predecessor { get { return m_predecessor; } } public BasicBlock Successor { get { return m_successor; } } public BasicBlockEdgeClass EdgeClass { get { return m_edgeClass; } set { m_edgeClass = value; } } } } ================================================ FILE: Zelig/Zelig/CompileTime/CodeGenerator/IntermediateRepresentation/BasicBlocks/BasicBlockEdgeClass.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // namespace Microsoft.Zelig.CodeGeneration.IR { using System; public enum BasicBlockEdgeClass { Unknown , TreeEdge , ForwardEdge, BackEdge , CrossEdge , } } ================================================ FILE: Zelig/Zelig/CompileTime/CodeGenerator/IntermediateRepresentation/BasicBlocks/Cloning/CloneForwardGraph.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // namespace Microsoft.Zelig.CodeGeneration.IR { using System; using System.Collections.Generic; using Microsoft.Zelig.Runtime.TypeSystem; public sealed class CloneForwardGraph : CloningContext { // // Constructor Methods // public CloneForwardGraph( ControlFlowGraphState cfgSource , ControlFlowGraphState cfgDestination , InstantiationContext ic ) : base( cfgSource, cfgDestination, ic ) { } } } ================================================ FILE: Zelig/Zelig/CompileTime/CodeGenerator/IntermediateRepresentation/BasicBlocks/Cloning/CloneForwardGraphButLinkToExceptionHandlers.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // namespace Microsoft.Zelig.CodeGeneration.IR { using System; using System.Collections.Generic; using Microsoft.Zelig.Runtime.TypeSystem; public sealed class CloneForwardGraphButLinkToExceptionHandlers : CloningContext { // // Constructor Methods // public CloneForwardGraphButLinkToExceptionHandlers( ControlFlowGraphState cfgSource , ControlFlowGraphState cfgDestination , InstantiationContext ic ) : base( cfgSource, cfgDestination, ic ) { } //--// protected override bool FoundInCache( object from , out object to ) { if(base.FoundInCache( from, out to )) return true; if(from is ExceptionHandlerBasicBlock) { to = from; return true; } return false; } } } ================================================ FILE: Zelig/Zelig/CompileTime/CodeGenerator/IntermediateRepresentation/BasicBlocks/Cloning/CloneSingleBasicBlock.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // namespace Microsoft.Zelig.CodeGeneration.IR { using System; using System.Collections.Generic; using Microsoft.Zelig.Runtime.TypeSystem; public sealed class CloneSingleBasicBlock : CloningContext { // // State // private readonly BasicBlock m_singleBasicBlockToClone; // // Constructor Methods // private CloneSingleBasicBlock( BasicBlock basicBlock ) : base( basicBlock.Owner, basicBlock.Owner, null ) { m_singleBasicBlockToClone = basicBlock; } //--// public static BasicBlock Execute( BasicBlock block ) { CloningContext context = new CloneSingleBasicBlock( block ); return context.Clone( block ); } //--// protected override bool FoundInCache( object from , out object to ) { if(base.FoundInCache( from, out to )) return true; if(from is BasicBlock && from != m_singleBasicBlockToClone) { to = from; return true; } if(from is Expression) { to = from; return true; } return false; } } } ================================================ FILE: Zelig/Zelig/CompileTime/CodeGenerator/IntermediateRepresentation/BasicBlocks/Cloning/CloningContext.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // namespace Microsoft.Zelig.CodeGeneration.IR { using System; using System.Collections.Generic; using Microsoft.Zelig.Runtime.TypeSystem; public abstract class CloningContext { // // State // protected readonly ControlFlowGraphState m_cfgDestination; protected readonly ControlFlowGraphState m_cfgSource; protected readonly InstantiationContext m_ic; protected readonly GrowOnlyHashTable< object, object > m_cloned = HashTableFactory.New< object, object >(); // // Constructor Methods // protected CloningContext( ControlFlowGraphState cfgSource , ControlFlowGraphState cfgDestination , InstantiationContext ic ) { m_cfgSource = cfgSource; m_cfgDestination = cfgDestination; m_ic = ic; } //--// public T ConvertType( T td ) where T : TypeRepresentation { if(m_ic != null) { td = (T)m_ic.Instantiate( td ); } return td; } public T ConvertField( T fd ) where T : FieldRepresentation { if(m_ic != null) { fd = (T)m_ic.Instantiate( fd ); } return fd; } public T[] ConvertFields( T[] fdArray ) where T : FieldRepresentation { if(m_ic != null && fdArray != null) { fdArray = (T[])m_ic.Instantiate( fdArray ); } return fdArray; } public T ConvertMethod( T md ) where T : MethodRepresentation { if(m_ic != null) { md = (T)m_ic.Instantiate( md ); } return md; } public T[] ConvertMethods( T[] mdArray ) where T : MethodRepresentation { if(m_ic != null && mdArray != null) { mdArray = (T[])m_ic.Instantiate( mdArray ); } return mdArray; } //--// protected virtual void RegisterInner( object from , object to ) { m_cloned[from] = to; } public void Register( BasicBlock from , BasicBlock to ) { RegisterInner( from, to ); } public void Register( Expression from , Expression to ) { RegisterInner( from, to ); } public void Register( Operator from , Operator to ) { RegisterInner( from, to ); } public void Register( Annotation from , Annotation to ) { RegisterInner( from, to ); } public void Register( ExceptionClause from , ExceptionClause to ) { RegisterInner( from, to ); } public T LookupRegistered( T key ) { object val; m_cloned.TryGetValue( key, out val ); return (T)val; } //--// protected virtual bool FoundInCache( object from , out object to ) { return m_cloned.TryGetValue( from, out to ); } private bool ShouldClone( ref T from ) { object o; if(from == null) return false; if(FoundInCache( from, out o )) { from = (T)o; return false; } return true; } private bool ShouldClone( ref T[] from ) { object o; if(from == null) return false; if(from.Length == 0) return false; if(FoundInCache( from, out o )) { from = (T[])o; return false; } return true; } //--// public BasicBlock Clone( BasicBlock from ) { if(!ShouldClone( ref from )) return from; BasicBlock clone = from.Clone( this ); return clone; } public BasicBlock[] Clone( BasicBlock[] from ) { if(!ShouldClone( ref from )) return from; BasicBlock[] clone = new BasicBlock[from.Length]; m_cloned[from] = clone; for(int i = 0; i < from.Length; i++) { clone[i] = Clone( from[i] ); } return clone; } public ExceptionHandlerBasicBlock[] Clone( ExceptionHandlerBasicBlock[] from ) { if(!ShouldClone( ref from )) return from; ExceptionHandlerBasicBlock[] clone = new ExceptionHandlerBasicBlock[from.Length]; m_cloned[from] = clone; for(int i = 0; i < from.Length; i++) { clone[i] = (ExceptionHandlerBasicBlock)Clone( from[i] ); } return clone; } //--// public Expression Clone( Expression from ) { if(!ShouldClone( ref from )) return from; if(m_cfgSource == m_cfgDestination) { // // Same flow graph, we don't create new local and argument variables. // if(from is ArgumentVariableExpression) { return from; } if(from is LocalVariableExpression) { return from; } } Expression clone = from.Clone( this ); return clone; } public Expression[] Clone( Expression[] from ) { if(!ShouldClone( ref from )) return from; Expression[] clone = new Expression[from.Length]; m_cloned[from] = clone; for(int i = 0; i < from.Length; i++) { clone[i] = Clone( from[i] ); } return clone; } public VariableExpression[] Clone( VariableExpression[] from ) { if(!ShouldClone( ref from )) return from; VariableExpression[] clone = new VariableExpression[from.Length]; m_cloned[from] = clone; for(int i = 0; i < from.Length; i++) { clone[i] = (VariableExpression)Clone( from[i] ); } return clone; } //--// public Operator Clone( Operator from ) { if(!ShouldClone( ref from )) return from; Operator clone = from.Clone( this ); return clone; } public Operator[] Clone( Operator[] from ) { if(!ShouldClone( ref from )) return from; Operator[] clone = new Operator[from.Length]; m_cloned[from] = clone; for(int i = 0; i < from.Length; i++) { clone[i] = Clone( from[i] ); } return clone; } //--// public Annotation Clone( Annotation from ) { if(!ShouldClone( ref from )) return from; Annotation clone = from.Clone( this ); return clone; } public Annotation[] Clone( Annotation[] from ) { if(!ShouldClone( ref from )) return from; Annotation[] clone = new Annotation[from.Length]; m_cloned[from] = clone; for(int i = 0; i < from.Length; i++) { clone[i] = Clone( from[i] ); } return clone; } //--// public ExceptionClause Clone( ExceptionClause from ) { if(!ShouldClone( ref from )) return from; ExceptionClause clone = from.Clone( this ); return clone; } public ExceptionClause[] Clone( ExceptionClause[] from ) { if(!ShouldClone( ref from )) return from; ExceptionClause[] clone = new ExceptionClause[from.Length]; m_cloned[from] = clone; for(int i = 0; i < from.Length; i++) { clone[i] = Clone( from[i] ); } return clone; } //--// // // Access Methods // public ControlFlowGraphState ControlFlowGraphSource { get { return m_cfgSource; } } public ControlFlowGraphState ControlFlowGraphDestination { get { return m_cfgDestination; } } public TypeSystemForIR TypeSystem { get { return m_cfgDestination.TypeSystemForIR; } } } } ================================================ FILE: Zelig/Zelig/CompileTime/CodeGenerator/IntermediateRepresentation/BasicBlocks/CompilationConstraints.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // namespace Microsoft.Zelig.CodeGeneration.IR { using System; using System.Collections.Generic; using Microsoft.Zelig.Runtime.TypeSystem; public enum CompilationConstraints { Allocations_ON , Allocations_OFF , StackAccess_ON , StackAccess_OFF , BoundsChecks_ON , BoundsChecks_OFF , BoundsChecks_OFF_DEEP, NullChecks_ON , NullChecks_OFF , NullChecks_OFF_DEEP , } } ================================================ FILE: Zelig/Zelig/CompileTime/CodeGenerator/IntermediateRepresentation/BasicBlocks/ControlFlowGraphState.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // #define CACHEINFO_ENABLE_TRACKING_THREADS //#define CACHEINFO_DEBUG_THREADING_ISSUES namespace Microsoft.Zelig.CodeGeneration.IR { using System; using System.Collections.Generic; using Microsoft.Zelig.Runtime.TypeSystem; public abstract class ControlFlowGraphState { public static CompilationConstraints[] SharedEmptyCompilationConstraintsArray = new CompilationConstraints[0]; public abstract class CachedInfo : IDisposable { public static CachedInfo[] SharedEmptyArray = new CachedInfo[0]; // // State // protected ControlFlowGraphState m_owner; private int m_version; private int m_lockCount; #if CACHEINFO_ENABLE_TRACKING_THREADS private System.Threading.Thread m_lockOwner; #if CACHEINFO_DEBUG_THREADING_ISSUES protected System.Diagnostics.StackTrace m_lockTrace; #endif #endif // // Constructor Methods // protected CachedInfo() { } // // Helper Methods // public void Dispose() { Unlock(); } public void Lock() { #if CACHEINFO_ENABLE_TRACKING_THREADS System.Threading.Thread thisThread = System.Threading.Thread.CurrentThread; System.Threading.Thread activeThread = System.Threading.Interlocked.CompareExchange( ref m_lockOwner, thisThread, null ); CHECKS.ASSERT( activeThread == null || activeThread == thisThread, "Lock on {0} for method '{1}' already claimed", this.GetType().FullName, m_owner.Method.ToShortString() ); #if CACHEINFO_DEBUG_THREADING_ISSUES if(m_lockCount == 0) { m_lockTrace = new System.Diagnostics.StackTrace(); } #endif #endif m_lockCount++; } public void Unlock() { #if CACHEINFO_ENABLE_TRACKING_THREADS CHECKS.ASSERT( System.Threading.Thread.CurrentThread == m_lockOwner, "Lock on {0} not owned by current thread", this.GetType().FullName ); #endif CHECKS.ASSERT( m_lockCount > 0, "Underflow for lock on {0}", this.GetType().FullName ); m_lockCount--; #if CACHEINFO_ENABLE_TRACKING_THREADS if(m_lockCount == 0) { m_lockOwner = null; #if CACHEINFO_DEBUG_THREADING_ISSUES m_lockTrace = null; #endif } #endif } public void RefreshIfNeeded() { ThreadLockInfo.Assert( m_owner.Method ); if(m_version != m_owner.m_version) { if(m_lockCount != 0) { throw TypeConsistencyErrorException.Create( "Detected attempt to modify state of Control Flow Graph for {0}", this.GetType().FullName ); } Update(); m_version = m_owner.m_version; m_owner.LatestCachedVersion = m_version; } } protected abstract void Update(); // // Access Methods // internal ControlFlowGraphState Owner { set { m_owner = value; } } } //--// class ThreadLockInfo : IDisposable { internal class ExceptionInfo : IDisposable { // // Constructor Methods // internal ExceptionInfo( MethodRepresentation md ) { s_lockException = md; } // // Helper Methods // public void Dispose() { s_lockException = null; } } // // State // [ThreadStatic] private static MethodRepresentation s_lock; [ThreadStatic] private static MethodRepresentation s_lockException; // // Constructor Methods // internal ThreadLockInfo( MethodRepresentation md ) { Assert( md ); s_lock = md; } internal ThreadLockInfo( MethodRepresentation md , MethodRepresentation md2 ) { Assert( md ); s_lock = md; s_lockException = md2; } // // Helper Methods // public void Dispose() { s_lock = null; s_lockException = null; } internal static void Assert( MethodRepresentation md ) { if(s_lock == null || md == s_lock || md == s_lockException) { return; } throw TypeConsistencyErrorException.Create( "Detected attempt to access state of Control Flow Graph for '{0}' while thread is locked to access only '{1}'", md.ToShortString(), s_lock.ToShortString() ); } } class GroupLockInfo : IDisposable { // // State // private readonly IDisposable[] m_locks; // // Constructor Methods // internal GroupLockInfo( IDisposable[] locks ) { m_locks = locks; } // // Helper Methods // public void Dispose() { // // Release in opposite order. // for(int i = m_locks.Length; --i >= 0; ) { m_locks[i].Dispose(); } } } //--// class CachedInfo_FlowInformation : CachedInfo { // // Helper Methods // protected override void Update() { using(new PerformanceCounters.ContextualTiming( m_owner, "FlowInformation" )) { foreach(BasicBlock bb in m_owner.m_basicBlocks) { bb.ResetFlowInformation(); } foreach(BasicBlock bb in m_owner.m_basicBlocks) { bb.UpdateFlowInformation(); } } } } //--// // // State // protected MethodRepresentation m_md; protected int m_version; protected EntryBasicBlock m_entryBasicBlock; protected ExitBasicBlock m_exitBasicBlock; protected BasicBlock[] m_basicBlocks; // This is the set of all the basic blocks in the CFG. protected VariableExpression m_returnValue; protected VariableExpression[] m_arguments; protected VariableExpression[] m_variables; protected int m_variablesCount; protected CachedInfo[] m_cache; // // Constructor Methods // protected ControlFlowGraphState() // Default constructor required by TypeSystemSerializer. { m_cache = CachedInfo.SharedEmptyArray; } protected ControlFlowGraphState( MethodRepresentation md ) { m_md = md; m_version = 1; m_basicBlocks = BasicBlock.SharedEmptyArray; m_variables = VariableExpression.SharedEmptyArray; m_cache = CachedInfo.SharedEmptyArray; } protected ControlFlowGraphState( ControlFlowGraphState source ) : this( source.m_md ) { } //--// // // Helper Methods // protected virtual void CloneVariables( CloningContext context , ControlFlowGraphState source ) { VariableExpression var; var = source.m_returnValue; if(var != null) { m_returnValue = AllocateTemporary( var.Type, var.DebugName ); context.Register( var, m_returnValue ); } //--// VariableExpression[] args = source.m_arguments; int argsNum = args.Length; m_arguments = new VariableExpression[argsNum]; for(int i = 0; i < argsNum; i++) { var = args[i]; m_arguments[i] = new ArgumentVariableExpression( var.Type, var.DebugName, i ); context.Register( var, m_arguments[i] ); } } //--// protected void TrackVariable( VariableExpression var ) { if(m_variablesCount == m_variables.Length) { m_variables = ArrayUtility.EnsureSizeOfNotNullArray( m_variables, m_variablesCount + 16 ); } m_variables[m_variablesCount++] = var; } public LocalVariableExpression AllocateLocal( TypeRepresentation td , VariableExpression.DebugInfo debugInfo ) { LocalVariableExpression newLocal = new LocalVariableExpression( td, debugInfo ); TrackVariable( newLocal ); return newLocal; } public TemporaryVariableExpression AllocateTemporary( TypeRepresentation td , VariableExpression.DebugInfo debugInfo ) { TemporaryVariableExpression newTmp = new TemporaryVariableExpression( td, debugInfo ); TrackVariable( newTmp ); return newTmp; } public ExceptionObjectVariableExpression AllocateExceptionObjectVariable( TypeRepresentation td ) { ExceptionObjectVariableExpression newEx = new ExceptionObjectVariableExpression( td, null ); TrackVariable( newEx ); return newEx; } //--// internal void Register( BasicBlock basicBlock ) { BumpVersion(); if(basicBlock is EntryBasicBlock) { CHECKS.ASSERT( m_entryBasicBlock == null, "Entry Basic Block already exists" ); m_entryBasicBlock = (EntryBasicBlock)basicBlock; } else if(basicBlock is ExitBasicBlock) { CHECKS.ASSERT( m_exitBasicBlock == null, "Exit Basic Block already exists" ); m_exitBasicBlock = (ExitBasicBlock)basicBlock; } m_basicBlocks = ArrayUtility.AddUniqueToNotNullArray( m_basicBlocks, basicBlock ); } internal void Deregister( BasicBlock basicBlock ) { BumpVersion(); if(basicBlock == m_entryBasicBlock) { m_entryBasicBlock = null; } else if(basicBlock == m_exitBasicBlock) { m_exitBasicBlock = null; } } internal void BumpVersion() { m_version++; } //--// public static IDisposable LockThreadToMethod( MethodRepresentation md ) { return new ThreadLockInfo( md ); } public static IDisposable AddExceptionToThreadMethodLock( MethodRepresentation md ) { return new ThreadLockInfo.ExceptionInfo( md ); } public IDisposable GroupLock( params IDisposable[] locks ) { return new GroupLockInfo( locks ); } protected T GetCachedInfo< T >() where T : CachedInfo, new() { foreach(CachedInfo ci in m_cache) { if(ci is T) { ci.RefreshIfNeeded(); return (T)ci; } } T newCI = new T(); newCI.Owner = this; m_cache = ArrayUtility.AppendToNotNullArray( m_cache, newCI ); newCI.RefreshIfNeeded(); return newCI; } public void UpdateFlowInformation() { GetCachedInfo< CachedInfo_FlowInformation >(); } public IDisposable LockFlowInformation() { var ci = GetCachedInfo< CachedInfo_FlowInformation >(); ci.Lock(); return ci; } //--// int m_checkpointCachedVersion = -1; protected int LatestCachedVersion { get; set; } public void ResetCacheCheckpoint( ) { m_checkpointCachedVersion = LatestCachedVersion; } public void AssertNoCacheRefreshSinceCheckpoint( ) { CHECKS.ASSERT( m_checkpointCachedVersion == LatestCachedVersion, "Cached info updated since checkpoint. The cache used was stale!" ); } //--// protected void InnerApplyTransformation( TransformationContextForIR context ) { context.Transform( ref m_md ); context.Transform( ref m_version ); context.Transform( ref m_entryBasicBlock ); context.Transform( ref m_exitBasicBlock ); context.Transform( ref m_basicBlocks ); context.Transform( ref m_returnValue ); context.Transform( ref m_arguments ); context.Transform( ref m_variables ); context.Transform( ref m_variablesCount ); } //--// public void PerformActionOnOperators( Action action ) { foreach(BasicBlock bb in m_basicBlocks) { foreach(Operator op in bb.Operators) { action( op ); } } } //--// public BasicBlock FirstBasicBlock { get { if(m_basicBlocks != null && m_basicBlocks.Length > 0) { return m_basicBlocks[0]; } return CreateFirstNormalBasicBlock(); } } public NormalBasicBlock CreateFirstNormalBasicBlock() { // // Important: get 'NormalizedEntryBasicBlock' before allocating the new basic block, or it will be reclaimed!! // var bbPrev = this.NormalizedEntryBasicBlock; var bbNext = this.NormalizedExitBasicBlock; var bb = new NormalBasicBlock( this ); bbPrev.FlowControl = UnconditionalControlOperator.New( null, bb ); bb .FlowControl = UnconditionalControlOperator.New( null, bbNext ); return bb; } public NormalBasicBlock CreateLastNormalBasicBlock() { // // Important: get 'NormalizedExitBasicBlock' before allocating the new basic block, or it will be reclaimed!! // var bbNext = this.NormalizedExitBasicBlock; var bb = new NormalBasicBlock( this ); bb.FlowControl = UnconditionalControlOperator.New( null, bbNext ); return bb; } public void AddReturnOperator() { // // Create proper flow control for exit basic block. // ControlOperator op; if(m_returnValue != null) { op = ReturnControlOperator.New( m_returnValue ); } else { op = ReturnControlOperator.New(); } m_exitBasicBlock.AddOperator( op ); } public Operator GenerateVariableInitialization( Debugging.DebugInfo debugInfo , VariableExpression var ) { return GenerateVariableInitialization( debugInfo, var, var.Type, false ); } public abstract Operator GenerateVariableInitialization( Debugging.DebugInfo debugInfo , Expression var , TypeRepresentation td , bool fThroughPointer ); public abstract BasicBlock GetInjectionPoint( BasicBlock.Qualifier qualifier ); //--// public virtual void RenumberVariables() { int numLocal = 0; int numTmp = 0; int numEx = 0; foreach(VariableExpression var in m_variables) { if(var is LocalVariableExpression) { var.Number = numLocal++; } else if(var is TemporaryVariableExpression) { var.Number = numTmp++; } else if(var is ExceptionObjectVariableExpression) { var.Number = numEx++; } } } //--// public static bool SameCompilationConstraints( CompilationConstraints[] ccArray1 , CompilationConstraints[] ccArray2 ) { int len1 = ccArray1.Length; int len2 = ccArray2.Length; if(len1 != len2) { return false; } for(int i = 0; i < len1; i++) { if(ccArray1[i] != ccArray2[i]) { return false; } } return true; } public static CompilationConstraints[] AddCompilationConstraint( CompilationConstraints[] ccArray , CompilationConstraints cc ) { int pos = 0; for(; pos < ccArray.Length; pos++) { CompilationConstraints cc2 = ccArray[pos]; if(cc2 == cc) { return ccArray; } if(cc2 > cc) { break; } } return ArrayUtility.InsertAtPositionOfNotNullArray( ccArray, pos, cc ); } public static CompilationConstraints[] RemoveCompilationConstraint( CompilationConstraints[] ccArray , CompilationConstraints cc ) { for(int pos = 0; pos < ccArray.Length; pos++) { CompilationConstraints cc2 = ccArray[pos]; if(cc2 == cc) { return ArrayUtility.RemoveAtPositionFromNotNullArray( ccArray, pos ); } if(cc2 > cc) { break; } } return ccArray; } public static bool HasCompilationConstraint( CompilationConstraints[] ccArray , CompilationConstraints cc ) { for(int pos = 0; pos < ccArray.Length; pos++) { CompilationConstraints cc2 = ccArray[pos]; if(cc2 == cc) { return true; } if(cc2 > cc) { break; } } return false; } public static bool HasAnyCompilationConstraint( CompilationConstraints[] ccTarget , params CompilationConstraints[] ccFilter ) { CompilationConstraints match; return HasAnyCompilationConstraint( ccTarget, out match, ccFilter ); } public static bool HasAnyCompilationConstraint( CompilationConstraints[] ccTarget , out CompilationConstraints match , params CompilationConstraints[] ccFilter ) { foreach(CompilationConstraints cc in ccFilter) { if(HasCompilationConstraint( ccTarget, cc )) { match = cc; return true; } } match = default(CompilationConstraints); return false; } //--// public static Operator CheckSingleUse( Operator[][] useChains , VariableExpression var ) { Operator[] uses = useChains[var.SpanningTreeIndex]; if(uses.Length == 1) { return uses[0]; } return null; } public static Operator CheckSingleDefinition( Operator[][] defChains , VariableExpression var ) { Operator[] defs = defChains[var.SpanningTreeIndex]; if(defs.Length == 1) { return defs[0]; } return null; } public static Operator CheckSingleDefinition( GrowOnlyHashTable< VariableExpression, Operator > defLookup , Expression ex ) { VariableExpression var = ex as VariableExpression; if(var != null) { Operator def; if(defLookup.TryGetValue( var, out def )) { return def; } } return null; } //--// // // Access Methods // public abstract TypeSystemForIR TypeSystemForIR { get; } public CompilationConstraints[] CompilationConstraintsArray { get { CompilationConstraints[] res = SharedEmptyCompilationConstraintsArray; MethodRepresentation.BuildTimeAttributes bta = m_md.BuildTimeFlags; if ((bta & MethodRepresentation.BuildTimeAttributes.CanAllocate ) != 0) res = AddCompilationConstraint( res, CompilationConstraints.Allocations_ON ); else if((bta & MethodRepresentation.BuildTimeAttributes.CannotAllocate ) != 0) res = AddCompilationConstraint( res, CompilationConstraints.Allocations_OFF ); if ((bta & MethodRepresentation.BuildTimeAttributes.StackAvailable ) != 0) res = AddCompilationConstraint( res, CompilationConstraints.StackAccess_ON ); else if((bta & MethodRepresentation.BuildTimeAttributes.StackNotAvailable ) != 0) res = AddCompilationConstraint( res, CompilationConstraints.StackAccess_OFF ); if ((bta & MethodRepresentation.BuildTimeAttributes.EnableBoundsChecks ) != 0) res = AddCompilationConstraint( res, CompilationConstraints.BoundsChecks_ON ); else if((bta & MethodRepresentation.BuildTimeAttributes.DisableBoundsChecks ) != 0) res = AddCompilationConstraint( res, CompilationConstraints.BoundsChecks_OFF ); else if((bta & MethodRepresentation.BuildTimeAttributes.DisableDeepBoundsChecks) != 0) res = AddCompilationConstraint( res, CompilationConstraints.BoundsChecks_OFF_DEEP ); if ((bta & MethodRepresentation.BuildTimeAttributes.EnableNullChecks ) != 0) res = AddCompilationConstraint( res, CompilationConstraints.NullChecks_ON ); else if((bta & MethodRepresentation.BuildTimeAttributes.DisableNullChecks ) != 0) res = AddCompilationConstraint( res, CompilationConstraints.NullChecks_OFF ); else if((bta & MethodRepresentation.BuildTimeAttributes.DisableDeepNullChecks ) != 0) res = AddCompilationConstraint( res, CompilationConstraints.NullChecks_OFF_DEEP ); return res; } } public MethodRepresentation Method { get { return m_md; } } public EntryBasicBlock EntryBasicBlock { get { return m_entryBasicBlock; } } public ExitBasicBlock ExitBasicBlock { get { return m_exitBasicBlock; } } public BasicBlock NormalizedEntryBasicBlock { get { return this.GetInjectionPoint( BasicBlock.Qualifier.EntryInjectionStart ); } } public BasicBlock NormalizedExitBasicBlock { get { return this.GetInjectionPoint( BasicBlock.Qualifier.EpilogueStart ); } } public VariableExpression ReturnValue { get { return m_returnValue; } } public VariableExpression[] Arguments { get { return m_arguments; } } public int Version { get { return m_version; } } //--// // // Debug Methods // public override string ToString() { return string.Format( "FlowGraph({0})", m_md.ToShortString() ); } public void Dump( IIntermediateRepresentationDumper dumper ) { dumper.DumpGraph( this ); } public abstract string ToPrettyString( Operator op ); } } ================================================ FILE: Zelig/Zelig/CompileTime/CodeGenerator/IntermediateRepresentation/BasicBlocks/EntryBasicBlock.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // namespace Microsoft.Zelig.CodeGeneration.IR { using System; using System.Collections.Generic; public sealed class EntryBasicBlock : BasicBlock { // // Constructor Methods // public EntryBasicBlock( ControlFlowGraphState owner ) : base( owner ) { } //--// // // Helper Methods // public override BasicBlock Clone( CloningContext context ) { return RegisterAndCloneState( context, new EntryBasicBlock( context.ControlFlowGraphDestination ) ); } //--// // // Debug Methods // public override string ToShortString() { return ToShortStringInner( "EntryBasicBlock" ); } } } ================================================ FILE: Zelig/Zelig/CompileTime/CodeGenerator/IntermediateRepresentation/BasicBlocks/ExceptionClause.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // namespace Microsoft.Zelig.CodeGeneration.IR { using System; using System.Collections.Generic; using Microsoft.Zelig.Runtime.TypeSystem; public sealed class ExceptionClause { public static readonly ExceptionClause[] SharedEmptyArray = new ExceptionClause[0]; // // Internal Classes // public enum ExceptionFlag { None = 0x0000, Filter = 0x0001, Finally = 0x0002, Fault = 0x0004, } // // State // private ExceptionFlag m_flags; private TypeRepresentation m_classObject; // // Constructor Methods // public ExceptionClause( ExceptionFlag flags , TypeRepresentation classObject ) { m_flags = flags; m_classObject = classObject; } //--// // // Helper Methods // public ExceptionClause Clone( CloningContext context ) { TypeRepresentation classObject = context.ConvertType( m_classObject ); ExceptionClause clone = new ExceptionClause( m_flags, classObject ); context.Register( this, clone ); return clone; } //--// public void ApplyTransformation( TransformationContextForIR context ) { context.Push( this ); context.Transform( ref m_flags ); context.Transform( ref m_classObject ); context.Pop(); } // // Access Methods // public ExceptionFlag Flags { get { return m_flags; } } public TypeRepresentation ClassObject { get { return m_classObject; } } // // Debug Methods // public override String ToString() { System.Text.StringBuilder sb = new System.Text.StringBuilder( "EHClause(" ); sb.Append( m_flags ); sb.Append( "," ); sb.Append( m_classObject ); sb.Append( ")" ); return sb.ToString(); } } } ================================================ FILE: Zelig/Zelig/CompileTime/CodeGenerator/IntermediateRepresentation/BasicBlocks/ExceptionHandlerBasicBlock.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // namespace Microsoft.Zelig.CodeGeneration.IR { using System; using System.Collections.Generic; using Microsoft.Zelig.Runtime.TypeSystem; public sealed class ExceptionHandlerBasicBlock : BasicBlock { public static new readonly ExceptionHandlerBasicBlock[] SharedEmptyArray = new ExceptionHandlerBasicBlock[0]; // // State // private ExceptionClause[] m_handlerFor; // // Constructor Methods // public ExceptionHandlerBasicBlock( ControlFlowGraphState owner ) : base( owner ) { m_handlerFor = ExceptionClause.SharedEmptyArray; } //--// // // Helper Methods // public override BasicBlock Clone( CloningContext context ) { return RegisterAndCloneState( context, new ExceptionHandlerBasicBlock( context.ControlFlowGraphDestination ) ); } public override void CloneState( CloningContext context , BasicBlock clone ) { base.CloneState( context, clone ); ExceptionHandlerBasicBlock cloneEh = (ExceptionHandlerBasicBlock)clone; cloneEh.m_handlerFor = context.Clone( m_handlerFor ); } //--// public override void ApplyTransformation( TransformationContextForIR context ) { context.Push( this ); base.ApplyTransformation( context ); context.Transform( ref m_handlerFor ); context.Pop(); } //--// public void SetAsHandlerFor( ExceptionClause ec ) { BumpVersion(); m_handlerFor = ArrayUtility.AddUniqueToNotNullArray( m_handlerFor, ec ); } public void SubstituteHandlerFor( ExceptionClause ecOld , ExceptionClause ecNew ) { int pos = ArrayUtility.FindInNotNullArray( m_handlerFor, ecOld ); if(pos >= 0) { m_handlerFor = ArrayUtility.ReplaceAtPositionOfNotNullArray( m_handlerFor, pos, ecNew ); BumpVersion(); } } //--// // // Access Methods // public ExceptionClause[] HandlerFor { get { return m_handlerFor; } } //--// // // Debug Methods // public override string ToShortString() { return ToShortStringInner( "ExceptionBasicBlock" ); } } } ================================================ FILE: Zelig/Zelig/CompileTime/CodeGenerator/IntermediateRepresentation/BasicBlocks/ExitBasicBlock.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // namespace Microsoft.Zelig.CodeGeneration.IR { using System; using System.Collections.Generic; public sealed class ExitBasicBlock : BasicBlock { // // Constructor Methods // public ExitBasicBlock( ControlFlowGraphState owner ) : base( owner ) { } //--// // // Helper Methods // public override BasicBlock Clone( CloningContext context ) { return RegisterAndCloneState( context, new ExitBasicBlock( context.ControlFlowGraphDestination ) ); } //--// // // Debug Methods // public override string ToShortString() { return ToShortStringInner( "ExitBasicBlock" ); } } } ================================================ FILE: Zelig/Zelig/CompileTime/CodeGenerator/IntermediateRepresentation/BasicBlocks/NormalBasicBlock.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // namespace Microsoft.Zelig.CodeGeneration.IR { using System; using System.Collections.Generic; public sealed class NormalBasicBlock : BasicBlock { // // Constructor Methods // public NormalBasicBlock( ControlFlowGraphState owner ) : base( owner ) { } //--// // // Helper Methods // public override BasicBlock Clone( CloningContext context ) { return RegisterAndCloneState( context, new NormalBasicBlock( context.ControlFlowGraphDestination ) ); } public static NormalBasicBlock CreateWithSameProtection( BasicBlock bb ) { // // Create new basic block, copying the exception handler sets. // var res = new NormalBasicBlock( bb.Owner ); res.m_protectedBy = ArrayUtility.CopyNotNullArray( bb.ProtectedBy ); return res; } //--// // // Debug Methods // public override string ToShortString() { return ToShortStringInner( "BasicBlock" ); } } } ================================================ FILE: Zelig/Zelig/CompileTime/CodeGenerator/IntermediateRepresentation/ByteCode/ByteCodeBlock.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // namespace Microsoft.Zelig.CodeGeneration.IR { using System; using System.Collections.Generic; using Microsoft.Zelig.MetaData; using Microsoft.Zelig.MetaData.Normalized; using Microsoft.Zelig.Runtime.TypeSystem; internal class ByteCodeBlock { [Flags] internal enum Flags { Reached = 0x01, EntryPoint = 0x02, JoinNode = 0x04, BranchNode = 0x08, BackEdge = 0x10, ExceptionHandler = 0x20, NormalEntryPoint = EntryPoint | JoinNode , ExceptionHandlerEntryPoint = EntryPoint | JoinNode | ExceptionHandler, } internal static readonly ByteCodeBlock[] SharedEmptyArray = new ByteCodeBlock[0]; // // State // private readonly Flags m_kind; private readonly int m_offsetOfFirstInstruction; private int m_numberOfInstructions; private ByteCodeBlock[] m_predecessors; private ByteCodeBlock[] m_successors; private ByteCodeBlock[] m_protectedBy; private EHClause[] m_handlerFor; private ExceptionObjectVariableExpression m_ehVariable; private BasicBlock m_basicBlock; private Expression[] m_exitStackModel; // // Constructor Methods // internal ByteCodeBlock( Flags kind , int offsetOfFirstInstruction ) { m_kind = kind; m_offsetOfFirstInstruction = offsetOfFirstInstruction; m_numberOfInstructions = 0; m_predecessors = ByteCodeBlock.SharedEmptyArray; m_successors = ByteCodeBlock.SharedEmptyArray; m_protectedBy = ByteCodeBlock.SharedEmptyArray; m_handlerFor = EHClause .SharedEmptyArray; } //--// internal void IncrementInstructionCount() { m_numberOfInstructions++; } internal void SetPredecessor( ByteCodeBlock bcb ) { m_predecessors = ArrayUtility.AddUniqueToNotNullArray( m_predecessors, bcb ); } internal void SetSuccessor( ByteCodeBlock bcb ) { m_successors = ArrayUtility.AddUniqueToNotNullArray( m_successors, bcb ); } internal void SetProtectedBy( ByteCodeBlock bcb ) { m_protectedBy = ArrayUtility.AddUniqueToNotNullArray( m_protectedBy, bcb ); } internal void SetAsHandlerFor( EHClause eh ) { m_handlerFor = ArrayUtility.AddUniqueToNotNullArray( m_handlerFor, eh ); } //--// internal int OffsetOfFirstInstruction { get { return m_offsetOfFirstInstruction; } } internal int NumberOfInstructions { get { return m_numberOfInstructions; } } internal Flags Kind { get { return m_kind; } } internal ByteCodeBlock[] Predecessors { get { return m_predecessors; } } internal ByteCodeBlock[] Successors { get { return m_successors; } } internal ByteCodeBlock[] ProtectedBy { get { return m_protectedBy; } } internal EHClause[] HandlerFor { get { return m_handlerFor; } } internal ExceptionObjectVariableExpression EhVariable { get { return m_ehVariable; } set { m_ehVariable = value; } } internal BasicBlock BasicBlock { get { return m_basicBlock; } set { m_basicBlock = value; } } internal Expression[] ExitStackModel { get { return m_exitStackModel; } set { m_exitStackModel = value; } } } } ================================================ FILE: Zelig/Zelig/CompileTime/CodeGenerator/IntermediateRepresentation/ByteCode/ByteCodeConverter.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // namespace Microsoft.Zelig.CodeGeneration.IR { using System; using System.Collections.Generic; using Microsoft.Zelig.MetaData; using Microsoft.Zelig.MetaData.Normalized; using Microsoft.Zelig.Runtime.TypeSystem; ///////////////////////////////////////////////////////////////////////////////////////////// // // Method analysis: // // 1) Discover basic blocks (starting points: exception handlers and first bytecode). // 2) Operators to zero-out all local variables. // 3) Build state of evaluation stack, inferring types of every slot. // 4) Convert the evaluation stack to variables. // 5) Convert every bytecode to a set of operators (input: set of variables, output: a variable). // 6) Optimize. // 7) Code-generation. // public sealed partial class ByteCodeConverter { // // State // private readonly TypeSystemForIR m_typeSystem; private readonly ConversionContext m_context; private readonly MethodRepresentation m_md; private readonly MetaData.Normalized.SignatureType[] m_mdLocals; private readonly Debugging.MethodDebugInfo m_mdDebugInfo; private readonly Instruction[] m_instructions; private readonly EHClause[] m_ehTable; private List< ByteCodeBlock > m_byteCodeBlocks; private ByteCodeBlock[] m_instructionToByteCodeBlock; private object[] m_byteCodeArguments; private TypeRepresentation[] m_localsTypes; // // Constructor Methods // public ByteCodeConverter( TypeSystemForIR typeSystem , ref ConversionContext context , MethodRepresentation md , MetaData.Normalized.SignatureType[] mdLocals , Debugging.MethodDebugInfo mdDebugInfo ) { MetaDataMethodBase metadata = typeSystem.GetAssociatedMetaData( md ); m_typeSystem = typeSystem; m_context = context; m_md = md; m_mdLocals = mdLocals; m_mdDebugInfo = mdDebugInfo; m_instructions = metadata.Instructions; m_ehTable = metadata.EHTable; } //--// public void PerformDelayedByteCodeAnalysis() { m_typeSystem.Report( "Converting byte code for {0}...", m_md ); BuildByteCodeBlocks( AnalyzeControlFlow() ); SetExceptionHandlingDomains(); PopulateBasicBlocks(); } //--// #region ExpandByteCodeArguments public void ExpandByteCodeArguments() { int numInstructions = m_instructions.Length; m_byteCodeArguments = new object[numInstructions]; for(int i = 0; i < numInstructions; i++) { object o = m_instructions[i].Argument; if(o is MetaDataTypeDefinitionAbstract) { o = m_typeSystem.ConvertToIR( (MetaDataTypeDefinitionAbstract)o, m_context ); } else if(o is MetaDataMethodAbstract) { o = m_typeSystem.ConvertToIR( (MetaDataMethodAbstract)o, m_context ); } else if(o is MetaDataFieldAbstract) { o = m_typeSystem.ConvertToIR( null, (MetaDataFieldAbstract)o, m_context ); } else if(o is MetaDataObject) { throw TypeConsistencyErrorException.Create( "Found unexpected metadata object {0} in method {1}", o, m_md ); } m_byteCodeArguments[i] = o; } if(m_mdLocals != null) { m_localsTypes = new TypeRepresentation[m_mdLocals.Length]; // // We need to convert the types of the local variables here, even if we don't keep the result around. // The ByteCodeConverter will actually pass the values to the FlowGraphState object. // for(int i = 0; i < m_mdLocals.Length; i++) { m_localsTypes[i] = m_typeSystem.ConvertToIR( m_mdLocals[i].Type, m_context ); } } else { m_localsTypes = TypeRepresentation.SharedEmptyArray; } } #endregion ExpandByteCodeArguments //--// #region AnalyzeControlFlow private ByteCodeBlock.Flags[] AnalyzeControlFlow() { int numInstructions = m_instructions.Length; ByteCodeBlock.Flags[] byteCodeBlockKinds = new ByteCodeBlock.Flags[numInstructions]; try { // // The first instruction is for sure the start of a new basic block. // byteCodeBlockKinds[0] |= ByteCodeBlock.Flags.NormalEntryPoint; for(int i = 0; i < m_ehTable.Length; i++) { byteCodeBlockKinds[ m_ehTable[i].HandlerOffset ] |= ByteCodeBlock.Flags.ExceptionHandlerEntryPoint; // // Force a basic block boundary on entry to a try block. // byteCodeBlockKinds[ m_ehTable[i].TryOffset ] |= ByteCodeBlock.Flags.JoinNode; } for(int outerIndex = 0; outerIndex < numInstructions; outerIndex++) { if(byteCodeBlockKinds[outerIndex] != 0 && (byteCodeBlockKinds[outerIndex] & ByteCodeBlock.Flags.Reached) == 0) { for(int innerIndex = outerIndex; (byteCodeBlockKinds[innerIndex] & ByteCodeBlock.Flags.Reached) == 0; innerIndex++) { byteCodeBlockKinds[innerIndex] |= ByteCodeBlock.Flags.Reached; Instruction instr = m_instructions[innerIndex]; Instruction.OpcodeInfo oi = instr.Operator; Instruction.OpcodeFlowControl ctrl = oi.Control; if(ctrl != Instruction.OpcodeFlowControl.None) { switch(oi.OperandFormat) { case Instruction.OpcodeOperand.Branch: { int target = (int)instr.Argument; byteCodeBlockKinds[innerIndex] |= ByteCodeBlock.Flags.BranchNode; outerIndex = AnalyzeControlFlow_ProcessBranch( byteCodeBlockKinds, target, innerIndex, outerIndex ); } break; case Instruction.OpcodeOperand.Switch: { byteCodeBlockKinds[innerIndex] |= ByteCodeBlock.Flags.BranchNode; foreach(int target in (int[])instr.Argument) { outerIndex = AnalyzeControlFlow_ProcessBranch( byteCodeBlockKinds, target, innerIndex, outerIndex ); } } break; } if(ctrl != Instruction.OpcodeFlowControl.ConditionalControl) { break; } } } } } for(int outerIndex = 0; outerIndex < numInstructions; outerIndex++) { if(byteCodeBlockKinds[outerIndex] == 0) { m_typeSystem.Report( "Unreachable bytecode {0} for {1}", m_instructions[outerIndex], m_md ); } } } catch { throw TypeConsistencyErrorException.Create( "Invalid byte code for '{0}'", m_md ); } return byteCodeBlockKinds; } private static int AnalyzeControlFlow_ProcessBranch( ByteCodeBlock.Flags[] byteCodeBlockKinds , int target , int innerIndex , int outerIndex ) { byteCodeBlockKinds[target] |= ByteCodeBlock.Flags.JoinNode; if(target < innerIndex) { byteCodeBlockKinds[target] |= ByteCodeBlock.Flags.BackEdge; } // // Backtrack external loop. // if((byteCodeBlockKinds[target] & ByteCodeBlock.Flags.Reached) == 0 && outerIndex > target) { outerIndex = target - 1; } return outerIndex; } #endregion AnalyzeControlFlow //--// #region BuildByteCodeBlocks private void BuildByteCodeBlocks( ByteCodeBlock.Flags[] byteCodeBlockKinds ) { int numInstructions = m_instructions.Length; ByteCodeBlock currentBCB = null; m_byteCodeBlocks = new List(); m_instructionToByteCodeBlock = new ByteCodeBlock[numInstructions]; for(int i = 0; i < numInstructions; i++) { if((byteCodeBlockKinds[i] & ByteCodeBlock.Flags.JoinNode) != 0) { currentBCB = null; } if(currentBCB == null) { currentBCB = BuildByteCodeBlocks_Fetch( i, byteCodeBlockKinds ); } else { m_instructionToByteCodeBlock[i] = currentBCB; } Instruction instr = m_instructions[i]; bool fJoinWithNext = false; currentBCB.IncrementInstructionCount(); switch(instr.Operator.OperandFormat) { case Instruction.OpcodeOperand.Branch: { int target = (int)instr.Argument; BuildByteCodeBlocks_Link( currentBCB, target, byteCodeBlockKinds ); fJoinWithNext = (instr.Operator.Control == Instruction.OpcodeFlowControl.ConditionalControl); } break; case Instruction.OpcodeOperand.Switch: { foreach(int target in (int[])instr.Argument) { BuildByteCodeBlocks_Link( currentBCB, target, byteCodeBlockKinds ); } fJoinWithNext = (instr.Operator.Control == Instruction.OpcodeFlowControl.ConditionalControl); } break; default: { if(instr.Operator.Control == Instruction.OpcodeFlowControl.None) { int target = i + 1; if(target < numInstructions && (byteCodeBlockKinds[target] & ByteCodeBlock.Flags.JoinNode) != 0) { fJoinWithNext = true; } } } break; } if(fJoinWithNext) { BuildByteCodeBlocks_Link( currentBCB, i+1, byteCodeBlockKinds ); } if((byteCodeBlockKinds[i] & ByteCodeBlock.Flags.BranchNode) != 0) { currentBCB = null; } } } private ByteCodeBlock BuildByteCodeBlocks_Fetch( int i , ByteCodeBlock.Flags[] byteCodeBlockKinds ) { ByteCodeBlock current = m_instructionToByteCodeBlock[i]; if(current == null) { current = new ByteCodeBlock( byteCodeBlockKinds[i], i ); m_byteCodeBlocks.Add( current ); m_instructionToByteCodeBlock[i] = current; } return current; } private void BuildByteCodeBlocks_Link( ByteCodeBlock currentBCB , int target , ByteCodeBlock.Flags[] byteCodeBlockKinds ) { ByteCodeBlock targetBCB = BuildByteCodeBlocks_Fetch( target, byteCodeBlockKinds ); targetBCB .SetPredecessor( currentBCB ); currentBCB.SetSuccessor ( targetBCB ); } #endregion BuildByteCodeBlocks //--// #region SetExceptionHandlingDomains private void SetExceptionHandlingDomains() { for(int i = 0; i < m_ehTable.Length; i++) { EHClause eh = m_ehTable[i]; ByteCodeBlock bcbLast = null; ByteCodeBlock bcbHandler = m_instructionToByteCodeBlock[eh.HandlerOffset]; bcbHandler.SetAsHandlerFor( eh ); for(int j = eh.TryOffset; j < eh.TryEnd; j++) { ByteCodeBlock bcb = m_instructionToByteCodeBlock[j]; if(bcb != bcbLast) { bcb.SetProtectedBy( bcbHandler ); bcbLast = bcb; } } } } #endregion SetExceptionHandlingDomains //--// // // Access Methods // //--// // // Debug Methods // } } ================================================ FILE: Zelig/Zelig/CompileTime/CodeGenerator/IntermediateRepresentation/ByteCode/ByteCodeConverter_Helpers.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // namespace Microsoft.Zelig.CodeGeneration.IR { using System; using System.Collections.Generic; using Microsoft.Zelig.MetaData; using Microsoft.Zelig.MetaData.Normalized; using Microsoft.Zelig.Runtime.TypeSystem; public sealed partial class ByteCodeConverter { // // State // private int m_currentInstructionOffset; private Expression[] m_activeStackModel; // // Constructor Methods // private TypeRepresentation ProcessInstruction_GetTypeFromActionType( Instruction instr , TypeRepresentation tdRef ) { WellKnownTypes wkt = m_typeSystem.WellKnownTypes; switch(instr.Operator.ActionType) { case Instruction.OpcodeActionType.I1 : return wkt.System_SByte; case Instruction.OpcodeActionType.U1 : return wkt.System_Byte; case Instruction.OpcodeActionType.I2 : return wkt.System_Int16; case Instruction.OpcodeActionType.U2 : return wkt.System_UInt16; case Instruction.OpcodeActionType.I4 : return wkt.System_Int32; case Instruction.OpcodeActionType.U4 : return wkt.System_UInt32; case Instruction.OpcodeActionType.I8 : return wkt.System_Int64; case Instruction.OpcodeActionType.U8 : return wkt.System_UInt64; case Instruction.OpcodeActionType.I : return wkt.System_IntPtr; case Instruction.OpcodeActionType.U : return wkt.System_UIntPtr; case Instruction.OpcodeActionType.R4 : return wkt.System_Single; case Instruction.OpcodeActionType.R8 : return wkt.System_Double; case Instruction.OpcodeActionType.R : return wkt.System_Double; case Instruction.OpcodeActionType.String: return wkt.System_String; case Instruction.OpcodeActionType.Reference: { return tdRef; } case Instruction.OpcodeActionType.Token: { return this.CurrentArgumentAsType; } default: { throw IncorrectEncodingException.Create( "Invalid OpcodeActionType {0} for {1}", instr.Operator.ActionType, instr ); } } } private Expression ProcessInstruction_GetTypeOfActionTarget( Instruction instr , out TypeRepresentation tdTarget , out FieldRepresentation fdTarget ) { Expression ex; switch(instr.Operator.ActionTarget) { case Instruction.OpcodeActionTarget.Local: ex = m_locals[this.CurrentArgumentAsInt32]; break; case Instruction.OpcodeActionTarget.Argument: ex = m_arguments[m_variable_arguments_offset + this.CurrentArgumentAsInt32]; break; case Instruction.OpcodeActionTarget.Null: ex = CreateNewNullPointer( m_typeSystem.WellKnownTypes.System_Object ); break; case Instruction.OpcodeActionTarget.Constant: ex = CreateNewConstant( m_typeSystem.GetTypeOfValue( this.CurrentArgument ), this.CurrentArgument ); break; case Instruction.OpcodeActionTarget.Field: case Instruction.OpcodeActionTarget.StaticField: { fdTarget = this.CurrentArgumentAsField; tdTarget = fdTarget.FieldType; return null; } case Instruction.OpcodeActionTarget.String: ex = CreateNewConstant( m_typeSystem.WellKnownTypes.System_String, this.CurrentArgument ); break; case Instruction.OpcodeActionTarget.Token: { object o = this.CurrentArgument; if(o is TypeRepresentation || o is FieldRepresentation || o is MethodRepresentation ) { ex = m_typeSystem.CreateRuntimeHandle( o ); break; } throw TypeConsistencyErrorException.Create( "Unknown token {0}", o ); } default: { throw IncorrectEncodingException.Create( "Invalid OpcodeActionTarget {0} for {1}", instr.Operator.ActionTarget, instr ); } } fdTarget = null; tdTarget = ex.Type; return ex; } //--// private TypeRepresentation ProcessInstruction_ExtractAddressType( Instruction instr , Expression exAddr , TypeRepresentation tdFormal ) { if(tdFormal == null) { TypeRepresentation td = exAddr.Type; TypeRepresentation tdActual; if(td is PointerTypeRepresentation) { tdActual = td.UnderlyingType; } else if(td is BoxedValueTypeRepresentation) { tdActual = td.UnderlyingType; } else if(td.StackEquivalentType == StackEquivalentType.NativeInt) { tdActual = m_typeSystem.WellKnownTypes.System_IntPtr; } else { throw TypeConsistencyErrorException.Create( "Expecting pointer type, got {0}", td ); } tdFormal = ProcessInstruction_GetTypeFromActionType( instr, tdActual ); // // TODO: Need to distinguish between safe and unsafe code. For safe code, the check should be performed. // //// if(m_typeSystem.CanBeAssignedFrom( tdFormal, tdActual ) == false) //// { //// throw TypeConsistencyErrorException.Create( "Expecting pointer type {0}, got {1}", tdFormal, tdActual ); //// } } return tdFormal; } private Operator ProcessInstruction_LoadIndirect( Instruction instr , Expression exAddr , TypeRepresentation tdFormal ) { TypeRepresentation td = ProcessInstruction_ExtractAddressType( instr, exAddr, tdFormal ); VariableExpression exRes = CreateNewTemporary( td ); ModifyStackModel( 1, exRes ); return LoadIndirectOperator.New( instr.DebugInfo, td, exRes, exAddr, null, 0, false, true ); } private Operator ProcessInstruction_StoreIndirect( Instruction instr , Expression exAddr , Expression exValue , TypeRepresentation tdFormal ) { TypeRepresentation td = ProcessInstruction_ExtractAddressType( instr, exAddr, tdFormal ); if(exValue is ConstantExpression) { exValue = CoerceConstantToType( (ConstantExpression)exValue, td ); } if(!CanBeAssignedFromEvaluationStack( td, exValue )) { throw TypeConsistencyErrorException.Create( "Expecting value of type {0}, got {1}", td, exValue.Type ); } PopStackModel( 2 ); return StoreIndirectOperator.New( instr.DebugInfo, td, exAddr, exValue, null, 0, true ); } //--//--//--//--//--//--//--//--//--// internal int CurrentInstructionOffset { get { return m_currentInstructionOffset; } set { m_currentInstructionOffset = value; } } internal object CurrentArgument { get { return m_byteCodeArguments[m_currentInstructionOffset]; } } internal int CurrentArgumentAsInt32 { get { return (int)CurrentArgument; } } internal TypeRepresentation CurrentArgumentAsType { get { return (TypeRepresentation)CurrentArgument; } } internal FieldRepresentation CurrentArgumentAsField { get { return (FieldRepresentation)CurrentArgument; } } internal MethodRepresentation CurrentArgumentAsMethod { get { return (MethodRepresentation)CurrentArgument; } } internal BasicBlock GetBasicBlockFromInstruction( int offset ) { if(offset < 0 || offset >= m_instructionToByteCodeBlock.Length) { return null; } return m_instructionToByteCodeBlock[offset].BasicBlock; } //--// internal void ModifyStackModel( int slotsToPop , Expression slotToPush ) { Expression[] stackModel = m_activeStackModel; int newLen = stackModel.Length - slotsToPop; if(slotToPush != null) newLen += 1; Expression[] res = new Expression[newLen]; for(int i = 0; i < newLen; i++) { if(slotToPush != null) { res[i] = slotToPush; slotToPush = null; } else { res[i] = stackModel[slotsToPop++]; } } m_activeStackModel = res; } internal void PushStackModel( Expression slot ) { ModifyStackModel( 0, slot ); } internal void PopStackModel( int slots ) { ModifyStackModel( slots, null ); } internal void EmptyStackModel() { m_activeStackModel = Expression.SharedEmptyArray; } internal Expression GetArgumentFromStack( int pos, int tot ) { pos = tot - 1 - pos; CHECKS.ASSERT( pos >= 0 , "Evaluation stack underflow in {0}", m_md ); CHECKS.ASSERT( pos < m_activeStackModel.Length, "Evaluation stack overflow in {0}" , m_md ); return m_activeStackModel[pos]; } internal Expression GetArgumentFromStack( int pos, int tot, TypeRepresentation formalType ) { Expression argument = GetArgumentFromStack( pos, tot ); if(argument is ConstantExpression) { argument = CoerceConstantToType( (ConstantExpression)argument, formalType ); } return argument; } //--//--//--//--//--//--//--//--//--// private ConstantExpression CoerceConstantToType( ConstantExpression expr, TypeRepresentation type ) { if (expr.Type != type) { // Null pointers can be cast to any non-value type. if(expr.IsEqualToZero() && !(type is ValueTypeRepresentation)) { return CreateNewNullPointer( type ); } // Scalar literals are validated before MSIL, so we can cast without validating. if((type is ScalarTypeRepresentation) && (expr.Value != null)) { return CreateNewConstant( type, expr.Value ); } } return expr; } private bool CanBeAssignedFromEvaluationStack( TypeRepresentation dst , Expression src ) { if(src.CanBeNull == CanBeNull.Yes) { if(dst is ReferenceTypeRepresentation) { return true; } if(dst is PointerTypeRepresentation) { return true; } } TypeRepresentation expandedDst = ExpandForEvaluationStack( dst ); return expandedDst.CanBeAssignedFrom( src.Type, null ); } private TypeRepresentation ExpandForEvaluationStack( TypeRepresentation td ) { if(td is EnumerationTypeRepresentation) { td = td.UnderlyingType; } if(td is ScalarTypeRepresentation) { switch(td.BuiltInType) { case TypeRepresentation.BuiltInTypes.BOOLEAN: case TypeRepresentation.BuiltInTypes.I1: case TypeRepresentation.BuiltInTypes.U1: case TypeRepresentation.BuiltInTypes.I2: case TypeRepresentation.BuiltInTypes.U2: case TypeRepresentation.BuiltInTypes.CHAR: case TypeRepresentation.BuiltInTypes.U4: return m_typeSystem.WellKnownTypes.System_Int32; } } return td; } private ConstantExpression CreateNewNullPointer( TypeRepresentation td ) { return m_typeSystem.CreateNullPointer( td ); } private ConstantExpression CreateNewConstant( TypeRepresentation td , object value ) { return m_typeSystem.CreateConstant( td, value ); } private TemporaryVariableExpression CreateNewTemporary( TypeRepresentation td ) { td = ExpandForEvaluationStack( td ); return m_cfg.AllocateTemporary( td, null ); } private void AddOperator( Operator op ) { m_currentBasicBlock.AddOperator( op ); } private void AddControl( ControlOperator op ) { m_currentBasicBlock.FlowControl = op; } /// /// Ensure a given pointer expression is a pointer to the correct type. This can be necessary when an IntPtr is /// passed as a managed or unmanaged pointer in an unsafe context. /// /// Expression containing the pointer to coerce. /// The desired underlying object type. /// Debug info to assign to any added instructions /// Canonicalized pointer with the desired type. private Expression EnsurePointerType( Expression pointer, TypeRepresentation objectType, Debugging.DebugInfo debugInfo) { if ((pointer.Type is ScalarTypeRepresentation) && (objectType != pointer.Type)) { TypeRepresentation objPointerType = m_typeSystem.CreateManagedPointerToType(objectType); VariableExpression objPointer = CreateNewTemporary(objPointerType); AddOperator(SingleAssignmentOperator.New(debugInfo, objPointer, pointer)); pointer = objPointer; } return pointer; } } } ================================================ FILE: Zelig/Zelig/CompileTime/CodeGenerator/IntermediateRepresentation/ByteCode/ByteCodeConverter_ProcessInstruction.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // namespace Microsoft.Zelig.CodeGeneration.IR { using System; using System.Diagnostics; using Microsoft.Zelig.MetaData; using Microsoft.Zelig.MetaData.Normalized; using Microsoft.Zelig.Runtime.TypeSystem; public sealed partial class ByteCodeConverter { // // State // private int m_variable_arguments_offset; // Static methods always have a fake first argument. private VariableExpression[] m_arguments; private VariableExpression[] m_locals; private BitVector m_addressTaken_arguments; private BitVector m_addressTaken_locals; private ControlFlowGraphState m_cfg; private BasicBlock m_exitBasicBlock; private BasicBlock m_currentBasicBlock; private int m_mod_unaligned; private int m_mod_nocheck; private TypeRepresentation m_mod_constrained; private bool m_mod_fVolatile; private bool m_mod_fTailCall; private bool m_mod_fReadonly; //--// private void PopulateBasicBlocks() { InitializeBasicBlocks(); CreateVariables(); m_exitBasicBlock = m_cfg.NormalizedExitBasicBlock; var entryPoint = m_cfg.CreateFirstNormalBasicBlock(); using(m_cfg.LockFlowInformation()) { CreateBasicBlocks( entryPoint ); ProcessByteCodeBlocks(); } } //--// private void CreateVariables() { m_variable_arguments_offset = (m_md is InstanceMethodRepresentation) ? 0 : 1; m_addressTaken_arguments = new BitVector( m_md.ThisPlusArguments.Length ); m_addressTaken_locals = new BitVector( m_localsTypes .Length ); } //--// private void InitializeBasicBlocks() { #if GENERICS_DEBUG if(m_md.ToString() == "NonVirtualMethodRepresentation(void generic Microsoft.Zelig.Runtime.KernelNode`1::InsertBefore(delayed Microsoft.Zelig.Runtime.KernelNode`1))") { } #endif m_cfg = m_typeSystem.CreateControlFlowGraphState( m_md, m_localsTypes, m_mdDebugInfo != null ? m_mdDebugInfo.LocalVarNames : null, out m_arguments, out m_locals ); m_currentBasicBlock = null; } private void CreateBasicBlocks( BasicBlock entryPoint ) { bool fGotFirstBasicBlock = false; // // First allocate all the basic blocks. // foreach(ByteCodeBlock current in m_byteCodeBlocks) { BasicBlock bb; if((current.Kind & ByteCodeBlock.Flags.ExceptionHandler) != 0) { MetaDataTypeDefinitionAbstract tdCatch = null; foreach(EHClause eh in current.HandlerFor) { if(tdCatch == null) { tdCatch = eh.TypeObject; } else if(tdCatch != eh.TypeObject) { throw TypeConsistencyErrorException.Create( "Multiple incompatible exception handlers share the same byte code for {0}", m_md ); } } if(tdCatch != null) { TypeRepresentation td = m_typeSystem.ConvertToIRWithoutContext( tdCatch ); current.EhVariable = m_cfg.AllocateExceptionObjectVariable( td ); } bb = new ExceptionHandlerBasicBlock( m_cfg ); } else { if(!fGotFirstBasicBlock) { fGotFirstBasicBlock = true; // // The entry point already has a control operator towards the exit. // We need to remove it to correctly import the byte code. // entryPoint.FlowControl.Delete(); bb = entryPoint; } else { bb = new NormalBasicBlock( m_cfg ); } } current.BasicBlock = bb; } // // Then link them to the exception handlers. // foreach(ByteCodeBlock current in m_byteCodeBlocks) { BasicBlock bb = current.BasicBlock; foreach(ByteCodeBlock protectedBy in current.ProtectedBy) { bb.SetProtectedBy( (ExceptionHandlerBasicBlock)protectedBy.BasicBlock ); } if(bb is ExceptionHandlerBasicBlock) { ExceptionHandlerBasicBlock ehBB = (ExceptionHandlerBasicBlock)bb; foreach(EHClause eh in current.HandlerFor) { ExceptionClause ehNew = new ExceptionClause( (ExceptionClause.ExceptionFlag)eh.Flags, m_typeSystem.ConvertToIRWithoutContext( eh.TypeObject ) ); ehBB.SetAsHandlerFor( ehNew ); } } } // // Create proper flow control for exit basic block. // m_cfg.AddReturnOperator(); } //--// private void ProcessByteCodeBlocks() { // // First of all, find all the variable whose address has been taken. // for(int pos = 0; pos < m_instructions.Length; pos++) { Instruction instr = m_instructions[pos]; if(instr.Operator.Action == Instruction.OpcodeAction.LoadAddress) { switch(instr.Operator.ActionTarget) { case Instruction.OpcodeActionTarget.Argument: m_addressTaken_arguments.Set( (int)m_byteCodeArguments[pos] + m_variable_arguments_offset ); break; case Instruction.OpcodeActionTarget.Local: m_addressTaken_locals.Set( (int)m_byteCodeArguments[pos] ); break; } } } for(int pos = 0; pos < m_instructions.Length; pos++) { ByteCodeBlock current = m_instructionToByteCodeBlock[pos]; if(current.OffsetOfFirstInstruction == pos) { m_currentBasicBlock = current.BasicBlock; Expression[] mergedStackModel = null; if(current.Predecessors.Length > 0) { bool fFoundBackEdge = false; // // Merge incoming flows. // foreach(ByteCodeBlock prev in current.Predecessors) { if(prev.OffsetOfFirstInstruction >= current.OffsetOfFirstInstruction) { fFoundBackEdge = true; } else { Expression[] prevStackModel = prev.ExitStackModel; CHECKS.ASSERT( prevStackModel != null, "" ); if(mergedStackModel == null) { mergedStackModel = ArrayUtility.CopyNotNullArray( prevStackModel ); } else { int depth = mergedStackModel.Length; if(prevStackModel.Length != depth) { throw TypeConsistencyErrorException.Create( "Inconsistent evaluation stack for {0}", m_md ); } //--// if(depth > 0) { // // We found at least two flows joining in one point with non-empty evaluation stack. // So we need to reconcile the stack. // // To do that, we find the common type for each slots and create a new temporary variable. // Then each flow is merged, inserting an extra assignment to the new variable if needed. // for(int i = 0; i < depth; i++) { Expression exActive = mergedStackModel[i]; Expression exPrev = prevStackModel [i]; if(exActive != exPrev) { TypeRepresentation tdMerged; if(CanPromote( exActive, exPrev )) { tdMerged = exPrev.Type; } else if(CanPromote( exPrev, exActive )) { tdMerged = exActive.Type; } else { tdMerged = TypeRepresentation.FindCommonType( exActive.Type, exPrev.Type ); if(tdMerged == null) { throw TypeConsistencyErrorException.Create( "Incompatible evaluation stack for {0}: {1} != {2}", m_md, exActive, exPrev ); } } if(!(exActive is TemporaryVariableExpression) || exActive.Type != tdMerged) { mergedStackModel[i] = CreateNewTemporary( tdMerged ); } } } } } } } if(fFoundBackEdge) { if(mergedStackModel != null && mergedStackModel.Length > 0) { throw TypeConsistencyErrorException.Create( "Evaluation stack not empty on backward branch for {0}", m_md ); } } else { // // After merging the incoming flows, we need to back-patch the predecessor, adding assignments to the new temporaries. // foreach(ByteCodeBlock prev in current.Predecessors) { Expression[] exitStackModel = prev.ExitStackModel; for(int i = 0; i < exitStackModel.Length; i++) { if(mergedStackModel[i] != exitStackModel[i]) { Operator opMerge = SingleAssignmentOperator.New( null, (VariableExpression)mergedStackModel[i], exitStackModel[i] ); prev.BasicBlock.AddOperator( opMerge ); } } prev.ExitStackModel = mergedStackModel; } } } if(mergedStackModel == null) { mergedStackModel = Expression.SharedEmptyArray; } //--// if(m_currentBasicBlock is ExceptionHandlerBasicBlock) { ExceptionHandlerBasicBlock ehBB = (ExceptionHandlerBasicBlock)m_currentBasicBlock; // // Exception handlers start with an header block followed by a normal one, // which contains the actual code. // NormalBasicBlock bb = NormalBasicBlock.CreateWithSameProtection( ehBB ); ehBB.AddOperator( UnconditionalControlOperator.New( null, bb ) ); m_currentBasicBlock = bb; //--// VariableExpression var = current.EhVariable; if(var != null) { FetchExceptionOperator op = FetchExceptionOperator.New( m_instructions[current.OffsetOfFirstInstruction].DebugInfo, var.Type, var ); bb.AddOperator( op ); mergedStackModel = new Expression[] { var }; } } m_activeStackModel = mergedStackModel; ConvertInstructionToOperators( current ); } } } private static bool CanPromote( Expression value , Expression reference ) { if(value is ConstantExpression) { ConstantExpression valueConst = (ConstantExpression)value; if(valueConst.Value == null) { return true; } } return false; } //--//--// private void ConvertInstructionToOperators( ByteCodeBlock current ) { int pos = current.OffsetOfFirstInstruction; int end = pos + current.NumberOfInstructions; ResetModifiers(); for(;pos < end; pos++) { Instruction instr = m_instructions[pos]; this.CurrentInstructionOffset = pos; ProcessInstruction( instr ); } current.ExitStackModel = ArrayUtility.CopyNotNullArray( m_activeStackModel ); if(m_currentBasicBlock.FlowControl == null) { if(current.Successors.Length != 1) { throw TypeConsistencyErrorException.Create( "No flow control operator on basic block with multiple exits, for {0}", m_md ); } m_currentBasicBlock.AddOperator( UnconditionalControlOperator.New( null, current.Successors[0].BasicBlock ) ); } if(m_activeStackModel.Length > 0) { // // Make sure there's no backward branch, since the evaluation stack is not empty. // foreach(ByteCodeBlock next in current.Successors) { if(next.OffsetOfFirstInstruction <= current.OffsetOfFirstInstruction) { throw TypeConsistencyErrorException.Create( "Evaluation stack not empty on backward branch for {0}", m_md ); } } } } //--// private void ResetModifiers() { m_mod_unaligned = 0; m_mod_nocheck = 0; m_mod_constrained = null; m_mod_fVolatile = false; m_mod_fTailCall = false; m_mod_fReadonly = false; } //--// private void ProcessInstruction( Instruction instr ) { if (instr.DebugInfo != null) { instr.DebugInfo.Scope = m_cfg.Method; instr.DebugInfo.MethodName = m_cfg.Method.FullyQualifiedName; } switch (instr.Operator.Action) { case Instruction.OpcodeAction.Load: ProcessInstruction_Load( instr ); break; case Instruction.OpcodeAction.LoadAddress: ProcessInstruction_LoadAddress( instr ); break; case Instruction.OpcodeAction.LoadIndirect: ProcessInstruction_LoadIndirect( instr ); break; case Instruction.OpcodeAction.LoadElement: ProcessInstruction_LoadElement( instr ); break; case Instruction.OpcodeAction.LoadElementAddress: ProcessInstruction_LoadElementAddress( instr ); break; case Instruction.OpcodeAction.Store: ProcessInstruction_Store( instr ); break; case Instruction.OpcodeAction.StoreIndirect: ProcessInstruction_StoreIndirect( instr ); break; case Instruction.OpcodeAction.StoreElement: ProcessInstruction_StoreElement( instr ); break; case Instruction.OpcodeAction.Stack: ProcessInstruction_Stack( instr ); break; case Instruction.OpcodeAction.Jump: ProcessInstruction_Jump( instr ); break; case Instruction.OpcodeAction.Call: ProcessInstruction_Call( instr ); break; case Instruction.OpcodeAction.Return: ProcessInstruction_Return( instr ); break; case Instruction.OpcodeAction.Branch: ProcessInstruction_Branch( instr ); break; case Instruction.OpcodeAction.ALU: ProcessInstruction_ALU( instr ); break; case Instruction.OpcodeAction.Convert: ProcessInstruction_Convert( instr ); break; case Instruction.OpcodeAction.Object: ProcessInstruction_Object( instr ); break; case Instruction.OpcodeAction.TypedRef: ProcessInstruction_TypedRef( instr ); break; case Instruction.OpcodeAction.EH: ProcessInstruction_ExceptionHandling( instr ); break; case Instruction.OpcodeAction.Set: ProcessInstruction_Set( instr ); break; case Instruction.OpcodeAction.Modifier: ProcessInstruction_Modifier( instr ); return; // Return directly, because the code after the switch resets the modifiers. case Instruction.OpcodeAction.Debug: ProcessInstruction_Debug( instr ); break; } ResetModifiers(); } //--// // // LDARG = Action_Load | Target_Argument , // LDLOC = Action_Load | Target_Local , // LDNULL = Action_Load | Target_Null , // LDC = Action_Load | Target_Constant , // LDSTR = Action_Load | Target_String , // LDFLD = Action_Load | Target_Field , // LDSFLD = Action_Load | Target_StaticField , // LDTOKEN = Action_Load | Target_Token , // LDFTN = Action_Load | Target_Method , // LDVIRTFTN = Action_Load | Target_Method , // private void ProcessInstruction_Load( Instruction instr ) { if(m_mod_fVolatile) { // TODO: Implement the modifier. } TypeRepresentation tdVal; FieldRepresentation fdVal; Expression exVal = ProcessInstruction_GetTypeOfActionTarget( instr, out tdVal, out fdVal ); // // Don't create a temporary variable if the source is a constant value. // if(exVal is ConstantExpression) { PushStackModel( exVal ); return; } switch(instr.Operator.ActionTarget) { case Instruction.OpcodeActionTarget.Field: { VariableExpression exRes = CreateNewTemporary( tdVal ); Expression exObj = GetArgumentFromStack( 0, 1 ); if(exObj.Type.GetInstantiationFlavor( m_typeSystem ) == TypeRepresentation.InstantiationFlavor.Delayed) { throw TypeConsistencyErrorException.Create( "Cannot access the fields of delayed type {0}", exObj.Type ); } ModifyStackModel( 1, exRes ); exObj = EnsurePointerType(exObj, fdVal.OwnerType, instr.DebugInfo); // // This happens when we reference a value type on the evaluation stack. // Normally it's the result of a previous operation that is not stored in a local variable. // if (exObj.Type is ValueTypeRepresentation) { VariableExpression exResPtr = CreateNewTemporary( m_typeSystem.CreateManagedPointerToType( exObj.Type ) ); AddOperator( AddressAssignmentOperator.New( instr.DebugInfo, exResPtr, exObj ) ); exObj = exResPtr; } AddOperator( LoadInstanceFieldOperator.New( instr.DebugInfo, fdVal, exRes, (VariableExpression)exObj, true ) ); } break; case Instruction.OpcodeActionTarget.StaticField: { VariableExpression exRes = CreateNewTemporary( tdVal ); PushStackModel( exRes ); AddOperator( LoadStaticFieldOperator.New( instr.DebugInfo, fdVal, exRes ) ); } break; default: // 1.8.1.5 Delegate constructors // The verification algorithm shall require that one of the following code sequences is used for constructing // delegates; no other code sequence in verifiable code shall contain a newobj instruction for a delegate type. // There shall be only one instance constructor method for a delegate (overloading is not allowed) // The verification algorithm shall fail if a branch target is within these instruction sequences (other than at the // start of the sequence). // [Note: See Partition II for the signature of delegates and a validity requirement regarding the signature of the // method used in the constructor and the signature of Invoke and other methods on the delegate class. end note] // // 1.8.1.5.1 Delegating via virtual dispatch // The following CIL instruction sequence shall be used or the verification algorithm shall fail. The sequence // begins with an object on the stack. // // dup // ldvirtftn mthd ; Method shall be on the class of the object, // ; or one of its parent classes, or an interface // ; implemented by the object // newobj delegateclass::.ctor(object, native int) // // [Rationale: The dup is required to ensure that it is precisely the same object stored in the delegate as was used // to compute the virtual method. If another object of a subtype were used the object and the method wouldnt // match and could lead to memory violations. end rationale] // // 1.8.1.5.2 Delegating via instance dispatch // The following CIL instruction sequence shall be used or the verification algorithm shall fail. The sequence // begins with either null or an object on the stack. // // ldftn mthd ; Method shall either be a static method or // ; a method on the class of the object on the stack or // ; one of the objects parent classes // newobj delegateclass::.ctor(object, native int) { Operator opNew = null; if(tdVal.IsNumeric) { TypeRepresentation tdValInner = tdVal.UnderlyingType; if(tdValInner != tdVal) { VariableExpression exRes = CreateNewTemporary( tdVal ); PushStackModel( exRes ); if(tdValInner.IsSigned) { opNew = SignExtendOperator.New( instr.DebugInfo, tdValInner.Size, false, exRes, exVal ); } else { opNew = ZeroExtendOperator.New( instr.DebugInfo, tdValInner.Size, false, exRes, exVal ); } AddOperator( opNew ); } } if(opNew == null) { #if FORCE_LOCAL_EXPANSION // Expand the loaded argument into a new temporary. VariableExpression exRes = CreateNewTemporary( tdVal ); PushStackModel( exRes ); AddOperator( SingleAssignmentOperator.New( instr.DebugInfo, exRes, exVal ) ); #else // FORCE_LOCAL_EXPANSION PushStackModel( exVal ); #endif // FORCE_LOCAL_EXPANSION } } break; } } // // LDARGA = Action_LoadAddress | Target_Argument , // LDLOCA = Action_LoadAddress | Target_Local , // LDFLDA = Action_LoadAddress | Target_Field , // LDSFLDA = Action_LoadAddress | Target_StaticField , // private void ProcessInstruction_LoadAddress( Instruction instr ) { TypeRepresentation tdVal; FieldRepresentation fdVal; Expression exVal = ProcessInstruction_GetTypeOfActionTarget( instr, out tdVal, out fdVal ); VariableExpression exRes = CreateNewTemporary( m_typeSystem.CreateManagedPointerToType( tdVal ) ); switch(instr.Operator.ActionTarget) { case Instruction.OpcodeActionTarget.Field: { Expression exObj = GetArgumentFromStack( 0, 1 ); TypeRepresentation tdObj = exObj.Type; if(tdObj.GetInstantiationFlavor( m_typeSystem ) == TypeRepresentation.InstantiationFlavor.Delayed) { throw TypeConsistencyErrorException.Create( "Cannot access the field of delayed type {0}", tdObj ); } ModifyStackModel( 1, exRes ); exObj = EnsurePointerType(exObj, fdVal.OwnerType, instr.DebugInfo); AddOperator( LoadInstanceFieldAddressOperator.New( instr.DebugInfo, fdVal, exRes, (VariableExpression)exObj, true ) ); } break; case Instruction.OpcodeActionTarget.StaticField: { PushStackModel( exRes ); AddOperator( LoadStaticFieldAddressOperator.New( instr.DebugInfo, fdVal, exRes ) ); } break; default: { PushStackModel( exRes ); AddOperator( AddressAssignmentOperator.New( instr.DebugInfo, exRes, exVal ) ); } break; } } // // LDIND_I1 = Action_LoadIndirect | Type_I1 , // LDIND_U1 = Action_LoadIndirect | Type_U1 , // LDIND_I2 = Action_LoadIndirect | Type_I2 , // LDIND_U2 = Action_LoadIndirect | Type_U2 , // LDIND_I4 = Action_LoadIndirect | Type_I4 , // LDIND_U4 = Action_LoadIndirect | Type_U4 , // LDIND_I8 = Action_LoadIndirect | Type_I8 , // LDIND_I = Action_LoadIndirect | Type_I , // LDIND_R4 = Action_LoadIndirect | Type_R4 , // LDIND_R8 = Action_LoadIndirect | Type_R8 , // LDIND_REF = Action_LoadIndirect | Type_Reference , // private void ProcessInstruction_LoadIndirect( Instruction instr ) { Expression exAddr = GetArgumentFromStack( 0, 1 ); AddOperator( ProcessInstruction_LoadIndirect( instr, exAddr, null ) ); } // // LDELEM_I1 = Action_LoadElement | Type_I1 , // LDELEM_U1 = Action_LoadElement | Type_U1 , // LDELEM_I2 = Action_LoadElement | Type_I2 , // LDELEM_U2 = Action_LoadElement | Type_U2 , // LDELEM_I4 = Action_LoadElement | Type_I4 , // LDELEM_U4 = Action_LoadElement | Type_U4 , // LDELEM_I8 = Action_LoadElement | Type_I8 , // LDELEM_I = Action_LoadElement | Type_I , // LDELEM_R4 = Action_LoadElement | Type_R4 , // LDELEM_R8 = Action_LoadElement | Type_R8 , // LDELEM_REF = Action_LoadElement | Type_Reference , // LDELEM = Action_LoadElement | Type_Token , // private void ProcessInstruction_LoadElement( Instruction instr ) { Expression exAddr = GetArgumentFromStack( 0, 2 ); Expression exIndex = GetArgumentFromStack( 1, 2 ); TypeRepresentation td = exAddr.Type; if(td is SzArrayReferenceTypeRepresentation) { SzArrayReferenceTypeRepresentation tdArray = (SzArrayReferenceTypeRepresentation)td; TypeRepresentation tdElement = tdArray.ContainedType; VariableExpression exRes = CreateNewTemporary( tdElement ); TypeRepresentation tdFormal = ProcessInstruction_GetTypeFromActionType( instr, exRes.Type ); if(tdFormal.CanBeAssignedFrom( tdElement, null ) == false) { throw TypeConsistencyErrorException.Create( "Expecting array type {0}, got {1}", tdFormal, exRes.Type ); } ModifyStackModel( 2, exRes ); AddOperator( LoadElementOperator.New( instr.DebugInfo, exRes, exAddr, exIndex, null, true ) ); } else { throw TypeConsistencyErrorException.Create( "Expecting zero-based array type, got {0}", td ); } } // // LDELEMA = Action_LoadElementAddress | Type_Token , // private void ProcessInstruction_LoadElementAddress( Instruction instr ) { Expression exAddr = GetArgumentFromStack( 0, 2 ); Expression exIndex = GetArgumentFromStack( 1, 2 ); TypeRepresentation td = exAddr.Type; if(m_mod_fReadonly) { // TODO: Implement the modifier. } if(td is SzArrayReferenceTypeRepresentation) { SzArrayReferenceTypeRepresentation tdArray = (SzArrayReferenceTypeRepresentation)td; TypeRepresentation tdElement = ProcessInstruction_GetTypeFromActionType( instr, null ); VariableExpression exRes = CreateNewTemporary( m_typeSystem.CreateManagedPointerToType( tdElement ) ); if(tdArray.ContainedType != tdElement) { throw TypeConsistencyErrorException.Create( "Expecting array type {0}, got {1}", tdElement, tdArray.ContainedType ); } ModifyStackModel( 2, exRes ); AddOperator( LoadElementAddressOperator.New( instr.DebugInfo, exRes, exAddr, exIndex, null, true ) ); } else { throw TypeConsistencyErrorException.Create( "Expecting zero-based array type, got {0}", td ); } } // // STARG = Action_Store | Target_Argument , // STLOC = Action_Store | Target_Local , // STFLD = Action_Store | Target_Field , // STSFLD = Action_Store | Target_StaticField , // private void ProcessInstruction_Store( Instruction instr ) { TypeRepresentation tdTarget; FieldRepresentation fdTarget; Expression exTarget = ProcessInstruction_GetTypeOfActionTarget( instr, out tdTarget, out fdTarget ); switch(instr.Operator.ActionTarget) { case Instruction.OpcodeActionTarget.Field: { Expression exObj = GetArgumentFromStack( 0, 2 ); Expression exVal = GetArgumentFromStack( 1, 2 ); TypeRepresentation tdObj = exObj.Type; if(tdObj.GetInstantiationFlavor( m_typeSystem ) == TypeRepresentation.InstantiationFlavor.Delayed) { throw TypeConsistencyErrorException.Create( "Cannot access the fields of delayed type {0}", tdObj ); } PopStackModel( 2 ); exObj = EnsurePointerType(exObj, fdTarget.OwnerType, instr.DebugInfo); AddOperator( StoreInstanceFieldOperator.New( instr.DebugInfo, fdTarget, exObj, exVal, true ) ); } break; case Instruction.OpcodeActionTarget.StaticField: { Expression exVal = GetArgumentFromStack( 0, 1 ); PopStackModel( 1 ); AddOperator( StoreStaticFieldOperator.New( instr.DebugInfo, fdTarget, exVal ) ); } break; default: { Expression exVal = GetArgumentFromStack( 0, 1 ); PopStackModel( 1 ); AddOperator( SingleAssignmentOperator.New( instr.DebugInfo, (VariableExpression)exTarget, exVal ) ); } break; } } // // STIND_REF = Action_StoreIndirect | Type_Reference , // STIND_I1 = Action_StoreIndirect | Type_I1 , // STIND_I2 = Action_StoreIndirect | Type_I2 , // STIND_I4 = Action_StoreIndirect | Type_I4 , // STIND_I8 = Action_StoreIndirect | Type_I8 , // STIND_R4 = Action_StoreIndirect | Type_R4 , // STIND_R8 = Action_StoreIndirect | Type_R8 , // STIND_I = Action_StoreIndirect | Type_I , // private void ProcessInstruction_StoreIndirect( Instruction instr ) { Expression exAddr = GetArgumentFromStack( 0, 2 ); Expression exValue = GetArgumentFromStack( 1, 2 ); AddOperator( ProcessInstruction_StoreIndirect( instr, exAddr, exValue, null ) ); } // // STELEM_I = Action_StoreElement | Type_I , // STELEM_I1 = Action_StoreElement | Type_I1 , // STELEM_I2 = Action_StoreElement | Type_I2 , // STELEM_I4 = Action_StoreElement | Type_I4 , // STELEM_I8 = Action_StoreElement | Type_I8 , // STELEM_R4 = Action_StoreElement | Type_R4 , // STELEM_R8 = Action_StoreElement | Type_R8 , // STELEM_REF = Action_StoreElement | Type_Reference , // STELEM = Action_StoreElement | Type_Token , // private void ProcessInstruction_StoreElement( Instruction instr ) { Expression exAddr = GetArgumentFromStack( 0, 3 ); Expression exIndex = GetArgumentFromStack( 1, 3 ); Expression exValue = GetArgumentFromStack( 2, 3 ); TypeRepresentation td = exAddr.Type; if(td is SzArrayReferenceTypeRepresentation) { SzArrayReferenceTypeRepresentation tdArray = (SzArrayReferenceTypeRepresentation)td; TypeRepresentation tdFormal = ProcessInstruction_GetTypeFromActionType( instr, tdArray.ContainedType ); if(exValue is ConstantExpression) { exValue = CoerceConstantToType( (ConstantExpression)exValue, tdFormal ); } if(!CanBeAssignedFromEvaluationStack( tdFormal, exValue )) { throw TypeConsistencyErrorException.Create( "Expecting array type {0}, got {1}", tdFormal, exValue.Type ); } PopStackModel( 3 ); AddOperator( StoreElementOperator.New( instr.DebugInfo, exAddr, exIndex, exValue, null, true ) ); } else { throw TypeConsistencyErrorException.Create( "Expecting zero-based array type, got {0}", td ); } } // // DUP = Action_Stack | Stack_Dup , // POP = Action_Stack | Stack_Pop , // LOCALLOC = Action_Stack | Stack_LocAlloc , // private void ProcessInstruction_Stack( Instruction instr ) { switch(instr.Operator.ActionStack) { case Instruction.OpcodeActionStack.Dup: { Expression ex = GetArgumentFromStack( 0, 1 ); VariableExpression exRes = CreateNewTemporary( ex.Type ); VariableExpression exRes2 = CreateNewTemporary( ex.Type ); PopStackModel( 1 ); PushStackModel( exRes ); PushStackModel( exRes2 ); AddOperator( SingleAssignmentOperator.New( instr.DebugInfo, exRes, ex ) ); AddOperator( SingleAssignmentOperator.New( instr.DebugInfo, exRes2, ex ) ); } break; case Instruction.OpcodeActionStack.Pop: { PopStackModel( 1 ); AddOperator( NopOperator.New( instr.DebugInfo ) ); } break; case Instruction.OpcodeActionStack.LocAlloc: { Expression exSize = GetArgumentFromStack( 0, 1 ); VariableExpression exRes = CreateNewTemporary( m_typeSystem.WellKnownTypes.System_IntPtr ); ModifyStackModel( 1, exRes ); AddOperator( StackAllocationOperator.New( instr.DebugInfo, exRes, exSize ) ); } break; case Instruction.OpcodeActionStack.ArgList: { VariableExpression exRes = CreateNewTemporary( m_typeSystem.WellKnownTypes.System_RuntimeArgumentHandle ); PushStackModel( exRes ); AddOperator( ArgListOperator.New( instr.DebugInfo, exRes ) ); } break; default: { throw IncorrectEncodingException.Create( "Invalid OpcodeActionStack {0} for {1}", instr.Operator.ActionStack, instr ); } } } // // JMP = Action_Jump , // private void ProcessInstruction_Jump( Instruction instr ) { throw new NotImplementedException(); } // // CALL = Action_Call | Call_Direct , // CALLI = Action_Call | Call_Indirect , // CALLVIRT = Action_Call | Call_Virtual , // private void ProcessInstruction_Call( Instruction instr ) { if(m_mod_fTailCall) { // TODO: Implement the modifier. } if(m_mod_constrained != null) { // TODO: Implement the modifier. } switch(instr.Operator.ActionCall) { case Instruction.OpcodeActionCall.Direct: case Instruction.OpcodeActionCall.Virtual: { MethodRepresentation md = this.CurrentArgumentAsMethod; TypeRepresentation[] args = md.ThisPlusArguments; int argsNum = args.Length; bool fInstance = md is InstanceMethodRepresentation; int skip = fInstance ? 0 : 1; // Static methods has an extra slot in the Arguments array. Expression[] exActual = new Expression[argsNum]; VariableExpression exRes; if(fInstance) { TypeRepresentation tdThis = args[0]; exActual[0] = GetArgumentFromStack( 0, argsNum ); if(m_mod_constrained != null) { exActual[0] = EnsurePointerType(exActual[0], m_mod_constrained, instr.DebugInfo); ManagedPointerTypeRepresentation tdActual2 = exActual[0].Type as ManagedPointerTypeRepresentation; if(tdActual2 == null || tdActual2.ContainedType != m_mod_constrained) { throw TypeConsistencyErrorException.Create( "Incorrect 'this' argument on constrained call to {0} from {1}: got {2}, expecting {3}", md, m_md, exActual[0].Type, md.OwnerType ); } TypeRepresentation tdActual3 = tdActual2.ContainedType; if(m_mod_constrained is ReferenceTypeRepresentation) { VariableExpression ex = CreateNewTemporary( m_mod_constrained ); AddOperator( LoadIndirectOperator.New( instr.DebugInfo, m_mod_constrained, ex, exActual[0], null, 0, false, true ) ); exActual[0] = ex; } else { MethodRepresentation md2 = tdActual3.FindMatch( md, null ); if(md2 != null) { md = md2; args = md.ThisPlusArguments; tdThis = args[0]; } else { TypeRepresentation tdBoxed = m_typeSystem.CreateBoxedValueType( (ValueTypeRepresentation)m_mod_constrained ); VariableExpression ex = CreateNewTemporary( m_mod_constrained ); AddOperator( LoadIndirectOperator.New( instr.DebugInfo, m_mod_constrained, ex, exActual[0], null, 0, false, true ) ); exRes = CreateNewTemporary( tdBoxed ); AddOperator( BoxOperator.New( instr.DebugInfo, tdBoxed, exRes, ex ) ); exActual[0] = exRes; } } } if(!CanBeAssignedFromEvaluationStack( tdThis, exActual[0] )) { throw TypeConsistencyErrorException.Create( "Incorrect 'this' argument on call to {0} from {1}: got {2}, expecting {3}", md, m_md, exActual[0].Type, md.OwnerType ); } } else { exActual[0] = CreateNewNullPointer( args[0] ); } for(int i = 1; i < argsNum; i++) { exActual[i] = GetArgumentFromStack( i - 1, argsNum - 1, args[i] ); if(!CanBeAssignedFromEvaluationStack( args[i], exActual[i] )) { throw TypeConsistencyErrorException.Create( "Incorrect argument {0} on call to {1} from {2}: got {3}, expecting {4}", i - 1, md, m_md, exActual[i].Type, args[i] ); } } CallOperator.CallKind callType; if(instr.Operator.ActionCall == Instruction.OpcodeActionCall.Direct) { callType = CallOperator.CallKind.Direct; } else { callType = CallOperator.CallKind.Virtual; } if(md.ReturnType == m_typeSystem.WellKnownTypes.System_Void) { exRes = null; PopStackModel( argsNum - skip ); } else { exRes = CreateNewTemporary( md.ReturnType ); ModifyStackModel( argsNum - skip, exRes ); } var lhs = VariableExpression.ToArray( exRes ); if(fInstance) { AddOperator( InstanceCallOperator.New( instr.DebugInfo, callType, md, lhs, exActual, true ) ); } else { AddOperator( StaticCallOperator.New( instr.DebugInfo, callType, md, lhs, exActual ) ); } } break; case Instruction.OpcodeActionCall.Indirect: { throw new NotImplementedException(); } default: { throw IncorrectEncodingException.Create( "Invalid OpcodeActionCall {0} for {1}", instr.Operator.ActionCall, instr ); } } } // // RET = Action_Return , // private void ProcessInstruction_Return( Instruction instr ) { if(m_cfg.ReturnValue == null) { if(m_activeStackModel.Length != 0) { throw TypeConsistencyErrorException.Create( "Incorrect evaluation stack on method exit for {0}", m_md ); } } else { if(m_activeStackModel.Length != 1) { throw TypeConsistencyErrorException.Create( "Incorrect evaluation stack on method exit for {0}", m_md ); } Expression exRes = GetArgumentFromStack( 0, 1 ); PopStackModel( 1 ); if(!CanBeAssignedFromEvaluationStack( m_cfg.ReturnValue.Type, exRes )) { throw TypeConsistencyErrorException.Create( "Incorrect return type on evaluation stack on method exit for {0}", m_md ); } AddOperator( SingleAssignmentOperator.New( instr.DebugInfo, m_cfg.ReturnValue, exRes ) ); } AddControl( UnconditionalControlOperator.New( instr.DebugInfo, m_exitBasicBlock ) ); } // // BR = Action_Branch | Cond_ALWAYS , // BRFALSE = Action_Branch | Cond_FALSE , // BRTRUE = Action_Branch | Cond_TRUE , // BEQ = Action_Branch | Cond_EQ , // BGE = Action_Branch | Cond_GE , // BGT = Action_Branch | Cond_GT , // BLE = Action_Branch | Cond_LE , // BLT = Action_Branch | Cond_LT , // BNE_UN = Action_Branch | Cond_NE | Unsigned , // BGE_UN = Action_Branch | Cond_GE | Unsigned , // BGT_UN = Action_Branch | Cond_GT | Unsigned , // BLE_UN = Action_Branch | Cond_LE | Unsigned , // BLT_UN = Action_Branch | Cond_LT | Unsigned , // SWITCH = Action_Branch | Cond_Val , // private void ProcessInstruction_Branch( Instruction instr ) { Instruction.OpcodeActionCondition cond = instr.Operator.ActionCondition; ControlOperator op; BasicBlock targetBranchNotTaken = GetBasicBlockFromInstruction( this.CurrentInstructionOffset + 1 ); switch(cond) { case Instruction.OpcodeActionCondition.ALWAYS: { BasicBlock targetBranchTaken = GetBasicBlockFromInstruction( this.CurrentArgumentAsInt32 ); op = UnconditionalControlOperator.New( instr.DebugInfo, targetBranchTaken ); } break; case Instruction.OpcodeActionCondition.TRUE: case Instruction.OpcodeActionCondition.FALSE: { Expression exVal = GetArgumentFromStack( 0, 1 ); BasicBlock targetBranchTaken = GetBasicBlockFromInstruction( this.CurrentArgumentAsInt32 ); PopStackModel( 1 ); if(cond == Instruction.OpcodeActionCondition.FALSE) { BasicBlock tmp; tmp = targetBranchNotTaken; targetBranchNotTaken = targetBranchTaken; targetBranchTaken = tmp; } op = BinaryConditionalControlOperator.New( instr.DebugInfo, exVal, targetBranchNotTaken, targetBranchTaken ); } break; case Instruction.OpcodeActionCondition.Val: { Expression exVal = GetArgumentFromStack( 0, 1 ); int[] offsets = (int[])this.CurrentArgument; BasicBlock[] targets = new BasicBlock[offsets.Length]; for(int i = 0; i < offsets.Length; i++) { targets[i] = GetBasicBlockFromInstruction( offsets[i] ); } PopStackModel( 1 ); op = MultiWayConditionalControlOperator.New( instr.DebugInfo, exVal, targetBranchNotTaken, targets ); } break; default: { Expression exLeft = GetArgumentFromStack( 0, 2 ); Expression exRight = GetArgumentFromStack( 1, 2 ); VariableExpression exRes = CreateNewTemporary( m_typeSystem.WellKnownTypes.System_Int32 ); BasicBlock targetBranchTaken = GetBasicBlockFromInstruction( this.CurrentArgumentAsInt32 ); PopStackModel( 2 ); // // Section 1.5 of ECMA spec, Partition III // StackEquivalentType seLeft = exLeft .StackEquivalentType; StackEquivalentType seRight = exRight.StackEquivalentType; if(seLeft != seRight) { bool fIsPointerLeft = (seLeft == StackEquivalentType.Pointer || seLeft == StackEquivalentType.NativeInt); bool fIsPointerRight = (seRight == StackEquivalentType.Pointer || seRight == StackEquivalentType.NativeInt); // // The ECMA spec says that you can only compare Pointer and NativeInt for equality, but the framework does otherwise... // if(fIsPointerLeft != fIsPointerRight) { throw TypeConsistencyErrorException.Create( "Condition branch operation '{0}' applied to incompatible types: {1} != {2}", instr, exLeft.Type, exRight.Type ); } } CompareAndSetOperator.ActionCondition cond2; switch(cond) { case Instruction.OpcodeActionCondition.EQ: cond2 = CompareAndSetOperator.ActionCondition.EQ; break; case Instruction.OpcodeActionCondition.GE: cond2 = CompareAndSetOperator.ActionCondition.GE; break; case Instruction.OpcodeActionCondition.GT: cond2 = CompareAndSetOperator.ActionCondition.GT; break; case Instruction.OpcodeActionCondition.LE: cond2 = CompareAndSetOperator.ActionCondition.LE; break; case Instruction.OpcodeActionCondition.LT: cond2 = CompareAndSetOperator.ActionCondition.LT; break; case Instruction.OpcodeActionCondition.NE: cond2 = CompareAndSetOperator.ActionCondition.NE; break; default: throw TypeConsistencyErrorException.Create( "Invalid condition {0} for branch operation '{1}'", cond, instr ); } AddOperator( CompareAndSetOperator.New( instr.DebugInfo, cond2, instr.Operator.IsSigned, exRes, exLeft, exRight ) ); op = BinaryConditionalControlOperator.New( instr.DebugInfo, exRes, targetBranchNotTaken, targetBranchTaken ); } break; } AddControl( op ); } // // NOP = Action_ALU | Op_NOP , // ADD = Action_ALU | Op_ADD , // SUB = Action_ALU | Op_SUB , // MUL = Action_ALU | Op_MUL , // DIV = Action_ALU | Op_DIV , // DIV_UN = Action_ALU | Op_DIV | Unsigned , // REM = Action_ALU | Op_REM , // REM_UN = Action_ALU | Op_REM | Unsigned , // AND = Action_ALU | Op_AND , // OR = Action_ALU | Op_OR , // XOR = Action_ALU | Op_XOR , // SHL = Action_ALU | Op_SHL , // SHR = Action_ALU | Op_SHR , // SHR_UN = Action_ALU | Op_SHR | Unsigned , // NEG = Action_ALU | Op_NEG , // NOT = Action_ALU | Op_NOT , // CKFINITE = Action_ALU | Op_FINITE , // ADD_OVF = Action_ALU | Op_ADD | Overflow, // ADD_OVF_UN = Action_ALU | Op_ADD | Unsigned | Overflow, // MUL_OVF = Action_ALU | Op_MUL | Overflow, // MUL_OVF_UN = Action_ALU | Op_MUL | Unsigned | Overflow, // SUB_OVF = Action_ALU | Op_SUB | Overflow, // SUB_OVF_UN = Action_ALU | Op_SUB | Unsigned | Overflow, // private void ProcessInstruction_ALU( Instruction instr ) { Instruction.OpcodeActionALU alu = instr.Operator.ActionALU; switch(alu) { case Instruction.OpcodeActionALU.ADD: case Instruction.OpcodeActionALU.SUB: case Instruction.OpcodeActionALU.MUL: case Instruction.OpcodeActionALU.DIV: case Instruction.OpcodeActionALU.REM: case Instruction.OpcodeActionALU.AND: case Instruction.OpcodeActionALU.OR: case Instruction.OpcodeActionALU.XOR: case Instruction.OpcodeActionALU.SHL: case Instruction.OpcodeActionALU.SHR: { Expression exLeft = GetArgumentFromStack( 0, 2 ); Expression exRight = GetArgumentFromStack( 1, 2 ); TypeRepresentation tdRes = null; StackEquivalentType seLeft = exLeft .StackEquivalentType; StackEquivalentType seRight = exRight.StackEquivalentType; bool fAddSub = alu == Instruction.OpcodeActionALU.ADD || alu == Instruction.OpcodeActionALU.SUB; bool fShift = alu == Instruction.OpcodeActionALU.SHL || alu == Instruction.OpcodeActionALU.SHR; // // Section 1.5 of ECMA spec, Partition III // switch(seLeft) { case StackEquivalentType.Int32: switch(seRight) { case StackEquivalentType.Int32: tdRes = exLeft.Type; break; case StackEquivalentType.NativeInt: tdRes = exRight.Type; break; case StackEquivalentType.Pointer: if(alu == Instruction.OpcodeActionALU.ADD) { tdRes = exRight.Type; } break; } break; case StackEquivalentType.Int64: switch(seRight) { case StackEquivalentType.Int32: if(fShift) { tdRes = exLeft.Type; } break; case StackEquivalentType.Int64: tdRes = exLeft.Type; break; } break; case StackEquivalentType.NativeInt: switch(seRight) { case StackEquivalentType.Int32: tdRes = exLeft.Type; break; case StackEquivalentType.NativeInt: tdRes = exLeft.Type; break; case StackEquivalentType.Pointer: if(fAddSub) { // // The SUB case seems to be prohibited by the ECMA spec, but it occurs in unsafe code. // tdRes = exRight.Type; } break; } break; case StackEquivalentType.Float: switch(seRight) { case StackEquivalentType.Float: tdRes = exLeft.Type; break; } break; case StackEquivalentType.Pointer: switch(seRight) { case StackEquivalentType.Int32: if(alu == Instruction.OpcodeActionALU.DIV) { // // This case seems to be prohibited by the ECMA spec, but it occurs in unsafe code, see System.String.revmemcpyimpl. // tdRes = m_typeSystem.WellKnownTypes.System_IntPtr; } else if(fAddSub) { tdRes = exLeft.Type; } break; case StackEquivalentType.NativeInt: if(fAddSub) { tdRes = exLeft.Type; } break; case StackEquivalentType.Pointer: if(alu == Instruction.OpcodeActionALU.SUB) { tdRes = m_typeSystem.WellKnownTypes.System_IntPtr; } break; } break; } BinaryOperator.ALU alu2; switch(alu) { case Instruction.OpcodeActionALU.ADD: alu2 = BinaryOperator.ALU.ADD; break; case Instruction.OpcodeActionALU.SUB: alu2 = BinaryOperator.ALU.SUB; break; case Instruction.OpcodeActionALU.MUL: alu2 = BinaryOperator.ALU.MUL; break; case Instruction.OpcodeActionALU.DIV: alu2 = BinaryOperator.ALU.DIV; break; case Instruction.OpcodeActionALU.REM: alu2 = BinaryOperator.ALU.REM; break; case Instruction.OpcodeActionALU.AND: alu2 = BinaryOperator.ALU.AND; break; case Instruction.OpcodeActionALU.OR : alu2 = BinaryOperator.ALU.OR ; break; case Instruction.OpcodeActionALU.XOR: alu2 = BinaryOperator.ALU.XOR; break; case Instruction.OpcodeActionALU.SHL: alu2 = BinaryOperator.ALU.SHL; break; case Instruction.OpcodeActionALU.SHR: alu2 = BinaryOperator.ALU.SHR; break; default: throw IncorrectEncodingException.Create( "Invalid OpcodeActionALU {0} for {1}", alu, instr ); } if(tdRes == null) { throw TypeConsistencyErrorException.Create( "ALU operation '{0}' applied to incompatible types: {1} != {2}", instr, exLeft.Type, exRight.Type ); } VariableExpression exRes = CreateNewTemporary( tdRes ); ModifyStackModel( 2, exRes ); bool fSigned; switch(alu) { case Instruction.OpcodeActionALU.MUL: // // There's no unsigned bytecode for mul, but we need to determine the exact flavor for proper expansion. // fSigned = (exLeft.Type.IsSigned || exRight.Type.IsSigned); break; default: fSigned = instr.Operator.IsSigned; break; } AddOperator( BinaryOperator.New( instr.DebugInfo, alu2, fSigned, instr.Operator.RequiresOverflowCheck, exRes, exLeft, exRight ) ); } break; case Instruction.OpcodeActionALU.NEG: case Instruction.OpcodeActionALU.NOT: case Instruction.OpcodeActionALU.FINITE: { Expression ex = GetArgumentFromStack( 0, 1 ); VariableExpression exRes = CreateNewTemporary( ex.Type ); ModifyStackModel( 1, exRes ); UnaryOperator.ALU alu2; switch(alu) { case Instruction.OpcodeActionALU.NEG : alu2 = UnaryOperator.ALU.NEG ; break; case Instruction.OpcodeActionALU.NOT : alu2 = UnaryOperator.ALU.NOT ; break; case Instruction.OpcodeActionALU.FINITE: alu2 = UnaryOperator.ALU.FINITE; break; default: throw IncorrectEncodingException.Create( "Invalid OpcodeActionALU {0} for {1}", alu, instr ); } AddOperator( UnaryOperator.New( instr.DebugInfo, alu2, instr.Operator.IsSigned, instr.Operator.RequiresOverflowCheck, exRes, ex ) ); } break; case Instruction.OpcodeActionALU.NOP: { AddOperator( NopOperator.New( instr.DebugInfo ) ); } break; default: { throw IncorrectEncodingException.Create( "Invalid OpcodeActionALU {0} for {1}", alu, instr ); } } } // // CONV_I1 = Action_Convert | Type_I1 , // CONV_I2 = Action_Convert | Type_I2 , // CONV_I4 = Action_Convert | Type_I4 , // CONV_I8 = Action_Convert | Type_I8 , // CONV_R4 = Action_Convert | Type_R4 , // CONV_R8 = Action_Convert | Type_R8 , // CONV_U4 = Action_Convert | Type_U4 , // CONV_U8 = Action_Convert | Type_U8 , // CONV_R_UN = Action_Convert | Type_R | Unsigned , // CONV_OVF_I1_UN = Action_Convert | Type_I1 | Unsigned | Overflow, // CONV_OVF_I2_UN = Action_Convert | Type_I2 | Unsigned | Overflow, // CONV_OVF_I4_UN = Action_Convert | Type_I4 | Unsigned | Overflow, // CONV_OVF_I8_UN = Action_Convert | Type_I8 | Unsigned | Overflow, // CONV_OVF_U1_UN = Action_Convert | Type_R4 | Unsigned | Overflow, // CONV_OVF_U2_UN = Action_Convert | Type_R8 | Unsigned | Overflow, // CONV_OVF_U4_UN = Action_Convert | Type_U4 | Unsigned | Overflow, // CONV_OVF_U8_UN = Action_Convert | Type_U8 | Unsigned | Overflow, // CONV_OVF_I_UN = Action_Convert | Type_I | Unsigned | Overflow, // CONV_OVF_U_UN = Action_Convert | Type_U | Unsigned | Overflow, // CONV_OVF_I1 = Action_Convert | Type_I1 | Overflow, // CONV_OVF_U1 = Action_Convert | Type_U1 | Overflow, // CONV_OVF_I2 = Action_Convert | Type_I2 | Overflow, // CONV_OVF_U2 = Action_Convert | Type_U2 | Overflow, // CONV_OVF_I4 = Action_Convert | Type_I4 | Overflow, // CONV_OVF_U4 = Action_Convert | Type_U4 | Overflow, // CONV_OVF_I8 = Action_Convert | Type_I8 | Overflow, // CONV_OVF_U8 = Action_Convert | Type_U8 | Overflow, // CONV_U2 = Action_Convert | Type_U2 , // CONV_U1 = Action_Convert | Type_U1 , // CONV_I = Action_Convert | Type_I , // CONV_OVF_I = Action_Convert | Type_I | Overflow, // CONV_OVF_U = Action_Convert | Type_U | Overflow, // CONV_U = Action_Convert | Type_U , // private void ProcessInstruction_Convert( Instruction instr ) { Expression exValue = GetArgumentFromStack( 0, 1 ); ScalarTypeRepresentation td = (ScalarTypeRepresentation)ProcessInstruction_GetTypeFromActionType( instr, this.CurrentArgumentAsType ); if(exValue is ConstantExpression) { ConstantExpression exConst = (ConstantExpression)exValue; Expression exRes = CreateNewConstant( td, exConst.Value ); ModifyStackModel( 1, exRes ); AddOperator( NopOperator.New( instr.DebugInfo ) ); // Value is a constant, nothing to do. } else { VariableExpression exRes = CreateNewTemporary( td ); ModifyStackModel( 1, exRes ); ConvertKind kindSrc = Convert_AnalyzeArgument( exValue ); ConvertKind kindDst = Convert_AnalyzeArgument( exRes ); bool fIsDstSigned = td.IsSigned; bool fIsSrcSigned = instr.Operator.IsSigned; bool fOverflow = instr.Operator.RequiresOverflowCheck; ConvertOp opKind = ConvertOp.Unknown; uint opSize = td.Size; TypeRepresentation.BuiltInTypes kindInput = TypeRepresentation.BuiltInTypes.END; TypeRepresentation.BuiltInTypes kindOutput = TypeRepresentation.BuiltInTypes.END; switch(kindSrc) { case ConvertKind.Int: switch(kindDst) { case ConvertKind.Int: if(fIsSrcSigned == fIsDstSigned && opSize == sizeof(int)) { opKind = ConvertOp.Identity; } else { opKind = fIsDstSigned ? ConvertOp.SignExtend : ConvertOp.ZeroExtend; } break; case ConvertKind.Long: opSize = exValue.Type.Size; opKind = fIsDstSigned ? ConvertOp.SignExtend : ConvertOp.ZeroExtend; break; case ConvertKind.Single: opKind = ConvertOp.Convert; kindInput = fIsSrcSigned ? TypeRepresentation.BuiltInTypes.I4 : TypeRepresentation.BuiltInTypes.U4; kindOutput = TypeRepresentation.BuiltInTypes.R4; break; case ConvertKind.Double: opKind = ConvertOp.Convert; kindInput = fIsSrcSigned ? TypeRepresentation.BuiltInTypes.I4 : TypeRepresentation.BuiltInTypes.U4; kindOutput = TypeRepresentation.BuiltInTypes.R8; break; } break; case ConvertKind.Long: switch(kindDst) { case ConvertKind.Int: opKind = ConvertOp.Truncate; break; case ConvertKind.Long: if(fIsSrcSigned == fIsDstSigned) { opKind = ConvertOp.Identity; } else { opKind = fIsDstSigned ? ConvertOp.SignExtend : ConvertOp.ZeroExtend; } break; case ConvertKind.Single: opKind = ConvertOp.Convert; kindInput = fIsSrcSigned ? TypeRepresentation.BuiltInTypes.I8 : TypeRepresentation.BuiltInTypes.U8; kindOutput = TypeRepresentation.BuiltInTypes.R4; break; case ConvertKind.Double: opKind = ConvertOp.Convert; kindInput = fIsSrcSigned ? TypeRepresentation.BuiltInTypes.I8 : TypeRepresentation.BuiltInTypes.U8; kindOutput = TypeRepresentation.BuiltInTypes.R8; break; } break; case ConvertKind.Single: switch(kindDst) { case ConvertKind.Int: opKind = ConvertOp.Convert; kindInput = TypeRepresentation.BuiltInTypes.R4; kindOutput = fIsDstSigned ? TypeRepresentation.BuiltInTypes.I4 : TypeRepresentation.BuiltInTypes.U4; break; case ConvertKind.Long: opKind = ConvertOp.Convert; kindInput = TypeRepresentation.BuiltInTypes.R4; kindOutput = fIsDstSigned ? TypeRepresentation.BuiltInTypes.I8 : TypeRepresentation.BuiltInTypes.U8; break; case ConvertKind.Single: opKind = ConvertOp.Identity; break; case ConvertKind.Double: opKind = ConvertOp.Convert; kindInput = TypeRepresentation.BuiltInTypes.R4; kindOutput = TypeRepresentation.BuiltInTypes.R8; break; } break; case ConvertKind.Double: switch(kindDst) { case ConvertKind.Int: opKind = ConvertOp.Convert; kindInput = TypeRepresentation.BuiltInTypes.R8; kindOutput = fIsDstSigned ? TypeRepresentation.BuiltInTypes.I4 : TypeRepresentation.BuiltInTypes.U4; break; case ConvertKind.Long: opKind = ConvertOp.Convert; kindInput = TypeRepresentation.BuiltInTypes.R8; kindOutput = fIsDstSigned ? TypeRepresentation.BuiltInTypes.I8 : TypeRepresentation.BuiltInTypes.U8; break; case ConvertKind.Single: opKind = ConvertOp.Convert; kindInput = TypeRepresentation.BuiltInTypes.R8; kindOutput = TypeRepresentation.BuiltInTypes.R4; break; case ConvertKind.Double: opKind = ConvertOp.Identity; break; } break; case ConvertKind.Pointer: case ConvertKind.Object: switch(kindDst) { case ConvertKind.Int: opKind = ConvertOp.Identity; break; case ConvertKind.Long: opSize = exValue.Type.Size; opKind = fIsDstSigned ? ConvertOp.SignExtend : ConvertOp.ZeroExtend; break; } break; } switch(opKind) { case ConvertOp.Unknown: throw new NotImplementedException(); case ConvertOp.Identity: AddOperator( SingleAssignmentOperator.New( instr.DebugInfo, exRes, exValue ) ); break; case ConvertOp.ZeroExtend: AddOperator( ZeroExtendOperator.New( instr.DebugInfo, opSize, fOverflow, exRes, exValue ) ); break; case ConvertOp.SignExtend: AddOperator( SignExtendOperator.New( instr.DebugInfo, opSize, fOverflow, exRes, exValue ) ); break; case ConvertOp.Truncate: AddOperator( TruncateOperator.New( instr.DebugInfo, opSize, fOverflow, exRes, exValue ) ); break; case ConvertOp.Convert: AddOperator( ConvertOperator.New( instr.DebugInfo, kindInput, kindOutput, fOverflow, exRes, exValue ) ); break; } } } enum ConvertKind { Int , Long , Single , Double , Pointer, Object , } enum ConvertOp { Unknown , Identity , ZeroExtend, SignExtend, Truncate , Convert , } private static ConvertKind Convert_AnalyzeArgument( Expression ex ) { TypeRepresentation td = ex.Type; if(td is PointerTypeRepresentation) { return ConvertKind.Pointer; } else if(td is ReferenceTypeRepresentation) { return ConvertKind.Object; } else if(td is ScalarTypeRepresentation) { if(td.IsInteger) { return td.Size == 4 ? ConvertKind.Int : ConvertKind.Long; } else if(td.IsFloatingPoint) { return td.Size == 4 ? ConvertKind.Single : ConvertKind.Double; } } throw TypeConsistencyErrorException.Create( "Type '{0}' cannot be used in a convert context", td ); } //--// // // CPOBJ = Action_Object | Obj_CpObj , // LDOBJ = Action_Object | Obj_LdObj , // NEWOBJ = Action_Object | Obj_New , // CASTCLASS = Action_Object | Obj_Cast , // ISINST = Action_Object | Obj_IsInst , // UNBOX = Action_Object | Obj_Unbox , // STOBJ = Action_Object | Obj_StObj , // BOX = Action_Object | Obj_Box , // NEWARR = Action_Object | Obj_NewArr , // LDLEN = Action_Object | Obj_LdLen , // UNBOX_ANY = Action_Object | Obj_UnboxAny , // LDFTN = Action_Object | Obj_LdFtn , // LDVIRTFTN = Action_Object | Obj_LdVirtFtn , // INITOBJ = Action_Object | Obj_InitObj , // CPBLK = Action_Object | Obj_CpBlk , // INITBLK = Action_Object | Obj_InitBlk , // SIZEOF = Action_Object | Obj_SizeOf , // private void ProcessInstruction_Object( Instruction instr ) { switch(instr.Operator.ActionObject) { case Instruction.OpcodeActionObject.New: { MethodRepresentation md = this.CurrentArgumentAsMethod; TypeRepresentation[] args = md.ThisPlusArguments; int argsNum = args.Length; Expression[] exActual = new Expression[argsNum]; TypeRepresentation thisTd = args[0]; LocalVariableExpression local = null; // // If we are allocate a value type on the stack, we need to: // // 1) Create a local variable. // 2) Initialize it to zero. // 3) Take its address and store it in a temporary. // 4) Call the constructor using the address as the this pointer. // 5) Put the local variable on the evaluation stack. // if(thisTd is ManagedPointerTypeRepresentation) { Debug.Assert(thisTd.UnderlyingType is ValueTypeRepresentation, "Only value types can be passed as managed pointers for 'this' argument."); local = m_cfg.AllocateLocal( thisTd.UnderlyingType, null ); } TemporaryVariableExpression tmp = CreateNewTemporary( thisTd ); exActual[0] = tmp; for(int i = 1; i < argsNum; i++) { exActual[i] = GetArgumentFromStack( i - 1, argsNum - 1, args[i] ); if(!CanBeAssignedFromEvaluationStack( args[i], exActual[i] )) { throw TypeConsistencyErrorException.Create( "Incorrect argument {0} on call to {1} from {2}: got {3}, expecting {4}", i - 1, md, m_md, exActual[i].Type, args[i] ); } } ModifyStackModel( argsNum - 1, local ?? exActual[0] ); if(local != null) { AddOperator( m_cfg.GenerateVariableInitialization( instr.DebugInfo, local ) ); AddOperator( AddressAssignmentOperator.New ( instr.DebugInfo, tmp, local ) ); } else { Expression[] exArgs = ArrayUtility.RemoveAtPositionFromNotNullArray( exActual, 0 ); AddOperator( ObjectAllocationOperator.New( instr.DebugInfo, md, (VariableExpression)exActual[0], exArgs ) ); } AddOperator( InstanceCallOperator.New( instr.DebugInfo, CallOperator.CallKind.Direct, md, exActual, true ) ); } break; case Instruction.OpcodeActionObject.NewArr: { TypeRepresentation td = this.CurrentArgumentAsType; Expression exLength = GetArgumentFromStack( 0, 1 ); VariableExpression exRes = CreateNewTemporary( m_typeSystem.CreateArrayOfType( td ) ); ModifyStackModel( 1, exRes ); AddOperator( ArrayAllocationOperator.New( instr.DebugInfo, exRes.Type, exRes, exLength ) ); } break; case Instruction.OpcodeActionObject.LdLen: { Expression exArray = GetArgumentFromStack( 0, 1 ); TypeRepresentation tdArray = exArray.Type; if(!(tdArray is ArrayReferenceTypeRepresentation)) { throw TypeConsistencyErrorException.Create( "Expecting an array, found {0}", tdArray ); } VariableExpression ex = CreateNewTemporary( m_typeSystem.WellKnownTypes.System_UIntPtr ); ModifyStackModel( 1, ex ); AddOperator( ArrayLengthOperator.New( instr.DebugInfo, ex, exArray ) ); } break; case Instruction.OpcodeActionObject.Cast: { Expression exValue = GetArgumentFromStack( 0, 1 ); TypeRepresentation td = m_typeSystem.CreateBoxedValueTypeIfNecessary( this.CurrentArgumentAsType ); VariableExpression exRes = CreateNewTemporary( td ); // // Exact match? No need to do a cast. // if(exValue.Type == td) { AddOperator( SingleAssignmentOperator.New( instr.DebugInfo, exRes, exValue ) ); } else { AddOperator( CastOperator.New( instr.DebugInfo, td, exRes, exValue ) ); } ModifyStackModel( 1, exRes ); } break; case Instruction.OpcodeActionObject.IsInst: { Expression exVal = GetArgumentFromStack( 0, 1 ); TypeRepresentation td = m_typeSystem.CreateBoxedValueTypeIfNecessary( this.CurrentArgumentAsType ); if(CanBeAssignedFromEvaluationStack( td, exVal )) { // // We can statically prove that the expression is an instance of the required type, // so there's nothing to do. // AddOperator( NopOperator.New( instr.DebugInfo ) ); } else { VariableExpression exRes = CreateNewTemporary( td ); ModifyStackModel( 1, exRes ); AddOperator( IsInstanceOperator.New( instr.DebugInfo, td, exRes, exVal ) ); } } break; case Instruction.OpcodeActionObject.Box: { Expression exVal = GetArgumentFromStack( 0, 1 ); TypeRepresentation td = this.CurrentArgumentAsType; switch(td.GetInstantiationFlavor( m_typeSystem )) { case TypeRepresentation.InstantiationFlavor.Class: { VariableExpression exRes = CreateNewTemporary( td ); ModifyStackModel( 1, exRes ); AddOperator( SingleAssignmentOperator.New( instr.DebugInfo, exRes, exVal ) ); } break; case TypeRepresentation.InstantiationFlavor.Delayed: case TypeRepresentation.InstantiationFlavor.ValueType: if(m_typeSystem.IsNullable( td )) { TypeRepresentation tdBoxedNullable = m_typeSystem.CreateBoxedValueType( td ); TypeRepresentation tdBoxed = m_typeSystem.CreateBoxedValueType( m_typeSystem.GetNullableParameter( td ) ); VariableExpression exResPtr = CreateNewTemporary( tdBoxedNullable ); VariableExpression exRes = CreateNewTemporary( tdBoxed ); MethodRepresentation mdBox = td.FindMatch( "Box" ); AddOperator( AddressAssignmentOperator.New( instr.DebugInfo, exResPtr, exVal ) ); AddOperator( InstanceCallOperator.New( instr.DebugInfo, CallOperator.CallKind.Direct, mdBox, VariableExpression.ToArray( exRes ), new Expression[] { exResPtr }, false ) ); } else { TypeRepresentation tdBoxed = m_typeSystem.CreateBoxedValueTypeIfNecessary( td ); VariableExpression exRes = CreateNewTemporary( tdBoxed ); ModifyStackModel( 1, exRes ); AddOperator( BoxOperator.New( instr.DebugInfo, tdBoxed, exRes, exVal ) ); } break; default: throw TypeConsistencyErrorException.Create( "Uncorrect type for boxing: {0}", td ); } } break; case Instruction.OpcodeActionObject.Unbox: { Expression exBoxed = GetArgumentFromStack( 0, 1 ); TypeRepresentation td = this.CurrentArgumentAsType; TypeRepresentation tdBoxed = m_typeSystem.CreateBoxedValueTypeIfNecessary( td ); TypeRepresentation tdPtr = m_typeSystem.CreateManagedPointerToType ( td ); VariableExpression exRes = CreateNewTemporary( tdPtr ); // // Exact match? No need to do a cast. // if(exBoxed.Type == tdBoxed) { AddOperator( UnboxOperator.New( instr.DebugInfo, tdBoxed, exRes, exBoxed ) ); } else { VariableExpression exCasted = CreateNewTemporary( tdBoxed ); AddOperator( CastOperator.New( instr.DebugInfo, tdBoxed, exCasted, exBoxed ) ); AddOperator( UnboxOperator.New( instr.DebugInfo, tdBoxed, exRes, exBoxed ) ); } ModifyStackModel( 1, exRes ); } break; case Instruction.OpcodeActionObject.UnboxAny: { Expression exBoxed = GetArgumentFromStack( 0, 1 ); TypeRepresentation td = this.CurrentArgumentAsType; VariableExpression exRes = CreateNewTemporary( td ); switch(td.GetInstantiationFlavor( m_typeSystem )) { case TypeRepresentation.InstantiationFlavor.Class: { // // Exact match? No need to do a cast. // if(exBoxed.Type == td) { AddOperator( SingleAssignmentOperator.New( instr.DebugInfo, exRes, exBoxed ) ); } else { AddOperator( CastOperator.New( instr.DebugInfo, td, exRes, exBoxed ) ); } } break; case TypeRepresentation.InstantiationFlavor.Delayed: case TypeRepresentation.InstantiationFlavor.ValueType: { TypeRepresentation tdBoxed = m_typeSystem.CreateBoxedValueTypeIfNecessary( td ); TypeRepresentation tdPtr = m_typeSystem.CreateManagedPointerToType ( td ); VariableExpression exPtr = CreateNewTemporary( tdPtr ); // // Exact match? No need to do a cast. // if(exBoxed.Type == tdBoxed) { AddOperator( UnboxOperator.New( instr.DebugInfo, tdBoxed, exPtr, exBoxed ) ); } else { VariableExpression exCasted = CreateNewTemporary( tdBoxed ); AddOperator( CastOperator.New( instr.DebugInfo, tdBoxed, exCasted, exBoxed ) ); AddOperator( UnboxOperator.New( instr.DebugInfo, tdBoxed, exPtr, exCasted ) ); } AddOperator( LoadIndirectOperator.New( instr.DebugInfo, td, exRes, exPtr, null, 0, false, true ) ); } break; default: throw TypeConsistencyErrorException.Create( "Uncorrect type for boxing: {0}", td ); } ModifyStackModel( 1, exRes ); } break; case Instruction.OpcodeActionObject.LdFtn: { VariableExpression exRes = CreateNewTemporary( m_typeSystem.WellKnownTypes.System_IntPtr ); PushStackModel( exRes ); AddOperator( MethodRepresentationOperator.New( instr.DebugInfo, this.CurrentArgumentAsMethod, exRes ) ); } break; case Instruction.OpcodeActionObject.LdVirtFtn: { Expression exObj = GetArgumentFromStack( 0, 1 ); VariableExpression exRes = CreateNewTemporary( m_typeSystem.WellKnownTypes.System_IntPtr ); ModifyStackModel( 1, exRes ); AddOperator( MethodRepresentationOperator.New( instr.DebugInfo, this.CurrentArgumentAsMethod, exRes, exObj ) ); } break; case Instruction.OpcodeActionObject.InitObj: { Expression exAddr = GetArgumentFromStack( 0, 1 ); TypeRepresentation td = ProcessInstruction_ExtractAddressType( instr, exAddr, this.CurrentArgumentAsType ); PopStackModel( 1 ); AddOperator( m_cfg.GenerateVariableInitialization( instr.DebugInfo, exAddr, td, true ) ); } break; case Instruction.OpcodeActionObject.LdObj: { Expression exAddr = GetArgumentFromStack( 0, 1 ); AddOperator( ProcessInstruction_LoadIndirect( instr, exAddr, this.CurrentArgumentAsType ) ); } break; case Instruction.OpcodeActionObject.CpObj: { TypeRepresentation td = this.CurrentArgumentAsType; Expression exAddrDst = GetArgumentFromStack( 0, 2 ); Expression exAddrSrc = GetArgumentFromStack( 1, 2 ); Expression exValue; AddOperator( ProcessInstruction_LoadIndirect( instr, exAddrSrc, td ) ); exValue = GetArgumentFromStack( 1, 2 ); AddOperator( ProcessInstruction_StoreIndirect( instr, exAddrDst, exValue, td ) ); } break; case Instruction.OpcodeActionObject.StObj: { Expression exAddr = GetArgumentFromStack( 0, 2 ); Expression exValue = GetArgumentFromStack( 1, 2 ); AddOperator( ProcessInstruction_StoreIndirect( instr, exAddr, exValue, this.CurrentArgumentAsType ) ); } break; case Instruction.OpcodeActionObject.InitBlk: { throw new NotImplementedException(); } case Instruction.OpcodeActionObject.CpBlk: { throw new NotImplementedException(); } case Instruction.OpcodeActionObject.SizeOf: { VariableExpression exRes = CreateNewTemporary( m_typeSystem.WellKnownTypes.System_UInt32 ); PushStackModel( exRes ); // // Section 4.25 of ECMA spec, Partition III // // [Rationale: The definition of a value type can change between the time the CIL is generated and the time that it // is loaded for execution. Thus, the size of the type is not always known when the CIL is generated. The sizeof // instruction allows CIL code to determine the size at runtime without the need to call into the Framework class // library. The computation can occur entirely at runtime or at CIL-to-native-code compilation time. sizeof // returns the total size that would be occupied by each element in an array of this type including any padding // the implementation chooses to add. Specifically, array elements lie sizeof bytes apart. end rationale] // TypeRepresentation td = this.CurrentArgumentAsType; if(!(td is ValueTypeRepresentation)) { td = m_typeSystem.WellKnownTypes.System_UIntPtr; } AddOperator( SingleAssignmentOperator.New( instr.DebugInfo, exRes, m_typeSystem.CreateConstantForTypeSize( td ) ) ); } break; default: { throw IncorrectEncodingException.Create( "Invalid OpcodeActionObject {0} for {1}", instr.Operator.ActionObject, instr ); } } } // // REFANYVAL = Action_TypedRef | TypedRef_RefAnyVal , // MKREFANY = Action_TypedRef | TypedRef_MkRefAny , // REFANYTYPE = Action_TypedRef | TypedRef_RefAnyType , // private void ProcessInstruction_TypedRef( Instruction instr ) { switch(instr.Operator.ActionTypedReference) { case Instruction.OpcodeActionTypedReference.RefAnyVal: { TypeRepresentation td = m_typeSystem.CreateManagedPointerToType( this.CurrentArgumentAsType ); Expression exTypedref = GetArgumentFromStack( 0, 1 ); VariableExpression exRes = CreateNewTemporary( td ); ModifyStackModel( 1, exRes ); AddOperator( RefAnyValOperator.New( instr.DebugInfo, td, exRes, exTypedref ) ); } break; case Instruction.OpcodeActionTypedReference.MkRefAny: { TypeRepresentation td = m_typeSystem.CreateManagedPointerToType( this.CurrentArgumentAsType ); Expression exPtr = GetArgumentFromStack( 0, 1 ); VariableExpression exRes = CreateNewTemporary( m_typeSystem.WellKnownTypes.System_TypedReference ); ModifyStackModel( 1, exRes ); AddOperator( MkRefAnyOperator.New( instr.DebugInfo, td, exRes, exPtr ) ); } break; case Instruction.OpcodeActionTypedReference.RefAnyType: { Expression exTypedref = GetArgumentFromStack( 0, 1 ); VariableExpression exRes = CreateNewTemporary( m_typeSystem.WellKnownTypes.System_RuntimeTypeHandle ); ModifyStackModel( 1, exRes ); AddOperator( RefAnyTypeOperator.New( instr.DebugInfo, exRes, exTypedref ) ); } break; default: { throw IncorrectEncodingException.Create( "Invalid OpcodeActionTypedReference {0} for {1}", instr.Operator.ActionTypedReference, instr ); } } } // // THROW = Action_EH | EH_Throw , // ENDFINALLY = Action_EH | EH_EndFinally , // LEAVE = Action_EH | EH_Leave , // LEAVE_S = Action_EH | EH_Leave , // ENDFILTER = Action_EH | EH_EndFilter , // RETHROW = Action_EH | EH_ReThrow , // private void ProcessInstruction_ExceptionHandling( Instruction instr ) { ControlOperator op; switch(instr.Operator.ActionExceptionHandling) { case Instruction.OpcodeActionExceptionHandling.Throw: { Expression ex = GetArgumentFromStack( 0, 1 ); EmptyStackModel(); op = ThrowControlOperator.New( instr.DebugInfo, ex ); } break; case Instruction.OpcodeActionExceptionHandling.EndFinally: { EmptyStackModel(); op = EndFinallyControlOperator.New( instr.DebugInfo ); } break; case Instruction.OpcodeActionExceptionHandling.Leave: { BasicBlock targetBranchTaken = GetBasicBlockFromInstruction( this.CurrentArgumentAsInt32 ); EmptyStackModel(); op = LeaveControlOperator.New( instr.DebugInfo, targetBranchTaken ); } break; case Instruction.OpcodeActionExceptionHandling.EndFilter: { throw new NotImplementedException(); } case Instruction.OpcodeActionExceptionHandling.ReThrow: { EmptyStackModel(); op = RethrowControlOperator.New( instr.DebugInfo ); } break; default: { throw IncorrectEncodingException.Create( "Invalid OpcodeActionExceptionHandling {0} for {1}", instr.Operator.ActionExceptionHandling, instr ); } } AddControl( op ); } // // CEQ = Action_Set | Cond_EQ , // CGT = Action_Set | Cond_GT , // CGT_UN = Action_Set | Cond_GT | Unsigned , // CLT = Action_Set | Cond_LT , // CLT_UN = Action_Set | Cond_LT | Unsigned , // private void ProcessInstruction_Set( Instruction instr ) { Expression exLeft = GetArgumentFromStack( 0, 2 ); Expression exRight = GetArgumentFromStack( 1, 2 ); VariableExpression exRes = CreateNewTemporary( m_typeSystem.WellKnownTypes.System_Int32 ); ModifyStackModel( 2, exRes ); // // Section 1.5 of ECMA spec, Partition III // BUGBUG: several cases we do not handle yet... // StackEquivalentType seLeft = exLeft .StackEquivalentType; StackEquivalentType seRight = exRight.StackEquivalentType; if(seLeft != seRight) { // ints and manager pointers are 1-o-1 compatible if(seLeft == StackEquivalentType.NativeInt && seRight == StackEquivalentType.Int32 || seLeft == StackEquivalentType.Int32 && seRight == StackEquivalentType.NativeInt) { } else if(seLeft == StackEquivalentType.Pointer && (exRight.CanBeNull == CanBeNull.Yes || seRight == StackEquivalentType.NativeInt)) { } else if(seRight == StackEquivalentType.Pointer && (exLeft.CanBeNull == CanBeNull.Yes || seLeft == StackEquivalentType.NativeInt)) { } else { throw TypeConsistencyErrorException.Create( "CompareAndSet operation '{0}' applied to incompatible types: {1} != {2}", instr, exLeft.Type, exRight.Type ); } } CompareAndSetOperator.ActionCondition cond2; switch(instr.Operator.ActionCondition) { case Instruction.OpcodeActionCondition.EQ: cond2 = CompareAndSetOperator.ActionCondition.EQ; break; case Instruction.OpcodeActionCondition.GT: cond2 = CompareAndSetOperator.ActionCondition.GT; break; case Instruction.OpcodeActionCondition.LT: cond2 = CompareAndSetOperator.ActionCondition.LT; break; default: throw TypeConsistencyErrorException.Create( "Invalid condition {0} for set operation '{1}'", instr.Operator.ActionCondition, instr ); } // // " Greater Than Zero" for an unsigned variable is equivalent to " Not Equal to Zero". // if(exRight.IsEqualToZero()) { if(instr.Operator.IsSigned == false && cond2 == CompareAndSetOperator.ActionCondition.GT) { cond2 = CompareAndSetOperator.ActionCondition.NE; } } AddOperator( CompareAndSetOperator.New( instr.DebugInfo, cond2, instr.Operator.IsSigned, exRes, exLeft, exRight ) ); } // // UNALIGNED = Action_Modifier | Mod_Unaligned , // VOLATILE = Action_Modifier | Mod_Volatile , // TAILCALL = Action_Modifier | Mod_TailCall , // CONSTRAINED = Action_Modifier | Mod_Constrained , // NO = Action_Modifier | Mod_NoCheck , // READONLY = Action_Modifier | Mod_Readonly , // private void ProcessInstruction_Modifier( Instruction instr ) { switch(instr.Operator.ActionModifier) { case Instruction.OpcodeActionModifier.Unaligned: m_mod_unaligned = this.CurrentArgumentAsInt32; break; case Instruction.OpcodeActionModifier.Volatile: m_mod_fVolatile = true; break; case Instruction.OpcodeActionModifier.TailCall: m_mod_fTailCall = true; break; case Instruction.OpcodeActionModifier.Constrained: m_mod_constrained = this.CurrentArgumentAsType; break; case Instruction.OpcodeActionModifier.NoCheck: m_mod_nocheck = this.CurrentArgumentAsInt32; break; case Instruction.OpcodeActionModifier.Readonly: m_mod_fReadonly = true; break; } } // // BREAK = Action_Debug | Debug_Breakpoint , // private void ProcessInstruction_Debug( Instruction instr ) { throw new NotImplementedException(); } } } ================================================ FILE: Zelig/Zelig/CompileTime/CodeGenerator/IntermediateRepresentation/Expressions/ArgumentVariableExpression.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // namespace Microsoft.Zelig.CodeGeneration.IR { using System; using System.Collections.Generic; using Microsoft.Zelig.Runtime.TypeSystem; public sealed class ArgumentVariableExpression : VariableExpression { // // Constructor Methods // public ArgumentVariableExpression( TypeRepresentation type , DebugInfo debugInfo , int number ) : base( type, debugInfo ) { m_number = number; } //--// // // Helper Methods // public override Expression Clone( CloningContext context ) { // // Arguments cannot be allocated after control flow graph creation. // return RegisterAndCloneState( context, context.ControlFlowGraphDestination.Arguments[ m_number ] ); } //--// public override int GetVariableKind() { return c_VariableKind_Argument; } // // Debug Methods // public override void InnerToString( System.Text.StringBuilder sb ) { sb.Append( "Arg" ); base.InnerToString( sb ); } } } ================================================ FILE: Zelig/Zelig/CompileTime/CodeGenerator/IntermediateRepresentation/Expressions/ConstantExpression.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // namespace Microsoft.Zelig.CodeGeneration.IR { using System; using System.Collections.Generic; using Microsoft.Zelig.Runtime.TypeSystem; public sealed class ConstantExpression : Expression { public abstract class DelayedValue { // // Access Methods // public abstract bool CanEvaluate { get; } public abstract object Value { get; } } //--// public static new readonly ConstantExpression[] SharedEmptyArray = new ConstantExpression[0]; // // State // private object m_value; // // Constructor Methods // public ConstantExpression( TypeRepresentation type , object value ) : base( type ) { m_value = value; // // Coming from byte code, we might see loads for long/ulong that take a 32 bit value as input. // if(this.IsValueInteger) { ulong val; this.GetAsRawUlong( out val ); m_value = ConvertToType( type, val ); } } //--// // // Helper Methods // public override Expression Clone( CloningContext context ) { TypeRepresentation td = context.ConvertType( m_type ); if(Object.ReferenceEquals( td, m_type )) { return this; // Constants don't need to be cloned. } else { return new ConstantExpression( td, m_value ); } } //--// public override void ApplyTransformation( TransformationContextForIR context ) { context.Push( this ); base.ApplyTransformation( context ); context.Transform( ref m_value ); context.Pop(); } //--// public override Operator.OperatorLevel GetLevel( Operator.IOperatorLevelHelper helper ) { if(m_type.ValidLayout == false) { return Operator.OperatorLevel.ConcreteTypes; } if(helper.FitsInPhysicalRegister( m_type )) { // // If they can fit in a register, we consider it good enough to be at the lowest level. // return Operator.OperatorLevel.Lowest; } return Operator.OperatorLevel.ConcreteTypes_NoExceptions; } //--// public bool GetAsRawUlong( out ulong value ) { return DataConversion.GetAsRawUlong( this.Value, out value ); } public bool GetAsUnsignedInteger( out ulong value ) { return DataConversion.GetAsUnsignedInteger( this.Value, out value ); } public bool GetAsSignedInteger( out long value ) { return DataConversion.GetAsSignedInteger( this.Value, out value ); } public bool GetFloatingPoint( out double value ) { return DataConversion.GetFloatingPoint( this.Value, out value ); } //--// public static object ConvertToType( TypeRepresentation type , ulong value ) { // // Special case for memory-mapped peripherals. // if(type is ReferenceTypeRepresentation) { return new UIntPtr( (uint)value ); } // // Special case for pointers. // if(type is PointerTypeRepresentation) { return new UIntPtr( (uint)value ); } if(type is EnumerationTypeRepresentation) { type = type.UnderlyingType; } if(type is ScalarTypeRepresentation) { switch(type.BuiltInType) { case TypeRepresentation.BuiltInTypes.BOOLEAN: return value != 0; case TypeRepresentation.BuiltInTypes.CHAR : return (char )value; case TypeRepresentation.BuiltInTypes.I1 : return (sbyte )value; case TypeRepresentation.BuiltInTypes.U1 : return (byte )value; case TypeRepresentation.BuiltInTypes.I2 : return (short )value; case TypeRepresentation.BuiltInTypes.U2 : return (ushort)value; case TypeRepresentation.BuiltInTypes.I4 : return (int )value; case TypeRepresentation.BuiltInTypes.U4 : return (uint )value; case TypeRepresentation.BuiltInTypes.I8 : return (long )value; case TypeRepresentation.BuiltInTypes.U8 : return (ulong )value; case TypeRepresentation.BuiltInTypes.I : return new IntPtr ( (int )value ); case TypeRepresentation.BuiltInTypes.U : return new UIntPtr ( (uint )value ); case TypeRepresentation.BuiltInTypes.R4 : return DataConversion.GetFloatFromBytes ( (uint )value ); case TypeRepresentation.BuiltInTypes.R8 : return DataConversion.GetDoubleFromBytes( value ); } } throw TypeConsistencyErrorException.Create( "Cannot convert {0} to {1}", value, type ); } //--// // // Access Methods // public object Value { get { DelayedValue delayedValue = m_value as DelayedValue; if(delayedValue != null && delayedValue.CanEvaluate) { return delayedValue.Value; } return m_value; } } public override CanBeNull CanBeNull { get { object val = this.Value; return (val == null) ? CanBeNull.Yes : CanBeNull.No; } } public override bool CanTakeAddress { get { return false; } } public int SizeOfValue { get { switch(this.TypeCode) { case TypeCode.Boolean: return 1; case TypeCode.Char : return 2; case TypeCode.SByte : return 1; case TypeCode.Byte : return 1; case TypeCode.Int16 : return 2; case TypeCode.UInt16 : return 2; case TypeCode.Int32 : return 4; case TypeCode.UInt32 : return 4; case TypeCode.Int64 : return 8; case TypeCode.UInt64 : return 8; case TypeCode.Single : return 4; case TypeCode.Double : return 8; //// case TypeCode.Decimal: } return 0; } } public bool IsValueSigned { get { switch(this.TypeCode) { case TypeCode.SByte : return true; case TypeCode.Int16 : return true; case TypeCode.Int32 : return true; case TypeCode.Int64 : return true; case TypeCode.Single : return true; case TypeCode.Double : return true; //// case TypeCode.Decimal: } return false; } } public bool IsValueInteger { get { switch(this.TypeCode) { case TypeCode.Boolean: case TypeCode.Char : case TypeCode.SByte : case TypeCode.Byte : case TypeCode.Int16 : case TypeCode.UInt16 : case TypeCode.Int32 : case TypeCode.UInt32 : case TypeCode.Int64 : case TypeCode.UInt64 : return true; } return false; } } public TypeCode TypeCode { get { return DataConversion.GetTypeCode( this.Value ); } } public bool IsValueFloatingPoint { get { object val = this.Value; if(val is float ) return true; if(val is double) return true; return false; } } //--// // // Debug Methods // public override void InnerToString( System.Text.StringBuilder sb ) { object val = this.Value; if(val != null) { sb.AppendFormat( "$Const({0} {1})", m_type.FullNameWithAbbreviation, val ); } else { sb.Append( "" ); } } } } ================================================ FILE: Zelig/Zelig/CompileTime/CodeGenerator/IntermediateRepresentation/Expressions/ExceptionObjectVariableExpression.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // namespace Microsoft.Zelig.CodeGeneration.IR { using System; using System.Collections.Generic; using Microsoft.Zelig.Runtime.TypeSystem; public sealed class ExceptionObjectVariableExpression : VariableExpression { public static new readonly ExceptionObjectVariableExpression[] SharedEmptyArray = new ExceptionObjectVariableExpression[0]; // // Constructor Methods // internal ExceptionObjectVariableExpression( TypeRepresentation type , DebugInfo debugInfo ) : base( type, debugInfo ) { } //--// // // Helper Methods // public override Expression Clone( CloningContext context ) { TypeRepresentation td = context.ConvertType( m_type ); return RegisterAndCloneState( context, context.ControlFlowGraphDestination.AllocateExceptionObjectVariable( td ) ); } //--// public override int GetVariableKind() { return c_VariableKind_Exception; } //--// // // Access Methods // public override CanBeNull CanBeNull { get { return CanBeNull.No; } } //--// // // Debug Methods // public override void InnerToString( System.Text.StringBuilder sb ) { sb.Append( "Exception" ); base.InnerToString( sb ); } } } ================================================ FILE: Zelig/Zelig/CompileTime/CodeGenerator/IntermediateRepresentation/Expressions/Expression.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // #if DEBUG #define TRACK_EXPRESSION_IDENTITY //#define TRACK_EXPRESSION_IDENTITY_DUMP #else //#define TRACK_EXPRESSION_IDENTITY //#define TRACK_EXPRESSION_IDENTITY_DUMP #endif namespace Microsoft.Zelig.CodeGeneration.IR { using System; using System.Collections.Generic; using Microsoft.Zelig.Runtime.TypeSystem; public enum CanBeNull { Unknown, No , Yes , } public abstract class Expression { public static readonly Expression[] SharedEmptyArray = new Expression[0]; // // State // #if TRACK_EXPRESSION_IDENTITY protected static int s_identity; #endif public int m_identity; //--// protected TypeRepresentation m_type; protected int m_index; // // Constructor Methods // protected Expression() // Default constructor required by TypeSystemSerializer. { #if TRACK_EXPRESSION_IDENTITY m_identity = s_identity++; #endif m_index = -1; } protected Expression( TypeRepresentation type ) : this() { m_type = type; } // // Equality Methods // public virtual bool IsTheSamePhysicalEntity( Expression ex ) { return Object.ReferenceEquals( this, ex ); } public virtual bool IsTheSameAggregate( Expression ex ) { return Object.ReferenceEquals( this, ex ); } //--// // // Helper Methods // public abstract Expression Clone( CloningContext context ); protected Expression RegisterAndCloneState( CloningContext context , Expression clone ) { context.Register( this, clone ); CloneState( context, clone ); return clone; } protected virtual void CloneState( CloningContext context , Expression clone ) { } //--// public virtual void ApplyTransformation( TransformationContextForIR context ) { context.Push( this ); context.Transform( ref m_type ); context.Pop(); } //--// public virtual Operator.OperatorLevel GetLevel( Operator.IOperatorLevelHelper helper ) { if(m_type.ValidLayout == false) { return Operator.OperatorLevel.ConcreteTypes; } return Operator.OperatorLevel.ConcreteTypes_NoExceptions; } //--// public bool IsEqualToZero() { var exConst = this as ConstantExpression; if(exConst != null) { if(exConst.Value == null) { return true; } ulong val; if(exConst.GetAsRawUlong( out val ) && val == 0) { return true; } } return false; } //--// // // Access Methods // public TypeRepresentation Type { [System.Diagnostics.DebuggerHidden] get { return m_type; } } public int SpanningTreeIndex { [System.Diagnostics.DebuggerHidden] get { return m_index; } set { m_index = value; } } //--// public StackEquivalentType StackEquivalentType { get { return m_type.StackEquivalentType; } } public abstract CanBeNull CanBeNull { get; } public abstract bool CanTakeAddress { get; } public bool CanPointToMemory { get { return m_type.CanPointToMemory; } } //--// // // Debug Methods // public override string ToString() { System.Text.StringBuilder sb = new System.Text.StringBuilder(); InnerToString( sb ); return sb.ToString(); } public abstract void InnerToString( System.Text.StringBuilder sb ); protected void AppendIdentity( System.Text.StringBuilder sb ) { #if TRACK_EXPRESSION_IDENTITY_DUMP sb.AppendFormat( "{{ID:{0}}}", m_identity ); #endif } } } ================================================ FILE: Zelig/Zelig/CompileTime/CodeGenerator/IntermediateRepresentation/Expressions/LocalVariableExpression.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // namespace Microsoft.Zelig.CodeGeneration.IR { using System; using System.Collections.Generic; using Microsoft.Zelig.Runtime.TypeSystem; public sealed class LocalVariableExpression : VariableExpression { public static new readonly LocalVariableExpression[] SharedEmptyArray = new LocalVariableExpression[0]; // // Constructor Methods // internal LocalVariableExpression( TypeRepresentation type , DebugInfo debugInfo ) : base( type, debugInfo ) { } //--// // // Helper Methods // public override Expression Clone( CloningContext context ) { TypeRepresentation td = context.ConvertType( m_type ); return RegisterAndCloneState( context, context.ControlFlowGraphDestination.AllocateLocal( td, m_debugInfo ) ); } //--// public override int GetVariableKind() { return c_VariableKind_Local; } //--// // // Debug Methods // public override void InnerToString( System.Text.StringBuilder sb ) { sb.Append( "Local" ); base.InnerToString( sb ); } } } ================================================ FILE: Zelig/Zelig/CompileTime/CodeGenerator/IntermediateRepresentation/Expressions/TemporaryVariableExpression.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // namespace Microsoft.Zelig.CodeGeneration.IR { using System; using System.Collections.Generic; using Microsoft.Zelig.Runtime.TypeSystem; public sealed class TemporaryVariableExpression : VariableExpression { public static new readonly TemporaryVariableExpression[] SharedEmptyArray = new TemporaryVariableExpression[0]; // // Constructor Methods // internal TemporaryVariableExpression( TypeRepresentation type , DebugInfo debugInfo ) : base( type, debugInfo ) { } //--// // // Helper Methods // public override Expression Clone( CloningContext context ) { TypeRepresentation td = context.ConvertType( m_type ); return RegisterAndCloneState( context, context.ControlFlowGraphDestination.AllocateTemporary( td, m_debugInfo ) ); } //--// public override int GetVariableKind() { return c_VariableKind_Temporary; } //--// // // Access Methods // public override CanBeNull CanBeNull { get { return CanBeNull.Unknown; } } //--// // // Debug Methods // public override void InnerToString( System.Text.StringBuilder sb ) { sb.Append( "Temp" ); base.InnerToString( sb ); } } } ================================================ FILE: Zelig/Zelig/CompileTime/CodeGenerator/IntermediateRepresentation/Expressions/VariableExpression.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // namespace Microsoft.Zelig.CodeGeneration.IR { using System; using System.Collections.Generic; using Microsoft.Zelig.Runtime.TypeSystem; public abstract class VariableExpression : Expression { [Flags] public enum Property { AddressTaken = 0x00000001, Volatile = 0x00000002, PhysicalRegister = 0x00000004, } public sealed class DebugInfo { // // State // private MethodRepresentation m_context; private string m_name; private int m_number; private bool m_isLocal; // // Constructor Methods // public DebugInfo( MethodRepresentation context , string name , int number , bool isLocal ) { m_context = context; m_name = name; m_number = number; m_isLocal = isLocal; } // // Helper Methods // public void ApplyTransformation( TransformationContextForIR context ) { context.Push( this ); context.Transform( ref m_context ); context.Transform( ref m_name ); context.Transform( ref m_number ); context.Transform( ref m_isLocal ); context.Pop(); } // // Access Methods // public MethodRepresentation Context { get { return m_context; } } public string Name { get { return m_name; } } public int Number { get { return m_number; } } public bool IsLocal { get { return m_isLocal; } } } //--// public static new readonly VariableExpression[] SharedEmptyArray = new VariableExpression[0]; protected const int c_VariableKind_Argument = 0; protected const int c_VariableKind_Local = 1; protected const int c_VariableKind_Exception = 2; protected const int c_VariableKind_Temporary = 3; // // State // protected DebugInfo m_debugInfo; protected int m_number; // // Constructor Methods // protected VariableExpression( TypeRepresentation type , DebugInfo debugInfo ) : base( type ) { m_debugInfo = debugInfo; m_number = -1; } //--// // // Helper Methods // public static Comparison< VariableExpression > GetSorter() { return SortVariables; } private static int SortVariables( VariableExpression x , VariableExpression y ) { int xKind = x.GetVariableKind(); int yKind = y.GetVariableKind(); if(xKind < yKind) return -1; if(xKind > yKind) return 1; return x.Number - y.Number; } public abstract int GetVariableKind(); //--// public override void ApplyTransformation( TransformationContextForIR context ) { context.Push( this ); base.ApplyTransformation( context ); context.Transform( ref m_number ); context.Transform( ref m_debugInfo ); context.Pop(); } //--// public static VariableExpression ExtractAliased( Expression ex ) { VariableExpression var = ex as VariableExpression; if(var != null) { return var.AliasedVariable; } return null; } public static VariableExpression[] ToArray( VariableExpression ex ) { return ex != null ? new VariableExpression[] { ex } : SharedEmptyArray; } // // Access Methods // public IInliningPathAnnotation InliningPath { get; set; } public DebugInfo DebugName { get { return m_debugInfo; } } public int Number { get { return m_number; } set { m_number = value; } } public override CanBeNull CanBeNull { get { return CanBeNull.Unknown; } } public override bool CanTakeAddress { get { return true; } } public virtual VariableExpression AliasedVariable { get { return this; } } public bool SkipReferenceCounting { get; set; } //--// // // Debug Methods // public override void InnerToString( System.Text.StringBuilder sb ) { string name; string fmt; if (m_number >= 0) { sb.Append( m_number ); } if(m_index >= 0) { sb.AppendFormat( "_{0}", m_index ); } AppendIdentity( sb ); if(m_debugInfo != null) { name = m_debugInfo.Name; } else { name = null; } if(name != null) { fmt = "({0} {1})"; } else { fmt = "({0})"; } sb.AppendFormat( fmt, m_type.FullNameWithAbbreviation, name ); } } } ================================================ FILE: Zelig/Zelig/CompileTime/CodeGenerator/IntermediateRepresentation/IIntermediateRepresentationDumper.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // namespace Microsoft.Zelig.CodeGeneration.IR { using System; using System.Collections.Generic; using Microsoft.Zelig.Runtime.TypeSystem; // // Debug classes // public interface IIntermediateRepresentationDumper { string FormatOutput( string s , object arg1 ); string FormatOutput( string s , object arg1 , object arg2 ); string FormatOutput( string s , object arg1 , object arg2 , object arg3 ); string FormatOutput( string s , params object[] args ); void DumpGraph( ControlFlowGraphState cfg ); string CreateName( Expression ex ); string CreateLabel( BasicBlock bb ); } } ================================================ FILE: Zelig/Zelig/CompileTime/CodeGenerator/IntermediateRepresentation/IntermediateRepresentation.csproj ================================================  Debug AnyCPU 9.0.21022 2.0 {186F31A3-EF89-4A25-B2D5-20060603AA01} Library Properties Microsoft.Zelig.CodeGeneration.IR Microsoft.Zelig.CodeGeneration.IntermediateRepresentation $(LlilumBuildRoot)\Host\obj\$(MSBuildProjectName)\ v4.5 true full false $(LlilumBuildRoot)\Host\bin\$(Configuration)\ DEBUG;TRACE prompt 4 true AllRules.ruleset AnyCPU false pdbonly true $(LlilumBuildRoot)\Host\bin\$(Configuration)\ TRACE prompt 4 true AllRules.ruleset AnyCPU false $(LlilumBuildRoot)\Host\bin\$(Configuration)\ true DEBUG;TRACE AnyCPU false {186F31A3-EF89-4A25-B2D5-20060510AA01} Normalized False {186F31A3-EF89-4A25-B2D5-20061218AA01} Common False {186F31A3-EF89-4A25-B2D5-20060720AA01} TypeSystem False 3.5 ================================================ FILE: Zelig/Zelig/CompileTime/CodeGenerator/IntermediateRepresentation/Operators/AbstractAssignmentOperator.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // namespace Microsoft.Zelig.CodeGeneration.IR { using System; using System.Collections.Generic; using Microsoft.Zelig.Runtime.TypeSystem; public abstract class AbstractAssignmentOperator : Operator { private const OperatorCapabilities cCapabilities = OperatorCapabilities.IsNonCommutative | OperatorCapabilities.DoesNotMutateExistingStorage | OperatorCapabilities.DoesNotAllocateStorage | OperatorCapabilities.DoesNotReadExistingMutableStorage | OperatorCapabilities.DoesNotThrow | OperatorCapabilities.DoesNotReadThroughPointerOperands | OperatorCapabilities.DoesNotWriteThroughPointerOperands | OperatorCapabilities.DoesNotCapturePointerOperands ; // // Constructor Methods // protected AbstractAssignmentOperator( Debugging.DebugInfo debugInfo ) : base( debugInfo, cCapabilities, OperatorLevel.Lowest ) { } //--// // // Helper Methods // //--// // // Access Methods // //--// // // Debug Methods // } } ================================================ FILE: Zelig/Zelig/CompileTime/CodeGenerator/IntermediateRepresentation/Operators/AbstractBinaryOperator.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // namespace Microsoft.Zelig.CodeGeneration.IR { using System; using System.Collections.Generic; using Microsoft.Zelig.Runtime.TypeSystem; public abstract class AbstractBinaryOperator : Operator { public enum ALU { ADD = 0, SUB = 1, MUL = 2, DIV = 3, REM = 4, AND = 5, OR = 6, XOR = 7, SHL = 8, SHR = 9, } // // State // protected ALU m_alu; protected bool m_fSigned; protected bool m_fOverflow; // // Constructor Methods // protected AbstractBinaryOperator( Debugging.DebugInfo debugInfo , OperatorCapabilities capabilities , OperatorLevel level , ALU alu , bool fSigned , bool fOverflow ) : base( debugInfo, capabilities, level ) { m_alu = alu; m_fSigned = fSigned; m_fOverflow = fOverflow; } //--// // // Helper Methods // public override void ApplyTransformation( TransformationContextForIR context ) { context.Push( this ); base.ApplyTransformation( context ); context.Transform( ref m_alu ); context.Transform( ref m_fSigned ); context.Transform( ref m_fOverflow ); context.Pop(); } //--// // // Access Methods // public ALU Alu { get { return m_alu; } } public bool Signed { get { return m_fSigned; } } public bool CheckOverflow { get { return m_fOverflow; } } //--// // // Debug Methods // public override void InnerToString( System.Text.StringBuilder sb ) { base.InnerToString( sb ); sb.AppendFormat( " ALU: {0}" , m_alu ); sb.AppendFormat( " Signed: {0}" , m_fSigned ); sb.AppendFormat( " Overflow: {0}", m_fOverflow ); } } } ================================================ FILE: Zelig/Zelig/CompileTime/CodeGenerator/IntermediateRepresentation/Operators/AbstractUnaryOperator.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // namespace Microsoft.Zelig.CodeGeneration.IR { using System; using System.Collections.Generic; using Microsoft.Zelig.Runtime.TypeSystem; public abstract class AbstractUnaryOperator : Operator { public enum ALU { NEG = 0, NOT = 1, FINITE = 2, } // // State // protected ALU m_alu; protected bool m_fSigned; protected bool m_fOverflow; // // Constructor Methods // protected AbstractUnaryOperator( Debugging.DebugInfo debugInfo , OperatorCapabilities capabilities , OperatorLevel level , ALU alu , bool fSigned , bool fOverflow ) : base( debugInfo, capabilities, level ) { m_alu = alu; m_fSigned = fSigned; m_fOverflow = fOverflow; } //--// // // Helper Methods // public override void ApplyTransformation( TransformationContextForIR context ) { context.Push( this ); base.ApplyTransformation( context ); context.Transform( ref m_alu ); context.Transform( ref m_fSigned ); context.Transform( ref m_fOverflow ); context.Pop(); } //--// // // Access Methods // public ALU Alu { get { return m_alu; } } public bool Signed { get { return m_fSigned; } } public bool CheckOverflow { get { return m_fOverflow; } } //--// // // Debug Methods // public override void InnerToString( System.Text.StringBuilder sb ) { base.InnerToString( sb ); sb.AppendFormat( " ALU: {0}" , m_alu ); sb.AppendFormat( " Signed: {0}" , m_fSigned ); sb.AppendFormat( " Overflow: {0}", m_fOverflow ); } } } ================================================ FILE: Zelig/Zelig/CompileTime/CodeGenerator/IntermediateRepresentation/Operators/BinaryOperator.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // namespace Microsoft.Zelig.CodeGeneration.IR { using System; using System.Collections.Generic; using Microsoft.Zelig.Runtime.TypeSystem; public sealed class BinaryOperator : AbstractBinaryOperator { // // Constructor Methods // private BinaryOperator( Debugging.DebugInfo debugInfo , OperatorCapabilities capabilities , OperatorLevel level , ALU alu , bool fSigned , bool fOverflow ) : base( debugInfo, capabilities, level, alu, fSigned, fOverflow ) { } //--// public static BinaryOperator New( Debugging.DebugInfo debugInfo , ALU alu , bool fSigned , bool fOverflow , VariableExpression lhs , Expression rhsLeft , Expression rhsRight ) { OperatorCapabilities capabilities = OperatorCapabilities.DoesNotMutateExistingStorage | OperatorCapabilities.DoesNotAllocateStorage | OperatorCapabilities.DoesNotReadExistingMutableStorage | OperatorCapabilities.DoesNotReadThroughPointerOperands | OperatorCapabilities.DoesNotWriteThroughPointerOperands | OperatorCapabilities.DoesNotCapturePointerOperands ; switch(alu) { case ALU.ADD: case ALU.MUL: case ALU.AND: case ALU.OR: case ALU.XOR: capabilities |= OperatorCapabilities.IsCommutative; break; default: capabilities |= OperatorCapabilities.IsNonCommutative; break; } if(fOverflow) capabilities |= OperatorCapabilities.MayThrow; else capabilities |= OperatorCapabilities.DoesNotThrow; OperatorLevel level = fOverflow ? OperatorLevel.ConcreteTypes : OperatorLevel.Lowest; var res = new BinaryOperator( debugInfo, capabilities, level, alu, fSigned, fOverflow ); res.SetLhs( lhs ); res.SetRhs( rhsLeft, rhsRight ); return res; } //--// // // Helper Methods // public override Operator Clone( CloningContext context ) { return RegisterAndCloneState( context, new BinaryOperator( m_debugInfo, m_capabilities, m_level, m_alu, m_fSigned, m_fOverflow ) ); } //--// public override ConstantExpression CanEvaluate( Operator[][] defChains , Operator[][] useChains , VariableExpression.Property[] properties ) { var exL = FindConstantOrigin( this.FirstArgument , defChains, useChains, properties ); var exR = FindConstantOrigin( this.SecondArgument, defChains, useChains, properties ); if(exL != null && exR != null) { // // BUGBUG: Overflow checking is ignored! // if(exL.IsValueInteger) { if(!exR.IsValueInteger) { throw TypeConsistencyErrorException.Create( "Cannot mix integer and floating-point values in the same operation: {0}", this ); } ulong valL; ulong valR; if(exL.GetAsRawUlong( out valL ) == false || exR.GetAsRawUlong( out valR ) == false ) { return null; } switch(m_alu) { case ALU.ADD: valL = valL + valR; break; case ALU.SUB: valL = valL - valR; break; case ALU.MUL: case ALU.DIV: case ALU.REM: { bool negate = false; if(exL.IsValueSigned) { long svalL = (long)valL; if(svalL < 0) { valL = (ulong)-svalL; negate = !negate; } } if(exR.IsValueSigned) { long svalR = (long)valR; if(svalR < 0) { valR = (ulong)-svalR; negate = !negate; } } switch(m_alu) { case ALU.MUL: valL = valL * valR; break; case ALU.DIV: if(valR == 0) { throw TypeConsistencyErrorException.Create( "Found division by zero: {0}", this ); } valL = valL / valR; break; case ALU.REM: if(valR == 0) { throw TypeConsistencyErrorException.Create( "Found remainder by zero: {0}", this ); } valL = valL % valR; break; } if(negate) { long svalL = (long)valL; valL = (ulong)-svalL; } } break; case ALU.AND: valL = valL & valR; break; case ALU.OR : valL = valL | valR; break; case ALU.XOR: valL = valL ^ valR; break; case ALU.SHL: valL <<= (int)valR; break; case ALU.SHR: if(exL.IsValueSigned) { long svalL = (long)valL; valL = (ulong)(svalL >> (int)valR); } else { valL = valL >> (int)valR; } break; default: return null; } return new ConstantExpression( this.FirstResult.Type, valL ); } if(exL.IsValueFloatingPoint) { if(!exR.IsValueFloatingPoint) { throw TypeConsistencyErrorException.Create( "Cannot mix integer and floating-point values in the same operation: {0}", this ); } object valL = exL.Value; object valR = exR.Value; if(valL is float) { if(!(valR is float)) { throw TypeConsistencyErrorException.Create( "Cannot mix single and double values in the same operation: {0}", this ); } float valL2 = (float)valL; float valR2 = (float)valR; switch(m_alu) { case ALU.ADD: valL2 = valL2 + valR2; break; case ALU.SUB: valL2 = valL2 - valR2; break; case ALU.MUL: valL2 = valL2 * valR2; break; case ALU.DIV: // Divide by zero for float/double is a valid option it should return NaN //if(valR2 == 0) //{ // throw TypeConsistencyErrorException.Create( "Found division by zero: {0}", this ); //} valL2 = valL2 / valR2; break; case ALU.REM: // Divide by zero for float/double is a valid option it should return NaN //if(valR2 == 0) //{ // throw TypeConsistencyErrorException.Create( "Found remainder by zero: {0}", this ); //} valL2 = valL2 % valR2; break; default: return null; } return new ConstantExpression( this.FirstResult.Type, valL2 ); } if(valL is double) { if(!(valR is double)) { throw TypeConsistencyErrorException.Create( "Cannot mix single and double values in the same operation: {0}", this ); } double valL2 = (double)valL; double valR2 = (double)valR; switch(m_alu) { case ALU.ADD: valL2 = valL2 + valR2; break; case ALU.SUB: valL2 = valL2 - valR2; break; case ALU.MUL: valL2 = valL2 * valR2; break; case ALU.DIV: // Divide by zero for float/double is a valid option it should return NaN //if(valR2 == 0) //{ // throw TypeConsistencyErrorException.Create( "Found division by zero: {0}", this ); //} valL2 = valL2 / valR2; break; case ALU.REM: // Divide by zero for float/double is a valid option it should return NaN //if(valR2 == 0) //{ // throw TypeConsistencyErrorException.Create( "Found remainder by zero: {0}", this ); //} valL2 = valL2 % valR2; break; default: return null; } return new ConstantExpression( this.FirstResult.Type, valL2 ); } } } return null; } public override bool Simplify( Operator[][] defChains , Operator[][] useChains , VariableExpression.Property[] properties ) { if(base.Simplify( defChains, useChains, properties )) { return true; } var rhs1 = this.FirstArgument; var rhs2 = this.SecondArgument; var exConst1 = FindConstantOrigin( rhs1, defChains, useChains, properties ); var exConst2 = FindConstantOrigin( rhs2, defChains, useChains, properties ); if(exConst2 != null) { if(Simplify( rhs1, exConst2 )) { return true; } } if(exConst1 != null && this.IsCommutative) { if(Simplify( rhs2, exConst1 )) { return true; } } return false; } private bool Simplify( Expression rhs , ConstantExpression exConst ) { if(exConst != null && exConst.IsValueInteger) { ulong valU; if(exConst.GetAsRawUlong( out valU )) { long val = (long)valU; TypeSystemForIR ts = m_basicBlock.Owner.TypeSystemForIR; var lhs = this.FirstResult; if(val == 0) { switch(this.Alu) { case ALU.ADD: case ALU.SUB: case ALU.OR: case ALU.XOR: case ALU.SHL: case ALU.SHR: { var opNew = SingleAssignmentOperator.New( this.DebugInfo, lhs, rhs ); this.SubstituteWithOperator( opNew, Operator.SubstitutionFlags.CopyAnnotations ); return true; } case ALU.MUL: case ALU.AND: { ConstantExpression exConst2 = ts.CreateConstant( ts.WellKnownTypes.System_Int32, 0 ); var opNew = SingleAssignmentOperator.New( this.DebugInfo, lhs, exConst2 ); this.SubstituteWithOperator( opNew, Operator.SubstitutionFlags.CopyAnnotations ); return true; } } } else if(val == 1) { switch(this.Alu) { case ALU.MUL: case ALU.DIV: { var opNew = SingleAssignmentOperator.New( this.DebugInfo, lhs, rhs ); this.SubstituteWithOperator( opNew, Operator.SubstitutionFlags.CopyAnnotations ); return true; } case ALU.REM: { ConstantExpression exConst2 = ts.CreateConstant( ts.WellKnownTypes.System_Int32, 0 ); var opNew = SingleAssignmentOperator.New( this.DebugInfo, lhs, exConst2 ); this.SubstituteWithOperator( opNew, Operator.SubstitutionFlags.CopyAnnotations ); return true; } } } // // Look for simple shifts between values of the same type. // var tdLhs = lhs.Type; var tdRhs = rhs.Type; bool fCheckSimpleShift; if(tdLhs == tdRhs) { fCheckSimpleShift = true; } else if(tdLhs.ValidLayout && tdRhs.ValidLayout && tdLhs.Size == tdRhs.Size) { fCheckSimpleShift = true; } else { fCheckSimpleShift = false; } if(fCheckSimpleShift) { if(val > 0 && val < uint.MaxValue) { uint val2 = (uint)val; int pos = BitVector.GetPositionOfFirstBitSet( val2 ); val2 &= ~(1u << pos); if(val2 == 0) { // // It's a power of two. // switch(this.Alu) { case ALU.MUL: { // // It's just a shift. // ConstantExpression exConst2 = ts.CreateConstant( ts.WellKnownTypes.System_Int32, pos ); BinaryOperator opNew = BinaryOperator.New( this.DebugInfo, ALU.SHL, this.Signed, this.CheckOverflow, lhs, rhs, exConst2 ); this.SubstituteWithOperator( opNew, Operator.SubstitutionFlags.CopyAnnotations ); return true; } case ALU.DIV: { // // It's just a shift. // ConstantExpression exConst2 = ts.CreateConstant( ts.WellKnownTypes.System_Int32, pos ); BinaryOperator opNew = BinaryOperator.New( this.DebugInfo, ALU.SHR, this.Signed, this.CheckOverflow, lhs, rhs, exConst2 ); this.SubstituteWithOperator( opNew, Operator.SubstitutionFlags.CopyAnnotations ); return true; } case ALU.REM: { // // It's just a mask. // ConstantExpression exConst2 = ts.CreateConstant( ts.WellKnownTypes.System_Int32, (1 << pos ) - 1 ); BinaryOperator opNew = BinaryOperator.New( this.DebugInfo, ALU.AND, this.Signed, this.CheckOverflow, lhs, rhs, exConst2 ); this.SubstituteWithOperator( opNew, Operator.SubstitutionFlags.CopyAnnotations ); return true; } } } } } } } return false; } //--// // // Access Methods // //--// // // Debug Methods // public override void InnerToString( System.Text.StringBuilder sb ) { sb.Append( "BinaryOperator(" ); base.InnerToString( sb ); sb.Append( ")" ); } public override string FormatOutput( IIntermediateRepresentationDumper dumper ) { return dumper.FormatOutput( "{0} = {1} {2} {3}{4}", this.FirstResult, this.FirstArgument, m_alu, this.SecondArgument, this.MayThrow ? " MayThrow" : "" ); } } } ================================================ FILE: Zelig/Zelig/CompileTime/CodeGenerator/IntermediateRepresentation/Operators/Call/AddActivationRecordEventOperator.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // namespace Microsoft.Zelig.CodeGeneration.IR { using System; using System.Collections.Generic; using Microsoft.Zelig.Runtime.TypeSystem; public class AddActivationRecordEventOperator : Operator { private const OperatorCapabilities cCapabilities = OperatorCapabilities.IsNonCommutative | OperatorCapabilities.DoesNotMutateExistingStorage | OperatorCapabilities.DoesNotAllocateStorage | OperatorCapabilities.DoesNotReadExistingMutableStorage | OperatorCapabilities.DoesNotThrow | OperatorCapabilities.DoesNotReadThroughPointerOperands | OperatorCapabilities.DoesNotWriteThroughPointerOperands | OperatorCapabilities.DoesNotCapturePointerOperands ; // // State // private Runtime.ActivationRecordEvents m_ev; // // Constructor Methods // private AddActivationRecordEventOperator( Debugging.DebugInfo debugInfo , Runtime.ActivationRecordEvents ev ) : base( debugInfo, cCapabilities, OperatorLevel.Lowest ) { m_ev = ev; } //--// public static AddActivationRecordEventOperator New( Debugging.DebugInfo debugInfo , Runtime.ActivationRecordEvents ev ) { var res = new AddActivationRecordEventOperator( debugInfo, ev ); return res; } //--// // // Helper Methods // public override Operator Clone( CloningContext context ) { return RegisterAndCloneState( context, new AddActivationRecordEventOperator( m_debugInfo, m_ev ) ); } //--// public override void ApplyTransformation( TransformationContextForIR context ) { context.Push( this ); base.ApplyTransformation( context ); context.Transform( ref m_ev ); context.Pop(); } //--// public override bool CanPropagateCopy( Expression exOld , Expression exNew ) { return false; } // // Access Methods // public override bool ShouldNotBeRemoved { [System.Diagnostics.DebuggerHidden] get { return true; } } public Runtime.ActivationRecordEvents ActivationRecordEvent { get { return m_ev; } } // // Debug Methods // public override void InnerToString( System.Text.StringBuilder sb ) { sb.AppendFormat( "AddActivationRecordEventOperator({0}", m_ev ); base.InnerToString( sb ); sb.Append( ")" ); } public override string FormatOutput( IIntermediateRepresentationDumper dumper ) { return dumper.FormatOutput( "", m_ev ); } } } ================================================ FILE: Zelig/Zelig/CompileTime/CodeGenerator/IntermediateRepresentation/Operators/Call/CallOperator.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // namespace Microsoft.Zelig.CodeGeneration.IR { using System; using System.Collections.Generic; using Microsoft.Zelig.Runtime.TypeSystem; public abstract class CallOperator : Operator { public enum CallKind { Direct = 0, Indirect = 1, Virtual = 2, Overridden = 3, OverriddenNoCheck = 4, } // // State // protected CallKind m_callType; protected MethodRepresentation m_md; // // Constructor Methods // protected CallOperator( Debugging.DebugInfo debugInfo , OperatorCapabilities capabilities , OperatorLevel level , CallKind callType , MethodRepresentation md ) : base( debugInfo, capabilities, level ) { m_callType = callType; m_md = md; } //--// // // Helper Methods // public override void ApplyTransformation( TransformationContextForIR context ) { context.Push( this ); base.ApplyTransformation( context ); context.Transform( ref m_callType ); context.Transform( ref m_md ); context.Pop(); } //--// internal static bool MatchSignature( MethodRepresentation md , Expression[] rhs , CallKind callType ) { int offset; int i; switch(callType) { case CallKind.OverriddenNoCheck: i = md.ThisPlusArguments.Length; // Skip all, they might not match. offset = 0; break; case CallKind.Overridden: i = 1; // Skip 'this' on overridden, it won't match. offset = 0; break; case CallKind.Indirect: i = 1; // Skip the 'this' pointer, which could be of any type. Required for delegate support. offset = 1; // Skip first rhs value, it's the method pointer. break; default: i = 0; offset = 0; break; } if(md.ThisPlusArguments.Length + offset != rhs.Length) { return false; } for(; i < md.ThisPlusArguments.Length; i++) { TypeRepresentation td = md.ThisPlusArguments[i]; Expression ex = rhs[i+offset]; if(!td.CanBeAssignedFrom( ex.Type, null )) { // Allow passing null object pointers as any type. REVIEW: This should be unnecessary, but there // still exist places in the system that fail to coerce null pointers to the correct type. This test // should be considered a short term patch while we sort out those few remaining cases. var constEx = ex as ConstantExpression; if( (constEx != null) && (constEx.Value == null) && !(td is ValueTypeRepresentation) ) { continue; } // Ignore scalar type incompatibilities. The eval stack extends scalars to 32 bits, and we'll // convert these to the correct type during a later phase anyway. if((td is ScalarTypeRepresentation) && (ex.Type is ScalarTypeRepresentation)) { continue; } return false; } } return true; } //--// // // Access Methods // public CallKind CallType { get { return m_callType; } } public MethodRepresentation TargetMethod { get { return m_md; } set { CHECKS.ASSERT( m_md.MatchSignature( value, null ) && value.MatchSignature( m_md, null ), "Cannot swap incompatible methods '{0}' and '{1}'", m_md, value ); m_md = value; } } //--// protected static bool HasPointerArguments( Expression[] rhs , int offset ) { for(; offset < rhs.Length; offset++) { Expression ex = rhs[offset]; if(ex.Type is PointerTypeRepresentation) { return true; } } return false; } //--// // // Debug Methods // public override void InnerToString( System.Text.StringBuilder sb ) { base.InnerToString( sb ); sb.AppendFormat( " {0}", m_callType ); sb.AppendFormat( " {0}", m_md ); } } } ================================================ FILE: Zelig/Zelig/CompileTime/CodeGenerator/IntermediateRepresentation/Operators/Call/ExternalCallOperator.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // namespace Microsoft.Zelig.CodeGeneration.IR { using System; using System.Collections.Generic; using Microsoft.Zelig.Runtime.TypeSystem; using System.IO; public sealed class ExternalCallOperator : Operator { public interface IExternalCallGlobalContext { void Initialize(); } public interface IExternalCallContext { Debugging.DebugInfo DebugInfo { get; } void UpdateRelocation ( object relocation ); bool PerformCodeLinkage( object region, object section, object core ); Operator Owner { get; set; } uint OperatorOffset { get; } } private IExternalCallContext m_context; private static List s_nativeImportDirs = new List(); private static List s_nativeImportFiles = new List(); private const OperatorCapabilities cCapabilities = OperatorCapabilities.IsNonCommutative | OperatorCapabilities.MayMutateExistingStorage | OperatorCapabilities.MayAllocateStorage | OperatorCapabilities.MayReadExistingMutableStorage | OperatorCapabilities.MayThrow | OperatorCapabilities.DoesNotReadThroughPointerOperands | OperatorCapabilities.DoesNotWriteThroughPointerOperands | OperatorCapabilities.DoesNotCapturePointerOperands ; // // Constructor Methods // private ExternalCallOperator( IExternalCallContext ctx ) : base( ctx.DebugInfo, cCapabilities, OperatorLevel.Lowest ) { m_context = ctx; } //--// public static ExternalCallOperator New( IExternalCallContext ctx ) { return new ExternalCallOperator( ctx ); } public override bool ShouldNotBeRemoved { get { return true; } } //--// // // Helper Methods // public override Operator Clone( CloningContext context ) { return RegisterAndCloneState( context, new ExternalCallOperator( m_context ) ); } public bool Encode( object region, object section, object core ) { return m_context.PerformCodeLinkage( region, section, core ); } public static List NativeImportDirectories { get { return s_nativeImportDirs ; } set { s_nativeImportDirs = value; } } public static List NativeImportLibraries { get { return s_nativeImportFiles ; } set { s_nativeImportFiles = value; } } //--// // // Access Methods // public override bool PerformsNoActions { get { return false; } } public IExternalCallContext Context { get { return m_context; } } //--// // // Debug Methods // public override void InnerToString( System.Text.StringBuilder sb ) { sb.Append( "IExternalCallOperator(" ); base.InnerToString( sb ); sb.Append( ")" ); } public override string FormatOutput( IIntermediateRepresentationDumper dumper ) { return dumper.FormatOutput( "ExternalCall" ); } } } ================================================ FILE: Zelig/Zelig/CompileTime/CodeGenerator/IntermediateRepresentation/Operators/Call/IndirectCallOperator.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // namespace Microsoft.Zelig.CodeGeneration.IR { using System; using System.Collections.Generic; using Microsoft.Zelig.Runtime.TypeSystem; public sealed class IndirectCallOperator : CallOperator { // // Constructor Methods // private IndirectCallOperator( Debugging.DebugInfo debugInfo , OperatorCapabilities capabilities , OperatorLevel level , MethodRepresentation md , bool isInstance ) : base( debugInfo, capabilities, level, CallKind.Indirect, md ) { IsInstanceCall = isInstance; } //--// public static IndirectCallOperator New( Debugging.DebugInfo debugInfo , MethodRepresentation md , Expression[] rhs , bool isInstance , bool fNullCheck ) { CHECKS.ASSERT( md.ReturnType.BuiltInType == TypeRepresentation.BuiltInTypes.VOID, "Method '{0}' does not return a value, it cannot be assigned to an Lvalue", md ); IndirectCallOperator res = Alloc( debugInfo, md, rhs, isInstance, fNullCheck ); res.SetRhsArray( rhs ); return res; } public static IndirectCallOperator New( Debugging.DebugInfo debugInfo , MethodRepresentation md , VariableExpression[] lhs , Expression[] rhs , bool isInstance , bool fNullCheck ) { CHECKS.ASSERT( md.ReturnType.BuiltInType == TypeRepresentation.BuiltInTypes.VOID || lhs.Length != 0, "Method '{0}' does not return a value, it cannot be assigned to an Lvalue", md ); CHECKS.ASSERT( md.ReturnType.BuiltInType != TypeRepresentation.BuiltInTypes.VOID || lhs.Length == 0, "Method '{0}' returns a value, it must be assigned to an Lvalue" , md ); IndirectCallOperator res = Alloc( debugInfo, md, rhs, isInstance, fNullCheck ); res.SetLhsArray( lhs ); res.SetRhsArray( rhs ); return res; } private static IndirectCallOperator Alloc( Debugging.DebugInfo debugInfo , MethodRepresentation md , Expression[] rhs , bool isInstance , bool fNullCheck ) { CHECKS.ASSERT( CallOperator.MatchSignature( md, rhs, CallKind.Indirect ), "Incompatible arguments for call to '{0}'", md ); const OperatorCapabilities cCapabilitiesMay = OperatorCapabilities.IsNonCommutative | OperatorCapabilities.MayMutateExistingStorage | OperatorCapabilities.MayAllocateStorage | OperatorCapabilities.MayReadExistingMutableStorage | OperatorCapabilities.MayThrow | OperatorCapabilities.MayReadThroughPointerOperands | OperatorCapabilities.MayWriteThroughPointerOperands | OperatorCapabilities.MayCapturePointerOperands ; const OperatorCapabilities cCapabilitiesDoesnt = OperatorCapabilities.IsNonCommutative | OperatorCapabilities.MayMutateExistingStorage | OperatorCapabilities.MayAllocateStorage | OperatorCapabilities.MayReadExistingMutableStorage | OperatorCapabilities.MayThrow | OperatorCapabilities.DoesNotReadThroughPointerOperands | OperatorCapabilities.DoesNotWriteThroughPointerOperands | OperatorCapabilities.DoesNotCapturePointerOperands ; OperatorCapabilities capabilities = HasPointerArguments( rhs, 1 ) ? cCapabilitiesMay : cCapabilitiesDoesnt; OperatorLevel level; if(fNullCheck) { level = OperatorLevel.ConcreteTypes; } else { level = OperatorLevel.ConcreteTypes_NoExceptions; } return new IndirectCallOperator(debugInfo, capabilities, level, md, isInstance); } //--// // // Helper Methods // public override Operator Clone( CloningContext context ) { MethodRepresentation md = context.ConvertMethod( m_md ); var op = new IndirectCallOperator(m_debugInfo, m_capabilities, m_level, md, IsInstanceCall); return RegisterAndCloneState(context, op); } //--// // // Access Methods // public bool IsInstanceCall { get; } //--// // // Debug Methods // public override void InnerToString( System.Text.StringBuilder sb ) { sb.Append( "IndirectCallOperator(" ); base.InnerToString( sb ); sb.Append( ")" ); } public override string FormatOutput( IIntermediateRepresentationDumper dumper ) { System.Text.StringBuilder sb = new System.Text.StringBuilder(); if(this.Arguments.Length > 2) { sb.Append( " " ); for(int i = 2; i < this.Arguments.Length; i++) { if(i != 2) sb.Append( ", " ); this.Arguments[i].InnerToString( sb ); } sb.Append( " " ); } if(this.Results.Length == 0) { return dumper.FormatOutput( "callIndirect[{0}] {1}.{2}({3})", this.FirstArgument, this.SecondArgument, this.TargetMethod, sb.ToString() ); } else { return dumper.FormatOutput( "{4} = callIndirect[{0}] {1}.{2}({3})", this.FirstArgument, this.SecondArgument, this.TargetMethod, sb.ToString(), this.FirstResult ); } } } } ================================================ FILE: Zelig/Zelig/CompileTime/CodeGenerator/IntermediateRepresentation/Operators/Call/InstanceCallOperator.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // namespace Microsoft.Zelig.CodeGeneration.IR { using System; using System.Collections.Generic; using Microsoft.Zelig.Runtime.TypeSystem; public sealed class InstanceCallOperator : CallOperator { // // Constructor Methods // private InstanceCallOperator( Debugging.DebugInfo debugInfo , OperatorCapabilities capabilities , OperatorLevel level , CallKind callType , MethodRepresentation md ) : base( debugInfo, capabilities, level, callType, md ) { } //--// public static InstanceCallOperator New( Debugging.DebugInfo debugInfo , CallKind callType , MethodRepresentation md , Expression[] rhs , bool fNullCheck ) { if(callType == CallKind.Virtual && !(md is VirtualMethodRepresentation)) { callType = CallKind.Direct; } CHECKS.ASSERT( md.ReturnType.BuiltInType == TypeRepresentation.BuiltInTypes.VOID, "Method '{0}' does not return a value, it cannot be assigned to an Lvalue", md ); InstanceCallOperator res = Alloc( debugInfo, callType, md, rhs, fNullCheck ); res.SetRhsArray( rhs ); return res; } public static InstanceCallOperator New( Debugging.DebugInfo debugInfo , CallKind callType , MethodRepresentation md , VariableExpression[] lhs , Expression[] rhs , bool fNullCheck ) { if(callType == CallKind.Virtual && !(md is VirtualMethodRepresentation)) { callType = CallKind.Direct; } CHECKS.ASSERT( md.ReturnType.BuiltInType == TypeRepresentation.BuiltInTypes.VOID || lhs.Length != 0, "Method '{0}' does not return a value, it cannot be assigned to an Lvalue", md ); CHECKS.ASSERT( md.ReturnType.BuiltInType != TypeRepresentation.BuiltInTypes.VOID || lhs.Length == 0, "Method '{0}' returns a value, it must be assigned to an Lvalue" , md ); InstanceCallOperator res = Alloc( debugInfo, callType, md, rhs, fNullCheck ); res.SetLhsArray( lhs ); res.SetRhsArray( rhs ); return res; } private static InstanceCallOperator Alloc( Debugging.DebugInfo debugInfo , CallKind callType , MethodRepresentation md , Expression[] rhs , bool fNullCheck ) { CHECKS.ASSERT( CallOperator.MatchSignature( md, rhs, callType ), "Incompatible arguments for call to '{0}'", md ); const OperatorCapabilities cCapabilitiesMay = OperatorCapabilities.IsNonCommutative | OperatorCapabilities.MayMutateExistingStorage | OperatorCapabilities.MayAllocateStorage | OperatorCapabilities.MayReadExistingMutableStorage | OperatorCapabilities.MayThrow | OperatorCapabilities.MayReadThroughPointerOperands | OperatorCapabilities.MayWriteThroughPointerOperands | OperatorCapabilities.MayCapturePointerOperands ; const OperatorCapabilities cCapabilitiesDoesnt = OperatorCapabilities.IsNonCommutative | OperatorCapabilities.MayMutateExistingStorage | OperatorCapabilities.MayAllocateStorage | OperatorCapabilities.MayReadExistingMutableStorage | OperatorCapabilities.MayThrow | OperatorCapabilities.DoesNotReadThroughPointerOperands | OperatorCapabilities.DoesNotWriteThroughPointerOperands | OperatorCapabilities.DoesNotCapturePointerOperands ; OperatorCapabilities capabilities = HasPointerArguments( rhs, 0 ) ? cCapabilitiesMay : cCapabilitiesDoesnt; OperatorLevel level; if(callType == CallKind.Virtual) { level = OperatorLevel.ObjectOriented; } else if(fNullCheck) { level = OperatorLevel.ConcreteTypes; } else { level = OperatorLevel.ConcreteTypes_NoExceptions; } return new InstanceCallOperator( debugInfo, capabilities, level, callType, md ); } //--// // // Helper Methods // public override Operator Clone( CloningContext context ) { MethodRepresentation md = context.ConvertMethod( m_md ); return RegisterAndCloneState( context, new InstanceCallOperator( m_debugInfo, m_capabilities, m_level, m_callType, md ) ); } //--// // // Access Methods // //--// // // Debug Methods // public override void InnerToString( System.Text.StringBuilder sb ) { sb.Append( "InstanceCallOperator(" ); base.InnerToString( sb ); sb.Append( ")" ); } public override string FormatOutput( IIntermediateRepresentationDumper dumper ) { System.Text.StringBuilder sb = new System.Text.StringBuilder(); if(this.Arguments.Length > 1) { sb.Append( " " ); for(int i = 1; i < this.Arguments.Length; i++) { if(i != 1) sb.Append( ", " ); this.Arguments[i].InnerToString( sb ); } sb.Append( " " ); } string call; switch(this.CallType) { default : call = "call" ; break; case CallKind.Indirect : call = "callIndirect" ; break; case CallKind.Virtual : call = "callVirtual" ; break; case CallKind.Overridden : call = "callOverridden" ; break; case CallKind.OverriddenNoCheck: call = "callOverriddenNoCheck"; break; } if(this.Results.Length == 0) { return dumper.FormatOutput( "{0} {1}.{2}({3})", call, this.FirstArgument, this.TargetMethod, sb.ToString() ); } else { return dumper.FormatOutput( "{4} = {0} {1}.{2}({3})", call, this.FirstArgument, this.TargetMethod, sb.ToString(), this.FirstResult ); } } } } ================================================ FILE: Zelig/Zelig/CompileTime/CodeGenerator/IntermediateRepresentation/Operators/Call/StaticCallOperator.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // namespace Microsoft.Zelig.CodeGeneration.IR { using System; using System.Collections.Generic; using Microsoft.Zelig.Runtime.TypeSystem; public sealed class StaticCallOperator : CallOperator { // // Constructor Methods // private StaticCallOperator( Debugging.DebugInfo debugInfo , OperatorCapabilities capabilities , CallOperator.CallKind callType , MethodRepresentation md ) : base( debugInfo, capabilities, OperatorLevel.ConcreteTypes_NoExceptions, callType, md ) { } //--// public static StaticCallOperator New( Debugging.DebugInfo debugInfo , CallKind callType , MethodRepresentation md , Expression[] rhs ) { CHECKS.ASSERT( callType != CallKind.Virtual , "Method '{0}' cannot be called as virtual" , md ); CHECKS.ASSERT( md.ReturnType.BuiltInType == TypeRepresentation.BuiltInTypes.VOID, "Method '{0}' does not return a value, it cannot be assigned to an Lvalue", md ); StaticCallOperator res = Alloc( debugInfo, callType, md, rhs ); res.SetRhsArray( rhs ); return res; } public static StaticCallOperator New( Debugging.DebugInfo debugInfo , CallKind callType , MethodRepresentation md , VariableExpression[] lhs , Expression[] rhs ) { CHECKS.ASSERT( callType != CallKind.Virtual , "Method '{0}' cannot be called as virtual" , md ); CHECKS.ASSERT( md.ReturnType.BuiltInType == TypeRepresentation.BuiltInTypes.VOID || lhs.Length != 0, "Method '{0}' does not return a value, it cannot be assigned to an Lvalue", md ); CHECKS.ASSERT( md.ReturnType.BuiltInType != TypeRepresentation.BuiltInTypes.VOID || lhs.Length == 0, "Method '{0}' returns a value, it must be assigned to an Lvalue" , md ); StaticCallOperator res = Alloc( debugInfo, callType, md, rhs ); res.SetLhsArray( lhs ); res.SetRhsArray( rhs ); return res; } private static StaticCallOperator Alloc( Debugging.DebugInfo debugInfo , CallKind callType , MethodRepresentation md , Expression[] rhs ) { CHECKS.ASSERT( CallOperator.MatchSignature( md, rhs, callType ), "Incompatible arguments for call to '{0}'", md ); const OperatorCapabilities cCapabilitiesMay = OperatorCapabilities.IsNonCommutative | OperatorCapabilities.MayMutateExistingStorage | OperatorCapabilities.MayAllocateStorage | OperatorCapabilities.MayReadExistingMutableStorage | OperatorCapabilities.MayThrow | OperatorCapabilities.MayReadThroughPointerOperands | OperatorCapabilities.MayWriteThroughPointerOperands | OperatorCapabilities.MayCapturePointerOperands ; const OperatorCapabilities cCapabilitiesDoesnt = OperatorCapabilities.IsNonCommutative | OperatorCapabilities.MayMutateExistingStorage | OperatorCapabilities.MayAllocateStorage | OperatorCapabilities.MayReadExistingMutableStorage | OperatorCapabilities.MayThrow | OperatorCapabilities.DoesNotReadThroughPointerOperands | OperatorCapabilities.DoesNotWriteThroughPointerOperands | OperatorCapabilities.DoesNotCapturePointerOperands ; OperatorCapabilities capabilities = HasPointerArguments( rhs, 0 ) ? cCapabilitiesMay : cCapabilitiesDoesnt; return new StaticCallOperator( debugInfo, capabilities, callType, md ); } //--// // // Helper Methods // public override Operator Clone( CloningContext context ) { MethodRepresentation md = context.ConvertMethod( m_md ); return RegisterAndCloneState( context, new StaticCallOperator( m_debugInfo, m_capabilities, m_callType, md ) ); } //--// // // Access Methods // //--// // // Debug Methods // public override void InnerToString( System.Text.StringBuilder sb ) { sb.Append( "StaticCallOperator(" ); base.InnerToString( sb ); sb.Append( ")" ); } public override string FormatOutput( IIntermediateRepresentationDumper dumper ) { System.Text.StringBuilder sb = new System.Text.StringBuilder(); if(this.Arguments.Length > 0) { sb.Append( " " ); for(int i = 0; i < this.Arguments.Length; i++) { if(i != 0) sb.Append( ", " ); this.Arguments[i].InnerToString( sb ); } sb.Append( " " ); } if(this.Results.Length == 0) { return dumper.FormatOutput( "callStatic {0}({1})", this.TargetMethod, sb.ToString() ); } else { return dumper.FormatOutput( "{2} = callStatic {0}({1})", this.TargetMethod, sb.ToString(), this.FirstResult ); } } } } ================================================ FILE: Zelig/Zelig/CompileTime/CodeGenerator/IntermediateRepresentation/Operators/Checks/NullCheckOperator.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // namespace Microsoft.Zelig.CodeGeneration.IR { using System; using System.Collections.Generic; using Microsoft.Zelig.Runtime.TypeSystem; public sealed class NullCheckOperator : Operator { private const OperatorCapabilities cCapabilities = OperatorCapabilities.IsNonCommutative | OperatorCapabilities.DoesNotMutateExistingStorage | OperatorCapabilities.DoesNotAllocateStorage | OperatorCapabilities.DoesNotReadExistingMutableStorage | OperatorCapabilities.MayThrow | // Null pointer check can throw. OperatorCapabilities.DoesNotReadThroughPointerOperands | OperatorCapabilities.DoesNotWriteThroughPointerOperands | OperatorCapabilities.DoesNotCapturePointerOperands ; // // Constructor Methods // private NullCheckOperator( Debugging.DebugInfo debugInfo ) : base( debugInfo, cCapabilities, OperatorLevel.ConcreteTypes ) { } //--// public static NullCheckOperator New( Debugging.DebugInfo debugInfo , Expression rhs ) { NullCheckOperator res = new NullCheckOperator( debugInfo ); res.SetRhs( rhs ); return res; } //--// // // Helper Methods // public override Operator Clone( CloningContext context ) { return RegisterAndCloneState( context, new NullCheckOperator( m_debugInfo ) ); } //--// // // Access Methods // //--// // // Debug Methods // public override void InnerToString( System.Text.StringBuilder sb ) { sb.Append( "NullCheckOperator(" ); base.InnerToString( sb ); sb.Append( ")" ); } public override string FormatOutput( IIntermediateRepresentationDumper dumper ) { return dumper.FormatOutput( "nullcheck {0}", this.FirstArgument ); } } } ================================================ FILE: Zelig/Zelig/CompileTime/CodeGenerator/IntermediateRepresentation/Operators/Checks/OutOfBoundCheckOperator.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // namespace Microsoft.Zelig.CodeGeneration.IR { using System; using System.Collections.Generic; using Microsoft.Zelig.Runtime.TypeSystem; public sealed class OutOfBoundCheckOperator : Operator { private const OperatorCapabilities cCapabilities = OperatorCapabilities.IsNonCommutative | OperatorCapabilities.DoesNotMutateExistingStorage | OperatorCapabilities.DoesNotAllocateStorage | OperatorCapabilities.DoesNotReadExistingMutableStorage | OperatorCapabilities.MayThrow | // Out of bound check can throw. OperatorCapabilities.DoesNotReadThroughPointerOperands | OperatorCapabilities.DoesNotWriteThroughPointerOperands | OperatorCapabilities.DoesNotCapturePointerOperands ; // // Constructor Methods // private OutOfBoundCheckOperator( Debugging.DebugInfo debugInfo ) : base( debugInfo, cCapabilities, OperatorLevel.ConcreteTypes ) { } //--// public static OutOfBoundCheckOperator New( Debugging.DebugInfo debugInfo , Expression rhsAddr , Expression rhsIndex ) { OutOfBoundCheckOperator res = new OutOfBoundCheckOperator( debugInfo ); res.SetRhs( rhsAddr, rhsIndex ); return res; } //--// // // Helper Methods // public override Operator Clone( CloningContext context ) { return RegisterAndCloneState( context, new OutOfBoundCheckOperator( m_debugInfo ) ); } //--// // // Access Methods // //--// // // Debug Methods // public override void InnerToString( System.Text.StringBuilder sb ) { sb.Append( "OutOfBoundCheckOperator(" ); base.InnerToString( sb ); sb.Append( ")" ); } public override string FormatOutput( IIntermediateRepresentationDumper dumper ) { return dumper.FormatOutput( "boundcheck {0} {1}", this.FirstArgument, this.SecondArgument ); } } } ================================================ FILE: Zelig/Zelig/CompileTime/CodeGenerator/IntermediateRepresentation/Operators/Checks/OverflowCheckOperator.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // namespace Microsoft.Zelig.CodeGeneration.IR { using System; using System.Collections.Generic; using Microsoft.Zelig.Runtime.TypeSystem; public sealed class OverflowCheckOperator : Operator { private const OperatorCapabilities cCapabilities = OperatorCapabilities.IsNonCommutative | OperatorCapabilities.DoesNotMutateExistingStorage | OperatorCapabilities.DoesNotAllocateStorage | OperatorCapabilities.DoesNotReadExistingMutableStorage | OperatorCapabilities.MayThrow | // Null pointer check can throw. OperatorCapabilities.DoesNotReadThroughPointerOperands | OperatorCapabilities.DoesNotWriteThroughPointerOperands | OperatorCapabilities.DoesNotCapturePointerOperands ; // // Constructor Methods // private OverflowCheckOperator( Debugging.DebugInfo debugInfo ) : base( debugInfo, cCapabilities, OperatorLevel.ConcreteTypes ) { } //--// public static OverflowCheckOperator New( Debugging.DebugInfo debugInfo , Expression rhs ) { OverflowCheckOperator res = new OverflowCheckOperator( debugInfo ); res.SetRhs( rhs ); return res; } //--// // // Helper Methods // public override Operator Clone( CloningContext context ) { return RegisterAndCloneState( context, new OverflowCheckOperator( m_debugInfo ) ); } //--// // // Access Methods // //--// // // Debug Methods // public override void InnerToString( System.Text.StringBuilder sb ) { sb.Append( "OverflowCheckOperator(" ); base.InnerToString( sb ); sb.Append( ")" ); } public override string FormatOutput( IIntermediateRepresentationDumper dumper ) { return dumper.FormatOutput( "overflowcheck {0}", this.FirstArgument ); } } } ================================================ FILE: Zelig/Zelig/CompileTime/CodeGenerator/IntermediateRepresentation/Operators/CompareAndSetOperator.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // namespace Microsoft.Zelig.CodeGeneration.IR { using System; using System.Collections.Generic; using Microsoft.Zelig.Runtime.TypeSystem; public sealed class CompareAndSetOperator : Operator { public enum ActionCondition { EQ = 0, GE = 1, GT = 2, LE = 3, LT = 4, NE = 5, } // // State // private ActionCondition m_condition; private bool m_fSigned; // // Constructor Methods // private CompareAndSetOperator( Debugging.DebugInfo debugInfo , OperatorCapabilities capabilities , ActionCondition condition , bool fSigned ) : base( debugInfo, capabilities, OperatorLevel.ConcreteTypes_NoExceptions ) { m_condition = condition; m_fSigned = fSigned; } //--// public static CompareAndSetOperator New( Debugging.DebugInfo debugInfo , ActionCondition condition , bool fSigned , VariableExpression lhs , Expression rhsLeft , Expression rhsRight ) { OperatorCapabilities capabilities = OperatorCapabilities.DoesNotMutateExistingStorage | OperatorCapabilities.DoesNotAllocateStorage | OperatorCapabilities.DoesNotReadExistingMutableStorage | OperatorCapabilities.DoesNotThrow | OperatorCapabilities.DoesNotReadThroughPointerOperands | OperatorCapabilities.DoesNotWriteThroughPointerOperands | OperatorCapabilities.DoesNotCapturePointerOperands ; switch(condition) { case ActionCondition.EQ: case ActionCondition.NE: capabilities |= OperatorCapabilities.IsCommutative; break; default: capabilities |= OperatorCapabilities.IsNonCommutative; break; } CompareAndSetOperator res = new CompareAndSetOperator( debugInfo, capabilities, condition, fSigned ); res.SetLhs( lhs ); res.SetRhs( rhsLeft, rhsRight ); return res; } //--// // // Helper Methods // public override Operator Clone( CloningContext context ) { return RegisterAndCloneState( context, new CompareAndSetOperator( m_debugInfo, m_capabilities, m_condition, m_fSigned ) ); } //--// public override void ApplyTransformation( TransformationContextForIR context ) { context.Push( this ); base.ApplyTransformation( context ); context.Transform( ref m_condition ); context.Transform( ref m_fSigned ); context.Pop(); } //--// public override ConstantExpression CanEvaluate( Operator[][] defChains , Operator[][] useChains , VariableExpression.Property[] properties ) { var exL = FindConstantOrigin( this.FirstArgument , defChains, useChains, properties ); var exR = FindConstantOrigin( this.SecondArgument, defChains, useChains, properties ); if(exL != null && exR != null) { if(exL.IsValueInteger) { if(!exR.IsValueInteger) { throw TypeConsistencyErrorException.Create( "Cannot mix integer and floating-point values in the same operation: {0}", this ); } bool res; if(this.Signed) { long valL; long valR; if(exL.GetAsSignedInteger( out valL ) == false || exR.GetAsSignedInteger( out valR ) == false ) { return null; } switch(m_condition) { case ActionCondition.EQ: res = (valL == valR); break; case ActionCondition.GE: res = (valL >= valR); break; case ActionCondition.GT: res = (valL > valR); break; case ActionCondition.LE: res = (valL <= valR); break; case ActionCondition.LT: res = (valL < valR); break; case ActionCondition.NE: res = (valL != valR); break; default: return null; } } else { ulong valL; ulong valR; if(exL.GetAsUnsignedInteger( out valL ) == false || exR.GetAsUnsignedInteger( out valR ) == false ) { return null; } switch(m_condition) { case ActionCondition.EQ: res = (valL == valR); break; case ActionCondition.GE: res = (valL >= valR); break; case ActionCondition.GT: res = (valL > valR); break; case ActionCondition.LE: res = (valL <= valR); break; case ActionCondition.LT: res = (valL < valR); break; case ActionCondition.NE: res = (valL != valR); break; default: return null; } } return new ConstantExpression( this.FirstResult.Type, res ); } if(exL.IsValueFloatingPoint) { if(!exR.IsValueFloatingPoint) { throw TypeConsistencyErrorException.Create( "Cannot mix integer and floating-point values in the same operation: {0}", this ); } object valL = exL.Value; object valR = exR.Value; if(valL is float) { if(!(valR is float)) { throw TypeConsistencyErrorException.Create( "Cannot mix single and double values in the same operation: {0}", this ); } float valL2 = (float)valL; float valR2 = (float)valR; bool res; switch(m_condition) { case ActionCondition.EQ: res = (valL2 == valR2); break; case ActionCondition.GE: res = (valL2 >= valR2); break; case ActionCondition.GT: res = (valL2 > valR2); break; case ActionCondition.LE: res = (valL2 <= valR2); break; case ActionCondition.LT: res = (valL2 < valR2); break; case ActionCondition.NE: res = (valL2 != valR2); break; default: return null; } return new ConstantExpression( this.FirstResult.Type, res ); } if(valL is double) { if(!(valR is double)) { throw TypeConsistencyErrorException.Create( "Cannot mix single and double values in the same operation: {0}", this ); } double valL2 = (double)valL; double valR2 = (double)valR; bool res; switch(m_condition) { case ActionCondition.EQ: res = (valL2 == valR2); break; case ActionCondition.GE: res = (valL2 >= valR2); break; case ActionCondition.GT: res = (valL2 > valR2); break; case ActionCondition.LE: res = (valL2 <= valR2); break; case ActionCondition.LT: res = (valL2 < valR2); break; case ActionCondition.NE: res = (valL2 != valR2); break; default: return null; } return new ConstantExpression( this.FirstResult.Type, res ); } } } return null; } //--// // // Access Methods // public ActionCondition Condition { get { return m_condition; } } public ActionCondition InvertedCondition { get { switch(m_condition) { case ActionCondition.EQ: return ActionCondition.NE; case ActionCondition.GE: return ActionCondition.LT; case ActionCondition.GT: return ActionCondition.LE; case ActionCondition.LE: return ActionCondition.GT; case ActionCondition.LT: return ActionCondition.GE; case ActionCondition.NE: return ActionCondition.EQ; } throw TypeConsistencyErrorException.Create( "Unexpected condition value: {0}", m_condition ); } } public bool Signed { get { return m_fSigned; } } //--// // // Debug Methods // public override void InnerToString( System.Text.StringBuilder sb ) { sb.Append( "CompareAndSetOperator(" ); base.InnerToString( sb ); sb.AppendFormat( " Cond: {0}", m_condition ); sb.AppendFormat( " Signed: {0}", m_fSigned ); sb.Append( ")" ); } public override string FormatOutput( IIntermediateRepresentationDumper dumper ) { return dumper.FormatOutput( "{0} = {1} {2}{3} {4}", this.FirstResult, this.FirstArgument, m_condition, m_fSigned ? ".signed" : ".unsigned", this.SecondArgument ); } } } ================================================ FILE: Zelig/Zelig/CompileTime/CodeGenerator/IntermediateRepresentation/Operators/CompilationConstraintsOperator.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // namespace Microsoft.Zelig.CodeGeneration.IR { using System; using System.Collections.Generic; using Microsoft.Zelig.Runtime.TypeSystem; public sealed class CompilationConstraintsOperator : Operator { private const OperatorCapabilities cCapabilities = OperatorCapabilities.IsNonCommutative | OperatorCapabilities.DoesNotMutateExistingStorage | OperatorCapabilities.DoesNotAllocateStorage | OperatorCapabilities.DoesNotReadExistingMutableStorage | OperatorCapabilities.DoesNotThrow | OperatorCapabilities.DoesNotReadThroughPointerOperands | OperatorCapabilities.DoesNotWriteThroughPointerOperands | OperatorCapabilities.DoesNotCapturePointerOperands | OperatorCapabilities.IsMetaOperator ; // // State // private CompilationConstraints[] m_ccArraySet; private CompilationConstraints[] m_ccArrayReset; // // Constructor Methods // private CompilationConstraintsOperator( Debugging.DebugInfo debugInfo , CompilationConstraints[] ccArraySet , CompilationConstraints[] ccArrayReset ) : base( debugInfo, cCapabilities, OperatorLevel.Lowest ) { m_ccArraySet = ccArraySet; m_ccArrayReset = ccArrayReset; } //--// public static CompilationConstraintsOperator New( Debugging.DebugInfo debugInfo , CompilationConstraints[] ccArraySet , CompilationConstraints[] ccArrayReset ) { CompilationConstraintsOperator res = new CompilationConstraintsOperator( debugInfo, ccArraySet, ccArrayReset ); return res; } //--// // // Helper Methods // public override Operator Clone( CloningContext context ) { return RegisterAndCloneState( context, new CompilationConstraintsOperator( m_debugInfo, m_ccArraySet, m_ccArrayReset ) ); } //--// public override void ApplyTransformation( TransformationContextForIR context ) { context.Push( this ); base.ApplyTransformation( context ); context.Transform( ref m_ccArraySet ); context.Transform( ref m_ccArrayReset ); context.Pop(); } //--// public CompilationConstraints[] TransformCompilationConstraints( CompilationConstraints[] ccArray ) { foreach(CompilationConstraints cc in m_ccArrayReset) { ccArray = ControlFlowGraphState.RemoveCompilationConstraint( ccArray, cc ); } foreach(CompilationConstraints cc in m_ccArraySet) { ccArray = ControlFlowGraphState.AddCompilationConstraint( ccArray, cc ); } return ccArray; } //--// // // Access Methods // public CompilationConstraints[] Set { get { return m_ccArraySet; } } public CompilationConstraints[] Reset { get { return m_ccArrayReset; } } //--// // // Debug Methods // public override void InnerToString( System.Text.StringBuilder sb ) { sb.Append( "CompilationConstraintsOperator(" ); base.InnerToString( sb ); foreach(CompilationConstraints cc in m_ccArrayReset) { sb.AppendFormat( " Reset:{0}", cc ); } foreach(CompilationConstraints cc in m_ccArraySet) { sb.AppendFormat( " Set:{0}", cc ); } sb.Append( ")" ); } public override string FormatOutput( IIntermediateRepresentationDumper dumper ) { System.Text.StringBuilder sb = new System.Text.StringBuilder(); sb.Append( "constraint" ); foreach(CompilationConstraints cc in m_ccArrayReset) { sb.AppendFormat( " Reset:{0}", cc ); } foreach(CompilationConstraints cc in m_ccArraySet) { sb.AppendFormat( " Set:{0}", cc ); } return sb.ToString(); } } } ================================================ FILE: Zelig/Zelig/CompileTime/CodeGenerator/IntermediateRepresentation/Operators/Control/BinaryConditionalControlOperator.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // namespace Microsoft.Zelig.CodeGeneration.IR { using System; using System.Collections.Generic; using Microsoft.Zelig.Runtime.TypeSystem; public sealed class BinaryConditionalControlOperator : ConditionalControlOperator { // // State // private BasicBlock m_targetBranchTaken; // // Constructor Methods // private BinaryConditionalControlOperator( Debugging.DebugInfo debugInfo , OperatorCapabilities capabilities ) : base( debugInfo, capabilities, OperatorLevel.ConcreteTypes_NoExceptions ) { } //--// public static BinaryConditionalControlOperator New( Debugging.DebugInfo debugInfo , Expression rhs , BasicBlock targetFalse , BasicBlock targetTrue ) { OperatorCapabilities capabilities = OperatorCapabilities.IsNonCommutative | OperatorCapabilities.DoesNotMutateExistingStorage | OperatorCapabilities.DoesNotAllocateStorage | OperatorCapabilities.DoesNotReadExistingMutableStorage | OperatorCapabilities.DoesNotThrow | OperatorCapabilities.DoesNotReadThroughPointerOperands | OperatorCapabilities.DoesNotWriteThroughPointerOperands | OperatorCapabilities.DoesNotCapturePointerOperands ; BinaryConditionalControlOperator res = new BinaryConditionalControlOperator( debugInfo, capabilities ); res.SetRhs( rhs ); res.m_targetBranchNotTaken = targetFalse; res.m_targetBranchTaken = targetTrue; return res; } //--// // // Helper Methods // public override Operator Clone( CloningContext context ) { return RegisterAndCloneState( context, new BinaryConditionalControlOperator( m_debugInfo, m_capabilities ) ); } protected override void CloneState( CloningContext context , Operator clone ) { BinaryConditionalControlOperator clone2 = (BinaryConditionalControlOperator)clone; clone2.m_targetBranchTaken = context.Clone( m_targetBranchTaken ); base.CloneState( context, clone ); } //--// public override void ApplyTransformation( TransformationContextForIR context ) { context.Push( this ); base.ApplyTransformation( context ); context.Transform( ref m_targetBranchTaken ); context.Pop(); } //--// protected override void UpdateSuccessorInformation() { base.UpdateSuccessorInformation(); m_basicBlock.LinkToNormalBasicBlock( m_targetBranchTaken ); } //--// public override bool SubstituteTarget( BasicBlock oldBB , BasicBlock newBB ) { bool fChanged = base.SubstituteTarget( oldBB, newBB ); if(m_targetBranchTaken == oldBB) { m_targetBranchTaken = newBB; BumpVersion(); fChanged = true; } return fChanged; } //--// // // Access Methods // public BasicBlock TargetBranchTaken { get { return m_targetBranchTaken; } } //--// // // Debug Methods // public override void InnerToString( System.Text.StringBuilder sb ) { sb.Append( "BinaryConditionalControlOperator(" ); base.InnerToString( sb ); sb.AppendFormat( " Taken: {0}", m_targetBranchTaken.SpanningTreeIndex ); sb.Append( ")" ); } public override string FormatOutput( IIntermediateRepresentationDumper dumper ) { return dumper.FormatOutput( "if {0} != ZERO then goto {1} else goto {2}", this.FirstArgument, m_targetBranchTaken, m_targetBranchNotTaken ); } } } ================================================ FILE: Zelig/Zelig/CompileTime/CodeGenerator/IntermediateRepresentation/Operators/Control/CompareConditionalControlOperator.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // namespace Microsoft.Zelig.CodeGeneration.IR { using System; using System.Collections.Generic; using Microsoft.Zelig.Runtime.TypeSystem; public sealed class CompareConditionalControlOperator : ConditionalControlOperator { // // State // private CompareAndSetOperator.ActionCondition m_condition; private bool m_fSigned; private BasicBlock m_targetBranchTaken; // // Constructor Methods // private CompareConditionalControlOperator( Debugging.DebugInfo debugInfo , OperatorCapabilities capabilities , CompareAndSetOperator.ActionCondition condition , bool fSigned ) : base( debugInfo, capabilities, OperatorLevel.ConcreteTypes_NoExceptions ) { m_condition = condition; m_fSigned = fSigned; } //--// public static CompareConditionalControlOperator New( Debugging.DebugInfo debugInfo , CompareAndSetOperator.ActionCondition condition , bool fSigned , Expression rhsLeft , Expression rhsRight , BasicBlock targetFalse , BasicBlock targetTrue ) { OperatorCapabilities capabilities = OperatorCapabilities.DoesNotMutateExistingStorage | OperatorCapabilities.DoesNotAllocateStorage | OperatorCapabilities.DoesNotReadExistingMutableStorage | OperatorCapabilities.DoesNotThrow | OperatorCapabilities.DoesNotReadThroughPointerOperands | OperatorCapabilities.DoesNotWriteThroughPointerOperands | OperatorCapabilities.DoesNotCapturePointerOperands ; switch(condition) { case CompareAndSetOperator.ActionCondition.EQ: case CompareAndSetOperator.ActionCondition.NE: capabilities |= OperatorCapabilities.IsCommutative; break; default: capabilities |= OperatorCapabilities.IsNonCommutative; break; } CompareConditionalControlOperator res = new CompareConditionalControlOperator( debugInfo, capabilities, condition, fSigned ); res.SetRhs( rhsLeft, rhsRight ); res.m_targetBranchNotTaken = targetFalse; res.m_targetBranchTaken = targetTrue; return res; } //--// // // Helper Methods // public override Operator Clone( CloningContext context ) { return RegisterAndCloneState( context, new CompareConditionalControlOperator( m_debugInfo, m_capabilities, m_condition, m_fSigned ) ); } protected override void CloneState( CloningContext context , Operator clone ) { CompareConditionalControlOperator clone2 = (CompareConditionalControlOperator)clone; clone2.m_targetBranchTaken = context.Clone( m_targetBranchTaken ); base.CloneState( context, clone ); } //--// public override void ApplyTransformation( TransformationContextForIR context ) { context.Push( this ); base.ApplyTransformation( context ); context.Transform( ref m_condition ); context.Transform( ref m_fSigned ); context.Transform( ref m_targetBranchTaken ); context.Pop(); } //--// protected override void UpdateSuccessorInformation() { base.UpdateSuccessorInformation(); m_basicBlock.LinkToNormalBasicBlock( m_targetBranchTaken ); } //--// public override bool SubstituteTarget( BasicBlock oldBB , BasicBlock newBB ) { bool fChanged = base.SubstituteTarget( oldBB, newBB ); if(m_targetBranchTaken == oldBB) { m_targetBranchTaken = newBB; BumpVersion(); fChanged = true; } return fChanged; } //--// public override bool Simplify( Operator[][] defChains , Operator[][] useChains , VariableExpression.Property[] properties ) { var exL = FindConstantOrigin( this.FirstArgument , defChains, useChains, properties ); var exR = FindConstantOrigin( this.SecondArgument, defChains, useChains, properties ); if(exL != null && exR != null) { bool res; if(exL.IsValueInteger) { if(!exR.IsValueInteger) { throw TypeConsistencyErrorException.Create( "Cannot mix integer and floating-point values in the same operation: {0}", this ); } if(this.Signed) { long valL; long valR; if(exL.GetAsSignedInteger( out valL ) == false || exR.GetAsSignedInteger( out valR ) == false ) { return false; } switch(m_condition) { case CompareAndSetOperator.ActionCondition.EQ: res = (valL == valR); break; case CompareAndSetOperator.ActionCondition.GE: res = (valL >= valR); break; case CompareAndSetOperator.ActionCondition.GT: res = (valL > valR); break; case CompareAndSetOperator.ActionCondition.LE: res = (valL <= valR); break; case CompareAndSetOperator.ActionCondition.LT: res = (valL < valR); break; case CompareAndSetOperator.ActionCondition.NE: res = (valL != valR); break; default: return false; } } else { ulong valL; ulong valR; if(exL.GetAsUnsignedInteger( out valL ) == false || exR.GetAsUnsignedInteger( out valR ) == false ) { return false; } switch(m_condition) { case CompareAndSetOperator.ActionCondition.EQ: res = (valL == valR); break; case CompareAndSetOperator.ActionCondition.GE: res = (valL >= valR); break; case CompareAndSetOperator.ActionCondition.GT: res = (valL > valR); break; case CompareAndSetOperator.ActionCondition.LE: res = (valL <= valR); break; case CompareAndSetOperator.ActionCondition.LT: res = (valL < valR); break; case CompareAndSetOperator.ActionCondition.NE: res = (valL != valR); break; default: return false; } } } else if(exL.IsValueFloatingPoint) { if(!exR.IsValueFloatingPoint) { throw TypeConsistencyErrorException.Create( "Cannot mix integer and floating-point values in the same operation: {0}", this ); } object valL = exL.Value; object valR = exR.Value; if(valL is float) { if(!(valR is float)) { throw TypeConsistencyErrorException.Create( "Cannot mix single and double values in the same operation: {0}", this ); } float valL2 = (float)valL; float valR2 = (float)valR; switch(m_condition) { case CompareAndSetOperator.ActionCondition.EQ: res = (valL2 == valR2); break; case CompareAndSetOperator.ActionCondition.GE: res = (valL2 >= valR2); break; case CompareAndSetOperator.ActionCondition.GT: res = (valL2 > valR2); break; case CompareAndSetOperator.ActionCondition.LE: res = (valL2 <= valR2); break; case CompareAndSetOperator.ActionCondition.LT: res = (valL2 < valR2); break; case CompareAndSetOperator.ActionCondition.NE: res = (valL2 != valR2); break; default: return false; } } else if(valL is double) { if(!(valR is double)) { throw TypeConsistencyErrorException.Create( "Cannot mix single and double values in the same operation: {0}", this ); } double valL2 = (double)valL; double valR2 = (double)valR; switch(m_condition) { case CompareAndSetOperator.ActionCondition.EQ: res = (valL2 == valR2); break; case CompareAndSetOperator.ActionCondition.GE: res = (valL2 >= valR2); break; case CompareAndSetOperator.ActionCondition.GT: res = (valL2 > valR2); break; case CompareAndSetOperator.ActionCondition.LE: res = (valL2 <= valR2); break; case CompareAndSetOperator.ActionCondition.LT: res = (valL2 < valR2); break; case CompareAndSetOperator.ActionCondition.NE: res = (valL2 != valR2); break; default: return false; } } else { return false; } } else { return false; } this.SubstituteWithOperator( UnconditionalControlOperator.New( this.DebugInfo, res ? this.TargetBranchTaken : this.TargetBranchNotTaken ), SubstitutionFlags.Default ); return true; } return false; } //--// // // Access Methods // public CompareAndSetOperator.ActionCondition Condition { get { return m_condition; } } public CompareAndSetOperator.ActionCondition InvertedCondition { get { switch(m_condition) { case CompareAndSetOperator.ActionCondition.EQ: return CompareAndSetOperator.ActionCondition.NE; case CompareAndSetOperator.ActionCondition.GE: return CompareAndSetOperator.ActionCondition.LT; case CompareAndSetOperator.ActionCondition.GT: return CompareAndSetOperator.ActionCondition.LE; case CompareAndSetOperator.ActionCondition.LE: return CompareAndSetOperator.ActionCondition.GT; case CompareAndSetOperator.ActionCondition.LT: return CompareAndSetOperator.ActionCondition.GE; case CompareAndSetOperator.ActionCondition.NE: return CompareAndSetOperator.ActionCondition.EQ; } throw TypeConsistencyErrorException.Create( "Unexpected condition value: {0}", m_condition ); } } public bool Signed { get { return m_fSigned; } } public BasicBlock TargetBranchTaken { get { return m_targetBranchTaken; } } //--// // // Debug Methods // public override void InnerToString( System.Text.StringBuilder sb ) { sb.Append( "CompareConditionalControlOperator(" ); base.InnerToString( sb ); sb.AppendFormat( " Cond: {0}", m_condition ); sb.AppendFormat( " Signed: {0}", m_fSigned ); sb.AppendFormat( " Taken: {0}", m_targetBranchTaken.SpanningTreeIndex ); sb.Append( ")" ); } public override string FormatOutput( IIntermediateRepresentationDumper dumper ) { return dumper.FormatOutput( "if {0} {1}{2} {3} then goto {4} else goto {5}", this.FirstArgument, m_condition, m_fSigned ? ".signed" : ".unsigned", this.SecondArgument, m_targetBranchTaken, m_targetBranchNotTaken ); } } } ================================================ FILE: Zelig/Zelig/CompileTime/CodeGenerator/IntermediateRepresentation/Operators/Control/ConditionalControlOperator.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // namespace Microsoft.Zelig.CodeGeneration.IR { using System; using System.Collections.Generic; using Microsoft.Zelig.Runtime.TypeSystem; public abstract class ConditionalControlOperator : ControlOperator { // // State // protected BasicBlock m_targetBranchNotTaken; // // Constructor Methods // protected ConditionalControlOperator( Debugging.DebugInfo debugInfo , OperatorCapabilities capabilities , OperatorLevel level ) : base( debugInfo, capabilities, level ) { } //--// protected override void UpdateSuccessorInformation() { m_basicBlock.LinkToNormalBasicBlock( m_targetBranchNotTaken ); } //--// // // Helper Methods // protected override void CloneState( CloningContext context , Operator clone ) { ConditionalControlOperator clone2 = (ConditionalControlOperator)clone; clone2.m_targetBranchNotTaken = context.Clone( m_targetBranchNotTaken ); base.CloneState( context, clone ); } //--// public override void ApplyTransformation( TransformationContextForIR context ) { context.Push( this ); base.ApplyTransformation( context ); context.Transform( ref m_targetBranchNotTaken ); context.Pop(); } //--// public override bool SubstituteTarget( BasicBlock oldBB , BasicBlock newBB ) { if(m_targetBranchNotTaken == oldBB) { m_targetBranchNotTaken = newBB; BumpVersion(); return true; } return false; } //--// // // Access Methods // public BasicBlock TargetBranchNotTaken { get { return m_targetBranchNotTaken; } } //--// // // Debug Methods // public override void InnerToString( System.Text.StringBuilder sb ) { base.InnerToString( sb ); sb.AppendFormat( " NotTaken: {0}", m_targetBranchNotTaken.SpanningTreeIndex ); } } } ================================================ FILE: Zelig/Zelig/CompileTime/CodeGenerator/IntermediateRepresentation/Operators/Control/ControlOperator.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // namespace Microsoft.Zelig.CodeGeneration.IR { using System; using System.Collections.Generic; using Microsoft.Zelig.Runtime.TypeSystem; public abstract class ControlOperator : Operator { // // Constructor Methods // protected ControlOperator( Debugging.DebugInfo debugInfo , OperatorCapabilities capabilities , OperatorLevel level ) : base( debugInfo, capabilities, level ) { } //--// // // Helper Methods // internal void UpdateSuccessorInformationInner() { UpdateSuccessorInformation(); } protected abstract void UpdateSuccessorInformation(); public virtual bool ShouldIncludeInScheduling( BasicBlock bbNext ) { return (bbNext is ExceptionHandlerBasicBlock) == false; } //--// public abstract bool SubstituteTarget( BasicBlock oldBB , BasicBlock newBB ); } } ================================================ FILE: Zelig/Zelig/CompileTime/CodeGenerator/IntermediateRepresentation/Operators/Control/DeadControlOperator.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // namespace Microsoft.Zelig.CodeGeneration.IR { using System; using System.Collections.Generic; using Microsoft.Zelig.Runtime.TypeSystem; public sealed class DeadControlOperator : ControlOperator { private const OperatorCapabilities cCapabilities = OperatorCapabilities.IsNonCommutative | OperatorCapabilities.DoesNotMutateExistingStorage | OperatorCapabilities.DoesNotAllocateStorage | OperatorCapabilities.DoesNotReadExistingMutableStorage | OperatorCapabilities.DoesNotThrow | OperatorCapabilities.DoesNotReadThroughPointerOperands | OperatorCapabilities.DoesNotWriteThroughPointerOperands | OperatorCapabilities.DoesNotCapturePointerOperands ; // // Constructor Methods // private DeadControlOperator( Debugging.DebugInfo debugInfo ) : base( debugInfo, cCapabilities, OperatorLevel.Lowest ) { } //--// public static DeadControlOperator New( Debugging.DebugInfo debugInfo ) { DeadControlOperator res = new DeadControlOperator( debugInfo ); return res; } //--// // // Helper Methods // public override Operator Clone( CloningContext context ) { return RegisterAndCloneState( context, new DeadControlOperator( m_debugInfo ) ); } //--// protected override void UpdateSuccessorInformation() { } //--// public override bool SubstituteTarget( BasicBlock oldBB , BasicBlock newBB ) { return false; } //--// // // Access Methods // //--// // // Debug Methods // public override void InnerToString( System.Text.StringBuilder sb ) { sb.Append( "DeadControlOperator(" ); base.InnerToString( sb ); sb.Append( ")" ); } public override string FormatOutput( IIntermediateRepresentationDumper dumper ) { return dumper.FormatOutput( "dead code" ); } } } ================================================ FILE: Zelig/Zelig/CompileTime/CodeGenerator/IntermediateRepresentation/Operators/Control/EndFinallyControlOperator.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // namespace Microsoft.Zelig.CodeGeneration.IR { using System; using System.Collections.Generic; using Microsoft.Zelig.Runtime.TypeSystem; public sealed class EndFinallyControlOperator : ControlOperator { private const OperatorCapabilities cCapabilities = OperatorCapabilities.IsNonCommutative | OperatorCapabilities.DoesNotMutateExistingStorage | OperatorCapabilities.DoesNotAllocateStorage | OperatorCapabilities.DoesNotReadExistingMutableStorage | OperatorCapabilities.MayThrow | OperatorCapabilities.DoesNotReadThroughPointerOperands | OperatorCapabilities.DoesNotWriteThroughPointerOperands | OperatorCapabilities.DoesNotCapturePointerOperands ; // // Constructor Methods // private EndFinallyControlOperator( Debugging.DebugInfo debugInfo ) : base( debugInfo, cCapabilities, OperatorLevel.FullyObjectOriented ) { } //--// public static EndFinallyControlOperator New( Debugging.DebugInfo debugInfo ) { EndFinallyControlOperator res = new EndFinallyControlOperator( debugInfo ); return res; } //--// // // Helper Methods // public override Operator Clone( CloningContext context ) { return RegisterAndCloneState( context, new EndFinallyControlOperator( m_debugInfo ) ); } //--// protected override void UpdateSuccessorInformation() { } //--// public override bool SubstituteTarget( BasicBlock oldBB , BasicBlock newBB ) { return false; } //--// // // Access Methods // //--// // // Debug Methods // public override void InnerToString( System.Text.StringBuilder sb ) { sb.Append( "EndFinallyControlOperator(" ); base.InnerToString( sb ); sb.Append( ")" ); } public override string FormatOutput( IIntermediateRepresentationDumper dumper ) { return dumper.FormatOutput( "endfinally" ); } } } ================================================ FILE: Zelig/Zelig/CompileTime/CodeGenerator/IntermediateRepresentation/Operators/Control/LeaveControlOperator.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // namespace Microsoft.Zelig.CodeGeneration.IR { using System; using System.Collections.Generic; using Microsoft.Zelig.Runtime.TypeSystem; public sealed class LeaveControlOperator : ControlOperator { private const OperatorCapabilities cCapabilities = OperatorCapabilities.IsNonCommutative | OperatorCapabilities.DoesNotMutateExistingStorage | OperatorCapabilities.DoesNotAllocateStorage | OperatorCapabilities.DoesNotReadExistingMutableStorage | OperatorCapabilities.DoesNotThrow | OperatorCapabilities.DoesNotReadThroughPointerOperands | OperatorCapabilities.DoesNotWriteThroughPointerOperands | OperatorCapabilities.DoesNotCapturePointerOperands ; // // State // private BasicBlock m_targetBranch; // // Constructor Methods // private LeaveControlOperator( Debugging.DebugInfo debugInfo ) : base( debugInfo, cCapabilities, OperatorLevel.ObjectOriented ) { } //--// public static LeaveControlOperator New( Debugging.DebugInfo debugInfo , BasicBlock target ) { LeaveControlOperator res = new LeaveControlOperator( debugInfo ); res.m_targetBranch = target; return res; } //--// // // Helper Methods // public override Operator Clone( CloningContext context ) { return RegisterAndCloneState( context, new LeaveControlOperator( m_debugInfo ) ); } protected override void CloneState( CloningContext context , Operator clone ) { LeaveControlOperator clone2 = (LeaveControlOperator)clone; clone2.m_targetBranch = context.Clone( m_targetBranch ); base.CloneState( context, clone ); } //--// public override void ApplyTransformation( TransformationContextForIR context ) { context.Push( this ); base.ApplyTransformation( context ); context.Transform( ref m_targetBranch ); context.Pop(); } //--// public override bool SubstituteTarget( BasicBlock oldBB , BasicBlock newBB ) { if(m_targetBranch == oldBB) { m_targetBranch = newBB; BumpVersion(); return true; } return false; } //--// // // Access Methods // public BasicBlock TargetBranch { get { return m_targetBranch; } } //--// protected override void UpdateSuccessorInformation() { m_basicBlock.LinkToNormalBasicBlock( m_targetBranch ); } //--// // // Debug Methods // public override void InnerToString( System.Text.StringBuilder sb ) { sb.Append( "LeaveControlOperator(" ); base.InnerToString( sb ); sb.Append( ")" ); } public override string FormatOutput( IIntermediateRepresentationDumper dumper ) { return dumper.FormatOutput( "leave {0}", m_targetBranch ); } } } ================================================ FILE: Zelig/Zelig/CompileTime/CodeGenerator/IntermediateRepresentation/Operators/Control/MultiWayConditionalControlOperator.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // namespace Microsoft.Zelig.CodeGeneration.IR { using System; using System.Collections.Generic; using Microsoft.Zelig.Runtime.TypeSystem; public sealed class MultiWayConditionalControlOperator : ConditionalControlOperator { private const OperatorCapabilities cCapabilities = OperatorCapabilities.IsNonCommutative | OperatorCapabilities.DoesNotMutateExistingStorage | OperatorCapabilities.DoesNotAllocateStorage | OperatorCapabilities.DoesNotReadExistingMutableStorage | OperatorCapabilities.DoesNotThrow | OperatorCapabilities.DoesNotReadThroughPointerOperands | OperatorCapabilities.DoesNotWriteThroughPointerOperands | OperatorCapabilities.DoesNotCapturePointerOperands ; // // State // private BasicBlock[] m_targets; // // Constructor Methods // private MultiWayConditionalControlOperator( Debugging.DebugInfo debugInfo ) : base( debugInfo, cCapabilities, OperatorLevel.Lowest ) { } //--// public static MultiWayConditionalControlOperator New( Debugging.DebugInfo debugInfo , Expression rhs , BasicBlock targetNotTaken , BasicBlock[] targets ) { MultiWayConditionalControlOperator res = new MultiWayConditionalControlOperator( debugInfo ); res.SetRhs( rhs ); res.m_targetBranchNotTaken = targetNotTaken; res.m_targets = targets; return res; } //--// // // Helper Methods // public override Operator Clone( CloningContext context ) { return RegisterAndCloneState( context, new MultiWayConditionalControlOperator( m_debugInfo ) ); } protected override void CloneState( CloningContext context , Operator clone ) { MultiWayConditionalControlOperator clone2 = (MultiWayConditionalControlOperator)clone; clone2.m_targets = context.Clone( m_targets ); base.CloneState( context, clone ); } //--// public override void ApplyTransformation( TransformationContextForIR context ) { context.Push( this ); base.ApplyTransformation( context ); context.Transform( ref m_targets ); context.Pop(); } //--// protected override void UpdateSuccessorInformation() { base.UpdateSuccessorInformation(); foreach(BasicBlock target in m_targets) { m_basicBlock.LinkToNormalBasicBlock( target ); } } public override bool ShouldIncludeInScheduling( BasicBlock bbNext ) { if(base.ShouldIncludeInScheduling( bbNext ) == false) { return false; } return m_targetBranchNotTaken == bbNext; } //--// public override bool SubstituteTarget( BasicBlock oldBB , BasicBlock newBB ) { bool fChanged = base.SubstituteTarget( oldBB, newBB ); BasicBlock[] targets = m_targets; for(int pos = targets.Length; --pos >=0; ) { if(targets[pos] == oldBB) { if(m_targets == targets) { targets = ArrayUtility.CopyNotNullArray( m_targets ); } targets[pos] = newBB; } } if(m_targets != targets) { BumpVersion(); m_targets = targets; fChanged = true; } return fChanged; } //--// public override bool Simplify( Operator[][] defChains , Operator[][] useChains , VariableExpression.Property[] properties ) { if(base.Simplify( defChains, useChains, properties )) { return true; } var exConst = FindConstantOrigin( this.FirstArgument, defChains, useChains, properties ); if(exConst != null && exConst.IsValueInteger) { ulong val; if(exConst.GetAsRawUlong( out val )) { BasicBlock branch; if(val >= (ulong)m_targets.Length) { branch = m_targetBranchNotTaken; } else { branch = m_targets[(int)val]; } UnconditionalControlOperator opNew = UnconditionalControlOperator.New( this.DebugInfo, branch ); this.SubstituteWithOperator( opNew, Operator.SubstitutionFlags.CopyAnnotations ); return true; } } return false; } //--// // // Access Methods // public BasicBlock[] Targets { get { return m_targets; } } //--// // // Debug Methods // public override void InnerToString( System.Text.StringBuilder sb ) { sb.Append( "MultiWayConditionalControlOperator(" ); base.InnerToString( sb ); sb.Append( " Targets: ( " ); for(int i = 0; i < m_targets.Length; i++) { if(i != 0) sb.Append( ", " ); sb.Append( m_targets[i].SpanningTreeIndex ); } sb.Append( ")" ); } public override string FormatOutput( IIntermediateRepresentationDumper dumper ) { System.Text.StringBuilder sb = new System.Text.StringBuilder(); for(int i = 0; i < m_targets.Length; i++) { BasicBlock bb = m_targets[i]; if(i != 0) sb.Append( ", " ); sb.AppendFormat( "{0}", dumper.CreateLabel( bb ) ); } return dumper.FormatOutput( "switch {0} to {1}\n" + "goto {2}", this.FirstArgument, sb.ToString(), m_targetBranchNotTaken ); } } } ================================================ FILE: Zelig/Zelig/CompileTime/CodeGenerator/IntermediateRepresentation/Operators/Control/ResumeUnwindOperator.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // namespace Microsoft.Zelig.CodeGeneration.IR { using System; using System.Collections.Generic; using Microsoft.Zelig.Runtime.TypeSystem; public sealed class ResumeUnwindOperator : ControlOperator { private const OperatorCapabilities cCapabilities = OperatorCapabilities.IsNonCommutative | OperatorCapabilities.DoesNotMutateExistingStorage | OperatorCapabilities.DoesNotAllocateStorage | OperatorCapabilities.DoesNotReadExistingMutableStorage | OperatorCapabilities.MayThrow | OperatorCapabilities.DoesNotReadThroughPointerOperands | OperatorCapabilities.DoesNotWriteThroughPointerOperands | OperatorCapabilities.DoesNotCapturePointerOperands; private ResumeUnwindOperator(Debugging.DebugInfo debugInfo) : base(debugInfo, cCapabilities, OperatorLevel.Lowest) { } public static ResumeUnwindOperator New(Debugging.DebugInfo debugInfo, Expression exception) { ResumeUnwindOperator res = new ResumeUnwindOperator(debugInfo); res.SetRhs(exception); return res; } protected override void UpdateSuccessorInformation() { } public override bool SubstituteTarget(BasicBlock oldBB, BasicBlock newBB) { return false; } public override Operator Clone(CloningContext context) { return RegisterAndCloneState(context, new ResumeUnwindOperator(m_debugInfo)); } public override void InnerToString(System.Text.StringBuilder sb) { sb.Append("ResumeUnwindOperator("); base.InnerToString(sb); sb.Append(")"); } public override string FormatOutput(IIntermediateRepresentationDumper dumper) { return dumper.FormatOutput("throw {0}", this.FirstArgument); } } } ================================================ FILE: Zelig/Zelig/CompileTime/CodeGenerator/IntermediateRepresentation/Operators/Control/RethrowControlOperator.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // namespace Microsoft.Zelig.CodeGeneration.IR { using System; using System.Collections.Generic; using Microsoft.Zelig.Runtime.TypeSystem; public sealed class RethrowControlOperator : ControlOperator { private const OperatorCapabilities cCapabilities = OperatorCapabilities.IsNonCommutative | OperatorCapabilities.DoesNotMutateExistingStorage | OperatorCapabilities.DoesNotAllocateStorage | OperatorCapabilities.DoesNotReadExistingMutableStorage | OperatorCapabilities.MayThrow | OperatorCapabilities.DoesNotReadThroughPointerOperands | OperatorCapabilities.DoesNotWriteThroughPointerOperands | OperatorCapabilities.DoesNotCapturePointerOperands ; // // Constructor Methods // private RethrowControlOperator( Debugging.DebugInfo debugInfo ) : base( debugInfo, cCapabilities, OperatorLevel.FullyObjectOriented ) { } //--// public static RethrowControlOperator New( Debugging.DebugInfo debugInfo ) { RethrowControlOperator res = new RethrowControlOperator( debugInfo ); return res; } //--// // // Helper Methods // public override Operator Clone( CloningContext context ) { return RegisterAndCloneState( context, new RethrowControlOperator( m_debugInfo ) ); } //--// protected override void UpdateSuccessorInformation() { } //--// public override bool SubstituteTarget( BasicBlock oldBB , BasicBlock newBB ) { return false; } //--// // // Access Methods // //--// // // Debug Methods // public override void InnerToString( System.Text.StringBuilder sb ) { sb.Append( "RethrowControlOperator(" ); base.InnerToString( sb ); sb.Append( ")" ); } public override string FormatOutput( IIntermediateRepresentationDumper dumper ) { return dumper.FormatOutput( "rethrow" ); } } } ================================================ FILE: Zelig/Zelig/CompileTime/CodeGenerator/IntermediateRepresentation/Operators/Control/ReturnControlOperator.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // namespace Microsoft.Zelig.CodeGeneration.IR { using System; using System.Collections.Generic; using Microsoft.Zelig.Runtime.TypeSystem; public sealed class ReturnControlOperator : ControlOperator { private const OperatorCapabilities cCapabilities = OperatorCapabilities.IsNonCommutative | OperatorCapabilities.DoesNotMutateExistingStorage | OperatorCapabilities.DoesNotAllocateStorage | OperatorCapabilities.DoesNotReadExistingMutableStorage | OperatorCapabilities.DoesNotThrow | OperatorCapabilities.DoesNotReadThroughPointerOperands | OperatorCapabilities.DoesNotWriteThroughPointerOperands | OperatorCapabilities.DoesNotCapturePointerOperands ; // // Constructor Methods // private ReturnControlOperator() : base( null, cCapabilities, OperatorLevel.Lowest ) { } //--// public static ReturnControlOperator New() { ReturnControlOperator res = new ReturnControlOperator(); return res; } public static ReturnControlOperator New( Expression result ) { ReturnControlOperator res = new ReturnControlOperator(); res.SetRhs( result ); return res; } public static ReturnControlOperator New( Expression[] fragments ) { ReturnControlOperator res = new ReturnControlOperator(); res.SetRhsArray( fragments ); return res; } //--// // // Helper Methods // public override Operator Clone( CloningContext context ) { return RegisterAndCloneState( context, new ReturnControlOperator() ); } //--// protected override void UpdateSuccessorInformation() { } //--// public override bool SubstituteTarget( BasicBlock oldBB , BasicBlock newBB ) { return false; } //--// public override bool CanPropagateCopy( Expression exOld , Expression exNew ) { // // The Rvalues are used to keep alive the actual method result, so we cannot change them!! // return false; } //--// // // Access Methods // //--// // // Debug Methods // public override void InnerToString( System.Text.StringBuilder sb ) { sb.Append( "ReturnControlOperator(" ); base.InnerToString( sb ); sb.Append( ")" ); } public override string FormatOutput( IIntermediateRepresentationDumper dumper ) { System.Text.StringBuilder sb = new System.Text.StringBuilder( "return" ); object[] args = new object[this.Arguments.Length]; for(int i = 0; i < this.Arguments.Length; i++) { string fmt; if(i == 0) { fmt = " {0}{1}{2}"; } else { fmt = ", {0}{1}{2}"; } sb.AppendFormat( fmt, "{", i, "}" ); args[i] = this.Arguments[i]; } return dumper.FormatOutput( sb.ToString(), args ); } } } ================================================ FILE: Zelig/Zelig/CompileTime/CodeGenerator/IntermediateRepresentation/Operators/Control/ThrowControlOperator.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // namespace Microsoft.Zelig.CodeGeneration.IR { using System; using System.Collections.Generic; using Microsoft.Zelig.Runtime.TypeSystem; public sealed class ThrowControlOperator : ControlOperator { private const OperatorCapabilities cCapabilities = OperatorCapabilities.IsNonCommutative | OperatorCapabilities.DoesNotMutateExistingStorage | OperatorCapabilities.DoesNotAllocateStorage | OperatorCapabilities.DoesNotReadExistingMutableStorage | OperatorCapabilities.MayThrow | OperatorCapabilities.DoesNotReadThroughPointerOperands | OperatorCapabilities.DoesNotWriteThroughPointerOperands | OperatorCapabilities.DoesNotCapturePointerOperands ; // // Constructor Methods // private ThrowControlOperator( Debugging.DebugInfo debugInfo ) : base( debugInfo, cCapabilities, OperatorLevel.FullyObjectOriented ) { } //--// public static ThrowControlOperator New( Debugging.DebugInfo debugInfo , Expression eh ) { ThrowControlOperator res = new ThrowControlOperator( debugInfo ); res.SetRhs( eh ); return res; } //--// // // Helper Methods // public override Operator Clone( CloningContext context ) { return RegisterAndCloneState( context, new ThrowControlOperator( m_debugInfo ) ); } //--// protected override void UpdateSuccessorInformation() { } //--// public override bool SubstituteTarget( BasicBlock oldBB , BasicBlock newBB ) { return false; } //--// // // Access Methods // //--// // // Debug Methods // public override void InnerToString( System.Text.StringBuilder sb ) { sb.Append( "ThrowControlOperator(" ); base.InnerToString( sb ); sb.Append( ")" ); } public override string FormatOutput( IIntermediateRepresentationDumper dumper ) { return dumper.FormatOutput( "throw {0}", this.FirstArgument ); } } } ================================================ FILE: Zelig/Zelig/CompileTime/CodeGenerator/IntermediateRepresentation/Operators/Control/UnconditionalControlOperator.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // namespace Microsoft.Zelig.CodeGeneration.IR { using System; using System.Collections.Generic; using Microsoft.Zelig.Runtime.TypeSystem; public sealed class UnconditionalControlOperator : ControlOperator { private const OperatorCapabilities cCapabilities = OperatorCapabilities.IsNonCommutative | OperatorCapabilities.DoesNotMutateExistingStorage | OperatorCapabilities.DoesNotAllocateStorage | OperatorCapabilities.DoesNotReadExistingMutableStorage | OperatorCapabilities.DoesNotThrow | OperatorCapabilities.DoesNotReadThroughPointerOperands | OperatorCapabilities.DoesNotWriteThroughPointerOperands | OperatorCapabilities.DoesNotCapturePointerOperands ; // // State // private BasicBlock m_targetBranch; // // Constructor Methods // private UnconditionalControlOperator( Debugging.DebugInfo debugInfo ) : base( debugInfo, cCapabilities, OperatorLevel.Lowest ) { } //--// public static UnconditionalControlOperator New( Debugging.DebugInfo debugInfo , BasicBlock target ) { UnconditionalControlOperator res = new UnconditionalControlOperator( debugInfo ); res.m_targetBranch = target; return res; } //--// // // Helper Methods // public override Operator Clone( CloningContext context ) { return RegisterAndCloneState( context, new UnconditionalControlOperator( m_debugInfo ) ); } protected override void CloneState( CloningContext context , Operator clone ) { UnconditionalControlOperator clone2 = (UnconditionalControlOperator)clone; clone2.m_targetBranch = context.Clone( m_targetBranch ); base.CloneState( context, clone ); } //--// public override void ApplyTransformation( TransformationContextForIR context ) { context.Push( this ); base.ApplyTransformation( context ); context.Transform( ref m_targetBranch ); context.Pop(); } //--// protected override void UpdateSuccessorInformation() { m_basicBlock.LinkToNormalBasicBlock( m_targetBranch ); } //--// public override bool SubstituteTarget( BasicBlock oldBB , BasicBlock newBB ) { if(m_targetBranch == oldBB) { m_targetBranch = newBB; BumpVersion(); return true; } return false; } //--// // // Access Methods // public BasicBlock TargetBranch { get { return m_targetBranch; } } //--// // // Debug Methods // public override void InnerToString( System.Text.StringBuilder sb ) { sb.Append( "UnconditionalControlOperator(" ); base.InnerToString( sb ); sb.AppendFormat( " Target: {0}", m_targetBranch.SpanningTreeIndex ); sb.Append( ")" ); } public override string FormatOutput( IIntermediateRepresentationDumper dumper ) { return dumper.FormatOutput( "goto {0}", dumper.CreateLabel( m_targetBranch ) ); } } } ================================================ FILE: Zelig/Zelig/CompileTime/CodeGenerator/IntermediateRepresentation/Operators/ConversionOperator.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // namespace Microsoft.Zelig.CodeGeneration.IR { using System; using System.Collections.Generic; using Microsoft.Zelig.Runtime.TypeSystem; public abstract class ConversionOperator : Operator { // // State // private uint m_significantSize; private bool m_fOverflow; // // Constructor Methods // protected ConversionOperator( Debugging.DebugInfo debugInfo , OperatorCapabilities capabilities , OperatorLevel level , uint significantSize , bool fOverflow ) : base( debugInfo, capabilities, level ) { m_significantSize = significantSize; m_fOverflow = fOverflow; } //--// // // Helper Methods // public override void ApplyTransformation( TransformationContextForIR context ) { context.Push( this ); base.ApplyTransformation( context ); context.Transform( ref m_significantSize ); context.Transform( ref m_fOverflow ); context.Pop(); } //--// public override bool CanPropagateCopy( Expression exOld , Expression exNew ) { return exOld.Type == exNew.Type; } //--// // // Access Methods // public uint SignificantSize { get { return m_significantSize; } } public bool CheckOverflow { get { return m_fOverflow; } } //--// // // Debug Methods // public override void InnerToString( System.Text.StringBuilder sb ) { base.InnerToString( sb ); sb.AppendFormat( " SignificantSize: {0}", m_significantSize ); sb.AppendFormat( " Overflow: {0}", m_fOverflow ); } } } ================================================ FILE: Zelig/Zelig/CompileTime/CodeGenerator/IntermediateRepresentation/Operators/ConvertOperator.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // namespace Microsoft.Zelig.CodeGeneration.IR { using System; using System.Collections.Generic; using Microsoft.Zelig.Runtime.TypeSystem; public sealed class ConvertOperator : Operator { // // State // private TypeRepresentation.BuiltInTypes m_kindInput; private TypeRepresentation.BuiltInTypes m_kindOutput; private bool m_fOverflow; // // Constructor Methods // private ConvertOperator( Debugging.DebugInfo debugInfo , OperatorCapabilities capabilities , OperatorLevel level , TypeRepresentation.BuiltInTypes kindInput , TypeRepresentation.BuiltInTypes kindOutput , bool fOverflow ) : base( debugInfo, capabilities, level ) { m_kindInput = kindInput; m_kindOutput = kindOutput; m_fOverflow = fOverflow; } //--// public static ConvertOperator New( Debugging.DebugInfo debugInfo , TypeRepresentation.BuiltInTypes kindInput , TypeRepresentation.BuiltInTypes kindOutput , bool fOverflow , VariableExpression lhs , Expression rhs ) { OperatorCapabilities capabilities = OperatorCapabilities.IsNonCommutative | OperatorCapabilities.DoesNotMutateExistingStorage | OperatorCapabilities.DoesNotAllocateStorage | OperatorCapabilities.DoesNotReadExistingMutableStorage | OperatorCapabilities.DoesNotReadThroughPointerOperands | OperatorCapabilities.DoesNotWriteThroughPointerOperands | OperatorCapabilities.DoesNotCapturePointerOperands ; if(fOverflow) capabilities |= OperatorCapabilities.MayThrow; else capabilities |= OperatorCapabilities.DoesNotThrow; OperatorLevel level = fOverflow ? OperatorLevel.ConcreteTypes : (lhs.Type.IsNumeric && rhs.Type.IsNumeric ? OperatorLevel.ScalarValues : OperatorLevel.ConcreteTypes_NoExceptions); ConvertOperator res = new ConvertOperator( debugInfo, capabilities, level, kindInput, kindOutput, fOverflow ); res.SetLhs( lhs ); res.SetRhs( rhs ); return res; } //--// // // Helper Methods // public override Operator Clone( CloningContext context ) { return RegisterAndCloneState( context, new ConvertOperator( m_debugInfo, m_capabilities, m_level, m_kindInput, m_kindOutput, m_fOverflow ) ); } //--// public override void ApplyTransformation( TransformationContextForIR context ) { context.Push( this ); base.ApplyTransformation( context ); context.Transform( ref m_kindInput ); context.Transform( ref m_kindOutput ); context.Transform( ref m_fOverflow ); context.Pop(); } //--// public override ConstantExpression CanEvaluate( Operator[][] defChains , Operator[][] useChains , VariableExpression.Property[] properties ) { // // TODO: We should change the condition code to the outcome of the operation. // if(this.Results.Length != 1) { return null; } var ex = FindConstantOrigin( this.FirstArgument, defChains, useChains, properties ); if(ex != null) { // // BUGBUG: Overflow checking is ignored! // object valIN = ex.Value; object valOUT = null; switch(m_kindOutput) { case TypeRepresentation.BuiltInTypes.R4: if(valIN is int) { int val = (int)valIN; valOUT = (float)val; } else if(valIN is uint) { uint val = (uint)valIN; valOUT = (float)val; } else if(valIN is long) { long val = (long)valIN; valOUT = (float)val; } else if(valIN is ulong) { ulong val = (ulong)valIN; valOUT = (float)val; } else if(valIN is float) { valOUT = (float)valIN; } else if(valIN is double) { double val = (double)valIN; valOUT = (float)val; } break; case TypeRepresentation.BuiltInTypes.R8: if(valIN is int) { int val = (int)valIN; valOUT = (double)val; } else if(valIN is uint) { uint val = (uint)valIN; valOUT = (double)val; } else if(valIN is long) { long val = (long)valIN; valOUT = (double)val; } else if(valIN is ulong) { ulong val = (ulong)valIN; valOUT = (double)val; } else if(valIN is float) { float val = (float)valIN; valOUT = (double)val; } else if(valIN is double) { valOUT = (double)valIN; } break; case TypeRepresentation.BuiltInTypes.I4: if(valIN is float) { float val = (float)valIN; valOUT = (int)val; } else if(valIN is double) { double val = (double)valIN; valOUT = (int)val; } break; case TypeRepresentation.BuiltInTypes.U4: if(valIN is float) { float val = (float)valIN; valOUT = (uint)val; } else if(valIN is double) { double val = (double)valIN; valOUT = (uint)val; } break; case TypeRepresentation.BuiltInTypes.I8: if(valIN is float) { float val = (float)valIN; valOUT = (ulong)val; } else if(valIN is double) { double val = (double)valIN; valOUT = (ulong)val; } break; case TypeRepresentation.BuiltInTypes.U8: if(valIN is float) { float val = (float)valIN; valOUT = (long)val; } else if(valIN is double) { double val = (double)valIN; valOUT = (long)val; } break; } if(valOUT != null) { return new ConstantExpression( this.FirstResult.Type, valOUT ); } } return null; } //--// // // Access Methods // public TypeRepresentation.BuiltInTypes InputKind { get { return m_kindInput; } } public TypeRepresentation.BuiltInTypes OutputKind { get { return m_kindOutput; } } public bool CheckOverflow { get { return m_fOverflow; } } //--// // // Debug Methods // public override void InnerToString( System.Text.StringBuilder sb ) { sb.Append( "ConvertOperator(" ); base.InnerToString( sb ); sb.AppendFormat( " Input: {0}" , m_kindInput ); sb.AppendFormat( " Output: {0}", m_kindOutput ); sb.Append( ")" ); } public override string FormatOutput( IIntermediateRepresentationDumper dumper ) { return dumper.FormatOutput( "{0} = convert {1} from {2} to {3}{4}", this.FirstResult, this.FirstArgument, m_kindInput, m_kindOutput, this.MayThrow ? " MayThrow" : "" ); } } } ================================================ FILE: Zelig/Zelig/CompileTime/CodeGenerator/IntermediateRepresentation/Operators/FetchExceptionOperator.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // namespace Microsoft.Zelig.CodeGeneration.IR { using System; using System.Collections.Generic; using Microsoft.Zelig.Runtime.TypeSystem; public sealed class FetchExceptionOperator : Operator { private const OperatorCapabilities cCapabilities = OperatorCapabilities.IsNonCommutative | OperatorCapabilities.DoesNotMutateExistingStorage | OperatorCapabilities.DoesNotAllocateStorage | OperatorCapabilities.DoesNotReadExistingMutableStorage | OperatorCapabilities.DoesNotThrow | OperatorCapabilities.DoesNotReadThroughPointerOperands | OperatorCapabilities.DoesNotWriteThroughPointerOperands | OperatorCapabilities.DoesNotCapturePointerOperands ; // // State // private TypeRepresentation m_td; // // Constructor Methods // private FetchExceptionOperator( Debugging.DebugInfo debugInfo , TypeRepresentation td ) : base( debugInfo, cCapabilities, OperatorLevel.FullyObjectOriented ) { m_td = td; } //--// public static FetchExceptionOperator New( Debugging.DebugInfo debugInfo , TypeRepresentation td , VariableExpression lhs ) { FetchExceptionOperator res = new FetchExceptionOperator( debugInfo, td ); res.SetLhs( lhs ); return res; } //--// // // Helper Methods // public override Operator Clone( CloningContext context ) { TypeRepresentation td = context.ConvertType( m_td ); return RegisterAndCloneState( context, new FetchExceptionOperator( m_debugInfo, td ) ); } //--// public override void ApplyTransformation( TransformationContextForIR context ) { context.Push( this ); base.ApplyTransformation( context ); context.Transform( ref m_td ); context.Pop(); } //--// // // Access Methods // public TypeRepresentation Type { get { return m_td; } } //--// // // Debug Methods // public override void InnerToString( System.Text.StringBuilder sb ) { sb.Append( "FetchExceptionOperator(" ); base.InnerToString( sb ); sb.AppendFormat( " {0}", m_td ); sb.Append( ")" ); } public override string FormatOutput( IIntermediateRepresentationDumper dumper ) { return dumper.FormatOutput( "{0} = fetch exception {1}", this.FirstResult, m_td ); } } } ================================================ FILE: Zelig/Zelig/CompileTime/CodeGenerator/IntermediateRepresentation/Operators/LandingPadOperator.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // namespace Microsoft.Zelig.CodeGeneration.IR { using System; using System.Collections.Generic; using Microsoft.Zelig.Runtime.TypeSystem; public sealed class LandingPadOperator : Operator { private const OperatorCapabilities cCapabilities = OperatorCapabilities.IsNonCommutative | OperatorCapabilities.DoesNotMutateExistingStorage | OperatorCapabilities.DoesNotAllocateStorage | OperatorCapabilities.DoesNotReadExistingMutableStorage | OperatorCapabilities.DoesNotThrow | OperatorCapabilities.DoesNotReadThroughPointerOperands | OperatorCapabilities.DoesNotWriteThroughPointerOperands | OperatorCapabilities.DoesNotCapturePointerOperands; private LandingPadOperator(Debugging.DebugInfo debugInfo, bool hasCleanupClause) : base(debugInfo, cCapabilities, OperatorLevel.Lowest) { HasCleanupClause = hasCleanupClause; } public bool HasCleanupClause { get; } public static LandingPadOperator New( Debugging.DebugInfo debugInfo, VariableExpression result, Expression[] handledTypes, bool hasCleanupClause) { LandingPadOperator res = new LandingPadOperator(debugInfo, hasCleanupClause); res.SetLhs(result); res.SetRhsArray(handledTypes); return res; } public override Operator Clone(CloningContext context) { return RegisterAndCloneState(context, new LandingPadOperator(m_debugInfo, HasCleanupClause)); } protected override void CloneState(CloningContext context, Operator clone) { base.CloneState(context, clone); } //--// public override void ApplyTransformation(TransformationContextForIR context) { context.Push(this); base.ApplyTransformation(context); context.Pop(); } public override bool CanPropagateCopy(Expression exOld, Expression exNew) { return false; } public override void InnerToString(System.Text.StringBuilder sb) { sb.Append("LandingPadOperator("); base.InnerToString(sb); sb.Append(")"); } public override string FormatOutput(IIntermediateRepresentationDumper dumper) { System.Text.StringBuilder sb = new System.Text.StringBuilder(); for (int pos = 0; pos < this.Arguments.Length; pos++) { Expression ex = this.Arguments[pos]; string format; if (pos == 0) { format = "catch {0}"; } else { format = ", catch {0}"; } sb.Append(dumper.FormatOutput(format, Arguments[pos])); } return dumper.FormatOutput("{0} = landingpad({1})", FirstResult, sb.ToString()); } } } ================================================ FILE: Zelig/Zelig/CompileTime/CodeGenerator/IntermediateRepresentation/Operators/LongBinaryOperator.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // namespace Microsoft.Zelig.CodeGeneration.IR { using System; using System.Collections.Generic; using Microsoft.Zelig.Runtime.TypeSystem; public sealed class LongBinaryOperator : AbstractBinaryOperator { // // Constructor Methods // private LongBinaryOperator( Debugging.DebugInfo debugInfo , OperatorCapabilities capabilities , OperatorLevel level , ALU alu , bool fSigned , bool fOverflow ) : base( debugInfo, capabilities, level, alu, fSigned, fOverflow ) { } //--// public static LongBinaryOperator New( Debugging.DebugInfo debugInfo , ALU alu , bool fSigned , bool fOverflow , VariableExpression lhsLo , VariableExpression lhsHi , Expression rhsLeft , Expression rhsRight ) { OperatorCapabilities capabilities = OperatorCapabilities.DoesNotMutateExistingStorage | OperatorCapabilities.DoesNotAllocateStorage | OperatorCapabilities.DoesNotReadExistingMutableStorage | OperatorCapabilities.DoesNotReadThroughPointerOperands | OperatorCapabilities.DoesNotWriteThroughPointerOperands | OperatorCapabilities.DoesNotCapturePointerOperands ; switch(alu) { case ALU.ADD: case ALU.MUL: case ALU.AND: case ALU.OR: case ALU.XOR: capabilities |= OperatorCapabilities.IsCommutative; break; default: capabilities |= OperatorCapabilities.IsNonCommutative; break; } if(fOverflow) capabilities |= OperatorCapabilities.MayThrow; else capabilities |= OperatorCapabilities.DoesNotThrow; OperatorLevel level = fOverflow ? OperatorLevel.ConcreteTypes : OperatorLevel.Lowest; var res = new LongBinaryOperator( debugInfo, capabilities, level, alu, fSigned, fOverflow ); res.SetLhs( lhsLo , lhsHi ); res.SetRhs( rhsLeft, rhsRight ); return res; } //--// // // Helper Methods // public override Operator Clone( CloningContext context ) { return RegisterAndCloneState( context, new LongBinaryOperator( m_debugInfo, m_capabilities, m_level, m_alu, m_fSigned, m_fOverflow ) ); } //--// // // Access Methods // //--// // // Debug Methods // public override void InnerToString( System.Text.StringBuilder sb ) { sb.Append( "LongBinaryOperator(" ); base.InnerToString( sb ); sb.Append( ")" ); } public override string FormatOutput( IIntermediateRepresentationDumper dumper ) { return dumper.FormatOutput( "{0}, {1} = {2} {3} {4}{5}", this.FirstResult, this.SecondResult, this.FirstArgument, m_alu, this.SecondArgument, this.MayThrow ? " MayThrow" : "" ); } } } ================================================ FILE: Zelig/Zelig/CompileTime/CodeGenerator/IntermediateRepresentation/Operators/Memory/AddressAssignmentOperator.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // namespace Microsoft.Zelig.CodeGeneration.IR { using System; using System.Collections.Generic; using Microsoft.Zelig.Runtime.TypeSystem; public sealed class AddressAssignmentOperator : Operator { private const OperatorCapabilities cCapabilities = OperatorCapabilities.IsNonCommutative | OperatorCapabilities.DoesNotMutateExistingStorage | OperatorCapabilities.DoesNotAllocateStorage | OperatorCapabilities.DoesNotReadExistingMutableStorage | OperatorCapabilities.DoesNotThrow | OperatorCapabilities.DoesNotReadThroughPointerOperands | OperatorCapabilities.DoesNotWriteThroughPointerOperands | OperatorCapabilities.DoesNotCapturePointerOperands ; // // Constructor Methods // private AddressAssignmentOperator( Debugging.DebugInfo debugInfo ) : base( debugInfo, cCapabilities, OperatorLevel.Lowest ) { } //--// public static AddressAssignmentOperator New( Debugging.DebugInfo debugInfo , VariableExpression lhs , Expression rhs ) { AddressAssignmentOperator res = new AddressAssignmentOperator( debugInfo ); res.SetLhs( lhs ); res.SetRhs( rhs ); return res; } //--// // // Helper Methods // public override Operator Clone( CloningContext context ) { return RegisterAndCloneState( context, new AddressAssignmentOperator( m_debugInfo ) ); } //--// public override bool CanPropagateCopy( Expression exOld , Expression exNew ) { return false; } //--// // // Access Methods // //--// // // Debug Methods // public override void InnerToString( System.Text.StringBuilder sb ) { sb.Append( "AddressAssignmentOperator(" ); base.InnerToString( sb ); sb.Append( ")" ); } public override string FormatOutput( IIntermediateRepresentationDumper dumper ) { return dumper.FormatOutput( "{0} = address of {1}", this.FirstResult, this.FirstArgument ); } } } ================================================ FILE: Zelig/Zelig/CompileTime/CodeGenerator/IntermediateRepresentation/Operators/Memory/ArgListOperator.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // namespace Microsoft.Zelig.CodeGeneration.IR { using System; using System.Collections.Generic; using Microsoft.Zelig.Runtime.TypeSystem; public sealed class ArgListOperator : Operator { private const OperatorCapabilities cCapabilities = OperatorCapabilities.IsNonCommutative | OperatorCapabilities.DoesNotMutateExistingStorage | OperatorCapabilities.DoesNotAllocateStorage | OperatorCapabilities.DoesNotReadExistingMutableStorage | OperatorCapabilities.DoesNotThrow | OperatorCapabilities.DoesNotReadThroughPointerOperands | OperatorCapabilities.DoesNotWriteThroughPointerOperands | OperatorCapabilities.DoesNotCapturePointerOperands ; // // Constructor Methods // private ArgListOperator( Debugging.DebugInfo debugInfo ) : base( debugInfo, cCapabilities, OperatorLevel.FullyObjectOriented ) { } //--// public static ArgListOperator New( Debugging.DebugInfo debugInfo , VariableExpression lhs ) { ArgListOperator res = new ArgListOperator( debugInfo ); res.SetLhs( lhs ); return res; } //--// // // Helper Methods // public override Operator Clone( CloningContext context ) { return RegisterAndCloneState( context, new ArgListOperator( m_debugInfo ) ); } //--// // // Access Methods // //--// // // Debug Methods // public override void InnerToString( System.Text.StringBuilder sb ) { sb.Append( "ArgListOperator(" ); base.InnerToString( sb ); sb.Append( ")" ); } public override string FormatOutput( IIntermediateRepresentationDumper dumper ) { return dumper.FormatOutput( "{0} = arglist", this.FirstResult ); } } } ================================================ FILE: Zelig/Zelig/CompileTime/CodeGenerator/IntermediateRepresentation/Operators/Memory/ElementOperator.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // namespace Microsoft.Zelig.CodeGeneration.IR { using System; using System.Collections.Generic; using Microsoft.Zelig.Runtime.TypeSystem; public abstract class ElementOperator : Operator { // // State // protected FieldRepresentation[] m_accessPath; // // Constructor Methods // protected ElementOperator( Debugging.DebugInfo debugInfo , OperatorCapabilities capabilities , OperatorLevel level , FieldRepresentation[] accessPath ) : base( debugInfo, capabilities, level ) { m_accessPath = accessPath; } //--// // // Helper Methods // public override void ApplyTransformation( TransformationContextForIR context ) { context.Push( this ); base.ApplyTransformation( context ); context.Transform( ref m_accessPath ); context.Pop(); } // // Access Methods // public FieldRepresentation[] AccessPath { get { return m_accessPath; } } // // Debug Methods // public override void InnerToString( System.Text.StringBuilder sb ) { base.InnerToString( sb ); if(m_accessPath != null) { foreach(FieldRepresentation fd in m_accessPath) { sb.AppendFormat(",Field={0}", fd ); } } } } } ================================================ FILE: Zelig/Zelig/CompileTime/CodeGenerator/IntermediateRepresentation/Operators/Memory/FieldOperator.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // namespace Microsoft.Zelig.CodeGeneration.IR { using System; using System.Collections.Generic; using Microsoft.Zelig.Runtime.TypeSystem; public abstract class FieldOperator : Operator { // // State // private FieldRepresentation m_fd; // // Constructor Methods // protected FieldOperator( Debugging.DebugInfo debugInfo , OperatorCapabilities capabilities , OperatorLevel level , FieldRepresentation field ) : base( debugInfo, capabilities, level ) { m_fd = field; } //--// // // Helper Methods // public override void ApplyTransformation( TransformationContextForIR context ) { context.Push( this ); base.ApplyTransformation( context ); context.Transform( ref m_fd ); context.Pop(); } // // Access Methods // public FieldRepresentation Field { get { return m_fd; } } // // Debug Methods // public override void InnerToString( System.Text.StringBuilder sb ) { sb.AppendFormat( "{0} ", m_fd ); base.InnerToString( sb ); } } } ================================================ FILE: Zelig/Zelig/CompileTime/CodeGenerator/IntermediateRepresentation/Operators/Memory/IndirectOperator.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // namespace Microsoft.Zelig.CodeGeneration.IR { using System; using System.Collections.Generic; using Microsoft.Zelig.Runtime.TypeSystem; public abstract class IndirectOperator : Operator { // // State // protected TypeRepresentation m_td; protected int m_offset; protected FieldRepresentation[] m_accessPath; // // Constructor Methods // protected IndirectOperator( Debugging.DebugInfo debugInfo , OperatorCapabilities capabilities , OperatorLevel level , TypeRepresentation td , FieldRepresentation[] accessPath , int offset ) : base( debugInfo, capabilities, level ) { m_td = td; m_accessPath = accessPath; m_offset = offset; } //--// // // Helper Methods // public override void ApplyTransformation( TransformationContextForIR context ) { context.Push( this ); base.ApplyTransformation( context ); context.Transform( ref m_td ); context.Transform( ref m_offset ); context.Transform( ref m_accessPath ); context.Pop(); } //--// // // Access Methods // public TypeRepresentation Type { get { return m_td; } } public FieldRepresentation[] AccessPath { get { return m_accessPath; } } public int Offset { get { return m_offset; } } // // Debug Methods // public override void InnerToString( System.Text.StringBuilder sb ) { base.InnerToString( sb ); if(m_accessPath != null) { foreach(FieldRepresentation fd in m_accessPath) { sb.AppendFormat(",Field={0}", fd ); } } if(m_offset != 0) { sb.AppendFormat(",Offset={0}", m_offset ); } } } } ================================================ FILE: Zelig/Zelig/CompileTime/CodeGenerator/IntermediateRepresentation/Operators/Memory/LoadAddressOperator.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // namespace Microsoft.Zelig.CodeGeneration.IR { using System; using System.Collections.Generic; using Microsoft.Zelig.Runtime.TypeSystem; public abstract class LoadAddressOperator : FieldOperator { // // Constructor Methods // protected LoadAddressOperator( Debugging.DebugInfo debugInfo , OperatorCapabilities capabilities , OperatorLevel level , FieldRepresentation field ) : base( debugInfo, capabilities, level, field ) { } //--// // // Helper Methods // //--// // // Access Methods // //--// // // Debug Methods // } } ================================================ FILE: Zelig/Zelig/CompileTime/CodeGenerator/IntermediateRepresentation/Operators/Memory/LoadElementAddressOperator.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // namespace Microsoft.Zelig.CodeGeneration.IR { using System; using System.Collections.Generic; using Microsoft.Zelig.Runtime.TypeSystem; public sealed class LoadElementAddressOperator : ElementOperator { // // Constructor Methods // private LoadElementAddressOperator( Debugging.DebugInfo debugInfo , OperatorCapabilities capabilities , OperatorLevel level , FieldRepresentation[] accessPath ) : base( debugInfo, capabilities, level, accessPath ) { } //--// public static LoadElementAddressOperator New( Debugging.DebugInfo debugInfo , VariableExpression lhs , Expression rhsArray , Expression rhsIndex , FieldRepresentation[] accessPath , bool fNullCheck ) { OperatorLevel level; OperatorCapabilities capabilities = OperatorCapabilities.IsNonCommutative | OperatorCapabilities.DoesNotMutateExistingStorage | OperatorCapabilities.DoesNotAllocateStorage | OperatorCapabilities.DoesNotReadExistingMutableStorage | OperatorCapabilities.DoesNotReadThroughPointerOperands | OperatorCapabilities.DoesNotWriteThroughPointerOperands | OperatorCapabilities.DoesNotCapturePointerOperands ; if(fNullCheck) { level = OperatorLevel .ConcreteTypes; capabilities |= OperatorCapabilities.MayThrow; // Out-of-bounds and null pointer checks can throw. } else { level = OperatorLevel .Lowest; capabilities |= OperatorCapabilities.DoesNotThrow; } LoadElementAddressOperator res = new LoadElementAddressOperator( debugInfo, capabilities, level, accessPath ); res.SetLhs( lhs ); res.SetRhs( rhsArray, rhsIndex ); return res; } //--// // // Helper Methods // public override Operator Clone( CloningContext context ) { FieldRepresentation[] accessPath = context.ConvertFields( m_accessPath ); return RegisterAndCloneState( context, new LoadElementAddressOperator( m_debugInfo, m_capabilities, m_level, accessPath ) ); } //--// // // Access Methods // //--// // // Debug Methods // public override void InnerToString( System.Text.StringBuilder sb ) { sb.Append( "LoadElementAddressOperator(" ); base.InnerToString( sb ); sb.Append( ")" ); } public override string FormatOutput( IIntermediateRepresentationDumper dumper ) { return dumper.FormatOutput( "{0} = address of {1}[{2}]{3}", this.FirstResult, this.FirstArgument, this.SecondArgument, this.MayThrow ? " MayThrow" : "" ); } } } ================================================ FILE: Zelig/Zelig/CompileTime/CodeGenerator/IntermediateRepresentation/Operators/Memory/LoadElementOperator.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // namespace Microsoft.Zelig.CodeGeneration.IR { using System; using System.Collections.Generic; using Microsoft.Zelig.Runtime.TypeSystem; public sealed class LoadElementOperator : ElementOperator { // // Constructor Methods // private LoadElementOperator( Debugging.DebugInfo debugInfo , OperatorCapabilities capabilities , OperatorLevel level , FieldRepresentation[] accessPath ) : base( debugInfo, capabilities, level, accessPath ) { } //--// public static LoadElementOperator New( Debugging.DebugInfo debugInfo , VariableExpression lhs , Expression rhsArray , Expression rhsIndex , FieldRepresentation[] accessPath , bool fNullCheck ) { OperatorLevel level; OperatorCapabilities capabilities = OperatorCapabilities.IsNonCommutative | OperatorCapabilities.DoesNotMutateExistingStorage | OperatorCapabilities.DoesNotAllocateStorage | OperatorCapabilities.MayReadExistingMutableStorage | OperatorCapabilities.DoesNotReadThroughPointerOperands | OperatorCapabilities.DoesNotWriteThroughPointerOperands | OperatorCapabilities.DoesNotCapturePointerOperands ; if(fNullCheck) { level = OperatorLevel .ConcreteTypes; capabilities |= OperatorCapabilities.MayThrow; // Out-of-bounds and null pointer checks can throw. } else { level = OperatorLevel .Lowest; capabilities |= OperatorCapabilities.DoesNotThrow; } LoadElementOperator res = new LoadElementOperator( debugInfo, capabilities, level, accessPath ); res.SetLhs( lhs ); res.SetRhs( rhsArray, rhsIndex ); return res; } //--// // // Helper Methods // public override Operator Clone( CloningContext context ) { FieldRepresentation[] accessPath = context.ConvertFields( m_accessPath ); return RegisterAndCloneState( context, new LoadElementOperator( m_debugInfo, m_capabilities, m_level, accessPath ) ); } //--// // // Access Methods // //--// // // Debug Methods // public override void InnerToString( System.Text.StringBuilder sb ) { sb.Append( "LoadElementOperator(" ); base.InnerToString( sb ); sb.Append( ")" ); } public override string FormatOutput( IIntermediateRepresentationDumper dumper ) { return dumper.FormatOutput( "{0} <= {1}[{2}]{3}", this.FirstResult, this.FirstArgument, this.SecondArgument, this.MayThrow ? " MayThrow" : "" ); } } } ================================================ FILE: Zelig/Zelig/CompileTime/CodeGenerator/IntermediateRepresentation/Operators/Memory/LoadFieldOperator.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // namespace Microsoft.Zelig.CodeGeneration.IR { using System; using System.Collections.Generic; using Microsoft.Zelig.Runtime.TypeSystem; public abstract class LoadFieldOperator : FieldOperator { // // Constructor Methods // protected LoadFieldOperator( Debugging.DebugInfo debugInfo , OperatorCapabilities capabilities , OperatorLevel level , FieldRepresentation field ) : base( debugInfo, capabilities, level, field ) { } //--// // // Helper Methods // //--// // // Access Methods // //--// // // Debug Methods // } } ================================================ FILE: Zelig/Zelig/CompileTime/CodeGenerator/IntermediateRepresentation/Operators/Memory/LoadIndirectOperator.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // namespace Microsoft.Zelig.CodeGeneration.IR { using System; using System.Collections.Generic; using Microsoft.Zelig.Runtime.TypeSystem; public sealed class LoadIndirectOperator : IndirectOperator { // // State // // // Constructor Methods // private LoadIndirectOperator( Debugging.DebugInfo debugInfo , OperatorCapabilities capabilities , OperatorLevel level , TypeRepresentation td , FieldRepresentation[] accessPath , int offset ) : base( debugInfo, capabilities, level, td, accessPath, offset ) { } //--// public static LoadIndirectOperator New( Debugging.DebugInfo debugInfo , TypeRepresentation td , VariableExpression lhs , Expression rhs , FieldRepresentation[] accessPath , int offset , bool fIsVolatile , bool fNullCheck ) { OperatorLevel level; OperatorCapabilities capabilities = OperatorCapabilities.IsNonCommutative | OperatorCapabilities.DoesNotAllocateStorage | OperatorCapabilities.MayReadExistingMutableStorage | // TODO: method analysis could discover the pointer is outside the stack. OperatorCapabilities.MayReadThroughPointerOperands | OperatorCapabilities.DoesNotWriteThroughPointerOperands | OperatorCapabilities.MayCapturePointerOperands ; // TODO: Is it true? if(fIsVolatile) { capabilities |= OperatorCapabilities.MayMutateExistingStorage; } else { capabilities |= OperatorCapabilities.DoesNotMutateExistingStorage; } if(fNullCheck) { level = OperatorLevel .ConcreteTypes; capabilities |= OperatorCapabilities.MayThrow; } else { level = OperatorLevel .Lowest; capabilities |= OperatorCapabilities.DoesNotThrow; } LoadIndirectOperator res = new LoadIndirectOperator( debugInfo, capabilities, level, td, accessPath, offset ); res.SetLhs( lhs ); res.SetRhs( rhs ); return res; } //--// // // Helper Methods // public override Operator Clone( CloningContext context ) { TypeRepresentation td = context.ConvertType ( m_td ); FieldRepresentation[] accessPath = context.ConvertFields( m_accessPath ); return RegisterAndCloneState( context, new LoadIndirectOperator( m_debugInfo, m_capabilities, m_level, td, accessPath, m_offset ) ); } //--// // // Access Methods // //--// // // Debug Methods // public override void InnerToString( System.Text.StringBuilder sb ) { sb.Append( "LoadIndirectOperator(" ); base.InnerToString( sb ); sb.Append( ")" ); } public override string FormatOutput( IIntermediateRepresentationDumper dumper ) { return dumper.FormatOutput( "{0} <= [{1},#{2}] as {3}{4}", this.FirstResult, this.FirstArgument, m_offset, m_td, this.MayThrow ? " MayThrow" : "" ); } } } ================================================ FILE: Zelig/Zelig/CompileTime/CodeGenerator/IntermediateRepresentation/Operators/Memory/LoadInstanceFieldAddressOperator.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // namespace Microsoft.Zelig.CodeGeneration.IR { using System; using System.Collections.Generic; using Microsoft.Zelig.Runtime.TypeSystem; public sealed class LoadInstanceFieldAddressOperator : LoadAddressOperator { // // Constructor Methods // private LoadInstanceFieldAddressOperator( Debugging.DebugInfo debugInfo , OperatorCapabilities capabilities , OperatorLevel level , FieldRepresentation field ) : base( debugInfo, capabilities, level, field ) { } //--// public static LoadInstanceFieldAddressOperator New( Debugging.DebugInfo debugInfo , FieldRepresentation field , VariableExpression lhs , Expression rhsObj , bool fNullCheck ) { OperatorLevel level; OperatorCapabilities capabilities = OperatorCapabilities.IsNonCommutative | OperatorCapabilities.DoesNotMutateExistingStorage | OperatorCapabilities.DoesNotAllocateStorage | OperatorCapabilities.DoesNotReadExistingMutableStorage | OperatorCapabilities.DoesNotReadThroughPointerOperands | OperatorCapabilities.DoesNotWriteThroughPointerOperands | OperatorCapabilities.DoesNotCapturePointerOperands ; if(fNullCheck) { level = OperatorLevel .ConcreteTypes; capabilities |= OperatorCapabilities.MayThrow; } else { level = OperatorLevel .ConcreteTypes_NoExceptions; capabilities |= OperatorCapabilities.DoesNotThrow; } LoadInstanceFieldAddressOperator res = new LoadInstanceFieldAddressOperator( debugInfo, capabilities, level, field ); res.SetLhs( lhs ); res.SetRhs( rhsObj ); return res; } //--// // // Helper Methods // public override Operator Clone( CloningContext context ) { FieldRepresentation fd = context.ConvertField( this.Field ); return RegisterAndCloneState( context, new LoadInstanceFieldAddressOperator( m_debugInfo, m_capabilities, m_level, fd ) ); } //--// // // Access Methods // //--// // // Debug Methods // public override void InnerToString( System.Text.StringBuilder sb ) { sb.Append( "LoadInstanceFieldAddressOperator(" ); base.InnerToString( sb ); sb.Append( ")" ); } public override string FormatOutput( IIntermediateRepresentationDumper dumper ) { return dumper.FormatOutput( "{0} = address of [{1}, {2}]{3}", this.FirstResult, this.FirstArgument, this.Field, this.MayThrow ? " MayThrow" : "" ); } } } ================================================ FILE: Zelig/Zelig/CompileTime/CodeGenerator/IntermediateRepresentation/Operators/Memory/LoadInstanceFieldOperator.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // namespace Microsoft.Zelig.CodeGeneration.IR { using System; using System.Collections.Generic; using Microsoft.Zelig.Runtime.TypeSystem; public sealed class LoadInstanceFieldOperator : LoadFieldOperator { // // Constructor Methods // private LoadInstanceFieldOperator( Debugging.DebugInfo debugInfo , OperatorCapabilities capabilities , OperatorLevel level , FieldRepresentation field ) : base( debugInfo, capabilities, level, field ) { } //--// public static LoadInstanceFieldOperator New( Debugging.DebugInfo debugInfo , FieldRepresentation field , VariableExpression lhs , Expression rhsObj , bool fNullCheck ) { OperatorLevel level; OperatorCapabilities capabilities = OperatorCapabilities.IsNonCommutative | OperatorCapabilities.DoesNotMutateExistingStorage | OperatorCapabilities.DoesNotAllocateStorage | OperatorCapabilities.MayReadExistingMutableStorage | // TODO: method analysis could discover the pointer is outside the stack. OperatorCapabilities.DoesNotWriteThroughPointerOperands ; if(rhsObj.Type is PointerTypeRepresentation || rhsObj.Type is BoxedValueTypeRepresentation ) { capabilities |= OperatorCapabilities.MayReadThroughPointerOperands | OperatorCapabilities.MayCapturePointerOperands ; } else { capabilities |= OperatorCapabilities.DoesNotReadThroughPointerOperands | OperatorCapabilities.DoesNotCapturePointerOperands ; } if(fNullCheck) { level = OperatorLevel .ConcreteTypes; capabilities |= OperatorCapabilities.MayThrow; } else { level = OperatorLevel .ConcreteTypes_NoExceptions; capabilities |= OperatorCapabilities.DoesNotThrow; } LoadInstanceFieldOperator res = new LoadInstanceFieldOperator( debugInfo, capabilities, level, field ); res.SetLhs( lhs ); res.SetRhs( rhsObj ); return res; } //--// // // Helper Methods // public override Operator Clone( CloningContext context ) { FieldRepresentation fd = context.ConvertField( this.Field ); return RegisterAndCloneState( context, new LoadInstanceFieldOperator( m_debugInfo, m_capabilities, m_level, fd ) ); } // // Access Methods // //--// // // Debug Methods // public override void InnerToString( System.Text.StringBuilder sb ) { sb.Append( "LoadInstanceFieldOperator(" ); base.InnerToString( sb ); sb.Append( ")" ); } public override string FormatOutput( IIntermediateRepresentationDumper dumper ) { return dumper.FormatOutput( "{0} <= [{1}, {2}]{3}", this.FirstResult, this.FirstArgument, this.Field, this.MayThrow ? " MayThrow" : "" ); } } } ================================================ FILE: Zelig/Zelig/CompileTime/CodeGenerator/IntermediateRepresentation/Operators/Memory/LoadStaticFieldAddressOperator.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // namespace Microsoft.Zelig.CodeGeneration.IR { using System; using System.Collections.Generic; using Microsoft.Zelig.Runtime.TypeSystem; public sealed class LoadStaticFieldAddressOperator : LoadAddressOperator { private const OperatorCapabilities cCapabilities = OperatorCapabilities.IsNonCommutative | OperatorCapabilities.DoesNotMutateExistingStorage | OperatorCapabilities.DoesNotAllocateStorage | OperatorCapabilities.DoesNotReadExistingMutableStorage | OperatorCapabilities.DoesNotThrow | OperatorCapabilities.DoesNotReadThroughPointerOperands | OperatorCapabilities.DoesNotWriteThroughPointerOperands | OperatorCapabilities.DoesNotCapturePointerOperands ; // // Constructor Methods // private LoadStaticFieldAddressOperator( Debugging.DebugInfo debugInfo , FieldRepresentation field ) : base( debugInfo, cCapabilities, OperatorLevel.FullyObjectOriented, field ) { } //--// public static LoadStaticFieldAddressOperator New( Debugging.DebugInfo debugInfo , FieldRepresentation field , VariableExpression lhs ) { LoadStaticFieldAddressOperator res = new LoadStaticFieldAddressOperator( debugInfo, field ); res.SetLhs( lhs ); return res; } //--// // // Helper Methods // public override Operator Clone( CloningContext context ) { FieldRepresentation fd = context.ConvertField( this.Field ); return RegisterAndCloneState( context, new LoadStaticFieldAddressOperator( m_debugInfo, fd ) ); } //--// // // Access Methods // //--// // // Debug Methods // public override void InnerToString( System.Text.StringBuilder sb ) { sb.Append( "LoadStaticFieldAddressOperator(" ); base.InnerToString( sb ); sb.Append( ")" ); } public override string FormatOutput( IIntermediateRepresentationDumper dumper ) { return dumper.FormatOutput( "{0} = address of [{1}]", this.FirstResult, this.Field ); } } } ================================================ FILE: Zelig/Zelig/CompileTime/CodeGenerator/IntermediateRepresentation/Operators/Memory/LoadStaticFieldOperator.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // namespace Microsoft.Zelig.CodeGeneration.IR { using System; using System.Collections.Generic; using Microsoft.Zelig.Runtime.TypeSystem; public sealed class LoadStaticFieldOperator : LoadFieldOperator { private const OperatorCapabilities cCapabilities = OperatorCapabilities.IsNonCommutative | OperatorCapabilities.DoesNotMutateExistingStorage | OperatorCapabilities.DoesNotAllocateStorage | OperatorCapabilities.MayReadExistingMutableStorage | // TODO: Are static fields part of the heap? OperatorCapabilities.DoesNotThrow | OperatorCapabilities.DoesNotReadThroughPointerOperands | OperatorCapabilities.DoesNotWriteThroughPointerOperands | OperatorCapabilities.DoesNotCapturePointerOperands ; // // Constructor Methods // private LoadStaticFieldOperator( Debugging.DebugInfo debugInfo , FieldRepresentation field ) : base( debugInfo, cCapabilities, OperatorLevel.FullyObjectOriented, field ) { } //--// public static LoadStaticFieldOperator New( Debugging.DebugInfo debugInfo , FieldRepresentation field , VariableExpression lhs ) { LoadStaticFieldOperator res = new LoadStaticFieldOperator( debugInfo, field ); res.SetLhs( lhs ); return res; } //--// // // Helper Methods // public override Operator Clone( CloningContext context ) { FieldRepresentation fd = context.ConvertField( this.Field ); return RegisterAndCloneState( context, new LoadStaticFieldOperator( m_debugInfo, fd ) ); } //--// // // Access Methods // //--// // // Debug Methods // public override void InnerToString( System.Text.StringBuilder sb ) { sb.Append( "LoadStaticFieldOperator(" ); base.InnerToString( sb ); sb.Append( ")" ); } public override string FormatOutput( IIntermediateRepresentationDumper dumper ) { return dumper.FormatOutput( "{0} <= [{1}]", this.FirstResult, this.Field ); } } } ================================================ FILE: Zelig/Zelig/CompileTime/CodeGenerator/IntermediateRepresentation/Operators/Memory/StackAllocationOperator.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // namespace Microsoft.Zelig.CodeGeneration.IR { using System; using System.Collections.Generic; using Microsoft.Zelig.Runtime.TypeSystem; public sealed class StackAllocationOperator : Operator { private const OperatorCapabilities cCapabilities = OperatorCapabilities.IsNonCommutative | OperatorCapabilities.DoesNotMutateExistingStorage | OperatorCapabilities.DoesNotAllocateStorage | // It only allocates in the stack space. OperatorCapabilities.DoesNotReadExistingMutableStorage | OperatorCapabilities.MayThrow | // Stack overflow. OperatorCapabilities.DoesNotReadThroughPointerOperands | OperatorCapabilities.DoesNotWriteThroughPointerOperands | OperatorCapabilities.DoesNotCapturePointerOperands ; // // Constructor Methods // private StackAllocationOperator( Debugging.DebugInfo debugInfo ) : base( debugInfo, cCapabilities, OperatorLevel.ConcreteTypes ) // Stack overflow is possible. { } //--// public static StackAllocationOperator New( Debugging.DebugInfo debugInfo , VariableExpression lhs , Expression rhs ) { StackAllocationOperator res = new StackAllocationOperator( debugInfo ); res.SetLhs( lhs ); res.SetRhs( rhs ); return res; } //--// // // Helper Methods // public override Operator Clone( CloningContext context ) { return RegisterAndCloneState( context, new StackAllocationOperator( m_debugInfo ) ); } //--// // // Access Methods // //--// // // Debug Methods // public override void InnerToString( System.Text.StringBuilder sb ) { sb.Append( "StackAllocationOperator(" ); base.InnerToString( sb ); sb.Append( ")" ); } public override string FormatOutput( IIntermediateRepresentationDumper dumper ) { return dumper.FormatOutput( "{0} = stack alloc {1}", this.FirstResult, this.FirstArgument ); } } } ================================================ FILE: Zelig/Zelig/CompileTime/CodeGenerator/IntermediateRepresentation/Operators/Memory/StoreElementOperator.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // namespace Microsoft.Zelig.CodeGeneration.IR { using System; using System.Collections.Generic; using Microsoft.Zelig.Runtime.TypeSystem; public sealed class StoreElementOperator : ElementOperator { // // Constructor Methods // private StoreElementOperator( Debugging.DebugInfo debugInfo , OperatorCapabilities capabilities , OperatorLevel level , FieldRepresentation[] accessPath ) : base( debugInfo, capabilities, level, accessPath ) { } //--// public static StoreElementOperator New( Debugging.DebugInfo debugInfo , Expression rhsArray , Expression rhsIndex , Expression rhsVal , FieldRepresentation[] accessPath , bool fNullCheck ) { OperatorLevel level; OperatorCapabilities capabilities = OperatorCapabilities.IsNonCommutative | OperatorCapabilities.MayMutateExistingStorage | // TODO: method analysis could yield a better answer. OperatorCapabilities.DoesNotAllocateStorage | OperatorCapabilities.DoesNotReadExistingMutableStorage | OperatorCapabilities.DoesNotReadThroughPointerOperands | OperatorCapabilities.DoesNotWriteThroughPointerOperands | OperatorCapabilities.DoesNotCapturePointerOperands ; if(fNullCheck) { level = OperatorLevel .ConcreteTypes; capabilities |= OperatorCapabilities.MayThrow; // Out-of-bounds and null pointer checks can throw. } else { level = OperatorLevel .Lowest; capabilities |= OperatorCapabilities.DoesNotThrow; } StoreElementOperator res = new StoreElementOperator( debugInfo, capabilities, level, accessPath ); res.SetRhs( rhsArray, rhsIndex, rhsVal ); return res; } //--// // // Helper Methods // public override Operator Clone( CloningContext context ) { FieldRepresentation[] accessPath = context.ConvertFields( m_accessPath ); return RegisterAndCloneState( context, new StoreElementOperator( m_debugInfo, m_capabilities, m_level, accessPath ) ); } //--// // // Access Methods // //--// // // Debug Methods // public override void InnerToString( System.Text.StringBuilder sb ) { sb.Append( "StoreElementOperator(" ); base.InnerToString( sb ); sb.Append( ")" ); } public override string FormatOutput( IIntermediateRepresentationDumper dumper ) { return dumper.FormatOutput( "{0}[{1}] <= {2}{3}", this.FirstArgument, this.SecondArgument, this.ThirdArgument, this.MayThrow ? " MayThrow" : "" ); } } } ================================================ FILE: Zelig/Zelig/CompileTime/CodeGenerator/IntermediateRepresentation/Operators/Memory/StoreFieldOperator.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // namespace Microsoft.Zelig.CodeGeneration.IR { using System; using System.Collections.Generic; using Microsoft.Zelig.Runtime.TypeSystem; public abstract class StoreFieldOperator : FieldOperator { // // Constructor Methods // protected StoreFieldOperator( Debugging.DebugInfo debugInfo , OperatorCapabilities capabilities , OperatorLevel level , FieldRepresentation field ) : base( debugInfo, capabilities, level, field ) { } //--// // // Helper Methods // //--// // // Access Methods // //--// // // Debug Methods // } } ================================================ FILE: Zelig/Zelig/CompileTime/CodeGenerator/IntermediateRepresentation/Operators/Memory/StoreIndirectOperator.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // namespace Microsoft.Zelig.CodeGeneration.IR { using System; using System.Collections.Generic; using Microsoft.Zelig.Runtime.TypeSystem; public sealed class StoreIndirectOperator : IndirectOperator { // // State // // // Constructor Methods // private StoreIndirectOperator( Debugging.DebugInfo debugInfo , OperatorCapabilities capabilities , OperatorLevel level , TypeRepresentation td , FieldRepresentation[] accessPath , int offset ) : base( debugInfo, capabilities, level, td, accessPath, offset ) { } //--// public static StoreIndirectOperator New( Debugging.DebugInfo debugInfo , TypeRepresentation td , Expression rhsAddr , Expression rhsValue , FieldRepresentation[] accessPath , int offset , bool fNullCheck ) { OperatorLevel level; OperatorCapabilities capabilities = OperatorCapabilities.IsNonCommutative | OperatorCapabilities.MayMutateExistingStorage | // TODO: method analysis could yield a better answer. OperatorCapabilities.DoesNotAllocateStorage | OperatorCapabilities.DoesNotReadExistingMutableStorage | OperatorCapabilities.DoesNotReadThroughPointerOperands | OperatorCapabilities.MayWriteThroughPointerOperands | OperatorCapabilities.MayCapturePointerOperands ; if(fNullCheck) { level = OperatorLevel .ConcreteTypes; capabilities |= OperatorCapabilities.MayThrow; } else { level = OperatorLevel .Lowest; capabilities |= OperatorCapabilities.DoesNotThrow; } StoreIndirectOperator res = new StoreIndirectOperator( debugInfo, capabilities, level, td, accessPath, offset ); res.SetRhs( rhsAddr, rhsValue ); return res; } //--// // // Helper Methods // public override Operator Clone( CloningContext context ) { TypeRepresentation td = context.ConvertType ( m_td ); FieldRepresentation[] accessPath = context.ConvertFields( m_accessPath ); return RegisterAndCloneState( context, new StoreIndirectOperator( m_debugInfo, m_capabilities, m_level, td, accessPath, m_offset ) ); } //--// // // Access Methods // //--// // // Debug Methods // public override void InnerToString( System.Text.StringBuilder sb ) { sb.Append( "StoreIndirectOperator(" ); base.InnerToString( sb ); sb.Append( ")" ); } public override string FormatOutput( IIntermediateRepresentationDumper dumper ) { return dumper.FormatOutput( "[{0},#{2}] <= {1} as {3}{4}", this.FirstArgument, this.SecondArgument, m_offset, m_td, this.MayThrow ? " MayThrow" : "" ); } } } ================================================ FILE: Zelig/Zelig/CompileTime/CodeGenerator/IntermediateRepresentation/Operators/Memory/StoreInstanceFieldOperator.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // namespace Microsoft.Zelig.CodeGeneration.IR { using System; using System.Collections.Generic; using Microsoft.Zelig.Runtime.TypeSystem; public sealed class StoreInstanceFieldOperator : StoreFieldOperator { // // Constructor Methods // private StoreInstanceFieldOperator( Debugging.DebugInfo debugInfo , OperatorCapabilities capabilities , OperatorLevel level , FieldRepresentation field ) : base( debugInfo, capabilities, level, field ) { } //--// public static StoreInstanceFieldOperator New( Debugging.DebugInfo debugInfo , FieldRepresentation field , Expression rhsObj , Expression rhsVal , bool fNullCheck ) { OperatorLevel level; OperatorCapabilities capabilities = OperatorCapabilities.IsNonCommutative | OperatorCapabilities.MayMutateExistingStorage | OperatorCapabilities.DoesNotAllocateStorage | OperatorCapabilities.DoesNotReadExistingMutableStorage | OperatorCapabilities.DoesNotReadThroughPointerOperands ; if(rhsObj.Type is PointerTypeRepresentation || rhsObj.Type is BoxedValueTypeRepresentation ) { capabilities |= OperatorCapabilities.MayWriteThroughPointerOperands | OperatorCapabilities.MayCapturePointerOperands ; } else { capabilities |= OperatorCapabilities.DoesNotWriteThroughPointerOperands | OperatorCapabilities.DoesNotCapturePointerOperands ; } if(fNullCheck) { level = OperatorLevel .ConcreteTypes; capabilities |= OperatorCapabilities.MayThrow; } else { level = OperatorLevel .ConcreteTypes_NoExceptions; capabilities |= OperatorCapabilities.DoesNotThrow; } StoreInstanceFieldOperator res = new StoreInstanceFieldOperator( debugInfo, capabilities, level, field ); res.SetRhs( rhsObj, rhsVal ); return res; } //--// // // Helper Methods // public override Operator Clone( CloningContext context ) { FieldRepresentation fd = context.ConvertField( this.Field ); return RegisterAndCloneState( context, new StoreInstanceFieldOperator( m_debugInfo, m_capabilities, m_level, fd ) ); } // // Access Methods // //--// // // Debug Methods // public override void InnerToString( System.Text.StringBuilder sb ) { sb.Append( "StoreInstanceFieldOperator(" ); base.InnerToString( sb ); sb.Append( ")" ); } public override string FormatOutput( IIntermediateRepresentationDumper dumper ) { return dumper.FormatOutput( "[{0}, {1}] <= {2}{3}", this.FirstArgument, this.Field, this.SecondArgument, this.MayThrow ? " MayThrow" : "" ); } } } ================================================ FILE: Zelig/Zelig/CompileTime/CodeGenerator/IntermediateRepresentation/Operators/Memory/StoreStaticFieldOperator.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // namespace Microsoft.Zelig.CodeGeneration.IR { using System; using System.Collections.Generic; using Microsoft.Zelig.Runtime.TypeSystem; public sealed class StoreStaticFieldOperator : StoreFieldOperator { private const OperatorCapabilities cCapabilities = OperatorCapabilities.IsNonCommutative | OperatorCapabilities.MayMutateExistingStorage | // TODO: Are static fields part of the heap? OperatorCapabilities.DoesNotAllocateStorage | OperatorCapabilities.DoesNotReadExistingMutableStorage | OperatorCapabilities.DoesNotThrow | OperatorCapabilities.DoesNotReadThroughPointerOperands | OperatorCapabilities.DoesNotWriteThroughPointerOperands | OperatorCapabilities.DoesNotCapturePointerOperands ; // // Constructor Methods // private StoreStaticFieldOperator( Debugging.DebugInfo debugInfo , FieldRepresentation field ) : base( debugInfo, cCapabilities, OperatorLevel.FullyObjectOriented, field ) { } //--// public static StoreStaticFieldOperator New( Debugging.DebugInfo debugInfo , FieldRepresentation field , Expression val ) { StoreStaticFieldOperator res = new StoreStaticFieldOperator( debugInfo, field ); res.SetRhs( val ); return res; } //--// // // Helper Methods // public override Operator Clone( CloningContext context ) { FieldRepresentation fd = context.ConvertField( this.Field ); return RegisterAndCloneState( context, new StoreStaticFieldOperator( m_debugInfo, fd ) ); } // // Access Methods // //--// // // Debug Methods // public override void InnerToString( System.Text.StringBuilder sb ) { sb.Append( "StoreStaticFieldOperator(" ); base.InnerToString( sb ); sb.Append( ")" ); } public override string FormatOutput( IIntermediateRepresentationDumper dumper ) { return dumper.FormatOutput( "[{0}] <= {1}", this.Field, this.FirstArgument ); } } } ================================================ FILE: Zelig/Zelig/CompileTime/CodeGenerator/IntermediateRepresentation/Operators/NopOperator.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // namespace Microsoft.Zelig.CodeGeneration.IR { using System; using System.Collections.Generic; using Microsoft.Zelig.Runtime.TypeSystem; public sealed class NopOperator : Operator { private const OperatorCapabilities cCapabilities = OperatorCapabilities.IsNonCommutative | OperatorCapabilities.DoesNotMutateExistingStorage | OperatorCapabilities.DoesNotAllocateStorage | OperatorCapabilities.DoesNotReadExistingMutableStorage | OperatorCapabilities.DoesNotThrow | OperatorCapabilities.DoesNotReadThroughPointerOperands | OperatorCapabilities.DoesNotWriteThroughPointerOperands | OperatorCapabilities.DoesNotCapturePointerOperands ; // // Constructor Methods // private NopOperator( Debugging.DebugInfo debugInfo ) : base( debugInfo, cCapabilities, OperatorLevel.Lowest ) { } //--// public static NopOperator New( Debugging.DebugInfo debugInfo ) { NopOperator res = new NopOperator( debugInfo ); return res; } //--// // // Helper Methods // public override Operator Clone( CloningContext context ) { return RegisterAndCloneState( context, new NopOperator( m_debugInfo ) ); } //--// // // Access Methods // public override bool PerformsNoActions { get { return m_debugInfo == null; } } //--// // // Debug Methods // public override void InnerToString( System.Text.StringBuilder sb ) { sb.Append( "NopOperator(" ); base.InnerToString( sb ); sb.Append( ")" ); } public override string FormatOutput( IIntermediateRepresentationDumper dumper ) { return dumper.FormatOutput( "nop" ); } } } ================================================ FILE: Zelig/Zelig/CompileTime/CodeGenerator/IntermediateRepresentation/Operators/Object/ArrayAllocationOperator.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // namespace Microsoft.Zelig.CodeGeneration.IR { using System; using System.Collections.Generic; using Microsoft.Zelig.Runtime.TypeSystem; public sealed class ArrayAllocationOperator : Operator { private const OperatorCapabilities cCapabilities = OperatorCapabilities.IsNonCommutative | OperatorCapabilities.DoesNotMutateExistingStorage | OperatorCapabilities.MayAllocateStorage | OperatorCapabilities.DoesNotReadExistingMutableStorage | OperatorCapabilities.MayThrow | // Out of memory. OperatorCapabilities.DoesNotReadThroughPointerOperands | OperatorCapabilities.DoesNotWriteThroughPointerOperands | OperatorCapabilities.DoesNotCapturePointerOperands ; // // State // private TypeRepresentation m_td; // // Constructor Methods // private ArrayAllocationOperator( Debugging.DebugInfo debugInfo , TypeRepresentation td ) : base( debugInfo, cCapabilities, OperatorLevel.FullyObjectOriented ) { m_td = td; } //--// public static ArrayAllocationOperator New( Debugging.DebugInfo debugInfo , TypeRepresentation td , VariableExpression lhs , Expression rhs ) { ArrayAllocationOperator res = new ArrayAllocationOperator( debugInfo, td ); res.SetLhs( lhs ); res.SetRhs( rhs ); return res; } //--// // // Helper Methods // public override Operator Clone( CloningContext context ) { TypeRepresentation td = context.ConvertType( m_td ); return RegisterAndCloneState( context, new ArrayAllocationOperator( m_debugInfo, td ) ); } //--// public override void ApplyTransformation( TransformationContextForIR context ) { context.Push( this ); base.ApplyTransformation( context ); context.Transform( ref m_td ); context.Pop(); } //--// // // Access Methods // public TypeRepresentation Type { get { return m_td; } } //--// // // Debug Methods // public override void InnerToString( System.Text.StringBuilder sb ) { sb.Append( "ArrayAllocationOperator(" ); base.InnerToString( sb ); sb.AppendFormat( " {0}", m_td ); sb.Append( ")" ); } public override string FormatOutput( IIntermediateRepresentationDumper dumper ) { return dumper.FormatOutput( "{0} = new array {1}[{2}]", this.FirstResult, m_td, this.FirstArgument ); } } } ================================================ FILE: Zelig/Zelig/CompileTime/CodeGenerator/IntermediateRepresentation/Operators/Object/ArrayLengthOperator.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // namespace Microsoft.Zelig.CodeGeneration.IR { using System; using System.Collections.Generic; using Microsoft.Zelig.Runtime.TypeSystem; public sealed class ArrayLengthOperator : Operator { private const OperatorCapabilities cCapabilities = OperatorCapabilities.IsNonCommutative | OperatorCapabilities.DoesNotMutateExistingStorage | OperatorCapabilities.DoesNotAllocateStorage | OperatorCapabilities.DoesNotReadExistingMutableStorage | // The size of an array cannot change. OperatorCapabilities.MayThrow | // Null pointer check can throw. OperatorCapabilities.DoesNotReadThroughPointerOperands | OperatorCapabilities.DoesNotWriteThroughPointerOperands | OperatorCapabilities.DoesNotCapturePointerOperands ; // // Constructor Methods // private ArrayLengthOperator( Debugging.DebugInfo debugInfo ) : base( debugInfo, cCapabilities, OperatorLevel.FullyObjectOriented ) { } //--// public static ArrayLengthOperator New( Debugging.DebugInfo debugInfo , VariableExpression lhs , Expression rhs ) { ArrayLengthOperator res = new ArrayLengthOperator( debugInfo ); res.SetLhs( lhs ); res.SetRhs( rhs ); return res; } //--// // // Helper Methods // public override Operator Clone( CloningContext context ) { return RegisterAndCloneState( context, new ArrayLengthOperator( m_debugInfo ) ); } //--// // // Access Methods // //--// // // Debug Methods // public override void InnerToString( System.Text.StringBuilder sb ) { sb.Append( "ArrayLengthOperator(" ); base.InnerToString( sb ); sb.Append( ")" ); } public override string FormatOutput( IIntermediateRepresentationDumper dumper ) { return dumper.FormatOutput( "{0} <= length of {1}{2}", this.FirstResult, this.FirstArgument, this.MayThrow ? " MayThrow" : "" ); } } } ================================================ FILE: Zelig/Zelig/CompileTime/CodeGenerator/IntermediateRepresentation/Operators/Object/BoxOperator.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // namespace Microsoft.Zelig.CodeGeneration.IR { using System; using System.Collections.Generic; using Microsoft.Zelig.Runtime.TypeSystem; public sealed class BoxOperator : Operator { private const OperatorCapabilities cCapabilities = OperatorCapabilities.IsNonCommutative | OperatorCapabilities.DoesNotMutateExistingStorage | OperatorCapabilities.MayAllocateStorage | OperatorCapabilities.MayReadExistingMutableStorage | // TODO: method analysis could yield better answer. OperatorCapabilities.MayThrow | // Out of memory. OperatorCapabilities.DoesNotReadThroughPointerOperands | OperatorCapabilities.DoesNotWriteThroughPointerOperands | OperatorCapabilities.DoesNotCapturePointerOperands ; // // State // private TypeRepresentation m_td; // // Constructor Methods // private BoxOperator( Debugging.DebugInfo debugInfo , TypeRepresentation td ) : base( debugInfo, cCapabilities, OperatorLevel.FullyObjectOriented ) { m_td = td; } //--// public static BoxOperator New( Debugging.DebugInfo debugInfo , TypeRepresentation td , VariableExpression lhs , Expression rhs ) { BoxOperator res = new BoxOperator( debugInfo, td ); res.SetLhs( lhs ); res.SetRhs( rhs ); return res; } //--// // // Helper Methods // public override Operator Clone( CloningContext context ) { return RegisterAndCloneState( context, new BoxOperator( m_debugInfo, m_td ) ); } //--// public override void ApplyTransformation( TransformationContextForIR context ) { context.Push( this ); base.ApplyTransformation( context ); context.Transform( ref m_td ); context.Pop(); } // // Access Methods // public TypeRepresentation Type { get { return m_td; } } //--// // // Debug Methods // public override void InnerToString( System.Text.StringBuilder sb ) { sb.Append( "BoxOperator(" ); base.InnerToString( sb ); sb.AppendFormat( " Class: {0}", m_td ); sb.Append( ")" ); } public override string FormatOutput( IIntermediateRepresentationDumper dumper ) { return dumper.FormatOutput( "{0} = box {1} as {2}", this.FirstResult, this.FirstArgument, m_td ); } } } ================================================ FILE: Zelig/Zelig/CompileTime/CodeGenerator/IntermediateRepresentation/Operators/Object/CastOperator.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // namespace Microsoft.Zelig.CodeGeneration.IR { using System; using System.Collections.Generic; using Microsoft.Zelig.Runtime.TypeSystem; public sealed class CastOperator : Operator { private const OperatorCapabilities cCapabilities = OperatorCapabilities.IsNonCommutative | OperatorCapabilities.DoesNotMutateExistingStorage | OperatorCapabilities.DoesNotAllocateStorage | OperatorCapabilities.DoesNotReadExistingMutableStorage | OperatorCapabilities.MayThrow | OperatorCapabilities.DoesNotReadThroughPointerOperands | OperatorCapabilities.DoesNotWriteThroughPointerOperands | OperatorCapabilities.DoesNotCapturePointerOperands ; // // State // private TypeRepresentation m_td; // // Constructor Methods // private CastOperator( Debugging.DebugInfo debugInfo , TypeRepresentation td ) : base( debugInfo, cCapabilities, OperatorLevel.FullyObjectOriented ) { m_td = td; } //--// public static CastOperator New( Debugging.DebugInfo debugInfo , TypeRepresentation td , VariableExpression lhs , Expression rhs ) { CastOperator res = new CastOperator( debugInfo, td ); res.SetLhs( lhs ); res.SetRhs( rhs ); return res; } //--// // // Helper Methods // public override Operator Clone( CloningContext context ) { TypeRepresentation td = context.ConvertType( m_td ); return RegisterAndCloneState( context, new CastOperator( m_debugInfo, td ) ); } //--// public override void ApplyTransformation( TransformationContextForIR context ) { context.Push( this ); base.ApplyTransformation( context ); context.Transform( ref m_td ); context.Pop(); } //--// // // Access Methods // public TypeRepresentation Type { get { return m_td; } } //--// // // Debug Methods // public override void InnerToString( System.Text.StringBuilder sb ) { sb.Append( "CastOperator(" ); base.InnerToString( sb ); sb.AppendFormat( " Class: {0}", m_td ); sb.Append( ")" ); } public override string FormatOutput( IIntermediateRepresentationDumper dumper ) { return dumper.FormatOutput( "{0} = {1} cast as {2}", this.FirstResult, this.FirstArgument, m_td ); } } } ================================================ FILE: Zelig/Zelig/CompileTime/CodeGenerator/IntermediateRepresentation/Operators/Object/IsInstanceOperator.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // namespace Microsoft.Zelig.CodeGeneration.IR { using System; using System.Collections.Generic; using Microsoft.Zelig.Runtime.TypeSystem; public sealed class IsInstanceOperator : Operator { private const OperatorCapabilities cCapabilities = OperatorCapabilities.IsNonCommutative | OperatorCapabilities.DoesNotMutateExistingStorage | OperatorCapabilities.DoesNotAllocateStorage | OperatorCapabilities.DoesNotReadExistingMutableStorage | OperatorCapabilities.DoesNotThrow | OperatorCapabilities.DoesNotReadThroughPointerOperands | OperatorCapabilities.DoesNotWriteThroughPointerOperands | OperatorCapabilities.DoesNotCapturePointerOperands ; // // State // private TypeRepresentation m_td; // // Constructor Methods // private IsInstanceOperator( Debugging.DebugInfo debugInfo , TypeRepresentation td ) : base( debugInfo, cCapabilities, OperatorLevel.FullyObjectOriented ) { m_td = td; } //--// public static IsInstanceOperator New( Debugging.DebugInfo debugInfo , TypeRepresentation td , VariableExpression lhs , Expression rhs ) { IsInstanceOperator res = new IsInstanceOperator( debugInfo, td ); res.SetLhs( lhs ); res.SetRhs( rhs ); return res; } //--// // // Helper Methods // public override Operator Clone( CloningContext context ) { TypeRepresentation td = context.ConvertType( m_td ); return RegisterAndCloneState( context, new IsInstanceOperator( m_debugInfo, td ) ); } //--// public override void ApplyTransformation( TransformationContextForIR context ) { context.Push( this ); base.ApplyTransformation( context ); context.Transform( ref m_td ); context.Pop(); } //--// // // Access Methods // public TypeRepresentation Type { get { return m_td; } } //--// // // Debug Methods // public override void InnerToString( System.Text.StringBuilder sb ) { sb.Append( "IsInstanceOperator(" ); base.InnerToString( sb ); sb.AppendFormat( " Class: {0}", m_td ); sb.Append( ")" ); } public override string FormatOutput( IIntermediateRepresentationDumper dumper ) { return dumper.FormatOutput( "{0} = {1} isinst {2}", this.FirstResult, this.FirstArgument, m_td ); } } } ================================================ FILE: Zelig/Zelig/CompileTime/CodeGenerator/IntermediateRepresentation/Operators/Object/MethodRepresentationOperator.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // namespace Microsoft.Zelig.CodeGeneration.IR { using System; using System.Collections.Generic; using Microsoft.Zelig.Runtime.TypeSystem; public sealed class MethodRepresentationOperator : Operator { // // State // private MethodRepresentation m_md; // // Constructor Methods // private MethodRepresentationOperator( Debugging.DebugInfo debugInfo , OperatorCapabilities capabilities , OperatorLevel level , MethodRepresentation md ) : base( debugInfo, capabilities, level ) { m_md = md; } //--// public static MethodRepresentationOperator New( Debugging.DebugInfo debugInfo , MethodRepresentation md , VariableExpression lhs ) { OperatorCapabilities capabilities = OperatorCapabilities.IsNonCommutative | OperatorCapabilities.DoesNotMutateExistingStorage | OperatorCapabilities.DoesNotAllocateStorage | OperatorCapabilities.DoesNotReadExistingMutableStorage | OperatorCapabilities.DoesNotThrow | OperatorCapabilities.DoesNotReadThroughPointerOperands | OperatorCapabilities.DoesNotWriteThroughPointerOperands | OperatorCapabilities.DoesNotCapturePointerOperands ; MethodRepresentationOperator res = new MethodRepresentationOperator( debugInfo, capabilities, OperatorLevel.Lowest, md ); res.SetLhs( lhs ); return res; } public static MethodRepresentationOperator New( Debugging.DebugInfo debugInfo , MethodRepresentation md , VariableExpression lhs , Expression rhsObject ) { OperatorCapabilities capabilities = OperatorCapabilities.IsNonCommutative | OperatorCapabilities.DoesNotMutateExistingStorage | OperatorCapabilities.DoesNotAllocateStorage | OperatorCapabilities.DoesNotReadExistingMutableStorage | OperatorCapabilities.MayThrow | OperatorCapabilities.DoesNotReadThroughPointerOperands | OperatorCapabilities.DoesNotWriteThroughPointerOperands | OperatorCapabilities.DoesNotCapturePointerOperands ; MethodRepresentationOperator res = new MethodRepresentationOperator( debugInfo, capabilities, OperatorLevel.ConcreteTypes, md ); // 'rhsObject' may be null. res.SetLhs( lhs ); res.SetRhs( rhsObject ); return res; } //--// // // Helper Methods // public override Operator Clone( CloningContext context ) { MethodRepresentation md = context.ConvertMethod( m_md ); return RegisterAndCloneState( context, new MethodRepresentationOperator( m_debugInfo, m_capabilities, m_level, md ) ); } //--// public override void ApplyTransformation( TransformationContextForIR context ) { context.Push( this ); base.ApplyTransformation( context ); context.Transform( ref m_md ); context.Pop(); } //--// // // Access Methods // public MethodRepresentation Method { get { return m_md; } } //--// // // Debug Methods // public override void InnerToString( System.Text.StringBuilder sb ) { sb.Append( "MethodRepresentationOperator(" ); base.InnerToString( sb ); sb.AppendFormat( " {0}", m_md ); sb.Append( ")" ); } public override string FormatOutput( IIntermediateRepresentationDumper dumper ) { if(this.Arguments.Length == 0) { return dumper.FormatOutput( "{0} = descriptor for static method {1}", this.FirstResult, m_md ); } else { return dumper.FormatOutput( "{0} = descriptor for method {1} on {2}", this.FirstResult, m_md, this.FirstArgument ); } } } } ================================================ FILE: Zelig/Zelig/CompileTime/CodeGenerator/IntermediateRepresentation/Operators/Object/ObjectAllocationOperator.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // namespace Microsoft.Zelig.CodeGeneration.IR { using System; using System.Collections.Generic; using Microsoft.Zelig.Runtime.TypeSystem; public sealed class ObjectAllocationOperator : Operator { private const OperatorCapabilities cCapabilities = OperatorCapabilities.IsNonCommutative | OperatorCapabilities.DoesNotMutateExistingStorage | OperatorCapabilities.MayAllocateStorage | OperatorCapabilities.DoesNotReadExistingMutableStorage | OperatorCapabilities.MayThrow | // Out of memory. OperatorCapabilities.DoesNotReadThroughPointerOperands | OperatorCapabilities.DoesNotWriteThroughPointerOperands | OperatorCapabilities.DoesNotCapturePointerOperands ; // // State // private TypeRepresentation m_td; private MethodRepresentation m_md; // // Constructor Methods // private ObjectAllocationOperator( Debugging.DebugInfo debugInfo , TypeRepresentation td , MethodRepresentation md ) : base( debugInfo, cCapabilities, OperatorLevel.FullyObjectOriented ) { m_td = td; m_md = md; } //--// public static ObjectAllocationOperator New( Debugging.DebugInfo debugInfo , TypeRepresentation td , VariableExpression lhs ) { ObjectAllocationOperator res = new ObjectAllocationOperator( debugInfo, td, null ); res.SetLhs( lhs ); return res; } public static ObjectAllocationOperator New( Debugging.DebugInfo debugInfo , MethodRepresentation md , VariableExpression lhs , Expression[] rhs ) { ObjectAllocationOperator res = new ObjectAllocationOperator( debugInfo, md.OwnerType, md ); res.SetLhs ( lhs ); res.SetRhsArray( rhs ); return res; } //--// // // Helper Methods // public override Operator Clone( CloningContext context ) { TypeRepresentation td = context.ConvertType ( m_td ); MethodRepresentation md = context.ConvertMethod( m_md ); return RegisterAndCloneState( context, new ObjectAllocationOperator( m_debugInfo, td, md ) ); } //--// public override void ApplyTransformation( TransformationContextForIR context ) { context.Push( this ); base.ApplyTransformation( context ); context.Transform( ref m_td ); context.Transform( ref m_md ); context.Pop(); } //--// // // Access Methods // public TypeRepresentation Type { get { return m_td; } } public MethodRepresentation Method { get { return m_md; } } //--// // // Debug Methods // public override void InnerToString( System.Text.StringBuilder sb ) { sb.Append( "ObjectAllocationOperator(" ); base.InnerToString( sb ); sb.AppendFormat( " {0}", m_td ); if(m_md != null) { sb.AppendFormat( " - {0}", m_md ); } sb.Append( ")" ); } public override string FormatOutput( IIntermediateRepresentationDumper dumper ) { return dumper.FormatOutput( "{0} = new {1}", this.FirstResult, m_td ); } } } ================================================ FILE: Zelig/Zelig/CompileTime/CodeGenerator/IntermediateRepresentation/Operators/Object/UnboxOperator.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // namespace Microsoft.Zelig.CodeGeneration.IR { using System; using System.Collections.Generic; using Microsoft.Zelig.Runtime.TypeSystem; public sealed class UnboxOperator : Operator { private const OperatorCapabilities cCapabilities = OperatorCapabilities.IsNonCommutative | OperatorCapabilities.DoesNotMutateExistingStorage | OperatorCapabilities.DoesNotAllocateStorage | OperatorCapabilities.DoesNotReadExistingMutableStorage | OperatorCapabilities.MayThrow | OperatorCapabilities.DoesNotReadThroughPointerOperands | OperatorCapabilities.DoesNotWriteThroughPointerOperands | OperatorCapabilities.DoesNotCapturePointerOperands ; // // State // private TypeRepresentation m_td; // // Constructor Methods // private UnboxOperator( Debugging.DebugInfo debugInfo , TypeRepresentation td ) : base( debugInfo, cCapabilities, OperatorLevel.FullyObjectOriented ) { m_td = td; } //--// public static UnboxOperator New( Debugging.DebugInfo debugInfo , TypeRepresentation td , VariableExpression lhs , Expression rhs ) { // If we are dealing with a boxed type in the R-value, then the underlying type must match. Refernce types are just OK CHECKS.ASSERT( rhs.Type is BoxedValueTypeRepresentation ? lhs.Type is ManagedPointerTypeRepresentation && lhs.Type.ContainedType == rhs.Type.ContainedType : true, "Incompatible types for unbox operator: {0} <=> {1}", lhs.Type, rhs.Type ); UnboxOperator res = new UnboxOperator( debugInfo, td ); res.SetLhs( lhs ); res.SetRhs( rhs ); return res; } //--// // // Helper Methods // public override Operator Clone( CloningContext context ) { return RegisterAndCloneState( context, new UnboxOperator( m_debugInfo, m_td ) ); } //--// public override void ApplyTransformation( TransformationContextForIR context ) { context.Push( this ); base.ApplyTransformation( context ); context.Transform( ref m_td ); context.Pop(); } // // Access Methods // public TypeRepresentation Type { get { return m_td; } } //--// // // Debug Methods // public override void InnerToString( System.Text.StringBuilder sb ) { sb.Append( "UnboxOperator(" ); base.InnerToString( sb ); sb.AppendFormat( " Class: {0}", m_td ); sb.Append( ")" ); } public override string FormatOutput( IIntermediateRepresentationDumper dumper ) { return dumper.FormatOutput( "{0} = unbox {1} as {2}", this.FirstResult, this.FirstArgument, m_td ); } } } ================================================ FILE: Zelig/Zelig/CompileTime/CodeGenerator/IntermediateRepresentation/Operators/Operator.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // #if DEBUG #define TRACK_OPERATOR_IDENTITY #else //#define TRACK_OPERATOR_IDENTITY #endif namespace Microsoft.Zelig.CodeGeneration.IR { using System; using System.Collections.Generic; using Microsoft.Zelig.Runtime.TypeSystem; public abstract class Operator { [Flags] public enum SubstitutionFlags { Default = 0x00000001, CopyAnnotations = 0x00000001, } // // It's important to notice that both the positive and negative cases are explicitly expressed. // // This acts as a sort of parity-checking on the definition of an operator's capabilities, // ensuring that whenever a new capability or a new operator is added, all the bases are covered. // [Flags] public enum OperatorCapabilities { IsCommutative = 0x00000001, IsNonCommutative = 0x00000002, MayMutateExistingStorage = 0x00000004, DoesNotMutateExistingStorage = 0x00000008, MayAllocateStorage = 0x00000010, DoesNotAllocateStorage = 0x00000020, MayReadExistingMutableStorage = 0x00000040, DoesNotReadExistingMutableStorage = 0x00000080, MayThrow = 0x00000100, DoesNotThrow = 0x00000200, MayReadThroughPointerOperands = 0x00000400, DoesNotReadThroughPointerOperands = 0x00000800, MayWriteThroughPointerOperands = 0x00001000, DoesNotWriteThroughPointerOperands = 0x00002000, MayCapturePointerOperands = 0x00004000, DoesNotCapturePointerOperands = 0x00008000, IsMetaOperator = 0x00010000, MutuallyExclusive = IsCommutative | MayMutateExistingStorage | MayAllocateStorage | MayReadExistingMutableStorage | MayThrow | MayReadThroughPointerOperands | MayWriteThroughPointerOperands | MayCapturePointerOperands , } public enum OperatorLevel { Registers , // Instead of using Variables, use only Registers. StackLocations , // Instead of using Variables, use only Registers and StackLocations. ScalarValues , // All the variables have been split into word-sized fragments that could fit in a machine register. ConcreteTypes_NoExceptions, // All implicit exception checks are converted into explict ones. ConcreteTypes , // Nothing but types and concrete (non-virtual) method calls. ObjectOriented , // Static fields, allocations, casts have been removed. FullyObjectOriented , // Everything coming directly from byte code. Lowest = Registers , Highest = FullyObjectOriented, } public interface IOperatorLevelHelper { bool FitsInPhysicalRegister( TypeRepresentation td ); } //--// public static readonly Operator[] SharedEmptyArray = new Operator[0]; public static readonly Operator[][] SharedEmptyArrayArray = new Operator[0][]; // // State // #if TRACK_OPERATOR_IDENTITY protected static int s_identity; #endif public int m_identity; //--// protected Debugging.DebugInfo m_debugInfo; protected OperatorCapabilities m_capabilities; protected OperatorLevel m_level; protected int m_index; protected BasicBlock m_basicBlock; private VariableExpression[] m_lhs; private Expression[] m_rhs; protected Annotation[] m_annotations; // // Constructor Methods // protected Operator() // Default constructor required by TypeSystemSerializer. { #if TRACK_OPERATOR_IDENTITY m_identity = s_identity++; #endif ClearState(); } protected Operator( Debugging.DebugInfo debugInfo , OperatorCapabilities capabilities , OperatorLevel level ) : this() { if(CHECKS.ENABLED) // Avoid expensive boxing of "capabilities" below. { uint oddMask = (uint)capabilities & (uint)OperatorCapabilities.MutuallyExclusive; uint evenMask = ((uint)capabilities >> 1) & (uint)OperatorCapabilities.MutuallyExclusive; if((oddMask ^ evenMask) != (uint)OperatorCapabilities.MutuallyExclusive || (oddMask & evenMask) != 0x00000 ) { CHECKS.ASSERT( false, "Capabilities are not paired correctly: {0}", capabilities ); } } m_debugInfo = debugInfo; m_capabilities = capabilities; m_level = level; } //--// // // Helper Methods // public abstract Operator Clone( CloningContext context ); protected Operator RegisterAndCloneState( CloningContext context , Operator clone ) { context.Register( this, clone ); CloneState( context, clone ); return clone; } protected virtual void CloneState( CloningContext context , Operator clone ) { clone.m_index = m_index; clone.m_basicBlock = context.Clone( m_basicBlock ); clone.m_lhs = context.Clone( m_lhs ); clone.m_rhs = context.Clone( m_rhs ); clone.m_annotations = context.Clone( m_annotations ); } //--// public OperatorLevel GetLevel( IOperatorLevelHelper helper ) { OperatorLevel level = m_level; OperatorLevel level2; foreach(var ex in m_lhs) { level2 = ex.GetLevel( helper ); if(level < level2) { level = level2; } } foreach(var ex in m_rhs) { level2 = ex.GetLevel( helper ); if(level < level2) { level = level2; } } foreach(var an in m_annotations) { level2 = an.GetLevel( helper ); if(level < level2) { level = level2; } } return level; } protected void SetLhs( VariableExpression lhs ) { SetLhsArray( lhs ); } protected void SetLhs( VariableExpression lhs1 , VariableExpression lhs2 ) { SetLhsArray( lhs1, lhs2 ); } protected void SetLhs( VariableExpression lhs1 , VariableExpression lhs2 , VariableExpression lhs3 ) { SetLhsArray( lhs1, lhs2, lhs3 ); } protected void SetLhsArray( params VariableExpression[] lhs ) { CHECKS.ASSERT( this.IsDetached, "Cannot set LHS after associating operator with basic block." ); m_lhs = lhs; } protected void SetRhs( Expression rhs ) { SetRhsArray( rhs ); } protected void SetRhs( Expression rhs1 , Expression rhs2 ) { SetRhsArray( rhs1, rhs2 ); } protected void SetRhs( Expression rhs1 , Expression rhs2 , Expression rhs3 ) { SetRhsArray( rhs1, rhs2, rhs3 ); } protected void SetRhsArray( params Expression[] rhs ) { CHECKS.ASSERT( this.IsDetached, "Cannot set LHS after associating operator with basic block." ); m_rhs = rhs; } protected void BumpVersion() { m_basicBlock.BumpVersion(); } //--// public virtual void ApplyTransformation( TransformationContextForIR context ) { context.Push( this ); context.Transform( ref m_debugInfo ); context.Transform( ref m_capabilities ); context.Transform( ref m_level ); context.Transform( ref m_basicBlock ); context.Transform( ref m_lhs ); context.Transform( ref m_rhs ); context.Transform( ref m_annotations ); context.Pop(); } internal void Retarget( BasicBlock owner ) { m_basicBlock = owner; } public virtual void NotifyMerge( BasicBlock entryBB , BasicBlock exitBB ) { } public virtual void NotifyNewPredecessor( BasicBlock oldBB , BasicBlock newBB ) { } //--// public bool AddAnnotation( Annotation an ) { if(ArrayUtility.FindInNotNullArray( m_annotations, an ) >= 0) { return false; } if(this.IsDetached == false) { BumpVersion(); } m_annotations = ArrayUtility.AppendToNotNullArray( m_annotations, an ); return true; } public void RemoveAnnotation( Annotation an ) { if(this.IsDetached == false) { BumpVersion(); } m_annotations = ArrayUtility.RemoveUniqueFromNotNullArray( m_annotations, an ); } public void CopyAnnotations( Operator op ) { foreach(Annotation an in op.Annotations) { AddAnnotation( an ); } } public bool HasAnnotation< T >() where T : Annotation { return GetAnnotation< T >() != null; } public T GetAnnotation< T >() where T : Annotation { foreach(Annotation an in m_annotations) { T res = an as T; if(res != null) { return res; } } return null; } public AnnotationEnumeratorProvider< T > FilterAnnotations() where T : Annotation { return new AnnotationEnumeratorProvider< T >( m_annotations ); } public struct AnnotationEnumeratorProvider< T > where T : Annotation { // // State // private readonly Annotation[] m_values; // // Constructor Methods // internal AnnotationEnumeratorProvider( Annotation[] values ) { m_values = values; } // // Helper Methods // public AnnotationEnumerator< T > GetEnumerator() { return new AnnotationEnumerator< T >( m_values ); } } public struct AnnotationEnumerator< T > where T : Annotation { // // State // private readonly Annotation[] m_values; private T m_current; private int m_index; // // Constructor Methods // internal AnnotationEnumerator( Annotation[] values ) { m_values = values; m_current = null; m_index = 0; } // // Helper Methods // public void Dispose() { } public bool MoveNext() { while(m_index < m_values.Length) { m_current = m_values[m_index++] as T; if(m_current != null) { return true; } } return false; } public T Current { get { return m_current; } } } //--// public void AddOperatorBefore( Operator op ) { m_basicBlock.AddOperatorBefore( op, this ); } public void AddOperatorAfter( Operator op ) { m_basicBlock.AddOperatorAfter( this, op ); } //--// public void SubstituteWithOperator( Operator op , SubstitutionFlags flags ) { m_basicBlock.SubstituteOperator( this, op, flags ); } //--// public BasicBlock SubstituteWithSubGraph( BasicBlock entry , BasicBlock exit ) { CHECKS.ASSERT( entry.Annotation == BasicBlock.Qualifier.Normal, "Entry must be a normal basic block" ); CHECKS.ASSERT( exit == null || exit .Annotation == BasicBlock.Qualifier.Normal, "Exit must be a normal basic block" ); BasicBlock current = this.BasicBlock; BasicBlock split = current.SplitAtOperator( this, true, true ); // // Redirect flow control to go through the sub graph. // /**************/ current.FlowControl = UnconditionalControlOperator.New( null, entry ); if(exit != null) exit .FlowControl = UnconditionalControlOperator.New( null, split ); return (exit != null) ? split : null; } public void SubstituteAnnotation( InvalidationAnnotation anOld , InvalidationAnnotation anNew ) { CHECKS.ASSERT( anNew != null , "Cannot substitute annotation with null pointer: {0}" , this ); CHECKS.ASSERT( anOld != anNew, "Expecting different annotations for substituition: {0}", this ); var annotations = m_annotations; for(int i = 0; i < annotations.Length; i++) { if(annotations[i] == anOld) { BumpVersion(); if(m_annotations == annotations) { // // In-place updates are not allowed, we have to guarantee that the values returned by 'Operator.Rhs' don't change. // m_annotations = ArrayUtility.CopyNotNullArray( annotations ); } m_annotations[i] = anNew; } } } public void SubstituteDefinition( VariableExpression exOld , VariableExpression exNew ) { CHECKS.ASSERT( exNew != null , "Cannot substitute definition with null pointer: {0}" , this ); CHECKS.ASSERT( exOld != exNew, "Expecting different expressions for substituition: {0}", this ); var lhs = m_lhs; for(int i = 0; i < lhs.Length; i++) { if(lhs[i] == exOld) { BumpVersion(); if(m_lhs == lhs) { // // In-place updates are not allowed, we have to guarantee that the values returned by 'Operator.Rhs' don't change. // m_lhs = ArrayUtility.CopyNotNullArray( lhs ); } m_lhs[i] = exNew; } } } public void SubstituteUsage( Expression exOld , Expression exNew ) { CHECKS.ASSERT( exNew != null , "Cannot substitute usage with null pointer: {0}" , this ); CHECKS.ASSERT( exOld != exNew, "Expecting different expressions for substituition: {0}", this ); Expression[] rhs = m_rhs; for(int i = 0; i < rhs.Length; i++) { if(rhs[i] == exOld) { BumpVersion(); if(m_rhs == rhs) { // // In-place updates are not allowed, we have to guarantee that the values returned by 'Operator.Rhs' don't change. // m_rhs = ArrayUtility.CopyNotNullArray( rhs ); } m_rhs[i] = exNew; } } } public void SubstituteUsage( int index , Expression exNew ) { CHECKS.ASSERT( 0 <= index && index < m_rhs.Length, "Index of usage to substitute is invalid: {0} {1}", index, this ); CHECKS.ASSERT( m_rhs[index] != exNew, "Expecting different expressions for substituition: {0}", this ); BumpVersion(); // // In-place updates are not allowed, we have to guarantee that the values returned by 'Operator.Rhs' don't change. // m_rhs = ArrayUtility.CopyNotNullArray( m_rhs ); m_rhs[index] = exNew; } public bool IsSourceOfExpression( Expression target ) { foreach(var ex in m_lhs) { if(ex == target) { return true; } } foreach(var an in m_annotations) { var anInv = an as InvalidationAnnotation; if(anInv != null && anInv.Target == target) { return true; } } return false; } public virtual bool CanPropagateCopy( Expression exOld , Expression exNew ) { return true; } public void MoveBefore( Operator opDst ) { if(m_basicBlock != null) { m_basicBlock.RemoveOperator( this ); } opDst.AddOperatorBefore( this ); } public void Delete() { if(m_basicBlock != null) { m_basicBlock.RemoveOperator( this ); CHECKS.ASSERT( this.IsDetached, "Deleting operator {0} from basic block {1} failed!", this, m_basicBlock ); } ClearState(); } internal void ClearState() { m_index = -1; m_basicBlock = null; m_lhs = VariableExpression.SharedEmptyArray; m_rhs = Expression .SharedEmptyArray; m_annotations = Annotation .SharedEmptyArray; } //--// public int GetBasicBlockIndex() { if(m_basicBlock != null) { return ArrayUtility.FindReferenceInNotNullArray( m_basicBlock.Operators, this ); } return -1; } public Operator GetPreviousOperator() { if(m_basicBlock != null) { Operator[] ops = m_basicBlock.Operators; int pos = ArrayUtility.FindReferenceInNotNullArray( ops, this ); pos -= 1; if(pos >= 0) { return ops[pos]; } } return null; } public Operator GetNextOperator() { if(m_basicBlock != null) { Operator[] ops = m_basicBlock.Operators; int pos = ArrayUtility.FindReferenceInNotNullArray( ops, this ); pos += 1; if(pos < ops.Length) { return ops[pos]; } } return null; } //--// public bool SameDebugInfo( Operator op ) { if(op != null) { return this.m_debugInfo == op.m_debugInfo; } return false; } //--// protected static ConstantExpression FindConstantOrigin( Expression ex , Operator[][] defChains , Operator[][] useChains , VariableExpression.Property[] properties ) { BitVector visited = null; while(true) { var res = ex as ConstantExpression; if(res != null) { return res; } if((properties[ex.SpanningTreeIndex] & VariableExpression.Property.AddressTaken) == 0) { Operator singleDef = ControlFlowGraphState.CheckSingleDefinition( defChains, (VariableExpression)ex ); if(singleDef != null) { if(singleDef is AbstractAssignmentOperator && singleDef.Arguments.Length == 1) { if(visited == null) { visited = new BitVector(); } if(visited.Set( singleDef.SpanningTreeIndex ) == false) { // // Detected loop. // return null; } ex = singleDef.FirstArgument; continue; } } } return null; } } public virtual bool Simplify( Operator[][] defChains , Operator[][] useChains , VariableExpression.Property[] properties ) { if(this.Results.Length == 1) { ConstantExpression exConst = this.CanEvaluate( defChains, useChains, properties ); if(exConst != null) { var opNew = SingleAssignmentOperator.New( this.DebugInfo, this.FirstResult, exConst ); this.SubstituteWithOperator( opNew, Operator.SubstitutionFlags.CopyAnnotations ); return true; } } return false; } public virtual ConstantExpression CanEvaluate( Operator[][] defChains , Operator[][] useChains , VariableExpression.Property[] properties ) { return null; } public void EnsureConstantToTheRight() { if(this.IsCommutative) { Expression[] rhs = m_rhs; if(rhs.Length == 2) { Expression left = rhs[0]; Expression right = rhs[1]; if( (left is ConstantExpression) && !(right is ConstantExpression) ) { m_rhs = new Expression[2]; m_rhs[0] = right; m_rhs[1] = left; } } } } public Expression IsBinaryOperationAgainstConstant( out ConstantExpression exConst , out bool fConstOnRight ) { Expression[] rhs = m_rhs; if(rhs.Length == 2) { Expression left = rhs[0]; Expression right = rhs[1]; ConstantExpression ex; ex = left as ConstantExpression; if(ex != null) { exConst = ex; fConstOnRight = false; return right; } ex = right as ConstantExpression; if(ex != null) { exConst = ex; fConstOnRight = true; return left; } } exConst = null; fConstOnRight = false; return null; } public Expression IsBinaryOperationAgainstZeroValue( out bool fNullOnRight ) { Expression[] rhs = m_rhs; if(rhs.Length == 2) { if(rhs[0].IsEqualToZero()) { fNullOnRight = false; return rhs[1]; } if(rhs[1].IsEqualToZero()) { fNullOnRight = true; return rhs[0]; } } fNullOnRight = false; return null; } public bool IsAddOrSubAgainstConstant( out VariableExpression var , out long constVal ) { var opBin = this as BinaryOperator; if(opBin != null) { ConstantExpression exConst; bool fConstOnRight; var = opBin.IsBinaryOperationAgainstConstant( out exConst, out fConstOnRight ) as VariableExpression; if(var != null) { if(exConst.GetAsSignedInteger( out constVal )) { switch(opBin.Alu) { case AbstractBinaryOperator.ALU.ADD: return true; case AbstractBinaryOperator.ALU.SUB: if(fConstOnRight) { constVal = -constVal; return true; } break; } } } } var = null; constVal = 0; return false; } public bool IsDominatedBy( Operator opTarget , BitVector[] dominance ) { var bbTarget = opTarget.BasicBlock; var bbSource = this .BasicBlock; if(bbSource.IsDominatedBy( bbTarget, dominance )) { if(bbTarget != bbSource) { return true; } return opTarget.SpanningTreeIndex < this.SpanningTreeIndex; } return false; } //--// // // Access Methods // public Debugging.DebugInfo DebugInfo { get { return m_debugInfo; } } public OperatorCapabilities Capabilities { get { return m_capabilities; } } public BasicBlock BasicBlock { get { return m_basicBlock; } internal set { m_basicBlock = value; } } public int SpanningTreeIndex { [System.Diagnostics.DebuggerHidden] get { return m_index; } [System.Diagnostics.DebuggerHidden] set { m_index = value; } } public VariableExpression[] Results { [System.Diagnostics.DebuggerHidden] get { return m_lhs; } } public VariableExpression FirstResult { [System.Diagnostics.DebuggerHidden] get { return m_lhs[0]; } } public VariableExpression SecondResult { [System.Diagnostics.DebuggerHidden] get { return m_lhs[1]; } } public VariableExpression ThirdResult { [System.Diagnostics.DebuggerHidden] get { return m_lhs[2]; } } public Expression[] Arguments { [System.Diagnostics.DebuggerHidden] get { return m_rhs; } [System.Diagnostics.DebuggerHidden] protected set { m_rhs = value; } } public Expression FirstArgument { [System.Diagnostics.DebuggerHidden] get { return m_rhs[0]; } } public Expression SecondArgument { [System.Diagnostics.DebuggerHidden] get { return m_rhs[1]; } } public Expression ThirdArgument { [System.Diagnostics.DebuggerHidden] get { return m_rhs[2]; } } public Expression FourthArgument { [System.Diagnostics.DebuggerHidden] get { return m_rhs[3]; } } public virtual bool ShouldNotBeRemoved { [System.Diagnostics.DebuggerHidden] get { return false; } } public Annotation[] Annotations { [System.Diagnostics.DebuggerHidden] get { return m_annotations; } } public bool IsDetached { [System.Diagnostics.DebuggerHidden] get { return m_basicBlock == null; } } //--// public bool IsCommutative { [System.Diagnostics.DebuggerHidden] get { return (m_capabilities & OperatorCapabilities.IsCommutative) != 0; } } public bool MayMutateExistingStorage { [System.Diagnostics.DebuggerHidden] get { return (m_capabilities & OperatorCapabilities.MayMutateExistingStorage) != 0; } } public bool MayAllocateStorage { [System.Diagnostics.DebuggerHidden] get { return (m_capabilities & OperatorCapabilities.MayAllocateStorage) != 0; } } public bool MayReadExistingMutableStorage { [System.Diagnostics.DebuggerHidden] get { return (m_capabilities & OperatorCapabilities.MayReadExistingMutableStorage) != 0; } } public bool MayThrow { [System.Diagnostics.DebuggerHidden] get { return (m_capabilities & OperatorCapabilities.MayThrow) != 0; } } public bool MayReadThroughPointerOperands { [System.Diagnostics.DebuggerHidden] get { return (m_capabilities & OperatorCapabilities.MayReadThroughPointerOperands) != 0; } } public bool MayWriteThroughPointerOperands { [System.Diagnostics.DebuggerHidden] get { return (m_capabilities & OperatorCapabilities.MayWriteThroughPointerOperands) != 0; } } public bool MayCapturePointerOperands { [System.Diagnostics.DebuggerHidden] get { return (m_capabilities & OperatorCapabilities.MayCapturePointerOperands) != 0; } } public bool IsMetaOperator { [System.Diagnostics.DebuggerHidden] get { return (m_capabilities & OperatorCapabilities.IsMetaOperator) != 0; } } public virtual bool PerformsNoActions { get { return false; } } //--// // // Debug Methods // public override string ToString() { System.Text.StringBuilder sb = new System.Text.StringBuilder(); InnerToString( sb ); return sb.ToString(); } public virtual void InnerToString( System.Text.StringBuilder sb ) { if(m_lhs.Length > 0) { sb.Append( " Res: (" ); for(int i = 0; i < m_lhs.Length; i++) { if(i != 0) sb.Append( ", " ); sb.Append( m_lhs[i] ); } sb.Append( ")" ); } if(m_rhs.Length > 0) { sb.Append( " Arg: (" ); for(int i = 0; i < m_rhs.Length; i++) { if(i != 0) sb.Append( ", " ); sb.Append( m_rhs[i] ); } sb.Append( ")" ); } if(this.MayThrow) { sb.Append( " MayThrow" ); } } public abstract string FormatOutput( IIntermediateRepresentationDumper dumper ); public string ToPrettyString() { return m_basicBlock.Owner.ToPrettyString( this ); } } } ================================================ FILE: Zelig/Zelig/CompileTime/CodeGenerator/IntermediateRepresentation/Operators/PartialAssignmentOperator.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // namespace Microsoft.Zelig.CodeGeneration.IR { using System; using System.Collections.Generic; using Microsoft.Zelig.Runtime.TypeSystem; public sealed class PartialAssignmentOperator : Operator { private const OperatorCapabilities cCapabilities = OperatorCapabilities.IsNonCommutative | OperatorCapabilities.DoesNotMutateExistingStorage | OperatorCapabilities.DoesNotAllocateStorage | OperatorCapabilities.DoesNotReadExistingMutableStorage | OperatorCapabilities.DoesNotThrow | OperatorCapabilities.DoesNotReadThroughPointerOperands | OperatorCapabilities.DoesNotWriteThroughPointerOperands | OperatorCapabilities.DoesNotCapturePointerOperands ; // // State // private uint m_srcOffset; private uint m_dstOffset; // // Constructor Methods // private PartialAssignmentOperator( Debugging.DebugInfo debugInfo , uint srcOffset , uint dstOffset ) : base( debugInfo, cCapabilities, Operator.OperatorLevel.Lowest ) { m_srcOffset = srcOffset; m_dstOffset = dstOffset; } //--// public static PartialAssignmentOperator New( Debugging.DebugInfo debugInfo , VariableExpression lhs , uint dstOffset , Expression rhs , uint srcOffset ) { PartialAssignmentOperator res = new PartialAssignmentOperator( debugInfo, srcOffset, dstOffset ); res.SetLhs( lhs ); res.SetRhs( rhs ); return res; } //--// // // Helper Methods // public override void ApplyTransformation( TransformationContextForIR context ) { context.Push( this ); base.ApplyTransformation( context ); context.Transform( ref m_srcOffset ); context.Transform( ref m_dstOffset ); context.Pop(); } public override Operator Clone( CloningContext context ) { return RegisterAndCloneState( context, new PartialAssignmentOperator( m_debugInfo, m_srcOffset, m_dstOffset ) ); } //--// // // Access Methods // public override bool PerformsNoActions { get { return false; } } //--// // // Access Methods // public uint SourceOffset { get { return m_srcOffset; } } public uint DestinationOffset { get { return m_dstOffset; } } //--// // // Debug Methods // public override void InnerToString( System.Text.StringBuilder sb ) { sb.Append( "PartialAssignmentOperator(" ); base.InnerToString( sb ); sb.AppendFormat( " SourceOffset: {0}" , m_srcOffset ); sb.AppendFormat( " DestinationOffset: {0}", m_dstOffset ); sb.Append( ")" ); } public override string FormatOutput( IIntermediateRepresentationDumper dumper ) { if(this.FirstResult.Type.SizeOfHoldingVariableInWords < this.FirstArgument.Type.SizeOfHoldingVariableInWords) { return dumper.FormatOutput( "{0} = slice {1} at offset {2}", this.FirstResult, this.FirstArgument, m_srcOffset ); } else { return dumper.FormatOutput( "{0} = insert {1} at offset {2}", this.FirstResult, this.FirstArgument, m_dstOffset ); } } } } ================================================ FILE: Zelig/Zelig/CompileTime/CodeGenerator/IntermediateRepresentation/Operators/SignExtendOperator.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // namespace Microsoft.Zelig.CodeGeneration.IR { using System; using System.Collections.Generic; using Microsoft.Zelig.Runtime.TypeSystem; public sealed class SignExtendOperator : ConversionOperator { // // Constructor Methods // private SignExtendOperator( Debugging.DebugInfo debugInfo , OperatorCapabilities capabilities , OperatorLevel level , uint sourceSize , bool fOverflow ) : base( debugInfo, capabilities, level, sourceSize, fOverflow ) { } //--// public static SignExtendOperator New( Debugging.DebugInfo debugInfo , uint sourceSize , bool fOverflow , VariableExpression lhs , Expression rhs ) { OperatorLevel level; OperatorCapabilities capabilities = OperatorCapabilities.IsNonCommutative | OperatorCapabilities.DoesNotMutateExistingStorage | OperatorCapabilities.DoesNotAllocateStorage | OperatorCapabilities.DoesNotReadExistingMutableStorage | OperatorCapabilities.DoesNotReadThroughPointerOperands | OperatorCapabilities.DoesNotWriteThroughPointerOperands | OperatorCapabilities.DoesNotCapturePointerOperands ; if(fOverflow) { capabilities |= OperatorCapabilities.MayThrow; level = OperatorLevel.ConcreteTypes; } else { capabilities |= OperatorCapabilities.DoesNotThrow; level = OperatorLevel.Lowest; } SignExtendOperator res = new SignExtendOperator( debugInfo, capabilities, level, sourceSize, fOverflow ); res.SetLhs( lhs ); res.SetRhs( rhs ); return res; } //--// // // Helper Methods // public override Operator Clone( CloningContext context ) { return RegisterAndCloneState( context, new SignExtendOperator( m_debugInfo, m_capabilities, m_level, this.SignificantSize, this.CheckOverflow ) ); } //--// public override ConstantExpression CanEvaluate( Operator[][] defChains , Operator[][] useChains , VariableExpression.Property[] properties ) { var ex = FindConstantOrigin( this.FirstArgument, defChains, useChains, properties ); if(ex != null) { if(ex.IsValueInteger) { ulong val; if(ex.GetAsRawUlong( out val ) == false) { return null; } int bits = 8 * (int)this.SignificantSize; int shift = 64 - bits; long signedVal = (long)val; signedVal <<= shift; signedVal >>= shift; ulong valModified = (ulong)signedVal; if(this.CheckOverflow) { if(valModified != val) { throw TypeConsistencyErrorException.Create( "Found an overflow: cannot sign extend '{0}' from {1} bits without losing precision", ex, bits ); } } return new ConstantExpression( this.FirstResult.Type, valModified ); } } return null; } // // Debug Methods // public override void InnerToString( System.Text.StringBuilder sb ) { sb.Append( "SignExtend(" ); base.InnerToString( sb ); sb.Append( ")" ); } public override string FormatOutput( IIntermediateRepresentationDumper dumper ) { return dumper.FormatOutput( "{0} = signextend {1} from {2} bits {3}", this.FirstResult, this.FirstArgument, 8 * this.SignificantSize, this.CheckOverflow ? " with overflow check" : "" ); } } } ================================================ FILE: Zelig/Zelig/CompileTime/CodeGenerator/IntermediateRepresentation/Operators/SingleAssignmentOperator.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // namespace Microsoft.Zelig.CodeGeneration.IR { using System; using System.Collections.Generic; using Microsoft.Zelig.Runtime.TypeSystem; public sealed class SingleAssignmentOperator : AbstractAssignmentOperator { // // Constructor Methods // private SingleAssignmentOperator( Debugging.DebugInfo debugInfo ) : base( debugInfo ) { } //--// public static SingleAssignmentOperator New( Debugging.DebugInfo debugInfo , VariableExpression lhs , Expression rhs ) { var res = new SingleAssignmentOperator( debugInfo ); res.SetLhs( lhs ); res.SetRhs( rhs ); return res; } //--// // // Helper Methods // public override Operator Clone( CloningContext context ) { return RegisterAndCloneState( context, new SingleAssignmentOperator( m_debugInfo ) ); } //--// // // Access Methods // public override bool PerformsNoActions { get { return this.FirstResult == this.FirstArgument; // We need a strong identity, because of use/definition chains. } } //--// // // Debug Methods // public override void InnerToString( System.Text.StringBuilder sb ) { sb.Append( "SingleAssignmentOperator(" ); base.InnerToString( sb ); sb.Append( ")" ); } public override string FormatOutput( IIntermediateRepresentationDumper dumper ) { return dumper.FormatOutput( "{0} = {1}", this.FirstResult, this.FirstArgument ); } } } ================================================ FILE: Zelig/Zelig/CompileTime/CodeGenerator/IntermediateRepresentation/Operators/TruncateOperator.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // namespace Microsoft.Zelig.CodeGeneration.IR { using System; using System.Collections.Generic; using Microsoft.Zelig.Runtime.TypeSystem; public sealed class TruncateOperator : ConversionOperator { // // Constructor Methods // private TruncateOperator( Debugging.DebugInfo debugInfo , OperatorCapabilities capabilities , OperatorLevel level , uint destinationSize , bool fOverflow ) : base( debugInfo, capabilities, level, destinationSize, fOverflow ) { } //--// public static TruncateOperator New( Debugging.DebugInfo debugInfo , uint destinationSize , bool fOverflow , VariableExpression lhs , Expression rhs ) { OperatorLevel level; OperatorCapabilities capabilities = OperatorCapabilities.IsNonCommutative | OperatorCapabilities.DoesNotMutateExistingStorage | OperatorCapabilities.DoesNotAllocateStorage | OperatorCapabilities.DoesNotReadExistingMutableStorage | OperatorCapabilities.DoesNotReadThroughPointerOperands | OperatorCapabilities.DoesNotWriteThroughPointerOperands | OperatorCapabilities.DoesNotCapturePointerOperands ; if(fOverflow) { capabilities |= OperatorCapabilities.MayThrow; level = OperatorLevel.ConcreteTypes; } else { capabilities |= OperatorCapabilities.DoesNotThrow; level = OperatorLevel.Lowest; } TruncateOperator res = new TruncateOperator( debugInfo, capabilities, level, destinationSize, fOverflow ); res.SetLhs( lhs ); res.SetRhs( rhs ); return res; } //--// // // Helper Methods // public override Operator Clone( CloningContext context ) { return RegisterAndCloneState( context, new TruncateOperator( m_debugInfo, m_capabilities, m_level, this.SignificantSize, this.CheckOverflow ) ); } //--// public override ConstantExpression CanEvaluate( Operator[][] defChains , Operator[][] useChains , VariableExpression.Property[] properties ) { var ex = FindConstantOrigin( this.FirstArgument, defChains, useChains, properties ); if(ex != null) { if(ex.IsValueInteger) { ulong val; if(ex.GetAsRawUlong( out val ) == false) { return null; } int bits = 8 * (int)this.SignificantSize; ulong valModified = val & ((1ul << bits) - 1ul); if(this.CheckOverflow) { if(valModified != val) { throw TypeConsistencyErrorException.Create( "Found an overflow: cannot truncate '{0}' from {1} bits without losing precision", ex, bits ); } } return new ConstantExpression( this.FirstResult.Type, valModified ); } } return null; } // // Debug Methods // public override void InnerToString( System.Text.StringBuilder sb ) { sb.Append( "Truncate(" ); base.InnerToString( sb ); sb.Append( ")" ); } public override string FormatOutput( IIntermediateRepresentationDumper dumper ) { return dumper.FormatOutput( "{0} = truncate {1} to {2} bits {3}", this.FirstResult, this.FirstArgument, 8 * this.SignificantSize, this.CheckOverflow ? " with overflow check" : "" ); } } } ================================================ FILE: Zelig/Zelig/CompileTime/CodeGenerator/IntermediateRepresentation/Operators/TypedReference/MkRefAnyOperator.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // namespace Microsoft.Zelig.CodeGeneration.IR { using System; using System.Collections.Generic; using Microsoft.Zelig.Runtime.TypeSystem; public sealed class MkRefAnyOperator : Operator { private const OperatorCapabilities cCapabilities = OperatorCapabilities.IsNonCommutative | OperatorCapabilities.DoesNotMutateExistingStorage | OperatorCapabilities.DoesNotAllocateStorage | OperatorCapabilities.DoesNotReadExistingMutableStorage | OperatorCapabilities.DoesNotThrow | OperatorCapabilities.DoesNotReadThroughPointerOperands | OperatorCapabilities.DoesNotWriteThroughPointerOperands | OperatorCapabilities.DoesNotCapturePointerOperands ; // // State // private TypeRepresentation m_td; // // Constructor Methods // private MkRefAnyOperator( Debugging.DebugInfo debugInfo , TypeRepresentation td ) : base( debugInfo, cCapabilities, OperatorLevel.FullyObjectOriented ) { m_td = td; } //--// public static MkRefAnyOperator New( Debugging.DebugInfo debugInfo , TypeRepresentation td , VariableExpression lhs , Expression rhs ) { MkRefAnyOperator res = new MkRefAnyOperator( debugInfo, td ); res.SetLhs( lhs ); res.SetRhs( rhs ); return res; } //--// // // Helper Methods // public override Operator Clone( CloningContext context ) { TypeRepresentation td = context.ConvertType( m_td ); return RegisterAndCloneState( context, new MkRefAnyOperator( m_debugInfo, td ) ); } //--// public override void ApplyTransformation( TransformationContextForIR context ) { context.Push( this ); base.ApplyTransformation( context ); context.Transform( ref m_td ); context.Pop(); } //--// // // Access Methods // public TypeRepresentation Type { get { return m_td; } } //--// // // Debug Methods // public override void InnerToString( System.Text.StringBuilder sb ) { sb.Append( "MkRefAnyOperator(" ); base.InnerToString( sb ); sb.AppendFormat( " {0}", m_td ); sb.Append( ")" ); } public override string FormatOutput( IIntermediateRepresentationDumper dumper ) { return dumper.FormatOutput( "{0} = typedref {1} for {2}", this.FirstResult, m_td, this.FirstArgument ); } } } ================================================ FILE: Zelig/Zelig/CompileTime/CodeGenerator/IntermediateRepresentation/Operators/TypedReference/RefAnyTypeOperator.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // namespace Microsoft.Zelig.CodeGeneration.IR { using System; using System.Collections.Generic; using Microsoft.Zelig.Runtime.TypeSystem; public sealed class RefAnyTypeOperator : Operator { private const OperatorCapabilities cCapabilities = OperatorCapabilities.IsNonCommutative | OperatorCapabilities.DoesNotMutateExistingStorage | OperatorCapabilities.DoesNotAllocateStorage | OperatorCapabilities.DoesNotReadExistingMutableStorage | OperatorCapabilities.DoesNotThrow | OperatorCapabilities.DoesNotReadThroughPointerOperands | OperatorCapabilities.DoesNotWriteThroughPointerOperands | OperatorCapabilities.DoesNotCapturePointerOperands ; // // Constructor Methods // private RefAnyTypeOperator( Debugging.DebugInfo debugInfo ) : base( debugInfo, cCapabilities, OperatorLevel.FullyObjectOriented ) { } //--// public static RefAnyTypeOperator New( Debugging.DebugInfo debugInfo , VariableExpression lhs , Expression rhs ) { RefAnyTypeOperator res = new RefAnyTypeOperator( debugInfo ); res.SetLhs( lhs ); res.SetRhs( rhs ); return res; } //--// // // Helper Methods // public override Operator Clone( CloningContext context ) { return RegisterAndCloneState( context, new RefAnyTypeOperator( m_debugInfo ) ); } //--// // // Access Methods // //--// // // Debug Methods // public override void InnerToString( System.Text.StringBuilder sb ) { sb.Append( "RefAnyTypeOperator(" ); base.InnerToString( sb ); sb.Append( ")" ); } public override string FormatOutput( IIntermediateRepresentationDumper dumper ) { return dumper.FormatOutput( "{0} = type from typedref {1}", this.FirstResult, this.FirstArgument ); } } } ================================================ FILE: Zelig/Zelig/CompileTime/CodeGenerator/IntermediateRepresentation/Operators/TypedReference/RefAnyValOperator.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // namespace Microsoft.Zelig.CodeGeneration.IR { using System; using System.Collections.Generic; using Microsoft.Zelig.Runtime.TypeSystem; public sealed class RefAnyValOperator : Operator { private const OperatorCapabilities cCapabilities = OperatorCapabilities.IsNonCommutative | OperatorCapabilities.DoesNotMutateExistingStorage | OperatorCapabilities.DoesNotAllocateStorage | OperatorCapabilities.DoesNotReadExistingMutableStorage | OperatorCapabilities.MayThrow | OperatorCapabilities.DoesNotReadThroughPointerOperands | OperatorCapabilities.DoesNotWriteThroughPointerOperands | OperatorCapabilities.DoesNotCapturePointerOperands ; // // State // private TypeRepresentation m_td; // // Constructor Methods // private RefAnyValOperator( Debugging.DebugInfo debugInfo , TypeRepresentation td ) : base( debugInfo, cCapabilities, OperatorLevel.FullyObjectOriented ) { m_td = td; } //--// public static RefAnyValOperator New( Debugging.DebugInfo debugInfo , TypeRepresentation td , VariableExpression lhs , Expression rhs ) { RefAnyValOperator res = new RefAnyValOperator( debugInfo, td ); res.SetLhs( lhs ); res.SetRhs( rhs ); return res; } //--// // // Helper Methods // public override Operator Clone( CloningContext context ) { TypeRepresentation td = context.ConvertType( m_td ); return RegisterAndCloneState( context, new RefAnyValOperator( m_debugInfo, td ) ); } //--// public override void ApplyTransformation( TransformationContextForIR context ) { context.Push( this ); base.ApplyTransformation( context ); context.Transform( ref m_td ); context.Pop(); } //--// // // Access Methods // public TypeRepresentation Type { get { return m_td; } } //--// // // Debug Methods // public override void InnerToString( System.Text.StringBuilder sb ) { sb.Append( "RefAnyValOperator(" ); base.InnerToString( sb ); sb.AppendFormat( " {0}", m_td ); sb.Append( ")" ); } public override string FormatOutput( IIntermediateRepresentationDumper dumper ) { return dumper.FormatOutput( "{0} = value from typedref {1}", this.FirstResult, this.FirstArgument ); } } } ================================================ FILE: Zelig/Zelig/CompileTime/CodeGenerator/IntermediateRepresentation/Operators/UnaryOperator.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // namespace Microsoft.Zelig.CodeGeneration.IR { using System; using System.Collections.Generic; using Microsoft.Zelig.Runtime.TypeSystem; public sealed class UnaryOperator : AbstractUnaryOperator { // // Constructor Methods // private UnaryOperator( Debugging.DebugInfo debugInfo , OperatorCapabilities capabilities , OperatorLevel level , ALU alu , bool fSigned , bool fOverflow ) : base( debugInfo, capabilities, level, alu, fSigned, fOverflow ) { } //--// public static UnaryOperator New( Debugging.DebugInfo debugInfo , ALU alu , bool fSigned , bool fOverflow , VariableExpression lhs , Expression rhs ) { OperatorCapabilities capabilities = OperatorCapabilities.IsNonCommutative | OperatorCapabilities.DoesNotMutateExistingStorage | OperatorCapabilities.DoesNotAllocateStorage | OperatorCapabilities.DoesNotReadExistingMutableStorage | OperatorCapabilities.DoesNotReadThroughPointerOperands | OperatorCapabilities.DoesNotWriteThroughPointerOperands | OperatorCapabilities.DoesNotCapturePointerOperands ; if(fOverflow) capabilities |= OperatorCapabilities.MayThrow; else capabilities |= OperatorCapabilities.DoesNotThrow; OperatorLevel level = fOverflow ? OperatorLevel.ConcreteTypes : OperatorLevel.Lowest; var res = new UnaryOperator( debugInfo, capabilities, level, alu, fSigned, fOverflow ); res.SetLhs( lhs ); res.SetRhs( rhs ); return res; } //--// // // Helper Methods // public override Operator Clone( CloningContext context ) { return RegisterAndCloneState( context, new UnaryOperator( m_debugInfo, m_capabilities, m_level, m_alu, m_fSigned, m_fOverflow ) ); } //--// public override ConstantExpression CanEvaluate( Operator[][] defChains , Operator[][] useChains , VariableExpression.Property[] properties ) { var ex = FindConstantOrigin( this.FirstArgument, defChains, useChains, properties ); if(ex != null) { // // BUGBUG: Overflow checking is ignored! // if(ex.IsValueInteger) { ulong val; if(ex.GetAsRawUlong( out val ) == false) { return null; } switch(m_alu) { case ALU.NEG: val = 0 - val; break; case ALU.NOT: val = ~val; break; default: return null; } return new ConstantExpression( ex.Type, val ); } if(ex.IsValueFloatingPoint) { object val = ex.Value; if(val is float) { float val2 = (float)val; switch(m_alu) { case ALU.NEG: val2 = -val2; break; default: return null; } return new ConstantExpression( ex.Type, val2 ); } if(val is double) { double val2 = (double)val; switch(m_alu) { case ALU.NEG: val2 = -val2; break; default: return null; } return new ConstantExpression( ex.Type, val2 ); } } } return null; } //--// // // Access Methods // //--// // // Debug Methods // public override void InnerToString( System.Text.StringBuilder sb ) { sb.Append( "UnaryOperator(" ); base.InnerToString( sb ); sb.Append( ")" ); } public override string FormatOutput( IIntermediateRepresentationDumper dumper ) { return dumper.FormatOutput( "{0} = {1} {2}{3}", this.FirstResult, m_alu, this.FirstArgument, this.MayThrow ? " MayThrow" : "" ); } } } ================================================ FILE: Zelig/Zelig/CompileTime/CodeGenerator/IntermediateRepresentation/Operators/ZeroExtendOperator.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // namespace Microsoft.Zelig.CodeGeneration.IR { using System; using System.Collections.Generic; using Microsoft.Zelig.Runtime.TypeSystem; public sealed class ZeroExtendOperator : ConversionOperator { // // Constructor Methods // private ZeroExtendOperator( Debugging.DebugInfo debugInfo , OperatorCapabilities capabilities , OperatorLevel level , uint sourceSize , bool fOverflow ) : base( debugInfo, capabilities, level, sourceSize, fOverflow ) { } //--// public static ZeroExtendOperator New( Debugging.DebugInfo debugInfo , uint sourceSize , bool fOverflow , VariableExpression lhs , Expression rhs ) { OperatorLevel level; OperatorCapabilities capabilities = OperatorCapabilities.IsNonCommutative | OperatorCapabilities.DoesNotMutateExistingStorage | OperatorCapabilities.DoesNotAllocateStorage | OperatorCapabilities.DoesNotReadExistingMutableStorage | OperatorCapabilities.DoesNotReadThroughPointerOperands | OperatorCapabilities.DoesNotWriteThroughPointerOperands | OperatorCapabilities.DoesNotCapturePointerOperands ; if(fOverflow) { capabilities |= OperatorCapabilities.MayThrow; level = OperatorLevel.ConcreteTypes; } else { capabilities |= OperatorCapabilities.DoesNotThrow; level = OperatorLevel.Lowest; } ZeroExtendOperator res = new ZeroExtendOperator( debugInfo, capabilities, level, sourceSize, fOverflow ); res.SetLhs( lhs ); res.SetRhs( rhs ); return res; } //--// // // Helper Methods // public override Operator Clone( CloningContext context ) { return RegisterAndCloneState( context, new ZeroExtendOperator( m_debugInfo, m_capabilities, m_level, this.SignificantSize, this.CheckOverflow ) ); } //--// public override ConstantExpression CanEvaluate( Operator[][] defChains , Operator[][] useChains , VariableExpression.Property[] properties ) { var ex = FindConstantOrigin( this.FirstArgument, defChains, useChains, properties ); if(ex != null) { if(ex.IsValueInteger) { ulong val; if(ex.GetAsRawUlong( out val ) == false) { return null; } int bits = 8 * (int)this.SignificantSize; ulong valModified = val & ((1ul << bits) - 1ul); if(this.CheckOverflow) { if(valModified != val) { throw TypeConsistencyErrorException.Create( "Found an overflow: cannot zero extend '{0}' from {1} bits without losing precision", ex, bits ); } } return new ConstantExpression( this.FirstResult.Type, valModified ); } } return null; } // // Debug Methods // public override void InnerToString( System.Text.StringBuilder sb ) { sb.Append( "ZeroExtend(" ); base.InnerToString( sb ); sb.Append( ")" ); } public override string FormatOutput( IIntermediateRepresentationDumper dumper ) { return dumper.FormatOutput( "{0} = zeroextend {1} from {2} bits {3}", this.FirstResult, this.FirstArgument, 8 * this.SignificantSize, this.CheckOverflow ? " with overflow check" : "" ); } } } ================================================ FILE: Zelig/Zelig/CompileTime/CodeGenerator/IntermediateRepresentation/Properties/AssemblyInfo.cs ================================================ using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; // General Information about an assembly is controlled through the following // set of attributes. Change these attribute values to modify the information // associated with an assembly. [assembly: AssemblyTitle( "Microsoft.Zelig.CodeGeneration.IntermediateRepresentation" )] [assembly: AssemblyDescription( "" )] [assembly: AssemblyConfiguration( "" )] [assembly: AssemblyCompany( "Microsoft" )] [assembly: AssemblyProduct( "Microsoft.Zelig.CodeGeneration.IntermediateRepresentation" )] [assembly: AssemblyCopyright( "Copyright © Microsoft 2006" )] [assembly: AssemblyTrademark( "" )] [assembly: AssemblyCulture( "" )] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible( false )] //// The following GUID is for the ID of the typelib if this project is exposed to COM //[assembly: Guid( "57de0ebe-e971-4cb9-8985-5f6b66934a91" )] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Revision and Build Numbers // by using the '*' as shown below: [assembly: AssemblyVersion( "1.0.0.0" )] [assembly: AssemblyFileVersion( "1.0.0.0" )] ================================================ FILE: Zelig/Zelig/CompileTime/CodeGenerator/IntermediateRepresentation/TransformationContextForIR.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // namespace Microsoft.Zelig.CodeGeneration.IR { using System; using System.Collections.Generic; using Microsoft.Zelig.Runtime.TypeSystem; public abstract class TransformationContextForIR : TransformationContext { public abstract void Transform( ref ControlFlowGraphState cfg ); public abstract void Transform( ref Operator op ); public abstract void Transform( ref Operator[] opArray ); public abstract void Transform( ref Annotation an ); public abstract void Transform( ref Annotation[] anArray ); public abstract void Transform( ref Expression ex ); public abstract void Transform( ref ConstantExpression ex ); public abstract void Transform( ref VariableExpression ex ); public abstract void Transform( ref VariableExpression.DebugInfo val ); public abstract void Transform( ref Expression[] exArray ); public abstract void Transform( ref VariableExpression[] exArray ); public abstract void Transform( ref List< ConstantExpression > exLst ); public abstract void Transform( ref BasicBlock bb ); public abstract void Transform( ref EntryBasicBlock bb ); public abstract void Transform( ref ExitBasicBlock bb ); public abstract void Transform( ref ExceptionHandlerBasicBlock bb ); public abstract void Transform( ref BasicBlock[] bbArray ); public abstract void Transform( ref ExceptionHandlerBasicBlock[] bbArray ); public abstract void Transform( ref BasicBlock.Qualifier val ); public abstract void Transform( ref ExceptionClause ec ); public abstract void Transform( ref ExceptionClause[] ecArray ); public abstract void Transform( ref ExceptionClause.ExceptionFlag val ); public abstract void Transform( ref CompilationConstraints val ); public abstract void Transform( ref CompilationConstraints[] valArray ); public abstract void Transform( ref Operator.OperatorCapabilities val ); public abstract void Transform( ref Operator.OperatorLevel val ); public abstract void Transform( ref AbstractBinaryOperator.ALU val ); public abstract void Transform( ref AbstractUnaryOperator.ALU val ); public abstract void Transform( ref CallOperator.CallKind val ); public abstract void Transform( ref CompareAndSetOperator.ActionCondition val ); } } ================================================ FILE: Zelig/Zelig/CompileTime/CodeGenerator/IntermediateRepresentation/TypeSystemForIR.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // namespace Microsoft.Zelig.CodeGeneration.IR { using System; using System.Collections.Generic; using Microsoft.Zelig.MetaData; using Microsoft.Zelig.MetaData.Normalized; using Microsoft.Zelig.Runtime.TypeSystem; public abstract class TypeSystemForIR : TypeSystem { // // Constructor Methods // public TypeSystemForIR( IEnvironmentProvider env ) : base( env ) { } // // Helper Methods // public ControlFlowGraphState CreateControlFlowGraphState( MethodRepresentation md ) { VariableExpression[] arguments; VariableExpression[] locals; return CreateControlFlowGraphState( md, null, null, out arguments, out locals ); } public abstract ControlFlowGraphState CreateControlFlowGraphState( MethodRepresentation md , TypeRepresentation[] localVars , string[] localVarNames , out VariableExpression[] arguments , out VariableExpression[] locals ); public abstract ConstantExpression CreateNullPointer( TypeRepresentation td ); public abstract ConstantExpression CreateConstant( TypeRepresentation td , object value ); public abstract ConstantExpression CreateConstant( int value ); public abstract ConstantExpression CreateConstant( uint value ); public abstract ConstantExpression CreateConstantFromObject( object value ); public abstract Expression[] CreateConstantsFromObjects( params object[] array ); public abstract ConstantExpression CreateConstantForType( VTable vTable ); public abstract ConstantExpression CreateConstantForTypeSize( TypeRepresentation td ); public abstract ConstantExpression CreateConstantForFieldOffset( FieldRepresentation fd ); public abstract Expression CreateRuntimeHandle( object o ); public abstract Annotation CreateUniqueAnnotation( Annotation an ); public abstract Expression[] AddTypePointerToArgumentsOfStaticMethod( MethodRepresentation md , params Expression[] rhs ); } } ================================================ FILE: Zelig/Zelig/CompileTime/Llvm.NET/LibLLVM/AnalysisBindings.cpp ================================================ #include "AnalysisBindings.h" #include "llvm-c/Analysis.h" #include "llvm-c/Initialization.h" #include "llvm/IR/Module.h" #include "llvm/IR/Verifier.h" #include "llvm/Support/raw_ostream.h" #include using namespace llvm; extern "C" { // The standard LLVMVerifyFunction (unlike LLVMVerifyModule) doesn't provide // a way to capture error message strings (only success/fail or print to // stderr is available). This provides a version that matches the general // patern established by LLVMVerifyModule(). LLVMBool LLVMVerifyFunctionEx( LLVMValueRef Fn , LLVMVerifierFailureAction Action , char **OutMessages ) { raw_ostream *DebugOS = Action != LLVMReturnStatusAction ? &errs( ) : nullptr; std::string Messages; raw_string_ostream MsgsOS( Messages ); LLVMBool Result = verifyFunction( *unwrap( Fn ), OutMessages ? &MsgsOS : DebugOS ); // Duplicate the output to stderr. if( DebugOS && OutMessages ) *DebugOS << MsgsOS.str( ); if( Action == LLVMAbortProcessAction && Result ) report_fatal_error( "Broken function found, compilation aborted!" ); if( OutMessages ) *OutMessages = strdup( MsgsOS.str( ).c_str( ) ); return Result; } } ================================================ FILE: Zelig/Zelig/CompileTime/Llvm.NET/LibLLVM/AnalysisBindings.h ================================================ #ifndef _ANALYSIS_BINDINGS_H_ #define _ANALYSIS_BINDINGS_H_ #include "llvm-c/Core.h" #include "llvm-c/Analysis.h" #ifdef __cplusplus extern "C" { #endif LLVMBool LLVMVerifyFunctionEx( LLVMValueRef Fn , LLVMVerifierFailureAction Action , char **OutMessages ); #ifdef __cplusplus } #endif #endif ================================================ FILE: Zelig/Zelig/CompileTime/Llvm.NET/LibLLVM/AttributeBindings.cpp ================================================ #include "AttributeBindings.h" #include "llvm\IR\Attributes.h" #include "llvm\IR\LLVMContext.h" #include "llvm\IR\Value.h" #include "llvm\IR\Function.h" #include "llvm\IR\CallSite.h" #include "llvm\Support\CBindingWrapping.h" #include using namespace llvm; DEFINE_SIMPLE_CONVERSION_FUNCTIONS( AttrBuilder, LLVMAttributeBuilderRef ) // Validate assumptions regarding the attribute classes made in this code // in order to project the types to other languages static_assert( sizeof( std::uintptr_t ) == sizeof( Attribute ), "ERROR: Size mismatch on Attribute" ); static_assert( std::is_trivially_copy_constructible::value, "ERROR: Attribute cannot be trivially copy constructed" ); static_assert( std::is_standard_layout::value, "ERROR: Attribute is not a 'C' compatible standard layout" ); LLVMAttributeValue wrap( Attribute attribute ) { return *reinterpret_cast< LLVMAttributeValue* >( &attribute ); } Attribute AsAttribute( LLVMAttributeValue attribute ) { return *reinterpret_cast< Attribute* >( &attribute ); } static_assert( sizeof( std::uintptr_t ) == sizeof( AttributeSet ), "ERROR: Size mismatch on AttributeSet" ); static_assert( std::is_trivially_copy_constructible::value, "ERROR: AttributeSet cannot be trivially copy constructed" ); static_assert( std::is_standard_layout::value, "ERROR: AttributeSet is not a 'C' compatible standard layout" ); LLVMAttributeSet wrap( AttributeSet attribute ) { return *reinterpret_cast< LLVMAttributeSet* >( &attribute ); } AttributeSet AsAttributeSet( LLVMAttributeSet attribute ) { return *reinterpret_cast< AttributeSet* >( &attribute ); } static_assert( sizeof( ArrayRef::iterator ) == sizeof( uintptr_t ), "ERROR: Size mismatch on ArrayRef::iterator" ); extern "C" { //--- AttributeSet wrappers LLVMAttributeSet LLVMCreateEmptyAttributeSet( ) { return wrap( AttributeSet( ) ); } LLVMAttributeSet LLVMCreateAttributeSetFromKindArray( LLVMContextRef context, unsigned index, LLVMAttrKind* pKinds, uint64_t len ) { auto attributes = ArrayRef( reinterpret_cast< Attribute::AttrKind* >( pKinds ), static_cast< size_t >( len ) ); return wrap( AttributeSet::get( *unwrap( context ), index, attributes ) ); } LLVMAttributeSet LLVMCreateAttributeSetFromAttributeSetArray( LLVMContextRef context, LLVMAttributeSet* pAttributes, uint64_t len ) { auto attributeSets = ArrayRef( reinterpret_cast< AttributeSet* >( pAttributes ), static_cast< size_t >( len ) ); return wrap( AttributeSet::get( *unwrap( context ), attributeSets ) ); } LLVMAttributeSet LLVMCreateAttributeSetFromBuilder( LLVMContextRef context, unsigned index, LLVMAttributeBuilderRef bldr ) { return wrap( AttributeSet::get( *unwrap( context ), index, *unwrap( bldr ) ) ); } LLVMAttributeSet LLVMAttributeSetAddKind( LLVMAttributeSet attributeSet, LLVMContextRef context, unsigned index, LLVMAttrKind kind ) { auto attributes = AsAttributeSet( attributeSet ); return wrap( attributes.addAttribute( *unwrap( context ), index, ( Attribute::AttrKind )kind ) ); } LLVMAttributeSet LLVMAttributeSetAddString( LLVMAttributeSet attributeSet, LLVMContextRef context, unsigned index, char const*name ) { auto attributes = AsAttributeSet( attributeSet ); return wrap( attributes.addAttribute( *unwrap( context ), index, name ) ); } LLVMAttributeSet LLVMAttributeSetAddStringValue( LLVMAttributeSet attributeSet, LLVMContextRef context, unsigned index, char const* name, char const* value ) { auto attributes = AsAttributeSet( attributeSet ); return wrap( attributes.addAttribute( *unwrap( context ), index, name, value ) ); } LLVMAttributeSet LLVMAttributeSetAddAttributes( LLVMAttributeSet attributeSet, LLVMContextRef context, unsigned index, LLVMAttributeSet otherAttributeSet ) { auto attributes = AsAttributeSet( attributeSet ); auto otherAttributes = AsAttributeSet( otherAttributeSet ); return wrap( attributes.addAttributes( *unwrap( context ), index, otherAttributes ) ); } LLVMAttributeSet LLVMAttributeSetRemoveAttributeKind( LLVMAttributeSet attributeSet, unsigned index, LLVMAttrKind kind ) { auto attributes = AsAttributeSet( attributeSet ); if( attributes.isEmpty( ) ) return attributeSet; return wrap( attributes.removeAttribute( attributes.getContext(), index, (Attribute::AttrKind )kind ) ); } LLVMAttributeSet LLVMAttributeSetRemoveAttributeSet( LLVMAttributeSet attributeSet, unsigned index, LLVMAttributeSet attributesToRemove ) { auto attributes = AsAttributeSet( attributeSet ); auto attributeSetToRemove = AsAttributeSet( attributesToRemove ); if( attributes.isEmpty( ) || attributeSetToRemove.isEmpty( ) ) return attributeSet; assert( &attributes.getContext( ) == &attributeSetToRemove.getContext( ) && "Mismatched contexts on AttributeSet" ); return wrap( attributes.removeAttributes( attributes.getContext(), index, attributeSetToRemove ) ); } LLVMAttributeSet LLVMAttributeSetRemoveAttributeBuilder( LLVMAttributeSet attributeSet, LLVMContextRef context, unsigned index, LLVMAttributeBuilderRef bldr ) { LLVMContext* pContext = unwrap( context ); auto attributes = AsAttributeSet( attributeSet ); AttrBuilder& attributeBuilder = *unwrap( bldr ); assert( ( attributes.isEmpty() || &attributes.getContext( ) == pContext ) && "Mismatched contexts on AttributeSet" ); return wrap( attributes.removeAttributes( *pContext, index, attributeBuilder ) ); } LLVMContextRef LLVMAttributeSetGetContext( LLVMAttributeSet attributeSet ) { return wrap( &AsAttributeSet( attributeSet ).getContext( ) ); } LLVMAttributeSet LLVMAttributeGetAttributes( LLVMAttributeSet attributeSet, unsigned index ) { auto attributes = AsAttributeSet( attributeSet ); switch( index ) { case AttributeSet::AttrIndex::FunctionIndex: return wrap( attributes.getFnAttributes( ) ); case AttributeSet::AttrIndex::ReturnIndex: return wrap( attributes.getRetAttributes( ) ); default: return wrap( attributes.getParamAttributes( index ) ); } } LLVMBool LLVMAttributeSetHasAttributeKind( LLVMAttributeSet attributeSet, unsigned index, LLVMAttrKind kind ) { auto attributes = AsAttributeSet( attributeSet ); return attributes.hasAttribute( index, ( Attribute::AttrKind )kind ); } LLVMBool LLVMAttributeSetHasStringAttribute( LLVMAttributeSet attributeSet, unsigned index, char const* name ) { auto attributes = AsAttributeSet( attributeSet ); return attributes.hasAttribute( index, name ); } LLVMBool LLVMAttributeSetHasAttributes( LLVMAttributeSet attributeSet, unsigned index ) { auto attributes = AsAttributeSet( attributeSet ); return attributes.hasAttributes( index ); } LLVMBool LLVMAttributeSetHasAttributeSomewhere( LLVMAttributeSet attributeSet, LLVMAttrKind kind ) { auto attributes = AsAttributeSet( attributeSet ); return attributes.hasAttrSomewhere( ( Attribute::AttrKind )kind ); } LLVMAttributeValue LLVMAttributeSetGetAttributeByKind( LLVMAttributeSet attributeSet, unsigned index, LLVMAttrKind kind ) { auto attributes = AsAttributeSet( attributeSet ); return wrap( attributes.getAttribute( index, ( Attribute::AttrKind )kind ) ); } LLVMAttributeValue LLVMAttributeSetGetAttributeByName( LLVMAttributeSet attributeSet, unsigned index, char const* name ) { auto attributes = AsAttributeSet( attributeSet ); return wrap( attributes.getAttribute( index, name ) ); } char const* LLVMAttributeSetToString( LLVMAttributeSet attributeSet, unsigned index, LLVMBool inGroup ) { auto attributes = AsAttributeSet( attributeSet ); return LLVMCreateMessage( attributes.getAsString( index, inGroup != 0 ).c_str() ); } unsigned LLVMAttributeSetGetNumSlots( LLVMAttributeSet attributeSet ) { auto attributes = AsAttributeSet( attributeSet ); return attributes.getNumSlots( ); } LLVMAttributeSet LLVMAttributeSetGetSlotAttributes( LLVMAttributeSet attributeSet, unsigned slot ) { auto attributes = AsAttributeSet( attributeSet ); return wrap( attributes.getSlotAttributes( slot ) ); } unsigned LLVMAttributeSetGetSlotIndex( LLVMAttributeSet attributeSet, unsigned slot ) { auto attributes = AsAttributeSet( attributeSet ); return attributes.getSlotIndex( slot ); } LLVMAttributeSet LLVMGetFunctionAttributeSet( LLVMValueRef /*Function*/ function ) { auto func = unwrap( function ); return wrap( func->getAttributes() ); } void LLVMSetFunctionAttributeSet( LLVMValueRef /*Function*/ function, LLVMAttributeSet attributeSet ) { auto func = unwrap( function ); func->setAttributes( AsAttributeSet( attributeSet ) ); } LLVMAttributeSet LLVMGetCallSiteAttributeSet( LLVMValueRef /*Instruction*/ instruction ) { CallSite call = CallSite( unwrap( instruction ) ); return wrap( call.getAttributes( ) ); } void LLVMSetCallSiteAttributeSet( LLVMValueRef /*Instruction*/ instruction, LLVMAttributeSet attributeSet ) { CallSite call = CallSite( unwrap( instruction ) ); call.setAttributes( AsAttributeSet( attributeSet ) ); } uintptr_t LLVMAttributeSetGetIteratorStartToken( LLVMAttributeSet attributeSet, unsigned slot ) { auto attributes = AsAttributeSet( attributeSet ); return reinterpret_cast( attributes.begin( slot ) ); } LLVMAttributeValue LLVMAttributeSetIteratorGetNext( LLVMAttributeSet attributeSet, unsigned slot, uintptr_t* pToken ) { auto attributes = AsAttributeSet( attributeSet ); auto it = *reinterpret_cast< Attribute**>( pToken ); if( it >= attributes.end( slot ) || it < attributes.begin( slot ) ) return wrap( Attribute( ) ); auto retVal = wrap( *it ); *pToken = reinterpret_cast( ++it ); return retVal; } //--- Attribute Wrappers LLVMBool LLVMIsEnumAttribute( LLVMAttributeValue attribute ) { return AsAttribute( attribute ).isEnumAttribute( ); } LLVMBool LLVMIsIntAttribute( LLVMAttributeValue attribute ) { return AsAttribute( attribute ).isIntAttribute( ); } LLVMBool LLVMIsStringAttribute( LLVMAttributeValue attribute ) { return AsAttribute( attribute ).isStringAttribute( ); } LLVMBool LLVMHasAttributeKind( LLVMAttributeValue attribute, LLVMAttrKind kind ) { return AsAttribute( attribute ).hasAttribute( ( llvm::Attribute::AttrKind )kind ); } LLVMBool LLVMHasAttributeString( LLVMAttributeValue attribute, char const* name ) { return AsAttribute( attribute ).hasAttribute( name ); } LLVMAttrKind LLVMGetAttributeKind( LLVMAttributeValue attribute ) { return ( LLVMAttrKind )AsAttribute( attribute ).getKindAsEnum( ); } uint64_t LLVMGetAttributeValue( LLVMAttributeValue attribute ) { return AsAttribute( attribute ).getValueAsInt( ); } char const* LLVMGetAttributeName( LLVMAttributeValue attribute ) { return AsAttribute( attribute ).getKindAsString( ).data(); } char const* LLVMGetAttributeStringValue( LLVMAttributeValue attribute ) { return AsAttribute( attribute ).getValueAsString( ).data(); } char const* LLVMAttributeToString( LLVMAttributeValue attribute ) { return LLVMCreateMessage( AsAttribute( attribute ).getAsString( ).c_str( ) ); } LLVMAttributeValue LLVMCreateAttribute( LLVMContextRef ctx, LLVMAttrKind kind, uint64_t value ) { return wrap( llvm::Attribute::get( *unwrap( ctx ), ( llvm::Attribute::AttrKind )kind, value ) ); } LLVMAttributeValue LVMCreateTargetDependentAttribute( LLVMContextRef ctx, char const* name, char const* value ) { return wrap( llvm::Attribute::get( *unwrap( ctx ), name, value ) ); } //--- AttrBuilder Wrappers LLVMAttributeBuilderRef LLVMCreateAttributeBuilder( ) { return wrap( new AttrBuilder( ) ); } LLVMAttributeBuilderRef LLVMCreateAttributeBuilder2( LLVMAttributeValue value ) { return wrap( new AttrBuilder( AsAttribute( value ) ) ); } LLVMAttributeBuilderRef LLVMCreateAttributeBuilder3( LLVMAttributeSet attributeSet, unsigned index ) { return wrap( new AttrBuilder( AsAttributeSet( attributeSet ), index ) ); } void LLVMAttributeBuilderDispose( LLVMAttributeBuilderRef bldr ) { delete unwrap( bldr ); } void LLVMAttributeBuilderClear( LLVMAttributeBuilderRef bldr ) { unwrap( bldr )->clear( ); } void LLVMAttributeBuilderAddEnum( LLVMAttributeBuilderRef bldr, LLVMAttrKind kind ) { unwrap( bldr )->addAttribute( ( Attribute::AttrKind )kind ); } void LLVMAttributeBuilderAddAttribute( LLVMAttributeBuilderRef bldr, LLVMAttributeValue value ) { unwrap( bldr )->addAttribute( AsAttribute( value ) ); } void LLVMAttributeBuilderAddStringAttribute( LLVMAttributeBuilderRef bldr, char const* name, char const* value ) { unwrap( bldr )->addAttribute( name, value ); } void LLVMAttributeBuilderRemoveEnum( LLVMAttributeBuilderRef bldr, LLVMAttrKind kind ) { unwrap( bldr )->removeAttribute( ( Attribute::AttrKind )kind ); } void LLVMAttributeBuilderRemoveAttributes( LLVMAttributeBuilderRef bldr, LLVMAttributeSet attributeSet, unsigned index ) { unwrap( bldr )->removeAttributes( AsAttributeSet( attributeSet ), index ); } void LLVMAttributeBuilderRemoveAttribute( LLVMAttributeBuilderRef bldr, char const* name ) { unwrap( bldr )->removeAttribute( name ); } void LLVMAttributeBuilderRemoveBldr( LLVMAttributeBuilderRef bldr, LLVMAttributeBuilderRef other ) { unwrap( bldr )->remove( *unwrap( other ) ); } void LLVMAttributeBuilderMerge( LLVMAttributeBuilderRef bldr, LLVMAttributeBuilderRef other ) { unwrap( bldr )->merge( *unwrap( other ) ); } LLVMBool LLVMAttributeBuilderOverlaps( LLVMAttributeBuilderRef bldr, LLVMAttributeBuilderRef other ) { return unwrap( bldr )->overlaps( *unwrap( other ) ); } LLVMBool LLVMAttributeBuilderContainsEnum( LLVMAttributeBuilderRef bldr, LLVMAttrKind kind ) { return unwrap( bldr )->contains( ( Attribute::AttrKind )kind ); } LLVMBool LLVMAttributeBuilderContainsName( LLVMAttributeBuilderRef bldr, char const* name ) { return unwrap( bldr )->contains( name ); } LLVMBool LLVMAttributeBuilderHasAnyAttributes( LLVMAttributeBuilderRef bldr ) { return unwrap( bldr )->hasAttributes( ); } LLVMBool LLVMAttributeBuilderHasAttributes( LLVMAttributeBuilderRef bldr, LLVMAttributeSet attributeset, unsigned index ) { return unwrap( bldr )->hasAttributes( AsAttributeSet( attributeset ), index ); } LLVMBool LLVMAttributeBuilderHasTargetIndependentAttrs( LLVMAttributeBuilderRef bldr ) { return !unwrap( bldr )->empty( ); } LLVMBool LLVMAttributeBuilderHasTargetDependentAttrs( LLVMAttributeBuilderRef bldr ) { return !unwrap( bldr )->td_empty( ); } } ================================================ FILE: Zelig/Zelig/CompileTime/Llvm.NET/LibLLVM/AttributeBindings.h ================================================ //===- AttributeBindings.h - Additional bindings for IR ----------------*- C++ -*-===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // This file defines additional C bindings for LLVM Attributes IR Attributes. // //===----------------------------------------------------------------------===// #ifndef LLVM_BINDINGS_LLVM_ATTRIBUTEBINDINGS_H #define LLVM_BINDINGS_LLVM_ATTRIBUTEBINDINGS_H #include "llvm-c/Core.h" #include #ifdef __cplusplus extern "C" { #endif enum LLVMAttrKind { // IR-Level Attributes LLVMAttrKindNone, ///< No attributes have been set LLVMAttrKindAlignment, ///< Alignment of parameter (5 bits) ///< stored as log2 of alignment with +1 bias ///< 0 means unaligned (different from align(1)) LLVMAttrKindAlwaysInline, ///< inline=always LLVMAttrKindBuiltin, ///< Callee is recognized as a builtin, despite ///< nobuiltin attribute on its declaration. LLVMAttrKindByVal, ///< Pass structure by value LLVMAttrKindInAlloca, ///< Pass structure in an alloca LLVMAttrKindCold, ///< Marks function as being in a cold path. LLVMAttrKindConvergent, ///< Can only be moved to control-equivalent blocks LLVMAttrKindInlineHint, ///< Source said inlining was desirable LLVMAttrKindInReg, ///< Force argument to be passed in register LLVMAttrKindJumpTable, ///< Build jump-instruction tables and replace refs. LLVMAttrKindMinSize, ///< Function must be optimized for size first LLVMAttrKindNaked, ///< Naked function LLVMAttrKindNest, ///< Nested function static chain LLVMAttrKindNoAlias, ///< Considered to not alias after call LLVMAttrKindNoBuiltin, ///< Callee isn't recognized as a builtin LLVMAttrKindNoCapture, ///< Function creates no aliases of pointer LLVMAttrKindNoDuplicate, ///< Call cannot be duplicated LLVMAttrKindNoImplicitFloat, ///< Disable implicit floating point insts LLVMAttrKindNoInline, ///< inline=never LLVMAttrKindNonLazyBind, ///< Function is called early and/or ///< often, so lazy binding isn't worthwhile LLVMAttrKindNonNull, ///< Pointer is known to be not null LLVMAttrKindDereferenceable, ///< Pointer is known to be dereferenceable LLVMAttrKindDereferenceableOrNull, ///< Pointer is either null or dereferenceable LLVMAttrKindNoRedZone, ///< Disable redzone LLVMAttrKindNoReturn, ///< Mark the function as not returning LLVMAttrKindNoUnwind, ///< Function doesn't unwind stack LLVMAttrKindOptimizeForSize, ///< opt_size LLVMAttrKindOptimizeNone, ///< Function must not be optimized. LLVMAttrKindReadNone, ///< Function does not access memory LLVMAttrKindReadOnly, ///< Function only reads from memory LLVMAttrKindArgMemOnly, ///< Funciton can access memory only using pointers ///< based on its arguments. LLVMAttrKindReturned, ///< Return value is always equal to this argument LLVMAttrKindReturnsTwice, ///< Function can return twice LLVMAttrKindSExt, ///< Sign extended before/after call LLVMAttrKindStackAlignment, ///< Alignment of stack for function (3 bits) ///< stored as log2 of alignment with +1 bias 0 ///< means unaligned (different from ///< alignstack=(1)) LLVMAttrKindStackProtect, ///< Stack protection. LLVMAttrKindStackProtectReq, ///< Stack protection required. LLVMAttrKindStackProtectStrong, ///< Strong Stack protection. LLVMAttrKindSafeStack, ///< Safe Stack protection. LLVMAttrKindStructRet, ///< Hidden pointer to structure to return LLVMAttrKindSanitizeAddress, ///< AddressSanitizer is on. LLVMAttrKindSanitizeThread, ///< ThreadSanitizer is on. LLVMAttrKindSanitizeMemory, ///< MemorySanitizer is on. LLVMAttrKindUWTable, ///< Function must be in a unwind table LLVMAttrKindZExt, ///< Zero extended before/after call EndAttrKinds ///< Sentinal value useful for loops }; // These functions replace the LLVM*FunctionAttr functions in the stable C API // since the underlying attribute support has changed dramatically in 3.7.0 /** * @defgroup LibLLVM Attributes * * Attributes are available for functions, function return types and parameters. * In previous releases of LLVM attributes were essentially a bit field. However, * as more attributes were added the number of bits had to grow. Furthermore, some * of the attributes such as stack alignment require a parameter value. Thus, the * attribute system evolved. Unfortunately the C API did not. Moving towards version * 4.0 of LLVM the entire bitfield approach is being deprecated. Thus these APIs * make the functionality of Attribute, AttributeSet and, AttrBuilder available * to language bindings based on a C-API * * The Attribute and AttributeSet classes are somewhat problematic to expose in * "C" as they are not officially POD types and therefore have limited defined * portable usage in "C". However, they are officially standard layout and trivially * copy constructible. The reason they are not POD is that they have a custom default * constructor. Thus construction cannot be assumed as trivially zero initializing * the memory for the type. To manage that with projections to "C" and other languages * this API exposes the underlying class constructors as "C" functions returning an * instance of the constructed type. Furthermore this API assumes that llvm::Attribute * and llvm::AttributeSet are defined using the Pointer to Implementation (PIMPL) * pattern and are entirely representable in a LLVMAttributeSet. (This is statically checked * in the AttributeBindings.cpp file along with the trivial copy construction and * standard layout type traits. Any changes in LLVM that would invalidate these assumptions * will trigger a compilation error, rather than failing in inexplicable ways at runtime.) * @{ */ typedef uintptr_t LLVMAttributeSet; typedef uintptr_t LLVMAttributeValue; typedef struct LLVMOpaqueAttributeBuilder* LLVMAttributeBuilderRef; /** @name AttributeSet * @{ */ LLVMAttributeSet LLVMCreateEmptyAttributeSet( ); LLVMAttributeSet LLVMCreateAttributeSetFromKindArray( LLVMContextRef context, unsigned index, LLVMAttrKind* pKinds, uint64_t len ); LLVMAttributeSet LLVMCreateAttributeSetFromAttributeSetArray( LLVMContextRef context, LLVMAttributeSet* pAttributes, uint64_t len ); LLVMAttributeSet LLVMCreateAttributeSetFromBuilder( LLVMContextRef context, unsigned index, LLVMAttributeBuilderRef bldr ); LLVMAttributeSet LLVMAttributeSetAddKind( LLVMAttributeSet attributeSet, LLVMContextRef context, unsigned index, LLVMAttrKind kind ); LLVMAttributeSet LLVMAttributeSetAddString( LLVMAttributeSet attributeSet, LLVMContextRef context, unsigned index, char const*name ); LLVMAttributeSet LLVMAttributeSetAddStringValue( LLVMAttributeSet attributeSet, LLVMContextRef context, unsigned index, char const* name, char const* value ); LLVMAttributeSet LLVMAttributeSetAddAttributes( LLVMAttributeSet attributeSet, LLVMContextRef context, unsigned index, LLVMAttributeSet otherAttributeSet ); LLVMAttributeSet LLVMAttributeSetRemoveAttributeKind( LLVMAttributeSet attributeSet, unsigned index, LLVMAttrKind kind ); LLVMAttributeSet LLVMAttributeSetRemoveAttributeSet( LLVMAttributeSet attributeSet, unsigned index, LLVMAttributeSet attributes ); LLVMAttributeSet LLVMAttributeSetRemoveAttributeBuilder( LLVMAttributeSet attributeSet, LLVMContextRef context, unsigned index, LLVMAttributeBuilderRef bldr ); LLVMContextRef LLVMAttributeSetGetContext( LLVMAttributeSet attributeSet ); LLVMAttributeSet LLVMAttributeGetAttributes( LLVMAttributeSet attributeSet, unsigned index ); LLVMBool LLVMAttributeSetHasAttributeKind( LLVMAttributeSet attributeSet, unsigned index, LLVMAttrKind kind ); LLVMBool LLVMAttributeSetHasStringAttribute( LLVMAttributeSet attributeSet, unsigned index, char const* name ); LLVMBool LLVMAttributeSetHasAttributes( LLVMAttributeSet attributeSet, unsigned index ); LLVMBool LLVMAttributeSetHasAttributeSomewhere( LLVMAttributeSet attributeSet, LLVMAttrKind kind ); LLVMAttributeValue LLVMAttributeSetGetAttributeByKind( LLVMAttributeSet attributeSet, unsigned index, LLVMAttrKind kind ); LLVMAttributeValue LLVMAttributeSetGetAttributeByName( LLVMAttributeSet attributeSet, unsigned index, char const* name ); char const* LLVMAttributeSetToString( LLVMAttributeSet attributeSet, unsigned index, LLVMBool inGroup ); unsigned LLVMAttributeSetGetNumSlots( LLVMAttributeSet attributeSet ); LLVMAttributeSet LLVMAttributeSetGetSlotAttributes( LLVMAttributeSet attributeSet, unsigned slot ); unsigned LLVMAttributeSetGetSlotIndex( LLVMAttributeSet attributeSet, unsigned slot ); LLVMAttributeSet LLVMGetFunctionAttributeSet( LLVMValueRef /*Function*/ function ); void LLVMSetFunctionAttributeSet( LLVMValueRef /*Function*/ function, LLVMAttributeSet attributeSet ); LLVMAttributeSet LLVMGetCallSiteAttributeSet( LLVMValueRef /*Instruction*/ instruction ); void LLVMSetCallSiteAttributeSet( LLVMValueRef /*Instruction*/ instruction, LLVMAttributeSet attributeSet ); uintptr_t LLVMAttributeSetGetIteratorStartToken( LLVMAttributeSet attributeSet, unsigned slot ); LLVMAttributeValue LLVMAttributeSetIteratorGetNext( LLVMAttributeSet attributeSet, unsigned slot, uintptr_t* pToken ); /** * @} */ /** @name Attribute * @{ */ LLVMBool LLVMIsEnumAttribute( LLVMAttributeValue attribute ); LLVMBool LLVMIsIntAttribute( LLVMAttributeValue attribute ); LLVMBool LLVMIsStringAttribute( LLVMAttributeValue attribute ); LLVMBool LLVMHasAttributeKind( LLVMAttributeValue attribute, LLVMAttrKind kind ); LLVMBool LLVMHasAttributeString( LLVMAttributeValue attribute, char const* name ); LLVMAttrKind LLVMGetAttributeKind( LLVMAttributeValue attribute ); uint64_t LLVMGetAttributeValue( LLVMAttributeValue attribute ); char const* LLVMGetAttributeName( LLVMAttributeValue attribute ); char const* LLVMGetAttributeStringValue( LLVMAttributeValue attribute ); char const* LLVMAttributeToString( LLVMAttributeValue attribute ); LLVMAttributeValue LLVMCreateAttribute( LLVMContextRef ctx, LLVMAttrKind kind, uint64_t value ); LLVMAttributeValue LVMCreateTargetDependentAttribute( LLVMContextRef ctx, char const* name, char const* value ); /** * @} */ /** @name AttrBuilder * @{ */ LLVMAttributeBuilderRef LLVMCreateAttributeBuilder( ); LLVMAttributeBuilderRef LLVMCreateAttributeBuilder2( LLVMAttributeValue value ); LLVMAttributeBuilderRef LLVMCreateAttributeBuilder3( LLVMAttributeSet attributeSet, unsigned index ); void LLVMAttributeBuilderDispose( LLVMAttributeBuilderRef bldr ); void LLVMAttributeBuilderClear( LLVMAttributeBuilderRef bldr ); void LLVMAttributeBuilderAddEnum( LLVMAttributeBuilderRef bldr, LLVMAttrKind kind ); void LLVMAttributeBuilderAddAttribute( LLVMAttributeBuilderRef bldr, LLVMAttributeValue value ); void LLVMAttributeBuilderAddStringAttribute( LLVMAttributeBuilderRef bldr, char const* name, char const* value ); void LLVMAttributeBuilderRemoveEnum( LLVMAttributeBuilderRef bldr, LLVMAttrKind kind ); void LLVMAttributeBuilderRemoveAttributes( LLVMAttributeBuilderRef bldr, LLVMAttributeSet attributeSet, unsigned index ); void LLVMAttributeBuilderRemoveAttribute( LLVMAttributeBuilderRef bldr, char const* name ); void LLVMAttributeBuilderRemoveBldr( LLVMAttributeBuilderRef bldr, LLVMAttributeBuilderRef ohter ); void LLVMAttributeBuilderMerge( LLVMAttributeBuilderRef bldr, LLVMAttributeBuilderRef ohter ); LLVMBool LLVMAttributeBuilderOverlaps( LLVMAttributeBuilderRef bldr, LLVMAttributeBuilderRef other ); LLVMBool LLVMAttributeBuilderContainsEnum( LLVMAttributeBuilderRef bldr, LLVMAttrKind kind ); LLVMBool LLVMAttributeBuilderContainsName( LLVMAttributeBuilderRef bldr, char const* name ); LLVMBool LLVMAttributeBuilderHasAnyAttributes( LLVMAttributeBuilderRef bldr ); LLVMBool LLVMAttributeBuilderHasAttributes( LLVMAttributeBuilderRef bldr, LLVMAttributeSet attributeset, unsigned index ); LLVMBool LLVMAttributeBuilderHasTargetIndependentAttrs( LLVMAttributeBuilderRef bldr ); LLVMBool LLVMAttributeBuilderHasTargetDependentAttrs( LLVMAttributeBuilderRef bldr ); // TODO: Define support for iterators over target dependent attributes /** * @} */ /** * @} */ #ifdef __cplusplus } #endif #endif ================================================ FILE: Zelig/Zelig/CompileTime/Llvm.NET/LibLLVM/BuildLlvmWithVS.cmd ================================================ @echo off @REM - This script file should be placed into the root of the LLVM source tree @REM - It can be run from there, with no parameters to generate all the @REM - Libs for Win32 and x64 with the Debug, RelWithDebInfo, and Release @REM - configurations. setlocal set LLVM_ROOT=%~d0%~p0 @REM By default do the following: @REM 1 - Generate the build project and solutions from CMake @REM 2 - Build all the Platform\configuration combos (2x3) @REM 3 - Register the output location in registry set GENERATE=1 set BUILD=1 set REGISTER=1 set LlvmVersion=3.8.1 @REM - Allow overriding default version and disabling any of the stages via parameters :arg_loop if /i "%1"=="-g-" set GENERATE=0 if /i "%1"=="-b-" set BUILD=0 if /i "%1"=="-r-" set REGISTER=0 if /i "%1"=="-v" ( set LlvmVersion=%2 shift ) if /i "%1"=="-?" goto :ShowUsage if /i "%1"=="/?" goto :ShowUsage if /i "%1"=="/h" goto :ShowUsage if /i "%1"=="-h" goto :ShowUsage if /i "%1"=="/help" goto :ShowUsage if /i "%1"=="/-help" goto :ShowUsage @rem - move to next arg and loop back around if it isn't empty shift if NOT "%1"=="" goto :arg_loop @REM - End of args parsing @REM - Verification if NOT EXIST %LLVM_ROOT%CMakeLists.txt ( @echo CMakeLists.txt is missing, the current directory does not appear to be an LLVM source directory goto :exit ) @REM - Execution if %GENERATE%==1 ( where cmake | findstr "cmake.exe" if %ERRORLEVEL% GTR 0 ( @echo cmake.exe not found, you must have cmake 3.2.3 installed and available on your PATH variable goto :exit ) call :CongigureLLVMBuild "Visual Studio 14 2015 Win64" x64 if %ERRORLEVEL% GTR 0 goto :exit call :CongigureLLVMBuild "Visual Studio 14 2015" Win32 if %ERRORLEVEL% GTR 0 goto :exit ) if %BUILD%==1 ( call :BuildLLVMPlatform x64 if %ERRORLEVEL% GTR 0 goto :exit call :BuildLLVMPlatform Win32 if %ERRORLEVEL% GTR 0 goto :exit ) if %REGISTER%==1 ( @echo registering LLVM path in registry reg add HKCU\Software\LLVM\%LlvmVersion% /v SrcRoot /d %LLVM_ROOT% /f echo Setting per machine registry path echo NOTE: Administrator permissions required to set per machine registry settings. echo If you get 'ERROR: Access is denied.' the per machine registration is not available reg add HKLM\Software\LLVM\%LlvmVersion% /v SrcRoot /d %LLVM_ROOT% /f @REM - Sadly, despite documentation to the contrary, reg won't set ERRORLEVEL on failure... ) goto :exit :ShowUsage @echo. @echo Description: @echo Builds LLVM libraries using the Microsoft Visual Studio 2015 compilers with the following basic steps @echo 1) Generates the VS projects from LLVM source via CMake @echo 2) Builds the sources for win32 and x64 platforms with the Debug,Release, and RelWithDebInfo configurations @echo 3) Adds a registry entry for the location of the src and build output HKCU\SOFTWARE\LLVM\^\SrcRoot @echo 4) Adds a registry entry for the location of the src and build output HKLM\SOFTWARE\LLVM\^\SrcRoot @echo. @echo Usage: @echo BuildLlvmWithVS [-g-][-b-][-r-][-v ^] @echo. @echo Where: @echo -g- disables the cmake project generation phase @echo -b- disables the code build phase @echo -r- disables the registry update @echo -v ^ sets the LLVM version number used for the registry entry (Default is 3.8.1) @echo. @echo The registry entry is used by the LlvmApplication.props Propertysheet for VC projects to locate the various @echo LLVM headers and libs. Alternatively, if LLVM_SRCROOT_DIR is provided either as an environment variable @echo or as an MsBuild property for the application's build then LlvmApplication.props will use it and the registry @echo entry is not required. This is to support automated build servers where this script may be run on a machine @echo sharing out the results and the application build server is run from a different account and machine where @echo settings are different. @echo. goto :exit :CongigureLLVMBuild @echo __--== Generating build configuration of LLVM For %2 ==--__ if NOT EXIST "build\%2" md build\%2 pushd build\%2 @rem - NOTE: Enabling RTTI allows for extended C API projections to use RTTI even on classes where the LLVM custom RTTI support isn't defined cmake -G"%~1" -DLLVM_ENABLE_RTTI=1 -DCMAKE_INSTALL_PREFIX=Install ..\.. popd if %ERRORLEVEL% GTR 0 exit /B %ERRORLEVEL% goto :EOF :BuildLLVMPlatform @echo __--== Building LLVM For %1 ==--__ @echo __--== Building Release configuration For %1 ==--__ cmake --build build\%1. --config Release if %ERRORLEVEL% GTR 0 exit /B %ERRORLEVEL% @echo __--== Building Checked configuration For %1 ==--__ cmake --build build\%1 --config RelWithDebInfo if %ERRORLEVEL% GTR 0 exit /B %ERRORLEVEL% @echo __--== Building Debug configuration For %1 ==--__ cmake --build build\%1 --config Debug if %ERRORLEVEL% GTR 0 exit /B %ERRORLEVEL% goto :EOF :exit endlocal goto :EOF ================================================ FILE: Zelig/Zelig/CompileTime/Llvm.NET/LibLLVM/DIBuilderBindings.cpp ================================================ //===- DIBuilderBindings.cpp - Bindings for DIBuilder ---------------------===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // This file defines C bindings for the DIBuilder class. // //===----------------------------------------------------------------------===// #include "DIBuilderBindings.h" #include "IRBindings.h" #include "llvm/IR/DIBuilder.h" #include "llvm/IR/IRBuilder.h" #include "llvm/IR/Module.h" #include "llvm/IR/Constant.h" #include "llvm/Support/raw_ostream.h" using namespace llvm; DEFINE_SIMPLE_CONVERSION_FUNCTIONS( DIBuilder, LLVMDIBuilderRef ) DEFINE_SIMPLE_CONVERSION_FUNCTIONS( MDOperand, LLVMMDOperandRef ) extern "C" { LLVMContextRef LLVMGetNodeContext( LLVMMetadataRef /*MDNode*/ node ) { MDNode* pNode = unwrap( node ); return wrap( &pNode->getContext( ) ); } LLVMMetadataRef /*DILocalScope*/ LLVMGetDILocationScope( LLVMMetadataRef /*DILocation*/ location ) { DILocation* loc = unwrap( location ); return wrap( loc->getScope( ) ); } unsigned LLVMGetDILocationLine( LLVMMetadataRef /*DILocation*/ location ) { DILocation* loc = unwrap( location ); return loc->getLine( ); } unsigned LLVMGetDILocationColumn( LLVMMetadataRef /*DILocation*/ location ) { DILocation* loc = unwrap( location ); return loc->getColumn( ); } LLVMMetadataRef /*DILocation*/ LLVMGetDILocationInlinedAt( LLVMMetadataRef /*DILocation*/ location ) { DILocation* loc = unwrap( location ); return wrap( loc->getInlinedAt( ) ); } LLVMMetadataRef /*DILocalScope*/ LLVMDILocationGetInlinedAtScope( LLVMMetadataRef /*DILocation*/ location ) { DILocation* loc = unwrap( location ); return wrap( loc->getInlinedAtScope( ) ); } char const* LLVMGetDIFileName( LLVMMetadataRef /*DIFile*/ file ) { DIFile* pFile = unwrap( file ); return pFile->getFilename( ).data( ); } char const* LLVMGetDIFileDirectory( LLVMMetadataRef /*DIFile*/ file ) { DIFile* pFile = unwrap( file ); return pFile->getDirectory( ).data( ); } void LLVMSetDILocation( LLVMValueRef inst, LLVMMetadataRef location ) { DILocation* loc = unwrap( location ); unwrap( inst )->setDebugLoc( loc ); } void LLVMSetDebugLoc( LLVMValueRef inst, unsigned line, unsigned column, LLVMMetadataRef scope ) { unwrap( inst )->setDebugLoc( DebugLoc::get( line, column, unwrap( scope ) ) ); } LLVMDIBuilderRef LLVMNewDIBuilder( LLVMModuleRef mref, LLVMBool allowUnresolved ) { Module *m = unwrap( mref ); return wrap( new DIBuilder( *m, allowUnresolved != 0 ) ); } void LLVMDIBuilderDestroy( LLVMDIBuilderRef dref ) { DIBuilder *d = unwrap( dref ); delete d; } void LLVMDIBuilderFinalize( LLVMDIBuilderRef dref ) { unwrap( dref )->finalize( ); } LLVMMetadataRef LLVMDIBuilderCreateCompileUnit( LLVMDIBuilderRef Dref , unsigned Lang , const char *File , const char *Dir , const char *Producer , int Optimized, const char *Flags , unsigned RuntimeVersion ) { DIBuilder *D = unwrap( Dref ); DICompileUnit* CU = D->createCompileUnit( Lang , File , Dir , Producer , Optimized , Flags , RuntimeVersion ); return wrap( CU ); } LLVMMetadataRef LLVMDIBuilderCreateFile( LLVMDIBuilderRef Dref , const char *File , const char *Dir ) { DIBuilder *D = unwrap( Dref ); DIFile* F = D->createFile( File, Dir ); return wrap( F ); } LLVMMetadataRef LLVMDIBuilderCreateLexicalBlock( LLVMDIBuilderRef Dref , LLVMMetadataRef Scope , LLVMMetadataRef File , unsigned Line , unsigned Column ) { DIBuilder *D = unwrap( Dref ); DILexicalBlock* LB = D->createLexicalBlock( unwrap( Scope ) , File ? unwrap( File ) : nullptr , Line , Column ); return wrap( LB ); } LLVMMetadataRef LLVMDIBuilderCreateLexicalBlockFile( LLVMDIBuilderRef Dref , LLVMMetadataRef Scope , LLVMMetadataRef File , unsigned Discriminator ) { DIBuilder *D = unwrap( Dref ); DILexicalBlockFile* LBF = D->createLexicalBlockFile( unwrap( Scope ) , unwrap( File ) , Discriminator ); return wrap( LBF ); } LLVMMetadataRef LLVMDIBuilderCreateFunction( LLVMDIBuilderRef Dref , LLVMMetadataRef Scope , const char *Name , const char *LinkageName , LLVMMetadataRef File , unsigned Line , LLVMMetadataRef CompositeType , int IsLocalToUnit , int IsDefinition , unsigned ScopeLine , unsigned Flags , int IsOptimized , LLVMMetadataRef /*DITemplateParameterArray*/ TParams /*= nullptr*/ , LLVMMetadataRef /*DISubProgram */ Decl /*= nullptr*/ ) { DIBuilder *D = unwrap( Dref ); DISubprogram* SP = D->createFunction( unwrap( Scope ) , Name , LinkageName , File ? unwrap( File ) : nullptr , Line , unwrap( CompositeType ) , IsLocalToUnit , IsDefinition , ScopeLine , Flags , IsOptimized , TParams ? DITemplateParameterArray( unwrap( TParams ) ) : nullptr , Decl ? unwrap( Decl ) : nullptr ); return wrap( SP ); } LLVMMetadataRef LLVMDIBuilderCreateTempFunctionFwdDecl( LLVMDIBuilderRef Dref , LLVMMetadataRef /*DIScope* */Scope , char const* Name , char const* LinkageName , LLVMMetadataRef /*DIFile* */ File , unsigned LineNo , LLVMMetadataRef /*DISubroutineType* */ Ty , bool isLocalToUnit , bool isDefinition , unsigned ScopeLine , unsigned Flags /*= 0*/ , bool isOptimized /*= false*/ , LLVMMetadataRef /*DITemplateParameterArray*/ TParams /*= nullptr*/ , LLVMMetadataRef /*DISubProgram */ Decl /*= nullptr*/ ) { DIBuilder *D = unwrap( Dref ); DISubprogram* SP = D->createTempFunctionFwdDecl( unwrap( Scope ) , Name , LinkageName , File ? unwrap( File ) : nullptr , LineNo , unwrap( Ty ) , isLocalToUnit , isDefinition , ScopeLine , Flags , isOptimized , TParams ? DITemplateParameterArray( unwrap( TParams ) ) : nullptr , Decl ? unwrap( Decl ) : nullptr ); return wrap( SP ); } LLVMMetadataRef LLVMDIBuilderCreateAutoVariable( LLVMDIBuilderRef Dref , LLVMMetadataRef Scope , const char *Name , LLVMMetadataRef File , unsigned Line , LLVMMetadataRef Ty , int AlwaysPreserve , unsigned Flags ) { DIBuilder *D = unwrap( Dref ); DIVariable* V = D->createAutoVariable( unwrap( Scope ) , Name , File ? unwrap( File ) : nullptr , Line , unwrap( Ty ) , AlwaysPreserve , Flags ); return wrap( V ); } LLVMMetadataRef LLVMDIBuilderCreateParameterVariable( LLVMDIBuilderRef Dref , LLVMMetadataRef Scope , const char *Name , unsigned ArgNo , LLVMMetadataRef File , unsigned Line , LLVMMetadataRef Ty , int AlwaysPreserve , unsigned Flags ) { DIBuilder *D = unwrap( Dref ); DIVariable* V = D->createParameterVariable( unwrap( Scope ) , Name , ArgNo , File ? unwrap( File ) : nullptr , Line , unwrap( Ty ) , AlwaysPreserve , Flags ); return wrap( V ); } LLVMMetadataRef LLVMDIBuilderCreateBasicType( LLVMDIBuilderRef Dref , const char *Name , uint64_t SizeInBits , uint64_t AlignInBits , unsigned Encoding ) { DIBuilder *D = unwrap( Dref ); DIBasicType* T = D->createBasicType( Name, SizeInBits, AlignInBits, Encoding ); return wrap( T ); } LLVMMetadataRef LLVMDIBuilderCreatePointerType( LLVMDIBuilderRef Dref , LLVMMetadataRef PointeeType , uint64_t SizeInBits , uint64_t AlignInBits , const char *Name ) { DIBuilder *D = unwrap( Dref ); DIDerivedType* T = D->createPointerType( PointeeType ? unwrap( PointeeType ) : nullptr // nullptr == void , SizeInBits , AlignInBits , Name ); return wrap( T ); } LLVMMetadataRef LLVMDIBuilderCreateQualifiedType( LLVMDIBuilderRef Dref , uint32_t Tag , LLVMMetadataRef BaseType ) { DIBuilder* D = unwrap( Dref ); DIDerivedType* T = D->createQualifiedType( Tag, unwrap( BaseType ) ); return wrap( T ); } LLVMMetadataRef LLVMDIBuilderCreateSubroutineType( LLVMDIBuilderRef Dref , LLVMMetadataRef ParameterTypes , unsigned Flags ) { DIBuilder *D = unwrap( Dref ); DISubroutineType* sub = D->createSubroutineType( DITypeRefArray( unwrap( ParameterTypes ) ) , Flags ); return wrap( sub ); } LLVMMetadataRef LLVMDIBuilderCreateStructType( LLVMDIBuilderRef Dref , LLVMMetadataRef Scope , const char *Name , LLVMMetadataRef File , unsigned Line , uint64_t SizeInBits , uint64_t AlignInBits , unsigned Flags , LLVMMetadataRef DerivedFrom , LLVMMetadataRef ElementTypes ) { DIBuilder *D = unwrap( Dref ); DICompositeType* CT = D->createStructType( unwrap( Scope ) , Name , File ? unwrap( File ) : nullptr , Line , SizeInBits , AlignInBits , Flags , DerivedFrom ? unwrap( DerivedFrom ) : nullptr , ElementTypes ? DINodeArray( unwrap( ElementTypes ) ) : nullptr ); return wrap( CT ); } LLVMMetadataRef LLVMDIBuilderCreateReplaceableCompositeType( LLVMDIBuilderRef Dref , unsigned Tag , const char *Name , LLVMMetadataRef Scope , LLVMMetadataRef File , unsigned Line , unsigned RuntimeLang , uint64_t SizeInBits , uint64_t AlignInBits , unsigned Flags ) { DIBuilder *D = unwrap( Dref ); DICompositeType* type = D->createReplaceableCompositeType( Tag , Name , Scope ? unwrap( Scope ) : nullptr , File ? unwrap( File ) : nullptr , Line , RuntimeLang , SizeInBits , AlignInBits , Flags ); return wrap( type ); } LLVMMetadataRef LLVMDIBuilderCreateMemberType( LLVMDIBuilderRef Dref , LLVMMetadataRef Scope , const char *Name , LLVMMetadataRef File , unsigned Line , uint64_t SizeInBits , uint64_t AlignInBits , uint64_t OffsetInBits , unsigned Flags , LLVMMetadataRef Ty ) { DIBuilder *D = unwrap( Dref ); DIDerivedType* DT = D->createMemberType( unwrap( Scope ) , Name , File ? unwrap( File ) : nullptr , Line , SizeInBits , AlignInBits , OffsetInBits , Flags , unwrap( Ty ) ); return wrap( DT ); } LLVMMetadataRef LLVMDIBuilderCreateArrayType( LLVMDIBuilderRef Dref , uint64_t SizeInBits , uint64_t AlignInBits , LLVMMetadataRef ElementType , LLVMMetadataRef Subscripts ) { DIBuilder *D = unwrap( Dref ); DICompositeType* CT = D->createArrayType( SizeInBits , AlignInBits , unwrap( ElementType ) , DINodeArray( unwrap( Subscripts ) ) ); return wrap( CT ); } LLVMMetadataRef LLVMDIBuilderCreateVectorType( LLVMDIBuilderRef Dref , uint64_t SizeInBits , uint64_t AlignInBits , LLVMMetadataRef ElementType , LLVMMetadataRef Subscripts ) { DIBuilder *D = unwrap( Dref ); DICompositeType* CT = D->createVectorType( SizeInBits , AlignInBits , unwrap( ElementType ) , DINodeArray( unwrap( Subscripts ) ) ); return wrap( CT ); } LLVMMetadataRef LLVMDIBuilderCreateTypedef( LLVMDIBuilderRef Dref , LLVMMetadataRef Ty , const char *Name , LLVMMetadataRef File , unsigned Line , LLVMMetadataRef Context ) { DIBuilder *D = unwrap( Dref ); DIDerivedType* DT = D->createTypedef( Ty ? unwrap( Ty ) : nullptr , Name , File ? unwrap( File ) : nullptr , Line , Context ? unwrap( Context ) : nullptr ); return wrap( DT ); } LLVMMetadataRef LLVMDIBuilderGetOrCreateSubrange( LLVMDIBuilderRef Dref , int64_t Lo , int64_t Count ) { DIBuilder *D = unwrap( Dref ); DISubrange* S = D->getOrCreateSubrange( Lo, Count ); return wrap( S ); } LLVMMetadataRef LLVMDIBuilderGetOrCreateArray( LLVMDIBuilderRef Dref , LLVMMetadataRef *Data , size_t Length ) { DIBuilder *D = unwrap( Dref ); Metadata **DataValue = unwrap( Data ); ArrayRef Elements( DataValue, Length ); DINodeArray A = D->getOrCreateArray( Elements ); return wrap( A.get( ) ); } LLVMMetadataRef LLVMDIBuilderGetOrCreateTypeArray( LLVMDIBuilderRef Dref , LLVMMetadataRef *Data , size_t Length ) { DIBuilder *D = unwrap( Dref ); Metadata **DataValue = unwrap( Data ); ArrayRef Elements( DataValue, Length ); DITypeRefArray A = D->getOrCreateTypeArray( Elements ); return wrap( A.get( ) ); } LLVMMetadataRef LLVMDIBuilderCreateExpression( LLVMDIBuilderRef Dref , int64_t *Addr , size_t Length ) { DIBuilder *D = unwrap( Dref ); DIExpression* Expr = D->createExpression( ArrayRef( Addr, Length ) ); return wrap( Expr ); } LLVMValueRef LLVMDIBuilderInsertDeclareAtEnd( LLVMDIBuilderRef Dref , LLVMValueRef Storage , LLVMMetadataRef VarInfo , LLVMMetadataRef Expr , LLVMMetadataRef diLocation , LLVMBasicBlockRef Block ) { DIBuilder *D = unwrap( Dref ); Instruction *Instr = D->insertDeclare( unwrap( Storage ) , unwrap( VarInfo ) , unwrap( Expr ) , unwrap( diLocation ) , unwrap( Block ) ); return wrap( Instr ); } LLVMValueRef LLVMDIBuilderInsertValueAtEnd( LLVMDIBuilderRef Dref , LLVMValueRef Val , uint64_t Offset , LLVMMetadataRef VarInfo , LLVMMetadataRef Expr , LLVMMetadataRef diLocation , LLVMBasicBlockRef Block ) { DIBuilder *D = unwrap( Dref ); Instruction *Instr = D->insertDbgValueIntrinsic( unwrap( Val ) , Offset , unwrap( VarInfo ) , unwrap( Expr ) , unwrap( diLocation ) , unwrap( Block ) ); return wrap( Instr ); } LLVMMetadataRef LLVMDIBuilderCreateEnumerationType( LLVMDIBuilderRef Dref , LLVMMetadataRef Scope // DIScope , char const* Name , LLVMMetadataRef File // DIFile , unsigned LineNumber , uint64_t SizeInBits , uint64_t AlignInBits , LLVMMetadataRef Elements // DINodeArray , LLVMMetadataRef UnderlyingType // DIType , char const* UniqueId ) { DIBuilder* D = unwrap( Dref ); DICompositeType* type = D->createEnumerationType( unwrap( Scope ) , Name , File ? unwrap( File ) : nullptr , LineNumber , SizeInBits , AlignInBits , DINodeArray( unwrap( Elements ) ) , unwrap( UnderlyingType ) , UniqueId ); return wrap( type ); } /// createEnumerator - Create a single enumerator value. //DIEnumerator createEnumerator( StringRef Name, int64_t Val ); LLVMMetadataRef LLVMDIBuilderCreateEnumeratorValue( LLVMDIBuilderRef Dref, char const* Name, int64_t Val ) { DIBuilder* D = unwrap( Dref ); DIEnumerator* enumerator = D->createEnumerator( Name, Val ); return wrap( enumerator ); } LLVMDwarfTag LLVMDIDescriptorGetTag( LLVMMetadataRef descriptor ) { DINode* desc = unwrap( descriptor ); return ( LLVMDwarfTag )desc->getTag( ); } LLVMMetadataRef LLVMDIBuilderCreateGlobalVariable( LLVMDIBuilderRef Dref , LLVMMetadataRef Context , char const* Name , char const* LinkageName , LLVMMetadataRef File // DIFile , unsigned LineNo , LLVMMetadataRef Ty //DITypeRef , LLVMBool isLocalToUnit , LLVMValueRef Val , LLVMMetadataRef Decl // = nullptr ) { DIBuilder* D = unwrap( Dref ); DIGlobalVariable* globalVar = D->createGlobalVariable( unwrap( Context ) , Name , LinkageName , File ? unwrap( File ) : nullptr , LineNo , unwrap( Ty ) , isLocalToUnit , unwrap( Val ) , Decl ? unwrap( Decl ) : nullptr ); return wrap( globalVar ); } LLVMValueRef LLVMDIBuilderInsertDeclareBefore( LLVMDIBuilderRef Dref , LLVMValueRef Storage // Value , LLVMMetadataRef VarInfo // DIVariable , LLVMMetadataRef Expr // DIExpression , LLVMMetadataRef diLocation // DILocation , LLVMValueRef InsertBefore // Instruction ) { DIBuilder* D = unwrap( Dref ); Instruction* pInstruction = D->insertDeclare( unwrap( Storage ) , unwrap( VarInfo ) , unwrap( Expr ) , unwrap( diLocation ) , unwrap( InsertBefore ) ); return wrap( pInstruction ); } LLVMValueRef LLVMDIBuilderInsertValueBefore( LLVMDIBuilderRef Dref , /*llvm::Value **/LLVMValueRef Val , uint64_t Offset , /*DILocalVariable **/ LLVMMetadataRef VarInfo , /*DIExpression **/ LLVMMetadataRef Expr , /*const DILocation **/ LLVMMetadataRef DL , /*Instruction **/ LLVMValueRef InsertBefore ) { DIBuilder* D = unwrap( Dref ); Instruction* pInstruction = D->insertDbgValueIntrinsic( unwrap( Val ) , Offset , unwrap( VarInfo ) , unwrap( Expr ) , unwrap( DL ) , unwrap( InsertBefore ) ); return wrap( pInstruction ); } char const* LLVMMetadataAsString( LLVMMetadataRef descriptor ) { std::string Messages; raw_string_ostream Msg( Messages ); Metadata* d = unwrap( descriptor ); d->print( Msg ); return LLVMCreateMessage( Msg.str( ).c_str( ) ); } void LLVMMDNodeReplaceAllUsesWith( LLVMMetadataRef oldDescriptor, LLVMMetadataRef newDescriptor ) { MDNode* o = unwrap( oldDescriptor ); Metadata* n = unwrap( newDescriptor ); o->replaceAllUsesWith( n ); } LLVMMetadataRef LLVMDILocation( LLVMContextRef context, unsigned Line, unsigned Column, LLVMMetadataRef scope, LLVMMetadataRef InlinedAt ) { DILocation* pLoc = DILocation::get( *unwrap( context ) , Line , Column , unwrap( scope ) , InlinedAt ? unwrap( InlinedAt ) : nullptr ); return wrap( pLoc ); } LLVMBool LLVMSubProgramDescribes( LLVMMetadataRef subProgram, LLVMValueRef /*const Function **/F ) { DISubprogram* pSub = unwrap( subProgram ); return pSub->describes( unwrap( F ) ); } LLVMMetadataRef LLVMDIBuilderCreateNamespace( LLVMDIBuilderRef Dref, LLVMMetadataRef scope, char const* name, LLVMMetadataRef file, unsigned line ) { DIBuilder* D = unwrap( Dref ); DINamespace* pNamespace = D->createNameSpace( scope ? unwrap( scope ) : nullptr , name , file ? unwrap( file ) : nullptr , line ); return wrap( pNamespace ); } LLVMMetadataKind LLVMGetMetadataID( LLVMMetadataRef /*Metadata*/ md ) { Metadata* pMetadata = unwrap( md ); return ( LLVMMetadataKind )pMetadata->getMetadataID( ); } uint32_t LLVMMDNodeGetNumOperands( LLVMMetadataRef /*MDNode*/ node ) { MDNode* pNode = unwrap( node ); return pNode->getNumOperands( ); } LLVMMDOperandRef LLVMMDNodeGetOperand( LLVMMetadataRef /*MDNode*/ node, uint32_t index ) { MDNode* pNode = unwrap( node ); return wrap( &pNode->getOperand( index ) ); } LLVMMetadataRef LLVMGetOperandNode( LLVMMDOperandRef operand ) { MDOperand const* pOperand = unwrap( operand ); return wrap( pOperand->get( ) ); } /*DISubProgram*/ LLVMMetadataRef LLVMDILocalScopeGetSubProgram( LLVMMetadataRef /*DILocalScope*/ localScope ) { DILocalScope* pScope = unwrap( localScope ); return wrap( pScope->getSubprogram( ) ); } } ================================================ FILE: Zelig/Zelig/CompileTime/Llvm.NET/LibLLVM/DIBuilderBindings.h ================================================ //===- DIBuilderBindings.h - Bindings for DIBuilder -------------*- C++ -*-===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // This file defines C bindings for the DIBuilder class. // //===----------------------------------------------------------------------===// // This file was adapted from the GO language bindings provided in standard LLVM Distribution #ifndef LLVM_BINDINGS_LLVM_DIBUILDERBINDINGS_H #define LLVM_BINDINGS_LLVM_DIBUILDERBINDINGS_H #include #include "IRBindings.h" #include "llvm-c/Core.h" #ifdef __cplusplus extern "C" { #endif enum LLVMDwarfTag { LLVMDwarfTagArrayType = 0x01, LLVMDwarfTagCLassType = 0x02, LLVMDwarfTagEntryPoint = 0x03, LLVMDwarfTagEnumerationType = 0x04, LLVMDwarfTagFormalParameter = 0x05, LLVMDwarfTagImportedDeclaration = 0x08, LLVMDwarfTagLabel = 0x0a, LLVMDwarfTagLexicalBlock = 0x0b, LLVMDwarfTagMember = 0x0d, LLVMDwarfTagPointerType = 0x0f, LLVMDwarfTagReferenceType = 0x10, LLVMDwarfTagCompileUnit = 0x11, LLVMDwarfTagStringType = 0x12, LLVMDwarfTagStructureType = 0x13, LLVMDwarfTagSubroutineType = 0x15, LLVMDwarfTagTypeDef = 0x16, LLVMDwarfTagUnionType = 0x17, LLVMDwarfTagUnspecifiedParameters = 0x18, LLVMDwarfTagVariant = 0x19, LLVMDwarfTagCommonBlock = 0x1a, LLVMDwarfTagCommonInclusion = 0x1b, LLVMDwarfTagInheritance = 0x1c, LLVMDwarfTagInlinedSubroutine = 0x1d, LLVMDwarfTagModule = 0x1e, LLVMDwarfTagPtrToMemberType = 0x1f, LLVMDwarfTagSetType = 0x20, LLVMDwarfTagSubrangeType = 0x21, LLVMDwarfTagWithStatement = 0x22, LLVMDwarfTagAccessDeclaration = 0x23, LLVMDwarfTagBaseType = 0x24, LLVMDwarfTagCatchBlock = 0x25, LLVMDwarfTagConstType = 0x26, LLVMDwarfTagConstant = 0x27, LLVMDwarfTagEnumerator = 0x28, LLVMDwarfTagFileType = 0x29, LLVMDwarfTagFriend = 0x2a, LLVMDwarfTagNameList = 0x2b, LLVMDwarfTagNameListItem = 0x2c, LLVMDwarfTagPackedType = 0x2d, LLVMDwarfTagSubProgram = 0x2e, LLVMDwarfTagTemplateTypeParameter = 0x2f, LLVMDwarfTagTemplateValueParameter = 0x30, LLVMDwarfTagThrownType = 0x31, LLVMDwarfTagTryBlock = 0x32, LLVMDwarfTagVariantPart = 0x33, LLVMDwarfTagVariable = 0x34, LLVMDwarfTagVolatileType = 0x35, LLVMDwarfTagDwarfProcedure = 0x36, LLVMDwarfTagRestrictType = 0x37, LLVMDwarfTagInterfaceType = 0x38, LLVMDwarfTagNamespace = 0x39, LLVMDwarfTagImportedModule = 0x3a, LLVMDwarfTagUnspecifiedType = 0x3b, LLVMDwarfTagPartialUnit = 0x3c, LLVMDwarfTagImportedUnit = 0x3d, LLVMDwarfTagCondition = 0x3f, LLVMDwarfTagSharedType = 0x40, LLVMDwarfTagTypeUnit = 0x41, LLVMDwarfTagRValueReferenceType = 0x42, LLVMDwarfTagTemplateAlias = 0x43, // New in DWARF 5: LLVMDwarfTagCoArrayType = 0x44, LLVMDwarfTagGenericSubrange = 0x45, LLVMDwarfTagDynamicType = 0x46, LLVMDwarfTagMipsLoop = 0x4081, LLVMDwarfTagFormatLabel = 0x4101, LLVMDwarfTagFunctionTemplate = 0x4102, LLVMDwarfTagClassTemplate = 0x4103, LLVMDwarfTagGnuTemplateTemplateParam = 0x4106, LLVMDwarfTagGnuTemplateParameterPack = 0x4107, LLVMDwarfTagGnuFormalParameterPack = 0x4108, LLVMDwarfTagLoUser = 0x4080, LLVMDwarfTagAppleProperty = 0x4200, LLVMDwarfTagHiUser = 0xffff }; // This should match the MetaDataKind enum in the C++ headers enum LLVMMetadataKind { LLVMMetadaKindMDTuple, LLVMMetadaKindDILocation, LLVMMetadaKindGenericDINode, LLVMMetadaKindDISubrange, LLVMMetadaKindDIEnumerator, LLVMMetadaKindDIBasicType, LLVMMetadaKindDIDerivedType, LLVMMetadaKindDICompositeType, LLVMMetadaKindDISubroutineType, LLVMMetadaKindDIFile, LLVMMetadaKindDICompileUnit, LLVMMetadaKindDISubprogram, LLVMMetadaKindDILexicalBlock, LLVMMetadaKindDILexicalBlockFile, LLVMMetadaKindDINamespace, LLVMMetadaKindDIModule, LLVMMetadaKindDITemplateTypeParameter, LLVMMetadaKindDITemplateValueParameter, LLVMMetadaKindDIGlobalVariable, LLVMMetadaKindDILocalVariable, LLVMMetadaKindDIExpression, LLVMMetadaKindDIObjCProperty, LLVMMetadaKindDIImportedEntity, LLVMMetadaKindConstantAsMetadata, LLVMMetadaKindLocalAsMetadata, LLVMMetadaKindMDString }; enum LLVMMetadataFormat { LLVMMetadataFormatDefault, LLVMMetadataFormatAsOperand, }; typedef struct LLVMOpaqueDIBuilder *LLVMDIBuilderRef; void LLVMSetDILocation( LLVMValueRef inst, LLVMMetadataRef location ); void LLVMSetDebugLoc( LLVMValueRef inst, unsigned line, unsigned column, LLVMMetadataRef scope ); LLVMMetadataRef /*DILocalScope*/ LLVMGetDILocationScope( LLVMMetadataRef /*DILocation*/ location ); unsigned LLVMGetDILocationLine( LLVMMetadataRef /*DILocation*/ location ); unsigned LLVMGetDILocationColumn( LLVMMetadataRef /*DILocation*/ location ); LLVMMetadataRef /*DILocation*/ LLVMGetDILocationInlinedAt( LLVMMetadataRef /*DILocation*/ location ); LLVMMetadataRef /*DILocalScope*/ LLVMDILocationGetInlinedAtScope( LLVMMetadataRef /*DILocation*/ location ); LLVMDIBuilderRef LLVMNewDIBuilder( LLVMModuleRef m, LLVMBool allowUnresolved ); void LLVMDIBuilderDestroy( LLVMDIBuilderRef d ); void LLVMDIBuilderFinalize( LLVMDIBuilderRef d ); LLVMMetadataRef LLVMDIBuilderCreateCompileUnit( LLVMDIBuilderRef D , unsigned Language , const char *File , const char *Dir , const char *Producer , int Optimized , const char *Flags , unsigned RuntimeVersion ); LLVMMetadataRef LLVMDIBuilderCreateFile( LLVMDIBuilderRef D , const char *File , const char *Dir ); LLVMMetadataRef LLVMDIBuilderCreateLexicalBlock( LLVMDIBuilderRef D , LLVMMetadataRef Scope , LLVMMetadataRef File , unsigned Line , unsigned Column ); LLVMMetadataRef LLVMDIBuilderCreateLexicalBlockFile( LLVMDIBuilderRef D , LLVMMetadataRef Scope , LLVMMetadataRef File , unsigned Discriminator ); LLVMMetadataRef LLVMDIBuilderCreateFunction( LLVMDIBuilderRef D , LLVMMetadataRef Scope , const char *Name , const char *LinkageName , LLVMMetadataRef File , unsigned Line , LLVMMetadataRef CompositeType , int IsLocalToUnit , int IsDefinition , unsigned ScopeLine , unsigned Flags , int IsOptimized , LLVMMetadataRef /*DITemplateParameterArray*/ TParams /*= nullptr*/ , LLVMMetadataRef /*DISubProgram */ Decl /*= nullptr*/ ); LLVMMetadataRef LLVMDIBuilderCreateTempFunctionFwdDecl( LLVMDIBuilderRef D , LLVMMetadataRef /*DIScope* */Scope , char const* Name , char const* LinkageName , LLVMMetadataRef /*DIFile* */ File , unsigned LineNo , LLVMMetadataRef /*DISubroutineType* */ Ty , bool isLocalToUnit , bool isDefinition , unsigned ScopeLine , unsigned Flags /*= 0*/ , bool isOptimized /*= false*/ , LLVMMetadataRef /*DITemplateParameterArray*/ TParams /*= nullptr*/ , LLVMMetadataRef /*DISubProgram */ Decl /*= nullptr*/ ); LLVMMetadataRef LLVMDIBuilderCreateAutoVariable( LLVMDIBuilderRef D , LLVMMetadataRef Scope , const char *Name , LLVMMetadataRef File , unsigned Line , LLVMMetadataRef Ty , int AlwaysPreserve , unsigned Flags ); LLVMMetadataRef LLVMDIBuilderCreateParameterVariable( LLVMDIBuilderRef D , LLVMMetadataRef Scope , const char *Name , unsigned ArgNo , LLVMMetadataRef File , unsigned Line , LLVMMetadataRef Ty , int AlwaysPreserve , unsigned Flags ); LLVMMetadataRef LLVMDIBuilderCreateBasicType( LLVMDIBuilderRef D , const char *Name , uint64_t SizeInBits , uint64_t AlignInBits , unsigned Encoding ); LLVMMetadataRef LLVMDIBuilderCreatePointerType( LLVMDIBuilderRef D , LLVMMetadataRef PointeeType , uint64_t SizeInBits , uint64_t AlignInBits , const char *Name ); LLVMMetadataRef LLVMDIBuilderCreateQualifiedType( LLVMDIBuilderRef D , uint32_t Tag , LLVMMetadataRef BaseType ); LLVMMetadataRef LLVMDIBuilderCreateSubroutineType( LLVMDIBuilderRef D , LLVMMetadataRef ParameterTypes , unsigned Flags ); LLVMMetadataRef LLVMDIBuilderCreateStructType( LLVMDIBuilderRef D , LLVMMetadataRef Scope , const char *Name , LLVMMetadataRef File , unsigned Line , uint64_t SizeInBits , uint64_t AlignInBits , unsigned Flags , LLVMMetadataRef DerivedFrom , LLVMMetadataRef ElementTypes ); LLVMMetadataRef LLVMDIBuilderCreateReplaceableCompositeType( LLVMDIBuilderRef D , unsigned Tag , const char *Name , LLVMMetadataRef Scope , LLVMMetadataRef File , unsigned Line , unsigned RuntimeLang , uint64_t SizeInBits , uint64_t AlignInBits , unsigned Flags ); LLVMMetadataRef LLVMDIBuilderCreateMemberType( LLVMDIBuilderRef D , LLVMMetadataRef Scope , const char *Name , LLVMMetadataRef File , unsigned Line , uint64_t SizeInBits , uint64_t AlignInBits , uint64_t OffsetInBits , unsigned Flags , LLVMMetadataRef Ty ); LLVMMetadataRef LLVMDIBuilderCreateArrayType( LLVMDIBuilderRef D , uint64_t SizeInBits , uint64_t AlignInBits , LLVMMetadataRef ElementType , LLVMMetadataRef Subscripts ); LLVMMetadataRef LLVMDIBuilderCreateVectorType( LLVMDIBuilderRef D , uint64_t SizeInBits , uint64_t AlignInBits , LLVMMetadataRef ElementType , LLVMMetadataRef Subscripts ); LLVMMetadataRef LLVMDIBuilderCreateTypedef( LLVMDIBuilderRef D , LLVMMetadataRef Ty , const char *Name , LLVMMetadataRef File , unsigned Line , LLVMMetadataRef Context ); LLVMMetadataRef LLVMDIBuilderGetOrCreateSubrange( LLVMDIBuilderRef D , int64_t Lo , int64_t Count ); LLVMMetadataRef LLVMDIBuilderGetOrCreateArray( LLVMDIBuilderRef D , LLVMMetadataRef *Data , size_t Length ); LLVMMetadataRef LLVMDIBuilderGetOrCreateTypeArray( LLVMDIBuilderRef D , LLVMMetadataRef *Data , size_t Length ); LLVMMetadataRef LLVMDIBuilderCreateExpression( LLVMDIBuilderRef Dref , int64_t *Addr , size_t Length ); LLVMValueRef LLVMDIBuilderInsertDeclareAtEnd( LLVMDIBuilderRef D , LLVMValueRef Storage , LLVMMetadataRef VarInfo , LLVMMetadataRef Expr , LLVMMetadataRef diLocation , LLVMBasicBlockRef Block ); LLVMValueRef LLVMDIBuilderInsertValueAtEnd( LLVMDIBuilderRef D , LLVMValueRef Val , uint64_t Offset , LLVMMetadataRef VarInfo , LLVMMetadataRef Expr , LLVMMetadataRef diLocation , LLVMBasicBlockRef Block ); /// createEnumerationType - Create debugging information entry for an /// enumeration. /// @param Scope Scope in which this enumeration is defined. /// @param Name Union name. /// @param File File where this member is defined. /// @param LineNumber Line number. /// @param SizeInBits Member size. /// @param AlignInBits Member alignment. /// @param Elements Enumeration elements. /// @param UnderlyingType Underlying type of a C++11/ObjC fixed enum. /// @param UniqueIdentifier A unique identifier for the enum. LLVMMetadataRef LLVMDIBuilderCreateEnumerationType( LLVMDIBuilderRef D , LLVMMetadataRef Scope // DIScope , char const* Name , LLVMMetadataRef File // DIFile , unsigned LineNumber , uint64_t SizeInBits , uint64_t AlignInBits , LLVMMetadataRef Elements // DIArray , LLVMMetadataRef UnderlyingType // DIType , char const* ); /// createEnumerator - Create a single enumerator value. //DIEnumerator createEnumerator( StringRef Name, int64_t Val ); LLVMMetadataRef LLVMDIBuilderCreateEnumeratorValue( LLVMDIBuilderRef D, char const* Name, int64_t Val ); /// createGlobalVariable - Create a new descriptor for the specified /// variable. /// @param Context Variable scope. /// @param Name Name of the variable. /// @param LinkageName Mangled name of the variable. /// @param File File where this variable is defined. /// @param LineNo Line number. /// @param Ty Variable Type. /// @param isLocalToUnit Boolean flag indicate whether this variable is /// externally visible or not. /// @param Val llvm::Value of the variable. /// @param Decl Reference to the corresponding declaration. /*DIGlobalVariable*/ LLVMMetadataRef LLVMDIBuilderCreateGlobalVariable( LLVMDIBuilderRef D , LLVMMetadataRef Context , char const* Name , char const* LinkageName , LLVMMetadataRef File // DIFile , unsigned LineNo , LLVMMetadataRef Ty //DITypeRef , LLVMBool isLocalToUnit , LLVMValueRef Val , LLVMMetadataRef Decl // = nullptr ); LLVMDwarfTag LLVMDIDescriptorGetTag( LLVMMetadataRef descriptor ); /// insertDeclare - Insert a new llvm.dbg.declare intrinsic call. /// @param Storage llvm::Value of the variable /// @param VarInfo Variable's debug info descriptor. /// @param Expr A complex location expression. /// @param InsertBefore Location for the new intrinsic. /*Instruction */ LLVMValueRef LLVMDIBuilderInsertDeclareBefore( LLVMDIBuilderRef Dref , LLVMValueRef Storage // Value , LLVMMetadataRef VarInfo // DIVariable , LLVMMetadataRef Expr // DIExpression , LLVMMetadataRef diLocation , LLVMValueRef InsertBefore // Instruction ); /// Insert a new llvm.dbg.value intrinsic call. /// \param Val llvm::Value of the variable /// \param Offset Offset /// \param VarInfo Variable's debug info descriptor. /// \param Expr A complex location expression. /// \param DL Debug info location. /// \param InsertBefore Location for the new intrinsic. /*Instruction **/ LLVMValueRef LLVMDIBuilderInsertValueBefore( LLVMDIBuilderRef Dref , /*llvm::Value **/LLVMValueRef Val , uint64_t Offset , /*DILocalVariable **/ LLVMMetadataRef VarInfo , /*DIExpression **/ LLVMMetadataRef Expr , /*const DILocation **/ LLVMMetadataRef DL , /*Instruction **/ LLVMValueRef InsertBefore ); // caller must call LLVMDisposeMessage() on the returned string char const* LLVMMetadataAsString( LLVMMetadataRef descriptor ); void LLVMMDNodeReplaceAllUsesWith( LLVMMetadataRef oldDescriptor, LLVMMetadataRef newDescriptor ); LLVMMetadataRef LLVMDILocation( LLVMContextRef context, unsigned Line, unsigned Column, LLVMMetadataRef scope, LLVMMetadataRef InlinedAt ); LLVMBool LLVMSubProgramDescribes( LLVMMetadataRef subProgram, LLVMValueRef /*const Function **/F ); LLVMMetadataRef LLVMDIBuilderCreateNamespace( LLVMDIBuilderRef Dref, LLVMMetadataRef scope, char const* name, LLVMMetadataRef file, unsigned line ); LLVMContextRef LLVMGetNodeContext( LLVMMetadataRef /*MDNode*/ node ); LLVMMetadataKind LLVMGetMetadataID( LLVMMetadataRef /*Metadata*/ md ); uint32_t LLVMMDNodeGetNumOperands( LLVMMetadataRef /*MDNode*/ node ); LLVMMDOperandRef LLVMMDNodeGetOperand( LLVMMetadataRef /*MDNode*/ node, uint32_t index ); LLVMMetadataRef LLVMGetOperandNode( LLVMMDOperandRef operand ); /*DISubProgram*/ LLVMMetadataRef LLVMDILocalScopeGetSubProgram( LLVMMetadataRef /*DILocalScope*/ localScope ); #ifdef __cplusplus } // extern "C" #endif #endif ================================================ FILE: Zelig/Zelig/CompileTime/Llvm.NET/LibLLVM/DITypeBindings.cpp ================================================ #include "DITypeBindings.h" #include "llvm/IR/DIBuilder.h" #include "llvm/IR/IRBuilder.h" #include "llvm/IR/Module.h" #include "llvm/IR/Constant.h" #include "llvm/Support/raw_ostream.h" using namespace llvm; extern "C" { unsigned LLVMDITypeGetLine( LLVMMetadataRef typeRef ) { DIType* pType = unwrap( typeRef ); return pType->getLine( ); } uint64_t LLVMDITypeGetSizeInBits( LLVMMetadataRef typeRef ) { DIType* pType = unwrap( typeRef ); return pType->getSizeInBits( ); } uint64_t LLVMDITypeGetAlignInBits( LLVMMetadataRef typeRef ) { DIType* pType = unwrap( typeRef ); return pType->getAlignInBits( ); } uint64_t LLVMDITypeGetOffsetInBits( LLVMMetadataRef typeRef ) { DIType* pType = unwrap( typeRef ); return pType->getOffsetInBits( ); } unsigned LLVMDITypeGetFlags( LLVMMetadataRef typeRef ) { DIType* pType = unwrap( typeRef ); return pType->getFlags( ); } LLVMMetadataRef LLVMDITypeGetScope( LLVMMetadataRef typeRef ) { DIType* pType = unwrap( typeRef ); return wrap( pType->getScope( ) ); } char const* LLVMDITypeGetName( LLVMMetadataRef typeRef ) { DIType* pType = unwrap( typeRef ); return pType->getName( ).data( ); } LLVMMetadataRef LLVMDIScopeGetFile( LLVMMetadataRef scopeRef ) { DIScope* pType = unwrap( scopeRef ); return wrap( pType->getFile() ); } } ================================================ FILE: Zelig/Zelig/CompileTime/Llvm.NET/LibLLVM/DITypeBindings.h ================================================ #ifndef LLVM_BINDINGS_LLVM_DITYPEBINDINGS_H #define LLVM_BINDINGS_LLVM_DITYPEBINDINGS_H #include "IRBindings.h" #include "llvm-c/Core.h" #ifdef __cplusplus extern "C" { #endif unsigned LLVMDITypeGetLine( LLVMMetadataRef typeRef ); uint64_t LLVMDITypeGetSizeInBits( LLVMMetadataRef typeRef ); uint64_t LLVMDITypeGetAlignInBits( LLVMMetadataRef typeRef ); uint64_t LLVMDITypeGetOffsetInBits( LLVMMetadataRef typeRef ); unsigned LLVMDITypeGetFlags( LLVMMetadataRef typeRef ); LLVMMetadataRef LLVMDITypeGetScope( LLVMMetadataRef typeRef ); char const* LLVMDITypeGetName( LLVMMetadataRef typeRef ); LLVMMetadataRef LLVMDIScopeGetFile( LLVMMetadataRef typeRef ); #ifdef __cplusplus } #endif #endif ================================================ FILE: Zelig/Zelig/CompileTime/Llvm.NET/LibLLVM/EXPORTS.DEF ================================================ EXPORTS ; extensions to standard LLVM-C API LLVMAddModuleFlag LLVMModuleGetModuleFlagsMetadata LLVMNamedMDNodeGetNumOperands LLVMNamedMDNodeGetOperand LLVMNamedMDNodeGetParentModule LLVMVerifyFunctionEx LLVMConstantAsMetadata LLVMMDString2 LLVMMDNode2 LLVMTemporaryMDNode LLVMAddNamedMetadataOperand2 LLVMSetMetadata2 LLVMMetadataReplaceAllUsesWith LLVMSetCurrentDebugLocation2 LLVMIsConstantZeroValue LLVMRemoveGlobalFromParent LLVMGetOrInsertFunction LLVMBuildIntCast2 LLVMGetValueID LLVMMetadataAsValue LLVMGetModuleName LLVMIsTemporary LLVMIsResolved LLVMIsUniqued LLVMIsDistinct LLVMGetMDStringText LLVMGetGlobalAlias LLVMGetAliasee LLVMMDNodeResolveCycles LLVMGetArgumentIndex LLVMGetVersionInfo LLVMFunctionHasPersonalityFunction ; Debug info functions not part of standard LLVM-C API LLVMDIScopeGetFile LLVMFunctionGetSubprogram LLVMFunctionSetSubprogram LLVMGetMetadataID LLVMGetNodeContext LLVMGetDIFileName LLVMGetDIFileDirectory LLVMGetDILocationScope LLVMGetDILocationLine LLVMGetDILocationColumn LLVMGetDILocationInlinedAt LLVMDILocationGetInlinedAtScope LLVMSetDILocation LLVMSetDebugLoc LLVMNewDIBuilder LLVMDIBuilderDestroy LLVMDIBuilderFinalize LLVMDIBuilderCreateCompileUnit LLVMDIBuilderCreateFile LLVMDIBuilderCreateLexicalBlock LLVMDIBuilderCreateLexicalBlockFile LLVMDIBuilderCreateFunction LLVMDIBuilderCreateTempFunctionFwdDecl LLVMDIBuilderCreateAutoVariable LLVMDIBuilderCreateParameterVariable LLVMDIBuilderCreateBasicType LLVMDIBuilderCreatePointerType LLVMDIBuilderCreateQualifiedType LLVMDIBuilderCreateSubroutineType LLVMDIBuilderCreateStructType LLVMDIBuilderCreateReplaceableCompositeType LLVMDIBuilderCreateMemberType LLVMDIBuilderCreateArrayType LLVMDIBuilderCreateVectorType LLVMDIBuilderCreateTypedef LLVMDIBuilderGetOrCreateSubrange LLVMDIBuilderGetOrCreateArray LLVMDIBuilderGetOrCreateTypeArray LLVMDIBuilderCreateExpression LLVMDIBuilderInsertDeclareAtEnd LLVMDIBuilderInsertValueAtEnd LLVMDIBuilderCreateEnumerationType LLVMDIBuilderCreateEnumeratorValue LLVMDIDescriptorGetTag LLVMDIBuilderCreateGlobalVariable LLVMDIBuilderInsertDeclareBefore LLVMDIBuilderInsertValueBefore LLVMDIBuilderCreateNamespace LLVMMetadataAsString LLVMMDNodeReplaceAllUsesWith LLVMDILocation LLVMSubProgramDescribes LLVMDITypeGetLine LLVMDITypeGetSizeInBits LLVMDITypeGetAlignInBits LLVMDITypeGetOffsetInBits LLVMDITypeGetFlags LLVMDITypeGetScope LLVMDITypeGetName LLVMMDNodeGetNumOperands LLVMMDNodeGetOperand LLVMGetOperandNode LLVMDILocalScopeGetSubProgram ; AttributeSet manipulation LLVMCreateEmptyAttributeSet LLVMCreateAttributeSetFromKindArray LLVMCreateAttributeSetFromAttributeSetArray LLVMCreateAttributeSetFromBuilder LLVMAttributeSetAddKind LLVMAttributeSetAddString LLVMAttributeSetAddStringValue LLVMAttributeSetAddAttributes LLVMAttributeSetRemoveAttributeKind LLVMAttributeSetRemoveAttributeSet LLVMAttributeSetRemoveAttributeBuilder LLVMAttributeSetGetContext LLVMAttributeGetAttributes LLVMAttributeSetHasAttributeKind LLVMAttributeSetHasStringAttribute LLVMAttributeSetHasAttributes LLVMAttributeSetHasAttributeSomewhere LLVMAttributeSetGetAttributeByKind LLVMAttributeSetGetAttributeByName LLVMAttributeSetToString LLVMAttributeSetGetNumSlots LLVMAttributeSetGetSlotAttributes LLVMAttributeSetGetSlotIndex LLVMGetFunctionAttributeSet LLVMSetFunctionAttributeSet LLVMGetCallSiteAttributeSet LLVMSetCallSiteAttributeSet LLVMAttributeSetGetIteratorStartToken LLVMAttributeSetIteratorGetNext LLVMIsEnumAttribute LLVMIsIntAttribute LLVMIsStringAttribute LLVMHasAttributeKind LLVMHasAttributeString LLVMGetAttributeKind LLVMGetAttributeValue LLVMGetAttributeName LLVMGetAttributeStringValue LLVMAttributeToString LLVMCreateAttribute LVMCreateTargetDependentAttribute ;Attribute class wrappers LLVMIsEnumAttribute LLVMIsIntAttribute LLVMIsStringAttribute LLVMHasAttributeKind LLVMHasAttributeString LLVMGetAttributeKind LLVMGetAttributeValue LLVMGetAttributeName LLVMGetAttributeStringValue LLVMAttributeToString LLVMCreateAttribute LVMCreateTargetDependentAttribute LLVMCreateAttributeBuilder LLVMCreateAttributeBuilder2 LLVMCreateAttributeBuilder3 LLVMAttributeBuilderDispose LLVMAttributeBuilderClear LLVMAttributeBuilderAddEnum LLVMAttributeBuilderAddAttribute LLVMAttributeBuilderAddStringAttribute LLVMAttributeBuilderRemoveEnum LLVMAttributeBuilderRemoveAttributes LLVMAttributeBuilderRemoveAttribute LLVMAttributeBuilderRemoveBldr LLVMAttributeBuilderMerge LLVMAttributeBuilderOverlaps LLVMAttributeBuilderContainsEnum LLVMAttributeBuilderContainsName LLVMAttributeBuilderHasAnyAttributes LLVMAttributeBuilderHasAttributes LLVMAttributeBuilderHasTargetIndependentAttrs LLVMAttributeBuilderHasTargetDependentAttrs ; Instrumentation Bindings LLVMAddAddressSanitizerFunctionPass LLVMAddAddressSanitizerModulePass LLVMAddThreadSanitizerPass LLVMAddMemorySanitizerPass LLVMAddDataFlowSanitizerPass ; Redirecting to non-inlined functions for inlined LLVM-C APIs LLVMInitializeAllAsmParsers = LLVMInitializeAllAsmParsersExport LLVMInitializeAllAsmPrinters = LLVMInitializeAllAsmPrintersExport LLVMInitializeAllTargets = LLVMInitializeAllTargetsExport LLVMInitializeAllTargetMCs = LLVMInitializeAllTargetMCsExport LLVMInitializeAllDisassemblers = LLVMInitializeAllDisassemblersExport LLVMInitializeAllTargetInfos = LLVMInitializeAllTargetInfosExport LLVMInitializeNativeTarget = LLVMInitializeNativeTargetExport LLVMInitializeNativeAsmParser = LLVMInitializeNativeAsmParserExport LLVMInitializeNativeAsmPrinter = LLVMInitializeNativeAsmPrinterExport LLVMInitializeNativeDisassembler = LLVMInitializeNativeDisassemblerExport ;LTO APIs ;llvm_create_optimizer ;llvm_destroy_optimizer ;llvm_read_object_file ;llvm_optimize_modules ;lto_get_version ;lto_get_error_message ;lto_module_is_object_file ;lto_module_is_object_file_for_target ;lto_module_is_object_file_in_memory ;lto_module_is_object_file_in_memory_for_target ;lto_module_create ;lto_module_create_from_memory ;lto_module_create_from_memory_with_path ;lto_module_create_in_local_context ;lto_module_create_in_codegen_context ;lto_module_create_from_fd ;lto_module_create_from_fd_at_offset ;lto_module_dispose ;lto_module_get_target_triple ;lto_module_set_target_triple ;lto_module_get_num_symbols ;lto_module_get_symbol_name ;lto_module_get_symbol_attribute ;lto_module_get_num_deplibs ;lto_module_get_deplib ;lto_module_get_num_linkeropts ;lto_module_get_linkeropt ;lto_codegen_set_diagnostic_handler ;lto_codegen_create ;lto_codegen_create_in_local_context ;lto_codegen_dispose ;lto_codegen_add_module ;lto_codegen_set_debug_model ;lto_codegen_set_pic_model ;lto_codegen_set_cpu ;lto_codegen_set_assembler_path ;lto_codegen_set_assembler_args ;lto_codegen_add_must_preserve_symbol ;lto_codegen_write_merged_modules ;lto_codegen_compile ;lto_codegen_compile_to_file ;lto_codegen_debug_options ;lto_initialize_disassembler ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ; standard LLVM-C API exports ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; LLVMInitializeAArch64AsmParser LLVMInitializeAArch64AsmPrinter LLVMInitializeAArch64Target LLVMInitializeAArch64TargetMC LLVMInitializeAArch64Disassembler LLVMInitializeAArch64TargetInfo LLVMInitializeAnalysis LLVMVerifyFunction LLVMVerifyModule LLVMViewFunctionCFG LLVMViewFunctionCFGOnly LLVMInitializeARMAsmParser LLVMInitializeARMAsmPrinter LLVMInitializeARMTarget LLVMInitializeARMTargetMC LLVMInitializeARMDisassembler LLVMInitializeARMTargetInfo LLVMGetBitcodeModule LLVMGetBitcodeModuleInContext LLVMParseBitcode LLVMParseBitcodeInContext LLVMWriteBitcodeToFD LLVMWriteBitcodeToFile LLVMWriteBitcodeToFileHandle LLVMWriteBitcodeToMemoryBuffer LLVMInitializeCodeGen LLVMAddAlias LLVMAddCase LLVMAddClause LLVMAddDestination LLVMAddFunction LLVMAddGlobal LLVMAddGlobalInAddressSpace LLVMAddIncoming LLVMAddNamedMetadataOperand LLVMAlignOf LLVMAppendBasicBlock LLVMAppendBasicBlockInContext LLVMArrayType LLVMBasicBlockAsValue LLVMBlockAddress LLVMBuildAShr LLVMBuildAdd LLVMBuildAddrSpaceCast LLVMBuildAggregateRet LLVMBuildAlloca LLVMBuildAnd LLVMBuildArrayAlloca LLVMBuildArrayMalloc LLVMBuildAtomicCmpXchg LLVMBuildAtomicRMW LLVMBuildBinOp LLVMBuildBitCast LLVMBuildBr LLVMBuildCall LLVMBuildCast LLVMBuildCondBr LLVMBuildExactSDiv LLVMBuildExtractElement LLVMBuildExtractValue LLVMBuildFAdd LLVMBuildFCmp LLVMBuildFDiv LLVMBuildFMul LLVMBuildFNeg LLVMBuildFPCast LLVMBuildFPExt LLVMBuildFPToSI LLVMBuildFPToUI LLVMBuildFPTrunc LLVMBuildFRem LLVMBuildFSub LLVMBuildFence LLVMBuildFree LLVMBuildGEP LLVMBuildGlobalString LLVMBuildGlobalStringPtr LLVMBuildICmp LLVMBuildInBoundsGEP LLVMBuildIndirectBr LLVMBuildInsertElement LLVMBuildInsertValue LLVMBuildIntCast LLVMBuildIntToPtr LLVMBuildInvoke LLVMBuildIsNotNull LLVMBuildIsNull LLVMBuildLShr LLVMBuildLandingPad LLVMBuildLoad LLVMBuildMalloc LLVMBuildMul LLVMBuildNSWAdd LLVMBuildNSWMul LLVMBuildNSWNeg LLVMBuildNSWSub LLVMBuildNUWAdd LLVMBuildNUWMul LLVMBuildNUWNeg LLVMBuildNUWSub LLVMBuildNeg LLVMBuildNot LLVMBuildOr LLVMBuildPhi LLVMBuildPointerCast LLVMBuildPtrDiff LLVMBuildPtrToInt LLVMBuildResume LLVMBuildRet LLVMBuildRetVoid LLVMBuildSDiv LLVMBuildSExt LLVMBuildSExtOrBitCast LLVMBuildSIToFP LLVMBuildSRem LLVMBuildSelect LLVMBuildShl LLVMBuildShuffleVector LLVMBuildStore LLVMBuildStructGEP LLVMBuildSub LLVMBuildSwitch LLVMBuildTrunc LLVMBuildTruncOrBitCast LLVMBuildUDiv LLVMBuildUIToFP LLVMBuildURem LLVMBuildUnreachable LLVMBuildVAArg LLVMBuildXor LLVMBuildZExt LLVMBuildZExtOrBitCast LLVMClearInsertionPosition LLVMConstAShr LLVMConstAdd LLVMConstAddrSpaceCast LLVMConstAllOnes LLVMConstAnd LLVMConstArray LLVMConstBitCast LLVMConstExactSDiv LLVMConstExtractElement LLVMConstExtractValue LLVMConstFAdd LLVMConstFCmp LLVMConstFDiv LLVMConstFMul LLVMConstFNeg LLVMConstFPCast LLVMConstFPExt LLVMConstFPToSI LLVMConstFPToUI LLVMConstFPTrunc LLVMConstFRem LLVMConstFSub LLVMConstGEP LLVMConstICmp LLVMConstInBoundsGEP LLVMConstInlineAsm LLVMConstInsertElement LLVMConstInsertValue LLVMConstInt LLVMConstIntCast LLVMConstIntGetSExtValue LLVMConstIntGetZExtValue LLVMConstIntOfArbitraryPrecision LLVMConstIntOfString LLVMConstIntOfStringAndSize LLVMConstIntToPtr LLVMConstLShr LLVMConstMul LLVMConstNSWAdd LLVMConstNSWMul LLVMConstNSWNeg LLVMConstNSWSub LLVMConstNUWAdd LLVMConstNUWMul LLVMConstNUWNeg LLVMConstNUWSub LLVMConstNamedStruct LLVMConstNeg LLVMConstNot LLVMConstNull LLVMConstOr LLVMConstPointerCast LLVMConstPointerNull LLVMConstPtrToInt LLVMConstReal LLVMConstRealGetDouble LLVMConstRealOfString LLVMConstRealOfStringAndSize LLVMConstSDiv LLVMConstSExt LLVMConstSExtOrBitCast LLVMConstSIToFP LLVMConstSRem LLVMConstSelect LLVMConstShl LLVMConstShuffleVector LLVMConstString LLVMConstStringInContext LLVMConstStruct LLVMConstStructInContext LLVMConstSub LLVMConstTrunc LLVMConstTruncOrBitCast LLVMConstUDiv LLVMConstUIToFP LLVMConstURem LLVMConstVector LLVMConstXor LLVMConstZExt LLVMConstZExtOrBitCast LLVMContextCreate LLVMContextDispose LLVMContextSetDiagnosticHandler LLVMContextSetYieldCallback LLVMCountBasicBlocks LLVMCountIncoming LLVMCountParamTypes LLVMCountParams LLVMCountStructElementTypes LLVMCreateBuilder LLVMCreateBuilderInContext LLVMCreateFunctionPassManager LLVMCreateFunctionPassManagerForModule LLVMCreateMemoryBufferWithContentsOfFile LLVMCreateMemoryBufferWithMemoryRange LLVMCreateMemoryBufferWithMemoryRangeCopy LLVMCreateMemoryBufferWithSTDIN LLVMCreateMessage LLVMCreateModuleProviderForExistingModule LLVMCreatePassManager LLVMDeleteBasicBlock LLVMDeleteFunction LLVMDeleteGlobal LLVMDisposeBuilder LLVMDisposeMemoryBuffer LLVMDisposeMessage LLVMDisposeModule LLVMDisposeModuleProvider LLVMDisposePassManager LLVMDoubleType LLVMDoubleTypeInContext LLVMDumpModule LLVMDumpType LLVMDumpValue LLVMFP128Type LLVMFP128TypeInContext LLVMFinalizeFunctionPassManager LLVMFloatType LLVMFloatTypeInContext LLVMFunctionType LLVMGetAlignment LLVMGetArrayLength LLVMGetAsString LLVMGetBasicBlockParent LLVMGetBasicBlockTerminator LLVMGetBasicBlocks LLVMGetBufferSize LLVMGetBufferStart LLVMGetCondition LLVMGetConstOpcode LLVMGetCurrentDebugLocation LLVMGetDLLStorageClass LLVMGetDataLayout LLVMGetDiagInfoDescription LLVMGetDiagInfoSeverity LLVMGetElementAsConstant LLVMGetElementType LLVMGetEntryBasicBlock LLVMGetFCmpPredicate LLVMGetFirstBasicBlock LLVMGetFirstFunction LLVMGetFirstGlobal LLVMGetFirstInstruction LLVMGetFirstParam LLVMGetFirstUse LLVMGetFunctionCallConv LLVMGetGC LLVMGetGlobalContext LLVMGetGlobalParent LLVMGetGlobalPassRegistry LLVMGetICmpPredicate LLVMGetIncomingBlock LLVMGetIncomingValue LLVMGetInitializer LLVMGetInsertBlock LLVMGetInstructionCallConv LLVMGetInstructionOpcode LLVMGetInstructionParent LLVMGetIntTypeWidth LLVMGetIntrinsicID LLVMGetLastBasicBlock LLVMGetLastFunction LLVMGetLastGlobal LLVMGetLastInstruction LLVMGetLastParam LLVMGetLinkage LLVMGetMDKindID LLVMGetMDKindIDInContext LLVMGetMDNodeNumOperands LLVMGetMDNodeOperands LLVMGetMDString LLVMGetMetadata LLVMGetModuleContext LLVMGetNamedFunction LLVMGetNamedGlobal LLVMGetNamedMetadataNumOperands LLVMGetNamedMetadataOperands LLVMGetNextBasicBlock LLVMGetNextFunction LLVMGetNextGlobal LLVMGetNextInstruction LLVMGetNextParam LLVMGetNextUse LLVMGetNumOperands LLVMGetNumSuccessors LLVMGetOperand LLVMGetOperandUse LLVMGetParam LLVMGetParamParent LLVMGetParamTypes LLVMGetParams LLVMGetPersonalityFn LLVMGetPointerAddressSpace LLVMGetPreviousBasicBlock LLVMGetPreviousFunction LLVMGetPreviousGlobal LLVMGetPreviousInstruction LLVMGetPreviousParam LLVMGetReturnType LLVMGetSection LLVMGetStructElementTypes LLVMGetStructName LLVMGetSuccessor LLVMGetSwitchDefaultDest LLVMGetTarget LLVMGetThreadLocalMode LLVMGetTypeByName LLVMGetTypeContext LLVMGetTypeKind LLVMGetUndef LLVMGetUsedValue LLVMGetUser LLVMGetValueName LLVMGetVectorSize LLVMGetVisibility LLVMGetVolatile LLVMGetOrdering LLVMHalfType LLVMHalfTypeInContext LLVMHasMetadata LLVMHasUnnamedAddr LLVMInitializeCore LLVMInitializeFunctionPassManager LLVMInsertBasicBlock LLVMInsertBasicBlockInContext LLVMInsertIntoBuilder LLVMInsertIntoBuilderWithName LLVMInstructionClone LLVMInstructionEraseFromParent LLVMInt16Type LLVMInt16TypeInContext LLVMInt1Type LLVMInt1TypeInContext LLVMInt32Type LLVMInt32TypeInContext LLVMInt64Type LLVMInt64TypeInContext LLVMInt128Type LLVMInt128TypeInContext LLVMInt8Type LLVMInt8TypeInContext LLVMIntType LLVMIntTypeInContext LLVMIsAAddrSpaceCastInst LLVMIsAAllocaInst LLVMIsAArgument LLVMIsABasicBlock LLVMIsABinaryOperator LLVMIsABitCastInst LLVMIsABlockAddress LLVMIsABranchInst LLVMIsACallInst LLVMIsACastInst LLVMIsACmpInst LLVMIsAConstant LLVMIsAConstantAggregateZero LLVMIsAConstantArray LLVMIsAConstantDataArray LLVMIsAConstantDataSequential LLVMIsAConstantDataVector LLVMIsAConstantExpr LLVMIsAConstantFP LLVMIsAConstantInt LLVMIsAConstantPointerNull LLVMIsAConstantStruct LLVMIsAConstantVector LLVMIsADbgDeclareInst LLVMIsADbgInfoIntrinsic LLVMIsAExtractElementInst LLVMIsAExtractValueInst LLVMIsAFCmpInst LLVMIsAFPExtInst LLVMIsAFPToSIInst LLVMIsAFPToUIInst LLVMIsAFPTruncInst LLVMIsAFunction LLVMIsAGetElementPtrInst LLVMIsAGlobalAlias LLVMIsAGlobalObject LLVMIsAGlobalValue LLVMIsAGlobalVariable LLVMIsAICmpInst LLVMIsAIndirectBrInst LLVMIsAInlineAsm LLVMIsAInsertElementInst LLVMIsAInsertValueInst LLVMIsAInstruction LLVMIsAIntToPtrInst LLVMIsAIntrinsicInst LLVMIsAInvokeInst LLVMIsALandingPadInst LLVMIsALoadInst LLVMIsAMDNode LLVMIsAMDString LLVMIsAMemCpyInst LLVMIsAMemIntrinsic LLVMIsAMemMoveInst LLVMIsAMemSetInst LLVMIsAPHINode LLVMIsAPtrToIntInst LLVMIsAResumeInst LLVMIsAReturnInst LLVMIsASExtInst LLVMIsASIToFPInst LLVMIsASelectInst LLVMIsAShuffleVectorInst LLVMIsAStoreInst LLVMIsASwitchInst LLVMIsATerminatorInst LLVMIsATruncInst LLVMIsAUIToFPInst LLVMIsAUnaryInstruction LLVMIsAUndefValue LLVMIsAUnreachableInst LLVMIsAUser LLVMIsAVAArgInst LLVMIsAZExtInst LLVMIsConditional LLVMIsConstant LLVMIsConstantString LLVMIsDeclaration LLVMIsExternallyInitialized LLVMIsFunctionVarArg LLVMIsGlobalConstant LLVMIsMultithreaded LLVMIsNull LLVMIsOpaqueStruct LLVMIsPackedStruct LLVMIsTailCall LLVMIsThreadLocal LLVMIsUndef LLVMLabelType LLVMLabelTypeInContext LLVMMDNode LLVMMDNodeInContext LLVMMDString LLVMMDStringInContext LLVMModuleCreateWithName LLVMModuleCreateWithNameInContext LLVMMoveBasicBlockAfter LLVMMoveBasicBlockBefore LLVMPPCFP128Type LLVMPPCFP128TypeInContext LLVMPointerType LLVMPositionBuilder LLVMPositionBuilderAtEnd LLVMPositionBuilderBefore LLVMPrintModuleToFile LLVMPrintModuleToString LLVMPrintTypeToString LLVMPrintValueToString LLVMRemoveBasicBlockFromParent LLVMReplaceAllUsesWith LLVMRunFunctionPassManager LLVMRunPassManager LLVMSetAlignment LLVMSetCleanup LLVMSetCondition LLVMSetCurrentDebugLocation LLVMSetDLLStorageClass LLVMSetDataLayout LLVMSetExternallyInitialized LLVMSetFunctionCallConv LLVMSetGC LLVMSetGlobalConstant LLVMSetInitializer LLVMSetInstDebugLocation LLVMSetInstrParamAlignment LLVMSetInstructionCallConv LLVMSetLinkage LLVMSetMetadata LLVMSetModuleInlineAsm LLVMSetOperand LLVMSetParamAlignment LLVMSetPersonalityFn LLVMSetSection LLVMSetSuccessor LLVMSetTailCall LLVMSetTarget LLVMSetThreadLocal LLVMSetThreadLocalMode LLVMSetUnnamedAddr LLVMSetValueName LLVMSetVisibility LLVMSetVolatile LLVMSetOrdering LLVMShutdown LLVMSizeOf LLVMStartMultithreaded LLVMStopMultithreaded LLVMStructCreateNamed LLVMStructSetBody LLVMStructType LLVMStructTypeInContext LLVMTypeIsSized LLVMTypeOf LLVMValueAsBasicBlock LLVMValueIsBasicBlock LLVMVectorType LLVMVoidType LLVMVoidTypeInContext LLVMX86FP80Type LLVMX86FP80TypeInContext LLVMX86MMXType LLVMX86MMXTypeInContext LLVMInitializeCppBackendTarget LLVMInitializeCppBackendTargetInfo LLVMInitializeCppBackendTargetMC LLVMAddGlobalMapping LLVMAddModule LLVMCreateExecutionEngineForModule LLVMCreateGenericValueOfFloat LLVMCreateGenericValueOfInt LLVMCreateGenericValueOfPointer LLVMCreateInterpreterForModule LLVMCreateJITCompilerForModule LLVMCreateMCJITCompilerForModule LLVMCreateSimpleMCJITMemoryManager LLVMDisposeExecutionEngine LLVMDisposeGenericValue LLVMDisposeMCJITMemoryManager LLVMFindFunction LLVMFreeMachineCodeForFunction LLVMGenericValueIntWidth LLVMGenericValueToFloat LLVMGenericValueToInt LLVMGenericValueToPointer LLVMGetExecutionEngineTargetData LLVMGetExecutionEngineTargetMachine LLVMGetFunctionAddress LLVMGetGlobalValueAddress LLVMGetPointerToGlobal LLVMInitializeMCJITCompilerOptions LLVMRecompileAndRelinkFunction LLVMRemoveModule LLVMRunFunction LLVMRunFunctionAsMain LLVMRunStaticConstructors LLVMRunStaticDestructors LLVMInitializeHexagonAsmPrinter LLVMInitializeHexagonTarget LLVMInitializeHexagonTargetMC LLVMInitializeHexagonDisassembler LLVMInitializeHexagonTargetInfo LLVMInitializeInstCombine LLVMInitializeInstrumentation LLVMLinkInInterpreter LLVMInitializeIPA LLVMAddAlwaysInlinerPass LLVMAddArgumentPromotionPass LLVMAddConstantMergePass LLVMAddDeadArgEliminationPass LLVMAddFunctionAttrsPass LLVMAddFunctionInliningPass LLVMAddGlobalDCEPass LLVMAddGlobalOptimizerPass LLVMAddIPConstantPropagationPass LLVMAddIPSCCPPass LLVMAddInternalizePass LLVMAddPruneEHPass LLVMAddStripDeadPrototypesPass LLVMAddStripSymbolsPass LLVMInitializeIPO LLVMPassManagerBuilderCreate LLVMPassManagerBuilderDispose LLVMPassManagerBuilderPopulateFunctionPassManager LLVMPassManagerBuilderPopulateLTOPassManager LLVMPassManagerBuilderPopulateModulePassManager LLVMPassManagerBuilderSetDisableSimplifyLibCalls LLVMPassManagerBuilderSetDisableUnitAtATime LLVMPassManagerBuilderSetDisableUnrollLoops LLVMPassManagerBuilderSetOptLevel LLVMPassManagerBuilderSetSizeLevel LLVMPassManagerBuilderUseInlinerWithThreshold LLVMParseIRInContext LLVMLinkModules LLVMCreateDisasm LLVMCreateDisasmCPU LLVMCreateDisasmCPUFeatures LLVMDisasmDispose LLVMDisasmInstruction LLVMSetDisasmOptions LLVMLinkInMCJIT LLVMInitializeMipsAsmParser LLVMInitializeMipsAsmPrinter LLVMInitializeMipsTarget LLVMInitializeMipsTargetMC LLVMInitializeMipsDisassembler LLVMInitializeMipsTargetInfo LLVMInitializeMSP430Target LLVMInitializeMSP430AsmPrinter LLVMInitializeMSP430TargetMC LLVMInitializeMSP430TargetInfo LLVMInitializeNVPTXAsmPrinter LLVMInitializeNVPTXTarget LLVMInitializeNVPTXTargetMC LLVMInitializeNVPTXTargetInfo LLVMInitializeObjCARCOpts LLVMCreateObjectFile LLVMDisposeObjectFile LLVMDisposeRelocationIterator LLVMDisposeSectionIterator LLVMDisposeSymbolIterator LLVMGetRelocationOffset LLVMGetRelocationSymbol LLVMGetRelocationType LLVMGetRelocationTypeName LLVMGetRelocationValueString LLVMGetRelocations LLVMGetSectionAddress LLVMGetSectionContainsSymbol LLVMGetSectionContents LLVMGetSectionName LLVMGetSectionSize LLVMGetSections LLVMGetSymbolAddress LLVMGetSymbolName LLVMGetSymbolSize LLVMGetSymbols LLVMIsRelocationIteratorAtEnd LLVMIsSectionIteratorAtEnd LLVMIsSymbolIteratorAtEnd LLVMMoveToContainingSection LLVMMoveToNextRelocation LLVMMoveToNextSection LLVMMoveToNextSymbol LLVMInitializePowerPCAsmParser LLVMInitializePowerPCAsmPrinter LLVMInitializePowerPCTarget LLVMInitializePowerPCTargetMC LLVMInitializePowerPCDisassembler LLVMInitializePowerPCTargetInfo LLVMInitializeAMDGPUAsmParser LLVMInitializeAMDGPUAsmPrinter LLVMInitializeAMDGPUTarget LLVMInitializeAMDGPUTargetMC LLVMInitializeAMDGPUTargetInfo LLVMAddAggressiveDCEPass LLVMAddAlignmentFromAssumptionsPass LLVMAddBasicAliasAnalysisPass LLVMAddCFGSimplificationPass LLVMAddConstantPropagationPass LLVMAddCorrelatedValuePropagationPass LLVMAddDeadStoreEliminationPass LLVMAddDemoteMemoryToRegisterPass LLVMAddEarlyCSEPass LLVMAddGVNPass LLVMAddIndVarSimplifyPass LLVMAddInstructionCombiningPass LLVMAddJumpThreadingPass LLVMAddLICMPass LLVMAddLoopDeletionPass LLVMAddLoopIdiomPass LLVMAddLoopRerollPass LLVMAddLoopRotatePass LLVMAddLoopUnrollPass LLVMAddLoopUnswitchPass LLVMAddLowerExpectIntrinsicPass LLVMAddLowerSwitchPass LLVMAddMemCpyOptPass LLVMAddMergedLoadStoreMotionPass LLVMAddPartiallyInlineLibCallsPass LLVMAddPromoteMemoryToRegisterPass LLVMAddReassociatePass LLVMAddSCCPPass LLVMAddScalarReplAggregatesPass LLVMAddScalarReplAggregatesPassSSA LLVMAddScalarReplAggregatesPassWithThreshold LLVMAddScalarizerPass LLVMAddScopedNoAliasAAPass LLVMAddSimplifyLibCallsPass LLVMAddTailCallEliminationPass LLVMAddTypeBasedAliasAnalysisPass LLVMAddVerifierPass LLVMInitializeScalarOpts LLVMInitializeSparcAsmParser LLVMInitializeSparcAsmPrinter LLVMInitializeSparcTarget LLVMInitializeSparcTargetMC LLVMInitializeSparcDisassembler LLVMInitializeSparcTargetInfo LLVMParseCommandLineOptions LLVMInstallFatalErrorHandler LLVMResetFatalErrorHandler LLVMEnablePrettyStackTrace LLVMLoadLibraryPermanently LLVMInitializeSystemZAsmParser LLVMInitializeSystemZAsmPrinter LLVMInitializeSystemZTarget LLVMInitializeSystemZTargetMC LLVMInitializeSystemZDisassembler LLVMInitializeSystemZTargetInfo LLVMABIAlignmentOfType LLVMABISizeOfType LLVMAddTargetData LLVMAddTargetLibraryInfo LLVMByteOrder LLVMCallFrameAlignmentOfType LLVMCopyStringRepOfTargetData LLVMCreateTargetData LLVMDisposeTargetData LLVMElementAtOffset LLVMInitializeTarget LLVMIntPtrType LLVMIntPtrTypeForAS LLVMIntPtrTypeForASInContext LLVMIntPtrTypeInContext LLVMOffsetOfElement LLVMPointerSize LLVMPointerSizeForAS LLVMPreferredAlignmentOfGlobal LLVMPreferredAlignmentOfType LLVMSizeOfTypeInBits LLVMStoreSizeOfType LLVMAddAnalysisPasses LLVMCreateTargetMachine LLVMDisposeTargetMachine LLVMGetDefaultTargetTriple LLVMGetFirstTarget LLVMGetNextTarget LLVMGetTargetDescription LLVMGetTargetFromName LLVMGetTargetFromTriple LLVMGetTargetMachineCPU LLVMGetTargetMachineData LLVMGetTargetMachineFeatureString LLVMGetTargetMachineTarget LLVMGetTargetMachineTriple LLVMGetTargetName LLVMSetTargetMachineAsmVerbosity LLVMTargetHasAsmBackend LLVMTargetHasJIT LLVMTargetHasTargetMachine LLVMTargetMachineEmitToFile LLVMTargetMachineEmitToMemoryBuffer LLVMCloneModule LLVMInitializeTransformUtils LLVMAddBBVectorizePass LLVMAddLoopVectorizePass LLVMAddSLPVectorizePass LLVMInitializeVectorization LLVMInitializeX86AsmParser LLVMInitializeX86AsmPrinter LLVMInitializeX86Target LLVMInitializeX86TargetMC LLVMInitializeX86Disassembler LLVMInitializeX86TargetInfo LLVMInitializeXCoreAsmPrinter LLVMInitializeXCoreTarget LLVMInitializeXCoreTargetMC LLVMInitializeXCoreDisassembler LLVMInitializeXCoreTargetInfo ================================================ FILE: Zelig/Zelig/CompileTime/Llvm.NET/LibLLVM/IRBindings.cpp ================================================ //===- IRBindings.cpp - Additional bindings for ir ------------------------===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // This file defines additional C bindings for the ir component. // //===----------------------------------------------------------------------===// #include "IRBindings.h" #include "llvm/IR/Attributes.h" #include "llvm/IR/DebugLoc.h" #include "llvm/IR/Function.h" #include "llvm/IR/IRBuilder.h" #include "llvm/IR/LLVMContext.h" #include "llvm/IR/Module.h" #include "llvm/IR/CallSite.h" #include "llvm/IR/DebugInfoMetadata.h" #include using namespace llvm; extern "C" { void LLVMGetVersionInfo( LLVMVersionInfo* pVersionInfo ) { *pVersionInfo = { LLVM_VERSION_MAJOR, LLVM_VERSION_MINOR, LLVM_VERSION_PATCH, LLVM_VERSION_STRING }; } LLVMMetadataRef LLVMConstantAsMetadata( LLVMValueRef C ) { return wrap( ConstantAsMetadata::get( unwrap( C ) ) ); } LLVMMetadataRef LLVMMDString2( LLVMContextRef C, char const *Str, unsigned SLen ) { return wrap( MDString::get( *unwrap( C ), StringRef( Str, SLen ) ) ); } LLVMMetadataRef LLVMMDNode2( LLVMContextRef C , LLVMMetadataRef *MDs , unsigned Count ) { auto node = MDNode::get( *unwrap( C ) , ArrayRef( unwrap( MDs ), Count ) ); return wrap( node ); } LLVMMetadataRef LLVMTemporaryMDNode( LLVMContextRef C , LLVMMetadataRef *MDs , unsigned Count ) { auto node = MDTuple::getTemporary( *unwrap( C ) , ArrayRef( unwrap( MDs ), Count ) ); return wrap( node.release() ); } void LLVMAddNamedMetadataOperand2( LLVMModuleRef M , char const *name , LLVMMetadataRef Val ) { NamedMDNode *N = unwrap( M )->getOrInsertNamedMetadata( name ); if( !N ) return; if( !Val ) return; N->addOperand( unwrap( Val ) ); } void LLVMSetMetadata2( LLVMValueRef Inst, unsigned KindID, LLVMMetadataRef MD ) { MDNode *N = MD ? unwrap( MD ) : nullptr; unwrap( Inst )->setMetadata( KindID, N ); } void LLVMMetadataReplaceAllUsesWith( LLVMMetadataRef MD, LLVMMetadataRef New ) { auto *Node = unwrap( MD ); Node->replaceAllUsesWith( unwrap( New ) ); MDNode::deleteTemporary( Node ); } void LLVMSetCurrentDebugLocation2( LLVMBuilderRef Bref , unsigned Line , unsigned Col , LLVMMetadataRef Scope , LLVMMetadataRef InlinedAt ) { auto loc = DebugLoc::get( Line , Col , Scope ? unwrap( Scope ) : nullptr , InlinedAt ? unwrap( InlinedAt ) : nullptr ); unwrap( Bref )->SetCurrentDebugLocation( loc ); } LLVMBool LLVMIsTemporary( LLVMMetadataRef M ) { auto pMetadata = unwrap( M ); return pMetadata->isTemporary(); } LLVMBool LLVMIsResolved( LLVMMetadataRef M ) { auto pMetadata = unwrap( M ); return pMetadata->isResolved( ); } LLVMBool LLVMIsUniqued( LLVMMetadataRef M ) { auto pMetadata = unwrap( M ); return pMetadata->isUniqued( ); } LLVMBool LLVMIsDistinct( LLVMMetadataRef M ) { auto pMetadata = unwrap( M ); return pMetadata->isDistinct( ); } char const* LLVMGetMDStringText( LLVMMetadataRef mdstring, unsigned* len ) { MDString const* S = unwrap( mdstring ); *len = S->getString( ).size( ); return S->getString( ).data( ); } void LLVMMDNodeResolveCycles( LLVMMetadataRef M ) { MDNode* pNode = unwrap( M ); if( pNode->isResolved() ) return; pNode->resolveCycles( ); } LLVMMetadataRef LLVMFunctionGetSubprogram( LLVMValueRef function ) { Function* pFunction = unwrap( function ); return wrap( pFunction->getSubprogram( ) ); } void LLVMFunctionSetSubprogram( LLVMValueRef function, LLVMMetadataRef subprogram ) { Function* pFunction = unwrap( function ); pFunction->setSubprogram( unwrap( subprogram ) ); } static AtomicOrdering mapFromLLVMOrdering( LLVMAtomicOrdering Ordering ) { switch( Ordering ) { case LLVMAtomicOrderingNotAtomic: return NotAtomic; case LLVMAtomicOrderingUnordered: return Unordered; case LLVMAtomicOrderingMonotonic: return Monotonic; case LLVMAtomicOrderingAcquire: return Acquire; case LLVMAtomicOrderingRelease: return Release; case LLVMAtomicOrderingAcquireRelease: return AcquireRelease; case LLVMAtomicOrderingSequentiallyConsistent: return SequentiallyConsistent; } llvm_unreachable( "Invalid LLVMAtomicOrdering value!" ); } LLVMValueRef LLVMBuildAtomicCmpXchg( LLVMBuilderRef B , LLVMValueRef Ptr , LLVMValueRef Cmp , LLVMValueRef New , LLVMAtomicOrdering successOrdering , LLVMAtomicOrdering failureOrdering , LLVMBool singleThread ) { auto builder = unwrap(B); auto cmpxchg = builder->CreateAtomicCmpXchg( unwrap( Ptr ) , unwrap( Cmp ) , unwrap( New ) , mapFromLLVMOrdering( successOrdering ) , mapFromLLVMOrdering( failureOrdering ) , singleThread ? SingleThread : CrossThread ); return wrap( cmpxchg ); } LLVMBool LLVMFunctionHasPersonalityFunction( LLVMValueRef function ) { Function* pFunc = unwrap( function ); return pFunc->hasPersonalityFn( ); } } ================================================ FILE: Zelig/Zelig/CompileTime/Llvm.NET/LibLLVM/IRBindings.h ================================================ //===- IRBindings.h - Additional bindings for IR ----------------*- C++ -*-===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // This file defines additional C bindings for the IR component. // //===----------------------------------------------------------------------===// #ifndef LLVM_BINDINGS_LLVM_IRBINDINGS_H #define LLVM_BINDINGS_LLVM_IRBINDINGS_H #include "llvm-c/Core.h" #ifdef __cplusplus #include "llvm/IR/Metadata.h" #include "llvm/Support/CBindingWrapping.h" #endif #include #ifdef __cplusplus extern "C" { #endif typedef struct LLVMVersionInfo { int Major; int Minor; int Patch; char const* VersionString; }LLVMVersionInfo; void LLVMGetVersionInfo( LLVMVersionInfo* pVersionInfo ); typedef struct LLVMOpaqueMetadata* LLVMMetadataRef; typedef struct LLVMOpaqueMDOperand* LLVMMDOperandRef; LLVMMetadataRef LLVMConstantAsMetadata(LLVMValueRef Val); LLVMMetadataRef LLVMMDString2(LLVMContextRef C, const char *Str, unsigned SLen); LLVMMetadataRef LLVMMDNode2(LLVMContextRef C, LLVMMetadataRef *MDs, unsigned Count); LLVMMetadataRef LLVMTemporaryMDNode(LLVMContextRef C, LLVMMetadataRef *MDs, unsigned Count); char const* LLVMGetMDStringText( LLVMMetadataRef mdstring, unsigned* len ); void LLVMAddNamedMetadataOperand2(LLVMModuleRef M, const char *name, LLVMMetadataRef Val); void LLVMSetMetadata2(LLVMValueRef Inst, unsigned KindID, LLVMMetadataRef MD); void LLVMMetadataReplaceAllUsesWith(LLVMMetadataRef MD, LLVMMetadataRef New); void LLVMSetCurrentDebugLocation2(LLVMBuilderRef Bref, unsigned Line, unsigned Col, LLVMMetadataRef Scope, LLVMMetadataRef InlinedAt); LLVMBool LLVMIsTemporary( LLVMMetadataRef M ); LLVMBool LLVMIsResolved( LLVMMetadataRef M ); LLVMBool LLVMIsUniqued( LLVMMetadataRef M ); LLVMBool LLVMIsDistinct( LLVMMetadataRef M ); void LLVMMDNodeResolveCycles( LLVMMetadataRef M ); char const* LLVMGetDIFileName( LLVMMetadataRef /*DIFile*/ file ); char const* LLVMGetDIFileDirectory( LLVMMetadataRef /*DIFile*/ file ); LLVMValueRef LLVMBuildAtomicCmpXchg( LLVMBuilderRef B, LLVMValueRef Ptr, LLVMValueRef Cmp, LLVMValueRef New, LLVMAtomicOrdering successOrdering, LLVMAtomicOrdering failureOrdering, LLVMBool singleThread ); LLVMMetadataRef LLVMFunctionGetSubprogram( LLVMValueRef function ); void LLVMFunctionSetSubprogram( LLVMValueRef function, LLVMMetadataRef subprogram ); LLVMBool LLVMFunctionHasPersonalityFunction( LLVMValueRef function ); #ifdef __cplusplus } namespace llvm { DEFINE_ISA_CONVERSION_FUNCTIONS(Metadata, LLVMMetadataRef) inline Metadata **unwrap(LLVMMetadataRef *Vals) { return reinterpret_cast(Vals); } } #endif #endif ================================================ FILE: Zelig/Zelig/CompileTime/Llvm.NET/LibLLVM/InlinedExports.cpp ================================================ #include "llvm-c/Target.h" extern "C" { // exportable wrappers around static in-lined functions // EXPORTS.DEF uses aliasing to export these as the standard name // (e.g. dropping the trailing "Export" from the name.) This // mechanism is needed since the in-lined functions are marked static // and therefore the linker doesn't see them as externally visible // so it can't export them. /** LLVMInitializeAllTargetInfos - The main program should call this function if it wants access to all available targets that LLVM is configured to support. */ void LLVMInitializeAllTargetInfosExport( void ) { LLVMInitializeAllTargetInfos( ); } /** LLVMInitializeAllTargets - The main program should call this function if it wants to link in all available targets that LLVM is configured to support. */ void LLVMInitializeAllTargetsExport( void ) { LLVMInitializeAllTargets( ); } /** LLVMInitializeAllTargetMCs - The main program should call this function if it wants access to all available target MC that LLVM is configured to support. */ void LLVMInitializeAllTargetMCsExport( void ) { LLVMInitializeAllTargetMCs( ); } /** LLVMInitializeAllAsmPrinters - The main program should call this function if it wants all asm printers that LLVM is configured to support, to make them available via the TargetRegistry. */ void LLVMInitializeAllAsmPrintersExport( void ) { LLVMInitializeAllAsmPrinters( ); } /** LLVMInitializeAllAsmParsers - The main program should call this function if it wants all asm parsers that LLVM is configured to support, to make them available via the TargetRegistry. */ void LLVMInitializeAllAsmParsersExport( void ) { LLVMInitializeAllAsmParsers( ); } /** LLVMInitializeAllDisassemblers - The main program should call this function if it wants all disassemblers that LLVM is configured to support, to make them available via the TargetRegistry. */ void LLVMInitializeAllDisassemblersExport( void ) { LLVMInitializeAllDisassemblers( ); } LLVMBool LLVMInitializeNativeTargetExport(void) { return LLVMInitializeNativeTarget(); } LLVMBool LLVMInitializeNativeAsmParserExport(void) { return LLVMInitializeNativeAsmParser(); } LLVMBool LLVMInitializeNativeAsmPrinterExport(void) { return LLVMInitializeNativeAsmPrinter(); } LLVMBool LLVMInitializeNativeDisassemblerExport(void) { return LLVMInitializeNativeDisassembler(); } } ================================================ FILE: Zelig/Zelig/CompileTime/Llvm.NET/LibLLVM/InlinedExports.h ================================================ #ifndef _INLINED_EXPORTS_H_ #define _INLINED_EXPORTS_H_ #include "llvm-c\Support.h" #ifdef __cplusplus extern "C" { #endif // exportable wrappers around static inlined functions // EXPORTS.DEF uses aliasing to export these as the standard name // (e.g. dropping the trailing "Export" from the name.) This // mechanism is needed since the inlined functions are marked static // and therefore the linker doesn't see them as externally visible // so it can't export them. /** LLVMInitializeAllTargetInfos - The main program should call this function if it wants access to all available targets that LLVM is configured to support. */ void LLVMInitializeAllTargetInfosExport( void ); /** LLVMInitializeAllTargets - The main program should call this function if it wants to link in all available targets that LLVM is configured to support. */ void LLVMInitializeAllTargetsExport( void ); /** LLVMInitializeAllTargetMCs - The main program should call this function if it wants access to all available target MC that LLVM is configured to support. */ void LLVMInitializeAllTargetMCsExport( void ); /** LLVMInitializeAllAsmPrinters - The main program should call this function if it wants all asm printers that LLVM is configured to support, to make them available via the TargetRegistry. */ void LLVMInitializeAllAsmPrintersExport( void ); /** LLVMInitializeAllAsmParsers - The main program should call this function if it wants all asm parsers that LLVM is configured to support, to make them available via the TargetRegistry. */ void LLVMInitializeAllAsmParsersExport( void ); /** LLVMInitializeAllDisassemblers - The main program should call this function if it wants all disassemblers that LLVM is configured to support, to make them available via the TargetRegistry. */ void LLVMInitializeAllDisassemblersExport( void ); LLVMBool LLVMInitializeNativeTargetExport(void); LLVMBool LLVMInitializeNativeAsmParserExport(void); LLVMBool LLVMInitializeNativeAsmPrinterExport(void); LLVMBool LLVMInitializeNativeDisassemblerExport(void); #ifdef __cplusplus } #endif #endif ================================================ FILE: Zelig/Zelig/CompileTime/Llvm.NET/LibLLVM/InstrumentationBindings.cpp ================================================ //===- InstrumentationBindings.cpp - instrumentation bindings -------------===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // This file defines C bindings for the instrumentation component. // //===----------------------------------------------------------------------===// #include "InstrumentationBindings.h" #include "llvm-c/Core.h" #include "llvm/IR/LegacyPassManager.h" #include "llvm/IR/Module.h" #include "llvm/Transforms/Instrumentation.h" using namespace llvm; extern "C" { void LLVMAddAddressSanitizerFunctionPass( LLVMPassManagerRef PM ) { unwrap( PM )->add( createAddressSanitizerFunctionPass( ) ); } void LLVMAddAddressSanitizerModulePass( LLVMPassManagerRef PM ) { unwrap( PM )->add( createAddressSanitizerModulePass( ) ); } void LLVMAddThreadSanitizerPass( LLVMPassManagerRef PM ) { unwrap( PM )->add( createThreadSanitizerPass( ) ); } void LLVMAddMemorySanitizerPass( LLVMPassManagerRef PM ) { unwrap( PM )->add( createMemorySanitizerPass( ) ); } void LLVMAddDataFlowSanitizerPass( LLVMPassManagerRef PM, int ABIListFilesNum, const char **ABIListFiles ) { std::vector ABIListFilesVec; for (int i = 0; i != ABIListFilesNum; ++i) { ABIListFilesVec.push_back(ABIListFiles[i]); } unwrap(PM)->add(createDataFlowSanitizerPass(ABIListFilesVec)); } } ================================================ FILE: Zelig/Zelig/CompileTime/Llvm.NET/LibLLVM/InstrumentationBindings.h ================================================ //===- InstrumentationBindings.h - instrumentation bindings -----*- C++ -*-===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // This file defines C bindings for the Transforms/Instrumentation component. // //===----------------------------------------------------------------------===// #ifndef LLVM_BINDINGS_LLVM_INSTRUMENTATIONBINDINGS_H #define LLVM_BINDINGS_LLVM_INSTRUMENTATIONBINDINGS_H #include "llvm-c/Core.h" #ifdef __cplusplus extern "C" { #endif // FIXME: These bindings shouldn't be language binding-specific and should eventually move to // a (somewhat) less stable collection of C APIs for use in creating bindings of // LLVM in other languages. void LLVMAddAddressSanitizerFunctionPass(LLVMPassManagerRef PM); void LLVMAddAddressSanitizerModulePass(LLVMPassManagerRef PM); void LLVMAddThreadSanitizerPass(LLVMPassManagerRef PM); void LLVMAddMemorySanitizerPass(LLVMPassManagerRef PM); void LLVMAddDataFlowSanitizerPass( LLVMPassManagerRef PM, int ABIListFilesNum, const char **ABIListFiles ); #ifdef __cplusplus } #endif #endif ================================================ FILE: Zelig/Zelig/CompileTime/Llvm.NET/LibLLVM/LibLLVM.vcxproj ================================================  Debug Win32 Debug x64 Release Win32 Release x64 {6C77A7DE-D464-430F-96A9-A64768763B5F} Win32Proj LibLLVM LibLLVM 8.1 @(AllLlvmLibs);$(AdditionalDependencies) true 8.1 DynamicLibrary true v140 Unicode DynamicLibrary true v140 Unicode DynamicLibrary false v140 true Unicode DynamicLibrary false v140 true Unicode true ..\..\..\..\ZeligBuild\Host\bin\$(Configuration)\ ..\..\..\..\ZeligBuild\Host\bin\$(Configuration)\ true $(ProjectDir)$(Platform)\$(Configuration)\ $(Platform)\$(Configuration)\ false ..\..\..\..\ZeligBuild\Host\bin\$(Configuration)\ ..\..\..\..\ZeligBuild\Host\bin\$(Configuration)\ false $(ProjectDir)$(Platform)\$(Configuration)\ $(Platform)\$(Configuration)\ NotUsing Level3 Disabled Win32;_DEBUG;_WINDOWS;_USRDLL;LIBLLVM_EXPORTS;%(PreprocessorDefinitions) %(AdditionalIncludeDirectories) Windows true EXPORTS.DEF $(AllLlvmStaticLibs);%(AdditionalDependencies) NotUsing Level3 Disabled Win32;_DEBUG;_WINDOWS;_USRDLL;LIBLLVM_EXPORTS;%(PreprocessorDefinitions) %(AdditionalIncludeDirectories) Windows true EXPORTS.DEF $(AllLlvmStaticLibs);%(AdditionalDependencies) Level3 NotUsing MaxSpeed true true Win32;NDEBUG;_WINDOWS;_USRDLL;LIBLLVM_EXPORTS;%(PreprocessorDefinitions) %(AdditionalIncludeDirectories) Windows true true true EXPORTS.DEF $(AllLlvmStaticLibs);%(AdditionalDependencies) Level3 NotUsing MaxSpeed true true Win32;NDEBUG;_WINDOWS;_USRDLL;LIBLLVM_EXPORTS;%(PreprocessorDefinitions) %(AdditionalIncludeDirectories) Windows true true true EXPORTS.DEF $(AllLlvmStaticLibs);%(AdditionalDependencies) true false true false true false true false Designer true false true false true false true false ================================================ FILE: Zelig/Zelig/CompileTime/Llvm.NET/LibLLVM/LibLLVM.vcxproj.filters ================================================  {4FC737F1-C7A5-4376-A066-2A32D752A2FF} cpp;c;cc;cxx;def;odl;idl;hpj;bat;asm;asmx {93995380-89BD-4b04-88EB-625FBE52EBFB} h;hh;hpp;hxx;hm;inl;inc;xsd {67DA6AB6-F800-4c08-8B7A-83BB121AAD01} rc;ico;cur;bmp;dlg;rc2;rct;bin;rgs;gif;jpg;jpeg;jpe;resx;tiff;tif;png;wav;mfcribbon-ms Source Files Source Files Source Files Source Files Source Files Source Files Source Files Source Files Source Files Source Files Header Files Header Files Header Files Header Files Header Files Header Files Header Files Header Files Header Files Header Files Resource Files ================================================ FILE: Zelig/Zelig/CompileTime/Llvm.NET/LibLLVM/LlvmApplication.props ================================================ 3 8 1 $(LlvmVersionMajor).$(llvmVersionMinor).$(LlvmVersionBuild) $([MSBuild]::GetRegistryValue(`HKEY_CURRENT_USER\Software\LLVM\$(LLVM_VERSION)\`, `SrcRoot`)) $([MSBuild]::GetRegistryValueFromView(`HKEY_LOCAL_MACHINE\Software\LLVM\$(LLVM_VERSION)\`, `SrcRoot`, null, RegistryView.Registry64, RegistryView.Registry32)) $(LLVM_SRCROOT_DIR)\ $(LLVM_SRCROOT_DIR)Build\ $(LLVM_BUILD_DIR)\ generatedversioninfo.h $(LlvmVersionMajor) $(LlvmVersionMinor) $(LlvmVersionBuild) 0 1 $(ProductVersionMajor) $(ProductVersionMinor) $(LLVM_SRCROOT_DIR)Include $(LLVM_BUILD_DIR)$(Platform)\ $(LLVM_PLATFORM_DIR)$(Configuration)\ $(LLVM_PLATFORM_DIR)Include\ $(LLVM_CONFIG_DIR)bin\ $(LLVM_CONFIG_DIR)lib\ @(AllLlvmLibs) $(AdditionalOptions) /Zc:sizedDealloc- $(LLVM_CONFIG_INCLUDE);$(LLVM_INCLUDE);%(AdditionalIncludeDirectories) 4141;4267;4244;4800;4291;4996;4624 $(AllLlvmStaticLibs);$(AdditionalDependencies) ================================================ FILE: Zelig/Zelig/CompileTime/Llvm.NET/LibLLVM/LlvmApplication.targets ================================================ ================================================ FILE: Zelig/Zelig/CompileTime/Llvm.NET/LibLLVM/LlvmDebugInfo.cpp ================================================ #include #include "LlvmDebugInfo.h" #include #include using namespace llvm; // Create wrappers for C Binding types (see CBindingWrapping.h). DEFINE_SIMPLE_CONVERSION_FUNCTIONS( DIBuilder, LLVMDIBuilderRef ) #define LLVM_DEFINE_DINODE_CAST(name) \ LLVMDIDescriptorRef LLVMIsA##name( LLVMDIDescriptorRef Val ) \ { \ return wrap( static_cast( dyn_cast_or_null( unwrap( Val ) ) ) ); \ } LLVM_FOR_EACH_DIDESCRIPTOR_SUBCLASS( LLVM_DEFINE_DINODE_CAST ) extern "C" LLVMDIBuilderRef LLVMDIBuilderCreate( LLVMModuleRef M ) { return wrap( new DIBuilder( *unwrap( M ) ) ); } extern "C" void LLVMDIBuilderDispose( LLVMDIBuilderRef Builder ) { delete unwrap( Builder ); } extern "C" void LLVMDIBuilderFinalize( LLVMDIBuilderRef Builder ) { auto bldr = unwrap( Builder ); bldr->finalize( ); } extern "C" LLVMValueRef LLVMDIBuilderCreateCompileUnit( LLVMDIBuilderRef Builder , unsigned Lang , const char* File , const char* Dir , const char* Producer , bool isOptimized , const char* Flags , unsigned RuntimeVer , const char* SplitName ) { auto bldr = unwrap( Builder ); auto unwrappedResult = bldr->createCompileUnit( Lang , File , Dir , Producer , isOptimized , Flags , RuntimeVer , SplitName ); return wrap( unwrappedResult ); } extern "C" LLVMValueRef LLVMDIBuilderCreateFile( LLVMDIBuilderRef Builder , const char* Filename , const char* Directory ) { auto bldr = unwrap( Builder ); auto result = bldr->createFile( Filename, Directory ); return wrap( result ); } extern "C" LLVMValueRef LLVMDIBuilderCreateSubroutineType( LLVMDIBuilderRef Builder , LLVMValueRef File , LLVMValueRef ParameterTypes ) { auto bldr = unwrap( Builder ); auto unwrappedVal = bldr->createSubroutineType( unwrapDI( File ) , unwrapDI( ParameterTypes ) ); return wrap( unwrappedVal ); } extern "C" LLVMValueRef LLVMDIBuilderCreateFunction( LLVMDIBuilderRef Builder , LLVMValueRef Scope , const char* Name , const char* LinkageName , LLVMValueRef File , unsigned LineNo , LLVMValueRef Ty , bool isLocalToUnit , bool isDefinition , unsigned ScopeLine , unsigned Flags , bool isOptimized , LLVMValueRef Fn , LLVMValueRef TParam , LLVMValueRef Decl ) { auto bldr = unwrap( Builder ); auto unwrapped = bldr->createFunction( unwrapDI( Scope ) , Name , LinkageName , unwrapDI( File ) , LineNo , unwrapDI( Ty ) , isLocalToUnit , isDefinition , ScopeLine , Flags , isOptimized , unwrap( Fn ) , unwrapDI( TParam ) , unwrapDI( Decl ) ); return wrap( unwrapped ); } extern "C" LLVMValueRef LLVMDIBuilderCreateBasicType( LLVMDIBuilderRef Builder , const char* Name , uint64_t SizeInBits , uint64_t AlignInBits , unsigned Encoding ) { auto bldr = unwrap( Builder ); auto unwrapped = bldr->createBasicType( Name, SizeInBits, AlignInBits, Encoding ); return wrap( unwrapped ); } extern "C" LLVMValueRef LLVMDIBuilderCreatePointerType( LLVMDIBuilderRef Builder , LLVMValueRef PointeeTy , uint64_t SizeInBits , uint64_t AlignInBits , const char* Name ) { auto bldr = unwrap( Builder ); auto unwrapped = bldr->createPointerType( unwrapDI( PointeeTy ), SizeInBits, AlignInBits, Name ); return wrap( unwrapped ); } extern "C" LLVMValueRef LLVMDIBuilderCreateForwardDecl( LLVMDIBuilderRef Builder , unsigned Tag , const char* Name , LLVMValueRef Scope , LLVMValueRef File , unsigned Line , unsigned RuntimeLang , uint64_t SizeInBits , uint64_t AlignInBits , const char* UniqueId ) { auto bldr = unwrap( Builder ); auto unwrapped = bldr->createForwardDecl( Tag , Name , unwrapDI( Scope ) , unwrapDI( File ) , Line , RuntimeLang , SizeInBits , AlignInBits , UniqueId ); return wrap( unwrapped ); } extern "C" LLVMValueRef LLVMDIBuilderCreateStructType( LLVMDIBuilderRef Builder , LLVMValueRef Scope , const char* Name , LLVMValueRef File , unsigned LineNumber , uint64_t SizeInBits , uint64_t AlignInBits , unsigned Flags , LLVMValueRef DerivedFrom , LLVMValueRef Elements , unsigned RunTimeLang , LLVMValueRef VTableHolder , const char *UniqueId ) { auto bldr = unwrap( Builder ); auto unwrapped = bldr->createStructType( unwrapDI( Scope ) , Name , unwrapDI( File ) , LineNumber , SizeInBits , AlignInBits , Flags , unwrapDI( DerivedFrom ) , unwrapDI( Elements ) , RunTimeLang , unwrapDI( VTableHolder ) , UniqueId ); return wrap( unwrapped ); } extern "C" LLVMValueRef LLVMDIBuilderCreateClassType( LLVMDIBuilderRef Builder , LLVMValueRef Scope , const char* Name , LLVMValueRef File , unsigned LineNumber , uint64_t SizeInBits , uint64_t AlignInBits , uint64_t OffsetInBits , unsigned Flags , LLVMValueRef DerivedFrom , LLVMValueRef Elements , LLVMValueRef VTableHolder , LLVMValueRef TemplateParms , const char *UniqueId ) { auto bldr = unwrap( Builder ); auto unwrapped = bldr->createClassType( unwrapDI( Scope ) , Name , unwrapDI( File ) , LineNumber , SizeInBits , AlignInBits , OffsetInBits , Flags , unwrapDI( DerivedFrom ) , unwrapDI( Elements ) , unwrapDI( VTableHolder ) , unwrapDI( TemplateParms ) , UniqueId ); return wrap( unwrapped ); } extern "C" LLVMValueRef LLVMDIBuilderCreateMemberType( LLVMDIBuilderRef Builder , LLVMValueRef Scope , const char* Name , LLVMValueRef File , unsigned LineNo , uint64_t SizeInBits , uint64_t AlignInBits , uint64_t OffsetInBits , unsigned Flags , LLVMValueRef Ty ) { auto bldr = unwrap( Builder ); auto unwrappedResult = bldr->createMemberType( unwrapDI( Scope ) , Name , unwrapDI( File ) , LineNo , SizeInBits , AlignInBits , OffsetInBits , Flags , unwrapDI( Ty ) ); return wrap( unwrappedResult ); } extern "C" LLVMValueRef LLVMDIBuilderCreateLexicalBlock( LLVMDIBuilderRef Builder , LLVMValueRef Scope , LLVMValueRef File , unsigned Line , unsigned Col , unsigned Discriminator ) { auto bldr = unwrap( Builder ); auto unwrappedResult = bldr->createLexicalBlock( unwrapDI( Scope ) , unwrapDI( File ) , Line , Col , Discriminator ); return wrap( unwrappedResult ); } extern "C" LLVMValueRef LLVMDIBuilderCreateStaticVariable( LLVMDIBuilderRef Builder , LLVMValueRef Context , const char* Name , const char* LinkageName , LLVMValueRef File , unsigned LineNo , LLVMValueRef Ty , bool isLocalToUnit , LLVMValueRef Val , LLVMValueRef Decl ) { auto bldr = unwrap( Builder ); auto unwrappedResult = bldr->createStaticVariable( unwrapDI( Context ) , Name , LinkageName , unwrapDI( File ) , LineNo , unwrapDI( Ty ) , isLocalToUnit , unwrap( Val ) , unwrapDI( Decl ) ); return wrap( unwrappedResult ); } extern "C" LLVMValueRef LLVMDIBuilderCreateLocalVariable( LLVMDIBuilderRef Builder , unsigned Tag , LLVMValueRef Scope , const char* Name , LLVMValueRef File , unsigned LineNo , LLVMValueRef Ty , bool AlwaysPreserve , unsigned Flags , unsigned ArgNo ) { auto bldr = unwrap( Builder ); auto unwrappedResult = bldr->createLocalVariable( Tag , unwrapDI( Scope ) , Name , unwrapDI( File ) , LineNo , unwrapDI( Ty ) , AlwaysPreserve , Flags , ArgNo ); return wrap( unwrappedResult ); } extern "C" LLVMValueRef LLVMDIBuilderCreateArrayType( LLVMDIBuilderRef Builder , uint64_t Size , uint64_t AlignInBits , LLVMValueRef Ty , LLVMValueRef Subscripts ) { auto bldr = unwrap( Builder ); auto unrwappedResult = bldr->createArrayType( Size , AlignInBits , unwrapDI( Ty ) , unwrapDI( Subscripts ) ); return wrap( unrwappedResult ); } extern "C" LLVMValueRef LLVMDIBuilderCreateVectorType( LLVMDIBuilderRef Builder , uint64_t Size , uint64_t AlignInBits , LLVMValueRef Ty , LLVMValueRef Subscripts ) { auto bldr = unwrap( Builder ); auto unwrappedResult = bldr->createVectorType( Size , AlignInBits , unwrapDI( Ty ) , unwrapDI( Subscripts ) ); return wrap( unwrappedResult ); } extern "C" LLVMValueRef LLVMDIBuilderGetOrCreateSubrange( LLVMDIBuilderRef Builder , int64_t Lo , int64_t Count ) { auto bldr = unwrap( Builder ); auto unwrappedResult = bldr->getOrCreateSubrange( Lo, Count ); return wrap( unwrappedResult ); } extern "C" LLVMValueRef LLVMDIBuilderGetOrCreateArray( LLVMDIBuilderRef Builder , LLVMValueRef* Ptr , unsigned Count ) { auto bldr = unwrap( Builder ); auto unwrappedResult = bldr->getOrCreateArray( ArrayRef( reinterpret_cast< Value** >( Ptr ), Count ) ); return wrap( unwrappedResult ); } extern "C" LLVMValueRef LLVMDIBuilderInsertDeclareAtEnd( LLVMDIBuilderRef Builder , LLVMValueRef Val , LLVMValueRef VarInfo , LLVMBasicBlockRef InsertAtEnd ) { auto bldr = unwrap( Builder ); auto unwrappedResult = bldr->insertDeclare( unwrap( Val ) , unwrapDI( VarInfo ) , unwrap( InsertAtEnd ) ); return wrap( unwrappedResult ); } extern "C" LLVMValueRef LLVMDIBuilderInsertDeclareBefore( LLVMDIBuilderRef Builder , LLVMValueRef Val , LLVMValueRef VarInfo , LLVMValueRef InsertBefore ) { auto bldr = unwrap( Builder ); auto unwrappedResult = bldr->insertDeclare( unwrap( Val ) , unwrapDI( VarInfo ) , unwrap( InsertBefore ) ); return wrap( unwrappedResult ); } extern "C" LLVMValueRef LLVMDIBuilderCreateEnumerator( LLVMDIBuilderRef Builder , const char* Name , uint64_t Val ) { return wrap( unwrap( Builder )->createEnumerator( Name, Val ) ); } extern "C" LLVMValueRef LLVMDIBuilderCreateEnumerationType( LLVMDIBuilderRef Builder , LLVMValueRef Scope , const char* Name , LLVMValueRef File , unsigned LineNumber , uint64_t SizeInBits , uint64_t AlignInBits , LLVMValueRef Elements , LLVMValueRef ClassType ) { return wrap( unwrap( Builder )->createEnumerationType( unwrapDI( Scope ) , Name , unwrapDI( File ) , LineNumber , SizeInBits , AlignInBits , unwrapDI( Elements ) , unwrapDI( ClassType ) ) ); } extern "C" LLVMValueRef LLVMDIBuilderCreateUnionType( LLVMDIBuilderRef Builder , LLVMValueRef Scope , const char* Name , LLVMValueRef File , unsigned LineNumber , uint64_t SizeInBits , uint64_t AlignInBits , unsigned Flags , LLVMValueRef Elements , unsigned RunTimeLang , const char* UniqueId ) { return wrap( unwrap( Builder )->createUnionType( unwrapDI( Scope ) , Name , unwrapDI( File ) , LineNumber , SizeInBits , AlignInBits , Flags , unwrapDI( Elements ) , RunTimeLang , UniqueId ) ); } extern "C" LLVMValueRef LLVMDIBuilderCreateTemplateTypeParameter( LLVMDIBuilderRef Builder , LLVMValueRef Scope , const char* Name , LLVMValueRef Ty , LLVMValueRef File , unsigned LineNo , unsigned ColumnNo ) { return wrap( unwrap( Builder )->createTemplateTypeParameter( unwrapDI( Scope ) , Name , unwrapDI( Ty ) , unwrapDI( File ) , LineNo , ColumnNo ) ); } extern "C" LLVMValueRef LLVMDIBuilderCreateOpDeref( LLVMTypeRef IntTy ) { return LLVMConstInt( IntTy, DIBuilder::OpDeref, true ); } extern "C" LLVMValueRef LLVMDIBuilderCreateOpPlus( LLVMTypeRef IntTy ) { return LLVMConstInt( IntTy, DIBuilder::OpPlus, true ); } extern "C" LLVMValueRef LLVMDIBuilderCreateComplexVariable( LLVMDIBuilderRef Builder , unsigned Tag , LLVMValueRef Scope , const char *Name , LLVMValueRef File , unsigned LineNo , LLVMValueRef Ty , LLVMValueRef* AddrOps , unsigned AddrOpsCount , unsigned ArgNo ) { llvm::ArrayRef addr_ops( ( llvm::Value** )AddrOps, AddrOpsCount ); return wrap( unwrap( Builder )->createComplexVariable( Tag , unwrapDI( Scope ) , Name , unwrapDI( File ) , LineNo , unwrapDI( Ty ) , addr_ops , ArgNo ) ); } extern "C" LLVMValueRef LLVMDIBuilderCreateNameSpace( LLVMDIBuilderRef Builder , LLVMValueRef Scope , const char* Name , LLVMValueRef File , unsigned LineNo ) { return wrap( unwrap( Builder )->createNameSpace( unwrapDI( Scope ) , Name , unwrapDI( File ) , LineNo ) ); } extern "C" void LLVMDICompositeTypeSetTypeArray( LLVMValueRef* CompositeType , LLVMValueRef TypeArray ) { auto compositeType = unwrapDI( *CompositeType ); compositeType.setTypeArray( unwrapDI( TypeArray ) ); *CompositeType = wrap( compositeType ); } ================================================ FILE: Zelig/Zelig/CompileTime/Llvm.NET/LibLLVM/LlvmDebugInfo.h ================================================ #pragma once #include "llvm-c/Core.h" #ifdef __cplusplus extern "C" { #endif #define DECLARE_LLVMC_REF( n ) typedef struct LLVMOpaque##n##* LLVM##n##Ref DECLARE_LLVMC_REF( DIBuilder ); DECLARE_LLVMC_REF( DIBasicType ); DECLARE_LLVMC_REF( DICompileUnit ); DECLARE_LLVMC_REF( DICompositeType ); DECLARE_LLVMC_REF( DIDerivedType ); DECLARE_LLVMC_REF( DIDescriptor ); DECLARE_LLVMC_REF( DIFile ); DECLARE_LLVMC_REF( DIEnumerator ); DECLARE_LLVMC_REF( DIType ); DECLARE_LLVMC_REF( DIArray ); DECLARE_LLVMC_REF( DIGlobalVariable ); DECLARE_LLVMC_REF( DIImportedEntity ); DECLARE_LLVMC_REF( DINameSpace ); DECLARE_LLVMC_REF( DIVariable ); DECLARE_LLVMC_REF( DISubrange ); DECLARE_LLVMC_REF( DILexicalBlockFile ); DECLARE_LLVMC_REF( DILexicalBlock ); DECLARE_LLVMC_REF( DIScope ); DECLARE_LLVMC_REF( DISubprogram ); DECLARE_LLVMC_REF( DITemplateTypeParameter ); DECLARE_LLVMC_REF( DITemplateValueParameter ); DECLARE_LLVMC_REF( DIObjCProperty ); #define LLVM_FOR_EACH_DIDESCRIPTOR_SUBCLASS(macro) \ macro(DIDescriptor) \ macro(DILocation) \ macro(DIObjCProperty) \ macro(DITemplateValueParameter) \ macro(DITemplateTypeParameter) \ macro(DIEnumerator) \ macro(DIGlobalVariable) \ macro(DIImportedEntity) \ macro(DISubrange) \ macro(DIVariable) \ macro(DIScope) \ macro(DISubprogram) \ macro(DICompileUnit) \ macro(DIFile) \ macro(DINameSpace) \ macro(DILexicalBlock) \ macro(DILexicalBlockFile) \ macro(DIType) \ macro(DIBasicType) \ macro(DIDerivedType) \ macro(DICompositeType) #define LLVM_DECLARE_DINODE_CAST(name) LLVMDIDescriptorRef LLVMIsA##name( LLVMDIDescriptorRef node ); LLVM_FOR_EACH_DIDESCRIPTOR_SUBCLASS( LLVM_DECLARE_DINODE_CAST ); LLVMDIBuilderRef LLVMDIBuilderCreate( LLVMModuleRef M ); void LLVMDIBuilderDispose( LLVMDIBuilderRef Builder ); void LLVMDIBuilderFinalize( LLVMDIBuilderRef Builder ); LLVMValueRef LLVMDIBuilderCreateCompileUnit( LLVMDIBuilderRef Builder , unsigned Lang , const char* File , const char* Dir , const char* Producer , bool isOptimized , const char* Flags , unsigned RuntimeVer , const char* SplitName ); LLVMValueRef LLVMDIBuilderCreateFile( LLVMDIBuilderRef Builder, const char* Filename, const char* Directory ); LLVMValueRef LLVMDIBuilderCreateSubroutineType( LLVMDIBuilderRef Builder , LLVMValueRef File , LLVMValueRef ParameterTypes ); LLVMValueRef LLVMDIBuilderCreateFunction( LLVMDIBuilderRef Builder , LLVMValueRef Scope , const char* Name , const char* LinkageName , LLVMValueRef File , unsigned LineNo , LLVMValueRef Ty , bool isLocalToUnit , bool isDefinition , unsigned ScopeLine , unsigned Flags , bool isOptimized , LLVMValueRef Fn , LLVMValueRef TParam , LLVMValueRef Decl ); LLVMValueRef LLVMDIBuilderCreateBasicType( LLVMDIBuilderRef Builder , const char* Name , uint64_t SizeInBits , uint64_t AlignInBits , unsigned Encoding ); LLVMValueRef LLVMDIBuilderCreatePointerType( LLVMDIBuilderRef Builder , LLVMValueRef PointeeTy , uint64_t SizeInBits , uint64_t AlignInBits , const char* Name ); LLVMValueRef LLVMDIBuilderCreateForwardDecl( LLVMDIBuilderRef Builder , unsigned Tag , const char* Name , LLVMValueRef Scope , LLVMValueRef File , unsigned Line , unsigned RuntimeLang , uint64_t SizeInBits , uint64_t AlignInBits , const char* UniqueId ); LLVMValueRef LLVMDIBuilderCreateStructType( LLVMDIBuilderRef Builder , LLVMValueRef Scope , const char* Name , LLVMValueRef File , unsigned LineNumber , uint64_t SizeInBits , uint64_t AlignInBits , unsigned Flags , LLVMValueRef DerivedFrom , LLVMValueRef Elements , unsigned RunTimeLang , LLVMValueRef VTableHolder , const char *UniqueId ); LLVMValueRef LLVMDIBuilderCreateClassType( LLVMDIBuilderRef Builder , LLVMValueRef Scope , const char* Name , LLVMValueRef File , unsigned LineNumber , uint64_t SizeInBits , uint64_t AlignInBits , uint64_t OffsetInBits , unsigned Flags , LLVMValueRef DerivedFrom , LLVMValueRef Elements , LLVMValueRef VTableHolder , LLVMValueRef TemplateParms , const char *UniqueId ); LLVMValueRef LLVMDIBuilderCreateMemberType( LLVMDIBuilderRef Builder , LLVMValueRef Scope , const char* Name , LLVMValueRef File , unsigned LineNo , uint64_t SizeInBits , uint64_t AlignInBits , uint64_t OffsetInBits , unsigned Flags , LLVMValueRef Ty ); LLVMValueRef LLVMDIBuilderCreateLexicalBlock( LLVMDIBuilderRef Builder , LLVMValueRef Scope , LLVMValueRef File , unsigned Line , unsigned Col , unsigned Discriminator ); LLVMValueRef LLVMDIBuilderCreateStaticVariable( LLVMDIBuilderRef Builder , LLVMValueRef Context , const char* Name , const char* LinkageName , LLVMValueRef File , unsigned LineNo , LLVMValueRef Ty , bool isLocalToUnit , LLVMValueRef Val , LLVMValueRef Decl ); LLVMValueRef LLVMDIBuilderCreateLocalVariable( LLVMDIBuilderRef Builder , unsigned Tag , LLVMValueRef Scope , const char* Name , LLVMValueRef File , unsigned LineNo , LLVMValueRef Ty , bool AlwaysPreserve , unsigned Flags , unsigned ArgNo ); LLVMValueRef LLVMDIBuilderCreateArrayType( LLVMDIBuilderRef Builder , uint64_t Size , uint64_t AlignInBits , LLVMValueRef Ty , LLVMValueRef Subscripts ); LLVMValueRef LLVMDIBuilderCreateVectorType( LLVMDIBuilderRef Builder , uint64_t Size , uint64_t AlignInBits , LLVMValueRef Ty , LLVMValueRef Subscripts ); LLVMValueRef LLVMDIBuilderGetOrCreateSubrange( LLVMDIBuilderRef Builder , int64_t Lo , int64_t Count ); LLVMValueRef LLVMDIBuilderGetOrCreateArray( LLVMDIBuilderRef Builder , LLVMValueRef* Ptr , unsigned Count ); LLVMValueRef LLVMDIBuilderInsertDeclareAtEnd( LLVMDIBuilderRef Builder , LLVMValueRef Val , LLVMValueRef VarInfo , LLVMBasicBlockRef InsertAtEnd ); LLVMValueRef LLVMDIBuilderInsertDeclareBefore( LLVMDIBuilderRef Builder , LLVMValueRef Val , LLVMValueRef VarInfo , LLVMValueRef InsertBefore ); LLVMValueRef LLVMDIBuilderCreateEnumerator( LLVMDIBuilderRef Builder , const char* Name , uint64_t Val ); LLVMValueRef LLVMDIBuilderCreateEnumerationType( LLVMDIBuilderRef Builder , LLVMValueRef Scope , const char* Name , LLVMValueRef File , unsigned LineNumber , uint64_t SizeInBits , uint64_t AlignInBits , LLVMValueRef Elements , LLVMValueRef ClassType ); LLVMValueRef LLVMDIBuilderCreateUnionType( LLVMDIBuilderRef Builder , LLVMValueRef Scope , const char* Name , LLVMValueRef File , unsigned LineNumber , uint64_t SizeInBits , uint64_t AlignInBits , unsigned Flags , LLVMValueRef Elements , unsigned RunTimeLang , const char* UniqueId ); LLVMValueRef LLVMDIBuilderCreateTemplateTypeParameter( LLVMDIBuilderRef Builder , LLVMValueRef Scope , const char* Name , LLVMValueRef Ty , LLVMValueRef File , unsigned LineNo , unsigned ColumnNo ); LLVMValueRef LLVMDIBuilderCreateOpDeref( LLVMTypeRef IntTy ); LLVMValueRef LLVMDIBuilderCreateOpPlus( LLVMTypeRef IntTy ); LLVMValueRef LLVMDIBuilderCreateComplexVariable( LLVMDIBuilderRef Builder , unsigned Tag , LLVMValueRef Scope , const char *Name , LLVMValueRef File , unsigned LineNo , LLVMValueRef Ty , LLVMValueRef* AddrOps , unsigned AddrOpsCount , unsigned ArgNo ); LLVMValueRef LLVMDIBuilderCreateNameSpace( LLVMDIBuilderRef Builder , LLVMValueRef Scope , const char* Name , LLVMValueRef File , unsigned LineNo ); void LLVMDICompositeTypeSetTypeArray( LLVMValueRef* CompositeType , LLVMValueRef TypeArray ); void LLVMAddModuleFlag( LLVMModuleRef M, const char *name, uint32_t value ); #ifdef __cplusplus } #endif ================================================ FILE: Zelig/Zelig/CompileTime/Llvm.NET/LibLLVM/ModuleBindings.cpp ================================================ #include #include "ModuleBindings.h" #include "IRBindings.h" using namespace llvm; DEFINE_SIMPLE_CONVERSION_FUNCTIONS( NamedMDNode, LLVMNamedMDNodeRef ) extern "C" { void LLVMAddModuleFlag( LLVMModuleRef M , LLVMModFlagBehavior behavior , const char *name , uint32_t value ) { unwrap( M )->addModuleFlag( (Module::ModFlagBehavior)behavior, name, value ); } LLVMValueRef LLVMGetOrInsertFunction( LLVMModuleRef module, const char* name, LLVMTypeRef functionType ) { auto pModule = unwrap( module ); auto pSignature = cast< FunctionType >( unwrap( functionType ) ); return wrap( pModule->getOrInsertFunction( name, pSignature ) ); } char const* LLVMGetModuleName( LLVMModuleRef module ) { auto pModule = unwrap( module ); return pModule->getModuleIdentifier( ).c_str( ); } LLVMValueRef LLVMGetGlobalAlias( LLVMModuleRef module, char const* name ) { auto pModule = unwrap( module ); return wrap( pModule->getNamedAlias( name ) ); } LLVMNamedMDNodeRef LLVMModuleGetModuleFlagsMetadata( LLVMModuleRef module ) { auto pModule = unwrap( module ); return wrap( pModule->getModuleFlagsMetadata( ) ); } unsigned LLVMNamedMDNodeGetNumOperands( LLVMNamedMDNodeRef namedMDNode ) { auto pMDNode = unwrap( namedMDNode ); return pMDNode->getNumOperands( ); } LLVMMetadataRef LLVMNamedMDNodeGetOperand( LLVMNamedMDNodeRef namedMDNode, unsigned index ) { auto pMDNode = unwrap( namedMDNode ); if( index >= pMDNode->getNumOperands( ) ) return nullptr; return wrap( pMDNode->getOperand( index ) ); } LLVMModuleRef LLVMNamedMDNodeGetParentModule( LLVMNamedMDNodeRef namedMDNode ) { auto pMDNode = unwrap( namedMDNode ); return wrap( pMDNode->getParent( ) ); } } ================================================ FILE: Zelig/Zelig/CompileTime/Llvm.NET/LibLLVM/ModuleBindings.h ================================================ #ifndef _MODULE_BINDINGS_H_ #define _MODULE_BINDINGS_H_ #include "llvm-c/Core.h" #include "IRBindings.h" #ifdef __cplusplus extern "C" { #endif typedef struct OpaqueNameMDNodeRef* LLVMNamedMDNodeRef; /// See Module::ModFlagBehavior enum LLVMModFlagBehavior { Error = 1, Warning = 2, Require = 3, Override = 4, Append = 5, AppendUnique = 6, ModFlagBehaviorFirstVal = Error, ModFlagBehaviorLastVal = AppendUnique }; void LLVMAddModuleFlag( LLVMModuleRef M , LLVMModFlagBehavior behavior , const char *name , uint32_t value ); LLVMValueRef LLVMGetOrInsertFunction( LLVMModuleRef module, const char* name, LLVMTypeRef functionType ); char const* LLVMGetModuleName( LLVMModuleRef module ); LLVMValueRef LLVMGetGlobalAlias( LLVMModuleRef module, char const* name ); LLVMNamedMDNodeRef LLVMModuleGetModuleFlagsMetadata( LLVMModuleRef module ); unsigned LLVMNamedMDNodeGetNumOperands( LLVMNamedMDNodeRef namedMDNode ); /*MDNode*/ LLVMMetadataRef LLVMNamedMDNodeGetOperand( LLVMNamedMDNodeRef namedMDNode, unsigned index ); LLVMModuleRef LLVMNamedMDNodeGetParentModule( LLVMNamedMDNodeRef namedMDNode ); #ifdef __cplusplus } #endif #endif ================================================ FILE: Zelig/Zelig/CompileTime/Llvm.NET/LibLLVM/ValueBindings.cpp ================================================ #include "ValueBindings.h" #include #include #include #include using namespace llvm; extern "C" { uint32_t LLVMGetArgumentIndex( LLVMValueRef valueRef ) { auto pArgument = unwrap( valueRef ); return pArgument->getArgNo( ); } LLVMBool LLVMIsConstantZeroValue( LLVMValueRef valueRef ) { auto pConstant = dyn_cast< Constant >( unwrap( valueRef ) ); if( pConstant == nullptr ) return 0; return pConstant->isZeroValue( ) ? 1 : 0; } void LLVMRemoveGlobalFromParent( LLVMValueRef valueRef ) { auto pGlobal = dyn_cast< GlobalVariable >( unwrap( valueRef ) ); if( pGlobal == nullptr ) return; pGlobal->removeFromParent( ); } LLVMValueRef LLVMBuildIntCast2( LLVMBuilderRef B, LLVMValueRef Val, LLVMTypeRef DestTy, LLVMBool isSigned, const char *Name ) { return wrap( unwrap( B )->CreateIntCast( unwrap( Val ), unwrap( DestTy ), isSigned, Name ) ); } int LLVMGetValueID( LLVMValueRef valueRef ) { return unwrap( valueRef )->getValueID( ); } LLVMValueRef LLVMMetadataAsValue( LLVMContextRef context, LLVMMetadataRef metadataRef ) { LLVMContext* ctx = unwrap( context ); auto md = unwrap( metadataRef ); return wrap( MetadataAsValue::get( *ctx, md ) ); } LLVMValueRef LLVMGetAliasee( LLVMValueRef Val ) { auto pAlias = unwrap( Val ); return wrap( pAlias->getAliasee( ) ); } } ================================================ FILE: Zelig/Zelig/CompileTime/Llvm.NET/LibLLVM/ValueBindings.h ================================================ #ifndef _VALUE_BINDINGS_H_ #define _VALUE_BINDINGS_H_ #include "llvm-c/Core.h" #include "DIBuilderBindings.h" #ifdef __cplusplus extern "C" { #endif enum LLVMValueKind { LLVMValueKindArgumentVal, // This is an instance of Argument LLVMValueKindBasicBlockVal, // This is an instance of BasicBlock LLVMValueKindFunctionVal, // This is an instance of Function LLVMValueKindGlobalAliasVal, // This is an instance of GlobalAlias LLVMValueKindGlobalVariableVal, // This is an instance of GlobalVariable LLVMValueKindUndefValueVal, // This is an instance of UndefValue LLVMValueKindBlockAddressVal, // This is an instance of BlockAddress LLVMValueKindConstantExprVal, // This is an instance of ConstantExpr LLVMValueKindConstantAggregateZeroVal, // This is an instance of ConstantAggregateZero LLVMValueKindConstantDataArrayVal, // This is an instance of ConstantDataArray LLVMValueKindConstantDataVectorVal, // This is an instance of ConstantDataVector LLVMValueKindConstantIntVal, // This is an instance of ConstantInt LLVMValueKindConstantFPVal, // This is an instance of ConstantFP LLVMValueKindConstantArrayVal, // This is an instance of ConstantArray LLVMValueKindConstantStructVal, // This is an instance of ConstantStruct LLVMValueKindConstantVectorVal, // This is an instance of ConstantVector LLVMValueKindConstantPointerNullVal, // This is an instance of ConstantPointerNull LLVMValueKindMetadataAsValueVal, // This is an instance of MetadataAsValue LLVMValueKindInlineAsmVal, // This is an instance of InlineAsm LLVMValueKindInstructionVal, // This is an instance of Instruction // Enum values starting at InstructionVal are used for Instructions; // Markers: LLVMValueKindConstantFirstVal = LLVMValueKindFunctionVal, LLVMValueKindConstantLastVal = LLVMValueKindConstantPointerNullVal }; LLVMBool LLVMIsConstantZeroValue( LLVMValueRef valueRef ); void LLVMRemoveGlobalFromParent( LLVMValueRef valueRef ); LLVMValueRef LLVMBuildIntCast2( LLVMBuilderRef B, LLVMValueRef Val, LLVMTypeRef DestTy, LLVMBool isSigned, const char *Name ); int LLVMGetValueID( LLVMValueRef valueRef); LLVMValueRef LLVMMetadataAsValue( LLVMContextRef context, LLVMMetadataRef metadataRef ); LLVMValueRef LLVMGetAliasee( LLVMValueRef Val ); uint32_t LLVMGetArgumentIndex( LLVMValueRef Val); #ifdef __cplusplus } #endif #endif ================================================ FILE: Zelig/Zelig/CompileTime/Llvm.NET/LibLLVM/resource.h ================================================ //{{NO_DEPENDENCIES}} // Microsoft Visual C++ generated include file. // Used by Resource.rc // Next default values for new objects // #ifdef APSTUDIO_INVOKED #ifndef APSTUDIO_READONLY_SYMBOLS #define _APS_NEXT_RESOURCE_VALUE 101 #define _APS_NEXT_COMMAND_VALUE 40001 #define _APS_NEXT_CONTROL_VALUE 1001 #define _APS_NEXT_SYMED_VALUE 101 #endif #endif ================================================ FILE: Zelig/Zelig/CompileTime/Llvm.NET/LibLLVM/stdafx.h ================================================ // stdafx.h : include file for standard system include files, // or project specific include files that are used frequently, but // are changed infrequently // #pragma once #include "targetver.h" #define WIN32_LEAN_AND_MEAN // Exclude rarely-used stuff from Windows headers // Windows Header Files: #include // TODO: reference additional headers your program requires here ================================================ FILE: Zelig/Zelig/CompileTime/Llvm.NET/LibLLVM/targetver.h ================================================ #pragma once // Including SDKDDKVer.h defines the highest available Windows platform. // If you wish to build your application for a previous Windows platform, include WinSDKVer.h and // set the _WIN32_WINNT macro to the platform you wish to support before including SDKDDKVer.h. #include ================================================ FILE: Zelig/Zelig/CompileTime/Llvm.NET/Llvm.NET/ArgValidationExtensions.cs ================================================ using System; namespace Llvm.NET { internal static class ArgValidationExtensions { /// Fluent style method for validating a function argument is not null /// Type of the argument /// argument value to test for null /// name of the argument to appear in the exception /// /// unless it is null, in which case an /// is thrown. /// /// /// This is useful for validating cases where a parameter must be used to compute /// an additional parameter to a base class constructor. /// internal static T VerifyArgNotNull( this T self, string name ) where T : class { if( self == null ) throw new ArgumentNullException( name ); return self; } } } ================================================ FILE: Zelig/Zelig/CompileTime/Llvm.NET/Llvm.NET/Context.cs ================================================ using System; using System.Collections.Generic; using System.Diagnostics; using System.Linq; using System.Text; using Llvm.NET.DebugInfo; using Llvm.NET.Native; using Llvm.NET.Types; using Llvm.NET.Values; namespace Llvm.NET { /// Encapsulates an LLVM context /// /// A context in LLVM is a container for interning (LLVM refers /// to this as "uniqueing") various types and values in the system. This /// allows running multiple LLVM tool transforms etc.. on different threads /// without causing them to collide namespaces and types even if they use /// the same name (e.g. module one may have a type Foo, and so does module /// two but they are completely distinct from each other) /// /// LLVM Debug information is ultimately all parented to a top level /// as the scope, and a compilation /// unit is bound to a , even though, technically /// the types are owned by a Context. Thus to keep things simpler and help /// make working with debug information easier. Lllvm.NET encapsulates the /// native type and the debug type in separate classes that are instances /// of the interface /// It is important to be aware of the fact that a Context /// is not thread safe. The context itself and the object instances it owns /// are intended for use by a single thread only. Accessing and manipulating /// LLVM objects from multiple threads may lead to race conditions corrupted /// state and any number of other undefined issues. /// public sealed class Context : IDisposable { /// Creates a new context public Context( ) : this( NativeMethods.ContextCreate( ) ) { } /// Flag to indicate if this instance is still valid public bool IsDisposed => ContextHandle.Pointer == IntPtr.Zero; /// Get's the LLVM void type for this context public ITypeRef VoidType => TypeRef.FromHandle( NativeMethods.VoidTypeInContext( ContextHandle ) ); /// Get's the LLVM boolean type for this context public ITypeRef BoolType => TypeRef.FromHandle( NativeMethods.Int1TypeInContext( ContextHandle ) ); /// Get's the LLVM 8 bit integer type for this context public ITypeRef Int8Type => TypeRef.FromHandle( NativeMethods.Int8TypeInContext( ContextHandle ) ); /// Get's the LLVM 16 bit integer type for this context public ITypeRef Int16Type => TypeRef.FromHandle( NativeMethods.Int16TypeInContext( ContextHandle ) ); /// Get's the LLVM 32 bit integer type for this context public ITypeRef Int32Type => TypeRef.FromHandle( NativeMethods.Int32TypeInContext( ContextHandle ) ); /// Get's the LLVM 64 bit integer type for this context public ITypeRef Int64Type => TypeRef.FromHandle( NativeMethods.Int64TypeInContext( ContextHandle ) ); /// Get's the LLVM half precision floating point type for this context public ITypeRef HalfFloatType => TypeRef.FromHandle( NativeMethods.HalfTypeInContext( ContextHandle ) ); /// Get's the LLVM single precision floating point type for this context public ITypeRef FloatType => TypeRef.FromHandle( NativeMethods.FloatTypeInContext( ContextHandle ) ); /// Get's the LLVM double precision floating point type for this context public ITypeRef DoubleType => TypeRef.FromHandle( NativeMethods.DoubleTypeInContext( ContextHandle ) ); /// Gets an enumerable collection of all the metadata created in this context public IEnumerable Metadata => MetadataCache.Values; /// Get a type that is a pointer to a value of a given type /// Type of value the pointer points to /// for a pointer that references a value of type public IPointerType GetPointerTypeFor( ITypeRef elementType ) { if( elementType == null ) throw new ArgumentNullException( nameof( elementType ) ); if( elementType.Context != this ) throw new ArgumentException( "Cannot mix types from different contexts", nameof( elementType ) ); return TypeRef.FromHandle( NativeMethods.PointerType( elementType.GetTypeRef( ), 0 ) ); } /// Get's an LLVM integer type of arbitrary bit width /// /// For standard integer bit widths (e.g. 1,8,16,32,64) this will return /// the same type as the corresponding specialized property. /// (e.g. GetIntType(1) is the same as , /// GetIntType(16) is the same as , etc... ) /// public ITypeRef GetIntType( uint bitWidth ) { if( bitWidth == 0 ) throw new ArgumentException( "integer bit width must be greater than 0" ); switch( bitWidth ) { case 1: return BoolType; case 8: return Int8Type; case 16: return Int16Type; case 32: return Int32Type; case 64: return Int64Type; default: return TypeRef.FromHandle( NativeMethods.IntTypeInContext( ContextHandle, bitWidth ) ); } } /// Get an LLVM Function type (e.g. signature) /// Return type of the function /// Optional set of function argument types /// Signature type for the specified signature public IFunctionType GetFunctionType( ITypeRef returnType, params ITypeRef[ ] args ) { return GetFunctionType( returnType, args, false ); } /// Get an LLVM Function type (e.g. signature) /// Return type of the function /// Potentially empty set of function argument types /// Signature type for the specified signature public IFunctionType GetFunctionType( ITypeRef returnType, IEnumerable args ) { return GetFunctionType( returnType, args, false ); } /// Get an LLVM Function type (e.g. signature) /// Return type of the function /// Potentially empty set of function argument types /// Flag to indicate if the method supports C/C++ style VarArgs /// Signature type for the specified signature public IFunctionType GetFunctionType( ITypeRef returnType, IEnumerable args, bool isVarArgs ) { if( returnType == null ) throw new ArgumentNullException( nameof( returnType ) ); if( ContextHandle.Pointer != returnType.Context.ContextHandle.Pointer ) throw new ArgumentException( "Mismatched context", nameof( returnType ) ); LLVMTypeRef[ ] llvmArgs = args.Select( a => a.GetTypeRef( ) ).ToArray( ); var argCount = llvmArgs.Length; // have to pass a valid addressable object to native interop // so allocate space for a single value but tell LLVM the length is 0 if( llvmArgs.Length == 0 ) llvmArgs = new LLVMTypeRef[ 1 ]; var signature = NativeMethods.FunctionType( returnType.GetTypeRef( ), out llvmArgs[ 0 ], ( uint )argCount, isVarArgs ); return TypeRef.FromHandle( signature ); } /// Creates a FunctionType with Debug information /// to use to create the debug information /// Return type of the function /// Argument types of the function /// Function signature public DebugFunctionType CreateFunctionType( DebugInfoBuilder diBuilder , IDebugType retType , params IDebugType[ ] argTypes ) { return CreateFunctionType( diBuilder, false, retType, argTypes ); } /// Creates a FunctionType with Debug information /// to use to create the debug information /// Return type of the function /// Argument types of the function /// Function signature public DebugFunctionType CreateFunctionType( DebugInfoBuilder diBuilder , IDebugType retType , IEnumerable> argTypes ) { return CreateFunctionType( diBuilder, false, retType, argTypes ); } /// Creates a FunctionType with Debug information /// to use to create the debug information /// Flag to indicate if this function is variadic /// Return type of the function /// Argument types of the function /// Function signature public DebugFunctionType CreateFunctionType( DebugInfoBuilder diBuilder , bool isVarArg , IDebugType retType , params IDebugType[ ] argTypes ) { return CreateFunctionType( diBuilder, isVarArg, retType, ( IEnumerable> )argTypes ); } /// Creates a FunctionType with Debug information /// to use to create the debug information /// Flag to indicate if this function is variadic /// Return type of the function /// Argument types of the function /// Function signature public DebugFunctionType CreateFunctionType( DebugInfoBuilder diBuilder , bool isVarArg , IDebugType retType , IEnumerable> argTypes ) { if( diBuilder == null ) throw new ArgumentNullException( nameof( diBuilder ) ); if( !retType.HasDebugInfo( ) ) throw new ArgumentNullException( nameof( retType ), "Return type does not have debug information" ); var nativeArgTypes = new List( ); var debugArgTypes = new List( ); var msg = new StringBuilder( "One or more parameter types do not include debug information:\n" ); var missingDebugInfo = false; foreach( var indexedPair in argTypes.Select( ( t, i ) => new { Type = t, Index = i } ) ) { nativeArgTypes.Add( indexedPair.Type.NativeType ); debugArgTypes.Add( indexedPair.Type.DIType ); if( indexedPair.Type.HasDebugInfo( ) ) continue; msg.AppendFormat( "\tArgument {0} does not contain debug type information", indexedPair.Index ); missingDebugInfo = true; } // if any parameters don't have a valid DIType yet, then provide a hopefully helpful message indicating which one(s) if( missingDebugInfo ) throw new ArgumentException( msg.ToString( ), nameof( argTypes ) ); var llvmType = GetFunctionType( retType.NativeType, nativeArgTypes, isVarArg ); var diType = diBuilder.CreateSubroutineType( 0, retType.DIType, debugArgTypes ); Debug.Assert( diType != null && !diType.IsTemporary ); return new DebugFunctionType( llvmType, diType ); } /// Creates a constant structure from a set of values /// Flag to indicate if the structure is packed and no alignment should be applied to the members /// Set of values to use in forming the structure /// Newly created /// /// The actual concrete return type depends on the parameters provided and will be one of the following: /// /// /// derived typeDescription /// /// ConstantAggregateZeroIf all the member values are zero constants /// UndefValueIf all the member values are UndefValue /// ConstantStructAll other cases /// /// /// public Constant CreateConstantStruct( bool packed, params Constant[ ] values ) { return CreateConstantStruct( packed, ( IEnumerable )values ); } /// Creates a constant structure from a set of values /// Set of values to use in forming the structure /// Flag to indicate if the structure is packed and no alignment should be applied to the members /// Newly created /// /// The actual concrete return type depends on the parameters provided and will be one of the following: /// /// /// derived typeDescription /// /// ConstantAggregateZeroIf all the member values are zero constants /// UndefValueIf all the member values are UndefValue /// ConstantStructAll other cases /// /// /// public Constant CreateConstantStruct( bool packed, IEnumerable values ) { var valueHandles = values.Select( v => v.ValueHandle ).ToArray( ); if( valueHandles.Length == 0 ) throw new ArgumentException( "structure must have at least one element", nameof( values ) ); var handle = NativeMethods.ConstStructInContext( ContextHandle, out valueHandles[ 0 ], ( uint )valueHandles.Length, packed ); return Value.FromHandle( handle ); } /// Creates a constant instance of a specified structure type from a set of values /// Type of the structure to create /// Set of values to use in forming the structure /// Newly created /// /// The actual concrete return type depends on the parameters provided and will be one of the following: /// /// /// derived typeDescription /// /// ConstantAggregateZeroIf all the member values are zero constants /// UndefValueIf all the member values are UndefValue /// ConstantStructAll other cases /// /// /// public Constant CreateNamedConstantStruct( IStructType type, params Constant[ ] values ) { return CreateNamedConstantStruct( type, ( IEnumerable )values ); } /// Creates a constant instance of a specified structure type from a set of values /// Type of the structure to create /// Set of values to use in forming the structure /// Newly created /// /// The actual concrete return type depends on the parameters provided and will be one of the following: /// /// /// derived typeDescription /// /// ConstantAggregateZeroIf all the member values are zero constants /// UndefValueIf all the member values are UndefValue /// ConstantStructAll other cases /// /// /// public Constant CreateNamedConstantStruct( IStructType type, IEnumerable values ) { if( type == null ) throw new ArgumentNullException( nameof( type ) ); if( type.Context != this ) throw new ArgumentException( "Cannot create named constant struct with type from another context", nameof( type ) ); var valueList = values as IList ?? values.ToList( ); var valueHandles = valueList.Select( v => v.ValueHandle ).ToArray( ); if( type.Members.Count != valueHandles.Length ) throw new ArgumentException( "Number of values provided must match the number of elements in the specified type" ); var mismatchedTypes = from indexedVal in valueList.Select( ( v, i ) => new { Value = v, Index = i } ) where indexedVal.Value.NativeType != type.Members[ indexedVal.Index ] select indexedVal; if( mismatchedTypes.Any( ) ) { var msg = new StringBuilder( "One or more values provided do not match the corresponding member type:" ); msg.AppendLine( ); foreach( var mismatch in mismatchedTypes ) { msg.AppendFormat( "\t[{0}]: member type={1}; value type={2}" , mismatch.Index , type.Members[ mismatch.Index ] , valueList[ mismatch.Index ].NativeType ); } throw new ArgumentException( msg.ToString( ) ); } // To interop correctly, we need to have an array of at least size one. uint valuesLength = (uint)valueHandles.Length; if( valuesLength == 0 ) { valueHandles = new LLVMValueRef[1]; } var handle = NativeMethods.ConstNamedStruct( type.GetTypeRef( ), out valueHandles[ 0 ], valuesLength ); return Value.FromHandle( handle ); } /// Create an empty structure type /// Name of the type /// New type public IStructType CreateStructType( string name ) { if( string.IsNullOrWhiteSpace( name ) ) throw new ArgumentNullException( nameof( name ) ); var handle = NativeMethods.StructCreateNamed( ContextHandle, name ); return TypeRef.FromHandle( handle ); } /// Create an anonymous structure type (e.g. Tuple) /// Flag to indicate if the structure is "packed" /// Type of the first field of the structure /// Types of any additional fields of the structure /// /// with the specified body defined. /// public IStructType CreateStructType( bool packed, ITypeRef element0, params ITypeRef[ ] elements ) { if( elements == null ) throw new ArgumentNullException( nameof( elements ) ); LLVMTypeRef[ ] llvmArgs = new LLVMTypeRef[ elements.Length + 1 ]; llvmArgs[ 0 ] = element0.GetTypeRef( ); for( int i = 1; i < llvmArgs.Length; ++i ) llvmArgs[ i ] = elements[ i - 1 ].GetTypeRef( ); var handle = NativeMethods.StructTypeInContext( ContextHandle, out llvmArgs[ 0 ], ( uint )llvmArgs.Length, packed ); return TypeRef.FromHandle( handle ); } /// Creates a new structure type in this /// Name of the structure /// Flag indicating if the structure is packed /// Types for the structures elements in layout order /// /// with the specified body defined. /// /// /// If the elements argument list is empty then an opaque type is created (e.g. a forward reference) /// The method provides a means to add a body to /// an opaque type at a later time if the details of the body are required. (If only pointers to /// to the type are required the body isn't required) /// public IStructType CreateStructType( string name, bool packed, params ITypeRef[ ] elements ) { if( elements == null ) throw new ArgumentNullException( nameof( elements ) ); var retVal = TypeRef.FromHandle( NativeMethods.StructCreateNamed( ContextHandle, name ) ); if( elements.Length > 0 ) { retVal.SetBody( packed, elements ); } return retVal; } /// Creates a metadata string from the given string /// string to create as metadata /// new metadata string public MDString CreateMetadataString( string value ) { value = value ?? string.Empty; var handle = NativeMethods.MDString2( ContextHandle, value, ( uint )value.Length ); return new MDString( handle ); } /// Create a constant data string value /// string to convert into an LLVM constant value /// new /// /// This converts th string to ANSI form and creates an LLVM constant array of i8 /// characters for the data without any terminating null character. /// public ConstantDataArray CreateConstantString( string value ) { if( value == null ) throw new ArgumentNullException( nameof( value ) ); var handle = NativeMethods.ConstStringInContext( ContextHandle, value, ( uint )value.Length, true ); return Value.FromHandle( handle ); } /// Create a constant data string value /// string to convert into an LLVM constant value /// flag to indicate if the string should include a null terminator /// new /// /// This converts the string to ANSI form and creates an LLVM constant array of i8 /// characters for the data without any terminating null character. /// public ConstantDataArray CreateConstantString( string value, bool nullTerminate ) { if( value == null ) throw new ArgumentNullException( nameof( value ) ); var handle = NativeMethods.ConstStringInContext( ContextHandle, value, ( uint )value.Length, !nullTerminate ); return Value.FromHandle( handle ); } /// Creates a new with a bit length of 1 /// Value for the constant /// representing the value public Constant CreateConstant( bool constValue ) { var handle = NativeMethods.ConstInt( BoolType.GetTypeRef( ) , ( ulong )( constValue ? 1 : 0 ) , new LLVMBool( 0 ) ); return Value.FromHandle( handle ); } /// Creates a new with a bit length of 8 /// Value for the constant /// representing the value public Constant CreateConstant( byte constValue ) { var handle = NativeMethods.ConstInt( Int8Type.GetTypeRef( ), constValue, new LLVMBool( 0 ) ); return Value.FromHandle( handle ); } /// Creates a new with a bit length of 8 /// Value for the constant /// representing the value public Constant CreateConstant( sbyte constValue ) { var handle = NativeMethods.ConstInt( Int8Type.GetTypeRef( ), ( ulong )constValue, new LLVMBool( 1 ) ); return Value.FromHandle( handle ); } /// Creates a new with a bit length of 16 /// Value for the constant /// representing the value public Constant CreateConstant( Int16 constValue ) { var handle = NativeMethods.ConstInt( Int16Type.GetTypeRef( ), ( ulong )constValue, new LLVMBool( 1 ) ); return Value.FromHandle( handle ); } /// Creates a new with a bit length of 16 /// Value for the constant /// representing the value [System.Diagnostics.CodeAnalysis.SuppressMessage( "Language", "CSE0003:Use expression-bodied members", Justification = "Readability" )] public Constant CreateConstant( UInt16 constValue ) { var handle = NativeMethods.ConstInt( Int16Type.GetTypeRef( ), constValue, new LLVMBool( 0 ) ); return Value.FromHandle( handle ); } /// Creates a new with a bit length of 32 /// Value for the constant /// representing the value public Constant CreateConstant( Int32 constValue ) { var handle = NativeMethods.ConstInt( Int32Type.GetTypeRef( ), ( ulong )constValue, new LLVMBool( 1 ) ); return Value.FromHandle( handle ); } /// Creates a new with a bit length of 32 /// Value for the constant /// representing the value public Constant CreateConstant( UInt32 constValue ) { var handle = NativeMethods.ConstInt( Int32Type.GetTypeRef( ), constValue, new LLVMBool( 0 ) ); return Value.FromHandle( handle ); } /// Creates a new with a bit length of 64 /// Value for the constant /// representing the value public Constant CreateConstant( Int64 constValue ) { var handle = NativeMethods.ConstInt( Int64Type.GetTypeRef( ), ( ulong )constValue, new LLVMBool( 1 ) ); return Value.FromHandle( handle ); } /// Creates a new with a bit length of 64 /// Value for the constant /// representing the value [System.Diagnostics.CodeAnalysis.SuppressMessage( "Language", "CSE0003:Use expression-bodied members", Justification = "Readability" )] public Constant CreateConstant( UInt64 constValue ) { var handle = NativeMethods.ConstInt( Int64Type.GetTypeRef( ), constValue, new LLVMBool( 0 ) ); return Value.FromHandle( handle ); } /// Creates a new with a bit length of 64 /// Bit width of the integer /// Value for the constant /// flag to indicate if the const value should be sign extended /// representing the value public Constant CreateConstant( uint bitWidth, UInt64 constValue, bool signExtend ) { var intType = GetIntType( bitWidth ); return CreateConstant( intType, constValue, signExtend ); } /// Create a constant value of the specified integer type /// Integer type /// value /// flag to indicate if is sign extended /// Constant for the specified value public Constant CreateConstant( ITypeRef intType, UInt64 constValue, bool signExtend ) { if( intType == null ) throw new ArgumentNullException( nameof( intType ) ); if( intType.Context != this ) throw new ArgumentException( "Cannot mix types from different contexts", nameof( intType ) ); if( intType.Kind != TypeKind.Integer ) throw new ArgumentException( "Integer type required", nameof( intType ) ); return Value.FromHandle( NativeMethods.ConstInt( intType.GetTypeRef( ), constValue, signExtend ) ); } /// Creates a constant floating point value for a given value /// Value to make into a /// Constant value public ConstantFP CreateConstant( float constValue ) { return Value.FromHandle( NativeMethods.ConstReal( FloatType.GetTypeRef( ), constValue ) ); } /// Creates a constant floating point value for a given value /// Value to make into a /// Constant value public ConstantFP CreateConstant( double constValue ) { return Value.FromHandle( NativeMethods.ConstReal( DoubleType.GetTypeRef( ), constValue ) ); } /// Current context for the current thread /// /// While most LLVM types contain the ability to retrieve their owning /// it is not always possible. For example, in LLVM, an empty doesn't /// actually have a Context so adding attributes to an empty requires /// a but adding attributes to a non-empty set does not. Thus, without some /// other means of getting a default multiple overloads for the Add operation /// would need to exist. Furthermore, calling code would need to manage dealing with deciding which /// variation of the overloaded methods to call at runtime. All of that and other similar cases are /// eliminated by having a thread static property to access whenever a instance /// is required but otherwise not conveniently available. /// public static Context CurrentContext => CurrentThreadContext; // These methods provide unique mapping between the .NET wrappers and the underlying LLVM instances // The mapping ensures that any LibLLVM handle is always re-mappable to a exactly one wrapper instance. // This helps reduce the number of wrapper instances created and also allows reference equality to work // as expected for managed types. #region Interning Factories internal void AddModule( NativeModule module ) { ModuleCache.Add( module.ModuleHandle.Pointer, module ); } internal NativeModule GetModuleFor( LLVMModuleRef moduleRef ) { if( moduleRef.Pointer == IntPtr.Zero ) throw new ArgumentNullException( nameof( moduleRef ) ); var hModuleContext = NativeMethods.GetModuleContext( moduleRef ); if( hModuleContext.Pointer != ContextHandle.Pointer ) throw new ArgumentException( "Incorrect context for module" ); NativeModule retVal; if( !ModuleCache.TryGetValue( moduleRef.Pointer, out retVal ) ) retVal = new NativeModule( moduleRef ); return retVal; } internal static Context GetContextFor( LLVMModuleRef moduleRef ) { if( moduleRef.Pointer == IntPtr.Zero ) return null; var hContext = NativeMethods.GetModuleContext( moduleRef ); Debug.Assert( hContext.Pointer != IntPtr.Zero ); return GetContextFor( hContext ); } internal static Context GetContextFor( LLVMValueRef valueRef ) { if( valueRef.Pointer == IntPtr.Zero ) return null; var hType = NativeMethods.TypeOf( valueRef ); Debug.Assert( hType.Pointer != IntPtr.Zero ); return GetContextFor( hType ); } internal static Context GetContextFor( LLVMTypeRef typeRef ) { if( typeRef.Pointer == IntPtr.Zero ) return null; var hContext = NativeMethods.GetTypeContext( typeRef ); Debug.Assert( hContext.Pointer != IntPtr.Zero ); return GetContextFor( hContext ); } internal static Context GetContextFor( LLVMContextRef contextRef ) { if( contextRef.Pointer == IntPtr.Zero ) return null; lock ( ContextCache ) { Context retVal; if( ContextCache.TryGetValue( contextRef, out retVal ) ) return retVal; return new Context( contextRef ); } } internal static Context GetContextFor( LLVMMetadataRef handle ) { if( handle == LLVMMetadataRef.Zero ) return null; var hContext = NativeMethods.GetNodeContext( handle ); Debug.Assert( hContext.Pointer != IntPtr.Zero ); return GetContextFor( hContext ); } internal void RemoveDeletedNode( MDNode node ) { MetadataCache.Remove( node.MetadataHandle ); } internal LLVMContextRef ContextHandle { get; private set; } [System.Diagnostics.CodeAnalysis.SuppressMessage( "Microsoft.Performance", "CA1822:MarkMembersAsStatic", Justification = "Conditional attribute makes this an empty method in release builds" )] [Conditional( "DEBUG" )] internal void AssertValueNotInterned( LLVMValueRef valueRef ) { Debug.Assert( !ValueCache.ContainsKey( valueRef.Pointer ) ); } internal Value GetValueFor( LLVMValueRef valueRef, Func constructor ) { if( valueRef.Pointer == IntPtr.Zero ) throw new ArgumentNullException( nameof( valueRef ) ); Value retVal = null; if( ValueCache.TryGetValue( valueRef.Pointer, out retVal ) ) return retVal; retVal = constructor( valueRef ); ValueCache.Add( valueRef.Pointer, retVal ); return retVal; } internal LlvmMetadata GetNodeFor( LLVMMetadataRef handle, Func staticFactory ) { if( handle == LLVMMetadataRef.Zero ) throw new ArgumentNullException( nameof( handle ) ); LlvmMetadata retVal = null; if( MetadataCache.TryGetValue( handle, out retVal ) ) return retVal; retVal = staticFactory( handle ); MetadataCache.Add( handle, retVal ); return retVal; } internal MDOperand GetOperandFor( MDNode owningNode, LLVMMDOperandRef handle ) { if( owningNode.Context != this ) throw new ArgumentException( "Cannot get operand for a node from a different context", nameof( owningNode ) ); if( handle.Pointer == IntPtr.Zero ) throw new ArgumentNullException( nameof( handle ) ); MDOperand retVal = null; if( MDOperandCache.TryGetValue( handle, out retVal ) ) return retVal; retVal = new MDOperand( owningNode, handle ); MDOperandCache.Add( handle, retVal ); return retVal; } [System.Diagnostics.CodeAnalysis.SuppressMessage( "Microsoft.Performance", "CA1822:MarkMembersAsStatic", Justification = "Conditional attribute makes this an empty method in release builds" )] [Conditional( "DEBUG" )] internal void AssertTypeNotInterned( LLVMTypeRef typeRef ) { Debug.Assert( !TypeCache.ContainsKey( typeRef.Pointer ) ); } internal ITypeRef GetTypeFor( LLVMTypeRef valueRef, Func constructor ) { if( valueRef.Pointer == IntPtr.Zero ) throw new ArgumentNullException( nameof( valueRef ) ); ITypeRef retVal; if( TypeCache.TryGetValue( valueRef.Pointer, out retVal ) ) return retVal; retVal = constructor( valueRef ); TypeCache.Add( valueRef.Pointer, retVal ); return retVal; } #endregion #region IDisposable Support [System.Diagnostics.CodeAnalysis.SuppressMessage( "Microsoft.Usage", "CA1801:ReviewUnusedParameters", MessageId = "disposing" )] void Dispose( bool disposing ) { if( ContextHandle.Pointer != IntPtr.Zero ) { // allow creating another context after this one is disposed if( CurrentThreadContext == this ) CurrentThreadContext = null; lock ( ContextCache ) { ContextCache.Remove( ContextHandle ); } NativeMethods.ContextDispose( ContextHandle ); ContextHandle = default( LLVMContextRef ); } } ~Context( ) { Dispose( false ); } // This code added to correctly implement the disposable pattern. public void Dispose( ) { Dispose( true ); GC.SuppressFinalize( this ); } #endregion private Context( LLVMContextRef contextRef ) { if( CurrentThreadContext != null ) throw new InvalidOperationException( "Context already exists for this thread" ); ContextHandle = contextRef; lock ( ContextCache ) { ContextCache.Add( contextRef, this ); } NativeMethods.ContextSetDiagnosticHandler( ContextHandle, DiagnosticHandler, IntPtr.Zero ); CurrentThreadContext = this; } [ThreadStatic] private static Context CurrentThreadContext; private void DiagnosticHandler( out LLVMOpaqueDiagnosticInfo param0, IntPtr param1 ) { Debug.Assert( false ); } private readonly Dictionary< IntPtr, Value > ValueCache = new Dictionary< IntPtr, Value >( ); private readonly Dictionary< IntPtr, ITypeRef > TypeCache = new Dictionary< IntPtr, ITypeRef >( ); private readonly Dictionary< IntPtr, NativeModule > ModuleCache = new Dictionary< IntPtr, NativeModule >( ); private readonly Dictionary< LLVMMetadataRef, LlvmMetadata > MetadataCache = new Dictionary< LLVMMetadataRef, LlvmMetadata >( ); private readonly Dictionary< LLVMMDOperandRef, MDOperand > MDOperandCache = new Dictionary< LLVMMDOperandRef, MDOperand >( ); private static Dictionary ContextCache = new Dictionary( ); } } ================================================ FILE: Zelig/Zelig/CompileTime/Llvm.NET/Llvm.NET/ContextValidator.cs ================================================ using System; namespace Llvm.NET { /// Provides validation extensions to the class /// /// These are done as extensions deliberately to allow for the possibility that the provided /// context may actually be , which wouldn't be possible as member methods. /// public static class ContextValidator { /// Throw an if the is or is disposed /// to test /// Argument name /// Error message for the exception public static Context VerifyAsArg( this Context context, string name, string message ) { Verify( context, name, message, ThrowArgException ); return context; } /// Throw an if the is or is disposed /// to test /// Argument name public static Context VerifyAsArg( this Context context, string name ) => VerifyAsArg( context, name, InvalidContextArgMsg ); /// Throw an if the is or is disposed /// to test /// Error message for the exception public static Context VerifyOperation( this Context context, string message ) { return Verify( context, null, message, ThrowInvalidOperationException ); } /// Throw an if the is or is disposed /// to test public static Context VerifyOperation( this Context context ) => VerifyOperation( context, InvalidContextOperationMsg ); /// Execute a given action if the is or is disposed /// to test /// Argument name or if name is not needed by the supplied /// Error message for the /// Action to perform if the verification fails public static Context Verify( this Context context, string name, string message, Action failAction ) { if( failAction == null ) throw new ArgumentNullException( nameof( failAction ) ); if( context == null || context.IsDisposed ) { failAction( name, message ); } return context; } private static void ThrowArgException( string name, string message ) { throw new ArgumentException( message, name ); } private static void ThrowInvalidOperationException( string name, string message ) { throw new InvalidOperationException( message ); } private const string InvalidContextArgMsg = "Provided context cannot be null or disposed"; private const string InvalidContextOperationMsg = "Cannot use a null or disposed Context"; } } ================================================ FILE: Zelig/Zelig/CompileTime/Llvm.NET/Llvm.NET/DataLayout.cs ================================================ using System; using System.Collections.Generic; using Llvm.NET.Native; using Llvm.NET.Types; using Llvm.NET.Values; namespace Llvm.NET { // TODO: rename this to DataLayout to match underlying LLVM // TODO: update this to reflect the deprecation of retrieving a pointer to the layout in 3.7.0 // (e.g. the layout should be copy constructed, rather than holding a pointer/handle) /// Provides access to LLVM target data layout information /// /// There is a distinction between various sizes and alignment for a given type /// that are target dependent. /// The following table illustrates the differences in sizes and their meaning /// for a sample set of types. /// /// /// Type /// SizeInBits /// StoreSizeInBits /// AllocSizeInBits /// /// i1 1 8 8 /// i8 8 8 8 /// i19 19 24 32 /// i32 32 32 32 /// i100 100 104 128 /// i128 128 128 128 /// Float 32 32 32 /// Double 64 64 64 /// X86_FP80 80 80 96 /// /// /// The alloc size depends on the alignment, and thus on the target. /// The values in the example table are for x86-32-linux. /// /// public class DataLayout : IDisposable { /// Context used for this data (in particular, for retrieving pointer types) public Context Context { get; } /// Retrieves the byte ordering for this target public ByteOrdering Endianess => ( ByteOrdering )NativeMethods.ByteOrder( OpaqueHandle ); /// Retrieves the size of a pointer for the default address space of the target /// Size of a pointer to the default address space public uint PointerSize( ) => NativeMethods.PointerSize( OpaqueHandle ); /// Retrieves the size of a pointer for a given address space of the target /// Address space for the pointer /// Size of a pointer public uint PointerSize( uint addressSpace ) => NativeMethods.PointerSizeForAS( OpaqueHandle, addressSpace ); /// Retrieves an LLVM integer type with the same bit width as /// a pointer for the default address space of the target /// Integer type matching the bit width of a native pointer in the target's default address space public ITypeRef IntPtrType( ) => TypeRef.FromHandle( NativeMethods.IntPtrTypeInContext( Context.ContextHandle, OpaqueHandle ) ); /// Retrieves an LLVM integer type with the same bit width as /// a pointer for the given address space of the target /// Integer type matching the bit width of a native pointer in the target's address space public ITypeRef IntPtrType( uint addressSpace ) { var typeHandle = NativeMethods.IntPtrTypeForASInContext( Context.ContextHandle, OpaqueHandle, addressSpace ); return TypeRef.FromHandle( typeHandle ); } /// Returns the number of bits necessary to hold the specified type. /// Type to retrieve the size of /// /// This method determines the bit size of a type (e.g. the minimum number of /// bits required to represent any value of the given type.) This is distinct from the storage /// and stack size due to various target alignment requirements. /// public ulong BitSizeOf( ITypeRef typeRef ) { VerifySized( typeRef, nameof( typeRef ) ); return NativeMethods.SizeOfTypeInBits( OpaqueHandle, typeRef.GetTypeRef( ) ); } /// Retrieves the number of bits required to store a value of the given type /// Type to retrieve the storage size of /// Number of bits required to store a value of the given type in the target /// This method retrieves the storage size in bits of a given type. The storage size /// includes any trailing padding bits that may be needed if the target requires reading a wider /// word size. (e.g. most systems can't write a single bit value for an LLVM i1, thus the /// storage size is whatever the minimum number of bits that the target requires to store a value /// of the given type) /// public ulong StoreSizeOf( ITypeRef typeRef ) { VerifySized( typeRef, nameof( typeRef ) ); return NativeMethods.StoreSizeOfType( OpaqueHandle, typeRef.GetTypeRef( ) ); } /// Retrieves the ABI specified size of the given type /// Type to get the size from /// Size of the type public ulong AbiSizeOf( ITypeRef typeRef ) { VerifySized( typeRef, nameof( typeRef ) ); return NativeMethods.ABISizeOfType( OpaqueHandle, typeRef.GetTypeRef( ) ); } /// Retrieves the ABI specified alignment, in bytes, for a specified type /// Type to get the alignment for /// ABI specified alignment public uint AbiAlignmentOf( ITypeRef typeRef ) { VerifySized( typeRef, nameof( typeRef ) ); return NativeMethods.ABIAlignmentOfType( OpaqueHandle, typeRef.GetTypeRef( ) ); } /// Retrieves the call frame alignment for a given type /// type to get the alignment of /// Alignment for the type public uint CallFrameAlignmentOf( ITypeRef typeRef ) { VerifySized( typeRef, nameof( typeRef ) ); return NativeMethods.CallFrameAlignmentOfType( OpaqueHandle, typeRef.GetTypeRef( ) ); } public uint PreferredAlignmentOf( ITypeRef typeRef ) { VerifySized( typeRef, nameof( typeRef ) ); return NativeMethods.PreferredAlignmentOfType( OpaqueHandle, typeRef.GetTypeRef( ) ); } public uint PreferredAlignmentOf( Value value ) { if( value == null ) throw new ArgumentNullException( nameof( value ) ); VerifySized( value.NativeType, nameof( value ) ); return NativeMethods.PreferredAlignmentOfGlobal( OpaqueHandle, value.ValueHandle ); } [System.Diagnostics.CodeAnalysis.SuppressMessage( "Microsoft.Design", "CA1011:ConsiderPassingBaseTypesAsParameters", Justification = "Specific type required by interop call" )] public uint ElementAtOffset( IStructType structType, ulong offset ) { VerifySized( structType, nameof( structType ) ); return NativeMethods.ElementAtOffset( OpaqueHandle, structType.GetTypeRef( ), offset ); } [System.Diagnostics.CodeAnalysis.SuppressMessage( "Microsoft.Design", "CA1011:ConsiderPassingBaseTypesAsParameters", Justification = "Specific type required by interop call" )] public ulong OffsetOfElement( IStructType structType, uint element ) { VerifySized( structType, nameof( structType ) ); return NativeMethods.OffsetOfElement( OpaqueHandle, structType.GetTypeRef( ), element ); } public override string ToString( ) { IntPtr msgPtr = NativeMethods.CopyStringRepOfTargetData( OpaqueHandle ); return NativeMethods.MarshalMsg( msgPtr ); } public ulong ByteSizeOf( ITypeRef llvmType ) => BitSizeOf( llvmType ) / 8u; public uint PreferredBitAlignementOf( ITypeRef llvmType ) => PreferredAlignmentOf( llvmType ) * 8; public uint AbiBitAlignmentOf( ITypeRef llvmType ) => AbiAlignmentOf( llvmType ) * 8; public ulong BitOffsetOfElement( IStructType llvmType, uint element ) => OffsetOfElement( llvmType, element ) * 8; /// Parses an LLVM target layout string /// for types created by the new /// string to parse /// Parsed target data /// For full details on the syntax of the string see http://llvm.org/releases/3.7.0/docs/LangRef.html#data-layout public static DataLayout Parse( Context context, string layout ) { var handle = NativeMethods.CreateTargetData( layout ); return FromHandle( context, handle, true ); } #region IDisposable Support private readonly bool IsDisposable; protected virtual void Dispose( bool disposing ) { if( OpaqueHandle.Pointer != IntPtr.Zero && IsDisposable ) { NativeMethods.DisposeTargetData( OpaqueHandle ); OpaqueHandle = default( LLVMTargetDataRef ); } } ~DataLayout( ) { // Do not change this code. Put cleanup code in Dispose(bool disposing) above. Dispose( false ); } // This code added to correctly implement the disposable pattern. public void Dispose( ) { // Do not change this code. Put cleanup code in Dispose(bool disposing) above. Dispose( true ); GC.SuppressFinalize( this ); } #endregion internal DataLayout( Context context, LLVMTargetDataRef targetDataHandle, bool isDisposable ) { OpaqueHandle = targetDataHandle; IsDisposable = isDisposable; Context = context; } internal static DataLayout FromHandle( Context context, LLVMTargetDataRef targetDataRef, bool isDisposable ) { lock ( TargetDataMap ) { DataLayout retVal; if( TargetDataMap.TryGetValue( targetDataRef.Pointer, out retVal ) ) return retVal; retVal = new DataLayout( context, targetDataRef, isDisposable ); TargetDataMap.Add( targetDataRef.Pointer, retVal ); return retVal; } } internal LLVMTargetDataRef OpaqueHandle { get; private set; } private static void VerifySized( ITypeRef type, string name ) { if( !type.IsSized ) throw new ArgumentException( "Type must be sized to get target size information", name ); } private static readonly Dictionary TargetDataMap = new Dictionary( ); } } ================================================ FILE: Zelig/Zelig/CompileTime/Llvm.NET/Llvm.NET/DebugInfo/DIBasicType.cs ================================================ using Llvm.NET.Native; namespace Llvm.NET.DebugInfo { /// Debug information for a basic type /// public class DIBasicType : DIType { internal DIBasicType( LLVMMetadataRef handle ) : base( handle ) { } } } ================================================ FILE: Zelig/Zelig/CompileTime/Llvm.NET/Llvm.NET/DebugInfo/DICompileUnit.cs ================================================ using Llvm.NET.Native; namespace Llvm.NET.DebugInfo { /// see public class DICompileUnit : DIScope { internal DICompileUnit( LLVMMetadataRef handle ) : base( handle ) { } } } ================================================ FILE: Zelig/Zelig/CompileTime/Llvm.NET/Llvm.NET/DebugInfo/DICompositeType.cs ================================================ using System.Collections.Generic; using Llvm.NET.Native; namespace Llvm.NET.DebugInfo { /// see public class DICompositeType : DIType { internal DICompositeType( LLVMMetadataRef handle ) : base( handle ) { } public DIType BaseType => Operands[ 3 ].Metadata as DIType; public IReadOnlyList Elements => new TupleTypedArrayWrapper( Operands[ 4 ].Metadata as MDTuple ); // TODO: VTableHolder Operands[5] // TODO: TemplateParams Operands[6] // TODO: Identifier Operands[7] } } ================================================ FILE: Zelig/Zelig/CompileTime/Llvm.NET/Llvm.NET/DebugInfo/DIDerivedType.cs ================================================ using Llvm.NET.Native; namespace Llvm.NET.DebugInfo { /// see public class DIDerivedType : DIType { internal DIDerivedType( LLVMMetadataRef handle ) : base( handle ) { } } } ================================================ FILE: Zelig/Zelig/CompileTime/Llvm.NET/Llvm.NET/DebugInfo/DIEnumerator.cs ================================================ using Llvm.NET.Native; namespace Llvm.NET.DebugInfo { /// see public class DIEnumerator : DINode { internal DIEnumerator( LLVMMetadataRef handle ) : base( handle ) { } } } ================================================ FILE: Zelig/Zelig/CompileTime/Llvm.NET/Llvm.NET/DebugInfo/DIExpression.cs ================================================ using Llvm.NET.Native; namespace Llvm.NET.DebugInfo { /// see public class DIExpression : MDNode { internal DIExpression( LLVMMetadataRef handle ) : base( handle ) { } } } ================================================ FILE: Zelig/Zelig/CompileTime/Llvm.NET/Llvm.NET/DebugInfo/DIFile.cs ================================================ using System; using System.Runtime.InteropServices; using Llvm.NET.Native; namespace Llvm.NET.DebugInfo { /// see public class DIFile : DIScope { internal DIFile( LLVMMetadataRef handle ) : base( handle ) { } public string FileName { get { IntPtr name = NativeMethods.GetDIFileName( MetadataHandle ); return Marshal.PtrToStringAnsi( name ); } } public string Directory { get { IntPtr dir = NativeMethods.GetDIFileDirectory( MetadataHandle ); return Marshal.PtrToStringAnsi( dir ); } } public string Path => System.IO.Path.Combine( Directory, FileName ); } } ================================================ FILE: Zelig/Zelig/CompileTime/Llvm.NET/Llvm.NET/DebugInfo/DIGlobalVariable.cs ================================================ using Llvm.NET.Native; namespace Llvm.NET.DebugInfo { /// see public class DIGlobalVariable : DIVariable { internal DIGlobalVariable( LLVMMetadataRef handle ) : base( handle ) { } } } ================================================ FILE: Zelig/Zelig/CompileTime/Llvm.NET/Llvm.NET/DebugInfo/DIImportedEntity.cs ================================================ using Llvm.NET.Native; namespace Llvm.NET.DebugInfo { /// see public class DIImportedEntity : DINode { internal DIImportedEntity( LLVMMetadataRef handle ) : base( handle ) { } } } ================================================ FILE: Zelig/Zelig/CompileTime/Llvm.NET/Llvm.NET/DebugInfo/DILexicalBlock.cs ================================================ using Llvm.NET.Native; namespace Llvm.NET.DebugInfo { /// see public class DILexicalBlock : DILexicalBlockBase { internal DILexicalBlock( LLVMMetadataRef handle ) : base( handle ) { } } } ================================================ FILE: Zelig/Zelig/CompileTime/Llvm.NET/Llvm.NET/DebugInfo/DILexicalBlockBase.cs ================================================ using Llvm.NET.Native; namespace Llvm.NET.DebugInfo { public class DILexicalBlockBase : DILocalScope { internal DILexicalBlockBase( LLVMMetadataRef handle ) : base( handle ) { } } } ================================================ FILE: Zelig/Zelig/CompileTime/Llvm.NET/Llvm.NET/DebugInfo/DILexicalBlockFile.cs ================================================ using Llvm.NET.Native; namespace Llvm.NET.DebugInfo { /// see public class DILexicalBlockFile : DILexicalBlockBase { internal DILexicalBlockFile( LLVMMetadataRef handle ) : base( handle ) { } } } ================================================ FILE: Zelig/Zelig/CompileTime/Llvm.NET/Llvm.NET/DebugInfo/DILocalScope.cs ================================================ using Llvm.NET.Native; namespace Llvm.NET.DebugInfo { /// Legal scope for lexical blocks, local variables, and debug info locations public class DILocalScope : DIScope { internal DILocalScope( LLVMMetadataRef handle ) : base( handle ) { } // returns "this" if the scope is a subprogram, otherwise walks up the scopes to find // the containing subprogram. public DISubProgram SubProgram => FromHandle< DISubProgram>( NativeMethods.DILocalScopeGetSubProgram(MetadataHandle) ); } } ================================================ FILE: Zelig/Zelig/CompileTime/Llvm.NET/Llvm.NET/DebugInfo/DILocalVariable.cs ================================================ using Llvm.NET.Native; namespace Llvm.NET.DebugInfo { /// see public class DILocalVariable : DIVariable { internal DILocalVariable( LLVMMetadataRef handle ) : base( handle ) { } public new DILocalScope Scope => base.Scope as DILocalScope; } } ================================================ FILE: Zelig/Zelig/CompileTime/Llvm.NET/Llvm.NET/DebugInfo/DILocation.cs ================================================ using Llvm.NET.Native; using Llvm.NET.Values; namespace Llvm.NET.DebugInfo { public class DILocation : MDNode { public DILocation( Context context, uint line, uint column, DILocalScope scope ) : this( context, line, column, scope, null ) { } public DILocation( Context context, uint line, uint column, DILocalScope scope, DILocation inlinedAt ) : base( NativeMethods.DILocation( context.VerifyArgNotNull( nameof( context ) ).ContextHandle , line , column , scope.VerifyArgNotNull(nameof(scope)).MetadataHandle , inlinedAt?.MetadataHandle ?? LLVMMetadataRef.Zero ) ) { } public DILocalScope Scope => FromHandle< DILocalScope >( NativeMethods.GetDILocationScope( MetadataHandle ) ); public uint Line => NativeMethods.GetDILocationLine( MetadataHandle ); public uint Column => NativeMethods.GetDILocationColumn( MetadataHandle ); public DILocation InlinedAt { get { var handle = NativeMethods.GetDILocationInlinedAt( MetadataHandle ); return FromHandle( handle ); } } public DILocalScope InlinedAtScope { get { var handle = NativeMethods.DILocationGetInlinedAtScope( MetadataHandle ); return FromHandle( handle ); } } public override string ToString( ) { return $"{Scope.File}({Line},{Column})"; } public bool Describes( Function function ) { return Scope.SubProgram.Describes( function ) || InlinedAtScope.SubProgram.Describes( function ); } internal DILocation( LLVMMetadataRef handle ) : base( handle ) { } } } ================================================ FILE: Zelig/Zelig/CompileTime/Llvm.NET/Llvm.NET/DebugInfo/DIModule.cs ================================================ using Llvm.NET.Native; namespace Llvm.NET.DebugInfo { public class DIModule : DIScope { internal DIModule( LLVMMetadataRef handle ) : base( handle ) { } } } ================================================ FILE: Zelig/Zelig/CompileTime/Llvm.NET/Llvm.NET/DebugInfo/DINamespace.cs ================================================ using Llvm.NET.Native; namespace Llvm.NET.DebugInfo { /// see public class DINamespace : DIScope { internal DINamespace( LLVMMetadataRef handle ) : base( handle ) { } } } ================================================ FILE: Zelig/Zelig/CompileTime/Llvm.NET/Llvm.NET/DebugInfo/DINode.cs ================================================ using System; using Llvm.NET.Native; namespace Llvm.NET.DebugInfo { /// Root of the object hierarchy for Debug information metadata nodes public class DINode : MDNode { /// Dwarf tag for the descriptor public Tag Tag { get { if( MetadataHandle.Pointer == IntPtr.Zero ) return (Tag)(ushort.MaxValue); return ( Tag )NativeMethods.DIDescriptorGetTag( MetadataHandle ); } } internal DINode( LLVMMetadataRef handle ) : base( handle ) { } } } ================================================ FILE: Zelig/Zelig/CompileTime/Llvm.NET/Llvm.NET/DebugInfo/DINodeArray.cs ================================================ using System; using System.Collections; using System.Collections.Generic; using System.Linq; namespace Llvm.NET.DebugInfo { /// Generic wrapper to treat an MDTuple as an array of elements of specific type /// Type of elements /// /// This treats the operands of a tuple as the elements of the array /// [System.Diagnostics.CodeAnalysis.SuppressMessage( "Microsoft.Naming", "CA1710:IdentifiersShouldHaveCorrectSuffix" )] public class TupleTypedArrayWrapper : IReadOnlyList where T : LlvmMetadata { public TupleTypedArrayWrapper( MDTuple tuple ) { Tuple = tuple; } public MDTuple Tuple { get; } public int Count => Tuple.Operands.Count; public T this[ int index ] { get { if( Tuple == null ) throw new InvalidOperationException( "Wrapped node is null" ); if( index > Tuple.Operands.Count ) throw new ArgumentOutOfRangeException( nameof( index ) ); return Tuple.Operands[ index ].Metadata as T; } } public IEnumerator GetEnumerator( ) { return Tuple.Operands .Select( n => n.Metadata as T ) .GetEnumerator(); } IEnumerator IEnumerable.GetEnumerator( ) { return GetEnumerator(); } } /// Array of debug information nodes for use with methods /// [System.Diagnostics.CodeAnalysis.SuppressMessage( "Microsoft.Naming", "CA1710:IdentifiersShouldHaveCorrectSuffix" )] public class DINodeArray : TupleTypedArrayWrapper { internal DINodeArray( MDTuple tuple ) : base( tuple ) { } } } ================================================ FILE: Zelig/Zelig/CompileTime/Llvm.NET/Llvm.NET/DebugInfo/DIObjCProperty.cs ================================================ using Llvm.NET.Native; namespace Llvm.NET.DebugInfo { public class DIObjCProperty : DINode { internal DIObjCProperty( LLVMMetadataRef handle ) : base( handle ) { } } } ================================================ FILE: Zelig/Zelig/CompileTime/Llvm.NET/Llvm.NET/DebugInfo/DIScope.cs ================================================ using Llvm.NET.Native; namespace Llvm.NET.DebugInfo { /// Base class for all Debug info scopes public class DIScope : DINode { internal DIScope( LLVMMetadataRef handle ) : base( handle ) { } public DIFile File { get { var handle = NativeMethods.DIScopeGetFile( MetadataHandle ); if( handle == LLVMMetadataRef.Zero ) return null; return MDNode.FromHandle( handle ); } } } } ================================================ FILE: Zelig/Zelig/CompileTime/Llvm.NET/Llvm.NET/DebugInfo/DISubProgram.cs ================================================ using Llvm.NET.Native; using Llvm.NET.Values; namespace Llvm.NET.DebugInfo { /// see [System.Diagnostics.CodeAnalysis.SuppressMessage( "Microsoft.Naming", "CA1702:CompoundWordsShouldBeCasedCorrectly", MessageId = "SubProgram" )] public class DISubProgram : DILocalScope { internal DISubProgram( LLVMMetadataRef handle ) : base( handle ) { } [System.Diagnostics.CodeAnalysis.SuppressMessage( "Microsoft.Design", "CA1011:ConsiderPassingBaseTypesAsParameters", Justification = "Specific type required by interop call" )] public bool Describes( Function function ) => NativeMethods.SubProgramDescribes( MetadataHandle, function.VerifyArgNotNull( nameof( function )).ValueHandle ); } } ================================================ FILE: Zelig/Zelig/CompileTime/Llvm.NET/Llvm.NET/DebugInfo/DISubRange.cs ================================================ using Llvm.NET.Native; namespace Llvm.NET.DebugInfo { /// see public class DISubRange : DINode { internal DISubRange( LLVMMetadataRef handle ) : base( handle ) { } } } ================================================ FILE: Zelig/Zelig/CompileTime/Llvm.NET/Llvm.NET/DebugInfo/DISubroutineType.cs ================================================ using Llvm.NET.Native; namespace Llvm.NET.DebugInfo { /// see public class DISubroutineType : DICompositeType { internal DISubroutineType( LLVMMetadataRef handle ) : base( handle ) { } } } ================================================ FILE: Zelig/Zelig/CompileTime/Llvm.NET/Llvm.NET/DebugInfo/DITemplateParameter.cs ================================================ using Llvm.NET.Native; namespace Llvm.NET.DebugInfo { public class DITemplateParameter : DINode { internal DITemplateParameter( LLVMMetadataRef handle ) : base( handle ) { } } } ================================================ FILE: Zelig/Zelig/CompileTime/Llvm.NET/Llvm.NET/DebugInfo/DITemplateTypeParameter.cs ================================================ using Llvm.NET.Native; namespace Llvm.NET.DebugInfo { public class DITemplateTypeParameter : DITemplateParameter { internal DITemplateTypeParameter( LLVMMetadataRef handle ) : base( handle ) { } } } ================================================ FILE: Zelig/Zelig/CompileTime/Llvm.NET/Llvm.NET/DebugInfo/DITemplateValueParameter.cs ================================================ using Llvm.NET.Native; namespace Llvm.NET.DebugInfo { public class DITemplateValueParameter : DITemplateParameter { internal DITemplateValueParameter( LLVMMetadataRef handle ) : base( handle ) { } } } ================================================ FILE: Zelig/Zelig/CompileTime/Llvm.NET/Llvm.NET/DebugInfo/DIType.cs ================================================ using System; using System.Runtime.InteropServices; using Llvm.NET.Native; namespace Llvm.NET.DebugInfo { /// Base class for Debug info types public class DIType : DIScope { internal DIType( LLVMMetadataRef handle ) : base( handle ) { } public DebugInfoFlags DebugInfoFlags { get { if( MetadataHandle.Pointer == IntPtr.Zero ) return 0; return ( DebugInfoFlags )NativeMethods.DITypeGetFlags( MetadataHandle ); } } public DIScope Scope { get { var handle = NativeMethods.DITypeGetScope( MetadataHandle ); if( handle.Pointer == IntPtr.Zero ) return null; return FromHandle< DIScope >( handle ); } } public UInt32 Line => NativeMethods.DITypeGetLine( MetadataHandle ); public UInt64 BitSize => NativeMethods.DITypeGetSizeInBits( MetadataHandle ); public UInt64 BitAlignment => NativeMethods.DITypeGetAlignInBits( MetadataHandle ); public UInt64 BitOffset => NativeMethods.DITypeGetOffsetInBits( MetadataHandle ); public bool IsPrivate => ( DebugInfoFlags & DebugInfoFlags.AccessibilityMask ) == DebugInfoFlags.Private; public bool IsProtected => ( DebugInfoFlags & DebugInfoFlags.AccessibilityMask ) == DebugInfoFlags.Protected; public bool IsPublic => ( DebugInfoFlags & DebugInfoFlags.AccessibilityMask ) == DebugInfoFlags.Public; public bool IsForwardDeclaration => DebugInfoFlags.HasFlag( DebugInfoFlags.ForwardDeclaration ); public bool IsAppleBlockExtension => DebugInfoFlags.HasFlag( DebugInfoFlags.AppleBlock ); public bool IsBlockByRefStruct => DebugInfoFlags.HasFlag( DebugInfoFlags.BlockByrefStruct ); public bool IsVirtual => DebugInfoFlags.HasFlag( DebugInfoFlags.Virtual ); public bool IsArtificial => DebugInfoFlags.HasFlag( DebugInfoFlags.Artificial ); public bool IsObjectPointer => DebugInfoFlags.HasFlag( DebugInfoFlags.ObjectPointer ); public bool IsObjClassComplete => DebugInfoFlags.HasFlag( DebugInfoFlags.ObjcClassComplete ); public bool IsVector => DebugInfoFlags.HasFlag( DebugInfoFlags.Vector ); public bool IsStaticMember => DebugInfoFlags.HasFlag( DebugInfoFlags.StaticMember ); public bool IsLvalueReference => DebugInfoFlags.HasFlag( DebugInfoFlags.LValueReference ); public bool IsRvalueReference => DebugInfoFlags.HasFlag( DebugInfoFlags.RValueReference ); public string Name => Marshal.PtrToStringAnsi( NativeMethods.DITypeGetName( MetadataHandle ) ); } } ================================================ FILE: Zelig/Zelig/CompileTime/Llvm.NET/Llvm.NET/DebugInfo/DITypeArray.cs ================================================ using Llvm.NET.Native; namespace Llvm.NET.DebugInfo { /// Array of see nodes for use with see methods public class DITypeArray { internal DITypeArray( LLVMMetadataRef handle ) { MetadataHandle = handle; } internal LLVMMetadataRef MetadataHandle { get; } } } ================================================ FILE: Zelig/Zelig/CompileTime/Llvm.NET/Llvm.NET/DebugInfo/DIVariable.cs ================================================ using Llvm.NET.Native; namespace Llvm.NET.DebugInfo { public class DIVariable : DINode { internal DIVariable( LLVMMetadataRef handle ) : base( handle ) { } // TODO: UInt32 Line => NativeMethods.DIVariableGetLine( MetadataHandle ); public DIScope Scope => Operands[ 0 ]?.Metadata as DIScope; public string Name => ( Operands[ 1 ]?.Metadata as MDString )?.ToString( ) ?? string.Empty; public DIFile File => Operands[ 2 ]?.Metadata as DIFile; [System.Diagnostics.CodeAnalysis.SuppressMessage( "Microsoft.Naming", "CA1721:PropertyNamesShouldNotMatchGetMethods" )] public DIType Type => Operands[ 3 ]?.Metadata as DIType; } } ================================================ FILE: Zelig/Zelig/CompileTime/Llvm.NET/Llvm.NET/DebugInfo/DebugArrayType.cs ================================================ using System; using Llvm.NET.Types; namespace Llvm.NET.DebugInfo { /// Provides debug information binding between an and a public class DebugArrayType : DebugType , IArrayType { /// Creates a new /// Underlying LLVM array type to bind debug info to /// Array element type with debug information /// module to use for creating debug information /// Number of elements in the array /// Lower bound of the array [default = 0] public DebugArrayType( IArrayType llvmType , IDebugType elementType , NativeModule module , uint count , uint lowerBound = 0 ) : base( llvmType , CreateDebugInfoForArray( llvmType, elementType, module, count, lowerBound ) ) { if( llvmType == null ) throw new ArgumentNullException( nameof( llvmType ) ); if( elementType == null ) throw new ArgumentNullException( nameof( elementType ) ); if( llvmType.ElementType.TypeHandle != elementType.TypeHandle ) throw new ArgumentException( "elementType doesn't match array element type" ); DebugElementType = elementType; } /// Constructs a new /// Type of elements in the array /// to use for the context of the debug information /// Number of elements in the array /// value for the array indices [Default: 0] public DebugArrayType( IDebugType elementType, NativeModule module, uint count, uint lowerBound = 0 ) : this( elementType.VerifyArgNotNull( nameof( elementType ) ).CreateArrayType( count ) , elementType , module , count , lowerBound ) { } /// Constructs a new /// Native LLVM type for the elements /// to use for the context of the debug information /// Debug type of the array elements /// Number of elements in the array /// value for the array indices [Default: 0] public DebugArrayType( IArrayType llvmType, NativeModule module, DIType elementType, uint count, uint lowerBound = 0 ) : this( DebugType.Create( llvmType.VerifyArgNotNull( nameof( llvmType ) ).ElementType, elementType ), module, count, lowerBound ) { } /// Full type for the elements public IDebugType DebugElementType { get; } /// public ITypeRef ElementType => DebugElementType; /// public uint Length => NativeType.Length; /// Lower bound of the array, usually but not always zero public uint LowerBound { get; } /// Resolves a temporary metadata node for the array if full size information wasn't available at creation time /// Type layout information /// Debug information builder for creating the new debug information public void ResolveTemporary( DataLayout layout, DebugInfoBuilder diBuilder ) { if( layout == null ) throw new ArgumentNullException( nameof( layout ) ); if( diBuilder == null ) throw new ArgumentNullException( nameof( diBuilder ) ); if( DIType.IsTemporary && !DIType.IsResolved ) { DIType = diBuilder.CreateArrayType( layout.BitSizeOf( NativeType ) , layout.AbiBitAlignmentOf( NativeType ) , DebugElementType.DIType , diBuilder.CreateSubRange( LowerBound, NativeType.Length ) ); } } private static DICompositeType CreateDebugInfoForArray( IArrayType llvmType , IDebugType elementType , NativeModule module , uint count , uint lowerBound ) { if( llvmType.IsSized ) { return module.DIBuilder.CreateArrayType( module.Layout.BitSizeOf( llvmType ) , module.Layout.AbiBitAlignmentOf( llvmType ) , elementType.DIType , module.DIBuilder.CreateSubRange( lowerBound, count ) ); } else { return module.DIBuilder.CreateReplaceableCompositeType( Tag.ArrayType, string.Empty, module.DICompileUnit, null, 0 ); } } } } ================================================ FILE: Zelig/Zelig/CompileTime/Llvm.NET/Llvm.NET/DebugInfo/DebugBasicType.cs ================================================ using System; using Llvm.NET.Types; namespace Llvm.NET.DebugInfo { /// Debug information binding between an LLVM native and a /// /// This class provides a binding between an LLVM type and a corresponding . /// In LLVM all primitive types are unnamed and interned. That is, any use of an i8 is always the same /// type. However, at the source language level it is common to have named primitive types that map /// to the same underlying LLVM. For example, in C and C++ char maps to i8 but so does unsigned char /// (LLVM integral types don't have signed vs unsigned). This class is designed to handle this sort /// of one to many mapping of the lower level LLVM types to source level debugging types. Each /// instance of this class represents a source level basic type and the corresponding representation /// for LLVM. /// public class DebugBasicType : DebugType { /// Create a debug type for a basic type /// Type to wrap debug information for /// Module to use when constructing the debug information /// Source language name of the type /// Encoding for the type public DebugBasicType( ITypeRef llvmType, NativeModule module, string name, DiTypeKind encoding ) : base( ValidateType( llvmType ) , module.VerifyArgNotNull( nameof(module) ) .DIBuilder .CreateBasicType( name , module.VerifyArgNotNull( nameof( module ) ).Layout.BitSizeOf( llvmType ) , module.VerifyArgNotNull( nameof( module ) ).Layout.AbiBitAlignmentOf( llvmType ) , encoding ) ) { } // Fluent style argument validator to verify arguments before passing to base class. // Only primitive types are supported. private static ITypeRef ValidateType( ITypeRef typeRef ) { if( typeRef == null ) throw new ArgumentNullException( nameof( typeRef ) ); switch( typeRef.Kind ) { case TypeKind.Label: case TypeKind.Function: case TypeKind.Struct: case TypeKind.Array: case TypeKind.Pointer: case TypeKind.Vector: case TypeKind.Metadata: throw new ArgumentException( "Expected a primitive type", nameof( typeRef ) ); default: return typeRef; } } } } ================================================ FILE: Zelig/Zelig/CompileTime/Llvm.NET/Llvm.NET/DebugInfo/DebugFunctionType.cs ================================================ using Llvm.NET.Types; using System.Collections.Generic; using System.Linq; namespace Llvm.NET.DebugInfo { /// This class provides debug information binding for an /// and a /// /// /// Function signatures are unnamed interned types in LLVM. While there is usually a one /// to one mapping between an LLVM function signature type and the source language debug /// signature type that isn't always true. In particular, when passing data by value. In /// cases where the address of a by value structure is needed a common pattern is to use /// a pointer to the structure in the signature, then perform an Alloca + memcpy. The /// actual approach taken depends on the calling conventions of the target. In these cases /// you get an LLVM signature that doesn't match the source and could actually match another /// source function where a pointer to the structure is actually used in the source. /// For example, the following two C language functions might use the same LLVM signature: /// void foo(struct bar) /// void foo2(struct bar*) /// Implementing both of those might be done in LLVM with a single signature: /// void (%struct.bar*) /// This class is designed to provide mapping between the debug signature type /// and the underlying LLVM type /// It is important to keep in mind that signatures are only concerned /// with types. That is, they do not include names of parameters. Parameter information is /// provided by /// and /// public class DebugFunctionType : DebugType , IFunctionType { /// Constructs a new /// Native LLVM function signature /// to use when construction debug information /// for this signature /// Return type for the function /// Potentially empty set of argument types for the signature public DebugFunctionType( IFunctionType llvmType , NativeModule module , DebugInfoFlags debugFlags , DebugType retType , params DebugType[ ] argTypes ) : base( llvmType.VerifyArgNotNull( nameof( llvmType ) ) , module.VerifyArgNotNull( nameof( module ) ) .DIBuilder .CreateSubroutineType( debugFlags , retType.VerifyArgNotNull( nameof( retType ) ).DIType , argTypes.Select( t=>t.DIType ) ) ) { } /// public bool IsVarArg => NativeType.IsVarArg; /// public ITypeRef ReturnType => NativeType.ReturnType; /// public IReadOnlyList ParameterTypes => NativeType.ParameterTypes; internal DebugFunctionType( IFunctionType rawType, DISubroutineType sub ) : base( rawType, sub ) { } } } ================================================ FILE: Zelig/Zelig/CompileTime/Llvm.NET/Llvm.NET/DebugInfo/DebugInfoBuilder.cs ================================================ using System; using System.Collections.Generic; using System.Linq; using Llvm.NET.Values; using Llvm.NET.Instructions; using System.IO; using System.Text; using Llvm.NET.Native; namespace Llvm.NET.DebugInfo { /// DebugInfoBuilder is a factory class for creating DebugInformation for an LLVM /// /// /// Many Debug information metadata nodes are created with unresolved references to additional /// metadata. To ensure such metadata is resolved applications should call the /// method to resolve and finalize the metadata. After this point only fully resolved nodes may /// be added to ensure that the data remains valid. /// public sealed class DebugInfoBuilder : IDisposable { /// Creates a new /// for the compilation unit /// Full path to the source file of this compilation unit /// Name of the application processing the compilation unit /// Flag to indicate if the code in this compilation unit is optimized /// Additional tool specific flags /// Runtime version /// public DICompileUnit CreateCompileUnit( SourceLanguage language , string sourceFilePath , string producer , bool optimized , string compilationFlags , uint runtimeVersion ) { return CreateCompileUnit( language , Path.GetFileName( sourceFilePath ) , Path.GetDirectoryName( sourceFilePath ) ?? Environment.CurrentDirectory , producer , optimized , compilationFlags , runtimeVersion ); } /// Creates a new /// for the compilation unit /// Name of the source file of this compilation unit (without any path) /// Path of the directory containing the file /// Name of the application processing the compilation unit /// Flag to indicate if the code in this compilation unit is optimized /// Additional tool specific flags /// Runtime version /// [System.Diagnostics.CodeAnalysis.SuppressMessage( "Microsoft.Naming", "CA2204:Literals should be spelled correctly", MessageId = "DICompileUnit" )] public DICompileUnit CreateCompileUnit( SourceLanguage language , string fileName , string fileDirectory , string producer , bool optimized , string compilationFlags , uint runtimeVersion ) { if( OwningModule.DICompileUnit != null ) throw new InvalidOperationException( "LLVM only allows one DICompileUnit per module" ); var handle = NativeMethods.DIBuilderCreateCompileUnit( BuilderHandle , ( uint )language , fileName , fileDirectory , producer , optimized ? 1 : 0 , compilationFlags , runtimeVersion ); var retVal = MDNode.FromHandle( handle ); OwningModule.DICompileUnit = retVal; return retVal; } /// Creates a /// Containing scope for the namespace or null if the namespace is a global one /// Name of the namespace /// Source file containing the declaration (may be null if more than one or not known) /// Line number of the namespace declaration /// [System.Diagnostics.CodeAnalysis.SuppressMessage( "Microsoft.Design", "CA1011:ConsiderPassingBaseTypesAsParameters", Justification = "Specific type required by interop call" )] public DINamespace CreateNamespace( DIScope scope, string name, DIFile file, uint line ) { if( string.IsNullOrWhiteSpace( name ) ) throw new ArgumentException( "name cannot be null or empty", nameof( name ) ); var handle = NativeMethods.DIBuilderCreateNamespace( BuilderHandle , scope?.MetadataHandle ?? LLVMMetadataRef.Zero , name , file?.MetadataHandle ?? LLVMMetadataRef.Zero , line ); return MDNode.FromHandle( handle ); } /// Creates a /// Path of the file (may be or empty) /// /// or if /// is empty, or all whitespace /// public DIFile CreateFile( string path ) { if( string.IsNullOrWhiteSpace( path ) ) return null; return CreateFile( Path.GetFileName( path ), Path.GetDirectoryName( path ) ); } /// Creates a /// Name of the file (may be or empty) /// Path of the directory containing the file (may be or empty) /// /// or if /// is empty, or all whitespace /// public DIFile CreateFile( string fileName, string directory ) { if( string.IsNullOrWhiteSpace( fileName ) ) return null; var handle = NativeMethods.DIBuilderCreateFile( BuilderHandle, fileName, directory ?? string.Empty ); return MDNode.FromHandle( handle ); } /// Creates a new /// for the block /// containing the block /// Starting line number for the block /// Starting column for the block /// /// created from the parameters /// [System.Diagnostics.CodeAnalysis.SuppressMessage( "Microsoft.Design", "CA1011:ConsiderPassingBaseTypesAsParameters", Justification = "Specific type required by interop call" )] public DILexicalBlock CreateLexicalBlock( DIScope scope, DIFile file, uint line, uint column ) { if( scope == null ) throw new ArgumentNullException( nameof( scope ) ); var handle = NativeMethods.DIBuilderCreateLexicalBlock( BuilderHandle , scope.MetadataHandle , file?.MetadataHandle ?? LLVMMetadataRef.Zero , line , column ); return MDNode.FromHandle( handle ); } /// Creates a /// for the block /// /// Discriminator to disambiguate lexical blocks with the same file info /// /// constructed from the parameters /// [System.Diagnostics.CodeAnalysis.SuppressMessage( "Microsoft.Design", "CA1011:ConsiderPassingBaseTypesAsParameters", Justification = "Specific type required by interop call" )] public DILexicalBlockFile CreateLexicalBlockFile( DIScope scope, DIFile file, uint discriminator ) { if( scope == null ) throw new ArgumentNullException( nameof( scope ) ); if( file == null ) throw new ArgumentNullException( nameof( file ) ); var handle = NativeMethods.DIBuilderCreateLexicalBlockFile( BuilderHandle, scope.MetadataHandle, file.MetadataHandle, discriminator ); return MDNode.FromHandle( handle ); } /// Create a with debug information /// for the function /// Name of the function as it appears in the source language /// Linkage (mangled) name of the function /// containing the function /// starting line of the function definition /// for the function's signature type /// Flag to indicate if this function is local to the compilation unit or available externally /// Flag to indicate if this is a definition or a declaration only /// starting line of the first scope of the function's body /// for this function /// Flag to indicate if this function is optimized /// Underlying LLVM to attach debug info to /// Template parameter [default = null] /// Template declarations [default = null] [System.Diagnostics.CodeAnalysis.SuppressMessage( "Microsoft.Design", "CA1011:ConsiderPassingBaseTypesAsParameters", Justification = "Specific type required by interop call" )] public DISubProgram CreateFunction( DIScope scope , string name , string mangledName , DIFile file , uint line , DISubroutineType signatureType , bool isLocalToUnit , bool isDefinition , uint scopeLine , DebugInfoFlags debugFlags , bool isOptimized , Function function , MDNode typeParameter = null , MDNode declaration = null ) { if( scope == null ) throw new ArgumentNullException( nameof( scope ) ); if( string.IsNullOrWhiteSpace( name ) ) name = string.Empty; if( string.IsNullOrWhiteSpace( mangledName ) ) mangledName = string.Empty; if( signatureType == null ) throw new ArgumentNullException( nameof( signatureType ) ); if( function == null ) throw new ArgumentNullException( nameof( function ) ); var handle = NativeMethods.DIBuilderCreateFunction( BuilderHandle , scope.MetadataHandle , name , mangledName , file?.MetadataHandle ?? LLVMMetadataRef.Zero , line , signatureType.MetadataHandle , isLocalToUnit ? 1 : 0 , isDefinition ? 1 : 0 , scopeLine , ( uint )debugFlags , isOptimized ? 1 : 0 , typeParameter?.MetadataHandle ?? LLVMMetadataRef.Zero , declaration?.MetadataHandle ?? LLVMMetadataRef.Zero ); return MDNode.FromHandle( handle ); } /// Creates a new forward declaration to a function /// for the declaration /// Name of the function as it appears in source /// mangled name of the function (for linker) /// Source file location for the function /// starting line of the declaration /// Signature for the function /// Flag to indicate if this declaration is local to the compilation unit /// Flag to indicate if this is a definition /// Line of the first scope block /// for the function /// Flag to indicate if the function is optimized /// [System.Diagnostics.CodeAnalysis.SuppressMessage( "Microsoft.Design", "CA1011:ConsiderPassingBaseTypesAsParameters", Justification = "Specific type required by interop call" )] public DISubProgram ForwardDeclareFunction( DIScope scope , string name , string mangledName , DIFile file , uint line , DISubroutineType subroutineType , bool isLocalToUnit , bool isDefinition , uint scopeLine , DebugInfoFlags debugFlags , bool isOptimized ) { if( scope == null ) throw new ArgumentNullException( nameof( scope ) ); if( subroutineType == null ) throw new ArgumentNullException( nameof( subroutineType ) ); if( string.IsNullOrWhiteSpace( name ) ) name = string.Empty; if( string.IsNullOrWhiteSpace( mangledName ) ) mangledName = string.Empty; var handle = NativeMethods.DIBuilderCreateTempFunctionFwdDecl( BuilderHandle , scope.MetadataHandle , name , mangledName , file?.MetadataHandle ?? LLVMMetadataRef.Zero , line , subroutineType.MetadataHandle , isLocalToUnit ? 1 : 0 , isDefinition ? 1 : 0 , scopeLine , ( uint )debugFlags , isOptimized ? 1 : 0 , LLVMMetadataRef.Zero , LLVMMetadataRef.Zero ); return MDNode.FromHandle( handle ); } [System.Diagnostics.CodeAnalysis.SuppressMessage( "Microsoft.Design", "CA1011:ConsiderPassingBaseTypesAsParameters" )] public DILocalVariable CreateLocalVariable( DIScope scope , string name , DIFile file , uint line , DIType type , bool alwaysPreserve , DebugInfoFlags debugFlags ) { if( scope == null ) throw new ArgumentNullException( nameof( scope ) ); if( type == null ) throw new ArgumentNullException( nameof( type ) ); var handle = NativeMethods.DIBuilderCreateAutoVariable( BuilderHandle , scope.MetadataHandle , name , file?.MetadataHandle ?? LLVMMetadataRef.Zero , line , type.MetadataHandle , alwaysPreserve ? 1 : 0 , ( uint )debugFlags ); return MDNode.FromHandle( handle ); } /// Creates an argument for a function as a /// Scope for the argument /// Name of the argument /// containing the function this argument is declared in /// Line number fort his argument /// Debug type for this argument /// Flag to indicate if this argument is always preserved for debug view even if optimization would remove it /// for this argument /// One based argument index on the method (e.g the first argument is 1 not 0 ) /// representing the function argument [System.Diagnostics.CodeAnalysis.SuppressMessage( "Microsoft.Design", "CA1011:ConsiderPassingBaseTypesAsParameters" )] public DILocalVariable CreateArgument( DIScope scope , string name , DIFile file , uint line , DIType type , bool alwaysPreserve , DebugInfoFlags debugFlags , ushort argNo ) { if( scope == null ) throw new ArgumentNullException( nameof( scope ) ); if( type == null ) throw new ArgumentNullException( nameof( type ) ); var handle = NativeMethods.DIBuilderCreateParameterVariable( BuilderHandle , scope.MetadataHandle , name , argNo , file?.MetadataHandle ?? LLVMMetadataRef.Zero , line , type.MetadataHandle , alwaysPreserve ? 1 : 0 , ( uint )debugFlags ); return MDNode.FromHandle( handle ); } /// Construct debug information for a basic type (a.k.a. primitive type) /// Name of the type /// Bit size for the type /// Bit alignment for the type /// encoding for the type /// public DIBasicType CreateBasicType( string name, ulong bitSize, ulong bitAlign, DiTypeKind encoding ) { var handle = NativeMethods.DIBuilderCreateBasicType( BuilderHandle, name, bitSize, bitAlign, ( uint )encoding ); return MDNode.FromHandle( handle ); } [System.Diagnostics.CodeAnalysis.SuppressMessage( "Microsoft.Design", "CA1011:ConsiderPassingBaseTypesAsParameters", Justification = "Specific type required by interop call" )] public DIDerivedType CreatePointerType( DIType pointeeType, string name, ulong bitSize, ulong bitAlign ) { var handle = NativeMethods.DIBuilderCreatePointerType( BuilderHandle , pointeeType?.MetadataHandle ?? LLVMMetadataRef.Zero // null == void , bitSize , bitAlign , name ?? string.Empty ); return MDNode.FromHandle( handle ); } [System.Diagnostics.CodeAnalysis.SuppressMessage( "Microsoft.Design", "CA1011:ConsiderPassingBaseTypesAsParameters", Justification = "Specific type required by interop call" )] public DIDerivedType CreateQualifiedType( DIType baseType, QualifiedTypeTag tag ) { if( baseType == null ) throw new ArgumentNullException( nameof( baseType ) ); var handle = NativeMethods.DIBuilderCreateQualifiedType( BuilderHandle, ( uint )tag, baseType.MetadataHandle ); return MDNode.FromHandle( handle ); } public DITypeArray CreateTypeArray( params DIType[ ] types ) => CreateTypeArray( ( IEnumerable )types ); public DITypeArray CreateTypeArray( IEnumerable types ) { var handles = types.Select( t => t.MetadataHandle ).ToArray( ); var count = handles.LongLength; if( count == 0 ) handles = new[ ] { default( LLVMMetadataRef ) }; var handle = NativeMethods.DIBuilderGetOrCreateTypeArray( BuilderHandle, out handles[ 0 ], ( ulong )count ); return new DITypeArray( handle ); } [System.Diagnostics.CodeAnalysis.SuppressMessage( "Microsoft.Design", "CA1011:ConsiderPassingBaseTypesAsParameters", Justification = "Specific type required by interop call" )] public DISubroutineType CreateSubroutineType( DebugInfoFlags debugFlags, DITypeArray types ) { if( types == null ) throw new ArgumentNullException( nameof( types ) ); var handle = NativeMethods.DIBuilderCreateSubroutineType( BuilderHandle , types.MetadataHandle , ( uint )debugFlags ); return MDNode.FromHandle( handle ); } public DISubroutineType CreateSubroutineType( DebugInfoFlags debugFlags ) { var typeArray = GetOrCreateTypeArray( null ); return CreateSubroutineType( debugFlags, typeArray ); } public DISubroutineType CreateSubroutineType( DebugInfoFlags debugFlags, DIType returnType, IEnumerable types ) { var typeArray = GetOrCreateTypeArray( ScalarEnumerable.Combine( returnType, types ) ); return CreateSubroutineType( debugFlags, typeArray ); } [System.Diagnostics.CodeAnalysis.SuppressMessage( "Microsoft.Design", "CA1011:ConsiderPassingBaseTypesAsParameters", Justification = "Specific type required by interop call" )] public DICompositeType CreateStructType( DIScope scope , string name , DIFile file , uint line , ulong bitSize , ulong bitAlign , uint flags , DIType derivedFrom , DINodeArray elements ) { if( scope == null ) throw new ArgumentNullException( nameof( scope ) ); if( elements == null ) throw new ArgumentNullException( nameof( elements ) ); var handle = NativeMethods.DIBuilderCreateStructType( BuilderHandle , scope.MetadataHandle , name , file?.MetadataHandle ?? LLVMMetadataRef.Zero , line , bitSize , bitAlign , flags , derivedFrom?.MetadataHandle ?? LLVMMetadataRef.Zero , elements.Tuple.MetadataHandle ); return MDNode.FromHandle( handle ); } public DICompositeType CreateStructType( DIScope scope , string name , DIFile file , uint line , ulong bitSize , ulong bitAlign , DebugInfoFlags debugFlags , DIType derivedFrom , params DINode[ ] elements ) { return CreateStructType( scope, name, file, line, bitSize, bitAlign, ( uint )debugFlags, derivedFrom, GetOrCreateArray( elements ) ); } public DICompositeType CreateStructType( DIScope scope , string name , DIFile file , uint line , ulong bitSize , ulong bitAlign , DebugInfoFlags debugFlags , DIType derivedFrom , IEnumerable elements ) { return CreateStructType( scope, name, file, line, bitSize, bitAlign, ( uint )debugFlags, derivedFrom, GetOrCreateArray( elements ) ); } [System.Diagnostics.CodeAnalysis.SuppressMessage( "Microsoft.Design", "CA1011:ConsiderPassingBaseTypesAsParameters", Justification = "Specific type required by interop call" )] public DIDerivedType CreateMemberType( DIScope scope , string name , DIFile file , uint line , ulong bitSize , ulong bitAlign , ulong bitOffset , DebugInfoFlags debugFlags , DIType type ) { if( scope == null ) throw new ArgumentNullException( nameof( scope ) ); if( type == null ) throw new ArgumentNullException( nameof( type ) ); var handle = NativeMethods.DIBuilderCreateMemberType( BuilderHandle , scope.MetadataHandle , name , file?.MetadataHandle ?? LLVMMetadataRef.Zero , line , bitSize , bitAlign , bitOffset , ( uint )debugFlags , type.MetadataHandle ); return MDNode.FromHandle( handle ); } [System.Diagnostics.CodeAnalysis.SuppressMessage( "Microsoft.Design", "CA1011:ConsiderPassingBaseTypesAsParameters", Justification = "Specific type required by interop call" )] public DICompositeType CreateArrayType( ulong bitSize, ulong bitAlign, DIType elementType, DINodeArray subscripts ) { if( elementType == null ) throw new ArgumentNullException( nameof( elementType ) ); if( subscripts == null ) throw new ArgumentNullException( nameof( subscripts ) ); var handle = NativeMethods.DIBuilderCreateArrayType( BuilderHandle, bitSize, bitAlign, elementType.MetadataHandle, subscripts.Tuple.MetadataHandle ); return MDNode.FromHandle( handle ); } public DICompositeType CreateArrayType( ulong bitSize, ulong bitAlign, DIType elementType, params DINode[ ] subscripts ) { return CreateArrayType( bitSize, bitAlign, elementType, GetOrCreateArray( subscripts ) ); } [System.Diagnostics.CodeAnalysis.SuppressMessage( "Microsoft.Design", "CA1011:ConsiderPassingBaseTypesAsParameters", Justification = "Specific type required by interop call" )] public DIDerivedType CreateTypedef( DIType type, string name, DIFile file, uint line, DINode context ) { var handle = NativeMethods.DIBuilderCreateTypedef( BuilderHandle , type?.MetadataHandle ?? LLVMMetadataRef.Zero , name , file?.MetadataHandle ?? LLVMMetadataRef.Zero , line , context?.MetadataHandle ?? LLVMMetadataRef.Zero ); return MDNode.FromHandle( handle ); } public DISubRange CreateSubRange( long lo, long count ) { var handle = NativeMethods.DIBuilderGetOrCreateSubrange( BuilderHandle, lo, count ); return MDNode.FromHandle( handle ); } public DINodeArray GetOrCreateArray( IEnumerable elements ) { var buf = elements.Select( d => d?.MetadataHandle ?? LLVMMetadataRef.Zero ).ToArray( ); var actualLen = buf.LongLength; // for the out parameter trick to work - need to have a valid array with at least one element if( buf.LongLength == 0 ) buf = new LLVMMetadataRef[ 1 ]; var handle = NativeMethods.DIBuilderGetOrCreateArray( BuilderHandle, out buf[ 0 ], ( ulong )actualLen ); return new DINodeArray( LlvmMetadata.FromHandle( OwningModule.Context, handle ) ); } public DITypeArray GetOrCreateTypeArray( params DIType[ ] types ) => GetOrCreateTypeArray( ( IEnumerable )types ); public DITypeArray GetOrCreateTypeArray( IEnumerable types ) { var buf = types.Select( t => t?.MetadataHandle ?? LLVMMetadataRef.Zero ).ToArray( ); var handle = NativeMethods.DIBuilderGetOrCreateTypeArray( BuilderHandle, out buf[ 0 ], ( ulong )buf.LongLength ); return new DITypeArray( handle ); } public DIEnumerator CreateEnumeratorValue( string name, long value ) { var handle = NativeMethods.DIBuilderCreateEnumeratorValue( BuilderHandle, name, value ); return MDNode.FromHandle( handle ); } [System.Diagnostics.CodeAnalysis.SuppressMessage( "Microsoft.Design", "CA1011:ConsiderPassingBaseTypesAsParameters", Justification = "Specific type required by interop call" )] public DICompositeType CreateEnumerationType( DIScope scope , string name , DIFile file , uint lineNumber , ulong sizeInBits , ulong alignInBits , IEnumerable elements , DIType underlyingType , string uniqueId = "" ) { if( scope == null ) throw new ArgumentNullException( nameof( scope ) ); if( underlyingType == null ) throw new ArgumentNullException( nameof( underlyingType ) ); var elementHandles = elements.Select( e => e.MetadataHandle ).ToArray( ); var elementArray = NativeMethods.DIBuilderGetOrCreateArray( BuilderHandle, out elementHandles[ 0 ], ( ulong )elementHandles.LongLength ); var handle = NativeMethods.DIBuilderCreateEnumerationType( BuilderHandle , scope.MetadataHandle , name , file?.MetadataHandle ?? LLVMMetadataRef.Zero , lineNumber , sizeInBits , alignInBits , elementArray , underlyingType.MetadataHandle , uniqueId ); return MDNode.FromHandle( handle ); } [System.Diagnostics.CodeAnalysis.SuppressMessage( "Microsoft.Design", "CA1011:ConsiderPassingBaseTypesAsParameters", Justification = "Specific type required by interop call" )] public DIGlobalVariable CreateGlobalVariable( DINode scope , string name , string linkageName , DIFile file , uint lineNo , DIType type , bool isLocalToUnit , Value value , DINode declaration = null ) { if( scope == null ) throw new ArgumentNullException( nameof( scope ) ); if( type == null ) throw new ArgumentNullException( nameof( type ) ); if( value == null ) throw new ArgumentNullException( nameof( value ) ); var handle = NativeMethods.DIBuilderCreateGlobalVariable( BuilderHandle , scope.MetadataHandle , name , linkageName , file?.MetadataHandle ?? LLVMMetadataRef.Zero , lineNo , type.MetadataHandle , isLocalToUnit , value.ValueHandle , declaration?.MetadataHandle ?? LLVMMetadataRef.Zero ); return MDNode.FromHandle( handle ); } public void Finish( ) { if( !IsFinished ) { var unresolvedTemps = from node in OwningModule.Context.Metadata.OfType( ) where node.IsTemporary && !node.IsResolved select node; if( unresolvedTemps.Any( ) ) { var bldr = new StringBuilder( "Temporaries must be resolved before finalizing debug information:\n" ); foreach( var node in unresolvedTemps ) bldr.AppendFormat( "\t{0}\n", node.ToString( ) ); throw new InvalidOperationException( bldr.ToString( ) ); } NativeMethods.DIBuilderFinalize( BuilderHandle ); IsFinished = true; } } public Instruction InsertDeclare( Value storage, DILocalVariable varInfo, DILocation location, Instruction insertBefore ) { return InsertDeclare( storage, varInfo, CreateExpression( ), location, insertBefore ); } [System.Diagnostics.CodeAnalysis.SuppressMessage( "Microsoft.Design", "CA1011:ConsiderPassingBaseTypesAsParameters", Justification = "Specific type required by interop call" )] public Instruction InsertDeclare( Value storage, DILocalVariable varInfo, DIExpression expression, DILocation location, Instruction insertBefore ) { if( storage == null ) throw new ArgumentNullException( nameof( storage ) ); if( varInfo == null ) throw new ArgumentNullException( nameof( varInfo ) ); if( expression == null ) throw new ArgumentNullException( nameof( expression ) ); if( location == null ) throw new ArgumentNullException( nameof( location ) ); if( insertBefore == null ) throw new ArgumentNullException( nameof( insertBefore ) ); var handle = NativeMethods.DIBuilderInsertDeclareBefore( BuilderHandle , storage.ValueHandle , varInfo.MetadataHandle , expression.MetadataHandle , location.MetadataHandle , insertBefore.ValueHandle ); return Value.FromHandle( handle ); } public CallInstruction InsertDeclare( Value storage, DILocalVariable varInfo, DILocation location, BasicBlock insertAtEnd ) { return InsertDeclare( storage, varInfo, CreateExpression( ), location, insertAtEnd ); } [System.Diagnostics.CodeAnalysis.SuppressMessage( "Microsoft.Design", "CA1011:ConsiderPassingBaseTypesAsParameters", Justification = "Specific type required by interop call" )] public CallInstruction InsertDeclare( Value storage, DILocalVariable varInfo, DIExpression espression, DILocation location, BasicBlock insertAtEnd ) { if( storage == null ) throw new ArgumentNullException( nameof( storage ) ); if( varInfo == null ) throw new ArgumentNullException( nameof( varInfo ) ); if( espression == null ) throw new ArgumentNullException( nameof( espression ) ); if( location == null ) throw new ArgumentNullException( nameof( location ) ); if( insertAtEnd == null ) throw new ArgumentNullException( nameof( insertAtEnd ) ); if( location.Scope.SubProgram != varInfo.Scope.SubProgram ) throw new ArgumentException( "Mismatched scopes for location and variable" ); var handle = NativeMethods.DIBuilderInsertDeclareAtEnd( BuilderHandle , storage.ValueHandle , varInfo.MetadataHandle , espression.MetadataHandle , location.MetadataHandle , insertAtEnd.BlockHandle ); return Value.FromHandle( handle ); } public CallInstruction InsertValue( Value value , UInt64 offset , DILocalVariable varInfo , DILocation location , Instruction insertBefore ) { return InsertValue( value, offset, varInfo, null, location, insertBefore ); } [System.Diagnostics.CodeAnalysis.SuppressMessage( "Microsoft.Design", "CA1011:ConsiderPassingBaseTypesAsParameters" )] public CallInstruction InsertValue( Value value , UInt64 offset , DILocalVariable varInfo , DIExpression expression , DILocation location , Instruction insertBefore ) { if( value == null ) throw new ArgumentNullException( nameof( value ) ); if( varInfo == null ) throw new ArgumentNullException( nameof( varInfo ) ); if( expression == null ) throw new ArgumentNullException( nameof( expression ) ); if( location == null ) throw new ArgumentNullException( nameof( location ) ); if( insertBefore == null ) throw new ArgumentNullException( nameof( insertBefore ) ); var handle = NativeMethods.DIBuilderInsertValueBefore( BuilderHandle , value.ValueHandle , offset , varInfo.MetadataHandle , expression?.MetadataHandle ?? CreateExpression( ).MetadataHandle , location.MetadataHandle , insertBefore.ValueHandle ); var retVal = Value.FromHandle( handle ); retVal.IsTailCall = true; return retVal; } public CallInstruction InsertValue( Value value , UInt64 offset , DILocalVariable varInfo , DILocation location , BasicBlock insertAtEnd ) { return InsertValue( value, offset, varInfo, null, location, insertAtEnd ); } [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1011:ConsiderPassingBaseTypesAsParameters")] public CallInstruction InsertValue(Value value , DILocalVariable varInfo , DIExpression expression , DILocation location , BasicBlock insertAtEnd ) { return InsertValue(value, 0, varInfo, expression, location, insertAtEnd); } [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1011:ConsiderPassingBaseTypesAsParameters")] public CallInstruction InsertValue( Value value , UInt64 offset , DILocalVariable varInfo , DIExpression expression , DILocation location , BasicBlock insertAtEnd ) { if( value == null ) throw new ArgumentNullException( nameof( value ) ); if( varInfo == null ) throw new ArgumentNullException( nameof( varInfo ) ); if( expression == null ) throw new ArgumentNullException( nameof( expression ) ); if( location == null ) throw new ArgumentNullException( nameof( location ) ); if( insertAtEnd == null ) throw new ArgumentNullException( nameof( insertAtEnd ) ); if( location.Scope != varInfo.Scope ) throw new ArgumentException( "mismatched scopes" ); if( !location.Describes(insertAtEnd.ContainingFunction ) ) throw new ArgumentException( "location does not describe the specified block's containing function" ); var handle = NativeMethods.DIBuilderInsertValueAtEnd( BuilderHandle , value.ValueHandle , offset , varInfo.MetadataHandle , expression?.MetadataHandle ?? CreateExpression( ).MetadataHandle , location.MetadataHandle , insertAtEnd.BlockHandle ); var retVal = Value.FromHandle( handle ); retVal.IsTailCall = true; return retVal; } public DIExpression CreateExpression( params ExpressionOp[ ] operations ) => CreateExpression( ( IEnumerable )operations ); public DIExpression CreateExpression( IEnumerable operations ) { var args = operations.Cast( ).ToArray( ); var actualCount = args.LongLength; if( args.Length == 0 ) args = new long[ 1 ]; var handle = NativeMethods.DIBuilderCreateExpression( BuilderHandle, out args[ 0 ], ( ulong )actualCount ); return new DIExpression( handle ); } [System.Diagnostics.CodeAnalysis.SuppressMessage( "Microsoft.Design", "CA1011:ConsiderPassingBaseTypesAsParameters", Justification = "Specific type required by interop call" )] public DICompositeType CreateReplaceableCompositeType( Tag tag , string name , DINode scope , DIFile file , uint line , uint lang = 0 , ulong sizeInBits = 0 , ulong alignBits = 0 , DebugInfoFlags flags = DebugInfoFlags.None ) { if( scope == null ) throw new ArgumentNullException( nameof( scope ) ); var handle = NativeMethods.DIBuilderCreateReplaceableCompositeType( BuilderHandle , ( uint )tag , name , scope.MetadataHandle , file?.MetadataHandle ?? LLVMMetadataRef.Zero , line , lang , sizeInBits , alignBits , ( uint )flags ); return MDNode.FromHandle( handle ); } public void Dispose( ) { if( BuilderHandle.Pointer != IntPtr.Zero ) { NativeMethods.DIBuilderDestroy( BuilderHandle ); BuilderHandle = default( LLVMDIBuilderRef ); } } internal DebugInfoBuilder( NativeModule owningModule ) : this( owningModule, true ) { } // keeping this private for now as there doesn't seem to be a good reason to support // allowUnresolved == false private DebugInfoBuilder( NativeModule owningModule, bool allowUnresolved ) { if( owningModule == null ) throw new ArgumentNullException( nameof( owningModule ) ); BuilderHandle = NativeMethods.NewDIBuilder( owningModule.ModuleHandle, allowUnresolved ); OwningModule = owningModule; } private readonly NativeModule OwningModule; private bool IsFinished; internal LLVMDIBuilderRef BuilderHandle { get; private set; } } } ================================================ FILE: Zelig/Zelig/CompileTime/Llvm.NET/Llvm.NET/DebugInfo/DebugMemberInfo.cs ================================================ using Llvm.NET.Types; namespace Llvm.NET.DebugInfo { /// DebugMemberLayout is used to define custom layout information for structure members /// /// Ordinarily layout information is handle automatically in /// /// however in cases where explicitly controlled (or "packed") layout is required, instances of DebugMemberLayout are /// used to provide the information necessary to generate a proper type and debug information. /// public class DebugMemberLayout { /// Constructs a new /// Size of the member in bits /// Alignment of the member in bits /// Offset of the member in bits public DebugMemberLayout( uint bitSize, uint bitAlignment, ulong bitOffset ) { BitSize = bitSize; BitAlignment = bitAlignment; BitOffset = bitOffset; } /// Bit size for the field public uint BitSize { get; } /// Bit alignment for the field public uint BitAlignment { get; } /// Bit offset for the field in it's containing type public ulong BitOffset { get; } } /// Describes a member/field of a type for creating debug information /// /// This class is used with /// to provide debug information for a type. /// In order to support explicit layout structures the members relating to layout are all . /// When they are null then modules target specific layout information is used to determine /// layout details. Setting the layout members of this class to non-null will override that behavior to define explicit /// layout details. /// public class DebugMemberInfo { /// LLVM structure element index this descriptor describes public uint Index { get; set; } /// Name of the field public string Name { get; set; } /// File the field is declared in public DIFile File { get; set; } /// Line the field is declared on public uint Line { get; set; } /// flags for the field declaration public DebugInfoFlags DebugInfoFlags { get; set; } /// Debug type information for this field public IDebugType DebugType { get; set; } /// Provides explicit layout information for this member /// If this is null then /// will default to using to determine the size using the module's target specific layout. /// /// If this property is provided (e.g. is not ) for any member of a type, then /// it must be set for all members. In other words explicit layout must be defined for all members /// or none. Furthermore, for types using explicit layout, the type containing this member must /// include the "packed" modifier. /// /// public DebugMemberLayout ExplicitLayout { get; set; } } } ================================================ FILE: Zelig/Zelig/CompileTime/Llvm.NET/Llvm.NET/DebugInfo/DebugPointerType.cs ================================================ using Llvm.NET.Types; namespace Llvm.NET.DebugInfo { /// Binding between a and an public class DebugPointerType : DebugType , IPointerType { /// Constructs a new /// Debug type of the pointee /// used for creating the pointer type and debug information /// Target address space for the pointer [Default: 0] /// Name of the type [Default: null] public DebugPointerType( IDebugType debugElementType, NativeModule module, uint addressSpace = 0, string name = null ) : this( debugElementType.VerifyArgNotNull( nameof( debugElementType ) ).NativeType , module , debugElementType.VerifyArgNotNull( nameof( debugElementType ) ).DIType , addressSpace , name ) { } /// Constructs a new /// Native type of the pointee /// used for creating the pointer type and debug information /// Debug type of the pointee /// Target address space for the pointer [Default: 0] /// Name of the type [Default: null] public DebugPointerType( ITypeRef llvmElementType, NativeModule module, DIType elementType, uint addressSpace = 0, string name = null ) : this( llvmElementType.VerifyArgNotNull( nameof( llvmElementType ) ).CreatePointerType( addressSpace ), module, elementType, name ) { } /// Constructs a new /// Native type of the pointer /// used for creating the pointer type and debug information /// Debug type of the pointee /// Name of the type [Default: null] public DebugPointerType( IPointerType llvmPtrType, NativeModule module, DIType elementType, string name = null ) : this( llvmPtrType , module.VerifyArgNotNull( nameof( module ) ) .DIBuilder .CreatePointerType( elementType , name , module.VerifyArgNotNull( nameof( module ) ).Layout.BitSizeOf( llvmPtrType ) , module.VerifyArgNotNull( nameof( module ) ).Layout.AbiBitAlignmentOf( llvmPtrType ) ) ) { } /// Constructs a new /// Native type of the pointer /// Debug type for the pointer /// /// This constructor is typically used when building typedefs to a basic type /// to provide namespace scoping for the typedef for languages that support /// such a concept. This is needed because basic types don't have any namespace /// information in the LLVM Debug information (they are implicitly in the global /// namespace) /// public DebugPointerType( IPointerType llvmPtrType, DIDerivedType debugType ) : base( llvmPtrType, debugType ) { } /// public uint AddressSpace => NativeType.AddressSpace; /// public ITypeRef ElementType => NativeType.ElementType; } } ================================================ FILE: Zelig/Zelig/CompileTime/Llvm.NET/Llvm.NET/DebugInfo/DebugStructType.cs ================================================ using Llvm.NET.Types; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Linq; namespace Llvm.NET.DebugInfo { public class DebugStructType : DebugType , IStructType { public DebugStructType( IStructType llvmType , NativeModule module , DIScope scope , string name , DIFile file , uint line , DebugInfoFlags debugFlags , DIType derivedFrom , IEnumerable elements ) : base( llvmType , module.VerifyArgNotNull( nameof( module ) ) .DIBuilder .CreateStructType( scope , name , file , line , module.VerifyArgNotNull( nameof( module ) ).Layout.BitSizeOf( llvmType ) , module.VerifyArgNotNull( nameof( module ) ).Layout.AbiBitAlignmentOf( llvmType ) , debugFlags , derivedFrom , elements ) ) { } public DebugStructType( IStructType llvmType , NativeModule module , DIScope scope , string name , DIFile file , uint line ) : base( llvmType , module.VerifyArgNotNull( nameof( module ) ) .DIBuilder .CreateReplaceableCompositeType( Tag.StructureType , name , scope , file , line ) ) { } public DebugStructType( NativeModule module , string nativeName , DIScope scope , string name , DIFile file = null , uint line = 0 ) : this( module.VerifyArgNotNull( nameof( module ) ).Context.CreateStructType( nativeName ), module, scope, name, file, line ) { } public bool IsOpaque => NativeType.IsOpaque; public bool IsPacked => NativeType.IsPacked; public IReadOnlyList Members => NativeType.Members; public string Name => NativeType.Name; public void SetBody( bool packed, params ITypeRef[ ] elements ) { NativeType.SetBody( packed, elements ); } public void SetBody( bool packed , NativeModule module , DIScope scope , DIFile diFile , uint line , DebugInfoFlags debugFlags , IEnumerable debugElements ) { var debugMembersArray = debugElements as IList ?? debugElements.ToList(); var nativeElements = debugMembersArray.Select( e => e.DebugType.NativeType ); SetBody( packed, module, scope, diFile, line, debugFlags, nativeElements, debugMembersArray ); } public void SetBody( bool packed , NativeModule module , DIScope scope , DIFile diFile , uint line , DebugInfoFlags debugFlags , IEnumerable nativeElements , IEnumerable debugElements , uint? bitSize = null , uint? bitAlignment = null ) { DebugMembers = new ReadOnlyCollection( debugElements as IList ?? debugElements.ToList( ) ); SetBody( packed, nativeElements.ToArray() ); var memberTypes = from memberInfo in DebugMembers select CreateMemberType( module, memberInfo ); var concreteType = module.DIBuilder.CreateStructType( scope: scope , name: DIType.Name , file: diFile , line: line , bitSize: bitSize ?? module.Layout.BitSizeOf( NativeType ) , bitAlign: bitAlignment ?? module.Layout.AbiBitAlignmentOf( NativeType ) , debugFlags: debugFlags , derivedFrom: null , elements: memberTypes ); DIType = concreteType; } private DIDerivedType CreateMemberType( NativeModule module, DebugMemberInfo memberInfo ) { ulong bitSize; ulong bitAlign; ulong bitOffset; // if explicit layout info provided, use it; // otherwise use module.Layout as the default if( memberInfo.ExplicitLayout != null ) { bitSize = memberInfo.ExplicitLayout.BitSize; bitAlign = memberInfo.ExplicitLayout.BitAlignment; bitOffset = memberInfo.ExplicitLayout.BitOffset; } else { bitSize = module.Layout.BitSizeOf( memberInfo.DebugType.NativeType ); bitAlign = module.Layout.AbiBitAlignmentOf( memberInfo.DebugType.NativeType ); bitOffset = module.Layout.BitOffsetOfElement( NativeType, memberInfo.Index ); } return module.DIBuilder.CreateMemberType( scope: DIType , name: memberInfo.Name , file: memberInfo.File , line: memberInfo.Line , bitSize: bitSize , bitAlign: bitAlign , bitOffset: bitOffset , debugFlags: memberInfo.DebugInfoFlags , type: memberInfo.DebugType.DIType ); } public IReadOnlyList DebugMembers { get; private set; } } } ================================================ FILE: Zelig/Zelig/CompileTime/Llvm.NET/Llvm.NET/DebugInfo/DebugType.cs ================================================ using System; using System.Diagnostics.CodeAnalysis; using Llvm.NET.Types; using Llvm.NET.Values; namespace Llvm.NET.DebugInfo { /// Provides pairing of a with a for function signatures /// /// Primitive types and function signature types are all interned in LLVM, thus there won't be a /// strict one to one relationship between an LLVM type and corresponding language specific debug /// type. (e.g. unsigned char, char, byte and signed byte might all be 8 bit integer values as far /// as LLVM is concerned. Also, when using the pointer+alloca+memcpy pattern to pass by value the /// actual source debug info type is different than the LLVM function signature. This class is used /// to construct native type and debug info pairing to allow applications to maintain a link from /// their AST or IR types into the LLVM native type and debug information. /// /// /// It is important to note that the relationship between the to it's /// properties is strictly one way. That is, there is no way to take an arbitrary and re-associate /// it with the DIType or an implementation of this interface as there may be many such mappings to choose from. /// /// public interface IDebugType : ITypeRef where TNative : ITypeRef where TDebug : DIType { /// LLVM NativeType this interface is associating with debug info in TNative NativeType { get; } /// Debug information type this interface is associating with TDebug DIType { get; } } public class DebugType : IDebugType , ITypeRef where TNative : ITypeRef where TDebug : DIType { internal DebugType( TNative llvmType, TDebug diType ) { NativeType = llvmType; DIType = diType; } [SuppressMessage( "Microsoft.Naming", "CA2204:Literals should be spelled correctly", MessageId = "DIType" )] public TDebug DIType { get { return DIType_; } set { if( DIType_ == null ) { DIType_ = value; } else if( DIType_.IsTemporary ) { if( value.IsTemporary ) throw new InvalidOperationException( "Cannot replace a temporary with another temporary" ); DIType_.ReplaceAllUsesWith( value ); DIType_ = value; } else throw new InvalidOperationException( "Cannot replace non temporary DIType with a new Type" ); } } private TDebug DIType_; public TNative NativeType { get; } public IntPtr TypeHandle => NativeType.TypeHandle; public bool IsSized => NativeType.IsSized; public TypeKind Kind => NativeType.Kind; public Context Context => NativeType.Context; public uint IntegerBitWidth => NativeType.IntegerBitWidth; public bool IsInteger => NativeType.IsInteger; public bool IsFloat => NativeType.IsFloat; public bool IsDouble => NativeType.IsDouble; public bool IsVoid => NativeType.IsVoid; public bool IsStruct => NativeType.IsStruct; public bool IsPointer => NativeType.IsPointer; public bool IsSequence => NativeType.IsSequence; public bool IsFloatingPoint => NativeType.IsFloatingPoint; public bool IsPointerPointer => NativeType.IsPointerPointer; public Constant GetNullValue( ) => NativeType.GetNullValue( ); public IArrayType CreateArrayType( uint count ) => NativeType.CreateArrayType( count ); public IPointerType CreatePointerType( ) => NativeType.CreatePointerType( ); public IPointerType CreatePointerType( uint addressSpace ) => NativeType.CreatePointerType( addressSpace ); public DebugPointerType CreatePointerType( NativeModule module, uint addressSpace ) { if( DIType == null ) throw new ArgumentException( "Type does not have associated Debug type from which to construct a pointer type" ); var nativePointer = NativeType.CreatePointerType( addressSpace ); return new DebugPointerType( nativePointer, module, DIType, string.Empty ); } public DebugArrayType CreateArrayType( NativeModule module, uint lowerBound, uint count ) { if( DIType == null ) throw new ArgumentException( "Type does not have associated Debug type from which to construct an array type" ); var llvmArray = NativeType.CreateArrayType( count ); return new DebugArrayType( llvmArray, module, DIType, count, lowerBound ); } public bool TryGetExtendedPropertyValue( string id, out TProperty value ) { if( PropertyContainer.TryGetExtendedPropertyValue( id, out value ) ) return true; return NativeType.TryGetExtendedPropertyValue( id, out value ); } public void AddExtendedPropertyValue( string id, object value ) { PropertyContainer.AddExtendedPropertyValue( id, value ); } [SuppressMessage( "Microsoft.Usage", "CA2225:OperatorOverloadsHaveNamedAlternates", Justification = "Available as a property, this is for convenience" )] public static implicit operator TDebug( DebugType self ) => self.VerifyArgNotNull(nameof(self)).DIType; private readonly ExtensiblePropertyContainer PropertyContainer = new ExtensiblePropertyContainer( ); } public static class DebugType { /// Creates a new instance inferring the generic arguments from the parameters /// Type of the Native LLVM type for the association /// Type of the debug information type for the association /// type instance for this association /// type instance for this association /// implementation for the specified association public static IDebugType Create( TNative nativeType , TDebug debugType ) where TNative : ITypeRef where TDebug : DIType { return new DebugType( nativeType, debugType ); } /// Convenience extensions for determining if the property is valid /// /// In LLVM Debug information a is /// used to represent the void type. Thus, looking only at the property is /// insufficient to distinguish between a type with no debug information and one representing the void /// type. This property is used to disambiguate the two possibilities. /// public static bool HasDebugInfo( this IDebugType debugType ) { if( debugType == null ) throw new ArgumentNullException( nameof( debugType ) ); return debugType.DIType != null || debugType.NativeType.IsVoid; } } } ================================================ FILE: Zelig/Zelig/CompileTime/Llvm.NET/Llvm.NET/DebugInfo/DwarfEnumerations.cs ================================================  using System; using Llvm.NET.Native; namespace Llvm.NET.DebugInfo { public enum SourceLanguage { Invalid = 0, // Language names C89 = 0x0001, C = 0x0002, Ada83 = 0x0003, CPlusPlus = 0x0004, Cobol74 = 0x0005, Cobol85 = 0x0006, Fortran77 = 0x0007, Fortran90 = 0x0008, Pascal83 = 0x0009, Modula2 = 0x000a, Java = 0x000b, C99 = 0x000c, Ada95 = 0x000d, Fortran95 = 0x000e, PLI = 0x000f, ObjC = 0x0010, ObjCPlusPlus = 0x0011, UPC = 0x0012, D = 0x0013, // New in DWARF 5: Python = 0x0014, OpenCL = 0x0015, Go = 0x0016, Modula3 = 0x0017, Haskell = 0x0018, CPlusPlus03 = 0x0019, CPlusPlus11 = 0x001a, OCaml = 0x001b, UserMin = 0x8000, LlvmMipsAssembler = UserMin + 1, CSharp = UserMin + 0x0100, ILAsm = UserMin + 0x01001, UserMax = 0xffff } [System.Diagnostics.CodeAnalysis.SuppressMessage( "Microsoft.Design", "CA1028:EnumStorageShouldBeInt32" )] public enum Tag : ushort { Invalid = 0, ArrayType = LLVMDwarfTag.LLVMDwarfTagArrayType, ClassType= LLVMDwarfTag.LLVMDwarfTagClassType, EntryPoint= LLVMDwarfTag.LLVMDwarfTagEntryPoint, EnumerationType= LLVMDwarfTag.LLVMDwarfTagEnumerationType, FormalParameter= LLVMDwarfTag.LLVMDwarfTagFormalParameter, ImportedDeclaration= LLVMDwarfTag.LLVMDwarfTagImportedDeclaration, Label= LLVMDwarfTag.LLVMDwarfTagLabel, LexicalBlock= LLVMDwarfTag.LLVMDwarfTagLexicalBlock, Member= LLVMDwarfTag.LLVMDwarfTagMember, PointerType= LLVMDwarfTag.LLVMDwarfTagPointerType, ReferenceType= LLVMDwarfTag.LLVMDwarfTagReferenceType, CompileUnit= LLVMDwarfTag.LLVMDwarfTagCompileUnit, StringType= LLVMDwarfTag.LLVMDwarfTagStringType, StructureType= LLVMDwarfTag.LLVMDwarfTagStructureType, SubroutineType= LLVMDwarfTag.LLVMDwarfTagSubroutineType, TypeDef= LLVMDwarfTag.LLVMDwarfTagTypeDef, UnionType= LLVMDwarfTag.LLVMDwarfTagUnionType, UnspecifiedParameters= LLVMDwarfTag.LLVMDwarfTagUnspecifiedParameters, Variant= LLVMDwarfTag.LLVMDwarfTagVariant, CommonBlock= LLVMDwarfTag.LLVMDwarfTagCommonBlock, CommonInclusion= LLVMDwarfTag.LLVMDwarfTagCommonInclusion, Inheritance= LLVMDwarfTag.LLVMDwarfTagInheritance, InlinedSubroutine= LLVMDwarfTag.LLVMDwarfTagInlinedSubroutine, Module= LLVMDwarfTag.LLVMDwarfTagModule, PtrToMemberType= LLVMDwarfTag.LLVMDwarfTagPtrToMemberType, SetType= LLVMDwarfTag.LLVMDwarfTagSetType, SubrangeType= LLVMDwarfTag.LLVMDwarfTagSubrangeType, WithStatement= LLVMDwarfTag.LLVMDwarfTagWithStatement, AccessDeclaration= LLVMDwarfTag.LLVMDwarfTagAccessDeclaration, BaseType= LLVMDwarfTag.LLVMDwarfTagBaseType, CatchBlock= LLVMDwarfTag.LLVMDwarfTagCatchBlock, ConstType= LLVMDwarfTag.LLVMDwarfTagConstType, Constant= LLVMDwarfTag.LLVMDwarfTagConstant, Enumerator= LLVMDwarfTag.LLVMDwarfTagEnumerator, FileType= LLVMDwarfTag.LLVMDwarfTagFileType, Friend= LLVMDwarfTag.LLVMDwarfTagFriend, NameList= LLVMDwarfTag.LLVMDwarfTagNameList, NameListItem= LLVMDwarfTag.LLVMDwarfTagNameListItem, PackedType= LLVMDwarfTag.LLVMDwarfTagPackedType, SubProgram = LLVMDwarfTag.LLVMDwarfTagSubProgram, TemplateTypeParameter= LLVMDwarfTag.LLVMDwarfTagTemplateTypeParameter, TemplateValueParameter= LLVMDwarfTag.LLVMDwarfTagTemplateValueParameter, ThrownType= LLVMDwarfTag.LLVMDwarfTagThrownType, TryBlock= LLVMDwarfTag.LLVMDwarfTagTryBlock, VariantPart= LLVMDwarfTag.LLVMDwarfTagVariantPart, Variable= LLVMDwarfTag.LLVMDwarfTagVariable, VolatileType= LLVMDwarfTag.LLVMDwarfTagVolatileType, DwarfProcedure= LLVMDwarfTag.LLVMDwarfTagDwarfProcedure, RestrictType= LLVMDwarfTag.LLVMDwarfTagRestrictType, InterfaceType= LLVMDwarfTag.LLVMDwarfTagInterfaceType, Namespace= LLVMDwarfTag.LLVMDwarfTagNamespace, ImportedModule= LLVMDwarfTag.LLVMDwarfTagImportedModule, UnspecifiedType= LLVMDwarfTag.LLVMDwarfTagUnspecifiedType, PartialUnit= LLVMDwarfTag.LLVMDwarfTagPartialUnit, ImportedUnit= LLVMDwarfTag.LLVMDwarfTagImportedUnit, Condition= LLVMDwarfTag.LLVMDwarfTagCondition, SharedType= LLVMDwarfTag.LLVMDwarfTagSharedType, TypeUnit= LLVMDwarfTag.LLVMDwarfTagTypeUnit, RValueReferenceType= LLVMDwarfTag.LLVMDwarfTagRValueReferenceType, TemplateAlias= LLVMDwarfTag.LLVMDwarfTagTemplateAlias, // New in DWARF 5: // New in DWARF 5: CoArrayType= LLVMDwarfTag.LLVMDwarfTagCoArrayType, GenericSubrange= LLVMDwarfTag.LLVMDwarfTagGenericSubrange, DynamicType= LLVMDwarfTag.LLVMDwarfTagDynamicType, // LLVM Custom constants AutoVariable = 0x100, // Tag for local (auto) variables. ArgVariable = 0x101, // Tag for argument variables. Expression = 0x102, // Tag for complex address expressions. UserBase = 0x1000, // Recommended base for user tags. MipsLoop = LLVMDwarfTag.LLVMDwarfTagMipsLoop, FormatLabel= LLVMDwarfTag.LLVMDwarfTagFormatLabel, FunctionTemplate= LLVMDwarfTag.LLVMDwarfTagFunctionTemplate, ClassTemplate= LLVMDwarfTag.LLVMDwarfTagClassTemplate, GnuTemplateTemplateParameter = LLVMDwarfTag.LLVMDwarfTagGnuTemplateTemplateParam, GnuTemplateParameterPack= LLVMDwarfTag.LLVMDwarfTagGnuTemplateParameterPack, GnuFormalParameterPack= LLVMDwarfTag.LLVMDwarfTagGnuFormalParameterPack, LoUser= LLVMDwarfTag.LLVMDwarfTagLoUser, AppleProperty= LLVMDwarfTag.LLVMDwarfTagAppleProperty, HiUser = LLVMDwarfTag.LLVMDwarfTagHiUser } public enum QualifiedTypeTag { None = 0, Const = Tag.ConstType, Volatile = Tag.VolatileType, } [System.Diagnostics.CodeAnalysis.SuppressMessage( "Microsoft.Design", "CA1028:EnumStorageShouldBeInt32" )] public enum DiTypeKind : uint { Invalid = 0, // Encoding attribute values Address = 0x01, Boolean = 0x02, ComplexFloat = 0x03, Float = 0x04, Signed = 0x05, SignedChar = 0x06, Unsigned = 0x07, UnsignedChar = 0x08, ImaginaryFloat = 0x09, PackedDecimal = 0x0a, NumericString = 0x0b, Edited = 0x0c, SignedFixed = 0x0d, UnsignedFixed = 0x0e, DecimalFloat = 0x0f, UTF = 0x10, LoUser = 0x80, HiUser = 0xff } /// Accessibility flags /// /// The three accessibility flags are mutually exclusive and rolled together /// in the first two bits. /// [System.Diagnostics.CodeAnalysis.SuppressMessage( "Microsoft.Naming", "CA1726:UsePreferredTerms", MessageId = "Flags" )] [Flags] public enum DebugInfoFlags { None = 0, Private = 1, Protected = 2, Public = 3, AccessibilityMask = 1 << 0 | 1 << 1, ForwardDeclaration = 1 << 2, AppleBlock = 1 << 3, BlockByrefStruct = 1 << 4, Virtual = 1 << 5, Artificial = 1 << 6, Explicit = 1 << 7, Prototyped = 1 << 8, ObjcClassComplete = 1 << 9, ObjectPointer = 1 << 10, Vector = 1 << 11, StaticMember = 1 << 12, IndirectVariable = 1 << 13, LValueReference = 1 << 14, RValueReference = 1 << 15 } [System.Diagnostics.CodeAnalysis.SuppressMessage( "Microsoft.Design", "CA1028:EnumStorageShouldBeInt32" )] public enum ExpressionOp : long { Invalid = 0, addr = 0x03, deref = 0x06, const1u = 0x08, const1s = 0x09, const2u = 0x0a, const2s = 0x0b, const4u = 0x0c, const4s = 0x0d, const8u = 0x0e, const8s = 0x0f, constu = 0x10, consts = 0x11, dup = 0x12, drop = 0x13, over = 0x14, pick = 0x15, swap = 0x16, rot = 0x17, xderef = 0x18, abs = 0x19, and = 0x1a, div = 0x1b, minus = 0x1c, mod = 0x1d, mul = 0x1e, neg = 0x1f, not = 0x20, or = 0x21, plus = 0x22, plus_uconst = 0x23, shl = 0x24, shr = 0x25, shra = 0x26, xor = 0x27, skip = 0x2f, bra = 0x28, eq = 0x29, ge = 0x2a, gt = 0x2b, le = 0x2c, lt = 0x2d, ne = 0x2e, lit0 = 0x30, lit1 = 0x31, lit2 = 0x32, lit3 = 0x33, lit4 = 0x34, lit5 = 0x35, lit6 = 0x36, lit7 = 0x37, lit8 = 0x38, lit9 = 0x39, lit10 = 0x3a, lit11 = 0x3b, lit12 = 0x3c, lit13 = 0x3d, lit14 = 0x3e, lit15 = 0x3f, lit16 = 0x40, lit17 = 0x41, lit18 = 0x42, lit19 = 0x43, lit20 = 0x44, lit21 = 0x45, lit22 = 0x46, lit23 = 0x47, lit24 = 0x48, lit25 = 0x49, lit26 = 0x4a, lit27 = 0x4b, lit28 = 0x4c, lit29 = 0x4d, lit30 = 0x4e, lit31 = 0x4f, reg0 = 0x50, reg1 = 0x51, reg2 = 0x52, reg3 = 0x53, reg4 = 0x54, reg5 = 0x55, reg6 = 0x56, reg7 = 0x57, reg8 = 0x58, reg9 = 0x59, reg10 = 0x5a, reg11 = 0x5b, reg12 = 0x5c, reg13 = 0x5d, reg14 = 0x5e, reg15 = 0x5f, reg16 = 0x60, reg17 = 0x61, reg18 = 0x62, reg19 = 0x63, reg20 = 0x64, reg21 = 0x65, reg22 = 0x66, reg23 = 0x67, reg24 = 0x68, reg25 = 0x69, reg26 = 0x6a, reg27 = 0x6b, reg28 = 0x6c, reg29 = 0x6d, reg30 = 0x6e, reg31 = 0x6f, breg0 = 0x70, breg1 = 0x71, breg2 = 0x72, breg3 = 0x73, breg4 = 0x74, breg5 = 0x75, breg6 = 0x76, breg7 = 0x77, breg8 = 0x78, breg9 = 0x79, breg10 = 0x7a, breg11 = 0x7b, breg12 = 0x7c, breg13 = 0x7d, breg14 = 0x7e, breg15 = 0x7f, breg16 = 0x80, breg17 = 0x81, breg18 = 0x82, breg19 = 0x83, breg20 = 0x84, breg21 = 0x85, breg22 = 0x86, breg23 = 0x87, breg24 = 0x88, breg25 = 0x89, breg26 = 0x8a, breg27 = 0x8b, breg28 = 0x8c, breg29 = 0x8d, breg30 = 0x8e, breg31 = 0x8f, regx = 0x90, fbreg = 0x91, bregx = 0x92, piece = 0x93, deref_size = 0x94, xderef_size = 0x95, nop = 0x96, push_object_address = 0x97, call2 = 0x98, call4 = 0x99, call_ref = 0x9a, form_tls_address = 0x9b, call_frame_cfa = 0x9c, bit_piece = 0x9d, implicit_value = 0x9e, stack_value = 0x9f, // Extensions for GNU-style thread-local storage. GNU_push_tls_address = 0xe0, // Extensions for Fission proposal. GNU_addr_index = 0xfb, GNU_const_index = 0xfc, } } ================================================ FILE: Zelig/Zelig/CompileTime/Llvm.NET/Llvm.NET/DebugInfo/GenericDINode.cs ================================================ using Llvm.NET.Native; namespace Llvm.NET.DebugInfo { public class GenericDINode : DINode { internal GenericDINode( LLVMMetadataRef handle ) : base( handle ) { } } } ================================================ FILE: Zelig/Zelig/CompileTime/Llvm.NET/Llvm.NET/DebugInfo/MDNodeOperandList.cs ================================================ using System; using System.Collections.Generic; using Llvm.NET.Native; namespace Llvm.NET.Values { /// Support class to provide readonly list semantics to the operands of an MDNode internal class MDNodeOperandList : IReadOnlyList { internal MDNodeOperandList( MDNode owningNode ) { OwningNode = owningNode; } public MDOperand this[ int index ] { get { if( index >= Count || index < 0 ) throw new ArgumentOutOfRangeException( nameof( index ) ); var handle = NativeMethods.MDNodeGetOperand( OwningNode.MetadataHandle, ( uint )index ); return MDOperand.FromHandle( OwningNode, handle ); } } public int Count { get { uint count = NativeMethods.MDNodeGetNumOperands( OwningNode.MetadataHandle ); return ( int )Math.Min( count, int.MaxValue ); } } public IEnumerator GetEnumerator( ) { for( uint i = 0; i < Count; ++i ) { LLVMMDOperandRef handle = NativeMethods.MDNodeGetOperand( OwningNode.MetadataHandle, i ) ; if( handle.Pointer == IntPtr.Zero ) yield break; yield return MDOperand.FromHandle( OwningNode, handle ); } } System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator( ) => GetEnumerator( ); private MDNode OwningNode; } } ================================================ FILE: Zelig/Zelig/CompileTime/Llvm.NET/Llvm.NET/Enumerations.cs ================================================ // This file maps the lower level internal LLVM enumeration names to something // more compatible with the styles, patterns and conventions familiar to .NET Developers. // This also keeping the lower level interop namespace internal to prevent mis-use or // violations of uniqueness rules using Llvm.NET.Native; namespace Llvm.NET { /// See Module::ModFlagBehavior [System.Diagnostics.CodeAnalysis.SuppressMessage( "Microsoft.Design", "CA1028:EnumStorageShouldBeInt32" )] [System.Diagnostics.CodeAnalysis.SuppressMessage( "Microsoft.Naming", "CA1726:UsePreferredTerms", MessageId = "Flag" )] public enum ModuleFlagBehavior : uint { Invalid = 0, Error = LLVMModFlagBehavior.Error, Warning = LLVMModFlagBehavior.Warning, Require = LLVMModFlagBehavior.Require, Override = LLVMModFlagBehavior.Override, Append = LLVMModFlagBehavior.Append, AppendUnique = LLVMModFlagBehavior.AppendUnique }; /// LLVM Instruction opcodes /// /// These are based on the "C" API and therefore more stable as changes in the underlying instruction ids are remapped in the C API layer /// [System.Diagnostics.CodeAnalysis.SuppressMessage( "Microsoft.Design", "CA1028:EnumStorageShouldBeInt32" )] [System.Diagnostics.CodeAnalysis.SuppressMessage( "Microsoft.Design", "CA1027:MarkEnumsWithFlags", Justification = "Not actually flags" )] public enum OpCode : uint { Invalid = 0, /* Terminator Instructions */ Return = LLVMOpcode.LLVMRet, Branch = LLVMOpcode.LLVMBr, Switch = LLVMOpcode.LLVMSwitch, IndirectBranch = LLVMOpcode.LLVMIndirectBr, Invoke = LLVMOpcode.LLVMInvoke, Unreachable = LLVMOpcode.LLVMUnreachable, /* Standard Binary Operators */ Add = LLVMOpcode.LLVMAdd, FAdd = LLVMOpcode.LLVMFAdd, Sub = LLVMOpcode.LLVMSub, FSub = LLVMOpcode.LLVMFSub, Mul = LLVMOpcode.LLVMMul, FMul = LLVMOpcode.LLVMFMul, UDiv = LLVMOpcode.LLVMUDiv, SDiv = LLVMOpcode.LLVMSDiv, FDiv = LLVMOpcode.LLVMFDiv, URem = LLVMOpcode.LLVMURem, SRem = LLVMOpcode.LLVMSRem, FRem = LLVMOpcode.LLVMFRem, /* Logical Operators */ Shl = LLVMOpcode.LLVMShl, LShr = LLVMOpcode.LLVMLShr, AShr = LLVMOpcode.LLVMAShr, And = LLVMOpcode.LLVMAnd, Or = LLVMOpcode.LLVMOr, Xor = LLVMOpcode.LLVMXor, /* Memory Operators */ Alloca = LLVMOpcode.LLVMAlloca, Load = LLVMOpcode.LLVMLoad, Store = LLVMOpcode.LLVMStore, GetElementPtr = LLVMOpcode.LLVMGetElementPtr, /* Cast Operators */ Trunc = LLVMOpcode.LLVMTrunc, ZeroExtend = LLVMOpcode.LLVMZExt, SignExtend = LLVMOpcode.LLVMSExt, FPToUI = LLVMOpcode.LLVMFPToUI, FPToSI = LLVMOpcode.LLVMFPToSI, UIToFP = LLVMOpcode.LLVMUIToFP, SIToFP = LLVMOpcode.LLVMSIToFP, FPTrunc = LLVMOpcode.LLVMFPTrunc, FPExt = LLVMOpcode.LLVMFPExt, PtrToInt = LLVMOpcode.LLVMPtrToInt, IntToPtr = LLVMOpcode.LLVMIntToPtr, BitCast = LLVMOpcode.LLVMBitCast, AddrSpaceCast = LLVMOpcode.LLVMAddrSpaceCast, /* Other Operators */ ICmp = LLVMOpcode.LLVMICmp, FCmp = LLVMOpcode.LLVMFCmp, Phi = LLVMOpcode.LLVMPHI, Call = LLVMOpcode.LLVMCall, Select = LLVMOpcode.LLVMSelect, UserOp1 = LLVMOpcode.LLVMUserOp1, UserOp2 = LLVMOpcode.LLVMUserOp2, VaArg = LLVMOpcode.LLVMVAArg, ExtractElement = LLVMOpcode.LLVMExtractElement, InsertElement = LLVMOpcode.LLVMInsertElement, ShuffleVector = LLVMOpcode.LLVMShuffleVector, ExtractValue = LLVMOpcode.LLVMExtractValue, InsertValue = LLVMOpcode.LLVMInsertValue, /* Atomic operators */ Fence = LLVMOpcode.LLVMFence, AtomicCmpXchg = LLVMOpcode.LLVMAtomicCmpXchg, AtomicRMW = LLVMOpcode.LLVMAtomicRMW, /* Exception Handling Operators */ Resume = LLVMOpcode.LLVMResume, LandingPad = LLVMOpcode.LLVMLandingPad, CleanupRet = LLVMOpcode.LLVMCleanupRet, CatchRet = LLVMOpcode.LLVMCatchRet, CatchPad = LLVMOpcode.LLVMCatchPad, CleanupPad = LLVMOpcode.LLVMCleandupPad, CatchSwitch = LLVMOpcode.LLVMCatchSwitch } /// Basic kind of a type [System.Diagnostics.CodeAnalysis.SuppressMessage( "Microsoft.Design", "CA1028:EnumStorageShouldBeInt32" )] public enum TypeKind : uint { Void = LLVMTypeKind.LLVMVoidTypeKind, // type with no size Float16 = LLVMTypeKind.LLVMHalfTypeKind, // 16 bit floating point type Float32 = LLVMTypeKind.LLVMFloatTypeKind, // 32 bit floating point type Float64 = LLVMTypeKind.LLVMDoubleTypeKind, // 64 bit floating point type X86Float80 = LLVMTypeKind.LLVMX86_FP80TypeKind, // 80 bit floating point type (X87) Float128m112 = LLVMTypeKind.LLVMFP128TypeKind, // 128 bit floating point type (112-bit mantissa) Float128 = LLVMTypeKind.LLVMPPC_FP128TypeKind, // 128 bit floating point type (two 64-bits) Label = LLVMTypeKind.LLVMLabelTypeKind, // Labels Integer = LLVMTypeKind.LLVMIntegerTypeKind, // Arbitrary bit width integers Function = LLVMTypeKind.LLVMFunctionTypeKind, // Functions Struct = LLVMTypeKind.LLVMStructTypeKind, // Structures Array = LLVMTypeKind.LLVMArrayTypeKind, // Arrays Pointer = LLVMTypeKind.LLVMPointerTypeKind, // Pointers Vector = LLVMTypeKind.LLVMVectorTypeKind, // SIMD 'packed' format, or other vector type Metadata = LLVMTypeKind.LLVMMetadataTypeKind, // Metadata X86MMX = LLVMTypeKind.LLVMX86_MMXTypeKind, // X86 MMX Token = LLVMTypeKind.LLVMTokenTypeKind // Exception handler Tokens } /// Calling Convention for functions [System.Diagnostics.CodeAnalysis.SuppressMessage( "Microsoft.Design", "CA1028:EnumStorageShouldBeInt32" )] public enum CallingConvention : uint { C = LLVMCallConv.LLVMCCallConv, FastCall = LLVMCallConv.LLVMFastCallConv, ColdCall = LLVMCallConv.LLVMColdCallConv, WebKitJS = LLVMCallConv.LLVMWebKitJSCallConv, AnyReg = LLVMCallConv.LLVMAnyRegCallConv, x86StdCall = LLVMCallConv.LLVMX86StdcallCallConv, x86FastCall = LLVMCallConv.LLVMX86FastcallCallConv } /// Linkage specification for functions and globals [System.Diagnostics.CodeAnalysis.SuppressMessage( "Microsoft.Design", "CA1028:EnumStorageShouldBeInt32" )] public enum Linkage : uint { External = LLVMLinkage.LLVMExternalLinkage, /*< Externally visible function */ AvailableExternally = LLVMLinkage.LLVMAvailableExternallyLinkage, LinkOnceAny = LLVMLinkage.LLVMLinkOnceAnyLinkage, /*< Keep one copy of function when linking (inline)*/ LinkOnceODR = LLVMLinkage.LLVMLinkOnceODRLinkage, /*< Same, but only replaced by something equivalent. */ //LLVMLinkage.LLVMLinkOnceODRAutoHideLinkage, /**< Obsolete */ Weak = LLVMLinkage.LLVMWeakAnyLinkage, /*< Keep one copy of function when linking (weak) */ WeakODR = LLVMLinkage.LLVMWeakODRLinkage, /*< Same, but only replaced by something equivalent. */ Append = LLVMLinkage.LLVMAppendingLinkage, /*< Special purpose, only applies to global arrays */ Internal = LLVMLinkage.LLVMInternalLinkage, /*< Rename collisions when linking (static functions) */ Private = LLVMLinkage.LLVMPrivateLinkage, /*< Like Internal, but omit from symbol table */ DllImport = LLVMLinkage.LLVMDLLImportLinkage, /*< Function to be imported from DLL */ DllExport = LLVMLinkage.LLVMDLLExportLinkage, /*< Function to be accessible from DLL */ ExternalWeak = LLVMLinkage.LLVMExternalWeakLinkage,/*< ExternalWeak linkage description */ //LLVMLinkage.LLVMGhostLinkage, /*< Obsolete */ Common = LLVMLinkage.LLVMCommonLinkage, /*< Tentative definitions */ LinkerPrivate = LLVMLinkage.LLVMLinkerPrivateLinkage, /*< Like Private, but linker removes. */ LinkerPrivateWeak = LLVMLinkage.LLVMLinkerPrivateWeakLinkage /*< Like LinkerPrivate, but is weak. */ } ///Enumeration for the visibility of a global value [System.Diagnostics.CodeAnalysis.SuppressMessage( "Microsoft.Design", "CA1028:EnumStorageShouldBeInt32" )] public enum Visibility : uint { Default = LLVMVisibility.LLVMDefaultVisibility, /*< The GV is visible */ Hidden = LLVMVisibility.LLVMHiddenVisibility, /*< The GV is hidden */ Protected = LLVMVisibility.LLVMProtectedVisibility /*< The GV is protected */ } /// Unified predicate enumeration /// /// Underneath the C API this is what LLVM uses. For some reason the C API /// split it into the integer and float predicate enumerations. /// [System.Diagnostics.CodeAnalysis.SuppressMessage( "Microsoft.Design", "CA1028:EnumStorageShouldBeInt32" )] [System.Diagnostics.CodeAnalysis.SuppressMessage( "Microsoft.Design", "CA1027:MarkEnumsWithFlags" )] public enum Predicate : uint { False = LLVMRealPredicate.LLVMRealPredicateFalse, OrderedAndEqual = LLVMRealPredicate.LLVMRealOEQ, OrderedAndGreaterThan = LLVMRealPredicate.LLVMRealOGT, OrderedAndGreaterThanOrEqual = LLVMRealPredicate.LLVMRealOGE, OrderedAndLessThan = LLVMRealPredicate.LLVMRealOLT, OrderedAndLessThanOrEqual = LLVMRealPredicate.LLVMRealOLE, OrderedAndNotEqual = LLVMRealPredicate.LLVMRealONE, Ordered = LLVMRealPredicate.LLVMRealORD, Unordered = LLVMRealPredicate.LLVMRealUNO, UnorderedAndEqual = LLVMRealPredicate.LLVMRealUEQ, UnorderedOrGreaterThan = LLVMRealPredicate.LLVMRealUGT, UnorderedOrGreaterThanOrEqual = LLVMRealPredicate.LLVMRealUGE, UnorderedOrLessThan = LLVMRealPredicate.LLVMRealULT, UnorderedOrLessThanOrEqual = LLVMRealPredicate.LLVMRealULE, UnorderedOrNotEqual = LLVMRealPredicate.LLVMRealUNE, True = LLVMRealPredicate.LLVMRealPredicateTrue, FirstFcmpPredicate = False, LastFcmpPredicate = True, /// Any value Greater than or equal to this is not valid for Fcmp operations BadFcmpPredicate = LastFcmpPredicate + 1, Equal = LLVMIntPredicate.LLVMIntEQ, NotEqual = LLVMIntPredicate.LLVMIntNE, UnsignedGreater = LLVMIntPredicate.LLVMIntUGT, UnsignedGreaterOrEqual = LLVMIntPredicate.LLVMIntUGE, UnsignedLess = LLVMIntPredicate.LLVMIntULT, UnsignedLessOrEqual = LLVMIntPredicate.LLVMIntULE, SignedGreater = LLVMIntPredicate.LLVMIntSGT, SignedGreaterOrEqual = LLVMIntPredicate.LLVMIntSGE, SignedLess = LLVMIntPredicate.LLVMIntSLT, SignedLessOrEqual = LLVMIntPredicate.LLVMIntSLE, FirstIcmpPredicate = Equal, LastIcmpPredicate = SignedLessOrEqual, /// Any value Greater than or equal to this is not valid for Icmp operations BadIcmpPredicate = LastIcmpPredicate + 1 } ///Predicate enumeration for integer comparison [System.Diagnostics.CodeAnalysis.SuppressMessage( "Microsoft.Design", "CA1028:EnumStorageShouldBeInt32" )] public enum IntPredicate : uint { False = LLVMRealPredicate.LLVMRealPredicateFalse, Equal = LLVMIntPredicate.LLVMIntEQ, NotEqual = LLVMIntPredicate.LLVMIntNE, UnsignedGreater = LLVMIntPredicate.LLVMIntUGT, UnsignedGreaterOrEqual = LLVMIntPredicate.LLVMIntUGE, UnsignedLess = LLVMIntPredicate.LLVMIntULT, UnsignedLessOrEqual = LLVMIntPredicate.LLVMIntULE, SignedGreater = LLVMIntPredicate.LLVMIntSGT, SignedGreaterOrEqual = LLVMIntPredicate.LLVMIntSGE, SignedLess = LLVMIntPredicate.LLVMIntSLT, SignedLessOrEqual = LLVMIntPredicate.LLVMIntSLE } ///Predicate enumeration for integer comparison [System.Diagnostics.CodeAnalysis.SuppressMessage( "Microsoft.Design", "CA1028:EnumStorageShouldBeInt32" )] public enum RealPredicate : uint { False = LLVMRealPredicate.LLVMRealPredicateFalse, OrderedAndEqual = LLVMRealPredicate.LLVMRealOEQ, OrderedAndGreaterThan = LLVMRealPredicate.LLVMRealOGT, OrderedAndGreaterThanOrEqual = LLVMRealPredicate.LLVMRealOGE, OrderedAndLessThan = LLVMRealPredicate.LLVMRealOLT, OrderedAndLessThanOrEqual = LLVMRealPredicate.LLVMRealOLE, OrderedAndNotEqual = LLVMRealPredicate.LLVMRealONE, Ordered = LLVMRealPredicate.LLVMRealORD, Unordered = LLVMRealPredicate.LLVMRealUNO, UnorderedAndEqual = LLVMRealPredicate.LLVMRealUEQ, UnorderedOrGreaterThan = LLVMRealPredicate.LLVMRealUGT, UnorderedOrGreaterThanOrEqual = LLVMRealPredicate.LLVMRealUGE, UnorderedOrLessThan = LLVMRealPredicate.LLVMRealULT, UnorderedOrLessThanOrEqual = LLVMRealPredicate.LLVMRealULE, UnorderedOrNotEqual = LLVMRealPredicate.LLVMRealUNE, True = LLVMRealPredicate.LLVMRealPredicateTrue, } /// Optimization level for target code generation [System.Diagnostics.CodeAnalysis.SuppressMessage( "Microsoft.Design", "CA1028:EnumStorageShouldBeInt32" )] public enum CodeGenOpt : uint { None = LLVMCodeGenOptLevel.LLVMCodeGenLevelNone, Less = LLVMCodeGenOptLevel.LLVMCodeGenLevelLess, Default = LLVMCodeGenOptLevel.LLVMCodeGenLevelDefault, Aggressive = LLVMCodeGenOptLevel.LLVMCodeGenLevelAggressive } /// Relocation type for target code generation [System.Diagnostics.CodeAnalysis.SuppressMessage( "Microsoft.Design", "CA1028:EnumStorageShouldBeInt32" )] public enum Reloc : uint { Default = LLVMRelocMode.LLVMRelocDefault, Static = LLVMRelocMode.LLVMRelocStatic, PositionIndependent = LLVMRelocMode.LLVMRelocPIC, Dynamic = LLVMRelocMode.LLVMRelocDynamicNoPic } /// Code model to use for target code generation [System.Diagnostics.CodeAnalysis.SuppressMessage( "Microsoft.Design", "CA1028:EnumStorageShouldBeInt32" )] public enum CodeModel : uint { Default = LLVMCodeModel.LLVMCodeModelDefault, JitDefault = LLVMCodeModel.LLVMCodeModelJITDefault, Small = LLVMCodeModel.LLVMCodeModelSmall, Kernel = LLVMCodeModel.LLVMCodeModelKernel, Medium = LLVMCodeModel.LLVMCodeModelMedium, Large = LLVMCodeModel.LLVMCodeModelLarge } /// Output file type for target code generation [System.Diagnostics.CodeAnalysis.SuppressMessage( "Microsoft.Design", "CA1028:EnumStorageShouldBeInt32" )] public enum CodeGenFileType : uint { AssemblySource = LLVMCodeGenFileType.LLVMAssemblyFile, ObjectFile = LLVMCodeGenFileType.LLVMObjectFile } /// Byte ordering for target code generation and data type layout [System.Diagnostics.CodeAnalysis.SuppressMessage( "Microsoft.Design", "CA1028:EnumStorageShouldBeInt32" )] public enum ByteOrdering : uint { LittleEndian = LLVMByteOrdering.LLVMLittleEndian, BigEndian = LLVMByteOrdering.LLVMBigEndian } /// LLVM module linker mode [System.Diagnostics.CodeAnalysis.SuppressMessage( "Microsoft.Design", "CA1028:EnumStorageShouldBeInt32" )] public enum LinkerMode : uint { DestroySource = LLVMLinkerMode.LLVMLinkerDestroySource, PreserveSource = LLVMLinkerMode.LLVMLinkerPreserveSource } /// Enumeration for well known attribute kinds /// /// The numeric value of the members of this enumeration are subject /// to change from version to version. Therefore code must never /// rely on the actual underlying value and use only the symbolic name /// /// /// For details on what the values should be see attributes.def in /// the LLVM source. This was added in v3.8.0 along with a change in /// the numerical values. /// public enum AttributeKind { None = LLVMAttrKind.None, Alignment = LLVMAttrKind.Alignment, AlwaysInline = LLVMAttrKind.AlwaysInline, ArgMemOnly = LLVMAttrKind.ArgMemOnly, Builtin = LLVMAttrKind.Builtin, ByVal = LLVMAttrKind.ByVal, Cold = LLVMAttrKind.Cold, Convergent = LLVMAttrKind.Convergent, Dereferenceable = LLVMAttrKind.Dereferenceable, DereferenceableOrNull = LLVMAttrKind.DereferenceableOrNull, InAlloca = LLVMAttrKind.InAlloca, InReg = LLVMAttrKind.InReg, InaccessibleMemOnly = LLVMAttrKind.InaccessibleMemOnly, InaccessibleMemOrArgMemOnly = LLVMAttrKind.InaccessibleMemOrArgMemOnly, InlineHint = LLVMAttrKind.InlineHint, JumpTable = LLVMAttrKind.JumpTable, MinSize = LLVMAttrKind.MinSize, Naked = LLVMAttrKind.Naked, Nest = LLVMAttrKind.Nest, NoAlias = LLVMAttrKind.NoAlias, NoBuiltin = LLVMAttrKind.NoBuiltin, NoCapture = LLVMAttrKind.NoCapture, NoDuplicate = LLVMAttrKind.NoDuplicate, NoImplicitFloat = LLVMAttrKind.NoImplicitFloat, NoInline = LLVMAttrKind.NoInline, NoRecurse = LLVMAttrKind.NoRecurse, NoRedZone = LLVMAttrKind.NoRedZone, NoReturn = LLVMAttrKind.NoReturn, NoUnwind = LLVMAttrKind.NoUnwind, NonLazyBind = LLVMAttrKind.NonLazyBind, NonNull = LLVMAttrKind.NonNull, OptimizeForSize = LLVMAttrKind.OptimizeForSize, OptimizeNone = LLVMAttrKind.OptimizeNone, ReadNone = LLVMAttrKind.ReadNone, ReadOnly = LLVMAttrKind.ReadOnly, Returned = LLVMAttrKind.Returned, ReturnsTwice = LLVMAttrKind.ReturnsTwice, SExt = LLVMAttrKind.SExt, SafeStack = LLVMAttrKind.SafeStack, SanitizeAddress = LLVMAttrKind.SanitizeAddress, SanitizeMemory = LLVMAttrKind.SanitizeMemory, SanitizeThread = LLVMAttrKind.SanitizeThread, StackAlignment = LLVMAttrKind.StackAlignment, StackProtect = LLVMAttrKind.StackProtect, StackProtectReq = LLVMAttrKind.StackProtectReq, StackProtectStrong = LLVMAttrKind.StackProtectStrong, StructRet = LLVMAttrKind.StructRet, UWTable = LLVMAttrKind.UWTable, ZExt = LLVMAttrKind.ZExt, EndAttrKinds // Sentinel value useful for loops }; /// Function index for attributes /// /// Attributes on functions apply to the function itself, the return type /// or one of the function's parameters. This enumeration is used to /// identify where the attribute applies. /// public enum FunctionAttributeIndex { /// The attribute applies to the function itself Function = -1, /// The attribute applies to the return type of the function ReturnType = 0, /// The attribute applies to the first parameter of the function /// /// Additional parameters can identified by simply adding an integer value to /// this value. (i.e. FunctionAttributeIndex.Parameter0 + 1 ) /// Parameter0 = 1 } } ================================================ FILE: Zelig/Zelig/CompileTime/Llvm.NET/Llvm.NET/GlobalPassRegistry.cs ================================================ using System; using System.Threading; using Llvm.NET.Native; namespace Llvm.NET { public static class GlobalPassRegistry { public static void InitializeAll() { InitializeCore( ); InitializeTransformUtils( ); InitializeScalarOpts( ); InitializeObjCARCOpts( ); InitializeVectorization( ); InitializeInstCombine( ); InitializeIPO( ); InitializeInstrumentation( ); InitializeAnalysis( ); InitializeIPA( ); InitializeCodeGen( ); InitializeTarget( ); } public static void InitializeCore() { NativeMethods.InitializeCore( PassRegistryHandle.Value ); } public static void InitializeTransformUtils() { NativeMethods.InitializeTransformUtils( PassRegistryHandle.Value ); } public static void InitializeScalarOpts() { NativeMethods.InitializeScalarOpts( PassRegistryHandle.Value ); } public static void InitializeObjCARCOpts() { NativeMethods.InitializeObjCARCOpts( PassRegistryHandle.Value ); } public static void InitializeVectorization() { NativeMethods.InitializeVectorization( PassRegistryHandle.Value ); } public static void InitializeInstCombine( ) { NativeMethods.InitializeInstCombine( PassRegistryHandle.Value ); } public static void InitializeIPO( ) { NativeMethods.InitializeIPO( PassRegistryHandle.Value ); } public static void InitializeInstrumentation( ) { NativeMethods.InitializeInstrumentation( PassRegistryHandle.Value ); } public static void InitializeAnalysis( ) { NativeMethods.InitializeAnalysis( PassRegistryHandle.Value ); } public static void InitializeIPA( ) { NativeMethods.InitializeIPA( PassRegistryHandle.Value ); } public static void InitializeCodeGen( ) { NativeMethods.InitializeCodeGen( PassRegistryHandle.Value ); } public static void InitializeTarget( ) { NativeMethods.InitializeTarget( PassRegistryHandle.Value ); } private static Lazy PassRegistryHandle = new Lazy( ( ) => NativeMethods.GetGlobalPassRegistry( ), LazyThreadSafetyMode.ExecutionAndPublication ); } } ================================================ FILE: Zelig/Zelig/CompileTime/Llvm.NET/Llvm.NET/IExtensiblePropertyContainer.cs ================================================ using System; using System.Collections.Generic; namespace Llvm.NET { /// Interface to allow adding arbitrary named data items to an object /// /// It is sometimes useful for code generation applications to attach some tool specific /// data to the LLVM objects created but that don't need representation as LLVM Metadata /// nodes. This interface provides such a facility. /// public interface IExtensiblePropertyContainer { /// Try to get a value from the container /// Type of value to retrieve /// id of the value to retrieve /// value retrieved if present (or default value of type otherwise) /// /// true if the item was found and it's type matches false otherwise. /// bool TryGetExtendedPropertyValue( string id, out T value ); /// Adds a value to the container /// Id of the value /// value to add /// /// Adds the value with the specified id. If a value with the same id /// already exists and its type is the same as /// it is replaced. If the existing value is of a different type, then /// an ArgumentException is thrown. /// void AddExtendedPropertyValue( string id, object value ); } /// Provides consistent accessors for an extended property /// Type of values stored in the property /// /// This class is used to describe a property stored in a class implementing /// . Using a single, typically /// , instance of this class to describe and access /// an extended property helps to encapsulate the type casting and property /// ID into a single place. Making calling code easier to comprehend and /// less prone to typographical errors that a compiler can't catch ahead of /// time. /// public class ExtensiblePropertyDescriptor { /// Creates a new instance of a property descriptor /// Name of the extended property public ExtensiblePropertyDescriptor( string name ) { Name = name; } /// Gets a value for the property from the container /// container /// Value retrieved from the property or the default value of type public T GetValueFrom( IExtensiblePropertyContainer container ) { return GetValueFrom( container, default( T ) ); } /// Gets a value for the property from the container /// container /// default value if the value is not yet present as an extended property /// Value retrieved from the property or if it wasn't found /// If the value didn't exist a new value with is added to the container public T GetValueFrom( IExtensiblePropertyContainer container, T defaultValue ) { return GetValueFrom( container, ( ) => defaultValue ); } /// Gets a value for the property from the container /// container /// default value factory delegate to create the default value if the value is not yet present as an extended property /// Value retrieved from the property or default value created by if it wasn't found /// If the value didn't exist a new value created by calling with is added to the container public T GetValueFrom( IExtensiblePropertyContainer container, Func lazyDefaultFactory ) { if( container == null ) throw new ArgumentNullException( nameof( container ) ); if( lazyDefaultFactory == null ) throw new ArgumentNullException( nameof( lazyDefaultFactory ) ); T retVal; if( container.TryGetExtendedPropertyValue( Name, out retVal ) ) return retVal; retVal = lazyDefaultFactory( ); container.AddExtendedPropertyValue( Name, retVal ); return retVal; } /// Sets the value of an extended property in a container /// Container to set the value in /// value of the property public void SetValueIn( IExtensiblePropertyContainer container, T value ) { if( container == null ) throw new ArgumentNullException( nameof( container ) ); container.AddExtendedPropertyValue( Name, value ); } /// Name of the property public string Name { get; } } /// Common implementation of /// /// This class implements through an /// internal /// public class ExtensiblePropertyContainer : IExtensiblePropertyContainer { /// public void AddExtendedPropertyValue( string id, object value ) { lock ( Items ) { object currentValue; if( Items.TryGetValue( id, out currentValue ) ) { if( currentValue != null && value != null && currentValue.GetType( ) != value.GetType( ) ) throw new ArgumentException( " Cannot change type of an extended property once set", nameof( value ) ); } Items[ id ] = value; } } /// public bool TryGetExtendedPropertyValue( string id, out T value ) { value = default( T ); object item; lock ( Items ) { if( !Items.TryGetValue( id, out item ) ) return false; } if( !( item is T ) ) return false; value = ( T )item; return true; } readonly Dictionary Items = new Dictionary(); } } ================================================ FILE: Zelig/Zelig/CompileTime/Llvm.NET/Llvm.NET/Instructions/AddressSpaceCast.cs ================================================ using Llvm.NET.Native; namespace Llvm.NET.Instructions { class AddressSpaceCast : Cast { internal AddressSpaceCast( LLVMValueRef valueRef ) : base( valueRef ) { } } } ================================================ FILE: Zelig/Zelig/CompileTime/Llvm.NET/Llvm.NET/Instructions/Alloca.cs ================================================ using Llvm.NET.Native; namespace Llvm.NET.Instructions { public class Alloca : UnaryInstruction { internal Alloca( LLVMValueRef valueRef ) : base( valueRef ) { } } } ================================================ FILE: Zelig/Zelig/CompileTime/Llvm.NET/Llvm.NET/Instructions/AtomicCmpXchg.cs ================================================ using Llvm.NET.Native; namespace Llvm.NET.Instructions { public class AtomicCmpXchg : Instruction { internal AtomicCmpXchg( LLVMValueRef valueRef ) : base( valueRef ) { } } } ================================================ FILE: Zelig/Zelig/CompileTime/Llvm.NET/Llvm.NET/Instructions/AtomicRMW.cs ================================================ using Llvm.NET.Native; namespace Llvm.NET.Instructions { public class AtomicRMW : Instruction { internal AtomicRMW( LLVMValueRef valueRef ) : base( valueRef ) { } } } ================================================ FILE: Zelig/Zelig/CompileTime/Llvm.NET/Llvm.NET/Instructions/BinaryOperator.cs ================================================ using Llvm.NET.Native; namespace Llvm.NET.Instructions { public class BinaryOperator : Instruction { internal BinaryOperator( LLVMValueRef valueRef ) : base( valueRef ) { } } } ================================================ FILE: Zelig/Zelig/CompileTime/Llvm.NET/Llvm.NET/Instructions/BitCast.cs ================================================ using Llvm.NET.Native; namespace Llvm.NET.Instructions { public class BitCast : Cast { internal BitCast( LLVMValueRef valueRef ) : base( valueRef ) { } } } ================================================ FILE: Zelig/Zelig/CompileTime/Llvm.NET/Llvm.NET/Instructions/Branch.cs ================================================ using Llvm.NET.Native; namespace Llvm.NET.Instructions { public class Branch : Terminator { internal Branch( LLVMValueRef valueRef) : base( valueRef ) { } } } ================================================ FILE: Zelig/Zelig/CompileTime/Llvm.NET/Llvm.NET/Instructions/Call.cs ================================================ using Llvm.NET.Native; using Llvm.NET.Values; namespace Llvm.NET.Instructions { public class CallInstruction : Instruction , IAttributeSetContainer { public AttributeSet Attributes { get { if( TargetFunction == null ) return new AttributeSet(); return new AttributeSet( NativeMethods.GetCallSiteAttributeSet( ValueHandle ) ); } set { NativeMethods.SetCallSiteAttributeSet( ValueHandle, value.NativeAttributeSet ); } } public Function TargetFunction { get { if( Operands.Count < 1 ) return null; // last Operand is the target function return Operands[ Operands.Count - 1 ] as Function; } } public bool IsTailCall { get { return NativeMethods.IsTailCall( ValueHandle ); } set { NativeMethods.SetTailCall( ValueHandle, value ); } } internal CallInstruction( LLVMValueRef valueRef ) : base( valueRef ) { } } } ================================================ FILE: Zelig/Zelig/CompileTime/Llvm.NET/Llvm.NET/Instructions/Cast.cs ================================================ using Llvm.NET.Native; namespace Llvm.NET.Instructions { public class Cast : UnaryInstruction { internal Cast( LLVMValueRef valueRef ) : base( valueRef ) { } } } ================================================ FILE: Zelig/Zelig/CompileTime/Llvm.NET/Llvm.NET/Instructions/CatchPad.cs ================================================ using Llvm.NET.Native; namespace Llvm.NET.Instructions { public class CatchPad : FuncletPad { internal CatchPad( LLVMValueRef valueRef ) : base( valueRef ) { } } } ================================================ FILE: Zelig/Zelig/CompileTime/Llvm.NET/Llvm.NET/Instructions/CatchReturn.cs ================================================ using Llvm.NET.Native; namespace Llvm.NET.Instructions { public class CatchReturn : Terminator { internal CatchReturn( LLVMValueRef valueRef ) : base( valueRef ) { } } } ================================================ FILE: Zelig/Zelig/CompileTime/Llvm.NET/Llvm.NET/Instructions/CatchSwitch.cs ================================================ using Llvm.NET.Native; namespace Llvm.NET.Instructions { public class CatchSwitch : Instruction { internal CatchSwitch( LLVMValueRef valueRef ) : base( valueRef ) { } } } ================================================ FILE: Zelig/Zelig/CompileTime/Llvm.NET/Llvm.NET/Instructions/CleanupPad.cs ================================================ using Llvm.NET.Native; namespace Llvm.NET.Instructions { public class CleanupPad : FuncletPad { internal CleanupPad( LLVMValueRef valueRef ) : base( valueRef ) { } } } ================================================ FILE: Zelig/Zelig/CompileTime/Llvm.NET/Llvm.NET/Instructions/CleanupReturn.cs ================================================ using Llvm.NET.Native; namespace Llvm.NET.Instructions { public class CleanupReturn : Terminator { internal CleanupReturn( LLVMValueRef valueRef ) : base( valueRef ) { } } } ================================================ FILE: Zelig/Zelig/CompileTime/Llvm.NET/Llvm.NET/Instructions/Cmp.cs ================================================ using Llvm.NET.Native; namespace Llvm.NET.Instructions { public class Cmp : Instruction { internal Cmp( LLVMValueRef valueRef ) : base( valueRef ) { } public Predicate Predicate { get { switch( Opcode ) { case OpCode.ICmp: return ( Predicate )NativeMethods.GetICmpPredicate( ValueHandle ); case OpCode.FCmp: return ( Predicate )NativeMethods.GetFCmpPredicate( ValueHandle ); default: return Predicate.BadFcmpPredicate; } } } } } ================================================ FILE: Zelig/Zelig/CompileTime/Llvm.NET/Llvm.NET/Instructions/DebugDeclare.cs ================================================ using Llvm.NET.Native; namespace Llvm.NET.Instructions { public class DebugDeclare : DebugInfoIntrinsic { internal DebugDeclare( LLVMValueRef valueRef ) : base( valueRef ) { } } } ================================================ FILE: Zelig/Zelig/CompileTime/Llvm.NET/Llvm.NET/Instructions/DebugInfoIntrinsic.cs ================================================ using Llvm.NET.Native; namespace Llvm.NET.Instructions { public class DebugInfoIntrinsic : Intrinsic { internal DebugInfoIntrinsic( LLVMValueRef valueRef ) : base( valueRef ) { } } } ================================================ FILE: Zelig/Zelig/CompileTime/Llvm.NET/Llvm.NET/Instructions/ExtractElement.cs ================================================ using Llvm.NET.Native; namespace Llvm.NET.Instructions { public class ExtractElement : Instruction { internal ExtractElement( LLVMValueRef valueRef ) : base( valueRef ) { } } } ================================================ FILE: Zelig/Zelig/CompileTime/Llvm.NET/Llvm.NET/Instructions/ExtractValue.cs ================================================ using Llvm.NET.Native; namespace Llvm.NET.Instructions { public class ExtractValue : UnaryInstruction { internal ExtractValue( LLVMValueRef valueRef ) : base( valueRef ) { } } } ================================================ FILE: Zelig/Zelig/CompileTime/Llvm.NET/Llvm.NET/Instructions/FCmp.cs ================================================ using Llvm.NET.Native; namespace Llvm.NET.Instructions { public class FCmp : Cmp { internal FCmp( LLVMValueRef valueRef ) : base( valueRef ) { } } } ================================================ FILE: Zelig/Zelig/CompileTime/Llvm.NET/Llvm.NET/Instructions/FPExt.cs ================================================ using Llvm.NET.Native; namespace Llvm.NET.Instructions { class FPExt : Cast { internal FPExt( LLVMValueRef valueRef ) : base( valueRef ) { } } } ================================================ FILE: Zelig/Zelig/CompileTime/Llvm.NET/Llvm.NET/Instructions/FPToSI.cs ================================================ using Llvm.NET.Native; namespace Llvm.NET.Instructions { class FPToSI : Cast { internal FPToSI( LLVMValueRef valueRef ) : base( valueRef ) { } } } ================================================ FILE: Zelig/Zelig/CompileTime/Llvm.NET/Llvm.NET/Instructions/FPToUI.cs ================================================ using Llvm.NET.Native; namespace Llvm.NET.Instructions { class FPToUI : Cast { internal FPToUI( LLVMValueRef valueRef ) : base( valueRef ) { } } } ================================================ FILE: Zelig/Zelig/CompileTime/Llvm.NET/Llvm.NET/Instructions/FPTrunc.cs ================================================ using Llvm.NET.Native; namespace Llvm.NET.Instructions { class FPTrunc : Cast { internal FPTrunc( LLVMValueRef valueRef ) : base( valueRef ) { } } } ================================================ FILE: Zelig/Zelig/CompileTime/Llvm.NET/Llvm.NET/Instructions/Fence.cs ================================================ using Llvm.NET.Native; namespace Llvm.NET.Instructions { public class Fence : Instruction { internal Fence( LLVMValueRef valueRef ) : base( valueRef ) { } } } ================================================ FILE: Zelig/Zelig/CompileTime/Llvm.NET/Llvm.NET/Instructions/FuncletPad.cs ================================================ using Llvm.NET.Native; namespace Llvm.NET.Instructions { public class FuncletPad : Instruction { internal FuncletPad( LLVMValueRef valueRef ) : base( valueRef ) { } } } ================================================ FILE: Zelig/Zelig/CompileTime/Llvm.NET/Llvm.NET/Instructions/GetElementPtr.cs ================================================ using Llvm.NET.Native; namespace Llvm.NET.Instructions { public class GetElementPtr : Instruction { internal GetElementPtr( LLVMValueRef valueRef ) : base( valueRef ) { } } } ================================================ FILE: Zelig/Zelig/CompileTime/Llvm.NET/Llvm.NET/Instructions/IndirectBranch.cs ================================================ using Llvm.NET.Native; namespace Llvm.NET.Instructions { public class IndirectBranch : Terminator { internal IndirectBranch( LLVMValueRef valueRef ) : base( valueRef ) { } } } ================================================ FILE: Zelig/Zelig/CompileTime/Llvm.NET/Llvm.NET/Instructions/InsertElement.cs ================================================ using Llvm.NET.Native; namespace Llvm.NET.Instructions { public class InsertElement : Instruction { internal InsertElement( LLVMValueRef valueRef ) : base( valueRef ) { } } } ================================================ FILE: Zelig/Zelig/CompileTime/Llvm.NET/Llvm.NET/Instructions/InsertValue.cs ================================================ using Llvm.NET.Native; namespace Llvm.NET.Instructions { public class InsertValue : Instruction { internal InsertValue( LLVMValueRef valueRef ) : base( valueRef ) { } } } ================================================ FILE: Zelig/Zelig/CompileTime/Llvm.NET/Llvm.NET/Instructions/Instruction.cs ================================================ using System; using Llvm.NET.Native; using Llvm.NET.Values; namespace Llvm.NET.Instructions { /// Exposes an LLVM Instruction public class Instruction : User { /// Block that contains this instruction public BasicBlock ContainingBlock => BasicBlock.FromHandle( NativeMethods.GetInstructionParent( ValueHandle ) ); /// Gets the LLVM opcode for the instruction public OpCode Opcode => ( OpCode )NativeMethods.GetInstructionOpcode( ValueHandle ); /// FLag to indicate if the opcode is for a memory access , , public bool IsMemoryAccess { get { var opCode = Opcode; return opCode == OpCode.Alloca || opCode == OpCode.Load || opCode == OpCode.Store; } } /// Alignment for the instruction /// /// The alignment is always 0 for instructions other than Alloca, Load, and Store /// that deal with memory accesses. Setting the alignment for other instructions /// results in an InvalidOperationException() /// public uint Alignment { get { return IsMemoryAccess ? NativeMethods.GetAlignment( ValueHandle ) : 0; } set { if( !IsMemoryAccess ) throw new InvalidOperationException( "Alignment can only be set for instructions dealing with memory read/write (alloca, load, store)" ); NativeMethods.SetAlignment( ValueHandle, value ); } } internal Instruction( LLVMValueRef valueRef ) : base( valueRef ) { } } /// Provides extension methods to that cannot be achieved as members of the class /// /// Using generic static extension methods allows for fluent coding while retaining the type of the "this" parameter. /// If these were members of the class then the only return type could be /// thus losing the original type and requiring a cast to get back to it, thereby defeating the purpose of the fluent style. /// public static class InstructionExtensions { /// Fluent style extension method to set the for an instruction /// Type of the instruction (usually implicitly inferred from usage) /// Instruction to set the for /// New alignment for the instruction /// To allow fluent style coding this returns the parameter public static T Alignment( this T self, uint value ) where T : Instruction { if( self.IsMemoryAccess ) self.Alignment = value; return self; } /// Fluent style extension method to set the Volatile property of a or instruction /// Type of the instruction (usually implicitly inferred from usage) /// Instruction to set the Volatile property for /// Flag to indicate if the instruction's operation is volatile /// To allow fluent style coding this returns the parameter public static T IsVolatile( this T self, bool value ) where T : Instruction { if( self.IsMemoryAccess ) { // only load and store instructions have the volatile property var loadInst = self as Load; if( loadInst != null ) loadInst.IsVolatile = value; else { var storeinst = self as Store; if( storeinst != null ) storeinst.IsVolatile = value; } } return self; } } } ================================================ FILE: Zelig/Zelig/CompileTime/Llvm.NET/Llvm.NET/Instructions/InstructionBuilder.cs ================================================ using System; using System.Collections.Generic; using System.Diagnostics; using System.Linq; using Llvm.NET.Native; using Llvm.NET.Types; using Llvm.NET.Values; namespace Llvm.NET.Instructions { ///LLVM Instruction builder allowing managed code to generate IR instructions public class InstructionBuilder : IDisposable { /// Creates an for a given context /// Context used for creating instructions public InstructionBuilder( Context context ) { if( context == null ) throw new ArgumentNullException( nameof( context ) ); Context = context; BuilderHandle = NativeMethods.CreateBuilderInContext( context.ContextHandle ); } /// Creates an for a /// Block this builder is initially attached to public InstructionBuilder( BasicBlock block ) : this( block.VerifyArgNotNull( nameof( block ) ).ContainingFunction.ParentModule.Context ) { PositionAtEnd( block ); } /// Gets the context this builder is creating instructions for public Context Context { get; } /// Positions the builder at the end of a given /// public void PositionAtEnd( BasicBlock basicBlock ) { if( basicBlock == null ) throw new ArgumentNullException( nameof( basicBlock ) ); NativeMethods.PositionBuilderAtEnd( BuilderHandle, basicBlock.BlockHandle ); } /// Positions the builder before the given instruction /// Instruction to position the builder before /// This method will position the builder to add new instructions /// immediately before the specified instruction. /// It is important to keep in mind that this can change the /// block this builder is targeting. That is, /// is not required to come from the same block the instruction builder is /// currently referencing. /// [System.Diagnostics.CodeAnalysis.SuppressMessage( "Microsoft.Design", "CA1011:ConsiderPassingBaseTypesAsParameters", Justification = "Specific type required by interop call" )] public void PositionBefore( Instruction instr ) { if( instr == null ) throw new ArgumentNullException( nameof( instr ) ); NativeMethods.PositionBuilderBefore( BuilderHandle, instr.ValueHandle ); } public Value FNeg( Value value ) => BuildUnaryOp( NativeMethods.BuildFNeg, value ); public Value FAdd( Value lhs, Value rhs ) => BuildBinOp( NativeMethods.BuildFAdd, lhs, rhs ); public Value FSub( Value lhs, Value rhs ) => BuildBinOp( NativeMethods.BuildFSub, lhs, rhs ); public Value FMul( Value lhs, Value rhs ) => BuildBinOp( NativeMethods.BuildFMul, lhs, rhs ); public Value FDiv( Value lhs, Value rhs ) => BuildBinOp( NativeMethods.BuildFDiv, lhs, rhs ); public Value FRem( Value lhs, Value rhs ) => BuildBinOp( NativeMethods.BuildFRem, lhs, rhs ); public Value Neg( Value value ) => BuildUnaryOp( NativeMethods.BuildNeg, value ); public Value Not( Value value ) => BuildUnaryOp( NativeMethods.BuildNot, value ); public Value Add( Value lhs, Value rhs ) => BuildBinOp( NativeMethods.BuildAdd, lhs, rhs ); public Value And( Value lhs, Value rhs ) => BuildBinOp( NativeMethods.BuildAnd, lhs, rhs ); public Value Sub( Value lhs, Value rhs ) => BuildBinOp( NativeMethods.BuildSub, lhs, rhs ); public Value Mul( Value lhs, Value rhs ) => BuildBinOp( NativeMethods.BuildMul, lhs, rhs ); public Value ShiftLeft( Value lhs, Value rhs ) => BuildBinOp( NativeMethods.BuildShl, lhs, rhs ); public Value ArithmeticShiftRight( Value lhs, Value rhs ) => BuildBinOp( NativeMethods.BuildAShr, lhs, rhs ); public Value LogicalShiftRight( Value lhs, Value rhs ) => BuildBinOp( NativeMethods.BuildLShr, lhs, rhs ); public Value UDiv( Value lhs, Value rhs ) => BuildBinOp( NativeMethods.BuildUDiv, lhs, rhs ); public Value SDiv( Value lhs, Value rhs ) => BuildBinOp( NativeMethods.BuildUDiv, lhs, rhs ); public Value URem( Value lhs, Value rhs ) => BuildBinOp( NativeMethods.BuildURem, lhs, rhs ); public Value SRem( Value lhs, Value rhs ) => BuildBinOp( NativeMethods.BuildSRem, lhs, rhs ); public Value Xor( Value lhs, Value rhs ) => BuildBinOp( NativeMethods.BuildXor, lhs, rhs ); public Value Or( Value lhs, Value rhs ) => BuildBinOp( NativeMethods.BuildOr, lhs, rhs ); public Alloca Alloca( ITypeRef typeRef ) { var handle = NativeMethods.BuildAlloca( BuilderHandle, typeRef.GetTypeRef( ), string.Empty ); return Value.FromHandle( handle ); } [System.Diagnostics.CodeAnalysis.SuppressMessage( "Microsoft.Design", "CA1011:ConsiderPassingBaseTypesAsParameters", Justification = "Specific type required by interop call" )] public Alloca Alloca( ITypeRef typeRef, ConstantInt elements ) { if( typeRef == null ) throw new ArgumentNullException( nameof( typeRef ) ); if( elements == null ) throw new ArgumentNullException( nameof( elements ) ); var instHandle = NativeMethods.BuildArrayAlloca( BuilderHandle, typeRef.GetTypeRef( ), elements.ValueHandle, string.Empty ); return Value.FromHandle( instHandle ); } public ReturnInstruction Return( ) => Value.FromHandle( NativeMethods.BuildRetVoid( BuilderHandle ) ); public ReturnInstruction Return( Value value ) { if( value == null ) throw new ArgumentNullException( nameof( value ) ); var handle = NativeMethods.BuildRet( BuilderHandle, value.ValueHandle ); return Value.FromHandle( handle ); } public CallInstruction Call( Value func, params Value[ ] args ) => Call( func, ( IReadOnlyList )args ); public CallInstruction Call( Value func, IReadOnlyList args ) { LLVMValueRef hCall = BuildCall( func, args ); var retVal = Value.FromHandle( hCall ); return retVal; } public Invoke Invoke( Value func, IReadOnlyList args, BasicBlock then, BasicBlock catchBlock ) { if( then == null ) throw new ArgumentNullException( nameof( then ) ); if( catchBlock == null ) throw new ArgumentNullException( nameof( catchBlock ) ); ValidateCallArgs( func, args ); LLVMValueRef[] llvmArgs = args.Select( v => v.ValueHandle ).ToArray(); int argCount = llvmArgs.Length; // Must always provide at least one element for successful marshaling/interop, but tell LLVM there are none. if( argCount == 0 ) { llvmArgs = new LLVMValueRef[1]; } LLVMValueRef invoke = NativeMethods.BuildInvoke( BuilderHandle , func.ValueHandle , out llvmArgs[0] , (uint)argCount , then.BlockHandle , catchBlock.BlockHandle , string.Empty ); return Value.FromHandle( invoke ); } public LandingPad LandingPad( ITypeRef resultType ) { LLVMValueRef landingPad = NativeMethods.BuildLandingPad( BuilderHandle , resultType.GetTypeRef() , LLVMValueRef.Zero // personality function no longer part of instruction , 0 , string.Empty ); return Value.FromHandle( landingPad ); } public ResumeInstruction Resume( Value exception ) { if( exception == null ) throw new ArgumentNullException( nameof( exception ) ); LLVMValueRef resume = NativeMethods.BuildResume( BuilderHandle, exception.ValueHandle ); return Value.FromHandle( resume ); } /// Builds an LLVM Store instruction /// Value to store in destination /// value for the destination /// instruction /// /// Since store targets memory the type of /// must be an . Furthermore, the element type of /// the pointer must match the type of . Otherwise, /// an is thrown. /// public Store Store( Value value, Value destination ) { if( value == null ) throw new ArgumentNullException( nameof( value ) ); if( destination == null ) throw new ArgumentNullException( nameof( destination ) ); var ptrType = destination.NativeType as IPointerType; if( ptrType == null ) throw new ArgumentException( "Expected pointer value", nameof( destination ) ); if( !ptrType.ElementType.Equals( value.NativeType ) || ( value.NativeType.Kind == TypeKind.Integer && value.NativeType.IntegerBitWidth != ptrType.ElementType.IntegerBitWidth ) ) { throw new ArgumentException( string.Format( IncompatibleTypeMsgFmt, ptrType.ElementType, value.NativeType ) ); } return Value.FromHandle( NativeMethods.BuildStore( BuilderHandle, value.ValueHandle, destination.ValueHandle ) ); } public Load Load( Value sourcePtr ) { if( sourcePtr == null ) throw new ArgumentNullException( nameof( sourcePtr ) ); var handle = NativeMethods.BuildLoad( BuilderHandle, sourcePtr.ValueHandle, string.Empty ); return Value.FromHandle( handle ); } public Value AtomicXchg( Value ptr, Value val ) => BuildAtomicBinOp( LLVMAtomicRMWBinOp.LLVMAtomicRMWBinOpXchg, ptr, val ); public Value AtomicAdd( Value ptr, Value val ) => BuildAtomicBinOp( LLVMAtomicRMWBinOp.LLVMAtomicRMWBinOpAdd, ptr, val ); public Value AtomicSub( Value ptr, Value val ) => BuildAtomicBinOp( LLVMAtomicRMWBinOp.LLVMAtomicRMWBinOpSub, ptr, val ); public Value AtomicAnd( Value ptr, Value val ) => BuildAtomicBinOp( LLVMAtomicRMWBinOp.LLVMAtomicRMWBinOpAnd, ptr, val ); public Value AtomicNand( Value ptr, Value val ) => BuildAtomicBinOp( LLVMAtomicRMWBinOp.LLVMAtomicRMWBinOpNand, ptr, val ); public Value AtomicOr( Value ptr, Value val ) => BuildAtomicBinOp( LLVMAtomicRMWBinOp.LLVMAtomicRMWBinOpOr, ptr, val ); public Value AtomicXor( Value ptr, Value val ) => BuildAtomicBinOp( LLVMAtomicRMWBinOp.LLVMAtomicRMWBinOpXor, ptr, val ); public Value AtomicMax( Value ptr, Value val ) => BuildAtomicBinOp( LLVMAtomicRMWBinOp.LLVMAtomicRMWBinOpMax, ptr, val ); public Value AtomicMin( Value ptr, Value val ) => BuildAtomicBinOp( LLVMAtomicRMWBinOp.LLVMAtomicRMWBinOpMin, ptr, val ); public Value AtomicUMax( Value ptr, Value val ) => BuildAtomicBinOp( LLVMAtomicRMWBinOp.LLVMAtomicRMWBinOpUMax, ptr, val ); public Value AtomicUMin( Value ptr, Value val ) => BuildAtomicBinOp( LLVMAtomicRMWBinOp.LLVMAtomicRMWBinOpUMin, ptr, val ); public Value AtomicCmpXchg( Value ptr, Value cmp, Value value ) { if( ptr == null ) throw new ArgumentNullException( nameof( ptr ) ); if( cmp == null ) throw new ArgumentNullException( nameof( cmp ) ); if( value == null ) throw new ArgumentNullException( nameof( value ) ); var ptrType = ptr.NativeType as IPointerType; if( ptrType == null ) throw new ArgumentException( "Expected pointer value", nameof( ptr ) ); if( ptrType.ElementType != cmp.NativeType ) throw new ArgumentException( string.Format( IncompatibleTypeMsgFmt, ptrType.ElementType, cmp.NativeType ) ); if( ptrType.ElementType != value.NativeType ) throw new ArgumentException( string.Format( IncompatibleTypeMsgFmt, ptrType.ElementType, value.NativeType ) ); var handle = NativeMethods.BuildAtomicCmpXchg( BuilderHandle , ptr.ValueHandle , cmp.ValueHandle , value.ValueHandle , LLVMAtomicOrdering.LLVMAtomicOrderingSequentiallyConsistent , LLVMAtomicOrdering.LLVMAtomicOrderingSequentiallyConsistent , false ); return Value.FromHandle( handle ); } /// Creates a that accesses an element (field) of a structure /// pointer to the structure to get an element from /// element index /// /// for the member access. This is a /// as LLVM may optimize the expression to a if it /// can so the actual type of the result may be /// or . /// Note that must be a pointer to a structure /// or an exception is thrown. /// public Value GetStructElementPointer( Value pointer, uint index ) { if( pointer == null ) throw new ArgumentNullException( nameof( pointer ) ); var ptrType = pointer.NativeType as IPointerType; if( ptrType == null ) throw new ArgumentException( "Pointer value expected", nameof( pointer ) ); var elementStructType = ptrType.ElementType as IStructType; if( elementStructType == null ) throw new ArgumentException( "Pointer to a structure expected", nameof( pointer ) ); if( !elementStructType.IsSized && index > 0 ) throw new ArgumentException( "Cannot get element of unsized/opaque structures" ); var handle = NativeMethods.BuildStructGEP( BuilderHandle, pointer.ValueHandle, index, string.Empty ); return Value.FromHandle( handle ); } /// Creates a that accesses an element of a type referenced by a pointer /// pointer to get an element from /// additional indices for computing the resulting pointer /// /// for the member access. This is a /// as LLVM may optimize the expression to a if it /// can so the actual type of the result may be /// or . /// Note that must be a pointer to a structure /// or an exception is thrown. /// /// /// For details on GetElementPointer (GEP) see http://llvm.org/docs/GetElementPtr.html. The /// basic gist is that the GEP instruction does not access memory, it only computes a pointer /// offset from a base. A common confusion is around the first index and what it means. For C /// and C++ programmers an expression like pFoo->bar seems to only have a single offset or /// index. However, that is only syntactic sugar where the compiler implicitly hides the first /// index. That is, there is no difference between pFoo[0].bar and pFoo->bar except that the /// former makes the first index explicit. In order to properly compute the offset for a given /// element in an aggregate type LLVM requires an explicit first index even if it is zero. /// public Value GetElementPtr( Value pointer, IEnumerable args ) { var llvmArgs = GetValidatedGEPArgs( pointer, args ); var handle = NativeMethods.BuildGEP( BuilderHandle , pointer.ValueHandle , out llvmArgs[ 0 ] , ( uint )llvmArgs.Length , string.Empty ); return Value.FromHandle( handle ); } /// Creates a that accesses an element of a type referenced by a pointer /// pointer to get an element from /// additional indices for computing the resulting pointer /// /// for the member access. This is a /// as LLVM may optimize the expression to a if it /// can so the actual type of the result may be /// or . /// Note that must be a pointer to a structure /// or an exception is thrown. /// /// /// For details on GetElementPointer (GEP) see http://llvm.org/docs/GetElementPtr.html. The /// basic gist is that the GEP instruction does not access memory, it only computes a pointer /// offset from a base. A common confusion is around the first index and what it means. For C /// and C++ programmers an expression like pFoo->bar seems to only have a single offset or /// index. However that is only syntactic sugar where the compiler implicitly hides the first /// index. That is, there is no difference between pFoo[0].bar and pFoo->bar except that the /// former makes the first index explicit. In order to properly compute the offset for a given /// element in an aggregate type LLVM requires an explicit first index even if it is zero. /// public Value GetElementPtrInBounds( Value pointer, params Value[ ] args ) => GetElementPtrInBounds( pointer, ( IEnumerable )args ); /// Creates a that accesses an element of a type referenced by a pointer /// pointer to get an element from /// additional indices for computing the resulting pointer /// /// for the member access. This is a /// as LLVM may optimize the expression to a if it /// can so the actual type of the result may be /// or . /// Note that must be a pointer to a structure /// or an exception is thrown. /// /// /// For details on GetElementPointer (GEP) see http://llvm.org/docs/GetElementPtr.html. The /// basic gist is that the GEP instruction does not access memory, it only computes a pointer /// offset from a base. A common confusion is around the first index and what it means. For C /// and C++ programmers an expression like pFoo->bar seems to only have a single offset or /// index. However, that is only syntactic sugar where the compiler implicitly hides the first /// index. That is, there is no difference between pFoo[0].bar and pFoo->bar except that the /// former makes the first index explicit. In order to properly compute the offset for a given /// element in an aggregate type LLVM requires an explicit first index even if it is zero. /// public Value GetElementPtrInBounds( Value pointer, IEnumerable args ) { var llvmArgs = GetValidatedGEPArgs( pointer, args ); var hRetVal = NativeMethods.BuildInBoundsGEP( BuilderHandle , pointer.ValueHandle , out llvmArgs[ 0 ] , ( uint )llvmArgs.Length , string.Empty ); return Value.FromHandle( hRetVal ); } /// Creates a that accesses an element of a type referenced by a pointer /// pointer to get an element from /// additional indices for computing the resulting pointer /// /// for the member access. This is a User as LLVM may /// optimize the expression to a if it /// can so the actual type of the result may be /// or . /// Note that must be a pointer to a structure /// or an exception is thrown. /// /// /// For details on GetElementPointer (GEP) see http://llvm.org/docs/GetElementPtr.html. The /// basic gist is that the GEP instruction does not access memory, it only computes a pointer /// offset from a base. A common confusion is around the first index and what it means. For C /// and C++ programmers an expression like pFoo->bar seems to only have a single offset or /// index. However that is only syntactic sugar where the compiler implicitly hides the first /// index. That is, there is no difference between pFoo[0].bar and pFoo->bar except that the /// former makes the first index explicit. LLVM requires an explicit first index even if it is /// zero, in order to properly compute the offset for a given element in an aggregate type. /// [System.Diagnostics.CodeAnalysis.SuppressMessage( "Microsoft.Performance", "CA1822:MarkMembersAsStatic" )] public Value ConstGetElementPtrInBounds( Value pointer, params Value[ ] args ) { var llvmArgs = GetValidatedGEPArgs( pointer, args ); var handle = NativeMethods.ConstInBoundsGEP( pointer.ValueHandle, out llvmArgs[ 0 ], ( uint )llvmArgs.Length ); return Value.FromHandle( handle ); } /// Builds a cast from an integer to a pointer /// Integer value to cast /// pointer type to return /// Resulting value from the cast /// /// The actual type of value returned depends on /// and is either a or an /// instruction. Conversion to a constant expression is performed whenever possible. /// [System.Diagnostics.CodeAnalysis.SuppressMessage( "Microsoft.Design", "CA1011:ConsiderPassingBaseTypesAsParameters", Justification = "Specific type required by interop call" )] public Value IntToPointer( Value intValue, IPointerType ptrType ) { if( intValue == null ) throw new ArgumentNullException( nameof( intValue ) ); if( ptrType == null ) throw new ArgumentNullException( nameof( ptrType ) ); if( intValue is Constant ) return Value.FromHandle( NativeMethods.ConstIntToPtr( intValue.ValueHandle, ptrType.GetTypeRef( ) ) ); var handle = NativeMethods.BuildIntToPtr( BuilderHandle, intValue.ValueHandle, ptrType.GetTypeRef( ), string.Empty ); return Value.FromHandle( handle ); } /// Builds a cast from a pointer to an integer type /// Pointer value to cast /// Integer type to return /// Resulting value from the cast /// /// The actual type of value returned depends on /// and is either a or a /// instruction. Conversion to a constant expression is performed whenever possible. /// public Value PointerToInt( Value ptrValue, ITypeRef intType ) { if( ptrValue == null ) throw new ArgumentNullException( nameof( ptrValue ) ); if( intType == null ) throw new ArgumentNullException( nameof( intType ) ); if( ptrValue.NativeType.Kind != TypeKind.Pointer ) throw new ArgumentException( "Expected a pointer value", nameof( ptrValue ) ); if( intType.Kind != TypeKind.Integer ) throw new ArgumentException( "Expected pointer to integral type", nameof( intType ) ); if( ptrValue is Constant ) return Value.FromHandle( NativeMethods.ConstPtrToInt( ptrValue.ValueHandle, intType.GetTypeRef( ) ) ); var handle = NativeMethods.BuildPtrToInt( BuilderHandle, ptrValue.ValueHandle, intType.GetTypeRef( ), string.Empty ); return Value.FromHandle( handle ); } public Branch Branch( BasicBlock target ) => Value.FromHandle( NativeMethods.BuildBr( BuilderHandle, target.VerifyArgNotNull( nameof( target ) ).BlockHandle ) ); public Branch Branch( Value ifCondition, BasicBlock thenTarget, BasicBlock elseTarget ) { if( ifCondition == null ) throw new ArgumentNullException( nameof( ifCondition ) ); if( thenTarget == null ) throw new ArgumentNullException( nameof( thenTarget ) ); if( elseTarget == null ) throw new ArgumentNullException( nameof( elseTarget ) ); var handle = NativeMethods.BuildCondBr( BuilderHandle , ifCondition.ValueHandle , thenTarget.BlockHandle , elseTarget.BlockHandle ); return Value.FromHandle( handle ); } public Unreachable Unreachable( ) => Value.FromHandle( NativeMethods.BuildUnreachable( BuilderHandle ) ); /// Builds an Integer compare instruction /// Integer predicate for the comparison /// Left hand side of the comparison /// Right hand side of the comparison /// Comparison instruction public Value Compare( IntPredicate predicate, Value lhs, Value rhs ) { if( lhs == null ) throw new ArgumentNullException( nameof( lhs ) ); if( rhs == null ) throw new ArgumentNullException( nameof( rhs ) ); if( !lhs.NativeType.IsInteger && !lhs.NativeType.IsPointer ) throw new ArgumentException( "Expecting an integer or pointer type", nameof( lhs ) ); if( !rhs.NativeType.IsInteger && !lhs.NativeType.IsPointer ) throw new ArgumentException( "Expecting an integer or pointer type", nameof( rhs ) ); var handle = NativeMethods.BuildICmp( BuilderHandle, ( LLVMIntPredicate )predicate, lhs.ValueHandle, rhs.ValueHandle, string.Empty ); return Value.FromHandle( handle ); } /// Builds a Floating point compare instruction /// predicate for the comparison /// Left hand side of the comparison /// Right hand side of the comparison /// Comparison instruction public Value Compare( RealPredicate predicate, Value lhs, Value rhs ) { if( lhs == null ) throw new ArgumentNullException( nameof( lhs ) ); if( rhs == null ) throw new ArgumentNullException( nameof( rhs ) ); if( !lhs.NativeType.IsFloatingPoint ) throw new ArgumentException( "Expecting an integer type", nameof( lhs ) ); if( !rhs.NativeType.IsFloatingPoint ) throw new ArgumentException( "Expecting an integer type", nameof( rhs ) ); var handle = NativeMethods.BuildFCmp( BuilderHandle , ( LLVMRealPredicate )predicate , lhs.ValueHandle , rhs.ValueHandle , string.Empty ); return Value.FromHandle( handle ); } /// Builds a compare instruction /// predicate for the comparison /// Left hand side of the comparison /// Right hand side of the comparison /// Comparison instruction public Value Compare( Predicate predicate, Value lhs, Value rhs ) { if( predicate <= Predicate.LastFcmpPredicate ) return Compare( ( RealPredicate )predicate, lhs, rhs ); if( predicate >= Predicate.FirstIcmpPredicate && predicate <= Predicate.LastIcmpPredicate ) return Compare( ( IntPredicate )predicate, lhs, rhs ); throw new ArgumentOutOfRangeException( nameof( predicate ), $"'{predicate}' is not a valid value for a compare predicate" ); } public Value ZeroExtendOrBitCast( Value valueRef, ITypeRef targetType ) { if( valueRef == null ) throw new ArgumentNullException( nameof( valueRef ) ); if( targetType == null ) throw new ArgumentNullException( nameof( targetType ) ); // short circuit cast to same type as it won't be a Constant or a BitCast if( valueRef.NativeType == targetType ) return valueRef; LLVMValueRef handle; if( valueRef is Constant ) handle = NativeMethods.ConstZExtOrBitCast( valueRef.ValueHandle, targetType.GetTypeRef( ) ); else handle = NativeMethods.BuildZExtOrBitCast( BuilderHandle, valueRef.ValueHandle, targetType.GetTypeRef( ), string.Empty ); return Value.FromHandle( handle ); } public Value SignExtendOrBitCast( Value valueRef, ITypeRef targetType ) { if( valueRef == null ) throw new ArgumentNullException( nameof( valueRef ) ); if( targetType == null ) throw new ArgumentNullException( nameof( targetType ) ); // short circuit cast to same type as it won't be a Constant or a BitCast if( valueRef.NativeType == targetType ) return valueRef; LLVMValueRef handle; if( valueRef is Constant ) handle = NativeMethods.ConstSExtOrBitCast( valueRef.ValueHandle, targetType.GetTypeRef( ) ); else handle = NativeMethods.BuildSExtOrBitCast( BuilderHandle, valueRef.ValueHandle, targetType.GetTypeRef( ), string.Empty ); return Value.FromHandle( handle ); } public Value TruncOrBitCast( Value valueRef, ITypeRef targetType ) { if( valueRef == null ) throw new ArgumentNullException( nameof( valueRef ) ); if( targetType == null ) throw new ArgumentNullException( nameof( targetType ) ); // short circuit cast to same type as it won't be a Constant or a BitCast if( valueRef.NativeType == targetType ) return valueRef; LLVMValueRef handle; if( valueRef is Constant ) handle = NativeMethods.ConstTruncOrBitCast( valueRef.ValueHandle, targetType.GetTypeRef( ) ); else handle = NativeMethods.BuildTruncOrBitCast( BuilderHandle, valueRef.ValueHandle, targetType.GetTypeRef( ), string.Empty ); return Value.FromHandle( handle ); } public Value ZeroExtend( Value valueRef, ITypeRef targetType ) { if( valueRef == null ) throw new ArgumentNullException( nameof( valueRef ) ); if( targetType == null ) throw new ArgumentNullException( nameof( targetType ) ); LLVMValueRef handle; if( valueRef is Constant ) handle = NativeMethods.ConstZExt( valueRef.ValueHandle, targetType.GetTypeRef( ) ); else handle = NativeMethods.BuildZExt( BuilderHandle, valueRef.ValueHandle, targetType.GetTypeRef( ), string.Empty ); return Value.FromHandle( handle ); } public Value SignExtend( Value valueRef, ITypeRef targetType ) { if( valueRef == null ) throw new ArgumentNullException( nameof( valueRef ) ); if( targetType == null ) throw new ArgumentNullException( nameof( targetType ) ); if( valueRef is Constant ) return Value.FromHandle( NativeMethods.ConstSExt( valueRef.ValueHandle, targetType.GetTypeRef( ) ) ); var retValueRef = NativeMethods.BuildSExt( BuilderHandle, valueRef.ValueHandle, targetType.GetTypeRef( ), string.Empty ); return Value.FromHandle( retValueRef ); } public Value BitCast( Value valueRef, ITypeRef targetType ) { if( valueRef == null ) throw new ArgumentNullException( nameof( valueRef ) ); if( targetType == null ) throw new ArgumentNullException( nameof( targetType ) ); // short circuit cast to same type as it won't be a Constant or a BitCast if( valueRef.NativeType == targetType ) return valueRef; LLVMValueRef handle; if( valueRef is Constant ) handle = NativeMethods.ConstBitCast( valueRef.ValueHandle, targetType.GetTypeRef( ) ); else handle = NativeMethods.BuildBitCast( BuilderHandle, valueRef.ValueHandle, targetType.GetTypeRef( ), string.Empty ); return Value.FromHandle( handle ); } public Value IntCast( Value valueRef, ITypeRef targetType, bool isSigned ) { if( valueRef == null ) throw new ArgumentNullException( nameof( valueRef ) ); if( targetType == null ) throw new ArgumentNullException( nameof( targetType ) ); LLVMValueRef handle; if( valueRef is Constant ) handle = NativeMethods.ConstIntCast( valueRef.ValueHandle, targetType.GetTypeRef( ), isSigned ); else handle = NativeMethods.BuildIntCast( BuilderHandle, valueRef.ValueHandle, targetType.GetTypeRef( ), string.Empty ); return Value.FromHandle( handle ); } public Value Trunc( Value valueRef, ITypeRef targetType ) { if( valueRef == null ) throw new ArgumentNullException( nameof( valueRef ) ); if( targetType == null ) throw new ArgumentNullException( nameof( targetType ) ); if( valueRef is Constant ) return Value.FromHandle( NativeMethods.ConstTrunc( valueRef.ValueHandle, targetType.GetTypeRef( ) ) ); return Value.FromHandle( NativeMethods.BuildTrunc( BuilderHandle, valueRef.ValueHandle, targetType.GetTypeRef( ), string.Empty ) ); } public Value SIToFPCast( Value valueRef, ITypeRef targetType ) { if( valueRef == null ) throw new ArgumentNullException( nameof( valueRef ) ); if( targetType == null ) throw new ArgumentNullException( nameof( targetType ) ); LLVMValueRef handle; if( valueRef is Constant ) handle = NativeMethods.ConstSIToFP( valueRef.ValueHandle, targetType.GetTypeRef( ) ); else handle = NativeMethods.BuildSIToFP( BuilderHandle, valueRef.ValueHandle, targetType.GetTypeRef( ), string.Empty ); return Value.FromHandle( handle ); } public Value UIToFPCast( Value valueRef, ITypeRef targetType ) { if( valueRef == null ) throw new ArgumentNullException( nameof( valueRef ) ); if( targetType == null ) throw new ArgumentNullException( nameof( targetType ) ); LLVMValueRef handle; if( valueRef is Constant ) handle = NativeMethods.ConstUIToFP( valueRef.ValueHandle, targetType.GetTypeRef( ) ); else handle = NativeMethods.BuildUIToFP( BuilderHandle, valueRef.ValueHandle, targetType.GetTypeRef( ), string.Empty ); return Value.FromHandle( handle ); } public Value FPToUICast( Value valueRef, ITypeRef targetType ) { if( valueRef == null ) throw new ArgumentNullException( nameof( valueRef ) ); if( targetType == null ) throw new ArgumentNullException( nameof( targetType ) ); LLVMValueRef handle; if( valueRef is Constant ) handle = NativeMethods.ConstFPToUI( valueRef.ValueHandle, targetType.GetTypeRef( ) ); else handle = NativeMethods.BuildFPToUI( BuilderHandle, valueRef.ValueHandle, targetType.GetTypeRef( ), string.Empty ); return Value.FromHandle( handle ); } public Value FPToSICast( Value valueRef, ITypeRef targetType ) { if( valueRef == null ) throw new ArgumentNullException( nameof( valueRef ) ); if( targetType == null ) throw new ArgumentNullException( nameof( targetType ) ); LLVMValueRef handle; if( valueRef is Constant ) handle = NativeMethods.ConstFPToSI( valueRef.ValueHandle, targetType.GetTypeRef( ) ); else handle = NativeMethods.BuildFPToSI( BuilderHandle, valueRef.ValueHandle, targetType.GetTypeRef( ), string.Empty ); return Value.FromHandle( handle ); } public Value FPExt( Value valueRef, ITypeRef toType ) { if( valueRef == null ) throw new ArgumentNullException( nameof( valueRef ) ); if( toType == null ) throw new ArgumentNullException( nameof( toType ) ); LLVMValueRef handle; if( valueRef is Constant ) handle = NativeMethods.ConstFPExt( valueRef.ValueHandle, toType.GetTypeRef( ) ); else handle = NativeMethods.BuildFPExt( BuilderHandle, valueRef.ValueHandle, toType.GetTypeRef( ), string.Empty ); return Value.FromHandle( handle ); } public Value FPTrunc( Value valueRef, ITypeRef toType ) { if( valueRef == null ) throw new ArgumentNullException( nameof( valueRef ) ); if( toType == null ) throw new ArgumentNullException( nameof( toType ) ); LLVMValueRef handle; if( valueRef is Constant ) handle = NativeMethods.ConstFPTrunc( valueRef.ValueHandle, toType.GetTypeRef( ) ); else handle = NativeMethods.BuildFPTrunc( BuilderHandle, valueRef.ValueHandle, toType.GetTypeRef( ), string.Empty ); return Value.FromHandle( handle ); } public PhiNode PhiNode( ITypeRef resultType ) { var handle = NativeMethods.BuildPhi( BuilderHandle, resultType.GetTypeRef( ), string.Empty ); return Value.FromHandle( handle ); } public Value ExtractValue( Value instance, uint index ) { if( instance == null ) throw new ArgumentNullException( nameof( instance ) ); var handle = NativeMethods.BuildExtractValue( BuilderHandle, instance.ValueHandle, index, string.Empty ); return Value.FromHandle( handle ); } public Instructions.Switch Switch( Value value, BasicBlock defaultCase, uint numCases ) { if( value == null ) throw new ArgumentNullException( nameof( value ) ); if( defaultCase == null ) throw new ArgumentNullException( nameof( defaultCase ) ); var handle = NativeMethods.BuildSwitch( BuilderHandle, value.ValueHandle, defaultCase.BlockHandle, numCases ); return Value.FromHandle( handle ); } public Value DoNothing( NativeModule module ) { if( module == null ) throw new ArgumentNullException( nameof( module ) ); var func = module.GetFunction( Intrinsic.DoNothingName ); if( func == null ) { var ctx = module.Context; var signature = ctx.GetFunctionType( ctx.VoidType ); func = module.AddFunction( Intrinsic.DoNothingName, signature ); } var hCall = BuildCall( func ); return Value.FromHandle( hCall ); } public Value DebugTrap( NativeModule module ) { if( module == null ) throw new ArgumentNullException( nameof( module ) ); var func = module.GetFunction( Intrinsic.DebugTrapName ); if( func == null ) { var ctx = module.Context; var signature = ctx.GetFunctionType( ctx.VoidType ); func = module.AddFunction( Intrinsic.DebugTrapName, signature ); } LLVMValueRef args; var hCall = NativeMethods.BuildCall( BuilderHandle, func.ValueHandle, out args, 0U, string.Empty ); return Value.FromHandle( hCall ); } /// Builds a memcpy intrinsic call /// Module to add the declaration of the intrinsic to if it doesn't already exist /// Destination pointer of the memcpy /// Source pointer of the memcpy /// length of the data to copy /// Alignment of the data for the copy /// Flag to indicate if the copy involves volatile data such as physical registers /// call for the memcpy /// /// LLVM has many overloaded variants of the memcpy intrinsic, this implementation will deduce the types from /// the provided values and generate a more specific call without the need to provide overloaded forms of this /// method and otherwise complicating the calling code. /// [System.Diagnostics.CodeAnalysis.SuppressMessage( "Microsoft.Naming", "CA2204:Literals should be spelled correctly", MessageId = "MemCopy" )] public Value MemCpy( NativeModule module, Value destination, Value source, Value len, Int32 align, bool isVolatile ) { if( module == null ) throw new ArgumentNullException( nameof( module ) ); if( destination == null ) throw new ArgumentNullException( nameof( destination ) ); if( source == null ) throw new ArgumentNullException( nameof( source ) ); if( len == null ) throw new ArgumentNullException( nameof( len ) ); if( destination == source ) throw new InvalidOperationException( "Source and destination arguments for MemCopy are the same value" ); var dstPtrType = destination.NativeType as IPointerType; if( dstPtrType == null ) throw new ArgumentException( "Pointer type expected", nameof( destination ) ); var srcPtrType = source.NativeType as IPointerType; if( srcPtrType == null ) throw new ArgumentException( "Pointer type expected", nameof( source ) ); if( !len.NativeType.IsInteger ) throw new ArgumentException( "Integer type expected", nameof( len ) ); if( Context != module.Context ) throw new ArgumentException( "Module and instruction builder must come from the same context" ); if( !dstPtrType.ElementType.IsInteger ) { dstPtrType = module.Context.Int8Type.CreatePointerType( ); destination = BitCast( destination, dstPtrType ); } if( !srcPtrType.ElementType.IsInteger ) { srcPtrType = module.Context.Int8Type.CreatePointerType( ); source = BitCast( source, srcPtrType ); } // find the name of the appropriate overloaded form var intrinsicName = Instructions.MemCpy.GetIntrinsicNameForArgs( dstPtrType, srcPtrType, len.NativeType ); var func = module.GetFunction( intrinsicName ); if( func == null ) { var signature = module.Context.GetFunctionType( module.Context.VoidType // return , dstPtrType , srcPtrType , len.NativeType , module.Context.Int32Type // alignment , module.Context.BoolType // isVolatile ); func = module.AddFunction( intrinsicName, signature ); } var call = BuildCall( func , destination , source , len , module.Context.CreateConstant( align ) , module.Context.CreateConstant( isVolatile ) ); return Value.FromHandle( call ); } /// Builds a memmov intrinsic call /// Module to add the declaration of the intrinsic to if it doesn't already exist /// Destination pointer of the memcpy /// Source pointer of the memcpy /// length of the data to copy /// Alignment of the data for the copy /// Flag to indicate if the copy involves volatile data such as physical registers /// call for the memcpy /// /// LLVM has many overloaded variants of the memmov intrinsic, this implementation currently assumes the /// single form defined by , which matches the classic "C" style memmov /// function. However future implementations should be able to deduce the types from the provided values /// and generate a more specific call without changing any caller code (as is done with . /// public Value MemMove( NativeModule module, Value destination, Value source, Value len, Int32 align, bool isVolatile ) { if( module == null ) throw new ArgumentNullException( nameof( module ) ); if( destination == null ) throw new ArgumentNullException( nameof( destination ) ); if( source == null ) throw new ArgumentNullException( nameof( source ) ); if( len == null ) throw new ArgumentNullException( nameof( len ) ); //TODO: make this auto select the LLVM intrinsic signature like memcpy... if( !destination.NativeType.IsPointer ) throw new ArgumentException( "Pointer type expected", nameof( destination ) ); if( !source.NativeType.IsPointer ) throw new ArgumentException( "Pointer type expected", nameof( source ) ); if( !len.NativeType.IsInteger ) throw new ArgumentException( "Integer type expected", nameof( len ) ); var ctx = module.Context; destination = BitCast( destination, ctx.Int8Type.CreatePointerType( ) ); source = BitCast( source, ctx.Int8Type.CreatePointerType( ) ); var func = module.GetFunction( Intrinsic.MemMoveName ); if( func == null ) { var signature = ctx.GetFunctionType( ctx.VoidType , ctx.Int8Type.CreatePointerType( ) , ctx.Int8Type.CreatePointerType( ) , ctx.Int32Type , ctx.Int32Type , ctx.BoolType ); func = module.AddFunction( Intrinsic.MemMoveName, signature ); } var call = BuildCall( func, destination, source, len, module.Context.CreateConstant( align ), module.Context.CreateConstant( isVolatile ) ); return Value.FromHandle( call ); } /// Builds a memset intrinsic call /// Module to add the declaration of the intrinsic to if it doesn't already exist /// Destination pointer of the memset /// fill value for the memset /// length of the data to fill /// ALignment of the data for the fill /// Flag to indicate if the fill involves volatile data such as physical registers /// call for the memcpy /// /// LLVM has many overloaded variants of the memcpy intrinsic, this implementation currently assumes the /// single form defined by , which matches the classic "C" style memcpy /// function. However future implementations should be able to deduce the types from the provided values /// and generate a more specific call without changing any caller code (as is done with . /// public Value MemSet( NativeModule module, Value destination, Value value, Value len, Int32 align, bool isVolatile ) { if( module == null ) throw new ArgumentNullException( nameof( module ) ); if( destination == null ) throw new ArgumentNullException( nameof( destination ) ); if( value == null ) throw new ArgumentNullException( nameof( value ) ); if( len == null ) throw new ArgumentNullException( nameof( len ) ); if( destination.NativeType.Kind != TypeKind.Pointer ) throw new ArgumentException( "Pointer type expected", nameof( destination ) ); if( value.NativeType.IntegerBitWidth != 8 ) throw new ArgumentException( "8bit value expected", nameof( value ) ); var ctx = module.Context; destination = BitCast( destination, ctx.Int8Type.CreatePointerType( ) ); var func = module.GetFunction( Intrinsic.MemSetName ); if( func == null ) { var signature = ctx.GetFunctionType( ctx.VoidType , ctx.Int8Type.CreatePointerType( ) , ctx.Int8Type , ctx.Int32Type , ctx.Int32Type , ctx.BoolType ); func = module.AddFunction( Intrinsic.MemSetName, signature ); } var call = BuildCall( func , destination , value , len , module.Context.CreateConstant( align ) , module.Context.CreateConstant( isVolatile ) ); return Value.FromHandle( call ); } public Value InsertValue( Value aggValue, Value elementValue, uint index ) { if( aggValue == null ) throw new ArgumentNullException( nameof( aggValue ) ); if( elementValue == null ) throw new ArgumentNullException( nameof( elementValue ) ); var handle = NativeMethods.BuildInsertValue( BuilderHandle, aggValue.ValueHandle, elementValue.ValueHandle, index, string.Empty ); return Value.FromHandle( handle ); } #region Disposable Pattern public void Dispose( ) { Dispose( true ); GC.SuppressFinalize( this ); } protected virtual void Dispose( bool disposing ) { NativeMethods.DisposeBuilder( BuilderHandle ); } ~InstructionBuilder( ) { Dispose( false ); } #endregion internal static LLVMValueRef[ ] GetValidatedGEPArgs( Value pointer, IEnumerable args ) { if( pointer == null ) throw new ArgumentNullException( nameof( pointer ) ); if( pointer.NativeType.Kind != TypeKind.Pointer ) throw new ArgumentException( "Pointer value expected", nameof( pointer ) ); // if not an array already, pull from source enumerable into an array only once var argsArray = args as Value[ ] ?? args.ToArray( ); if( argsArray.Any( a => !a.NativeType.IsInteger ) ) throw new ArgumentException( $"GEP index arguments must be integers" ); LLVMValueRef[ ] llvmArgs = argsArray.Select( a => a.ValueHandle ).ToArray( ); if( llvmArgs.Length == 0 ) throw new ArgumentException( "There must be at least one index argument", nameof( args ) ); return llvmArgs; } internal LLVMBuilderRef BuilderHandle { get; } // LLVM will automatically perform constant folding, thus the result of applying // a unary operator instruction may actually be a constant value and not an instruction // this deals with that to produce a correct managed wrapper type private Value BuildUnaryOp( Func opFactory , Value operand ) { var valueRef = opFactory( BuilderHandle, operand.ValueHandle, string.Empty ); return Value.FromHandle( valueRef ); } // LLVM will automatically perform constant folding, thus the result of applying // a binary operator instruction may actually be a constant value and not an instruction // this deals with that to produce a correct managed wrapper type private Value BuildBinOp( Func opFactory , Value lhs , Value rhs ) { var valueRef = opFactory( BuilderHandle, lhs.ValueHandle, rhs.ValueHandle, string.Empty ); return Value.FromHandle( valueRef ); } private Value BuildAtomicBinOp( LLVMAtomicRMWBinOp op, Value ptr, Value val ) { var ptrType = ptr.NativeType as IPointerType; if( ptrType == null ) { throw new ArgumentException( "Expected pointer type", nameof( ptr ) ); } if( ptrType.ElementType != val.NativeType ) { throw new ArgumentException( string.Format( IncompatibleTypeMsgFmt, ptrType.ElementType, val.NativeType ) ); } var handle = NativeMethods.BuildAtomicRMW( BuilderHandle, op, ptr.ValueHandle, val.ValueHandle, LLVMAtomicOrdering.LLVMAtomicOrderingSequentiallyConsistent, false ); return Value.FromHandle( handle ); } private static void ValidateCallArgs( Value func, IReadOnlyList args ) { if( func == null ) throw new ArgumentNullException( nameof( func ) ); var funcPtrType = func.NativeType as IPointerType; if( funcPtrType == null ) throw new ArgumentException( "Expected pointer to function", nameof( func ) ); var elementType = funcPtrType.ElementType as FunctionType; if( elementType == null ) throw new ArgumentException( "A pointer to a function is required for an indirect call", nameof( func ) ); if( args.Count != elementType.ParameterTypes.Count ) throw new ArgumentException( "Mismatched parameter count with call site", nameof( args ) ); for( int i = 0; i < args.Count; ++i ) { if( args[ i ].NativeType != elementType.ParameterTypes[ i ] ) { var msg = $"Call site argument type mismatch for function {func} at index {i}; argType={args[ i ].NativeType}; signatureType={elementType.ParameterTypes[ i ]}"; Debug.WriteLine( msg ); throw new ArgumentException( msg, nameof( args ) ); } } } private LLVMValueRef BuildCall( Value func, params Value[ ] args ) => BuildCall( func, ( IReadOnlyList )args ); private LLVMValueRef BuildCall( Value func ) => BuildCall( func, new List( ) ); private LLVMValueRef BuildCall( Value func, IReadOnlyList args ) { ValidateCallArgs( func, args ); LLVMValueRef[ ] llvmArgs = args.Select( v => v.ValueHandle ).ToArray( ); int argCount = llvmArgs.Length; // must always provide at least one element for successful marshaling/interop, but tell LLVM there are none if( argCount == 0 ) llvmArgs = new LLVMValueRef[ 1 ]; return NativeMethods.BuildCall( BuilderHandle, func.ValueHandle, out llvmArgs[ 0 ], ( uint )argCount, string.Empty ); } const string IncompatibleTypeMsgFmt = "Incompatible types: destination pointer must be of the same type as the value stored.\n" + "Types are:\n" + "\tDestination: {0}\n" + "\tValue: {1}"; } } ================================================ FILE: Zelig/Zelig/CompileTime/Llvm.NET/Llvm.NET/Instructions/IntCmp.cs ================================================ using Llvm.NET.Native; namespace Llvm.NET.Instructions { public class IntCmp : Cmp { internal IntCmp( LLVMValueRef valueRef ) : base( valueRef ) { } } } ================================================ FILE: Zelig/Zelig/CompileTime/Llvm.NET/Llvm.NET/Instructions/IntToPointer.cs ================================================ using Llvm.NET.Native; namespace Llvm.NET.Instructions { public class IntToPointer : Cast { internal IntToPointer( LLVMValueRef valueRef ) : base( valueRef ) { } } } ================================================ FILE: Zelig/Zelig/CompileTime/Llvm.NET/Llvm.NET/Instructions/Intrinsic.cs ================================================ using Llvm.NET.Native; namespace Llvm.NET.Instructions { public class Intrinsic : CallInstruction { internal Intrinsic( LLVMValueRef valueRef ) : base( valueRef ) { } internal const string DoNothingName = "llvm.donothing"; internal const string DebugTrapName = "llvm.debugtrap"; // TODO: move these out of here to follow pattern in MemCpy internal const string MemMoveName = "llvm.memmove.p0i8.p0i8.i32"; internal const string MemSetName = "llvm.memset.p0i8.i32"; }; } ================================================ FILE: Zelig/Zelig/CompileTime/Llvm.NET/Llvm.NET/Instructions/Invoke.cs ================================================ using Llvm.NET.Native; using Llvm.NET.Values; namespace Llvm.NET.Instructions { public class Invoke : Terminator , IAttributeSetContainer { public AttributeSet Attributes { get { if( TargetFunction == null ) return new AttributeSet(); return new AttributeSet( NativeMethods.GetCallSiteAttributeSet( ValueHandle )); } set { // TODO: Verify the attributeSet doesn't contain any parameter indices not supported by the TargetFunction NativeMethods.SetCallSiteAttributeSet( ValueHandle, value.NativeAttributeSet ); } } public Function TargetFunction { get { if( Operands.Count < 1 ) return null; // last Operand of the instruction is the target function return Operands[ Operands.Count - 1 ] as Function; } } internal Invoke( LLVMValueRef valueRef ) : base( valueRef ) { } } } ================================================ FILE: Zelig/Zelig/CompileTime/Llvm.NET/Llvm.NET/Instructions/LandingPad.cs ================================================ using Llvm.NET.Values; using System; using Llvm.NET.Native; namespace Llvm.NET.Instructions { public class LandingPad : Instruction { internal LandingPad( LLVMValueRef valueRef ) : base( valueRef ) { } public void AddClause(Value clause) { if( clause == null ) throw new ArgumentNullException( nameof( clause ) ); NativeMethods.AddClause(ValueHandle, clause.ValueHandle); } public void SetCleanup( bool value ) => NativeMethods.SetCleanup( ValueHandle, value ); } } ================================================ FILE: Zelig/Zelig/CompileTime/Llvm.NET/Llvm.NET/Instructions/Load.cs ================================================ using Llvm.NET.Native; namespace Llvm.NET.Instructions { public class Load : UnaryInstruction { public bool IsVolatile { get { return NativeMethods.GetVolatile( ValueHandle ); } set { NativeMethods.SetVolatile( ValueHandle, value ); } } internal Load( LLVMValueRef valueRef ) : base( valueRef ) { } } } ================================================ FILE: Zelig/Zelig/CompileTime/Llvm.NET/Llvm.NET/Instructions/MemCpy.cs ================================================ using System.Diagnostics; using Llvm.NET.Native; using Llvm.NET.Types; namespace Llvm.NET.Instructions { public class MemCpy : MemIntrinsic { internal MemCpy( LLVMValueRef handle ) : base( handle ) { } internal static string GetIntrinsicNameForArgs( IPointerType dst, IPointerType src, ITypeRef len ) { Debug.Assert( dst != null && dst.ElementType.IsInteger && dst.ElementType.IntegerBitWidth > 0 ); Debug.Assert( src != null && src.ElementType.IsInteger && src.ElementType.IntegerBitWidth > 0 ); Debug.Assert( len.IsInteger && len.IntegerBitWidth > 0 ); return $"llvm.memcpy.p{dst.AddressSpace}i{dst.ElementType.IntegerBitWidth}.p{src.AddressSpace}i{src.ElementType.IntegerBitWidth}.i{len.IntegerBitWidth}"; } } } ================================================ FILE: Zelig/Zelig/CompileTime/Llvm.NET/Llvm.NET/Instructions/MemIntrinsic.cs ================================================ using Llvm.NET.Native; namespace Llvm.NET.Instructions { public class MemIntrinsic : Intrinsic { internal MemIntrinsic( LLVMValueRef valueRef ) : base( valueRef ) { } } } ================================================ FILE: Zelig/Zelig/CompileTime/Llvm.NET/Llvm.NET/Instructions/MemMove.cs ================================================ using Llvm.NET.Native; namespace Llvm.NET.Instructions { public class MemMove : MemIntrinsic { internal MemMove( LLVMValueRef valueRef ) : base( valueRef ) { } } } ================================================ FILE: Zelig/Zelig/CompileTime/Llvm.NET/Llvm.NET/Instructions/MemSet.cs ================================================ using Llvm.NET.Native; namespace Llvm.NET.Instructions { public class MemSet : MemIntrinsic { internal MemSet( LLVMValueRef valueRef ) : base( valueRef ) { } } } ================================================ FILE: Zelig/Zelig/CompileTime/Llvm.NET/Llvm.NET/Instructions/PhiNode.cs ================================================ using System; using Llvm.NET.Native; using Llvm.NET.Values; namespace Llvm.NET.Instructions { public class PhiNode : Instruction { public void AddIncoming( Value value, BasicBlock srcBlock ) { AddIncoming( Tuple.Create( value, srcBlock ) ); } public void AddIncoming( Tuple firstIncoming, params Tuple[ ] additionalIncoming ) { if( firstIncoming == null ) throw new ArgumentNullException( nameof( firstIncoming ) ); if( additionalIncoming == null ) throw new ArgumentNullException( nameof( additionalIncoming ) ); LLVMValueRef[ ] llvmValues = new LLVMValueRef[ additionalIncoming.Length + 1 ]; llvmValues[ 0 ] = firstIncoming.Item1.ValueHandle; for( int i = 0; i < additionalIncoming.Length; ++i ) llvmValues[ i + i ] = additionalIncoming[ i ].Item1.ValueHandle; LLVMBasicBlockRef[ ] llvmBlocks = new LLVMBasicBlockRef[ additionalIncoming.Length + 1 ]; llvmBlocks[ 0 ] = firstIncoming.Item2.BlockHandle; for( int i = 0; i < additionalIncoming.Length; ++i ) llvmBlocks[ i + i ] = additionalIncoming[ i ].Item2.BlockHandle; NativeMethods.AddIncoming( ValueHandle, out llvmValues[ 0 ], out llvmBlocks[ 0 ], ( uint )llvmValues.Length ); } internal PhiNode( LLVMValueRef valueRef ) : base( valueRef ) { } } } ================================================ FILE: Zelig/Zelig/CompileTime/Llvm.NET/Llvm.NET/Instructions/PointerToInt.cs ================================================ using Llvm.NET.Native; namespace Llvm.NET.Instructions { public class PointerToInt : Cast { internal PointerToInt( LLVMValueRef valueRef ) : base( valueRef ) { } } } ================================================ FILE: Zelig/Zelig/CompileTime/Llvm.NET/Llvm.NET/Instructions/Resume.cs ================================================ using Llvm.NET.Native; namespace Llvm.NET.Instructions { public class ResumeInstruction : Terminator { internal ResumeInstruction( LLVMValueRef valueRef ) : base( valueRef ) { } } } ================================================ FILE: Zelig/Zelig/CompileTime/Llvm.NET/Llvm.NET/Instructions/Return.cs ================================================ using Llvm.NET.Native; namespace Llvm.NET.Instructions { public class ReturnInstruction : Terminator { internal ReturnInstruction( LLVMValueRef valueRef ) : base( valueRef ) { } } } ================================================ FILE: Zelig/Zelig/CompileTime/Llvm.NET/Llvm.NET/Instructions/SIToFP.cs ================================================ using Llvm.NET.Native; namespace Llvm.NET.Instructions { class SIToFP : Cast { internal SIToFP( LLVMValueRef valueRef ) : base( valueRef ) { } } } ================================================ FILE: Zelig/Zelig/CompileTime/Llvm.NET/Llvm.NET/Instructions/Select.cs ================================================ using Llvm.NET.Native; namespace Llvm.NET.Instructions { public class Select : Instruction { internal Select( LLVMValueRef valueRef ) : base( valueRef ) { } } } ================================================ FILE: Zelig/Zelig/CompileTime/Llvm.NET/Llvm.NET/Instructions/ShuffleVector.cs ================================================ using Llvm.NET.Native; namespace Llvm.NET.Instructions { public class ShuffleVector : Instruction { internal ShuffleVector( LLVMValueRef valueRef ) : base( valueRef ) { } } } ================================================ FILE: Zelig/Zelig/CompileTime/Llvm.NET/Llvm.NET/Instructions/SignExtend.cs ================================================ using Llvm.NET.Native; namespace Llvm.NET.Instructions { public class SignExtend : Cast { internal SignExtend( LLVMValueRef valueRef ) : base( valueRef ) { } } } ================================================ FILE: Zelig/Zelig/CompileTime/Llvm.NET/Llvm.NET/Instructions/Store.cs ================================================ using Llvm.NET.Native; namespace Llvm.NET.Instructions { public class Store : Instruction { public bool IsVolatile { get { return NativeMethods.GetVolatile( ValueHandle ); } set { NativeMethods.SetVolatile( ValueHandle, value ); } } internal Store( LLVMValueRef valueRef ) : base( valueRef ) { } } } ================================================ FILE: Zelig/Zelig/CompileTime/Llvm.NET/Llvm.NET/Instructions/Switch.cs ================================================ using Llvm.NET.Native; using Llvm.NET.Values; namespace Llvm.NET.Instructions { public class Switch : Terminator { /// Default for the switch public BasicBlock Default => BasicBlock.FromHandle( NativeMethods.GetSwitchDefaultDest( ValueHandle ) ); /// Adds a new case to the instruction /// Value for the case to match /// Destination if the case matches public void AddCase( Value onVal, BasicBlock destination ) { if( onVal == null ) throw new System.ArgumentNullException( nameof( onVal ) ); if( destination == null ) throw new System.ArgumentNullException( nameof( destination ) ); NativeMethods.AddCase( ValueHandle, onVal.ValueHandle, destination.BlockHandle ); } internal Switch( LLVMValueRef valueRef ) : base( valueRef ) { } } } ================================================ FILE: Zelig/Zelig/CompileTime/Llvm.NET/Llvm.NET/Instructions/Terminator.cs ================================================ using Llvm.NET.Native; namespace Llvm.NET.Instructions { public class Terminator : Instruction { internal Terminator( LLVMValueRef valueRef ) : base( valueRef ) { } } } ================================================ FILE: Zelig/Zelig/CompileTime/Llvm.NET/Llvm.NET/Instructions/Trunc.cs ================================================ using Llvm.NET.Native; namespace Llvm.NET.Instructions { public class Trunc : Cast { internal Trunc( LLVMValueRef valueRef ) : base( valueRef ) { } } } ================================================ FILE: Zelig/Zelig/CompileTime/Llvm.NET/Llvm.NET/Instructions/UIToFP.cs ================================================ using Llvm.NET.Native; namespace Llvm.NET.Instructions { class UIToFP : Cast { internal UIToFP( LLVMValueRef valueRef ) : base( valueRef ) { } } } ================================================ FILE: Zelig/Zelig/CompileTime/Llvm.NET/Llvm.NET/Instructions/UnaryInstruction.cs ================================================ using Llvm.NET.Native; namespace Llvm.NET.Instructions { public class UnaryInstruction : Instruction { internal UnaryInstruction( LLVMValueRef valueRef ) : base( valueRef ) { } } } ================================================ FILE: Zelig/Zelig/CompileTime/Llvm.NET/Llvm.NET/Instructions/Unreachable.cs ================================================ using Llvm.NET.Native; namespace Llvm.NET.Instructions { public class Unreachable : Terminator { internal Unreachable( LLVMValueRef valueRef ) : base( valueRef ) { } } } ================================================ FILE: Zelig/Zelig/CompileTime/Llvm.NET/Llvm.NET/Instructions/UserOp1.cs ================================================ using Llvm.NET.Native; namespace Llvm.NET.Instructions { class UserOp1 : Instruction { internal UserOp1( LLVMValueRef valueRef ) : base( valueRef ) { } } } ================================================ FILE: Zelig/Zelig/CompileTime/Llvm.NET/Llvm.NET/Instructions/UserOp2.cs ================================================ using Llvm.NET.Native; namespace Llvm.NET.Instructions { class UserOp2 : Instruction { internal UserOp2( LLVMValueRef valueRef ) : base( valueRef ) { } } } ================================================ FILE: Zelig/Zelig/CompileTime/Llvm.NET/Llvm.NET/Instructions/VAArg.cs ================================================ using Llvm.NET.Native; namespace Llvm.NET.Instructions { class VaArg : UnaryInstruction { internal VaArg( LLVMValueRef valueRef ) : base( valueRef ) { } } } ================================================ FILE: Zelig/Zelig/CompileTime/Llvm.NET/Llvm.NET/Instructions/ZeroExtend.cs ================================================  using Llvm.NET.Native; namespace Llvm.NET.Instructions { public class ZeroExtend : Cast { internal ZeroExtend( LLVMValueRef valueRef ) : base( valueRef ) { } } } ================================================ FILE: Zelig/Zelig/CompileTime/Llvm.NET/Llvm.NET/InternalCodeGeneratorException.cs ================================================ using System; using System.Runtime.Serialization; namespace Llvm.NET { /// Exception generated when the internal state of the code generation cannot proceed due to an internal error [Serializable] public class InternalCodeGeneratorException : Exception { public InternalCodeGeneratorException( ) { } public InternalCodeGeneratorException( string message ) : base( message ) { } public InternalCodeGeneratorException( string message, Exception inner ) : base( message, inner ) { } protected InternalCodeGeneratorException( SerializationInfo info , StreamingContext context ) : base( info, context ) { } } } ================================================ FILE: Zelig/Zelig/CompileTime/Llvm.NET/Llvm.NET/LLVM/Generated.cs ================================================ // This file was generated from LLVM 3.6.1 llvm-c API using ClangSharp // it was further modified in the following ways: // - removed most uses of the partial keyword except for LLVMNative static class and LLVMBool // - added warning disable to avoid benign compiler warnings about fields only set by native code // - modified all elements to be internal instead of public // - modified PInvoke attributes to use fully qualified name for CallingConvention to avoid conflicts // - Added Missing LLVMLinkerMode enumeration // - Fixed signature of LLVMLinkModules to use new enum // - modified all LLVMNative.* functions returning a string to return IntPtr // as using string with default CLR marshaling was causing run-time // Heap Corruption. [Reason unknown] Calling these functions requires calling // Marshal.PtrToAnsi( x ) manually, which is handled by the OO wrappers. // - made Value field of LLVMBool private to help prevent confusion on use the Value. For status // code values code should use the Success/Failure properties (added to partial implementation) // and implicit casts to/from bool for actual boolean. Unfortunately nothing in LLVM or the // value of a LLVMBool can help in identifying which form one should use. The only way to know // at this point is to read the LLVM-C API documentation. In the Future it may be good to Create // an LLVMStatusResult type for those function returning a status and use standard marshaling // techniques for actual boolean values... // - manually updated to 3.8.0 APIs using System; using System.Runtime.InteropServices; //warning CS0649: Field 'xxx' is never assigned to, and will always have its default value 0 #pragma warning disable 649 namespace Llvm.NET.Native { internal struct LLVMOpaqueMemoryBuffer { } internal struct LLVMOpaqueContext { } internal struct LLVMOpaqueModule { } internal struct LLVMOpaqueType { } internal struct LLVMOpaqueValue { } internal struct LLVMOpaqueBasicBlock { } internal struct LLVMOpaqueBuilder { } internal struct LLVMOpaqueModuleProvider { } internal struct LLVMOpaquePassManager { } internal struct LLVMOpaquePassRegistry { } internal struct LLVMOpaqueUse { } internal struct LLVMOpaqueDiagnosticInfo { } internal struct LLVMOpInfoSymbol1 { public int @Present; [MarshalAs(UnmanagedType.LPStr)] public string @Name; public int @Value; } internal struct LLVMOpInfo1 { public LLVMOpInfoSymbol1 @AddSymbol; public LLVMOpInfoSymbol1 @SubtractSymbol; public int @Value; public int @VariantKind; } internal struct LLVMOpaqueTargetData { } internal struct LLVMOpaqueTargetLibraryInfotData { } internal struct LLVMOpaqueTargetMachine { } internal struct LLVMTarget { } internal struct LLVMOpaqueGenericValue { } internal struct LLVMOpaqueExecutionEngine { } internal struct LLVMOpaqueMCJITMemoryManager { } internal struct LLVMMCJITCompilerOptions { public uint @OptLevel; public LLVMCodeModel @CodeModel; public int @NoFramePointerElim; public int @EnableFastISel; public IntPtr @MCJMM; } internal struct LLVMOpaqueLTOModule { } internal struct LLVMOpaqueLTOCodeGenerator { } internal struct LLVMOpaqueObjectFile { } internal struct LLVMOpaqueSectionIterator { } internal struct LLVMOpaqueSymbolIterator { } internal struct LLVMOpaqueRelocationIterator { } internal struct LLVMOpaquePassManagerBuilder { } internal partial struct LLVMBool { public LLVMBool(int value) { this.Value = value; } internal int Value; } internal struct LLVMMemoryBufferRef { public LLVMMemoryBufferRef(IntPtr pointer) { this.Pointer = pointer; } public IntPtr Pointer; } internal struct LLVMContextRef { public LLVMContextRef(IntPtr pointer) { this.Pointer = pointer; } public IntPtr Pointer; } internal struct LLVMModuleRef { public LLVMModuleRef(IntPtr pointer) { this.Pointer = pointer; } public IntPtr Pointer; } internal struct LLVMTypeRef { public LLVMTypeRef(IntPtr pointer) { this.Pointer = pointer; } public IntPtr Pointer; } internal struct LLVMValueRef { public LLVMValueRef(IntPtr pointer) { this.Pointer = pointer; } public IntPtr Pointer { get; } public readonly static LLVMValueRef Zero = new LLVMValueRef( IntPtr.Zero ); } internal struct LLVMBasicBlockRef { public LLVMBasicBlockRef(IntPtr pointer) { this.Pointer = pointer; } public IntPtr Pointer; } internal struct LLVMBuilderRef { public LLVMBuilderRef(IntPtr pointer) { this.Pointer = pointer; } public IntPtr Pointer; } internal struct LLVMModuleProviderRef { public LLVMModuleProviderRef(IntPtr pointer) { this.Pointer = pointer; } public IntPtr Pointer; } internal struct LLVMPassManagerRef { public LLVMPassManagerRef(IntPtr pointer) { this.Pointer = pointer; } public IntPtr Pointer; } internal struct LLVMPassRegistryRef { public LLVMPassRegistryRef(IntPtr pointer) { this.Pointer = pointer; } public IntPtr Pointer; } internal struct LLVMUseRef { public LLVMUseRef(IntPtr pointer) { this.Pointer = pointer; } public IntPtr Pointer; } internal struct LLVMDiagnosticInfoRef { public LLVMDiagnosticInfoRef(IntPtr pointer) { this.Pointer = pointer; } public IntPtr Pointer; } [UnmanagedFunctionPointer(System.Runtime.InteropServices.CallingConvention.Cdecl, BestFitMapping = false, ThrowOnUnmappableChar = true)] internal delegate void LLVMFatalErrorHandler([MarshalAs(UnmanagedType.LPStr)] string @Reason); [UnmanagedFunctionPointer(System.Runtime.InteropServices.CallingConvention.Cdecl, BestFitMapping = false, ThrowOnUnmappableChar = true)] internal delegate void LLVMDiagnosticHandler(out LLVMOpaqueDiagnosticInfo @param0, IntPtr @param1); [UnmanagedFunctionPointer(System.Runtime.InteropServices.CallingConvention.Cdecl, BestFitMapping = false, ThrowOnUnmappableChar = true)] internal delegate void LLVMYieldCallback(out LLVMOpaqueContext @param0, IntPtr @param1); internal struct LLVMDisasmContextRef { public LLVMDisasmContextRef(IntPtr pointer) { this.Pointer = pointer; } public IntPtr Pointer; } [UnmanagedFunctionPointer(System.Runtime.InteropServices.CallingConvention.Cdecl, BestFitMapping = false, ThrowOnUnmappableChar = true)] internal delegate int LLVMOpInfoCallback(IntPtr @DisInfo, int @PC, int @Offset, int @Size, int @TagType, IntPtr @TagBuf); [UnmanagedFunctionPointer(System.Runtime.InteropServices.CallingConvention.Cdecl, BestFitMapping = false, ThrowOnUnmappableChar = true)] internal delegate string LLVMSymbolLookupCallback(IntPtr @DisInfo, int @ReferenceValue, out int @ReferenceType, int @ReferencePC, out IntPtr @ReferenceName); internal struct LLVMTargetDataRef { public LLVMTargetDataRef(IntPtr pointer) { this.Pointer = pointer; } public IntPtr Pointer; } internal struct LLVMTargetLibraryInfoRef { public LLVMTargetLibraryInfoRef(IntPtr pointer) { this.Pointer = pointer; } public IntPtr Pointer; } internal struct LLVMTargetMachineRef { public LLVMTargetMachineRef(IntPtr pointer) { this.Pointer = pointer; } public IntPtr Pointer; } internal struct LLVMTargetRef { public LLVMTargetRef(IntPtr pointer) { this.Pointer = pointer; } public IntPtr Pointer; } internal struct LLVMGenericValueRef { public LLVMGenericValueRef(IntPtr pointer) { this.Pointer = pointer; } public IntPtr Pointer; } internal struct LLVMExecutionEngineRef { public LLVMExecutionEngineRef(IntPtr pointer) { this.Pointer = pointer; } public IntPtr Pointer; } internal struct LLVMMCJITMemoryManagerRef { public LLVMMCJITMemoryManagerRef(IntPtr pointer) { this.Pointer = pointer; } public IntPtr Pointer; } [UnmanagedFunctionPointer(System.Runtime.InteropServices.CallingConvention.Cdecl, BestFitMapping = false, ThrowOnUnmappableChar = true)] internal delegate IntPtr LLVMMemoryManagerAllocateCodeSectionCallback(IntPtr @Opaque, int @Size, uint @Alignment, uint @SectionID, [MarshalAs(UnmanagedType.LPStr)] string @SectionName); [UnmanagedFunctionPointer(System.Runtime.InteropServices.CallingConvention.Cdecl, BestFitMapping = false, ThrowOnUnmappableChar = true)] internal delegate IntPtr LLVMMemoryManagerAllocateDataSectionCallback(IntPtr @Opaque, int @Size, uint @Alignment, uint @SectionID, [MarshalAs(UnmanagedType.LPStr)] string @SectionName, int @IsReadOnly); [UnmanagedFunctionPointer(System.Runtime.InteropServices.CallingConvention.Cdecl, BestFitMapping = false, ThrowOnUnmappableChar = true)] internal delegate int LLVMMemoryManagerFinalizeMemoryCallback(IntPtr @Opaque, out IntPtr @ErrMsg); [UnmanagedFunctionPointer(System.Runtime.InteropServices.CallingConvention.Cdecl, BestFitMapping = false, ThrowOnUnmappableChar = true)] internal delegate void LLVMMemoryManagerDestroyCallback(IntPtr @Opaque); //internal struct llvm_lto_t //{ // public llvm_lto_t(IntPtr pointer) // { // this.Pointer = pointer; // } // public IntPtr Pointer; //} //internal struct lto_bool_t //{ // public lto_bool_t(bool value) // { // this.Value = value; // } // public bool Value; //} //internal struct lto_module_t //{ // public lto_module_t(IntPtr pointer) // { // this.Pointer = pointer; // } // public IntPtr Pointer; //} //internal struct lto_code_gen_t //{ // public lto_code_gen_t(IntPtr pointer) // { // this.Pointer = pointer; // } // public IntPtr Pointer; //} //[UnmanagedFunctionPointer(System.Runtime.InteropServices.CallingConvention.Cdecl, BestFitMapping = false, ThrowOnUnmappableChar = true)] //internal delegate void lto_diagnostic_handler_t(lto_codegen_diagnostic_severity_t @severity, [MarshalAs(UnmanagedType.LPStr)] string @diag, IntPtr @ctxt); internal struct LLVMObjectFileRef { public LLVMObjectFileRef(IntPtr pointer) { this.Pointer = pointer; } public IntPtr Pointer; } internal struct LLVMSectionIteratorRef { public LLVMSectionIteratorRef(IntPtr pointer) { this.Pointer = pointer; } public IntPtr Pointer; } internal struct LLVMSymbolIteratorRef { public LLVMSymbolIteratorRef(IntPtr pointer) { this.Pointer = pointer; } public IntPtr Pointer; } internal struct LLVMRelocationIteratorRef { public LLVMRelocationIteratorRef(IntPtr pointer) { this.Pointer = pointer; } public IntPtr Pointer; } internal struct LLVMPassManagerBuilderRef { public LLVMPassManagerBuilderRef(IntPtr pointer) { this.Pointer = pointer; } public IntPtr Pointer; } internal enum LLVMAttribute : int { @LLVMZExtAttribute = 1, @LLVMSExtAttribute = 2, @LLVMNoReturnAttribute = 4, @LLVMInRegAttribute = 8, @LLVMStructRetAttribute = 16, @LLVMNoUnwindAttribute = 32, @LLVMNoAliasAttribute = 64, @LLVMByValAttribute = 128, @LLVMNestAttribute = 256, @LLVMReadNoneAttribute = 512, @LLVMReadOnlyAttribute = 1024, @LLVMNoInlineAttribute = 2048, @LLVMAlwaysInlineAttribute = 4096, @LLVMOptimizeForSizeAttribute = 8192, @LLVMStackProtectAttribute = 16384, @LLVMStackProtectReqAttribute = 32768, @LLVMAlignment = 2031616, @LLVMNoCaptureAttribute = 2097152, @LLVMNoRedZoneAttribute = 4194304, @LLVMNoImplicitFloatAttribute = 8388608, @LLVMNakedAttribute = 16777216, @LLVMInlineHintAttribute = 33554432, @LLVMStackAlignment = 469762048, @LLVMReturnsTwice = 536870912, @LLVMUWTable = 1073741824, @LLVMNonLazyBind = -2147483648, } internal enum LLVMOpcode : uint { @LLVMRet = 1, @LLVMBr = 2, @LLVMSwitch = 3, @LLVMIndirectBr = 4, @LLVMInvoke = 5, @LLVMUnreachable = 7, @LLVMAdd = 8, @LLVMFAdd = 9, @LLVMSub = 10, @LLVMFSub = 11, @LLVMMul = 12, @LLVMFMul = 13, @LLVMUDiv = 14, @LLVMSDiv = 15, @LLVMFDiv = 16, @LLVMURem = 17, @LLVMSRem = 18, @LLVMFRem = 19, @LLVMShl = 20, @LLVMLShr = 21, @LLVMAShr = 22, @LLVMAnd = 23, @LLVMOr = 24, @LLVMXor = 25, @LLVMAlloca = 26, @LLVMLoad = 27, @LLVMStore = 28, @LLVMGetElementPtr = 29, @LLVMTrunc = 30, @LLVMZExt = 31, @LLVMSExt = 32, @LLVMFPToUI = 33, @LLVMFPToSI = 34, @LLVMUIToFP = 35, @LLVMSIToFP = 36, @LLVMFPTrunc = 37, @LLVMFPExt = 38, @LLVMPtrToInt = 39, @LLVMIntToPtr = 40, @LLVMBitCast = 41, @LLVMAddrSpaceCast = 60, @LLVMICmp = 42, @LLVMFCmp = 43, @LLVMPHI = 44, @LLVMCall = 45, @LLVMSelect = 46, @LLVMUserOp1 = 47, @LLVMUserOp2 = 48, @LLVMVAArg = 49, @LLVMExtractElement = 50, @LLVMInsertElement = 51, @LLVMShuffleVector = 52, @LLVMExtractValue = 53, @LLVMInsertValue = 54, @LLVMFence = 55, @LLVMAtomicCmpXchg = 56, @LLVMAtomicRMW = 57, @LLVMResume = 58, @LLVMLandingPad = 59, // Gap = 60 @LLVMCleanupRet = 61, @LLVMCatchRet = 62, @LLVMCatchPad = 63, @LLVMCleandupPad = 64, @LLVMCatchSwitch = 65 } internal enum LLVMTypeKind : uint { @LLVMVoidTypeKind = 0, @LLVMHalfTypeKind = 1, @LLVMFloatTypeKind = 2, @LLVMDoubleTypeKind = 3, @LLVMX86_FP80TypeKind = 4, @LLVMFP128TypeKind = 5, @LLVMPPC_FP128TypeKind = 6, @LLVMLabelTypeKind = 7, @LLVMIntegerTypeKind = 8, @LLVMFunctionTypeKind = 9, @LLVMStructTypeKind = 10, @LLVMArrayTypeKind = 11, @LLVMPointerTypeKind = 12, @LLVMVectorTypeKind = 13, @LLVMMetadataTypeKind = 14, @LLVMX86_MMXTypeKind = 15, @LLVMTokenTypeKind = 16, } internal enum LLVMLinkage : uint { @LLVMExternalLinkage = 0, @LLVMAvailableExternallyLinkage = 1, @LLVMLinkOnceAnyLinkage = 2, @LLVMLinkOnceODRLinkage = 3, @LLVMLinkOnceODRAutoHideLinkage = 4, @LLVMWeakAnyLinkage = 5, @LLVMWeakODRLinkage = 6, @LLVMAppendingLinkage = 7, @LLVMInternalLinkage = 8, @LLVMPrivateLinkage = 9, @LLVMDLLImportLinkage = 10, @LLVMDLLExportLinkage = 11, @LLVMExternalWeakLinkage = 12, @LLVMGhostLinkage = 13, @LLVMCommonLinkage = 14, @LLVMLinkerPrivateLinkage = 15, @LLVMLinkerPrivateWeakLinkage = 16, } internal enum LLVMVisibility : uint { @LLVMDefaultVisibility = 0, @LLVMHiddenVisibility = 1, @LLVMProtectedVisibility = 2, } internal enum LLVMDLLStorageClass : uint { @LLVMDefaultStorageClass = 0, @LLVMDLLImportStorageClass = 1, @LLVMDLLExportStorageClass = 2, } internal enum LLVMCallConv : uint { @LLVMCCallConv = 0, @LLVMFastCallConv = 8, @LLVMColdCallConv = 9, @LLVMWebKitJSCallConv = 12, @LLVMAnyRegCallConv = 13, @LLVMX86StdcallCallConv = 64, @LLVMX86FastcallCallConv = 65, } internal enum LLVMIntPredicate : uint { @LLVMIntEQ = 32, @LLVMIntNE = 33, @LLVMIntUGT = 34, @LLVMIntUGE = 35, @LLVMIntULT = 36, @LLVMIntULE = 37, @LLVMIntSGT = 38, @LLVMIntSGE = 39, @LLVMIntSLT = 40, @LLVMIntSLE = 41, } internal enum LLVMRealPredicate : uint { @LLVMRealPredicateFalse = 0, @LLVMRealOEQ = 1, @LLVMRealOGT = 2, @LLVMRealOGE = 3, @LLVMRealOLT = 4, @LLVMRealOLE = 5, @LLVMRealONE = 6, @LLVMRealORD = 7, @LLVMRealUNO = 8, @LLVMRealUEQ = 9, @LLVMRealUGT = 10, @LLVMRealUGE = 11, @LLVMRealULT = 12, @LLVMRealULE = 13, @LLVMRealUNE = 14, @LLVMRealPredicateTrue = 15, } internal enum LLVMLandingPadClauseTy : uint { @LLVMLandingPadCatch = 0, @LLVMLandingPadFilter = 1, } internal enum LLVMThreadLocalMode : uint { @LLVMNotThreadLocal = 0, @LLVMGeneralDynamicTLSModel = 1, @LLVMLocalDynamicTLSModel = 2, @LLVMInitialExecTLSModel = 3, @LLVMLocalExecTLSModel = 4, } internal enum LLVMAtomicOrdering : uint { @LLVMAtomicOrderingNotAtomic = 0, @LLVMAtomicOrderingUnordered = 1, @LLVMAtomicOrderingMonotonic = 2, @LLVMAtomicOrderingAcquire = 4, @LLVMAtomicOrderingRelease = 5, @LLVMAtomicOrderingAcquireRelease = 6, @LLVMAtomicOrderingSequentiallyConsistent = 7, } internal enum LLVMAtomicRMWBinOp : uint { @LLVMAtomicRMWBinOpXchg = 0, @LLVMAtomicRMWBinOpAdd = 1, @LLVMAtomicRMWBinOpSub = 2, @LLVMAtomicRMWBinOpAnd = 3, @LLVMAtomicRMWBinOpNand = 4, @LLVMAtomicRMWBinOpOr = 5, @LLVMAtomicRMWBinOpXor = 6, @LLVMAtomicRMWBinOpMax = 7, @LLVMAtomicRMWBinOpMin = 8, @LLVMAtomicRMWBinOpUMax = 9, @LLVMAtomicRMWBinOpUMin = 10, } internal enum LLVMDiagnosticSeverity : uint { @LLVMDSError = 0, @LLVMDSWarning = 1, @LLVMDSRemark = 2, @LLVMDSNote = 3, } internal enum LLVMVerifierFailureAction : uint { @LLVMAbortProcessAction = 0, @LLVMPrintMessageAction = 1, @LLVMReturnStatusAction = 2, } internal enum LLVMByteOrdering : uint { @LLVMBigEndian = 0, @LLVMLittleEndian = 1, } internal enum LLVMCodeGenOptLevel : uint { @LLVMCodeGenLevelNone = 0, @LLVMCodeGenLevelLess = 1, @LLVMCodeGenLevelDefault = 2, @LLVMCodeGenLevelAggressive = 3, } internal enum LLVMRelocMode : uint { @LLVMRelocDefault = 0, @LLVMRelocStatic = 1, @LLVMRelocPIC = 2, @LLVMRelocDynamicNoPic = 3, } internal enum LLVMCodeModel : uint { @LLVMCodeModelDefault = 0, @LLVMCodeModelJITDefault = 1, @LLVMCodeModelSmall = 2, @LLVMCodeModelKernel = 3, @LLVMCodeModelMedium = 4, @LLVMCodeModelLarge = 5, } internal enum LLVMCodeGenFileType : uint { @LLVMAssemblyFile = 0, @LLVMObjectFile = 1, } internal enum llvm_lto_status : uint { @LLVM_LTO_UNKNOWN = 0, @LLVM_LTO_OPT_SUCCESS = 1, @LLVM_LTO_READ_SUCCESS = 2, @LLVM_LTO_READ_FAILURE = 3, @LLVM_LTO_WRITE_FAILURE = 4, @LLVM_LTO_NO_TARGET = 5, @LLVM_LTO_NO_WORK = 6, @LLVM_LTO_MODULE_MERGE_FAILURE = 7, @LLVM_LTO_ASM_FAILURE = 8, @LLVM_LTO_NULL_OBJECT = 9, } internal enum lto_symbol_attributes : uint { @LTO_SYMBOL_ALIGNMENT_MASK = 31, @LTO_SYMBOL_PERMISSIONS_MASK = 224, @LTO_SYMBOL_PERMISSIONS_CODE = 160, @LTO_SYMBOL_PERMISSIONS_DATA = 192, @LTO_SYMBOL_PERMISSIONS_RODATA = 128, @LTO_SYMBOL_DEFINITION_MASK = 1792, @LTO_SYMBOL_DEFINITION_REGULAR = 256, @LTO_SYMBOL_DEFINITION_TENTATIVE = 512, @LTO_SYMBOL_DEFINITION_WEAK = 768, @LTO_SYMBOL_DEFINITION_UNDEFINED = 1024, @LTO_SYMBOL_DEFINITION_WEAKUNDEF = 1280, @LTO_SYMBOL_SCOPE_MASK = 14336, @LTO_SYMBOL_SCOPE_INTERNAL = 2048, @LTO_SYMBOL_SCOPE_HIDDEN = 4096, @LTO_SYMBOL_SCOPE_PROTECTED = 8192, @LTO_SYMBOL_SCOPE_DEFAULT = 6144, @LTO_SYMBOL_SCOPE_DEFAULT_CAN_BE_HIDDEN = 10240, } internal enum lto_debug_model : uint { @LTO_DEBUG_MODEL_NONE = 0, @LTO_DEBUG_MODEL_DWARF = 1, } internal enum lto_codegen_model : uint { @LTO_CODEGEN_PIC_MODEL_STATIC = 0, @LTO_CODEGEN_PIC_MODEL_DYNAMIC = 1, @LTO_CODEGEN_PIC_MODEL_DYNAMIC_NO_PIC = 2, @LTO_CODEGEN_PIC_MODEL_DEFAULT = 3, } internal enum lto_codegen_diagnostic_severity_t : uint { @LTO_DS_ERROR = 0, @LTO_DS_WARNING = 1, @LTO_DS_REMARK = 3, @LTO_DS_NOTE = 2, } internal enum LLVMLinkerMode : uint { @LLVMLinkerDestroySource = 0, /* Allow source module to be destroyed. */ @LLVMLinkerPreserveSource = 1 /* Preserve the source module. */ } internal static partial class NativeMethods { private const string libraryPath = "LibLlvm.dll"; [DllImport(libraryPath, EntryPoint = "LLVMLoadLibraryPermanently", CallingConvention = System.Runtime.InteropServices.CallingConvention.Cdecl, BestFitMapping = false, ThrowOnUnmappableChar = true )] internal static extern LLVMBool LoadLibraryPermanently([MarshalAs(UnmanagedType.LPStr)] string @Filename); [DllImport(libraryPath, EntryPoint = "LLVMParseCommandLineOptions", CallingConvention = System.Runtime.InteropServices.CallingConvention.Cdecl, BestFitMapping = false, ThrowOnUnmappableChar = true)] internal static extern void ParseCommandLineOptions(int @argc, string[] @argv, [MarshalAs(UnmanagedType.LPStr)] string @Overview); [DllImport(libraryPath, EntryPoint = "LLVMInitializeCore", CallingConvention = System.Runtime.InteropServices.CallingConvention.Cdecl, BestFitMapping = false, ThrowOnUnmappableChar = true)] internal static extern void InitializeCore(LLVMPassRegistryRef @R); [DllImport(libraryPath, EntryPoint = "LLVMShutdown", CallingConvention = System.Runtime.InteropServices.CallingConvention.Cdecl, BestFitMapping = false, ThrowOnUnmappableChar = true)] internal static extern void Shutdown(); [DllImport(libraryPath, EntryPoint = "LLVMCreateMessage", CallingConvention = System.Runtime.InteropServices.CallingConvention.Cdecl, BestFitMapping = false, ThrowOnUnmappableChar = true)] internal static extern IntPtr CreateMessage([MarshalAs(UnmanagedType.LPStr)] string @Message); [DllImport(libraryPath, EntryPoint = "LLVMDisposeMessage", CallingConvention = System.Runtime.InteropServices.CallingConvention.Cdecl, BestFitMapping = false, ThrowOnUnmappableChar = true)] internal static extern void DisposeMessage(IntPtr @Message); [DllImport(libraryPath, EntryPoint = "LLVMInstallFatalErrorHandler", CallingConvention = System.Runtime.InteropServices.CallingConvention.Cdecl, BestFitMapping = false, ThrowOnUnmappableChar = true)] internal static extern void InstallFatalErrorHandler(LLVMFatalErrorHandler @Handler); [DllImport(libraryPath, EntryPoint = "LLVMResetFatalErrorHandler", CallingConvention = System.Runtime.InteropServices.CallingConvention.Cdecl, BestFitMapping = false, ThrowOnUnmappableChar = true)] internal static extern void ResetFatalErrorHandler(); [DllImport(libraryPath, EntryPoint = "LLVMEnablePrettyStackTrace", CallingConvention = System.Runtime.InteropServices.CallingConvention.Cdecl, BestFitMapping = false, ThrowOnUnmappableChar = true)] internal static extern void EnablePrettyStackTrace(); [DllImport(libraryPath, EntryPoint = "LLVMContextCreate", CallingConvention = System.Runtime.InteropServices.CallingConvention.Cdecl, BestFitMapping = false, ThrowOnUnmappableChar = true)] internal static extern LLVMContextRef ContextCreate(); [DllImport(libraryPath, EntryPoint = "LLVMGetGlobalContext", CallingConvention = System.Runtime.InteropServices.CallingConvention.Cdecl, BestFitMapping = false, ThrowOnUnmappableChar = true)] internal static extern LLVMContextRef GetGlobalContext(); [DllImport(libraryPath, EntryPoint = "LLVMContextSetDiagnosticHandler", CallingConvention = System.Runtime.InteropServices.CallingConvention.Cdecl, BestFitMapping = false, ThrowOnUnmappableChar = true)] internal static extern void ContextSetDiagnosticHandler(LLVMContextRef @C, LLVMDiagnosticHandler @Handler, IntPtr @DiagnosticContext); [DllImport(libraryPath, EntryPoint = "LLVMContextSetYieldCallback", CallingConvention = System.Runtime.InteropServices.CallingConvention.Cdecl, BestFitMapping = false, ThrowOnUnmappableChar = true)] internal static extern void ContextSetYieldCallback(LLVMContextRef @C, LLVMYieldCallback @Callback, IntPtr @OpaqueHandle); [DllImport(libraryPath, EntryPoint = "LLVMContextDispose", CallingConvention = System.Runtime.InteropServices.CallingConvention.Cdecl, BestFitMapping = false, ThrowOnUnmappableChar = true)] internal static extern void ContextDispose(LLVMContextRef @C); [DllImport(libraryPath, EntryPoint = "LLVMGetDiagInfoDescription", CallingConvention = System.Runtime.InteropServices.CallingConvention.Cdecl, BestFitMapping = false, ThrowOnUnmappableChar = true)] internal static extern IntPtr GetDiagInfoDescription(LLVMDiagnosticInfoRef @DI); [DllImport(libraryPath, EntryPoint = "LLVMGetDiagInfoSeverity", CallingConvention = System.Runtime.InteropServices.CallingConvention.Cdecl, BestFitMapping = false, ThrowOnUnmappableChar = true)] internal static extern LLVMDiagnosticSeverity GetDiagInfoSeverity(LLVMDiagnosticInfoRef @DI); [DllImport(libraryPath, EntryPoint = "LLVMGetMDKindIDInContext", CallingConvention = System.Runtime.InteropServices.CallingConvention.Cdecl, BestFitMapping = false, ThrowOnUnmappableChar = true)] internal static extern uint GetMDKindIDInContext(LLVMContextRef @C, [MarshalAs(UnmanagedType.LPStr)] string @Name, uint @SLen); [DllImport(libraryPath, EntryPoint = "LLVMGetMDKindID", CallingConvention = System.Runtime.InteropServices.CallingConvention.Cdecl, BestFitMapping = false, ThrowOnUnmappableChar = true)] internal static extern uint GetMDKindID([MarshalAs(UnmanagedType.LPStr)] string @Name, uint @SLen); [DllImport(libraryPath, EntryPoint = "LLVMModuleCreateWithName", CallingConvention = System.Runtime.InteropServices.CallingConvention.Cdecl, BestFitMapping = false, ThrowOnUnmappableChar = true)] internal static extern LLVMModuleRef ModuleCreateWithName([MarshalAs(UnmanagedType.LPStr)] string @ModuleID); [DllImport(libraryPath, EntryPoint = "LLVMModuleCreateWithNameInContext", CallingConvention = System.Runtime.InteropServices.CallingConvention.Cdecl, BestFitMapping = false, ThrowOnUnmappableChar = true)] internal static extern LLVMModuleRef ModuleCreateWithNameInContext([MarshalAs(UnmanagedType.LPStr)] string @ModuleID, LLVMContextRef @C); [DllImport(libraryPath, EntryPoint = "LLVMCloneModule", CallingConvention = System.Runtime.InteropServices.CallingConvention.Cdecl, BestFitMapping = false, ThrowOnUnmappableChar = true)] internal static extern LLVMModuleRef CloneModule(LLVMModuleRef @M); [DllImport(libraryPath, EntryPoint = "LLVMDisposeModule", CallingConvention = System.Runtime.InteropServices.CallingConvention.Cdecl, BestFitMapping = false, ThrowOnUnmappableChar = true)] internal static extern void DisposeModule(LLVMModuleRef @M); [DllImport(libraryPath, EntryPoint = "LLVMGetDataLayout", CallingConvention = System.Runtime.InteropServices.CallingConvention.Cdecl, BestFitMapping = false, ThrowOnUnmappableChar = true)] internal static extern IntPtr GetDataLayout(LLVMModuleRef @M); [DllImport(libraryPath, EntryPoint = "LLVMSetDataLayout", CallingConvention = System.Runtime.InteropServices.CallingConvention.Cdecl, BestFitMapping = false, ThrowOnUnmappableChar = true)] internal static extern void SetDataLayout(LLVMModuleRef @M, [MarshalAs(UnmanagedType.LPStr)] string @Triple); [DllImport(libraryPath, EntryPoint = "LLVMGetTarget", CallingConvention = System.Runtime.InteropServices.CallingConvention.Cdecl, BestFitMapping = false, ThrowOnUnmappableChar = true)] internal static extern IntPtr GetTarget(LLVMModuleRef @M); [DllImport(libraryPath, EntryPoint = "LLVMSetTarget", CallingConvention = System.Runtime.InteropServices.CallingConvention.Cdecl, BestFitMapping = false, ThrowOnUnmappableChar = true)] internal static extern void SetTarget(LLVMModuleRef @M, [MarshalAs(UnmanagedType.LPStr)] string @Triple); [DllImport(libraryPath, EntryPoint = "LLVMDumpModule", CallingConvention = System.Runtime.InteropServices.CallingConvention.Cdecl, BestFitMapping = false, ThrowOnUnmappableChar = true)] internal static extern void DumpModule(LLVMModuleRef @M); [DllImport(libraryPath, EntryPoint = "LLVMPrintModuleToFile", CallingConvention = System.Runtime.InteropServices.CallingConvention.Cdecl, BestFitMapping = false, ThrowOnUnmappableChar = true)] internal static extern LLVMBool PrintModuleToFile(LLVMModuleRef @M, [MarshalAs(UnmanagedType.LPStr)] string @Filename, out IntPtr @ErrorMessage); [DllImport(libraryPath, EntryPoint = "LLVMPrintModuleToString", CallingConvention = System.Runtime.InteropServices.CallingConvention.Cdecl, BestFitMapping = false, ThrowOnUnmappableChar = true)] internal static extern IntPtr PrintModuleToString(LLVMModuleRef @M); [DllImport(libraryPath, EntryPoint = "LLVMSetModuleInlineAsm", CallingConvention = System.Runtime.InteropServices.CallingConvention.Cdecl, BestFitMapping = false, ThrowOnUnmappableChar = true)] internal static extern void SetModuleInlineAsm(LLVMModuleRef @M, [MarshalAs(UnmanagedType.LPStr)] string @Asm); [DllImport(libraryPath, EntryPoint = "LLVMGetModuleContext", CallingConvention = System.Runtime.InteropServices.CallingConvention.Cdecl, BestFitMapping = false, ThrowOnUnmappableChar = true)] internal static extern LLVMContextRef GetModuleContext(LLVMModuleRef @M); [DllImport(libraryPath, EntryPoint = "LLVMGetTypeByName", CallingConvention = System.Runtime.InteropServices.CallingConvention.Cdecl, BestFitMapping = false, ThrowOnUnmappableChar = true)] internal static extern LLVMTypeRef GetTypeByName(LLVMModuleRef @M, [MarshalAs(UnmanagedType.LPStr)] string @Name); [DllImport(libraryPath, EntryPoint = "LLVMGetNamedMetadataNumOperands", CallingConvention = System.Runtime.InteropServices.CallingConvention.Cdecl, BestFitMapping = false, ThrowOnUnmappableChar = true)] internal static extern uint GetNamedMetadataNumOperands(LLVMModuleRef @M, [MarshalAs(UnmanagedType.LPStr)] string @name); [DllImport(libraryPath, EntryPoint = "LLVMGetNamedMetadataOperands", CallingConvention = System.Runtime.InteropServices.CallingConvention.Cdecl, BestFitMapping = false, ThrowOnUnmappableChar = true)] internal static extern void GetNamedMetadataOperands(LLVMModuleRef @M, [MarshalAs(UnmanagedType.LPStr)] string @name, out LLVMValueRef @Dest); [DllImport(libraryPath, EntryPoint = "LLVMAddNamedMetadataOperand", CallingConvention = System.Runtime.InteropServices.CallingConvention.Cdecl, BestFitMapping = false, ThrowOnUnmappableChar = true)] internal static extern void AddNamedMetadataOperand(LLVMModuleRef @M, [MarshalAs(UnmanagedType.LPStr)] string @name, LLVMValueRef @Val); [DllImport(libraryPath, EntryPoint = "LLVMAddFunction", CallingConvention = System.Runtime.InteropServices.CallingConvention.Cdecl, BestFitMapping = false, ThrowOnUnmappableChar = true)] internal static extern LLVMValueRef AddFunction(LLVMModuleRef @M, [MarshalAs(UnmanagedType.LPStr)] string @Name, LLVMTypeRef @FunctionTy); [DllImport(libraryPath, EntryPoint = "LLVMGetNamedFunction", CallingConvention = System.Runtime.InteropServices.CallingConvention.Cdecl, BestFitMapping = false, ThrowOnUnmappableChar = true)] internal static extern LLVMValueRef GetNamedFunction(LLVMModuleRef @M, [MarshalAs(UnmanagedType.LPStr)] string @Name); [DllImport(libraryPath, EntryPoint = "LLVMGetFirstFunction", CallingConvention = System.Runtime.InteropServices.CallingConvention.Cdecl, BestFitMapping = false, ThrowOnUnmappableChar = true)] internal static extern LLVMValueRef GetFirstFunction(LLVMModuleRef @M); [DllImport(libraryPath, EntryPoint = "LLVMGetLastFunction", CallingConvention = System.Runtime.InteropServices.CallingConvention.Cdecl, BestFitMapping = false, ThrowOnUnmappableChar = true)] internal static extern LLVMValueRef GetLastFunction(LLVMModuleRef @M); [DllImport(libraryPath, EntryPoint = "LLVMGetNextFunction", CallingConvention = System.Runtime.InteropServices.CallingConvention.Cdecl, BestFitMapping = false, ThrowOnUnmappableChar = true)] internal static extern LLVMValueRef GetNextFunction(LLVMValueRef @Fn); [DllImport(libraryPath, EntryPoint = "LLVMGetPreviousFunction", CallingConvention = System.Runtime.InteropServices.CallingConvention.Cdecl, BestFitMapping = false, ThrowOnUnmappableChar = true)] internal static extern LLVMValueRef GetPreviousFunction(LLVMValueRef @Fn); [DllImport(libraryPath, EntryPoint = "LLVMGetTypeKind", CallingConvention = System.Runtime.InteropServices.CallingConvention.Cdecl, BestFitMapping = false, ThrowOnUnmappableChar = true)] internal static extern LLVMTypeKind GetTypeKind(LLVMTypeRef @Ty); [DllImport(libraryPath, EntryPoint = "LLVMTypeIsSized", CallingConvention = System.Runtime.InteropServices.CallingConvention.Cdecl, BestFitMapping = false, ThrowOnUnmappableChar = true)] internal static extern LLVMBool TypeIsSized(LLVMTypeRef @Ty); [DllImport(libraryPath, EntryPoint = "LLVMGetTypeContext", CallingConvention = System.Runtime.InteropServices.CallingConvention.Cdecl, BestFitMapping = false, ThrowOnUnmappableChar = true)] internal static extern LLVMContextRef GetTypeContext(LLVMTypeRef @Ty); [DllImport(libraryPath, EntryPoint = "LLVMDumpType", CallingConvention = System.Runtime.InteropServices.CallingConvention.Cdecl, BestFitMapping = false, ThrowOnUnmappableChar = true)] internal static extern void DumpType(LLVMTypeRef @Val); [DllImport(libraryPath, EntryPoint = "LLVMPrintTypeToString", CallingConvention = System.Runtime.InteropServices.CallingConvention.Cdecl, BestFitMapping = false, ThrowOnUnmappableChar = true)] internal static extern IntPtr PrintTypeToString(LLVMTypeRef @Val); [DllImport(libraryPath, EntryPoint = "LLVMInt1TypeInContext", CallingConvention = System.Runtime.InteropServices.CallingConvention.Cdecl, BestFitMapping = false, ThrowOnUnmappableChar = true)] internal static extern LLVMTypeRef Int1TypeInContext(LLVMContextRef @C); [DllImport(libraryPath, EntryPoint = "LLVMInt8TypeInContext", CallingConvention = System.Runtime.InteropServices.CallingConvention.Cdecl, BestFitMapping = false, ThrowOnUnmappableChar = true)] internal static extern LLVMTypeRef Int8TypeInContext(LLVMContextRef @C); [DllImport(libraryPath, EntryPoint = "LLVMInt16TypeInContext", CallingConvention = System.Runtime.InteropServices.CallingConvention.Cdecl, BestFitMapping = false, ThrowOnUnmappableChar = true)] internal static extern LLVMTypeRef Int16TypeInContext(LLVMContextRef @C); [DllImport(libraryPath, EntryPoint = "LLVMInt32TypeInContext", CallingConvention = System.Runtime.InteropServices.CallingConvention.Cdecl, BestFitMapping = false, ThrowOnUnmappableChar = true)] internal static extern LLVMTypeRef Int32TypeInContext(LLVMContextRef @C); [DllImport(libraryPath, EntryPoint = "LLVMInt64TypeInContext", CallingConvention = System.Runtime.InteropServices.CallingConvention.Cdecl, BestFitMapping = false, ThrowOnUnmappableChar = true)] internal static extern LLVMTypeRef Int64TypeInContext(LLVMContextRef @C); [DllImport(libraryPath, EntryPoint = "LLVMIntTypeInContext", CallingConvention = System.Runtime.InteropServices.CallingConvention.Cdecl, BestFitMapping = false, ThrowOnUnmappableChar = true)] internal static extern LLVMTypeRef IntTypeInContext(LLVMContextRef @C, uint @NumBits); [DllImport(libraryPath, EntryPoint = "LLVMInt1Type", CallingConvention = System.Runtime.InteropServices.CallingConvention.Cdecl, BestFitMapping = false, ThrowOnUnmappableChar = true)] internal static extern LLVMTypeRef Int1Type(); [DllImport(libraryPath, EntryPoint = "LLVMInt8Type", CallingConvention = System.Runtime.InteropServices.CallingConvention.Cdecl, BestFitMapping = false, ThrowOnUnmappableChar = true)] internal static extern LLVMTypeRef Int8Type(); [DllImport(libraryPath, EntryPoint = "LLVMInt16Type", CallingConvention = System.Runtime.InteropServices.CallingConvention.Cdecl, BestFitMapping = false, ThrowOnUnmappableChar = true)] internal static extern LLVMTypeRef Int16Type(); [DllImport(libraryPath, EntryPoint = "LLVMInt32Type", CallingConvention = System.Runtime.InteropServices.CallingConvention.Cdecl, BestFitMapping = false, ThrowOnUnmappableChar = true)] internal static extern LLVMTypeRef Int32Type(); [DllImport(libraryPath, EntryPoint = "LLVMInt64Type", CallingConvention = System.Runtime.InteropServices.CallingConvention.Cdecl, BestFitMapping = false, ThrowOnUnmappableChar = true)] internal static extern LLVMTypeRef Int64Type(); [DllImport(libraryPath, EntryPoint = "LLVMIntType", CallingConvention = System.Runtime.InteropServices.CallingConvention.Cdecl, BestFitMapping = false, ThrowOnUnmappableChar = true)] internal static extern LLVMTypeRef IntType(uint @NumBits); [DllImport(libraryPath, EntryPoint = "LLVMGetIntTypeWidth", CallingConvention = System.Runtime.InteropServices.CallingConvention.Cdecl, BestFitMapping = false, ThrowOnUnmappableChar = true)] internal static extern uint GetIntTypeWidth(LLVMTypeRef @IntegerTy); [DllImport(libraryPath, EntryPoint = "LLVMHalfTypeInContext", CallingConvention = System.Runtime.InteropServices.CallingConvention.Cdecl, BestFitMapping = false, ThrowOnUnmappableChar = true)] internal static extern LLVMTypeRef HalfTypeInContext(LLVMContextRef @C); [DllImport(libraryPath, EntryPoint = "LLVMFloatTypeInContext", CallingConvention = System.Runtime.InteropServices.CallingConvention.Cdecl, BestFitMapping = false, ThrowOnUnmappableChar = true)] internal static extern LLVMTypeRef FloatTypeInContext(LLVMContextRef @C); [DllImport(libraryPath, EntryPoint = "LLVMDoubleTypeInContext", CallingConvention = System.Runtime.InteropServices.CallingConvention.Cdecl, BestFitMapping = false, ThrowOnUnmappableChar = true)] internal static extern LLVMTypeRef DoubleTypeInContext(LLVMContextRef @C); [DllImport(libraryPath, EntryPoint = "LLVMX86FP80TypeInContext", CallingConvention = System.Runtime.InteropServices.CallingConvention.Cdecl, BestFitMapping = false, ThrowOnUnmappableChar = true)] internal static extern LLVMTypeRef X86FP80TypeInContext(LLVMContextRef @C); [DllImport(libraryPath, EntryPoint = "LLVMFP128TypeInContext", CallingConvention = System.Runtime.InteropServices.CallingConvention.Cdecl, BestFitMapping = false, ThrowOnUnmappableChar = true)] internal static extern LLVMTypeRef FP128TypeInContext(LLVMContextRef @C); [DllImport(libraryPath, EntryPoint = "LLVMPPCFP128TypeInContext", CallingConvention = System.Runtime.InteropServices.CallingConvention.Cdecl, BestFitMapping = false, ThrowOnUnmappableChar = true)] internal static extern LLVMTypeRef PPCFP128TypeInContext(LLVMContextRef @C); [DllImport(libraryPath, EntryPoint = "LLVMHalfType", CallingConvention = System.Runtime.InteropServices.CallingConvention.Cdecl, BestFitMapping = false, ThrowOnUnmappableChar = true)] internal static extern LLVMTypeRef HalfType(); [DllImport(libraryPath, EntryPoint = "LLVMFloatType", CallingConvention = System.Runtime.InteropServices.CallingConvention.Cdecl, BestFitMapping = false, ThrowOnUnmappableChar = true)] internal static extern LLVMTypeRef FloatType(); [DllImport(libraryPath, EntryPoint = "LLVMDoubleType", CallingConvention = System.Runtime.InteropServices.CallingConvention.Cdecl, BestFitMapping = false, ThrowOnUnmappableChar = true)] internal static extern LLVMTypeRef DoubleType(); [DllImport(libraryPath, EntryPoint = "LLVMX86FP80Type", CallingConvention = System.Runtime.InteropServices.CallingConvention.Cdecl, BestFitMapping = false, ThrowOnUnmappableChar = true)] internal static extern LLVMTypeRef X86FP80Type(); [DllImport(libraryPath, EntryPoint = "LLVMFP128Type", CallingConvention = System.Runtime.InteropServices.CallingConvention.Cdecl, BestFitMapping = false, ThrowOnUnmappableChar = true)] internal static extern LLVMTypeRef FP128Type(); [DllImport(libraryPath, EntryPoint = "LLVMPPCFP128Type", CallingConvention = System.Runtime.InteropServices.CallingConvention.Cdecl, BestFitMapping = false, ThrowOnUnmappableChar = true)] internal static extern LLVMTypeRef PPCFP128Type(); [DllImport(libraryPath, EntryPoint = "LLVMFunctionType", CallingConvention = System.Runtime.InteropServices.CallingConvention.Cdecl, BestFitMapping = false, ThrowOnUnmappableChar = true)] internal static extern LLVMTypeRef FunctionType(LLVMTypeRef @ReturnType, out LLVMTypeRef @ParamTypes, uint @ParamCount, LLVMBool @IsVarArg); [DllImport(libraryPath, EntryPoint = "LLVMIsFunctionVarArg", CallingConvention = System.Runtime.InteropServices.CallingConvention.Cdecl, BestFitMapping = false, ThrowOnUnmappableChar = true)] internal static extern LLVMBool IsFunctionVarArg(LLVMTypeRef @FunctionTy); [DllImport(libraryPath, EntryPoint = "LLVMGetReturnType", CallingConvention = System.Runtime.InteropServices.CallingConvention.Cdecl, BestFitMapping = false, ThrowOnUnmappableChar = true)] internal static extern LLVMTypeRef GetReturnType(LLVMTypeRef @FunctionTy); [DllImport(libraryPath, EntryPoint = "LLVMCountParamTypes", CallingConvention = System.Runtime.InteropServices.CallingConvention.Cdecl, BestFitMapping = false, ThrowOnUnmappableChar = true)] internal static extern uint CountParamTypes(LLVMTypeRef @FunctionTy); [DllImport(libraryPath, EntryPoint = "LLVMGetParamTypes", CallingConvention = System.Runtime.InteropServices.CallingConvention.Cdecl, BestFitMapping = false, ThrowOnUnmappableChar = true)] internal static extern void GetParamTypes(LLVMTypeRef @FunctionTy, out LLVMTypeRef @Dest); [DllImport(libraryPath, EntryPoint = "LLVMStructTypeInContext", CallingConvention = System.Runtime.InteropServices.CallingConvention.Cdecl, BestFitMapping = false, ThrowOnUnmappableChar = true)] internal static extern LLVMTypeRef StructTypeInContext(LLVMContextRef @C, out LLVMTypeRef @ElementTypes, uint @ElementCount, LLVMBool @Packed); [DllImport(libraryPath, EntryPoint = "LLVMStructType", CallingConvention = System.Runtime.InteropServices.CallingConvention.Cdecl, BestFitMapping = false, ThrowOnUnmappableChar = true)] internal static extern LLVMTypeRef StructType(out LLVMTypeRef @ElementTypes, uint @ElementCount, LLVMBool @Packed); [DllImport(libraryPath, EntryPoint = "LLVMStructCreateNamed", CallingConvention = System.Runtime.InteropServices.CallingConvention.Cdecl, BestFitMapping = false, ThrowOnUnmappableChar = true)] internal static extern LLVMTypeRef StructCreateNamed(LLVMContextRef @C, [MarshalAs(UnmanagedType.LPStr)] string @Name); [DllImport(libraryPath, EntryPoint = "LLVMGetStructName", CallingConvention = System.Runtime.InteropServices.CallingConvention.Cdecl, BestFitMapping = false, ThrowOnUnmappableChar = true)] internal static extern IntPtr GetStructName(LLVMTypeRef @Ty); [DllImport(libraryPath, EntryPoint = "LLVMStructSetBody", CallingConvention = System.Runtime.InteropServices.CallingConvention.Cdecl, BestFitMapping = false, ThrowOnUnmappableChar = true)] internal static extern void StructSetBody(LLVMTypeRef @StructTy, out LLVMTypeRef @ElementTypes, uint @ElementCount, LLVMBool @Packed); [DllImport(libraryPath, EntryPoint = "LLVMCountStructElementTypes", CallingConvention = System.Runtime.InteropServices.CallingConvention.Cdecl, BestFitMapping = false, ThrowOnUnmappableChar = true)] internal static extern uint CountStructElementTypes(LLVMTypeRef @StructTy); [DllImport(libraryPath, EntryPoint = "LLVMGetStructElementTypes", CallingConvention = System.Runtime.InteropServices.CallingConvention.Cdecl, BestFitMapping = false, ThrowOnUnmappableChar = true)] internal static extern void GetStructElementTypes(LLVMTypeRef @StructTy, out LLVMTypeRef @Dest); [DllImport(libraryPath, EntryPoint = "LLVMIsPackedStruct", CallingConvention = System.Runtime.InteropServices.CallingConvention.Cdecl, BestFitMapping = false, ThrowOnUnmappableChar = true)] internal static extern LLVMBool IsPackedStruct(LLVMTypeRef @StructTy); [DllImport(libraryPath, EntryPoint = "LLVMIsOpaqueStruct", CallingConvention = System.Runtime.InteropServices.CallingConvention.Cdecl, BestFitMapping = false, ThrowOnUnmappableChar = true)] internal static extern LLVMBool IsOpaqueStruct(LLVMTypeRef @StructTy); [DllImport(libraryPath, EntryPoint = "LLVMGetElementType", CallingConvention = System.Runtime.InteropServices.CallingConvention.Cdecl, BestFitMapping = false, ThrowOnUnmappableChar = true)] internal static extern LLVMTypeRef GetElementType(LLVMTypeRef @Ty); [DllImport(libraryPath, EntryPoint = "LLVMArrayType", CallingConvention = System.Runtime.InteropServices.CallingConvention.Cdecl, BestFitMapping = false, ThrowOnUnmappableChar = true)] internal static extern LLVMTypeRef ArrayType(LLVMTypeRef @ElementType, uint @ElementCount); [DllImport(libraryPath, EntryPoint = "LLVMGetArrayLength", CallingConvention = System.Runtime.InteropServices.CallingConvention.Cdecl, BestFitMapping = false, ThrowOnUnmappableChar = true)] internal static extern uint GetArrayLength(LLVMTypeRef @ArrayTy); [DllImport(libraryPath, EntryPoint = "LLVMPointerType", CallingConvention = System.Runtime.InteropServices.CallingConvention.Cdecl, BestFitMapping = false, ThrowOnUnmappableChar = true)] internal static extern LLVMTypeRef PointerType(LLVMTypeRef @ElementType, uint @AddressSpace); [DllImport(libraryPath, EntryPoint = "LLVMGetPointerAddressSpace", CallingConvention = System.Runtime.InteropServices.CallingConvention.Cdecl, BestFitMapping = false, ThrowOnUnmappableChar = true)] internal static extern uint GetPointerAddressSpace(LLVMTypeRef @PointerTy); [DllImport(libraryPath, EntryPoint = "LLVMVectorType", CallingConvention = System.Runtime.InteropServices.CallingConvention.Cdecl, BestFitMapping = false, ThrowOnUnmappableChar = true)] internal static extern LLVMTypeRef VectorType(LLVMTypeRef @ElementType, uint @ElementCount); [DllImport(libraryPath, EntryPoint = "LLVMGetVectorSize", CallingConvention = System.Runtime.InteropServices.CallingConvention.Cdecl, BestFitMapping = false, ThrowOnUnmappableChar = true)] internal static extern uint GetVectorSize(LLVMTypeRef @VectorTy); [DllImport(libraryPath, EntryPoint = "LLVMVoidTypeInContext", CallingConvention = System.Runtime.InteropServices.CallingConvention.Cdecl, BestFitMapping = false, ThrowOnUnmappableChar = true)] internal static extern LLVMTypeRef VoidTypeInContext(LLVMContextRef @C); [DllImport(libraryPath, EntryPoint = "LLVMLabelTypeInContext", CallingConvention = System.Runtime.InteropServices.CallingConvention.Cdecl, BestFitMapping = false, ThrowOnUnmappableChar = true)] internal static extern LLVMTypeRef LabelTypeInContext(LLVMContextRef @C); [DllImport(libraryPath, EntryPoint = "LLVMX86MMXTypeInContext", CallingConvention = System.Runtime.InteropServices.CallingConvention.Cdecl, BestFitMapping = false, ThrowOnUnmappableChar = true)] internal static extern LLVMTypeRef X86MMXTypeInContext(LLVMContextRef @C); [DllImport(libraryPath, EntryPoint = "LLVMVoidType", CallingConvention = System.Runtime.InteropServices.CallingConvention.Cdecl, BestFitMapping = false, ThrowOnUnmappableChar = true)] internal static extern LLVMTypeRef VoidType(); [DllImport(libraryPath, EntryPoint = "LLVMLabelType", CallingConvention = System.Runtime.InteropServices.CallingConvention.Cdecl, BestFitMapping = false, ThrowOnUnmappableChar = true)] internal static extern LLVMTypeRef LabelType(); [DllImport(libraryPath, EntryPoint = "LLVMX86MMXType", CallingConvention = System.Runtime.InteropServices.CallingConvention.Cdecl, BestFitMapping = false, ThrowOnUnmappableChar = true)] internal static extern LLVMTypeRef X86MMXType(); [DllImport(libraryPath, EntryPoint = "LLVMTypeOf", CallingConvention = System.Runtime.InteropServices.CallingConvention.Cdecl, BestFitMapping = false, ThrowOnUnmappableChar = true)] internal static extern LLVMTypeRef TypeOf(LLVMValueRef @Val); [DllImport(libraryPath, EntryPoint = "LLVMGetValueName", CallingConvention = System.Runtime.InteropServices.CallingConvention.Cdecl, BestFitMapping = false, ThrowOnUnmappableChar = true)] internal static extern IntPtr GetValueName(LLVMValueRef @Val); [DllImport(libraryPath, EntryPoint = "LLVMSetValueName", CallingConvention = System.Runtime.InteropServices.CallingConvention.Cdecl, BestFitMapping = false, ThrowOnUnmappableChar = true)] internal static extern void SetValueName(LLVMValueRef @Val, [MarshalAs(UnmanagedType.LPStr)] string @Name); [DllImport(libraryPath, EntryPoint = "LLVMDumpValue", CallingConvention = System.Runtime.InteropServices.CallingConvention.Cdecl, BestFitMapping = false, ThrowOnUnmappableChar = true)] internal static extern void DumpValue(LLVMValueRef @Val); [DllImport(libraryPath, EntryPoint = "LLVMPrintValueToString", CallingConvention = System.Runtime.InteropServices.CallingConvention.Cdecl, BestFitMapping = false, ThrowOnUnmappableChar = true)] internal static extern IntPtr PrintValueToString(LLVMValueRef @Val); [DllImport(libraryPath, EntryPoint = "LLVMReplaceAllUsesWith", CallingConvention = System.Runtime.InteropServices.CallingConvention.Cdecl, BestFitMapping = false, ThrowOnUnmappableChar = true)] internal static extern void ReplaceAllUsesWith(LLVMValueRef @OldVal, LLVMValueRef @NewVal); [DllImport(libraryPath, EntryPoint = "LLVMIsConstant", CallingConvention = System.Runtime.InteropServices.CallingConvention.Cdecl, BestFitMapping = false, ThrowOnUnmappableChar = true)] internal static extern LLVMBool IsConstant(LLVMValueRef @Val); [DllImport(libraryPath, EntryPoint = "LLVMIsUndef", CallingConvention = System.Runtime.InteropServices.CallingConvention.Cdecl, BestFitMapping = false, ThrowOnUnmappableChar = true)] internal static extern LLVMBool IsUndef(LLVMValueRef @Val); [DllImport(libraryPath, EntryPoint = "LLVMIsAArgument", CallingConvention = System.Runtime.InteropServices.CallingConvention.Cdecl, BestFitMapping = false, ThrowOnUnmappableChar = true)] internal static extern LLVMValueRef IsAArgument(LLVMValueRef @Val); [DllImport(libraryPath, EntryPoint = "LLVMIsABasicBlock", CallingConvention = System.Runtime.InteropServices.CallingConvention.Cdecl, BestFitMapping = false, ThrowOnUnmappableChar = true)] internal static extern LLVMValueRef IsABasicBlock(LLVMValueRef @Val); [DllImport(libraryPath, EntryPoint = "LLVMIsAInlineAsm", CallingConvention = System.Runtime.InteropServices.CallingConvention.Cdecl, BestFitMapping = false, ThrowOnUnmappableChar = true)] internal static extern LLVMValueRef IsAInlineAsm(LLVMValueRef @Val); [DllImport(libraryPath, EntryPoint = "LLVMIsAUser", CallingConvention = System.Runtime.InteropServices.CallingConvention.Cdecl, BestFitMapping = false, ThrowOnUnmappableChar = true)] internal static extern LLVMValueRef IsAUser(LLVMValueRef @Val); [DllImport(libraryPath, EntryPoint = "LLVMIsAConstant", CallingConvention = System.Runtime.InteropServices.CallingConvention.Cdecl, BestFitMapping = false, ThrowOnUnmappableChar = true)] internal static extern LLVMValueRef IsAConstant(LLVMValueRef @Val); [DllImport(libraryPath, EntryPoint = "LLVMIsABlockAddress", CallingConvention = System.Runtime.InteropServices.CallingConvention.Cdecl, BestFitMapping = false, ThrowOnUnmappableChar = true)] internal static extern LLVMValueRef IsABlockAddress(LLVMValueRef @Val); [DllImport(libraryPath, EntryPoint = "LLVMIsAConstantAggregateZero", CallingConvention = System.Runtime.InteropServices.CallingConvention.Cdecl, BestFitMapping = false, ThrowOnUnmappableChar = true)] internal static extern LLVMValueRef IsAConstantAggregateZero(LLVMValueRef @Val); [DllImport(libraryPath, EntryPoint = "LLVMIsAConstantArray", CallingConvention = System.Runtime.InteropServices.CallingConvention.Cdecl, BestFitMapping = false, ThrowOnUnmappableChar = true)] internal static extern LLVMValueRef IsAConstantArray(LLVMValueRef @Val); [DllImport(libraryPath, EntryPoint = "LLVMIsAConstantDataSequential", CallingConvention = System.Runtime.InteropServices.CallingConvention.Cdecl, BestFitMapping = false, ThrowOnUnmappableChar = true)] internal static extern LLVMValueRef IsAConstantDataSequential(LLVMValueRef @Val); [DllImport(libraryPath, EntryPoint = "LLVMIsAConstantDataArray", CallingConvention = System.Runtime.InteropServices.CallingConvention.Cdecl, BestFitMapping = false, ThrowOnUnmappableChar = true)] internal static extern LLVMValueRef IsAConstantDataArray(LLVMValueRef @Val); [DllImport(libraryPath, EntryPoint = "LLVMIsAConstantDataVector", CallingConvention = System.Runtime.InteropServices.CallingConvention.Cdecl, BestFitMapping = false, ThrowOnUnmappableChar = true)] internal static extern LLVMValueRef IsAConstantDataVector(LLVMValueRef @Val); [DllImport(libraryPath, EntryPoint = "LLVMIsAConstantExpr", CallingConvention = System.Runtime.InteropServices.CallingConvention.Cdecl, BestFitMapping = false, ThrowOnUnmappableChar = true)] internal static extern LLVMValueRef IsAConstantExpr(LLVMValueRef @Val); [DllImport(libraryPath, EntryPoint = "LLVMIsAConstantFP", CallingConvention = System.Runtime.InteropServices.CallingConvention.Cdecl, BestFitMapping = false, ThrowOnUnmappableChar = true)] internal static extern LLVMValueRef IsAConstantFP(LLVMValueRef @Val); [DllImport(libraryPath, EntryPoint = "LLVMIsAConstantInt", CallingConvention = System.Runtime.InteropServices.CallingConvention.Cdecl, BestFitMapping = false, ThrowOnUnmappableChar = true)] internal static extern LLVMValueRef IsAConstantInt(LLVMValueRef @Val); [DllImport(libraryPath, EntryPoint = "LLVMIsAConstantPointerNull", CallingConvention = System.Runtime.InteropServices.CallingConvention.Cdecl, BestFitMapping = false, ThrowOnUnmappableChar = true)] internal static extern LLVMValueRef IsAConstantPointerNull(LLVMValueRef @Val); [DllImport(libraryPath, EntryPoint = "LLVMIsAConstantStruct", CallingConvention = System.Runtime.InteropServices.CallingConvention.Cdecl, BestFitMapping = false, ThrowOnUnmappableChar = true)] internal static extern LLVMValueRef IsAConstantStruct(LLVMValueRef @Val); [DllImport(libraryPath, EntryPoint = "LLVMIsAConstantVector", CallingConvention = System.Runtime.InteropServices.CallingConvention.Cdecl, BestFitMapping = false, ThrowOnUnmappableChar = true)] internal static extern LLVMValueRef IsAConstantVector(LLVMValueRef @Val); [DllImport(libraryPath, EntryPoint = "LLVMIsAGlobalValue", CallingConvention = System.Runtime.InteropServices.CallingConvention.Cdecl, BestFitMapping = false, ThrowOnUnmappableChar = true)] internal static extern LLVMValueRef IsAGlobalValue(LLVMValueRef @Val); [DllImport(libraryPath, EntryPoint = "LLVMIsAGlobalAlias", CallingConvention = System.Runtime.InteropServices.CallingConvention.Cdecl, BestFitMapping = false, ThrowOnUnmappableChar = true)] internal static extern LLVMValueRef IsAGlobalAlias(LLVMValueRef @Val); [DllImport(libraryPath, EntryPoint = "LLVMIsAGlobalObject", CallingConvention = System.Runtime.InteropServices.CallingConvention.Cdecl, BestFitMapping = false, ThrowOnUnmappableChar = true)] internal static extern LLVMValueRef IsAGlobalObject(LLVMValueRef @Val); [DllImport(libraryPath, EntryPoint = "LLVMIsAFunction", CallingConvention = System.Runtime.InteropServices.CallingConvention.Cdecl, BestFitMapping = false, ThrowOnUnmappableChar = true)] internal static extern LLVMValueRef IsAFunction(LLVMValueRef @Val); [DllImport(libraryPath, EntryPoint = "LLVMIsAGlobalVariable", CallingConvention = System.Runtime.InteropServices.CallingConvention.Cdecl, BestFitMapping = false, ThrowOnUnmappableChar = true)] internal static extern LLVMValueRef IsAGlobalVariable(LLVMValueRef @Val); [DllImport(libraryPath, EntryPoint = "LLVMIsAUndefValue", CallingConvention = System.Runtime.InteropServices.CallingConvention.Cdecl, BestFitMapping = false, ThrowOnUnmappableChar = true)] internal static extern LLVMValueRef IsAUndefValue(LLVMValueRef @Val); [DllImport(libraryPath, EntryPoint = "LLVMIsAInstruction", CallingConvention = System.Runtime.InteropServices.CallingConvention.Cdecl, BestFitMapping = false, ThrowOnUnmappableChar = true)] internal static extern LLVMValueRef IsAInstruction(LLVMValueRef @Val); [DllImport(libraryPath, EntryPoint = "LLVMIsABinaryOperator", CallingConvention = System.Runtime.InteropServices.CallingConvention.Cdecl, BestFitMapping = false, ThrowOnUnmappableChar = true)] internal static extern LLVMValueRef IsABinaryOperator(LLVMValueRef @Val); [DllImport(libraryPath, EntryPoint = "LLVMIsACallInst", CallingConvention = System.Runtime.InteropServices.CallingConvention.Cdecl, BestFitMapping = false, ThrowOnUnmappableChar = true)] internal static extern LLVMValueRef IsACallInst(LLVMValueRef @Val); [DllImport(libraryPath, EntryPoint = "LLVMIsAIntrinsicInst", CallingConvention = System.Runtime.InteropServices.CallingConvention.Cdecl, BestFitMapping = false, ThrowOnUnmappableChar = true)] internal static extern LLVMValueRef IsAIntrinsicInst(LLVMValueRef @Val); [DllImport(libraryPath, EntryPoint = "LLVMIsADbgInfoIntrinsic", CallingConvention = System.Runtime.InteropServices.CallingConvention.Cdecl, BestFitMapping = false, ThrowOnUnmappableChar = true)] internal static extern LLVMValueRef IsADbgInfoIntrinsic(LLVMValueRef @Val); [DllImport(libraryPath, EntryPoint = "LLVMIsADbgDeclareInst", CallingConvention = System.Runtime.InteropServices.CallingConvention.Cdecl, BestFitMapping = false, ThrowOnUnmappableChar = true)] internal static extern LLVMValueRef IsADbgDeclareInst(LLVMValueRef @Val); [DllImport(libraryPath, EntryPoint = "LLVMIsAMemIntrinsic", CallingConvention = System.Runtime.InteropServices.CallingConvention.Cdecl, BestFitMapping = false, ThrowOnUnmappableChar = true)] internal static extern LLVMValueRef IsAMemIntrinsic(LLVMValueRef @Val); [DllImport(libraryPath, EntryPoint = "LLVMIsAMemCpyInst", CallingConvention = System.Runtime.InteropServices.CallingConvention.Cdecl, BestFitMapping = false, ThrowOnUnmappableChar = true)] internal static extern LLVMValueRef IsAMemCpyInst(LLVMValueRef @Val); [DllImport(libraryPath, EntryPoint = "LLVMIsAMemMoveInst", CallingConvention = System.Runtime.InteropServices.CallingConvention.Cdecl, BestFitMapping = false, ThrowOnUnmappableChar = true)] internal static extern LLVMValueRef IsAMemMoveInst(LLVMValueRef @Val); [DllImport(libraryPath, EntryPoint = "LLVMIsAMemSetInst", CallingConvention = System.Runtime.InteropServices.CallingConvention.Cdecl, BestFitMapping = false, ThrowOnUnmappableChar = true)] internal static extern LLVMValueRef IsAMemSetInst(LLVMValueRef @Val); [DllImport(libraryPath, EntryPoint = "LLVMIsACmpInst", CallingConvention = System.Runtime.InteropServices.CallingConvention.Cdecl, BestFitMapping = false, ThrowOnUnmappableChar = true)] internal static extern LLVMValueRef IsACmpInst(LLVMValueRef @Val); [DllImport(libraryPath, EntryPoint = "LLVMIsAFCmpInst", CallingConvention = System.Runtime.InteropServices.CallingConvention.Cdecl, BestFitMapping = false, ThrowOnUnmappableChar = true)] internal static extern LLVMValueRef IsAFCmpInst(LLVMValueRef @Val); [DllImport(libraryPath, EntryPoint = "LLVMIsAICmpInst", CallingConvention = System.Runtime.InteropServices.CallingConvention.Cdecl, BestFitMapping = false, ThrowOnUnmappableChar = true)] internal static extern LLVMValueRef IsAICmpInst(LLVMValueRef @Val); [DllImport(libraryPath, EntryPoint = "LLVMIsAExtractElementInst", CallingConvention = System.Runtime.InteropServices.CallingConvention.Cdecl, BestFitMapping = false, ThrowOnUnmappableChar = true)] internal static extern LLVMValueRef IsAExtractElementInst(LLVMValueRef @Val); [DllImport(libraryPath, EntryPoint = "LLVMIsAGetElementPtrInst", CallingConvention = System.Runtime.InteropServices.CallingConvention.Cdecl, BestFitMapping = false, ThrowOnUnmappableChar = true)] internal static extern LLVMValueRef IsAGetElementPtrInst(LLVMValueRef @Val); [DllImport(libraryPath, EntryPoint = "LLVMIsAInsertElementInst", CallingConvention = System.Runtime.InteropServices.CallingConvention.Cdecl, BestFitMapping = false, ThrowOnUnmappableChar = true)] internal static extern LLVMValueRef IsAInsertElementInst(LLVMValueRef @Val); [DllImport(libraryPath, EntryPoint = "LLVMIsAInsertValueInst", CallingConvention = System.Runtime.InteropServices.CallingConvention.Cdecl, BestFitMapping = false, ThrowOnUnmappableChar = true)] internal static extern LLVMValueRef IsAInsertValueInst(LLVMValueRef @Val); [DllImport(libraryPath, EntryPoint = "LLVMIsALandingPadInst", CallingConvention = System.Runtime.InteropServices.CallingConvention.Cdecl, BestFitMapping = false, ThrowOnUnmappableChar = true)] internal static extern LLVMValueRef IsALandingPadInst(LLVMValueRef @Val); [DllImport(libraryPath, EntryPoint = "LLVMIsAPHINode", CallingConvention = System.Runtime.InteropServices.CallingConvention.Cdecl, BestFitMapping = false, ThrowOnUnmappableChar = true)] internal static extern LLVMValueRef IsAPHINode(LLVMValueRef @Val); [DllImport(libraryPath, EntryPoint = "LLVMIsASelectInst", CallingConvention = System.Runtime.InteropServices.CallingConvention.Cdecl, BestFitMapping = false, ThrowOnUnmappableChar = true)] internal static extern LLVMValueRef IsASelectInst(LLVMValueRef @Val); [DllImport(libraryPath, EntryPoint = "LLVMIsAShuffleVectorInst", CallingConvention = System.Runtime.InteropServices.CallingConvention.Cdecl, BestFitMapping = false, ThrowOnUnmappableChar = true)] internal static extern LLVMValueRef IsAShuffleVectorInst(LLVMValueRef @Val); [DllImport(libraryPath, EntryPoint = "LLVMIsAStoreInst", CallingConvention = System.Runtime.InteropServices.CallingConvention.Cdecl, BestFitMapping = false, ThrowOnUnmappableChar = true)] internal static extern LLVMValueRef IsAStoreInst(LLVMValueRef @Val); [DllImport(libraryPath, EntryPoint = "LLVMIsATerminatorInst", CallingConvention = System.Runtime.InteropServices.CallingConvention.Cdecl, BestFitMapping = false, ThrowOnUnmappableChar = true)] internal static extern LLVMValueRef IsATerminatorInst(LLVMValueRef @Val); [DllImport(libraryPath, EntryPoint = "LLVMIsABranchInst", CallingConvention = System.Runtime.InteropServices.CallingConvention.Cdecl, BestFitMapping = false, ThrowOnUnmappableChar = true)] internal static extern LLVMValueRef IsABranchInst(LLVMValueRef @Val); [DllImport(libraryPath, EntryPoint = "LLVMIsAIndirectBrInst", CallingConvention = System.Runtime.InteropServices.CallingConvention.Cdecl, BestFitMapping = false, ThrowOnUnmappableChar = true)] internal static extern LLVMValueRef IsAIndirectBrInst(LLVMValueRef @Val); [DllImport(libraryPath, EntryPoint = "LLVMIsAInvokeInst", CallingConvention = System.Runtime.InteropServices.CallingConvention.Cdecl, BestFitMapping = false, ThrowOnUnmappableChar = true)] internal static extern LLVMValueRef IsAInvokeInst(LLVMValueRef @Val); [DllImport(libraryPath, EntryPoint = "LLVMIsAReturnInst", CallingConvention = System.Runtime.InteropServices.CallingConvention.Cdecl, BestFitMapping = false, ThrowOnUnmappableChar = true)] internal static extern LLVMValueRef IsAReturnInst(LLVMValueRef @Val); [DllImport(libraryPath, EntryPoint = "LLVMIsASwitchInst", CallingConvention = System.Runtime.InteropServices.CallingConvention.Cdecl, BestFitMapping = false, ThrowOnUnmappableChar = true)] internal static extern LLVMValueRef IsASwitchInst(LLVMValueRef @Val); [DllImport(libraryPath, EntryPoint = "LLVMIsAUnreachableInst", CallingConvention = System.Runtime.InteropServices.CallingConvention.Cdecl, BestFitMapping = false, ThrowOnUnmappableChar = true)] internal static extern LLVMValueRef IsAUnreachableInst(LLVMValueRef @Val); [DllImport(libraryPath, EntryPoint = "LLVMIsAResumeInst", CallingConvention = System.Runtime.InteropServices.CallingConvention.Cdecl, BestFitMapping = false, ThrowOnUnmappableChar = true)] internal static extern LLVMValueRef IsAResumeInst(LLVMValueRef @Val); [DllImport(libraryPath, EntryPoint = "LLVMIsAUnaryInstruction", CallingConvention = System.Runtime.InteropServices.CallingConvention.Cdecl, BestFitMapping = false, ThrowOnUnmappableChar = true)] internal static extern LLVMValueRef IsAUnaryInstruction(LLVMValueRef @Val); [DllImport(libraryPath, EntryPoint = "LLVMIsAAllocaInst", CallingConvention = System.Runtime.InteropServices.CallingConvention.Cdecl, BestFitMapping = false, ThrowOnUnmappableChar = true)] internal static extern LLVMValueRef IsAAllocaInst(LLVMValueRef @Val); [DllImport(libraryPath, EntryPoint = "LLVMIsACastInst", CallingConvention = System.Runtime.InteropServices.CallingConvention.Cdecl, BestFitMapping = false, ThrowOnUnmappableChar = true)] internal static extern LLVMValueRef IsACastInst(LLVMValueRef @Val); [DllImport(libraryPath, EntryPoint = "LLVMIsAAddrSpaceCastInst", CallingConvention = System.Runtime.InteropServices.CallingConvention.Cdecl, BestFitMapping = false, ThrowOnUnmappableChar = true)] internal static extern LLVMValueRef IsAAddrSpaceCastInst(LLVMValueRef @Val); [DllImport(libraryPath, EntryPoint = "LLVMIsABitCastInst", CallingConvention = System.Runtime.InteropServices.CallingConvention.Cdecl, BestFitMapping = false, ThrowOnUnmappableChar = true)] internal static extern LLVMValueRef IsABitCastInst(LLVMValueRef @Val); [DllImport(libraryPath, EntryPoint = "LLVMIsAFPExtInst", CallingConvention = System.Runtime.InteropServices.CallingConvention.Cdecl, BestFitMapping = false, ThrowOnUnmappableChar = true)] internal static extern LLVMValueRef IsAFPExtInst(LLVMValueRef @Val); [DllImport(libraryPath, EntryPoint = "LLVMIsAFPToSIInst", CallingConvention = System.Runtime.InteropServices.CallingConvention.Cdecl, BestFitMapping = false, ThrowOnUnmappableChar = true)] internal static extern LLVMValueRef IsAFPToSIInst(LLVMValueRef @Val); [DllImport(libraryPath, EntryPoint = "LLVMIsAFPToUIInst", CallingConvention = System.Runtime.InteropServices.CallingConvention.Cdecl, BestFitMapping = false, ThrowOnUnmappableChar = true)] internal static extern LLVMValueRef IsAFPToUIInst(LLVMValueRef @Val); [DllImport(libraryPath, EntryPoint = "LLVMIsAFPTruncInst", CallingConvention = System.Runtime.InteropServices.CallingConvention.Cdecl, BestFitMapping = false, ThrowOnUnmappableChar = true)] internal static extern LLVMValueRef IsAFPTruncInst(LLVMValueRef @Val); [DllImport(libraryPath, EntryPoint = "LLVMIsAIntToPtrInst", CallingConvention = System.Runtime.InteropServices.CallingConvention.Cdecl, BestFitMapping = false, ThrowOnUnmappableChar = true)] internal static extern LLVMValueRef IsAIntToPtrInst(LLVMValueRef @Val); [DllImport(libraryPath, EntryPoint = "LLVMIsAPtrToIntInst", CallingConvention = System.Runtime.InteropServices.CallingConvention.Cdecl, BestFitMapping = false, ThrowOnUnmappableChar = true)] internal static extern LLVMValueRef IsAPtrToIntInst(LLVMValueRef @Val); [DllImport(libraryPath, EntryPoint = "LLVMIsASExtInst", CallingConvention = System.Runtime.InteropServices.CallingConvention.Cdecl, BestFitMapping = false, ThrowOnUnmappableChar = true)] internal static extern LLVMValueRef IsASExtInst(LLVMValueRef @Val); [DllImport(libraryPath, EntryPoint = "LLVMIsASIToFPInst", CallingConvention = System.Runtime.InteropServices.CallingConvention.Cdecl, BestFitMapping = false, ThrowOnUnmappableChar = true)] internal static extern LLVMValueRef IsASIToFPInst(LLVMValueRef @Val); [DllImport(libraryPath, EntryPoint = "LLVMIsATruncInst", CallingConvention = System.Runtime.InteropServices.CallingConvention.Cdecl, BestFitMapping = false, ThrowOnUnmappableChar = true)] internal static extern LLVMValueRef IsATruncInst(LLVMValueRef @Val); [DllImport(libraryPath, EntryPoint = "LLVMIsAUIToFPInst", CallingConvention = System.Runtime.InteropServices.CallingConvention.Cdecl, BestFitMapping = false, ThrowOnUnmappableChar = true)] internal static extern LLVMValueRef IsAUIToFPInst(LLVMValueRef @Val); [DllImport(libraryPath, EntryPoint = "LLVMIsAZExtInst", CallingConvention = System.Runtime.InteropServices.CallingConvention.Cdecl, BestFitMapping = false, ThrowOnUnmappableChar = true)] internal static extern LLVMValueRef IsAZExtInst(LLVMValueRef @Val); [DllImport(libraryPath, EntryPoint = "LLVMIsAExtractValueInst", CallingConvention = System.Runtime.InteropServices.CallingConvention.Cdecl, BestFitMapping = false, ThrowOnUnmappableChar = true)] internal static extern LLVMValueRef IsAExtractValueInst(LLVMValueRef @Val); [DllImport(libraryPath, EntryPoint = "LLVMIsALoadInst", CallingConvention = System.Runtime.InteropServices.CallingConvention.Cdecl, BestFitMapping = false, ThrowOnUnmappableChar = true)] internal static extern LLVMValueRef IsALoadInst(LLVMValueRef @Val); [DllImport(libraryPath, EntryPoint = "LLVMIsAVAArgInst", CallingConvention = System.Runtime.InteropServices.CallingConvention.Cdecl, BestFitMapping = false, ThrowOnUnmappableChar = true)] internal static extern LLVMValueRef IsAVAArgInst(LLVMValueRef @Val); [DllImport(libraryPath, EntryPoint = "LLVMIsAMDNode", CallingConvention = System.Runtime.InteropServices.CallingConvention.Cdecl, BestFitMapping = false, ThrowOnUnmappableChar = true)] internal static extern LLVMValueRef IsAMDNode(LLVMValueRef @Val); [DllImport(libraryPath, EntryPoint = "LLVMIsAMDString", CallingConvention = System.Runtime.InteropServices.CallingConvention.Cdecl, BestFitMapping = false, ThrowOnUnmappableChar = true)] internal static extern LLVMValueRef IsAMDString(LLVMValueRef @Val); [DllImport(libraryPath, EntryPoint = "LLVMGetFirstUse", CallingConvention = System.Runtime.InteropServices.CallingConvention.Cdecl, BestFitMapping = false, ThrowOnUnmappableChar = true)] internal static extern LLVMUseRef GetFirstUse(LLVMValueRef @Val); [DllImport(libraryPath, EntryPoint = "LLVMGetNextUse", CallingConvention = System.Runtime.InteropServices.CallingConvention.Cdecl, BestFitMapping = false, ThrowOnUnmappableChar = true)] internal static extern LLVMUseRef GetNextUse(LLVMUseRef @U); [DllImport(libraryPath, EntryPoint = "LLVMGetUser", CallingConvention = System.Runtime.InteropServices.CallingConvention.Cdecl, BestFitMapping = false, ThrowOnUnmappableChar = true)] internal static extern LLVMValueRef GetUser(LLVMUseRef @U); [DllImport(libraryPath, EntryPoint = "LLVMGetUsedValue", CallingConvention = System.Runtime.InteropServices.CallingConvention.Cdecl, BestFitMapping = false, ThrowOnUnmappableChar = true)] internal static extern LLVMValueRef GetUsedValue(LLVMUseRef @U); [DllImport(libraryPath, EntryPoint = "LLVMGetOperand", CallingConvention = System.Runtime.InteropServices.CallingConvention.Cdecl, BestFitMapping = false, ThrowOnUnmappableChar = true)] internal static extern LLVMValueRef GetOperand(LLVMValueRef @Val, uint @Index); [DllImport(libraryPath, EntryPoint = "LLVMGetOperandUse", CallingConvention = System.Runtime.InteropServices.CallingConvention.Cdecl, BestFitMapping = false, ThrowOnUnmappableChar = true)] internal static extern LLVMUseRef GetOperandUse(LLVMValueRef @Val, uint @Index); [DllImport(libraryPath, EntryPoint = "LLVMSetOperand", CallingConvention = System.Runtime.InteropServices.CallingConvention.Cdecl, BestFitMapping = false, ThrowOnUnmappableChar = true)] internal static extern void SetOperand(LLVMValueRef @User, uint @Index, LLVMValueRef @Val); [DllImport(libraryPath, EntryPoint = "LLVMGetNumOperands", CallingConvention = System.Runtime.InteropServices.CallingConvention.Cdecl, BestFitMapping = false, ThrowOnUnmappableChar = true)] internal static extern int GetNumOperands(LLVMValueRef @Val); [DllImport(libraryPath, EntryPoint = "LLVMConstNull", CallingConvention = System.Runtime.InteropServices.CallingConvention.Cdecl, BestFitMapping = false, ThrowOnUnmappableChar = true)] internal static extern LLVMValueRef ConstNull(LLVMTypeRef @Ty); [DllImport(libraryPath, EntryPoint = "LLVMConstAllOnes", CallingConvention = System.Runtime.InteropServices.CallingConvention.Cdecl, BestFitMapping = false, ThrowOnUnmappableChar = true)] internal static extern LLVMValueRef ConstAllOnes(LLVMTypeRef @Ty); [DllImport(libraryPath, EntryPoint = "LLVMGetUndef", CallingConvention = System.Runtime.InteropServices.CallingConvention.Cdecl, BestFitMapping = false, ThrowOnUnmappableChar = true)] internal static extern LLVMValueRef GetUndef(LLVMTypeRef @Ty); [DllImport(libraryPath, EntryPoint = "LLVMIsNull", CallingConvention = System.Runtime.InteropServices.CallingConvention.Cdecl, BestFitMapping = false, ThrowOnUnmappableChar = true)] internal static extern LLVMBool IsNull(LLVMValueRef @Val); [DllImport(libraryPath, EntryPoint = "LLVMConstPointerNull", CallingConvention = System.Runtime.InteropServices.CallingConvention.Cdecl, BestFitMapping = false, ThrowOnUnmappableChar = true)] internal static extern LLVMValueRef ConstPointerNull(LLVMTypeRef @Ty); [DllImport(libraryPath, EntryPoint = "LLVMConstInt", CallingConvention = System.Runtime.InteropServices.CallingConvention.Cdecl, BestFitMapping = false, ThrowOnUnmappableChar = true)] internal static extern LLVMValueRef ConstInt(LLVMTypeRef @IntTy, ulong @N, LLVMBool @SignExtend); [DllImport(libraryPath, EntryPoint = "LLVMConstIntOfArbitraryPrecision", CallingConvention = System.Runtime.InteropServices.CallingConvention.Cdecl, BestFitMapping = false, ThrowOnUnmappableChar = true)] internal static extern LLVMValueRef ConstIntOfArbitraryPrecision(LLVMTypeRef @IntTy, uint @NumWords, int[] @Words); [DllImport(libraryPath, EntryPoint = "LLVMConstIntOfString", CallingConvention = System.Runtime.InteropServices.CallingConvention.Cdecl, BestFitMapping = false, ThrowOnUnmappableChar = true)] internal static extern LLVMValueRef ConstIntOfString(LLVMTypeRef @IntTy, [MarshalAs(UnmanagedType.LPStr)] string @Text, char @Radix); [DllImport(libraryPath, EntryPoint = "LLVMConstIntOfStringAndSize", CallingConvention = System.Runtime.InteropServices.CallingConvention.Cdecl, BestFitMapping = false, ThrowOnUnmappableChar = true)] internal static extern LLVMValueRef ConstIntOfStringAndSize(LLVMTypeRef @IntTy, [MarshalAs(UnmanagedType.LPStr)] string @Text, uint @SLen, char @Radix); [DllImport(libraryPath, EntryPoint = "LLVMConstReal", CallingConvention = System.Runtime.InteropServices.CallingConvention.Cdecl, BestFitMapping = false, ThrowOnUnmappableChar = true)] internal static extern LLVMValueRef ConstReal(LLVMTypeRef @RealTy, double @N); [DllImport(libraryPath, EntryPoint = "LLVMConstRealOfString", CallingConvention = System.Runtime.InteropServices.CallingConvention.Cdecl, BestFitMapping = false, ThrowOnUnmappableChar = true)] internal static extern LLVMValueRef ConstRealOfString(LLVMTypeRef @RealTy, [MarshalAs(UnmanagedType.LPStr)] string @Text); [DllImport(libraryPath, EntryPoint = "LLVMConstRealOfStringAndSize", CallingConvention = System.Runtime.InteropServices.CallingConvention.Cdecl, BestFitMapping = false, ThrowOnUnmappableChar = true)] internal static extern LLVMValueRef ConstRealOfStringAndSize(LLVMTypeRef @RealTy, [MarshalAs(UnmanagedType.LPStr)] string @Text, uint @SLen); [DllImport(libraryPath, EntryPoint = "LLVMConstIntGetZExtValue", CallingConvention = System.Runtime.InteropServices.CallingConvention.Cdecl, BestFitMapping = false, ThrowOnUnmappableChar = true)] internal static extern ulong ConstIntGetZExtValue(LLVMValueRef @ConstantVal); [DllImport(libraryPath, EntryPoint = "LLVMConstIntGetSExtValue", CallingConvention = System.Runtime.InteropServices.CallingConvention.Cdecl, BestFitMapping = false, ThrowOnUnmappableChar = true)] internal static extern long ConstIntGetSExtValue(LLVMValueRef @ConstantVal); [DllImport(libraryPath, EntryPoint = "LLVMConstRealGetDouble", CallingConvention = System.Runtime.InteropServices.CallingConvention.Cdecl, BestFitMapping = false, ThrowOnUnmappableChar = true)] internal static extern double ConstRealGetDouble(LLVMValueRef @ConstantVal, out LLVMBool @losesInfo); [DllImport(libraryPath, EntryPoint = "LLVMConstStringInContext", CallingConvention = System.Runtime.InteropServices.CallingConvention.Cdecl, BestFitMapping = false, ThrowOnUnmappableChar = true)] internal static extern LLVMValueRef ConstStringInContext(LLVMContextRef @C, [MarshalAs(UnmanagedType.LPStr)] string @Str, uint @Length, LLVMBool @DontNullTerminate); [DllImport(libraryPath, EntryPoint = "LLVMConstString", CallingConvention = System.Runtime.InteropServices.CallingConvention.Cdecl, BestFitMapping = false, ThrowOnUnmappableChar = true)] internal static extern LLVMValueRef ConstString([MarshalAs(UnmanagedType.LPStr)] string @Str, uint @Length, LLVMBool @DontNullTerminate); [DllImport(libraryPath, EntryPoint = "LLVMIsConstantString", CallingConvention = System.Runtime.InteropServices.CallingConvention.Cdecl, BestFitMapping = false, ThrowOnUnmappableChar = true)] internal static extern LLVMBool IsConstantString(LLVMValueRef @c); [DllImport(libraryPath, EntryPoint = "LLVMGetAsString", CallingConvention = System.Runtime.InteropServices.CallingConvention.Cdecl, BestFitMapping = false, ThrowOnUnmappableChar = true)] internal static extern IntPtr GetAsString(LLVMValueRef @c, out int @out); [DllImport(libraryPath, EntryPoint = "LLVMConstStructInContext", CallingConvention = System.Runtime.InteropServices.CallingConvention.Cdecl, BestFitMapping = false, ThrowOnUnmappableChar = true)] internal static extern LLVMValueRef ConstStructInContext(LLVMContextRef @C, out LLVMValueRef @ConstantVals, uint @Count, LLVMBool @Packed); [DllImport(libraryPath, EntryPoint = "LLVMConstStruct", CallingConvention = System.Runtime.InteropServices.CallingConvention.Cdecl, BestFitMapping = false, ThrowOnUnmappableChar = true)] internal static extern LLVMValueRef ConstStruct(out LLVMValueRef @ConstantVals, uint @Count, LLVMBool @Packed); [DllImport(libraryPath, EntryPoint = "LLVMConstArray", CallingConvention = System.Runtime.InteropServices.CallingConvention.Cdecl, BestFitMapping = false, ThrowOnUnmappableChar = true)] internal static extern LLVMValueRef ConstArray(LLVMTypeRef @ElementTy, out LLVMValueRef @ConstantVals, uint @Length); [DllImport(libraryPath, EntryPoint = "LLVMConstNamedStruct", CallingConvention = System.Runtime.InteropServices.CallingConvention.Cdecl, BestFitMapping = false, ThrowOnUnmappableChar = true)] internal static extern LLVMValueRef ConstNamedStruct(LLVMTypeRef @StructTy, out LLVMValueRef @ConstantVals, uint @Count); [DllImport(libraryPath, EntryPoint = "LLVMGetElementAsConstant", CallingConvention = System.Runtime.InteropServices.CallingConvention.Cdecl, BestFitMapping = false, ThrowOnUnmappableChar = true)] internal static extern LLVMValueRef GetElementAsConstant(LLVMValueRef @c, uint @idx); [DllImport(libraryPath, EntryPoint = "LLVMConstVector", CallingConvention = System.Runtime.InteropServices.CallingConvention.Cdecl, BestFitMapping = false, ThrowOnUnmappableChar = true)] internal static extern LLVMValueRef ConstVector(out LLVMValueRef @ScalarConstantVals, uint @Size); [DllImport(libraryPath, EntryPoint = "LLVMGetConstOpcode", CallingConvention = System.Runtime.InteropServices.CallingConvention.Cdecl, BestFitMapping = false, ThrowOnUnmappableChar = true)] internal static extern LLVMOpcode GetConstOpcode(LLVMValueRef @ConstantVal); [DllImport(libraryPath, EntryPoint = "LLVMAlignOf", CallingConvention = System.Runtime.InteropServices.CallingConvention.Cdecl, BestFitMapping = false, ThrowOnUnmappableChar = true)] internal static extern LLVMValueRef AlignOf(LLVMTypeRef @Ty); [DllImport(libraryPath, EntryPoint = "LLVMSizeOf", CallingConvention = System.Runtime.InteropServices.CallingConvention.Cdecl, BestFitMapping = false, ThrowOnUnmappableChar = true)] internal static extern LLVMValueRef SizeOf(LLVMTypeRef @Ty); [DllImport(libraryPath, EntryPoint = "LLVMConstNeg", CallingConvention = System.Runtime.InteropServices.CallingConvention.Cdecl, BestFitMapping = false, ThrowOnUnmappableChar = true)] internal static extern LLVMValueRef ConstNeg(LLVMValueRef @ConstantVal); [DllImport(libraryPath, EntryPoint = "LLVMConstNSWNeg", CallingConvention = System.Runtime.InteropServices.CallingConvention.Cdecl, BestFitMapping = false, ThrowOnUnmappableChar = true)] internal static extern LLVMValueRef ConstNSWNeg(LLVMValueRef @ConstantVal); [DllImport(libraryPath, EntryPoint = "LLVMConstNUWNeg", CallingConvention = System.Runtime.InteropServices.CallingConvention.Cdecl, BestFitMapping = false, ThrowOnUnmappableChar = true)] internal static extern LLVMValueRef ConstNUWNeg(LLVMValueRef @ConstantVal); [DllImport(libraryPath, EntryPoint = "LLVMConstFNeg", CallingConvention = System.Runtime.InteropServices.CallingConvention.Cdecl, BestFitMapping = false, ThrowOnUnmappableChar = true)] internal static extern LLVMValueRef ConstFNeg(LLVMValueRef @ConstantVal); [DllImport(libraryPath, EntryPoint = "LLVMConstNot", CallingConvention = System.Runtime.InteropServices.CallingConvention.Cdecl, BestFitMapping = false, ThrowOnUnmappableChar = true)] internal static extern LLVMValueRef ConstNot(LLVMValueRef @ConstantVal); [DllImport(libraryPath, EntryPoint = "LLVMConstAdd", CallingConvention = System.Runtime.InteropServices.CallingConvention.Cdecl, BestFitMapping = false, ThrowOnUnmappableChar = true)] internal static extern LLVMValueRef ConstAdd(LLVMValueRef @LHSConstant, LLVMValueRef @RHSConstant); [DllImport(libraryPath, EntryPoint = "LLVMConstNSWAdd", CallingConvention = System.Runtime.InteropServices.CallingConvention.Cdecl, BestFitMapping = false, ThrowOnUnmappableChar = true)] internal static extern LLVMValueRef ConstNSWAdd(LLVMValueRef @LHSConstant, LLVMValueRef @RHSConstant); [DllImport(libraryPath, EntryPoint = "LLVMConstNUWAdd", CallingConvention = System.Runtime.InteropServices.CallingConvention.Cdecl, BestFitMapping = false, ThrowOnUnmappableChar = true)] internal static extern LLVMValueRef ConstNUWAdd(LLVMValueRef @LHSConstant, LLVMValueRef @RHSConstant); [DllImport(libraryPath, EntryPoint = "LLVMConstFAdd", CallingConvention = System.Runtime.InteropServices.CallingConvention.Cdecl, BestFitMapping = false, ThrowOnUnmappableChar = true)] internal static extern LLVMValueRef ConstFAdd(LLVMValueRef @LHSConstant, LLVMValueRef @RHSConstant); [DllImport(libraryPath, EntryPoint = "LLVMConstSub", CallingConvention = System.Runtime.InteropServices.CallingConvention.Cdecl, BestFitMapping = false, ThrowOnUnmappableChar = true)] internal static extern LLVMValueRef ConstSub(LLVMValueRef @LHSConstant, LLVMValueRef @RHSConstant); [DllImport(libraryPath, EntryPoint = "LLVMConstNSWSub", CallingConvention = System.Runtime.InteropServices.CallingConvention.Cdecl, BestFitMapping = false, ThrowOnUnmappableChar = true)] internal static extern LLVMValueRef ConstNSWSub(LLVMValueRef @LHSConstant, LLVMValueRef @RHSConstant); [DllImport(libraryPath, EntryPoint = "LLVMConstNUWSub", CallingConvention = System.Runtime.InteropServices.CallingConvention.Cdecl, BestFitMapping = false, ThrowOnUnmappableChar = true)] internal static extern LLVMValueRef ConstNUWSub(LLVMValueRef @LHSConstant, LLVMValueRef @RHSConstant); [DllImport(libraryPath, EntryPoint = "LLVMConstFSub", CallingConvention = System.Runtime.InteropServices.CallingConvention.Cdecl, BestFitMapping = false, ThrowOnUnmappableChar = true)] internal static extern LLVMValueRef ConstFSub(LLVMValueRef @LHSConstant, LLVMValueRef @RHSConstant); [DllImport(libraryPath, EntryPoint = "LLVMConstMul", CallingConvention = System.Runtime.InteropServices.CallingConvention.Cdecl, BestFitMapping = false, ThrowOnUnmappableChar = true)] internal static extern LLVMValueRef ConstMul(LLVMValueRef @LHSConstant, LLVMValueRef @RHSConstant); [DllImport(libraryPath, EntryPoint = "LLVMConstNSWMul", CallingConvention = System.Runtime.InteropServices.CallingConvention.Cdecl, BestFitMapping = false, ThrowOnUnmappableChar = true)] internal static extern LLVMValueRef ConstNSWMul(LLVMValueRef @LHSConstant, LLVMValueRef @RHSConstant); [DllImport(libraryPath, EntryPoint = "LLVMConstNUWMul", CallingConvention = System.Runtime.InteropServices.CallingConvention.Cdecl, BestFitMapping = false, ThrowOnUnmappableChar = true)] internal static extern LLVMValueRef ConstNUWMul(LLVMValueRef @LHSConstant, LLVMValueRef @RHSConstant); [DllImport(libraryPath, EntryPoint = "LLVMConstFMul", CallingConvention = System.Runtime.InteropServices.CallingConvention.Cdecl, BestFitMapping = false, ThrowOnUnmappableChar = true)] internal static extern LLVMValueRef ConstFMul(LLVMValueRef @LHSConstant, LLVMValueRef @RHSConstant); [DllImport(libraryPath, EntryPoint = "LLVMConstUDiv", CallingConvention = System.Runtime.InteropServices.CallingConvention.Cdecl, BestFitMapping = false, ThrowOnUnmappableChar = true)] internal static extern LLVMValueRef ConstUDiv(LLVMValueRef @LHSConstant, LLVMValueRef @RHSConstant); [DllImport(libraryPath, EntryPoint = "LLVMConstSDiv", CallingConvention = System.Runtime.InteropServices.CallingConvention.Cdecl, BestFitMapping = false, ThrowOnUnmappableChar = true)] internal static extern LLVMValueRef ConstSDiv(LLVMValueRef @LHSConstant, LLVMValueRef @RHSConstant); [DllImport(libraryPath, EntryPoint = "LLVMConstExactSDiv", CallingConvention = System.Runtime.InteropServices.CallingConvention.Cdecl, BestFitMapping = false, ThrowOnUnmappableChar = true)] internal static extern LLVMValueRef ConstExactSDiv(LLVMValueRef @LHSConstant, LLVMValueRef @RHSConstant); [DllImport(libraryPath, EntryPoint = "LLVMConstFDiv", CallingConvention = System.Runtime.InteropServices.CallingConvention.Cdecl, BestFitMapping = false, ThrowOnUnmappableChar = true)] internal static extern LLVMValueRef ConstFDiv(LLVMValueRef @LHSConstant, LLVMValueRef @RHSConstant); [DllImport(libraryPath, EntryPoint = "LLVMConstURem", CallingConvention = System.Runtime.InteropServices.CallingConvention.Cdecl, BestFitMapping = false, ThrowOnUnmappableChar = true)] internal static extern LLVMValueRef ConstURem(LLVMValueRef @LHSConstant, LLVMValueRef @RHSConstant); [DllImport(libraryPath, EntryPoint = "LLVMConstSRem", CallingConvention = System.Runtime.InteropServices.CallingConvention.Cdecl, BestFitMapping = false, ThrowOnUnmappableChar = true)] internal static extern LLVMValueRef ConstSRem(LLVMValueRef @LHSConstant, LLVMValueRef @RHSConstant); [DllImport(libraryPath, EntryPoint = "LLVMConstFRem", CallingConvention = System.Runtime.InteropServices.CallingConvention.Cdecl, BestFitMapping = false, ThrowOnUnmappableChar = true)] internal static extern LLVMValueRef ConstFRem(LLVMValueRef @LHSConstant, LLVMValueRef @RHSConstant); [DllImport(libraryPath, EntryPoint = "LLVMConstAnd", CallingConvention = System.Runtime.InteropServices.CallingConvention.Cdecl, BestFitMapping = false, ThrowOnUnmappableChar = true)] internal static extern LLVMValueRef ConstAnd(LLVMValueRef @LHSConstant, LLVMValueRef @RHSConstant); [DllImport(libraryPath, EntryPoint = "LLVMConstOr", CallingConvention = System.Runtime.InteropServices.CallingConvention.Cdecl, BestFitMapping = false, ThrowOnUnmappableChar = true)] internal static extern LLVMValueRef ConstOr(LLVMValueRef @LHSConstant, LLVMValueRef @RHSConstant); [DllImport(libraryPath, EntryPoint = "LLVMConstXor", CallingConvention = System.Runtime.InteropServices.CallingConvention.Cdecl, BestFitMapping = false, ThrowOnUnmappableChar = true)] internal static extern LLVMValueRef ConstXor(LLVMValueRef @LHSConstant, LLVMValueRef @RHSConstant); [DllImport(libraryPath, EntryPoint = "LLVMConstICmp", CallingConvention = System.Runtime.InteropServices.CallingConvention.Cdecl, BestFitMapping = false, ThrowOnUnmappableChar = true)] internal static extern LLVMValueRef ConstICmp(LLVMIntPredicate @Predicate, LLVMValueRef @LHSConstant, LLVMValueRef @RHSConstant); [DllImport(libraryPath, EntryPoint = "LLVMConstFCmp", CallingConvention = System.Runtime.InteropServices.CallingConvention.Cdecl, BestFitMapping = false, ThrowOnUnmappableChar = true)] internal static extern LLVMValueRef ConstFCmp(LLVMRealPredicate @Predicate, LLVMValueRef @LHSConstant, LLVMValueRef @RHSConstant); [DllImport(libraryPath, EntryPoint = "LLVMConstShl", CallingConvention = System.Runtime.InteropServices.CallingConvention.Cdecl, BestFitMapping = false, ThrowOnUnmappableChar = true)] internal static extern LLVMValueRef ConstShl(LLVMValueRef @LHSConstant, LLVMValueRef @RHSConstant); [DllImport(libraryPath, EntryPoint = "LLVMConstLShr", CallingConvention = System.Runtime.InteropServices.CallingConvention.Cdecl, BestFitMapping = false, ThrowOnUnmappableChar = true)] internal static extern LLVMValueRef ConstLShr(LLVMValueRef @LHSConstant, LLVMValueRef @RHSConstant); [DllImport(libraryPath, EntryPoint = "LLVMConstAShr", CallingConvention = System.Runtime.InteropServices.CallingConvention.Cdecl, BestFitMapping = false, ThrowOnUnmappableChar = true)] internal static extern LLVMValueRef ConstAShr(LLVMValueRef @LHSConstant, LLVMValueRef @RHSConstant); [DllImport(libraryPath, EntryPoint = "LLVMConstGEP", CallingConvention = System.Runtime.InteropServices.CallingConvention.Cdecl, BestFitMapping = false, ThrowOnUnmappableChar = true)] internal static extern LLVMValueRef ConstGEP(LLVMValueRef @ConstantVal, out LLVMValueRef @ConstantIndices, uint @NumIndices); [DllImport(libraryPath, EntryPoint = "LLVMConstInBoundsGEP", CallingConvention = System.Runtime.InteropServices.CallingConvention.Cdecl, BestFitMapping = false, ThrowOnUnmappableChar = true)] internal static extern LLVMValueRef ConstInBoundsGEP(LLVMValueRef @ConstantVal, out LLVMValueRef @ConstantIndices, uint @NumIndices); [DllImport(libraryPath, EntryPoint = "LLVMConstTrunc", CallingConvention = System.Runtime.InteropServices.CallingConvention.Cdecl, BestFitMapping = false, ThrowOnUnmappableChar = true)] internal static extern LLVMValueRef ConstTrunc(LLVMValueRef @ConstantVal, LLVMTypeRef @ToType); [DllImport(libraryPath, EntryPoint = "LLVMConstSExt", CallingConvention = System.Runtime.InteropServices.CallingConvention.Cdecl, BestFitMapping = false, ThrowOnUnmappableChar = true)] internal static extern LLVMValueRef ConstSExt(LLVMValueRef @ConstantVal, LLVMTypeRef @ToType); [DllImport(libraryPath, EntryPoint = "LLVMConstZExt", CallingConvention = System.Runtime.InteropServices.CallingConvention.Cdecl, BestFitMapping = false, ThrowOnUnmappableChar = true)] internal static extern LLVMValueRef ConstZExt(LLVMValueRef @ConstantVal, LLVMTypeRef @ToType); [DllImport(libraryPath, EntryPoint = "LLVMConstFPTrunc", CallingConvention = System.Runtime.InteropServices.CallingConvention.Cdecl, BestFitMapping = false, ThrowOnUnmappableChar = true)] internal static extern LLVMValueRef ConstFPTrunc(LLVMValueRef @ConstantVal, LLVMTypeRef @ToType); [DllImport(libraryPath, EntryPoint = "LLVMConstFPExt", CallingConvention = System.Runtime.InteropServices.CallingConvention.Cdecl, BestFitMapping = false, ThrowOnUnmappableChar = true)] internal static extern LLVMValueRef ConstFPExt(LLVMValueRef @ConstantVal, LLVMTypeRef @ToType); [DllImport(libraryPath, EntryPoint = "LLVMConstUIToFP", CallingConvention = System.Runtime.InteropServices.CallingConvention.Cdecl, BestFitMapping = false, ThrowOnUnmappableChar = true)] internal static extern LLVMValueRef ConstUIToFP(LLVMValueRef @ConstantVal, LLVMTypeRef @ToType); [DllImport(libraryPath, EntryPoint = "LLVMConstSIToFP", CallingConvention = System.Runtime.InteropServices.CallingConvention.Cdecl, BestFitMapping = false, ThrowOnUnmappableChar = true)] internal static extern LLVMValueRef ConstSIToFP(LLVMValueRef @ConstantVal, LLVMTypeRef @ToType); [DllImport(libraryPath, EntryPoint = "LLVMConstFPToUI", CallingConvention = System.Runtime.InteropServices.CallingConvention.Cdecl, BestFitMapping = false, ThrowOnUnmappableChar = true)] internal static extern LLVMValueRef ConstFPToUI(LLVMValueRef @ConstantVal, LLVMTypeRef @ToType); [DllImport(libraryPath, EntryPoint = "LLVMConstFPToSI", CallingConvention = System.Runtime.InteropServices.CallingConvention.Cdecl, BestFitMapping = false, ThrowOnUnmappableChar = true)] internal static extern LLVMValueRef ConstFPToSI(LLVMValueRef @ConstantVal, LLVMTypeRef @ToType); [DllImport(libraryPath, EntryPoint = "LLVMConstPtrToInt", CallingConvention = System.Runtime.InteropServices.CallingConvention.Cdecl, BestFitMapping = false, ThrowOnUnmappableChar = true)] internal static extern LLVMValueRef ConstPtrToInt(LLVMValueRef @ConstantVal, LLVMTypeRef @ToType); [DllImport(libraryPath, EntryPoint = "LLVMConstIntToPtr", CallingConvention = System.Runtime.InteropServices.CallingConvention.Cdecl, BestFitMapping = false, ThrowOnUnmappableChar = true)] internal static extern LLVMValueRef ConstIntToPtr(LLVMValueRef @ConstantVal, LLVMTypeRef @ToType); [DllImport(libraryPath, EntryPoint = "LLVMConstBitCast", CallingConvention = System.Runtime.InteropServices.CallingConvention.Cdecl, BestFitMapping = false, ThrowOnUnmappableChar = true)] internal static extern LLVMValueRef ConstBitCast(LLVMValueRef @ConstantVal, LLVMTypeRef @ToType); [DllImport(libraryPath, EntryPoint = "LLVMConstAddrSpaceCast", CallingConvention = System.Runtime.InteropServices.CallingConvention.Cdecl, BestFitMapping = false, ThrowOnUnmappableChar = true)] internal static extern LLVMValueRef ConstAddrSpaceCast(LLVMValueRef @ConstantVal, LLVMTypeRef @ToType); [DllImport(libraryPath, EntryPoint = "LLVMConstZExtOrBitCast", CallingConvention = System.Runtime.InteropServices.CallingConvention.Cdecl, BestFitMapping = false, ThrowOnUnmappableChar = true)] internal static extern LLVMValueRef ConstZExtOrBitCast(LLVMValueRef @ConstantVal, LLVMTypeRef @ToType); [DllImport(libraryPath, EntryPoint = "LLVMConstSExtOrBitCast", CallingConvention = System.Runtime.InteropServices.CallingConvention.Cdecl, BestFitMapping = false, ThrowOnUnmappableChar = true)] internal static extern LLVMValueRef ConstSExtOrBitCast(LLVMValueRef @ConstantVal, LLVMTypeRef @ToType); [DllImport(libraryPath, EntryPoint = "LLVMConstTruncOrBitCast", CallingConvention = System.Runtime.InteropServices.CallingConvention.Cdecl, BestFitMapping = false, ThrowOnUnmappableChar = true)] internal static extern LLVMValueRef ConstTruncOrBitCast(LLVMValueRef @ConstantVal, LLVMTypeRef @ToType); [DllImport(libraryPath, EntryPoint = "LLVMConstPointerCast", CallingConvention = System.Runtime.InteropServices.CallingConvention.Cdecl, BestFitMapping = false, ThrowOnUnmappableChar = true)] internal static extern LLVMValueRef ConstPointerCast(LLVMValueRef @ConstantVal, LLVMTypeRef @ToType); [DllImport(libraryPath, EntryPoint = "LLVMConstIntCast", CallingConvention = System.Runtime.InteropServices.CallingConvention.Cdecl, BestFitMapping = false, ThrowOnUnmappableChar = true)] internal static extern LLVMValueRef ConstIntCast(LLVMValueRef @ConstantVal, LLVMTypeRef @ToType, LLVMBool @isSigned); [DllImport(libraryPath, EntryPoint = "LLVMConstFPCast", CallingConvention = System.Runtime.InteropServices.CallingConvention.Cdecl, BestFitMapping = false, ThrowOnUnmappableChar = true)] internal static extern LLVMValueRef ConstFPCast(LLVMValueRef @ConstantVal, LLVMTypeRef @ToType); [DllImport(libraryPath, EntryPoint = "LLVMConstSelect", CallingConvention = System.Runtime.InteropServices.CallingConvention.Cdecl, BestFitMapping = false, ThrowOnUnmappableChar = true)] internal static extern LLVMValueRef ConstSelect(LLVMValueRef @ConstantCondition, LLVMValueRef @ConstantIfTrue, LLVMValueRef @ConstantIfFalse); [DllImport(libraryPath, EntryPoint = "LLVMConstExtractElement", CallingConvention = System.Runtime.InteropServices.CallingConvention.Cdecl, BestFitMapping = false, ThrowOnUnmappableChar = true)] internal static extern LLVMValueRef ConstExtractElement(LLVMValueRef @VectorConstant, LLVMValueRef @IndexConstant); [DllImport(libraryPath, EntryPoint = "LLVMConstInsertElement", CallingConvention = System.Runtime.InteropServices.CallingConvention.Cdecl, BestFitMapping = false, ThrowOnUnmappableChar = true)] internal static extern LLVMValueRef ConstInsertElement(LLVMValueRef @VectorConstant, LLVMValueRef @ElementValueConstant, LLVMValueRef @IndexConstant); [DllImport(libraryPath, EntryPoint = "LLVMConstShuffleVector", CallingConvention = System.Runtime.InteropServices.CallingConvention.Cdecl, BestFitMapping = false, ThrowOnUnmappableChar = true)] internal static extern LLVMValueRef ConstShuffleVector(LLVMValueRef @VectorAConstant, LLVMValueRef @VectorBConstant, LLVMValueRef @MaskConstant); [DllImport(libraryPath, EntryPoint = "LLVMConstExtractValue", CallingConvention = System.Runtime.InteropServices.CallingConvention.Cdecl, BestFitMapping = false, ThrowOnUnmappableChar = true)] internal static extern LLVMValueRef ConstExtractValue(LLVMValueRef @AggConstant, out uint @IdxList, uint @NumIdx); [DllImport(libraryPath, EntryPoint = "LLVMConstInsertValue", CallingConvention = System.Runtime.InteropServices.CallingConvention.Cdecl, BestFitMapping = false, ThrowOnUnmappableChar = true)] internal static extern LLVMValueRef ConstInsertValue(LLVMValueRef @AggConstant, LLVMValueRef @ElementValueConstant, out uint @IdxList, uint @NumIdx); [DllImport(libraryPath, EntryPoint = "LLVMConstInlineAsm", CallingConvention = System.Runtime.InteropServices.CallingConvention.Cdecl, BestFitMapping = false, ThrowOnUnmappableChar = true)] internal static extern LLVMValueRef ConstInlineAsm(LLVMTypeRef @Ty, [MarshalAs(UnmanagedType.LPStr)] string @AsmString, [MarshalAs(UnmanagedType.LPStr)] string @Constraints, LLVMBool @HasSideEffects, LLVMBool @IsAlignStack); [DllImport(libraryPath, EntryPoint = "LLVMBlockAddress", CallingConvention = System.Runtime.InteropServices.CallingConvention.Cdecl, BestFitMapping = false, ThrowOnUnmappableChar = true)] internal static extern LLVMValueRef BlockAddress(LLVMValueRef @F, LLVMBasicBlockRef @BB); [DllImport(libraryPath, EntryPoint = "LLVMGetGlobalParent", CallingConvention = System.Runtime.InteropServices.CallingConvention.Cdecl, BestFitMapping = false, ThrowOnUnmappableChar = true)] internal static extern LLVMModuleRef GetGlobalParent(LLVMValueRef @Global); [DllImport(libraryPath, EntryPoint = "LLVMIsDeclaration", CallingConvention = System.Runtime.InteropServices.CallingConvention.Cdecl, BestFitMapping = false, ThrowOnUnmappableChar = true)] internal static extern LLVMBool IsDeclaration(LLVMValueRef @Global); [DllImport(libraryPath, EntryPoint = "LLVMGetLinkage", CallingConvention = System.Runtime.InteropServices.CallingConvention.Cdecl, BestFitMapping = false, ThrowOnUnmappableChar = true)] internal static extern LLVMLinkage GetLinkage(LLVMValueRef @Global); [DllImport(libraryPath, EntryPoint = "LLVMSetLinkage", CallingConvention = System.Runtime.InteropServices.CallingConvention.Cdecl, BestFitMapping = false, ThrowOnUnmappableChar = true)] internal static extern void SetLinkage(LLVMValueRef @Global, LLVMLinkage @Linkage); [DllImport(libraryPath, EntryPoint = "LLVMGetSection", CallingConvention = System.Runtime.InteropServices.CallingConvention.Cdecl, BestFitMapping = false, ThrowOnUnmappableChar = true)] internal static extern IntPtr GetSection(LLVMValueRef @Global); [DllImport(libraryPath, EntryPoint = "LLVMSetSection", CallingConvention = System.Runtime.InteropServices.CallingConvention.Cdecl, BestFitMapping = false, ThrowOnUnmappableChar = true)] internal static extern void SetSection(LLVMValueRef @Global, [MarshalAs(UnmanagedType.LPStr)] string @Section); [DllImport(libraryPath, EntryPoint = "LLVMGetVisibility", CallingConvention = System.Runtime.InteropServices.CallingConvention.Cdecl, BestFitMapping = false, ThrowOnUnmappableChar = true)] internal static extern LLVMVisibility GetVisibility(LLVMValueRef @Global); [DllImport(libraryPath, EntryPoint = "LLVMSetVisibility", CallingConvention = System.Runtime.InteropServices.CallingConvention.Cdecl, BestFitMapping = false, ThrowOnUnmappableChar = true)] internal static extern void SetVisibility(LLVMValueRef @Global, LLVMVisibility @Viz); [DllImport(libraryPath, EntryPoint = "LLVMGetDLLStorageClass", CallingConvention = System.Runtime.InteropServices.CallingConvention.Cdecl, BestFitMapping = false, ThrowOnUnmappableChar = true)] internal static extern LLVMDLLStorageClass GetDLLStorageClass(LLVMValueRef @Global); [DllImport(libraryPath, EntryPoint = "LLVMSetDLLStorageClass", CallingConvention = System.Runtime.InteropServices.CallingConvention.Cdecl, BestFitMapping = false, ThrowOnUnmappableChar = true)] internal static extern void SetDLLStorageClass(LLVMValueRef @Global, LLVMDLLStorageClass @Class); [DllImport(libraryPath, EntryPoint = "LLVMHasUnnamedAddr", CallingConvention = System.Runtime.InteropServices.CallingConvention.Cdecl, BestFitMapping = false, ThrowOnUnmappableChar = true)] internal static extern LLVMBool HasUnnamedAddr(LLVMValueRef @Global); [DllImport(libraryPath, EntryPoint = "LLVMSetUnnamedAddr", CallingConvention = System.Runtime.InteropServices.CallingConvention.Cdecl, BestFitMapping = false, ThrowOnUnmappableChar = true)] internal static extern void SetUnnamedAddr(LLVMValueRef @Global, LLVMBool @HasUnnamedAddr); [DllImport(libraryPath, EntryPoint = "LLVMGetAlignment", CallingConvention = System.Runtime.InteropServices.CallingConvention.Cdecl, BestFitMapping = false, ThrowOnUnmappableChar = true)] internal static extern uint GetAlignment(LLVMValueRef @V); [DllImport(libraryPath, EntryPoint = "LLVMSetAlignment", CallingConvention = System.Runtime.InteropServices.CallingConvention.Cdecl, BestFitMapping = false, ThrowOnUnmappableChar = true)] internal static extern void SetAlignment(LLVMValueRef @V, uint @Bytes); [DllImport(libraryPath, EntryPoint = "LLVMAddGlobal", CallingConvention = System.Runtime.InteropServices.CallingConvention.Cdecl, BestFitMapping = false, ThrowOnUnmappableChar = true)] internal static extern LLVMValueRef AddGlobal(LLVMModuleRef @M, LLVMTypeRef @Ty, [MarshalAs(UnmanagedType.LPStr)] string @Name); [DllImport(libraryPath, EntryPoint = "LLVMAddGlobalInAddressSpace", CallingConvention = System.Runtime.InteropServices.CallingConvention.Cdecl, BestFitMapping = false, ThrowOnUnmappableChar = true)] internal static extern LLVMValueRef AddGlobalInAddressSpace(LLVMModuleRef @M, LLVMTypeRef @Ty, [MarshalAs(UnmanagedType.LPStr)] string @Name, uint @AddressSpace); [DllImport(libraryPath, EntryPoint = "LLVMGetNamedGlobal", CallingConvention = System.Runtime.InteropServices.CallingConvention.Cdecl, BestFitMapping = false, ThrowOnUnmappableChar = true)] internal static extern LLVMValueRef GetNamedGlobal(LLVMModuleRef @M, [MarshalAs(UnmanagedType.LPStr)] string @Name); [DllImport(libraryPath, EntryPoint = "LLVMGetFirstGlobal", CallingConvention = System.Runtime.InteropServices.CallingConvention.Cdecl, BestFitMapping = false, ThrowOnUnmappableChar = true)] internal static extern LLVMValueRef GetFirstGlobal(LLVMModuleRef @M); [DllImport(libraryPath, EntryPoint = "LLVMGetLastGlobal", CallingConvention = System.Runtime.InteropServices.CallingConvention.Cdecl, BestFitMapping = false, ThrowOnUnmappableChar = true)] internal static extern LLVMValueRef GetLastGlobal(LLVMModuleRef @M); [DllImport(libraryPath, EntryPoint = "LLVMGetNextGlobal", CallingConvention = System.Runtime.InteropServices.CallingConvention.Cdecl, BestFitMapping = false, ThrowOnUnmappableChar = true)] internal static extern LLVMValueRef GetNextGlobal(LLVMValueRef @GlobalVar); [DllImport(libraryPath, EntryPoint = "LLVMGetPreviousGlobal", CallingConvention = System.Runtime.InteropServices.CallingConvention.Cdecl, BestFitMapping = false, ThrowOnUnmappableChar = true)] internal static extern LLVMValueRef GetPreviousGlobal(LLVMValueRef @GlobalVar); [DllImport(libraryPath, EntryPoint = "LLVMDeleteGlobal", CallingConvention = System.Runtime.InteropServices.CallingConvention.Cdecl, BestFitMapping = false, ThrowOnUnmappableChar = true)] internal static extern void DeleteGlobal(LLVMValueRef @GlobalVar); [DllImport(libraryPath, EntryPoint = "LLVMGetInitializer", CallingConvention = System.Runtime.InteropServices.CallingConvention.Cdecl, BestFitMapping = false, ThrowOnUnmappableChar = true)] internal static extern LLVMValueRef GetInitializer(LLVMValueRef @GlobalVar); [DllImport(libraryPath, EntryPoint = "LLVMSetInitializer", CallingConvention = System.Runtime.InteropServices.CallingConvention.Cdecl, BestFitMapping = false, ThrowOnUnmappableChar = true)] internal static extern void SetInitializer(LLVMValueRef @GlobalVar, LLVMValueRef @ConstantVal); [DllImport(libraryPath, EntryPoint = "LLVMIsThreadLocal", CallingConvention = System.Runtime.InteropServices.CallingConvention.Cdecl, BestFitMapping = false, ThrowOnUnmappableChar = true)] internal static extern LLVMBool IsThreadLocal(LLVMValueRef @GlobalVar); [DllImport(libraryPath, EntryPoint = "LLVMSetThreadLocal", CallingConvention = System.Runtime.InteropServices.CallingConvention.Cdecl, BestFitMapping = false, ThrowOnUnmappableChar = true)] internal static extern void SetThreadLocal(LLVMValueRef @GlobalVar, LLVMBool @IsThreadLocal); [DllImport(libraryPath, EntryPoint = "LLVMIsGlobalConstant", CallingConvention = System.Runtime.InteropServices.CallingConvention.Cdecl, BestFitMapping = false, ThrowOnUnmappableChar = true)] internal static extern LLVMBool IsGlobalConstant(LLVMValueRef @GlobalVar); [DllImport(libraryPath, EntryPoint = "LLVMSetGlobalConstant", CallingConvention = System.Runtime.InteropServices.CallingConvention.Cdecl, BestFitMapping = false, ThrowOnUnmappableChar = true)] internal static extern void SetGlobalConstant(LLVMValueRef @GlobalVar, LLVMBool @IsConstant); [DllImport(libraryPath, EntryPoint = "LLVMGetThreadLocalMode", CallingConvention = System.Runtime.InteropServices.CallingConvention.Cdecl, BestFitMapping = false, ThrowOnUnmappableChar = true)] internal static extern LLVMThreadLocalMode GetThreadLocalMode(LLVMValueRef @GlobalVar); [DllImport(libraryPath, EntryPoint = "LLVMSetThreadLocalMode", CallingConvention = System.Runtime.InteropServices.CallingConvention.Cdecl, BestFitMapping = false, ThrowOnUnmappableChar = true)] internal static extern void SetThreadLocalMode(LLVMValueRef @GlobalVar, LLVMThreadLocalMode @Mode); [DllImport(libraryPath, EntryPoint = "LLVMIsExternallyInitialized", CallingConvention = System.Runtime.InteropServices.CallingConvention.Cdecl, BestFitMapping = false, ThrowOnUnmappableChar = true)] internal static extern LLVMBool IsExternallyInitialized(LLVMValueRef @GlobalVar); [DllImport(libraryPath, EntryPoint = "LLVMSetExternallyInitialized", CallingConvention = System.Runtime.InteropServices.CallingConvention.Cdecl, BestFitMapping = false, ThrowOnUnmappableChar = true)] internal static extern void SetExternallyInitialized(LLVMValueRef @GlobalVar, LLVMBool @IsExtInit); [DllImport(libraryPath, EntryPoint = "LLVMAddAlias", CallingConvention = System.Runtime.InteropServices.CallingConvention.Cdecl, BestFitMapping = false, ThrowOnUnmappableChar = true)] internal static extern LLVMValueRef AddAlias(LLVMModuleRef @M, LLVMTypeRef @Ty, LLVMValueRef @Aliasee, [MarshalAs(UnmanagedType.LPStr)] string @Name); [DllImport(libraryPath, EntryPoint = "LLVMDeleteFunction", CallingConvention = System.Runtime.InteropServices.CallingConvention.Cdecl, BestFitMapping = false, ThrowOnUnmappableChar = true)] internal static extern void DeleteFunction(LLVMValueRef @Fn); [DllImport(libraryPath, EntryPoint = "LLVMGetIntrinsicID", CallingConvention = System.Runtime.InteropServices.CallingConvention.Cdecl, BestFitMapping = false, ThrowOnUnmappableChar = true)] internal static extern uint GetIntrinsicID(LLVMValueRef @Fn); [DllImport(libraryPath, EntryPoint = "LLVMGetFunctionCallConv", CallingConvention = System.Runtime.InteropServices.CallingConvention.Cdecl, BestFitMapping = false, ThrowOnUnmappableChar = true)] internal static extern uint GetFunctionCallConv(LLVMValueRef @Fn); [DllImport(libraryPath, EntryPoint = "LLVMSetFunctionCallConv", CallingConvention = System.Runtime.InteropServices.CallingConvention.Cdecl, BestFitMapping = false, ThrowOnUnmappableChar = true)] internal static extern void SetFunctionCallConv(LLVMValueRef @Fn, uint @CC); [DllImport(libraryPath, EntryPoint = "LLVMGetGC", CallingConvention = System.Runtime.InteropServices.CallingConvention.Cdecl, BestFitMapping = false, ThrowOnUnmappableChar = true)] internal static extern IntPtr GetGC(LLVMValueRef @Fn); [DllImport(libraryPath, EntryPoint = "LLVMSetGC", CallingConvention = System.Runtime.InteropServices.CallingConvention.Cdecl, BestFitMapping = false, ThrowOnUnmappableChar = true)] internal static extern void SetGC(LLVMValueRef @Fn, [MarshalAs(UnmanagedType.LPStr)] string @Name); // legacy attribute manipulation is deprecated - use the LLVMAttributeXXX APIs in GeneratedExtensions.cs instead // attribute support was fairly significantly reworked in LLVM 3.6+ //[DllImport(libraryPath, EntryPoint = "LLVMAddFunctionAttr", CallingConvention = System.Runtime.InteropServices.CallingConvention.Cdecl, BestFitMapping = false, ThrowOnUnmappableChar = true)] //internal static extern void AddFunctionAttr(LLVMValueRef @Fn, LLVMAttribute @PA); //[DllImport(libraryPath, EntryPoint = "LLVMAddTargetDependentFunctionAttr", CallingConvention = System.Runtime.InteropServices.CallingConvention.Cdecl, BestFitMapping = false, ThrowOnUnmappableChar = true)] //internal static extern void AddTargetDependentFunctionAttr(LLVMValueRef @Fn, [MarshalAs(UnmanagedType.LPStr)] string @A, [MarshalAs(UnmanagedType.LPStr)] string @V); //[DllImport(libraryPath, EntryPoint = "LLVMGetFunctionAttr", CallingConvention = System.Runtime.InteropServices.CallingConvention.Cdecl, BestFitMapping = false, ThrowOnUnmappableChar = true)] //internal static extern LLVMAttribute GetFunctionAttr(LLVMValueRef @Fn); //[DllImport(libraryPath, EntryPoint = "LLVMRemoveFunctionAttr", CallingConvention = System.Runtime.InteropServices.CallingConvention.Cdecl, BestFitMapping = false, ThrowOnUnmappableChar = true)] //internal static extern void RemoveFunctionAttr(LLVMValueRef @Fn, LLVMAttribute @PA); //[DllImport(libraryPath, EntryPoint = "LLVMAddAttribute", CallingConvention = System.Runtime.InteropServices.CallingConvention.Cdecl, BestFitMapping = false, ThrowOnUnmappableChar = true)] //internal static extern void AddAttribute(LLVMValueRef @Arg, LLVMAttribute @PA); //[DllImport(libraryPath, EntryPoint = "LLVMRemoveAttribute", CallingConvention = System.Runtime.InteropServices.CallingConvention.Cdecl, BestFitMapping = false, ThrowOnUnmappableChar = true)] //internal static extern void RemoveAttribute(LLVMValueRef @Arg, LLVMAttribute @PA); //[DllImport(libraryPath, EntryPoint = "LLVMGetAttribute", CallingConvention = System.Runtime.InteropServices.CallingConvention.Cdecl, BestFitMapping = false, ThrowOnUnmappableChar = true)] //internal static extern LLVMAttribute GetAttribute(LLVMValueRef @Arg); //[DllImport(libraryPath, EntryPoint = "LLVMAddInstrAttribute", CallingConvention = System.Runtime.InteropServices.CallingConvention.Cdecl, BestFitMapping = false, ThrowOnUnmappableChar = true)] //internal static extern void AddInstrAttribute(LLVMValueRef @Instr, uint @index, LLVMAttribute @param2); //[DllImport(libraryPath, EntryPoint = "LLVMRemoveInstrAttribute", CallingConvention = System.Runtime.InteropServices.CallingConvention.Cdecl, BestFitMapping = false, ThrowOnUnmappableChar = true)] //internal static extern void RemoveInstrAttribute(LLVMValueRef @Instr, uint @index, LLVMAttribute @param2); [DllImport(libraryPath, EntryPoint = "LLVMCountParams", CallingConvention = System.Runtime.InteropServices.CallingConvention.Cdecl, BestFitMapping = false, ThrowOnUnmappableChar = true)] internal static extern uint CountParams(LLVMValueRef @Fn); [DllImport(libraryPath, EntryPoint = "LLVMGetParams", CallingConvention = System.Runtime.InteropServices.CallingConvention.Cdecl, BestFitMapping = false, ThrowOnUnmappableChar = true)] internal static extern void GetParams(LLVMValueRef @Fn, out LLVMValueRef @Params); [DllImport(libraryPath, EntryPoint = "LLVMGetParam", CallingConvention = System.Runtime.InteropServices.CallingConvention.Cdecl, BestFitMapping = false, ThrowOnUnmappableChar = true)] internal static extern LLVMValueRef GetParam(LLVMValueRef @Fn, uint @Index); [DllImport(libraryPath, EntryPoint = "LLVMGetParamParent", CallingConvention = System.Runtime.InteropServices.CallingConvention.Cdecl, BestFitMapping = false, ThrowOnUnmappableChar = true)] internal static extern LLVMValueRef GetParamParent(LLVMValueRef @Inst); [DllImport(libraryPath, EntryPoint = "LLVMGetFirstParam", CallingConvention = System.Runtime.InteropServices.CallingConvention.Cdecl, BestFitMapping = false, ThrowOnUnmappableChar = true)] internal static extern LLVMValueRef GetFirstParam(LLVMValueRef @Fn); [DllImport(libraryPath, EntryPoint = "LLVMGetLastParam", CallingConvention = System.Runtime.InteropServices.CallingConvention.Cdecl, BestFitMapping = false, ThrowOnUnmappableChar = true)] internal static extern LLVMValueRef GetLastParam(LLVMValueRef @Fn); [DllImport(libraryPath, EntryPoint = "LLVMGetNextParam", CallingConvention = System.Runtime.InteropServices.CallingConvention.Cdecl, BestFitMapping = false, ThrowOnUnmappableChar = true)] internal static extern LLVMValueRef GetNextParam(LLVMValueRef @Arg); [DllImport(libraryPath, EntryPoint = "LLVMGetPreviousParam", CallingConvention = System.Runtime.InteropServices.CallingConvention.Cdecl, BestFitMapping = false, ThrowOnUnmappableChar = true)] internal static extern LLVMValueRef GetPreviousParam(LLVMValueRef @Arg); [DllImport(libraryPath, EntryPoint = "LLVMSetParamAlignment", CallingConvention = System.Runtime.InteropServices.CallingConvention.Cdecl, BestFitMapping = false, ThrowOnUnmappableChar = true)] internal static extern void SetParamAlignment(LLVMValueRef @Arg, uint @align); [DllImport(libraryPath, EntryPoint = "LLVMMDStringInContext", CallingConvention = System.Runtime.InteropServices.CallingConvention.Cdecl, BestFitMapping = false, ThrowOnUnmappableChar = true)] internal static extern LLVMValueRef MDStringInContext(LLVMContextRef @C, [MarshalAs(UnmanagedType.LPStr)] string @Str, uint @SLen); [DllImport(libraryPath, EntryPoint = "LLVMMDString", CallingConvention = System.Runtime.InteropServices.CallingConvention.Cdecl, BestFitMapping = false, ThrowOnUnmappableChar = true)] internal static extern LLVMValueRef MDString([MarshalAs(UnmanagedType.LPStr)] string @Str, uint @SLen); [DllImport(libraryPath, EntryPoint = "LLVMMDNodeInContext", CallingConvention = System.Runtime.InteropServices.CallingConvention.Cdecl, BestFitMapping = false, ThrowOnUnmappableChar = true)] internal static extern LLVMValueRef MDNodeInContext(LLVMContextRef @C, out LLVMValueRef @Vals, uint @Count); [DllImport(libraryPath, EntryPoint = "LLVMMDNode", CallingConvention = System.Runtime.InteropServices.CallingConvention.Cdecl, BestFitMapping = false, ThrowOnUnmappableChar = true)] internal static extern LLVMValueRef MDNode(out LLVMValueRef @Vals, uint @Count); [DllImport(libraryPath, EntryPoint = "LLVMGetMDString", CallingConvention = System.Runtime.InteropServices.CallingConvention.Cdecl, BestFitMapping = false, ThrowOnUnmappableChar = true)] internal static extern IntPtr GetMDString(LLVMValueRef @V, out uint @Len); [DllImport(libraryPath, EntryPoint = "LLVMGetMDNodeNumOperands", CallingConvention = System.Runtime.InteropServices.CallingConvention.Cdecl, BestFitMapping = false, ThrowOnUnmappableChar = true)] internal static extern uint GetMDNodeNumOperands(LLVMValueRef @V); [DllImport(libraryPath, EntryPoint = "LLVMGetMDNodeOperands", CallingConvention = System.Runtime.InteropServices.CallingConvention.Cdecl, BestFitMapping = false, ThrowOnUnmappableChar = true)] internal static extern void GetMDNodeOperands(LLVMValueRef @V, out LLVMValueRef @Dest); [DllImport(libraryPath, EntryPoint = "LLVMBasicBlockAsValue", CallingConvention = System.Runtime.InteropServices.CallingConvention.Cdecl, BestFitMapping = false, ThrowOnUnmappableChar = true)] internal static extern LLVMValueRef BasicBlockAsValue(LLVMBasicBlockRef @BB); [DllImport(libraryPath, EntryPoint = "LLVMValueIsBasicBlock", CallingConvention = System.Runtime.InteropServices.CallingConvention.Cdecl, BestFitMapping = false, ThrowOnUnmappableChar = true)] internal static extern LLVMBool ValueIsBasicBlock(LLVMValueRef @Val); [DllImport(libraryPath, EntryPoint = "LLVMValueAsBasicBlock", CallingConvention = System.Runtime.InteropServices.CallingConvention.Cdecl, BestFitMapping = false, ThrowOnUnmappableChar = true)] internal static extern LLVMBasicBlockRef ValueAsBasicBlock(LLVMValueRef @Val); [DllImport(libraryPath, EntryPoint = "LLVMGetBasicBlockParent", CallingConvention = System.Runtime.InteropServices.CallingConvention.Cdecl, BestFitMapping = false, ThrowOnUnmappableChar = true)] internal static extern LLVMValueRef GetBasicBlockParent(LLVMBasicBlockRef @BB); [DllImport(libraryPath, EntryPoint = "LLVMGetBasicBlockTerminator", CallingConvention = System.Runtime.InteropServices.CallingConvention.Cdecl, BestFitMapping = false, ThrowOnUnmappableChar = true)] internal static extern LLVMValueRef GetBasicBlockTerminator(LLVMBasicBlockRef @BB); [DllImport(libraryPath, EntryPoint = "LLVMCountBasicBlocks", CallingConvention = System.Runtime.InteropServices.CallingConvention.Cdecl, BestFitMapping = false, ThrowOnUnmappableChar = true)] internal static extern uint CountBasicBlocks(LLVMValueRef @Fn); [DllImport(libraryPath, EntryPoint = "LLVMGetBasicBlocks", CallingConvention = System.Runtime.InteropServices.CallingConvention.Cdecl, BestFitMapping = false, ThrowOnUnmappableChar = true)] internal static extern void GetBasicBlocks(LLVMValueRef @Fn, out LLVMBasicBlockRef @BasicBlocks); [DllImport(libraryPath, EntryPoint = "LLVMGetFirstBasicBlock", CallingConvention = System.Runtime.InteropServices.CallingConvention.Cdecl, BestFitMapping = false, ThrowOnUnmappableChar = true)] internal static extern LLVMBasicBlockRef GetFirstBasicBlock(LLVMValueRef @Fn); [DllImport(libraryPath, EntryPoint = "LLVMGetLastBasicBlock", CallingConvention = System.Runtime.InteropServices.CallingConvention.Cdecl, BestFitMapping = false, ThrowOnUnmappableChar = true)] internal static extern LLVMBasicBlockRef GetLastBasicBlock(LLVMValueRef @Fn); [DllImport(libraryPath, EntryPoint = "LLVMGetNextBasicBlock", CallingConvention = System.Runtime.InteropServices.CallingConvention.Cdecl, BestFitMapping = false, ThrowOnUnmappableChar = true)] internal static extern LLVMBasicBlockRef GetNextBasicBlock(LLVMBasicBlockRef @BB); [DllImport(libraryPath, EntryPoint = "LLVMGetPreviousBasicBlock", CallingConvention = System.Runtime.InteropServices.CallingConvention.Cdecl, BestFitMapping = false, ThrowOnUnmappableChar = true)] internal static extern LLVMBasicBlockRef GetPreviousBasicBlock(LLVMBasicBlockRef @BB); [DllImport(libraryPath, EntryPoint = "LLVMGetEntryBasicBlock", CallingConvention = System.Runtime.InteropServices.CallingConvention.Cdecl, BestFitMapping = false, ThrowOnUnmappableChar = true)] internal static extern LLVMBasicBlockRef GetEntryBasicBlock(LLVMValueRef @Fn); [DllImport(libraryPath, EntryPoint = "LLVMAppendBasicBlockInContext", CallingConvention = System.Runtime.InteropServices.CallingConvention.Cdecl, BestFitMapping = false, ThrowOnUnmappableChar = true)] internal static extern LLVMBasicBlockRef AppendBasicBlockInContext(LLVMContextRef @C, LLVMValueRef @Fn, [MarshalAs(UnmanagedType.LPStr)] string @Name); [DllImport(libraryPath, EntryPoint = "LLVMAppendBasicBlock", CallingConvention = System.Runtime.InteropServices.CallingConvention.Cdecl, BestFitMapping = false, ThrowOnUnmappableChar = true)] internal static extern LLVMBasicBlockRef AppendBasicBlock(LLVMValueRef @Fn, [MarshalAs(UnmanagedType.LPStr)] string @Name); [DllImport(libraryPath, EntryPoint = "LLVMInsertBasicBlockInContext", CallingConvention = System.Runtime.InteropServices.CallingConvention.Cdecl, BestFitMapping = false, ThrowOnUnmappableChar = true)] internal static extern LLVMBasicBlockRef InsertBasicBlockInContext(LLVMContextRef @C, LLVMBasicBlockRef @BB, [MarshalAs(UnmanagedType.LPStr)] string @Name); [DllImport(libraryPath, EntryPoint = "LLVMInsertBasicBlock", CallingConvention = System.Runtime.InteropServices.CallingConvention.Cdecl, BestFitMapping = false, ThrowOnUnmappableChar = true)] internal static extern LLVMBasicBlockRef InsertBasicBlock(LLVMBasicBlockRef @InsertBeforeBB, [MarshalAs(UnmanagedType.LPStr)] string @Name); [DllImport(libraryPath, EntryPoint = "LLVMDeleteBasicBlock", CallingConvention = System.Runtime.InteropServices.CallingConvention.Cdecl, BestFitMapping = false, ThrowOnUnmappableChar = true)] internal static extern void DeleteBasicBlock(LLVMBasicBlockRef @BB); [DllImport(libraryPath, EntryPoint = "LLVMRemoveBasicBlockFromParent", CallingConvention = System.Runtime.InteropServices.CallingConvention.Cdecl, BestFitMapping = false, ThrowOnUnmappableChar = true)] internal static extern void RemoveBasicBlockFromParent(LLVMBasicBlockRef @BB); [DllImport(libraryPath, EntryPoint = "LLVMMoveBasicBlockBefore", CallingConvention = System.Runtime.InteropServices.CallingConvention.Cdecl, BestFitMapping = false, ThrowOnUnmappableChar = true)] internal static extern void MoveBasicBlockBefore(LLVMBasicBlockRef @BB, LLVMBasicBlockRef @MovePos); [DllImport(libraryPath, EntryPoint = "LLVMMoveBasicBlockAfter", CallingConvention = System.Runtime.InteropServices.CallingConvention.Cdecl, BestFitMapping = false, ThrowOnUnmappableChar = true)] internal static extern void MoveBasicBlockAfter(LLVMBasicBlockRef @BB, LLVMBasicBlockRef @MovePos); [DllImport(libraryPath, EntryPoint = "LLVMGetFirstInstruction", CallingConvention = System.Runtime.InteropServices.CallingConvention.Cdecl, BestFitMapping = false, ThrowOnUnmappableChar = true)] internal static extern LLVMValueRef GetFirstInstruction(LLVMBasicBlockRef @BB); [DllImport(libraryPath, EntryPoint = "LLVMGetLastInstruction", CallingConvention = System.Runtime.InteropServices.CallingConvention.Cdecl, BestFitMapping = false, ThrowOnUnmappableChar = true)] internal static extern LLVMValueRef GetLastInstruction(LLVMBasicBlockRef @BB); [DllImport(libraryPath, EntryPoint = "LLVMHasMetadata", CallingConvention = System.Runtime.InteropServices.CallingConvention.Cdecl, BestFitMapping = false, ThrowOnUnmappableChar = true)] internal static extern int HasMetadata(LLVMValueRef @Val); [DllImport(libraryPath, EntryPoint = "LLVMGetMetadata", CallingConvention = System.Runtime.InteropServices.CallingConvention.Cdecl, BestFitMapping = false, ThrowOnUnmappableChar = true)] internal static extern LLVMValueRef GetMetadata(LLVMValueRef @Val, uint @KindID); [DllImport(libraryPath, EntryPoint = "LLVMSetMetadata", CallingConvention = System.Runtime.InteropServices.CallingConvention.Cdecl, BestFitMapping = false, ThrowOnUnmappableChar = true)] internal static extern void SetMetadata(LLVMValueRef @Val, uint @KindID, LLVMValueRef @Node); [DllImport(libraryPath, EntryPoint = "LLVMGetInstructionParent", CallingConvention = System.Runtime.InteropServices.CallingConvention.Cdecl, BestFitMapping = false, ThrowOnUnmappableChar = true)] internal static extern LLVMBasicBlockRef GetInstructionParent(LLVMValueRef @Inst); [DllImport(libraryPath, EntryPoint = "LLVMGetNextInstruction", CallingConvention = System.Runtime.InteropServices.CallingConvention.Cdecl, BestFitMapping = false, ThrowOnUnmappableChar = true)] internal static extern LLVMValueRef GetNextInstruction(LLVMValueRef @Inst); [DllImport(libraryPath, EntryPoint = "LLVMGetPreviousInstruction", CallingConvention = System.Runtime.InteropServices.CallingConvention.Cdecl, BestFitMapping = false, ThrowOnUnmappableChar = true)] internal static extern LLVMValueRef GetPreviousInstruction(LLVMValueRef @Inst); [DllImport(libraryPath, EntryPoint = "LLVMInstructionEraseFromParent", CallingConvention = System.Runtime.InteropServices.CallingConvention.Cdecl, BestFitMapping = false, ThrowOnUnmappableChar = true)] internal static extern void InstructionEraseFromParent(LLVMValueRef @Inst); [DllImport(libraryPath, EntryPoint = "LLVMGetInstructionOpcode", CallingConvention = System.Runtime.InteropServices.CallingConvention.Cdecl, BestFitMapping = false, ThrowOnUnmappableChar = true)] internal static extern LLVMOpcode GetInstructionOpcode(LLVMValueRef @Inst); [DllImport(libraryPath, EntryPoint = "LLVMGetICmpPredicate", CallingConvention = System.Runtime.InteropServices.CallingConvention.Cdecl, BestFitMapping = false, ThrowOnUnmappableChar = true)] internal static extern LLVMIntPredicate GetICmpPredicate(LLVMValueRef @Inst); [DllImport(libraryPath, EntryPoint = "LLVMGetFCmpPredicate", CallingConvention = System.Runtime.InteropServices.CallingConvention.Cdecl, BestFitMapping = false, ThrowOnUnmappableChar = true)] internal static extern LLVMRealPredicate GetFCmpPredicate(LLVMValueRef @Inst); [DllImport(libraryPath, EntryPoint = "LLVMInstructionClone", CallingConvention = System.Runtime.InteropServices.CallingConvention.Cdecl, BestFitMapping = false, ThrowOnUnmappableChar = true)] internal static extern LLVMValueRef InstructionClone(LLVMValueRef @Inst); [DllImport(libraryPath, EntryPoint = "LLVMSetInstructionCallConv", CallingConvention = System.Runtime.InteropServices.CallingConvention.Cdecl, BestFitMapping = false, ThrowOnUnmappableChar = true)] internal static extern void SetInstructionCallConv(LLVMValueRef @Instr, uint @CC); [DllImport(libraryPath, EntryPoint = "LLVMGetInstructionCallConv", CallingConvention = System.Runtime.InteropServices.CallingConvention.Cdecl, BestFitMapping = false, ThrowOnUnmappableChar = true)] internal static extern uint GetInstructionCallConv(LLVMValueRef @Instr); [DllImport(libraryPath, EntryPoint = "LLVMSetInstrParamAlignment", CallingConvention = System.Runtime.InteropServices.CallingConvention.Cdecl, BestFitMapping = false, ThrowOnUnmappableChar = true)] internal static extern void SetInstrParamAlignment(LLVMValueRef @Instr, uint @index, uint @align); [DllImport(libraryPath, EntryPoint = "LLVMIsTailCall", CallingConvention = System.Runtime.InteropServices.CallingConvention.Cdecl, BestFitMapping = false, ThrowOnUnmappableChar = true)] internal static extern LLVMBool IsTailCall(LLVMValueRef @CallInst); [DllImport(libraryPath, EntryPoint = "LLVMSetTailCall", CallingConvention = System.Runtime.InteropServices.CallingConvention.Cdecl, BestFitMapping = false, ThrowOnUnmappableChar = true)] internal static extern void SetTailCall(LLVMValueRef @CallInst, LLVMBool @IsTailCall); [DllImport(libraryPath, EntryPoint = "LLVMGetNumSuccessors", CallingConvention = System.Runtime.InteropServices.CallingConvention.Cdecl, BestFitMapping = false, ThrowOnUnmappableChar = true)] internal static extern uint GetNumSuccessors(LLVMValueRef @Term); [DllImport(libraryPath, EntryPoint = "LLVMGetSuccessor", CallingConvention = System.Runtime.InteropServices.CallingConvention.Cdecl, BestFitMapping = false, ThrowOnUnmappableChar = true)] internal static extern LLVMBasicBlockRef GetSuccessor(LLVMValueRef @Term, uint @i); [DllImport(libraryPath, EntryPoint = "LLVMSetSuccessor", CallingConvention = System.Runtime.InteropServices.CallingConvention.Cdecl, BestFitMapping = false, ThrowOnUnmappableChar = true)] internal static extern void SetSuccessor(LLVMValueRef @Term, uint @i, LLVMBasicBlockRef @block); [DllImport(libraryPath, EntryPoint = "LLVMIsConditional", CallingConvention = System.Runtime.InteropServices.CallingConvention.Cdecl, BestFitMapping = false, ThrowOnUnmappableChar = true)] internal static extern LLVMBool IsConditional(LLVMValueRef @Branch); [DllImport(libraryPath, EntryPoint = "LLVMGetCondition", CallingConvention = System.Runtime.InteropServices.CallingConvention.Cdecl, BestFitMapping = false, ThrowOnUnmappableChar = true)] internal static extern LLVMValueRef GetCondition(LLVMValueRef @Branch); [DllImport(libraryPath, EntryPoint = "LLVMSetCondition", CallingConvention = System.Runtime.InteropServices.CallingConvention.Cdecl, BestFitMapping = false, ThrowOnUnmappableChar = true)] internal static extern void SetCondition(LLVMValueRef @Branch, LLVMValueRef @Cond); [DllImport(libraryPath, EntryPoint = "LLVMGetSwitchDefaultDest", CallingConvention = System.Runtime.InteropServices.CallingConvention.Cdecl, BestFitMapping = false, ThrowOnUnmappableChar = true)] internal static extern LLVMBasicBlockRef GetSwitchDefaultDest(LLVMValueRef @SwitchInstr); [DllImport(libraryPath, EntryPoint = "LLVMAddIncoming", CallingConvention = System.Runtime.InteropServices.CallingConvention.Cdecl, BestFitMapping = false, ThrowOnUnmappableChar = true)] internal static extern void AddIncoming(LLVMValueRef @PhiNode, out LLVMValueRef @IncomingValues, out LLVMBasicBlockRef @IncomingBlocks, uint @Count); [DllImport(libraryPath, EntryPoint = "LLVMCountIncoming", CallingConvention = System.Runtime.InteropServices.CallingConvention.Cdecl, BestFitMapping = false, ThrowOnUnmappableChar = true)] internal static extern uint CountIncoming(LLVMValueRef @PhiNode); [DllImport(libraryPath, EntryPoint = "LLVMGetIncomingValue", CallingConvention = System.Runtime.InteropServices.CallingConvention.Cdecl, BestFitMapping = false, ThrowOnUnmappableChar = true)] internal static extern LLVMValueRef GetIncomingValue(LLVMValueRef @PhiNode, uint @Index); [DllImport(libraryPath, EntryPoint = "LLVMGetIncomingBlock", CallingConvention = System.Runtime.InteropServices.CallingConvention.Cdecl, BestFitMapping = false, ThrowOnUnmappableChar = true)] internal static extern LLVMBasicBlockRef GetIncomingBlock(LLVMValueRef @PhiNode, uint @Index); [DllImport(libraryPath, EntryPoint = "LLVMCreateBuilderInContext", CallingConvention = System.Runtime.InteropServices.CallingConvention.Cdecl, BestFitMapping = false, ThrowOnUnmappableChar = true)] internal static extern LLVMBuilderRef CreateBuilderInContext(LLVMContextRef @C); [DllImport(libraryPath, EntryPoint = "LLVMCreateBuilder", CallingConvention = System.Runtime.InteropServices.CallingConvention.Cdecl, BestFitMapping = false, ThrowOnUnmappableChar = true)] internal static extern LLVMBuilderRef CreateBuilder(); [DllImport(libraryPath, EntryPoint = "LLVMPositionBuilder", CallingConvention = System.Runtime.InteropServices.CallingConvention.Cdecl, BestFitMapping = false, ThrowOnUnmappableChar = true)] internal static extern void PositionBuilder(LLVMBuilderRef @Builder, LLVMBasicBlockRef @Block, LLVMValueRef @Instr); [DllImport(libraryPath, EntryPoint = "LLVMPositionBuilderBefore", CallingConvention = System.Runtime.InteropServices.CallingConvention.Cdecl, BestFitMapping = false, ThrowOnUnmappableChar = true)] internal static extern void PositionBuilderBefore(LLVMBuilderRef @Builder, LLVMValueRef @Instr); [DllImport(libraryPath, EntryPoint = "LLVMPositionBuilderAtEnd", CallingConvention = System.Runtime.InteropServices.CallingConvention.Cdecl, BestFitMapping = false, ThrowOnUnmappableChar = true)] internal static extern void PositionBuilderAtEnd(LLVMBuilderRef @Builder, LLVMBasicBlockRef @Block); [DllImport(libraryPath, EntryPoint = "LLVMGetInsertBlock", CallingConvention = System.Runtime.InteropServices.CallingConvention.Cdecl, BestFitMapping = false, ThrowOnUnmappableChar = true)] internal static extern LLVMBasicBlockRef GetInsertBlock(LLVMBuilderRef @Builder); [DllImport(libraryPath, EntryPoint = "LLVMClearInsertionPosition", CallingConvention = System.Runtime.InteropServices.CallingConvention.Cdecl, BestFitMapping = false, ThrowOnUnmappableChar = true)] internal static extern void ClearInsertionPosition(LLVMBuilderRef @Builder); [DllImport(libraryPath, EntryPoint = "LLVMInsertIntoBuilder", CallingConvention = System.Runtime.InteropServices.CallingConvention.Cdecl, BestFitMapping = false, ThrowOnUnmappableChar = true)] internal static extern void InsertIntoBuilder(LLVMBuilderRef @Builder, LLVMValueRef @Instr); [DllImport(libraryPath, EntryPoint = "LLVMInsertIntoBuilderWithName", CallingConvention = System.Runtime.InteropServices.CallingConvention.Cdecl, BestFitMapping = false, ThrowOnUnmappableChar = true)] internal static extern void InsertIntoBuilderWithName(LLVMBuilderRef @Builder, LLVMValueRef @Instr, [MarshalAs(UnmanagedType.LPStr)] string @Name); [DllImport(libraryPath, EntryPoint = "LLVMDisposeBuilder", CallingConvention = System.Runtime.InteropServices.CallingConvention.Cdecl, BestFitMapping = false, ThrowOnUnmappableChar = true)] internal static extern void DisposeBuilder(LLVMBuilderRef @Builder); [DllImport(libraryPath, EntryPoint = "LLVMSetCurrentDebugLocation", CallingConvention = System.Runtime.InteropServices.CallingConvention.Cdecl, BestFitMapping = false, ThrowOnUnmappableChar = true)] internal static extern void SetCurrentDebugLocation(LLVMBuilderRef @Builder, LLVMValueRef @L); [DllImport(libraryPath, EntryPoint = "LLVMGetCurrentDebugLocation", CallingConvention = System.Runtime.InteropServices.CallingConvention.Cdecl, BestFitMapping = false, ThrowOnUnmappableChar = true)] internal static extern LLVMValueRef GetCurrentDebugLocation(LLVMBuilderRef @Builder); [DllImport(libraryPath, EntryPoint = "LLVMSetInstDebugLocation", CallingConvention = System.Runtime.InteropServices.CallingConvention.Cdecl, BestFitMapping = false, ThrowOnUnmappableChar = true)] internal static extern void SetInstDebugLocation(LLVMBuilderRef @Builder, LLVMValueRef @Inst); [DllImport(libraryPath, EntryPoint = "LLVMBuildRetVoid", CallingConvention = System.Runtime.InteropServices.CallingConvention.Cdecl, BestFitMapping = false, ThrowOnUnmappableChar = true)] internal static extern LLVMValueRef BuildRetVoid(LLVMBuilderRef @param0); [DllImport(libraryPath, EntryPoint = "LLVMBuildRet", CallingConvention = System.Runtime.InteropServices.CallingConvention.Cdecl, BestFitMapping = false, ThrowOnUnmappableChar = true)] internal static extern LLVMValueRef BuildRet(LLVMBuilderRef @param0, LLVMValueRef @V); [DllImport(libraryPath, EntryPoint = "LLVMBuildAggregateRet", CallingConvention = System.Runtime.InteropServices.CallingConvention.Cdecl, BestFitMapping = false, ThrowOnUnmappableChar = true)] internal static extern LLVMValueRef BuildAggregateRet(LLVMBuilderRef @param0, out LLVMValueRef @RetVals, uint @N); [DllImport(libraryPath, EntryPoint = "LLVMBuildBr", CallingConvention = System.Runtime.InteropServices.CallingConvention.Cdecl, BestFitMapping = false, ThrowOnUnmappableChar = true)] internal static extern LLVMValueRef BuildBr(LLVMBuilderRef @param0, LLVMBasicBlockRef @Dest); [DllImport(libraryPath, EntryPoint = "LLVMBuildCondBr", CallingConvention = System.Runtime.InteropServices.CallingConvention.Cdecl, BestFitMapping = false, ThrowOnUnmappableChar = true)] internal static extern LLVMValueRef BuildCondBr(LLVMBuilderRef @param0, LLVMValueRef @If, LLVMBasicBlockRef @Then, LLVMBasicBlockRef @Else); [DllImport(libraryPath, EntryPoint = "LLVMBuildSwitch", CallingConvention = System.Runtime.InteropServices.CallingConvention.Cdecl, BestFitMapping = false, ThrowOnUnmappableChar = true)] internal static extern LLVMValueRef BuildSwitch(LLVMBuilderRef @param0, LLVMValueRef @V, LLVMBasicBlockRef @Else, uint @NumCases); [DllImport(libraryPath, EntryPoint = "LLVMBuildIndirectBr", CallingConvention = System.Runtime.InteropServices.CallingConvention.Cdecl, BestFitMapping = false, ThrowOnUnmappableChar = true)] internal static extern LLVMValueRef BuildIndirectBr(LLVMBuilderRef @B, LLVMValueRef @Addr, uint @NumDests); [DllImport(libraryPath, EntryPoint = "LLVMBuildInvoke", CallingConvention = System.Runtime.InteropServices.CallingConvention.Cdecl, BestFitMapping = false, ThrowOnUnmappableChar = true)] internal static extern LLVMValueRef BuildInvoke(LLVMBuilderRef @param0, LLVMValueRef @Fn, out LLVMValueRef @Args, uint @NumArgs, LLVMBasicBlockRef @Then, LLVMBasicBlockRef @Catch, [MarshalAs(UnmanagedType.LPStr)] string @Name); [DllImport(libraryPath, EntryPoint = "LLVMBuildLandingPad", CallingConvention = System.Runtime.InteropServices.CallingConvention.Cdecl, BestFitMapping = false, ThrowOnUnmappableChar = true)] internal static extern LLVMValueRef BuildLandingPad(LLVMBuilderRef @B, LLVMTypeRef @Ty, LLVMValueRef PersFn, uint @NumClauses, [MarshalAs(UnmanagedType.LPStr)] string @Name); [DllImport(libraryPath, EntryPoint = "LLVMBuildResume", CallingConvention = System.Runtime.InteropServices.CallingConvention.Cdecl, BestFitMapping = false, ThrowOnUnmappableChar = true)] internal static extern LLVMValueRef BuildResume(LLVMBuilderRef @B, LLVMValueRef @Exn); [DllImport(libraryPath, EntryPoint = "LLVMBuildUnreachable", CallingConvention = System.Runtime.InteropServices.CallingConvention.Cdecl, BestFitMapping = false, ThrowOnUnmappableChar = true)] internal static extern LLVMValueRef BuildUnreachable(LLVMBuilderRef @param0); [DllImport(libraryPath, EntryPoint = "LLVMAddCase", CallingConvention = System.Runtime.InteropServices.CallingConvention.Cdecl, BestFitMapping = false, ThrowOnUnmappableChar = true)] internal static extern void AddCase(LLVMValueRef @Switch, LLVMValueRef @OnVal, LLVMBasicBlockRef @Dest); [DllImport(libraryPath, EntryPoint = "LLVMAddDestination", CallingConvention = System.Runtime.InteropServices.CallingConvention.Cdecl, BestFitMapping = false, ThrowOnUnmappableChar = true)] internal static extern void AddDestination(LLVMValueRef @IndirectBr, LLVMBasicBlockRef @Dest); [DllImport(libraryPath, EntryPoint = "LLVMAddClause", CallingConvention = System.Runtime.InteropServices.CallingConvention.Cdecl, BestFitMapping = false, ThrowOnUnmappableChar = true)] internal static extern void AddClause(LLVMValueRef @LandingPad, LLVMValueRef @ClauseVal); [DllImport(libraryPath, EntryPoint = "LLVMSetCleanup", CallingConvention = System.Runtime.InteropServices.CallingConvention.Cdecl, BestFitMapping = false, ThrowOnUnmappableChar = true)] internal static extern void SetCleanup(LLVMValueRef @LandingPad, LLVMBool @Val); [DllImport(libraryPath, EntryPoint = "LLVMBuildAdd", CallingConvention = System.Runtime.InteropServices.CallingConvention.Cdecl, BestFitMapping = false, ThrowOnUnmappableChar = true)] internal static extern LLVMValueRef BuildAdd(LLVMBuilderRef @param0, LLVMValueRef @LHS, LLVMValueRef @RHS, [MarshalAs(UnmanagedType.LPStr)] string @Name); [DllImport(libraryPath, EntryPoint = "LLVMBuildNSWAdd", CallingConvention = System.Runtime.InteropServices.CallingConvention.Cdecl, BestFitMapping = false, ThrowOnUnmappableChar = true)] internal static extern LLVMValueRef BuildNSWAdd(LLVMBuilderRef @param0, LLVMValueRef @LHS, LLVMValueRef @RHS, [MarshalAs(UnmanagedType.LPStr)] string @Name); [DllImport(libraryPath, EntryPoint = "LLVMBuildNUWAdd", CallingConvention = System.Runtime.InteropServices.CallingConvention.Cdecl, BestFitMapping = false, ThrowOnUnmappableChar = true)] internal static extern LLVMValueRef BuildNUWAdd(LLVMBuilderRef @param0, LLVMValueRef @LHS, LLVMValueRef @RHS, [MarshalAs(UnmanagedType.LPStr)] string @Name); [DllImport(libraryPath, EntryPoint = "LLVMBuildFAdd", CallingConvention = System.Runtime.InteropServices.CallingConvention.Cdecl, BestFitMapping = false, ThrowOnUnmappableChar = true)] internal static extern LLVMValueRef BuildFAdd(LLVMBuilderRef @param0, LLVMValueRef @LHS, LLVMValueRef @RHS, [MarshalAs(UnmanagedType.LPStr)] string @Name); [DllImport(libraryPath, EntryPoint = "LLVMBuildSub", CallingConvention = System.Runtime.InteropServices.CallingConvention.Cdecl, BestFitMapping = false, ThrowOnUnmappableChar = true)] internal static extern LLVMValueRef BuildSub(LLVMBuilderRef @param0, LLVMValueRef @LHS, LLVMValueRef @RHS, [MarshalAs(UnmanagedType.LPStr)] string @Name); [DllImport(libraryPath, EntryPoint = "LLVMBuildNSWSub", CallingConvention = System.Runtime.InteropServices.CallingConvention.Cdecl, BestFitMapping = false, ThrowOnUnmappableChar = true)] internal static extern LLVMValueRef BuildNSWSub(LLVMBuilderRef @param0, LLVMValueRef @LHS, LLVMValueRef @RHS, [MarshalAs(UnmanagedType.LPStr)] string @Name); [DllImport(libraryPath, EntryPoint = "LLVMBuildNUWSub", CallingConvention = System.Runtime.InteropServices.CallingConvention.Cdecl, BestFitMapping = false, ThrowOnUnmappableChar = true)] internal static extern LLVMValueRef BuildNUWSub(LLVMBuilderRef @param0, LLVMValueRef @LHS, LLVMValueRef @RHS, [MarshalAs(UnmanagedType.LPStr)] string @Name); [DllImport(libraryPath, EntryPoint = "LLVMBuildFSub", CallingConvention = System.Runtime.InteropServices.CallingConvention.Cdecl, BestFitMapping = false, ThrowOnUnmappableChar = true)] internal static extern LLVMValueRef BuildFSub(LLVMBuilderRef @param0, LLVMValueRef @LHS, LLVMValueRef @RHS, [MarshalAs(UnmanagedType.LPStr)] string @Name); [DllImport(libraryPath, EntryPoint = "LLVMBuildMul", CallingConvention = System.Runtime.InteropServices.CallingConvention.Cdecl, BestFitMapping = false, ThrowOnUnmappableChar = true)] internal static extern LLVMValueRef BuildMul(LLVMBuilderRef @param0, LLVMValueRef @LHS, LLVMValueRef @RHS, [MarshalAs(UnmanagedType.LPStr)] string @Name); [DllImport(libraryPath, EntryPoint = "LLVMBuildNSWMul", CallingConvention = System.Runtime.InteropServices.CallingConvention.Cdecl, BestFitMapping = false, ThrowOnUnmappableChar = true)] internal static extern LLVMValueRef BuildNSWMul(LLVMBuilderRef @param0, LLVMValueRef @LHS, LLVMValueRef @RHS, [MarshalAs(UnmanagedType.LPStr)] string @Name); [DllImport(libraryPath, EntryPoint = "LLVMBuildNUWMul", CallingConvention = System.Runtime.InteropServices.CallingConvention.Cdecl, BestFitMapping = false, ThrowOnUnmappableChar = true)] internal static extern LLVMValueRef BuildNUWMul(LLVMBuilderRef @param0, LLVMValueRef @LHS, LLVMValueRef @RHS, [MarshalAs(UnmanagedType.LPStr)] string @Name); [DllImport(libraryPath, EntryPoint = "LLVMBuildFMul", CallingConvention = System.Runtime.InteropServices.CallingConvention.Cdecl, BestFitMapping = false, ThrowOnUnmappableChar = true)] internal static extern LLVMValueRef BuildFMul(LLVMBuilderRef @param0, LLVMValueRef @LHS, LLVMValueRef @RHS, [MarshalAs(UnmanagedType.LPStr)] string @Name); [DllImport(libraryPath, EntryPoint = "LLVMBuildUDiv", CallingConvention = System.Runtime.InteropServices.CallingConvention.Cdecl, BestFitMapping = false, ThrowOnUnmappableChar = true)] internal static extern LLVMValueRef BuildUDiv(LLVMBuilderRef @param0, LLVMValueRef @LHS, LLVMValueRef @RHS, [MarshalAs(UnmanagedType.LPStr)] string @Name); [DllImport(libraryPath, EntryPoint = "LLVMBuildSDiv", CallingConvention = System.Runtime.InteropServices.CallingConvention.Cdecl, BestFitMapping = false, ThrowOnUnmappableChar = true)] internal static extern LLVMValueRef BuildSDiv(LLVMBuilderRef @param0, LLVMValueRef @LHS, LLVMValueRef @RHS, [MarshalAs(UnmanagedType.LPStr)] string @Name); [DllImport(libraryPath, EntryPoint = "LLVMBuildExactSDiv", CallingConvention = System.Runtime.InteropServices.CallingConvention.Cdecl, BestFitMapping = false, ThrowOnUnmappableChar = true)] internal static extern LLVMValueRef BuildExactSDiv(LLVMBuilderRef @param0, LLVMValueRef @LHS, LLVMValueRef @RHS, [MarshalAs(UnmanagedType.LPStr)] string @Name); [DllImport(libraryPath, EntryPoint = "LLVMBuildFDiv", CallingConvention = System.Runtime.InteropServices.CallingConvention.Cdecl, BestFitMapping = false, ThrowOnUnmappableChar = true)] internal static extern LLVMValueRef BuildFDiv(LLVMBuilderRef @param0, LLVMValueRef @LHS, LLVMValueRef @RHS, [MarshalAs(UnmanagedType.LPStr)] string @Name); [DllImport(libraryPath, EntryPoint = "LLVMBuildURem", CallingConvention = System.Runtime.InteropServices.CallingConvention.Cdecl, BestFitMapping = false, ThrowOnUnmappableChar = true)] internal static extern LLVMValueRef BuildURem(LLVMBuilderRef @param0, LLVMValueRef @LHS, LLVMValueRef @RHS, [MarshalAs(UnmanagedType.LPStr)] string @Name); [DllImport(libraryPath, EntryPoint = "LLVMBuildSRem", CallingConvention = System.Runtime.InteropServices.CallingConvention.Cdecl, BestFitMapping = false, ThrowOnUnmappableChar = true)] internal static extern LLVMValueRef BuildSRem(LLVMBuilderRef @param0, LLVMValueRef @LHS, LLVMValueRef @RHS, [MarshalAs(UnmanagedType.LPStr)] string @Name); [DllImport(libraryPath, EntryPoint = "LLVMBuildFRem", CallingConvention = System.Runtime.InteropServices.CallingConvention.Cdecl, BestFitMapping = false, ThrowOnUnmappableChar = true)] internal static extern LLVMValueRef BuildFRem(LLVMBuilderRef @param0, LLVMValueRef @LHS, LLVMValueRef @RHS, [MarshalAs(UnmanagedType.LPStr)] string @Name); [DllImport(libraryPath, EntryPoint = "LLVMBuildShl", CallingConvention = System.Runtime.InteropServices.CallingConvention.Cdecl, BestFitMapping = false, ThrowOnUnmappableChar = true)] internal static extern LLVMValueRef BuildShl(LLVMBuilderRef @param0, LLVMValueRef @LHS, LLVMValueRef @RHS, [MarshalAs(UnmanagedType.LPStr)] string @Name); [DllImport(libraryPath, EntryPoint = "LLVMBuildLShr", CallingConvention = System.Runtime.InteropServices.CallingConvention.Cdecl, BestFitMapping = false, ThrowOnUnmappableChar = true)] internal static extern LLVMValueRef BuildLShr(LLVMBuilderRef @param0, LLVMValueRef @LHS, LLVMValueRef @RHS, [MarshalAs(UnmanagedType.LPStr)] string @Name); [DllImport(libraryPath, EntryPoint = "LLVMBuildAShr", CallingConvention = System.Runtime.InteropServices.CallingConvention.Cdecl, BestFitMapping = false, ThrowOnUnmappableChar = true)] internal static extern LLVMValueRef BuildAShr(LLVMBuilderRef @param0, LLVMValueRef @LHS, LLVMValueRef @RHS, [MarshalAs(UnmanagedType.LPStr)] string @Name); [DllImport(libraryPath, EntryPoint = "LLVMBuildAnd", CallingConvention = System.Runtime.InteropServices.CallingConvention.Cdecl, BestFitMapping = false, ThrowOnUnmappableChar = true)] internal static extern LLVMValueRef BuildAnd(LLVMBuilderRef @param0, LLVMValueRef @LHS, LLVMValueRef @RHS, [MarshalAs(UnmanagedType.LPStr)] string @Name); [DllImport(libraryPath, EntryPoint = "LLVMBuildOr", CallingConvention = System.Runtime.InteropServices.CallingConvention.Cdecl, BestFitMapping = false, ThrowOnUnmappableChar = true)] internal static extern LLVMValueRef BuildOr(LLVMBuilderRef @param0, LLVMValueRef @LHS, LLVMValueRef @RHS, [MarshalAs(UnmanagedType.LPStr)] string @Name); [DllImport(libraryPath, EntryPoint = "LLVMBuildXor", CallingConvention = System.Runtime.InteropServices.CallingConvention.Cdecl, BestFitMapping = false, ThrowOnUnmappableChar = true)] internal static extern LLVMValueRef BuildXor(LLVMBuilderRef @param0, LLVMValueRef @LHS, LLVMValueRef @RHS, [MarshalAs(UnmanagedType.LPStr)] string @Name); [DllImport(libraryPath, EntryPoint = "LLVMBuildBinOp", CallingConvention = System.Runtime.InteropServices.CallingConvention.Cdecl, BestFitMapping = false, ThrowOnUnmappableChar = true)] internal static extern LLVMValueRef BuildBinOp(LLVMBuilderRef @B, LLVMOpcode @Op, LLVMValueRef @LHS, LLVMValueRef @RHS, [MarshalAs(UnmanagedType.LPStr)] string @Name); [DllImport(libraryPath, EntryPoint = "LLVMBuildNeg", CallingConvention = System.Runtime.InteropServices.CallingConvention.Cdecl, BestFitMapping = false, ThrowOnUnmappableChar = true)] internal static extern LLVMValueRef BuildNeg(LLVMBuilderRef @param0, LLVMValueRef @V, [MarshalAs(UnmanagedType.LPStr)] string @Name); [DllImport(libraryPath, EntryPoint = "LLVMBuildNSWNeg", CallingConvention = System.Runtime.InteropServices.CallingConvention.Cdecl, BestFitMapping = false, ThrowOnUnmappableChar = true)] internal static extern LLVMValueRef BuildNSWNeg(LLVMBuilderRef @B, LLVMValueRef @V, [MarshalAs(UnmanagedType.LPStr)] string @Name); [DllImport(libraryPath, EntryPoint = "LLVMBuildNUWNeg", CallingConvention = System.Runtime.InteropServices.CallingConvention.Cdecl, BestFitMapping = false, ThrowOnUnmappableChar = true)] internal static extern LLVMValueRef BuildNUWNeg(LLVMBuilderRef @B, LLVMValueRef @V, [MarshalAs(UnmanagedType.LPStr)] string @Name); [DllImport(libraryPath, EntryPoint = "LLVMBuildFNeg", CallingConvention = System.Runtime.InteropServices.CallingConvention.Cdecl, BestFitMapping = false, ThrowOnUnmappableChar = true)] internal static extern LLVMValueRef BuildFNeg(LLVMBuilderRef @param0, LLVMValueRef @V, [MarshalAs(UnmanagedType.LPStr)] string @Name); [DllImport(libraryPath, EntryPoint = "LLVMBuildNot", CallingConvention = System.Runtime.InteropServices.CallingConvention.Cdecl, BestFitMapping = false, ThrowOnUnmappableChar = true)] internal static extern LLVMValueRef BuildNot(LLVMBuilderRef @param0, LLVMValueRef @V, [MarshalAs(UnmanagedType.LPStr)] string @Name); [DllImport(libraryPath, EntryPoint = "LLVMBuildMalloc", CallingConvention = System.Runtime.InteropServices.CallingConvention.Cdecl, BestFitMapping = false, ThrowOnUnmappableChar = true)] internal static extern LLVMValueRef BuildMalloc(LLVMBuilderRef @param0, LLVMTypeRef @Ty, [MarshalAs(UnmanagedType.LPStr)] string @Name); [DllImport(libraryPath, EntryPoint = "LLVMBuildArrayMalloc", CallingConvention = System.Runtime.InteropServices.CallingConvention.Cdecl, BestFitMapping = false, ThrowOnUnmappableChar = true)] internal static extern LLVMValueRef BuildArrayMalloc(LLVMBuilderRef @param0, LLVMTypeRef @Ty, LLVMValueRef @Val, [MarshalAs(UnmanagedType.LPStr)] string @Name); [DllImport(libraryPath, EntryPoint = "LLVMBuildAlloca", CallingConvention = System.Runtime.InteropServices.CallingConvention.Cdecl, BestFitMapping = false, ThrowOnUnmappableChar = true)] internal static extern LLVMValueRef BuildAlloca(LLVMBuilderRef @param0, LLVMTypeRef @Ty, [MarshalAs(UnmanagedType.LPStr)] string @Name); [DllImport(libraryPath, EntryPoint = "LLVMBuildArrayAlloca", CallingConvention = System.Runtime.InteropServices.CallingConvention.Cdecl, BestFitMapping = false, ThrowOnUnmappableChar = true)] internal static extern LLVMValueRef BuildArrayAlloca(LLVMBuilderRef @param0, LLVMTypeRef @Ty, LLVMValueRef @Val, [MarshalAs(UnmanagedType.LPStr)] string @Name); [DllImport(libraryPath, EntryPoint = "LLVMBuildFree", CallingConvention = System.Runtime.InteropServices.CallingConvention.Cdecl, BestFitMapping = false, ThrowOnUnmappableChar = true)] internal static extern LLVMValueRef BuildFree(LLVMBuilderRef @param0, LLVMValueRef @PointerVal); [DllImport(libraryPath, EntryPoint = "LLVMBuildLoad", CallingConvention = System.Runtime.InteropServices.CallingConvention.Cdecl, BestFitMapping = false, ThrowOnUnmappableChar = true)] internal static extern LLVMValueRef BuildLoad(LLVMBuilderRef @param0, LLVMValueRef @PointerVal, [MarshalAs(UnmanagedType.LPStr)] string @Name); [DllImport(libraryPath, EntryPoint = "LLVMBuildStore", CallingConvention = System.Runtime.InteropServices.CallingConvention.Cdecl, BestFitMapping = false, ThrowOnUnmappableChar = true)] internal static extern LLVMValueRef BuildStore(LLVMBuilderRef @param0, LLVMValueRef @Val, LLVMValueRef @Ptr); [DllImport(libraryPath, EntryPoint = "LLVMBuildGEP", CallingConvention = System.Runtime.InteropServices.CallingConvention.Cdecl, BestFitMapping = false, ThrowOnUnmappableChar = true)] internal static extern LLVMValueRef BuildGEP(LLVMBuilderRef @B, LLVMValueRef @Pointer, out LLVMValueRef @Indices, uint @NumIndices, [MarshalAs(UnmanagedType.LPStr)] string @Name); [DllImport(libraryPath, EntryPoint = "LLVMBuildInBoundsGEP", CallingConvention = System.Runtime.InteropServices.CallingConvention.Cdecl, BestFitMapping = false, ThrowOnUnmappableChar = true)] internal static extern LLVMValueRef BuildInBoundsGEP(LLVMBuilderRef @B, LLVMValueRef @Pointer, out LLVMValueRef @Indices, uint @NumIndices, [MarshalAs(UnmanagedType.LPStr)] string @Name); [DllImport(libraryPath, EntryPoint = "LLVMBuildStructGEP", CallingConvention = System.Runtime.InteropServices.CallingConvention.Cdecl, BestFitMapping = false, ThrowOnUnmappableChar = true)] internal static extern LLVMValueRef BuildStructGEP(LLVMBuilderRef @B, LLVMValueRef @Pointer, uint @Idx, [MarshalAs(UnmanagedType.LPStr)] string @Name); [DllImport(libraryPath, EntryPoint = "LLVMBuildGlobalString", CallingConvention = System.Runtime.InteropServices.CallingConvention.Cdecl, BestFitMapping = false, ThrowOnUnmappableChar = true)] internal static extern LLVMValueRef BuildGlobalString(LLVMBuilderRef @B, [MarshalAs(UnmanagedType.LPStr)] string @Str, [MarshalAs(UnmanagedType.LPStr)] string @Name); [DllImport(libraryPath, EntryPoint = "LLVMBuildGlobalStringPtr", CallingConvention = System.Runtime.InteropServices.CallingConvention.Cdecl, BestFitMapping = false, ThrowOnUnmappableChar = true)] internal static extern LLVMValueRef BuildGlobalStringPtr(LLVMBuilderRef @B, [MarshalAs(UnmanagedType.LPStr)] string @Str, [MarshalAs(UnmanagedType.LPStr)] string @Name); [DllImport(libraryPath, EntryPoint = "LLVMGetVolatile", CallingConvention = System.Runtime.InteropServices.CallingConvention.Cdecl, BestFitMapping = false, ThrowOnUnmappableChar = true)] internal static extern LLVMBool GetVolatile(LLVMValueRef @MemoryAccessInst); [DllImport(libraryPath, EntryPoint = "LLVMSetVolatile", CallingConvention = System.Runtime.InteropServices.CallingConvention.Cdecl, BestFitMapping = false, ThrowOnUnmappableChar = true)] internal static extern void SetVolatile(LLVMValueRef @MemoryAccessInst, LLVMBool @IsVolatile); [DllImport( libraryPath, EntryPoint = "LLVMGetOrdering", CallingConvention = System.Runtime.InteropServices.CallingConvention.Cdecl, BestFitMapping = false, ThrowOnUnmappableChar = true )] internal static extern LLVMAtomicOrdering GetOrdering( LLVMValueRef @MemoryAccessInst ); [DllImport( libraryPath, EntryPoint = "LLVMSetOrdering", CallingConvention = System.Runtime.InteropServices.CallingConvention.Cdecl, BestFitMapping = false, ThrowOnUnmappableChar = true )] internal static extern void SetOrdering( LLVMValueRef @MemoryAccessInst, LLVMAtomicOrdering @Ordering ); [DllImport(libraryPath, EntryPoint = "LLVMBuildTrunc", CallingConvention = System.Runtime.InteropServices.CallingConvention.Cdecl, BestFitMapping = false, ThrowOnUnmappableChar = true)] internal static extern LLVMValueRef BuildTrunc(LLVMBuilderRef @param0, LLVMValueRef @Val, LLVMTypeRef @DestTy, [MarshalAs(UnmanagedType.LPStr)] string @Name); [DllImport(libraryPath, EntryPoint = "LLVMBuildZExt", CallingConvention = System.Runtime.InteropServices.CallingConvention.Cdecl, BestFitMapping = false, ThrowOnUnmappableChar = true)] internal static extern LLVMValueRef BuildZExt(LLVMBuilderRef @param0, LLVMValueRef @Val, LLVMTypeRef @DestTy, [MarshalAs(UnmanagedType.LPStr)] string @Name); [DllImport(libraryPath, EntryPoint = "LLVMBuildSExt", CallingConvention = System.Runtime.InteropServices.CallingConvention.Cdecl, BestFitMapping = false, ThrowOnUnmappableChar = true)] internal static extern LLVMValueRef BuildSExt(LLVMBuilderRef @param0, LLVMValueRef @Val, LLVMTypeRef @DestTy, [MarshalAs(UnmanagedType.LPStr)] string @Name); [DllImport(libraryPath, EntryPoint = "LLVMBuildFPToUI", CallingConvention = System.Runtime.InteropServices.CallingConvention.Cdecl, BestFitMapping = false, ThrowOnUnmappableChar = true)] internal static extern LLVMValueRef BuildFPToUI(LLVMBuilderRef @param0, LLVMValueRef @Val, LLVMTypeRef @DestTy, [MarshalAs(UnmanagedType.LPStr)] string @Name); [DllImport(libraryPath, EntryPoint = "LLVMBuildFPToSI", CallingConvention = System.Runtime.InteropServices.CallingConvention.Cdecl, BestFitMapping = false, ThrowOnUnmappableChar = true)] internal static extern LLVMValueRef BuildFPToSI(LLVMBuilderRef @param0, LLVMValueRef @Val, LLVMTypeRef @DestTy, [MarshalAs(UnmanagedType.LPStr)] string @Name); [DllImport(libraryPath, EntryPoint = "LLVMBuildUIToFP", CallingConvention = System.Runtime.InteropServices.CallingConvention.Cdecl, BestFitMapping = false, ThrowOnUnmappableChar = true)] internal static extern LLVMValueRef BuildUIToFP(LLVMBuilderRef @param0, LLVMValueRef @Val, LLVMTypeRef @DestTy, [MarshalAs(UnmanagedType.LPStr)] string @Name); [DllImport(libraryPath, EntryPoint = "LLVMBuildSIToFP", CallingConvention = System.Runtime.InteropServices.CallingConvention.Cdecl, BestFitMapping = false, ThrowOnUnmappableChar = true)] internal static extern LLVMValueRef BuildSIToFP(LLVMBuilderRef @param0, LLVMValueRef @Val, LLVMTypeRef @DestTy, [MarshalAs(UnmanagedType.LPStr)] string @Name); [DllImport(libraryPath, EntryPoint = "LLVMBuildFPTrunc", CallingConvention = System.Runtime.InteropServices.CallingConvention.Cdecl, BestFitMapping = false, ThrowOnUnmappableChar = true)] internal static extern LLVMValueRef BuildFPTrunc(LLVMBuilderRef @param0, LLVMValueRef @Val, LLVMTypeRef @DestTy, [MarshalAs(UnmanagedType.LPStr)] string @Name); [DllImport(libraryPath, EntryPoint = "LLVMBuildFPExt", CallingConvention = System.Runtime.InteropServices.CallingConvention.Cdecl, BestFitMapping = false, ThrowOnUnmappableChar = true)] internal static extern LLVMValueRef BuildFPExt(LLVMBuilderRef @param0, LLVMValueRef @Val, LLVMTypeRef @DestTy, [MarshalAs(UnmanagedType.LPStr)] string @Name); [DllImport(libraryPath, EntryPoint = "LLVMBuildPtrToInt", CallingConvention = System.Runtime.InteropServices.CallingConvention.Cdecl, BestFitMapping = false, ThrowOnUnmappableChar = true)] internal static extern LLVMValueRef BuildPtrToInt(LLVMBuilderRef @param0, LLVMValueRef @Val, LLVMTypeRef @DestTy, [MarshalAs(UnmanagedType.LPStr)] string @Name); [DllImport(libraryPath, EntryPoint = "LLVMBuildIntToPtr", CallingConvention = System.Runtime.InteropServices.CallingConvention.Cdecl, BestFitMapping = false, ThrowOnUnmappableChar = true)] internal static extern LLVMValueRef BuildIntToPtr(LLVMBuilderRef @param0, LLVMValueRef @Val, LLVMTypeRef @DestTy, [MarshalAs(UnmanagedType.LPStr)] string @Name); [DllImport(libraryPath, EntryPoint = "LLVMBuildBitCast", CallingConvention = System.Runtime.InteropServices.CallingConvention.Cdecl, BestFitMapping = false, ThrowOnUnmappableChar = true)] internal static extern LLVMValueRef BuildBitCast(LLVMBuilderRef @param0, LLVMValueRef @Val, LLVMTypeRef @DestTy, [MarshalAs(UnmanagedType.LPStr)] string @Name); [DllImport(libraryPath, EntryPoint = "LLVMBuildAddrSpaceCast", CallingConvention = System.Runtime.InteropServices.CallingConvention.Cdecl, BestFitMapping = false, ThrowOnUnmappableChar = true)] internal static extern LLVMValueRef BuildAddrSpaceCast(LLVMBuilderRef @param0, LLVMValueRef @Val, LLVMTypeRef @DestTy, [MarshalAs(UnmanagedType.LPStr)] string @Name); [DllImport(libraryPath, EntryPoint = "LLVMBuildZExtOrBitCast", CallingConvention = System.Runtime.InteropServices.CallingConvention.Cdecl, BestFitMapping = false, ThrowOnUnmappableChar = true)] internal static extern LLVMValueRef BuildZExtOrBitCast(LLVMBuilderRef @param0, LLVMValueRef @Val, LLVMTypeRef @DestTy, [MarshalAs(UnmanagedType.LPStr)] string @Name); [DllImport(libraryPath, EntryPoint = "LLVMBuildSExtOrBitCast", CallingConvention = System.Runtime.InteropServices.CallingConvention.Cdecl, BestFitMapping = false, ThrowOnUnmappableChar = true)] internal static extern LLVMValueRef BuildSExtOrBitCast(LLVMBuilderRef @param0, LLVMValueRef @Val, LLVMTypeRef @DestTy, [MarshalAs(UnmanagedType.LPStr)] string @Name); [DllImport(libraryPath, EntryPoint = "LLVMBuildTruncOrBitCast", CallingConvention = System.Runtime.InteropServices.CallingConvention.Cdecl, BestFitMapping = false, ThrowOnUnmappableChar = true)] internal static extern LLVMValueRef BuildTruncOrBitCast(LLVMBuilderRef @param0, LLVMValueRef @Val, LLVMTypeRef @DestTy, [MarshalAs(UnmanagedType.LPStr)] string @Name); [DllImport(libraryPath, EntryPoint = "LLVMBuildCast", CallingConvention = System.Runtime.InteropServices.CallingConvention.Cdecl, BestFitMapping = false, ThrowOnUnmappableChar = true)] internal static extern LLVMValueRef BuildCast(LLVMBuilderRef @B, LLVMOpcode @Op, LLVMValueRef @Val, LLVMTypeRef @DestTy, [MarshalAs(UnmanagedType.LPStr)] string @Name); [DllImport(libraryPath, EntryPoint = "LLVMBuildPointerCast", CallingConvention = System.Runtime.InteropServices.CallingConvention.Cdecl, BestFitMapping = false, ThrowOnUnmappableChar = true)] internal static extern LLVMValueRef BuildPointerCast(LLVMBuilderRef @param0, LLVMValueRef @Val, LLVMTypeRef @DestTy, [MarshalAs(UnmanagedType.LPStr)] string @Name); [DllImport(libraryPath, EntryPoint = "LLVMBuildIntCast", CallingConvention = System.Runtime.InteropServices.CallingConvention.Cdecl, BestFitMapping = false, ThrowOnUnmappableChar = true)] internal static extern LLVMValueRef BuildIntCast(LLVMBuilderRef @param0, LLVMValueRef @Val, LLVMTypeRef @DestTy, [MarshalAs(UnmanagedType.LPStr)] string @Name); [DllImport(libraryPath, EntryPoint = "LLVMBuildFPCast", CallingConvention = System.Runtime.InteropServices.CallingConvention.Cdecl, BestFitMapping = false, ThrowOnUnmappableChar = true)] internal static extern LLVMValueRef BuildFPCast(LLVMBuilderRef @param0, LLVMValueRef @Val, LLVMTypeRef @DestTy, [MarshalAs(UnmanagedType.LPStr)] string @Name); [DllImport(libraryPath, EntryPoint = "LLVMBuildICmp", CallingConvention = System.Runtime.InteropServices.CallingConvention.Cdecl, BestFitMapping = false, ThrowOnUnmappableChar = true)] internal static extern LLVMValueRef BuildICmp(LLVMBuilderRef @param0, LLVMIntPredicate @Op, LLVMValueRef @LHS, LLVMValueRef @RHS, [MarshalAs(UnmanagedType.LPStr)] string @Name); [DllImport(libraryPath, EntryPoint = "LLVMBuildFCmp", CallingConvention = System.Runtime.InteropServices.CallingConvention.Cdecl, BestFitMapping = false, ThrowOnUnmappableChar = true)] internal static extern LLVMValueRef BuildFCmp(LLVMBuilderRef @param0, LLVMRealPredicate @Op, LLVMValueRef @LHS, LLVMValueRef @RHS, [MarshalAs(UnmanagedType.LPStr)] string @Name); [DllImport(libraryPath, EntryPoint = "LLVMBuildPhi", CallingConvention = System.Runtime.InteropServices.CallingConvention.Cdecl, BestFitMapping = false, ThrowOnUnmappableChar = true)] internal static extern LLVMValueRef BuildPhi(LLVMBuilderRef @param0, LLVMTypeRef @Ty, [MarshalAs(UnmanagedType.LPStr)] string @Name); [DllImport(libraryPath, EntryPoint = "LLVMBuildCall", CallingConvention = System.Runtime.InteropServices.CallingConvention.Cdecl, BestFitMapping = false, ThrowOnUnmappableChar = true)] internal static extern LLVMValueRef BuildCall(LLVMBuilderRef @param0, LLVMValueRef @Fn, out LLVMValueRef @Args, uint @NumArgs, [MarshalAs(UnmanagedType.LPStr)] string @Name); [DllImport(libraryPath, EntryPoint = "LLVMBuildSelect", CallingConvention = System.Runtime.InteropServices.CallingConvention.Cdecl, BestFitMapping = false, ThrowOnUnmappableChar = true)] internal static extern LLVMValueRef BuildSelect(LLVMBuilderRef @param0, LLVMValueRef @If, LLVMValueRef @Then, LLVMValueRef @Else, [MarshalAs(UnmanagedType.LPStr)] string @Name); [DllImport(libraryPath, EntryPoint = "LLVMBuildVAArg", CallingConvention = System.Runtime.InteropServices.CallingConvention.Cdecl, BestFitMapping = false, ThrowOnUnmappableChar = true)] internal static extern LLVMValueRef BuildVAArg(LLVMBuilderRef @param0, LLVMValueRef @List, LLVMTypeRef @Ty, [MarshalAs(UnmanagedType.LPStr)] string @Name); [DllImport(libraryPath, EntryPoint = "LLVMBuildExtractElement", CallingConvention = System.Runtime.InteropServices.CallingConvention.Cdecl, BestFitMapping = false, ThrowOnUnmappableChar = true)] internal static extern LLVMValueRef BuildExtractElement(LLVMBuilderRef @param0, LLVMValueRef @VecVal, LLVMValueRef @Index, [MarshalAs(UnmanagedType.LPStr)] string @Name); [DllImport(libraryPath, EntryPoint = "LLVMBuildInsertElement", CallingConvention = System.Runtime.InteropServices.CallingConvention.Cdecl, BestFitMapping = false, ThrowOnUnmappableChar = true)] internal static extern LLVMValueRef BuildInsertElement(LLVMBuilderRef @param0, LLVMValueRef @VecVal, LLVMValueRef @EltVal, LLVMValueRef @Index, [MarshalAs(UnmanagedType.LPStr)] string @Name); [DllImport(libraryPath, EntryPoint = "LLVMBuildShuffleVector", CallingConvention = System.Runtime.InteropServices.CallingConvention.Cdecl, BestFitMapping = false, ThrowOnUnmappableChar = true)] internal static extern LLVMValueRef BuildShuffleVector(LLVMBuilderRef @param0, LLVMValueRef @V1, LLVMValueRef @V2, LLVMValueRef @Mask, [MarshalAs(UnmanagedType.LPStr)] string @Name); [DllImport(libraryPath, EntryPoint = "LLVMBuildExtractValue", CallingConvention = System.Runtime.InteropServices.CallingConvention.Cdecl, BestFitMapping = false, ThrowOnUnmappableChar = true)] internal static extern LLVMValueRef BuildExtractValue(LLVMBuilderRef @param0, LLVMValueRef @AggVal, uint @Index, [MarshalAs(UnmanagedType.LPStr)] string @Name); [DllImport(libraryPath, EntryPoint = "LLVMBuildInsertValue", CallingConvention = System.Runtime.InteropServices.CallingConvention.Cdecl, BestFitMapping = false, ThrowOnUnmappableChar = true)] internal static extern LLVMValueRef BuildInsertValue(LLVMBuilderRef @param0, LLVMValueRef @AggVal, LLVMValueRef @EltVal, uint @Index, [MarshalAs(UnmanagedType.LPStr)] string @Name); [DllImport(libraryPath, EntryPoint = "LLVMBuildIsNull", CallingConvention = System.Runtime.InteropServices.CallingConvention.Cdecl, BestFitMapping = false, ThrowOnUnmappableChar = true)] internal static extern LLVMValueRef BuildIsNull(LLVMBuilderRef @param0, LLVMValueRef @Val, [MarshalAs(UnmanagedType.LPStr)] string @Name); [DllImport(libraryPath, EntryPoint = "LLVMBuildIsNotNull", CallingConvention = System.Runtime.InteropServices.CallingConvention.Cdecl, BestFitMapping = false, ThrowOnUnmappableChar = true)] internal static extern LLVMValueRef BuildIsNotNull(LLVMBuilderRef @param0, LLVMValueRef @Val, [MarshalAs(UnmanagedType.LPStr)] string @Name); [DllImport(libraryPath, EntryPoint = "LLVMBuildPtrDiff", CallingConvention = System.Runtime.InteropServices.CallingConvention.Cdecl, BestFitMapping = false, ThrowOnUnmappableChar = true)] internal static extern LLVMValueRef BuildPtrDiff(LLVMBuilderRef @param0, LLVMValueRef @LHS, LLVMValueRef @RHS, [MarshalAs(UnmanagedType.LPStr)] string @Name); [DllImport(libraryPath, EntryPoint = "LLVMBuildFence", CallingConvention = System.Runtime.InteropServices.CallingConvention.Cdecl, BestFitMapping = false, ThrowOnUnmappableChar = true)] internal static extern LLVMValueRef BuildFence(LLVMBuilderRef @B, LLVMAtomicOrdering @ordering, LLVMBool @singleThread, [MarshalAs(UnmanagedType.LPStr)] string @Name); [DllImport(libraryPath, EntryPoint = "LLVMBuildAtomicRMW", CallingConvention = System.Runtime.InteropServices.CallingConvention.Cdecl, BestFitMapping = false, ThrowOnUnmappableChar = true)] internal static extern LLVMValueRef BuildAtomicRMW(LLVMBuilderRef @B, LLVMAtomicRMWBinOp @op, LLVMValueRef @PTR, LLVMValueRef @Val, LLVMAtomicOrdering @ordering, LLVMBool @singleThread); [DllImport(libraryPath, EntryPoint = "LLVMCreateModuleProviderForExistingModule", CallingConvention = System.Runtime.InteropServices.CallingConvention.Cdecl, BestFitMapping = false, ThrowOnUnmappableChar = true)] internal static extern LLVMModuleProviderRef CreateModuleProviderForExistingModule(LLVMModuleRef @M); [DllImport(libraryPath, EntryPoint = "LLVMDisposeModuleProvider", CallingConvention = System.Runtime.InteropServices.CallingConvention.Cdecl, BestFitMapping = false, ThrowOnUnmappableChar = true)] internal static extern void DisposeModuleProvider(LLVMModuleProviderRef @M); [DllImport(libraryPath, EntryPoint = "LLVMCreateMemoryBufferWithContentsOfFile", CallingConvention = System.Runtime.InteropServices.CallingConvention.Cdecl, BestFitMapping = false, ThrowOnUnmappableChar = true)] internal static extern LLVMBool CreateMemoryBufferWithContentsOfFile([MarshalAs(UnmanagedType.LPStr)] string @Path, out LLVMMemoryBufferRef @OutMemBuf, out IntPtr @OutMessage); [DllImport(libraryPath, EntryPoint = "LLVMCreateMemoryBufferWithSTDIN", CallingConvention = System.Runtime.InteropServices.CallingConvention.Cdecl, BestFitMapping = false, ThrowOnUnmappableChar = true)] internal static extern LLVMBool CreateMemoryBufferWithSTDIN(out LLVMMemoryBufferRef @OutMemBuf, out IntPtr @OutMessage); [DllImport(libraryPath, EntryPoint = "LLVMCreateMemoryBufferWithMemoryRange", CallingConvention = System.Runtime.InteropServices.CallingConvention.Cdecl, BestFitMapping = false, ThrowOnUnmappableChar = true)] internal static extern LLVMMemoryBufferRef CreateMemoryBufferWithMemoryRange([MarshalAs(UnmanagedType.LPStr)] string @InputData, int @InputDataLength, [MarshalAs(UnmanagedType.LPStr)] string @BufferName, LLVMBool @RequiresNullTerminator); [DllImport(libraryPath, EntryPoint = "LLVMCreateMemoryBufferWithMemoryRangeCopy", CallingConvention = System.Runtime.InteropServices.CallingConvention.Cdecl, BestFitMapping = false, ThrowOnUnmappableChar = true)] internal static extern LLVMMemoryBufferRef CreateMemoryBufferWithMemoryRangeCopy([MarshalAs(UnmanagedType.LPStr)] string @InputData, int @InputDataLength, [MarshalAs(UnmanagedType.LPStr)] string @BufferName); [DllImport(libraryPath, EntryPoint = "LLVMGetBufferStart", CallingConvention = System.Runtime.InteropServices.CallingConvention.Cdecl, BestFitMapping = false, ThrowOnUnmappableChar = true)] internal static extern IntPtr GetBufferStart(LLVMMemoryBufferRef @MemBuf); [DllImport(libraryPath, EntryPoint = "LLVMGetBufferSize", CallingConvention = System.Runtime.InteropServices.CallingConvention.Cdecl, BestFitMapping = false, ThrowOnUnmappableChar = true)] internal static extern int GetBufferSize(LLVMMemoryBufferRef @MemBuf); [DllImport(libraryPath, EntryPoint = "LLVMDisposeMemoryBuffer", CallingConvention = System.Runtime.InteropServices.CallingConvention.Cdecl, BestFitMapping = false, ThrowOnUnmappableChar = true)] internal static extern void DisposeMemoryBuffer(LLVMMemoryBufferRef @MemBuf); [DllImport(libraryPath, EntryPoint = "LLVMGetGlobalPassRegistry", CallingConvention = System.Runtime.InteropServices.CallingConvention.Cdecl, BestFitMapping = false, ThrowOnUnmappableChar = true)] internal static extern LLVMPassRegistryRef GetGlobalPassRegistry(); [DllImport(libraryPath, EntryPoint = "LLVMCreatePassManager", CallingConvention = System.Runtime.InteropServices.CallingConvention.Cdecl, BestFitMapping = false, ThrowOnUnmappableChar = true)] internal static extern LLVMPassManagerRef CreatePassManager(); [DllImport(libraryPath, EntryPoint = "LLVMCreateFunctionPassManagerForModule", CallingConvention = System.Runtime.InteropServices.CallingConvention.Cdecl, BestFitMapping = false, ThrowOnUnmappableChar = true)] internal static extern LLVMPassManagerRef CreateFunctionPassManagerForModule(LLVMModuleRef @M); [DllImport(libraryPath, EntryPoint = "LLVMCreateFunctionPassManager", CallingConvention = System.Runtime.InteropServices.CallingConvention.Cdecl, BestFitMapping = false, ThrowOnUnmappableChar = true)] internal static extern LLVMPassManagerRef CreateFunctionPassManager(LLVMModuleProviderRef @MP); [DllImport(libraryPath, EntryPoint = "LLVMRunPassManager", CallingConvention = System.Runtime.InteropServices.CallingConvention.Cdecl, BestFitMapping = false, ThrowOnUnmappableChar = true)] internal static extern LLVMBool RunPassManager(LLVMPassManagerRef @PM, LLVMModuleRef @M); [DllImport(libraryPath, EntryPoint = "LLVMInitializeFunctionPassManager", CallingConvention = System.Runtime.InteropServices.CallingConvention.Cdecl, BestFitMapping = false, ThrowOnUnmappableChar = true)] internal static extern LLVMBool InitializeFunctionPassManager(LLVMPassManagerRef @FPM); [DllImport(libraryPath, EntryPoint = "LLVMRunFunctionPassManager", CallingConvention = System.Runtime.InteropServices.CallingConvention.Cdecl, BestFitMapping = false, ThrowOnUnmappableChar = true)] internal static extern LLVMBool RunFunctionPassManager(LLVMPassManagerRef @FPM, LLVMValueRef @F); [DllImport(libraryPath, EntryPoint = "LLVMFinalizeFunctionPassManager", CallingConvention = System.Runtime.InteropServices.CallingConvention.Cdecl, BestFitMapping = false, ThrowOnUnmappableChar = true)] internal static extern LLVMBool FinalizeFunctionPassManager(LLVMPassManagerRef @FPM); [DllImport(libraryPath, EntryPoint = "LLVMDisposePassManager", CallingConvention = System.Runtime.InteropServices.CallingConvention.Cdecl, BestFitMapping = false, ThrowOnUnmappableChar = true)] internal static extern void DisposePassManager(LLVMPassManagerRef @PM); [DllImport(libraryPath, EntryPoint = "LLVMStartMultithreaded", CallingConvention = System.Runtime.InteropServices.CallingConvention.Cdecl, BestFitMapping = false, ThrowOnUnmappableChar = true)] internal static extern LLVMBool StartMultithreaded(); [DllImport(libraryPath, EntryPoint = "LLVMStopMultithreaded", CallingConvention = System.Runtime.InteropServices.CallingConvention.Cdecl, BestFitMapping = false, ThrowOnUnmappableChar = true)] internal static extern void StopMultithreaded(); [DllImport(libraryPath, EntryPoint = "LLVMIsMultithreaded", CallingConvention = System.Runtime.InteropServices.CallingConvention.Cdecl, BestFitMapping = false, ThrowOnUnmappableChar = true)] internal static extern LLVMBool IsMultithreaded(); [DllImport(libraryPath, EntryPoint = "LLVMVerifyModule", CallingConvention = System.Runtime.InteropServices.CallingConvention.Cdecl, BestFitMapping = false, ThrowOnUnmappableChar = true)] internal static extern LLVMBool VerifyModule(LLVMModuleRef @M, LLVMVerifierFailureAction @Action, out IntPtr @OutMessage); [DllImport(libraryPath, EntryPoint = "LLVMVerifyFunction", CallingConvention = System.Runtime.InteropServices.CallingConvention.Cdecl, BestFitMapping = false, ThrowOnUnmappableChar = true)] internal static extern LLVMBool VerifyFunction(LLVMValueRef @Fn, LLVMVerifierFailureAction @Action); [DllImport(libraryPath, EntryPoint = "LLVMViewFunctionCFG", CallingConvention = System.Runtime.InteropServices.CallingConvention.Cdecl, BestFitMapping = false, ThrowOnUnmappableChar = true)] internal static extern void ViewFunctionCFG(LLVMValueRef @Fn); [DllImport(libraryPath, EntryPoint = "LLVMViewFunctionCFGOnly", CallingConvention = System.Runtime.InteropServices.CallingConvention.Cdecl, BestFitMapping = false, ThrowOnUnmappableChar = true)] internal static extern void ViewFunctionCFGOnly(LLVMValueRef @Fn); [DllImport(libraryPath, EntryPoint = "LLVMParseBitcode", CallingConvention = System.Runtime.InteropServices.CallingConvention.Cdecl, BestFitMapping = false, ThrowOnUnmappableChar = true)] internal static extern LLVMBool ParseBitcode(LLVMMemoryBufferRef @MemBuf, out LLVMModuleRef @OutModule, out IntPtr @OutMessage); [DllImport(libraryPath, EntryPoint = "LLVMParseBitcodeInContext", CallingConvention = System.Runtime.InteropServices.CallingConvention.Cdecl, BestFitMapping = false, ThrowOnUnmappableChar = true)] internal static extern LLVMBool ParseBitcodeInContext(LLVMContextRef @ContextRef, LLVMMemoryBufferRef @MemBuf, out LLVMModuleRef @OutModule, out IntPtr @OutMessage); [DllImport(libraryPath, EntryPoint = "LLVMGetBitcodeModuleInContext", CallingConvention = System.Runtime.InteropServices.CallingConvention.Cdecl, BestFitMapping = false, ThrowOnUnmappableChar = true)] internal static extern LLVMBool GetBitcodeModuleInContext(LLVMContextRef @ContextRef, LLVMMemoryBufferRef @MemBuf, out LLVMModuleRef @OutM, out IntPtr @OutMessage); [DllImport(libraryPath, EntryPoint = "LLVMGetBitcodeModule", CallingConvention = System.Runtime.InteropServices.CallingConvention.Cdecl, BestFitMapping = false, ThrowOnUnmappableChar = true)] internal static extern LLVMBool GetBitcodeModule(LLVMMemoryBufferRef @MemBuf, out LLVMModuleRef @OutM, out IntPtr @OutMessage); [DllImport(libraryPath, EntryPoint = "LLVMWriteBitcodeToFile", CallingConvention = System.Runtime.InteropServices.CallingConvention.Cdecl, BestFitMapping = false, ThrowOnUnmappableChar = true)] internal static extern int WriteBitcodeToFile(LLVMModuleRef @M, [MarshalAs(UnmanagedType.LPStr)] string @Path); [DllImport(libraryPath, EntryPoint = "LLVMWriteBitcodeToFD", CallingConvention = System.Runtime.InteropServices.CallingConvention.Cdecl, BestFitMapping = false, ThrowOnUnmappableChar = true)] internal static extern int WriteBitcodeToFD(LLVMModuleRef @M, int @FD, int @ShouldClose, int @Unbuffered); [DllImport(libraryPath, EntryPoint = "LLVMWriteBitcodeToFileHandle", CallingConvention = System.Runtime.InteropServices.CallingConvention.Cdecl, BestFitMapping = false, ThrowOnUnmappableChar = true)] internal static extern int WriteBitcodeToFileHandle(LLVMModuleRef @M, int @Handle); [DllImport(libraryPath, EntryPoint = "LLVMWriteBitcodeToMemoryBuffer", CallingConvention = System.Runtime.InteropServices.CallingConvention.Cdecl, BestFitMapping = false, ThrowOnUnmappableChar = true)] internal static extern LLVMMemoryBufferRef WriteBitcodeToMemoryBuffer(LLVMModuleRef @M); [DllImport(libraryPath, EntryPoint = "LLVMCreateDisasm", CallingConvention = System.Runtime.InteropServices.CallingConvention.Cdecl, BestFitMapping = false, ThrowOnUnmappableChar = true)] internal static extern LLVMDisasmContextRef CreateDisasm([MarshalAs(UnmanagedType.LPStr)] string @TripleName, IntPtr @DisInfo, int @TagType, LLVMOpInfoCallback @GetOpInfo, LLVMSymbolLookupCallback @SymbolLookUp); [DllImport(libraryPath, EntryPoint = "LLVMCreateDisasmCPU", CallingConvention = System.Runtime.InteropServices.CallingConvention.Cdecl, BestFitMapping = false, ThrowOnUnmappableChar = true)] internal static extern LLVMDisasmContextRef CreateDisasmCPU([MarshalAs(UnmanagedType.LPStr)] string @Triple, [MarshalAs(UnmanagedType.LPStr)] string @CPU, IntPtr @DisInfo, int @TagType, LLVMOpInfoCallback @GetOpInfo, LLVMSymbolLookupCallback @SymbolLookUp); [DllImport(libraryPath, EntryPoint = "LLVMCreateDisasmCPUFeatures", CallingConvention = System.Runtime.InteropServices.CallingConvention.Cdecl, BestFitMapping = false, ThrowOnUnmappableChar = true)] internal static extern LLVMDisasmContextRef CreateDisasmCPUFeatures([MarshalAs(UnmanagedType.LPStr)] string @Triple, [MarshalAs(UnmanagedType.LPStr)] string @CPU, [MarshalAs(UnmanagedType.LPStr)] string @Features, IntPtr @DisInfo, int @TagType, LLVMOpInfoCallback @GetOpInfo, LLVMSymbolLookupCallback @SymbolLookUp); [DllImport(libraryPath, EntryPoint = "LLVMSetDisasmOptions", CallingConvention = System.Runtime.InteropServices.CallingConvention.Cdecl, BestFitMapping = false, ThrowOnUnmappableChar = true)] internal static extern int SetDisasmOptions(LLVMDisasmContextRef @DC, int @Options); [DllImport(libraryPath, EntryPoint = "LLVMDisasmDispose", CallingConvention = System.Runtime.InteropServices.CallingConvention.Cdecl, BestFitMapping = false, ThrowOnUnmappableChar = true)] internal static extern void DisasmDispose(LLVMDisasmContextRef @DC); [DllImport(libraryPath, EntryPoint = "LLVMDisasmInstruction", CallingConvention = System.Runtime.InteropServices.CallingConvention.Cdecl, BestFitMapping = false, ThrowOnUnmappableChar = true)] internal static extern int DisasmInstruction(LLVMDisasmContextRef @DC, out char @Bytes, int @BytesSize, int @PC, IntPtr @OutString, int @OutStringSize); [DllImport(libraryPath, EntryPoint = "LLVMInitializeAMDGPUTargetInfo", CallingConvention = System.Runtime.InteropServices.CallingConvention.Cdecl, BestFitMapping = false, ThrowOnUnmappableChar = true)] internal static extern void InitializeAMDGPUTargetInfo(); [DllImport(libraryPath, EntryPoint = "LLVMInitializeSystemZTargetInfo", CallingConvention = System.Runtime.InteropServices.CallingConvention.Cdecl, BestFitMapping = false, ThrowOnUnmappableChar = true)] internal static extern void InitializeSystemZTargetInfo(); [DllImport(libraryPath, EntryPoint = "LLVMInitializeHexagonTargetInfo", CallingConvention = System.Runtime.InteropServices.CallingConvention.Cdecl, BestFitMapping = false, ThrowOnUnmappableChar = true)] internal static extern void InitializeHexagonTargetInfo(); [DllImport(libraryPath, EntryPoint = "LLVMInitializeNVPTXTargetInfo", CallingConvention = System.Runtime.InteropServices.CallingConvention.Cdecl, BestFitMapping = false, ThrowOnUnmappableChar = true)] internal static extern void InitializeNVPTXTargetInfo(); [DllImport(libraryPath, EntryPoint = "LLVMInitializeCppBackendTargetInfo", CallingConvention = System.Runtime.InteropServices.CallingConvention.Cdecl, BestFitMapping = false, ThrowOnUnmappableChar = true)] internal static extern void InitializeCppBackendTargetInfo(); [DllImport(libraryPath, EntryPoint = "LLVMInitializeMSP430TargetInfo", CallingConvention = System.Runtime.InteropServices.CallingConvention.Cdecl, BestFitMapping = false, ThrowOnUnmappableChar = true)] internal static extern void InitializeMSP430TargetInfo(); [DllImport(libraryPath, EntryPoint = "LLVMInitializeXCoreTargetInfo", CallingConvention = System.Runtime.InteropServices.CallingConvention.Cdecl, BestFitMapping = false, ThrowOnUnmappableChar = true)] internal static extern void InitializeXCoreTargetInfo(); [DllImport(libraryPath, EntryPoint = "LLVMInitializeMipsTargetInfo", CallingConvention = System.Runtime.InteropServices.CallingConvention.Cdecl, BestFitMapping = false, ThrowOnUnmappableChar = true)] internal static extern void InitializeMipsTargetInfo(); [DllImport(libraryPath, EntryPoint = "LLVMInitializeAArch64TargetInfo", CallingConvention = System.Runtime.InteropServices.CallingConvention.Cdecl, BestFitMapping = false, ThrowOnUnmappableChar = true)] internal static extern void InitializeAArch64TargetInfo(); [DllImport(libraryPath, EntryPoint = "LLVMInitializeARMTargetInfo", CallingConvention = System.Runtime.InteropServices.CallingConvention.Cdecl, BestFitMapping = false, ThrowOnUnmappableChar = true)] internal static extern void InitializeARMTargetInfo(); [DllImport(libraryPath, EntryPoint = "LLVMInitializePowerPCTargetInfo", CallingConvention = System.Runtime.InteropServices.CallingConvention.Cdecl, BestFitMapping = false, ThrowOnUnmappableChar = true)] internal static extern void InitializePowerPCTargetInfo(); [DllImport(libraryPath, EntryPoint = "LLVMInitializeSparcTargetInfo", CallingConvention = System.Runtime.InteropServices.CallingConvention.Cdecl, BestFitMapping = false, ThrowOnUnmappableChar = true)] internal static extern void InitializeSparcTargetInfo(); [DllImport(libraryPath, EntryPoint = "LLVMInitializeX86TargetInfo", CallingConvention = System.Runtime.InteropServices.CallingConvention.Cdecl, BestFitMapping = false, ThrowOnUnmappableChar = true)] internal static extern void InitializeX86TargetInfo(); [DllImport(libraryPath, EntryPoint = "LLVMInitializeAMDGPUTarget", CallingConvention = System.Runtime.InteropServices.CallingConvention.Cdecl, BestFitMapping = false, ThrowOnUnmappableChar = true)] internal static extern void InitializeAMDGPUTarget(); [DllImport(libraryPath, EntryPoint = "LLVMInitializeSystemZTarget", CallingConvention = System.Runtime.InteropServices.CallingConvention.Cdecl, BestFitMapping = false, ThrowOnUnmappableChar = true)] internal static extern void InitializeSystemZTarget(); [DllImport(libraryPath, EntryPoint = "LLVMInitializeHexagonTarget", CallingConvention = System.Runtime.InteropServices.CallingConvention.Cdecl, BestFitMapping = false, ThrowOnUnmappableChar = true)] internal static extern void InitializeHexagonTarget(); [DllImport(libraryPath, EntryPoint = "LLVMInitializeNVPTXTarget", CallingConvention = System.Runtime.InteropServices.CallingConvention.Cdecl, BestFitMapping = false, ThrowOnUnmappableChar = true)] internal static extern void InitializeNVPTXTarget(); [DllImport(libraryPath, EntryPoint = "LLVMInitializeCppBackendTarget", CallingConvention = System.Runtime.InteropServices.CallingConvention.Cdecl, BestFitMapping = false, ThrowOnUnmappableChar = true)] internal static extern void InitializeCppBackendTarget(); [DllImport(libraryPath, EntryPoint = "LLVMInitializeMSP430Target", CallingConvention = System.Runtime.InteropServices.CallingConvention.Cdecl, BestFitMapping = false, ThrowOnUnmappableChar = true)] internal static extern void InitializeMSP430Target(); [DllImport(libraryPath, EntryPoint = "LLVMInitializeXCoreTarget", CallingConvention = System.Runtime.InteropServices.CallingConvention.Cdecl, BestFitMapping = false, ThrowOnUnmappableChar = true)] internal static extern void InitializeXCoreTarget(); [DllImport(libraryPath, EntryPoint = "LLVMInitializeMipsTarget", CallingConvention = System.Runtime.InteropServices.CallingConvention.Cdecl, BestFitMapping = false, ThrowOnUnmappableChar = true)] internal static extern void InitializeMipsTarget(); [DllImport(libraryPath, EntryPoint = "LLVMInitializeAArch64Target", CallingConvention = System.Runtime.InteropServices.CallingConvention.Cdecl, BestFitMapping = false, ThrowOnUnmappableChar = true)] internal static extern void InitializeAArch64Target(); [DllImport(libraryPath, EntryPoint = "LLVMInitializeARMTarget", CallingConvention = System.Runtime.InteropServices.CallingConvention.Cdecl, BestFitMapping = false, ThrowOnUnmappableChar = true)] internal static extern void InitializeARMTarget(); [DllImport(libraryPath, EntryPoint = "LLVMInitializePowerPCTarget", CallingConvention = System.Runtime.InteropServices.CallingConvention.Cdecl, BestFitMapping = false, ThrowOnUnmappableChar = true)] internal static extern void InitializePowerPCTarget(); [DllImport(libraryPath, EntryPoint = "LLVMInitializeSparcTarget", CallingConvention = System.Runtime.InteropServices.CallingConvention.Cdecl, BestFitMapping = false, ThrowOnUnmappableChar = true)] internal static extern void InitializeSparcTarget(); [DllImport(libraryPath, EntryPoint = "LLVMInitializeX86Target", CallingConvention = System.Runtime.InteropServices.CallingConvention.Cdecl, BestFitMapping = false, ThrowOnUnmappableChar = true)] internal static extern void InitializeX86Target(); [DllImport(libraryPath, EntryPoint = "LLVMInitializeAMDGPUTargetMC", CallingConvention = System.Runtime.InteropServices.CallingConvention.Cdecl, BestFitMapping = false, ThrowOnUnmappableChar = true)] internal static extern void InitializeAMDGPUTargetMC(); [DllImport(libraryPath, EntryPoint = "LLVMInitializeSystemZTargetMC", CallingConvention = System.Runtime.InteropServices.CallingConvention.Cdecl, BestFitMapping = false, ThrowOnUnmappableChar = true)] internal static extern void InitializeSystemZTargetMC(); [DllImport(libraryPath, EntryPoint = "LLVMInitializeHexagonTargetMC", CallingConvention = System.Runtime.InteropServices.CallingConvention.Cdecl, BestFitMapping = false, ThrowOnUnmappableChar = true)] internal static extern void InitializeHexagonTargetMC(); [DllImport(libraryPath, EntryPoint = "LLVMInitializeNVPTXTargetMC", CallingConvention = System.Runtime.InteropServices.CallingConvention.Cdecl, BestFitMapping = false, ThrowOnUnmappableChar = true)] internal static extern void InitializeNVPTXTargetMC(); [DllImport(libraryPath, EntryPoint = "LLVMInitializeCppBackendTargetMC", CallingConvention = System.Runtime.InteropServices.CallingConvention.Cdecl, BestFitMapping = false, ThrowOnUnmappableChar = true)] internal static extern void InitializeCppBackendTargetMC(); [DllImport(libraryPath, EntryPoint = "LLVMInitializeMSP430TargetMC", CallingConvention = System.Runtime.InteropServices.CallingConvention.Cdecl, BestFitMapping = false, ThrowOnUnmappableChar = true)] internal static extern void InitializeMSP430TargetMC(); [DllImport(libraryPath, EntryPoint = "LLVMInitializeXCoreTargetMC", CallingConvention = System.Runtime.InteropServices.CallingConvention.Cdecl, BestFitMapping = false, ThrowOnUnmappableChar = true)] internal static extern void InitializeXCoreTargetMC(); [DllImport(libraryPath, EntryPoint = "LLVMInitializeMipsTargetMC", CallingConvention = System.Runtime.InteropServices.CallingConvention.Cdecl, BestFitMapping = false, ThrowOnUnmappableChar = true)] internal static extern void InitializeMipsTargetMC(); [DllImport(libraryPath, EntryPoint = "LLVMInitializeAArch64TargetMC", CallingConvention = System.Runtime.InteropServices.CallingConvention.Cdecl, BestFitMapping = false, ThrowOnUnmappableChar = true)] internal static extern void InitializeAArch64TargetMC(); [DllImport(libraryPath, EntryPoint = "LLVMInitializeARMTargetMC", CallingConvention = System.Runtime.InteropServices.CallingConvention.Cdecl, BestFitMapping = false, ThrowOnUnmappableChar = true)] internal static extern void InitializeARMTargetMC(); [DllImport(libraryPath, EntryPoint = "LLVMInitializePowerPCTargetMC", CallingConvention = System.Runtime.InteropServices.CallingConvention.Cdecl, BestFitMapping = false, ThrowOnUnmappableChar = true)] internal static extern void InitializePowerPCTargetMC(); [DllImport(libraryPath, EntryPoint = "LLVMInitializeSparcTargetMC", CallingConvention = System.Runtime.InteropServices.CallingConvention.Cdecl, BestFitMapping = false, ThrowOnUnmappableChar = true)] internal static extern void InitializeSparcTargetMC(); [DllImport(libraryPath, EntryPoint = "LLVMInitializeX86TargetMC", CallingConvention = System.Runtime.InteropServices.CallingConvention.Cdecl, BestFitMapping = false, ThrowOnUnmappableChar = true)] internal static extern void InitializeX86TargetMC(); [DllImport(libraryPath, EntryPoint = "LLVMInitializeAMDGPUAsmPrinter", CallingConvention = System.Runtime.InteropServices.CallingConvention.Cdecl, BestFitMapping = false, ThrowOnUnmappableChar = true)] internal static extern void InitializeAMDGPUAsmPrinter(); [DllImport(libraryPath, EntryPoint = "LLVMInitializeSystemZAsmPrinter", CallingConvention = System.Runtime.InteropServices.CallingConvention.Cdecl, BestFitMapping = false, ThrowOnUnmappableChar = true)] internal static extern void InitializeSystemZAsmPrinter(); [DllImport(libraryPath, EntryPoint = "LLVMInitializeHexagonAsmPrinter", CallingConvention = System.Runtime.InteropServices.CallingConvention.Cdecl, BestFitMapping = false, ThrowOnUnmappableChar = true)] internal static extern void InitializeHexagonAsmPrinter(); [DllImport(libraryPath, EntryPoint = "LLVMInitializeNVPTXAsmPrinter", CallingConvention = System.Runtime.InteropServices.CallingConvention.Cdecl, BestFitMapping = false, ThrowOnUnmappableChar = true)] internal static extern void InitializeNVPTXAsmPrinter(); [DllImport(libraryPath, EntryPoint = "LLVMInitializeMSP430AsmPrinter", CallingConvention = System.Runtime.InteropServices.CallingConvention.Cdecl, BestFitMapping = false, ThrowOnUnmappableChar = true)] internal static extern void InitializeMSP430AsmPrinter(); [DllImport(libraryPath, EntryPoint = "LLVMInitializeXCoreAsmPrinter", CallingConvention = System.Runtime.InteropServices.CallingConvention.Cdecl, BestFitMapping = false, ThrowOnUnmappableChar = true)] internal static extern void InitializeXCoreAsmPrinter(); [DllImport(libraryPath, EntryPoint = "LLVMInitializeMipsAsmPrinter", CallingConvention = System.Runtime.InteropServices.CallingConvention.Cdecl, BestFitMapping = false, ThrowOnUnmappableChar = true)] internal static extern void InitializeMipsAsmPrinter(); [DllImport(libraryPath, EntryPoint = "LLVMInitializeAArch64AsmPrinter", CallingConvention = System.Runtime.InteropServices.CallingConvention.Cdecl, BestFitMapping = false, ThrowOnUnmappableChar = true)] internal static extern void InitializeAArch64AsmPrinter(); [DllImport(libraryPath, EntryPoint = "LLVMInitializeARMAsmPrinter", CallingConvention = System.Runtime.InteropServices.CallingConvention.Cdecl, BestFitMapping = false, ThrowOnUnmappableChar = true)] internal static extern void InitializeARMAsmPrinter(); [DllImport(libraryPath, EntryPoint = "LLVMInitializePowerPCAsmPrinter", CallingConvention = System.Runtime.InteropServices.CallingConvention.Cdecl, BestFitMapping = false, ThrowOnUnmappableChar = true)] internal static extern void InitializePowerPCAsmPrinter(); [DllImport(libraryPath, EntryPoint = "LLVMInitializeSparcAsmPrinter", CallingConvention = System.Runtime.InteropServices.CallingConvention.Cdecl, BestFitMapping = false, ThrowOnUnmappableChar = true)] internal static extern void InitializeSparcAsmPrinter(); [DllImport(libraryPath, EntryPoint = "LLVMInitializeX86AsmPrinter", CallingConvention = System.Runtime.InteropServices.CallingConvention.Cdecl, BestFitMapping = false, ThrowOnUnmappableChar = true)] internal static extern void InitializeX86AsmPrinter(); [DllImport(libraryPath, EntryPoint = "LLVMInitializeAMDGPUAsmParser", CallingConvention = System.Runtime.InteropServices.CallingConvention.Cdecl, BestFitMapping = false, ThrowOnUnmappableChar = true)] internal static extern void InitializeAMDGPUAsmParser(); [DllImport(libraryPath, EntryPoint = "LLVMInitializeSystemZAsmParser", CallingConvention = System.Runtime.InteropServices.CallingConvention.Cdecl, BestFitMapping = false, ThrowOnUnmappableChar = true)] internal static extern void InitializeSystemZAsmParser(); [DllImport(libraryPath, EntryPoint = "LLVMInitializeMipsAsmParser", CallingConvention = System.Runtime.InteropServices.CallingConvention.Cdecl, BestFitMapping = false, ThrowOnUnmappableChar = true)] internal static extern void InitializeMipsAsmParser(); [DllImport(libraryPath, EntryPoint = "LLVMInitializeAArch64AsmParser", CallingConvention = System.Runtime.InteropServices.CallingConvention.Cdecl, BestFitMapping = false, ThrowOnUnmappableChar = true)] internal static extern void InitializeAArch64AsmParser(); [DllImport(libraryPath, EntryPoint = "LLVMInitializeARMAsmParser", CallingConvention = System.Runtime.InteropServices.CallingConvention.Cdecl, BestFitMapping = false, ThrowOnUnmappableChar = true)] internal static extern void InitializeARMAsmParser(); [DllImport(libraryPath, EntryPoint = "LLVMInitializePowerPCAsmParser", CallingConvention = System.Runtime.InteropServices.CallingConvention.Cdecl, BestFitMapping = false, ThrowOnUnmappableChar = true)] internal static extern void InitializePowerPCAsmParser(); [DllImport(libraryPath, EntryPoint = "LLVMInitializeSparcAsmParser", CallingConvention = System.Runtime.InteropServices.CallingConvention.Cdecl, BestFitMapping = false, ThrowOnUnmappableChar = true)] internal static extern void InitializeSparcAsmParser(); [DllImport(libraryPath, EntryPoint = "LLVMInitializeX86AsmParser", CallingConvention = System.Runtime.InteropServices.CallingConvention.Cdecl, BestFitMapping = false, ThrowOnUnmappableChar = true)] internal static extern void InitializeX86AsmParser(); [DllImport(libraryPath, EntryPoint = "LLVMInitializeSystemZDisassembler", CallingConvention = System.Runtime.InteropServices.CallingConvention.Cdecl, BestFitMapping = false, ThrowOnUnmappableChar = true)] internal static extern void InitializeSystemZDisassembler(); [DllImport(libraryPath, EntryPoint = "LLVMInitializeHexagonDisassembler", CallingConvention = System.Runtime.InteropServices.CallingConvention.Cdecl, BestFitMapping = false, ThrowOnUnmappableChar = true)] internal static extern void InitializeHexagonDisassembler(); [DllImport(libraryPath, EntryPoint = "LLVMInitializeXCoreDisassembler", CallingConvention = System.Runtime.InteropServices.CallingConvention.Cdecl, BestFitMapping = false, ThrowOnUnmappableChar = true)] internal static extern void InitializeXCoreDisassembler(); [DllImport(libraryPath, EntryPoint = "LLVMInitializeMipsDisassembler", CallingConvention = System.Runtime.InteropServices.CallingConvention.Cdecl, BestFitMapping = false, ThrowOnUnmappableChar = true)] internal static extern void InitializeMipsDisassembler(); [DllImport(libraryPath, EntryPoint = "LLVMInitializeAArch64Disassembler", CallingConvention = System.Runtime.InteropServices.CallingConvention.Cdecl, BestFitMapping = false, ThrowOnUnmappableChar = true)] internal static extern void InitializeAArch64Disassembler(); [DllImport(libraryPath, EntryPoint = "LLVMInitializeARMDisassembler", CallingConvention = System.Runtime.InteropServices.CallingConvention.Cdecl, BestFitMapping = false, ThrowOnUnmappableChar = true)] internal static extern void InitializeARMDisassembler(); [DllImport(libraryPath, EntryPoint = "LLVMInitializePowerPCDisassembler", CallingConvention = System.Runtime.InteropServices.CallingConvention.Cdecl, BestFitMapping = false, ThrowOnUnmappableChar = true)] internal static extern void InitializePowerPCDisassembler(); [DllImport(libraryPath, EntryPoint = "LLVMInitializeSparcDisassembler", CallingConvention = System.Runtime.InteropServices.CallingConvention.Cdecl, BestFitMapping = false, ThrowOnUnmappableChar = true)] internal static extern void InitializeSparcDisassembler(); [DllImport(libraryPath, EntryPoint = "LLVMInitializeX86Disassembler", CallingConvention = System.Runtime.InteropServices.CallingConvention.Cdecl, BestFitMapping = false, ThrowOnUnmappableChar = true)] internal static extern void InitializeX86Disassembler(); [DllImport(libraryPath, EntryPoint = "LLVMInitializeAllTargetInfos", CallingConvention = System.Runtime.InteropServices.CallingConvention.Cdecl, BestFitMapping = false, ThrowOnUnmappableChar = true)] internal static extern void InitializeAllTargetInfos(); [DllImport(libraryPath, EntryPoint = "LLVMInitializeAllTargets", CallingConvention = System.Runtime.InteropServices.CallingConvention.Cdecl, BestFitMapping = false, ThrowOnUnmappableChar = true)] internal static extern void InitializeAllTargets(); [DllImport(libraryPath, EntryPoint = "LLVMInitializeAllTargetMCs", CallingConvention = System.Runtime.InteropServices.CallingConvention.Cdecl, BestFitMapping = false, ThrowOnUnmappableChar = true)] internal static extern void InitializeAllTargetMCs(); [DllImport(libraryPath, EntryPoint = "LLVMInitializeAllAsmPrinters", CallingConvention = System.Runtime.InteropServices.CallingConvention.Cdecl, BestFitMapping = false, ThrowOnUnmappableChar = true)] internal static extern void InitializeAllAsmPrinters(); [DllImport(libraryPath, EntryPoint = "LLVMInitializeAllAsmParsers", CallingConvention = System.Runtime.InteropServices.CallingConvention.Cdecl, BestFitMapping = false, ThrowOnUnmappableChar = true)] internal static extern void InitializeAllAsmParsers(); [DllImport(libraryPath, EntryPoint = "LLVMInitializeAllDisassemblers", CallingConvention = System.Runtime.InteropServices.CallingConvention.Cdecl, BestFitMapping = false, ThrowOnUnmappableChar = true)] internal static extern void InitializeAllDisassemblers(); [DllImport(libraryPath, EntryPoint = "LLVMInitializeNativeTarget", CallingConvention = System.Runtime.InteropServices.CallingConvention.Cdecl, BestFitMapping = false, ThrowOnUnmappableChar = true)] internal static extern LLVMBool InitializeNativeTarget(); [DllImport(libraryPath, EntryPoint = "LLVMInitializeNativeAsmParser", CallingConvention = System.Runtime.InteropServices.CallingConvention.Cdecl, BestFitMapping = false, ThrowOnUnmappableChar = true)] internal static extern LLVMBool InitializeNativeAsmParser(); [DllImport(libraryPath, EntryPoint = "LLVMInitializeNativeAsmPrinter", CallingConvention = System.Runtime.InteropServices.CallingConvention.Cdecl, BestFitMapping = false, ThrowOnUnmappableChar = true)] internal static extern LLVMBool InitializeNativeAsmPrinter(); [DllImport(libraryPath, EntryPoint = "LLVMInitializeNativeDisassembler", CallingConvention = System.Runtime.InteropServices.CallingConvention.Cdecl, BestFitMapping = false, ThrowOnUnmappableChar = true)] internal static extern LLVMBool InitializeNativeDisassembler(); [DllImport(libraryPath, EntryPoint = "LLVMCreateTargetData", CallingConvention = System.Runtime.InteropServices.CallingConvention.Cdecl, BestFitMapping = false, ThrowOnUnmappableChar = true)] internal static extern LLVMTargetDataRef CreateTargetData([MarshalAs(UnmanagedType.LPStr)] string @StringRep); [DllImport(libraryPath, EntryPoint = "LLVMAddTargetData", CallingConvention = System.Runtime.InteropServices.CallingConvention.Cdecl, BestFitMapping = false, ThrowOnUnmappableChar = true)] internal static extern void AddTargetData(LLVMTargetDataRef @TD, LLVMPassManagerRef @PM); [DllImport(libraryPath, EntryPoint = "LLVMAddTargetLibraryInfo", CallingConvention = System.Runtime.InteropServices.CallingConvention.Cdecl, BestFitMapping = false, ThrowOnUnmappableChar = true)] internal static extern void AddTargetLibraryInfo(LLVMTargetLibraryInfoRef @TLI, LLVMPassManagerRef @PM); [DllImport(libraryPath, EntryPoint = "LLVMCopyStringRepOfTargetData", CallingConvention = System.Runtime.InteropServices.CallingConvention.Cdecl, BestFitMapping = false, ThrowOnUnmappableChar = true)] internal static extern IntPtr CopyStringRepOfTargetData(LLVMTargetDataRef @TD); [DllImport(libraryPath, EntryPoint = "LLVMByteOrder", CallingConvention = System.Runtime.InteropServices.CallingConvention.Cdecl, BestFitMapping = false, ThrowOnUnmappableChar = true)] internal static extern LLVMByteOrdering ByteOrder(LLVMTargetDataRef @TD); [DllImport(libraryPath, EntryPoint = "LLVMPointerSize", CallingConvention = System.Runtime.InteropServices.CallingConvention.Cdecl, BestFitMapping = false, ThrowOnUnmappableChar = true)] internal static extern uint PointerSize(LLVMTargetDataRef @TD); [DllImport(libraryPath, EntryPoint = "LLVMPointerSizeForAS", CallingConvention = System.Runtime.InteropServices.CallingConvention.Cdecl, BestFitMapping = false, ThrowOnUnmappableChar = true)] internal static extern uint PointerSizeForAS(LLVMTargetDataRef @TD, uint @AS); [DllImport(libraryPath, EntryPoint = "LLVMIntPtrType", CallingConvention = System.Runtime.InteropServices.CallingConvention.Cdecl, BestFitMapping = false, ThrowOnUnmappableChar = true)] internal static extern LLVMTypeRef IntPtrType(LLVMTargetDataRef @TD); [DllImport(libraryPath, EntryPoint = "LLVMIntPtrTypeForAS", CallingConvention = System.Runtime.InteropServices.CallingConvention.Cdecl, BestFitMapping = false, ThrowOnUnmappableChar = true)] internal static extern LLVMTypeRef IntPtrTypeForAS(LLVMTargetDataRef @TD, uint @AS); [DllImport(libraryPath, EntryPoint = "LLVMIntPtrTypeInContext", CallingConvention = System.Runtime.InteropServices.CallingConvention.Cdecl, BestFitMapping = false, ThrowOnUnmappableChar = true)] internal static extern LLVMTypeRef IntPtrTypeInContext(LLVMContextRef @C, LLVMTargetDataRef @TD); [DllImport(libraryPath, EntryPoint = "LLVMIntPtrTypeForASInContext", CallingConvention = System.Runtime.InteropServices.CallingConvention.Cdecl, BestFitMapping = false, ThrowOnUnmappableChar = true)] internal static extern LLVMTypeRef IntPtrTypeForASInContext(LLVMContextRef @C, LLVMTargetDataRef @TD, uint @AS); [DllImport(libraryPath, EntryPoint = "LLVMSizeOfTypeInBits", CallingConvention = System.Runtime.InteropServices.CallingConvention.Cdecl, BestFitMapping = false, ThrowOnUnmappableChar = true)] internal static extern ulong SizeOfTypeInBits(LLVMTargetDataRef @TD, LLVMTypeRef @Ty); [DllImport(libraryPath, EntryPoint = "LLVMStoreSizeOfType", CallingConvention = System.Runtime.InteropServices.CallingConvention.Cdecl, BestFitMapping = false, ThrowOnUnmappableChar = true)] internal static extern ulong StoreSizeOfType(LLVMTargetDataRef @TD, LLVMTypeRef @Ty); [DllImport(libraryPath, EntryPoint = "LLVMABISizeOfType", CallingConvention = System.Runtime.InteropServices.CallingConvention.Cdecl, BestFitMapping = false, ThrowOnUnmappableChar = true)] internal static extern ulong ABISizeOfType(LLVMTargetDataRef @TD, LLVMTypeRef @Ty); [DllImport(libraryPath, EntryPoint = "LLVMABIAlignmentOfType", CallingConvention = System.Runtime.InteropServices.CallingConvention.Cdecl, BestFitMapping = false, ThrowOnUnmappableChar = true)] internal static extern uint ABIAlignmentOfType(LLVMTargetDataRef @TD, LLVMTypeRef @Ty); [DllImport(libraryPath, EntryPoint = "LLVMCallFrameAlignmentOfType", CallingConvention = System.Runtime.InteropServices.CallingConvention.Cdecl, BestFitMapping = false, ThrowOnUnmappableChar = true)] internal static extern uint CallFrameAlignmentOfType(LLVMTargetDataRef @TD, LLVMTypeRef @Ty); [DllImport(libraryPath, EntryPoint = "LLVMPreferredAlignmentOfType", CallingConvention = System.Runtime.InteropServices.CallingConvention.Cdecl, BestFitMapping = false, ThrowOnUnmappableChar = true)] internal static extern uint PreferredAlignmentOfType(LLVMTargetDataRef @TD, LLVMTypeRef @Ty); [DllImport(libraryPath, EntryPoint = "LLVMPreferredAlignmentOfGlobal", CallingConvention = System.Runtime.InteropServices.CallingConvention.Cdecl, BestFitMapping = false, ThrowOnUnmappableChar = true)] internal static extern uint PreferredAlignmentOfGlobal(LLVMTargetDataRef @TD, LLVMValueRef @GlobalVar); [DllImport(libraryPath, EntryPoint = "LLVMElementAtOffset", CallingConvention = System.Runtime.InteropServices.CallingConvention.Cdecl, BestFitMapping = false, ThrowOnUnmappableChar = true)] internal static extern uint ElementAtOffset(LLVMTargetDataRef @TD, LLVMTypeRef @StructTy, ulong @Offset); [DllImport(libraryPath, EntryPoint = "LLVMOffsetOfElement", CallingConvention = System.Runtime.InteropServices.CallingConvention.Cdecl, BestFitMapping = false, ThrowOnUnmappableChar = true)] internal static extern ulong OffsetOfElement(LLVMTargetDataRef @TD, LLVMTypeRef @StructTy, uint @Element); [DllImport(libraryPath, EntryPoint = "LLVMDisposeTargetData", CallingConvention = System.Runtime.InteropServices.CallingConvention.Cdecl, BestFitMapping = false, ThrowOnUnmappableChar = true)] internal static extern void DisposeTargetData(LLVMTargetDataRef @TD); [DllImport(libraryPath, EntryPoint = "LLVMGetFirstTarget", CallingConvention = System.Runtime.InteropServices.CallingConvention.Cdecl, BestFitMapping = false, ThrowOnUnmappableChar = true)] internal static extern LLVMTargetRef GetFirstTarget(); [DllImport(libraryPath, EntryPoint = "LLVMGetNextTarget", CallingConvention = System.Runtime.InteropServices.CallingConvention.Cdecl, BestFitMapping = false, ThrowOnUnmappableChar = true)] internal static extern LLVMTargetRef GetNextTarget(LLVMTargetRef @T); [DllImport(libraryPath, EntryPoint = "LLVMGetTargetFromName", CallingConvention = System.Runtime.InteropServices.CallingConvention.Cdecl, BestFitMapping = false, ThrowOnUnmappableChar = true)] internal static extern LLVMTargetRef GetTargetFromName([MarshalAs(UnmanagedType.LPStr)] string @Name); [DllImport(libraryPath, EntryPoint = "LLVMGetTargetFromTriple", CallingConvention = System.Runtime.InteropServices.CallingConvention.Cdecl, BestFitMapping = false, ThrowOnUnmappableChar = true)] internal static extern LLVMBool GetTargetFromTriple([MarshalAs(UnmanagedType.LPStr)] string @Triple, out LLVMTargetRef @T, out IntPtr @ErrorMessage); [DllImport(libraryPath, EntryPoint = "LLVMGetTargetName", CallingConvention = System.Runtime.InteropServices.CallingConvention.Cdecl, BestFitMapping = false, ThrowOnUnmappableChar = true)] internal static extern IntPtr GetTargetName(LLVMTargetRef @T); [DllImport(libraryPath, EntryPoint = "LLVMGetTargetDescription", CallingConvention = System.Runtime.InteropServices.CallingConvention.Cdecl, BestFitMapping = false, ThrowOnUnmappableChar = true)] internal static extern IntPtr GetTargetDescription(LLVMTargetRef @T); [DllImport(libraryPath, EntryPoint = "LLVMTargetHasJIT", CallingConvention = System.Runtime.InteropServices.CallingConvention.Cdecl, BestFitMapping = false, ThrowOnUnmappableChar = true)] internal static extern LLVMBool TargetHasJIT(LLVMTargetRef @T); [DllImport(libraryPath, EntryPoint = "LLVMTargetHasTargetMachine", CallingConvention = System.Runtime.InteropServices.CallingConvention.Cdecl, BestFitMapping = false, ThrowOnUnmappableChar = true)] internal static extern LLVMBool TargetHasTargetMachine(LLVMTargetRef @T); [DllImport(libraryPath, EntryPoint = "LLVMTargetHasAsmBackend", CallingConvention = System.Runtime.InteropServices.CallingConvention.Cdecl, BestFitMapping = false, ThrowOnUnmappableChar = true)] internal static extern LLVMBool TargetHasAsmBackend(LLVMTargetRef @T); [DllImport(libraryPath, EntryPoint = "LLVMCreateTargetMachine", CallingConvention = System.Runtime.InteropServices.CallingConvention.Cdecl, BestFitMapping = false, ThrowOnUnmappableChar = true)] internal static extern LLVMTargetMachineRef CreateTargetMachine(LLVMTargetRef @T, [MarshalAs(UnmanagedType.LPStr)] string @Triple, [MarshalAs(UnmanagedType.LPStr)] string @CPU, [MarshalAs(UnmanagedType.LPStr)] string @Features, LLVMCodeGenOptLevel @Level, LLVMRelocMode @Reloc, LLVMCodeModel @CodeModel); [DllImport(libraryPath, EntryPoint = "LLVMDisposeTargetMachine", CallingConvention = System.Runtime.InteropServices.CallingConvention.Cdecl, BestFitMapping = false, ThrowOnUnmappableChar = true)] internal static extern void DisposeTargetMachine(LLVMTargetMachineRef @T); [DllImport(libraryPath, EntryPoint = "LLVMGetTargetMachineTarget", CallingConvention = System.Runtime.InteropServices.CallingConvention.Cdecl, BestFitMapping = false, ThrowOnUnmappableChar = true)] internal static extern LLVMTargetRef GetTargetMachineTarget(LLVMTargetMachineRef @T); [DllImport(libraryPath, EntryPoint = "LLVMGetTargetMachineTriple", CallingConvention = System.Runtime.InteropServices.CallingConvention.Cdecl, BestFitMapping = false, ThrowOnUnmappableChar = true)] internal static extern IntPtr GetTargetMachineTriple(LLVMTargetMachineRef @T); [DllImport(libraryPath, EntryPoint = "LLVMGetTargetMachineCPU", CallingConvention = System.Runtime.InteropServices.CallingConvention.Cdecl, BestFitMapping = false, ThrowOnUnmappableChar = true)] internal static extern IntPtr GetTargetMachineCPU(LLVMTargetMachineRef @T); [DllImport(libraryPath, EntryPoint = "LLVMGetTargetMachineFeatureString", CallingConvention = System.Runtime.InteropServices.CallingConvention.Cdecl, BestFitMapping = false, ThrowOnUnmappableChar = true)] internal static extern IntPtr GetTargetMachineFeatureString(LLVMTargetMachineRef @T); [DllImport(libraryPath, EntryPoint = "LLVMGetTargetMachineData", CallingConvention = System.Runtime.InteropServices.CallingConvention.Cdecl, BestFitMapping = false, ThrowOnUnmappableChar = true)] internal static extern LLVMTargetDataRef GetTargetMachineData(LLVMTargetMachineRef @T); [DllImport(libraryPath, EntryPoint = "LLVMSetTargetMachineAsmVerbosity", CallingConvention = System.Runtime.InteropServices.CallingConvention.Cdecl, BestFitMapping = false, ThrowOnUnmappableChar = true)] internal static extern void SetTargetMachineAsmVerbosity(LLVMTargetMachineRef @T, LLVMBool @VerboseAsm); [DllImport(libraryPath, EntryPoint = "LLVMTargetMachineEmitToFile", CallingConvention = System.Runtime.InteropServices.CallingConvention.Cdecl, BestFitMapping = false, ThrowOnUnmappableChar = true)] internal static extern LLVMBool TargetMachineEmitToFile(LLVMTargetMachineRef @T, LLVMModuleRef @M, [MarshalAs(UnmanagedType.LPStr)] string @Filename, LLVMCodeGenFileType @codegen, out IntPtr @ErrorMessage); [DllImport(libraryPath, EntryPoint = "LLVMTargetMachineEmitToMemoryBuffer", CallingConvention = System.Runtime.InteropServices.CallingConvention.Cdecl, BestFitMapping = false, ThrowOnUnmappableChar = true)] internal static extern LLVMBool TargetMachineEmitToMemoryBuffer(LLVMTargetMachineRef @T, LLVMModuleRef @M, LLVMCodeGenFileType @codegen, out IntPtr @ErrorMessage, out LLVMMemoryBufferRef @OutMemBuf); [DllImport(libraryPath, EntryPoint = "LLVMGetDefaultTargetTriple", CallingConvention = System.Runtime.InteropServices.CallingConvention.Cdecl, BestFitMapping = false, ThrowOnUnmappableChar = true)] internal static extern IntPtr GetDefaultTargetTriple(); [DllImport(libraryPath, EntryPoint = "LLVMAddAnalysisPasses", CallingConvention = System.Runtime.InteropServices.CallingConvention.Cdecl, BestFitMapping = false, ThrowOnUnmappableChar = true)] internal static extern void AddAnalysisPasses(LLVMTargetMachineRef @T, LLVMPassManagerRef @PM); [DllImport(libraryPath, EntryPoint = "LLVMLinkInMCJIT", CallingConvention = System.Runtime.InteropServices.CallingConvention.Cdecl, BestFitMapping = false, ThrowOnUnmappableChar = true)] internal static extern void LinkInMCJIT(); [DllImport(libraryPath, EntryPoint = "LLVMLinkInInterpreter", CallingConvention = System.Runtime.InteropServices.CallingConvention.Cdecl, BestFitMapping = false, ThrowOnUnmappableChar = true)] internal static extern void LinkInInterpreter(); [DllImport(libraryPath, EntryPoint = "LLVMCreateGenericValueOfInt", CallingConvention = System.Runtime.InteropServices.CallingConvention.Cdecl, BestFitMapping = false, ThrowOnUnmappableChar = true)] internal static extern LLVMGenericValueRef CreateGenericValueOfInt(LLVMTypeRef @Ty, ulong @N, LLVMBool @IsSigned); [DllImport(libraryPath, EntryPoint = "LLVMCreateGenericValueOfPointer", CallingConvention = System.Runtime.InteropServices.CallingConvention.Cdecl, BestFitMapping = false, ThrowOnUnmappableChar = true)] internal static extern LLVMGenericValueRef CreateGenericValueOfPointer(IntPtr @P); [DllImport(libraryPath, EntryPoint = "LLVMCreateGenericValueOfFloat", CallingConvention = System.Runtime.InteropServices.CallingConvention.Cdecl, BestFitMapping = false, ThrowOnUnmappableChar = true)] internal static extern LLVMGenericValueRef CreateGenericValueOfFloat(LLVMTypeRef @Ty, double @N); [DllImport(libraryPath, EntryPoint = "LLVMGenericValueIntWidth", CallingConvention = System.Runtime.InteropServices.CallingConvention.Cdecl, BestFitMapping = false, ThrowOnUnmappableChar = true)] internal static extern uint GenericValueIntWidth(LLVMGenericValueRef @GenValRef); [DllImport(libraryPath, EntryPoint = "LLVMGenericValueToInt", CallingConvention = System.Runtime.InteropServices.CallingConvention.Cdecl, BestFitMapping = false, ThrowOnUnmappableChar = true)] internal static extern ulong GenericValueToInt(LLVMGenericValueRef @GenVal, LLVMBool @IsSigned); [DllImport(libraryPath, EntryPoint = "LLVMGenericValueToPointer", CallingConvention = System.Runtime.InteropServices.CallingConvention.Cdecl, BestFitMapping = false, ThrowOnUnmappableChar = true)] internal static extern IntPtr GenericValueToPointer(LLVMGenericValueRef @GenVal); [DllImport(libraryPath, EntryPoint = "LLVMGenericValueToFloat", CallingConvention = System.Runtime.InteropServices.CallingConvention.Cdecl, BestFitMapping = false, ThrowOnUnmappableChar = true)] internal static extern double GenericValueToFloat(LLVMTypeRef @TyRef, LLVMGenericValueRef @GenVal); [DllImport(libraryPath, EntryPoint = "LLVMDisposeGenericValue", CallingConvention = System.Runtime.InteropServices.CallingConvention.Cdecl, BestFitMapping = false, ThrowOnUnmappableChar = true)] internal static extern void DisposeGenericValue(LLVMGenericValueRef @GenVal); [DllImport(libraryPath, EntryPoint = "LLVMCreateExecutionEngineForModule", CallingConvention = System.Runtime.InteropServices.CallingConvention.Cdecl, BestFitMapping = false, ThrowOnUnmappableChar = true)] internal static extern LLVMBool CreateExecutionEngineForModule(out LLVMExecutionEngineRef @OutEE, LLVMModuleRef @M, out IntPtr @OutError); [DllImport(libraryPath, EntryPoint = "LLVMCreateInterpreterForModule", CallingConvention = System.Runtime.InteropServices.CallingConvention.Cdecl, BestFitMapping = false, ThrowOnUnmappableChar = true)] internal static extern LLVMBool CreateInterpreterForModule(out LLVMExecutionEngineRef @OutInterp, LLVMModuleRef @M, out IntPtr @OutError); [DllImport(libraryPath, EntryPoint = "LLVMCreateJITCompilerForModule", CallingConvention = System.Runtime.InteropServices.CallingConvention.Cdecl, BestFitMapping = false, ThrowOnUnmappableChar = true)] internal static extern LLVMBool CreateJITCompilerForModule(out LLVMExecutionEngineRef @OutJIT, LLVMModuleRef @M, uint @OptLevel, out IntPtr @OutError); [DllImport(libraryPath, EntryPoint = "LLVMInitializeMCJITCompilerOptions", CallingConvention = System.Runtime.InteropServices.CallingConvention.Cdecl, BestFitMapping = false, ThrowOnUnmappableChar = true)] internal static extern void InitializeMCJITCompilerOptions(out LLVMMCJITCompilerOptions @Options, int @SizeOfOptions); [DllImport(libraryPath, EntryPoint = "LLVMCreateMCJITCompilerForModule", CallingConvention = System.Runtime.InteropServices.CallingConvention.Cdecl, BestFitMapping = false, ThrowOnUnmappableChar = true)] internal static extern LLVMBool CreateMCJITCompilerForModule(out LLVMExecutionEngineRef @OutJIT, LLVMModuleRef @M, out LLVMMCJITCompilerOptions @Options, int @SizeOfOptions, out IntPtr @OutError); [DllImport(libraryPath, EntryPoint = "LLVMDisposeExecutionEngine", CallingConvention = System.Runtime.InteropServices.CallingConvention.Cdecl, BestFitMapping = false, ThrowOnUnmappableChar = true)] internal static extern void DisposeExecutionEngine(LLVMExecutionEngineRef @EE); [DllImport(libraryPath, EntryPoint = "LLVMRunStaticConstructors", CallingConvention = System.Runtime.InteropServices.CallingConvention.Cdecl, BestFitMapping = false, ThrowOnUnmappableChar = true)] internal static extern void RunStaticConstructors(LLVMExecutionEngineRef @EE); [DllImport(libraryPath, EntryPoint = "LLVMRunStaticDestructors", CallingConvention = System.Runtime.InteropServices.CallingConvention.Cdecl, BestFitMapping = false, ThrowOnUnmappableChar = true)] internal static extern void RunStaticDestructors(LLVMExecutionEngineRef @EE); [DllImport(libraryPath, EntryPoint = "LLVMRunFunctionAsMain", CallingConvention = System.Runtime.InteropServices.CallingConvention.Cdecl, BestFitMapping = false, ThrowOnUnmappableChar = true)] internal static extern int RunFunctionAsMain(LLVMExecutionEngineRef @EE, LLVMValueRef @F, uint @ArgC, string[] @ArgV, string[] @EnvP); [DllImport(libraryPath, EntryPoint = "LLVMRunFunction", CallingConvention = System.Runtime.InteropServices.CallingConvention.Cdecl, BestFitMapping = false, ThrowOnUnmappableChar = true)] internal static extern LLVMGenericValueRef RunFunction(LLVMExecutionEngineRef @EE, LLVMValueRef @F, uint @NumArgs, out LLVMGenericValueRef @Args); [DllImport(libraryPath, EntryPoint = "LLVMFreeMachineCodeForFunction", CallingConvention = System.Runtime.InteropServices.CallingConvention.Cdecl, BestFitMapping = false, ThrowOnUnmappableChar = true)] internal static extern void FreeMachineCodeForFunction(LLVMExecutionEngineRef @EE, LLVMValueRef @F); [DllImport(libraryPath, EntryPoint = "LLVMAddModule", CallingConvention = System.Runtime.InteropServices.CallingConvention.Cdecl, BestFitMapping = false, ThrowOnUnmappableChar = true)] internal static extern void AddModule(LLVMExecutionEngineRef @EE, LLVMModuleRef @M); [DllImport(libraryPath, EntryPoint = "LLVMRemoveModule", CallingConvention = System.Runtime.InteropServices.CallingConvention.Cdecl, BestFitMapping = false, ThrowOnUnmappableChar = true)] internal static extern LLVMBool RemoveModule(LLVMExecutionEngineRef @EE, LLVMModuleRef @M, out LLVMModuleRef @OutMod, out IntPtr @OutError); [DllImport(libraryPath, EntryPoint = "LLVMFindFunction", CallingConvention = System.Runtime.InteropServices.CallingConvention.Cdecl, BestFitMapping = false, ThrowOnUnmappableChar = true)] internal static extern LLVMBool FindFunction(LLVMExecutionEngineRef @EE, [MarshalAs(UnmanagedType.LPStr)] string @Name, out LLVMValueRef @OutFn); [DllImport(libraryPath, EntryPoint = "LLVMRecompileAndRelinkFunction", CallingConvention = System.Runtime.InteropServices.CallingConvention.Cdecl, BestFitMapping = false, ThrowOnUnmappableChar = true)] internal static extern IntPtr RecompileAndRelinkFunction(LLVMExecutionEngineRef @EE, LLVMValueRef @Fn); [DllImport(libraryPath, EntryPoint = "LLVMGetExecutionEngineTargetData", CallingConvention = System.Runtime.InteropServices.CallingConvention.Cdecl, BestFitMapping = false, ThrowOnUnmappableChar = true)] internal static extern LLVMTargetDataRef GetExecutionEngineTargetData(LLVMExecutionEngineRef @EE); [DllImport(libraryPath, EntryPoint = "LLVMGetExecutionEngineTargetMachine", CallingConvention = System.Runtime.InteropServices.CallingConvention.Cdecl, BestFitMapping = false, ThrowOnUnmappableChar = true)] internal static extern LLVMTargetMachineRef GetExecutionEngineTargetMachine(LLVMExecutionEngineRef @EE); [DllImport(libraryPath, EntryPoint = "LLVMAddGlobalMapping", CallingConvention = System.Runtime.InteropServices.CallingConvention.Cdecl, BestFitMapping = false, ThrowOnUnmappableChar = true)] internal static extern void AddGlobalMapping(LLVMExecutionEngineRef @EE, LLVMValueRef @Global, IntPtr @Addr); [DllImport(libraryPath, EntryPoint = "LLVMGetPointerToGlobal", CallingConvention = System.Runtime.InteropServices.CallingConvention.Cdecl, BestFitMapping = false, ThrowOnUnmappableChar = true)] internal static extern IntPtr GetPointerToGlobal(LLVMExecutionEngineRef @EE, LLVMValueRef @Global); [DllImport(libraryPath, EntryPoint = "LLVMGetGlobalValueAddress", CallingConvention = System.Runtime.InteropServices.CallingConvention.Cdecl, BestFitMapping = false, ThrowOnUnmappableChar = true)] internal static extern int GetGlobalValueAddress(LLVMExecutionEngineRef @EE, [MarshalAs(UnmanagedType.LPStr)] string @Name); [DllImport(libraryPath, EntryPoint = "LLVMGetFunctionAddress", CallingConvention = System.Runtime.InteropServices.CallingConvention.Cdecl, BestFitMapping = false, ThrowOnUnmappableChar = true)] internal static extern int GetFunctionAddress(LLVMExecutionEngineRef @EE, [MarshalAs(UnmanagedType.LPStr)] string @Name); [DllImport(libraryPath, EntryPoint = "LLVMCreateSimpleMCJITMemoryManager", CallingConvention = System.Runtime.InteropServices.CallingConvention.Cdecl, BestFitMapping = false, ThrowOnUnmappableChar = true)] internal static extern LLVMMCJITMemoryManagerRef CreateSimpleMCJITMemoryManager(IntPtr @Opaque, LLVMMemoryManagerAllocateCodeSectionCallback @AllocateCodeSection, LLVMMemoryManagerAllocateDataSectionCallback @AllocateDataSection, LLVMMemoryManagerFinalizeMemoryCallback @FinalizeMemory, LLVMMemoryManagerDestroyCallback @Destroy); [DllImport(libraryPath, EntryPoint = "LLVMDisposeMCJITMemoryManager", CallingConvention = System.Runtime.InteropServices.CallingConvention.Cdecl, BestFitMapping = false, ThrowOnUnmappableChar = true)] internal static extern void DisposeMCJITMemoryManager(LLVMMCJITMemoryManagerRef @MM); [DllImport(libraryPath, EntryPoint = "LLVMInitializeTransformUtils", CallingConvention = System.Runtime.InteropServices.CallingConvention.Cdecl, BestFitMapping = false, ThrowOnUnmappableChar = true)] internal static extern void InitializeTransformUtils(LLVMPassRegistryRef @R); [DllImport(libraryPath, EntryPoint = "LLVMInitializeScalarOpts", CallingConvention = System.Runtime.InteropServices.CallingConvention.Cdecl, BestFitMapping = false, ThrowOnUnmappableChar = true)] internal static extern void InitializeScalarOpts(LLVMPassRegistryRef @R); [DllImport(libraryPath, EntryPoint = "LLVMInitializeObjCARCOpts", CallingConvention = System.Runtime.InteropServices.CallingConvention.Cdecl, BestFitMapping = false, ThrowOnUnmappableChar = true)] internal static extern void InitializeObjCARCOpts(LLVMPassRegistryRef @R); [DllImport(libraryPath, EntryPoint = "LLVMInitializeVectorization", CallingConvention = System.Runtime.InteropServices.CallingConvention.Cdecl, BestFitMapping = false, ThrowOnUnmappableChar = true)] internal static extern void InitializeVectorization(LLVMPassRegistryRef @R); [DllImport(libraryPath, EntryPoint = "LLVMInitializeInstCombine", CallingConvention = System.Runtime.InteropServices.CallingConvention.Cdecl, BestFitMapping = false, ThrowOnUnmappableChar = true)] internal static extern void InitializeInstCombine(LLVMPassRegistryRef @R); [DllImport(libraryPath, EntryPoint = "LLVMInitializeIPO", CallingConvention = System.Runtime.InteropServices.CallingConvention.Cdecl, BestFitMapping = false, ThrowOnUnmappableChar = true)] internal static extern void InitializeIPO(LLVMPassRegistryRef @R); [DllImport(libraryPath, EntryPoint = "LLVMInitializeInstrumentation", CallingConvention = System.Runtime.InteropServices.CallingConvention.Cdecl, BestFitMapping = false, ThrowOnUnmappableChar = true)] internal static extern void InitializeInstrumentation(LLVMPassRegistryRef @R); [DllImport(libraryPath, EntryPoint = "LLVMInitializeAnalysis", CallingConvention = System.Runtime.InteropServices.CallingConvention.Cdecl, BestFitMapping = false, ThrowOnUnmappableChar = true)] internal static extern void InitializeAnalysis(LLVMPassRegistryRef @R); [DllImport(libraryPath, EntryPoint = "LLVMInitializeIPA", CallingConvention = System.Runtime.InteropServices.CallingConvention.Cdecl, BestFitMapping = false, ThrowOnUnmappableChar = true)] internal static extern void InitializeIPA(LLVMPassRegistryRef @R); [DllImport(libraryPath, EntryPoint = "LLVMInitializeCodeGen", CallingConvention = System.Runtime.InteropServices.CallingConvention.Cdecl, BestFitMapping = false, ThrowOnUnmappableChar = true)] internal static extern void InitializeCodeGen(LLVMPassRegistryRef @R); [DllImport(libraryPath, EntryPoint = "LLVMInitializeTarget", CallingConvention = System.Runtime.InteropServices.CallingConvention.Cdecl, BestFitMapping = false, ThrowOnUnmappableChar = true)] internal static extern void InitializeTarget(LLVMPassRegistryRef @R); [DllImport(libraryPath, EntryPoint = "LLVMParseIRInContext", CallingConvention = System.Runtime.InteropServices.CallingConvention.Cdecl, BestFitMapping = false, ThrowOnUnmappableChar = true)] internal static extern LLVMBool ParseIRInContext(LLVMContextRef @ContextRef, LLVMMemoryBufferRef @MemBuf, out LLVMModuleRef @OutM, out IntPtr @OutMessage); [DllImport(libraryPath, EntryPoint = "LLVMLinkModules", CallingConvention = System.Runtime.InteropServices.CallingConvention.Cdecl, BestFitMapping = false, ThrowOnUnmappableChar = true)] internal static extern LLVMBool LinkModules(LLVMModuleRef @Dest, LLVMModuleRef @Src, LLVMLinkerMode @Mode, out IntPtr @OutMessage); [DllImport(libraryPath, EntryPoint = "LLVMCreateObjectFile", CallingConvention = System.Runtime.InteropServices.CallingConvention.Cdecl, BestFitMapping = false, ThrowOnUnmappableChar = true)] internal static extern LLVMObjectFileRef CreateObjectFile(LLVMMemoryBufferRef @MemBuf); [DllImport(libraryPath, EntryPoint = "LLVMDisposeObjectFile", CallingConvention = System.Runtime.InteropServices.CallingConvention.Cdecl, BestFitMapping = false, ThrowOnUnmappableChar = true)] internal static extern void DisposeObjectFile(LLVMObjectFileRef @ObjectFile); [DllImport(libraryPath, EntryPoint = "LLVMGetSections", CallingConvention = System.Runtime.InteropServices.CallingConvention.Cdecl, BestFitMapping = false, ThrowOnUnmappableChar = true)] internal static extern LLVMSectionIteratorRef GetSections(LLVMObjectFileRef @ObjectFile); [DllImport(libraryPath, EntryPoint = "LLVMDisposeSectionIterator", CallingConvention = System.Runtime.InteropServices.CallingConvention.Cdecl, BestFitMapping = false, ThrowOnUnmappableChar = true)] internal static extern void DisposeSectionIterator(LLVMSectionIteratorRef @SI); [DllImport(libraryPath, EntryPoint = "LLVMIsSectionIteratorAtEnd", CallingConvention = System.Runtime.InteropServices.CallingConvention.Cdecl, BestFitMapping = false, ThrowOnUnmappableChar = true)] internal static extern LLVMBool IsSectionIteratorAtEnd(LLVMObjectFileRef @ObjectFile, LLVMSectionIteratorRef @SI); [DllImport(libraryPath, EntryPoint = "LLVMMoveToNextSection", CallingConvention = System.Runtime.InteropServices.CallingConvention.Cdecl, BestFitMapping = false, ThrowOnUnmappableChar = true)] internal static extern void MoveToNextSection(LLVMSectionIteratorRef @SI); [DllImport(libraryPath, EntryPoint = "LLVMMoveToContainingSection", CallingConvention = System.Runtime.InteropServices.CallingConvention.Cdecl, BestFitMapping = false, ThrowOnUnmappableChar = true)] internal static extern void MoveToContainingSection(LLVMSectionIteratorRef @Sect, LLVMSymbolIteratorRef @Sym); [DllImport(libraryPath, EntryPoint = "LLVMGetSymbols", CallingConvention = System.Runtime.InteropServices.CallingConvention.Cdecl, BestFitMapping = false, ThrowOnUnmappableChar = true)] internal static extern LLVMSymbolIteratorRef GetSymbols(LLVMObjectFileRef @ObjectFile); [DllImport(libraryPath, EntryPoint = "LLVMDisposeSymbolIterator", CallingConvention = System.Runtime.InteropServices.CallingConvention.Cdecl, BestFitMapping = false, ThrowOnUnmappableChar = true)] internal static extern void DisposeSymbolIterator(LLVMSymbolIteratorRef @SI); [DllImport(libraryPath, EntryPoint = "LLVMIsSymbolIteratorAtEnd", CallingConvention = System.Runtime.InteropServices.CallingConvention.Cdecl, BestFitMapping = false, ThrowOnUnmappableChar = true)] internal static extern LLVMBool IsSymbolIteratorAtEnd(LLVMObjectFileRef @ObjectFile, LLVMSymbolIteratorRef @SI); [DllImport(libraryPath, EntryPoint = "LLVMMoveToNextSymbol", CallingConvention = System.Runtime.InteropServices.CallingConvention.Cdecl, BestFitMapping = false, ThrowOnUnmappableChar = true)] internal static extern void MoveToNextSymbol(LLVMSymbolIteratorRef @SI); [DllImport(libraryPath, EntryPoint = "LLVMGetSectionName", CallingConvention = System.Runtime.InteropServices.CallingConvention.Cdecl, BestFitMapping = false, ThrowOnUnmappableChar = true)] internal static extern IntPtr GetSectionName(LLVMSectionIteratorRef @SI); [DllImport(libraryPath, EntryPoint = "LLVMGetSectionSize", CallingConvention = System.Runtime.InteropServices.CallingConvention.Cdecl, BestFitMapping = false, ThrowOnUnmappableChar = true)] internal static extern int GetSectionSize(LLVMSectionIteratorRef @SI); [DllImport(libraryPath, EntryPoint = "LLVMGetSectionContents", CallingConvention = System.Runtime.InteropServices.CallingConvention.Cdecl, BestFitMapping = false, ThrowOnUnmappableChar = true)] internal static extern IntPtr GetSectionContents(LLVMSectionIteratorRef @SI); [DllImport(libraryPath, EntryPoint = "LLVMGetSectionAddress", CallingConvention = System.Runtime.InteropServices.CallingConvention.Cdecl, BestFitMapping = false, ThrowOnUnmappableChar = true)] internal static extern int GetSectionAddress(LLVMSectionIteratorRef @SI); [DllImport(libraryPath, EntryPoint = "LLVMGetSectionContainsSymbol", CallingConvention = System.Runtime.InteropServices.CallingConvention.Cdecl, BestFitMapping = false, ThrowOnUnmappableChar = true)] internal static extern LLVMBool GetSectionContainsSymbol(LLVMSectionIteratorRef @SI, LLVMSymbolIteratorRef @Sym); [DllImport(libraryPath, EntryPoint = "LLVMGetRelocations", CallingConvention = System.Runtime.InteropServices.CallingConvention.Cdecl, BestFitMapping = false, ThrowOnUnmappableChar = true)] internal static extern LLVMRelocationIteratorRef GetRelocations(LLVMSectionIteratorRef @Section); [DllImport(libraryPath, EntryPoint = "LLVMDisposeRelocationIterator", CallingConvention = System.Runtime.InteropServices.CallingConvention.Cdecl, BestFitMapping = false, ThrowOnUnmappableChar = true)] internal static extern void DisposeRelocationIterator(LLVMRelocationIteratorRef @RI); [DllImport(libraryPath, EntryPoint = "LLVMIsRelocationIteratorAtEnd", CallingConvention = System.Runtime.InteropServices.CallingConvention.Cdecl, BestFitMapping = false, ThrowOnUnmappableChar = true)] internal static extern LLVMBool IsRelocationIteratorAtEnd(LLVMSectionIteratorRef @Section, LLVMRelocationIteratorRef @RI); [DllImport(libraryPath, EntryPoint = "LLVMMoveToNextRelocation", CallingConvention = System.Runtime.InteropServices.CallingConvention.Cdecl, BestFitMapping = false, ThrowOnUnmappableChar = true)] internal static extern void MoveToNextRelocation(LLVMRelocationIteratorRef @RI); [DllImport(libraryPath, EntryPoint = "LLVMGetSymbolName", CallingConvention = System.Runtime.InteropServices.CallingConvention.Cdecl, BestFitMapping = false, ThrowOnUnmappableChar = true)] internal static extern IntPtr GetSymbolName(LLVMSymbolIteratorRef @SI); [DllImport(libraryPath, EntryPoint = "LLVMGetSymbolAddress", CallingConvention = System.Runtime.InteropServices.CallingConvention.Cdecl, BestFitMapping = false, ThrowOnUnmappableChar = true)] internal static extern int GetSymbolAddress(LLVMSymbolIteratorRef @SI); [DllImport(libraryPath, EntryPoint = "LLVMGetSymbolSize", CallingConvention = System.Runtime.InteropServices.CallingConvention.Cdecl, BestFitMapping = false, ThrowOnUnmappableChar = true)] internal static extern int GetSymbolSize(LLVMSymbolIteratorRef @SI); [DllImport(libraryPath, EntryPoint = "LLVMGetRelocationOffset", CallingConvention = System.Runtime.InteropServices.CallingConvention.Cdecl, BestFitMapping = false, ThrowOnUnmappableChar = true)] internal static extern int GetRelocationOffset(LLVMRelocationIteratorRef @RI); [DllImport(libraryPath, EntryPoint = "LLVMGetRelocationSymbol", CallingConvention = System.Runtime.InteropServices.CallingConvention.Cdecl, BestFitMapping = false, ThrowOnUnmappableChar = true)] internal static extern LLVMSymbolIteratorRef GetRelocationSymbol(LLVMRelocationIteratorRef @RI); [DllImport(libraryPath, EntryPoint = "LLVMGetRelocationType", CallingConvention = System.Runtime.InteropServices.CallingConvention.Cdecl, BestFitMapping = false, ThrowOnUnmappableChar = true)] internal static extern int GetRelocationType(LLVMRelocationIteratorRef @RI); [DllImport(libraryPath, EntryPoint = "LLVMGetRelocationTypeName", CallingConvention = System.Runtime.InteropServices.CallingConvention.Cdecl, BestFitMapping = false, ThrowOnUnmappableChar = true)] internal static extern IntPtr GetRelocationTypeName(LLVMRelocationIteratorRef @RI); [DllImport(libraryPath, EntryPoint = "LLVMGetRelocationValueString", CallingConvention = System.Runtime.InteropServices.CallingConvention.Cdecl, BestFitMapping = false, ThrowOnUnmappableChar = true)] internal static extern IntPtr GetRelocationValueString(LLVMRelocationIteratorRef @RI); [DllImport(libraryPath, EntryPoint = "LLVMAddArgumentPromotionPass", CallingConvention = System.Runtime.InteropServices.CallingConvention.Cdecl, BestFitMapping = false, ThrowOnUnmappableChar = true)] internal static extern void AddArgumentPromotionPass(LLVMPassManagerRef @PM); [DllImport(libraryPath, EntryPoint = "LLVMAddConstantMergePass", CallingConvention = System.Runtime.InteropServices.CallingConvention.Cdecl, BestFitMapping = false, ThrowOnUnmappableChar = true)] internal static extern void AddConstantMergePass(LLVMPassManagerRef @PM); [DllImport(libraryPath, EntryPoint = "LLVMAddDeadArgEliminationPass", CallingConvention = System.Runtime.InteropServices.CallingConvention.Cdecl, BestFitMapping = false, ThrowOnUnmappableChar = true)] internal static extern void AddDeadArgEliminationPass(LLVMPassManagerRef @PM); [DllImport(libraryPath, EntryPoint = "LLVMAddFunctionAttrsPass", CallingConvention = System.Runtime.InteropServices.CallingConvention.Cdecl, BestFitMapping = false, ThrowOnUnmappableChar = true)] internal static extern void AddFunctionAttrsPass(LLVMPassManagerRef @PM); [DllImport(libraryPath, EntryPoint = "LLVMAddFunctionInliningPass", CallingConvention = System.Runtime.InteropServices.CallingConvention.Cdecl, BestFitMapping = false, ThrowOnUnmappableChar = true)] internal static extern void AddFunctionInliningPass(LLVMPassManagerRef @PM); [DllImport(libraryPath, EntryPoint = "LLVMAddAlwaysInlinerPass", CallingConvention = System.Runtime.InteropServices.CallingConvention.Cdecl, BestFitMapping = false, ThrowOnUnmappableChar = true)] internal static extern void AddAlwaysInlinerPass(LLVMPassManagerRef @PM); [DllImport(libraryPath, EntryPoint = "LLVMAddGlobalDCEPass", CallingConvention = System.Runtime.InteropServices.CallingConvention.Cdecl, BestFitMapping = false, ThrowOnUnmappableChar = true)] internal static extern void AddGlobalDCEPass(LLVMPassManagerRef @PM); [DllImport(libraryPath, EntryPoint = "LLVMAddGlobalOptimizerPass", CallingConvention = System.Runtime.InteropServices.CallingConvention.Cdecl, BestFitMapping = false, ThrowOnUnmappableChar = true)] internal static extern void AddGlobalOptimizerPass(LLVMPassManagerRef @PM); [DllImport(libraryPath, EntryPoint = "LLVMAddIPConstantPropagationPass", CallingConvention = System.Runtime.InteropServices.CallingConvention.Cdecl, BestFitMapping = false, ThrowOnUnmappableChar = true)] internal static extern void AddIPConstantPropagationPass(LLVMPassManagerRef @PM); [DllImport(libraryPath, EntryPoint = "LLVMAddPruneEHPass", CallingConvention = System.Runtime.InteropServices.CallingConvention.Cdecl, BestFitMapping = false, ThrowOnUnmappableChar = true)] internal static extern void AddPruneEHPass(LLVMPassManagerRef @PM); [DllImport(libraryPath, EntryPoint = "LLVMAddIPSCCPPass", CallingConvention = System.Runtime.InteropServices.CallingConvention.Cdecl, BestFitMapping = false, ThrowOnUnmappableChar = true)] internal static extern void AddIPSCCPPass(LLVMPassManagerRef @PM); [DllImport(libraryPath, EntryPoint = "LLVMAddInternalizePass", CallingConvention = System.Runtime.InteropServices.CallingConvention.Cdecl, BestFitMapping = false, ThrowOnUnmappableChar = true)] internal static extern void AddInternalizePass(LLVMPassManagerRef @param0, uint @AllButMain); [DllImport(libraryPath, EntryPoint = "LLVMAddStripDeadPrototypesPass", CallingConvention = System.Runtime.InteropServices.CallingConvention.Cdecl, BestFitMapping = false, ThrowOnUnmappableChar = true)] internal static extern void AddStripDeadPrototypesPass(LLVMPassManagerRef @PM); [DllImport(libraryPath, EntryPoint = "LLVMAddStripSymbolsPass", CallingConvention = System.Runtime.InteropServices.CallingConvention.Cdecl, BestFitMapping = false, ThrowOnUnmappableChar = true)] internal static extern void AddStripSymbolsPass(LLVMPassManagerRef @PM); [DllImport(libraryPath, EntryPoint = "LLVMPassManagerBuilderCreate", CallingConvention = System.Runtime.InteropServices.CallingConvention.Cdecl, BestFitMapping = false, ThrowOnUnmappableChar = true)] internal static extern LLVMPassManagerBuilderRef PassManagerBuilderCreate(); [DllImport(libraryPath, EntryPoint = "LLVMPassManagerBuilderDispose", CallingConvention = System.Runtime.InteropServices.CallingConvention.Cdecl, BestFitMapping = false, ThrowOnUnmappableChar = true)] internal static extern void PassManagerBuilderDispose(LLVMPassManagerBuilderRef @PMB); [DllImport(libraryPath, EntryPoint = "LLVMPassManagerBuilderSetOptLevel", CallingConvention = System.Runtime.InteropServices.CallingConvention.Cdecl, BestFitMapping = false, ThrowOnUnmappableChar = true)] internal static extern void PassManagerBuilderSetOptLevel(LLVMPassManagerBuilderRef @PMB, uint @OptLevel); [DllImport(libraryPath, EntryPoint = "LLVMPassManagerBuilderSetSizeLevel", CallingConvention = System.Runtime.InteropServices.CallingConvention.Cdecl, BestFitMapping = false, ThrowOnUnmappableChar = true)] internal static extern void PassManagerBuilderSetSizeLevel(LLVMPassManagerBuilderRef @PMB, uint @SizeLevel); [DllImport(libraryPath, EntryPoint = "LLVMPassManagerBuilderSetDisableUnitAtATime", CallingConvention = System.Runtime.InteropServices.CallingConvention.Cdecl, BestFitMapping = false, ThrowOnUnmappableChar = true)] internal static extern void PassManagerBuilderSetDisableUnitAtATime(LLVMPassManagerBuilderRef @PMB, LLVMBool @Value); [DllImport(libraryPath, EntryPoint = "LLVMPassManagerBuilderSetDisableUnrollLoops", CallingConvention = System.Runtime.InteropServices.CallingConvention.Cdecl, BestFitMapping = false, ThrowOnUnmappableChar = true)] internal static extern void PassManagerBuilderSetDisableUnrollLoops(LLVMPassManagerBuilderRef @PMB, LLVMBool @Value); [DllImport(libraryPath, EntryPoint = "LLVMPassManagerBuilderSetDisableSimplifyLibCalls", CallingConvention = System.Runtime.InteropServices.CallingConvention.Cdecl, BestFitMapping = false, ThrowOnUnmappableChar = true)] internal static extern void PassManagerBuilderSetDisableSimplifyLibCalls(LLVMPassManagerBuilderRef @PMB, LLVMBool @Value); [DllImport(libraryPath, EntryPoint = "LLVMPassManagerBuilderUseInlinerWithThreshold", CallingConvention = System.Runtime.InteropServices.CallingConvention.Cdecl, BestFitMapping = false, ThrowOnUnmappableChar = true)] internal static extern void PassManagerBuilderUseInlinerWithThreshold(LLVMPassManagerBuilderRef @PMB, uint @Threshold); [DllImport(libraryPath, EntryPoint = "LLVMPassManagerBuilderPopulateFunctionPassManager", CallingConvention = System.Runtime.InteropServices.CallingConvention.Cdecl, BestFitMapping = false, ThrowOnUnmappableChar = true)] internal static extern void PassManagerBuilderPopulateFunctionPassManager(LLVMPassManagerBuilderRef @PMB, LLVMPassManagerRef @PM); [DllImport(libraryPath, EntryPoint = "LLVMPassManagerBuilderPopulateModulePassManager", CallingConvention = System.Runtime.InteropServices.CallingConvention.Cdecl, BestFitMapping = false, ThrowOnUnmappableChar = true)] internal static extern void PassManagerBuilderPopulateModulePassManager(LLVMPassManagerBuilderRef @PMB, LLVMPassManagerRef @PM); [DllImport(libraryPath, EntryPoint = "LLVMPassManagerBuilderPopulateLTOPassManager", CallingConvention = System.Runtime.InteropServices.CallingConvention.Cdecl, BestFitMapping = false, ThrowOnUnmappableChar = true)] internal static extern void PassManagerBuilderPopulateLTOPassManager(LLVMPassManagerBuilderRef @PMB, LLVMPassManagerRef @PM, LLVMBool @Internalize, LLVMBool @RunInliner); [DllImport(libraryPath, EntryPoint = "LLVMAddAggressiveDCEPass", CallingConvention = System.Runtime.InteropServices.CallingConvention.Cdecl, BestFitMapping = false, ThrowOnUnmappableChar = true)] internal static extern void AddAggressiveDCEPass(LLVMPassManagerRef @PM); [DllImport(libraryPath, EntryPoint = "LLVMAddAlignmentFromAssumptionsPass", CallingConvention = System.Runtime.InteropServices.CallingConvention.Cdecl, BestFitMapping = false, ThrowOnUnmappableChar = true)] internal static extern void AddAlignmentFromAssumptionsPass(LLVMPassManagerRef @PM); [DllImport(libraryPath, EntryPoint = "LLVMAddCFGSimplificationPass", CallingConvention = System.Runtime.InteropServices.CallingConvention.Cdecl, BestFitMapping = false, ThrowOnUnmappableChar = true)] internal static extern void AddCFGSimplificationPass(LLVMPassManagerRef @PM); [DllImport(libraryPath, EntryPoint = "LLVMAddDeadStoreEliminationPass", CallingConvention = System.Runtime.InteropServices.CallingConvention.Cdecl, BestFitMapping = false, ThrowOnUnmappableChar = true)] internal static extern void AddDeadStoreEliminationPass(LLVMPassManagerRef @PM); [DllImport(libraryPath, EntryPoint = "LLVMAddScalarizerPass", CallingConvention = System.Runtime.InteropServices.CallingConvention.Cdecl, BestFitMapping = false, ThrowOnUnmappableChar = true)] internal static extern void AddScalarizerPass(LLVMPassManagerRef @PM); [DllImport(libraryPath, EntryPoint = "LLVMAddMergedLoadStoreMotionPass", CallingConvention = System.Runtime.InteropServices.CallingConvention.Cdecl, BestFitMapping = false, ThrowOnUnmappableChar = true)] internal static extern void AddMergedLoadStoreMotionPass(LLVMPassManagerRef @PM); [DllImport(libraryPath, EntryPoint = "LLVMAddGVNPass", CallingConvention = System.Runtime.InteropServices.CallingConvention.Cdecl, BestFitMapping = false, ThrowOnUnmappableChar = true)] internal static extern void AddGVNPass(LLVMPassManagerRef @PM); [DllImport(libraryPath, EntryPoint = "LLVMAddIndVarSimplifyPass", CallingConvention = System.Runtime.InteropServices.CallingConvention.Cdecl, BestFitMapping = false, ThrowOnUnmappableChar = true)] internal static extern void AddIndVarSimplifyPass(LLVMPassManagerRef @PM); [DllImport(libraryPath, EntryPoint = "LLVMAddInstructionCombiningPass", CallingConvention = System.Runtime.InteropServices.CallingConvention.Cdecl, BestFitMapping = false, ThrowOnUnmappableChar = true)] internal static extern void AddInstructionCombiningPass(LLVMPassManagerRef @PM); [DllImport(libraryPath, EntryPoint = "LLVMAddJumpThreadingPass", CallingConvention = System.Runtime.InteropServices.CallingConvention.Cdecl, BestFitMapping = false, ThrowOnUnmappableChar = true)] internal static extern void AddJumpThreadingPass(LLVMPassManagerRef @PM); [DllImport(libraryPath, EntryPoint = "LLVMAddLICMPass", CallingConvention = System.Runtime.InteropServices.CallingConvention.Cdecl, BestFitMapping = false, ThrowOnUnmappableChar = true)] internal static extern void AddLICMPass(LLVMPassManagerRef @PM); [DllImport(libraryPath, EntryPoint = "LLVMAddLoopDeletionPass", CallingConvention = System.Runtime.InteropServices.CallingConvention.Cdecl, BestFitMapping = false, ThrowOnUnmappableChar = true)] internal static extern void AddLoopDeletionPass(LLVMPassManagerRef @PM); [DllImport(libraryPath, EntryPoint = "LLVMAddLoopIdiomPass", CallingConvention = System.Runtime.InteropServices.CallingConvention.Cdecl, BestFitMapping = false, ThrowOnUnmappableChar = true)] internal static extern void AddLoopIdiomPass(LLVMPassManagerRef @PM); [DllImport(libraryPath, EntryPoint = "LLVMAddLoopRotatePass", CallingConvention = System.Runtime.InteropServices.CallingConvention.Cdecl, BestFitMapping = false, ThrowOnUnmappableChar = true)] internal static extern void AddLoopRotatePass(LLVMPassManagerRef @PM); [DllImport(libraryPath, EntryPoint = "LLVMAddLoopRerollPass", CallingConvention = System.Runtime.InteropServices.CallingConvention.Cdecl, BestFitMapping = false, ThrowOnUnmappableChar = true)] internal static extern void AddLoopRerollPass(LLVMPassManagerRef @PM); [DllImport(libraryPath, EntryPoint = "LLVMAddLoopUnrollPass", CallingConvention = System.Runtime.InteropServices.CallingConvention.Cdecl, BestFitMapping = false, ThrowOnUnmappableChar = true)] internal static extern void AddLoopUnrollPass(LLVMPassManagerRef @PM); [DllImport(libraryPath, EntryPoint = "LLVMAddLoopUnswitchPass", CallingConvention = System.Runtime.InteropServices.CallingConvention.Cdecl, BestFitMapping = false, ThrowOnUnmappableChar = true)] internal static extern void AddLoopUnswitchPass(LLVMPassManagerRef @PM); [DllImport(libraryPath, EntryPoint = "LLVMAddMemCpyOptPass", CallingConvention = System.Runtime.InteropServices.CallingConvention.Cdecl, BestFitMapping = false, ThrowOnUnmappableChar = true)] internal static extern void AddMemCpyOptPass(LLVMPassManagerRef @PM); [DllImport(libraryPath, EntryPoint = "LLVMAddPartiallyInlineLibCallsPass", CallingConvention = System.Runtime.InteropServices.CallingConvention.Cdecl, BestFitMapping = false, ThrowOnUnmappableChar = true)] internal static extern void AddPartiallyInlineLibCallsPass(LLVMPassManagerRef @PM); [DllImport(libraryPath, EntryPoint = "LLVMAddLowerSwitchPass", CallingConvention = System.Runtime.InteropServices.CallingConvention.Cdecl, BestFitMapping = false, ThrowOnUnmappableChar = true)] internal static extern void AddLowerSwitchPass(LLVMPassManagerRef @PM); [DllImport(libraryPath, EntryPoint = "LLVMAddPromoteMemoryToRegisterPass", CallingConvention = System.Runtime.InteropServices.CallingConvention.Cdecl, BestFitMapping = false, ThrowOnUnmappableChar = true)] internal static extern void AddPromoteMemoryToRegisterPass(LLVMPassManagerRef @PM); [DllImport(libraryPath, EntryPoint = "LLVMAddReassociatePass", CallingConvention = System.Runtime.InteropServices.CallingConvention.Cdecl, BestFitMapping = false, ThrowOnUnmappableChar = true)] internal static extern void AddReassociatePass(LLVMPassManagerRef @PM); [DllImport(libraryPath, EntryPoint = "LLVMAddSCCPPass", CallingConvention = System.Runtime.InteropServices.CallingConvention.Cdecl, BestFitMapping = false, ThrowOnUnmappableChar = true)] internal static extern void AddSCCPPass(LLVMPassManagerRef @PM); [DllImport(libraryPath, EntryPoint = "LLVMAddScalarReplAggregatesPass", CallingConvention = System.Runtime.InteropServices.CallingConvention.Cdecl, BestFitMapping = false, ThrowOnUnmappableChar = true)] internal static extern void AddScalarReplAggregatesPass(LLVMPassManagerRef @PM); [DllImport(libraryPath, EntryPoint = "LLVMAddScalarReplAggregatesPassSSA", CallingConvention = System.Runtime.InteropServices.CallingConvention.Cdecl, BestFitMapping = false, ThrowOnUnmappableChar = true)] internal static extern void AddScalarReplAggregatesPassSSA(LLVMPassManagerRef @PM); [DllImport(libraryPath, EntryPoint = "LLVMAddScalarReplAggregatesPassWithThreshold", CallingConvention = System.Runtime.InteropServices.CallingConvention.Cdecl, BestFitMapping = false, ThrowOnUnmappableChar = true)] internal static extern void AddScalarReplAggregatesPassWithThreshold(LLVMPassManagerRef @PM, int @Threshold); [DllImport(libraryPath, EntryPoint = "LLVMAddSimplifyLibCallsPass", CallingConvention = System.Runtime.InteropServices.CallingConvention.Cdecl, BestFitMapping = false, ThrowOnUnmappableChar = true)] internal static extern void AddSimplifyLibCallsPass(LLVMPassManagerRef @PM); [DllImport(libraryPath, EntryPoint = "LLVMAddTailCallEliminationPass", CallingConvention = System.Runtime.InteropServices.CallingConvention.Cdecl, BestFitMapping = false, ThrowOnUnmappableChar = true)] internal static extern void AddTailCallEliminationPass(LLVMPassManagerRef @PM); [DllImport(libraryPath, EntryPoint = "LLVMAddConstantPropagationPass", CallingConvention = System.Runtime.InteropServices.CallingConvention.Cdecl, BestFitMapping = false, ThrowOnUnmappableChar = true)] internal static extern void AddConstantPropagationPass(LLVMPassManagerRef @PM); [DllImport(libraryPath, EntryPoint = "LLVMAddDemoteMemoryToRegisterPass", CallingConvention = System.Runtime.InteropServices.CallingConvention.Cdecl, BestFitMapping = false, ThrowOnUnmappableChar = true)] internal static extern void AddDemoteMemoryToRegisterPass(LLVMPassManagerRef @PM); [DllImport(libraryPath, EntryPoint = "LLVMAddVerifierPass", CallingConvention = System.Runtime.InteropServices.CallingConvention.Cdecl, BestFitMapping = false, ThrowOnUnmappableChar = true)] internal static extern void AddVerifierPass(LLVMPassManagerRef @PM); [DllImport(libraryPath, EntryPoint = "LLVMAddCorrelatedValuePropagationPass", CallingConvention = System.Runtime.InteropServices.CallingConvention.Cdecl, BestFitMapping = false, ThrowOnUnmappableChar = true)] internal static extern void AddCorrelatedValuePropagationPass(LLVMPassManagerRef @PM); [DllImport(libraryPath, EntryPoint = "LLVMAddEarlyCSEPass", CallingConvention = System.Runtime.InteropServices.CallingConvention.Cdecl, BestFitMapping = false, ThrowOnUnmappableChar = true)] internal static extern void AddEarlyCSEPass(LLVMPassManagerRef @PM); [DllImport(libraryPath, EntryPoint = "LLVMAddLowerExpectIntrinsicPass", CallingConvention = System.Runtime.InteropServices.CallingConvention.Cdecl, BestFitMapping = false, ThrowOnUnmappableChar = true)] internal static extern void AddLowerExpectIntrinsicPass(LLVMPassManagerRef @PM); [DllImport(libraryPath, EntryPoint = "LLVMAddTypeBasedAliasAnalysisPass", CallingConvention = System.Runtime.InteropServices.CallingConvention.Cdecl, BestFitMapping = false, ThrowOnUnmappableChar = true)] internal static extern void AddTypeBasedAliasAnalysisPass(LLVMPassManagerRef @PM); [DllImport(libraryPath, EntryPoint = "LLVMAddScopedNoAliasAAPass", CallingConvention = System.Runtime.InteropServices.CallingConvention.Cdecl, BestFitMapping = false, ThrowOnUnmappableChar = true)] internal static extern void AddScopedNoAliasAAPass(LLVMPassManagerRef @PM); [DllImport(libraryPath, EntryPoint = "LLVMAddBasicAliasAnalysisPass", CallingConvention = System.Runtime.InteropServices.CallingConvention.Cdecl, BestFitMapping = false, ThrowOnUnmappableChar = true)] internal static extern void AddBasicAliasAnalysisPass(LLVMPassManagerRef @PM); [DllImport(libraryPath, EntryPoint = "LLVMAddBBVectorizePass", CallingConvention = System.Runtime.InteropServices.CallingConvention.Cdecl, BestFitMapping = false, ThrowOnUnmappableChar = true)] internal static extern void AddBBVectorizePass(LLVMPassManagerRef @PM); [DllImport(libraryPath, EntryPoint = "LLVMAddLoopVectorizePass", CallingConvention = System.Runtime.InteropServices.CallingConvention.Cdecl, BestFitMapping = false, ThrowOnUnmappableChar = true)] internal static extern void AddLoopVectorizePass(LLVMPassManagerRef @PM); [DllImport(libraryPath, EntryPoint = "LLVMAddSLPVectorizePass", CallingConvention = System.Runtime.InteropServices.CallingConvention.Cdecl, BestFitMapping = false, ThrowOnUnmappableChar = true)] internal static extern void AddSLPVectorizePass(LLVMPassManagerRef @PM); [DllImport(libraryPath, EntryPoint = "LLVMGetPersonalityFn", CallingConvention = System.Runtime.InteropServices.CallingConvention.Cdecl, BestFitMapping = false, ThrowOnUnmappableChar = true)] internal static extern LLVMValueRef GetPersonalityFunction(LLVMValueRef function); [DllImport(libraryPath, EntryPoint = "LLVMSetPersonalityFn", CallingConvention = System.Runtime.InteropServices.CallingConvention.Cdecl, BestFitMapping = false, ThrowOnUnmappableChar = true)] internal static extern void SetPersonalityFunction(LLVMValueRef function, LLVMValueRef personalityFunction); } } ================================================ FILE: Zelig/Zelig/CompileTime/Llvm.NET/Llvm.NET/LLVM/GeneratedExtensions.cs ================================================ // This file was generated from LLVMLib.3.6.1 Extended API using ClangSharp P/Invoke generator // it was further modified in the following ways: // - removed most uses of the partial keyword except for LLVMNative static class // - added warning disable to avoid benign compiler warnings about fields only set by native code // - modified all elements to be internal instead of public // - modified PInvoke attributes to use fully qualified name for CallingConvention to avoid conflicts // - removed C++ function unwrap() // - removed DEFINE_ISA_CONVERSION_FUNCTIONS which was erroneously mis-identified as a function // declaration rather than a preprocessor macro instantiation // - converted several int return and parameter types to proper LLVMxxxRef types not handled correctly // by the ClangSharp code generator // - numerous additional extension methods added manually. (e.g. as new APIs are added they are done so // manually rather than re-running a tool and then fixing everything up again ) // - manually updated to 3.7.0 APIs // - added BestFitMapping = false, ThrowOnUnmappableChar = true to resolve FxCop issue CA2101 using System; using System.Runtime.InteropServices; namespace Llvm.NET.Native { internal partial struct LLVMMetadataRef { internal LLVMMetadataRef(IntPtr pointer) { Pointer = pointer; } internal readonly IntPtr Pointer; } internal partial struct LLVMDIBuilderRef { internal LLVMDIBuilderRef(IntPtr pointer) { Pointer = pointer; } internal readonly IntPtr Pointer; } internal partial struct LLVMMDOperandRef { internal LLVMMDOperandRef(IntPtr pointer) { Pointer = pointer; } internal readonly IntPtr Pointer; } internal partial struct LLVMNamedMDNodeRef { internal LLVMNamedMDNodeRef(IntPtr pointer) { Pointer = pointer; } internal readonly IntPtr Pointer; } internal partial struct LLVMVersionInfo { internal readonly int Major; internal readonly int Minor; internal readonly int Patch; readonly IntPtr VersionString; } internal enum LLVMModFlagBehavior { @Error = 1, @Warning = 2, @Require = 3, @Override = 4, @Append = 5, @AppendUnique = 6, @ModFlagBehaviorFirstVal = Error, @ModFlagBehaviorLastVal = AppendUnique } internal enum LLVMValueKind : int { @LLVMValueKindArgumentVal, // This is an instance of Argument @LLVMValueKindBasicBlockVal, // This is an instance of BasicBlock @LLVMValueKindFunctionVal, // This is an instance of Function @LLVMValueKindGlobalAliasVal, // This is an instance of GlobalAlias @LLVMValueKindGlobalVariableVal, // This is an instance of GlobalVariable @LLVMValueKindUndefValueVal, // This is an instance of UndefValue @LLVMValueKindBlockAddressVal, // This is an instance of BlockAddress @LLVMValueKindConstantExprVal, // This is an instance of ConstantExpr @LLVMValueKindConstantAggregateZeroVal, // This is an instance of ConstantAggregateZero @LLVMValueKindConstantDataArrayVal, // This is an instance of ConstantDataArray @LLVMValueKindConstantDataVectorVal, // This is an instance of ConstantDataVector @LLVMValueKindConstantIntVal, // This is an instance of ConstantInt @LLVMValueKindConstantFPVal, // This is an instance of ConstantFP @LLVMValueKindConstantArrayVal, // This is an instance of ConstantArray @LLVMValueKindConstantStructVal, // This is an instance of ConstantStruct @LLVMValueKindConstantVectorVal, // This is an instance of ConstantVector @LLVMValueKindConstantPointerNullVal, // This is an instance of ConstantPointerNull @LLVMValueKindConstantTokenNoneVal, // This is an instance of ConstantTokenNull @LLVMValueKindMetadataAsValueVal, // This is an instance of MetadataAsValue @LLVMValueKindInlineAsmVal, // This is an instance of InlineAsm @LLVMValueKindInstructionVal, // This is an instance of Instruction // Enum values starting at InstructionVal are used for Instructions; // Markers: @LLVMValueKindConstantFirstVal = LLVMValueKindFunctionVal, @LLVMValueKindConstantLastVal = LLVMValueKindConstantPointerNullVal }; enum LLVMDwarfTag : ushort { LLVMDwarfTagArrayType = 0x01, LLVMDwarfTagClassType = 0x02, LLVMDwarfTagEntryPoint = 0x03, LLVMDwarfTagEnumerationType = 0x04, LLVMDwarfTagFormalParameter = 0x05, LLVMDwarfTagImportedDeclaration = 0x08, LLVMDwarfTagLabel = 0x0a, LLVMDwarfTagLexicalBlock = 0x0b, LLVMDwarfTagMember = 0x0d, LLVMDwarfTagPointerType = 0x0f, LLVMDwarfTagReferenceType = 0x10, LLVMDwarfTagCompileUnit = 0x11, LLVMDwarfTagStringType = 0x12, LLVMDwarfTagStructureType = 0x13, LLVMDwarfTagSubroutineType = 0x15, LLVMDwarfTagTypeDef = 0x16, LLVMDwarfTagUnionType = 0x17, LLVMDwarfTagUnspecifiedParameters = 0x18, LLVMDwarfTagVariant = 0x19, LLVMDwarfTagCommonBlock = 0x1a, LLVMDwarfTagCommonInclusion = 0x1b, LLVMDwarfTagInheritance = 0x1c, LLVMDwarfTagInlinedSubroutine = 0x1d, LLVMDwarfTagModule = 0x1e, LLVMDwarfTagPtrToMemberType = 0x1f, LLVMDwarfTagSetType = 0x20, LLVMDwarfTagSubrangeType = 0x21, LLVMDwarfTagWithStatement = 0x22, LLVMDwarfTagAccessDeclaration = 0x23, LLVMDwarfTagBaseType = 0x24, LLVMDwarfTagCatchBlock = 0x25, LLVMDwarfTagConstType = 0x26, LLVMDwarfTagConstant = 0x27, LLVMDwarfTagEnumerator = 0x28, LLVMDwarfTagFileType = 0x29, LLVMDwarfTagFriend = 0x2a, LLVMDwarfTagNameList = 0x2b, LLVMDwarfTagNameListItem = 0x2c, LLVMDwarfTagPackedType = 0x2d, LLVMDwarfTagSubProgram = 0x2e, LLVMDwarfTagTemplateTypeParameter = 0x2f, LLVMDwarfTagTemplateValueParameter = 0x30, LLVMDwarfTagThrownType = 0x31, LLVMDwarfTagTryBlock = 0x32, LLVMDwarfTagVariantPart = 0x33, LLVMDwarfTagVariable = 0x34, LLVMDwarfTagVolatileType = 0x35, LLVMDwarfTagDwarfProcedure = 0x36, LLVMDwarfTagRestrictType = 0x37, LLVMDwarfTagInterfaceType = 0x38, LLVMDwarfTagNamespace = 0x39, LLVMDwarfTagImportedModule = 0x3a, LLVMDwarfTagUnspecifiedType = 0x3b, LLVMDwarfTagPartialUnit = 0x3c, LLVMDwarfTagImportedUnit = 0x3d, LLVMDwarfTagCondition = 0x3f, LLVMDwarfTagSharedType = 0x40, LLVMDwarfTagTypeUnit = 0x41, LLVMDwarfTagRValueReferenceType = 0x42, LLVMDwarfTagTemplateAlias = 0x43, // New in DWARF 5: LLVMDwarfTagCoArrayType = 0x44, LLVMDwarfTagGenericSubrange = 0x45, LLVMDwarfTagDynamicType = 0x46, LLVMDwarfTagMipsLoop = 0x4081, LLVMDwarfTagFormatLabel = 0x4101, LLVMDwarfTagFunctionTemplate = 0x4102, LLVMDwarfTagClassTemplate = 0x4103, LLVMDwarfTagGnuTemplateTemplateParam = 0x4106, LLVMDwarfTagGnuTemplateParameterPack = 0x4107, LLVMDwarfTagGnuFormalParameterPack = 0x4108, LLVMDwarfTagLoUser = 0x4080, LLVMDwarfTagAppleProperty = 0x4200, LLVMDwarfTagHiUser = 0xffff }; internal enum LLVMAttrKind { None, Alignment, AlwaysInline, ArgMemOnly, Builtin, ByVal, Cold, Convergent, Dereferenceable, DereferenceableOrNull, InAlloca, InReg, InaccessibleMemOnly, InaccessibleMemOrArgMemOnly, InlineHint, JumpTable, MinSize, Naked, Nest, NoAlias, NoBuiltin, NoCapture, NoDuplicate, NoImplicitFloat, NoInline, NoRecurse, NoRedZone, NoReturn, NoUnwind, NonLazyBind, NonNull, OptimizeForSize, OptimizeNone, ReadNone, ReadOnly, Returned, ReturnsTwice, SExt, SafeStack, SanitizeAddress, SanitizeMemory, SanitizeThread, StackAlignment, StackProtect, StackProtectReq, StackProtectStrong, StructRet, UWTable, ZExt, }; internal enum LLVMMetadataKind { LLVMMetadaKindMDTuple, LLVMMetadaKindDILocation, LLVMMetadaKindGenericDINode, LLVMMetadaKindDISubrange, LLVMMetadaKindDIEnumerator, LLVMMetadaKindDIBasicType, LLVMMetadaKindDIDerivedType, LLVMMetadaKindDICompositeType, LLVMMetadaKindDISubroutineType, LLVMMetadaKindDIFile, LLVMMetadaKindDICompileUnit, LLVMMetadaKindDISubprogram, LLVMMetadaKindDILexicalBlock, LLVMMetadaKindDILexicalBlockFile, LLVMMetadaKindDINamespace, LLVMMetadaKindDIModule, LLVMMetadaKindDITemplateTypeParameter, LLVMMetadaKindDITemplateValueParameter, LLVMMetadaKindDIGlobalVariable, LLVMMetadaKindDILocalVariable, LLVMMetadaKindDIExpression, LLVMMetadaKindDIObjCProperty, LLVMMetadaKindDIImportedEntity, LLVMMetadaKindConstantAsMetadata, LLVMMetadaKindLocalAsMetadata, LLVMMetadaKindMDString }; internal static partial class NativeMethods { [DllImport(libraryPath, EntryPoint = "LLVMGetVersionInfo", CallingConvention = System.Runtime.InteropServices.CallingConvention.Cdecl, BestFitMapping = false, ThrowOnUnmappableChar = true)] public static extern void GetVersionInfo(ref LLVMVersionInfo pVersionInfo); [DllImport( libraryPath, EntryPoint = "LLVMGetValueID", CallingConvention = System.Runtime.InteropServices.CallingConvention.Cdecl, BestFitMapping = false, ThrowOnUnmappableChar = true)] public static extern int GetValueID( LLVMValueRef @val ); [ DllImport( libraryPath, EntryPoint = "LLVMBuildIntCast2", CallingConvention = System.Runtime.InteropServices.CallingConvention.Cdecl, BestFitMapping = false, ThrowOnUnmappableChar = true)] public static extern LLVMValueRef BuildIntCast( LLVMBuilderRef @param0, LLVMValueRef @Val, LLVMTypeRef @DestTy, LLVMBool isSigned, [MarshalAs( UnmanagedType.LPStr )] string @Name ); [DllImport( libraryPath, EntryPoint = "LLVMSetDebugLoc", CallingConvention = System.Runtime.InteropServices.CallingConvention.Cdecl, BestFitMapping = false, ThrowOnUnmappableChar = true)] internal static extern void SetDebugLoc( LLVMValueRef inst, uint line, uint column, LLVMMetadataRef scope ); [DllImport( libraryPath, EntryPoint = "LLVMSetDILocation", CallingConvention = System.Runtime.InteropServices.CallingConvention.Cdecl, BestFitMapping = false, ThrowOnUnmappableChar = true )] internal static extern void SetDILocation( LLVMValueRef inst, LLVMMetadataRef location ); [DllImport( libraryPath, EntryPoint = "LLVMGetDILocationScope", CallingConvention = System.Runtime.InteropServices.CallingConvention.Cdecl, BestFitMapping = false, ThrowOnUnmappableChar = true )] internal static extern LLVMMetadataRef /*DILocalScope*/ GetDILocationScope( LLVMMetadataRef /*DILocation*/ location ); [DllImport( libraryPath, EntryPoint = "LLVMGetDILocationLine", CallingConvention = System.Runtime.InteropServices.CallingConvention.Cdecl, BestFitMapping = false, ThrowOnUnmappableChar = true )] internal static extern UInt32 GetDILocationLine( LLVMMetadataRef /*DILocation*/ location ); [DllImport( libraryPath, EntryPoint = "LLVMGetDILocationColumn", CallingConvention = System.Runtime.InteropServices.CallingConvention.Cdecl, BestFitMapping = false, ThrowOnUnmappableChar = true )] internal static extern UInt32 GetDILocationColumn( LLVMMetadataRef /*DILocation*/ location ); [DllImport( libraryPath, EntryPoint = "LLVMGetDILocationInlinedAt", CallingConvention = System.Runtime.InteropServices.CallingConvention.Cdecl, BestFitMapping = false, ThrowOnUnmappableChar = true )] internal static extern LLVMMetadataRef /*DILocation*/ GetDILocationInlinedAt( LLVMMetadataRef /*DILocation*/ location ); [DllImport( libraryPath, EntryPoint = "LLVMDILocationGetInlinedAtScope", CallingConvention = System.Runtime.InteropServices.CallingConvention.Cdecl, BestFitMapping = false, ThrowOnUnmappableChar = true )] internal static extern LLVMMetadataRef /*DILocalScope*/ DILocationGetInlinedAtScope( LLVMMetadataRef /*DILocation*/ location ); [DllImport(libraryPath, EntryPoint = "LLVMVerifyFunctionEx", CallingConvention = System.Runtime.InteropServices.CallingConvention.Cdecl, BestFitMapping = false, ThrowOnUnmappableChar = true)] internal static extern LLVMBool VerifyFunctionEx(LLVMValueRef @Fn, LLVMVerifierFailureAction @Action, out IntPtr @OutMessages); [DllImport(libraryPath, EntryPoint = "LLVMAddAddressSanitizerFunctionPass", CallingConvention = System.Runtime.InteropServices.CallingConvention.Cdecl, BestFitMapping = false, ThrowOnUnmappableChar = true)] internal static extern void AddAddressSanitizerFunctionPass( LLVMPassManagerRef @PM ); [DllImport(libraryPath, EntryPoint = "LLVMAddAddressSanitizerModulePass", CallingConvention = System.Runtime.InteropServices.CallingConvention.Cdecl, BestFitMapping = false, ThrowOnUnmappableChar = true)] internal static extern void AddAddressSanitizerModulePass( LLVMPassManagerRef @PM ); [DllImport(libraryPath, EntryPoint = "LLVMAddThreadSanitizerPass", CallingConvention = System.Runtime.InteropServices.CallingConvention.Cdecl, BestFitMapping = false, ThrowOnUnmappableChar = true)] internal static extern void AddThreadSanitizerPass( LLVMPassManagerRef @PM ); [DllImport(libraryPath, EntryPoint = "LLVMAddMemorySanitizerPass", CallingConvention = System.Runtime.InteropServices.CallingConvention.Cdecl, BestFitMapping = false, ThrowOnUnmappableChar = true)] internal static extern void AddMemorySanitizerPass( LLVMPassManagerRef @PM ); [DllImport(libraryPath, EntryPoint = "LLVMAddDataFlowSanitizerPass", CallingConvention = System.Runtime.InteropServices.CallingConvention.Cdecl, BestFitMapping = false, ThrowOnUnmappableChar = true)] internal static extern void AddDataFlowSanitizerPass( LLVMPassManagerRef @PM, [MarshalAs(UnmanagedType.LPStr)] string @ABIListFile); [DllImport(libraryPath, EntryPoint = "LLVMAddModuleFlag", CallingConvention = System.Runtime.InteropServices.CallingConvention.Cdecl, BestFitMapping = false, ThrowOnUnmappableChar = true)] internal static extern void AddModuleFlag(LLVMModuleRef @M, LLVMModFlagBehavior behavior, [MarshalAs(UnmanagedType.LPStr)] string @name, uint @value); [DllImport(libraryPath, EntryPoint = "LLVMModuleGetModuleFlagsMetadata", CallingConvention = System.Runtime.InteropServices.CallingConvention.Cdecl, BestFitMapping = false, ThrowOnUnmappableChar = true)] internal static extern LLVMNamedMDNodeRef ModuleGetModuleFlagsMetadata( LLVMModuleRef module ); [DllImport(libraryPath, EntryPoint = "LLVMNamedMDNodeGetNumOperands", CallingConvention = System.Runtime.InteropServices.CallingConvention.Cdecl, BestFitMapping = false, ThrowOnUnmappableChar = true)] internal static extern UInt32 NamedMDNodeGetNumOperands( LLVMNamedMDNodeRef namedMDNode ); [DllImport(libraryPath, EntryPoint = "LLVMNamedMDNodeGetOperand", CallingConvention = System.Runtime.InteropServices.CallingConvention.Cdecl, BestFitMapping = false, ThrowOnUnmappableChar = true)] internal static extern /*MDNode*/ LLVMMetadataRef NamedMDNodeGetOperand( LLVMNamedMDNodeRef namedMDNode, UInt32 index ); [DllImport(libraryPath, EntryPoint = "LLVMNamedMDNodeGetParentModule", CallingConvention = System.Runtime.InteropServices.CallingConvention.Cdecl, BestFitMapping = false, ThrowOnUnmappableChar = true)] internal static extern LLVMModuleRef NamedMDNodeGetParentModule( LLVMNamedMDNodeRef namedMDNode ); [DllImport( libraryPath, EntryPoint = "LLVMGetOrInsertFunction", CallingConvention = System.Runtime.InteropServices.CallingConvention.Cdecl, BestFitMapping = false, ThrowOnUnmappableChar = true)] internal static extern LLVMValueRef GetOrInsertFunction( LLVMModuleRef module, [MarshalAs( UnmanagedType.LPStr )] string @name, LLVMTypeRef functionType ); [DllImport(libraryPath, EntryPoint = "LLVMIsConstantZeroValue", CallingConvention = System.Runtime.InteropServices.CallingConvention.Cdecl, BestFitMapping = false, ThrowOnUnmappableChar = true)] internal static extern LLVMBool IsConstantZeroValue( LLVMValueRef @Val ); [DllImport( libraryPath, EntryPoint = "LLVMRemoveGlobalFromParent", CallingConvention = System.Runtime.InteropServices.CallingConvention.Cdecl, BestFitMapping = false, ThrowOnUnmappableChar = true)] internal static extern void RemoveGlobalFromParent( LLVMValueRef @Val ); [DllImport(libraryPath, EntryPoint = "LLVMConstantAsMetadata", CallingConvention = System.Runtime.InteropServices.CallingConvention.Cdecl, BestFitMapping = false, ThrowOnUnmappableChar = true)] internal static extern LLVMMetadataRef ConstantAsMetadata( LLVMValueRef @Val ); [DllImport(libraryPath, EntryPoint = "LLVMMDString2", CallingConvention = System.Runtime.InteropServices.CallingConvention.Cdecl, BestFitMapping = false, ThrowOnUnmappableChar = true)] internal static extern LLVMMetadataRef MDString2(LLVMContextRef @C, [MarshalAs(UnmanagedType.LPStr)] string @Str, uint @SLen); [DllImport(libraryPath, EntryPoint = "LLVMMDNode2", CallingConvention = System.Runtime.InteropServices.CallingConvention.Cdecl, BestFitMapping = false, ThrowOnUnmappableChar = true)] internal static extern LLVMMetadataRef MDNode2( LLVMContextRef @C, out LLVMMetadataRef @MDs, uint @Count); [DllImport(libraryPath, EntryPoint = "LLVMTemporaryMDNode", CallingConvention = System.Runtime.InteropServices.CallingConvention.Cdecl, BestFitMapping = false, ThrowOnUnmappableChar = true)] internal static extern LLVMMetadataRef TemporaryMDNode( LLVMContextRef @C, out LLVMMetadataRef @MDs, uint @Count); [DllImport(libraryPath, EntryPoint = "LLVMAddNamedMetadataOperand2", CallingConvention = System.Runtime.InteropServices.CallingConvention.Cdecl, BestFitMapping = false, ThrowOnUnmappableChar = true)] internal static extern void AddNamedMetadataOperand2( LLVMModuleRef @M, [MarshalAs(UnmanagedType.LPStr)] string @name, LLVMMetadataRef @Val); [DllImport(libraryPath, EntryPoint = "LLVMSetMetadata2", CallingConvention = System.Runtime.InteropServices.CallingConvention.Cdecl, BestFitMapping = false, ThrowOnUnmappableChar = true)] internal static extern void SetMetadata2( LLVMValueRef @Inst, uint @KindID, LLVMMetadataRef @MD); [DllImport(libraryPath, EntryPoint = "LLVMMetadataReplaceAllUsesWith", CallingConvention = System.Runtime.InteropServices.CallingConvention.Cdecl, BestFitMapping = false, ThrowOnUnmappableChar = true)] internal static extern void MetadataReplaceAllUsesWith(LLVMMetadataRef @MD, LLVMMetadataRef @New); [DllImport(libraryPath, EntryPoint = "LLVMSetCurrentDebugLocation2", CallingConvention = System.Runtime.InteropServices.CallingConvention.Cdecl, BestFitMapping = false, ThrowOnUnmappableChar = true)] internal static extern void SetCurrentDebugLocation2( LLVMBuilderRef @Bref, uint @Line, uint @Col, LLVMMetadataRef @Scope, LLVMMetadataRef @InlinedAt); [DllImport(libraryPath, EntryPoint = "LLVMNewDIBuilder", CallingConvention = System.Runtime.InteropServices.CallingConvention.Cdecl, BestFitMapping = false, ThrowOnUnmappableChar = true)] internal static extern LLVMDIBuilderRef NewDIBuilder( LLVMModuleRef @m, LLVMBool allowUnresolved ); [DllImport(libraryPath, EntryPoint = "LLVMDIBuilderDestroy", CallingConvention = System.Runtime.InteropServices.CallingConvention.Cdecl, BestFitMapping = false, ThrowOnUnmappableChar = true)] internal static extern void DIBuilderDestroy(LLVMDIBuilderRef @d); [DllImport(libraryPath, EntryPoint = "LLVMDIBuilderFinalize", CallingConvention = System.Runtime.InteropServices.CallingConvention.Cdecl, BestFitMapping = false, ThrowOnUnmappableChar = true)] internal static extern void DIBuilderFinalize(LLVMDIBuilderRef @d); [DllImport(libraryPath, EntryPoint = "LLVMDIBuilderCreateCompileUnit", CallingConvention = System.Runtime.InteropServices.CallingConvention.Cdecl, BestFitMapping = false, ThrowOnUnmappableChar = true)] internal static extern LLVMMetadataRef DIBuilderCreateCompileUnit(LLVMDIBuilderRef @D, uint @Language, [MarshalAs(UnmanagedType.LPStr)] string @File, [MarshalAs(UnmanagedType.LPStr)] string @Dir, [MarshalAs(UnmanagedType.LPStr)] string @Producer, int @Optimized, [MarshalAs(UnmanagedType.LPStr)] string @Flags, uint @RuntimeVersion); [DllImport(libraryPath, EntryPoint = "LLVMDIBuilderCreateFile", CallingConvention = System.Runtime.InteropServices.CallingConvention.Cdecl, BestFitMapping = false, ThrowOnUnmappableChar = true)] internal static extern LLVMMetadataRef DIBuilderCreateFile(LLVMDIBuilderRef @D, [MarshalAs(UnmanagedType.LPStr)] string @File, [MarshalAs(UnmanagedType.LPStr)] string @Dir); [DllImport(libraryPath, EntryPoint = "LLVMDIBuilderCreateLexicalBlock", CallingConvention = System.Runtime.InteropServices.CallingConvention.Cdecl, BestFitMapping = false, ThrowOnUnmappableChar = true)] internal static extern LLVMMetadataRef DIBuilderCreateLexicalBlock(LLVMDIBuilderRef @D, LLVMMetadataRef @Scope, LLVMMetadataRef @File, uint @Line, uint @Column); [DllImport(libraryPath, EntryPoint = "LLVMDIBuilderCreateLexicalBlockFile", CallingConvention = System.Runtime.InteropServices.CallingConvention.Cdecl, BestFitMapping = false, ThrowOnUnmappableChar = true)] internal static extern LLVMMetadataRef DIBuilderCreateLexicalBlockFile(LLVMDIBuilderRef @D, LLVMMetadataRef @Scope, LLVMMetadataRef @File, uint @Discriminator); [DllImport(libraryPath, EntryPoint = "LLVMDIBuilderCreateFunction", CallingConvention = System.Runtime.InteropServices.CallingConvention.Cdecl, BestFitMapping = false, ThrowOnUnmappableChar = true)] internal static extern LLVMMetadataRef DIBuilderCreateFunction(LLVMDIBuilderRef @D, LLVMMetadataRef @Scope, [MarshalAs(UnmanagedType.LPStr)] string @Name, [MarshalAs(UnmanagedType.LPStr)] string @LinkageName, LLVMMetadataRef @File, uint @Line, LLVMMetadataRef @CompositeType, int @IsLocalToUnit, int @IsDefinition, uint @ScopeLine, uint @Flags, int @IsOptimized, LLVMMetadataRef TParam, LLVMMetadataRef Decl ); [DllImport(libraryPath, EntryPoint = "LLVMDIBuilderCreateTempFunctionFwdDecl", CallingConvention = System.Runtime.InteropServices.CallingConvention.Cdecl, BestFitMapping = false, ThrowOnUnmappableChar = true)] internal static extern LLVMMetadataRef DIBuilderCreateTempFunctionFwdDecl(LLVMDIBuilderRef @D, LLVMMetadataRef @Scope, [MarshalAs(UnmanagedType.LPStr)] string @Name, [MarshalAs(UnmanagedType.LPStr)] string @LinkageName, LLVMMetadataRef @File, uint @Line, LLVMMetadataRef @CompositeType, int @IsLocalToUnit, int @IsDefinition, uint @ScopeLine, uint @Flags, int @IsOptimized, LLVMMetadataRef TParam, LLVMMetadataRef Decl ); [DllImport(libraryPath, EntryPoint = "LLVMDIBuilderCreateAutoVariable", CallingConvention = System.Runtime.InteropServices.CallingConvention.Cdecl, BestFitMapping = false, ThrowOnUnmappableChar = true)] internal static extern LLVMMetadataRef DIBuilderCreateAutoVariable(LLVMDIBuilderRef @D, LLVMMetadataRef @Scope, [MarshalAs(UnmanagedType.LPStr)] string @Name, LLVMMetadataRef @File, uint @Line, LLVMMetadataRef @Ty, int @AlwaysPreserve, uint @Flags); [DllImport(libraryPath, EntryPoint = "LLVMDIBuilderCreateParameterVariable", CallingConvention = System.Runtime.InteropServices.CallingConvention.Cdecl, BestFitMapping = false, ThrowOnUnmappableChar = true)] internal static extern LLVMMetadataRef DIBuilderCreateParameterVariable(LLVMDIBuilderRef @D, LLVMMetadataRef @Scope, [MarshalAs(UnmanagedType.LPStr)] string @Name, uint @ArgNo, LLVMMetadataRef @File, uint @Line, LLVMMetadataRef @Ty, int @AlwaysPreserve, uint @Flags); [DllImport(libraryPath, EntryPoint = "LLVMDIBuilderCreateBasicType", CallingConvention = System.Runtime.InteropServices.CallingConvention.Cdecl, BestFitMapping = false, ThrowOnUnmappableChar = true)] internal static extern LLVMMetadataRef DIBuilderCreateBasicType(LLVMDIBuilderRef @D, [MarshalAs(UnmanagedType.LPStr)] string @Name, ulong @SizeInBits, ulong @AlignInBits, uint @Encoding); [DllImport(libraryPath, EntryPoint = "LLVMDIBuilderCreatePointerType", CallingConvention = System.Runtime.InteropServices.CallingConvention.Cdecl, BestFitMapping = false, ThrowOnUnmappableChar = true)] internal static extern LLVMMetadataRef DIBuilderCreatePointerType(LLVMDIBuilderRef @D, LLVMMetadataRef @PointeeType, ulong @SizeInBits, ulong @AlignInBits, [MarshalAs(UnmanagedType.LPStr)] string @Name); [DllImport(libraryPath, EntryPoint = "LLVMDIBuilderCreateQualifiedType", CallingConvention = System.Runtime.InteropServices.CallingConvention.Cdecl, BestFitMapping = false, ThrowOnUnmappableChar = true)] internal static extern LLVMMetadataRef DIBuilderCreateQualifiedType( LLVMDIBuilderRef Dref, uint Tag, LLVMMetadataRef BaseType ); [DllImport(libraryPath, EntryPoint = "LLVMDIBuilderCreateSubroutineType", CallingConvention = System.Runtime.InteropServices.CallingConvention.Cdecl, BestFitMapping = false, ThrowOnUnmappableChar = true)] internal static extern LLVMMetadataRef DIBuilderCreateSubroutineType(LLVMDIBuilderRef @D, LLVMMetadataRef @ParameterTypes, uint @Flags); [DllImport(libraryPath, EntryPoint = "LLVMDIBuilderCreateStructType", CallingConvention = System.Runtime.InteropServices.CallingConvention.Cdecl, BestFitMapping = false, ThrowOnUnmappableChar = true)] internal static extern LLVMMetadataRef DIBuilderCreateStructType(LLVMDIBuilderRef @D, LLVMMetadataRef @Scope, [MarshalAs(UnmanagedType.LPStr)] string @Name, LLVMMetadataRef @File, uint @Line, ulong @SizeInBits, ulong @AlignInBits, uint @Flags, LLVMMetadataRef @DerivedFrom, LLVMMetadataRef @ElementTypes); [DllImport(libraryPath, EntryPoint = "LLVMDIBuilderCreateMemberType", CallingConvention = System.Runtime.InteropServices.CallingConvention.Cdecl, BestFitMapping = false, ThrowOnUnmappableChar = true)] internal static extern LLVMMetadataRef DIBuilderCreateMemberType(LLVMDIBuilderRef @D, LLVMMetadataRef @Scope, [MarshalAs(UnmanagedType.LPStr)] string @Name, LLVMMetadataRef @File, uint @Line, ulong @SizeInBits, ulong @AlignInBits, ulong @OffsetInBits, uint @Flags, LLVMMetadataRef @Ty); [DllImport(libraryPath, EntryPoint = "LLVMDIBuilderCreateArrayType", CallingConvention = System.Runtime.InteropServices.CallingConvention.Cdecl, BestFitMapping = false, ThrowOnUnmappableChar = true)] internal static extern LLVMMetadataRef DIBuilderCreateArrayType(LLVMDIBuilderRef @D, ulong @SizeInBits, ulong @AlignInBits, LLVMMetadataRef @ElementType, LLVMMetadataRef @Subscripts); [DllImport(libraryPath, EntryPoint = "LLVMDIBuilderCreateVectorType", CallingConvention = System.Runtime.InteropServices.CallingConvention.Cdecl, BestFitMapping = false, ThrowOnUnmappableChar = true)] internal static extern LLVMMetadataRef DIBuilderCreateVectorType(LLVMDIBuilderRef @D, ulong @SizeInBits, ulong @AlignInBits, LLVMMetadataRef @ElementType, LLVMMetadataRef @Subscripts); [DllImport(libraryPath, EntryPoint = "LLVMDIBuilderCreateTypedef", CallingConvention = System.Runtime.InteropServices.CallingConvention.Cdecl, BestFitMapping = false, ThrowOnUnmappableChar = true)] internal static extern LLVMMetadataRef DIBuilderCreateTypedef(LLVMDIBuilderRef @D, LLVMMetadataRef @Ty, [MarshalAs(UnmanagedType.LPStr)] string @Name, LLVMMetadataRef @File, uint @Line, LLVMMetadataRef @Context); [DllImport(libraryPath, EntryPoint = "LLVMDIBuilderGetOrCreateSubrange", CallingConvention = System.Runtime.InteropServices.CallingConvention.Cdecl, BestFitMapping = false, ThrowOnUnmappableChar = true)] internal static extern LLVMMetadataRef DIBuilderGetOrCreateSubrange(LLVMDIBuilderRef @D, long @Lo, long @Count); [DllImport(libraryPath, EntryPoint = "LLVMDIBuilderGetOrCreateArray", CallingConvention = System.Runtime.InteropServices.CallingConvention.Cdecl, BestFitMapping = false, ThrowOnUnmappableChar = true)] internal static extern LLVMMetadataRef DIBuilderGetOrCreateArray(LLVMDIBuilderRef @D, out LLVMMetadataRef @Data, ulong @Length); [DllImport(libraryPath, EntryPoint = "LLVMDIBuilderGetOrCreateTypeArray", CallingConvention = System.Runtime.InteropServices.CallingConvention.Cdecl, BestFitMapping = false, ThrowOnUnmappableChar = true)] internal static extern LLVMMetadataRef DIBuilderGetOrCreateTypeArray(LLVMDIBuilderRef @D, out LLVMMetadataRef @Data, ulong @Length); [DllImport(libraryPath, EntryPoint = "LLVMDIBuilderCreateExpression", CallingConvention = System.Runtime.InteropServices.CallingConvention.Cdecl, BestFitMapping = false, ThrowOnUnmappableChar = true)] internal static extern LLVMMetadataRef DIBuilderCreateExpression(LLVMDIBuilderRef @Dref, out long @Addr, ulong @Length); [DllImport(libraryPath, EntryPoint = "LLVMDIBuilderInsertDeclareAtEnd", CallingConvention = System.Runtime.InteropServices.CallingConvention.Cdecl, BestFitMapping = false, ThrowOnUnmappableChar = true)] internal static extern LLVMValueRef DIBuilderInsertDeclareAtEnd(LLVMDIBuilderRef @D, LLVMValueRef @Storage, LLVMMetadataRef @VarInfo, LLVMMetadataRef @Expr, LLVMMetadataRef Location, LLVMBasicBlockRef @Block); [DllImport(libraryPath, EntryPoint = "LLVMDIBuilderInsertValueAtEnd", CallingConvention = System.Runtime.InteropServices.CallingConvention.Cdecl, BestFitMapping = false, ThrowOnUnmappableChar = true)] internal static extern LLVMValueRef DIBuilderInsertValueAtEnd(LLVMDIBuilderRef @D, LLVMValueRef @Val, ulong @Offset, LLVMMetadataRef @VarInfo, LLVMMetadataRef @Expr, LLVMMetadataRef Location, LLVMBasicBlockRef @Block); [DllImport(libraryPath, EntryPoint = "LLVMDIBuilderCreateEnumerationType", CallingConvention = System.Runtime.InteropServices.CallingConvention.Cdecl, BestFitMapping = false, ThrowOnUnmappableChar = true)] internal static extern LLVMMetadataRef DIBuilderCreateEnumerationType( LLVMDIBuilderRef @D, LLVMMetadataRef @Scope, [MarshalAs(UnmanagedType.LPStr)] string @Name, LLVMMetadataRef @File, uint @LineNumber, ulong @SizeInBits, ulong @AlignInBits, LLVMMetadataRef @Elements, LLVMMetadataRef @UnderlyingType, [MarshalAs(UnmanagedType.LPStr)]string @UniqueId ); [DllImport( libraryPath, EntryPoint = "LLVMDIBuilderCreateEnumeratorValue", CallingConvention = System.Runtime.InteropServices.CallingConvention.Cdecl, BestFitMapping = false, ThrowOnUnmappableChar = true)] internal static extern LLVMMetadataRef DIBuilderCreateEnumeratorValue( LLVMDIBuilderRef @D, [MarshalAs(UnmanagedType.LPStr)]string @Name, long @Val ); [DllImport( libraryPath, EntryPoint = "LLVMDIDescriptorGetTag", CallingConvention = System.Runtime.InteropServices.CallingConvention.Cdecl, BestFitMapping = false, ThrowOnUnmappableChar = true)] internal static extern LLVMDwarfTag DIDescriptorGetTag( LLVMMetadataRef descriptor ); [DllImport( libraryPath, EntryPoint = "LLVMDIBuilderCreateGlobalVariable", CallingConvention = System.Runtime.InteropServices.CallingConvention.Cdecl, BestFitMapping = false, ThrowOnUnmappableChar = true)] internal static extern LLVMMetadataRef DIBuilderCreateGlobalVariable( LLVMDIBuilderRef Dref, LLVMMetadataRef Context, [MarshalAs(UnmanagedType.LPStr)] string Name, [MarshalAs(UnmanagedType.LPStr)] string LinkageName, LLVMMetadataRef File, uint LineNo, LLVMMetadataRef Ty, LLVMBool isLocalToUnit, LLVMValueRef Val, LLVMMetadataRef Decl ); [DllImport( libraryPath, EntryPoint = "LLVMDIBuilderInsertDeclareBefore", CallingConvention = System.Runtime.InteropServices.CallingConvention.Cdecl, BestFitMapping = false, ThrowOnUnmappableChar = true)] internal static extern LLVMValueRef DIBuilderInsertDeclareBefore( LLVMDIBuilderRef Dref, LLVMValueRef Storage, LLVMMetadataRef VarInfo, LLVMMetadataRef Expr, LLVMMetadataRef Location, LLVMValueRef InsertBefore ); [DllImport( libraryPath, EntryPoint = "LLVMDIBuilderInsertValueBefore", CallingConvention = System.Runtime.InteropServices.CallingConvention.Cdecl, BestFitMapping = false, ThrowOnUnmappableChar = true)] internal static extern LLVMValueRef DIBuilderInsertValueBefore( LLVMDIBuilderRef Dref, /*llvm::Value **/LLVMValueRef Val, UInt64 Offset, /*DILocalVariable **/ LLVMMetadataRef VarInfo, /*DIExpression **/ LLVMMetadataRef Expr, /*const DILocation **/ LLVMMetadataRef DL, /*Instruction **/ LLVMValueRef InsertBefore ); [DllImport( libraryPath, EntryPoint = "LLVMMetadataAsString", CallingConvention = System.Runtime.InteropServices.CallingConvention.Cdecl, BestFitMapping = false, ThrowOnUnmappableChar = true)] internal static extern IntPtr MetadataAsString( LLVMMetadataRef descriptor ); [DllImport( libraryPath, EntryPoint = "LLVMMDNodeReplaceAllUsesWith", CallingConvention = System.Runtime.InteropServices.CallingConvention.Cdecl, BestFitMapping = false, ThrowOnUnmappableChar = true)] internal static extern void MDNodeReplaceAllUsesWith( LLVMMetadataRef oldDescriptor, LLVMMetadataRef newDescriptor ); [DllImport( libraryPath, EntryPoint = "LLVMMetadataAsValue", CallingConvention = System.Runtime.InteropServices.CallingConvention.Cdecl, BestFitMapping = false, ThrowOnUnmappableChar = true)] internal static extern LLVMValueRef MetadataAsValue( LLVMContextRef context, LLVMMetadataRef metadataRef ); [DllImport( libraryPath, EntryPoint = "LLVMDIBuilderCreateReplaceableCompositeType", CallingConvention = System.Runtime.InteropServices.CallingConvention.Cdecl, BestFitMapping = false, ThrowOnUnmappableChar = true)] internal static extern LLVMMetadataRef DIBuilderCreateReplaceableCompositeType( LLVMDIBuilderRef Dref, uint Tag, [MarshalAs(UnmanagedType.LPStr)] string Name, LLVMMetadataRef Scope, LLVMMetadataRef File, uint Line, uint RuntimeLang, ulong SizeInBits, ulong AlignInBits, uint Flags); [DllImport( libraryPath, EntryPoint = "LLVMDIBuilderCreateNamespace", CallingConvention = System.Runtime.InteropServices.CallingConvention.Cdecl, BestFitMapping = false, ThrowOnUnmappableChar = true)] internal static extern LLVMMetadataRef DIBuilderCreateNamespace( LLVMDIBuilderRef Dref, LLVMMetadataRef scope, [MarshalAs( UnmanagedType.LPStr )] string name, LLVMMetadataRef file, uint line ); [DllImport( libraryPath, EntryPoint = "LLVMDILocation", CallingConvention = System.Runtime.InteropServices.CallingConvention.Cdecl, BestFitMapping = false, ThrowOnUnmappableChar = true)] internal static extern LLVMMetadataRef DILocation( LLVMContextRef context, uint Line, uint Column, LLVMMetadataRef scope, LLVMMetadataRef InlinedAt ); [DllImport( libraryPath, EntryPoint = "LLVMGetModuleName", CallingConvention = System.Runtime.InteropServices.CallingConvention.Cdecl, BestFitMapping = false, ThrowOnUnmappableChar = true)] internal static extern IntPtr GetModuleName( LLVMModuleRef module ); [DllImport( libraryPath, EntryPoint = "LLVMIsTemporary", CallingConvention = System.Runtime.InteropServices.CallingConvention.Cdecl, BestFitMapping = false, ThrowOnUnmappableChar = true)] internal static extern LLVMBool IsTemporary( LLVMMetadataRef M ); [DllImport( libraryPath, EntryPoint = "LLVMIsResolved", CallingConvention = System.Runtime.InteropServices.CallingConvention.Cdecl, BestFitMapping = false, ThrowOnUnmappableChar = true)] internal static extern LLVMBool IsResolved( LLVMMetadataRef M ); [DllImport( libraryPath, EntryPoint = "LLVMIsDistinct", CallingConvention = System.Runtime.InteropServices.CallingConvention.Cdecl, BestFitMapping = false, ThrowOnUnmappableChar = true )] internal static extern LLVMBool IsDistinct( LLVMMetadataRef M ); [DllImport( libraryPath, EntryPoint = "LLVMIsUniqued", CallingConvention = System.Runtime.InteropServices.CallingConvention.Cdecl, BestFitMapping = false, ThrowOnUnmappableChar = true )] internal static extern LLVMBool IsUniqued( LLVMMetadataRef M ); [DllImport( libraryPath, EntryPoint = "LLVMGetMDStringText", CallingConvention = System.Runtime.InteropServices.CallingConvention.Cdecl, BestFitMapping = false, ThrowOnUnmappableChar = true)] internal static extern IntPtr GetMDStringText( LLVMMetadataRef M, out uint len ); [DllImport( libraryPath, EntryPoint = "LLVMGetGlobalAlias", CallingConvention = System.Runtime.InteropServices.CallingConvention.Cdecl, BestFitMapping = false, ThrowOnUnmappableChar = true)] internal static extern LLVMValueRef GetGlobalAlias( LLVMModuleRef module, [MarshalAs(UnmanagedType.LPStr)] string name ); [DllImport( libraryPath, EntryPoint = "LLVMGetAliasee", CallingConvention = System.Runtime.InteropServices.CallingConvention.Cdecl, BestFitMapping = false, ThrowOnUnmappableChar = true)] internal static extern LLVMValueRef GetAliasee( LLVMValueRef Val ); [DllImport( libraryPath, EntryPoint = "LLVMMDNodeResolveCycles", CallingConvention = System.Runtime.InteropServices.CallingConvention.Cdecl, BestFitMapping = false, ThrowOnUnmappableChar = true)] internal static extern void MDNodeResolveCycles( LLVMMetadataRef M ); [DllImport( libraryPath, EntryPoint = "LLVMSubProgramDescribes", CallingConvention = System.Runtime.InteropServices.CallingConvention.Cdecl, BestFitMapping = false, ThrowOnUnmappableChar = true)] internal static extern LLVMBool SubProgramDescribes( LLVMMetadataRef subProgram, LLVMValueRef function ); [DllImport( libraryPath, EntryPoint = "LLVMDITypeGetLine", CallingConvention = System.Runtime.InteropServices.CallingConvention.Cdecl, BestFitMapping = false, ThrowOnUnmappableChar = true)] internal static extern UInt32 DITypeGetLine( LLVMMetadataRef typeRef ); [DllImport( libraryPath, EntryPoint = "LLVMDITypeGetSizeInBits", CallingConvention = System.Runtime.InteropServices.CallingConvention.Cdecl, BestFitMapping = false, ThrowOnUnmappableChar = true)] internal static extern UInt64 DITypeGetSizeInBits( LLVMMetadataRef typeRef ); [DllImport( libraryPath, EntryPoint = "LLVMDITypeGetAlignInBits", CallingConvention = System.Runtime.InteropServices.CallingConvention.Cdecl, BestFitMapping = false, ThrowOnUnmappableChar = true)] internal static extern UInt64 DITypeGetAlignInBits( LLVMMetadataRef typeRef ); [DllImport( libraryPath, EntryPoint = "LLVMDITypeGetOffsetInBits", CallingConvention = System.Runtime.InteropServices.CallingConvention.Cdecl, BestFitMapping = false, ThrowOnUnmappableChar = true)] internal static extern UInt64 DITypeGetOffsetInBits( LLVMMetadataRef typeRef ); [DllImport( libraryPath, EntryPoint = "LLVMDITypeGetFlags", CallingConvention = System.Runtime.InteropServices.CallingConvention.Cdecl, BestFitMapping = false, ThrowOnUnmappableChar = true)] internal static extern UInt32 DITypeGetFlags( LLVMMetadataRef typeRef ); [DllImport( libraryPath, EntryPoint = "LLVMDITypeGetScope", CallingConvention = System.Runtime.InteropServices.CallingConvention.Cdecl, BestFitMapping = false, ThrowOnUnmappableChar = true)] internal static extern LLVMMetadataRef DITypeGetScope( LLVMMetadataRef typeRef ); [DllImport( libraryPath, EntryPoint = "LLVMDITypeGetName", CallingConvention = System.Runtime.InteropServices.CallingConvention.Cdecl, BestFitMapping = false, ThrowOnUnmappableChar = true)] internal static extern IntPtr DITypeGetName( LLVMMetadataRef typeRef ); [DllImport( libraryPath, EntryPoint = "LLVMDIScopeGetFile", CallingConvention = System.Runtime.InteropServices.CallingConvention.Cdecl, BestFitMapping = false, ThrowOnUnmappableChar = true )] internal static extern LLVMMetadataRef DIScopeGetFile( LLVMMetadataRef scope ); [DllImport( libraryPath, EntryPoint = "LLVMGetArgumentIndex", CallingConvention = System.Runtime.InteropServices.CallingConvention.Cdecl, BestFitMapping = false, ThrowOnUnmappableChar = true )] internal static extern UInt32 GetArgumentIndex( LLVMValueRef Val ); [DllImport( libraryPath, EntryPoint = "LLVMGetDIFileName", CallingConvention = System.Runtime.InteropServices.CallingConvention.Cdecl, BestFitMapping = false, ThrowOnUnmappableChar = true )] internal static extern IntPtr GetDIFileName( LLVMMetadataRef /*DIFile*/ file ); [DllImport( libraryPath, EntryPoint = "LLVMGetDIFileDirectory", CallingConvention = System.Runtime.InteropServices.CallingConvention.Cdecl, BestFitMapping = false, ThrowOnUnmappableChar = true )] internal static extern IntPtr GetDIFileDirectory( LLVMMetadataRef /*DIFile*/ file ); [DllImport( libraryPath, EntryPoint = "LLVMBuildAtomicCmpXchg", CallingConvention = System.Runtime.InteropServices.CallingConvention.Cdecl, BestFitMapping = false, ThrowOnUnmappableChar = true )] internal static extern LLVMValueRef BuildAtomicCmpXchg( LLVMBuilderRef @B, LLVMValueRef @Ptr, LLVMValueRef @Cmp, LLVMValueRef @New, LLVMAtomicOrdering @successOrdering, LLVMAtomicOrdering @failureOrdering, LLVMBool @singleThread ); [DllImport( libraryPath, EntryPoint = "LLVMGetNodeContext", CallingConvention = System.Runtime.InteropServices.CallingConvention.Cdecl, BestFitMapping = false, ThrowOnUnmappableChar = true )] internal static extern LLVMContextRef GetNodeContext( LLVMMetadataRef /*MDNode*/ node ); [DllImport( libraryPath, EntryPoint = "LLVMGetMetadataID", CallingConvention = System.Runtime.InteropServices.CallingConvention.Cdecl, BestFitMapping = false, ThrowOnUnmappableChar = true )] internal static extern LLVMMetadataKind GetMetadataID( LLVMMetadataRef /*Metadata*/ md ); [DllImport( libraryPath, EntryPoint = "LLVMMDNodeGetNumOperands", CallingConvention = System.Runtime.InteropServices.CallingConvention.Cdecl, BestFitMapping = false, ThrowOnUnmappableChar = true )] internal static extern UInt32 MDNodeGetNumOperands( LLVMMetadataRef /*MDNode*/ node ); [DllImport( libraryPath, EntryPoint = "LLVMMDNodeGetOperand", CallingConvention = System.Runtime.InteropServices.CallingConvention.Cdecl, BestFitMapping = false, ThrowOnUnmappableChar = true )] internal static extern LLVMMDOperandRef MDNodeGetOperand( LLVMMetadataRef /*MDNode*/ node, UInt32 index ); [DllImport( libraryPath, EntryPoint = "LLVMGetOperandNode", CallingConvention = System.Runtime.InteropServices.CallingConvention.Cdecl, BestFitMapping = false, ThrowOnUnmappableChar = true )] internal static extern LLVMMetadataRef GetOperandNode( LLVMMDOperandRef operand ); [DllImport( libraryPath, EntryPoint = "LLVMCreateEmptyAttributeSet", CallingConvention = System.Runtime.InteropServices.CallingConvention.Cdecl, BestFitMapping = false, ThrowOnUnmappableChar = true )] internal static extern UIntPtr CreateEmptyAttributeSet( ); [DllImport( libraryPath, EntryPoint = "LLVMCreateAttributeSetFromKindArray", CallingConvention = System.Runtime.InteropServices.CallingConvention.Cdecl, BestFitMapping = false, ThrowOnUnmappableChar = true )] internal static extern UIntPtr CreateAttributeSetFromKindArray( LLVMContextRef context, UInt32 index, out LLVMAttrKind pKinds, UInt64 len ); [DllImport( libraryPath, EntryPoint = "LLVMCreateAttributeSetFromAttributeSetArray", CallingConvention = System.Runtime.InteropServices.CallingConvention.Cdecl, BestFitMapping = false, ThrowOnUnmappableChar = true )] internal static extern UIntPtr CreateAttributeSetFromAttributeSetArray( LLVMContextRef context, out UIntPtr pAttributes, UInt64 len ); [DllImport( libraryPath, EntryPoint = "LLVMCreateAttributeSetFromBuilder", CallingConvention = System.Runtime.InteropServices.CallingConvention.Cdecl, BestFitMapping = false, ThrowOnUnmappableChar = true )] internal static extern UIntPtr CreateAttributeSetFromBuilder( LLVMContextRef context, UInt32 index, AttributeBuilderHandle bldr ); [DllImport( libraryPath, EntryPoint = "LLVMAttributeSetAddKind", CallingConvention = System.Runtime.InteropServices.CallingConvention.Cdecl, BestFitMapping = false, ThrowOnUnmappableChar = true )] internal static extern UIntPtr AttributeSetAddKind( UIntPtr attributeSet, LLVMContextRef context, UInt32 index, LLVMAttrKind kind ); [DllImport( libraryPath, EntryPoint = "LLVMAttributeSetAddString", CallingConvention = System.Runtime.InteropServices.CallingConvention.Cdecl, BestFitMapping = false, ThrowOnUnmappableChar = true )] internal static extern UIntPtr AttributeSetAddString( UIntPtr attributeSet, LLVMContextRef context, UInt32 index, [MarshalAs(UnmanagedType.LPStr)] string name ); [DllImport( libraryPath, EntryPoint = "LLVMAttributeSetAddStringValue", CallingConvention = System.Runtime.InteropServices.CallingConvention.Cdecl, BestFitMapping = false, ThrowOnUnmappableChar = true )] internal static extern UIntPtr AttributeSetAddStringValue( UIntPtr attributeSet, LLVMContextRef context, UInt32 index, [MarshalAs(UnmanagedType.LPStr)] string name, [MarshalAs(UnmanagedType.LPStr)] string value ); [DllImport( libraryPath, EntryPoint = "LLVMAttributeSetAddAttributes", CallingConvention = System.Runtime.InteropServices.CallingConvention.Cdecl, BestFitMapping = false, ThrowOnUnmappableChar = true )] internal static extern UIntPtr AttributeSetAddAttributes( UIntPtr attributeSet, LLVMContextRef context, UInt32 index, UIntPtr otherAttributeSet ); [DllImport( libraryPath, EntryPoint = "LLVMAttributeSetRemoveAttributeKind", CallingConvention = System.Runtime.InteropServices.CallingConvention.Cdecl, BestFitMapping = false, ThrowOnUnmappableChar = true )] internal static extern UIntPtr AttributeSetRemoveAttributeKind( UIntPtr attributeSet, UInt32 index, LLVMAttrKind kind ); [DllImport( libraryPath, EntryPoint = "LLVMAttributeSetRemoveAttributeSet", CallingConvention = System.Runtime.InteropServices.CallingConvention.Cdecl, BestFitMapping = false, ThrowOnUnmappableChar = true )] internal static extern UIntPtr AttributeSetRemoveAttributeSet( UIntPtr attributeSet, UInt32 index, UIntPtr attributes ); [DllImport( libraryPath, EntryPoint = "LLVMAttributeSetRemoveAttributeBuilder", CallingConvention = System.Runtime.InteropServices.CallingConvention.Cdecl, BestFitMapping = false, ThrowOnUnmappableChar = true )] internal static extern UIntPtr AttributeSetRemoveAttributeBuilder( UIntPtr attributeSet, LLVMContextRef context, UInt32 index, AttributeBuilderHandle bldr ); [DllImport( libraryPath, EntryPoint = "LLVMAttributeSetGetContext", CallingConvention = System.Runtime.InteropServices.CallingConvention.Cdecl, BestFitMapping = false, ThrowOnUnmappableChar = true )] internal static extern LLVMContextRef AttributeSetGetContext( UIntPtr attributeSet ); [DllImport( libraryPath, EntryPoint = "LLVMAttributeGetAttributes", CallingConvention = System.Runtime.InteropServices.CallingConvention.Cdecl, BestFitMapping = false, ThrowOnUnmappableChar = true )] internal static extern UIntPtr AttributeGetAttributes( UIntPtr attributeSet, UInt32 index ); [DllImport( libraryPath, EntryPoint = "LLVMAttributeSetHasAttributeKind", CallingConvention = System.Runtime.InteropServices.CallingConvention.Cdecl, BestFitMapping = false, ThrowOnUnmappableChar = true )] internal static extern LLVMBool AttributeSetHasAttributeKind( UIntPtr attributeSet, UInt32 index, LLVMAttrKind kind ); [DllImport( libraryPath, EntryPoint = "LLVMAttributeSetHasStringAttribute", CallingConvention = System.Runtime.InteropServices.CallingConvention.Cdecl, BestFitMapping = false, ThrowOnUnmappableChar = true )] internal static extern LLVMBool AttributeSetHasStringAttribute( UIntPtr attributeSet, UInt32 index, [MarshalAs(UnmanagedType.LPStr)] string name ); [DllImport( libraryPath, EntryPoint = "LLVMAttributeSetHasAttributes", CallingConvention = System.Runtime.InteropServices.CallingConvention.Cdecl, BestFitMapping = false, ThrowOnUnmappableChar = true )] internal static extern LLVMBool AttributeSetHasAttributes( UIntPtr attributeSet, UInt32 index ); [DllImport( libraryPath, EntryPoint = "LLVMAttributeSetHasAttributeSomewhere", CallingConvention = System.Runtime.InteropServices.CallingConvention.Cdecl, BestFitMapping = false, ThrowOnUnmappableChar = true )] internal static extern LLVMBool AttributeSetHasAttributeSomewhere( UIntPtr attributeSet, LLVMAttrKind kind ); [DllImport( libraryPath, EntryPoint = "LLVMAttributeSetGetAttributeByKind", CallingConvention = System.Runtime.InteropServices.CallingConvention.Cdecl, BestFitMapping = false, ThrowOnUnmappableChar = true )] internal static extern UIntPtr AttributeSetGetAttributeByKind( UIntPtr attributeSet, UInt32 index, LLVMAttrKind kind ); [DllImport( libraryPath, EntryPoint = "LLVMAttributeSetGetAttributeByName", CallingConvention = System.Runtime.InteropServices.CallingConvention.Cdecl, BestFitMapping = false, ThrowOnUnmappableChar = true )] internal static extern UIntPtr AttributeSetGetAttributeByName( UIntPtr attributeSet, UInt32 index, [MarshalAs(UnmanagedType.LPStr)] string name ); [DllImport( libraryPath, EntryPoint = "LLVMAttributeSetToString", CallingConvention = System.Runtime.InteropServices.CallingConvention.Cdecl, BestFitMapping = false, ThrowOnUnmappableChar = true )] internal static extern IntPtr AttributeSetToString( UIntPtr attributeSet, UInt32 index, LLVMBool inGroup ); [DllImport( libraryPath, EntryPoint = "LLVMAttributeSetGetNumSlots", CallingConvention = System.Runtime.InteropServices.CallingConvention.Cdecl, BestFitMapping = false, ThrowOnUnmappableChar = true )] internal static extern UInt32 AttributeSetGetNumSlots( UIntPtr attributeSet ); [DllImport( libraryPath, EntryPoint = "LLVMAttributeSetGetSlotAttributes", CallingConvention = System.Runtime.InteropServices.CallingConvention.Cdecl, BestFitMapping = false, ThrowOnUnmappableChar = true )] internal static extern UIntPtr AttributeSetGetSlotAttributes( UIntPtr attributeSet, UInt32 slot ); [DllImport( libraryPath, EntryPoint = "LLVMAttributeSetGetSlotIndex", CallingConvention = System.Runtime.InteropServices.CallingConvention.Cdecl, BestFitMapping = false, ThrowOnUnmappableChar = true )] internal static extern UInt32 AttributeSetGetSlotIndex( UIntPtr attributeSet, UInt32 slot ); [DllImport( libraryPath, EntryPoint = "LLVMGetFunctionAttributeSet", CallingConvention = System.Runtime.InteropServices.CallingConvention.Cdecl, BestFitMapping = false, ThrowOnUnmappableChar = true )] internal static extern UIntPtr GetFunctionAttributeSet( LLVMValueRef /*Function*/ function ); [DllImport( libraryPath, EntryPoint = "LLVMSetFunctionAttributeSet", CallingConvention = System.Runtime.InteropServices.CallingConvention.Cdecl, BestFitMapping = false, ThrowOnUnmappableChar = true )] internal static extern void SetFunctionAttributeSet( LLVMValueRef /*Function*/ function, UIntPtr attributeSet ); [DllImport( libraryPath, EntryPoint = "LLVMGetCallSiteAttributeSet", CallingConvention = System.Runtime.InteropServices.CallingConvention.Cdecl, BestFitMapping = false, ThrowOnUnmappableChar = true )] internal static extern UIntPtr GetCallSiteAttributeSet( LLVMValueRef /*Instruction*/ instruction ); [DllImport( libraryPath, EntryPoint = "LLVMSetCallSiteAttributeSet", CallingConvention = System.Runtime.InteropServices.CallingConvention.Cdecl, BestFitMapping = false, ThrowOnUnmappableChar = true )] internal static extern void SetCallSiteAttributeSet( LLVMValueRef /*Instruction*/ instruction, UIntPtr attributeSet ); [DllImport( libraryPath, EntryPoint = "LLVMAttributeSetGetIteratorStartToken", CallingConvention = System.Runtime.InteropServices.CallingConvention.Cdecl, BestFitMapping = false, ThrowOnUnmappableChar = true )] internal static extern UIntPtr AttributeSetGetIteratorStartToken( UIntPtr attributeSet, UInt32 slot ); [DllImport( libraryPath, EntryPoint = "LLVMAttributeSetIteratorGetNext", CallingConvention = System.Runtime.InteropServices.CallingConvention.Cdecl, BestFitMapping = false, ThrowOnUnmappableChar = true )] internal static extern UIntPtr AttributeSetIteratorGetNext( UIntPtr attributeSet, UInt32 slot, ref UIntPtr pToken ); [DllImport( libraryPath, EntryPoint = "LLVMIsEnumAttribute", CallingConvention = System.Runtime.InteropServices.CallingConvention.Cdecl, BestFitMapping = false, ThrowOnUnmappableChar = true )] internal static extern LLVMBool IsEnumAttribute( UIntPtr attribute ); [DllImport( libraryPath, EntryPoint = "LLVMIsIntAttribute", CallingConvention = System.Runtime.InteropServices.CallingConvention.Cdecl, BestFitMapping = false, ThrowOnUnmappableChar = true )] internal static extern LLVMBool IsIntAttribute( UIntPtr attribute ); [DllImport( libraryPath, EntryPoint = "LLVMIsStringAttribute", CallingConvention = System.Runtime.InteropServices.CallingConvention.Cdecl, BestFitMapping = false, ThrowOnUnmappableChar = true )] internal static extern LLVMBool IsStringAttribute( UIntPtr attribute ); [DllImport( libraryPath, EntryPoint = "LLVMHasAttributeKind", CallingConvention = System.Runtime.InteropServices.CallingConvention.Cdecl, BestFitMapping = false, ThrowOnUnmappableChar = true )] internal static extern LLVMBool HasAttributeKind( UIntPtr attribute, LLVMAttrKind kind ); [DllImport( libraryPath, EntryPoint = "LLVMHasAttributeString", CallingConvention = System.Runtime.InteropServices.CallingConvention.Cdecl, BestFitMapping = false, ThrowOnUnmappableChar = true )] internal static extern LLVMBool HasAttributeString( UIntPtr attribute, [MarshalAs(UnmanagedType.LPStr)] string name ); [DllImport( libraryPath, EntryPoint = "LLVMGetAttributeKind", CallingConvention = System.Runtime.InteropServices.CallingConvention.Cdecl, BestFitMapping = false, ThrowOnUnmappableChar = true )] internal static extern LLVMAttrKind GetAttributeKind( UIntPtr attribute ); [DllImport( libraryPath, EntryPoint = "LLVMGetAttributeValue", CallingConvention = System.Runtime.InteropServices.CallingConvention.Cdecl, BestFitMapping = false, ThrowOnUnmappableChar = true )] internal static extern UInt64 GetAttributeValue( UIntPtr attribute ); [DllImport( libraryPath, EntryPoint = "LLVMGetAttributeName", CallingConvention = System.Runtime.InteropServices.CallingConvention.Cdecl, BestFitMapping = false, ThrowOnUnmappableChar = true )] internal static extern IntPtr GetAttributeName( UIntPtr attribute ); [DllImport( libraryPath, EntryPoint = "LLVMGetAttributeStringValue", CallingConvention = System.Runtime.InteropServices.CallingConvention.Cdecl, BestFitMapping = false, ThrowOnUnmappableChar = true )] internal static extern IntPtr GetAttributeStringValue( UIntPtr attribute ); [DllImport( libraryPath, EntryPoint = "LLVMAttributeToString", CallingConvention = System.Runtime.InteropServices.CallingConvention.Cdecl, BestFitMapping = false, ThrowOnUnmappableChar = true )] internal static extern IntPtr AttributeToString( UIntPtr attribute ); [DllImport( libraryPath, EntryPoint = "LLVMCreateAttribute", CallingConvention = System.Runtime.InteropServices.CallingConvention.Cdecl, BestFitMapping = false, ThrowOnUnmappableChar = true )] internal static extern UIntPtr CreateAttribute( LLVMContextRef ctx, LLVMAttrKind kind, UInt64 value ); [DllImport( libraryPath, EntryPoint = "LVMCreateTargetDependentAttribute", CallingConvention = System.Runtime.InteropServices.CallingConvention.Cdecl, BestFitMapping = false, ThrowOnUnmappableChar = true )] internal static extern UIntPtr CreateTargetDependentAttribute( LLVMContextRef ctx, [MarshalAs(UnmanagedType.LPStr)] string name, [MarshalAs(UnmanagedType.LPStr)] string value ); [DllImport( libraryPath, EntryPoint = "LLVMCreateAttributeBuilder", CallingConvention = System.Runtime.InteropServices.CallingConvention.Cdecl, BestFitMapping = false, ThrowOnUnmappableChar = true )] internal static extern AttributeBuilderHandle CreateAttributeBuilder( ); [DllImport( libraryPath, EntryPoint = "LLVMCreateAttributeBuilder2", CallingConvention = System.Runtime.InteropServices.CallingConvention.Cdecl, BestFitMapping = false, ThrowOnUnmappableChar = true )] internal static extern AttributeBuilderHandle CreateAttributeBuilder2( UIntPtr value ); [DllImport( libraryPath, EntryPoint = "LLVMCreateAttributeBuilder3", CallingConvention = System.Runtime.InteropServices.CallingConvention.Cdecl, BestFitMapping = false, ThrowOnUnmappableChar = true )] internal static extern AttributeBuilderHandle CreateAttributeBuilder3( UIntPtr attributeSet, UInt32 index ); [DllImport( libraryPath, EntryPoint = "LLVMAttributeBuilderDispose", CallingConvention = System.Runtime.InteropServices.CallingConvention.Cdecl, BestFitMapping = false, ThrowOnUnmappableChar = true )] internal static extern void AttributeBuilderDispose( IntPtr bldr ); [DllImport( libraryPath, EntryPoint = "LLVMAttributeBuilderClear", CallingConvention = System.Runtime.InteropServices.CallingConvention.Cdecl, BestFitMapping = false, ThrowOnUnmappableChar = true )] internal static extern void AttributeBuilderClear( AttributeBuilderHandle bldr ); [DllImport( libraryPath, EntryPoint = "LLVMAttributeBuilderAddEnum", CallingConvention = System.Runtime.InteropServices.CallingConvention.Cdecl, BestFitMapping = false, ThrowOnUnmappableChar = true )] internal static extern void AttributeBuilderAddEnum( AttributeBuilderHandle bldr, LLVMAttrKind kind ); [DllImport( libraryPath, EntryPoint = "LLVMAttributeBuilderAddAttribute", CallingConvention = System.Runtime.InteropServices.CallingConvention.Cdecl, BestFitMapping = false, ThrowOnUnmappableChar = true )] internal static extern void AttributeBuilderAddAttribute( AttributeBuilderHandle bldr, UIntPtr value ); [DllImport( libraryPath, EntryPoint = "LLVMAttributeBuilderAddStringAttribute", CallingConvention = System.Runtime.InteropServices.CallingConvention.Cdecl, BestFitMapping = false, ThrowOnUnmappableChar = true )] internal static extern void AttributeBuilderAddStringAttribute( AttributeBuilderHandle bldr, [MarshalAs(UnmanagedType.LPStr)] string name, [MarshalAs(UnmanagedType.LPStr)] string value ); [DllImport( libraryPath, EntryPoint = "LLVMAttributeBuilderRemoveEnum", CallingConvention = System.Runtime.InteropServices.CallingConvention.Cdecl, BestFitMapping = false, ThrowOnUnmappableChar = true )] internal static extern void AttributeBuilderRemoveEnum( AttributeBuilderHandle bldr, LLVMAttrKind kind ); [DllImport( libraryPath, EntryPoint = "LLVMAttributeBuilderRemoveAttributes", CallingConvention = System.Runtime.InteropServices.CallingConvention.Cdecl, BestFitMapping = false, ThrowOnUnmappableChar = true )] internal static extern void AttributeBuilderRemoveAttributes( AttributeBuilderHandle bldr, UIntPtr attributeSet, UInt32 index ); [DllImport( libraryPath, EntryPoint = "LLVMAttributeBuilderRemoveAttribute", CallingConvention = System.Runtime.InteropServices.CallingConvention.Cdecl, BestFitMapping = false, ThrowOnUnmappableChar = true )] internal static extern void AttributeBuilderRemoveAttribute( AttributeBuilderHandle bldr, [MarshalAs(UnmanagedType.LPStr)] string name ); [DllImport( libraryPath, EntryPoint = "LLVMAttributeBuilderRemoveBldr", CallingConvention = System.Runtime.InteropServices.CallingConvention.Cdecl, BestFitMapping = false, ThrowOnUnmappableChar = true )] internal static extern void AttributeBuilderRemoveBldr( AttributeBuilderHandle bldr, AttributeBuilderHandle ohter ); [DllImport( libraryPath, EntryPoint = "LLVMAttributeBuilderMerge", CallingConvention = System.Runtime.InteropServices.CallingConvention.Cdecl, BestFitMapping = false, ThrowOnUnmappableChar = true )] internal static extern void AttributeBuilderMerge( AttributeBuilderHandle bldr, AttributeBuilderHandle ohter ); [DllImport( libraryPath, EntryPoint = "LLVMAttributeBuilderOverlaps", CallingConvention = System.Runtime.InteropServices.CallingConvention.Cdecl, BestFitMapping = false, ThrowOnUnmappableChar = true )] internal static extern LLVMBool AttributeBuilderOverlaps( AttributeBuilderHandle bldr, AttributeBuilderHandle other ); [DllImport( libraryPath, EntryPoint = "LLVMAttributeBuilderContainsEnum", CallingConvention = System.Runtime.InteropServices.CallingConvention.Cdecl, BestFitMapping = false, ThrowOnUnmappableChar = true )] internal static extern LLVMBool AttributeBuilderContainsEnum( AttributeBuilderHandle bldr, LLVMAttrKind kind ); [DllImport( libraryPath, EntryPoint = "LLVMAttributeBuilderContainsName", CallingConvention = System.Runtime.InteropServices.CallingConvention.Cdecl, BestFitMapping = false, ThrowOnUnmappableChar = true )] internal static extern LLVMBool AttributeBuilderContainsName( AttributeBuilderHandle bldr, [MarshalAs(UnmanagedType.LPStr)] string name ); [DllImport( libraryPath, EntryPoint = "LLVMAttributeBuilderHasAnyAttributes", CallingConvention = System.Runtime.InteropServices.CallingConvention.Cdecl, BestFitMapping = false, ThrowOnUnmappableChar = true )] internal static extern LLVMBool AttributeBuilderHasAnyAttributes( AttributeBuilderHandle bldr ); [DllImport( libraryPath, EntryPoint = "LLVMAttributeBuilderHasAttributes", CallingConvention = System.Runtime.InteropServices.CallingConvention.Cdecl, BestFitMapping = false, ThrowOnUnmappableChar = true )] internal static extern LLVMBool AttributeBuilderHasAttributes( AttributeBuilderHandle bldr, UIntPtr attributeset, UInt32 index ); [DllImport( libraryPath, EntryPoint = "LLVMAttributeBuilderHasTargetIndependentAttrs", CallingConvention = System.Runtime.InteropServices.CallingConvention.Cdecl, BestFitMapping = false, ThrowOnUnmappableChar = true )] internal static extern LLVMBool AttributeBuilderHasTargetIndependentAttrs( AttributeBuilderHandle bldr ); [DllImport( libraryPath, EntryPoint = "LLVMAttributeBuilderHasTargetDependentAttrs", CallingConvention = System.Runtime.InteropServices.CallingConvention.Cdecl, BestFitMapping = false, ThrowOnUnmappableChar = true )] internal static extern LLVMBool AttributeBuilderHasTargetDependentAttrs( AttributeBuilderHandle bldr ); [DllImport(libraryPath, EntryPoint = "LLVMDILocalScopeGetSubProgram", CallingConvention = System.Runtime.InteropServices.CallingConvention.Cdecl, BestFitMapping = false, ThrowOnUnmappableChar = true)] internal static extern LLVMMetadataRef DILocalScopeGetSubProgram(LLVMMetadataRef /*DILocalScope*/ localScope); [DllImport( libraryPath, EntryPoint = "LLVMFunctionGetSubprogram", CallingConvention = System.Runtime.InteropServices.CallingConvention.Cdecl, BestFitMapping = false, ThrowOnUnmappableChar = true )] internal static extern LLVMMetadataRef FunctionGetSubprogram( LLVMValueRef function ); [DllImport( libraryPath, EntryPoint = "LLVMFunctionSetSubprogram", CallingConvention = System.Runtime.InteropServices.CallingConvention.Cdecl, BestFitMapping = false, ThrowOnUnmappableChar = true )] internal static extern void FunctionSetSubprogram( LLVMValueRef function, LLVMMetadataRef subprogram ); [DllImport(libraryPath, EntryPoint = "LLVMFunctionHasPersonalityFunction", CallingConvention = System.Runtime.InteropServices.CallingConvention.Cdecl, BestFitMapping = false, ThrowOnUnmappableChar = true)] internal static extern LLVMBool FunctionHasPersonalityFunction( LLVMValueRef function ); } } ================================================ FILE: Zelig/Zelig/CompileTime/Llvm.NET/Llvm.NET/LLVM/LLVMNative.cs ================================================ using System; using System.Diagnostics; using System.IO; using System.Reflection; using System.Runtime.InteropServices; using System.Text.RegularExpressions; using System.Threading; using Llvm.NET.Values; namespace Llvm.NET.Native { internal enum ValueKind : uint { Argument = LLVMValueKind.LLVMValueKindArgumentVal, // This is an instance of Argument BasicBlock = LLVMValueKind.LLVMValueKindBasicBlockVal, // This is an instance of BasicBlock Function = LLVMValueKind.LLVMValueKindFunctionVal, // This is an instance of Function GlobalAlias = LLVMValueKind.LLVMValueKindGlobalAliasVal, // This is an instance of GlobalAlias GlobalVariable = LLVMValueKind.LLVMValueKindGlobalVariableVal, // This is an instance of GlobalVariable UndefValue = LLVMValueKind.LLVMValueKindUndefValueVal, // This is an instance of UndefValue BlockAddress = LLVMValueKind.LLVMValueKindBlockAddressVal, // This is an instance of BlockAddress ConstantExpr = LLVMValueKind.LLVMValueKindConstantExprVal, // This is an instance of ConstantExpr ConstantAggregateZero = LLVMValueKind.LLVMValueKindConstantAggregateZeroVal,// This is an instance of ConstantAggregateZero ConstantDataArray = LLVMValueKind.LLVMValueKindConstantDataArrayVal, // This is an instance of ConstantDataArray ConstantDataVector = LLVMValueKind.LLVMValueKindConstantDataVectorVal, // This is an instance of ConstantDataVector ConstantInt = LLVMValueKind.LLVMValueKindConstantIntVal, // This is an instance of ConstantInt ConstantFP = LLVMValueKind.LLVMValueKindConstantFPVal, // This is an instance of ConstantFP ConstantArray = LLVMValueKind.LLVMValueKindConstantArrayVal, // This is an instance of ConstantArray ConstantStruct = LLVMValueKind.LLVMValueKindConstantStructVal, // This is an instance of ConstantStruct ConstantVector = LLVMValueKind.LLVMValueKindConstantVectorVal, // This is an instance of ConstantVector ConstantPointerNull = LLVMValueKind.LLVMValueKindConstantPointerNullVal, // This is an instance of ConstantPointerNull ConstantTokenNone = LLVMValueKind.LLVMValueKindConstantTokenNoneVal, // This is an instance of ConstantTokenNone MetadataAsValue = LLVMValueKind.LLVMValueKindMetadataAsValueVal, // This is an instance of MetadataAsValue InlineAsm = LLVMValueKind.LLVMValueKindInlineAsmVal, // This is an instance of InlineAsm Instruction = LLVMValueKind.LLVMValueKindInstructionVal, // This is an instance of Instruction // Enum values starting at InstructionVal are used for Instructions; // instruction values come directly from LLVM Instruction.def which is different from the "stable" // LLVM-C API, therefore they are less "stable" and bound to the C++ implementation version and // subject to change from version to version. Return = 1 + Instruction, // Terminators Branch = 2 + Instruction, Switch = 3 + Instruction, IndirectBranch = 4 + Instruction, Invoke = 5 + Instruction, Resume = 6 + Instruction, Unreachable = 7 + Instruction, CleanUpReturn = 8 + Instruction, CatchReturn = 9 + Instruction, CatchSwitch = 10 + Instruction, Add = 11 + Instruction, // binary operators FAdd = 12 + Instruction, Sub = 13 + Instruction, FSub = 14 + Instruction, Mul = 15 + Instruction, FMul = 16 + Instruction, UDiv = 17 + Instruction, SDiv = 18 + Instruction, FDiv = 19 + Instruction, URem = 20 + Instruction, SRem = 21 + Instruction, FRem = 22 + Instruction, Shl = 23 + Instruction, // Logical Operators LShr = 24 + Instruction, AShr = 25 + Instruction, And = 26 + Instruction, Or = 27 + Instruction, Xor = 28 + Instruction, Alloca = 29 + Instruction, // Memory Operators Load = 30 + Instruction, Store = 31 + Instruction, GetElementPtr = 32 + Instruction, Fence = 33 + Instruction, AtomicCmpXchg = 34 + Instruction, AtomicRMW = 35 + Instruction, Trunc = 36 + Instruction, // cast/conversion operators ZeroExtend = 37 + Instruction, SignExtend = 38 + Instruction, FPToUI = 39 + Instruction, FPToSI = 40 + Instruction, UIToFP = 41 + Instruction, SIToFP = 42 + Instruction, FPTrunc = 43 + Instruction, FPExt = 44 + Instruction, PtrToInt = 45 + Instruction, IntToPtr = 46 + Instruction, BitCast = 47 + Instruction, AddrSpaceCast = 48 + Instruction, CleanupPad = 49 + Instruction, // New Exception pads CatchPad = 50 + Instruction, ICmp = 51 + Instruction, FCmp = 52 + Instruction, Phi = 53 + Instruction, Call = 54 + Instruction, Select = 55 + Instruction, UserOp1 = 56 + Instruction, UserOp2 = 57 + Instruction, VaArg = 58 + Instruction, ExtractElement = 59 + Instruction, InsertElement = 60 + Instruction, ShuffleVector = 61 + Instruction, ExtractValue = 62 + Instruction, InsertValue = 63 + Instruction, LandingPad = 64 + Instruction, // Markers: ConstantFirstVal = Function, ConstantLastVal = ConstantPointerNull } internal partial struct LLVMVersionInfo { public override string ToString() { if( VersionString == IntPtr.Zero ) return null; return Marshal.PtrToStringAnsi( VersionString ); } public static implicit operator Version( LLVMVersionInfo versionInfo ) { return new Version(versionInfo.Major, versionInfo.Minor, versionInfo.Patch); } } // add implicit conversions to/from C# bool for convenience internal partial struct LLVMBool { // sometimes LLVMBool values are actually success/failure codes // and thus a zero value actually means success and not false or failure. public bool Succeeded => Value == 0; public bool Failed => !Succeeded; public static implicit operator LLVMBool( bool value ) => new LLVMBool( value ? 1 : 0 ); public static implicit operator bool( LLVMBool value ) => value.Value != 0; } internal partial struct LLVMMetadataRef : IEquatable { internal static LLVMMetadataRef Zero = new LLVMMetadataRef( IntPtr.Zero ); public override int GetHashCode( ) => Pointer.GetHashCode( ); public override bool Equals( object obj ) { if( obj is LLVMMetadataRef ) return Equals( ( LLVMMetadataRef )obj ); if( obj is IntPtr ) return Pointer.Equals( obj ); return base.Equals( obj ); } public bool Equals( LLVMMetadataRef other ) => Pointer == other.Pointer; public static bool operator ==( LLVMMetadataRef lhs, LLVMMetadataRef rhs ) => lhs.Equals( rhs ); public static bool operator !=( LLVMMetadataRef lhs, LLVMMetadataRef rhs ) => !lhs.Equals( rhs ); } internal static partial class NativeMethods { internal static ValueKind GetValueKind( LLVMValueRef valueRef ) => ( ValueKind )GetValueID( valueRef ); static void FatalErrorHandler( string Reason ) { Trace.TraceError( Reason ); // LLVM will call exit() upon return from this function } /// This method is used to marshal a string when NativeMethods.DisposeMessage() is required on the string allocated from native code /// POinter to the native code allocated string /// Managed code string marshaled from the native content /// /// This method will, construct a new managed string containing the test of the string from native code, normalizing /// the line endings to the current execution environments line endings (See: ). /// internal static string MarshalMsg( IntPtr msg ) { var retVal = string.Empty; if( msg != IntPtr.Zero ) { try { retVal = NormalizeLineEndings( msg ); } finally { DisposeMessage( msg ); } } return retVal; } /// Static constructor for NativeMethods [System.Diagnostics.CodeAnalysis.SuppressMessage( "Microsoft.Design", "CA1065:DoNotRaiseExceptionsInUnexpectedLocations" )] [System.Diagnostics.CodeAnalysis.SuppressMessage( "Microsoft.Performance", "CA1810:InitializeReferenceTypeStaticFieldsInline" )] static NativeMethods() { // force loading the appropriate architecture specific // DLL before any use of the wrapped inter-op APIs to // allow building this library as ANYCPU var path = Path.GetDirectoryName( Assembly.GetExecutingAssembly( ).Location ); if( Directory.Exists( Path.Combine( path, "LibLLVM") ) ) { LoadWin32Library( libraryPath, "LibLLVM" ); } else { // fall-back to standard library search paths to allow building // CPU specific variants with only one native DLL without needing // conditional compilation on this library, which is useful for // unit testing or whenever the Nuget packaging isn't desired. LoadWin32Library( libraryPath, null ); } // initialize the static fields LineEndingNormalizingRegEx = new Regex( "(\r\n|\n\r|\r|\n)" ); LLVMVersionInfo versionInfo = new LLVMVersionInfo(); GetVersionInfo(ref versionInfo); if( versionInfo.Major != VersionMajor || versionInfo.Minor != VersionMinor || versionInfo.Patch != VersionPatch ) { throw new BadImageFormatException("Mismatched LibLLVM version"); } FatalErrorHandlerDelegate = new Lazy( ( ) => FatalErrorHandler, LazyThreadSafetyMode.PublicationOnly ); InstallFatalErrorHandler( FatalErrorHandlerDelegate.Value ); } // LLVM doesn't use environment/OS specific line endings, so this will // normalize the line endings from strings provided by LLVM into the current // environment's normal format. internal static string NormalizeLineEndings( IntPtr llvmString ) { if( llvmString == IntPtr.Zero ) return string.Empty; var str = Marshal.PtrToStringAnsi( llvmString ); return NormalizeLineEndings( str ); } internal static string NormalizeLineEndings( IntPtr llvmString, int len ) { if( llvmString == IntPtr.Zero || len == 0 ) return string.Empty; var str = Marshal.PtrToStringAnsi( llvmString, len ); return NormalizeLineEndings( str ); } private static string NormalizeLineEndings( string txt ) { // shortcut optimization for environments that match the LLVM assumption if( Environment.NewLine.Length == 1 && Environment.NewLine[ 0 ] == '\n' ) return txt; return LineEndingNormalizingRegEx.Replace( txt, Environment.NewLine ); } // lazy initialized singleton unmanaged delegate so it is never collected private static Lazy FatalErrorHandlerDelegate; private static readonly Regex LineEndingNormalizingRegEx; // version info for verification of matched LibLLVM private const int VersionMajor = 3; private const int VersionMinor = 8; private const int VersionPatch = 1; } } ================================================ FILE: Zelig/Zelig/CompileTime/Llvm.NET/Llvm.NET/LLVM/LlvmHandles.cs ================================================ using System; using System.Runtime.ConstrainedExecution; using System.Runtime.InteropServices; using System.Security; using System.Security.Permissions; namespace Llvm.NET.Native { internal static class IntPtrExtensions { public static bool IsNull( this IntPtr self ) => self == IntPtr.Zero; public static bool IsNull( this UIntPtr self ) => self == UIntPtr.Zero; } /// Base class for LLVM disposable types that are instantiated outside of an LLVM and therefore won't be disposed by the context [SecurityCritical] [SecurityPermission(SecurityAction.InheritanceDemand, UnmanagedCode = true)] internal abstract class SafeHandleNullIsInvalid : SafeHandle { [ReliabilityContract(Consistency.WillNotCorruptState, Cer.MayFail)] protected SafeHandleNullIsInvalid( bool ownsHandle) : base( IntPtr.Zero, ownsHandle ) { } public bool IsNull => handle.IsNull(); public override bool IsInvalid { [SecurityCritical] get { return IsNull; } } } [SecurityCritical] internal class AttributeBuilderHandle : SafeHandleNullIsInvalid { internal AttributeBuilderHandle() : base( true ) { } [System.Diagnostics.CodeAnalysis.SuppressMessage( "Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode", Justification = "Required for marshaling support (used via reflection)" )] internal AttributeBuilderHandle( IntPtr handle ) : base( true ) { SetHandle( handle ); } [SecurityCritical] protected override bool ReleaseHandle( ) { NativeMethods.AttributeBuilderDispose( this.handle ); return true; } } } ================================================ FILE: Zelig/Zelig/CompileTime/Llvm.NET/Llvm.NET/Llvm.NET.csproj ================================================  Debug x64 {0162C8CE-6641-4922-8664-F8A44356FBF7} Library Properties Llvm.NET Llvm.NET v4.5 512 true $(LlilumBuildRoot)\Host\bin\$(Configuration)\ DEBUG;TRACE full x64 prompt Llvm.NET.ruleset $(LlilumBuildRoot)\Host\bin\$(Configuration)\ true pdbonly x64 prompt Llvm.NET.ruleset true $(LlilumBuildRoot)\Host\bin\$(Configuration)\ DEBUG;TRACE full x86 prompt MinimumRecommendedRules.ruleset $(LlilumBuildRoot)\Host\bin\$(Configuration)\ true pdbonly x86 prompt MinimumRecommendedRules.ruleset true $(LlilumBuildRoot)\Host\bin\$(Configuration)\ DEBUG;TRACE full AnyCPU prompt Llvm.NET.ruleset $(LlilumBuildRoot)\Host\bin\$(Configuration)\ true pdbonly AnyCPU prompt Llvm.NET.ruleset {6c77a7de-d464-430f-96a9-a64768763b5f} LibLLVM false True ================================================ FILE: Zelig/Zelig/CompileTime/Llvm.NET/Llvm.NET/Llvm.NET.ruleset ================================================  ================================================ FILE: Zelig/Zelig/CompileTime/Llvm.NET/Llvm.NET/MemoryBuffer.cs ================================================ using System; using Llvm.NET.Native; namespace Llvm.NET { /// LLVM MemoryBuffer public sealed class MemoryBuffer : IDisposable { /// Load a file as an LLVM Memory Buffer /// Path of the file to load into a public MemoryBuffer( string path ) { IntPtr msg; if( NativeMethods.CreateMemoryBufferWithContentsOfFile( path, out BufferHandle_, out msg ).Succeeded ) return; throw new InternalCodeGeneratorException( NativeMethods.MarshalMsg( msg ) ); } /// Size of the buffer public int Size { get { if( BufferHandle.Pointer == IntPtr.Zero ) return 0; return NativeMethods.GetBufferSize( BufferHandle ); } } public void Dispose( ) { if( BufferHandle.Pointer != IntPtr.Zero ) { NativeMethods.DisposeMemoryBuffer( BufferHandle ); BufferHandle_ = default(LLVMMemoryBufferRef); } } internal LLVMMemoryBufferRef BufferHandle => BufferHandle_; // keep as a private field so this is usable as an out parameter in constructor private LLVMMemoryBufferRef BufferHandle_; } } ================================================ FILE: Zelig/Zelig/CompileTime/Llvm.NET/Llvm.NET/Metadata/ConstantAsMetadata.cs ================================================ using Llvm.NET.Native; namespace Llvm.NET { public class ConstantAsMetadata : ValueAsMetadata { internal ConstantAsMetadata( LLVMMetadataRef handle ) : base( handle ) { } } } ================================================ FILE: Zelig/Zelig/CompileTime/Llvm.NET/Llvm.NET/Metadata/LocalAsMetadata.cs ================================================ using Llvm.NET.Native; namespace Llvm.NET { public class LocalAsMetadata : ValueAsMetadata { internal LocalAsMetadata( LLVMMetadataRef handle ) : base( handle ) { } } } ================================================ FILE: Zelig/Zelig/CompileTime/Llvm.NET/Llvm.NET/Metadata/MDNode.cs ================================================ using System; using System.Collections.Generic; using Llvm.NET.Native; using Llvm.NET.Values; namespace Llvm.NET { public class MDNode : LlvmMetadata { internal MDNode( LLVMMetadataRef handle ) : base( handle ) { Operands = new MDNodeOperandList( this ); } public Context Context => Context.GetContextFor( MetadataHandle ); public bool IsDeleted => MetadataHandle == LLVMMetadataRef.Zero; public bool IsTemporary => NativeMethods.IsTemporary( MetadataHandle ); public bool IsResolved => NativeMethods.IsResolved( MetadataHandle ); public bool IsUniqued => NativeMethods.IsUniqued( MetadataHandle ); public bool IsDistinct => NativeMethods.IsDistinct( MetadataHandle ); public IReadOnlyList Operands { get; } public void ResolveCycles( ) => NativeMethods.MDNodeResolveCycles( MetadataHandle ); [System.Diagnostics.CodeAnalysis.SuppressMessage( "Microsoft.Naming", "CA2204:Literals should be spelled correctly", MessageId = "MDNode" )] public override void ReplaceAllUsesWith( LlvmMetadata other ) { if( other == null ) throw new ArgumentNullException( nameof( other ) ); if( !IsTemporary || IsResolved ) throw new InvalidOperationException( "Cannot replace non temporary or resolved MDNode" ); if( MetadataHandle.Pointer == IntPtr.Zero ) throw new InvalidOperationException( "Cannot Replace all uses of a null descriptor" ); NativeMethods.MDNodeReplaceAllUsesWith( MetadataHandle, other.MetadataHandle ); // remove current node mapping from the context. // It won't be valid for use after clearing the handle Context.RemoveDeletedNode( this ); MetadataHandle = LLVMMetadataRef.Zero; } internal static T FromHandle( LLVMMetadataRef handle ) where T : MDNode { if( handle.Pointer.IsNull( ) ) return null; var context = Context.GetContextFor( handle ); return FromHandle( context, handle ); } } } ================================================ FILE: Zelig/Zelig/CompileTime/Llvm.NET/Llvm.NET/Metadata/MDOperand.cs ================================================ using System; using Llvm.NET.Native; namespace Llvm.NET { public class MDOperand { public MDNode OwningNode { get; } public LlvmMetadata Metadata => LlvmMetadata.FromHandle( OwningNode.Context, NativeMethods.GetOperandNode( OperandHandle ) ); internal MDOperand( MDNode owningNode, LLVMMDOperandRef handle ) { if( handle.Pointer == IntPtr.Zero ) throw new ArgumentNullException( nameof( handle ) ); OperandHandle = handle; OwningNode = owningNode; } internal static MDOperand FromHandle( MDNode owningNode, LLVMMDOperandRef handle ) { return owningNode.Context.GetOperandFor( owningNode, handle ); } private readonly LLVMMDOperandRef OperandHandle; } } ================================================ FILE: Zelig/Zelig/CompileTime/Llvm.NET/Llvm.NET/Metadata/MDString.cs ================================================ using Llvm.NET.Native; namespace Llvm.NET { public class MDString : LlvmMetadata { internal MDString( LLVMMetadataRef handle ) : base( handle ) { } public override string ToString( ) { uint len; var ptr = NativeMethods.GetMDStringText( MetadataHandle, out len ); return NativeMethods.NormalizeLineEndings( ptr, ( int )len ); } } } ================================================ FILE: Zelig/Zelig/CompileTime/Llvm.NET/Llvm.NET/Metadata/MDTuple.cs ================================================ using Llvm.NET.Native; namespace Llvm.NET { public class MDTuple : MDNode { internal MDTuple( LLVMMetadataRef handle ) : base( handle ) { } } } ================================================ FILE: Zelig/Zelig/CompileTime/Llvm.NET/Llvm.NET/Metadata/Metadata.cs ================================================ using System; using Llvm.NET.DebugInfo; using Llvm.NET.Native; namespace Llvm.NET { /// Root of the LLVM Metadata hierarchy /// In LLVM this is just "Metadata" however that name has the potential /// to conflict with the .NET runtime namespace of the same name, so the name /// is changed in the .NET bindings to avoid the conflict. public abstract class LlvmMetadata { // ideally this would be protected + internal but C# // doesn't have any syntax to allow such a thing so it // is internal and internal code should ensure it is // only ever used by derived type constructors internal /*protected*/ LlvmMetadata( LLVMMetadataRef handle ) { if( handle == LLVMMetadataRef.Zero ) throw new ArgumentNullException( nameof( handle ) ); MetadataHandle = handle; } /// Replace all uses of this descriptor with another /// New descriptor to replace this one with public virtual void ReplaceAllUsesWith( LlvmMetadata other ) { if( other == null ) throw new ArgumentNullException( nameof( other ) ); if( MetadataHandle.Pointer == IntPtr.Zero ) throw new InvalidOperationException( "Cannot Replace all uses of a null descriptor" ); NativeMethods.MetadataReplaceAllUsesWith( MetadataHandle, other.MetadataHandle ); MetadataHandle = LLVMMetadataRef.Zero; } /// public override string ToString( ) { if( MetadataHandle.Pointer == IntPtr.Zero ) return string.Empty; return NativeMethods.MarshalMsg( NativeMethods.MetadataAsString( MetadataHandle ) ); } internal LLVMMetadataRef MetadataHandle { get; /*protected*/ set; } internal static T FromHandle( Context context, LLVMMetadataRef handle ) where T : LlvmMetadata { if( handle == LLVMMetadataRef.Zero ) return null; return ( T )context.GetNodeFor( handle, StaticFactory ); } /// Enumeration to define debug information metadata nodes private enum MetadataKind : uint { MDTuple, DILocation, GenericDINode, DISubrange, DIEnumerator, DIBasicType, DIDerivedType, DICompositeType, DISubroutineType, DIFile, DICompileUnit, DISubprogram, DILexicalBlock, DILexicalBlockFile, DINamespace, DIModule, DITemplateTypeParameter, DITemplateValueParameter, DIGlobalVariable, DILocalVariable, DIExpression, DIObjCProperty, DIImportedEntity, ConstantAsMetadata, LocalAsMetadata, MDString } [System.Diagnostics.CodeAnalysis.SuppressMessage( "Microsoft.Maintainability", "CA1506:AvoidExcessiveClassCoupling", Justification = "Static factory method" )] [System.Diagnostics.CodeAnalysis.SuppressMessage( "Microsoft.Maintainability", "CA1502:AvoidExcessiveComplexity", Justification = "Static factory method" )] private static LlvmMetadata StaticFactory( LLVMMetadataRef handle ) { // use the native kind value to determine the managed type // that should wrap this particular handle var kind = ( MetadataKind )NativeMethods.GetMetadataID( handle ); switch( kind ) { case MetadataKind.MDTuple: return new MDTuple( handle ); case MetadataKind.DILocation: return new DILocation( handle ); case MetadataKind.GenericDINode: return new GenericDINode( handle ); case MetadataKind.DISubrange: return new DISubRange( handle ); case MetadataKind.DIEnumerator: return new DIEnumerator( handle ); case MetadataKind.DIBasicType: return new DIBasicType( handle ); case MetadataKind.DIDerivedType: return new DIDerivedType( handle ); case MetadataKind.DICompositeType: return new DICompositeType( handle ); case MetadataKind.DISubroutineType: return new DISubroutineType( handle ); case MetadataKind.DIFile: return new DIFile( handle ); case MetadataKind.DICompileUnit: return new DICompileUnit( handle ); case MetadataKind.DISubprogram: return new DISubProgram( handle ); case MetadataKind.DILexicalBlock: return new DILexicalBlock( handle ); case MetadataKind.DILexicalBlockFile: return new DILexicalBlockFile( handle ); case MetadataKind.DINamespace: return new DINamespace( handle ); case MetadataKind.DIModule: return new DIModule( handle ); case MetadataKind.DITemplateTypeParameter: return new DITemplateTypeParameter( handle ); case MetadataKind.DITemplateValueParameter: return new DITemplateValueParameter( handle ); case MetadataKind.DIGlobalVariable: return new DIGlobalVariable( handle ); case MetadataKind.DILocalVariable: return new DILocalVariable( handle ); case MetadataKind.DIExpression: return new DIExpression( handle ); case MetadataKind.DIObjCProperty: return new DIObjCProperty( handle ); case MetadataKind.DIImportedEntity: return new DIImportedEntity( handle ); case MetadataKind.ConstantAsMetadata: return new ConstantAsMetadata( handle ); case MetadataKind.LocalAsMetadata: return new LocalAsMetadata( handle ); case MetadataKind.MDString: return new MDString( handle ); default: throw new NotImplementedException( ); } } } } ================================================ FILE: Zelig/Zelig/CompileTime/Llvm.NET/Llvm.NET/Metadata/MetadataAsValue.cs ================================================ using System; using Llvm.NET.Native; using Llvm.NET.Values; namespace Llvm.NET { public class MetadataAsValue : Value { internal MetadataAsValue( LLVMValueRef valueRef ) : base( valueRef ) { } internal static LLVMValueRef IsAMetadataAsValue( LLVMValueRef value ) { if( value.Pointer == IntPtr.Zero ) return value; return NativeMethods.GetValueKind( value ) == ValueKind.MetadataAsValue ? value : default( LLVMValueRef ); } //public static implicit operator Metadata( MetadataAsValue self ) //{ // // TODO: Add support to get the metadata ref from the value... // // e.g. call C++ MetadataAsValue.getMetadata() // throw new NotImplementedException(); //} } } ================================================ FILE: Zelig/Zelig/CompileTime/Llvm.NET/Llvm.NET/Metadata/NamedMDNode.cs ================================================ using System.Collections; using System.Collections.Generic; using Llvm.NET.Native; namespace Llvm.NET { /// Wraps an LLVM NamedMDNode /// Despite its name a NamedMDNode is not itself an MDNode. public class NamedMDNode { internal NamedMDNode( LLVMNamedMDNodeRef nativeNode ) { NativeHandle = nativeNode; Operands = new OperandIterator( this ); } // TODO: Enable retrieving the name from LibLLVM //public string Name { get; } public IReadOnlyList Operands { get; } public NativeModule ParentModule => NativeModule.FromHandle( NativeMethods.NamedMDNodeGetParentModule( NativeHandle ) ); private LLVMNamedMDNodeRef NativeHandle; // internal iterator for Metadata operands private class OperandIterator : IReadOnlyList { internal OperandIterator( NamedMDNode owner ) { OwningNode = owner; } public MDNode this[ int index ] { get { var nodeHanlde = NativeMethods.NamedMDNodeGetOperand( OwningNode.NativeHandle, (uint)index ); return LlvmMetadata.FromHandle( OwningNode.ParentModule.Context, nodeHanlde ); } } public int Count => (int)NativeMethods.NamedMDNodeGetNumOperands( OwningNode.NativeHandle ); public IEnumerator GetEnumerator( ) { for( int i = 0; i < Count; ++i ) yield return this[ i ]; } IEnumerator IEnumerable.GetEnumerator( ) { return GetEnumerator( ); } private NamedMDNode OwningNode; } } } ================================================ FILE: Zelig/Zelig/CompileTime/Llvm.NET/Llvm.NET/Metadata/ValueAsMetadata.cs ================================================ using Llvm.NET.Native; namespace Llvm.NET { public class ValueAsMetadata : LlvmMetadata { internal ValueAsMetadata( LLVMMetadataRef handle ) : base( handle ) { } } } ================================================ FILE: Zelig/Zelig/CompileTime/Llvm.NET/Llvm.NET/Module.cs ================================================ using System; using System.Collections.Generic; using System.Diagnostics; using System.IO; using Llvm.NET.DebugInfo; using Llvm.NET.Native; using Llvm.NET.Types; using Llvm.NET.Values; namespace Llvm.NET { /// LLVM Bit code module /// /// A module is the basic unit for containing code in LLVM. Modules are an in memory /// representation of the LLVM bit-code. /// public sealed class NativeModule : IDisposable , IExtensiblePropertyContainer { internal NativeModule( LLVMModuleRef handle ) { ModuleHandle = handle; DIBuilder_ = new Lazy( ( ) => new DebugInfoBuilder( this ) ); Context.AddModule( this ); } /// Creates an unnamed module without debug information public NativeModule( ) : this( string.Empty, null ) { } /// Creates a new module with the specified id in a new context /// Module's ID public NativeModule( string moduleId ) : this( moduleId, null ) { } /// Creates an named module in a given context /// Module's ID /// Context for the module [System.Diagnostics.CodeAnalysis.SuppressMessage( "Microsoft.Reliability", "CA2000:Dispose objects before losing scope" )] public NativeModule( string moduleId, Context context ) { if( moduleId == null ) moduleId = string.Empty; if( context == null ) { context = new Context( ); OwnsContext = true; } ModuleHandle = NativeMethods.ModuleCreateWithNameInContext( moduleId, context.ContextHandle ); if( ModuleHandle.Pointer == IntPtr.Zero ) throw new InternalCodeGeneratorException( "Could not create module in context" ); DIBuilder_ = new Lazy( ( ) => new DebugInfoBuilder( this ) ); Context.AddModule( this ); } /// Creates a named module with a root to contain debugging information /// Module name /// Language to store in the debugging information /// path of source file to set for the compilation unit /// Name of the application producing this module /// Flag to indicate if the module is optimized /// Additional flags /// Runtime version if any (use 0 if the runtime version has no meaning) public NativeModule( string moduleId , SourceLanguage language , string srcFilePath , string producer , bool optimized = false , string flags = "" , uint runtimeVersion = 0 ) : this( moduleId , null , language , srcFilePath , producer , optimized , flags , runtimeVersion ) { } /// Creates a named module with a root to contain debugging information /// Module name /// Context for the module /// Language to store in the debugging information /// path of source file to set for the compilation unit /// Name of the application producing this module /// Flag to indicate if the module is optimized /// Additional flags /// Runtime version if any (use 0 if the runtime version has no meaning) public NativeModule( string moduleId , Context context , SourceLanguage language , string srcFilePath , string producer , bool optimized = false , string compilationFlags = "" , uint runtimeVersion = 0 ) : this( moduleId, context ) { DICompileUnit = DIBuilder.CreateCompileUnit( language , srcFilePath , producer , optimized , compilationFlags , runtimeVersion ); } #region IDisposable Pattern public void Dispose( ) { Dispose( true ); GC.SuppressFinalize( this ); } ~NativeModule( ) { Dispose( false ); } void Dispose( bool disposing ) { // if not already disposed, dispose the module // Do this only on dispose. The containing context // will clean up the module when it is disposed or // finalized. Since finalization order isn't // deterministic it is possible that the module is // finalized after the context has already run its // finalizer, which would cause an access violation // in the native LLVM layer. if( disposing && ModuleHandle.Pointer != IntPtr.Zero ) { // if this module created the context then just dispose // the context as that will clean up the module as well. if( OwnsContext ) Context.Dispose( ); else NativeMethods.DisposeModule( ModuleHandle ); ModuleHandle = default( LLVMModuleRef ); } } #endregion /// Name of the Debug Version information module flag public const string DebugVersionValue = "Debug Info Version"; /// Name of the Dwarf Version module flag public const string DwarfVersionValue = "Dwarf Version"; /// Version of the Debug information Metadata public const UInt32 DebugMetadataVersion = 3; /* DEBUG_METADATA_VERSION (for LLVM v3.7.0) */ /// this module belongs to public Context Context { get { if( ModuleHandle.Pointer == IntPtr.Zero ) return null; return Context.GetContextFor( ModuleHandle ); } } /// to create debug information for this module public DebugInfoBuilder DIBuilder => DIBuilder_.Value; /// Debug Compile unit for this module public DICompileUnit DICompileUnit { get; internal set; } /// Data layout string /// /// Note the data layout string doesn't do what seems obvious. /// That is, it doesn't force the target back-end to generate code /// or types with a particular layout. Rather, the layout string has /// to match the implicit layout of the target. The layout string /// provides hints to the optimization passes about the target at /// the expense of making the bit code and front-end a bit target /// dependent. /// public string DataLayoutString { get { return Layout?.ToString( ) ?? string.Empty; } set { Layout = DataLayout.Parse( Context, value ); } } /// Target data layout for this module /// The layout is produced by parsing the /// therefore this property changes anytime the is /// set. Furthermore, setting this property will change the value of . /// In other words, Layout and are two different views /// of the same information and setting either one updates the other. /// public DataLayout Layout { get { return Layout_; } set { if( Layout_ != null ) Layout_.Dispose( ); Layout_ = value; NativeMethods.SetDataLayout( ModuleHandle, value?.ToString( ) ?? string.Empty ); } } private DataLayout Layout_; /// Target Triple describing the target, ABI and OS public string TargetTriple { get { var ptr = NativeMethods.GetTarget( ModuleHandle ); return NativeMethods.NormalizeLineEndings( ptr ); } set { NativeMethods.SetTarget( ModuleHandle, value ); } } /// Globals contained by this module public IEnumerable Globals { get { var current = NativeMethods.GetFirstGlobal( ModuleHandle ); while( current.Pointer != IntPtr.Zero ) { yield return Value.FromHandle( current ); current = NativeMethods.GetNextGlobal( current ); } } } /// Enumerable collection of functions contained in this module public IEnumerable Functions { get { var current = NativeMethods.GetFirstFunction( ModuleHandle ); while( current.Pointer != IntPtr.Zero ) { yield return Value.FromHandle( current ); current = NativeMethods.GetNextFunction( current ); } } } // TODO: Add enumerator for GlobalAlias(s) // TODO: Add enumerator for Comdat(s) // TODO: Add enumerator for NamedMDNode(s) /// Name of the module public string Name { get { var ptr = NativeMethods.GetModuleName( ModuleHandle ); return NativeMethods.NormalizeLineEndings( ptr ); } } /// Link another bit-code module into the current module /// Module to merge into this one /// Linker mode to use when merging public void Link( NativeModule otherModule, LinkerMode linkMode ) { if( otherModule == null ) throw new ArgumentNullException( nameof( otherModule ) ); IntPtr errMsgPtr; if( 0 != NativeMethods.LinkModules( ModuleHandle, otherModule.ModuleHandle, ( LLVMLinkerMode )linkMode, out errMsgPtr ).Value ) { var errMsg = NativeMethods.MarshalMsg( errMsgPtr ); throw new InternalCodeGeneratorException( errMsg ); } } /// Verifies a bit-code module /// Error messages describing any issues found in the bit-code /// true if the verification succeeded and false if not. public bool Verify( out string errmsg ) { errmsg = null; IntPtr msgPtr; LLVMBool result = NativeMethods.VerifyModule( ModuleHandle, LLVMVerifierFailureAction.LLVMReturnStatusAction, out msgPtr ); if( result.Succeeded ) return true; errmsg = NativeMethods.MarshalMsg( msgPtr ); return false; } /// Gets a function by name from this module /// Name of the function to get /// The function or null if not found public Function GetFunction( string name ) { var funcRef = NativeMethods.GetNamedFunction( ModuleHandle, name ); if( funcRef.Pointer == IntPtr.Zero ) return null; return Value.FromHandle( funcRef ); } /// Add a function with the specified signature to the module /// Name of the function to add /// Signature of the function /// matching the specified signature and name /// /// If a matching function already exists it is returned, and therefore the returned /// may have a body and additional attributes. If a function of /// the same name exists with a different signature an exception is thrown as LLVM does /// not perform any function overloading. /// [System.Diagnostics.CodeAnalysis.SuppressMessage( "Microsoft.Design", "CA1011:ConsiderPassingBaseTypesAsParameters", Justification = "Specific type required by interop call" )] public Function AddFunction( string name, IFunctionType signature ) { return Value.FromHandle( NativeMethods.GetOrInsertFunction( ModuleHandle, name, signature.GetTypeRef( ) ) ); } /// Writes a bit-code module to a file /// Path to write the bit-code into /// /// This is a blind write. (e.g. no verification is performed) /// So if an invalid module is saved it might not work with any /// later stage processing tools. /// public void WriteToFile( string path ) { var err = NativeMethods.WriteBitcodeToFile( ModuleHandle, path ); if( err < 0 ) throw new IOException( ); } /// Writes this module as LLVM IR source to a file /// File to write the LLVM IR source to /// Error messages encountered, if any /// if successful or if not public bool WriteToTextFile( string path, out string errMsg ) { errMsg = string.Empty; IntPtr msg; if( NativeMethods.PrintModuleToFile( ModuleHandle, path, out msg ) ) return true; errMsg = NativeMethods.MarshalMsg( msg ); return false; } /// Creates a string representation of the module /// LLVM textual representation of the module /// /// This is intentionally NOT an override of ToString() as that is /// used by debuggers to show the value of a type and this can take /// an extremely long time (up to many seconds depending on complexity /// of the module) which is bad for the debugger. /// public string AsString( ) { return NativeMethods.MarshalMsg( NativeMethods.PrintModuleToString( ModuleHandle ) ); } /// Add an alias to the module /// Value being aliased /// Name of the alias /// for the alias public GlobalAlias AddAlias( Value aliasee, string aliasName ) { if( aliasee == null ) throw new ArgumentNullException( nameof( aliasee ) ); var handle = NativeMethods.AddAlias( ModuleHandle, aliasee.NativeType.GetTypeRef( ), aliasee.ValueHandle, aliasName ); return Value.FromHandle( handle ); } /// Get an alias by name /// name of the alias to get /// Alias matching or null if no such alias exists public GlobalAlias GetAlias( string name ) { var handle = NativeMethods.GetGlobalAlias( ModuleHandle, name ); return Value.FromHandle( handle ); } /// Adds a global to this module /// Type of the global's value /// Name of the global /// The new /// /// - What does LLVM do if creating a second Global with the same name (return null, throw, crash??,...) /// public GlobalVariable AddGlobal( ITypeRef typeRef, string name ) { var handle = NativeMethods.AddGlobal( ModuleHandle, typeRef.GetTypeRef( ), name ); return Value.FromHandle( handle ); } /// Adds a global to this module /// Type of the global's value /// Flag to indicate if this global is a constant /// Linkage type for this global /// Initial value for the global /// New global variable public GlobalVariable AddGlobal( ITypeRef typeRef, bool isConst, Linkage linkage, Constant constVal ) { return AddGlobal( typeRef, isConst, linkage, constVal, string.Empty ); } /// Adds a global to this module /// Type of the global's value /// Flag to indicate if this global is a constant /// Linkage type for this global /// Initial value for the global /// Name of the variable /// New global variable public GlobalVariable AddGlobal( ITypeRef typeRef, bool isConst, Linkage linkage, Constant constVal, string name ) { var retVal = AddGlobal( typeRef, name ); retVal.IsConstant = isConst; retVal.Linkage = linkage; retVal.Initializer = constVal; return retVal; } /// Retrieves a by name from the module /// Name of the type /// The type or null if no type with the specified name exists in the module public ITypeRef GetTypeByName( string name ) { var hType = NativeMethods.GetTypeByName( ModuleHandle, name ); return hType.Pointer == IntPtr.Zero ? null : TypeRef.FromHandle( hType ); } /// Retrieves a named global from the module /// /// public GlobalVariable GetNamedGlobal( string name ) { var hGlobal = NativeMethods.GetNamedGlobal( ModuleHandle, name ); if( hGlobal.Pointer == IntPtr.Zero ) return null; return Value.FromHandle( hGlobal ); } /// Adds a module flag to the module /// Module flag behavior for this flag /// Name of the flag /// Value of the flag public void AddModuleFlag( ModuleFlagBehavior behavior, string name, UInt32 value ) { // AddModuleFlag comes from custom LLVMDebug-C API NativeMethods.AddModuleFlag( ModuleHandle, ( LLVMModFlagBehavior )behavior, name, value ); } /// Adds operand value to named metadata /// Name of the metadata /// operand value public void AddNamedMetadataOperand( string name, LlvmMetadata value ) { NativeMethods.AddNamedMetadataOperand2( ModuleHandle, name, value?.MetadataHandle ?? LLVMMetadataRef.Zero ); } /// Adds an llvm.ident metadata string to the module /// version information to place in the llvm.ident metadata public void AddVersionIdentMetadata( string version ) { var elements = new LLVMMetadataRef[ ] { NativeMethods.MDString2( Context.ContextHandle, version, ( uint )( version?.Length ?? 0 ) ) }; var hNode = NativeMethods.MDNode2( Context.ContextHandle, out elements[ 0 ], 1 ); NativeMethods.AddNamedMetadataOperand2( ModuleHandle, "llvm.ident", hNode ); } /// Creates a Function definition with Debug information /// Containing scope for the function /// Name of the function in source language form /// Mangled linker visible name of the function (may be same as if mangling not required by source language /// File containing the function definition /// Line number of the function definition /// LLVM Function type for the signature of the function /// Flag to indicate if this function is local to the compilation unit /// Flag to indicate if this is a definition /// First line of the function's outermost scope, this may not be the same as the first line of the function definition due to source formatting /// Additional flags describing this function /// Flag to indicate if this function is optimized /// /// /// Function described by the arguments public Function CreateFunction( DIScope scope , string name , string linkageName , DIFile file , uint line , DebugFunctionType signature , bool isLocalToUnit , bool isDefinition , uint scopeLine , DebugInfoFlags debugFlags , bool isOptimized , MDNode tParam = null , MDNode decl = null ) { if( scope == null ) throw new ArgumentNullException( nameof( scope ) ); if( string.IsNullOrWhiteSpace( name ) ) throw new ArgumentException( "Name cannot be null, empty or whitespace", nameof( name ) ); if( signature == null ) throw new ArgumentNullException( nameof( signature ) ); var func = AddFunction( linkageName ?? name, signature ); var diSignature = signature.DIType; Debug.Assert( diSignature != null ); var diFunc = DIBuilder.CreateFunction( scope: scope , name: name , mangledName: linkageName , file: file , line: line , signatureType: diSignature , isLocalToUnit: isLocalToUnit , isDefinition: isDefinition , scopeLine: scopeLine , debugFlags: debugFlags , isOptimized: isOptimized , function: func , typeParameter: tParam , declaration: decl ); Debug.Assert( diFunc.Describes( func ) ); func.DISubProgram = diFunc; return func; } public Function CreateFunction( string name , bool isVarArg , IDebugType returnType , params IDebugType[] argumentTypes ) { IFunctionType signature = Context.CreateFunctionType( DIBuilder, isVarArg, returnType, argumentTypes ); return AddFunction( name, signature ); } /// bool IExtensiblePropertyContainer.TryGetExtendedPropertyValue( string id, out T value ) { return PropertyBag.TryGetExtendedPropertyValue( id, out value ); } /// void IExtensiblePropertyContainer.AddExtendedPropertyValue( string id, object value ) { PropertyBag.AddExtendedPropertyValue( id, value ); } internal static NativeModule FromHandle( LLVMModuleRef nativeHandle ) { var context = Context.GetContextFor( nativeHandle ); return context.GetModuleFor( nativeHandle ); } /// Load a bit-code module from a given file /// path of the file to load /// Context to use for creating the module /// Loaded public static NativeModule LoadFrom( string path, Context context ) { if( string.IsNullOrWhiteSpace( path ) ) throw new ArgumentException( "path cannot be null or an empty string", nameof( path ) ); if( context == null ) throw new ArgumentNullException( nameof( context ) ); if( !File.Exists( path ) ) throw new FileNotFoundException( "Specified bit-code file does not exist", path ); using( var buffer = new MemoryBuffer( path ) ) { LLVMModuleRef modRef; IntPtr errMsgPtr; if( NativeMethods.ParseBitcodeInContext( context.ContextHandle, buffer.BufferHandle, out modRef, out errMsgPtr ).Failed ) { var errMsg = NativeMethods.MarshalMsg( errMsgPtr ); throw new InternalCodeGeneratorException( errMsg ); } return context.GetModuleFor( modRef ); } } internal LLVMModuleRef ModuleHandle { get; private set; } private readonly ExtensiblePropertyContainer PropertyBag = new ExtensiblePropertyContainer( ); private readonly Lazy DIBuilder_; private readonly bool OwnsContext; } } ================================================ FILE: Zelig/Zelig/CompileTime/Llvm.NET/Llvm.NET/NativeMethods.cs ================================================ using System; using System.ComponentModel; using System.IO; using System.Runtime.InteropServices; namespace Llvm.NET.Native { internal static partial class NativeMethods { /// Dynamically loads a DLL from a directory dependent on the current architecture /// name of the DLL /// Root path to find the DLL from /// Handle for the DLL /// /// This method will detect the architecture the code is executing on (i.e. x86 or x64) /// and will load the DLL from an architecture specific sub folder of . /// This allows use of AnyCPU builds and interop to simplify build processes from needing to /// deal with "mixed" configurations or other accidental combinations that are a pain to /// sort out and keep straight when the tools insist on creating AnyCPU projects and "mixed" configurations /// by default. /// If the Is , empty or all whitespace then /// the standard DLL search paths are used. This assumes the correct variant of the DLL is available /// (e.g. for a 32 bit system a 32 bit native DLL is found). This allows for either building as AnyCPU /// plus shipping multiple native DLLs, or building for a specific CPU type while shipping only one native /// DLL. Different products or projects may have different needs so this covers those cases. /// /// internal static IntPtr LoadWin32Library( string moduleName, string rootPath ) { if( string.IsNullOrWhiteSpace( moduleName ) ) throw new ArgumentNullException( nameof( moduleName ) ); string libPath; if( string.IsNullOrWhiteSpace( rootPath ) ) libPath = moduleName; else { if( Environment.Is64BitProcess ) libPath = Path.Combine( rootPath, "x64", moduleName ); else libPath = Path.Combine( rootPath, "x86", moduleName ); } IntPtr moduleHandle = LoadLibrary( libPath ); if( moduleHandle == IntPtr.Zero ) { var lasterror = Marshal.GetLastWin32Error( ); throw new Win32Exception( lasterror ); } return moduleHandle; } [DllImport("kernel32", SetLastError=true, BestFitMapping = false, ThrowOnUnmappableChar = true)] static extern IntPtr LoadLibrary([MarshalAs(UnmanagedType.LPStr)]string lpFileName); } } ================================================ FILE: Zelig/Zelig/CompileTime/Llvm.NET/Llvm.NET/PassManagerBuilder.cs ================================================ using System; using Llvm.NET.Native; namespace Llvm.NET { /// Provides a wrapper around an LLVM Pass Manager /// This class is still in the experimental stage as there is a lack of full support from the C API public sealed class PassManagerBuilder : IDisposable { public PassManagerBuilder( ) { PassManagerBuilderHandle = NativeMethods.PassManagerBuilderCreate( ); } public void SetOptLevel( uint optLevel ) { NativeMethods.PassManagerBuilderSetOptLevel( PassManagerBuilderHandle, optLevel ); } public void SetSizeLevel( uint sizeLevel ) { NativeMethods.PassManagerBuilderSetSizeLevel( PassManagerBuilderHandle, sizeLevel ); } public void SetDisableUnitAtATime( bool value ) { NativeMethods.PassManagerBuilderSetDisableUnitAtATime( PassManagerBuilderHandle, value ); } public void SetDisableUnrollLoops( bool value ) { NativeMethods.PassManagerBuilderSetDisableUnrollLoops( PassManagerBuilderHandle, value ); } public void SetDisableSimplifyLibCalls( bool value ) { NativeMethods.PassManagerBuilderSetDisableSimplifyLibCalls( PassManagerBuilderHandle, value ); } //public void PopulateFunctionPassManager( PassManager passManager ) //{ // LLVMNative.PassManagerBuilderPopulateFunctionPassManager( PassManagerBuilderHandle, passManager.PassManagerHandle ); //} //public void PopulateModulePassManager( PassManager passManager ) //{ // LLVMNative.PassManagerBuilderPopulateModulePassManager( PassManagerBuilderHandle, passManager.PassManagerHandle ); //} //public void PopulateLTOPassManager( PassManager passManager, bool internalize, bool runInliner ) //{ // LLVMNative.PassManagerBuilderPopulateLTOPassManager( PassManagerBuilderHandle // , passManager.PassManagerHandle // , internalize // , runInliner // ); //} public void Dispose( ) { if( PassManagerBuilderHandle.Pointer != IntPtr.Zero ) { NativeMethods.PassManagerBuilderDispose( PassManagerBuilderHandle ); PassManagerBuilderHandle = default( LLVMPassManagerBuilderRef ); } } LLVMPassManagerBuilderRef PassManagerBuilderHandle; } } ================================================ FILE: Zelig/Zelig/CompileTime/Llvm.NET/Llvm.NET/Properties/AssemblyInfo.cs ================================================ using System; using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; // General Information about an assembly is controlled through the following // set of attributes. Change these attribute values to modify the information // associated with an assembly. [assembly: AssemblyTitle("Llvm.NET")] [assembly: AssemblyDescription(".NET bindings for LLVM-C API libraries in LibLLVM dll")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("Microsoft .NET Foundation")] [assembly: AssemblyProduct("Llvm.NET")] [assembly: AssemblyCopyright("Copyright © 2015")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] [assembly: CLSCompliant( false )] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible(false)] // The following GUID is for the ID of the typelib if this project is exposed to COM [assembly: Guid("2bb51f2e-afcd-417a-b211-6bccd6da545d")] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Build and Revision Numbers // by using the '*' as shown below: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyFileVersion("1.0.0.0")] ================================================ FILE: Zelig/Zelig/CompileTime/Llvm.NET/Llvm.NET/ScalarEnumerable.cs ================================================ using System.Collections.Generic; namespace Llvm.NET { /// Static utility class for constructing enumerable sequences using single values public static class ScalarEnumerable { /// Create an enumerator that provides a single value /// Type of value to enumerate /// Value for the enumerator to provide /// Enumerable sequence containing a single value public static IEnumerable From( T scalar ) { yield return scalar; } /// Creates a new enumerable that prepends a value to an existing enumerable sequence /// Type of values to enumerate /// Value to prepend to the sequence /// Existing enumerable /// New enumerable sequence starting with public static IEnumerable Combine( T scalar, IEnumerable values ) { yield return scalar; foreach( T value in values ) yield return value; } /// Creates a new enumerable that appends a value to an existing enumerable sequence /// Type of values to enumerate /// Existing enumerable /// Value to append to the existing sequence /// New enumerable sequence ending with public static IEnumerable Combine( IEnumerable values, T scalar ) { foreach( T value in values ) yield return value; yield return scalar; } } } ================================================ FILE: Zelig/Zelig/CompileTime/Llvm.NET/Llvm.NET/StaticState.cs ================================================ using System; using Llvm.NET.Native; namespace Llvm.NET { /// Target tools to register/enable [Flags] public enum TargetRegistrations { /// Register nothing None = 0x00, /// Register the Target class Target = 0x01, /// Register the Target info for the target TargetInfo = 0x02, /// Register the target machine(s) for a target TargetMachine = 0x04, /// Registers the assembly source code generator for a target AsmPrinter = 0x08, /// Registers the Disassembler for a target Disassembler = 0x10, /// Registers the assembly source parser for a target AsmParser = 0x20, /// Registers all the code generation components CodeGen = Target | TargetInfo | TargetMachine, /// Registers all components All = CodeGen | AsmPrinter | Disassembler | AsmParser } /// Provides support for various LLVM static state initialization and manipulation public static class StaticState { public static void ParseCommandLineOptions( string[ ] args, string overview ) { if( args == null ) throw new ArgumentNullException( nameof( args ) ); NativeMethods.ParseCommandLineOptions( args.Length, args, overview ); } // basic pattern to follow for any new targets in the future //public static void RegisterXXX( TargetRegistrations registrations = TargetRegistration.All ) //{ // if( registrations.HasFlag( TargetRegistrations.Target ) ) // LLVMNative.InitializeXXXTarget( ); // if( registrations.HasFlag( TargetRegistrations.TargetInfo ) ) // LLVMNative.InitializeXXXTargetInfo( ); // if( registrations.HasFlag( TargetRegistrations.TargetMachine ) ) // LLVMNative.InitializeXXXTargetMC( ); // if( registrations.HasFlag( TargetRegistrations.AsmPrinter ) ) // LLVMNative.InitializeXXXAsmPrinter( ); // if( registrations.HasFlag( TargetRegistrations.Disassembler ) ) // LLVMNative.InitializeXXXDisassembler( ); // if( registrations.HasFlag( TargetRegistrations.AsmParser ) ) // LLVMNative.InitializeXXXAsmParser( ); //} /// Registers components for all available targets /// Flags indicating which components to register/enable public static void RegisterAll( TargetRegistrations registrations = TargetRegistrations.All ) { if( registrations.HasFlag( TargetRegistrations.Target ) ) NativeMethods.InitializeAllTargets( ); if( registrations.HasFlag( TargetRegistrations.TargetInfo ) ) NativeMethods.InitializeAllTargetInfos( ); if( registrations.HasFlag( TargetRegistrations.TargetMachine ) ) NativeMethods.InitializeAllTargetMCs( ); if( registrations.HasFlag( TargetRegistrations.AsmPrinter ) ) NativeMethods.InitializeAllAsmPrinters( ); if( registrations.HasFlag( TargetRegistrations.Disassembler ) ) NativeMethods.InitializeAllDisassemblers( ); if( registrations.HasFlag( TargetRegistrations.AsmParser ) ) NativeMethods.InitializeAllAsmParsers( ); } /// Registers components for the target representing the system the calling process is running on /// Flags indicating which components to register/enable public static void RegisterNative( TargetRegistrations registrations = TargetRegistrations.All ) { if( registrations.HasFlag( TargetRegistrations.Target ) ) NativeMethods.InitializeNativeTarget( ); //if( registrations.HasFlag( TargetRegistration.TargetInfo ) ) // LLVMNative.InitializeNativeTargetInfo( ); //if( registrations.HasFlag( TargetRegistration.TargetMachine ) ) // LLVMNative.InitializeNativeTargetMC( ); if( registrations.HasFlag( TargetRegistrations.AsmPrinter ) ) NativeMethods.InitializeNativeAsmPrinter( ); if( registrations.HasFlag( TargetRegistrations.Disassembler ) ) NativeMethods.InitializeNativeDisassembler( ); if( registrations.HasFlag( TargetRegistrations.AsmParser ) ) NativeMethods.InitializeNativeAsmParser( ); } /// Registers components for ARM AArch64 target(s) /// Flags indicating which components to register/enable public static void RegisterAArch64( TargetRegistrations registrations = TargetRegistrations.All ) { if( registrations.HasFlag( TargetRegistrations.Target ) ) NativeMethods.InitializeAArch64Target( ); if( registrations.HasFlag( TargetRegistrations.TargetInfo ) ) NativeMethods.InitializeAArch64TargetInfo( ); if( registrations.HasFlag( TargetRegistrations.TargetMachine ) ) NativeMethods.InitializeAArch64TargetMC( ); if( registrations.HasFlag( TargetRegistrations.AsmPrinter ) ) NativeMethods.InitializeAArch64AsmPrinter( ); if( registrations.HasFlag( TargetRegistrations.Disassembler ) ) NativeMethods.InitializeAArch64Disassembler( ); if( registrations.HasFlag( TargetRegistrations.AsmParser ) ) NativeMethods.InitializeAArch64AsmParser( ); } /// Registers components for ARM 32bit and 16bit thumb targets /// Flags indicating which components to register/enable public static void RegisterARM( TargetRegistrations registrations = TargetRegistrations.All ) { if( registrations.HasFlag( TargetRegistrations.Target ) ) NativeMethods.InitializeARMTarget( ); if( registrations.HasFlag( TargetRegistrations.TargetInfo ) ) NativeMethods.InitializeARMTargetInfo( ); if( registrations.HasFlag( TargetRegistrations.TargetMachine ) ) NativeMethods.InitializeARMTargetMC( ); if( registrations.HasFlag( TargetRegistrations.AsmPrinter ) ) NativeMethods.InitializeARMAsmPrinter( ); if( registrations.HasFlag( TargetRegistrations.Disassembler ) ) NativeMethods.InitializeARMDisassembler( ); if( registrations.HasFlag( TargetRegistrations.AsmParser ) ) NativeMethods.InitializeARMAsmParser( ); } /// Registers components for the Hexagon CPU /// Flags indicating which components to register/enable public static void RegisterHexagon( TargetRegistrations registrations = TargetRegistrations.All ) { if( registrations.HasFlag( TargetRegistrations.Target ) ) NativeMethods.InitializeHexagonTarget( ); if( registrations.HasFlag( TargetRegistrations.TargetInfo ) ) NativeMethods.InitializeHexagonTargetInfo( ); if( registrations.HasFlag( TargetRegistrations.TargetMachine ) ) NativeMethods.InitializeHexagonTargetMC( ); if( registrations.HasFlag( TargetRegistrations.AsmPrinter ) ) NativeMethods.InitializeHexagonAsmPrinter( ); if( registrations.HasFlag( TargetRegistrations.Disassembler ) ) NativeMethods.InitializeHexagonDisassembler( ); //if( registrations.HasFlag( TargetRegistration.AsmParser ) ) // LLVMNative.InitializeHexagonAsmParser( ); } /// Registers components for MIPS targets /// Flags indicating which components to register/enable public static void RegisterMips( TargetRegistrations registrations = TargetRegistrations.All ) { if( registrations.HasFlag( TargetRegistrations.Target ) ) NativeMethods.InitializeMipsTarget( ); if( registrations.HasFlag( TargetRegistrations.TargetInfo ) ) NativeMethods.InitializeMipsTargetInfo( ); if( registrations.HasFlag( TargetRegistrations.TargetMachine ) ) NativeMethods.InitializeMipsTargetMC( ); if( registrations.HasFlag( TargetRegistrations.AsmPrinter ) ) NativeMethods.InitializeMipsAsmPrinter( ); if( registrations.HasFlag( TargetRegistrations.Disassembler ) ) NativeMethods.InitializeMipsDisassembler( ); if( registrations.HasFlag( TargetRegistrations.AsmParser ) ) NativeMethods.InitializeMipsAsmParser( ); } /// Registers components for MSP430 targets /// Flags indicating which components to register/enable public static void RegisterMSP430( TargetRegistrations registrations = TargetRegistrations.All ) { if( registrations.HasFlag( TargetRegistrations.Target ) ) NativeMethods.InitializeMSP430Target( ); if( registrations.HasFlag( TargetRegistrations.TargetInfo ) ) NativeMethods.InitializeMSP430TargetInfo( ); if( registrations.HasFlag( TargetRegistrations.TargetMachine ) ) NativeMethods.InitializeMSP430TargetMC( ); if( registrations.HasFlag( TargetRegistrations.AsmPrinter ) ) NativeMethods.InitializeMSP430AsmPrinter( ); //if( registrations.HasFlag( TargetRegistration.Disassembler ) ) // LLVMNative.InitializeMSP430Disassembler( ); //if( registrations.HasFlag( TargetRegistration.AsmParser ) ) // LLVMNative.InitializeMSP430AsmParser( ); } /// Registers components for the NVPTX targets /// Flags indicating which components to register/enable public static void RegisterNVPTX( TargetRegistrations registrations = TargetRegistrations.All ) { if( registrations.HasFlag( TargetRegistrations.Target ) ) NativeMethods.InitializeNVPTXTarget( ); if( registrations.HasFlag( TargetRegistrations.TargetInfo ) ) NativeMethods.InitializeNVPTXTargetInfo( ); if( registrations.HasFlag( TargetRegistrations.TargetMachine ) ) NativeMethods.InitializeNVPTXTargetMC( ); if( registrations.HasFlag( TargetRegistrations.AsmPrinter ) ) NativeMethods.InitializeNVPTXAsmPrinter( ); //if( registrations.HasFlag( TargetRegistration.Disassembler ) ) // LLVMNative.InitializeNVPTXDisassembler( ); //if( registrations.HasFlag( TargetRegistration.AsmParser ) ) // LLVMNative.InitializeNVPTXAsmParser( ); } /// Registers components for the PowerPC targets /// Flags indicating which components to register/enable public static void RegisterPowerPC( TargetRegistrations registrations = TargetRegistrations.All ) { if( registrations.HasFlag( TargetRegistrations.Target ) ) NativeMethods.InitializePowerPCTarget( ); if( registrations.HasFlag( TargetRegistrations.TargetInfo ) ) NativeMethods.InitializePowerPCTargetInfo( ); if( registrations.HasFlag( TargetRegistrations.TargetMachine ) ) NativeMethods.InitializePowerPCTargetMC( ); if( registrations.HasFlag( TargetRegistrations.AsmPrinter ) ) NativeMethods.InitializePowerPCAsmPrinter( ); if( registrations.HasFlag( TargetRegistrations.Disassembler ) ) NativeMethods.InitializePowerPCDisassembler( ); if( registrations.HasFlag( TargetRegistrations.AsmParser ) ) NativeMethods.InitializePowerPCAsmParser( ); } /// Registers components for AMDGPU targets /// Flags indicating which components to register/enable public static void RegisterAMDGPU( TargetRegistrations registrations = TargetRegistrations.All ) { if( registrations.HasFlag( TargetRegistrations.Target ) ) NativeMethods.InitializeAMDGPUTarget( ); if( registrations.HasFlag( TargetRegistrations.TargetInfo ) ) NativeMethods.InitializeAMDGPUTargetInfo( ); if( registrations.HasFlag( TargetRegistrations.TargetMachine ) ) NativeMethods.InitializeAMDGPUTargetMC( ); if( registrations.HasFlag( TargetRegistrations.AsmPrinter ) ) NativeMethods.InitializeAMDGPUAsmPrinter( ); //if( registrations.HasFlag( TargetRegistration.Disassembler ) ) // LLVMNative.InitializeAMDGPUDisassembler( ); if( registrations.HasFlag( TargetRegistrations.AsmParser ) ) NativeMethods.InitializeAMDGPUAsmParser( ); } /// Registers components for SPARC targets /// Flags indicating which components to register/enable public static void RegisterSparc( TargetRegistrations registrations = TargetRegistrations.All ) { if( registrations.HasFlag( TargetRegistrations.Target ) ) NativeMethods.InitializeSparcTarget( ); if( registrations.HasFlag( TargetRegistrations.TargetInfo ) ) NativeMethods.InitializeSparcTargetInfo( ); if( registrations.HasFlag( TargetRegistrations.TargetMachine ) ) NativeMethods.InitializeSparcTargetMC( ); if( registrations.HasFlag( TargetRegistrations.AsmPrinter ) ) NativeMethods.InitializeSparcAsmPrinter( ); if( registrations.HasFlag( TargetRegistrations.Disassembler ) ) NativeMethods.InitializeSparcDisassembler( ); if( registrations.HasFlag( TargetRegistrations.AsmParser ) ) NativeMethods.InitializeSparcAsmParser( ); } /// Registers components for SystemZ targets /// Flags indicating which components to register/enable public static void RegisterSystemZ( TargetRegistrations registrations = TargetRegistrations.All ) { if( registrations.HasFlag( TargetRegistrations.Target ) ) NativeMethods.InitializeSystemZTarget( ); if( registrations.HasFlag( TargetRegistrations.TargetInfo ) ) NativeMethods.InitializeSystemZTargetInfo( ); if( registrations.HasFlag( TargetRegistrations.TargetMachine ) ) NativeMethods.InitializeSystemZTargetMC( ); if( registrations.HasFlag( TargetRegistrations.AsmPrinter ) ) NativeMethods.InitializeSystemZAsmPrinter( ); if( registrations.HasFlag( TargetRegistrations.Disassembler ) ) NativeMethods.InitializeSystemZDisassembler( ); if( registrations.HasFlag( TargetRegistrations.AsmParser ) ) NativeMethods.InitializeSystemZAsmParser( ); } /// Registers components for X86 targets /// Flags indicating which components to register/enable public static void RegisterX86( TargetRegistrations registrations = TargetRegistrations.All ) { if( registrations.HasFlag( TargetRegistrations.Target ) ) NativeMethods.InitializeX86Target( ); if( registrations.HasFlag( TargetRegistrations.TargetInfo ) ) NativeMethods.InitializeX86TargetInfo( ); if( registrations.HasFlag( TargetRegistrations.TargetMachine ) ) NativeMethods.InitializeX86TargetMC( ); if( registrations.HasFlag( TargetRegistrations.AsmPrinter ) ) NativeMethods.InitializeX86AsmPrinter( ); if( registrations.HasFlag( TargetRegistrations.Disassembler ) ) NativeMethods.InitializeX86Disassembler( ); if( registrations.HasFlag( TargetRegistrations.AsmParser ) ) NativeMethods.InitializeX86AsmParser( ); } /// Registers components for XCore targets /// Flags indicating which components to register/enable public static void RegisterXCore( TargetRegistrations registrations = TargetRegistrations.All ) { if( registrations.HasFlag( TargetRegistrations.Target ) ) NativeMethods.InitializeXCoreTarget( ); if( registrations.HasFlag( TargetRegistrations.TargetInfo ) ) NativeMethods.InitializeXCoreTargetInfo( ); if( registrations.HasFlag( TargetRegistrations.TargetMachine ) ) NativeMethods.InitializeXCoreTargetMC( ); if( registrations.HasFlag( TargetRegistrations.AsmPrinter ) ) NativeMethods.InitializeXCoreAsmPrinter( ); if( registrations.HasFlag( TargetRegistrations.Disassembler ) ) NativeMethods.InitializeXCoreDisassembler( ); //if( registrations.HasFlag( TargetRegistration.AsmParser ) ) // LLVMNative.InitializeXCoreAsmParser( ); } } } ================================================ FILE: Zelig/Zelig/CompileTime/Llvm.NET/Llvm.NET/Target.cs ================================================ using System; using System.Collections.Generic; using System.Runtime.InteropServices; using Llvm.NET.Native; namespace Llvm.NET { /// LLVM Target Instruction Set Architecture public class Target { // TODO: add constants for all the known "triple" values public const string UnknownEabiTriple = "UnknownArch-none-eabi"; public const string ThumbV7mEabiTriple = "thumbv7m-none-eabi"; public const string Win32EabiTriple = "x86_64-pc-windows-msvc"; /// Name of this target public string Name => Marshal.PtrToStringAnsi( NativeMethods.GetTargetName( TargetHandle ) ); /// Description of this target public string Description => NativeMethods.NormalizeLineEndings( NativeMethods.GetTargetDescription( TargetHandle ) ); /// Flag indicating if this target has JIT support public bool HasJIT => 0 != NativeMethods.TargetHasJIT( TargetHandle ).Value; /// Flag indicating if this target has a TargetMachine initialized public bool HasTargetMachine => 0 != NativeMethods.TargetHasTargetMachine( TargetHandle ).Value; /// Flag indicating if this target has an Assembly code generating back end initialized public bool HasAsmBackEnd => 0 != NativeMethods.TargetHasAsmBackend( TargetHandle ).Value; /// Creates a for the target and specified parameters /// Context to use for LLVM objects created by this machine /// Target triple for this machine (e.g. -mtriple) /// CPU for this machine (e.g. -mcpu) /// Features for this machine (e.g. -mattr...) /// Optimization level /// Relocation mode for generated code /// to use for generated code /// based on the specified parameters public TargetMachine CreateTargetMachine( Context context , string triple , string cpu , string features , CodeGenOpt optLevel , Reloc relocationMode , CodeModel codeModel ) { var targetMachineHandle = NativeMethods.CreateTargetMachine( TargetHandle , triple , cpu , features , ( LLVMCodeGenOptLevel )optLevel , ( LLVMRelocMode )relocationMode , ( LLVMCodeModel )codeModel ); return new TargetMachine( context, targetMachineHandle ); } /// Retrieves an enumerable collection of the available targets built into this library public static IEnumerable AvailableTargets { get { var current = NativeMethods.GetFirstTarget( ); while( current.Pointer != IntPtr.Zero ) { yield return FromHandle( current ); current = NativeMethods.GetNextTarget( current ); } } } /// Gets the target for a given target "triple" value /// Target triple string describing the target /// Target for the given triple public static Target FromTriple( string targetTriple ) { LLVMTargetRef targetHandle; IntPtr msgPtr; if( 0 != NativeMethods.GetTargetFromTriple( targetTriple, out targetHandle, out msgPtr ).Value ) { var msg = NativeMethods.MarshalMsg( msgPtr ); throw new InternalCodeGeneratorException( msg ); } return FromHandle( targetHandle ); } internal Target( LLVMTargetRef targetHandle ) { TargetHandle = targetHandle; } internal LLVMTargetRef TargetHandle { get; } internal static Target FromHandle( LLVMTargetRef targetHandle ) { lock( TargetMap ) { Target retVal; if( TargetMap.TryGetValue( targetHandle.Pointer, out retVal ) ) return retVal; retVal = new Target( targetHandle ); TargetMap.Add( targetHandle.Pointer, retVal ); return retVal; } } static Dictionary TargetMap = new Dictionary( ); } } ================================================ FILE: Zelig/Zelig/CompileTime/Llvm.NET/Llvm.NET/TargetMachine.cs ================================================ using System; using Llvm.NET.Native; namespace Llvm.NET { /// Target specific code generation information public class TargetMachine : IDisposable { /// Retrieves the Target that owns this public Target Target => Target.FromHandle( NativeMethods.GetTargetMachineTarget( TargetMachineHandle ) ); /// Target triple describing this machine public string Triple => NativeMethods.MarshalMsg( NativeMethods.GetTargetMachineTriple( TargetMachineHandle ) ); /// CPU Type for this machine public string Cpu => NativeMethods.MarshalMsg( NativeMethods.GetTargetMachineCPU( TargetMachineHandle ) ); /// CPU specific features for this machine public string Features => NativeMethods.MarshalMsg( NativeMethods.GetTargetMachineFeatureString( TargetMachineHandle ) ); /// Layout information for this machine /// /// This property is currently planned for removal in LLVM v4.0. /// Though it is unclear what the replacement will be as there is no other way to get /// the layout information if it isn't already known. /// public DataLayout TargetData { get { var handle = NativeMethods.GetTargetMachineData( TargetMachineHandle ); if( handle.Pointer == IntPtr.Zero ) return null; return DataLayout.FromHandle( Context, handle, isDisposable: false ); } } /// Generate code for the target machine from a module /// to generate the code from /// Path to the output file /// Type of file to emit public void EmitToFile( NativeModule module, string path, CodeGenFileType fileType ) { if( module == null ) throw new ArgumentNullException( nameof( module ) ); if( string.IsNullOrWhiteSpace( path ) ) throw new ArgumentException( "Null or empty paths ar not valid", nameof( path ) ); if( module.TargetTriple != null && Triple != module.TargetTriple ) throw new ArgumentException( "Triple specifed for the module doesn't match target machine", nameof( module ) ); IntPtr errMsg; if( 0 != NativeMethods.TargetMachineEmitToFile( TargetMachineHandle, module.ModuleHandle, path, (LLVMCodeGenFileType)fileType, out errMsg ).Value ) { var errTxt = NativeMethods.MarshalMsg( errMsg ); throw new InternalCodeGeneratorException( errTxt ); } } public Context Context { get; } internal TargetMachine( Context context, LLVMTargetMachineRef targetMachineHandle ) { TargetMachineHandle = targetMachineHandle; Context = context; } #region IDisposable Support private bool IsDisposed => TargetMachineHandle.Pointer == IntPtr.Zero; protected virtual void Dispose( bool disposing ) { if( !IsDisposed ) { // no managed state to dispose here //if( disposing ) //{ // // dispose managed state (managed objects). //} NativeMethods.DisposeTargetMachine( TargetMachineHandle ); TargetMachineHandle = default( LLVMTargetMachineRef ); } } ~TargetMachine( ) { // Do not change this code. Put cleanup code in Dispose(bool disposing) above. Dispose( false ); } // This code added to correctly implement the disposable pattern. public void Dispose( ) { // Do not change this code. Put cleanup code in Dispose(bool disposing) above. Dispose( true ); GC.SuppressFinalize(this); } #endregion internal LLVMTargetMachineRef TargetMachineHandle { get; private set; } } } ================================================ FILE: Zelig/Zelig/CompileTime/Llvm.NET/Llvm.NET/Types/ArrayType.cs ================================================ using System; using Llvm.NET.Native; namespace Llvm.NET.Types { /// Interface for an LLVM array type public interface IArrayType : ISequenceType { /// Length of the array uint Length { get; } } /// Array type definition /// /// Array's in LLVM are fixed length sequences of elements /// internal class ArrayType : SequenceType , IArrayType { /// Length of the array public uint Length => NativeMethods.GetArrayLength( TypeHandle_ ); internal ArrayType( LLVMTypeRef typeRef ) : base( typeRef ) { if( NativeMethods.GetTypeKind( typeRef ) != LLVMTypeKind.LLVMArrayTypeKind ) throw new ArgumentException( "Array type reference expected", nameof( typeRef ) ); } } } ================================================ FILE: Zelig/Zelig/CompileTime/Llvm.NET/Llvm.NET/Types/FunctionType.cs ================================================ using System.Collections.Generic; using System.Linq; using Llvm.NET.Native; namespace Llvm.NET.Types { /// Interface to represent the LLVM type of a function (e.g. a signature) public interface IFunctionType : ITypeRef { /// Flag to indicate if this signature is for a variadic function bool IsVarArg { get; } /// Return type of the function ITypeRef ReturnType { get; } /// Collection of types of the parameters for the function IReadOnlyList ParameterTypes { get; } } /// Class to represent the LLVM type of a function (e.g. a signature) internal class FunctionType : TypeRef , IFunctionType { internal FunctionType( LLVMTypeRef typeRef ) : base( typeRef ) { } /// public bool IsVarArg => NativeMethods.IsFunctionVarArg( TypeHandle_ ); /// public ITypeRef ReturnType => FromHandle( NativeMethods.GetReturnType( TypeHandle_ ) ); /// public IReadOnlyList ParameterTypes { get { var paramCount = NativeMethods.CountParamTypes( TypeHandle_ ); if( paramCount == 0 ) return new List().AsReadOnly(); var paramTypes = new LLVMTypeRef[ paramCount ]; NativeMethods.GetParamTypes( TypeHandle_, out paramTypes[ 0 ] ); return paramTypes.Select( FromHandle ) .ToList( ) .AsReadOnly( ); } } } } ================================================ FILE: Zelig/Zelig/CompileTime/Llvm.NET/Llvm.NET/Types/ITypeRef.cs ================================================ using Llvm.NET.Values; using System; using Llvm.NET.Native; namespace Llvm.NET.Types { /// Interface for a Type in LLVM public interface ITypeRef : IExtensiblePropertyContainer { /// LibLLVM handle for the type IntPtr TypeHandle { get; } /// Flag to indicate if the type is sized bool IsSized { get; } /// LLVM Type kind for this type TypeKind Kind { get; } /// Flag to indicate if this type is an integer bool IsInteger { get; } // Return true if value is 'float', a 32-bit IEEE floating point type. bool IsFloat { get; } // Return true if this is 'double', a 64-bit IEEE floating point type bool IsDouble { get; } /// Flag to indicate if this type represents the void type bool IsVoid { get; } /// Flag to indicate if this type is a structure type bool IsStruct { get; } /// Flag to indicate if this type is a pointer bool IsPointer { get; } /// Flag to indicate if this type is a sequence type bool IsSequence { get; } /// Flag to indicate if this type is a floating point type bool IsFloatingPoint { get; } /// FLag to indicate if this type is a pointer to a pointer bool IsPointerPointer { get; } /// Context that owns this type Context Context { get; } /// Integer bit width of this type or 0 for non integer types [System.Diagnostics.CodeAnalysis.SuppressMessage( "Microsoft.Naming", "CA1720:IdentifiersShouldNotContainTypeNames", MessageId = "integer" )] uint IntegerBitWidth { get; } /// Gets a null value (e.g. all bits == 0 ) for the type /// /// This is a getter function instead of a property as it can throw exceptions /// for types that don't support such a thing (i.e. void ) /// [System.Diagnostics.CodeAnalysis.SuppressMessage( "Microsoft.Design", "CA1024:UsePropertiesWhereAppropriate" )] Constant GetNullValue( ); /// Array type factory for an array with elements of this type /// Number of elements in the array /// for the array IArrayType CreateArrayType( uint count ); /// Get a for a type that points to elements of this type in the default (0) address space /// corresponding to the type of a pointer that refers to elements of this type IPointerType CreatePointerType( ); /// Get a for a type that points to elements of this type in the specified address space /// Address space for the pointer /// corresponding to the type of a pointer that refers to elements of this type IPointerType CreatePointerType( uint addressSpace ); } internal static class TypeRefExtensions { internal static LLVMTypeRef GetTypeRef( this ITypeRef self ) => new LLVMTypeRef( self.TypeHandle ); } } ================================================ FILE: Zelig/Zelig/CompileTime/Llvm.NET/Llvm.NET/Types/PointerType.cs ================================================ using System; using Llvm.NET.Native; namespace Llvm.NET.Types { /// Interface for a pointer type in LLVM public interface IPointerType : ISequenceType { /// Address space the pointer refers to uint AddressSpace { get; } } /// LLVM pointer type internal class PointerType : SequenceType , IPointerType { /// Address space the pointer refers to public uint AddressSpace => NativeMethods.GetPointerAddressSpace( TypeHandle_ ); internal PointerType( LLVMTypeRef typeRef ) : base( typeRef ) { if( NativeMethods.GetTypeKind( typeRef ) != LLVMTypeKind.LLVMPointerTypeKind ) throw new ArgumentException( "Pointer type reference expected", nameof( typeRef ) ); } } } ================================================ FILE: Zelig/Zelig/CompileTime/Llvm.NET/Llvm.NET/Types/SequenceType.cs ================================================ using System; using Llvm.NET.Native; namespace Llvm.NET.Types { /// Interface for an LLVM sequence type /// /// Sequence types represent a sequence of elements of the same type /// that are contiguous in memory. These include Vectors, Arrays, and /// pointers. /// public interface ISequenceType : ITypeRef { /// Type of elements in the sequence ITypeRef ElementType { get; } } internal class SequenceType : TypeRef , ISequenceType { public ITypeRef ElementType { get { var typeRef = NativeMethods.GetElementType( this.GetTypeRef() ); if( typeRef.Pointer == IntPtr.Zero ) return null; return FromHandle( typeRef ); } } internal SequenceType( LLVMTypeRef typeRef ) : base( typeRef ) { if( !IsSequenceTypeRef( typeRef ) ) throw new ArgumentException( "Expected a sequence type", nameof( typeRef ) ); } internal static bool IsSequenceTypeRef( LLVMTypeRef typeRef ) { var kind = ( TypeKind )NativeMethods.GetTypeKind( typeRef ); return kind == TypeKind.Array || kind == TypeKind.Vector || kind == TypeKind.Pointer; } } } ================================================ FILE: Zelig/Zelig/CompileTime/Llvm.NET/Llvm.NET/Types/StructType.cs ================================================ using System.Collections.Generic; using System.Linq; using System.Runtime.InteropServices; using Llvm.NET.Native; namespace Llvm.NET.Types { /// Interface for an LLVM structure type public interface IStructType : ITypeRef { /// Name of the structure string Name { get; } /// Indicates if the structure is opaque (e.g. has no body defined yet) bool IsOpaque { get; } /// Indicates if the structure is packed (e.g. no automatic alignment padding between elements) bool IsPacked { get; } /// List of types for all member elements of the structure IReadOnlyList Members { get; } /// Sets the body of the structure /// Flag to indicate if the body elements are packed (e.g. no padding) /// Optional types of each element /// /// To set the body , at least one element type is required. If none are provided this is a NOP. /// void SetBody( bool packed, params ITypeRef[ ] elements ); } internal class StructType : TypeRef , IStructType { public void SetBody( bool packed, params ITypeRef[ ] elements ) { LLVMTypeRef[ ] llvmArgs = elements.Select( e => e.GetTypeRef() ).ToArray( ); uint argsLength = (uint)llvmArgs.Length; // To interop correctly, we need to have an array of at least size one. if ( argsLength == 0 ) llvmArgs = new LLVMTypeRef[ 1 ]; NativeMethods.StructSetBody( TypeHandle_, out llvmArgs[ 0 ], argsLength, packed ); } public string Name { get { var ptr = NativeMethods.GetStructName( TypeHandle_ ); return Marshal.PtrToStringAnsi( ptr ); } } public bool IsOpaque => NativeMethods.IsOpaqueStruct( TypeHandle_ ); public bool IsPacked => NativeMethods.IsPackedStruct( TypeHandle_ ); public IReadOnlyList Members { get { var members = new List( ); if( Kind == TypeKind.Struct && !IsOpaque ) { uint count = NativeMethods.CountStructElementTypes( TypeHandle_ ); if (count > 0) { LLVMTypeRef[] structElements = new LLVMTypeRef[ count ]; NativeMethods.GetStructElementTypes( TypeHandle_, out structElements[ 0 ] ); members.AddRange( structElements.Select( h => FromHandle( h ) ) ); } } return members; } } internal StructType( LLVMTypeRef typeRef ) : base( typeRef ) { } } } ================================================ FILE: Zelig/Zelig/CompileTime/Llvm.NET/Llvm.NET/Types/TypeRef.cs ================================================ using System; using Llvm.NET.Native; using Llvm.NET.Values; namespace Llvm.NET.Types { /// LLVM Type internal class TypeRef : ITypeRef { public IntPtr TypeHandle => TypeHandle_.Pointer; /// Flag to indicate if the type is sized public bool IsSized { get { if( Kind == TypeKind.Function ) return false; return NativeMethods.TypeIsSized( TypeHandle_ ); } } /// LLVM Type kind for this type public TypeKind Kind => ( TypeKind )NativeMethods.GetTypeKind( TypeHandle_ ); public bool IsInteger=> Kind == TypeKind.Integer; // Return true if value is 'float', a 32-bit IEEE fp type. public bool IsFloat => Kind == TypeKind.Float32; // Return true if this is 'double', a 64-bit IEEE fp type public bool IsDouble => Kind == TypeKind.Float64; public bool IsVoid => Kind == TypeKind.Void; public bool IsStruct => Kind == TypeKind.Struct; public bool IsPointer => Kind == TypeKind.Pointer; /// Flag to indicate if the type is a sequence type public bool IsSequence => Kind == TypeKind.Array || Kind == TypeKind.Vector || Kind == TypeKind.Pointer; public bool IsFloatingPoint { get { switch( Kind ) { case TypeKind.Float16: case TypeKind.Float32: case TypeKind.Float64: case TypeKind.X86Float80: case TypeKind.Float128m112: case TypeKind.Float128: return true; default: return false; } } } public bool IsPointerPointer { get { var ptrType = this as IPointerType; return ptrType != null && ptrType.ElementType.Kind == TypeKind.Pointer; } } /// Context that owns this type public Context Context => Context.GetContextFor( TypeHandle_ ); /// Integer bid width of this type or 0 for non integer types public uint IntegerBitWidth { get { if( Kind != TypeKind.Integer ) return 0; return NativeMethods.GetIntTypeWidth( TypeHandle_ ); } } /// Gets a null value (e.g. all bits = 0 ) for the type /// This is a getter function instead of a property as it can throw exceptions public Constant GetNullValue() => Constant.NullValueFor( this ); /// Retrieves an expression that results in the size of the type [Obsolete("Use TargetData layout information to compute size and create a constant from that")] public Constant GetSizeOfExpression( int pointerSize ) { if( !IsSized || Kind == TypeKind.Void || Kind == TypeKind.Function || ( Kind == TypeKind.Struct && ( NativeMethods.IsOpaqueStruct( TypeHandle_ ) ) ) ) { return Context.CreateConstant( 0 ); } var hSize = NativeMethods.SizeOf( TypeHandle_ ); // LLVM uses an expression to construct Sizeof, however it is hard coded to // use an i64 as the type for the size, which isn't valid for 32 bit systems var sizeOfBitWidth = NativeMethods.GetIntTypeWidth( NativeMethods.TypeOf( hSize ) ); var hIntPtr = new LLVMTypeRef( Context.GetIntType( ( uint )pointerSize ).TypeHandle ); if( sizeOfBitWidth > pointerSize ) hSize = NativeMethods.ConstTrunc( hSize, hIntPtr ); else if( sizeOfBitWidth < pointerSize ) hSize = NativeMethods.ConstZExt( hSize, hIntPtr ); return Value.FromHandle( hSize ); } /// Array type factory for an array with elements of this type /// Number of elements in the array /// for the array public IArrayType CreateArrayType( uint count ) => FromHandle( NativeMethods.ArrayType( TypeHandle_, count ) ); /// Get a for a type that points to elements of this type in the default (0) address space /// corresponding to the type of a pointer that referns to elements of this type public IPointerType CreatePointerType( ) => CreatePointerType( 0 ); /// Get a for a type that points to elements of this type in the specified address space /// Address space for the pointer /// corresponding to the type of a pointer that referns to elements of this type public IPointerType CreatePointerType( uint addressSpace ) { if( IsVoid ) throw new InvalidOperationException( "Cannot create pointer to void in LLVM, use i8* instead" ); return FromHandle( NativeMethods.PointerType( TypeHandle_, addressSpace ) ); } public bool TryGetExtendedPropertyValue( string id, out T value ) => ExtensibleProperties.TryGetExtendedPropertyValue( id, out value ); public void AddExtendedPropertyValue( string id, object value ) => ExtensibleProperties.AddExtendedPropertyValue( id, value ); /// Builds a string representation for this type in LLVM assembly language form /// Formatted string for this type public override string ToString( ) { var msgString = NativeMethods.PrintTypeToString( TypeHandle_ ); return NativeMethods.MarshalMsg( msgString ); } internal TypeRef( LLVMTypeRef typeRef ) { TypeHandle_ = typeRef; if( typeRef.Pointer == IntPtr.Zero ) throw new ArgumentNullException( nameof( typeRef ) ); #if DEBUG var ctx = Llvm.NET.Context.GetContextFor( typeRef ); ctx.AssertTypeNotInterned( typeRef ); #endif } internal static TypeRef FromHandle( LLVMTypeRef typeRef ) => FromHandle( typeRef ); internal static T FromHandle( LLVMTypeRef typeRef ) where T : class, ITypeRef { if( typeRef.Pointer == IntPtr.Zero ) return null; var ctx = Context.GetContextFor( typeRef ); return ( T )ctx.GetTypeFor( typeRef, StaticFactory ); } private static ITypeRef StaticFactory( LLVMTypeRef typeRef ) { var kind = (TypeKind)NativeMethods.GetTypeKind( typeRef ); switch( kind ) { case TypeKind.Struct: return new StructType( typeRef ); case TypeKind.Array: return new ArrayType( typeRef ); case TypeKind.Pointer: return new PointerType( typeRef ); case TypeKind.Vector: return new VectorType( typeRef ); case TypeKind.Function: // NOTE: This is a signature rather than a Function, which is a Value return new FunctionType( typeRef ); // other types not yet supported in Object wrappers // but the pattern for doing so should be pretty obvious... case TypeKind.Void: case TypeKind.Float16: case TypeKind.Float32: case TypeKind.Float64: case TypeKind.X86Float80: case TypeKind.Float128m112: case TypeKind.Float128: case TypeKind.Label: case TypeKind.Integer: case TypeKind.Metadata: case TypeKind.X86MMX: default: return new TypeRef( typeRef ); } } internal readonly LLVMTypeRef TypeHandle_; private readonly ExtensiblePropertyContainer ExtensibleProperties = new ExtensiblePropertyContainer( ); } } ================================================ FILE: Zelig/Zelig/CompileTime/Llvm.NET/Llvm.NET/Types/VectorType.cs ================================================ using System; using Llvm.NET.Native; namespace Llvm.NET.Types { public interface IVectorType : ISequenceType { uint Size { get; } } internal class VectorType : SequenceType , IVectorType { public uint Size => NativeMethods.GetVectorSize( TypeHandle_ ); internal VectorType( LLVMTypeRef typeRef ) : base( typeRef ) { if( NativeMethods.GetTypeKind( typeRef ) != LLVMTypeKind.LLVMVectorTypeKind ) throw new ArgumentException( "Vector type reference expected", nameof( typeRef ) ); } } } ================================================ FILE: Zelig/Zelig/CompileTime/Llvm.NET/Llvm.NET/Values/Argument.cs ================================================ using System; using System.Collections.Generic; using Llvm.NET.Native; namespace Llvm.NET.Values { /// An LLVM Value representing an Argument to a function public class Argument : Value , IAttributeSetContainer { /// Function this argument belongs to public Function ContainingFunction => FromHandle( NativeMethods.GetParamParent( ValueHandle ) ); /// Zero based index of the argument public uint Index => NativeMethods.GetArgumentIndex( ValueHandle ); /// Sets the alignment for the argument /// Alignment value for this argument public Argument SetAlignment( uint value ) { ContainingFunction.AddAttribute( FunctionAttributeIndex.Parameter0 + ( int ) Index , new AttributeValue( Context, AttributeKind.Alignment, value ) ); return this; } /// Attributes for this parameter public AttributeSet Attributes { get { return ContainingFunction.Attributes.ParameterAttributes( ( int )Index ); } set { ContainingFunction.AddAttributes( FunctionAttributeIndex.Parameter0 + ( int )Index, value ); } } internal Argument( LLVMValueRef valueRef ) : base( valueRef ) { } } } ================================================ FILE: Zelig/Zelig/CompileTime/Llvm.NET/Llvm.NET/Values/AttributeBuilder.cs ================================================ using System; using Llvm.NET.Native; namespace Llvm.NET.Values { /// Factory for building AttributeSets, which are otherwise immutable public sealed class AttributeBuilder : IDisposable { public AttributeBuilder() { BuilderHandle = NativeMethods.CreateAttributeBuilder( ); } public AttributeBuilder( AttributeValue value ) { BuilderHandle = NativeMethods.CreateAttributeBuilder2( value.NativeAttribute ); } public AttributeBuilder( AttributeSet attributes, FunctionAttributeIndex index ) { BuilderHandle = NativeMethods.CreateAttributeBuilder3( attributes.NativeAttributeSet, ( uint )index ); } public void Dispose( ) { BuilderHandle.Dispose( ); } public AttributeBuilder Add( AttributeKind kind ) { if( BuilderHandle.IsClosed ) throw new ObjectDisposedException( nameof( AttributeBuilder ) ); if( kind.RequiresIntValue( ) ) throw new ArgumentException( "Attribute requires a value" ); NativeMethods.AttributeBuilderAddEnum( BuilderHandle, ( LLVMAttrKind )kind ); return this; } public AttributeBuilder Add( AttributeValue value ) { if( BuilderHandle.IsClosed ) throw new ObjectDisposedException( nameof( AttributeBuilder ) ); NativeMethods.AttributeBuilderAddAttribute( BuilderHandle, value.NativeAttribute ); return this; } public AttributeBuilder Add( string name ) { if( BuilderHandle.IsClosed ) throw new ObjectDisposedException( nameof( AttributeBuilder ) ); return Add( name, string.Empty ); } public AttributeBuilder Add( string name, string value ) { if( BuilderHandle.IsClosed ) throw new ObjectDisposedException( nameof( AttributeBuilder ) ); NativeMethods.AttributeBuilderAddStringAttribute( BuilderHandle, name, value ); return this; } public AttributeBuilder Remove( AttributeKind kind ) { if( BuilderHandle.IsClosed ) throw new ObjectDisposedException( nameof( AttributeBuilder ) ); NativeMethods.AttributeBuilderRemoveEnum( BuilderHandle, ( LLVMAttrKind )kind ); return this; } public AttributeBuilder Remove( AttributeSet attributes, FunctionAttributeIndex index ) { if( BuilderHandle.IsClosed ) throw new ObjectDisposedException( nameof( AttributeBuilder ) ); NativeMethods.AttributeBuilderRemoveAttributes( BuilderHandle, attributes.NativeAttributeSet, (uint)index ); return this; } public AttributeBuilder Remove( string name ) { if( BuilderHandle.IsClosed ) throw new ObjectDisposedException( nameof( AttributeBuilder ) ); NativeMethods.AttributeBuilderRemoveAttribute( BuilderHandle, name ); return this; } public AttributeBuilder Merge( AttributeBuilder other ) { if(other == null) throw new ArgumentNullException( nameof( other ) ); if( BuilderHandle.IsClosed ) throw new ObjectDisposedException( nameof( AttributeBuilder ) ); NativeMethods.AttributeBuilderMerge( BuilderHandle, other.BuilderHandle ); return this; } public AttributeBuilder Remove( AttributeBuilder other ) { if(other == null) throw new ArgumentNullException( nameof( other ) ); if( BuilderHandle.IsClosed ) throw new ObjectDisposedException( nameof( AttributeBuilder ) ); NativeMethods.AttributeBuilderRemoveBldr( BuilderHandle, other.BuilderHandle ); return this; } public bool Overlaps( AttributeBuilder other ) { if(other == null) throw new ArgumentNullException( nameof( other ) ); if( BuilderHandle.IsClosed ) throw new ObjectDisposedException( nameof( AttributeBuilder ) ); return NativeMethods.AttributeBuilderOverlaps( BuilderHandle, other.BuilderHandle ); } public bool Contains( AttributeKind kind ) { if( BuilderHandle.IsClosed ) throw new ObjectDisposedException( nameof( AttributeBuilder ) ); return NativeMethods.AttributeBuilderContainsEnum( BuilderHandle, ( LLVMAttrKind )kind ); } public bool Contains( string name ) { if( BuilderHandle.IsClosed ) throw new ObjectDisposedException( nameof( AttributeBuilder ) ); return NativeMethods.AttributeBuilderContainsName( BuilderHandle, name ); } public bool HasAnyAttributes => BuilderHandle.IsClosed ? false : (bool)NativeMethods.AttributeBuilderHasAnyAttributes( BuilderHandle ); public bool HasAttributes( AttributeSet attributes, FunctionAttributeIndex index ) { if( BuilderHandle.IsClosed ) throw new ObjectDisposedException( nameof( AttributeBuilder ) ); return NativeMethods.AttributeBuilderHasAttributes( BuilderHandle, attributes.NativeAttributeSet, ( uint )index ); } public bool IsEmpty { get { if( BuilderHandle.IsClosed ) return true; // don't throw an exception in a property getter method return !NativeMethods.AttributeBuilderHasTargetDependentAttrs( BuilderHandle ) && !NativeMethods.AttributeBuilderHasTargetIndependentAttrs( BuilderHandle ); } } public AttributeSet ToAttributeSet( FunctionAttributeIndex index ) => ToAttributeSet( index, Context.CurrentContext ); public AttributeSet ToAttributeSet( FunctionAttributeIndex index, Context context ) { if( BuilderHandle.IsClosed ) throw new ObjectDisposedException( nameof( AttributeBuilder ) ); return new AttributeSet( context, index, this ); } internal AttributeBuilderHandle BuilderHandle; } } ================================================ FILE: Zelig/Zelig/CompileTime/Llvm.NET/Llvm.NET/Values/AttributeKindExtensions.cs ================================================ using System; using System.Diagnostics; namespace Llvm.NET.Values { /// Enumeration flags to indicate which attribute set index an attribute may apply to [Flags] public enum FunctionIndexKinds { /// Invalid attributes don't apply to any index None = 0, /// The attribute is applicable to a function Function = 1, /// The attribute is applicable to a function's return Return = 2, /// The attribute is applicable to a function's parameter Parameter = 4 } /// Utility class to provide extension methods for validating usage of attribute kinds public static class AttributeKindExtensions { public static bool RequiresIntValue( this AttributeKind kind ) { Debug.Assert( kind >= AttributeKind.None && kind < AttributeKind.EndAttrKinds ); switch( kind ) { case AttributeKind.Alignment: case AttributeKind.StackAlignment: case AttributeKind.Dereferenceable: case AttributeKind.DereferenceableOrNull: return true; default: return false; } } public static bool CheckAttributeUsage( this AttributeKind kind, FunctionAttributeIndex index, Function function ) { Debug.Assert( kind >= AttributeKind.None && kind < AttributeKind.EndAttrKinds ); FunctionIndexKinds allowedindices = kind.GetAllowedIndexes( ); switch( index ) { case FunctionAttributeIndex.Function: if( !allowedindices.HasFlag( FunctionIndexKinds.Function ) ) return false; break; case FunctionAttributeIndex.ReturnType: if( !allowedindices.HasFlag( FunctionIndexKinds.Return ) ) return false; break; //case FunctionAttributeIndex.Parameter0: default: if(function == null) throw new ArgumentNullException( nameof( function ) ); if( !allowedindices.HasFlag( FunctionIndexKinds.Parameter ) ) return false; var paramIndex = index - FunctionAttributeIndex.Parameter0; if( paramIndex >= function.Parameters.Count ) return false; break; } return true; } public static void VerifyAttributeUsage( this AttributeKind kind, FunctionAttributeIndex index ) { Debug.Assert( kind >= AttributeKind.None && kind < AttributeKind.EndAttrKinds ); FunctionIndexKinds allowedindices = kind.GetAllowedIndexes( ); switch( index ) { case FunctionAttributeIndex.Function: if( !allowedindices.HasFlag( FunctionIndexKinds.Function ) ) throw new ArgumentException( "Attribute not allowed on functions", nameof( index ) ); break; case FunctionAttributeIndex.ReturnType: if( !allowedindices.HasFlag( FunctionIndexKinds.Return ) ) throw new ArgumentException( "Attribute not allowed on function Return", nameof( index ) ); break; //case FunctionAttributeIndex.Parameter0: default: if( !allowedindices.HasFlag( FunctionIndexKinds.Parameter ) ) throw new ArgumentException( "Attribute not allowed on function parameter", nameof( index ) ); break; } } // To prevent native asserts or crashes - validates parameters before passing down to native code public static void VerifyIntAttributeUsage( this AttributeKind kind, FunctionAttributeIndex index, ulong value ) { kind.VerifyAttributeUsage( index ); kind.RangeCheckValue( value ); } public static void RangeCheckValue( this AttributeKind kind, ulong value ) { Debug.Assert( kind >= AttributeKind.None && kind < AttributeKind.EndAttrKinds ); // To prevent native asserts or crashes - validate parameters before passing down to native code switch( kind ) { case AttributeKind.Alignment: if( value > UInt32.MaxValue ) throw new ArgumentOutOfRangeException( nameof( value ), "Expected a 32 bit value for alignment" ); break; case AttributeKind.StackAlignment: if( value > UInt32.MaxValue ) throw new ArgumentOutOfRangeException( nameof( value ), "Expected a 32 bit value for stack alignment" ); break; case AttributeKind.Dereferenceable: case AttributeKind.DereferenceableOrNull: break; default: throw new ArgumentException( $"Attribute '{kind}' does not support an argument", nameof( kind ) ); } } public static FunctionIndexKinds GetAllowedIndexes( this AttributeKind kind ) { Debug.Assert( kind >= AttributeKind.None && kind < AttributeKind.EndAttrKinds ); switch( kind ) { default: return FunctionIndexKinds.None; case AttributeKind.ZExt: case AttributeKind.SExt: case AttributeKind.InReg: case AttributeKind.ByVal: case AttributeKind.InAlloca: case AttributeKind.StructRet: case AttributeKind.Alignment: case AttributeKind.NoAlias: case AttributeKind.NoCapture: case AttributeKind.Nest: case AttributeKind.Returned: case AttributeKind.NonNull: case AttributeKind.Dereferenceable: case AttributeKind.DereferenceableOrNull: return FunctionIndexKinds.Parameter | FunctionIndexKinds.Return; case AttributeKind.StackAlignment: case AttributeKind.AlwaysInline: case AttributeKind.Builtin: case AttributeKind.Cold: case AttributeKind.Convergent: case AttributeKind.InlineHint: case AttributeKind.JumpTable: case AttributeKind.MinSize: case AttributeKind.Naked: case AttributeKind.NoBuiltin: case AttributeKind.NoDuplicate: case AttributeKind.NoImplicitFloat: case AttributeKind.NoInline: case AttributeKind.NonLazyBind: case AttributeKind.NoRedZone: case AttributeKind.NoReturn: //case AttributeKind.NoRecurse: // ver > 3.7.0? case AttributeKind.NoUnwind: case AttributeKind.OptimizeForSize: case AttributeKind.OptimizeNone: case AttributeKind.ReadNone: case AttributeKind.ReadOnly: case AttributeKind.ArgMemOnly: case AttributeKind.ReturnsTwice: case AttributeKind.SafeStack: case AttributeKind.SanitizeAddress: case AttributeKind.SanitizeMemory: case AttributeKind.SanitizeThread: case AttributeKind.StackProtect: case AttributeKind.StackProtectReq: case AttributeKind.StackProtectStrong: case AttributeKind.UWTable: return FunctionIndexKinds.Function; } } } } ================================================ FILE: Zelig/Zelig/CompileTime/Llvm.NET/Llvm.NET/Values/AttributeSet.cs ================================================ using System; using System.Collections.Generic; using System.Diagnostics; using System.Linq; using System.Text; using Llvm.NET.Native; namespace Llvm.NET.Values { /// AttributeSet for a , , or instruction /// /// The underlying LLVM AttributeSet class is an immutable value type, unfortunately it includes a non-default constructor /// and therefore isn't a POD. However, it is trivially copy constructible and standard layout so this class simply wraps /// the LLVM AttributeSet class. All data allocated for an AttributeSet is owned by a , which /// will handle cleaning it up on . /// [System.Diagnostics.CodeAnalysis.SuppressMessage( "Microsoft.Design", "CA1049:TypesThatOwnNativeResourcesShouldBeDisposable", Justification = "LLVM Context owns the attribute set" )] public struct AttributeSet : IEquatable { public AttributeSet( Context context, FunctionAttributeIndex index, AttributeBuilder builder ) { if( context == null ) throw new ArgumentNullException( nameof( context ) ); if( builder == null ) throw new ArgumentNullException( nameof( builder ) ); context.VerifyAsArg( nameof( context ) ); NativeAttributeSet = NativeMethods.CreateAttributeSetFromBuilder( context.ContextHandle, ( uint )index, builder.BuilderHandle ); } #region IEquatable public override int GetHashCode( ) => NativeAttributeSet.GetHashCode( ); public override bool Equals( object obj ) { if( ReferenceEquals( this, obj ) ) return true; if( obj is AttributeSet ) return Equals( ( LLVMMetadataRef )obj ); if( obj is UIntPtr ) return NativeAttributeSet.Equals( obj ); return false; } public bool Equals( AttributeSet other ) => NativeAttributeSet == other.NativeAttributeSet; public static bool operator ==( AttributeSet left, AttributeSet right ) => left.Equals( right ); public static bool operator !=( AttributeSet left, AttributeSet right ) => !left.Equals( right ); #endregion /// Context used to intern this /// /// The Context returned will be if this is empty. /// This ensures that there is always a context available for creating new AttributeSets /// public Context Context { get { if( NativeAttributeSet.IsNull( ) ) return Context.CurrentContext; return Context.GetContextFor( NativeMethods.AttributeSetGetContext( NativeAttributeSet ) ); } } /// Retrieves an attributeSet filtered by the specified function index /// Index to filter on /// A new with attributes from this set belonging to the specified index public AttributeSet this[ FunctionAttributeIndex index ] { get { // explicitly check Context so that getter method doesn't throw an exception if( Context == null || Context.IsDisposed || !HasAny( index ) ) return new AttributeSet( ); return new AttributeSet( NativeMethods.AttributeGetAttributes( NativeAttributeSet, ( uint )index ) ); } } /// Enumerates the values that have attributes associated in this public IEnumerable Indexes { get { // explicitly check Context so that getter method doesn't throw an exception if( Context == null || Context.IsDisposed ) yield break; var numIndices = NativeMethods.AttributeSetGetNumSlots( NativeAttributeSet ); for( uint i = 0; i < numIndices; ++i ) yield return ( FunctionAttributeIndex )NativeMethods.AttributeSetGetSlotIndex( NativeAttributeSet, i ); } } /// Gets the attributes for the function return public AttributeSet ReturnAttributes => this[ FunctionAttributeIndex.ReturnType ]; /// Gets the attributes for the function itself public AttributeSet FunctionAttributes => this[ FunctionAttributeIndex.Function ]; /// Gets the attributes for a function parameter /// Parameter index [ 0 based ] /// filtered for the specified parameter [System.Diagnostics.CodeAnalysis.SuppressMessage( "Microsoft.Naming", "CA2204:Literals should be spelled correctly", MessageId = "AttributeSet" )] public AttributeSet ParameterAttributes( int parameterIndex ) { Context.VerifyOperation( ); // prevent overflow on offset addition below if( parameterIndex > int.MaxValue - ( int )FunctionAttributeIndex.Parameter0 ) throw new ArgumentOutOfRangeException( nameof( parameterIndex ) ); var index = FunctionAttributeIndex.Parameter0 + parameterIndex; return new AttributeSet( NativeMethods.AttributeGetAttributes( NativeAttributeSet, ( uint )index ) ); } /// Get LLVM formatted string representation of this for a given index /// Index to get the string for /// Formatted string for the specified attribute index public string AsString( FunctionAttributeIndex index ) { Context.VerifyOperation( ); var msgPtr = NativeMethods.AttributeSetToString( NativeAttributeSet, ( uint )index, false ); return NativeMethods.MarshalMsg( msgPtr ); } public IEnumerable AllAttributes { get { var numSlots = NativeMethods.AttributeSetGetNumSlots( NativeAttributeSet ); for( uint slot = 0; slot < numSlots; ++slot ) { var index = ( FunctionAttributeIndex )NativeMethods.AttributeSetGetSlotIndex( NativeAttributeSet, slot ); UIntPtr token = NativeMethods.AttributeSetGetIteratorStartToken( NativeAttributeSet, slot ); UIntPtr attr = UIntPtr.Zero; do { attr = NativeMethods.AttributeSetIteratorGetNext( NativeAttributeSet, slot, ref token ); if( attr == UIntPtr.Zero ) break; yield return new IndexedAttributeValue( index, new AttributeValue( attr ) ); } while( attr != UIntPtr.Zero ); } } } /// Creates a formatted string representation of the entire (e.g. all indices) /// Formatted string representation of the public override string ToString( ) { Context.VerifyOperation( ); var bldr = new StringBuilder( ); var indexGroups = from attribute in AllAttributes group attribute.Value.ToString( ) by attribute.Index; foreach( var group in indexGroups ) { var values = string.Join( ", ", group ); if( group.Key < FunctionAttributeIndex.Parameter0 ) bldr.AppendFormat( "[{0}: {1}]", group.Key, values ); else bldr.AppendFormat( "[Parameter{0}: {1}]", group.Key - FunctionAttributeIndex.Parameter0, values ); } return bldr.ToString( ); } /// Adds a set of attributes /// Index for the attribute /// Attributes to add public AttributeSet Add( FunctionAttributeIndex index, params AttributeValue[ ] attributes ) { return Add( index, ( IEnumerable )attributes ); } /// Produces a new that includes the attributes from this set along with additional attributes provided /// to use for the new attributes /// Collection of attributes to add /// Newly created with the new attributes added public AttributeSet Add( FunctionAttributeIndex index, IEnumerable attributes ) { if( attributes == null ) throw new ArgumentNullException( nameof( attributes ) ); Context.VerifyOperation( ); using( var bldr = new AttributeBuilder( ) ) { foreach( var attribute in attributes ) bldr.Add( attribute ); return Add( index, bldr.ToAttributeSet( index, Context ) ); } } /// Adds a single attribute /// Index for the attribute /// kind to add public AttributeSet Add( FunctionAttributeIndex index, AttributeValue attribute ) { Context.VerifyOperation( ); using( var bldr = new AttributeBuilder( ) ) { bldr.Add( attribute ); return Add( index, bldr.ToAttributeSet( index, Context ) ); } } /// Adds Attributes from another attribute set along a given index /// Index to add attributes to and from /// to add the attributes from /// New Containing all attributes of this set plus any /// attributes from along the specified public AttributeSet Add( FunctionAttributeIndex index, AttributeSet attributes ) { Context.VerifyOperation( ); var nativeSet = NativeMethods.AttributeSetAddAttributes( NativeAttributeSet, Context.ContextHandle, ( uint )index, attributes.NativeAttributeSet ); return new AttributeSet( nativeSet ); } /// Removes the specified attribute from the attribute set public AttributeSet Remove( FunctionAttributeIndex index, AttributeKind kind ) { Context.VerifyOperation( ); var nativeSet = NativeMethods.AttributeSetRemoveAttributeKind( NativeAttributeSet, ( uint )index, ( LLVMAttrKind )kind ); return new AttributeSet( nativeSet ); } public AttributeSet Remove( FunctionAttributeIndex index, AttributeBuilder builder ) { if( builder == null ) throw new ArgumentNullException( nameof( builder ) ); Context.VerifyOperation( ); var nativeSet = NativeMethods.AttributeSetRemoveAttributeBuilder( NativeAttributeSet, Context.ContextHandle, ( uint )index, builder.BuilderHandle ); return new AttributeSet( nativeSet ); } /// Remove a target specific attribute /// Index for the attribute /// Name of the attribute public AttributeSet Remove( FunctionAttributeIndex index, string name ) { Context.VerifyOperation( ); using( var bldr = new AttributeBuilder( ) ) { bldr.Add( name ); return Remove( index, bldr ); } } /// Get an integer value for an index /// Index to get the value from /// to get the value of (see remarks for supported attributes) /// Value of the attribute /// /// The only attributes supporting an integer value are , /// , , /// . /// public UInt64 GetAttributeValue( FunctionAttributeIndex index, AttributeKind kind ) { Context.VerifyOperation( ); kind.VerifyIntAttributeUsage( index, 0 ); var value = new AttributeValue( NativeMethods.AttributeSetGetAttributeByKind( NativeAttributeSet, ( uint )index, ( LLVMAttrKind )kind ) ); Debug.Assert( value.IntegerValue.HasValue ); return value.IntegerValue.Value; } /// Tests if an has any attributes in the specified index /// Index for the attribute public bool HasAny( FunctionAttributeIndex index ) { Context.VerifyOperation( ); return NativeMethods.AttributeSetHasAttributes( NativeAttributeSet, ( uint )index ); } /// Tests if this attribute set has a given AttributeValue kind /// Index for the attribute /// Kind of AttributeValue to test for /// true if the AttributeValue exists or false if not public bool Has( FunctionAttributeIndex index, AttributeKind kind ) { Context.VerifyOperation( ); return NativeMethods.AttributeSetHasAttributeKind( NativeAttributeSet, ( uint )index, ( LLVMAttrKind )kind ); } /// Tests if this attribute set has a given string attribute /// Index for the attribute /// Name of the attribute to test for /// true if the attribute exists or false if not public bool Has( FunctionAttributeIndex index, string name ) { Context.VerifyOperation( ); return NativeMethods.AttributeSetHasStringAttribute( NativeAttributeSet, ( uint )index, name ); } internal AttributeSet( UIntPtr nativeAttributeSet ) { NativeAttributeSet = nativeAttributeSet; } // underlying native llvm::AttributeSet follows the basic Pointer to Implementation (PIMPL) pattern. // Thus, the total size of the structure is that of a pointer. While it isn't POD it is trivially // copy constructible and standard layout so it is safe to just use a pointer here and pass that to // native code as a simple IntPtr. The implementation for the PIMPL pattern is allocated and owned by // the context. Since AttributeSets are "interned" multiple AttributeSets may refer to the same internal // implementation instance. There is no dispose for the AttributeSet however as the context will take // care of cleaning them up when it is disposed. [System.Diagnostics.CodeAnalysis.SuppressMessage( "Microsoft.Reliability", "CA2006:UseSafeHandleToEncapsulateNativeResources", Justification = "LLVM Context will clean up the allocations for this" )] internal readonly UIntPtr NativeAttributeSet; } } ================================================ FILE: Zelig/Zelig/CompileTime/Llvm.NET/Llvm.NET/Values/AttributeSetContainer.cs ================================================ using System; using System.Linq; using System.Collections.Generic; namespace Llvm.NET.Values { /// Static class to provide mutators for otherwise immutable s /// /// The methods of this class provide mutators for an contained in a /// class implementing . (This includes /// , and . An /// is immutable, all of the methods that modify an attribute set actually /// produce a new attribute set. (This follows the underlying LLVM model and semantics). Thus, to /// change the attributes of a you must get the /// set, produce a modified version and then set the /// new value back to the property. The methods in /// this class will perform the read, modify and write back sequence as a single call for any of the /// available implementations. /// public static class AttributeSetContainer { public static T AddAttribute( this T self, FunctionAttributeIndex index, AttributeKind[ ] values ) where T : IAttributeSetContainer { if( values == null ) throw new ArgumentNullException( nameof( values ) ); using( var bldr = new AttributeBuilder( self.Attributes, index ) ) { foreach( var kind in values ) bldr.Add( kind ); self.Attributes = self.Attributes.Add( index, bldr.ToAttributeSet( index ) ); return self; } } public static T AddAttribute( this T self, FunctionAttributeIndex index, AttributeKind value ) where T : IAttributeSetContainer { self.Attributes = self.Attributes.Add( index, new AttributeValue( self.Attributes.Context, value ) ); return self; } public static T AddAttribute( this T self, FunctionAttributeIndex index, AttributeValue value ) where T : IAttributeSetContainer { self.Attributes = self.Attributes.Add( index, value ); return self; } /// Compatibility extension method to handle migrating code from older attribute handling /// Function to add attributes to /// Attributes to add /// The function itself /// /// Adds attributes to a given function itself (as opposed to the return or one of the function's parameters) /// This is equivalent to calling /// with as the first parameter /// public static Function AddAttributes( this Function self, params AttributeValue[ ] attributes ) { if( self == null ) throw new ArgumentNullException( nameof( self ) ); self.Attributes = self.Attributes.Add( FunctionAttributeIndex.Function, attributes ); return self; } /// Compatibility extension method to handle migrating code from older attribute handling /// Function to add attributes to /// Attributes to add /// The function itself /// /// Adds attributes to a given function itself (as opposed to the return or one of the function's parameters) /// This is equivalent to calling /// with as the first parameter /// public static Function AddAttributes( this Function self, IEnumerable attributes ) { if( self == null ) throw new ArgumentNullException( nameof( self ) ); self.Attributes = self.Attributes.Add( FunctionAttributeIndex.Function, attributes ); return self; } /// Compatibility extension method to handle migrating code from older attribute handling /// Function to remove attributes from /// Attribute to remove /// The function itself /// /// Removes attributes from a given function itself (as opposed to the return or one of the function's parameters) /// This is equivalent to calling /// with as the first parameter /// public static Function RemoveAttribute( this Function self, AttributeKind kind ) { if( self == null ) throw new ArgumentNullException( nameof( self ) ); self.Attributes = self.Attributes.Remove( FunctionAttributeIndex.Function, kind ); return self; } /// Compatibility extension method to handle migrating code from older attribute handling /// Function to remove attributes from /// Attribute to remove /// The function itself /// /// Removes attributes from a given function itself (as opposed to the return or one of the function's parameters) /// This is equivalent to calling /// with as the first parameter /// public static Function RemoveAttribute( this Function self, string name ) { if( self == null ) throw new ArgumentNullException( nameof( self ) ); self.Attributes = self.Attributes.Remove( FunctionAttributeIndex.Function, name ); return self; } public static T AddAttributes( this T self, FunctionAttributeIndex index, params AttributeValue[ ] attributes ) where T : IAttributeSetContainer { self.Attributes = self.Attributes.Add( index, attributes ); return self; } public static T AddAttributes( this T self, FunctionAttributeIndex index, AttributeSet attributes ) where T : IAttributeSetContainer { self.Attributes = self.Attributes.Add( index, attributes[ index ] ); return self; } public static T AddAttributes( this T self, FunctionAttributeIndex index, IEnumerable attributes ) where T : IAttributeSetContainer { self.Attributes = self.Attributes.Add( index, attributes ); return self; } public static T RemoveAttribute( this T self, FunctionAttributeIndex index, AttributeKind kind ) where T : IAttributeSetContainer { self.Attributes = self.Attributes.Remove( index, kind ); return self; } public static T RemoveAttribute( this T self, FunctionAttributeIndex index, string name ) where T : IAttributeSetContainer { self.Attributes = self.Attributes.Remove( index, name ); return self; } } } ================================================ FILE: Zelig/Zelig/CompileTime/Llvm.NET/Llvm.NET/Values/AttributeValue.cs ================================================ using System; using System.Diagnostics.CodeAnalysis; using System.Runtime.InteropServices; using Llvm.NET.Native; namespace Llvm.NET.Values { public struct IndexedAttributeValue : IEquatable { public IndexedAttributeValue( FunctionAttributeIndex index, AttributeValue value ) { Index = index; Value = value; } public FunctionAttributeIndex Index { get; } public AttributeValue Value { get; } public override string ToString( ) { if( Index < FunctionAttributeIndex.Parameter0 ) return $"{Index}: {Value}"; return $"Parameter{( int )(Index - FunctionAttributeIndex.Parameter0)}: {Value}"; } #region Equality operators public bool Equals( IndexedAttributeValue other ) { return other.Index == Index && other.Value == Value; } public override bool Equals( object obj ) { if( !( obj is IndexedAttributeValue ) ) return false; return Equals( ( IndexedAttributeValue )obj ); } public override int GetHashCode( ) { return Value.GetHashCode( ) ^ Index.GetHashCode( ); } public static bool operator==( IndexedAttributeValue left, IndexedAttributeValue right ) { return left.Equals( right ); } public static bool operator!=( IndexedAttributeValue left, IndexedAttributeValue right ) { return left.Equals( right ); } #endregion } /// Single attribute for functions, function returns and function parameters /// /// This is the equivalent to the underlying llvm::Attribute class. The name was changed to /// AttributeValue in .NET to prevent confusion with the class /// that is used throughout .NET libraries. As with the underlying LLVM type, this is an /// immutable value type. /// [SuppressMessage( "Microsoft.Design" , "CA1049:TypesThatOwnNativeResourcesShouldBeDisposable" , Justification = "The native pointer isn't owned by this structure, it is owned by the LLVM context" ) ] public struct AttributeValue { /// Creates a simple boolean attribute /// Kind of attribute public AttributeValue( AttributeKind kind ) : this( Context.CurrentContext, kind, 0ul ) { if( kind.RequiresIntValue() ) throw new ArgumentException( $"Attribute {kind} requires a value", nameof( kind ) ); } /// Creates a simple boolean attribute /// Context for creating the attribute /// Kind of attribute public AttributeValue( Context context, AttributeKind kind ) : this( context, kind, 0ul ) { if( kind.RequiresIntValue() ) throw new ArgumentException( $"Attribute {kind} requires a value", nameof( kind ) ); } /// Creates an attribute with an integer value parameter /// The kind of attribute /// Value for the attribute /// /// Not all attributes support a value and those that do don't all support /// a full 64bit value. The following table provides the kinds of attributes /// accepting a value and the allowed size of the values. /// /// Bit Length /// 32 /// 32 /// 64 /// 64 /// /// public AttributeValue( AttributeKind kind, UInt64 value ) : this( Context.CurrentContext, kind, value ) { } /// Creates an attribute with an integer value parameter /// Context used for interning attributes /// The kind of attribute /// Value for the attribute /// /// Not all attributes support a value and those that do don't all support /// a full 64bit value. The following table provides the kinds of attributes /// accepting a value and the allowed size of the values. /// /// Bit Length /// 32 /// 32 /// 64 /// 64 /// /// public AttributeValue( Context context, AttributeKind kind, UInt64 value ) : this( NativeMethods.CreateAttribute( context.VerifyAsArg( nameof( context ) ).ContextHandle , ( LLVMAttrKind )kind , value ) ) { } /// Adds a valueless named attribute /// Attribute name public AttributeValue( string name ) : this( Context.CurrentContext, name, string.Empty ) { } /// Adds a valueless named attribute /// Context to use for interning attributes /// Attribute name public AttributeValue( Context context, string name ) : this( context, name, string.Empty ) { } /// Adds a Target specific named attribute with value /// Name of the attribute /// Value of the attribute /// Since a valid is required to create an attribute value /// this requires that is not . /// In other words a Context must have already been created for the current thread by the /// time this is called so it cannot be used to initialize static instances. /// public AttributeValue( string name, string value ) : this( Context.CurrentContext, name, value ) { } /// Adds a Target specific named attribute with value /// Context to use for interning attributes /// Name of the attribute /// Value of the attribute [SuppressMessage( "Microsoft.Design", "CA1062:Validate arguments of public methods", MessageId = "0" )] public AttributeValue( Context context, string name, string value ) { context.VerifyAsArg( nameof( context ) ); if( string.IsNullOrWhiteSpace( name ) ) throw new ArgumentException( "AttributeValue name cannot be null, Empty or all whitespace" ); NativeAttribute = NativeMethods.CreateTargetDependentAttribute( context.ContextHandle, name, value ); } internal AttributeValue( UIntPtr nativeValue ) { NativeAttribute = nativeValue; } #region IEquatable public override int GetHashCode( ) => NativeAttribute.GetHashCode( ); public override bool Equals( object obj ) { if( obj is AttributeValue ) return Equals( ( LLVMMetadataRef )obj ); if( obj is UIntPtr ) return NativeAttribute.Equals( obj ); return base.Equals( obj ); } public bool Equals( AttributeValue other ) => NativeAttribute == other.NativeAttribute; public static bool operator ==( AttributeValue left, AttributeValue right ) => left.Equals( right ); public static bool operator !=( AttributeValue left, AttributeValue right ) => !left.Equals( right ); #endregion /// Kind of the attribute, or null for target specif named attributes public AttributeKind? Kind => IsString ? (AttributeKind?)null : ( AttributeKind )NativeMethods.GetAttributeKind( NativeAttribute ); /// Name of a named attribute or null for other kinds of attributes public string Name { get { if( !IsString ) return null; var llvmString = NativeMethods.GetAttributeName( NativeAttribute ); return Marshal.PtrToStringAnsi( llvmString ); } } /// StringValue for named attributes with values public string StringValue { get { if( !IsString ) return null; var llvmString = NativeMethods.GetAttributeStringValue( NativeAttribute ); return Marshal.PtrToStringAnsi( llvmString ); } } /// Integer value of the attribute or null if the attribute doesn't have a value public UInt64? IntegerValue => IsInt ? NativeMethods.GetAttributeValue( NativeAttribute ) : (UInt64?)null; /// Flag to indicate if this attribute is a target specific string value public bool IsString => NativeMethods.IsStringAttribute( NativeAttribute ); /// Flag to indicate if this attribute has an integer attribute public bool IsInt => NativeMethods.IsIntAttribute( NativeAttribute ); /// Flag to indicate if this attribute is a simple enumeration value public bool IsEnum => NativeMethods.IsEnumAttribute( NativeAttribute ); public bool IsValidOn( FunctionAttributeIndex index, Function function ) { // for now all string attributes are valid everywhere as they are target dependent // (e.g. no way to verify the validity of an arbitrary without knowing the target) if( IsString ) return true; return Kind.Value.CheckAttributeUsage( index, function ); } public override string ToString( ) { if( IsString ) { if( !string.IsNullOrWhiteSpace( StringValue ) ) return $"\"{ Name }\" = \"{ StringValue }\""; return Name; } if( IsInt ) { return $"{ Kind } = { IntegerValue }"; } return Kind.ToString( ); } [System.Diagnostics.CodeAnalysis.SuppressMessage( "Microsoft.Reliability", "CA2006:UseSafeHandleToEncapsulateNativeResources" )] internal readonly UIntPtr NativeAttribute; /// Implicitly cast an to an /// Kind of attribute to create [SuppressMessage( "Microsoft.Usage", "CA2225:OperatorOverloadsHaveNamedAlternates", Justification = "Available via constructor, this is for convenience" )] public static implicit operator AttributeValue( AttributeKind kind ) => new AttributeValue( kind ); /// Implicitly cast a string to an named /// Attribute name [SuppressMessage( "Microsoft.Usage", "CA2225:OperatorOverloadsHaveNamedAlternates", Justification = "Available via constructor, this is for convenience" )] public static implicit operator AttributeValue( string kind ) => new AttributeValue( kind ); } } ================================================ FILE: Zelig/Zelig/CompileTime/Llvm.NET/Llvm.NET/Values/BasicBlock.cs ================================================ using System; using System.Collections.Generic; using Llvm.NET.Instructions; using Llvm.NET.Native; namespace Llvm.NET.Values { /// Provides aaccess to an LLVM Basic block /// /// A basic block is a sequence of instructions with a single entry /// and a single exit. The exit point must be a /// instruction or the block is not (yet) well-formed. /// public class BasicBlock : Value { /// Function containing the block public Function ContainingFunction { get { var parent = NativeMethods.GetBasicBlockParent( BlockHandle ); if( parent.Pointer == IntPtr.Zero ) return null; // cache functions and use lookups to ensure // identity/interning remains consistent with actual // LLVM model of interning return Value.FromHandle( parent ); } } /// First instruction in the block public Instruction FirstInstruction { get { var firstInst = NativeMethods.GetFirstInstruction( BlockHandle ); if( firstInst.Pointer == IntPtr.Zero ) return null; return Value.FromHandle( firstInst ); } } /// Last instruction in the block public Instruction LastInstruction { get { var lastInst = NativeMethods.GetLastInstruction( BlockHandle ); if( lastInst.Pointer == IntPtr.Zero) return null; return Value.FromHandle( lastInst ); } } /// Terminator instruction for the block /// May be null if the block is not yet well-formed /// as is commonly the case while generating code for a new block /// public Instruction Terminator { get { var terminator = NativeMethods.GetBasicBlockTerminator( BlockHandle ); if( terminator.Pointer == IntPtr.Zero) return null; return Value.FromHandle( terminator ); } } /// Enumerable collection of all instructions in the block public IEnumerable Instructions { get { var current = FirstInstruction; while( current != null ) { yield return current; current = GetNextInstruction( current ); } } } /// Gets the instruction that follows a given instruction in a block /// instruction in the block to get the next instruction from /// Next instruction or null if none /// Thrown when is from a different block public Instruction GetNextInstruction( Instruction instruction ) { if( instruction == null ) throw new ArgumentNullException( nameof( instruction ) ); if( instruction.ContainingBlock != this ) throw new ArgumentException( "Instruction is from a different block", nameof( instruction ) ); var hInst = NativeMethods.GetNextInstruction( instruction.ValueHandle ); return hInst.Pointer == IntPtr.Zero ? null : Value.FromHandle( hInst ); } internal BasicBlock( LLVMValueRef valueRef ) : base( valueRef ) { } internal LLVMBasicBlockRef BlockHandle => NativeMethods.ValueAsBasicBlock( ValueHandle ); internal static BasicBlock FromHandle( LLVMBasicBlockRef basicBlockRef ) { return Value.FromHandle( NativeMethods.BasicBlockAsValue( basicBlockRef ) ); } } } ================================================ FILE: Zelig/Zelig/CompileTime/Llvm.NET/Llvm.NET/Values/BlockAddress.cs ================================================ using Llvm.NET.Native; namespace Llvm.NET.Values { public class BlockAddress : Constant { internal BlockAddress( LLVMValueRef valueRef ) : base( valueRef ) { } } } ================================================ FILE: Zelig/Zelig/CompileTime/Llvm.NET/Llvm.NET/Values/ConstPointerNull.cs ================================================ using Llvm.NET.Native; using Llvm.NET.Types; namespace Llvm.NET.Values { public class ConstantPointerNull : Constant { /// Creates a constant null pointer to a given type /// /// public static ConstantPointerNull From( ITypeRef type ) { return FromHandle( NativeMethods.ConstPointerNull( type.GetTypeRef() ) ); } internal ConstantPointerNull( LLVMValueRef valueRef ) : base( valueRef ) { } } } ================================================ FILE: Zelig/Zelig/CompileTime/Llvm.NET/Llvm.NET/Values/Constant.cs ================================================ using System; using Llvm.NET.Native; using Llvm.NET.Types; namespace Llvm.NET.Values { /// Contains an LLVM Constant value public class Constant : User { /// Indicates if the constant is a Zero value for the its type public bool IsZeroValue => NativeMethods.IsConstantZeroValue( ValueHandle ); /// Create a NULL pointer for a given type /// Type of pointer to create a null vale for /// Constant NULL pointer of the specified type public static Constant NullValueFor( ITypeRef typeRef ) { if( typeRef == null ) throw new ArgumentNullException( nameof( typeRef ) ); var kind = typeRef.Kind; var structType = typeRef as StructType; if( kind == TypeKind.Label || kind == TypeKind.Function || ( structType != null && structType.IsOpaque ) ) throw new ArgumentException( "Cannot get a Null value for labels, functions and opaque types" ); return FromHandle( NativeMethods.ConstNull( typeRef.GetTypeRef( ) ) ); } /// Creates a constant instance of with all bits in the instance set to 1 /// Type of value to create /// Constant for the type with all instance bits set to 1 public static Constant AllOnesValueFor( ITypeRef typeRef ) => FromHandle( NativeMethods.ConstAllOnes( typeRef.GetTypeRef( ) ) ); /// Creates an representing an undefined value for /// Type to create the undefined value for /// /// representing an undefined value of /// public static Constant UndefinedValueFor( ITypeRef typeRef ) => FromHandle( NativeMethods.GetUndef( typeRef.GetTypeRef( ) ) ); /// Create a constant NULL pointer for a given type /// Type of pointer to create a null value for /// Constant NULL pointer of the specified type public static Constant ConstPointerToNullFor( ITypeRef typeRef ) => FromHandle( NativeMethods.ConstPointerNull( typeRef.GetTypeRef( ) ) ); internal Constant( LLVMValueRef valueRef ) : base( valueRef ) { } } } ================================================ FILE: Zelig/Zelig/CompileTime/Llvm.NET/Llvm.NET/Values/ConstantAggregateZero.cs ================================================ using Llvm.NET.Native; namespace Llvm.NET.Values { public class ConstantAggregateZero : Constant { internal ConstantAggregateZero( LLVMValueRef valueRef ) : base( valueRef ) { } } } ================================================ FILE: Zelig/Zelig/CompileTime/Llvm.NET/Llvm.NET/Values/ConstantArray.cs ================================================ using System.Linq; using System.Collections.Generic; using System; using Llvm.NET.Types; using Llvm.NET.Native; namespace Llvm.NET.Values { /// LLVM Constant Array /// /// Due to how LLVM treats constant arrays internally creating a constant array /// with the From method overloads may not actually produce a ConstantArray /// instance. At the least it will produce a Constant. LLVM will determine the /// appropriate internal representation based on the input types and values /// public class ConstantArray : Constant { /// Create a constant array of values of a given type /// Type of elements in the array /// Values to initialize the array /// Constant representing the array public static Constant From( ITypeRef elementType, params Constant[ ] values ) { return From( elementType, ( IList )values ); } /// Create a constant arra of values of a given type with a fixed size, zero filling any un-specified values /// Type of elements in the array /// Length of the array /// Values to initialize the array /// Constant representing the array /// /// If the number of arguments provided for the values is less than /// then the remaining elements of the array are set with the null value for the /// public static Constant From( ITypeRef elementType, int len, params Constant[] values ) { var zeroFilledValues = ZeroFill( elementType, len, values ).ToList( ); return From( elementType, zeroFilledValues ); } /// Create a constant array of values of a given type /// Type of elements in the array /// Values to initialize the array /// Constant representing the array public static Constant From( ITypeRef elementType, IList values ) { if( values.Any( v => v.NativeType.TypeHandle != elementType.TypeHandle ) ) throw new ArgumentException( "One or more value(s) type does not match specified array element type" ); var valueHandles = values.Select( v => v.ValueHandle ).ToArray( ); var argCount = valueHandles.Length; if( argCount == 0 ) valueHandles = new LLVMValueRef[ 1 ]; var handle = NativeMethods.ConstArray( elementType.GetTypeRef(), out valueHandles[ 0 ], (uint)argCount ); return FromHandle( handle ); } internal ConstantArray( LLVMValueRef valueRef ) : base( valueRef ) { } private static IEnumerable ZeroFill( ITypeRef elementType, int len, IList values) { foreach( var value in values ) yield return value; var zeroVal = elementType.GetNullValue( ); for( int i = values.Count; i < len; ++i ) yield return zeroVal; } } } ================================================ FILE: Zelig/Zelig/CompileTime/Llvm.NET/Llvm.NET/Values/ConstantDataArray.cs ================================================ using Llvm.NET.Native; namespace Llvm.NET.Values { public class ConstantDataArray : ConstantDataSequential { internal ConstantDataArray( LLVMValueRef valueRef ) : base( valueRef ) { } } } ================================================ FILE: Zelig/Zelig/CompileTime/Llvm.NET/Llvm.NET/Values/ConstantDataSequential.cs ================================================ using System; using System.Runtime.InteropServices; using Llvm.NET.Native; namespace Llvm.NET.Values { /// /// A vector or array constant whose element type is a simple 1/2/4/8-byte integer /// or float/double, and whose elements are just simple data values /// (i.e. ConstantInt/ConstantFP). /// /// /// This Constant node has no operands because /// it stores all of the elements of the constant as densely packed data, instead /// of as s /// public class ConstantDataSequential : Constant { public bool IsString => NativeMethods.IsConstantString( ValueHandle ); [System.Diagnostics.CodeAnalysis.SuppressMessage( "Microsoft.Naming", "CA2204:Literals should be spelled correctly", MessageId = "ConstantDataSequential" )] public string ExtractAsString() { if( !IsString ) throw new InvalidOperationException( "ConstantDataSequential is not a string" ); int len; var strPtr = NativeMethods.GetAsString( ValueHandle, out len ); return NativeMethods.NormalizeLineEndings( strPtr, len ); } internal ConstantDataSequential( LLVMValueRef valueRef ) : base( valueRef ) { } } } ================================================ FILE: Zelig/Zelig/CompileTime/Llvm.NET/Llvm.NET/Values/ConstantDataVector.cs ================================================ using Llvm.NET.Native; namespace Llvm.NET.Values { public class ConstantDataVector : ConstantDataSequential { internal ConstantDataVector( LLVMValueRef valueRef ) : base( valueRef ) { } } } ================================================ FILE: Zelig/Zelig/CompileTime/Llvm.NET/Llvm.NET/Values/ConstantExpression.cs ================================================ using System; using Llvm.NET.Types; using System.Collections.Generic; using Llvm.NET.Instructions; using Llvm.NET.Native; namespace Llvm.NET.Values { /// While technically a type in LLVM, ConstantExpression is primarily a static factory for Constants public class ConstantExpression : Constant { public OpCode OpCode => ( OpCode )NativeMethods.GetConstOpcode( ValueHandle ); [System.Diagnostics.CodeAnalysis.SuppressMessage( "Microsoft.Design", "CA1011:ConsiderPassingBaseTypesAsParameters", Justification = "Specific type required by interop call" )] public static Constant IntToPtrExpression( Constant value, ITypeRef type ) { if( value == null ) throw new ArgumentNullException( nameof( value ) ); if( value.NativeType.Kind != TypeKind.Integer ) throw new ArgumentException( "Integer Type expected", nameof( value ) ); if( !( type is IPointerType ) ) throw new ArgumentException( "pointer type expected", nameof( type ) ); return FromHandle( NativeMethods.ConstIntToPtr( value.ValueHandle, type.GetTypeRef( ) ) ); } [System.Diagnostics.CodeAnalysis.SuppressMessage( "Microsoft.Design", "CA1011:ConsiderPassingBaseTypesAsParameters", Justification = "Specific type required by interop call" )] public static Constant BitCast( Constant value, ITypeRef toType ) { if( value == null ) throw new ArgumentNullException( nameof( value ) ); var handle = NativeMethods.ConstBitCast( value.ValueHandle, toType.GetTypeRef( ) ); return FromHandle( handle ); } [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1011:ConsiderPassingBaseTypesAsParameters", Justification = "Specific type required by interop call")] public static Constant GetElementPtr(Constant value, IEnumerable args) { var llvmArgs = InstructionBuilder.GetValidatedGEPArgs(value, args); var handle = NativeMethods.ConstGEP(value.ValueHandle, out llvmArgs[0], (uint)llvmArgs.Length); return FromHandle(handle); } internal ConstantExpression( LLVMValueRef valueRef ) : base( valueRef ) { } } } ================================================ FILE: Zelig/Zelig/CompileTime/Llvm.NET/Llvm.NET/Values/ConstantFP.cs ================================================ using Llvm.NET.Native; namespace Llvm.NET.Values { /// Floating point constant value in LLVM public class ConstantFP : Constant { public double Value { get { bool loosesInfo; return GetValueWithLoss( out loosesInfo ); } } public double GetValueWithLoss( out bool loosesInfo ) { loosesInfo = false; LLVMBool nativeLoosesInfo; var retVal = NativeMethods.ConstRealGetDouble( ValueHandle, out nativeLoosesInfo ); loosesInfo = nativeLoosesInfo; return retVal; } internal ConstantFP( LLVMValueRef valueRef ) : base( valueRef ) { } } } ================================================ FILE: Zelig/Zelig/CompileTime/Llvm.NET/Llvm.NET/Values/ConstantInt.cs ================================================ using System; using Llvm.NET.Native; namespace Llvm.NET.Values { /// Represents an arbitrary bit width integer constant in LLVM /// /// Note - for integers, in LLVM, signed or unsigned is not part of the type of /// the integer. The distinction between them is determined entirely by the /// instructions used on the integer values. /// public class ConstantInt : Constant { /// Retrieves the value of the constant zero extended to 64 bits public UInt64 ZeroExtendedValue => NativeMethods.ConstIntGetZExtValue( ValueHandle ); /// Sign extends the value to a 64 bit value public Int64 SignExtendedValue => NativeMethods.ConstIntGetSExtValue( ValueHandle ); internal ConstantInt( LLVMValueRef valueRef ) : base( valueRef ) { } } } ================================================ FILE: Zelig/Zelig/CompileTime/Llvm.NET/Llvm.NET/Values/ConstantStruct.cs ================================================ using Llvm.NET.Native; namespace Llvm.NET.Values { public class ConstantStruct : Constant { internal ConstantStruct( LLVMValueRef valueRef ) : base( valueRef ) { } } } ================================================ FILE: Zelig/Zelig/CompileTime/Llvm.NET/Llvm.NET/Values/ConstantTokenNone.cs ================================================ using Llvm.NET.Native; namespace Llvm.NET.Values { public class ConstantTokenNone : Constant { internal ConstantTokenNone( LLVMValueRef valueRef ) : base( valueRef ) { } } } ================================================ FILE: Zelig/Zelig/CompileTime/Llvm.NET/Llvm.NET/Values/ConstantVector.cs ================================================ using Llvm.NET.Native; namespace Llvm.NET.Values { public class ConstantVector : Constant { internal ConstantVector( LLVMValueRef valueRef ) : base( valueRef ) { } } } ================================================ FILE: Zelig/Zelig/CompileTime/Llvm.NET/Llvm.NET/Values/Function.cs ================================================ using System; using System.Linq; using System.Collections.Generic; using System.Diagnostics; using System.Runtime.InteropServices; using Llvm.NET.Types; using Llvm.NET.DebugInfo; using Llvm.NET.Native; namespace Llvm.NET.Values { /// LLVM Function definition public class Function : GlobalObject , IAttributeSetContainer { /// Signature type of the function public IFunctionType Signature => TypeRef.FromHandle( NativeMethods.GetElementType( NativeMethods.TypeOf( ValueHandle ) ) ); /// Entry block for this function public BasicBlock EntryBlock { get { if( NativeMethods.CountBasicBlocks( ValueHandle ) == 0 ) return null; return BasicBlock.FromHandle( NativeMethods.GetEntryBasicBlock( ValueHandle ) ); } } /// Basic Blocks for the function public IReadOnlyList BasicBlocks { get { uint count = NativeMethods.CountBasicBlocks( ValueHandle ); var buf = new LLVMBasicBlockRef[ count ]; if( count > 0 ) NativeMethods.GetBasicBlocks( ValueHandle, out buf[ 0 ] ); return buf.Select( BasicBlock.FromHandle ) .ToList( ) .AsReadOnly( ); } } /// Parameters for the function including any method definition specific attributes (i.e. ByVal) public IReadOnlyList Parameters => new FunctionParameterList( this ); /// Calling convention for the method public CallingConvention CallingConvention { get { return ( CallingConvention )NativeMethods.GetFunctionCallConv( ValueHandle ); } set { NativeMethods.SetFunctionCallConv( ValueHandle, ( uint )value ); } } /// LLVM instrinsicID for the method public uint IntrinsicId => NativeMethods.GetIntrinsicID( ValueHandle ); /// Flag to indicate if the method signature accepts variable arguments public bool IsVarArg => Signature.IsVarArg; /// Return type of the function public ITypeRef ReturnType => Signature.ReturnType; public Function PersonalityFunction { get { if( !NativeMethods.FunctionHasPersonalityFunction( ValueHandle ) ) return null; return FromHandle( NativeMethods.GetPersonalityFunction( ValueHandle ) ); } set { NativeMethods.SetPersonalityFunction( ValueHandle, value?.ValueHandle ?? LLVMValueRef.Zero ); } } /// Debug information for this function public DISubProgram DISubProgram { get { return MDNode.FromHandle( NativeMethods.FunctionGetSubprogram( ValueHandle ) ); } set { if( ( value != null ) && !value.Describes( this ) ) throw new ArgumentException( "Subprogram does not describe this Function" ); NativeMethods.FunctionSetSubprogram( ValueHandle, value?.MetadataHandle ?? LLVMMetadataRef.Zero ); } } /// Garbage collection engine name that this function is generated to work with /// For details on GC support in LLVM see: http://llvm.org/docs/GarbageCollection.html public string GcName { get { var nativePtr = NativeMethods.GetGC( ValueHandle ); return Marshal.PtrToStringAnsi( nativePtr ); } set { NativeMethods.SetGC( ValueHandle, value ); } } /// Verifies the function is valid and all blocks properly terminated public void Verify( ) { IntPtr errMsgPtr; var status = NativeMethods.VerifyFunctionEx( ValueHandle, LLVMVerifierFailureAction.LLVMReturnStatusAction, out errMsgPtr ); if( status ) throw new InternalCodeGeneratorException( NativeMethods.MarshalMsg( errMsgPtr ) ); } public AttributeSet Attributes { get { return new AttributeSet( NativeMethods.GetFunctionAttributeSet( ValueHandle ) ); } set { // TODO: verify that the attribute set doesn't contain any attributes for parameter indices not available in this function. NativeMethods.SetFunctionAttributeSet( ValueHandle, value.NativeAttributeSet ); } } /// Add a new basic block to the beginning of a function /// Name (label) for the block /// created and inserted at the beginning of the function public BasicBlock PrependBasicBlock( string name ) { LLVMBasicBlockRef firstBlock = NativeMethods.GetFirstBasicBlock( ValueHandle ); BasicBlock retVal; if( firstBlock.Pointer == IntPtr.Zero ) { retVal = AppendBasicBlock( name ); } else { var blockRef = NativeMethods.InsertBasicBlockInContext( NativeType.Context.ContextHandle, firstBlock, name ); retVal = BasicBlock.FromHandle( blockRef ); } return retVal; } /// Appends a new basic block to a function /// Name (label) of the block /// created and inserted onto the end of the function public BasicBlock AppendBasicBlock( string name ) { LLVMBasicBlockRef blockRef = NativeMethods.AppendBasicBlockInContext( NativeType.Context.ContextHandle, ValueHandle, name ); return BasicBlock.FromHandle( blockRef ); } /// Retrieves or creates block by name /// Block name (label) to look for or create /// If the block was created it is appended to the end of function /// /// This method tries to find a block by it's name and returns it if found, if not found a new block is /// created and appended to the current function. /// public BasicBlock FindOrCreateNamedBlock( string name ) { var retVal = BasicBlocks.FirstOrDefault( b => b.Name == name ); if( ReferenceEquals( retVal, null ) ) retVal = AppendBasicBlock( name ); Debug.Assert( retVal.ContainingFunction.ValueHandle.Pointer == ValueHandle.Pointer ); return retVal; } internal Function( LLVMValueRef valueRef ) : base( valueRef ) { } } } ================================================ FILE: Zelig/Zelig/CompileTime/Llvm.NET/Llvm.NET/Values/FunctionParameterList.cs ================================================ using System; using System.Collections.Generic; using Llvm.NET.Native; namespace Llvm.NET.Values { /// Support class to provide read only list semantics to the parameters of a method internal class FunctionParameterList : IReadOnlyList { internal FunctionParameterList( Function owningFunction ) { OwningFunction = owningFunction; } public Argument this[ int index ] { get { if( index >= Count || index < 0 ) throw new ArgumentOutOfRangeException( nameof( index ) ); return Value.FromHandle( NativeMethods.GetParam( OwningFunction.ValueHandle, ( uint )index ) ); } } public int Count { get { uint count = NativeMethods.CountParams( OwningFunction.ValueHandle ); return ( int )Math.Min( count, int.MaxValue ); } } public IEnumerator GetEnumerator( ) { for( uint i = 0; i < Count; ++i ) { LLVMValueRef val = NativeMethods.GetParam( OwningFunction.ValueHandle, i ); if( val.Pointer == IntPtr.Zero ) yield break; yield return Value.FromHandle( val ); } } System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator( ) => GetEnumerator( ); private Function OwningFunction; } } ================================================ FILE: Zelig/Zelig/CompileTime/Llvm.NET/Llvm.NET/Values/GlobalAlias.cs ================================================ using System; using Llvm.NET.Native; namespace Llvm.NET.Values { /// LLVM Global Alias for a function or global value public class GlobalAlias : GlobalValue { public Constant Aliasee { get { if( ValueHandle.Pointer == IntPtr.Zero ) return null; var handle = NativeMethods.GetAliasee( ValueHandle ); if( handle.Pointer == IntPtr.Zero ) return null; return FromHandle( handle ); } } internal GlobalAlias( LLVMValueRef valueRef ) : base( valueRef ) { } } } ================================================ FILE: Zelig/Zelig/CompileTime/Llvm.NET/Llvm.NET/Values/GlobalObject.cs ================================================ using System.Runtime.InteropServices; using Llvm.NET.Native; namespace Llvm.NET.Values { public class GlobalObject : GlobalValue { internal GlobalObject( LLVMValueRef valueRef ) : base( valueRef ) { } /// Alignment requirements for this object public uint Alignment { get { return NativeMethods.GetAlignment( ValueHandle ); } set { NativeMethods.SetAlignment( ValueHandle, value ); } } /// Linker section this object belongs to public string Section { get { var ptr = NativeMethods.GetSection( ValueHandle ); return Marshal.PtrToStringAnsi( ptr ); } set { NativeMethods.SetSection( ValueHandle, value ); } } } } ================================================ FILE: Zelig/Zelig/CompileTime/Llvm.NET/Llvm.NET/Values/GlobalValue.cs ================================================ using Llvm.NET.Native; namespace Llvm.NET.Values { /// LLVM Global value public class GlobalValue : Constant { /// Visibility of this global value public Visibility Visibility { get { return ( Visibility )NativeMethods.GetVisibility( ValueHandle ); } set { NativeMethods.SetVisibility( ValueHandle, ( LLVMVisibility )value ); } } /// Linkage specification for this symbol public Linkage Linkage { get { return ( Linkage )NativeMethods.GetLinkage( ValueHandle ); } set { NativeMethods.SetLinkage( ValueHandle, ( LLVMLinkage )value ); } } /// Flag to indicate if this is an Unnamed address public bool UnnamedAddress { get { return NativeMethods.HasUnnamedAddr( ValueHandle ); } set { NativeMethods.SetUnnamedAddr( ValueHandle, value ); } } /// Flag to indicate if this is a declaration public bool IsDeclaration => NativeMethods.IsDeclaration( ValueHandle ); /// Module containing this global value public NativeModule ParentModule => NativeType.Context.GetModuleFor( NativeMethods.GetGlobalParent( ValueHandle ) ); internal GlobalValue( LLVMValueRef valueRef ) : base( valueRef ) { } } public static class GlobalValueExtensions { /// Visibility of this global value public static T Visibility( this T self, Visibility value ) where T : GlobalValue { self.Visibility = value; return self; } /// Linkage specification for this symbol public static T Linkage( this T self, Linkage value ) where T : GlobalValue { self.Linkage = value; return self; } } } ================================================ FILE: Zelig/Zelig/CompileTime/Llvm.NET/Llvm.NET/Values/GlobalVariable.cs ================================================ using System; using Llvm.NET.Native; namespace Llvm.NET.Values { /// An LLVM Global Variable public class GlobalVariable : GlobalObject { /// Flag to indicate if this variable is initialized in an external module public bool IsExternallyInitialized { get { return NativeMethods.IsExternallyInitialized( ValueHandle ); } set { NativeMethods.SetExternallyInitialized( ValueHandle, value ); } } /// Gets or sets if this global is a Constant public bool IsConstant { get { return NativeMethods.IsGlobalConstant( ValueHandle ); } set { NativeMethods.SetGlobalConstant( ValueHandle, value ); } } /// Flag to indicate if this global is stored per thread public bool IsThreadLocal { get { return NativeMethods.IsThreadLocal( ValueHandle ); } set { NativeMethods.SetThreadLocal( ValueHandle, value ); } } /// Initial value for the variable public Constant Initializer { get { var handle = NativeMethods.GetInitializer( ValueHandle ); if( handle.Pointer == IntPtr.Zero ) return null; return FromHandle( handle ); } set { NativeMethods.SetInitializer( ValueHandle, value?.ValueHandle ?? LLVMValueRef.Zero ); } } /// Removes the value from its parent module, but does not delete it public void RemoveFromParent() { NativeMethods.RemoveGlobalFromParent( ValueHandle ); } internal GlobalVariable( LLVMValueRef valueRef ) : base( valueRef ) { } } } ================================================ FILE: Zelig/Zelig/CompileTime/Llvm.NET/Llvm.NET/Values/IAttributeSetContainer.cs ================================================ namespace Llvm.NET.Values { /// Interface for values containing an AttributeSet /// /// This is used to allow the extension /// to act as mutators for the otherwise immutable . /// Each method of the extension class will read the attribute set from the container /// and create a new set based on the parameters (adding or removing attributes from the set) /// producing a new attributeSet that is then re-assigned back to the container. /// public interface IAttributeSetContainer { /// Attributes for this container AttributeSet Attributes { get; set; } } } ================================================ FILE: Zelig/Zelig/CompileTime/Llvm.NET/Llvm.NET/Values/InlineAsm.cs ================================================ using Llvm.NET.Native; namespace Llvm.NET.Values { public enum AsmDialect { ATT, Intel } public class InlineAsm : Value { internal InlineAsm( LLVMValueRef valueRef ) : base( valueRef ) { } //bool HasSideEffects => LLVMNative.HasSideEffects( ValueHandle ); //bool IsAlignStack => LLVMNative.IsAlignStack( ValueHandle ); //AsmDialect Dialect => LLVMNative.GetAsmDialect( ValueHandle ); } } ================================================ FILE: Zelig/Zelig/CompileTime/Llvm.NET/Llvm.NET/Values/UndefValue.cs ================================================ using Llvm.NET.Native; namespace Llvm.NET.Values { public class UndefValue : Constant { internal UndefValue( LLVMValueRef valueRef ) : base( valueRef ) { } } } ================================================ FILE: Zelig/Zelig/CompileTime/Llvm.NET/Llvm.NET/Values/Use.cs ================================================ using System; using System.Linq; using System.Collections.Generic; using Llvm.NET.Native; namespace Llvm.NET.Values { /// LLVM Use, which is essentially a tuple of the and the used /// /// A Use in LLVM forms a link in a directed graph of dependencies for values. /// public class Use { internal Use( LLVMUseRef useRef ) { OpaqueHandle = useRef; } public User User => Value.FromHandle( NativeMethods.GetUser( OpaqueHandle ) ); public Value Value => Value.FromHandle( NativeMethods.GetUsedValue( OpaqueHandle ) ); private LLVMUseRef OpaqueHandle; } } ================================================ FILE: Zelig/Zelig/CompileTime/Llvm.NET/Llvm.NET/Values/User.cs ================================================ using System; using System.Collections.Generic; using Llvm.NET.Native; namespace Llvm.NET.Values { /// Contains an LLVM User value /// /// A user is one role in the user->uses relationship /// conveyed by the LLVM value model. A User can contain /// references (e.g. uses) of other values. /// public class User : Value { internal User( LLVMValueRef userRef ) : base( userRef ) { OperandList = new UserOperandList( this ); } /// Collection of operands public IReadOnlyList Operands => OperandList; /// Enumerable collection of s public IEnumerable Uses { get { LLVMUseRef current = NativeMethods.GetFirstUse( ValueHandle ); while( current.Pointer != IntPtr.Zero ) { // TODO: intern the use instances? yield return new Use( current ); current = NativeMethods.GetNextUse( current ); } } } private UserOperandList OperandList; } } ================================================ FILE: Zelig/Zelig/CompileTime/Llvm.NET/Llvm.NET/Values/UserOperandList.cs ================================================ using System; using System.Collections.Generic; using Llvm.NET.Native; namespace Llvm.NET.Values { /// Support class to provide read-only list semantics to the operands of a of a method internal class UserOperandList : IReadOnlyList { internal UserOperandList( User owner ) { Owner = owner; } public Value this[ int index ] { get { if( index >= Count || index < 0 ) throw new ArgumentOutOfRangeException( nameof( index ) ); return Value.FromHandle( NativeMethods.GetOperand( Owner.ValueHandle, ( uint )index ) ); } } public int Count { get { int count = NativeMethods.GetNumOperands( Owner.ValueHandle ); return Math.Min( count, int.MaxValue ); } } public IEnumerator GetEnumerator( ) { for( uint i = 0; i < Count; ++i ) { LLVMValueRef val = NativeMethods.GetOperand( Owner.ValueHandle, i ); if( val.Pointer == IntPtr.Zero ) yield break; yield return Value.FromHandle( val ); } } System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator( ) => GetEnumerator( ); private User Owner; } } ================================================ FILE: Zelig/Zelig/CompileTime/Llvm.NET/Llvm.NET/Values/Value.cs ================================================ using System; using System.Diagnostics; using System.Runtime.InteropServices; using Llvm.NET.DebugInfo; using Llvm.NET.Instructions; using Llvm.NET.Native; using Llvm.NET.Types; namespace Llvm.NET.Values { /// LLVM Value /// /// Value is the root of a hierarchy of types representing values /// in LLVM. Values (and derived classes) are never constructed /// directly with the new operator. Instead, they are produced by /// other classes in this library internally. This is because they /// are just wrappers around the LLVM-C API handles and must /// maintain the "uniqueing" semantics. (e.g. allowing reference /// equality for values that are fundamentally the same value) /// This is generally hidden in the internals of the Llvm.NET /// library so callers need not be concerned with the details /// but can rely on the expected behavior that two Value instances /// referring to the same actual value (i.e. a function) are actually /// the same .NET object as well within the same /// [System.Diagnostics.CodeAnalysis.SuppressMessage( "Microsoft.Maintainability", "CA1506:AvoidExcessiveClassCoupling" )] public class Value : IExtensiblePropertyContainer { /// Name of the value (if any) public string Name { get { if( Context.IsDisposed ) return string.Empty; var ptr = NativeMethods.GetValueName( ValueHandle ); return Marshal.PtrToStringAnsi( ptr ); } set { NativeMethods.SetValueName( ValueHandle, value ); // LLVM auto adds a numeric suffix if a register with the same name already exists Debug.Assert( Name.StartsWith( value, StringComparison.Ordinal ) ); } } /// Indicates if this value is Undefined public bool IsUndefined => NativeMethods.IsUndef( ValueHandle ); /// Determines if the Value represents the NULL value for the values type public bool IsNull => NativeMethods.IsNull( ValueHandle ); /// Type of the value public ITypeRef NativeType => TypeRef.FromHandle( NativeMethods.TypeOf( ValueHandle ) ); public Context Context => NativeType.Context; /// Generates a string representing the LLVM syntax of the value /// string version of the value formatted by LLVM public override string ToString( ) { var ptr = NativeMethods.PrintValueToString( ValueHandle ); return NativeMethods.MarshalMsg( ptr ); } /// Replace all uses of a with another one /// New value public void ReplaceAllUsesWith( Value other ) { if( other == null ) throw new ArgumentNullException( nameof( other ) ); NativeMethods.ReplaceAllUsesWith( ValueHandle, other.ValueHandle ); } /// public bool TryGetExtendedPropertyValue( string id, out T value ) => ExtensibleProperties.TryGetExtendedPropertyValue( id, out value ); /// public void AddExtendedPropertyValue( string id, object value ) => ExtensibleProperties.AddExtendedPropertyValue( id, value ); internal Value( LLVMValueRef valueRef ) { if( valueRef.Pointer == IntPtr.Zero ) throw new ArgumentNullException( nameof( valueRef ) ); #if DEBUG var context = Llvm.NET.Context.GetContextFor( valueRef ); context.AssertValueNotInterned( valueRef ); #endif ValueHandle = valueRef; } internal LLVMValueRef ValueHandle { get; } /// Gets an Llvm.NET managed wrapper for a LibLLVM value handle /// Value handle to wrap /// LLVM.NET managed instance for the handle /// /// This method uses a cached mapping to ensure that two calls given the same /// input handle returns the same managed instance so that reference equality /// works as expected. /// internal static Value FromHandle( LLVMValueRef valueRef ) => FromHandle( valueRef ); /// Gets an Llvm.NET managed wrapper for a LibLLVM value handle /// Required type for the handle /// Value handle to wrap /// LLVM.NET managed instance for the handle /// /// This method uses a cached mapping to ensure that two calls given the same /// input handle returns the same managed instance so that reference equality /// works as expected. /// /// When the handle is for a different type of handle than specified by internal static T FromHandle( LLVMValueRef valueRef ) where T : Value { var context = Context.GetContextFor( valueRef ); return ( T )context.GetValueFor( valueRef, StaticFactory ); } /// Central factory for creating instances of and all derived types /// LibLLVM handle for the value /// New Value or derived type instance that wraps the underlying LibLLVM handle /// /// This method will determine the correct type for the handle and construct an instance of that /// type wrapping the handle. /// [System.Diagnostics.CodeAnalysis.SuppressMessage( "Microsoft.Maintainability", "CA1506:AvoidExcessiveClassCoupling" )] [System.Diagnostics.CodeAnalysis.SuppressMessage( "Microsoft.Maintainability", "CA1502:AvoidExcessiveComplexity" )] private static Value StaticFactory( LLVMValueRef h ) { var kind = NativeMethods.GetValueKind( h ); switch( kind ) { case ValueKind.Argument: return new Argument( h ); case ValueKind.BasicBlock: return new BasicBlock( h ); case ValueKind.Function: return new Function( h ); case ValueKind.GlobalAlias: return new GlobalAlias( h ); case ValueKind.GlobalVariable: return new GlobalVariable( h ); case ValueKind.UndefValue: return new UndefValue( h ); case ValueKind.BlockAddress: return new BlockAddress( h ); case ValueKind.ConstantExpr: return new ConstantExpression( h ); case ValueKind.ConstantAggregateZero: return new ConstantAggregateZero( h ); case ValueKind.ConstantDataArray: return new ConstantDataArray( h ); case ValueKind.ConstantDataVector: return new ConstantDataVector( h ); case ValueKind.ConstantInt: return new ConstantInt( h ); case ValueKind.ConstantFP: return new ConstantFP( h ); case ValueKind.ConstantArray: return new ConstantArray( h ); case ValueKind.ConstantStruct: return new ConstantStruct( h ); case ValueKind.ConstantVector: return new ConstantVector( h ); case ValueKind.ConstantPointerNull: return new ConstantPointerNull( h ); case ValueKind.MetadataAsValue: return new MetadataAsValue( h ); case ValueKind.InlineAsm: return new InlineAsm( h ); case ValueKind.Instruction: throw new ArgumentException( "Value with kind==Instruction is not valid" ); case ValueKind.Return: return new Instructions.ReturnInstruction( h ); case ValueKind.Branch: return new Instructions.Branch( h ); case ValueKind.Switch: return new Instructions.Switch( h ); case ValueKind.IndirectBranch: return new Instructions.IndirectBranch( h ); case ValueKind.Invoke: return new Instructions.Invoke( h ); case ValueKind.Unreachable: return new Instructions.Unreachable( h ); case ValueKind.Add: case ValueKind.FAdd: case ValueKind.Sub: case ValueKind.FSub: case ValueKind.Mul: case ValueKind.FMul: case ValueKind.UDiv: case ValueKind.SDiv: case ValueKind.FDiv: case ValueKind.URem: case ValueKind.SRem: case ValueKind.FRem: case ValueKind.Shl: case ValueKind.LShr: case ValueKind.AShr: case ValueKind.And: case ValueKind.Or: case ValueKind.Xor: return new Instructions.BinaryOperator( h ); case ValueKind.Alloca: return new Instructions.Alloca( h ); case ValueKind.Load: return new Instructions.Load( h ); case ValueKind.Store: return new Instructions.Store( h ); case ValueKind.GetElementPtr: return new Instructions.GetElementPtr( h ); case ValueKind.Trunc: return new Instructions.Trunc( h ); case ValueKind.ZeroExtend: return new Instructions.ZeroExtend( h ); case ValueKind.SignExtend: return new Instructions.SignExtend( h ); case ValueKind.FPToUI: return new Instructions.FPToUI( h ); case ValueKind.FPToSI: return new Instructions.FPToSI( h ); case ValueKind.UIToFP: return new Instructions.UIToFP( h ); case ValueKind.SIToFP: return new Instructions.SIToFP( h ); case ValueKind.FPTrunc: return new Instructions.FPTrunc( h ); case ValueKind.FPExt: return new Instructions.FPExt( h ); case ValueKind.PtrToInt: return new Instructions.PointerToInt( h ); case ValueKind.IntToPtr: return new Instructions.IntToPointer( h ); case ValueKind.BitCast: return new Instructions.BitCast( h ); case ValueKind.AddrSpaceCast: return new Instructions.AddressSpaceCast( h ); case ValueKind.ICmp: return new Instructions.IntCmp( h ); case ValueKind.FCmp: return new Instructions.FCmp( h ); case ValueKind.Phi: return new Instructions.PhiNode( h ); case ValueKind.Call: return new Instructions.CallInstruction( h ); case ValueKind.Select: return new Instructions.Select( h ); case ValueKind.UserOp1: return new Instructions.UserOp1( h ); case ValueKind.UserOp2: return new Instructions.UserOp2( h ); case ValueKind.VaArg: return new Instructions.VaArg( h ); case ValueKind.ExtractElement: return new Instructions.ExtractElement( h ); case ValueKind.InsertElement: return new Instructions.InsertElement( h ); case ValueKind.ShuffleVector: return new Instructions.ShuffleVector( h ); case ValueKind.ExtractValue: return new Instructions.ExtractValue( h ); case ValueKind.InsertValue: return new Instructions.InsertValue( h ); case ValueKind.Fence: return new Instructions.Fence( h ); case ValueKind.AtomicCmpXchg: return new Instructions.AtomicCmpXchg( h ); case ValueKind.AtomicRMW: return new Instructions.AtomicRMW( h ); case ValueKind.Resume: return new Instructions.ResumeInstruction( h ); case ValueKind.LandingPad: return new Instructions.LandingPad( h ); case ValueKind.CleanUpReturn: return new Instructions.CleanupReturn( h ); case ValueKind.CatchReturn: return new Instructions.CatchReturn( h ); case ValueKind.CatchPad: return new Instructions.CatchPad( h ); case ValueKind.CleanupPad: return new Instructions.CleanupPad( h ); case ValueKind.CatchSwitch: return new Instructions.CatchSwitch( h ); default: if( kind >= ValueKind.ConstantFirstVal && kind <= ValueKind.ConstantLastVal ) return new Constant( h ); return kind > ValueKind.Instruction ? new Instructions.Instruction( h ) : new Value( h ); } } private readonly ExtensiblePropertyContainer ExtensibleProperties = new ExtensiblePropertyContainer( ); } /// Provides extension methods to that cannot be achieved as members of the class /// /// Using generic static extension methods allows for fluent coding while retaining the type of the "this" parameter. /// If these were members of the class then the only return type could be , /// thus losing the original type and requiring a cast to get back to it. /// public static class ValueExtensions { /// Sets the debugging location for a value /// Type of the value to tag /// Value to set debug location for /// Debug location information /// /// Technically speaking only an can have debug location /// information. However, since LLVM will perform constant folding in the /// most of the methods in return a rather than a /// more specific . Thus, without this extension method here, /// code would need to know ahead of time that an actual instruction would be produced then cast the result /// to an and then set the debug location. This makes the code rather /// ugly and tedious to manage. Placing this as a generic extension method ensures that the return type matches /// the original and no additional casting is needed, which would defeat the purpose of doing this. For /// types that are not instructions this does nothing. This allows for a simpler fluent /// style of programming where the actual type is retained even in cases where an /// method will always return an actual instruction. /// In order to help simplify code generation for cases where not all of the source information is /// available this is a NOP if is null. Thus, it is safe to call even when debugging /// information isn't actually available. This helps to avoid cluttering calling code with test for debug info /// before trying to add it. /// [System.Diagnostics.CodeAnalysis.SuppressMessage( "Microsoft.Design", "CA1011:ConsiderPassingBaseTypesAsParameters", Justification = "Specific type required by interop call" )] public static T SetDebugLocation( this T value, DILocation location ) where T : Value { if( value == null ) throw new ArgumentNullException( nameof( value ) ); if( location == null ) return value; var instruction = value as Instructions.Instruction; if( instruction != null ) { if( !location.Scope.SubProgram.Describes( instruction.ContainingBlock.ContainingFunction ) ) throw new ArgumentException( "Location does not describe the function containing the provided instruction", nameof( location ) ); NativeMethods.SetDILocation( value.ValueHandle, location.MetadataHandle ); } return value; } /// Sets the debugging location for a value /// Type of the value to tag /// Value to set debug location for /// Line number /// Column number /// Scope for the value /// /// Technically speaking only an can have debug location /// information. However, since LLVM will perform constant folding in the /// most of the methods in return a rather than a /// more specific . Thus, without this extension method here, /// code would need to know ahead of time that an actual instruction would be produced then cast the result /// to an and then set the debug location. This makes the code rather /// ugly and tedious to manage. Placing this as a generic extension method ensures that the return type matches /// the original and no additional casting is needed, which would defeat the purpose of doing this. For /// types that are not instructions this does nothing. This allows for a simpler fluent /// style of programming where the actual type is retained even in cases where an /// method will always return an actual instruction. /// In order to help simplify code generation for cases where not all of the source information is /// available this is a NOP if is null. Thus, it is safe to call even when debugging /// information isn't actually available. This helps to avoid cluttering calling code with test for debug info /// before trying to add it. /// [System.Diagnostics.CodeAnalysis.SuppressMessage( "Microsoft.Design", "CA1011:ConsiderPassingBaseTypesAsParameters", Justification = "Specific type required by interop call" )] public static T SetDebugLocation( this T value, uint line, uint column, DebugInfo.DILocalScope scope ) where T : Value { if( scope == null ) return value; var instruction = value as Instructions.Instruction; if( instruction != null ) { if( !scope.SubProgram.Describes( instruction.ContainingBlock.ContainingFunction ) ) throw new ArgumentException( "scope does not describe the function containing the provided instruction", nameof( scope ) ); NativeMethods.SetDebugLoc( value.ValueHandle, line, column, scope.MetadataHandle ); } return value; } /// Sets the virtual register name for a value /// Type of the value to set the name for /// Value to set register name for /// Name for the virtual register the value represents /// /// Technically speaking only an can have register name /// information. However, since LLVM will perform constant folding in the /// it almost all of the methods in return a rather /// than an more specific . Thus, without this extension method here, /// code would need to know ahead of time that an actual instruction would be produced then cast the result /// to an and then set the debug location. This makes the code rather /// ugly and tedious to manage. Placing this as a generic extension method ensures that the return type matches /// the original and no additional casting is needed, which would defeat the purpose of doing this. For /// types that are not instructions this does nothing. This allows for a simpler fluent /// style of programming where the actual type is retained even in cases where an /// method will always return an actual instruction. /// Since the property is available on all s this is slightly /// redundant. It is useful for maintaining the fluent style of coding along with expressing intent more clearly. /// (e.g. using this makes it expressly clear that the intent is to set the virtual register name and not the /// name of a local variable etc...) Using the fluent style allows a significant reduction in the number of /// overloaded methods in to account for all variations with or without a name. /// /// public static T RegisterName( this T value, string name ) where T : Value { var inst = value as Instructions.Instruction; if( inst != null ) value.Name = name; return value; } } } ================================================ FILE: Zelig/Zelig/CompileTime/Llvm.NET/Llvm.NET.sln ================================================  Microsoft Visual Studio Solution File, Format Version 12.00 # Visual Studio 14 VisualStudioVersion = 14.0.23107.0 MinimumVisualStudioVersion = 10.0.40219.1 Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "LibLLVM", "LibLLVM\LibLLVM.vcxproj", "{6C77A7DE-D464-430F-96A9-A64768763B5F}" EndProject Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Llvm.NET", "Llvm.NET\Llvm.NET.csproj", "{0162C8CE-6641-4922-8664-F8A44356FBF7}" EndProject Global GlobalSection(SolutionConfigurationPlatforms) = preSolution Debug|Any CPU = Debug|Any CPU Debug|Win32 = Debug|Win32 Debug|x64 = Debug|x64 Release|Any CPU = Release|Any CPU Release|Win32 = Release|Win32 Release|x64 = Release|x64 RelWithDebInfo|Any CPU = RelWithDebInfo|Any CPU RelWithDebInfo|Win32 = RelWithDebInfo|Win32 RelWithDebInfo|x64 = RelWithDebInfo|x64 EndGlobalSection GlobalSection(ProjectConfigurationPlatforms) = postSolution {6C77A7DE-D464-430F-96A9-A64768763B5F}.Debug|Any CPU.ActiveCfg = Debug|Win32 {6C77A7DE-D464-430F-96A9-A64768763B5F}.Debug|Win32.ActiveCfg = Debug|Win32 {6C77A7DE-D464-430F-96A9-A64768763B5F}.Debug|Win32.Build.0 = Debug|Win32 {6C77A7DE-D464-430F-96A9-A64768763B5F}.Debug|x64.ActiveCfg = Debug|x64 {6C77A7DE-D464-430F-96A9-A64768763B5F}.Debug|x64.Build.0 = Debug|x64 {6C77A7DE-D464-430F-96A9-A64768763B5F}.Release|Any CPU.ActiveCfg = Release|Win32 {6C77A7DE-D464-430F-96A9-A64768763B5F}.Release|Win32.ActiveCfg = Release|Win32 {6C77A7DE-D464-430F-96A9-A64768763B5F}.Release|Win32.Build.0 = Release|Win32 {6C77A7DE-D464-430F-96A9-A64768763B5F}.Release|x64.ActiveCfg = Release|x64 {6C77A7DE-D464-430F-96A9-A64768763B5F}.Release|x64.Build.0 = Release|x64 {6C77A7DE-D464-430F-96A9-A64768763B5F}.RelWithDebInfo|Any CPU.ActiveCfg = RelWithDebInfo|Win32 {6C77A7DE-D464-430F-96A9-A64768763B5F}.RelWithDebInfo|Win32.ActiveCfg = RelWithDebInfo|Win32 {6C77A7DE-D464-430F-96A9-A64768763B5F}.RelWithDebInfo|Win32.Build.0 = RelWithDebInfo|Win32 {6C77A7DE-D464-430F-96A9-A64768763B5F}.RelWithDebInfo|x64.ActiveCfg = RelWithDebInfo|x64 {6C77A7DE-D464-430F-96A9-A64768763B5F}.RelWithDebInfo|x64.Build.0 = RelWithDebInfo|x64 {0162C8CE-6641-4922-8664-F8A44356FBF7}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {0162C8CE-6641-4922-8664-F8A44356FBF7}.Debug|Any CPU.Build.0 = Debug|Any CPU {0162C8CE-6641-4922-8664-F8A44356FBF7}.Debug|Win32.ActiveCfg = Debug|Any CPU {0162C8CE-6641-4922-8664-F8A44356FBF7}.Debug|Win32.Build.0 = Debug|Any CPU {0162C8CE-6641-4922-8664-F8A44356FBF7}.Debug|x64.ActiveCfg = Debug|Any CPU {0162C8CE-6641-4922-8664-F8A44356FBF7}.Debug|x64.Build.0 = Debug|Any CPU {0162C8CE-6641-4922-8664-F8A44356FBF7}.Release|Any CPU.ActiveCfg = Release|Any CPU {0162C8CE-6641-4922-8664-F8A44356FBF7}.Release|Any CPU.Build.0 = Release|Any CPU {0162C8CE-6641-4922-8664-F8A44356FBF7}.Release|Win32.ActiveCfg = Release|Any CPU {0162C8CE-6641-4922-8664-F8A44356FBF7}.Release|Win32.Build.0 = Release|Any CPU {0162C8CE-6641-4922-8664-F8A44356FBF7}.Release|x64.ActiveCfg = Release|Any CPU {0162C8CE-6641-4922-8664-F8A44356FBF7}.Release|x64.Build.0 = Release|Any CPU {0162C8CE-6641-4922-8664-F8A44356FBF7}.RelWithDebInfo|Any CPU.ActiveCfg = RelWithDebInfo|Any CPU {0162C8CE-6641-4922-8664-F8A44356FBF7}.RelWithDebInfo|Any CPU.Build.0 = RelWithDebInfo|Any CPU {0162C8CE-6641-4922-8664-F8A44356FBF7}.RelWithDebInfo|Win32.ActiveCfg = RelWithDebInfo|Any CPU {0162C8CE-6641-4922-8664-F8A44356FBF7}.RelWithDebInfo|Win32.Build.0 = RelWithDebInfo|Any CPU {0162C8CE-6641-4922-8664-F8A44356FBF7}.RelWithDebInfo|x64.ActiveCfg = RelWithDebInfo|Any CPU {0162C8CE-6641-4922-8664-F8A44356FBF7}.RelWithDebInfo|x64.Build.0 = RelWithDebInfo|Any CPU EndGlobalSection GlobalSection(SolutionProperties) = preSolution HideSolutionNode = FALSE EndGlobalSection EndGlobal ================================================ FILE: Zelig/Zelig/CompileTime/MetaData/Importer/AbstractMetaDataException.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // // // Originally based on the Bartok code base. // using System; using System.Collections.Generic; using System.Collections; using System.Reflection; using System.Text; namespace Microsoft.Zelig.MetaData.Importer { public abstract class AbstractMetaDataException : Exception { // // Constructor Methods // protected AbstractMetaDataException ( String reason ) : base( reason ) { } } } ================================================ FILE: Zelig/Zelig/CompileTime/MetaData/Importer/ArrayReader.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // using System; using System.Collections.Generic; using System.Text; namespace Microsoft.Zelig.MetaData.Importer { public unsafe class ArrayReader { private static readonly System.Text.UTF8Encoding s_stringEncoding = new System.Text.UTF8Encoding(); // // State // byte[] m_image; int m_startPosition; int m_currentPosition; int m_endPosition; GrowOnlySet< string > m_lookup; // // Constructor Methods // public ArrayReader( byte[] image ) { m_image = image; m_startPosition = 0; m_currentPosition = 0; m_endPosition = image.Length; m_lookup = SetFactory.New< string >(); } public ArrayReader( ArrayReader scanner , int offset ) { m_image = scanner.m_image; m_startPosition = scanner.m_currentPosition + offset; m_currentPosition = m_startPosition; m_endPosition = scanner.m_endPosition; m_lookup = scanner.m_lookup; if(m_startPosition < 0) { throw new IndexOutOfRangeException(); } } public ArrayReader( ArrayReader scanner , int offset , int count ) { m_image = scanner.m_image; m_startPosition = scanner.m_currentPosition + offset; m_currentPosition = m_startPosition; m_endPosition = m_startPosition + count; m_lookup = scanner.m_lookup; if(m_startPosition < 0 || m_endPosition > scanner.m_endPosition) { throw new IndexOutOfRangeException(); } } //--// public override bool Equals( Object obj ) { if(obj is ArrayReader) { ArrayReader other = (ArrayReader)obj; if(this.Length == other.Length) { int len = this.Length; while(len-- > 0) { if(m_image[m_startPosition+len] != other.m_image[other.m_startPosition+len]) { return false; } } return true; } } return false; } public override int GetHashCode() { return (int)this.Length; } //--// private void CheckRange( int size ) { if(size < 0 || m_currentPosition + size > m_endPosition) { throw new IndexOutOfRangeException(); } } public bool ReadBoolean() { return (ReadUInt8() != 0); } public byte PeekUInt8() { CheckRange( 1 ); return m_image[m_currentPosition]; } public byte ReadUInt8() { CheckRange( 1 ); byte res = m_image[m_currentPosition]; m_currentPosition += 1; return res; } public ushort ReadUInt16() { CheckRange( 2 ); ushort res = (ushort)(((uint)m_image[m_currentPosition ] ) | ((uint)m_image[m_currentPosition+1] << 8) ); m_currentPosition += 2; return res; } public uint ReadUInt32() { CheckRange( 4 ); uint res = (((uint)m_image[m_currentPosition ] ) | ((uint)m_image[m_currentPosition+1] << 8) | ((uint)m_image[m_currentPosition+2] << 16) | ((uint)m_image[m_currentPosition+3] << 24) ); m_currentPosition += 4; return res; } public ulong ReadUInt64() { ulong res = (((ulong)ReadUInt32() ) | ((ulong)ReadUInt32() << 32) ); return res; } public sbyte ReadInt8() { return (sbyte)ReadUInt8(); } public short ReadInt16() { return (short)ReadUInt16(); } public int ReadInt32() { return (int)ReadUInt32(); } public long ReadInt64() { return (long)ReadUInt64(); } public char ReadChar() { return (char)ReadUInt16(); } public unsafe float ReadSingle() { uint tmpBuffer = ReadUInt32(); return *((float*)&tmpBuffer); } public unsafe double ReadDouble() { ulong tmpBuffer = ReadUInt64(); return *((double*)&tmpBuffer); } //--// public uint ReadCompressedUInt32() { byte firstByte = this.ReadUInt8(); if((firstByte & 0x80) == 0) { // encoded in a single byte return firstByte; } else if((firstByte & 0x40) == 0) { // encoded in two bytes firstByte &= 0x3F; return (((uint)firstByte << 8) | ((uint)this.ReadUInt8() ) ); } else { // encoded in four bytes firstByte &= 0x3F; return (((uint)firstByte << 24) | ((uint)this.ReadUInt8() << 16) | ((uint)this.ReadUInt8() << 8) | ((uint)this.ReadUInt8() ) ); } } public string ReadCompressedString() { byte firstByte = this.ReadUInt8(); if(firstByte == 0xFF) { return null; } m_currentPosition--; uint len = this.ReadCompressedUInt32(); byte[] bytes = this.ReadUInt8Array( (int)len ); return s_stringEncoding.GetString( bytes ); } public int ReadCompressedToken() { uint codedToken = ReadCompressedUInt32(); TokenType tokenType; switch(codedToken & 0x3) { case 0x0: tokenType = TokenType.TypeDef ; break; case 0x1: tokenType = TokenType.TypeRef ; break; case 0x2: tokenType = TokenType.TypeSpec; break; default : throw IllegalMetaDataFormatException.Create( "Bad signature token: {0}", codedToken ); } return MetaData.PackToken( tokenType, (int)(codedToken >> 2) ); } public Guid ReadGuid() { const int sizeOfGuid = 16; return new Guid( this.ReadUInt8Array( sizeOfGuid ) ); } //--// public void CopyIntoArray( byte[] dst , int offset , int count ) { CheckRange( count ); Array.Copy( m_image, m_currentPosition, dst, offset, count ); m_currentPosition += count; } public byte[] ReadUInt8Array( int count ) { byte[] res = new byte[count]; CopyIntoArray( res, 0, count ); return res; } public byte[] ReadUInt8Array( int count , int extraAlloc ) { byte[] res = new byte[count + extraAlloc]; CopyIntoArray( res, 0, count ); return res; } public char[] ReadCharArray( int count ) { char[] res = new char[count]; for(int i = 0; i < count; i++) { res[i] = ReadChar(); } return res; } public int[] ReadInt32Array( int count ) { int[] res = new int[count]; for(int i = 0; i < count; i++) { res[i] = ReadInt32(); } return res; } public uint[] ReadUInt32Array( int count ) { uint[] res = new uint[count]; for(int i = 0; i < count; i++) { res[i] = ReadUInt32(); } return res; } public string ReadZeroTerminatedUInt8String() { StringBuilder sb = new StringBuilder(); while(true) { byte c = ReadUInt8(); if(c == 0) break; sb.Append( (char)c ); } return sb.ToString(); } public string ReadZeroTerminatedUTF8String() { int start = m_currentPosition; int end = start; while(m_image[end] != 0) { end++; } CheckRange( end + 1 - start ); m_currentPosition = end + 1; string res = s_stringEncoding.GetString( m_image, start, end - start ); string res2; if(m_lookup.Contains( res, out res2 )) { return res2; } else { m_lookup.Insert( res ); return res; } } public string ReadUInt8String( int count ) { char[] res = new char[count]; for(int i = 0; i < count; i++) { res[i] = (char)ReadUInt8(); } return new String( res ); } public string ReadUInt16String( int count ) { char[] res = ReadCharArray( count ); return new String( res ); } //--// public ArrayReader CreateSubset( int count ) { CheckRange( count ); return new ArrayReader( this, 0, count ); } public ArrayReader CreateSubsetAndAdvance( int count ) { ArrayReader res = CreateSubset( count ); m_currentPosition += count; return res; } // public uint ComputeCRC() // { // return CRC32.Compute( m_image, m_currentPosition, m_endPosition-m_currentPosition, 0 ); // } //--// public void Seek( int offset ) { SeekAbsolute( m_currentPosition + offset ); } public void SeekAbsolute( int newPosition ) { if(newPosition < m_startPosition || newPosition > m_endPosition) { throw new IndexOutOfRangeException(); } m_currentPosition = newPosition; } public void Align( int count ) { int rem = this.Position % count; if(rem != 0) { Seek( count - rem ); } } public void AlignAbsolute( int count ) { int rem = m_currentPosition % count; if(rem != 0) { Seek( count - rem ); } } public void Rewind() { m_currentPosition = m_startPosition; } public bool IsEOF { get { return m_currentPosition == m_endPosition; } } public int Length { get { return m_endPosition - m_startPosition; } } public int Position { get { return m_currentPosition - m_startPosition; } set { int newPosition = m_startPosition + value; if(newPosition < m_startPosition || newPosition >= m_endPosition) { throw new IndexOutOfRangeException(); } m_currentPosition = newPosition; } } //--// public override string ToString() { StringBuilder sb = new StringBuilder(); AppendAsString( sb, true ); return sb.ToString(); } public void AppendAsString( StringBuilder sb , bool whole ) { int pos = whole ? m_startPosition : m_currentPosition; AppendAsString( sb, m_image, pos, m_endPosition - pos ); } //--// public static void AppendAsString( StringBuilder sb , byte[] buffer ) { AppendAsString( sb, buffer, 0, buffer.Length ); } public static void AppendAsString( StringBuilder sb , byte[] buffer , int offset , int count ) { int end = count + offset; bool fFirst = true; while(offset < end) { if(fFirst) { fFirst = false; } else { sb.Append( "," ); } sb.Append( "0x" ); sb.Append( buffer[offset++].ToString( "x2" ) ); } } } } ================================================ FILE: Zelig/Zelig/CompileTime/MetaData/Importer/ArrayWriter.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // using System; using System.Collections.Generic; using System.Text; namespace Microsoft.Zelig.MetaData.Importer { public unsafe class ArrayWriter { private static readonly System.Text.UTF8Encoding s_stringEncoding = new System.Text.UTF8Encoding(); // // State // System.IO.MemoryStream m_image; // // Constructor Methods // public ArrayWriter() { m_image = new System.IO.MemoryStream(); } // // Helper Methods // public void SetLength( int length ) { m_image.SetLength( length ); } public void Seek( int offset ) { if(offset > m_image.Length) { SetLength( offset ); } m_image.Seek( offset, System.IO.SeekOrigin.Begin ); } public void Write( bool val ) { Write( val ? 1 : 0 ); } public void Write( byte val ) { m_image.WriteByte( val ); } public void Write( ushort val ) { Write( (byte) val ); Write( (byte)(val >> 8) ); } public void Write( uint val ) { Write( (byte) val ); Write( (byte)(val >> 8) ); Write( (byte)(val >> 16) ); Write( (byte)(val >> 24) ); } public void Write( ulong val ) { Write( (uint) val ); Write( (uint)(val >> 32) ); } public void Write( sbyte val ) { Write( (byte)val ); } public void Write( short val ) { Write( (ushort)val ); } public void Write( int val ) { Write( (uint)val ); } public void Write( long val ) { Write( (ulong)val ); } public void Write( char val ) { Write( (ushort)val ); } public unsafe void Write( float val ) { Write( *((uint*)&val) ); } public unsafe void Write( double val ) { Write( *((ulong*)&val) ); } public void Write( ArrayWriter sub ) { byte[] buf = sub.m_image.ToArray(); m_image.Write( buf, 0, buf.Length ); } //--// public void WriteCompressedUInt32( uint val ) { if(val < 0x80) { // encoded in a single byte Write( (byte)val ); return; } else if(val < 0x4000) { // encoded in two bytes Write( (byte)((val >> 8) & 0x3F | 0x80) ); Write( (byte)((val ) ) ); } else { // encoded in four bytes Write( (byte)((val >> 24) & 0x3F | 0xC0) ); Write( (byte)((val >> 16) ) ); Write( (byte)((val >> 8) ) ); Write( (byte)((val ) ) ); } } public void WriteCompressedString( string val ) { if(val == null) { Write( (byte)0xFF ); } else { uint len = (uint)val.Length; WriteCompressedUInt32( len ); Write( s_stringEncoding.GetBytes( val ) ); } } public void WriteCompressedToken( int val ) { TokenType tokenType = MetaData.UnpackTokenAsType ( val ); uint tokenIdx = (uint)MetaData.UnpackTokenAsIndex( val ); uint codedToken; switch(tokenType) { case TokenType.TypeDef : codedToken = 0; break; case TokenType.TypeRef : codedToken = 1; break; case TokenType.TypeSpec: codedToken = 2; break; default : throw IllegalMetaDataFormatException.Create( "Bad signature token: {0}", val ); } WriteCompressedUInt32( tokenIdx << 2 | codedToken ); } public void Write( Guid val ) { Write( val.ToByteArray() ); } //--//--//--//--// public void Write( byte[] val ) { Write( val, 0, val.Length ); } public void Write( byte[] val , int offset , int count ) { m_image.Write( val, offset, count ); } //--// public void Write( char[] val ) { Write( val, 0, val.Length ); } public void Write( char[] val , int offset , int count ) { while(count-- > 0) { Write( val[offset++] ); } } //--// public void Write( int[] val ) { Write( val, 0, val.Length ); } public void Write( int[] val , int offset , int count ) { while(count-- > 0) { Write( val[offset++] ); } } //--// public void Write( uint[] val ) { Write( val, 0, val.Length ); } public void Write( uint[] val , int offset , int count ) { while(count-- > 0) { Write( val[offset++] ); } } //--// public void WriteZeroTerminatedUInt8String( string val ) { foreach(char c in val) { Write( (byte)c ); } Write( (byte)0 ); } public void WriteZeroTerminatedUTF8String( string val ) { foreach(byte b in s_stringEncoding.GetBytes( val )) { Write( b ); } Write( (byte)0 ); } public void WriteUInt16String( string val ) { foreach(char c in val) { Write( c ); } } //--// public void Align( int count ) { int rem = this.Length % count; while(rem-- != 0) { m_image.WriteByte( 0 ); } } public byte[] ToArray() { return m_image.ToArray(); } // // Access Methods // public int Length { get { return (int)m_image.Length; } } } } ================================================ FILE: Zelig/Zelig/CompileTime/MetaData/Importer/EHClause.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // // // Originally based on the Bartok code base. // using System; using System.Collections.Generic; using System.Text; namespace Microsoft.Zelig.MetaData.Importer { public class EHClause { // // Internal Classes // public enum ExceptionFlag { None = 0x0000, Filter = 0x0001, Finally = 0x0002, Fault = 0x0004, } // // State // private readonly ExceptionFlag m_flags; private readonly int m_tryOffset; private readonly int m_tryEnd; private readonly int m_handlerOffset; private readonly int m_handlerEnd; private readonly int m_filterOffset; private IMetaDataTypeDefOrRef m_classObject; // // Constructor Methods // internal EHClause( int flags , int tryOffset , int tryLength , int handlerOffset , int handlerLength , int filterOffset , IMetaDataTypeDefOrRef classObject ) { m_flags = (ExceptionFlag)flags; m_tryOffset = tryOffset; m_tryEnd = tryOffset + tryLength; m_handlerOffset = handlerOffset; m_handlerEnd = handlerOffset + handlerLength; m_filterOffset = filterOffset; m_classObject = classObject; } internal Normalized.EHClause Normalize( MetaDataNormalizationContext context ) { Normalized.EHClause ehNew = new Normalized.EHClause(); ehNew.m_flags = (Normalized.EHClause.ExceptionFlag)m_flags; ehNew.m_tryOffset = m_tryOffset; ehNew.m_tryEnd = m_tryEnd; ehNew.m_handlerOffset = m_handlerOffset; ehNew.m_handlerEnd = m_handlerEnd; ehNew.m_filterOffset = m_filterOffset; context.GetNormalizedObject( m_classObject, out ehNew.m_classObject, MetaDataNormalizationMode.Default ); return ehNew; } // // Access Methods // public ExceptionFlag Flags { get { return m_flags; } } public int TryOffset { get { return m_tryOffset; } } public int TryEnd { get { return m_tryEnd; } } public int HandlerOffset { get { return m_handlerOffset; } } public int HandlerEnd { get { return m_handlerEnd; } } public int FilterOffset { get { return m_filterOffset; } } public IMetaDataTypeDefOrRef TypeObject { get { return m_classObject; } } // // Debug Methods // public override String ToString() { System.Text.StringBuilder sb = new System.Text.StringBuilder( "EHClause(" ); sb.Append( m_flags ); sb.Append( ",try(" ); sb.Append( m_tryOffset.ToString( "x" ) ); sb.Append( "," ); sb.Append( m_tryEnd.ToString( "x" ) ); sb.Append( "),handler(" ); sb.Append( m_handlerOffset.ToString( "x" ) ); sb.Append( "," ); sb.Append( m_handlerEnd.ToString( "x" ) ); sb.Append( ")," ); sb.Append( m_filterOffset.ToString( "x" ) ); sb.Append( "," ); sb.Append( m_classObject ); sb.Append( ")" ); return sb.ToString(); } } } ================================================ FILE: Zelig/Zelig/CompileTime/MetaData/Importer/IllegalMetaDataFormatException.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // // // Originally based on the Bartok code base. // using System; using System.Collections.Generic; using System.Collections; using System.Reflection; using System.Text; namespace Microsoft.Zelig.MetaData.Importer { public class IllegalMetaDataFormatException : AbstractMetaDataException { // // Constructor Methods // private IllegalMetaDataFormatException( String reason ) : base( reason ) { } // // Helper Methods // public static IllegalMetaDataFormatException Create( string format , params object[] args ) { return new IllegalMetaDataFormatException( String.Format( format, args ) ); } } } ================================================ FILE: Zelig/Zelig/CompileTime/MetaData/Importer/Importer.csproj ================================================  Debug AnyCPU 9.0.21022 2.0 {186F31A3-EF89-4A25-B2D5-20060404AA01} Library Properties Microsoft.Zelig.MetaData.Importer Microsoft.Zelig.MetaData.Importer $(LlilumBuildRoot)\Host\obj\$(MSBuildProjectName)\ v4.5 true full false $(LlilumBuildRoot)\Host\bin\$(Configuration)\ DEBUG;TRACE prompt 4 true true AllRules.ruleset AnyCPU false pdbonly true $(LlilumBuildRoot)\Host\bin\$(Configuration)\ TRACE prompt 4 true true AllRules.ruleset AnyCPU false $(LlilumBuildRoot)\Host\bin\$(Configuration)\ AnyCPU TRACE;DEBUG true true false {186F31A3-EF89-4A25-B2D5-20061218AA01} Common False {186F31A3-EF89-4A25-B2D5-20060510AA01} Normalized False 3.5 ================================================ FILE: Zelig/Zelig/CompileTime/MetaData/Importer/Instruction.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // // // Originally based on the Bartok code base. // using System; using System.Collections.Generic; using System.Collections; using System.Text; namespace Microsoft.Zelig.MetaData.Importer { public class Instruction { public abstract class Operand { internal abstract object Normalize( MetaDataNormalizationContext context ); } public class OperandInt : Operand { // // State // private readonly int m_value; // // Constructor Methods // internal OperandInt( int value ) { m_value = value; } internal override object Normalize( MetaDataNormalizationContext context ) { return m_value; } // // Access Methods // public int Value { get { return m_value; } } // // Debug Methods // public override String ToString() { return "OperandInt(0x" + m_value.ToString( "x" ) + "/" + m_value + ")"; } } public class OperandTarget : Operand { // // State // private readonly int m_target; // // Constructor Methods // internal OperandTarget( int target ) { m_target = target; } internal override object Normalize( MetaDataNormalizationContext context ) { return m_target; } // // Access Methods // public int Target { get { return m_target; } } // // Debug Methods // public override String ToString() { return "OperandTarget(IL_" + m_target.ToString( "x4" ) + ")"; } } public class OperandSingle : Operand { // // State // private readonly float m_value; // // Constructor Methods // internal OperandSingle( float value ) { m_value = value; } internal override object Normalize( MetaDataNormalizationContext context ) { return m_value; } // // Access Methods // public float Value { get { return m_value; } } // // Debug Methods // public override String ToString() { return "OperandSingle(" + m_value + ")"; } } public class OperandDouble : Operand { // // State // private readonly double m_value; // // Constructor Methods // internal OperandDouble( double value ) { m_value = value; } internal override object Normalize( MetaDataNormalizationContext context ) { return m_value; } // // Access Methods // public double Value { get { return m_value; } } // // Debug Methods // public override String ToString() { return "OperandDouble(" + m_value + ")"; } } public class OperandTargetArray : Operand { // // State // private readonly int[] m_targets; // // Constructor Methods // internal OperandTargetArray( int[] targets ) { m_targets = targets; } internal override object Normalize( MetaDataNormalizationContext context ) { return m_targets; } // // Access Methods // public int[] Targets { get { return m_targets; } } // // Debug Methods // public override String ToString() { System.Text.StringBuilder sb = new System.Text.StringBuilder( "OperandTargetArray(" ); if(m_targets.Length > 0) { for(int i = 0; i < m_targets.Length; i++) { if(i != 0) { sb.Append( "," ); } sb.Append( "IL_" ); sb.Append( m_targets[i].ToString( "x4" ) ); } } sb.Append( ")" ); return sb.ToString(); } } public class OperandByteArray : Operand { // // State // private readonly byte[] m_value; // // Constructor Methods // internal OperandByteArray( byte[] value ) { m_value = value; } internal override object Normalize( MetaDataNormalizationContext context ) { return m_value; } // // Access Methods // public byte[] Value { get { return m_value; } } // // Debug Methods // public override String ToString() { System.Text.StringBuilder sb = new System.Text.StringBuilder( "OperandByteArray(" ); if(m_value.Length > 0) { for(int i = 0; i < m_value.Length; i++) { if(i != 0) { sb.Append( "," ); } sb.Append( m_value[i] ); } } sb.Append( ")" ); return sb.ToString(); } } public class OperandLong : Operand { // // State // private readonly long m_value; // // Constructor Methods // internal OperandLong( long value ) { m_value = value; } internal override object Normalize( MetaDataNormalizationContext context ) { return m_value; } // // Access Methods // public long Value { get { return m_value; } } // // Debug Methods // public override String ToString() { return "OperandLong(" + m_value + ")"; } } public class OperandString : Operand { // // State // private readonly String m_value; // // Constructor Methods // internal OperandString( String value ) { m_value = value; } internal override object Normalize( MetaDataNormalizationContext context ) { return m_value; } // // Access Methods // public String Value { get { return m_value; } } // // Debug Methods // public override String ToString() { return "OperandString(\"" + m_value + "\")"; } } public class OperandObject : Operand { // // State // private MetaDataObject m_value; // // Constructor Methods // internal OperandObject( MetaDataObject value ) { m_value = value; } internal override object Normalize( MetaDataNormalizationContext context ) { Normalized.MetaDataObject res; context.GetNormalizedObject( m_value, out res, MetaDataNormalizationMode.Default ); return res; } // // Access Methods // public MetaDataObject Value { get { return m_value; } } // // Debug Methods // public override String ToString() { return "OperandObject(" + m_value + ")"; } } //--// // // State // private readonly Normalized.Instruction.OpcodeInfo m_opcodeInfo; private readonly Operand m_operand; private readonly Debugging.DebugInfo m_debugInfo; // // Constructor Methods // internal Instruction( Normalized.Instruction.OpcodeInfo opcodeInfo , Operand operand , Debugging.DebugInfo debugInfo ) { m_opcodeInfo = opcodeInfo; m_operand = operand; m_debugInfo = debugInfo; } internal Normalized.Instruction Normalize( MetaDataNormalizationContext context ) { object operand = null; if(m_operand != null) { operand = m_operand.Normalize( context ); } Normalized.Instruction inst = new Normalized.Instruction( m_opcodeInfo, operand, m_debugInfo ); return inst; } // // Access Methods // public Normalized.Instruction.OpcodeInfo Operator { get { return m_opcodeInfo; } } public Operand Argument { get { return m_operand; } } public Debugging.DebugInfo DebugInfo { get { return m_debugInfo; } } // // Debug Methods // public override String ToString() { if(m_debugInfo != null) { return (m_opcodeInfo.Name + m_debugInfo.ToString()); } else { return (m_opcodeInfo.Name); } } } } ================================================ FILE: Zelig/Zelig/CompileTime/MetaData/Importer/LogWriter.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // using System; using System.Collections.Generic; using System.Text; namespace Microsoft.Zelig.MetaData.Importer { public class LogWriter { // // State // System.IO.TextWriter m_writer; // // Constructor Methods // public LogWriter( System.IO.TextWriter writer ) { m_writer = writer; } public void WriteLine() { m_writer.WriteLine(); } public void WriteLine( string s ) { m_writer.WriteLine( s ); } public void WriteLine( string s , object arg1 ) { m_writer.WriteLine( s, arg1 ); } public void WriteLine( string s , object arg1 , object arg2 ) { m_writer.WriteLine( s, arg1, arg2 ); } public void WriteLine( string s , object arg1 , object arg2 , object arg3 ) { m_writer.WriteLine( s, arg1, arg2, arg3 ); } public void Flush() { m_writer.Flush(); } } } ================================================ FILE: Zelig/Zelig/CompileTime/MetaData/Importer/MarshalSpec.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // // // Originally based on the Bartok code base. // using System; using System.Collections.Generic; using System.Text; namespace Microsoft.Zelig.MetaData.Importer { public abstract class MarshalSpec { // // Constructor Methods // internal static MarshalSpec Create( ArrayReader reader ) { NativeTypes kind = (NativeTypes)reader.ReadCompressedUInt32(); switch(kind) { case NativeTypes.BOOLEAN : case NativeTypes.I1 : case NativeTypes.U1 : case NativeTypes.I2 : case NativeTypes.U2 : case NativeTypes.I4 : case NativeTypes.U4 : case NativeTypes.I8 : case NativeTypes.U8 : case NativeTypes.R4 : case NativeTypes.R8 : case NativeTypes.CURRENCY : case NativeTypes.BSTR : case NativeTypes.LPSTR : case NativeTypes.LPWSTR : case NativeTypes.LPTSTR : case NativeTypes.IUNKNOWN : case NativeTypes.IDISPATCH : case NativeTypes.STRUCT : case NativeTypes.INTF : case NativeTypes.INT : case NativeTypes.UINT : case NativeTypes.BYVALSTR : case NativeTypes.ANSIBSTR : case NativeTypes.TBSTR : case NativeTypes.VARIANTBOOL: case NativeTypes.FUNC : case NativeTypes.ASANY : case NativeTypes.LPSTRUCT : case NativeTypes.ERROR : case NativeTypes.MAX : { Signature.CheckEndOfSignature( reader ); return new MarshalSpecNative( kind ); } case NativeTypes.SAFEARRAY: { VariantTypes elemType; if(reader.IsEOF) { elemType = VariantTypes.VT_EMPTY; } else { elemType = (VariantTypes)reader.ReadCompressedUInt32(); } // APPCOMPACT: Some system assemblies add an extra byte to the marshalling spec. //Signature.CheckEndOfSignature( reader ); return new MarshalSpecSafeArray( elemType ); } case NativeTypes.FIXEDSYSSTRING: { uint elemCount = reader.ReadCompressedUInt32(); Signature.CheckEndOfSignature( reader ); return new MarshalSpecFixedString( elemCount ); } case NativeTypes.FIXEDARRAY: { uint elemCount = reader.ReadCompressedUInt32(); Signature.CheckEndOfSignature( reader ); return new MarshalSpecFixedArray( elemCount ); } case NativeTypes.CUSTOMMARSHALER: { String guid = reader.ReadCompressedString(); String unmanagedType = reader.ReadCompressedString(); String managedType = reader.ReadCompressedString(); String cookie = reader.ReadCompressedString(); Signature.CheckEndOfSignature( reader ); return new MarshalSpecCustom( guid, unmanagedType, managedType, cookie ); } case NativeTypes.ARRAY: { NativeTypes elemType = (NativeTypes)reader.ReadCompressedUInt32(); uint paramNumber = (reader.IsEOF ? 0 : reader.ReadCompressedUInt32()); uint extras = (reader.IsEOF ? 0 : reader.ReadCompressedUInt32()); // APPCOMPACT: Some system assemblies add an extra byte to the marshalling spec. //Signature.CheckEndOfSignature( reader ); return new MarshalSpecArray( elemType, paramNumber, extras ); } default: { throw new Exception( "Unknown marshal spec kind " + kind ); } } } public override abstract String ToString(); } public class MarshalSpecNative : MarshalSpec { // // State // private readonly NativeTypes m_kind; // // Constructor Methods // public MarshalSpecNative( NativeTypes kind ) { m_kind = kind; } // // Access Methods // public NativeTypes Kind { get { return m_kind; } } public override String ToString() { return "MarshalSpecNative(" + m_kind + ")"; } } public class MarshalSpecSafeArray : MarshalSpec { // // State // private readonly VariantTypes m_elemType; // // Constructor Methods // public MarshalSpecSafeArray( VariantTypes elemType ) { m_elemType = elemType; } // // Access Methods // public VariantTypes ElementType { get { return m_elemType; } } public override String ToString() { return "MarshalSpecSafeArray(" + m_elemType + ")"; } } public class MarshalSpecFixedString : MarshalSpec { // // State // private readonly uint m_elemCount; // // Constructor Methods // public MarshalSpecFixedString( uint elemCount ) { m_elemCount = elemCount; } // // Access Methods // public uint ElementCount { get { return m_elemCount; } } public override String ToString() { return "MarshalSpecFixedString(" + m_elemCount + ")"; } } public class MarshalSpecFixedArray : MarshalSpec { // // State // private readonly uint m_elemCount; // // Constructor Methods // public MarshalSpecFixedArray( uint elemCount ) { m_elemCount = elemCount; } // // Access Methods // public uint ElementCount { get { return m_elemCount; } } public override String ToString() { return "MarshalSpecFixedArray(" + m_elemCount + ")"; } } public class MarshalSpecCustom : MarshalSpec { // // State // private readonly String m_guid; private readonly String m_unmanagedType; private readonly String m_managedType; private readonly String m_cookie; // // Constructor Methods // public MarshalSpecCustom( String guid , String unmanagedType , String managedType , String cookie ) { m_guid = guid; m_unmanagedType = unmanagedType; m_managedType = managedType; m_cookie = cookie; } // // Access Methods // public String Guid { get { return m_guid; } } public String UnmanagedType { get { return m_unmanagedType; } } public String ManagedType { get { return m_managedType; } } public String Cookie { get { return m_cookie; } } public override String ToString() { return "MarshalSpecCustom(" + m_guid + "," + m_managedType + "->" + m_unmanagedType + "," + m_cookie + ")"; } } public class MarshalSpecArray : MarshalSpec { // // State // private readonly NativeTypes m_elemType; private readonly uint m_paramNumber; private readonly uint m_extras; // // Constructor Methods // public MarshalSpecArray( NativeTypes elemType , uint paramNumber , uint extras ) { m_elemType = elemType; m_paramNumber = paramNumber; m_extras = extras; } // // Access Methods // public NativeTypes ElementType { get { return m_elemType; } } public uint ParameterNumber { get { return m_paramNumber; } } public uint ExtraCount { get { return m_extras; } } public override String ToString() { return "MarshalSpecArray(" + m_elemType + "," + m_paramNumber + "," + m_extras + ")"; } } } ================================================ FILE: Zelig/Zelig/CompileTime/MetaData/Importer/MetaData.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // // // Originally based on the Bartok code base. // // Holder of MetaData information /********************************************************************** * * The Microsoft.Zelig.MetaData.Importer.MetaData* classes (except MetaData) * represent entries in the big table of meta data stored * away in URT binaries. Each class represents data from one kind of * entry in the table. Some of the information in other classes may * have been incorporated into the representatives (e.g., the * MetaDataMethod objects have lists of fields and methods). * * The MetaData objects contain the arrays of MetaData* objects * representing the metadata from a single URT binary. * * The Parser class is used to load meta data information from * binaries. A consumer of meta data information need not inspect * Parser.cs. * **********************************************************************/ using System; using System.Collections.Generic; using System.Text; namespace Microsoft.Zelig.MetaData.Importer { [Flags] public enum MetaDataLoaderFlags { Default = 0x00, LoadCode = 0x01, LoadSectionsFromExecutable = 0x02, LoadDebugInfo = 0x04, Messages = 0x08, } public sealed class MetaData : IMetaDataObject { internal class ObjectComparer : IEqualityComparer< IMetaDataNormalize > { public bool Equals( IMetaDataNormalize x , IMetaDataNormalize y ) { return Object.ReferenceEquals( x, y ); } public int GetHashCode( IMetaDataNormalize obj ) { return obj != null ? obj.GetHashCode() : 0; } } internal class SignatureComparer : IEqualityComparer< IMetaDataNormalizeSignature > { public bool Equals( IMetaDataNormalizeSignature x , IMetaDataNormalizeSignature y ) { return Object.ReferenceEquals( x, y ); } public int GetHashCode( IMetaDataNormalizeSignature obj ) { return obj != null ? obj.GetHashCode() : 0; } } // // State // internal String m_name; internal MetaDataMethod m_entryPoint; internal long m_imageBase; internal MetaDataObject[][] m_tables; internal MetaDataModule [] m_moduleArray; internal MetaDataTypeReference [] m_typeRefArray; internal MetaDataTypeDefinition [] m_typeDefArray; internal MetaDataField [] m_fieldArray; internal MetaDataMethod [] m_methodArray; internal MetaDataParam [] m_paramArray; internal MetaDataMemberRef [] m_memberRefArray; internal MetaDataConstant [] m_constantArray; internal MetaDataCustomAttribute [] m_customAttributeArray; internal MetaDataFieldMarshal [] m_fieldMarshalArray; internal MetaDataDeclSecurity [] m_declSecurityArray; internal MetaDataClassLayout [] m_classLayoutArray; internal MetaDataFieldLayout [] m_fieldLayoutArray; internal MetaDataStandAloneSig [] m_standAloneSigArray; internal MetaDataEvent [] m_eventArray; internal MetaDataProperty [] m_propertyArray; internal MetaDataMethodSemantics [] m_methodSemanticsArray; internal MetaDataMethodImpl [] m_methodImplArray; internal MetaDataModuleRef [] m_moduleRefArray; internal MetaDataTypeSpec [] m_typeSpecArray; internal MetaDataImplMap [] m_implMapArray; internal MetaDataFieldRVA [] m_fieldRVAArray; internal MetaDataAssembly [] m_assemblyArray; internal MetaDataAssemblyRef [] m_assemblyRefArray; internal MetaDataFile [] m_fileArray; internal MetaDataManifestResource [] m_manifestResourceArray; internal MetaDataGenericParam [] m_genericParamArray; internal MetaDataMethodSpec [] m_methodSpecArray; // // Constructor Methods // public static MetaData loadMetaData( String name , ISymbolResolverHelper symbolHelper , PELoader peLoader ) { return loadMetaData( name, symbolHelper, peLoader, MetaDataLoaderFlags.Default ); } public static MetaData loadMetaData( String name , ISymbolResolverHelper symbolHelper , PELoader peLoader , MetaDataLoaderFlags flags ) { Parser parser = new Parser( name, symbolHelper, peLoader, flags ); return parser.MetaData; } internal MetaData( String name ) { m_name = name; } //--// internal void AllocateNormalizedObject( MetaDataResolver.AssemblyPair pair , MetaDataNormalizationContext context ) { // // Already processed this phase? // if(pair.Phase >= context.Phase) { return; } switch(context.Phase) { case MetaDataNormalizationPhase.ResolutionOfAssemblyReferences: { Normalized.MetaDataAssembly asmlNew; context.GetNormalizedObject( this.Assembly, out asmlNew, MetaDataNormalizationMode.Allocate ); pair.Normalized = asmlNew; foreach(MetaDataAssemblyRef asmlRef in m_assemblyRefArray) { Normalized.MetaDataAssembly asmlRefNew; context.GetNormalizedObject( asmlRef, out asmlRefNew, MetaDataNormalizationMode.Allocate ); } } pair.Phase = MetaDataNormalizationPhase.ResolutionOfAssemblyReferences; return; } throw context.InvalidPhase( this ); } internal bool ExecuteNormalizationPhase( MetaDataResolver.AssemblyPair pair , MetaDataNormalizationContext context ) { // // Already processed this phase? // if(pair.Phase >= context.Phase) { return true; } Normalized.MetaDataAssembly asml = pair.Normalized; context = context.Push( asml ); switch(context.Phase) { case MetaDataNormalizationPhase.ConversionOfResources: { foreach(MetaDataManifestResource res in m_manifestResourceArray) { Normalized.MetaDataManifestResource resNew; context.GetNormalizedObject( res, out resNew, MetaDataNormalizationMode.Allocate ); } } break; case MetaDataNormalizationPhase.CreationOfTypeDefinitions: { foreach(MetaDataTypeDefinition td in m_typeDefArray) { Normalized.MetaDataTypeDefinitionBase tdNew; context.GetNormalizedObject( td, out tdNew, MetaDataNormalizationMode.Allocate ); } } break; case MetaDataNormalizationPhase.LinkingOfNestedClasses : case MetaDataNormalizationPhase.DiscoveryOfBuiltInTypes : case MetaDataNormalizationPhase.CreationOfTypeHierarchy : case MetaDataNormalizationPhase.CompletionOfTypeNormalization : case MetaDataNormalizationPhase.CreationOfFieldDefinitions : case MetaDataNormalizationPhase.CreationOfMethodDefinitions : case MetaDataNormalizationPhase.CompletionOfMethodNormalization: { foreach(MetaDataTypeDefinition td in m_typeDefArray) { context.ProcessPhase( td ); } } break; case MetaDataNormalizationPhase.CreationOfMethodImplDefinitions: { foreach(MetaDataMethodImpl mi in m_methodImplArray) { Normalized.MetaDataMethodImpl miNew; context.GetNormalizedObject( mi, out miNew, MetaDataNormalizationMode.Allocate ); } } break; case MetaDataNormalizationPhase.CompletionOfMethodImplNormalization: { foreach(MetaDataMethodImpl mi in m_methodImplArray) { context.ProcessPhase( mi ); } } break; case MetaDataNormalizationPhase.CreationOfSpecialArrayMethods: { Normalized.MetaDataTypeDefinitionArray[] tdToProcess = asml.PendingArrays.ToArray(); bool fDone = true; asml.PendingArrays.Clear(); foreach(Normalized.MetaDataTypeDefinitionArray array in tdToProcess) { if(array.m_methods == null) { fDone = false; asml.OtherTypes.Add( array ); if(array is Normalized.MetaDataTypeDefinitionArrayMulti) { Normalized.MetaDataTypeDefinitionArrayMulti arrayMulti = (Normalized.MetaDataTypeDefinitionArrayMulti)array; context.CreateSpecialMethods( arrayMulti ); } context.ImplementSpecialInterfaces( array ); } } if(fDone == false) { return false; } } break; case MetaDataNormalizationPhase.ResolutionOfTypeReferences: { foreach(MetaDataTypeReference trRef in m_typeRefArray) { Normalized.MetaDataTypeDefinitionBase tr; context.GetNormalizedObject( trRef, out tr, MetaDataNormalizationMode.Allocate ); } } break; case MetaDataNormalizationPhase.ResolutionOfEntryPoint: { context.GetNormalizedObject( m_entryPoint, out asml.m_entryPoint, MetaDataNormalizationMode.Default ); } break; case MetaDataNormalizationPhase.ResolutionOfCustomAttributes: { context.ProcessPhase( this.Assembly ); foreach(MetaDataTypeDefinition td in m_typeDefArray) { context.ProcessPhase( td ); } } break; default: throw context.InvalidPhase( this ); } pair.Phase = context.Phase; return true; } //--// public static int PackToken( TokenType tbl , int index ) { return (int)tbl << 24 | (index & 0x00FFFFFF); } public static TokenType UnpackTokenAsType( int token ) { return (TokenType)(token >> 24); } public static int UnpackTokenAsIndex( int token ) { return token & 0x00FFFFFF; } //--// // // Access Methods // public string Name { get { return m_name; } } public MetaDataMethod EntryPoint { get { return m_entryPoint; } } public long ImageBase { get { return m_imageBase; } } public MetaDataModule[] Modules { get { return m_moduleArray; } } public MetaDataTypeReference[] TypeRefs { get { return m_typeRefArray; } } public MetaDataTypeDefinition[] TypeDefs { get { return m_typeDefArray; } } public MetaDataField[] Fields { get { return m_fieldArray; } } public MetaDataMethod[] Methods { get { return m_methodArray; } } public MetaDataParam[] Parameters { get { return m_paramArray; } } public MetaDataMemberRef[] MemberRefs { get { return m_memberRefArray; } } public MetaDataConstant[] Constants { get { return m_constantArray; } } public MetaDataCustomAttribute[] CustomAttributes { get { return m_customAttributeArray; } } public MetaDataFieldMarshal[] FieldMarshals { get { return m_fieldMarshalArray; } } public MetaDataDeclSecurity[] DeclSecurities { get { return m_declSecurityArray; } } public MetaDataClassLayout[] ClassLayouts { get { return m_classLayoutArray; } } public MetaDataFieldLayout[] FieldLayouts { get { return m_fieldLayoutArray; } } public MetaDataStandAloneSig[] StandAloneSigs { get { return m_standAloneSigArray; } } public MetaDataEvent[] Events { get { return m_eventArray; } } public MetaDataProperty[] Properties { get { return m_propertyArray; } } public MetaDataMethodSemantics[] MethodSemanticss { get { return m_methodSemanticsArray; } } public MetaDataMethodImpl[] MethodImpls { get { return m_methodImplArray; } } public MetaDataModuleRef[] ModuleRefs { get { return m_moduleRefArray; } } public MetaDataTypeSpec[] TypeSpecs { get { return m_typeSpecArray; } } public MetaDataImplMap[] ImplMaps { get { return m_implMapArray; } } public MetaDataFieldRVA[] FieldRVAs { get { return m_fieldRVAArray; } } public MetaDataAssembly Assembly { get { return m_assemblyArray[0]; } } public MetaDataAssemblyRef[] AssemblyRefs { get { return m_assemblyRefArray; } } public MetaDataFile[] files { get { return m_fileArray; } } public MetaDataManifestResource[] ManifestResources { get { return m_manifestResourceArray; } } public MetaDataGenericParam[] GenericParams { get { return m_genericParamArray; } } public MetaDataMethodSpec[] MethodSpecs { get { return m_methodSpecArray; } } //--// public override String ToString() { return "MetaData(" + m_name + ")"; } } } ================================================ FILE: Zelig/Zelig/CompileTime/MetaData/Importer/MetaDataAssembly.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // // // Originally based on the Bartok code base. // using System; using System.Collections.Generic; using System.Text; namespace Microsoft.Zelig.MetaData.Importer { public sealed class MetaDataAssembly : MetaDataObject, IMetaDataHasDeclSecurity, IMetaDataNormalize { // // State // private MetaData m_owner; private HashAlgorithmID m_hashAlgorithmId; private MetaDataVersion m_version; private String m_name; private String m_locale; // // Constructor Methods // private MetaDataAssembly( int index ) : base( TokenType.Assembly, index ) { } // Helper methods to work around limitations in generics, see Parser.InitializeTable internal static MetaDataObject.CreateInstance GetCreator() { return new MetaDataObject.CreateInstance( Creator ); } private static MetaDataObject Creator( int index ) { return new MetaDataAssembly( index ); } //--// internal override void Parse( Parser parser , Parser.TableSchema ts , ArrayReader reader ) { m_owner = parser.MetaData; m_hashAlgorithmId = (HashAlgorithmID) reader.ReadInt32(); m_version = ParseVersion( parser, reader ); m_name = parser.readIndexAsString( reader ); m_locale = parser.readIndexAsString( reader ); } internal static MetaDataVersion ParseVersion( Parser parser , ArrayReader reader ) { MetaDataVersion ver = new MetaDataVersion(); ver.m_majorVersion = reader.ReadInt16(); ver.m_minorVersion = reader.ReadInt16(); ver.m_buildNumber = reader.ReadInt16(); ver.m_revisionNumber = reader.ReadInt16(); ver.m_flags = (AssemblyFlags) reader.ReadInt32(); ver.m_publicKey = parser.readIndexAsBlob( reader ); return ver; } // // IMetaDataNormalize methods // Normalized.MetaDataObject IMetaDataNormalize.AllocateNormalizedObject( MetaDataNormalizationContext context ) { Normalized.MetaDataAssembly res = new Normalized.MetaDataAssembly( context.UniqueDictionary, m_token ); res.m_hashAlgorithmId = m_hashAlgorithmId; res.m_version = m_version; res.m_name = m_name; res.m_locale = m_locale; return res; } void IMetaDataNormalize.ExecuteNormalizationPhase( Normalized.IMetaDataObject obj , MetaDataNormalizationContext context ) { Normalized.MetaDataAssembly asml = (Normalized.MetaDataAssembly)obj; switch(context.Phase) { case MetaDataNormalizationPhase.ResolutionOfCustomAttributes: { context.GetNormalizedObjectList( this.CustomAttributes, out asml.m_customAttributes, MetaDataNormalizationMode.Allocate ); } return; } throw context.InvalidPhase( this ); } // // Access Methods // public MetaData Owner { get { return m_owner; } } public HashAlgorithmID HashAlgorithmId { get { return m_hashAlgorithmId; } } public MetaDataVersion Version { get { return m_version; } } public String Name { get { return m_name; } } public String Locale { get { return m_locale; } } // // Debug Methods // public override String ToString() { System.Text.StringBuilder sb = new System.Text.StringBuilder( "MetaDataAssembly(" ); sb.Append( m_hashAlgorithmId ); sb.Append( "," ); sb.Append( m_version ); sb.Append( "," ); sb.Append( m_name ); sb.Append( "," ); sb.Append( m_locale ); sb.Append( ")" ); return sb.ToString(); } } } ================================================ FILE: Zelig/Zelig/CompileTime/MetaData/Importer/MetaDataAssemblyRef.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // // // Originally based on the Bartok code base. // using System; using System.Collections.Generic; using System.Text; namespace Microsoft.Zelig.MetaData.Importer { public sealed class MetaDataAssemblyRef : MetaDataObject, IMetaDataImplementation, IMetaDataResolutionScope, IMetaDataNormalize { // // State // private MetaDataVersion m_version; private String m_name; private String m_locale; private byte[] m_hashValue; // // Constructor Methods // private MetaDataAssemblyRef( int index ) : base( TokenType.AssemblyRef, index ) { } // Helper methods to work around limitations in generics, see Parser.InitializeTable internal static MetaDataObject.CreateInstance GetCreator() { return new MetaDataObject.CreateInstance( Creator ); } private static MetaDataObject Creator( int index ) { return new MetaDataAssemblyRef( index ); } //--// internal override void Parse( Parser parser , Parser.TableSchema ts , ArrayReader reader ) { m_version = MetaDataAssembly.ParseVersion( parser, reader ); m_name = parser.readIndexAsString ( reader ); m_locale = parser.readIndexAsString ( reader ); m_hashValue = parser.readIndexAsBlob ( reader ); } // // IMetaDataNormalize methods // Normalized.MetaDataObject IMetaDataNormalize.AllocateNormalizedObject( MetaDataNormalizationContext context ) { MetaDataResolver.AssemblyPair pair = context.FindAssembly( m_name, m_version ); return pair.Normalized; } void IMetaDataNormalize.ExecuteNormalizationPhase( Normalized.IMetaDataObject obj , MetaDataNormalizationContext context ) { throw context.InvalidPhase( this ); } // // Access Methods // public MetaDataVersion Version { get { return m_version; } } public String Name { get { return m_name; } } public String Locale { get { return m_locale; } } public byte[] HashValue { get { return m_hashValue; } } // // Debug Methods // public override String ToString() { System.Text.StringBuilder sb = new System.Text.StringBuilder( "MetaDataAssemblyRef(" ); sb.Append( m_version ); sb.Append( "," ); sb.Append( m_name ); sb.Append( "," ); sb.Append( m_locale ); sb.Append( ",[" ); ArrayReader.AppendAsString( sb, m_hashValue ); sb.Append( "])" ); return sb.ToString(); } } } ================================================ FILE: Zelig/Zelig/CompileTime/MetaData/Importer/MetaDataClassLayout.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // // // Originally based on the Bartok code base. // using System; using System.Collections.Generic; using System.Text; namespace Microsoft.Zelig.MetaData.Importer { public sealed class MetaDataClassLayout : MetaDataObject, IMetaDataNormalize { // // State // private short m_packingSize; private int m_classSize; private MetaDataTypeDefinition m_parent; // // Constructor Methods // private MetaDataClassLayout( int index ) : base( TokenType.ClassLayout, index ) { } // Helper methods to work around limitations in generics, see Parser.InitializeTable internal static MetaDataObject.CreateInstance GetCreator() { return new MetaDataObject.CreateInstance( Creator ); } private static MetaDataObject Creator( int index ) { return new MetaDataClassLayout( index ); } //--// internal override void Parse( Parser parser , Parser.TableSchema ts , ArrayReader reader ) { Parser.IndexReader parentReader = ts.m_columns[2].m_reader; int parentIndex; m_packingSize = reader.ReadInt16(); m_classSize = reader.ReadInt32(); parentIndex = parentReader( reader ); m_parent = parser.getTypeDef( parentIndex ); m_parent.SetClassLayout( this ); } // // IMetaDataNormalize methods // Normalized.MetaDataObject IMetaDataNormalize.AllocateNormalizedObject( MetaDataNormalizationContext context ) { switch(context.Phase) { case MetaDataNormalizationPhase.CompletionOfTypeNormalization: { Normalized.MetaDataClassLayout cl = new Normalized.MetaDataClassLayout( m_token ); cl.m_packingSize = m_packingSize; cl.m_classSize = m_classSize; return cl; } } throw context.InvalidPhase( this ); } void IMetaDataNormalize.ExecuteNormalizationPhase( Normalized.IMetaDataObject obj , MetaDataNormalizationContext context ) { throw context.InvalidPhase( this ); } // // Access Methods // public short PackingSize { get { return m_packingSize; } } public int ClassSize { get { return m_classSize; } } public MetaDataTypeDefinition Parent { get { return m_parent; } } // // Debug Methods // public override String ToString() { return "MetaDataClassLayout(" + m_packingSize + "," + m_classSize + "," + m_parent + ")"; } } } ================================================ FILE: Zelig/Zelig/CompileTime/MetaData/Importer/MetaDataConstant.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // // // Originally based on the Bartok code base. // using System; using System.Collections.Generic; using System.Text; namespace Microsoft.Zelig.MetaData.Importer { public sealed class MetaDataConstant : MetaDataObject, IMetaDataNormalize { // // State // private ElementTypes m_type; private IMetaDataHasConstant m_parent; private byte[] m_valueBuffer; // // Constructor Methods // private MetaDataConstant( int index ) : base( TokenType.Constant, index ) { } // Helper methods to work around limitations in generics, see Parser.InitializeTable internal static MetaDataObject.CreateInstance GetCreator() { return new MetaDataObject.CreateInstance( Creator ); } private static MetaDataObject Creator( int index ) { return new MetaDataConstant( index ); } //--// internal override void Parse( Parser parser , Parser.TableSchema ts , ArrayReader reader ) { Parser.IndexReader parentReader = ts.m_columns[1].m_reader; byte padding; int parentIndex; m_type = (ElementTypes) reader.ReadUInt8(); padding = reader.ReadUInt8(); parentIndex = parentReader ( reader ); m_valueBuffer = parser.readIndexAsBlob( reader ); m_parent = parser.getHasConstant( parentIndex ); if(m_parent is MetaDataField) { MetaDataField parentField = (MetaDataField)m_parent; parentField.SetConstant( this ); } if(m_parent is MetaDataParam) { MetaDataParam parentParam = (MetaDataParam)m_parent; parentParam.SetConstant( this ); } if(m_parent is MetaDataProperty) { MetaDataProperty parentProperty = (MetaDataProperty)m_parent; parentProperty.SetConstant( this ); } } // // IMetaDataNormalize methods // Normalized.MetaDataObject IMetaDataNormalize.AllocateNormalizedObject( MetaDataNormalizationContext context ) { switch(context.Phase) { case MetaDataNormalizationPhase.CreationOfFieldDefinitions: { Normalized.MetaDataConstant constNew = new Normalized.MetaDataConstant( m_token ); constNew.m_value = this.Value; return constNew; } } throw context.InvalidPhase( this ); } void IMetaDataNormalize.ExecuteNormalizationPhase( Normalized.IMetaDataObject obj , MetaDataNormalizationContext context ) { throw context.InvalidPhase( this ); } // // Access Methods // public ElementTypes Type { get { return m_type; } } // May be one of MetaData{Field,ParamDef,Property} public IMetaDataHasConstant Parent { get { return m_parent; } } public byte[] ValueBuffer { get { return m_valueBuffer; } } public Object ValueToType( ElementTypes type ) { if(m_type == type || SameSizeType( type, this.Type )) { return ValueFromBuffer( type, this.ValueBuffer ); } else { long value = LongValueFromBuffer( this.Type, this.ValueBuffer ); switch(type) { case ElementTypes.BOOLEAN: return (value != 0) ? true : false; case ElementTypes.I1 : return (sbyte )value; case ElementTypes.U1 : return (byte )value; case ElementTypes.CHAR : return (char )value; case ElementTypes.I2 : return (short )value; case ElementTypes.U2 : return (ushort)value; case ElementTypes.I4 : return (int )value; case ElementTypes.U4 : return (uint )value; case ElementTypes.I8 : return (long )value; case ElementTypes.U8 : return (ulong )value; default : return value; } } } private bool SameSizeType( ElementTypes type1 , ElementTypes type2 ) { switch(type1) { case ElementTypes.BOOLEAN: case ElementTypes.I1: case ElementTypes.U1: switch(type2) { case ElementTypes.BOOLEAN: case ElementTypes.I1: case ElementTypes.U1: return true; } break; case ElementTypes.CHAR: case ElementTypes.I2: case ElementTypes.U2: switch(type2) { case ElementTypes.CHAR: case ElementTypes.I2: case ElementTypes.U2: return true; } break; case ElementTypes.I4: case ElementTypes.U4: switch(type2) { case ElementTypes.I4: case ElementTypes.U4: return true; } break; case ElementTypes.I8: case ElementTypes.U8: switch(type2) { case ElementTypes.I8: case ElementTypes.U8: return true; } break; case ElementTypes.U: case ElementTypes.I: switch(type2) { case ElementTypes.U: case ElementTypes.I: return true; } break; } return false; } public Object Value { get { return ValueFromBuffer( this.Type, this.ValueBuffer ); } } private static long LongValueFromBuffer( ElementTypes type , byte[] buffer ) { ArrayReader reader = new ArrayReader( buffer ); switch(type) { case ElementTypes.BOOLEAN: return reader.ReadBoolean() ? 1L : 0L; case ElementTypes.CHAR : return (long)reader.ReadChar (); case ElementTypes.I1 : return (long)reader.ReadInt8 (); case ElementTypes.U1 : return (long)reader.ReadUInt8 (); case ElementTypes.I2 : return (long)reader.ReadInt16 (); case ElementTypes.U2 : return (long)reader.ReadUInt16(); case ElementTypes.I4 : return (long)reader.ReadInt32 (); case ElementTypes.U4 : return (long)reader.ReadUInt32(); case ElementTypes.I8 : return (long)reader.ReadInt64 (); case ElementTypes.U8 : return (long)reader.ReadUInt64(); case ElementTypes.R4 : return (long)reader.ReadSingle(); case ElementTypes.R8 : return (long)reader.ReadDouble(); default: throw IllegalMetaDataFormatException.Create( "Unknown type of constant: {0}", type ); } } private static Object ValueFromBuffer( ElementTypes type , byte[] buffer ) { ArrayReader reader = new ArrayReader( buffer ); switch(type) { case ElementTypes.BOOLEAN: return reader.ReadBoolean(); case ElementTypes.CHAR : return reader.ReadChar (); case ElementTypes.I1 : return reader.ReadInt8 (); case ElementTypes.U1 : return reader.ReadUInt8 (); case ElementTypes.I2 : return reader.ReadInt16 (); case ElementTypes.U2 : return reader.ReadUInt16 (); case ElementTypes.I4 : return reader.ReadInt32 (); case ElementTypes.U4 : return reader.ReadUInt32 (); case ElementTypes.I8 : return reader.ReadInt64 (); case ElementTypes.U8 : return reader.ReadUInt64 (); case ElementTypes.R4 : return reader.ReadSingle (); case ElementTypes.R8 : return reader.ReadDouble (); case ElementTypes.STRING : return reader.ReadUInt16String( buffer.Length / 2 ); default: throw IllegalMetaDataFormatException.Create( "Unknown type of constant: {0}", type ); } } // // Debug Methods // public override String ToString() { System.Text.StringBuilder sb = new System.Text.StringBuilder( "MetaDataConstant(" ); sb.Append( m_type ); sb.Append( "," ); sb.Append( m_parent ); sb.Append( "," ); sb.Append( this.Value ); sb.Append( ")" ); return sb.ToString(); } } } ================================================ FILE: Zelig/Zelig/CompileTime/MetaData/Importer/MetaDataCustomAttribute.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // // // Originally based on the Bartok code base. // using System; using System.Collections.Generic; using System.Text; namespace Microsoft.Zelig.MetaData.Importer { public sealed class MetaDataCustomAttribute : MetaDataObject, IMetaDataNormalize { // // State // private IMetaDataHasCustomAttribute m_parent; private IMetaDataCustomAttributeType m_type; private ArrayReader m_buffer; // // Constructor Methods // private MetaDataCustomAttribute( int index ) : base( TokenType.CustomAttribute, index ) { } // Helper methods to work around limitations in generics, see Parser.InitializeTable internal static MetaDataObject.CreateInstance GetCreator() { return new MetaDataObject.CreateInstance( Creator ); } private static MetaDataObject Creator( int index ) { return new MetaDataCustomAttribute( index ); } //--// internal override void Parse( Parser parser , Parser.TableSchema ts , ArrayReader reader ) { Parser.IndexReader parentReader = ts.m_columns[0].m_reader; Parser.IndexReader typeReader = ts.m_columns[1].m_reader; int parentIndex; int typeIndex; parentIndex = parentReader ( reader ); typeIndex = typeReader ( reader ); m_buffer = new ArrayReader( parser.readIndexAsBlob( reader ) ); m_parent = parser.getHasCustomAttribute ( parentIndex ); m_type = parser.getCustomAttributeType( typeIndex ); ((MetaDataObject)m_parent).AddCustomAttribute( this ); //// custom attribute starts with a prolog with value of 0x0001 //if(this.valueBuffer.Length < 2) //{ // Console.Out.WriteLine( "WARNING: Custome Attrbute should have at least two bytes in size" ); //} } // // IMetaDataNormalize methods // Normalized.MetaDataObject IMetaDataNormalize.AllocateNormalizedObject( MetaDataNormalizationContext context ) { switch(context.Phase) { case MetaDataNormalizationPhase.ResolutionOfCustomAttributes: { Normalized.MetaDataMethodBase method; context.GetNormalizedObject( m_type, out method, MetaDataNormalizationMode.Default ); if(method.Name != ".ctor") { throw IllegalMetaDataFormatException.Create( "Custom attribute with unexpected method name: {0}", method.Name ); } ArrayReader reader = new ArrayReader( m_buffer, 0 ); if(reader.ReadUInt8() != 0x01 || reader.ReadUInt8() != 0x00 ) { throw IllegalMetaDataFormatException.Create( "Custom Attribute doesn't start with 0x0001!" ); } Normalized.SignatureMethod signature = method.Signature; Normalized.SignatureType[] parameters = signature.Parameters; int fixedCount = parameters.Length; Object[] fixedArgs = new Object[fixedCount]; for(int i = 0; i < fixedCount; i++) { Normalized.SignatureType parameter = parameters[i]; Object value = ExtractParameter( parameter.Type, reader, context ); fixedArgs[i] = value; } short namedCount = ((reader.IsEOF) ? (short)0 : reader.ReadInt16()); ////if(namedCount > this.buffer.Length && this.Name == "System.Runtime.CompilerServices.RequiredAttributeAttribute") ////{ //// // Some CLR libraries have been compiled against a version of //// // mscorlib that had a fixed parameter to RequiredAttribute. //// // Simply ignore whatever the parameter was! //// namedCount = 0; ////} Normalized.MetaDataCustomAttribute.NamedArg[] namedArgs = new Normalized.MetaDataCustomAttribute.NamedArg[namedCount]; for(int i = 0; i < namedCount; i++) { SerializationTypes propOrField = (SerializationTypes)reader.ReadUInt8(); if(propOrField == SerializationTypes.FIELD || propOrField == SerializationTypes.PROPERTY) { SerializationTypes fieldType = (SerializationTypes)reader.ReadUInt8(); SerializationTypes arrayType = (SerializationTypes)ElementTypes.END; String enumName = null; switch(fieldType) { case SerializationTypes.SZARRAY: { arrayType = (SerializationTypes)reader.ReadUInt8(); if(arrayType == SerializationTypes.ENUM) { throw new Exception( "Not implemented: Array of ENUM for named field/property" ); } } break; case SerializationTypes.ENUM: { enumName = reader.ReadCompressedString(); } break; } String name = reader.ReadCompressedString(); Object value; if(fieldType == SerializationTypes.TAGGED_OBJECT) { fieldType = (SerializationTypes)reader.ReadUInt8(); } if(enumName != null) { Normalized.MetaDataTypeDefinitionBase typeDef = context.ResolveName( enumName ); value = ExtractEnumValue( typeDef, reader, context ); } else if(fieldType == SerializationTypes.SZARRAY) { value = ExtractArrayValue( arrayType, reader, context ); } else { value = ExtractValue( fieldType, reader, context ); } namedArgs[i] = new Normalized.MetaDataCustomAttribute.NamedArg( propOrField == SerializationTypes.FIELD, -1, name, fieldType, value ); } else { throw IllegalMetaDataFormatException.Create( "Unknown prop-or-field type: {0}", propOrField ); } } Normalized.MetaDataCustomAttribute ca = new Normalized.MetaDataCustomAttribute( context.GetAssemblyFromContext(), m_token ); ca.m_constructor = method; ca.m_fixedArgs = fixedArgs; ca.m_namedArgs = namedArgs; return ca.MakeUnique(); } } throw context.InvalidPhase( this ); } void IMetaDataNormalize.ExecuteNormalizationPhase( Normalized.IMetaDataObject obj , MetaDataNormalizationContext context ) { throw context.InvalidPhase( this ); } //--// private static Object ExtractParameter( Normalized.MetaDataTypeDefinitionAbstract type , ArrayReader reader , MetaDataNormalizationContext context ) { switch(type.ElementType) { case ElementTypes.VALUETYPE: { String superName = type.Extends.FullName; if(superName != "System.Enum") { throw IllegalMetaDataFormatException.Create( "Found valuetype that wasn't an Enum: {0}", type.Extends ); } if(!(type is Normalized.MetaDataTypeDefinition)) { throw IllegalMetaDataFormatException.Create( "Found valuetype that wasn't a simple type: {0}", type ); } return ExtractEnumValue( (Normalized.MetaDataTypeDefinition)type, reader, context ); } case ElementTypes.CLASS: { String className = type.FullName; // handle cases for reference types first if(className == "System.String") { return reader.ReadCompressedString(); } else if(className == "System.Object") { goto case ElementTypes.OBJECT; } else if(className == "System.Type") { string typeName = reader.ReadCompressedString(); return context.ResolveName( typeName ); } // Enums are just ints, e.g. the case of AttributeTargets param for AttributeUsage attribute if (type.Extends.ElementType == ElementTypes.VALUETYPE) { return reader.ReadInt32(); } throw new Exception( "Not implemented: object encoding an array (class was " + type +")" ); } case ElementTypes.OBJECT: case (ElementTypes)SerializationTypes.TAGGED_OBJECT: { SerializationTypes objectType = (SerializationTypes)reader.ReadUInt8(); switch(objectType) { case SerializationTypes.ENUM: case SerializationTypes.TYPE: { return ExtractValue( objectType, reader, context ); } default: { throw new Exception( "Found OBJECT type with type " + objectType ); } } } case ElementTypes.SZARRAY: { Normalized.MetaDataTypeDefinitionArraySz typeArray = (Normalized.MetaDataTypeDefinitionArraySz)type; return ExtractArrayValue( typeArray.ObjectType, reader, context ); } default: { return ExtractValue( (SerializationTypes)type.ElementType, reader, context ); } } } private static Object ExtractValue( SerializationTypes type , ArrayReader reader , MetaDataNormalizationContext context ) { switch(type) { case SerializationTypes.BOOLEAN: return reader.ReadBoolean(); case SerializationTypes.CHAR : return (char)reader.ReadUInt16 (); case SerializationTypes.I1 : return reader.ReadInt8 (); case SerializationTypes.U1 : return reader.ReadUInt8 (); case SerializationTypes.I2 : return reader.ReadInt16 (); case SerializationTypes.U2 : return reader.ReadUInt16 (); case SerializationTypes.I4 : return reader.ReadInt32 (); case SerializationTypes.U4 : return reader.ReadUInt32 (); case SerializationTypes.I8 : return reader.ReadInt64 (); case SerializationTypes.U8 : return reader.ReadUInt64 (); case SerializationTypes.R4 : return reader.ReadSingle (); case SerializationTypes.R8 : return reader.ReadDouble (); case SerializationTypes.STRING: return reader.ReadCompressedString(); case SerializationTypes.TYPE: { String typeName = reader.ReadCompressedString(); return context.ResolveName( typeName ); } case SerializationTypes.ENUM: { String typeName = reader.ReadCompressedString(); Normalized.MetaDataTypeDefinitionBase typeDef = context.ResolveName( typeName ); return ExtractEnumValue( typeDef, reader, context ); } default: throw IllegalMetaDataFormatException.Create( "Found unexpected type {0} in custom attribute parameter", type ); } } private static Object ExtractEnumValue( Normalized.MetaDataTypeDefinitionBase typeDef , ArrayReader reader , MetaDataNormalizationContext context ) { foreach(Normalized.MetaDataField classField in typeDef.Fields) { if((classField.Flags & FieldAttributes.Static) == 0) { if(classField.Name != "value__") { throw IllegalMetaDataFormatException.Create( "Found enum with non-static field '{0}'", classField.Name ); } return ExtractValue( (SerializationTypes)classField.FieldSignature.TypeSignature.Type.ElementType, reader, context ); } } throw IllegalMetaDataFormatException.Create( "Found enum without non-static field" ); } private static Object ExtractArrayValue( Normalized.MetaDataTypeDefinitionAbstract type , ArrayReader reader , MetaDataNormalizationContext context ) { int arraySize = reader.ReadInt32(); if(arraySize >= 0) { if(type.ElementType == ElementTypes.CLASS) { Object[] array = new Object[arraySize]; for(int i = 0; i < arraySize; i++) { array[i] = ExtractParameter( type, reader, context ); } return array; } else { return ExtractArrayValue( (SerializationTypes)type.ElementType, arraySize, reader, context ); } } else { throw new Exception( "Not implemented: custom attribute class array with negative length" ); } } private static Object ExtractArrayValue( SerializationTypes elementType , ArrayReader reader , MetaDataNormalizationContext context ) { int arraySize = reader.ReadInt32(); if(arraySize >= 0) { return ExtractArrayValue( elementType, arraySize, reader, context ); } else { throw new Exception( "Not implemented: custom atribute array with negative length" ); } } private static Object ExtractArrayValue( SerializationTypes elementType , int arraySize , ArrayReader reader , MetaDataNormalizationContext context ) { switch(elementType) { case SerializationTypes.BOOLEAN: { bool[] array = new bool[arraySize]; for(int i = 0; i < arraySize; i++) { array[i] = reader.ReadBoolean(); } return array; } case SerializationTypes.CHAR: { char[] array = new char[arraySize]; for(int i = 0; i < arraySize; i++) { array[i] = (char)reader.ReadUInt16(); } return array; } case SerializationTypes.I1: { sbyte[] array = new sbyte[arraySize]; for(int i = 0; i < arraySize; i++) { array[i] = reader.ReadInt8(); } return array; } case SerializationTypes.U1: { byte[] array = new byte[arraySize]; for(int i = 0; i < arraySize; i++) { array[i] = reader.ReadUInt8(); } return array; } case SerializationTypes.I2: { short[] array = new short[arraySize]; for(int i = 0; i < arraySize; i++) { array[i] = reader.ReadInt16(); } return array; } case SerializationTypes.U2: { ushort[] array = new ushort[arraySize]; for(int i = 0; i < arraySize; i++) { array[i] = reader.ReadUInt16(); } return array; } case SerializationTypes.I4: { int[] array = new int[arraySize]; for(int i = 0; i < arraySize; i++) { array[i] = reader.ReadInt32(); } return array; } case SerializationTypes.U4: { uint[] array = new uint[arraySize]; for(int i = 0; i < arraySize; i++) { array[i] = reader.ReadUInt32(); } return array; } case SerializationTypes.I8: { long[] array = new long[arraySize]; for(int i = 0; i < arraySize; i++) { array[i] = reader.ReadInt64(); } return array; } case SerializationTypes.U8: { ulong[] array = new ulong[arraySize]; for(int i = 0; i < arraySize; i++) { array[i] = reader.ReadUInt64(); } return array; } case SerializationTypes.R4: { float[] array = new float[arraySize]; for(int i = 0; i < arraySize; i++) { array[i] = reader.ReadSingle(); } return array; } case SerializationTypes.R8: { double[] array = new double[arraySize]; for(int i = 0; i < arraySize; i++) { array[i] = reader.ReadDouble(); } return array; } case SerializationTypes.STRING: { String[] array = new String[arraySize]; for(int i = 0; i < arraySize; i++) { array[i] = reader.ReadCompressedString(); } return array; } case SerializationTypes.OBJECT: { Object[] array = new Object[arraySize]; for(int i = 0; i < arraySize; i++) { SerializationTypes type = (SerializationTypes)reader.ReadUInt8(); array[i] = ExtractValue( type, reader, context ); } return array; } default: throw new Exception( "Not implemented: custom attribute array of type " + elementType ); } } // // Access Methods // public IMetaDataHasCustomAttribute Parent { get { return m_parent; } } public IMetaDataCustomAttributeType Type { get { return m_type; } } //--// // // Debug Methods // public override String ToString() { System.Text.StringBuilder sb = new System.Text.StringBuilder( "MetaDataCustomAttribute(" ); sb.Append( m_type ); sb.Append( "," ); sb.Append( m_parent ); sb.Append( ")[" ); sb.Append( m_buffer ); sb.Append( "]" ); return sb.ToString(); } } } ================================================ FILE: Zelig/Zelig/CompileTime/MetaData/Importer/MetaDataDeclSecurity.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // // // Originally based on the Bartok code base. // using System; using System.Collections.Generic; using System.Text; namespace Microsoft.Zelig.MetaData.Importer { public sealed class MetaDataDeclSecurity : MetaDataObject, IMetaDataNormalize { // // State // private short m_action; private IMetaDataHasDeclSecurity m_parent; private ArrayReader m_permissionSet; // // Constructor Methods // private MetaDataDeclSecurity( int index ) : base( TokenType.DeclSecurity, index ) { } // Helper methods to work around limitations in generics, see Parser.InitializeTable internal static MetaDataObject.CreateInstance GetCreator() { return new MetaDataObject.CreateInstance( Creator ); } private static MetaDataObject Creator( int index ) { return new MetaDataDeclSecurity( index ); } //--// internal override void Parse( Parser parser , Parser.TableSchema ts , ArrayReader reader ) { Parser.IndexReader parentReader = ts.m_columns[1].m_reader; int parentIndex; int permissionSetIndex; m_action = reader.ReadInt16(); parentIndex = parentReader ( reader ); permissionSetIndex = parser.readIndexAsForBlob( reader ); m_parent = parser.getHasDeclSecurity( parentIndex ); m_permissionSet = new ArrayReader( parser.getBlobBytes ( permissionSetIndex ) ); } // // IMetaDataNormalize methods // Normalized.MetaDataObject IMetaDataNormalize.AllocateNormalizedObject( MetaDataNormalizationContext context ) { //// resolver.ResolveExternalReference( ref this.parent ); throw context.InvalidPhase( this ); } void IMetaDataNormalize.ExecuteNormalizationPhase( Normalized.IMetaDataObject obj , MetaDataNormalizationContext context ) { throw context.InvalidPhase( this ); } // // Access Methods // public short Action { get { return m_action; } } public IMetaDataHasDeclSecurity Parent { get { return m_parent; } } public ArrayReader PermissionSet { get { return m_permissionSet; } } // // Debug Methods // public override String ToString() { return "MetaDataDeclSecurity(" + m_action + "," + m_parent + "," + m_permissionSet + ")"; } } } ================================================ FILE: Zelig/Zelig/CompileTime/MetaData/Importer/MetaDataDumper.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // // // Originally based on the Bartok code base. // namespace Microsoft.Zelig.MetaData { using System; using System.Collections.Generic; using System.Collections; using System.Reflection; using System.Text; public class MetaDataDumper : Normalized.IMetaDataDumper, IDisposable { // // State // MetaDataDumper m_sub; System.IO.TextWriter m_writer; int m_indent; GrowOnlySet< Normalized.MetaDataObject > m_processed; Normalized.MetaDataObject m_context; // // Constructor Methods // public MetaDataDumper( string name , MetaDataVersion ver ) { name = name.Replace( "<", "" ); name = name.Replace( ">", "" ); name = name.Replace( ":", "" ); m_sub = null; m_writer = new System.IO.StreamWriter( String.Format( "{0}_{1}.{2}.{3}.{4}.txt", name, ver.MajorVersion, ver.MinorVersion, ver.BuildNumber, ver.RevisionNumber ), false, Encoding.ASCII ); m_indent = 0; m_processed = SetFactory.NewWithReferenceEquality< Normalized.MetaDataObject >(); m_context = null; } private MetaDataDumper( MetaDataDumper sub , Normalized.MetaDataObject context ) { m_sub = sub; m_writer = sub.m_writer; m_indent = sub.m_indent; m_processed = sub.m_processed; m_context = context; } public void IndentPush( string s ) { WriteLine( s ); m_indent += 1; } public void IndentPop( string s ) { m_indent -= 1; WriteLine( s ); } public void WriteLine() { WriteIndentation(); m_writer.WriteLine(); } public void WriteLine( string s ) { WriteIndentation(); m_writer.WriteLine( s ); } public void WriteLine( string s , object arg1 ) { WriteIndentedLine( s, arg1 ); } public void WriteLine( string s , object arg1 , object arg2 ) { WriteIndentedLine( s, arg1, arg2 ); } public void WriteLine( string s , object arg1 , object arg2 , object arg3 ) { WriteIndentedLine( s, arg1, arg2, arg3 ); } public void WriteLine( string s , params object[] args ) { WriteIndentedLine( s, args ); } public void Process( Normalized.MetaDataObject obj , bool fOnlyOnce ) { if(fOnlyOnce == false || m_processed.Contains( obj ) == false) { m_processed.Insert( obj ); obj.Dump( this ); } } public bool AlreadyProcessed( Normalized.MetaDataObject obj ) { return m_processed.Contains( obj ); } public Normalized.MetaDataMethodAbstract GetContextMethodAndPop( out Normalized.IMetaDataDumper context ) { MetaDataDumper pThis = this; while(pThis != null) { Normalized.MetaDataObject obj = pThis.m_context; if(obj is Normalized.MetaDataMethodAbstract) { Normalized.MetaDataMethodAbstract md = (Normalized.MetaDataMethodAbstract)obj; context = pThis.m_sub; if(obj is Normalized.MetaDataMethodGeneric) { while(pThis != null) { if(pThis.m_context is Normalized.MetaDataMethodGenericInstantiation) { Normalized.MetaDataMethodGenericInstantiation inst = (Normalized.MetaDataMethodGenericInstantiation)pThis.m_context; if(inst.BaseMethod.Equals( md )) { context = pThis.m_sub; md = inst; break; } } pThis = pThis.m_sub; } } return md; } pThis = pThis.m_sub; } context = null; return null; } public Normalized.MetaDataTypeDefinitionAbstract GetContextTypeAndPop( out Normalized.IMetaDataDumper context ) { MetaDataDumper pThis = this; while(pThis != null) { Normalized.MetaDataObject obj = pThis.m_context; if(obj is Normalized.MetaDataTypeDefinitionAbstract) { Normalized.MetaDataTypeDefinitionAbstract td = (Normalized.MetaDataTypeDefinitionAbstract)obj; context = pThis.m_sub; if(obj is Normalized.MetaDataTypeDefinitionGeneric) { while(pThis != null) { if(pThis.m_context is Normalized.MetaDataTypeDefinitionGenericInstantiation) { Normalized.MetaDataTypeDefinitionGenericInstantiation inst = (Normalized.MetaDataTypeDefinitionGenericInstantiation)pThis.m_context; if(inst.GenericType.Equals( td )) { context = pThis.m_sub; td = inst; break; } } pThis = pThis.m_sub; } } return td; } pThis = pThis.m_sub; } context = null; return null; } public Normalized.IMetaDataDumper PushContext( Normalized.MetaDataObject obj ) { return new MetaDataDumper( this, obj ); } //--// private void WriteIndentedLine( string s , params object[] args ) { WriteIndentation(); m_writer.WriteLine( s, args ); } private void WriteIndentation() { for(int i = 0; i < m_indent; i++) { m_writer.Write( " " ); } } #region IDisposable Members public void Dispose() { if(m_writer != null) { m_writer.Dispose(); m_writer = null; } } #endregion } } ================================================ FILE: Zelig/Zelig/CompileTime/MetaData/Importer/MetaDataEvent.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // // // Originally based on the Bartok code base. // using System; using System.Collections.Generic; using System.Text; namespace Microsoft.Zelig.MetaData.Importer { public sealed class MetaDataEvent : MetaDataObject, IMetaDataHasSemantic, IMetaDataNormalize { // // State // private EventAttributes m_flags; private String m_name; private IMetaDataTypeDefOrRef m_eventType; private MetaDataTypeDefinition m_owner; // // Constructor Methods // private MetaDataEvent( int index ) : base( TokenType.Event, index ) { } // Helper methods to work around limitations in generics, see Parser.InitializeTable internal static MetaDataObject.CreateInstance GetCreator() { return new MetaDataObject.CreateInstance( Creator ); } private static MetaDataObject Creator( int index ) { return new MetaDataEvent( index ); } //--// internal override void Parse( Parser parser , Parser.TableSchema ts , ArrayReader reader ) { Parser.IndexReader eventTypeReader = ts.m_columns[2].m_reader; int eventTypeIndex; m_flags = (EventAttributes) reader.ReadInt16(); m_name = parser.readIndexAsString( reader ); eventTypeIndex = eventTypeReader ( reader ); m_eventType = parser.getTypeDefOrRef( eventTypeIndex ); m_owner = parser.GetTypeFromEventIndex( MetaData.UnpackTokenAsIndex( m_token ) ); m_owner.AddEvent( this ); } // // IMetaDataNormalize methods // Normalized.MetaDataObject IMetaDataNormalize.AllocateNormalizedObject( MetaDataNormalizationContext context ) { switch(context.Phase) { case MetaDataNormalizationPhase.CompletionOfMethodNormalization: { Normalized.MetaDataEvent eventNew = new Normalized.MetaDataEvent( context.GetTypeFromContext(), m_token ); eventNew.m_flags = m_flags; eventNew.m_name = m_name; context.GetNormalizedObject( m_eventType, out eventNew.m_eventType, MetaDataNormalizationMode.Default ); return eventNew.MakeUnique(); } } throw context.InvalidPhase( this ); } void IMetaDataNormalize.ExecuteNormalizationPhase( Normalized.IMetaDataObject obj , MetaDataNormalizationContext context ) { Normalized.MetaDataEvent ev = (Normalized.MetaDataEvent)obj; context = context.Push( obj ); switch(context.Phase) { case MetaDataNormalizationPhase.ResolutionOfCustomAttributes: { context.GetNormalizedObjectList( this.CustomAttributes, out ev.m_customAttributes, MetaDataNormalizationMode.Allocate ); } return; } throw context.InvalidPhase( this ); } // // Access Methods // public EventAttributes Flags { get { return m_flags; } } public String Name { get { return m_name; } } // Returns one of MetaData{TypeDef,TypeRef,TypeSpec} public IMetaDataTypeDefOrRef Type { get { return m_eventType; } } // // Debug Methods // public override String ToString() { return "MetaDataEvent(" + m_flags + "," + m_name + "," + m_eventType + ")"; } } } ================================================ FILE: Zelig/Zelig/CompileTime/MetaData/Importer/MetaDataField.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // // // Originally based on the Bartok code base. // using System; using System.Collections.Generic; using System.Text; namespace Microsoft.Zelig.MetaData.Importer { public sealed class MetaDataField : MetaDataObject, IMetaDataHasConstant, IMetaDataHasFieldMarshal, IMetaDataMemberForwarded, IMetaDataNormalize { // // State // private FieldAttributes m_flags; private string m_name; private SignatureField m_signature; private MetaDataTypeDefinition m_parent; private MetaDataFieldRVA m_fieldRVA; private MetaDataConstant m_constant; private MetaDataFieldLayout m_layout; // // Constructor Methods // private MetaDataField( int index ) : base( TokenType.Field, index ) { } // Helper methods to work around limitations in generics, see Parser.InitializeTable internal static MetaDataObject.CreateInstance GetCreator() { return new MetaDataObject.CreateInstance( Creator ); } private static MetaDataObject Creator( int index ) { return new MetaDataField( index ); } //--// internal override void Parse( Parser parser , Parser.TableSchema ts , ArrayReader reader ) { int signatureIndex; m_flags = (FieldAttributes) reader.ReadInt16(); m_name = parser.readIndexAsString ( reader ); signatureIndex = parser.readIndexAsForBlob( reader ); m_signature = SignatureField.Parse( parser, parser.getSignature( signatureIndex ) ); m_parent = parser.GetTypeFromFieldIndex( MetaData.UnpackTokenAsIndex( m_token ) ); m_parent.AddField( this ); } // // IMetaDataNormalize methods // Normalized.MetaDataObject IMetaDataNormalize.AllocateNormalizedObject( MetaDataNormalizationContext context ) { switch(context.Phase) { case MetaDataNormalizationPhase.CreationOfFieldDefinitions: { Normalized.MetaDataField fieldNew = new Normalized.MetaDataField( context.GetTypeFromContext(), m_token ); fieldNew.m_flags = m_flags; fieldNew.m_name = m_name; context.GetNormalizedSignature( m_signature, out fieldNew.m_signature, MetaDataNormalizationMode.Default ); context.GetNormalizedObject ( m_fieldRVA , out fieldNew.m_fieldRVA , MetaDataNormalizationMode.Default ); context.GetNormalizedObject ( m_constant , out fieldNew.m_constant , MetaDataNormalizationMode.Default ); context.GetNormalizedObject ( m_layout , out fieldNew.m_layout , MetaDataNormalizationMode.Default ); return fieldNew; } } throw context.InvalidPhase( this ); } void IMetaDataNormalize.ExecuteNormalizationPhase( Normalized.IMetaDataObject obj , MetaDataNormalizationContext context ) { Normalized.MetaDataField field = (Normalized.MetaDataField)obj; context = context.Push( obj ); switch(context.Phase) { case MetaDataNormalizationPhase.ResolutionOfCustomAttributes: { context.GetNormalizedObjectList( this.CustomAttributes, out field.m_customAttributes, MetaDataNormalizationMode.Allocate ); } return; } throw context.InvalidPhase( this ); } //--// internal void SetRVA( MetaDataFieldRVA fieldRVA ) { m_fieldRVA = fieldRVA; } internal void SetConstant( MetaDataConstant constant ) { m_constant = constant; } internal void SetLayout( MetaDataFieldLayout fieldLayout ) { m_layout = fieldLayout; } // // Access Methods // public FieldAttributes Flags { get { return m_flags; } } public override string FullName { get { if(m_parent != null) { return m_parent.FullName + "." + this.Name; } else { return this.Name; } } } public override string FullNameWithContext { get { return "field " + this.FullName; } } public string Name { get { return m_name; } } public SignatureField Signature { get { return m_signature; } } public MetaDataTypeDefinition Parent { get { return m_parent; } } public Object DefaultValueToType( ElementTypes type ) { if((m_flags & FieldAttributes.HasDefault) != 0 && m_constant != null) { return m_constant.ValueToType( type ); } else { return this.DefaultValue; } } public Object DefaultValue { get { if((m_flags & FieldAttributes.HasDefault) != 0 && m_constant != null) { return m_constant.Value; } else if((m_flags & FieldAttributes.HasFieldRVA) != 0 && m_fieldRVA != null) { return m_fieldRVA.DataBytes; } else { return null; } } } public int RVA { get { if((m_flags & FieldAttributes.HasFieldRVA) != 0 && m_fieldRVA != null) { return m_fieldRVA.RVA; } else { return 0; } } } public MetaDataFieldLayout Layout { get { return m_layout; } } // // Debug Methods // public override String ToString() { System.Text.StringBuilder sb = new System.Text.StringBuilder( "MetaDataField(" ); sb.Append( m_flags ); sb.Append( "," ); sb.Append( m_parent.FullName ); sb.Append( "." ); sb.Append( m_name ); sb.Append( "," ); sb.Append( m_signature ); if(this.DefaultValue != null) { sb.Append( "[" ); sb.Append( this.DefaultValue ); sb.Append( "]" ); } sb.Append( ")" ); return sb.ToString(); } } } ================================================ FILE: Zelig/Zelig/CompileTime/MetaData/Importer/MetaDataFieldLayout.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // // // Originally based on the Bartok code base. // using System; using System.Collections.Generic; using System.Text; namespace Microsoft.Zelig.MetaData.Importer { public sealed class MetaDataFieldLayout : MetaDataObject, IMetaDataNormalize { // // State // private int m_offset; private MetaDataField m_field; // // Constructor Methods // private MetaDataFieldLayout( int index ) : base( TokenType.FieldLayout, index ) { } // Helper methods to work around limitations in generics, see Parser.InitializeTable internal static MetaDataObject.CreateInstance GetCreator() { return new MetaDataObject.CreateInstance( Creator ); } private static MetaDataObject Creator( int index ) { return new MetaDataFieldLayout( index ); } //--// internal override void Parse( Parser parser , Parser.TableSchema ts , ArrayReader reader ) { Parser.IndexReader fieldReader = ts.m_columns[1].m_reader; int fieldIndex; m_offset = reader.ReadInt32(); fieldIndex = fieldReader( reader ); m_field = parser.getField( fieldIndex ); m_field.SetLayout( this ); } // // IMetaDataNormalize methods // Normalized.MetaDataObject IMetaDataNormalize.AllocateNormalizedObject( MetaDataNormalizationContext context ) { switch(context.Phase) { case MetaDataNormalizationPhase.CreationOfFieldDefinitions: { Normalized.MetaDataFieldLayout res = new Normalized.MetaDataFieldLayout( m_token ); res.m_offset = m_offset; return res; } } throw context.InvalidPhase( this ); } void IMetaDataNormalize.ExecuteNormalizationPhase( Normalized.IMetaDataObject obj , MetaDataNormalizationContext context ) { throw context.InvalidPhase( this ); } // // Access Methods // public int Offset { get { return m_offset; } } public MetaDataField Field { get { return m_field; } } // // Debug Methods // public override String ToString() { return "MetaDataFieldLayout(" + m_offset + "," + m_field + ")"; } } } ================================================ FILE: Zelig/Zelig/CompileTime/MetaData/Importer/MetaDataFieldMarshal.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // // // Originally based on the Bartok code base. // using System; using System.Collections.Generic; using System.Text; namespace Microsoft.Zelig.MetaData.Importer { public sealed class MetaDataFieldMarshal : MetaDataObject, IMetaDataNormalize { // // State // private IMetaDataHasFieldMarshal m_parent; private MarshalSpec m_nativeType; // // Constructor Methods // private MetaDataFieldMarshal( int index ) : base( TokenType.FieldMarshal, index ) { } // Helper methods to work around limitations in generics, see Parser.InitializeTable internal static MetaDataObject.CreateInstance GetCreator() { return new MetaDataObject.CreateInstance( Creator ); } private static MetaDataObject Creator( int index ) { return new MetaDataFieldMarshal( index ); } //--// internal override void Parse( Parser parser , Parser.TableSchema ts , ArrayReader reader ) { Parser.IndexReader parentReader = ts.m_columns[0].m_reader; int parentIndex = parentReader ( reader ); int nativeTypeIndex = parser.readIndexAsForBlob( reader ); m_parent = parser.getHasFieldMarshal( parentIndex ); m_nativeType = parser.getNativeType ( nativeTypeIndex ); } // // IMetaDataNormalize methods // Normalized.MetaDataObject IMetaDataNormalize.AllocateNormalizedObject( MetaDataNormalizationContext context ) { //// resolver.ResolveExternalReference( ref this.parent ); throw context.InvalidPhase( this ); } void IMetaDataNormalize.ExecuteNormalizationPhase( Normalized.IMetaDataObject obj , MetaDataNormalizationContext context ) { throw context.InvalidPhase( this ); } // // Access Methods // public IMetaDataHasFieldMarshal Parent { get { return m_parent; } } public MarshalSpec NativeType { get { return m_nativeType; } } // // Debug Methods // public override String ToString() { return "MetaDataFieldMarshal(" + ((MetaDataObject)m_parent).ToStringLong() + "," + m_nativeType + ")"; } } } ================================================ FILE: Zelig/Zelig/CompileTime/MetaData/Importer/MetaDataFieldRVA.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // // // Originally based on the Bartok code base. // using System; using System.Collections.Generic; using System.Reflection; using System.Text; namespace Microsoft.Zelig.MetaData.Importer { public sealed class MetaDataFieldRVA : MetaDataObject, IMetaDataNormalize { // BUGBUG: Should be machine dependent! private const int c_machineIntSize = 4; // // State // private int m_rva; private byte[] m_dataBytes; private MetaDataField m_field; // // Constructor Methods // private MetaDataFieldRVA( int index ) : base( TokenType.FieldRVA, index ) { } // Helper methods to work around limitations in generics, see Parser.InitializeTable internal static MetaDataObject.CreateInstance GetCreator() { return new MetaDataObject.CreateInstance( Creator ); } private static MetaDataObject Creator( int index ) { return new MetaDataFieldRVA( index ); } //--// internal override void Parse( Parser parser , Parser.TableSchema ts , ArrayReader reader ) { Parser.IndexReader fieldReader = ts.m_columns[1].m_reader; int fieldIndex; m_rva = reader.ReadInt32(); fieldIndex = fieldReader( reader ); m_field = parser.getField( fieldIndex ); SignatureField fieldSignature = (SignatureField)m_field.Signature; SignatureType fieldType = fieldSignature.FieldType; int dataSize = this.getFieldSize( fieldType ); ArrayReader reader2 = parser.ImageReaderAtVirtualAddress( m_rva ); if(reader2 != null) { m_dataBytes = reader2.ReadUInt8Array( dataSize ); } else { m_dataBytes = new byte[dataSize]; } m_field.SetRVA( this ); } // // IMetaDataNormalize methods // Normalized.MetaDataObject IMetaDataNormalize.AllocateNormalizedObject( MetaDataNormalizationContext context ) { switch(context.Phase) { case MetaDataNormalizationPhase.CreationOfFieldDefinitions: { Normalized.MetaDataFieldRVA fieldRVA = new Normalized.MetaDataFieldRVA( m_token ); fieldRVA.m_dataBytes = m_dataBytes; return fieldRVA; } } throw context.InvalidPhase( this ); } void IMetaDataNormalize.ExecuteNormalizationPhase( Normalized.IMetaDataObject obj , MetaDataNormalizationContext context ) { throw context.InvalidPhase( this ); } // // Access Methods // public byte[] DataBytes { get { return m_dataBytes; } } public MetaDataField Field { get { return m_field; } } public int RVA { get { return m_rva; } } // // Helper Methods // private int getFieldSize( SignatureType fieldType ) { switch(fieldType.ElementType) { case ElementTypes.VOID: return 0; case ElementTypes.BOOLEAN: case ElementTypes.I1: case ElementTypes.U1: return 1; case ElementTypes.CHAR: case ElementTypes.I2: case ElementTypes.U2: return 2; case ElementTypes.I4: case ElementTypes.U4: case ElementTypes.R4: return 4; case ElementTypes.I8: case ElementTypes.U8: case ElementTypes.R8: return 8; case ElementTypes.OBJECT: case ElementTypes.STRING: case ElementTypes.FNPTR: case ElementTypes.CLASS: case ElementTypes.PTR: case ElementTypes.BYREF: case ElementTypes.U: case ElementTypes.I: return c_machineIntSize; case ElementTypes.TYPEDBYREF: return 2 * c_machineIntSize; case ElementTypes.VALUETYPE: { SignatureType.ClassOrStruct fieldTypeClassOrStruct = (SignatureType.ClassOrStruct)fieldType; IMetaDataTypeDefOrRef classObject = fieldTypeClassOrStruct.ClassObject; if(!(classObject is MetaDataTypeDefinition)) { return -1; } MetaDataTypeDefinition typedef = (MetaDataTypeDefinition)classObject; if((typedef.Flags & TypeAttributes.Interface) != 0 || (typedef.Flags & TypeAttributes.Abstract ) != 0 ) { return -1; } int classSize = 0; int packSize = 0; if(typedef.ClassLayout != null) { classSize = typedef.ClassLayout.ClassSize; packSize = typedef.ClassLayout.PackingSize; } int instanceFieldSize = 0; if(typedef.Fields != null) { if((typedef.Flags & TypeAttributes.ExplicitLayout) != 0) { foreach(MetaDataField mdField in typedef.Fields) { if((mdField.Flags & FieldAttributes.Static) == 0) { SignatureType nestedFieldType = mdField.Signature.FieldType; int fieldSize = this.getFieldSize( nestedFieldType ); int offset = mdField.Layout.Offset; int fieldEnd = fieldSize + offset; if(fieldEnd > instanceFieldSize) { instanceFieldSize = fieldEnd; } } } } else { foreach(MetaDataField mdField in typedef.Fields) { if((mdField.Flags & FieldAttributes.Static) == 0) { SignatureType nestedFieldType = mdField.Signature.FieldType; int fieldSize = this.getFieldSize( nestedFieldType ); if(fieldSize == -1) { return -1; } if(packSize > 1) { int delta = instanceFieldSize % packSize; if(delta > 0) { instanceFieldSize += packSize - delta; } } instanceFieldSize += fieldSize; } } } } if(instanceFieldSize > classSize) { return instanceFieldSize; } else if(classSize > 0) { return classSize; } else { return 1; } } case ElementTypes.ARRAY: { SignatureType.Array fieldTypeArray = (SignatureType.Array)fieldType; int elementCount = 1; SignatureType.Array.Dimension[] dimensions = fieldTypeArray.Dimensions; int rank = dimensions.Length; for(int i = 0; i < rank; i++) { int dimSize = (int)(dimensions[i].m_upperBound - dimensions[i].m_lowerBound); if(dimSize == 0) { // Must be an array of pointers to other arrays return elementCount * c_machineIntSize; } else { elementCount *= dimSize; } } int elementSize = this.getFieldSize( fieldTypeArray.BaseType ); return elementCount * elementSize; } case ElementTypes.PINNED: { SignatureType.Prefix fieldTypePrefix = (SignatureType.Prefix)fieldType; return this.getFieldSize( fieldTypePrefix.InnerType ); } case ElementTypes.SZARRAY: // Should be machine dependent! return 4; case ElementTypes.SENTINEL: case ElementTypes.END: default: return -1; } } // // Debug Methods // public override String ToString() { System.Text.StringBuilder sb = new System.Text.StringBuilder( "MetaDataFieldRVA(" ); sb.Append( m_field ); sb.Append( "," ); if(m_dataBytes == null) { sb.Append( m_rva ); } else { sb.Append( "[" ); for(int i = 0; i < m_dataBytes.Length; i++) { if(i != 0) { sb.Append( "," ); } sb.Append( m_dataBytes[i].ToString( "x2" ) ); } sb.Append( "]" ); } sb.Append( ")" ); return sb.ToString(); } } } ================================================ FILE: Zelig/Zelig/CompileTime/MetaData/Importer/MetaDataFile.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // // // Originally based on the Bartok code base. // using System; using System.Collections.Generic; using System.Text; namespace Microsoft.Zelig.MetaData.Importer { public sealed class MetaDataFile : MetaDataObject, IMetaDataImplementation, IMetaDataNormalize { // // State // private FileAttributes m_flags; private String m_name; private byte[] m_hashValue; // // Constructor Methods // private MetaDataFile( int index ) : base( TokenType.File, index ) { } // Helper methods to work around limitations in generics, see Parser.InitializeTable internal static MetaDataObject.CreateInstance GetCreator() { return new MetaDataObject.CreateInstance( Creator ); } private static MetaDataObject Creator( int index ) { return new MetaDataFile( index ); } //--// internal override void Parse( Parser parser , Parser.TableSchema ts , ArrayReader reader ) { m_flags = (FileAttributes) reader.ReadInt32(); m_name = parser.readIndexAsString( reader ); m_hashValue = parser.readIndexAsBlob ( reader ); } // // IMetaDataNormalize methods // Normalized.MetaDataObject IMetaDataNormalize.AllocateNormalizedObject( MetaDataNormalizationContext context ) { // LT72: added normalization for metadatafile; not necessary with previous implementation on fraemwork 3.5 //throw context.InvalidPhase( this ); Normalized.MetaDataFile file = new Normalized.MetaDataFile( this.Token ); file.m_flags = this.m_flags; file.m_name = this.m_name; file.m_hashValue = this.m_hashValue; return file; } void IMetaDataNormalize.ExecuteNormalizationPhase( Normalized.IMetaDataObject obj , MetaDataNormalizationContext context ) { throw context.InvalidPhase( this ); } // // Access Methods // public FileAttributes Flags { get { return m_flags; } } public String Name { get { return m_name; } } public byte[] HashValue { get { return m_hashValue; } } // // Debug Methods // public override String ToString() { return "MetaDataFile(" + m_name + ")"; } public override String ToStringLong() { System.Text.StringBuilder sb = new System.Text.StringBuilder( "MetaDataFile(" ); sb.Append( m_flags.ToString( "x" ) ); sb.Append( "," ); sb.Append( m_name ); sb.Append( ",[" ); for(int i = 0; i < m_hashValue.Length; i++) { if(i != 0) { sb.Append( "," ); } sb.Append( "0x" ); sb.Append( m_hashValue[i].ToString( "x2" ) ); } sb.Append( "])" ); return sb.ToString(); } } } ================================================ FILE: Zelig/Zelig/CompileTime/MetaData/Importer/MetaDataGenericParam.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // // // Originally based on the Bartok code base. // using System; using System.Collections.Generic; using System.Collections; using System.Text; namespace Microsoft.Zelig.MetaData.Importer { public sealed class MetaDataGenericParam : MetaDataObject, IMetaDataNormalize { // // State // private short m_number; private GenericParameterAttributes m_flags; private IMetaDataTypeOrMethodDef m_owner; private String m_name; private List m_genericParamConstraints; // // Constructor Methods // private MetaDataGenericParam( int index ) : base( TokenType.GenericParam, index ) { } // Helper methods to work around limitations in generics, see Parser.InitializeTable internal static MetaDataObject.CreateInstance GetCreator() { return new MetaDataObject.CreateInstance( Creator ); } private static MetaDataObject Creator( int index ) { return new MetaDataGenericParam( index ); } //--// internal override void Parse( Parser parser , Parser.TableSchema ts , ArrayReader reader ) { Parser.IndexReader ownerReader = ts.m_columns[2].m_reader; int ownerIndex; m_number = reader.ReadInt16(); m_flags = (GenericParameterAttributes) reader.ReadInt16(); ownerIndex = ownerReader ( reader ); m_name = parser.readIndexAsString ( reader ); m_owner = parser.getTypeOrMethodDef( ownerIndex ); if(m_owner is MetaDataTypeDefinition) { ((MetaDataTypeDefinition)m_owner).AddGenericParam( this ); } else if(m_owner is MetaDataMethod) { ((MetaDataMethod)m_owner).AddGenericParam( this ); } else { throw IllegalMetaDataFormatException.Create( "Unknown owner of GenericParam: {0}", m_owner ); } } // // IMetaDataNormalize methods // Normalized.MetaDataObject IMetaDataNormalize.AllocateNormalizedObject( MetaDataNormalizationContext context ) { switch(context.Phase) { case MetaDataNormalizationPhase.CreationOfTypeDefinitions: if(m_owner is MetaDataTypeDefinition) { Normalized.MetaDataGenericTypeParam param = new Normalized.MetaDataGenericTypeParam( context.GetTypeFromContext(), m_token ); param.m_number = m_number; param.m_flags = m_flags; param.m_name = m_name; return param; } break; case MetaDataNormalizationPhase.CreationOfMethodDefinitions: if(m_owner is MetaDataMethod) { Normalized.MetaDataGenericMethodParam param = new Normalized.MetaDataGenericMethodParam( (Normalized.MetaDataMethodGeneric)context.GetMethodFromContext(), m_token ); param.m_number = m_number; param.m_flags = m_flags; param.m_name = m_name; return param; } break; } throw context.InvalidPhase( this ); } void IMetaDataNormalize.ExecuteNormalizationPhase( Normalized.IMetaDataObject obj , MetaDataNormalizationContext context ) { Normalized.MetaDataGenericParam param = (Normalized.MetaDataGenericParam)obj; switch(context.Phase) { case MetaDataNormalizationPhase.CompletionOfTypeNormalization: { context.GetNormalizedObjectList( m_genericParamConstraints, out param.m_genericParamConstraints, MetaDataNormalizationMode.Default ); } return; case MetaDataNormalizationPhase.ResolutionOfCustomAttributes: { context.GetNormalizedObjectList( this.CustomAttributes, out param.m_customAttributes, MetaDataNormalizationMode.Allocate ); } return; } throw context.InvalidPhase( this ); } //--// internal void AddGenericParamConstraint( IMetaDataTypeDefOrRef constraint ) { if(m_genericParamConstraints == null) { m_genericParamConstraints = new List( 2 ); } m_genericParamConstraints.Add( constraint ); } // // Access Methods // public short Number { get { return m_number; } } public GenericParameterAttributes Flags { get { return m_flags; } } public IMetaDataTypeOrMethodDef Owner { get { return m_owner; } } public String Name { get { return m_name; } } public List GenericParamConstraints { get { return m_genericParamConstraints; } } // // Debug Methods // public override String ToString() { return "MetaDataGenericParam(" + m_name + ")"; } public override String ToStringLong() { return "MetaDataGenericParam(" + m_number + "," + m_flags.ToString( "x" ) + "," + m_owner + "," + m_name + ")"; } } } ================================================ FILE: Zelig/Zelig/CompileTime/MetaData/Importer/MetaDataImplMap.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // // // Originally based on the Bartok code base. // using System; using System.Collections.Generic; using System.Text; namespace Microsoft.Zelig.MetaData.Importer { public sealed class MetaDataImplMap : MetaDataObject, IMetaDataNormalize { // // State // private ImplementationMapAttributes m_flags; private IMetaDataMemberForwarded m_memberForwarded; private String m_importName; private MetaDataModuleRef m_importScope; // // Constructor Methods // private MetaDataImplMap( int index ) : base( TokenType.ImplMap, index ) { } // Helper methods to work around limitations in generics, see Parser.InitializeTable internal static MetaDataObject.CreateInstance GetCreator() { return new MetaDataObject.CreateInstance( Creator ); } private static MetaDataObject Creator( int index ) { return new MetaDataImplMap( index ); } //--// internal override void Parse( Parser parser , Parser.TableSchema ts , ArrayReader reader ) { Parser.IndexReader memberForwardedReader = ts.m_columns[1].m_reader; Parser.IndexReader importScopeReader = ts.m_columns[3].m_reader; int memberForwardedIndex; int importScopeIndex; m_flags = (ImplementationMapAttributes) reader.ReadInt16(); memberForwardedIndex = memberForwardedReader ( reader ); m_importName = parser.readIndexAsString ( reader ); importScopeIndex = importScopeReader ( reader ); m_memberForwarded = parser.getMemberForwarded( memberForwardedIndex ); m_importScope = parser.getModuleRef ( importScopeIndex ); } // // IMetaDataNormalize methods // Normalized.MetaDataObject IMetaDataNormalize.AllocateNormalizedObject( MetaDataNormalizationContext context ) { //// resolver.ResolveExternalReference( ref this.memberForwarded ); throw context.InvalidPhase( this ); } void IMetaDataNormalize.ExecuteNormalizationPhase( Normalized.IMetaDataObject obj , MetaDataNormalizationContext context ) { throw context.InvalidPhase( this ); } // // Access Methods // public ImplementationMapAttributes Flags { get { return m_flags; } } public IMetaDataMemberForwarded MemberForwarded { get { return m_memberForwarded; } } public String ImportName { get { return m_importName; } } public MetaDataModuleRef ImportScope { get { return m_importScope; } } // // Debug Methods // public override String ToString() { return "MetaDataImplMap(" + m_flags.ToString( "x" ) + "," + m_memberForwarded + "," + m_importName + "," + m_importScope + ")"; } } } ================================================ FILE: Zelig/Zelig/CompileTime/MetaData/Importer/MetaDataManifestResource.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // // // Originally based on the Bartok code base. // using System; using System.Collections.Generic; using System.Text; namespace Microsoft.Zelig.MetaData.Importer { public sealed class MetaDataManifestResource : MetaDataObject, IMetaDataNormalize { // // State // private int m_offset; private ManifestResourceAttributes m_flags; private String m_name; private byte[] m_data; private IMetaDataImplementation m_implementation; private Dictionary< string, object > m_values; // // Constructor Methods // private MetaDataManifestResource( int index ) : base( TokenType.ManifestResource, index ) { } // Helper methods to work around limitations in generics, see Parser.InitializeTable internal static MetaDataObject.CreateInstance GetCreator() { return new MetaDataObject.CreateInstance( Creator ); } private static MetaDataObject Creator( int index ) { return new MetaDataManifestResource( index ); } //--// internal override void Parse( Parser parser , Parser.TableSchema ts , ArrayReader reader ) { Parser.IndexReader implementationReader = ts.m_columns[3].m_reader; int implementationIndex; m_offset = reader.ReadInt32(); m_flags = (ManifestResourceAttributes) reader.ReadInt32(); m_name = parser.readIndexAsString ( reader ); implementationIndex = implementationReader ( reader ); m_implementation = parser.getImplementation( implementationIndex ); m_data = (implementationIndex == 0) ? parser.getResourceBytes( m_offset ) : null; try { if(m_data != null) { System.IO.MemoryStream stream = new System.IO.MemoryStream( m_data ); if(stream.CanSeek && stream.Length > 4) { System.IO.BinaryReader br = new System.IO.BinaryReader( stream ); if(br.ReadInt32() == System.Resources.ResourceManager.MagicNumber) { stream.Seek( 0, System.IO.SeekOrigin.Begin ); System.Resources.ResourceSet rs = new System.Resources.ResourceSet( stream ); Dictionary< string, object > values = new Dictionary< string, object >(); foreach(System.Collections.DictionaryEntry entry in rs) { string name = (string)entry.Key; values[name] = entry.Value; } m_values = values; } } } } catch { } } // // IMetaDataNormalize methods // Normalized.MetaDataObject IMetaDataNormalize.AllocateNormalizedObject( MetaDataNormalizationContext context ) { switch(context.Phase) { case MetaDataNormalizationPhase.ConversionOfResources: { Normalized.MetaDataAssembly owner = (Normalized.MetaDataAssembly)context.Value; Normalized.MetaDataManifestResource resNew = new Normalized.MetaDataManifestResource( owner, m_token ); resNew.m_offset = m_offset; resNew.m_flags = m_flags; resNew.m_name = m_name; resNew.m_data = m_data; resNew.m_values = m_values; context.GetNormalizedObject( m_implementation, out resNew.m_implementation, MetaDataNormalizationMode.Default ); owner.Resources.Add( resNew ); return resNew; } } throw context.InvalidPhase( this ); } void IMetaDataNormalize.ExecuteNormalizationPhase( Normalized.IMetaDataObject obj , MetaDataNormalizationContext context ) { throw context.InvalidPhase( this ); } // // Access Methods // public int Offset { get { return m_offset; } } public ManifestResourceAttributes Flags { get { return m_flags; } } public String Name { get { return m_name; } } // Returns one of MetaData{File,AssemblyRef,ExportedType} public IMetaDataImplementation Implementation { get { return m_implementation; } } public byte[] Data { get { return m_data; } } public Dictionary< string, object > Values { get { return m_values; } } // // Debug Methods // public override String ToString() { return "MetaDataManifestResource(" + m_name + ")"; } public override String ToStringLong() { if(m_implementation == null) { return "MetaDataManifestResource(" + m_offset + "," + m_flags.ToString( "x" ) + "," + m_name + "," + m_data + ")"; } else { return "MetaDataManifestResource(" + m_offset + "," + m_flags.ToString( "x" ) + "," + m_name + "," + m_implementation + ")"; } } } } ================================================ FILE: Zelig/Zelig/CompileTime/MetaData/Importer/MetaDataMemberRef.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // // // Originally based on the Bartok code base. // using System; using System.Collections.Generic; using System.Text; namespace Microsoft.Zelig.MetaData.Importer { public sealed class MetaDataMemberRef : MetaDataObject, IMetaDataMethodDefOrRef, IMetaDataCustomAttributeType, IMetaDataNormalize { // // State // private IMetaDataMemberRefParent m_classObject; private String m_name; private Signature m_signature; // // Constructor Methods // private MetaDataMemberRef( int index ) : base( TokenType.MemberRef, index ) { } // Helper methods to work around limitations in generics, see Parser.InitializeTable internal static MetaDataObject.CreateInstance GetCreator() { return new MetaDataObject.CreateInstance( Creator ); } private static MetaDataObject Creator( int index ) { return new MetaDataMemberRef( index ); } //--// internal override void Parse( Parser parser , Parser.TableSchema ts , ArrayReader reader ) { Parser.IndexReader classReader = ts.m_columns[0].m_reader; int classIndex; int signatureIndex; classIndex = classReader ( reader ); m_name = parser.readIndexAsString ( reader ); signatureIndex = parser.readIndexAsForBlob( reader ); m_classObject = parser.getMemberRefParent( classIndex ); m_signature = Signature.ParseMemberRef( parser, parser.getSignature( signatureIndex ) ); } // // IMetaDataNormalize methods // Normalized.MetaDataObject IMetaDataNormalize.AllocateNormalizedObject( MetaDataNormalizationContext context ) { Normalized.MetaDataTypeDefinitionAbstract classObjectAbstract; context.GetNormalizedObject( m_classObject, out classObjectAbstract, MetaDataNormalizationMode.Default ); Normalized.MetaDataTypeDefinitionAbstract typeContext = classObjectAbstract; Normalized.MetaDataMethodAbstract methodContext = context.GetMethodFromContext(); if(m_signature is Importer.SignatureMethod) { Importer.SignatureMethod signature = (Importer.SignatureMethod)m_signature; Normalized.SignatureMethod signatureMethod; context.GetNormalizedSignature( signature, out signatureMethod, MetaDataNormalizationMode.Default ); while(classObjectAbstract != null) { Normalized.MetaDataMethodBase mdNew = null; if(classObjectAbstract is Normalized.MetaDataTypeDefinition) { Normalized.MetaDataTypeDefinition classObject = (Normalized.MetaDataTypeDefinition)classObjectAbstract; mdNew = Match( classObject.Methods, m_name, signatureMethod ); } else if(classObjectAbstract is Normalized.MetaDataTypeDefinitionGeneric) { Normalized.MetaDataTypeDefinitionGeneric classObject = (Normalized.MetaDataTypeDefinitionGeneric)classObjectAbstract; mdNew = Match( classObject.Methods, m_name, signatureMethod ); } else if(classObjectAbstract is Normalized.MetaDataTypeDefinitionGenericInstantiation) { Normalized.MetaDataTypeDefinitionGenericInstantiation classObject = (Normalized.MetaDataTypeDefinitionGenericInstantiation)classObjectAbstract; mdNew = Match( classObject.GenericType.Methods, m_name, signatureMethod ); } else if(classObjectAbstract is Normalized.MetaDataTypeDefinitionArray) { Normalized.MetaDataTypeDefinitionArray classObject = (Normalized.MetaDataTypeDefinitionArray)classObjectAbstract; mdNew = Match( classObject.Methods, m_name, signatureMethod ); } if(mdNew != null) { if(mdNew.IsOpenMethod || (classObjectAbstract is Normalized.MetaDataTypeDefinitionGenericInstantiation)) { Normalized.MetaDataMethodWithContext mdNew2 = new Normalized.MetaDataMethodWithContext( typeContext, methodContext, mdNew ); return mdNew2.MakeUnique(); } return mdNew; } classObjectAbstract = classObjectAbstract.Extends; } throw UnresolvedExternalReferenceException.Create( this, "Cannot find method {0} with signature {1} in type {2}", m_name, m_signature, m_classObject ); } else if(m_signature is Importer.SignatureField) { Normalized.SignatureField signatureField; context.GetNormalizedSignature( m_signature, out signatureField, MetaDataNormalizationMode.Default ); while(classObjectAbstract != null) { Normalized.MetaDataField fdNew = null; if(classObjectAbstract is Normalized.MetaDataTypeDefinitionBase) { Normalized.MetaDataTypeDefinition classObject = (Normalized.MetaDataTypeDefinition)classObjectAbstract; fdNew = Match( classObject.Fields, m_name, signatureField ); } else if(classObjectAbstract is Normalized.MetaDataTypeDefinitionGenericInstantiation) { Normalized.MetaDataTypeDefinitionGenericInstantiation classObject = (Normalized.MetaDataTypeDefinitionGenericInstantiation)classObjectAbstract; fdNew = Match( classObject.GenericType.Fields, m_name, signatureField ); } if(fdNew != null) { if(fdNew.IsOpenField || (classObjectAbstract is Normalized.MetaDataTypeDefinitionGenericInstantiation)) { Normalized.MetaDataFieldWithContext fdNew2 = new Normalized.MetaDataFieldWithContext( typeContext, fdNew ); return fdNew2.MakeUnique(); } return fdNew; } classObjectAbstract = classObjectAbstract.Extends; } } throw context.InvalidPhase( this ); } void IMetaDataNormalize.ExecuteNormalizationPhase( Normalized.IMetaDataObject obj , MetaDataNormalizationContext context ) { throw context.InvalidPhase( this ); } private static Normalized.MetaDataMethodBase Match( Normalized.MetaDataMethodBase[] methods , string name , Normalized.SignatureMethod signature ) { foreach(Normalized.MetaDataMethodBase md in methods) { if(md.Match( name, signature )) { return md; } } return null; } private static Normalized.MetaDataField Match( Normalized.MetaDataField[] fields , string name , Normalized.SignatureField signature ) { foreach(Normalized.MetaDataField field in fields) { if(field.Match( name, signature )) { return field; } } return null; } // // Access Methods // public IMetaDataMemberRefParent Class { get { return m_classObject; } } public override string FullName { get { if(m_classObject != null) { return ((MetaDataObject)m_classObject).FullName + "." + this.Name; } else { return this.Name; } } } public override string FullNameWithContext { get { return "member reference " + this.FullName; } } public String Name { get { return m_name; } } public Signature Signature { get { return m_signature; } } // // Debug Methods // public override String ToString() { return "MetaDataMemberRef(" + m_classObject + "," + m_name + "," + m_signature + ")"; } } } ================================================ FILE: Zelig/Zelig/CompileTime/MetaData/Importer/MetaDataMethod.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // // // Originally based on the Bartok code base. // using System; using System.Collections.Generic; using System.Collections; using System.Text; namespace Microsoft.Zelig.MetaData.Importer { public partial class MetaDataMethod : MetaDataObject, IMetaDataHasDeclSecurity, IMetaDataMethodDefOrRef, IMetaDataMemberForwarded, IMetaDataCustomAttributeType, IMetaDataTypeOrMethodDef, IMetaDataNormalize { // // State // private int m_rva; private MethodImplAttributes m_implFlags; private MethodAttributes m_flags; private string m_name; private SignatureMethod m_signature; private List m_paramList; private List m_genericParamList; private MetaDataTypeDefinition m_parent; private Instruction[] m_instructions; private EHClause[] m_ehTable; private int m_maxStack; private SignatureType[] m_locals; private bool m_initLocals; // information for debugging private Debugging.MethodDebugInfo m_debugInfo; // // Constructor Methods // private MetaDataMethod( int index ) : base( TokenType.Method, index ) { } // Helper methods to work around limitations in generics, see Parser.InitializeTable internal static MetaDataObject.CreateInstance GetCreator() { return new MetaDataObject.CreateInstance( Creator ); } private static MetaDataObject Creator( int index ) { return new MetaDataMethod( index ); } //--// internal override void Parse( Parser parser , Parser.TableSchema ts , ArrayReader reader ) { Parser.IndexReader paramReader = ts.m_columns[5].m_reader; int signatureIndex; int paramIndex; m_rva = reader.ReadInt32(); m_implFlags = (MethodImplAttributes) reader.ReadInt16(); m_flags = (MethodAttributes) reader.ReadInt16(); m_name = parser.readIndexAsString ( reader ); signatureIndex = parser.readIndexAsForBlob( reader ); paramIndex = paramReader ( reader ); m_signature = SignatureMethod.Parse( parser, parser.getSignature( signatureIndex ) ); parser.SetParamIndex( this, paramIndex ); m_parent = parser.GetTypeFromMethodIndex( MetaData.UnpackTokenAsIndex( m_token ) ); m_parent.AddMethod( this ); } // // IMetaDataNormalize methods // Normalized.MetaDataObject IMetaDataNormalize.AllocateNormalizedObject( MetaDataNormalizationContext context ) { switch(context.Phase) { case MetaDataNormalizationPhase.CreationOfMethodDefinitions: { Normalized.MetaDataMethodBase mdNew; Normalized.MetaDataTypeDefinitionBase owner = (Normalized.MetaDataTypeDefinitionBase)context.GetTypeFromContext(); if(m_genericParamList != null && m_genericParamList.Count > 0) { mdNew = new Normalized.MetaDataMethodGeneric( owner, m_token ); } else { mdNew = new Normalized.MetaDataMethod( owner, m_token ); } //--// mdNew.m_implFlags = m_implFlags; mdNew.m_flags = m_flags; mdNew.m_name = m_name; mdNew.m_maxStack = m_maxStack; mdNew.m_initLocals = m_initLocals; mdNew.m_debugInfo = m_debugInfo; context = context.Push( mdNew ); if(mdNew is Normalized.MetaDataMethodGeneric) { Normalized.MetaDataMethodGeneric mdNewG = (Normalized.MetaDataMethodGeneric)mdNew; context.GetNormalizedObjectList( m_genericParamList, out mdNewG.m_genericParams, MetaDataNormalizationMode.Default ); } context.GetNormalizedSignature ( m_signature, out mdNew.m_signature, MetaDataNormalizationMode.Default ); context.GetNormalizedObjectList ( m_paramList, out mdNew.m_paramList, MetaDataNormalizationMode.Default ); context.GetNormalizedSignatureArray( m_locals , out mdNew.m_locals , MetaDataNormalizationMode.Default ); return mdNew; } } throw context.InvalidPhase( this ); } void IMetaDataNormalize.ExecuteNormalizationPhase( Normalized.IMetaDataObject obj , MetaDataNormalizationContext context ) { Normalized.MetaDataMethodBase md = (Normalized.MetaDataMethodBase)obj; context = context.Push( obj ); switch(context.Phase) { case MetaDataNormalizationPhase.CompletionOfMethodNormalization: { if(m_instructions != null) { md.m_instructions = new Normalized.Instruction[m_instructions.Length]; for(int i = 0; i < m_instructions.Length; i++) { md.m_instructions[i] = m_instructions[i].Normalize( context ); } } if(m_ehTable != null) { md.m_ehTable = new Normalized.EHClause[m_ehTable.Length]; for(int i = 0; i < m_ehTable.Length; i++) { md.m_ehTable[i] = m_ehTable[i].Normalize( context ); } } } return; case MetaDataNormalizationPhase.ResolutionOfCustomAttributes: { context.GetNormalizedObjectList( this.CustomAttributes, out md.m_customAttributes, MetaDataNormalizationMode.Allocate ); context.ProcessPhaseList( m_paramList ); } return; } throw context.InvalidPhase( this ); } //--// // These are technically not constructor methods, but they are meant to // be used to set up the object internal void AddParam( MetaDataParam param ) { if(m_paramList == null) { m_paramList = new List( 2 ); } if(m_paramList.Count > 0 && m_paramList[m_paramList.Count-1].Sequence >= param.Sequence) { throw IllegalMetaDataFormatException.Create( "Parameters out of order - is this allowed?" ); } m_paramList.Add( param ); } internal void AddGenericParam( MetaDataGenericParam genericParam ) { if(m_genericParamList == null) { m_genericParamList = new List( 2 ); } if(genericParam.Number != m_genericParamList.Count) { throw IllegalMetaDataFormatException.Create( "Generic parameters out of order - is this allowed?" ); } m_genericParamList.Add( genericParam ); } //--// internal void loadInstructions( Parser mdLoader , PdbInfo.PdbFunction pdbFunction ) { if(m_rva != 0) { if((m_flags & MethodAttributes.PinvokeImpl ) == 0 || (m_flags & MethodAttributes.UnmanagedExport) != 0 ) { getInstructions( mdLoader, pdbFunction ); if(pdbFunction != null) { List list = new List(); pdbFunction.CollectSlots( list ); int max = -1; foreach(PdbInfo.PdbSlot slot in list) { if(max < slot.Slot) max = (int)slot.Slot; } if(max >= 0) { String[] localVarNames = new String[this.Locals.Length]; foreach(PdbInfo.PdbSlot slot in list) { localVarNames[slot.Slot] = slot.Name; } m_debugInfo = new Debugging.MethodDebugInfo( localVarNames ); } } } else { throw new NotImplementedException( "Not loading embedded native code for " + this ); } } } // // Access Methods // public List ParamList { get { return m_paramList; } } public List GenericParamList { get { return m_genericParamList; } } public Instruction[] Instructions { get { return m_instructions; } } public EHClause[] EHTable { get { return m_ehTable; } } public int MaxStack { get { return m_maxStack; } } public SignatureType[] Locals { get { return m_locals; } } public MethodImplAttributes ImplFlags { get { return m_implFlags; } } public MethodAttributes Flags { get { return m_flags; } } public override string FullName { get { if(m_parent != null) { return m_parent.FullName + "." + this.Name; } else { return this.Name; } } } public override string FullNameWithContext { get { return "method " + this.FullName; } } public string Name { get { return m_name; } } public SignatureMethod Signature { get { return (SignatureMethod)m_signature; } } public MetaDataTypeDefinition Parent { get { return m_parent; } } public int Rva { get { return m_rva; } } public bool IsEmpty { get { return (m_rva == 0); } } public bool InitLocals { get { return m_initLocals; } } //--// public Debugging.MethodDebugInfo DebugInformation { get { return m_debugInfo; } } // // Debug Methods // public override string ToString() { return "MetaDataMethod(" + this.FullName + ")"; } public override string ToStringLong() { System.Text.StringBuilder sb = new System.Text.StringBuilder( "MetaDataMethod(" ); if(m_genericParamList != null && m_genericParamList.Count > 0) { sb.Append( "GenericParams<" ); foreach(MetaDataGenericParam param in m_genericParamList) { sb.Append( param.ToString() ); sb.Append( "," ); } sb.Remove( sb.Length - 1, 1 ); sb.Append( ">," ); } sb.Append( m_rva ); sb.Append( "," ); sb.Append( m_implFlags.ToString( "x" ) ); sb.Append( "," ); sb.Append( m_flags.ToString( "x" ) ); sb.Append( "," ); if(m_parent != null) { sb.Append( m_parent.FullName ); sb.Append( "." ); } sb.Append( m_name ); sb.Append( "," ); sb.Append( m_signature ); sb.Append( "," ); if(m_paramList == null || m_paramList.Count == 0) { sb.Append( "No parameters" ); } else { sb.Append( "parameters(" ); foreach(MetaDataParam param in m_paramList) { sb.Append( param.ToString() ); sb.Append( "," ); } sb.Remove( sb.Length - 1, 1 ); sb.Append( ")" ); } sb.Append( ")" ); return sb.ToString(); } } } ================================================ FILE: Zelig/Zelig/CompileTime/MetaData/Importer/MetaDataMethodImpl.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // // // Originally based on the Bartok code base. // using System; using System.Collections.Generic; using System.Text; namespace Microsoft.Zelig.MetaData.Importer { public sealed class MetaDataMethodImpl : MetaDataObject, IMetaDataNormalize { // // State // private MetaDataTypeDefinition m_classObject; private IMetaDataMethodDefOrRef m_body; private IMetaDataMethodDefOrRef m_declaration; // // Constructor Methods // private MetaDataMethodImpl( int index ) : base( TokenType.MethodImpl, index ) { } // Helper methods to work around limitations in generics, see Parser.InitializeTable internal static MetaDataObject.CreateInstance GetCreator() { return new MetaDataObject.CreateInstance( Creator ); } private static MetaDataObject Creator( int index ) { return new MetaDataMethodImpl( index ); } //--// internal override void Parse( Parser parser , Parser.TableSchema ts , ArrayReader reader ) { Parser.IndexReader classReader = ts.m_columns[0].m_reader; Parser.IndexReader bodyReader = ts.m_columns[1].m_reader; Parser.IndexReader declarationReader = ts.m_columns[2].m_reader; int classIndex = classReader ( reader ); int bodyIndex = bodyReader ( reader ); int declarationIndex = declarationReader( reader ); m_classObject = parser.getTypeDef ( classIndex ); m_body = parser.getMethodDefOrRef( bodyIndex ); m_declaration = parser.getMethodDefOrRef( declarationIndex ); } // // IMetaDataNormalize methods // Normalized.MetaDataObject IMetaDataNormalize.AllocateNormalizedObject( MetaDataNormalizationContext context ) { switch(context.Phase) { case MetaDataNormalizationPhase.CreationOfMethodImplDefinitions: { Normalized.MetaDataMethodImpl miNew = new Normalized.MetaDataMethodImpl( m_token ); context.GetNormalizedObject( m_classObject, out miNew.m_classObject, MetaDataNormalizationMode.LookupExisting ); context.GetNormalizedObject( m_body , out miNew.m_body , MetaDataNormalizationMode.LookupExisting ); context.GetNormalizedObject( m_declaration, out miNew.m_declaration, MetaDataNormalizationMode.Default ); return miNew; } } throw context.InvalidPhase( this ); } void IMetaDataNormalize.ExecuteNormalizationPhase( Normalized.IMetaDataObject obj , MetaDataNormalizationContext context ) { Normalized.MetaDataMethodImpl mi = (Normalized.MetaDataMethodImpl)obj; context = context.Push( obj ); switch(context.Phase) { case MetaDataNormalizationPhase.CompletionOfMethodImplNormalization: { Normalized.MetaDataTypeDefinitionBase td = (Normalized.MetaDataTypeDefinitionBase)mi.Body.Owner; td.m_methodImpls = ArrayUtility.AppendToArray( td.m_methodImpls, mi ); } return; } throw context.InvalidPhase( this ); } // // Access Methods // public MetaDataTypeDefinition Class { get { return m_classObject; } } public IMetaDataMethodDefOrRef Body { get { return m_body; } } public IMetaDataMethodDefOrRef Declaration { get { return m_declaration; } } // // Debug Methods // public override String ToString() { return "MetaDataMethodImpl(" + m_classObject + "," + m_body + "," + m_declaration + ")"; } } } ================================================ FILE: Zelig/Zelig/CompileTime/MetaData/Importer/MetaDataMethodSemantics.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // // // Originally based on the Bartok code base. // using System; using System.Collections.Generic; using System.Text; namespace Microsoft.Zelig.MetaData.Importer { public sealed class MetaDataMethodSemantics : MetaDataObject, IMetaDataNormalize { // // State // private MethodSemanticAttributes m_semantic; private MetaDataMethod m_method; private IMetaDataHasSemantic m_association; // // Constructor Methods // private MetaDataMethodSemantics( int index ) : base( TokenType.MethodSemantics, index ) { } // Helper methods to work around limitations in generics, see Parser.InitializeTable internal static MetaDataObject.CreateInstance GetCreator() { return new MetaDataObject.CreateInstance( Creator ); } private static MetaDataObject Creator( int index ) { return new MetaDataMethodSemantics( index ); } //--// internal override void Parse( Parser parser , Parser.TableSchema ts , ArrayReader reader ) { Parser.IndexReader methodReader = ts.m_columns[1].m_reader; Parser.IndexReader associationReader = ts.m_columns[2].m_reader; int methodIndex; int associationIndex; m_semantic = (MethodSemanticAttributes) reader.ReadInt16(); methodIndex = methodReader ( reader ); associationIndex = associationReader ( reader ); m_method = parser.getMethod ( methodIndex ); m_association = parser.getHasSemantic( associationIndex ); } // // IMetaDataNormalize methods // Normalized.MetaDataObject IMetaDataNormalize.AllocateNormalizedObject( MetaDataNormalizationContext context ) { //// resolver.ResolveExternalReference( ref this.association ); throw context.InvalidPhase( this ); } void IMetaDataNormalize.ExecuteNormalizationPhase( Normalized.IMetaDataObject obj , MetaDataNormalizationContext context ) { throw context.InvalidPhase( this ); } // // Access Methods // public MethodSemanticAttributes Semantic { get { return m_semantic; } } public MetaDataMethod Method { get { return m_method; } } public IMetaDataHasSemantic Association { get { return m_association; } } // // Debug Methods // public override String ToString() { return "MetaDataMethodSemantics(" + m_semantic + "," + m_method + "," + m_association + ")"; } } } ================================================ FILE: Zelig/Zelig/CompileTime/MetaData/Importer/MetaDataMethodSpec.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // // // Originally based on the Bartok code base. // using System; using System.Collections.Generic; using System.Text; namespace Microsoft.Zelig.MetaData.Importer { public sealed class MetaDataMethodSpec : MetaDataObject, IMetaDataNormalize { // // State // private IMetaDataMethodDefOrRef m_method; private SignatureMethodSpec m_instantiationValue; // // Constructor Methods // private MetaDataMethodSpec( int index ) : base( TokenType.MethodSpec, index ) { } // Helper methods to work around limitations in generics, see Parser.InitializeTable internal static MetaDataObject.CreateInstance GetCreator() { return new MetaDataObject.CreateInstance( Creator ); } private static MetaDataObject Creator( int index ) { return new MetaDataMethodSpec( index ); } //--// internal override void Parse( Parser parser , Parser.TableSchema ts , ArrayReader reader ) { Parser.IndexReader methodReader = ts.m_columns[0].m_reader; int methodIndex = methodReader ( reader ); int instantiationValueIndex = parser.readIndexAsForBlob( reader ); m_method = parser.getMethodDefOrRef( methodIndex ); m_instantiationValue = SignatureMethodSpec.Parse( parser, parser.getSignature( instantiationValueIndex ) ); } // // IMetaDataNormalize methods // Normalized.MetaDataObject IMetaDataNormalize.AllocateNormalizedObject( MetaDataNormalizationContext context ) { Normalized.MetaDataMethodAbstract baseMethod; Normalized.SignatureMethod instantiationValue; context.GetNormalizedObject ( m_method , out baseMethod , MetaDataNormalizationMode.Default ); context.GetNormalizedSignature( m_instantiationValue, out instantiationValue, MetaDataNormalizationMode.Default ); Normalized.MetaDataMethodGenericInstantiation mdNew = new Normalized.MetaDataMethodGenericInstantiation( context.GetAssemblyFromContext(), 0 ); mdNew.m_baseMethod = baseMethod; mdNew.m_parameters = instantiationValue.m_parameters; return mdNew.MakeUnique(); } void IMetaDataNormalize.ExecuteNormalizationPhase( Normalized.IMetaDataObject obj , MetaDataNormalizationContext context ) { throw context.InvalidPhase( this ); } // // Access Methods // public IMetaDataMethodDefOrRef Method { get { return m_method; } } public SignatureMethodSpec InstantiationValue { get { return m_instantiationValue; } } // // Debug Methods // public override String ToString() { return "MetaDataMethodSpec()"; } public override String ToStringLong() { return "MetaDataMethodSpec(" + m_method + ")"; } } } ================================================ FILE: Zelig/Zelig/CompileTime/MetaData/Importer/MetaDataMethod_Code.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // // // Originally based on the Bartok code base. // using System; using System.Collections.Generic; using System.Collections; using System.Text; namespace Microsoft.Zelig.MetaData.Importer { public partial class MetaDataMethod : MetaDataObject { // Internal Types private enum MethodFormats : byte { Tiny = 2, Fat = 3, Tiny1 = 6 } private enum SectionKind : byte { Reserved = 0, EHTable = 1, OptILTable = 2 } private static readonly EHClause[] s_sharedEmptyTable = new EHClause[0]; // // Constructor Methods // private void getInstructions( Parser mdParser , PdbInfo.PdbFunction pdbFunction ) { ArrayReader reader = mdParser.ImageReaderAtVirtualAddress( m_rva ); byte headerByte = reader.ReadUInt8(); byte formatMask = (byte)(headerByte & 0x7); int codeSize; ArrayReader codeReader; m_ehTable = s_sharedEmptyTable; switch((MethodFormats)formatMask) { case MethodFormats.Tiny: case MethodFormats.Tiny1: { m_initLocals = false; m_maxStack = 8; m_locals = null; codeSize = headerByte >> 2; codeReader = reader.CreateSubsetAndAdvance( codeSize ); break; } case MethodFormats.Fat: { // // for Fat format, check for CorILMethod_InitLocals // Section 25.4.3 of ECMA spec, Partition II // m_initLocals = ((headerByte & 0x10) != 0); byte headerByte2 = reader.ReadUInt8(); int size = headerByte2 >> 4; if(size != 3) { throw new IllegalInstructionStreamException( "Unexpected FAT size: " + size ); } m_maxStack = reader.ReadUInt16(); codeSize = reader.ReadInt32(); int localVarSignatureToken = reader.ReadInt32(); if(localVarSignatureToken == 0) { m_locals = null; } else { MetaDataStandAloneSig standAloneSig = (MetaDataStandAloneSig)mdParser.getObjectFromToken( localVarSignatureToken ); SignatureLocalVar localVarSignature = (SignatureLocalVar)standAloneSig.Signature; m_locals = localVarSignature.Locals; } codeReader = reader.CreateSubsetAndAdvance( codeSize ); break; } default: { throw new IllegalInstructionStreamException( "Unknown format: " + formatMask.ToString( "x" ) ); } } int[] byteToInstrMapping = new int[codeSize + 1]; int instructionCount = 0; while(true) { byteToInstrMapping[codeReader.Position] = instructionCount; if(codeReader.Position >= codeSize) break; instructionCount++; Normalized.Instruction.Opcode opcode = (Normalized.Instruction.Opcode)codeReader.ReadUInt8(); switch(opcode) { case Normalized.Instruction.Opcode.PREFIX1: opcode = (Normalized.Instruction.Opcode)((int)codeReader.ReadUInt8() + 256); if(opcode < 0 || (Normalized.Instruction.Opcode)opcode >= Normalized.Instruction.Opcode.COUNT) { throw new IllegalInstructionStreamException( "Saw prefixed opcode of " + opcode ); } break; case Normalized.Instruction.Opcode.PREFIXREF: case Normalized.Instruction.Opcode.PREFIX2: case Normalized.Instruction.Opcode.PREFIX3: case Normalized.Instruction.Opcode.PREFIX4: case Normalized.Instruction.Opcode.PREFIX5: case Normalized.Instruction.Opcode.PREFIX6: case Normalized.Instruction.Opcode.PREFIX7: throw new IllegalInstructionStreamException( "Saw unexpected prefix opcode " + opcode ); } Normalized.Instruction.OpcodeInfo opcodeInfo = Normalized.Instruction.OpcodeInfoTable[(int)opcode]; int operandSize = opcodeInfo.OperandSize; if(operandSize == -1) { switch(opcodeInfo.OperandFormat) { case Normalized.Instruction.OpcodeOperand.Switch: { int caseCount = codeReader.ReadInt32(); codeReader.Seek( 4 * caseCount ); break; } } } else { codeReader.Seek( operandSize ); } } //--// // Check whether or not there is an EH section if(formatMask == (byte)MethodFormats.Fat && (headerByte & 0x08) != 0) { int sectionPadding = (m_rva + codeSize) % 4; if(sectionPadding != 0) { while(sectionPadding < 4) { sectionPadding++; byte padding = reader.ReadUInt8(); } } byte sectionKind = reader.ReadUInt8(); if((sectionKind & 0x80) != 0) { throw new IllegalInstructionStreamException( "More than one section after the code" ); } if((sectionKind & 0x3F) != (int)SectionKind.EHTable) { throw new IllegalInstructionStreamException( "Expected EH table section, got " + sectionKind.ToString( "x" ) ); } //--// bool smallSection = ((sectionKind & 0x40) == 0); int dataSize; if(smallSection) { // Small section int ehByteCount = reader.ReadUInt8(); switch((ehByteCount % 12)) { case 0: // Some compilers generate the wrong value here, they forget to add the size of the header. case 4: break; default: throw new IllegalInstructionStreamException( "Unexpected byte count for small EH table: " + ehByteCount ); } int sectSmallReserved = reader.ReadInt16(); dataSize = (ehByteCount) / 12; } else { // Fat section int ehByteCount; ehByteCount = reader.ReadUInt8(); ehByteCount |= reader.ReadUInt8() << 8; ehByteCount |= reader.ReadUInt8() << 16; switch((ehByteCount % 24)) { case 0: // Some compilers generate the wrong value here, they forget to add the size of the header. case 4: break; default: throw new IllegalInstructionStreamException( "Unexpected byte count for fat EH table: " + ehByteCount ); } dataSize = ehByteCount / 24; } m_ehTable = new EHClause[dataSize]; for(int i = 0; i < dataSize; i++) { int flags; int tryOffset; int tryLength; int handlerOffset; int handlerLength; int tokenOrOffset; if(smallSection) { flags = reader.ReadUInt16(); tryOffset = reader.ReadUInt16(); tryLength = reader.ReadUInt8(); handlerOffset = reader.ReadUInt16(); handlerLength = reader.ReadUInt8(); tokenOrOffset = reader.ReadInt32(); } else { flags = reader.ReadInt32(); tryOffset = reader.ReadInt32(); tryLength = reader.ReadInt32(); handlerOffset = reader.ReadInt32(); handlerLength = reader.ReadInt32(); tokenOrOffset = reader.ReadInt32(); } int tryInstrOffset = byteToInstrMapping[tryOffset ]; int tryInstrEnd = byteToInstrMapping[tryOffset + tryLength ]; int handlerInstrOffset = byteToInstrMapping[handlerOffset ]; int handlerInstrEnd = byteToInstrMapping[handlerOffset + handlerLength]; IMetaDataTypeDefOrRef classObject = null; if((flags & (int)EHClause.ExceptionFlag.Filter) != 0) { tokenOrOffset = byteToInstrMapping[tokenOrOffset]; } else if(flags == (int)EHClause.ExceptionFlag.None) { classObject = (IMetaDataTypeDefOrRef)mdParser.getObjectFromToken( tokenOrOffset ); tokenOrOffset = 0; } else { // // Managed C++ emits finally blocks with a token. So we cannot enforce this check. // //if(MetaData.UnpackTokenAsIndex( tokenOrOffset ) != 0) //{ // throw new IllegalInstructionStreamException( "Unknown token or offset " + tokenOrOffset.ToString( "x8" ) ); //} } m_ehTable[i] = new EHClause( flags , tryInstrOffset , tryInstrEnd - tryInstrOffset , handlerInstrOffset , handlerInstrEnd - handlerInstrOffset , tokenOrOffset , classObject ); } } m_instructions = new Instruction[instructionCount]; int instructionCounter = 0; Debugging.DebugInfo debugInfo = null; codeReader.Rewind(); while(codeReader.Position < codeSize) { int pc = codeReader.Position; if(pc > 0 && byteToInstrMapping[pc] == 0) { throw new IllegalInstructionStreamException( "Out of sync at " + pc.ToString( "x" ) ); } Normalized.Instruction.Opcode opcode = (Normalized.Instruction.Opcode)codeReader.ReadUInt8(); if(opcode == Normalized.Instruction.Opcode.PREFIX1) { opcode = (Normalized.Instruction.Opcode)((int)codeReader.ReadUInt8() + 256); } Normalized.Instruction.OpcodeInfo opcodeInfo = Normalized.Instruction.OpcodeInfoTable[(int)opcode]; int operandSize = opcodeInfo.OperandSize; Instruction.Operand operand; switch(opcodeInfo.OperandFormat) { case Normalized.Instruction.OpcodeOperand.None: operand = null; break; case Normalized.Instruction.OpcodeOperand.Var: operand = new Instruction.OperandInt( (int)ReadOperandUInt( opcodeInfo, codeReader ) ); break; case Normalized.Instruction.OpcodeOperand.Int: if(operandSize == 8) { operand = new Instruction.OperandLong( codeReader.ReadInt64() ); } else { operand = new Instruction.OperandInt( ReadOperandInt( opcodeInfo, codeReader ) ); } break; case Normalized.Instruction.OpcodeOperand.Float: if(operandSize == 8) { operand = new Instruction.OperandDouble( codeReader.ReadDouble() ); } else { operand = new Instruction.OperandSingle( codeReader.ReadSingle() ); } break; case Normalized.Instruction.OpcodeOperand.Branch: { int target = ReadOperandInt( opcodeInfo, codeReader ); int instrTarget = byteToInstrMapping[codeReader.Position + target]; operand = new Instruction.OperandTarget( instrTarget ); break; } case Normalized.Instruction.OpcodeOperand.Method: { int token = codeReader.ReadInt32(); MetaDataObject mdMethod = mdParser.getObjectFromToken( token ); operand = new Instruction.OperandObject( mdMethod ); break; } case Normalized.Instruction.OpcodeOperand.Field: { int token = codeReader.ReadInt32(); MetaDataObject mdField = mdParser.getObjectFromToken( token ); operand = new Instruction.OperandObject( mdField ); break; } case Normalized.Instruction.OpcodeOperand.Type: { int token = codeReader.ReadInt32(); MetaDataObject type = mdParser.getObjectFromToken( token ); operand = new Instruction.OperandObject( type ); break; } case Normalized.Instruction.OpcodeOperand.Token: { int token = codeReader.ReadInt32(); MetaDataObject mdToken = mdParser.getObjectFromToken( token ); operand = new Instruction.OperandObject( mdToken ); break; } case Normalized.Instruction.OpcodeOperand.String: { int token = codeReader.ReadInt32(); if(MetaData.UnpackTokenAsType( token ) != TokenType.String) { throw new IllegalInstructionStreamException( "Unexpected string token " + token.ToString( "x" ) ); } int index = MetaData.UnpackTokenAsIndex( token ); operand = new Instruction.OperandString( mdParser.getUserString( index ) ); break; } case Normalized.Instruction.OpcodeOperand.Sig: { int token = codeReader.ReadInt32(); MetaDataObject calleeDescr = mdParser.getObjectFromToken( token ); operand = new Instruction.OperandObject( calleeDescr ); break; } case Normalized.Instruction.OpcodeOperand.Switch: { int caseCount = codeReader.ReadInt32(); int[] branchArray = new int[caseCount]; int nextPC = codeReader.Position + 4 * caseCount; for(int j = 0; j < caseCount; j++) { int target = codeReader.ReadInt32(); int instrTarget = byteToInstrMapping[nextPC + target]; branchArray[j] = instrTarget; } operand = new Instruction.OperandTargetArray( branchArray ); break; } default: throw new IllegalInstructionStreamException( "Invalid opcode " + opcodeInfo ); } // read in the line number information. PdbInfo.PdbSource file; PdbInfo.PdbLine line; if(pdbFunction != null && pdbFunction.FindOffset( (uint)pc, out file, out line )) { if(line.LineBegin != 0xFEEFEE) { debugInfo = new Debugging.DebugInfo( file.Name, (int)line.LineBegin, (int)line.ColumnBegin, (int)line.LineEnd, (int)line.ColumnEnd ); } else { // No debugging info. } } m_instructions[instructionCounter] = new Instruction( opcodeInfo, operand, debugInfo ); instructionCounter++; } } private static int ReadOperandInt( Normalized.Instruction.OpcodeInfo opcodeInfo, ArrayReader codeReader ) { switch(opcodeInfo.OperandSize) { case 0: return opcodeInfo.ImplicitOperandValue; case 1: return codeReader.ReadInt8(); case 2: return codeReader.ReadInt16(); case 4: return codeReader.ReadInt32(); } throw new IllegalInstructionStreamException( "Unknown operand size " + opcodeInfo.OperandSize ); } private static uint ReadOperandUInt( Normalized.Instruction.OpcodeInfo opcodeInfo, ArrayReader codeReader ) { switch(opcodeInfo.OperandSize) { case 0: return (uint)opcodeInfo.ImplicitOperandValue; case 1: return codeReader.ReadUInt8 (); case 2: return codeReader.ReadUInt16(); case 4: return codeReader.ReadUInt32(); } throw new IllegalInstructionStreamException( "Unknown operand size " + opcodeInfo.OperandSize ); } ////////////////////////////////////////////////////////////////////////////////////////////////////////////// // Internal classes public class IllegalInstructionStreamException : Exception { // // Constructor Methods // internal IllegalInstructionStreamException( String message ) : base( message ) { } } } } ================================================ FILE: Zelig/Zelig/CompileTime/MetaData/Importer/MetaDataModule.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // // // Originally based on the Bartok code base. // using System; using System.Collections.Generic; using System.Text; namespace Microsoft.Zelig.MetaData.Importer { public sealed class MetaDataModule : MetaDataObject, IMetaDataResolutionScope, IMetaDataNormalize { // // State // private short m_generation; private String m_name; private Guid m_mvid; // // Constructor Methods // private MetaDataModule( int index ) : base( TokenType.Module, index ) { } // Helper methods to work around limitations in generics, see Parser.InitializeTable internal static MetaDataObject.CreateInstance GetCreator() { return new MetaDataObject.CreateInstance( Creator ); } private static MetaDataObject Creator( int index ) { return new MetaDataModule( index ); } //--// internal override void Parse( Parser parser , Parser.TableSchema ts , ArrayReader reader ) { Parser.IndexReader encodingReader = ts.m_columns[3].m_reader; int encodingIndex; int encodingBaseIdIndex; m_generation = reader.ReadInt16(); m_name = parser.readIndexAsString ( reader ); m_mvid = parser.readIndexAsGuid ( reader ); encodingIndex = encodingReader ( reader ); encodingBaseIdIndex = encodingReader( reader ); if(encodingIndex != 0 || encodingBaseIdIndex != 0) { throw IllegalMetaDataFormatException.Create( "Illegal Module table" ); } } // // IMetaDataNormalize methods // Normalized.MetaDataObject IMetaDataNormalize.AllocateNormalizedObject( MetaDataNormalizationContext context ) { throw context.InvalidPhase( this ); } void IMetaDataNormalize.ExecuteNormalizationPhase( Normalized.IMetaDataObject obj , MetaDataNormalizationContext context ) { throw context.InvalidPhase( this ); } // // Access Methods // public short Generation { get { return m_generation; } } public String Name { get { return m_name; } } public Guid MVID { get { return m_mvid; } } // // Debug Methods // public override String ToString() { return "MetaDataModule(" + m_name + "," + m_mvid + ")"; } } } ================================================ FILE: Zelig/Zelig/CompileTime/MetaData/Importer/MetaDataModuleRef.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // // // Originally based on the Bartok code base. // using System; using System.Collections.Generic; using System.Text; namespace Microsoft.Zelig.MetaData.Importer { public sealed class MetaDataModuleRef : MetaDataObject, IMetaDataResolutionScope, IMetaDataNormalize { // // State // private String m_name; // // Constructor Methods // private MetaDataModuleRef( int index ) : base( TokenType.ModuleRef, index ) { } // Helper methods to work around limitations in generics, see Parser.InitializeTable internal static MetaDataObject.CreateInstance GetCreator() { return new MetaDataObject.CreateInstance( Creator ); } private static MetaDataObject Creator( int index ) { return new MetaDataModuleRef( index ); } //--// internal override void Parse( Parser parser , Parser.TableSchema ts , ArrayReader reader ) { m_name = parser.readIndexAsString( reader ); } // // IMetaDataNormalize methods // Normalized.MetaDataObject IMetaDataNormalize.AllocateNormalizedObject( MetaDataNormalizationContext context ) { throw context.InvalidPhase( this ); } void IMetaDataNormalize.ExecuteNormalizationPhase( Normalized.IMetaDataObject obj , MetaDataNormalizationContext context ) { throw context.InvalidPhase( this ); } // // Access Methods // public String Name { get { return m_name; } } // // Debug Methods // public override String ToString() { return "MetaDataModuleRef(" + m_name + ")"; } } } ================================================ FILE: Zelig/Zelig/CompileTime/MetaData/Importer/MetaDataNormalizationContext.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // // // Originally based on the Bartok code base. // using System; using System.Collections.Generic; using System.Collections; using System.Reflection; using System.Text; namespace Microsoft.Zelig.MetaData { internal enum MetaDataNormalizationPhase { Uninitialized , ResolutionOfAssemblyReferences , ConversionOfResources , CreationOfTypeDefinitions , LinkingOfNestedClasses , DiscoveryOfBuiltInTypes , ResolutionOfTypeReferences , CreationOfTypeHierarchy , CompletionOfTypeNormalization , CreationOfFieldDefinitions , CreationOfMethodDefinitions , CreationOfSpecialArrayMethods , CompletionOfMethodNormalization , CreationOfMethodImplDefinitions , CompletionOfMethodImplNormalization, ResolutionOfCustomAttributes , ResolutionOfEntryPoint , Max } [Flags] internal enum MetaDataNormalizationMode { LookupExisting = 1, Allocate = 2, Default = LookupExisting | Allocate, } internal class MetaDataNormalizationContext { // // State // private MetaDataResolver m_resolver; private MetaDataNormalizationPhase m_phase; private MetaDataNormalizationContext m_outsideContext; private Normalized.IMetaDataObject m_normalized; private List< Exception > m_errors; // // Constructor Methods // internal MetaDataNormalizationContext( MetaDataResolver resolver ) { m_resolver = resolver; m_errors = new List< Exception >(); } private MetaDataNormalizationContext( MetaDataNormalizationContext context , Normalized.IMetaDataObject normalized ) { m_resolver = context.m_resolver; m_phase = context.m_phase; m_errors = context.m_errors; m_outsideContext = context; m_normalized = normalized; } internal MetaDataNormalizationContext Push( Normalized.IMetaDataObject normalized ) { return new MetaDataNormalizationContext( this, normalized ); } internal MetaDataNormalizationContext Pop() { return m_outsideContext; } internal void SetPhase( MetaDataNormalizationPhase phase ) { m_phase = phase; } internal void FlushErrors() { if(m_errors.Count == 0) { return; } Console.Error.WriteLine( "Failed to resolve external references:" ); GrowOnlySet< string > errorsHistory = SetFactory.New< string >(); int numErrors = 0; foreach(var ex in m_errors) { Importer.UnresolvedExternalReferenceException ex2 = ex as Importer.UnresolvedExternalReferenceException; if(ex2 != null) { string msg = ex.Message; if(!errorsHistory.Insert( msg )) { Console.Error.WriteLine( "{0}", msg ); numErrors++; } } } m_errors.Clear(); throw Importer.SilentCompilationAbortException.Create( "Failed to resolve {0} external references:", numErrors ); } //--// internal MetaDataNormalizationPhase Phase { get { return m_phase; } } internal Normalized.IMetaDataObject Value { get { return m_normalized; } } internal GrowOnlySet< Normalized.IMetaDataUnique > UniqueDictionary { get { return m_resolver.UniqueDictionary; } } //--// //[System.Diagnostics.DebuggerHidden] internal void GetNormalizedObject( S src , out D dst , MetaDataNormalizationMode mode ) where S : Importer.IMetaDataObject where D : Normalized.IMetaDataObject { if(src != null) { try { Normalized.IMetaDataObject res = m_resolver.GetNormalizedObject( (Importer.IMetaDataNormalize)src, this, mode ); if(res is D) { dst = (D)res; } else { throw Importer.IllegalMetaDataFormatException.Create( "Cannot resolve reference '{0}' as type '{1}'", src, typeof(D) ); } } catch(Exception ex) { m_errors.Add( ex ); switch(Phase) { case MetaDataNormalizationPhase.ResolutionOfAssemblyReferences: case MetaDataNormalizationPhase.ResolutionOfCustomAttributes: case MetaDataNormalizationPhase.ResolutionOfTypeReferences: case MetaDataNormalizationPhase.CompletionOfMethodNormalization: dst = default( D ); return; } throw; } } else { dst = default( D ); } } //[System.Diagnostics.DebuggerHidden] internal void GetNormalizedObjectList( List src , out D[] dst , MetaDataNormalizationMode mode ) where S : Importer.IMetaDataObject where D : Normalized.IMetaDataObject { if(src != null) { dst = new D[src.Count]; int i = 0; foreach(S s in src) { D d; this.GetNormalizedObject( s, out d, mode ); dst[i++] = d; } } else { dst = new D[0]; } } //--// //[System.Diagnostics.DebuggerHidden] internal void GetNormalizedSignature( S src , out D dst , MetaDataNormalizationMode mode ) where S : Importer.Signature where D : Normalized.MetaDataSignature { if(src != null) { try { Normalized.IMetaDataObject res = m_resolver.GetNormalizedObject( (Importer.IMetaDataNormalizeSignature)src, this, mode ); if(res is D) { dst = (D)res; } else { throw Importer.IllegalMetaDataFormatException.Create( "Cannot resolve reference '{0}' as type '{1}'", src, typeof(D) ); } } catch(Exception ex) { m_errors.Add( ex ); switch(Phase) { case MetaDataNormalizationPhase.ResolutionOfAssemblyReferences: case MetaDataNormalizationPhase.ResolutionOfCustomAttributes: case MetaDataNormalizationPhase.ResolutionOfTypeReferences: case MetaDataNormalizationPhase.CompletionOfMethodNormalization: dst = default( D ); return; } throw; } } else { dst = default( D ); } } //[System.Diagnostics.DebuggerHidden] internal void GetNormalizedSignatureArray( S[] src , out D[] dst , MetaDataNormalizationMode mode ) where S : Importer.Signature where D : Normalized.MetaDataSignature { if(src != null) { dst = new D[src.Length]; int i = 0; foreach(S s in src) { D d; this.GetNormalizedSignature( s, out d, mode ); dst[i++] = d; } } else { dst = null; } } //--// //[System.Diagnostics.DebuggerHidden] internal void ProcessPhase( Importer.IMetaDataObject src ) { if(src != null) { m_resolver.ProcessPhase( src, this ); } } //[System.Diagnostics.DebuggerHidden] internal void ProcessPhaseList( List src ) where S : Importer.IMetaDataObject { if(src != null) { foreach(S s in src) { this.ProcessPhase( s ); } } } //--// internal MetaDataResolver.AssemblyPair FindAssembly( string name , MetaDataVersion version ) { return m_resolver.FindAssembly( name, version, this ); } internal Normalized.MetaDataTypeDefinitionBase ResolveName( String key ) { return m_resolver.ResolveName( key, this ); } internal void RegisterBuiltIn( Normalized.MetaDataTypeDefinition td , ElementTypes elementType ) { m_resolver.RegisterBuiltIn( td, elementType ); } internal Normalized.MetaDataTypeDefinition LookupBuiltIn( ElementTypes elementType ) { return m_resolver.LookupBuiltIn( elementType ); } //--// internal Normalized.MetaDataTypeDefinitionAbstract GetTypeFromContext() { MetaDataNormalizationContext context = this; while(context != null) { if(context.m_normalized is Normalized.MetaDataMethodBase) { Normalized.MetaDataMethodBase res = (Normalized.MetaDataMethodBase)context.m_normalized; return res.m_owner; } if(context.m_normalized is Normalized.MetaDataTypeDefinitionAbstract) { return (Normalized.MetaDataTypeDefinitionAbstract)context.m_normalized; } context = context.m_outsideContext; } throw Importer.IllegalMetaDataFormatException.Create( "Cannot get type from context: {0}", m_normalized ); } internal Normalized.MetaDataMethodAbstract GetMethodFromContext() { MetaDataNormalizationContext context = this; while(context != null) { if(context.m_normalized is Normalized.MetaDataMethodAbstract) { return (Normalized.MetaDataMethodAbstract)context.m_normalized; } context = context.m_outsideContext; } return null; } internal Normalized.MetaDataAssembly GetAssemblyFromContext() { MetaDataNormalizationContext context = this; while(context != null) { if(context.m_normalized is Normalized.MetaDataAssembly) { return (Normalized.MetaDataAssembly)context.m_normalized; } context = context.m_outsideContext; } throw Importer.IllegalMetaDataFormatException.Create( "Cannot get assembly from context: {0}", m_normalized ); } internal Normalized.MetaDataAssembly GetAssemblyForDelayedParameters() { return m_resolver.GetAssemblyForDelayedParameters(); } //--// internal void ImplementSpecialInterfaces( Normalized.MetaDataTypeDefinitionArray array ) { Normalized.MetaDataTypeDefinitionGenericInstantiation tdItf; tdItf = InstantiateInterface( "System.Collections.Generic.IList`1", array ); ImplementMethodsOnInterface( array, tdItf ); array.m_interfaces = ArrayUtility.AddUniqueToArray( array.m_interfaces, (Normalized.MetaDataTypeDefinitionAbstract)tdItf ); tdItf = InstantiateInterface( "System.Collections.Generic.ICollection`1", array ); ImplementMethodsOnInterface( array, tdItf ); array.m_interfaces = ArrayUtility.AddUniqueToArray( array.m_interfaces, (Normalized.MetaDataTypeDefinitionAbstract)tdItf ); tdItf = InstantiateInterface( "System.Collections.Generic.IEnumerable`1", array ); ImplementMethodsOnInterface( array, tdItf ); } internal Normalized.MetaDataTypeDefinitionGenericInstantiation InstantiateInterface( string name , Normalized.MetaDataTypeDefinitionArray array ) { Normalized.MetaDataTypeDefinitionGeneric itf = (Normalized.MetaDataTypeDefinitionGeneric)this.ResolveName( name ); return InstantiateInterface( itf, array ); } internal Normalized.MetaDataTypeDefinitionGenericInstantiation InstantiateInterface( Normalized.MetaDataTypeDefinitionGeneric gen , Normalized.MetaDataTypeDefinitionArray array ) { Normalized.MetaDataTypeDefinitionGenericInstantiation genInst = new Normalized.MetaDataTypeDefinitionGenericInstantiation( array.Owner, 0 ); genInst.m_baseType = gen; genInst.m_parameters = new Normalized.SignatureType[1]; genInst.m_parameters[0] = Normalized.SignatureType.CreateUnique( array.m_objectType ); return (Normalized.MetaDataTypeDefinitionGenericInstantiation)genInst.MakeUnique(); } internal void ImplementMethodsOnInterface( Normalized.MetaDataTypeDefinitionArray cls , Normalized.MetaDataTypeDefinitionAbstract itf ) { if(itf is Normalized.MetaDataTypeDefinitionGenericInstantiation) { Normalized.MetaDataTypeDefinitionGenericInstantiation itfInst = (Normalized.MetaDataTypeDefinitionGenericInstantiation)itf; foreach(Normalized.MetaDataMethodBase md in itfInst.m_baseType.m_methods) { Normalized.SignatureType returnType; Normalized.SignatureType[] parameters; returnType = Substitute( md.m_signature.m_returnType, cls ); if(md.m_signature.m_parameters != null) { parameters = new Normalized.SignatureType[md.m_signature.m_parameters.Length]; for(int i = 0; i < md.m_signature.m_parameters.Length; i++) { parameters[i] = Substitute( md.m_signature.m_parameters[i], cls ); } } else { parameters = null; } Normalized.MetaDataMethodBase mdNew = CreateMethod( cls, md.m_name, returnType, parameters ); cls.m_methods = ArrayUtility.AddUniqueToArray( cls.m_methods, mdNew ); } } } internal Normalized.SignatureType Substitute( Normalized.SignatureType td , Normalized.MetaDataTypeDefinitionArray cls ) { Normalized.MetaDataTypeDefinitionAbstract tdInner = td.Type; if(tdInner.IsOpenType) { if(tdInner is Normalized.MetaDataTypeDefinitionDelayed) { return Normalized.SignatureType.CreateUnique( cls.m_objectType ); } if(tdInner is Normalized.MetaDataTypeDefinitionArraySz) { Normalized.MetaDataTypeDefinitionArraySz array = (Normalized.MetaDataTypeDefinitionArraySz)tdInner; if(array.IsOpenType && array.m_objectType is Normalized.MetaDataTypeDefinitionDelayed) { return Normalized.SignatureType.CreateUnique( cls ); } } if(tdInner is Normalized.MetaDataTypeDefinitionGenericInstantiation) { Normalized.MetaDataTypeDefinitionGenericInstantiation inst = (Normalized.MetaDataTypeDefinitionGenericInstantiation)tdInner; return Normalized.SignatureType.CreateUnique( InstantiateInterface( inst.GenericType, cls ) ); } throw Importer.IllegalMetaDataFormatException.Create( "Unknown type in array instantiation: {0}", td ); } return td; } //--// internal void CreateSpecialMethods( Normalized.MetaDataTypeDefinitionArrayMulti array ) { // // Synthesize .ctor, Set, Get, and Address methods: // // .ctor ( *rank ) // Get ( *rank ) // void Set ( *rank, ) // ByRef Address( *rank ) // Normalized.MetaDataTypeDefinitionByRef byref = new Normalized.MetaDataTypeDefinitionByRef( array.m_owner, 0, ElementTypes.BYREF ); byref.m_type = array.m_objectType; byref = (Normalized.MetaDataTypeDefinitionByRef)byref.MakeUnique(); //--// Normalized.SignatureType objectType = Normalized.SignatureType.CreateUnique( array.m_objectType ); Normalized.SignatureType byrefSig = Normalized.SignatureType.CreateUnique( byref ); array.m_methods = new Normalized.MetaDataMethodBase[4]; array.m_methods[0] = CreateMultiArrayMethodVoid( array, ".ctor" ); array.m_methods[1] = CreateMultiArrayMethod ( array, "Get" , objectType ); array.m_methods[2] = CreateMultiArrayMethodVoid( array, "Set" , objectType ); array.m_methods[3] = CreateMultiArrayMethod ( array, "Address", byrefSig ); } private Normalized.MetaDataMethodBase CreateMultiArrayMethodVoid( Normalized.MetaDataTypeDefinitionArrayMulti owner , string name , params Normalized.SignatureType[] parameters ) { Normalized.MetaDataTypeDefinitionAbstract returnType = this.LookupBuiltIn( ElementTypes.VOID ); return CreateMultiArrayMethod( owner, name, Normalized.SignatureType.CreateUnique( returnType ), parameters ); } private Normalized.MetaDataMethodBase CreateMultiArrayMethod( Normalized.MetaDataTypeDefinitionArrayMulti owner , string name , Normalized.SignatureType returnType , params Normalized.SignatureType[] parameters ) { int rank = (int)owner.m_rank; Normalized.MetaDataTypeDefinitionAbstract index = this.LookupBuiltIn( ElementTypes.I4 ); Normalized.SignatureType[] parameters2; parameters2 = new Normalized.SignatureType[rank + parameters.Length]; for(int i = 0; i < rank; i++) { parameters2[i] = Normalized.SignatureType.CreateUnique( index ); } for(int i = 0; i < parameters.Length; i++) { parameters2[rank+i] = parameters[i]; } return CreateMethod( owner, name, returnType, parameters2 ); } internal Normalized.MetaDataMethodBase CreateMethod( Normalized.MetaDataTypeDefinitionAbstract owner , string name , Normalized.SignatureType returnType , params Normalized.SignatureType[] parameters ) { Normalized.SignatureMethod sig = new Normalized.SignatureMethod( 0 ); sig.m_callingConvention = Normalized.SignatureMethod.CallingConventions.HasThis; sig.m_returnType = returnType; sig.m_parameters = parameters; //--// Normalized.MetaDataMethodBase mdNew = new Normalized.MetaDataMethod( owner, 0 ); //--// mdNew.m_implFlags = MethodImplAttributes.Managed | MethodImplAttributes.InternalCall; mdNew.m_flags = MethodAttributes.Public | MethodAttributes.HideBySig | MethodAttributes.SpecialName | MethodAttributes.RTSpecialName; mdNew.m_name = name; mdNew.m_signature = (Normalized.SignatureMethod)sig.MakeUnique(); return mdNew; } //--// internal Exception InvalidPhase( object src ) { return Importer.IllegalMetaDataFormatException.Create( "InvalidPhase at {0}", src ); } } } ================================================ FILE: Zelig/Zelig/CompileTime/MetaData/Importer/MetaDataObject.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // // // Originally based on the Bartok code base. // using System; using System.Collections.Generic; using System.Collections; using System.Text; namespace Microsoft.Zelig.MetaData.Importer { // // Many metadata tables contain tokens of multiple types, see CodeToken. // // To make the relationships between tables more explicit, instead of using a reference to MetaDataObject, // the classes that represent the various tables use references to these interfaces. // public interface IMetaDataObject { } // // MetaDataTypeDefinition, MetaDataTypeReference, MetaDataTypeSpec // public interface IMetaDataTypeDefOrRef : IMetaDataObject { } // // MetaDataProperty, MetaDataField, MetaDataParam // public interface IMetaDataHasConstant : IMetaDataObject { } // // MetaDataObject // public interface IMetaDataHasCustomAttribute : IMetaDataObject { } // // MetaDataField, MetaDataParam // public interface IMetaDataHasFieldMarshal : IMetaDataObject { } // // MetaDataTypeDefinition, MetaDataMethod, MetaDataAssembly // public interface IMetaDataHasDeclSecurity : IMetaDataObject { } // // MetaDataTypeReference, MetaDataTypeSpec // public interface IMetaDataMemberRefParent : IMetaDataObject { } // // MetaDataProperty, MetaDataEvent // public interface IMetaDataHasSemantic : IMetaDataObject { } // // MetaDataMethod, MetaDataMemberRef // public interface IMetaDataMethodDefOrRef : IMetaDataObject { } // // MetaDataMethod, MetaDataField // public interface IMetaDataMemberForwarded : IMetaDataObject { } // // MetaDataMethod, MetaDataMemberRef // public interface IMetaDataCustomAttributeType : IMetaDataObject { } // // MetaDataAssemblyRef, MetaDataFile // public interface IMetaDataImplementation : IMetaDataObject { } // // MetaDataAssemblyRef, MetaDataTypeReference, MetaDataModule, MetaDataModuleRef // public interface IMetaDataResolutionScope : IMetaDataObject { } // // MetaDataTypeDefinition, MetaDataMethod // public interface IMetaDataTypeOrMethodDef : IMetaDataObject { } internal interface IMetaDataNormalize { Normalized.MetaDataObject AllocateNormalizedObject( MetaDataNormalizationContext context ); void ExecuteNormalizationPhase( Normalized.IMetaDataObject obj , MetaDataNormalizationContext context ); } internal interface IMetaDataNormalizeSignature { Normalized.MetaDataSignature AllocateNormalizedObject( MetaDataNormalizationContext context ); } //--// // // This class's primary reason for existence is its place in the class hierarchy. // // Convenient place to store CustomAttribute information // public abstract class MetaDataObject : IMetaDataHasCustomAttribute { internal delegate MetaDataObject CreateInstance( int token ); internal static int s_debugSequence; // // State // internal int m_debugSequence; protected int m_token; private List m_customAttributes; // // Constructor Methods // protected MetaDataObject( TokenType tbl , int index ) { m_debugSequence = s_debugSequence++; m_token = MetaData.PackToken( tbl, index ); } internal abstract void Parse( Parser parser , Parser.TableSchema ts , ArrayReader reader ); //--// internal void AddCustomAttribute( MetaDataCustomAttribute ca ) { if(m_customAttributes == null) { m_customAttributes = new List( 2 ); } m_customAttributes.Add( ca ); } //--// public int Token { get { return m_token; } } public List CustomAttributes { get { return m_customAttributes; } } // // Debug Methods // public virtual String ToStringLong() { return this.ToString(); } // The name of the meta data object, in a user-comprehensible // form. public virtual String FullName { get { return this.ToString(); } } // The name of the meta data object, in a user-comprehensible // form, along with the kind of object. // // For example, a method A.B.f would be printed out as: // // method A.B.f public virtual String FullNameWithContext { get { return this.ToString(); } } } } ================================================ FILE: Zelig/Zelig/CompileTime/MetaData/Importer/MetaDataParam.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // // // Originally based on the Bartok code base. // using System; using System.Collections.Generic; using System.Text; namespace Microsoft.Zelig.MetaData.Importer { public sealed class MetaDataParam : MetaDataObject, IMetaDataHasConstant, IMetaDataHasFieldMarshal, IMetaDataNormalize { // // State // private ParamAttributes m_flags; private short m_sequence; private String m_name; private MetaDataMethod m_parent; private MetaDataConstant m_constant; // // Constructor Methods // private MetaDataParam( int index ) : base( TokenType.Param, index ) { } // Helper methods to work around limitations in generics, see Parser.InitializeTable internal static MetaDataObject.CreateInstance GetCreator() { return new MetaDataObject.CreateInstance( Creator ); } private static MetaDataObject Creator( int index ) { return new MetaDataParam( index ); } //--// internal override void Parse( Parser parser , Parser.TableSchema ts , ArrayReader reader ) { m_flags = (ParamAttributes) reader.ReadInt16(); m_sequence = reader.ReadInt16(); m_name = parser.readIndexAsString( reader ); m_parent = parser.GetMethodFromParamIndex( MetaData.UnpackTokenAsIndex( m_token ) ); m_parent.AddParam( this ); } // // IMetaDataNormalize methods // Normalized.MetaDataObject IMetaDataNormalize.AllocateNormalizedObject( MetaDataNormalizationContext context ) { Normalized.MetaDataParam paramNew = new Normalized.MetaDataParam( m_token ); paramNew.m_flags = m_flags; paramNew.m_sequence = m_sequence; paramNew.m_name = m_name; context.GetNormalizedObject( m_constant, out paramNew.m_constant, MetaDataNormalizationMode.Default ); return paramNew; } void IMetaDataNormalize.ExecuteNormalizationPhase( Normalized.IMetaDataObject obj , MetaDataNormalizationContext context ) { Normalized.MetaDataParam param = (Normalized.MetaDataParam)obj; switch(context.Phase) { case MetaDataNormalizationPhase.ResolutionOfCustomAttributes: { context.GetNormalizedObjectList( this.CustomAttributes, out param.m_customAttributes, MetaDataNormalizationMode.Allocate ); } return; } throw context.InvalidPhase( this ); } //--// internal void SetConstant( MetaDataConstant constant ) { m_constant = constant; } // // Access Methods // public ParamAttributes Flags { get { return m_flags; } } public short Sequence { get { return m_sequence; } } public override string FullName { get { if(m_parent != null) { return m_parent.FullName + "." + this.Name; } else { return this.Name; } } } public override string FullNameWithContext { get { return "parameter " + this.FullName; } } public String Name { get { return m_name; } } public MetaDataMethod Parent { get { return m_parent; } } public Object DefaultValue { get { if((m_flags & ParamAttributes.HasDefault) != 0) { return m_constant.Value; } else { return null; } } } // // Debug Methods // public override String ToString() { return "MetaDataParam(" + m_name + ")"; } public override String ToStringLong() { return "MetaDataParam(" + m_flags.ToString( "x" ) + "," + m_sequence + "," + m_name + "<" + m_parent + ">)"; } } } ================================================ FILE: Zelig/Zelig/CompileTime/MetaData/Importer/MetaDataProperty.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // // // Originally based on the Bartok code base. // using System; using System.Collections.Generic; using System.Text; namespace Microsoft.Zelig.MetaData.Importer { public sealed class MetaDataProperty : MetaDataObject, IMetaDataHasConstant, IMetaDataHasSemantic, IMetaDataNormalize { // // State // private PropertyAttributes m_flags; private String m_name; private SignatureProperty m_type; private MetaDataTypeDefinition m_owner; private MetaDataConstant m_constant; // // Constructor Methods // private MetaDataProperty( int index ) : base( TokenType.Property, index ) { } // Helper methods to work around limitations in generics, see Parser.InitializeTable internal static MetaDataObject.CreateInstance GetCreator() { return new MetaDataObject.CreateInstance( Creator ); } private static MetaDataObject Creator( int index ) { return new MetaDataProperty( index ); } //--// internal override void Parse( Parser parser , Parser.TableSchema ts , ArrayReader reader ) { int typeIndex; m_flags = (PropertyAttributes) reader.ReadInt16(); m_name = parser.readIndexAsString ( reader ); typeIndex = parser.readIndexAsForBlob( reader ); m_type = SignatureProperty.Parse( parser, parser.getSignature( typeIndex ) ); m_owner = parser.GetTypeFromPropertyIndex( MetaData.UnpackTokenAsIndex( m_token ) ); m_owner.AddProperty( this ); } // // IMetaDataNormalize methods // Normalized.MetaDataObject IMetaDataNormalize.AllocateNormalizedObject( MetaDataNormalizationContext context ) { switch(context.Phase) { case MetaDataNormalizationPhase.CompletionOfMethodNormalization: { Normalized.MetaDataProperty propertyNew = new Normalized.MetaDataProperty( context.GetTypeFromContext(), m_token ); propertyNew.m_flags = m_flags; propertyNew.m_name = m_name; context.GetNormalizedSignature( m_type , out propertyNew.m_type , MetaDataNormalizationMode.Default ); context.GetNormalizedObject ( m_constant, out propertyNew.m_constant, MetaDataNormalizationMode.Default ); return propertyNew.MakeUnique(); } } throw context.InvalidPhase( this ); } void IMetaDataNormalize.ExecuteNormalizationPhase( Normalized.IMetaDataObject obj , MetaDataNormalizationContext context ) { Normalized.MetaDataProperty prop = (Normalized.MetaDataProperty)obj; context = context.Push( obj ); switch(context.Phase) { case MetaDataNormalizationPhase.ResolutionOfCustomAttributes: { context.GetNormalizedObjectList( this.CustomAttributes, out prop.m_customAttributes, MetaDataNormalizationMode.Allocate ); } return; } throw context.InvalidPhase( this ); } //--// internal void SetConstant( MetaDataConstant constant ) { m_constant = constant; } // // Access Methods // public PropertyAttributes Flags { get { return m_flags; } } public String Name { get { return m_name; } } public SignatureProperty PropertySignature { get { return m_type; } } public Object DefaultValue { get { if((m_flags & PropertyAttributes.HasDefault) != 0) { return m_constant.Value; } else { return null; } } } // // Debug Methods // public override String ToString() { return "MetaDataProperty(" + m_flags.ToString( "x" ) + "," + m_name + "," + m_type + ")"; } } } ================================================ FILE: Zelig/Zelig/CompileTime/MetaData/Importer/MetaDataResolver.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // // // Originally based on the Bartok code base. // //#define METADATARESOLVER_DEBUG #define METADATARESOLVER_DEBUG_OP_EQUALITY using System; using System.Collections.Generic; using System.Collections; using System.Reflection; using System.Text; namespace Microsoft.Zelig.MetaData { public interface ISymbolResolverHelper { Importer.PdbInfo.PdbFile ResolveAssemblySymbols( string file ); } public interface IMetaDataResolverHelper { Importer.MetaData ResolveAssemblyReference( string name , MetaDataVersion ver ); } public sealed class MetaDataResolver : Normalized.IMetaDataBootstrap { internal class AssemblyPair { // // State // internal Importer.MetaData Imported; internal Normalized.MetaDataAssembly Normalized; internal MetaDataNormalizationPhase Phase; // // Constructor Methods // internal AssemblyPair( Importer.MetaData imported , Normalized.MetaDataAssembly normalized ) { this.Imported = imported; this.Normalized = normalized; this.Phase = MetaDataNormalizationPhase.Uninitialized; } } //--// // // State // private IMetaDataResolverHelper m_metaDataResolverHelper; private List< Importer.MetaData > m_metaDataInitialSet; private List< AssemblyPair > m_metaDataList; private List< object > m_pendingEntries; private Normalized.MetaDataTypeDefinition[] m_lookupBuiltin; private GrowOnlyHashTable< String , Normalized.MetaDataTypeDefinitionBase > m_lookupTypeNames; private GrowOnlyHashTable< Importer .IMetaDataNormalize , Normalized.IMetaDataObject > m_lookupEntries; private GrowOnlyHashTable< Importer .IMetaDataNormalizeSignature, Normalized.MetaDataSignature > m_lookupSignatureEntries; private GrowOnlySet < Normalized.IMetaDataUnique > m_lookupUniques; private Normalized.MetaDataAssembly m_assemblyForDelayedParameters; // // Constructor Methods // public MetaDataResolver( IMetaDataResolverHelper metaDataResolverHelper ) { Importer.MetaData.ObjectComparer impComparer = new Importer.MetaData.ObjectComparer (); Importer.MetaData.SignatureComparer sigComparer = new Importer.MetaData.SignatureComparer(); m_metaDataResolverHelper = metaDataResolverHelper; m_metaDataInitialSet = new List< Importer.MetaData >(); m_metaDataList = new List< AssemblyPair >(); m_pendingEntries = new List< object >(); m_lookupBuiltin = new Normalized.MetaDataTypeDefinition[(int)ElementTypes.MAX]; m_lookupTypeNames = HashTableFactory.New < String , Normalized.MetaDataTypeDefinitionBase >( ); m_lookupEntries = HashTableFactory.NewWithComparer< Importer .IMetaDataNormalize , Normalized.IMetaDataObject >( impComparer ); m_lookupSignatureEntries = HashTableFactory.NewWithComparer< Importer .IMetaDataNormalizeSignature, Normalized.MetaDataSignature >( sigComparer ); m_lookupUniques = SetFactory .New < Normalized.IMetaDataUnique >( ); //--// m_assemblyForDelayedParameters = new Normalized.MetaDataAssembly( this.UniqueDictionary, 0 ); m_assemblyForDelayedParameters.m_name = ""; m_assemblyForDelayedParameters.m_version = new MetaDataVersion(); AssemblyPair pair = new AssemblyPair( null, m_assemblyForDelayedParameters ); m_metaDataList.Add( pair ); } //--// [System.Diagnostics.Conditional( "METADATARESOLVER_DEBUG" )] void DebugPrint( string fmt , params object[] args ) { Console.WriteLine( fmt, args ); } //--// public void Add( Importer.MetaData metaData ) { m_metaDataInitialSet.Add( metaData ); } //--// //[System.Diagnostics.DebuggerHidden] internal void RegisterBuiltIn( Normalized.MetaDataTypeDefinition td , ElementTypes elementType ) { m_lookupBuiltin[(int)elementType] = td; td.m_elementType = elementType; } //[System.Diagnostics.DebuggerHidden] internal Normalized.MetaDataTypeDefinition LookupBuiltIn( ElementTypes elementType ) { Normalized.MetaDataTypeDefinition res = m_lookupBuiltin[(int)elementType]; if(res != null) { return res; } throw Importer.IllegalMetaDataFormatException.Create( "Cannot resolve builtin {0}", elementType ); } //[System.Diagnostics.DebuggerHidden] internal Normalized.MetaDataTypeDefinitionBase ResolveName( String key , MetaDataNormalizationContext context ) { Normalized.MetaDataTypeDefinitionBase res; if(m_lookupTypeNames.TryGetValue( key, out res )) { return res; } string nameSpace; string name; string[] nested; string assemblyName; string extraInfo; Importer.MetaDataTypeDefinition.ParseName( key, out nameSpace, out name, out nested, out assemblyName, out extraInfo ); if(assemblyName != null) { AssemblyPair pair = FindAssembly( assemblyName, null, context ); Normalized.MetaDataTypeDefinitionBase td = ResolveName( pair, nameSpace, name, nested ); if(td != null) { m_lookupTypeNames[key] = td; return td; } } else { foreach(AssemblyPair pair in m_metaDataList) { Normalized.MetaDataTypeDefinitionBase td = ResolveName( pair, nameSpace, name, nested ); if(td != null) { m_lookupTypeNames[key] = td; return td; } } } throw Importer.UnresolvedExternalReferenceException.Create( null, "Cannot resolve reference to type '{0}' in '{1}'", key, context ); } private Normalized.MetaDataTypeDefinitionBase ResolveName( AssemblyPair pair , string nameSpace , string name , string[] nested ) { if(pair.Normalized != null) { return ResolveName( pair.Normalized, nameSpace, name, nested ); } return null; } private Normalized.MetaDataTypeDefinitionBase ResolveName( Normalized.MetaDataAssembly asml , string nameSpace , string name , string[] nested ) { foreach(Normalized.MetaDataTypeDefinitionAbstract td in asml.Types) { if(td is Normalized.MetaDataTypeDefinitionBase) { Normalized.MetaDataTypeDefinitionBase td2 = (Normalized.MetaDataTypeDefinitionBase)td; if(td2.IsNameMatch( nameSpace, name, nested )) { return td2; } } } return null; } //--// private void TrackRecursion_EnterNormalization( object src ) { if(m_pendingEntries.Contains( src )) { throw Importer.IllegalMetaDataFormatException.Create( "Detected recursive resolution attempt on: {0}", src ); } DebugPrint( "Normalizing:\r\n IN :{0}", src ); m_pendingEntries.Add( src ); } private void TrackRecursion_ExitNormalization( object src , object dst ) { m_pendingEntries.Remove( src ); DebugPrint( "Normalized:\r\n IN :{0}\r\n OUT:{1}", src, dst ); } private void TrackRecursion_EnterProcessing( object src , object dst ) { if(m_pendingEntries.Contains( src )) { throw Importer.IllegalMetaDataFormatException.Create( "Detected recursive resolution attempt on: {0}", src ); } DebugPrint( "Processing:\r\n IN :{0}\r\n OUT:{1}", src, dst ); m_pendingEntries.Add( src ); } private void TrackRecursion_ExitProcessing( object src , object dst ) { m_pendingEntries.Remove( src ); DebugPrint( "Processed:\r\n IN :{0}\r\n OUT:{1}", src, dst ); } //--// internal Normalized.MetaDataAssembly GetAssemblyForDelayedParameters() { return m_assemblyForDelayedParameters; } //--// //[System.Diagnostics.DebuggerHidden] internal Normalized.IMetaDataObject Lookup( Importer.IMetaDataObject key , MetaDataNormalizationContext context ) { if(key != null) { Normalized.IMetaDataObject en; if(m_lookupEntries.TryGetValue( (Importer.IMetaDataNormalize)key, out en )) { DebugPrint( "Lookup:\r\n IN :{0}\r\n OUT:{1}", key, en ); return en; } } return null; } //[System.Diagnostics.DebuggerHidden] internal Normalized.IMetaDataObject GetNormalizedObject( Importer.IMetaDataNormalize obj , MetaDataNormalizationContext context , MetaDataNormalizationMode mode ) { if(obj == null) { return null; } bool fLookupExisting = (mode & MetaDataNormalizationMode.LookupExisting ) != 0; bool fAllocate = (mode & MetaDataNormalizationMode.Allocate ) != 0; Normalized.IMetaDataObject en; if(m_lookupEntries.TryGetValue( obj, out en )) { if(fLookupExisting) { DebugPrint( "Lookup:\r\n IN :{0}\r\n OUT:{1}", obj, en ); return en; } throw Importer.IllegalMetaDataFormatException.Create( "Detected recursive allocation attempt on: {0}", obj ); } if(!fAllocate) { throw Importer.IllegalMetaDataFormatException.Create( "Cannot resolve lookup: {0}", obj ); } //--// TrackRecursion_EnterNormalization( obj ); Normalized.IMetaDataObject res = obj.AllocateNormalizedObject( context ); if(res == null) { throw Unresolvable( obj ); } TrackRecursion_ExitNormalization( obj, res ); //--// if(m_lookupEntries.ContainsKey( obj )) { throw Importer.IllegalMetaDataFormatException.Create( "Internal error: MetaData object redefined => {0}", obj ); } m_lookupEntries.Add( obj, res ); return res; } //[System.Diagnostics.DebuggerHidden] internal Normalized.MetaDataSignature GetNormalizedObject( Importer.IMetaDataNormalizeSignature obj , MetaDataNormalizationContext context , MetaDataNormalizationMode mode ) { if(obj == null) { return null; } bool fLookupExisting = (mode & MetaDataNormalizationMode.LookupExisting ) != 0; bool fAllocate = (mode & MetaDataNormalizationMode.Allocate ) != 0; Normalized.MetaDataSignature en; if(m_lookupSignatureEntries.TryGetValue( obj, out en )) { if(fLookupExisting) { DebugPrint( "Lookup:\r\n IN :{0}\r\n OUT:{1}", obj, en ); return en; } throw Importer.IllegalMetaDataFormatException.Create( "Detected recursive allocation attempt on: {0}", obj ); } if(!fAllocate) { throw Importer.IllegalMetaDataFormatException.Create( "Cannot resolve lookup: {0}", obj ); } //--// TrackRecursion_EnterNormalization( obj ); Normalized.MetaDataSignature res = obj.AllocateNormalizedObject( context ); if(res == null) { throw Unresolvable( obj ); } TrackRecursion_ExitNormalization( obj, res ); //--// if(m_lookupSignatureEntries.ContainsKey( obj )) { throw Importer.IllegalMetaDataFormatException.Create( "Internal error: MetaData object redefined => {0}", obj ); } m_lookupSignatureEntries.Add( obj, res ); return res; } //[System.Diagnostics.DebuggerHidden] internal void ProcessPhase( Importer.IMetaDataObject obj , MetaDataNormalizationContext context ) { if(obj != null) { Importer.IMetaDataNormalize obj2 = (Importer.IMetaDataNormalize)obj; Normalized.IMetaDataObject dst = GetNormalizedObject( obj2, context, MetaDataNormalizationMode.LookupExisting ); TrackRecursion_EnterProcessing( obj2, dst ); obj2.ExecuteNormalizationPhase( dst, context ); TrackRecursion_ExitProcessing( obj2, dst ); } } //--// public Normalized.MetaDataAssembly[] NormalizedAssemblies { get { List< Normalized.MetaDataAssembly > lst = new List< Normalized.MetaDataAssembly >(); foreach(AssemblyPair pair in m_metaDataList) { lst.Add( pair.Normalized ); } return lst.ToArray(); } } public Normalized.MetaDataMethodBase ApplicationEntryPoint { get { foreach(AssemblyPair pair in m_metaDataList) { Normalized.MetaDataMethodBase entryPoint = pair.Normalized.EntryPoint; if(entryPoint != null) { return entryPoint; } } return null; } } internal GrowOnlySet< Normalized.IMetaDataUnique > UniqueDictionary { get { return m_lookupUniques; } } //--// // // Normalized.IMetaDataBootstrap // Normalized.MetaDataAssembly Normalized.IMetaDataBootstrap.GetAssembly( string name ) { List res = new List(); foreach(AssemblyPair pair in m_metaDataList) { Normalized.MetaDataAssembly asml = pair.Normalized; // // BUGBUG: We need a better check. // if(asml.Name == name) { return asml; } } return null; } Normalized.MetaDataTypeDefinitionAbstract Normalized.IMetaDataBootstrap.ResolveType( Normalized.MetaDataAssembly asml , string nameSpace , string name ) { return ResolveName( asml, nameSpace, name, null ); } Normalized.MetaDataMethodBase Normalized.IMetaDataBootstrap.GetApplicationEntryPoint() { return this.ApplicationEntryPoint; } void Normalized.IMetaDataBootstrap.FilterTypesByCustomAttribute( Normalized.MetaDataTypeDefinitionAbstract filter , Normalized.IMetaDataBootstrap_FilterTypesByCustomAttributeCallback callback ) { foreach(Normalized.MetaDataAssembly asml in this.NormalizedAssemblies) { foreach(Normalized.MetaDataTypeDefinitionAbstract td in asml.Types) { Normalized.MetaDataCustomAttribute[] caArray = td.CustomAttributes; if(caArray != null) { foreach(Normalized.MetaDataCustomAttribute ca in caArray) { Normalized.MetaDataMethodBase md = ca.Constructor as Normalized.MetaDataMethodBase; if(md != null && md.Owner == filter) { callback( td, ca ); } } } } } } //--// public void ResolveAll() { MetaDataNormalizationContext context = new MetaDataNormalizationContext( this ); MetaDataNormalizationPhase phase; #if METADATARESOLVER_DEBUG System.IO.TextWriter orig = Console.Out; System.IO.StreamWriter writer = new System.IO.StreamWriter( Environment.ExpandEnvironmentVariables( @"%DEPOTROOT%\ZeligUnitTestResults\MetaDataResolver.txt" ), false, System.Text.Encoding.ASCII ); Console.SetOut( writer ); #endif for(phase = MetaDataNormalizationPhase.ResolutionOfAssemblyReferences; phase < MetaDataNormalizationPhase.Max; phase++) //for(phase = MetaDataNormalizationPhase.ResolutionOfAssemblyReferences; phase < MetaDataNormalizationPhase.ResolutionOfCustomAttributes; phase++) { RunPhase( context, phase ); } #if METADATARESOLVER_DEBUG Console.SetOut( orig ); writer.Close(); #endif } private void RunPhase( MetaDataNormalizationContext context , MetaDataNormalizationPhase phase ) { context.SetPhase( phase ); if(phase == MetaDataNormalizationPhase.ResolutionOfAssemblyReferences) { while(m_metaDataInitialSet.Count > 0) { Importer.MetaData md = m_metaDataInitialSet[0]; m_metaDataInitialSet.RemoveAt( 0 ); EnqueueAssembly( md, context ); } } else { bool fDone; do { fDone = true; foreach(AssemblyPair pair in m_metaDataList.ToArray()) { Importer.MetaData imported = pair.Imported; if(imported != null) { if(imported.ExecuteNormalizationPhase( pair, context ) == false) { fDone = false; break; } } } } while(fDone == false); } context.FlushErrors(); } //--// private Exception Unresolvable( object obj ) { return Importer.IllegalMetaDataFormatException.Create( "Cannot resolve reference: {0}", obj ); } //--// internal AssemblyPair FindAssembly( Importer.MetaData md ) { foreach(AssemblyPair pair in m_metaDataList) { if(pair.Imported == md) { return pair; } } return null; } internal AssemblyPair FindAssembly( string name , MetaDataVersion version , MetaDataNormalizationContext context ) { Importer.MetaData md = FindImporterAssembly( name, version ); if(md == null) { md = m_metaDataResolverHelper.ResolveAssemblyReference( name, version ); if(md == null) { throw Importer.UnresolvedExternalReferenceException.Create( null, "Cannot resolve reference to assembly: {0} {1}", name, version ); } } return EnqueueAssembly( md, context ); } private AssemblyPair EnqueueAssembly( Importer.MetaData md , MetaDataNormalizationContext context ) { AssemblyPair pair = FindAssembly( md ); if(pair == null) { pair = new AssemblyPair( md, null ); m_metaDataList.Add( pair ); MetaDataNormalizationPhase activePhase = context.Phase; MetaDataNormalizationPhase runPhase = MetaDataNormalizationPhase.ResolutionOfAssemblyReferences; context.SetPhase( runPhase ); md.AllocateNormalizedObject( pair, context ); while(++runPhase < activePhase) { context.SetPhase( runPhase ); while(md.ExecuteNormalizationPhase( pair, context ) == false) { } } context.SetPhase( activePhase ); } return pair; } private Importer.MetaData FindImporterAssembly( string name , MetaDataVersion version ) { foreach(AssemblyPair pair in m_metaDataList) { Importer.MetaData imported = pair.Imported; if(imported != null) { Importer.MetaDataAssembly asml = imported.Assembly; if(asml.Name == name) { // // BUGBUG: This version check does not cover at all the complexity of versioning... // if(version == null || asml.Version.IsCompatible( version, false )) { return pair.Imported; } } } } for(int i = 0; i < m_metaDataInitialSet.Count; i++) { Importer.MetaData md = m_metaDataInitialSet[i]; if(md.Assembly.Name == name) { // // BUGBUG: This version check does not cover at all the complexity of versioning... // if(version == null || md.Assembly.Version.IsCompatible( version, false )) { m_metaDataInitialSet.RemoveAt( i ); return md; } } } return null; } } } ================================================ FILE: Zelig/Zelig/CompileTime/MetaData/Importer/MetaDataStandAloneSig.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // // // Originally based on the Bartok code base. // using System; using System.Collections.Generic; using System.Text; namespace Microsoft.Zelig.MetaData.Importer { public sealed class MetaDataStandAloneSig : MetaDataObject, IMetaDataNormalize { // // State // private Signature m_signature; // // Constructor Methods // private MetaDataStandAloneSig( int index ) : base( TokenType.StandAloneSig, index ) { } // Helper methods to work around limitations in generics, see Parser.InitializeTable internal static MetaDataObject.CreateInstance GetCreator() { return new MetaDataObject.CreateInstance( Creator ); } private static MetaDataObject Creator( int index ) { return new MetaDataStandAloneSig( index ); } //--// internal override void Parse( Parser parser , Parser.TableSchema ts , ArrayReader reader ) { Parser.IndexReader signatureReader = ts.m_columns[0].m_reader; int signatureIndex = signatureReader( reader ); m_signature = Signature.ParseUnknown( parser, parser.getSignature( signatureIndex ) ); } // // IMetaDataNormalize methods // Normalized.MetaDataObject IMetaDataNormalize.AllocateNormalizedObject( MetaDataNormalizationContext context ) { //// this.signature.resolveExternalReferences( resolver ); throw context.InvalidPhase( this ); } void IMetaDataNormalize.ExecuteNormalizationPhase( Normalized.IMetaDataObject obj , MetaDataNormalizationContext context ) { throw context.InvalidPhase( this ); } // // Access Methods // public Signature Signature { get { return m_signature; } } // // Debug Methods // public override String ToString() { return "MetaDataStandAloneSig(" + m_signature + ")"; } } } ================================================ FILE: Zelig/Zelig/CompileTime/MetaData/Importer/MetaDataTypeDefinition.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // // // Originally based on the Bartok code base. // using System; using System.Collections.Generic; using System.Collections; using System.Reflection; using System.Text; namespace Microsoft.Zelig.MetaData.Importer { public sealed class MetaDataTypeDefinition : MetaDataObject, IMetaDataTypeDefOrRef, IMetaDataHasDeclSecurity, IMetaDataTypeOrMethodDef, IMetaDataNormalize { // // State // private TypeAttributes m_flags; private IMetaDataTypeDefOrRef m_extends; private string m_name; private string m_nameSpace; private MetaDataTypeDefinition m_enclosingClass; private List m_nestedClasses; private List m_genericParamList; private List m_interfaces; private List m_fields; private List m_methods; private List m_events; private List m_properties; private MetaDataClassLayout m_classLayout; // // Constructor Methods // private MetaDataTypeDefinition( int index ) : base( TokenType.TypeDef, index ) { } // Helper methods to work around limitations in generics, see Parser.InitializeTable internal static MetaDataObject.CreateInstance GetCreator() { return new MetaDataObject.CreateInstance( Creator ); } private static MetaDataObject Creator( int index ) { return new MetaDataTypeDefinition( index ); } //--// internal override void Parse( Parser parser , Parser.TableSchema ts , ArrayReader reader ) { Parser.IndexReader extendsReader = ts.m_columns[3].m_reader; Parser.IndexReader fieldReader = ts.m_columns[4].m_reader; Parser.IndexReader methodReader = ts.m_columns[5].m_reader; int extendsIndex; int fieldIndex; int methodIndex; m_flags = (TypeAttributes) reader.ReadInt32(); m_name = parser.readIndexAsString( reader ); m_nameSpace = parser.readIndexAsString( reader ); extendsIndex = extendsReader ( reader ); fieldIndex = fieldReader ( reader ); methodIndex = methodReader ( reader ); m_extends = parser.getTypeDefOrRef( extendsIndex ); parser.SetFieldIndex ( this, fieldIndex ); parser.SetMethodIndex( this, methodIndex ); } // // IMetaDataNormalize methods // Normalized.MetaDataObject IMetaDataNormalize.AllocateNormalizedObject( MetaDataNormalizationContext context ) { switch(context.Phase) { case MetaDataNormalizationPhase.CreationOfTypeDefinitions: { Normalized.MetaDataTypeDefinitionBase tdNew; Normalized.MetaDataAssembly owner = (Normalized.MetaDataAssembly)context.Value; if(m_genericParamList != null && m_genericParamList.Count > 0) { tdNew = new Normalized.MetaDataTypeDefinitionGeneric( owner, m_token ); } else { tdNew = new Normalized.MetaDataTypeDefinition( owner, m_token ); } tdNew.m_flags = m_flags; tdNew.m_name = m_name; tdNew.m_nameSpace = m_nameSpace; owner.Types.Add( tdNew ); context = context.Push( tdNew ); if(tdNew is Normalized.MetaDataTypeDefinitionGeneric) { Normalized.MetaDataTypeDefinitionGeneric tdNewG = (Normalized.MetaDataTypeDefinitionGeneric)tdNew; context.GetNormalizedObjectList( m_genericParamList, out tdNewG.m_genericParams, MetaDataNormalizationMode.Default ); } return tdNew; } } throw context.InvalidPhase( this ); } void IMetaDataNormalize.ExecuteNormalizationPhase( Normalized.IMetaDataObject obj , MetaDataNormalizationContext context ) { Normalized.MetaDataTypeDefinitionBase td = (Normalized.MetaDataTypeDefinitionBase)obj; context = context.Push( obj ); switch(context.Phase) { case MetaDataNormalizationPhase.LinkingOfNestedClasses: { context.GetNormalizedObject ( m_enclosingClass, out td.m_enclosingClass, MetaDataNormalizationMode.LookupExisting ); context.GetNormalizedObjectList( m_nestedClasses , out td.m_nestedClasses , MetaDataNormalizationMode.LookupExisting ); } return; case MetaDataNormalizationPhase.DiscoveryOfBuiltInTypes: { ElementTypes elementType = ElementTypes.END; if(m_enclosingClass == null && m_nameSpace == "System" && td.m_owner.Name == "mscorlib") { switch(m_name) { case "Void" : elementType = ElementTypes.VOID ; break; case "Boolean" : elementType = ElementTypes.BOOLEAN ; break; case "Char" : elementType = ElementTypes.CHAR ; break; case "SByte" : elementType = ElementTypes.I1 ; break; case "Byte" : elementType = ElementTypes.U1 ; break; case "Int16" : elementType = ElementTypes.I2 ; break; case "UInt16" : elementType = ElementTypes.U2 ; break; case "Int32" : elementType = ElementTypes.I4 ; break; case "UInt32" : elementType = ElementTypes.U4 ; break; case "Int64" : elementType = ElementTypes.I8 ; break; case "UInt64" : elementType = ElementTypes.U8 ; break; case "Single" : elementType = ElementTypes.R4 ; break; case "Double" : elementType = ElementTypes.R8 ; break; case "String" : elementType = ElementTypes.STRING ; break; case "IntPtr" : elementType = ElementTypes.I ; break; case "UIntPtr" : elementType = ElementTypes.U ; break; case "Object" : elementType = ElementTypes.OBJECT ; break; case "Array" : elementType = ElementTypes.SZARRAY ; break; case "ValueType" : elementType = ElementTypes.VALUETYPE ; break; case "TypedReference": elementType = ElementTypes.TYPEDBYREF; break; } } if(elementType != ElementTypes.END) { context.RegisterBuiltIn( (Normalized.MetaDataTypeDefinition)td, elementType ); } } return; case MetaDataNormalizationPhase.CreationOfTypeHierarchy: { context.GetNormalizedObject( m_extends, out td.m_extends, MetaDataNormalizationMode.Default ); if(td.m_elementType == ElementTypes.END) { if((td.m_flags & TypeAttributes.ClassSemanticsMask) == TypeAttributes.Interface) { td.m_elementType = ElementTypes.CLASS; } else if(td.m_extends != null && td.m_extends.m_elementType == ElementTypes.VALUETYPE) { td.m_elementType = ElementTypes.VALUETYPE; } else { td.m_elementType = ElementTypes.CLASS; } } } return; case MetaDataNormalizationPhase.CompletionOfTypeNormalization: { context.GetNormalizedObjectList( m_interfaces, out td.m_interfaces, MetaDataNormalizationMode.Default ); if(td is Normalized.MetaDataTypeDefinitionGeneric) { context.ProcessPhaseList( m_genericParamList ); } context.GetNormalizedObject( m_classLayout, out td.m_classLayout, MetaDataNormalizationMode.Default ); } return; case MetaDataNormalizationPhase.CreationOfFieldDefinitions: { context.GetNormalizedObjectList( m_fields, out td.m_fields, MetaDataNormalizationMode.Allocate ); } return; case MetaDataNormalizationPhase.CreationOfMethodDefinitions: { context.GetNormalizedObjectList( m_methods, out td.m_methods, MetaDataNormalizationMode.Allocate ); } return; case MetaDataNormalizationPhase.CompletionOfMethodNormalization: { context.GetNormalizedObjectList( m_events , out td.m_events , MetaDataNormalizationMode.Allocate ); context.GetNormalizedObjectList( m_properties, out td.m_properties, MetaDataNormalizationMode.Allocate ); context.ProcessPhaseList( m_methods ); } return; case MetaDataNormalizationPhase.ResolutionOfCustomAttributes: { context.GetNormalizedObjectList( this.CustomAttributes, out td.m_customAttributes, MetaDataNormalizationMode.Allocate ); context.ProcessPhaseList( m_genericParamList ); context.ProcessPhaseList( m_fields ); context.ProcessPhaseList( m_methods ); context.ProcessPhaseList( m_events ); context.ProcessPhaseList( m_properties ); } return; } throw context.InvalidPhase( this ); } //--// // These are technically not constructor methods, but they are meant // to be used to set up the object internal void AddGenericParam( MetaDataGenericParam genericParam ) { if(m_genericParamList == null) { m_genericParamList = new List( 2 ); } if(genericParam.Number != m_genericParamList.Count) { throw IllegalMetaDataFormatException.Create( "Generic parameters out of order - is this allowed?" ); } m_genericParamList.Add( genericParam ); } internal void AddInterface( IMetaDataTypeDefOrRef itf ) { if(m_interfaces == null) { m_interfaces = new List( 2 ); } m_interfaces.Add( itf ); } internal void AddField( MetaDataField field ) { if(m_fields == null) { m_fields = new List( 2 ); } m_fields.Add( field ); } internal void AddMethod( MetaDataMethod method ) { if(m_methods == null) { m_methods = new List( 2 ); } m_methods.Add( method ); } internal void AddNestedClass( MetaDataTypeDefinition nestedClass ) { if(m_nestedClasses == null) { m_nestedClasses = new List( 2 ); } m_nestedClasses.Add( nestedClass ); nestedClass.m_enclosingClass = this; } internal void AddEvent( MetaDataEvent eventObject ) { if(m_events == null) { m_events = new List( 2 ); } m_events.Add( eventObject ); } internal void AddProperty( MetaDataProperty propertyObject ) { if(m_properties == null) { m_properties = new List( 2 ); } m_properties.Add( propertyObject ); } //--// internal void SetClassLayout( MetaDataClassLayout classLayout ) { m_classLayout = classLayout; } // // Access Methods // public TypeAttributes Flags { get { return m_flags; } } public string Name { get { return m_name; } } public string Namespace { get { return m_nameSpace; } } public List GenericParamList { get { return m_genericParamList; } } public IMetaDataTypeDefOrRef Extends { get { return m_extends; } } public List Interfaces { get { return m_interfaces; } } public List Fields { get { return m_fields; } } public List Methods { get { return m_methods; } } public MetaDataTypeDefinition EnclosingClass { get { return m_enclosingClass; } } public List NestedClasses { get { return m_nestedClasses; } } public MetaDataClassLayout ClassLayout { get { return m_classLayout; } } public bool IsNestedType { get { return m_enclosingClass != null; } } // for non-nested types, returns . // for nested types, returns . public override string FullName { get { System.Text.StringBuilder sb = new System.Text.StringBuilder(); if(this.IsNestedType) { sb.Append( this.EnclosingClass.FullName ); sb.Append( "." ); } if(this.Namespace.Length != 0) { sb.Append( this.Namespace ); sb.Append( "." ); } sb.Append( this.Name ); return sb.ToString(); } } public override string FullNameWithContext { get { return "type definition " + this.FullName; } } public static void ParseName( string typeName , out string nameSpace , out string name , out string[] nested , out string assemblyName , out string extraInfo ) { // // An external type reference has this structure: // // .[+]*[, [, Version=[, Culture=[, PublicKeyToken=]]]] // int index; index = typeName.IndexOf( ',' ); if(index >= 0) { extraInfo = typeName.Substring( index+1 ).TrimStart(); typeName = typeName.Substring( 0 , index ); index = extraInfo.IndexOf( ',' ); if(index >= 0) { assemblyName = extraInfo.Substring( 0 , index ); extraInfo = extraInfo.Substring( index+1 ).TrimStart(); } else { assemblyName = null; } } else { assemblyName = null; extraInfo = null; } // Is this a nested class? index = typeName.IndexOf( '+' ); if(index >= 0) { string[] split = typeName.Split( '+' ); nested = new string[split.Length-1]; Array.Copy( split, 1, nested, 0, nested.Length ); typeName = split[0]; } else { nested = null; } index = typeName.LastIndexOf( '.' ); if(index >= 0) { nameSpace = typeName.Substring( 0 , index ); name = typeName.Substring( index+1 ); } else { nameSpace = null; name = typeName; } } public bool IsNameMatch( string nameSpace , string name , string[] nested ) { MetaDataTypeDefinition td = this; if(nested != null) { int nestedSize = nested.Length; while(nestedSize > 0) { if(td.IsNestedType == false) { return false; } if(td.Name != nested[--nestedSize]) { return false; } td = td.m_enclosingClass; } } if(td.IsNestedType == true) { return false; } if(td.Namespace == nameSpace && td.Name == name) { return true; } return false; } public override string ToString() { return "MetaDataTypeDefinition(" + this.FullName + ")"; } public override string ToStringLong() { System.Text.StringBuilder sb = new System.Text.StringBuilder( "MetaDataTypeDefinition(" ); sb.Append( ((int)m_flags).ToString( "x" ) ); sb.Append( "," ); sb.Append( this.FullName ); sb.Append( "," ); if(m_genericParamList != null && m_genericParamList.Count > 0) { sb.Append( "GenericParams<" ); foreach(MetaDataGenericParam param in m_genericParamList) { sb.Append( param.ToString() ); sb.Append( "," ); } sb.Remove( sb.Length - 1, 1 ); sb.Append( ">," ); } if(m_extends != null) { sb.Append( m_extends.ToString() ); } sb.Append( "," ); if(m_interfaces != null && m_interfaces.Count > 0) { sb.Append( "interfaces(" ); foreach(MetaDataObject interfaceObject in m_interfaces) { sb.Append( interfaceObject.ToString() ); sb.Append( "," ); } sb.Remove( sb.Length - 1, 1 ); sb.Append( ")" ); } else { sb.Append( "No interfaces" ); } sb.Append( "," ); if(m_fields.Count > 0) { sb.Append( "fields(" ); foreach(MetaDataField field in m_fields) { sb.Append( field.ToString() ); sb.Append( "," ); } sb.Remove( sb.Length - 1, 1 ); sb.Append( ")" ); } else { sb.Append( "No fields" ); } sb.Append( "," ); if(m_methods.Count > 0) { sb.Append( "methods(" ); foreach(MetaDataMethod method in m_methods) { sb.Append( method.ToString() ); sb.Append( "," ); } sb.Remove( sb.Length - 1, 1 ); sb.Append( ")" ); } else { sb.Append( "No methods" ); } sb.Append( ")" ); return sb.ToString(); } } } ================================================ FILE: Zelig/Zelig/CompileTime/MetaData/Importer/MetaDataTypeReference.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // // // Originally based on the Bartok code base. // using System; using System.Collections.Generic; using System.Text; namespace Microsoft.Zelig.MetaData.Importer { public sealed class MetaDataTypeReference : MetaDataObject, IMetaDataTypeDefOrRef, IMetaDataMemberRefParent, IMetaDataResolutionScope, IMetaDataNormalize { // // State // private IMetaDataResolutionScope m_resolutionScope; private String m_name; private String m_nameSpace; // // Constructor Methods // private MetaDataTypeReference( int index ) : base( TokenType.TypeRef, index ) { } // Helper methods to work around limitations in generics, see Parser.InitializeTable internal static MetaDataObject.CreateInstance GetCreator() { return new MetaDataObject.CreateInstance( Creator ); } private static MetaDataObject Creator( int index ) { return new MetaDataTypeReference( index ); } //--// internal override void Parse( Parser parser , Parser.TableSchema ts , ArrayReader reader ) { Parser.IndexReader bigScopeIndexReader = ts.m_columns[0].m_reader; int resolutionScopeIndex; resolutionScopeIndex = bigScopeIndexReader( reader ); m_name = parser.readIndexAsString ( reader ); m_nameSpace = parser.readIndexAsString ( reader ); m_resolutionScope = parser.getResolutionScope( resolutionScopeIndex ); } // // IMetaDataNormalize methods // Normalized.MetaDataObject IMetaDataNormalize.AllocateNormalizedObject( MetaDataNormalizationContext context ) { switch(context.Phase) { case MetaDataNormalizationPhase.ResolutionOfTypeReferences: { Normalized.IMetaDataObject scope; context.GetNormalizedObject( m_resolutionScope, out scope, MetaDataNormalizationMode.Default ); // // WARNING: This lookup is oblivious of visibility constraints!! // if(scope is Normalized.MetaDataAssembly) { Normalized.MetaDataAssembly asml = (Normalized.MetaDataAssembly)scope; foreach(Normalized.MetaDataTypeDefinitionAbstract td in asml.Types) { if(td is Normalized.MetaDataTypeDefinitionBase) { Normalized.MetaDataTypeDefinitionBase td2 = (Normalized.MetaDataTypeDefinitionBase)td; if(td2.Namespace == m_nameSpace && td2.Name == m_name ) { return td2; } } } } else if(scope is Normalized.MetaDataTypeDefinitionBase) { Normalized.MetaDataTypeDefinitionBase td = (Normalized.MetaDataTypeDefinitionBase)scope; foreach(Normalized.MetaDataTypeDefinitionAbstract tdNested in td.NestedClasses) { if(tdNested is Normalized.MetaDataTypeDefinitionBase) { Normalized.MetaDataTypeDefinitionBase tdNested2 = (Normalized.MetaDataTypeDefinitionBase)tdNested; if(tdNested2.Name == m_name) { return tdNested2; } } } } throw UnresolvedExternalReferenceException.Create( this, "Cannot resolve external reference '{0}'", this.FullName ); } } throw context.InvalidPhase( this ); } void IMetaDataNormalize.ExecuteNormalizationPhase( Normalized.IMetaDataObject obj , MetaDataNormalizationContext context ) { throw context.InvalidPhase( this ); } // // Access Methods // // Returns one of MetaData{Module,ModuleRef,AssemblyRef,TypeReference} public IMetaDataResolutionScope ResolutionScope { get { return m_resolutionScope; } } public String Name { get { return m_name; } } public String Namespace { get { return m_nameSpace; } } public override string FullName { get { String fullName; if(this.Namespace.Length == 0) { fullName = this.Name; } else { fullName = this.Namespace + "." + this.Name; } if(this.ResolutionScope is MetaDataTypeReference) { MetaDataTypeReference typeRef = (MetaDataTypeReference)this.ResolutionScope; fullName = typeRef.FullName + "." + fullName; } return fullName; } } public override string FullNameWithContext { get { return "type reference " + this.FullName; } } // // Debug Methods // public override String ToString() { return "MetaDataTypeReference(" + this.FullName + ")"; } public override String ToStringLong() { System.Text.StringBuilder sb = new System.Text.StringBuilder( "MetaDataTypeReference(" ); sb.Append( "[" ); sb.Append( m_resolutionScope ); sb.Append( "]" ); sb.Append( this.FullName ); sb.Append( ")" ); return sb.ToString(); } } } ================================================ FILE: Zelig/Zelig/CompileTime/MetaData/Importer/MetaDataTypeSpec.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // // // Originally based on the Bartok code base. // using System; using System.Collections.Generic; using System.Text; namespace Microsoft.Zelig.MetaData.Importer { public sealed class MetaDataTypeSpec : MetaDataObject, IMetaDataTypeDefOrRef, IMetaDataMemberRefParent, IMetaDataNormalize { // // State // private SignatureTypeSpec m_signature; // // Constructor Methods // private MetaDataTypeSpec( int index ) : base( TokenType.TypeSpec, index ) { } // Helper methods to work around limitations in generics, see Parser.InitializeTable internal static MetaDataObject.CreateInstance GetCreator() { return new MetaDataObject.CreateInstance( Creator ); } private static MetaDataObject Creator( int index ) { return new MetaDataTypeSpec( index ); } //--// internal override void Parse( Parser parser , Parser.TableSchema ts , ArrayReader reader ) { int signatureIndex = parser.readIndexAsForBlob( reader ); m_signature = SignatureTypeSpec.Parse( parser, parser.getSignature( signatureIndex ) ); } // // IMetaDataNormalize methods // Normalized.MetaDataObject IMetaDataNormalize.AllocateNormalizedObject( MetaDataNormalizationContext context ) { switch(context.Phase) { case MetaDataNormalizationPhase.CreationOfTypeHierarchy : case MetaDataNormalizationPhase.CompletionOfTypeNormalization : case MetaDataNormalizationPhase.CompletionOfMethodNormalization: { Normalized.SignatureType res; context.GetNormalizedSignature( m_signature, out res, MetaDataNormalizationMode.Default ); return res.Type; } } throw context.InvalidPhase( this ); } void IMetaDataNormalize.ExecuteNormalizationPhase( Normalized.IMetaDataObject obj , MetaDataNormalizationContext context ) { throw context.InvalidPhase( this ); } // // Access Methods // public SignatureTypeSpec Signature { get { return m_signature; } } // // Debug Methods // public override String ToString() { return "MetaDataTypeSpec(" + m_signature + ")"; } } } ================================================ FILE: Zelig/Zelig/CompileTime/MetaData/Importer/PDBInfo/BitSet.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // // // Originally from the Microsoft Research Singularity code base. // namespace Microsoft.Zelig.MetaData.Importer.PdbInfo.Features { public class BitSet { // // State // private int m_size; private uint[] m_words; // // Constructor Methods // public BitSet( ArrayReader bits ) { m_size = bits.ReadInt32 ( ); // 0..3 : Number of words m_words = bits.ReadUInt32Array( m_size ); } public BitSet( int size ) { m_size = size; m_words = new uint[size]; } // // Helper Methods // public void Emit( ArrayWriter writer ) { writer.Write( m_size ); writer.Write( m_words ); } //--// public bool IsSet( int index ) { int word = index / 32; if(word >= 0 && word < m_words.Length) { return ((m_words[word] & GetBit( index )) != 0); } return false; } public void Set( int index ) { int word = index / 32; EnsureSize( word ); m_words[word] |= GetBit( index ); } public void Clear( int index ) { int word = index / 32; EnsureSize( word ); m_words[word] &= ~GetBit( index ); } private void EnsureSize( int word ) { m_words = ArrayUtility.EnsureSizeOfNotNullArray( m_words, word + 1 ); m_size = m_words.Length; } private static uint GetBit( int index ) { return ((uint)1 << (index % 32)); } // // Access Methods // public bool IsEmpty { get { return m_size == 0; } } } } ================================================ FILE: Zelig/Zelig/CompileTime/MetaData/Importer/PDBInfo/CvInfo.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // // // Originally from the Microsoft Research Singularity code base. // // // File: CvInfo.cs // // Generic CodeView information definitions // // Structures, constants, etc. for accessing and interpreting // CodeView information. // // The master copy of this file resides in the langapi project (in C++). // All Microsoft projects are required to use the master copy without // modification. Modification of the master version or a copy // without consultation with all parties concerned is extremely // risky. // // When this file is modified, the corresponding documentation file // omfdeb.doc in the langapi project must be updated. // // This is a read-only copy of the C++ file converted to C#. // namespace Microsoft.Zelig.MetaData.Importer.PdbInfo.CodeView { using System; public struct FLOAT10 { public byte Data_0; public byte Data_1; public byte Data_2; public byte Data_3; public byte Data_4; public byte Data_5; public byte Data_6; public byte Data_7; public byte Data_8; public byte Data_9; } public enum CV_SIGNATURE { C6 = 0, // Actual signature is >64K C7 = 1, // First explicit signature C11 = 2, // C11 (vc5.x) 32-bit types C13 = 4, // C13 (vc7.x) zero terminated names RESERVERD = 5, // All signatures from 5 to 64K are reserved } // CodeView Symbol and Type OMF type information is broken up into two // ranges. Type indices less than 0x1000 describe type information // that is frequently used. Type indices above 0x1000 are used to // describe more complex features such as functions, arrays and // structures. // // Primitive types have predefined meaning that is encoded in the // values of the various bit fields in the value. // // A CodeView primitive type is defined as: // // 1 1 // 1 089 7654 3 210 // r mode type r sub // // Where // mode is the pointer mode // type is a type indicator // sub is a subtype enumeration // r is a reserved field // // See Microsoft Symbol and Type OMF (Version 4.0) for more // information. // // pointer mode enumeration values public enum CV_prmode { CV_TM_DIRECT = 0, // mode is not a pointer CV_TM_NPTR32 = 4, // mode is a 32 bit near pointer CV_TM_NPTR64 = 6, // mode is a 64 bit near pointer CV_TM_NPTR128 = 7, // mode is a 128 bit near pointer } // type enumeration values public enum CV_type { CV_SPECIAL = 0x00, // special type size values CV_SIGNED = 0x01, // signed integral size values CV_UNSIGNED = 0x02, // unsigned integral size values CV_BOOLEAN = 0x03, // Boolean size values CV_REAL = 0x04, // real number size values CV_COMPLEX = 0x05, // complex number size values CV_SPECIAL2 = 0x06, // second set of special types CV_INT = 0x07, // integral (int) values CV_CVRESERVED = 0x0F, } // subtype enumeration values for CV_SPECIAL public enum CV_special { CV_SP_NOTYPE = 0x00, CV_SP_ABS = 0x01, CV_SP_SEGMENT = 0x02, CV_SP_VOID = 0x03, CV_SP_CURRENCY = 0x04, CV_SP_NBASICSTR = 0x05, CV_SP_FBASICSTR = 0x06, CV_SP_NOTTRANS = 0x07, CV_SP_HRESULT = 0x08, } // subtype enumeration values for CV_SPECIAL2 public enum CV_special2 { CV_S2_BIT = 0x00, CV_S2_PASCHAR = 0x01, // Pascal CHAR } // subtype enumeration values for CV_SIGNED, CV_UNSIGNED and CV_BOOLEAN public enum CV_integral { CV_IN_1BYTE = 0x00, CV_IN_2BYTE = 0x01, CV_IN_4BYTE = 0x02, CV_IN_8BYTE = 0x03, CV_IN_16BYTE = 0x04, } // subtype enumeration values for CV_REAL and CV_COMPLEX public enum CV_real { CV_RC_REAL32 = 0x00, CV_RC_REAL64 = 0x01, CV_RC_REAL80 = 0x02, CV_RC_REAL128 = 0x03, } // subtype enumeration values for CV_INT (really int) public enum CV_int { CV_RI_CHAR = 0x00, CV_RI_INT1 = 0x00, CV_RI_WCHAR = 0x01, CV_RI_UINT1 = 0x01, CV_RI_INT2 = 0x02, CV_RI_UINT2 = 0x03, CV_RI_INT4 = 0x04, CV_RI_UINT4 = 0x05, CV_RI_INT8 = 0x06, CV_RI_UINT8 = 0x07, CV_RI_INT16 = 0x08, CV_RI_UINT16 = 0x09, } public struct CV_PRIMITIVE_TYPE { const uint CV_MMASK = 0x700; // mode mask const uint CV_TMASK = 0x0F0; // type mask const uint CV_SMASK = 0x00F; // subtype mask const int CV_MSHIFT = 8; // primitive mode right shift count const int CV_TSHIFT = 4; // primitive type right shift count const int CV_SSHIFT = 0; // primitive subtype right shift count // function to extract primitive mode, type and size public static CV_prmode CV_MODE( TYPE_ENUM typ ) { return (CV_prmode)((((uint)typ) & CV_MMASK) >> CV_MSHIFT); } public static CV_type CV_TYPE( TYPE_ENUM typ ) { return (CV_type)((((uint)typ) & CV_TMASK) >> CV_TSHIFT); } public static uint CV_SUBT( TYPE_ENUM typ ) { return ((((uint)typ) & CV_SMASK) >> CV_SSHIFT); } // functions to check the type of a primitive public static bool CV_TYP_IS_DIRECT( TYPE_ENUM typ ) { return (CV_MODE( typ ) == CV_prmode.CV_TM_DIRECT); } public static bool CV_TYP_IS_PTR( TYPE_ENUM typ ) { return (CV_MODE( typ ) != CV_prmode.CV_TM_DIRECT); } public static bool CV_TYP_IS_SIGNED( TYPE_ENUM typ ) { return (((CV_TYPE( typ ) == CV_type.CV_SIGNED) && CV_TYP_IS_DIRECT( typ )) || (typ == TYPE_ENUM.T_INT1) || (typ == TYPE_ENUM.T_INT2) || (typ == TYPE_ENUM.T_INT4) || (typ == TYPE_ENUM.T_INT8) || (typ == TYPE_ENUM.T_INT16) || (typ == TYPE_ENUM.T_RCHAR)); } public static bool CV_TYP_IS_UNSIGNED( TYPE_ENUM typ ) { return (((CV_TYPE( typ ) == CV_type.CV_UNSIGNED) && CV_TYP_IS_DIRECT( typ )) || (typ == TYPE_ENUM.T_UINT1) || (typ == TYPE_ENUM.T_UINT2) || (typ == TYPE_ENUM.T_UINT4) || (typ == TYPE_ENUM.T_UINT8) || (typ == TYPE_ENUM.T_UINT16)); } public static bool CV_TYP_IS_REAL( TYPE_ENUM typ ) { return ((CV_TYPE( typ ) == CV_type.CV_REAL) && CV_TYP_IS_DIRECT( typ )); } const uint CV_FIRST_NONPRIM = 0x1000; public static bool CV_IS_PRIMITIVE( TYPE_ENUM typ ) { return ((uint)(typ) < CV_FIRST_NONPRIM); } public static bool CV_TYP_IS_COMPLEX( TYPE_ENUM typ ) { return ((CV_TYPE( typ ) == CV_type.CV_COMPLEX) && CV_TYP_IS_DIRECT( typ )); } public static bool CV_IS_INTERNAL_PTR( TYPE_ENUM typ ) { return (CV_IS_PRIMITIVE( typ ) && CV_TYPE( typ ) == CV_type.CV_CVRESERVED && CV_TYP_IS_PTR( typ )); } } // selected values for type_index - for a more complete definition, see // Microsoft Symbol and Type OMF document // Special Types public enum TYPE_ENUM { // Special Types T_NOTYPE = 0x0000, // uncharacterized type (no type) T_ABS = 0x0001, // absolute symbol T_SEGMENT = 0x0002, // segment type T_VOID = 0x0003, // void T_HRESULT = 0x0008, // OLE/COM HRESULT T_32PHRESULT = 0x0408, // OLE/COM HRESULT __ptr32// T_64PHRESULT = 0x0608, // OLE/COM HRESULT __ptr64// T_PVOID = 0x0103, // near pointer to void T_PFVOID = 0x0203, // far pointer to void T_PHVOID = 0x0303, // huge pointer to void T_32PVOID = 0x0403, // 32 bit pointer to void T_64PVOID = 0x0603, // 64 bit pointer to void T_CURRENCY = 0x0004, // BASIC 8 byte currency value T_NOTTRANS = 0x0007, // type not translated by cvpack T_BIT = 0x0060, // bit T_PASCHAR = 0x0061, // Pascal CHAR // Character types T_CHAR = 0x0010, // 8 bit signed T_32PCHAR = 0x0410, // 32 bit pointer to 8 bit signed T_64PCHAR = 0x0610, // 64 bit pointer to 8 bit signed T_UCHAR = 0x0020, // 8 bit unsigned T_32PUCHAR = 0x0420, // 32 bit pointer to 8 bit unsigned T_64PUCHAR = 0x0620, // 64 bit pointer to 8 bit unsigned // really a character types T_RCHAR = 0x0070, // really a char T_32PRCHAR = 0x0470, // 32 bit pointer to a real char T_64PRCHAR = 0x0670, // 64 bit pointer to a real char // really a wide character types T_WCHAR = 0x0071, // wide char T_32PWCHAR = 0x0471, // 32 bit pointer to a wide char T_64PWCHAR = 0x0671, // 64 bit pointer to a wide char // 8 bit int types T_INT1 = 0x0068, // 8 bit signed int T_32PINT1 = 0x0468, // 32 bit pointer to 8 bit signed int T_64PINT1 = 0x0668, // 64 bit pointer to 8 bit signed int T_UINT1 = 0x0069, // 8 bit unsigned int T_32PUINT1 = 0x0469, // 32 bit pointer to 8 bit unsigned int T_64PUINT1 = 0x0669, // 64 bit pointer to 8 bit unsigned int // 16 bit short types T_SHORT = 0x0011, // 16 bit signed T_32PSHORT = 0x0411, // 32 bit pointer to 16 bit signed T_64PSHORT = 0x0611, // 64 bit pointer to 16 bit signed T_USHORT = 0x0021, // 16 bit unsigned T_32PUSHORT = 0x0421, // 32 bit pointer to 16 bit unsigned T_64PUSHORT = 0x0621, // 64 bit pointer to 16 bit unsigned // 16 bit int types T_INT2 = 0x0072, // 16 bit signed int T_32PINT2 = 0x0472, // 32 bit pointer to 16 bit signed int T_64PINT2 = 0x0672, // 64 bit pointer to 16 bit signed int T_UINT2 = 0x0073, // 16 bit unsigned int T_32PUINT2 = 0x0473, // 32 bit pointer to 16 bit unsigned int T_64PUINT2 = 0x0673, // 64 bit pointer to 16 bit unsigned int // 32 bit long types T_LONG = 0x0012, // 32 bit signed T_ULONG = 0x0022, // 32 bit unsigned T_32PLONG = 0x0412, // 32 bit pointer to 32 bit signed T_32PULONG = 0x0422, // 32 bit pointer to 32 bit unsigned T_64PLONG = 0x0612, // 64 bit pointer to 32 bit signed T_64PULONG = 0x0622, // 64 bit pointer to 32 bit unsigned // 32 bit int types T_INT4 = 0x0074, // 32 bit signed int T_32PINT4 = 0x0474, // 32 bit pointer to 32 bit signed int T_64PINT4 = 0x0674, // 64 bit pointer to 32 bit signed int T_UINT4 = 0x0075, // 32 bit unsigned int T_32PUINT4 = 0x0475, // 32 bit pointer to 32 bit unsigned int T_64PUINT4 = 0x0675, // 64 bit pointer to 32 bit unsigned int // 64 bit quad types T_QUAD = 0x0013, // 64 bit signed T_32PQUAD = 0x0413, // 32 bit pointer to 64 bit signed T_64PQUAD = 0x0613, // 64 bit pointer to 64 bit signed T_UQUAD = 0x0023, // 64 bit unsigned T_32PUQUAD = 0x0423, // 32 bit pointer to 64 bit unsigned T_64PUQUAD = 0x0623, // 64 bit pointer to 64 bit unsigned // 64 bit int types T_INT8 = 0x0076, // 64 bit signed int T_32PINT8 = 0x0476, // 32 bit pointer to 64 bit signed int T_64PINT8 = 0x0676, // 64 bit pointer to 64 bit signed int T_UINT8 = 0x0077, // 64 bit unsigned int T_32PUINT8 = 0x0477, // 32 bit pointer to 64 bit unsigned int T_64PUINT8 = 0x0677, // 64 bit pointer to 64 bit unsigned int // 128 bit octet types T_OCT = 0x0014, // 128 bit signed T_32POCT = 0x0414, // 32 bit pointer to 128 bit signed T_64POCT = 0x0614, // 64 bit pointer to 128 bit signed T_UOCT = 0x0024, // 128 bit unsigned T_32PUOCT = 0x0424, // 32 bit pointer to 128 bit unsigned T_64PUOCT = 0x0624, // 64 bit pointer to 128 bit unsigned // 128 bit int types T_INT16 = 0x0078, // 128 bit signed int T_32PINT16 = 0x0478, // 32 bit pointer to 128 bit signed int T_64PINT16 = 0x0678, // 64 bit pointer to 128 bit signed int T_UINT16 = 0x0079, // 128 bit unsigned int T_32PUINT16 = 0x0479, // 32 bit pointer to 128 bit unsigned int T_64PUINT16 = 0x0679, // 64 bit pointer to 128 bit unsigned int // 32 bit real types T_REAL32 = 0x0040, // 32 bit real T_32PREAL32 = 0x0440, // 32 bit pointer to 32 bit real T_64PREAL32 = 0x0640, // 64 bit pointer to 32 bit real // 64 bit real types T_REAL64 = 0x0041, // 64 bit real T_32PREAL64 = 0x0441, // 32 bit pointer to 64 bit real T_64PREAL64 = 0x0641, // 64 bit pointer to 64 bit real // 80 bit real types T_REAL80 = 0x0042, // 80 bit real T_32PREAL80 = 0x0442, // 32 bit pointer to 80 bit real T_64PREAL80 = 0x0642, // 64 bit pointer to 80 bit real // 128 bit real types T_REAL128 = 0x0043, // 128 bit real T_32PREAL128 = 0x0443, // 32 bit pointer to 128 bit real T_64PREAL128 = 0x0643, // 64 bit pointer to 128 bit real // 32 bit complex types T_CPLX32 = 0x0050, // 32 bit complex T_32PCPLX32 = 0x0450, // 32 bit pointer to 32 bit complex T_64PCPLX32 = 0x0650, // 64 bit pointer to 32 bit complex // 64 bit complex types T_CPLX64 = 0x0051, // 64 bit complex T_32PCPLX64 = 0x0451, // 32 bit pointer to 64 bit complex T_64PCPLX64 = 0x0651, // 64 bit pointer to 64 bit complex // 80 bit complex types T_CPLX80 = 0x0052, // 80 bit complex T_32PCPLX80 = 0x0452, // 32 bit pointer to 80 bit complex T_64PCPLX80 = 0x0652, // 64 bit pointer to 80 bit complex // 128 bit complex types T_CPLX128 = 0x0053, // 128 bit complex T_32PCPLX128 = 0x0453, // 32 bit pointer to 128 bit complex T_64PCPLX128 = 0x0653, // 64 bit pointer to 128 bit complex // boolean types T_BOOL08 = 0x0030, // 8 bit boolean T_32PBOOL08 = 0x0430, // 32 bit pointer to 8 bit boolean T_64PBOOL08 = 0x0630, // 64 bit pointer to 8 bit boolean T_BOOL16 = 0x0031, // 16 bit boolean T_32PBOOL16 = 0x0431, // 32 bit pointer to 18 bit boolean T_64PBOOL16 = 0x0631, // 64 bit pointer to 18 bit boolean T_BOOL32 = 0x0032, // 32 bit boolean T_32PBOOL32 = 0x0432, // 32 bit pointer to 32 bit boolean T_64PBOOL32 = 0x0632, // 64 bit pointer to 32 bit boolean T_BOOL64 = 0x0033, // 64 bit boolean T_32PBOOL64 = 0x0433, // 32 bit pointer to 64 bit boolean T_64PBOOL64 = 0x0633, // 64 bit pointer to 64 bit boolean } // No leaf index can have a value of 0x0000. The leaf indices are // separated into ranges depending upon the use of the type record. // The second range is for the type records that are directly referenced // in symbols. The first range is for type records that are not // referenced by symbols but instead are referenced by other type // records. All type records must have a starting leaf index in these // first two ranges. The third range of leaf indices are used to build // up complex lists such as the field list of a class type record. No // type record can begin with one of the leaf indices. The fourth ranges // of type indices are used to represent numeric data in a symbol or // type record. These leaf indices are greater than 0x8000. At the // point that type or symbol processor is expecting a numeric field, the // next two bytes in the type record are examined. If the value is less // than 0x8000, then the two bytes contain the numeric value. If the // value is greater than 0x8000, then the data follows the leaf index in // a format specified by the leaf index. The final range of leaf indices // are used to force alignment of subfields within a complex type record.. // public enum LEAF { // leaf indices starting records but referenced from symbol records LF_VTSHAPE = 0x000A, LF_COBOL1 = 0x000C, LF_LABEL = 0x000E, LF_NULL = 0x000F, LF_NOTTRAN = 0x0010, LF_ENDPRECOMP = 0x0014, // not referenced from symbol LF_TYPESERVER_ST = 0x0016, // not referenced from symbol // leaf indices starting records but referenced only from type records LF_LIST = 0x0203, LF_REFSYM = 0x020C, LF_ENUMERATE_ST = 0x0403, // 32-bit type index versions of leaves, all have the 0x1000 bit set // LF_TI16_MAX = 0x1000, LF_MODIFIER = 0x1001, LF_POINTER = 0x1002, LF_ARRAY_ST = 0x1003, LF_CLASS_ST = 0x1004, LF_STRUCTURE_ST = 0x1005, LF_UNION_ST = 0x1006, LF_ENUM_ST = 0x1007, LF_PROCEDURE = 0x1008, LF_MFUNCTION = 0x1009, LF_COBOL0 = 0x100A, LF_BARRAY = 0x100B, LF_DIMARRAY_ST = 0x100C, LF_VFTPATH = 0x100D, LF_PRECOMP_ST = 0x100E, // not referenced from symbol LF_OEM = 0x100F, // oem definable type string LF_ALIAS_ST = 0x1010, // alias (typedef) type LF_OEM2 = 0x1011, // oem definable type string // leaf indices starting records but referenced only from type records LF_SKIP = 0x1200, LF_ARGLIST = 0x1201, LF_DEFARG_ST = 0x1202, LF_FIELDLIST = 0x1203, LF_DERIVED = 0x1204, LF_BITFIELD = 0x1205, LF_METHODLIST = 0x1206, LF_DIMCONU = 0x1207, LF_DIMCONLU = 0x1208, LF_DIMVARU = 0x1209, LF_DIMVARLU = 0x120A, LF_BCLASS = 0x1400, LF_VBCLASS = 0x1401, LF_IVBCLASS = 0x1402, LF_FRIENDFCN_ST = 0x1403, LF_INDEX = 0x1404, LF_MEMBER_ST = 0x1405, LF_STMEMBER_ST = 0x1406, LF_METHOD_ST = 0x1407, LF_NESTTYPE_ST = 0x1408, LF_VFUNCTAB = 0x1409, LF_FRIENDCLS = 0x140A, LF_ONEMETHOD_ST = 0x140B, LF_VFUNCOFF = 0x140C, LF_NESTTYPEEX_ST = 0x140D, LF_MEMBERMODIFY_ST = 0x140E, LF_MANAGED_ST = 0x140F, // Types w/ SZ names LF_ST_MAX = 0x1500, LF_TYPESERVER = 0x1501, // not referenced from symbol LF_ENUMERATE = 0x1502, LF_ARRAY = 0x1503, LF_CLASS = 0x1504, LF_STRUCTURE = 0x1505, LF_UNION = 0x1506, LF_ENUM = 0x1507, LF_DIMARRAY = 0x1508, LF_PRECOMP = 0x1509, // not referenced from symbol LF_ALIAS = 0x150A, // alias (typedef) type LF_DEFARG = 0x150B, LF_FRIENDFCN = 0x150C, LF_MEMBER = 0x150D, LF_STMEMBER = 0x150E, LF_METHOD = 0x150F, LF_NESTTYPE = 0x1510, LF_ONEMETHOD = 0x1511, LF_NESTTYPEEX = 0x1512, LF_MEMBERMODIFY = 0x1513, LF_MANAGED = 0x1514, LF_TYPESERVER2 = 0x1515, LF_NUMERIC = 0x8000, LF_CHAR = 0x8000, LF_SHORT = 0x8001, LF_USHORT = 0x8002, LF_LONG = 0x8003, LF_ULONG = 0x8004, LF_REAL32 = 0x8005, LF_REAL64 = 0x8006, LF_REAL80 = 0x8007, LF_REAL128 = 0x8008, LF_QUADWORD = 0x8009, LF_UQUADWORD = 0x800A, LF_COMPLEX32 = 0x800C, LF_COMPLEX64 = 0x800D, LF_COMPLEX80 = 0x800E, LF_COMPLEX128 = 0x800F, LF_VARSTRING = 0x8010, LF_OCTWORD = 0x8017, LF_UOCTWORD = 0x8018, LF_DECIMAL = 0x8019, LF_DATE = 0x801A, LF_UTF8STRING = 0x801B, LF_PAD0 = 0x00F0, LF_PAD1 = 0x00F1, LF_PAD2 = 0x00F2, LF_PAD3 = 0x00F3, LF_PAD4 = 0x00F4, LF_PAD5 = 0x00F5, LF_PAD6 = 0x00F6, LF_PAD7 = 0x00F7, LF_PAD8 = 0x00F8, LF_PAD9 = 0x00F9, LF_PAD10 = 0x00FA, LF_PAD11 = 0x00FB, LF_PAD12 = 0x00FC, LF_PAD13 = 0x00FD, LF_PAD14 = 0x00FE, LF_PAD15 = 0x00FF, } // end of leaf indices // Type enum for pointer records // Pointers can be one of the following types public enum CV_ptrtype { CV_PTR_BASE_SEG = 0x03, // based on segment CV_PTR_BASE_VAL = 0x04, // based on value of base CV_PTR_BASE_SEGVAL = 0x05, // based on segment value of base CV_PTR_BASE_ADDR = 0x06, // based on address of base CV_PTR_BASE_SEGADDR = 0x07, // based on segment address of base CV_PTR_BASE_TYPE = 0x08, // based on type CV_PTR_BASE_SELF = 0x09, // based on self CV_PTR_NEAR32 = 0x0A, // 32 bit pointer CV_PTR_64 = 0x0C, // 64 bit pointer CV_PTR_UNUSEDPTR = 0x0D, // first unused pointer type } // Mode enum for pointers // Pointers can have one of the following modes public enum CV_ptrmode { CV_PTR_MODE_PTR = 0x00, // "normal" pointer CV_PTR_MODE_REF = 0x01, // reference CV_PTR_MODE_PMEM = 0x02, // pointer to data member CV_PTR_MODE_PMFUNC = 0x03, // pointer to member function CV_PTR_MODE_RESERVED = 0x04, // first unused pointer mode } // enumeration for pointer-to-member types public enum CV_pmtype { CV_PMTYPE_Undef = 0x00, // not specified (pre VC8) CV_PMTYPE_D_Single = 0x01, // member data, single inheritance CV_PMTYPE_D_Multiple = 0x02, // member data, multiple inheritance CV_PMTYPE_D_Virtual = 0x03, // member data, virtual inheritance CV_PMTYPE_D_General = 0x04, // member data, most general CV_PMTYPE_F_Single = 0x05, // member function, single inheritance CV_PMTYPE_F_Multiple = 0x06, // member function, multiple inheritance CV_PMTYPE_F_Virtual = 0x07, // member function, virtual inheritance CV_PMTYPE_F_General = 0x08, // member function, most general } // enumeration for method properties public enum CV_methodprop { CV_MTvanilla = 0x00, CV_MTvirtual = 0x01, CV_MTstatic = 0x02, CV_MTfriend = 0x03, CV_MTintro = 0x04, CV_MTpurevirt = 0x05, CV_MTpureintro = 0x06, } // enumeration for virtual shape table entries public enum CV_VTS_desc { CV_VTS_near = 0x00, CV_VTS_far = 0x01, CV_VTS_thin = 0x02, CV_VTS_outer = 0x03, CV_VTS_meta = 0x04, CV_VTS_near32 = 0x05, CV_VTS_far32 = 0x06, CV_VTS_unused = 0x07, } // enumeration for LF_LABEL address modes public enum CV_LABEL_TYPE { CV_LABEL_NEAR = 0, // near return CV_LABEL_FAR = 4, // far return } // enumeration for LF_MODIFIER values [Flags] public enum CV_modifier : ushort { MOD_const = 0x0001, MOD_volatile = 0x0002, MOD_unaligned = 0x0004, } // bit field structure describing class/struct/union/enum properties [Flags] public enum CV_prop : ushort { packed = 0x0001, // true if structure is packed ctor = 0x0002, // true if constructors or destructors present ovlops = 0x0004, // true if overloaded operators present isnested = 0x0008, // true if this is a nested class cnested = 0x0010, // true if this class contains nested types opassign = 0x0020, // true if overloaded assignment (=) opcast = 0x0040, // true if casting methods fwdref = 0x0080, // true if forward reference (incomplete defn) scoped = 0x0100, // scoped definition } // class field attribute [Flags] public enum CV_fldattr { access = 0x0003, // access protection CV_access_t mprop = 0x001c, // method properties CV_methodprop_t pseudo = 0x0020, // compiler generated fcn and does not exist noinherit = 0x0040, // true if class cannot be inherited noconstruct = 0x0080, // true if class cannot be constructed compgenx = 0x0100, // compiler generated fcn and does exist } // Structures to access to the type records public struct TYPTYPE { public ushort len; public ushort leaf; // byte data[]; // char *NextType (char * pType) { // return (pType + ((TYPTYPE *)pType)->len + sizeof(ushort)); // } } // general types record // memory representation of pointer to member. These representations are // indexed by the enumeration above in the LF_POINTER record // representation of a 32 bit pointer to data for a class with // or without virtual functions and no virtual bases public struct CV_PDMR32_NVVFCN { public int mdisp; // displacement to data (NULL = 0x80000000) } // representation of a 32 bit pointer to data for a class // with virtual bases public struct CV_PDMR32_VBASE { public int mdisp; // displacement to data public int pdisp; // this pointer displacement public int vdisp; // vbase table displacement // NULL = (,,0xffffffff) } // representation of a 32 bit pointer to member function for a // class with no virtual bases and a single address point public struct CV_PMFR32_NVSA { public uint off; // near address of function (NULL = 0L) } // representation of a 32 bit pointer to member function for a // class with no virtual bases and multiple address points public struct CV_PMFR32_NVMA { public uint off; // near address of function (NULL = 0L,x) public int disp; } // representation of a 32 bit pointer to member function for a // class with virtual bases public struct CV_PMFR32_VBASE { public uint off; // near address of function (NULL = 0L,x,x,x) public int mdisp; // displacement to data public int pdisp; // this pointer displacement public int vdisp; // vbase table displacement } ////////////////////////////////////////////////////////////////////////////// // // The following type records are basically variant records of the // above structure. The "ushort leaf" of the above structure and // the "ushort leaf" of the following type definitions are the same // symbol. // // Notes on alignment // Alignment of the fields in most of the type records is done on the // basis of the TYPTYPE record base. That is why in most of the lf* // records that the type is located on what appears to // be a offset mod 4 == 2 boundary. The exception to this rule are those // records that are in a list (lfFieldList, lfMethodList), which are // aligned to their own bases since they don't have the length field // // Type record for LF_MODIFIER public struct LeafModifier { // public ushort leaf; // LF_MODIFIER [TYPTYPE] public uint type; // (type index) modified type public CV_modifier attr; // modifier attribute modifier_t } // type record for LF_POINTER [Flags] public enum LeafPointerAttr : uint { ptrtype = 0x0000001F, // ordinal specifying pointer type (CV_ptrtype) ptrmode = 0x000000E0, // ordinal specifying pointer mode (CV_ptrmode) isflat32 = 0x00000100, // true if 0:32 pointer isvolatile = 0x00000200, // TRUE if volatile pointer isconst = 0x00000400, // TRUE if const pointer isunaligned = 0x00000800, // TRUE if unaligned pointer isrestrict = 0x00001000, // TRUE if restricted pointer (allow agressive opts) } public struct LeafPointer { public struct LeafPointerBody { // public ushort leaf; // LF_POINTER [TYPTYPE] public uint utype; // (type index) type index of the underlying type public LeafPointerAttr attr; } #if false union { public struct { uint pmclass; // (type index) index of containing class for pointer to member ushort pmenum; // enumeration specifying pm format (CV_pmtype) } ushort bseg; // base segment if PTR_BASE_SEG byte[] Sym; // copy of base symbol record (including length) public struct { uint index; // (type index) type index if CV_PTR_BASE_TYPE string name; // name of base type } btype; } pbase; #endif } // type record for LF_ARRAY public struct LeafArray { // public ushort leaf; // LF_ARRAY [TYPTYPE] public uint elemtype; // (type index) type index of element type public uint idxtype; // (type index) type index of indexing type public byte[] data; // variable length data specifying size in bytes public string name; } // type record for LF_CLASS, LF_STRUCTURE public struct LeafClass { // public ushort leaf; // LF_CLASS, LF_STRUCT [TYPTYPE] public ushort count; // count of number of elements in class public ushort property; // (CV_prop_t) property attribute field (prop_t) public uint field; // (type index) type index of LF_FIELD descriptor list public uint derived; // (type index) type index of derived from list if not zero public uint vshape; // (type index) type index of vshape table for this class public byte[] data; // data describing length of structure in bytes public string name; } // type record for LF_UNION public struct LeafUnion { // public ushort leaf; // LF_UNION [TYPTYPE] public ushort count; // count of number of elements in class public ushort property; // (CV_prop_t) property attribute field public uint field; // (type index) type index of LF_FIELD descriptor list public byte[] data; // variable length data describing length of public string name; } // type record for LF_ALIAS public struct LeafAlias { // public ushort leaf; // LF_ALIAS [TYPTYPE] public uint utype; // (type index) underlying type public string name; // alias name } // type record for LF_MANAGED public struct LeafManaged { // public ushort leaf; // LF_MANAGED [TYPTYPE] public string name; // utf8, zero terminated managed type name } // type record for LF_ENUM public struct LeafEnum { // public ushort leaf; // LF_ENUM [TYPTYPE] public ushort count; // count of number of elements in class public ushort property; // (CV_propt_t) property attribute field public uint utype; // (type index) underlying type of the enum public uint field; // (type index) type index of LF_FIELD descriptor list public string name; // length prefixed name of enum } // Type record for LF_PROCEDURE public struct LeafProc { // public ushort leaf; // LF_PROCEDURE [TYPTYPE] public uint rvtype; // (type index) type index of return value public byte calltype; // calling convention (CV_call_t) public byte reserved; // reserved for future use public ushort parmcount; // number of parameters public uint arglist; // (type index) type index of argument list } // Type record for member function public struct LeafMFunc { // public ushort leaf; // LF_MFUNCTION [TYPTYPE] public uint rvtype; // (type index) type index of return value public uint classtype; // (type index) type index of containing class public uint thistype; // (type index) type index of this pointer (model specific) public byte calltype; // calling convention (call_t) public byte reserved; // reserved for future use public ushort parmcount; // number of parameters public uint arglist; // (type index) type index of argument list public int thisadjust; // this adjuster (long because pad required anyway) } // type record for virtual function table shape public struct LeafVTShape { // public ushort leaf; // LF_VTSHAPE [TYPTYPE] public ushort count; // number of entries in vfunctable public byte[] desc; // 4 bit (CV_VTS_desc) descriptors } // type record for cobol0 public struct LeafCobol0 { // public ushort leaf; // LF_COBOL0 [TYPTYPE] public uint type; // (type index) parent type record index public byte[] data; } // type record for cobol1 public struct LeafCobol1 { // public ushort leaf; // LF_COBOL1 [TYPTYPE] public byte[] data; } // type record for basic array public struct LeafBArray { // public ushort leaf; // LF_BARRAY [TYPTYPE] public uint utype; // (type index) type index of underlying type } // type record for assembler labels public struct LeafLabel { // public ushort leaf; // LF_LABEL [TYPTYPE] public ushort mode; // addressing mode of label } // type record for dimensioned arrays public struct LeafDimArray { // public ushort leaf; // LF_DIMARRAY [TYPTYPE] public uint utype; // (type index) underlying type of the array public uint diminfo; // (type index) dimension information public string name; // length prefixed name } // type record describing path to virtual function table public struct LeafVFTPath { // public ushort leaf; // LF_VFTPATH [TYPTYPE] public uint count; // count of number of bases in path public uint[] bases; // (type index) bases from root to leaf } // type record describing inclusion of precompiled types public struct LeafPreComp { // public ushort leaf; // LF_PRECOMP [TYPTYPE] public uint start; // starting type index included public uint count; // number of types in inclusion public uint signature; // signature public string name; // length prefixed name of included type file } // type record describing end of precompiled types that can be // included by another file public struct LeafEndPreComp { // public ushort leaf; // LF_ENDPRECOMP [TYPTYPE] public uint signature; // signature } // type record for OEM definable type strings public struct LeafOEM { // public ushort leaf; // LF_OEM [TYPTYPE] public ushort cvOEM; // MS assigned OEM identified public ushort recOEM; // OEM assigned type identifier public uint count; // count of type indices to follow public uint[] index; // (type index) array of type indices followed // by OEM defined data } public enum OEM_ID { OEM_MS_FORTRAN90 = 0xF090, OEM_ODI = 0x0010, OEM_THOMSON_SOFTWARE = 0x5453, OEM_ODI_REC_BASELIST = 0x0000, } public struct LeafOEM2 { // public ushort leaf; // LF_OEM2 [TYPTYPE] public Guid idOem; // an oem ID (Guid) public uint count; // count of type indices to follow public uint[] index; // (type index) array of type indices followed // by OEM defined data } // type record describing using of a type server public struct LeafTypeServer { // public ushort leaf; // LF_TYPESERVER [TYPTYPE] public uint signature; // signature public uint age; // age of database used by this module public string name; // length prefixed name of PDB } // type record describing using of a type server with v7 (GUID) signatures public struct LeafTypeServer2 { // public ushort leaf; // LF_TYPESERVER2 [TYPTYPE] public Guid sig70; // guid signature public uint age; // age of database used by this module public string name; // length prefixed name of PDB } // description of type records that can be referenced from // type records referenced by symbols // type record for skip record public struct LeafSkip { // public ushort leaf; // LF_SKIP [TYPTYPE] public uint type; // (type index) next valid index public byte[] data; // pad data } // argument list leaf public struct LeafArgList { // public ushort leaf; // LF_ARGLIST [TYPTYPE] public uint count; // number of arguments public uint[] arg; // (type index) number of arguments } // derived class list leaf public struct LeafDerived { // public ushort leaf; // LF_DERIVED [TYPTYPE] public uint count; // number of arguments public uint[] drvdcls; // (type index) type indices of derived classes } // leaf for default arguments public struct LeafDefArg { // public ushort leaf; // LF_DEFARG [TYPTYPE] public uint type; // (type index) type of resulting expression public byte[] expr; // length prefixed expression string } // list leaf // This list should no longer be used because the utilities cannot // verify the contents of the list without knowing what type of list // it is. New specific leaf indices should be used instead. public struct LeafList { // public ushort leaf; // LF_LIST [TYPTYPE] public byte[] data; // data format specified by indexing type } // field list leaf // This is the header leaf for a complex list of class and structure // subfields. public struct LeafFieldList { // public ushort leaf; // LF_FIELDLIST [TYPTYPE] public char[] data; // field list sub lists } // type record for non-static methods and friends in overloaded method list public struct mlMethod { public ushort attr; // (CV_fldattr_t) method attribute public ushort pad0; // internal padding, must be 0 public uint index; // (type index) index to type record for procedure public uint[] vbaseoff; // offset in vfunctable if intro virtual } public struct LeafMethodList { // public ushort leaf; // LF_METHODLIST [TYPTYPE] public byte[] mList; // really a mlMethod type } // type record for LF_BITFIELD public struct LeafBitfield { // public ushort leaf; // LF_BITFIELD [TYPTYPE] public uint type; // (type index) type of bitfield public byte length; public byte position; } // type record for dimensioned array with constant bounds public struct LeafDimCon { // public ushort leaf; // LF_DIMCONU or LF_DIMCONLU [TYPTYPE] public uint typ; // (type index) type of index public ushort rank; // number of dimensions public byte[] dim; // array of dimension information with // either upper bounds or lower/upper bound } // type record for dimensioned array with variable bounds public struct LeafDimVar { // public ushort leaf; // LF_DIMVARU or LF_DIMVARLU [TYPTYPE] public uint rank; // number of dimensions public uint typ; // (type index) type of index public uint[] dim; // (type index) array of type indices for either // variable upper bound or variable // lower/upper bound. The count of type // indices is rank or rank*2 depending on // whether it is LFDIMVARU or LF_DIMVARLU. // The referenced types must be // LF_REFSYM or T_VOID } // type record for referenced symbol public struct LeafRefSym { // public ushort leaf; // LF_REFSYM [TYPTYPE] public byte[] Sym; // copy of referenced symbol record // (including length) } // the following are numeric leaves. They are used to indicate the // size of the following variable length data. When the numeric // data is a single byte less than 0x8000, then the data is output // directly. If the data is more the 0x8000 or is a negative value, // then the data is preceeded by the proper index. // // signed character leaf public struct LeafChar { // public ushort leaf; // LF_CHAR [TYPTYPE] public sbyte val; // signed 8-bit value } // signed short leaf public struct LeafShort { // public ushort leaf; // LF_SHORT [TYPTYPE] public short val; // signed 16-bit value } // ushort leaf public struct LeafUShort { // public ushort leaf; // LF_ushort [TYPTYPE] public ushort val; // unsigned 16-bit value } // signed (32-bit) long leaf public struct LeafLong { // public ushort leaf; // LF_LONG [TYPTYPE] public int val; // signed 32-bit value } // uint leaf public struct LeafULong { // public ushort leaf; // LF_ULONG [TYPTYPE] public uint val; // unsigned 32-bit value } // signed quad leaf public struct LeafQuad { // public ushort leaf; // LF_QUAD [TYPTYPE] public long val; // signed 64-bit value } // unsigned quad leaf public struct LeafUQuad { // public ushort leaf; // LF_UQUAD [TYPTYPE] public ulong val; // unsigned 64-bit value } // signed int128 leaf public struct LeafOct { // public ushort leaf; // LF_OCT [TYPTYPE] public ulong val0; public ulong val1; // signed 128-bit value } // unsigned int128 leaf public struct LeafUOct { // public ushort leaf; // LF_UOCT [TYPTYPE] public ulong val0; public ulong val1; // unsigned 128-bit value } // real 32-bit leaf public struct LeafReal32 { // public ushort leaf; // LF_REAL32 [TYPTYPE] public float val; // 32-bit real value } // real 64-bit leaf public struct LeafReal64 { // public ushort leaf; // LF_REAL64 [TYPTYPE] public double val; // 64-bit real value } // real 80-bit leaf public struct LeafReal80 { // public ushort leaf; // LF_REAL80 [TYPTYPE] public FLOAT10 val; // real 80-bit value } // real 128-bit leaf public struct LeafReal128 { // public ushort leaf; // LF_REAL128 [TYPTYPE] public ulong val0; public ulong val1; // real 128-bit value } // complex 32-bit leaf public struct LeafCmplx32 { // public ushort leaf; // LF_COMPLEX32 [TYPTYPE] public float val_real; // real component public float val_imag; // imaginary component } // complex 64-bit leaf public struct LeafCmplx64 { // public ushort leaf; // LF_COMPLEX64 [TYPTYPE] public double val_real; // real component public double val_imag; // imaginary component } // complex 80-bit leaf public struct LeafCmplx80 { // public ushort leaf; // LF_COMPLEX80 [TYPTYPE] public FLOAT10 val_real; // real component public FLOAT10 val_imag; // imaginary component } // complex 128-bit leaf public struct LeafCmplx128 { // public ushort leaf; // LF_COMPLEX128 [TYPTYPE] public ulong val0_real; public ulong val1_real; // real component public ulong val0_imag; public ulong val1_imag; // imaginary component } // variable length numeric field public struct LeafVarString { // public ushort leaf; // LF_VARSTRING [TYPTYPE] public ushort len; // length of value in bytes public byte[] value; // value } // index leaf - contains type index of another leaf // a major use of this leaf is to allow the compilers to emit a // long complex list (LF_FIELD) in smaller pieces. public struct LeafIndex { // public ushort leaf; // LF_INDEX [TYPTYPE] public ushort pad0; // internal padding, must be 0 public uint index; // (type index) type index of referenced leaf } // subfield record for base class field public struct LeafBClass { // public ushort leaf; // LF_BCLASS [TYPTYPE] public ushort attr; // (CV_fldattr_t) attribute public uint index; // (type index) type index of base class public byte[] offset; // variable length offset of base within class } // subfield record for direct and indirect virtual base class field public struct LeafVBClass { // public ushort leaf; // LF_VBCLASS | LV_IVBCLASS [TYPTYPE] public ushort attr; // (CV_fldattr_t) attribute public uint index; // (type index) type index of direct virtual base class public uint vbptr; // (type index) type index of virtual base pointer public byte[] vbpoff; // virtual base pointer offset from address point // followed by virtual base offset from vbtable } // subfield record for friend class public struct LeafFriendCls { // public ushort leaf; // LF_FRIENDCLS [TYPTYPE] public ushort pad0; // internal padding, must be 0 public uint index; // (type index) index to type record of friend class } // subfield record for friend function public struct LeafFriendFcn { // public ushort leaf; // LF_FRIENDFCN [TYPTYPE] public ushort pad0; // internal padding, must be 0 public uint index; // (type index) index to type record of friend function public string name; // name of friend function } // subfield record for non-static data members public struct LeafMember { // public ushort leaf; // LF_MEMBER [TYPTYPE] public ushort attr; // (CV_fldattr_t)attribute mask public uint index; // (type index) index of type record for field public byte[] offset; // variable length offset of field public string name; // length prefixed name of field } // type record for static data members public struct LeafSTMember { // public ushort leaf; // LF_STMEMBER [TYPTYPE] public ushort attr; // (CV_fldattr_t) attribute mask public uint index; // (type index) index of type record for field public string name; // length prefixed name of field } // subfield record for virtual function table pointer public struct LeafVFuncTab { // public ushort leaf; // LF_VFUNCTAB [TYPTYPE] public ushort pad0; // internal padding, must be 0 public uint type; // (type index) type index of pointer } // subfield record for virtual function table pointer with offset public struct LeafVFuncOff { // public ushort leaf; // LF_VFUNCOFF [TYPTYPE] public ushort pad0; // internal padding, must be 0. public uint type; // (type index) type index of pointer public int offset; // offset of virtual function table pointer } // subfield record for overloaded method list public struct LeafMethod { // public ushort leaf; // LF_METHOD [TYPTYPE] public ushort count; // number of occurrences of function public uint mList; // (type index) index to LF_METHODLIST record public string name; // length prefixed name of method } // subfield record for nonoverloaded method public struct LeafOneMethod { // public ushort leaf; // LF_ONEMETHOD [TYPTYPE] public ushort attr; // (CV_fldattr_t) method attribute public uint index; // (type index) index to type record for procedure public uint[] vbaseoff; // offset in vfunctable if intro virtual public string name; } // subfield record for enumerate public struct LeafEnumerate { // public ushort leaf; // LF_ENUMERATE [TYPTYPE] public ushort attr; // (CV_fldattr_t) access public byte[] value; // variable length value field public string name; } // type record for nested (scoped) type definition public struct LeafNestType { // public ushort leaf; // LF_NESTTYPE [TYPTYPE] public ushort pad0; // internal padding, must be 0 public uint index; // (type index) index of nested type definition public string name; // length prefixed type name } // type record for nested (scoped) type definition, with attributes // new records for vC v5.0, no need to have 16-bit ti versions. public struct LeafNestTypeEx { // public ushort leaf; // LF_NESTTYPEEX [TYPTYPE] public ushort attr; // (CV_fldattr_t) member access public uint index; // (type index) index of nested type definition public string name; // length prefixed type name } // type record for modifications to members public struct LeafMemberModify { // public ushort leaf; // LF_MEMBERMODIFY [TYPTYPE] public ushort attr; // (CV_fldattr_t) the new attributes public uint index; // (type index) index of base class type definition public string name; // length prefixed member name } // type record for pad leaf public struct LeafPad { public byte leaf; } // Symbol definitions public enum SYM { S_END = 0x0006, // Block, procedure, "with" or thunk end S_OEM = 0x0404, // OEM defined symbol S_REGISTER_ST = 0x1001, // Register variable S_CONSTANT_ST = 0x1002, // constant symbol S_UDT_ST = 0x1003, // User defined type S_COBOLUDT_ST = 0x1004, // special UDT for cobol that does not symbol pack S_MANYREG_ST = 0x1005, // multiple register variable S_BPREL32_ST = 0x1006, // BP-relative S_LDATA32_ST = 0x1007, // Module-local symbol S_GDATA32_ST = 0x1008, // Global data symbol S_PUB32_ST = 0x1009, // a public symbol (CV internal reserved) S_LPROC32_ST = 0x100a, // Local procedure start S_GPROC32_ST = 0x100b, // Global procedure start S_VFTABLE32 = 0x100c, // address of virtual function table S_REGREL32_ST = 0x100d, // register relative address S_LTHREAD32_ST = 0x100e, // local thread storage S_GTHREAD32_ST = 0x100f, // global thread storage S_LPROCMIPS_ST = 0x1010, // Local procedure start S_GPROCMIPS_ST = 0x1011, // Global procedure start // new symbol records for edit and continue information S_FRAMEPROC = 0x1012, // extra frame and proc information S_COMPILE2_ST = 0x1013, // extended compile flags and info // new symbols necessary for 16-bit enumerates of IA64 registers // and IA64 specific symbols S_MANYREG2_ST = 0x1014, // multiple register variable S_LPROCIA64_ST = 0x1015, // Local procedure start (IA64) S_GPROCIA64_ST = 0x1016, // Global procedure start (IA64) // Local symbols for IL S_LOCALSLOT_ST = 0x1017, // local IL sym with field for local slot index S_PARAMSLOT_ST = 0x1018, // local IL sym with field for parameter slot index S_ANNOTATION = 0x1019, // Annotation string literals // symbols to support managed code debugging S_GMANPROC_ST = 0x101a, // Global proc S_LMANPROC_ST = 0x101b, // Local proc S_RESERVED1 = 0x101c, // reserved S_RESERVED2 = 0x101d, // reserved S_RESERVED3 = 0x101e, // reserved S_RESERVED4 = 0x101f, // reserved S_LMANDATA_ST = 0x1020, S_GMANDATA_ST = 0x1021, S_MANFRAMEREL_ST = 0x1022, S_MANREGISTER_ST = 0x1023, S_MANSLOT_ST = 0x1024, S_MANMANYREG_ST = 0x1025, S_MANREGREL_ST = 0x1026, S_MANMANYREG2_ST = 0x1027, S_MANTYPREF = 0x1028, // Index for type referenced by name from metadata S_UNAMESPACE_ST = 0x1029, // Using namespace // Symbols w/ SZ name fields. All name fields contain utf8 encoded strings. S_ST_MAX = 0x1100, // starting point for SZ name symbols S_OBJNAME = 0x1101, // path to object file name S_THUNK32 = 0x1102, // Thunk Start S_BLOCK32 = 0x1103, // block start S_WITH32 = 0x1104, // with start S_LABEL32 = 0x1105, // code label S_REGISTER = 0x1106, // Register variable S_CONSTANT = 0x1107, // constant symbol S_UDT = 0x1108, // User defined type S_COBOLUDT = 0x1109, // special UDT for cobol that does not symbol pack S_MANYREG = 0x110a, // multiple register variable S_BPREL32 = 0x110b, // BP-relative S_LDATA32 = 0x110c, // Module-local symbol S_GDATA32 = 0x110d, // Global data symbol S_PUB32 = 0x110e, // a public symbol (CV internal reserved) S_LPROC32 = 0x110f, // Local procedure start S_GPROC32 = 0x1110, // Global procedure start S_REGREL32 = 0x1111, // register relative address S_LTHREAD32 = 0x1112, // local thread storage S_GTHREAD32 = 0x1113, // global thread storage S_LPROCMIPS = 0x1114, // Local procedure start S_GPROCMIPS = 0x1115, // Global procedure start S_COMPILE2 = 0x1116, // extended compile flags and info S_MANYREG2 = 0x1117, // multiple register variable S_LPROCIA64 = 0x1118, // Local procedure start (IA64) S_GPROCIA64 = 0x1119, // Global procedure start (IA64) S_LOCALSLOT = 0x111a, // local IL sym with field for local slot index S_SLOT = S_LOCALSLOT, // alias for LOCALSLOT S_PARAMSLOT = 0x111b, // local IL sym with field for parameter slot index // symbols to support managed code debugging S_LMANDATA = 0x111c, S_GMANDATA = 0x111d, S_MANFRAMEREL = 0x111e, S_MANREGISTER = 0x111f, S_MANSLOT = 0x1120, S_MANMANYREG = 0x1121, S_MANREGREL = 0x1122, S_MANMANYREG2 = 0x1123, S_UNAMESPACE = 0x1124, // Using namespace // ref symbols with name fields S_PROCREF = 0x1125, // Reference to a procedure S_DATAREF = 0x1126, // Reference to data S_LPROCREF = 0x1127, // Local Reference to a procedure S_ANNOTATIONREF = 0x1128, // Reference to an S_ANNOTATION symbol S_TOKENREF = 0x1129, // Reference to one of the many MANPROCSYM's // continuation of managed symbols S_GMANPROC = 0x112a, // Global proc S_LMANPROC = 0x112b, // Local proc // short, light-weight thunks S_TRAMPOLINE = 0x112c, // trampoline thunks S_MANCONSTANT = 0x112d, // constants with metadata type info // native attributed local/parms S_ATTR_FRAMEREL = 0x112e, // relative to virtual frame ptr S_ATTR_REGISTER = 0x112f, // stored in a register S_ATTR_REGREL = 0x1130, // relative to register (alternate frame ptr) S_ATTR_MANYREG = 0x1131, // stored in >1 register // Separated code (from the compiler) support S_SEPCODE = 0x1132, S_LOCAL = 0x1133, // defines a local symbol in optimized code S_DEFRANGE = 0x1134, // defines a single range of addresses in which symbol can be evaluated S_DEFRANGE2 = 0x1135, // defines ranges of addresses in which symbol can be evaluated S_SECTION = 0x1136, // A COFF section in a PE executable S_COFFGROUP = 0x1137, // A COFF group S_EXPORT = 0x1138, // A export S_CALLSITEINFO = 0x1139, // Indirect call site information S_FRAMECOOKIE = 0x113a, // Security cookie information S_DISCARDED = 0x113b, // Discarded by LINK /OPT:REF (experimental, see richards) S_RECTYPE_MAX, // one greater than last S_RECTYPE_LAST = S_RECTYPE_MAX - 1, } // enum describing compile flag ambient data model public enum CV_CFL_DATA { CV_CFL_DNEAR = 0x00, CV_CFL_DFAR = 0x01, CV_CFL_DHUGE = 0x02, } // enum describing compile flag ambiant code model public enum CV_CFL_CODE { CV_CFL_CNEAR = 0x00, CV_CFL_CFAR = 0x01, CV_CFL_CHUGE = 0x02, } // enum describing compile flag target floating point package public enum CV_CFL_FPKG { CV_CFL_NDP = 0x00, CV_CFL_EMU = 0x01, CV_CFL_ALT = 0x02, } // enum describing function return method [Flags] public enum CV_PROCFLAGS : byte { CV_PFLAG_NOFPO = 0x01, // frame pointer present CV_PFLAG_INT = 0x02, // interrupt return CV_PFLAG_FAR = 0x04, // far return CV_PFLAG_NEVER = 0x08, // function does not return CV_PFLAG_NOTREACHED = 0x10, // label isn't fallen into CV_PFLAG_CUST_CALL = 0x20, // custom calling convention CV_PFLAG_NOINLINE = 0x40, // function marked as noinline CV_PFLAG_OPTDBGINFO = 0x80, // function has debug information for optimized code } // Extended proc flags // public struct CV_EXPROCFLAGS { public byte flags; // (CV_PROCFLAGS) public byte reserved; // must be zero } // local variable flags [Flags] public enum CV_LVARFLAGS : ushort { fIsParam = 0x0001, // variable is a parameter fAddrTaken = 0x0002, // address is taken fCompGenx = 0x0004, // variable is compiler generated fIsAggregate = 0x0008, // the symbol is splitted in temporaries, // which are treated by compiler as // independent entities fIsAggregated = 0x0010, // Counterpart of fIsAggregate - tells // that it is a part of a fIsAggregate symbol fIsAliased = 0x0020, // variable has multiple simultaneous lifetimes fIsAlias = 0x0040, // represents one of the multiple simultaneous lifetimes } // represents an address range, used for optimized code debug info public struct CV_lvar_addr_range { // defines a range of addresses public uint offStart; public ushort isectStart; public uint cbRange; } // enum describing function data return method public enum CV_GENERIC_STYLE { CV_GENERIC_VOID = 0x00, // void return type CV_GENERIC_REG = 0x01, // return data is in registers CV_GENERIC_ICAN = 0x02, // indirect caller allocated near CV_GENERIC_ICAF = 0x03, // indirect caller allocated far CV_GENERIC_IRAN = 0x04, // indirect returnee allocated near CV_GENERIC_IRAF = 0x05, // indirect returnee allocated far CV_GENERIC_UNUSED = 0x06, // first unused } [Flags] public enum CV_GENERIC_FLAG : ushort { cstyle = 0x0001, // true push varargs right to left rsclean = 0x0002, // true if returnee stack cleanup } // flag bitfields for separated code attributes [Flags] public enum CV_SEPCODEFLAGS : uint { fIsLexicalScope = 0x00000001, // S_SEPCODE doubles as lexical scope fReturnsToParent = 0x00000002, // code frag returns to parent } // Generic layout for symbol records public struct SYMTYPE { public ushort reclen; // Record length public ushort rectyp; // Record type // byte data[CV_ZEROLEN]; // SYMTYPE *NextSym (SYMTYPE * pSym) { // return (SYMTYPE *) ((char *)pSym + pSym->reclen + sizeof(ushort)); // } } // non-model specific symbol types public struct RegSym { // public ushort reclen; // Record length [SYMTYPE] // public ushort rectyp; // S_REGISTER public uint typind; // (type index) Type index or Metadata token public ushort reg; // register enumerate public string name; // Length-prefixed name } public struct AttrRegSym { // public ushort reclen; // Record length [SYMTYPE] // public ushort rectyp; // S_MANREGISTER | S_ATTR_REGISTER public uint typind; // (type index) Type index or Metadata token public uint offCod; // first code address where var is live public ushort segCod; public ushort flags; // (CV_LVARFLAGS)local var flags public ushort reg; // register enumerate public string name; // Length-prefixed name } public struct ManyRegSym { // public ushort reclen; // Record length [SYMTYPE] // public ushort rectyp; // S_MANYREG public uint typind; // (type index) Type index or metadata token public byte count; // count of number of registers public byte[] reg; // count register enumerates, most-sig first public string name; // length-prefixed name. } public struct ManyRegSym2 { // public ushort reclen; // Record length [SYMTYPE] // public ushort rectyp; // S_MANYREG2 public uint typind; // (type index) Type index or metadata token public ushort count; // count of number of registers, public ushort[] reg; // count register enumerates, most-sig first public string name; // length-prefixed name. } public struct AttrManyRegSym { // public ushort reclen; // Record length [SYMTYPE] // public ushort rectyp; // S_MANMANYREG public uint typind; // (type index) Type index or metadata token public uint offCod; // first code address where var is live public ushort segCod; public ushort flags; // (CV_LVARFLAGS)local var flags public byte count; // count of number of registers public byte[] reg; // count register enumerates, most-sig first public string name; // utf-8 encoded zero terminate name } public struct AttrManyRegSym2 { // public ushort reclen; // Record length [SYMTYPE] // public ushort rectyp; // S_MANMANYREG2 | S_ATTR_MANYREG public uint typind; // (type index) Type index or metadata token public uint offCod; // first code address where var is live public ushort segCod; public ushort flags; // (CV_LVARFLAGS)local var flags public ushort count; // count of number of registers public ushort[] reg; // count register enumerates, most-sig first public string name; // utf-8 encoded zero terminate name } public struct ConstSym { // public ushort reclen; // Record length [SYMTYPE] // public ushort rectyp; // S_CONSTANT or S_MANCONSTANT public uint typind; // (type index) Type index (containing enum if enumerate) or metadata token public ushort value; // numeric leaf containing value public string name; // Length-prefixed name } public struct UdtSym { // public ushort reclen; // Record length [SYMTYPE] // public ushort rectyp; // S_UDT | S_COBOLUDT public uint typind; // (type index) Type index public string name; // Length-prefixed name } public struct ManyTypRef { // public ushort reclen; // Record length [SYMTYPE] // public ushort rectyp; // S_MANTYPREF public uint typind; // (type index) Type index } public struct SearchSym { // public ushort reclen; // Record length [SYMTYPE] // public ushort rectyp; // S_SSEARCH public uint startsym; // offset of the procedure public ushort seg; // segment of symbol } [Flags] public enum CFLAGSYM_FLAGS : ushort { pcode = 0x0001, // true if pcode present floatprec = 0x0006, // floating precision floatpkg = 0x0018, // float package ambdata = 0x00e0, // ambient data model ambcode = 0x0700, // ambient code model mode32 = 0x0800, // true if compiled 32 bit mode } public struct CFlagSym { // public ushort reclen; // Record length [SYMTYPE] // public ushort rectyp; // S_COMPILE public byte machine; // target processor public byte language; // language index public ushort flags; // (CFLAGSYM_FLAGS) public string ver; // Length-prefixed compiler version string } [Flags] public enum COMPILESYM_FLAGS : uint { iLanguage = 0x000000FF, // language index fEC = 0x00000100, // compiled for E/C fNoDbgInfo = 0x00000200, // not compiled with debug info fLTCG = 0x00000400, // compiled with LTCG fNoDataAlign = 0x00000800, // compiled with -Bzalign fManagedPresent = 0x00001000, // managed code/data present fSecurityChecks = 0x00002000, // compiled with /GS fHotPatch = 0x00004000, // compiled with /hotpatch fCVTCIL = 0x00008000, // converted with CVTCIL fMSILModule = 0x00010000, // MSIL netmodule } public struct CompileSym { // public ushort reclen; // Record length [SYMTYPE] // public ushort rectyp; // S_COMPILE2 public uint flags; // (COMPILESYM_FLAGS) public ushort machine; // target processor public ushort verFEMajor; // front end major version # public ushort verFEMinor; // front end minor version # public ushort verFEBuild; // front end build version # public ushort verMajor; // back end major version # public ushort verMinor; // back end minor version # public ushort verBuild; // back end build version # public string verSt; // Length-prefixed compiler version string, followed public string[] verArgs; // block of zero terminated strings, ended by double-zero. } public struct ObjNameSym { // public ushort reclen; // Record length [SYMTYPE] // public ushort rectyp; // S_OBJNAME public uint signature; // signature public string name; // Length-prefixed name } public struct EndArgSym { // public ushort reclen; // Record length [SYMTYPE] // public ushort rectyp; // S_ENDARG } public struct ReturnSym { // public ushort reclen; // Record length [SYMTYPE] // public ushort rectyp; // S_RETURN public CV_GENERIC_FLAG flags; // flags public byte style; // CV_GENERIC_STYLE return style // followed by return method data } public struct EntryThisSym { // public ushort reclen; // Record length [SYMTYPE] // public ushort rectyp; // S_ENTRYTHIS public byte thissym; // symbol describing this pointer on entry } public struct BpRelSym32 { // public ushort reclen; // Record length [SYMTYPE] // public ushort rectyp; // S_BPREL32 public int off; // BP-relative offset public uint typind; // (type index) Type index or Metadata token public string name; // Length-prefixed name } public struct FrameRelSym { // public ushort reclen; // Record length [SYMTYPE] // public ushort rectyp; // S_MANFRAMEREL | S_ATTR_FRAMEREL public int off; // Frame relative offset public uint typind; // (type index) Type index or Metadata token public uint offCod; // first code address where var is live public ushort segCod; public ushort flags; // (CV_LVARFLAGS)local var flags public string name; // Length-prefixed name } public struct SlotSym32 { // public ushort reclen; // Record length [SYMTYPE] // public ushort rectyp; // S_LOCALSLOT or S_PARAMSLOT public uint index; // slot index public uint typind; // (type index) Type index or Metadata token public string name; // Length-prefixed name } public struct AttrSlotSym { // public ushort reclen; // Record length [SYMTYPE] // public ushort rectyp; // S_MANSLOT public uint index; // slot index public uint typind; // (type index) Type index or Metadata token public uint offCod; // first code address where var is live public ushort segCod; public ushort flags; // (CV_LVARFLAGS)local var flags public string name; // Length-prefixed name } public struct AnnotationSym { // public ushort reclen; // Record length [SYMTYPE] // public ushort rectyp; // S_ANNOTATION public uint off; public ushort seg; public ushort csz; // Count of zero terminated annotation strings public string[] rgsz; // Sequence of zero terminated annotation strings } public struct DatasSym32 { // public ushort reclen; // Record length [SYMTYPE] // public ushort rectyp; // S_LDATA32, S_GDATA32 or S_PUB32, S_LMANDATA, S_GMANDATA public uint typind; // (type index) Type index, or Metadata token if a managed symbol public uint off; public ushort seg; public string name; // Length-prefixed name } [Flags] public enum CV_PUBSYMFLAGS : uint { fNone = 0x00000000, fCode = 0x00000001, // set if public symbol refers to a code address fFunction = 0x00000002, // set if public symbol is a function fManaged = 0x00000004, // set if managed code (native or IL) fMSIL = 0x00000008, // set if managed IL code } public struct PubSym32 { // public ushort reclen; // Record length [SYMTYPE] // public ushort rectyp; // S_PUB32 public uint flags; // (CV_PUBSYMFLAGS) public uint off; public ushort seg; public string name; // Length-prefixed name } public struct ProcSym32 { // public ushort reclen; // Record length [SYMTYPE] // public ushort rectyp; // S_GPROC32 or S_LPROC32 public uint parent; // pointer to the parent public uint end; // pointer to this blocks end public uint next; // pointer to next symbol public uint len; // Proc length public uint dbgStart; // Debug start offset public uint dbgEnd; // Debug end offset public uint typind; // (type index) Type index public uint off; public ushort seg; public byte flags; // (CV_PROCFLAGS) Proc flags public string name; // Length-prefixed name } public struct ManProcSym { // public ushort reclen; // Record length [SYMTYPE] // public ushort rectyp; // S_GMANPROC, S_LMANPROC, S_GMANPROCIA64 or S_LMANPROCIA64 public uint parent; // pointer to the parent public uint end; // pointer to this blocks end public uint next; // pointer to next symbol public uint len; // Proc length public uint dbgStart; // Debug start offset public uint dbgEnd; // Debug end offset public uint token; // COM+ metadata token for method public uint off; public ushort seg; public byte flags; // (CV_PROCFLAGS) Proc flags public ushort retReg; // Register return value is in (may not be used for all archs) public string name; // optional name field } public struct ManProcSymMips { // public ushort reclen; // Record length [SYMTYPE] // public ushort rectyp; // S_GMANPROCMIPS or S_LMANPROCMIPS public uint parent; // pointer to the parent public uint end; // pointer to this blocks end public uint next; // pointer to next symbol public uint len; // Proc length public uint dbgStart; // Debug start offset public uint dbgEnd; // Debug end offset public uint regSave; // int register save mask public uint fpSave; // fp register save mask public uint intOff; // int register save offset public uint fpOff; // fp register save offset public uint token; // COM+ token type public uint off; public ushort seg; public byte retReg; // Register return value is in public byte frameReg; // Frame pointer register public string name; // optional name field } public struct ThunkSym32 { // public ushort reclen; // Record length [SYMTYPE] // public ushort rectyp; // S_THUNK32 public uint parent; // pointer to the parent public uint end; // pointer to this blocks end public uint next; // pointer to next symbol public uint off; public ushort seg; public ushort len; // length of thunk public byte ord; // THUNK_ORDINAL specifying type of thunk public string name; // Length-prefixed name public byte[] variant; // variant portion of thunk } public enum TRAMP { // Trampoline subtype trampIncremental, // incremental thunks trampBranchIsland, // Branch island thunks } public struct TrampolineSym { // Trampoline thunk symbol // public ushort reclen; // Record length [SYMTYPE] // public ushort rectyp; // S_TRAMPOLINE public ushort trampType; // trampoline sym subtype public ushort cbThunk; // size of the thunk public uint offThunk; // offset of the thunk public uint offTarget; // offset of the target of the thunk public ushort sectThunk; // section index of the thunk public ushort sectTarget; // section index of the target of the thunk } public struct LabelSym32 { // public ushort reclen; // Record length [SYMTYPE] // public ushort rectyp; // S_LABEL32 public uint off; public ushort seg; public byte flags; // (CV_PROCFLAGS) flags public string name; // Length-prefixed name } public struct BlockSym32 { // public ushort reclen; // Record length [SYMTYPE] // public ushort rectyp; // S_BLOCK32 public uint parent; // pointer to the parent public uint end; // pointer to this blocks end public uint len; // Block length public uint off; // Offset in code segment public ushort seg; // segment of label public string name; // Length-prefixed name } public struct WithSym32 { // public ushort reclen; // Record length [SYMTYPE] // public ushort rectyp; // S_WITH32 public uint parent; // pointer to the parent public uint end; // pointer to this blocks end public uint len; // Block length public uint off; // Offset in code segment public ushort seg; // segment of label public string expr; // Length-prefixed expression string } public struct VpathSym32 { // public ushort reclen; // record length // public ushort rectyp; // S_VFTABLE32 public uint root; // (type index) type index of the root of path public uint path; // (type index) type index of the path record public uint off; // offset of virtual function table public ushort seg; // segment of virtual function table } public struct RegRel32 { // public ushort reclen; // Record length [SYMTYPE] // public ushort rectyp; // S_REGREL32 public uint off; // offset of symbol public uint typind; // (type index) Type index or metadata token public ushort reg; // register index for symbol public string name; // Length-prefixed name } public struct AttrRegRel { // public ushort reclen; // Record length [SYMTYPE] // public ushort rectyp; // S_MANREGREL | S_ATTR_REGREL public uint off; // offset of symbol public uint typind; // (type index) Type index or metadata token public ushort reg; // register index for symbol public uint offCod; // first code address where var is live public ushort segCod; public ushort flags; // (CV_LVARFLAGS)local var flags public string name; // Length-prefixed name } public struct ThreadSym32 { // public ushort reclen; // record length // public ushort rectyp; // S_LTHREAD32 | S_GTHREAD32 public uint typind; // (type index) type index public uint off; // offset into thread storage public ushort seg; // segment of thread storage public string name; // length prefixed name } public struct Slink32 { // public ushort reclen; // record length // public ushort rectyp; // S_SLINK32 public uint framesize; // frame size of parent procedure public int off; // signed offset where the static link was saved relative to the value of reg public ushort reg; } public struct ProcSymMips { // public ushort reclen; // Record length [SYMTYPE] // public ushort rectyp; // S_GPROCMIPS or S_LPROCMIPS public uint parent; // pointer to the parent public uint end; // pointer to this blocks end public uint next; // pointer to next symbol public uint len; // Proc length public uint dbgStart; // Debug start offset public uint dbgEnd; // Debug end offset public uint regSave; // int register save mask public uint fpSave; // fp register save mask public uint intOff; // int register save offset public uint fpOff; // fp register save offset public uint typind; // (type index) Type index public uint off; // Symbol offset public ushort seg; // Symbol segment public byte retReg; // Register return value is in public byte frameReg; // Frame pointer register public string name; // Length-prefixed name } public struct ProcSymIa64 { // public ushort reclen; // Record length [SYMTYPE] // public ushort rectyp; // S_GPROCIA64 or S_LPROCIA64 public uint parent; // pointer to the parent public uint end; // pointer to this blocks end public uint next; // pointer to next symbol public uint len; // Proc length public uint dbgStart; // Debug start offset public uint dbgEnd; // Debug end offset public uint typind; // (type index) Type index public uint off; // Symbol offset public ushort seg; // Symbol segment public ushort retReg; // Register return value is in public byte flags; // (CV_PROCFLAGS) Proc flags public string name; // Length-prefixed name } public struct RefSym { // public ushort reclen; // Record length [SYMTYPE] // public ushort rectyp; // S_PROCREF_ST, S_DATAREF_ST, or S_LPROCREF_ST public uint sumName; // SUC of the name public uint ibSym; // Offset of actual symbol in $$Symbols public ushort imod; // Module containing the actual symbol public ushort usFill; // align this record } public struct RefSym2 { // public ushort reclen; // Record length [SYMTYPE] // public ushort rectyp; // S_PROCREF, S_DATAREF, or S_LPROCREF public uint sumName; // SUC of the name public uint ibSym; // Offset of actual symbol in $$Symbols public ushort imod; // Module containing the actual symbol public string name; // hidden name made a first class member } public struct AlignSym { // public ushort reclen; // Record length [SYMTYPE] // public ushort rectyp; // S_ALIGN } public struct OemSymbol { // public ushort reclen; // Record length [SYMTYPE] // public ushort rectyp; // S_OEM public Guid idOem; // an oem ID (GUID) public uint typind; // (type index) Type index public byte[] rgl; // user data, force 4-byte alignment } [Flags] public enum FRAMEPROCSYM_FLAGS : uint { fHasAlloca = 0x00000001, // function uses _alloca() fHasSetJmp = 0x00000002, // function uses setjmp() fHasLongJmp = 0x00000004, // function uses longjmp() fHasInlAsm = 0x00000008, // function uses inline asm fHasEH = 0x00000010, // function has EH states fInlSpec = 0x00000020, // function was speced as inline fHasSEH = 0x00000040, // function has SEH fNaked = 0x00000080, // function is __declspec(naked) fSecurityChecks = 0x00000100, // function has buffer security check introduced by /GS. fAsyncEH = 0x00000200, // function compiled with /EHa fGSNoStackOrdering = 0x00000400, // function has /GS buffer checks, but stack ordering couldn't be done fWasInlined = 0x00000800, // function was inlined within another function } public struct FrameProcSym { // public ushort reclen; // Record length [SYMTYPE] // public ushort rectyp; // S_FRAMEPROC public uint cbFrame; // count of bytes of total frame of procedure public uint cbPad; // count of bytes of padding in the frame public uint offPad; // offset (rel to frame) to where padding starts public uint cbSaveRegs; // count of bytes of callee save registers public uint offExHdlr; // offset of exception handler public ushort secExHdlr; // section id of exception handler public uint flags; // (FRAMEPROCSYM_FLAGS) } public struct UnamespaceSym { // public ushort reclen; // Record length [SYMTYPE] // public ushort rectyp; // S_UNAMESPACE public string name; // name } public struct SepCodSym { // public ushort reclen; // Record length [SYMTYPE] // public ushort rectyp; // S_SEPCODE public uint parent; // pointer to the parent public uint end; // pointer to this block's end public uint length; // count of bytes of this block public uint scf; // (CV_SEPCODEFLAGS) flags public uint off; // sec:off of the separated code public uint offParent; // secParent:offParent of the enclosing scope public ushort sec; // (proc, block, or sepcode) public ushort secParent; } public struct LocalSym { // public ushort reclen; // Record length [SYMTYPE] // public ushort rectyp; // S_LOCAL public uint id; // id of the local public uint typind; // (type index) type index public ushort flags; // (CV_LVARFLAGS) local var flags public uint idParent; // This is is parent variable - fIsAggregated or fIsAlias public uint offParent; // Offset in parent variable - fIsAggregated public uint expr; // NI of expression that this temp holds public uint pad0; // pad, must be zero public uint pad1; // pad, must be zero public string name; // Name of this symbol. } public struct DefRangeSym { // public ushort reclen; // Record length [SYMTYPE] // public ushort rectyp; // S_DEFRANGE public uint id; // ID of the local symbol for which this formula holds public uint program; // program to evaluate the value of the symbol public CV_lvar_addr_range range; // Range of addresses where this program is valid } public struct DefRangeSym2 { // public ushort reclen; // Record length [SYMTYPE] // public ushort rectyp; // S_DEFRANGE2 public uint id; // ID of the local symbol for which this formula holds public uint program; // program to evaluate the value of the symbol public ushort count; // count of CV_lvar_addr_range records following public CV_lvar_addr_range[] range; // Range of addresses where this program is valid } public struct SectionSym { // public ushort reclen // Record length // public ushort rectyp; // S_SECTION public ushort isec; // Section number public byte align; // Alignment of this section (power of 2) public byte bReserved; // Reserved. Must be zero. public uint rva; public uint cb; public uint characteristics; public string name; // name } public struct CoffGroupSym { // public ushort reclen; // Record length [SYMTYPE] // public ushort rectyp; // S_COFFGROUP public uint cb; public uint characteristics; public uint off; // Symbol offset public ushort seg; // Symbol segment public string name; // name } [Flags] public enum EXPORTSYM_FLAGS : ushort { fConstant = 0x0001, // CONSTANT fData = 0x0002, // DATA fPrivate = 0x0004, // PRIVATE fNoName = 0x0008, // NONAME fOrdinal = 0x0010, // Ordinal was explicitly assigned fForwarder = 0x0020, // This is a forwarder } public struct ExportSym { // public ushort reclen; // Record length [SYMTYPE] // public ushort rectyp; // S_EXPORT public ushort ordinal; public ushort flags; // (EXPORTSYM_FLAGS) public string name; // name of } // // Symbol for describing indirect calls when they are using // a function pointer cast on some other type or temporary. // Typical content will be an LF_POINTER to an LF_PROCEDURE // type record that should mimic an actual variable with the // function pointer type in question. // // Since the compiler can sometimes tail-merge a function call // through a function pointer, there may be more than one // S_CALLSITEINFO record at an address. This is similar to what // you could do in your own code by: // // if (expr) // pfn = &function1; // else // pfn = &function2; // // (*pfn)(arg list); // public struct CallsiteInfo { // public ushort reclen; // Record length [SYMTYPE] // public ushort rectyp; // S_CALLSITEINFO public int off; // offset of call site public ushort ect; // section index of call site public ushort pad0; // alignment padding field, must be zero public uint typind; // (type index) type index describing function signature } // Frame cookie information public enum CV_cookietype { CV_COOKIETYPE_COPY = 0, CV_COOKIETYPE_XOR_SP, CV_COOKIETYPE_XOR_BP, CV_COOKIETYPE_XOR_R13, } // Symbol for describing security cookie's position and type // (raw, xor'd with esp, xor'd with ebp). public struct FrameCookie { // public ushort reclen; // Record length [SYMTYPE] // public ushort rectyp; // S_FRAMECOOKIE public int off; // Frame relative offset public ushort reg; // Register index public int cookietype; // (CV_cookietype) Type of the cookie public byte flags; // Flags describing this cookie } public enum CV_DISCARDED : uint { CV_DISCARDED_UNKNOWN = 0, CV_DISCARDED_NOT_SELECTED = 1, CV_DISCARDED_NOT_REFERENCED = 2, } public struct DiscardedSym { // public ushort reclen; // Record length [SYMTYPE] // public ushort rectyp; // S_DISCARDED public CV_DISCARDED iscarded; public uint fileid; // First FILEID if line number info present public uint linenum; // First line number public byte[] data; // Original record(s) with invalid indices } // // V7 line number data types // public enum DEBUG_S_SUBSECTION_TYPE : uint { DEBUG_S_IGNORE = 0x80000000, // if this bit is set in a subsection type then ignore the subsection contents DEBUG_S_SYMBOLS = 0xF1, DEBUG_S_LINES = 0xF2, DEBUG_S_STRINGTABLE = 0xF3, DEBUG_S_FILECHKSMS = 0xF4, DEBUG_S_FRAMEDATA = 0xF5, } // // Line flags (data present) // public enum CV_LINE_SUBSECTION_FLAGS : ushort { CV_LINES_HAVE_COLUMNS = 0x0001, } public struct CV_LineSection { public uint off; public ushort sec; public ushort flags; public uint cod; } public struct CV_SourceFile { public uint index; // Index to file in checksum section. public uint count; // Number of CV_Line records. public uint linsiz; // Size of CV_Line recods. } [Flags] public enum CV_Line_Flags : uint { linenumStart = 0x00FFFFFF, // line where statement/expression starts deltaLineEnd = 0x7F000000, // delta to line where statement ends (optional) fStatement = 0x80000000, // true if a statement linenumber, else an expression line num } public struct CV_Line { public uint offset; // Offset to start of code bytes for line number public uint flags; // (CV_Line_Flags) } public struct CV_Column { public ushort offColumnStart; public ushort offColumnEnd; } // File information public enum CV_FILE_CHECKSUM_TYPE : byte { None = 0, MD5 = 1, } public struct CV_FileCheckSum { public uint name; // Index of name in name table. public byte len; // Hash length public byte type; // Hash type } [Flags] public enum FRAMEDATA_FLAGS : uint { fHasSEH = 0x00000001, fHasEH = 0x00000002, fIsFunctionStart = 0x00000004, } public struct FrameData { public uint ulRvaStart; public uint cbBlock; public uint cbLocals; public uint cbParams; public uint cbStkMax; public uint frameFunc; public ushort cbProlog; public ushort cbSavedRegs; public uint flags; // (FRAMEDATA_FLAGS) } public struct XFixupData { public ushort wType; public ushort wExtra; public uint rva; public uint rvaTarget; } public enum DEBUG_S_SUBSECTION { SYMBOLS = 0xF1, LINES = 0xF2, STRINGTABLE = 0xF3, FILECHKSMS = 0xF4, FRAMEDATA = 0xF5, } } ================================================ FILE: Zelig/Zelig/CompileTime/MetaData/Importer/PDBInfo/DataStream.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // // // Originally from the Microsoft Research Singularity code base. // namespace Microsoft.Zelig.MetaData.Importer.PdbInfo { using System; using System.Collections; using System.Collections.Generic; using Microsoft.Zelig.MetaData.Importer.PdbInfo.CodeView; public class DataStream { // // State // private int m_contentSize; private int[] m_pages; private byte[] m_payload; // // Constructor Methods // public DataStream() { m_contentSize = 0; m_pages = new int[0]; m_payload = new byte[0]; } internal DataStream( int contentSize , PdbReader reader , ArrayReader bits ) { m_contentSize = contentSize; int pageCount = reader.PagesFromSize( contentSize ); if(pageCount > 0) { m_pages = bits.ReadInt32Array( pageCount ); } else { m_pages = new int[0]; } m_payload = new byte[contentSize]; int pageSize = reader.PageSize; int pageNumber = 0; int offset = 0; while(contentSize > 0) { int pageAvailable = Math.Min( pageSize, contentSize ); reader.Seek( m_pages[pageNumber], 0 ); reader.Read( m_payload, offset, pageAvailable ); pageNumber += 1; offset += pageAvailable; contentSize -= pageAvailable; } } // // Helper Methods // public ArrayReader GetReader() { return new ArrayReader( m_payload ); } public void Copy( PdbWriter pdbWriter , DataStream src ) { if(src.Length > 0) { byte[] data = src.Payload; Write( pdbWriter, data, data.Length ); } } internal void Write( PdbWriter writer , ArrayWriter buffer ) { byte[] bytes = buffer.ToArray(); int data = bytes.Length; Write( writer, bytes, data ); } internal void Write( PdbWriter writer , byte[] bytes , int data ) { if(bytes == null || data == 0) { return; } int left = data; int used = 0; int rema = m_contentSize % writer.PageSize; if(rema != 0) { int todo = writer.PageSize - rema; if(todo > left) { todo = left; } int lastPage = m_pages[m_pages.Length - 1]; writer.Seek( lastPage, rema ); writer.Write( bytes, used, todo ); used += todo; left -= todo; } if(left > 0) { int count = (left + writer.PageSize - 1) / writer.PageSize; int page0 = writer.AllocatePages( count ); writer.Seek( page0, 0 ); writer.Write( bytes, used, left ); AddPages( page0, count ); } m_contentSize += data; } private void AddPages( int page0 , int count ) { int used = m_pages.Length; m_pages = ArrayUtility.EnsureSizeOfNotNullArray( m_pages, used + count ); for(int i = 0; i < count; i++) { m_pages[used + i] = page0 + i; } } public int GetPage( int index ) { return m_pages[index]; } // // Access Methods // public int[] Pages { get { return m_pages; } } public int NumOfPages { get { return m_pages.Length; } } public int Length { get { return m_contentSize; } } public byte[] Payload { get { return m_payload; } set { m_contentSize = value.Length; m_payload = value; m_pages = null; } } } } ================================================ FILE: Zelig/Zelig/CompileTime/MetaData/Importer/PDBInfo/DbiHeader.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // // // Originally from the Microsoft Research Singularity code base. // namespace Microsoft.Zelig.MetaData.Importer.PdbInfo.Features { using System; using System.Collections; using System.Collections.Generic; using Microsoft.Zelig.MetaData.Importer.PdbInfo.CodeView; public enum DbgType { dbgtypeFPO = 0, dbgtypeException = 1, dbgtypeFixup = 2, dbgtypeOmapToSrc = 3, dbgtypeOmapFromSrc = 4, dbgtypeSectionHdr = 5, dbgtypeTokenRidMap = 6, dbgtypeXdata = 7, dbgtypePdata = 8, dbgtypeNewFPO = 9, dbgtypeSectionHdrOrig = 10, dbgtypeFirst = dbgtypeFPO, } public struct DbiHeader { public int sig; // 0..3 public int ver; // 4..7 public int age; // 8..11 public short gssymStream; // 12..13 public ushort vers; // 14..15 public short pssymStream; // 16..17 public ushort pdbver; // 18..19 public short symrecStream; // 20..21 public ushort pdbver2; // 22..23 public int gpmodiSize; // 24..27 public int secconSize; // 28..31 public int secmapSize; // 32..35 public int filinfSize; // 36..39 public int tsmapSize; // 40..43 public int mfcIndex; // 44..47 public int dbghdrSize; // 48..51 public int ecinfoSize; // 52..55 public ushort flags; // 56..57 public ushort machine; // 58..59 public int reserved; // 60..63 public DbiHeader( ArrayReader bits ) { sig = bits.ReadInt32(); ver = bits.ReadInt32(); age = bits.ReadInt32(); gssymStream = bits.ReadInt16(); vers = bits.ReadUInt16(); pssymStream = bits.ReadInt16(); pdbver = bits.ReadUInt16(); symrecStream = bits.ReadInt16(); pdbver2 = bits.ReadUInt16(); gpmodiSize = bits.ReadInt32(); secconSize = bits.ReadInt32(); secmapSize = bits.ReadInt32(); filinfSize = bits.ReadInt32(); tsmapSize = bits.ReadInt32(); mfcIndex = bits.ReadInt32(); dbghdrSize = bits.ReadInt32(); ecinfoSize = bits.ReadInt32(); flags = bits.ReadUInt16(); machine = bits.ReadUInt16(); reserved = bits.ReadInt32(); } } } ================================================ FILE: Zelig/Zelig/CompileTime/MetaData/Importer/PDBInfo/DbiModuleInfo.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // // // Originally from the Microsoft Research Singularity code base. // namespace Microsoft.Zelig.MetaData.Importer.PdbInfo.Features { using System; using System.Collections; using System.Collections.Generic; using Microsoft.Zelig.MetaData.Importer.PdbInfo.CodeView; public class DbiModuleInfo { // // State // public int opened; // 0..3 public DbiSecCon section; // 4..31 public ushort flags; // 32..33 public short stream; // 34..35 public int cbSyms; // 36..39 public int cbOldLines; // 40..43 public int cbLines; // 44..57 public short files; // 48..49 public short pad1; // 50..51 public uint offsets; public int niSource; public int niCompiler; public string moduleName; public string objectName; // // Constructor Methods // public DbiModuleInfo( ArrayReader bits ) { opened = bits.ReadInt32(); section = new DbiSecCon( bits ); flags = bits.ReadUInt16(); stream = bits.ReadInt16(); cbSyms = bits.ReadInt32(); cbOldLines = bits.ReadInt32(); cbLines = bits.ReadInt32(); files = bits.ReadInt16(); pad1 = bits.ReadInt16(); offsets = bits.ReadUInt32(); niSource = bits.ReadInt32(); niCompiler = bits.ReadInt32(); moduleName = bits.ReadZeroTerminatedUTF8String(); objectName = bits.ReadZeroTerminatedUTF8String(); bits.AlignAbsolute( 4 ); if(opened != 0 /*|| pad1 != 0*/) { throw new PdbException( "opened is {0}, not 0", opened ); } } } } ================================================ FILE: Zelig/Zelig/CompileTime/MetaData/Importer/PDBInfo/DbiSecCon.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // // // Originally from the Microsoft Research Singularity code base. // namespace Microsoft.Zelig.MetaData.Importer.PdbInfo.Features { using System; using System.Collections; using System.Collections.Generic; using Microsoft.Zelig.MetaData.Importer.PdbInfo.CodeView; public struct DbiSecCon { public short section; // 0..1 public short pad1; // 2..3 public int offset; // 4..7 public int size; // 8..11 public uint flags; // 12..15 public short module; // 16..17 public short pad2; // 18..19 public uint dataCrc; // 20..23 public uint relocCrc; // 24..27 public DbiSecCon( ArrayReader bits ) { section = bits.ReadInt16(); pad1 = bits.ReadInt16(); offset = bits.ReadInt32(); size = bits.ReadInt32(); flags = bits.ReadUInt32(); module = bits.ReadInt16(); pad2 = bits.ReadInt16(); dataCrc = bits.ReadUInt32(); relocCrc = bits.ReadUInt32(); //if(pad1 != 0 || pad2 != 0) //{ // throw new PdbException( "pad1 or pad2 != 0" ); //} } } } ================================================ FILE: Zelig/Zelig/CompileTime/MetaData/Importer/PDBInfo/MsfDirectory.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // // // Originally from the Microsoft Research Singularity code base. // namespace Microsoft.Zelig.MetaData.Importer.PdbInfo.Features { using System; using System.Collections; using System.Collections.Generic; using Microsoft.Zelig.MetaData.Importer.PdbInfo.CodeView; public class MsfDirectory { // // State // private DataStream[] m_streams; // // Constructor Methods // public MsfDirectory() { m_streams = new DataStream[0]; } public MsfDirectory( PdbReader reader , PdbFileHeader head ) { // 0..n in page of directory pages. reader.Seek( head.directoryRoot, 0 ); DataStream stream = new DataStream( head.directorySize, reader, reader.Image ); ArrayReader bits = stream.GetReader(); // 0..3 in directory pages int count = bits.ReadInt32(); // 4..n int[] sizes = bits.ReadInt32Array( count ); // n..m m_streams = new DataStream[count]; for(int i = 0; i < count; i++) { if(sizes[i] <= 0) { m_streams[i] = new DataStream(); } else { m_streams[i] = new DataStream( sizes[i], reader, bits ); } } } // // Helper Methods // public ArrayReader GetArrayReaderForStream( int idx ) { return m_streams[idx].GetReader(); } public DataStream CreateNewStream() { int idx; return CreateNewStream( out idx ); } public DataStream CreateNewStream( out int idx ) { idx = m_streams.Length; return CreateNewStream( idx ); } public DataStream CreateNewStream( int idx ) { m_streams = ArrayUtility.EnsureSizeOfNotNullArray( m_streams, idx + 1 ); DataStream res = new DataStream(); m_streams[idx] = res; return res; } //--// public void Emit( PdbWriter pdbWriter , out int directoryRoot , out int directorySize ) { int pages = 0; foreach(DataStream stream in m_streams) { if(stream.Length > 0) { pages += stream.NumOfPages; } } ArrayWriter writer = new ArrayWriter(); writer.Write( m_streams.Length ); foreach(DataStream stream in m_streams) { writer.Write( stream.Length ); } foreach(DataStream stream in m_streams) { if(stream.Length > 0) { writer.Write( stream.Pages ); } } DataStream directory = new DataStream(); directory.Write( pdbWriter, writer ); directorySize = directory.Length; //--// ArrayWriter writer2 = new ArrayWriter(); writer2.Write( directory.Pages ); DataStream ddir = new DataStream(); ddir.Write( pdbWriter, writer2 ); directoryRoot = ddir.Pages[0]; } // // Access Methods // public DataStream[] Streams { get { return m_streams; } } } } ================================================ FILE: Zelig/Zelig/CompileTime/MetaData/Importer/PDBInfo/PdbException.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // // // Originally from the Microsoft Research Singularity code base. // namespace Microsoft.Zelig.MetaData.Importer.PdbInfo { using System; public class PdbException : Exception { // // Constructor Methods // public PdbException( String format , params object[] args ) : base( String.Format( format, args ) ) { } } } ================================================ FILE: Zelig/Zelig/CompileTime/MetaData/Importer/PDBInfo/PdbFile.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // // // Originally from the Microsoft Research Singularity code base. // namespace Microsoft.Zelig.MetaData.Importer.PdbInfo { using System; using System.Collections; using System.Collections.Generic; using Microsoft.Zelig.MetaData.Importer.PdbInfo.CodeView; using Microsoft.Zelig.MetaData.Importer.PdbInfo.Features; public class PdbFile { // // State // const int c_Index_PdbStream = 1; const int c_Index_DbiStream = 3; private PdbFileHeader m_head; private MsfDirectory m_dir; private PdbStream m_pdbStream; private PdbFunction[] m_funcs; private Dictionary< uint, PdbFunction > m_lookupToken; // // Constructor Methods // public PdbFile( ArrayReader image ) { PdbReader pdbReader; m_head = new PdbFileHeader( image ); pdbReader = new PdbReader ( image , m_head.pageSize ); m_dir = new MsfDirectory ( pdbReader, m_head ); m_pdbStream = new PdbStream ( m_dir.GetArrayReaderForStream( c_Index_PdbStream ) ); int nameStream = m_pdbStream.GetStreamNumber( "/names" ); if(nameStream <= 0) { throw new PdbException( "No name stream" ); } ushort tokenRidMapStream; uint[] tokenRidMap = null; Dictionary< int, string > names = LoadNameStream( m_dir.GetArrayReaderForStream( nameStream ) ); List< DbiModuleInfo > modules = LoadDbiStream ( m_dir.GetArrayReaderForStream( c_Index_DbiStream ), out tokenRidMapStream ); if(tokenRidMapStream != 0xFFFF) { tokenRidMap = LoadTokenRidMap( m_dir.GetArrayReaderForStream( tokenRidMapStream ) ); } List< PdbFunction > funcList = new List< PdbFunction >(); foreach(DbiModuleInfo module in modules) { if(module.stream > 0) { LoadFuncsFromDbiModule( m_dir.GetArrayReaderForStream( module.stream ), module, names, funcList ); } } m_funcs = funcList.ToArray(); m_lookupToken = new Dictionary< uint, PdbFunction >(); // // Remap function tokens. // foreach(PdbFunction func in m_funcs) { uint token = func.Token; if(tokenRidMap != null) { TokenType tt = MetaData.UnpackTokenAsType( (int)token ); if(tt == TokenType.Method) { int index = MetaData.UnpackTokenAsIndex( (int)token ); if(index >= 0 && index < tokenRidMap.Length) { token = (uint)MetaData.PackToken( TokenType.Method, (int)tokenRidMap[index] ); func.Token = token; } } } m_lookupToken[token] = func; } Array.Sort( m_funcs, PdbFunction.byAddress ); } public byte[] Emit() { ArrayWriter writer = new ArrayWriter(); int pageSize = m_head.pageSize; while(true) { int totalNumberOfPages = 3; for(int i = 0; i < m_dir.Streams.Length; i++) { int size = m_dir.Streams[i].Length; totalNumberOfPages += (size + pageSize - 1) / pageSize; } if(totalNumberOfPages < pageSize * 8) { break; } pageSize *= 2; } PdbWriter pdbWriter = new PdbWriter( writer, pageSize ); MsfDirectory newDir = new MsfDirectory(); for(int i = 0; i < m_dir.Streams.Length; i++) { DataStream src = m_dir .Streams[i]; DataStream dst = newDir.CreateNewStream( i ); dst.Copy( pdbWriter, src ); } pdbWriter.Emit( newDir ); return writer.ToArray(); } public DataStream GetStream( string name ) { int idx = m_pdbStream.GetStreamNumber( name ); if(idx == -1) { return null; } return m_dir.Streams[ idx ]; } public DataStream CreateNewStream( string name ) { DataStream res = GetStream( name ); if(res == null) { int idx; res = m_dir.CreateNewStream( out idx ); m_pdbStream.SetStreamNumber( name, idx ); DataStream stream = m_dir.CreateNewStream( c_Index_PdbStream ); ArrayWriter writer = new ArrayWriter(); m_pdbStream.Emit( writer ); stream.Payload = writer.ToArray(); } return res; } public PdbFunction[] Functions { get { return m_funcs; } } public PdbFunction FindFunction( uint token ) { PdbFunction res; if(m_lookupToken.TryGetValue( token, out res )) { return res; } return null; } //--// static Dictionary< int, string > LoadNameStream( ArrayReader bits ) { Dictionary< int, string > ht = new Dictionary< int, string >(); uint sig = bits.ReadUInt32(); // 0..3 Signature int ver = bits.ReadInt32(); // 4..7 Version if(sig != 0xEFFEEFFE || ver != 1) { throw new PdbException( "Unsupported Name Stream version" ); } // Read (or skip) string buffer. int stringBufLen = bits.ReadInt32(); // 8..11 Bytes of Strings ArrayReader stringBits = bits.CreateSubsetAndAdvance( stringBufLen ); // Read hash table. int siz = bits.ReadInt32(); // n+0..3 Number of hash buckets. ArrayReader subBits = new ArrayReader( bits, 0 ); for(int i = 0; i < siz; i++) { int ni = subBits.ReadInt32(); if(ni != 0) { stringBits.Position = ni; string name = stringBits.ReadZeroTerminatedUTF8String(); ht.Add( ni, name ); } } return ht; } private static PdbFunction FindFunction( PdbFunction[] funcs , ushort sec , uint off ) { PdbFunction match = new PdbFunction(); match.Segment = sec; match.Address = off; int item = Array.BinarySearch( funcs, match, PdbFunction.byAddress ); if(item >= 0) { return funcs[item]; } return null; } static void LoadManagedLines( PdbFunction[] funcs , Dictionary names , ArrayReader bits , uint limit ) { Dictionary checks = new Dictionary(); Array.Sort( funcs, PdbFunction.byAddress ); // Read the files first ArrayReader subBits = bits.CreateSubset( (int)(limit - bits.Position) ); while(subBits.IsEOF == false) { DEBUG_S_SUBSECTION sig = (DEBUG_S_SUBSECTION)subBits.ReadInt32(); int siz = subBits.ReadInt32(); ArrayReader subsectionBits = subBits.CreateSubsetAndAdvance( siz ); switch(sig) { case DEBUG_S_SUBSECTION.FILECHKSMS: while(subsectionBits.IsEOF == false) { CV_FileCheckSum chk; int ni = subsectionBits.Position; chk.name = subsectionBits.ReadUInt32(); chk.len = subsectionBits.ReadUInt8 (); chk.type = subsectionBits.ReadUInt8 (); string name = names[(int)chk.name]; PdbSource src = new PdbSource( (uint)ni, name ); checks.Add( ni, src ); subsectionBits.Seek( chk.len ); subsectionBits.AlignAbsolute( 4 ); } break; } } // Read the lines next. subBits.Rewind(); while(subBits.IsEOF == false) { DEBUG_S_SUBSECTION sig = (DEBUG_S_SUBSECTION)subBits.ReadInt32(); int siz = subBits.ReadInt32(); ArrayReader subsectionBits = subBits.CreateSubsetAndAdvance( siz ); switch(sig) { case DEBUG_S_SUBSECTION.LINES: { CV_LineSection sec; sec.off = subsectionBits.ReadUInt32(); sec.sec = subsectionBits.ReadUInt16(); sec.flags = subsectionBits.ReadUInt16(); sec.cod = subsectionBits.ReadUInt32(); PdbFunction func = FindFunction( funcs, sec.sec, sec.off ); // Count the line blocks. List blocks = new List(); while(subsectionBits.IsEOF == false) { CV_SourceFile file; file.index = subsectionBits.ReadUInt32(); file.count = subsectionBits.ReadUInt32(); file.linsiz = subsectionBits.ReadUInt32(); // Size of payload. // // Apparently, file.linsiz overestimates the size of the payload... // int linsiz = (int)file.count * (8 + ((sec.flags & 1) != 0 ? 4 : 0)); ArrayReader payloadBits = subsectionBits.CreateSubsetAndAdvance( linsiz ); PdbSource src = checks[(int)file.index]; PdbLines tmp = new PdbLines( src, file.count ); blocks.Add( tmp ); PdbLine[] lines = tmp.Lines; ArrayReader plinBits = payloadBits.CreateSubsetAndAdvance( 8 * (int)file.count ); for(int i = 0; i < file.count; i++) { CV_Line line; CV_Column column = new CV_Column(); line.offset = plinBits.ReadUInt32(); line.flags = plinBits.ReadUInt32(); uint delta = (line.flags & 0x7f000000) >> 24; bool statement = ((line.flags & 0x80000000) == 0); uint lineNo = line.flags & 0x00FFFFFF; if((sec.flags & 1) != 0) { column.offColumnStart = payloadBits.ReadUInt16(); column.offColumnEnd = payloadBits.ReadUInt16(); } lines[i] = new PdbLine( line.offset, lineNo, lineNo + delta, column.offColumnStart, column.offColumnEnd ); } } func.LineBlocks = blocks.ToArray(); break; } } } } static PdbFunction[] LoadManagedFunctions( string module , ArrayReader bits , uint limit ) { List funcList = new List(); while(bits.Position < limit) { ushort siz = bits.ReadUInt16(); ArrayReader subBits = bits.CreateSubsetAndAdvance( siz ); SYM rec = (SYM)subBits.ReadUInt16(); switch(rec) { case SYM.S_GMANPROC: case SYM.S_LMANPROC: { ManProcSym proc = new ManProcSym(); proc.parent = subBits.ReadUInt32(); proc.end = subBits.ReadUInt32(); proc.next = subBits.ReadUInt32(); proc.len = subBits.ReadUInt32(); proc.dbgStart = subBits.ReadUInt32(); proc.dbgEnd = subBits.ReadUInt32(); proc.token = subBits.ReadUInt32(); proc.off = subBits.ReadUInt32(); proc.seg = subBits.ReadUInt16(); proc.flags = subBits.ReadUInt8 (); proc.retReg = subBits.ReadUInt16(); proc.name = subBits.ReadZeroTerminatedUTF8String(); funcList.Add( new PdbFunction( module, proc, bits ) ); } break; default: throw new PdbException( "Unknown SYMREC {0}", rec ); } } return funcList.ToArray(); } static void LoadFuncsFromDbiModule( ArrayReader bits , DbiModuleInfo info , Dictionary names , List funcList ) { bits.Rewind(); int sig = bits.ReadInt32(); if(sig != 4) { throw new PdbException( "Invalid signature." ); } PdbFunction[] funcs = LoadManagedFunctions( info.moduleName, bits, (uint)info.cbSyms ); if(funcs != null) { bits.Position = info.cbSyms + info.cbOldLines; LoadManagedLines( funcs, names, bits, (uint)(info.cbSyms + info.cbOldLines + info.cbLines) ); for(int i = 0; i < funcs.Length; i++) { funcList.Add( funcs[i] ); } } } static List LoadDbiStream( ArrayReader bits , out ushort tokenRidMapStream ) { DbiHeader dh = new DbiHeader( bits ); if(dh.sig != -1 || dh.ver != 19990903) { throw new PdbException( "Unsupported DBI Stream version" ); } ArrayReader subBits; // Read gpmod section. List modList = new List(); subBits = bits.CreateSubsetAndAdvance( dh.gpmodiSize ); while(subBits.IsEOF == false) { modList.Add( new DbiModuleInfo( subBits ) ); } // Skip the Section Contribution substream. bits.Seek( dh.secconSize ); // Skip the Section Map substream. bits.Seek( dh.secmapSize ); // Skip the File Info substream. bits.Seek( dh.filinfSize ); // Skip the TSM substream. bits.Seek( dh.tsmapSize ); // Skip the EC substream. bits.Seek( dh.ecinfoSize ); // Read the optional header. subBits = bits.CreateSubsetAndAdvance( dh.dbghdrSize ); DbgType idx = DbgType.dbgtypeFirst; tokenRidMapStream = 0xFFFF; while(subBits.IsEOF == false) { ushort stream = subBits.ReadUInt16(); if(idx == DbgType.dbgtypeTokenRidMap) { tokenRidMapStream = stream; break; } idx++; } return modList; } static uint[] LoadTokenRidMap( ArrayReader bits ) { return bits.ReadUInt32Array( bits.Length / 4 ); } } } ================================================ FILE: Zelig/Zelig/CompileTime/MetaData/Importer/PDBInfo/PdbFileHeader.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // // // Originally from the Microsoft Research Singularity code base. // namespace Microsoft.Zelig.MetaData.Importer.PdbInfo.Features { using System; using System.Collections; using System.Collections.Generic; using Microsoft.Zelig.MetaData.Importer.PdbInfo.CodeView; public class PdbFileHeader { // // State // public readonly byte[] magic; public readonly int pageSize; public int freePageMap; public int pagesUsed; public int directorySize; public readonly int zero; public int directoryRoot; // // Constructor Methods // public PdbFileHeader( int pageSize ) { this.magic = new byte[32] { 0x4D, 0x69, 0x63, 0x72, 0x6F, 0x73, 0x6F, 0x66, // "Microsof" 0x74, 0x20, 0x43, 0x2F, 0x43, 0x2B, 0x2B, 0x20, // "t C/C++ " 0x4D, 0x53, 0x46, 0x20, 0x37, 0x2E, 0x30, 0x30, // "MSF 7.00" 0x0D, 0x0A, 0x1A, 0x44, 0x53, 0x00, 0x00, 0x00 // "^^^DS^^^" }; this.pageSize = pageSize; this.zero = 0; } public PdbFileHeader( ArrayReader image ) { image.Rewind(); this.magic = image.ReadUInt8Array( 32 ); // 0..31 this.pageSize = image.ReadInt32(); // 32..35 this.freePageMap = image.ReadInt32(); // 36..39 this.pagesUsed = image.ReadInt32(); // 40..43 this.directorySize = image.ReadInt32(); // 44..47 this.zero = image.ReadInt32(); // 48..51 this.directoryRoot = image.ReadInt32(); // 52..55 } // // Helper Methods // public void Emit( ArrayWriter writer ) { writer.Write( magic ); // 0..31 writer.Write( pageSize ); // 32..35 writer.Write( freePageMap ); // 36..39 writer.Write( pagesUsed ); // 40..43 writer.Write( directorySize ); // 44..47 writer.Write( zero ); // 48..51 writer.Write( directoryRoot ); // 52..55 } } } ================================================ FILE: Zelig/Zelig/CompileTime/MetaData/Importer/PDBInfo/PdbFunction.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // // // Originally from the Microsoft Research Singularity code base. // namespace Microsoft.Zelig.MetaData.Importer.PdbInfo { using System; using System.Collections; using System.Collections.Generic; using Microsoft.Zelig.MetaData.Importer.PdbInfo.CodeView; using Microsoft.Zelig.MetaData.Importer.PdbInfo.Features; public class PdbFunction { internal static readonly Guid msilMetaData = new Guid( 0xC6EA3FC9, 0x59B3, 0x49D6, 0xBC, 0x25, 0x09, 0x02,0xBB, 0xAB, 0xB4, 0x60 ); internal static readonly IComparer byAddress = new PdbFunctionsByAddress(); // // State // public uint Token; public uint SlotToken; public string Name; public string Module; public ushort Flags; public uint Segment; public uint Address; public uint Length; public byte[] Metadata; public PdbScope[] Scopes; public PdbLines[] LineBlocks; // // Constructor Methods // internal PdbFunction() { } internal PdbFunction( string module , ManProcSym proc , ArrayReader bits ) { this.Token = proc.token; this.Module = module; this.Name = proc.name; this.Flags = proc.flags; this.Segment = proc.seg; this.Address = proc.off; this.Length = proc.len; this.SlotToken = 0; this.LineBlocks = new PdbLines[0]; if(proc.seg != 1) { throw new PdbException( "Segment is {0}, not 1.", proc.seg ); } if(proc.parent != 0 || proc.next != 0) { throw new PdbException( "Warning parent={0}, next={1}", proc.parent, proc.next ); } if(proc.dbgStart != 0 || proc.dbgEnd != 0) { throw new PdbException( "Warning DBG start={0}, end={1}", proc.dbgStart, proc.dbgEnd ); } int scopeCount; int slotCount; CountScopesAndSlots( bits, proc.end, out scopeCount, out slotCount ); Scopes = new PdbScope[scopeCount]; int scope = 0; while(bits.Position < proc.end) { ushort siz = bits.ReadUInt16(); ArrayReader subBits = bits.CreateSubsetAndAdvance( siz ); SYM rec = (SYM)subBits.ReadUInt16(); switch(rec) { case SYM.S_OEM: { // 0x0404 OemSymbol oem; oem.idOem = subBits.ReadGuid (); oem.typind = subBits.ReadUInt32(); // public byte[] rgl; // user data, force 4-byte alignment if(oem.idOem == msilMetaData) { Metadata = subBits.ReadUInt8Array( subBits.Length - subBits.Position ); } else { throw new PdbException( "OEM section: guid={0} ti={1}", oem.idOem, oem.typind ); // bits.Position = stop; } } break; case SYM.S_BLOCK32: { BlockSym32 block = new BlockSym32(); block.parent = subBits.ReadUInt32(); block.end = subBits.ReadUInt32(); block.len = subBits.ReadUInt32(); block.off = subBits.ReadUInt32(); block.seg = subBits.ReadUInt16(); block.name = subBits.ReadZeroTerminatedUTF8String(); Scopes[scope++] = new PdbScope( block, bits, out SlotToken ); bits.Position = (int)block.end; } break; case SYM.S_UNAMESPACE: break; case SYM.S_END: break; default: throw new PdbException( "Unknown SYM: {0}", rec ); } } if(bits.Position != proc.end) { throw new PdbException( "Not at S_END" ); } ushort esiz = bits.ReadUInt16(); ushort erec = bits.ReadUInt16(); if(erec != (ushort)SYM.S_END) { throw new PdbException( "Missing S_END" ); } } public bool FindOffset( uint offset , out PdbSource resFile , out PdbLine resLine ) { foreach(PdbLines lineBlock in LineBlocks) { foreach(PdbLine line in lineBlock.Lines) { if(line.Offset == offset) { resFile = lineBlock.File; resLine = line; return true; } } } resFile = null; resLine = new PdbLine(); return false; } public void CollectSlots( List list ) { foreach(PdbScope scope in Scopes) { scope.CollectSlots( list ); } } //--// internal static void CountScopesAndSlots( ArrayReader bits , uint limit , out int scopes , out int slots ) { BlockSym32 block; slots = 0; scopes = 0; int pos = bits.Position; while(bits.Position < limit) { ushort siz = bits.ReadUInt16(); ArrayReader subBits = bits.CreateSubsetAndAdvance( siz ); SYM rec = (SYM)subBits.ReadUInt16(); switch(rec) { case SYM.S_BLOCK32: { block.parent = subBits.ReadUInt32(); block.end = subBits.ReadUInt32(); scopes++; bits.Position = (int)block.end; } break; case SYM.S_MANSLOT: slots++; break; } } bits.Position = pos; } //--// internal class PdbFunctionsByAddress : IComparer { public int Compare( PdbFunction fx , PdbFunction fy ) { if(fx.Segment < fy.Segment) { return -1; } else if(fx.Segment > fy.Segment) { return 1; } else if(fx.Address < fy.Address) { return -1; } else if(fx.Address > fy.Address) { return 1; } else { return 0; } } } internal class PdbFunctionsByToken : IComparer { public int Compare( PdbFunction fx , PdbFunction fy ) { if(fx.Token < fy.Token) { return -1; } else if(fx.Token > fy.Token) { return 1; } else { return 0; } } } } } ================================================ FILE: Zelig/Zelig/CompileTime/MetaData/Importer/PDBInfo/PdbLine.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // // // Originally from the Microsoft Research Singularity code base. // namespace Microsoft.Zelig.MetaData.Importer.PdbInfo { using System; using System.Collections; using System.Collections.Generic; using Microsoft.Zelig.MetaData.Importer.PdbInfo.CodeView; using Microsoft.Zelig.MetaData.Importer.PdbInfo.Features; public struct PdbLine { public uint Offset; public uint LineBegin; public uint LineEnd; public ushort ColumnBegin; public ushort ColumnEnd; public PdbLine( uint offset , uint lineBegin , uint lineEnd , ushort colBegin , ushort colEnd ) { this.Offset = offset; this.LineBegin = lineBegin; this.LineEnd = lineEnd; this.ColumnBegin = colBegin; this.ColumnEnd = colEnd; } public override string ToString() { System.Text.StringBuilder sb = new System.Text.StringBuilder(); sb.AppendFormat( "Off:{0} [{1}:{2} - {3}:{4}]", this.Offset, this.LineBegin, this.ColumnBegin, this.LineEnd, this.ColumnEnd ); return sb.ToString(); } } } ================================================ FILE: Zelig/Zelig/CompileTime/MetaData/Importer/PDBInfo/PdbLines.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // // // Originally from the Microsoft Research Singularity code base. // namespace Microsoft.Zelig.MetaData.Importer.PdbInfo { using System; using System.Collections; using System.Collections.Generic; using Microsoft.Zelig.MetaData.Importer.PdbInfo.CodeView; using Microsoft.Zelig.MetaData.Importer.PdbInfo.Features; public class PdbLines { // // State // public PdbSource File; public PdbLine[] Lines; // // Constructor Methods // public PdbLines( PdbSource file , uint count ) { this.File = file; this.Lines = new PdbLine[count]; } } } ================================================ FILE: Zelig/Zelig/CompileTime/MetaData/Importer/PDBInfo/PdbReader.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // // // Originally from the Microsoft Research Singularity code base. // namespace Microsoft.Zelig.MetaData.Importer.PdbInfo { using System; using System.Collections; using System.Collections.Generic; using Microsoft.Zelig.MetaData.Importer.PdbInfo.CodeView; public class PdbReader { // // State // private readonly ArrayReader m_image; private readonly int m_pageSize; // // Constructor Methods // public PdbReader( ArrayReader image , int pageSize ) { m_image = image; m_pageSize = pageSize; } // // Helper Methods // public void Seek( int page , int offset ) { m_image.SeekAbsolute( page * m_pageSize + offset ); } public void Read( byte[] bytes , int offset , int count ) { m_image.CopyIntoArray( bytes, offset, count ); } public int PagesFromSize( int size ) { return (size + m_pageSize - 1) / (m_pageSize); } public ArrayReader Image { get { return m_image; } } public int PageSize { get { return m_pageSize; } } } } ================================================ FILE: Zelig/Zelig/CompileTime/MetaData/Importer/PDBInfo/PdbScope.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // // // Originally from the Microsoft Research Singularity code base. // namespace Microsoft.Zelig.MetaData.Importer.PdbInfo { using System; using System.Collections; using System.Collections.Generic; using Microsoft.Zelig.MetaData.Importer.PdbInfo.CodeView; using Microsoft.Zelig.MetaData.Importer.PdbInfo.Features; public class PdbScope { // // State // public PdbSlot[] Slots; public PdbScope[] Scopes; public uint Segment; public uint Address; public uint Length; // // Constructor Methods // internal PdbScope( BlockSym32 block , ArrayReader bits , out uint typind ) { this.Segment = block.seg; this.Address = block.off; this.Length = block.len; typind = 0; int scopeCount; int slotCount; PdbFunction.CountScopesAndSlots( bits, block.end, out scopeCount, out slotCount ); Scopes = new PdbScope[scopeCount]; Slots = new PdbSlot [slotCount]; int scope = 0; int slot = 0; while(bits.Position < block.end) { ushort siz = bits.ReadUInt16(); ArrayReader subBits = bits.CreateSubsetAndAdvance( siz ); SYM rec = (SYM)subBits.ReadUInt16(); switch(rec) { case SYM.S_BLOCK32: { BlockSym32 sub = new BlockSym32(); sub.parent = subBits.ReadUInt32(); sub.end = subBits.ReadUInt32(); sub.len = subBits.ReadUInt32(); sub.off = subBits.ReadUInt32(); sub.seg = subBits.ReadUInt16(); sub.name = subBits.ReadZeroTerminatedUTF8String(); Scopes[scope++] = new PdbScope( sub, bits, out typind ); bits.Position = (int)sub.end; break; } case SYM.S_MANSLOT: Slots[slot++] = new PdbSlot( subBits, out typind ); break; case SYM.S_END: case SYM.S_UNAMESPACE: case SYM.S_MANCONSTANT: break; default: throw new PdbException( "Unknown SYM in scope {0}", rec ); // bits.Position = stop; } } if(bits.Position != block.end) { throw new PdbException( "Not at S_END" ); } ushort esiz = bits.ReadUInt16(); ushort erec = bits.ReadUInt16(); if(erec != (ushort)SYM.S_END) { throw new PdbException( "Missing S_END" ); } } internal void CollectSlots( List list ) { foreach(PdbSlot slot in Slots) { list.Add( slot ); } foreach(PdbScope scope in Scopes) { scope.CollectSlots( list ); } } } } ================================================ FILE: Zelig/Zelig/CompileTime/MetaData/Importer/PDBInfo/PdbSlot.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // // // Originally from the Microsoft Research Singularity code base. // namespace Microsoft.Zelig.MetaData.Importer.PdbInfo { using System; using System.Collections; using System.Collections.Generic; using Microsoft.Zelig.MetaData.Importer.PdbInfo.CodeView; using Microsoft.Zelig.MetaData.Importer.PdbInfo.Features; public class PdbSlot { // // State // public uint Slot; public string Name; public ushort Flags; public uint Segment; public uint Address; // // Constructor Methods // internal PdbSlot( ArrayReader bits , out uint typind ) { AttrSlotSym slot; slot.index = bits.ReadUInt32(); slot.typind = bits.ReadUInt32(); slot.offCod = bits.ReadUInt32(); slot.segCod = bits.ReadUInt16(); slot.flags = bits.ReadUInt16(); slot.name = bits.ReadZeroTerminatedUTF8String(); this.Slot = slot.index; this.Name = slot.name; this.Flags = slot.flags; this.Segment = slot.segCod; this.Address = slot.offCod; typind = slot.typind; } } } ================================================ FILE: Zelig/Zelig/CompileTime/MetaData/Importer/PDBInfo/PdbSource.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // // // Originally from the Microsoft Research Singularity code base. // namespace Microsoft.Zelig.MetaData.Importer.PdbInfo { using System; using System.Collections; using System.Collections.Generic; using Microsoft.Zelig.MetaData.Importer.PdbInfo.CodeView; using Microsoft.Zelig.MetaData.Importer.PdbInfo.Features; public class PdbSource { // // State // public uint Index; public string Name; // // Constructor Methods // public PdbSource( uint index , string name ) { this.Index = index; this.Name = name; } } } ================================================ FILE: Zelig/Zelig/CompileTime/MetaData/Importer/PDBInfo/PdbStream.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // // // Originally from the Microsoft Research Singularity code base. // namespace Microsoft.Zelig.MetaData.Importer.PdbInfo { using System; using System.Collections; using System.Collections.Generic; using Microsoft.Zelig.MetaData.Importer.PdbInfo.CodeView; using Microsoft.Zelig.MetaData.Importer.PdbInfo.Features; public class PdbStream { // // State // private int m_ver; private int m_sig; private int m_age; private Guid m_guid; private Dictionary< string, int > m_lookupStream = new Dictionary< string, int >(); // // Constructor Methods // public PdbStream( ArrayReader bits ) { m_ver = bits.ReadInt32(); // 0..3 Version m_sig = bits.ReadInt32(); // 4..7 Signature m_age = bits.ReadInt32(); // 8..11 Age m_guid = bits.ReadGuid(); // 12..27 GUID if(m_ver != 20000404) { throw new PdbException( "Unsupported PDB Stream version: {0}", m_ver ); } // Read string buffer. int stringBufLen = bits.ReadInt32(); // 28..31 Bytes of Strings ArrayReader stringBits = bits.CreateSubsetAndAdvance( stringBufLen ); // Read map index. int cnt = bits.ReadInt32(); // n+0..3 hash size. int max = bits.ReadInt32(); // n+4..7 maximum ni. BitSet present = new BitSet( bits ); BitSet deleted = new BitSet( bits ); if(!deleted.IsEmpty) { throw new PdbException( "Unsupported PDB deleted bitset is not empty." ); } int j = 0; for(int i = 0; i < max; i++) { if(present.IsSet( i )) { int ns = bits.ReadInt32(); int ni = bits.ReadInt32(); stringBits.Position = ns; string name = stringBits.ReadZeroTerminatedUTF8String(); SetStreamNumber( name, ni ); j++; } } if(j != cnt) { throw new PdbException( "Stream count mismatch" ); } } // // Helper Methods // public int GetStreamNumber( string name ) { int res; if(m_lookupStream.TryGetValue( name, out res ) == false) { return -1; } return res; } public void SetStreamNumber( string name , int idx ) { m_lookupStream[name] = idx; } public void Emit( ArrayWriter writer ) { writer.Write( m_ver ); // 0..3 Version writer.Write( m_sig ); // 4..7 Signature writer.Write( m_age ); // 8..11 Age writer.Write( m_guid ); // 12..27 GUID var lookupOffset = new Dictionary< string, int >(); var subWriter = new ArrayWriter(); BitSet present = new BitSet( 0 ); BitSet deleted = new BitSet( 0 ); int cnt = 0; int max = 0; // // Streams should be sorted by index. // var lst = new List< KeyValuePair< string, int > >( m_lookupStream ); lst.Sort( delegate( KeyValuePair< string, int > x, KeyValuePair< string, int > y ) { return x.Value.CompareTo( y.Value ); } ); foreach(var pair in lst) { var name = pair.Key; if(lookupOffset.ContainsKey( name ) == false) { lookupOffset[name] = subWriter.Length; subWriter.WriteZeroTerminatedUTF8String( name ); } present.Set( cnt++ ); max = Math.Max( max, m_lookupStream[name] ); } // Write string buffer. writer.Write( subWriter.Length ); // 28..31 Bytes of Strings writer.Write( subWriter ); // Write map index. writer.Write( cnt ); // n+0..3 hash size. writer.Write( max ); // n+4..7 maximum ni. present.Emit( writer ); deleted.Emit( writer ); foreach(var pair in lst) { writer.Write( lookupOffset[pair.Key ] ); writer.Write( pair.Value ); } writer.Write( (int)0 ); } } } ================================================ FILE: Zelig/Zelig/CompileTime/MetaData/Importer/PDBInfo/PdbWriter.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // // // Originally from the Microsoft Research Singularity code base. // namespace Microsoft.Zelig.MetaData.Importer.PdbInfo { using System; using System.Collections; using System.Collections.Generic; using Microsoft.Zelig.MetaData.Importer.PdbInfo.CodeView; using Microsoft.Zelig.MetaData.Importer.PdbInfo.Features; public class PdbWriter { // // State // private ArrayWriter m_writer; private int m_pageSize; private int m_usedBytes; // // Constructor Methods // public PdbWriter( ArrayWriter writer , int pageSize ) { m_writer = writer; m_pageSize = pageSize; m_usedBytes = pageSize * 3; } // // Helper Methods // public void Emit( MsfDirectory dir ) { PdbFileHeader head = new PdbFileHeader( m_pageSize ); dir.Emit( this, out head.directoryRoot, out head.directorySize ); WriteFreeMap(); head.freePageMap = 2; head.pagesUsed = m_usedBytes / m_pageSize; Seek( 0, 0 ); head.Emit( m_writer ); } private void WriteDirectory( DataStream[] streams , out int directoryRoot , out int directorySize ) { int pages = 0; foreach(DataStream stream in streams) { if(stream.Length > 0) { pages += stream.NumOfPages; } } ArrayWriter writer = new ArrayWriter(); writer.Write( streams.Length ); foreach(DataStream stream in streams) { writer.Write( stream.Length ); } foreach(DataStream stream in streams) { if(stream.Length > 0) { writer.Write( stream.Pages ); } } DataStream directory = new DataStream(); directory.Write( this, writer ); directorySize = directory.Length; //--// ArrayWriter writer2 = new ArrayWriter(); writer2.Write( directory.Pages ); DataStream ddir = new DataStream(); ddir.Write( this, writer2 ); directoryRoot = ddir.Pages[0]; } private void WriteFreeMap() { byte[] buffer = new byte[m_pageSize]; // We configure the old free map with only the first 3 pages allocated. buffer[0] = 0xF8; for(int i = 1; i < m_pageSize; i++) { buffer[i] = 0xff; } Seek ( 1, 0 ); Write( buffer, 0, m_pageSize ); // We configure the new free map with all of the used pages gone. int count = m_usedBytes / m_pageSize; int full = count / 8; for(int i = 0; i < full; i++) { buffer[i] = 0; } int rema = count % 8; buffer[full] = (byte)(0xff << rema); Seek ( 2 , 0 ); Write( buffer, 0, m_pageSize ); } internal int AllocatePages( int count ) { int begin = m_usedBytes; m_usedBytes += count * m_pageSize; m_writer.SetLength( m_usedBytes ); if(m_usedBytes > m_pageSize * m_pageSize * 8) { throw new Exception( "PdbWriter does not support multiple free maps." ); } return begin / m_pageSize; } internal void Seek( int page , int offset ) { m_writer.Seek( page * m_pageSize + offset ); } internal void Write( byte[] bytes , int offset , int count ) { m_writer.Write( bytes, offset, count ); } // // Access Methods // public int PageSize { get { return m_pageSize; } } } } ================================================ FILE: Zelig/Zelig/CompileTime/MetaData/Importer/PELoader.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // // // Originally based on the Bartok code base. // using System; using System.Collections.Generic; using System.Text; namespace Microsoft.Zelig.MetaData.Importer { public sealed class PELoader { // // State // private String m_path; private byte[] m_peImage; private DOSHeader m_dosHeader; private NTHeader m_ntHeader; private COMHeader m_comHeader; private SectionHeader[] m_sectionArray; // // Constructor Methods // public PELoader( String path , byte[] peImage ) { m_path = path; m_peImage = peImage; loadPEHeaders(); } // // Access Methods // internal ArrayReader getStream() { return new ArrayReader( m_peImage ); } internal int getEntryPoint() { return m_comHeader.entryPointToken; } internal int getMetaDataOffset() { return this.VaToOffset( m_comHeader.metaData.virtualAddress ); } internal int getMetaDataSize() { return m_comHeader.metaData.size; } internal int getResourceOffset() { return this.VaToOffsetSafe( m_comHeader.resources.virtualAddress ); } internal int getRelocationOffset() { int limit = m_ntHeader.numberOfSections; for(int i = 0; i < limit; i++) { SectionHeader section = m_sectionArray[i]; if(section.name.StartsWith( ".reloc" )) { return this.VaToOffset( section.virtualAddress ); } } return 0; } internal int getVtableFixupOffset() { return this.VaToOffsetSafe( m_comHeader.vtableFixups.virtualAddress ); } internal int getDelayIATOffset() { return this.VaToOffsetSafe( m_ntHeader.dataDirectory[DirectoryEntry.DELAYLOADIMPORTADDRESSTABLE].virtualAddress ); } internal long getImageBase() { return m_ntHeader.imageBase; } internal int getResourceSize() { return m_comHeader.resources.size; } internal int getVtableFixupSize() { return m_comHeader.vtableFixups.size; } internal int getDelayIATSize() { return m_ntHeader.dataDirectory[DirectoryEntry.DELAYLOADIMPORTADDRESSTABLE].size; } internal bool IsExecutableImage() { return ((m_ntHeader.characteristics & NTHeader.IMAGE_FILE_EXECUTABLE_IMAGE) != 0) && ((m_ntHeader.characteristics & NTHeader.IMAGE_FILE_DLL ) == 0); } // Output Routines public void DumpHeader( LogWriter outputStream ) { outputStream.WriteLine( "// DOS Header:" ); outputStream.WriteLine(); m_dosHeader.DumpLimitedToStream( outputStream ); outputStream.WriteLine( "// PE Header:" ); outputStream.WriteLine(); m_ntHeader.DumpLimitedToStream( outputStream ); this.DumpIAT( outputStream, "Import directory" , m_ntHeader.dataDirectory[DirectoryEntry.IMPORT ] ); this.DumpIAT( outputStream, "Import Address Table" , m_ntHeader.dataDirectory[DirectoryEntry.IMPORTADDRESSTABLE ] ); this.DumpIAT( outputStream, "Delay Load Import Address Table", m_ntHeader.dataDirectory[DirectoryEntry.DELAYLOADIMPORTADDRESSTABLE] ); m_comHeader.DumpHeader( outputStream ); } internal void DumpCodeManager( LogWriter outputStream ) { outputStream.WriteLine( "// Code Manager Table" ); if(m_comHeader.codeManagerTable.size == 0) { outputStream.WriteLine( "// default" ); return; } // BUGBUG throw new NotYetImplemented( "DumpCodeManager" ); } internal void DumpVTables( LogWriter outputStream ) { outputStream.WriteLine( "// VTableFixup Directory:" ); if(m_comHeader.vtableFixups.virtualAddress == 0) { outputStream.WriteLine( "// No data." ); return; } // BUGBUG throw new NotYetImplemented( "DumpVTables" ); } internal void DumpEATTable( LogWriter outputStream ) { outputStream.WriteLine( "// Export Address Table Jumps:" ); if(m_comHeader.exportAddressTableJumps.virtualAddress == 0) { outputStream.WriteLine( "// No data." ); return; } // BUGBUG throw new NotYetImplemented( "DumpEATTable" ); } internal void DumpStatistics( LogWriter outputStream ) { throw new NotYetImplemented( "DumpStatistics" ); } public override String ToString() { return "PELoader(" + m_path + ")"; } // // Private Helper Methods // private void loadPEHeaders() { ArrayReader reader = new ArrayReader( m_peImage ); m_dosHeader = new DOSHeader( reader ); reader.Position = m_dosHeader.lfanew; m_ntHeader = new NTHeader( reader ); // Load the sections int sectionCount = m_ntHeader.numberOfSections; SectionHeader[] sectionArray = new SectionHeader[sectionCount]; m_sectionArray = sectionArray; for(int i = 0; i < sectionCount; i++) { m_sectionArray[i] = new SectionHeader( reader ); int startAddr = sectionArray[i].virtualAddress; int endAddr = sectionArray[i].virtualAddress + sectionArray[i].sizeOfRawData; int delta = sectionArray[i].pointerToRawData - sectionArray[i].virtualAddress; } // Load the COM/COR20 header DirectoryEntry entry = m_ntHeader.dataDirectory[DirectoryEntry.CLRHEADER]; int comOffset = this.VaToOffsetSafe( entry.virtualAddress ); if(comOffset == -1) { throw new MissingCLRheaderException( "Missing CLR header in " + m_path ); } reader.Position = comOffset; m_comHeader = new COMHeader( reader ); } internal int VaToOffset( int virtualAddress ) { int result = VaToOffsetSafe( virtualAddress ); if(result == -1) { throw new IllegalPEFormatException( "Unknown VA " + virtualAddress ); } return result; } internal int VaToOffsetSafe( int virtualAddress ) { int limit = m_ntHeader.numberOfSections; for(int i = 0; i < limit; i++) { SectionHeader section = m_sectionArray[i]; if(virtualAddress >= section.virtualAddress && virtualAddress < (section.virtualAddress + section.sizeOfRawData)) { return (virtualAddress - section.virtualAddress + section.pointerToRawData); } } return -1; } private void DumpIAT( LogWriter outputStream , String title , DirectoryEntry entry ) { outputStream.WriteLine( "// " + title ); if(entry.size == 0) { outputStream.WriteLine( "// No data." ); outputStream.WriteLine(); return; } if(entry.size < ImportDescriptor.SIZE) { outputStream.WriteLine( "Not enough data for IMAGE_IMPORT_DESCRIPTOR" ); return; } int importOffset = this.VaToOffset( entry.virtualAddress ); ArrayReader reader = new ArrayReader( m_peImage ); while(true) { reader.Position = importOffset; ImportDescriptor importDescriptor = new ImportDescriptor( reader ); if(importDescriptor.firstChunk == 0) { return; } String name = null; if(importDescriptor.name != 0) { int nameOffset = this.VaToOffset( importDescriptor.name ); reader.Position = nameOffset; name = reader.ReadZeroTerminatedUInt8String(); } outputStream.WriteLine( "// " + name ); importDescriptor.DumpToStream( outputStream ); outputStream.WriteLine( "//" ); int importTableOffset = this.VaToOffset( importDescriptor.firstChunk ); while(true) { reader.Position = importTableOffset; int importTableID = reader.ReadInt32(); if(importTableID == 0) { break; } outputStream.WriteLine( "importTableID is " + importTableID.ToString( "x" ) ); outputStream.Flush(); int nameStringOffset = this.VaToOffset( importTableID & 0x7fffffff ); reader.Position = nameStringOffset; if((importTableID & 0x8000000) != 0) { outputStream.WriteLine( "// " + reader.ReadInt16().ToString( "x8" ) + " by ordinal " + (importTableID & 0x7ffffff) ); } else { outputStream.WriteLine( "// " + reader.ReadInt16().ToString( "x8" ) + " " + reader.ReadZeroTerminatedUInt8String() ); } importTableOffset += 4; } outputStream.WriteLine(); importOffset += ImportDescriptor.SIZE; } } internal Section[] loadSections() { ArrayReader reader = new ArrayReader( m_peImage ); Section[] sections = new Section[m_sectionArray.Length]; for(int i = 0; i < m_sectionArray.Length; i++) { Section section = new Section( m_sectionArray[i] ); section.LoadSection( this, reader ); sections[i] = section; } return sections; } // Nested classes internal class DOSHeader { // Corresponds to the WinNT IMAGE_DOS_HEADER data structure internal const short IMAGE_DOS_SIGNATURE = 0x5A4D; // // State // internal short magic; // Magic number internal short cblp; // Bytes on last page of file internal short cp; // Pages in file internal short crlc; // Relocations internal short cparhdr; // Size of header in paragraphs internal short minalloc; // Minimum extra paragraphs needed internal short maxalloc; // Maximum extra paragraphs needed internal short ss; // Initial (relative) SS value internal short sp; // Initial SP value internal short csum; // Checksum internal short ip; // Initial IP value internal short cs; // Initial (relative) CS value internal short lfarlc; // File address of relocation table internal short ovno; // Overlay number internal short res_0; // Reserved words internal short res_1; internal short res_2; internal short res_3; internal short oemid; // OEM identifier (for e_oeminfo) internal short oeminfo; // OEM information; e_oemid specific internal short res2_0; // Reserved words internal short res2_1; internal short res2_2; internal short res2_3; internal short res2_4; internal short res2_5; internal short res2_6; internal short res2_7; internal short res2_8; internal short res2_9; internal int lfanew; // File address of new exe header // // Constructor Methods // internal DOSHeader( ArrayReader reader ) { // We could just read the magic and lfanew fields, but let's read everything for now this.magic = reader.ReadInt16(); this.cblp = reader.ReadInt16(); this.cp = reader.ReadInt16(); this.crlc = reader.ReadInt16(); this.cparhdr = reader.ReadInt16(); this.minalloc = reader.ReadInt16(); this.maxalloc = reader.ReadInt16(); this.ss = reader.ReadInt16(); this.sp = reader.ReadInt16(); this.csum = reader.ReadInt16(); this.ip = reader.ReadInt16(); this.cs = reader.ReadInt16(); this.lfarlc = reader.ReadInt16(); this.ovno = reader.ReadInt16(); this.res_0 = reader.ReadInt16(); this.res_1 = reader.ReadInt16(); this.res_2 = reader.ReadInt16(); this.res_3 = reader.ReadInt16(); this.oemid = reader.ReadInt16(); this.oeminfo = reader.ReadInt16(); this.res2_0 = reader.ReadInt16(); this.res2_1 = reader.ReadInt16(); this.res2_2 = reader.ReadInt16(); this.res2_3 = reader.ReadInt16(); this.res2_4 = reader.ReadInt16(); this.res2_5 = reader.ReadInt16(); this.res2_6 = reader.ReadInt16(); this.res2_7 = reader.ReadInt16(); this.res2_8 = reader.ReadInt16(); this.res2_9 = reader.ReadInt16(); this.lfanew = reader.ReadInt32(); // Verify that we have a correct DOS header and a valid // pointer to the NT header if(this.magic != DOSHeader.IMAGE_DOS_SIGNATURE || this.lfanew <= 0) { throw new IllegalPEFormatException( "DOS header problems" ); } } // Output Routines internal void DumpLimitedToStream( LogWriter outputStream ) { outputStream.WriteLine( "// Magic: {0:X2}", this.magic ); // TODO: More here } } internal class NTHeader { // Corresponds to the WinNT IMAGE_NT_HEADERS data structure internal const int IMAGE_NT_SIGNATURE = 0x00004550; // PE00 internal const short IMAGE_SIZEOF_NT_OPTIONAL32_HEADER = 224; internal const short IMAGE_SIZEOF_NT_OPTIONAL32PLUS_HEADER = 240; internal const short IMAGE_NT_OPTIONAL_HDR32_MAGIC = 0x010B; internal const short IMAGE_NT_OPTIONAL_HDR32PLUS_MAGIC = 0x020B; internal const short IMAGE_FILE_EXECUTABLE_IMAGE = 0x0002; // File is executable (i.e. no unresolved external references). internal const short IMAGE_FILE_DLL = 0x2000; // File is a DLL. // // State // internal int signature; // IMAGE_FILE_HEADER internal short machine; internal short numberOfSections; internal int timeDateStamp; internal int pointerToSymbolTable; internal int numberOfSymbols; internal short sizeOfOptionalHeader; internal short characteristics; // IMAGE_OPTIONAL_HEADER32 internal short magic; internal Byte majorLinkerVersion; internal Byte minorLinkerVersion; internal int sizeOfCode; internal int sizeOfInitializedData; internal int sizeOfUninitializedData; internal int addressOfEntryPoint; internal int baseOfCode; private int baseOfData; //this is not used on x64 internal long imageBase; internal int sectionAlignment; internal int fileAlignment; internal short majorOperatingSystemVersion; internal short minorOperatingSystemVersion; internal short majorImageVersion; internal short minorImageVersion; internal short majorSubsystemVersion; internal short minorSubsystemVersion; internal int win32VersionValue; internal int sizeOfImage; internal int sizeOfHeaders; internal int checkSum; internal short subsystem; internal short dllCharacteristics; internal long sizeOfStackReserve; internal long sizeOfStackCommit; internal long sizeOfHeapReserve; internal long sizeOfHeapCommit; internal int loaderFlags; internal int numberOfRvaAndSizes; // IMAGE_DATA_DIRECTORY internal DirectoryEntry[] dataDirectory; //whether or not image is PE32+ (determined from magic number) internal bool isPe32Plus; // // Constructor Methods // internal NTHeader( ArrayReader reader ) { // We could read a selection of these, but read every // field for now. this.signature = reader.ReadInt32(); this.machine = reader.ReadInt16(); this.numberOfSections = reader.ReadInt16(); this.timeDateStamp = reader.ReadInt32(); this.pointerToSymbolTable = reader.ReadInt32(); this.numberOfSymbols = reader.ReadInt32(); this.sizeOfOptionalHeader = reader.ReadInt16(); this.characteristics = reader.ReadInt16(); this.magic = reader.ReadInt16(); this.isPe32Plus = (magic == NTHeader.IMAGE_NT_OPTIONAL_HDR32PLUS_MAGIC); this.majorLinkerVersion = reader.ReadUInt8(); this.minorLinkerVersion = reader.ReadUInt8(); this.sizeOfCode = reader.ReadInt32(); this.sizeOfInitializedData = reader.ReadInt32(); this.sizeOfUninitializedData = reader.ReadInt32(); this.addressOfEntryPoint = reader.ReadInt32(); this.baseOfCode = reader.ReadInt32(); if(!this.isPe32Plus) { this.baseOfData = reader.ReadInt32(); } else { this.baseOfData = 0; } this.imageBase = readIntPtr( reader ); this.sectionAlignment = reader.ReadInt32(); this.fileAlignment = reader.ReadInt32(); this.majorOperatingSystemVersion = reader.ReadInt16(); this.minorOperatingSystemVersion = reader.ReadInt16(); this.majorImageVersion = reader.ReadInt16(); this.minorImageVersion = reader.ReadInt16(); this.majorSubsystemVersion = reader.ReadInt16(); this.minorSubsystemVersion = reader.ReadInt16(); this.win32VersionValue = reader.ReadInt32(); this.sizeOfImage = reader.ReadInt32(); this.sizeOfHeaders = reader.ReadInt32(); this.checkSum = reader.ReadInt32(); this.subsystem = reader.ReadInt16(); this.dllCharacteristics = reader.ReadInt16(); this.sizeOfStackReserve = readIntPtr( reader ); this.sizeOfStackCommit = readIntPtr( reader ); this.sizeOfHeapReserve = readIntPtr( reader ); this.sizeOfHeapCommit = readIntPtr( reader ); this.loaderFlags = reader.ReadInt32(); int count = reader.ReadInt32(); this.numberOfRvaAndSizes = count; DirectoryEntry[] directoryArray = new DirectoryEntry[count]; this.dataDirectory = directoryArray; for(int i = 0; i < count; i++) { directoryArray[i] = new DirectoryEntry( reader ); } int iSizeOfOptionalHeader = this.isPe32Plus ? NTHeader.IMAGE_SIZEOF_NT_OPTIONAL32PLUS_HEADER : NTHeader.IMAGE_SIZEOF_NT_OPTIONAL32_HEADER; int iMagic = this.isPe32Plus ? NTHeader.IMAGE_NT_OPTIONAL_HDR32PLUS_MAGIC : NTHeader.IMAGE_NT_OPTIONAL_HDR32_MAGIC; // Verify that we have a valid NT header if(this.signature != NTHeader.IMAGE_NT_SIGNATURE || this.sizeOfOptionalHeader != iSizeOfOptionalHeader || this.magic != iMagic || this.numberOfRvaAndSizes != 16 ) { throw new IllegalPEFormatException( "NT header problems" ); } } // Output Routines internal void DumpLimitedToStream( LogWriter outputStream ) { outputStream.WriteLine( "// Subsystem: {0:X8}", this.subsystem ); outputStream.WriteLine( "// Native entry point address: {0:X8}", this.addressOfEntryPoint ); outputStream.WriteLine( "// Image base: {0:X8}", this.imageBase ); outputStream.WriteLine( "// Section alignment: {0:X8}", this.sectionAlignment ); outputStream.WriteLine( "// File alignment: {0:X8}", this.fileAlignment ); outputStream.WriteLine( "// Stack reserve size: {0:X8}", this.sizeOfStackReserve ); outputStream.WriteLine( "// Stack commit size: {0:X8}", this.sizeOfStackCommit ); outputStream.WriteLine( "// Directories: {0:X8}", this.numberOfRvaAndSizes ); this.dataDirectory[DirectoryEntry.EXPORT ].DumpToStream( outputStream, "of Export directory " ); this.dataDirectory[DirectoryEntry.IMPORT ].DumpToStream( outputStream, "of Import directory" ); this.dataDirectory[DirectoryEntry.RESOURCE ].DumpToStream( outputStream, "of Resource directory" ); this.dataDirectory[DirectoryEntry.EXCEPTION ].DumpToStream( outputStream, "of Exception directory" ); this.dataDirectory[DirectoryEntry.SECURITY ].DumpToStream( outputStream, "of Security directory" ); this.dataDirectory[DirectoryEntry.BASERELOCATIONTABLE ].DumpToStream( outputStream, "of Base Relocation Table" ); this.dataDirectory[DirectoryEntry.DEBUG ].DumpToStream( outputStream, "of Debug directory" ); this.dataDirectory[DirectoryEntry.ARCHITECTURE ].DumpToStream( outputStream, "of Architecture specific" ); this.dataDirectory[DirectoryEntry.GLOBALPOINTER ].DumpToStream( outputStream, "of Global pointer directory" ); this.dataDirectory[DirectoryEntry.TLS ].DumpToStream( outputStream, "of TLS directory " ); this.dataDirectory[DirectoryEntry.LOADCONFIG ].DumpToStream( outputStream, "of Load config directory" ); this.dataDirectory[DirectoryEntry.BOUNDIMPORT ].DumpToStream( outputStream, "of Bound import directory" ); this.dataDirectory[DirectoryEntry.IMPORTADDRESSTABLE ].DumpToStream( outputStream, "of Import Address Table" ); this.dataDirectory[DirectoryEntry.DELAYLOADIMPORTADDRESSTABLE].DumpToStream( outputStream, "of Delay Load IAT" ); this.dataDirectory[DirectoryEntry.CLRHEADER ].DumpToStream( outputStream, "of CLR Header" ); } private long readIntPtr( ArrayReader reader ) { if(this.isPe32Plus) { return reader.ReadInt64(); } else { return (long)reader.ReadInt32(); } } } internal struct DirectoryEntry { internal const int EXPORT = 0; internal const int IMPORT = 1; internal const int RESOURCE = 2; internal const int EXCEPTION = 3; internal const int SECURITY = 4; internal const int BASERELOCATIONTABLE = 5; internal const int DEBUG = 6; internal const int ARCHITECTURE = 7; internal const int GLOBALPOINTER = 8; internal const int TLS = 9; internal const int LOADCONFIG = 10; internal const int BOUNDIMPORT = 11; internal const int IMPORTADDRESSTABLE = 12; internal const int DELAYLOADIMPORTADDRESSTABLE = 13; internal const int CLRHEADER = 14; // // State // internal int virtualAddress; internal int size; // // Constructor Methods // internal DirectoryEntry( ArrayReader reader ) { this.virtualAddress = reader.ReadInt32(); this.size = reader.ReadInt32(); } // Output Routines internal void DumpToStream( LogWriter outputStream , String suffix ) { outputStream.WriteLine( "// {0:X8} [{1:X8}] {2}", this.virtualAddress, this.size, suffix ); } } public class Section { // // State // public SectionHeader header; byte[] rawData; // // Constructor Methods // public Section( SectionHeader header ) { this.header = header; } public void LoadSection( PELoader peLoader , ArrayReader reader ) { reader.Position = peLoader.VaToOffset( header.virtualAddress ); this.rawData = reader.ReadUInt8Array( header.sizeOfRawData ); } } public class SectionHeader { // // State // public String name; public int virtualSize; public int virtualAddress; public int sizeOfRawData; public int pointerToRawData; public int pointerToRelocations; public int pointerToLinenumbers; public short numberOfRelocations; public short numberOfLinenumbers; public int characteristics; // // Constructor Methods // public SectionHeader( ArrayReader reader ) { char[] chars = new char[8]; for(int j = 0; j < 8; j++) { chars[j] = (char)reader.ReadUInt8(); } this.name = new String( chars ); this.virtualSize = reader.ReadInt32(); this.virtualAddress = reader.ReadInt32(); this.sizeOfRawData = reader.ReadInt32(); this.pointerToRawData = reader.ReadInt32(); this.pointerToRelocations = reader.ReadInt32(); this.pointerToLinenumbers = reader.ReadInt32(); this.numberOfRelocations = reader.ReadInt16(); this.numberOfLinenumbers = reader.ReadInt16(); this.characteristics = reader.ReadInt32(); } } internal class COMHeader { // // State // // Corresponds to the WinNT IMAGE_COR20_HEADER data structure // Header Versioning internal int cb; internal short majorRuntimeVersion; internal short minorRuntimeVersion; // Symbol table and startup information internal DirectoryEntry metaData; internal int flags; internal int entryPointToken; // Binding information internal DirectoryEntry resources; internal DirectoryEntry strongNameSignature; // Regular fixup and binding information internal DirectoryEntry codeManagerTable; internal DirectoryEntry vtableFixups; internal DirectoryEntry exportAddressTableJumps; // Managed Native Code internal DirectoryEntry managedNativeHeader; // // Constructor Methods // internal COMHeader( ArrayReader reader ) { this.cb = reader.ReadInt32(); this.majorRuntimeVersion = reader.ReadInt16(); this.minorRuntimeVersion = reader.ReadInt16(); this.metaData = new DirectoryEntry( reader ); this.flags = reader.ReadInt32(); this.entryPointToken = reader.ReadInt32(); this.resources = new DirectoryEntry( reader ); this.strongNameSignature = new DirectoryEntry( reader ); this.codeManagerTable = new DirectoryEntry( reader ); this.vtableFixups = new DirectoryEntry( reader ); this.exportAddressTableJumps = new DirectoryEntry( reader ); this.managedNativeHeader = new DirectoryEntry( reader ); // Verify that we have a valid header if(this.majorRuntimeVersion == 1 || this.majorRuntimeVersion > 2) { throw new IllegalPEFormatException( "COM header problems" ); } } internal void DumpHeader( LogWriter outputStream ) { outputStream.WriteLine( "// CLR Header:" ); outputStream.WriteLine( "// {0:X8} Header size" , this.cb ); outputStream.WriteLine( "// {0:X4} Major runtime version" , this.majorRuntimeVersion ); outputStream.WriteLine( "// {0:X4} Minor runtime version" , this.minorRuntimeVersion ); outputStream.WriteLine( "// {0:X8} Flags" , this.flags ); outputStream.WriteLine( "// {0:X8} Entrypoint token" , this.entryPointToken ); outputStream.WriteLine( "// {0:X8} [{1:X8}] address [size] of Metadata directory" , this.metaData .virtualAddress, this.metaData .size ); outputStream.WriteLine( "// {0:X8} [{1:X8}] address [size] of Resources directory" , this.resources .virtualAddress, this.resources .size ); outputStream.WriteLine( "// {0:X8} [{1:X8}] address [size] of Strong name signature" , this.strongNameSignature .virtualAddress, this.strongNameSignature .size ); outputStream.WriteLine( "// {0:X8} [{1:X8}] address [size] of CodeManager table" , this.codeManagerTable .virtualAddress, this.codeManagerTable .size ); outputStream.WriteLine( "// {0:X8} [{1:X8}] address [size] of VTableFixups directory", this.vtableFixups .virtualAddress, this.vtableFixups .size ); outputStream.WriteLine( "// {0:X8} [{1:X8}] address [size] of Export address table" , this.exportAddressTableJumps.virtualAddress, this.exportAddressTableJumps.size ); outputStream.WriteLine( "// {0:X8} [{1:X8}] address [size] of Precompile header" , this.managedNativeHeader .virtualAddress, this.managedNativeHeader .size ); } } internal class ImportDescriptor { // Size of this structure in stream internal const int SIZE = 20; // // State // internal int characteristics; internal int timeDateStamp; internal int forwarderChain; internal int name; internal int firstChunk; // // Constructor Methods // internal ImportDescriptor( ArrayReader reader ) { this.characteristics = reader.ReadInt32(); this.timeDateStamp = reader.ReadInt32(); this.forwarderChain = reader.ReadInt32(); this.name = reader.ReadInt32(); this.firstChunk = reader.ReadInt32(); } internal void DumpToStream( LogWriter outputStream ) { outputStream.WriteLine( "// {0:X8} Import Address Table" , this.firstChunk ); outputStream.WriteLine( "// {0:X8} Import Name Table" , this.name ); outputStream.WriteLine( "// {0:X8} time date stamp" , this.timeDateStamp ); outputStream.WriteLine( "// {0:X8} characteristics" , this.characteristics ); outputStream.WriteLine( "// {0:X8} index of first forwarder reference", this.forwarderChain ); } } public class IllegalPEFormatException : Exception { // // Constructor Methods // internal IllegalPEFormatException( String reason ) : base( reason ) { } } public class MissingCLRheaderException : Exception { // // Constructor Methods // internal MissingCLRheaderException( String reason ) : base( reason ) { } } public class NotYetImplemented : Exception { // // Constructor Methods // internal NotYetImplemented( String reason ) : base( reason ) { } } } } ================================================ FILE: Zelig/Zelig/CompileTime/MetaData/Importer/Parser.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // // // Originally based on the Bartok code base. // using System; using System.Collections.Generic; using System.Collections; using System.Reflection; using System.Text; namespace Microsoft.Zelig.MetaData.Importer { public class Parser { internal delegate int IndexReader( ArrayReader reader ); internal class TableSchema { // // State // internal readonly int m_rows; internal ArrayReader m_reader; internal int m_rowSize; internal ColumnSchema[] m_columns; // // Constructor Methods // internal TableSchema( int rows ) { m_rows = rows; } } internal class ColumnSchema { // // State // internal byte m_size; internal byte m_offset; internal IndexReader m_reader; } //--// // // Same secondary tables don't have a pointer to the primary table (FieldDef, MethodDef, ParamDef, Event, and Property). // // This generic builds a lookup table as the primary table is parsed. // class ReverseListLookup { // // State // int currentIndex; T current; T[] list; // // Constructor Methods // internal ReverseListLookup( int count ) { this.currentIndex = 0; this.list = new T[count]; } internal void Add( T item , int index ) { index--; while(this.currentIndex < index) { this.list[this.currentIndex++] = this.current; } this.current = item; } internal void Complete() { while(this.currentIndex < this.list.Length) { this.list[this.currentIndex++] = this.current; } } internal T Get( int index ) { index--; return list[index]; } } //--// private const int METAMODEL_MAJOR_VER_A = 1; private const int METAMODEL_MINOR_VER_A1 = 0; private const int METAMODEL_MINOR_VER_A2 = 1; private const int METAMODEL_MAJOR_VER_B = 2; private const int METAMODEL_MINOR_VER_B = 0; private const int HEAPBITS_MASK_STRINGS = 0x01; private const int HEAPBITS_MASK_GUID = 0x02; private const int HEAPBITS_MASK_BLOB = 0x04; private const int HEAPBITS_MASK_PADDING_BIT = 0x08; private const int HEAPBITS_MASK_DELTA_ONLY = 0x20; private const int HEAPBITS_MASK_EXTRA_DATA = 0x40; private const int HEAPBITS_MASK_HAS_DELETE = 0x80; private static readonly byte[][] TableColumnKinds = new byte[(int)TokenType.Count][] { // rModuleCols new byte[] { (byte) ColumnKindId.UShort, (byte) ColumnKindId.String, (byte) ColumnKindId.Guid, (byte) ColumnKindId.Guid, (byte) ColumnKindId.Guid }, // rTypeRefCols new byte[] { (byte) ColumnKindId.CodedToken + (byte) CodeToken.ResolutionScope, (byte) ColumnKindId.String, (byte) ColumnKindId.String }, // rTypeDefCols new byte[] { (byte) ColumnKindId.ULong, (byte) ColumnKindId.String, (byte) ColumnKindId.String, (byte) ColumnKindId.CodedToken + (byte) CodeToken.TypeDefOrRef, (byte) TokenType.Field, (byte) TokenType.Method }, // rFieldPtrCols null, // Not Supported ////new byte[] ////{ //// (byte) TokenType.Field ////}, // rFieldCols new byte[] { (byte) ColumnKindId.UShort, (byte) ColumnKindId.String, (byte) ColumnKindId.Blob }, // rMethodPtrCols null, // Not Supported ////new byte[] ////{ //// (byte) TokenType.Method ////}, // rMethodCols new byte[] { (byte) ColumnKindId.ULong, (byte) ColumnKindId.UShort, (byte) ColumnKindId.UShort, (byte) ColumnKindId.String, (byte) ColumnKindId.Blob, (byte) TokenType.Param }, // rParamPtrCols null, // Not Supported ////new byte[] ////{ //// (byte) TokenType.Param ////}, // rParamCols new byte[] { (byte) ColumnKindId.UShort, (byte) ColumnKindId.UShort, (byte) ColumnKindId.String }, // rInterfaceImplCols new byte[] { (byte) TokenType.TypeDef, (byte) ColumnKindId.CodedToken + (byte) CodeToken.TypeDefOrRef }, // rMemberRefCols new byte[] { (byte) ColumnKindId.CodedToken + (byte) CodeToken.MemberRefParent, (byte) ColumnKindId.String, (byte) ColumnKindId.Blob }, // rConstantCols new byte[] { (byte) ColumnKindId.Byte, (byte) ColumnKindId.CodedToken + (byte) CodeToken.HasConstant, (byte) ColumnKindId.Blob }, // rCustomAttributeCols new byte[] { (byte) ColumnKindId.CodedToken + (byte) CodeToken.HasCustomAttribute, (byte) ColumnKindId.CodedToken + (byte) CodeToken.CustomAttributeType, (byte) ColumnKindId.Blob }, // rFieldMarshalCols new byte[] { (byte) ColumnKindId.CodedToken + (byte) CodeToken.HasFieldMarshal, (byte) ColumnKindId.Blob }, // rDeclSecurityCols new byte[] { (byte) ColumnKindId.Short, (byte) ColumnKindId.CodedToken + (byte) CodeToken.HasDeclSecurity, (byte) ColumnKindId.Blob }, // rClassLayoutCols new byte[] { (byte) ColumnKindId.UShort, (byte) ColumnKindId.ULong, (byte) TokenType.TypeDef }, // rFieldLayoutCols new byte[] { (byte) ColumnKindId.ULong, (byte) TokenType.Field }, // rStandAloneSigCols new byte[] { (byte) ColumnKindId.Blob }, // rEventMapCols new byte[] { (byte) TokenType.TypeDef, (byte) TokenType.Event }, // rEventPtrCols null, // Not Supported ////new byte[] ////{ //// (byte) TokenType.Event ////}, // rEventCols new byte[] { (byte) ColumnKindId.UShort, (byte) ColumnKindId.String, (byte) ColumnKindId.CodedToken + (byte) CodeToken.TypeDefOrRef }, // rPropertyMapCols new byte[] { (byte) TokenType.TypeDef, (byte) TokenType.Property }, // rPropertyPtrCols null, // Not Supported ////new byte[] ////{ //// (byte) TokenType.Property ////}, // rPropertyCols new byte[] { (byte) ColumnKindId.UShort, (byte) ColumnKindId.String, (byte) ColumnKindId.Blob }, // rMethodSemanticsCols new byte[] { (byte) ColumnKindId.UShort, (byte) TokenType.Method, (byte) ColumnKindId.CodedToken + (byte) CodeToken.HasSemantic }, // rMethodImplCols new byte[] { (byte) TokenType.TypeDef, (byte) ColumnKindId.CodedToken + (byte) CodeToken.MethodDefOrRef, (byte) ColumnKindId.CodedToken + (byte) CodeToken.MethodDefOrRef }, // rModuleRefCols new byte[] { (byte) ColumnKindId.String }, // rTypeSpecCols new byte[] { (byte) ColumnKindId.Blob }, // rImplMapCols new byte[] { (byte) ColumnKindId.UShort, (byte) ColumnKindId.CodedToken + (byte) CodeToken.MemberForwarded, (byte) ColumnKindId.String, (byte) TokenType.ModuleRef }, // rFieldRVACols new byte[] { (byte) ColumnKindId.ULong, (byte) TokenType.Field }, // rENCLogCols null, // Not Supported ////new byte[] ////{ //// (byte) ColumnKindId.ULong, //// (byte) ColumnKindId.ULong ////}, // rENCMapCols null, // Not Supported ////new byte[] ////{ //// (byte) ColumnKindId.ULong ////}, // rAssemblyCols new byte[] { (byte) ColumnKindId.ULong, (byte) ColumnKindId.UShort, (byte) ColumnKindId.UShort, (byte) ColumnKindId.UShort, (byte) ColumnKindId.UShort, (byte) ColumnKindId.ULong, (byte) ColumnKindId.Blob, (byte) ColumnKindId.String, (byte) ColumnKindId.String }, // rAssemblyProcessorCols new byte[] { (byte) ColumnKindId.ULong }, // rAssemblyOSCols new byte[] { (byte) ColumnKindId.ULong, (byte) ColumnKindId.ULong, (byte) ColumnKindId.ULong }, // rAssemblyRefCols new byte[] { (byte) ColumnKindId.UShort, (byte) ColumnKindId.UShort, (byte) ColumnKindId.UShort, (byte) ColumnKindId.UShort, (byte) ColumnKindId.ULong, (byte) ColumnKindId.Blob, (byte) ColumnKindId.String, (byte) ColumnKindId.String, (byte) ColumnKindId.Blob }, // rAssemblyRefProcessorCols new byte[] { (byte) ColumnKindId.ULong, (byte) TokenType.AssemblyRef }, // rAssemblyRefOSCols new byte[] { (byte) ColumnKindId.ULong, (byte) ColumnKindId.ULong, (byte) ColumnKindId.ULong, (byte) TokenType.AssemblyRef }, // rFileCols new byte[] { (byte) ColumnKindId.ULong, (byte) ColumnKindId.String, (byte) ColumnKindId.Blob }, // rExportedTypeCols new byte[] { (byte) ColumnKindId.ULong, (byte) ColumnKindId.ULong, (byte) ColumnKindId.String, (byte) ColumnKindId.String, (byte) ColumnKindId.CodedToken + (byte) CodeToken.Implementation }, // rManifestResourceCols new byte[] { (byte) ColumnKindId.ULong, (byte) ColumnKindId.ULong, (byte) ColumnKindId.String, (byte) ColumnKindId.CodedToken + (byte) CodeToken.Implementation }, // rNestedClassCols new byte[] { (byte) TokenType.TypeDef, (byte) TokenType.TypeDef }, // rGenericParamCols new byte[] { (byte) ColumnKindId.UShort, (byte) ColumnKindId.UShort, (byte) ColumnKindId.CodedToken + (byte) CodeToken.TypeOrMethodDef, (byte) ColumnKindId.String, }, // rMethodSpecCols new byte[] { (byte) ColumnKindId.CodedToken + (byte) CodeToken.MethodDefOrRef, (byte) ColumnKindId.Blob }, // rGenericParamConstraintCols new byte[] { (byte) ColumnKindId.CodedToken + (byte) CodeToken.GenericParam, (byte) ColumnKindId.CodedToken + (byte) CodeToken.TypeDefOrRef }, }; // These are for informational use only! Not used anywhere. private static readonly String[][] TableColumnNames = new String[(int)TokenType.Count][] { // rModuleColNames new String[] { "Generation", "Name", "Mvid", "EncId", "EncBaseId" }, // rTypeRefColNames new String[] { "ResolutionScope", "Name", "Namespace" }, // rTypeDefColNames new String[] { "Flags", "Name", "Namespace", "Extends", "FieldList", "MethodList" }, // rFieldPtrColNames new String[] { "Field" }, // rFieldColNames new String[] { "Flags", "Name", "Signature" }, // rMethodPtrColNames new String[] { "Method" }, // rMethodColNames new String[] { "RVA", "ImplFlags", "Flags", "Name", "Signature", "ParamList" }, // rParamPtrColNames new String[] { "Param" }, // rParamColNames new String[] { "Flags", "Sequence", "Name" }, // rInterfaceImplColNames new String[] { "Class", "Interface" }, // rMemberRefColNames new String[] { "Class", "Name", "Signature" }, // rConstantColNames new String[] { "Type", "Parent", "Value" }, // rCustomAttributeColNames new String[] { "Parent", "Type", "Value" }, // rFieldMarshalColNames new String[] { "Parent", "NativeType" }, // rDeclSecurityColNames new String[] { "Action", "Parent", "PermissionSet" }, // rClassLayoutColNames new String[] { "PackingSize", "ClassSize", "Parent" }, // rFieldLayoutColNames new String[] { "OffSet", "Field" }, // rStandAloneSigColNames new String[] { "Signature" }, // rEventMapColNames new String[] { "Parent", "EventList" }, // rEventPtrColNames new String[] { "Event" }, // rEventColNames new String[] { "EventFlags", "Name", "EventType" }, // rPropertyMapColNames new String[] { "Parent", "PropertyList" }, // rPropertyPtrColNames new String[] { "Property" }, // rPropertyColNames new String[] { "PropFlags", "Name", "Type" }, // rMethodSemanticsColNames new String[] { "Semantic", "Method", "Association" }, // rMethodImplColNames new String[] { "Class", "MethodBody", "MethodDeclaration" }, // rModuleRefColNames new String[] { "Name" }, // rTypeSpecColNames new String[] { "Signature" }, // rImplMapColNames new String[] { "MappingFlags", "MemberForwarded", "ImportName", "ImportScope" }, // rFieldRVAColNames new String[] { "RVA", "Field" }, // rENCLogColNames new String[] { "Token", "FuncCode" }, // rENCMapColNames new String[] { "Token" }, // rAssemblyColNames new String[] { "HashAlgId", "MajorVersion", "MinorVersion", "BuildNumber", "RevisionNumber", "Flags", "PublicKey", "Name", "Locale" }, // rAssemblyProcessorColNames new String[] { "Processor" }, // rAssemblyOSColNames new String[] { "OSPlatformId", "OSMajorVersion", "OSMinorVersion" }, // rAssemblyRefColNames new String[] { "MajorVersion", "MinorVersion", "BuildNumber", "RevisionNumber", "Flags", "PublicKeyOrToken", "Name", "Locale", "HashValue" }, // rAssemblyRefProcessorColNames new String[] { "Processor", "AssemblyRef" }, // rAssemblyRefOSColNames new String[] { "OSPlatformId", "OSMajorVersion", "OSMinorVersion", "AssemblyRef" }, // rFileColNames new String[] { "Flags", "Name", "HashValue" }, // rExportedTypeColNames new String[] { "Flags", "TypeDefId", "TypeName", "TypeNamespace", "Implementation" }, // rManifestResourceColNames new String[] { "Offset", "Flags", "Name", "Implementation" }, // rNestedClassColNames new String[] { "NestedClass", "EnclosingClass" }, // rGenericParamColNames new String[] { "Number", "Flags", "Owner", "Name" }, // rMethodSpecNames new String[] { "Method", "Instantiation" }, // rGenericParamConstraintColNames new String[] { "Owner", "Constraint" }, }; private static readonly int[] BitsForCountArray = new int[] { 0,1,1,2,2,3,3,3,3,4,4,4,4,4,4,4,4,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5 }; private static readonly int[] MaskForCountArray = new int[] { 0,1,1,3,3,7,7,7,7,0xF,0xF,0xF,0xF,0xF,0xF,0xF,0xF,0x1F,0x1F,0x1F, 0x1F,0x1F,0x1F,0x1F,0x1F,0x1F,0x1F,0x1F,0x1F,0x1F,0x1F,0x1F,0x1F }; private static readonly TokenType[][] CodeTokenTypeLists = new TokenType[(int)CodeToken.Count][] { // TypeDefOrRef new TokenType[] { TokenType.TypeDef, TokenType.TypeRef, TokenType.TypeSpec }, // HasConstant new TokenType[] { TokenType.FieldDef, TokenType.ParamDef, TokenType.Property }, // HasCustomAttribute new TokenType[] { TokenType.MethodDef, TokenType.FieldDef, TokenType.TypeRef, TokenType.TypeDef, TokenType.ParamDef, TokenType.InterfaceImpl, TokenType.MemberRef, TokenType.Module, TokenType.Permission, TokenType.Property, TokenType.Event, TokenType.Signature, TokenType.ModuleRef, TokenType.TypeSpec, TokenType.Assembly, TokenType.AssemblyRef, TokenType.File, TokenType.ExportedType, TokenType.ManifestResource}, // HasFieldMarshal new TokenType[] { TokenType.FieldDef, TokenType.ParamDef }, // HasDeclSecurity new TokenType[] { TokenType.TypeDef, TokenType.MethodDef, TokenType.Assembly }, // MemberRefParent new TokenType[] { TokenType.Illegal, TokenType.TypeRef, TokenType.ModuleRef, TokenType.MethodDef, TokenType.TypeSpec }, // HasSemantic new TokenType[] { TokenType.Event, TokenType.Property }, // MethodDefOrRef new TokenType[] { TokenType.MethodDef, TokenType.MemberRef }, // MemberForwarded new TokenType[] { TokenType.FieldDef, TokenType.MethodDef }, // Implementation new TokenType[] { TokenType.File, TokenType.AssemblyRef, TokenType.ExportedType }, // CustomAttributeType new TokenType[] { TokenType.Illegal, TokenType.Illegal, TokenType.MethodDef, TokenType.MemberRef, TokenType.Illegal }, // ResolutionScope new TokenType[] { TokenType.Module, TokenType.ModuleRef, TokenType.AssemblyRef, TokenType.TypeRef }, // TypeOrMethodDef new TokenType[] { TokenType.TypeDef, TokenType.MethodDef }, // GenericParam new TokenType[] { TokenType.GenericParam }, }; protected enum MetaDataFormat : byte { Invalid , ReadOnly , ReadWrite, ICR } private enum ColumnKindId { RowIdMax = 63, CodedToken = 64, CodedTokenMax = 95, Short = 96, UShort = 97, Long = 98, ULong = 99, Byte = 100, String = 101, Guid = 102, Blob = 103 }; // // Section 24.2.6 of ECMA spec, Partition II // private enum CodeToken : byte { TypeDefOrRef , // TypeDef, TypeRef, TypeSpec HasConstant , // FieldDef, ParamDef, Property HasCustomAttribute , // Every table except CustomAttribute HasFieldMarshal , // FieldDef, ParamDef HasDeclSecurity , // TypeDef, MethodDef, Assembly MemberRefParent , // TypeRef, ModuleRef, MethodDef, TypeSpec HasSemantic , // Event, Property MethodDefOrRef , // MethodDef, MethodRef MemberForwarded , // FieldDef, MethodDef Implementation , // File, AssemblyRef, ExportedType CustomAttributeType, // MethodDef, MethodRef ResolutionScope , // Module, ModuleRef, AssemblyRef, TypeRef TypeOrMethodDef , // TypeDef, MethodDef GenericParam , // GenericParam Count }; // // State // private readonly ISymbolResolverHelper symbolHelper; private readonly PELoader peLoader; private readonly ArrayReader imageReader; private readonly ArrayReader metaDataReader; private readonly StorageStream dataStream; private readonly StorageStream stringPoolStream; private readonly StorageStream userBlobPoolStream; private readonly StorageStream guidPoolStream; private readonly StorageStream blobPoolStream; // Schema fields (for logical tables) private int reserved; private byte majorVersion; private byte minorVersion; private byte heapBits; private byte rowId; private long maskValid; private long maskSorted; private int extraData; //--// private TableSchema[] schemaArray = new TableSchema[(int)TokenType.Count]; private byte stringIndexSize; private byte guidIndexSize; private byte blobIndexSize; private ArrayReader stringStreamReader; private ArrayReader blobStreamReader; private ArrayReader userStringStreamReader; private ArrayReader resourceReader; private Guid[] guidArray; private MetaData metaDataObject; private ReverseListLookup lookup_fieldIndexToType; private ReverseListLookup lookup_methodIndexToType; private ReverseListLookup lookup_eventIndexToType; private ReverseListLookup lookup_propertyIndexToType; private ReverseListLookup lookup_paramIndexToMethod; // // Constructor Methods // internal Parser( String name , ISymbolResolverHelper symbolHelper , PELoader peLoader , MetaDataLoaderFlags flags ) { int metaDataOffset = peLoader.getMetaDataOffset(); int metaDataSize = peLoader.getMetaDataSize (); this.symbolHelper = symbolHelper; this.peLoader = peLoader; this.imageReader = peLoader.getStream(); this.metaDataReader = new ArrayReader( this.imageReader, metaDataOffset, metaDataSize ); this.metaDataObject = new MetaData( name ); StorageSignature storageSignature = new StorageSignature( this.metaDataReader ); StorageHeader storageHeader = new StorageHeader ( this.metaDataReader ); // The pointer is at the first stream in the list MetaDataFormat format = MetaDataFormat.Invalid; // Lightning/Src/MD/Runtime/MDInternalDisp.cpp for(int i = 0; i < storageHeader.streamCount; i++) { StorageStream storageStream = new StorageStream( this.metaDataReader ); switch(storageStream.name) { case StorageStream.COMPRESSED_MODEL: if(format == MetaDataFormat.Invalid || format == MetaDataFormat.ICR) { format = MetaDataFormat.ReadOnly; this.dataStream = storageStream; } break; case StorageStream.ENC_MODEL: if(format == MetaDataFormat.Invalid || format == MetaDataFormat.ICR) { format = MetaDataFormat.ReadWrite; this.dataStream = storageStream; } break; case StorageStream.SCHEMA: if(format == MetaDataFormat.Invalid) { format = MetaDataFormat.ICR; this.dataStream = storageStream; } break; case StorageStream.STRING_POOL: this.stringPoolStream = storageStream; break; case StorageStream.BLOB_POOL: this.blobPoolStream = storageStream; break; case StorageStream.USER_BLOB_POOL: this.userBlobPoolStream = storageStream; break; case StorageStream.VARIANT_POOL: // It doesn't look like we are using this stream, ever break; case StorageStream.GUID_POOL: this.guidPoolStream = storageStream; break; default: throw IllegalMetaDataFormatException.Create( "Unknown stream name '{0}'", storageStream.name ); } } if(format != MetaDataFormat.ReadOnly) { throw IllegalMetaDataFormatException.Create( "Unsupported format: {0}", format ); } this.LoadStreams(); this.LoadMethods( flags ); this.metaDataObject.m_entryPoint = (MetaDataMethod)this.getObjectFromToken( peLoader.getEntryPoint() ); this.metaDataObject.m_imageBase = peLoader.getImageBase(); } // // Helper Methods // private void LoadStreams() { this.metaDataReader.Rewind(); // Read the stream of GUIDs { ArrayReader reader = new ArrayReader( this.metaDataReader, guidPoolStream.offset, guidPoolStream.size ); const int sizeOfGuid = 16; int guidCount = guidPoolStream.size / sizeOfGuid; this.guidArray = new Guid[guidCount]; for(int i = 0; i < guidCount; i++) { this.guidArray[i] = new Guid( reader.ReadUInt8Array( sizeOfGuid ) ); } } // Read the stream of strings if(this.stringPoolStream != null && this.stringPoolStream.size > 0) { this.stringStreamReader = new ArrayReader( this.metaDataReader, stringPoolStream.offset, stringPoolStream.size ); } // Read the stream of blobs if(this.blobPoolStream != null && this.blobPoolStream.size > 0) { this.blobStreamReader = new ArrayReader( this.metaDataReader, blobPoolStream.offset, blobPoolStream.size ); } // Read the stream of user strings, if there is one if(this.userBlobPoolStream != null && this.userBlobPoolStream.size > 0) { this.userStringStreamReader = new ArrayReader( this.metaDataReader, userBlobPoolStream.offset, userBlobPoolStream.size ); } // Read the resource data, if there is any { int resourceOffset = peLoader.getResourceOffset(); int resourceSize = peLoader.getResourceSize(); if(resourceOffset > 0 && resourceSize > 0) { this.resourceReader = new ArrayReader( this.peLoader.getStream(), resourceOffset, resourceSize ); } } // Read the schema { ArrayReader reader = new ArrayReader( this.metaDataReader, dataStream.offset, dataStream.size ); // First read the fixed fields (CMiniMdSchemaBase) this.ReadSchemaBase( reader ); // Read the variable fields (this is the compressed part) int count = (int)TokenType.Count; long mask = this.maskValid; for(int dst = 0; dst < count; dst++) { this.schemaArray[dst] = new TableSchema( (mask & 1) != 0 ? reader.ReadInt32() : 0 ); mask >>= 1; } // Skip the counters we don't understand for(int dst = count; dst < 64; dst++) { if((mask & 1) != 0) { reader.Seek( 4 ); } mask >>= 1; } // Retrieve any extra data if((this.heapBits & HEAPBITS_MASK_EXTRA_DATA) != 0) { this.extraData = reader.ReadInt32(); } if((this.majorVersion != METAMODEL_MAJOR_VER_A || (this.minorVersion != METAMODEL_MINOR_VER_A1 && this.minorVersion != METAMODEL_MINOR_VER_A2) ) && (this.majorVersion != METAMODEL_MAJOR_VER_B || this.minorVersion != METAMODEL_MINOR_VER_B ) ) { throw IllegalMetaDataFormatException.Create( "Unknown version {0}.{1}", this.majorVersion, this.minorVersion ); } // Compute the width of all the coded tokens this.InitializeRowInfo(); // Read the data into the tables this.InitializeMetaDataTables( reader ); } } //--// private void ReadSchemaBase( ArrayReader reader ) { this.reserved = reader.ReadInt32(); // Must be zero this.majorVersion = reader.ReadUInt8(); // Version numbers this.minorVersion = reader.ReadUInt8(); this.heapBits = reader.ReadUInt8(); // Bits for heap sizes this.rowId = reader.ReadUInt8(); // log-base-2 of largest rid this.maskValid = reader.ReadInt64(); // Present table counts this.maskSorted = reader.ReadInt64(); // Sorted tables if(this.reserved != 0) { throw IllegalMetaDataFormatException.Create( "Reserved not zero" ); } } private void InitializeRowInfo() { IndexReader reader1 = new IndexReader( ReadIndexUInt8 ); IndexReader reader2 = new IndexReader( ReadIndexUInt16 ); IndexReader reader4 = new IndexReader( ReadIndexUInt32 ); this.stringIndexSize = (byte)(((this.heapBits & HEAPBITS_MASK_STRINGS) != 0) ? 4 : 2); this.guidIndexSize = (byte)(((this.heapBits & HEAPBITS_MASK_GUID ) != 0) ? 4 : 2); this.blobIndexSize = (byte)(((this.heapBits & HEAPBITS_MASK_BLOB ) != 0) ? 4 : 2); for(int tableIndex = 0; tableIndex < (int)TokenType.Count; tableIndex++) { byte[] columnKinds = TableColumnKinds[tableIndex]; if(columnKinds != null) { int columnCount = columnKinds.Length; ColumnSchema[] columns = new ColumnSchema[columnCount]; this.schemaArray[tableIndex].m_columns = columns; byte columnOffset = 0; // Running size of record for(int columnIndex = 0; columnIndex < columnCount; columnIndex++) { byte columnKind = columnKinds[columnIndex]; byte columnSize; if(columnKind <= (byte)ColumnKindId.RowIdMax) { if(this.schemaArray[columnKind].m_rows > 0xFFFF) { columnSize = 4; } else { columnSize = 2; } } else if(columnKind <= (byte)ColumnKindId.CodedTokenMax) { byte codeToken = (byte)(columnKind - (byte)ColumnKindId.CodedToken); TokenType[] tokenTypeList = CodeTokenTypeLists[codeToken]; int maxCount = 0; int listLength = tokenTypeList.Length; for(int i = 0; i < listLength; i++) { TokenType tokenType = tokenTypeList[i]; // Ignore string tokens if(tokenType != TokenType.Illegal) { int index = (int)tokenType; if(this.schemaArray[index].m_rows > maxCount) { maxCount = this.schemaArray[index].m_rows; } } } int maxIndex = maxCount << BitsForCountArray[listLength]; if(maxIndex > 0xFFFF) { columnSize = 4; } else { columnSize = 2; } } else { switch((ColumnKindId)columnKind) { case ColumnKindId.Byte: columnSize = 1; break; case ColumnKindId.Short: case ColumnKindId.UShort: columnSize = 2; break; case ColumnKindId.Long: case ColumnKindId.ULong: columnSize = 4; break; case ColumnKindId.String: columnSize = this.stringIndexSize; break; case ColumnKindId.Guid: columnSize = this.guidIndexSize; break; case ColumnKindId.Blob: columnSize = this.blobIndexSize; break; default: throw IllegalMetaDataFormatException.Create( "Unexpected schema kind: {0}", columnKind ); } } // Save away the size and offset ColumnSchema cs = new ColumnSchema(); cs.m_size = columnSize; cs.m_offset = columnOffset; switch(columnSize) { case 1: cs.m_reader = reader1; break; case 2: cs.m_reader = reader2; break; case 4: cs.m_reader = reader4; break; default: throw IllegalMetaDataFormatException.Create( "Unexpected schema size: {0}", columnSize ); } columns[columnIndex] = cs; // Align to 2 bytes columnSize += (byte)(columnSize & 1); columnOffset += columnSize; } this.schemaArray[tableIndex].m_rowSize = columnOffset; } else { if(this.schemaArray[tableIndex].m_rows != 0) { throw IllegalMetaDataFormatException.Create( "Unsupported table: {0}", (TokenType)tableIndex ); } } } } private void InitializeMetaDataTables( ArrayReader reader ) { int count = (int)TokenType.Count; this.metaDataObject.m_tables = new MetaDataObject[count][]; // Create all the readers for the different tables. for(int i = 0; i < count; i++) { TableSchema ts = this.schemaArray[i]; ts.m_reader = reader.CreateSubsetAndAdvance( ts.m_rows * ts.m_rowSize ); } // Parse what goes in the tables this.parseAssemblyRefTable (); this.parseModuleRefTable (); this.parseTypeRefTable (); this.parseAssemblyTable (); this.parseModuleTable (); this.parseFileTable (); this.parseManifestResourceTable (); this.parseTypeSpecTable (); this.parseTypeDefTable (); this.parseClassLayoutTable (); this.parseNestedClassTable (); this.parseInterfaceImplTable (); this.parseMemberRefTable (); this.parseFieldTable (); this.parseMethodTable (); this.parseMethodImplTable (); this.parseImplMapTable (); this.parseParamTable (); this.parseEventMapTable (); this.parseEventTable (); this.parsePropertyMapTable (); this.parsePropertyTable (); this.parseMethodSemanticsTable (); this.parseConstantTable (); this.parseFieldMarshalTable (); this.parseFieldRVATable (); this.parseFieldLayoutTable (); this.parseCustomAttributeTable (); this.parseDeclSecurityTable (); this.parseGenericParamTable (); this.parseGenericParamConstraintTable(); this.parseMethodSpecTable (); this.parseStandAloneSigTable (); } //--// private void LoadMethods( MetaDataLoaderFlags flags ) { PdbInfo.PdbFile pdbFile = null; if((flags & MetaDataLoaderFlags.LoadCode ) != 0 && (flags & MetaDataLoaderFlags.LoadDebugInfo) != 0 ) { if(symbolHelper != null) { pdbFile = symbolHelper.ResolveAssemblySymbols( this.metaDataObject.m_name ); } } foreach(MetaDataMethod method in this.metaDataObject.m_methodArray) { if((flags & MetaDataLoaderFlags.LoadCode) != 0) { PdbInfo.PdbFunction pdbFunction = null; if(pdbFile != null) { pdbFunction = pdbFile.FindFunction( (uint)method.Token ); } method.loadInstructions( this, pdbFunction ); } } } //--// private static int ReadIndexUInt8( ArrayReader reader ) { uint res = reader.ReadUInt8(); reader.Seek( 1 ); return (int)res; } private static int ReadIndexUInt16( ArrayReader reader ) { uint res = reader.ReadUInt16(); return (int)res; } private static int ReadIndexUInt32( ArrayReader reader ) { uint res = reader.ReadUInt32(); return (int)res; } //--// internal String readIndexAsString( ArrayReader reader ) { int index = (int)(this.stringIndexSize == 2 ? reader.ReadUInt16() : reader.ReadUInt32()); return this.getString( index ); } internal Guid readIndexAsGuid( ArrayReader reader ) { int index = (int)(this.guidIndexSize == 2 ? reader.ReadUInt16() : reader.ReadUInt32()); if(index == 0) return new Guid(); return this.guidArray[index-1]; } internal byte[] readIndexAsBlob( ArrayReader reader ) { int index = (int)(this.blobIndexSize == 2 ? reader.ReadUInt16() : reader.ReadUInt32()); return this.getBlobBytes( index ); } internal int readIndexAsForBlob( ArrayReader reader ) { return (int)(this.blobIndexSize == 2 ? reader.ReadUInt16() : reader.ReadUInt32()); } //--// internal String getString( int stringIndex ) { try { this.stringStreamReader.Position = stringIndex; return this.stringStreamReader.ReadZeroTerminatedUTF8String(); } catch { throw IllegalMetaDataFormatException.Create( "Cannot find string ", stringIndex ); } } //--// internal byte[] getBlobBytes( int blobIndex ) { this.blobStreamReader.Position = blobIndex; int size = (int)this.blobStreamReader.ReadCompressedUInt32(); return this.blobStreamReader.ReadUInt8Array( size ); } internal ArrayReader getSignature( int signatureIndex ) { this.blobStreamReader.Position = signatureIndex; int size = (int)this.blobStreamReader.ReadCompressedUInt32(); return this.blobStreamReader.CreateSubset( size ); } internal byte[] getResourceBytes( int offset ) { this.resourceReader.Position = offset; int size = this.resourceReader.ReadInt32(); return this.resourceReader.ReadUInt8Array( size ); } internal MarshalSpec getNativeType( int nativeTypeIndex ) { ArrayReader reader = this.getSignature( nativeTypeIndex ); return MarshalSpec.Create( reader ); } internal Guid getGuid( int guidIndex ) { try { return this.guidArray[guidIndex-1]; } catch { throw IllegalMetaDataFormatException.Create( "Cannot find GUID {0}", guidIndex ); } } private MetaDataObject getObjectFromTableSet( int codedIndex , CodeToken codeToken ) { if(codedIndex == 0) { return null; } int codeCount = CodeTokenTypeLists[(int)codeToken].Length; int kind = codedIndex & MaskForCountArray[codeCount]; int index = codedIndex >> BitsForCountArray[codeCount]; TokenType tokenType = CodeTokenTypeLists[(int)codeToken][kind]; return this.getObjectFromToken( MetaData.PackToken( tokenType, index ) ); } // // Access Methods // internal String getUserString( int stringIndex ) { this.userStringStreamReader.Position = stringIndex; int size = (int)this.userStringStreamReader.ReadCompressedUInt32(); return this.userStringStreamReader.ReadUInt16String( size / 2 ); } //--// internal IMetaDataTypeDefOrRef getTypeDefOrRef( int codedIndex ) { return (IMetaDataTypeDefOrRef)this.getObjectFromTableSet( codedIndex, CodeToken.TypeDefOrRef ); } internal IMetaDataHasConstant getHasConstant( int codedIndex ) { return (IMetaDataHasConstant)this.getObjectFromTableSet( codedIndex, CodeToken.HasConstant ); } internal IMetaDataHasCustomAttribute getHasCustomAttribute( int codedIndex ) { return (IMetaDataHasCustomAttribute)this.getObjectFromTableSet( codedIndex, CodeToken.HasCustomAttribute ); } internal IMetaDataHasFieldMarshal getHasFieldMarshal( int codedIndex ) { return (IMetaDataHasFieldMarshal)this.getObjectFromTableSet( codedIndex, CodeToken.HasFieldMarshal ); } internal IMetaDataHasDeclSecurity getHasDeclSecurity( int codedIndex ) { return (IMetaDataHasDeclSecurity)this.getObjectFromTableSet( codedIndex, CodeToken.HasDeclSecurity ); } internal IMetaDataMemberRefParent getMemberRefParent( int codedIndex ) { return (IMetaDataMemberRefParent)this.getObjectFromTableSet( codedIndex, CodeToken.MemberRefParent ); } internal IMetaDataHasSemantic getHasSemantic( int codedIndex ) { return (IMetaDataHasSemantic)this.getObjectFromTableSet( codedIndex, CodeToken.HasSemantic ); } internal IMetaDataMethodDefOrRef getMethodDefOrRef( int codedIndex ) { return (IMetaDataMethodDefOrRef)this.getObjectFromTableSet( codedIndex, CodeToken.MethodDefOrRef ); } internal IMetaDataMemberForwarded getMemberForwarded( int codedIndex ) { return (IMetaDataMemberForwarded)this.getObjectFromTableSet( codedIndex, CodeToken.MemberForwarded ); } internal IMetaDataImplementation getImplementation( int codedIndex ) { return (IMetaDataImplementation)this.getObjectFromTableSet( codedIndex, CodeToken.Implementation ); } internal IMetaDataCustomAttributeType getCustomAttributeType( int codedIndex ) { return (IMetaDataCustomAttributeType)this.getObjectFromTableSet( codedIndex, CodeToken.CustomAttributeType ); } internal IMetaDataResolutionScope getResolutionScope( int resolutionIndex ) { return (IMetaDataResolutionScope)this.getObjectFromTableSet( resolutionIndex, CodeToken.ResolutionScope ); } internal IMetaDataTypeOrMethodDef getTypeOrMethodDef( int resolutionIndex ) { return (IMetaDataTypeOrMethodDef)this.getObjectFromTableSet( resolutionIndex, CodeToken.TypeOrMethodDef ); } //--// internal MetaDataObject getObjectFromToken( int token ) { TokenType type = MetaData.UnpackTokenAsType ( token ); int index = MetaData.UnpackTokenAsIndex( token ); if(index == 0) return null; MetaDataObject[] array = this.metaDataObject.m_tables[(int)type]; if(array == null) { throw new Exception( "Missing table for " + type ); } MetaDataObject res = array[index - 1]; if(res == null) { if(type == TokenType.TypeSpec) { res = this.parseTypeSpecEntry( index ); } if(res == null) { throw new Exception( "Missing entry " + index + " in table for " + type ); } } return res; } //--// internal void SetFieldIndex( MetaDataTypeDefinition type , int fieldIndex ) { this.lookup_fieldIndexToType.Add( type, fieldIndex ); } internal void SetMethodIndex( MetaDataTypeDefinition type , int methodIndex ) { this.lookup_methodIndexToType.Add( type, methodIndex ); } internal void SetParamIndex( MetaDataMethod method , int paramIndex ) { this.lookup_paramIndexToMethod.Add( method, paramIndex ); } internal MetaDataTypeDefinition GetTypeFromFieldIndex( int fieldIndex ) { return this.lookup_fieldIndexToType.Get( fieldIndex ); } internal MetaDataTypeDefinition GetTypeFromMethodIndex( int methodIndex ) { return this.lookup_methodIndexToType.Get( methodIndex ); } internal MetaDataTypeDefinition GetTypeFromEventIndex( int eventIndex ) { return this.lookup_eventIndexToType.Get( eventIndex ); } internal MetaDataTypeDefinition GetTypeFromPropertyIndex( int propertyIndex ) { return this.lookup_propertyIndexToType.Get( propertyIndex ); } internal MetaDataMethod GetMethodFromParamIndex( int paramIndex ) { return this.lookup_paramIndexToMethod.Get( paramIndex ); } //--// // Methods for initializing the tables and table objects private TableSchema InitializeTableNoAlloc( TokenType tbl , ref T[] res ) where T : MetaDataObject { TableSchema ts = this.schemaArray[(int)tbl]; int count = ts.m_rows; T[] array = new T[count]; res = array; this.metaDataObject.m_tables[(int)tbl] = array; return ts; } private TableSchema InitializeTable( TokenType tbl , ref T[] res , MetaDataObject.CreateInstance creator ) where T : MetaDataObject { TableSchema ts = this.schemaArray[(int)tbl]; int count = ts.m_rows; T[] array = new T[count]; res = array; this.metaDataObject.m_tables[(int)tbl] = array; for(int i = 0; i < count; i++) { array[i] = (T)creator( i+1 ); } return ts; } private void InitializeTableAndLoad( TokenType tbl , ref T[] res , MetaDataObject.CreateInstance creator ) where T : MetaDataObject { TableSchema ts = InitializeTable( tbl, ref res, creator ); ArrayReader reader = ts.m_reader; reader.Rewind(); foreach(T o in res) { o.Parse( this, ts, reader ); } } private MetaDataObject parseTypeSpecEntry( int index ) { TableSchema ts = this.schemaArray[(int)TokenType.TypeSpec]; ArrayReader reader = ts.m_reader; reader.Rewind(); reader.Seek( ts.m_rowSize * (index-1) ); MetaDataTypeSpec item = (MetaDataTypeSpec)MetaDataTypeSpec.GetCreator()( index ); this.metaDataObject.m_typeSpecArray[index-1] = item; item.Parse( this, ts, reader ); return item; } //--// private T Fetch( TokenType tbl , int index , T[] array ) where T : MetaDataObject { if(index == 0) return null; if(array == null) { throw IllegalMetaDataFormatException.Create( "Forward reference to {0} {1}", tbl, index ); } T item = array[index-1]; if(item == null) { if(tbl == TokenType.TypeSpec) { item = (T)this.parseTypeSpecEntry( index ); } if(item == null) { throw IllegalMetaDataFormatException.Create( "Forward reference to {0} {1}", tbl, index ); } } return item; } internal MetaDataTypeDefinition getTypeDef( int typeDefIndex ) { return Fetch( TokenType.TypeDef, typeDefIndex, this.metaDataObject.m_typeDefArray ); } internal MetaDataField getField( int fieldIndex ) { return Fetch( TokenType.Field, fieldIndex, this.metaDataObject.m_fieldArray ); } internal MetaDataMethod getMethod( int methodIndex ) { return Fetch( TokenType.Method, methodIndex, this.metaDataObject.m_methodArray ); } internal MetaDataModuleRef getModuleRef( int moduleRefIndex ) { return Fetch( TokenType.ModuleRef, moduleRefIndex , this.metaDataObject.m_moduleRefArray ); } internal MetaDataGenericParam getGenericParam( int genericParamIndex ) { return Fetch( TokenType.GenericParam, genericParamIndex, this.metaDataObject.m_genericParamArray ); } //--// // 0x00 private void parseModuleTable() { InitializeTableAndLoad( TokenType.Module, ref this.metaDataObject.m_moduleArray, MetaDataModule.GetCreator() ); } // 0x01 private void parseTypeRefTable() { InitializeTableAndLoad( TokenType.TypeRef, ref this.metaDataObject.m_typeRefArray, MetaDataTypeReference.GetCreator() ); } // 0x02 private void parseTypeDefTable() { int fieldCount = this.schemaArray[(int)TokenType.Field ].m_rows; int methodCount = this.schemaArray[(int)TokenType.Method].m_rows; this.lookup_fieldIndexToType = new ReverseListLookup( fieldCount ); this.lookup_methodIndexToType = new ReverseListLookup( methodCount ); InitializeTableAndLoad( TokenType.TypeDef, ref this.metaDataObject.m_typeDefArray, MetaDataTypeDefinition.GetCreator() ); this.lookup_fieldIndexToType .Complete(); this.lookup_methodIndexToType.Complete(); } // 0x04 private void parseFieldTable() { InitializeTableAndLoad( TokenType.Field, ref this.metaDataObject.m_fieldArray, MetaDataField.GetCreator() ); } // 0x06 private void parseMethodTable() { int paramCount = this.schemaArray[(int)TokenType.Param].m_rows; this.lookup_paramIndexToMethod = new ReverseListLookup( paramCount ); InitializeTableAndLoad( TokenType.Method, ref this.metaDataObject.m_methodArray, MetaDataMethod.GetCreator() ); this.lookup_paramIndexToMethod.Complete(); } // 0x08 private void parseParamTable() { InitializeTableAndLoad( TokenType.Param, ref this.metaDataObject.m_paramArray, MetaDataParam.GetCreator() ); } // 0x09 private void parseInterfaceImplTable() { TableSchema ts = this.schemaArray[(int)TokenType.InterfaceImpl]; IndexReader classReader = ts.m_columns[0].m_reader; IndexReader interfaceReader = ts.m_columns[1].m_reader; for(int i = 0; i < ts.m_rows; i++) { int classIndex = classReader ( ts.m_reader ); int interfaceIndex = interfaceReader( ts.m_reader ); MetaDataTypeDefinition classObject = this.getTypeDef ( classIndex ); IMetaDataTypeDefOrRef interfaceObject = this.getTypeDefOrRef( interfaceIndex ); classObject.AddInterface( interfaceObject ); } } // 0x0A private void parseMemberRefTable() { InitializeTableAndLoad( TokenType.MemberRef, ref this.metaDataObject.m_memberRefArray, MetaDataMemberRef.GetCreator() ); } // 0x0B private void parseConstantTable() { InitializeTableAndLoad( TokenType.Constant, ref this.metaDataObject.m_constantArray, MetaDataConstant.GetCreator() ); } // 0x0C private void parseCustomAttributeTable() { InitializeTableAndLoad( TokenType.CustomAttribute, ref this.metaDataObject.m_customAttributeArray, MetaDataCustomAttribute.GetCreator() ); } // 0x0D private void parseFieldMarshalTable() { InitializeTableAndLoad( TokenType.FieldMarshal, ref this.metaDataObject.m_fieldMarshalArray, MetaDataFieldMarshal.GetCreator() ); } // 0x0E private void parseDeclSecurityTable() { InitializeTableAndLoad( TokenType.DeclSecurity, ref this.metaDataObject.m_declSecurityArray, MetaDataDeclSecurity.GetCreator() ); } // 0x0F private void parseClassLayoutTable() { InitializeTableAndLoad( TokenType.ClassLayout, ref this.metaDataObject.m_classLayoutArray, MetaDataClassLayout.GetCreator() ); } // 0x10 private void parseFieldLayoutTable() { InitializeTableAndLoad( TokenType.FieldLayout, ref this.metaDataObject.m_fieldLayoutArray, MetaDataFieldLayout.GetCreator() ); } // 0x11 private void parseStandAloneSigTable() { InitializeTableAndLoad( TokenType.StandAloneSig, ref this.metaDataObject.m_standAloneSigArray, MetaDataStandAloneSig.GetCreator() ); } // 0x12 private void parseEventMapTable() { int eventCount = this.schemaArray[(int)TokenType.Event].m_rows; this.lookup_eventIndexToType = new ReverseListLookup( eventCount ); TableSchema ts = this.schemaArray[(int)TokenType.EventMap]; IndexReader parentReader = ts.m_columns[0].m_reader; IndexReader eventListReader = ts.m_columns[1].m_reader; ArrayReader reader = ts.m_reader; for(int i = 0; i < ts.m_rows; i++) { int parentIndex = parentReader ( reader ); int eventListIndex = eventListReader( reader ); this.lookup_eventIndexToType.Add( this.getTypeDef( parentIndex ), eventListIndex ); } this.lookup_eventIndexToType.Complete(); } // 0x14 private void parseEventTable() { InitializeTableAndLoad( TokenType.Event, ref this.metaDataObject.m_eventArray, MetaDataEvent.GetCreator() ); } // 0x15 private void parsePropertyMapTable() { int propertyCount = this.schemaArray[(int)TokenType.Property].m_rows; this.lookup_propertyIndexToType = new ReverseListLookup( propertyCount ); TableSchema ts = this.schemaArray[(int)TokenType.PropertyMap]; IndexReader parentReader = ts.m_columns[0].m_reader; IndexReader propertyListReader = ts.m_columns[1].m_reader; ArrayReader reader = ts.m_reader; for(int i = 0; i < ts.m_rows; i++) { int parentIndex = parentReader ( reader ); int propertyListIndex = propertyListReader( reader ); this.lookup_propertyIndexToType.Add( this.getTypeDef( parentIndex ), propertyListIndex ); } this.lookup_propertyIndexToType.Complete(); } // 0x17 private void parsePropertyTable() { InitializeTableAndLoad( TokenType.Property, ref this.metaDataObject.m_propertyArray, MetaDataProperty.GetCreator() ); } // 0x18 private void parseMethodSemanticsTable() { InitializeTableAndLoad( TokenType.MethodSemantics, ref this.metaDataObject.m_methodSemanticsArray, MetaDataMethodSemantics.GetCreator() ); } // 0x19 private void parseMethodImplTable() { InitializeTableAndLoad( TokenType.MethodImpl, ref this.metaDataObject.m_methodImplArray, MetaDataMethodImpl.GetCreator() ); } // 0x1A private void parseModuleRefTable() { InitializeTableAndLoad( TokenType.ModuleRef, ref this.metaDataObject.m_moduleRefArray, MetaDataModuleRef.GetCreator() ); } // 0x1B private void parseTypeSpecTable() { // // TypeSpec is the exception to the rule. // Since TypeSpec can point to TypeDef and viceversa, we need to break the loop. // The entries from the TypeSpec table are parsed on demand, instead of in a batch. // InitializeTableNoAlloc( TokenType.TypeSpec, ref this.metaDataObject.m_typeSpecArray ); } // 0x1C private void parseImplMapTable() { InitializeTableAndLoad( TokenType.ImplMap, ref this.metaDataObject.m_implMapArray, MetaDataImplMap.GetCreator() ); } // 0x1D private void parseFieldRVATable() { InitializeTableAndLoad( TokenType.FieldRVA, ref this.metaDataObject.m_fieldRVAArray, MetaDataFieldRVA.GetCreator() ); } // 0x20 private void parseAssemblyTable() { InitializeTableAndLoad( TokenType.Assembly, ref this.metaDataObject.m_assemblyArray, MetaDataAssembly.GetCreator() ); if(this.metaDataObject.m_assemblyArray.Length != 1) { throw IllegalMetaDataFormatException.Create( "More than one record in the Assembly table" ); } } // 0x23 private void parseAssemblyRefTable() { InitializeTableAndLoad( TokenType.AssemblyRef, ref this.metaDataObject.m_assemblyRefArray, MetaDataAssemblyRef.GetCreator() ); } // 0x26 private void parseFileTable() { InitializeTableAndLoad( TokenType.File, ref this.metaDataObject.m_fileArray, MetaDataFile.GetCreator() ); } // 0x28 private void parseManifestResourceTable() { InitializeTableAndLoad( TokenType.ManifestResource, ref this.metaDataObject.m_manifestResourceArray, MetaDataManifestResource.GetCreator() ); } // 0x29 private void parseNestedClassTable() { TableSchema ts = this.schemaArray[(int)TokenType.NestedClass]; IndexReader nestedClassReader = ts.m_columns[0].m_reader; IndexReader enclosingClassReader = ts.m_columns[1].m_reader; ArrayReader reader = ts.m_reader; for(int i = 0; i < ts.m_rows; i++) { int nestedClassIndex = nestedClassReader ( reader ); int enclosingClassIndex = enclosingClassReader( reader ); MetaDataTypeDefinition nestedClass = this.getTypeDef( nestedClassIndex ); MetaDataTypeDefinition enclosingClass = this.getTypeDef( enclosingClassIndex ); enclosingClass.AddNestedClass( nestedClass ); } } // 0x2A private void parseGenericParamTable() { InitializeTableAndLoad( TokenType.GenericParam, ref this.metaDataObject.m_genericParamArray, MetaDataGenericParam.GetCreator() ); } // 0x2B private void parseMethodSpecTable() { InitializeTableAndLoad( TokenType.MethodSpec, ref this.metaDataObject.m_methodSpecArray, MetaDataMethodSpec.GetCreator() ); } // 0x2C private void parseGenericParamConstraintTable() { TableSchema ts = this.schemaArray[(int)TokenType.GenericParamConstraint]; IndexReader ownerReader = ts.m_columns[0].m_reader; IndexReader constraintReader = ts.m_columns[1].m_reader; ArrayReader reader = ts.m_reader; for(int i = 0; i < ts.m_rows; i++) { int ownerIndex = ownerReader ( reader ); int constraintIndex = constraintReader( reader ); MetaDataGenericParam owner = this.getGenericParam( ownerIndex ); IMetaDataTypeDefOrRef constraint = this.getTypeDefOrRef( constraintIndex ); owner.AddGenericParamConstraint( constraint ); } } //--// // // Access Methods // internal MetaData MetaData { get { return this.metaDataObject; } } //--// internal ArrayReader ImageReaderAt( int offset ) { return new ArrayReader( this.imageReader, offset ); } internal ArrayReader ImageReaderAtVirtualAddress( int va ) { int address = this.peLoader.VaToOffsetSafe( va ); if(address == -1) return null; return ImageReaderAt( address ); } // Nested Classes private class StorageSignature { private const int STORAGE_MAGIC_SIG = 0x424A5342; private const int FILE_MAJOR_VERSION = 1; private const int FILE_MINOR_VERSION = 1; // // State // internal readonly int signature; internal readonly short majorVersion; internal readonly short minorVersion; internal readonly int extraData; internal readonly String versionString; // // Constructor Methods // internal StorageSignature( ArrayReader reader ) { this.signature = reader.ReadInt32(); this.majorVersion = reader.ReadInt16(); this.minorVersion = reader.ReadInt16(); this.extraData = reader.ReadInt32(); int length = reader.ReadInt32(); this.versionString = reader.ReadUInt8String( length ); if(this.signature != StorageSignature.STORAGE_MAGIC_SIG) { throw IllegalMetaDataFormatException.Create( "Don't know signature 0x{0:X8}", this.signature ); } if(this.majorVersion != StorageSignature.FILE_MAJOR_VERSION || this.minorVersion != StorageSignature.FILE_MINOR_VERSION) { throw IllegalMetaDataFormatException.Create( "Unknown version" ); } } } private class StorageHeader { internal const Byte STGHDR_EXTRADATA = 0x01; // // State // internal Byte flags; internal Byte pad; internal short streamCount; internal byte[] extra; // // Constructor Methods // internal StorageHeader( ArrayReader reader ) { this.flags = reader.ReadUInt8(); this.pad = reader.ReadUInt8(); this.streamCount = reader.ReadInt16(); if((this.flags & STGHDR_EXTRADATA) != 0) { int count = reader.ReadInt32(); this.extra = reader.ReadUInt8Array( count ); } } } private class StorageStream { internal const String COMPRESSED_MODEL = "#~"; internal const String ENC_MODEL = "#-"; internal const String SCHEMA = "#Schema"; internal const String STRING_POOL = "#Strings"; internal const String BLOB_POOL = "#Blob"; internal const String USER_BLOB_POOL = "#US"; internal const String VARIANT_POOL = "#Variants"; internal const String GUID_POOL = "#GUID"; // // State // internal int offset; internal int size; internal String name; // // Constructor Methods // internal StorageStream( ArrayReader reader ) { this.offset = reader.ReadInt32(); this.size = reader.ReadInt32(); int startPosition = reader.Position; this.name = reader.ReadZeroTerminatedUInt8String(); // // Align to word boundary. // while((reader.Position - startPosition) % 4 != 0) { reader.ReadUInt8(); } } // // Output Methods // public override String ToString() { return "StorageStream(" + this.name + "," + this.offset + "," + this.size + ")"; } } } } ================================================ FILE: Zelig/Zelig/CompileTime/MetaData/Importer/Properties/AssemblyInfo.cs ================================================ using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; // General Information about an assembly is controlled through the following // set of attributes. Change these attribute values to modify the information // associated with an assembly. [assembly: AssemblyTitle( "Microsoft.Zelig.MetaData.Importer" )] [assembly: AssemblyDescription( "" )] [assembly: AssemblyConfiguration( "" )] [assembly: AssemblyCompany( "Microsoft" )] [assembly: AssemblyProduct( "Microsoft.Zelig.MetaData.Importer" )] [assembly: AssemblyCopyright( "Copyright © Microsoft 2006" )] [assembly: AssemblyTrademark( "" )] [assembly: AssemblyCulture( "" )] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible( false )] //// The following GUID is for the ID of the typelib if this project is exposed to COM //[assembly: Guid( "012e8fb6-008e-45a0-ba5d-64b07a84aa95" )] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Revision and Build Numbers // by using the '*' as shown below: [assembly: AssemblyVersion( "1.0.0.0" )] [assembly: AssemblyFileVersion( "1.0.0.0" )] ================================================ FILE: Zelig/Zelig/CompileTime/MetaData/Importer/Signature.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // // // Originally based on the Bartok code base. // using System; using System.Collections.Generic; using System.Text; /********************************************************************** * * The Microsoft.Zelig.MetaData.Importer.Signature* classes represent the signatures read * from the Blob heap of the input file(s). * * Since the signatures have references to MetaData* objects, the * signatures are initially just an array of bytes. When all the * MetaData objects have been created, the array of bytes is processed * and the references resolved. * **********************************************************************/ namespace Microsoft.Zelig.MetaData.Importer { public abstract class SignatureType : Signature { // // State // protected readonly ElementTypes m_elementType; protected Modifier m_modifierChain; // // Constructor Methods // protected SignatureType( ElementTypes elementType ) { m_elementType = elementType; } //--// internal void SetModifierChain( Modifier modifierChain ) { m_modifierChain = modifierChain; } //--// internal Normalized.MetaDataSignature ApplyModifiers( Normalized.MetaDataTypeDefinitionAbstract obj , MetaDataNormalizationContext context ) { Normalized.SignatureType sig = Normalized.SignatureType.Create( obj ); if(m_modifierChain != null) { m_modifierChain.Apply( sig, context ); } return (Normalized.MetaDataSignature)sig.MakeUnique(); } // // Access Methods // public ElementTypes ElementType { get { return m_elementType; } } public Modifier ModifierChain { get { return m_modifierChain; } } // // Debug Methods // public override string ToString() { StringBuilder sb = new StringBuilder(); sb.Append( m_elementType ); if(m_modifierChain != null) { sb.Append( "," ); sb.Append( m_modifierChain ); } return sb.ToString(); } //--//--// public class BuiltIn : SignatureType, IMetaDataNormalizeSignature { // // Constructor Methods // public BuiltIn( ElementTypes elementType ) : base( elementType ) { } //--// // // IMetaDataNormalizeSignature methods // Normalized.MetaDataSignature IMetaDataNormalizeSignature.AllocateNormalizedObject( MetaDataNormalizationContext context ) { Normalized.MetaDataTypeDefinitionAbstract res = context.LookupBuiltIn( m_elementType ); return ApplyModifiers( res, context ); } // // Debug Methods // public override string ToString() { StringBuilder sb = new StringBuilder(); sb.Append( base.ToString() ); return sb.ToString(); } } public class ClassOrStruct : SignatureType, IMetaDataNormalizeSignature { // // State // protected IMetaDataTypeDefOrRef m_classObject; // // Constructor Methods // public ClassOrStruct( ElementTypes elementType , IMetaDataTypeDefOrRef classObject ) : base( elementType ) { m_classObject = classObject; } // // IMetaDataNormalizeSignature methods // Normalized.MetaDataSignature IMetaDataNormalizeSignature.AllocateNormalizedObject( MetaDataNormalizationContext context ) { Normalized.MetaDataTypeDefinitionAbstract res; context.GetNormalizedObject( m_classObject, out res, MetaDataNormalizationMode.LookupExisting ); return ApplyModifiers( res, context ); } // // Access Methods // public IMetaDataTypeDefOrRef ClassObject { get { return m_classObject; } } // // Debug Methods // public override string ToString() { StringBuilder sb = new StringBuilder( "ClassOrStruct(" ); sb.Append( base.ToString() ); sb.Append( "," ); sb.Append( m_classObject ); sb.Append( ")" ); return sb.ToString(); } } public class Prefix : SignatureType, IMetaDataNormalizeSignature { // // State // protected readonly SignatureType m_type; // // Constructor Methods // public Prefix( ElementTypes elementType , SignatureType type ) : base( elementType ) { m_type = type; } // // IMetaDataNormalizeSignature methods // Normalized.MetaDataSignature IMetaDataNormalizeSignature.AllocateNormalizedObject( MetaDataNormalizationContext context ) { Normalized.SignatureType sig; context.GetNormalizedSignature( m_type, out sig, MetaDataNormalizationMode.Default ); //--// Normalized.MetaDataTypeDefinitionByRef byref = new Normalized.MetaDataTypeDefinitionByRef( context.GetAssemblyFromContext(), 0, m_elementType ); byref.m_type = sig.Type; return ApplyModifiers( byref, context ); } // // Access Methods // public SignatureType InnerType { get { return m_type; } } // // Debug Methods // public override string ToString() { StringBuilder sb = new StringBuilder( "Prefix(" ); sb.Append( base.ToString() ); sb.Append( "," ); sb.Append( m_type ); sb.Append( ")" ); return sb.ToString(); } } public class Method : SignatureType, IMetaDataNormalizeSignature { // // State // protected readonly SignatureMethod m_method; // // Constructor Methods // public Method( SignatureMethod method ) : base( ElementTypes.FNPTR ) { m_method = method; } // // IMetaDataNormalizeSignature methods // Normalized.MetaDataSignature IMetaDataNormalizeSignature.AllocateNormalizedObject( MetaDataNormalizationContext context ) { throw IllegalMetaDataFormatException.Create( "FNPTR elements in signatures not supported" ); } // // Access Methods // public SignatureMethod Signature { get { return m_method; } } // // Debug Methods // public override string ToString() { StringBuilder sb = new StringBuilder( "Method(" ); sb.Append( base.ToString() ); sb.Append( "," ); sb.Append( m_method ); sb.Append( ")" ); return sb.ToString(); } } public abstract class BaseArray : SignatureType { // // Constructor Methods // protected BaseArray( ElementTypes elementType ) : base( elementType ) { } } public class SzArray : BaseArray, IMetaDataNormalizeSignature { // // State // protected readonly SignatureType m_typeObject; // // Constructor Methods // public SzArray( SignatureType typeObject ) : base( ElementTypes.SZARRAY ) { m_typeObject = typeObject; } // // IMetaDataNormalizeSignature methods // Normalized.MetaDataSignature IMetaDataNormalizeSignature.AllocateNormalizedObject( MetaDataNormalizationContext context ) { Normalized.SignatureType sigTypeObject; context.GetNormalizedSignature( m_typeObject, out sigTypeObject, MetaDataNormalizationMode.Default ); //--// Normalized.MetaDataTypeDefinitionArraySz arrayNew = new Normalized.MetaDataTypeDefinitionArraySz( context.GetAssemblyFromContext(), 0 ); arrayNew.m_elementType = m_elementType; arrayNew.m_extends = context.LookupBuiltIn( ElementTypes.SZARRAY ); arrayNew.m_objectType = sigTypeObject.Type; return ApplyModifiers( arrayNew, context ); } // // Access Methods // public SignatureType TypeObject { get { return m_typeObject; } } // // Debug Methods // public override string ToString() { StringBuilder sb = new StringBuilder( "SzArray(" ); sb.Append( base.ToString() ); sb.Append( "," ); sb.Append( m_typeObject ); sb.Append( ")" ); return sb.ToString(); } } public class Array : BaseArray, IMetaDataNormalizeSignature { public struct Dimension { // // State // public uint m_lowerBound; public uint m_upperBound; } // // State // protected readonly SignatureType m_type; protected readonly uint m_rank; protected readonly Dimension[] m_dimensions; // // Constructor Methods // public Array( SignatureType type , uint rank , Dimension[] dimensions ) : base( ElementTypes.ARRAY ) { m_type = type; m_rank = rank; m_dimensions = dimensions; } // // IMetaDataNoIMetaDataNormalizeSignaturermalize methods // Normalized.MetaDataSignature IMetaDataNormalizeSignature.AllocateNormalizedObject( MetaDataNormalizationContext context ) { Normalized.SignatureType sigTypeObject; context.GetNormalizedSignature( m_type, out sigTypeObject, MetaDataNormalizationMode.Default ); //--// Normalized.MetaDataTypeDefinitionArrayMulti arrayNew = new Normalized.MetaDataTypeDefinitionArrayMulti( context.GetAssemblyFromContext(), 0 ); arrayNew.m_extends = context.LookupBuiltIn( ElementTypes.SZARRAY ); arrayNew.m_objectType = sigTypeObject.Type; arrayNew.m_rank = m_rank; arrayNew.m_dimensions = new Normalized.MetaDataTypeDefinitionArrayMulti.Dimension[m_dimensions.Length]; for(int i = 0; i < m_dimensions.Length; i++) { arrayNew.m_dimensions[i].m_lowerBound = m_dimensions[i].m_lowerBound; arrayNew.m_dimensions[i].m_upperBound = m_dimensions[i].m_upperBound; } return ApplyModifiers( arrayNew, context ); } // // Access Methods // public SignatureType BaseType { get { return m_type; } } public uint Rank { get { return m_rank; } } public Dimension[] Dimensions { get { return m_dimensions; } } // // Debug Methods // public override string ToString() { StringBuilder sb = new StringBuilder( "Array(" ); sb.Append( base.ToString() ); sb.Append( "," ); sb.Append( m_type ); sb.Append( "[" ); for(int i = 0; i < m_rank; i++) { uint lower = m_dimensions[i].m_lowerBound; uint upper = m_dimensions[i].m_upperBound; if(i != 0) { sb.Append( "," ); } if(lower != 0 || upper != 0) { sb.Append( lower ); if(upper > lower) { sb.Append( ".." ); sb.Append( upper ); } } } sb.Append( "]" ); sb.Append( ")" ); return sb.ToString(); } } public class GenericParameter : SignatureType, IMetaDataNormalizeSignature { // // State // private readonly uint m_number; // // Constructor Methods // public GenericParameter( ElementTypes elementType , uint number ) : base( elementType ) { m_number = number; } // // IMetaDataNormalizeSignature methods // Normalized.MetaDataSignature IMetaDataNormalizeSignature.AllocateNormalizedObject( MetaDataNormalizationContext context ) { switch(m_elementType) { case ElementTypes.VAR: { Normalized.MetaDataTypeDefinitionDelayed tdNew = new Normalized.MetaDataTypeDefinitionDelayed( context.GetAssemblyForDelayedParameters(), 0 ); tdNew.m_elementType = ElementTypes.VAR; tdNew.m_parameterNumber = (int)m_number; tdNew.m_isMethodParam = false; return ApplyModifiers( tdNew, context ); } case ElementTypes.MVAR: { Normalized.MetaDataTypeDefinitionDelayed tdNew = new Normalized.MetaDataTypeDefinitionDelayed( context.GetAssemblyForDelayedParameters(), 0 ); tdNew.m_elementType = ElementTypes.MVAR; tdNew.m_parameterNumber = (int)m_number; tdNew.m_isMethodParam = true; return ApplyModifiers( tdNew, context ); } } throw IllegalMetaDataFormatException.Create( "'{0}' cannot be resolved in the context of '{1}'", this, context ); } // // Access Methods // public uint Number { get { return m_number; } } // // Debug Methods // public override string ToString() { StringBuilder sb = new StringBuilder( "GenParam(" ); sb.Append( base.ToString() ); sb.Append( "," ); sb.Append( m_number ); sb.Append( ")" ); return sb.ToString(); } } public class GenericInstantiation : SignatureType, IMetaDataNormalizeSignature { // // State // private readonly SignatureType m_type; private readonly SignatureType[] m_parameters; // // Constructor Methods // public GenericInstantiation( SignatureType type , SignatureType[] parameters ) : base( ElementTypes.GENERICINST ) { m_type = type; m_parameters = parameters; } // // IMetaDataNormalizeSignature methods // Normalized.MetaDataSignature IMetaDataNormalizeSignature.AllocateNormalizedObject( MetaDataNormalizationContext context ) { Normalized.SignatureType baseType; Normalized.SignatureType[] parameters; context.GetNormalizedSignature ( m_type , out baseType , MetaDataNormalizationMode.Default ); context.GetNormalizedSignatureArray( m_parameters, out parameters, MetaDataNormalizationMode.Default ); Normalized.MetaDataTypeDefinitionGenericInstantiation tdNew = new Normalized.MetaDataTypeDefinitionGenericInstantiation( context.GetAssemblyFromContext(), 0 ); tdNew.m_baseType = (Normalized.MetaDataTypeDefinitionGeneric)baseType.Type; tdNew.m_parameters = parameters; return ApplyModifiers( tdNew, context ); } // // Access Methods // public SignatureType Type { get { return m_type; } } public SignatureType[] Parameters { get { return m_parameters; } } // // Debug Methods // public override string ToString() { StringBuilder sb = new StringBuilder( "GenInst(" ); sb.Append( base.ToString() ); sb.Append( "," ); sb.Append( m_type ); sb.Append( "<" ); for(int i = 0; i < m_parameters.Length; i++) { if(i != 0) { sb.Append( "," ); } sb.Append( m_parameters[i] ); } sb.Append( ">" ); sb.Append( ")" ); return sb.ToString(); } } //--// public class Modifier { // // State // private ElementTypes m_mod; private IMetaDataTypeDefOrRef m_classObject; private Modifier m_next; // // Constructor Methods // public Modifier( ElementTypes mod , IMetaDataTypeDefOrRef classObject , Modifier next ) { m_mod = mod; m_classObject = classObject; m_next = next; } internal void Apply( Normalized.SignatureType sig , MetaDataNormalizationContext context ) { Normalized.MetaDataTypeDefinitionAbstract classObject; context.GetNormalizedObject( m_classObject, out classObject, MetaDataNormalizationMode.Default ); sig.m_modifiers = ArrayUtility.AppendToArray( sig.m_modifiers, classObject ); if(m_next != null) { m_next.Apply( sig, context ); } } // // Access Methods // public ElementTypes Kind { get { return m_mod; } } public IMetaDataTypeDefOrRef ClassObject { get { return m_classObject; } } public Modifier Next { get { return m_next; } } // // Debug Methods // public override string ToString() { StringBuilder sb = new StringBuilder(); sb.Append( m_mod ); sb.Append( "(" ); sb.Append( m_classObject ); sb.Append( ")" ); if(m_next != null) { sb.Append( " " ); sb.Append( m_next ); } return sb.ToString(); } } } //--// public abstract class Signature { [Flags] internal enum ParseFlags { Default = 0x00, AllowCustomModifiers = 0x01, AllowPinned = 0x02, AllowByRef = 0x04, AllowTypedByRef = 0x08, AllowVoid = 0x10, MustBeWholeSignature = 0x20, } public enum CallingConventions : byte { Default = 0x00, Unmanaged_cdecl = 0x01, Unmanaged_sdtcall = 0x02, Unmanaged_thiscall = 0x03, Unmanaged_fastcall = 0x04, VarArg = 0x05, Field = 0x06, LocalVar = 0x07, Property = 0x08, Unmanaged = 0x09, GenericInst = 0x0A, Mask = 0x0F, Generic = 0x10, HasThis = 0x20, ExplicitThis = 0x40 } // // Helper Methods // internal static void CheckEndOfSignature( ArrayReader reader ) { if(reader.IsEOF == false) { throw IllegalMetaDataFormatException.Create( "Only read {0} bytes of signature {1}", reader.Position, reader ); } } internal static Signature ParseUnknown( Parser parser , ArrayReader reader ) { return Signature.ParseUnknown( parser, reader, ParseFlags.MustBeWholeSignature ); } internal static Signature ParseUnknown( Parser parser , ArrayReader reader , ParseFlags flags ) { if((flags & ParseFlags.MustBeWholeSignature) != 0) { flags &= ~ParseFlags.MustBeWholeSignature; Signature type = ParseUnknown( parser, reader, flags ); Signature.CheckEndOfSignature( reader ); //Console.Out.WriteLine( "{0}", type ); return type; } //--// uint unmaskedCallingConvention = reader.ReadCompressedUInt32(); CallingConventions callingConvention = (CallingConventions)(unmaskedCallingConvention & (uint)CallingConventions.Mask); switch(callingConvention) { case CallingConventions.Field: { // // Section 23.2.4 of ECMA spec, Partition II // // // ParseFlags.AllowByRef is added to allow parsing of managed C++ assemblies. // SignatureType type = Signature.ParseType( parser, reader, ParseFlags.AllowCustomModifiers | ParseFlags.AllowByRef ); return new SignatureField( type ); } case CallingConventions.LocalVar: { // // Section 23.2.6 of ECMA spec, Partition II // uint count = reader.ReadCompressedUInt32(); SignatureType[] locals = new SignatureType[count]; for(int i = 0; i < count; i++) { locals[i] = Signature.ParseSignatureLocal( parser, reader ); } return new SignatureLocalVar( locals ); } case CallingConventions.Property: { // // Section 23.2.5 of ECMA spec, Partition II // uint paramCount = reader.ReadCompressedUInt32(); SignatureType returnType = Signature.ParseReturnType( parser, reader ); SignatureType[] parameters = new SignatureType[paramCount]; for(int i = 0; i < paramCount; i++) { parameters[i] = Signature.ParseParam( parser, reader ); } return new SignatureProperty( returnType, parameters ); } case CallingConventions.GenericInst: { // // Section 22.29, 23.2.15 of ECMA spec, Partition II // uint genericParamCount = reader.ReadCompressedUInt32(); SignatureType[] genericParameters = new SignatureType[genericParamCount]; for(int i = 0; i < genericParamCount; i++) { genericParameters[i] = Signature.ParseParam( parser, reader ); } return new SignatureMethodSpec( genericParameters ); } default: { // // Section 23.2.1, 23.2.2, and 23.2.3 of ECMA spec, Partition II // uint genericParamCount = 0; if((unmaskedCallingConvention & (uint)CallingConventions.Generic) != 0) { genericParamCount = reader.ReadCompressedUInt32(); } uint paramCount = reader.ReadCompressedUInt32(); SignatureType returnType = Signature.ParseReturnType( parser, reader ); int sentinelLocation = -1; SignatureType[] parameters = new SignatureType[paramCount]; for(int i = 0; i < paramCount; i++) { byte first = reader.PeekUInt8(); if(first == (byte)ElementTypes.SENTINEL) { reader.Seek( 1 ); sentinelLocation = i; } parameters[i] = Signature.ParseParam( parser, reader ); } return new SignatureMethod( (CallingConventions)unmaskedCallingConvention, genericParamCount, sentinelLocation, returnType, parameters ); } } } internal static Signature ParseMemberRef( Parser parser , ArrayReader reader ) { Signature sig = Signature.ParseUnknown( parser, reader ); if(sig is SignatureField) { } else if(sig is SignatureMethod) { } else { throw IllegalMetaDataFormatException.Create( "Not a member ref signature: {0}", sig ); } return sig; } internal static SignatureType ParseType( Parser parser , ArrayReader reader , ParseFlags flags ) { if((flags & ParseFlags.AllowCustomModifiers) != 0) { // // The flag is not reset to allow parsing of managed C++ assemblies, // where a type can have multiple custom modifiers throughout the signature. // SignatureType.Modifier modifier = ParseOptionalModifier( parser, reader ); if(modifier != null) { SignatureType type = Signature.ParseType( parser, reader, flags ); type.SetModifierChain( modifier ); return type; } } ElementTypes elementType = (ElementTypes)reader.ReadUInt8(); switch(elementType) { case ElementTypes.VOID: { if((flags & ParseFlags.AllowVoid) == 0) { throw IllegalMetaDataFormatException.Create( "Unexpected VOID element at {0} in {1}", reader.Position, reader ); } goto case ElementTypes.BOOLEAN; } case ElementTypes.TYPEDBYREF: { // APPCOMPACT: Although not allowed, v1.1 mscorlib.dll contains a TYPEDBYREF field... //if((flags & ParseFlags.AllowTypedByRef) == 0) //{ // throw new IllegalMetaDataFormatException( "Unexpected TYPEDBYREF element at " + reader.Position + " in " + reader ); //} goto case ElementTypes.BOOLEAN; } case ElementTypes.BOOLEAN: case ElementTypes.CHAR : case ElementTypes.I1 : case ElementTypes.U1 : case ElementTypes.I2 : case ElementTypes.U2 : case ElementTypes.I4 : case ElementTypes.U4 : case ElementTypes.I8 : case ElementTypes.U8 : case ElementTypes.R4 : case ElementTypes.R8 : case ElementTypes.U : case ElementTypes.I : case ElementTypes.OBJECT : case ElementTypes.STRING : { return new SignatureType.BuiltIn( elementType ); } case ElementTypes.VALUETYPE: case ElementTypes.CLASS : { // Followed by: TypeDefOrRefEncoded int typeEncoded = reader.ReadCompressedToken(); return new SignatureType.ClassOrStruct( elementType, (IMetaDataTypeDefOrRef)parser.getObjectFromToken( typeEncoded ) ); } case ElementTypes.SZARRAY: { // Followed by: CustomMod* Type SignatureType type = Signature.ParseType( parser, reader, ParseFlags.AllowCustomModifiers ); return new SignatureType.SzArray( type ); } case ElementTypes.ARRAY: { // Followed by: Type ArrayShape SignatureType type = Signature.ParseType( parser, reader, ParseFlags.Default ); uint rank = reader.ReadCompressedUInt32(); if(rank == 0) { throw IllegalMetaDataFormatException.Create( "ARRAY with rank 0" ); } SignatureType.Array.Dimension[] dimensions = new SignatureType.Array.Dimension[rank]; uint numUpperBounds = reader.ReadCompressedUInt32(); if(numUpperBounds > rank) { throw IllegalMetaDataFormatException.Create( "ARRAY with upper bounds > rank" ); } for(int i = 0; i < numUpperBounds; i++) { dimensions[i].m_upperBound = reader.ReadCompressedUInt32(); } uint numLowerBounds = reader.ReadCompressedUInt32(); if(numLowerBounds > rank) { throw IllegalMetaDataFormatException.Create( "ARRAY with lower bounds > rank" ); } for(int i = 0; i < numLowerBounds; i++) { dimensions[i].m_lowerBound = reader.ReadCompressedUInt32(); } return new SignatureType.Array( type, rank, dimensions ); } case ElementTypes.FNPTR: { // Followed by: MethodDefSig or MethodRefSig SignatureMethod signature = SignatureMethod.Parse( parser, reader, ParseFlags.Default ); return new SignatureType.Method( signature ); } case ElementTypes.VAR : case ElementTypes.MVAR: { // Generic type variables uint number = reader.ReadCompressedUInt32(); return new SignatureType.GenericParameter( elementType, number ); } case ElementTypes.GENERICINST: { // Generic type instantiation SignatureType type = Signature.ParseType( parser, reader, ParseFlags.Default ); uint typeCount = reader.ReadCompressedUInt32(); SignatureType[] typeParams = new SignatureType[typeCount]; for(int i = 0; i < typeCount; i++) { SignatureType paramType = typeParams[i] = Signature.ParseType( parser, reader, ParseFlags.Default ); } return new SignatureType.GenericInstantiation( type, typeParams ); } case ElementTypes.CMOD_REQD: case ElementTypes.CMOD_OPT : throw IllegalMetaDataFormatException.Create( "Unexpected custom modifier: 0x{0:X2} at {1} in {2}", (byte)elementType, reader.Position, reader ); case ElementTypes.PINNED: { // APPCOMPACT: Although not allowed, v1.1 mscorlib.dll contains a PINNED field... //if((flags & ParseFlags.AllowPinned) == 0) //{ // throw new IllegalMetaDataFormatException( "Unexpected PINNED prefix at " + reader.Position + " in " + reader ); //} flags &= ~ParseFlags.AllowPinned; // APPCOMPACT: fixed (void* pBuffer) gets encoded as PINNED BYREF VOID. if((flags & ParseFlags.AllowByRef) != 0) { flags |= ParseFlags.AllowVoid; } SignatureType type = Signature.ParseType( parser, reader, flags ); return new SignatureType.Prefix( elementType, type ); } case ElementTypes.PTR: { // Modifiers SignatureType type = Signature.ParseType( parser, reader, ParseFlags.AllowCustomModifiers | ParseFlags.AllowVoid ); return new SignatureType.Prefix( elementType, type ); } case ElementTypes.BYREF: { if((flags & ParseFlags.AllowByRef) == 0) { throw IllegalMetaDataFormatException.Create( "Unexpected BYREF prefix at {0} in {1}", reader.Position, reader ); } flags &= ~ParseFlags.AllowByRef; SignatureType type = Signature.ParseType( parser, reader, flags ); return new SignatureType.Prefix( elementType, type ); } default: { throw IllegalMetaDataFormatException.Create( "Unknown signature type: 0x{0:X2} at {1} in {2}", (byte)elementType, reader.Position, reader ); } } } protected static SignatureType.Modifier ParseOptionalModifier( Parser parser , ArrayReader reader ) { SignatureType.Modifier result = null; while(reader.IsEOF == false) { ElementTypes mod = (ElementTypes)reader.PeekUInt8(); if(mod == ElementTypes.CMOD_REQD || mod == ElementTypes.CMOD_OPT ) { reader.Seek( 1 ); int typeEncoded = reader.ReadCompressedToken(); result = new SignatureType.Modifier( mod, (IMetaDataTypeDefOrRef)parser.getObjectFromToken( typeEncoded ), result ); } else { break; } } return result; } protected static SignatureType ParseParam( Parser parser , ArrayReader reader ) { return Signature.ParseType( parser, reader, ParseFlags.AllowCustomModifiers | ParseFlags.AllowByRef | ParseFlags.AllowTypedByRef ); } protected static SignatureType ParseReturnType( Parser parser , ArrayReader reader ) { return Signature.ParseType( parser, reader, ParseFlags.AllowCustomModifiers | ParseFlags.AllowByRef | ParseFlags.AllowTypedByRef | ParseFlags.AllowVoid ); } protected static SignatureType ParseSignatureLocal( Parser parser , ArrayReader reader ) { return Signature.ParseType( parser, reader, ParseFlags.AllowCustomModifiers | ParseFlags.AllowPinned | ParseFlags.AllowByRef | ParseFlags.AllowTypedByRef ); } } } ================================================ FILE: Zelig/Zelig/CompileTime/MetaData/Importer/SignatureField.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // // // Originally based on the Bartok code base. // using System; using System.Collections.Generic; using System.Text; namespace Microsoft.Zelig.MetaData.Importer { public class SignatureField : Signature, IMetaDataNormalizeSignature { // // State // private readonly SignatureType m_type; // // Constructor Methods // internal SignatureField( SignatureType type ) { m_type = type; } internal static SignatureField Parse( Parser parser , ArrayReader reader ) { Signature sig = Signature.ParseUnknown( parser, reader ); if(sig is SignatureField) { return (SignatureField)sig; } throw IllegalMetaDataFormatException.Create( "Not a field signature: {0}", sig ); } // // IMetaDataNormalizeSignature methods // Normalized.MetaDataSignature IMetaDataNormalizeSignature.AllocateNormalizedObject( MetaDataNormalizationContext context ) { Normalized.SignatureField res = new Normalized.SignatureField( 0 ); context.GetNormalizedSignature( m_type, out res.m_type, MetaDataNormalizationMode.Default ); return (Normalized.MetaDataSignature)res.MakeUnique(); } // // Access Methods // public SignatureType FieldType { get { return m_type; } } // // Debug Methods // public override String ToString() { return "SignatureField(" + m_type + ")"; } } } ================================================ FILE: Zelig/Zelig/CompileTime/MetaData/Importer/SignatureLocalVar.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // // // Originally based on the Bartok code base. // using System; using System.Collections.Generic; using System.Text; namespace Microsoft.Zelig.MetaData.Importer { public class SignatureLocalVar : Signature { // // State // private readonly SignatureType[] m_locals; // // Constructor Methods // internal SignatureLocalVar( SignatureType[] locals ) { m_locals = locals; } internal static SignatureLocalVar Parse( Parser parser , ArrayReader reader ) { Signature sig = Signature.ParseUnknown( parser, reader ); if(sig is SignatureLocalVar) { return (SignatureLocalVar)sig; } throw IllegalMetaDataFormatException.Create( "Not a local variables signature: {0}", sig ); } // // Access Methods // public SignatureType[] Locals { get { return m_locals; } } // // Debug Methods // public override String ToString() { StringBuilder sb = new StringBuilder( "SignatureLocalVar(" ); for(int i = 0; i < m_locals.Length; i++) { if(i != 0) { sb.Append( "," ); } sb.Append( m_locals[i] ); } sb.Append( ")" ); return sb.ToString(); } } } ================================================ FILE: Zelig/Zelig/CompileTime/MetaData/Importer/SignatureMethod.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // // // Originally based on the Bartok code base. // using System; using System.Collections.Generic; using System.Text; namespace Microsoft.Zelig.MetaData.Importer { public class SignatureMethod : Signature, IMetaDataNormalizeSignature { // // State // private readonly CallingConventions m_callingConvention; private readonly uint m_genericParameterCount; private readonly int m_sentinelLocation; private readonly SignatureType m_returnType; private readonly SignatureType[] m_parameters; // // Constructor Methods // internal SignatureMethod( CallingConventions callingConvention , uint genericParameterCount , int sentinelLocation , SignatureType returnType , SignatureType[] parameters ) { m_callingConvention = callingConvention; m_genericParameterCount = genericParameterCount; m_returnType = returnType; m_parameters = parameters; m_sentinelLocation = sentinelLocation; } internal static SignatureMethod Parse( Parser parser , ArrayReader reader ) { return SignatureMethod.Parse( parser, reader, ParseFlags.MustBeWholeSignature ); } internal static SignatureMethod Parse( Parser parser , ArrayReader reader , Signature.ParseFlags flags ) { Signature sig = Signature.ParseUnknown( parser, reader, flags ); if(sig is SignatureMethod) { return (SignatureMethod)sig; } throw IllegalMetaDataFormatException.Create( "Not a method signature: {0}", sig ); } // // IMetaDataNormalizeSignature methods // Normalized.MetaDataSignature IMetaDataNormalizeSignature.AllocateNormalizedObject( MetaDataNormalizationContext context ) { Normalized.SignatureMethod res = new Normalized.SignatureMethod( 0 ); res.m_callingConvention = (Normalized.SignatureMethod.CallingConventions)m_callingConvention; context.GetNormalizedSignature ( m_returnType, out res.m_returnType, MetaDataNormalizationMode.Default ); context.GetNormalizedSignatureArray( m_parameters, out res.m_parameters, MetaDataNormalizationMode.Default ); return (Normalized.MetaDataSignature)res.MakeUnique(); } // // Access Methods // public CallingConventions CallingConvention { get { return m_callingConvention; } } public uint GenericParameterCount { get { return m_genericParameterCount; } } public SignatureType ReturnType { get { return m_returnType; } } public SignatureType[] Parameters { get { return m_parameters; } } public int SentinelLocation { get { return m_sentinelLocation; } } // other handy methods public bool HasThis { get { return ((((int)m_callingConvention) & ((int)Signature.CallingConventions.HasThis)) != 0); } } public bool ExplicitThis { get { return ((((int)m_callingConvention) & ((int)Signature.CallingConventions.ExplicitThis)) != 0); } } public bool NoThis { get { return !(HasThis || ExplicitThis); } } // // Debug Methods // public override String ToString() { StringBuilder sb = new StringBuilder( "SignatureMethod(" ); sb.Append( m_callingConvention ); sb.Append( "," ); if((m_callingConvention & CallingConventions.Generic) != 0) { sb.Append( "genParamCount=" ); sb.Append( m_genericParameterCount ); sb.Append( "," ); } sb.Append( m_returnType ); sb.Append( "," ); sb.Append( "parameters(" ); for(int i = 0; i < m_parameters.Length; i++) { if(i != 0) { sb.Append( "," ); } if(m_sentinelLocation == i) { sb.Append( "," ); } sb.Append( m_parameters[i] ); } sb.Append( "))" ); return sb.ToString(); } } } ================================================ FILE: Zelig/Zelig/CompileTime/MetaData/Importer/SignatureMethodSpec.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // // // Originally based on the Bartok code base. // using System; using System.Collections.Generic; using System.Text; namespace Microsoft.Zelig.MetaData.Importer { public class SignatureMethodSpec : Signature, IMetaDataNormalizeSignature { // // State // private readonly SignatureType[] m_genericParameters; // // Constructor Methods // internal SignatureMethodSpec( SignatureType[] genericParameters ) { m_genericParameters = genericParameters; } internal static SignatureMethodSpec Parse( Parser parser , ArrayReader reader ) { return SignatureMethodSpec.Parse( parser, reader, ParseFlags.MustBeWholeSignature ); } internal static SignatureMethodSpec Parse( Parser parser , ArrayReader reader , Signature.ParseFlags flags ) { Signature sig = Signature.ParseUnknown( parser, reader, flags ); if(sig is SignatureMethodSpec) { return (SignatureMethodSpec)sig; } throw IllegalMetaDataFormatException.Create( "Not a method spec signature: {0}", sig ); } // // IMetaDataNormalizeSignature methods // Normalized.MetaDataSignature IMetaDataNormalizeSignature.AllocateNormalizedObject( MetaDataNormalizationContext context ) { Normalized.SignatureMethod res = new Normalized.SignatureMethod( 0 ); res.m_callingConvention = 0; res.m_returnType = null; context.GetNormalizedSignatureArray( m_genericParameters, out res.m_parameters, MetaDataNormalizationMode.Default ); return res; } // // Access Methods // public SignatureType[] GenericParameters { get { return m_genericParameters; } } // // Debug Methods // public override String ToString() { StringBuilder sb = new StringBuilder( "SignatureMethodSpec(" ); sb.Append( "generic parameters(" ); for(int i = 0; i < m_genericParameters.Length; i++) { if(i != 0) { sb.Append( "," ); } sb.Append( m_genericParameters[i] ); } sb.Append( "))" ); return sb.ToString(); } } } ================================================ FILE: Zelig/Zelig/CompileTime/MetaData/Importer/SignatureProperty.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // // // Originally based on the Bartok code base. // using System; using System.Collections.Generic; using System.Text; namespace Microsoft.Zelig.MetaData.Importer { public class SignatureProperty : Signature, IMetaDataNormalizeSignature { // // State // private readonly SignatureType m_returnType; private readonly SignatureType[] m_parameters; // // Constructor Methods // internal SignatureProperty( SignatureType returnType , SignatureType[] parameters ) { m_returnType = returnType; m_parameters = parameters; } internal static SignatureProperty Parse( Parser parser , ArrayReader reader ) { Signature sig = Signature.ParseUnknown( parser, reader ); if(sig is SignatureProperty) { return (SignatureProperty)sig; } throw IllegalMetaDataFormatException.Create( "Not a property signature: {0}", sig ); } // // IMetaDataNormalizeSignature methods // Normalized.MetaDataSignature IMetaDataNormalizeSignature.AllocateNormalizedObject( MetaDataNormalizationContext context ) { Normalized.SignatureMethod res = new Normalized.SignatureMethod( 0 ); res.m_callingConvention = Normalized.SignatureMethod.CallingConventions.Default; context.GetNormalizedSignature ( m_returnType, out res.m_returnType, MetaDataNormalizationMode.Default ); context.GetNormalizedSignatureArray( m_parameters, out res.m_parameters, MetaDataNormalizationMode.Default ); return (Normalized.SignatureMethod)res.MakeUnique(); } // // Debug Methods // public override String ToString() { StringBuilder sb = new StringBuilder( "SignatureProperty(" ); sb.Append( m_returnType ); if(m_parameters.Length > 0) { sb.Append( ",(" ); for(int i = 0; i < m_parameters.Length; i++) { if(i != 0) { sb.Append( "," ); } sb.Append( m_parameters[i] ); } sb.Append( ")" ); } sb.Append( ")" ); return sb.ToString(); } } } ================================================ FILE: Zelig/Zelig/CompileTime/MetaData/Importer/SignatureTypeSpec.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // // // Originally based on the Bartok code base. // using System; using System.Collections.Generic; using System.Text; namespace Microsoft.Zelig.MetaData.Importer { public class SignatureTypeSpec : Signature, IMetaDataNormalizeSignature { // // State // private readonly SignatureType m_type; // // Constructor Methods // internal SignatureTypeSpec( SignatureType type ) { m_type = type; } internal static SignatureTypeSpec Parse( Parser parser , ArrayReader reader ) { // // Section 23.2.14 ECMA spec, Partition II // ElementTypes elementType = (ElementTypes)reader.PeekUInt8(); switch(elementType) { case ElementTypes.PTR: case ElementTypes.FNPTR: case ElementTypes.ARRAY: case ElementTypes.SZARRAY: case ElementTypes.GENERICINST: case ElementTypes.VAR: case ElementTypes.MVAR: break; default: throw IllegalMetaDataFormatException.Create( "Not a typespec signature: {0}", reader ); } SignatureType type = Signature.ParseType( parser, reader, Signature.ParseFlags.MustBeWholeSignature ); return new SignatureTypeSpec( type ); } // // IMetaDataNormalizeSignature methods // Normalized.MetaDataSignature IMetaDataNormalizeSignature.AllocateNormalizedObject( MetaDataNormalizationContext context ) { Normalized.SignatureType res; context.GetNormalizedSignature( m_type, out res, MetaDataNormalizationMode.Default ); return res; } // // Access Methods // public SignatureType TypeSpecType { get { return m_type; } } // // Debug Methods // public override String ToString() { return "SignatureTypeSpec(" + m_type + ")"; } } } ================================================ FILE: Zelig/Zelig/CompileTime/MetaData/Importer/SilentCompilationAbortException.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // // // Originally based on the Bartok code base. // using System; using System.Collections.Generic; using System.Collections; using System.Reflection; using System.Text; namespace Microsoft.Zelig.MetaData.Importer { public class SilentCompilationAbortException : AbstractMetaDataException { // // Constructor Methods // private SilentCompilationAbortException( String reason ) : base( reason ) { } // // Helper Methods // public static SilentCompilationAbortException Create( string format , params object[] args ) { return new SilentCompilationAbortException( String.Format( format, args ) ); } } } ================================================ FILE: Zelig/Zelig/CompileTime/MetaData/Importer/UnresolvedExternalReferenceException.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // // // Originally based on the Bartok code base. // using System; using System.Collections.Generic; using System.Collections; using System.Reflection; using System.Text; namespace Microsoft.Zelig.MetaData.Importer { public class UnresolvedExternalReferenceException : AbstractMetaDataException { // // State // public readonly object Context; // // Constructor Methods // private UnresolvedExternalReferenceException( object context , String reason ) : base( reason ) { this.Context = context; } // // Helper Methods // public static UnresolvedExternalReferenceException Create( object context , string format , params object[] args ) { return new UnresolvedExternalReferenceException( context, String.Format( format, args ) ); } } } ================================================ FILE: Zelig/Zelig/CompileTime/MetaData/MetaData.UnitTest/Bench.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // namespace Microsoft.Zelig.MetaData.UnitTest { using System; using System.Collections.Generic; using System.Text; using Microsoft.Zelig.MetaData; class Bench { public static void Main( string[] args ) { if(args != null) { foreach(string arg in args) { switch(arg) { case "PELoaderTester": new PELoaderTester().Run( args ); break; case "PDBFileTester": new PDBFileTester().Run( args ); break; case "CompressionTester": new CompressionTester().Run( args ); break; case "MetaDataParserTester": new MetaDataParserTester().Run( args ); break; case "MetaDataResolverTester": new MetaDataResolverTester().Run( args ); break; } } } } } } ================================================ FILE: Zelig/Zelig/CompileTime/MetaData/MetaData.UnitTest/CompressionTester.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // namespace Microsoft.Zelig.MetaData.UnitTest { using System; using System.Collections.Generic; using System.Text; using Microsoft.Zelig.MetaData; using Microsoft.Zelig.Test; class CompressionTester : TestBase { override public TestResult Run( string[] args ) { string currentDir = System.Environment.CurrentDirectory; Compress( Expand( currentDir + @"\Test\TestPayload__CLR1_1__VanillaSingleClass.dll" ) ); foreach(string file in System.IO.Directory.GetFiles( Expand( @"%WINDIR%\Microsoft.NET\Framework\v2.0.50727" ), "*.dll" )) { try { Compress( file ); } catch(Importer.PELoader.IllegalPEFormatException) { } catch(Exception e) { Console.WriteLine( "Error while loading {0}: {1}", file, e ); } } return TestResult.Pass; } static string Expand( string file ) { return Environment.ExpandEnvironmentVariables( file ); } static void Compress( string file ) { byte[] image = System.IO.File.ReadAllBytes( file ); file = System.IO.Path.GetFileName( file ); byte[] spacedImage = new byte[image.Length * 2]; for(int i = 0; i < image.Length; i++) { spacedImage[i*2] = image[i]; } byte[] imageC = Compress( image ); byte[] spacedImageC = Compress( spacedImage ); Console.WriteLine( "{0,-48} O:{1,7} C:{2,7}/{3,7} Loss:{4,3}", file, image.Length, imageC.Length, spacedImageC.Length, Math.Round( ((double)spacedImageC.Length / (double)imageC.Length - 1) * 100 ) ); } static byte[] Compress( byte[] buf ) { System.IO.MemoryStream ms = new System.IO.MemoryStream(); System.IO.Compression.GZipStream gzip = new System.IO.Compression.GZipStream( ms, System.IO.Compression.CompressionMode.Compress ); gzip.Write( buf, 0, buf.Length ); gzip.Flush(); return ms.ToArray(); } } } ================================================ FILE: Zelig/Zelig/CompileTime/MetaData/MetaData.UnitTest/MetaData.UnitTest.csproj ================================================  Debug AnyCPU 9.0.21022 2.0 {186F31A3-EF89-4A25-B2D5-20060606AA02} Exe Properties Microsoft.Zelig.MetaData.UnitTest Microsoft.Zelig.MetaData.UnitTest $(LlilumBuildRoot)\Host\obj\$(MSBuildProjectName)\ v4.5 true full false $(LlilumBuildRoot)\Host\bin\$(Configuration)\ DEBUG;TRACE prompt 4 false true AllRules.ruleset x86 false pdbonly true $(LlilumBuildRoot)\Host\bin\$(Configuration)\ TRACE prompt 4 false true AllRules.ruleset x86 false $(LlilumBuildRoot)\Host\bin\$(Configuration)\ TRACE;DEBUG x86 true false 3.5 {b649b569-516b-4c88-a7b1-ebd02e12dd99} Test_Common {186f31a3-ef89-4a25-b2d5-20060404aa01} Importer {186f31a3-ef89-4a25-b2d5-20060510aa01} Normalized ================================================ FILE: Zelig/Zelig/CompileTime/MetaData/MetaData.UnitTest/MetaDataParserTester.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // namespace Microsoft.Zelig.MetaData.UnitTest { using System; using System.Collections.Generic; using System.Text; using Microsoft.Zelig.MetaData; using Microsoft.Zelig.Test; class MetaDataParserTester : TestBase, ISymbolResolverHelper { override public TestResult Run( string[] args ) { Importer.MetaData md; MetaDataParserTester pThis; pThis = new MetaDataParserTester(); string currentDir = System.Environment.CurrentDirectory; md = pThis.LoadAssembly( Expand( currentDir + @"\Test\TestPayload__CLR1_1__VanillaSingleClass.dll" ) ); md = pThis.LoadAssembly( Expand( @"%WINDIR%\Microsoft.NET\Framework\v2.0.50727\mscorlib.dll" ) ); foreach(string file in System.IO.Directory.GetFiles( Expand( @"%WINDIR%\Microsoft.NET\Framework\v2.0.50727" ), "*.dll" )) { try { Console.WriteLine( "Parsing {0}", file ); md = pThis.LoadAssembly( file ); } catch(Importer.PELoader.MissingCLRheaderException e) { Console.WriteLine( "CLR header is missing, nothing to parse {0}: {1}", file, e); } catch(Importer.PELoader.IllegalPEFormatException e) { Console.WriteLine( "Error while parsing {0}: {1}", file, e); } catch(Exception e) { Console.WriteLine( "Error while loading {0}: {1}", file, e ); } } return TestResult.Pass; } static string Expand( string file ) { return Environment.ExpandEnvironmentVariables( file ); } private Microsoft.Zelig.MetaData.Importer.MetaData LoadAssembly( string file ) { byte[] image = System.IO.File.ReadAllBytes( file ); Importer.PELoader pe = new Importer.PELoader( file, image ); Importer.MetaData md = Importer.MetaData.loadMetaData( file, this, pe, Importer.MetaDataLoaderFlags.LoadCode | Importer.MetaDataLoaderFlags.LoadDebugInfo ); return md; } //--// Importer.PdbInfo.PdbFile ISymbolResolverHelper.ResolveAssemblySymbols( string file ) { try { file = System.IO.Path.GetDirectoryName( file ) + @"\" + System.IO.Path.GetFileNameWithoutExtension( file ) + ".pdb"; if(System.IO.File.Exists( file )) { byte[] image = System.IO.File.ReadAllBytes( file ); Importer.PdbInfo.PdbFile pdbFile = new Importer.PdbInfo.PdbFile( new Importer.ArrayReader( image ) ); return pdbFile; } } catch { } return null; } } } ================================================ FILE: Zelig/Zelig/CompileTime/MetaData/MetaData.UnitTest/MetaDataResolverTester.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // namespace Microsoft.Zelig.MetaData.UnitTest { using System; using System.Collections.Generic; using System.Text; using System.IO; using Microsoft.Zelig.MetaData; using Microsoft.Zelig.Test; class MetaDataResolverTester : TestBase, IMetaDataResolverHelper, ISymbolResolverHelper { // // State // private string baseFile; override public TestResult Run( string[] args ) { MetaDataResolverTester pThis; string currentDir = System.Environment.CurrentDirectory; pThis = new MetaDataResolverTester(); pThis.LoadAndResolve( Expand( currentDir + @"\Test\TestPayload__CLR1_1__VanillaSingleClass.dll" ), fDump: true ); pThis.LoadAndResolve( Expand( @"%WINDIR%\Microsoft.NET\Framework\v2.0.50727\mscorlib.dll" ), fDump : true ); return TestResult.Pass; } static string Expand( string file ) { return Environment.ExpandEnvironmentVariables( file ); } private MetaDataResolver LoadAndResolve( string file , bool fDump ) { this.baseFile = file; Importer.MetaData md = LoadAssembly( file ); MetaDataResolver resolver = new Zelig.MetaData.MetaDataResolver( this ); resolver.Add( md ); resolver.ResolveAll(); //--// if(fDump) { DirectoryInfo di = Directory.CreateDirectory( md.Assembly.Name ); string oldCD = Environment.CurrentDirectory; Environment.CurrentDirectory = di.FullName; foreach(Normalized.MetaDataAssembly asmlNormalized in resolver.NormalizedAssemblies) { using(MetaDataDumper writer = new MetaDataDumper( asmlNormalized.Name, asmlNormalized.Version )) { writer.Process( asmlNormalized, true ); } } Environment.CurrentDirectory = oldCD; } return resolver; } private Importer.MetaData LoadAssembly( string file ) { byte[] image = System.IO.File.ReadAllBytes( file ); Importer.PELoader pe = new Importer.PELoader( file, image ); Importer.MetaData md = Importer.MetaData.loadMetaData( file, this, pe, Importer.MetaDataLoaderFlags.LoadCode | Importer.MetaDataLoaderFlags.LoadDebugInfo ); return md; } //--// Importer.PdbInfo.PdbFile ISymbolResolverHelper.ResolveAssemblySymbols( string file ) { try { file = System.IO.Path.GetDirectoryName( file ) + @"\" + System.IO.Path.GetFileNameWithoutExtension( file ) + ".pdb"; //// if(System.IO.Path.GetFileNameWithoutExtension( file ) == "mscorlib") //// { //// file = @"z:\VS_Symbols_Cache\mscorlib.pdb\06A826D298CB41A3B63D7BDACDDAF9321\mscorlib.pdb"; //// } if(System.IO.File.Exists( file )) { byte[] image = System.IO.File.ReadAllBytes( file ); Importer.PdbInfo.PdbFile pdbFile = new Importer.PdbInfo.PdbFile( new Importer.ArrayReader( image ) ); return pdbFile; } } catch { } return null; } Importer.MetaData IMetaDataResolverHelper.ResolveAssemblyReference( string name , MetaDataVersion ver ) { Importer.MetaData md; md = CheckAndLoad( System.IO.Path.GetDirectoryName( baseFile ), name, ver ); if(md != null) { return md; } //md = CheckAndLoad( Expand( @"%WINDIR%\Microsoft.NET\Framework\v1.1.4322" ), name, ver ); md = CheckAndLoad( Expand( @"%WINDIR%\Microsoft.NET\Framework\v2.0.50727" ), name, ver ); if(md != null) { return md; } return null; } Importer.MetaData CheckAndLoad( string dir , string name , MetaDataVersion ver ) { string file = dir + @"\" + name + ".dll"; if(System.IO.File.Exists( file )) { try { Importer.MetaData md = LoadAssembly( file ); if(md.Assembly.Name == name && md.Assembly.Version.IsCompatible( ver, false )) { return md; } } catch { } } return null; } } } ================================================ FILE: Zelig/Zelig/CompileTime/MetaData/MetaData.UnitTest/PDBFileTester.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // namespace Microsoft.Zelig.MetaData.UnitTest { using System; using System.Collections.Generic; using System.Text; using Microsoft.Zelig.MetaData.Importer; using Microsoft.Zelig.MetaData.Importer.PdbInfo; using Microsoft.Zelig.Test; class PDBFileTester : TestBase { override public TestResult Run( string[] args ) { string currentDir = System.Environment.CurrentDirectory; LoadSymbols( Expand( currentDir + @"\Test\TestPayload__CLR1_1__VanillaSingleClass.pdb" ) ); return TestResult.Pass; } static string Expand( string file ) { return Environment.ExpandEnvironmentVariables( file ); } static PdbFunction[] LoadSymbols( string file ) { byte[] image = System.IO.File.ReadAllBytes( file ); PdbFile pdbFile = new PdbFile( new ArrayReader( image ) ); PdbFunction[] funcs = pdbFile.Functions; for(int f = 0; f < funcs.Length; f++) { Dump( funcs[f], 0 ); } return funcs; } //--// public static void Dump( PdbFunction f , int indent ) { string pad = new String( ' ', indent ); Console.WriteLine( " {0}Func: [{1}] addr={2:x4}:{3:x8} len={4:x4} token={5:x8}", pad, f.Name, f.Segment, f.Address, f.Length, f.Token ); if(f.Metadata != null) { Console.Write( " {0} Meta: [", pad ); for(int i = 0; i < f.Metadata.Length; i++) { Console.Write( "{0:x2}", f.Metadata[i] ); } Console.WriteLine( "]" ); } if(f.Scopes != null) { for(int i = 0; i < f.Scopes.Length; i++) { Dump( f.Scopes[i], indent + 1 ); } } if(f.LineBlocks != null) { for(int i = 0; i < f.LineBlocks.Length; i++) { Dump( f.LineBlocks[i], indent + 1 ); } } } public static void Dump( PdbScope s , int indent ) { string pad = new String( ' ', indent ); Console.WriteLine( " {0}Scope: addr={1:x4}:{2:x8} len={3:x4}", pad, s.Segment, s.Address, s.Length ); if(s.Slots != null) { for(int i = 0; i < s.Slots.Length; i++) { Dump( s.Slots[i], indent + 1 ); } } if(s.Scopes != null) { for(int i = 0; i < s.Scopes.Length; i++) { Dump( s.Scopes[i], indent + 1 ); } } } public static void Dump( PdbSlot s , int indent ) { string pad = new String( ' ', indent ); Console.WriteLine( " {0}Slot: {1,2} [{2}] addr={3:x4}:{4:x8}", pad, s.Slot, s.Name, s.Segment, s.Address ); } public static void Dump( PdbSource s , int indent ) { string pad = new String( ' ', indent ); Console.WriteLine( " {0}[{1}] : {2}", pad, s.Name, s.Index ); } public static void Dump( PdbLines s , int indent ) { string pad = new String( ' ', indent ); Console.WriteLine( " {0}[{1}]", pad, s.File.Name ); for(int i = 0; i < s.Lines.Length; i++) { Dump( s.Lines[i], indent + 1 ); } } public static void Dump( PdbLine s , int indent ) { string pad = new String( ' ', indent ); if(s.LineBegin == 0xFEEFEE && s.ColumnBegin == 0 && s.ColumnEnd == 0) { Console.WriteLine( " {0}off={1:x8} #---------", pad, s.Offset, s.LineBegin, s.ColumnBegin ); } else { Console.WriteLine( " {0}off={1:x8} #{2,6},{3,2}", pad, s.Offset, s.LineBegin, s.ColumnBegin ); } } } } ================================================ FILE: Zelig/Zelig/CompileTime/MetaData/MetaData.UnitTest/PELoaderTester.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // namespace Microsoft.Zelig.MetaData.UnitTest { using System; using System.Collections.Generic; using System.Text; using Microsoft.Zelig.MetaData; using Microsoft.Zelig.Test; class PELoaderTester : TestBase { public PELoaderTester() { } override public TestResult Run( string[] args ) { string currentDir = System.Environment.CurrentDirectory; LoadPE( Expand( @"%WINDIR%\Microsoft.NET\Framework\v2.0.50727\mscorlib.dll" ) ); LoadPE( Expand( currentDir + @"\Test\TestPayload__CLR1_1__VanillaSingleClass.dll" ) ); return TestResult.Pass; } static string Expand( string file ) { return Environment.ExpandEnvironmentVariables( file ); } static void LoadPE( string file ) { byte[] image = System.IO.File.ReadAllBytes( file ); Importer.PELoader pe = new Zelig.MetaData.Importer.PELoader( file, image ); Importer.LogWriter log = new Zelig.MetaData.Importer.LogWriter( Console.Out ); pe.DumpHeader( log ); } } } ================================================ FILE: Zelig/Zelig/CompileTime/MetaData/MetaData.UnitTest/Properties/AssemblyInfo.cs ================================================ using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; // General Information about an assembly is controlled through the following // set of attributes. Change these attribute values to modify the information // associated with an assembly. [assembly: AssemblyTitle( "Microsoft.Zelig.MetaData.UnitTest" )] [assembly: AssemblyDescription( "" )] [assembly: AssemblyConfiguration( "" )] [assembly: AssemblyCompany( "Microsoft" )] [assembly: AssemblyProduct( "Microsoft.Zelig.MetaData.UnitTest" )] [assembly: AssemblyCopyright( "Copyright © Microsoft 2006" )] [assembly: AssemblyTrademark( "" )] [assembly: AssemblyCulture( "" )] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible( false )] //// The following GUID is for the ID of the typelib if this project is exposed to COM //[assembly: Guid( "012e8fb6-008e-45a0-ba5d-64b07a84aa95" )] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Revision and Build Numbers // by using the '*' as shown below: [assembly: AssemblyVersion( "1.0.0.0" )] [assembly: AssemblyFileVersion( "1.0.0.0" )] ================================================ FILE: Zelig/Zelig/CompileTime/MetaData/Normalized/EHClause.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // namespace Microsoft.Zelig.MetaData.Normalized { using System; // // Don't remove "sealed" attribute unless you read comments on Equals method. // public sealed class EHClause : IMetaDataUnique { public static readonly EHClause[] SharedEmptyArray = new EHClause[0]; // // Internal Classes // public enum ExceptionFlag { None = 0x0000, Filter = 0x0001, Finally = 0x0002, Fault = 0x0004, } // // State // internal ExceptionFlag m_flags; internal int m_tryOffset; internal int m_tryEnd; internal int m_handlerOffset; internal int m_handlerEnd; internal int m_filterOffset; internal MetaDataTypeDefinitionAbstract m_classObject; // // Constructor Methods // internal EHClause() { } // // MetaDataEquality Methods // public override bool Equals( object obj ) { if(obj is EHClause) // Since the class is sealed (no subclasses allowed), there's no need to compare using .GetType() { EHClause other = (EHClause)obj; if(m_flags == other.m_flags && m_tryOffset == other.m_tryOffset && m_tryEnd == other.m_tryEnd && m_handlerOffset == other.m_handlerOffset && m_handlerEnd == other.m_handlerEnd && m_filterOffset == other.m_filterOffset && m_classObject == other.m_classObject ) { return true; } } return false; } public override int GetHashCode() { return m_tryOffset << 12 ^ m_tryEnd ; } // // Access Methods // public ExceptionFlag Flags { get { return m_flags; } } public int TryOffset { get { return m_tryOffset; } } public int TryEnd { get { return m_tryEnd; } } public int HandlerOffset { get { return m_handlerOffset; } } public int HandlerEnd { get { return m_handlerEnd; } } public int FilterOffset { get { return m_filterOffset; } } public MetaDataTypeDefinitionAbstract TypeObject { get { return m_classObject; } } // // Debug Methods // public override String ToString() { System.Text.StringBuilder sb = new System.Text.StringBuilder( "EHClause(" ); sb.Append ( m_flags ); sb.AppendFormat( ",try({0:x},{1:x})" , m_tryOffset , m_tryEnd ); sb.AppendFormat( ",handler({0:x},{1:x})", m_handlerOffset, m_handlerEnd ); sb.AppendFormat( ",filter({0:x})" , m_filterOffset ); sb.Append ( "," ); sb.Append ( m_classObject ); sb.Append( ")" ); return sb.ToString(); } } } ================================================ FILE: Zelig/Zelig/CompileTime/MetaData/Normalized/Instruction.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // namespace Microsoft.Zelig.MetaData.Normalized { using System; // // Don't remove "sealed" attribute unless you read comments on Equals method. // public sealed class Instruction : IMetaDataUnique { public enum Opcode : short { NOP , BREAK , LDARG_0 , LDARG_1 , LDARG_2 , LDARG_3 , LDLOC_0 , LDLOC_1 , LDLOC_2 , LDLOC_3 , STLOC_0 , STLOC_1 , STLOC_2 , STLOC_3 , LDARG_S , LDARGA_S , STARG_S , LDLOC_S , LDLOCA_S , STLOC_S , LDNULL , LDC_I4_M1 , LDC_I4_0 , LDC_I4_1 , LDC_I4_2 , LDC_I4_3 , LDC_I4_4 , LDC_I4_5 , LDC_I4_6 , LDC_I4_7 , LDC_I4_8 , LDC_I4_S , LDC_I4 , LDC_I8 , LDC_R4 , LDC_R8 , UNUSED49 , DUP , POP , JMP , CALL , CALLI , RET , BR_S , BRFALSE_S , BRTRUE_S , BEQ_S , BGE_S , BGT_S , BLE_S , BLT_S , BNE_UN_S , BGE_UN_S , BGT_UN_S , BLE_UN_S , BLT_UN_S , BR , BRFALSE , BRTRUE , BEQ , BGE , BGT , BLE , BLT , BNE_UN , BGE_UN , BGT_UN , BLE_UN , BLT_UN , SWITCH , LDIND_I1 , LDIND_U1 , LDIND_I2 , LDIND_U2 , LDIND_I4 , LDIND_U4 , LDIND_I8 , LDIND_I , LDIND_R4 , LDIND_R8 , LDIND_REF , STIND_REF , STIND_I1 , STIND_I2 , STIND_I4 , STIND_I8 , STIND_R4 , STIND_R8 , ADD , SUB , MUL , DIV , DIV_UN , REM , REM_UN , AND , OR , XOR , SHL , SHR , SHR_UN , NEG , NOT , CONV_I1 , CONV_I2 , CONV_I4 , CONV_I8 , CONV_R4 , CONV_R8 , CONV_U4 , CONV_U8 , CALLVIRT , CPOBJ , LDOBJ , LDSTR , NEWOBJ , CASTCLASS , ISINST , CONV_R_UN , UNUSED58 , UNUSED1 , UNBOX , THROW , LDFLD , LDFLDA , STFLD , LDSFLD , LDSFLDA , STSFLD , STOBJ , CONV_OVF_I1_UN , CONV_OVF_I2_UN , CONV_OVF_I4_UN , CONV_OVF_I8_UN , CONV_OVF_U1_UN , CONV_OVF_U2_UN , CONV_OVF_U4_UN , CONV_OVF_U8_UN , CONV_OVF_I_UN , CONV_OVF_U_UN , BOX , NEWARR , LDLEN , LDELEMA , LDELEM_I1 , LDELEM_U1 , LDELEM_I2 , LDELEM_U2 , LDELEM_I4 , LDELEM_U4 , LDELEM_I8 , LDELEM_I , LDELEM_R4 , LDELEM_R8 , LDELEM_REF , STELEM_I , STELEM_I1 , STELEM_I2 , STELEM_I4 , STELEM_I8 , STELEM_R4 , STELEM_R8 , STELEM_REF , LDELEM , STELEM , UNBOX_ANY , UNUSED5 , UNUSED6 , UNUSED7 , UNUSED8 , UNUSED9 , UNUSED10 , UNUSED11 , UNUSED12 , UNUSED13 , UNUSED14 , UNUSED15 , UNUSED16 , UNUSED17 , CONV_OVF_I1 , CONV_OVF_U1 , CONV_OVF_I2 , CONV_OVF_U2 , CONV_OVF_I4 , CONV_OVF_U4 , CONV_OVF_I8 , CONV_OVF_U8 , UNUSED50 , UNUSED18 , UNUSED19 , UNUSED20 , UNUSED21 , UNUSED22 , UNUSED23 , REFANYVAL , CKFINITE , UNUSED24 , UNUSED25 , MKREFANY , UNUSED59 , UNUSED60 , UNUSED61 , UNUSED62 , UNUSED63 , UNUSED64 , UNUSED65 , UNUSED66 , UNUSED67 , LDTOKEN , CONV_U2 , CONV_U1 , CONV_I , CONV_OVF_I , CONV_OVF_U , ADD_OVF , ADD_OVF_UN , MUL_OVF , MUL_OVF_UN , SUB_OVF , SUB_OVF_UN , ENDFINALLY , LEAVE , LEAVE_S , STIND_I , CONV_U , UNUSED26 , UNUSED27 , UNUSED28 , UNUSED29 , UNUSED30 , UNUSED31 , UNUSED32 , UNUSED33 , UNUSED34 , UNUSED35 , UNUSED36 , UNUSED37 , UNUSED38 , UNUSED39 , UNUSED40 , UNUSED41 , UNUSED42 , UNUSED43 , UNUSED44 , UNUSED45 , UNUSED46 , UNUSED47 , UNUSED48 , PREFIX7 , PREFIX6 , PREFIX5 , PREFIX4 , PREFIX3 , PREFIX2 , PREFIX1 , PREFIXREF , ARGLIST , CEQ , CGT , CGT_UN , CLT , CLT_UN , LDFTN , LDVIRTFTN , UNUSED56 , LDARG , LDARGA , STARG , LDLOC , LDLOCA , STLOC , LOCALLOC , UNUSED57 , ENDFILTER , UNALIGNED , VOLATILE , TAILCALL , INITOBJ , CONSTRAINED , CPBLK , INITBLK , NO , RETHROW , UNUSED51 , SIZEOF , REFANYTYPE , READONLY , UNUSED53 , UNUSED54 , UNUSED55 , UNUSED70 , ILLEGAL , MACRO_END , COUNT } public enum OpcodeOperand { None = 0x00000000, Var = 0x00000001, Int = 0x00000002, Float = 0x00000003, Branch = 0x00000004, Method = 0x00000005, Field = 0x00000006, Type = 0x00000007, String = 0x00000008, Sig = 0x00000009, Token = 0x0000000A, Switch = 0x0000000B, Illegal = 0x0000000F, } public enum OpcodeSize { None = 0x00000000, Byte = 0x00000010, Short = 0x00000020, Word = 0x00000030, DWord = 0x00000040, Variable = 0x00000050, Implicit_M1 = 0x00000060, Implicit_0 = 0x00000070, Implicit_1 = 0x00000080, Implicit_2 = 0x00000090, Implicit_3 = 0x000000A0, Implicit_4 = 0x000000B0, Implicit_5 = 0x000000C0, Implicit_6 = 0x000000D0, Implicit_7 = 0x000000E0, Implicit_8 = 0x000000F0, } public enum OpcodeFlowControl { None = 0x00000000, ConditionalControl = 0x00000100, UnconditionalControl = 0x00000200, ExceptionHandling = 0x00000300, } public enum OpcodeAction { Invalid = 0x00000000, Load = 0x00001000, // OpcodeActionTarget.* LoadAddress = 0x00002000, // OpcodeActionTarget.* LoadIndirect = 0x00003000, // OpcodeActionType.* LoadElement = 0x00004000, // OpcodeActionType.* LoadElementAddress = 0x00005000, // OpcodeActionType.* Store = 0x00006000, // OpcodeActionTarget.* StoreIndirect = 0x00007000, // OpcodeActionType.* StoreElement = 0x00008000, // OpcodeActionType.* Stack = 0x00009000, // OpcodeActionStack.* Jump = 0x0000A000, Call = 0x0000B000, // OpcodeActionCall.* Return = 0x0000C000, Branch = 0x0000D000, // OpcodeActionCond.* Unsigned? ALU = 0x0000E000, // OpcodeActionALU.* Unsigned? Overflow? Convert = 0x0000F000, // OpcodeActionType.* Unsigned? Overflow? Object = 0x00010000, // OpcodeActionObject.* TypedRef = 0x00011000, // OpcodeActionTypedRef.* EH = 0x00012000, // OpcodeActionExceptionHandling.* Set = 0x00013000, // OpcodeActionCond.* Unsigned? Modifier = 0x00014000, // OpcodeActionModifier.* Debug = 0x00015000, // OpcodeActionDebug.* } public enum OpcodeActionDebug { Breakpoint = 0x00000000, } public enum OpcodeActionTarget { Local = 0x00000000, Argument = 0x00100000, Null = 0x00200000, Constant = 0x00300000, Field = 0x00400000, StaticField = 0x00500000, Token = 0x00600000, String = 0x00700000, } public enum OpcodeActionStack { Dup = 0x00000000, Pop = 0x00100000, LocAlloc = 0x00200000, ArgList = 0x00300000, } public enum OpcodeActionCall { Direct = 0x00000000, Indirect = 0x00100000, Virtual = 0x00200000, } public enum OpcodeActionObject { New = 0x00000000, NewArr = 0x00100000, LdLen = 0x00200000, Cast = 0x00300000, IsInst = 0x00400000, Box = 0x00500000, Unbox = 0x00600000, UnboxAny = 0x00700000, LdFtn = 0x00800000, LdVirtFtn = 0x00900000, InitObj = 0x00A00000, LdObj = 0x00B00000, CpObj = 0x00C00000, StObj = 0x00D00000, InitBlk = 0x00E00000, CpBlk = 0x00F00000, SizeOf = 0x01000000, } public enum OpcodeActionTypedReference { RefAnyVal = 0x00000000, MkRefAny = 0x00100000, RefAnyType = 0x00200000, } public enum OpcodeActionExceptionHandling { Throw = 0x00000000, EndFinally = 0x00100000, Leave = 0x00200000, EndFilter = 0x00300000, ReThrow = 0x00400000, } public enum OpcodeActionCondition { ALWAYS = 0x00000000, FALSE = 0x00100000, TRUE = 0x00200000, EQ = 0x00300000, GE = 0x00400000, GT = 0x00500000, LE = 0x00600000, LT = 0x00700000, NE = 0x00800000, Val = 0x00900000, } public enum OpcodeActionALU { ADD = 0x00000000, SUB = 0x00100000, MUL = 0x00200000, DIV = 0x00300000, REM = 0x00400000, AND = 0x00500000, OR = 0x00600000, XOR = 0x00700000, SHL = 0x00800000, SHR = 0x00900000, NEG = 0x00A00000, NOT = 0x00B00000, NOP = 0x00C00000, FINITE = 0x00D00000, } public enum OpcodeActionModifier { Unaligned = 0x00000000, Volatile = 0x00100000, TailCall = 0x00200000, Constrained = 0x00300000, NoCheck = 0x00400000, Readonly = 0x00500000, } public enum OpcodeActionType { I1 = 0x00000000, U1 = 0x00100000, I2 = 0x00200000, U2 = 0x00300000, I4 = 0x00400000, U4 = 0x00500000, I8 = 0x00600000, U8 = 0x00700000, I = 0x00800000, U = 0x00900000, R4 = 0x00A00000, R8 = 0x00B00000, R = 0x00C00000, String = 0x00D00000, Reference = 0x00E00000, Token = 0x00F00000, } [Flags] internal enum Format { None = OpcodeOperand.None , Var = OpcodeOperand.Var , Int = OpcodeOperand.Int , Float = OpcodeOperand.Float , Branch = OpcodeOperand.Branch , Method = OpcodeOperand.Method , Field = OpcodeOperand.Field , Type = OpcodeOperand.Type , String = OpcodeOperand.String , Sig = OpcodeOperand.Sig , Token = OpcodeOperand.Token , Switch = OpcodeOperand.Switch , Illegal = OpcodeOperand.Illegal, Operand_MASK = 0x0000000F, SizeNone = OpcodeSize.None , SizeByte = OpcodeSize.Byte , SizeShort = OpcodeSize.Short , SizeWord = OpcodeSize.Word , SizeDWord = OpcodeSize.DWord , SizeVariable = OpcodeSize.Variable , SizeImplicit_M1 = OpcodeSize.Implicit_M1, SizeImplicit_0 = OpcodeSize.Implicit_0 , SizeImplicit_1 = OpcodeSize.Implicit_1 , SizeImplicit_2 = OpcodeSize.Implicit_2 , SizeImplicit_3 = OpcodeSize.Implicit_3 , SizeImplicit_4 = OpcodeSize.Implicit_4 , SizeImplicit_5 = OpcodeSize.Implicit_5 , SizeImplicit_6 = OpcodeSize.Implicit_6 , SizeImplicit_7 = OpcodeSize.Implicit_7 , SizeImplicit_8 = OpcodeSize.Implicit_8 , Size_MASK = 0x000000F0, ConditionalControl = OpcodeFlowControl.ConditionalControl , UnconditionalControl = OpcodeFlowControl.UnconditionalControl, ExceptionHandling = OpcodeFlowControl.ExceptionHandling , FlowControl_MASK = 0x00000300, //--// Unused_0x00000400 = 0x00000400, Unused_0x00000800 = 0x00000800, Action_Invalid = OpcodeAction.Invalid , Action_Load = OpcodeAction.Load , Action_LoadAddress = OpcodeAction.LoadAddress , Action_LoadIndirect = OpcodeAction.LoadIndirect , Action_LoadElement = OpcodeAction.LoadElement , Action_LoadElementAddress = OpcodeAction.LoadElementAddress , Action_Store = OpcodeAction.Store , Action_StoreIndirect = OpcodeAction.StoreIndirect , Action_StoreElement = OpcodeAction.StoreElement , Action_Stack = OpcodeAction.Stack , Action_Jump = OpcodeAction.Jump , Action_Call = OpcodeAction.Call , Action_Return = OpcodeAction.Return , Action_Branch = OpcodeAction.Branch , Action_ALU = OpcodeAction.ALU , Action_Convert = OpcodeAction.Convert , Action_Object = OpcodeAction.Object , Action_TypedRef = OpcodeAction.TypedRef , Action_EH = OpcodeAction.EH , Action_Set = OpcodeAction.Set , Action_Modifier = OpcodeAction.Modifier , Action_Debug = OpcodeAction.Debug , Action_MASK = 0x0001F000, Unused_0x00020000 = 0x00020000, Unused_0x00040000 = 0x00040000, Unused_0x00080000 = 0x00080000, //--// Debug_Breakpoint = OpcodeActionDebug.Breakpoint, Debug_MASK = 0x01F00000, Target_Local = OpcodeActionTarget.Local , Target_Argument = OpcodeActionTarget.Argument , Target_Null = OpcodeActionTarget.Null , Target_Constant = OpcodeActionTarget.Constant , Target_Field = OpcodeActionTarget.Field , Target_StaticField = OpcodeActionTarget.StaticField, Target_Token = OpcodeActionTarget.Token , Target_String = OpcodeActionTarget.String , Target_MASK = 0x01F00000, Stack_Dup = OpcodeActionStack.Dup , Stack_Pop = OpcodeActionStack.Pop , Stack_LocAlloc = OpcodeActionStack.LocAlloc, Stack_ArgList = OpcodeActionStack.ArgList , Stack_MASK = 0x01F00000, Call_Direct = OpcodeActionCall.Direct , Call_Indirect = OpcodeActionCall.Indirect, Call_Virtual = OpcodeActionCall.Virtual , Call_MASK = 0x01F00000, Obj_New = OpcodeActionObject.New , Obj_NewArr = OpcodeActionObject.NewArr , Obj_LdLen = OpcodeActionObject.LdLen , Obj_Cast = OpcodeActionObject.Cast , Obj_IsInst = OpcodeActionObject.IsInst , Obj_Box = OpcodeActionObject.Box , Obj_Unbox = OpcodeActionObject.Unbox , Obj_UnboxAny = OpcodeActionObject.UnboxAny , Obj_LdFtn = OpcodeActionObject.LdFtn , Obj_LdVirtFtn = OpcodeActionObject.LdVirtFtn, Obj_InitObj = OpcodeActionObject.InitObj , Obj_LdObj = OpcodeActionObject.LdObj , Obj_CpObj = OpcodeActionObject.CpObj , Obj_StObj = OpcodeActionObject.StObj , Obj_InitBlk = OpcodeActionObject.InitBlk , Obj_CpBlk = OpcodeActionObject.CpBlk , Obj_SizeOf = OpcodeActionObject.SizeOf , Obj_MASK = 0x01F00000, TypedRef_RefAnyVal = OpcodeActionTypedReference.RefAnyVal , TypedRef_MkRefAny = OpcodeActionTypedReference.MkRefAny , TypedRef_RefAnyType = OpcodeActionTypedReference.RefAnyType, TypedRef_MASK = 0x01F00000, EH_Throw = OpcodeActionExceptionHandling.Throw , EH_EndFinally = OpcodeActionExceptionHandling.EndFinally, EH_Leave = OpcodeActionExceptionHandling.Leave , EH_EndFilter = OpcodeActionExceptionHandling.EndFilter , EH_ReThrow = OpcodeActionExceptionHandling.ReThrow , EH_MASK = 0x01F00000, Cond_ALWAYS = OpcodeActionCondition.ALWAYS, Cond_FALSE = OpcodeActionCondition.FALSE , Cond_TRUE = OpcodeActionCondition.TRUE , Cond_EQ = OpcodeActionCondition.EQ , Cond_GE = OpcodeActionCondition.GE , Cond_GT = OpcodeActionCondition.GT , Cond_LE = OpcodeActionCondition.LE , Cond_LT = OpcodeActionCondition.LT , Cond_NE = OpcodeActionCondition.NE , Cond_Val = OpcodeActionCondition.Val , Cond_MASK = 0x01F00000, Op_ADD = OpcodeActionALU.ADD , Op_SUB = OpcodeActionALU.SUB , Op_MUL = OpcodeActionALU.MUL , Op_DIV = OpcodeActionALU.DIV , Op_REM = OpcodeActionALU.REM , Op_AND = OpcodeActionALU.AND , Op_OR = OpcodeActionALU.OR , Op_XOR = OpcodeActionALU.XOR , Op_SHL = OpcodeActionALU.SHL , Op_SHR = OpcodeActionALU.SHR , Op_NEG = OpcodeActionALU.NEG , Op_NOT = OpcodeActionALU.NOT , Op_NOP = OpcodeActionALU.NOP , Op_FINITE = OpcodeActionALU.FINITE, Op_MASK = 0x01F00000, Mod_Unaligned = OpcodeActionModifier.Unaligned , Mod_Volatile = OpcodeActionModifier.Volatile , Mod_TailCall = OpcodeActionModifier.TailCall , Mod_Constrained = OpcodeActionModifier.Constrained, Mod_NoCheck = OpcodeActionModifier.NoCheck , Mod_Readonly = OpcodeActionModifier.Readonly , Mod_MASK = 0x01F00000, Type_I1 = OpcodeActionType.I1 , Type_U1 = OpcodeActionType.U1 , Type_I2 = OpcodeActionType.I2 , Type_U2 = OpcodeActionType.U2 , Type_I4 = OpcodeActionType.I4 , Type_U4 = OpcodeActionType.U4 , Type_I8 = OpcodeActionType.I8 , Type_U8 = OpcodeActionType.U8 , Type_I = OpcodeActionType.I , Type_U = OpcodeActionType.U , Type_R4 = OpcodeActionType.R4 , Type_R8 = OpcodeActionType.R8 , Type_R = OpcodeActionType.R , Type_String = OpcodeActionType.String , Type_Reference = OpcodeActionType.Reference, Type_Token = OpcodeActionType.Token , Type_MASK = 0x01F00000, Unsigned = 0x02000000, Overflow = 0x04000000, Unused_0x08000000 = 0x08000000, Unused_0x10000000 = 0x10000000, Unused_0x20000000 = 0x20000000, Unused_0x40000000 = 0x40000000, //Unused_0x80000000 = 0x80000000, //--// // // Bytecode decoding. // NOP = Action_ALU | Op_NOP , BREAK = Action_Debug | Debug_Breakpoint , LDARGA = Action_LoadAddress | Target_Argument , LDARG = Action_Load | Target_Argument , STARG = Action_Store | Target_Argument , LDLOCA = Action_LoadAddress | Target_Local , LDLOC = Action_Load | Target_Local , STLOC = Action_Store | Target_Local , LDNULL = Action_Load | Target_Null , LDC = Action_Load | Target_Constant , DUP = Action_Stack | Stack_Dup , POP = Action_Stack | Stack_Pop , JMP = Action_Jump , CALL = Action_Call | Call_Direct , CALLI = Action_Call | Call_Indirect , RET = Action_Return , BR = Action_Branch | Cond_ALWAYS , BRFALSE = Action_Branch | Cond_FALSE , BRTRUE = Action_Branch | Cond_TRUE , BEQ = Action_Branch | Cond_EQ , BGE = Action_Branch | Cond_GE , BGT = Action_Branch | Cond_GT , BLE = Action_Branch | Cond_LE , BLT = Action_Branch | Cond_LT , BNE_UN = Action_Branch | Cond_NE | Unsigned , BGE_UN = Action_Branch | Cond_GE | Unsigned , BGT_UN = Action_Branch | Cond_GT | Unsigned , BLE_UN = Action_Branch | Cond_LE | Unsigned , BLT_UN = Action_Branch | Cond_LT | Unsigned , SWITCH = Action_Branch | Cond_Val , LDIND_I1 = Action_LoadIndirect | Type_I1 , LDIND_U1 = Action_LoadIndirect | Type_U1 , LDIND_I2 = Action_LoadIndirect | Type_I2 , LDIND_U2 = Action_LoadIndirect | Type_U2 , LDIND_I4 = Action_LoadIndirect | Type_I4 , LDIND_U4 = Action_LoadIndirect | Type_U4 , LDIND_I8 = Action_LoadIndirect | Type_I8 , LDIND_I = Action_LoadIndirect | Type_I , LDIND_R4 = Action_LoadIndirect | Type_R4 , LDIND_R8 = Action_LoadIndirect | Type_R8 , LDIND_REF = Action_LoadIndirect | Type_Reference , STIND_REF = Action_StoreIndirect | Type_Reference , STIND_I1 = Action_StoreIndirect | Type_I1 , STIND_I2 = Action_StoreIndirect | Type_I2 , STIND_I4 = Action_StoreIndirect | Type_I4 , STIND_I8 = Action_StoreIndirect | Type_I8 , STIND_R4 = Action_StoreIndirect | Type_R4 , STIND_R8 = Action_StoreIndirect | Type_R8 , ADD = Action_ALU | Op_ADD , SUB = Action_ALU | Op_SUB , MUL = Action_ALU | Op_MUL , DIV = Action_ALU | Op_DIV , DIV_UN = Action_ALU | Op_DIV | Unsigned , REM = Action_ALU | Op_REM , REM_UN = Action_ALU | Op_REM | Unsigned , AND = Action_ALU | Op_AND , OR = Action_ALU | Op_OR , XOR = Action_ALU | Op_XOR , SHL = Action_ALU | Op_SHL , SHR = Action_ALU | Op_SHR , SHR_UN = Action_ALU | Op_SHR | Unsigned , NEG = Action_ALU | Op_NEG , NOT = Action_ALU | Op_NOT , CONV_I1 = Action_Convert | Type_I1 , CONV_I2 = Action_Convert | Type_I2 , CONV_I4 = Action_Convert | Type_I4 , CONV_I8 = Action_Convert | Type_I8 , CONV_R4 = Action_Convert | Type_R4 , CONV_R8 = Action_Convert | Type_R8 , CONV_U4 = Action_Convert | Type_U4 , CONV_U8 = Action_Convert | Type_U8 , CALLVIRT = Action_Call | Call_Virtual , CPOBJ = Action_Object | Obj_CpObj , LDOBJ = Action_Object | Obj_LdObj , LDSTR = Action_Load | Target_String , NEWOBJ = Action_Object | Obj_New , CASTCLASS = Action_Object | Obj_Cast , ISINST = Action_Object | Obj_IsInst , CONV_R_UN = Action_Convert | Type_R | Unsigned , UNBOX = Action_Object | Obj_Unbox , THROW = Action_EH | EH_Throw , LDFLD = Action_Load | Target_Field , LDFLDA = Action_LoadAddress | Target_Field , STFLD = Action_Store | Target_Field , LDSFLD = Action_Load | Target_StaticField , LDSFLDA = Action_LoadAddress | Target_StaticField , STSFLD = Action_Store | Target_StaticField , STOBJ = Action_Object | Obj_StObj , CONV_OVF_I1_UN = Action_Convert | Type_I1 | Unsigned | Overflow, CONV_OVF_I2_UN = Action_Convert | Type_I2 | Unsigned | Overflow, CONV_OVF_I4_UN = Action_Convert | Type_I4 | Unsigned | Overflow, CONV_OVF_I8_UN = Action_Convert | Type_I8 | Unsigned | Overflow, CONV_OVF_U1_UN = Action_Convert | Type_R4 | Unsigned | Overflow, CONV_OVF_U2_UN = Action_Convert | Type_R8 | Unsigned | Overflow, CONV_OVF_U4_UN = Action_Convert | Type_U4 | Unsigned | Overflow, CONV_OVF_U8_UN = Action_Convert | Type_U8 | Unsigned | Overflow, CONV_OVF_I_UN = Action_Convert | Type_I | Unsigned | Overflow, CONV_OVF_U_UN = Action_Convert | Type_U | Unsigned | Overflow, BOX = Action_Object | Obj_Box , NEWARR = Action_Object | Obj_NewArr , LDLEN = Action_Object | Obj_LdLen , LDELEMA = Action_LoadElementAddress | Type_Token , LDELEM_I1 = Action_LoadElement | Type_I1 , LDELEM_U1 = Action_LoadElement | Type_U1 , LDELEM_I2 = Action_LoadElement | Type_I2 , LDELEM_U2 = Action_LoadElement | Type_U2 , LDELEM_I4 = Action_LoadElement | Type_I4 , LDELEM_U4 = Action_LoadElement | Type_U4 , LDELEM_I8 = Action_LoadElement | Type_I8 , LDELEM_I = Action_LoadElement | Type_I , LDELEM_R4 = Action_LoadElement | Type_R4 , LDELEM_R8 = Action_LoadElement | Type_R8 , LDELEM_REF = Action_LoadElement | Type_Reference , STELEM_I = Action_StoreElement | Type_I , STELEM_I1 = Action_StoreElement | Type_I1 , STELEM_I2 = Action_StoreElement | Type_I2 , STELEM_I4 = Action_StoreElement | Type_I4 , STELEM_I8 = Action_StoreElement | Type_I8 , STELEM_R4 = Action_StoreElement | Type_R4 , STELEM_R8 = Action_StoreElement | Type_R8 , STELEM_REF = Action_StoreElement | Type_Reference , LDELEM = Action_LoadElement | Type_Token , STELEM = Action_StoreElement | Type_Token , UNBOX_ANY = Action_Object | Obj_UnboxAny , CONV_OVF_I1 = Action_Convert | Type_I1 | Overflow, CONV_OVF_U1 = Action_Convert | Type_U1 | Overflow, CONV_OVF_I2 = Action_Convert | Type_I2 | Overflow, CONV_OVF_U2 = Action_Convert | Type_U2 | Overflow, CONV_OVF_I4 = Action_Convert | Type_I4 | Overflow, CONV_OVF_U4 = Action_Convert | Type_U4 | Overflow, CONV_OVF_I8 = Action_Convert | Type_I8 | Overflow, CONV_OVF_U8 = Action_Convert | Type_U8 | Overflow, REFANYVAL = Action_TypedRef | TypedRef_RefAnyVal , CKFINITE = Action_ALU | Op_FINITE , MKREFANY = Action_TypedRef | TypedRef_MkRefAny , LDTOKEN = Action_Load | Target_Token , CONV_U2 = Action_Convert | Type_U2 , CONV_U1 = Action_Convert | Type_U1 , CONV_I = Action_Convert | Type_I , CONV_OVF_I = Action_Convert | Type_I | Overflow, CONV_OVF_U = Action_Convert | Type_U | Overflow, ADD_OVF = Action_ALU | Op_ADD | Overflow, ADD_OVF_UN = Action_ALU | Op_ADD | Unsigned | Overflow, MUL_OVF = Action_ALU | Op_MUL | Overflow, MUL_OVF_UN = Action_ALU | Op_MUL | Unsigned | Overflow, SUB_OVF = Action_ALU | Op_SUB | Overflow, SUB_OVF_UN = Action_ALU | Op_SUB | Unsigned | Overflow, ENDFINALLY = Action_EH | EH_EndFinally , LEAVE = Action_EH | EH_Leave , LEAVE_S = Action_EH | EH_Leave , STIND_I = Action_StoreIndirect | Type_I , CONV_U = Action_Convert | Type_U , ARGLIST = Action_Stack | Stack_ArgList , CEQ = Action_Set | Cond_EQ , CGT = Action_Set | Cond_GT , CGT_UN = Action_Set | Cond_GT | Unsigned , CLT = Action_Set | Cond_LT , CLT_UN = Action_Set | Cond_LT | Unsigned , LDFTN = Action_Object | Obj_LdFtn , LDVIRTFTN = Action_Object | Obj_LdVirtFtn , LOCALLOC = Action_Stack | Stack_LocAlloc , ENDFILTER = Action_EH | EH_EndFilter , UNALIGNED = Action_Modifier | Mod_Unaligned , VOLATILE = Action_Modifier | Mod_Volatile , TAILCALL = Action_Modifier | Mod_TailCall , INITOBJ = Action_Object | Obj_InitObj , CONSTRAINED = Action_Modifier | Mod_Constrained , CPBLK = Action_Object | Obj_CpBlk , INITBLK = Action_Object | Obj_InitBlk , NO = Action_Modifier | Mod_NoCheck , RETHROW = Action_EH | EH_ReThrow , SIZEOF = Action_Object | Obj_SizeOf , REFANYTYPE = Action_TypedRef | TypedRef_RefAnyType , READONLY = Action_Modifier | Mod_Readonly , } public class OpcodeInfo { // // State // private readonly String m_name; private readonly Opcode m_opcode; private readonly Format m_format; // // Constructor Methods // internal OpcodeInfo( String name , Opcode opcode , Format format ) { m_name = name; m_opcode = opcode; m_format = format; } // // Access Methods // public String Name { get { return m_name; } } public Opcode Opcode { get { return m_opcode; } } public OpcodeOperand OperandFormat { get { return (OpcodeOperand)(m_format & Format.Operand_MASK); } } public OpcodeFlowControl Control { get { return (OpcodeFlowControl)(m_format & Format.FlowControl_MASK); } } public int OperandSize { get { switch((OpcodeSize)(m_format & Format.Size_MASK)) { case OpcodeSize.Byte : return 1; case OpcodeSize.Short : return 2; case OpcodeSize.Word : return 4; case OpcodeSize.DWord : return 8; case OpcodeSize.Variable: return -1; default : return 0; } } } public int ImplicitOperandValue { get { switch((OpcodeSize)(m_format & Format.Size_MASK)) { case OpcodeSize.Implicit_M1: return -1; case OpcodeSize.Implicit_0 : return 0; case OpcodeSize.Implicit_1 : return 1; case OpcodeSize.Implicit_2 : return 2; case OpcodeSize.Implicit_3 : return 3; case OpcodeSize.Implicit_4 : return 4; case OpcodeSize.Implicit_5 : return 5; case OpcodeSize.Implicit_6 : return 6; case OpcodeSize.Implicit_7 : return 7; case OpcodeSize.Implicit_8 : return 8; default : return 0; } } } //--// public OpcodeAction Action { get { return (OpcodeAction)(m_format & Format.Action_MASK); } } public OpcodeActionDebug ActionDebug { get { return (OpcodeActionDebug)(m_format & Format.Debug_MASK); } } public OpcodeActionTarget ActionTarget { get { return (OpcodeActionTarget)(m_format & Format.Target_MASK); } } public OpcodeActionStack ActionStack { get { return (OpcodeActionStack)(m_format & Format.Stack_MASK); } } public OpcodeActionCall ActionCall { get { return (OpcodeActionCall)(m_format & Format.Call_MASK); } } public OpcodeActionObject ActionObject { get { return (OpcodeActionObject)(m_format & Format.Obj_MASK); } } public OpcodeActionTypedReference ActionTypedReference { get { return (OpcodeActionTypedReference)(m_format & Format.TypedRef_MASK); } } public OpcodeActionExceptionHandling ActionExceptionHandling { get { return (OpcodeActionExceptionHandling)(m_format & Format.EH_MASK); } } public OpcodeActionCondition ActionCondition { get { return (OpcodeActionCondition)(m_format & Format.Cond_MASK); } } public OpcodeActionALU ActionALU { get { return (OpcodeActionALU)(m_format & Format.Op_MASK); } } public OpcodeActionModifier ActionModifier { get { return (OpcodeActionModifier)(m_format & Format.Mod_MASK); } } public OpcodeActionType ActionType { get { return (OpcodeActionType)(m_format & Format.Type_MASK); } } public bool IsSigned { get { return (m_format & Format.Unsigned) == 0; } } public bool IsUnsigned { get { return (m_format & Format.Unsigned) != 0; } } public bool RequiresOverflowCheck { get { return (m_format & Format.Overflow) != 0; } } // // Debug Methods // public override String ToString() { return m_name; } } internal static readonly OpcodeInfo[] OpcodeInfoTable = new OpcodeInfo[(int)Opcode.COUNT] { new OpcodeInfo( "nop" , Opcode.NOP , Format.NOP | Format.None ), new OpcodeInfo( "break" , Opcode.BREAK , Format.BREAK | Format.None ), new OpcodeInfo( "ldarg.0" , Opcode.LDARG_0 , Format.LDARG | Format.Var | Format.SizeImplicit_0 ), new OpcodeInfo( "ldarg.1" , Opcode.LDARG_1 , Format.LDARG | Format.Var | Format.SizeImplicit_1 ), new OpcodeInfo( "ldarg.2" , Opcode.LDARG_2 , Format.LDARG | Format.Var | Format.SizeImplicit_2 ), new OpcodeInfo( "ldarg.3" , Opcode.LDARG_3 , Format.LDARG | Format.Var | Format.SizeImplicit_3 ), new OpcodeInfo( "ldloc.0" , Opcode.LDLOC_0 , Format.LDLOC | Format.Var | Format.SizeImplicit_0 ), new OpcodeInfo( "ldloc.1" , Opcode.LDLOC_1 , Format.LDLOC | Format.Var | Format.SizeImplicit_1 ), new OpcodeInfo( "ldloc.2" , Opcode.LDLOC_2 , Format.LDLOC | Format.Var | Format.SizeImplicit_2 ), new OpcodeInfo( "ldloc.3" , Opcode.LDLOC_3 , Format.LDLOC | Format.Var | Format.SizeImplicit_3 ), new OpcodeInfo( "stloc.0" , Opcode.STLOC_0 , Format.STLOC | Format.Var | Format.SizeImplicit_0 ), new OpcodeInfo( "stloc.1" , Opcode.STLOC_1 , Format.STLOC | Format.Var | Format.SizeImplicit_1 ), new OpcodeInfo( "stloc.2" , Opcode.STLOC_2 , Format.STLOC | Format.Var | Format.SizeImplicit_2 ), new OpcodeInfo( "stloc.3" , Opcode.STLOC_3 , Format.STLOC | Format.Var | Format.SizeImplicit_3 ), new OpcodeInfo( "ldarg.s" , Opcode.LDARG_S , Format.LDARG | Format.Var | Format.SizeByte ), new OpcodeInfo( "ldarga.s" , Opcode.LDARGA_S , Format.LDARGA | Format.Var | Format.SizeByte ), new OpcodeInfo( "starg.s" , Opcode.STARG_S , Format.STARG | Format.Var | Format.SizeByte ), new OpcodeInfo( "ldloc.s" , Opcode.LDLOC_S , Format.LDLOC | Format.Var | Format.SizeByte ), new OpcodeInfo( "ldloca.s" , Opcode.LDLOCA_S , Format.LDLOCA | Format.Var | Format.SizeByte ), new OpcodeInfo( "stloc.s" , Opcode.STLOC_S , Format.STLOC | Format.Var | Format.SizeByte ), new OpcodeInfo( "ldnull" , Opcode.LDNULL , Format.LDNULL | Format.None ), new OpcodeInfo( "ldc.i4.m1" , Opcode.LDC_I4_M1 , Format.LDC | Format.Int | Format.SizeImplicit_M1 ), new OpcodeInfo( "ldc.i4.0" , Opcode.LDC_I4_0 , Format.LDC | Format.Int | Format.SizeImplicit_0 ), new OpcodeInfo( "ldc.i4.1" , Opcode.LDC_I4_1 , Format.LDC | Format.Int | Format.SizeImplicit_1 ), new OpcodeInfo( "ldc.i4.2" , Opcode.LDC_I4_2 , Format.LDC | Format.Int | Format.SizeImplicit_2 ), new OpcodeInfo( "ldc.i4.3" , Opcode.LDC_I4_3 , Format.LDC | Format.Int | Format.SizeImplicit_3 ), new OpcodeInfo( "ldc.i4.4" , Opcode.LDC_I4_4 , Format.LDC | Format.Int | Format.SizeImplicit_4 ), new OpcodeInfo( "ldc.i4.5" , Opcode.LDC_I4_5 , Format.LDC | Format.Int | Format.SizeImplicit_5 ), new OpcodeInfo( "ldc.i4.6" , Opcode.LDC_I4_6 , Format.LDC | Format.Int | Format.SizeImplicit_6 ), new OpcodeInfo( "ldc.i4.7" , Opcode.LDC_I4_7 , Format.LDC | Format.Int | Format.SizeImplicit_7 ), new OpcodeInfo( "ldc.i4.8" , Opcode.LDC_I4_8 , Format.LDC | Format.Int | Format.SizeImplicit_8 ), new OpcodeInfo( "ldc.i4.s" , Opcode.LDC_I4_S , Format.LDC | Format.Int | Format.SizeByte ), new OpcodeInfo( "ldc.i4" , Opcode.LDC_I4 , Format.LDC | Format.Int | Format.SizeWord ), new OpcodeInfo( "ldc.i8" , Opcode.LDC_I8 , Format.LDC | Format.Int | Format.SizeDWord ), new OpcodeInfo( "ldc.r4" , Opcode.LDC_R4 , Format.LDC | Format.Float | Format.SizeWord ), new OpcodeInfo( "ldc.r8" , Opcode.LDC_R8 , Format.LDC | Format.Float | Format.SizeDWord ), new OpcodeInfo( "unused" , Opcode.UNUSED49 , Format.Illegal ), new OpcodeInfo( "dup" , Opcode.DUP , Format.DUP | Format.None ), new OpcodeInfo( "pop" , Opcode.POP , Format.POP | Format.None ), new OpcodeInfo( "jmp" , Opcode.JMP , Format.JMP | Format.Method | Format.SizeWord | Format.UnconditionalControl ), new OpcodeInfo( "call" , Opcode.CALL , Format.CALL | Format.Method | Format.SizeWord ), new OpcodeInfo( "calli" , Opcode.CALLI , Format.CALLI | Format.Sig | Format.SizeWord ), new OpcodeInfo( "ret" , Opcode.RET , Format.RET | Format.None | Format.UnconditionalControl ), new OpcodeInfo( "br.s" , Opcode.BR_S , Format.BR | Format.Branch | Format.SizeByte | Format.UnconditionalControl ), new OpcodeInfo( "brfalse.s" , Opcode.BRFALSE_S , Format.BRFALSE | Format.Branch | Format.SizeByte | Format.ConditionalControl ), new OpcodeInfo( "brtrue.s" , Opcode.BRTRUE_S , Format.BRTRUE | Format.Branch | Format.SizeByte | Format.ConditionalControl ), new OpcodeInfo( "beq.s" , Opcode.BEQ_S , Format.BEQ | Format.Branch | Format.SizeByte | Format.ConditionalControl ), new OpcodeInfo( "bge.s" , Opcode.BGE_S , Format.BGE | Format.Branch | Format.SizeByte | Format.ConditionalControl ), new OpcodeInfo( "bgt.s" , Opcode.BGT_S , Format.BGT | Format.Branch | Format.SizeByte | Format.ConditionalControl ), new OpcodeInfo( "ble.s" , Opcode.BLE_S , Format.BLE | Format.Branch | Format.SizeByte | Format.ConditionalControl ), new OpcodeInfo( "blt.s" , Opcode.BLT_S , Format.BLT | Format.Branch | Format.SizeByte | Format.ConditionalControl ), new OpcodeInfo( "bne.un.s" , Opcode.BNE_UN_S , Format.BNE_UN | Format.Branch | Format.SizeByte | Format.ConditionalControl ), new OpcodeInfo( "bge.un.s" , Opcode.BGE_UN_S , Format.BGE_UN | Format.Branch | Format.SizeByte | Format.ConditionalControl ), new OpcodeInfo( "bgt.un.s" , Opcode.BGT_UN_S , Format.BGT_UN | Format.Branch | Format.SizeByte | Format.ConditionalControl ), new OpcodeInfo( "ble.un.s" , Opcode.BLE_UN_S , Format.BLE_UN | Format.Branch | Format.SizeByte | Format.ConditionalControl ), new OpcodeInfo( "blt.un.s" , Opcode.BLT_UN_S , Format.BLT_UN | Format.Branch | Format.SizeByte | Format.ConditionalControl ), new OpcodeInfo( "br" , Opcode.BR , Format.BR | Format.Branch | Format.SizeWord | Format.UnconditionalControl ), new OpcodeInfo( "brfalse" , Opcode.BRFALSE , Format.BRFALSE | Format.Branch | Format.SizeWord | Format.ConditionalControl ), new OpcodeInfo( "brtrue" , Opcode.BRTRUE , Format.BRTRUE | Format.Branch | Format.SizeWord | Format.ConditionalControl ), new OpcodeInfo( "beq" , Opcode.BEQ , Format.BEQ | Format.Branch | Format.SizeWord | Format.ConditionalControl ), new OpcodeInfo( "bge" , Opcode.BGE , Format.BGE | Format.Branch | Format.SizeWord | Format.ConditionalControl ), new OpcodeInfo( "bgt" , Opcode.BGT , Format.BGT | Format.Branch | Format.SizeWord | Format.ConditionalControl ), new OpcodeInfo( "ble" , Opcode.BLE , Format.BLE | Format.Branch | Format.SizeWord | Format.ConditionalControl ), new OpcodeInfo( "blt" , Opcode.BLT , Format.BLT | Format.Branch | Format.SizeWord | Format.ConditionalControl ), new OpcodeInfo( "bne.un" , Opcode.BNE_UN , Format.BNE_UN | Format.Branch | Format.SizeWord | Format.ConditionalControl ), new OpcodeInfo( "bge.un" , Opcode.BGE_UN , Format.BGE_UN | Format.Branch | Format.SizeWord | Format.ConditionalControl ), new OpcodeInfo( "bgt.un" , Opcode.BGT_UN , Format.BGT_UN | Format.Branch | Format.SizeWord | Format.ConditionalControl ), new OpcodeInfo( "ble.un" , Opcode.BLE_UN , Format.BLE_UN | Format.Branch | Format.SizeWord | Format.ConditionalControl ), new OpcodeInfo( "blt.un" , Opcode.BLT_UN , Format.BLT_UN | Format.Branch | Format.SizeWord | Format.ConditionalControl ), new OpcodeInfo( "switch" , Opcode.SWITCH , Format.SWITCH | Format.Switch | Format.SizeVariable | Format.ConditionalControl ), new OpcodeInfo( "ldind.i1" , Opcode.LDIND_I1 , Format.LDIND_I1 | Format.None ), new OpcodeInfo( "ldind.u1" , Opcode.LDIND_U1 , Format.LDIND_U1 | Format.None ), new OpcodeInfo( "ldind.i2" , Opcode.LDIND_I2 , Format.LDIND_I2 | Format.None ), new OpcodeInfo( "ldind.u2" , Opcode.LDIND_U2 , Format.LDIND_U2 | Format.None ), new OpcodeInfo( "ldind.i4" , Opcode.LDIND_I4 , Format.LDIND_I4 | Format.None ), new OpcodeInfo( "ldind.u4" , Opcode.LDIND_U4 , Format.LDIND_U4 | Format.None ), new OpcodeInfo( "ldind.i8" , Opcode.LDIND_I8 , Format.LDIND_I8 | Format.None ), new OpcodeInfo( "ldind.i" , Opcode.LDIND_I , Format.LDIND_I | Format.None ), new OpcodeInfo( "ldind.r4" , Opcode.LDIND_R4 , Format.LDIND_R4 | Format.None ), new OpcodeInfo( "ldind.r8" , Opcode.LDIND_R8 , Format.LDIND_R8 | Format.None ), new OpcodeInfo( "ldind.ref" , Opcode.LDIND_REF , Format.LDIND_REF | Format.None ), new OpcodeInfo( "stind.ref" , Opcode.STIND_REF , Format.STIND_REF | Format.None ), new OpcodeInfo( "stind.i1" , Opcode.STIND_I1 , Format.STIND_I1 | Format.None ), new OpcodeInfo( "stind.i2" , Opcode.STIND_I2 , Format.STIND_I2 | Format.None ), new OpcodeInfo( "stind.i4" , Opcode.STIND_I4 , Format.STIND_I4 | Format.None ), new OpcodeInfo( "stind.i8" , Opcode.STIND_I8 , Format.STIND_I8 | Format.None ), new OpcodeInfo( "stind.r4" , Opcode.STIND_R4 , Format.STIND_R4 | Format.None ), new OpcodeInfo( "stind.r8" , Opcode.STIND_R8 , Format.STIND_R8 | Format.None ), new OpcodeInfo( "add" , Opcode.ADD , Format.ADD | Format.None ), new OpcodeInfo( "sub" , Opcode.SUB , Format.SUB | Format.None ), new OpcodeInfo( "mul" , Opcode.MUL , Format.MUL | Format.None ), new OpcodeInfo( "div" , Opcode.DIV , Format.DIV | Format.None ), new OpcodeInfo( "div.un" , Opcode.DIV_UN , Format.DIV_UN | Format.None ), new OpcodeInfo( "rem" , Opcode.REM , Format.REM | Format.None ), new OpcodeInfo( "rem.un" , Opcode.REM_UN , Format.REM_UN | Format.None ), new OpcodeInfo( "and" , Opcode.AND , Format.AND | Format.None ), new OpcodeInfo( "or" , Opcode.OR , Format.OR | Format.None ), new OpcodeInfo( "xor" , Opcode.XOR , Format.XOR | Format.None ), new OpcodeInfo( "shl" , Opcode.SHL , Format.SHL | Format.None ), new OpcodeInfo( "shr" , Opcode.SHR , Format.SHR | Format.None ), new OpcodeInfo( "shr.un" , Opcode.SHR_UN , Format.SHR_UN | Format.None ), new OpcodeInfo( "neg" , Opcode.NEG , Format.NEG | Format.None ), new OpcodeInfo( "not" , Opcode.NOT , Format.NOT | Format.None ), new OpcodeInfo( "conv.i1" , Opcode.CONV_I1 , Format.CONV_I1 | Format.None ), new OpcodeInfo( "conv.i2" , Opcode.CONV_I2 , Format.CONV_I2 | Format.None ), new OpcodeInfo( "conv.i4" , Opcode.CONV_I4 , Format.CONV_I4 | Format.None ), new OpcodeInfo( "conv.i8" , Opcode.CONV_I8 , Format.CONV_I8 | Format.None ), new OpcodeInfo( "conv.r4" , Opcode.CONV_R4 , Format.CONV_R4 | Format.None ), new OpcodeInfo( "conv.r8" , Opcode.CONV_R8 , Format.CONV_R8 | Format.None ), new OpcodeInfo( "conv.u4" , Opcode.CONV_U4 , Format.CONV_U4 | Format.None ), new OpcodeInfo( "conv.u8" , Opcode.CONV_U8 , Format.CONV_U8 | Format.None ), new OpcodeInfo( "callvirt" , Opcode.CALLVIRT , Format.CALLVIRT | Format.Method | Format.SizeWord ), new OpcodeInfo( "cpobj" , Opcode.CPOBJ , Format.CPOBJ | Format.Type | Format.SizeWord ), new OpcodeInfo( "ldobj" , Opcode.LDOBJ , Format.LDOBJ | Format.Type | Format.SizeWord ), new OpcodeInfo( "ldstr" , Opcode.LDSTR , Format.LDSTR | Format.String | Format.SizeWord ), new OpcodeInfo( "newobj" , Opcode.NEWOBJ , Format.NEWOBJ | Format.Method | Format.SizeWord ), new OpcodeInfo( "castclass" , Opcode.CASTCLASS , Format.CASTCLASS | Format.Type | Format.SizeWord ), new OpcodeInfo( "isinst" , Opcode.ISINST , Format.ISINST | Format.Type | Format.SizeWord ), new OpcodeInfo( "conv.r.un" , Opcode.CONV_R_UN , Format.CONV_R_UN | Format.None ), new OpcodeInfo( "unused" , Opcode.UNUSED58 , Format.Illegal ), new OpcodeInfo( "unused" , Opcode.UNUSED1 , Format.Illegal ), new OpcodeInfo( "unbox" , Opcode.UNBOX , Format.UNBOX | Format.Type | Format.SizeWord ), new OpcodeInfo( "throw" , Opcode.THROW , Format.THROW | Format.None | Format.ExceptionHandling ), new OpcodeInfo( "ldfld" , Opcode.LDFLD , Format.LDFLD | Format.Field | Format.SizeWord ), new OpcodeInfo( "ldflda" , Opcode.LDFLDA , Format.LDFLDA | Format.Field | Format.SizeWord ), new OpcodeInfo( "stfld" , Opcode.STFLD , Format.STFLD | Format.Field | Format.SizeWord ), new OpcodeInfo( "ldsfld" , Opcode.LDSFLD , Format.LDSFLD | Format.Field | Format.SizeWord ), new OpcodeInfo( "ldsflda" , Opcode.LDSFLDA , Format.LDSFLDA | Format.Field | Format.SizeWord ), new OpcodeInfo( "stsfld" , Opcode.STSFLD , Format.STSFLD | Format.Field | Format.SizeWord ), new OpcodeInfo( "stobj" , Opcode.STOBJ , Format.STOBJ | Format.Type | Format.SizeWord ), new OpcodeInfo( "conv.ovf.i1.un" , Opcode.CONV_OVF_I1_UN , Format.CONV_OVF_I1_UN | Format.None ), new OpcodeInfo( "conv.ovf.i2.un" , Opcode.CONV_OVF_I2_UN , Format.CONV_OVF_I2_UN | Format.None ), new OpcodeInfo( "conv.ovf.i4.un" , Opcode.CONV_OVF_I4_UN , Format.CONV_OVF_I4_UN | Format.None ), new OpcodeInfo( "conv.ovf.i8.un" , Opcode.CONV_OVF_I8_UN , Format.CONV_OVF_I8_UN | Format.None ), new OpcodeInfo( "conv.ovf.u1.un" , Opcode.CONV_OVF_U1_UN , Format.CONV_OVF_U1_UN | Format.None ), new OpcodeInfo( "conv.ovf.u2.un" , Opcode.CONV_OVF_U2_UN , Format.CONV_OVF_U2_UN | Format.None ), new OpcodeInfo( "conv.ovf.u4.un" , Opcode.CONV_OVF_U4_UN , Format.CONV_OVF_U4_UN | Format.None ), new OpcodeInfo( "conv.ovf.u8.un" , Opcode.CONV_OVF_U8_UN , Format.CONV_OVF_U8_UN | Format.None ), new OpcodeInfo( "conv.ovf.i.un" , Opcode.CONV_OVF_I_UN , Format.CONV_OVF_I_UN | Format.None ), new OpcodeInfo( "conv.ovf.u.un" , Opcode.CONV_OVF_U_UN , Format.CONV_OVF_U_UN | Format.None ), new OpcodeInfo( "box" , Opcode.BOX , Format.BOX | Format.Type | Format.SizeWord ), new OpcodeInfo( "newarr" , Opcode.NEWARR , Format.NEWARR | Format.Type | Format.SizeWord ), new OpcodeInfo( "ldlen" , Opcode.LDLEN , Format.LDLEN | Format.None ), new OpcodeInfo( "ldelema" , Opcode.LDELEMA , Format.LDELEMA | Format.Type | Format.SizeWord ), new OpcodeInfo( "ldelem.i1" , Opcode.LDELEM_I1 , Format.LDELEM_I1 | Format.None ), new OpcodeInfo( "ldelem.u1" , Opcode.LDELEM_U1 , Format.LDELEM_U1 | Format.None ), new OpcodeInfo( "ldelem.i2" , Opcode.LDELEM_I2 , Format.LDELEM_I2 | Format.None ), new OpcodeInfo( "ldelem.u2" , Opcode.LDELEM_U2 , Format.LDELEM_U2 | Format.None ), new OpcodeInfo( "ldelem.i4" , Opcode.LDELEM_I4 , Format.LDELEM_I4 | Format.None ), new OpcodeInfo( "ldelem.u4" , Opcode.LDELEM_U4 , Format.LDELEM_U4 | Format.None ), new OpcodeInfo( "ldelem.i8" , Opcode.LDELEM_I8 , Format.LDELEM_I8 | Format.None ), new OpcodeInfo( "ldelem.i" , Opcode.LDELEM_I , Format.LDELEM_I | Format.None ), new OpcodeInfo( "ldelem.r4" , Opcode.LDELEM_R4 , Format.LDELEM_R4 | Format.None ), new OpcodeInfo( "ldelem.r8" , Opcode.LDELEM_R8 , Format.LDELEM_R8 | Format.None ), new OpcodeInfo( "ldelem.ref" , Opcode.LDELEM_REF , Format.LDELEM_REF | Format.None ), new OpcodeInfo( "stelem.i" , Opcode.STELEM_I , Format.STELEM_I | Format.None ), new OpcodeInfo( "stelem.i1" , Opcode.STELEM_I1 , Format.STELEM_I1 | Format.None ), new OpcodeInfo( "stelem.i2" , Opcode.STELEM_I2 , Format.STELEM_I2 | Format.None ), new OpcodeInfo( "stelem.i4" , Opcode.STELEM_I4 , Format.STELEM_I4 | Format.None ), new OpcodeInfo( "stelem.i8" , Opcode.STELEM_I8 , Format.STELEM_I8 | Format.None ), new OpcodeInfo( "stelem.r4" , Opcode.STELEM_R4 , Format.STELEM_R4 | Format.None ), new OpcodeInfo( "stelem.r8" , Opcode.STELEM_R8 , Format.STELEM_R8 | Format.None ), new OpcodeInfo( "stelem.ref" , Opcode.STELEM_REF , Format.STELEM_REF | Format.None ), new OpcodeInfo( "ldelem" , Opcode.LDELEM , Format.LDELEM | Format.Type | Format.SizeWord ), new OpcodeInfo( "stelem" , Opcode.STELEM , Format.STELEM | Format.Type | Format.SizeWord ), new OpcodeInfo( "unbox.any" , Opcode.UNBOX_ANY , Format.UNBOX_ANY | Format.Type | Format.SizeWord ), new OpcodeInfo( "unused" , Opcode.UNUSED5 , Format.Illegal ), new OpcodeInfo( "unused" , Opcode.UNUSED6 , Format.Illegal ), new OpcodeInfo( "unused" , Opcode.UNUSED7 , Format.Illegal ), new OpcodeInfo( "unused" , Opcode.UNUSED8 , Format.Illegal ), new OpcodeInfo( "unused" , Opcode.UNUSED9 , Format.Illegal ), new OpcodeInfo( "unused" , Opcode.UNUSED10 , Format.Illegal ), new OpcodeInfo( "unused" , Opcode.UNUSED11 , Format.Illegal ), new OpcodeInfo( "unused" , Opcode.UNUSED12 , Format.Illegal ), new OpcodeInfo( "unused" , Opcode.UNUSED13 , Format.Illegal ), new OpcodeInfo( "unused" , Opcode.UNUSED14 , Format.Illegal ), new OpcodeInfo( "unused" , Opcode.UNUSED15 , Format.Illegal ), new OpcodeInfo( "unused" , Opcode.UNUSED16 , Format.Illegal ), new OpcodeInfo( "unused" , Opcode.UNUSED17 , Format.Illegal ), new OpcodeInfo( "conv.ovf.i1" , Opcode.CONV_OVF_I1 , Format.CONV_OVF_I1 | Format.None ), new OpcodeInfo( "conv.ovf.u1" , Opcode.CONV_OVF_U1 , Format.CONV_OVF_U1 | Format.None ), new OpcodeInfo( "conv.ovf.i2" , Opcode.CONV_OVF_I2 , Format.CONV_OVF_I2 | Format.None ), new OpcodeInfo( "conv.ovf.u2" , Opcode.CONV_OVF_U2 , Format.CONV_OVF_U2 | Format.None ), new OpcodeInfo( "conv.ovf.i4" , Opcode.CONV_OVF_I4 , Format.CONV_OVF_I4 | Format.None ), new OpcodeInfo( "conv.ovf.u4" , Opcode.CONV_OVF_U4 , Format.CONV_OVF_U4 | Format.None ), new OpcodeInfo( "conv.ovf.i8" , Opcode.CONV_OVF_I8 , Format.CONV_OVF_I8 | Format.None ), new OpcodeInfo( "conv.ovf.u8" , Opcode.CONV_OVF_U8 , Format.CONV_OVF_U8 | Format.None ), new OpcodeInfo( "unused" , Opcode.UNUSED50 , Format.Illegal ), new OpcodeInfo( "unused" , Opcode.UNUSED18 , Format.Illegal ), new OpcodeInfo( "unused" , Opcode.UNUSED19 , Format.Illegal ), new OpcodeInfo( "unused" , Opcode.UNUSED20 , Format.Illegal ), new OpcodeInfo( "unused" , Opcode.UNUSED21 , Format.Illegal ), new OpcodeInfo( "unused" , Opcode.UNUSED22 , Format.Illegal ), new OpcodeInfo( "unused" , Opcode.UNUSED23 , Format.Illegal ), new OpcodeInfo( "refanyval" , Opcode.REFANYVAL , Format.REFANYVAL | Format.Type | Format.SizeWord ), new OpcodeInfo( "ckfinite" , Opcode.CKFINITE , Format.CKFINITE | Format.None ), new OpcodeInfo( "unused" , Opcode.UNUSED24 , Format.None ), new OpcodeInfo( "unused" , Opcode.UNUSED25 , Format.None ), new OpcodeInfo( "mkrefany" , Opcode.MKREFANY , Format.MKREFANY | Format.Type | Format.SizeWord ), new OpcodeInfo( "unused" , Opcode.UNUSED59 , Format.Illegal ), new OpcodeInfo( "unused" , Opcode.UNUSED60 , Format.Illegal ), new OpcodeInfo( "unused" , Opcode.UNUSED61 , Format.Illegal ), new OpcodeInfo( "unused" , Opcode.UNUSED62 , Format.Illegal ), new OpcodeInfo( "unused" , Opcode.UNUSED63 , Format.Illegal ), new OpcodeInfo( "unused" , Opcode.UNUSED64 , Format.Illegal ), new OpcodeInfo( "unused" , Opcode.UNUSED65 , Format.Illegal ), new OpcodeInfo( "unused" , Opcode.UNUSED66 , Format.Illegal ), new OpcodeInfo( "unused" , Opcode.UNUSED67 , Format.Illegal ), new OpcodeInfo( "ldtoken" , Opcode.LDTOKEN , Format.LDTOKEN | Format.Token | Format.SizeWord ), new OpcodeInfo( "conv.u2" , Opcode.CONV_U2 , Format.CONV_U2 | Format.None ), new OpcodeInfo( "conv.u1" , Opcode.CONV_U1 , Format.CONV_U1 | Format.None ), new OpcodeInfo( "conv.i" , Opcode.CONV_I , Format.CONV_I | Format.None ), new OpcodeInfo( "conv.ovf.i" , Opcode.CONV_OVF_I , Format.CONV_OVF_I | Format.None ), new OpcodeInfo( "conv.ovf.u" , Opcode.CONV_OVF_U , Format.CONV_OVF_U | Format.None ), new OpcodeInfo( "add.ovf" , Opcode.ADD_OVF , Format.ADD_OVF | Format.None ), new OpcodeInfo( "add.ovf.un" , Opcode.ADD_OVF_UN , Format.ADD_OVF_UN | Format.None ), new OpcodeInfo( "mul.ovf" , Opcode.MUL_OVF , Format.MUL_OVF | Format.None ), new OpcodeInfo( "mul.ovf.un" , Opcode.MUL_OVF_UN , Format.MUL_OVF_UN | Format.None ), new OpcodeInfo( "sub.ovf" , Opcode.SUB_OVF , Format.SUB_OVF | Format.None ), new OpcodeInfo( "sub.ovf.un" , Opcode.SUB_OVF_UN , Format.SUB_OVF_UN | Format.None ), new OpcodeInfo( "endfinally" , Opcode.ENDFINALLY , Format.ENDFINALLY | Format.None | Format.ExceptionHandling ), new OpcodeInfo( "leave" , Opcode.LEAVE , Format.LEAVE | Format.Branch | Format.SizeWord | Format.ExceptionHandling ), new OpcodeInfo( "leave.s" , Opcode.LEAVE_S , Format.LEAVE_S | Format.Branch | Format.SizeByte | Format.ExceptionHandling ), new OpcodeInfo( "stind.i" , Opcode.STIND_I , Format.STIND_I | Format.None ), new OpcodeInfo( "conv.u" , Opcode.CONV_U , Format.CONV_U | Format.None ), new OpcodeInfo( "unused" , Opcode.UNUSED26 , Format.Illegal ), new OpcodeInfo( "unused" , Opcode.UNUSED27 , Format.Illegal ), new OpcodeInfo( "unused" , Opcode.UNUSED28 , Format.Illegal ), new OpcodeInfo( "unused" , Opcode.UNUSED29 , Format.Illegal ), new OpcodeInfo( "unused" , Opcode.UNUSED30 , Format.Illegal ), new OpcodeInfo( "unused" , Opcode.UNUSED31 , Format.Illegal ), new OpcodeInfo( "unused" , Opcode.UNUSED32 , Format.Illegal ), new OpcodeInfo( "unused" , Opcode.UNUSED33 , Format.Illegal ), new OpcodeInfo( "unused" , Opcode.UNUSED34 , Format.Illegal ), new OpcodeInfo( "unused" , Opcode.UNUSED35 , Format.Illegal ), new OpcodeInfo( "unused" , Opcode.UNUSED36 , Format.Illegal ), new OpcodeInfo( "unused" , Opcode.UNUSED37 , Format.Illegal ), new OpcodeInfo( "unused" , Opcode.UNUSED38 , Format.Illegal ), new OpcodeInfo( "unused" , Opcode.UNUSED39 , Format.Illegal ), new OpcodeInfo( "unused" , Opcode.UNUSED40 , Format.Illegal ), new OpcodeInfo( "unused" , Opcode.UNUSED41 , Format.Illegal ), new OpcodeInfo( "unused" , Opcode.UNUSED42 , Format.Illegal ), new OpcodeInfo( "unused" , Opcode.UNUSED43 , Format.Illegal ), new OpcodeInfo( "unused" , Opcode.UNUSED44 , Format.Illegal ), new OpcodeInfo( "unused" , Opcode.UNUSED45 , Format.Illegal ), new OpcodeInfo( "unused" , Opcode.UNUSED46 , Format.Illegal ), new OpcodeInfo( "unused" , Opcode.UNUSED47 , Format.Illegal ), new OpcodeInfo( "unused" , Opcode.UNUSED48 , Format.Illegal ), new OpcodeInfo( "prefix7" , Opcode.PREFIX7 , Format.Illegal ), new OpcodeInfo( "prefix6" , Opcode.PREFIX6 , Format.Illegal ), new OpcodeInfo( "prefix5" , Opcode.PREFIX5 , Format.Illegal ), new OpcodeInfo( "prefix4" , Opcode.PREFIX4 , Format.Illegal ), new OpcodeInfo( "prefix3" , Opcode.PREFIX3 , Format.Illegal ), new OpcodeInfo( "prefix2" , Opcode.PREFIX2 , Format.Illegal ), new OpcodeInfo( "prefix1" , Opcode.PREFIX1 , Format.None ), new OpcodeInfo( "prefixref" , Opcode.PREFIXREF , Format.Illegal ), new OpcodeInfo( "arglist" , Opcode.ARGLIST , Format.ARGLIST | Format.None ), new OpcodeInfo( "ceq" , Opcode.CEQ , Format.CEQ | Format.None ), new OpcodeInfo( "cgt" , Opcode.CGT , Format.CGT | Format.None ), new OpcodeInfo( "cgt.un" , Opcode.CGT_UN , Format.CGT_UN | Format.None ), new OpcodeInfo( "clt" , Opcode.CLT , Format.CLT | Format.None ), new OpcodeInfo( "clt.un" , Opcode.CLT_UN , Format.CLT_UN | Format.None ), new OpcodeInfo( "ldftn" , Opcode.LDFTN , Format.LDFTN | Format.Method | Format.SizeWord ), new OpcodeInfo( "ldvirtftn" , Opcode.LDVIRTFTN , Format.LDVIRTFTN | Format.Method | Format.SizeWord ), new OpcodeInfo( "unused" , Opcode.UNUSED56 , Format.Illegal ), new OpcodeInfo( "ldarg" , Opcode.LDARG , Format.LDARG | Format.Var | Format.SizeShort ), new OpcodeInfo( "ldarga" , Opcode.LDARGA , Format.LDARGA | Format.Var | Format.SizeShort ), new OpcodeInfo( "starg" , Opcode.STARG , Format.STARG | Format.Var | Format.SizeShort ), new OpcodeInfo( "ldloc" , Opcode.LDLOC , Format.LDLOC | Format.Var | Format.SizeShort ), new OpcodeInfo( "ldloca" , Opcode.LDLOCA , Format.LDLOCA | Format.Var | Format.SizeShort ), new OpcodeInfo( "stloc" , Opcode.STLOC , Format.STLOC | Format.Var | Format.SizeShort ), new OpcodeInfo( "localloc" , Opcode.LOCALLOC , Format.LOCALLOC | Format.None ), new OpcodeInfo( "unused" , Opcode.UNUSED57 , Format.Illegal ), new OpcodeInfo( "endfilter" , Opcode.ENDFILTER , Format.ENDFILTER | Format.None | Format.ExceptionHandling ), new OpcodeInfo( "unaligned." , Opcode.UNALIGNED , Format.UNALIGNED | Format.Int | Format.SizeByte ), new OpcodeInfo( "volatile." , Opcode.VOLATILE , Format.VOLATILE | Format.None ), new OpcodeInfo( "tail." , Opcode.TAILCALL , Format.TAILCALL | Format.None ), new OpcodeInfo( "initobj" , Opcode.INITOBJ , Format.INITOBJ | Format.Type | Format.SizeWord ), new OpcodeInfo( "constrained." , Opcode.CONSTRAINED , Format.CONSTRAINED | Format.Type | Format.SizeWord ), new OpcodeInfo( "cpblk" , Opcode.CPBLK , Format.CPBLK | Format.None ), new OpcodeInfo( "initblk" , Opcode.INITBLK , Format.INITBLK | Format.None ), new OpcodeInfo( "no." , Opcode.NO , Format.NO | Format.Int | Format.SizeByte ), new OpcodeInfo( "rethrow" , Opcode.RETHROW , Format.RETHROW | Format.None | Format.ExceptionHandling ), new OpcodeInfo( "unused" , Opcode.UNUSED51 , Format.Illegal ), new OpcodeInfo( "sizeof" , Opcode.SIZEOF , Format.SIZEOF | Format.Type | Format.SizeWord ), new OpcodeInfo( "refanytype" , Opcode.REFANYTYPE , Format.REFANYTYPE | Format.None ), new OpcodeInfo( "readonly." , Opcode.READONLY , Format.READONLY | Format.None ), new OpcodeInfo( "unused" , Opcode.UNUSED53 , Format.Illegal ), new OpcodeInfo( "unused" , Opcode.UNUSED54 , Format.Illegal ), new OpcodeInfo( "unused" , Opcode.UNUSED55 , Format.Illegal ), new OpcodeInfo( "unused" , Opcode.UNUSED70 , Format.Illegal ), new OpcodeInfo( "illegal" , Opcode.ILLEGAL , Format.Illegal ), new OpcodeInfo( "endmac" , Opcode.MACRO_END , Format.Illegal ), }; //// static Instruction() //// { //// for(Opcode opcode = 0; opcode < Opcode.COUNT; opcode++) //// { //// if(OpcodeInfoTable[(int)opcode].Opcode != opcode) //// { //// throw new MetaDataMethod.IllegalInstructionStreamException( "opcode invariant failure" ); //// } //// } //// } //--// // // State // private readonly OpcodeInfo m_opcodeInfo; private readonly object m_operand; private readonly Debugging.DebugInfo m_debugInfo; // // Constructor Methods // internal Instruction( OpcodeInfo opcodeInfo , Object operand , Debugging.DebugInfo debugInfo ) { m_opcodeInfo = opcodeInfo; m_operand = operand; m_debugInfo = debugInfo; } // // MetaDataEquality Methods // public override bool Equals( object obj ) { if(obj is Instruction) // Since the class is sealed (no subclasses allowed), there's no need to compare using .GetType() { Instruction other = (Instruction)obj; if(m_opcodeInfo == other.m_opcodeInfo && m_operand == other.m_operand && m_debugInfo == other.m_debugInfo ) { return true; } } return false; } public override int GetHashCode() { return m_opcodeInfo.Name.GetHashCode() ^ (int)m_opcodeInfo.Opcode; } // // Access Methods // public OpcodeInfo Operator { get { return m_opcodeInfo; } } public object Argument { get { return m_operand; } } public Debugging.DebugInfo DebugInfo { get { return m_debugInfo; } } // // Debug Methods // public override String ToString() { if(m_debugInfo != null) { return (m_opcodeInfo.Name + m_debugInfo.ToString()); } else { return (m_opcodeInfo.Name); } } } } ================================================ FILE: Zelig/Zelig/CompileTime/MetaData/Normalized/MarshalSpec.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // namespace Microsoft.Zelig.MetaData.Normalized { using System; public abstract class MarshalSpec { public override abstract String ToString(); } public class MarshalSpecNative : MarshalSpec { // // State // private readonly NativeTypes m_kind; // // Constructor Methods // public MarshalSpecNative( NativeTypes kind ) { m_kind = kind; } // // Access Methods // public NativeTypes Kind { get { return m_kind; } } public override String ToString() { return "MarshalSpecNative(" + m_kind + ")"; } } public class MarshalSpecSafeArray : MarshalSpec { // // State // private readonly VariantTypes m_elemType; // // Constructor Methods // public MarshalSpecSafeArray( VariantTypes elemType ) { m_elemType = elemType; } // // Access Methods // public VariantTypes ElementType { get { return m_elemType; } } public override String ToString() { return "MarshalSpecSafeArray(" + m_elemType + ")"; } } public class MarshalSpecFixedString : MarshalSpec { // // State // private readonly uint m_elemCount; // // Constructor Methods // public MarshalSpecFixedString( uint elemCount ) { m_elemCount = elemCount; } // // Access Methods // public uint ElementCount { get { return m_elemCount; } } public override String ToString() { return "MarshalSpecFixedString(" + m_elemCount + ")"; } } public class MarshalSpecFixedArray : MarshalSpec { // // State // private readonly uint m_elemCount; // // Constructor Methods // public MarshalSpecFixedArray( uint elemCount ) { m_elemCount = elemCount; } // // Access Methods // public uint ElementCount { get { return m_elemCount; } } public override String ToString() { return "MarshalSpecFixedArray(" + m_elemCount + ")"; } } public class MarshalSpecCustom : MarshalSpec { // // State // private readonly String m_guid; private readonly String m_unmanagedType; private readonly String m_managedType; private readonly String m_cookie; // // Constructor Methods // public MarshalSpecCustom( String guid , String unmanagedType , String managedType , String cookie ) { m_guid = guid; m_unmanagedType = unmanagedType; m_managedType = managedType; m_cookie = cookie; } // // Access Methods // public String Guid { get { return m_guid; } } public String UnmanagedType { get { return m_unmanagedType; } } public String ManagedType { get { return m_managedType; } } public String Cookie { get { return m_cookie; } } public override String ToString() { return "MarshalSpecCustom(" + m_guid + "," + m_managedType + "->" + m_unmanagedType + "," + m_cookie + ")"; } } public class MarshalSpecArray : MarshalSpec { // // State // private readonly NativeTypes m_elemType; private readonly uint m_paramNumber; private readonly uint m_extras; // // Constructor Methods // public MarshalSpecArray( NativeTypes elemType , uint paramNumber , uint extras ) { m_elemType = elemType; m_paramNumber = paramNumber; m_extras = extras; } // // Access Methods // public NativeTypes ElementType { get { return m_elemType; } } public uint ParameterNumber { get { return m_paramNumber; } } public uint ExtraCount { get { return m_extras; } } public override String ToString() { return "MarshalSpecArray(" + m_elemType + "," + m_paramNumber + "," + m_extras + ")"; } } } ================================================ FILE: Zelig/Zelig/CompileTime/MetaData/Normalized/MetaDataAssembly.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // namespace Microsoft.Zelig.MetaData.Normalized { using System; using System.Collections.Generic; // // Don't remove "sealed" attribute unless you read comments on Equals method. // public sealed class MetaDataAssembly : MetaDataObject, IMetaDataHasDeclSecurity, IMetaDataUnique { // // State // internal HashAlgorithmID m_hashAlgorithmId; internal MetaDataVersion m_version; internal String m_name; internal String m_locale; //--// internal List< MetaDataTypeDefinitionAbstract > m_typesList; internal List< MetaDataTypeDefinitionGenericInstantiation > m_instantiatedTypesList; internal List< MetaDataTypeDefinitionAbstract > m_otherTypesList; internal List< MetaDataTypeDefinitionArray > m_pendingArraysList; internal List< MetaDataManifestResource > m_resourcesList; internal GrowOnlySet< IMetaDataUnique > m_lookupUniques; internal MetaDataMethodBase m_entryPoint; // // Constructor Methods // internal MetaDataAssembly( GrowOnlySet< IMetaDataUnique > lookupUniques , int token ) : base( token ) { m_typesList = new List< MetaDataTypeDefinitionAbstract >(); m_instantiatedTypesList = new List< MetaDataTypeDefinitionGenericInstantiation >(); m_otherTypesList = new List< MetaDataTypeDefinitionAbstract >(); m_pendingArraysList = new List< MetaDataTypeDefinitionArray >(); m_resourcesList = new List< MetaDataManifestResource >(); m_lookupUniques = lookupUniques; } //--// // // MetaDataEquality Methods // public override bool Equals( object obj ) { if(obj is MetaDataAssembly) // Since the class is sealed (no subclasses allowed), there's no need to compare using .GetType() { MetaDataAssembly other = (MetaDataAssembly)obj; if(m_hashAlgorithmId == other.m_hashAlgorithmId && m_name == other.m_name && m_locale == other.m_locale ) { if(m_version.Equals( other.m_version )) { return true; } } } return false; } public override int GetHashCode() { return (int)m_hashAlgorithmId ^ m_name .GetHashCode() ; } // // Helper Methods // internal override MetaDataObject MakeUnique() { return (MetaDataObject)MakeUnique( this ); } internal IMetaDataUnique MakeUnique( IMetaDataUnique obj ) { IMetaDataUnique res; if(m_lookupUniques.Contains( obj, out res )) { //// if(res != obj) //// { //// DebugPrint( "MakeUnique:\r\n IN :{0}\r\n OUT:{1}", obj, res ); //// //// obj = res; //// } return res; } else { m_lookupUniques.Insert( obj ); if(obj is MetaDataTypeDefinitionAbstract) { MetaDataTypeDefinitionAbstract td = (MetaDataTypeDefinitionAbstract)obj; MetaDataAssembly asml = td.Owner; if(td is MetaDataTypeDefinitionBase) { //throw new NotNormalized( "Unexpected type: " + td ); } else if(td is MetaDataTypeDefinitionGenericInstantiation) { asml.InstantiatedTypes.Add( (MetaDataTypeDefinitionGenericInstantiation)td ); } else if(td is MetaDataTypeDefinitionArray) { asml.PendingArrays.Add( (MetaDataTypeDefinitionArray)td ); } else { asml.OtherTypes.Add( td ); } } return obj; } } // // Access Methods // public HashAlgorithmID HashAlgorithmId { get { return m_hashAlgorithmId; } } public MetaDataVersion Version { get { return m_version; } } public String Name { get { return m_name; } } public String Locale { get { return m_locale; } } public MetaDataMethodBase EntryPoint { get { return m_entryPoint; } } public List< MetaDataTypeDefinitionAbstract > Types { get { return m_typesList; } } public List< MetaDataTypeDefinitionGenericInstantiation > InstantiatedTypes { get { return m_instantiatedTypesList; } } public List< MetaDataTypeDefinitionAbstract > OtherTypes { get { return m_otherTypesList; } } public List< MetaDataManifestResource > Resources { get { return m_resourcesList; } } public List< MetaDataTypeDefinitionArray > PendingArrays { get { return m_pendingArraysList; } } //// public MetaDataFile[] files //// { //// get //// { //// return this.fileArray; //// } //// } // // Debug Methods // public override String ToString() { System.Text.StringBuilder sb = new System.Text.StringBuilder( "MetaDataAssembly(" ); sb.Append( m_hashAlgorithmId ); sb.Append( "," ); sb.Append( m_version ); sb.Append( "," ); sb.Append( m_name ); sb.Append( "," ); sb.Append( m_locale ); sb.Append( ")" ); return sb.ToString(); } public override void Dump( IMetaDataDumper writer ) { writer.WriteLine( ".assembly {0} {1} {2}", TokenToString( m_token ), m_name, m_version ); writer.IndentPush( "{" ); if(m_customAttributes != null) { foreach(MetaDataCustomAttribute ca in m_customAttributes) { writer.Process( ca, false ); } writer.WriteLine(); } writer.IndentPop( "}" ); writer.WriteLine(); foreach(MetaDataTypeDefinitionAbstract td in m_typesList) { writer.Process( td, true ); } } } } ================================================ FILE: Zelig/Zelig/CompileTime/MetaData/Normalized/MetaDataBits.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // namespace Microsoft.Zelig.MetaData { using System; // MetaDataBits // // definitions for various bit-level flags, masks // derived from //urtdist/builds/src/2727/Lightning/Src/inc/CorHdr.h public enum NativeTypes : byte { END = 0x00, //DEPRECATED VOID = 0x01, //DEPRECATED BOOLEAN = 0x02, // (4 byte boolean value: TRUE = non-zero, FALSE = 0) I1 = 0x03, U1 = 0x04, I2 = 0x05, U2 = 0x06, I4 = 0x07, U4 = 0x08, I8 = 0x09, U8 = 0x0A, R4 = 0x0B, R8 = 0x0C, SYSCHAR = 0x0D, //DEPRECATED VARIANT = 0x0E, //DEPRECATED CURRENCY = 0x0F, PTR = 0x10, //DEPRECATED DECIMAL = 0x11, //DEPRECATED DATE = 0x12, //DEPRECATED BSTR = 0x13, LPSTR = 0x14, LPWSTR = 0x15, LPTSTR = 0x16, FIXEDSYSSTRING = 0x17, OBJECTREF = 0x18, //DEPRECATED IUNKNOWN = 0x19, IDISPATCH = 0x1A, STRUCT = 0x1B, INTF = 0x1C, SAFEARRAY = 0x1D, FIXEDARRAY = 0x1E, INT = 0x1F, UINT = 0x20, //////////////////////////@todo: sync up the spec NESTEDSTRUCT = 0x21, //DEPRECATED (use STRUCT) BYVALSTR = 0x22, ANSIBSTR = 0x23, TBSTR = 0x24, // select BSTR or ANSIBSTR depending on platform VARIANTBOOL = 0x25, // (2-byte boolean value: TRUE = -1, FALSE = 0) FUNC = 0x26, ASANY = 0x28, ARRAY = 0x2A, LPSTRUCT = 0x2B, CUSTOMMARSHALER = 0x2C, // Custom marshaler native type. This must be followed ////////////////////////// by a string of the following format: ////////////////////////// "Native type name/0Custom marshaler type name/0Optional cookie/0" ////////////////////////// Or ////////////////////////// "{Native type GUID}/0Custom marshaler type name/0Optional cookie/0" ERROR = 0x2D, // This native type coupled with ELEMENT_TYPE_I4 will map to VT_HRESULT MAX = 0x50 // first invalid element type } public enum VariantTypes { VT_EMPTY = 0, VT_NULL = 1, VT_I2 = 2, VT_I4 = 3, VT_R4 = 4, VT_R8 = 5, VT_CY = 6, VT_DATE = 7, VT_BSTR = 8, VT_DISPATCH = 9, VT_ERROR = 10, VT_BOOL = 11, VT_VARIANT = 12, VT_UNKNOWN = 13, VT_DECIMAL = 14, VT_I1 = 16, VT_UI1 = 17, VT_UI2 = 18, VT_UI4 = 19, VT_I8 = 20, VT_UI8 = 21, VT_INT = 22, VT_UINT = 23, VT_VOID = 24, VT_HRESULT = 25, VT_PTR = 26, VT_SAFEARRAY = 27, VT_CARRAY = 28, VT_USERDEFINED = 29, VT_LPSTR = 30, VT_LPWSTR = 31, VT_RECORD = 36, VT_FILETIME = 64, VT_BLOB = 65, VT_STREAM = 66, VT_STORAGE = 67, VT_STREAMED_OBJECT = 68, VT_STORED_OBJECT = 69, VT_BLOB_OBJECT = 70, VT_CF = 71, VT_CLSID = 72, VT_BSTR_BLOB = 0x0FFF, VT_VECTOR = 0x1000, VT_ARRAY = 0x2000, VT_BYREF = 0x4000, VT_RESERVED = 0x8000, VT_ILLEGAL = 0xFFFF, VT_ILLEGALMASKED = 0x0FFF, VT_TYPEMASK = 0x0FFF }; public enum TokenType : byte { Module = 0x00, TypeRef = 0x01, TypeDef = 0x02, FieldPtr = 0x03, // Not Supported Field = 0x04, MethodPtr = 0x05, // Not Supported Method = 0x06, ParamPtr = 0x07, // Not Supported Param = 0x08, InterfaceImpl = 0x09, MemberRef = 0x0A, Constant = 0x0B, CustomAttribute = 0x0C, FieldMarshal = 0x0D, DeclSecurity = 0x0E, ClassLayout = 0x0F, FieldLayout = 0x10, StandAloneSig = 0x11, EventMap = 0x12, EventPtr = 0x13, // Not Supported Event = 0x14, PropertyMap = 0x15, PropertyPtr = 0x16, // Not Supported Property = 0x17, MethodSemantics = 0x18, MethodImpl = 0x19, ModuleRef = 0x1A, TypeSpec = 0x1B, ImplMap = 0x1C, FieldRVA = 0x1D, ENCLog = 0x1E, // Not Supported ENCMap = 0x1F, // Not Supported Assembly = 0x20, AssemblyProcessor = 0x21, // Ignored AssemblyOS = 0x22, // Ignored AssemblyRef = 0x23, AssemblyRefProcessor = 0x24, // Ignored AssemblyRefOS = 0x25, // Ignored File = 0x26, ExportedType = 0x27, // Not Supported ManifestResource = 0x28, NestedClass = 0x29, GenericParam = 0x2A, MethodSpec = 0x2B, GenericParamConstraint = 0x2C, Count = GenericParamConstraint + 1, // Common synonyms. FieldDef = Field, MethodDef = Method, ParamDef = Param, Permission = DeclSecurity, Signature = StandAloneSig, String = 0x70, Illegal = 0xFF, } //--// // // Section 23.1.1 of ECMA spec, Partition II // public enum HashAlgorithmID { None = 0x0000, MD5 = 0x8003, SHA1 = 0x8004 } // // Section 23.1.2 of ECMA spec, Partition II // [Flags] public enum AssemblyFlags { PublicKey = 0x0001, // The assembly ref holds the full (unhashed) public key. CompatibilityMask = 0x0070, SideBySideCompatible = 0x0000, // The assembly is side by side compatible. NonSideBySideAppDomain = 0x0010, // The assembly cannot execute with other versions if they are executing in the same application domain. NonSideBySideProcess = 0x0020, // The assembly cannot execute with other versions if they are executing in the same process. NonSideBySideMachine = 0x0030, // The assembly cannot execute with other versions if they are executing on the same machine. EnableJITcompileTracking = 0x8000, // From "DebuggableAttribute". DisableJITcompileOptimizer = 0x4000 // From "DebuggableAttribute". } // // Section 23.1.4 of ECMA spec, Partition II // [Flags] public enum EventAttributes : ushort { SpecialName = 0x0200, // Event is special. Name describes how. ReservedMask = 0x0400, // Reserved flags for Runtime use only. RTSpecialName = 0x0400 // Runtime (metadata internal APIs) should check name encoding. } // // Section 23.1.5 of ECMA spec, Partition II // [Flags] public enum FieldAttributes : ushort { FieldAccessMask = 0x0007, // member access mask - Use this mask to retrieve accessibility information. PrivateScope = 0x0000, // Member not referenceable. Private = 0x0001, // Accessible only by the parent type. FamANDAssem = 0x0002, // Accessible by sub-types only in this Assembly. Assembly = 0x0003, // Accessibly by anyone in the Assembly. Family = 0x0004, // Accessible only by type and sub-types. FamORAssem = 0x0005, // Accessibly by sub-types anywhere, plus anyone in assembly. Public = 0x0006, // Accessibly by anyone who has visibility to this scope. // end member access mask // field contract attributes. Static = 0x0010, // Defined on type, else per instance. InitOnly = 0x0020, // Field may only be initialized, not written to after init. Literal = 0x0040, // Value is compile time constant. NotSerialized = 0x0080, // Field does not have to be serialized when type is remoted. SpecialName = 0x0200, // field is special. Name describes how. // interop attributes PinvokeImpl = 0x2000, // Implementation is forwarded through pinvoke. // Reserved flags for runtime use only. ReservedMask = 0x9500, RTSpecialName = 0x0400, // Runtime(metadata internal APIs) should check name encoding. HasFieldMarshal = 0x1000, // Field has marshalling information. HasDefault = 0x8000, // Field has default. HasFieldRVA = 0x0100 // Field has RVA. } // // Section 23.1.6 of ECMA spec, Partition II // [Flags] public enum FileAttributes { ContainsMetaData = 0x0000, // This is not a resource file, ContainsNoMetaData = 0x0001 // This is a resource file or other non-metadata-containing file } // // Section 23.1.7 of ECMA spec, Partition II // [Flags] public enum GenericParameterAttributes : ushort { VarianceMask = 0x0003, NonVariant = 0x0000, // The generic parameter is non-variant Covariant = 0x0001, // The generic parameter is covariant Contravariant = 0x0002, // The generic parameter is contravariant SpecialConstraintMask = 0x001C, ReferenceTypeConstraint = 0x0004, // The generic parameter has the class special constraint NotNullableValueTypeConstraint = 0x0008, // The generic parameter has the valuetype special constraint DefaultConstructorConstraint = 0x0010, // The generic parameter has the .ctor special constraint } // // Section 23.1.8 of ECMA spec, Partition II // [Flags] public enum ImplementationMapAttributes : ushort { NoMangle = 0x0001, // Pinvoke is to use the member name as specified. // Character set flags CharSetMask = 0x0006, // Use this mask to retrieve the CharSet information. CharSetNotSpec = 0x0000, CharSetAnsi = 0x0002, CharSetUnicode = 0x0004, CharSetAuto = 0x0006, SupportsLastError = 0x0040, // Information about target function. Not relevant for fields. // None of the calling convention flags is relevant for fields. CallConvMask = 0x0700, CallConvWinapi = 0x0100, // Pinvoke will use native callconv appropriate to target windows platform. CallConvCdecl = 0x0200, CallConvStdcall = 0x0300, CallConvThiscall = 0x0400, // In M9, pinvoke will raise exception. CallConvFastcall = 0x0500 } // // Section 23.1.9 of ECMA spec, Partition II // [Flags] public enum ManifestResourceAttributes { VisibilityMask = 0x0007, Public = 0x0001, // The Resource is exported from the Assembly. Private = 0x0002 // The Resource is private to the Assembly. } // // Section 23.1.10 of ECMA spec, Partition II // [Flags] public enum MethodAttributes : ushort { // member access attributes MemberAccessMask = 0x0007, // Use this mask to retrieve accessibility information. PrivateScope = 0x0000, // Member not referenceable. Private = 0x0001, // Accessible only by the parent type. FamANDAssem = 0x0002, // Accessible by sub-types only in this Assembly. Assem = 0x0003, // Accessibly by anyone in the Assembly. Family = 0x0004, // Accessible only by type and sub-types. FamORAssem = 0x0005, // Accessibly by sub-types anywhere, plus anyone in assembly. Public = 0x0006, // Accessibly by anyone who has visibility to this scope. // method contract attributes. Static = 0x0010, // Defined on type, else per instance. Final = 0x0020, // Method may not be overridden. Virtual = 0x0040, // Method virtual. HideBySig = 0x0080, // Method hides by name+sig, else just by name. // vtable layout mask - Use this mask to retrieve vtable attributes. VtableLayoutMask = 0x0100, ReuseSlot = 0x0000, // The default. NewSlot = 0x0100, // Method always gets a new slot in the vtable. Strict = 0x0200, // method implementation attributes. Abstract = 0x0400, // Method does not provide an implementation. SpecialName = 0x0800, // Method is special. Name describes how. // interop attributes PinvokeImpl = 0x2000, // Implementation is forwarded through pinvoke. UnmanagedExport = 0x0008, // Managed method exported via thunk to unmanaged code. // Reserved flags for runtime use only. ReservedMask = 0xD000, RTSpecialName = 0x1000, // Runtime should check name encoding. HasSecurity = 0x4000, // Method has security associate with it. RequireSecObject = 0x8000 // Method calls another method containing security code. } // // Section 23.1.11 of ECMA spec, Partition II // [Flags] public enum MethodImplAttributes : ushort { // code impl mask CodeTypeMask = 0x0003, // Flags about code type. IL = 0x0000, // Method impl is IL. Native = 0x0001, // Method impl is native. OPTIL = 0x0002, // Method impl is OPTIL Runtime = 0x0003, // Method impl is provided by the runtime. // managed mask ManagedMask = 0x0004, // Flags specifying whether the code is managed or unmanaged. Unmanaged = 0x0004, // Method impl is unmanaged, otherwise managed. Managed = 0x0000, // Method impl is managed. // implementation info and interop ForwardRef = 0x0010, // Indicates method is defined; used primarily in merge scenarios. PreserveSig = 0x0080, // Indicates method sig is not to be mangled to do HRESULT conversion. InternalCall = 0x1000, // Reserved for internal use. Synchronized = 0x0020, // Method is single threaded through the body. NoInlining = 0x0008, // Method may not be inlined. MaxMethodImplVal = 0xFFFF // Range check value } // // Section 23.1.12 of ECMA spec, Partition II // [Flags] public enum MethodSemanticAttributes : ushort { Setter = 0x0001, // Setter for property Getter = 0x0002, // Getter for property Other = 0x0004, // other method for property or event AddOn = 0x0008, // AddOn method for event RemoveOn = 0x0010, // RemoveOn method for event Fire = 0x0020 // Fire method for event } // // Section 23.1.13 of ECMA spec, Partition II // [Flags] public enum ParamAttributes : ushort { In = 0x0001, // Param is [In] Out = 0x0002, // Param is [out] Optional = 0x0010, // Param is optional // Reserved flags for Runtime use only. ReservedMask = 0xF000, HasDefault = 0x1000, // Param has default value. HasFieldMarshal = 0x2000, // Param has FieldMarshal. Unused = 0xCFE0 } // // Section 23.1.14 of ECMA spec, Partition II // [Flags] public enum PropertyAttributes : ushort { SpecialName = 0x0200, // property is special. Name describes how. // Reserved flags for Runtime use only. ReservedMask = 0xF400, RTSpecialName = 0x0400, // Runtime(metadata internal APIs) should check name encoding. HasDefault = 0x1000, // Property has default Unused = 0xE9FF } // // Section 23.1.15 of ECMA spec, Partition II // [Flags] public enum TypeAttributes { VisibilityMask = 0x00000007, NotPublic = 0x00000000, // Class is not public scope. Public = 0x00000001, // Class is public scope. NestedPublic = 0x00000002, // Class is nested with public visibility. NestedPrivate = 0x00000003, // Class is nested with private visibility. NestedFamily = 0x00000004, // Class is nested with family visibility. NestedAssembly = 0x00000005, // Class is nested with assembly visibility. NestedFamANDAssem = 0x00000006, // Class is nested with family and assembly visibility. NestedFamORAssem = 0x00000007, // Class is nested with family or assembly visibility. // Use this mask to retrieve class layout informaiton // 0 is AutoLayout, 0x2 is SequentialLayout, 4 is ExplicitLayout LayoutMask = 0x00000018, AutoLayout = 0x00000000, // Class fields are auto-laid out SequentialLayout = 0x00000008, // Class fields are laid out sequentially ExplicitLayout = 0x00000010, // Layout is supplied explicitly // end layout mask // Use this mask to distinguish a type declaration as a Class, ValueType or Interface ClassSemanticsMask = 0x00000020, Class = 0x00000000, // Type is a class. Interface = 0x00000020, // Type is an interface. // Special semantics in addition to class semantics. Abstract = 0x00000080, // Class is abstract Sealed = 0x00000100, // Class is concrete and may not be extended SpecialName = 0x00000400, // Class name is special. Name describes how. // Implementation attributes. Import = 0x00001000, // Class / interface is imported Serializable = 0x00002000, // The class is Serializable. // Use tdStringFormatMask to retrieve string information for native interop StringFormatMask = 0x00030000, AnsiClass = 0x00000000, // LPTSTR is interpreted as ANSI in this class UnicodeClass = 0x00010000, // LPTSTR is interpreted as UNICODE AutoClass = 0x00020000, // LPTSTR is interpreted automatically CustomFormatClass = 0x00030000, // A non-standard encoding specified by CustomFormatMask CustomFormatMask = 0x00C00000, // Use this mask to retrieve non-standard encoding information for native interop. The meaning of the values of these 2 bits is unspecified. // end string format mask BeforeFieldInit = 0x00100000, // Initialize the class any time before first static field access. // Flags reserved for runtime use. ReservedMask = 0x00040800, RTSpecialName = 0x00000800, // Runtime should check name encoding. HasSecurity = 0x00040000, // Class has security associate with it. } // // Section 23.1.16 of ECMA spec, Partition II // public enum ElementTypes : byte { END = 0x00, VOID = 0x01, BOOLEAN = 0x02, CHAR = 0x03, I1 = 0x04, U1 = 0x05, I2 = 0x06, U2 = 0x07, I4 = 0x08, U4 = 0x09, I8 = 0x0A, U8 = 0x0B, R4 = 0x0C, R8 = 0x0D, STRING = 0x0E, ///////////////////////// every type above PTR will be simple type PTR = 0x0F, // PTR BYREF = 0x10, // BYREF ///////////////////////// Please use VALUETYPE. VALUECLASS is deprecated. VALUETYPE = 0x11, // VALUETYPE CLASS = 0x12, // CLASS VAR = 0x13, // a class type variable VAR ARRAY = 0x14, // MDARRAY ... ... GENERICINST = 0x15, // instantiated type TYPEDBYREF = 0x16, // This is a simple type. I = 0x18, // native integer size U = 0x19, // native unsigned integer size FNPTR = 0x1B, // FNPTR OBJECT = 0x1C, // Shortcut for System.Object SZARRAY = 0x1D, // Shortcut for single dimension zero lower bound array ///////////////////////// SZARRAY ///////////////////////// This is only for binding MVAR = 0x1E, // a method type variable MVAR CMOD_REQD = 0x1F, // required C modifier : E_T_CMOD_REQD CMOD_OPT = 0x20, // optional C modifier : E_T_CMOD_OPT ///////////////////////// This is for signatures generated internally (which will not be persisted in any way). INTERNAL = 0x21, // INTERNAL ///////////////////////// Note that this is the max of base type excluding modifiers MAX = 0x22, // first invalid element type MODIFIER = 0x40, SENTINEL = 0x01 | MODIFIER, // sentinel for varargs PINNED = 0x05 | MODIFIER } public enum SerializationTypes { BOOLEAN = ElementTypes.BOOLEAN, CHAR = ElementTypes.CHAR, I1 = ElementTypes.I1, U1 = ElementTypes.U1, I2 = ElementTypes.I2, U2 = ElementTypes.U2, I4 = ElementTypes.I4, U4 = ElementTypes.U4, I8 = ElementTypes.I8, U8 = ElementTypes.U8, R4 = ElementTypes.R4, R8 = ElementTypes.R8, STRING = ElementTypes.STRING, OBJECT = ElementTypes.OBJECT, SZARRAY = ElementTypes.SZARRAY, // Shortcut for single dimension zero lower bound array TYPE = 0x50, TAGGED_OBJECT = 0x51, FIELD = 0x53, PROPERTY = 0x54, ENUM = 0x55 } } ================================================ FILE: Zelig/Zelig/CompileTime/MetaData/Normalized/MetaDataClassLayout.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // namespace Microsoft.Zelig.MetaData.Normalized { using System; // // Don't remove "sealed" attribute unless you read comments on Equals method. // public sealed class MetaDataClassLayout : MetaDataObject, IMetaDataUnique { // // State // internal short m_packingSize; internal int m_classSize; // // Constructor Methods // internal MetaDataClassLayout( int token ) : base( token ) { } //--// // // MetaDataEquality Methods // public override bool Equals( object obj ) { if(obj is MetaDataClassLayout) // Since the class is sealed (no subclasses allowed), there's no need to compare using .GetType() { MetaDataClassLayout other = (MetaDataClassLayout)obj; if(m_packingSize == other.m_packingSize && m_classSize == other.m_classSize ) { return true; } } return false; } public override int GetHashCode() { return (int)m_packingSize << 10 ^ (int)m_classSize ; } // // Helper Methods // internal override MetaDataObject MakeUnique() { throw new NotNormalized( "MakeUnique" ); } // // Access Methods // public short PackingSize { get { return m_packingSize; } } public int ClassSize { get { return m_classSize; } } // // Debug Methods // public override String ToString() { return "MetaDataClassLayout(" + m_packingSize + "," + m_classSize + ")"; } public override void Dump( IMetaDataDumper writer ) { throw new NotNormalized( "Dump" ); } } } ================================================ FILE: Zelig/Zelig/CompileTime/MetaData/Normalized/MetaDataConstant.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // namespace Microsoft.Zelig.MetaData.Normalized { using System; // // Don't remove "sealed" attribute unless you read comments on Equals method. // public sealed class MetaDataConstant : MetaDataObject, IMetaDataUnique { // // State // internal Object m_value; // // Constructor Methods // internal MetaDataConstant( int token ) : base( token ) { } //--// // // MetaDataEquality Methods // public override bool Equals( object obj ) { if(obj is MetaDataConstant) // Since the class is sealed (no subclasses allowed), there's no need to compare using .GetType() { MetaDataConstant other = (MetaDataConstant)obj; return Object.Equals( m_value, other.m_value ); } return false; } public override int GetHashCode() { return 0xDEAD01; // Just to have something... } // // Helper Methods // internal override MetaDataObject MakeUnique() { throw new NotNormalized( "MakeUnique" ); } // // Access Methods // public object Value { get { return m_value; } } // // Debug Methods // public override String ToString() { System.Text.StringBuilder sb = new System.Text.StringBuilder( "MetaDataConstant(" ); sb.Append( m_value ); sb.Append( ")" ); return sb.ToString(); } public override void Dump( IMetaDataDumper writer ) { throw new NotNormalized( "Dump" ); } } } ================================================ FILE: Zelig/Zelig/CompileTime/MetaData/Normalized/MetaDataCustomAttribute.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // namespace Microsoft.Zelig.MetaData.Normalized { using System; // // Don't remove "sealed" attribute unless you read comments on Equals method. // public sealed class MetaDataCustomAttribute : MetaDataObject, IMetaDataUnique { // // State // internal readonly MetaDataAssembly m_owner; internal MetaDataMethodAbstract m_constructor; internal Object[] m_fixedArgs; internal NamedArg[] m_namedArgs; // // Constructor Methods // internal MetaDataCustomAttribute( MetaDataAssembly owner , int token ) : base( token ) { m_owner = owner; } // // MetaDataEquality Methods // public override bool Equals( object obj ) { if(obj is MetaDataCustomAttribute) // Since the class is sealed (no subclasses allowed), there's no need to compare using .GetType() { MetaDataCustomAttribute other = (MetaDataCustomAttribute)obj; if(m_owner == other.m_owner && m_constructor == other.m_constructor ) { if(ArrayUtility.ArrayEquals( m_fixedArgs, other.m_fixedArgs ) && ArrayUtility.ArrayEquals( m_namedArgs, other.m_namedArgs ) ) { return true; } } } return false; } public override int GetHashCode() { return m_constructor.GetHashCode(); } // // Helper Methods // internal override MetaDataObject MakeUnique() { return (MetaDataObject)m_owner.MakeUnique( this ); } // // Access Methods // public MetaDataAssembly Owner { get { return m_owner; } } public MetaDataMethodAbstract Constructor { get { return m_constructor; } } public Object[] FixedArgs { get { return m_fixedArgs; } } public NamedArg[] NamedArgs { get { return m_namedArgs; } } // // Debug Methods // public override String ToString() { System.Text.StringBuilder sb = new System.Text.StringBuilder( "MetaDataCustomAttribute(" ); sb.Append( m_constructor ); sb.Append( "," ); if(m_fixedArgs != null && m_fixedArgs.Length > 0) { sb.Append( "FixedArgs(" ); for(int i = 0; i < m_fixedArgs.Length; i++) { if(i != 0) sb.Append( "," ); sb.Append( m_fixedArgs[i] ); } sb.Append( ")," ); } if(m_namedArgs != null && m_namedArgs.Length > 0) { sb.Append( "NamedArgs(" ); for(int i = 0; i < m_namedArgs.Length; i++) { if(i != 0) sb.Append( "," ); sb.Append( m_namedArgs[i] ); } sb.Append( ")," ); } sb.Append( ")" ); return sb.ToString(); } public override void Dump( IMetaDataDumper writer ) { MetaDataMethodBase md = (MetaDataMethodBase)m_constructor; writer.WriteLine( ".custom {0} {1}", TokenToString( m_token ), md.DumpSignature( writer, null, true ) ); } //--// public class NamedArg { // // State // private bool m_isFieldArg; private int m_arrayDim; private String m_name; private SerializationTypes m_type; private Object m_value; // // Constructor Methods // internal NamedArg( bool isFieldArg , int arrayDim , String name , SerializationTypes type , Object value ) { m_isFieldArg = isFieldArg; m_arrayDim = arrayDim; m_type = type; m_name = name; m_value = value; } public bool IsFieldArg { get { return m_isFieldArg; } } public bool IsArray { get { return m_arrayDim >= 0; } } public int ArrayDim { get { if(m_arrayDim < 0) { throw new Exception( "NamedArg is not an array" ); } return m_arrayDim; } } public SerializationTypes Type { get { return m_type; } } public String Name { get { return m_name; } } public Object Value { get { return m_value; } } public override String ToString() { return "NamedArg(" + m_name + ":" + m_type + ((m_arrayDim < 0) ? "" : ("[" + m_arrayDim + "]")) + "->" + m_value + ")"; } } } } ================================================ FILE: Zelig/Zelig/CompileTime/MetaData/Normalized/MetaDataDeclSecurity.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // namespace Microsoft.Zelig.MetaData.Normalized { using System; // // Don't remove "sealed" attribute unless you read comments on Equals method. // public sealed class MetaDataDeclSecurity : MetaDataObject, IMetaDataUnique { // // State // internal IMetaDataHasDeclSecurity m_owner; internal short m_action; internal byte[] m_permissionSet; // // Constructor Methods // internal MetaDataDeclSecurity( int token ) : base( token ) { } // // MetaDataEquality Methods // public override bool Equals( object obj ) { if(obj is MetaDataDeclSecurity) // Since the class is sealed (no subclasses allowed), there's no need to compare using .GetType() { MetaDataDeclSecurity other = (MetaDataDeclSecurity)obj; throw new NotNormalized( "MetaDataEquality" ); } return false; } public override int GetHashCode() { throw new NotNormalized( "MetaDataEquality" ); } // // Helper Methods // internal override MetaDataObject MakeUnique() { throw new NotNormalized( "MakeUnique" ); } // // Access Methods // public short Action { get { return m_action; } } public IMetaDataHasDeclSecurity Owner { get { return m_owner; } } public byte[] PermissionSet { get { return m_permissionSet; } } // Debug Methods public override String ToString() { return "MetaDataDeclSecurity(" + m_owner + "," + m_action + "," + m_permissionSet + ")"; } public override void Dump( IMetaDataDumper writer ) { throw new NotNormalized( "Dump" ); } } } ================================================ FILE: Zelig/Zelig/CompileTime/MetaData/Normalized/MetaDataEvent.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // namespace Microsoft.Zelig.MetaData.Normalized { using System; // // Don't remove "sealed" attribute unless you read comments on Equals method. // public sealed class MetaDataEvent : MetaDataObject, IMetaDataHasSemantic, IMetaDataUnique { // // State // internal readonly MetaDataTypeDefinitionAbstract m_owner; internal EventAttributes m_flags; internal String m_name; internal MetaDataTypeDefinitionAbstract m_eventType; // // Constructor Methods // internal MetaDataEvent( MetaDataTypeDefinitionAbstract owner , int token ) : base( token ) { m_owner = owner; } //--// // // MetaDataEquality Methods // public override bool Equals( object obj ) { if(obj is MetaDataEvent) // Since the class is sealed (no subclasses allowed), there's no need to compare using .GetType() { MetaDataEvent other = (MetaDataEvent)obj; if(m_owner == other.m_owner && m_flags == other.m_flags && m_name == other.m_name && m_eventType == other.m_eventType ) { return true; } } return false; } public override int GetHashCode() { return (int)m_flags ^ m_name .GetHashCode() ^ 0x00DEAD03; } // // Helper Methods // internal override MetaDataObject MakeUnique() { return m_owner.MakeUnique( this ); } // // Access Methods // public MetaDataTypeDefinitionAbstract Owner { get { return m_owner; } } public EventAttributes Flags { get { return m_flags; } } public String Name { get { return m_name; } } // Returns one of MetaData{TypeDef,TypeRef,TypeSpec} public MetaDataTypeDefinitionAbstract Type { get { return m_eventType; } } // // Debug Methods // public override String ToString() { return "MetaDataEvent(" + m_flags + "," + m_name + "," + m_eventType + ")"; } public override void Dump( IMetaDataDumper writer ) { writer.WriteLine( ".event {0} {1} {2} {3}", TokenToString( m_token ), m_flags, m_name, m_eventType.ToStringWithAbbreviations( writer ) ); } } } ================================================ FILE: Zelig/Zelig/CompileTime/MetaData/Normalized/MetaDataField.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // namespace Microsoft.Zelig.MetaData.Normalized { using System; // // Don't remove "sealed" attribute unless you read comments on Equals method. // public sealed class MetaDataField : MetaDataFieldAbstract { // // State // internal readonly MetaDataTypeDefinitionAbstract m_owner; internal FieldAttributes m_flags; internal string m_name; internal SignatureField m_signature; internal MetaDataFieldRVA m_fieldRVA; internal MetaDataConstant m_constant; internal MetaDataFieldLayout m_layout; // // Constructor Methods // internal MetaDataField( MetaDataTypeDefinitionAbstract owner , int token ) : base( token ) { m_owner = owner; } // // MetaDataEquality Methods // public override bool Equals( object obj ) { if(obj is MetaDataField) // Since the class is sealed (no subclasses allowed), there's no need to compare using .GetType() { MetaDataField other = (MetaDataField)obj; if(m_owner == other.m_owner && m_flags == other.m_flags && m_name == other.m_name && m_signature == other.m_signature ) { return true; } } return false; } public override int GetHashCode() { return m_owner.GetHashCode() ^ (int)m_flags ^ m_name .GetHashCode(); } // // Helper Methods // internal override MetaDataObject MakeUnique() { return m_owner.MakeUnique( this ); } internal bool Match( string name , SignatureField sig ) { if(m_name == name) { return m_signature.Match( sig ); } return false; } //--// // // Access Methods // public MetaDataTypeDefinitionAbstract Owner { get { return m_owner; } } public FieldAttributes Flags { get { return m_flags; } } public string Name { get { return m_name; } } public SignatureField FieldSignature { get { return m_signature; } } public override bool IsOpenField { get { return m_signature.IsOpenType; } } public override bool UsesTypeParameters { get { return m_signature.UsesTypeParameters; } } public override bool UsesMethodParameters { get { return m_signature.UsesMethodParameters; } } //// public Object DefaultValueToType( ElementTypes type ) //// { //// if((this.flags & Attributes.HasDefault) != 0 && this.constant != null) //// { //// return this.constant.ValueToType( type ); //// } //// else //// { //// return this.DefaultValue; //// } //// } public Object DefaultValue { get { if((m_flags & FieldAttributes.HasDefault) != 0 && m_constant != null) { return m_constant.Value; } else if((m_flags & FieldAttributes.HasFieldRVA) != 0 && m_fieldRVA != null) { return m_fieldRVA.DataBytes; } else { return null; } } } public MetaDataFieldLayout Layout { get { return m_layout; } } // // Debug Methods // public override string FullName { get { System.Text.StringBuilder sb = new System.Text.StringBuilder(); sb.Append( m_flags ); sb.Append( "," ); sb.Append( m_name ); sb.Append( "," ); sb.Append( m_signature ); return sb.ToString(); } } public override String ToString() { return "MetaDataField(" + this.FullName + ")"; } public override String ToString( IMetaDataDumper context ) { System.Text.StringBuilder sb = new System.Text.StringBuilder(); sb.Append( m_signature.TypeSignature.ToStringWithAbbreviations( context.PushContext( m_owner ) ) ); sb.Append( " " ); sb.Append( m_owner.ToStringWithAbbreviations( context ) ); sb.Append( "::" ); sb.Append( m_name ); sb.Append( " " ); sb.Append( TokenToString( m_token ) ); return sb.ToString(); } public override void Dump( IMetaDataDumper writer ) { System.Text.StringBuilder sb = new System.Text.StringBuilder( ".field " ); sb.Append( TokenToString( m_token ) ); sb.Append( " " ); sb.Append( EnumToString( m_flags ) ); sb.Append( m_signature.TypeSignature.ToStringWithAbbreviations( writer ) ); sb.Append( " " ); sb.Append( m_name ); if(m_constant != null) { sb.Append( " = " ); sb.Append( m_constant.Value ); } writer.WriteLine( sb.ToString() ); } private static string EnumToString( FieldAttributes val ) { System.Text.StringBuilder sb = new System.Text.StringBuilder(); if((val & FieldAttributes.FieldAccessMask) == FieldAttributes.Public ) sb.Append( "public " ); if((val & FieldAttributes.FieldAccessMask) == FieldAttributes.Private ) sb.Append( "private " ); if((val & FieldAttributes.Static ) != 0 ) sb.Append( "static " ); if((val & FieldAttributes.FieldAccessMask) == FieldAttributes.Family ) sb.Append( "family " ); if((val & FieldAttributes.FieldAccessMask) == FieldAttributes.Assembly ) sb.Append( "assembly " ); if((val & FieldAttributes.FieldAccessMask) == FieldAttributes.FamANDAssem ) sb.Append( "famandassem " ); if((val & FieldAttributes.FieldAccessMask) == FieldAttributes.FamORAssem ) sb.Append( "famorassem " ); if((val & FieldAttributes.FieldAccessMask) == FieldAttributes.PrivateScope) sb.Append( "privatescope " ); if((val & FieldAttributes.InitOnly ) != 0 ) sb.Append( "initonly " ); if((val & FieldAttributes.Literal ) != 0 ) sb.Append( "literal " ); if((val & FieldAttributes.NotSerialized ) != 0 ) sb.Append( "notserialized " ); if((val & FieldAttributes.SpecialName ) != 0 ) sb.Append( "specialname " ); if((val & FieldAttributes.RTSpecialName ) != 0 ) sb.Append( "rtspecialname " ); return sb.ToString(); } } } ================================================ FILE: Zelig/Zelig/CompileTime/MetaData/Normalized/MetaDataFieldAbstract.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // namespace Microsoft.Zelig.MetaData.Normalized { using System; public abstract class MetaDataFieldAbstract : MetaDataObject, IMetaDataHasConstant, IMetaDataHasFieldMarshal, IMetaDataMemberForwarded, IMetaDataUnique { // // Constructor Methods // protected MetaDataFieldAbstract( int token ) : base( token ) { } // // Helper Methods // public abstract bool IsOpenField { get; } // // Debug Methods // public abstract string FullName { get; } public abstract String ToString( IMetaDataDumper context ); } } ================================================ FILE: Zelig/Zelig/CompileTime/MetaData/Normalized/MetaDataFieldLayout.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // namespace Microsoft.Zelig.MetaData.Normalized { using System; // // Don't remove "sealed" attribute unless you read comments on Equals method. // public sealed class MetaDataFieldLayout : MetaDataObject, IMetaDataUnique { // // State // internal int m_offset; // // Constructor Methods // internal MetaDataFieldLayout( int token ) : base( token ) { } // // MetaDataEquality Methods // public override bool Equals( object obj ) { if(obj is MetaDataFieldLayout) // Since the class is sealed (no subclasses allowed), there's no need to compare using .GetType() { MetaDataFieldLayout other = (MetaDataFieldLayout)obj; if(m_offset == other.m_offset) { return true; } } return false; } public override int GetHashCode() { return (int)m_offset; } // // Helper Methods // internal override MetaDataObject MakeUnique() { throw new NotNormalized( "MakeUnique" ); } // // Access Methods // public int Offset { get { return m_offset; } } // Debug Methods public override String ToString() { return "MetaDataFieldLayout(" + m_offset + ")"; } public override void Dump( IMetaDataDumper writer ) { throw new NotNormalized( "Dump" ); } } } ================================================ FILE: Zelig/Zelig/CompileTime/MetaData/Normalized/MetaDataFieldMarshal.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // namespace Microsoft.Zelig.MetaData.Normalized { using System; // // Don't remove "sealed" attribute unless you read comments on Equals method. // public sealed class MetaDataFieldMarshal : MetaDataObject, IMetaDataUnique { // // State // internal IMetaDataHasFieldMarshal m_owner; internal MarshalSpec m_nativeType; // // Constructor Methods // internal MetaDataFieldMarshal( int token ) : base( token ) { } // // MetaDataEquality Methods // public override bool Equals( object obj ) { if(obj is MetaDataFieldMarshal) // Since the class is sealed (no subclasses allowed), there's no need to compare using .GetType() { MetaDataFieldMarshal other = (MetaDataFieldMarshal)obj; throw new NotNormalized( "MetaDataEquality" ); } return false; } public override int GetHashCode() { throw new NotNormalized( "MetaDataEquality" ); } // // Helper Methods // internal override MetaDataObject MakeUnique() { throw new NotNormalized( "MakeUnique" ); } // // Access Methods // public IMetaDataHasFieldMarshal Owner { get { return m_owner; } } public MarshalSpec NativeType { get { return m_nativeType; } } // Debug Methods public override String ToString() { return "MetaDataFieldMarshal(" + ((MetaDataObject)m_owner).ToString() + "," + m_nativeType + ")"; } public override void Dump( IMetaDataDumper writer ) { throw new NotNormalized( "Dump" ); } } } ================================================ FILE: Zelig/Zelig/CompileTime/MetaData/Normalized/MetaDataFieldRVA.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // namespace Microsoft.Zelig.MetaData.Normalized { using System; // // Don't remove "sealed" attribute unless you read comments on Equals method. // public sealed class MetaDataFieldRVA : MetaDataObject, IMetaDataUnique { // // State // internal byte[] m_dataBytes; // // Constructor Methods // internal MetaDataFieldRVA( int token ) : base( token ) { } // // MetaDataEquality Methods // public override bool Equals( object obj ) { if(obj is MetaDataFieldRVA) // Since the class is sealed (no subclasses allowed), there's no need to compare using .GetType() { MetaDataFieldRVA other = (MetaDataFieldRVA)obj; return ArrayUtility.ByteArrayEquals( m_dataBytes, other.m_dataBytes ); } return false; } public override int GetHashCode() { return m_dataBytes.GetHashCode(); } // // Helper Methods // internal override MetaDataObject MakeUnique() { throw new NotNormalized( "MakeUnique" ); } // // Access Methods // public byte[] DataBytes { get { return m_dataBytes; } } // // Debug Methods // public override String ToString() { System.Text.StringBuilder sb = new System.Text.StringBuilder( "MetaDataFieldRVA(" ); for(int i = 0; i < m_dataBytes.Length; i++) { if(i != 0) sb.Append( "," ); sb.Append( m_dataBytes[i].ToString( "x2" ) ); } sb.Append( ")" ); return sb.ToString(); } public override void Dump( IMetaDataDumper writer ) { throw new NotNormalized( "Dump" ); } } } ================================================ FILE: Zelig/Zelig/CompileTime/MetaData/Normalized/MetaDataFieldWithContext.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // namespace Microsoft.Zelig.MetaData.Normalized { using System; // // Don't remove "sealed" attribute unless you read comments on Equals method. // public sealed class MetaDataFieldWithContext : MetaDataFieldAbstract, IMetaDataUnique { // // State // internal readonly MetaDataTypeDefinitionAbstract m_contextType; internal readonly MetaDataField m_baseField; // // Constructor Methods // internal MetaDataFieldWithContext( MetaDataTypeDefinitionAbstract contextType , MetaDataField baseField ) : base( 0 ) { m_contextType = contextType; m_baseField = baseField; } //--// // // MetaDataEquality Methods // public override bool Equals( object obj ) { if(obj is MetaDataFieldWithContext) // Since the class is sealed (no subclasses allowed), there's no need to compare using .GetType() { MetaDataFieldWithContext other = (MetaDataFieldWithContext)obj; if(m_contextType == other.m_contextType && m_baseField == other.m_baseField ) { return true; } } return false; } public override int GetHashCode() { return m_baseField.GetHashCode(); } // // Helper Methods // public override bool IsOpenField { get { if(m_baseField.IsOpenField) { if(m_contextType != null) { if(m_contextType.IsOpenType == false) { return false; } } return true; } return false; } } public override bool UsesTypeParameters { get { return m_baseField.UsesTypeParameters; } } public override bool UsesMethodParameters { get { return m_baseField.UsesMethodParameters; } } internal override MetaDataObject MakeUnique() { return m_contextType.MakeUnique( (IMetaDataUnique)this ); } // // Access Methods // public MetaDataTypeDefinitionAbstract ContextType { get { return m_contextType; } } public MetaDataField BaseField { get { return m_baseField; } } // // Debug Methods // public override string FullName { get { System.Text.StringBuilder sb = new System.Text.StringBuilder(); sb.Append( "{" ); sb.Append( m_contextType.FullName ); sb.Append( "}" ); sb.Append( m_baseField.FullName ); return sb.ToString(); } } public override string ToString() { return "MetaDataFieldWithContext(" + this.FullName + ")"; } public override String ToString( IMetaDataDumper context ) { string res; context = context.PushContext( m_contextType ); res = m_baseField.ToString( context ); return res; } public override void Dump( IMetaDataDumper writer ) { throw new NotNormalized( "Dump" ); } } } ================================================ FILE: Zelig/Zelig/CompileTime/MetaData/Normalized/MetaDataFile.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // namespace Microsoft.Zelig.MetaData.Normalized { using System; // // Don't remove "sealed" attribute unless you read comments on Equals method. // public sealed class MetaDataFile : MetaDataObject, IMetaDataImplementation, IMetaDataUnique { // // State // internal FileAttributes m_flags; internal String m_name; internal byte[] m_hashValue; // // Constructor Methods // internal MetaDataFile( int token ) : base( token ) { } // // MetaDataEquality Methods // public override bool Equals( object obj ) { if(obj is MetaDataFile) // Since the class is sealed (no subclasses allowed), there's no need to compare using .GetType() { MetaDataFile other = (MetaDataFile)obj; throw new NotNormalized( "MetaDataEquality" ); } return false; } public override int GetHashCode() { throw new NotNormalized( "MetaDataEquality" ); } // // Helper Methods // internal override MetaDataObject MakeUnique() { throw new NotNormalized( "MakeUnique" ); } // // Access Methods // public FileAttributes Flags { get { return m_flags; } } public String Name { get { return m_name; } } public byte[] HashValue { get { return m_hashValue; } } // // Debug Methods // public override String ToString() { System.Text.StringBuilder sb = new System.Text.StringBuilder( "MetaDataFile(" ); sb.Append( m_flags.ToString( "x" ) ); sb.Append( "," ); sb.Append( m_name ); sb.Append( ",[" ); for(int i = 0; i < m_hashValue.Length; i++) { if(i != 0) sb.Append( "," ); sb.Append( "0x" ); sb.Append( m_hashValue[i].ToString( "x2" ) ); } sb.Append( "])" ); return sb.ToString(); } public override void Dump( IMetaDataDumper writer ) { throw new NotNormalized( "Dump" ); } } } ================================================ FILE: Zelig/Zelig/CompileTime/MetaData/Normalized/MetaDataGenericMethodParam.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // namespace Microsoft.Zelig.MetaData.Normalized { using System; // // Don't remove "sealed" attribute unless you read comments on Equals method. // public sealed class MetaDataGenericMethodParam : MetaDataGenericParam, IMetaDataUnique { // // State // internal readonly MetaDataMethodGeneric m_owner; // // Constructor Methods // internal MetaDataGenericMethodParam( MetaDataMethodGeneric owner , int token ) : base( token ) { m_owner = owner; } // // MetaDataEquality Methods // public override bool Equals( object obj ) { if(obj is MetaDataGenericMethodParam) // Since the class is sealed (no subclasses allowed), there's no need to compare using .GetType() { MetaDataGenericMethodParam other = (MetaDataGenericMethodParam)obj; if(m_owner == other.m_owner) { return InnerEquals( other ); } } return false; } public override int GetHashCode() { return InnerGetHashCode(); } // // Helper Methods // internal override MetaDataObject MakeUnique() { return m_owner.MakeUnique( this ); } // // Debug Methods // public override String ToString() { return "MetaDataGenericMethodParam(" + m_owner.FullName + "," + m_name + ")"; } public override void Dump( IMetaDataDumper writer ) { throw new NotNormalized( "Dump" ); } } } ================================================ FILE: Zelig/Zelig/CompileTime/MetaData/Normalized/MetaDataGenericParam.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // namespace Microsoft.Zelig.MetaData.Normalized { using System; public abstract class MetaDataGenericParam : MetaDataObject { // // State // internal short m_number; internal GenericParameterAttributes m_flags; internal String m_name; internal MetaDataTypeDefinitionAbstract[] m_genericParamConstraints; // // Constructor Methods // internal MetaDataGenericParam( int token ) : base( token ) { } // // MetaDataEquality Methods // protected bool InnerEquals( MetaDataGenericParam other ) { if(m_number == other.m_number && m_flags == other.m_flags && m_name == other.m_name ) { if(ArrayUtility.ArrayEquals( m_genericParamConstraints, other.m_genericParamConstraints )) { return true; } } return false; } protected int InnerGetHashCode() { return (int)m_number ^ (int)m_flags ^ m_name .GetHashCode() ; } // // Access Methods // public short Number { get { return m_number; } } public GenericParameterAttributes Flags { get { return m_flags; } } public String Name { get { return m_name; } } public MetaDataTypeDefinitionAbstract[] GenericParamConstraints { get { return m_genericParamConstraints; } } // // Debug Methods // public String ToString( IMetaDataDumper context ) { return MetaDataTypeDefinitionAbstract.ParameterToString( context, m_number, this is MetaDataGenericMethodParam, m_name ); } } } ================================================ FILE: Zelig/Zelig/CompileTime/MetaData/Normalized/MetaDataGenericTypeParam.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // namespace Microsoft.Zelig.MetaData.Normalized { using System; // // Don't remove "sealed" attribute unless you read comments on Equals method. // public sealed class MetaDataGenericTypeParam : MetaDataGenericParam, IMetaDataUnique { // // State // internal readonly MetaDataTypeDefinitionAbstract m_owner; // // Constructor Methods // internal MetaDataGenericTypeParam( MetaDataTypeDefinitionAbstract owner , int token ) : base( token ) { m_owner = owner; } // // MetaDataEquality Methods // public override bool Equals( object obj ) { if(obj is MetaDataGenericTypeParam) // Since the class is sealed (no subclasses allowed), there's no need to compare using .GetType() { MetaDataGenericTypeParam other = (MetaDataGenericTypeParam)obj; if(m_owner == other.m_owner) { return InnerEquals( other ); } } return false; } public override int GetHashCode() { return InnerGetHashCode(); } // // Helper Methods // internal override MetaDataObject MakeUnique() { return m_owner.MakeUnique( (IMetaDataUnique)this ); } // // Debug Methods // public override String ToString() { return "MetaDataGenericTypeParam(" + m_owner.FullName + "," + m_name + ")"; } public override void Dump( IMetaDataDumper writer ) { throw new NotNormalized( "Dump" ); } } } ================================================ FILE: Zelig/Zelig/CompileTime/MetaData/Normalized/MetaDataImplMap.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // namespace Microsoft.Zelig.MetaData.Normalized { using System; // // Don't remove "sealed" attribute unless you read comments on Equals method. // public sealed class MetaDataImplMap : MetaDataObject, IMetaDataUnique { // // State // internal ImplementationMapAttributes m_flags; internal IMetaDataMemberForwarded m_memberForwarded; internal String m_importName; internal MetaDataModule m_importScope; // // Constructor Methods // internal MetaDataImplMap( int token ) : base( token ) { } // // MetaDataEquality Methods // public override bool Equals( object obj ) { if(obj is MetaDataImplMap) // Since the class is sealed (no subclasses allowed), there's no need to compare using .GetType() { MetaDataImplMap other = (MetaDataImplMap)obj; throw new NotNormalized( "MetaDataEquality" ); } return false; } public override int GetHashCode() { throw new NotNormalized( "MetaDataEquality" ); } // // Helper Methods // internal override MetaDataObject MakeUnique() { throw new NotNormalized( "MakeUnique" ); } // // Access Methods // public ImplementationMapAttributes Flags { get { return m_flags; } } public IMetaDataMemberForwarded MemberForwarded { get { return m_memberForwarded; } } public String ImportName { get { return m_importName; } } public MetaDataModule ImportScope { get { return m_importScope; } } // // Debug Methods // public override String ToString() { return "MetaDataImplMap(" + m_flags.ToString( "x" ) + "," + m_memberForwarded + "," + m_importName + "," + m_importScope + ")"; } public override void Dump( IMetaDataDumper writer ) { throw new NotNormalized( "Dump" ); } } } ================================================ FILE: Zelig/Zelig/CompileTime/MetaData/Normalized/MetaDataInterfaces.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // namespace Microsoft.Zelig.MetaData.Normalized { using System.Collections.Generic; // // Every class implementing this interface provides a proper implementation of the Equals and GetHashCode methods. // // The normalizer uses this property to guarantee that there's a single instantiation of an object, // so the rest of the system can use referential equality to compare metadata objects. // public interface IMetaDataUnique { } // // Many metadata tables contain tokens of multiple types, see CodeToken. // // To make the relationships between tables more explicit, instead of using a reference to MetaDataObject, // the classes that represent the various tables use references to these interfaces. // public interface IMetaDataObject { } public interface IMetaDataTypeDefOrRef : IMetaDataObject { } public interface IMetaDataHasConstant : IMetaDataObject { } public interface IMetaDataHasCustomAttribute : IMetaDataObject { } public interface IMetaDataHasFieldMarshal : IMetaDataObject { } public interface IMetaDataHasDeclSecurity : IMetaDataObject { } public interface IMetaDataMemberRefParent : IMetaDataObject { } public interface IMetaDataHasSemantic : IMetaDataObject { } public interface IMetaDataMethodDefOrRef : IMetaDataObject { } public interface IMetaDataMemberForwarded : IMetaDataObject { } public interface IMetaDataCustomAttributeType : IMetaDataObject { } public interface IMetaDataImplementation : IMetaDataObject { } public interface IMetaDataResolutionScope : IMetaDataObject { } public interface IMetaDataTypeOrMethodDef : IMetaDataObject { } public delegate void IMetaDataBootstrap_FilterTypesByCustomAttributeCallback( MetaDataTypeDefinitionAbstract td, MetaDataCustomAttribute ca ); // // Bootstrapping interface for the type system. // public interface IMetaDataBootstrap { MetaDataAssembly GetAssembly( string name ); MetaDataTypeDefinitionAbstract ResolveType( MetaDataAssembly asml, string nameSpace, string name ); MetaDataMethodBase GetApplicationEntryPoint(); void FilterTypesByCustomAttribute( MetaDataTypeDefinitionAbstract filter, IMetaDataBootstrap_FilterTypesByCustomAttributeCallback callback ); } // // Debug classes // public interface IMetaDataDumper { void IndentPush( string s ); void IndentPop ( string s ); void WriteLine(); void WriteLine( string s ); void WriteLine( string s , object arg1 ); void WriteLine( string s , object arg1 , object arg2 ); void WriteLine( string s , object arg1 , object arg2 , object arg3 ); void WriteLine( string s , params object[] args ); void Process( MetaDataObject obj , bool fOnlyOnce ); bool AlreadyProcessed( MetaDataObject obj ); MetaDataMethodAbstract GetContextMethodAndPop( out IMetaDataDumper context ); MetaDataTypeDefinitionAbstract GetContextTypeAndPop ( out IMetaDataDumper context ); IMetaDataDumper PushContext( MetaDataObject obj ); } } ================================================ FILE: Zelig/Zelig/CompileTime/MetaData/Normalized/MetaDataManifestResource.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // namespace Microsoft.Zelig.MetaData.Normalized { using System; using System.Collections.Generic; // // Don't remove "sealed" attribute unless you read comments on Equals method. // public sealed class MetaDataManifestResource : MetaDataObject, IMetaDataUnique { // // State // internal readonly MetaDataAssembly m_owner; internal int m_offset; internal ManifestResourceAttributes m_flags; internal String m_name; internal byte[] m_data; internal IMetaDataImplementation m_implementation; internal Dictionary< string, object > m_values; // // Constructor Methods // internal MetaDataManifestResource( MetaDataAssembly owner , int token ) : base( token ) { m_owner = owner; } // // MetaDataEquality Methods // public override bool Equals( object obj ) { if(obj is MetaDataManifestResource) // Since the class is sealed (no subclasses allowed), there's no need to compare using .GetType() { MetaDataManifestResource other = (MetaDataManifestResource)obj; if(m_owner == other.m_owner && m_offset == other.m_offset && m_flags == other.m_flags && m_name == other.m_name && m_implementation == other.m_implementation ) { return true; } } return false; } public override int GetHashCode() { int res = m_name.GetHashCode(); res ^= m_owner.GetHashCode(); return res; } // // Helper Methods // internal override MetaDataObject MakeUnique() { return (MetaDataObject)m_owner.MakeUnique( (IMetaDataUnique)this ); } // // Access Methods // public MetaDataAssembly Owner { get { return m_owner; } } public int Offset { get { return m_offset; } } public ManifestResourceAttributes Flags { get { return m_flags; } } public String Name { get { return m_name; } } public IMetaDataImplementation Implementation { get { return m_implementation; } } public byte[] Data { get { return m_data; } } public Dictionary< string, object > Values { get { return m_values; } } // // Debug Methods // public override String ToString() { return "MetaDataManifestResource(" + m_name + ")"; } public override void Dump( IMetaDataDumper writer ) { writer.WriteLine( ".mresource {0} {1} {2}", TokenToString( m_token ), m_flags, m_name ); } } } ================================================ FILE: Zelig/Zelig/CompileTime/MetaData/Normalized/MetaDataMethod.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // namespace Microsoft.Zelig.MetaData.Normalized { using System; // // Don't remove "sealed" attribute unless you read comments on Equals method. // public sealed class MetaDataMethod : MetaDataMethodBase, IMetaDataUnique { // // Constructor Methods // internal MetaDataMethod( MetaDataTypeDefinitionAbstract owner , int token ) : base( owner, token ) { } //--// // // MetaDataEquality Methods // public override bool Equals( object obj ) { if(obj is MetaDataMethod) // Since the class is sealed (no subclasses allowed), there's no need to compare using .GetType() { MetaDataMethod other = (MetaDataMethod)obj; return InnerEquals( other ); } return false; } public override int GetHashCode() { return (int)m_implFlags ^ (int)m_flags ^ m_name .GetHashCode() ^ m_signature.GetHashCode(); } // // Helper Methods // public override bool IsOpenMethod { get { return false; } } //--// // // Debug Methods // public override string ToString() { return "MetaDataMethod(" + this.FullName + ")"; } public override String ToString( IMetaDataDumper context ) { return InnerToString( context, null ); } public override void Dump( IMetaDataDumper writer ) { InnerDump( writer, null ); } } } ================================================ FILE: Zelig/Zelig/CompileTime/MetaData/Normalized/MetaDataMethodAbstract.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // namespace Microsoft.Zelig.MetaData.Normalized { using System; public abstract class MetaDataMethodAbstract : MetaDataObject, IMetaDataHasDeclSecurity, IMetaDataMethodDefOrRef, IMetaDataMemberForwarded, IMetaDataCustomAttributeType, IMetaDataTypeOrMethodDef { // // Constructor Methods // protected MetaDataMethodAbstract( int token ) : base( token ) { } //--// // // Helper Methods // public abstract bool IsOpenMethod { get; } // // Debug Methods // public abstract string FullName { get; } public abstract String ToString( IMetaDataDumper context ); } } ================================================ FILE: Zelig/Zelig/CompileTime/MetaData/Normalized/MetaDataMethodBase.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // namespace Microsoft.Zelig.MetaData.Normalized { using System; using System.Collections.Generic; public abstract class MetaDataMethodBase : MetaDataMethodAbstract { // // State // internal readonly MetaDataTypeDefinitionAbstract m_owner; internal MethodImplAttributes m_implFlags; internal MethodAttributes m_flags; internal string m_name; internal SignatureMethod m_signature; internal MetaDataParam[] m_paramList; internal SignatureType[] m_locals; internal bool m_initLocals; internal Instruction[] m_instructions; internal EHClause[] m_ehTable; internal int m_maxStack; internal Debugging.MethodDebugInfo m_debugInfo; // // Constructor Methods // protected MetaDataMethodBase( MetaDataTypeDefinitionAbstract owner , int token ) : base( token ) { m_owner = owner; } //--// // // MetaDataEquality Methods // protected bool InnerEquals( MetaDataMethodBase other ) { if(m_name == other.m_name && m_owner == other.m_owner ) { return m_signature.Equals( other.m_signature ); } return false; } protected int InnerGetHashCode() { return m_name.GetHashCode(); } // // Helper Methods // internal override MetaDataObject MakeUnique() { return MakeUnique( (IMetaDataUnique)this ); } internal MetaDataObject MakeUnique( IMetaDataUnique obj ) { return m_owner.MakeUnique( obj ); } //--// internal bool Match( string name , SignatureMethod sig ) { if(m_name == name) { return m_signature.Match( sig ); } return false; } //--// // // Access Methods // public MethodImplAttributes ImplFlags { get { return m_implFlags; } } public MethodAttributes Flags { get { return m_flags; } } public string Name { get { return m_name; } } public SignatureMethod Signature { get { return m_signature; } } public MetaDataTypeDefinitionAbstract Owner { get { return m_owner; } } public MetaDataParam[] ParamList { get { return m_paramList; } } public SignatureType[] Locals { get { return m_locals; } } public bool InitLocals { get { return m_initLocals; } } public Instruction[] Instructions { get { return m_instructions; } } public EHClause[] EHTable { get { return m_ehTable; } } public int MaxStack { get { return m_maxStack; } } public Debugging.MethodDebugInfo DebugInformation { get { return m_debugInfo; } } public override bool UsesTypeParameters { get { if(m_owner.UsesTypeParameters) return true; return m_signature.UsesTypeParameters; } } public override bool UsesMethodParameters { get { if(m_owner.UsesMethodParameters) return true; return m_signature.UsesMethodParameters; } } //--// public override string FullName { get { System.Text.StringBuilder sb = new System.Text.StringBuilder(); PrettyPrintSignature( sb ); return sb.ToString(); } } //--// // // Debug Methods // public void PrettyPrintSignature( System.Text.StringBuilder sb ) { if(m_signature != null) { sb.Append( SignatureMethod.EnumToString( m_signature.m_callingConvention ) ); sb.Append( m_signature.ReturnType.FullNameWithAbbreviation ); } sb.Append( " [" ); sb.Append( m_owner.Owner.Name ); sb.Append( "]" ); sb.Append( m_owner.FullName ); sb.Append( "::" ); sb.Append( m_name ); if(this is MetaDataMethodGeneric) { MetaDataMethodGeneric md2 = (MetaDataMethodGeneric)this; MetaDataGenericMethodParam[] genericParams = md2.GenericParams; if(genericParams != null) { sb.Append( "<" ); for(int i = 0; i < genericParams.Length; i++) { MetaDataGenericMethodParam param = genericParams[i]; if(i != 0) { sb.Append( ", " ); } if(param != null) { MetaDataTypeDefinitionAbstract[] genericParamConstraints = param.GenericParamConstraints; if(genericParamConstraints != null) { sb.Append( "(" ); for(int j = 0; j < genericParamConstraints.Length; j++) { MetaDataTypeDefinitionAbstract td = genericParamConstraints[j]; if(j != 0) { sb.Append( ", " ); } sb.Append( td.FullNameWithAbbreviation ); } sb.Append( ")" ); } sb.Append( param.Name ); } else { sb.AppendFormat( "$Param_{0}", i ); } } sb.Append( ">" ); } } sb.Append( "(" ); if(m_signature != null) { SignatureType[] parameters = m_signature.Parameters; for(int i = 0; i < parameters.Length; i++) { SignatureType td = parameters[i]; if(i != 0) { sb.Append( ", " ); } sb.Append( td.FullNameWithAbbreviation ); } } sb.Append( ")" ); } //--// protected void InnerDump( IMetaDataDumper writer , MetaDataGenericMethodParam[] genericParams ) { writer = writer.PushContext( this ); writer.WriteLine( ".method {0} {1}", TokenToString( m_token ), EnumToString( m_flags ) ); writer.WriteLine( " {0}{1}" , DumpSignature( writer, genericParams, false ), EnumToString( m_implFlags ) ); writer.IndentPush( "{" ); if(m_customAttributes != null) { foreach(MetaDataCustomAttribute ca in m_customAttributes) { writer.Process( ca, false ); } writer.WriteLine(); } writer.WriteLine( ".maxstack {0}", m_maxStack ); if(m_locals != null) { string[] localNames = (m_debugInfo != null) ? m_debugInfo.LocalVarNames : null; for(int num = 0; num < m_locals.Length; num++) { System.Text.StringBuilder sb = new System.Text.StringBuilder( ".local " ); sb.Append( m_locals[num].ToStringWithAbbreviations( writer ) ); if(localNames != null && localNames[num] != null) { sb.AppendFormat( " {0}", localNames[num] ); } else { sb.AppendFormat( " V_{0}", num + 1 ); } writer.WriteLine( sb.ToString() ); } writer.WriteLine(); } if(m_instructions != null) { List[] tryBlocksStart = new List[m_instructions.Length]; List[] tryBlocksEnd = new List[m_instructions.Length]; List[] handlersStart = new List[m_instructions.Length]; List[] handlersEnd = new List[m_instructions.Length]; if(m_ehTable != null) { foreach(EHClause eh in m_ehTable) { Set( tryBlocksStart, eh.TryOffset , eh ); Set( tryBlocksEnd , eh.TryEnd - 1, eh ); Set( handlersStart , eh.HandlerOffset , eh ); Set( handlersEnd , eh.HandlerEnd - 1, eh ); } } int indent = 0; for(int i = 0; i < m_instructions.Length; i++) { Instruction instr = m_instructions[i]; if(tryBlocksStart[i] != null) { EHClause ehLast = null; foreach(EHClause eh in tryBlocksStart[i]) { if(ehLast == null || ehLast.TryEnd != eh.TryEnd) { writer.WriteLine( ".try" ); writer.IndentPush( "{" ); indent++; } ehLast = eh; } } if(handlersStart[i] != null) { if(handlersStart[i].Count > 1) { throw new NotNormalized( "Two EH handlers start at the same position" ); } foreach(EHClause eh in handlersStart[i]) { switch(eh.Flags) { case EHClause.ExceptionFlag.None: if(eh.TypeObject != null) { writer.WriteLine( ".catch({0})", eh.TypeObject.ToString( writer ) ); } else { writer.WriteLine( ".catch" ); } break; case EHClause.ExceptionFlag.Finally: writer.WriteLine( ".finally" ); break; default: writer.WriteLine( ".filter" ); break; } writer.IndentPush( "{" ); indent++; } } Instruction.OpcodeInfo oi = instr.Operator; switch(oi.OperandFormat) { case Instruction.OpcodeOperand.Branch: { writer.WriteLine( "IL_{0:X4}: {1,-10} IL_{2:X4}", i, instr.Operator.Name, instr.Argument ); } break; case Instruction.OpcodeOperand.Switch: { writer.WriteLine( "IL_{0:X4}: {1,-10} ( ", i, instr.Operator.Name ); foreach(int target in (int[])instr.Argument) { writer.WriteLine( " IL_{0:X4}", target ); } writer.WriteLine( " )" ); } break; case Instruction.OpcodeOperand.Type: { MetaDataTypeDefinitionAbstract obj = (MetaDataTypeDefinitionAbstract)instr.Argument; writer.WriteLine( "IL_{0:X4}: {1,-10} {2}", i, instr.Operator.Name, obj.ToString( writer ) ); } break; case Instruction.OpcodeOperand.Method: { MetaDataMethodAbstract obj = (MetaDataMethodAbstract)instr.Argument; writer.WriteLine( "IL_{0:X4}: {1,-10} {2}", i, instr.Operator.Name, obj.ToString( writer ) ); } break; case Instruction.OpcodeOperand.Field: { MetaDataFieldAbstract obj = (MetaDataFieldAbstract)instr.Argument; writer.WriteLine( "IL_{0:X4}: {1,-10} {2}", i, instr.Operator.Name, obj.ToString( writer ) ); } break; case Instruction.OpcodeOperand.Token: { MetaDataObject obj = (MetaDataObject)instr.Argument; if(obj is MetaDataTypeDefinitionAbstract) goto case Instruction.OpcodeOperand.Type; if(obj is MetaDataMethodAbstract ) goto case Instruction.OpcodeOperand.Method; if(obj is MetaDataField ) goto case Instruction.OpcodeOperand.Field; throw new NotNormalized( "Unvalid token: " + obj ); } case Instruction.OpcodeOperand.None: { writer.WriteLine( "IL_{0:X4}: {1,-10}", i, instr.Operator.Name ); } break; default: { if(oi.OperandSize == 0) goto case Instruction.OpcodeOperand.None; if(instr.Argument is MetaDataObject) { throw new NotNormalized( "Unvalid argument: " + instr.Argument ); } writer.WriteLine( "IL_{0:X4}: {1,-10} {2}", i, instr.Operator.Name, instr.Argument ); } break; } if(handlersEnd[i] != null) { foreach(EHClause eh in handlersEnd[i]) { writer.IndentPop( "}" ); indent--; } } if(tryBlocksEnd[i] != null) { EHClause ehLast = null; foreach(EHClause eh in tryBlocksEnd[i]) { if(ehLast == null || ehLast.TryOffset != eh.TryOffset) { if(ehLast != null) { throw new NotNormalized( "Two separate try blocks end at the same position" ); } writer.IndentPop( "}" ); indent--; } ehLast = eh; } } } } writer.IndentPop( "} // end of method '" + this.FullName + "'" ); writer.WriteLine(); } private void Set( List[] array , int pos , EHClause eh ) { if(array[pos] == null) { array[pos] = new List(); } array[pos].Add( eh ); } internal string DumpSignature( IMetaDataDumper writer , MetaDataGenericMethodParam[] genericParams , bool fWithOwner ) { System.Text.StringBuilder sb = new System.Text.StringBuilder(); sb.Append( SignatureMethod.EnumToString( m_signature.m_callingConvention ) ); sb.Append( m_signature.m_returnType.ToStringWithAbbreviations( writer ) ); sb.Append( " " ); if(fWithOwner) { sb.Append( m_owner.ToString( writer ) ); sb.Append( "::" ); } sb.Append( m_name ); if(genericParams != null) { sb.Append( "<" ); for(int i = 0; i < genericParams.Length; i++) { MetaDataGenericMethodParam param = genericParams[i]; if(i != 0) { sb.Append( ", " ); } if(param.m_genericParamConstraints != null) { sb.Append( "(" ); for(int j = 0; j < param.m_genericParamConstraints.Length; j++) { MetaDataTypeDefinitionAbstract td = param.m_genericParamConstraints[j]; if(j != 0) { sb.Append( ", " ); } sb.Append( td.ToStringWithAbbreviations( writer ) ); } sb.Append( ")" ); } sb.Append( param.m_name ); } sb.Append( ">" ); } sb.Append( "(" ); for(int i = 0; i < m_signature.m_parameters.Length; i++) { SignatureType td = m_signature.m_parameters[i]; if(i != 0) { sb.Append( ", " ); } sb.Append( td.ToStringWithAbbreviations( writer ) ); if(m_paramList != null && i < m_paramList.Length) { sb.Append( " " ); sb.Append( m_paramList[i].Name ); } } sb.Append( ")" ); return sb.ToString(); } internal string InnerToString( IMetaDataDumper writer , MetaDataGenericMethodParam[] genericParams ) { System.Text.StringBuilder sb = new System.Text.StringBuilder(); writer = writer.PushContext( this ); writer = writer.PushContext( m_owner ); sb.Append( SignatureMethod.EnumToString( m_signature.m_callingConvention ) ); sb.Append( m_signature.m_returnType.ToStringWithAbbreviations( writer ) ); sb.Append( " " ); sb.Append( m_owner.ToString( writer ) ); sb.Append( "::" ); sb.Append( m_name ); if(genericParams != null) { sb.Append( "<" ); for(int i = 0; i < genericParams.Length; i++) { MetaDataGenericMethodParam param = genericParams[i]; if(i != 0) { sb.Append( ", " ); } if(param.m_genericParamConstraints != null) { sb.Append( "(" ); for(int j = 0; j < param.m_genericParamConstraints.Length; j++) { MetaDataTypeDefinitionAbstract td = param.m_genericParamConstraints[j]; if(j != 0) { sb.Append( ", " ); } sb.Append( td.ToStringWithAbbreviations( writer ) ); } sb.Append( ")" ); } sb.Append( param.m_name ); } sb.Append( ">" ); } sb.Append( "(" ); for(int i = 0; i < m_signature.m_parameters.Length; i++) { SignatureType td = m_signature.m_parameters[i]; if(i != 0) { sb.Append( ", " ); } sb.Append( td.ToStringWithAbbreviations( writer ) ); if(m_paramList != null && i < m_paramList.Length) { sb.Append( " " ); sb.Append( m_paramList[i].Name ); } } sb.Append( ") " ); sb.Append( TokenToString( m_token ) ); return sb.ToString(); } private static string EnumToString( MethodAttributes val ) { System.Text.StringBuilder sb = new System.Text.StringBuilder(); if((val & MethodAttributes.MemberAccessMask) == MethodAttributes.Public ) sb.Append( "public " ); if((val & MethodAttributes.MemberAccessMask) == MethodAttributes.Private ) sb.Append( "private " ); if((val & MethodAttributes.MemberAccessMask) == MethodAttributes.Family ) sb.Append( "family " ); if((val & MethodAttributes.MemberAccessMask) == MethodAttributes.Assem ) sb.Append( "assembly " ); if((val & MethodAttributes.MemberAccessMask) == MethodAttributes.FamANDAssem ) sb.Append( "famandassem " ); if((val & MethodAttributes.MemberAccessMask) == MethodAttributes.FamORAssem ) sb.Append( "famorassem " ); if((val & MethodAttributes.MemberAccessMask) == MethodAttributes.PrivateScope) sb.Append( "privatescope " ); if((val & MethodAttributes.HideBySig ) != 0 ) sb.Append( "hidebysig " ); if((val & MethodAttributes.VtableLayoutMask) == MethodAttributes.NewSlot ) sb.Append( "newslot " ); if((val & MethodAttributes.SpecialName ) != 0 ) sb.Append( "specialname " ); if((val & MethodAttributes.RTSpecialName ) != 0 ) sb.Append( "rtspecialname " ); if((val & MethodAttributes.Static ) != 0 ) sb.Append( "static " ); if((val & MethodAttributes.Abstract ) != 0 ) sb.Append( "abstract " ); if((val & MethodAttributes.Strict ) != 0 ) sb.Append( "strict " ); if((val & MethodAttributes.Virtual ) != 0 ) sb.Append( "virtual " ); if((val & MethodAttributes.Final ) != 0 ) sb.Append( "final " ); if((val & MethodAttributes.UnmanagedExport ) != 0 ) sb.Append( "unmanagedexp " ); if((val & MethodAttributes.RequireSecObject) != 0 ) sb.Append( "reqsecobj " ); return sb.ToString(); } private static string EnumToString( MethodImplAttributes val ) { System.Text.StringBuilder sb = new System.Text.StringBuilder(); if((val & MethodImplAttributes.CodeTypeMask) == MethodImplAttributes.Native ) sb.Append( " native" ); if((val & MethodImplAttributes.CodeTypeMask) == MethodImplAttributes.IL ) sb.Append( " cil" ); if((val & MethodImplAttributes.CodeTypeMask) == MethodImplAttributes.OPTIL ) sb.Append( " optil" ); if((val & MethodImplAttributes.CodeTypeMask) == MethodImplAttributes.Runtime ) sb.Append( " runtime" ); if((val & MethodImplAttributes.ManagedMask ) == MethodImplAttributes.Unmanaged) sb.Append( " unmanaged" ); if((val & MethodImplAttributes.ManagedMask ) == MethodImplAttributes.Managed ) sb.Append( " managed" ); if((val & MethodImplAttributes.PreserveSig ) != 0 ) sb.Append( " preservesig" ); if((val & MethodImplAttributes.ForwardRef ) != 0 ) sb.Append( " forwardref" ); if((val & MethodImplAttributes.InternalCall) != 0 ) sb.Append( " internalcall" ); if((val & MethodImplAttributes.Synchronized) != 0 ) sb.Append( " synchronized" ); if((val & MethodImplAttributes.NoInlining ) != 0 ) sb.Append( " noinlining" ); return sb.ToString(); } } } ================================================ FILE: Zelig/Zelig/CompileTime/MetaData/Normalized/MetaDataMethodGeneric.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // namespace Microsoft.Zelig.MetaData.Normalized { using System; // // Don't remove "sealed" attribute unless you read comments on Equals method. // public sealed class MetaDataMethodGeneric : MetaDataMethodBase, IMetaDataUnique { // // State // internal MetaDataGenericMethodParam[] m_genericParams; // // Constructor Methods // internal MetaDataMethodGeneric( MetaDataTypeDefinitionAbstract owner , int token ) : base( owner, token ) { } //--// // // MetaDataEquality Methods // public override bool Equals( object obj ) { if(obj is MetaDataMethodGeneric) // Since the class is sealed (no subclasses allowed), there's no need to compare using .GetType() { MetaDataMethodGeneric other = (MetaDataMethodGeneric)obj; if(ArrayUtility.ArrayEquals( m_genericParams, other.m_genericParams )) { return InnerEquals( other ); } } return false; } public override int GetHashCode() { return InnerGetHashCode(); } // // Helper Methods // public override bool IsOpenMethod { get { return true; } } public override bool UsesTypeParameters { get { return base.UsesTypeParameters; } } public override bool UsesMethodParameters { get { return true; } } //--// // // Access Methods // public MetaDataGenericMethodParam[] GenericParams { get { return m_genericParams; } } // // Debug Methods // public override string ToString() { return "MetaDataMethodGeneric(" + this.FullName + ")"; } public override String ToString( IMetaDataDumper context ) { return InnerToString( context, m_genericParams ); } public override void Dump( IMetaDataDumper writer ) { InnerDump( writer, m_genericParams ); } } } ================================================ FILE: Zelig/Zelig/CompileTime/MetaData/Normalized/MetaDataMethodGenericInstantiation.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // namespace Microsoft.Zelig.MetaData.Normalized { using System; // // Don't remove "sealed" attribute unless you read comments on Equals method. // public sealed class MetaDataMethodGenericInstantiation : MetaDataMethodAbstract, IMetaDataUnique { // // State // internal readonly MetaDataAssembly m_owner; internal MetaDataMethodAbstract m_baseMethod; internal SignatureType[] m_parameters; // // Constructor Methods // internal MetaDataMethodGenericInstantiation( MetaDataAssembly owner , int token ) : base( token ) { m_owner = owner; } //--// // // MetaDataEquality Methods // public override bool Equals( object obj ) { if(obj is MetaDataMethodGenericInstantiation) // Since the class is sealed (no subclasses allowed), there's no need to compare using .GetType() { MetaDataMethodGenericInstantiation other = (MetaDataMethodGenericInstantiation)obj; if(m_baseMethod == other.m_baseMethod) { if(ArrayUtility.ArrayEquals( m_parameters, other.m_parameters)) { return true; } } } return false; } public override int GetHashCode() { return m_baseMethod.GetHashCode(); } // // Helper Methods // public override bool IsOpenMethod { get { for(int i = 0; i < m_parameters.Length; i++) { if(m_parameters[i].IsOpenType) { return true; } } return false; } } internal override MetaDataObject MakeUnique() { return (MetaDataObject)m_owner.MakeUnique( this ); } // // Access Methods // public MetaDataAssembly Owner { get { return m_owner; } } public MetaDataMethodAbstract BaseMethod { get { return m_baseMethod; } } public SignatureType[] InstantiationParams { get { return m_parameters; } } // // Debug Methods // public override string FullName { get { return m_baseMethod.FullName; } } public override string ToString() { return "MetaDataMethodGenericInstantiation(" + this.FullName + ")"; } public override String ToString( IMetaDataDumper context ) { string res; context = context.PushContext( this ); res = m_baseMethod.ToString( context ); return res; } public override void Dump( IMetaDataDumper writer ) { throw new NotNormalized( "Dump" ); } } } ================================================ FILE: Zelig/Zelig/CompileTime/MetaData/Normalized/MetaDataMethodImpl.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // namespace Microsoft.Zelig.MetaData.Normalized { using System; // // Don't remove "sealed" attribute unless you read comments on Equals method. // public sealed class MetaDataMethodImpl : MetaDataObject, IMetaDataUnique { // // State // internal MetaDataTypeDefinitionBase m_classObject; internal MetaDataMethodBase m_body; internal MetaDataMethodAbstract m_declaration; // // Constructor Methods // internal MetaDataMethodImpl( int token ) : base( token ) { } // // MetaDataEquality Methods // public override bool Equals( object obj ) { if(obj is MetaDataMethodImpl) // Since the class is sealed (no subclasses allowed), there's no need to compare using .GetType() { MetaDataMethodImpl other = (MetaDataMethodImpl)obj; if(m_classObject == other.m_classObject && m_body == other.m_body && m_declaration == other.m_declaration ) { return true; } } return false; } public override int GetHashCode() { return m_classObject.GetHashCode() ^ m_body .GetHashCode() ^ m_declaration.GetHashCode(); } // // Helper Methods // internal override MetaDataObject MakeUnique() { throw new NotNormalized( "MakeUnique" ); } // // Access Methods // public MetaDataTypeDefinitionBase Class { get { return m_classObject; } } public MetaDataMethodBase Body { get { return m_body; } } public MetaDataMethodAbstract Declaration { get { return m_declaration; } } // Debug Methods public override String ToString() { return "MetaDataMethodImpl(" + m_classObject + "," + m_body + "," + m_declaration + ")"; } public override void Dump( IMetaDataDumper writer ) { throw new NotNormalized( "Dump" ); } } } ================================================ FILE: Zelig/Zelig/CompileTime/MetaData/Normalized/MetaDataMethodSemantics.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // namespace Microsoft.Zelig.MetaData.Normalized { using System; // // Don't remove "sealed" attribute unless you read comments on Equals method. // public sealed class MetaDataMethodSemantics : MetaDataObject, IMetaDataUnique { // // State // internal MethodSemanticAttributes m_semantic; internal MetaDataMethod m_method; internal IMetaDataHasSemantic m_association; // // Constructor Methods // internal MetaDataMethodSemantics( int token ) : base( token ) { } // // MetaDataEquality Methods // public override bool Equals( object obj ) { if(obj is MetaDataMethodSemantics) // Since the class is sealed (no subclasses allowed), there's no need to compare using .GetType() { MetaDataMethodSemantics other = (MetaDataMethodSemantics)obj; throw new NotNormalized( "MetaDataEquality" ); } return false; } public override int GetHashCode() { throw new NotNormalized( "MetaDataEquality" ); } // // Helper Methods // internal override MetaDataObject MakeUnique() { throw new NotNormalized( "MakeUnique" ); } // // Access Methods // public MethodSemanticAttributes Semantic { get { return m_semantic; } } public MetaDataMethod Method { get { return m_method; } } public IMetaDataHasSemantic Association { get { return m_association; } } // // Debug Methods // public override String ToString() { return "MetaDataMethodSemantics(" + m_semantic + "," + m_method + "," + m_association + ")"; } public override void Dump( IMetaDataDumper writer ) { throw new NotNormalized( "Dump" ); } } } ================================================ FILE: Zelig/Zelig/CompileTime/MetaData/Normalized/MetaDataMethodWithContext.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // namespace Microsoft.Zelig.MetaData.Normalized { using System; // // Don't remove "sealed" attribute unless you read comments on Equals method. // public sealed class MetaDataMethodWithContext : MetaDataMethodAbstract, IMetaDataUnique { // // State // internal readonly MetaDataTypeDefinitionAbstract m_contextType; internal readonly MetaDataMethodAbstract m_contextMethod; internal readonly MetaDataMethodBase m_baseMethod; // // Constructor Methods // internal MetaDataMethodWithContext( MetaDataTypeDefinitionAbstract contextType , MetaDataMethodAbstract contextMethod , MetaDataMethodBase baseMethod ) : base( 0 ) { m_contextType = contextType; m_contextMethod = contextMethod; m_baseMethod = baseMethod; } //--// // // MetaDataEquality Methods // public override bool Equals( object obj ) { if(obj is MetaDataMethodWithContext) // Since the class is sealed (no subclasses allowed), there's no need to compare using .GetType() { MetaDataMethodWithContext other = (MetaDataMethodWithContext)obj; if(m_contextType == other.m_contextType && m_contextMethod == other.m_contextMethod && m_baseMethod == other.m_baseMethod ) { return true; } } return false; } public override int GetHashCode() { return m_baseMethod.GetHashCode(); } // // Helper Methods // public override bool IsOpenMethod { get { if(m_baseMethod.IsOpenMethod) { if(m_contextMethod != null) { if(m_contextMethod.IsOpenMethod == false) { return false; } } return true; } return false; } } public override bool UsesTypeParameters { get { return m_baseMethod.UsesTypeParameters; } } public override bool UsesMethodParameters { get { return m_baseMethod.UsesMethodParameters; } } internal override MetaDataObject MakeUnique() { return m_contextType.MakeUnique( (IMetaDataUnique)this ); } // // Access Methods // public MetaDataTypeDefinitionAbstract ContextType { get { return m_contextType; } } public MetaDataMethodAbstract ContextMethod { get { return m_contextMethod; } } public MetaDataMethodBase BaseMethod { get { return m_baseMethod; } } // // Debug Methods // public override string FullName { get { System.Text.StringBuilder sb = new System.Text.StringBuilder(); sb.Append( "{" ); sb.Append( m_contextType.FullName ); if(m_contextMethod != null) { sb.Append( "," ); sb.Append( m_contextMethod.FullName ); } sb.Append( "}" ); sb.Append( m_baseMethod.FullName ); return sb.ToString(); } } public override string ToString() { return "MetaDataMethodWithContext(" + this.FullName + ")"; } public override String ToString( IMetaDataDumper context ) { string res; context = context.PushContext( m_contextType ); context = context.PushContext( m_contextMethod ); res = m_baseMethod.ToString( context ); return res; } public override void Dump( IMetaDataDumper writer ) { throw new NotNormalized( "Dump" ); } } } ================================================ FILE: Zelig/Zelig/CompileTime/MetaData/Normalized/MetaDataModule.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // namespace Microsoft.Zelig.MetaData.Normalized { using System; // // Don't remove "sealed" attribute unless you read comments on Equals method. // public sealed class MetaDataModule : MetaDataObject, IMetaDataResolutionScope, IMetaDataUnique { // // State // internal short m_generation; internal String m_name; internal Guid m_mvid; // // Constructor Methods // internal MetaDataModule( int token ) : base( token ) { } // // MetaDataEquality Methods // public override bool Equals( object obj ) { if(obj is MetaDataModule) // Since the class is sealed (no subclasses allowed), there's no need to compare using .GetType() { MetaDataModule other = (MetaDataModule)obj; throw new NotNormalized( "MetaDataEquality" ); } return false; } public override int GetHashCode() { throw new NotNormalized( "MetaDataEquality" ); } // // Helper Methods // internal override MetaDataObject MakeUnique() { throw new NotNormalized( "MakeUnique" ); } // // Access Methods // public short Generation { get { return m_generation; } } public String Name { get { return m_name; } } public Guid MVID { get { return m_mvid; } } // Debug Methods public override String ToString() { return "MetaDataModule(" + m_name + "," + m_mvid + ")"; } public override void Dump( IMetaDataDumper writer ) { throw new NotNormalized( "Dump" ); } } } ================================================ FILE: Zelig/Zelig/CompileTime/MetaData/Normalized/MetaDataObject.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // #if DEBUG #define TRACK_METADATAOBJECT_IDENTITY #else //#define TRACK_METADATAOBJECT_IDENTITY #endif namespace Microsoft.Zelig.MetaData.Normalized { using System; public class NotNormalized : Exception { // // Constructor Methods // public NotNormalized( string reason ) : base( reason ) { } } //--// // // This class's primary reason for existence is its place in the class hierarchy. // // Convenient place to store CustomAttribute information // public abstract class MetaDataObject : IMetaDataHasCustomAttribute { // // State // #if TRACK_METADATAOBJECT_IDENTITY protected static int s_identity; #endif public int m_identity; //--// internal readonly int m_token; internal MetaDataCustomAttribute[] m_customAttributes; // // Constructor Methods // protected MetaDataObject( int token ) { #if TRACK_METADATAOBJECT_IDENTITY m_identity = s_identity++; #endif m_token = token; } // // Helper methods // internal abstract MetaDataObject MakeUnique(); // // Access Methods // public int Token { get { return m_token; } } public MetaDataCustomAttribute[] CustomAttributes { get { return m_customAttributes; } } public virtual bool UsesTypeParameters { get { return false; } } public virtual bool UsesMethodParameters { get { return false; } } // // Debug Methods // public abstract void Dump( IMetaDataDumper writer ); protected static string TokenToString( int token ) { return String.Format( "/*{0:X8}*/", token ); } } } ================================================ FILE: Zelig/Zelig/CompileTime/MetaData/Normalized/MetaDataParam.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // namespace Microsoft.Zelig.MetaData.Normalized { using System; // // Don't remove "sealed" attribute unless you read comments on Equals method. // public sealed class MetaDataParam : MetaDataObject, IMetaDataHasConstant, IMetaDataHasFieldMarshal, IMetaDataUnique { // // State // internal ParamAttributes m_flags; internal short m_sequence; internal String m_name; internal MetaDataConstant m_constant; // // Constructor Methods // internal MetaDataParam( int token ) : base( token ) { } // // MetaDataEquality Methods // public override bool Equals( object obj ) { if(obj is MetaDataParam) // Since the class is sealed (no subclasses allowed), there's no need to compare using .GetType() { MetaDataParam other = (MetaDataParam)obj; if(m_flags == other.m_flags && m_sequence == other.m_sequence && m_name == other.m_name && m_constant == other.m_constant ) { return true; } } return false; } public override int GetHashCode() { return (int)m_flags ^ (int)m_sequence ^ m_name .GetHashCode() ; } // // Helper Methods // internal override MetaDataObject MakeUnique() { throw new NotNormalized( "MakeUnique" ); } // // Access Methods // public ParamAttributes Flags { get { return m_flags; } } public short Sequence { get { return m_sequence; } } public String Name { get { return m_name; } } public string FullName { get { return this.Name; } } public Object DefaultValue { get { if((m_flags & ParamAttributes.HasDefault) != 0) { return m_constant.Value; } else { return null; } } } // Debug Methods public override String ToString() { return "MetaDataParam(" + m_name + ")"; } public override void Dump( IMetaDataDumper writer ) { throw new NotNormalized( "Dump" ); } } } ================================================ FILE: Zelig/Zelig/CompileTime/MetaData/Normalized/MetaDataProperty.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // namespace Microsoft.Zelig.MetaData.Normalized { using System; // // Don't remove "sealed" attribute unless you read comments on Equals method. // public sealed class MetaDataProperty : MetaDataObject, IMetaDataHasConstant, IMetaDataHasSemantic, IMetaDataUnique { // // State // internal readonly MetaDataTypeDefinitionAbstract m_owner; internal PropertyAttributes m_flags; internal String m_name; internal SignatureMethod m_type; internal MetaDataConstant m_constant; // // Constructor Methods // internal MetaDataProperty( MetaDataTypeDefinitionAbstract owner , int token ) : base( token ) { m_owner = owner; } //--// // // MetaDataEquality Methods // public override bool Equals( object obj ) { if(obj is MetaDataProperty) // Since the class is sealed (no subclasses allowed), there's no need to compare using .GetType() { MetaDataProperty other = (MetaDataProperty)obj; if(m_owner == other.m_owner && m_flags == other.m_flags && m_name == other.m_name && m_type == other.m_type ) { return true; } } return false; } public override int GetHashCode() { return (int)m_flags ^ m_name .GetHashCode() ; } // // Helper Methods // internal override MetaDataObject MakeUnique() { return m_owner.MakeUnique( this ); } // // Access Methods // public PropertyAttributes Flags { get { return m_flags; } } public String Name { get { return m_name; } } public SignatureMethod Type { get { return m_type; } } public Object DefaultValue { get { if((m_flags & PropertyAttributes.HasDefault) != 0) { return m_constant.Value; } else { return null; } } } // // Debug Methods // public override String ToString() { return "MetaDataProperty(" + m_flags.ToString( "x" ) + "," + m_name + "," + m_type + ")"; } public override void Dump( IMetaDataDumper writer ) { throw new NotNormalized( "Dump" ); } } } ================================================ FILE: Zelig/Zelig/CompileTime/MetaData/Normalized/MetaDataSignature.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // namespace Microsoft.Zelig.MetaData.Normalized { using System; public abstract class MetaDataSignature : MetaDataObject { // // State // internal MetaDataTypeDefinitionAbstract[] m_modifiers; // // Constructor Methods // protected MetaDataSignature( int token ) : base( token ) { } // // Helper Methods // protected bool InnerEquals( MetaDataSignature other ) { if(ArrayUtility.ArrayEquals( m_modifiers, other.m_modifiers )) { return true; } return false; } // // Access Methods // public MetaDataTypeDefinitionAbstract[] Modifiers { get { return m_modifiers; } } // // Debug Methods // } } ================================================ FILE: Zelig/Zelig/CompileTime/MetaData/Normalized/MetaDataTypeDefinition.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // namespace Microsoft.Zelig.MetaData.Normalized { using System; // // Don't remove "sealed" attribute unless you read comments on Equals method. // public sealed class MetaDataTypeDefinition : MetaDataTypeDefinitionBase, IMetaDataUnique { // // Constructor Methods // internal MetaDataTypeDefinition( MetaDataAssembly owner , int token ) : base( owner, token ) { } // // MetaDataEquality Methods // public override bool Equals( object obj ) { if(obj is MetaDataTypeDefinition) // Since the class is sealed (no subclasses allowed), there's no need to compare using .GetType() { MetaDataTypeDefinition other = (MetaDataTypeDefinition)obj; return InnerEquals( other ); } return false; } public override int GetHashCode() { return InnerGetHashCode(); } // // Helper Methods // public override bool IsOpenType { get { return false; } } public override bool Match( MetaDataTypeDefinitionAbstract typeContext , MetaDataMethodAbstract methodContext , MetaDataTypeDefinitionAbstract type ) { // LT72: previous code used operator equality, which apparently differs in impplementation from 2.0 to 4.5 //return this == type; return Equals( type ); } // // Debug Methods // public override string ToString() { return QualifiedToString( "MetaDataTypeDefinition" ); } public override String ToString( IMetaDataDumper context ) { System.Text.StringBuilder sb = new System.Text.StringBuilder(); if(this.IsNestedType) { sb.Append( this.EnclosingClass.ToString( context ) ); sb.Append( "." ); } if(this.Namespace != null && this.Namespace.Length != 0) { sb.Append( this.Namespace ); sb.Append( "." ); } sb.Append( this.Name ); sb.Append( TokenToString( m_token ) ); return sb.ToString(); } public override void Dump( IMetaDataDumper writer ) { InnerDump( writer, null ); } } } ================================================ FILE: Zelig/Zelig/CompileTime/MetaData/Normalized/MetaDataTypeDefinitionAbstract.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // namespace Microsoft.Zelig.MetaData.Normalized { using System; public abstract class MetaDataTypeDefinitionAbstract : MetaDataObject, IMetaDataHasDeclSecurity { // // State // internal readonly MetaDataAssembly m_owner; internal ElementTypes m_elementType; internal MetaDataTypeDefinitionAbstract m_extends; // // Constructor Methods // internal MetaDataTypeDefinitionAbstract( MetaDataAssembly owner , int token ) : base( token ) { m_owner = owner; } // // Helper Methods // internal override MetaDataObject MakeUnique() { return MakeUnique( (IMetaDataUnique)this ); } internal MetaDataObject MakeUnique( IMetaDataUnique obj ) { return (MetaDataObject)m_owner.MakeUnique( obj ); } // // Access Methods // public ElementTypes ElementType { get { return m_elementType; } } public MetaDataTypeDefinitionAbstract Extends { get { return m_extends; } } public MetaDataAssembly Owner { get { return m_owner; } } // // Helper Methods // public abstract bool IsOpenType { get; } public abstract bool Match( MetaDataTypeDefinitionAbstract typeContext , MetaDataMethodAbstract methodContext , MetaDataTypeDefinitionAbstract type ); public bool IsScalar { get { switch(m_elementType) { case ElementTypes.VOID : case ElementTypes.BOOLEAN: case ElementTypes.CHAR : case ElementTypes.I1 : case ElementTypes.U1 : case ElementTypes.I2 : case ElementTypes.U2 : case ElementTypes.I4 : case ElementTypes.U4 : case ElementTypes.I8 : case ElementTypes.U8 : case ElementTypes.R4 : case ElementTypes.R8 : case ElementTypes.I : case ElementTypes.U : return true; } return false; } } public bool IsInteger // BEWARE: this only applies to Scalars. { get { switch(m_elementType) { case ElementTypes.BOOLEAN: case ElementTypes.CHAR : case ElementTypes.I1 : case ElementTypes.U1 : case ElementTypes.I2 : case ElementTypes.U2 : case ElementTypes.I4 : case ElementTypes.U4 : case ElementTypes.I8 : case ElementTypes.U8 : case ElementTypes.I : case ElementTypes.U : return true; } return false; } } public uint ScalarSize { get { switch(m_elementType) { case ElementTypes.VOID : return 0; case ElementTypes.BOOLEAN: return 1; case ElementTypes.CHAR : return 2; case ElementTypes.I1 : return 1; case ElementTypes.U1 : return 1; case ElementTypes.I2 : return 2; case ElementTypes.U2 : return 2; case ElementTypes.I4 : return 4; case ElementTypes.U4 : return 4; case ElementTypes.I8 : return 8; case ElementTypes.U8 : return 8; case ElementTypes.R4 : return 4; case ElementTypes.R8 : return 8; case ElementTypes.I : return 4; case ElementTypes.U : return 4; } return uint.MaxValue; } } public bool IsSigned { get { switch(m_elementType) { case ElementTypes.I1: case ElementTypes.I2: case ElementTypes.I4: case ElementTypes.I8: case ElementTypes.R4: case ElementTypes.R8: case ElementTypes.I : return true; } return false; } } // // Debug Methods // public abstract String FullName { get; } public virtual String FullNameWithAbbreviation { get { string result = GetAbbreviation(); if(result == null) { return this.FullName; } else { return result; } } } public abstract String ToString( IMetaDataDumper context ); public string GetAbbreviation() { switch(this.ElementType) { case ElementTypes.VOID : return "void" ; case ElementTypes.BOOLEAN: return "bool" ; case ElementTypes.CHAR : return "char" ; case ElementTypes.I1 : return "sbyte" ; case ElementTypes.U1 : return "byte" ; case ElementTypes.I2 : return "short" ; case ElementTypes.U2 : return "ushort" ; case ElementTypes.I4 : return "int" ; case ElementTypes.U4 : return "uint" ; case ElementTypes.I8 : return "long" ; case ElementTypes.U8 : return "ulong" ; case ElementTypes.R4 : return "float" ; case ElementTypes.R8 : return "double" ; case ElementTypes.STRING : return "string" ; case ElementTypes.OBJECT : return "object" ; default : return null; } } public string ToStringWithAbbreviations( IMetaDataDumper context ) { string result = GetAbbreviation(); if(result == null) { return this.ToString( context ); } else { return result; } } internal static string ParameterToString( IMetaDataDumper context , int number , bool fIsMethodParam , string fallback ) { string res; if(fIsMethodParam) { MetaDataMethodAbstract md = context.GetContextMethodAndPop( out context ); if(md is MetaDataMethodGeneric) { MetaDataMethodGeneric md2 = (MetaDataMethodGeneric)md; res = "!!" + md2.GenericParams[number].m_name; } else if(md is MetaDataMethodGenericInstantiation) { MetaDataMethodGenericInstantiation md2 = (MetaDataMethodGenericInstantiation)md; res = md2.m_parameters[number].ToStringWithAbbreviations( context ); } else { if(fallback == null) { throw new NotNormalized( "ParametersToString" ); } res = fallback; } } else { MetaDataTypeDefinitionAbstract td = context.GetContextTypeAndPop( out context ); if(td is MetaDataTypeDefinitionGeneric) { MetaDataTypeDefinitionGeneric td2 = (MetaDataTypeDefinitionGeneric)td; res = "!" + td2.GenericParams[number].m_name; } else if(td is MetaDataTypeDefinitionGenericInstantiation) { MetaDataTypeDefinitionGenericInstantiation td2 = (MetaDataTypeDefinitionGenericInstantiation)td; res = td2.m_parameters[number].ToStringWithAbbreviations( context ); } else { if(fallback == null) { throw new NotNormalized( "ParametersToString" ); } res = fallback; } } return res; } protected string QualifiedToString( string prefix ) { System.Text.StringBuilder sb = new System.Text.StringBuilder( prefix ); sb.Append( "(" ); sb.Append( "[" ); sb.Append( this.Owner.Name ); sb.Append( "]" ); sb.Append( this.FullName ); sb.Append( ")" ); return sb.ToString(); } } } ================================================ FILE: Zelig/Zelig/CompileTime/MetaData/Normalized/MetaDataTypeDefinitionArray.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // namespace Microsoft.Zelig.MetaData.Normalized { using System; public abstract class MetaDataTypeDefinitionArray : MetaDataTypeDefinitionAbstract { // // State // internal MetaDataTypeDefinitionAbstract m_objectType; internal MetaDataTypeDefinitionAbstract[] m_interfaces; internal MetaDataMethodBase[] m_methods; // // Constructor Methods // internal MetaDataTypeDefinitionArray( MetaDataAssembly owner , int token ) : base( owner, token ) { } // // MetaDataEquality Methods // protected bool InnerEquals( MetaDataTypeDefinitionArray other ) { if(m_objectType == other.m_objectType) { return true; } return false; } protected int InnerGetHashCode() { return m_objectType.GetHashCode(); } // // Helper Methods // public override bool IsOpenType { get { return m_objectType.IsOpenType; } } public override bool UsesTypeParameters { get { return m_objectType.UsesTypeParameters; } } public override bool UsesMethodParameters { get { return m_objectType.UsesMethodParameters; } } // // Access Methods // public MetaDataTypeDefinitionAbstract ObjectType { get { return m_objectType; } } public MetaDataTypeDefinitionAbstract[] Interfaces { get { return m_interfaces; } } public MetaDataMethodBase[] Methods { get { return m_methods; } } } } ================================================ FILE: Zelig/Zelig/CompileTime/MetaData/Normalized/MetaDataTypeDefinitionArrayMulti.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // namespace Microsoft.Zelig.MetaData.Normalized { using System; // // Don't remove "sealed" attribute unless you read comments on Equals method. // public sealed class MetaDataTypeDefinitionArrayMulti : MetaDataTypeDefinitionArray, IMetaDataUnique { public struct Dimension { // // State // public uint m_lowerBound; public uint m_upperBound; } // // State // internal uint m_rank; internal Dimension[] m_dimensions; // // Constructor Methods // internal MetaDataTypeDefinitionArrayMulti( MetaDataAssembly owner , int token ) : base( owner, token ) { m_elementType = ElementTypes.ARRAY; } // // MetaDataEquality Methods // public override bool Equals( object obj ) { if(obj is MetaDataTypeDefinitionArrayMulti) // Since the class is sealed (no subclasses allowed), there's no need to compare using .GetType() { MetaDataTypeDefinitionArrayMulti other = (MetaDataTypeDefinitionArrayMulti)obj; if(m_rank == other.m_rank) { if(ArrayUtility.ArrayEquals( m_dimensions, other.m_dimensions )) { return InnerEquals( other ); } } } return false; } public override int GetHashCode() { return InnerGetHashCode(); } // // Helper Methods // public override bool Match( MetaDataTypeDefinitionAbstract typeContext , MetaDataMethodAbstract methodContext , MetaDataTypeDefinitionAbstract type ) { throw new NotNormalized( "Match" ); } // // Access Methods // public uint Rank { get { return m_rank; } } public Dimension[] Dimensions { get { return m_dimensions; } } // // Debug Methods // public override string FullName { get { return AppendQualifiers( m_objectType.FullName ); } } public override string FullNameWithAbbreviation { get { return AppendQualifiers( m_objectType.FullNameWithAbbreviation ); } } public override string ToString() { return QualifiedToString( "MetaDataTypeDefinitionArrayMulti" ); } public override String ToString( IMetaDataDumper context ) { System.Text.StringBuilder sb = new System.Text.StringBuilder(); sb.Append( m_objectType.ToStringWithAbbreviations( context ) ); sb.Append( "[" ); for(int i = 0; i < m_rank; i++) { if(i != 0) { sb.Append( "," ); } if(i < m_dimensions.Length) { Dimension dm = m_dimensions[i]; if(dm.m_lowerBound != 0 || dm.m_upperBound != 0) { sb.Append( dm.m_lowerBound ); sb.Append( ".." ); sb.Append( dm.m_upperBound ); } } } sb.Append( "]" ); return sb.ToString(); } public override void Dump( IMetaDataDumper writer ) { throw new NotNormalized( "Dump" ); } //--// private string AppendQualifiers( string prefix ) { System.Text.StringBuilder sb = new System.Text.StringBuilder( prefix ); sb.Append( "[" ); for(int i = 0; i < m_rank; i++) { if(i != 0) { sb.Append( "," ); } if(i < m_dimensions.Length) { Dimension dm = m_dimensions[i]; if(dm.m_lowerBound != 0 || dm.m_upperBound != 0) { sb.Append( dm.m_lowerBound ); sb.Append( ".." ); sb.Append( dm.m_upperBound ); } } } sb.Append( "]" ); return sb.ToString(); } } } ================================================ FILE: Zelig/Zelig/CompileTime/MetaData/Normalized/MetaDataTypeDefinitionArraySz.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // namespace Microsoft.Zelig.MetaData.Normalized { using System; // // Don't remove "sealed" attribute unless you read comments on Equals method. // public sealed class MetaDataTypeDefinitionArraySz : MetaDataTypeDefinitionArray, IMetaDataUnique { // // Constructor Methods // internal MetaDataTypeDefinitionArraySz( MetaDataAssembly owner , int token ) : base( owner, token ) { m_elementType = ElementTypes.SZARRAY; } // // MetaDataEquality Methods // public override bool Equals( object obj ) { if(obj is MetaDataTypeDefinitionArraySz) // Since the class is sealed (no subclasses allowed), there's no need to compare using .GetType() { MetaDataTypeDefinitionArraySz other = (MetaDataTypeDefinitionArraySz)obj; return InnerEquals( other ); } return false; } public override int GetHashCode() { return InnerGetHashCode(); } // // Helper Methods // public override bool Match( MetaDataTypeDefinitionAbstract typeContext , MetaDataMethodAbstract methodContext , MetaDataTypeDefinitionAbstract type ) { if(type is MetaDataTypeDefinitionArraySz) { MetaDataTypeDefinitionArraySz array = (MetaDataTypeDefinitionArraySz)type; return m_objectType.Match( typeContext, methodContext, array.m_objectType ); } return false; } // // Debug Methods // public override string FullName { get { return AppendQualifiers( m_objectType.FullName ); } } public override string FullNameWithAbbreviation { get { return AppendQualifiers( m_objectType.FullNameWithAbbreviation ); } } public override string ToString() { return QualifiedToString( "MetaDataTypeDefinitionArraySz" ); } public override String ToString( IMetaDataDumper context ) { System.Text.StringBuilder sb = new System.Text.StringBuilder(); sb.Append( m_objectType.ToStringWithAbbreviations( context ) ); sb.Append( "[]" ); return sb.ToString(); } public override void Dump( IMetaDataDumper writer ) { throw new NotNormalized( "Dump" ); } //--// private string AppendQualifiers( string prefix ) { System.Text.StringBuilder sb = new System.Text.StringBuilder( prefix ); sb.Append( "[]" ); return sb.ToString(); } } } ================================================ FILE: Zelig/Zelig/CompileTime/MetaData/Normalized/MetaDataTypeDefinitionBase.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // namespace Microsoft.Zelig.MetaData.Normalized { using System; public abstract class MetaDataTypeDefinitionBase : MetaDataTypeDefinitionAbstract { // // State // internal TypeAttributes m_flags; internal string m_name; internal string m_nameSpace; internal MetaDataTypeDefinitionAbstract m_enclosingClass; internal MetaDataTypeDefinitionAbstract[] m_nestedClasses; internal MetaDataTypeDefinitionAbstract[] m_interfaces; internal MetaDataField[] m_fields; internal MetaDataMethodBase[] m_methods; internal MetaDataMethodImpl[] m_methodImpls; internal MetaDataEvent[] m_events; internal MetaDataProperty[] m_properties; internal MetaDataClassLayout m_classLayout; // // Constructor Methods // protected MetaDataTypeDefinitionBase( MetaDataAssembly owner , int token ) : base( owner, token ) { } // // MetaDataEquality Methods // protected bool InnerEquals( MetaDataTypeDefinitionBase other ) { // LT72: previous code used operator equality, which apparently differs in impplementation from 2.0 to 4.5 //if(m_name == other.m_name && // m_nameSpace == other.m_nameSpace && // m_owner == other.m_owner && // m_enclosingClass == other.m_enclosingClass && // m_extends == other.m_extends ) //{ // return true; //} if ( m_name .Equals( other.m_name ) && m_nameSpace .Equals( other.m_nameSpace ) && m_owner .Equals( other.m_owner ) && ((m_enclosingClass == null && other.m_enclosingClass == null) || m_enclosingClass.Equals( other.m_enclosingClass )) && ((m_extends == null && other.m_extends == null) || m_extends .Equals( other.m_extends )) ) { return true; } return false; } protected int InnerGetHashCode() { int res = m_name.GetHashCode(); if(m_nameSpace != null) { res ^= m_nameSpace.GetHashCode(); } res ^= m_owner.GetHashCode(); return res; } // // Access Methods // public TypeAttributes Flags { get { return m_flags; } } public string Name { get { return m_name; } } public string Namespace { get { return m_nameSpace; } } public MetaDataTypeDefinitionAbstract[] Interfaces { get { return m_interfaces; } } public MetaDataField[] Fields { get { return m_fields; } } public MetaDataMethodBase[] Methods { get { return m_methods; } } public MetaDataMethodImpl[] MethodImpls { get { return m_methodImpls; } } public MetaDataTypeDefinitionAbstract EnclosingClass { get { return m_enclosingClass; } } public MetaDataTypeDefinitionAbstract[] NestedClasses { get { return m_nestedClasses; } } public MetaDataClassLayout ClassLayout { get { return m_classLayout; } } public bool IsNestedType { get { return m_enclosingClass != null; } } public override string FullName { get { System.Text.StringBuilder sb = new System.Text.StringBuilder(); if(this.IsNestedType) { sb.Append( this.EnclosingClass.FullName ); sb.Append( "." ); } if(this.Namespace != null && this.Namespace.Length != 0) { sb.Append( this.Namespace ); sb.Append( "." ); } sb.Append( this.Name ); return sb.ToString(); } } public bool IsNameMatch( string nameSpace , string name , string[] nested ) { MetaDataTypeDefinitionBase td = this; if(nested != null) { int nestedSize = nested.Length; while(nestedSize > 0) { if(td.IsNestedType == false) { return false; } if(td.m_name != nested[--nestedSize]) { return false; } td = (MetaDataTypeDefinitionBase)td.m_enclosingClass; } } if(td.IsNestedType == true) { return false; } if(td.m_nameSpace == nameSpace && td.m_name == name) { return true; } return false; } // // Debug Methods // public void InnerDump( IMetaDataDumper writer , MetaDataGenericTypeParam[] genericParams ) { if(m_enclosingClass != null && writer.AlreadyProcessed( m_enclosingClass ) == false) { return; } writer = writer.PushContext( this ); writer.WriteLine( ".class {0} {1}{2}", TokenToString( m_token ), EnumToString( m_flags ), DumpSignature( writer, genericParams ) ); if(m_extends != null) { writer.WriteLine( " extends {0}", m_extends.ToString( writer ) ); } if(m_interfaces != null) { System.Text.StringBuilder sb = new System.Text.StringBuilder(); for(int i = 0; i < m_interfaces.Length; i++) { MetaDataTypeDefinitionAbstract itf = m_interfaces[i]; sb.Length = 0; if(i == 0) { sb.Append( " implements " ); } else { sb.Append( " " ); } sb.Append( itf.ToString( writer ) ); if(i != m_interfaces.Length - 1) { sb.Append( "," ); } writer.WriteLine( sb.ToString() ); } } writer.IndentPush( "{" ); if(m_customAttributes != null) { foreach(MetaDataCustomAttribute ca in m_customAttributes) { writer.Process( ca, false ); } writer.WriteLine(); } if(m_nestedClasses != null) { foreach(MetaDataTypeDefinitionAbstract nested in m_nestedClasses) { writer.Process( nested, true ); } } if(m_fields != null) { foreach(MetaDataField field in m_fields) { writer.Process( field, true ); } writer.WriteLine(); } if(m_methods != null) { foreach(MetaDataMethodBase md in m_methods) { writer.Process( md, true ); } writer.WriteLine(); } writer.IndentPop( "} // end of class '" + this.FullName + "'" ); writer.WriteLine(); } internal string DumpSignature( IMetaDataDumper writer , MetaDataGenericTypeParam[] genericParams ) { System.Text.StringBuilder sb = new System.Text.StringBuilder(); sb.Append( this.FullName ); if(genericParams != null) { sb.Append( "<" ); bool fGot1 = false; foreach(MetaDataGenericTypeParam param in genericParams) { if(fGot1) { sb.Append( ", " ); } else { fGot1 = true; } if(param.m_genericParamConstraints != null) { sb.Append( "(" ); bool fGot2 = false; foreach(MetaDataTypeDefinitionAbstract td in param.m_genericParamConstraints) { if(fGot2) { sb.Append( ", " ); } else { fGot2 = true; } sb.Append( td.ToStringWithAbbreviations( writer ) ); } sb.Append( ")" ); } sb.Append( param.m_name ); } sb.Append( ">" ); } return sb.ToString(); } private static string EnumToString( TypeAttributes val ) { System.Text.StringBuilder sb = new System.Text.StringBuilder(); if((val & TypeAttributes.ClassSemanticsMask) == TypeAttributes.Interface ) sb.Append( "interface " ); if((val & TypeAttributes.VisibilityMask ) == TypeAttributes.Public ) sb.Append( "public " ); if((val & TypeAttributes.VisibilityMask ) == TypeAttributes.NotPublic ) sb.Append( "private " ); if((val & TypeAttributes.Abstract ) != 0 ) sb.Append( "abstract " ); if((val & TypeAttributes.LayoutMask ) == TypeAttributes.AutoLayout ) sb.Append( "auto " ); if((val & TypeAttributes.LayoutMask ) == TypeAttributes.SequentialLayout ) sb.Append( "sequential " ); if((val & TypeAttributes.LayoutMask ) == TypeAttributes.ExplicitLayout ) sb.Append( "explicit " ); if((val & TypeAttributes.StringFormatMask ) == TypeAttributes.AnsiClass ) sb.Append( "ansi " ); if((val & TypeAttributes.StringFormatMask ) == TypeAttributes.UnicodeClass ) sb.Append( "unicode " ); if((val & TypeAttributes.StringFormatMask ) == TypeAttributes.AutoClass ) sb.Append( "autochar " ); if((val & TypeAttributes.Import ) != 0 ) sb.Append( "import " ); if((val & TypeAttributes.Serializable ) != 0 ) sb.Append( "serializable " ); if((val & TypeAttributes.Sealed ) != 0 ) sb.Append( "sealed " ); if((val & TypeAttributes.VisibilityMask ) == TypeAttributes.NestedPublic ) sb.Append( "nested public " ); if((val & TypeAttributes.VisibilityMask ) == TypeAttributes.NestedPrivate ) sb.Append( "nested private " ); if((val & TypeAttributes.VisibilityMask ) == TypeAttributes.NestedFamily ) sb.Append( "nested family " ); if((val & TypeAttributes.VisibilityMask ) == TypeAttributes.NestedAssembly ) sb.Append( "nested assembly " ); if((val & TypeAttributes.VisibilityMask ) == TypeAttributes.NestedFamANDAssem) sb.Append( "nested famandassem " ); if((val & TypeAttributes.VisibilityMask ) == TypeAttributes.NestedFamORAssem ) sb.Append( "nested famorassem " ); if((val & TypeAttributes.BeforeFieldInit ) != 0 ) sb.Append( "beforefieldinit " ); if((val & TypeAttributes.SpecialName ) != 0 ) sb.Append( "specialname " ); if((val & TypeAttributes.RTSpecialName ) != 0 ) sb.Append( "rtspecialname " ); return sb.ToString(); } } } ================================================ FILE: Zelig/Zelig/CompileTime/MetaData/Normalized/MetaDataTypeDefinitionByRef.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // namespace Microsoft.Zelig.MetaData.Normalized { using System; // // Don't remove "sealed" attribute unless you read comments on Equals method. // public sealed class MetaDataTypeDefinitionByRef : MetaDataTypeDefinitionAbstract, IMetaDataUnique { // // State // internal MetaDataTypeDefinitionAbstract m_type; // // Constructor Methods // internal MetaDataTypeDefinitionByRef( MetaDataAssembly owner , int token , ElementTypes elementType ) : base( owner, token ) { m_elementType = elementType; } //--// // // MetaDataEquality Methods // public override bool Equals( object obj ) { if(obj is MetaDataTypeDefinitionByRef) // Since the class is sealed (no subclasses allowed), there's no need to compare using .GetType() { MetaDataTypeDefinitionByRef other = (MetaDataTypeDefinitionByRef)obj; if(m_elementType == other.m_elementType && m_type == other.m_type ) { return true; } } return false; } public override int GetHashCode() { return m_type.GetHashCode(); } // // Helper Methods // public override bool IsOpenType { get { return m_type.IsOpenType; } } public override bool UsesTypeParameters { get { return m_type.UsesTypeParameters; } } public override bool UsesMethodParameters { get { return m_type.UsesMethodParameters; } } public override bool Match( MetaDataTypeDefinitionAbstract typeContext , MetaDataMethodAbstract methodContext , MetaDataTypeDefinitionAbstract type ) { if(type is MetaDataTypeDefinitionByRef) { MetaDataTypeDefinitionByRef byref = (MetaDataTypeDefinitionByRef)type; return m_type.Match( typeContext, methodContext, byref.m_type ); } return false; } // // Access Methods // public MetaDataTypeDefinitionAbstract BaseType { get { return m_type; } } // // Debug Methods // public override string FullName { get { return InnerToString( m_type.FullName ); } } public override string FullNameWithAbbreviation { get { return InnerToString( m_type.FullNameWithAbbreviation ); } } public override string ToString() { return QualifiedToString( "MetaDataTypeDefinitionByRef" ); } public override String ToString( IMetaDataDumper context ) { return InnerToString( m_type.ToStringWithAbbreviations( context ) ); } private String InnerToString( string type ) { switch(m_elementType) { case ElementTypes.BYREF: return "byref " + type; case ElementTypes.PTR: return type + " *"; case ElementTypes.PINNED: return "pinned " + type; default: return m_elementType.ToString() + " " + type; } } public override void Dump( IMetaDataDumper writer ) { throw new NotNormalized( "Dump" ); } } } ================================================ FILE: Zelig/Zelig/CompileTime/MetaData/Normalized/MetaDataTypeDefinitionDelayed.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // namespace Microsoft.Zelig.MetaData.Normalized { using System; using System.Collections.Generic; // // Don't remove "sealed" attribute unless you read comments on Equals method. // public sealed class MetaDataTypeDefinitionDelayed : MetaDataTypeDefinitionAbstract, IMetaDataUnique { // // State // internal int m_parameterNumber; internal bool m_isMethodParam; // // Constructor Methods // internal MetaDataTypeDefinitionDelayed( MetaDataAssembly owner , int token ) : base( owner, token ) { } //--// // // MetaDataEquality Methods // public override bool Equals( object obj ) { if(obj is MetaDataTypeDefinitionDelayed) // Since the class is sealed (no subclasses allowed), there's no need to compare using .GetType() { MetaDataTypeDefinitionDelayed other = (MetaDataTypeDefinitionDelayed)obj; if(m_owner == other.m_owner && m_parameterNumber == other.m_parameterNumber && m_isMethodParam == other.m_isMethodParam ) { return true; } } return false; } public override int GetHashCode() { return (int) m_parameterNumber ^ (m_isMethodParam ? 0 : 1) ; } // // Helper Methods // public override bool IsOpenType { get { return true; } } public override bool Match( MetaDataTypeDefinitionAbstract typeContext , MetaDataMethodAbstract methodContext , MetaDataTypeDefinitionAbstract type ) { if(type is MetaDataTypeDefinitionDelayed) // Since the class is sealed (no subclasses allowed), there's no need to compare using .GetType() { MetaDataTypeDefinitionDelayed other = (MetaDataTypeDefinitionDelayed)type; if(m_parameterNumber == other.m_parameterNumber && m_isMethodParam == other.m_isMethodParam ) { return true; } } return false; } // // Access Methods // public int ParameterNumber { get { return m_parameterNumber; } } public bool IsMethodParameter { get { return m_isMethodParam; } } public override bool UsesTypeParameters { get { return m_isMethodParam == false; } } public override bool UsesMethodParameters { get { return m_isMethodParam == true; } } // // Debug Methods // public override string FullName { get { return AppendQualifiers(); } } public override string FullNameWithAbbreviation { get { return AppendQualifiers(); } } public override string ToString() { return QualifiedToString( "MetaDataTypeDefinitionDelayed" ); } public override String ToString( IMetaDataDumper context ) { return MetaDataTypeDefinitionAbstract.ParameterToString( context, m_parameterNumber, m_isMethodParam, null ); } public override void Dump( IMetaDataDumper writer ) { throw new NotNormalized( "Dump" ); } //--// private string AppendQualifiers() { System.Text.StringBuilder sb = new System.Text.StringBuilder(); sb.Append( "{" ); sb.Append( m_isMethodParam ? "MVAR" : "VAR" ); sb.Append( "," ); sb.Append( m_parameterNumber ); sb.Append( "}" ); return sb.ToString(); } } } ================================================ FILE: Zelig/Zelig/CompileTime/MetaData/Normalized/MetaDataTypeDefinitionGeneric.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // namespace Microsoft.Zelig.MetaData.Normalized { using System; // // Don't remove "sealed" attribute unless you read comments on Equals method. // public sealed class MetaDataTypeDefinitionGeneric : MetaDataTypeDefinitionBase, IMetaDataUnique { // // State // internal MetaDataGenericTypeParam[] m_genericParams; // // Constructor Methods // internal MetaDataTypeDefinitionGeneric( MetaDataAssembly owner , int token ) : base( owner, token ) { } //--// // // MetaDataEquality Methods // public override bool Equals( object obj ) { if(obj is MetaDataTypeDefinitionGeneric) // Since the class is sealed (no subclasses allowed), there's no need to compare using .GetType() { MetaDataTypeDefinitionGeneric other = (MetaDataTypeDefinitionGeneric)obj; if(InnerEquals( other )) { return ArrayUtility.ArrayEquals( m_genericParams, other.m_genericParams ); } } return false; } public override int GetHashCode() { return InnerGetHashCode(); } // // Helper Methods // public override bool IsOpenType { get { return true; } } public override bool UsesTypeParameters { get { return true; } } public override bool UsesMethodParameters { get { return false; } } public override bool Match( MetaDataTypeDefinitionAbstract typeContext , MetaDataMethodAbstract methodContext , MetaDataTypeDefinitionAbstract type ) { throw new NotNormalized( "Match" ); } // // Access Methods // public MetaDataGenericTypeParam[] GenericParams { get { return m_genericParams; } } public override string FullName { get { System.Text.StringBuilder sb = new System.Text.StringBuilder(); if(this.IsNestedType) { sb.Append( this.EnclosingClass.FullName ); sb.Append( "." ); } if(this.Namespace != null && this.Namespace.Length != 0) { sb.Append( this.Namespace ); sb.Append( "." ); } sb.Append( this.Name ); return sb.ToString(); } } public override string ToString() { return QualifiedToString( "MetaDataTypeDefinitionGeneric" ); } public override String ToString( IMetaDataDumper context ) { System.Text.StringBuilder sb = new System.Text.StringBuilder(); if(this.IsNestedType) { sb.Append( this.EnclosingClass.ToString( context ) ); sb.Append( "." ); } if(this.Namespace != null && this.Namespace.Length != 0) { sb.Append( this.Namespace ); sb.Append( "." ); } sb.Append( this.Name ); sb.Append( TokenToString( m_token ) ); sb.Append( "<" ); for(int i = 0; i < m_genericParams.Length; i++) { if(i != 0) sb.Append( "," ); sb.Append( m_genericParams[i].ToString( context ) ); } sb.Append( ">" ); return sb.ToString(); } public override void Dump( IMetaDataDumper writer ) { InnerDump( writer, m_genericParams ); } } } ================================================ FILE: Zelig/Zelig/CompileTime/MetaData/Normalized/MetaDataTypeDefinitionGenericInstantiation.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // namespace Microsoft.Zelig.MetaData.Normalized { using System; // // Don't remove "sealed" attribute unless you read comments on Equals method. // public sealed class MetaDataTypeDefinitionGenericInstantiation : MetaDataTypeDefinitionAbstract, IMetaDataUnique { // // State // internal MetaDataTypeDefinitionGeneric m_baseType; internal SignatureType[] m_parameters; // // Constructor Methods // internal MetaDataTypeDefinitionGenericInstantiation( MetaDataAssembly owner , int token ) : base( owner, token ) { m_elementType = ElementTypes.GENERICINST; } //--// // // MetaDataEquality Methods // public override bool Equals( object obj ) { if(obj is MetaDataTypeDefinitionGenericInstantiation) // Since the class is sealed (no subclasses allowed), there's no need to compare using .GetType() { MetaDataTypeDefinitionGenericInstantiation other = (MetaDataTypeDefinitionGenericInstantiation)obj; if(m_baseType == other.m_baseType) { if(ArrayUtility.ArrayEquals( m_parameters, other.m_parameters)) { return true; } } } return false; } public override int GetHashCode() { return m_baseType.GetHashCode(); } // // Helper Methods // public override bool IsOpenType { get { for(int i = 0; i < m_parameters.Length; i++) { if(m_parameters[i].IsOpenType) { return true; } } return false; } } public override bool Match( MetaDataTypeDefinitionAbstract typeContext , MetaDataMethodAbstract methodContext , MetaDataTypeDefinitionAbstract type ) { if(type is MetaDataTypeDefinitionGenericInstantiation) { MetaDataTypeDefinitionGenericInstantiation other = (MetaDataTypeDefinitionGenericInstantiation)type; if(m_baseType == other.m_baseType && m_parameters.Length == other.m_parameters.Length ) { for(int i = 0; i < m_parameters.Length; i++) { if(m_parameters[i].Match( typeContext, methodContext, other.m_parameters[i] ) == false) { return false; } } return true; } } return false; } public MetaDataTypeDefinitionGenericInstantiation Specialize( SignatureType[] genericParameters ) { MetaDataTypeDefinitionGenericInstantiation tdNew = new MetaDataTypeDefinitionGenericInstantiation( m_owner, 0 ); tdNew.m_baseType = m_baseType; tdNew.m_parameters = genericParameters; return tdNew; } // // Access Methods // public MetaDataTypeDefinitionGeneric GenericType { get { return m_baseType; } } public SignatureType[] InstantiationParams { get { return m_parameters; } } public override bool UsesTypeParameters { get { foreach(SignatureType td in m_parameters) { if(td.UsesTypeParameters) return true; } return false; } } public override bool UsesMethodParameters { get { foreach(SignatureType td in m_parameters) { if(td.UsesMethodParameters) return true; } return false; } } // // Debug Methods // public override string FullName { get { System.Text.StringBuilder sb = new System.Text.StringBuilder(); sb.Append( m_baseType.FullName ); sb.Append( "<" ); for(int i = 0; i < m_parameters.Length; i++) { if(i != 0) sb.Append( "," ); sb.Append( m_parameters[i].FullName ); } sb.Append( ">" ); return sb.ToString(); } } public override string FullNameWithAbbreviation { get { System.Text.StringBuilder sb = new System.Text.StringBuilder(); sb.Append( m_baseType.FullNameWithAbbreviation ); sb.Append( "<" ); for(int i = 0; i < m_parameters.Length; i++) { if(i != 0) sb.Append( "," ); sb.Append( m_parameters[i].FullNameWithAbbreviation ); } sb.Append( ">" ); return sb.ToString(); } } public override string ToString() { return QualifiedToString( "MetaDataTypeDefinitionGenericInstantiation" ); } public override String ToString( IMetaDataDumper context ) { System.Text.StringBuilder sb = new System.Text.StringBuilder(); context = context.PushContext( this ); sb.Append( m_baseType.ToString( context ) ); return sb.ToString(); } public override void Dump( IMetaDataDumper writer ) { throw new NotNormalized( "Dump" ); } } } ================================================ FILE: Zelig/Zelig/CompileTime/MetaData/Normalized/MetaDataTypeDefinitionPartiallyDelayedMethodParameter.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // namespace Microsoft.Zelig.MetaData.Normalized { using System; using System.Collections.Generic; // // Don't remove "sealed" attribute unless you read comments on Equals method. // public sealed class MetaDataTypeDefinitionPartiallyDelayedMethodParameter : MetaDataTypeDefinitionAbstract, IMetaDataUnique { // // State // internal readonly MetaDataMethodGeneric m_contextMethod; internal readonly int m_parameterNumber; // // Constructor Methods // public MetaDataTypeDefinitionPartiallyDelayedMethodParameter( MetaDataMethodGeneric contextMethod , int parameterNumber ) : base( contextMethod.Owner.Owner, 0 ) { m_contextMethod = contextMethod; m_parameterNumber = parameterNumber; } //--// // // MetaDataEquality Methods // public override bool Equals( object obj ) { if(obj is MetaDataTypeDefinitionPartiallyDelayedMethodParameter) // Since the class is sealed (no subclasses allowed), there's no need to compare using .GetType() { MetaDataTypeDefinitionPartiallyDelayedMethodParameter other = (MetaDataTypeDefinitionPartiallyDelayedMethodParameter)obj; if(m_contextMethod == other.m_contextMethod && m_parameterNumber == other.m_parameterNumber ) { return true; } } return false; } public override int GetHashCode() { return m_contextMethod .GetHashCode() ^ (int)m_parameterNumber ; } // // Helper Methods // public override bool IsOpenType { get { return true; } } public override bool Match( MetaDataTypeDefinitionAbstract typeContext , MetaDataMethodAbstract methodContext , MetaDataTypeDefinitionAbstract type ) { throw new NotNormalized( "Match" ); } // // Access Methods // public MetaDataMethodGeneric ContextMethod { get { return m_contextMethod; } } public int ParameterNumber { get { return m_parameterNumber; } } public override bool UsesTypeParameters { get { return false; } } public override bool UsesMethodParameters { get { return true; } } // // Debug Methods // public override string FullName { get { return AppendQualifiers(); } } public override string FullNameWithAbbreviation { get { return AppendQualifiers(); } } public override string ToString() { return QualifiedToString( "MetaDataTypeDefinitionPartiallyDelayedMethodParameter" ); } public override String ToString( IMetaDataDumper context ) { return MetaDataTypeDefinitionAbstract.ParameterToString( context, m_parameterNumber, true, null ); } public override void Dump( IMetaDataDumper writer ) { throw new NotNormalized( "Dump" ); } //--// private string AppendQualifiers() { System.Text.StringBuilder sb = new System.Text.StringBuilder(); sb.Append( m_contextMethod.FullName ); sb.Append( "." ); sb.Append( m_contextMethod.GenericParams[m_parameterNumber].Name ); return sb.ToString(); } } } ================================================ FILE: Zelig/Zelig/CompileTime/MetaData/Normalized/MetaDataTypeDefinitionPartiallyDelayedTypeParameter.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // namespace Microsoft.Zelig.MetaData.Normalized { using System; using System.Collections.Generic; // // Don't remove "sealed" attribute unless you read comments on Equals method. // public sealed class MetaDataTypeDefinitionPartiallyDelayedTypeParameter : MetaDataTypeDefinitionAbstract, IMetaDataUnique { // // State // internal readonly MetaDataTypeDefinitionGeneric m_contextType; internal readonly int m_parameterNumber; // // Constructor Methods // public MetaDataTypeDefinitionPartiallyDelayedTypeParameter( MetaDataTypeDefinitionGeneric contextType , int parameterNumber ) : base( contextType.Owner, 0 ) { m_contextType = contextType; m_parameterNumber = parameterNumber; } //--// // // MetaDataEquality Methods // public override bool Equals( object obj ) { if(obj is MetaDataTypeDefinitionPartiallyDelayedTypeParameter) // Since the class is sealed (no subclasses allowed), there's no need to compare using .GetType() { MetaDataTypeDefinitionPartiallyDelayedTypeParameter other = (MetaDataTypeDefinitionPartiallyDelayedTypeParameter)obj; if(m_contextType == other.m_contextType && m_parameterNumber == other.m_parameterNumber ) { return true; } } return false; } public override int GetHashCode() { return m_contextType .GetHashCode() ^ (int)m_parameterNumber ; } // // Helper Methods // public override bool IsOpenType { get { return true; } } public override bool Match( MetaDataTypeDefinitionAbstract typeContext , MetaDataMethodAbstract methodContext , MetaDataTypeDefinitionAbstract type ) { throw new NotNormalized( "Match" ); } // // Access Methods // public MetaDataTypeDefinitionGeneric ContextType { get { return m_contextType; } } public int ParameterNumber { get { return m_parameterNumber; } } public override bool UsesTypeParameters { get { return true; } } public override bool UsesMethodParameters { get { return false; } } // // Debug Methods // public override string FullName { get { return AppendQualifiers(); } } public override string FullNameWithAbbreviation { get { return AppendQualifiers(); } } public override string ToString() { return QualifiedToString( "MetaDataTypeDefinitionPartiallyDelayedTypeParameter" ); } public override String ToString( IMetaDataDumper context ) { return MetaDataTypeDefinitionAbstract.ParameterToString( context, m_parameterNumber, false, null ); } public override void Dump( IMetaDataDumper writer ) { throw new NotNormalized( "Dump" ); } //--// private string AppendQualifiers() { System.Text.StringBuilder sb = new System.Text.StringBuilder(); sb.Append( m_contextType.FullName ); sb.Append( "." ); sb.Append( m_contextType.GenericParams[m_parameterNumber].Name ); return sb.ToString(); } } } ================================================ FILE: Zelig/Zelig/CompileTime/MetaData/Normalized/MetaDataVersion.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // namespace Microsoft.Zelig.MetaData { using System; using System.Collections.Generic; using System.Text; // // Don't remove "sealed" attribute unless you read comments on Equals method. // public sealed class MetaDataVersion : Normalized.IMetaDataUnique { // // State // internal short m_majorVersion; internal short m_minorVersion; internal short m_buildNumber; internal short m_revisionNumber; internal AssemblyFlags m_flags; internal byte[] m_publicKey; // // Constructor Methods // internal MetaDataVersion() { } // // MetaDataEquality Methods // public override bool Equals( object obj ) { if(obj is MetaDataVersion) // Since the class is sealed (no subclasses allowed), there's no need to compare using .GetType() { MetaDataVersion other = (MetaDataVersion)obj; return IsCompatible( other, true ); } return false; } public override int GetHashCode() { return (int)m_majorVersion << 15 ^ (int)m_minorVersion << 10 ^ (int)m_buildNumber << 5 ^ (int)m_revisionNumber ; } // // Helper Methods // public bool IsCompatible( MetaDataVersion ver , bool exact ) { // BUGBUG: This ignores the strong name of an assembly. if(m_majorVersion < ver.m_majorVersion ) return false; if(m_majorVersion > ver.m_majorVersion && !exact) return true; if(m_minorVersion < ver.m_minorVersion ) return false; if(m_minorVersion > ver.m_minorVersion && !exact) return true; if(m_buildNumber < ver.m_buildNumber ) return false; if(m_buildNumber > ver.m_buildNumber && !exact) return true; if(m_revisionNumber < ver.m_revisionNumber ) return false; if(m_revisionNumber > ver.m_revisionNumber && !exact) return true; return true; } // // Access Methods // public short MajorVersion { get { return m_majorVersion; } } public short MinorVersion { get { return m_minorVersion; } } public short BuildNumber { get { return m_buildNumber; } } public short RevisionNumber { get { return m_revisionNumber; } } public AssemblyFlags Flags { get { return m_flags; } } public byte[] PublicKey { get { return m_publicKey; } } // // Debug Methods // public override String ToString() { System.Text.StringBuilder sb = new System.Text.StringBuilder( "MetaDataVersion(" ); sb.Append( m_majorVersion ); sb.Append( "," ); sb.Append( m_minorVersion ); sb.Append( "," ); sb.Append( m_buildNumber ); sb.Append( "," ); sb.Append( m_revisionNumber ); sb.Append( "," ); sb.Append( m_flags ); sb.Append( ",[" ); // BUGBUG: ArrayReader.AppendAsString( sb, m_publicKey ); sb.Append( "])" ); return sb.ToString(); } } } ================================================ FILE: Zelig/Zelig/CompileTime/MetaData/Normalized/Normalized.csproj ================================================  Debug AnyCPU 9.0.21022 2.0 {186F31A3-EF89-4A25-B2D5-20060510AA01} Library Properties Microsoft.Zelig.MetaData.Normalized Microsoft.Zelig.MetaData.Normalized $(LlilumBuildRoot)\Host\obj\$(MSBuildProjectName)\ v4.5 true full false $(LlilumBuildRoot)\Host\bin\$(Configuration)\ DEBUG;TRACE prompt 4 true AllRules.ruleset AnyCPU false pdbonly true $(LlilumBuildRoot)\Host\bin\$(Configuration)\ TRACE prompt 4 true AllRules.ruleset AnyCPU false $(LlilumBuildRoot)\Host\bin\$(Configuration)\ DEBUG;TRACE AnyCPU true false {186F31A3-EF89-4A25-B2D5-20061218AA01} Common False 3.5 ================================================ FILE: Zelig/Zelig/CompileTime/MetaData/Normalized/Properties/AssemblyInfo.cs ================================================ using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; // General Information about an assembly is controlled through the following // set of attributes. Change these attribute values to modify the information // associated with an assembly. [assembly: AssemblyTitle( "Microsoft.Zelig.MetaData.Normalized" )] [assembly: AssemblyDescription( "" )] [assembly: AssemblyConfiguration( "" )] [assembly: AssemblyCompany( "Microsoft" )] [assembly: AssemblyProduct( "Microsoft.Zelig.MetaData.Normalized" )] [assembly: AssemblyCopyright( "Copyright © Microsoft 2006" )] [assembly: AssemblyTrademark( "" )] [assembly: AssemblyCulture( "" )] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible( false )] //// The following GUID is for the ID of the typelib if this project is exposed to COM //[assembly: Guid( "196b4aef-da6d-4ebf-9f6c-06b8e3bfe8b5" )] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Revision and Build Numbers // by using the '*' as shown below: [assembly: AssemblyVersion( "1.0.0.0" )] [assembly: AssemblyFileVersion( "1.0.0.0" )] [assembly: InternalsVisibleTo( "Microsoft.Zelig.MetaData.Importer" )] ================================================ FILE: Zelig/Zelig/CompileTime/MetaData/Normalized/SignatureField.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // namespace Microsoft.Zelig.MetaData.Normalized { using System; // // Don't remove "sealed" attribute unless you read comments on Equals method. // public sealed class SignatureField : MetaDataSignature, IMetaDataUnique { // // State // internal SignatureType m_type; // // Constructor Methods // internal SignatureField( int token ) : base( token ) { } // // MetaDataEquality Methods // public override bool Equals( object obj ) { if(obj is SignatureField) // Since the class is sealed (no subclasses allowed), there's no need to compare using .GetType() { SignatureField other = (SignatureField)obj; if(m_type == other.m_type) { if(base.InnerEquals( other )) { return true; } } } return false; } public override int GetHashCode() { return m_type.GetHashCode(); } // // Helper Methods // internal override MetaDataObject MakeUnique() { return m_type.Type.MakeUnique( this ); } // // Helper Methods // public bool Match( SignatureField sig ) { return m_type.Match( null, null, sig.m_type ); } // // Access Methods // public SignatureType TypeSignature { get { return m_type; } } public bool IsOpenType { get { return m_type.IsOpenType; } } public override bool UsesTypeParameters { get { return m_type.UsesTypeParameters; } } public override bool UsesMethodParameters { get { return m_type.UsesMethodParameters; } } // // Debug Methods // public String FullName { get { System.Text.StringBuilder sb = new System.Text.StringBuilder(); sb.Append( m_type.FullName ); return sb.ToString(); } } public override String ToString() { System.Text.StringBuilder sb = new System.Text.StringBuilder( "SignatureField(" ); sb.Append( this.FullName ); return sb.ToString(); } public override void Dump( IMetaDataDumper writer ) { throw new NotNormalized( "Dump" ); } } } ================================================ FILE: Zelig/Zelig/CompileTime/MetaData/Normalized/SignatureMethod.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // namespace Microsoft.Zelig.MetaData.Normalized { using System; // // Don't remove "sealed" attribute unless you read comments on Equals method. // public sealed class SignatureMethod : MetaDataSignature, IMetaDataUnique { public enum CallingConventions : byte { Default = 0x00, Unmanaged_cdecl = 0x01, Unmanaged_sdtcall = 0x02, Unmanaged_thiscall = 0x03, Unmanaged_fastcall = 0x04, VarArg = 0x05, Field = 0x06, LocalVar = 0x07, Property = 0x08, Unmanaged = 0x09, GenericInst = 0x0A, Mask = 0x0F, Generic = 0x10, HasThis = 0x20, ExplicitThis = 0x40 } // // State // internal CallingConventions m_callingConvention; internal SignatureType m_returnType; internal SignatureType[] m_parameters; // // Constructor Methods // internal SignatureMethod( int token ) : base( token ) { } // // MetaDataEquality Methods // public override bool Equals( object obj ) { if(obj is SignatureMethod) // Since the class is sealed (no subclasses allowed), there's no need to compare using .GetType() { SignatureMethod other = (SignatureMethod)obj; if(m_callingConvention == other.m_callingConvention && m_returnType == other.m_returnType ) { if(ArrayUtility.ArrayEquals( m_parameters, other.m_parameters )) { if(base.InnerEquals( other )) { return true; } } } } return false; } public override int GetHashCode() { int res = (int)m_callingConvention ^ m_returnType .GetHashCode() ; if(m_parameters != null) { for(int i = 0; i < m_parameters.Length; i++) { res = res << 5 ^ m_parameters[i].GetHashCode() ^ res >> (32-5); } } return res; } // // Helper Methods // internal override MetaDataObject MakeUnique() { return m_returnType.Type.MakeUnique( this ); } // // Helper Methods // public bool Match( SignatureMethod sig ) { if(sig.CallingConvention == (SignatureMethod.CallingConventions)m_callingConvention) { if(m_parameters.Length == sig.m_parameters.Length) { if(m_returnType.Match( null, null, sig.m_returnType )) { for(int i = 0; i < m_parameters.Length; i++) { if(m_parameters[i].Match( null, null, sig.m_parameters[i] ) == false) { return false; } } return true; } } } return false; } // // Access Methods // public CallingConventions CallingConvention { get { return m_callingConvention; } } public SignatureType ReturnType { get { return m_returnType; } } public SignatureType[] Parameters { get { return m_parameters; } } public override bool UsesTypeParameters { get { if(m_returnType.UsesTypeParameters) return true; foreach(SignatureType td in m_parameters) { if(td.UsesTypeParameters) return true; } return false; } } public override bool UsesMethodParameters { get { if(m_returnType.UsesMethodParameters) return true; foreach(SignatureType td in m_parameters) { if(td.UsesMethodParameters) return true; } return false; } } // // Debug Methods // public String FullName { get { System.Text.StringBuilder sb = new System.Text.StringBuilder(); sb.Append( m_returnType.FullName ); sb.Append( " <= " ); if((m_callingConvention & CallingConventions.HasThis) != 0) { sb.Append( "this," ); } for(int i = 0; i < m_parameters.Length; i++) { if(i != 0) { sb.Append( "," ); } sb.Append( m_parameters[i].FullName ); } return sb.ToString(); } } public override String ToString() { System.Text.StringBuilder sb = new System.Text.StringBuilder( "SignatureMethod(" ); sb.Append( m_callingConvention ); sb.Append( "," ); sb.Append( m_returnType ); sb.Append( "," ); sb.Append( "parameters(" ); for(int i = 0; i < m_parameters.Length; i++) { if(i != 0) { sb.Append( "," ); } sb.Append( m_parameters[i] ); } sb.Append( "))" ); return sb.ToString(); } public override void Dump( IMetaDataDumper writer ) { throw new NotNormalized( "Dump" ); } internal static string EnumToString( CallingConventions val ) { System.Text.StringBuilder sb = new System.Text.StringBuilder(); if((val & CallingConventions.ExplicitThis) != 0 ) sb.Append( "explicit " ); if((val & CallingConventions.HasThis ) != 0 ) sb.Append( "instance " ); if((val & CallingConventions.Mask ) == CallingConventions.Unmanaged_cdecl ) sb.Append( "unmanaged cdecl " ); if((val & CallingConventions.Mask ) == CallingConventions.Unmanaged_sdtcall ) sb.Append( "unmanaged stdcall " ); if((val & CallingConventions.Mask ) == CallingConventions.Unmanaged_thiscall) sb.Append( "unmanaged thiscall " ); if((val & CallingConventions.Mask ) == CallingConventions.Unmanaged_fastcall) sb.Append( "unmanaged fastcall " ); if((val & CallingConventions.Mask ) == CallingConventions.VarArg ) sb.Append( "vararg " ); return sb.ToString(); } } } ================================================ FILE: Zelig/Zelig/CompileTime/MetaData/Normalized/SignatureType.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // namespace Microsoft.Zelig.MetaData.Normalized { using System; // // Don't remove "sealed" attribute unless you read comments on Equals method. // public sealed class SignatureType : MetaDataSignature, IMetaDataUnique { // // State // internal MetaDataTypeDefinitionAbstract m_type; // // Constructor Methods // internal SignatureType( int token ) : base( token ) { } private SignatureType( MetaDataTypeDefinitionAbstract type ) : base( 0 ) { m_type = (MetaDataTypeDefinitionAbstract)type.MakeUnique(); } // // MetaDataEquality Methods // public override bool Equals( object obj ) { if(obj is SignatureType) // Since the class is sealed (no subclasses allowed), there's no need to compare using .GetType() { SignatureType other = (SignatureType)obj; if(m_type == other.m_type) { if(base.InnerEquals( other )) { return true; } } } return false; } public override int GetHashCode() { return m_type.GetHashCode(); } // // Helper Methods // internal override MetaDataObject MakeUnique() { return m_type.MakeUnique( this ); } public static SignatureType Create( MetaDataTypeDefinitionAbstract type ) { return new SignatureType( type ); } public static SignatureType CreateUnique( MetaDataTypeDefinitionAbstract type ) { return (SignatureType)type.MakeUnique( new SignatureType( type ) ); } //--// public bool Match( MetaDataTypeDefinitionAbstract typeContext , MetaDataMethodAbstract methodContext , SignatureType sig ) { return m_type.Match( typeContext, methodContext, sig.m_type ); } // // Access Methods // public MetaDataTypeDefinitionAbstract Type { get { return m_type; } } public bool IsOpenType { get { return m_type.IsOpenType; } } public override bool UsesTypeParameters { get { return m_type.UsesTypeParameters; } } public override bool UsesMethodParameters { get { return m_type.UsesMethodParameters; } } // // Debug Methods // public string FullNameWithAbbreviation { get { return m_type.FullNameWithAbbreviation; } } public string ToStringWithAbbreviations( IMetaDataDumper context ) { return m_type.ToStringWithAbbreviations( context ); } public String FullName { get { System.Text.StringBuilder sb = new System.Text.StringBuilder(); sb.Append( m_type.FullName ); return sb.ToString(); } } public override String ToString() { System.Text.StringBuilder sb = new System.Text.StringBuilder( "SignatureType(" ); sb.Append( this.FullName ); return sb.ToString(); } public override void Dump( IMetaDataDumper writer ) { throw new NotNormalized( "Dump" ); } } } ================================================ FILE: Zelig/Zelig/CompileTime/TargetModels/ArmProcessor/ARM/EncodingDefinition_ARM.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // namespace Microsoft.Zelig.TargetModel.ArmProcessor { public class EncodingDefinition_ARM : EncodingDefinition { // // +---------+---+---+---+---------------+---+---------+---------+---------+---------------+---------+ // | 3 3 2 2 | 2 | 2 | 2 | 2 2 2 2 | 2 | 1 1 1 1 | 1 1 1 1 | 1 1 9 8 | 7 6 5 4 | 3 2 1 0 | // | 1 0 9 8 | 7 | 6 | 5 | 4 3 2 1 | 0 | 9 8 7 6 | 5 4 3 2 | 1 0 | | | // +---------+---+---+---+---+---+---+---+---+---------+---------+---------+---------------+---------+ // | Cond | 0 0 0 1 0 | Ps| 0 0 | 1 1 1 1 | Rd | 0 0 0 0 0 0 0 0 | 0 0 0 0 | MRS // +---------+-------------------+---+-------+---------+---------+-------------------------+---------+ // | Cond | 0 0 0 1 0 | Pd| 1 0 | S S S S | 1 1 1 1 | 0 0 0 0 0 0 0 0 | Rm | MSR // +---------+-------------------+---+-------+---------+---------+---------+---------------+---------+ // | Cond | 0 0 1 1 0 | Pd| 1 0 | S S S S | 1 1 1 1 | Rotate | Immediate | MSR // +---------+---+---+---+-------+---+---+---+---------+---------+---------+-------------------------+ // | Cond | 0 | 0 | 1 | Opcode | S | Rn | Rd | Rotate | Immediate | Data Processing / PSR Transfer // +---------+---+---+---+---------------+---+---------+---------+---------+---+-------+---+---------+ // | Cond | 0 | 0 | 0 | Opcode | S | Rn | Rd | Shift Imm | SType | 0 | Rm | Data Processing / PSR Transfer // +---------+---+---+---+---------------+---+---------+---------+---------+---+-------+---+---------+ // | Cond | 0 | 0 | 0 | Opcode | S | Rn | Rd | Shift Rp| 0 | SType | 1 | Rm | Data Processing / PSR Transfer // +---------+---+---+---+---+---+---+---+---+---------+---------+---------+---+---+---+---+---------+ // | Cond | 0 | 0 | 0 | 0 | 0 | 0 | A | S | Rd | Rn | Rs | 1 | 0 | 0 | 1 | Rm | Multiply // +---------+---+---+---+---+---+---+---+---+---------+---------+---------+---+---+---+---+---------+ // | Cond | 0 | 0 | 0 | 0 | 1 | U | A | S | RdHi | RdLo | Rn | 1 | 0 | 0 | 1 | Rm | Multiply Long // +---------+---+---+---+---+---+---+---+---+---------+---------+---------+---+---+---+---+---------+ // | Cond | 0 | 0 | 0 | 1 | 0 | B | 0 | 0 | Rn | Rd | 0 0 0 0 | 1 | 0 | 0 | 1 | Rm | Single Data Swap // +---------+---+---+---+---+---+---+---+---+---------+---------+---------+---+---+---+---+---------+ // | Cond | 0 | 0 | 0 | 1 | 0 | 0 | 1 | 0 | 1 1 1 1 | 1 1 1 1 | 1 1 1 1 | 0 | 0 | 0 | 1 | Rn | Branch and Exchange // +---------+---+---+---+---+---+---+---+---+---------+---------+---------+---+---+---+---+---------+ // | Cond | 0 | 0 | 0 | P | U | 0 | W | L | Rn | Rd | 0 0 0 0 | 1 | S | H | 1 | Rm | Halfword Data Transfer: register offset // +---------+---+---+---+---+---+---+---+---+---------+---------+---------+---+---+---+---+---------+ // | Cond | 0 | 0 | 0 | P | U | 1 | W | L | Rn | Rd | Offset | 1 | S | H | 1 | Offset | Halfword Data Transfer: immediate offset // +---------+---+---+---+---+---+---+---+---+---------+---------+---------+---+---+---+---+---------+ // | Cond | 0 | 1 | 0 | P | U | B | W | L | Rn | Rd | Immediate Offset | Single Data Transfer // +---------+---+---+---+---+---+---+---+---+---------+---------+---------+---+---+---+---+---------+ // | Cond | 0 | 1 | 1 | P | U | B | W | L | Rn | Rd | Shift Imm | SType | 0 | Rm | Single Data Transfer // +---------+---+---+---+---+---+---+---+---+---------+---------+---------+---+-------+---+---------+ // | Cond | 0 | 1 | 1 | P | U | B | W | L | Rn | Rd | Shift Rp| 0 | SType | 1 | Rm | Single Data Transfer // +---------+---+---+---+---+---+---+---+---+---------+---------+---------+---+-------+---+---------+ // | Cond | 0 | 1 | 1 | XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX| 1 | XXXXX | 1 | XXXXXX | Undefined // +---------+---+---+---+---+---+---+---+---+---------+---------+---------+---+-------+---+---------+ // | Cond | 1 | 0 | 0 | P | U | S | W | L | Rn | Register List | Block Data Transfer // +---------+---+---+---+---+---+---+---+---+---------+---------------------------------------------+ // | Cond | 1 | 0 | 1 | L | Offset | Branch // +---------+---+---+---+---+---+---+---+---+---------+---------+---------+-------------------------+ // | Cond | 1 | 1 | 0 | P | U | N | W | L | Rn | CRd | CP# | Offset | Coprocessor Data Transfer // +---------+---+---+---+---+---+---+---+---+---------+---------+---------+-----------+---+---------+ // | Cond | 1 | 1 | 1 | 0 | CP Opc | CRn | CRd | CP# | CP | 0 | CRm | Coprocessor Data Operation // +---------+---+---+---+---+-----------+---+---------+---------+---------+-----------+---+---------+ // | Cond | 1 | 1 | 1 | 0 | CP Opc | L | CRn | Rd | CP# | CP | 1 | CRm | Coprocessor Register Transfer // +---------+---+---+---+---+-----------+---+---------+---------+---------+-----------+---+---------+ // | Cond | 1 | 1 | 1 | 1 | Ignored by processor | Software Interrupt // +---------+---+---+---+---+-----------------------------------------------------------------------+ // public const uint op_MRS = 0x010F0000; public const uint opmask_MRS = 0x0FBF0FFF; public const uint op_MSR_1 = 0x0120F000; public const uint opmask_MSR_1 = 0x0FB0FFF0; public const uint op_MSR_2 = 0x0320F000; public const uint opmask_MSR_2 = 0x0FB0F000; public const uint op_DataProcessing_1 = 0x02000000; public const uint opmask_DataProcessing_1 = 0x0E000000; public const uint op_DataProcessing_2 = 0x00000000; public const uint opmask_DataProcessing_2 = 0x0E000010; public const uint op_DataProcessing_3 = 0x00000010; public const uint opmask_DataProcessing_3 = 0x0E000090; public const uint op_Multiply = 0x00000090; public const uint opmask_Multiply = 0x0FC000F0; public const uint op_MultiplyLong = 0x00800090; public const uint opmask_MultiplyLong = 0x0F8000F0; public const uint op_SingleDataSwap = 0x01000090; public const uint opmask_SingleDataSwap = 0x0FB00FF0; public const uint op_BranchAndExchange = 0x012FFF10; public const uint opmask_BranchAndExchange = 0x0FFFFFF0; public const uint op_HalfwordDataTransfer_1 = 0x00000090; public const uint opmask_HalfwordDataTransfer_1 = 0x0E400F90; public const uint op_HalfwordDataTransfer_2 = 0x00400090; public const uint opmask_HalfwordDataTransfer_2 = 0x0E400090; public const uint op_SingleDataTransfer_1 = 0x04000000; public const uint opmask_SingleDataTransfer_1 = 0x0E000000; public const uint op_SingleDataTransfer_2 = 0x06000000; public const uint opmask_SingleDataTransfer_2 = 0x0E000010; public const uint op_SingleDataTransfer_3 = 0x06000010; public const uint opmask_SingleDataTransfer_3 = 0x0E000090; public const uint op_Undefined = 0x06000090; public const uint opmask_Undefined = 0x0E000090; public const uint op_BlockDataTransfer = 0x08000000; public const uint opmask_BlockDataTransfer = 0x0E000000; public const uint op_Branch = 0x0A000000; public const uint opmask_Branch = 0x0E000000; public const uint op_CoprocDataTransfer = 0x0C000000; public const uint opmask_CoprocDataTransfer = 0x0E000000; public const uint op_CoprocDataOperation = 0x0E000000; public const uint opmask_CoprocDataOperation = 0x0F000010; public const uint op_CoprocRegisterTransfer = 0x0E000010; public const uint opmask_CoprocRegisterTransfer = 0x0F000010; public const uint op_SoftwareInterrupt = 0x0F000000; public const uint opmask_SoftwareInterrupt = 0x0F000000; public const uint op_Breakpoint = 0xE1200070; public const uint opmask_Breakpoint = 0xFFF000F0; //--// public const int c_psr_bit_T = 5; public const int c_psr_bit_F = 6; public const int c_psr_bit_I = 7; public const int c_psr_bit_V = 28; public const int c_psr_bit_C = 29; public const int c_psr_bit_Z = 30; public const int c_psr_bit_N = 31; public const uint c_psr_T = 1U << c_psr_bit_T; public const uint c_psr_F = 1U << c_psr_bit_F; public const uint c_psr_I = 1U << c_psr_bit_I; public const uint c_psr_V = 1U << c_psr_bit_V; public const uint c_psr_C = 1U << c_psr_bit_C; public const uint c_psr_Z = 1U << c_psr_bit_Z; public const uint c_psr_N = 1U << c_psr_bit_N; public const int c_psr_cc_shift = c_psr_bit_V; public const uint c_psr_cc_num = 1U << (c_psr_bit_N - c_psr_bit_V + 1); public const uint c_psr_cc_mask = c_psr_cc_num - 1; public const uint c_psr_mode = 0x0000001F; public const uint c_psr_mode_USER = 0x00000010; public const uint c_psr_mode_FIQ = 0x00000011; public const uint c_psr_mode_IRQ = 0x00000012; public const uint c_psr_mode_SVC = 0x00000013; public const uint c_psr_mode_ABORT = 0x00000017; public const uint c_psr_mode_UNDEF = 0x0000001B; public const uint c_psr_mode_SYS = 0x0000001F; //--// ///////////////////////////////////////// public const uint c_cond_EQ = 0x0; // Z set equal public const uint c_cond_NE = 0x1; // Z clear not equal public const uint c_cond_CS = 0x2; // C set unsigned higher or same public const uint c_cond_CC = 0x3; // C clear unsigned lower public const uint c_cond_MI = 0x4; // N set negative public const uint c_cond_PL = 0x5; // N clear positive or zero public const uint c_cond_VS = 0x6; // V set overflow public const uint c_cond_VC = 0x7; // V clear no overflow public const uint c_cond_HI = 0x8; // C set and Z clear unsigned higher public const uint c_cond_LS = 0x9; // C clear or Z set unsigned lower or same public const uint c_cond_GE = 0xA; // N equals V greater or equal public const uint c_cond_LT = 0xB; // N not equal to V less than public const uint c_cond_GT = 0xC; // Z clear AND (N equals V) greater than public const uint c_cond_LE = 0xD; // Z set OR (N not equal to V) less than or equal public const uint c_cond_AL = 0xE; // (ignored) always public const uint c_cond_UNUSED = 0xF; // ///////////////////////////////////////// public const uint c_cond_NUM = 0x10; /////////////////////////////////////////// public const uint c_operation_AND = 0x0; // operand1 AND operand2 public const uint c_operation_EOR = 0x1; // operand1 EOR operand2 public const uint c_operation_SUB = 0x2; // operand1 - operand2 public const uint c_operation_RSB = 0x3; // operand2 - operand1 public const uint c_operation_ADD = 0x4; // operand1 + operand2 public const uint c_operation_ADC = 0x5; // operand1 + operand2 + carry public const uint c_operation_SBC = 0x6; // operand1 - operand2 + carry - 1 public const uint c_operation_RSC = 0x7; // operand2 - operand1 + carry - 1 public const uint c_operation_TST = 0x8; // as AND, but result is not written public const uint c_operation_TEQ = 0x9; // as EOR, but result is not written public const uint c_operation_CMP = 0xA; // as SUB, but result is not written public const uint c_operation_CMN = 0xB; // as ADD, but result is not written public const uint c_operation_ORR = 0xC; // operand1 OR operand2 public const uint c_operation_MOV = 0xD; // operand2(operand1 is ignored) public const uint c_operation_BIC = 0xE; // operand1 AND NOT operand2(Bit clear) public const uint c_operation_MVN = 0xF; // NOT operand2(operand1 is ignored) /////////////////////////////////////////// //--// /////////////////////////////////////// public const uint c_shift_LSL = 0x0; // logical shift left public const uint c_shift_LSR = 0x1; // logical shift right public const uint c_shift_ASR = 0x2; // arithmetic shift right public const uint c_shift_ROR = 0x3; // rotate right public const uint c_shift_RRX = 0x4; // rotate right with extend /////////////////////////////////////// //--// ////////////////////////////////////////////// public const uint c_halfwordkind_SWP = 0x0; // public const uint c_halfwordkind_U2 = 0x1; // public const uint c_halfwordkind_I1 = 0x2; // public const uint c_halfwordkind_I2 = 0x3; // ////////////////////////////////////////////// //--// ///////////////////////////////////////// public const uint c_psr_field_c = 0x1; // the control field PSR[ 7: 0] public const uint c_psr_field_x = 0x2; // the extension field PSR[15: 8] public const uint c_psr_field_s = 0x4; // the status field PSR[23:16] public const uint c_psr_field_f = 0x8; // the flags field PSR[31:24] public const uint c_psr_field_ALL = c_psr_field_c | c_psr_field_x | c_psr_field_s | c_psr_field_f ; ///////////////////////////////////////// //--// ////////////////////////////////////////// public const uint c_register_cpsr = 16; // public const uint c_register_spsr = 17; // ////////////////////////////////////////// //--// override public uint get_ConditionCodes ( uint op ) { return OPCODE_DECODE_EXTRACTFIELD( op , 28, 4 ); } override public uint set_ConditionCodes ( uint val ) { return OPCODE_DECODE_INSERTFIELD ( val, 28, 4 ); } override public bool get_ShouldSetConditions( uint op ) { return OPCODE_DECODE_CHECKFLAG ( op , 20 ); } override public uint set_ShouldSetConditions( bool val ) { return OPCODE_DECODE_SETFLAG ( val, 20 ); } //--// override public uint get_Register1( uint op ) { return OPCODE_DECODE_EXTRACTFIELD( op , 16, 4 ); } override public uint set_Register1( uint val ) { return OPCODE_DECODE_INSERTFIELD ( val, 16, 4 ); } override public uint get_Register2( uint op ) { return OPCODE_DECODE_EXTRACTFIELD( op , 12, 4 ); } override public uint set_Register2( uint val ) { return OPCODE_DECODE_INSERTFIELD ( val, 12, 4 ); } override public uint get_Register3( uint op ) { return OPCODE_DECODE_EXTRACTFIELD( op , 8, 4 ); } override public uint set_Register3( uint val ) { return OPCODE_DECODE_INSERTFIELD ( val, 8, 4 ); } override public uint get_Register4( uint op ) { return OPCODE_DECODE_EXTRACTFIELD( op , 0, 4 ); } override public uint set_Register4( uint val ) { return OPCODE_DECODE_INSERTFIELD ( val, 0, 4 ); } //--// override public bool get_Multiply_IsAccumulate( uint op ) { return OPCODE_DECODE_CHECKFLAG( op , 21 ); } override public uint set_Multiply_IsAccumulate( bool val ) { return OPCODE_DECODE_SETFLAG ( val, 21 ); } override public bool get_Multiply_IsSigned ( uint op ) { return OPCODE_DECODE_CHECKFLAG( op , 22 ); } override public uint set_Multiply_IsSigned ( bool val ) { return OPCODE_DECODE_SETFLAG ( val, 22 ); } //--// override public bool get_StatusRegister_IsSPSR( uint op ) { return OPCODE_DECODE_CHECKFLAG( op , 22 ); } override public uint set_StatusRegister_IsSPSR( bool val ) { return OPCODE_DECODE_SETFLAG ( val, 22 ); } override public uint get_StatusRegister_Fields( uint op ) { return OPCODE_DECODE_EXTRACTFIELD( op , 16, 4 ); } override public uint set_StatusRegister_Fields( uint val ) { return OPCODE_DECODE_INSERTFIELD ( val, 16, 4 ); } //--// override public uint get_Shift_Type ( uint op ) { return OPCODE_DECODE_EXTRACTFIELD( op , 5, 2 ); } override public uint set_Shift_Type ( uint val ) { return OPCODE_DECODE_INSERTFIELD ( val, 5, 2 ); } override public uint get_Shift_Immediate( uint op ) { return OPCODE_DECODE_EXTRACTFIELD( op , 7, 5 ); } override public uint set_Shift_Immediate( uint val ) { return OPCODE_DECODE_INSERTFIELD ( val, 7, 5 ); } override public uint get_Shift_Register ( uint op ) { return OPCODE_DECODE_EXTRACTFIELD( op , 8, 4 ); } override public uint set_Shift_Register ( uint val ) { return OPCODE_DECODE_INSERTFIELD ( val, 8, 4 ); } //--// override public uint get_DataProcessing_Operation( uint op ) { return OPCODE_DECODE_EXTRACTFIELD( op , 21, 4 ); } override public uint set_DataProcessing_Operation( uint val ) { return OPCODE_DECODE_INSERTFIELD ( val, 21, 4 ); } override public uint get_DataProcessing_ImmediateSeed ( uint op ) { return OPCODE_DECODE_EXTRACTFIELD( op , 0, 8 ); } override public uint set_DataProcessing_ImmediateSeed ( uint val ) { return OPCODE_DECODE_INSERTFIELD ( val, 0, 8 ); } override public uint get_DataProcessing_ImmediateRotation( uint op ) { return OPCODE_DECODE_EXTRACTFIELD( op , 8, 4 ); } override public uint set_DataProcessing_ImmediateRotation( uint val ) { return OPCODE_DECODE_INSERTFIELD ( val, 8, 4 ); } override public uint get_DataProcessing_ImmediateValue( uint op ) { return get_DataProcessing_ImmediateValue( get_DataProcessing_ImmediateSeed( op ), get_DataProcessing_ImmediateRotation( op ) ); } override public uint get_DataProcessing_ImmediateValue( uint imm, uint rot ) { rot *= 2; return (imm >> (int)rot) | (imm << (int)(32 - rot)); } override public bool check_DataProcessing_ImmediateValue( uint val, out uint immRes, out uint rotRes ) { uint imm = val; uint rot = 0; while((imm & ~0xFF) != 0) { if(rot == 16) { immRes = 0; rotRes = 0; return false; } imm = (imm << 2) | (imm >> 30); rot++; } immRes = imm; rotRes = rot; return true; } //--// override public bool get_DataTransfer_IsLoad ( uint op ) { return OPCODE_DECODE_CHECKFLAG( op , 20 ); } override public uint set_DataTransfer_IsLoad ( bool val ) { return OPCODE_DECODE_SETFLAG ( val, 20 ); } override public bool get_DataTransfer_ShouldWriteBack( uint op ) { return OPCODE_DECODE_CHECKFLAG( op , 21 ); } override public uint set_DataTransfer_ShouldWriteBack( bool val ) { return OPCODE_DECODE_SETFLAG ( val, 21 ); } override public bool get_DataTransfer_IsByteTransfer ( uint op ) { return OPCODE_DECODE_CHECKFLAG( op , 22 ); } override public uint set_DataTransfer_IsByteTransfer ( bool val ) { return OPCODE_DECODE_SETFLAG ( val, 22 ); } override public bool get_DataTransfer_IsUp ( uint op ) { return OPCODE_DECODE_CHECKFLAG( op , 23 ); } override public uint set_DataTransfer_IsUp ( bool val ) { return OPCODE_DECODE_SETFLAG ( val, 23 ); } override public bool get_DataTransfer_IsPreIndexing ( uint op ) { return OPCODE_DECODE_CHECKFLAG( op , 24 ); } override public uint set_DataTransfer_IsPreIndexing ( bool val ) { return OPCODE_DECODE_SETFLAG ( val, 24 ); } override public uint get_DataTransfer_Offset ( uint op ) { return OPCODE_DECODE_EXTRACTFIELD( op , 0, 12 ); } override public uint set_DataTransfer_Offset ( uint val ) { return OPCODE_DECODE_INSERTFIELD ( val, 0, 12 ); } //--// override public uint get_HalfWordDataTransfer_Kind ( uint op ) { return OPCODE_DECODE_EXTRACTFIELD( op , 5, 2 ) ; } override public uint set_HalfWordDataTransfer_Kind ( uint val ) { return OPCODE_DECODE_INSERTFIELD ( val, 5, 2 ) ; } override public uint get_HalfWordDataTransfer_Offset( uint op ) { return OPCODE_DECODE_EXTRACTFIELD( op , 4, 8, 8, 4 ) | OPCODE_DECODE_EXTRACTFIELD( op , 0, 8, 0, 4 ); } override public uint set_HalfWordDataTransfer_Offset( uint val ) { return OPCODE_DECODE_INSERTFIELD ( val, 4, 8, 8, 4 ) | OPCODE_DECODE_INSERTFIELD ( val, 0, 8, 0, 4 ); } //--// override public bool get_BlockDataTransfer_LoadPSR ( uint op ) { return OPCODE_DECODE_CHECKFLAG( op , 22 ); } override public uint set_BlockDataTransfer_LoadPSR ( bool val ) { return OPCODE_DECODE_SETFLAG ( val, 22 ); } override public uint get_BlockDataTransfer_RegisterList( uint op ) { return OPCODE_DECODE_EXTRACTFIELD( op , 0 , 16 ); } override public uint set_BlockDataTransfer_RegisterList( uint val ) { return OPCODE_DECODE_INSERTFIELD ( val, 0 , 16 ); } //--// override public bool get_Branch_IsLink( uint op ) { return OPCODE_DECODE_CHECKFLAG( op , 24 ); } override public uint set_Branch_IsLink( bool val ) { return OPCODE_DECODE_SETFLAG ( val, 24 ); } override public int get_Branch_Offset( uint op ) { return ((int)(op << 8)) >> 6; } override public uint set_Branch_Offset( int val ) { return OPCODE_DECODE_INSERTFIELD( val >> 2, 0, 24); } //--// override public uint get_Coproc_CpNum( uint op ) { return OPCODE_DECODE_EXTRACTFIELD( op , 8, 4 ); } override public uint set_Coproc_CpNum( uint val ) { return OPCODE_DECODE_INSERTFIELD ( val, 8, 4 ); } //--// override public bool get_CoprocRegisterTransfer_IsMRC( uint op ) { return OPCODE_DECODE_CHECKFLAG( op , 20 ); } override public uint set_CoprocRegisterTransfer_IsMRC( bool val ) { return OPCODE_DECODE_SETFLAG ( val, 20 ); } override public uint get_CoprocRegisterTransfer_Op1 ( uint op ) { return OPCODE_DECODE_EXTRACTFIELD( op , 21, 3 ); } override public uint set_CoprocRegisterTransfer_Op1 ( uint val ) { return OPCODE_DECODE_INSERTFIELD ( val, 21, 3 ); } override public uint get_CoprocRegisterTransfer_Op2 ( uint op ) { return OPCODE_DECODE_EXTRACTFIELD( op , 5, 3 ); } override public uint set_CoprocRegisterTransfer_Op2 ( uint val ) { return OPCODE_DECODE_INSERTFIELD ( val, 5, 3 ); } override public uint get_CoprocRegisterTransfer_CRn ( uint op ) { return OPCODE_DECODE_EXTRACTFIELD( op , 16, 4 ); } override public uint set_CoprocRegisterTransfer_CRn ( uint val ) { return OPCODE_DECODE_INSERTFIELD ( val, 16, 4 ); } override public uint get_CoprocRegisterTransfer_CRm ( uint op ) { return OPCODE_DECODE_EXTRACTFIELD( op , 0, 4 ); } override public uint set_CoprocRegisterTransfer_CRm ( uint val ) { return OPCODE_DECODE_INSERTFIELD ( val, 0, 4 ); } override public uint get_CoprocRegisterTransfer_Rd ( uint op ) { return OPCODE_DECODE_EXTRACTFIELD( op , 12, 4 ); } override public uint set_CoprocRegisterTransfer_Rd ( uint val ) { return OPCODE_DECODE_INSERTFIELD ( val, 12, 4 ); } //--// override public bool get_CoprocDataTransfer_IsLoad ( uint op ) { return OPCODE_DECODE_CHECKFLAG( op , 20 ); } override public uint set_CoprocDataTransfer_IsLoad ( bool val ) { return OPCODE_DECODE_SETFLAG ( val, 20 ); } override public bool get_CoprocDataTransfer_ShouldWriteBack( uint op ) { return OPCODE_DECODE_CHECKFLAG( op , 21 ); } override public uint set_CoprocDataTransfer_ShouldWriteBack( bool val ) { return OPCODE_DECODE_SETFLAG ( val, 21 ); } override public bool get_CoprocDataTransfer_IsWide ( uint op ) { return OPCODE_DECODE_CHECKFLAG( op , 22 ); } override public uint set_CoprocDataTransfer_IsWide ( bool val ) { return OPCODE_DECODE_SETFLAG ( val, 22 ); } override public bool get_CoprocDataTransfer_IsUp ( uint op ) { return OPCODE_DECODE_CHECKFLAG( op , 23 ); } override public uint set_CoprocDataTransfer_IsUp ( bool val ) { return OPCODE_DECODE_SETFLAG ( val, 23 ); } override public bool get_CoprocDataTransfer_IsPreIndexing ( uint op ) { return OPCODE_DECODE_CHECKFLAG( op , 24 ); } override public uint set_CoprocDataTransfer_IsPreIndexing ( bool val ) { return OPCODE_DECODE_SETFLAG ( val, 24 ); } override public uint get_CoprocDataTransfer_Rn ( uint op ) { return OPCODE_DECODE_EXTRACTFIELD( op , 16, 4 ); } override public uint set_CoprocDataTransfer_Rn ( uint val ) { return OPCODE_DECODE_INSERTFIELD ( val, 16, 4 ); } override public uint get_CoprocDataTransfer_CRd ( uint op ) { return OPCODE_DECODE_EXTRACTFIELD( op , 12, 4 ); } override public uint set_CoprocDataTransfer_CRd ( uint val ) { return OPCODE_DECODE_INSERTFIELD ( val, 12, 4 ); } override public uint get_CoprocDataTransfer_Offset ( uint op ) { return OPCODE_DECODE_EXTRACTFIELD( op , 0, 8 ); } override public uint set_CoprocDataTransfer_Offset ( uint val ) { return OPCODE_DECODE_INSERTFIELD ( val, 0, 8 ); } //--// override public uint get_CoprocDataOperation_Op1 ( uint op ) { return OPCODE_DECODE_EXTRACTFIELD( op , 20, 4 ); } override public uint set_CoprocDataOperation_Op1 ( uint val ) { return OPCODE_DECODE_INSERTFIELD ( val, 20, 4 ); } override public uint get_CoprocDataOperation_Op2 ( uint op ) { return OPCODE_DECODE_EXTRACTFIELD( op , 5, 3 ); } override public uint set_CoprocDataOperation_Op2 ( uint val ) { return OPCODE_DECODE_INSERTFIELD ( val, 5, 3 ); } override public uint get_CoprocDataOperation_CRn ( uint op ) { return OPCODE_DECODE_EXTRACTFIELD( op , 16, 4 ); } override public uint set_CoprocDataOperation_CRn ( uint val ) { return OPCODE_DECODE_INSERTFIELD ( val, 16, 4 ); } override public uint get_CoprocDataOperation_CRm ( uint op ) { return OPCODE_DECODE_EXTRACTFIELD( op , 0, 4 ); } override public uint set_CoprocDataOperation_CRm ( uint val ) { return OPCODE_DECODE_INSERTFIELD ( val, 0, 4 ); } override public uint get_CoprocDataOperation_CRd ( uint op ) { return OPCODE_DECODE_EXTRACTFIELD( op , 12, 4 ); } override public uint set_CoprocDataOperation_CRd ( uint val ) { return OPCODE_DECODE_INSERTFIELD ( val, 12, 4 ); } //--// override public uint get_SoftwareInterrupt_Immediate( uint op ) { return OPCODE_DECODE_EXTRACTFIELD( op , 0, 24 ); } override public uint set_SoftwareInterrupt_Immediate( uint val ) { return OPCODE_DECODE_INSERTFIELD ( val, 0, 24 ); } //--// override public uint get_Breakpoint_Immediate( uint op ) { return OPCODE_DECODE_EXTRACTFIELD( op , 4, 16, 8, 12 ) | OPCODE_DECODE_EXTRACTFIELD( op , 0, 16, 0, 4 ); } override public uint set_Breakpoint_Immediate( uint val ) { return OPCODE_DECODE_INSERTFIELD ( val, 4, 16, 8, 12 ) | OPCODE_DECODE_INSERTFIELD ( val, 0, 16, 0, 4 ); } } } ================================================ FILE: Zelig/Zelig/CompileTime/TargetModels/ArmProcessor/ARM/EncodingDefinition_VFP_ARM.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // namespace Microsoft.Zelig.TargetModel.ArmProcessor { public class EncodingDefinition_VFP_ARM : EncodingDefinition_VFP { //--// override public uint get_Rn( uint op ) { return EncodingDefinition_ARM.OPCODE_DECODE_EXTRACTFIELD( op , 16, 4 ); } override public uint set_Rn( uint val ) { return EncodingDefinition_ARM.OPCODE_DECODE_INSERTFIELD ( val, 16, 4 ); } override public uint get_SysReg( uint op ) { return EncodingDefinition_ARM.OPCODE_DECODE_EXTRACTFIELD( op , 16, 4 ); } override public uint set_SysReg( uint val ) { return EncodingDefinition_ARM.OPCODE_DECODE_INSERTFIELD ( val, 16, 4 ); } override public uint get_Fn( uint op ) { return EncodingDefinition_ARM.OPCODE_DECODE_EXTRACTFIELD( op , 1, 5, 16, 4 ) | EncodingDefinition_ARM.OPCODE_DECODE_EXTRACTFIELD( op , 0, 5, 7, 1 ); } override public uint set_Fn( uint val ) { return EncodingDefinition_ARM.OPCODE_DECODE_INSERTFIELD ( val, 1, 5, 16, 4 ) | EncodingDefinition_ARM.OPCODE_DECODE_INSERTFIELD ( val, 0, 5, 7, 1 ); } override public uint get_Rd( uint op ) { return EncodingDefinition_ARM.OPCODE_DECODE_EXTRACTFIELD( op , 12, 4 ); } override public uint set_Rd( uint val ) { return EncodingDefinition_ARM.OPCODE_DECODE_INSERTFIELD ( val, 12, 4 ); } override public uint get_Fd( uint op ) { return EncodingDefinition_ARM.OPCODE_DECODE_EXTRACTFIELD( op , 1, 5, 12, 4 ) | EncodingDefinition_ARM.OPCODE_DECODE_EXTRACTFIELD( op , 0, 5, 22, 1 ); } override public uint set_Fd( uint val ) { return EncodingDefinition_ARM.OPCODE_DECODE_INSERTFIELD ( val, 1, 5, 12, 4 ) | EncodingDefinition_ARM.OPCODE_DECODE_INSERTFIELD ( val, 0, 5, 22, 1 ); } override public uint get_Fm( uint op ) { return EncodingDefinition_ARM.OPCODE_DECODE_EXTRACTFIELD( op , 1, 5, 0, 4 ) | EncodingDefinition_ARM.OPCODE_DECODE_EXTRACTFIELD( op , 0, 5, 5, 1 ); } override public uint set_Fm( uint val ) { return EncodingDefinition_ARM.OPCODE_DECODE_INSERTFIELD ( val, 1, 5, 0, 4 ) | EncodingDefinition_ARM.OPCODE_DECODE_INSERTFIELD ( val, 0, 5, 5, 1 ); } override public bool get_IsDouble( uint op ) { return EncodingDefinition_ARM.OPCODE_DECODE_CHECKFLAG( op , 8 ); } override public uint set_IsDouble( bool val ) { return EncodingDefinition_ARM.OPCODE_DECODE_SETFLAG ( val, 8 ); } override public bool get_CheckNaN( uint op ) { return EncodingDefinition_ARM.OPCODE_DECODE_CHECKFLAG( op , 7 ); } override public uint set_CheckNaN( bool val ) { return EncodingDefinition_ARM.OPCODE_DECODE_SETFLAG ( val, 7 ); } //--// override public uint get_BinaryOperation( uint op ) { return EncodingDefinition_ARM.OPCODE_DECODE_EXTRACTFIELD( op , 3, 4, 23, 1 ) | EncodingDefinition_ARM.OPCODE_DECODE_EXTRACTFIELD( op , 1, 4, 20, 2 ) | EncodingDefinition_ARM.OPCODE_DECODE_EXTRACTFIELD( op , 0, 4, 6, 1 ); } override public uint set_BinaryOperation( uint val ) { return EncodingDefinition_ARM.OPCODE_DECODE_INSERTFIELD ( val, 3, 4, 23, 1 ) | EncodingDefinition_ARM.OPCODE_DECODE_INSERTFIELD ( val, 1, 4, 20, 2 ) | EncodingDefinition_ARM.OPCODE_DECODE_INSERTFIELD ( val, 0, 4, 6, 1 ); } //--// override public uint get_UnaryOperation( uint op ) { return EncodingDefinition_ARM.OPCODE_DECODE_EXTRACTFIELD( op , 1, 5, 16, 4 ) | EncodingDefinition_ARM.OPCODE_DECODE_EXTRACTFIELD( op , 0, 5, 7, 1 ); } override public uint set_UnaryOperation( uint val ) { return EncodingDefinition_ARM.OPCODE_DECODE_INSERTFIELD ( val, 1, 5, 16, 4 ) | EncodingDefinition_ARM.OPCODE_DECODE_INSERTFIELD ( val, 0, 5, 7, 1 ); } //-// override public bool get_RegisterTransfer_IsFromCoproc( uint op ) { return EncodingDefinition_ARM.OPCODE_DECODE_CHECKFLAG( op , 20 ); } override public uint set_RegisterTransfer_IsFromCoproc( bool val ) { return EncodingDefinition_ARM.OPCODE_DECODE_SETFLAG ( val, 20 ); } //--// override public bool get_DataTransfer_IsLoad ( uint op ) { return EncodingDefinition_ARM.OPCODE_DECODE_CHECKFLAG( op , 20 ); } override public uint set_DataTransfer_IsLoad ( bool val ) { return EncodingDefinition_ARM.OPCODE_DECODE_SETFLAG ( val, 20 ); } override public bool get_DataTransfer_ShouldWriteBack( uint op ) { return EncodingDefinition_ARM.OPCODE_DECODE_CHECKFLAG( op , 21 ); } override public uint set_DataTransfer_ShouldWriteBack( bool val ) { return EncodingDefinition_ARM.OPCODE_DECODE_SETFLAG ( val, 21 ); } override public bool get_DataTransfer_IsUp ( uint op ) { return EncodingDefinition_ARM.OPCODE_DECODE_CHECKFLAG( op , 23 ); } override public uint set_DataTransfer_IsUp ( bool val ) { return EncodingDefinition_ARM.OPCODE_DECODE_SETFLAG ( val, 23 ); } override public bool get_DataTransfer_IsPreIndexing ( uint op ) { return EncodingDefinition_ARM.OPCODE_DECODE_CHECKFLAG( op , 24 ); } override public uint set_DataTransfer_IsPreIndexing ( bool val ) { return EncodingDefinition_ARM.OPCODE_DECODE_SETFLAG ( val, 24 ); } override public uint get_DataTransfer_Offset ( uint op ) { return EncodingDefinition_ARM.OPCODE_DECODE_EXTRACTFIELD( op , 0, 8 ); } override public uint set_DataTransfer_Offset ( uint val ) { return EncodingDefinition_ARM.OPCODE_DECODE_INSERTFIELD ( val, 0, 8 ); } } } ================================================ FILE: Zelig/Zelig/CompileTime/TargetModels/ArmProcessor/ArmProcessor.csproj ================================================  Debug AnyCPU 9.0.21022 2.0 {186F31A3-EF89-4A25-B2D5-20070519AA01} Library Properties Microsoft.Zelig.TargetModel.ArmProcessor Microsoft.Zelig.TargetModel.ArmProcessor $(LlilumBuildRoot)\Host\obj\$(MSBuildProjectName)\ v4.5 true full false $(LlilumBuildRoot)\Host\bin\$(Configuration)\ DEBUG;TRACE prompt 4 true AllRules.ruleset AnyCPU false pdbonly true $(LlilumBuildRoot)\Host\bin\$(Configuration)\ TRACE prompt 4 true AllRules.ruleset AnyCPU false $(LlilumBuildRoot)\Host\bin\$(Configuration)\ TRACE;DEBUG AnyCPU true false 3.5 ================================================ FILE: Zelig/Zelig/CompileTime/TargetModels/ArmProcessor/CurrentInstructionSetEncoding.cs ================================================ using System; namespace Microsoft.Zelig.TargetModel.ArmProcessor { public class CurrentInstructionSetEncoding { // // Singleton // private static EncodingDefinition s_CurrentEncoding; private static EncodingDefinition_VFP s_CurrentEncodingVFP; private static object s_sync = new object(); protected CurrentInstructionSetEncoding() { } //--// public static void RegisterCurrentEncoding( InstructionSetVersion isv ) { lock(s_sync) { if(s_CurrentEncoding != null) { throw new InvalidOperationException("Cannot change encoding"); } EncodingDefinition_ARM enc = null; switch(isv.PlatformVersion) { case InstructionSetVersion.Platform_Version__ARMv4: case InstructionSetVersion.Platform_Version__ARMv5: enc = new EncodingDefinition_ARM(); break; case InstructionSetVersion.Platform_Version__ARMv6M: case InstructionSetVersion.Platform_Version__ARMv7M: case InstructionSetVersion.Platform_Version__ARMv7R: case InstructionSetVersion.Platform_Version__ARMv7A: default: throw new ArgumentException("Cannot register unsupported instruction set"); } EncodingDefinition_VFP encVFP = null; switch(isv.PlatformVFPSupport) { case InstructionSetVersion.Platform_VFP__HardVFP: encVFP = new EncodingDefinition_VFP_ARM(); break; case InstructionSetVersion.Platform_VFP__SoftVFP: case InstructionSetVersion.Platform_VFP__NoVFP: break; default: throw new ArgumentException("Cannot register unsupported instruction set"); } s_CurrentEncoding = enc; s_CurrentEncodingVFP = encVFP; } } public static EncodingDefinition GetEncoding() { if(s_CurrentEncoding == null) { s_CurrentEncoding = new EncodingDefinition_ARM(); //throw new InvalidOperationException("Instruction set encoding is unknown"); } return s_CurrentEncoding; } public static EncodingDefinition_VFP GetVFPEncoding() { return s_CurrentEncodingVFP; } } } ================================================ FILE: Zelig/Zelig/CompileTime/TargetModels/ArmProcessor/EncodingDefinition.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // namespace Microsoft.Zelig.TargetModel.ArmProcessor { abstract public class EncodingDefinition { public const int c_PC_offset = 8; //--// ///////////////////////////////////////// //--// ///////////////////////////////////////// public const uint c_register_r0 = 0; // public const uint c_register_r1 = 1; // public const uint c_register_r2 = 2; // public const uint c_register_r3 = 3; // public const uint c_register_r4 = 4; // public const uint c_register_r5 = 5; // public const uint c_register_r6 = 6; // public const uint c_register_r7 = 7; // public const uint c_register_r8 = 8; // public const uint c_register_r9 = 9; // public const uint c_register_r10 = 10; // public const uint c_register_r11 = 11; // public const uint c_register_r12 = 12; // public const uint c_register_r13 = 13; // public const uint c_register_r14 = 14; // public const uint c_register_r15 = 15; // public const uint c_register_sp = 13; // public const uint c_register_lr = 14; // public const uint c_register_pc = 15; // ///////////////////////////////////////// ////////////////////////////////////////// public const uint c_register_lst_r0 = 1U << (int)c_register_r0 ; public const uint c_register_lst_r1 = 1U << (int)c_register_r1 ; public const uint c_register_lst_r2 = 1U << (int)c_register_r2 ; public const uint c_register_lst_r3 = 1U << (int)c_register_r3 ; public const uint c_register_lst_r4 = 1U << (int)c_register_r4 ; public const uint c_register_lst_r5 = 1U << (int)c_register_r5 ; public const uint c_register_lst_r6 = 1U << (int)c_register_r6 ; public const uint c_register_lst_r7 = 1U << (int)c_register_r7 ; public const uint c_register_lst_r8 = 1U << (int)c_register_r8 ; public const uint c_register_lst_r9 = 1U << (int)c_register_r9 ; public const uint c_register_lst_r10 = 1U << (int)c_register_r10; public const uint c_register_lst_r11 = 1U << (int)c_register_r11; public const uint c_register_lst_r12 = 1U << (int)c_register_r12; public const uint c_register_lst_r13 = 1U << (int)c_register_r13; public const uint c_register_lst_r14 = 1U << (int)c_register_r14; public const uint c_register_lst_r15 = 1U << (int)c_register_r15; public const uint c_register_lst_sp = 1U << (int)c_register_sp ; public const uint c_register_lst_lr = 1U << (int)c_register_lr ; public const uint c_register_lst_pc = 1U << (int)c_register_pc ; //--// public enum Format { MRS , MSR_1 , MSR_2 , DataProcessing_1 , DataProcessing_2 , DataProcessing_3 , Multiply , MultiplyLong , SingleDataSwap , BranchAndExchange , HalfwordDataTransfer_1 , HalfwordDataTransfer_2 , SingleDataTransfer_1 , SingleDataTransfer_2 , SingleDataTransfer_3 , Undefined , BlockDataTransfer , Branch , CoprocDataTransfer , CoprocDataOperation , CoprocRegisterTransfer , SoftwareInterrupt , FIRST_FORMAT = MRS, LAST_FORMAT = SoftwareInterrupt, NUM_OF_FORMATS = (SoftwareInterrupt - MRS + 1) }; //--// [System.Diagnostics.Conditional( "DEBUG" )] static void OPCODE_VERIFY_INSERT_FIELD( int val , int bitLen ) { int valHigh = val >> bitLen; if(valHigh != 0 && valHigh != -1 ) { throw new System.ArgumentException( string.Format( "Found value outside bounds of field [{0}:{1}]: {2}", -(1 << (bitLen-1)), (1 << (bitLen-1)), val ) ); } } [System.Diagnostics.Conditional( "DEBUG" )] static void OPCODE_VERIFY_INSERT_FIELD( uint val , int bitLen ) { uint valHigh = val >> bitLen; if(valHigh != 0) { throw new System.ArgumentException( string.Format( "Found value outside bounds of field [{0}:{1}]: {2}", 0, (1 << bitLen) - 1, val ) ); } } [System.Diagnostics.Conditional( "DEBUG" )] static void OPCODE_VERIFY_INSERT_FIELD( uint val , int valPos , int valLen , int bitLen ) { uint valHigh = val >> valLen; if(valHigh != 0) { throw new System.ArgumentException( string.Format( "Found value outside bounds of field [{0}:{1}]: {2}", 0, (1 << bitLen) - 1, val ) ); } } //--// static public uint OPCODE_DECODE_MASK( int len ) { return (1U << len) - 1U; } static public uint OPCODE_DECODE_INSERTFIELD( int val , int bitPos , int bitLen ) { OPCODE_VERIFY_INSERT_FIELD( val, bitLen ); return ((uint)val & OPCODE_DECODE_MASK( bitLen )) << bitPos; } static public uint OPCODE_DECODE_INSERTFIELD( uint val , int bitPos , int bitLen ) { OPCODE_VERIFY_INSERT_FIELD( val, bitLen ); return (val & OPCODE_DECODE_MASK( bitLen )) << bitPos; } static public uint OPCODE_DECODE_INSERTFIELD( uint val , int valPos , int valLen , int bitPos , int bitLen ) { OPCODE_VERIFY_INSERT_FIELD( val, valPos, valLen, bitLen ); return ((val >> valPos) & EncodingDefinition_ARM.OPCODE_DECODE_MASK( bitLen )) << bitPos; } static public uint OPCODE_DECODE_EXTRACTFIELD( uint op , int bitPos , int bitLen ) { return (op >> bitPos) & OPCODE_DECODE_MASK( bitLen ); } static public uint OPCODE_DECODE_EXTRACTFIELD( uint op , int valPos , int valLen , int bitPos , int bitLen ) { return ((op >> bitPos) & EncodingDefinition_ARM.OPCODE_DECODE_MASK( bitLen )) << valPos; } //--// static public uint OPCODE_DECODE_SETFLAG( bool val , int bitPos ) { return val ? (1U << bitPos) : 0U; } static public bool OPCODE_DECODE_CHECKFLAG( uint op , int bitPos ) { return (op & (1U << bitPos)) != 0; } //--// abstract public uint get_ConditionCodes ( uint op ); abstract public uint set_ConditionCodes ( uint val ); abstract public bool get_ShouldSetConditions( uint op ); abstract public uint set_ShouldSetConditions( bool val ); //--// abstract public uint get_Register1( uint op ); abstract public uint set_Register1( uint val ); abstract public uint get_Register2( uint op ); abstract public uint set_Register2( uint val ); abstract public uint get_Register3( uint op ); abstract public uint set_Register3( uint val ); abstract public uint get_Register4( uint op ); abstract public uint set_Register4( uint val ); //--// abstract public bool get_Multiply_IsAccumulate( uint op ); abstract public uint set_Multiply_IsAccumulate( bool val ); abstract public bool get_Multiply_IsSigned ( uint op ); abstract public uint set_Multiply_IsSigned ( bool val ); //--// abstract public bool get_StatusRegister_IsSPSR( uint op ); abstract public uint set_StatusRegister_IsSPSR( bool val ); abstract public uint get_StatusRegister_Fields( uint op ); abstract public uint set_StatusRegister_Fields( uint val ); //--// abstract public uint get_Shift_Type ( uint op ); abstract public uint set_Shift_Type ( uint val ); abstract public uint get_Shift_Immediate( uint op ); abstract public uint set_Shift_Immediate( uint val ); abstract public uint get_Shift_Register ( uint op ); abstract public uint set_Shift_Register ( uint val ); //--// abstract public uint get_DataProcessing_Operation( uint op ); abstract public uint set_DataProcessing_Operation( uint val ); abstract public uint get_DataProcessing_ImmediateSeed ( uint op ); abstract public uint set_DataProcessing_ImmediateSeed ( uint val ); abstract public uint get_DataProcessing_ImmediateRotation( uint op ); abstract public uint set_DataProcessing_ImmediateRotation( uint val ); abstract public uint get_DataProcessing_ImmediateValue( uint op ); abstract public uint get_DataProcessing_ImmediateValue( uint imm, uint rot ); abstract public bool check_DataProcessing_ImmediateValue( uint val, out uint immRes, out uint rotRes ); //--// abstract public bool get_DataTransfer_IsLoad ( uint op ); abstract public uint set_DataTransfer_IsLoad ( bool val ); abstract public bool get_DataTransfer_ShouldWriteBack( uint op ); abstract public uint set_DataTransfer_ShouldWriteBack( bool val ); abstract public bool get_DataTransfer_IsByteTransfer ( uint op ); abstract public uint set_DataTransfer_IsByteTransfer ( bool val ); abstract public bool get_DataTransfer_IsUp ( uint op ); abstract public uint set_DataTransfer_IsUp ( bool val ); abstract public bool get_DataTransfer_IsPreIndexing ( uint op ); abstract public uint set_DataTransfer_IsPreIndexing ( bool val ); abstract public uint get_DataTransfer_Offset ( uint op ); abstract public uint set_DataTransfer_Offset ( uint val ); //--// abstract public uint get_HalfWordDataTransfer_Kind ( uint op ); abstract public uint set_HalfWordDataTransfer_Kind ( uint val ); abstract public uint get_HalfWordDataTransfer_Offset( uint op ); abstract public uint set_HalfWordDataTransfer_Offset( uint val ); //--// abstract public bool get_BlockDataTransfer_LoadPSR ( uint op ); abstract public uint set_BlockDataTransfer_LoadPSR ( bool val ); abstract public uint get_BlockDataTransfer_RegisterList( uint op ); abstract public uint set_BlockDataTransfer_RegisterList( uint val ); //--// abstract public bool get_Branch_IsLink( uint op ); abstract public uint set_Branch_IsLink( bool val ); abstract public int get_Branch_Offset( uint op ); abstract public uint set_Branch_Offset( int val ); //--// abstract public uint get_Coproc_CpNum( uint op ); abstract public uint set_Coproc_CpNum( uint val ); //--// abstract public bool get_CoprocRegisterTransfer_IsMRC( uint op ); abstract public uint set_CoprocRegisterTransfer_IsMRC( bool val ); abstract public uint get_CoprocRegisterTransfer_Op1 ( uint op ); abstract public uint set_CoprocRegisterTransfer_Op1 ( uint val ); abstract public uint get_CoprocRegisterTransfer_Op2 ( uint op ); abstract public uint set_CoprocRegisterTransfer_Op2 ( uint val ); abstract public uint get_CoprocRegisterTransfer_CRn ( uint op ); abstract public uint set_CoprocRegisterTransfer_CRn ( uint val ); abstract public uint get_CoprocRegisterTransfer_CRm ( uint op ); abstract public uint set_CoprocRegisterTransfer_CRm ( uint val ); abstract public uint get_CoprocRegisterTransfer_Rd ( uint op ); abstract public uint set_CoprocRegisterTransfer_Rd ( uint val ); //--// abstract public bool get_CoprocDataTransfer_IsLoad ( uint op ); abstract public uint set_CoprocDataTransfer_IsLoad ( bool val ); abstract public bool get_CoprocDataTransfer_ShouldWriteBack( uint op ); abstract public uint set_CoprocDataTransfer_ShouldWriteBack( bool val ); abstract public bool get_CoprocDataTransfer_IsWide ( uint op ); abstract public uint set_CoprocDataTransfer_IsWide ( bool val ); abstract public bool get_CoprocDataTransfer_IsUp ( uint op ); abstract public uint set_CoprocDataTransfer_IsUp ( bool val ); abstract public bool get_CoprocDataTransfer_IsPreIndexing ( uint op ); abstract public uint set_CoprocDataTransfer_IsPreIndexing ( bool val ); abstract public uint get_CoprocDataTransfer_Rn ( uint op ); abstract public uint set_CoprocDataTransfer_Rn ( uint val ); abstract public uint get_CoprocDataTransfer_CRd ( uint op ); abstract public uint set_CoprocDataTransfer_CRd ( uint val ); abstract public uint get_CoprocDataTransfer_Offset ( uint op ); abstract public uint set_CoprocDataTransfer_Offset ( uint val ); //--// abstract public uint get_CoprocDataOperation_Op1 ( uint op ); abstract public uint set_CoprocDataOperation_Op1 ( uint val ); abstract public uint get_CoprocDataOperation_Op2 ( uint op ); abstract public uint set_CoprocDataOperation_Op2 ( uint val ); abstract public uint get_CoprocDataOperation_CRn ( uint op ); abstract public uint set_CoprocDataOperation_CRn ( uint val ); abstract public uint get_CoprocDataOperation_CRm ( uint op ); abstract public uint set_CoprocDataOperation_CRm ( uint val ); abstract public uint get_CoprocDataOperation_CRd ( uint op ); abstract public uint set_CoprocDataOperation_CRd ( uint val ); //--// abstract public uint get_SoftwareInterrupt_Immediate( uint op ); abstract public uint set_SoftwareInterrupt_Immediate( uint val ); //--// abstract public uint get_Breakpoint_Immediate( uint op ); abstract public uint set_Breakpoint_Immediate( uint val ); } } ================================================ FILE: Zelig/Zelig/CompileTime/TargetModels/ArmProcessor/EncodingDefinition_VFP.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // namespace Microsoft.Zelig.TargetModel.ArmProcessor { public abstract class EncodingDefinition_VFP { // // +---------+-------+---+----+---+-----+---------+---------+---------+----+----+---+---+---------+ // | 3 3 2 2 | 2 2 2 | 2 | 2 | 2 | 2 2 | 1 1 1 1 | 1 1 1 1 | 1 1 9 8 | 7 | 6 | 5 | 4 | 3 2 1 0 | // | 1 0 9 8 | 7 6 5 | 4 | 3 | 2 | 1 0 | 9 8 7 6 | 5 4 3 2 | 1 0 | | | | | | // +---------+-----------+----+---+-----+---------+---------+---------+----+----+---+---+---------+ // | Cond | 1 1 1 0 | Op | D | Op | Fn | Fd | 1 0 1 0 | N | Op | M | 0 | Fm | Addressing Mode 1 - Single-precision vectors (binary) // +---------+-----------+----+---+-----+---------+---------+---------+----+----+---+---+---------+ // | Cond | 1 1 1 0 | Op | 0 | Op | Dn | Dd | 1 0 1 1 | 0 | Op | 0 | 0 | Dm | Addressing Mode 2 - Double-precision vectors (binary) // +---------+-----------+----+---+-----+---------+---------+---------+----+----+---+---+---------+ // | Cond | 1 1 1 0 1 | D | 1 1 | Op | Fd | 1 0 1 0 | Op | 1 | M | 0 | Fm | Addressing Mode 3 - Single-precision vectors (unary) // +---------+----------------+---+-----+---------+---------+---------+----+----+---+---+---------+ // | Cond | 1 1 1 0 1 | 0 | 1 1 | Op | Dd | 1 0 1 1 | Op | 1 | 0 | 0 | Dm | Addressing Mode 4 - Double-precision vectors (unary) // +---------+-------+---+----+---+-----+---------+---------+---------+----+----+---+---+---------+ // | Cond | 1 1 0 | P | U | D | W L | Rn | Fd | 1 0 1 0 | Offset | Addressing Mode 5 - VFP load/store multiple // +---------+-------+---+----+---+-----+---------+---------+---------+----+----+---+---+---------+ // | Cond | 1 1 0 | P | U | 0 | W L | Rn | Dd | 1 0 1 1 | Offset | Addressing Mode 5 - VFP load/store multiple // +---------+-------+---+----+---+-----+---------+---------+---------+----+----+---+---+---------+ // // 31 28 27 26 25 24 23 22 21 20 19 18 17 16 15 12 11 10 9 8 7 6 5 4 3 0 // +------+---------------+---+------+------------+------+-----------+---+---+---+---+----+ // | cond | 1 1 0 1 U | 0 | 0 L | Rn | Dd | 1 0 1 1 | offset | FSTD/FLDD Coprocessor Data Transfer // +------+---------------+---+------+------------+------+-----------+---+---+---+---+----+ // +------+---------------+---+------+------------+------+-----------+---+---+---+---+----+ // | cond | 1 1 0 P U | 0 | W L | Rn | Dd | 1 0 1 1 | offset | FSTMD/FLDMD Coprocessor Data Transfer // +------+---------------+---+------+------------+------+-----------+---+---+---+---+----+ // +------+---------------+---+------+------------+------+-----------+---+---+---+---+----+ // | cond | 1 1 0 0 0 | 1 | 0 Dr| Rn | Rd | 1 0 1 1 | 0 | 0 | 0 | 1 | Dm | FMDRR/FMRRD Coprocessor Data Transfer // +------+---------------+---+------+------------+------+-----------+---+---+---+---+----+ // | cond | 1 1 1 0 0 | 0 | 0 Dr| Dn | Rd | 1 0 1 1 | 0 | 0 | 0 | 1 | 0 | FMDLR/FMRDL Coprocessor Register Transfer // +------+---------------+---+------+------------+------+-----------+---+---+---+---+----+ // | cond | 1 1 1 0 0 | 0 | 1 Dr| Dn | Rd | 1 0 1 1 | 0 | 0 | 0 | 1 | 0 | FMDHR/FMRDH Coprocessor Register Transfer // +------+---------------+---+------+------------+------+-----------+---+---+---+---+----+ // +------+---------------+---+------+------------+------+-----------+---+---+---+---+----+ // | cond | 1 1 1 0 0 | 0 | 0 0 | Dn | Dd | 1 0 1 1 | 0 | 0 | 0 | 0 | Dm | FMACD Coprocessor Data Operation // +------+---------------+---+------+------------+------+-----------+---+---+---+---+----+ // | cond | 1 1 1 0 0 | 0 | 0 0 | Dn | Dd | 1 0 1 1 | 0 | 1 | 0 | 0 | Dm | FNMACD Coprocessor Data Operation // +------+---------------+---+------+------------+------+-----------+---+---+---+---+----+ // | cond | 1 1 1 0 0 | 0 | 0 1 | Dn | Dd | 1 0 1 1 | 0 | 0 | 0 | 0 | Dm | FMSCD Coprocessor Data Operation // +------+---------------+---+------+------------+------+-----------+---+---+---+---+----+ // | cond | 1 1 1 0 0 | 0 | 0 1 | Dn | Dd | 1 0 1 1 | 0 | 1 | 0 | 0 | Dm | FNMSCD Coprocessor Data Operation // +------+---------------+---+------+------------+------+-----------+---+---+---+---+----+ // | cond | 1 1 1 0 0 | 0 | 1 0 | Dn | Dd | 1 0 1 1 | 0 | 0 | 0 | 0 | Dm | FMULD Coprocessor Data Operation // +------+---------------+---+------+------------+------+-----------+---+---+---+---+----+ // | cond | 1 1 1 0 0 | 0 | 1 0 | Dn | Dd | 1 0 1 1 | 0 | 1 | 0 | 0 | Dm | FNMULD Coprocessor Data Operation // +------+---------------+---+------+------------+------+-----------+---+---+---+---+----+ // | cond | 1 1 1 0 0 | 0 | 1 1 | Dn | Dd | 1 0 1 1 | 0 | 0 | 0 | 0 | Dm | FADDD Coprocessor Data Operation // +------+---------------+---+------+------------+------+-----------+---+---+---+---+----+ // | cond | 1 1 1 0 0 | 0 | 1 1 | Dn | Dd | 1 0 1 1 | 0 | 1 | 0 | 0 | Dm | FSUBD Coprocessor Data Operation // +------+---------------+---+------+------------+------+-----------+---+---+---+---+----+ // | cond | 1 1 1 0 1 | 0 | 0 0 | Dn | Dd | 1 0 1 1 | 0 | 0 | 0 | 0 | Dm | FDIVD Coprocessor Data Operation // +------+---------------+---+------+------------+------+-----------+---+---+---+---+----+ // +------+---------------+---+------+------------+------+-----------+---+---+---+---+----+ // | cond | 1 1 1 0 1 | 0 | 1 1 | 0 0 0 0 | Dd | 1 0 1 1 | 0 | 1 | 0 | 0 | Dm | FCPYD Coprocessor Data Operation // +------+---------------+---+------+------------+------+-----------+---+---+---+---+----+ // | cond | 1 1 1 0 1 | 0 | 1 1 | 0 0 0 0 | Dd | 1 0 1 1 | 1 | 1 | 0 | 0 | Dm | FABSD Coprocessor Data Operation // +------+---------------+---+------+------------+------+-----------+---+---+---+---+----+ // | cond | 1 1 1 0 1 | 0 | 1 1 | 0 0 0 1 | Dd | 1 0 1 1 | 0 | 1 | 0 | 0 | Dm | FNEGD Coprocessor Data Operation // +------+---------------+---+------+------------+------+-----------+---+---+---+---+----+ // | cond | 1 1 1 0 1 | 0 | 1 1 | 0 0 0 1 | Dd | 1 0 1 1 | 1 | 1 | 0 | 0 | Dm | FSQRTD Coprocessor Data Operation // +------+---------------+---+------+------------+------+-----------+---+---+---+---+----+ // | cond | 1 1 1 0 1 | 0 | 1 1 | 0 1 0 0 | Dd | 1 0 1 1 | 0 | 1 | 0 | 0 | Dm | FCMPD Coprocessor Data Operation // +------+---------------+---+------+------------+------+-----------+---+---+---+---+----+ // | cond | 1 1 1 0 1 | 0 | 1 1 | 0 1 0 0 | Dd | 1 0 1 1 | 1 | 1 | 0 | 0 | Dm | FCMPED Coprocessor Data Operation // +------+---------------+---+------+------------+------+-----------+---+---+---+---+----+ // | cond | 1 1 1 0 1 | 0 | 1 1 | 0 1 0 1 | Dd | 1 0 1 1 | 0 | 1 | 0 | 0 | 0 | FCMPZD Coprocessor Data Operation // +------+---------------+---+------+------------+------+-----------+---+---+---+---+----+ // | cond | 1 1 1 0 1 | 0 | 1 1 | 0 1 0 1 | Dd | 1 0 1 1 | 1 | 1 | 0 | 0 | 0 | FCMPEZD Coprocessor Data Operation // +------+---------------+---+------+------------+------+-----------+---+---+---+---+----+ // | cond | 1 1 1 0 1 | D | 1 1 | 0 1 1 1 | Fd | 1 0 1 1 | 1 | 1 | 0 | 0 | Dm | FCVTSD Coprocessor Data Operation // +------+---------------+---+------+------------+------+-----------+---+---+---+---+----+ // | cond | 1 1 1 0 1 | 0 | 1 1 | 1 0 0 0 | Dd | 1 0 1 1 | 0 | 1 | M | 0 | Fm | FUITOD Coprocessor Data Operation // +------+---------------+---+------+------------+------+-----------+---+---+---+---+----+ // | cond | 1 1 1 0 1 | 0 | 1 1 | 1 0 0 0 | Dd | 1 0 1 1 | 1 | 1 | M | 0 | Fm | FSITOD Coprocessor Data Operation // +------+---------------+---+------+------------+------+-----------+---+---+---+---+----+ // | cond | 1 1 1 0 1 | D | 1 1 | 1 1 0 0 | Fd | 1 0 1 1 | Z | 1 | 0 | 0 | Dm | FTOUID Coprocessor Data Operation // +------+---------------+---+------+------------+------+-----------+---+---+---+---+----+ // | cond | 1 1 1 0 1 | D | 1 1 | 1 1 0 1 | Fd | 1 0 1 1 | Z | 1 | 0 | 0 | Dm | FTOSID Coprocessor Data Operation // +------+---------------+---+------+------------+------+-----------+---+---+---+---+----+ // // ################################################################################ // ################################################################################ // // 31 28 27 26 25 24 23 22 21 20 19 18 17 16 15 12 11 10 9 8 7 6 5 4 3 0 // +------+---------------+---+------+------------+------+-----------+---+---+---+---+----+ // | cond | 1 1 0 1 U | D | 0 L | Rn | Fd | 1 0 1 0 | offset | FSTS/FLDS Coprocessor Data Transfer // +------+---------------+---+------+------------+------+-----------+---+---+---+---+----+ // +------+---------------+---+------+------------+------+-----------+---+---+---+---+----+ // | cond | 1 1 0 P U | D | W L | Rn | Fd | 1 0 1 0 | offset | FSTMS/FLDMS Coprocessor Data Transfer // +------+---------------+---+------+------------+------+-----------+---+---+---+---+----+ // +------+---------------+---+------+------------+------+-----------+---+---+---+---+----+ // | cond | 1 1 0 0 0 | 1 | 0 Dr| Rn | Rd | 1 0 1 0 | 0 | 0 | M | 1 | Fm | FMSRR/FMRRS Coprocessor Data Transfer // +------+---------------+---+------+------------+------+-----------+---+---+---+---+----+ // | cond | 1 1 1 0 0 | 0 | 0 Dr| Fn | Rd | 1 0 1 0 | N | 0 | 0 | 1 | 0 | FMSR/FMRS Coprocessor Register Transfer // +------+---------------+---+------+------------+------+-----------+---+---+---+---+----+ // | cond | 1 1 1 0 1 | 1 | 1 Dr| reg | Rd | 1 0 1 0 | 0 | 0 | 0 | 1 | 0 | FMXR/FMRX Coprocessor Register Transfer // +------+---------------+---+------+------------+------+-----------+---+---+---+---+----+ // | cond | 1 1 1 0 1 | 1 | 1 1 | 0 0 0 1 | 1111 | 1 0 1 0 | 0 | 0 | 0 | 1 | 0 | FMSTAT Coprocessor Register Transfer // +------+---------------+---+------+------------+------+-----------+---+---+---+---+----+ // +------+---------------+---+------+------------+------+-----------+---+---+---+---+----+ // | cond | 1 1 1 0 0 | D | 0 0 | Fn | Fd | 1 0 1 0 | N | 0 | M | 0 | Fm | FMACS Coprocessor Data Operation // +------+---------------+---+------+------------+------+-----------+---+---+---+---+----+ // | cond | 1 1 1 0 0 | D | 0 0 | Fn | Fd | 1 0 1 0 | N | 1 | M | 0 | Fm | FNMACS Coprocessor Data Operation // +------+---------------+---+------+------------+------+-----------+---+---+---+---+----+ // | cond | 1 1 1 0 0 | D | 0 1 | Fn | Fd | 1 0 1 0 | N | 0 | M | 0 | Fm | FMSCS Coprocessor Data Operation // +------+---------------+---+------+------------+------+-----------+---+---+---+---+----+ // | cond | 1 1 1 0 0 | D | 0 1 | Fn | Fd | 1 0 1 0 | N | 1 | M | 0 | Fm | FNMSCS Coprocessor Data Operation // +------+---------------+---+------+------------+------+-----------+---+---+---+---+----+ // | cond | 1 1 1 0 0 | D | 1 0 | Fn | Fd | 1 0 1 0 | N | 0 | M | 0 | Fm | FMULS Coprocessor Data Operation // +------+---------------+---+------+------------+------+-----------+---+---+---+---+----+ // | cond | 1 1 1 0 0 | D | 1 0 | Fn | Fd | 1 0 1 0 | N | 1 | M | 0 | Fm | FNMULS Coprocessor Data Operation // +------+---------------+---+------+------------+------+-----------+---+---+---+---+----+ // | cond | 1 1 1 0 0 | D | 1 1 | Fn | Fd | 1 0 1 0 | N | 0 | M | 0 | Fm | FADDS Coprocessor Data Operation // +------+---------------+---+------+------------+------+-----------+---+---+---+---+----+ // | cond | 1 1 1 0 0 | D | 1 1 | Fn | Fd | 1 0 1 0 | N | 1 | M | 0 | Fm | FSUBS Coprocessor Data Operation // +------+---------------+---+------+------------+------+-----------+---+---+---+---+----+ // | cond | 1 1 1 0 1 | D | 0 0 | Fn | Fd | 1 0 1 0 | N | 0 | M | 0 | Fm | FDIVS Coprocessor Data Operation // +------+---------------+---+------+------------+------+-----------+---+---+---+---+----+ // +------+---------------+---+------+------------+------+-----------+---+---+---+---+----+ // | cond | 1 1 1 0 1 | D | 1 1 | 0 0 0 0 | Fd | 1 0 1 0 | 0 | 1 | M | 0 | Fm | FCPYS Coprocessor Data Operation // +------+---------------+---+------+------------+------+-----------+---+---+---+---+----+ // | cond | 1 1 1 0 1 | D | 1 1 | 0 0 0 0 | Fd | 1 0 1 0 | 1 | 1 | M | 0 | Fm | FABSS Coprocessor Data Operation // +------+---------------+---+------+------------+------+-----------+---+---+---+---+----+ // | cond | 1 1 1 0 1 | D | 1 1 | 0 0 0 1 | Fd | 1 0 1 0 | 0 | 1 | M | 0 | Fm | FNEGS Coprocessor Data Operation // +------+---------------+---+------+------------+------+-----------+---+---+---+---+----+ // | cond | 1 1 1 0 1 | D | 1 1 | 0 0 0 1 | Fd | 1 0 1 0 | 1 | 1 | M | 0 | Fm | FSQRTS Coprocessor Data Operation // +------+---------------+---+------+------------+------+-----------+---+---+---+---+----+ // | cond | 1 1 1 0 1 | D | 1 1 | 0 1 0 0 | Fd | 1 0 1 0 | 0 | 1 | M | 0 | Fm | FCMPS Coprocessor Data Operation // +------+---------------+---+------+------------+------+-----------+---+---+---+---+----+ // | cond | 1 1 1 0 1 | D | 1 1 | 0 1 0 0 | Fd | 1 0 1 0 | 1 | 1 | M | 0 | Fm | FCMPES Coprocessor Data Operation // +------+---------------+---+------+------------+------+-----------+---+---+---+---+----+ // | cond | 1 1 1 0 1 | D | 1 1 | 0 1 0 1 | Fd | 1 0 1 0 | 0 | 1 | 0 | 0 | 0 | FCMPZS Coprocessor Data Operation // +------+---------------+---+------+------------+------+-----------+---+---+---+---+----+ // | cond | 1 1 1 0 1 | D | 1 1 | 0 1 0 1 | Fd | 1 0 1 0 | 1 | 1 | 0 | 0 | 0 | FCMPEZS Coprocessor Data Operation // +------+---------------+---+------+------------+------+-----------+---+---+---+---+----+ // | cond | 1 1 1 0 1 | 0 | 1 1 | 0 1 1 1 | Dd | 1 0 1 0 | 1 | 1 | M | 0 | Fm | FCVTDS Coprocessor Data Operation // +------+---------------+---+------+------------+------+-----------+---+---+---+---+----+ // | cond | 1 1 1 0 1 | D | 1 1 | 1 0 0 0 | Dd | 1 0 1 0 | 0 | 1 | M | 0 | Fm | FUITOS Coprocessor Data Operation // +------+---------------+---+------+------------+------+-----------+---+---+---+---+----+ // | cond | 1 1 1 0 1 | D | 1 1 | 1 0 0 0 | Fd | 1 0 1 0 | 1 | 1 | M | 0 | Fm | FSITOS Coprocessor Data Operation // +------+---------------+---+------+------------+------+-----------+---+---+---+---+----+ // | cond | 1 1 1 0 1 | D | 1 1 | 1 1 0 0 | Fd | 1 0 1 0 | Z | 1 | M | 0 | Fm | FTOUIS Coprocessor Data Operation // +------+---------------+---+------+------------+------+-----------+---+---+---+---+----+ // | cond | 1 1 1 0 1 | D | 1 1 | 1 1 0 1 | Fd | 1 0 1 0 | Z | 1 | M | 0 | Fm | FTOSIS Coprocessor Data Operation // +------+---------------+---+------+------------+------+-----------+---+---+---+---+----+ // // public const uint op_ConditionCodeTransfer = 0x0EF1FA10; public const uint opmask_ConditionCodeTransfer = 0x0FFFFFFF; public const uint op_SystemRegisterTransfer = 0x0EE00A10; public const uint opmask_SystemRegisterTransfer = 0x0FE00FFF; public const uint op_32bitLoRegisterTransfer = 0x0E000B10; public const uint opmask_32bitLoRegisterTransfer = 0x0FE00FFF; public const uint op_32bitHiRegisterTransfer = 0x0E200B10; public const uint opmask_32bitHiRegisterTransfer = 0x0FE00FFF; public const uint op_32bitRegisterTransfer = 0x0E000A10; public const uint opmask_32bitRegisterTransfer = 0x0FE00F7F; public const uint op_64bitRegisterTransfer = 0x0C400A10; public const uint opmask_64bitRegisterTransfer = 0x0FE00ED0; public const uint op_DataTransfer = 0x0D000A00; public const uint opmask_DataTransfer = 0x0F200E00; public const uint op_CompareToZero = 0x0EB50A40; public const uint opmask_CompareToZero = 0x0FBF0E7F; public const uint op_ConvertFloatToFloat = 0x0EB70AC0; public const uint opmask_ConvertFloatToFloat = 0x0FBF0ED0; public const uint op_UnaryDataOperation = 0x0EB00A40; public const uint opmask_UnaryDataOperation = 0x0FB00E50; public const uint op_BinaryDataOperation = 0x0E000A00; public const uint opmask_BinaryDataOperation = 0x0F000E10; public const uint op_BlockDataTransfer = 0x0C000A00; public const uint opmask_BlockDataTransfer = 0x0E000E00; //--// ////////////////////////////////////////////////////////////////////////// public const uint c_register_s0 = 0 + 32 ; // public const uint c_register_s1 = 1 + 32 ; // public const uint c_register_s2 = 2 + 32 ; // public const uint c_register_s3 = 3 + 32 ; // public const uint c_register_s4 = 4 + 32 ; // public const uint c_register_s5 = 5 + 32 ; // public const uint c_register_s6 = 6 + 32 ; // public const uint c_register_s7 = 7 + 32 ; // public const uint c_register_s8 = 8 + 32 ; // public const uint c_register_s9 = 9 + 32 ; // public const uint c_register_s10 = 10 + 32 ; // public const uint c_register_s11 = 11 + 32 ; // public const uint c_register_s12 = 12 + 32 ; // public const uint c_register_s13 = 13 + 32 ; // public const uint c_register_s14 = 14 + 32 ; // public const uint c_register_s15 = 15 + 32 ; // public const uint c_register_s16 = 16 + 32 ; // public const uint c_register_s17 = 17 + 32 ; // public const uint c_register_s18 = 18 + 32 ; // public const uint c_register_s19 = 19 + 32 ; // public const uint c_register_s20 = 20 + 32 ; // public const uint c_register_s21 = 21 + 32 ; // public const uint c_register_s22 = 22 + 32 ; // public const uint c_register_s23 = 23 + 32 ; // public const uint c_register_s24 = 24 + 32 ; // public const uint c_register_s25 = 25 + 32 ; // public const uint c_register_s26 = 26 + 32 ; // public const uint c_register_s27 = 27 + 32 ; // public const uint c_register_s28 = 28 + 32 ; // public const uint c_register_s29 = 29 + 32 ; // public const uint c_register_s30 = 30 + 32 ; // public const uint c_register_s31 = 31 + 32 ; // // public const uint c_register_d0 = 0 + 32+32 ; // public const uint c_register_d1 = 1 + 32+32 ; // public const uint c_register_d2 = 2 + 32+32 ; // public const uint c_register_d3 = 3 + 32+32 ; // public const uint c_register_d4 = 4 + 32+32 ; // public const uint c_register_d5 = 5 + 32+32 ; // public const uint c_register_d6 = 6 + 32+32 ; // public const uint c_register_d7 = 7 + 32+32 ; // public const uint c_register_d8 = 8 + 32+32 ; // public const uint c_register_d9 = 9 + 32+32 ; // public const uint c_register_d10 = 10 + 32+32 ; // public const uint c_register_d11 = 11 + 32+32 ; // public const uint c_register_d12 = 12 + 32+32 ; // public const uint c_register_d13 = 13 + 32+32 ; // public const uint c_register_d14 = 14 + 32+32 ; // public const uint c_register_d15 = 15 + 32+32 ; // // public const uint c_register_FPSID = c_systemRegister_FPSID + 32+32+16; // public const uint c_register_FPSCR = c_systemRegister_FPSCR + 32+32+16; // public const uint c_register_FPEXC = c_systemRegister_FPEXC + 32+32+16; // ////////////////////////////////////////////////////////////////////////// /////////////////////////////////////////// public const uint c_systemRegister_FPSID = 0; public const uint c_systemRegister_FPSCR = 1; public const uint c_systemRegister_FPEXC = 8; /////////////////////////////////////////// /////////////////////////////////////////// public const uint c_binaryOperation_MAC = 0x0; // Floating-point Multiply and Accumulate public const uint c_binaryOperation_NMAC = 0x1; // Floating-point Negated Multiply and Accumulate public const uint c_binaryOperation_MSC = 0x2; // Floating-point Multiply and Subtract public const uint c_binaryOperation_NMSC = 0x3; // Floating-point Negated Multiply and Subtract public const uint c_binaryOperation_MUL = 0x4; // Floating-point Multiply public const uint c_binaryOperation_NMUL = 0x5; // Floating-point Negated Multiply public const uint c_binaryOperation_ADD = 0x6; // Floating-point Addition public const uint c_binaryOperation_SUB = 0x7; // Floating-point Subtract public const uint c_binaryOperation_DIV = 0x8; // Floating-point Divide /////////////////////////////////////////// //--// /////////////////////////////////////////// public const uint c_unaryOperation_CPY = 0x00; // Floating-point Copy public const uint c_unaryOperation_ABS = 0x01; // Floating-point Absolute Value public const uint c_unaryOperation_NEG = 0x02; // Floating-point Negate public const uint c_unaryOperation_SQRT = 0x03; // Floating-point Square Root public const uint c_unaryOperation_CMP = 0x08; // Floating-point Compare public const uint c_unaryOperation_CMPE = 0x09; // Floating-point Compare (NaN Exceptions) public const uint c_unaryOperation_UITO = 0x10; // Convert Unsigned Integer to Floating-point public const uint c_unaryOperation_SITO = 0x11; // Convert Signed Integer to Floating-point public const uint c_unaryOperation_TOUI = 0x18; // Convert from Floating-point to Unsigned Integer public const uint c_unaryOperation_TOUIZ = 0x19; // Convert from Floating-point to Unsigned Integer, Round Towards Zero public const uint c_unaryOperation_TOSI = 0x1A; // Convert from Floating-point to Signed Integer public const uint c_unaryOperation_TOSIZ = 0x1B; // Convert from Floating-point to Signed Integer, Round Towards Zero /////////////////////////////////////////// //--// /////////////////////////////////////////// public const int c_fpexc_bit_EN = 30; public const int c_fpexc_bit_EX = 31; public const uint c_fpexc_EN = 1U << c_fpexc_bit_EN; public const uint c_fpexc_EX = 1U << c_fpexc_bit_EX; /////////////////////////////////////////// /////////////////////////////////////////// public const int c_fpscr_bit_IOC = 0; // Invalid Operation (Cumulative exception bit) public const int c_fpscr_bit_IOE = 8; // Invalid Operation (Trap enable bit) public const int c_fpscr_bit_DZC = 1; // Division by Zero (Cumulative exception bit) public const int c_fpscr_bit_DZE = 9; // Division by Zero (Trap enable bit) public const int c_fpscr_bit_OFC = 2; // Overflow (Cumulative exception bit) public const int c_fpscr_bit_OFE = 10; // Overflow (Trap enable bit) public const int c_fpscr_bit_UFC = 3; // Underflow (Cumulative exception bit) public const int c_fpscr_bit_UFE = 11; // Underflow (Trap enable bit) public const int c_fpscr_bit_IXC = 4; // Inexact (Cumulative exception bit) public const int c_fpscr_bit_IXE = 12; // Inexact (Trap enable bit) public const int c_fpscr_bit_IDC = 7; // Input Denormal (Cumulative exception bit) public const int c_fpscr_bit_IDE = 15; // Input Denormal (Trap enable bit) public const int c_fpscr_shift_LEN = 16; // Vector length for VFP instructions public const int c_fpscr_mask_LEN = 0x7; // public const int c_fpscr_shift_STRIDE = 20; // Vector stride for VFP instructions public const int c_fpscr_mask_STRIDE = 0x3; // public const int c_fpscr_shift_RMODE = 22; // Rounding mode control public const int c_fpscr_mask_RMODE = 0x3; // public const int c_fpscr_bit_FZ = 24; // Flush-to-zero mode control public const int c_fpscr_bit_DN = 25; // Default NaN mode control public const int c_fpscr_bit_V = 28; // Is 1 if the comparison produced an unordered result. public const int c_fpscr_bit_C = 29; // Is 1 if the comparison produced an equal, greater than or unordered result public const int c_fpscr_bit_Z = 30; // Is 1 if the comparison produced an equal result public const int c_fpscr_bit_N = 31; // Is 1 if the comparison produced a less than result public const uint c_fpscr_IOC = 1U << c_fpscr_bit_IOC; public const uint c_fpscr_IOE = 1U << c_fpscr_bit_IOE; public const uint c_fpscr_DZC = 1U << c_fpscr_bit_DZC; public const uint c_fpscr_DZE = 1U << c_fpscr_bit_DZE; public const uint c_fpscr_OFC = 1U << c_fpscr_bit_OFC; public const uint c_fpscr_OFE = 1U << c_fpscr_bit_OFE; public const uint c_fpscr_UFC = 1U << c_fpscr_bit_UFC; public const uint c_fpscr_UFE = 1U << c_fpscr_bit_UFE; public const uint c_fpscr_IXC = 1U << c_fpscr_bit_IXC; public const uint c_fpscr_IXE = 1U << c_fpscr_bit_IXE; public const uint c_fpscr_IDC = 1U << c_fpscr_bit_IDC; public const uint c_fpscr_IDE = 1U << c_fpscr_bit_IDE; public const uint c_fpscr_FZ = 1U << c_fpscr_bit_FZ; public const uint c_fpscr_DN = 1U << c_fpscr_bit_DN; public const uint c_fpscr_V = 1U << c_fpscr_bit_V; public const uint c_fpscr_C = 1U << c_fpscr_bit_C; public const uint c_fpscr_Z = 1U << c_fpscr_bit_Z; public const uint c_fpscr_N = 1U << c_fpscr_bit_N; /////////////////////////////////////////// //--// abstract public uint get_Rn( uint op ); abstract public uint set_Rn( uint val ); abstract public uint get_SysReg( uint op ); abstract public uint set_SysReg( uint val ); abstract public uint get_Fn( uint op ); abstract public uint set_Fn( uint val ); abstract public uint get_Rd( uint op ); abstract public uint set_Rd( uint val ); abstract public uint get_Fd( uint op ); abstract public uint set_Fd( uint val ); abstract public uint get_Fm( uint op ); abstract public uint set_Fm( uint val ); abstract public bool get_IsDouble( uint op ); abstract public uint set_IsDouble( bool val ); abstract public bool get_CheckNaN( uint op ); abstract public uint set_CheckNaN( bool val ); //--// abstract public uint get_BinaryOperation( uint op ); abstract public uint set_BinaryOperation( uint val ); //--// abstract public uint get_UnaryOperation( uint op ); abstract public uint set_UnaryOperation( uint val ); //-// abstract public bool get_RegisterTransfer_IsFromCoproc( uint op ); abstract public uint set_RegisterTransfer_IsFromCoproc( bool val ); //--// abstract public bool get_DataTransfer_IsLoad ( uint op ); abstract public uint set_DataTransfer_IsLoad ( bool val ); abstract public bool get_DataTransfer_ShouldWriteBack( uint op ); abstract public uint set_DataTransfer_ShouldWriteBack( bool val ); abstract public bool get_DataTransfer_IsUp ( uint op ); abstract public uint set_DataTransfer_IsUp ( bool val ); abstract public bool get_DataTransfer_IsPreIndexing ( uint op ); abstract public uint set_DataTransfer_IsPreIndexing ( bool val ); abstract public uint get_DataTransfer_Offset ( uint op ); abstract public uint set_DataTransfer_Offset ( uint val ); } } ================================================ FILE: Zelig/Zelig/CompileTime/TargetModels/ArmProcessor/InstructionSet.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // namespace Microsoft.Zelig.TargetModel.ArmProcessor { using EncDef = Microsoft.Zelig.TargetModel.ArmProcessor.EncodingDefinition_ARM; public class InstructionSet { private static EncodingDefinition_ARM s_Encoding = (EncodingDefinition_ARM)CurrentInstructionSetEncoding.GetEncoding(); public override bool Equals(object obj) { InstructionSet match = obj as InstructionSet; if(match != null) { return m_version == match.Version; } return false; } public override int GetHashCode() { return base.GetHashCode(); } // // State // private readonly InstructionSetVersion m_version; //--// private readonly Opcode_MRS m_MRS; private readonly Opcode_MSR_1 m_MSR_1; private readonly Opcode_MSR_2 m_MSR_2; private readonly Opcode_DataProcessing_1 m_DataProcessing_1; private readonly Opcode_DataProcessing_2 m_DataProcessing_2; private readonly Opcode_DataProcessing_3 m_DataProcessing_3; private readonly Opcode_Multiply m_Multiply; private readonly Opcode_MultiplyLong m_MultiplyLong; private readonly Opcode_SingleDataSwap m_SingleDataSwap; private readonly Opcode_BranchAndExchange m_BranchAndExchange; private readonly Opcode_HalfwordDataTransfer_1 m_HalfwordDataTransfer_1; private readonly Opcode_HalfwordDataTransfer_2 m_HalfwordDataTransfer_2; private readonly Opcode_SingleDataTransfer_1 m_SingleDataTransfer_1; private readonly Opcode_SingleDataTransfer_2 m_SingleDataTransfer_2; private readonly Opcode_SingleDataTransfer_3 m_SingleDataTransfer_3; private readonly Opcode_BlockDataTransfer m_BlockDataTransfer; private readonly Opcode_Branch m_Branch; private readonly Opcode_CoprocDataTransfer m_CoprocDataTransfer; private readonly Opcode_CoprocDataOperation m_CoprocDataOperation; private readonly Opcode_CoprocRegisterTransfer m_CoprocRegisterTransfer; private readonly Opcode_SoftwareInterrupt m_SoftwareInterrupt; private readonly Opcode_Breakpoint m_Breakpoint; // // Constructor Methods // public InstructionSet(InstructionSetVersion version) { m_version = version; //--// m_MRS = new Opcode_MRS (); m_MSR_1 = new Opcode_MSR_1 (); m_MSR_2 = new Opcode_MSR_2 (); m_DataProcessing_1 = new Opcode_DataProcessing_1 (); m_DataProcessing_2 = new Opcode_DataProcessing_2 (); m_DataProcessing_3 = new Opcode_DataProcessing_3 (); m_Multiply = new Opcode_Multiply (); m_MultiplyLong = new Opcode_MultiplyLong (); m_SingleDataSwap = new Opcode_SingleDataSwap (); m_BranchAndExchange = new Opcode_BranchAndExchange (); m_HalfwordDataTransfer_1 = new Opcode_HalfwordDataTransfer_1(); m_HalfwordDataTransfer_2 = new Opcode_HalfwordDataTransfer_2(); m_SingleDataTransfer_1 = new Opcode_SingleDataTransfer_1 (); m_SingleDataTransfer_2 = new Opcode_SingleDataTransfer_2 (); m_SingleDataTransfer_3 = new Opcode_SingleDataTransfer_3 (); m_BlockDataTransfer = new Opcode_BlockDataTransfer (); m_Branch = new Opcode_Branch (); m_CoprocDataTransfer = new Opcode_CoprocDataTransfer (); m_CoprocDataOperation = new Opcode_CoprocDataOperation (); m_CoprocRegisterTransfer = new Opcode_CoprocRegisterTransfer(); m_SoftwareInterrupt = new Opcode_SoftwareInterrupt (); m_Breakpoint = new Opcode_Breakpoint (); } //--// //--// Version //--// public InstructionSetVersion Version { get { return m_version; } } //--// public Opcode_MRS PrepareForMRS { get { return m_MRS ; } } public Opcode_MSR_1 PrepareForMSR_1 { get { return m_MSR_1 ; } } public Opcode_MSR_2 PrepareForMSR_2 { get { return m_MSR_2 ; } } public Opcode_DataProcessing_1 PrepareForDataProcessing_1 { get { return m_DataProcessing_1 ; } } public Opcode_DataProcessing_2 PrepareForDataProcessing_2 { get { return m_DataProcessing_2 ; } } public Opcode_DataProcessing_3 PrepareForDataProcessing_3 { get { return m_DataProcessing_3 ; } } public Opcode_Multiply PrepareForMultiply { get { return m_Multiply ; } } public Opcode_MultiplyLong PrepareForMultiplyLong { get { return m_MultiplyLong ; } } public Opcode_SingleDataSwap PrepareForSingleDataSwap { get { return m_SingleDataSwap ; } } public Opcode_BranchAndExchange PrepareForBranchAndExchange { get { return m_BranchAndExchange ; } } public Opcode_HalfwordDataTransfer_1 PrepareForHalfwordDataTransfer_1 { get { return m_HalfwordDataTransfer_1; } } public Opcode_HalfwordDataTransfer_2 PrepareForHalfwordDataTransfer_2 { get { return m_HalfwordDataTransfer_2; } } public Opcode_SingleDataTransfer_1 PrepareForSingleDataTransfer_1 { get { return m_SingleDataTransfer_1 ; } } public Opcode_SingleDataTransfer_2 PrepareForSingleDataTransfer_2 { get { return m_SingleDataTransfer_2 ; } } public Opcode_SingleDataTransfer_3 PrepareForSingleDataTransfer_3 { get { return m_SingleDataTransfer_3 ; } } public Opcode_BlockDataTransfer PrepareForBlockDataTransfer { get { return m_BlockDataTransfer ; } } public Opcode_Branch PrepareForBranch { get { return m_Branch ; } } public Opcode_CoprocDataTransfer PrepareForCoprocDataTransfer { get { return m_CoprocDataTransfer ; } } public Opcode_CoprocDataOperation PrepareForCoprocDataOperation { get { return m_CoprocDataOperation ; } } public Opcode_CoprocRegisterTransfer PrepareForCoprocRegisterTransfer { get { return m_CoprocRegisterTransfer; } } public Opcode_SoftwareInterrupt PrepareForSoftwareInterrupt { get { return m_SoftwareInterrupt ; } } public Opcode_Breakpoint PrepareForBreakpoint { get { return m_Breakpoint ; } } //--// public virtual Opcode Decode( uint op ) { Opcode opcode = null; if ((op & EncDef.opmask_Breakpoint ) == EncDef.op_Breakpoint ) opcode = m_Breakpoint ; else if((op & EncDef.opmask_MRS ) == EncDef.op_MRS ) opcode = m_MRS ; else if((op & EncDef.opmask_MSR_1 ) == EncDef.op_MSR_1 ) opcode = m_MSR_1 ; else if((op & EncDef.opmask_MSR_2 ) == EncDef.op_MSR_2 ) opcode = m_MSR_2 ; else if((op & EncDef.opmask_DataProcessing_1 ) == EncDef.op_DataProcessing_1 ) opcode = m_DataProcessing_1 ; else if((op & EncDef.opmask_DataProcessing_2 ) == EncDef.op_DataProcessing_2 ) opcode = m_DataProcessing_2 ; else if((op & EncDef.opmask_DataProcessing_3 ) == EncDef.op_DataProcessing_3 ) opcode = m_DataProcessing_3 ; else if((op & EncDef.opmask_Multiply ) == EncDef.op_Multiply ) opcode = m_Multiply ; else if((op & EncDef.opmask_MultiplyLong ) == EncDef.op_MultiplyLong ) opcode = m_MultiplyLong ; else if((op & EncDef.opmask_SingleDataSwap ) == EncDef.op_SingleDataSwap ) opcode = m_SingleDataSwap ; else if((op & EncDef.opmask_BranchAndExchange ) == EncDef.op_BranchAndExchange ) opcode = m_BranchAndExchange ; else if((op & EncDef.opmask_HalfwordDataTransfer_1) == EncDef.op_HalfwordDataTransfer_1) opcode = m_HalfwordDataTransfer_1; else if((op & EncDef.opmask_HalfwordDataTransfer_2) == EncDef.op_HalfwordDataTransfer_2) opcode = m_HalfwordDataTransfer_2; else if((op & EncDef.opmask_SingleDataTransfer_1 ) == EncDef.op_SingleDataTransfer_1 ) opcode = m_SingleDataTransfer_1 ; else if((op & EncDef.opmask_SingleDataTransfer_2 ) == EncDef.op_SingleDataTransfer_2 ) opcode = m_SingleDataTransfer_2 ; else if((op & EncDef.opmask_SingleDataTransfer_3 ) == EncDef.op_SingleDataTransfer_3 ) opcode = m_SingleDataTransfer_3 ; else if((op & EncDef.opmask_Undefined ) == EncDef.op_Undefined ) opcode = null ; else if((op & EncDef.opmask_BlockDataTransfer ) == EncDef.op_BlockDataTransfer ) opcode = m_BlockDataTransfer ; else if((op & EncDef.opmask_Branch ) == EncDef.op_Branch ) opcode = m_Branch ; else if((op & EncDef.opmask_CoprocDataTransfer ) == EncDef.op_CoprocDataTransfer ) opcode = m_CoprocDataTransfer ; else if((op & EncDef.opmask_CoprocDataOperation ) == EncDef.op_CoprocDataOperation ) opcode = m_CoprocDataOperation ; else if((op & EncDef.opmask_CoprocRegisterTransfer) == EncDef.op_CoprocRegisterTransfer) opcode = m_CoprocRegisterTransfer; else if((op & EncDef.opmask_SoftwareInterrupt ) == EncDef.op_SoftwareInterrupt ) opcode = m_SoftwareInterrupt ; if(opcode != null) { opcode.Decode( op ); } return opcode; } public string DecodeAndPrint( uint address , uint op , out uint target , out bool targetIsCode ) { target = 0; targetIsCode = false; Opcode dec = Decode( op ); if(dec == null) { return ""; } else { System.Text.StringBuilder str = new System.Text.StringBuilder(); dec.Print( this, str, address, ref target, ref targetIsCode ); return str.ToString(); } } //--// public static string DumpMode( uint mode ) { switch(mode & EncDef.c_psr_mode) { case EncDef.c_psr_mode_USER : return "USER"; case EncDef.c_psr_mode_FIQ : return "FIQ"; case EncDef.c_psr_mode_IRQ : return "IRQ"; case EncDef.c_psr_mode_SVC : return "SVC"; case EncDef.c_psr_mode_ABORT: return "ABORT"; case EncDef.c_psr_mode_UNDEF: return "UNDEF"; case EncDef.c_psr_mode_SYS : return "SYS"; } return "??"; } //--// public abstract class Opcode { // // State // public uint ConditionCodes; //--// protected void Prepare( uint ConditionCodes ) { this.ConditionCodes = ConditionCodes; } //--// public virtual void Decode( uint op ) { this.ConditionCodes = s_Encoding.get_ConditionCodes( op ); } public virtual uint Encode() { return s_Encoding.set_ConditionCodes( this.ConditionCodes ); } public abstract void Print( InstructionSet owner , System.Text.StringBuilder str , uint opcodeAddress , ref uint target , ref bool targetIsCode ); //--// protected void PrintMnemonic( System.Text.StringBuilder str , string format , params object[] args ) { int start = str.Length; str.AppendFormat( format, args ); int len = str.Length - start; if(len < 9) { str.Append( new string( ' ', 9 - len ) ); } } //--// protected string DumpCondition() { switch(this.ConditionCodes) { case EncDef.c_cond_EQ: return "EQ"; case EncDef.c_cond_NE: return "NE"; case EncDef.c_cond_CS: return "CS"; case EncDef.c_cond_CC: return "CC"; case EncDef.c_cond_MI: return "MI"; case EncDef.c_cond_PL: return "PL"; case EncDef.c_cond_VS: return "VS"; case EncDef.c_cond_VC: return "VC"; case EncDef.c_cond_HI: return "HI"; case EncDef.c_cond_LS: return "LS"; case EncDef.c_cond_GE: return "GE"; case EncDef.c_cond_LT: return "LT"; case EncDef.c_cond_GT: return "GT"; case EncDef.c_cond_LE: return "LE"; case EncDef.c_cond_AL: return ""; } return "??"; } //--// public static string DumpRegister( uint reg ) { switch(reg) { case EncDef.c_register_r0 : return "r0"; case EncDef.c_register_r1 : return "r1"; case EncDef.c_register_r2 : return "r2"; case EncDef.c_register_r3 : return "r3"; case EncDef.c_register_r4 : return "r4"; case EncDef.c_register_r5 : return "r5"; case EncDef.c_register_r6 : return "r6"; case EncDef.c_register_r7 : return "r7"; case EncDef.c_register_r8 : return "r8"; case EncDef.c_register_r9 : return "r9"; case EncDef.c_register_r10: return "r10"; case EncDef.c_register_r11: return "r11"; case EncDef.c_register_r12: return "r12"; case EncDef.c_register_sp : return "sp"; case EncDef.c_register_lr : return "lr"; case EncDef.c_register_pc : return "pc"; } return "??"; } //--// static protected string DumpShiftType( uint stype ) { switch(stype) { case EncDef.c_shift_LSL: return "LSL"; case EncDef.c_shift_LSR: return "LSR"; case EncDef.c_shift_ASR: return "ASR"; case EncDef.c_shift_ROR: return "ROR"; case EncDef.c_shift_RRX: return "RRX"; } return "???"; } static protected string DumpHalfWordKind( uint kind ) { switch(kind) { case EncDef.c_halfwordkind_SWP: return "SWP"; case EncDef.c_halfwordkind_U2 : return "H"; case EncDef.c_halfwordkind_I1 : return "SB"; case EncDef.c_halfwordkind_I2 : return "SH"; } return "??"; } } public sealed class Opcode_MRS : Opcode { // // State // public bool UseSPSR; public uint Rd; // // Constructor Methods // internal Opcode_MRS() { } //--// public void Prepare( uint ConditionCodes , bool UseSPSR , uint Rd ) { base.Prepare( ConditionCodes ); this.UseSPSR = UseSPSR; this.Rd = Rd; } //--// public override void Decode( uint op ) { base.Decode( op ); this.UseSPSR = s_Encoding.get_StatusRegister_IsSPSR( op ); this.Rd = s_Encoding.get_Register2 ( op ); } public override uint Encode() { uint op = base.Encode(); op |= s_Encoding.set_StatusRegister_IsSPSR( this.UseSPSR ); op |= s_Encoding.set_Register2 ( this.Rd ); return op | EncDef.op_MRS; } public override void Print( InstructionSet owner , System.Text.StringBuilder str , uint opcodeAddress , ref uint target , ref bool targetIsCode ) { PrintMnemonic( str, "MRS{0}", DumpCondition() ); str.AppendFormat( "{0},{1}", DumpRegister( this.Rd ), this.UseSPSR ? "SPSR" : "CPSR" ); } } public abstract class Opcode_MSR : Opcode { // // State // public bool UseSPSR; public uint Fields; //--// protected void Prepare( uint ConditionCodes , bool UseSPSR , uint Fields ) { base.Prepare( ConditionCodes ); this.UseSPSR = UseSPSR; this.Fields = Fields; } //--// public override void Decode( uint op ) { base.Decode( op ); this.UseSPSR = s_Encoding.get_StatusRegister_IsSPSR( op ); this.Fields = s_Encoding.get_StatusRegister_Fields( op ); } public override uint Encode() { uint op = base.Encode(); op |= s_Encoding.set_StatusRegister_IsSPSR( this.UseSPSR ); op |= s_Encoding.set_StatusRegister_Fields( this.Fields ); return op; } protected void PrintPre( System.Text.StringBuilder str ) { PrintMnemonic( str, "MSR{0}", DumpCondition() ); str.AppendFormat( "{0}_{1}{2}{3}{4}", this.UseSPSR ? "SPSR" : "CPSR", (this.Fields & EncDef.c_psr_field_c) != 0 ? "c" : "" , (this.Fields & EncDef.c_psr_field_x) != 0 ? "x" : "" , (this.Fields & EncDef.c_psr_field_s) != 0 ? "s" : "" , (this.Fields & EncDef.c_psr_field_f) != 0 ? "f" : "" ); } } public sealed class Opcode_MSR_1 : Opcode_MSR { // // State // public uint Rm; // // Constructor Methods // internal Opcode_MSR_1() { } //--// public void Prepare( uint ConditionCodes , bool UseSPSR , uint Fields , uint Rm ) { base.Prepare( ConditionCodes , UseSPSR , Fields ); this.Rm = Rm; } //--// public override void Decode( uint op ) { base.Decode( op ); this.Rm = s_Encoding.get_Register4( op ); } public override uint Encode() { uint op = base.Encode(); op |= s_Encoding.set_Register4( this.Rm ); return op | EncDef.op_MSR_1; } public override void Print( InstructionSet owner , System.Text.StringBuilder str , uint opcodeAddress , ref uint target , ref bool targetIsCode ) { PrintPre( str ); str.AppendFormat( ",{0}", DumpRegister( this.Rm ) ); } } public sealed class Opcode_MSR_2 : Opcode_MSR { // // State // public uint ImmediateSeed; public uint ImmediateRotation; // // Constructor Methods // internal Opcode_MSR_2() { } //--// public void Prepare( uint ConditionCodes , bool UseSPSR , uint Fields , uint ImmediateSeed , uint ImmediateRotation ) { base.Prepare( ConditionCodes , UseSPSR , Fields ); this.ImmediateSeed = ImmediateSeed; this.ImmediateRotation = ImmediateRotation; } //--// public override void Decode( uint op ) { base.Decode( op ); this.ImmediateSeed = s_Encoding.get_DataProcessing_ImmediateSeed ( op ); this.ImmediateRotation = s_Encoding.get_DataProcessing_ImmediateRotation( op ); } public override uint Encode() { uint op = base.Encode(); op |= s_Encoding.set_DataProcessing_ImmediateSeed ( this.ImmediateSeed ); op |= s_Encoding.set_DataProcessing_ImmediateRotation( this.ImmediateRotation ); return op | EncDef.op_MSR_2; } public override void Print( InstructionSet owner , System.Text.StringBuilder str , uint opcodeAddress , ref uint target , ref bool targetIsCode ) { PrintPre( str ); str.AppendFormat( ",#0x{0:X}", this.Immediate ); } public uint Immediate { get { return s_Encoding.get_DataProcessing_ImmediateValue( this.ImmediateSeed, this.ImmediateRotation ); } } } //--// public abstract class Opcode_DataProcessing : Opcode { // // State // public uint Rn; public uint Rd; public uint Alu; public bool SetCC; //--// protected void Prepare( uint ConditionCodes , uint Rn , uint Rd , uint Alu , bool SetCC ) { base.Prepare( ConditionCodes ); this.Rn = Rn; this.Rd = Rd; this.Alu = Alu; this.SetCC = SetCC; } //--// public override void Decode( uint op ) { base.Decode( op ); this.Rn = s_Encoding.get_Register1 ( op ); this.Rd = s_Encoding.get_Register2 ( op ); this.Alu = s_Encoding.get_DataProcessing_Operation( op ); this.SetCC = s_Encoding.get_ShouldSetConditions ( op ); } public override uint Encode() { uint op = base.Encode(); op |= s_Encoding.set_Register1 ( this.Rn ); op |= s_Encoding.set_Register2 ( this.Rd ); op |= s_Encoding.set_DataProcessing_Operation( this.Alu ); op |= s_Encoding.set_ShouldSetConditions ( this.SetCC ); return op; } protected void PrintPre( System.Text.StringBuilder str ) { bool fMov = false; bool fTst = false; switch(this.Alu) { case EncDef.c_operation_MOV: case EncDef.c_operation_MVN: fMov = true; break; case EncDef.c_operation_TEQ: case EncDef.c_operation_TST: case EncDef.c_operation_CMP: case EncDef.c_operation_CMN: fTst = true; break; } PrintMnemonic( str, "{0}{1}{2}", DumpOperation( this.Alu ), DumpCondition(), !fTst && this.SetCC ? 'S' : ' ' ); if(fMov) { str.AppendFormat( "{0}", DumpRegister( this.Rd ) ); } else if(fTst) { str.AppendFormat( "{0}", DumpRegister( this.Rn ) ); } else { str.AppendFormat( "{0},{1}", DumpRegister( this.Rd ), DumpRegister( this.Rn ) ); } } private static string DumpOperation( uint alu ) { switch(alu) { case EncDef.c_operation_AND: return "AND"; case EncDef.c_operation_EOR: return "EOR"; case EncDef.c_operation_SUB: return "SUB"; case EncDef.c_operation_RSB: return "RSB"; case EncDef.c_operation_ADD: return "ADD"; case EncDef.c_operation_ADC: return "ADC"; case EncDef.c_operation_SBC: return "SBC"; case EncDef.c_operation_RSC: return "RSC"; case EncDef.c_operation_TST: return "TST"; case EncDef.c_operation_TEQ: return "TEQ"; case EncDef.c_operation_CMP: return "CMP"; case EncDef.c_operation_CMN: return "CMN"; case EncDef.c_operation_ORR: return "ORR"; case EncDef.c_operation_MOV: return "MOV"; case EncDef.c_operation_BIC: return "BIC"; case EncDef.c_operation_MVN: return "MVN"; } return "??"; } } public sealed class Opcode_DataProcessing_1 : Opcode_DataProcessing { // // State // public uint ImmediateSeed; public uint ImmediateRotation; // // Constructor Methods // internal Opcode_DataProcessing_1() { } //--// public void Prepare( uint ConditionCodes , uint Rn , uint Rd , uint Alu , bool SetCC , uint ImmediateSeed , uint ImmediateRotation ) { base.Prepare( ConditionCodes , Rn , Rd , Alu , SetCC ); this.ImmediateSeed = ImmediateSeed; this.ImmediateRotation = ImmediateRotation; } //--// public override void Decode( uint op ) { base.Decode( op ); this.ImmediateSeed = s_Encoding.get_DataProcessing_ImmediateSeed ( op ); this.ImmediateRotation = s_Encoding.get_DataProcessing_ImmediateRotation( op ); } public override uint Encode() { uint op = base.Encode(); op |= s_Encoding.set_DataProcessing_ImmediateSeed ( this.ImmediateSeed ); op |= s_Encoding.set_DataProcessing_ImmediateRotation( this.ImmediateRotation ); return op | EncDef.op_DataProcessing_1; } public override void Print( InstructionSet owner , System.Text.StringBuilder str , uint opcodeAddress , ref uint target , ref bool targetIsCode ) { uint offset = this.Immediate; PrintPre( str ); str.AppendFormat( ",#0x{0:X}", offset ); if(Rn == 15) { switch(Alu) { case EncDef.c_operation_ADD: target = (uint)(opcodeAddress + 8 + offset); str.AppendFormat( " ; 0x{0:X8}", target ); break; case EncDef.c_operation_SUB: target = (uint)(opcodeAddress + 8 - offset); str.AppendFormat( " ; 0x{0:X8}", target ); break; } } } public uint Immediate { get { return s_Encoding.get_DataProcessing_ImmediateValue( this.ImmediateSeed, this.ImmediateRotation ); } } } public abstract class Opcode_DataProcessing_23 : Opcode_DataProcessing { // // State // public uint Rm; public uint ShiftType; //--// protected void Prepare( uint ConditionCodes , uint Rn , uint Rd , uint Alu , bool SetCC , uint Rm , uint ShiftType ) { base.Prepare( ConditionCodes , Rn , Rd , Alu , SetCC ); this.Rm = Rm; this.ShiftType = ShiftType; } //--// public override void Decode( uint op ) { base.Decode( op ); this.Rm = s_Encoding.get_Register4 ( op ); this.ShiftType = s_Encoding.get_Shift_Type( op ); } public override uint Encode() { uint op = base.Encode(); op |= s_Encoding.set_Register4 ( this.Rm ); op |= s_Encoding.set_Shift_Type( this.ShiftType ); return op; } protected new void PrintPre( System.Text.StringBuilder str ) { base.PrintPre( str ); str.AppendFormat( ",{0}", DumpRegister( this.Rm ) ); } } public sealed class Opcode_DataProcessing_2 : Opcode_DataProcessing_23 { // // State // public uint ShiftValue; // // Constructor Methods // internal Opcode_DataProcessing_2() { } //--// public void Prepare( uint ConditionCodes , uint Rn , uint Rd , uint Alu , bool SetCC , uint Rm , uint ShiftType , uint ShiftValue ) { base.Prepare( ConditionCodes , Rn , Rd , Alu , SetCC , Rm , ShiftType ); this.ShiftValue = ShiftValue; } //--// public override void Decode( uint op ) { base.Decode( op ); this.ShiftValue = s_Encoding.get_Shift_Immediate( op ); if(this.ShiftValue == 0) { switch(ShiftType) { case EncDef.c_shift_LSR: case EncDef.c_shift_ASR: this.ShiftValue = 32; break; case EncDef.c_shift_ROR: this.ShiftValue = 1; this.ShiftType = EncDef.c_shift_RRX; break; } } } public override uint Encode() { // // Save values. // uint shiftValue = this.ShiftValue; uint shiftType = this.ShiftType; switch(this.ShiftType) { case EncDef.c_shift_LSR: case EncDef.c_shift_ASR: if(this.ShiftValue == 32) { this.ShiftValue = 0; } break; case EncDef.c_shift_RRX: this.ShiftType = EncDef.c_shift_ROR; this.ShiftValue = 0; break; } uint op = base.Encode(); op |= s_Encoding.set_Shift_Immediate( this.ShiftValue ); // // Restore values. // this.ShiftValue = shiftValue; this.ShiftType = shiftType; return op | EncDef.op_DataProcessing_2; } public override void Print( InstructionSet owner , System.Text.StringBuilder str , uint opcodeAddress , ref uint target , ref bool targetIsCode ) { PrintPre( str ); if(this.ShiftValue != 0) { str.AppendFormat( ",{0} #{1}", DumpShiftType( this.ShiftType ), this.ShiftValue ); } } } public sealed class Opcode_DataProcessing_3 : Opcode_DataProcessing_23 { // // State // public uint Rs; // // Constructor Methods // internal Opcode_DataProcessing_3() { } //--// public void Prepare( uint ConditionCodes , uint Rn , uint Rd , uint Alu , bool SetCC , uint Rm , uint ShiftType , uint Rs ) { base.Prepare( ConditionCodes , Rn , Rd , Alu , SetCC , Rm , ShiftType ); this.Rs = Rs; } //--// public override void Decode( uint op ) { base.Decode( op ); this.Rs = s_Encoding.get_Register3( op ); } public override uint Encode() { uint op = base.Encode(); op |= s_Encoding.set_Register3( this.Rs ); return op | EncDef.op_DataProcessing_3; } public override void Print( InstructionSet owner , System.Text.StringBuilder str , uint opcodeAddress , ref uint target , ref bool targetIsCode ) { PrintPre( str ); str.AppendFormat( ",{0} {1}", DumpShiftType( this.ShiftType ), DumpRegister( this.Rs ) ); } } //--// public sealed class Opcode_Multiply : Opcode { // // State // public uint Rd; public uint Rn; public uint Rs; public uint Rm; public bool SetCC; public bool IsAccumulate; // // Constructor Methods // internal Opcode_Multiply() { } //--// public void Prepare( uint ConditionCodes , uint Rd , uint Rn , uint Rs , uint Rm , bool SetCC , bool IsAccumulate ) { base.Prepare( ConditionCodes ); this.Rd = Rd; this.Rn = Rn; this.Rs = Rs; this.Rm = Rm; this.SetCC = SetCC; this.IsAccumulate = IsAccumulate; } //--// public override void Decode( uint op ) { base.Decode( op ); this.Rd = s_Encoding.get_Register1 ( op ); this.Rn = s_Encoding.get_Register2 ( op ); this.Rs = s_Encoding.get_Register3 ( op ); this.Rm = s_Encoding.get_Register4 ( op ); this.SetCC = s_Encoding.get_ShouldSetConditions ( op ); this.IsAccumulate = s_Encoding.get_Multiply_IsAccumulate( op ); } public override uint Encode() { uint op = base.Encode(); op |= s_Encoding.set_Register1 ( this.Rd ); op |= s_Encoding.set_Register2 ( this.Rn ); op |= s_Encoding.set_Register3 ( this.Rs ); op |= s_Encoding.set_Register4 ( this.Rm ); op |= s_Encoding.set_ShouldSetConditions ( this.SetCC ); op |= s_Encoding.set_Multiply_IsAccumulate( this.IsAccumulate ); return op | EncDef.op_Multiply; } public override void Print( InstructionSet owner , System.Text.StringBuilder str , uint opcodeAddress , ref uint target , ref bool targetIsCode ) { PrintMnemonic( str, "{0}{1}{2}", this.IsAccumulate ? "MLA" : "MUL", DumpCondition(), this.SetCC ? 'S' : ' ' ); str.AppendFormat( "{0},{1},{2}", DumpRegister( this.Rd ), DumpRegister( this.Rm ), DumpRegister( this.Rs ) ); if(this.IsAccumulate) { str.AppendFormat( ",{0}", DumpRegister( this.Rn ) ); } } } public sealed class Opcode_MultiplyLong : Opcode { // // State // public uint RdHi; public uint RdLo; public uint Rs; public uint Rm; public bool SetCC; public bool IsAccumulate; public bool IsSigned; // // Constructor Methods // internal Opcode_MultiplyLong() { } //--// public void Prepare( uint ConditionCodes , uint RdHi , uint RdLo , uint Rs , uint Rm , bool SetCC , bool IsAccumulate , bool IsSigned ) { base.Prepare( ConditionCodes ); this.RdHi = RdHi; this.RdLo = RdLo; this.Rs = Rs; this.Rm = Rm; this.SetCC = SetCC; this.IsAccumulate = IsAccumulate; this.IsSigned = IsSigned; } //--// public override void Decode( uint op ) { base.Decode( op ); this.RdHi = s_Encoding.get_Register1 ( op ); this.RdLo = s_Encoding.get_Register2 ( op ); this.Rs = s_Encoding.get_Register3 ( op ); this.Rm = s_Encoding.get_Register4 ( op ); this.SetCC = s_Encoding.get_ShouldSetConditions ( op ); this.IsAccumulate = s_Encoding.get_Multiply_IsAccumulate( op ); this.IsSigned = s_Encoding.get_Multiply_IsSigned ( op ); } public override uint Encode() { uint op = base.Encode(); op |= s_Encoding.set_Register1 ( this.RdHi ); op |= s_Encoding.set_Register2 ( this.RdLo ); op |= s_Encoding.set_Register3 ( this.Rs ); op |= s_Encoding.set_Register4 ( this.Rm ); op |= s_Encoding.set_ShouldSetConditions ( this.SetCC ); op |= s_Encoding.set_Multiply_IsAccumulate( this.IsAccumulate ); op |= s_Encoding.set_Multiply_IsSigned ( this.IsSigned ); return op | EncDef.op_MultiplyLong; } public override void Print( InstructionSet owner , System.Text.StringBuilder str , uint opcodeAddress , ref uint target , ref bool targetIsCode ) { PrintMnemonic( str, "{0}{1}{2}{3}", this.IsSigned ? 'S' : 'U', this.IsAccumulate ? "MLAL" : "MULL", DumpCondition(), this.SetCC ? 'S' : ' ' ); str.AppendFormat( "{0},{1},{2},{3}", DumpRegister( this.RdLo ), DumpRegister( this.RdHi ), DumpRegister( this.Rm ), DumpRegister( this.Rs ) ); } } //--// public sealed class Opcode_SingleDataSwap : Opcode { // // State // public uint Rn; public uint Rd; public uint Rm; public bool IsByte; // // Constructor Methods // internal Opcode_SingleDataSwap() { } //--// public void Prepare( uint ConditionCodes , uint Rn , uint Rd , uint Rm , bool IsByte ) { base.Prepare( ConditionCodes ); this.Rn = Rn; this.Rd = Rd; this.Rm = Rm; this.IsByte = IsByte; } //--// public override void Decode( uint op ) { base.Decode( op ); this.Rn = s_Encoding.get_Register1 ( op ); this.Rd = s_Encoding.get_Register2 ( op ); this.Rm = s_Encoding.get_Register4 ( op ); this.IsByte = s_Encoding.get_DataTransfer_IsByteTransfer( op ); } public override uint Encode() { uint op = base.Encode(); op |= s_Encoding.set_Register1 ( this.Rn ); op |= s_Encoding.set_Register2 ( this.Rd ); op |= s_Encoding.set_Register4 ( this.Rm ); op |= s_Encoding.set_DataTransfer_IsByteTransfer( this.IsByte ); return op | EncDef.op_SingleDataSwap; } public override void Print( InstructionSet owner , System.Text.StringBuilder str , uint opcodeAddress , ref uint target , ref bool targetIsCode ) { PrintMnemonic( str, "{0}{1}{2}", "SWP", DumpCondition(), this.IsByte ? "B" : "" ); str.AppendFormat( "{0},{1},[{2}]", DumpRegister( this.Rd ), DumpRegister( this.Rm ), DumpRegister( this.Rn ) ); } } //--// public sealed class Opcode_Branch : Opcode { // // State // public int Offset; public bool IsLink; // // Constructor Methods // internal Opcode_Branch() { } //--// public void Prepare( uint ConditionCodes , int Offset , bool IsLink ) { base.Prepare( ConditionCodes ); this.Offset = Offset; this.IsLink = IsLink; } //--// public override void Decode( uint op ) { base.Decode( op ); this.Offset = s_Encoding.get_Branch_Offset( op ); this.IsLink = s_Encoding.get_Branch_IsLink( op ); } public override uint Encode() { uint op = base.Encode(); op |= s_Encoding.set_Branch_Offset( this.Offset ); op |= s_Encoding.set_Branch_IsLink( this.IsLink ); return op | EncDef.op_Branch; } public override void Print( InstructionSet owner , System.Text.StringBuilder str , uint opcodeAddress , ref uint target , ref bool targetIsCode ) { PrintMnemonic( str, "B{0}{1}", this.IsLink ? "L" : "", DumpCondition() ); target = (uint)(opcodeAddress + 8 + this.Offset); targetIsCode = true; str.AppendFormat( "0x{0:X8}", target ); } } public sealed class Opcode_BranchAndExchange : Opcode { // // State // public uint Rn; // // Constructor Methods // internal Opcode_BranchAndExchange() { } //--// public void Prepare( uint ConditionCodes , uint Rn ) { base.Prepare( ConditionCodes ); this.Rn = Rn; } //--// public override void Decode( uint op ) { base.Decode( op ); this.Rn = s_Encoding.get_Register4( op ); } public override uint Encode() { uint op = base.Encode(); op |= s_Encoding.set_Register4( this.Rn ); return op | EncDef.op_BranchAndExchange; } public override void Print( InstructionSet owner , System.Text.StringBuilder str , uint opcodeAddress , ref uint target , ref bool targetIsCode ) { PrintMnemonic( str, "BX{0}", DumpCondition() ); str.AppendFormat( "{0}", DumpRegister( this.Rn ) ); } } //--// public abstract class Opcode_DataTransfer : Opcode { // // State // public uint Rn; public bool IsLoad; public bool PreIndex; public bool Up; public bool WriteBack; //--// protected void Prepare( uint ConditionCodes , uint Rn , bool IsLoad , bool PreIndex , bool Up , bool WriteBack ) { base.Prepare( ConditionCodes ); this.Rn = Rn; this.IsLoad = IsLoad; this.PreIndex = PreIndex; this.Up = Up; this.WriteBack = WriteBack; } //--// public override void Decode( uint op ) { base.Decode( op ); this.Rn = s_Encoding.get_Register1 ( op ); this.IsLoad = s_Encoding.get_DataTransfer_IsLoad ( op ); this.PreIndex = s_Encoding.get_DataTransfer_IsPreIndexing ( op ); this.Up = s_Encoding.get_DataTransfer_IsUp ( op ); this.WriteBack = s_Encoding.get_DataTransfer_ShouldWriteBack( op ); } public override uint Encode() { uint op = base.Encode(); op |= s_Encoding.set_Register1 ( this.Rn ); op |= s_Encoding.set_DataTransfer_IsLoad ( this.IsLoad ); op |= s_Encoding.set_DataTransfer_IsPreIndexing ( this.PreIndex ); op |= s_Encoding.set_DataTransfer_IsUp ( this.Up ); op |= s_Encoding.set_DataTransfer_ShouldWriteBack( this.WriteBack ); return op; } } public abstract class Opcode_WordDataTransfer : Opcode_DataTransfer { // // State // public uint Rd; //--// protected void Prepare( uint ConditionCodes , uint Rn , bool IsLoad , bool PreIndex , bool Up , bool WriteBack , uint Rd ) { base.Prepare( ConditionCodes , Rn , IsLoad , PreIndex , Up , WriteBack ); this.Rd = Rd; } //--// public override void Decode( uint op ) { base.Decode( op ); this.Rd = s_Encoding.get_Register2( op ); } public override uint Encode() { uint op = base.Encode(); op |= s_Encoding.set_Register2( this.Rd ); return op; } } public abstract class Opcode_HalfwordDataTransfer : Opcode_WordDataTransfer { // // State // public uint Kind; //--// protected void Prepare( uint ConditionCodes , uint Rn , bool IsLoad , bool PreIndex , bool Up , bool WriteBack , uint Rd , uint Kind ) { base.Prepare( ConditionCodes , Rn , IsLoad , PreIndex , Up , WriteBack , Rd ); this.Kind = Kind; } //--// public override void Decode( uint op ) { base.Decode( op ); this.Kind = s_Encoding.get_HalfWordDataTransfer_Kind( op ); } public override uint Encode() { uint op = base.Encode(); op |= s_Encoding.set_HalfWordDataTransfer_Kind( this.Kind ); return op; } protected void PrintPre( System.Text.StringBuilder str ) { PrintMnemonic( str, "{0}{1}{2}", this.IsLoad ? "LDR" : "STR", DumpCondition(), DumpHalfWordKind( this.Kind ) ); str.AppendFormat( "{0},[{1}", DumpRegister( this.Rd ), DumpRegister( this.Rn ) ); if(PreIndex == false) str.Append( "]" ); } protected void PrintPost( System.Text.StringBuilder str ) { if(this.PreIndex) str.Append( "]" ); if(this.WriteBack) { str.Append( "!" ); } } } public sealed class Opcode_HalfwordDataTransfer_1 : Opcode_HalfwordDataTransfer { // // State // public uint Rm; // // Constructor Methods // internal Opcode_HalfwordDataTransfer_1() { } //--// public void Prepare( uint ConditionCodes , uint Rn , bool IsLoad , bool PreIndex , bool Up , bool WriteBack , uint Rd , uint Kind , uint Rm ) { base.Prepare( ConditionCodes , Rn , IsLoad , PreIndex , Up , WriteBack , Rd , Kind ); this.Rm = Rm; } //--// public override void Decode( uint op ) { base.Decode( op ); this.Rm = s_Encoding.get_Register4( op ); } public override uint Encode() { uint op = base.Encode(); op |= s_Encoding.set_Register4( this.Rm ); return op | EncDef.op_HalfwordDataTransfer_1; } public override void Print( InstructionSet owner , System.Text.StringBuilder str , uint opcodeAddress , ref uint target , ref bool targetIsCode ) { PrintPre( str ); str.AppendFormat( ",{0}{1}", this.Up ? "" : "-", DumpRegister( this.Rm ) ); PrintPost( str ); } } public sealed class Opcode_HalfwordDataTransfer_2 : Opcode_HalfwordDataTransfer { // // State // public uint Offset; // // Constructor Methods // internal Opcode_HalfwordDataTransfer_2() { } //--// public void Prepare( uint ConditionCodes , uint Rn , bool IsLoad , bool PreIndex , bool Up , bool WriteBack , uint Rd , uint Kind , uint Offset ) { base.Prepare( ConditionCodes , Rn , IsLoad , PreIndex , Up , WriteBack , Rd , Kind ); this.Offset = Offset; } //--// public override void Decode( uint op ) { base.Decode( op ); this.Offset = s_Encoding.get_HalfWordDataTransfer_Offset( op ); } public override uint Encode() { uint op = base.Encode(); op |= s_Encoding.set_HalfWordDataTransfer_Offset( this.Offset ); return op | EncDef.op_HalfwordDataTransfer_2; } public override void Print( InstructionSet owner , System.Text.StringBuilder str , uint opcodeAddress , ref uint target , ref bool targetIsCode ) { PrintPre( str ); str.AppendFormat( ",#{0}{1}", this.Up ? "" : "-", this.Offset ); PrintPost( str ); if(this.Rn == 15) { int address = (int)(opcodeAddress + 8); if(this.PreIndex) { address += (this.Up ? +(int)this.Offset : -(int)this.Offset); } target = (uint)address; str.AppendFormat( " ; 0x{0:X8}", target ); } } } public abstract class Opcode_SingleDataTransfer : Opcode_WordDataTransfer { // // State // public bool IsByte; //--// protected void Prepare( uint ConditionCodes , uint Rn , bool IsLoad , bool PreIndex , bool Up , bool WriteBack , uint Rd , bool IsByte ) { base.Prepare( ConditionCodes , Rn , IsLoad , PreIndex , Up , WriteBack , Rd ); this.IsByte = IsByte; } //--// public override void Decode( uint op ) { base.Decode( op ); this.IsByte = s_Encoding.get_DataTransfer_IsByteTransfer( op ); } public override uint Encode() { uint op = base.Encode(); op |= s_Encoding.set_DataTransfer_IsByteTransfer( this.IsByte ); return op; } protected void PrintPre( System.Text.StringBuilder str ) { if(this.IsPLD) { PrintMnemonic( str, "PLD" ); str.AppendFormat( "{0}", DumpRegister( this.Rn ) ); } else { PrintMnemonic( str, "{0}{1}{2}", this.IsLoad ? "LDR" : "STR", DumpCondition(), this.IsByte ? "B" : "" ); str.AppendFormat( "{0},[{1}", DumpRegister( this.Rd ), DumpRegister( this.Rn ) ); if(this.PreIndex == false) str.Append( "]" ); } } protected void PrintPost( System.Text.StringBuilder str ) { if(this.IsPLD) { } else { if(this.PreIndex) str.Append( "]" ); if(this.WriteBack) { str.Append( "!" ); } } } //--// public bool IsPLD { get { if( this.ConditionCodes == EncDef.c_cond_UNUSED && this.Rd == 0xF && this.IsLoad && this.PreIndex && !this.WriteBack ) { return true; } return false; } } } public sealed class Opcode_SingleDataTransfer_1 : Opcode_SingleDataTransfer { // // State // public uint Offset; // // Constructor Methods // internal Opcode_SingleDataTransfer_1() { } //--// public void Prepare( uint ConditionCodes , uint Rn , bool IsLoad , bool PreIndex , bool Up , bool WriteBack , uint Rd , bool IsByte , uint Offset ) { base.Prepare( ConditionCodes , Rn , IsLoad , PreIndex , Up , WriteBack , Rd , IsByte ); this.Offset = Offset; } //--// public override void Decode( uint op ) { base.Decode( op ); this.Offset = s_Encoding.get_DataTransfer_Offset( op ); } public override uint Encode() { uint op = base.Encode(); op |= s_Encoding.set_DataTransfer_Offset( this.Offset ); return op | EncDef.op_SingleDataTransfer_1; } public override void Print( InstructionSet owner , System.Text.StringBuilder str , uint opcodeAddress , ref uint target , ref bool targetIsCode ) { PrintPre( str ); if(this.Offset != 0) { str.AppendFormat( ",#{0}0x{1:X}", this.Up ? "" : "-", this.Offset ); } PrintPost( str ); if(this.Rn == 15) { int address = (int)(opcodeAddress + 8); if(this.PreIndex) { address += (this.Up ? +(int)this.Offset : -(int)this.Offset); } target = (uint)address; str.AppendFormat( " ; 0x{0:X8}", target ); } } } public abstract class Opcode_SingleDataTransfer_23 : Opcode_SingleDataTransfer { // // State // public uint Rm; public uint ShiftType; //--// protected void Prepare( uint ConditionCodes , uint Rn , bool IsLoad , bool PreIndex , bool Up , bool WriteBack , uint Rd , bool IsByte , uint Rm , uint ShiftType ) { base.Prepare( ConditionCodes , Rn , IsLoad , PreIndex , Up , WriteBack , Rd , IsByte ); this.Rm = Rm; this.ShiftType = ShiftType; } //--// public override void Decode( uint op ) { base.Decode( op ); this.Rm = s_Encoding.get_Register4 ( op ); this.ShiftType = s_Encoding.get_Shift_Type( op ); } public override uint Encode() { uint op = base.Encode(); op |= s_Encoding.set_Register4 ( this.Rm ); op |= s_Encoding.set_Shift_Type( this.ShiftType ); return op; } protected new void PrintPre( System.Text.StringBuilder str ) { base.PrintPre( str ); str.AppendFormat( ",{0}{1}", this.Up ? "" : "-", DumpRegister( this.Rm ) ); } protected new void PrintPost( System.Text.StringBuilder str ) { base.PrintPost( str ); } } public sealed class Opcode_SingleDataTransfer_2 : Opcode_SingleDataTransfer_23 { // // State // public uint ShiftValue; // // Constructor Methods // internal Opcode_SingleDataTransfer_2() { } //--// public void Prepare( uint ConditionCodes , uint Rn , bool IsLoad , bool PreIndex , bool Up , bool WriteBack , uint Rd , bool IsByte , uint Rm , uint ShiftType , uint ShiftValue ) { base.Prepare( ConditionCodes , Rn , IsLoad , PreIndex , Up , WriteBack , Rd , IsByte , Rm , ShiftType ); this.ShiftValue = ShiftValue; } //--// public override void Decode( uint op ) { base.Decode( op ); this.ShiftValue = s_Encoding.get_Shift_Immediate( op ); if(this.ShiftValue == 0) { switch(ShiftType) { case EncDef.c_shift_LSR: case EncDef.c_shift_ASR: this.ShiftValue = 32; break; case EncDef.c_shift_ROR: this.ShiftValue = 1; this.ShiftType = EncDef.c_shift_RRX; break; } } } public override uint Encode() { // // Save values. // uint shiftValue = this.ShiftValue; uint shiftType = this.ShiftType; switch(this.ShiftType) { case EncDef.c_shift_LSR: case EncDef.c_shift_ASR: if(this.ShiftValue == 32) { this.ShiftValue = 0; } break; case EncDef.c_shift_RRX: this.ShiftType = EncDef.c_shift_ROR; this.ShiftValue = 0; break; } uint op = base.Encode(); op |= s_Encoding.set_Shift_Immediate( this.ShiftValue ); // // Restore values. // this.ShiftValue = shiftValue; this.ShiftType = shiftType; return op | EncDef.op_SingleDataTransfer_2; } public override void Print( InstructionSet owner , System.Text.StringBuilder str , uint opcodeAddress , ref uint target , ref bool targetIsCode ) { PrintPre( str ); if(this.ShiftValue != 0) { str.AppendFormat( ",{0} #{1}", DumpShiftType( this.ShiftType ), this.ShiftValue ); } PrintPost( str ); } } public sealed class Opcode_SingleDataTransfer_3 : Opcode_SingleDataTransfer_23 { // // State // public uint Rs; // // Constructor Methods // internal Opcode_SingleDataTransfer_3() { } //--// public void Prepare( uint ConditionCodes , uint Rn , bool IsLoad , bool PreIndex , bool Up , bool WriteBack , uint Rd , bool IsByte , uint Rm , uint ShiftType , uint Rs ) { base.Prepare( ConditionCodes , Rn , IsLoad , PreIndex , Up , WriteBack , Rd , IsByte , Rm , ShiftType ); this.Rs = Rs; } //--// public override void Decode( uint op ) { base.Decode( op ); this.Rs = s_Encoding.get_Register3( op ); } public override uint Encode() { uint op = base.Encode(); op |= s_Encoding.set_Register3( this.Rs ); return op | EncDef.op_SingleDataTransfer_3; } public override void Print( InstructionSet owner , System.Text.StringBuilder str , uint opcodeAddress , ref uint target , ref bool targetIsCode ) { PrintPre( str ); str.AppendFormat( ",{0} {1}", DumpShiftType( this.ShiftType ), DumpRegister( this.Rs ) ); PrintPost( str ); } } public sealed class Opcode_BlockDataTransfer : Opcode_DataTransfer { // // State // public uint Lst; public bool LoadPSR; // // Constructor Methods // internal Opcode_BlockDataTransfer() { } //--// public void Prepare( uint ConditionCodes , uint Rn , bool IsLoad , bool PreIndex , bool Up , bool WriteBack , uint Lst , bool LoadPSR ) { base.Prepare( ConditionCodes , Rn , IsLoad , PreIndex , Up , WriteBack ); this.Lst = Lst; this.LoadPSR = LoadPSR; } //--// public override void Decode( uint op ) { base.Decode( op ); this.Lst = s_Encoding.get_BlockDataTransfer_RegisterList( op ); this.LoadPSR = s_Encoding.get_BlockDataTransfer_LoadPSR ( op ); } public override uint Encode() { uint op = base.Encode(); op |= s_Encoding.set_BlockDataTransfer_RegisterList( this.Lst ); op |= s_Encoding.set_BlockDataTransfer_LoadPSR ( this.LoadPSR ); return op | EncDef.op_BlockDataTransfer; } public override void Print( InstructionSet owner , System.Text.StringBuilder str , uint opcodeAddress , ref uint target , ref bool targetIsCode ) { char c1; char c2; if(this.Rn == 13) { if(this.IsLoad) { c1 = this.PreIndex ? 'E' : 'F'; c2 = this.Up ? 'D' : 'A'; } else { c1 = this.PreIndex ? 'F' : 'E'; c2 = this.Up ? 'A' : 'D'; } } else { c1 = this.Up ? 'I' : 'D'; c2 = this.PreIndex ? 'B' : 'A'; } PrintMnemonic( str, "{0}{1}{2}{3}", this.IsLoad ? "LDM" : "STM", c1, c2, DumpCondition() ); str.AppendFormat( "{0}{1},", DumpRegister( this.Rn ), this.WriteBack ? "!" : "" ); uint Rd = 0; uint lst = this.Lst; str.Append( "{" ); while(lst != 0) { while((lst & 1) == 0) { lst >>= 1; Rd++; } uint Rfirst = Rd; while((lst & 1) != 0) { lst >>= 1; Rd++; } str.AppendFormat( "{0}", DumpRegister( Rfirst ) ); if(Rd - Rfirst > 2) { str.AppendFormat( "-{0}", DumpRegister( Rd-1 ) ); } else if(Rd - Rfirst > 1) { str.AppendFormat( ",{0}", DumpRegister( Rd-1 ) ); } if(lst != 0) { str.Append( "," ); } } str.Append( "}" ); if(this.LoadPSR) { str.Append( "^" ); } } } public abstract class Opcode_Coproc : Opcode { // // State // public uint CpNum; // // Constructor Methods // protected Opcode_Coproc() { } //--// public void Prepare( uint ConditionCodes , uint CpNum ) { base.Prepare( ConditionCodes ); this.CpNum = CpNum; } //--// public override void Decode( uint op ) { base.Decode( op ); this.CpNum = s_Encoding.get_Coproc_CpNum( op ); } public override uint Encode() { uint op = base.Encode(); op |= s_Encoding.set_Coproc_CpNum( this.CpNum ); return op; } } public sealed class Opcode_CoprocDataTransfer : Opcode_Coproc { // // State // public bool IsLoad; public bool WriteBack; public bool Wide; public bool Up; public bool PreIndex; public uint Rn; public uint CRd; public uint Offset; // // Constructor Methods // internal Opcode_CoprocDataTransfer() { } //--// public void Prepare( uint ConditionCodes , bool IsLoad , bool WriteBack , bool Wide , bool Up , bool PreIndex , uint CpNum , uint Rn , uint CRd , uint Offset ) { base.Prepare( ConditionCodes, CpNum ); this.IsLoad = IsLoad; this.WriteBack = WriteBack; this.Wide = Wide; this.Up = Up; this.PreIndex = PreIndex; this.Rn = Rn; this.CRd = CRd; this.Offset = Offset; } //--// public override void Decode( uint op ) { base.Decode( op ); this.IsLoad = s_Encoding.get_CoprocDataTransfer_IsLoad ( op ); this.WriteBack = s_Encoding.get_CoprocDataTransfer_ShouldWriteBack( op ); this.Wide = s_Encoding.get_CoprocDataTransfer_IsWide ( op ); this.Up = s_Encoding.get_CoprocDataTransfer_IsUp ( op ); this.PreIndex = s_Encoding.get_CoprocDataTransfer_IsPreIndexing ( op ); this.Rn = s_Encoding.get_CoprocDataTransfer_Rn ( op ); this.CRd = s_Encoding.get_CoprocDataTransfer_CRd ( op ); this.Offset = s_Encoding.get_CoprocDataTransfer_Offset ( op ); } public override uint Encode() { uint op = base.Encode(); op |= s_Encoding.set_CoprocDataTransfer_IsLoad ( this.IsLoad ); op |= s_Encoding.set_CoprocDataTransfer_ShouldWriteBack( this.WriteBack ); op |= s_Encoding.set_CoprocDataTransfer_IsWide ( this.Wide ); op |= s_Encoding.set_CoprocDataTransfer_IsUp ( this.Up ); op |= s_Encoding.set_CoprocDataTransfer_IsPreIndexing ( this.PreIndex ); op |= s_Encoding.set_CoprocDataTransfer_Rn ( this.Rn ); op |= s_Encoding.set_CoprocDataTransfer_CRd ( this.CRd ); op |= s_Encoding.set_CoprocDataTransfer_Offset ( this.Offset ); return op | EncDef.op_CoprocDataTransfer; } public override void Print( InstructionSet owner , System.Text.StringBuilder str , uint opcodeAddress , ref uint target , ref bool targetIsCode ) { if(this.IsLoad) { PrintMnemonic( str, "LDC{0}", DumpCondition() ); } else { PrintMnemonic( str, "STC{0}", DumpCondition() ); } str.AppendFormat( "CP{0}, P={1}, U={2}, N={3}, W={4}, C{5}, {6}, 0x{7}", this.CpNum, this.PreIndex ? 1 : 0, this.Up ? 1 : 0, this.Wide ? 1 : 0, this.WriteBack ? 1 : 0, this.CRd, DumpRegister( this.Rn ), this.Offset ); } } public sealed class Opcode_CoprocDataOperation : Opcode_Coproc { // // State // public uint Op1; public uint Op2; public uint CRn; public uint CRm; public uint CRd; // // Constructor Methods // internal Opcode_CoprocDataOperation() { } //--// public void Prepare( uint ConditionCodes , uint Op1 , uint Op2 , uint CpNum , uint CRn , uint CRm , uint CRd ) { base.Prepare( ConditionCodes, CpNum ); this.Op1 = Op1; this.Op2 = Op2; this.CRn = CRn; this.CRm = CRm; this.CRd = CRd; } //--// public override void Decode( uint op ) { base.Decode( op ); this.Op1 = s_Encoding.get_CoprocDataOperation_Op1( op ); this.Op2 = s_Encoding.get_CoprocDataOperation_Op2( op ); this.CRn = s_Encoding.get_CoprocDataOperation_CRn( op ); this.CRm = s_Encoding.get_CoprocDataOperation_CRm( op ); this.CRd = s_Encoding.get_CoprocDataOperation_CRd( op ); } public override uint Encode() { uint op = base.Encode(); op |= s_Encoding.set_CoprocDataOperation_Op1( this.Op1 ); op |= s_Encoding.set_CoprocDataOperation_Op2( this.Op2 ); op |= s_Encoding.set_CoprocDataOperation_CRn( this.CRn ); op |= s_Encoding.set_CoprocDataOperation_CRm( this.CRm ); op |= s_Encoding.set_CoprocDataOperation_CRd( this.CRd ); return op | EncDef.op_CoprocDataOperation; } public override void Print( InstructionSet owner , System.Text.StringBuilder str , uint opcodeAddress , ref uint target , ref bool targetIsCode ) { str.AppendFormat( "CDP CP{0},0x{1},C{2},C{3},C{4},0x{5}", this.CpNum, this.Op1, this.CRd, this.CRn, this.CRm, this.Op2 ); } } public sealed class Opcode_CoprocRegisterTransfer : Opcode_Coproc { // // State // public bool IsMRC; public uint Op1; public uint Op2; public uint CRn; public uint CRm; public uint Rd; // // Constructor Methods // internal Opcode_CoprocRegisterTransfer() { } //--// public void Prepare( uint ConditionCodes , bool IsMRC , uint Op1 , uint Op2 , uint CpNum , uint CRn , uint CRm , uint Rd ) { base.Prepare( ConditionCodes, CpNum ); this.IsMRC = IsMRC; this.Op1 = Op1; this.Op2 = Op2; this.CRn = CRn; this.CRm = CRm; this.Rd = Rd; } //--// public override void Decode( uint op ) { base.Decode( op ); this.IsMRC = s_Encoding.get_CoprocRegisterTransfer_IsMRC( op ); this.Op1 = s_Encoding.get_CoprocRegisterTransfer_Op1 ( op ); this.Op2 = s_Encoding.get_CoprocRegisterTransfer_Op2 ( op ); this.CRn = s_Encoding.get_CoprocRegisterTransfer_CRn ( op ); this.CRm = s_Encoding.get_CoprocRegisterTransfer_CRm ( op ); this.Rd = s_Encoding.get_CoprocRegisterTransfer_Rd ( op ); } public override uint Encode() { uint op = base.Encode(); op |= s_Encoding.set_CoprocRegisterTransfer_IsMRC( this.IsMRC ); op |= s_Encoding.set_CoprocRegisterTransfer_Op1 ( this.Op1 ); op |= s_Encoding.set_CoprocRegisterTransfer_Op2 ( this.Op2 ); op |= s_Encoding.set_CoprocRegisterTransfer_CRn ( this.CRn ); op |= s_Encoding.set_CoprocRegisterTransfer_CRm ( this.CRm ); op |= s_Encoding.set_CoprocRegisterTransfer_Rd ( this.Rd ); return op | EncDef.op_CoprocRegisterTransfer; } public override void Print( InstructionSet owner , System.Text.StringBuilder str , uint opcodeAddress , ref uint target , ref bool targetIsCode ) { if(this.IsMRC) { PrintMnemonic( str, "MRC{0}", DumpCondition() ); } else { PrintMnemonic( str, "MCR{0}", DumpCondition() ); } str.AppendFormat( "CP{0},0x{1},{2},C{3},C{4},0x{5}", this.CpNum, this.Op1, DumpRegister( this.Rd ), this.CRn, this.CRm, this.Op2 ); } } public sealed class Opcode_SoftwareInterrupt : Opcode { // // State // public uint Value; // // Constructor Methods // internal Opcode_SoftwareInterrupt() { } //--// public void Prepare( uint ConditionCodes , uint Value ) { base.Prepare( ConditionCodes ); this.Value = Value; } //--// public override void Decode( uint op ) { base.Decode( op ); this.Value = s_Encoding.get_SoftwareInterrupt_Immediate( op ); } public override uint Encode() { uint op = base.Encode(); op |= s_Encoding.set_SoftwareInterrupt_Immediate( this.Value ); return op | EncDef.op_SoftwareInterrupt; } public override void Print( InstructionSet owner , System.Text.StringBuilder str , uint opcodeAddress , ref uint target , ref bool targetIsCode ) { PrintMnemonic( str, "SWI{0}", DumpCondition() ); str.AppendFormat( "#0x{0:X6}", this.Value ); } } public sealed class Opcode_Breakpoint : Opcode { // // State // public uint Value; // // Constructor Methods // internal Opcode_Breakpoint() { } //--// public void Prepare( uint ConditionCodes , uint Value ) { base.Prepare( ConditionCodes ); this.Value = Value; } //--// public override void Decode( uint op ) { base.Decode( op ); this.Value = s_Encoding.get_Breakpoint_Immediate( op ); } public override uint Encode() { uint op = s_Encoding.set_Breakpoint_Immediate( this.Value ); return op | EncDef.op_Breakpoint; } public override void Print( InstructionSet owner , System.Text.StringBuilder str , uint opcodeAddress , ref uint target , ref bool targetIsCode ) { PrintMnemonic( str, "BKPT" ); str.AppendFormat( "#0x{0:X6}", this.Value ); } } } } ================================================ FILE: Zelig/Zelig/CompileTime/TargetModels/ArmProcessor/InstructionSetVersion.cs ================================================ using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace Microsoft.Zelig.TargetModel.ArmProcessor { public class InstructionSetVersion { // // Platforms // public const string CodeGenerator_Zelig = "Zelig"; public const string CodeGenerator_LLVM = "LLVM"; // // Platform descriptors fields: fields in the same group are mutually exclusive // // // Platforms // public const uint Platform_Family__ARM = 0x01000000; public const uint Platform_Family__Cortex = 0x02000000; public const uint Platform_Family__Mask = 0xFF000000; // // Platform Version // public const uint Platform_Version__ARMv4 = 0x00000001; public const uint Platform_Version__ARMv5 = 0x00000002; public const uint Platform_Version__ARMv6M = 0x00000004; public const uint Platform_Version__ARMv7M = 0x00000008; public const uint Platform_Version__ARMv7R = 0x00000010; public const uint Platform_Version__ARMv7A = 0x00000020; public const uint Platform_Version__x86 = 0x00000100; public const uint Platform_Version__ARMv7_all = 0x00000038; public const uint Platform_Version__ARM_legacy = 0x00000003; public const uint Platform_Version__Mask = 0x0000FFFF; // // Platform VFP Version // public const uint Platform_VFP__NoVFP = 0x00010000; public const uint Platform_VFP__SoftVFP = 0x00020000; public const uint Platform_VFP__HardVFP = 0x00040000; public const uint Platform_VFP__Mask = 0x00FF0000; //--// // // State // private uint m_platformDescriptor; // // Constructor Methods // public static InstructionSetVersion ARM { get { return new InstructionSetVersion( Platform_Family__ARM ); } } public static InstructionSetVersion Cortex { get { return new InstructionSetVersion( Platform_Family__Cortex ); } } public static InstructionSetVersion Build( uint descriptor ) { return new InstructionSetVersion( descriptor ); } public InstructionSetVersion With( uint descriptor ) { m_platformDescriptor |= descriptor; ValidateDescriptor( descriptor ); return this; } private InstructionSetVersion( uint descriptor ) { m_platformDescriptor = descriptor; } public uint PlatformFamily { get { return m_platformDescriptor & Platform_Family__Mask; } } public uint PlatformVersion { get { return m_platformDescriptor & Platform_Version__Mask; } } public uint PlatformVFPSupport { get { return m_platformDescriptor & Platform_VFP__Mask; } } // // IEquals // public override bool Equals(object obj) { InstructionSetVersion match = obj as InstructionSetVersion; if(match != null) { return m_platformDescriptor == match.m_platformDescriptor; } return false; } public override int GetHashCode() { return base.GetHashCode(); } //--// private void ValidateDescriptor( uint descriptor ) { // // it is OK to set the same descriptor twice, but it is not OK to change fields // uint family = descriptor & Platform_Family__Mask; uint version = descriptor & Platform_Version__Mask; uint vfp = descriptor & Platform_VFP__Mask; uint familyCurrent = m_platformDescriptor & Platform_Family__Mask; uint versionCurrent = m_platformDescriptor & Platform_Version__Mask; uint vfpCurrent = m_platformDescriptor & Platform_VFP__Mask; if( family != 0 && family != familyCurrent || version != 0 && version != versionCurrent || vfp != 0 && vfp != vfpCurrent ) { throw new ArgumentException( String.Format( "Descriptor {0} is incompatible with current values {1}", descriptor, m_platformDescriptor ) ); } } } } ================================================ FILE: Zelig/Zelig/CompileTime/TargetModels/ArmProcessor/InstructionSet_VFP.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // //#define VERIFY_INSTRUCTIONSET_VFP namespace Microsoft.Zelig.TargetModel.ArmProcessor { using EncDef = Microsoft.Zelig.TargetModel.ArmProcessor.EncodingDefinition_VFP_ARM; public class InstructionSet_VFP : InstructionSet { private static EncodingDefinition_VFP_ARM s_EncodingVFP = (EncodingDefinition_VFP_ARM)CurrentInstructionSetEncoding.GetVFPEncoding(); // // State // private Opcode_VFP_DataTransfer m_DataTransfer; private Opcode_VFP_BlockDataTransfer m_BlockDataTransfer; private Opcode_VFP_ConditionCodeTransfer m_ConditionCodeTransfer; private Opcode_VFP_SystemRegisterTransfer m_SystemRegisterTransfer; private Opcode_VFP_64bitRegisterTransfer m_64bitRegisterTransfer; private Opcode_VFP_32bitRegisterTransfer m_32bitRegisterTransfer; private Opcode_VFP_32bitLoRegisterTransfer m_32bitLoRegisterTransfer; private Opcode_VFP_32bitHiRegisterTransfer m_32bitHiRegisterTransfer; private Opcode_VFP_CompareToZero m_CompareToZero; private Opcode_VFP_ConvertFloatToFloat m_ConvertFloatToFloat; private Opcode_VFP_UnaryDataOperation m_UnaryDataOperation; private Opcode_VFP_BinaryDataOperation m_BinaryDataOperation; // // Constructor Methods // public InstructionSet_VFP( InstructionSetVersion version ) : base(version) { m_DataTransfer = new Opcode_VFP_DataTransfer (); m_BlockDataTransfer = new Opcode_VFP_BlockDataTransfer (); m_ConditionCodeTransfer = new Opcode_VFP_ConditionCodeTransfer (); m_SystemRegisterTransfer = new Opcode_VFP_SystemRegisterTransfer (); m_64bitRegisterTransfer = new Opcode_VFP_64bitRegisterTransfer (); m_32bitRegisterTransfer = new Opcode_VFP_32bitRegisterTransfer (); m_32bitLoRegisterTransfer = new Opcode_VFP_32bitLoRegisterTransfer(); m_32bitHiRegisterTransfer = new Opcode_VFP_32bitHiRegisterTransfer(); m_CompareToZero = new Opcode_VFP_CompareToZero (); m_ConvertFloatToFloat = new Opcode_VFP_ConvertFloatToFloat (); m_UnaryDataOperation = new Opcode_VFP_UnaryDataOperation (); m_BinaryDataOperation = new Opcode_VFP_BinaryDataOperation (); } //--// // // Helper Methods // public Opcode_VFP_DataTransfer PrepareForVFP_DataTransfer { get { return m_DataTransfer ; } } public Opcode_VFP_BlockDataTransfer PrepareForVFP_BlockDataTransfer { get { return m_BlockDataTransfer ; } } public Opcode_VFP_ConditionCodeTransfer PrepareForVFP_ConditionCodeTransfer { get { return m_ConditionCodeTransfer ; } } public Opcode_VFP_SystemRegisterTransfer PrepareForVFP_SystemRegisterTransfer { get { return m_SystemRegisterTransfer ; } } public Opcode_VFP_64bitRegisterTransfer PrepareForVFP_64bitRegisterTransfer { get { return m_64bitRegisterTransfer ; } } public Opcode_VFP_32bitRegisterTransfer PrepareForVFP_32bitRegisterTransfer { get { return m_32bitRegisterTransfer ; } } public Opcode_VFP_32bitLoRegisterTransfer PrepareForVFP_32bitLoRegisterTransfer { get { return m_32bitLoRegisterTransfer; } } public Opcode_VFP_32bitHiRegisterTransfer PrepareForVFP_32bitHiRegisterTransfer { get { return m_32bitHiRegisterTransfer; } } public Opcode_VFP_CompareToZero PrepareForVFP_CompareToZero { get { return m_CompareToZero ; } } public Opcode_VFP_ConvertFloatToFloat PrepareForVFP_ConvertFloatToFloat { get { return m_ConvertFloatToFloat ; } } public Opcode_VFP_UnaryDataOperation PrepareForVFP_UnaryDataOperation { get { return m_UnaryDataOperation ; } } public Opcode_VFP_BinaryDataOperation PrepareForVFP_BinaryDataOperation { get { return m_BinaryDataOperation ; } } //--// public override Opcode Decode( uint op ) { Opcode opcode = null; if ((op & EncDef.opmask_ConditionCodeTransfer ) == EncDef.op_ConditionCodeTransfer ) opcode = m_ConditionCodeTransfer ; else if((op & EncDef.opmask_SystemRegisterTransfer ) == EncDef.op_SystemRegisterTransfer ) opcode = m_SystemRegisterTransfer ; else if((op & EncDef.opmask_32bitLoRegisterTransfer) == EncDef.op_32bitLoRegisterTransfer) opcode = m_32bitLoRegisterTransfer; else if((op & EncDef.opmask_32bitHiRegisterTransfer) == EncDef.op_32bitHiRegisterTransfer) opcode = m_32bitHiRegisterTransfer; else if((op & EncDef.opmask_32bitRegisterTransfer ) == EncDef.op_32bitRegisterTransfer ) opcode = m_32bitRegisterTransfer ; else if((op & EncDef.opmask_64bitRegisterTransfer ) == EncDef.op_64bitRegisterTransfer ) opcode = m_64bitRegisterTransfer ; else if((op & EncDef.opmask_DataTransfer ) == EncDef.op_DataTransfer ) opcode = m_DataTransfer ; else if((op & EncDef.opmask_CompareToZero ) == EncDef.op_CompareToZero ) opcode = m_CompareToZero ; else if((op & EncDef.opmask_ConvertFloatToFloat ) == EncDef.op_ConvertFloatToFloat ) opcode = m_ConvertFloatToFloat ; else if((op & EncDef.opmask_UnaryDataOperation ) == EncDef.op_UnaryDataOperation ) opcode = m_UnaryDataOperation ; else if((op & EncDef.opmask_BinaryDataOperation ) == EncDef.op_BinaryDataOperation ) opcode = m_BinaryDataOperation ; else if((op & EncDef.opmask_BlockDataTransfer ) == EncDef.op_BlockDataTransfer ) opcode = m_BlockDataTransfer ; if(opcode != null) { opcode.Decode( op ); return opcode; } return base.Decode( op ); } // // Debug Methods // #if VERIFY_INSTRUCTIONSET_VFP class Data { public string Name; public uint Opcode; } static Data[] c_Data = new Data[] { new Data { Name = "FCPYS" , Opcode = 0xeeb00a40 }, new Data { Name = "FMRS" , Opcode = 0xee100a10 }, new Data { Name = "FMSR" , Opcode = 0xee000a10 }, new Data { Name = "FMSTAT" , Opcode = 0xeef1fa10 }, new Data { Name = "FSITOS" , Opcode = 0xeeb80ac0 }, new Data { Name = "FUITOS" , Opcode = 0xeeb80a40 }, new Data { Name = "FTOSIS" , Opcode = 0xeebd0a40 }, new Data { Name = "FTOSIZS", Opcode = 0xeebd0ac0 }, new Data { Name = "FTOUIS" , Opcode = 0xeebc0a40 }, new Data { Name = "FTOUIZS", Opcode = 0xeebc0ac0 }, new Data { Name = "FMRX" , Opcode = 0xeef00a10 }, new Data { Name = "FMXR" , Opcode = 0xeee00a10 }, new Data { Name = "FLDS" , Opcode = 0xed100a00 }, new Data { Name = "FSTS" , Opcode = 0xed000a00 }, new Data { Name = "FLDMIAS", Opcode = 0xec900a00 }, new Data { Name = "FLDMDBS", Opcode = 0xed300a00 }, //// new Data { Name = "FLDMIAX", Opcode = 0xec900b00 }, //// new Data { Name = "FLDMDBX", Opcode = 0xed300b00 }, new Data { Name = "FSTMIAS", Opcode = 0xec800a00 }, new Data { Name = "FSTMDBS", Opcode = 0xed200a00 }, //// new Data { Name = "FSTMIAX", Opcode = 0xec800b00 }, //// new Data { Name = "FSTMDBX", Opcode = 0xed200b00 }, new Data { Name = "FABSS" , Opcode = 0xeeb00ac0 }, new Data { Name = "FNEGS" , Opcode = 0xeeb10a40 }, new Data { Name = "FSQRTS" , Opcode = 0xeeb10ac0 }, new Data { Name = "FADDS" , Opcode = 0xee300a00 }, new Data { Name = "FSUBS" , Opcode = 0xee300a40 }, new Data { Name = "FMULS" , Opcode = 0xee200a00 }, new Data { Name = "FDIVS" , Opcode = 0xee800a00 }, new Data { Name = "FMACS" , Opcode = 0xee000a00 }, new Data { Name = "FMSCS" , Opcode = 0xee100a00 }, new Data { Name = "FNMULS" , Opcode = 0xee200a40 }, new Data { Name = "FNMACS" , Opcode = 0xee000a40 }, new Data { Name = "FNMSCS" , Opcode = 0xee100a40 }, new Data { Name = "FCMPS" , Opcode = 0xeeb40a40 }, new Data { Name = "FCMPZS" , Opcode = 0xeeb50a40 }, new Data { Name = "FCMPES" , Opcode = 0xeeb40ac0 }, new Data { Name = "FCMPEZS", Opcode = 0xeeb50ac0 }, new Data { Name = "FCPYD" , Opcode = 0xeeb00b40 }, new Data { Name = "FCVTDS" , Opcode = 0xeeb70ac0 }, new Data { Name = "FCVTSD" , Opcode = 0xeeb70bc0 }, new Data { Name = "FMDHR" , Opcode = 0xee200b10 }, new Data { Name = "FMDLR" , Opcode = 0xee000b10 }, new Data { Name = "FMRDH" , Opcode = 0xee300b10 }, new Data { Name = "FMRDL" , Opcode = 0xee100b10 }, new Data { Name = "FSITOD" , Opcode = 0xeeb80bc0 }, new Data { Name = "FUITOD" , Opcode = 0xeeb80b40 }, new Data { Name = "FTOSID" , Opcode = 0xeebd0b40 }, new Data { Name = "FTOSIZD", Opcode = 0xeebd0bc0 }, new Data { Name = "FTOUID" , Opcode = 0xeebc0b40 }, new Data { Name = "FTOUIZD", Opcode = 0xeebc0bc0 }, new Data { Name = "FLDD" , Opcode = 0xed100b00 }, new Data { Name = "FSTD" , Opcode = 0xed000b00 }, new Data { Name = "FLDMIAD", Opcode = 0xec900b00 }, new Data { Name = "FLDMDBD", Opcode = 0xed300b00 }, new Data { Name = "FSTMIAD", Opcode = 0xec800b00 }, new Data { Name = "FSTMDBD", Opcode = 0xed200b00 }, new Data { Name = "FABSD" , Opcode = 0xeeb00bc0 }, new Data { Name = "FNEGD" , Opcode = 0xeeb10b40 }, new Data { Name = "FSQRTD" , Opcode = 0xeeb10bc0 }, new Data { Name = "FADDD" , Opcode = 0xee300b00 }, new Data { Name = "FSUBD" , Opcode = 0xee300b40 }, new Data { Name = "FMULD" , Opcode = 0xee200b00 }, new Data { Name = "FDIVD" , Opcode = 0xee800b00 }, new Data { Name = "FMACD" , Opcode = 0xee000b00 }, new Data { Name = "FMSCD" , Opcode = 0xee100b00 }, new Data { Name = "FNMULD" , Opcode = 0xee200b40 }, new Data { Name = "FNMACD" , Opcode = 0xee000b40 }, new Data { Name = "FNMSCD" , Opcode = 0xee100b40 }, new Data { Name = "FCMPD" , Opcode = 0xeeb40b40 }, new Data { Name = "FCMPZD" , Opcode = 0xeeb50b40 }, new Data { Name = "FCMPED" , Opcode = 0xeeb40bc0 }, new Data { Name = "FCMPEZD", Opcode = 0xeeb50bc0 }, new Data { Name = "FMSRR" , Opcode = 0xec400a10 }, new Data { Name = "FMRRS" , Opcode = 0xec500a10 }, new Data { Name = "FMDRR" , Opcode = 0xec400b10 }, new Data { Name = "FMRRD" , Opcode = 0xec500b10 }, }; public void TestCompliance() { System.Text.StringBuilder str = new System.Text.StringBuilder(); InstructionSet.Opcode op; foreach(Data d in c_Data) { op = this.Decode( d.Opcode ); if(op == null) { throw IncorrectEncodingException.Create( "Cannot decode {0,9} [0x{1:X8}]", d.Name, d.Opcode ); } else { uint target = 0; bool targetIsCode = false; op.Print( this, str, 0, ref target, ref targetIsCode ); if(d.Name != str.ToString().Split( ' ' )[0]) { throw IncorrectEncodingException.Create( "Incorrect decoding {0,9} [0x{1:X8}]: got {2}", d.Name, d.Opcode, str ); } str.Length = 0; } } } #endif //--// public abstract class Opcode_VFP_Flavor : Opcode { // // State // public bool IsDouble; //--// protected void Prepare( uint ConditionCodes , bool IsDouble ) { base.Prepare( ConditionCodes ); this.IsDouble = IsDouble; } //--// public override void Decode( uint op ) { base.Decode( op ); this.IsDouble = s_EncodingVFP.get_IsDouble( op ); } public override uint Encode() { uint op = base.Encode(); op |= s_EncodingVFP.set_IsDouble( this.IsDouble ); return op; } //--// public static string DumpRegister( uint reg , bool isDouble ) { if(isDouble) { switch(reg) { case 0 : return "d0"; case 2 : return "d1"; case 4 : return "d2"; case 6 : return "d3"; case 8 : return "d4"; case 10: return "d5"; case 12: return "d6"; case 14: return "d7"; case 16: return "d8"; case 18: return "d9"; case 20: return "d10"; case 22: return "d11"; case 24: return "d12"; case 26: return "d13"; case 28: return "d14"; case 30: return "d15"; } } else { switch(reg) { case 0 : return "s0"; case 1 : return "s1"; case 2 : return "s2"; case 3 : return "s3"; case 4 : return "s4"; case 5 : return "s5"; case 6 : return "s6"; case 7 : return "s7"; case 8 : return "s8"; case 9 : return "s9"; case 10: return "s10"; case 11: return "s11"; case 12: return "s12"; case 13: return "s13"; case 14: return "s14"; case 15: return "s15"; case 16: return "s16"; case 17: return "s17"; case 18: return "s18"; case 19: return "s19"; case 20: return "s20"; case 21: return "s21"; case 22: return "s22"; case 23: return "s23"; case 24: return "s24"; case 25: return "s25"; case 26: return "s26"; case 27: return "s27"; case 28: return "s28"; case 29: return "s29"; case 30: return "s30"; case 31: return "s31"; } } return "??"; } } public abstract class Opcode_VFP_BaseDataTransfer : Opcode_VFP_Flavor { // // State // public uint Rn; public uint Fd; public bool IsLoad; public bool Up; public uint Offset; //--// protected void Prepare( uint ConditionCodes , bool IsDouble , uint Rn , uint Fd , bool IsLoad , bool Up , uint Offset ) { base.Prepare( ConditionCodes, IsDouble ); this.Rn = Rn; this.Fd = Fd; this.IsLoad = IsLoad; this.Up = Up; this.Offset = Offset; } //--// public override void Decode( uint op ) { base.Decode( op ); this.Rn = s_EncodingVFP.get_Rn ( op ); this.Fd = s_EncodingVFP.get_Fd ( op ); this.IsLoad = s_EncodingVFP.get_DataTransfer_IsLoad( op ); this.Up = s_EncodingVFP.get_DataTransfer_IsUp ( op ); this.Offset = s_EncodingVFP.get_DataTransfer_Offset( op ); } public override uint Encode() { uint op = base.Encode(); op |= s_EncodingVFP.set_Rn ( this.Rn ); op |= s_EncodingVFP.set_Fd ( this.Fd ); op |= s_EncodingVFP.set_DataTransfer_IsLoad( this.IsLoad ); op |= s_EncodingVFP.set_DataTransfer_IsUp ( this.Up ); op |= s_EncodingVFP.set_DataTransfer_Offset( this.Offset ); return op; } } public sealed class Opcode_VFP_DataTransfer : Opcode_VFP_BaseDataTransfer { // // Constructor Methods // internal Opcode_VFP_DataTransfer() { } //--// public new void Prepare( uint ConditionCodes , bool IsDouble , uint Rn , uint Fd , bool IsLoad , bool Up , uint Offset ) { base.Prepare( ConditionCodes, IsDouble, Rn, Fd, IsLoad, Up, Offset ); } public override uint Encode() { uint op = base.Encode(); return op | EncDef.op_DataTransfer; } public override void Print( InstructionSet owner , System.Text.StringBuilder str , uint opcodeAddress , ref uint target , ref bool targetIsCode ) { PrintMnemonic( str, "{0}{1}{2}", this.IsLoad ? "FLD" : "FST", this.IsDouble ? "D" : "S", DumpCondition() ); str.AppendFormat( "{0},[{1}", DumpRegister( this.Fd, this.IsDouble ), DumpRegister( this.Rn ) ); if(this.Offset != 0) { str.AppendFormat( ",#{0}0x{1:X}", this.Up ? "" : "-", this.Offset * 4 ); } str.Append( "]" ); } } public sealed class Opcode_VFP_BlockDataTransfer : Opcode_VFP_BaseDataTransfer { // // State // public bool PreIndex; public bool WriteBack; // // Constructor Methods // internal Opcode_VFP_BlockDataTransfer() { } //--// public void Prepare( uint ConditionCodes , bool IsDouble , uint Rn , uint Fd , bool IsLoad , bool PreIndex , bool Up , bool WriteBack , uint Count ) { base.Prepare( ConditionCodes, IsDouble, Rn, Fd, IsLoad, Up, Count ); this.PreIndex = PreIndex; this.WriteBack = WriteBack; } public override void Decode( uint op ) { base.Decode( op ); this.PreIndex = s_EncodingVFP.get_DataTransfer_IsPreIndexing ( op ); this.WriteBack = s_EncodingVFP.get_DataTransfer_ShouldWriteBack( op ); } public override uint Encode() { uint op = base.Encode(); op |= s_EncodingVFP.set_DataTransfer_IsPreIndexing ( this.PreIndex ); op |= s_EncodingVFP.set_DataTransfer_ShouldWriteBack( this.WriteBack ); return op | EncDef.op_BlockDataTransfer; } public override void Print( InstructionSet owner , System.Text.StringBuilder str , uint opcodeAddress , ref uint target , ref bool targetIsCode ) { char c1; char c2; if(this.Rn == 13) { if(this.IsLoad) { c1 = this.PreIndex ? 'E' : 'F'; c2 = this.Up ? 'D' : 'A'; } else { c1 = this.PreIndex ? 'F' : 'E'; c2 = this.Up ? 'A' : 'D'; } } else { c1 = this.Up ? 'I' : 'D'; c2 = this.PreIndex ? 'B' : 'A'; } PrintMnemonic( str, "{0}{1}{2}{3}{4}", this.IsLoad ? "FLDM" : "FSTM", c1, c2, this.IsDouble ? "D" : "S", DumpCondition() ); str.AppendFormat( "{0}{1},", DumpRegister( this.Rn ), this.WriteBack ? "!" : "" ); str.Append( "{" ); for(uint pos = 0; pos < this.Offset; pos += this.IsDouble ? 2u : 1u) { if(pos != 0) { str.Append( "," ); } str.AppendFormat( "{0}", DumpRegister( this.Fd + pos, this.IsDouble ) ); } str.Append( "}" ); } } public sealed class Opcode_VFP_ConditionCodeTransfer : Opcode { // // Constructor Methods // internal Opcode_VFP_ConditionCodeTransfer() { } //--// public new void Prepare( uint ConditionCodes ) { base.Prepare( ConditionCodes ); } public override uint Encode() { uint op = base.Encode(); return op | EncDef.op_ConditionCodeTransfer; } public override void Print( InstructionSet owner , System.Text.StringBuilder str , uint opcodeAddress , ref uint target , ref bool targetIsCode ) { PrintMnemonic( str, "{0}{1}", "FMSTAT", DumpCondition() ); } } public abstract class Opcode_VFP_BaseRegisterTransfer : Opcode_VFP_Flavor { // // State // public uint Rd; public bool IsFromCoProc; //--// protected void Prepare( uint ConditionCodes , bool IsDouble , uint Rd , bool IsFromCoProc ) { base.Prepare( ConditionCodes, IsDouble ); this.Rd = Rd; this.IsFromCoProc = IsFromCoProc; } //--// public override void Decode( uint op ) { base.Decode( op ); this.Rd = s_EncodingVFP.get_Rd ( op ); this.IsFromCoProc = s_EncodingVFP.get_RegisterTransfer_IsFromCoproc( op ); } public override uint Encode() { uint op = base.Encode(); op |= s_EncodingVFP.set_Rd ( this.Rd ); op |= s_EncodingVFP.set_RegisterTransfer_IsFromCoproc( this.IsFromCoProc ); return op; } } public sealed class Opcode_VFP_SystemRegisterTransfer : Opcode_VFP_BaseRegisterTransfer { // // State // public uint SysReg; // // Constructor Methods // internal Opcode_VFP_SystemRegisterTransfer() { } //--// public void Prepare( uint ConditionCodes , uint Rd , uint SysReg , bool IsFromCoProc ) { base.Prepare( ConditionCodes, false, Rd, IsFromCoProc ); this.SysReg = SysReg; } //--// public override void Decode( uint op ) { base.Decode( op ); this.SysReg = s_EncodingVFP.get_SysReg( op ); } public override uint Encode() { uint op = base.Encode(); op |= s_EncodingVFP.set_SysReg( this.SysReg ); return op | EncDef.op_SystemRegisterTransfer; } public override void Print( InstructionSet owner , System.Text.StringBuilder str , uint opcodeAddress , ref uint target , ref bool targetIsCode ) { PrintMnemonic( str, "{0}{1}", this.IsFromCoProc ? "FMRX" : "FMXR", DumpCondition() ); str.AppendFormat( this.IsFromCoProc ? "{0},{1}" : "{1},{0}", DumpRegister( this.Rd ), DumpSystemRegister( this.SysReg ) ); } private static string DumpSystemRegister( uint reg ) { switch(reg) { case EncDef.c_systemRegister_FPSID: return "FPSID"; case EncDef.c_systemRegister_FPSCR: return "FPSCR"; case EncDef.c_systemRegister_FPEXC: return "FPEXC"; } return "??"; } } public sealed class Opcode_VFP_64bitRegisterTransfer : Opcode_VFP_BaseRegisterTransfer { // // State // public uint Rn; public uint Fm; // // Constructor Methods // internal Opcode_VFP_64bitRegisterTransfer() { } //--// public void Prepare( uint ConditionCodes , bool IsDouble , uint Rd , uint Rn , uint Fm , bool IsFromCoProc ) { base.Prepare( ConditionCodes, IsDouble, Rd, IsFromCoProc ); this.Rn = Rn; this.Fm = Fm; } //--// public override void Decode( uint op ) { base.Decode( op ); this.Rn = s_EncodingVFP.get_Rn( op ); this.Fm = s_EncodingVFP.get_Fm( op ); } public override uint Encode() { uint op = base.Encode(); op |= s_EncodingVFP.set_Rn( this.Rn ); op |= s_EncodingVFP.set_Fm( this.Fm ); return op | EncDef.op_64bitRegisterTransfer; } public override void Print( InstructionSet owner , System.Text.StringBuilder str , uint opcodeAddress , ref uint target , ref bool targetIsCode ) { if(this.IsDouble) { PrintMnemonic( str, "{0}{1}", this.IsFromCoProc ? "FMRRD" : "FMDRR", DumpCondition() ); str.AppendFormat( this.IsFromCoProc ? "{0},{1},{2}" : "{2},{0},{1}", DumpRegister( this.Rd ), DumpRegister( this.Rn ), DumpRegister( this.Fm, true ) ); } else { PrintMnemonic( str, "{0}{1}", this.IsFromCoProc ? "FMRRS" : "FMSRR", DumpCondition() ); str.AppendFormat( this.IsFromCoProc ? "{0},{1},{2},{3}" : "{2},{3},{0},{1}", DumpRegister( this.Rd ), DumpRegister( this.Rn ), DumpRegister( this.Fm, false ), DumpRegister( (this.Fm + 1) % 32, false ) ); } } } public sealed class Opcode_VFP_32bitRegisterTransfer : Opcode_VFP_BaseRegisterTransfer { // // State // public uint Fn; // // Constructor Methods // internal Opcode_VFP_32bitRegisterTransfer() { } //--// public void Prepare( uint ConditionCodes , uint Rd , uint Fn , bool IsFromCoProc ) { base.Prepare( ConditionCodes, false, Rd, IsFromCoProc ); this.Fn = Fn; } //--// public override void Decode( uint op ) { base.Decode( op ); this.Fn = s_EncodingVFP.get_Fn( op ); } public override uint Encode() { uint op = base.Encode(); op |= s_EncodingVFP.set_Fn( this.Fn ); return op | EncDef.op_32bitRegisterTransfer; } public override void Print( InstructionSet owner , System.Text.StringBuilder str , uint opcodeAddress , ref uint target , ref bool targetIsCode ) { PrintMnemonic( str, "{0}{1}", this.IsFromCoProc ? "FMRS" : "FMSR", DumpCondition() ); str.AppendFormat( this.IsFromCoProc ? "{0},{1}" : "{1},{0}", DumpRegister( this.Rd ), DumpRegister( this.Fn, false ) ); } } public sealed class Opcode_VFP_32bitLoRegisterTransfer : Opcode_VFP_BaseRegisterTransfer { // // State // public uint Fn; // // Constructor Methods // internal Opcode_VFP_32bitLoRegisterTransfer() { } //--// public void Prepare( uint ConditionCodes , uint Rd , uint Fn , bool IsFromCoProc ) { base.Prepare( ConditionCodes, true, Rd, IsFromCoProc ); this.Fn = Fn; } //--// public override void Decode( uint op ) { base.Decode( op ); this.Fn = s_EncodingVFP.get_Fn( op ); } public override uint Encode() { uint op = base.Encode(); op |= s_EncodingVFP.set_Fn( this.Fn ); return op | EncDef.op_32bitLoRegisterTransfer; } public override void Print( InstructionSet owner , System.Text.StringBuilder str , uint opcodeAddress , ref uint target , ref bool targetIsCode ) { PrintMnemonic( str, "{0}{1}", this.IsFromCoProc ? "FMRDL" : "FMDLR", DumpCondition() ); str.AppendFormat( this.IsFromCoProc ? "{0},{1}" : "{1},{0}", DumpRegister( this.Rd ), DumpRegister( this.Fn, true ) ); } } public sealed class Opcode_VFP_32bitHiRegisterTransfer : Opcode_VFP_BaseRegisterTransfer { // // State // public uint Fn; // // Constructor Methods // internal Opcode_VFP_32bitHiRegisterTransfer() { } //--// public void Prepare( uint ConditionCodes , uint Rd , uint Fn , bool IsFromCoProc ) { base.Prepare( ConditionCodes, true, Rd, IsFromCoProc ); this.Fn = Fn; } //--// public override void Decode( uint op ) { base.Decode( op ); this.Fn = s_EncodingVFP.get_Fn( op ); } public override uint Encode() { uint op = base.Encode(); op |= s_EncodingVFP.set_Fn( this.Fn ); return op | EncDef.op_32bitHiRegisterTransfer; } public override void Print( InstructionSet owner , System.Text.StringBuilder str , uint opcodeAddress , ref uint target , ref bool targetIsCode ) { PrintMnemonic( str, "{0}{1}", this.IsFromCoProc ? "FMRDH" : "FMDHR", DumpCondition() ); str.AppendFormat( this.IsFromCoProc ? "{0},{1}" : "{1},{0}", DumpRegister( this.Rd ), DumpRegister( this.Fn, true ) ); } } public sealed class Opcode_VFP_CompareToZero : Opcode_VFP_Flavor { // // State // public uint Fd; public bool CheckNaN; // // Constructor Methods // internal Opcode_VFP_CompareToZero() { } //--// public void Prepare( uint ConditionCodes , bool IsDouble , uint Fd , bool CheckNaN ) { base.Prepare( ConditionCodes, IsDouble ); this.Fd = Fd; this.CheckNaN = CheckNaN; } //--// public override void Decode( uint op ) { base.Decode( op ); this.Fd = s_EncodingVFP.get_Fd ( op ); this.CheckNaN = s_EncodingVFP.get_CheckNaN( op ); } public override uint Encode() { uint op = base.Encode(); op |= s_EncodingVFP.set_Fd ( this.Fd ); op |= s_EncodingVFP.set_CheckNaN( this.CheckNaN ); return op | EncDef.op_CompareToZero; } public override void Print( InstructionSet owner , System.Text.StringBuilder str , uint opcodeAddress , ref uint target , ref bool targetIsCode ) { PrintMnemonic( str, "FCMP{0}Z{1}{2}", this.CheckNaN ? "E" : "", this.IsDouble ? "D" : "S", DumpCondition() ); str.AppendFormat( "{0}", DumpRegister( this.Fd, this.IsDouble ) ); } } public sealed class Opcode_VFP_ConvertFloatToFloat : Opcode_VFP_Flavor { // // State // public uint Fd; public uint Fm; // // Constructor Methods // internal Opcode_VFP_ConvertFloatToFloat() { } //--// public void Prepare( uint ConditionCodes , bool IsDouble , uint Fd , uint Fm ) { base.Prepare( ConditionCodes, IsDouble ); this.Fd = Fd; this.Fm = Fm; } //--// public override void Decode( uint op ) { base.Decode( op ); this.Fd = s_EncodingVFP.get_Fd( op ); this.Fm = s_EncodingVFP.get_Fm( op ); } public override uint Encode() { uint op = base.Encode(); op |= s_EncodingVFP.set_Fd( this.Fd ); op |= s_EncodingVFP.set_Fm( this.Fm ); return op | EncDef.op_ConvertFloatToFloat; } public override void Print( InstructionSet owner , System.Text.StringBuilder str , uint opcodeAddress , ref uint target , ref bool targetIsCode ) { PrintMnemonic( str, "FCVT{0}{1}", this.IsDouble ? "SD" : "DS", DumpCondition() ); str.AppendFormat( "{0},{1}", DumpRegister( this.Fd, !this.IsDouble ), DumpRegister( this.Fm, this.IsDouble ) ); } } public sealed class Opcode_VFP_UnaryDataOperation : Opcode_VFP_Flavor { // // State // public uint Fd; public uint Fm; public uint Alu; // // Constructor Methods // internal Opcode_VFP_UnaryDataOperation() { } //--// public void Prepare( uint ConditionCodes , bool IsDouble , uint Fd , uint Fm , uint Alu ) { base.Prepare( ConditionCodes, IsDouble ); this.Fd = Fd; this.Fm = Fm; this.Alu = Alu; } //--// public override void Decode( uint op ) { base.Decode( op ); this.Fd = s_EncodingVFP.get_Fd ( op ); this.Fm = s_EncodingVFP.get_Fm ( op ); this.Alu = s_EncodingVFP.get_UnaryOperation( op ); } public override uint Encode() { uint op = base.Encode(); op |= s_EncodingVFP.set_Fd ( this.Fd ); op |= s_EncodingVFP.set_Fm ( this.Fm ); op |= s_EncodingVFP.set_UnaryOperation( this.Alu ); return op | EncDef.op_UnaryDataOperation; } public override void Print( InstructionSet owner , System.Text.StringBuilder str , uint opcodeAddress , ref uint target , ref bool targetIsCode ) { PrintMnemonic( str, "{0}{1}{2}", DumpOperation( this.Alu ), this.IsDouble ? "D" : "S", DumpCondition() ); switch(this.Alu) { case EncDef.c_unaryOperation_TOUI : case EncDef.c_unaryOperation_TOUIZ: case EncDef.c_unaryOperation_TOSI : case EncDef.c_unaryOperation_TOSIZ: str.AppendFormat( "{0},", DumpRegister( this.Fd, false ) ); break; default: str.AppendFormat( "{0},", DumpRegister( this.Fd, this.IsDouble ) ); break; } switch(this.Alu) { case EncDef.c_unaryOperation_UITO : case EncDef.c_unaryOperation_SITO : str.AppendFormat( "{0}", DumpRegister( this.Fm, false ) ); break; default: str.AppendFormat( "{0}", DumpRegister( this.Fm, this.IsDouble ) ); break; } } private static string DumpOperation( uint alu ) { switch(alu) { case EncDef.c_unaryOperation_CPY : return "FCPY"; case EncDef.c_unaryOperation_ABS : return "FABS"; case EncDef.c_unaryOperation_NEG : return "FNEG"; case EncDef.c_unaryOperation_SQRT : return "FSQRT"; case EncDef.c_unaryOperation_CMP : return "FCMP"; case EncDef.c_unaryOperation_CMPE : return "FCMPE"; case EncDef.c_unaryOperation_UITO : return "FUITO"; case EncDef.c_unaryOperation_SITO : return "FSITO"; case EncDef.c_unaryOperation_TOUI : return "FTOUI"; case EncDef.c_unaryOperation_TOUIZ: return "FTOUIZ"; case EncDef.c_unaryOperation_TOSI : return "FTOSI"; case EncDef.c_unaryOperation_TOSIZ: return "FTOSIZ"; } return "??"; } } public sealed class Opcode_VFP_BinaryDataOperation : Opcode_VFP_Flavor { // // State // public uint Fd; public uint Fn; public uint Fm; public uint Alu; // // Constructor Methods // internal Opcode_VFP_BinaryDataOperation() { } //--// public void Prepare( uint ConditionCodes , bool IsDouble , uint Fd , uint Fn , uint Fm , uint Alu ) { base.Prepare( ConditionCodes, IsDouble ); this.Fd = Fd; this.Fn = Fn; this.Fm = Fm; this.Alu = Alu; } //--// public override void Decode( uint op ) { base.Decode( op ); this.Fd = s_EncodingVFP.get_Fd ( op ); this.Fn = s_EncodingVFP.get_Fn ( op ); this.Fm = s_EncodingVFP.get_Fm ( op ); this.Alu = s_EncodingVFP.get_BinaryOperation( op ); } public override uint Encode() { uint op = base.Encode(); op |= s_EncodingVFP.set_Fd ( this.Fd ); op |= s_EncodingVFP.set_Fn ( this.Fn ); op |= s_EncodingVFP.set_Fm ( this.Fm ); op |= s_EncodingVFP.set_BinaryOperation( this.Alu ); return op | EncDef.op_BinaryDataOperation; } public override void Print( InstructionSet owner , System.Text.StringBuilder str , uint opcodeAddress , ref uint target , ref bool targetIsCode ) { PrintMnemonic( str, "{0}{1}{2}", DumpOperation( this.Alu ), this.IsDouble ? "D" : "S", DumpCondition() ); str.AppendFormat( "{0},{1},{2}", DumpRegister( this.Fd, this.IsDouble ), DumpRegister( this.Fn, this.IsDouble ), DumpRegister( this.Fm, this.IsDouble ) ); } private static string DumpOperation( uint alu ) { switch(alu) { case EncDef.c_binaryOperation_MAC : return "FMAC"; case EncDef.c_binaryOperation_NMAC: return "FNMAC"; case EncDef.c_binaryOperation_MSC : return "FMSC"; case EncDef.c_binaryOperation_NMSC: return "FNMSC"; case EncDef.c_binaryOperation_MUL : return "FMUL"; case EncDef.c_binaryOperation_NMUL: return "FNMUL"; case EncDef.c_binaryOperation_ADD : return "FADD"; case EncDef.c_binaryOperation_SUB : return "FSUB"; case EncDef.c_binaryOperation_DIV : return "FDIV"; } return "??"; } } } } ================================================ FILE: Zelig/Zelig/CompileTime/TargetModels/ArmProcessor/Properties/AssemblyInfo.cs ================================================ using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; // General Information about an assembly is controlled through the following // set of attributes. Change these attribute values to modify the information // associated with an assembly. [assembly: AssemblyTitle( "Microsoft.Zelig.TargetModel.ArmProcessor" )] [assembly: AssemblyDescription( "" )] [assembly: AssemblyConfiguration( "" )] [assembly: AssemblyCompany( "Microsoft" )] [assembly: AssemblyProduct( "Microsoft.Zelig.TargetModel.ArmProcessor" )] [assembly: AssemblyCopyright( "Copyright © Microsoft 2006" )] [assembly: AssemblyTrademark( "" )] [assembly: AssemblyCulture( "" )] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible( false )] //// The following GUID is for the ID of the typelib if this project is exposed to COM //[assembly: Guid( "57de0ebe-e971-4cb9-8985-5f6b66934a91" )] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Revision and Build Numbers // by using the '*' as shown below: [assembly: AssemblyVersion( "1.0.0.0" )] [assembly: AssemblyFileVersion( "1.0.0.0" )] ================================================ FILE: Zelig/Zelig/CompileTime/TargetModels/ProductConfiguration/Abstractions/ARM/ArchitectureVersions/ArmV4.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // namespace Microsoft.Zelig.Configuration.Environment.Abstractions.Architectures { using System; using System.Collections.Generic; using Microsoft.Zelig.Runtime.TypeSystem; using Microsoft.Zelig.TargetModel.ArmProcessor; using ZeligIR = Microsoft.Zelig.CodeGeneration.IR; public sealed partial class ArmV4 : ArmPlatform { private const Capabilities c_ProcessorCapabilities = Capabilities.ARMv4; // // Constructor Methods // public ArmV4() : base( c_ProcessorCapabilities ) // Default constructor required by TypeSystemSerializer. { } public ArmV4( ZeligIR.TypeSystemForCodeTransformation typeSystem , MemoryMapCategory memoryMap ) : base( typeSystem, memoryMap, c_ProcessorCapabilities ) { } // // Helper Methods // public override void RegisterForNotifications( ZeligIR.TypeSystemForCodeTransformation ts , ZeligIR.CompilationSteps.DelegationCache cache ) { base.RegisterForNotifications( ts, cache ); cache.Register( new ZeligIR.CompilationSteps.Handlers.SoftwareFloatingPoint() ); cache.Register( new Optimizations( this ) ); } //--// public override TypeRepresentation GetMethodWrapperType() { return m_typeSystem.GetWellKnownType( "Microsoft_Zelig_ProcessorARMv4_MethodWrapper" ); } public override bool HasRegisterContextArgument( MethodRepresentation md ) { if(md.ThisPlusArguments.Length > 1) { TypeRepresentation td = md.ThisPlusArguments[1]; if(td is PointerTypeRepresentation) { td = td.UnderlyingType; if(td == m_typeSystem.GetWellKnownType( "Microsoft_Zelig_ProcessorARMv4_RegistersOnStack" )) { return true; } } } return false; } protected override void ComputeRegisterFlushFixup( BitVector registersToSave ) { } } } ================================================ FILE: Zelig/Zelig/CompileTime/TargetModels/ProductConfiguration/Abstractions/ARM/ArchitectureVersions/ArmV4_Optimizations.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // //#define ENABLE_LOW_LEVEL_OPTIMIZATIONS namespace Microsoft.Zelig.Configuration.Environment.Abstractions.Architectures { using System; using System.Collections.Generic; using Microsoft.Zelig.Runtime.TypeSystem; using Microsoft.Zelig.TargetModel.ArmProcessor; using ZeligIR = Microsoft.Zelig.CodeGeneration.IR; public sealed partial class ArmV4 { public class Optimizations { // // State // ArmPlatform m_owner; // // Constructor Methods // public Optimizations( ArmPlatform owner ) { m_owner = owner; } //--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--// //--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--// //--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--// #if ENABLE_LOW_LEVEL_OPTIMIZATIONS [ZeligIR.CompilationSteps.OptimizationHandler(RunOnce=false, RunInSSAForm=true)] #endif // ENABLE_LOW_LEVEL_OPTIMIZATIONS private void OptimizeIndirectOperators( ZeligIR.CompilationSteps.PhaseExecution.NotificationContext nc ) { CompactIndirectOperators ( nc ); if(nc.CanContinue == false) return; MergeIndirectOperatorWithIndexUpdate( nc ); if(nc.CanContinue == false) return; FuseSpecialRegisterUpdates ( nc ); } private void CompactIndirectOperators( ZeligIR.CompilationSteps.PhaseExecution.NotificationContext nc ) { var cfg = nc.CurrentCFG; using(cfg.GroupLock( cfg.LockSpanningTree(), cfg.LockUseDefinitionChains() )) { var def = cfg.DataFlow_DefinitionChains; var visited = new BitVector(); foreach(var op in cfg.FilterOperators< ZeligIR.IndirectOperator >()) { // // Peephole optimization. // // Input: // // = +/- // Load/Store , // // Output: // // Load/Store , +/- // var opSrc = ZeligIR.ControlFlowGraphStateForCodeTransformation.FindOrigin( op.FirstArgument, def, visited ) as ZeligIR.BinaryOperator; if(opSrc != null) { ZeligIR.VariableExpression exAddress; long val; if(opSrc.IsAddOrSubAgainstConstant( out exAddress, out val )) { var alias = exAddress.AliasedVariable; if(alias is ZeligIR.PseudoRegisterExpression || alias is ZeligIR.PhysicalRegisterExpression ) { long iNewOffset = op.Offset + val; if(Math.Abs( iNewOffset ) < m_owner.GetOffsetLimit( op.Type )) { Debugging.DebugInfo debugInfo = op.DebugInfo; TypeRepresentation td = op.Type; ZeligIR.Operator opNew; if(op is ZeligIR.StoreIndirectOperator) { opNew = ZeligIR.StoreIndirectOperator.New( debugInfo, td, exAddress, op.SecondArgument, op.AccessPath, (int)iNewOffset, false ); } else { opNew = ZeligIR.LoadIndirectOperator.New( debugInfo, td, op.FirstResult, exAddress, op.AccessPath, (int)iNewOffset, op.MayMutateExistingStorage, false ); } op.SubstituteWithOperator( opNew, ZeligIR.Operator.SubstitutionFlags.CopyAnnotations ); nc.MarkAsModified(); } } } } } } } //--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--// //--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--// //--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--// [ZeligIR.CompilationSteps.PhaseFilter( typeof(ZeligIR.CompilationSteps.Phases.FuseOperators) )] [ZeligIR.CompilationSteps.OperatorHandler( typeof(ZeligIR.BinaryOperator) )] private static void MergeOperationWithShift( ZeligIR.CompilationSteps.PhaseExecution.NotificationContext nc ) { var cfg = nc.CurrentCFG; var op = (ZeligIR.BinaryOperator)nc.CurrentOperator; switch(op.Alu) { case ZeligIR.AbstractBinaryOperator.ALU.ADD: case ZeligIR.AbstractBinaryOperator.ALU.AND: case ZeligIR.AbstractBinaryOperator.ALU.OR: case ZeligIR.AbstractBinaryOperator.ALU.XOR: if(ConvertToBinaryOperatorWithShift( cfg, op, op.SecondArgument, op.FirstArgument )) { nc.MarkAsModified(); return; } goto case ZeligIR.AbstractBinaryOperator.ALU.SUB; case ZeligIR.AbstractBinaryOperator.ALU.SUB: if(ConvertToBinaryOperatorWithShift( cfg, op, op.FirstArgument, op.SecondArgument )) { nc.MarkAsModified(); return; } break; } } private static bool ConvertToBinaryOperatorWithShift( ZeligIR.ControlFlowGraphStateForCodeTransformation cfg , ZeligIR.BinaryOperator op , ZeligIR.Expression exLeft , ZeligIR.Expression exRight ) { if(exLeft is ZeligIR.VariableExpression) { var opShift = cfg.FindSingleDefinition( exRight ) as ZeligIR.BinaryOperator; if(opShift != null) { switch(opShift.Alu) { case ZeligIR.AbstractBinaryOperator.ALU.SHL: case ZeligIR.AbstractBinaryOperator.ALU.SHR: var opNew = ARM.BinaryOperatorWithShift.New( op.DebugInfo, op.Alu, op.Signed, opShift.Alu, opShift.Signed, op.FirstResult, exLeft, opShift.FirstArgument, opShift.SecondArgument ); op.SubstituteWithOperator( opNew, ZeligIR.Operator.SubstitutionFlags.Default ); return true; } } } return false; } //--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--// [ZeligIR.CompilationSteps.PhaseFilter( typeof(ZeligIR.CompilationSteps.Phases.CollectRegisterAllocationConstraints) )] [ZeligIR.CompilationSteps.OperatorHandler( typeof(ARM.BinaryOperatorWithShift) )] private static void Handle_BinaryOperatorWithShift( ZeligIR.CompilationSteps.PhaseExecution.NotificationContext nc ) { ZeligIR.Operator op = nc.CurrentOperator; SetConstraintOnResultsBasedOnType ( nc, op.Results ); SetConstraintOnArgumentsBasedOnType( nc, op.Arguments ); } //--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--// //--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--// //--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--// class ScoreBoardForIndirectOperatorWithIndexUpdate { internal ZeligIR.IndirectOperator m_opTarget; internal ZeligIR.BinaryOperator m_opVarIndexUpdate; internal long m_C1; internal ZeligIR.VariableExpression m_indexPre; internal ZeligIR.VariableExpression m_indexPost; } private void MergeIndirectOperatorWithIndexUpdate( ZeligIR.CompilationSteps.PhaseExecution.NotificationContext nc ) { var cfg = nc.CurrentCFG; //// if(cfg.ToString() == "FlowGraph(void Microsoft.VoxSoloFormFactorLoader.Loader::ExitCFI(ushort*))") //// if(cfg.ToString() == "FlowGraph(void Microsoft.Zelig.Runtime.Memory::Fill(System.UIntPtr,System.UIntPtr,uint))") //// if(cfg.ToString() == "FlowGraph(void Microsoft.Zelig.Runtime.Memory::CopyNonOverlapping(System.UIntPtr,System.UIntPtr,System.UIntPtr))") //// { //// //// } //////////////////////////////////////////// // // Before: // Access [ V0 +/- C1 ] // V1 = V0 +/- C1 << This use must be dominated by Access // // After: // V1 = Access [ V0 +/- C1 ] ! // //////////////////////////////////////////// // // Before: // Access [ V0 ] // V1 = V0 +/- C1 << This use must be dominated by Access // // After: // V1 = Access [ V0 ] +/- C1 ! // //////////////////////////////////////////// // // Before: // V1 = V0 +/- C1 // Access [ V1 ] << All the other uses of V1 must be dominated by Access *and* V0 must be alive at Access // // After: // V1 = Access [ V0 +/- C1 ] ! // //////////////////////////////////////////// // using(cfg.GroupLock( cfg.LockSpanningTree () , cfg.LockDominance () , cfg.LockUseDefinitionChains() )) { var dominance = cfg.DataFlow_Dominance; var use = cfg.DataFlow_UseChains; var def = cfg.DataFlow_DefinitionChains; var visited = new BitVector(); var workList = HashTableFactory.NewWithReferenceEquality< ZeligIR.BinaryOperator, ScoreBoardForIndirectOperatorWithIndexUpdate >(); foreach(var opTarget in cfg.FilterOperators< ZeligIR.IndirectOperator >()) { var varIndex = opTarget.FirstArgument as ZeligIR.VariableExpression; if(varIndex != null) { bool fLoad = opTarget is ZeligIR.LoadIndirectOperator; bool fStore = opTarget is ZeligIR.StoreIndirectOperator; if(!fLoad && !fStore) { continue; } // // Look for this pattern: // // Access [ V0 +/- C1 ] or Access [ V0 ] // V1 = V0 +/- C1 // // Or // // V1 = V0 +/- C1 // Access [ V0 +/- C1 ] or Access [ V0 ] // foreach(var opVarIndexUse in use[varIndex.SpanningTreeIndex]) { if(opTarget.BasicBlock != opVarIndexUse.BasicBlock) { // // For now, let's limit optimization to same basic block. // continue; } ZeligIR.VariableExpression V0; long C1; if(opVarIndexUse.IsAddOrSubAgainstConstant( out V0, out C1 ) && V0 == varIndex && Math.Abs( C1 ) < m_owner.GetOffsetLimit( opTarget.Type )) { ZeligIR.VariableExpression V1 = opVarIndexUse.FirstResult; if(opTarget.Offset == 0 || opTarget.Offset == C1) { // // Found "V1 = V0 +/- C1" // It's a possible candidate. // var opVarIndexUse2 = (ZeligIR.BinaryOperator)opVarIndexUse; //--// if(opVarIndexUse2.SpanningTreeIndex > opTarget.SpanningTreeIndex) { // // Case: // // Access [ V0 +/- C1 ] or Access [ V0 ] // V1 = V0 +/- C1 // // // Is V0 used after opTarget? // If so, it's not a good candidate, we'd need to move V0 to another register, undoing the saving from the optimization. // foreach(var opOtherUse in use[V0.SpanningTreeIndex]) { if(opOtherUse == opTarget ) continue; if(opOtherUse == opVarIndexUse2) continue; if(opOtherUse.IsDominatedBy( opTarget, dominance )) { opVarIndexUse2 = null; break; } } if(opVarIndexUse2 == null) { continue; } } else { // // Case: // // V1 = V0 +/- C1 // Access [ V0 +/- C1 ] or Access [ V0 ] // // // Is V1 used before opTarget? // If so, it's not a good candidate. // foreach(var opOtherUse in use[V1.SpanningTreeIndex]) { if(opOtherUse.BasicBlock == opTarget.BasicBlock) { var idx = opOtherUse.SpanningTreeIndex; if(idx > opVarIndexUse.SpanningTreeIndex && idx < opTarget.SpanningTreeIndex) { opVarIndexUse2 = null; break; } } } if(opVarIndexUse2 == null) { continue; } } //--// ScoreBoardForIndirectOperatorWithIndexUpdate scoreBoardOld; if(workList.TryGetValue( opVarIndexUse2, out scoreBoardOld )) { if(scoreBoardOld.m_opTarget.IsDominatedBy( opTarget, dominance )) { continue; } } var scoreboard = new ScoreBoardForIndirectOperatorWithIndexUpdate() { m_opTarget = opTarget, m_opVarIndexUpdate = opVarIndexUse2, m_C1 = C1, m_indexPre = V0, m_indexPost = V1, }; workList[opVarIndexUse2] = scoreboard; } } } // // Look for this pattern: // // V1 = V0 +/- C1 // Access [ V1 ] << All the other uses of V1 must be dominated by Access *and* V0 must be alive at Access // if(opTarget.Offset == 0) { var opVarIndexDef = ZeligIR.ControlFlowGraphStateForCodeTransformation.FindOrigin( opTarget.FirstArgument, def, visited ) as ZeligIR.BinaryOperator; if(opVarIndexDef != null) { ZeligIR.VariableExpression V0; long C1; if(opVarIndexDef.IsAddOrSubAgainstConstant( out V0, out C1 ) && Math.Abs( C1 ) < m_owner.GetOffsetLimit( opTarget.Type )) { // // Found "V1 = V0 +/- C1" // // It's a possible candidate. // // // Is V1 used between opVarIndexDef and opTarget? // If so, it's not a good candidate. // foreach(var opOtherUse in use[varIndex.SpanningTreeIndex]) { if(opOtherUse.BasicBlock == opTarget.BasicBlock) { var idx = opOtherUse.SpanningTreeIndex; if(idx > opVarIndexDef.SpanningTreeIndex && idx < opTarget.SpanningTreeIndex) { continue; } varIndex = null; break; } } if(varIndex == null) { continue; } //--// ScoreBoardForIndirectOperatorWithIndexUpdate scoreBoardOld; if(workList.TryGetValue( opVarIndexDef, out scoreBoardOld )) { if(scoreBoardOld.m_opTarget.IsDominatedBy( opTarget, dominance )) { continue; } } var scoreboard = new ScoreBoardForIndirectOperatorWithIndexUpdate() { m_opTarget = opTarget, m_opVarIndexUpdate = opVarIndexDef, m_C1 = C1, m_indexPre = V0, m_indexPost = varIndex, }; workList[opVarIndexDef] = scoreboard; } } } } } foreach(var scoreboard in workList.Values) { var opTarget = scoreboard.m_opTarget; var opVarIndexUpdate = scoreboard.m_opVarIndexUpdate; if(opTarget .IsDetached || opVarIndexUpdate.IsDetached ) { continue; } var indexPre = MoveToPseudoRegister( cfg, opTarget, scoreboard.m_indexPre ); var indexPost = scoreboard.m_indexPost; var di = opTarget.DebugInfo; var td = opTarget.Type; var ap = opTarget.AccessPath; var offset = opTarget.Offset; ZeligIR.Operator opNew; if(opTarget is ZeligIR.LoadIndirectOperator) { opNew = ARM.LoadIndirectOperatorWithIndexUpdate.New( di, td, opTarget.FirstResult, indexPost, indexPre, ap, (int)scoreboard.m_C1, opTarget.MayMutateExistingStorage, offset == 0 ); opNew.AddAnnotation( ZeligIR.RegisterCouplingConstraintAnnotation.Create( nc.TypeSystem, 1, true, 0, false ) ); } else { opNew = ARM.StoreIndirectOperatorWithIndexUpdate.New( di, td, indexPost, indexPre, opTarget.SecondArgument, ap, (int)scoreboard.m_C1, opTarget.MayMutateExistingStorage, offset == 0 ); opNew.AddAnnotation( ZeligIR.RegisterCouplingConstraintAnnotation.Create( nc.TypeSystem, 0, true, 0, false ) ); } opTarget.SubstituteWithOperator( opNew, ZeligIR.Operator.SubstitutionFlags.Default ); opVarIndexUpdate.Delete(); nc.MarkAsModified(); } } } //--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--// //--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--// //--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--// class ScoreBoardForFuseSpecialRegisterUpdates { internal ZeligIR.Expression m_src; internal long m_C1; internal ZeligIR.SingleAssignmentOperator m_target; } private void FuseSpecialRegisterUpdates( ZeligIR.CompilationSteps.PhaseExecution.NotificationContext nc ) { var cfg = nc.CurrentCFG; using(cfg.GroupLock( cfg.LockSpanningTree () , cfg.LockDominance () , cfg.LockUseDefinitionChains() )) { var workList = HashTableFactory.NewWithReferenceEquality< ZeligIR.SingleAssignmentOperator, ScoreBoardForFuseSpecialRegisterUpdates >(); FuseSpecialRegisterUpdates( cfg, workList, EncodingDefinition.c_register_sp ); FuseSpecialRegisterUpdates( cfg, workList, EncodingDefinition.c_register_lr ); foreach(var scoreboard in workList.Values) { var opTarget = scoreboard.m_target; if(opTarget.IsDetached) { continue; } ZeligIR.BinaryOperator opNew; if(scoreboard.m_C1 >= 0) { opNew = ZeligIR.BinaryOperator.New( opTarget.DebugInfo, ZeligIR.AbstractBinaryOperator.ALU.ADD, false, false, opTarget.FirstResult, scoreboard.m_src, nc.TypeSystem.CreateConstant( (uint)scoreboard.m_C1 ) ); } else { opNew = ZeligIR.BinaryOperator.New( opTarget.DebugInfo, ZeligIR.AbstractBinaryOperator.ALU.SUB, false, false, opTarget.FirstResult, scoreboard.m_src, nc.TypeSystem.CreateConstant( (uint)-scoreboard.m_C1 ) ); } opTarget.SubstituteWithOperator( opNew, ZeligIR.Operator.SubstitutionFlags.CopyAnnotations ); nc.MarkAsModified(); } } } private void FuseSpecialRegisterUpdates( ZeligIR.ControlFlowGraphStateForCodeTransformation cfg , GrowOnlyHashTable< ZeligIR.SingleAssignmentOperator, ScoreBoardForFuseSpecialRegisterUpdates > workList , uint targetEncoding ) { var dominance = cfg.DataFlow_Dominance; var use = cfg.DataFlow_UseChains; var def = cfg.DataFlow_DefinitionChains; foreach(var opTarget in cfg.FilterOperators< ZeligIR.SingleAssignmentOperator >()) { var regTarget = ZeligIR.Abstractions.RegisterDescriptor.ExtractFromExpression( opTarget.FirstResult ); if(regTarget != null && regTarget.Encoding == targetEncoding) { var varSrc1 = opTarget.FirstArgument as ZeligIR.VariableExpression; if(varSrc1 != null) { var opSrc1 = def[varSrc1.SpanningTreeIndex][0]; ZeligIR.VariableExpression varSrc2; long C1; if(opSrc1.IsAddOrSubAgainstConstant( out varSrc2, out C1 )) { var opSrc2 = def[varSrc2.SpanningTreeIndex][0] as ZeligIR.SingleAssignmentOperator; if(opSrc2 != null) { var varOrigin = opSrc2.FirstArgument; var regOrigin = ZeligIR.Abstractions.RegisterDescriptor.ExtractFromExpression( varOrigin ); if(regOrigin != null && regOrigin.Encoding == targetEncoding) { var scoreboard = new ScoreBoardForFuseSpecialRegisterUpdates() { m_src = varOrigin, m_C1 = C1, m_target = opTarget, }; workList[opTarget] = scoreboard; } } } } } } } //--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--// [ZeligIR.CompilationSteps.PhaseFilter( typeof(ZeligIR.CompilationSteps.Phases.CollectRegisterAllocationConstraints) )] [ZeligIR.CompilationSteps.OperatorHandler( typeof(ARM.IndirectOperatorWithIndexUpdate) )] private static void Handle_IndirectOperatorWithIndexUpdate( ZeligIR.CompilationSteps.PhaseExecution.NotificationContext nc ) { ZeligIR.Operator op = nc.CurrentOperator; SetConstraintOnResultsBasedOnType ( nc, op.Results ); SetConstraintOnArgumentsBasedOnType( nc, op.Arguments ); } } } } ================================================ FILE: Zelig/Zelig/CompileTime/TargetModels/ProductConfiguration/Abstractions/ARM/ArchitectureVersions/ArmV5.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // namespace Microsoft.Zelig.Configuration.Environment.Abstractions.Architectures { using System; using System.Collections.Generic; using Microsoft.Zelig.Runtime.TypeSystem; using Microsoft.Zelig.TargetModel.ArmProcessor; using ZeligIR = Microsoft.Zelig.CodeGeneration.IR; public sealed partial class ArmV5 : ArmPlatform { const Capabilities c_ProcessorCapabilities = Capabilities.ARMv5; // // Constructor Methods // public ArmV5() : base( c_ProcessorCapabilities ) // Default constructor required by TypeSystemSerializer. { } public ArmV5( ZeligIR.TypeSystemForCodeTransformation typeSystem , MemoryMapCategory memoryMap ) : base( typeSystem, memoryMap, c_ProcessorCapabilities ) { } // // Helper Methods // public override void RegisterForNotifications( ZeligIR.TypeSystemForCodeTransformation ts , ZeligIR.CompilationSteps.DelegationCache cache ) { base.RegisterForNotifications( ts, cache ); cache.Register( new ZeligIR.CompilationSteps.Handlers.SoftwareFloatingPoint() ); cache.Register( new ArmV4.Optimizations( this ) ); } //--// public override TypeRepresentation GetMethodWrapperType() { return m_typeSystem.GetWellKnownType( "Microsoft_Zelig_ProcessorARMv4_MethodWrapper" ); } public override bool HasRegisterContextArgument( MethodRepresentation md ) { if(md.ThisPlusArguments.Length > 1) { TypeRepresentation td = md.ThisPlusArguments[1]; if(td is PointerTypeRepresentation) { td = td.UnderlyingType; if(td == m_typeSystem.GetWellKnownType( "Microsoft_Zelig_ProcessorARMv5_RegistersOnStack" )) { return true; } } } return false; } //--// protected override void ComputeRegisterFlushFixup( BitVector registersToSave ) { while(true) { bool fDone = true; foreach(ZeligIR.Abstractions.RegisterDescriptor regToSave in this.GetRegisters()) { int pos = (int)regToSave.Encoding; if(registersToSave[pos]) { uint size = regToSave.PhysicalStorageSize; foreach(ZeligIR.Abstractions.RegisterDescriptor regInterfere in regToSave.InterfersWith) { if(regInterfere.PhysicalStorageSize > size) { registersToSave.Set ( (int)regInterfere.Encoding ); registersToSave.Clear( pos ); fDone = false; break; } } } } if(fDone) { break; } } } } } ================================================ FILE: Zelig/Zelig/CompileTime/TargetModels/ProductConfiguration/Abstractions/ARM/ArchitectureVersions/ArmV5_VFP.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // namespace Microsoft.Zelig.Configuration.Environment.Abstractions.Architectures { using System; using System.Collections.Generic; using Microsoft.Zelig.Runtime.TypeSystem; using Microsoft.Zelig.TargetModel.ArmProcessor; using ZeligIR = Microsoft.Zelig.CodeGeneration.IR; public sealed partial class ArmV5_VFP : ArmPlatform { const Capabilities c_ProcessorCapabilities = Capabilities.ARMv5 | Capabilities.VFPv2; // // Constructor Methods // public ArmV5_VFP() : base( c_ProcessorCapabilities ) // Default constructor required by TypeSystemSerializer. { } public ArmV5_VFP( ZeligIR.TypeSystemForCodeTransformation typeSystem , MemoryMapCategory memoryMap ) : base( typeSystem, memoryMap, c_ProcessorCapabilities ) { } // // Helper Methods // public override void RegisterForNotifications( ZeligIR.TypeSystemForCodeTransformation ts , ZeligIR.CompilationSteps.DelegationCache cache ) { base.RegisterForNotifications( ts, cache ); cache.Register( new FloatingPointEmulation() ); cache.Register( new CollectRegisterAllocationConstraints() ); cache.Register( new ArmV4.Optimizations( this ) ); } //--// public override TypeRepresentation GetMethodWrapperType() { return m_typeSystem.GetWellKnownType( "Microsoft_Zelig_ProcessorARMv5_VFP_MethodWrapper" ); } public override bool HasRegisterContextArgument( MethodRepresentation md ) { if(md.ThisPlusArguments.Length > 1) { TypeRepresentation td = md.ThisPlusArguments[1]; if(td is PointerTypeRepresentation) { td = td.UnderlyingType; if(td == m_typeSystem.GetWellKnownType( "Microsoft_Zelig_ProcessorARMv5_VFP_RegistersOnStack" )) { return true; } } } return false; } //--// protected override void ComputeRegisterFlushFixup( BitVector registersToSave ) { while(true) { bool fDone = true; foreach(ZeligIR.Abstractions.RegisterDescriptor regToSave in this.GetRegisters()) { int pos = (int)regToSave.Encoding; if(registersToSave[pos]) { uint size = regToSave.PhysicalStorageSize; foreach(ZeligIR.Abstractions.RegisterDescriptor regInterfere in regToSave.InterfersWith) { if(regInterfere.PhysicalStorageSize > size) { registersToSave.Set ( (int)regInterfere.Encoding ); registersToSave.Clear( pos ); fDone = false; break; } } } } if(fDone) { break; } } } } } ================================================ FILE: Zelig/Zelig/CompileTime/TargetModels/ProductConfiguration/Abstractions/ARM/ArchitectureVersions/ArmV5_VFP_CollectRegisterAllocationConstraints.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // namespace Microsoft.Zelig.Configuration.Environment.Abstractions.Architectures { using System; using System.Collections.Generic; using Microsoft.Zelig.Runtime.TypeSystem; using Microsoft.Zelig.TargetModel.ArmProcessor; using ZeligIR = Microsoft.Zelig.CodeGeneration.IR; public sealed partial class ArmV5_VFP { class CollectRegisterAllocationConstraints { // // Helper Methods // //--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--// //--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--// //--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--// [ZeligIR.CompilationSteps.PhaseFilter( typeof(ZeligIR.CompilationSteps.Phases.CollectRegisterAllocationConstraints) )] [ZeligIR.CompilationSteps.OperatorHandler( typeof(ZeligIR.SingleAssignmentOperator) )] private void Handle_SingleAssignmentOperator( ZeligIR.CompilationSteps.PhaseExecution.NotificationContext nc ) { var op = (ZeligIR.SingleAssignmentOperator)nc.CurrentOperator; if(op.FirstArgument is ZeligIR.ConstantExpression) { SetConstraintOnLhsBasedOnType( nc, op.Results, 0 ); } } [ZeligIR.CompilationSteps.PhaseFilter( typeof(ZeligIR.CompilationSteps.Phases.CollectRegisterAllocationConstraints) )] [ZeligIR.CompilationSteps.OperatorHandler( typeof(ZeligIR.LoadIndirectOperator) )] private void Handle_LoadIndirectOperator( ZeligIR.CompilationSteps.PhaseExecution.NotificationContext nc ) { SetConstraintOnLhsBasedOnType( nc, nc.CurrentOperator.Results, 0 ); } [ZeligIR.CompilationSteps.PhaseFilter( typeof(ZeligIR.CompilationSteps.Phases.CollectRegisterAllocationConstraints) )] [ZeligIR.CompilationSteps.OperatorHandler( typeof(ZeligIR.StoreIndirectOperator) )] private void Handle_StoreIndirectOperator( ZeligIR.CompilationSteps.PhaseExecution.NotificationContext nc ) { SetConstraintOnRhsBasedOnType( nc, nc.CurrentOperator.Arguments, 1 ); } [ZeligIR.CompilationSteps.PhaseFilter( typeof(ZeligIR.CompilationSteps.Phases.CollectRegisterAllocationConstraints) )] [ZeligIR.CompilationSteps.OperatorHandler( typeof(ZeligIR.IndirectOperator ) )] [ZeligIR.CompilationSteps.OperatorHandler( typeof(ZeligIR.AddressAssignmentOperator ) )] [ZeligIR.CompilationSteps.OperatorHandler( typeof(ZeligIR.IndirectSubroutineOperator) )] private void Handle_AddressForFirstArgument( ZeligIR.CompilationSteps.PhaseExecution.NotificationContext nc ) { SetConstraintOnRHS( nc, 0, ZeligIR.Abstractions.RegisterClass.Address ); } [ZeligIR.CompilationSteps.PhaseFilter( typeof(ZeligIR.CompilationSteps.Phases.CollectRegisterAllocationConstraints) )] [ZeligIR.CompilationSteps.OperatorHandler( typeof(ZeligIR.SetIfConditionIsTrueOperator) )] [ZeligIR.CompilationSteps.OperatorHandler( typeof(ZeligIR.ConversionOperator ) )] [ZeligIR.CompilationSteps.OperatorHandler( typeof(ARM.MoveFromCoprocessor ) )] [ZeligIR.CompilationSteps.OperatorHandler( typeof(ARM.GetStatusRegisterOperator ) )] private void Handle_IntegerForResult( ZeligIR.CompilationSteps.PhaseExecution.NotificationContext nc ) { SetConstraintOnLHS( nc, 0, ZeligIR.Abstractions.RegisterClass.Integer ); } [ZeligIR.CompilationSteps.PhaseFilter( typeof(ZeligIR.CompilationSteps.Phases.CollectRegisterAllocationConstraints) )] [ZeligIR.CompilationSteps.OperatorHandler( typeof(ZeligIR.MultiWayConditionalControlOperator) )] [ZeligIR.CompilationSteps.OperatorHandler( typeof(ZeligIR.ConversionOperator ) )] [ZeligIR.CompilationSteps.OperatorHandler( typeof(ARM.MoveToCoprocessor ) )] [ZeligIR.CompilationSteps.OperatorHandler( typeof(ARM.SetStatusRegisterOperator ) )] private void Handle_IntegerForFirstArgument( ZeligIR.CompilationSteps.PhaseExecution.NotificationContext nc ) { SetConstraintOnRHS( nc, 0, ZeligIR.Abstractions.RegisterClass.Integer ); } [ZeligIR.CompilationSteps.PhaseFilter( typeof(ZeligIR.CompilationSteps.Phases.CollectRegisterAllocationConstraints) )] [ZeligIR.CompilationSteps.OperatorHandler( typeof(ZeligIR.ConvertOperator) )] private void Handle_ConvertOperator( ZeligIR.CompilationSteps.PhaseExecution.NotificationContext nc ) { ZeligIR.ConvertOperator op = (ZeligIR.ConvertOperator)nc.CurrentOperator; bool fInputFloat; bool fOutputFloat; switch(op.InputKind) { case TypeRepresentation.BuiltInTypes.R4: case TypeRepresentation.BuiltInTypes.R8: fInputFloat = true; break; default: fInputFloat = false; break; } switch(op.OutputKind) { case TypeRepresentation.BuiltInTypes.R4: case TypeRepresentation.BuiltInTypes.R8: fOutputFloat = true; break; default: fOutputFloat = false; break; } CHECKS.ASSERT( fOutputFloat || fInputFloat, "Expecting at least one floating point argument to {0}", op ); if(fOutputFloat || fInputFloat) { SetConstraintOnRHS( nc, 0, op.InputKind == TypeRepresentation.BuiltInTypes.R8 ? ZeligIR.Abstractions.RegisterClass.DoublePrecision : ZeligIR.Abstractions.RegisterClass.SinglePrecision ); SetConstraintOnLHS( nc, 0, op.OutputKind == TypeRepresentation.BuiltInTypes.R8 ? ZeligIR.Abstractions.RegisterClass.DoublePrecision : ZeligIR.Abstractions.RegisterClass.SinglePrecision ); } } [ZeligIR.CompilationSteps.PhaseFilter( typeof(ZeligIR.CompilationSteps.Phases.CollectRegisterAllocationConstraints) )] [ZeligIR.CompilationSteps.OperatorHandler( typeof(ZeligIR.AbstractUnaryOperator ) )] [ZeligIR.CompilationSteps.OperatorHandler( typeof(ZeligIR.AbstractBinaryOperator) )] [ZeligIR.CompilationSteps.OperatorHandler( typeof(ARM.VectorHack_Finalize ) )] private void Handle_GenericComputation( ZeligIR.CompilationSteps.PhaseExecution.NotificationContext nc ) { ZeligIR.Operator op = nc.CurrentOperator; SetConstraintOnResultsBasedOnType ( nc, op.Results ); SetConstraintOnArgumentsBasedOnType( nc, op.Arguments ); } [ZeligIR.CompilationSteps.PhaseFilter( typeof(ZeligIR.CompilationSteps.Phases.CollectRegisterAllocationConstraints) )] [ZeligIR.CompilationSteps.OperatorHandler( typeof(ZeligIR.CompareOperator ) )] [ZeligIR.CompilationSteps.OperatorHandler( typeof(ZeligIR.ConditionalCompareOperator) )] private void Handle_CompareOperators( ZeligIR.CompilationSteps.PhaseExecution.NotificationContext nc ) { ZeligIR.Operator op = nc.CurrentOperator; SetConstraintOnArgumentsBasedOnType( nc, op.Arguments ); } } } } ================================================ FILE: Zelig/Zelig/CompileTime/TargetModels/ProductConfiguration/Abstractions/ARM/ArchitectureVersions/ArmV5_VFP_Emulation.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // namespace Microsoft.Zelig.Configuration.Environment.Abstractions.Architectures { using System; using System.Collections.Generic; using Microsoft.Zelig.Runtime.TypeSystem; using Microsoft.Zelig.TargetModel.ArmProcessor; using ZeligIR = Microsoft.Zelig.CodeGeneration.IR; public sealed partial class ArmV5_VFP { public class FloatingPointEmulation { const string c_Convert_LongToFloat = "SoftVFP_Convert_LongToFloat"; const string c_Convert_UnsignedLongToFloat = "SoftVFP_Convert_UnsignedLongToFloat"; const string c_Convert_DoubleToFloat = "SoftVFP_Convert_DoubleToFloat"; const string c_Convert_LongToDouble = "SoftVFP_Convert_LongToDouble"; const string c_Convert_UnsignedLongToDouble = "SoftVFP_Convert_UnsignedLongToDouble"; const string c_Convert_FloatToLong = "SoftVFP_Convert_FloatToLong"; const string c_Convert_FloatToUnsignedLong = "SoftVFP_Convert_FloatToUnsignedLong"; const string c_Convert_DoubleToLong = "SoftVFP_Convert_DoubleToLong"; const string c_Convert_DoubleToUnsignedLong = "SoftVFP_Convert_DoubleToUnsignedLong"; const string c_BinaryOperations_FloatRem = "SoftVFP_BinaryOperations_FloatRem"; const string c_BinaryOperations_DoubleRem = "SoftVFP_BinaryOperations_DoubleRem"; //--// [ZeligIR.CompilationSteps.CallClosureHandler( typeof(ZeligIR.ConvertOperator) )] private static void Protect_ConvertOperator( ZeligIR.CompilationSteps.ComputeCallsClosure.Context host , ZeligIR.Operator target ) { ZeligIR.ConvertOperator op = (ZeligIR.ConvertOperator)target; ZeligIR.TypeSystemForCodeTransformation ts = host.TypeSystem; TypeRepresentation.BuiltInTypes kindInput = op.InputKind; TypeRepresentation.BuiltInTypes kindOutput = op.OutputKind; string name = null; switch(kindOutput) { case TypeRepresentation.BuiltInTypes.R4: switch(kindInput) { case TypeRepresentation.BuiltInTypes.I8: name = c_Convert_LongToFloat ; break; case TypeRepresentation.BuiltInTypes.U8: name = c_Convert_UnsignedLongToFloat; break; } break; case TypeRepresentation.BuiltInTypes.R8: switch(kindInput) { case TypeRepresentation.BuiltInTypes.I8: name = c_Convert_LongToDouble ; break; case TypeRepresentation.BuiltInTypes.U8: name = c_Convert_UnsignedLongToDouble; break; } break; case TypeRepresentation.BuiltInTypes.I8: switch(kindInput) { case TypeRepresentation.BuiltInTypes.R4: name = c_Convert_FloatToLong ; break; case TypeRepresentation.BuiltInTypes.R8: name = c_Convert_DoubleToLong; break; } break; case TypeRepresentation.BuiltInTypes.U8: switch(kindInput) { case TypeRepresentation.BuiltInTypes.R4: name = c_Convert_FloatToUnsignedLong ; break; case TypeRepresentation.BuiltInTypes.R8: name = c_Convert_DoubleToUnsignedLong; break; } break; } if(name != null) { host.CoverObject( ts.GetWellKnownMethod( name ) ); } } [ZeligIR.CompilationSteps.CallClosureHandler( typeof(ZeligIR.BinaryOperator) )] private static void Protect_BinaryOperator( ZeligIR.CompilationSteps.ComputeCallsClosure.Context host , ZeligIR.Operator target ) { ZeligIR.BinaryOperator op = (ZeligIR.BinaryOperator)target; TypeRepresentation td = op.FirstArgument.Type; ZeligIR.TypeSystemForCodeTransformation ts = host.TypeSystem; WellKnownTypes wkt = ts.WellKnownTypes; string name = null; if(td == wkt.System_Single) { switch(op.Alu) { case ZeligIR.BinaryOperator.ALU.REM: name = c_BinaryOperations_FloatRem; break; } } else if(td == wkt.System_Double) { switch(op.Alu) { case ZeligIR.BinaryOperator.ALU.REM: name = c_BinaryOperations_DoubleRem; break; } } if(name != null) { host.CoverObject( ts.GetWellKnownMethod( name ) ); } } //--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--// //--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--// //--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--// [ZeligIR.CompilationSteps.PhaseFilter( typeof(ZeligIR.CompilationSteps.Phases.FromImplicitToExplicitExceptions) )] [ZeligIR.CompilationSteps.OperatorHandler( typeof(ZeligIR.ConvertOperator) )] private static void Handle_ConvertOperator_Exceptions( ZeligIR.CompilationSteps.PhaseExecution.NotificationContext nc ) { ZeligIR.ConvertOperator op = (ZeligIR.ConvertOperator)nc.CurrentOperator; ZeligIR.VariableExpression lhs = op.FirstResult; ZeligIR.Expression rhs = op.FirstArgument; if(op.CheckOverflow) { ZeligIR.ConvertOperator opNew = ZeligIR.ConvertOperator.New( op.DebugInfo, op.InputKind, op.OutputKind, false, lhs, rhs ); op.SubstituteWithOperator( opNew, ZeligIR.Operator.SubstitutionFlags.CopyAnnotations ); // // BUGBUG: We are dropping the overflow check!! // //// CreateOverflowCheck( nc, op, opNew ); nc.MarkAsModified(); } } //--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--// //--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--// //--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--// [ZeligIR.CompilationSteps.PhaseFilter( typeof(ZeligIR.CompilationSteps.Phases.ConvertUnsupportedOperatorsToMethodCalls) )] [ZeligIR.CompilationSteps.OperatorHandler( typeof(ZeligIR.ConvertOperator) )] private static void Handle_ConvertOperator( ZeligIR.CompilationSteps.PhaseExecution.NotificationContext nc ) { ZeligIR.ConvertOperator op = (ZeligIR.ConvertOperator)nc.CurrentOperator; ZeligIR.TypeSystemForCodeTransformation ts = nc.TypeSystem; TypeRepresentation.BuiltInTypes kindInput = op.InputKind; TypeRepresentation.BuiltInTypes kindOutput = op.OutputKind; string name = null; switch(kindOutput) { case TypeRepresentation.BuiltInTypes.R4: switch(kindInput) { case TypeRepresentation.BuiltInTypes.I8: name = c_Convert_LongToFloat ; break; case TypeRepresentation.BuiltInTypes.U8: name = c_Convert_UnsignedLongToFloat; break; } break; case TypeRepresentation.BuiltInTypes.R8: switch(kindInput) { case TypeRepresentation.BuiltInTypes.I8: name = c_Convert_LongToDouble ; break; case TypeRepresentation.BuiltInTypes.U8: name = c_Convert_UnsignedLongToDouble; break; } break; case TypeRepresentation.BuiltInTypes.I8: switch(kindInput) { case TypeRepresentation.BuiltInTypes.R4: name = c_Convert_FloatToLong ; break; case TypeRepresentation.BuiltInTypes.R8: name = c_Convert_DoubleToLong; break; } break; case TypeRepresentation.BuiltInTypes.U8: switch(kindInput) { case TypeRepresentation.BuiltInTypes.R4: name = c_Convert_FloatToUnsignedLong ; break; case TypeRepresentation.BuiltInTypes.R8: name = c_Convert_DoubleToUnsignedLong; break; } break; } if(name != null) { MethodRepresentation md = ts.GetWellKnownMethod( name ); ZeligIR.Expression[] rhs = ts.AddTypePointerToArgumentsOfStaticMethod( md, op.FirstArgument, ts.CreateConstant( ts.WellKnownTypes.System_Boolean, op.CheckOverflow ) ); ZeligIR.StaticCallOperator opCall = ZeligIR.StaticCallOperator.New( op.DebugInfo, ZeligIR.CallOperator.CallKind.Direct, md, op.Results, rhs ); op.SubstituteWithOperator( opCall, ZeligIR.Operator.SubstitutionFlags.Default ); nc.MarkAsModified(); } } [ZeligIR.CompilationSteps.PhaseFilter( typeof(ZeligIR.CompilationSteps.Phases.ConvertUnsupportedOperatorsToMethodCalls) )] [ZeligIR.CompilationSteps.OperatorHandler( typeof(ZeligIR.BinaryOperator) )] private static void Handle_BinaryOperator( ZeligIR.CompilationSteps.PhaseExecution.NotificationContext nc ) { ZeligIR.BinaryOperator op = (ZeligIR.BinaryOperator)nc.CurrentOperator; ZeligIR.Expression exSrc1 = op.FirstArgument; ZeligIR.Expression exSrc2 = op.SecondArgument; TypeRepresentation tdSrc1 = exSrc1.Type; TypeRepresentation tdSrc2 = exSrc2.Type; if(tdSrc1.IsFloatingPoint && tdSrc2.IsFloatingPoint ) { ZeligIR.ControlFlowGraphStateForCodeTransformation cfg = nc.CurrentCFG; ZeligIR.TypeSystemForCodeTransformation ts = nc.TypeSystem; ZeligIR.VariableExpression exRes = op.FirstResult; TypeRepresentation tdRes = exRes .Type; uint sizeRes = tdRes .SizeOfHoldingVariableInWords; uint sizeSrc1 = tdSrc1.SizeOfHoldingVariableInWords; uint sizeSrc2 = tdSrc2.SizeOfHoldingVariableInWords; string name = null; CHECKS.ASSERT( sizeSrc1 == sizeSrc2, "Cannot compare entities of different size: {0} <=> {1}", exSrc1, exSrc2 ); if(sizeSrc1 == 1) { switch(op.Alu) { case ZeligIR.BinaryOperator.ALU.REM: name = c_BinaryOperations_FloatRem; break; } } else if(sizeSrc1 == 2) { switch(op.Alu) { case ZeligIR.BinaryOperator.ALU.REM: name = c_BinaryOperations_DoubleRem; break; } } else { throw TypeConsistencyErrorException.Create( "Unsupported inputs for binary operator: {0}", op ); } if(name != null) { ts.SubstituteWithCallToHelper( name, op ); nc.MarkAsModified(); } } } } } } ================================================ FILE: Zelig/Zelig/CompileTime/TargetModels/ProductConfiguration/Abstractions/ARM/ArmCallingConvention.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // namespace Microsoft.Zelig.Configuration.Environment.Abstractions { using System; using System.Collections.Generic; using Microsoft.Zelig.Runtime.TypeSystem; using Microsoft.Zelig.TargetModel.ArmProcessor; using ZeligIR = Microsoft.Zelig.CodeGeneration.IR; public class ArmCallingConvention : ZeligIR.Abstractions.CallingConvention { class ArmCallState : ZeligIR.Abstractions.CallingConvention.CallState { // // State // internal int m_numberOfWordsPassedInRegistersForIntegers; internal int m_numberOfWordsPassedInRegistersForFloatingPoints; internal int m_numberOfWordsPerArgument; internal uint m_nextRegForArgumentsInteger; internal uint m_nextRegForArgumentsFloatingPoint; internal uint m_nextRegForResultValueInteger; internal uint m_nextRegForResultValueFloatingPoint; internal uint m_nextStackIn; internal uint m_nextStackLocal; internal uint m_nextStackOut; // // Constructor Methods // internal ArmCallState() // Default constructor required by TypeSystemSerializer. { } internal ArmCallState( Direction direction , int numberOfWordsPassedInRegistersForIntegers , int numberOfWordsPassedInRegistersForFloatingPoints , int numberOfWordsPerArgument ) : base( direction ) { m_numberOfWordsPassedInRegistersForIntegers = numberOfWordsPassedInRegistersForIntegers; m_numberOfWordsPassedInRegistersForFloatingPoints = numberOfWordsPassedInRegistersForFloatingPoints; m_numberOfWordsPerArgument = numberOfWordsPerArgument; } // // Helper Methods // public override void ApplyTransformation( TransformationContext context ) { ZeligIR.TransformationContextForCodeTransformation context2 = (ZeligIR.TransformationContextForCodeTransformation)context; context2.Push( this ); base.ApplyTransformation( context2 ); context2.Transform( ref m_numberOfWordsPassedInRegistersForIntegers ); context2.Transform( ref m_numberOfWordsPassedInRegistersForFloatingPoints ); context2.Transform( ref m_numberOfWordsPerArgument ); context2.Transform( ref m_nextRegForArgumentsInteger ); context2.Transform( ref m_nextRegForArgumentsFloatingPoint ); context2.Transform( ref m_nextRegForResultValueInteger ); context2.Transform( ref m_nextRegForResultValueFloatingPoint ); context2.Transform( ref m_nextStackIn ); context2.Transform( ref m_nextStackLocal ); context2.Transform( ref m_nextStackOut ); context2.Pop(); } public override ZeligIR.Abstractions.RegisterDescriptor GetNextRegister( ZeligIR.Abstractions.Platform platform , TypeRepresentation sourceTd , TypeRepresentation fragmentTd , ZeligIR.ControlFlowGraphStateForCodeTransformation.KindOfFragment kind ) { switch(kind) { case ZeligIR.ControlFlowGraphStateForCodeTransformation.KindOfFragment.CopyIncomingArgumentFromPhysicalToPseudoRegister: case ZeligIR.ControlFlowGraphStateForCodeTransformation.KindOfFragment.AllocatePhysicalRegisterForArgument: case ZeligIR.ControlFlowGraphStateForCodeTransformation.KindOfFragment.AllocatePhysicalRegisterForReturnValue: int idx = GetNextIndex( platform, sourceTd, fragmentTd, kind ); return platform.GetRegisters()[idx]; } throw TypeConsistencyErrorException.Create( "Unexpected fragment kind {0}", kind ); } public override int GetNextIndex( ZeligIR.Abstractions.Platform platform , TypeRepresentation sourceTd , TypeRepresentation fragmentTd , ZeligIR.ControlFlowGraphStateForCodeTransformation.KindOfFragment kind ) { switch(kind) { case ZeligIR.ControlFlowGraphStateForCodeTransformation.KindOfFragment.CopyIncomingArgumentFromPhysicalToPseudoRegister: case ZeligIR.ControlFlowGraphStateForCodeTransformation.KindOfFragment.AllocatePhysicalRegisterForArgument: return GetNextIndex( platform, fragmentTd, ref m_nextRegForArgumentsInteger, ref m_nextRegForArgumentsFloatingPoint ); case ZeligIR.ControlFlowGraphStateForCodeTransformation.KindOfFragment.AllocatePhysicalRegisterForReturnValue: return GetNextIndex( platform, fragmentTd, ref m_nextRegForResultValueInteger, ref m_nextRegForResultValueFloatingPoint ); case ZeligIR.ControlFlowGraphStateForCodeTransformation.KindOfFragment.CopyIncomingArgumentFromStackToPseudoRegister: case ZeligIR.ControlFlowGraphStateForCodeTransformation.KindOfFragment.AllocateStackInLocation: return (int)m_nextStackIn++; case ZeligIR.ControlFlowGraphStateForCodeTransformation.KindOfFragment.AllocateStackLocalLocation: return (int)m_nextStackLocal++; case ZeligIR.ControlFlowGraphStateForCodeTransformation.KindOfFragment.AllocateStackOutLocation: return (int)m_nextStackOut++; } throw TypeConsistencyErrorException.Create( "Unexpected fragment kind {0}", kind ); } public override bool CanMapToRegister( ZeligIR.Abstractions.Platform platform , TypeRepresentation td ) { uint requiredRegisters = td.SizeOfHoldingVariableInWords; if(ShouldUseFloatingPointRegister( platform, td )) { uint nextReg = m_nextRegForArgumentsFloatingPoint; if(requiredRegisters == 2 && ((nextReg & 1) != 0)) nextReg++; // Align to Double-Precision register boundary. return ( requiredRegisters <= m_numberOfWordsPassedInRegistersForFloatingPoints && nextReg + requiredRegisters <= m_numberOfWordsPassedInRegistersForFloatingPoints ); } else { return ( requiredRegisters <= m_numberOfWordsPassedInRegistersForIntegers && m_nextRegForArgumentsInteger + requiredRegisters <= m_numberOfWordsPassedInRegistersForIntegers ); } } public override bool CanMapResultToRegister( ZeligIR.Abstractions.Platform platform , TypeRepresentation td ) { uint requiredRegisters = td.SizeOfHoldingVariableInWords; return (requiredRegisters <= m_numberOfWordsPerArgument); } //--// private static bool ShouldUseFloatingPointRegister( ZeligIR.Abstractions.Platform platform , TypeRepresentation td ) { if(td.IsFloatingPoint) { ArmPlatform paArm = (ArmPlatform)platform; if(paArm.HasVFPv2) { return true; } } return false; } private static int GetNextIndex( ZeligIR.Abstractions.Platform platform , TypeRepresentation td , ref uint nextRegInteger , ref uint nextRegFloatingPoint ) { uint encoding; if(ShouldUseFloatingPointRegister( platform, td )) { uint requiredRegisters = td.SizeOfHoldingVariableInWords; uint nextReg = nextRegFloatingPoint; if(requiredRegisters == 2 && ((nextReg & 1) != 0)) nextReg++; // Align to Double-Precision register boundary. nextRegFloatingPoint = nextReg + requiredRegisters; if(requiredRegisters == 2) { encoding = EncodingDefinition_VFP.c_register_d0 + (nextReg / 2); } else { encoding = EncodingDefinition_VFP.c_register_s0 + nextReg; } } else { uint nextReg = nextRegInteger++; encoding = EncodingDefinition.c_register_r0 + nextReg; } foreach(var regDesc in platform.GetRegisters()) { if(regDesc.Encoding == encoding) { return regDesc.Index; } } throw TypeConsistencyErrorException.Create( "Failed to find register with encoding {0}", encoding ); } } // // State // internal int m_numberOfWordsPassedInRegistersForIntegers = 4; internal int m_numberOfWordsPassedInRegistersForFloatingPoints = 4; internal int m_numberOfWordsPerArgument = 2; // // Constructor Methods // public ArmCallingConvention() // Default constructor required by TypeSystemSerializer. { } public ArmCallingConvention( ZeligIR.TypeSystemForCodeTransformation typeSystem ) : base( typeSystem ) { } // // Helper Methods // public override void RegisterForNotifications( ZeligIR.TypeSystemForCodeTransformation ts , ZeligIR.CompilationSteps.DelegationCache cache ) { } //--// public override CallState CreateCallState( Direction direction ) { ArmPlatform paArm = (ArmPlatform)m_typeSystem.PlatformAbstraction; if(paArm.HasVFPv2) { return new ArmCallState( direction, m_numberOfWordsPassedInRegistersForIntegers, m_numberOfWordsPassedInRegistersForFloatingPoints, m_numberOfWordsPerArgument ); } else { return new ArmCallState( direction, m_numberOfWordsPassedInRegistersForIntegers, 0, m_numberOfWordsPerArgument ); } } public override ZeligIR.Expression[] AssignArgument( ZeligIR.ControlFlowGraphStateForCodeTransformation cfg , ZeligIR.Operator insertionOp , ZeligIR.Expression ex , TypeRepresentation td , ZeligIR.Abstractions.CallingConvention.CallState callState ) { ZeligIR.VariableExpression sourceVar = ex as ZeligIR.VariableExpression; ZeligIR.VariableExpression.DebugInfo debugInfo; ZeligIR.ControlFlowGraphStateForCodeTransformation.KindOfFragment kind; if(callState.Direction == Direction.Caller) { // // On the caller side, we don't associate the fragments with the original expression, // since the same fragments will be used for multiple expressions, on different method calls. // sourceVar = null; debugInfo = null; } else { debugInfo = sourceVar.DebugName; } if(callState.CanMapToRegister( cfg.TypeSystem.PlatformAbstraction, td )) { if(callState.Direction == Direction.Callee) { kind = ZeligIR.ControlFlowGraphStateForCodeTransformation.KindOfFragment.CopyIncomingArgumentFromPhysicalToPseudoRegister; } else { kind = ZeligIR.ControlFlowGraphStateForCodeTransformation.KindOfFragment.AllocatePhysicalRegisterForArgument; } return cfg.MapExpressionToFragments( insertionOp, debugInfo, sourceVar, td, callState, kind ); } else { if(callState.Direction == Direction.Callee) { kind = ZeligIR.ControlFlowGraphStateForCodeTransformation.KindOfFragment.CopyIncomingArgumentFromStackToPseudoRegister; } else { kind = ZeligIR.ControlFlowGraphStateForCodeTransformation.KindOfFragment.AllocateStackOutLocation; } return cfg.MapExpressionToFragments( insertionOp, debugInfo, sourceVar, td, callState, kind ); } } public override ZeligIR.Expression[] AssignReturnValue( ZeligIR.ControlFlowGraphStateForCodeTransformation cfg , ZeligIR.Operator insertionOp , ZeligIR.VariableExpression exReturnValue , TypeRepresentation tdReturnValue , ZeligIR.Abstractions.CallingConvention.CallState callState ) { ZeligIR.VariableExpression.DebugInfo debugInfo; if(exReturnValue != null) { debugInfo = exReturnValue.DebugName; } else { debugInfo = null; } if(callState.Direction == Direction.Caller) { // // On the caller side, we don't associate the fragments with the original expression, // since the same fragments will be used for multiple expressions, on different method calls. // exReturnValue = null; debugInfo = null; } if(callState.CanMapResultToRegister( cfg.TypeSystem.PlatformAbstraction, tdReturnValue )) { return cfg.MapExpressionToFragments( insertionOp, debugInfo, exReturnValue, tdReturnValue, callState, ZeligIR.ControlFlowGraphStateForCodeTransformation.KindOfFragment.AllocatePhysicalRegisterForReturnValue ); } else { ZeligIR.ControlFlowGraphStateForCodeTransformation.KindOfFragment kind; if(callState.Direction == Direction.Callee) { kind = ZeligIR.ControlFlowGraphStateForCodeTransformation.KindOfFragment.AllocateStackInLocation; } else { kind = ZeligIR.ControlFlowGraphStateForCodeTransformation.KindOfFragment.AllocateStackOutLocation; } // // For methods whose return value is too big, share the return value variable as the first slot on the stack. // return cfg.MapExpressionToFragments( insertionOp, debugInfo, exReturnValue, tdReturnValue, callState, kind ); } } public override ZeligIR.VariableExpression[] CollectExpressionsToInvalidate( ZeligIR.ControlFlowGraphStateForCodeTransformation cfg , ZeligIR.CallOperator op , ZeligIR.Expression[] resFragments ) { ZeligIR.VariableExpression[] res = ZeligIR.VariableExpression.SharedEmptyArray; ZeligIR.Abstractions.CallingConvention.CallState callState = cfg.TypeSystem.CallingConvention.CreateCallState( Direction.Caller ); // // Because of the aliasing between physical registers, it's important that we add the expressions to invalidate // in the right order: // // 1) Actual return values (first because we need that value after the call) // 2) Formal return values // 3) Call arguments // 4) Registers and stack locations affected by the calling convention. // res = MergeFragments( res, resFragments ); if(op != null) { MethodRepresentation md = op.TargetMethod; { TypeRepresentation tdReturn = md.ReturnType; if(tdReturn != cfg.TypeSystem.WellKnownTypes.System_Void) { ZeligIR.Expression[] resFormalFragments = AssignReturnValue( cfg, null, null, tdReturn, callState ); res = MergeFragments( res, resFormalFragments ); } } foreach(TypeRepresentation tdArg in md.ThisPlusArguments) { ZeligIR.Expression[] argFragments = AssignArgument( cfg, null, null, tdArg, callState ); res = MergeFragments( res, argFragments ); } } foreach(ZeligIR.Abstractions.RegisterDescriptor regDesc in m_typeSystem.PlatformAbstraction.GetRegisters()) { bool fAdd = false; if(regDesc.InIntegerRegisterFile) { // // These registers are part of the calling convention, they can be scratched. // if((regDesc.Encoding - EncodingDefinition.c_register_r0) < m_numberOfWordsPassedInRegistersForIntegers || regDesc.Encoding == EncodingDefinition.c_register_r12 || regDesc.Encoding == EncodingDefinition.c_register_lr ) { fAdd = true; } } if(regDesc.InFloatingPointRegisterFile) { // // These registers are part of the calling convention, they can be scratched. // if(regDesc.IsDoublePrecision) { if(ArmCompilationState.GetDoublePrecisionEncoding( regDesc ) < m_numberOfWordsPassedInRegistersForFloatingPoints) { fAdd = true; } } else { if(ArmCompilationState.GetSinglePrecisionEncoding( regDesc ) < m_numberOfWordsPassedInRegistersForFloatingPoints) { fAdd = true; } } } if(fAdd) { res = AddUniqueToFragment( res, cfg.AllocatePhysicalRegister( regDesc ) ); } } res = AddUniqueToFragment( res, cfg.AllocateConditionCode() ); return CollectAddressTakenExpressionsToInvalidate( cfg, res, op ); } public override bool ShouldSaveRegister( ZeligIR.Abstractions.RegisterDescriptor regDesc ) { if(regDesc.IsSpecial) { return false; } if(regDesc.IsSystemRegister) { return false; } if(regDesc.InIntegerRegisterFile) { if((regDesc.Encoding - EncodingDefinition.c_register_r0 ) < m_numberOfWordsPassedInRegistersForIntegers || regDesc.Encoding == EncodingDefinition.c_register_r12 || regDesc.Encoding == EncodingDefinition.c_register_lr ) { // // These registers are part of the calling convention, they can be scratched. // return false; } } if(regDesc.InFloatingPointRegisterFile) { if(regDesc.IsDoublePrecision) { if(ArmCompilationState.GetDoublePrecisionEncoding( regDesc ) < m_numberOfWordsPassedInRegistersForFloatingPoints) { // // These registers are part of the calling convention, they can be scratched. // return false; } } else { if(ArmCompilationState.GetSinglePrecisionEncoding( regDesc ) < m_numberOfWordsPassedInRegistersForFloatingPoints) { // // These registers are part of the calling convention, they can be scratched. // return false; } } } return true; } } } ================================================ FILE: Zelig/Zelig/CompileTime/TargetModels/ProductConfiguration/Abstractions/ARM/ArmPlatform.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // namespace Microsoft.Zelig.Configuration.Environment.Abstractions { using System; using System.Collections.Generic; using Microsoft.Zelig.Runtime.TypeSystem; using Microsoft.Zelig.TargetModel.ArmProcessor; using ZeligIR = Microsoft.Zelig.CodeGeneration.IR; public abstract partial class ArmPlatform : ZeligIR.Abstractions.Platform { public enum Comparison : uint { Equal = 0x00, // EQ => Z set NotEqual = 0x01, // NE => Z clear CarrySet = 0x02, // CS/HS => C set CarryClear = 0x03, // CC/LO => C clear Negative = 0x04, // MI => N set PositiveOrZero = 0x05, // PL => N clear Overflow = 0x06, // VS => V set NoOverflow = 0x07, // VC => V clear UnsignedHigherThan = 0x08, // HI => C set and Z clear UnsignedLowerThanOrSame = 0x09, // LS => C clear or Z set SignedGreaterThanOrEqual = 0x0A, // GE => N set and V set, or N clear and V clear (N == V) SignedLessThan = 0x0B, // LT => N set and V clear, or N clear and V set (N != V) SignedGreaterThan = 0x0C, // GT => Z clear, and either N set and V set, or N clear and V clear (Z ==0, N == V) SignedLessThanOrEqual = 0x0D, // LE => Z set, or N set and V clear, or N clear and V set (Z == 1 or N != V) Always = 0x0E, // AL Always (unconditional) NotValid = 0x0F, // UnsignedHigherThanOrSame = CarrySet , UnsignedLowerThan = CarryClear, } [Flags] public enum Capabilities : uint { None = 0x00000000, ARMv4 = 0x00000001, ARMv5 = 0x00000002, ARMv6M = 0x00000004, ARMv7M = 0x00000008, ARMv7R = 0x00000010, ARMv7A = 0x00000020, VFPv2 = 0x00010000, } // // State // private List< Runtime.Memory.Range > m_memoryBlocks; private Capabilities m_processorCapabilities; private ZeligIR.Abstractions.PlacementRequirements m_memoryRequirement_VectorTable; private ZeligIR.Abstractions.PlacementRequirements m_memoryRequirement_Bootstrap; private ZeligIR.Abstractions.PlacementRequirements m_memoryRequirement_Code; private ZeligIR.Abstractions.PlacementRequirements m_memoryRequirement_Data_RW; private ZeligIR.Abstractions.PlacementRequirements m_memoryRequirement_Data_RO; private bool m_fGotVectorTable; private MethodRepresentation m_vectorTable; // // Constructor Methods // protected ArmPlatform( Capabilities processorCapabilities ) { AllocateState( processorCapabilities ); } protected ArmPlatform( ZeligIR.TypeSystemForCodeTransformation typeSystem , MemoryMapCategory memoryMap , Capabilities processorCapabilities ) : base( typeSystem ) { AllocateState( processorCapabilities ); if(memoryMap != null) { ConfigureMemoryMap( memoryMap ); } //--// List< ZeligIR.Abstractions.RegisterDescriptor > regs = new List< ZeligIR.Abstractions.RegisterDescriptor >(); CreateRegisters( regs ); m_registers = regs.ToArray(); } public override InstructionSet GetInstructionSetProvider() { if(m_instructionSetProvider == null) { InstructionSetVersion iset = InstructionSetVersion.Build( this.PlatformFamily ).With( this.PlatformVersion ).With( this.PlatformVFP ); if(this.HasVFPv2) { m_instructionSetProvider = new TargetModel.ArmProcessor.InstructionSet_VFP( iset ); } else { m_instructionSetProvider = new TargetModel.ArmProcessor.InstructionSet( iset ); } } return m_instructionSetProvider; } protected virtual void AllocateState( Capabilities processorCapabilities ) { m_processorCapabilities = processorCapabilities; m_memoryBlocks = new List< Runtime.Memory.Range >(); m_memoryRequirement_VectorTable = CreatePlacement( Runtime.MemoryUsage.VectorsTable ); m_memoryRequirement_Bootstrap = CreatePlacement( Runtime.MemoryUsage.Bootstrap ); m_memoryRequirement_Code = CreatePlacement( Runtime.MemoryUsage.Code ); m_memoryRequirement_Data_RO = CreatePlacement( Runtime.MemoryUsage.DataRO ); m_memoryRequirement_Data_RW = CreatePlacement( Runtime.MemoryUsage.DataRW ); } private static ZeligIR.Abstractions.PlacementRequirements CreatePlacement( Runtime.MemoryUsage usage ) { ZeligIR.Abstractions.PlacementRequirements pr = new ZeligIR.Abstractions.PlacementRequirements( sizeof(uint), 0 ); pr.AddConstraint( usage ); return pr; } // // Helper Methods // public override void ApplyTransformation( TransformationContext context ) { ZeligIR.TransformationContextForCodeTransformation context2 = (ZeligIR.TransformationContextForCodeTransformation)context; context2.Push( this ); base.ApplyTransformation( context2 ); context2.Transform( ref m_memoryBlocks ); context2.Transform( ref m_memoryRequirement_VectorTable ); context2.Transform( ref m_memoryRequirement_Bootstrap ); context2.Transform( ref m_memoryRequirement_Code ); context2.Transform( ref m_memoryRequirement_Data_RW ); context2.Transform( ref m_memoryRequirement_Data_RO ); context2.Transform( ref m_registers ); context2.Transform( ref m_scratchRegister ); context2.Pop(); } public override void RegisterForNotifications( ZeligIR.TypeSystemForCodeTransformation ts , ZeligIR.CompilationSteps.DelegationCache cache ) { cache.Register( this ); cache.Register( new ArmPlatform.PrepareForRegisterAllocation( this ) ); } public override TypeRepresentation GetRuntimeType( ZeligIR.TypeSystemForCodeTransformation ts , ZeligIR.Abstractions.RegisterDescriptor regDesc ) { WellKnownTypes wkt = ts.WellKnownTypes; if(regDesc.InIntegerRegisterFile) { return wkt.System_UIntPtr; } else if(regDesc.InFloatingPointRegisterFile) { if(regDesc.IsDoublePrecision) { return wkt.System_Double; } else { return wkt.System_Single; } } else { return wkt.System_UInt32; } } public override bool CanFitInRegister( TypeRepresentation td ) { if(td.IsFloatingPoint) { if(this.HasVFPv2) { return true; } } return (td.SizeOfHoldingVariableInWords <= 1); } //--// public void AddMemoryBlock( Runtime.Memory.Range range ) { m_memoryBlocks.Add( range ); } public void ConfigureMemoryMap( MemoryMapCategory memoryMap ) { foreach(AbstractCategory.ValueContext ctx in memoryMap.SearchValues( typeof(MemoryCategory) )) { MemoryCategory val = (MemoryCategory)ctx.Value; Runtime.MemoryAttributes flags = val.Characteristics; string name = null; Runtime.MemoryUsage usage = Runtime.MemoryUsage.Undefined; Type hnd = null; if((flags & (Runtime.MemoryAttributes.FLASH | Runtime.MemoryAttributes.RAM)) == 0) { // // Only interested in programmable memories, not peripherals. // continue; } MemorySectionAttribute attrib = ReflectionHelper.GetAttribute< MemorySectionAttribute >( ctx.Field, false ); if(attrib != null) { name = attrib.Name; usage = attrib.Usage; hnd = attrib.ExtensionHandler; } //--// uint address = val.BaseAddress; if(hnd != null) { object obj = Activator.CreateInstance( hnd ); if(obj is IMemoryMapper) { IMemoryMapper itf = (IMemoryMapper)obj; address = itf.GetCacheableAddress( address ); } } UIntPtr beginning = new UIntPtr( address ); UIntPtr end = new UIntPtr( address + val.SizeInBytes ); List< Runtime.Memory.Range > ranges = new List< Runtime.Memory.Range >(); ranges.Add( new Runtime.Memory.Range( beginning, end, name, flags, usage, hnd ) ); foreach(ReserveBlockAttribute resAttrib in ReflectionHelper.GetAttributes< ReserveBlockAttribute >( ctx.Field, false )) { UIntPtr blockStart = AddressMath.Increment( beginning , resAttrib.Offset ); UIntPtr blockEnd = AddressMath.Increment( blockStart, resAttrib.Size ); for(int i = ranges.Count; --i >= 0; ) { var rng = ranges[i]; Runtime.Memory.Range.SubstractionAction action = rng.ComputeSubstraction( blockStart, blockEnd ); if(action != Runtime.Memory.Range.SubstractionAction.RemoveNothing) { ranges.RemoveAt( i ); if(action == Runtime.Memory.Range.SubstractionAction.RemoveStart || action == Runtime.Memory.Range.SubstractionAction.RemoveMiddle ) { ranges.Insert( i, rng.CloneSettings( blockEnd, rng.End ) ); } if(action == Runtime.Memory.Range.SubstractionAction.RemoveMiddle || action == Runtime.Memory.Range.SubstractionAction.RemoveEnd ) { ranges.Insert( i, rng.CloneSettings( rng.Start, blockStart ) ); } } } } foreach(var rng in ranges) { AddMemoryBlock( rng ); } } } //--// public override void GetListOfMemoryBlocks( List< Runtime.Memory.Range > lst ) { lst.AddRange( m_memoryBlocks ); } public override ZeligIR.Abstractions.PlacementRequirements GetMemoryRequirements( object obj ) { if(m_fGotVectorTable == false) { m_fGotVectorTable = true; m_vectorTable = m_typeSystem.TryGetHandler( Runtime.HardwareException.VectorTable ); } // // TODO: Based on profiling data, we could decide to put some code or data in RAM. // MethodRepresentation md = null; if(obj is ZeligIR.ControlFlowGraphStateForCodeTransformation) { md = ((ZeligIR.ControlFlowGraphStateForCodeTransformation)obj).Method; } else if(obj is ZeligIR.BasicBlock) { md = ((ZeligIR.BasicBlock)obj).Owner.Method; } if(md != null) { ZeligIR.Abstractions.PlacementRequirements pr = m_typeSystem.GetPlacementRequirements( md ); if(pr != null) { return pr; } if(md == m_vectorTable) { return m_memoryRequirement_VectorTable; } switch(m_typeSystem.ExtractHardwareExceptionSettingsForMethod( md )) { case Runtime.HardwareException.Bootstrap: case Runtime.HardwareException.Reset: return m_memoryRequirement_Bootstrap; } return m_memoryRequirement_Code; } else if(obj is ZeligIR.DataManager.DataDescriptor) { ZeligIR.DataManager.DataDescriptor dd = (ZeligIR.DataManager.DataDescriptor)obj; ZeligIR.Abstractions.PlacementRequirements pr = dd.PlacementRequirements; if(pr != null) { return pr; } if(dd.IsMutable) { pr = m_memoryRequirement_Data_RW; } else { pr = m_memoryRequirement_Data_RO; } return pr; } throw TypeConsistencyErrorException.Create( "Unable to determine the memory requirements for {0}", obj ); } public override ZeligIR.ImageBuilders.CompilationState CreateCompilationState( ZeligIR.ImageBuilders.Core core , ZeligIR.ControlFlowGraphStateForCodeTransformation cfg ) { return new ArmCompilationState( core, cfg ); } // // Access Methods // public override string CodeGenerator { get { return InstructionSetVersion.CodeGenerator_Zelig; } } public override uint PlatformFamily { get { return InstructionSetVersion.Platform_Family__ARM; } } public override uint PlatformVersion { get { uint ver = InstructionSetVersion.Platform_Version__ARMv4; if(0 != (m_processorCapabilities & Capabilities.ARMv4)) { ver = InstructionSetVersion.Platform_Version__ARMv4; } else if(0 != ( m_processorCapabilities & Capabilities.ARMv5 )) { ver = InstructionSetVersion.Platform_Version__ARMv5; } else if(0 != ( m_processorCapabilities & Capabilities.ARMv6M )) { ver = InstructionSetVersion.Platform_Version__ARMv6M; } else if(0 != ( m_processorCapabilities & Capabilities.ARMv7M )) { ver = InstructionSetVersion.Platform_Version__ARMv7M; } else if(0 != ( m_processorCapabilities & Capabilities.ARMv7R )) { ver = InstructionSetVersion.Platform_Version__ARMv7R; } else if(0 != ( m_processorCapabilities & Capabilities.ARMv7A )) { ver = InstructionSetVersion.Platform_Version__ARMv7A; } return ver; } } public override uint PlatformVFP { get { uint vfp = InstructionSetVersion.Platform_VFP__NoVFP; if(0 != ( m_processorCapabilities & Capabilities.VFPv2 )) { vfp = InstructionSetVersion.Platform_VFP__HardVFP; } return vfp; } } public override bool PlatformBigEndian { get { return false; } } public override bool CanUseMultipleConditionCodes { get { return false; } } public override int EstimatedCostOfLoadOperation { get { return 1 + 3; } } public override int EstimatedCostOfStoreOperation { get { return 1 + 2; } } public override uint MemoryAlignment { get { return sizeof(uint); } } public Capabilities ProcessorCapabilities { get { return m_processorCapabilities; } } public bool HasVFPv2 { get { return (m_processorCapabilities & ArmPlatform.Capabilities.VFPv2) != 0; } } } } ================================================ FILE: Zelig/Zelig/CompileTime/TargetModels/ProductConfiguration/Abstractions/ARM/ArmPlatform_CompilationState.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // namespace Microsoft.Zelig.Configuration.Environment.Abstractions { using System; using System.Collections.Generic; using Microsoft.Zelig.TargetModel.ArmProcessor; using ZeligIR = Microsoft.Zelig.CodeGeneration.IR; public partial class ArmCompilationState : ZeligIR.ImageBuilders.CompilationState { // // State // internal ZeligIR.Abstractions.RegisterDescriptor m_reg_Scratch; internal ZeligIR.Abstractions.RegisterDescriptor m_reg_R0; internal ZeligIR.Abstractions.RegisterDescriptor m_reg_R1; internal ZeligIR.Abstractions.RegisterDescriptor m_reg_R2; internal ZeligIR.Abstractions.RegisterDescriptor m_reg_R3; internal ZeligIR.Abstractions.RegisterDescriptor m_reg_R4; internal ZeligIR.Abstractions.RegisterDescriptor m_reg_LR; internal ZeligIR.Abstractions.RegisterDescriptor m_reg_SP; internal ZeligIR.Abstractions.RegisterDescriptor m_reg_PC; internal ZeligIR.Abstractions.RegisterDescriptor m_reg_D0; internal ZeligIR.Abstractions.RegisterDescriptor m_reg_FPSCR; internal ZeligIR.Abstractions.RegisterDescriptor m_reg_FPEXC; private BitVector m_registersUsed = new BitVector(); private BitVector m_registersToSave = new BitVector(); private uint m_stackForWrapper; private uint m_stackForLocals; private uint m_stackForCalls; // // Constructor Methods // protected ArmCompilationState() // Default constructor required by TypeSystemSerializer. { } internal ArmCompilationState( ZeligIR.ImageBuilders.Core owner , ZeligIR.ControlFlowGraphStateForCodeTransformation cfg ) : base( owner, cfg ) { } // // Helper Methods // public override void ApplyTransformation( ZeligIR.TransformationContextForCodeTransformation context ) { context.Push( this ); base.ApplyTransformation( context ); context.Transform( ref m_registersUsed ); context.Transform( ref m_registersToSave ); context.Transform( ref m_stackForWrapper ); context.Transform( ref m_stackForLocals ); context.Transform( ref m_stackForCalls ); context.Pop(); } //--// protected override void PrepareDataStructures() { base.PrepareDataStructures(); //--// ZeligIR.Abstractions.Platform pa = m_cfg.TypeSystem.PlatformAbstraction; m_reg_Scratch = pa.GetScratchRegister(); m_reg_R0 = pa.GetRegisterForEncoding( EncodingDefinition_ARM.c_register_r0 ); m_reg_R1 = pa.GetRegisterForEncoding( EncodingDefinition_ARM.c_register_r1 ); m_reg_R2 = pa.GetRegisterForEncoding( EncodingDefinition_ARM.c_register_r2 ); m_reg_R3 = pa.GetRegisterForEncoding( EncodingDefinition_ARM.c_register_r3 ); m_reg_R4 = pa.GetRegisterForEncoding( EncodingDefinition_ARM.c_register_r4 ); m_reg_LR = pa.GetRegisterForEncoding( EncodingDefinition_ARM.c_register_lr ); m_reg_SP = pa.GetRegisterForEncoding( EncodingDefinition_ARM.c_register_sp ); m_reg_PC = pa.GetRegisterForEncoding( EncodingDefinition_ARM.c_register_pc ); m_reg_D0 = pa.GetRegisterForEncoding( EncodingDefinition_VFP_ARM.c_register_d0 ); m_reg_FPSCR = pa.GetRegisterForEncoding( EncodingDefinition_VFP_ARM.c_register_FPSCR ); m_reg_FPEXC = pa.GetRegisterForEncoding( EncodingDefinition_VFP_ARM.c_register_FPEXC ); } protected ZeligIR.Abstractions.RegisterDescriptor GetNextRegister( ZeligIR.Abstractions.RegisterDescriptor reg ) { ZeligIR.Abstractions.Platform pa = m_cfg.TypeSystem.PlatformAbstraction; return pa.GetRegisterForEncoding( reg.Encoding + 1 ); } //--// protected override void AssignStackLocations_RecordRegister( ZeligIR.PhysicalRegisterExpression regVar ) { m_registersUsed.Set( (int)regVar.RegisterDescriptor.Encoding ); } protected override void AssignStackLocations_RecordStackOut( ZeligIR.StackLocationExpression stackVar ) { m_stackForCalls = Math.Max( m_stackForCalls, (uint)stackVar.Number + 1 ); } protected override void AssignStackLocations_RecordStackLocal( List< StateForLocalStackAssignment > states ) { m_stackForLocals = StateForLocalStackAssignment.ComputeLayout( states ); } protected override void AssignStackLocations_Finalize() { ZeligIR.TypeSystemForCodeTransformation ts = m_cfg.TypeSystem; ZeligIR.Abstractions.Platform pa = ts.PlatformAbstraction; ZeligIR.Abstractions.CallingConvention cc = ts.CallingConvention; Runtime.HardwareException he; pa.ComputeSetOfRegistersToSave( cc, m_cfg, m_registersUsed, out m_registersToSave, out he ); uint savedBytes = ComputeSizeOfStackWrapper(); uint stackOffsetForOUT = 0; uint stackOffsetForLOCAL = stackOffsetForOUT + m_stackForCalls * sizeof(uint); uint stackOffsetForSAVED = stackOffsetForLOCAL + m_stackForLocals * sizeof(uint); uint stackOffsetForIN = stackOffsetForSAVED + savedBytes; m_stackOffsetForSAVED = stackOffsetForSAVED; foreach(var var in m_variables) { var stackVar = var as ZeligIR.StackLocationExpression; if(stackVar != null) { switch(stackVar.StackPlacement) { case ZeligIR.StackLocationExpression.Placement.In : stackVar.AllocationOffset = stackOffsetForIN + (uint)stackVar.Number * sizeof(uint); break; case ZeligIR.StackLocationExpression.Placement.Local: stackVar.AllocationOffset = stackOffsetForLOCAL + stackVar.AllocationOffset ; break; case ZeligIR.StackLocationExpression.Placement.Out : stackVar.AllocationOffset = stackOffsetForOUT + (uint)stackVar.Number * sizeof(uint); break; } } } } private uint ComputeSizeOfStackWrapper() { uint res = 0; ZeligIR.BasicBlock bb = m_cfg.EntryBasicBlock; ZeligIR.BasicBlock bbEnd = m_cfg.NormalizedEntryBasicBlock; while(bb != null && bb != bbEnd) { foreach(var op in bb.Operators) { var op2 = op as ARM.MoveIntegerRegistersOperator; if(op2 != null) { res += ComputeStackSize_ARM_MoveIntegerRegistersOperator( op2 ); continue; } var op3 = op as ARM.MoveFloatingPointRegistersOperator; if(op3 != null) { res += ComputeStackSize_ARM_MoveFloatingPointRegistersOperator( op3 ); continue; } ZeligIR.VariableExpression var; long value; if(op.IsAddOrSubAgainstConstant( out var, out value ) && GetRegisterDescriptor( var ) == m_reg_SP) { res = (uint)(res - value); continue; } var op4 = op as ZeligIR.UnconditionalControlOperator; if(op4 != null) { bb = op4.TargetBranch; break; } if(op is ZeligIR.ControlOperator) { throw NotImplemented(); } } } return res; } protected override void FixupEmptyRegion( ZeligIR.ImageBuilders.SequentialRegion reg ) { var sec = reg.GetSectionOfFixedSize( sizeof(uint) ); InstructionSet.Opcode_Breakpoint enc = this.Encoder.PrepareForBreakpoint; enc.Prepare( EncodingDefinition_ARM.c_cond_AL, // uint ConditionCodes , 0xFFFF ); // uint Value ); sec.Write( enc.Encode() ); } // // Access Methods // public ArmPlatform ArmPlatform { get { return (ArmPlatform)m_cfg.TypeSystem.PlatformAbstraction; } } } } ================================================ FILE: Zelig/Zelig/CompileTime/TargetModels/ProductConfiguration/Abstractions/ARM/ArmPlatform_CompilationState_CodeMap.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // namespace Microsoft.Zelig.Configuration.Environment.Abstractions { using System; using System.Collections.Generic; using Microsoft.Zelig.Runtime.TypeSystem; using Microsoft.Zelig.TargetModel.ArmProcessor; using ZeligIR = Microsoft.Zelig.CodeGeneration.IR; public partial class ArmCompilationState { class CodeMapBuilder { class Delta { // // State // internal uint Address; internal GCInfo.Kind PtrKind; internal ushort StorageNumber; internal bool IsRegister; internal bool IsAlive; // // Helper Methods // internal bool IsMatch( GCInfo.Kind ptrKind , ushort storageNumber , bool isRegister ) { return (this.PtrKind == ptrKind && this.StorageNumber == storageNumber && this.IsRegister == isRegister ); } // // Debug Methods // public override string ToString() { return string.Format( "0x{0:X8}: {1} {2}{3} {4}", this.Address, this.PtrKind, this.IsRegister ? "Reg" : "Stack", this.StorageNumber, this.IsAlive ? "ALIVE" : "DEAD" ); } } // // State // CodeMap m_codeMap; ZeligIR.ImageBuilders.SequentialRegion m_firstRegion; ZeligIR.ImageBuilders.SequentialRegion m_lastRegion; List< Delta > m_deltas; CodeMap.EncodedStackWalk[] m_workingArray; int m_workingPos; // // Constructor Methods // internal CodeMapBuilder( CodeMap cm ) { m_codeMap = cm; m_deltas = new List< Delta >(); } // // Helper Methods // internal void Compress( ArmCompilationState cs , ZeligIR.ImageBuilders.SequentialRegion reg ) { uint startAddress = reg.BaseAddress.ToUInt32(); if(m_lastRegion != null) { uint endAddress = m_lastRegion.EndAddress.ToUInt32(); if(endAddress != startAddress) { CHECKS.ASSERT( endAddress < startAddress, "Incorrect ordering of regions: {0} <=> {1}", reg, m_lastRegion ); Emit( cs ); } else if(reg.Context is ZeligIR.EntryBasicBlock) { // // Make sure the entry point to a method is always at the start of a range. // Emit( cs ); } } if(m_firstRegion == null) { m_firstRegion = reg; } m_lastRegion = reg; // // We assume that all the variables are dead on entry to a basic block. // for(int idx = 0; idx < cs.m_variables.Length; idx++) { CompressAddVariable( cs, cs.m_variables[idx], startAddress, false ); } foreach(ZeligIR.ImageBuilders.ImageAnnotation an in reg.AnnotationList) { ZeligIR.ImageBuilders.TrackVariableLifetime tvl = an as ZeligIR.ImageBuilders.TrackVariableLifetime; if(tvl != null) { CompressAddVariable( cs, (ZeligIR.VariableExpression)tvl.Target, startAddress + tvl.Offset, tvl.IsAlive ); } } } internal void CompressAddVariable( ArmCompilationState cs , ZeligIR.VariableExpression var , uint address , bool fIsAlive ) { if(ZeligIR.ImageBuilders.TrackVariableLifetime.ShouldTrackAsAPointer( var )) { GCInfo.Kind ptrKind = var.Type.ClassifyAsPointer(); if(var is ZeligIR.PhysicalRegisterExpression) { ZeligIR.PhysicalRegisterExpression varReg = (ZeligIR.PhysicalRegisterExpression)var; if(varReg.RegisterDescriptor.InIntegerRegisterFile) { Add( address, ptrKind, (int)varReg.RegisterDescriptor.Encoding, true, fIsAlive ); } } else if(var is ZeligIR.StackLocationExpression) { Add( address, ptrKind, (cs.GetOffsetOfStackLocation( var ) / sizeof(uint)), false, fIsAlive ); } else { CHECKS.ASSERT( false, "Unexpected variable tracked as pointer: {0}", var ); } } } internal void Emit( ArmCompilationState cs ) { if(m_firstRegion != null) { CodeMap.Range rng = new CodeMap.Range(); ZeligIR.BasicBlock bb = (ZeligIR.BasicBlock)m_firstRegion.Context; rng.Flags = cs.m_headerFlags; if(bb is ZeligIR.EntryBasicBlock) { rng.Flags |= CodeMap.Flags.EntryPoint; if(bb.Owner.Method.HasBuildTimeFlag( MethodRepresentation.BuildTimeAttributes.BottomOfCallStack )) { rng.Flags |= CodeMap.Flags.BottomOfCallStack; } } else if(bb is ZeligIR.ExceptionHandlerBasicBlock) { rng.Flags |= CodeMap.Flags.ExceptionHandler; } else { rng.Flags |= CodeMap.Flags.NormalCode; } rng.Start = m_firstRegion.BaseAddress; rng.End = m_lastRegion .EndAddress; //--// uint lastAddress = rng.Start.ToUInt32(); GCInfo.Kind currentPtrKind = GCInfo.Kind.Heap; m_workingArray = null; m_workingPos = 0; foreach(Delta dt in m_deltas) { // // Move forward the opcode pointer. // if(dt.Address != lastAddress) { CHECKS.ASSERT( dt.Address > lastAddress, "Incorrect delta sequence" ); uint diff = (dt.Address - lastAddress) / sizeof(uint); while(diff > 0) { uint count = Math.Min( diff, (uint)CodeMap.EncodedStackWalk.SkipMax ); AddTrackingInfo( CodeMap.EncodedStackWalk.SkipToOpcode, CodeMap.EncodedStackWalk.SkipMask, count ); diff -= count; } lastAddress = dt.Address; } if(dt.PtrKind != currentPtrKind) { uint val; switch(dt.PtrKind) { case GCInfo.Kind.Heap: val = (uint)CodeMap.EncodedStackWalk.TrackingHeapPointers; break; case GCInfo.Kind.Internal: val = (uint)CodeMap.EncodedStackWalk.TrackingInternalPointers; break; case GCInfo.Kind.Potential: val = (uint)CodeMap.EncodedStackWalk.TrackingPotentialPointers; break; default: throw TypeConsistencyErrorException.Create( "Unexcepted pointer kind: {0}", dt.PtrKind ); } AddTrackingInfo( CodeMap.EncodedStackWalk.SetMode, CodeMap.EncodedStackWalk.ModeMask, val ); currentPtrKind = dt.PtrKind; } if(dt.IsRegister) { CodeMap.EncodedStackWalk effect = dt.IsAlive ? CodeMap.EncodedStackWalk.EnterRegisterSet : CodeMap.EncodedStackWalk.LeaveRegisterSet; AddTrackingInfo( effect, CodeMap.EncodedStackWalk.RegisterMask, dt.StorageNumber ); } else { CodeMap.EncodedStackWalk effect = dt.IsAlive ? CodeMap.EncodedStackWalk.EnterStack : CodeMap.EncodedStackWalk.LeaveStack; ushort offset = dt.StorageNumber; if(offset <= (ushort)CodeMap.EncodedStackWalk.StackOffsetMax) { AddTrackingInfo( effect, CodeMap.EncodedStackWalk.StackOffsetMask, offset ); } else if(offset < 0xFF) { AddTrackingInfo( effect, CodeMap.EncodedStackWalk.StackOffsetMask, (uint)CodeMap.EncodedStackWalk.StackOffset8BitExtender ); AddTrackingInfo( (CodeMap.EncodedStackWalk)offset ); } else { AddTrackingInfo( effect, CodeMap.EncodedStackWalk.StackOffsetMask, (uint)CodeMap.EncodedStackWalk.StackOffset16BitExtender ); AddTrackingInfo( (CodeMap.EncodedStackWalk)(offset >> 0) ); AddTrackingInfo( (CodeMap.EncodedStackWalk)(offset >> 8) ); } } } if(m_workingArray != null) { rng.StackWalk = ArrayUtility.ExtractSliceFromNotNullArray( m_workingArray, 0, m_workingPos ); } m_codeMap.Ranges = ArrayUtility.AppendToNotNullArray( m_codeMap.Ranges, rng ); //--// m_deltas.Clear(); m_firstRegion = null; m_lastRegion = null; } } //--// private void Add( uint address , GCInfo.Kind ptrKind , int storageNumber , bool isRegister , bool isAlive ) { Add( address, ptrKind, (ushort)storageNumber, isRegister, isAlive ); } private void Add( uint address , GCInfo.Kind ptrKind , ushort storageNumber , bool isRegister , bool isAlive ) { int pos = m_deltas.Count; while(--pos >= 0) { Delta dt = m_deltas[pos]; if(dt.IsMatch( ptrKind, storageNumber, isRegister )) { if(dt.IsAlive == isAlive) { // // Nothing change, just exit. // return; } if(dt.Address == address) { // // Since we found a toggling at the target offset, // make sure we don't have a previous delta with the same state. // If so, remove the current delta, since it would do nothing. // for(int pos2 = pos; --pos2 >= 0; ) { Delta dt2 = m_deltas[pos2]; if(dt2.IsMatch( ptrKind, storageNumber, isRegister )) { if(dt2.IsAlive == isAlive) { // // Found a delta with the same direction, remove the later one. // m_deltas.RemoveAt( pos ); return; } break; } } // // Update liveness. // dt.IsAlive = isAlive; return; } break; } } // // Initial state is dead anyway, don't create a redundant delta. // if(pos < 0 && isAlive == false) { return; } Delta dtNew = new Delta(); dtNew.Address = address; dtNew.PtrKind = ptrKind; dtNew.StorageNumber = storageNumber; dtNew.IsRegister = isRegister; dtNew.IsAlive = isAlive; m_deltas.Add( dtNew ); } //--// private void AddTrackingInfo( CodeMap.EncodedStackWalk effect , CodeMap.EncodedStackWalk mask , uint val ) { CHECKS.ASSERT( val <= 0xFF && ((CodeMap.EncodedStackWalk)val & ~mask) == 0, "Invalid range for tracking info: {0} does not fit in {1}", val, mask ); AddTrackingInfo( (effect | ((CodeMap.EncodedStackWalk)val & mask)) ); } private void AddTrackingInfo( CodeMap.EncodedStackWalk val ) { if(m_workingArray == null) { m_workingArray = new CodeMap.EncodedStackWalk[128]; } else if(m_workingPos >= m_workingArray.Length) { m_workingArray = ArrayUtility.IncreaseSizeOfNotNullArray( m_workingArray, 128 ); } m_workingArray[m_workingPos++] = val; } } // // State // // // Constructor Methods // // // Helper Methods // public override bool CreateCodeMaps() { // // We don't need to worry about how we get to a certain opcode, // the point of CodeMap.Range is to describe the pointers alive at each opcode. // // So play the TrackPointerLifetime history for each region, computing the "final" state at each offset. // If it's different from the previous one, emit the delta info. // ZeligIR.ImageBuilders.SequentialRegion[] regions = GetSortedCodeRegions(); //--// CodeMap cm = new CodeMap(); cm.Target = m_cfg.Method; cm.Ranges = CodeMap.Range.SharedEmptyArray; CodeMapBuilder cmb = new CodeMapBuilder( cm ); foreach(ZeligIR.ImageBuilders.SequentialRegion reg in regions) { cmb.Compress( this, reg ); } cmb.Emit( this ); //--// CodeMap cmOld = m_cfg.Method.CodeMap; if(cmOld != null) { cm.ExceptionMap = cmOld.ExceptionMap; } if(cmOld == null || CodeMap.SameContents( cmOld, cm ) == false) { m_cfg.Method.CodeMap = cm; return true; } return false; } } } ================================================ FILE: Zelig/Zelig/CompileTime/TargetModels/ProductConfiguration/Abstractions/ARM/ArmPlatform_CompilationState_EmitCode.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // namespace Microsoft.Zelig.Configuration.Environment.Abstractions { using System; using Microsoft.Zelig.CodeGeneration.IR; using Microsoft.Zelig.Runtime.TypeSystem; using Microsoft.Zelig.TargetModel.ArmProcessor; using ZeligIR = Microsoft.Zelig.CodeGeneration.IR; public partial class ArmCompilationState { // // State // private uint m_stackOffsetForSAVED; private CodeMap.Flags m_headerFlags; // // Constructor Methods // // // Helper Methods // public override void EmitCodeForBasicBlock( ZeligIR.BasicBlock bb ) { m_pendingCondition = EncodingDefinition_ARM.c_cond_AL; base.EmitCodeForBasicBlock( bb ); } protected override bool EmitCodeForBasicBlock_ShouldSkip( ZeligIR.Operator op ) { return base.EmitCodeForBasicBlock_ShouldSkip( op ); } protected override uint EmitCodeForBasicBlock_EstimateMinimumSize( ZeligIR.Operator op ) { if(EmitCodeForBasicBlock_ShouldSkip( op )) { return 0; } if(op is ZeligIR.NopOperator || op is ZeligIR.AddActivationRecordEventOperator ) { return 0; } if(op is ZeligIR.SingleAssignmentOperator) { ZeligIR.PhysicalRegisterExpression lhs = op.FirstResult as ZeligIR.PhysicalRegisterExpression; ZeligIR.PhysicalRegisterExpression rhs = op.FirstArgument as ZeligIR.PhysicalRegisterExpression; if(lhs != null && rhs != null) { if(lhs.RegisterDescriptor == rhs.RegisterDescriptor) { return 0; } } } if(op is ZeligIR.UnconditionalControlOperator) { ZeligIR.UnconditionalControlOperator opCtrl = (ZeligIR.UnconditionalControlOperator)op; ZeligIR.ImageBuilders.Core.BranchEncodingLevel level = m_owner.GetEncodingLevelForBranch( op, opCtrl.TargetBranch, false ); if(level == ZeligIR.ImageBuilders.Core.BranchEncodingLevel.Skip) { return 0; } } if(op is ARM.MoveStackPointerOperator) { if(m_stackOffsetForSAVED == 0) { return 0; } } if(op is ARM.MoveIntegerRegistersOperator) { uint mask; bool fFast; bool fSkip; PrepareCode_ARM_MoveIntegerRegistersOperator( (ARM.MoveIntegerRegistersOperator)op, out mask, out fFast, out fSkip ); if(fSkip) { return 0; } } if(op is ARM.MoveFloatingPointRegistersOperator) { uint indexLow; uint indexHigh; bool fSkip; PrepareCode_ARM_MoveFloatingPointRegistersOperator( (ARM.MoveFloatingPointRegistersOperator)op, out indexLow, out indexHigh, out fSkip ); if(fSkip) { return 0; } } return sizeof(uint); } protected override void EmitCodeForBasicBlock_EmitOperator( ZeligIR.Operator op ) { AddOperatorContext( op ); if(op is ZeligIR.UnconditionalControlOperator) { EmitCode_UnconditionalControlOperator( (ZeligIR.UnconditionalControlOperator)op ); } else if(op is ZeligIR.MultiWayConditionalControlOperator) { EmitCode_MultiWayConditionalControlOperator( (ZeligIR.MultiWayConditionalControlOperator)op ); } else if(op is ZeligIR.ConditionCodeConditionalControlOperator) { EmitCode_ConditionCodeConditionalControlOperator( (ZeligIR.ConditionCodeConditionalControlOperator)op ); } else if(op is ZeligIR.DeadControlOperator) { EmitCode_DeadControlOperator( (ZeligIR.DeadControlOperator)op ); } else if(op is ZeligIR.ReturnControlOperator) { EmitCode_ReturnControlOperator( (ZeligIR.ReturnControlOperator)op ); } else if(op is ZeligIR.NopOperator) { EmitCode_NopOperator( (ZeligIR.NopOperator)op ); } else if(op is ZeligIR.SingleAssignmentOperator) { EmitCode_SingleAssignmentOperator( (ZeligIR.SingleAssignmentOperator)op ); } else if(op is ZeligIR.PartialAssignmentOperator) { EmitCode_PartialAssignmentOperator( (ZeligIR.PartialAssignmentOperator)op ); } else if(op is ZeligIR.AddressAssignmentOperator) { EmitCode_AddressAssignmentOperator( (ZeligIR.AddressAssignmentOperator)op ); } else if(op is ZeligIR.CompareOperator) { EmitCode_CompareOperator( (ZeligIR.CompareOperator)op ); } else if(op is ZeligIR.BitTestOperator) { EmitCode_BitTestOperator( (ZeligIR.BitTestOperator)op ); } else if(op is ZeligIR.ConditionalCompareOperator) { EmitCode_ConditionalCompareOperator( (ZeligIR.ConditionalCompareOperator)op ); } else if(op is ZeligIR.AbstractBinaryOperator) { EmitCode_AbstractBinaryOperator( (ZeligIR.AbstractBinaryOperator)op ); } else if(op is ZeligIR.AbstractUnaryOperator) { EmitCode_AbstractUnaryOperator( (ZeligIR.AbstractUnaryOperator)op ); } else if(op is ZeligIR.ZeroExtendOperator) { EmitCode_ZeroExtendOperator( (ZeligIR.ZeroExtendOperator)op ); } else if(op is ZeligIR.SignExtendOperator) { EmitCode_SignExtendOperator( (ZeligIR.SignExtendOperator)op ); } else if(op is ZeligIR.TruncateOperator) { EmitCode_TruncateOperator( (ZeligIR.TruncateOperator)op ); } else if(op is ZeligIR.ConvertOperator) { EmitCode_ConvertOperator( (ZeligIR.ConvertOperator)op ); } else if(op is ZeligIR.SetIfConditionIsTrueOperator) { EmitCode_SetIfConditionIsTrueOperator( (ZeligIR.SetIfConditionIsTrueOperator)op ); } else if(op is ZeligIR.LoadIndirectOperator) { EmitCode_LoadIndirectOperator( (ZeligIR.LoadIndirectOperator)op ); } else if(op is ZeligIR.StoreIndirectOperator) { EmitCode_StoreIndirectOperator( (ZeligIR.StoreIndirectOperator)op ); } else if(op is ZeligIR.DirectSubroutineOperator) { EmitCode_DirectSubroutineOperator( (ZeligIR.DirectSubroutineOperator)op ); } else if(op is ZeligIR.IndirectSubroutineOperator) { EmitCode_IndirectSubroutineOperator( (ZeligIR.IndirectSubroutineOperator)op ); } else if(op is ZeligIR.AddActivationRecordEventOperator) { EmitCode_AddActivationRecordEventOperator( (ZeligIR.AddActivationRecordEventOperator)op ); } else if(op is ZeligIR.ExternalCallOperator) { EmitCode_ExternalMethodCallOperator( (ZeligIR.ExternalCallOperator)op ); } //--//--//--//--//--//--//--//--//--//--//--// else if(op is ARM.BinaryOperatorWithShift) { EmitCode_ARM_BinaryOperatorWithShift( (ARM.BinaryOperatorWithShift)op ); } else if(op is ARM.LoadIndirectOperatorWithIndexUpdate) { EmitCode_ARM_LoadIndirectOperatorWithIndexUpdate( (ARM.LoadIndirectOperatorWithIndexUpdate)op ); } else if(op is ARM.StoreIndirectOperatorWithIndexUpdate) { EmitCode_ARM_StoreIndirectOperatorWithIndexUpdate( (ARM.StoreIndirectOperatorWithIndexUpdate)op ); } else if(op is ARM.SetStatusRegisterOperator) { EmitCode_ARM_SetStatusRegisterOperator( (ARM.SetStatusRegisterOperator)op ); } else if(op is ARM.GetStatusRegisterOperator) { EmitCode_ARM_GetStatusRegisterOperator( (ARM.GetStatusRegisterOperator)op ); } else if(op is ARM.MoveFromCoprocessor) { EmitCode_ARM_MoveFromCoprocessor( (ARM.MoveFromCoprocessor)op ); } else if(op is ARM.MoveToCoprocessor) { EmitCode_ARM_MoveToCoprocessor( (ARM.MoveToCoprocessor)op ); } else if(op is ARM.MoveIntegerRegistersOperator) { EmitCode_ARM_MoveIntegerRegistersOperator( (ARM.MoveIntegerRegistersOperator)op ); } else if(op is ARM.MoveFloatingPointRegistersOperator) { EmitCode_ARM_MoveFloatingPointRegistersOperator( (ARM.MoveFloatingPointRegistersOperator)op ); } else if(op is ARM.MoveStackPointerOperator) { EmitCode_ARM_MoveStackPointerOperator( (ARM.MoveStackPointerOperator)op ); } else if(op is ARM.BreakpointOperator) { EmitCode_ARM_BreakpointOperator( (ARM.BreakpointOperator)op ); } else if(op is ARM.VectorHack_Initialize) { EmitCode_ARM_VectorHack_Initialize( (ARM.VectorHack_Initialize)op ); } else if(op is ARM.VectorHack_Prepare) { EmitCode_ARM_VectorHack_Prepare( (ARM.VectorHack_Prepare)op ); } else if(op is ARM.VectorHack_LoadData) { EmitCode_ARM_VectorHack_LoadData( (ARM.VectorHack_LoadData)op ); } else if(op is ARM.VectorHack_MultiplyAndAccumulate) { EmitCode_ARM_VectorHack_MultiplyAndAccumulate( (ARM.VectorHack_MultiplyAndAccumulate)op ); } else if(op is ARM.VectorHack_Finalize) { EmitCode_ARM_VectorHack_Finalize( (ARM.VectorHack_Finalize)op ); } else if(op is ARM.VectorHack_Cleanup) { EmitCode_ARM_VectorHack_Cleanup( (ARM.VectorHack_Cleanup)op ); } else { throw NotImplemented(); } } protected override void EmitCodeForBasicBlock_FlushOperators() { FlushOperatorContext(); } private void UpdateLivenessInfo( BitVector aliveHistory , BitVector alive ) { aliveHistory.XorInPlace( alive ); // // Now 'aliveHistory' contains the set of variables that changed liveness status. // // We do two passes, first track the variables that went dead, then the ones that became alive. // The reason for this is that multiple variables map to the same physical register, // it's normal for a register to die and be born on the same instruction. // The end result should be a register that is still alive. // We'll compress the table later, when we switch from variables to actual storage places. // foreach(int idx in aliveHistory) { if(alive[idx] == false) { TrackVariable( m_variables[idx], false ); } } foreach(int idx in aliveHistory) { if(alive[idx] == true) { TrackVariable( m_variables[idx], true ); } } aliveHistory.Assign( alive ); } private ArmCodeRelocation_Branch CreateRelocation_Branch( ZeligIR.Operator opSource , ZeligIR.BasicBlock bb , int skew , bool fConditional ) { return new ArmCodeRelocation_Branch( m_activeCodeSection.Context, m_activeCodeSection.Offset, bb, this, opSource, skew, fConditional ); } private ArmCodeRelocation_LDR CreateRelocation_LDR( ZeligIR.Operator opSource , object obj , int skew ) { ZeligIR.ImageBuilders.CodeConstant cc = m_owner.CompileCodeConstant( obj, m_activeCodeRegion ); ArmCodeRelocation_LDR reloc = new ArmCodeRelocation_LDR( m_activeCodeSection.Context, m_activeCodeSection.Offset, cc, this, opSource, skew ); cc.Source = reloc; return reloc; } private ArmCodeRelocation_FLD CreateRelocation_FLD( ZeligIR.Operator opSource , object obj , int skew ) { ZeligIR.ImageBuilders.CodeConstant cc = m_owner.CompileCodeConstant( obj, m_activeCodeRegion ); ArmCodeRelocation_FLD reloc = new ArmCodeRelocation_FLD( m_activeCodeSection.Context, m_activeCodeSection.Offset, cc, this, opSource, skew ); cc.Source = reloc; return reloc; } private ArmCodeRelocation_MOV CreateRelocation_MOV( ZeligIR.Operator opSource , object obj , int skew , int numOfOpcodes ) { ZeligIR.ImageBuilders.CodeConstant cc = m_owner.CompileCodeConstant( obj, m_activeCodeRegion ); ArmCodeRelocation_MOV reloc = new ArmCodeRelocation_MOV( m_activeCodeSection.Context, m_activeCodeSection.Offset, cc, this, opSource, skew, numOfOpcodes ); cc.Source = reloc; return reloc; } //--// private void EmitCode_BranchToBasicBlock( ZeligIR.Operator opSource , ZeligIR.BasicBlock bb , bool fConditional ) { m_owner.CompileBasicBlock( bb ); var level = GetEncodingLevelForBranch( opSource, bb, fConditional ); switch(level) { case ZeligIR.ImageBuilders.Core.BranchEncodingLevel.Skip: if(AreBasicBlocksAdjacent( opSource.BasicBlock, bb ) == false) { goto case ZeligIR.ImageBuilders.Core.BranchEncodingLevel.ShortBranch; } RecordAdjacencyNeed( opSource, bb ); break; case ZeligIR.ImageBuilders.Core.BranchEncodingLevel.ShortBranch: CreateRelocation_Branch( opSource, bb, EncodingDefinition_ARM.c_PC_offset, fConditional ); EmitOpcode__BR( 0 ); break; case ZeligIR.ImageBuilders.Core.BranchEncodingLevel.NearRelativeLoad: CreateRelocation_LDR( opSource, bb, EncodingDefinition_ARM.c_PC_offset ); EmitOpcode__LDR( m_reg_PC, m_reg_PC, 0 ); break; default: Build32BitIntegerExpression( opSource, m_reg_Scratch, bb ); EmitOpcode__LDRwithRotate( m_reg_PC, m_reg_PC, m_reg_Scratch, 0 ); break; } } private void EmitCode_ExternalMethodCallOperator( ZeligIR.ExternalCallOperator op ) { m_pendingCondition = EncodingDefinition_ARM.c_cond_AL; FlushOperatorContext(); if(!op.Encode( m_activeCodeRegion, m_activeCodeSection, m_owner )) { throw new Exception( "Unable to generate external method call: " + op.DebugInfo != null ? op.DebugInfo.MethodName : "" ); } } private void EmitCode_UnconditionalControlOperator( ZeligIR.UnconditionalControlOperator op ) { ZeligIR.BasicBlock bb = op.TargetBranch; EmitCode_BranchToBasicBlock( op, bb, false ); } private void EmitCode_MultiWayConditionalControlOperator( ZeligIR.MultiWayConditionalControlOperator op ) { ZeligIR.BasicBlock[] bbTargets = op.Targets; ZeligIR.BasicBlock bbDefault = op.TargetBranchNotTaken; ZeligIR.Abstractions.RegisterDescriptor valRD = GetRegisterDescriptor( op.FirstArgument ); if(valRD != null) { uint valSeed; uint valRot; if(CanEncodeAs8BitImmediate( bbTargets.Length, out valSeed, out valRot )) { EmitOpcode__CMP_CONST( valRD, valSeed, valRot ); } else { Build32BitIntegerExpression( op, m_reg_Scratch, bbTargets.Length ); EmitOpcode__CMP( valRD, m_reg_Scratch ); } // // The offset is zero because it's implicit a +8 in the value of PC. // PrepareCondition( Abstractions.ArmPlatform.Comparison.UnsignedLowerThan ); // Unsigned Lower EmitOpcode__LDRwithRotate( m_reg_PC, m_reg_PC, valRD, 2u ); EmitCode_BranchToBasicBlock( op, bbDefault, true ); // // Emit the table. // foreach(ZeligIR.BasicBlock bbTarget in bbTargets) { m_activeCodeSection.WritePointerToBasicBlock( bbTarget ); } } else { throw NotImplemented(); } } private void EmitCode_ConditionCodeConditionalControlOperator( ZeligIR.ConditionCodeConditionalControlOperator op ) { ZeligIR.BasicBlock bbThis = op.BasicBlock; ZeligIR.BasicBlock bbTaken = op.TargetBranchTaken; ZeligIR.BasicBlock bbNotTaken = op.TargetBranchNotTaken; bool fConditionalOnTaken; if(AreBasicBlocksAdjacent( bbThis, bbNotTaken )) { fConditionalOnTaken = true; } else if(AreBasicBlocksAdjacent( bbThis, bbTaken )) { fConditionalOnTaken = false; } else { if(CompareSchedulingWeights( bbTaken, bbNotTaken ) >= 0) { fConditionalOnTaken = true; } else { fConditionalOnTaken = false; } } if(fConditionalOnTaken) { PrepareCondition( op.Condition ); EmitCode_BranchToBasicBlock( op, bbTaken , true ); EmitCode_BranchToBasicBlock( op, bbNotTaken, false ); } else { PrepareCondition( ZeligIR.ConditionCodeExpression.NegateCondition( op.Condition ) ); EmitCode_BranchToBasicBlock( op, bbNotTaken, true ); EmitCode_BranchToBasicBlock( op, bbTaken , false ); } } //--// private void EmitCode_DeadControlOperator( ZeligIR.DeadControlOperator op ) { // Nothing to do, we should never reach this point. EmitOpcode__SWI( 0 ); } private void EmitCode_ReturnControlOperator( ZeligIR.ReturnControlOperator op ) { if(m_activeHardwareException == Runtime.HardwareException.VectorTable) { EmitCodeForVector( Runtime.HardwareException.Bootstrap ); EmitCodeForVector( Runtime.HardwareException.UndefinedInstruction ); EmitCodeForVector( Runtime.HardwareException.SoftwareInterrupt ); EmitCodeForVector( Runtime.HardwareException.PrefetchAbort ); EmitCodeForVector( Runtime.HardwareException.DataAbort ); EmitCodeForVector( Runtime.HardwareException.None ); // Unused EmitCodeForVector( Runtime.HardwareException.Interrupt ); EmitCodeForVector( Runtime.HardwareException.FastInterrupt ); } else if(m_activeHardwareException == Runtime.HardwareException.Bootstrap) { EmitCodeForVector( Runtime.HardwareException.Reset ); } else { // Nothing to do, the return values are already in the correct registers/stack locations. } } private void EmitCodeForVector( Runtime.HardwareException he ) { MethodRepresentation md = m_owner.TypeSystem.TryGetHandler( he ); if(md != null) { ZeligIR.ControlFlowGraphStateForCodeTransformation cfg = ZeligIR.TypeSystemForCodeTransformation.GetCodeForMethod( md ); if(cfg == null) { return; } CHECKS.ASSERT( cfg != null, "Cannot compile a method without implementation: {0}", md ); m_owner.CompileMethod( cfg ); CreateRelocation_LDR( cfg.EntryBasicBlock.FirstOperator, cfg.EntryBasicBlock, EncodingDefinition_ARM.c_PC_offset ); EmitOpcode__LDR( m_reg_PC, m_reg_PC, 0 ); } else { EmitOpcode__SWI( (uint)he ); } } //--// private void EmitCode_NopOperator( ZeligIR.NopOperator op ) { // TODO: Add a nop opcode for debug builds. //// if(op.DebugInfo != null) //// { //// EmitOpcode__MOV( EncodingDefinition_ARM.c_register_r0, EncodingDefinition_ARM.c_register_r0 ); //// } } //--// private void EmitCode_CompareOperator( ZeligIR.CompareOperator op ) { EmitCode_CommonCompare( op ); } private void EmitCode_ConditionalCompareOperator( ZeligIR.ConditionalCompareOperator op ) { PrepareCondition( op.Condition ); EmitCode_CommonCompare( op ); } private void EmitCode_CommonCompare( ZeligIR.Operator op ) { ZeligIR.Expression left = op.FirstArgument; ZeligIR.Expression right = op.SecondArgument; ZeligIR.Abstractions.RegisterDescriptor leftReg = GetRegisterDescriptor( left ); ZeligIR.Abstractions.RegisterDescriptor rightReg = GetRegisterDescriptor( right ); if(leftReg != null && rightReg != null) { if(leftReg.InIntegerRegisterFile) { EmitOpcode__CMP( leftReg, rightReg ); } else { EmitOpcode__FCMP( leftReg, rightReg ); EmitOpcode__FMSTAT(); } } else if(leftReg != null && right is ZeligIR.ConstantExpression) { if(leftReg.InIntegerRegisterFile) { uint valSeed; uint valRot; EncodeAs8BitImmediate( right, out valSeed, out valRot ); EmitOpcode__CMP_CONST( leftReg, valSeed, valRot ); } else { if(right.IsEqualToZero()) { EmitOpcode__FCMPZ( leftReg ); EmitOpcode__FMSTAT(); } else { throw NotImplemented(); } } } else { throw NotImplemented(); } } //--// private void EmitCode_BitTestOperator( ZeligIR.BitTestOperator op ) { EmitCode_CommonBitTest( op ); } private void EmitCode_CommonBitTest( ZeligIR.Operator op ) { ZeligIR.Expression left = op.FirstArgument; ZeligIR.Expression right = op.SecondArgument; ZeligIR.Abstractions.RegisterDescriptor leftReg = GetRegisterDescriptor( left ); ZeligIR.Abstractions.RegisterDescriptor rightReg = GetRegisterDescriptor( right ); if(leftReg != null && rightReg != null) { if(leftReg.InIntegerRegisterFile) { EmitOpcode__TST( leftReg, rightReg ); } else { throw NotImplemented(); } } else if(leftReg != null && right is ZeligIR.ConstantExpression) { if(leftReg.InIntegerRegisterFile) { uint valSeed; uint valRot; EncodeAs8BitImmediate( right, out valSeed, out valRot ); EmitOpcode__TST_CONST( leftReg, valSeed, valRot ); } else { throw NotImplemented(); } } else { throw NotImplemented(); } } //--// private void EmitCode_SetIfConditionIsTrueOperator( ZeligIR.SetIfConditionIsTrueOperator op ) { ZeligIR.Abstractions.RegisterDescriptor regRd = GetRegisterDescriptor( op.FirstResult ); ZeligIR.ConditionCodeExpression.Comparison cond = op.Condition; PrepareCondition( cond ); EmitOpcode__MOV_CONST( regRd, 1, 0 ); PrepareCondition( ZeligIR.ConditionCodeExpression.NegateCondition( cond ) ); EmitOpcode__MOV_CONST( regRd, 0, 0 ); } //--// private void EmitCode_SingleAssignmentOperator( ZeligIR.SingleAssignmentOperator op ) { ZeligIR.VariableExpression lhs = op.FirstResult; ZeligIR.Expression rhs = op.FirstArgument; ZeligIR.Abstractions.RegisterDescriptor lhsReg = GetRegisterDescriptor( lhs ); ZeligIR.Abstractions.RegisterDescriptor rhsReg = GetRegisterDescriptor( rhs ); if(lhsReg != null && rhsReg != null) { uint offsetRhs = 0; if(op.HasAnnotation()) { if(rhs.Type == m_owner.TypeSystem.WellKnownTypes.System_String) { offsetRhs += 8; } else if(!( rhs.Type is ValueTypeRepresentation || rhs.Type.UnderlyingType is ValueTypeRepresentation )) { offsetRhs += 4; } } EmitCode_MoveRegisters( lhsReg, 0, rhsReg, offsetRhs ); } else if(lhsReg != null && rhs is ZeligIR.ConstantExpression) { if(lhsReg.InIntegerRegisterFile) { Build32BitIntegerExpression( op, lhsReg, rhs ); } else { if(lhsReg.IsDoublePrecision) { Build64BitFloatingPointExpression( op, lhsReg, rhs ); } else { Build32BitFloatingPointExpression( op, lhsReg, rhs ); } } } else if(lhsReg != null && rhs is ZeligIR.StackLocationExpression) { int offsetRhs = GetOffsetOfStackLocation( rhs ); if(op.HasAnnotation()) { if(rhs.Type == m_owner.TypeSystem.WellKnownTypes.System_String) { offsetRhs += 8; } else if(!( rhs.Type is ValueTypeRepresentation || rhs.Type.UnderlyingType is ValueTypeRepresentation )) { offsetRhs += 4; } } EmitOpcode__Load( lhsReg, m_reg_SP, offsetRhs, rhs.Type ); } else if(lhs is ZeligIR.StackLocationExpression && rhs is ZeligIR.ConstantExpression) { int offsetLhs = GetOffsetOfStackLocation( lhs ); Build32BitIntegerExpression( op, m_reg_Scratch, rhs ); EmitOpcode__Store( m_reg_SP, offsetLhs, m_reg_Scratch, lhs.Type ); } else if(lhs is ZeligIR.StackLocationExpression && rhsReg != null) { int offsetLhs = GetOffsetOfStackLocation( lhs ); EmitOpcode__Store( m_reg_SP, offsetLhs, rhsReg, lhs.Type ); } else if(lhs is ZeligIR.StackLocationExpression && rhs is ZeligIR.StackLocationExpression) { int offsetLhs = GetOffsetOfStackLocation( lhs ); int offsetRhs = GetOffsetOfStackLocation( rhs ); if(offsetLhs != offsetRhs) { EmitOpcode__Load( m_reg_Scratch, m_reg_SP, offsetRhs, rhs.Type ); EmitOpcode__Store( m_reg_SP, offsetLhs, m_reg_Scratch, lhs.Type ); } else { // // Nothing to do, source and destination are at the same offset. // } } else { throw NotImplemented(); } } private void EmitCode_PartialAssignmentOperator( ZeligIR.PartialAssignmentOperator op ) { ZeligIR.VariableExpression lhs = op.FirstResult; ZeligIR.Expression rhs = op.FirstArgument; ZeligIR.Abstractions.RegisterDescriptor lhsReg = GetRegisterDescriptor( lhs ); ZeligIR.Abstractions.RegisterDescriptor rhsReg = GetRegisterDescriptor( rhs ); if(lhsReg != null && rhsReg != null) { EmitCode_MoveRegisters( lhsReg, op.DestinationOffset, rhsReg, op.SourceOffset ); } else { throw NotImplemented(); } } private void EmitCode_MoveRegisters( ZeligIR.Abstractions.RegisterDescriptor lhsReg , uint lhsOffset , ZeligIR.Abstractions.RegisterDescriptor rhsReg , uint rhsOffset ) { switch(ZeligIR.Abstractions.RegisterDescriptor.GetPairState( lhsReg, rhsReg )) { case ZeligIR.Abstractions.RegisterDescriptor.Pair.Int_Int: if(rhsOffset == 0) { EmitOpcode__MOV_IfDifferent( lhsReg, rhsReg ); } else { EmitOpcode__ADD_CONST( lhsReg, rhsReg, rhsOffset, 0 ); } break; case ZeligIR.Abstractions.RegisterDescriptor.Pair.Int_FP: if(rhsReg.IsDoublePrecision) { if(lhsReg.PhysicalStorageSize == 1) { if(rhsOffset == 0) { EmitOpcode__FMRDL( lhsReg, rhsReg ); } else { EmitOpcode__FMRDH( lhsReg, rhsReg ); } } else { throw NotImplemented(); } } else { EmitOpcode__FMRS( lhsReg, rhsReg ); } break; case ZeligIR.Abstractions.RegisterDescriptor.Pair.FP_Int: if(lhsReg.IsDoublePrecision) { if(rhsReg.PhysicalStorageSize == 1) { if(lhsOffset == 0) { EmitOpcode__FMDLR( rhsReg, lhsReg ); } else { EmitOpcode__FMDHR( rhsReg, lhsReg ); } } else { throw NotImplemented(); } } else { EmitOpcode__FMSR( rhsReg, lhsReg ); } break; case ZeligIR.Abstractions.RegisterDescriptor.Pair.FP_FP: EmitOpcode__FCPY_IfDifferent( lhsReg, rhsReg ); break; case ZeligIR.Abstractions.RegisterDescriptor.Pair.Int_Sys: EmitOpcode__FMRX( lhsReg, rhsReg ); break; case ZeligIR.Abstractions.RegisterDescriptor.Pair.Sys_Int: EmitOpcode__FMXR( rhsReg, lhsReg ); break; default: throw TypeConsistencyErrorException.Create( "Unexpected pair of registers for assignment: {0} = {1}", lhsReg, rhsReg ); } } private void EmitCode_AddressAssignmentOperator( ZeligIR.AddressAssignmentOperator op ) { ZeligIR.Abstractions.RegisterDescriptor lhsReg = GetRegisterDescriptor( op.FirstResult ); ZeligIR.StackLocationExpression rhs = (ZeligIR.StackLocationExpression)op.FirstArgument; int offset = GetOffsetOfStackLocation( rhs ); uint valSeed; uint valRot; if(CanEncodeAs8BitImmediate( offset, out valSeed, out valRot )) { EmitOpcode__ADD_CONST( lhsReg, m_reg_SP, valSeed, valRot ); } else { Build32BitIntegerExpression( op, lhsReg, offset ); EmitOpcode__ADD( lhsReg, m_reg_SP, lhsReg ); } } private void EmitCode_AbstractBinaryOperator( ZeligIR.AbstractBinaryOperator op ) { ZeligIR.Abstractions.RegisterDescriptor regLhs = GetRegisterDescriptor( op.FirstResult ); ZeligIR.Expression left = op.FirstArgument; ZeligIR.Expression right = op.SecondArgument; ZeligIR.Abstractions.RegisterDescriptor regLeft = GetRegisterDescriptor( left ); ZeligIR.Abstractions.RegisterDescriptor regRight = GetRegisterDescriptor( right ); bool fIsBin = op is ZeligIR.BinaryOperator; bool fIsBinWithCarryIn = op is ZeligIR.BinaryOperatorWithCarryIn; bool fIsBinWithCarryInAndOut = op is ZeligIR.BinaryOperatorWithCarryInAndOut; bool fIsBinWithCarryOut = op is ZeligIR.BinaryOperatorWithCarryOut; bool fIsLong = op is ZeligIR.LongBinaryOperator; if(regLeft != null && regRight != null) { if(regLhs.InIntegerRegisterFile) { if(fIsLong) { switch(op.Alu) { case ZeligIR.BinaryOperator.ALU.MUL: ZeligIR.Abstractions.RegisterDescriptor regLhsHi = GetRegisterDescriptor( op.SecondResult ); EmitOpcode__MULL( regLhsHi, regLhs, regLeft, regRight, op.Signed ); break; default: throw NotImplemented(); } } else if(fIsBin || fIsBinWithCarryOut) { switch(op.Alu) { case ZeligIR.BinaryOperator.ALU.ADD: EmitOpcode__ADD( regLhs, regLeft, regRight ); break; case ZeligIR.BinaryOperator.ALU.SUB: EmitOpcode__SUB( regLhs, regLeft, regRight ); break; case ZeligIR.BinaryOperator.ALU.MUL: EmitOpcode__MUL( regLhs, regLeft, regRight ); break; case ZeligIR.BinaryOperator.ALU.AND: EmitOpcode__AND( regLhs, regLeft, regRight ); break; case ZeligIR.BinaryOperator.ALU.OR: EmitOpcode__OR( regLhs, regLeft, regRight ); break; case ZeligIR.BinaryOperator.ALU.XOR: EmitOpcode__EOR( regLhs, regLeft, regRight ); break; case ZeligIR.BinaryOperator.ALU.SHL: EmitOpcode__LSL( regLhs, regLeft, regRight ); break; case ZeligIR.BinaryOperator.ALU.SHR: if(op.Signed) { EmitOpcode__ASR( regLhs, regLeft, regRight ); } else { EmitOpcode__LSR( regLhs, regLeft, regRight ); } break; default: throw NotImplemented(); } } else if(fIsBinWithCarryIn || fIsBinWithCarryInAndOut) { switch(op.Alu) { case ZeligIR.BinaryOperator.ALU.ADD: EmitOpcode__ADC( regLhs, regLeft, regRight ); break; case ZeligIR.BinaryOperator.ALU.SUB: EmitOpcode__SBC( regLhs, regLeft, regRight ); break; default: throw NotImplemented(); } } else { throw NotImplemented(); } } else { if(fIsBin) { switch(op.Alu) { case ZeligIR.BinaryOperator.ALU.ADD: EmitOpcode__FADD( regLhs, regLeft, regRight ); break; case ZeligIR.BinaryOperator.ALU.SUB: EmitOpcode__FSUB( regLhs, regLeft, regRight ); break; case ZeligIR.BinaryOperator.ALU.MUL: EmitOpcode__FMUL( regLhs, regLeft, regRight ); break; case ZeligIR.BinaryOperator.ALU.DIV: EmitOpcode__FDIV( regLhs, regLeft, regRight ); break; default: throw NotImplemented(); } } else { throw NotImplemented(); } } } else if(regLeft != null && right is ZeligIR.ConstantExpression) { if(fIsBin || fIsBinWithCarryOut) { bool fCanUseInvertedForm; switch(op.Alu) { case ZeligIR.BinaryOperator.ALU.ADD: case ZeligIR.BinaryOperator.ALU.SUB: case ZeligIR.BinaryOperator.ALU.AND: fCanUseInvertedForm = true; break; default: fCanUseInvertedForm = false; break; } uint valSeed; uint valRot; bool fInverted = EncodeAs8BitImmediate( right, fCanUseInvertedForm, out valSeed, out valRot ); switch(op.Alu) { case ZeligIR.BinaryOperator.ALU.ADD: if(fInverted) { EmitOpcode__SUB_CONST( regLhs, regLeft, valSeed, valRot ); } else { EmitOpcode__ADD_CONST( regLhs, regLeft, valSeed, valRot ); } break; case ZeligIR.BinaryOperator.ALU.SUB: if(fInverted) { EmitOpcode__ADD_CONST( regLhs, regLeft, valSeed, valRot ); } else { EmitOpcode__SUB_CONST( regLhs, regLeft, valSeed, valRot ); } break; case ZeligIR.BinaryOperator.ALU.AND: if(fInverted) { EmitOpcode__BIC_CONST( regLhs, regLeft, valSeed, valRot ); } else { EmitOpcode__AND_CONST( regLhs, regLeft, valSeed, valRot ); } break; case ZeligIR.BinaryOperator.ALU.OR: EmitOpcode__OR_CONST( regLhs, regLeft, valSeed, valRot ); break; case ZeligIR.BinaryOperator.ALU.XOR: EmitOpcode__EOR_CONST( regLhs, regLeft, valSeed, valRot ); break; case ZeligIR.BinaryOperator.ALU.SHL: if(valRot == 0) { EmitOpcode__LSL_CONST( regLhs, regLeft, valSeed ); } else { EmitOpcode__MOV_CONST( regLhs, 0, 0 ); } break; case ZeligIR.BinaryOperator.ALU.SHR: if(valRot == 0) { if(op.Signed) { EmitOpcode__ASR_CONST( regLhs, regLeft, valSeed ); } else { EmitOpcode__LSR_CONST( regLhs, regLeft, valSeed ); } } else { if(op.Signed) { EmitOpcode__ASR_CONST( regLhs, regLeft, 31 ); // Extend sign. } else { EmitOpcode__MOV_CONST( regLhs, 0, 0 ); } } break; default: throw NotImplemented(); } } else if(fIsBinWithCarryIn || fIsBinWithCarryInAndOut) { uint valSeed; uint valRot; EncodeAs8BitImmediate( right, out valSeed, out valRot ); switch(op.Alu) { case ZeligIR.BinaryOperator.ALU.ADD: EmitOpcode__ADC_CONST( regLhs, regLeft, valSeed, valRot ); break; case ZeligIR.BinaryOperator.ALU.SUB: EmitOpcode__SBC_CONST( regLhs, regLeft, valSeed, valRot ); break; default: throw NotImplemented(); } } else { throw NotImplemented(); } } else if(left is ZeligIR.ConstantExpression && regRight != null) { if(fIsBin || fIsBinWithCarryOut) { uint valSeed; uint valRot; EncodeAs8BitImmediate( left, out valSeed, out valRot ); switch(op.Alu) { case ZeligIR.BinaryOperator.ALU.SUB: EmitOpcode__RSB_CONST( regLhs, regRight, valSeed, valRot ); break; default: throw NotImplemented(); } } else if(fIsBinWithCarryIn || fIsBinWithCarryInAndOut) { uint valSeed; uint valRot; EncodeAs8BitImmediate( left, out valSeed, out valRot ); switch(op.Alu) { case ZeligIR.BinaryOperator.ALU.SUB: EmitOpcode__RSC_CONST( regLhs, regRight, valSeed, valRot ); break; // 'ALU.ADD' should not reach this point, thanks to calls to Operator.EnsureConstantToTheRight default: throw NotImplemented(); } } else { throw NotImplemented(); } } else { throw NotImplemented(); } if(fIsBinWithCarryOut || fIsBinWithCarryInAndOut) { SetConditionBit(); } } //--// private void EmitCode_AbstractUnaryOperator( ZeligIR.AbstractUnaryOperator op ) { ZeligIR.Abstractions.RegisterDescriptor regLhs = GetRegisterDescriptor( op.FirstResult ); ZeligIR.Abstractions.RegisterDescriptor regRhs = GetRegisterDescriptor( op.FirstArgument ); if(regLhs != null && regRhs != null) { if(regLhs.InIntegerRegisterFile) { switch(op.Alu) { case ZeligIR.UnaryOperator.ALU.NEG: EmitOpcode__RSB_CONST( regLhs, regRhs, 0, 0 ); break; case ZeligIR.UnaryOperator.ALU.NOT: EmitOpcode__MVN( regLhs, regRhs ); break; default: throw NotImplemented(); } } else { switch(op.Alu) { case ZeligIR.UnaryOperator.ALU.NEG: EmitOpcode__FNEG( regLhs, regRhs ); break; default: throw NotImplemented(); } } } else { throw NotImplemented(); } if(op is ZeligIR.UnaryOperatorWithCarryOut) { SetConditionBit(); } } private void EmitCode_ZeroExtendOperator( ZeligIR.ZeroExtendOperator op ) { ZeligIR.Abstractions.RegisterDescriptor regRd = GetRegisterDescriptor( op.FirstResult ); ZeligIR.Abstractions.RegisterDescriptor regRs = GetRegisterDescriptor( op.FirstArgument ); uint shift = 8 * (4 - op.SignificantSize); switch(shift) { case 0: EmitOpcode__MOV_IfDifferent( regRd, regRs ); break; case 24: EmitOpcode__AND_CONST( regRd, regRs, 0xFFu, 0 ); break; default: EmitOpcode__LSL_CONST( regRd, regRs, shift ); EmitOpcode__LSR_CONST( regRd, regRd, shift ); break; } } private void EmitCode_SignExtendOperator( ZeligIR.SignExtendOperator op ) { ZeligIR.Abstractions.RegisterDescriptor regRd = GetRegisterDescriptor( op.FirstResult ); ZeligIR.Abstractions.RegisterDescriptor regRs = GetRegisterDescriptor( op.FirstArgument ); uint shift = 8 * (4 - op.SignificantSize); switch(shift) { case 0: EmitOpcode__MOV_IfDifferent( regRd, regRs ); break; default: EmitOpcode__LSL_CONST( regRd, regRs, shift ); EmitOpcode__ASR_CONST( regRd, regRd, shift ); break; } } private void EmitCode_TruncateOperator( ZeligIR.TruncateOperator op ) { ZeligIR.Abstractions.RegisterDescriptor regRd = GetRegisterDescriptor( op.FirstResult ); ZeligIR.Abstractions.RegisterDescriptor regRs = GetRegisterDescriptor( op.FirstArgument ); uint shift = 8 * (4 - op.SignificantSize); switch(shift) { case 0: EmitOpcode__MOV_IfDifferent( regRd, regRs ); break; case 24: EmitOpcode__AND_CONST( regRd, regRs, 0xFFu, 0 ); break; default: EmitOpcode__LSL_CONST( regRd, regRs, shift ); EmitOpcode__LSR_CONST( regRd, regRd, shift ); break; } } private void EmitCode_ConvertOperator( ZeligIR.ConvertOperator op ) { ZeligIR.Abstractions.RegisterDescriptor regLhs = GetRegisterDescriptor( op.FirstResult ); ZeligIR.Abstractions.RegisterDescriptor regRhs = GetRegisterDescriptor( op.FirstArgument ); TypeRepresentation.BuiltInTypes kindInput = op.InputKind; TypeRepresentation.BuiltInTypes kindOutput = op.OutputKind; switch(kindOutput) { case TypeRepresentation.BuiltInTypes.R4: switch(kindInput) { case TypeRepresentation.BuiltInTypes.I4: EmitOpcode__FSITOS( regLhs, regRhs ); return; case TypeRepresentation.BuiltInTypes.U4: EmitOpcode__FUITOS( regLhs, regRhs ); return; case TypeRepresentation.BuiltInTypes.R8: EmitOpcode__FCVTSD( regLhs, regRhs ); return; } break; case TypeRepresentation.BuiltInTypes.R8: switch(kindInput) { case TypeRepresentation.BuiltInTypes.I4: EmitOpcode__FSITOD( regLhs, regRhs ); return; case TypeRepresentation.BuiltInTypes.U4: EmitOpcode__FUITOD( regLhs, regRhs ); return; case TypeRepresentation.BuiltInTypes.R4: EmitOpcode__FCVTDS( regLhs, regRhs ); return; } break; case TypeRepresentation.BuiltInTypes.I4: switch(kindInput) { case TypeRepresentation.BuiltInTypes.R4: EmitOpcode__FTOSIS( regLhs, regRhs ); return; case TypeRepresentation.BuiltInTypes.R8: EmitOpcode__FTOSID( regLhs, regRhs ); return; } break; case TypeRepresentation.BuiltInTypes.U4: switch(kindInput) { case TypeRepresentation.BuiltInTypes.R4: EmitOpcode__FTOUIS( regLhs, regRhs ); return; case TypeRepresentation.BuiltInTypes.R8: EmitOpcode__FTOUID( regLhs, regRhs ); return; } break; } throw NotImplemented(); } //--// private void EmitCode_LoadIndirectOperator( ZeligIR.LoadIndirectOperator op ) { ZeligIR.Abstractions.RegisterDescriptor regRd = GetRegisterDescriptor( op.FirstResult ); ZeligIR.Abstractions.RegisterDescriptor regRs = GetRegisterDescriptor( op.FirstArgument ); if(regRd != null && regRs != null) { EmitOpcode__Load( regRd, regRs, op.Offset, op.Type ); } else { throw NotImplemented(); } } private void EmitCode_StoreIndirectOperator( ZeligIR.StoreIndirectOperator op ) { ZeligIR.Abstractions.RegisterDescriptor regRd = GetRegisterDescriptor( op.FirstArgument ); ZeligIR.Abstractions.RegisterDescriptor regRs = GetRegisterDescriptor( op.SecondArgument ); EmitOpcode__Store( regRd, op.Offset, regRs, op.Type ); } //--// private void EmitCode_DirectSubroutineOperator( ZeligIR.DirectSubroutineOperator op ) { ZeligIR.ControlFlowGraphStateForCodeTransformation cfg = ZeligIR.TypeSystemForCodeTransformation.GetCodeForMethod( op.TargetMethod ); if(cfg == null) { return; } CHECKS.ASSERT( cfg != null, "Cannot compile a method without implementation: {0}", op.TargetMethod ); ZeligIR.BasicBlock bb = cfg.EntryBasicBlock; m_owner.CompileBasicBlock( bb ); var level = GetEncodingLevelForBranch( op, bb, false ); bool fDeadJump; if((m_headerFlags & CodeMap.Flags.HasIntRegisterSave) != 0) { fDeadJump = false; } else { fDeadJump = op.GetNextOperator() is ZeligIR.DeadControlOperator; } switch(level) { case ZeligIR.ImageBuilders.Core.BranchEncodingLevel.Skip: case ZeligIR.ImageBuilders.Core.BranchEncodingLevel.ShortBranch: CreateRelocation_Branch( op, bb, EncodingDefinition_ARM.c_PC_offset, false ); if(fDeadJump) { EmitOpcode__BR( 0 ); } else { EmitOpcode__BL( 0 ); } break; case ZeligIR.ImageBuilders.Core.BranchEncodingLevel.NearRelativeLoad: if(!fDeadJump) { EmitOpcode__MOV( m_reg_LR, m_reg_PC ); } CreateRelocation_LDR( op, bb, EncodingDefinition_ARM.c_PC_offset ); EmitOpcode__LDR( m_reg_PC, m_reg_PC, 0 ); break; default: Build32BitIntegerExpression( op, m_reg_Scratch, bb ); EmitOpcode__MOV ( m_reg_LR, m_reg_PC ); EmitOpcode__LDRwithRotate( m_reg_PC, m_reg_PC, m_reg_Scratch, 0 ); break; } } private void EmitCode_IndirectSubroutineOperator( ZeligIR.IndirectSubroutineOperator op ) { ZeligIR.Abstractions.RegisterDescriptor regPointer = GetRegisterDescriptor( op.FirstArgument ); EmitOpcode__MOV( m_reg_LR, m_reg_PC ); EmitOpcode__MOV( m_reg_PC, regPointer ); } //--// private void EmitCode_ARM_BinaryOperatorWithShift( ARM.BinaryOperatorWithShift op ) { ZeligIR.Abstractions.RegisterDescriptor regLhs = GetRegisterDescriptor( op.FirstResult ); ZeligIR.Expression left = op.FirstArgument; ZeligIR.Expression right = op.SecondArgument; ZeligIR.Expression shift = op.ThirdArgument; ZeligIR.Abstractions.RegisterDescriptor regLeft = GetRegisterDescriptor( left ); ZeligIR.Abstractions.RegisterDescriptor regRight = GetRegisterDescriptor( right ); ZeligIR.Abstractions.RegisterDescriptor regShift = GetRegisterDescriptor( shift ); if(regLeft != null && regRight != null) { if(regLhs.InIntegerRegisterFile) { uint cpuALU; uint cpuSHIFT; switch(op.Alu) { case ZeligIR.AbstractBinaryOperator.ALU.ADD: cpuALU = EncodingDefinition_ARM.c_operation_ADD; break; case ZeligIR.AbstractBinaryOperator.ALU.SUB: cpuALU = EncodingDefinition_ARM.c_operation_SUB; break; case ZeligIR.AbstractBinaryOperator.ALU.AND: cpuALU = EncodingDefinition_ARM.c_operation_AND; break; case ZeligIR.AbstractBinaryOperator.ALU.OR : cpuALU = EncodingDefinition_ARM.c_operation_ORR; break; case ZeligIR.AbstractBinaryOperator.ALU.XOR: cpuALU = EncodingDefinition_ARM.c_operation_EOR; break; default: throw NotImplemented(); } switch(op.AluShift) { case ZeligIR.AbstractBinaryOperator.ALU.SHL: cpuSHIFT = EncodingDefinition_ARM.c_shift_LSL; break; case ZeligIR.AbstractBinaryOperator.ALU.SHR: cpuSHIFT = op.SignedShift ? EncodingDefinition_ARM.c_shift_ASR : EncodingDefinition_ARM.c_shift_LSR; break; default: throw NotImplemented(); } if(regShift != null) { InstructionSet.Opcode_DataProcessing_3 enc = this.Encoder.PrepareForDataProcessing_3; enc.Prepare( m_pendingCondition , // uint ConditionCodes , GetIntegerEncoding( regLeft ) , // uint Rn , GetIntegerEncoding( regLhs ) , // uint Rd , cpuALU , // uint Alu , false , // bool SetCC , GetIntegerEncoding( regRight ) , // uint Rm , cpuSHIFT , // uint ShiftType , GetIntegerEncoding( regShift ) ); // uint Rs , EnqueueOpcode( enc ); } else { uint valSeed; uint valRot; EncodeAs8BitImmediate( shift, false, out valSeed, out valRot ); if(valRot == 0) { InstructionSet.Opcode_DataProcessing_2 enc = this.Encoder.PrepareForDataProcessing_2; enc.Prepare( m_pendingCondition , // uint ConditionCodes , GetIntegerEncoding( regLeft ) , // uint Rn , GetIntegerEncoding( regLhs ) , // uint Rd , cpuALU , // uint Alu , false , // bool SetCC , GetIntegerEncoding( regRight ) , // uint Rm , cpuSHIFT , // uint ShiftType , valSeed ); // uint ShiftValue , EnqueueOpcode( enc ); } else { throw NotImplemented(); } } } else { throw NotImplemented(); } } else { throw NotImplemented(); } } private void EmitCode_ARM_LoadIndirectOperatorWithIndexUpdate( ARM.LoadIndirectOperatorWithIndexUpdate op ) { var target = op.Type; var offset = op.Offset; CHECKS.ASSERT( Math.Abs( offset ) < this.ArmPlatform.GetOffsetLimit( target ), "Offset too big for encoding Store( {0}[{1}] )", target, offset ); ZeligIR.Abstractions.RegisterDescriptor regRd = GetRegisterDescriptor( op.FirstResult ); ZeligIR.Abstractions.RegisterDescriptor regRs = GetRegisterDescriptor( op.FirstArgument ); CHECKS.ASSERT( regRd == GetRegisterDescriptor( op.FirstResult ), "FirstResult and FirstArgument should point to the same register: {0} != {1}", op.FirstResult, op.FirstArgument ); if(regRd.InIntegerRegisterFile) { bool fPreIndex = (op.PostUpdate == false); bool fWriteBack = (op.PostUpdate == false); switch(target.SizeOfHoldingVariable) { case 1: if(target.IsSigned) { EmitOpcode__LDRSB( regRd, regRs, offset, fPreIndex, fWriteBack ); } else { EmitOpcode__LDRB( regRd, regRs, offset, fPreIndex, fWriteBack ); } break; case 2: if(target.IsSigned) { EmitOpcode__LDRSH( regRd, regRs, offset, fPreIndex, fWriteBack ); } else { EmitOpcode__LDRH( regRd, regRs, offset, fPreIndex, fWriteBack ); } break; case 4: EmitOpcode__LDR( regRd, regRs, offset, fPreIndex, fWriteBack ); break; default: throw NotImplemented(); } } else { throw NotImplemented(); } } private void EmitCode_ARM_StoreIndirectOperatorWithIndexUpdate( ARM.StoreIndirectOperatorWithIndexUpdate op ) { var target = op.Type; var offset = op.Offset; CHECKS.ASSERT( Math.Abs( offset ) < this.ArmPlatform.GetOffsetLimit( target ), "Offset too big for encoding Store( {0}[{1}] )", target, offset ); ZeligIR.Abstractions.RegisterDescriptor regRd = GetRegisterDescriptor( op.FirstArgument ); ZeligIR.Abstractions.RegisterDescriptor regRs = GetRegisterDescriptor( op.SecondArgument ); CHECKS.ASSERT( regRd == GetRegisterDescriptor( op.FirstResult ), "FirstResult and FirstArgument should point to the same register: {0} != {1}", op.FirstResult, op.FirstArgument ); if(regRs.InIntegerRegisterFile) { bool fPreIndex = (op.PostUpdate == false); bool fWriteBack = (op.PostUpdate == false); switch(target.SizeOfHoldingVariable) { case 1: EmitOpcode__STRB( regRd, offset, regRs, fPreIndex, fWriteBack ); break; case 2: EmitOpcode__STRH( regRd, offset, regRs, fPreIndex, fWriteBack ); break; case 4: EmitOpcode__STR( regRd, offset, regRs, fPreIndex, fWriteBack ); break; default: throw NotImplemented(); } } else { throw NotImplemented(); } } private void EmitCode_ARM_SetStatusRegisterOperator( ARM.SetStatusRegisterOperator op ) { ZeligIR.Expression ex = op.FirstArgument; ZeligIR.Abstractions.RegisterDescriptor regEx = GetRegisterDescriptor( ex ); if(regEx != null) { EmitOpcode__MSR( op.UseSPSR, op.Fields, regEx ); } else if(ex is ZeligIR.ConstantExpression) { uint valSeed; uint valRot; bool fInverted; if(CanEncodeAs8BitImmediate( NormalizeValue( ex ), out valSeed, out valRot, out fInverted ) && fInverted == false) { EmitOpcode__MSR_CONST( op.UseSPSR, op.Fields, valSeed, valRot ); } else { Build32BitIntegerExpression( op, m_reg_Scratch, ex ); EmitOpcode__MSR( op.UseSPSR, op.Fields, m_reg_Scratch ); } } else { throw NotImplemented(); } } private void EmitCode_ARM_GetStatusRegisterOperator( ARM.GetStatusRegisterOperator op ) { ZeligIR.Abstractions.RegisterDescriptor regLhs = GetRegisterDescriptor( op.FirstResult ); EmitOpcode__MRS( op.UseSPSR, regLhs ); } //--// private void EmitCode_ARM_MoveToCoprocessor( ARM.MoveToCoprocessor op ) { ZeligIR.Expression ex = op.FirstArgument; ZeligIR.Abstractions.RegisterDescriptor regRhs = GetRegisterDescriptor( ex ); if(regRhs != null) { } else if(ex is ZeligIR.ConstantExpression) { Build32BitIntegerExpression( op, m_reg_Scratch, ex ); regRhs = m_reg_Scratch; } else { throw NotImplemented(); } EmitOpcode__MCR( op.CpNum, op.Op1, regRhs, op.CRn, op.CRm, op.Op2 ); } private void EmitCode_ARM_MoveFromCoprocessor( ARM.MoveFromCoprocessor op ) { ZeligIR.Abstractions.RegisterDescriptor regLhs = GetRegisterDescriptor( op.FirstResult ); EmitOpcode__MRC( op.CpNum, op.Op1, regLhs, op.CRn, op.CRm, op.Op2 ); } //--// private void EmitCode_AddActivationRecordEventOperator( ZeligIR.AddActivationRecordEventOperator op ) { var ev = op.ActivationRecordEvent; switch(ev) { case Runtime.ActivationRecordEvents.EnteringException: m_headerFlags |= CodeMap.Flags.InterruptHandler; break; case Runtime.ActivationRecordEvents.NonReachable: m_fStopProcessingOperatorsForCurrentBasicBlock = true; break; default: AddNewImageAnnotation( ev ); break; } } //--// private void EmitCode_ARM_MoveStackPointerOperator( ARM.MoveStackPointerOperator op ) { if(m_stackOffsetForSAVED > 0) { uint valSeed; uint valRot; if(CanEncodeAs8BitImmediate( (int)m_stackOffsetForSAVED, out valSeed, out valRot )) { if(op.IsPush) { if(m_cfg.Method.HasBuildTimeFlag( MethodRepresentation.BuildTimeAttributes.StackNotAvailable ) == false) { EmitOpcode__SUB_CONST( m_reg_SP, m_reg_SP, valSeed, valRot ); } } else { if(m_cfg.Method.HasBuildTimeFlag( MethodRepresentation.BuildTimeAttributes.NoReturn ) == false) { EmitOpcode__ADD_CONST( m_reg_SP, m_reg_SP, valSeed, valRot ); } } } else { throw NotImplemented(); } m_headerFlags |= CodeMap.Flags.HasStackAdjustment; } } private uint ComputeStackSize_ARM_MoveStackPointerOperator( ARM.MoveStackPointerOperator op ) { if(op.IsPush) { return (m_stackForCalls + m_stackForLocals) * sizeof(uint); } return 0; } //--// private void EmitCode_ARM_MoveIntegerRegistersOperator( ARM.MoveIntegerRegistersOperator op ) { uint mask; bool fFast; bool fSkip; PrepareCode_ARM_MoveIntegerRegistersOperator( op, out mask, out fFast, out fSkip ); if(fSkip == false) { var Rn = GetRegisterDescriptor( op.FirstArgument ); if(op.IsLoad) { if(fFast) { EmitOpcode__MOV( m_reg_PC, m_reg_LR ); } else { EmitOpcode__LDM( Rn, mask, false, true, op.ShouldWriteBackIndexRegister, op.ShouldRestoreSPSR ); } } else { EmitOpcode__STM( Rn, mask, true, false, op.ShouldWriteBackIndexRegister ); m_headerFlags |= CodeMap.Flags.HasIntRegisterSave; } } } private uint ComputeStackSize_ARM_MoveIntegerRegistersOperator( ARM.MoveIntegerRegistersOperator op ) { if(op.IsLoad) { return 0; } if(m_reg_SP != GetRegisterDescriptor( op.FirstArgument )) { return 0; } uint mask; bool fFast; bool fSkip; PrepareCode_ARM_MoveIntegerRegistersOperator( op, out mask, out fFast, out fSkip ); if(fSkip) { return 0; } return BitVector.CountBits( mask ) * sizeof(uint); } private void PrepareCode_ARM_MoveIntegerRegistersOperator( ARM.MoveIntegerRegistersOperator op , out uint mask , out bool fFast , out bool fSkip ) { var pa = this.ArmPlatform; mask = op.RegisterMask; fFast = false; fSkip = false; if(op.ShouldAddComputedRegisters) { mask |= pa.Emit__GetIntegerList( this, m_registersToSave ); } if(op.IsLoad) { if(mask == EncodingDefinition_ARM.c_register_lst_pc && pa.Emit__WasRegisterTouched( m_reg_LR, m_registersUsed ) == false) { fFast = true; } } else { if(mask == EncodingDefinition_ARM.c_register_lst_lr && pa.Emit__WasRegisterTouched( m_reg_LR, m_registersUsed ) == false) { fSkip = true; } } } //--// private void EmitCode_ARM_MoveFloatingPointRegistersOperator( ARM.MoveFloatingPointRegistersOperator op ) { uint indexLow; uint indexHigh; bool fSkip; PrepareCode_ARM_MoveFloatingPointRegistersOperator( op, out indexLow, out indexHigh, out fSkip ); if(fSkip == false) { var pa = this.ArmPlatform; var Rn = GetRegisterDescriptor( op.FirstArgument ); var Fd = pa.GetRegisterForEncoding( EncodingDefinition_VFP_ARM.c_register_d0 + indexLow / 2 ); uint count = indexHigh - indexLow + 2; if(op.IsLoad) { EmitOpcode__FLDM( Rn, Fd, count, false, true, op.ShouldWriteBackIndexRegister ); } else { EmitOpcode__FSTM( Rn, Fd, count, true, false, op.ShouldWriteBackIndexRegister ); m_headerFlags |= CodeMap.Flags.HasFpRegisterSave; } } } private uint ComputeStackSize_ARM_MoveFloatingPointRegistersOperator( ARM.MoveFloatingPointRegistersOperator op ) { if(op.IsLoad) { return 0; } if(m_reg_SP != GetRegisterDescriptor( op.FirstArgument )) { return 0; } uint indexLow; uint indexHigh; bool fSkip; PrepareCode_ARM_MoveFloatingPointRegistersOperator( op, out indexLow, out indexHigh, out fSkip ); if(fSkip) { return 0; } return BitVector.CountBits( indexHigh - indexLow + 2 ) * sizeof(uint); } private void PrepareCode_ARM_MoveFloatingPointRegistersOperator( ARM.MoveFloatingPointRegistersOperator op , out uint indexLow , out uint indexHigh , out bool fSkip ) { var pa = this.ArmPlatform; indexLow = op.RegisterLow; indexHigh = op.RegisterHigh; if(op.ShouldAddComputedRegisters) { ZeligIR.Abstractions.RegisterDescriptor regLowest; ZeligIR.Abstractions.RegisterDescriptor regHighest; pa.Emit__GetFloatingPointList( this, m_registersToSave, out regLowest, out regHighest ); if(regLowest != null) { indexLow = Math.Min( indexLow , GetDoublePrecisionEncoding( regLowest ) ); indexHigh = Math.Max( indexHigh, GetDoublePrecisionEncoding( regHighest ) ); } } fSkip = indexLow >= indexHigh; } //--// private void EmitCode_ARM_BreakpointOperator( ARM.BreakpointOperator op ) { EmitOpcode__BKPT( op.Value ); } //--//--// private void EmitCode_ARM_VectorHack_Initialize( ARM.VectorHack_Initialize op ) { EmitOpcode__FMRX ( m_reg_Scratch, m_reg_FPSCR ); EmitOpcode__BIC_CONST( m_reg_Scratch, m_reg_Scratch, 7 << 16 ); EmitOpcode__OR_CONST ( m_reg_Scratch, m_reg_Scratch, (op.Size - 1) << 16 ); EmitOpcode__FMXR ( m_reg_Scratch, m_reg_FPSCR ); } private void EmitCode_ARM_VectorHack_Prepare( ARM.VectorHack_Prepare op ) { EmitOpcode__MOV_CONST( m_reg_Scratch, 0, 0 ); var reg = op.ResultBankBase; for(int i = 0; i < op.Size; i++) { EmitOpcode__FMSR( m_reg_Scratch, reg ); reg = GetNextRegister( reg ); } } private void EmitCode_ARM_VectorHack_LoadData( ARM.VectorHack_LoadData op ) { EmitOpcode__FLDM( GetRegisterDescriptor( op.FirstArgument ), op.DestinationBankBase, (uint)op.Size, false, true, true ); } private void EmitCode_ARM_VectorHack_MultiplyAndAccumulate( ARM.VectorHack_MultiplyAndAccumulate op ) { EmitOpcode__FMAC( op.ResultBankBase, op.LeftBankBase, op.RightBankBase ); } private void EmitCode_ARM_VectorHack_Finalize( ARM.VectorHack_Finalize op ) { var regSrc = op.ResultBankBase; var regRes = GetRegisterDescriptor( op.FirstResult ); switch(op.Size) { case 1: EmitOpcode__FCPY( regRes, regSrc ); break; default: var regLeft = regSrc; for(int i = 1; i < op.Size; i++) { regSrc = GetNextRegister( regSrc ); EmitOpcode__FADD( regRes, regLeft, regSrc ); regLeft = regRes; } break; } } private void EmitCode_ARM_VectorHack_Cleanup( ARM.VectorHack_Cleanup op ) { EmitOpcode__FMRX ( m_reg_Scratch, m_reg_FPSCR ); EmitOpcode__BIC_CONST( m_reg_Scratch, m_reg_Scratch, 7 << 16 ); EmitOpcode__FMXR ( m_reg_Scratch, m_reg_FPSCR ); } //--//--// private int GetOffsetOfStackLocation( ZeligIR.Expression ex ) { ZeligIR.StackLocationExpression var = (ZeligIR.StackLocationExpression)ex; return (int)var.AllocationOffset; } private static ZeligIR.Abstractions.RegisterDescriptor GetRegisterDescriptor( ZeligIR.Expression ex ) { return ZeligIR.Abstractions.RegisterDescriptor.ExtractFromExpression( ex ); } public static uint GetIntegerEncoding( ZeligIR.Abstractions.RegisterDescriptor reg ) { CHECKS.ASSERT( reg.InIntegerRegisterFile == true, "Expecting an integer register, got {0}", reg ); return reg.Encoding - EncodingDefinition_ARM.c_register_r0; } public static uint GetSystemEncoding( ZeligIR.Abstractions.RegisterDescriptor reg ) { CHECKS.ASSERT( reg.IsSystemRegister, "Expecting a system register, got {0}", reg ); return reg.Encoding - EncodingDefinition_VFP_ARM.c_register_FPSID; } public static uint GetSinglePrecisionEncoding( ZeligIR.Abstractions.RegisterDescriptor reg ) { CHECKS.ASSERT( reg.InFloatingPointRegisterFile == true && reg.IsDoublePrecision == false, "Expecting a single-precision register, got {0}", reg ); return reg.Encoding - EncodingDefinition_VFP_ARM.c_register_s0; } public static uint GetDoublePrecisionEncoding( ZeligIR.Abstractions.RegisterDescriptor reg ) { CHECKS.ASSERT( reg.InFloatingPointRegisterFile == true && reg.IsDoublePrecision == true, "Expecting a double-precision register, got {0}", reg ); return (reg.Encoding - EncodingDefinition_VFP_ARM.c_register_d0) * 2; } } } ================================================ FILE: Zelig/Zelig/CompileTime/TargetModels/ProductConfiguration/Abstractions/ARM/ArmPlatform_CompilationState_Encoder.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // namespace Microsoft.Zelig.Configuration.Environment.Abstractions { using System; using Microsoft.Zelig.Runtime.TypeSystem; using Microsoft.Zelig.TargetModel.ArmProcessor; using ZeligIR = Microsoft.Zelig.CodeGeneration.IR; public partial class ArmCompilationState { private static EncodingDefinition_ARM s_Encoding = (EncodingDefinition_ARM)CurrentInstructionSetEncoding.GetEncoding(); // // State // private uint m_pendingCondition; // // Helper Methods // private InstructionSet Encoder { get { return m_owner.GetInstructionSetProvider(); } } private InstructionSet_VFP Encoder_VFP { get { return (InstructionSet_VFP)this.Encoder; } } internal static InstructionSet.Opcode GetOpcode( ZeligIR.ImageBuilders.CompilationState cs , ZeligIR.ImageBuilders.SequentialRegion reg , uint offset ) { ArmCompilationState cs2 = (ArmCompilationState)cs; return cs2.Encoder.Decode( reg.ReadUInt( offset ) ); } internal static void SetOpcode( ZeligIR.ImageBuilders.CompilationState cs , ZeligIR.ImageBuilders.SequentialRegion reg , uint offset , InstructionSet.Opcode op ) { reg.Write( offset, op.Encode() ); } //--// private void PrepareCondition( ZeligIR.ConditionCodeExpression.Comparison condIR ) { Abstractions.ArmPlatform.Comparison condARM; switch(condIR) { case ZeligIR.ConditionCodeExpression.Comparison.Equal : condARM = ArmPlatform.Comparison.Equal ; break; case ZeligIR.ConditionCodeExpression.Comparison.NotEqual : condARM = ArmPlatform.Comparison.NotEqual ; break; case ZeligIR.ConditionCodeExpression.Comparison.Negative : condARM = ArmPlatform.Comparison.Negative ; break; case ZeligIR.ConditionCodeExpression.Comparison.PositiveOrZero : condARM = ArmPlatform.Comparison.PositiveOrZero ; break; case ZeligIR.ConditionCodeExpression.Comparison.Overflow : condARM = ArmPlatform.Comparison.Overflow ; break; case ZeligIR.ConditionCodeExpression.Comparison.NoOverflow : condARM = ArmPlatform.Comparison.NoOverflow ; break; case ZeligIR.ConditionCodeExpression.Comparison.UnsignedHigherThanOrSame: condARM = ArmPlatform.Comparison.UnsignedHigherThanOrSame; break; case ZeligIR.ConditionCodeExpression.Comparison.UnsignedLowerThan : condARM = ArmPlatform.Comparison.UnsignedLowerThan ; break; case ZeligIR.ConditionCodeExpression.Comparison.UnsignedHigherThan : condARM = ArmPlatform.Comparison.UnsignedHigherThan ; break; case ZeligIR.ConditionCodeExpression.Comparison.UnsignedLowerThanOrSame : condARM = ArmPlatform.Comparison.UnsignedLowerThanOrSame ; break; case ZeligIR.ConditionCodeExpression.Comparison.SignedGreaterThanOrEqual: condARM = ArmPlatform.Comparison.SignedGreaterThanOrEqual; break; case ZeligIR.ConditionCodeExpression.Comparison.SignedLessThan : condARM = ArmPlatform.Comparison.SignedLessThan ; break; case ZeligIR.ConditionCodeExpression.Comparison.SignedGreaterThan : condARM = ArmPlatform.Comparison.SignedGreaterThan ; break; case ZeligIR.ConditionCodeExpression.Comparison.SignedLessThanOrEqual : condARM = ArmPlatform.Comparison.SignedLessThanOrEqual ; break; default: throw NotImplemented(); } PrepareCondition( condARM ); } private void PrepareCondition( Abstractions.ArmPlatform.Comparison condARM ) { m_pendingCondition = (uint)condARM; } private void EnqueueOpcode( InstructionSet.Opcode enc ) { m_pendingCondition = EncodingDefinition_ARM.c_cond_AL; FlushOperatorContext(); m_activeCodeSection.Write( enc.Encode() ); } //--// private void SetConditionBit() { uint offset = m_activeCodeSection.Offset - sizeof(uint); ZeligIR.ImageBuilders.SequentialRegion context = m_activeCodeSection.Context; InstructionSet encoder = this.Encoder; InstructionSet.Opcode op = encoder.Decode( context.ReadUInt( offset ) ); if(op is InstructionSet.Opcode_DataProcessing) { InstructionSet.Opcode_DataProcessing op2 = (InstructionSet.Opcode_DataProcessing)op; op2.SetCC = true; } else if(op is InstructionSet.Opcode_Multiply) { InstructionSet.Opcode_Multiply op2 = (InstructionSet.Opcode_Multiply)op; op2.SetCC = true; } else if(op is InstructionSet.Opcode_MultiplyLong) { InstructionSet.Opcode_MultiplyLong op2 = (InstructionSet.Opcode_MultiplyLong)op; op2.SetCC = true; } context.Write( offset, op.Encode() ); } private void Build32BitIntegerExpression( ZeligIR.Operator opSource , ZeligIR.Abstractions.RegisterDescriptor reg , object obj ) { CHECKS.ASSERT( reg.InIntegerRegisterFile, "Expecting an integer register, got {0}", reg ); int val; if(GetValue( obj, out val )) { uint valSeed; uint valRot; bool fInverted; if(CanEncodeAs8BitImmediate( obj, out valSeed, out valRot, out fInverted )) { if(fInverted) { EmitOpcode__MVN_CONST( reg, valSeed, valRot ); } else { EmitOpcode__MOV_CONST( reg, valSeed, valRot ); } return; } } //--// obj = NormalizeValue( obj ); var level = GetEncodingLevelForConstant( opSource ); switch(level) { case ZeligIR.ImageBuilders.Core.ConstantAddressEncodingLevel.Immediate: case ZeligIR.ImageBuilders.Core.ConstantAddressEncodingLevel.SmallLoad: case ZeligIR.ImageBuilders.Core.ConstantAddressEncodingLevel.NearRelativeLoad: CreateRelocation_LDR( opSource, obj, EncodingDefinition_ARM.c_PC_offset ); EmitOpcode__LDR( reg, m_reg_PC, 0 ); break; case ZeligIR.ImageBuilders.Core.ConstantAddressEncodingLevel.FarRelativeLoad16Bit: CreateRelocation_MOV( opSource, obj, EncodingDefinition_ARM.c_PC_offset, 2 ); EmitOpcode__MOV_CONST( m_reg_Scratch, 0, 0 ); EmitOpcode__OR_CONST ( m_reg_Scratch, m_reg_Scratch, 0, 0 ); EmitOpcode__LDRwithRotate( reg, m_reg_PC, m_reg_Scratch, 0 ); break; case ZeligIR.ImageBuilders.Core.ConstantAddressEncodingLevel.FarRelativeLoad24Bit: CreateRelocation_MOV( opSource, obj, EncodingDefinition_ARM.c_PC_offset, 3 ); EmitOpcode__MOV_CONST( m_reg_Scratch, 0, 0 ); EmitOpcode__OR_CONST ( m_reg_Scratch, m_reg_Scratch, 0, 0 ); EmitOpcode__OR_CONST ( m_reg_Scratch, m_reg_Scratch, 0, 0 ); EmitOpcode__LDRwithRotate( reg, m_reg_PC, m_reg_Scratch, 0 ); break; case ZeligIR.ImageBuilders.Core.ConstantAddressEncodingLevel.FarRelativeLoad32Bit: CreateRelocation_MOV( opSource, obj, EncodingDefinition_ARM.c_PC_offset, 4 ); EmitOpcode__MOV_CONST( m_reg_Scratch, 0, 0 ); EmitOpcode__OR_CONST ( m_reg_Scratch, m_reg_Scratch, 0, 0 ); EmitOpcode__OR_CONST ( m_reg_Scratch, m_reg_Scratch, 0, 0 ); EmitOpcode__OR_CONST ( m_reg_Scratch, m_reg_Scratch, 0, 0 ); EmitOpcode__LDRwithRotate( reg, m_reg_PC, m_reg_Scratch, 0 ); break; default: throw NotImplemented(); } } private void Build32BitFloatingPointExpression( ZeligIR.Operator opSource , ZeligIR.Abstractions.RegisterDescriptor reg , object obj ) { CHECKS.ASSERT( reg.InFloatingPointRegisterFile && !reg.IsDoublePrecision, "Expecting a single-precision register, got {0}", reg ); BuildFloatingPointExpression( opSource, reg, obj ); } private void Build64BitFloatingPointExpression( ZeligIR.Operator opSource , ZeligIR.Abstractions.RegisterDescriptor reg , object obj ) { CHECKS.ASSERT( reg.InFloatingPointRegisterFile && reg.IsDoublePrecision, "Expecting a double-precision register, got {0}", reg ); BuildFloatingPointExpression( opSource, reg, obj ); } private void BuildFloatingPointExpression( ZeligIR.Operator opSource , ZeligIR.Abstractions.RegisterDescriptor reg , object obj ) { CHECKS.ASSERT( reg.InFloatingPointRegisterFile, "Expecting a floating-point, got {0}", reg ); obj = NormalizeValue( obj ); var level = GetEncodingLevelForConstant( opSource ); switch(level) { case ZeligIR.ImageBuilders.Core.ConstantAddressEncodingLevel.Immediate: case ZeligIR.ImageBuilders.Core.ConstantAddressEncodingLevel.SmallLoad: case ZeligIR.ImageBuilders.Core.ConstantAddressEncodingLevel.NearRelativeLoad: CreateRelocation_FLD( opSource, obj, EncodingDefinition_ARM.c_PC_offset ); EmitOpcode__FLD( reg, m_reg_PC, 0 ); break; case ZeligIR.ImageBuilders.Core.ConstantAddressEncodingLevel.FarRelativeLoad16Bit: CreateRelocation_MOV( opSource, obj, EncodingDefinition_ARM.c_PC_offset, 2 ); EmitOpcode__MOV_CONST( m_reg_Scratch, 0, 0 ); EmitOpcode__OR_CONST ( m_reg_Scratch, m_reg_Scratch, 0, 0 ); EmitOpcode__ADD ( m_reg_Scratch, m_reg_Scratch, m_reg_PC ); EmitOpcode__FLD ( reg , m_reg_Scratch, 0 ); break; case ZeligIR.ImageBuilders.Core.ConstantAddressEncodingLevel.FarRelativeLoad24Bit: CreateRelocation_MOV( opSource, obj, EncodingDefinition_ARM.c_PC_offset, 3 ); EmitOpcode__MOV_CONST( m_reg_Scratch, 0, 0 ); EmitOpcode__OR_CONST ( m_reg_Scratch, m_reg_Scratch, 0, 0 ); EmitOpcode__OR_CONST ( m_reg_Scratch, m_reg_Scratch, 0, 0 ); EmitOpcode__ADD ( m_reg_Scratch, m_reg_Scratch, m_reg_PC ); EmitOpcode__FLD ( reg , m_reg_Scratch, 0 ); break; case ZeligIR.ImageBuilders.Core.ConstantAddressEncodingLevel.FarRelativeLoad32Bit: CreateRelocation_MOV( opSource, obj, EncodingDefinition_ARM.c_PC_offset, 4 ); EmitOpcode__MOV_CONST( m_reg_Scratch, 0, 0 ); EmitOpcode__OR_CONST ( m_reg_Scratch, m_reg_Scratch, 0, 0 ); EmitOpcode__OR_CONST ( m_reg_Scratch, m_reg_Scratch, 0, 0 ); EmitOpcode__OR_CONST ( m_reg_Scratch, m_reg_Scratch, 0, 0 ); EmitOpcode__ADD ( m_reg_Scratch, m_reg_Scratch, m_reg_PC ); EmitOpcode__FLD ( reg , m_reg_Scratch, 0 ); break; default: throw NotImplemented(); } } private static bool CanEncodeAs8BitImmediate( object o , out uint valSeed , out uint valRot , out bool fInverted ) { valSeed = 0; valRot = 0; fInverted = false; int val; if(GetValue( o, out val ) == false) { return false; } if(CanEncodeAs8BitImmediate( val, out valSeed, out valRot ) == true) { return true; } if(CanEncodeAs8BitImmediate( ~val, out valSeed, out valRot ) == true) { fInverted = true; return true; } return false; } private static bool CanEncodeAs8BitImmediate( int val , out uint valSeed , out uint valRot ) { return s_Encoding.check_DataProcessing_ImmediateValue( (uint)val, out valSeed, out valRot ); } //--// private static void EncodeAs8BitImmediate( object o , out uint valSeed , out uint valRot ) { EncodeAs8BitImmediate( o, false, out valSeed, out valRot ); } private static bool EncodeAs8BitImmediate( object o , bool fCanUseInvertedForm , out uint valSeed , out uint valRot ) { valSeed = 0; valRot = 0; int val; if(GetValue( o, out val )) { if(CanEncodeAs8BitImmediate( val, out valSeed, out valRot )) { return false; } if(fCanUseInvertedForm && CanEncodeAs8BitImmediate( ~val, out valSeed, out valRot )) { return true; } } throw TypeConsistencyErrorException.Create( "Cannot encode as 8-bit immediate: {0}", o ); } //--// public void EmitOpcode__BR( int offset ) { InstructionSet.Opcode_Branch enc = this.Encoder.PrepareForBranch; enc.Prepare( m_pendingCondition, // uint ConditionCodes , offset , // int Offset , false ); // bool IsLink ); EnqueueOpcode( enc ); } public void EmitOpcode__BL( int offset ) { InstructionSet.Opcode_Branch enc = this.Encoder.PrepareForBranch; enc.Prepare( m_pendingCondition, // uint ConditionCodes , offset , // int Offset , true ); // bool IsLink ); EnqueueOpcode( enc ); } //--// public void EmitOpcode__Store( ZeligIR.Abstractions.RegisterDescriptor Rd , int offset , ZeligIR.Abstractions.RegisterDescriptor Rs , TypeRepresentation target ) { CHECKS.ASSERT( Math.Abs( offset ) < this.ArmPlatform.GetOffsetLimit( target ), "Offset too big for encoding Store( {0}[{1}] )", target, offset ); if(Rs.InFloatingPointRegisterFile) { EmitOpcode__FST( Rs, Rd, offset ); } else { switch(target.SizeOfHoldingVariable) { case 1: EmitOpcode__STRB( Rd, offset, Rs, true, false ); break; case 2: EmitOpcode__STRH( Rd, offset, Rs, true, false ); break; case 4: EmitOpcode__STR( Rd, offset, Rs, true, false ); break; default: throw NotImplemented(); } } } public void EmitOpcode__STR( ZeligIR.Abstractions.RegisterDescriptor Rd , int offset , ZeligIR.Abstractions.RegisterDescriptor Rs , bool preIndex , bool writeBack ) { InstructionSet.Opcode_SingleDataTransfer_1 enc = this.Encoder.PrepareForSingleDataTransfer_1; bool fUp; uint uOffset; if(offset < 0) { fUp = false; uOffset = (uint)-offset; } else { fUp = true; uOffset = (uint)offset; } enc.Prepare( m_pendingCondition , // uint ConditionCodes , GetIntegerEncoding( Rd ), // uint Rn , false , // bool IsLoad , preIndex , // bool PreIndex , fUp , // bool Up , writeBack , // bool WriteBack , GetIntegerEncoding( Rs ), // uint Rd , false , // bool IsByte , uOffset ); // uint Offset , EnqueueOpcode( enc ); } public void EmitOpcode__STRB( ZeligIR.Abstractions.RegisterDescriptor Rd , int offset , ZeligIR.Abstractions.RegisterDescriptor Rs , bool preIndex , bool writeBack ) { InstructionSet.Opcode_SingleDataTransfer_1 enc = this.Encoder.PrepareForSingleDataTransfer_1; bool fUp; uint uOffset; if(offset < 0) { fUp = false; uOffset = (uint)-offset; } else { fUp = true; uOffset = (uint)offset; } enc.Prepare( m_pendingCondition , // uint ConditionCodes , GetIntegerEncoding( Rd ), // uint Rn , false , // bool IsLoad , preIndex , // bool PreIndex , fUp , // bool Up , writeBack , // bool WriteBack , GetIntegerEncoding( Rs ), // uint Rd , true , // bool IsByte , uOffset ); // uint Offset , EnqueueOpcode( enc ); } public void EmitOpcode__STRH( ZeligIR.Abstractions.RegisterDescriptor Rd , int offset , ZeligIR.Abstractions.RegisterDescriptor Rs , bool preIndex , bool writeBack ) { InstructionSet.Opcode_HalfwordDataTransfer_2 enc = this.Encoder.PrepareForHalfwordDataTransfer_2; bool fUp; uint uOffset; if(offset < 0) { fUp = false; uOffset = (uint)-offset; } else { fUp = true; uOffset = (uint)offset; } enc.Prepare( m_pendingCondition , // uint ConditionCodes , GetIntegerEncoding( Rd ) , // uint Rn , false , // bool IsLoad , preIndex , // bool PreIndex , fUp , // bool Up , writeBack , // bool WriteBack , GetIntegerEncoding( Rs ) , // uint Rd , EncodingDefinition_ARM.c_halfwordkind_U2, // uint Kind , uOffset ); // uint Offset , EnqueueOpcode( enc ); } //--// public void EmitOpcode__Push( ZeligIR.Abstractions.RegisterDescriptor Rd , ZeligIR.Abstractions.RegisterDescriptor Rs ) { InstructionSet.Opcode_SingleDataTransfer_1 enc = this.Encoder.PrepareForSingleDataTransfer_1; enc.Prepare( m_pendingCondition , // uint ConditionCodes , GetIntegerEncoding( Rd ), // uint Rn , false , // bool IsLoad , true , // bool PreIndex , false , // bool Up , true , // bool WriteBack , GetIntegerEncoding( Rs ), // uint Rd , false , // bool IsByte , sizeof(uint) ); // uint Offset , EnqueueOpcode( enc ); } public void EmitOpcode__Pop( ZeligIR.Abstractions.RegisterDescriptor Rd , ZeligIR.Abstractions.RegisterDescriptor Rs ) { InstructionSet.Opcode_SingleDataTransfer_1 enc = this.Encoder.PrepareForSingleDataTransfer_1; enc.Prepare( m_pendingCondition , // uint ConditionCodes , GetIntegerEncoding( Rd ), // uint Rn , true , // bool IsLoad , false , // bool PreIndex , true , // bool Up , true , // bool WriteBack , GetIntegerEncoding( Rs ), // uint Rd , false , // bool IsByte , sizeof(uint) ); // uint Offset , EnqueueOpcode( enc ); } //--// public void EmitOpcode__Load( ZeligIR.Abstractions.RegisterDescriptor Rd , ZeligIR.Abstractions.RegisterDescriptor Rs , int offset , TypeRepresentation target ) { CHECKS.ASSERT( Math.Abs( offset ) < this.ArmPlatform.GetOffsetLimit( target ), "Offset too big for encoding Load( {0}[{1}] )", target, offset ); if(Rd.InFloatingPointRegisterFile) { EmitOpcode__FLD( Rd, Rs, offset ); } else { switch(target.SizeOfHoldingVariable) { case 1: if(target.IsSigned) { EmitOpcode__LDRSB( Rd, Rs, offset, true, false ); } else { EmitOpcode__LDRB( Rd, Rs, offset, true, false ); } break; case 2: if(target.IsSigned) { EmitOpcode__LDRSH( Rd, Rs, offset, true, false ); } else { EmitOpcode__LDRH( Rd, Rs, offset, true, false ); } break; case 4: EmitOpcode__LDR( Rd, Rs, offset ); break; default: throw NotImplemented(); } } } public void EmitOpcode__LDRwithRotate( ZeligIR.Abstractions.RegisterDescriptor Rd , ZeligIR.Abstractions.RegisterDescriptor Rs , ZeligIR.Abstractions.RegisterDescriptor Ridx , uint shift ) { InstructionSet.Opcode_SingleDataTransfer_2 enc = this.Encoder.PrepareForSingleDataTransfer_2; enc.Prepare( m_pendingCondition , // uint ConditionCodes , GetIntegerEncoding( Rs ) , // uint Rn , true , // bool IsLoad , true , // bool PreIndex , true , // bool Up , false , // bool WriteBack , GetIntegerEncoding( Rd ) , // uint Rd , false , // bool IsByte , GetIntegerEncoding( Ridx ) , // uint Rm , EncodingDefinition_ARM.c_shift_LSL, // uint ShiftType , shift ); // uint ShiftValue , EnqueueOpcode( enc ); } public void EmitOpcode__PLD( ZeligIR.Abstractions.RegisterDescriptor Rs , int offset ) { InstructionSet.Opcode_SingleDataTransfer_1 enc = this.Encoder.PrepareForSingleDataTransfer_1; bool fUp; uint uOffset; if(offset < 0) { fUp = false; uOffset = (uint)-offset; } else { fUp = true; uOffset = (uint)offset; } enc.Prepare( EncodingDefinition_ARM.c_cond_UNUSED, // uint ConditionCodes , GetIntegerEncoding( Rs ), // uint Rn , true , // bool IsLoad , true , // bool PreIndex , fUp , // bool Up , false , // bool WriteBack , 0xF , // uint Rd , true , // bool IsByte , uOffset ); // uint Offset , EnqueueOpcode( enc ); } public void EmitOpcode__LDR( ZeligIR.Abstractions.RegisterDescriptor Rd , ZeligIR.Abstractions.RegisterDescriptor Rs , int offset ) { EmitOpcode__LDR( Rd, Rs, offset, true, false ); } public void EmitOpcode__LDR( ZeligIR.Abstractions.RegisterDescriptor Rd , ZeligIR.Abstractions.RegisterDescriptor Rs , int offset , bool preIndex , bool writeBack ) { InstructionSet.Opcode_SingleDataTransfer_1 enc = this.Encoder.PrepareForSingleDataTransfer_1; bool fUp; uint uOffset; if(offset < 0) { fUp = false; uOffset = (uint)-offset; } else { fUp = true; uOffset = (uint)offset; } enc.Prepare( m_pendingCondition , // uint ConditionCodes , GetIntegerEncoding( Rs ), // uint Rn , true , // bool IsLoad , preIndex , // bool PreIndex , fUp , // bool Up , writeBack , // bool WriteBack , GetIntegerEncoding( Rd ), // uint Rd , false , // bool IsByte , uOffset ); // uint Offset , EnqueueOpcode( enc ); } public void EmitOpcode__LDRSH( ZeligIR.Abstractions.RegisterDescriptor Rd , ZeligIR.Abstractions.RegisterDescriptor Rs , int offset , bool preIndex , bool writeBack ) { InstructionSet.Opcode_HalfwordDataTransfer_2 enc = this.Encoder.PrepareForHalfwordDataTransfer_2; bool fUp; uint uOffset; if(offset < 0) { fUp = false; uOffset = (uint)-offset; } else { fUp = true; uOffset = (uint)offset; } enc.Prepare( m_pendingCondition , // uint ConditionCodes , GetIntegerEncoding( Rs ) , // uint Rn , true , // bool IsLoad , preIndex , // bool PreIndex , fUp , // bool Up , writeBack , // bool WriteBack , GetIntegerEncoding( Rd ) , // uint Rd , EncodingDefinition_ARM.c_halfwordkind_I2, // uint Kind , uOffset ); // uint Offset EnqueueOpcode( enc ); } public void EmitOpcode__LDRH( ZeligIR.Abstractions.RegisterDescriptor Rd , ZeligIR.Abstractions.RegisterDescriptor Rs , int offset , bool preIndex , bool writeBack ) { InstructionSet.Opcode_HalfwordDataTransfer_2 enc = this.Encoder.PrepareForHalfwordDataTransfer_2; bool fUp; uint uOffset; if(offset < 0) { fUp = false; uOffset = (uint)-offset; } else { fUp = true; uOffset = (uint)offset; } enc.Prepare( m_pendingCondition , // uint ConditionCodes , GetIntegerEncoding( Rs ) , // uint Rn , true , // bool IsLoad , preIndex , // bool PreIndex , fUp , // bool Up , writeBack , // bool WriteBack , GetIntegerEncoding( Rd ) , // uint Rd , EncodingDefinition_ARM.c_halfwordkind_U2, // uint Kind , uOffset ); // uint Offset EnqueueOpcode( enc ); } public void EmitOpcode__LDRSB( ZeligIR.Abstractions.RegisterDescriptor Rd , ZeligIR.Abstractions.RegisterDescriptor Rs , int offset , bool preIndex , bool writeBack ) { InstructionSet.Opcode_HalfwordDataTransfer_2 enc = this.Encoder.PrepareForHalfwordDataTransfer_2; bool fUp; uint uOffset; if(offset < 0) { fUp = false; uOffset = (uint)-offset; } else { fUp = true; uOffset = (uint)offset; } enc.Prepare( m_pendingCondition , // uint ConditionCodes , GetIntegerEncoding( Rs ) , // uint Rn , true , // bool IsLoad , preIndex , // bool PreIndex , fUp , // bool Up , writeBack , // bool WriteBack , GetIntegerEncoding( Rd ) , // uint Rd , EncodingDefinition_ARM.c_halfwordkind_I1, // uint Kind , uOffset ); // uint Offset EnqueueOpcode( enc ); } public void EmitOpcode__LDRB( ZeligIR.Abstractions.RegisterDescriptor Rd , ZeligIR.Abstractions.RegisterDescriptor Rs , int offset , bool preIndex , bool writeBack ) { InstructionSet.Opcode_SingleDataTransfer_1 enc = this.Encoder.PrepareForSingleDataTransfer_1; bool fUp; uint uOffset; if(offset < 0) { fUp = false; uOffset = (uint)-offset; } else { fUp = true; uOffset = (uint)offset; } enc.Prepare( m_pendingCondition , // uint ConditionCodes , GetIntegerEncoding( Rs ), // uint Rn , true , // bool IsLoad , preIndex , // bool PreIndex , fUp , // bool Up , writeBack , // bool WriteBack , GetIntegerEncoding( Rd ), // uint Rd , true , // bool IsByte , uOffset ); // uint Offset , EnqueueOpcode( enc ); } //--// public void EmitOpcode__MOV_CONST( ZeligIR.Abstractions.RegisterDescriptor Rd , uint valSeed , uint valRot ) { InstructionSet.Opcode_DataProcessing_1 enc = this.Encoder.PrepareForDataProcessing_1; enc.Prepare( m_pendingCondition , // uint ConditionCodes , EncodingDefinition_ARM.c_register_r0 , // uint Rn , GetIntegerEncoding( Rd ) , // uint Rd , EncodingDefinition_ARM.c_operation_MOV, // uint Alu , false , // bool SetCC , valSeed , // uint ImmediateSeed , valRot ); // uint ImmediateRotation , EnqueueOpcode( enc ); } public void EmitOpcode__MVN_CONST( ZeligIR.Abstractions.RegisterDescriptor Rd , uint valSeed , uint valRot ) { InstructionSet.Opcode_DataProcessing_1 enc = this.Encoder.PrepareForDataProcessing_1; enc.Prepare( m_pendingCondition , // uint ConditionCodes , EncodingDefinition_ARM.c_register_r0 , // uint Rn , GetIntegerEncoding( Rd ) , // uint Rd , EncodingDefinition_ARM.c_operation_MVN, // uint Alu , false , // bool SetCC , valSeed , // uint ImmediateSeed , valRot ); // uint ImmediateRotation , EnqueueOpcode( enc ); } public void EmitOpcode__ADD_CONST( ZeligIR.Abstractions.RegisterDescriptor Rd , ZeligIR.Abstractions.RegisterDescriptor Rs , uint valSeed , uint valRot ) { InstructionSet.Opcode_DataProcessing_1 enc = this.Encoder.PrepareForDataProcessing_1; enc.Prepare( m_pendingCondition , // uint ConditionCodes , GetIntegerEncoding( Rs ) , // uint Rn , GetIntegerEncoding( Rd ) , // uint Rd , EncodingDefinition_ARM.c_operation_ADD, // uint Alu , false , // bool SetCC , valSeed , // uint ImmediateSeed , valRot ); // uint ImmediateRotation , EnqueueOpcode( enc ); } public void EmitOpcode__ADC_CONST( ZeligIR.Abstractions.RegisterDescriptor Rd , ZeligIR.Abstractions.RegisterDescriptor Rs , uint valSeed , uint valRot ) { InstructionSet.Opcode_DataProcessing_1 enc = this.Encoder.PrepareForDataProcessing_1; enc.Prepare( m_pendingCondition , // uint ConditionCodes , GetIntegerEncoding( Rs ) , // uint Rn , GetIntegerEncoding( Rd ) , // uint Rd , EncodingDefinition_ARM.c_operation_ADC, // uint Alu , false , // bool SetCC , valSeed , // uint ImmediateSeed , valRot ); // uint ImmediateRotation , EnqueueOpcode( enc ); } public void EmitOpcode__SUB_CONST( ZeligIR.Abstractions.RegisterDescriptor Rd , ZeligIR.Abstractions.RegisterDescriptor Rs , uint valSeed , uint valRot ) { InstructionSet.Opcode_DataProcessing_1 enc = this.Encoder.PrepareForDataProcessing_1; enc.Prepare( m_pendingCondition , // uint ConditionCodes , GetIntegerEncoding( Rs ) , // uint Rn , GetIntegerEncoding( Rd ) , // uint Rd , EncodingDefinition_ARM.c_operation_SUB, // uint Alu , false , // bool SetCC , valSeed , // uint ImmediateSeed , valRot ); // uint ImmediateRotation , EnqueueOpcode( enc ); } public void EmitOpcode__SBC_CONST( ZeligIR.Abstractions.RegisterDescriptor Rd , ZeligIR.Abstractions.RegisterDescriptor Rs , uint valSeed , uint valRot ) { InstructionSet.Opcode_DataProcessing_1 enc = this.Encoder.PrepareForDataProcessing_1; enc.Prepare( m_pendingCondition , // uint ConditionCodes , GetIntegerEncoding( Rs ) , // uint Rn , GetIntegerEncoding( Rd ) , // uint Rd , EncodingDefinition_ARM.c_operation_SBC, // uint Alu , false , // bool SetCC , valSeed , // uint ImmediateSeed , valRot ); // uint ImmediateRotation , EnqueueOpcode( enc ); } public void EmitOpcode__RSB_CONST( ZeligIR.Abstractions.RegisterDescriptor Rd , ZeligIR.Abstractions.RegisterDescriptor Rs , uint valSeed , uint valRot ) { InstructionSet.Opcode_DataProcessing_1 enc = this.Encoder.PrepareForDataProcessing_1; enc.Prepare( m_pendingCondition , // uint ConditionCodes , GetIntegerEncoding( Rs ) , // uint Rn , GetIntegerEncoding( Rd ) , // uint Rd , EncodingDefinition_ARM.c_operation_RSB, // uint Alu , false , // bool SetCC , valSeed , // uint ImmediateSeed , valRot ); // uint ImmediateRotation , EnqueueOpcode( enc ); } public void EmitOpcode__RSC_CONST( ZeligIR.Abstractions.RegisterDescriptor Rd , ZeligIR.Abstractions.RegisterDescriptor Rs , uint valSeed , uint valRot ) { InstructionSet.Opcode_DataProcessing_1 enc = this.Encoder.PrepareForDataProcessing_1; enc.Prepare( m_pendingCondition , // uint ConditionCodes , GetIntegerEncoding( Rs ) , // uint Rn , GetIntegerEncoding( Rd ) , // uint Rd , EncodingDefinition_ARM.c_operation_RSC, // uint Alu , false , // bool SetCC , valSeed , // uint ImmediateSeed , valRot ); // uint ImmediateRotation , EnqueueOpcode( enc ); } public void EmitOpcode__CMP_CONST( ZeligIR.Abstractions.RegisterDescriptor Rs , uint valSeed , uint valRot ) { InstructionSet.Opcode_DataProcessing_1 enc = this.Encoder.PrepareForDataProcessing_1; enc.Prepare( m_pendingCondition , // uint ConditionCodes , GetIntegerEncoding( Rs ) , // uint Rn , 0 , // uint Rd , EncodingDefinition_ARM.c_operation_CMP, // uint Alu , true , // bool SetCC , valSeed , // uint ImmediateSeed , valRot ); // uint ImmediateRotation , EnqueueOpcode( enc ); } public void EmitOpcode__TST_CONST( ZeligIR.Abstractions.RegisterDescriptor Rs , uint valSeed , uint valRot ) { InstructionSet.Opcode_DataProcessing_1 enc = this.Encoder.PrepareForDataProcessing_1; enc.Prepare( m_pendingCondition , // uint ConditionCodes , GetIntegerEncoding( Rs ) , // uint Rn , 0 , // uint Rd , EncodingDefinition_ARM.c_operation_TST, // uint Alu , true , // bool SetCC , valSeed , // uint ImmediateSeed , valRot ); // uint ImmediateRotation , EnqueueOpcode( enc ); } public void EmitOpcode__AND_CONST( ZeligIR.Abstractions.RegisterDescriptor Rd , ZeligIR.Abstractions.RegisterDescriptor Rs , int val ) { uint valSeed; uint valRot; EncodeAs8BitImmediate( val, out valSeed, out valRot ); EmitOpcode__AND_CONST( Rd, Rs, valSeed, valRot ); } public void EmitOpcode__AND_CONST( ZeligIR.Abstractions.RegisterDescriptor Rd , ZeligIR.Abstractions.RegisterDescriptor Rs , uint valSeed , uint valRot ) { InstructionSet.Opcode_DataProcessing_1 enc = this.Encoder.PrepareForDataProcessing_1; enc.Prepare( m_pendingCondition , // uint ConditionCodes , GetIntegerEncoding( Rs ) , // uint Rn , GetIntegerEncoding( Rd ) , // uint Rd , EncodingDefinition_ARM.c_operation_AND, // uint Alu , false , // bool SetCC , valSeed , // uint ImmediateSeed , valRot ); // uint ImmediateRotation , EnqueueOpcode( enc ); } public void EmitOpcode__BIC_CONST( ZeligIR.Abstractions.RegisterDescriptor Rd , ZeligIR.Abstractions.RegisterDescriptor Rs , int val ) { uint valSeed; uint valRot; EncodeAs8BitImmediate( val, out valSeed, out valRot ); EmitOpcode__BIC_CONST( Rd, Rs, valSeed, valRot ); } public void EmitOpcode__BIC_CONST( ZeligIR.Abstractions.RegisterDescriptor Rd , ZeligIR.Abstractions.RegisterDescriptor Rs , uint valSeed , uint valRot ) { InstructionSet.Opcode_DataProcessing_1 enc = this.Encoder.PrepareForDataProcessing_1; enc.Prepare( m_pendingCondition , // uint ConditionCodes , GetIntegerEncoding( Rs ) , // uint Rn , GetIntegerEncoding( Rd ) , // uint Rd , EncodingDefinition_ARM.c_operation_BIC, // uint Alu , false , // bool SetCC , valSeed , // uint ImmediateSeed , valRot ); // uint ImmediateRotation , EnqueueOpcode( enc ); } public void EmitOpcode__OR_CONST( ZeligIR.Abstractions.RegisterDescriptor Rd , ZeligIR.Abstractions.RegisterDescriptor Rs , int val ) { uint valSeed; uint valRot; EncodeAs8BitImmediate( val, out valSeed, out valRot ); EmitOpcode__OR_CONST( Rd, Rs, valSeed, valRot ); } public void EmitOpcode__OR_CONST( ZeligIR.Abstractions.RegisterDescriptor Rd , ZeligIR.Abstractions.RegisterDescriptor Rs , uint valSeed , uint valRot ) { InstructionSet.Opcode_DataProcessing_1 enc = this.Encoder.PrepareForDataProcessing_1; enc.Prepare( m_pendingCondition , // uint ConditionCodes , GetIntegerEncoding( Rs ) , // uint Rn , GetIntegerEncoding( Rd ) , // uint Rd , EncodingDefinition_ARM.c_operation_ORR, // uint Alu , false , // bool SetCC , valSeed , // uint ImmediateSeed , valRot ); // uint ImmediateRotation , EnqueueOpcode( enc ); } public void EmitOpcode__EOR_CONST( ZeligIR.Abstractions.RegisterDescriptor Rd , ZeligIR.Abstractions.RegisterDescriptor Rs , int val ) { uint valSeed; uint valRot; EncodeAs8BitImmediate( val, out valSeed, out valRot ); EmitOpcode__EOR_CONST( Rd, Rs, valSeed, valRot ); } public void EmitOpcode__EOR_CONST( ZeligIR.Abstractions.RegisterDescriptor Rd , ZeligIR.Abstractions.RegisterDescriptor Rs , uint valSeed , uint valRot ) { InstructionSet.Opcode_DataProcessing_1 enc = this.Encoder.PrepareForDataProcessing_1; enc.Prepare( m_pendingCondition , // uint ConditionCodes , GetIntegerEncoding( Rs ) , // uint Rn , GetIntegerEncoding( Rd ) , // uint Rd , EncodingDefinition_ARM.c_operation_EOR, // uint Alu , false , // bool SetCC , valSeed , // uint ImmediateSeed , valRot ); // uint ImmediateRotation , EnqueueOpcode( enc ); } //--// public void EmitOpcode__MOV_IfDifferent( ZeligIR.Abstractions.RegisterDescriptor Rd , ZeligIR.Abstractions.RegisterDescriptor Rs ) { if(Rd != Rs) { EmitOpcode__MOV( Rd, Rs ); } } public void EmitOpcode__MOV( ZeligIR.Abstractions.RegisterDescriptor Rd , ZeligIR.Abstractions.RegisterDescriptor Rs ) { InstructionSet.Opcode_DataProcessing_2 enc = this.Encoder.PrepareForDataProcessing_2; enc.Prepare( m_pendingCondition , // uint ConditionCodes , EncodingDefinition_ARM.c_register_r0 , // uint Rn , GetIntegerEncoding( Rd ) , // uint Rd , EncodingDefinition_ARM.c_operation_MOV, // uint Alu , false , // bool SetCC , GetIntegerEncoding( Rs ) , // uint Rm , EncodingDefinition_ARM.c_shift_LSL , // uint ShiftType , 0 ); // uint ShiftValue , EnqueueOpcode( enc ); } public void EmitOpcode__MVN( ZeligIR.Abstractions.RegisterDescriptor Rd , ZeligIR.Abstractions.RegisterDescriptor Rs ) { InstructionSet.Opcode_DataProcessing_2 enc = this.Encoder.PrepareForDataProcessing_2; enc.Prepare( m_pendingCondition , // uint ConditionCodes , EncodingDefinition_ARM.c_register_r0 , // uint Rn , GetIntegerEncoding( Rd ) , // uint Rd , EncodingDefinition_ARM.c_operation_MVN, // uint Alu , false , // bool SetCC , GetIntegerEncoding( Rs ) , // uint Rm , EncodingDefinition_ARM.c_shift_LSL , // uint ShiftType , 0 ); // uint ShiftValue , EnqueueOpcode( enc ); } public void EmitOpcode__ADD( ZeligIR.Abstractions.RegisterDescriptor Rd , ZeligIR.Abstractions.RegisterDescriptor Rn , ZeligIR.Abstractions.RegisterDescriptor Rm ) { InstructionSet.Opcode_DataProcessing_2 enc = this.Encoder.PrepareForDataProcessing_2; enc.Prepare( m_pendingCondition , // uint ConditionCodes , GetIntegerEncoding( Rn ) , // uint Rn , GetIntegerEncoding( Rd ) , // uint Rd , EncodingDefinition_ARM.c_operation_ADD, // uint Alu , false , // bool SetCC , GetIntegerEncoding( Rm ) , // uint Rm , EncodingDefinition_ARM.c_shift_LSL , // uint ShiftType , 0 ); // uint ShiftValue , EnqueueOpcode( enc ); } public void EmitOpcode__ADC( ZeligIR.Abstractions.RegisterDescriptor Rd , ZeligIR.Abstractions.RegisterDescriptor Rn , ZeligIR.Abstractions.RegisterDescriptor Rm ) { InstructionSet.Opcode_DataProcessing_2 enc = this.Encoder.PrepareForDataProcessing_2; enc.Prepare( m_pendingCondition , // uint ConditionCodes , GetIntegerEncoding( Rn ) , // uint Rn , GetIntegerEncoding( Rd ) , // uint Rd , EncodingDefinition_ARM.c_operation_ADC, // uint Alu , false , // bool SetCC , GetIntegerEncoding( Rm ) , // uint Rm , EncodingDefinition_ARM.c_shift_LSL , // uint ShiftType , 0 ); // uint ShiftValue , EnqueueOpcode( enc ); } public void EmitOpcode__SUB( ZeligIR.Abstractions.RegisterDescriptor Rd , ZeligIR.Abstractions.RegisterDescriptor Rn , ZeligIR.Abstractions.RegisterDescriptor Rm ) { InstructionSet.Opcode_DataProcessing_2 enc = this.Encoder.PrepareForDataProcessing_2; enc.Prepare( m_pendingCondition , // uint ConditionCodes , GetIntegerEncoding( Rn ) , // uint Rn , GetIntegerEncoding( Rd ) , // uint Rd , EncodingDefinition_ARM.c_operation_SUB, // uint Alu , false , // bool SetCC , GetIntegerEncoding( Rm ) , // uint Rm , EncodingDefinition_ARM.c_shift_LSL , // uint ShiftType , 0 ); // uint ShiftValue , EnqueueOpcode( enc ); } public void EmitOpcode__SBC( ZeligIR.Abstractions.RegisterDescriptor Rd , ZeligIR.Abstractions.RegisterDescriptor Rn , ZeligIR.Abstractions.RegisterDescriptor Rm ) { InstructionSet.Opcode_DataProcessing_2 enc = this.Encoder.PrepareForDataProcessing_2; enc.Prepare( m_pendingCondition , // uint ConditionCodes , GetIntegerEncoding( Rn ) , // uint Rn , GetIntegerEncoding( Rd ) , // uint Rd , EncodingDefinition_ARM.c_operation_SBC, // uint Alu , false , // bool SetCC , GetIntegerEncoding( Rm ) , // uint Rm , EncodingDefinition_ARM.c_shift_LSL , // uint ShiftType , 0 ); // uint ShiftValue , EnqueueOpcode( enc ); } public void EmitOpcode__RSC( ZeligIR.Abstractions.RegisterDescriptor Rd , ZeligIR.Abstractions.RegisterDescriptor Rn , ZeligIR.Abstractions.RegisterDescriptor Rm ) { InstructionSet.Opcode_DataProcessing_2 enc = this.Encoder.PrepareForDataProcessing_2; enc.Prepare( m_pendingCondition , // uint ConditionCodes , GetIntegerEncoding( Rn ) , // uint Rn , GetIntegerEncoding( Rd ) , // uint Rd , EncodingDefinition_ARM.c_operation_RSC, // uint Alu , false , // bool SetCC , GetIntegerEncoding( Rm ) , // uint Rm , EncodingDefinition_ARM.c_shift_LSL , // uint ShiftType , 0 ); // uint ShiftValue , EnqueueOpcode( enc ); } public void EmitOpcode__CMP( ZeligIR.Abstractions.RegisterDescriptor Rn , ZeligIR.Abstractions.RegisterDescriptor Rm ) { InstructionSet.Opcode_DataProcessing_2 enc = this.Encoder.PrepareForDataProcessing_2; enc.Prepare( m_pendingCondition , // uint ConditionCodes , GetIntegerEncoding( Rn ) , // uint Rn , 0 , // uint Rd , EncodingDefinition_ARM.c_operation_CMP, // uint Alu , true , // bool SetCC , GetIntegerEncoding( Rm ) , // uint Rm , EncodingDefinition_ARM.c_shift_LSL , // uint ShiftType , 0 ); // uint ShiftValue , EnqueueOpcode( enc ); } public void EmitOpcode__TST( ZeligIR.Abstractions.RegisterDescriptor Rn , ZeligIR.Abstractions.RegisterDescriptor Rm ) { InstructionSet.Opcode_DataProcessing_2 enc = this.Encoder.PrepareForDataProcessing_2; enc.Prepare( m_pendingCondition , // uint ConditionCodes , GetIntegerEncoding( Rn ) , // uint Rn , 0 , // uint Rd , EncodingDefinition_ARM.c_operation_TST, // uint Alu , true , // bool SetCC , GetIntegerEncoding( Rm ) , // uint Rm , EncodingDefinition_ARM.c_shift_LSL , // uint ShiftType , 0 ); // uint ShiftValue , EnqueueOpcode( enc ); } public void EmitOpcode__AND( ZeligIR.Abstractions.RegisterDescriptor Rd , ZeligIR.Abstractions.RegisterDescriptor Rn , ZeligIR.Abstractions.RegisterDescriptor Rm ) { InstructionSet.Opcode_DataProcessing_2 enc = this.Encoder.PrepareForDataProcessing_2; enc.Prepare( m_pendingCondition , // uint ConditionCodes , GetIntegerEncoding( Rn ) , // uint Rn , GetIntegerEncoding( Rd ) , // uint Rd , EncodingDefinition_ARM.c_operation_AND, // uint Alu , false , // bool SetCC , GetIntegerEncoding( Rm ) , // uint Rm , EncodingDefinition_ARM.c_shift_LSL , // uint ShiftType , 0 ); // uint ShiftValue , EnqueueOpcode( enc ); } public void EmitOpcode__OR( ZeligIR.Abstractions.RegisterDescriptor Rd , ZeligIR.Abstractions.RegisterDescriptor Rn , ZeligIR.Abstractions.RegisterDescriptor Rm ) { InstructionSet.Opcode_DataProcessing_2 enc = this.Encoder.PrepareForDataProcessing_2; enc.Prepare( m_pendingCondition , // uint ConditionCodes , GetIntegerEncoding( Rn ) , // uint Rn , GetIntegerEncoding( Rd ) , // uint Rd , EncodingDefinition_ARM.c_operation_ORR, // uint Alu , false , // bool SetCC , GetIntegerEncoding( Rm ) , // uint Rm , EncodingDefinition_ARM.c_shift_LSL , // uint ShiftType , 0 ); // uint ShiftValue , EnqueueOpcode( enc ); } public void EmitOpcode__EOR( ZeligIR.Abstractions.RegisterDescriptor Rd , ZeligIR.Abstractions.RegisterDescriptor Rn , ZeligIR.Abstractions.RegisterDescriptor Rm ) { InstructionSet.Opcode_DataProcessing_2 enc = this.Encoder.PrepareForDataProcessing_2; enc.Prepare( m_pendingCondition , // uint ConditionCodes , GetIntegerEncoding( Rn ) , // uint Rn , GetIntegerEncoding( Rd ) , // uint Rd , EncodingDefinition_ARM.c_operation_EOR, // uint Alu , false , // bool SetCC , GetIntegerEncoding( Rm ) , // uint Rm , EncodingDefinition_ARM.c_shift_LSL , // uint ShiftType , 0 ); // uint ShiftValue , EnqueueOpcode( enc ); } public void EmitOpcode__LSL( ZeligIR.Abstractions.RegisterDescriptor Rd , ZeligIR.Abstractions.RegisterDescriptor Rm , ZeligIR.Abstractions.RegisterDescriptor Rs ) { InstructionSet.Opcode_DataProcessing_3 enc = this.Encoder.PrepareForDataProcessing_3; enc.Prepare( m_pendingCondition , // uint ConditionCodes , 0 , // uint Rn , GetIntegerEncoding( Rd ) , // uint Rd , EncodingDefinition_ARM.c_operation_MOV, // uint Alu , false , // bool SetCC , GetIntegerEncoding( Rm ) , // uint Rm , EncodingDefinition_ARM.c_shift_LSL , // uint ShiftType , GetIntegerEncoding( Rs ) ); // uint Rs , EnqueueOpcode( enc ); } public void EmitOpcode__LSR( ZeligIR.Abstractions.RegisterDescriptor Rd , ZeligIR.Abstractions.RegisterDescriptor Rm , ZeligIR.Abstractions.RegisterDescriptor Rs ) { InstructionSet.Opcode_DataProcessing_3 enc = this.Encoder.PrepareForDataProcessing_3; enc.Prepare( m_pendingCondition , // uint ConditionCodes , 0 , // uint Rn , GetIntegerEncoding( Rd ) , // uint Rd , EncodingDefinition_ARM.c_operation_MOV, // uint Alu , false , // bool SetCC , GetIntegerEncoding( Rm ) , // uint Rm , EncodingDefinition_ARM.c_shift_LSR , // uint ShiftType , GetIntegerEncoding( Rs ) ); // uint Rs , EnqueueOpcode( enc ); } public void EmitOpcode__ASR( ZeligIR.Abstractions.RegisterDescriptor Rd , ZeligIR.Abstractions.RegisterDescriptor Rm , ZeligIR.Abstractions.RegisterDescriptor Rs ) { InstructionSet.Opcode_DataProcessing_3 enc = this.Encoder.PrepareForDataProcessing_3; enc.Prepare( m_pendingCondition , // uint ConditionCodes , 0 , // uint Rn , GetIntegerEncoding( Rd ) , // uint Rd , EncodingDefinition_ARM.c_operation_MOV, // uint Alu , false , // bool SetCC , GetIntegerEncoding( Rm ) , // uint Rm , EncodingDefinition_ARM.c_shift_ASR , // uint ShiftType , GetIntegerEncoding( Rs ) ); // uint Rs , EnqueueOpcode( enc ); } //--// public void EmitOpcode__LSL_CONST( ZeligIR.Abstractions.RegisterDescriptor Rd , ZeligIR.Abstractions.RegisterDescriptor Rs , uint shift ) { InstructionSet.Opcode_DataProcessing_2 enc = this.Encoder.PrepareForDataProcessing_2; enc.Prepare( m_pendingCondition , // uint ConditionCodes , EncodingDefinition_ARM.c_register_r0 , // uint Rn , GetIntegerEncoding( Rd ) , // uint Rd , EncodingDefinition_ARM.c_operation_MOV, // uint Alu , false , // bool SetCC , GetIntegerEncoding( Rs ) , // uint Rm , EncodingDefinition_ARM.c_shift_LSL , // uint ShiftType , shift ); // uint ShiftValue , EnqueueOpcode( enc ); } public void EmitOpcode__LSR_CONST( ZeligIR.Abstractions.RegisterDescriptor Rd , ZeligIR.Abstractions.RegisterDescriptor Rs , uint shift ) { InstructionSet.Opcode_DataProcessing_2 enc = this.Encoder.PrepareForDataProcessing_2; enc.Prepare( m_pendingCondition , // uint ConditionCodes , EncodingDefinition_ARM.c_register_r0 , // uint Rn , GetIntegerEncoding( Rd ) , // uint Rd , EncodingDefinition_ARM.c_operation_MOV, // uint Alu , false , // bool SetCC , GetIntegerEncoding( Rs ) , // uint Rm , EncodingDefinition_ARM.c_shift_LSR , // uint ShiftType , shift ); // uint ShiftValue , EnqueueOpcode( enc ); } public void EmitOpcode__ASR_CONST( ZeligIR.Abstractions.RegisterDescriptor Rd , ZeligIR.Abstractions.RegisterDescriptor Rs , uint shift ) { InstructionSet.Opcode_DataProcessing_2 enc = this.Encoder.PrepareForDataProcessing_2; enc.Prepare( m_pendingCondition , // uint ConditionCodes , EncodingDefinition_ARM.c_register_r0 , // uint Rn , GetIntegerEncoding( Rd ) , // uint Rd , EncodingDefinition_ARM.c_operation_MOV, // uint Alu , false , // bool SetCC , GetIntegerEncoding( Rs ) , // uint Rm , EncodingDefinition_ARM.c_shift_ASR , // uint ShiftType , shift ); // uint ShiftValue , EnqueueOpcode( enc ); } //--// public void EmitOpcode__MULL( ZeligIR.Abstractions.RegisterDescriptor RdHi , ZeligIR.Abstractions.RegisterDescriptor RdLo , ZeligIR.Abstractions.RegisterDescriptor Rs , ZeligIR.Abstractions.RegisterDescriptor Rm , bool fIsSigned ) { InstructionSet.Opcode_MultiplyLong enc = this.Encoder.PrepareForMultiplyLong; enc.Prepare( m_pendingCondition , // uint ConditionCodes , GetIntegerEncoding( RdHi ), // uint RdHi , GetIntegerEncoding( RdLo ), // uint RdLo , GetIntegerEncoding( Rs ), // uint Rs , GetIntegerEncoding( Rm ), // uint Rm , false , // bool SetCC , false , // bool IsAccumulate , fIsSigned ); // bool IsSigned ) EnqueueOpcode( enc ); } //--// public void EmitOpcode__MUL( ZeligIR.Abstractions.RegisterDescriptor Rd , ZeligIR.Abstractions.RegisterDescriptor Rs , ZeligIR.Abstractions.RegisterDescriptor Rm ) { InstructionSet.Opcode_Multiply enc = this.Encoder.PrepareForMultiply; enc.Prepare( m_pendingCondition , // uint ConditionCodes , GetIntegerEncoding( Rd ), // uint Rd , 0 , // uint Rn , GetIntegerEncoding( Rs ), // uint Rs , GetIntegerEncoding( Rm ), // uint Rm , false , // bool SetCC , false ); // bool IsAccumulate EnqueueOpcode( enc ); } //--// public void EmitOpcode__STMFD( ZeligIR.Abstractions.RegisterDescriptor Rn , uint lst ) { EmitOpcode__STM( Rn, lst, true, false, true ); } public void EmitOpcode__STM( ZeligIR.Abstractions.RegisterDescriptor Rn , uint lst , bool PreIndex , bool Up , bool WriteBack ) { InstructionSet.Opcode_BlockDataTransfer enc = this.Encoder.PrepareForBlockDataTransfer; enc.Prepare( m_pendingCondition , // uint ConditionCodes , GetIntegerEncoding( Rn ), // uint Rn , false , // bool IsLoad , PreIndex , // bool PreIndex , Up , // bool Up , WriteBack , // bool WriteBack , lst , // uint Lst , false ); // bool LoadPSR ); EnqueueOpcode( enc ); } //--// public void EmitOpcode__LDMFD( ZeligIR.Abstractions.RegisterDescriptor Rn , uint lst , bool LoadPSR ) { EmitOpcode__LDM( Rn, lst, false, true, true, LoadPSR ); } public void EmitOpcode__LDM( ZeligIR.Abstractions.RegisterDescriptor Rn , uint lst , bool PreIndex , bool Up , bool WriteBack , bool LoadPSR ) { InstructionSet.Opcode_BlockDataTransfer enc = this.Encoder.PrepareForBlockDataTransfer; enc.Prepare( m_pendingCondition , // uint ConditionCodes , GetIntegerEncoding( Rn ), // uint Rn , true , // bool IsLoad , PreIndex , // bool PreIndex , Up , // bool Up , WriteBack , // bool WriteBack , lst , // uint Lst , LoadPSR ); // bool LoadPSR ); EnqueueOpcode( enc ); } public void EmitOpcode__SWI( uint val ) { InstructionSet.Opcode_SoftwareInterrupt enc = this.Encoder.PrepareForSoftwareInterrupt; enc.Prepare( m_pendingCondition, // uint ConditionCodes , val ); // uint Value ); EnqueueOpcode( enc ); } public void EmitOpcode__MRS( bool UseSPSR , ZeligIR.Abstractions.RegisterDescriptor Rd ) { InstructionSet.Opcode_MRS enc = this.Encoder.PrepareForMRS; enc.Prepare( m_pendingCondition , // uint ConditionCodes , UseSPSR , // bool UseSPSR , GetIntegerEncoding( Rd ) ); // uint Rd ); EnqueueOpcode( enc ); } public void EmitOpcode__MSR( bool UseSPSR , uint Fields , ZeligIR.Abstractions.RegisterDescriptor Rm ) { InstructionSet.Opcode_MSR_1 enc = this.Encoder.PrepareForMSR_1; enc.Prepare( m_pendingCondition , // uint ConditionCodes , UseSPSR , // bool UseSPSR , Fields , // uint Fields , GetIntegerEncoding( Rm ) ); // uint Rm ); EnqueueOpcode( enc ); } public void EmitOpcode__MSR_CONST( bool UseSPSR , uint Fields , uint valSeed , uint valRot ) { InstructionSet.Opcode_MSR_2 enc = this.Encoder.PrepareForMSR_2; enc.Prepare( m_pendingCondition, // uint ConditionCodes , UseSPSR , // bool UseSPSR , Fields , // uint Fields , valSeed , // uint ImmediateSeed , valRot ); // uint ImmediateRotation ); EnqueueOpcode( enc ); } public void EmitOpcode__MCR( uint CpNum , uint Op1 , ZeligIR.Abstractions.RegisterDescriptor Rn , uint CRn , uint CRm , uint Op2 ) { InstructionSet.Opcode_CoprocRegisterTransfer enc = this.Encoder.PrepareForCoprocRegisterTransfer; enc.Prepare( m_pendingCondition , // uint ConditionCodes , false , // bool IsMRC , Op1 , // uint Op1 , Op2 , // uint Op2 , CpNum , // uint CpNum , CRn , // uint CRn , CRm , // uint CRm , GetIntegerEncoding( Rn ) ); // uint Rd ); EnqueueOpcode( enc ); } public void EmitOpcode__MRC( uint CpNum , uint Op1 , ZeligIR.Abstractions.RegisterDescriptor Rd , uint CRn , uint CRm , uint Op2 ) { InstructionSet.Opcode_CoprocRegisterTransfer enc = this.Encoder.PrepareForCoprocRegisterTransfer; enc.Prepare( m_pendingCondition , // uint ConditionCodes , true , // bool IsMRC , Op1 , // uint Op1 , Op2 , // uint Op2 , CpNum , // uint CpNum , CRn , // uint CRn , CRm , // uint CRm , GetIntegerEncoding( Rd ) ); // uint Rd ); EnqueueOpcode( enc ); } //--// public void EmitOpcode__BKPT( uint val ) { InstructionSet.Opcode_Breakpoint enc = this.Encoder.PrepareForBreakpoint; enc.Prepare( m_pendingCondition, // uint ConditionCodes , val ); // uint Value ); EnqueueOpcode( enc ); } //--// // // Debug Methods // protected override void DumpOpcodes( System.IO.TextWriter textWriter ) { InstructionSet encoder = this.Encoder; textWriter.WriteLine( "{0}", m_cfg ); foreach(ZeligIR.ImageBuilders.SequentialRegion reg in m_associatedRegions) { reg.Dump( textWriter ); } textWriter.WriteLine(); textWriter.WriteLine(); } } } ================================================ FILE: Zelig/Zelig/CompileTime/TargetModels/ProductConfiguration/Abstractions/ARM/ArmPlatform_CompilationState_Encoder_VFP.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // namespace Microsoft.Zelig.Configuration.Environment.Abstractions { using System; using System.Collections.Generic; using Microsoft.Zelig.Runtime.TypeSystem; using Microsoft.Zelig.TargetModel.ArmProcessor; using ZeligIR = Microsoft.Zelig.CodeGeneration.IR; public partial class ArmCompilationState { // // Helper Methods // public void EmitOpcode__FCPY_IfDifferent( ZeligIR.Abstractions.RegisterDescriptor Fd , ZeligIR.Abstractions.RegisterDescriptor Fm ) { if(Fd.Encoding != Fm.Encoding) { EmitOpcode__FCPY( Fd, Fm ); } } public void EmitOpcode__FCPY( ZeligIR.Abstractions.RegisterDescriptor Fd , ZeligIR.Abstractions.RegisterDescriptor Fm ) { EmitOpcode__UnaryOp( Fd, Fm, EncodingDefinition_VFP.c_unaryOperation_CPY ); } public void EmitOpcode__FNEG( ZeligIR.Abstractions.RegisterDescriptor Fd , ZeligIR.Abstractions.RegisterDescriptor Fm ) { EmitOpcode__UnaryOp( Fd, Fm, EncodingDefinition_VFP.c_unaryOperation_NEG ); } public void EmitOpcode__FCMP( ZeligIR.Abstractions.RegisterDescriptor Fd , ZeligIR.Abstractions.RegisterDescriptor Fm ) { EmitOpcode__UnaryOp( Fd, Fm, EncodingDefinition_VFP.c_unaryOperation_CMP ); } public void EmitOpcode__FCMPZ( ZeligIR.Abstractions.RegisterDescriptor Fd ) { InstructionSet_VFP.Opcode_VFP_CompareToZero enc = this.Encoder_VFP.PrepareForVFP_CompareToZero; if(Fd.IsDoublePrecision) { enc.Prepare( m_pendingCondition , // uint ConditionCodes , true , // bool IsDouble , GetDoublePrecisionEncoding( Fd ) , // uint Fd , false ); // bool CheckNaN ) } else { enc.Prepare( m_pendingCondition , // uint ConditionCodes , false , // bool IsDouble , GetSinglePrecisionEncoding( Fd ) , // uint Fd , false ); // bool CheckNaN ) } EnqueueOpcode( enc ); } public void EmitOpcode__FMSTAT() { InstructionSet_VFP.Opcode_VFP_ConditionCodeTransfer enc = this.Encoder_VFP.PrepareForVFP_ConditionCodeTransfer; enc.Prepare( m_pendingCondition ); // uint ConditionCodes , EnqueueOpcode( enc ); } public void EmitOpcode__FMRX( ZeligIR.Abstractions.RegisterDescriptor Rd , ZeligIR.Abstractions.RegisterDescriptor reg ) { InstructionSet_VFP.Opcode_VFP_SystemRegisterTransfer enc = this.Encoder_VFP.PrepareForVFP_SystemRegisterTransfer; enc.Prepare( m_pendingCondition, // uint ConditionCodes , GetIntegerEncoding( Rd ) , // uint Rd , GetSystemEncoding( reg ) , // uint SysReg , true ); // bool IsFromCoProc ) EnqueueOpcode( enc ); } public void EmitOpcode__FMXR( ZeligIR.Abstractions.RegisterDescriptor Rd , ZeligIR.Abstractions.RegisterDescriptor reg ) { InstructionSet_VFP.Opcode_VFP_SystemRegisterTransfer enc = this.Encoder_VFP.PrepareForVFP_SystemRegisterTransfer; enc.Prepare( m_pendingCondition, // uint ConditionCodes , GetIntegerEncoding( Rd ) , // uint Rd , GetSystemEncoding( reg ) , // uint SysReg , false ); // bool IsFromCoProc ) EnqueueOpcode( enc ); } private void EmitOpcode__UnaryOp( ZeligIR.Abstractions.RegisterDescriptor Fd , ZeligIR.Abstractions.RegisterDescriptor Fm , uint Alu ) { InstructionSet_VFP.Opcode_VFP_UnaryDataOperation enc = this.Encoder_VFP.PrepareForVFP_UnaryDataOperation; if(Fd.IsDoublePrecision) { enc.Prepare( m_pendingCondition , // uint ConditionCodes , true , // bool IsDouble , GetDoublePrecisionEncoding( Fd ), // uint Fd , GetDoublePrecisionEncoding( Fm ), // uint Fm , Alu ); // uint Alu , } else { enc.Prepare( m_pendingCondition , // uint ConditionCodes , false , // bool IsDouble , GetSinglePrecisionEncoding( Fd ), // uint Fd , GetSinglePrecisionEncoding( Fm ), // uint Fm , Alu ); // uint Alu , } EnqueueOpcode( enc ); } //--// public void EmitOpcode__FSITOS( ZeligIR.Abstractions.RegisterDescriptor Fd , ZeligIR.Abstractions.RegisterDescriptor Fm ) { InstructionSet_VFP.Opcode_VFP_UnaryDataOperation enc = this.Encoder_VFP.PrepareForVFP_UnaryDataOperation; enc.Prepare( m_pendingCondition , // uint ConditionCodes , false , // bool IsDouble , GetSinglePrecisionEncoding( Fd ) , // uint Fd , GetSinglePrecisionEncoding( Fm ) , // uint Fm , EncodingDefinition_VFP.c_unaryOperation_SITO ); // uint Alu , EnqueueOpcode( enc ); } public void EmitOpcode__FSITOD( ZeligIR.Abstractions.RegisterDescriptor Fd , ZeligIR.Abstractions.RegisterDescriptor Fm ) { InstructionSet_VFP.Opcode_VFP_UnaryDataOperation enc = this.Encoder_VFP.PrepareForVFP_UnaryDataOperation; enc.Prepare( m_pendingCondition , // uint ConditionCodes , true , // bool IsDouble , GetDoublePrecisionEncoding( Fd ) , // uint Fd , GetSinglePrecisionEncoding( Fm ) , // uint Fm , EncodingDefinition_VFP.c_unaryOperation_SITO ); // uint Alu , EnqueueOpcode( enc ); } public void EmitOpcode__FUITOS( ZeligIR.Abstractions.RegisterDescriptor Fd , ZeligIR.Abstractions.RegisterDescriptor Fm ) { InstructionSet_VFP.Opcode_VFP_UnaryDataOperation enc = this.Encoder_VFP.PrepareForVFP_UnaryDataOperation; enc.Prepare( m_pendingCondition , // uint ConditionCodes , false , // bool IsDouble , GetSinglePrecisionEncoding( Fd ) , // uint Fd , GetSinglePrecisionEncoding( Fm ) , // uint Fm , EncodingDefinition_VFP.c_unaryOperation_UITO ); // uint Alu , EnqueueOpcode( enc ); } public void EmitOpcode__FUITOD( ZeligIR.Abstractions.RegisterDescriptor Fd , ZeligIR.Abstractions.RegisterDescriptor Fm ) { InstructionSet_VFP.Opcode_VFP_UnaryDataOperation enc = this.Encoder_VFP.PrepareForVFP_UnaryDataOperation; enc.Prepare( m_pendingCondition , // uint ConditionCodes , true , // bool IsDouble , GetDoublePrecisionEncoding( Fd ) , // uint Fd , GetSinglePrecisionEncoding( Fm ) , // uint Fm , EncodingDefinition_VFP.c_unaryOperation_UITO ); // uint Alu , EnqueueOpcode( enc ); } public void EmitOpcode__FTOSIS( ZeligIR.Abstractions.RegisterDescriptor Fd , ZeligIR.Abstractions.RegisterDescriptor Fm ) { InstructionSet_VFP.Opcode_VFP_UnaryDataOperation enc = this.Encoder_VFP.PrepareForVFP_UnaryDataOperation; enc.Prepare( m_pendingCondition , // uint ConditionCodes , false , // bool IsDouble , GetSinglePrecisionEncoding( Fd ) , // uint Fd , GetSinglePrecisionEncoding( Fm ) , // uint Fm , EncodingDefinition_VFP.c_unaryOperation_TOSI ); // uint Alu , EnqueueOpcode( enc ); } public void EmitOpcode__FTOSID( ZeligIR.Abstractions.RegisterDescriptor Fd , ZeligIR.Abstractions.RegisterDescriptor Fm ) { InstructionSet_VFP.Opcode_VFP_UnaryDataOperation enc = this.Encoder_VFP.PrepareForVFP_UnaryDataOperation; enc.Prepare( m_pendingCondition , // uint ConditionCodes , true , // bool IsDouble , GetSinglePrecisionEncoding( Fd ) , // uint Fd , GetDoublePrecisionEncoding( Fm ) , // uint Fm , EncodingDefinition_VFP.c_unaryOperation_TOSI ); // uint Alu , EnqueueOpcode( enc ); } public void EmitOpcode__FTOUIS( ZeligIR.Abstractions.RegisterDescriptor Fd , ZeligIR.Abstractions.RegisterDescriptor Fm ) { InstructionSet_VFP.Opcode_VFP_UnaryDataOperation enc = this.Encoder_VFP.PrepareForVFP_UnaryDataOperation; enc.Prepare( m_pendingCondition , // uint ConditionCodes , false , // bool IsDouble , GetSinglePrecisionEncoding( Fd ) , // uint Fd , GetSinglePrecisionEncoding( Fm ) , // uint Fm , EncodingDefinition_VFP.c_unaryOperation_TOUI ); // uint Alu , EnqueueOpcode( enc ); } public void EmitOpcode__FTOUID( ZeligIR.Abstractions.RegisterDescriptor Fd , ZeligIR.Abstractions.RegisterDescriptor Fm ) { InstructionSet_VFP.Opcode_VFP_UnaryDataOperation enc = this.Encoder_VFP.PrepareForVFP_UnaryDataOperation; enc.Prepare( m_pendingCondition , // uint ConditionCodes , true , // bool IsDouble , GetSinglePrecisionEncoding( Fd ) , // uint Fd , GetDoublePrecisionEncoding( Fm ) , // uint Fm , EncodingDefinition_VFP.c_unaryOperation_TOUI ); // uint Alu , EnqueueOpcode( enc ); } public void EmitOpcode__FCVTSD( ZeligIR.Abstractions.RegisterDescriptor Sd , ZeligIR.Abstractions.RegisterDescriptor Dm ) { InstructionSet_VFP.Opcode_VFP_ConvertFloatToFloat enc = this.Encoder_VFP.PrepareForVFP_ConvertFloatToFloat; enc.Prepare( m_pendingCondition , // uint ConditionCodes , true , // bool IsDouble , GetSinglePrecisionEncoding( Sd ) , // uint Fd , GetDoublePrecisionEncoding( Dm ) ); // uint Fm ) EnqueueOpcode( enc ); } public void EmitOpcode__FCVTDS( ZeligIR.Abstractions.RegisterDescriptor Dd , ZeligIR.Abstractions.RegisterDescriptor Sm ) { InstructionSet_VFP.Opcode_VFP_ConvertFloatToFloat enc = this.Encoder_VFP.PrepareForVFP_ConvertFloatToFloat; enc.Prepare( m_pendingCondition , // uint ConditionCodes , false , // bool IsDouble , GetDoublePrecisionEncoding( Dd ) , // uint Fd , GetSinglePrecisionEncoding( Sm ) ); // uint Fm ) EnqueueOpcode( enc ); } //--// public void EmitOpcode__FADD( ZeligIR.Abstractions.RegisterDescriptor Fd , ZeligIR.Abstractions.RegisterDescriptor Fn , ZeligIR.Abstractions.RegisterDescriptor Fm ) { EmitOpcode__BinaryOp( Fd, Fn, Fm, EncodingDefinition_VFP.c_binaryOperation_ADD ); } public void EmitOpcode__FSUB( ZeligIR.Abstractions.RegisterDescriptor Fd , ZeligIR.Abstractions.RegisterDescriptor Fn , ZeligIR.Abstractions.RegisterDescriptor Fm ) { EmitOpcode__BinaryOp( Fd, Fn, Fm, EncodingDefinition_VFP.c_binaryOperation_SUB ); } public void EmitOpcode__FMAC( ZeligIR.Abstractions.RegisterDescriptor Fd , ZeligIR.Abstractions.RegisterDescriptor Fn , ZeligIR.Abstractions.RegisterDescriptor Fm ) { EmitOpcode__BinaryOp( Fd, Fn, Fm, EncodingDefinition_VFP.c_binaryOperation_MAC ); } public void EmitOpcode__FMUL( ZeligIR.Abstractions.RegisterDescriptor Fd , ZeligIR.Abstractions.RegisterDescriptor Fn , ZeligIR.Abstractions.RegisterDescriptor Fm ) { EmitOpcode__BinaryOp( Fd, Fn, Fm, EncodingDefinition_VFP.c_binaryOperation_MUL ); } public void EmitOpcode__FDIV( ZeligIR.Abstractions.RegisterDescriptor Fd , ZeligIR.Abstractions.RegisterDescriptor Fn , ZeligIR.Abstractions.RegisterDescriptor Fm ) { EmitOpcode__BinaryOp( Fd, Fn, Fm, EncodingDefinition_VFP.c_binaryOperation_DIV ); } private void EmitOpcode__BinaryOp( ZeligIR.Abstractions.RegisterDescriptor Fd , ZeligIR.Abstractions.RegisterDescriptor Fn , ZeligIR.Abstractions.RegisterDescriptor Fm , uint Alu ) { InstructionSet_VFP.Opcode_VFP_BinaryDataOperation enc = this.Encoder_VFP.PrepareForVFP_BinaryDataOperation; if(Fd.IsDoublePrecision) { enc.Prepare( m_pendingCondition , // uint ConditionCodes , true , // bool IsDouble , GetDoublePrecisionEncoding( Fd ) , // uint Fd , GetDoublePrecisionEncoding( Fn ) , // uint Fn , GetDoublePrecisionEncoding( Fm ) , // uint Fm , Alu ); // uint Alu , } else { enc.Prepare( m_pendingCondition , // uint ConditionCodes , false , // bool IsDouble , GetSinglePrecisionEncoding( Fd ) , // uint Fd , GetSinglePrecisionEncoding( Fn ) , // uint Fn , GetSinglePrecisionEncoding( Fm ) , // uint Fm , Alu ); // uint Alu , } EnqueueOpcode( enc ); } //--// public void EmitOpcode__FMRS( ZeligIR.Abstractions.RegisterDescriptor Rd , ZeligIR.Abstractions.RegisterDescriptor Fn ) { InstructionSet_VFP.Opcode_VFP_32bitRegisterTransfer enc = this.Encoder_VFP.PrepareForVFP_32bitRegisterTransfer; enc.Prepare( m_pendingCondition , // uint ConditionCodes , GetIntegerEncoding ( Rd ) , // uint Rd , GetSinglePrecisionEncoding( Fn ) , // uint Fn , true ); // bool IsFromCoProc ) EnqueueOpcode( enc ); } public void EmitOpcode__FMSR( ZeligIR.Abstractions.RegisterDescriptor Rd , ZeligIR.Abstractions.RegisterDescriptor Fn ) { InstructionSet_VFP.Opcode_VFP_32bitRegisterTransfer enc = this.Encoder_VFP.PrepareForVFP_32bitRegisterTransfer; enc.Prepare( m_pendingCondition , // uint ConditionCodes , GetIntegerEncoding ( Rd ), // uint Rd , GetSinglePrecisionEncoding( Fn ), // uint Fn , false ); // bool IsFromCoProc ) EnqueueOpcode( enc ); } //--// public void EmitOpcode__FMRDL( ZeligIR.Abstractions.RegisterDescriptor Rd , ZeligIR.Abstractions.RegisterDescriptor Fn ) { InstructionSet_VFP.Opcode_VFP_32bitLoRegisterTransfer enc = this.Encoder_VFP.PrepareForVFP_32bitLoRegisterTransfer; enc.Prepare( m_pendingCondition , // uint ConditionCodes , GetIntegerEncoding ( Rd ) , // uint Rd , GetDoublePrecisionEncoding( Fn ) , // uint Fn , true ); // bool IsFromCoProc ) EnqueueOpcode( enc ); } public void EmitOpcode__FMDLR( ZeligIR.Abstractions.RegisterDescriptor Rd , ZeligIR.Abstractions.RegisterDescriptor Fn ) { InstructionSet_VFP.Opcode_VFP_32bitLoRegisterTransfer enc = this.Encoder_VFP.PrepareForVFP_32bitLoRegisterTransfer; enc.Prepare( m_pendingCondition , // uint ConditionCodes , GetIntegerEncoding ( Rd ), // uint Rd , GetDoublePrecisionEncoding( Fn ), // uint Fn , false ); // bool IsFromCoProc ) EnqueueOpcode( enc ); } //--// public void EmitOpcode__FMRDH( ZeligIR.Abstractions.RegisterDescriptor Rd , ZeligIR.Abstractions.RegisterDescriptor Fn ) { InstructionSet_VFP.Opcode_VFP_32bitHiRegisterTransfer enc = this.Encoder_VFP.PrepareForVFP_32bitHiRegisterTransfer; enc.Prepare( m_pendingCondition , // uint ConditionCodes , GetIntegerEncoding ( Rd ) , // uint Rd , GetDoublePrecisionEncoding( Fn ) , // uint Fn , true ); // bool IsFromCoProc ) EnqueueOpcode( enc ); } public void EmitOpcode__FMDHR( ZeligIR.Abstractions.RegisterDescriptor Rd , ZeligIR.Abstractions.RegisterDescriptor Fn ) { InstructionSet_VFP.Opcode_VFP_32bitHiRegisterTransfer enc = this.Encoder_VFP.PrepareForVFP_32bitHiRegisterTransfer; enc.Prepare( m_pendingCondition , // uint ConditionCodes , GetIntegerEncoding ( Rd ), // uint Rd , GetDoublePrecisionEncoding( Fn ), // uint Fn , false ); // bool IsFromCoProc ) EnqueueOpcode( enc ); } //--// public void EmitOpcode__FLD( ZeligIR.Abstractions.RegisterDescriptor Fd , ZeligIR.Abstractions.RegisterDescriptor Rd , int offset ) { EmitOpcode__VFP_DataTransfer( Fd, Rd, offset, true ); } public void EmitOpcode__FST( ZeligIR.Abstractions.RegisterDescriptor Fd , ZeligIR.Abstractions.RegisterDescriptor Rd , int offset ) { EmitOpcode__VFP_DataTransfer( Fd, Rd, offset, false ); } private void EmitOpcode__VFP_DataTransfer( ZeligIR.Abstractions.RegisterDescriptor Fd , ZeligIR.Abstractions.RegisterDescriptor Rn , int offset , bool fLoad ) { CHECKS.ASSERT( offset % sizeof(uint) == 0, "offset must be word-aligned, got {0}", offset ); InstructionSet_VFP.Opcode_VFP_DataTransfer enc = this.Encoder_VFP.PrepareForVFP_DataTransfer; bool fUp; uint uOffset; if(offset < 0) { fUp = false; uOffset = ((uint)-offset) / sizeof(uint); } else { fUp = true; uOffset = ((uint)offset) / sizeof(uint); } if(Fd.IsDoublePrecision) { enc.Prepare( m_pendingCondition , // uint ConditionCodes , true , // bool IsDouble , GetIntegerEncoding ( Rn ) , // uint Rn , GetDoublePrecisionEncoding( Fd ) , // uint Fd , fLoad , // bool IsLoad , fUp , // bool Up , uOffset ); // uint Offset ) } else { enc.Prepare( m_pendingCondition , // uint ConditionCodes , false , // bool IsDouble , GetIntegerEncoding ( Rn ) , // uint Rn , GetSinglePrecisionEncoding( Fd ) , // uint Fd , fLoad , // bool IsLoad , fUp , // bool Up , uOffset ); // uint Offset ) } EnqueueOpcode( enc ); } //--// public void EmitOpcode__FLDM( ZeligIR.Abstractions.RegisterDescriptor Rn , ZeligIR.Abstractions.RegisterDescriptor Fd , uint count , bool fPreIndex , bool fUp , bool fWriteBack ) { InstructionSet_VFP.Opcode_VFP_BlockDataTransfer enc = this.Encoder_VFP.PrepareForVFP_BlockDataTransfer; if(Fd.IsDoublePrecision) { enc.Prepare( m_pendingCondition , // uint ConditionCodes , true , // bool IsDouble , GetIntegerEncoding ( Rn ), // uint Rn , GetDoublePrecisionEncoding( Fd ), // uint Fd , true , // bool IsLoad , fPreIndex , // bool PreIndex , fUp , // bool Up , fWriteBack , // bool WriteBack , count ); // uint Count ) } else { enc.Prepare( m_pendingCondition , // uint ConditionCodes , false , // bool IsDouble , GetIntegerEncoding ( Rn ), // uint Rn , GetSinglePrecisionEncoding( Fd ), // uint Fd , true , // bool IsLoad , fPreIndex , // bool PreIndex , fUp , // bool Up , fWriteBack , // bool WriteBack , count ); // uint Count ) } EnqueueOpcode( enc ); } public void EmitOpcode__FLDMFD( ZeligIR.Abstractions.RegisterDescriptor Rn , ZeligIR.Abstractions.RegisterDescriptor Fd , uint count ) { EmitOpcode__FLDM( Rn, Fd, count, false, true, true ); } //--// public void EmitOpcode__FSTM( ZeligIR.Abstractions.RegisterDescriptor Rn , ZeligIR.Abstractions.RegisterDescriptor Fd , uint count , bool fPreIndex , bool fUp , bool fWriteBack ) { InstructionSet_VFP.Opcode_VFP_BlockDataTransfer enc = this.Encoder_VFP.PrepareForVFP_BlockDataTransfer; if(Fd.IsDoublePrecision) { enc.Prepare( m_pendingCondition , // uint ConditionCodes , true , // bool IsDouble , GetIntegerEncoding ( Rn ), // uint Rn , GetDoublePrecisionEncoding( Fd ), // uint Fd , false , // bool IsLoad , fPreIndex , // bool PreIndex , fUp , // bool Up , fWriteBack , // bool WriteBack , count ); // uint Count ) } else { enc.Prepare( m_pendingCondition , // uint ConditionCodes , false , // bool IsDouble , GetIntegerEncoding ( Rn ), // uint Rn , GetSinglePrecisionEncoding( Fd ), // uint Fd , false , // bool IsLoad , fPreIndex , // bool PreIndex , fUp , // bool Up , fWriteBack , // bool WriteBack , count ); // uint Count ) } EnqueueOpcode( enc ); } public void EmitOpcode__FSTMFD( ZeligIR.Abstractions.RegisterDescriptor Rn , ZeligIR.Abstractions.RegisterDescriptor Fd , uint count ) { EmitOpcode__FSTM( Rn, Fd, count, true, false, true ); } } } ================================================ FILE: Zelig/Zelig/CompileTime/TargetModels/ProductConfiguration/Abstractions/ARM/ArmPlatform_EmitPrologueEpilogue.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // namespace Microsoft.Zelig.Configuration.Environment.Abstractions { using System; using System.Collections.Generic; using Microsoft.Zelig.Runtime.TypeSystem; using Microsoft.Zelig.TargetModel.ArmProcessor; using ZeligIR = Microsoft.Zelig.CodeGeneration.IR; public partial class ArmPlatform { // // Helper Methods // public bool Emit__WasRegisterTouched( ZeligIR.Abstractions.RegisterDescriptor regDesc , BitVector modifiedRegisters ) { return modifiedRegisters[ (int)regDesc.Encoding ]; } public uint Emit__GetIntegerList( ArmCompilationState cs , BitVector registersToSave ) { uint mask = 0; foreach(ZeligIR.Abstractions.RegisterDescriptor regToSave in this.GetRegisters()) { if(regToSave.InIntegerRegisterFile && regToSave.IsLinkAddress == false) { if(registersToSave[ (int)regToSave.Encoding ]) { mask |= 1U << (int)ArmCompilationState.GetIntegerEncoding( regToSave ); } } } return mask; } public void Emit__GetFloatingPointList( ArmCompilationState cs , BitVector registersToSave , out ZeligIR.Abstractions.RegisterDescriptor regLowest , out ZeligIR.Abstractions.RegisterDescriptor regHighest ) { regLowest = null; regHighest = null; foreach(ZeligIR.Abstractions.RegisterDescriptor regToSave in this.GetRegisters()) { if(regToSave.InFloatingPointRegisterFile) { if(registersToSave[ (int)regToSave.Encoding ]) { CHECKS.ASSERT( regToSave.IsDoublePrecision, "Expecting double-precision register, got {0}", regToSave ); if(regLowest == null || regLowest .Encoding > regToSave.Encoding) regLowest = regToSave; if(regHighest == null || regHighest.Encoding < regToSave.Encoding) regHighest = regToSave; } } } } //--// public override void ComputeSetOfRegistersToSave( ZeligIR.Abstractions.CallingConvention cc , ZeligIR.ControlFlowGraphStateForCodeTransformation cfg , BitVector modifiedRegisters , out BitVector registersToSave , out Runtime.HardwareException he ) { ZeligIR.TypeSystemForCodeTransformation ts = cfg.TypeSystem; MethodRepresentation md = cfg.Method; bool fFullContext = false; registersToSave = new BitVector(); he = ts.ExtractHardwareExceptionSettingsForMethod( md ); if(he != Runtime.HardwareException.None) { // // Make sure we also save the registers trashed by the calling convention. // foreach(ZeligIR.Abstractions.RegisterDescriptor regToSave in GetRegisters()) { if(regToSave.InIntegerRegisterFile) { if(he == Runtime.HardwareException.FastInterrupt && regToSave.Encoding >= EncodingDefinition.c_register_r8) { continue; } } else { // // Nothing special to do, save all the FP registers. // } if(cc.ShouldSaveRegister( regToSave ) == false && regToSave.IsSpecial == false ) { registersToSave.Set( (int)regToSave.Encoding ); } } if(HasRegisterContextArgument( md )) { fFullContext = true; } } if(md.HasBuildTimeFlag( MethodRepresentation.BuildTimeAttributes.SaveFullProcessorContext )) { fFullContext = true; } foreach(ZeligIR.Abstractions.RegisterDescriptor regToSave in this.GetRegisters()) { int pos = (int)regToSave.Encoding; if(fFullContext) { if(regToSave.IsSpecial) { continue; } } else { if(cc.ShouldSaveRegister( regToSave ) == false) { continue; } if(modifiedRegisters[pos] == false) { continue; } } registersToSave.Set( pos ); } ComputeRegisterFlushFixup( registersToSave ); } protected abstract void ComputeRegisterFlushFixup( BitVector registersToSave ); } } ================================================ FILE: Zelig/Zelig/CompileTime/TargetModels/ProductConfiguration/Abstractions/ARM/ArmPlatform_Handlers_ExpandAggregateTypes.cs.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // namespace Microsoft.Zelig.Configuration.Environment.Abstractions { using System; using System.Collections.Generic; using Microsoft.Zelig.Runtime.TypeSystem; using Microsoft.Zelig.TargetModel.ArmProcessor; using ZeligIR = Microsoft.Zelig.CodeGeneration.IR; public partial class ArmPlatform { [ZeligIR.CompilationSteps.PhaseFilter( typeof(ZeligIR.CompilationSteps.Phases.ExpandAggregateTypes) )] [ZeligIR.CompilationSteps.OperatorHandler( typeof(ARM.SetStatusRegisterOperator) )] private static void Handle_ARM_SetStatusRegisterOperator( ZeligIR.CompilationSteps.PhaseExecution.NotificationContext nc ) { ARM.SetStatusRegisterOperator op = (ARM.SetStatusRegisterOperator)nc.CurrentOperator; ZeligIR.TypeSystemForCodeTransformation ts = nc.TypeSystem; if(ts.OperatorAlreadyInScalarForm( op ) == false) { ZeligIR.ControlFlowGraphStateForCodeTransformation cfg = nc.CurrentCFG; ZeligIR.BasicBlock current = op.BasicBlock; Debugging.DebugInfo debugInfo = op.DebugInfo; ZeligIR.Expression exSrc = op.FirstArgument; ZeligIR.Expression[] srcFragments = cfg.GetFragmentsForExpression( exSrc ); CHECKS.ASSERT( exSrc.Type.SizeOfHoldingVariableInWords == 1, "Expecting a word-sized expression, got {0}", exSrc ); ARM.SetStatusRegisterOperator opNew = ARM.SetStatusRegisterOperator.New( debugInfo, op.UseSPSR, op.Fields, srcFragments[0] ); op.SubstituteWithOperator( opNew, ZeligIR.Operator.SubstitutionFlags.CopyAnnotations ); nc.MarkAsModified(); } } [ZeligIR.CompilationSteps.PhaseFilter( typeof(ZeligIR.CompilationSteps.Phases.ExpandAggregateTypes) )] [ZeligIR.CompilationSteps.OperatorHandler( typeof(ARM.GetStatusRegisterOperator) )] private static void Handle_ARM_GetStatusRegisterOperator( ZeligIR.CompilationSteps.PhaseExecution.NotificationContext nc ) { ARM.GetStatusRegisterOperator op = (ARM.GetStatusRegisterOperator)nc.CurrentOperator; ZeligIR.TypeSystemForCodeTransformation ts = nc.TypeSystem; if(ts.OperatorAlreadyInScalarForm( op ) == false) { ZeligIR.ControlFlowGraphStateForCodeTransformation cfg = nc.CurrentCFG; ZeligIR.BasicBlock current = op.BasicBlock; Debugging.DebugInfo debugInfo = op.DebugInfo; ZeligIR.VariableExpression exDst = op.FirstResult; ZeligIR.Expression[] dstFragments = cfg.GetFragmentsForExpression( exDst ); CHECKS.ASSERT( exDst.Type.SizeOfHoldingVariableInWords == 1, "Expecting a word-sized expression, got {0}", exDst ); ARM.GetStatusRegisterOperator opNew = ARM.GetStatusRegisterOperator.New( debugInfo, op.UseSPSR, (ZeligIR.VariableExpression)dstFragments[0] ); op.SubstituteWithOperator( opNew, ZeligIR.Operator.SubstitutionFlags.CopyAnnotations ); nc.MarkAsModified(); } } //--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--// //--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--// //--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--// [ZeligIR.CompilationSteps.PhaseFilter( typeof(ZeligIR.CompilationSteps.Phases.ExpandAggregateTypes) )] [ZeligIR.CompilationSteps.OperatorHandler( typeof(ARM.MoveToCoprocessor) )] private static void Handle_ARM_MoveToCoprocessor( ZeligIR.CompilationSteps.PhaseExecution.NotificationContext nc ) { ARM.MoveToCoprocessor op = (ARM.MoveToCoprocessor)nc.CurrentOperator; ZeligIR.TypeSystemForCodeTransformation ts = nc.TypeSystem; if(ts.OperatorAlreadyInScalarForm( op ) == false) { ZeligIR.ControlFlowGraphStateForCodeTransformation cfg = nc.CurrentCFG; ZeligIR.BasicBlock current = op.BasicBlock; Debugging.DebugInfo debugInfo = op.DebugInfo; ZeligIR.Expression exSrc = op.FirstArgument; ZeligIR.Expression[] srcFragments = cfg.GetFragmentsForExpression( exSrc ); CHECKS.ASSERT( exSrc.Type.SizeOfHoldingVariableInWords == 1, "Expecting a word-sized expression, got {0}", exSrc ); ARM.MoveToCoprocessor opNew = ARM.MoveToCoprocessor.New( debugInfo, op.CpNum, op.Op1, op.CRn, op.CRm, op.Op2, srcFragments[0] ); op.SubstituteWithOperator( opNew, ZeligIR.Operator.SubstitutionFlags.CopyAnnotations ); nc.MarkAsModified(); } } [ZeligIR.CompilationSteps.PhaseFilter( typeof(ZeligIR.CompilationSteps.Phases.ExpandAggregateTypes) )] [ZeligIR.CompilationSteps.OperatorHandler( typeof(ARM.MoveFromCoprocessor) )] private static void Handle_ARM_MoveFromCoprocessor( ZeligIR.CompilationSteps.PhaseExecution.NotificationContext nc ) { ARM.MoveFromCoprocessor op = (ARM.MoveFromCoprocessor)nc.CurrentOperator; ZeligIR.TypeSystemForCodeTransformation ts = nc.TypeSystem; if(ts.OperatorAlreadyInScalarForm( op ) == false) { ZeligIR.ControlFlowGraphStateForCodeTransformation cfg = nc.CurrentCFG; ZeligIR.BasicBlock current = op.BasicBlock; Debugging.DebugInfo debugInfo = op.DebugInfo; ZeligIR.VariableExpression exDst = op.FirstResult; ZeligIR.Expression[] dstFragments = cfg.GetFragmentsForExpression( exDst ); CHECKS.ASSERT( exDst.Type.SizeOfHoldingVariableInWords == 1, "Expecting a word-sized expression, got {0}", exDst ); ARM.MoveFromCoprocessor opNew = ARM.MoveFromCoprocessor.New( debugInfo, op.CpNum, op.Op1, op.CRn, op.CRm, op.Op2, (ZeligIR.VariableExpression)dstFragments[0] ); op.SubstituteWithOperator( opNew, ZeligIR.Operator.SubstitutionFlags.CopyAnnotations ); nc.MarkAsModified(); } } //--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--// //--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--// //--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--// [ZeligIR.CompilationSteps.PhaseFilter( typeof(ZeligIR.CompilationSteps.Phases.ExpandAggregateTypes) )] [ZeligIR.CompilationSteps.OperatorHandler( typeof(ARM.VectorHack_Finalize) )] private static void Handle_ARM_VectorHack_Finalize( ZeligIR.CompilationSteps.PhaseExecution.NotificationContext nc ) { ARM.VectorHack_Finalize op = (ARM.VectorHack_Finalize)nc.CurrentOperator; ZeligIR.TypeSystemForCodeTransformation ts = nc.TypeSystem; if(ts.OperatorAlreadyInScalarForm( op ) == false) { ZeligIR.ControlFlowGraphStateForCodeTransformation cfg = nc.CurrentCFG; ZeligIR.BasicBlock current = op.BasicBlock; Debugging.DebugInfo debugInfo = op.DebugInfo; ZeligIR.VariableExpression exDst = op.FirstResult; ZeligIR.Expression[] dstFragments = cfg.GetFragmentsForExpression( exDst ); CHECKS.ASSERT( exDst.Type.SizeOfHoldingVariableInWords == 1, "Expecting a word-sized expression, got {0}", exDst ); ARM.VectorHack_Finalize opNew = ARM.VectorHack_Finalize.New( debugInfo, op.Size, op.ResultBankBase, (ZeligIR.VariableExpression)dstFragments[0] ); op.SubstituteWithOperator( opNew, ZeligIR.Operator.SubstitutionFlags.CopyAnnotations ); nc.MarkAsModified(); } } [ZeligIR.CompilationSteps.PhaseFilter( typeof(ZeligIR.CompilationSteps.Phases.ExpandAggregateTypes) )] [ZeligIR.CompilationSteps.OperatorHandler( typeof(ARM.VectorHack_LoadData) )] private static void Handle_ARM_VectorHack_LoadData( ZeligIR.CompilationSteps.PhaseExecution.NotificationContext nc ) { ARM.VectorHack_LoadData op = (ARM.VectorHack_LoadData)nc.CurrentOperator; ZeligIR.TypeSystemForCodeTransformation ts = nc.TypeSystem; if(ts.OperatorAlreadyInScalarForm( op ) == false) { ZeligIR.ControlFlowGraphStateForCodeTransformation cfg = nc.CurrentCFG; ZeligIR.BasicBlock current = op.BasicBlock; Debugging.DebugInfo debugInfo = op.DebugInfo; ZeligIR.VariableExpression exDst = op.FirstResult; ZeligIR.Expression exSrc = op.FirstArgument; ZeligIR.Expression[] dstFragments = cfg.GetFragmentsForExpression( exDst ); ZeligIR.Expression[] srcFragments = cfg.GetFragmentsForExpression( exSrc ); CHECKS.ASSERT( exDst.Type.SizeOfHoldingVariableInWords == 1, "Expecting a word-sized expression, got {0}", exDst ); CHECKS.ASSERT( exSrc.Type.SizeOfHoldingVariableInWords == 1, "Expecting a word-sized expression, got {0}", exSrc ); ARM.VectorHack_LoadData opNew = ARM.VectorHack_LoadData.New( debugInfo, op.Size, op.DestinationBankBase, (ZeligIR.VariableExpression)dstFragments[0], srcFragments[0] ); op.SubstituteWithOperator( opNew, ZeligIR.Operator.SubstitutionFlags.CopyAnnotations ); nc.MarkAsModified(); } } } } ================================================ FILE: Zelig/Zelig/CompileTime/TargetModels/ProductConfiguration/Abstractions/ARM/ArmPlatform_Handlers_HighLevel.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // namespace Microsoft.Zelig.Configuration.Environment.Abstractions { using System; using System.Collections.Generic; using Microsoft.Zelig.Runtime.TypeSystem; using Microsoft.Zelig.TargetModel.ArmProcessor; using ZeligIR = Microsoft.Zelig.CodeGeneration.IR; public partial class ArmPlatform { [ZeligIR.CompilationSteps.PhaseFilter( typeof(ZeligIR.CompilationSteps.Phases.HighLevelTransformations) )] [ZeligIR.CompilationSteps.CallToWellKnownMethodHandler( "ProcessorARM_SetRegister" )] [ZeligIR.CompilationSteps.CallToWellKnownMethodHandler( "ProcessorARM_SetRegisterFP32" )] [ZeligIR.CompilationSteps.CallToWellKnownMethodHandler( "ProcessorARM_SetRegisterFP64" )] [ZeligIR.CompilationSteps.CallToWellKnownMethodHandler( "ProcessorARM_SetSystemRegister" )] private void Handle_ProcessorARM_SetRegister( ZeligIR.CompilationSteps.PhaseExecution.NotificationContext nc ) { ZeligIR.CallOperator op = nc.GetOperatorAndThrowIfNotCall(); ZeligIR.ControlFlowGraphStateForCodeTransformation cfg = nc.CurrentCFG; uint encoding = nc.ExtractConstantUIntParameter( op, 1 ); var regDesc = nc.TypeSystem.PlatformAbstraction.GetRegisterForEncoding( encoding ); if(regDesc == null) { // // We cannot fail, because code for different processors could be mixed in the same assembly and we don't know until later. // //// throw TypeConsistencyErrorException.Create( "Attempt to set non-existing register: {0}", encoding ); op.Delete(); } else { var opNew = ZeligIR.SingleAssignmentOperator.New( op.DebugInfo, cfg.AllocatePhysicalRegister( regDesc ), op.ThirdArgument ); op.SubstituteWithOperator( opNew, ZeligIR.Operator.SubstitutionFlags.Default ); opNew.AddAnnotation( ZeligIR.DontRemoveAnnotation.Create( nc.TypeSystem ) ); } nc.MarkAsModified(); } [ZeligIR.CompilationSteps.PhaseFilter( typeof(ZeligIR.CompilationSteps.Phases.HighLevelTransformations) )] [ZeligIR.CompilationSteps.CallToWellKnownMethodHandler( "ProcessorARM_GetRegister" )] [ZeligIR.CompilationSteps.CallToWellKnownMethodHandler( "ProcessorARM_GetRegisterFP32" )] [ZeligIR.CompilationSteps.CallToWellKnownMethodHandler( "ProcessorARM_GetRegisterFP64" )] [ZeligIR.CompilationSteps.CallToWellKnownMethodHandler( "ProcessorARM_GetSystemRegister" )] private void Handle_ProcessorARM_GetRegister( ZeligIR.CompilationSteps.PhaseExecution.NotificationContext nc ) { ZeligIR.CallOperator op = nc.GetOperatorAndThrowIfNotCall(); ZeligIR.ControlFlowGraphStateForCodeTransformation cfg = nc.CurrentCFG; uint encoding = nc.ExtractConstantUIntParameter( op, 1 ); var lhs = op.FirstResult; var regDesc = nc.TypeSystem.PlatformAbstraction.GetRegisterForEncoding( encoding ); if(regDesc == null) { // // We cannot fail, because code for different processors could be mixed in the same assembly and we don't know until later. // //// throw TypeConsistencyErrorException.Create( "Attempt to get non-existing register: {0}", encoding ); var opNew = ZeligIR.SingleAssignmentOperator.New( op.DebugInfo, lhs, nc.TypeSystem.CreateConstant( lhs.Type, 0 ) ); op.SubstituteWithOperator( opNew, ZeligIR.Operator.SubstitutionFlags.Default ); } else { var reg = cfg.AllocatePhysicalRegister( regDesc ); ZeligIR.Operator opNew; // // The PC processor reads 8 bytes past the current value, let's adjust it. // if(regDesc.Encoding == TargetModel.ArmProcessor.EncodingDefinition.c_register_pc) { opNew = ZeligIR.BinaryOperator.New( op.DebugInfo, ZeligIR.BinaryOperator.ALU.SUB, false, false, lhs, reg, nc.TypeSystem.CreateConstant( TargetModel.ArmProcessor.EncodingDefinition.c_PC_offset ) ); } else { opNew = ZeligIR.SingleAssignmentOperator.New( op.DebugInfo, lhs, reg ); } op.AddAnnotation( ZeligIR.PreInvalidationAnnotation.Create( nc.TypeSystem, reg ) ); op.SubstituteWithOperator( opNew, ZeligIR.Operator.SubstitutionFlags.Default ); } nc.MarkAsModified(); } //--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--// //--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--// //--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--// [ZeligIR.CompilationSteps.PhaseFilter( typeof(ZeligIR.CompilationSteps.Phases.HighLevelTransformations) )] [ZeligIR.CompilationSteps.CallToWellKnownMethodHandler( "ProcessorARM_SetStatusRegister" )] private void Handle_ProcessorARM_SetStatusRegister( ZeligIR.CompilationSteps.PhaseExecution.NotificationContext nc ) { Handle_ProcessorARM_SetStatusRegister( nc, false ); } [ZeligIR.CompilationSteps.PhaseFilter( typeof(ZeligIR.CompilationSteps.Phases.HighLevelTransformations) )] [ZeligIR.CompilationSteps.CallToWellKnownMethodHandler( "ProcessorARM_SetSavedStatusRegister" )] private void Handle_ProcessorARM_SetSavedStatusRegister( ZeligIR.CompilationSteps.PhaseExecution.NotificationContext nc ) { Handle_ProcessorARM_SetStatusRegister( nc, true ); } [ZeligIR.CompilationSteps.PhaseFilter( typeof(ZeligIR.CompilationSteps.Phases.HighLevelTransformations) )] [ZeligIR.CompilationSteps.CallToWellKnownMethodHandler( "ProcessorARM_GetStatusRegister" )] private void Handle_ProcessorARM_GetStatusRegister( ZeligIR.CompilationSteps.PhaseExecution.NotificationContext nc ) { Handle_ProcessorARM_GetStatusRegister( nc, false ); } [ZeligIR.CompilationSteps.PhaseFilter( typeof(ZeligIR.CompilationSteps.Phases.HighLevelTransformations) )] [ZeligIR.CompilationSteps.CallToWellKnownMethodHandler( "ProcessorARM_GetSavedStatusRegister" )] private void Handle_ProcessorARM_GetSavedStatusRegister( ZeligIR.CompilationSteps.PhaseExecution.NotificationContext nc ) { Handle_ProcessorARM_GetStatusRegister( nc, true ); } private void Handle_ProcessorARM_SetStatusRegister( ZeligIR.CompilationSteps.PhaseExecution.NotificationContext nc , bool fUseSPSR ) { ZeligIR.CallOperator op = nc.GetOperatorAndThrowIfNotCall(); ZeligIR.Expression exVal = op.ThirdArgument; uint fields = nc.ExtractConstantUIntParameter( op, 1 ); ZeligIR.Operator opNew = ARM.SetStatusRegisterOperator.New( op.DebugInfo, fUseSPSR, fields, exVal ); op.SubstituteWithOperator( opNew, ZeligIR.Operator.SubstitutionFlags.Default ); nc.MarkAsModified(); } private void Handle_ProcessorARM_GetStatusRegister( ZeligIR.CompilationSteps.PhaseExecution.NotificationContext nc , bool fUseSPSR ) { ZeligIR.CallOperator op = nc.GetOperatorAndThrowIfNotCall(); ZeligIR.Operator opNew = ARM.GetStatusRegisterOperator.New( op.DebugInfo, fUseSPSR, op.FirstResult ); op.SubstituteWithOperator( opNew, ZeligIR.Operator.SubstitutionFlags.Default ); nc.MarkAsModified(); } //--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--// //--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--// //--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--// [ZeligIR.CompilationSteps.PhaseFilter( typeof(ZeligIR.CompilationSteps.Phases.HighLevelTransformations) )] [ZeligIR.CompilationSteps.CallToWellKnownMethodHandler( "ProcessorARM_MoveToCoprocessor" )] private void Handle_ProcessorARM_MoveToCoprocessor( ZeligIR.CompilationSteps.PhaseExecution.NotificationContext nc ) { ZeligIR.CallOperator op = nc.GetOperatorAndThrowIfNotCall(); uint CpNum = nc.ExtractConstantUIntParameter( op, 1 ); uint Op1 = nc.ExtractConstantUIntParameter( op, 2 ); uint CRn = nc.ExtractConstantUIntParameter( op, 3 ); uint CRm = nc.ExtractConstantUIntParameter( op, 4 ); uint Op2 = nc.ExtractConstantUIntParameter( op, 5 ); ZeligIR.Operator opNew = ARM.MoveToCoprocessor.New( op.DebugInfo, CpNum, Op1, CRn, CRm, Op2, op.Arguments[6] ); op.SubstituteWithOperator( opNew, ZeligIR.Operator.SubstitutionFlags.Default ); nc.MarkAsModified(); } [ZeligIR.CompilationSteps.PhaseFilter( typeof(ZeligIR.CompilationSteps.Phases.HighLevelTransformations) )] [ZeligIR.CompilationSteps.CallToWellKnownMethodHandler( "ProcessorARM_MoveFromCoprocessor" )] private void Handle_ProcessorARM_MoveFromCoprocessor( ZeligIR.CompilationSteps.PhaseExecution.NotificationContext nc ) { ZeligIR.CallOperator op = nc.GetOperatorAndThrowIfNotCall(); uint CpNum = nc.ExtractConstantUIntParameter( op, 1 ); uint Op1 = nc.ExtractConstantUIntParameter( op, 2 ); uint CRn = nc.ExtractConstantUIntParameter( op, 3 ); uint CRm = nc.ExtractConstantUIntParameter( op, 4 ); uint Op2 = nc.ExtractConstantUIntParameter( op, 5 ); ZeligIR.Operator opNew = ARM.MoveFromCoprocessor.New( op.DebugInfo, CpNum, Op1, CRn, CRm, Op2, op.FirstResult ); op.SubstituteWithOperator( opNew, ZeligIR.Operator.SubstitutionFlags.Default ); nc.MarkAsModified(); } [ZeligIR.CompilationSteps.PhaseFilter( typeof(ZeligIR.CompilationSteps.Phases.HighLevelTransformations) )] [ZeligIR.CompilationSteps.CallToWellKnownMethodHandler( "ProcessorARM_Breakpoint" )] //////[ZeligIR.CompilationSteps.CallToWellKnownMethodHandler( "ProcessorARMv6_Breakpoint" )] //////[ZeligIR.CompilationSteps.CallToWellKnownMethodHandler( "ProcessorARMv7_Breakpoint" )] private void Handle_ProcessorARM_Breakpoint( ZeligIR.CompilationSteps.PhaseExecution.NotificationContext nc ) { ZeligIR.CallOperator op = nc.GetOperatorAndThrowIfNotCall(); uint Value = nc.ExtractConstantUIntParameter( op, 1 ); ZeligIR.Operator opNew = ARM.BreakpointOperator.New( op.DebugInfo, Value ); op.SubstituteWithOperator( opNew, ZeligIR.Operator.SubstitutionFlags.Default ); nc.MarkAsModified(); } //--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--// //--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--// //--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--// [ZeligIR.CompilationSteps.PhaseFilter( typeof(ZeligIR.CompilationSteps.Phases.HighLevelTransformations) )] [ZeligIR.CompilationSteps.CallToWellKnownMethodHandler( "Microsoft_Zelig_ProcessorARMv4_MethodWrapperHelpers_ScratchedRegisters" )] private void Handle_ProcessorARM_MethodWrapperHelpers_ScratchedRegisters( ZeligIR.CompilationSteps.PhaseExecution.NotificationContext nc ) { ZeligIR.CallOperator op = nc.GetOperatorAndThrowIfNotCall(); var cc = nc.TypeSystem.CallingConvention; var pa = nc.TypeSystem.PlatformAbstraction; uint mask = 0; foreach(var reg in pa.GetRegisters()) { if(reg.InIntegerRegisterFile && cc.ShouldSaveRegister( reg ) == false) { mask |= 1u << (int)(reg.Encoding - EncodingDefinition.c_register_r0); } } var opNew = ZeligIR.SingleAssignmentOperator.New( op.DebugInfo, op.FirstResult, nc.TypeSystem.CreateConstant( mask ) ); op.SubstituteWithOperator( opNew, ZeligIR.Operator.SubstitutionFlags.Default ); nc.MarkAsModified(); } [ZeligIR.CompilationSteps.PhaseFilter( typeof(ZeligIR.CompilationSteps.Phases.HighLevelTransformations) )] [ZeligIR.CompilationSteps.CallToWellKnownMethodHandler( "Microsoft_Zelig_ProcessorARMv4_MethodWrapperHelpers_PushRegisters" )] private void Handle_ProcessorARM_MethodWrapperHelpers_PushRegisters( ZeligIR.CompilationSteps.PhaseExecution.NotificationContext nc ) { ZeligIR.CallOperator op = nc.GetOperatorAndThrowIfNotCall(); if(nc.IsParameterConstant( op, 1 ) && nc.IsParameterConstant( op, 2 ) && nc.IsParameterConstant( op, 3 ) && nc.IsParameterConstant( op, 4 ) ) { uint indexRegister = nc.ExtractConstantUIntParameter( op, 1 ); bool fWriteBackIndexRegister = nc.ExtractConstantBoolParameter( op, 2 ); bool fAddComputedRegisters = nc.ExtractConstantBoolParameter( op, 3 ); uint registerMask = nc.ExtractConstantUIntParameter( op, 4 ); var exReg = nc.GetVariableForRegisterEncoding( indexRegister ); var opNew = ARM.MoveIntegerRegistersOperator.New( op.DebugInfo, false, fWriteBackIndexRegister, fAddComputedRegisters, false, registerMask, exReg ); opNew.AddAnnotation( ZeligIR.PreInvalidationAnnotation.Create( nc.TypeSystem, exReg ) ); op.SubstituteWithOperator( opNew, ZeligIR.Operator.SubstitutionFlags.Default ); nc.MarkAsModified(); } } [ZeligIR.CompilationSteps.PhaseFilter( typeof(ZeligIR.CompilationSteps.Phases.HighLevelTransformations) )] [ZeligIR.CompilationSteps.CallToWellKnownMethodHandler( "Microsoft_Zelig_ProcessorARMv4_MethodWrapperHelpers_PopRegisters" )] [ZeligIR.CompilationSteps.CallToWellKnownMethodHandler( "Microsoft_Zelig_ProcessorARMv7_MethodWrapperHelpers_PopRegisters" )] private void Handle_ProcessorARM_MethodWrapperHelpers_PopRegisters( ZeligIR.CompilationSteps.PhaseExecution.NotificationContext nc ) { ZeligIR.CallOperator op = nc.GetOperatorAndThrowIfNotCall(); if(nc.IsParameterConstant( op, 1 ) && nc.IsParameterConstant( op, 2 ) && nc.IsParameterConstant( op, 3 ) && nc.IsParameterConstant( op, 4 ) && nc.IsParameterConstant( op, 5 ) ) { uint indexRegister = nc.ExtractConstantUIntParameter( op, 1 ); bool fWriteBackIndexRegister = nc.ExtractConstantBoolParameter( op, 2 ); bool fAddComputedRegisters = nc.ExtractConstantBoolParameter( op, 3 ); bool fRestoreSPSR = nc.ExtractConstantBoolParameter( op, 4 ); uint registerMask = nc.ExtractConstantUIntParameter( op, 5 ); var exReg = nc.GetVariableForRegisterEncoding( indexRegister ); var opNew = ARM.MoveIntegerRegistersOperator.New( op.DebugInfo, true, fWriteBackIndexRegister, fAddComputedRegisters, fRestoreSPSR, registerMask, exReg ); opNew.AddAnnotation( ZeligIR.PreInvalidationAnnotation.Create( nc.TypeSystem, exReg ) ); op.SubstituteWithOperator( opNew, ZeligIR.Operator.SubstitutionFlags.Default ); nc.MarkAsModified(); } } [ZeligIR.CompilationSteps.PhaseFilter( typeof(ZeligIR.CompilationSteps.Phases.HighLevelTransformations) )] [ZeligIR.CompilationSteps.CallToWellKnownMethodHandler( "Microsoft_Zelig_ProcessorARMv5_VFP_MethodWrapperHelpers_PushFpRegisters" )] [ZeligIR.CompilationSteps.CallToWellKnownMethodHandler( "Microsoft_Zelig_ProcessorARMv7_VFP_MethodWrapperHelpers_PushFpRegisters" )] private void Handle_ProcessorARM_MethodWrapperHelpers_PushFpRegisters( ZeligIR.CompilationSteps.PhaseExecution.NotificationContext nc ) { Handle_ProcessorARM_MethodWrapperHelpers_MoveFpRegisters( nc, false ); } [ZeligIR.CompilationSteps.PhaseFilter( typeof(ZeligIR.CompilationSteps.Phases.HighLevelTransformations) )] [ZeligIR.CompilationSteps.CallToWellKnownMethodHandler( "Microsoft_Zelig_ProcessorARMv5_VFP_MethodWrapperHelpers_PopFpRegisters" )] [ZeligIR.CompilationSteps.CallToWellKnownMethodHandler( "Microsoft_Zelig_ProcessorARMv7_VFP_MethodWrapperHelpers_PopFpRegisters" )] private void Handle_ProcessorARM_MethodWrapperHelpers_PopFpRegisters( ZeligIR.CompilationSteps.PhaseExecution.NotificationContext nc ) { Handle_ProcessorARM_MethodWrapperHelpers_MoveFpRegisters( nc, true ); } private void Handle_ProcessorARM_MethodWrapperHelpers_MoveFpRegisters( ZeligIR.CompilationSteps.PhaseExecution.NotificationContext nc , bool fLoad ) { ZeligIR.CallOperator op = nc.GetOperatorAndThrowIfNotCall(); if(nc.IsParameterConstant( op, 1 ) && nc.IsParameterConstant( op, 2 ) && nc.IsParameterConstant( op, 3 ) && nc.IsParameterConstant( op, 4 ) && nc.IsParameterConstant( op, 5 ) ) { uint indexRegister = nc.ExtractConstantUIntParameter( op, 1 ); bool fWriteBackIndexRegister = nc.ExtractConstantBoolParameter( op, 2 ); bool fAddComputedRegisters = nc.ExtractConstantBoolParameter( op, 3 ); uint registerLow = nc.ExtractConstantUIntParameter( op, 4 ); uint registerHigh = nc.ExtractConstantUIntParameter( op, 5 ); var exReg = nc.GetVariableForRegisterEncoding( indexRegister ); var opNew = ARM.MoveFloatingPointRegistersOperator.New( op.DebugInfo, fLoad, fWriteBackIndexRegister, fAddComputedRegisters, registerLow, registerHigh, exReg ); opNew.AddAnnotation( ZeligIR.PreInvalidationAnnotation.Create( nc.TypeSystem, exReg ) ); op.SubstituteWithOperator( opNew, ZeligIR.Operator.SubstitutionFlags.Default ); nc.MarkAsModified(); } } [ZeligIR.CompilationSteps.PhaseFilter( typeof(ZeligIR.CompilationSteps.Phases.HighLevelTransformations) )] [ZeligIR.CompilationSteps.CallToWellKnownMethodHandler( "Microsoft_Zelig_ProcessorARMv4_MethodWrapperHelpers_PushStackFrame" )] private void Handle_ProcessorARM_MethodWrapperHelpers_PushStackFrame( ZeligIR.CompilationSteps.PhaseExecution.NotificationContext nc ) { Handle_ProcessorARM_MethodWrapperHelpers_MoveStackFrame( nc, true ); } [ZeligIR.CompilationSteps.PhaseFilter( typeof(ZeligIR.CompilationSteps.Phases.HighLevelTransformations) )] [ZeligIR.CompilationSteps.CallToWellKnownMethodHandler( "Microsoft_Zelig_ProcessorARMv4_MethodWrapperHelpers_PopStackFrame" )] private void Handle_ProcessorARM_MethodWrapperHelpers_PopStackFrame( ZeligIR.CompilationSteps.PhaseExecution.NotificationContext nc ) { Handle_ProcessorARM_MethodWrapperHelpers_MoveStackFrame( nc, false ); } private void Handle_ProcessorARM_MethodWrapperHelpers_MoveStackFrame( ZeligIR.CompilationSteps.PhaseExecution.NotificationContext nc , bool fPush ) { ZeligIR.CallOperator op = nc.GetOperatorAndThrowIfNotCall(); var opNew = ARM.MoveStackPointerOperator.New( op.DebugInfo, fPush ); op.SubstituteWithOperator( opNew, ZeligIR.Operator.SubstitutionFlags.Default ); nc.MarkAsModified(); } //--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--// //--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--// //--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--// [ZeligIR.CompilationSteps.PhaseFilter( typeof(ZeligIR.CompilationSteps.Phases.HighLevelTransformations) )] [ZeligIR.CompilationSteps.CallToWellKnownMethodHandler( "Solo_DSP_MatrixMultiply__MultiplyAndAccumulate" )] private void Handle_Solo_DSP_MatrixMultiply__MultiplyAndAccumulate( ZeligIR.CompilationSteps.PhaseExecution.NotificationContext nc ) { ZeligIR.CallOperator op = nc.GetOperatorAndThrowIfNotCall(); ZeligIR.ControlFlowGraphStateForCodeTransformation cfg = nc.CurrentCFG; ZeligIR.TypeSystemForCodeTransformation ts = nc.TypeSystem; ZeligIR.VariableExpression varRes = op.FirstResult; ZeligIR.Expression exAbase = op.SecondArgument; ZeligIR.Expression exBbase = op.ThirdArgument; ZeligIR.Expression exN = op.FourthArgument; int vectorSize = nc.ExtractConstantIntParameter( op, 4 ); if(vectorSize < 1 || vectorSize > 8) { throw TypeConsistencyErrorException.Create( "Invalid vector size for {0}: {1}", op, vectorSize ); } //--// var wkt = ts.WellKnownTypes; var tdValue = varRes.Type; var tdPtr = ts.CreateUnmanagedPointerToType( tdValue ); CHECKS.ASSERT( tdValue == wkt.System_Single, "Invalid result type, expecting 'float', got '{0}'", tdValue ); var debugInfo = op.DebugInfo; var pa = ts.PlatformAbstraction; ZeligIR.NormalBasicBlock bbEntry = new ZeligIR.NormalBasicBlock( cfg ); ZeligIR.NormalBasicBlock bbExit = new ZeligIR.NormalBasicBlock( cfg ); ZeligIR.NormalBasicBlock bbLoopHeader = new ZeligIR.NormalBasicBlock( cfg ); ZeligIR.NormalBasicBlock bbLoopBody = new ZeligIR.NormalBasicBlock( cfg ); ZeligIR.VariableExpression varAptr = cfg.AllocateTypedPhysicalRegister( tdPtr, pa.GetRegisterForEncoding( TargetModel.ArmProcessor.EncodingDefinition.c_register_r4 ), null, null, 0 ); ZeligIR.VariableExpression varBptr = cfg.AllocateTypedPhysicalRegister( tdPtr, pa.GetRegisterForEncoding( TargetModel.ArmProcessor.EncodingDefinition.c_register_r5 ), null, null, 0 ); ZeligIR.VariableExpression varAend = cfg.AllocateTypedPhysicalRegister( tdPtr, pa.GetRegisterForEncoding( TargetModel.ArmProcessor.EncodingDefinition.c_register_r6 ), null, null, 0 ); ZeligIR.VariableExpression varSize = cfg.AllocateTemporary ( wkt.System_Int32, null ); var regsLeftBankBase = GenerateVector( cfg, pa, vectorSize, TargetModel.ArmProcessor.EncodingDefinition_VFP.c_register_s8 ); var regsRightBankBase = GenerateVector( cfg, pa, vectorSize, TargetModel.ArmProcessor.EncodingDefinition_VFP.c_register_s16 ); var regsResultBankBase = GenerateVector( cfg, pa, vectorSize, TargetModel.ArmProcessor.EncodingDefinition_VFP.c_register_s24 ); //--// // // Entry: // float* Aptr = Abase; // float* Bptr = Bbase; // float* Aend = &Aptr[N]; // // // // // goto LoopHeader; // { var vecOp1 = ARM.VectorHack_Prepare.New( debugInfo, vectorSize, regsResultBankBase[0].RegisterDescriptor ); bbEntry.AddOperator( ZeligIR.SingleAssignmentOperator.New( debugInfo, varAptr, exAbase ) ); bbEntry.AddOperator( ZeligIR.SingleAssignmentOperator.New( debugInfo, varBptr, exBbase ) ); bbEntry.AddOperator( ZeligIR.BinaryOperator.New( debugInfo, ZeligIR.BinaryOperator.ALU.MUL, false, false, varSize, exN, ts.CreateConstant( (int)tdValue.SizeOfHoldingVariable ) ) ); bbEntry.AddOperator( ZeligIR.BinaryOperator.New( debugInfo, ZeligIR.BinaryOperator.ALU.ADD, false, false, varAend, varAptr, varSize ) ); bbEntry.AddOperator( ARM.VectorHack_Initialize.New( debugInfo, vectorSize ) ); bbEntry.AddOperator( vecOp1 ); AddSideEffects( ts, vecOp1, regsResultBankBase ); bbEntry.FlowControl = ZeligIR.UnconditionalControlOperator.New( debugInfo, bbLoopHeader ); } //--// // // LoopHeader: // if Aptr < Aend goto LoopBody else goto Exit; // { bbLoopHeader.FlowControl = ZeligIR.CompareConditionalControlOperator.New( debugInfo, ZeligIR.CompareAndSetOperator.ActionCondition.LT, false, varAptr, varAend, bbExit, bbLoopBody ); } //--// // // LoopBody: // // // // // goto LoopHeader; // { var vecOp1 = ARM.VectorHack_LoadData .New( debugInfo, vectorSize, regsLeftBankBase [0].RegisterDescriptor, varAptr, varAptr ); var vecOp2 = ARM.VectorHack_LoadData .New( debugInfo, vectorSize, regsRightBankBase[0].RegisterDescriptor, varBptr, varBptr ); var vecOp3 = ARM.VectorHack_MultiplyAndAccumulate.New( debugInfo, vectorSize, regsLeftBankBase [0].RegisterDescriptor, regsRightBankBase[0].RegisterDescriptor, regsResultBankBase[0].RegisterDescriptor ); bbLoopBody.AddOperator( vecOp1 ); AddSideEffects( ts, vecOp1, regsLeftBankBase ); bbLoopBody.AddOperator( vecOp2 ); AddSideEffects( ts, vecOp2, regsRightBankBase ); bbLoopBody.AddOperator( vecOp3 ); AddSideEffects( ts, vecOp3, regsLeftBankBase ); AddSideEffects( ts, vecOp3, regsRightBankBase ); AddSideEffects( ts, vecOp3, regsResultBankBase ); bbLoopBody.FlowControl = ZeligIR.UnconditionalControlOperator.New( debugInfo, bbLoopHeader ); } // // Exit: // // // { var vecOp1 = ARM.VectorHack_Finalize.New( debugInfo, vectorSize, regsResultBankBase[0].RegisterDescriptor, varRes ); bbExit.AddOperator( ARM.VectorHack_Cleanup.New( debugInfo, vectorSize ) ); bbExit.AddOperator( vecOp1 ); AddSideEffects( ts, vecOp1, regsResultBankBase ); } //--// op.SubstituteWithSubGraph( bbEntry, bbExit ); nc.MarkAsModified(); } private ZeligIR.PhysicalRegisterExpression[] GenerateVector( ZeligIR.ControlFlowGraphStateForCodeTransformation cfg , ZeligIR.Abstractions.Platform pa , int vectorSize , uint encoding ) { var res = new ZeligIR.PhysicalRegisterExpression[vectorSize]; for(int i = 0; i < vectorSize; i++) { res[i] = cfg.AllocatePhysicalRegister( pa.GetRegisterForEncoding( encoding++ ) ); } return res; } private void AddSideEffects( ZeligIR.TypeSystemForCodeTransformation ts , ZeligIR.Operator op , ZeligIR.PhysicalRegisterExpression[] regs ) { foreach(var reg in regs) { op.AddAnnotation( ZeligIR.PostInvalidationAnnotation.Create( ts, reg ) ); } } } } ================================================ FILE: Zelig/Zelig/CompileTime/TargetModels/ProductConfiguration/Abstractions/ARM/ArmPlatform_OperatorConstraints.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // //#define ENABLE_LOW_LEVEL_OPTIMIZATIONS namespace Microsoft.Zelig.Configuration.Environment.Abstractions { using System; using System.Collections.Generic; using Microsoft.Zelig.Runtime.TypeSystem; using Microsoft.Zelig.TargetModel.ArmProcessor; using ZeligIR = Microsoft.Zelig.CodeGeneration.IR; public partial class ArmPlatform { // // Helper Methods // protected override bool CanFitTypeInPhysicalRegister( TypeRepresentation td ) { if(td.ValidLayout) { if(td.IsFloatingPoint) { if(this.HasVFPv2) { return true; } } if(td.SizeOfHoldingVariable <= sizeof(uint)) { return true; } } return false; } public override bool CanPropagateCopy( ZeligIR.SingleAssignmentOperator opSrc , ZeligIR.Operator opDst , int exIndexInDst , ZeligIR.VariableExpression[] variables , BitVector[] variableUses , BitVector[] variableDefinitions , ZeligIR.Operator[] operators ) { ZeligIR.Expression exSrc = opSrc.FirstArgument; // // Don't propagate system registers. // { ZeligIR.PhysicalRegisterExpression regSrc = ZeligIR.PhysicalRegisterExpression.Extract( exSrc ); if(regSrc != null && regSrc.RegisterDescriptor.IsSystemRegister) { return false; } if(opDst is ZeligIR.SingleAssignmentOperator) { ZeligIR.PhysicalRegisterExpression regDst = ZeligIR.PhysicalRegisterExpression.Extract( opDst.FirstResult ); if(regDst != null && regDst.RegisterDescriptor.IsSystemRegister) { return false; } } } //--// ZeligIR.Abstractions.RegisterClass constraintDst = ZeligIR.RegisterAllocationConstraintAnnotation.ComputeConstraintsForRHS( opDst, exIndexInDst ); if(constraintDst != ZeligIR.Abstractions.RegisterClass.None) { // // The destination expression is constrained, make sure all the definitions of the source expression are compatible. // ZeligIR.Abstractions.RegisterClass constraintSrc = ZeligIR.Abstractions.RegisterClass.None; foreach(int def in variableDefinitions[exSrc.SpanningTreeIndex]) { constraintSrc |= ZeligIR.RegisterAllocationConstraintAnnotation.ComputeConstraintsForLHS( operators[def], (ZeligIR.VariableExpression)exSrc ); } if((constraintSrc & constraintDst) != constraintDst) { // // Source is less constrained than the destination, we cannot propagate the expression. // return false; } } return true; } #if ENABLE_LOW_LEVEL_OPTIMIZATIONS [ZeligIR.CompilationSteps.OptimizationHandler(RunOnce=false, RunInSSAForm=true)] #endif // ENABLE_LOW_LEVEL_OPTIMIZATIONS private static void RemoveConstantFromIndirectOperators( ZeligIR.CompilationSteps.PhaseExecution.NotificationContext nc ) { ZeligIR.ControlFlowGraphStateForCodeTransformation cfg = nc.CurrentCFG; foreach(var opInd in cfg.FilterOperators< ZeligIR.IndirectOperator >()) { var debugInfo = opInd.DebugInfo; var rhs = opInd.FirstArgument as ZeligIR.ConstantExpression; if(rhs != null) { var tmp = cfg.AllocatePseudoRegister( rhs.Type ); opInd.AddOperatorBefore( ZeligIR.SingleAssignmentOperator.New( debugInfo, tmp, rhs ) ); opInd.SubstituteUsage( rhs, tmp ); opInd.AddAnnotation( ZeligIR.BlockCopyPropagationAnnotation.Create( nc.TypeSystem, 0, false, false ) ); } } } } } ================================================ FILE: Zelig/Zelig/CompileTime/TargetModels/ProductConfiguration/Abstractions/ARM/ArmPlatform_Optimizations.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // //#define ENABLE_LOW_LEVEL_OPTIMIZATIONS namespace Microsoft.Zelig.Configuration.Environment.Abstractions { using System; using System.Collections.Generic; using Microsoft.Zelig.Runtime.TypeSystem; using Microsoft.Zelig.TargetModel.ArmProcessor; using ZeligIR = Microsoft.Zelig.CodeGeneration.IR; public partial class ArmPlatform { // // Helper Methods // #if ENABLE_LOW_LEVEL_OPTIMIZATIONS [ZeligIR.CompilationSteps.OptimizationHandler(RunOnce=false, RunInSSAForm=true)] #endif // ENABLE_LOW_LEVEL_OPTIMIZATIONS private static void InferBitMaskConditionals( ZeligIR.CompilationSteps.PhaseExecution.NotificationContext nc ) { ZeligIR.ControlFlowGraphStateForCodeTransformation cfg = nc.CurrentCFG; foreach(var opCtrl in cfg.FilterOperators< ZeligIR.ConditionCodeConditionalControlOperator >()) { ZeligIR.CompareOperator opCmp = cfg.FindSingleDefinition( opCtrl.FirstArgument ) as ZeligIR.CompareOperator; if(opCmp != null) { bool fNullOnRight; ZeligIR.Expression ex = opCmp.IsBinaryOperationAgainstZeroValue( out fNullOnRight ); if(ex != null) { ZeligIR.BinaryOperator opDef = cfg.FindSingleDefinition( ex ) as ZeligIR.BinaryOperator; if(opDef != null) { switch(opDef.Alu) { case ZeligIR.BinaryOperator.ALU.AND: // // Found code pattern: // // t1 = A and B // cc = compare t1 <-> 0 // if cc equal/not equal, then branch B1 else branch B2 // // Substitute with: // // cc = bittest A and B // if cc equal/not equal, then branch B1 else branch B2 // opCmp.SubstituteWithOperator( ZeligIR.BitTestOperator.New( opCmp.DebugInfo, opCmp.FirstResult, opDef.FirstArgument, opDef.SecondArgument ), ZeligIR.Operator.SubstitutionFlags.CopyAnnotations ); break; case ZeligIR.BinaryOperator.ALU.SHR: { ZeligIR.ConstantExpression exRightShift = opDef.SecondArgument as ZeligIR.ConstantExpression; if(exRightShift != null && opDef.Signed == false) { ZeligIR.BinaryOperator opDef2 = cfg.FindSingleDefinition( opDef.FirstArgument ) as ZeligIR.BinaryOperator; if(opDef2 != null && opDef2.Alu == ZeligIR.BinaryOperator.ALU.SHL) { ZeligIR.ConstantExpression exLeftShift = opDef2.SecondArgument as ZeligIR.ConstantExpression; if(exLeftShift != null) { // // Found code pattern: // // t1 = A << X // t2 = t1 >> Y // cc = compare t2 <-> 0 // if cc equal/not equal, then branch B1 else branch B2 // // Substitute with: // // cc = bittest A and // if cc equal/not equal, then branch B1 else branch B2 // ulong leftShift; ulong rightShift; if(exLeftShift .GetAsUnsignedInteger( out leftShift ) && exRightShift.GetAsUnsignedInteger( out rightShift ) ) { int maskSize = (int)(32 - rightShift); if(maskSize <= 8) // Only optimize bit tests that can fit in the immediate encoding of the TST instruction. { uint mask = ((1u << maskSize) - 1u) << (int)(32 - ((int)leftShift + maskSize)); opCmp.SubstituteWithOperator( ZeligIR.BitTestOperator.New( opCmp.DebugInfo, opCmp.FirstResult, opDef2.FirstArgument, cfg.TypeSystem.CreateConstant( mask ) ), ZeligIR.Operator.SubstitutionFlags.CopyAnnotations ); } } } } else { // // Found code pattern: // // t1 = A >> Y // cc = compare t1 <-> 0 // if cc equal/not equal, then branch B1 else branch B2 // // Substitute with: // // cc = bittest A and // if cc equal/not equal, then branch B1 else branch B2 // ulong rightShift; if(exRightShift.GetAsUnsignedInteger( out rightShift )) { int maskSize = (int)(32 - rightShift); if(maskSize <= 8) // Only optimize bit tests that can fit in the immediate encoding of the TST instruction. { uint mask = ((1u << maskSize) - 1u) << (int)(32 - maskSize); opCmp.SubstituteWithOperator( ZeligIR.BitTestOperator.New( opCmp.DebugInfo, opCmp.FirstResult, opDef.FirstArgument, cfg.TypeSystem.CreateConstant( mask ) ), ZeligIR.Operator.SubstitutionFlags.CopyAnnotations ); } } } } } break; } } } } } } } } ================================================ FILE: Zelig/Zelig/CompileTime/TargetModels/ProductConfiguration/Abstractions/ARM/ArmPlatform_PrepareForRegisterAllocation.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // namespace Microsoft.Zelig.Configuration.Environment.Abstractions { using Microsoft.Zelig.TargetModel.ArmProcessor; using ZeligIR = Microsoft.Zelig.CodeGeneration.IR; public partial class ArmPlatform { private static EncodingDefinition_ARM s_Encoding = (EncodingDefinition_ARM)CurrentInstructionSetEncoding.GetEncoding(); //--// class PrepareForRegisterAllocation { // // State // ArmPlatform m_owner; // // Constructor Methods // internal PrepareForRegisterAllocation( ArmPlatform owner ) { m_owner = owner; } // // Helper Methods // //--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--// //--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--// //--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--// [ZeligIR.CompilationSteps.PhaseFilter( typeof(ZeligIR.CompilationSteps.Phases.PrepareForRegisterAllocation) )] [ZeligIR.CompilationSteps.OperatorHandler( typeof(ZeligIR.LoadIndirectOperator ) )] [ZeligIR.CompilationSteps.OperatorHandler( typeof(ZeligIR.StoreIndirectOperator ) )] [ZeligIR.CompilationSteps.OperatorHandler( typeof(ZeligIR.SetIfConditionIsTrueOperator ) )] [ZeligIR.CompilationSteps.OperatorHandler( typeof(ZeligIR.ConditionalCompareOperator ) )] [ZeligIR.CompilationSteps.OperatorHandler( typeof(ZeligIR.AddressAssignmentOperator ) )] [ZeligIR.CompilationSteps.OperatorHandler( typeof(ZeligIR.AbstractUnaryOperator ) )] [ZeligIR.CompilationSteps.OperatorHandler( typeof(ZeligIR.ConversionOperator ) )] [ZeligIR.CompilationSteps.OperatorHandler( typeof(ZeligIR.MultiWayConditionalControlOperator) )] [ZeligIR.CompilationSteps.OperatorHandler( typeof(ARM.MoveToCoprocessor ) )] [ZeligIR.CompilationSteps.OperatorHandler( typeof(ARM.MoveFromCoprocessor ) )] [ZeligIR.CompilationSteps.OperatorHandler( typeof(ARM.SetStatusRegisterOperator ) )] [ZeligIR.CompilationSteps.OperatorHandler( typeof(ARM.LoadIndirectOperatorWithIndexUpdate ) )] [ZeligIR.CompilationSteps.OperatorHandler( typeof(ARM.StoreIndirectOperatorWithIndexUpdate ) )] private void Handle_GenericOperator( ZeligIR.CompilationSteps.PhaseExecution.NotificationContext nc ) { var op = nc.CurrentOperator; var cfg = nc.CurrentCFG; if(ConvertToPseudoRegister( cfg, op )) { nc.MarkAsModified(); return; } } [ZeligIR.CompilationSteps.PhaseFilter( typeof(ZeligIR.CompilationSteps.Phases.PrepareForRegisterAllocation) )] [ZeligIR.CompilationSteps.OperatorHandler( typeof(ZeligIR.SingleAssignmentOperator) )] private void Handle_AssignmentOperator( ZeligIR.CompilationSteps.PhaseExecution.NotificationContext nc ) { var op = (ZeligIR.SingleAssignmentOperator)nc.CurrentOperator; var lhs = op.FirstResult; var rhs = op.FirstArgument; var ts = nc.TypeSystem; if(ts.GetLevel( lhs ) == ZeligIR.Operator.OperatorLevel.StackLocations) { if(rhs is ZeligIR.ConstantExpression || ts.GetLevel( rhs ) == ZeligIR.Operator.OperatorLevel.StackLocations) { // // Constant to stack or stack to stack is not allowed. // if(ConvertToPseudoRegister( nc.CurrentCFG, op )) { nc.MarkAsModified(); return; } } } var lhsRegDesc = ZeligIR.Abstractions.RegisterDescriptor.ExtractFromExpression( lhs ); if(lhsRegDesc != null && lhsRegDesc.IsSystemRegister) { if(rhs is ZeligIR.ConstantExpression || ts.GetLevel( rhs ) == ZeligIR.Operator.OperatorLevel.StackLocations) { // // Constant or stack to system register is not allowed. // MoveToPseudoRegister( nc.CurrentCFG, op, rhs ); nc.MarkAsModified(); return; } } } [ZeligIR.CompilationSteps.PhaseFilter( typeof(ZeligIR.CompilationSteps.Phases.PrepareForRegisterAllocation) )] [ZeligIR.CompilationSteps.OperatorHandler( typeof(ZeligIR.CompareOperator ) )] [ZeligIR.CompilationSteps.OperatorHandler( typeof(ZeligIR.BitTestOperator ) )] [ZeligIR.CompilationSteps.OperatorHandler( typeof(ZeligIR.ConditionalCompareOperator) )] private void Handle_GenericDataProcessingOperator( ZeligIR.CompilationSteps.PhaseExecution.NotificationContext nc ) { var op = nc.CurrentOperator; if(ConvertToPseudoRegister( nc.CurrentCFG, op )) { nc.MarkAsModified(); return; } foreach(ZeligIR.Expression ex in op.Arguments) { ZeligIR.ConstantExpression exConst = ex as ZeligIR.ConstantExpression; if(exConst != null) { if(CanBeUsedAsAnImmediateValue( nc, exConst ) == false) { MoveToPseudoRegister( nc.CurrentCFG, op, exConst ); nc.MarkAsModified(); break; } } } } [ZeligIR.CompilationSteps.PhaseFilter( typeof(ZeligIR.CompilationSteps.Phases.PrepareForRegisterAllocation) )] [ZeligIR.CompilationSteps.OperatorHandler( typeof(ZeligIR.AbstractBinaryOperator) )] private void Handle_AbstractBinaryOperator( ZeligIR.CompilationSteps.PhaseExecution.NotificationContext nc ) { var op = (ZeligIR.AbstractBinaryOperator)nc.CurrentOperator; if(ConvertToPseudoRegister( nc.CurrentCFG, op )) { nc.MarkAsModified(); return; } foreach(ZeligIR.Expression ex in op.Arguments) { ZeligIR.ConstantExpression exConst = ex as ZeligIR.ConstantExpression; if(exConst != null) { bool fOk = CanBeUsedAsAnImmediateValue( nc, exConst ); if(fOk) { switch(op.Alu) { case ZeligIR.BinaryOperator.ALU.MUL: // // Multiplication operands should be in registers. // fOk = false; break; case ZeligIR.BinaryOperator.ALU.SHL: case ZeligIR.BinaryOperator.ALU.SHR: // // Left operand should be in a register. // if(exConst == op.FirstArgument) { fOk = false; } break; } } if(fOk == false) { MoveToPseudoRegister( nc.CurrentCFG, op, exConst ); nc.MarkAsModified(); break; } } } } [ZeligIR.CompilationSteps.PhaseFilter( typeof(ZeligIR.CompilationSteps.Phases.PrepareForRegisterAllocation) )] [ZeligIR.CompilationSteps.OperatorHandler( typeof(ARM.BinaryOperatorWithShift) )] private void Handle_ARM_BinaryOperatorWithShift( ZeligIR.CompilationSteps.PhaseExecution.NotificationContext nc ) { var op = (ARM.BinaryOperatorWithShift)nc.CurrentOperator; var cfg = nc.CurrentCFG; if(ConvertToPseudoRegister( cfg, op )) { nc.MarkAsModified(); return; } if(MoveToPseudoRegisterIfConstant( cfg, op, op.FirstArgument )) { nc.MarkAsModified(); return; } if(MoveToPseudoRegisterIfConstant( cfg, op, op.SecondArgument )) { nc.MarkAsModified(); return; } } //--// private bool CanBeUsedAsAnImmediateValue( ZeligIR.CompilationSteps.PhaseExecution.NotificationContext nc , ZeligIR.ConstantExpression exConst ) { ZeligIR.Operator op = nc.CurrentOperator; if(m_owner.HasVFPv2) { if(exConst.IsValueFloatingPoint) { if(exConst.IsEqualToZero() && op is ZeligIR.CompareOperator) { return true; } return false; } } if(exConst.IsEqualToZero()) { return true; } if(exConst.IsValueInteger || exConst.IsValueFloatingPoint ) { ulong val; if(exConst.GetAsRawUlong( out val )) { uint valSeed; uint valRot; if(s_Encoding.check_DataProcessing_ImmediateValue( (uint)val, out valSeed, out valRot ) == true) { return true; } if(s_Encoding.check_DataProcessing_ImmediateValue( ~(uint)val, out valSeed, out valRot ) == true) { var opBin = op as ZeligIR.BinaryOperator; if(opBin != null) { if(opBin.Alu == ZeligIR.AbstractBinaryOperator.ALU.AND) { return true; // This can be represented as a BIC. } } } } } return false; } } public static bool ConvertToPseudoRegister( ZeligIR.ControlFlowGraphStateForCodeTransformation cfg , ZeligIR.Operator op ) { ZeligIR.PseudoRegisterExpression var; bool fModified = false; for(int i = op.Results.Length; --i >= 0; ) { var lhs = op.Results[i]; // Make sure we get the latest Lhs, it might have changed as part of the conversion. var = AllocatePseudoRegisterIfNeeded( cfg, lhs ); if(var != null) { op.AddOperatorAfter( ZeligIR.SingleAssignmentOperator.New( op.DebugInfo, lhs, var ) ); op.SubstituteDefinition( lhs, var ); fModified = true; } } if(op is ZeligIR.AddressAssignmentOperator) { // Rvalue must be in stack locations. } else { for(int i = op.Arguments.Length; --i >= 0; ) { var ex = op.Arguments[i]; // Make sure we get the latest Rhs, it might have changed as part of the conversion. bool fConstantOk = true; if(op is ZeligIR.LoadIndirectOperator || op is ARM.LoadIndirectOperatorWithIndexUpdate ) { if(i == 0) // Destination value cannot be a constant. { fConstantOk = false; // // If the pointer is an object allocated at compile-time, // we can leave it alone, it will be removed later, see EmitCode_LoadIndirectOperator. // var constEx = ex as ZeligIR.ConstantExpression; if(constEx != null) { var dd = constEx.Value as ZeligIR.DataManager.DataDescriptor; if(dd != null) { if(dd.CanPropagate) { fConstantOk = true; } } } } } else if(op is ZeligIR.StoreIndirectOperator || op is ARM.StoreIndirectOperatorWithIndexUpdate ) { if(i == 0) // Destination value cannot be a constant. { fConstantOk = false; } if(i == 1) // Source value cannot be a constant. { fConstantOk = false; } } else if(op is ZeligIR.ZeroExtendOperator || op is ZeligIR.SignExtendOperator || op is ZeligIR.TruncateOperator ) { fConstantOk = false; } var = AllocatePseudoRegisterIfNeeded( cfg, ex, fConstantOk ); if(var != null) { op.AddOperatorBefore( ZeligIR.SingleAssignmentOperator.New( op.DebugInfo, var, ex ) ); op.SubstituteUsage( ex, var ); fModified = true; } } } return fModified; } } } ================================================ FILE: Zelig/Zelig/CompileTime/TargetModels/ProductConfiguration/Abstractions/ARM/ArmPlatform_RegisterAllocation.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // namespace Microsoft.Zelig.Configuration.Environment.Abstractions { using System.Collections.Generic; using Microsoft.Zelig.Runtime.TypeSystem; using Microsoft.Zelig.TargetModel.ArmProcessor; using ZeligIR = Microsoft.Zelig.CodeGeneration.IR; public partial class ArmPlatform { // // State // private ZeligIR.Abstractions.RegisterDescriptor[] m_registers; private ZeligIR.Abstractions.RegisterDescriptor m_scratchRegister; private InstructionSet m_instructionSetProvider; // // Helper Methods // public override ZeligIR.Abstractions.RegisterDescriptor[] GetRegisters() { return m_registers; } public override ZeligIR.Abstractions.RegisterDescriptor GetScratchRegister() { return m_scratchRegister; } public override ZeligIR.Abstractions.RegisterDescriptor GetRegisterForEncoding( uint encoding ) { foreach(var regDesc in m_registers) { if(regDesc.Encoding == encoding) { return regDesc; } } return null; } public override void ComputeNumberOfFragmentsForExpression( TypeRepresentation sourceTd , ZeligIR.ControlFlowGraphStateForCodeTransformation.KindOfFragment kind , out uint sourceFragments , out bool fDirect ) { if(sourceTd is ReferenceTypeRepresentation || sourceTd is PointerTypeRepresentation ) { CHECKS.ASSERT( sourceTd.SizeOfHoldingVariableInWords == 1, "Unexpected size for pointer type {0}: {1}", sourceTd, sourceTd.SizeOfHoldingVariableInWords ); sourceFragments = 1; fDirect = true; } else { CHECKS.ASSERT( sourceTd is ValueTypeRepresentation, "Unexpected type {0}", sourceTd ); if(sourceTd.IsFloatingPoint) { if(this.HasVFPv2) { sourceFragments = 1; fDirect = true; return; } } sourceFragments = sourceTd.SizeOfHoldingVariableInWords; fDirect = false; } } protected virtual void CreateRegisters( List< ZeligIR.Abstractions.RegisterDescriptor > lst ) { ZeligIR.Abstractions.RegisterDescriptor reg; for(uint encoding = EncodingDefinition_ARM.c_register_r0; encoding <= EncodingDefinition_ARM.c_register_r11; encoding++) { reg = ZeligIR.Abstractions.RegisterDescriptor.CreateTemplateFor32bitIntegerRegister( lst, string.Format( "R{0}", encoding ), encoding, encoding, ZeligIR.Abstractions.RegisterClass.AvailableForAllocation ); } //--// // // Reserved as a scratch register, so we cannot use it during register allocation. // reg = ZeligIR.Abstractions.RegisterDescriptor.CreateTemplateFor32bitIntegerRegister( lst, "R12", EncodingDefinition_ARM.c_register_r12, EncodingDefinition_ARM.c_register_r12, ZeligIR.Abstractions.RegisterClass.None ); m_scratchRegister = reg; //--// // // Intrinsic use. // reg = ZeligIR.Abstractions.RegisterDescriptor.CreateTemplateFor32bitIntegerRegister( lst, "SP", EncodingDefinition_ARM.c_register_sp, EncodingDefinition_ARM.c_register_sp, ZeligIR.Abstractions.RegisterClass.Special | ZeligIR.Abstractions.RegisterClass.StackPointer ); //--// reg = ZeligIR.Abstractions.RegisterDescriptor.CreateTemplateFor32bitIntegerRegister( lst, "LR", EncodingDefinition_ARM.c_register_lr, EncodingDefinition_ARM.c_register_lr, ZeligIR.Abstractions.RegisterClass.AvailableForAllocation | ZeligIR.Abstractions.RegisterClass.LinkAddress ); //--// // // Intrinsic use. // reg = ZeligIR.Abstractions.RegisterDescriptor.CreateTemplateFor32bitIntegerRegister( lst, "PC", EncodingDefinition_ARM.c_register_pc, EncodingDefinition_ARM.c_register_pc, ZeligIR.Abstractions.RegisterClass.Special | ZeligIR.Abstractions.RegisterClass.ProgramCounter ); //--// if(this.HasVFPv2) { uint encoding32Lo = EncodingDefinition_VFP_ARM.c_register_s0; uint encoding32Hi = EncodingDefinition_VFP_ARM.c_register_s1; uint encoding64 = EncodingDefinition_VFP_ARM.c_register_d0; for(uint i = 0; i < 16; i++) { // // S0 and S1 are aliases for D0, etc. // // To express that, the PhysicalStorageOffset of S<2*idx> is the same as D. Since D is twice as big as S<2*idx>, it also covers S<2*idx+1>. // var reg32Lo = ZeligIR.Abstractions.RegisterDescriptor.CreateTemplateFor32bitFloatingPointRegister( lst, string.Format( "S{0}", i * 2 ), encoding32Lo, encoding32Lo, ZeligIR.Abstractions.RegisterClass.AvailableForAllocation, true ); var reg32Hi = ZeligIR.Abstractions.RegisterDescriptor.CreateTemplateFor32bitFloatingPointRegister( lst, string.Format( "S{0}", i * 2 + 1 ), encoding32Hi, encoding32Hi, ZeligIR.Abstractions.RegisterClass.AvailableForAllocation, false ); var reg64 = ZeligIR.Abstractions.RegisterDescriptor.CreateTemplateFor64bitFloatingPointRegister( lst, string.Format( "D{0}", i ), encoding64 , encoding32Lo, ZeligIR.Abstractions.RegisterClass.AvailableForAllocation ); reg32Lo.AddInterference( reg64 ); reg32Hi.AddInterference( reg64 ); reg64 .AddInterference( reg32Lo ); reg64 .AddInterference( reg32Hi ); encoding32Lo += 2; encoding32Hi += 2; encoding64 += 1; } reg = ZeligIR.Abstractions.RegisterDescriptor.CreateTemplateFor32bitSystemRegister( lst, "FPSID", EncodingDefinition_VFP_ARM.c_register_FPSID, EncodingDefinition_VFP_ARM.c_register_FPSID, ZeligIR.Abstractions.RegisterClass.Special ); reg = ZeligIR.Abstractions.RegisterDescriptor.CreateTemplateFor32bitSystemRegister( lst, "FPSCR", EncodingDefinition_VFP_ARM.c_register_FPSCR, EncodingDefinition_VFP_ARM.c_register_FPSCR, ZeligIR.Abstractions.RegisterClass.Special ); reg = ZeligIR.Abstractions.RegisterDescriptor.CreateTemplateFor32bitSystemRegister( lst, "FPEXC", EncodingDefinition_VFP_ARM.c_register_FPEXC, EncodingDefinition_VFP_ARM.c_register_FPEXC, ZeligIR.Abstractions.RegisterClass.Special ); } //--// reg = ZeligIR.Abstractions.RegisterDescriptor.CreateTemplateFor32bitSystemRegister( lst, "CPSR", EncodingDefinition_ARM.c_register_cpsr, EncodingDefinition_ARM.c_register_cpsr, ZeligIR.Abstractions.RegisterClass.Special | ZeligIR.Abstractions.RegisterClass.StatusRegister ); reg = ZeligIR.Abstractions.RegisterDescriptor.CreateTemplateFor32bitSystemRegister( lst, "SPSR", EncodingDefinition_ARM.c_register_spsr, EncodingDefinition_ARM.c_register_spsr, ZeligIR.Abstractions.RegisterClass.Special | ZeligIR.Abstractions.RegisterClass.StatusRegister ); } } } ================================================ FILE: Zelig/Zelig/CompileTime/TargetModels/ProductConfiguration/Abstractions/ARM/ArmPlatform_SplitComplexOperators.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // namespace Microsoft.Zelig.Configuration.Environment.Abstractions { using System; using System.Collections.Generic; using Microsoft.Zelig.Runtime.TypeSystem; using Microsoft.Zelig.TargetModel.ArmProcessor; using ZeligIR = Microsoft.Zelig.CodeGeneration.IR; public partial class ArmPlatform { // // Helper Methods // public int GetOffsetLimit( TypeRepresentation target ) { if(HasVFPv2) { if(target.IsFloatingPoint) { return 256 * sizeof(uint); } } switch(target.SizeOfHoldingVariable) { case 1: return 256; case 2: return 256; case 4: return 4096; default: throw TypeConsistencyErrorException.Create( "Unsupported size of load/store: {0}", target ); } } [ZeligIR.CompilationSteps.PhaseFilter( typeof(ZeligIR.CompilationSteps.Phases.SplitComplexOperators) )] [ZeligIR.CompilationSteps.OperatorHandler( typeof(ZeligIR.IndirectOperator) )] private void HandleSplit_IndirectOperator( ZeligIR.CompilationSteps.PhaseExecution.NotificationContext nc ) { ZeligIR.IndirectOperator op = (ZeligIR.IndirectOperator)nc.CurrentOperator; if(Math.Abs( op.Offset ) >= GetOffsetLimit( op.Type )) { ZeligIR.TypeSystemForCodeTransformation ts = nc.TypeSystem; ZeligIR.ControlFlowGraphStateForCodeTransformation cfg = nc.CurrentCFG; Debugging.DebugInfo debugInfo = op.DebugInfo; TypeRepresentation td = op.Type; TypeRepresentation tdPtr = ts.GetManagedPointerToType( td ); ZeligIR.PseudoRegisterExpression tmpPtr = cfg.AllocatePseudoRegister( tdPtr ); ZeligIR.Operator opNew; // // Compute the address of the location to access. // op.AddOperatorBefore( ZeligIR.BinaryOperator.New( debugInfo, ZeligIR.BinaryOperator.ALU.ADD, false, false, tmpPtr, op.FirstArgument, ts.CreateConstant( op.Offset ) ) ); if(op is ZeligIR.StoreIndirectOperator) { opNew = ZeligIR.StoreIndirectOperator.New( debugInfo, td, tmpPtr, op.SecondArgument, op.AccessPath, 0, false ); } else { opNew = ZeligIR.LoadIndirectOperator.New( debugInfo, td, op.FirstResult, tmpPtr, op.AccessPath, 0, op.MayMutateExistingStorage, false ); } op.SubstituteWithOperator( opNew, ZeligIR.Operator.SubstitutionFlags.Default ); opNew.AddAnnotation( ZeligIR.BlockCopyPropagationAnnotation.Create( nc.TypeSystem, 0, false, false ) ); nc.MarkAsModified(); } } } } ================================================ FILE: Zelig/Zelig/CompileTime/TargetModels/ProductConfiguration/Abstractions/ARM/ImageAnnotations/ArmCodeRelocation_Branch.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // namespace Microsoft.Zelig.Configuration.Environment.Abstractions { using System; using System.Collections.Generic; using Microsoft.Zelig.Runtime.TypeSystem; using Microsoft.Zelig.TargetModel.ArmProcessor; using ZeligIR = Microsoft.Zelig.CodeGeneration.IR; internal sealed class ArmCodeRelocation_Branch : ZeligIR.ImageBuilders.CodeRelocation { // // State // bool m_fConditional; // // Constructor Methods // private ArmCodeRelocation_Branch() // Default constructor required by TypeSystemSerializer. { } internal ArmCodeRelocation_Branch( ZeligIR.ImageBuilders.SequentialRegion region , uint offset , ZeligIR.BasicBlock target , ZeligIR.ImageBuilders.CompilationState cs , ZeligIR.Operator origin , int skew , bool fConditional ) : base( region, offset, sizeof(uint), target, cs, origin, skew ) { m_fConditional = fConditional; } // // Helper Methods // public override void ApplyTransformation( ZeligIR.TransformationContextForCodeTransformation context ) { context.Push( this ); base.ApplyTransformation( context ); context.Transform( ref m_fConditional ); context.Pop(); } //--// public override void GetAllowedRelocationRange( out int lowerBound , out int upperBound ) { lowerBound = m_skew + (int.MinValue >> 8) * sizeof(uint); upperBound = m_skew + (int.MaxValue >> 8) * sizeof(uint); } protected override bool ApplyRelocation( uint srcAddress , uint dstAddress ) { InstructionSet.Opcode_Branch op = (InstructionSet.Opcode_Branch)ArmCompilationState.GetOpcode( m_cs, m_region, m_offset ); op.Offset = ((int)dstAddress - (int)srcAddress) - m_skew; ArmCompilationState.SetOpcode( m_cs, m_region, m_offset, op ); return true; } protected override void NotifyFailedRelocation() { ArmCompilationState cs = (ArmCompilationState)m_cs; cs.Owner.IncreaseEncodingLevelForBranch( m_origin, (ZeligIR.BasicBlock)m_target, m_fConditional ); } // // Access Methods // public bool IsConditional { get { return m_fConditional; } } } } ================================================ FILE: Zelig/Zelig/CompileTime/TargetModels/ProductConfiguration/Abstractions/ARM/ImageAnnotations/ArmCodeRelocation_ExternMethod.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // namespace Microsoft.Zelig.Configuration.Environment.Abstractions { using System; using System.Collections.Generic; using Microsoft.Zelig.Runtime.TypeSystem; using Microsoft.Zelig.TargetModel.ArmProcessor; using ZeligIR = Microsoft.Zelig.CodeGeneration.IR; using Microsoft.Zelig.CodeGeneration.IR; internal sealed class ArmCodeRelocation_ExternMethod : ZeligIR.ImageBuilders.CodeRelocation { // // State // bool m_fConditional; ExternalCallOperator.IExternalCallContext m_context; // // Constructor Methods // private ArmCodeRelocation_ExternMethod() // Default constructor required by TypeSystemSerializer. { } internal ArmCodeRelocation_ExternMethod( ZeligIR.ImageBuilders.SequentialRegion region , uint offset , ZeligIR.BasicBlock target , ZeligIR.ImageBuilders.CompilationState cs , ZeligIR.Operator origin , int skew , bool fConditional , ExternalCallOperator.IExternalCallContext context ) : base( region, offset, sizeof(uint), target, cs, origin, skew ) { m_fConditional = fConditional; m_context = context; } // // Helper Methods // public override void ApplyTransformation( ZeligIR.TransformationContextForCodeTransformation context ) { context.Push( this ); base.ApplyTransformation( context ); context.Transform( ref m_fConditional ); context.Pop(); } //--// public override void GetAllowedRelocationRange( out int lowerBound , out int upperBound ) { lowerBound = m_skew + (int.MinValue >> 8) * sizeof(uint); upperBound = m_skew + (int.MaxValue >> 8) * sizeof(uint); } protected override bool ApplyRelocation( uint srcAddress , uint dstAddress ) { m_context.UpdateRelocation( this ); return true; } protected override void NotifyFailedRelocation() { } // // Access Methods // public bool IsConditional { get { return m_fConditional; } } } } ================================================ FILE: Zelig/Zelig/CompileTime/TargetModels/ProductConfiguration/Abstractions/ARM/ImageAnnotations/ArmCodeRelocation_FLD.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // namespace Microsoft.Zelig.Configuration.Environment.Abstractions { using System; using System.Collections.Generic; using Microsoft.Zelig.Runtime.TypeSystem; using Microsoft.Zelig.TargetModel.ArmProcessor; using ZeligIR = Microsoft.Zelig.CodeGeneration.IR; internal sealed class ArmCodeRelocation_FLD : ZeligIR.ImageBuilders.CodeRelocation { // // State // // // Constructor Methods // private ArmCodeRelocation_FLD() // Default constructor required by TypeSystemSerializer. { } internal ArmCodeRelocation_FLD( ZeligIR.ImageBuilders.SequentialRegion region , uint offset , ZeligIR.ImageBuilders.CodeConstant target , ZeligIR.ImageBuilders.CompilationState cs , ZeligIR.Operator origin , int skew ) : base( region, offset, sizeof(uint), target, cs, origin, skew ) { } // // Helper Methods // public override void ApplyTransformation( ZeligIR.TransformationContextForCodeTransformation context ) { context.Push( this ); base.ApplyTransformation( context ); context.Pop(); } //--// public override void GetAllowedRelocationRange( out int lowerBound , out int upperBound ) { lowerBound = m_skew - ((1 << 8) - 1) * sizeof(uint); upperBound = m_skew + ((1 << 8) - 1) * sizeof(uint); } protected override bool ApplyRelocation( uint srcAddress , uint dstAddress ) { InstructionSet_VFP.Opcode_VFP_DataTransfer op = (InstructionSet_VFP.Opcode_VFP_DataTransfer)ArmCompilationState.GetOpcode( m_cs, m_region, m_offset ); if(op.Rn != EncodingDefinition.c_register_pc) { throw NotImplemented(); } int relPos = ((int)dstAddress - (int)srcAddress) - m_skew; if(relPos < 0) { op.Up = false; op.Offset = ((uint)-relPos) / sizeof(uint); } else { op.Up = true; op.Offset = ((uint)relPos) / sizeof(uint); } ArmCompilationState.SetOpcode( m_cs, m_region, m_offset, op ); return true; } protected override void NotifyFailedRelocation() { ArmCompilationState cs = (ArmCompilationState)m_cs; cs.Owner.IncreaseEncodingLevelForConstant( m_origin ); } // // Access Methods // } } ================================================ FILE: Zelig/Zelig/CompileTime/TargetModels/ProductConfiguration/Abstractions/ARM/ImageAnnotations/ArmCodeRelocation_LDR.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // namespace Microsoft.Zelig.Configuration.Environment.Abstractions { using System; using System.Collections.Generic; using Microsoft.Zelig.Runtime.TypeSystem; using Microsoft.Zelig.TargetModel.ArmProcessor; using ZeligIR = Microsoft.Zelig.CodeGeneration.IR; internal sealed class ArmCodeRelocation_LDR : ZeligIR.ImageBuilders.CodeRelocation { // // State // // // Constructor Methods // private ArmCodeRelocation_LDR() // Default constructor required by TypeSystemSerializer. { } internal ArmCodeRelocation_LDR( ZeligIR.ImageBuilders.SequentialRegion region , uint offset , ZeligIR.ImageBuilders.CodeConstant target , ZeligIR.ImageBuilders.CompilationState cs , ZeligIR.Operator origin , int skew ) : base( region, offset, sizeof(uint), target, cs, origin, skew ) { } // // Helper Methods // public override void ApplyTransformation( ZeligIR.TransformationContextForCodeTransformation context ) { context.Push( this ); base.ApplyTransformation( context ); context.Pop(); } //--// public override void GetAllowedRelocationRange( out int lowerBound , out int upperBound ) { lowerBound = m_skew - ((1 << 12) - 1); upperBound = m_skew + ((1 << 12) - 1); } protected override bool ApplyRelocation( uint srcAddress , uint dstAddress ) { InstructionSet.Opcode_SingleDataTransfer_1 op = (InstructionSet.Opcode_SingleDataTransfer_1)ArmCompilationState.GetOpcode( m_cs, m_region, m_offset ); if(op.Rn != EncodingDefinition.c_register_pc) { throw NotImplemented(); } int relPos = ((int)dstAddress - (int)srcAddress) - m_skew; if(relPos < 0) { op.Up = false; op.Offset = (uint)-relPos; } else { op.Up = true; op.Offset = (uint)relPos; } ArmCompilationState.SetOpcode( m_cs, m_region, m_offset, op ); return true; } protected override void NotifyFailedRelocation() { ArmCompilationState cs = (ArmCompilationState)m_cs; cs.Owner.IncreaseEncodingLevelForConstant( m_origin ); } // // Access Methods // } } ================================================ FILE: Zelig/Zelig/CompileTime/TargetModels/ProductConfiguration/Abstractions/ARM/ImageAnnotations/ArmCodeRelocation_MOV.cs ================================================ namespace Microsoft.Zelig.Configuration.Environment.Abstractions { using System; using System.Collections.Generic; using Microsoft.Zelig.Runtime.TypeSystem; using Microsoft.Zelig.TargetModel.ArmProcessor; using ZeligIR = Microsoft.Zelig.CodeGeneration.IR; internal sealed class ArmCodeRelocation_MOV : ZeligIR.ImageBuilders.CodeRelocation { private static EncodingDefinition_ARM s_Encoding = (EncodingDefinition_ARM)CurrentInstructionSetEncoding.GetEncoding(); // // State // int m_numOpcodes; // // Constructor Methods // private ArmCodeRelocation_MOV() // Default constructor required by TypeSystemSerializer. { } internal ArmCodeRelocation_MOV( ZeligIR.ImageBuilders.SequentialRegion region , uint offset , ZeligIR.ImageBuilders.CodeConstant target , ZeligIR.ImageBuilders.CompilationState cs , ZeligIR.Operator origin , int skew , int numOpcodes ) : base( region, offset, sizeof(uint), target, cs, origin, skew ) { m_numOpcodes = Math.Min( numOpcodes, 4 ); } // // Helper Methods // public override void ApplyTransformation( ZeligIR.TransformationContextForCodeTransformation context ) { context.Push( this ); base.ApplyTransformation( context ); context.Transform( ref m_numOpcodes ); context.Pop(); } //--// public override void GetAllowedRelocationRange( out int lowerBound , out int upperBound ) { int range; switch(m_numOpcodes) { case 1 : range = 0x000000FF; break; case 2 : range = 0x0000FFFF; break; case 3 : range = 0x00FFFFFF; break; default: range = 0x3FFFFFFF; break; } lowerBound = this.EffectiveSkew - range; upperBound = this.EffectiveSkew + range; } protected override bool ApplyRelocation( uint srcAddress , uint dstAddress ) { int relPos = ((int)dstAddress - (int)srcAddress) - this.EffectiveSkew; uint val; uint op0; uint op1; if(relPos <= 0) { val = ~(uint)relPos; op0 = EncodingDefinition_ARM.c_operation_MVN; op1 = EncodingDefinition_ARM.c_operation_BIC; } else { val = (uint)relPos; op0 = EncodingDefinition_ARM.c_operation_MOV; op1 = EncodingDefinition_ARM.c_operation_ORR; } for(uint pos = 0; pos < m_numOpcodes; pos++) { InstructionSet.Opcode_DataProcessing_1 op = (InstructionSet.Opcode_DataProcessing_1)ArmCompilationState.GetOpcode( m_cs, m_region, m_offset + pos * sizeof(uint) ); uint immRes; uint rotRes; s_Encoding.check_DataProcessing_ImmediateValue( val & (0xFFu << (8 * (int)pos)), out immRes, out rotRes ); op.Alu = pos == 0 ? op0 : op1; op.ImmediateSeed = immRes; op.ImmediateRotation = rotRes; ArmCompilationState.SetOpcode( m_cs, m_region, m_offset + pos * sizeof(uint), op ); } return true; } protected override void NotifyFailedRelocation() { ArmCompilationState cs = (ArmCompilationState)m_cs; ZeligIR.ImageBuilders.Core.ConstantAddressEncodingLevel level; switch(m_numOpcodes) { case 1 : case 2 : level = ZeligIR.ImageBuilders.Core.ConstantAddressEncodingLevel.FarRelativeLoad16Bit; break; case 3 : level = ZeligIR.ImageBuilders.Core.ConstantAddressEncodingLevel.FarRelativeLoad24Bit; break; default: level = ZeligIR.ImageBuilders.Core.ConstantAddressEncodingLevel.FarRelativeLoad32Bit; break; } cs.Owner.IncreaseEncodingLevelForConstant( m_origin, level ); } // // Access Methods // private int EffectiveSkew { get { return m_skew + m_numOpcodes * sizeof(uint); } } public int EncodingLength { get { return m_numOpcodes; } } } } ================================================ FILE: Zelig/Zelig/CompileTime/TargetModels/ProductConfiguration/Abstractions/ARM/Operators/BinaryOperatorWithShift.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // namespace Microsoft.Zelig.Configuration.Environment.Abstractions.ARM { using System; using System.Collections.Generic; using Microsoft.Zelig.Runtime.TypeSystem; using Microsoft.Zelig.CodeGeneration.IR; public sealed class BinaryOperatorWithShift : Operator { // // State // AbstractBinaryOperator.ALU m_alu; bool m_fSigned; AbstractBinaryOperator.ALU m_aluShift; bool m_fSignedShift; // // Constructor Methods // private BinaryOperatorWithShift( Debugging.DebugInfo debugInfo , OperatorCapabilities capabilities , AbstractBinaryOperator.ALU alu , bool fSigned , AbstractBinaryOperator.ALU aluShift , bool fSignedShift ) : base( debugInfo, capabilities, OperatorLevel.Lowest ) { m_alu = alu; m_fSigned = fSignedShift; m_aluShift = aluShift; m_fSignedShift = fSignedShift; } //--// public static BinaryOperatorWithShift New( Debugging.DebugInfo debugInfo , AbstractBinaryOperator.ALU alu , bool fSigned , AbstractBinaryOperator.ALU aluShift , bool fSignedShift , VariableExpression lhs , Expression rhsLeft , Expression rhsRight , Expression rhsShift ) { OperatorCapabilities capabilities = OperatorCapabilities.DoesNotMutateExistingStorage | OperatorCapabilities.DoesNotAllocateStorage | OperatorCapabilities.DoesNotReadExistingMutableStorage | OperatorCapabilities.DoesNotReadThroughPointerOperands | OperatorCapabilities.DoesNotWriteThroughPointerOperands | OperatorCapabilities.DoesNotCapturePointerOperands | OperatorCapabilities.DoesNotThrow ; switch(alu) { case AbstractBinaryOperator.ALU.ADD: case AbstractBinaryOperator.ALU.MUL: case AbstractBinaryOperator.ALU.AND: case AbstractBinaryOperator.ALU.OR: case AbstractBinaryOperator.ALU.XOR: capabilities |= OperatorCapabilities.IsCommutative; break; default: capabilities |= OperatorCapabilities.IsNonCommutative; break; } var res = new BinaryOperatorWithShift( debugInfo, capabilities, alu, fSigned, aluShift, fSignedShift ); res.SetLhs( lhs ); res.SetRhs( rhsLeft, rhsRight, rhsShift ); return res; } //--// // // Helper Methods // public override void ApplyTransformation( TransformationContextForIR context ) { context.Push( this ); base.ApplyTransformation( context ); context.Transform( ref m_alu ); context.Transform( ref m_fSigned ); context.Transform( ref m_aluShift ); context.Transform( ref m_fSignedShift ); context.Pop(); } public override Operator Clone( CloningContext context ) { return RegisterAndCloneState( context, new BinaryOperatorWithShift( m_debugInfo, m_capabilities, m_alu, m_fSigned, m_aluShift, m_fSignedShift ) ); } //--// // // Access Methods // public AbstractBinaryOperator.ALU Alu { get { return m_alu; } } public bool Signed { get { return m_fSigned; } } public AbstractBinaryOperator.ALU AluShift { get { return m_aluShift; } } public bool SignedShift { get { return m_fSignedShift; } } //--// // // Debug Methods // public override void InnerToString( System.Text.StringBuilder sb ) { sb.Append( "BinaryOperatorWithShift(" ); base.InnerToString( sb ); sb.Append( ")" ); } public override string FormatOutput( IIntermediateRepresentationDumper dumper ) { return dumper.FormatOutput( "{0} = {1} {2} ({3} {4} {5})", this.FirstResult, this.FirstArgument, m_alu, this.SecondArgument, m_aluShift, this.ThirdArgument ); } } } ================================================ FILE: Zelig/Zelig/CompileTime/TargetModels/ProductConfiguration/Abstractions/ARM/Operators/BreakpointOperator.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // namespace Microsoft.Zelig.Configuration.Environment.Abstractions.ARM { using System; using System.Collections.Generic; using Microsoft.Zelig.Runtime.TypeSystem; using Microsoft.Zelig.CodeGeneration.IR; public class BreakpointOperator : Operator { private const OperatorCapabilities cCapabilities = OperatorCapabilities.IsNonCommutative | OperatorCapabilities.DoesNotMutateExistingStorage | OperatorCapabilities.DoesNotAllocateStorage | OperatorCapabilities.DoesNotReadExistingMutableStorage | OperatorCapabilities.DoesNotThrow | OperatorCapabilities.DoesNotReadThroughPointerOperands | OperatorCapabilities.DoesNotWriteThroughPointerOperands | OperatorCapabilities.DoesNotCapturePointerOperands ; // // State // private uint m_value; // // Constructor Methods // private BreakpointOperator( Debugging.DebugInfo debugInfo , uint value ) : base( debugInfo, cCapabilities, OperatorLevel.Lowest ) { m_value = value; } //--// public static BreakpointOperator New( Debugging.DebugInfo debugInfo , uint value ) { BreakpointOperator res = new BreakpointOperator( debugInfo, value ); return res; } //--// // // Helper Methods // public override Operator Clone( CloningContext context ) { return RegisterAndCloneState( context, new BreakpointOperator( m_debugInfo, m_value ) ); } //--// public override void ApplyTransformation( TransformationContextForIR context ) { TransformationContextForCodeTransformation context2 = (TransformationContextForCodeTransformation)context; context2.Push( this ); base.ApplyTransformation( context2 ); context2.Transform( ref m_value ); context2.Pop(); } //--// public override bool CanPropagateCopy( Expression exOld , Expression exNew ) { if(exNew is ConstantExpression) { return false; } return true; } // // Access Methods // public override bool ShouldNotBeRemoved { [System.Diagnostics.DebuggerHidden] get { return true; } } public uint Value { get { return m_value; } } // // Debug Methods // public override void InnerToString( System.Text.StringBuilder sb ) { sb.AppendFormat( "BreakpointOperator(Value={0}", m_value ); base.InnerToString( sb ); sb.Append( ")" ); } public override string FormatOutput( IIntermediateRepresentationDumper dumper ) { return dumper.FormatOutput( "Bkpt(Value={0})", m_value ); } } } ================================================ FILE: Zelig/Zelig/CompileTime/TargetModels/ProductConfiguration/Abstractions/ARM/Operators/GetStatusRegisterOperator.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // namespace Microsoft.Zelig.Configuration.Environment.Abstractions.ARM { using System; using System.Collections.Generic; using Microsoft.Zelig.Runtime.TypeSystem; using Microsoft.Zelig.CodeGeneration.IR; public sealed class GetStatusRegisterOperator : Operator { private const OperatorCapabilities cCapabilities = OperatorCapabilities.IsNonCommutative | OperatorCapabilities.DoesNotMutateExistingStorage | OperatorCapabilities.DoesNotAllocateStorage | OperatorCapabilities.DoesNotReadExistingMutableStorage | OperatorCapabilities.DoesNotThrow | OperatorCapabilities.DoesNotReadThroughPointerOperands | OperatorCapabilities.DoesNotWriteThroughPointerOperands | OperatorCapabilities.DoesNotCapturePointerOperands ; // // State // private bool m_fUseSPSR; // // Constructor Methods // private GetStatusRegisterOperator( Debugging.DebugInfo debugInfo , bool fUseSPSR ) : base( debugInfo, cCapabilities, OperatorLevel.Lowest ) { m_fUseSPSR = fUseSPSR; } //--// public static GetStatusRegisterOperator New( Debugging.DebugInfo debugInfo , bool fUseSPSR , VariableExpression ex ) { GetStatusRegisterOperator res = new GetStatusRegisterOperator( debugInfo, fUseSPSR ); res.SetLhs( ex ); return res; } //--// // // Helper Methods // public override Operator Clone( CloningContext context ) { return RegisterAndCloneState( context, new GetStatusRegisterOperator( m_debugInfo, m_fUseSPSR ) ); } //--// public override void ApplyTransformation( TransformationContextForIR context ) { TransformationContextForCodeTransformation context2 = (TransformationContextForCodeTransformation)context; context2.Push( this ); base.ApplyTransformation( context2 ); context2.Transform( ref m_fUseSPSR ); context2.Pop(); } //--// // // Access Methods // public bool UseSPSR { get { return m_fUseSPSR; } } //--// // // Debug Methods // public override void InnerToString( System.Text.StringBuilder sb ) { sb.Append( "GetStatusRegisterOperator(" ); base.InnerToString( sb ); sb.Append( ")" ); } public override string FormatOutput( IIntermediateRepresentationDumper dumper ) { return dumper.FormatOutput( "{0} = <{1} status register>", this.FirstResult, m_fUseSPSR ? "saved" : "current" ); } } } ================================================ FILE: Zelig/Zelig/CompileTime/TargetModels/ProductConfiguration/Abstractions/ARM/Operators/IndirectOperatorWithIndexUpdate.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // namespace Microsoft.Zelig.Configuration.Environment.Abstractions.ARM { using System; using System.Collections.Generic; using Microsoft.Zelig.Runtime.TypeSystem; using Microsoft.Zelig.CodeGeneration.IR; public abstract class IndirectOperatorWithIndexUpdate : IndirectOperator { // // State // protected bool m_fPostUpdate; // // Constructor Methods // protected IndirectOperatorWithIndexUpdate( Debugging.DebugInfo debugInfo , OperatorCapabilities capabilities , TypeRepresentation td , FieldRepresentation[] accessPath , int offset , bool fPostUpdate ) : base( debugInfo, capabilities, OperatorLevel.Lowest, td, accessPath, offset ) { m_fPostUpdate = fPostUpdate; } //--// // // Helper Methods // public override void ApplyTransformation( TransformationContextForIR context ) { context.Push( this ); base.ApplyTransformation( context ); context.Transform( ref m_fPostUpdate ); context.Pop(); } //--// // // Access Methods // public bool PostUpdate { get { return m_fPostUpdate; } } // // Debug Methods // public override void InnerToString( System.Text.StringBuilder sb ) { base.InnerToString( sb ); sb.Append( m_fPostUpdate ? ",PostUpdate" : ",PreUpdate" ); } } } ================================================ FILE: Zelig/Zelig/CompileTime/TargetModels/ProductConfiguration/Abstractions/ARM/Operators/LoadIndirectOperatorWithIndexUpdate.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // namespace Microsoft.Zelig.Configuration.Environment.Abstractions.ARM { using System; using System.Collections.Generic; using Microsoft.Zelig.Runtime.TypeSystem; using Microsoft.Zelig.CodeGeneration.IR; public sealed class LoadIndirectOperatorWithIndexUpdate : IndirectOperatorWithIndexUpdate { // // State // // // Constructor Methods // private LoadIndirectOperatorWithIndexUpdate( Debugging.DebugInfo debugInfo , OperatorCapabilities capabilities , TypeRepresentation td , FieldRepresentation[] accessPath , int offset , bool fPostUpdate ) : base( debugInfo, capabilities, td, accessPath, offset, fPostUpdate ) { } //--// public static LoadIndirectOperatorWithIndexUpdate New( Debugging.DebugInfo debugInfo , TypeRepresentation td , VariableExpression lhs , VariableExpression lhsIndex , VariableExpression rhsIndex , FieldRepresentation[] accessPath , int offset , bool fIsVolatile , bool fPostUpdate ) { OperatorCapabilities capabilities = OperatorCapabilities.IsNonCommutative | OperatorCapabilities.DoesNotAllocateStorage | OperatorCapabilities.MayReadExistingMutableStorage | // TODO: method analysis could discover the pointer is outside the stack. OperatorCapabilities.MayReadThroughPointerOperands | OperatorCapabilities.DoesNotWriteThroughPointerOperands | OperatorCapabilities.MayCapturePointerOperands | // TODO: Is it true? OperatorCapabilities.DoesNotThrow ; if(fIsVolatile) { capabilities |= OperatorCapabilities.MayMutateExistingStorage; } else { capabilities |= OperatorCapabilities.DoesNotMutateExistingStorage; } var res = new LoadIndirectOperatorWithIndexUpdate( debugInfo, capabilities, td, accessPath, offset, fPostUpdate ); res.SetLhs( lhs, lhsIndex ); res.SetRhs( rhsIndex ); return res; } //--// // // Helper Methods // public override Operator Clone( CloningContext context ) { TypeRepresentation td = context.ConvertType ( m_td ); FieldRepresentation[] accessPath = context.ConvertFields( m_accessPath ); return RegisterAndCloneState( context, new LoadIndirectOperatorWithIndexUpdate( m_debugInfo, m_capabilities, td, accessPath, m_offset, m_fPostUpdate ) ); } //--// // // Access Methods // //--// // // Debug Methods // public override void InnerToString( System.Text.StringBuilder sb ) { sb.Append( "LoadIndirectOperatorWithUpdate(" ); base.InnerToString( sb ); sb.Append( ")" ); } public override string FormatOutput( IIntermediateRepresentationDumper dumper ) { string fmt; if(m_fPostUpdate) { fmt = "{0},{1} <= [{2}],#{3} as {4}"; } else { fmt = "{0},{1} <= [{2},#{3}] as {4}"; } return dumper.FormatOutput( fmt, this.FirstResult, this.SecondResult, this.FirstArgument, m_offset, m_td ); } } } ================================================ FILE: Zelig/Zelig/CompileTime/TargetModels/ProductConfiguration/Abstractions/ARM/Operators/MoveFloatingPointRegistersOperator.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // namespace Microsoft.Zelig.Configuration.Environment.Abstractions.ARM { using System; using System.Collections.Generic; using Microsoft.Zelig.Runtime.TypeSystem; using Microsoft.Zelig.CodeGeneration.IR; public class MoveFloatingPointRegistersOperator : Operator { private const OperatorCapabilities cCapabilities = OperatorCapabilities.IsNonCommutative | OperatorCapabilities.DoesNotMutateExistingStorage | OperatorCapabilities.DoesNotAllocateStorage | OperatorCapabilities.DoesNotReadExistingMutableStorage | OperatorCapabilities.DoesNotThrow | OperatorCapabilities.DoesNotReadThroughPointerOperands | OperatorCapabilities.DoesNotWriteThroughPointerOperands | OperatorCapabilities.DoesNotCapturePointerOperands ; // // State // private bool m_fLoad; private bool m_fAddComputedRegisters; private uint m_registerLow; private uint m_registerHigh; // // Constructor Methods // private MoveFloatingPointRegistersOperator( Debugging.DebugInfo debugInfo , bool fLoad , bool fAddComputedRegisters , uint registerLow , uint registerHigh ) : base( debugInfo, cCapabilities, OperatorLevel.Lowest ) { m_fLoad = fLoad; m_fAddComputedRegisters = fAddComputedRegisters; m_registerLow = registerLow; m_registerHigh = registerHigh; } //--// public static MoveFloatingPointRegistersOperator New( Debugging.DebugInfo debugInfo , bool fLoad , bool fWriteBackIndexRegister , bool fAddComputedRegisters , uint registerLow , uint registerHigh , PhysicalRegisterExpression ex ) { var res = new MoveFloatingPointRegistersOperator( debugInfo, fLoad, fAddComputedRegisters, registerLow, registerHigh ); res.SetRhs( ex ); if(fWriteBackIndexRegister) { res.SetLhs( ex ); } return res; } //--// // // Helper Methods // public override Operator Clone( CloningContext context ) { return RegisterAndCloneState( context, new MoveFloatingPointRegistersOperator( m_debugInfo, m_fLoad, m_fAddComputedRegisters, m_registerLow, m_registerHigh ) ); } //--// public override void ApplyTransformation( TransformationContextForIR context ) { TransformationContextForCodeTransformation context2 = (TransformationContextForCodeTransformation)context; context2.Push( this ); base.ApplyTransformation( context2 ); context2.Transform( ref m_fLoad ); context2.Transform( ref m_fAddComputedRegisters ); context2.Transform( ref m_registerLow ); context2.Transform( ref m_registerHigh ); context2.Pop(); } //--// public override bool CanPropagateCopy( Expression exOld , Expression exNew ) { return false; } // // Access Methods // public override bool ShouldNotBeRemoved { [System.Diagnostics.DebuggerHidden] get { return true; } } public bool IsLoad { get { return m_fLoad; } } public bool ShouldWriteBackIndexRegister { get { return this.Results.Length != 0; } } public bool ShouldAddComputedRegisters { get { return m_fAddComputedRegisters; } } public uint RegisterLow { get { return m_registerLow; } } public uint RegisterHigh { get { return m_registerHigh; } } // // Debug Methods // public override void InnerToString( System.Text.StringBuilder sb ) { sb.AppendFormat( "MoveFloatingPointRegisters(Load={0}, AddComputedRegisters={1}, RegisterLow={2}, RegisterHigh={3}", m_fLoad, m_fAddComputedRegisters, m_registerLow, m_registerHigh ); base.InnerToString( sb ); sb.Append( ")" ); } public override string FormatOutput( IIntermediateRepresentationDumper dumper ) { string fmt; if(this.IsLoad) { fmt = " = [{4}]{3}"; } else { fmt = "[{4}]{3} = "; } return dumper.FormatOutput( fmt, this.RegisterLow, this.RegisterHigh, this.ShouldAddComputedRegisters ? " and scratched registers" : "", this.ShouldWriteBackIndexRegister ? "!" : "", this.FirstArgument ); } } } ================================================ FILE: Zelig/Zelig/CompileTime/TargetModels/ProductConfiguration/Abstractions/ARM/Operators/MoveFromCoprocessor.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // namespace Microsoft.Zelig.Configuration.Environment.Abstractions.ARM { using System; using System.Collections.Generic; using Microsoft.Zelig.Runtime.TypeSystem; using Microsoft.Zelig.CodeGeneration.IR; public class MoveFromCoprocessor : Operator { private const OperatorCapabilities cCapabilities = OperatorCapabilities.IsNonCommutative | OperatorCapabilities.DoesNotMutateExistingStorage | OperatorCapabilities.DoesNotAllocateStorage | OperatorCapabilities.DoesNotReadExistingMutableStorage | OperatorCapabilities.DoesNotThrow | OperatorCapabilities.DoesNotReadThroughPointerOperands | OperatorCapabilities.DoesNotWriteThroughPointerOperands | OperatorCapabilities.DoesNotCapturePointerOperands ; // // State // private uint m_CpNum; private uint m_Op1; private uint m_CRn; private uint m_CRm; private uint m_Op2; // // Constructor Methods // private MoveFromCoprocessor( Debugging.DebugInfo debugInfo , uint CpNum , uint Op1 , uint CRn , uint CRm , uint Op2 ) : base( debugInfo, cCapabilities, OperatorLevel.Lowest ) { m_CpNum = CpNum; m_Op1 = Op1; m_CRn = CRn; m_CRm = CRm; m_Op2 = Op2; } //--// public static MoveFromCoprocessor New( Debugging.DebugInfo debugInfo , uint CpNum , uint Op1 , uint CRn , uint CRm , uint Op2 , VariableExpression lhs ) { MoveFromCoprocessor res = new MoveFromCoprocessor( debugInfo, CpNum, Op1, CRn, CRm, Op2 ); res.SetLhs( lhs ); return res; } //--// // // Helper Methods // public override Operator Clone( CloningContext context ) { return RegisterAndCloneState( context, new MoveFromCoprocessor( m_debugInfo, m_CpNum, m_Op1, m_CRn, m_CRm, m_Op2 ) ); } //--// public override void ApplyTransformation( TransformationContextForIR context ) { TransformationContextForCodeTransformation context2 = (TransformationContextForCodeTransformation)context; context2.Push( this ); base.ApplyTransformation( context2 ); context2.Transform( ref m_CpNum ); context2.Transform( ref m_Op1 ); context2.Transform( ref m_CRn ); context2.Transform( ref m_CRm ); context2.Transform( ref m_Op2 ); context2.Pop(); } // // Access Methods // public override bool ShouldNotBeRemoved { [System.Diagnostics.DebuggerHidden] get { return true; } } public uint CpNum { get { return m_CpNum; } } public uint Op1 { get { return m_Op1; } } public uint CRn { get { return m_CRn; } } public uint CRm { get { return m_CRm; } } public uint Op2 { get { return m_Op2; } } // // Debug Methods // public override void InnerToString( System.Text.StringBuilder sb ) { sb.AppendFormat( "MoveFromCoprocessor(CpNum={0}, Op1={1}, CRn={2}, CRm={3}, Op2={4}", m_CpNum, m_Op1, m_CRn, m_CRm, m_Op2 ); base.InnerToString( sb ); sb.Append( ")" ); } public override string FormatOutput( IIntermediateRepresentationDumper dumper ) { return dumper.FormatOutput( "{5} = CoProc(CpNum={0}, Op1={1}, CRn={2}, CRm={3}, Op2={4})", m_CpNum, m_Op1, m_CRn, m_CRm, m_Op2, this.FirstResult ); } } } ================================================ FILE: Zelig/Zelig/CompileTime/TargetModels/ProductConfiguration/Abstractions/ARM/Operators/MoveIntegerRegistersOperator.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // namespace Microsoft.Zelig.Configuration.Environment.Abstractions.ARM { using System; using System.Collections.Generic; using Microsoft.Zelig.Runtime.TypeSystem; using Microsoft.Zelig.CodeGeneration.IR; public class MoveIntegerRegistersOperator : Operator { private const OperatorCapabilities cCapabilities = OperatorCapabilities.IsNonCommutative | OperatorCapabilities.DoesNotMutateExistingStorage | OperatorCapabilities.DoesNotAllocateStorage | OperatorCapabilities.DoesNotReadExistingMutableStorage | OperatorCapabilities.DoesNotThrow | OperatorCapabilities.DoesNotReadThroughPointerOperands | OperatorCapabilities.DoesNotWriteThroughPointerOperands | OperatorCapabilities.DoesNotCapturePointerOperands ; // // State // private bool m_fLoad; private bool m_fAddComputedRegisters; private bool m_fRestoreSPSR; private uint m_registerMask; // // Constructor Methods // private MoveIntegerRegistersOperator( Debugging.DebugInfo debugInfo , bool fLoad , bool fAddComputedRegisters , bool fRestoreSPSR , uint registerMask ) : base( debugInfo, cCapabilities, OperatorLevel.Lowest ) { m_fLoad = fLoad; m_fAddComputedRegisters = fAddComputedRegisters; m_fRestoreSPSR = fRestoreSPSR; m_registerMask = registerMask; } //--// public static MoveIntegerRegistersOperator New( Debugging.DebugInfo debugInfo , bool fLoad , bool fWriteBackIndexRegister , bool fAddComputedRegisters , bool fRestoreSPSR , uint registerMask , PhysicalRegisterExpression ex ) { var res = new MoveIntegerRegistersOperator( debugInfo, fLoad, fAddComputedRegisters, fRestoreSPSR, registerMask ); res.SetRhs( ex ); if(fWriteBackIndexRegister) { res.SetLhs( ex ); } return res; } //--// // // Helper Methods // public override Operator Clone( CloningContext context ) { return RegisterAndCloneState( context, new MoveIntegerRegistersOperator( m_debugInfo, m_fLoad, m_fAddComputedRegisters, m_fRestoreSPSR, m_registerMask ) ); } //--// public override void ApplyTransformation( TransformationContextForIR context ) { TransformationContextForCodeTransformation context2 = (TransformationContextForCodeTransformation)context; context2.Push( this ); base.ApplyTransformation( context2 ); context2.Transform( ref m_fLoad ); context2.Transform( ref m_fAddComputedRegisters ); context2.Transform( ref m_fRestoreSPSR ); context2.Transform( ref m_registerMask ); context2.Pop(); } //--// public override bool CanPropagateCopy( Expression exOld , Expression exNew ) { return false; } // // Access Methods // public override bool ShouldNotBeRemoved { [System.Diagnostics.DebuggerHidden] get { return true; } } public bool IsLoad { get { return m_fLoad; } } public bool ShouldWriteBackIndexRegister { get { return this.Results.Length != 0; } } public bool ShouldAddComputedRegisters { get { return m_fAddComputedRegisters; } } public bool ShouldRestoreSPSR { get { return m_fRestoreSPSR; } } public uint RegisterMask { get { return m_registerMask; } } // // Debug Methods // public override void InnerToString( System.Text.StringBuilder sb ) { sb.AppendFormat( "MoveIntegerRegisters(Load={0}, AddComputedRegisters={1}, RestoreSPSR={2} RegisterMask={3:X8}", m_fLoad, m_fAddComputedRegisters, m_fRestoreSPSR, m_registerMask ); base.InnerToString( sb ); sb.Append( ")" ); } public override string FormatOutput( IIntermediateRepresentationDumper dumper ) { string fmt; if(this.IsLoad) { if(this.ShouldRestoreSPSR) { fmt = ",SPSR = [{3}]{2}"; } else { fmt = " = [{3}]{2}"; } } else { fmt = "[{3}]{2} = "; } return dumper.FormatOutput( fmt, this.RegisterMask, this.ShouldAddComputedRegisters ? " and scratched registers" : "", this.ShouldWriteBackIndexRegister ? "!" : "", this.FirstArgument ); } } } ================================================ FILE: Zelig/Zelig/CompileTime/TargetModels/ProductConfiguration/Abstractions/ARM/Operators/MoveStackPointerOperator.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // namespace Microsoft.Zelig.Configuration.Environment.Abstractions.ARM { using System; using System.Collections.Generic; using Microsoft.Zelig.Runtime.TypeSystem; using Microsoft.Zelig.CodeGeneration.IR; public class MoveStackPointerOperator : Operator { private const OperatorCapabilities cCapabilities = OperatorCapabilities.IsNonCommutative | OperatorCapabilities.DoesNotMutateExistingStorage | OperatorCapabilities.DoesNotAllocateStorage | OperatorCapabilities.DoesNotReadExistingMutableStorage | OperatorCapabilities.DoesNotThrow | OperatorCapabilities.DoesNotReadThroughPointerOperands | OperatorCapabilities.DoesNotWriteThroughPointerOperands | OperatorCapabilities.DoesNotCapturePointerOperands ; // // State // private bool m_fPush; // // Constructor Methods // private MoveStackPointerOperator( Debugging.DebugInfo debugInfo , bool fPush ) : base( debugInfo, cCapabilities, OperatorLevel.Lowest ) { m_fPush = fPush; } //--// public static MoveStackPointerOperator New( Debugging.DebugInfo debugInfo , bool fPush ) { var res = new MoveStackPointerOperator( debugInfo, fPush ); return res; } //--// // // Helper Methods // public override Operator Clone( CloningContext context ) { return RegisterAndCloneState( context, new MoveStackPointerOperator( m_debugInfo, m_fPush ) ); } //--// public override void ApplyTransformation( TransformationContextForIR context ) { TransformationContextForCodeTransformation context2 = (TransformationContextForCodeTransformation)context; context2.Push( this ); base.ApplyTransformation( context2 ); context2.Transform( ref m_fPush ); context2.Pop(); } //--// public override bool CanPropagateCopy( Expression exOld , Expression exNew ) { return false; } // // Access Methods // public override bool ShouldNotBeRemoved { [System.Diagnostics.DebuggerHidden] get { return true; } } public bool IsPush { get { return m_fPush; } } // // Debug Methods // public override void InnerToString( System.Text.StringBuilder sb ) { sb.AppendFormat( "MoveStackPointerOperator({0}", m_fPush ? "Push" : "Pop" ); base.InnerToString( sb ); sb.Append( ")" ); } public override string FormatOutput( IIntermediateRepresentationDumper dumper ) { return dumper.FormatOutput( "{0}", m_fPush ? "" : "" ); } } } ================================================ FILE: Zelig/Zelig/CompileTime/TargetModels/ProductConfiguration/Abstractions/ARM/Operators/MoveToCoprocessor.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // namespace Microsoft.Zelig.Configuration.Environment.Abstractions.ARM { using System; using System.Collections.Generic; using Microsoft.Zelig.Runtime.TypeSystem; using Microsoft.Zelig.CodeGeneration.IR; public class MoveToCoprocessor : Operator { private const OperatorCapabilities cCapabilities = OperatorCapabilities.IsNonCommutative | OperatorCapabilities.DoesNotMutateExistingStorage | OperatorCapabilities.DoesNotAllocateStorage | OperatorCapabilities.DoesNotReadExistingMutableStorage | OperatorCapabilities.DoesNotThrow | OperatorCapabilities.DoesNotReadThroughPointerOperands | OperatorCapabilities.DoesNotWriteThroughPointerOperands | OperatorCapabilities.DoesNotCapturePointerOperands ; // // State // private uint m_CpNum; private uint m_Op1; private uint m_CRn; private uint m_CRm; private uint m_Op2; // // Constructor Methods // private MoveToCoprocessor( Debugging.DebugInfo debugInfo , uint CpNum , uint Op1 , uint CRn , uint CRm , uint Op2 ) : base( debugInfo, cCapabilities, OperatorLevel.Lowest ) { m_CpNum = CpNum; m_Op1 = Op1; m_CRn = CRn; m_CRm = CRm; m_Op2 = Op2; } //--// public static MoveToCoprocessor New( Debugging.DebugInfo debugInfo , uint CpNum , uint Op1 , uint CRn , uint CRm , uint Op2 , Expression ex ) { MoveToCoprocessor res = new MoveToCoprocessor( debugInfo, CpNum, Op1, CRn, CRm, Op2 ); res.SetRhs( ex ); return res; } //--// // // Helper Methods // public override Operator Clone( CloningContext context ) { return RegisterAndCloneState( context, new MoveToCoprocessor( m_debugInfo, m_CpNum, m_Op1, m_CRn, m_CRm, m_Op2 ) ); } //--// public override void ApplyTransformation( TransformationContextForIR context ) { TransformationContextForCodeTransformation context2 = (TransformationContextForCodeTransformation)context; context2.Push( this ); base.ApplyTransformation( context2 ); context2.Transform( ref m_CpNum ); context2.Transform( ref m_Op1 ); context2.Transform( ref m_CRn ); context2.Transform( ref m_CRm ); context2.Transform( ref m_Op2 ); context2.Pop(); } //--// public override bool CanPropagateCopy( Expression exOld , Expression exNew ) { if(exNew is ConstantExpression) { return false; } return true; } // // Access Methods // public override bool ShouldNotBeRemoved { [System.Diagnostics.DebuggerHidden] get { return true; } } public uint CpNum { get { return m_CpNum; } } public uint Op1 { get { return m_Op1; } } public uint CRn { get { return m_CRn; } } public uint CRm { get { return m_CRm; } } public uint Op2 { get { return m_Op2; } } // // Debug Methods // public override void InnerToString( System.Text.StringBuilder sb ) { sb.AppendFormat( "MoveToCoprocessor(CpNum={0}, Op1={1}, CRn={2}, CRm={3}, Op2={4}", m_CpNum, m_Op1, m_CRn, m_CRm, m_Op2 ); base.InnerToString( sb ); sb.Append( ")" ); } public override string FormatOutput( IIntermediateRepresentationDumper dumper ) { return dumper.FormatOutput( "CoProc(CpNum={0}, Op1={1}, CRn={2}, CRm={3}, Op2={4}) = {5}", m_CpNum, m_Op1, m_CRn, m_CRm, m_Op2, this.FirstArgument ); } } } ================================================ FILE: Zelig/Zelig/CompileTime/TargetModels/ProductConfiguration/Abstractions/ARM/Operators/SetStatusRegisterOperator.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // namespace Microsoft.Zelig.Configuration.Environment.Abstractions.ARM { using System; using System.Collections.Generic; using Microsoft.Zelig.Runtime.TypeSystem; using Microsoft.Zelig.CodeGeneration.IR; public sealed class SetStatusRegisterOperator : Operator { private const OperatorCapabilities cCapabilities = OperatorCapabilities.IsNonCommutative | OperatorCapabilities.DoesNotMutateExistingStorage | OperatorCapabilities.DoesNotAllocateStorage | OperatorCapabilities.DoesNotReadExistingMutableStorage | OperatorCapabilities.DoesNotThrow | OperatorCapabilities.DoesNotReadThroughPointerOperands | OperatorCapabilities.DoesNotWriteThroughPointerOperands | OperatorCapabilities.DoesNotCapturePointerOperands ; // // State // private bool m_fUseSPSR; private uint m_fields; // // Constructor Methods // private SetStatusRegisterOperator( Debugging.DebugInfo debugInfo , bool fUseSPSR , uint fields ) : base( debugInfo, cCapabilities, OperatorLevel.Lowest ) { m_fUseSPSR = fUseSPSR; m_fields = fields; } //--// public static SetStatusRegisterOperator New( Debugging.DebugInfo debugInfo , bool fUseSPSR , uint fields , Expression ex ) { SetStatusRegisterOperator res = new SetStatusRegisterOperator( debugInfo, fUseSPSR, fields ); res.SetRhs( ex ); return res; } //--// // // Helper Methods // public override Operator Clone( CloningContext context ) { return RegisterAndCloneState( context, new SetStatusRegisterOperator( m_debugInfo, m_fUseSPSR, m_fields ) ); } //--// public override void ApplyTransformation( TransformationContextForIR context ) { TransformationContextForCodeTransformation context2 = (TransformationContextForCodeTransformation)context; context2.Push( this ); base.ApplyTransformation( context2 ); context2.Transform( ref m_fUseSPSR ); context2.Transform( ref m_fields ); context2.Pop(); } //--// // // Access Methods // public bool UseSPSR { get { return m_fUseSPSR; } } public uint Fields { get { return m_fields; } } //--// public override bool ShouldNotBeRemoved { [System.Diagnostics.DebuggerHidden] get { return true; } } //--// // // Debug Methods // public override void InnerToString( System.Text.StringBuilder sb ) { sb.Append( "SetStatusRegisterOperator(" ); base.InnerToString( sb ); sb.Append( ")" ); } public override string FormatOutput( IIntermediateRepresentationDumper dumper ) { return dumper.FormatOutput( "<{0} status register:0x{1:X1}> = {2}", m_fUseSPSR ? "saved" : "current", m_fields, this.FirstArgument ); } } } ================================================ FILE: Zelig/Zelig/CompileTime/TargetModels/ProductConfiguration/Abstractions/ARM/Operators/StoreIndirectOperatorWithIndexUpdate.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // namespace Microsoft.Zelig.Configuration.Environment.Abstractions.ARM { using System; using System.Collections.Generic; using Microsoft.Zelig.Runtime.TypeSystem; using Microsoft.Zelig.CodeGeneration.IR; public sealed class StoreIndirectOperatorWithIndexUpdate : IndirectOperatorWithIndexUpdate { // // State // // // Constructor Methods // private StoreIndirectOperatorWithIndexUpdate( Debugging.DebugInfo debugInfo , OperatorCapabilities capabilities , TypeRepresentation td , FieldRepresentation[] accessPath , int offset , bool fPostUpdate ) : base( debugInfo, capabilities, td, accessPath, offset, fPostUpdate ) { } //--// public static StoreIndirectOperatorWithIndexUpdate New( Debugging.DebugInfo debugInfo , TypeRepresentation td , VariableExpression lhsAddr , Expression rhsAddr , Expression rhsValue , FieldRepresentation[] accessPath , int offset , bool fIsVolatile , bool fPostUpdate ) { OperatorCapabilities capabilities = OperatorCapabilities.IsNonCommutative | OperatorCapabilities.DoesNotAllocateStorage | OperatorCapabilities.MayReadExistingMutableStorage | // TODO: method analysis could discover the pointer is outside the stack. OperatorCapabilities.MayReadThroughPointerOperands | OperatorCapabilities.DoesNotWriteThroughPointerOperands | OperatorCapabilities.MayCapturePointerOperands | // TODO: Is it true? OperatorCapabilities.DoesNotThrow ; if(fIsVolatile) { capabilities |= OperatorCapabilities.MayMutateExistingStorage; } else { capabilities |= OperatorCapabilities.DoesNotMutateExistingStorage; } var res = new StoreIndirectOperatorWithIndexUpdate( debugInfo, capabilities, td, accessPath, offset, fPostUpdate ); res.SetLhs( lhsAddr ); res.SetRhs( rhsAddr, rhsValue ); return res; } //--// // // Helper Methods // public override Operator Clone( CloningContext context ) { TypeRepresentation td = context.ConvertType ( m_td ); FieldRepresentation[] accessPath = context.ConvertFields( m_accessPath ); return RegisterAndCloneState( context, new StoreIndirectOperatorWithIndexUpdate( m_debugInfo, m_capabilities, td, accessPath, m_offset, m_fPostUpdate ) ); } //--// // // Access Methods // //--// // // Debug Methods // public override void InnerToString( System.Text.StringBuilder sb ) { sb.Append( "StoreIndirectOperatorWithUpdate(" ); base.InnerToString( sb ); sb.Append( ")" ); } public override string FormatOutput( IIntermediateRepresentationDumper dumper ) { string fmt; if(m_fPostUpdate) { fmt = "{0} <= [{1}],#{3} <= {2} as {4}"; } else { fmt = "{0} <= [{1},#{3}] <= {2} as {4}"; } return dumper.FormatOutput( fmt, this.FirstResult, this.FirstArgument, this.SecondArgument, m_offset, m_td ); } } } ================================================ FILE: Zelig/Zelig/CompileTime/TargetModels/ProductConfiguration/Abstractions/ARM/Operators/VectorHack_Base.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // namespace Microsoft.Zelig.Configuration.Environment.Abstractions.ARM { using System; using System.Collections.Generic; using Microsoft.Zelig.Runtime.TypeSystem; using Microsoft.Zelig.CodeGeneration.IR; public abstract class VectorHack_Base : Operator { private const OperatorCapabilities cCapabilities = OperatorCapabilities.IsNonCommutative | OperatorCapabilities.DoesNotMutateExistingStorage | OperatorCapabilities.DoesNotAllocateStorage | OperatorCapabilities.DoesNotReadExistingMutableStorage | OperatorCapabilities.DoesNotThrow | OperatorCapabilities.DoesNotReadThroughPointerOperands | OperatorCapabilities.DoesNotWriteThroughPointerOperands | OperatorCapabilities.DoesNotCapturePointerOperands ; // // State // private int m_size; // // Constructor Methods // protected VectorHack_Base( Debugging.DebugInfo debugInfo , int size ) : base( debugInfo, cCapabilities, OperatorLevel.Lowest ) { m_size = size; } //--// // // Helper Methods // public override void ApplyTransformation( TransformationContextForIR context ) { TransformationContextForCodeTransformation context2 = (TransformationContextForCodeTransformation)context; context2.Push( this ); base.ApplyTransformation( context2 ); context2.Transform( ref m_size ); context2.Pop(); } //--// public override bool CanPropagateCopy( Expression exOld , Expression exNew ) { return false; } // // Access Methods // public override bool ShouldNotBeRemoved { [System.Diagnostics.DebuggerHidden] get { return true; } } public int Size { get { return m_size; } } // // Debug Methods // } } ================================================ FILE: Zelig/Zelig/CompileTime/TargetModels/ProductConfiguration/Abstractions/ARM/Operators/VectorHack_Cleanup.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // namespace Microsoft.Zelig.Configuration.Environment.Abstractions.ARM { using System; using System.Collections.Generic; using Microsoft.Zelig.Runtime.TypeSystem; using Microsoft.Zelig.CodeGeneration.IR; public class VectorHack_Cleanup : VectorHack_Base { // // State // // // Constructor Methods // private VectorHack_Cleanup( Debugging.DebugInfo debugInfo , int size ) : base( debugInfo, size ) { } //--// public static VectorHack_Cleanup New( Debugging.DebugInfo debugInfo , int size ) { VectorHack_Cleanup res = new VectorHack_Cleanup( debugInfo, size ); return res; } //--// // // Helper Methods // public override Operator Clone( CloningContext context ) { return RegisterAndCloneState( context, new VectorHack_Cleanup( m_debugInfo, this.Size ) ); } //--// // // Access Methods // // // Debug Methods // public override void InnerToString( System.Text.StringBuilder sb ) { sb.AppendFormat( "VectorHack_Cleanup(Size={0}", this.Size ); base.InnerToString( sb ); sb.Append( ")" ); } public override string FormatOutput( IIntermediateRepresentationDumper dumper ) { return dumper.FormatOutput( "VectorHack_Cleanup(Size={0})", this.Size ); } } } ================================================ FILE: Zelig/Zelig/CompileTime/TargetModels/ProductConfiguration/Abstractions/ARM/Operators/VectorHack_Finalize.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // namespace Microsoft.Zelig.Configuration.Environment.Abstractions.ARM { using System; using System.Collections.Generic; using Microsoft.Zelig.Runtime.TypeSystem; using Microsoft.Zelig.CodeGeneration.IR; using ZeligIR = Microsoft.Zelig.CodeGeneration.IR; public class VectorHack_Finalize : VectorHack_Base { // // State // private ZeligIR.Abstractions.RegisterDescriptor m_resultBankBase; // // Constructor Methods // private VectorHack_Finalize( Debugging.DebugInfo debugInfo , int size , ZeligIR.Abstractions.RegisterDescriptor resultBankBase ) : base( debugInfo, size ) { m_resultBankBase = resultBankBase; } //--// public static VectorHack_Finalize New( Debugging.DebugInfo debugInfo , int size , ZeligIR.Abstractions.RegisterDescriptor resultBankBase , VariableExpression lhs ) { VectorHack_Finalize res = new VectorHack_Finalize( debugInfo, size, resultBankBase ); res.SetLhs( lhs ); return res; } //--// // // Helper Methods // public override Operator Clone( CloningContext context ) { return RegisterAndCloneState( context, new VectorHack_Finalize( m_debugInfo, this.Size, m_resultBankBase ) ); } //--// public override void ApplyTransformation( TransformationContextForIR context ) { TransformationContextForCodeTransformation context2 = (TransformationContextForCodeTransformation)context; context2.Push( this ); base.ApplyTransformation( context2 ); context2.Transform( ref m_resultBankBase ); context2.Pop(); } //--// // // Access Methods // public ZeligIR.Abstractions.RegisterDescriptor ResultBankBase { get { return m_resultBankBase; } } // // Debug Methods // public override void InnerToString( System.Text.StringBuilder sb ) { sb.AppendFormat( "VectorHack_Finalize(Size={0},Base={1}", this.Size, m_resultBankBase.Mnemonic ); base.InnerToString( sb ); sb.Append( ")" ); } public override string FormatOutput( IIntermediateRepresentationDumper dumper ) { return dumper.FormatOutput( "{0} = VectorHack_Finalize(Size={1},Base={2})", this.FirstResult, this.Size, m_resultBankBase.Mnemonic ); } } } ================================================ FILE: Zelig/Zelig/CompileTime/TargetModels/ProductConfiguration/Abstractions/ARM/Operators/VectorHack_Initialize.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // namespace Microsoft.Zelig.Configuration.Environment.Abstractions.ARM { using System; using System.Collections.Generic; using Microsoft.Zelig.Runtime.TypeSystem; using Microsoft.Zelig.CodeGeneration.IR; public class VectorHack_Initialize : VectorHack_Base { // // State // // // Constructor Methods // private VectorHack_Initialize( Debugging.DebugInfo debugInfo , int size ) : base( debugInfo, size ) { } //--// public static VectorHack_Initialize New( Debugging.DebugInfo debugInfo , int size ) { VectorHack_Initialize res = new VectorHack_Initialize( debugInfo, size ); return res; } //--// // // Helper Methods // public override Operator Clone( CloningContext context ) { return RegisterAndCloneState( context, new VectorHack_Initialize( m_debugInfo, this.Size ) ); } //--// // // Access Methods // // // Debug Methods // public override void InnerToString( System.Text.StringBuilder sb ) { sb.AppendFormat( "VectorHack_Initialize(Size={0}", this.Size ); base.InnerToString( sb ); sb.Append( ")" ); } public override string FormatOutput( IIntermediateRepresentationDumper dumper ) { return dumper.FormatOutput( "VectorHack_Initialize(Size={0})", this.Size ); } } } ================================================ FILE: Zelig/Zelig/CompileTime/TargetModels/ProductConfiguration/Abstractions/ARM/Operators/VectorHack_LoadData.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // namespace Microsoft.Zelig.Configuration.Environment.Abstractions.ARM { using System; using System.Collections.Generic; using Microsoft.Zelig.Runtime.TypeSystem; using Microsoft.Zelig.CodeGeneration.IR; using ZeligIR = Microsoft.Zelig.CodeGeneration.IR; public class VectorHack_LoadData : VectorHack_Base { // // State // private ZeligIR.Abstractions.RegisterDescriptor m_destinationBankBase; // // Constructor Methods // private VectorHack_LoadData( Debugging.DebugInfo debugInfo , int size , ZeligIR.Abstractions.RegisterDescriptor destinationBankBase ) : base( debugInfo, size ) { m_destinationBankBase = destinationBankBase; } //--// public static VectorHack_LoadData New( Debugging.DebugInfo debugInfo , int size , ZeligIR.Abstractions.RegisterDescriptor destinationBankBase , VariableExpression lhs , Expression rhs ) { VectorHack_LoadData res = new VectorHack_LoadData( debugInfo, size, destinationBankBase ); res.SetLhs( lhs ); res.SetRhs( rhs ); return res; } //--// // // Helper Methods // public override Operator Clone( CloningContext context ) { return RegisterAndCloneState( context, new VectorHack_LoadData( m_debugInfo, this.Size, m_destinationBankBase ) ); } //--// public override void ApplyTransformation( TransformationContextForIR context ) { TransformationContextForCodeTransformation context2 = (TransformationContextForCodeTransformation)context; context2.Push( this ); base.ApplyTransformation( context2 ); context2.Transform( ref m_destinationBankBase ); context2.Pop(); } //--// // // Access Methods // public ZeligIR.Abstractions.RegisterDescriptor DestinationBankBase { get { return m_destinationBankBase; } } // // Debug Methods // public override void InnerToString( System.Text.StringBuilder sb ) { sb.AppendFormat( "VectorHack_LoadData(Size={0},Base={1}", this.Size, m_destinationBankBase.Mnemonic ); base.InnerToString( sb ); sb.Append( ")" ); } public override string FormatOutput( IIntermediateRepresentationDumper dumper ) { return dumper.FormatOutput( "{0} = VectorHack_LoadData(Size={1},Base={2})[{3}]", this.FirstResult, this.Size, m_destinationBankBase.Mnemonic, this.FirstArgument ); } } } ================================================ FILE: Zelig/Zelig/CompileTime/TargetModels/ProductConfiguration/Abstractions/ARM/Operators/VectorHack_MultiplyAndAccumulate.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // namespace Microsoft.Zelig.Configuration.Environment.Abstractions.ARM { using System; using System.Collections.Generic; using Microsoft.Zelig.Runtime.TypeSystem; using Microsoft.Zelig.CodeGeneration.IR; using ZeligIR = Microsoft.Zelig.CodeGeneration.IR; public class VectorHack_MultiplyAndAccumulate : VectorHack_Base { // // State // private ZeligIR.Abstractions.RegisterDescriptor m_leftBankBase; private ZeligIR.Abstractions.RegisterDescriptor m_rightBankBase; private ZeligIR.Abstractions.RegisterDescriptor m_resultBankBase; // // Constructor Methods // private VectorHack_MultiplyAndAccumulate( Debugging.DebugInfo debugInfo , int size , ZeligIR.Abstractions.RegisterDescriptor leftBankBase , ZeligIR.Abstractions.RegisterDescriptor rightBankBase , ZeligIR.Abstractions.RegisterDescriptor resultBankBase ) : base( debugInfo, size ) { m_leftBankBase = leftBankBase; m_rightBankBase = rightBankBase; m_resultBankBase = resultBankBase; } //--// public static VectorHack_MultiplyAndAccumulate New( Debugging.DebugInfo debugInfo , int size , ZeligIR.Abstractions.RegisterDescriptor leftBankBase , ZeligIR.Abstractions.RegisterDescriptor rightBankBase , ZeligIR.Abstractions.RegisterDescriptor resultBankBase ) { VectorHack_MultiplyAndAccumulate res = new VectorHack_MultiplyAndAccumulate( debugInfo, size, leftBankBase, rightBankBase, resultBankBase ); return res; } //--// // // Helper Methods // public override Operator Clone( CloningContext context ) { return RegisterAndCloneState( context, new VectorHack_MultiplyAndAccumulate( m_debugInfo, this.Size, m_leftBankBase, m_rightBankBase, m_resultBankBase ) ); } //--// public override void ApplyTransformation( TransformationContextForIR context ) { TransformationContextForCodeTransformation context2 = (TransformationContextForCodeTransformation)context; context2.Push( this ); base.ApplyTransformation( context2 ); context2.Transform( ref m_leftBankBase ); context2.Transform( ref m_rightBankBase ); context2.Transform( ref m_resultBankBase ); context2.Pop(); } //--// // // Access Methods // public ZeligIR.Abstractions.RegisterDescriptor LeftBankBase { get { return m_leftBankBase; } } public ZeligIR.Abstractions.RegisterDescriptor RightBankBase { get { return m_rightBankBase; } } public ZeligIR.Abstractions.RegisterDescriptor ResultBankBase { get { return m_resultBankBase; } } // // Debug Methods // public override void InnerToString( System.Text.StringBuilder sb ) { sb.AppendFormat( "VectorHack_MultiplyAndAccumulate(Size={0},LeftBase={1},RightBase={2},ResultBase={3}", this.Size, m_leftBankBase.Mnemonic, m_rightBankBase.Mnemonic, m_resultBankBase.Mnemonic ); base.InnerToString( sb ); sb.Append( ")" ); } public override string FormatOutput( IIntermediateRepresentationDumper dumper ) { return dumper.FormatOutput( "VectorHack_MultiplyAndAccumulate(Size={0},LeftBase={1},RightBase={2},ResultBase={3})", this.Size, m_leftBankBase.Mnemonic, m_rightBankBase.Mnemonic, m_resultBankBase.Mnemonic ); } } } ================================================ FILE: Zelig/Zelig/CompileTime/TargetModels/ProductConfiguration/Abstractions/ARM/Operators/VectorHack_Prepare.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // namespace Microsoft.Zelig.Configuration.Environment.Abstractions.ARM { using System; using System.Collections.Generic; using Microsoft.Zelig.Runtime.TypeSystem; using Microsoft.Zelig.CodeGeneration.IR; using ZeligIR = Microsoft.Zelig.CodeGeneration.IR; public class VectorHack_Prepare : VectorHack_Base { // // State // private ZeligIR.Abstractions.RegisterDescriptor m_resultBankBase; // // Constructor Methods // private VectorHack_Prepare( Debugging.DebugInfo debugInfo , int size , ZeligIR.Abstractions.RegisterDescriptor resultBankBase ) : base( debugInfo, size ) { m_resultBankBase = resultBankBase; } //--// public static VectorHack_Prepare New( Debugging.DebugInfo debugInfo , int size , ZeligIR.Abstractions.RegisterDescriptor resultBankBase ) { VectorHack_Prepare res = new VectorHack_Prepare( debugInfo, size, resultBankBase ); return res; } //--// // // Helper Methods // public override Operator Clone( CloningContext context ) { return RegisterAndCloneState( context, new VectorHack_Prepare( m_debugInfo, this.Size, m_resultBankBase ) ); } //--// public override void ApplyTransformation( TransformationContextForIR context ) { TransformationContextForCodeTransformation context2 = (TransformationContextForCodeTransformation)context; context2.Push( this ); base.ApplyTransformation( context2 ); context2.Transform( ref m_resultBankBase ); context2.Pop(); } //--// // // Access Methods // public ZeligIR.Abstractions.RegisterDescriptor ResultBankBase { get { return m_resultBankBase; } } // // Debug Methods // public override void InnerToString( System.Text.StringBuilder sb ) { sb.AppendFormat( "VectorHack_Prepare(Size={0},Base={1}", this.Size, m_resultBankBase.Mnemonic ); base.InnerToString( sb ); sb.Append( ")" ); } public override string FormatOutput( IIntermediateRepresentationDumper dumper ) { return dumper.FormatOutput( "VectorHack_Prepare(Size={0},Base={1})", this.Size, m_resultBankBase.Mnemonic ); } } } ================================================ FILE: Zelig/Zelig/CompileTime/TargetModels/ProductConfiguration/Abstractions/LLVMforZelig/LlvmForArmV6M.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // namespace Microsoft.Zelig.Configuration.Environment.Abstractions.Architectures { using Microsoft.Zelig.Runtime.TypeSystem; using Microsoft.Zelig.TargetModel.ArmProcessor; using System; using System.Collections.Generic; using ZeligIR = Microsoft.Zelig.CodeGeneration.IR; public sealed class LlvmForArmV6M : ArmPlatform { private const Capabilities c_ProcessorCapabilities = Capabilities.ARMv6M; // // State // // // Constructor Methods // public LlvmForArmV6M( ZeligIR.TypeSystemForCodeTransformation typeSystem, MemoryMapCategory memoryMap ) : base( typeSystem, memoryMap, c_ProcessorCapabilities ) { } public override void RegisterForNotifications( ZeligIR.TypeSystemForCodeTransformation ts, ZeligIR.CompilationSteps.DelegationCache cache ) { base.RegisterForNotifications( ts, cache ); cache.Register( new ZeligIR.CompilationSteps.Handlers.SoftwareFloatingPoint() ); cache.Register( new ArmV4.Optimizations( this ) ); } public override ZeligIR.ImageBuilders.CompilationState CreateCompilationState( ZeligIR.ImageBuilders.Core core, ZeligIR.ControlFlowGraphStateForCodeTransformation cfg ) { return new LlvmForArmV7MCompilationState( core, cfg ); } //--// // // Access Methods // public override string CodeGenerator { get { return InstructionSetVersion.CodeGenerator_LLVM; } } public override uint PlatformFamily { get { return InstructionSetVersion.Platform_Family__Cortex; } } public override uint PlatformVersion { get { return InstructionSetVersion.Platform_Version__ARMv6M; } } public override uint PlatformVFP { get { return InstructionSetVersion.Platform_VFP__NoVFP; } } public override bool PlatformBigEndian { get { return false; } } //--// public override TypeRepresentation GetMethodWrapperType( ) { return m_typeSystem.GetWellKnownType( "Microsoft_Zelig_ARMv6ForLlvm_MethodWrapper" ); } // // Not implememted, and used only during machine code emission // public override bool HasRegisterContextArgument( MethodRepresentation md ) { //////if(md.ThisPlusArguments.Length > 1) //////{ ////// TypeRepresentation td = md.ThisPlusArguments[1]; ////// if(td is PointerTypeRepresentation) ////// { ////// td = td.UnderlyingType; ////// if(td == m_typeSystem.GetWellKnownType( "Microsoft_Zelig_ProcessorARMv6M_RegistersOnStack" )) ////// { ////// return true; ////// } ////// } //////} return false; } public override void ComputeSetOfRegistersToSave( ZeligIR.Abstractions.CallingConvention cc, ZeligIR.ControlFlowGraphStateForCodeTransformation cfg, BitVector modifiedRegisters, out BitVector registersToSave, out Runtime.HardwareException he ) { throw new Exception( "ComputeSetOfRegistersToSave not implemented" ); } //--// protected override void ComputeRegisterFlushFixup( BitVector registersToSave ) { throw new Exception( "ComputeRegisterFlushFixup not implemented" ); } } } ================================================ FILE: Zelig/Zelig/CompileTime/TargetModels/ProductConfiguration/Abstractions/LLVMforZelig/LlvmForArmV7M.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // namespace Microsoft.Zelig.Configuration.Environment.Abstractions.Architectures { using Microsoft.Zelig.Runtime.TypeSystem; using Microsoft.Zelig.TargetModel.ArmProcessor; using System; using System.Collections.Generic; using ZeligIR = Microsoft.Zelig.CodeGeneration.IR; public sealed class LlvmForArmV7M : ArmPlatform { private const Capabilities c_ProcessorCapabilities = Capabilities.ARMv7M; // // State // // // Constructor Methods // public LlvmForArmV7M( ZeligIR.TypeSystemForCodeTransformation typeSystem, MemoryMapCategory memoryMap ) : base( typeSystem, memoryMap, c_ProcessorCapabilities ) { } public override void RegisterForNotifications( ZeligIR.TypeSystemForCodeTransformation ts, ZeligIR.CompilationSteps.DelegationCache cache ) { base.RegisterForNotifications( ts, cache ); cache.Register( new ZeligIR.CompilationSteps.Handlers.SoftwareFloatingPoint() ); cache.Register( new ArmV4.Optimizations( this ) ); } public override ZeligIR.ImageBuilders.CompilationState CreateCompilationState( ZeligIR.ImageBuilders.Core core, ZeligIR.ControlFlowGraphStateForCodeTransformation cfg ) { return new LlvmForArmV7MCompilationState( core, cfg ); } //--// // // Access Methods // public override string CodeGenerator { get { return InstructionSetVersion.CodeGenerator_LLVM; } } public override uint PlatformFamily { get { return InstructionSetVersion.Platform_Family__Cortex; } } public override uint PlatformVersion { get { return InstructionSetVersion.Platform_Version__ARMv7M; } } public override uint PlatformVFP { get { return InstructionSetVersion.Platform_VFP__SoftVFP; } } public override bool PlatformBigEndian { get { return false; } } //--// public override TypeRepresentation GetMethodWrapperType( ) { return m_typeSystem.GetWellKnownType( "Microsoft_Zelig_ARMv7ForLlvm_MethodWrapper" ); } // // Not implemented, and used only during machine code emission // public override bool HasRegisterContextArgument( MethodRepresentation md ) { //////if(md.ThisPlusArguments.Length > 1) //////{ ////// TypeRepresentation td = md.ThisPlusArguments[1]; ////// if(td is PointerTypeRepresentation) ////// { ////// td = td.UnderlyingType; ////// if(td == m_typeSystem.GetWellKnownType( "Microsoft_Zelig_ProcessorARMv7M_RegistersOnStack" )) ////// { ////// return true; ////// } ////// } //////} return false; } public override void ComputeSetOfRegistersToSave( ZeligIR.Abstractions.CallingConvention cc, ZeligIR.ControlFlowGraphStateForCodeTransformation cfg, BitVector modifiedRegisters, out BitVector registersToSave, out Runtime.HardwareException he ) { throw new Exception( "ComputeSetOfRegistersToSave not implemented" ); } //--// protected override void ComputeRegisterFlushFixup( BitVector registersToSave ) { throw new Exception( "ComputeRegisterFlushFixup not implemented" ); } } } ================================================ FILE: Zelig/Zelig/CompileTime/TargetModels/ProductConfiguration/Abstractions/LLVMforZelig/LlvmForArmV7MCallingConvention.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // namespace Microsoft.Zelig.Configuration.Environment.Abstractions.Architectures { using System; using System.Collections.Generic; using Microsoft.Zelig.Runtime.TypeSystem; using Microsoft.Zelig.TargetModel.ArmProcessor; using ZeligIR = Microsoft.Zelig.CodeGeneration.IR; public class LlvmForArmV7MCallingConvention : ArmCallingConvention { public LlvmForArmV7MCallingConvention( ZeligIR.TypeSystemForCodeTransformation typeSystem ) : base( typeSystem ) { } public override void RegisterForNotifications( ZeligIR.TypeSystemForCodeTransformation ts, ZeligIR.CompilationSteps.DelegationCache cache ) { } //--// //////public override CallState CreateCallState( Direction direction ) //////{ ////// throw new Exception( "CreateCallState not implemented" ); //////} //////public override ZeligIR.Expression[] AssignArgument( ZeligIR.ControlFlowGraphStateForCodeTransformation cfg, ////// ZeligIR.Operator insertionOp, ////// ZeligIR.Expression ex, ////// TypeRepresentation td, ////// ZeligIR.Abstractions.CallingConvention.CallState callState ) //////{ ////// throw new Exception( "AssignArgument not implemented" ); //////} //////public override ZeligIR.Expression[] AssignReturnValue( ZeligIR.ControlFlowGraphStateForCodeTransformation cfg, ////// ZeligIR.Operator insertionOp, ////// ZeligIR.VariableExpression exReturnValue, ////// TypeRepresentation tdReturnValue, ////// ZeligIR.Abstractions.CallingConvention.CallState callState ) //////{ ////// throw new Exception( "AssignReturnValue not implemented" ); //////} //////public override ZeligIR.VariableExpression[] CollectExpressionsToInvalidate( ZeligIR.ControlFlowGraphStateForCodeTransformation cfg, ////// ZeligIR.CallOperator op, ////// ZeligIR.Expression[] resFragments ) //////{ ////// throw new Exception( "CollectExpressionsToInvalidate not implemented" ); //////} //////public override bool ShouldSaveRegister( ZeligIR.Abstractions.RegisterDescriptor regDesc ) //////{ ////// throw new Exception( "ShouldSaveRegister not implemented" ); //////} } } ================================================ FILE: Zelig/Zelig/CompileTime/TargetModels/ProductConfiguration/Abstractions/LLVMforZelig/LlvmForArmV7MCompilationState.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // namespace Microsoft.Zelig.Configuration.Environment.Abstractions.Architectures { using System; using System.Collections.Generic; using Microsoft.Zelig.LLVM; using ZeligIR = Microsoft.Zelig.CodeGeneration.IR; using TS = Microsoft.Zelig.Runtime.TypeSystem; public partial class LlvmForArmV7MCompilationState : ArmCompilationState { private _Function m_function; private LLVMModuleManager m_manager; private TS.MethodRepresentation m_method; private TS.WellKnownFields m_wkf; private TS.WellKnownTypes m_wkt; private GrowOnlyHashTable m_localValues; private GrowOnlyHashTable m_blocks; protected LlvmForArmV7MCompilationState( ) // Default constructor required by TypeSystemSerializer. { } internal LlvmForArmV7MCompilationState( ZeligIR.ImageBuilders.Core owner, ZeligIR.ControlFlowGraphStateForCodeTransformation cfg ) : base( owner, cfg ) { var typeSystem = owner.TypeSystem; m_manager = typeSystem.Module; m_method = cfg.Method; m_wkf = typeSystem.WellKnownFields; m_wkt = typeSystem.WellKnownTypes; m_localValues = HashTableFactory.New(); m_blocks = HashTableFactory.New(); // // HACK!!! Support Windows on its own compilation abstraction // //m_manager.SectionNameProvider = new Thumb2EabiSectionNameProvider( typeSystem ); if (typeSystem.PlatformAbstraction.PlatformFamily == TargetModel.Win32.InstructionSetVersion.Platform_Family__Win32) { m_manager.SectionNameProvider = new Win32SectionNameProvider(typeSystem); } else { m_manager.SectionNameProvider = new Thumb2EabiSectionNameProvider(typeSystem); } } // // Helper Methods // public override void ApplyTransformation( ZeligIR.TransformationContextForCodeTransformation context ) { context.Push( this ); base.ApplyTransformation( context ); context.Pop( ); } //--// protected override void PrepareDataStructures( ) { base.PrepareDataStructures( ); m_function = m_manager.GetOrInsertFunction( m_method ); m_function.SetInternalLinkage( ); m_manager .ConvertTypeLayoutsToLLVM( ); ReleaseAllLocks( ); } //protected ZeligIR.Abstractions.RegisterDescriptor GetNextRegister( ZeligIR.Abstractions.RegisterDescriptor reg ) //{ // ZeligIR.Abstractions.Platform pa = m_cfg.TypeSystem.PlatformAbstraction; // return pa.GetRegisterForEncoding( reg.Encoding + 1 ); //} //--// protected override void AssignStackLocations_RecordRegister( ZeligIR.PhysicalRegisterExpression regVar ) { } protected override void AssignStackLocations_RecordStackOut( ZeligIR.StackLocationExpression stackVar ) { } protected override void AssignStackLocations_RecordStackLocal( List states ) { } protected override void AssignStackLocations_Finalize( ) { } protected override void FixupEmptyRegion( ZeligIR.ImageBuilders.SequentialRegion reg ) { // // TODO: lt72: enable proper encoding // var sec = reg.GetSectionOfFixedSize( sizeof(uint) ); //InstructionSet.Opcode_Breakpoint enc = this.Encoder.PrepareForBreakpoint; //enc.Prepare( EncodingDefinition_ARM.c_cond_AL, // uint ConditionCodes , // 0xFFFF ); // uint Value ); sec.Write( 0xDEADBEEF ); } protected override void DumpOpcodes( System.IO.TextWriter textWriter ) { } // // Access Methods // public LlvmForArmV7M LLVMPlatform { get { return ( LlvmForArmV7M )m_cfg.TypeSystem.PlatformAbstraction; } } } } ================================================ FILE: Zelig/Zelig/CompileTime/TargetModels/ProductConfiguration/Abstractions/LLVMforZelig/LlvmForArmV7MCompilationState_BasicBlocks.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // //#define GENERATE_ONLY_TYPESYSTEM_AND_FUNCTION_DEFINITIONS namespace Microsoft.Zelig.Configuration.Environment.Abstractions.Architectures { using System; using System.Collections.Generic; using System.Diagnostics; using Llvm.NET.Values; using Microsoft.Zelig.LLVM; using IR = Microsoft.Zelig.CodeGeneration.IR; using TS = Microsoft.Zelig.Runtime.TypeSystem; public partial class LlvmForArmV7MCompilationState { private _BasicBlock m_basicBlock; private _BasicBlock GetOrInsertBasicBlock(IR.BasicBlock block) { _BasicBlock llvmBlock; if( m_blocks.TryGetValue( block, out llvmBlock ) ) { return llvmBlock; } llvmBlock = m_function.GetOrInsertBasicBlock( block.ToShortString( ) ); m_blocks.Add( block, llvmBlock ); return llvmBlock; } private _BasicBlock SplitCurrentBlock() { // REVIEW: This can result in chains of ".next.next.next...". In the future it may be // better to name these in a prettier fashion ".next1", ".next2", ... return m_function.GetOrInsertBasicBlock(m_basicBlock.Name + ".next"); } public override void EmitCodeForBasicBlock( IR.BasicBlock bb ) { #if GENERATE_ONLY_TYPESYSTEM_AND_FUNCTION_DEFINITIONS m_manager.TurnOffCompilationAndValidation( ); m_function.SetExternalLinkage( ); m_basicBlock = null; #else // GENERATE_ONLY_TYPESYSTEM_AND_FUNCTION_DEFINITIONS m_basicBlock = GetOrInsertBasicBlock( bb ); // If this is the entry block, set up local variable storage. if( bb == m_basicBlocks[ 0 ] ) { var defChains = m_cfg.DataFlow_DefinitionChains; var useChains = m_cfg.DataFlow_UseChains; foreach( IR.VariableExpression exp in m_variables ) { Debug.Assert( exp.SpanningTreeIndex >= 0, "Encountered unreachable expression; expected removal in prior phase: " + exp ); // Skip unused variables. These can exist when a value is aliased, but not otherwise referenced. if( ( defChains[exp.SpanningTreeIndex].Length == 0 ) && ( useChains[exp.SpanningTreeIndex].Length == 0 ) ) { continue; } Debug.Assert( !m_localValues.ContainsKey( exp ), "Found multiple definitions for expression: " + exp ); CreateValueCache( exp, defChains, useChains ); } } foreach( var op in bb.Operators ) { if ( EmitCodeForBasicBlock_ShouldSkip( op ) ) { continue; } TranslateOperator( op, bb ); } #endif // GENERATE_ONLY_TYPESYSTEM_AND_FUNCTION_DEFINITIONS } protected override bool EmitCodeForBasicBlock_ShouldSkip( IR.Operator op ) { return base.EmitCodeForBasicBlock_ShouldSkip( op ); } protected override uint EmitCodeForBasicBlock_EstimateMinimumSize( IR.Operator op ) { return sizeof(uint); } protected override void EmitCodeForBasicBlock_EmitOperator( IR.Operator op ) { throw new Exception( "EmitCodeForBasicBlock_EmitOperator not implemented." ); } protected override void EmitCodeForBasicBlock_FlushOperators( ) { } private void CreateValueCache(IR.VariableExpression expr, IR.Operator[][] defChains, IR.Operator[][] useChains) { Debug.Assert(expr.AliasedVariable == expr, "Aliased variables are currently unsupported."); // Get or create a slot for the backing variable. if (!m_localValues.ContainsKey(expr)) { ValueCache valueCache; if (RequiresAddress(expr, defChains, useChains)) { Value address = m_function.GetLocalStackValue(m_method, m_basicBlock, expr, m_manager); valueCache = new ValueCache(expr, address); } else { valueCache = new ValueCache(expr, m_manager.GetOrInsertType(expr.Type)); } m_localValues[expr] = valueCache; } } private bool RequiresAddress(IR.VariableExpression expr, IR.Operator[][] defChains, IR.Operator[][] useChains) { // LLVM needs an address to attach debug info, so give an address to all named variables. if (!string.IsNullOrWhiteSpace(expr.DebugName?.Name)) { return true; } // If the variable has more than one definition, give it an address instead of a phi node. if (defChains[expr.SpanningTreeIndex].Length > 1) { return true; } // If any operator takes the variable's address, it must be addressable. foreach (IR.Operator useOp in useChains[expr.SpanningTreeIndex]) { // Address assignment operators take their argument's address by definition. if (useOp is IR.AddressAssignmentOperator) { return true; } // Field accessors need the first argument to be an address, so value types need to stay indirected. if ((useOp is IR.StoreInstanceFieldOperator) || (useOp is IR.LoadInstanceFieldOperator) || (useOp is IR.LoadInstanceFieldAddressOperator)) { if ((expr == useOp.FirstArgument) && (expr.Type is TS.ValueTypeRepresentation)) { return true; } } } return false; } private Value GetImmediate(IR.BasicBlock block, IR.Expression expression) { return GetValue(block, expression, wantImmediate: true, allowLoad: true); } private Value GetAddress(IR.BasicBlock block, IR.Expression expression) { return GetValue(block, expression, wantImmediate: false, allowLoad: false); } private Value GetValue(IR.BasicBlock block, IR.Expression exp, bool wantImmediate, bool allowLoad) { if ( !IsSuitableForLLVMTranslation( exp ) ) { throw new System.InvalidOperationException( "Llilum output too low level." ); } if( exp is IR.VariableExpression ) { ValueCache valueCache = m_localValues[ exp ]; // If we don't need to load the value, just return the address. if( !wantImmediate ) { Debug.Assert( valueCache.IsAddressable ); return valueCache.Address; } // Never cache addressable values since we don't easily know when they'll be modified. // Instead, reload at each operator. Unnecessary loads will be optimized out by LLVM. if( valueCache.IsAddressable ) { return m_basicBlock.InsertLoad( valueCache.Address ); } // If we already have a cached value for this expression there's no need to load it again. Value value = valueCache.GetValueFromBlock(block); if (value != null) { return value; } // This value isn't addressable so it must have been set in a previous block. IR.BasicBlock idom = m_immediateDominators[ block.SpanningTreeIndex ]; if( idom == block ) { // This is the entry block so there's no predecessor to search. throw new InvalidOperationException( $"Encountered use of expression with no definition. Expression {exp} in {block.Owner.Method}" ); } value = GetValue(idom, exp, wantImmediate, allowLoad); valueCache.SetValueForBlock(block, value); return value; } if ( exp is IR.ConstantExpression ) { IR.ConstantExpression ce = ( IR.ConstantExpression )exp; if( ce.Value == null ) { Debug.Assert( wantImmediate, "Cannot take the address of a null constant." ); return m_manager.Module.GetNullValue( m_manager.GetOrInsertType( ce.Type ) ); } if( ce.Type.IsInteger || ce.Type.IsFloatingPoint ) { if( ce.SizeOfValue == 0 ) { throw new System.InvalidOperationException( "Scalar constant with 0 bits width." ); } Debug.Assert( wantImmediate, "Cannot take the address of a scalar constant." ); _Type scalarType = m_manager.GetOrInsertType( ce.Type ); object value = ce.Value; if( ce.Type.IsInteger ) { // Ensure integer types are converted to ulong. This will also catch enums and IntPtr/UIntPtr. ulong intValue; ce.GetAsRawUlong(out intValue); value = intValue; } return m_manager.Module.GetScalarConstant( scalarType, value ); } IR.DataManager.DataDescriptor dd = ce.Value as IR.DataManager.DataDescriptor; if( dd != null ) { Debug.Assert( wantImmediate || ( dd.Context is TS.ValueTypeRepresentation ), "Cannot take the address of a global object reference." ); // This call always returns a pointer to global storage, so value types may need to be loaded. Value value = m_manager.GlobalValueFromDataDescriptor(dd, true); if (wantImmediate && (dd.Context is TS.ValueTypeRepresentation)) { value = m_basicBlock.InsertLoad( value ); } return value; } throw new Exception( "Constant type not supported." ); } throw new Exception( "Expression type not supported." + exp ); } private void WarnUnimplemented( string msg ) { msg = "Unimplemented operator: " + msg; var color = Console.ForegroundColor; Console.ForegroundColor = ConsoleColor.Magenta; Console.WriteLine( msg ); Console.ForegroundColor = color; //Trick to list in-code missing operators. //m_basicBlock.InsertASMString( "; " + msg ); } private void OutputStringInline( string str ) { m_basicBlock.InsertASMString( "####################################################" ); m_basicBlock.InsertASMString( "# " + str ); m_basicBlock.InsertASMString( "####################################################" ); } private void TranslateOperator( IR.Operator op, IR.BasicBlock bb ) { if( ShouldSkipOperator( op ) ) { return; } // Load Debug metadata // Miguel: (Hack to remove processor.cs epilogue/prologue debug data) if( op.DebugInfo != null && !op.DebugInfo.SrcFileName.EndsWith( "ProcessorARMv7M.cs" ) ) { m_basicBlock.SetDebugInfo( m_manager, m_method, op ); } OutputStringInline( op.ToString( ) ); //ALU if( op is IR.AbstractBinaryOperator ) { Translate_AbstractBinaryOperator( ( IR.AbstractBinaryOperator )op ); } else if( op is IR.AbstractUnaryOperator ) { //Todo: Add unary "Finite" operation, which in fact is "CKfinite" from the checks. Translate_AbstractUnaryOperator( ( IR.AbstractUnaryOperator )op ); } //Conversions else if( op is IR.ConversionOperator ) { Translate_ConversionOperator( ( IR.ConversionOperator )op ); } else if( op is IR.ConvertOperator ) { Translate_ConvertOperator( ( IR.ConvertOperator )op ); } //Store-Load operators else if( op is IR.SingleAssignmentOperator ) { Translate_SingleAssignmentOperator( ( IR.SingleAssignmentOperator )op ); } else if( op is IR.AddressAssignmentOperator ) { Translate_AddressAssignmentOperator( ( IR.AddressAssignmentOperator )op ); } else if( op is IR.InitialValueOperator ) { Translate_InitialValueOperator( ( IR.InitialValueOperator )op ); } else if( op is IR.CompareAndSetOperator ) { Translate_CompareAndSetOperator( ( IR.CompareAndSetOperator )op ); } else if( op is IR.LoadIndirectOperator ) { Translate_LoadIndirectOperator( ( IR.LoadIndirectOperator )op ); } else if( op is IR.StoreIndirectOperator ) { Translate_StoreIndirectOperator( ( IR.StoreIndirectOperator )op ); } else if( op is IR.StoreInstanceFieldOperator ) { Translate_StoreInstanceFieldOperator( ( IR.StoreInstanceFieldOperator )op ); } else if( op is IR.LoadInstanceFieldOperator ) { Translate_LoadInstanceFieldOperator( ( IR.LoadInstanceFieldOperator )op ); } else if( op is IR.LoadInstanceFieldAddressOperator ) { Translate_LoadInstanceFieldAddressOperator( ( IR.LoadInstanceFieldAddressOperator )op ); } else if( op is IR.StoreElementOperator ) { Translate_StoreElementOperator( ( IR.StoreElementOperator )op ); } else if( op is IR.LoadElementOperator ) { Translate_LoadElementOperator( ( IR.LoadElementOperator )op ); } else if( op is IR.LoadElementAddressOperator ) { Translate_LoadElementAddressOperator( ( IR.LoadElementAddressOperator )op ); } //Control flow operators else if( op is IR.UnconditionalControlOperator ) { Translate_UnconditionalControlOperator( ( IR.UnconditionalControlOperator )op ); } else if( op is IR.BinaryConditionalControlOperator ) { Translate_BinaryConditionalControlOperator( ( IR.BinaryConditionalControlOperator )op ); } else if( op is IR.CompareConditionalControlOperator ) { Translate_CompareConditionalControlOperator( ( IR.CompareConditionalControlOperator )op ); } else if( op is IR.MultiWayConditionalControlOperator ) { Translate_MultiWayConditionalControlOperator( ( IR.MultiWayConditionalControlOperator )op ); } else if( op is IR.ReturnControlOperator ) { Translate_ReturnControlOperator( ( IR.ReturnControlOperator )op ); } else if( op is IR.DeadControlOperator ) { Translate_DeadControlOperator( ( IR.DeadControlOperator )op ); } //Calls else if( op is IR.StaticCallOperator ) { Translate_StaticCallOperator( ( IR.StaticCallOperator )op ); } else if( op is IR.InstanceCallOperator ) { Translate_InstanceCallOperator( ( IR.InstanceCallOperator )op ); } else if( op is IR.IndirectCallOperator ) { Translate_IndirectCallOperator( ( IR.IndirectCallOperator )op ); } //Other else if (op is IR.LandingPadOperator) { Translate_LandingPadOperator((IR.LandingPadOperator)op); } else if (op is IR.ResumeUnwindOperator) { Translate_ResumeUnwindOperator((IR.ResumeUnwindOperator)op); } else { WarnUnimplemented( op.ToString( ) ); } } private static bool ShouldSkipOperator( IR.Operator op ) { if( ( op is IR.NullCheckOperator ) || ( op is IR.OutOfBoundCheckOperator ) || ( op is IR.CompilationConstraintsOperator ) || ( op is IR.NopOperator ) ) { return true; } return false; } private bool IsSuitableForLLVMTranslation( IR.Expression varExp ) { if( varExp is IR.PhysicalRegisterExpression || varExp is IR.StackLocationExpression ) { return false; } return true; } private void EnsureSameType(ref Value valA, ref Value valB) { _Type typeA = valA.GetDebugType(); _Type typeB = valB.GetDebugType(); if (typeA.IsPointer != typeB.IsPointer) { // Convert the pointer parameter to an integer to match the other. valA = ConvertValueToALUOperableType(valA); valB = ConvertValueToALUOperableType(valB); } else if (typeA.IsPointer) { // Ensure pointer types match. valB = m_basicBlock.InsertBitCast(valB, typeA); } if (typeA.IsInteger && typeB.IsInteger) { if (typeA.SizeInBits < typeB.SizeInBits) { if (typeA.IsSigned) { valA = m_basicBlock.InsertSExt(valA, typeB, typeA.SizeInBits); } else { valA = m_basicBlock.InsertZExt(valA, typeB, typeA.SizeInBits); } } else if (typeA.SizeInBits > typeB.SizeInBits) { if (typeA.IsSigned) { valB = m_basicBlock.InsertSExt(valB, typeA, typeB.SizeInBits); } else { valB = m_basicBlock.InsertZExt(valB, typeA, typeB.SizeInBits); } } } } private Value ConvertValueToALUOperableType(Value val) { // LLVM doesn't accept pointers as operands for arithmetic operations, so convert them to integers. if (val.NativeType.IsPointer) { _Type intPtrType = m_manager.GetOrInsertType(m_wkt.System_UInt32); return m_basicBlock.InsertPointerToInt(val, intPtrType); } return val; } private Value ConvertValueToStoreToTarget(Value val, _Type targetType) { // Trivial case: Value is already the desired type. We compare the inner types directly because the outer // types will be the same between pointer types for arrays and strings, while the inner types won't. if (val.NativeType == targetType.DebugType.NativeType) { return val; } _Type type = val.GetDebugType(); if (type.IsPointer && targetType.IsPointer) { return m_basicBlock.InsertBitCast(val, targetType); } if (type.IsInteger && targetType.IsInteger) { if (type.SizeInBits < targetType.SizeInBits) { if (type.IsSigned) { return m_basicBlock.InsertSExt(val, targetType, type.SizeInBits); } else { return m_basicBlock.InsertZExt(val, targetType, type.SizeInBits); } } if (type.SizeInBits > targetType.SizeInBits) { return m_basicBlock.InsertTrunc(val, targetType, type.SizeInBits); } return m_basicBlock.InsertBitCast(val, targetType); } if (type.IsInteger && targetType.IsPointer) { return m_basicBlock.InsertIntToPointer(val, targetType); } if (type.IsPointer && targetType.IsInteger) { return m_basicBlock.InsertPointerToInt(val, targetType); } if (type.IsFloatingPoint && targetType.IsFloatingPoint) { if (type.SizeInBits > targetType.SizeInBits) { return m_basicBlock.InsertFPTrunc(val, targetType); } else { return m_basicBlock.InsertFPExt(val, targetType); } } if (type.IsFloatingPoint && targetType.IsInteger) { return m_basicBlock.InsertFPToInt(val, targetType); } if (type.IsInteger && targetType.IsFloatingPoint) { return m_basicBlock.InsertIntToFP(val, targetType); } throw new InvalidOperationException("Invalid type cast."); } private void StoreValue(ValueCache dst, Value src, IR.BasicBlock block) { Value convertedSrc = ConvertValueToStoreToTarget(src, dst.Type); m_basicBlock.SetVariableName( convertedSrc, dst.Expression ); if( dst.IsAddressable ) { StoreValue( dst.Address, convertedSrc ); } else { dst.SetValueForBlock(block, convertedSrc); } } private void StoreValue(Value dst, Value src) { m_basicBlock.InsertStore(ConvertValueToStoreToTarget(src, dst.GetUnderlyingType()), dst); } private void Translate_AbstractBinaryOperator(IR.AbstractBinaryOperator op) { if (!(op is IR.BinaryOperator)) { throw new Exception("Unhandled Binary Op: " + op); } Value valA = GetImmediate(op.BasicBlock, op.FirstArgument); Value valB = GetImmediate(op.BasicBlock, op.SecondArgument); valA = ConvertValueToALUOperableType(valA); valB = ConvertValueToALUOperableType(valB); // TODO: Add support for overflow exceptions. EnsureSameType(ref valA, ref valB); Value result = m_basicBlock.InsertBinaryOp((int)op.Alu, valA, valB, op.Signed); StoreValue(m_localValues[op.FirstResult], result, op.BasicBlock); } private void Translate_AbstractUnaryOperator(IR.AbstractUnaryOperator op) { if (!(op is IR.UnaryOperator)) { throw new Exception("Unhandled Unary Op: " + op); } // TODO: Add support for overflow exceptions. Value argument = GetImmediate(op.BasicBlock, op.FirstArgument); Value value = ConvertValueToALUOperableType(argument); Value result = m_basicBlock.InsertUnaryOp((int)op.Alu, value, op.Signed); StoreValue(m_localValues[op.FirstResult], result, op.BasicBlock); } private void Translate_ConversionOperator( IR.ConversionOperator op ) { // TODO: Add support for overflow exceptions Value argument = GetImmediate(op.BasicBlock, op.FirstArgument); Value value = ConvertValueToALUOperableType(argument); _Type resultType = m_manager.GetOrInsertType( op.FirstResult.Type ); if( op.FirstResult.Type == m_wkt.System_IntPtr || op.FirstResult.Type == m_wkt.System_UIntPtr || op.FirstResult.Type is TS.PointerTypeRepresentation ) { resultType = m_manager.GetOrInsertType( m_wkt.System_UInt32 ); } if( op is IR.ZeroExtendOperator ) { value = m_basicBlock.InsertZExt( value, resultType, 8 * ( int )op.SignificantSize ); } else if( op is IR.SignExtendOperator ) { value = m_basicBlock.InsertSExt( value, resultType, 8 * ( int )op.SignificantSize ); } else if( op is IR.TruncateOperator ) { value = m_basicBlock.InsertTrunc( value, resultType, 8 * ( int )op.SignificantSize ); } else { throw new Exception( "Unimplemented Conversion Operator: " + op.ToString( ) ); } StoreValue(m_localValues[ op.FirstResult ], value, op.BasicBlock); } private void Translate_ConvertOperator(IR.ConvertOperator op) { // TODO: Add support for overflow exceptions Value argument = GetImmediate(op.BasicBlock, op.FirstArgument); StoreValue(m_localValues[op.FirstResult], argument, op.BasicBlock); } private void Translate_SingleAssignmentOperator(IR.SingleAssignmentOperator op) { Value value = GetImmediate(op.BasicBlock, op.FirstArgument); StoreValue(m_localValues[op.FirstResult], value, op.BasicBlock); } private void Translate_AddressAssignmentOperator(IR.AddressAssignmentOperator op) { Value address = GetAddress(op.BasicBlock, op.FirstArgument); StoreValue(m_localValues[op.FirstResult], address, op.BasicBlock); } private void Translate_InitialValueOperator( IR.InitialValueOperator op ) { int index = op.FirstResult.Number; if (m_method is TS.StaticMethodRepresentation) { --index; } _Type type = m_manager.GetOrInsertType( op.FirstResult.Type ); Value argument = m_basicBlock.GetMethodArgument(index, type); StoreValue(m_localValues[ op.FirstResult ], argument, op.BasicBlock); } private void Translate_CompareAndSetOperator(IR.CompareAndSetOperator op) { Value left = GetImmediate(op.BasicBlock, op.FirstArgument); Value right = GetImmediate(op.BasicBlock, op.SecondArgument); EnsureSameType(ref left, ref right); Value value = m_basicBlock.InsertCmp((int)op.Condition, op.Signed, left, right); StoreValue(m_localValues[op.FirstResult], value, op.BasicBlock); } private void Translate_LoadIndirectOperator(IR.LoadIndirectOperator op) { Value argument = GetImmediate(op.BasicBlock, op.FirstArgument); Value address = m_basicBlock.LoadIndirect(argument, m_manager.GetOrInsertType(op.Type)); Value value = m_basicBlock.InsertLoad(address); StoreValue(m_localValues[op.FirstResult], value, op.BasicBlock); } private void Translate_StoreIndirectOperator(IR.StoreIndirectOperator op) { Value argument = GetImmediate(op.BasicBlock, op.FirstArgument); Value value = GetImmediate(op.BasicBlock, op.SecondArgument); Value address = m_basicBlock.LoadIndirect(argument, m_manager.GetOrInsertType(op.Type)); StoreValue(address, value); } private Value GetInstanceAddress(IR.FieldOperator op) { IR.Expression instance = op.FirstArgument; if (instance.Type is TS.ValueTypeRepresentation) { return GetAddress( op.BasicBlock, instance ); } else { return GetImmediate( op.BasicBlock, instance ); } } private void Translate_StoreInstanceFieldOperator(IR.StoreInstanceFieldOperator op) { Value objAddress = GetInstanceAddress(op); Value value = GetImmediate(op.BasicBlock, op.SecondArgument); _Type fieldType = m_manager.GetOrInsertType(op.Field.FieldType); Value fieldAddress = m_basicBlock.GetFieldAddress(objAddress, op.Field.Offset, fieldType); StoreValue(fieldAddress, value); } private void Translate_LoadInstanceFieldOperator(IR.LoadInstanceFieldOperator op) { Value objAddress = GetInstanceAddress(op); _Type fieldType = m_manager.GetOrInsertType(op.Field.FieldType); Value fieldAddress = m_basicBlock.GetFieldAddress(objAddress, op.Field.Offset, fieldType); Value value = m_basicBlock.InsertLoad(fieldAddress); StoreValue(m_localValues[op.FirstResult], value, op.BasicBlock); } private void Translate_LoadInstanceFieldAddressOperator(IR.LoadInstanceFieldAddressOperator op) { Value objAddress = GetInstanceAddress(op); _Type fieldType = m_manager.GetOrInsertType(op.Field.FieldType); Value fieldAddress = m_basicBlock.GetFieldAddress(objAddress, op.Field.Offset, fieldType); StoreValue(m_localValues[op.FirstResult], fieldAddress, op.BasicBlock); } private Value GetElementAddress(IR.ElementOperator op) { var arrayType = (TS.ArrayReferenceTypeRepresentation)op.FirstArgument.Type; _Type elementType = m_manager.GetOrInsertType(arrayType.ContainedType); Value array = GetImmediate(op.BasicBlock, op.FirstArgument); Value nativeArray = m_basicBlock.GetFieldAddress(array, (int)m_wkt.System_Array.Size, null); Value index = GetImmediate(op.BasicBlock, op.SecondArgument); Value aluIndex = ConvertValueToALUOperableType(index); return m_basicBlock.IndexLLVMArray(nativeArray, aluIndex, elementType); } private void Translate_LoadElementOperator(IR.LoadElementOperator op) { Value elementAddress = GetElementAddress(op); Value value = m_basicBlock.InsertLoad(elementAddress); StoreValue(m_localValues[op.FirstResult], value, op.BasicBlock); } private void Translate_LoadElementAddressOperator(IR.LoadElementAddressOperator op) { Value elementAddress = GetElementAddress(op); StoreValue(m_localValues[op.FirstResult], elementAddress, op.BasicBlock); } private void Translate_StoreElementOperator(IR.StoreElementOperator op) { Value elementAddress = GetElementAddress(op); Value value = GetImmediate(op.BasicBlock, op.ThirdArgument); StoreValue(elementAddress, value); } private void Translate_UnconditionalControlOperator( IR.UnconditionalControlOperator op ) { m_basicBlock.InsertUnconditionalBranch( GetOrInsertBasicBlock( op.TargetBranch ) ); } private void Translate_BinaryConditionalControlOperator( IR.BinaryConditionalControlOperator op ) { Value left = GetImmediate(op.BasicBlock, op.FirstArgument); Value zero = m_manager.Module.GetNullValue(left.GetDebugType()); Value condition = m_basicBlock.InsertCmp((int)IR.CompareAndSetOperator.ActionCondition.NE, false, left, zero); _BasicBlock taken = GetOrInsertBasicBlock( op.TargetBranchTaken ); _BasicBlock notTaken = GetOrInsertBasicBlock( op.TargetBranchNotTaken ); m_basicBlock.InsertConditionalBranch( condition, taken, notTaken ); } private void Translate_CompareConditionalControlOperator(IR.CompareConditionalControlOperator op) { Value left = GetImmediate(op.BasicBlock, op.FirstArgument); Value right = GetImmediate(op.BasicBlock, op.SecondArgument); EnsureSameType(ref left, ref right); Value condition = m_basicBlock.InsertCmp((int)op.Condition, op.Signed, left, right); _BasicBlock taken = GetOrInsertBasicBlock(op.TargetBranchTaken); _BasicBlock notTaken = GetOrInsertBasicBlock(op.TargetBranchNotTaken); m_basicBlock.InsertConditionalBranch(condition, taken, notTaken); } private void Translate_MultiWayConditionalControlOperator( IR.MultiWayConditionalControlOperator op ) { List caseValues = new List(); List<_BasicBlock> caseBBs = new List<_BasicBlock>(); for( int i = 0; i < op.Targets.Length; ++i ) { caseValues.Add( i ); caseBBs.Add( GetOrInsertBasicBlock( op.Targets[ i ] ) ); } Value argument = GetImmediate(op.BasicBlock, op.FirstArgument); _BasicBlock defaultBlock = GetOrInsertBasicBlock( op.TargetBranchNotTaken ); m_basicBlock.InsertSwitchAndCases( argument, defaultBlock, caseValues, caseBBs ); } private void Translate_ReturnControlOperator( IR.ReturnControlOperator op ) { switch( op.Arguments.Length ) { case 0: m_basicBlock.InsertRet( null ); break; case 1: Value result = GetImmediate(op.BasicBlock, op.FirstArgument); m_basicBlock.InsertRet( result ); break; default: throw new System.InvalidOperationException( "ReturnControlOperator with more than one arg not supported. " + op ); } } private void Translate_DeadControlOperator( IR.DeadControlOperator op ) { // Basic Block marked as dead code by Zelig. m_basicBlock.InsertUnreachable(); } private bool ReplaceMethodCallWithIntrinsic( TS.MethodRepresentation method, List convertedArgs, out Value result ) { TS.WellKnownMethods wkm = m_cfg.TypeSystem.WellKnownMethods; result = null; // System.Buffer.InternalMemoryCopy(byte*, byte*, int) => llvm.memcpy // System.Buffer.InternalBackwardMemoryCopy(byte*, byte*, int) => llvm.memmove if ( method == wkm.System_Buffer_InternalMemoryCopy //////|| method == wkm.System_Buffer_InternalBackwardMemoryCopy ) { bool overlapping = method != wkm.System_Buffer_InternalMemoryCopy; Value src = convertedArgs[0]; Value dst = convertedArgs[1]; Value size = convertedArgs[2]; m_basicBlock.InsertMemCpy(dst, src, size, overlapping); return true; } // Microsoft.Zelig.Runtime.Memory.Fill(byte*, int, byte) => llvm.memset if (method == wkm.Microsoft_Zelig_Runtime_Memory_Fill) { Value dst = convertedArgs[0]; Value size = convertedArgs[1]; Value value = convertedArgs[2]; m_basicBlock.InsertMemSet(dst, value, size); return true; } // Microsoft.Zelig.Runtime.InterlockedImpl.InternalAdd(ref int, int) => llvm.atomicrmw add // Note: there's no built-in support for 64bit interlocked methods at the moment. if (method == wkm.InterlockedImpl_InternalAdd_int) { Value ptr = convertedArgs[0]; Value val = convertedArgs[1]; Value oldVal = m_basicBlock.InsertAtomicAdd(ptr, val); // Because LLVM atomicrmw returns the old value, in order to match the behavior of Interlocked.Add // We need to calculate the new value to return. result = m_basicBlock.InsertBinaryOp((int)IR.BinaryOperator.ALU.ADD, oldVal, val, true); return true; } // Microsoft.Zelig.Runtime.InterlockedImpl.InternalExchange(ref int, int) => llvm.atomicrmw xchg // Microsoft.Zelig.Runtime.InterlockedImpl.InternalExchange(ref float, float) => llvm.atomicrmw xchg // Microsoft.Zelig.Runtime.InterlockedImpl.InternalExchange(ref IntPtr, IntPtr) => llvm.atomicrmw xchg // Microsoft.Zelig.Runtime.InterlockedImpl.InternalExchange(ref T, T) => llvm.atomicrmw xchg // Note: there's no built-in support for 64bit interlocked methods at the moment. if ((method == wkm.InterlockedImpl_InternalExchange_int) || (method == wkm.InterlockedImpl_InternalExchange_float) || (method == wkm.InterlockedImpl_InternalExchange_IntPtr) || (method.IsGenericInstantiation && method.GenericTemplate == wkm.InterlockedImpl_InternalExchange_Template)) { Value ptr = convertedArgs[0]; Value val = convertedArgs[1]; _Type type = val.GetDebugType(); // AtomicXchg only supports integer types, so need to convert them if necessary _Type intType = m_manager.GetOrInsertType( m_wkt.System_Int32 ); _Type intPtrType = m_manager.Module.GetOrInsertPointerType( intType ); if(!type.IsInteger) { ptr = m_basicBlock.InsertBitCast( ptr, intPtrType ); if(type.IsPointer) { val = m_basicBlock.InsertPointerToInt( val, intType ); } else { val = m_basicBlock.InsertBitCast( val, intType ); } } result = m_basicBlock.InsertAtomicXchg( ptr, val ); if (result.GetDebugType() != type) { if(type.IsPointer) { result = m_basicBlock.InsertIntToPointer( result, type ); } else { result = m_basicBlock.InsertBitCast( result, type ); } } return true; } // Microsoft.Zelig.Runtime.InterlockedImpl.InternalCompareExchange(ref int, int, int) => llvm.compxchg // Microsoft.Zelig.Runtime.InterlockedImpl.InternalCompareExchange(ref float, float, float) => llvm.compxchg // Microsoft.Zelig.Runtime.InterlockedImpl.InternalCompareExchange(ref IntPtr, IntPtr, IntPtr) => llvm.compxchg // Microsoft.Zelig.Runtime.InterlockedImpl.InternalCompareExchange(ref T, T, T) => llvm.compxchg // Note: there's no built-in support for 64bit interlocked methods at the moment. if ((method == wkm.InterlockedImpl_InternalCompareExchange_int) || (method == wkm.InterlockedImpl_InternalCompareExchange_float) || (method == wkm.InterlockedImpl_InternalCompareExchange_IntPtr) || (method.IsGenericInstantiation && method.GenericTemplate == wkm.InterlockedImpl_InternalCompareExchange_Template)) { Value ptr = convertedArgs[0]; Value val = convertedArgs[1]; Value cmp = convertedArgs[2]; _Type type = val.GetDebugType(); // AtomicCmpXchg only supports integer types, so need to convert them if necessary _Type intType = m_manager.GetOrInsertType( m_wkt.System_Int32 ); _Type intPtrType = m_manager.Module.GetOrInsertPointerType( intType ); if(!type.IsInteger) { ptr = m_basicBlock.InsertBitCast( ptr, intPtrType ); if(type.IsPointer) { val = m_basicBlock.InsertPointerToInt( val, intType ); cmp = m_basicBlock.InsertPointerToInt( cmp, intType ); } else { val = m_basicBlock.InsertBitCast( val, intType ); cmp = m_basicBlock.InsertBitCast( cmp, intType ); } } result = m_basicBlock.InsertAtomicCmpXchg( ptr, cmp, val ); if (result.GetDebugType() != type) { if(type.IsPointer) { result = m_basicBlock.InsertIntToPointer( result, type ); } else { result = m_basicBlock.InsertBitCast( result, type ); } } return true; } return false; } private void BuildMethodCallInstructions(IR.CallOperator op) { List args = new List(); TS.MethodRepresentation method = op.TargetMethod; int firstArgument = (method is TS.StaticMethodRepresentation) ? 1 : 0; int indirectAdjust = 0; bool callIndirect = op is IR.IndirectCallOperator; if (callIndirect) { firstArgument = ((IR.IndirectCallOperator)op).IsInstanceCall ? 0 : 1; indirectAdjust = 1; } for (int i = firstArgument; i < method.ThisPlusArguments.Length; ++i) { TS.TypeRepresentation typeRep = method.ThisPlusArguments[i]; _Type type = m_manager.GetOrInsertType(typeRep); Value argument = GetImmediate(op.BasicBlock, op.Arguments[i + indirectAdjust]); Value convertedArg = ConvertValueToStoreToTarget(argument, type); args.Add(convertedArg); } Value result; if (!ReplaceMethodCallWithIntrinsic(method, args, out result)) { _Type returnType = m_manager.GetOrInsertType(method.ReturnType); Value callAddress; if (callIndirect) { callAddress = GetImmediate(op.BasicBlock, op.Arguments[0]); } else { _Function targetFunc = m_manager.GetOrInsertFunction(method); if (method.Flags.HasFlag(TS.MethodRepresentation.Attributes.PinvokeImpl)) { targetFunc.SetExternalLinkage(); } callAddress = targetFunc.LlvmFunction; } // If this call is protected by a landing pad, replace it with an invoke instruction. if ((op.BasicBlock.ProtectedBy.Length > 0) && op.MayThrow) { _BasicBlock nextBlock = SplitCurrentBlock(); _BasicBlock catchBlock = GetOrInsertBasicBlock(op.BasicBlock.ProtectedBy[0]); result = m_basicBlock.InsertInvoke(callAddress, returnType, args, callIndirect, nextBlock, catchBlock); m_basicBlock = nextBlock; EnsurePersonalityFunction(); } else { result = m_basicBlock.InsertCall(callAddress, returnType, args, callIndirect); } } if (op.Results.Length == 1) { StoreValue(m_localValues[op.FirstResult], result, op.BasicBlock); } else if (op.Results.Length > 1) { throw new System.InvalidOperationException("More than one return values are not handled."); } } private void Translate_StaticCallOperator(IR.StaticCallOperator op) { BuildMethodCallInstructions(op); } private void Translate_InstanceCallOperator(IR.InstanceCallOperator op) { BuildMethodCallInstructions(op); } private void Translate_IndirectCallOperator(IR.IndirectCallOperator op) { BuildMethodCallInstructions(op); } private void Translate_LandingPadOperator(IR.LandingPadOperator op) { EnsurePersonalityFunction(); var vtables = new Value[op.Arguments.Length]; for (int i = 0; i < op.Arguments.Length; ++i) { var vtable = GetImmediate(op.BasicBlock, op.Arguments[i]); // BUGBUG: LLVM appears to have an issue with type-info pointers where GEP constant // expressions resolve to null. To work around this problem, we emit the "wrapped" // global with the object header and adjust to the real VTable pointer in the // personality routine. var vtableAsConst = (Constant)vtable; if (vtableAsConst.Operands.Count != 0) { vtable = vtableAsConst.Operands[0]; } vtables[i] = vtable; } _Type resultType = m_manager.GetOrInsertType(op.FirstResult.Type); Value result = m_basicBlock.InsertLandingPad(resultType, vtables, op.HasCleanupClause); StoreValue(m_localValues[op.FirstResult], result, op.BasicBlock); } private void Translate_ResumeUnwindOperator(IR.ResumeUnwindOperator op) { Value exception = GetImmediate(op.BasicBlock, op.FirstArgument); m_basicBlock.InsertResume(exception); } // Ensure that the currently emitting function has a personality function attached. private void EnsurePersonalityFunction() { m_function.LlvmFunction.PersonalityFunction = m_manager.Module.GetPersonalityFunction("LLOS_Personality"); } } } ================================================ FILE: Zelig/Zelig/CompileTime/TargetModels/ProductConfiguration/Abstractions/LLVMforZelig/LlvmForArmV7M_VFP.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // namespace Microsoft.Zelig.Configuration.Environment.Abstractions.Architectures { using Microsoft.Zelig.Runtime.TypeSystem; using Microsoft.Zelig.TargetModel.ArmProcessor; using System; using System.Collections.Generic; using ZeligIR = Microsoft.Zelig.CodeGeneration.IR; public sealed class LlvmForArmV7M_VFP : ArmPlatform { private const Capabilities c_ProcessorCapabilities = Capabilities.ARMv7M | Capabilities.VFPv2; // // State // // // Constructor Methods // public LlvmForArmV7M_VFP( ZeligIR.TypeSystemForCodeTransformation typeSystem, MemoryMapCategory memoryMap ) : base( typeSystem, memoryMap, c_ProcessorCapabilities ) { } public override void RegisterForNotifications( ZeligIR.TypeSystemForCodeTransformation ts, ZeligIR.CompilationSteps.DelegationCache cache ) { base.RegisterForNotifications( ts, cache ); cache.Register( new ZeligIR.CompilationSteps.Handlers.SoftwareFloatingPoint() ); cache.Register( new ArmV4.Optimizations( this ) ); } public override ZeligIR.ImageBuilders.CompilationState CreateCompilationState( ZeligIR.ImageBuilders.Core core, ZeligIR.ControlFlowGraphStateForCodeTransformation cfg ) { return new LlvmForArmV7MCompilationState( core, cfg ); } //--// // // Access Methods // public override string CodeGenerator { get { return InstructionSetVersion.CodeGenerator_LLVM; } } public override uint PlatformFamily { get { return InstructionSetVersion.Platform_Family__Cortex; } } public override uint PlatformVersion { get { return InstructionSetVersion.Platform_Version__ARMv7M; } } public override uint PlatformVFP { get { return InstructionSetVersion.Platform_VFP__HardVFP; } } public override bool PlatformBigEndian { get { return false; } } //--// public override TypeRepresentation GetMethodWrapperType( ) { return m_typeSystem.GetWellKnownType( "Microsoft_Zelig_ARMv7ForLlvm_MethodWrapper" ); } // // Not implememted, and used only during machine code emission // public override bool HasRegisterContextArgument( MethodRepresentation md ) { //////if(md.ThisPlusArguments.Length > 1) //////{ ////// TypeRepresentation td = md.ThisPlusArguments[1]; ////// if(td is PointerTypeRepresentation) ////// { ////// td = td.UnderlyingType; ////// if(td == m_typeSystem.GetWellKnownType( "Microsoft_Zelig_ProcessorARMv7M_RegistersOnStack" )) ////// { ////// return true; ////// } ////// } //////} return false; } public override void ComputeSetOfRegistersToSave( ZeligIR.Abstractions.CallingConvention cc, ZeligIR.ControlFlowGraphStateForCodeTransformation cfg, BitVector modifiedRegisters, out BitVector registersToSave, out Runtime.HardwareException he ) { throw new Exception( "ComputeSetOfRegistersToSave not implemented" ); } //--// protected override void ComputeRegisterFlushFixup( BitVector registersToSave ) { throw new Exception( "ComputeRegisterFlushFixup not implemented" ); } } } ================================================ FILE: Zelig/Zelig/CompileTime/TargetModels/ProductConfiguration/Abstractions/LLVMforZelig/LlvmForWin32.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // namespace Microsoft.Zelig.Configuration.Environment.Abstractions.Architectures { using Microsoft.Zelig.Runtime.TypeSystem; using WIN = Microsoft.Zelig.TargetModel.Win32; using System; using ZeligIR = Microsoft.Zelig.CodeGeneration.IR; public sealed class LlvmForWin32 : ArmPlatform { private const Capabilities c_ProcessorCapabilities = Capabilities.None; // // State // // // Constructor Methods // public LlvmForWin32( ZeligIR.TypeSystemForCodeTransformation typeSystem, MemoryMapCategory memoryMap ) : base( typeSystem, memoryMap, c_ProcessorCapabilities ) { } public override void RegisterForNotifications( ZeligIR.TypeSystemForCodeTransformation ts, ZeligIR.CompilationSteps.DelegationCache cache ) { base.RegisterForNotifications( ts, cache ); cache.Register( new ZeligIR.CompilationSteps.Handlers.SoftwareFloatingPoint() ); cache.Register( new ArmV4.Optimizations( this ) ); } public override ZeligIR.ImageBuilders.CompilationState CreateCompilationState( ZeligIR.ImageBuilders.Core core, ZeligIR.ControlFlowGraphStateForCodeTransformation cfg ) { return new LlvmForArmV7MCompilationState( core, cfg ); } //--// // // Access Methods // public override string CodeGenerator { get { return WIN.InstructionSetVersion.CodeGenerator_LLVM; } } public override uint PlatformFamily { get { return WIN.InstructionSetVersion.Platform_Family__Win32; } } public override uint PlatformVersion { get { return WIN.InstructionSetVersion.Platform_Version__x86; } } public override uint PlatformVFP { get { return WIN.InstructionSetVersion.Platform_VFP__NoVFP; } } public override bool PlatformBigEndian { get { return false; } } //--// public override TypeRepresentation GetMethodWrapperType( ) { return m_typeSystem.GetWellKnownType( "Microsoft_Zelig_Win32_MethodWrapper" ); } // // Not implemented, and used only during machine code emission // public override bool HasRegisterContextArgument( MethodRepresentation md ) { //////if(md.ThisPlusArguments.Length > 1) //////{ ////// TypeRepresentation td = md.ThisPlusArguments[1]; ////// if(td is PointerTypeRepresentation) ////// { ////// td = td.UnderlyingType; ////// if(td == m_typeSystem.GetWellKnownType( "Microsoft_Zelig_ProcessorWin32_RegistersOnStack" )) ////// { ////// return true; ////// } ////// } //////} return false; } public override void ComputeSetOfRegistersToSave( ZeligIR.Abstractions.CallingConvention cc, ZeligIR.ControlFlowGraphStateForCodeTransformation cfg, BitVector modifiedRegisters, out BitVector registersToSave, out Runtime.HardwareException he ) { throw new Exception( "ComputeSetOfRegistersToSave not implemented" ); } //--// protected override void ComputeRegisterFlushFixup( BitVector registersToSave ) { throw new Exception( "ComputeRegisterFlushFixup not implemented" ); } } } ================================================ FILE: Zelig/Zelig/CompileTime/TargetModels/ProductConfiguration/Abstractions/LLVMforZelig/ValueCache.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // using System; using Llvm.NET.Values; using Microsoft.Zelig.LLVM; using IR = Microsoft.Zelig.CodeGeneration.IR; namespace Microsoft.Zelig.Configuration.Environment.Abstractions.Architectures { internal class ValueCache { private GrowOnlyHashTable m_loadedValues; public ValueCache(IR.VariableExpression expression, _Type type) { Expression = expression; Type = type; m_loadedValues = HashTableFactory.New(); } public ValueCache(IR.VariableExpression expression, Value address) : this(expression, address.GetUnderlyingType()) { Address = address; } public IR.VariableExpression Expression { get; } public _Type Type { get; } public Value Address { get; } public bool IsAddressable { get { return Address != null; } } public Value GetValueFromBlock(IR.BasicBlock block) { Value value; if (m_loadedValues.TryGetValue(block, out value)) { return value; } return null; } public void SetValueForBlock(IR.BasicBlock block, Value value) { m_loadedValues[block] = value; } } } ================================================ FILE: Zelig/Zelig/CompileTime/TargetModels/ProductConfiguration/Loaders.Designer.cs ================================================ //------------------------------------------------------------------------------ // // This code was generated by a tool. // Runtime Version:4.0.30319.235 // // Changes to this file may cause incorrect behavior and will be lost if // the code is regenerated. // //------------------------------------------------------------------------------ namespace Microsoft.Zelig.ProductConfiguration { using System; /// /// A strongly-typed resource class, for looking up localized strings, etc. /// // This class was auto-generated by the StronglyTypedResourceBuilder // class via a tool like ResGen or Visual Studio. // To add or remove a member, edit your .ResX file then rerun ResGen // with the /str option, or rebuild your VS project. [global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Resources.Tools.StronglyTypedResourceBuilder", "4.0.0.0")] [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] [global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()] internal class Loaders { private static global::System.Resources.ResourceManager resourceMan; private static global::System.Globalization.CultureInfo resourceCulture; [global::System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")] internal Loaders() { } /// /// Returns the cached ResourceManager instance used by this class. /// [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)] internal static global::System.Resources.ResourceManager ResourceManager { get { if (object.ReferenceEquals(resourceMan, null)) { global::System.Resources.ResourceManager temp = new global::System.Resources.ResourceManager("Microsoft.Zelig.ProductConfiguration.Loaders", typeof(Loaders).Assembly); resourceMan = temp; } return resourceMan; } } /// /// Overrides the current thread's CurrentUICulture property for all /// resource lookups using this strongly typed resource class. /// [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)] internal static global::System.Globalization.CultureInfo Culture { get { return resourceCulture; } set { resourceCulture = value; } } /// /// Looks up a localized resource of type System.Byte[]. /// internal static byte[] Microsoft_iMote2Loader { get { object obj = ResourceManager.GetObject("Microsoft_iMote2Loader", resourceCulture); return ((byte[])(obj)); } } /// /// Looks up a localized resource of type System.Byte[]. /// internal static byte[] Microsoft_NohauLPC3180Loader { get { object obj = ResourceManager.GetObject("Microsoft_NohauLPC3180Loader", resourceCulture); return ((byte[])(obj)); } } /// /// Looks up a localized resource of type System.Byte[]. /// internal static byte[] Microsoft_VoxSoloFormFactorLoader { get { object obj = ResourceManager.GetObject("Microsoft_VoxSoloFormFactorLoader", resourceCulture); return ((byte[])(obj)); } } } } ================================================ FILE: Zelig/Zelig/CompileTime/TargetModels/ProductConfiguration/Loaders.resx ================================================  text/microsoft-resx 2.0 System.Resources.ResXResourceReader, System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 System.Resources.ResXResourceWriter, System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 Resources\Microsoft.iMote2Loader.hex;System.Byte[], mscorlib, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 Resources\Microsoft.NohauLPC3180Loader.hex;System.Byte[], mscorlib, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 Resources\Microsoft.VoxSoloFormFactorLoader.hex;System.Byte[], mscorlib, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 ================================================ FILE: Zelig/Zelig/CompileTime/TargetModels/ProductConfiguration/Manager.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // namespace Microsoft.Zelig.Configuration.Environment { using System; using System.Collections.Generic; using System.IO; public sealed class Manager { // // State // static GrowOnlyHashTable< string, Type > s_allTypes; List < AbstractCategory > m_allValues; List < Type > m_allOptions; GrowOnlyHashTable< Type, List< Type > > m_allOptionsByType; // // Constructor Methods // public Manager() { m_allValues = new List< AbstractCategory > (); m_allOptions = new List< Type > (); m_allOptionsByType = HashTableFactory.New< Type, List< Type > >(); } // // Helper Methods // public static void Serialize( System.Xml.XmlElement root , AbstractCategory category ) { GrowOnlyHashTable< object, int > visited = HashTableFactory.NewWithReferenceEquality< object, int >(); Serialize( root, category, visited ); } public static void Serialize( System.Xml.XmlElement container , AbstractCategory category , GrowOnlyHashTable< object, int > visited ) { System.Xml.XmlElement node = XmlHelper.AddElement( container, "Value" ); int index; if(visited.TryGetValue( category, out index )) { XmlHelper.AddAttribute( node, "BackReference", index.ToString() ); } else { visited[category] = visited.Count; Type t = category.GetType(); XmlHelper.AddAttribute( node, "Type", t.AssemblyQualifiedName ); foreach(System.Reflection.FieldInfo fi in ReflectionHelper.GetAllPublicInstanceFields( t )) { System.Xml.XmlElement subNode = XmlHelper.AddElement( node, "Field" ); XmlHelper.AddAttribute( subNode, "Name", fi.Name ); //// XmlHelper.AddAttribute( subNode, "Site", fi.DeclaringType.AssemblyQualifiedName ); object val = fi.GetValue( category ); if(val is Array) { Serialize( subNode, (Array)val, visited ); } else if(val is AbstractCategory) { Serialize( subNode, (AbstractCategory)val, visited ); } else if(val is Type) { Type tVal = (Type)val; XmlHelper.AddAttribute( subNode, "Value", tVal.AssemblyQualifiedName ); } else if(val != null) { XmlHelper.AddAttribute( subNode, "Value", val.ToString() ); } } } } public static void Serialize( System.Xml.XmlElement container , Array array , GrowOnlyHashTable< object, int > visited ) { System.Xml.XmlElement node = XmlHelper.AddElement( container, "Array" ); int index; if(visited.TryGetValue( array, out index )) { XmlHelper.AddAttribute( node, "BackReference", index.ToString() ); } else { visited[array] = visited.Count; XmlHelper.AddAttribute( node, "Type" , array.GetType().GetElementType().AssemblyQualifiedName ); XmlHelper.AddAttribute( node, "Length", array.Length ); for(int i = 0; i < array.Length; i++) { System.Xml.XmlElement subNode = XmlHelper.AddElement( node, "Element" ); object val = array.GetValue( i ); if(val is Array) { Serialize( subNode, (Array)val, visited ); } else if(val is AbstractCategory) { Serialize( subNode, (AbstractCategory)val, visited ); } else { throw TypeConsistencyErrorException.Create( "Cannot serialize configuration, unexpected array of type {0}", array.GetType() ); } } } } //--// public static AbstractCategory Deserialize( System.Xml.XmlNode root ) { List< object > visited = new List< object >(); return (AbstractCategory)Deserialize( root, visited, false ); } public static object Deserialize( System.Xml.XmlNode container , List< object > visited , bool fNullOk ) { System.Xml.XmlNode node; node = container.SelectSingleNode( "Value" ); if(node != null) { return DeserializeObject( container, node, visited ); } node = container.SelectSingleNode( "Array" ); if(node != null) { return DeserializeArray( container, node, visited ); } if(fNullOk) { return null; } throw TypeConsistencyErrorException.Create( "Cannot deserialize configuration, unknown tag {0}", container.Name ); } private static AbstractCategory DeserializeObject( System.Xml.XmlNode container , System.Xml.XmlNode node , List visited ) { System.Xml.XmlAttribute attrib; attrib = XmlHelper.FindAttribute( node, "BackReference" ); if(attrib != null) { return (AbstractCategory)visited[int.Parse( attrib.Value )]; } attrib = XmlHelper.FindAttribute( node, "Type" ); if(attrib == null) { throw TypeConsistencyErrorException.Create( "Cannot deserialize configuration, missing 'Type' tag" ); } Type t = ResolveType( attrib.Value ); AbstractCategory category = (AbstractCategory)Activator.CreateInstance( t ); visited.Add( category ); foreach(System.Xml.XmlNode field in node.SelectNodes( "Field" )) { attrib = XmlHelper.FindAttribute( field, "Name" ); if(attrib == null) { throw TypeConsistencyErrorException.Create( "Cannot deserialize configuration, missing 'Name' tag for 'Field' element" ); } System.Reflection.FieldInfo fi = t.GetField( attrib.Value ); object obj; attrib = XmlHelper.FindAttribute( field, "Value" ); if(attrib != null) { Type fieldType = fi.FieldType; if(fieldType == typeof(bool)) { obj = bool.Parse( attrib.Value ); } else if(fieldType == typeof(uint)) { obj = uint.Parse( attrib.Value ); } else if(fieldType == typeof(ulong)) { obj = ulong.Parse( attrib.Value ); } else if(fieldType == typeof(int)) { obj = int.Parse( attrib.Value ); } else if(fieldType == typeof(string)) { obj = attrib.Value; } else if(fieldType.IsSubclassOf( typeof(Enum ))) { obj = Enum.Parse( fieldType, attrib.Value ); } else if(fieldType == typeof(Type)) { obj = ResolveType( attrib.Value ); } else { throw TypeConsistencyErrorException.Create( "Cannot deserialize configuration, invalid value for {0}: {1}", fi, attrib.Value ); } } else { obj = Deserialize( field, visited, true ); } fi.SetValue( category, obj ); } return category; } private static Type ResolveType( string name ) { InitializeTypes(null); Type res; s_allTypes.TryGetValue( name, out res ); return res; } private static Array DeserializeArray( System.Xml.XmlNode container , System.Xml.XmlNode node , List visited ) { System.Xml.XmlAttribute attrib; attrib = XmlHelper.FindAttribute( node, "BackReference" ); if(attrib != null) { return (Array)visited[int.Parse( attrib.Value )]; } attrib = XmlHelper.FindAttribute( node, "Type" ); if(attrib == null) { throw TypeConsistencyErrorException.Create( "Cannot deserialize configuration, missing 'Type' tag" ); } Type t = ResolveType( attrib.Value ); attrib = XmlHelper.FindAttribute( node, "Length" ); if(attrib == null) { throw TypeConsistencyErrorException.Create( "Cannot deserialize configuration, missing 'Length' tag" ); } int length = int.Parse( attrib.Value ); //--// Array array = Array.CreateInstance( t, length ); visited.Add( array ); int pos = 0; foreach(System.Xml.XmlNode element in node.SelectNodes( "Element" )) { object val = Deserialize( element, visited, true ); array.SetValue( val, pos++ ); } return array; } //--// private static void InitializeTypes(string productAssemblyPath) { if (s_allTypes == null) { s_allTypes = HashTableFactory.New(); List assemblies = new List(AppDomain.CurrentDomain.GetAssemblies()); if(!string.IsNullOrWhiteSpace(productAssemblyPath)) { FileInfo file = new FileInfo(productAssemblyPath); System.Reflection.Assembly assembly = System.Reflection.Assembly.LoadFrom(file.FullName); if(assembly != null) { assemblies.Add(assembly); } } foreach (System.Reflection.Assembly assembly in assemblies) { foreach (Type t in assembly.GetTypes()) { s_allTypes[t.AssemblyQualifiedName] = t; } } } } public void AddAllAssemblies(string productAssemblyPath) { InitializeTypes(productAssemblyPath); foreach (Type t in s_allTypes.Values) { if (t.IsSubclassOf(typeof(AbstractCategory)) && t.IsAbstract == false) { m_allOptions.Add(t); for (Type lookup = t; lookup != null; lookup = lookup.BaseType) { HashTableWithListFactory.AddUnique(m_allOptionsByType, lookup, t); } } } } public void ComputeAllPossibleValuesForFields() { List< Type > stack = new List< Type >(); m_allValues.Clear(); foreach(Type t in m_allOptions) { ComputeAllPossibleValuesForFields( stack, t, null ); } } private AbstractCategory ComputeAllPossibleValuesForFields( List< Type > stack , Type t , GrowOnlyHashTable< string, AbstractDefaultsAttribute > defaultValuesInherited ) { if(stack.IndexOf( t ) >= 0) { System.Text.StringBuilder loop = new System.Text.StringBuilder(); bool fFirst = true; foreach(Type t2 in stack) { if(fFirst) { fFirst = false; } else { loop.Append( " -> " ); } loop.AppendFormat( "{0}", t2.FullName ); } throw TypeConsistencyErrorException.Create( "Detected loop in configuration definition: {0}", loop.ToString() ); } stack.Add( t ); //--// AbstractCategory option = (AbstractCategory)Activator.CreateInstance( t ); return ComputeAllPossibleValuesForFields( stack, option, defaultValuesInherited ); } private AbstractCategory ComputeAllPossibleValuesForFields( List< Type > stack , AbstractCategory option , GrowOnlyHashTable< string, AbstractDefaultsAttribute > defaultValuesInherited ) { Type t = option.GetType(); m_allValues.Add( option ); GrowOnlyHashTable< string, AbstractDefaultsAttribute > defaultValues = GatherDefaultValues( t, true ); defaultValues = MergeDefaultValues( defaultValues, defaultValuesInherited ); foreach(System.Reflection.FieldInfo fi in ReflectionHelper.GetAllPublicInstanceFields( t )) { GrowOnlyHashTable< string, AbstractDefaultsAttribute > defaultValuesForField = GatherDefaultValues( fi, false ); AllowedOptionsAttribute allowedOptions = ReflectionHelper.GetAttribute< AllowedOptionsAttribute >( fi, false ); if(allowedOptions != null) { foreach(Type allowedOption in allowedOptions.Targets) { Type allowedOptionType = ValidateOption( fi, allowedOption, "AllowedOption", true ); option.PossibleValues.Add( fi, ComputeAllPossibleValuesForFields( stack, allowedOptionType, defaultValuesForField ) ); } continue; } //--// Type fiType = fi.FieldType; if(fiType.IsArray) { Type fiSubType = fiType.GetElementType(); Type modelType; if(fiSubType == typeof( PeripheralCategory )) { List< PeripheralCategory > lst = new List< PeripheralCategory >(); modelType = AbstractCategory.FindHardwareModel( fi, HardwareModelAttribute.Kind.Peripheral ); if(modelType != null) { CreatePeripheral( stack, lst, modelType, defaultValuesForField ); } modelType = AbstractCategory.FindHardwareModel( fi, HardwareModelAttribute.Kind.PeripheralsGroup ); if(modelType != null) { CreatePeripheralsForNestedTypes( stack, lst, modelType, defaultValuesForField ); } option.PossibleValues.Add( fi, lst.ToArray() ); } else if(fiSubType == typeof(InteropCategory)) { List< InteropCategory > lst = new List< InteropCategory >(); modelType = AbstractCategory.FindHardwareModel( fi, HardwareModelAttribute.Kind.Interop ); if(modelType != null) { CreateInteropsForNestedTypes( stack, lst, modelType, defaultValuesForField ); } option.PossibleValues.Add( fi, lst.ToArray() ); } } else { if(fiType.IsSubclassOf( typeof(AbstractCategory) )) { List< Type > lst; if(m_allOptionsByType.TryGetValue( fiType, out lst )) { foreach(Type possibleOptionType in lst) { option.PossibleValues.Add( fi, ComputeAllPossibleValuesForFields( stack, possibleOptionType, defaultValuesForField ) ); } } } else { AbstractDefaultsAttribute value; if(defaultValues.TryGetValue( fi.Name, out value )) { option.PossibleValues.Add( fi, value.Value ); } } } } //--// stack.Remove( t ); return option; } private GrowOnlyHashTable< string, AbstractDefaultsAttribute > GatherDefaultValues( System.Reflection.MemberInfo mi , bool fInherit ) { GrowOnlyHashTable< string, AbstractDefaultsAttribute > values = HashTableFactory.New< string, AbstractDefaultsAttribute >(); foreach(AbstractDefaultsAttribute attrib in ReflectionHelper.GetAttributes< AbstractDefaultsAttribute >( mi, fInherit )) { values[ attrib.Member ] = attrib; } return values; } private GrowOnlyHashTable< string, AbstractDefaultsAttribute > MergeDefaultValues( GrowOnlyHashTable< string, AbstractDefaultsAttribute > baseline , GrowOnlyHashTable< string, AbstractDefaultsAttribute > extension ) { if(extension == null) { return baseline; } else { GrowOnlyHashTable< string, AbstractDefaultsAttribute > values = baseline.Clone(); foreach(string key in extension.Keys) { AbstractDefaultsAttribute newAttrib = extension[key]; AbstractDefaultsAttribute oldAttrib; if(values.TryGetValue( key, out oldAttrib )) { if(newAttrib.Merge) { if(newAttrib.Value is Runtime.MemoryAttributes && oldAttrib.Value is Runtime.MemoryAttributes ) { Runtime.MemoryAttributes newValue = (Runtime.MemoryAttributes)newAttrib.Value; Runtime.MemoryAttributes oldValue = (Runtime.MemoryAttributes)oldAttrib.Value; values[ key ] = new EnumDefaultsAttribute( key, oldValue | newValue ); continue; } } } values[ key ] = newAttrib; } return values; } } private void ApplyDefaultValue( List< Type > stack , AbstractCategory value , GrowOnlyHashTable< string, AbstractDefaultsAttribute > defaultValues ) { ComputeAllPossibleValuesForFields( stack, value, defaultValues ); } private void CreatePeripheral( List< Type > stack , List< PeripheralCategory > lst , Type modelType , GrowOnlyHashTable< string, AbstractDefaultsAttribute > defaultValues ) { PeripheralCategory value = new PeripheralCategory(); value.Model = modelType; ApplyDefaultValue( stack, value, defaultValues ); lst.Add( value ); } private void CreatePeripheralsForNestedTypes( List< Type > stack , List< PeripheralCategory > lst , Type modelType , GrowOnlyHashTable< string, AbstractDefaultsAttribute > defaultValues ) { Type[] array = modelType.GetNestedTypes( System.Reflection.BindingFlags.Public | System.Reflection.BindingFlags.NonPublic ); foreach(Type t in array) { if(t.IsAbstract == false && t.IsSubclassOf( typeof(Emulation.ArmProcessor.Simulator.Peripheral) )) { CreatePeripheral( stack, lst, t, defaultValues ); } } } private void CreateInterop( List< Type > stack , List< InteropCategory > lst , Type modelType , GrowOnlyHashTable< string, AbstractDefaultsAttribute > defaultValues ) { InteropCategory value = new InteropCategory(); value.Model = modelType; ApplyDefaultValue( stack, value, defaultValues ); lst.Add( value ); } private void CreateInteropsForNestedTypes( List< Type > stack , List< InteropCategory > lst , Type modelType , GrowOnlyHashTable< string, AbstractDefaultsAttribute > defaultValues ) { Type[] array = modelType.GetNestedTypes( System.Reflection.BindingFlags.Public | System.Reflection.BindingFlags.NonPublic ); foreach(Type t in array) { if(t.IsSubclassOf( typeof(Emulation.ArmProcessor.Simulator.InteropHandler) )) { CreateInterop( stack, lst, t, defaultValues ); } } } //--// private Type ValidateOption( System.Reflection.FieldInfo fi , Type t , string attrib , bool fRequired ) { List< Type > lst; if(m_allOptionsByType.TryGetValue( t, out lst ) == false) { throw TypeConsistencyErrorException.Create( "Field '{0}' is decorated with '{1} {2}', but '{2}' does not exist", fi, attrib, t.FullName ); } if(lst.Count != 1) { if(fRequired) { throw TypeConsistencyErrorException.Create( "Field '{0}' is decorated with '{1} {2}', but '{2}' is not unique", fi, attrib, t.FullName ); } return null; } return lst[0]; } // // Access Methods // public List< AbstractCategory > AllValues { get { return m_allValues; } } } } ================================================ FILE: Zelig/Zelig/CompileTime/TargetModels/ProductConfiguration/Models/Displays.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // namespace Microsoft.Zelig.Configuration.Environment { using System; using System.Collections.Generic; [DisplayName( "SED15E0 LCD controller" )] [Defaults ( "SizeInBytes", 0x00020000U )] [Defaults ( "WordSize" , 8 )] [Defaults ( "WaitStates" , 2 )] [HardwareModel(typeof(Emulation.ArmProcessor.Display.SED15E0), HardwareModelAttribute.Kind.Memory)] public sealed class SED15E0 : DisplayCategory { } } ================================================ FILE: Zelig/Zelig/CompileTime/TargetModels/ProductConfiguration/Models/Engines.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // namespace Microsoft.Zelig.Configuration.Environment { using System; using System.Collections.Generic; using Microsoft.Zelig.TargetModel.ArmProcessor; [DisplayName("ARM emulator")] [HardwareModel(typeof(Emulation.ArmProcessor.Simulator), HardwareModelAttribute.Kind.Engine)] public sealed class ArmEmulator : EngineCategory { public override object Instantiate(InstructionSet iset) { return new Emulation.ArmProcessor.Simulator(iset); } } } ================================================ FILE: Zelig/Zelig/CompileTime/TargetModels/ProductConfiguration/Models/LegacyProducts.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // namespace Microsoft.Zelig.Configuration.Environment { using System; using System.Collections.Generic; #region VOX PLATFORM [DisplayName( "Custom" )] public sealed class Custom : ProductCategory { [AllowedOptions( typeof( MM9691LP ) )] [Defaults( "CoreClockFrequency", 30000000UL )] [Defaults( "PeripheralsClockFrequency", 30000000UL )] [Defaults( "RealTimeClockFrequency", 32768UL )] public ProcessorCategory Processor; [Requires( "WordSize", 32 )] [Requires( "WordSize", 16 )] [Defaults( "BaseAddress", 0x10000000U )] [Defaults( "ConnectedToBus", typeof( MM9691LP.CacheController ) )] public FlashMemoryCategory FlashChip; [Defaults( "BaseAddress", 0x20000000U )] public DisplayCategory Display; } //--//--//--// [DisplayName( "VOX Solo Form Factor Board" )] public sealed class VoxSoloFormFactor : ProductCategory { class VoxSoloFormFactorLoader : NorFlashJtagLoaderCategory { public VoxSoloFormFactorLoader( ) : base( "VoxSoloFormFactorLoader", Microsoft.Zelig.ProductConfiguration.Loaders.Microsoft_VoxSoloFormFactorLoader ) { } } [AllowedOptions( typeof( VoxSoloFormFactorLoader ) )] [Defaults( "CanSetBreakpointsDuringReset", true )] [Defaults( "DriverName", "ARM7TDMI-S" )] public JtagLoaderCategory Loader; [AllowedOptions( typeof( MM9691LP ) )] [Defaults( "CoreClockFrequency", 30000000UL )] [Defaults( "PeripheralsClockFrequency", 30000000UL )] [Defaults( "RealTimeClockFrequency", 32768UL )] public ProcessorCategory Processor; [AllowedOptions( typeof( S29WS128N ) )] [Defaults( "BaseAddress", 0x10000000U )] [Requires( "WordSize", 16 )] [Defaults( "ConnectedToBus", typeof( MM9691LP.CacheController ) )] public FlashMemoryCategory FlashChip; [AllowedOptions( typeof( SED15E0 ) )] [Defaults( "BaseAddress", 0x20000000U )] [Defaults( "ConnectedToBus", typeof( MM9691LP.CacheController ) )] public DisplayCategory Display; [HardwareModel( typeof( Emulation.ArmProcessor.VoxSoloFormFactor.Interop ), HardwareModelAttribute.Kind.Interop )] public InteropCategory[] Interops; } [DisplayName( "VOX Solo Form Factor Board For RAM" )] public sealed class VoxSoloFormFactorForRAM : ProductCategory { class VoxSoloFormFactorLoader : RamJtagLoaderCategory { public VoxSoloFormFactorLoader( ) { } } [AllowedOptions( typeof( VoxSoloFormFactorLoader ) )] [Defaults( "CanSetBreakpointsDuringReset", true )] [Defaults( "DriverName", "ARM7TDMI-S" )] public JtagLoaderCategory Loader; [AllowedOptions( typeof( MM9691LP ) )] [Defaults( "CoreClockFrequency", 30000000UL )] [Defaults( "PeripheralsClockFrequency", 30000000UL )] [Defaults( "RealTimeClockFrequency", 32768UL )] public ProcessorCategory Processor; [AllowedOptions( typeof( S29WS128N ) )] [Defaults( "BaseAddress", 0x10000000U )] [Requires( "WordSize", 16 )] [Defaults( "ConnectedToBus", typeof( MM9691LP.CacheController ) )] public FlashMemoryCategory FlashChip; [AllowedOptions( typeof( SED15E0 ) )] [Defaults( "BaseAddress", 0x20000000U )] [Defaults( "ConnectedToBus", typeof( MM9691LP.CacheController ) )] public DisplayCategory Display; [HardwareModel( typeof( Emulation.ArmProcessor.VoxSoloFormFactor.Interop ), HardwareModelAttribute.Kind.Interop )] public InteropCategory[] Interops; } [DisplayName( "VOX Solo Form Factor Compilation" )] [Defaults( "Platform", typeof( Microsoft.Zelig.Configuration.Environment.Abstractions.Architectures.ArmV4 ) )] [Defaults( "CallingConvention", typeof( Microsoft.Zelig.Configuration.Environment.Abstractions.ArmCallingConvention ) )] [Defaults( "Product", typeof( VoxSoloFormFactor ) )] [Defaults( "MemoryMap", typeof( VoxSoloFormFactorMemoryMap ) )] public sealed class VoxSoloFormFactorCompilationSetup : CompilationSetupCategory { } [DisplayName( "VOX Solo Form Factor RAM Compilation" )] [Defaults( "Platform", typeof( Microsoft.Zelig.Configuration.Environment.Abstractions.Architectures.ArmV4 ) )] [Defaults( "CallingConvention", typeof( Microsoft.Zelig.Configuration.Environment.Abstractions.ArmCallingConvention ) )] [Defaults( "Product", typeof( VoxSoloFormFactorForRAM ) )] [Defaults( "MemoryMap", typeof( VoxSoloFormFactorRamMemoryMap ) )] public sealed class VoxSoloFormFactorRamCompilationSetup : CompilationSetupCategory { } [DisplayName( "VOX Solo Form Factor Memory Map" )] public sealed class VoxSoloFormFactorMemoryMap : MemoryMapCategory { [MergeEnumDefaults( "Characteristics", Runtime.MemoryAttributes.ExternalMemory | Runtime.MemoryAttributes.RandomAccessMemory | Runtime.MemoryAttributes.ConfiguredAtEntryPoint | Runtime.MemoryAttributes.LoadedAtEntrypoint )] [MemorySection( Runtime.MemoryUsage.Bootstrap | Runtime.MemoryUsage.Code | Runtime.MemoryUsage.DataRO | Runtime.MemoryUsage.Relocation, ExtensionHandler = typeof( MM9691LP.MemoryMapper ) )] [AllowedOptions( typeof( S29WS128N ) )] [Defaults( "BaseAddress", 0x10000000U )] public FlashMemoryCategory FlashChip; [MergeEnumDefaults( "Characteristics", Runtime.MemoryAttributes.InternalMemory | Runtime.MemoryAttributes.RandomAccessMemory | Runtime.MemoryAttributes.ConfiguredAtEntryPoint )] [MemorySection( Runtime.MemoryUsage.Stack | Runtime.MemoryUsage.Heap | Runtime.MemoryUsage.VectorsTable | Runtime.MemoryUsage.DataRW )] [AllowedOptions( typeof( MM9691LP.InternalRAM768KB ) )] public RamMemoryCategory RamChip; } [DisplayName( "VOX Solo Form Factor RAM Memory Map" )] public sealed class VoxSoloFormFactorRamMemoryMap : MemoryMapCategory { [MergeEnumDefaults( "Characteristics", Runtime.MemoryAttributes.InternalMemory | Runtime.MemoryAttributes.RandomAccessMemory | Runtime.MemoryAttributes.ConfiguredAtEntryPoint | Runtime.MemoryAttributes.LoadedAtEntrypoint )] [MemorySection( Runtime.MemoryUsage.Bootstrap | Runtime.MemoryUsage.Stack | Runtime.MemoryUsage.VectorsTable | Runtime.MemoryUsage.Code | Runtime.MemoryUsage.Heap | Runtime.MemoryUsage.DataRO | Runtime.MemoryUsage.DataRW )] [AllowedOptions( typeof( MM9691LP.InternalRAM768KB ) )] [Defaults( "BaseAddress", 0x08000000U )] public RamMemoryCategory RamChip; [AllowedOptions( typeof( S29WS064J ) )] [Defaults( "BaseAddress", 0x10000000U )] public FlashMemoryCategory FlashChip; } //--// [DisplayName( "VOX Solo Form Factor Loader Compilation" )] [Defaults( "Platform", typeof( Microsoft.Zelig.Configuration.Environment.Abstractions.Architectures.ArmV4 ) )] [Defaults( "CallingConvention", typeof( Microsoft.Zelig.Configuration.Environment.Abstractions.ArmCallingConvention ) )] [Defaults( "Product", typeof( VoxSoloFormFactorForRAM ) )] [Defaults( "MemoryMap", typeof( VoxSoloFormFactorLoaderMemoryMap ) )] public sealed class VoxSoloFormFactorLoaderCompilationSetup : LoaderCompilationSetupCategory { } [DisplayName( "VOX Solo Form Factor Loader Memory Map" )] public sealed class VoxSoloFormFactorLoaderMemoryMap : MemoryMapCategory { [MergeEnumDefaults( "Characteristics", Runtime.MemoryAttributes.InternalMemory | Runtime.MemoryAttributes.RandomAccessMemory | Runtime.MemoryAttributes.ConfiguredAtEntryPoint | Runtime.MemoryAttributes.LoadedAtEntrypoint )] [MemorySection( Runtime.MemoryUsage.Bootstrap | Runtime.MemoryUsage.Stack | Runtime.MemoryUsage.VectorsTable | Runtime.MemoryUsage.Code | Runtime.MemoryUsage.DataRO | Runtime.MemoryUsage.DataRW )] [AllowedOptions( typeof( MM9691LP.InternalRAM768KB ) )] [Defaults( "BaseAddress", 0x08000000U )] public RamMemoryCategory RamChip; [AllowedOptions( typeof( S29WS128N ) )] [Defaults( "BaseAddress", 0x10000000U )] public FlashMemoryCategory FlashChip; } #endregion // VOX_PLATFORM //--//--//--// #region LPC3180 Platform [DisplayName( "NOHAU LPC3180 Board for RAM" )] public sealed class NohauLPC3180ForRAM : ProductCategory { class NohauLPC3180ForRAMLoader : RamJtagLoaderCategory { public NohauLPC3180ForRAMLoader( ) { } } [AllowedOptions( typeof( NohauLPC3180ForRAMLoader ) )] [Defaults( "CanSetBreakpointsDuringReset", true )] [Defaults( "DriverName", "ARM9EJ-S" )] [Defaults( "Speed", 12000 )] public JtagLoaderCategory Loader; [AllowedOptions( typeof( LPC3180 ) )] [Defaults( "CoreClockFrequency", 208000000UL )] [Defaults( "PeripheralsClockFrequency", 13000000UL )] [Defaults( "RealTimeClockFrequency", 32768UL )] [Defaults( "AHBClockFrequency", 104000000UL )] [Defaults( "DRAMWideBus", true )] public ProcessorCategory Processor; //--// [AllowedOptions( typeof( MT48H8M16LF ) )] [Defaults( "BaseAddress", 0x80000000U )] public RamMemoryCategory ExternalRamChip; [AllowedOptions( typeof( ST_NAND256A ) )] [Defaults( "BaseAddress", 0xA0000000U )] public FlashMemoryCategory ExternalFlashChip; } public abstract class NohauLPC3180Abstract : ProductCategory { class NohauLPC3180Loader : NandFlashJtagLoaderCategory { class ExtraDeploymentSteps : Emulation.Hosting.ExtraDeploymentSteps { // // Helper Methods // public override List TransformImage( List image ) { const uint baseIRAM = 0x08000000; const uint baseAddress = 0xA0000000; const uint pageSize = 512; List< ImageSection > iramSections = new List( ); List< ImageSection > nandSections = new List( ); List< ImageSection > modifiedImage = new List( ); foreach( ImageSection sec in image ) { if( ( sec.Attributes & Runtime.MemoryAttributes.LoadedAtEntrypoint ) != 0 && ( sec.Usage & Runtime.MemoryUsage.Relocation ) == 0 ) { iramSections.Add( sec ); } else if( sec.NeedsRelocation == false ) { nandSections.Add( sec ); } } uint lowestAddress = uint.MaxValue; uint highestAddress = uint.MinValue; foreach( ImageSection sec in iramSections ) { uint address = sec.Address; lowestAddress = Math.Min( lowestAddress, address ); highestAddress = Math.Max( highestAddress, address + ( uint )sec.Payload.Length ); } byte numPages = ( byte )( ( highestAddress + pageSize - 1 ) / pageSize ); modifiedImage.Add( CreateSection( baseAddress, CreateICF( numPages ) ) ); foreach( ImageSection sec in iramSections ) { modifiedImage.Add( CreateSection( baseAddress + pageSize + ( sec.Address - baseIRAM ), sec.Payload ) ); } modifiedImage.AddRange( nandSections ); return modifiedImage; } public override void ExecuteToEntryPoint( Emulation.Hosting.AbstractHost owner, uint entryPointAddress ) { Emulation.Hosting.ProcessorControl svcPC; if( owner.GetHostingService( out svcPC ) ) { List< Emulation.Hosting.Breakpoint > lst = new List( ); Emulation.Hosting.Breakpoint bp = new Emulation.Hosting.Breakpoint( entryPointAddress, null, null ); bp.IsActive = true; lst.Add( bp ); svcPC.Execute( lst ); } } //--// private static byte[] CreateICF( byte size ) { // 0x00000000 F0 FF FF FF F0 FF FF FF F0 FF FF FF F0 FF FF FF ................ << ICR // 0x00000010 04 FF FF FF FB FF FF FF 04 FF FF FF FB FF FF FF ................ << Size (interleaved with ~Size) // 0x00000020 04 FF FF FF FB FF FF FF 04 FF FF FF FB FF FF FF ................ << Size (interleaved with ~Size) // 0x00000030 AA 00 00 00 FF FF FF FF FF FF FF FF FF FF FF FF ................ << OK marker byte[] payload = new byte[ 512 ]; for( int i = 0; i < 512; i++ ) { payload[ i ] = 0xFF; } for( int i = 0; i < 0x10; i += 4 ) { payload[ i ] = 0xF0; // ICR } size += 1; // Include ICF block in the count. for( int i = 0x10; i < 0x30; i += 8 ) { payload[ i ] = size; payload[ i + 4 ] = ( byte )~size; } payload[ 0x30 ] = 0xAA; payload[ 0x31 ] = 0x00; payload[ 0x32 ] = 0x00; payload[ 0x33 ] = 0x00; return payload; } private static ImageSection CreateSection( uint address, byte[] payload ) { const Runtime.MemoryAttributes attrib = Runtime.MemoryAttributes.FLASH | Runtime.MemoryAttributes.ExternalMemory | Runtime.MemoryAttributes.BlockBasedMemory; const Runtime.MemoryUsage usage = Runtime.MemoryUsage.Booter | Runtime.MemoryUsage.Relocation; return new ImageSection( address, payload, null, attrib, usage ); } } public NohauLPC3180Loader( ) : base( "NohauLPC3180Loader", Microsoft.Zelig.ProductConfiguration.Loaders.Microsoft_NohauLPC3180Loader ) { } //--// protected override object GetServiceInner( Type t ) { if( t == typeof( Emulation.Hosting.ExtraDeploymentSteps ) ) { return new ExtraDeploymentSteps( ); } return base.GetServiceInner( t ); } } [AllowedOptions( typeof( NohauLPC3180Loader ) )] [Defaults( "CanSetBreakpointsDuringReset", true )] [Defaults( "DriverName", "ARM9EJ-S" )] [Defaults( "Speed", 12000 )] public JtagLoaderCategory Loader; //--// [AllowedOptions( typeof( MT48H8M16LF ) )] [Defaults( "BaseAddress", 0x80000000U )] public RamMemoryCategory ExternalRamChip; [AllowedOptions( typeof( ST_NAND256A ) )] [Defaults( "BaseAddress", 0xA0000000U )] public FlashMemoryCategory ExternalFlashChip; } [DisplayName( "NOHAU LPC3180 Board" )] public sealed class NohauLPC3180 : NohauLPC3180Abstract { [AllowedOptions( typeof( LPC3180 ) )] [Defaults( "CoreClockFrequency", 208000000UL )] [Defaults( "PeripheralsClockFrequency", 13000000UL )] [Defaults( "RealTimeClockFrequency", 32768UL )] [Defaults( "AHBClockFrequency", 104000000UL )] [Defaults( "DRAMWideBus", true )] public ProcessorCategory Processor; } [DisplayName( "NOHAU LPC3180 Board For Solo" )] public sealed class NohauLPC3180Solo : NohauLPC3180Abstract { [AllowedOptions( typeof( LPC3180 ) )] [Defaults( "CoreClockFrequency", 104000000UL )] [Defaults( "PeripheralsClockFrequency", 13000000UL )] [Defaults( "RealTimeClockFrequency", 32768UL )] [Defaults( "AHBClockFrequency", 104000000UL )] [Defaults( "DRAMWideBus", false )] public ProcessorCategory Processor; } //--// [DisplayName( "NOHAU LPC3180 Loader Compilation" )] [Defaults( "Platform", typeof( Microsoft.Zelig.Configuration.Environment.Abstractions.Architectures.ArmV5_VFP ) )] [Defaults( "CallingConvention", typeof( Microsoft.Zelig.Configuration.Environment.Abstractions.ArmCallingConvention ) )] [Defaults( "Product", typeof( NohauLPC3180ForRAM ) )] [Defaults( "MemoryMap", typeof( NohauLPC3180LoaderMemoryMap ) )] public sealed class NohauLPC3180LoaderCompilationSetup : LoaderCompilationSetupCategory { } [DisplayName( "NOHAU LPC3180 Loader Memory Map" )] public sealed class NohauLPC3180LoaderMemoryMap : MemoryMapCategory { [MergeEnumDefaults( "Characteristics", Runtime.MemoryAttributes.InternalMemory | Runtime.MemoryAttributes.RandomAccessMemory | Runtime.MemoryAttributes.ConfiguredAtEntryPoint | Runtime.MemoryAttributes.LoadedAtEntrypoint )] [MemorySection( Runtime.MemoryUsage.Bootstrap | Runtime.MemoryUsage.Stack | Runtime.MemoryUsage.VectorsTable | Runtime.MemoryUsage.Code | Runtime.MemoryUsage.DataRO | Runtime.MemoryUsage.DataRW )] [AllowedOptions( typeof( LPC3180.InternalRAM64KB ) )] [Defaults( "BaseAddress", 0x08000000U )] public RamMemoryCategory RamChip; } //--// [DisplayName( "NOHAU LPC3180 Compilation" )] [Defaults( "Platform", typeof( Microsoft.Zelig.Configuration.Environment.Abstractions.Architectures.ArmV5_VFP ) )] [Defaults( "CallingConvention", typeof( Microsoft.Zelig.Configuration.Environment.Abstractions.ArmCallingConvention ) )] [Defaults( "Product", typeof( NohauLPC3180 ) )] [Defaults( "MemoryMap", typeof( NohauLPC3180MemoryMap ) )] public sealed class NohauLPC3180CompilationSetup : CompilationSetupCategory { } [DisplayName( "NOHAU LPC3180 For Solo Compilation" )] [Defaults( "Platform", typeof( Microsoft.Zelig.Configuration.Environment.Abstractions.Architectures.ArmV5_VFP ) )] [Defaults( "CallingConvention", typeof( Microsoft.Zelig.Configuration.Environment.Abstractions.ArmCallingConvention ) )] [Defaults( "Product", typeof( NohauLPC3180Solo ) )] [Defaults( "MemoryMap", typeof( NohauLPC3180MemoryMap ) )] public sealed class NohauLPC3180SoloCompilationSetup : CompilationSetupCategory { } [DisplayName( "NOHAU LPC3180 Memory Map" )] public sealed class NohauLPC3180MemoryMap : MemoryMapCategory { [MergeEnumDefaults( "Characteristics", Runtime.MemoryAttributes.InternalMemory | Runtime.MemoryAttributes.RandomAccessMemory | Runtime.MemoryAttributes.ConfiguredAtEntryPoint | Runtime.MemoryAttributes.LoadedAtEntrypoint )] [MemorySection( Runtime.MemoryUsage.Bootstrap | Runtime.MemoryUsage.Stack | Runtime.MemoryUsage.VectorsTable | Runtime.MemoryUsage.DataRW )] [AllowedOptions( typeof( LPC3180.InternalRAM64KB ) )] [ReserveBlock( 64 * 1024 - 4096, 4096, Reason = "This area is used by the ROM bootloader" )] [Defaults( "BaseAddress", 0x08000000U )] public RamMemoryCategory InternalRamChip; [MergeEnumDefaults( "Characteristics", Runtime.MemoryAttributes.ExternalMemory | Runtime.MemoryAttributes.RandomAccessMemory )] [MemorySection( Runtime.MemoryUsage.Code | Runtime.MemoryUsage.Heap | Runtime.MemoryUsage.DataRO | Runtime.MemoryUsage.DataRW )] [AllowedOptions( typeof( MT48H8M16LF ) )] [ReserveBlock( 1 * 8 * 1024 * 1024, 1 * 8 * 1024 * 1024, Reason = "This area is set aside for the Persistence Storage" )] [Defaults( "BaseAddress", 0x80000000U )] public RamMemoryCategory ExternalRamChip; [MergeEnumDefaults( "Characteristics", Runtime.MemoryAttributes.ExternalMemory | Runtime.MemoryAttributes.BlockBasedMemory )] [MemorySection( Runtime.MemoryUsage.Booter | Runtime.MemoryUsage.Relocation )] [ReserveBlock( 0x00000000, 2 * 32 * 1024, Reason = "This area is copied into internal RAM by LPC3180 during bootstrap" )] [AllowedOptions( typeof( ST_NAND256A ) )] [Defaults( "BaseAddress", 0xA0000000U )] public FlashMemoryCategory ExternalFlashChip; } #endregion //LPC3180 Platform //--//--//--// #region iMote2 Platform [DisplayName( "iMote2 Board for RAM" )] public sealed class iMote2ForRAM : ProductCategory { class iMote2ForRAMLoader : RamJtagLoaderCategory { public iMote2ForRAMLoader( ) { } } [AllowedOptions( typeof( iMote2ForRAMLoader ) )] [Defaults( "DriverName", "PXA27x" )] [Defaults( "Speed", 12000 )] public JtagLoaderCategory Loader; [AllowedOptions( typeof( PXA27x ) )] [Defaults( "CoreClockFrequency", 416000000UL )] [Defaults( "PeripheralsClockFrequency", 13000000UL )] [Defaults( "RealTimeClockFrequency", 1000000UL )] public ProcessorCategory Processor; //--// [Defaults( "BaseAddress", 0x5C000000U )] public RamMemoryCategory InternalRam; [AllowedOptions( typeof( MT48H16M16LF ) )] [Defaults( "BaseAddress", 0xA0000000U )] public RamMemoryCategory ExternalRamChip; [AllowedOptions( typeof( I28F256L18_16 ) )] [Defaults( "BaseAddress", 0x02000000U )] public FlashMemoryCategory ExternalFlashChip; } [DisplayName( "iMote2 Board" )] public sealed class iMote2 : ProductCategory { class iMote2Loader : XScaleNorFlashJTagLoaderCategory { public iMote2Loader( ) : base( "iMote2Loader", Microsoft.Zelig.ProductConfiguration.Loaders.Microsoft_iMote2Loader ) { } } [AllowedOptions( typeof( iMote2Loader ) )] [Defaults( "DriverName", "PXA27x" )] [Defaults( "Speed", 12000 )] public JtagLoaderCategory Loader; [AllowedOptions( typeof( PXA27x ) )] [Defaults( "CoreClockFrequency", 416000000UL )] [Defaults( "PeripheralsClockFrequency", 13000000UL )] [Defaults( "RealTimeClockFrequency", 1000000UL )] public ProcessorCategory Processor; //--// [Defaults( "BaseAddress", 0x5C000000U )] public RamMemoryCategory InternalRam; [AllowedOptions( typeof( MT48H16M16LF ) )] [Defaults( "BaseAddress", 0xA0000000U )] public RamMemoryCategory ExternalRamChip; [AllowedOptions( typeof( I28F256L18_16 ) )] [Defaults( "BaseAddress", 0x02000000U )] public FlashMemoryCategory ExternalFlashChip; } //--// [DisplayName( "iMote2 Loader Compilation" )] [Defaults( "Platform", typeof( Microsoft.Zelig.Configuration.Environment.Abstractions.Architectures.ArmV4 ) )] [Defaults( "CallingConvention", typeof( Microsoft.Zelig.Configuration.Environment.Abstractions.ArmCallingConvention ) )] [Defaults( "Product", typeof( iMote2ForRAM ) )] [Defaults( "MemoryMap", typeof( iMote2LoaderMemoryMap ) )] public sealed class iMote2LoaderCompilationSetup : LoaderCompilationSetupCategory { } [DisplayName( "iMote2 Loader Memory Map" )] public sealed class iMote2LoaderMemoryMap : MemoryMapCategory { [MergeEnumDefaults( "Characteristics", Runtime.MemoryAttributes.InternalMemory | Runtime.MemoryAttributes.RandomAccessMemory | Runtime.MemoryAttributes.ConfiguredAtEntryPoint | Runtime.MemoryAttributes.LoadedAtEntrypoint )] [MemorySection( Runtime.MemoryUsage.Bootstrap | Runtime.MemoryUsage.Stack | Runtime.MemoryUsage.VectorsTable | Runtime.MemoryUsage.Code | Runtime.MemoryUsage.DataRO | Runtime.MemoryUsage.DataRW )] [AllowedOptions( typeof( PXA27x.InternalRAM256KB ) )] [Defaults( "BaseAddress", 0x5C000000U )] public RamMemoryCategory RamChip; } //--// [DisplayName( "iMote2 Compilation" )] [Defaults( "Platform", typeof( Microsoft.Zelig.Configuration.Environment.Abstractions.Architectures.ArmV4 ) )] [Defaults( "CallingConvention", typeof( Microsoft.Zelig.Configuration.Environment.Abstractions.ArmCallingConvention ) )] [Defaults( "Product", typeof( iMote2 ) )] [Defaults( "MemoryMap", typeof( iMote2MemoryMap ) )] public sealed class iMote2CompilationSetup : CompilationSetupCategory { } [DisplayName( "iMote2 Memory Map" )] public sealed class iMote2MemoryMap : MemoryMapCategory { [MergeEnumDefaults( "Characteristics", Runtime.MemoryAttributes.ExternalMemory | Runtime.MemoryAttributes.RandomAccessMemory | Runtime.MemoryAttributes.ConfiguredAtEntryPoint | Runtime.MemoryAttributes.LoadedAtEntrypoint )] [MemorySection( Runtime.MemoryUsage.Bootstrap | Runtime.MemoryUsage.Code | Runtime.MemoryUsage.DataRO | Runtime.MemoryUsage.Relocation )] [AllowedOptions( typeof( I28F256L18_16 ) )] [Defaults( "BaseAddress", 0x02000000U )] public FlashMemoryCategory ExternalFlashChip; [MergeEnumDefaults( "Characteristics", Runtime.MemoryAttributes.InternalMemory | Runtime.MemoryAttributes.RandomAccessMemory | Runtime.MemoryAttributes.ConfiguredAtEntryPoint )] [MemorySection( Runtime.MemoryUsage.Stack | Runtime.MemoryUsage.VectorsTable | Runtime.MemoryUsage.Code )] [AllowedOptions( typeof( PXA27x.InternalRAM256KB ) )] [Defaults( "BaseAddress", 0x5C000000U )] public RamMemoryCategory InternalRamChip; [MergeEnumDefaults( "Characteristics", Runtime.MemoryAttributes.ExternalMemory | Runtime.MemoryAttributes.RandomAccessMemory )] [MemorySection( Runtime.MemoryUsage.Heap | Runtime.MemoryUsage.DataRW )] [AllowedOptions( typeof( MT48H16M16LF ) )] [ReserveBlock( 2 * 8 * 1024 * 1024, 2 * 8 * 1024 * 1024, Reason = "This area is set aside for the Persistence Storage" )] [Defaults( "BaseAddress", 0xA0000000U )] public RamMemoryCategory ExternalRamChip; } [DisplayName( "iMote2 Memory Map with Code in FLASH" )] public sealed class iMote2MemoryMapForCodeInFlash : MemoryMapCategory { [MergeEnumDefaults( "Characteristics", Runtime.MemoryAttributes.ExternalMemory | Runtime.MemoryAttributes.RandomAccessMemory | Runtime.MemoryAttributes.ConfiguredAtEntryPoint | Runtime.MemoryAttributes.LoadedAtEntrypoint )] [MemorySection( Runtime.MemoryUsage.Bootstrap | Runtime.MemoryUsage.Code | Runtime.MemoryUsage.DataRO | Runtime.MemoryUsage.Relocation )] [AllowedOptions( typeof( I28F256L18_16 ) )] [Defaults( "BaseAddress", 0x02000000U )] public FlashMemoryCategory ExternalFlashChip; [MergeEnumDefaults( "Characteristics", Runtime.MemoryAttributes.InternalMemory | Runtime.MemoryAttributes.RandomAccessMemory | Runtime.MemoryAttributes.ConfiguredAtEntryPoint )] [MemorySection( Runtime.MemoryUsage.Stack | Runtime.MemoryUsage.VectorsTable )] [AllowedOptions( typeof( PXA27x.InternalRAM256KB ) )] [Defaults( "BaseAddress", 0x5C000000U )] public RamMemoryCategory InternalRamChip; [MergeEnumDefaults( "Characteristics", Runtime.MemoryAttributes.ExternalMemory | Runtime.MemoryAttributes.RandomAccessMemory )] [MemorySection( Runtime.MemoryUsage.Heap | Runtime.MemoryUsage.DataRW )] [AllowedOptions( typeof( MT48H16M16LF ) )] [ReserveBlock( 2 * 8 * 1024 * 1024, 2 * 8 * 1024 * 1024, Reason = "This area is set aside for the Persistence Storage" )] [Defaults( "BaseAddress", 0xA0000000U )] public RamMemoryCategory ExternalRamChip; } #endregion //iMote2 Platform } ================================================ FILE: Zelig/Zelig/CompileTime/TargetModels/ProductConfiguration/Models/Memories.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // namespace Microsoft.Zelig.Configuration.Environment { using System; using System.Collections.Generic; [DisplayName( "Intel 8MB NOR Flash" )] [Defaults ( "SizeInBytes" , 8 * 1024 * 1024 )] [Defaults ( "WordSize" , 32 )] [Defaults ( "WaitStates" , 2 )] [EnumDefaults( "Characteristics", Runtime.MemoryAttributes.FLASH | Runtime.MemoryAttributes.RandomAccessMemory | Runtime.MemoryAttributes.ExternalMemory )] [HardwareModel(typeof(Emulation.ArmProcessor.Simulator.MemoryHandler), HardwareModelAttribute.Kind.Memory)] public sealed class I28F320W18_32 : FlashMemoryCategory { } [DisplayName( "Intel 32MB NOR Flash" )] [Defaults ( "SizeInBytes" , 32 * 1024 * 1024 )] [Defaults ( "WordSize" , 16 )] [Defaults ( "WaitStates" , 2 )] [EnumDefaults( "Characteristics", Runtime.MemoryAttributes.FLASH | Runtime.MemoryAttributes.RandomAccessMemory | Runtime.MemoryAttributes.ExternalMemory )] [HardwareModel(typeof(Emulation.ArmProcessor.Simulator.MemoryHandler), HardwareModelAttribute.Kind.Memory)] public sealed class I28F256L18_16 : FlashMemoryCategory { } [DisplayName("Spansion 8MB NOR Flash")] [Defaults ( "SizeInBytes" , 8 * 1024 * 1024 )] [Defaults ( "WordSize" , 16 )] [Defaults ( "WaitStates" , 2 )] [EnumDefaults( "Characteristics", Runtime.MemoryAttributes.FLASH | Runtime.MemoryAttributes.RandomAccessMemory | Runtime.MemoryAttributes.ExternalMemory )] [HardwareModel(typeof(Emulation.ArmProcessor.FlashMemory.S29WS064), HardwareModelAttribute.Kind.Memory)] public sealed class S29WS064J : FlashMemoryCategory { } [DisplayName( "Spansion 16MB NOR Flash" )] [Defaults ( "SizeInBytes" , 16 * 1024 * 1024 )] [Defaults ( "WordSize" , 16 )] [Defaults ( "WaitStates" , 2 )] [EnumDefaults( "Characteristics", Runtime.MemoryAttributes.FLASH | Runtime.MemoryAttributes.RandomAccessMemory | Runtime.MemoryAttributes.ExternalMemory )] [HardwareModel(typeof(Emulation.ArmProcessor.FlashMemory.S29WS128N), HardwareModelAttribute.Kind.Memory)] public sealed class S29WS128N : FlashMemoryCategory { } [DisplayName( "ST 256Mb NAND FLASH" )] [Defaults ( "SizeInBytes" , 32 * 1024 * 1024 )] [Defaults ( "WordSize" , 8 )] [Defaults ( "WaitStates" , 0 )] [EnumDefaults( "Characteristics", Runtime.MemoryAttributes.FLASH | Runtime.MemoryAttributes.BlockBasedMemory | Runtime.MemoryAttributes.ExternalMemory )] ////[HardwareModel(typeof(Emulation.ArmProcessor.NandFlashMemory.ST_NAND256A), HardwareModelAttribute.Kind.Memory)] public sealed class ST_NAND256A : FlashMemoryCategory { } [DisplayName( "Micron 16MB Mobile SDRAM" )] [Defaults ( "SizeInBytes" , 1 * 16 * 1024 * 1024 )] [Defaults ( "WordSize" , 1 * 16 )] [Defaults ( "WaitStates" , 0 )] [EnumDefaults( "Characteristics", Runtime.MemoryAttributes.RAM | Runtime.MemoryAttributes.RandomAccessMemory | Runtime.MemoryAttributes.ExternalMemory )] ////[HardwareModel(typeof(Emulation.ArmProcessor.FlashMemory.MT48H8M16LF), HardwareModelAttribute.Kind.Memory)] public sealed class MT48H8M16LF : RamMemoryCategory { } [DisplayName( "Micron 32MB Mobile SDRAM" )] [Defaults ( "SizeInBytes" , 1 * 32 * 1024 * 1024 )] [Defaults ( "WordSize" , 1 * 16 )] [Defaults ( "WaitStates" , 0 )] [EnumDefaults( "Characteristics", Runtime.MemoryAttributes.RAM | Runtime.MemoryAttributes.RandomAccessMemory | Runtime.MemoryAttributes.ExternalMemory )] ////[HardwareModel(typeof(Emulation.ArmProcessor.FlashMemory.MT48H8M16LF), HardwareModelAttribute.Kind.Memory)] public sealed class MT48H16M16LF : RamMemoryCategory { } } ================================================ FILE: Zelig/Zelig/CompileTime/TargetModels/ProductConfiguration/Models/Processors.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // namespace Microsoft.Zelig.Configuration.Environment { using System; using System.Collections.Generic; [DisplayName("MM9691LP (Ollie 768)")] public sealed class MM9691LP : ProcessorCategory { public class MemoryMapper : IMemoryMapper { const uint CacheableMask = 0x80000000u; //--// public uint GetCacheableAddress( uint address ) { return address | CacheableMask; } public uint GetUncacheableAddress( uint address ) { return address & ~CacheableMask; } } [DependsOn(typeof(MM9691LP))] [DisplayName("Internal 384KB Static RAM")] [Defaults ( "BaseAddress" , 0x08000000 )] [Defaults ( "SizeInBytes" , 384 * 1024 )] [Defaults ( "WordSize" , 32 )] [Defaults ( "WaitStates" , 0 )] [EnumDefaults( "Characteristics", Runtime.MemoryAttributes.RAM | Runtime.MemoryAttributes.RandomAccessMemory | Runtime.MemoryAttributes.InternalMemory | Runtime.MemoryAttributes.ConfiguredAtEntryPoint )] [HardwareModel(typeof(Emulation.ArmProcessor.Chipset.MM9691LP.RamMemoryHandler), HardwareModelAttribute.Kind.Memory)] public sealed class InternalRAM384KB : RamMemoryCategory { } [DependsOn(typeof(MM9691LP))] [DisplayName("Internal 768KB Static RAM")] [Defaults ( "BaseAddress" , 0x08000000 )] [Defaults ( "SizeInBytes" , 768 * 1024 )] [Defaults ( "WordSize" , 32 )] [Defaults ( "WaitStates" , 0 )] [EnumDefaults( "Characteristics", Runtime.MemoryAttributes.RAM | Runtime.MemoryAttributes.RandomAccessMemory | Runtime.MemoryAttributes.InternalMemory | Runtime.MemoryAttributes.ConfiguredAtEntryPoint )] [HardwareModel(typeof(Emulation.ArmProcessor.Chipset.MM9691LP.RamMemoryHandler), HardwareModelAttribute.Kind.Memory)] public sealed class InternalRAM768KB : RamMemoryCategory { } [DependsOn(typeof(MM9691LP))] [DisplayName("Cache Controller")] [Defaults( "WordSize" , 32 )] [Defaults( "WaitStates" , 0 )] [HardwareModel(typeof(Emulation.ArmProcessor.Chipset.MM9691LP.CacheMemoryHandler), HardwareModelAttribute.Kind.Memory)] public sealed class CacheController : CacheControllerCategory { public override uint GetUncacheableAddress( uint address ) { return Emulation.ArmProcessor.Chipset.MM9691LP.CacheMemoryHandler.GetUncacheableAddress( address ); } } [AllowedOptions(typeof(MM9691LP.InternalRAM768KB))] [Defaults( "ConnectedToBus", typeof(MM9691LP.CacheController) )] public RamMemoryCategory RamChip; [HardwareModel(typeof(Emulation.ArmProcessor.Chipset.MM9691LP), HardwareModelAttribute.Kind.PeripheralsGroup)] [Defaults( "ConnectedToBus", typeof(MM9691LP.CacheController))] public PeripheralCategory[] Peripherals; [AllowedOptions(typeof(MM9691LP.CacheController))] [Defaults( "ConnectedToBus", typeof(MM9691LP) )] public CacheControllerCategory Cache; } [DisplayName("LPC3180")] public sealed class LPC3180 : ProcessorCategory { [DependsOn(typeof(LPC3180))] [DisplayName("Internal 64KB Static RAM")] [Defaults ( "BaseAddress" , 0x08000000 )] [Defaults ( "SizeInBytes" , 64 * 1024 )] [Defaults ( "WordSize" , 32 )] [Defaults ( "WaitStates" , 0 )] [EnumDefaults( "Characteristics", Runtime.MemoryAttributes.RAM | Runtime.MemoryAttributes.RandomAccessMemory | Runtime.MemoryAttributes.InternalMemory | Runtime.MemoryAttributes.ConfiguredAtEntryPoint )] //// [HardwareModel(typeof(Emulation.ArmProcessor.LPC3180.RamMemoryHandler), HardwareModelAttribute.Kind.Memory)] public sealed class InternalRAM64KB : RamMemoryCategory { } [AllowedOptions(typeof(LPC3180.InternalRAM64KB))] [Defaults( "ConnectedToBus", typeof(LPC3180))] public RamMemoryCategory RamChip; //// [HardwareModel(typeof(Emulation.ArmProcessor.Chipset.MM9691LP), HardwareModelAttribute.Kind.PeripheralsGroup)] [Defaults( "ConnectedToBus", typeof(LPC3180))] public PeripheralCategory[] Peripherals; [DisplayName("AHB Clock Frequency")] [LinkToConfigurationOption("LPC3180__AHBClockFrequency")] public ulong AHBClockFrequency; [DisplayName("Use wide DRAM Bus")] [LinkToConfigurationOption("LPC3180__DRAMWideBus")] public bool DRAMWideBus; } [DisplayName("PXA27x")] public sealed class PXA27x : ProcessorCategory { [DependsOn(typeof(PXA27x))] [DisplayName("Internal 256KB Static RAM")] [Defaults ( "BaseAddress" , 0x5C000000 )] [Defaults ( "SizeInBytes" , 256 * 1024 )] [Defaults ( "WordSize" , 32 )] [Defaults ( "WaitStates" , 0 )] [EnumDefaults( "Characteristics", Runtime.MemoryAttributes.RAM | Runtime.MemoryAttributes.RandomAccessMemory | Runtime.MemoryAttributes.InternalMemory | Runtime.MemoryAttributes.ConfiguredAtEntryPoint )] [HardwareModel(typeof(Emulation.ArmProcessor.Chipset.PXA27x.RamMemoryHandler), HardwareModelAttribute.Kind.Memory)] public sealed class InternalRAM256KB : RamMemoryCategory { } [DependsOn( typeof( PXA27x ) )] [DisplayName( "Internal 32MB SDRAM" )] [Defaults( "BaseAddress", 0x20000000 )] [Defaults( "SizeInBytes", 32 * 1024 * 1024 )] [Defaults( "WordSize", 32 )] [Defaults( "WaitStates", 0 )] [EnumDefaults( "Characteristics", Runtime.MemoryAttributes.RAM | Runtime.MemoryAttributes.RandomAccessMemory | Runtime.MemoryAttributes.ExternalMemory | Runtime.MemoryAttributes.ConfiguredAtEntryPoint )] [HardwareModel( typeof( Emulation.ArmProcessor.Chipset.PXA27x.RamMemoryHandler ), HardwareModelAttribute.Kind.Memory )] public sealed class InternalSDRAM32MB : RamMemoryCategory { } [DependsOn( typeof( PXA27x ) )] [DisplayName( "Internal 32MB FLASH" )] [Defaults( "BaseAddress", 0x02000000 )] [Defaults( "SizeInBytes", 32 * 1024 * 1024 )] [Defaults( "WordSize", 32 )] [Defaults( "WaitStates", 0 )] [EnumDefaults( "Characteristics", Runtime.MemoryAttributes.RAM | Runtime.MemoryAttributes.RandomAccessMemory | Runtime.MemoryAttributes.InternalMemory | Runtime.MemoryAttributes.ConfiguredAtEntryPoint )] [HardwareModel( typeof( Emulation.ArmProcessor.Chipset.PXA27x.RamMemoryHandler ), HardwareModelAttribute.Kind.Memory )] public sealed class InternalFlash32MB : RamMemoryCategory { } [DependsOn(typeof(PXA27x))] [DisplayName("Cache Controller")] [Defaults( "WordSize" , 32 )] [Defaults( "WaitStates" , 0 )] [HardwareModel(typeof(Emulation.ArmProcessor.Chipset.PXA27x.CacheMemoryHandler), HardwareModelAttribute.Kind.Memory)] public sealed class CacheController : CacheControllerCategory { public override uint GetUncacheableAddress( uint address ) { return Emulation.ArmProcessor.Chipset.PXA27x.CacheMemoryHandler.GetUncacheableAddress( address ); } } [AllowedOptions(typeof(PXA27x.InternalRAM256KB))] [Defaults( "ConnectedToBus", typeof( PXA27x.CacheController ) )] public RamMemoryCategory RamChip; [AllowedOptions( typeof( PXA27x.InternalFlash32MB ) )] [Defaults( "ConnectedToBus", typeof( PXA27x.CacheController ) )] public RamMemoryCategory FlashChip; [AllowedOptions( typeof( PXA27x.InternalSDRAM32MB ) )] [Defaults( "ConnectedToBus", typeof( PXA27x.CacheController ) )] public RamMemoryCategory SDRamChip; [HardwareModel( typeof( Emulation.ArmProcessor.Chipset.PXA27x ), HardwareModelAttribute.Kind.PeripheralsGroup )] [Defaults( "ConnectedToBus", typeof( PXA27x.CacheController ) )] public PeripheralCategory[] Peripherals; [AllowedOptions( typeof( PXA27x.CacheController ) )] [Defaults( "ConnectedToBus", typeof( PXA27x ) )] public CacheControllerCategory Cache; //// [DisplayName("AHB Clock Frequency")] //// [LinkToConfigurationOption("LPC3180__AHBClockFrequency")] //// public ulong AHBClockFrequency; //// [DisplayName("Use wide DRAM Bus")] //// [LinkToConfigurationOption("LPC3180__DRAMWideBus")] //// public bool DRAMWideBus; } [DisplayName("mBed")] public sealed class mBed : ProcessorCategory { } } ================================================ FILE: Zelig/Zelig/CompileTime/TargetModels/ProductConfiguration/NandFlashJTagLoaderCategory.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // namespace Microsoft.Zelig.Configuration.Environment { using System; using System.Threading; using System.Collections.Generic; using Cfg = Microsoft.Zelig.Configuration.Environment; public abstract class NandFlashJtagLoaderCategory : JtagLoaderCategory { class NandFlashLoader : Emulation.Hosting.JTagCustomer { enum BlockState { Uninitialized , DataLoaded , DataLoadedAndChecked, BadBlock , } class BlockEntry { internal NandFlashLoader m_owner; internal BlockState m_state; internal uint m_index; internal uint m_physicalAddress; internal uint[] m_data; internal uint m_local_logicalAddress; internal uint m_local_checksum; internal bool m_local_fErased; internal uint m_device_logicalAddress; internal uint m_device_checksum; internal bool m_device_fErased; internal bool m_device_fBadBlock; // // Constructor Methods // internal BlockEntry( NandFlashLoader owner , uint index , uint address ) { m_owner = owner; m_state = BlockState.Uninitialized; m_index = index; m_physicalAddress = address; m_local_logicalAddress = address; } // // Helper Methods // internal void MoveToState( BlockState targetState ) { while(m_state < targetState) { m_state++; switch(m_state) { case BlockState.DataLoaded: m_data = new uint[m_owner.m_flashBlockSizeInWords]; for(int i = 0; i < m_owner.m_flashBlockSizeInWords; i++) { m_data[i] = erasedMemoryPattern; } break; case BlockState.DataLoadedAndChecked: uint localChecksum = 0; uint localMemoryAND = erasedMemoryPattern; for(int pos = 0; pos < m_data.Length; pos++) { uint val = m_data[pos]; localChecksum = ((localChecksum & 1) << 31) | (localChecksum >> 1); localChecksum += val; localMemoryAND &= val; } m_local_checksum = localChecksum; m_local_fErased = (localMemoryAND == erasedMemoryPattern); SetState(); break; } } } internal bool CanBePreparedForProgramming() { if(this.IsInitialized) { if(m_state == BlockState.BadBlock) { return false; } this.MoveToState( BlockState.DataLoadedAndChecked ); if(m_device_fBadBlock || (m_device_fErased == false && this.ChecksumMatch == false)) { //// Console.WriteLine( "Erasing block {0:X8}", m_physicalAddress ); m_owner.Execute_EraseBlock( m_physicalAddress ); SetState(); if(m_device_fBadBlock) { m_state = BlockState.BadBlock; return false; } } return true; } return false; } internal bool ShouldBeProgrammed() { if(this.IsInitialized) { if(m_state == BlockState.BadBlock) { return false; } this.MoveToState( BlockState.DataLoadedAndChecked ); return this.ChecksumMatch == false; } return false; } internal bool Program() { if(this.ShouldBeProgrammed()) { for(int retry = 1; retry < 5; retry++) { if(this.CanBePreparedForProgramming() == false) { return false; } //// Console.WriteLine( "Programming block {0:X8}, logical {1:X8}", physicalAddress, logicalAddress ); uint pages = m_owner.m_flashBlockSizeInWords / m_owner.m_flashPageSizeInWords; //// System.Diagnostics.Stopwatch st = new System.Diagnostics.Stopwatch(); //// Console.WriteLine( "Programming {0} pages", pages ); //// st.Start(); m_owner.Execute_ProgramMemory_Header( m_physicalAddress, pages ); uint logicalAddress = m_local_logicalAddress; for(uint offset = 0; offset < m_owner.m_flashBlockSizeInWords; offset += m_owner.m_flashPageSizeInWords) { m_owner.Execute_ProgramMemory_Data( m_data, m_owner.m_flashPageSizeInWords, offset, new uint[] { logicalAddress } ); logicalAddress += m_owner.m_flashPageSize; } bool fSuccess = m_owner.Execute_ProgramMemory_Feedback(); //// st.Stop(); //// Console.WriteLine( "Done in {0} msec", st.ElapsedMilliseconds ); //// uint[] page = m_owner.Execute_ReadPage( m_physicalAddress + 1 * m_owner.m_flashPageSize, out fSuccess) ; SetState(); if(this.ChecksumMatch) { break; } else { Thread.Sleep( 200 * retry ); } } if(m_device_fBadBlock || this.ChecksumMatch == false) { m_state = BlockState.BadBlock; return false; } } return true; } internal void MoveLocalState( BlockEntry other ) { m_data = other.m_data; m_local_logicalAddress = other.m_local_logicalAddress; m_local_checksum = other.m_local_checksum; m_local_fErased = other.m_local_fErased; } //--// private void SetState() { uint memoryAND; m_device_logicalAddress = 0xFFFFFFFF; m_device_fErased = false; m_device_fBadBlock = false; if(m_owner.Execute_ChecksumMemory( m_physicalAddress, m_data.Length, out m_device_checksum, out memoryAND ) || m_owner.Execute_ChecksumMemory( m_physicalAddress, m_data.Length, out m_device_checksum, out memoryAND ) ) { m_device_fErased = (memoryAND == erasedMemoryPattern); if(m_device_fErased == false) { bool fSuccess; uint[] spare = m_owner.Execute_ReadSpare( m_physicalAddress, out fSuccess ); if(fSuccess) { m_device_logicalAddress = spare[0]; } else { m_device_fBadBlock = true; } } } else { m_device_fBadBlock = true; } } // // Access Methods // internal bool IsInitialized { get { return m_state != BlockState.Uninitialized; } } internal bool HasData { get { switch(m_state) { case BlockState.DataLoaded : case BlockState.DataLoadedAndChecked: return true; } return false; } } internal uint Size { get { if(this.HasData) { return (uint)m_data.Length * sizeof(uint); } return 0; } } private bool ChecksumMatch { get { if(m_local_checksum == m_device_checksum && m_local_logicalAddress == m_device_logicalAddress ) { return true; } return false; } } } const uint cmd_Signature = 0xDEADC000; const uint cmd_Mask = 0xFFFFFF00; const byte cmd_Hello = 0x01; const byte cmd_GetConfig = 0x02; // => const byte cmd_ReadPage = 0x03; // Arg: Address => const byte cmd_ReadSpare = 0x04; // Arg: Address => const byte cmd_ChecksumMemory = 0x05; // Arg: Address => , const byte cmd_EraseBlock = 0x06; // Arg: Address => const byte cmd_ProgramPage = 0x07; // Arg: Address, # pages [bytes] => .... const uint erasedMemoryPattern = 0xFFFFFFFFu; //--// // // State // ProductCategory m_product; Emulation.Hosting.AbstractHost m_owner; Emulation.Hosting.DebugCommunicationChannel m_dcc; Emulation.Hosting.JTagConnector m_jtag; uint m_flashPageCount; uint m_flashPageSize; uint m_flashSpareSize; uint m_flashUsableSpareSize; uint m_flashBlockSize; Thread m_workerThread; uint m_flashPageSizeInWords; uint m_flashSpareSizeInWords; uint m_flashBlockSizeInWords; BlockEntry[] m_blocks; // // Constructor Methods // public NandFlashLoader() { } // // Helper Methods // public override void Deploy( Emulation.Hosting.AbstractHost owner , Cfg.ProductCategory product , List< Configuration.Environment.ImageSection > image , Emulation.Hosting.ProcessorControl.ProgressCallback callback ) { m_owner = owner; m_product = product; owner.GetHostingService( out m_dcc ); owner.GetHostingService( out m_jtag ); //--// try { Start(); ////////////////////////////////////////////////////////////// // // DEBUG!! DEBUG!! DEBUG!! DEBUG!! DEBUG!! // //// uint[] page1 = Execute_ReadPage( 0xA0000000u ); //// uint[] page2 = Execute_ReadPage( 0xA0000200u ); //// uint[] page3 = Execute_ReadPage( 0xA0010000u ); //// //// uint[] page1 = Execute_ReadPage( m_flashPageSize * 0 ); //// uint[] page2 = Execute_ReadPage( m_flashPageSize * 1 ); //// uint[] page3 = Execute_ReadPage( m_flashPageSize * 128 ); //// //// uint checksum; //// uint memoryAND; //// //// Execute_ChecksumMemory( m_flashPageSize * 0, (int)m_flashPageSize / sizeof(uint), out checksum, out memoryAND ); //// Execute_ChecksumMemory( m_flashPageSize * 128, (int)m_flashPageSize / sizeof(uint), out checksum, out memoryAND ); //// //// Execute_ProgramMemory( m_flashPageSize * 128, page2, (int)m_flashPageSize / sizeof(uint), 0 ); //// //// uint[] page4 = Execute_ReadPage( m_flashPageSize * 128 ); // // DEBUG!! DEBUG!! DEBUG!! DEBUG!! DEBUG!! // ////////////////////////////////////////////////////////////// //--// float position = 0; float total = 0; // // Split the image into the blocks. // foreach(var section in image) { if(section.NeedsRelocation == false) { uint address = section.Address; byte[] data = section.Payload; SplitIntoBlocks( address, data ); } } foreach(var bs in m_blocks) { total += bs.Size; } callback( "Checking {1}", 0.0f, total ); foreach(var bs in m_blocks) { if(bs.HasData) { bs.MoveToState( BlockState.DataLoadedAndChecked ); } } callback( "Programming {0}/{1}", 0.0f, total ); foreach(var bs in m_blocks) { if(bs.Program() == false) { if(Redistribute( bs ) == false) { throw Emulation.Hosting.AbstractEngineException.Create( Emulation.Hosting.AbstractEngineException.Kind.Deployment, "Hardware problem: failed to find good block for {0:X8}", bs.m_local_logicalAddress ); } } position += bs.Size; callback( "Programming {0}/{1}", position, total ); } } finally { Stop(); } //--// callback( "Preparing for execution..." ); Emulation.Hosting.ProcessorControl svcPC; owner.GetHostingService( out svcPC ); svcPC.ResetState( product ); } //--// private void WorkerThread() { try { m_dcc.Start(); m_jtag.RunDevice(); } finally { m_dcc.Stop(); } } private void SendData( uint data ) { if(m_dcc.WriteFromDebugger( data, 10 * 1000 ) == false) { throw TypeConsistencyErrorException.Create( "Timeout while sending data to device" ); } } private uint ReceiveData() { uint data; if(m_dcc.ReadFromDebugger( out data, 10 * 1000 ) == false) { throw TypeConsistencyErrorException.Create( "Timeout while receiving data from device" ); } return data; } private void VerifyData( uint expected ) { uint data = ReceiveData(); if(data != expected) { throw TypeConsistencyErrorException.Create( "Failed to synchronize with device, expecting {0:X8}, got {1:X8}", expected, data ); } } //--// private void LoadLoaderImage() { JtagLoaderCategory jtagLoader = m_product.SearchValue< Cfg.JtagLoaderCategory >(); if(jtagLoader == null) { throw TypeConsistencyErrorException.Create( "Product {0} does not have a JTAG loader", m_product.GetType() ); } //// using(var file = new System.IO.FileStream( @"s:\imagedump.bin", System.IO.FileMode.Create )) //// { //// foreach(uint address in jtagLoader.LoaderData.Keys) //// { //// var section = jtagLoader.LoaderData[address]; //// //// file.Seek( address - 0x08000000, System.IO.SeekOrigin.Begin ); //// file.Write( section, 0, section.Length ); //// } //// } foreach(uint address in jtagLoader.LoaderData.Keys) { m_jtag.WriteMemoryBlock( address, ToUint( jtagLoader.LoaderData[address] ) ); } m_jtag.ProgramCounter = jtagLoader.EntryPoint; // // Start execution on worker thread // m_workerThread = new Thread( WorkerThread ); m_workerThread.Start(); Execute_Hello(); } private void ParseFlashSectors() { Execute_GetConfig(); } //--// private void Execute_Hello() { SendData( cmd_Signature | cmd_Hello ); VerifyData( cmd_Signature | cmd_Hello ); } private void Execute_GetConfig() { SendData( cmd_Signature | cmd_GetConfig ); VerifyData( cmd_Signature | cmd_GetConfig ); m_flashPageCount = ReceiveData(); m_flashPageSize = ReceiveData(); m_flashSpareSize = ReceiveData(); m_flashUsableSpareSize = ReceiveData(); m_flashBlockSize = ReceiveData(); m_flashPageSizeInWords = m_flashPageSize / sizeof(uint); m_flashSpareSizeInWords = m_flashSpareSize / sizeof(uint); m_flashBlockSizeInWords = m_flashBlockSize / sizeof(uint); m_blocks = new BlockEntry[(m_flashPageCount * m_flashPageSize) / m_flashBlockSize]; for(uint i = 0; i < m_blocks.Length; i++) { m_blocks[i] = new BlockEntry( this, i, i * m_flashBlockSize ); } } private uint[] Execute_ReadPage( uint address , out bool fSuccess ) { SendData( cmd_Signature | cmd_ReadPage ); SendData( address ); VerifyData( cmd_Signature | cmd_ReadPage ); fSuccess = ReceiveData() != 0; uint[] res = new uint[m_flashPageSizeInWords + m_flashSpareSizeInWords]; for(int i = 0; i < res.Length; i++) { res[i] = ReceiveData(); } return res; } private uint[] Execute_ReadSpare( uint address , out bool fSuccess ) { SendData( cmd_Signature | cmd_ReadSpare ); SendData( address ); VerifyData( cmd_Signature | cmd_ReadSpare ); fSuccess = ReceiveData() != 0; uint[] res = new uint[(m_flashSpareSize) / sizeof(uint)]; for(int i = 0; i < res.Length; i++) { res[i] = ReceiveData(); } return res; } private bool Execute_ChecksumMemory( uint address , int size , out uint checksum , out uint memoryAND ) { SendData( cmd_Signature | cmd_ChecksumMemory ); SendData( address ); SendData( (uint)size ); VerifyData( cmd_Signature | cmd_ChecksumMemory ); bool status = ReceiveData() != 0; if(status) { checksum = ReceiveData(); memoryAND = ReceiveData(); } else { checksum = 0; memoryAND = 0; } return status; } private bool Execute_EraseBlock( uint address ) { SendData( cmd_Signature | cmd_EraseBlock ); SendData( address ); VerifyData( cmd_Signature | cmd_EraseBlock ); return ReceiveData() != 0; } private bool Execute_ProgramMemory( uint address , uint[] data , uint size , uint offset , uint[] spare ) { Execute_ProgramMemory_Header( address, 1 ); Execute_ProgramMemory_Data( data, size, offset, spare ); return Execute_ProgramMemory_Feedback(); } private void Execute_ProgramMemory_Header( uint address , uint pages ) { SendData( cmd_Signature | cmd_ProgramPage ); SendData( address ); SendData( pages ); VerifyData( cmd_Signature | cmd_ProgramPage ); } private void Execute_ProgramMemory_Data( uint[] data , uint size , uint offset , uint[] spare ) { Execute_ProgramMemory_Data( data , offset, size , m_flashPageSizeInWords ); Execute_ProgramMemory_Data( spare, 0, spare != null ? (uint)spare.Length : 0, m_flashSpareSizeInWords ); } private void Execute_ProgramMemory_Data( uint[] data , uint offset , uint count , uint required ) { for(uint i = 0; i < required; i++) { SendData( i < count ? data[offset++] : 0xFFFFFFFF ); } } private bool Execute_ProgramMemory_Feedback() { return ReceiveData() != 0; } //--// private void Start() { if(m_jtag.IsTargetStopped() == false) { m_jtag.StopTarget(); } LoadLoaderImage(); ParseFlashSectors(); } private void Stop() { m_jtag.AbortRunDevice(); m_workerThread.Join(); m_jtag.Cleanup(); } //--// private void SplitIntoBlocks( uint address , byte[] data ) { uint start = address; uint end = address + (uint)data.Length; uint[] buf = ToUint( data ); int bufLengthInWords = buf.Length; int posInWords = 0; while(posInWords < bufLengthInWords) { uint offsetInBytes = address & (m_flashBlockSize - 1); int lenInBytes = Math.Min( (int)(m_flashBlockSize - offsetInBytes), (bufLengthInWords - posInWords) * sizeof(uint) ); BlockEntry bs = GetBlock( address ); bs.MoveToState( BlockState.DataLoaded ); if(lenInBytes > 0) { Buffer.BlockCopy( buf, posInWords * sizeof(uint), bs.m_data, (int)offsetInBytes, lenInBytes ); } address += (uint)lenInBytes; posInWords += lenInBytes / sizeof(uint); } } private BlockEntry GetBlock( uint address ) { return m_blocks[(address / m_flashBlockSize) % m_blocks.Length]; } private bool Redistribute( BlockEntry bs ) { BlockEntry bsDst = FindFirstUntouchedBlock( bs ); if(bsDst == null) { return false; } //--// uint index = bsDst.m_index; while(true) { BlockEntry bsSrc = m_blocks[--index]; bsDst.MoveLocalState( bsSrc ); if(bsSrc == bs) { break; } bsDst = bsSrc; } return true; } private BlockEntry FindFirstUntouchedBlock( BlockEntry bs ) { for(uint i = bs.m_index + 1; i < m_blocks.Length; i++) { BlockEntry bsNext = m_blocks[i]; if(bsNext.IsInitialized == false) { bsNext.MoveToState( BlockState.DataLoadedAndChecked ); return bsNext; } } return null; } } //--// protected NandFlashJtagLoaderCategory( string name , byte[] file ) { using(System.IO.StreamReader reader = new System.IO.StreamReader( new System.IO.MemoryStream( file ) )) { List< Emulation.ArmProcessor.SRecordParser.Block > blocks = new List< Emulation.ArmProcessor.SRecordParser.Block >(); m_entryPoint = Emulation.ArmProcessor.SRecordParser.Parse( reader, name, blocks ); foreach(Emulation.ArmProcessor.SRecordParser.Block block in blocks) { m_loaderData[block.address] = block.data.ToArray(); } } } protected override object GetServiceInner( Type t ) { if(t == typeof(Emulation.Hosting.JTagCustomer)) { return new NandFlashLoader(); } return base.GetServiceInner( t ); } } } ================================================ FILE: Zelig/Zelig/CompileTime/TargetModels/ProductConfiguration/NorFlashJTagLoaderCategory.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // namespace Microsoft.Zelig.Configuration.Environment { using System; using System.Threading; using System.Collections.Generic; using Cfg = Microsoft.Zelig.Configuration.Environment; public abstract class NorFlashJtagLoaderCategory : JtagLoaderCategory { class NorFlashLoader : Emulation.Hosting.JTagCustomer { const uint cmd_Signature = 0xDEADC000; const uint cmd_Mask = 0xFFFFFF00; const byte cmd_Hello = 0x01; const byte cmd_EnterCFI = 0x02; // Arg: Address const byte cmd_ExitCFI = 0x03; // Arg: Address const byte cmd_ReadMemory8 = 0x04; // Arg: Address, Size => values const byte cmd_ReadMemory16 = 0x05; // Arg: Address, Size => values const byte cmd_ReadMemory32 = 0x06; // Arg: Address, Size => values const byte cmd_ChecksumMemory = 0x07; // Arg: Address, Size => CRC value, AND of all memory const byte cmd_EraseSector = 0x08; // Arg: Address => Status value const byte cmd_ProgramMemory = 0x09; // Arg: Address, Size, [32bits words] => Status value const uint erasedMemoryPattern = 0xFFFFFFFFu; delegate void ProgressCallback( uint pos, uint total ); //--// class EraseSection { internal uint m_baseAddress; internal uint m_endAddress; internal uint m_numEraseBlocks; internal uint m_sizeEraseBlocks; } // // State // ProductCategory m_product; Emulation.Hosting.AbstractHost m_owner; Emulation.Hosting.DebugCommunicationChannel m_dcc; Emulation.Hosting.JTagConnector m_jtag; uint m_flashBaseAddress; ulong m_flashSize; EraseSection[] m_eraseSections; Thread m_workerThread; // // Constructor Methods // public NorFlashLoader() { } // // Helper Methods // public override void Deploy( Emulation.Hosting.AbstractHost owner , Cfg.ProductCategory product , List< Configuration.Environment.ImageSection > image , Emulation.Hosting.ProcessorControl.ProgressCallback callback ) { m_owner = owner; m_product = product; owner.GetHostingService( out m_dcc ); owner.GetHostingService( out m_jtag ); bool fGot = false; foreach(MemoryCategory mem in product.SearchValues< MemoryCategory >()) { if((mem.Characteristics & Runtime.MemoryAttributes.FLASH) != 0) { m_flashBaseAddress = mem.BaseAddress; m_flashSize = mem.SizeInBytes; fGot = true; break; } } if(fGot == false) { throw TypeConsistencyErrorException.Create( "Product {0} does not have a valid FLASH memory", product.GetType() ); } //--// try { Start(); float position = 0; float total = 0; foreach(var section in image) { if(section.NeedsRelocation == false) { total += section.Payload.Length; } } callback( "Erasing {1}", 0.0f, (float)total ); //// EraseMemory( m_flashBaseAddress, m_flashBaseAddress + 384 * 1024 ); while(true) { bool fModified = false; foreach(var section in image) { if(section.NeedsRelocation == false) { bool fMemoryErased; uint address = section.Address; byte[] data = section.Payload; if(VerifyChecksum( address, data, out fMemoryErased ) == false) { if(!fMemoryErased) { EraseMemory( address, address + (uint)data.Length ); fModified = true; } } } } if(!fModified) break; } callback( "Programming {0}/{1}", 0, total ); foreach(var section in image) { if(section.NeedsRelocation == false) { bool fMemoryErased; uint address = section.Address; byte[] data = section.Payload; if(VerifyChecksum( address, data, out fMemoryErased ) == false) { ProgramMemory( address, data, delegate( uint positionSub, uint totalSub ) { callback( "Programming {0}/{1}", position + positionSub, total ); } ); } position += data.Length; callback( "Programming {0}/{1}", position, total ); } } } finally { Stop(); } //--// callback( "Preparing for execution..." ); Emulation.Hosting.ProcessorControl svcPC; owner.GetHostingService( out svcPC ); svcPC.ResetState( product ); } //--// private void WorkerThread() { try { m_dcc.Start(); if(m_jtag.RunDevice( Timeout.Infinite ) == true) { throw TypeConsistencyErrorException.Create( "Device stopped unexpectedly during deployment!" ); } } finally { m_dcc.Stop(); } } private void SendData( uint data ) { if(m_dcc.WriteFromDebugger( data, 10 * 1000 ) == false) { throw TypeConsistencyErrorException.Create( "Timeout while sending data to device" ); } } private uint ReceiveData() { uint data; if(m_dcc.ReadFromDebugger( out data, 10 * 1000 ) == false) { throw TypeConsistencyErrorException.Create( "Timeout while receiving data from device" ); } return data; } private void VerifyData( uint expected ) { uint data = ReceiveData(); if(data != expected) { throw TypeConsistencyErrorException.Create( "Failed to synchronize with device, expecting {0:X8}, got {1:X8}", expected, data ); } } //--// private void LoadLoaderImage() { JtagLoaderCategory jtagLoader = m_product.SearchValue< Cfg.JtagLoaderCategory >(); if(jtagLoader == null) { throw TypeConsistencyErrorException.Create( "Product {0} does not have a JTAG loader", m_product.GetType() ); } foreach(uint address in jtagLoader.LoaderData.Keys) { m_jtag.WriteMemoryBlock( address, ToUint( jtagLoader.LoaderData[address] ) ); } m_jtag.ProgramCounter = jtagLoader.EntryPoint; // // Start execution on worker thread // m_workerThread = new Thread( WorkerThread ); m_workerThread.Start(); Execute_Hello(); } private void ParseFlashSectors() { for(int tries = 0; tries < 3; tries++) { Execute_EnterCFI(); ushort[] cfg = Execute_ReadMemory16( m_flashBaseAddress, 128 ); if(cfg[0x10] == 'Q' && cfg[0x11] == 'R' && cfg[0x12] == 'Y' ) { uint numEraseBlockRegions = cfg[0x2C]; uint baseAddress = m_flashBaseAddress; m_eraseSections = new EraseSection[numEraseBlockRegions]; for(uint pos = 0; pos < numEraseBlockRegions; pos++) { EraseSection section = new EraseSection(); section.m_baseAddress = baseAddress; section.m_numEraseBlocks = ((uint)cfg[0x2D + pos * 4] + ((uint)cfg[0x2E + pos * 4] << 8)) + 1u; section.m_sizeEraseBlocks = ((uint)cfg[0x2F + pos * 4] + ((uint)cfg[0x30 + pos * 4] << 8)) * 256; baseAddress += section.m_numEraseBlocks * section.m_sizeEraseBlocks; section.m_endAddress = baseAddress; m_eraseSections[pos] = section; } Execute_ExitCFI(); return; } Execute_ExitCFI(); } throw TypeConsistencyErrorException.Create( "Cannot enter CFI mode" ); } //--// private void Execute_Hello() { SendData( cmd_Signature | cmd_Hello ); VerifyData( cmd_Signature | cmd_Hello ); } private void Execute_EnterCFI() { SendData( cmd_Signature | cmd_EnterCFI ); SendData( m_flashBaseAddress ); VerifyData( cmd_Signature | cmd_EnterCFI ); } private void Execute_ExitCFI() { SendData( cmd_Signature | cmd_ExitCFI ); SendData( m_flashBaseAddress ); VerifyData( cmd_Signature | cmd_ExitCFI ); } private byte[] Execute_ReadMemory8( uint address , int size ) { SendData( cmd_Signature | cmd_ReadMemory8 ); SendData( address ); SendData( (uint)size ); VerifyData( cmd_Signature | cmd_ReadMemory8 ); byte[] res = new byte[size]; for(int i = 0; i < size; i++) { res[i] = (byte)ReceiveData(); } return res; } private ushort[] Execute_ReadMemory16( uint address , int size ) { SendData( cmd_Signature | cmd_ReadMemory16 ); SendData( address ); SendData( (uint)size ); VerifyData( cmd_Signature | cmd_ReadMemory16 ); ushort[] res = new ushort[size]; for(int i = 0; i < size; i++) { res[i] = (ushort)ReceiveData(); } return res; } private uint[] Execute_ReadMemory32( uint address , int size ) { SendData( cmd_Signature | cmd_ReadMemory32 ); SendData( address ); SendData( (uint)size ); VerifyData( cmd_Signature | cmd_ReadMemory32 ); uint[] res = new uint[size]; for(int i = 0; i < size; i++) { res[i] = ReceiveData(); } return res; } private void Execute_ChecksumMemory( uint address , int size , out uint checksum , out uint memoryAND ) { SendData( cmd_Signature | cmd_ChecksumMemory ); SendData( address ); SendData( (uint)size ); VerifyData( cmd_Signature | cmd_ChecksumMemory ); checksum = ReceiveData(); memoryAND = ReceiveData(); } private uint Execute_EraseSector( uint address ) { SendData( cmd_Signature | cmd_EraseSector ); SendData( address ); VerifyData( cmd_Signature | cmd_EraseSector ); return ReceiveData(); } private uint Execute_ProgramMemory( uint address , uint[] data , int size , int offset ) { SendData( cmd_Signature | cmd_ProgramMemory ); SendData( address ); SendData( (uint)size ); VerifyData( cmd_Signature | cmd_ProgramMemory ); while(size-- > 0) { SendData( data[offset++] ); } return ReceiveData(); } //--// private void Start() { if(m_jtag.IsTargetStopped() == false) { m_jtag.StopTarget(); } LoadLoaderImage(); ParseFlashSectors(); } private void Stop() { m_jtag.AbortRunDevice(); m_workerThread.Join(); m_jtag.Cleanup(); } private bool VerifyChecksum( uint address , byte[] data , out bool fMemoryErased ) { uint[] buf = ToUint( data ); int len = buf.Length; uint checksum; uint memoryAND; Execute_ChecksumMemory( address, len, out checksum, out memoryAND ); uint localChecksum = 0; uint localMemoryAND = erasedMemoryPattern; for(int pos = 0; pos < len; pos++) { uint val = buf[pos]; localChecksum = ((localChecksum & 1) << 31) | (localChecksum >> 1); localChecksum += val; localMemoryAND &= val; } fMemoryErased = (memoryAND == erasedMemoryPattern); if(localChecksum == checksum) { return true; } if(fMemoryErased && localMemoryAND == erasedMemoryPattern) { return true; } return false; } private void EraseMemory( uint start , uint end ) { while(true) { EraseSection section = FindSector( start ); if(section == null) { break; } uint address = section.m_baseAddress; for(int j = 0; j < section.m_numEraseBlocks; j++) { uint endAddress = address + section.m_sizeEraseBlocks; if(address <= start && start < endAddress) { Execute_EraseSector( address ); uint checksum; uint memoryAND; Execute_ChecksumMemory( address, (int)section.m_sizeEraseBlocks / sizeof(uint), out checksum, out memoryAND ); if(memoryAND != erasedMemoryPattern) { throw Emulation.Hosting.AbstractEngineException.Create( Emulation.Hosting.AbstractEngineException.Kind.Deployment, "Hardware problem: failed to erase sector at {0:X8}, size={1}", address, section.m_sizeEraseBlocks ); } start = endAddress; if(start >= end) { return; } } address = endAddress; } } } private uint ProgramMemory( uint address , byte[] data , ProgressCallback callback ) { uint[] buf = ToUint( data ); int pos = 0; int lenBuf = buf.Length; while(pos < lenBuf) { EraseSection section = FindSector( address ); if(section == null) { break; } int len = Math.Min( 128, lenBuf - pos ); uint res = Execute_ProgramMemory( address, buf, len, pos ); if(res != 0) { return res; } address += (uint)(len * sizeof(uint)); pos += len; callback( (uint)(pos * sizeof(uint)), (uint)lenBuf ); } return 0; } //--// private EraseSection FindSector( uint address ) { for(int i = 0; i < m_eraseSections.Length; i++) { EraseSection section = m_eraseSections[i]; if(section.m_baseAddress <= address && address < section.m_endAddress) { return section; } } return null; } } //--// protected NorFlashJtagLoaderCategory( string name , byte[] file ) { using(System.IO.StreamReader reader = new System.IO.StreamReader( new System.IO.MemoryStream( file ) )) { List< Emulation.ArmProcessor.SRecordParser.Block > blocks = new List< Emulation.ArmProcessor.SRecordParser.Block >(); m_entryPoint = Emulation.ArmProcessor.SRecordParser.Parse( reader, name, blocks ); foreach(Emulation.ArmProcessor.SRecordParser.Block block in blocks) { m_loaderData[block.address] = block.data.ToArray(); } } } protected override object GetServiceInner( Type t ) { if(t == typeof(Emulation.Hosting.JTagCustomer)) { return new NorFlashLoader(); } return base.GetServiceInner( t ); } } } ================================================ FILE: Zelig/Zelig/CompileTime/TargetModels/ProductConfiguration/ProductConfiguration.csproj ================================================  Debug AnyCPU 9.0.21022 2.0 {186F31A3-EF89-4A25-B2D5-20070606AA01} Library Properties Microsoft.Zelig.ProductConfiguration Microsoft.Zelig.ProductConfiguration $(LlilumBuildRoot)\Host\obj\$(MSBuildProjectName)\ v4.5 true full false $(LlilumBuildRoot)\Host\bin\$(Configuration)\ DEBUG;TRACE prompt 4 true AllRules.ruleset AnyCPU false pdbonly true $(LlilumBuildRoot)\Host\bin\$(Configuration)\ TRACE prompt 4 true AllRules.ruleset AnyCPU false $(LlilumBuildRoot)\Host\bin\$(Configuration)\ TRACE;DEBUG AnyCPU true false True True Loaders.resx Code 3.5 {186F31A3-EF89-4A25-B2D5-20060704AA01} ArmProcessorEmulation False {186F31A3-EF89-4A25-B2D5-20070601AA01} CommonPC False {186F31A3-EF89-4A25-B2D5-20060509AA01} Kernel False {186F31A3-EF89-4A25-B2D5-20060720AA01} TypeSystem False {186F31A3-EF89-4A25-B2D5-20070222AA01} CodeTransformation False {186F31A3-EF89-4A25-B2D5-20060603AA01} IntermediateRepresentation False {186F31A3-EF89-4A25-B2D5-20060510AA01} Normalized False {186F31A3-EF89-4A25-B2D5-20061218AA01} Common False {186F31A3-EF89-4A25-B2D5-20070519AA01} ArmProcessor False {46478CA2-8163-47A0-8C65-3ACFC21CE57F} Win32Processor False {0162c8ce-6641-4922-8664-f8a44356fbf7} Llvm.NET {186f31a3-ef89-4a25-b2d5-20060404aa01} Importer Designer ResXFileCodeGenerator Loaders.Designer.cs ================================================ FILE: Zelig/Zelig/CompileTime/TargetModels/ProductConfiguration/Properties/AssemblyInfo.cs ================================================ using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; // General Information about an assembly is controlled through the following // set of attributes. Change these attribute values to modify the information // associated with an assembly. [assembly: AssemblyTitle( "Microsoft.Zelig.ProductConfiguration" )] [assembly: AssemblyDescription( "" )] [assembly: AssemblyConfiguration( "" )] [assembly: AssemblyCompany( "Microsoft" )] [assembly: AssemblyProduct( "Microsoft.Zelig.ProductConfiguration" )] [assembly: AssemblyCopyright( "Copyright © Microsoft 2007" )] [assembly: AssemblyTrademark( "" )] [assembly: AssemblyCulture( "" )] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible( false )] //// The following GUID is for the ID of the typelib if this project is exposed to COM //[assembly: Guid( "57de0ebe-e971-4cb9-8985-5f6b66934a91" )] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Revision and Build Numbers // by using the '*' as shown below: [assembly: AssemblyVersion( "1.0.0.0" )] [assembly: AssemblyFileVersion( "1.0.0.0" )] ================================================ FILE: Zelig/Zelig/CompileTime/TargetModels/ProductConfiguration/RamJTagLoaderCategory.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // namespace Microsoft.Zelig.Configuration.Environment { using System; using System.Threading; using System.Collections.Generic; using Cfg = Microsoft.Zelig.Configuration.Environment; public abstract class RamJtagLoaderCategory : JtagLoaderCategory { class RamLoader : Emulation.Hosting.JTagCustomer { // // State // ProductCategory m_product; Emulation.Hosting.AbstractHost m_owner; Emulation.Hosting.JTagConnector m_jtag; // // Constructor Methods // public RamLoader() { } // // Helper Methods // public override void Deploy( Emulation.Hosting.AbstractHost owner , Cfg.ProductCategory product , List< Configuration.Environment.ImageSection > image , Emulation.Hosting.ProcessorControl.ProgressCallback callback ) { m_owner = owner; m_product = product; owner.GetHostingService( out m_jtag ); //--// //// using(var file = new System.IO.FileStream( @"s:\imagedump.bin", System.IO.FileMode.Create )) //// { //// foreach(var section in image) //// { //// file.Seek( section.Address - 0x08000000, System.IO.SeekOrigin.Begin ); //// file.Write( section.Payload, 0, section.Payload.Length ); //// } //// } float position = 0; float total = 0; foreach(var section in image) { total += section.Payload.Length; } callback( "Downloading {0}/{1}", 0.0f, (float)total ); m_jtag.StopTarget(); foreach(var section in image) { const int chunkSize = 4096; uint address = section.Address; byte[] data = section.Payload; uint[] data32 = ToUint( data ); for(int chunk = 0; chunk < data32.Length; chunk += chunkSize) { int count = Math.Min( data32.Length - chunk, chunkSize ); m_jtag.WriteMemoryBlock( address, data32, chunk, count ); address += (uint)(count * sizeof(uint)); position += count * sizeof(uint); callback( "Downloading {0}/{1}", position, total ); } } } } //--// protected RamJtagLoaderCategory() { } protected override object GetServiceInner( Type t ) { if(t == typeof(Emulation.Hosting.JTagCustomer)) { return new RamLoader(); } return base.GetServiceInner( t ); } } } ================================================ FILE: Zelig/Zelig/CompileTime/TargetModels/ProductConfiguration/Resources/Microsoft.NohauLPC3180Loader.hex ================================================ S3150800000018F09FE518F09FE50A0000EF14F09FE549 S3150800001014F09FE5000000EF080000EF090000EF6C S315080000203000000864000008A8000008E80000087E S3150800003004F01FE528010008000091E5100AE1EE2A S315080000400C0091E500D0A0E1100091E500E0A0E1E8 S31508000050140081E20010A0E1200BB1ECFF9F91E8AB S315080000607FFF2FE104E04EE20F502DE9040B2DED42 S31508000070101F15EE28009FE5201080E5301F15EEAD S315080000801C009FE5281080E5101F16EE10009FE55E S31508000090241080E5700020E1040BBDEC0F90FDE80C S315080000A07FFF2FE15413000804E04EE20F502DE9BC S315080000B0040B2DED101F15EE1C001FE5201080E522 S315080000C0301F15EE28001FE5281080E5101F16EED4 S315080000D034001FE5241080E5700020E1040BBDEC18 S315080000E00F90FDE87FFF2FE108E04EE20F502DE963 S315080000F0040B2DED101F15EE5C001FE5201080E5A2 S31508000100301F15EE68001FE5281080E5101F16EE53 S3150800011074001FE5241080E5700020E1040BBDEC97 S315080001200F90FDE87FFF2FE1DFF021E32C019FE52B S31508000130041080E2020CA0E3000181E000D0A0E1F7 S315080001401C119FE51C219FE5000092E50200C0E313 S31508000150000082E5480091E5010010E3FCFFFF0A74 S31508000160500091E5020080E3500081E5500091E5DA S31508000170010010E3FCFFFF0A4C0091E5010080E353 S315080001804C0081E5440091E50200C0E3440081E5A6 S31508000190D4009FE5580081E5580091E5010010E379 S315080001A0FCFFFF0A3D00A0E3400081E5440091E51D S315080001B0040080E3440081E500C0A0E315CF07EE04 S315080001C000C0A0E316CF07EE100F11EE010A80E378 S315080001D0100F01EE94009FE5002090E50010A0E3C3 S315080001E0080000EA003090E5044090E5020000EAC5 S315080001F00000A0E3040083E4014044E2000054E365 S31508000200FAFFFF1A011081E2000092E5000051E1B1 S31508000210250400AA040082E2010180E0000090E5BE S31508000220083090E5000053E3EDFFFF0A083090E53B S31508000230043083E2084090E5045084E2044090E5E7 S31508000240045185E0000090E5010000EA044093E4CB S31508000250044080E4050053E1FBFFFF3AE8FFFFEAAC S31508000260FCF7000800400040484000401E400100DE S315080002708013000800402DE9010000EB710020E121 S315080002807FFF2FE1F0432DE9160100EB28149FE5C7 S31508000290360100EBF10000EA0610A0E1510100EB7F S315080002A0EE0000EA0610A0E14E0100EB0118A0E3FB S315080002B04C0100EB021CA0E34A0100EB1010A0E37E S315080002C0480100EB0610A0E3460100EB0119A0E384 S315080002D0440100EBE10000EA0040A0E3060000EA62 S315080002E0D8039FE5040080E2040180E0000090E561 S315080002F00010A0E13B0100EB014084E28000A0E38E S31508000300000054E1F5FFFFBA0F0000EA0100A0E380 S31508000310080000EA200100EB0040A0E10610A0E179 S31508000320300100EB0410A0E1340100EB000050E3BB S31508000330F5FFFF1A0000A0E30010A0E1290100EB79 S31508000340FF0006E2030050E3E2FFFF0A0040A0E3D5 S315080003500F0000EA68039FE5040080E2840080E05D S31508000360B030D0E158239FE5011084E20800A0E3ED S31508000370000051E1CE03002A040082E2810080E0F9 S31508000380B000D0E1000883E10010A0E1150100EB00 S31508000390024084E20800A0E3000054E1ECFFFFBA43 S315080003A0AE0000EAFC0000EB0040A0E1FA0000EB1A S315080003B00050A0E10070A0E30090E0E30180A0E314 S315080003C00610A0E1070100EBF8129FE50420A0E162 S315080003D0F70000EBF0129FE50520A0E1F40000EB22 S315080003E00760A0E10970A0E1310000EADC129FE590 S315080003F0011004E00E0000EAC0829FE52131A0E169 S315080004008020A0E3020053E1AB03002A042088E21F S31508000410032182E0008092E5013006E2A620A0E1F1 S31508000420832F82E1086082E0044084E2041081E2BE S31508000430015045E2000055E30100009A020C51E321 S31508000440ECFFFF3A0010A0E3050000EA6C229FE5E6 S31508000450042082E2012182E0002092E5027007E092 S31508000460011081E28020A0E3020051E1F6FFFFBA05 S315080004700010A0E30B0000EA44229FE5042082E274 S31508000480812082E0B080D2E134229FE5013081E20A S31508000490042082E2832082E0B020D2E1022888E1AB S315080004A0027007E0021081E2060051E3F1FFFFBA8D S315080004B00080A0E1000055E30600000A10029FE54F S315080004C0000004E00010A0E1CC0000EB000050E3BF S315080004D0C5FFFF1A000000EA0800A0E1FF0000E2DD S315080004E0000050E30C00000A0110A0E3BD0000EB79 S315080004F0E0119FE50620A0E1AD0000EBD8119FE5CD S315080005000720A0E1AA0000EB0610A0E1B50000EB69 S315080005100710A0E1B30000EB500000EA0010A0E3CA S31508000520B00000EB4D0000EA9B0000EB0040A0E1A4 S315080005300610A0E1AB0000EB0410A0E10F0100EBF0 S31508000540FF0000E2000050E30200000A0110A0E3E9 S31508000550A40000EB410000EA0010A0E3A10000EBB4 S315080005603E0000EA8C0000EB0070A0E18A0000EB78 S315080005700090A0E10610A0E19A0000EB0180A0E33C S315080005800060A0E3290000EA0040A0E3050000EAB5 S3150800059028519FE5800000EB041085E2041181E0F4 S315080005A0000081E5014084E28000A0E3000054E1F8 S315080005B0F6FFFFBA0040A0E3130000EA760000EB5E S315080005C00010A0E10128A0E12228A0E12008A0E16E S315080005D00008A0E12008A0E1E4109FE5041081E2EC S315080005E0841081E0B020C1E1D4309FE5012084E287 S315080005F00810A0E3010052E13103002A041083E247 S31508000600821081E0B000C1E1024084E20800A0E364 S31508000610000054E1E8FFFFBAFF4008E20710A0E136 S31508000620FE0000EB008004E0027C87E2016086E2BF S31508000630C62FA0E10010A0E3090056E00100D2E0B1 S31508000640D0FFFFBA000058E30100001A0000A0E33B S31508000650000000EA0100A0E30010A0E1610000EB41 S315080006604D0000EB0060A0E1FF20C0E36C109FE5A1 S31508000670010052E1F9FFFF1A64109FE50020A0E18E S315080006804B0000EB0600A0E1FF0000E2FF0000E2DD S31508000690010040E2070050E300F19F37EFFFFFEA51 S315080006A098020008A40200081403000814030008AE S315080006B0A403000828050008640500088413000838 S315080006C0B8130008BC150008D0150008EC1500087A S315080006D0FF01000000FEFFFF081600081C160008B0 S315080006E000C0ADDE3016000800402DE92210A0E358 S315080006F058009FE5C81080E554209FE554109FE5F3 S3150800070054009FE5000081E550009FE5002080E544 S315080007104C109FE5FF00A0E3000081E544009FE53B S31508000720000090E5010010E3FBFFFF0A0020A0E3AC S3150800073020109FE520009FE5000081E528009FE541 S31508000740002080E5FE0000EB0080BDE87FFF2FE17A S31508000750004000402423530344800B205EA200007F S3150800076034800B2000800B2048800B2030800B2023 S3150800077010402DE918409FE50400A0E1F90000EBC0 S315080007800400A0E10C109FE5F60000EB1080BDE820 S315080007907FFF2FE10000094054160008100E10EEE6 S315080007A0010010E3FCFFFF0A100E11EE0EF0A0E1A7 S315080007B07FFF2FE130402DE90250A0E130401FE5D0 S315080007C00400A0E1E70000EB0400A0E10510A0E1A9 S315080007D0F80000EB0400A0E148101FE5E10000EB7B S315080007E03080BDE87FFF2FE1100E10EE020010E307 S315080007F0FCFFFF1A101E01EE0EF0A0E17FFF2FE1AD S3150800080030402DE90150A0E154419FE554119FE580 S315080008100520A0E1E6FFFFEBA524A0E1C0101FE537 S315080008200000A0E3000081E53C119FE50000A0E37D S31508000830000081E5FF1002E22C019FE5001080E52B S315080008402204A0E1FF1000E21C019FE5001080E5EC S3150800085018119FE50000A0E3000081E5FC001FE5F4 S31508000860000090E5020010E3FBFFFF0A400010E3DA S315080008701D00000A000DA0E1200FA0E1F0109FE581 S315080008800020A0E1CAFFFFEB0010A0E3060000EA83 S31508000890D8311FE50400A0E1002090E5040083E2BA S315080008A0010180E0002080E5011081E28000A0E3DC S315080008B0000051E1F5FFFFBA0010A0E3060000EAC8 S315080008C004321FE50400A0E1B020D0E1040083E271 S315080008D0810080E0B020C0E1011081E20800A0E3B9 S315080008E0000051E1F5FFFFBA180000EA0010A0E386 S315080008F0060000EA3C321FE50400A0E1002090E56E S31508000900040083E2010180E0002080E5011081E215 S315080009108000A0E3000051E1F5FFFFBA0010A0E354 S31508000920060000EA68321FE50400A0E1B020D0E125 S31508000930040083E2810080E0B020C0E1011081E27A S315080009400800A0E3000051E1F5FFFFBA010000EA44 S315080009500000A0E3000000EA0100A0E33080BDE843 S315080009607FFF2FE100800A206416000804800B2010 S3150800097014800B208416000800402DE9520200EA74 S3150800098010402DE90140A0E184109FE50420A0E174 S3150800099087FFFFEBA424A0E13C121FE56000A0E35B S315080009A0000081E5FF1002E244001FE5001080E523 S315080009B02204A0E1FF1000E254001FE5001080E5C4 S315080009C064121FE5D000A0E3000081E56C021FE574 S315080009D0000090E5020010E3FBFFFF0A80121FE506 S315080009E07000A0E3000081E528009FE50040D0E5FF S315080009F024109FE50420A0E16DFFFFEB010004E24F S31508000A00000050E30100A0030000A0131080BDE819 S31508000A107FFF2FE1A016000800000B20C41600086F S31508000A2030402DE90150A0E1CC401FE504119FE5B7 S31508000A300520A0E15EFFFFEBA524A0E1E0121FE57B S31508000A400000A0E3000081E5EC121FE58000A0E3AA S31508000A50000081E5F0101FE50000A0E3000081E535 S31508000A60FF1002E200011FE5001080E52204A0E164 S31508000A70FF1000E210011FE5001080E5B8109FE5A1 S31508000A800000A0E3000081E50020A0E3060000EADC S31508000A900400A0E1DC131FE5041081E2021181E0E5 S31508000AA0001091E5001080E5012082E28000A0E3B5 S31508000AB0000052E1F5FFFFBA0020A0E3060000EAB5 S31508000AC00400A0E108141FE5041081E2821081E009 S31508000AD0B010D1E1B010C0E1012082E2030052E378 S31508000AE0F6FFFFBA54109FE5110EA0E3000081E55A S31508000AF090031FE5000090E5020010E3FBFFFF0AE4 S31508000B00A4131FE57000A0E3000081E5FC001FE5C3 S31508000B100040D0E500111FE50420A0E124FFFFEB0B S31508000B20010004E2000050E30100A0030000A01346 S31508000B303080BDE87FFF2FE1E016000808800B2013 S31508000B4010800B2000402DE914009FE50210A0E359 S31508000B500020A0E3E13BA0E3390000EB0080BDE8FC S31508000B607FFF2FE10000084070402DE90060A0E1FA S31508000B700150A0E1000055E30C00000A0040A0E384 S31508000B80070000EA0500A0E10410A0E1B60000EBAA S31508000B900018A0E12118A0E10600A0E1BF0000EBC3 S31508000BA0014084E2040095E5000054E1F4FFFFBA31 S31508000BB07080BDE87FFF2FE170402DE90060A0E15D S31508000BC00150A0E10600A0E15C109FE5E5FFFFEB00 S31508000BD01C40A0E3100000EA0A0040E2410080E25F S31508000BE00018A0E12118A0E1080000EA1F0004E2AD S31508000BF03500A0E10F0000E20A0050E3F5FFFF2AE6 S31508000C00300080E20008A0E12008A0E10010A0E181 S31508000C100600A0E1A10000EB044044E2000054E312 S31508000C20F1FFFFAA7080BDE87FFF2FE108170008D3 S31508000C300000A0E30EF0A0E17FFF2FE1710020E1A4 S31508000C407FFF2FE1F0402DE984D04DE20070A0E14E S31508000C500160A0E10250A0E10340A0E10000A0E38A S31508000C6000008DE50000A0E304008DE50000A0E388 S31508000C7008008DE50000A0E30C008DE50000A0E368 S31508000C8010008DE50000A0E314008DE50000A0E348 S31508000C9018008DE50000A0E31C008DE50000A0E328 S31508000CA020008DE50000A0E324008DE50000A0E308 S31508000CB028008DE50000A0E32C008DE50000A0E3E8 S31508000CC030008DE50000A0E334008DE50000A0E3C8 S31508000CD038008DE50000A0E33C008DE50000A0E3A8 S31508000CE040008DE50000A0E344008DE50000A0E388 S31508000CF048008DE50000A0E34C008DE50000A0E368 S31508000D0050008DE50000A0E354008DE50000A0E347 S31508000D1058008DE50000A0E35C008DE50000A0E327 S31508000D2060008DE50000A0E364008DE50000A0E307 S31508000D3068008DE50000A0E36C008DE50000A0E3E7 S31508000D4070008DE50000A0E374008DE50000A0E3C7 S31508000D5078008DE50000A0E37C008DE50000A0E3A7 S31508000D6080008DE558008DE20010A0E3570000EBE7 S31508000D7058009DE52C008DE55C009DE530008DE56D S31508000D8060009DE534008DE564009DE538008DE53D S31508000D9068009DE53C008DE56C009DE540008DE50D S31508000DA070009DE544008DE574009DE548008DE5DD S31508000DB078009DE54C008DE57C009DE550008DE5AD S31508000DC080009DE554008DE52C008DE2044080E509 S31508000DD02C108DE20800A0E30C0081E52C108DE2B2 S31508000DE00000A0E3080081E52C108DE20100A0E3D5 S31508000DF0100081E52C009DE500008DE530009DE59D S31508000E0004008DE534009DE508008DE538009DE574 S31508000E100C008DE53C009DE510008DE540009DE544 S31508000E2014008DE544009DE518008DE548009DE514 S31508000E301C008DE54C009DE520008DE550009DE5E4 S31508000E4024008DE554009DE528008DE5FF2005E288 S31508000E5000308DE20700A0E10610A0E1380000EBA3 S31508000E6084D08DE2F080BDE87FFF2FE100402DE9B8 S31508000E70000051E3200100BA042090E5020051E188 S31508000E801D0100AA080080E2810080E0000050E30E S31508000E902201000AB000D0E10080BDE87FFF2FE103 S31508000EA00020A0E11400D2E5000DA0E1A00FA0E10A S31508000EB0FF0000E2000050E3F9FFFF0A0108A0E185 S31508000EC02008A0E10000C2E50EF0A0E17FFF2FE1B7 S31508000ED0001080E5961DA0E3041080E50010A0E34D S31508000EE0081080E50810A0E30C1080E50110A0E3C7 S31508000EF0101080E5011BA0E3141080E5011BA0E398 S31508000F00181080E50010E0E31C1080E50010E0E30F S31508000F10201080E50010A0E3241080E50010A0E36F S31508000F202810C0E50010A0E32910C0E50010A0E3D2 S31508000F302A10C0E50010A0E32B10C0E50EF0A0E1D2 S31508000F407FFF2FE1F0412DE90060A0E10150A0E10B S31508000F500200A0E10340A0E1042094E54B0C52E313 S31508000F601B0000CA4B0D52E30D0000CA960E52E351 S31508000F700700000A4B0D52E30100000A2A0000EAA6 S31508000F807FFF2FE10180A0E3A970A0E30130A0E371 S31508000F90330000EA0180A0E3A970A0E30230A0E3D1 S31508000FA02F0000EA960D52E30500000A4B0C52E3A7 S31508000FB01D00001A0380A0E37F70A0E30130A0E3C0 S31508000FC0270000EA0380A0E3FE70A0E30130A0E357 S31508000FD0230000EAE10C52E30B0000CA960C52E328 S31508000FE00500000AE10C52E30F00001A0980A0E38D S31508000FF07F70A0E30130A0E3190000EA0680A0E3B1 S315080010007F70A0E30130A0E3150000EA80129FE597 S31508001010010052E10F00000AE10B52E30900000A41 S3150800102070129FE5010052E10200000A0000A0E3E9 S315080010300010A0E13D0000EA2680A0E34370A0E38B S315080010400130A0E3060000EA1380A0E34370A0E3A2 S315080010500130A0E3020000EA1380A0E38670A0E353 S315080010600130A0E31C291FE5000050E30100001A27 S315080010700110A0E3000000EA0210A0E30804A0E1C2 S315080010807F0C00E2FF7007E2FF00C0E3000087E183 S31508001090040055E305F19F37030000EAB410000881 S315080010A0B0110008EC110008281200080010A0E38F S315080010B01E0000EAE0719FE5007097E5018087E36E S315080010C0D4719FE5008087E5D0719FE5008097E59C S315080010D00112A0E1307001E23010C8E3017087E127 S315080010E0B8119FE5007081E5D00082E55B0000EA53 S315080010F00800A0E3240000EA040080E30C1094E54D S31508001100051041E2040051E301F19F37030000EAAC S315080011102811000838110008441100085011000869 S315080011200010A0E3010000EA0300C0E3090000EA9A S315080011300100A0E1F081BDE80300C0E3010080E3FF S31508001140040000EA0300C0E3020080E3010000EAAD S315080011500300C0E3030080E3851786E00020A0E3D0 S315080011600420C1E50720A0E30820C1E58020A0E30C S315080011700C20C1E50030C1E54324A0E10420C1E507 S315080011800C00C1E5E9FFFFEA1800A0E3101094E59A S31508001190011041E2020051E301F19F37010000EA24 S315080011A0FC100008F81000080010A0E3DFFFFFEAB3 S315080011B0E4709FE5007097E5028087E3D8709FE5A5 S315080011C0008087E5D4709FE5008097E50113A0E1CC S315080011D0C07001E2C010C8E3017087E1BC109FE54A S315080011E0007081E5D40082E51C0000EAA8709FE53E S315080011F0007097E5048087E39C709FE5008087E58B S3150800120098709FE5008097E50114A0E1037C01E250 S31508001210031CC8E3017087E180109FE5007081E533 S31508001220D80082E50D0000EA6C709FE5007097E52E S31508001230088087E360709FE5008087E55C709FE51E S31508001240008097E50115A0E1037B01E2031BC8E3D3 S31508001250017087E144109FE5007081E5DC0082E5B6 S315080012600000A0E3081094E5000051E3C6FFFF0A5A S31508001270080094E5010040E2020050E300F19F37C0 S31508001280010000EAF0100008881100080010A0E329 S31508001290A6FFFFEA00C2010000080700E44000407C S315080012A00440054000402DE91E0000EAF0FBFFEB74 S315080012B07FFF2FE1AFFDFFEB000000EFADFDFFEB79 S315080012C0000000EFABFDFFEB000000EF1C009FE500 S315080012D01C109FE555FEFFEB0010A0E114009FE5EA S315080012E0000081E504009FE553FEFFEB000000EFD8 S315080012F018170008181700081817000814001FE523 S3150800130014101FE549FEFFEB0010A0E11C001FE5C5 S31508001310000081E52C001FE547FEFFEB000000EF0B S31508001320DFFFFFEB000000EF40001FE518109FE508 S315080013303EFEFFEB0010A0E110009FE5000081E5EE S3150800134058001FE53CFEFFEB000000EF5C170008A5 S315080013505C1700089C170008801300089C170008F3 S315080013609C17000818170008B8130008BC150008D1 S31508001370FCF7000800000000000000000000000064 S315080013800000000015000000140000004E004F0089 S3150800139048004100550020004C006F0061006400C1 S315080013A0650072002000530074006100720074002A S315080013B065006400000000008000000000000000D6 S315080013C0000000000000000000000000000000000F S315080013D000000000000000000000000000000000FF S315080013E000000000000000000000000000000000EF S315080013F000000000000000000000000000000000DF S3150800140000000000000000000000000000000000CE S3150800141000000000000000000000000000000000BE S3150800142000000000000000000000000000000000AE S31508001430000000000000000000000000000000009E S31508001440000000000000000000000000000000008E S31508001450000000000000000000000000000000007E S31508001460000000000000000000000000000000006E S31508001470000000000000000000000000000000005E S31508001480000000000000000000000000000000004E S31508001490000000000000000000000000000000003E S315080014A0000000000000000000000000000000002E S315080014B0000000000000000000000000000000001E S315080014C0000000000000000000000000000000000E S315080014D000000000000000000000000000000000FE S315080014E000000000000000000000000000000000EE S315080014F000000000000000000000000000000000DE S3150800150000000000000000000000000000000000CD S3150800151000000000000000000000000000000000BD S3150800152000000000000000000000000000000000AD S31508001530000000000000000000000000000000009D S31508001540000000000000000000000000000000008D S31508001550000000000000000000000000000000007D S31508001560000000000000000000000000000000006D S31508001570000000000000000000000000000000005D S31508001580000000000000000000000000000000004D S31508001590000000000000000000000000000000003D S315080015A0000000000000000000000000000000002D S315080015B00000000000000000000000000800000015 S315080015C0000000000000000000000000000000000D S315080015D00A0000000900000041006400640072006F S315080015E06500730073003A00200000000A0000003E S315080015F0090000004C0065006E0067007400680072 S315080016003A00200020000000060000000500000047 S31508001610530075006D003A00200000000600000027 S315080016200500000041006E0064003A00200000003A S315080016300E0000000D00000047006F007400200037 S3150800164063006F006D006D0061006E0064003A0073 S315080016502000000003000000020000000D000A0040 S31508001660000000000C0000000B000000520065009E S3150800167061006400200050006100670065003A00C0 S315080016802000000009000000080000004600610074 S3150800169069006C00650064003A0020000000000044 S315080016A00E0000000D000000450072006100730086 S315080016B06500200042006C006F0063006B003A0072 S315080016C02000000009000000080000005300740014 S315080016D061007400750073003A00200000000000E5 S315080016E00F0000000E000000500072006F00670037 S315080016F0720061006D0020005000610067006500FF S315080017003A0020000000000003000000020000006C S3150800171030007800000000001D0000001C000000DA S315080017204100720067005F0049006E0064006500B2 S3150800173078004F00750074004F0066005200610083 S315080017406E0067006500450078006300650070005C S31508001750740069006F006E00000000001B000000A6 S315080017601A0000004100720067005F004E00750015 S315080017706C006C005200650066006500720065002A S315080017806E00630065004500780063006500700020 S31108001790740069006F006E000000000085 S3090800F7FC00020000F9 S70508000128C9 ================================================ FILE: Zelig/Zelig/CompileTime/TargetModels/ProductConfiguration/Resources/Microsoft.VoxSoloFormFactorLoader.hex ================================================ S3150800000018F09FE5050000EF0A0000EF060000EF74 S31508000010070000EF000000EF080000EF090000EFFE S315080000202400000804F01FE54C000008040091E5D0 S3150800003000D0A0E1080091E500E0A0E10C0081E213 S315080000400010A0E1FF9F91E87FFF2FE1DFF021E399 S31508000050FC009FE5041080E2020CA0E3000181E0A9 S3150800006000D0A0E1EC109FE50000A0E3500081E578 S315080000700000A0E3200081E5DC209FE5DC009FE589 S315080000800112A0E3001080E54215A0E3041080E504 S31508000090082080E5C8009FE54215A0E3001080E52A S315080000A01114A0E3041080E5082080E5B4409FE51C S315080000B0D510A0E32D0000EB090DA0E3040084E5AC S315080000C0FF00A0E3000084E59C009FE5002090E582 S315080000D00010A0E3080000EA003090E5044090E52F S315080000E0020000EA0000A0E3040083E4014044E2C1 S315080000F0000054E3FAFFFF1A011081E2000092E5BE S31508000100000051E1F60000AA040082E2010180E045 S31508000110000090E5083090E5000053E3EDFFFF0A84 S31508000120083090E5043083E2084090E5045084E204 S31508000130044090E5045185E0000090E5010000EADE S31508000140044093E4044080E4050053E1FBFFFF3AD2 S31508000150E8FFFFEAFCF70B08000001380220000060 S31508000160000001301000013000000B38EC040008D4 S31508000170100041E2000000EA060040E2000050E3F9 S31508000180FCFFFFCA0EF0A0E17FFF2FE100402DE93A S31508000190010000EB710020E17FFF2FE1F0412DE91E S315080001A0740000EA0010A0E1900000EB710000EA7C S315080001B0880000EB14129FE5011080E09800A0E388 S315080001C0B000C1E10810A0E1880000EB690000EA70 S315080001D0800000EBF010A0E3B010C0E10810A0E129 S315080001E0820000EB630000EA7A0000EB0040A0E121 S315080001F0780000EB0050A0E10810A0E17B0000EBBE S31508000200030000EA0100D4E40010A0E1770000EB47 S31508000210015045E2000055E3F9FFFF1A550000EAD0 S315080002206C0000EB0040A0E16A0000EB0050A0E182 S315080002300810A0E16D0000EB030000EAB200D4E06C S315080002400010A0E1690000EB015045E2000055E30B S31508000250F9FFFF1A470000EA5E0000EB0040A0E144 S315080002605C0000EB0050A0E10810A0E15F0000EB85 S31508000270030000EA040094E40010A0E15B0000EB30 S31508000280015045E2000055E3F9FFFF1A390000EA7C S31508000290500000EB0070A0E14E0000EB0060A0E10A S315080002A00050A0E30040E0E30810A0E14F0000EB97 S315080002B0060000EA042097E4011005E2A500A0E183 S315080002C0810F80E1025080E0024004E0016046E2CE S315080002D0000056E3F6FFFF1A0510A0E1430000EB05 S315080002E00410A0E1410000EB220000EA390000EB0F S315080002F00010A0E1430000EB0810A0E13B0000EB72 S315080003000010A0E3390000EB1A0000EA310000EB08 S315080003100040A0E12F0000EB0070A0E10810A0E16A S31508000320320000EB0F0000EA2A0000EB0060A0E1B3 S31508000330025084E20008A0E12008A0E10410A0E130 S315080003400020A0E14F0000EB024085E22608A0E16C S315080003500008A0E12008A0E10510A0E10020A0E126 S31508000360480000EB017047E2000057E3EDFFFF1A73 S315080003700010A0E31D0000EB160000EB0080A0E1D2 S31508000380FF20C0E348109FE5010052E1F9FFFF1A7C S315080003900010A0E1FF1001E2FF1001E2011041E2A6 S315080003A0090051E301F19F37F2FFFFEAA4010008B3 S315080003B0B0010008D0010008E80100082002000882 S315080003C05802000890020008EC0200080C03000816 S315080003D0AA0A000000C0ADDE100E10EE010010E300 S315080003E0FCFFFF0A100E11EE0EF0A0E17FFF2FE1D1 S315080003F0100E10EE020010E3FCFFFF1A101E01EEAD S315080004000EF0A0E17FFF2FE170009FE5000001E0FC S3150800041048201FE5023080E0AA20A0E3B020C3E10F S315080004205C209FE5023080E05520A0E3B020C3E1C0 S3150800043068201FE5023080E08020A0E3B020C3E1F9 S3150800044078201FE5023080E0AA20A0E3B020C3E1AF S315080004502C209FE5022080E05500A0E3B000C2E111 S315080004603000A0E3B000C1E1B020D1E1B000D1E195 S31508000470000052E1FBFFFF1A0EF0A0E17FFF2FE11B S31508000480000080FF5405000010402DE90240A0E15D S3150800049018001FE5003001E0D0001FE5002083E0CA S315080004A0AA00A0E3B000C2E12C001FE5002083E00B S315080004B05500A0E3B000C2E1F0001FE5002083E08C S315080004C0A000A0E3B000C2E1B040C1E1B020D1E194 S315080004D0B000D1E1000052E1FBFFFF1A1080BDE831 S315080004E07FFF2FE128FFFFEB7FFF2FE100000000D1 S309080BF7FC00020000EE S7050800004CA6 ================================================ FILE: Zelig/Zelig/CompileTime/TargetModels/ProductConfiguration/Resources/Microsoft.iMote2Loader.hex ================================================ S3155C00000018F09FE5050000EF0A0000EF060000EF20 S3155C000010070000EF000000EF080000EF090000EFAA S3155C0000202400005C04F01FE54C00005C040091E5D4 S3155C00003000D0A0E1080091E500E0A0E10C0081E2BF S3155C0000400010A0E1FF9F91E87FFF2FE1D7F021E34D S3155C000050C8009FE5041080E2020CA0E3000181E089 S3155C00006000D0A0E1DBF021E3B0009FE5041080E264 S3155C000070020CA0E3000181E000D0A0E1DFF021E307 S3155C00008098009FE5041080E2020CA0E3000181E089 S3155C00009000D0A0E188009FE5002090E50010A0E379 S3155C0000A0080000EA003090E5044090E5020000EAB2 S3155C0000B00000A0E3040083E4014044E2000054E352 S3155C0000C0FAFFFF1A011081E2000092E5000051E19F S3155C0000D0770100AA040082E2010180E0000090E55D S3155C0000E0083090E5000053E3EDFFFF0A083090E529 S3155C0000F0043083E2084090E5045084E2044090E5D5 S3155C000100045185E0000090E5010000EA044093E4B8 S3155C000110044080E4050053E1FBFFFF3AE8FFFFEA99 S3155C000120FCF7035C0407005C00402DE90C009FE5CE S3155C000130030000EB170000EB710020E17FFF2FE16D S3155C000140000030410010A0E140009FE5040081E51D S3155C000150080091E5040080E3080081E530009FE536 S3155C000160000081E503C0A0E310CE06EE100F12EE90 S3155C0001700C0091E5020210E3FCFFFF0A0C0091E51E S3155C000180010210E3FCFFFF0A0EF0A0E17FFF2FE106 S3155C0001900080500010020002F0432DE90110A0E33C S3155C0001A0B80000EBA00000EAFF1002E2FF0051E39A S3155C0001B09D00001A0010A0E1D30000EB0010A0E344 S3155C0001C0B00000EB980000EA0010A0E1CE0000EB66 S3155C0001D0950000EAC20000EB0010A0E1D50000EB40 S3155C0001E00910A0E1C80000EB8F0000EABC0000EB40 S3155C0001F00010A0E1D60000EB0910A0E1C20000EB04 S3155C000200890000EAB60000EB0040A0E1B40000EB18 S3155C0002100050A0E10910A0E1BB0000EB030000EA7E S3155C0002200100D4E40010A0E1B70000EB015045E208 S3155C000230000055E3F9FFFF1A7B0000EAA80000EB1B S3155C0002400040A0E1A60000EB0050A0E10910A0E18F S3155C000250AD0000EB030000EAB200D4E00010A0E1C0 S3155C000260A90000EB015045E2000055E3F9FFFF1AD7 S3155C0002706D0000EA9A0000EB0040A0E1980000EBFC S3155C0002800050A0E10910A0E19F0000EB030000EA2A S3155C000290040094E40010A0E19B0000EB015045E2F1 S3155C0002A0000055E3F9FFFF1A5F0000EA8C0000EBE3 S3155C0002B00070A0E18A0000EB0060A0E10050A0E3C2 S3155C0002C00040E0E30910A0E18F0000EB060000EAC5 S3155C0002D0042097E4011005E2A500A0E1810F80E10E S3155C0002E0025080E0024004E0016046E2000056E312 S3155C0002F0F6FFFF1A0510A0E1830000EB0410A0E1F5 S3155C000300810000EB480000EA750000EB0040A0E1CC S3155C0003100010A0E1920000EB0410A0E1980000EB55 S3155C0003200910A0E1780000EB0010A0E3760000EB7A S3155C0003303D0000EA6A0000EB0040A0E1680000EBCB S3155C0003400080A0E10910A0E16F0000EB320000EA3A S3155C000350630000EB0060A0E1025084E20008A0E1CB S3155C0003602008A0E10410A0E10020A0E1AD0000EBB4 S3155C000370024085E22608A0E10008A0E12008A0E191 S3155C0003800510A0E10020A0E1A60000EB018048E298 S3155C0003900400A0E11F0000EA100058E3EBFFFF3AFF S3155C0003A00410A0E16E0000EB0410A0E12020A0E3A5 S3155C0003B0840000EB0070A0E30F0000EA480000EB4D S3155C0003C00060A0E1025084E20008A0E12008A0E100 S3155C0003D00410A0E10020A0E18F0000EB024085E262 S3155C0003E02608A0E10008A0E12008A0E10510A0E134 S3155C0003F00020A0E1880000EB017087E2100057E363 S3155C000400EDFFFFBA400044E20010A0E1730000EB90 S3155C000410108048E20400A0E10040A0E1000058E33F S3155C000420DCFFFF1A0010A0E3370000EB2C0000EBAA S3155C0004300090A0E1FF20C0E344109FE5010052E17B S3155C000440F9FFFF1A0010A0E1FF2001E2FF1002E2B3 S3155C000450011041E2090051E301F19F3751FFFFEAC8 S3155C000460C801005CD401005CEC01005C0402005C29 S3155C0004703C02005C7402005CAC02005C0803005C3D S3155C0004803403005C00C0ADDE0120A0E140109FE5B6 S3155C00049040009FE5140081E534109FE538009FE538 S3155C0004A0180081E5FF0002E2000050E30500000A47 S3155C0004B01C009FE5181090E5000051E37E00000AE1 S3155C0004C018009FE5000081E5700020E10EF0A0E1D8 S3155C0004D07FFF2FE10807005C0000015C0000025C06 S3155C0004E0FFC0ADDE18001FE5140090E5042080E235 S3155C0004F024101FE5142081E5000050E37000000A1B S3155C000500000090E50EF0A0E17FFF2FE10130A0E155 S3155C00051044001FE5180090E5042080E250101FE5BA S3155C000520182081E5000050E36700000A003080E592 S3155C0005300EF0A0E17FFF2FE110009FE5001081E047 S3155C0005409800A0E3B000C1E10EF0A0E17FFF2FE1CF S3155C000550AA0A0000FF00A0E3B000C1E10EF0A0E132 S3155C0005607FFF2FE16000A0E3B000C1E1D000A0E313 S3155C000570B000C1E1FF00A0E3B000C1E10EF0A0E174 S3155C0005807FFF2FE10120A0E12000A0E3B000C2E1E3 S3155C000590D000A0E3B000C2E1B000D2E1800000E28E S3155C0005A0800050E3FBFFFF1AB010D2E15000A0E3DD S3155C0005B0B000C2E1FF00A0E3B000C2E10100A0E12F S3155C0005C00EF0A0E17FFF2FE1E800A0E3B000C1E1FF S3155C0005D0010042E2B000C1E10EF0A0E17FFF2FE135 S3155C0005E00120A0E1D000A0E3B000C2E1B000D2E1FE S3155C0005F0800000E2800050E3FBFFFF1AB010D2E1FE S3155C0006005000A0E3B000C2E1FF00A0E3B000C2E18D S3155C0006100100A0E10EF0A0E17FFF2FE1B020C1E177 S3155C0006200EF0A0E17FFF2FE130402DE90140A0E113 S3155C0006300250A0E10410A0E1C9FFFFEB0508A0E1B0 S3155C0006402008A0E10410A0E10020A0E1030000EB7B S3155C0006503080BDE87FFF2FE100402DE91C0000EAF9 S3155C0006600130A0E14000A0E3B000C3E1B020C3E1EB S3155C000670B000D3E1800000E2800050E3FBFFFF1A8C S3155C000680B010D3E15000A0E3B000C3E1FF00A0E3EB S3155C000690B000C3E10100A0E10EF0A0E17FFF2FE115 S3155C0006A00000A0E30EF0A0E17FFF2FE1710020E1E6 S3155C0006B07FFF2FE19BFEFFEB7FFF2FE1E5FFFFEB6B S3155C0006C0000000EFE3FFFFEB000000EFE1FFFFEB54 S3155C0006D0000000EF1C009FE51C109FE5EFFFFFEBA1 S3155C0006E00010A0E114009FE5000081E504009FE591 S3155C0006F0EDFFFFEB000000EF2807005C2807005CBD S3155C0007002807005C000000006807005C0407005CCA S3155C0007106807005C6807005C2807005C0000000056 S3155C00072000000000FCF7035C1B0000001A000000E0 S3155C0007304100720067005F004E0075006C006C0043 S3155C0007405200650066006500720065006E0063001D S3155C0007506500450078006300650070007400690000 S30D5C0007606F006E000000000052 S3095C03F7FC00020000A2 S7055C00004C52 ================================================ FILE: Zelig/Zelig/CompileTime/TargetModels/ProductConfiguration/XScaleNorFlashJTagLoaderCategory.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // //#define DEBUG_CMD_PERF namespace Microsoft.Zelig.Configuration.Environment { using System; using System.Threading; using System.Collections.Generic; using Cfg = Microsoft.Zelig.Configuration.Environment; public abstract class XScaleNorFlashJTagLoaderCategory : JtagLoaderCategory { class NorFlashLoader : Emulation.Hosting.JTagCustomer { const uint cmd_Signature = 0xDEADC000; const uint cmd_Mask = 0xFFFFFF00; const byte cmd_Hello = 0x01; const byte cmd_EnterCFI = 0x02; // Arg: Address const byte cmd_ExitCFI = 0x03; // Arg: Address const byte cmd_ReadMemory8 = 0x04; // Arg: Address, Size => values const byte cmd_ReadMemory16 = 0x05; // Arg: Address, Size => values const byte cmd_ReadMemory32 = 0x06; // Arg: Address, Size => values const byte cmd_ChecksumMemory = 0x07; // Arg: Address, Size => CRC value, AND of all memory const byte cmd_EraseSector = 0x08; // Arg: Address => Status value const byte cmd_ProgramMemory = 0x09; // Arg: Address, Size, [32bits words] => Status value const byte cmd_EndOfStream = 0xFF; const uint erasedMemoryPattern = 0xFFFFFFFFu; const uint baseIRAM = 0x5C000000; const uint blockSize = 64 * 1024; const uint baseHostToDevice = baseIRAM + blockSize * 1; const uint baseDeviceToHost = baseIRAM + blockSize * 2; delegate void ProgressCallback( uint pos, uint total ); //--// enum ScheduledWork { None , Program , EraseAndProgram, } class EraseSection { // // State // internal uint m_baseAddress; internal uint m_endAddress; internal uint m_numEraseBlocks; internal uint m_sizeEraseBlocks; internal ScheduledWork[] m_scheduledWork; } class PendingImageSection { // // State // internal readonly ImageSection m_imgSection; internal readonly uint m_offset; internal readonly uint m_len; // // Constructor Methods // internal PendingImageSection( ImageSection imgSection , uint offset , uint len ) { m_imgSection = imgSection; m_offset = offset; m_len = len; } } class ImageSection { // // State // internal readonly uint m_address; internal readonly byte[] m_data; // // Constructor Methods // internal ImageSection( Configuration.Environment.ImageSection section ) { m_address = section.Address; m_data = section.Payload; } // // Helper Methods // internal PendingImageSection Intersects( uint eraseStart , uint eraseEnd ) { uint addressStart = m_address; uint addressEnd = m_address + (uint)m_data.Length; if(addressStart < eraseStart) { if(addressEnd > eraseStart) { uint offset = eraseStart - addressStart; uint len = Math.Min( eraseEnd, addressEnd ) - eraseStart; return new PendingImageSection( this, offset, len ); } } else if(addressStart < eraseEnd) { uint offset = 0; uint len = Math.Min( eraseEnd, addressEnd ) - addressStart; return new PendingImageSection( this, offset, len ); } return null; } } class DelayedMemoryAccess { // // State // const int maxSize = 1024; Emulation.Hosting.JTagConnector m_jtag; uint m_baseAddress; uint m_currentAddress; uint[] m_data; uint m_posWriter; uint m_posReader; // // Constructor Methods // internal DelayedMemoryAccess( Emulation.Hosting.JTagConnector jtag , uint baseAddress ) { m_jtag = jtag; m_baseAddress = baseAddress; m_currentAddress = m_baseAddress; } // // Helper Methods // internal void Reset() { m_currentAddress = m_baseAddress; m_posReader = 0; m_posWriter = 0; } internal void FillBuffer() { if(m_posReader == m_posWriter) { m_data = m_jtag.ReadMemoryBlock( m_currentAddress, maxSize ); m_currentAddress += maxSize * sizeof(uint); m_posReader = 0; m_posWriter = maxSize; } } internal void FlushBuffer() { if(m_posWriter != 0) { m_jtag.WriteMemoryBlock( m_currentAddress, m_data, 0, (int)m_posWriter ); m_currentAddress += m_posWriter * sizeof(uint); m_posWriter = 0; } } internal void Write( uint value ) { if(m_data == null) { m_data = new uint[maxSize]; } if(m_posWriter >= maxSize) { FlushBuffer(); } m_data[m_posWriter++] = value; } internal uint Read() { FillBuffer(); return m_data[m_posReader++]; } } // // State // ProductCategory m_product; Emulation.Hosting.AbstractHost m_owner; Emulation.Hosting.JTagConnector m_jtag; Emulation.Hosting.ProcessorControl m_processorControl; Emulation.Hosting.ProcessorStatus m_processorStatus; DelayedMemoryAccess m_writer; DelayedMemoryAccess m_reader; uint m_flashBaseAddress; ulong m_flashSize; EraseSection[] m_eraseSections; // // Constructor Methods // public NorFlashLoader() { } // // Helper Methods // public override void Deploy( Emulation.Hosting.AbstractHost owner , Cfg.ProductCategory product , List< Configuration.Environment.ImageSection > image , Emulation.Hosting.ProcessorControl.ProgressCallback callback ) { m_owner = owner; m_product = product; owner.GetHostingService( out m_jtag ); owner.GetHostingService( out m_processorControl ); owner.GetHostingService( out m_processorStatus ); m_writer = new DelayedMemoryAccess( m_jtag, baseHostToDevice ); m_reader = new DelayedMemoryAccess( m_jtag, baseDeviceToHost ); try { bool fGot = false; foreach(MemoryCategory mem in product.SearchValues< MemoryCategory >()) { if((mem.Characteristics & Runtime.MemoryAttributes.FLASH) != 0) { m_flashBaseAddress = mem.BaseAddress; m_flashSize = mem.SizeInBytes; fGot = true; break; } } if(fGot == false) { throw TypeConsistencyErrorException.Create( "Product {0} does not have a valid FLASH memory", product.GetType() ); } //--// Start(); uint position = 0; uint total = 0; uint totalPending = 0; List< ImageSection > lst = new List< ImageSection >(); List< PendingImageSection > lstPending = new List< PendingImageSection >(); // // Collect work items. // foreach(var section in image) { if(section.NeedsRelocation == false) { var imgSection = new ImageSection( section ); lst.Add( imgSection ); total += (uint)section.Payload.Length; } } // // Verify if we need to perform any actions. // foreach(var imgSection in lst) { bool fMemoryErased; if(VerifyChecksum( imgSection.m_address, imgSection.m_data, 0, imgSection.m_data.Length, out fMemoryErased ) == false) { // // Found an item that needs attention. Map it to the various FLASH blocks. // foreach(var eraseSection in m_eraseSections) { for(uint pos = 0; pos < eraseSection.m_numEraseBlocks; pos++) { uint eraseStart = eraseSection.m_baseAddress + pos * eraseSection.m_sizeEraseBlocks; uint eraseEnd = eraseStart + eraseSection.m_sizeEraseBlocks; PendingImageSection pending = imgSection.Intersects( eraseStart, eraseEnd ); if(pending != null) { lstPending.Add( pending ); totalPending += pending.m_len; //--// if(eraseSection.m_scheduledWork[pos] != ScheduledWork.EraseAndProgram) { if(fMemoryErased == false) { callback( "Erasing {1}", 0.0f, (float)total ); EraseMemory( eraseStart, eraseEnd ); eraseSection.m_scheduledWork[pos] = ScheduledWork.EraseAndProgram; } else { eraseSection.m_scheduledWork[pos] = ScheduledWork.Program; } } } } } } } if(lstPending.Count > 0) { callback( "Programming {0}/{1} (total image {2})", 0, totalPending, total ); foreach(var pending in lstPending) { ProgramMemory( pending.m_imgSection.m_address, pending.m_imgSection.m_data, pending.m_offset, pending.m_len, delegate( uint positionSub, uint totalSub ) { callback( "Programming {0}/{1} (total image {2})", position + positionSub, totalPending, total ); } ); position += pending.m_len; callback( "Programming {0}/{1} (total image {2})", position, totalPending, total ); } } //--// callback( "Preparing for execution..." ); Emulation.Hosting.ProcessorControl svcPC; owner.GetHostingService( out svcPC ); svcPC.ResetState( product ); } finally { m_jtag.Cleanup(); } } //--// private void SendData( uint data ) { //// Console.WriteLine( "Data: 0x{0:X8}", data ); m_writer.Write( data ); } private uint ReceiveData() { return m_reader.Read(); } private void VerifyData( uint expected ) { SendData( cmd_Signature | cmd_EndOfStream ); m_writer.FlushBuffer(); LetDeviceRun(); m_writer.Reset(); m_reader.Reset(); uint data = ReceiveData(); if(data != expected) { throw TypeConsistencyErrorException.Create( "Failed to synchronize with device, expecting {0:X8}, got {1:X8}", expected, data ); } } //--// private void LoadLoaderImage() { JtagLoaderCategory jtagLoader = m_product.SearchValue< Cfg.JtagLoaderCategory >(); if(jtagLoader == null) { throw TypeConsistencyErrorException.Create( "Product {0} does not have a JTAG loader", m_product.GetType() ); } foreach(uint address in jtagLoader.LoaderData.Keys) { m_jtag.WriteMemoryBlock( address, ToUint( jtagLoader.LoaderData[address] ) ); } m_jtag.ProgramCounter = jtagLoader.EntryPoint; } private void ParseFlashSectors() { for(int tries = 0; tries < 3; tries++) { Execute_EnterCFI(); ushort[] cfg = Execute_ReadMemory16( m_flashBaseAddress, 128 ); if(cfg[0x10] == 'Q' && cfg[0x11] == 'R' && cfg[0x12] == 'Y' ) { uint numEraseBlockRegions = cfg[0x2C]; uint baseAddress = m_flashBaseAddress; m_eraseSections = new EraseSection[numEraseBlockRegions]; for(uint pos = 0; pos < numEraseBlockRegions; pos++) { EraseSection section = new EraseSection(); section.m_baseAddress = baseAddress; section.m_numEraseBlocks = ((uint)cfg[0x2D + pos * 4] + ((uint)cfg[0x2E + pos * 4] << 8)) + 1u; section.m_sizeEraseBlocks = ((uint)cfg[0x2F + pos * 4] + ((uint)cfg[0x30 + pos * 4] << 8)) * 256; section.m_scheduledWork = new ScheduledWork[section.m_numEraseBlocks]; baseAddress += section.m_numEraseBlocks * section.m_sizeEraseBlocks; section.m_endAddress = baseAddress; m_eraseSections[pos] = section; } Execute_ExitCFI(); return; } Execute_ExitCFI(); } throw TypeConsistencyErrorException.Create( "Cannot enter CFI mode" ); } //--// private void Execute_Hello() { SendData( cmd_Signature | cmd_Hello ); VerifyData( cmd_Signature | cmd_Hello ); } private void Execute_EnterCFI() { SendData( cmd_Signature | cmd_EnterCFI ); SendData( m_flashBaseAddress ); VerifyData( cmd_Signature | cmd_EnterCFI ); } private void Execute_ExitCFI() { SendData( cmd_Signature | cmd_ExitCFI ); SendData( m_flashBaseAddress ); VerifyData( cmd_Signature | cmd_ExitCFI ); } private byte[] Execute_ReadMemory8( uint address , int size ) { SendData( cmd_Signature | cmd_ReadMemory8 ); SendData( address ); SendData( (uint)size ); VerifyData( cmd_Signature | cmd_ReadMemory8 ); byte[] res = new byte[size]; for(int i = 0; i < size; i++) { res[i] = (byte)ReceiveData(); } return res; } private ushort[] Execute_ReadMemory16( uint address , int size ) { SendData( cmd_Signature | cmd_ReadMemory16 ); SendData( address ); SendData( (uint)size ); VerifyData( cmd_Signature | cmd_ReadMemory16 ); ushort[] res = new ushort[size]; for(int i = 0; i < size; i++) { res[i] = (ushort)ReceiveData(); } return res; } private uint[] Execute_ReadMemory32( uint address , int size ) { SendData( cmd_Signature | cmd_ReadMemory32 ); SendData( address ); SendData( (uint)size ); VerifyData( cmd_Signature | cmd_ReadMemory32 ); uint[] res = new uint[size]; for(int i = 0; i < size; i++) { res[i] = ReceiveData(); } return res; } private void Execute_ChecksumMemory( uint address , int size , out uint checksum , out uint memoryAND ) { SendData( cmd_Signature | cmd_ChecksumMemory ); SendData( address ); SendData( (uint)size ); VerifyData( cmd_Signature | cmd_ChecksumMemory ); checksum = ReceiveData(); memoryAND = ReceiveData(); } private uint Execute_EraseSector( uint address ) { SendData( cmd_Signature | cmd_EraseSector ); SendData( address ); VerifyData( cmd_Signature | cmd_EraseSector ); return ReceiveData(); } private uint Execute_ProgramMemory( uint address , uint[] data , int size , int offset ) { SendData( cmd_Signature | cmd_ProgramMemory ); SendData( address ); SendData( (uint)size ); while(size-- > 0) { SendData( data[offset++] ); } VerifyData( cmd_Signature | cmd_ProgramMemory ); return ReceiveData(); } //--// private void Start() { if(m_jtag.IsTargetStopped() == false) { m_jtag.StopTarget(); } LoadLoaderImage(); LetDeviceRun(); ParseFlashSectors(); } private void LetDeviceRun() { #if DEBUG_CMD_PERF System.Diagnostics.Stopwatch st = new System.Diagnostics.Stopwatch(); st.Start(); #endif if(m_jtag.RunDevice( 10000 ) == false) { throw new TimeoutException(); } #if DEBUG_CMD_PERF st.Stop(); //// if(m_processorStatus.ProgramCounter != 0x5C000638) //// { //// Console.WriteLine( "BAD PC: 0x{0:X8} {1}", m_processorStatus.ProgramCounter, fStop ); //// } Console.WriteLine( "PC: 0x{0:X8} {1}", m_processorStatus.ProgramCounter, st.ElapsedMilliseconds ); #endif // // Skip breakpoint instruction. // m_processorStatus.ProgramCounter = m_processorStatus.ProgramCounter + sizeof(uint); } private bool VerifyChecksum( uint address , byte[] data , int offset , int size , out bool fMemoryErased ) { uint[] buf = ToUint( data, offset, size ); int len = buf.Length; if(VerifyChecksumInner( (uint)(address + offset), 0, len, buf, out fMemoryErased)) { return true; } //// if(fMemoryErased == false) //// { //// for(uint chunk = 0; chunk < len; chunk += 8192) //// { //// int subLen = (int)(Math.Min( (int)(chunk + 8192), len ) - chunk); //// //// uint[] buf2 = Execute_ReadMemory32( (uint)(address + offset + chunk), subLen ); //// //// for(int pos = 0; pos < subLen; pos++) //// { //// if(buf2[pos] != buf[chunk+pos]) //// { //// Console.WriteLine( "Mismatch: 0x{0:X8}: 0x{1:X8} should be 0x{2:X8}", address + offset + (chunk + pos) * sizeof(uint), buf2[pos], buf[chunk+pos] ); //// } //// } //// } //// } return false; } private bool VerifyChecksumInner( uint address , uint offset , int len , uint[] data , out bool fMemoryErased ) { uint checksum; uint memoryAND; Execute_ChecksumMemory( address + offset * sizeof(uint), len, out checksum, out memoryAND ); uint localChecksum = 0; uint localMemoryAND = erasedMemoryPattern; for(int pos = 0; pos < len; pos++) { uint val = data[offset+pos]; localChecksum = ((localChecksum & 1) << 31) | (localChecksum >> 1); localChecksum += val; localMemoryAND &= val; } fMemoryErased = (memoryAND == erasedMemoryPattern); if(localChecksum == checksum) { return true; } if(fMemoryErased && localMemoryAND == erasedMemoryPattern) { return true; } return false; } private void EraseMemory( uint start , uint end ) { while(true) { EraseSection section = FindSector( start ); if(section == null) { break; } uint address = section.m_baseAddress; for(int j = 0; j < section.m_numEraseBlocks; j++) { uint endAddress = address + section.m_sizeEraseBlocks; if(address <= start && start < endAddress) { Execute_EraseSector( address ); uint checksum; uint memoryAND; Execute_ChecksumMemory( address, (int)section.m_sizeEraseBlocks / sizeof(uint), out checksum, out memoryAND ); if(memoryAND != erasedMemoryPattern) { throw Emulation.Hosting.AbstractEngineException.Create( Emulation.Hosting.AbstractEngineException.Kind.Deployment, "Hardware problem: failed to erase sector at {0:X8}, size={1}", address, section.m_sizeEraseBlocks ); } start = endAddress; if(start >= end) { return; } } address = endAddress; } } } private uint ProgramMemory( uint address , byte[] data , uint offset , uint len , ProgressCallback callback ) { uint rem = offset % sizeof(uint); if(rem != 0) { offset -= rem; len += rem; } uint[] buf = ToUint( data, (int)offset, (int)len ); int lenInWords = buf.Length; int posInWords = 0; while(posInWords < lenInWords) { uint addressBlock = address + offset + (uint)posInWords * sizeof(uint); EraseSection section = FindSector( addressBlock ); if(section == null) { break; } int countInWords = Math.Min( 32768 / sizeof(uint), lenInWords - posInWords ); uint res = Execute_ProgramMemory( addressBlock, buf, countInWords, posInWords ); if(res != 0) { return res; } posInWords += countInWords; callback( (uint)(posInWords * sizeof(uint)), (uint)(lenInWords * sizeof(uint)) ); } return 0; } //--// private EraseSection FindSector( uint address ) { for(int i = 0; i < m_eraseSections.Length; i++) { EraseSection section = m_eraseSections[i]; if(section.m_baseAddress <= address && address < section.m_endAddress) { return section; } } return null; } } //--// protected XScaleNorFlashJTagLoaderCategory( string name , byte[] file ) { using(System.IO.StreamReader reader = new System.IO.StreamReader( new System.IO.MemoryStream( file ) )) { List< Emulation.ArmProcessor.SRecordParser.Block > blocks = new List< Emulation.ArmProcessor.SRecordParser.Block >(); m_entryPoint = Emulation.ArmProcessor.SRecordParser.Parse( reader, name, blocks ); foreach(Emulation.ArmProcessor.SRecordParser.Block block in blocks) { m_loaderData[block.address] = block.data.ToArray(); } } } protected override object GetServiceInner( Type t ) { if(t == typeof(Emulation.Hosting.JTagCustomer)) { return new NorFlashLoader(); } return base.GetServiceInner( t ); } } } ================================================ FILE: Zelig/Zelig/CompileTime/TargetModels/Win32EmuProcessor/InstructionSetVersion.cs ================================================ namespace Microsoft.Zelig.TargetModel.Win32 { public class InstructionSetVersion { // // Platforms // public const string CodeGenerator_LLVM = "LLVM"; // // Platform descriptors fields: fields in the same group are mutually exclusive // // // Platforms // public const uint Platform_Family__Win32 = 0x10000000; public const uint Platform_Family__Mask = 0xFF000000; // // Platform Version // public const uint Platform_Version__x86 = 0x00000100; public const uint Platform_Version__Mask = 0x0000FFFF; // // Platform VFP Version // public const uint Platform_VFP__NoVFP = 0x00010000; public const uint Platform_VFP__Mask = 0x00FF0000; } } ================================================ FILE: Zelig/Zelig/CompileTime/TargetModels/Win32EmuProcessor/Properties/AssemblyInfo.cs ================================================ using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; // General Information about an assembly is controlled through the following // set of attributes. Change these attribute values to modify the information // associated with an assembly. [assembly: AssemblyTitle( "Microsoft.Zelig.TargetModel.ArmProcessor" )] [assembly: AssemblyDescription( "" )] [assembly: AssemblyConfiguration( "" )] [assembly: AssemblyCompany( "Microsoft" )] [assembly: AssemblyProduct( "Microsoft.Zelig.TargetModel.ArmProcessor" )] [assembly: AssemblyCopyright( "Copyright © Microsoft 2006" )] [assembly: AssemblyTrademark( "" )] [assembly: AssemblyCulture( "" )] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible( false )] //// The following GUID is for the ID of the typelib if this project is exposed to COM //[assembly: Guid( "57de0ebe-e971-4cb9-8985-5f6b66934a91" )] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Revision and Build Numbers // by using the '*' as shown below: [assembly: AssemblyVersion( "1.0.0.0" )] [assembly: AssemblyFileVersion( "1.0.0.0" )] ================================================ FILE: Zelig/Zelig/CompileTime/TargetModels/Win32EmuProcessor/Win32Processor.csproj ================================================  Debug AnyCPU 9.0.21022 2.0 {46478CA2-8163-47A0-8C65-3ACFC21CE57F} Library Properties Microsoft.Zelig.TargetModel.Win32EmuProcessor Microsoft.Zelig.TargetModel.Win32EmuProcessor $(LlilumBuildRoot)\Host\obj\$(MSBuildProjectName)\ v4.5 true full false $(LlilumBuildRoot)\Host\bin\$(Configuration)\ DEBUG;TRACE prompt 4 true AllRules.ruleset AnyCPU false pdbonly true $(LlilumBuildRoot)\Host\bin\$(Configuration)\ TRACE prompt 4 true AllRules.ruleset AnyCPU false $(LlilumBuildRoot)\Host\bin\$(Configuration)\ TRACE;DEBUG AnyCPU true false 3.5 ================================================ FILE: Zelig/Zelig/DebugTime/ArmProcessorEmulation/ArmProcessorEmulation.csproj ================================================  Debug AnyCPU 9.0.21022 2.0 {186F31A3-EF89-4A25-B2D5-20060704AA01} Library Properties Microsoft.Zelig.Emulation.ArmProcessor Microsoft.Zelig.Emulation.ArmProcessor $(LlilumBuildRoot)\Host\obj\$(MSBuildProjectName)\ v4.5 true full false $(LlilumBuildRoot)\Host\bin\$(Configuration)\ DEBUG;TRACE prompt 4 true AllRules.ruleset AnyCPU false pdbonly true $(LlilumBuildRoot)\Host\bin\$(Configuration)\ TRACE prompt 4 true AllRules.ruleset AnyCPU false $(LlilumBuildRoot)\Host\bin\$(Configuration)\ TRACE;DEBUG AnyCPU true false Form BaseDebuggerForm.cs 4.0 False ..\..\External\Binaries\JTAG\Debug\TargetAdapterAbstractionLayer.dll {186F31A3-EF89-4A25-B2D5-20070222AA01} CodeTransformation False {186F31A3-EF89-4A25-B2D5-20060510AA01} False Normalized {186F31A3-EF89-4A25-B2D5-20070519AA01} ArmProcessor False {186F31A3-EF89-4A25-B2D5-20070601AA01} CommonPC False {186F31A3-EF89-4A25-B2D5-20061218AA01} Common False BaseDebuggerForm.cs Designer ================================================ FILE: Zelig/Zelig/DebugTime/ArmProcessorEmulation/Forms/BaseDebuggerForm.Designer.cs ================================================ namespace Microsoft.Zelig.Emulation.Hosting.Forms { partial class BaseDebuggerForm { /// /// Required designer variable. /// private System.ComponentModel.IContainer components = null; /// /// Clean up any resources being used. /// /// true if managed resources should be disposed; otherwise, false. protected override void Dispose( bool disposing ) { if(disposing && (components != null)) { components.Dispose(); } base.Dispose( disposing ); } #region Windows Form Designer generated code /// /// Required method for Designer support - do not modify /// the contents of this method with the code editor. /// private void InitializeComponent() { this.SuspendLayout(); // // BaseDebuggerWindow // this.AutoScaleDimensions = new System.Drawing.SizeF( 6F, 13F ); this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font; this.ClientSize = new System.Drawing.Size( 292, 266 ); this.DoubleBuffered = true; this.Name = "BaseDebuggerForm"; this.VisibleChanged += new System.EventHandler( this.BaseDebuggerForm_VisibleChanged ); this.KeyUp += new System.Windows.Forms.KeyEventHandler( this.BaseDebuggerForm_KeyUp ); this.FormClosing += new System.Windows.Forms.FormClosingEventHandler( this.BaseDebuggerForm_FormClosing ); this.KeyDown += new System.Windows.Forms.KeyEventHandler( this.BaseDebuggerForm_KeyDown ); this.ResumeLayout( false ); } #endregion } } ================================================ FILE: Zelig/Zelig/DebugTime/ArmProcessorEmulation/Forms/BaseDebuggerForm.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Text; using System.Windows.Forms; namespace Microsoft.Zelig.Emulation.Hosting.Forms { public partial class BaseDebuggerForm : Form { // // State // private HostingSite m_site; // // Constructor Methods // private BaseDebuggerForm() // Unused contructor required by Visual Studio Designer { } public BaseDebuggerForm( HostingSite site ) { m_site = site; InitializeComponent(); } // // Helper Methods // protected virtual void NotifyChangeInVisibility( bool fVisible ) { } protected virtual bool ProcessKeyDown( KeyEventArgs e ) { return false; } protected virtual bool ProcessKeyUp( KeyEventArgs e ) { return false; } // // Access Methods // protected HostingSite Host { get { return m_site; } } public virtual Image ViewImage { get { return null; } } public virtual string ViewTitle { get { return null; } } // // Event Methods // private void BaseDebuggerForm_FormClosing( object sender , FormClosingEventArgs e ) { if(e.CloseReason == CloseReason.UserClosing) { e.Cancel = true; this.Hide(); } } private void BaseDebuggerForm_VisibleChanged( object sender , EventArgs e ) { bool fVisible = this.Visible; NotifyChangeInVisibility( fVisible ); m_site.ReportFormStatus( this, fVisible ); } private void BaseDebuggerForm_KeyDown( object sender , KeyEventArgs e ) { if(ProcessKeyDown( e ) == false) { m_site.ProcessKeyDownEvent( e ); } } private void BaseDebuggerForm_KeyUp( object sender , KeyEventArgs e ) { if(ProcessKeyUp( e ) == false) { m_site.ProcessKeyUpEvent( e ); } } } } ================================================ FILE: Zelig/Zelig/DebugTime/ArmProcessorEmulation/Forms/BaseDebuggerForm.resx ================================================ text/microsoft-resx 2.0 System.Resources.ResXResourceReader, System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 System.Resources.ResXResourceWriter, System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 ================================================ FILE: Zelig/Zelig/DebugTime/ArmProcessorEmulation/Forms/HostingSite.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // namespace Microsoft.Zelig.Emulation.Hosting.Forms { using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Text; using System.Windows.Forms; using Cfg = Microsoft.Zelig.Configuration.Environment; public abstract class HostingSite { public enum PublicationMode { View , Window, Tools , } //--// public enum ExecutionState { Invalid , Waiting , Loading , Deploying, Idle , Loaded , Running , Paused , } public enum NotificationResponse { DoNothing , RemoveFromNotificationList, } public delegate NotificationResponse ExecutionStateChangeNotification( HostingSite host, ExecutionState oldState, ExecutionState newState ); //--// public enum VisualizationEvent { NewStackFrame , BreakpointsChange, } public delegate NotificationResponse VisualizationEventNotification( HostingSite host, VisualizationEvent e ); //--// // // State // protected List< ExecutionStateChangeNotification > m_notifyExecutionStateChange = new List< ExecutionStateChangeNotification >(); protected List< VisualizationEventNotification > m_notifyVisualizationEvent = new List< VisualizationEventNotification >(); // // Helper Methods // public abstract void ProcessKeyDownEvent( KeyEventArgs e ); public abstract void ProcessKeyUpEvent( KeyEventArgs e ); public abstract void ReportFormStatus( BaseDebuggerForm form , bool fOpened ); public abstract void RegisterView( BaseDebuggerForm form , PublicationMode mode ); public abstract void UnregisterView( BaseDebuggerForm form , PublicationMode mode ); //--// public abstract void VisualizeDebugInfo( Debugging.DebugInfo di ); //--// public bool GetHostingService< T >( out T service ) { service = (T)GetHostingService( typeof(T) ); return service != null; } public abstract object GetHostingService( Type t ); public abstract void RegisterService( Type type , object impl ); public abstract void UnregisterService( object impl ); //--// public void RaiseNotification( ExecutionState oldState , ExecutionState newState ) { foreach(var dlg in m_notifyExecutionStateChange.ToArray()) { switch(dlg( this, oldState, newState )) { case NotificationResponse.RemoveFromNotificationList: m_notifyExecutionStateChange.Remove( dlg ); break; } } } public void RaiseNotification( VisualizationEvent e ) { foreach(var dlg in m_notifyVisualizationEvent.ToArray()) { switch(dlg( this, e )) { case NotificationResponse.RemoveFromNotificationList: m_notifyVisualizationEvent.Remove( dlg ); break; } } } // // Access Methods // public abstract bool IsIdle { get; } public event ExecutionStateChangeNotification NotifyOnExecutionStateChange { add { if(m_notifyExecutionStateChange.Contains( value ) == false) { m_notifyExecutionStateChange.Add( value ); } } remove { m_notifyExecutionStateChange.Remove( value ); } } public event VisualizationEventNotification NotifyOnVisualizationEvent { add { if(m_notifyVisualizationEvent.Contains( value ) == false) { m_notifyVisualizationEvent.Add( value ); } } remove { m_notifyVisualizationEvent.Remove( value ); } } } } ================================================ FILE: Zelig/Zelig/DebugTime/ArmProcessorEmulation/Hosting/AbstractEngine.cs ================================================ using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace Microsoft.Zelig.Emulation.Hosting { using Microsoft.Zelig.TargetModel.ArmProcessor; public abstract class AbstractEngine : AbstractHost { // // State // protected readonly InstructionSet m_instructionSet; // // Constructor Methods // public AbstractEngine(InstructionSet iset) { m_instructionSet = iset; } public bool CanDecode() { return m_instructionSet != null; } public InstructionSet InstructionSet { get { return m_instructionSet; } } } } ================================================ FILE: Zelig/Zelig/DebugTime/ArmProcessorEmulation/Hosting/AbstractEngineException.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // using System; using System.Collections.Generic; using System.Text; namespace Microsoft.Zelig.Emulation.Hosting { public class AbstractEngineException : Exception { public enum Kind { Initialization, Deployment , Shutdown , } // // State // public readonly Kind Reason; // // Constructor Methods // public AbstractEngineException( Kind reason , string message ) : base( message ) { this.Reason = reason; } public AbstractEngineException( Kind reason , string message , Exception innerException ) : base( message, innerException ) { this.Reason = reason; } // // Helper Methods // public static AbstractEngineException Create( Kind reason , string format , params object[] parms ) { return Create( reason, null, format, parms ); } public static AbstractEngineException Create( Kind reason , Exception innerException , string format , params object[] parms ) { return new AbstractEngineException( reason, string.Format( format, parms ), innerException ); } } } ================================================ FILE: Zelig/Zelig/DebugTime/ArmProcessorEmulation/Hosting/AbstractHardwarePlugIn.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // namespace Microsoft.Zelig.Emulation.Hosting { using System; using System.Collections.Generic; using Cfg = Microsoft.Zelig.Configuration.Environment; public abstract class AbstractHardwarePlugIn : AbstractPlugIn { // // State // protected Hosting.AbstractHost m_engine; protected Cfg.ProductCategory m_product; // // Constructor Methods // protected AbstractHardwarePlugIn( Hosting.AbstractHost engine , Cfg.ProductCategory product ) { m_engine = engine; m_product = product; } // // Helper Methods // } } ================================================ FILE: Zelig/Zelig/DebugTime/ArmProcessorEmulation/Hosting/AbstractHost.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // namespace Microsoft.Zelig.Emulation.Hosting { using System; using System.Collections.Generic; using Cfg = Microsoft.Zelig.Configuration.Environment; public abstract class AbstractHost { // // State // Dictionary< Type, object > m_registeredServices = new Dictionary< Type, object >(); List< AbstractHost > m_delegateServices = new List< AbstractHost >(); List< Hosting.AbstractHardwarePlugIn > m_plugIns = new List< Hosting.AbstractHardwarePlugIn >(); // // Helper Methods // public void RegisterService( Type t , object impl ) { m_registeredServices[t] = impl; } public void UnregisterService( object impl ) { List< Type > lst = new List< Type >( m_registeredServices.Keys ); foreach(Type t in lst) { object val; if(m_registeredServices.TryGetValue( t, out val ) && val == impl) { m_registeredServices.Remove( t ); } } } public bool GetHostingService< T >( out T service ) { service = (T)GetHostingService( typeof(T) ); return service != null; } public object GetHostingService( Type t ) { object obj; if(m_registeredServices.TryGetValue( t, out obj )) { return obj; } foreach(AbstractHost host in m_delegateServices) { if(host.m_registeredServices.TryGetValue( t, out obj )) { return obj; } } return null; } //--// protected void Link( object target ) { AbstractHost host = target as AbstractHost; if(host != null) { if(m_delegateServices.Contains( host ) == false) { host.m_delegateServices.Add( this ); this.m_delegateServices.Add( host ); } } } protected void Unlink( object target ) { AbstractHost host = target as AbstractHost; if(host != null) { host.m_delegateServices.Remove( this ); this.m_delegateServices.Remove( host ); } } //--// protected void StartPlugIns( Cfg.ProductCategory product , List< Type > extraHandlers ) { foreach(Type t in extraHandlers) { if(t.IsSubclassOf( typeof(Hosting.AbstractHardwarePlugIn))) { Hosting.AbstractHardwarePlugIn plugIn = (Hosting.AbstractHardwarePlugIn)Activator.CreateInstance( t, this, product ); m_plugIns.Add( plugIn ); plugIn.Start(); } } } protected void StopPlugIns() { foreach(Hosting.AbstractHardwarePlugIn plugIn in m_plugIns) { plugIn.Stop(); } m_plugIns.Clear(); } } } ================================================ FILE: Zelig/Zelig/DebugTime/ArmProcessorEmulation/Hosting/AbstractPlugIn.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // namespace Microsoft.Zelig.Emulation.Hosting { using System; using System.Collections.Generic; public abstract class AbstractPlugIn { // // Helper Methods // public abstract void Start(); public abstract void Stop(); } } ================================================ FILE: Zelig/Zelig/DebugTime/ArmProcessorEmulation/Hosting/AbstractUIPlugIn.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // namespace Microsoft.Zelig.Emulation.Hosting { using System; using System.Collections.Generic; using System.Windows.Forms; public abstract class AbstractUIPlugIn : AbstractPlugIn { // // State // protected Forms.HostingSite m_owner; // // Constructor Methods // protected AbstractUIPlugIn( Forms.HostingSite owner ) { m_owner = owner; } // // Helper Methods // } } ================================================ FILE: Zelig/Zelig/DebugTime/ArmProcessorEmulation/Hosting/BinaryBlob.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // namespace Microsoft.Zelig.Emulation.Hosting { using System; using System.Collections.Generic; using System.IO; public sealed class BinaryBlob { // // State // private readonly byte[] m_data; // // Constructor Methods // public BinaryBlob( int size ) { m_data = new byte[size]; } public BinaryBlob( byte[] data ) { m_data = data; } // // Helper Methods // public BinaryBlob Extract( int offset , int count ) { if(offset == 0 && count == this.Size) { return this; } var bb = new BinaryBlob( count ); for(int pos = 0; pos < count; pos++) { bb.WriteUInt8( this.ReadUInt8( pos + offset ), pos ); } return bb; } public void Insert( BinaryBlob bb , int offset ) { Insert( bb, offset, bb.Size ); } public void Insert( BinaryBlob bb , int offset , int count ) { for(int pos = 0; pos < count; pos++) { this.WriteUInt8( bb.ReadUInt8( pos ), pos + offset ); } } //--// public byte ReadUInt8( int offset ) { if(offset >= 0 && offset < m_data.Length) { return m_data[offset]; } return 0; } public ushort ReadUInt16( int offset ) { byte partLo = ReadUInt8( offset ); byte partHi = ReadUInt8( offset + sizeof(byte) ); return (ushort)(((uint)partHi << 8) | (uint)partLo); } public uint ReadUInt32( int offset ) { ushort partLo = ReadUInt16( offset ); ushort partHi = ReadUInt16( offset + sizeof(ushort) ); return (((uint)partHi << 16) | (uint)partLo); } public ulong ReadUInt64( int offset ) { uint partLo = ReadUInt32( offset ); uint partHi = ReadUInt32( offset + sizeof(uint) ); return (((ulong)partHi << 32) | (ulong)partLo); } public byte[] ReadBlock( int offset , int count ) { var res = new byte[count]; for(int pos = 0; pos < count; pos++) { res[pos] = this.ReadUInt8( offset + pos ); } return res; } //--// public void WriteUInt8( byte val , int offset ) { if(offset >= 0 && offset < m_data.Length) { m_data[offset] = val; } } public void WriteUInt16( ushort val , int offset ) { WriteUInt8( (byte) val , offset ); WriteUInt8( (byte)(val >> 8), offset + sizeof(byte) ); } public void WriteUInt32( uint val , int offset ) { WriteUInt16( (ushort) val , offset ); WriteUInt16( (ushort)(val >> 16), offset + sizeof(ushort) ); } public void WriteUInt64( ulong val , int offset ) { WriteUInt32( (uint) val , offset ); WriteUInt32( (uint)(val >> 32), offset + sizeof(uint) ); } //--// public void WriteBlock( byte[] buf , int offset ) { foreach(var val in buf) { WriteUInt8( val, offset++ ); } } //--// public static BinaryBlob Wrap( byte value ) { var bb = new BinaryBlob( sizeof(byte) ); bb.WriteUInt8( value, 0 ); return bb; } public static BinaryBlob Wrap( ushort value ) { var bb = new BinaryBlob( sizeof(ushort) ); bb.WriteUInt16( value, 0 ); return bb; } public static BinaryBlob Wrap( uint value ) { var bb = new BinaryBlob( sizeof(uint) ); bb.WriteUInt32( value, 0 ); return bb; } public static BinaryBlob Wrap( uint valueLo , uint valueHi ) { var bb = new BinaryBlob( sizeof(ulong) ); bb.WriteUInt32( valueLo, 0 ); bb.WriteUInt32( valueHi, 0 + sizeof(uint) ); return bb; } public static BinaryBlob Wrap( ulong value ) { var bb = new BinaryBlob( sizeof(ulong) ); bb.WriteUInt64( value, 0 ); return bb; } public static BinaryBlob Wrap( object value ) { if(value is bool) { return Wrap( (byte)((bool)value ? 1 : 0) ); } if(value is byte) { return Wrap( (byte)value ); } if(value is sbyte) { return Wrap( (byte)(sbyte)value ); } if(value is char) { return Wrap( (ushort)(char)value ); } if(value is short) { return Wrap( (ushort)(short)value ); } if(value is ushort) { return Wrap( (ushort)value ); } if(value is int) { return Wrap( (uint)(int)value ); } if(value is uint) { return Wrap( (uint)value ); } if(value is long) { return Wrap( (ulong)(long)value ); } if(value is ulong) { return Wrap( (ulong)value ); } if(value is float) { return Wrap( DataConversion.GetFloatAsBytes( (float)value )); } if(value is double) { return Wrap( DataConversion.GetDoubleAsBytes( (double)value )); } return null; } // // Access Methods // public byte[] Payload { get { return m_data; } } public int Size { get { return m_data.Length; } } } } ================================================ FILE: Zelig/Zelig/DebugTime/ArmProcessorEmulation/Hosting/Breakpoint.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // namespace Microsoft.Zelig.Emulation.Hosting { using System; using System.Collections.Generic; public class Breakpoint { public enum Status { NotSet , HardBreakpoint, SoftBreakpoint, } [Flags] public enum Response { DoNothing = 0x00000000, StopExecution = 0x00000001, NextInstruction = 0x00000002, } public delegate Response Callback( Breakpoint bp ); // // State // private readonly uint m_address; private readonly Debugging.DebugInfo m_di; private readonly Callback m_target; private int m_version; private bool m_fActive; private bool m_fIsOptional; private bool m_fIsTemporary; private bool m_fImplementInHardware; private bool m_fShowInUI; private long m_hitCount; private Status m_status; private bool m_fHit; private bool m_fIgnoreOnce; // // Constructor Methods // public Breakpoint( uint address , Debugging.DebugInfo di , Callback target ) { m_address = address; m_di = di; m_target = target; } // // Helper Methods // public bool ShouldStopOverStatement( uint pc ) { m_fHit = false; if(!m_fActive) { return false; } if(pc == m_address) { m_fIgnoreOnce = true; return true; } return false; } public void ClearIgnoreFlag() { m_fIgnoreOnce = false; } public Response Hit() { m_fHit = true; m_hitCount++; if(m_target == null) { return Response.StopExecution; } return m_target( this ); } //--// // // Access Methods // public uint Address { get { return m_address; } } public Debugging.DebugInfo DebugInfo { get { return m_di; } } public int Version { get { return m_version; } } public bool IsActive { get { return m_fActive; } set { m_fActive = value; m_version++; } } public Status SetAs { get { return m_status; } set { m_status = value; m_version++; } } public bool ShouldIgnoreOnce { get { return m_fIgnoreOnce; } } public bool IsOptional { get { return m_fIsOptional; } set { m_fIsOptional = value; m_version++; } } public bool ShowInUI { get { return m_fShowInUI; } set { m_fShowInUI = value; m_version++; } } public bool IsTemporary { get { return m_fIsTemporary; } set { m_fIsTemporary = value; m_version++; } } public bool ShouldImplementInHardware { get { return m_fImplementInHardware; } set { m_fImplementInHardware = value; m_version++; } } public bool WasHit { get { return m_fHit; } } public long HitCount { get { return m_hitCount; } set { m_hitCount = value; } } public Callback Target { get { return m_target; } } } } ================================================ FILE: Zelig/Zelig/DebugTime/ArmProcessorEmulation/Hosting/CodeCoverage.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // namespace Microsoft.Zelig.Emulation.Hosting { using System; using System.Collections.Generic; public abstract class CodeCoverage { public delegate void EnumerationCallback( uint address, uint hits, uint cycles, uint waitStates ); // // Helper Methods // public abstract void Reset(); public abstract void Dump(); public abstract void Enumerate( EnumerationCallback dlg ); public abstract void SetSymbols( ArmProcessor.SymDef.SymbolToAddressMap symdef , ArmProcessor.SymDef.AddressToSymbolMap symdef_Inverse ); // // Access Methods // public abstract bool Enable { get; set; } } } ================================================ FILE: Zelig/Zelig/DebugTime/ArmProcessorEmulation/Hosting/DebugCommunicationChannel.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // namespace Microsoft.Zelig.Emulation.Hosting { using System; using System.Collections.Generic; public abstract class DebugCommunicationChannel { // // State // protected int m_useCount; // // Helper Methods // public virtual void Start() { m_useCount++; } public virtual void Stop() { m_useCount--; } public abstract bool ReadFromProcessor ( out uint value ); public abstract bool WriteFromProcessor( uint value ); public abstract bool ReadFromDebugger ( out uint value, int Timeout ); public abstract bool WriteFromDebugger( uint value, int Timeout ); public abstract void AbortDebuggerRead (); public abstract void AbortDebuggerWrite(); //--// // // Access Methods // public bool IsActive { get { return m_useCount != 0; } } } } ================================================ FILE: Zelig/Zelig/DebugTime/ArmProcessorEmulation/Hosting/DeviceClockTicksTracking.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // namespace Microsoft.Zelig.Emulation.Hosting { using System; using System.Collections.Generic; public abstract class DeviceClockTicksTracking { public delegate void Callback(); public class ClockTickCallbackDescriptor { // // State // public readonly ulong ClockTicks; public readonly Callback Callback; // // Constructor Methods // public ClockTickCallbackDescriptor( ulong clockTicks , Callback callback ) { this.ClockTicks = clockTicks; this.Callback = callback; } } // // State // ulong m_clockFrequency; ulong m_nextClockTicksCallback; List< ClockTickCallbackDescriptor > m_clockTicksCallbacks; // // Constructor Methods // protected DeviceClockTicksTracking() { m_nextClockTicksCallback = ulong.MaxValue; m_clockTicksCallbacks = new List< ClockTickCallbackDescriptor >(); } // // Helper Methods // public virtual void ResetState() { m_nextClockTicksCallback = ulong.MaxValue; m_clockTicksCallbacks.Clear(); } public TimeSpan ClockTicksToTime( long clockTicks ) { return new TimeSpan( (long)((double)clockTicks / m_clockFrequency * TimeSpan.TicksPerSecond) ); } public long TimeToClockTicks( TimeSpan time ) { return (long)(time.TotalSeconds * m_clockFrequency); } public void RequestRelativeClockTickCallback( long relativeClockTicks , Callback callback ) { RequestAbsoluteClockTickCallback( this.ClockTicks + (ulong)relativeClockTicks, callback ); } public void RequestAbsoluteClockTickCallback( ulong absoluteClockTicks , Callback callback ) { CancelClockTickCallback( callback ); lock(this.LockRoot) { int pos = 0; while(pos < m_clockTicksCallbacks.Count) { ClockTickCallbackDescriptor cd = m_clockTicksCallbacks[pos]; if(cd.ClockTicks > absoluteClockTicks) { break; } pos++; } m_clockTicksCallbacks.Insert( pos, new ClockTickCallbackDescriptor( absoluteClockTicks, callback ) ); if(pos == 0) { m_nextClockTicksCallback = absoluteClockTicks; NotifyActivity(); } } } public void CancelClockTickCallback( Callback callback ) { lock(this.LockRoot) { for(int pos = 0; pos < m_clockTicksCallbacks.Count; pos++) { ClockTickCallbackDescriptor cd = m_clockTicksCallbacks[pos]; if(cd.Callback == callback) { m_clockTicksCallbacks.RemoveAt( pos ); if(pos == 0) { SetNextClockTickCallback(); } return; } } } } //--// public abstract bool GetAbsoluteTime( out ulong clockTicks , out ulong nanoseconds ); public abstract IDisposable SuspendTiming(); //--// private void SetNextClockTickCallback() { if(m_clockTicksCallbacks.Count > 0) { m_nextClockTicksCallback = m_clockTicksCallbacks[0].ClockTicks; NotifyActivity(); } else { m_nextClockTicksCallback = ulong.MaxValue; } } public bool ShouldProcessClockTicksCallback( ulong clockTicks ) { return m_nextClockTicksCallback <= clockTicks; } public long TimeToNextCallback( ulong clockTicks ) { return (long)(m_nextClockTicksCallback - clockTicks); } public void ProcessClockTicksCallback() { //// DumpTimestamped( "ProcessClockTicksCallback", clockTicks, "{0,9} Delta:{1}", m_nextClockTicksCallback, clockTicks - m_nextClockTicksCallback ); ClockTickCallbackDescriptor cd; lock(this.LockRoot) { CHECKS.ASSERT( m_clockTicksCallbacks.Count > 0, "'m_nextClockTicksCallback < m_clockTicks' and no work items to execute!" ); cd = m_clockTicksCallbacks[0]; if(cd.ClockTicks > this.ClockTicks) { // // If we get here and there's a race condition (someone modified the top callback), just exit. // return; } m_clockTicksCallbacks.RemoveAt( 0 ); SetNextClockTickCallback(); } //// DumpTimestamped( "Callback Start", this.ClockTicks, "{0} {1}", cd.m_callback.Method, GC.CollectionCount( 0 ) ); cd.Callback(); //// DumpTimestamped( "Callback End", this.ClockTicks, "{0} {1}", cd.m_callback.Method, GC.CollectionCount( 0 ) ); } protected abstract void NotifyActivity(); //--// public ulong FromPerformanceCounterToClockTicks( long perfTicks ) { return (ulong)((double)perfTicks / System.Diagnostics.Stopwatch.Frequency * m_clockFrequency); } public ulong FromMillisecondsToClockTicks( int milliSeconds ) { return (ulong)((double)milliSeconds / 1000 * m_clockFrequency); } public long FromClockTicksToMilliseconds( long clockTicks ) { return (long)((double)clockTicks / m_clockFrequency * 1000); } public double FromClockTicksToSeconds( long clockTicks ) { return (double)clockTicks / m_clockFrequency; } // // Access Methods // public ulong ClockFrequency { get { return m_clockFrequency; } set { m_clockFrequency = value; } } public abstract ulong ClockTicks { get; } protected abstract object LockRoot { get; } } } ================================================ FILE: Zelig/Zelig/DebugTime/ArmProcessorEmulation/Hosting/ExtraDeploymentSteps.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // namespace Microsoft.Zelig.Emulation.Hosting { using System; using System.Collections.Generic; using Cfg = Microsoft.Zelig.Configuration.Environment; public abstract class ExtraDeploymentSteps { // // State // // // Helper Methods // public abstract List< Configuration.Environment.ImageSection > TransformImage( List< Configuration.Environment.ImageSection > image ); public abstract void ExecuteToEntryPoint( Emulation.Hosting.AbstractHost owner , uint entryPointAddress ); } } ================================================ FILE: Zelig/Zelig/DebugTime/ArmProcessorEmulation/Hosting/HalButtons.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // namespace Microsoft.Zelig.Emulation.Hosting { using System; using System.Collections.Generic; public abstract class HalButtons { public const uint BUTTON_NONE = 0x00000000; public const uint BUTTON_B0 = 0x00000001; public const uint BUTTON_B1 = 0x00000002; public const uint BUTTON_B2 = 0x00000004; public const uint BUTTON_B3 = 0x00000008; public const uint BUTTON_B4 = 0x00000010; public const uint BUTTON_B5 = 0x00000020; //--// public abstract bool GetNextStateChange( out uint buttonsPressed , out uint buttonsReleased ); public abstract void QueueNextStateChange( uint buttonsPressed , uint buttonsReleased ); } } ================================================ FILE: Zelig/Zelig/DebugTime/ArmProcessorEmulation/Hosting/HalEvents.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // namespace Microsoft.Zelig.Emulation.Hosting { using System; using System.Collections.Generic; public abstract class HalEvents { public const uint SYSTEM_EVENT_FLAG_COM1_IN = 0x00000001; public const uint SYSTEM_EVENT_FLAG_COM1_OUT = 0x00000002; public const uint SYSTEM_EVENT_FLAG_COM2_IN = 0x00000004; public const uint SYSTEM_EVENT_FLAG_COM2_OUT = 0x00000008; public const uint SYSTEM_EVENT_FLAG_TIMER0 = 0x00000010; public const uint SYSTEM_EVENT_FLAG_TIMER1 = 0x00000020; public const uint SYSTEM_EVENT_FLAG_TIMER2 = 0x00000040; public const uint SYSTEM_EVENT_FLAG_RADIO = 0x00000080; public const uint SYSTEM_EVENT_FLAG_BUTTON = 0x00000100; public const uint SYSTEM_EVENT_FLAG_TONE_COMPLETE = 0x00000200; public const uint SYSTEM_EVENT_FLAG_TONE_BUFFER_EMPTY = 0x00000400; public const uint SYSTEM_EVENT_FLAG_ALARM = 0x00000800; public const uint SYSTEM_EVENT_FLAG_RSA_DECODE_COMPLETE = 0x00001000; public const uint SYSTEM_EVENT_FLAG_RSA_ENCODE_COMPLETE = 0x00002000; public const uint SYSTEM_EVENT_FLAG_UNUSED_0x00004000 = 0x00004000; public const uint SYSTEM_EVENT_FLAG_SPI_COMPLETE = 0x00008000; public const uint SYSTEM_EVENT_FLAG_CHARGER_CHANGE = 0x00010000; public const uint SYSTEM_EVENT_FLAG_APP_DEFINED_1 = 0x00020000; public const uint SYSTEM_EVENT_FLAG_APP_DEFINED_2 = 0x00040000; public const uint SYSTEM_EVENT_FLAG_APP_DEFINED_3 = 0x00080000; public const uint SYSTEM_EVENT_FLAG_APP_DEFINED_4 = 0x00100000; public const uint SYSTEM_EVENT_FLAG_VITERBI_DONE = 0x00200000; public const uint SYSTEM_EVENT_FLAG_MAC_DONE = 0x00400000; public const uint SYSTEM_EVENT_HEARTRATE = 0x00800000; public const uint SYSTEM_EVENT_TS_INIT_DONE = 0x01000000; public const uint SYSTEM_EVENT_AIRPRESSURE_DONE = 0x02000000; public const uint SYSTEM_EVENT_FLAG_USB_IN = 0x04000000; public const uint SYSTEM_EVENT_HW_INTERRUPT = 0x08000000; public const uint SYSTEM_EVENT_I2C_XACTION = 0x10000000; public const uint SYSTEM_EVENT_FLAG_UNUSED_0x20000000 = 0x20000000; public const uint SYSTEM_EVENT_FLAG_UNUSED_0x40000000 = 0x40000000; public const uint SYSTEM_EVENT_FLAG_UNUSED_0x80000000 = 0x80000000; public const uint SYSTEM_EVENT_FLAG_ALL = 0xFFFFFFFF; //--// public abstract void Clear( uint mask ); public abstract void Set( uint mask ); public abstract uint Get( uint mask ); public abstract uint MaskedRead( uint mask ); } } ================================================ FILE: Zelig/Zelig/DebugTime/ArmProcessorEmulation/Hosting/IAsynchronousSerialPort.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // namespace Microsoft.Zelig.Emulation.Hosting { using System; using System.Collections.Generic; public interface IAsynchronousSerialInterface { void Send( byte value ); bool Receive( int timeout, out byte value ); int PortNumber { get; } } } ================================================ FILE: Zelig/Zelig/DebugTime/ArmProcessorEmulation/Hosting/ISynchronousSerialInterfaceBus.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // namespace Microsoft.Zelig.Emulation.Hosting { using System; using System.Collections.Generic; // // Master mode, from controller to bus. // public interface ISynchronousSerialInterfaceBus { uint ShiftData( uint value , int bitSize , int clockFrequency ); } } ================================================ FILE: Zelig/Zelig/DebugTime/ArmProcessorEmulation/Hosting/ISynchronousSerialInterfaceController.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // namespace Microsoft.Zelig.Emulation.Hosting { using System; using System.Collections.Generic; // // Slave mode, from bus to controller. // public interface ISynchronousSerialInterfaceController { uint ShiftData( uint value , int bitSize , int clockFrequency ); void StartTransaction(); void EndTransaction(); } } ================================================ FILE: Zelig/Zelig/DebugTime/ArmProcessorEmulation/Hosting/Interop.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // namespace Microsoft.Zelig.Emulation.Hosting { using System; using System.Collections.Generic; public abstract class Interop { [Flags] public enum CallbackResponse { DoNothing = 0x00000000, StopExecution = 0x00000001, NextInstruction = 0x00000002, RemoveDetour = 0x00000004, } public delegate CallbackResponse Callback(); public class Registration { // // State // public readonly uint Address; public readonly bool IsPostProcessing; public readonly Callback Target; // // Constructor Methods // public Registration( uint address , bool isPostProcessing , Callback target ) { this.Address = address; this.IsPostProcessing = isPostProcessing; this.Target = target; } } //--// // // Helper Methods // public abstract Registration SetInterop( uint pc , bool fHead , bool fPostProcessing , Callback ftn ); public abstract void RemoveInterop( Registration reg ); } } ================================================ FILE: Zelig/Zelig/DebugTime/ArmProcessorEmulation/Hosting/JTagConnector.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // namespace Microsoft.Zelig.Emulation.Hosting { using System; using System.Collections.Generic; using System.Threading; using Cfg = Microsoft.Zelig.Configuration.Environment; public abstract class JTagConnector { public struct RegisterSet { public string Name; public object Value; } // // State // bool m_fStopExecution; Timer m_timer; // // Constructor Methods // protected JTagConnector() { m_timer = new Timer( new TimerCallback(OnTimer), this, -1, -1 ); } // // Helper Methods // public abstract bool IsTargetStopped(); public abstract void StopTarget(); public abstract bool ExecuteCode( int timeout , RegisterSet[] input , RegisterSet[] output ); public void RunDevice() { RunDevice( Timeout.Infinite ); } public bool RunDevice( int timeout ) { m_fStopExecution = false; if(timeout == Timeout.Infinite) { RunDeviceInner( ref m_fStopExecution ); } else { m_timer.Change( timeout, -1 ); RunDeviceInner( ref m_fStopExecution ); m_timer.Change( -1, -1 ); } return m_fStopExecution == false; } public void AbortRunDevice() { m_fStopExecution = true; } public abstract uint[] ReadMemoryBlock( uint address , int count ); public abstract void WriteMemoryBlock( uint address , uint[] values , int offset , int count ); public void WriteMemoryBlock( uint address , uint[] values ) { WriteMemoryBlock( address, values, 0, values.Length ); } //--// public virtual void Cleanup() { m_timer.Change( -1, -1 ); } //--// protected abstract void RunDeviceInner( ref bool fStop ); //--// private static void OnTimer(object state) { JTagConnector pThis = (JTagConnector)state; pThis.m_fStopExecution = true; } // // Access Methods // public abstract uint ProgramCounter { set; } } } ================================================ FILE: Zelig/Zelig/DebugTime/ArmProcessorEmulation/Hosting/JTagCustomer.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // namespace Microsoft.Zelig.Emulation.Hosting { using System; using System.Collections.Generic; using Cfg = Microsoft.Zelig.Configuration.Environment; public abstract class JTagCustomer { // // State // // // Helper Methods // public abstract void Deploy( Emulation.Hosting.AbstractHost owner , Cfg.ProductCategory product , List< Configuration.Environment.ImageSection > image , ProcessorControl.ProgressCallback callback ); //--// protected static uint[] ToUint( byte[] data8 ) { return ToUint( data8, 0, data8.Length ); } protected static uint[] ToUint( byte[] data8 , int offset , int size ) { uint[] data32 = new uint[(size + sizeof(uint) - 1) / sizeof(uint)]; Buffer.BlockCopy( data8, offset, data32, 0, size ); return data32; } // // Access Methods // } } ================================================ FILE: Zelig/Zelig/DebugTime/ArmProcessorEmulation/Hosting/MemoryProvider.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // namespace Microsoft.Zelig.Emulation.Hosting { using System; using Cfg = Microsoft.Zelig.Configuration.Environment; public abstract class MemoryProvider { // // State // AbstractHost m_owner; Cfg.CacheControllerCategory m_cache; // // Constructor Methods // protected MemoryProvider( AbstractHost owner , Cfg.CacheControllerCategory cache ) { m_cache = cache; m_owner = owner; m_owner.RegisterService( typeof(Emulation.Hosting.MemoryProvider), this ); } // // Helper Methods // public void Dispose() { m_owner.UnregisterService( this ); } public bool CanAccess( uint address , uint size ) { address = NormalizeAddress( address ); switch(size) { case 1: return CanAccessUInt8 ( address ); case 2: return CanAccessUInt16( address ); case 4: return CanAccessUInt32( address ); case 8: return CanAccessUInt64( address ); } return false; } //--// public bool GetUInt8( uint address , out byte result ) { address = NormalizeAddress( address ); try { result = ReadUInt8( address ); return true; } catch(Exception) { result = 0; return false; } } public bool GetUInt16( uint address , out ushort result ) { address = NormalizeAddress( address ); try { result = ReadUInt16( address ); return true; } catch(Exception) { result = 0; return false; } } public bool GetUInt32( uint address , out uint result ) { address = NormalizeAddress( address ); try { result = ReadUInt32( address ); return true; } catch(Exception) { result = 0; return false; } } public bool GetUInt64( uint address , out ulong result ) { address = NormalizeAddress( address ); try { result = ReadUInt64( address ); return true; } catch(Exception) { result = 0; return false; } } public bool GetBlock( uint address , int size , uint alignment , out byte[] result ) { address = NormalizeAddress( address ); try { result = ReadBlock( address, size, alignment ); return true; } catch(Exception) { result = null; return false; } } //--// public bool SetUInt8( uint address , byte result ) { address = NormalizeAddress( address ); try { WriteUInt8( address, result ); return true; } catch(Exception) { return false; } } public bool SetUInt16( uint address , ushort result ) { address = NormalizeAddress( address ); try { WriteUInt16( address, result ); return true; } catch(Exception) { return false; } } public bool SetUInt32( uint address , uint result ) { address = NormalizeAddress( address ); try { WriteUInt32( address, result ); return true; } catch(Exception) { return false; } } public bool SetUInt64( uint address , ulong result ) { address = NormalizeAddress( address ); try { WriteUInt64( address, result ); return true; } catch(Exception) { return false; } } public bool SetBlock( uint address , byte[] result , uint alignment ) { address = NormalizeAddress( address ); try { WriteBlock( address, result, alignment ); return true; } catch(Exception) { return false; } } //--// protected virtual uint NormalizeAddress( uint address ) { if(m_cache != null) { address = m_cache.GetUncacheableAddress( address ); } return address; } protected abstract bool CanAccessUInt8 ( uint address ); protected abstract bool CanAccessUInt16( uint address ); protected abstract bool CanAccessUInt32( uint address ); protected abstract bool CanAccessUInt64( uint address ); protected abstract byte ReadUInt8 ( uint address ); protected abstract ushort ReadUInt16( uint address ); protected abstract uint ReadUInt32( uint address ); protected abstract ulong ReadUInt64( uint address ); protected abstract byte[] ReadBlock ( uint address, int size, uint alignment ); protected abstract void WriteUInt8 ( uint address, byte result ); protected abstract void WriteUInt16( uint address, ushort result ); protected abstract void WriteUInt32( uint address, uint result ); protected abstract void WriteUInt64( uint address, ulong result ); protected abstract void WriteBlock ( uint address, byte[] result, uint alignment ); } } ================================================ FILE: Zelig/Zelig/DebugTime/ArmProcessorEmulation/Hosting/MonitorExecution.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // namespace Microsoft.Zelig.Emulation.Hosting { using System; using System.Collections.Generic; public abstract class MonitorExecution { // // Access Methods // public abstract bool MonitorMemory { get; set; } public abstract bool MonitorRegisters { get; set; } public abstract bool MonitorOpcodes { get; set; } public abstract bool MonitorCalls { get; set; } public abstract bool MonitorInterrupts { get; set; } public abstract bool MonitorInterruptDisabling { get; set; } public abstract bool NoSleep { get; set; } } } ================================================ FILE: Zelig/Zelig/DebugTime/ArmProcessorEmulation/Hosting/OutputSink.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // namespace Microsoft.Zelig.Emulation.Hosting { using System; using System.Collections.Generic; public abstract class OutputSink { public abstract void SetOutput( string file ); public abstract void StartOutput(); public abstract void OutputLine( string format , params object[] args ); public abstract void OutputChar( char c ); } } ================================================ FILE: Zelig/Zelig/DebugTime/ArmProcessorEmulation/Hosting/ProcessorControl.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // namespace Microsoft.Zelig.Emulation.Hosting { using System; using System.Collections.Generic; public abstract class ProcessorControl { public enum State { Stopped , Starting , Executing, Stopping , } public delegate void ProgressCallback( string format, params object[] args ); public delegate void StateChangeCallback( State oldState, State newState ); // // State // protected StateChangeCallback m_eventStateChange; private bool m_fLastStopWasForced; // // Helper Methods // public abstract void GetBreakpointCapabilities( out object softBreakpointOpcode , out int maxHardBreakpoints ); public virtual void Shutdown() { m_eventStateChange = null; } public virtual void ResetState( Configuration.Environment.ProductCategory product ) { m_eventStateChange = null; } public abstract void PrepareHardwareModels( Configuration.Environment.ProductCategory product ); public abstract void DeployImage( List< Configuration.Environment.ImageSection > image , ProgressCallback callback ); public abstract void StartPlugIns( List< Type > extraHandlers ); public abstract void StopPlugIns(); public abstract void Execute ( List< Breakpoint > breakpoints ); public abstract void ExecuteStep( List< Breakpoint > breakpoints ); public void Notify( State oldState , State newState ) { switch(newState) { case State.Starting: m_fLastStopWasForced = false; break; case State.Stopping: m_fLastStopWasForced = true; break; } var notify = m_eventStateChange; if(notify != null) { notify( oldState, newState ); } } //--// // // Access Methods // public abstract bool StopExecution { get; set; } public bool LastStopWasForced { get { return m_fLastStopWasForced; } } public event StateChangeCallback NotifyStateChange { add { m_eventStateChange += value; } remove { m_eventStateChange -= value; } } } } ================================================ FILE: Zelig/Zelig/DebugTime/ArmProcessorEmulation/Hosting/ProcessorPerformance.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // namespace Microsoft.Zelig.Emulation.Hosting { using System; using System.Collections.Generic; using IR = Microsoft.Zelig.CodeGeneration.IR; public abstract class ProcessorPerformance { // // Helper Methods // public abstract void SuspendTimingUpdates(); public abstract void ResumeTimingUpdates(); //--// // // Access Methods // public abstract ulong ClockCycles { get; } public abstract ulong WaitStates { get; } } } ================================================ FILE: Zelig/Zelig/DebugTime/ArmProcessorEmulation/Hosting/ProcessorStatus.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // namespace Microsoft.Zelig.Emulation.Hosting { using System; using System.Collections.Generic; using IR = Microsoft.Zelig.CodeGeneration.IR; public abstract class ProcessorStatus { public delegate void TrackExternalProgramFlowChange(); // // State // protected TrackExternalProgramFlowChange m_eventExternalProgramFlowChange; // // Helper Methods // public abstract BinaryBlob GetRegister( IR.Abstractions.RegisterDescriptor reg ); public abstract bool SetRegister( IR.Abstractions.RegisterDescriptor reg , BinaryBlob bb ); public virtual void RaiseExternalProgramFlowChange() { var dlg = m_eventExternalProgramFlowChange; if(dlg != null) { dlg(); } } //--// // // Access Methods // public abstract uint ProgramCounter { get; set; } public abstract uint StackPointer { get; set; } public event TrackExternalProgramFlowChange NotifyOnExternalProgramFlowChange { add { m_eventExternalProgramFlowChange += value; } remove { m_eventExternalProgramFlowChange -= value; } } } } ================================================ FILE: Zelig/Zelig/DebugTime/ArmProcessorEmulation/Hosting/SED15E0Sink.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // namespace Microsoft.Zelig.Emulation.Hosting { using System; using System.Collections.Generic; public abstract class SED15E0Sink { public abstract void NewScreenShot( uint[] buffer, int width, int height ); } } ================================================ FILE: Zelig/Zelig/DebugTime/ArmProcessorEmulation/Hosting/SimulatedDeviceClockTicksTracking.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // namespace Microsoft.Zelig.Emulation.Hosting { using System; using System.Collections.Generic; public abstract class SimulatedDeviceClockTicksTracking : DeviceClockTicksTracking { class FakeTimingStateSmartHandler : IDisposable { // // Helper Methods // public void Dispose() { } } // // State // System.Diagnostics.Stopwatch m_clockTicks; // // Constructor Methods // protected SimulatedDeviceClockTicksTracking() { m_clockTicks = new System.Diagnostics.Stopwatch(); } // // Helper Methods // //--// public override void ResetState() { base.ResetState(); m_clockTicks.Reset(); } public void Start() { m_clockTicks.Start(); } public void Stop() { m_clockTicks.Stop(); } public override bool GetAbsoluteTime( out ulong clockTicks , out ulong nanoseconds ) { clockTicks = 0; nanoseconds = 0; return false; } public override IDisposable SuspendTiming() { return new FakeTimingStateSmartHandler(); } //--// // // Access Methods // public override ulong ClockTicks { get { long clockTicks; lock(this.LockRoot) { clockTicks = m_clockTicks.ElapsedTicks; } return FromPerformanceCounterToClockTicks( clockTicks ); } } } } ================================================ FILE: Zelig/Zelig/DebugTime/ArmProcessorEmulation/Hosting/SimulatorControl.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // namespace Microsoft.Zelig.Emulation.Hosting { using System; using System.Collections.Generic; public abstract class SimulatorControl { public abstract void Wait( TimeSpan tm ); } } ================================================ FILE: Zelig/Zelig/DebugTime/ArmProcessorEmulation/Hosting/TypeSystem.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // namespace Microsoft.Zelig.Emulation.Hosting { public abstract class TypeSystem { public abstract string FetchString( uint address ); } } ================================================ FILE: Zelig/Zelig/DebugTime/ArmProcessorEmulation/Models/Chipset/MM9691LP.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // //#define TRACE_INTERRUPT_WITH_ARMTIMER #define OLLIE_USE_CACHE_PSEUDO_LRU namespace Microsoft.Zelig.Emulation.ArmProcessor.Chipset { using System; using System.Threading; using System.Collections.Generic; using EncDef = Microsoft.Zelig.TargetModel.ArmProcessor.EncodingDefinition; using ElementTypes = Microsoft.Zelig.MetaData.ElementTypes; using Cfg = Microsoft.Zelig.Configuration.Environment; //--// public static partial class MM9691LP { [Simulator.PeripheralRange(Base=0x30000000U,Length=0x0000000CU,ReadLatency=1,WriteLatency=2)] [Simulator.PeripheralRange(Base=0xB0000000U,Length=0x0000000CU,ReadLatency=1,WriteLatency=2)] public class BUSWATCHER : Simulator.Peripheral { public const uint AHB_Abort_Control__ERR = 0x00000001; public const uint AHB_Abort_Control__HWRITE = 0x00000002; public const uint AHB_Abort_Control__HTRANS = 0x0000000C; public const uint AHB_Abort_Control__HSIZE = 0x00000030; public const uint AHB_Abort_Control__HRESP = 0x000000C0; public const uint AHB_Abort_Control__HPROT = 0x00000F00; public const uint AHB_Abort_Control__HBURST = 0x00007000; public const uint AHB_Abort_Control__HMASTLOCK = 0x00008000; public const uint AHB_Abort_Control__HMASTER = 0x000F0000; public const uint AHB_Abort_Enable__ABEN = 0x00000001; //--// [Simulator.Register(Offset=0x00000000U)] public uint AHB_Abort_Address; [Simulator.Register(Offset=0x00000004U)] public uint AHB_Abort_Control; [Simulator.Register(Offset=0x00000008U)] public uint AHB_Abort_Enable { get { return 0; } } [Simulator.Register(Offset=0x00000010U)] public uint AHB_Counter_Enable; [Simulator.Register(Offset=0x00000014U)] public uint AHB_Counter_Restart; [Simulator.Register(Offset=0x00000018U)] public uint AHB_Valid_Count; [Simulator.Register(Offset=0x0000001CU)] public uint AHB_Idle_Count; [Simulator.Register(Offset=0x00000020U)] public uint AHB_Cache_Valid_Count; [Simulator.Register(Offset=0x00000024U)] public uint AHB_NonCache_Count; [Simulator.Register(Offset=0x00000028U)] public uint AHB_Cache_Miss; [Simulator.Register(Offset=0x0000002CU)] public uint AHB_CPU_Idle_Count; } [Simulator.PeripheralRange(Base=0x30010000U,Length=0x00000060U,ReadLatency=1,WriteLatency=2)] [Simulator.PeripheralRange(Base=0xB0010000U,Length=0x00000060U,ReadLatency=1,WriteLatency=2)] public class EBIU : Simulator.Peripheral { public class DEVICE : Simulator.Peripheral { public const uint Control__WS__mask = 0x0000003F; public const int Control__WS__shift = 0; public const uint Control__RCNT__mask = 0x00000300; public const int Control__RCNT__shift = 8; public const uint Control__SZ8 = 0x00001000; public const uint Control__SZ16 = 0x00002000; public const uint Control__SZ32 = 0x00003000; public const uint Control__RDY = 0x00008000; public const uint Control__WD = 0x00010000; public const uint Control__BRD = 0x00020000; public const uint Control__BFEN = 0x02000000; public const uint Control__mask = 0x0203B73F; public static uint Control__WS__set ( uint w ) { return (w << Control__WS__shift ) & Control__WS__mask ; } public static uint Control__RCNT__set( uint w ) { return (w << Control__RCNT__shift) & Control__RCNT__mask; } //--// [Simulator.LinkToContainer() ] public EBIU Parent; [Simulator.Register(Offset=0x00000000U)] public uint LowAddress; [Simulator.Register(Offset=0x00000004U)] public uint HighAddress; [Simulator.Register(Offset=0x00000008U)] public uint Control; } [Simulator.Register(Offset=0x00000000U,Size=0x00000010U)] public DEVICE Device0; [Simulator.Register(Offset=0x00000010U,Size=0x00000010U)] public DEVICE Device1; [Simulator.Register(Offset=0x00000020U,Size=0x00000010U)] public DEVICE Device2; [Simulator.Register(Offset=0x00000030U,Size=0x00000010U)] public DEVICE Device3; [Simulator.Register(Offset=0x00000040U,Size=0x00000010U)] public DEVICE Device4; [Simulator.Register(Offset=0x00000050U,Size=0x00000010U)] public DEVICE Device5; } [Simulator.PeripheralRange(Base=0x30020000U,Length=0x00000114U,ReadLatency=1,WriteLatency=2)] [Simulator.PeripheralRange(Base=0xB0020000U,Length=0x00000114U,ReadLatency=1,WriteLatency=2)] public class DMAC : Simulator.Peripheral { // // static const UINT32 c_DMAC_ENABLE 0x00000001 // static const UINT32 c_DMAC_ERROR 0x00000002 // static const UINT32 c_DMAC_DONE 0x00000004 // static const UINT32 c_DMAC_HALFDONE 0x00000008 // // static const UINT32 c_DMAC_SRC_INCR_UNCH 0x00000000 // static const UINT32 c_DMAC_SRC_INCR_1 0x00000010 // static const UINT32 c_DMAC_SRC_INCR_2 0x00000020 // static const UINT32 c_DMAC_SRC_INCR_4 0x00000030 // // static const UINT32 c_DMAC_SRC_XFER_SZ_1 0x00000000 // static const UINT32 c_DMAC_SRC_XFER_SZ_2 0x00000040 // static const UINT32 c_DMAC_SRC_XFER_SZ_4 0x00000080 // static const UINT32 c_DMAC_SRC_XFER_SZ_RES 0x000000C0 // // static const UINT32 c_DMAC_SRC_BURST_SING 0x00000000 // static const UINT32 c_DMAC_SRC_BURST_I2 0x00000100 // static const UINT32 c_DMAC_SRC_BURST_W4 0x00000200 // static const UINT32 c_DMAC_SRC_BURST_I4 0x00000300 // static const UINT32 c_DMAC_SRC_BURST_W8 0x00000400 // static const UINT32 c_DMAC_SRC_BURST_I8 0x00000500 // static const UINT32 c_DMAC_SRC_BURST_W16 0x00000600 // static const UINT32 c_DMAC_SRC_BURST_I16 0x00000700 // // static const UINT32 c_DMAC_DMA_MODE_NORM 0x00000000 // static const UINT32 c_DMAC_DMA_MODE_CONT 0x00000800 // static const UINT32 c_DMAC_DMA_MODE_LINK 0x00001000 // static const UINT32 c_DMAC_DMA_MODE_RES 0x00001800 // // static const UINT32 c_DMAC_SRC_BPR_1 0x00000000 // static const UINT32 c_DMAC_SRC_BPR_2 0x00002000 // static const UINT32 c_DMAC_SRC_BPR_4 0x00004000 // static const UINT32 c_DMAC_SRC_BPR_8 0x00006000 // static const UINT32 c_DMAC_SRC_BPR_16 0x00008000 // static const UINT32 c_DMAC_SRC_BPR_32 0x0000A000 // static const UINT32 c_DMAC_SRC_BPR_64 0x0000C000 // static const UINT32 c_DMAC_SRC_BPR_128 0x0000E000 // // static const UINT32 c_DMAC_DEST_INC_UNCH 0x00000000 // static const UINT32 c_DMAC_DEST_INC_1 0x00010000 // static const UINT32 c_DMAC_DEST_INC_2 0x00020000 // static const UINT32 c_DMAC_DEST_INC_4 0x00030000 // // static const UINT32 c_DMAC_DEST_XFER_SZ_1 0x00000000 // static const UINT32 c_DMAC_DEST_XFER_SZ_2 0x00040000 // static const UINT32 c_DMAC_DEST_XFER_SZ_4 0x00080000 // static const UINT32 c_DMAC_DEST_XFER_RES 0x000C0000 // // static const UINT32 c_DMAC_DEST_BURST_SING 0x00000000 // static const UINT32 c_DMAC_DEST_BURST_I2 0x00100000 // static const UINT32 c_DMAC_DEST_BURST_W4 0x00200000 // static const UINT32 c_DMAC_DEST_BURST_I4 0x00300000 // static const UINT32 c_DMAC_DEST_BURST_W8 0x00400000 // static const UINT32 c_DMAC_DEST_BURST_I8 0x00500000 // static const UINT32 c_DMAC_DEST_BURST_W16 0x00600000 // static const UINT32 c_DMAC_DEST_BURST_I16 0x00700000 // // static const UINT32 c_DMAC_DONE_2_SRC 0x00000000 // static const UINT32 c_DMAC_DONE_2_DEST 0x00800000 // // static const UINT32 c_DMAC_DEV_SEL_MASK 0x07000000 // static const UINT32 c_DMAC_DEV_SEL_SW 0x00000000 // static const UINT32 c_DMAC_DEV_SEL_USB 0x01000000 // static const UINT32 c_DMAC_DEV_SEL_MW_TX 0x02000000 // static const UINT32 c_DMAC_DEV_SEL_MW_RX 0x03000000 // static const UINT32 c_DMAC_DEV_SEL_SER1_TRX 0x04000000 // CHAN 7-4=RX CHAN 3-0=TX // static const UINT32 c_DMAC_DEV_SEL_SER2_TRX 0x05000000 // CHAN 7-4=RX CHAN 3-0=TX // static const UINT32 c_DMAC_DEV_SEL_VITERBI 0x06000000 // static const UINT32 c_DMAC_DEV_SEL_ACRTAN 0x07000000 // // static const UINT32 c_DMAC_IDL_CYCLE_INDEX 27 // static const UINT32 c_DMAC_IDL_CYCLE_MASK 0xf8000000 // public class CHANNEL : Simulator.Peripheral { [Simulator.LinkToContainer() ] public DMAC Parent; [Simulator.Register(Offset=0x00000000U)] public uint SourceStartAddress; [Simulator.Register(Offset=0x00000004U)] public uint DestinationStartAddress; [Simulator.Register(Offset=0x00000008U)] public uint SourceBeat; [Simulator.Register(Offset=0x0000000CU)] public uint ControlWord; } public class CHANNEL_STATE : Simulator.Peripheral { [Simulator.LinkToContainer() ] public DMAC Parent; [Simulator.Register(Offset=0x00000000U)] public uint SourceCurrentAddress; // read only [Simulator.Register(Offset=0x00000004U)] public uint DestinationCurrentAddress; // read only [Simulator.Register(Offset=0x00000008U)] public uint SourceCurrentBeatCount; // read only } //--// [Simulator.Register(Offset=0x00000000U,Size=0x00000010U,Instances=8)] public CHANNEL[] Channel; [Simulator.Register(Offset=0x00000080U,Size=0x00000010U,Instances=8)] public CHANNEL_STATE[] ChannelState; [Simulator.Register(Offset=0x00000100U )] public uint InterruptStatus; [Simulator.Register(Offset=0x00000104U )] public uint InterruptRawStatus; [Simulator.Register(Offset=0x00000108U )] public uint InterruptEnable; [Simulator.Register(Offset=0x0000010CU )] public uint InterruptEnableClear; [Simulator.Register(Offset=0x00000110U )] public uint InternalDMACTestMode; [Simulator.Register(Offset=0x00000114U )] public uint InternalTestRequest; } [Simulator.PeripheralRange(Base=0x30030000U,Length=0x00008008U,ReadLatency=1,WriteLatency=2)] [Simulator.PeripheralRange(Base=0xB0030000U,Length=0x00008008U,ReadLatency=1,WriteLatency=2)] public class VITERBI : Simulator.Peripheral { //// //--// //// //// CPU_MAC_INT16_ON_32 InputData[c_Input_Array_Elements]; // 0x0000 +0x0A00 //// /*************/ UINT32 Padding1 [ 128]; // 0x0A00 +0x0200 //// //// CPU_MAC_UINT16_ON_32 OutputData[c_Output_Array_Elements]; // 0x0C00 +0x0050 //// /*************/ UINT32 Padding2 [ 236]; // 0x0C50 +0x03B0 //// //// CPU_MAC_UINT16_ON_32 PathMetrics[c_PathMetrics_Array_Elements]; // 0x1000 +0x0800 //// /*************/ UINT32 Padding3 [ 512]; // 0x1800 +0x0800 //// //// CPU_MAC_UINT16_ON_32 TracebackArray[c_Traceback_Array_Elements]; // 0x2000 +0x5000 //// /*************/ UINT32 Padding4 [ 1024]; // 0x7000 +0x1000 //// //// /****/ volatile UINT32 RamControl; // 0x8000 +0x0004 //// static const UINT32 RamControl__CPU = 0x00000000; //// static const UINT32 RamControl__VITERBI = 0x00000001; //// //// /****/ volatile UINT32 Control; // 0x8004 +0x0004 //// static const UINT32 Control__DONE_ACS = 0x00000001; //// static const UINT32 Control__DONE_TRC = 0x00000002; //// static const UINT32 Control__IEN_ACS = 0x00000004; //// static const UINT32 Control__IEN_TRC = 0x00000008; //// static const UINT32 Control__DEN_ACS = 0x00000010; //// static const UINT32 Control__DEN_TRC = 0x00000020; //// static const UINT32 Control__GO_ACS = 0x00000040; //// static const UINT32 Control__GO_TRC = 0x00000080; //// static const UINT32 Control__GO_BOTH = 0x00000100; } [Simulator.PeripheralRange(Base=0x30040000U,Length=0x00008020U,ReadLatency=1,WriteLatency=2)] [Simulator.PeripheralRange(Base=0xB0040000U,Length=0x00008020U,ReadLatency=1,WriteLatency=2)] public class FILTERARCTAN : Simulator.Peripheral { //// static const UINT32 c_Base = 0xB0040000; //// //// static const UINT32 c_Arctan_Block_Size = 128; //// static const UINT32 c_Filter_Coefficient_Size = 512; //// static const UINT32 c_Filter_Input_Size = 2048; //// static const UINT32 c_Filter_Output_Size = 1024; //// //// static const UINT32 c_Arctan_Max = c_Arctan_Block_Size; //// static const UINT32 c_Complex_Max = c_Filter_Coefficient_Size / 2; //// static const UINT32 c_Vector_Max = c_Filter_Coefficient_Size; //// static const UINT32 c_Filter_Max = c_Filter_Output_Size; //// static const UINT32 c_Filter_Coefficient_Max = 31; //// //// //--// //// //// CPU_MAC_IQPAIR_ON_64 Arctan_InputData [c_Arctan_Block_Size ]; //// CPU_MAC_ANGLEMAG_ON_64 Arctan_OutputData [c_Arctan_Block_Size ]; //// CPU_MAC_INT16_ON_32 Filter_Coefficients[c_Filter_Coefficient_Size]; //// CPU_MAC_INT16_ON_32 Filter_InputData [c_Filter_Input_Size ]; //// CPU_MAC_INT32_ON_64 Filter_OutputData [c_Filter_Output_Size ]; //// /*************/ UINT32 Padding1 [ 3072]; //// //// /****/ volatile UINT32 RPT_CNT; //// static const UINT32 RPT_CNT__mask = 0x0000007F; //// //// /****/ volatile UINT32 reserved; //// //// /****/ volatile UINT32 NCOEF; //// static const UINT32 NCOEF__mask = 0x000001FF; //// static const UINT32 NCOEF__shift = 0; //// static const UINT32 NCOEF__CMPLX = 0x00000200; //// static const UINT32 NCOEF__LOW_N = 0x00000400; //// //// __inline static UINT32 NCOEF__set( UINT32 w ) { return (w << NCOEF__shift) & NCOEF__mask; } //// //// /****/ volatile UINT32 NOUT; //// static const UINT32 NOUT__mask = 0x000007FF; //// static const UINT32 NOUT__shift = 0; //// //// __inline static UINT32 NOUT__set( UINT32 w ) { return (w << NOUT__shift) & NOUT__mask; } //// //// /****/ volatile UINT32 IN_PTR; //// static const UINT32 IN_PTR__mask = 0x000007FF; //// static const UINT32 IN_PTR__shift = 0; //// //// __inline static UINT32 IN_PTR__set( UINT32 w ) { return (w << IN_PTR__shift) & IN_PTR__mask; } //// //// /****/ volatile UINT32 OUT_PTR; //// static const UINT32 OUT_PTR__mask = 0x000007FF; //// static const UINT32 OUT_PTR__shift = 0; //// //// __inline static UINT32 OUT_PTR__set( UINT32 w ) { return (w << OUT_PTR__shift) & OUT_PTR__mask; } //// //// /****/ volatile UINT32 RAM_CONT; //// static const UINT32 RAM_CONT__CPU = 0x00000000; //// static const UINT32 RAM_CONT__MAC = 0x00000001; //// //// /****/ volatile UINT32 CONT; //// static const UINT32 CONT__DONE_ATN = 0x00000001; //// static const UINT32 CONT__DONE_FILT = 0x00000002; //// static const UINT32 CONT__IEN_ATN = 0x00000004; //// static const UINT32 CONT__IEN_FILT = 0x00000008; //// static const UINT32 CONT__DEN_ATN = 0x00000010; //// static const UINT32 CONT__DEN_FILT = 0x00000020; //// static const UINT32 CONT__GO_ATN = 0x00000040; //// static const UINT32 CONT__GO_FILT = 0x00000080; } [Simulator.PeripheralRange(Base=0x38000000U,Length=0x00000210U,ReadLatency=1,WriteLatency=2)] public class INTC : Simulator.Peripheral { public const int IRQ_INDEX_unused0 = 0; public const int IRQ_INDEX_Programmed_Interrupt = 1; public const int IRQ_INDEX_Debug_Channel_Comms_Rx = 2; public const int IRQ_INDEX_Debug_Channel_Comms_Tx = 3; public const int IRQ_INDEX_ARM_Timer_1 = 4; public const int IRQ_INDEX_ARM_Timer_2 = 5; public const int IRQ_INDEX_Versatile_Timer_1 = 6; public const int IRQ_INDEX_Versatile_Timer_2 = 7; public const int IRQ_INDEX_Versatile_Timer_3 = 8; public const int IRQ_INDEX_Versatile_Timer_4 = 9; public const int IRQ_INDEX_Real_Time_Clock = 10; public const int IRQ_INDEX_USB = 11; public const int IRQ_INDEX_USART0_Tx = 12; public const int IRQ_INDEX_USART0_Rx = 13; public const int IRQ_INDEX_USART1_Tx = 14; public const int IRQ_INDEX_USART1_Rx = 15; public const int IRQ_INDEX_GPIO_00_07 = 16; public const int IRQ_INDEX_GPIO_08_15 = 17; public const int IRQ_INDEX_GPIO_16_23 = 18; public const int IRQ_INDEX_GPIO_24_31 = 19; public const int IRQ_INDEX_GPIO_32_39 = 20; public const int IRQ_INDEX_Edge_Detected_Interrupts = 21; public const int IRQ_INDEX_MicroWire = 22; public const int IRQ_INDEX_Watchdog = 23; public const int IRQ_INDEX_USART0_Flow_Control = 24; public const int IRQ_INDEX_USART1_Flow_Control = 25; public const int IRQ_INDEX_unused1 = 26; public const int IRQ_INDEX_APC = 27; public const int IRQ_INDEX_DMA_ALL_Channels = 28; public const int IRQ_INDEX_Viterbi_Processor = 29; public const int IRQ_INDEX_Filter_Processor = 30; public const int IRQ_INDEX_AHB_Write_Error = 31; public class IRQ : Simulator.Peripheral { [Simulator.LinkToContainer] public INTC Parent; [Simulator.Register(Offset=0x00000000U)] public uint Status { get { return m_state_EnableSet & this.RawStatus; } } [Simulator.Register(Offset=0x00000004U)] public uint RawStatus { get { uint rawStatus; if((this.SourceSelect & 1) == 0) { rawStatus = this.Parent.m_inputStatus | this.Soft; } else { rawStatus = this.TestSource; } return rawStatus; } } [Simulator.Register(Offset=0x00000008U)] public uint EnableSet { get { return m_state_EnableSet; } set { m_state_EnableSet |= value; this.Parent.Evaluate(); } } [Simulator.Register(Offset=0x0000000CU)] public uint EnableClear { get { return m_state_EnableSet; } set { m_state_EnableSet &= ~value; this.Parent.Evaluate(); } } [Simulator.Register(Offset=0x00000010U)] public uint Soft { get { return m_state_Soft; } set { m_state_Soft = value & (1U << IRQ_INDEX_Programmed_Interrupt); this.Parent.Evaluate(); } } [Simulator.Register(Offset=0x00000014U)] public uint TestSource { get { return m_state_TestSource; } set { m_state_TestSource = value; this.Parent.Evaluate(); } } [Simulator.Register(Offset=0x00000018U)] public uint SourceSelect { get { return m_state_SourceSelect; } set { m_state_SourceSelect = (value & 1); this.Parent.Evaluate(); } } //--// uint m_state_EnableSet; uint m_state_Soft; uint m_state_TestSource; uint m_state_SourceSelect; } public class FIRQ : Simulator.Peripheral { [Simulator.LinkToContainer] public INTC Parent; [Simulator.Register(Offset=0x00000000U)] public uint Status { get { return this.EnableSet & this.RawStatus; } } [Simulator.Register(Offset=0x00000004U)] public uint RawStatus { get { return (this.Parent.m_inputStatus >> (int)this.Select) & 1; } } [Simulator.Register(Offset=0x00000008U)] public uint EnableSet { get { return m_state_EnableSet; } set { m_state_EnableSet |= (value & 1); this.Parent.Evaluate(); } } [Simulator.Register(Offset=0x0000000CU)] public uint EnableClear { get { return m_state_EnableSet; } set { m_state_EnableSet &= ~(value & 1); this.Parent.Evaluate(); } } [Simulator.Register(Offset=0x00000014U)] public uint TestSource; [Simulator.Register(Offset=0x00000018U)] public uint SourceSelect; [Simulator.Register(Offset=0x0000001CU)] public uint Select { get { return m_state_Select; } set { m_state_Select = (value & 0x1F); this.Parent.Evaluate(); } } //--// uint m_state_EnableSet; uint m_state_Select; } [Simulator.Register(Offset=0x00000000U,Size=0x00000020U)] public IRQ Irq; [Simulator.Register(Offset=0x00000020U) ] public uint INTOUT_L_EnableSet; [Simulator.Register(Offset=0x00000024U) ] public uint INTOUT_L_EnableClear; [Simulator.Register(Offset=0x00000100U,Size=0x00000020U)] public FIRQ Fiq; [Simulator.Register(Offset=0x00000200U) ] public uint EdgeStatus; [Simulator.Register(Offset=0x00000204U) ] public uint EdgeRawStatus; [Simulator.Register(Offset=0x00000208U) ] public uint EdgeEnable; [Simulator.Register(Offset=0x0000020CU) ] public uint EdgeEnableClear; [Simulator.Register(Offset=0x00000210U) ] public uint EdgeClear; private uint m_inputStatus = 0; //--// public void Set( int index ) { uint oldStatus = m_inputStatus; m_inputStatus |= 1U << index; if(oldStatus != m_inputStatus) { Evaluate(); } } public void Reset( int index ) { uint oldStatus = m_inputStatus; m_inputStatus &= ~(1U << index); if(oldStatus != m_inputStatus) { Evaluate(); } } public void Evaluate() { m_owner.SetIrqStatus( (Irq.Status != 0) ); m_owner.SetFiqStatus( (Fiq.Status != 0) ); } } [Simulator.PeripheralRange(Base=0x38010000U,Length=0x0000005CU,ReadLatency=1,WriteLatency=2)] public class REMAP_PAUSE : Simulator.Peripheral { public const uint ResetStatus__POR = 0x00000001; [Simulator.Register(Offset=0x00000000U)] public uint Pause { set { m_owner.SpinUntilInterrupts(); } } [Simulator.Register(Offset=0x00000000U)] public uint Pause_CPU_ONLY; [Simulator.Register(Offset=0x00000010U)] public uint Identification = 0x4E969101; [Simulator.Register(Offset=0x00000020U)] public uint ClearResetMap { set { // // Map RAM to 0x00000000. // Simulator.AddressSpaceHandler hnd = m_owner.FindMemoryAtAddress( 0x08000000u ); if(hnd != null) { hnd.LinkAtAddress( 0 ); } } } [Simulator.Register(Offset=0x00000030U)] public uint ResetStatus; [Simulator.Register(Offset=0x00000034U)] public uint ResetStatusClear; [Simulator.Register(Offset=0x00000040U)] public uint SystemConfiguration; [Simulator.Register(Offset=0x00000050U)] public uint Cache_Enable { set { CacheMemoryHandler cache; m_owner.FindMemory( out cache ); if(cache != null) { cache.Enabled = (value != 0); } } } [Simulator.Register(Offset=0x00000054U)] public uint Cache_Tags_Reset { set { CacheMemoryHandler cache; m_owner.FindMemory( out cache ); if(cache != null) { cache.ResettingTags = (value == 0); } } } [Simulator.Register(Offset=0x00000058U)] public uint Cache_Flush_Enable { set { CacheMemoryHandler cache; m_owner.FindMemory( out cache ); if(cache != null) { cache.FlushEnabled = (value != 0); } } } //--// public override void OnConnected() { base.OnConnected(); // // Map FLASH to 0x00000000. // Simulator.AddressSpaceHandler hnd = m_owner.FindMemoryAtAddress( 0x10000000u ); if(hnd != null) { hnd.LinkAtAddress( 0 ); } } } public abstract class ARMTIMERx : Simulator.Peripheral { public const byte Control__PRESCALE_1 = 0x00; public const byte Control__PRESCALE_16 = 0x04; public const byte Control__PRESCALE_256 = 0x08; public const byte Control__MODE_FREE = 0x00; public const byte Control__MODE_PERIODIC = 0x40; public const byte Control__MODE_ENABLE = 0x80; [Simulator.Register(Offset=0x00000000U)] public ushort Load; [Simulator.Register(Offset=0x00000004U)] public ushort Value { get { #if TRACE_INTERRUPT_WITH_ARMTIMER Hosting.OutputSink sink; m_owner.GetHostingService( out sink ); if(sink != null) { sink.OutputLine( "" ); sink.OutputLine( "" ); sink.OutputLine( "ARMTIMER read at {0}", m_owner.ClockTicks ); sink.OutputLine( "" ); fActive = !fActive; if(fActive) { start = m_owner.ClockTicks; } else { sink.OutputLine( "Time: {0}", m_owner.ClockTicks - start ); sink.OutputLine( "" ); } } //// m_owner.MonitorOpcodes = !m_owner.MonitorOpcodes; //// m_owner.MonitorRegisters = !m_owner.MonitorRegisters; m_owner.MonitorCalls = !m_owner.MonitorCalls; #endif return (ushort)(0 - m_owner.ClockTicks); } } [Simulator.Register(Offset=0x00000008U)] public byte Control; [Simulator.Register(Offset=0x0000000CU)] public ushort Clear; #if TRACE_INTERRUPT_WITH_ARMTIMER bool fActive; ulong start; #endif } [Simulator.PeripheralRange(Base=0x38020000U,Length=0x00000020U,ReadLatency=1,WriteLatency=2)] public class ARMTIMER0 : ARMTIMERx { } [Simulator.PeripheralRange(Base=0x38020020U,Length=0x00000020U,ReadLatency=1,WriteLatency=2)] public class ARMTIMER1 : ARMTIMERx { } [Simulator.PeripheralRange(Base=0x38030000U,Length=0x00000050U,ReadLatency=1,WriteLatency=2)] public class VTU32 : Simulator.Peripheral { public class IO_CONTROL : Simulator.Peripheral { public const uint CxyEDG_000 = 0x00000000; public const uint CxyEDG_001 = 0x00000001; public const uint CxyEDG_010 = 0x00000002; public const uint CxyEDG_011 = 0x00000003; public const uint CxyEDG_100 = 0x00000004; public const uint CxyEDG_101 = 0x00000005; public const uint CxyEDG_110 = 0x00000006; public const uint CxyEDG_111 = 0x00000007; public const uint PxyPOL_RESET = 0x00000000; public const uint PxyPOL_SET = 0x00000008; [Simulator.LinkToContainer() ] public VTU32 Parent; [Simulator.Register(Offset=0x00000000U)] public uint Value; //--// // this puts the mode bits M for the chosen timer T (0-1), A/B (0-1) of a pair into the correct nibble/byte public static uint Set( uint T , uint A , uint M ) { return M << (int)(A*4 + T*8); } public static uint Get( uint T , uint A , uint M ) { return (M >> (int)(A*4 + T*8)) & 0x000F; } //--// internal int FindChannel() { return Array.IndexOf( this.Parent.IOControl, this ); } } public class CHANNEL_PAIR : Simulator.Peripheral { public class CHANNEL : Simulator.Peripheral { [Simulator.LinkToContainer() ] public CHANNEL_PAIR Parent; [Simulator.Register(Offset=0x00000000U)] public uint Counter { get { return GetCurrentCounter(); } set { m_state_Counter = value; } } [Simulator.Register(Offset=0x00000004U)] public uint PeriodCapture; [Simulator.Register(Offset=0x00000008U)] public uint DutyCycleCapture; internal ulong m_base; uint m_state_Counter; //--// //--// internal uint GetCurrentCounter() { ulong ticks = m_owner.ClockTicks - m_base; return m_state_Counter + (uint)(ticks * GetRatio()); } internal double GetRatio() { int idxPair = FindPairChannel(); int idxChn = FindChannel (); VTU32 vtu = this.Parent.Parent; uint mode = VTU32.ModeControl__get( (uint)(idxChn * 2 + idxPair), vtu.ModeControl ); switch(mode & VTU32.ModeControl__TMODx_MASK) { case VTU32.ModeControl__TMODx_LOW_POWER: break; case VTU32.ModeControl__TMODx_DUAL_PWM16: break; case VTU32.ModeControl__TMODx_PWM32: if((mode & VTU32.ModeControl__TxARUN) != 0) { return 1.0 / ((vtu.ChannelPair[idxChn].ClockPrescalar & 0xFF) + 1); } break; case VTU32.ModeControl__TMODx_CAPTURE: break; } return 0; } internal void Start() { m_base = m_owner.ClockTicks; } internal void Stop() { this.Counter = GetCurrentCounter(); } internal int FindPairChannel() { return Array.IndexOf( this.Parent.Channel, this ); } internal int FindChannel() { return this.Parent.FindChannel(); } } [Simulator.LinkToContainer() ] public VTU32 Parent; [Simulator.Register(Offset=0x00000000U)] public uint ClockPrescalar; [Simulator.Register(Offset=0x00000004U,Size=0x0CU,Instances=2)] public CHANNEL[] Channel; //--// public uint ClockPrescalar__get( uint T ) { return (ClockPrescalar >> (int)(T*8)) & 0x00FF; } public void ClockPrescalar__set( uint T , uint P ) { uint val = ClockPrescalar; val &= ~( 0x000000FFu << (int)(T*8)); val |= ((P & 0x000000FFu) << (int)(T*8)); ClockPrescalar = val; } //--// internal int FindChannel() { return Array.IndexOf( this.Parent.ChannelPair, this ); } } //--// public const uint c_TIO1A = GPIO.c_Pin_20; public const uint c_TIO2A = GPIO.c_Pin_21; public const uint c_TIO3A = GPIO.c_Pin_22; public const uint c_TIO4A = GPIO.c_Pin_23; public const uint c_TIO1B = GPIO.c_Pin_05; public const uint c_TIO2B = GPIO.c_Pin_06; public const uint c_TIO3B = GPIO.c_Pin_13; public const uint c_TIO4B = GPIO.c_Pin_14; //--// public const uint ModeControl__TxARUN = 0x00000001; public const uint ModeControl__TxBRUN = 0x00000002; public const uint ModeControl__TMODx_LOW_POWER = 0x00000000; public const uint ModeControl__TMODx_DUAL_PWM16 = 0x00000004; public const uint ModeControl__TMODx_PWM32 = 0x00000008; public const uint ModeControl__TMODx_CAPTURE = 0x0000000C; public const uint ModeControl__TMODx_MASK = 0x0000000C; public const uint Interrupt__Ix_None = 0x00000000; public const uint Interrupt__Ix_1 = 0x00000001; public const uint Interrupt__Ix_2 = 0x00000002; public const uint Interrupt__Ix_3 = 0x00000004; public const uint Interrupt__Ix_4 = 0x00000008; public const uint Interrupt__Ix_ALL = (Interrupt__Ix_1 | Interrupt__Ix_2 | Interrupt__Ix_3 | Interrupt__Ix_4); public const uint ExternalClockSelectRegister__CK1 = 0x00000001; public const uint ExternalClockSelectRegister__CK2 = 0x00000002; public const uint ExternalClockSelectRegister__CK3 = 0x00000004; public const uint ExternalClockSelectRegister__CK4 = 0x00000008; //--// [Simulator.Register(Offset=0x00000000U)] public uint ModeControl { get { return m_state_ModeControl; } set { for(uint timer = 0; timer < 4; timer++) { uint oldMode = ModeControl__get( timer, this.ModeControl ); uint newMode = ModeControl__get( timer, value ); if(oldMode != newMode) { switch(newMode & ModeControl__TMODx_MASK) { case ModeControl__TMODx_LOW_POWER: break; case ModeControl__TMODx_DUAL_PWM16: break; case ModeControl__TMODx_PWM32: CHANNEL_PAIR.CHANNEL chn = ChannelPair[timer/2].Channel[timer%2]; if((newMode & ModeControl__TxARUN) != 0) { chn.Start(); } else { chn.Stop(); } break; case ModeControl__TMODx_CAPTURE: break; } } } m_state_ModeControl = value; } } [Simulator.Register(Offset=0x00000004U,Size=0x04U,Instances=2)] public IO_CONTROL[] IOControl; [Simulator.Register(Offset=0x0000000CU)] public uint InterruptControl; [Simulator.Register(Offset=0x00000010U)] public uint InterruptPending { get { return 0; } } [Simulator.Register(Offset=0x00000014U,Size=0x1CU,Instances=2)] public CHANNEL_PAIR[] ChannelPair; [Simulator.Register(Offset=0x0000004CU)] public uint ExternalClockSelectRegister; //--// uint m_state_ModeControl; //--// // this puts the mode bits M for the chosen timer T (0-3) into the correct nibble public static uint ModeControl__set( uint T , uint M ) { return M << (int)(T*4); } public static uint ModeControl__get( uint T , uint M ) { return (M >> (int)(T*4)) & 0x000F; } // this puts the INT bits I for the chosen timer T (0-3) into the correct nibble public static uint Interrupt__set( uint T , uint I ) { return I << (int)(T*4); } public static uint Interrupt__get( uint T , uint I ) { return (I >> (int)(T*4)) & 0x000F; } } public abstract class USARTx : Simulator.Peripheral, Hosting.IAsynchronousSerialInterface { //// static const UINT32 SER1_CLKX = MM9637A_GPIO::c_Pin_00; //// static const UINT32 SER1_TDX = MM9637A_GPIO::c_Pin_01; //// static const UINT32 SER1_RDX = MM9637A_GPIO::c_Pin_02; //// static const UINT32 SER1_RTS = MM9637A_GPIO::c_Pin_03; //// static const UINT32 SER1_CTS = MM9637A_GPIO::c_Pin_04; //// static const UINT32 SER2_CLKX = MM9637A_GPIO::c_Pin_08; //// static const UINT32 SER2_TDX = MM9637A_GPIO::c_Pin_09; //// static const UINT32 SER2_RDX = MM9637A_GPIO::c_Pin_10; //// static const UINT32 SER2_RTS = MM9637A_GPIO::c_Pin_11; //// static const UINT32 SER2_CTS = MM9637A_GPIO::c_Pin_12; //--// public const byte UnICTRL__TBE = 0x01; public const byte UnICTRL__RBF = 0x02; public const byte UnICTRL__DCTS = 0x04; public const byte UnICTRL__CTS = 0x08; public const byte UnICTRL__EFCI = 0x10; public const byte UnICTRL__ETI = 0x20; public const byte UnICTRL__ERI = 0x40; public const byte UnICTRL__EEI = 0x80; public const byte UnICTRL__mask = (UnICTRL__EFCI | UnICTRL__ETI | UnICTRL__ERI | UnICTRL__EEI); public const byte UnSTAT__PE = 0x01; public const byte UnSTAT__FE = 0x02; public const byte UnSTAT__DOE = 0x04; public const byte UnSTAT__ERR = 0x08; public const byte UnSTAT__BKD = 0x10; public const byte UnSTAT__RB9 = 0x20; public const byte UnSTAT__XMIP = 0x40; public const byte UnFRS__CHAR_8 = 0x00; public const byte UnFRS__CHAR_7 = 0x01; public const byte UnFRS__CHAR_9 = 0x02; public const byte UnFRS__CHAR_9_LOOPBACK = 0x03; public const byte UnFRS__STP_1 = 0x00; public const byte UnFRS__STP_2 = 0x04; public const byte UnFRS__XB9_0 = 0x00; public const byte UnFRS__XB9_1 = 0x08; public const byte UnFRS__PSEL_ODD = 0x00; public const byte UnFRS__PSEL_EVEN = 0x10; public const byte UnFRS__PSEL_MARK = 0x20; public const byte UnFRS__PSEL_SPACE = 0x30; public const byte UnFRS__PEN_DISABLED = 0x00; public const byte UnFRS__PEN_ENABLED = 0x40; public static int UnFRS__LEN_CHAR__get( byte a ) { switch(a & 0x03) { case UnFRS__CHAR_7: return 7; case UnFRS__CHAR_8: return 8; default: return 9; } } public static int UnFRS__LEN_STOPS__get( byte a ) { return ((a & UnFRS__STP_2) != 0) ? 2 : 1; } public static int UnFRS__LEN_PARITY__get( byte a ) { return ((a & UnFRS__PEN_ENABLED) != 0) ? 1 : 0; } public const byte UnMDSL1__MOD = 0x01; public const byte UnMDSL1__ATN = 0x02; public const byte UnMDSL1__BRK = 0x04; public const byte UnMDSL1__CKS = 0x08; public const byte UnMDSL1__ETD = 0x10; public const byte UnMDSL1__ERD = 0x20; public const byte UnMDSL1__FCE = 0x40; public const byte UnMDSL1__RTS = 0x80; public static int UnBAUD__get ( byte a ) { return a ; } public static int UnPSR__DIV__get( byte a ) { return ((a << 8) & 0x0700); } public static int UnPSR__PSC__get( byte a ) { return ((a >> 3) & 0x001F); } public const byte UnOVSR__7 = 0x07; public const byte UnOVSR__8 = 0x08; public const byte UnOVSR__9 = 0x09; public const byte UnOVSR__10 = 0x0A; public const byte UnOVSR__11 = 0x0B; public const byte UnOVSR__12 = 0x0C; public const byte UnOVSR__13 = 0x0D; public const byte UnOVSR__14 = 0x0E; public const byte UnOVSR__15 = 0x0F; public const byte UnOVSR__16 = 0x00; public static int UnOVSR__get( byte a ) { return a == UnOVSR__16 ? 16 : (int)a; } public const byte UnMDSL2__SMD = 0x01; //--// [Simulator.LinkToPeripheral() ] public INTC InterruptController; [Simulator.LinkToPeripheral() ] public CMU ClockController; [Simulator.Register(Offset=0x00000000U)] public byte UnTBUF { get { if(this.IsClockEnabled) { return m_txBuffer; } else { return 0; } } set { if(this.IsClockEnabled) { if(m_owner.AreTimingUpdatesEnabled) { m_txBuffer = value; if(this.TransmitBufferEmpty) { this.TransmitBufferEmpty = false; } } } } } [Simulator.Register(Offset=0x00000004U)] public byte UnRBUF { get { if(this.IsClockEnabled) { byte res = m_rxBuffer; if(this.ReadBufferFull) { this.ReadBufferFull = false; } return res; } else { return 0; } } } [Simulator.Register(Offset=0x00000008U)] public byte UnICTRL { get { if(this.IsClockEnabled) { return m_state_UnICTRL; } else { return 0; } } set { if(this.IsClockEnabled) { if(m_owner.AreTimingUpdatesEnabled) { MaskedUpdateBitField( ref m_state_UnICTRL, value, UnICTRL__EEI | UnICTRL__ERI | UnICTRL__ETI ); AdvanceStateMachine(); } } } } [Simulator.Register(Offset=0x0000000CU)] public byte UnSTAT { get { if(this.IsClockEnabled) { return m_state_UnSTAT; } else { return 0; } } } [Simulator.Register(Offset=0x00000010U)] public byte UnFRS; [Simulator.Register(Offset=0x00000014U)] public byte UnMDSL1; [Simulator.Register(Offset=0x00000018U)] public byte UnBAUD; [Simulator.Register(Offset=0x0000001CU)] public byte UnPSR; [Simulator.Register(Offset=0x00000020U)] public byte UnOVSR; [Simulator.Register(Offset=0x00000024U)] public byte UnMDSL2; [Simulator.Register(Offset=0x00000028U)] public byte UnSPOS; //--// private byte m_state_UnICTRL = UnICTRL__TBE; private byte m_state_UnSTAT; protected int m_portNumber; private bool m_fAdvancingStateMachine; private bool m_fShutdown; private bool m_txShiftRegisterActive; private byte m_txShiftRegister; private byte m_txBuffer; private Queue< byte > m_txQueue = new Queue< byte >(); private AutoResetEvent m_txWait = new AutoResetEvent( false ); private bool m_rxShiftRegisterActive; private byte m_rxShiftRegister; private byte m_rxBuffer; private Queue< byte > m_rxQueue = new Queue< byte >(); //--// // // Interface Methods // void Hosting.IAsynchronousSerialInterface.Send( byte value ) { HostPushData( value ); } bool Hosting.IAsynchronousSerialInterface.Receive( int timeout , out byte value ) { return HostPullData( timeout, out value ); } int Hosting.IAsynchronousSerialInterface.PortNumber { get { return m_portNumber; } } // // Helper Methods // public override void OnDisconnected() { m_fShutdown = true; m_txWait.Set(); base.OnDisconnected(); } private void AdvanceStateMachine() { if(this.IsClockEnabled) { // // Prevent recursion. // if(m_fAdvancingStateMachine == false) { m_fAdvancingStateMachine = true; AdvanceStateMachine_RX(); AdvanceStateMachine_TX(); m_fAdvancingStateMachine = false; } UpdateInterruptStatus(); } } private void AdvanceStateMachine_TX() { if(this.ShiftRegisterTxBusy == false) { if(this.TransmitBufferEmpty == false) { m_txShiftRegister = m_txBuffer; this.ShiftRegisterTxBusy = true; this.TransmitBufferEmpty = true; //--// Hosting.DeviceClockTicksTracking svc; m_owner.GetHostingService( out svc ); svc.RequestRelativeClockTickCallback( this.CharacterClockCycles, delegate() { this.ShiftRegisterTxBusy = false; if(this.IsClockEnabled) { DevidePushData( m_txShiftRegister ); AdvanceStateMachine(); } } ); } } } private void AdvanceStateMachine_RX() { if(this.ShiftRegisterRxBusy == false) { if(DevicePullData( out m_rxShiftRegister )) { this.ShiftRegisterRxBusy = true; Hosting.DeviceClockTicksTracking svc; m_owner.GetHostingService( out svc ); svc.RequestRelativeClockTickCallback( this.CharacterClockCycles, delegate() { m_rxBuffer = m_rxShiftRegister; this.ShiftRegisterRxBusy = false; if(this.IsClockEnabled) { if(this.ReadBufferFull) { m_state_UnSTAT |= UnSTAT__ERR; } else { this.ReadBufferFull = true; } } } ); } } } private void UpdateInterruptStatus() { if(this.IsClockEnabled) { if(TestBitField( m_state_UnICTRL, UnICTRL__ETI ) && this.TransmitBufferEmpty) { this.InterruptController.Set( m_portNumber == 0 ? INTC.IRQ_INDEX_USART0_Tx : INTC.IRQ_INDEX_USART1_Tx ); } else { this.InterruptController.Reset( m_portNumber == 0 ? INTC.IRQ_INDEX_USART0_Tx : INTC.IRQ_INDEX_USART1_Tx ); } if((TestBitField( m_state_UnICTRL, UnICTRL__ERI ) && this.ReadBufferFull ) || (TestBitField( m_state_UnICTRL, UnICTRL__EEI ) && TestBitField( m_state_UnSTAT, UnSTAT__ERR )) ) { this.InterruptController.Set( m_portNumber == 0 ? INTC.IRQ_INDEX_USART0_Rx : INTC.IRQ_INDEX_USART1_Rx ); } else { this.InterruptController.Reset( m_portNumber == 0 ? INTC.IRQ_INDEX_USART0_Rx : INTC.IRQ_INDEX_USART1_Rx ); } } } private bool DevicePullData( out byte val ) { lock(m_rxQueue) { if(m_rxQueue.Count > 0) { val = m_rxQueue.Dequeue(); return true; } val = 0; return false; } } private void DevidePushData( byte val ) { lock(m_txQueue) { m_txQueue.Enqueue( val ); } m_txWait.Set(); } private bool HostPullData( int timeout, out byte val ) { while(true) { lock(m_txQueue) { if(m_txQueue.Count > 0) { val = m_txQueue.Dequeue(); return true; } } if(m_fShutdown || m_txWait.WaitOne( timeout, false ) == false) { val = 0; return false; } } } private void HostPushData( byte val ) { lock(m_rxQueue) { m_rxQueue.Enqueue( val ); } Hosting.DeviceClockTicksTracking svc; m_owner.GetHostingService( out svc ); svc.RequestRelativeClockTickCallback( this.CharacterClockCycles, delegate() { if(this.IsClockEnabled) { AdvanceStateMachine(); } } ); } // // Access Methods // public bool IsClockEnabled { get { return (this.ClockController.CLK_EN_REG & (m_portNumber == 0 ? CMU.MCLK_EN__USART0 : CMU.MCLK_EN__USART1)) != 0; } } private int CharacterClockCycles { get { int bitsCHAR = UnFRS__LEN_CHAR__get ( this.UnFRS ); int bitsPARITY = UnFRS__LEN_PARITY__get( this.UnFRS ); int bitsSTOP = UnFRS__LEN_STOPS__get ( this.UnFRS ); int bits = 1 + bitsCHAR + bitsPARITY + bitsSTOP; return (int)(bits * this.BaudRateInClockCycles); } } private float BaudRateInClockCycles { get { int oversample = UnOVSR__get ( this.UnOVSR ); int divisor = (UnPSR__DIV__get( this.UnPSR ) + UnBAUD__get( this.UnBAUD )) + 1; int prescaler = UnPSR__PSC__get( this.UnPSR ) + 1; return (oversample * divisor * prescaler) / 2.0f; } } //--// public bool TransmitBufferEmpty { get { return TestBitField( m_state_UnICTRL, UnICTRL__TBE ); } private set { UpdateBitField( ref m_state_UnICTRL, UnICTRL__TBE, value ); UpdateInterruptStatus(); AdvanceStateMachine(); } } public bool ReadBufferFull { get { return TestBitField( m_state_UnICTRL, UnICTRL__RBF ); } private set { UpdateBitField( ref m_state_UnICTRL, UnICTRL__RBF, value ); UpdateInterruptStatus(); AdvanceStateMachine(); } } public bool ShiftRegisterTxBusy { get { return m_txShiftRegisterActive; ; } private set { UpdateBitField( ref m_state_UnSTAT, UnSTAT__XMIP, value ); m_txShiftRegisterActive = value; } } public bool ShiftRegisterRxBusy { get { return m_rxShiftRegisterActive; } private set { m_rxShiftRegisterActive = value; } } } [Simulator.PeripheralRange(Base=0x38040000U,Length=0x00010000U,ReadLatency=1,WriteLatency=2)] public class USART0 : USARTx { public override void OnConnected() { base.OnConnected(); m_portNumber = 0; } } [Simulator.PeripheralRange(Base=0x38050000U,Length=0x00010000U,ReadLatency=1,WriteLatency=2)] public class USART1 : USARTx { public override void OnConnected() { base.OnConnected(); m_portNumber = 1; } } [Simulator.PeripheralRange(Base=0x38060000U,Length=0x00000100U,ReadLatency=1,WriteLatency=2)] public class USB : Simulator.Peripheral { //// struct ENDPNT //// { //// /****/ volatile UINT8 EPCT; //// // for EP0 //// static const UINT8 EPCT__EPC0_MASK = 0xDF; //// static const UINT8 EPCT__EPC0_EP = 0x0F; //// static const UINT8 USB_SETUP_FIX_DIS = 0x10; //// //// static const UINT8 EPCT__EPC0_DEF = 0x40; //// static const UINT8 EPCT__EPC0_STALL = 0x80; //// // for EP1-3 //// static const UINT8 EPCT__EPC_MASK = 0xBF; //// static const UINT8 EPCT__EPC_EP = 0x0F; //// static const UINT8 EPCT__EPC_EP_EN = 0x10; //// static const UINT8 EPCT__EPC_ISO = 0x20; //// static const UINT8 EPCT__EPC_STALL = 0x80; //// /*************/ UINT8 padding1[3]; //// //// /****/ volatile UINT8 TXD; //// static const UINT8 TXD__mask = 0xFF; //// /*************/ UINT8 padding2[3]; //// //// /****/ volatile UINT8 TXS; //// // for EP0 //// static const UINT8 TXS__TXS0_MASK = 0x6F; //// static const UINT8 TXS__TXS0_TCOUNT = 0x0F; //// static const UINT8 TXS__TXS0_TX_DONE = 0x20; //// static const UINT8 TXS__TXS0_ACK_STAT = 0x40; //// // for EP1-3 //// static const UINT8 TXS__TXS_MASK = 0xFF; //// static const UINT8 TXS__TXS_TCOUNT = 0x1F; //// static const UINT8 TXS__TXS_TX_DONE = 0x20; //// static const UINT8 TXS__TXS_ACK_STAT = 0x40; //// static const UINT8 TXS__TXS_TX_URUN = 0x80; //// /*************/ UINT8 padding3[3]; //// //// /****/ volatile UINT8 TXC; //// // for EP0 //// static const UINT8 TXC__TXC0_MASK = 0x14; //// static const UINT8 TXC__TXC0_TX_EN = 0x01; //// static const UINT8 TXC__TXC0_TOGGLE = 0x04; //// static const UINT8 TXC__TXC0_FLUSH = 0x08; //// static const UINT8 TXC__TXC0_IGN_IN = 0x10; //// // for EP1-3 //// static const UINT8 TXC__TXC_MASK = 0xE4; //// static const UINT8 TXC__TXC_TX_EN = 0x01; //// static const UINT8 TXC__TXC_LAST = 0x02; //// static const UINT8 TXC__TXC_TOGGLE = 0x04; //// static const UINT8 TXC__TXC_FLUSH = 0x08; //// static const UINT8 TXC__TXC_RFF = 0x10; //// static const UINT8 TXC__TXC_TFWL = 0x60; //// static const UINT8 TXC__TXC_IGN_ISOMSK = 0x80; //// /*************/ UINT8 padding4[3]; //// //// /****/ volatile UINT8 EPCR; // EPCR use EPCT macro //// /*************/ UINT8 padding5[3]; //// //// /****/ volatile UINT8 RXD; //// static const UINT8 RXD__mask = 0xFF; //// /*************/ UINT8 padding6[3]; //// //// /****/ volatile UINT8 RXS; //// // for EP0 //// static const UINT8 RXS__RXS0_MASK = 0x7F; //// static const UINT8 RXS__RXS0_RCOUNT = 0x0F; //// static const UINT8 RXS__RXS0_RX_LAST = 0x10; //// static const UINT8 RXS__RXS0_TOGGLE = 0x20; //// static const UINT8 RXS__RXS0_SETUP = 0x40; //// // for EP1-3 //// static const UINT8 RXS__RXS_MASK = 0xFF; //// static const UINT8 RXS__RXS_RCOUNT = 0x0F; //// static const UINT8 RXS__RXS_RX_LAST = 0x10; //// static const UINT8 RXS__RXS_TOGGLE = 0x20; //// static const UINT8 RXS__RXS_SETUP = 0x40; //// static const UINT8 RXS__RXS_RX_ERR = 0x80; //// /*************/ UINT8 padding7[3]; //// //// /****/ volatile UINT8 RXC; //// // for EP0 //// static const UINT8 RXC__RXC0_MASK = 0x06; //// static const UINT8 RXC__RXC0_RX_EN = 0x01; //// static const UINT8 RXC__RXC0_IGN_OUT = 0x02; //// static const UINT8 RXC__RXC0_IGN_SETUP = 0x04; //// static const UINT8 RXC__RXC0_FLUSH = 0x08; //// // for EP1-3 //// static const UINT8 RXC__RXC_MASK = 0x64; //// static const UINT8 RXC__RXC_RX_EN = 0x01; //// static const UINT8 RXC__RXC_IGN_SETUP = 0x04; //// static const UINT8 RXC__RXC_FLUSH = 0x08; //// static const UINT8 RXC__RXC_RFWL = 0x60; //// /*************/ UINT8 padding8[3]; //// }; //// //// //--// //// //// static const UINT32 c_Base = 0xB8060000; //// //// //--// //// //// /****/ volatile UINT8 MCNTRL; //// static const UINT8 MCNTRL__MASK = 0x09; //// static const UINT8 MCNTRL__USBEN = 0x01; //// static const UINT8 MCNTRL__DBG = 0x02; //// static const UINT8 MCNTRL__NAT = 0x08; //// /*************/ UINT8 Padding1[3]; //// //// /****/ volatile UINT8 XCVRDIAG; //// /*************/ UINT8 Padding2[3]; //// //// /****/ volatile UINT8 TCR; //// /*************/ UINT8 Padding3[3]; //// //// /****/ volatile UINT8 UTR; //// /*************/ UINT8 Padding4[3]; //// //// /****/ volatile UINT8 FAR_; //// static const UINT8 FAR__FAR_MASK = 0xFF; //// static const UINT8 FAR__FAR_AD = 0x7F; //// static const UINT8 FAR__FAR_AD_EN = 0x80; //// /*************/ UINT8 Padding5[3]; //// //// /****/ volatile UINT8 NFSR; //// static const UINT8 NFSR__STATE_NODE_MASK = 0x03; //// static const UINT8 NFSR__STATE_NODE_RESET = 0x00; //// static const UINT8 NFSR__STATE_NODE_RESUME = 0x01; //// static const UINT8 NFSR__STATE_NODE_OPERATIONAL = 0x02; //// static const UINT8 NFSR__STATE_NODE_SUSPEND = 0x03; //// /*************/ UINT8 Padding6[3]; //// //// /****/ volatile UINT8 MAEV; //// static const UINT8 MAEV__MASK = 0xFF; //// static const UINT8 MAEV__WARN = 0x01; //// static const UINT8 MAEV__ALT = 0x02; //// static const UINT8 MAEV__TX_EV = 0x04; //// static const UINT8 MAEV__FRAME = 0x08; //// static const UINT8 MAEV__NAK = 0x10; //// static const UINT8 MAEV__ULD = 0x20; //// static const UINT8 MAEV__RX_EV = 0x40; //// static const UINT8 MAEV__INTR = 0x80; //// /*************/ UINT8 Padding7[3]; //// //// /****/ volatile UINT8 MAMSK; //// static const UINT8 MAMSK__MASK = 0xFF; //// static const UINT8 MAMSK__WARN = 0x01; //// static const UINT8 MAMSK__ALT = 0x02; //// static const UINT8 MAMSK__TX_EV = 0x04; //// static const UINT8 MAMSK__FRAME = 0x08; //// static const UINT8 MAMSK__NAK = 0x10; //// static const UINT8 MAMSK__ULD = 0x20; //// static const UINT8 MAMSK__RX_EV = 0x40; //// static const UINT8 MAMSK__INTR = 0x80; //// /*************/ UINT8 Padding8[3]; //// //// /****/ volatile UINT8 ALTEV; //// static const UINT8 ALTEV__MASK = 0xFC; //// static const UINT8 ALTEV__DMA = 0x04; //// static const UINT8 ALTEV__EOP = 0x08; //// static const UINT8 ALTEV__SD3 = 0x10; //// static const UINT8 ALTEV__SD5 = 0x20; //// static const UINT8 ALTEV__RESET = 0x40; //// static const UINT8 ALTEV__RESUME = 0x80; //// /*************/ UINT8 Padding9[3]; //// //// /****/ volatile UINT8 ALTMSK; //// static const UINT8 ALTMSK__MASK = 0xFC; //// static const UINT8 ALTMSK__DMA = 0x04; //// static const UINT8 ALTMSK__EOP = 0x08; //// static const UINT8 ALTMSK__SD3 = 0x10; //// static const UINT8 ALTMSK__SD5 = 0x20; //// static const UINT8 ALTMSK__RESET = 0x40; //// static const UINT8 ALTMSK__RESUME = 0x80; //// /*************/ UINT8 Padding10[3]; //// //// /****/ volatile UINT8 TXEV; //// static const UINT8 TXEV__MASK = 0xFF; //// static const UINT8 TXEV__FIFO_ALL = 0x0F; //// static const UINT8 TXEV__FIFO_EP0 = 0x01; //// static const UINT8 TXEV__UNDERRUN_ALL = 0xF0; //// /*************/ UINT8 Padding11[3]; //// //// __inline static UINT8 TXEV__FIFO__set ( UINT32 n ) { return (0x01 << n); } //// __inline static UINT8 TXEV__UNDERRUN__set( UINT32 n ) { return (0x10 << n); } //// //// /****/ volatile UINT8 TXMSK; //// static const UINT8 TXMSK__MASK = 0xFF; //// static const UINT8 TXMSK__FIFO_ALL = 0x0F; //// static const UINT8 TXMSK__FIFO_EP0 = 0x01; //// static const UINT8 TXMSK__UNDERRUN_ALL = 0xF0; //// /*************/ UINT8 Padding12[3]; //// //// __inline static UINT8 TXMSK__FIFO__set ( UINT32 n ) { return (0x01 << n); } //// __inline static UINT8 TXMSK__UNDERRUN__set( UINT32 n ) { return (0x10 << n); } //// //// /****/ volatile UINT8 RXEV; //// static const UINT8 RXEV__MASK = 0xFF; //// static const UINT8 RXEV__FIFO_ALL = 0x0F; //// static const UINT8 RXEV__FIFO_EP0 = 0x01; //// static const UINT8 RXEV__OVERRUN_ALL = 0xF0; //// /*************/ UINT8 Padding13[3]; //// //// __inline static UINT8 RXEV__FIFO__set ( UINT32 n ) { return (0x01 << n); } //// __inline static UINT8 RXEV__OVERRUN__set( UINT32 n ) { return (0x10 << n); } //// //// /****/ volatile UINT8 RXMSK; //// static const UINT8 RXMSK__MASK = 0xFF; //// static const UINT8 RXMSK__FIFO_ALL = 0x0F; //// static const UINT8 RXMSK__FIFO_EP0 = 0x01; //// static const UINT8 RXMSK__OVERRUN_ALL = 0xF0; //// /*************/ UINT8 Padding14[3]; //// //// __inline static UINT8 RXMSK__FIFO__set ( UINT32 n ) { return (0x01 << n); } //// __inline static UINT8 RXMSK__OVERRUN__set( UINT32 n ) { return (0x10 << n); } //// //// /****/ volatile UINT8 NAKEV; //// static const UINT8 NAKEV__MASK = 0xFF; //// static const UINT8 NAKEV__IN_ALL = 0x0F; //// static const UINT8 NAKEV__OUT_ALL = 0xF0; //// /*************/ UINT8 Padding15[3]; //// //// __inline static UINT8 NAKEV__IN__set ( UINT32 n ) { return (0x01 << n); } //// __inline static UINT8 NAKEV__OUT__set( UINT32 n ) { return (0x10 << n); } //// //// /****/ volatile UINT8 NAKMSK; //// static const UINT8 NAKMSK__MASK = 0xFF; //// static const UINT8 NAKMSK__IN_ALL = 0x0F; //// static const UINT8 NAKMSK__OUT_ALL = 0xF0; //// /*************/ UINT8 Padding16[3]; //// //// __inline static UINT8 NAKMSK__IN__set ( UINT32 n ) { return (0x01 << n); } //// __inline static UINT8 NAKMSK__OUT__set( UINT32 n ) { return (0x10 << n); } //// //// /****/ volatile UINT8 FWEV; //// static const UINT8 FWEV__MASK = 0xEE; //// static const UINT8 FWEV__TXWARN = 0x0E; //// static const UINT8 FWEV__RXWARN = 0xE0; //// /*************/ UINT8 Padding17[3]; //// //// /****/ volatile UINT8 FWMSK; //// static const UINT8 FWMSK__MASK = 0xEE; //// static const UINT8 FWMSK__TXWARN = 0x0E; //// static const UINT8 FWMSK__RXWARN = 0xE0; //// /*************/ UINT8 Padding18[3]; //// //// /****/ volatile UINT8 FNH; //// static const UINT8 FNH__MASK = 0xE7; //// static const UINT8 FNH__FN = 0x07; //// static const UINT8 FNH__RFC = 0x20; //// static const UINT8 FNH__UL = 0x40; //// static const UINT8 FNH__MF = 0x80; //// /*************/ UINT8 Padding19[3]; //// //// /****/ volatile UINT8 FNL; //// static const UINT8 FNL__MASK = 0xFF; //// static const UINT8 FNL__FN = 0xFF; //// /*************/ UINT8 Padding20[3]; //// //// /****/ volatile UINT8 DMACNTRL; //// static const UINT8 DMACNTRL__MASK = 0xFF; //// static const UINT8 DMACNTRL__DSRC = 0x07; //// static const UINT8 DMACNTRL__DMOD = 0x08; //// static const UINT8 DMACNTRL__ADMA = 0x10; //// static const UINT8 DMACNTRL__DTGL = 0x20; //// static const UINT8 DMACNTRL__IGNRXTGL = 0x40; //// static const UINT8 DMACNTRL__DEN = 0x80; //// /*************/ UINT8 Padding21[3]; //// //// /****/ volatile UINT8 DMAEV; //// static const UINT8 DMAEV__MASK = 0x3F; //// static const UINT8 DMAEV__DSHLT = 0x01; //// static const UINT8 DMAEV__DERR = 0x02; //// static const UINT8 DMAEV__DCNT = 0x04; //// static const UINT8 DMAEV__DSIZ = 0x08; //// static const UINT8 DMAEV__NTGL = 0x20; //// static const UINT8 USB_DMAEV_ARDY = 0x10; //// /*************/ UINT8 Padding22[3]; //// //// /****/ volatile UINT8 DMAMSK; //// static const UINT8 DMAMSK__MASK = 0x2F; //// static const UINT8 DMAMSK__DSHLT = 0x01; //// static const UINT8 DMAMSK__DERR = 0x02; //// static const UINT8 DMAMSK__DCNT = 0x04; //// static const UINT8 DMAMSK__DSIZ = 0x08; //// static const UINT8 DMAMSK__NTGL = 0x20; //// /*************/ UINT8 Padding23[3]; //// //// /****/ volatile UINT8 MIR; //// static const UINT8 MIR__MASK = 0xFF; //// static const UINT8 MIR__STAT = 0xFF; //// /*************/ UINT8 Padding24[3]; //// //// /****/ volatile UINT8 DMACNT; //// static const UINT8 DMACNT__MASK = 0xFF; //// static const UINT8 DMACNT__DCOUNT = 0xFF; //// /*************/ UINT8 Padding25[3]; //// //// /****/ volatile UINT8 DMAERR; //// static const UINT8 DMAERR__MASK = 0xFF; //// static const UINT8 DMAERR__DMAERRCNT = 0x7F; //// static const UINT8 DMAERR__AEH = 0x80; //// /*************/ UINT8 Padding26[3]; //// //// /****/ volatile UINT8 WAKEUP; //// /*************/ UINT8 Padding27[3]; //// //// /*************/ UINT32 Padding28[5]; //// //// /*************/ ENDPNT EP[4]; } [Simulator.PeripheralRange(Base=0x38070000U,Length=0x00000200U,ReadLatency=1,WriteLatency=2)] public class GPIO : Simulator.Peripheral { public delegate void NotifyOnChange( uint index, bool fSet ); public class CW : Simulator.Peripheral { public const ushort PIN = 0x0001; public const ushort DOUT_IEN = 0x0002; public const ushort RES_DIS = 0x0000; public const ushort RES_EN = 0x0004; public const ushort RES_DIR_PULLDOWN = 0x0000; public const ushort RES_DIR_PULLUP = 0x0008; public const ushort RES_mask = 0x000C; public const ushort MODE_mask = 0x0070; public const ushort MODE_GPIN = 0x0000; public const ushort MODE_GPOUT = 0x0010; public const ushort MODE_ALTA = 0x0020; public const ushort MODE_ALTB = 0x0030; public const ushort MODE_INTRL = 0x0040; public const ushort MODE_INTRH = 0x0050; public const ushort MODE_INTRNE = 0x0060; public const ushort MODE_INTRPE = 0x0070; public const ushort DB_EN = 0x0080; public const ushort INTR_STAT = 0x0100; public const ushort INTR_RAW = 0x0200; public const ushort Config_Mask = (DOUT_IEN | RES_mask | MODE_mask | DB_EN); [Simulator.LinkToContainer() ] public GPIO Parent; [Simulator.Register(Offset=0x00000000U)] public ushort Data { get { return (ushort)this.RawValue; } set { this.RawValue = value; } } private ushort m_state_Data; bool m_fStatus; //--// // // Helper Methods // private void UpdateStatus( bool fOldStatus , bool fNewStatus ) { switch(m_state_Data & MODE_mask) { case MODE_INTRL : if(fNewStatus == false) { SetBitField( ref m_state_Data, INTR_RAW ); } else { ClearBitField( ref m_state_Data, INTR_RAW ); } break; case MODE_INTRH: if(fNewStatus == true) { SetBitField( ref m_state_Data, INTR_RAW ); } else { ClearBitField( ref m_state_Data, INTR_RAW ); } break; case MODE_INTRNE: if(fOldStatus == true && fNewStatus == false) { SetBitField( ref m_state_Data, INTR_RAW ); } break; case MODE_INTRPE: if(fOldStatus == false && fNewStatus == true) { SetBitField( ref m_state_Data, INTR_RAW ); } break; default: ClearBitField( ref m_state_Data, INTR_RAW ); break; } this.Parent.Notify( this, fOldStatus, fNewStatus ); this.Parent.UpdateInterrupts(); } internal void ResetInterrupt() { switch(m_state_Data & MODE_mask) { case MODE_INTRNE: case MODE_INTRPE: ClearBitField( ref m_state_Data, INTR_RAW ); this.Parent.UpdateInterrupts(); break; } } // // Access Methods // public uint RawValue { get { uint res = (uint)m_state_Data & Config_Mask; if(m_fStatus) { res |= PIN; } switch(m_state_Data & MODE_mask) { case MODE_INTRL : case MODE_INTRH : case MODE_INTRNE: case MODE_INTRPE: if((m_state_Data & INTR_RAW) != 0) { res |= INTR_RAW; if((res & DOUT_IEN) != 0) { res |= INTR_STAT; } } break; } return res; } set { if(this.RawValue != value) { bool fOldStatus = m_fStatus; // // Update the configuration, leave interrupt status untouched. // ClearBitField( ref m_state_Data, Config_Mask ); SetBitField ( ref m_state_Data, (ushort)(value & Config_Mask) ); if(TestBitField( value, INTR_STAT | INTR_RAW )) { this.ResetInterrupt(); } switch(m_state_Data & MODE_mask) { case MODE_GPOUT: m_fStatus = (value & DOUT_IEN) != 0; break; } UpdateStatus( fOldStatus, m_fStatus ); } } } public bool PinStatus { get { return m_fStatus; } set { bool fOldStatus = m_fStatus; if(fOldStatus != value) { switch(m_state_Data & MODE_mask) { case MODE_GPOUT: break; default: m_fStatus = value; UpdateStatus( fOldStatus, value ); break; } } } } public bool RawInterrupt { get { return TestBitField( this.RawValue, INTR_RAW ); } } public bool Interrupt { get { return TestBitField( this.RawValue, INTR_STAT ); } } } public class PIN8 : Simulator.Peripheral { public const byte DBCLK_SEL__SLOWCLK_DIV_00002 = 0x00; public const byte DBCLK_SEL__SLOWCLK_DIV_00004 = 0x01; public const byte DBCLK_SEL__SLOWCLK_DIV_00008 = 0x02; public const byte DBCLK_SEL__SLOWCLK_DIV_00016 = 0x03; public const byte DBCLK_SEL__SLOWCLK_DIV_00032 = 0x04; public const byte DBCLK_SEL__SLOWCLK_DIV_00064 = 0x05; public const byte DBCLK_SEL__SLOWCLK_DIV_00128 = 0x06; public const byte DBCLK_SEL__SLOWCLK_DIV_00256 = 0x07; public const byte DBCLK_SEL__SLOWCLK_DIV_00512 = 0x08; public const byte DBCLK_SEL__SLOWCLK_DIV_01024 = 0x09; public const byte DBCLK_SEL__SLOWCLK_DIV_02048 = 0x0A; public const byte DBCLK_SEL__SLOWCLK_DIV_04096 = 0x0B; public const byte DBCLK_SEL__SLOWCLK_DIV_08192 = 0x0C; public const byte DBCLK_SEL__SLOWCLK_DIV_16384 = 0x0D; public const byte DBCLK_SEL__SLOWCLK_DIV_32768 = 0x0E; public const byte DBCLK_SEL__SLOWCLK_DIV_65536 = 0x0F; [Simulator.LinkToContainer() ] public GPIO Parent; [Simulator.Register(Offset=0x00000000U)] public byte PIN_DIN8 { get { uint res = 0; uint offset = this.Parent.Index( this ); for(int i = 0; i < 8; i++) { if(this.Parent.Control[offset + i].PinStatus) { res = 1u << i; } } return (byte)res; } } [Simulator.Register(Offset=0x00000004U)] public byte DATA_OUT8 { get { uint res = 0; uint offset = this.Parent.Index( this ); for(int i = 0; i < 8; i++) { if(this.Parent.Control[offset + i].PinStatus) { res = 1u << i; } } return (byte)res; } set { uint offset = this.Parent.Index( this ); for(int i = 0; i < 8; i++) { var ctrl = this.Parent.Control[offset + i]; if((value & (1u << i)) != 0) { ctrl.RawValue |= CW.DOUT_IEN; } else { ctrl.RawValue &= ~(uint)CW.DOUT_IEN; } } } } [Simulator.Register(Offset=0x00000008U)] public byte INTR_STAT8; [Simulator.Register(Offset=0x0000000CU)] public byte INTR_RAW8 { get { uint res = 0; uint offset = this.Parent.Index( this ); for(int i = 0; i < 8; i++) { if(this.Parent.Control[offset + i].Interrupt) { res = 1u << i; } } return (byte)res; } set { ResetInterrupt( value ); } } [Simulator.Register(Offset=0x00000010U)] public byte DBCLK_SEL; // only valid in array offset 0 (+0x0110) // // Helper Methods // private void ResetInterrupt( uint value ) { uint offset = this.Parent.Index( this ); for(int i = 0; i < 8; i++) { if((value & (1u << i)) != 0) { this.Parent.Control[offset + i].ResetInterrupt(); } } } } public const uint c_Pin_None = 0xFFFFFFFF; public const uint c_Pin_00 = 0; public const uint c_Pin_01 = 1; public const uint c_Pin_02 = 2; public const uint c_Pin_03 = 3; public const uint c_Pin_04 = 4; public const uint c_Pin_05 = 5; public const uint c_Pin_06 = 6; public const uint c_Pin_07 = 7; public const uint c_Pin_08 = 8; public const uint c_Pin_09 = 9; public const uint c_Pin_10 = 10; public const uint c_Pin_11 = 11; public const uint c_Pin_12 = 12; public const uint c_Pin_13 = 13; public const uint c_Pin_14 = 14; public const uint c_Pin_15 = 15; public const uint c_Pin_16 = 16; public const uint c_Pin_17 = 17; public const uint c_Pin_18 = 18; public const uint c_Pin_19 = 19; public const uint c_Pin_20 = 20; public const uint c_Pin_21 = 21; public const uint c_Pin_22 = 22; public const uint c_Pin_23 = 23; public const uint c_Pin_24 = 24; public const uint c_Pin_25 = 25; // 26->31 are not available public const uint c_Pin_32 = 32; public const uint c_Pin_33 = 33; public const uint c_Pin_34 = 34; public const uint c_Pin_35 = 35; public const uint c_Pin_36 = 36; public const uint c_Pin_37 = 37; public const uint c_Pin_38 = 38; public const uint c_Pin_39 = 39; // 40->63 are not available //--// [Simulator.LinkToPeripheral() ] public INTC InterruptController; [Simulator.Register(Offset=0x00000000U,Size=0x04U,Instances=64)] public CW[] Control; [Simulator.Register(Offset=0x00000100U,Size=0x20U,Instances= 8)] public PIN8[] Pin8; NotifyOnChange[] m_callbacks = new NotifyOnChange[64]; //--// uint Index( PIN8 obj ) { return (uint)(Array.IndexOf( this.Pin8, obj ) * 8); } uint Index( CW obj ) { return (uint)(Array.IndexOf( this.Control, obj )); } void Notify( CW control , bool fOldStatus , bool fNewStatus ) { uint pin = Index( control ); NotifyOnChange dlg = m_callbacks[pin]; if(dlg != null) { dlg( pin, fNewStatus ); } } void UpdateInterrupts() { for(uint group = 0; group < 8; group++) { int index = -1; switch(group) { case 0: index = INTC.IRQ_INDEX_GPIO_00_07; break; case 1: index = INTC.IRQ_INDEX_GPIO_08_15; break; case 2: index = INTC.IRQ_INDEX_GPIO_16_23; break; case 3: index = INTC.IRQ_INDEX_GPIO_24_31; break; case 4: index = INTC.IRQ_INDEX_GPIO_32_39; break; } if(index >= 0) { bool fRaise = false; for(uint pin = 0; pin < 8; pin++) { if(this.Control[group * 8 + pin].Interrupt) { fRaise = true; break; } } if(fRaise) { this.InterruptController.Set( index ); } else { this.InterruptController.Reset( index ); } } } } //--// public void Register( uint pin , NotifyOnChange dlg ) { m_callbacks[pin] += dlg; } public void Unregister( uint pin , NotifyOnChange dlg ) { m_callbacks[pin] -= dlg; } public bool ReadPin( uint pin ) { return this.Control[pin].PinStatus; } public void SetPin( uint pin ) { this.Control[pin].PinStatus = true; } public void ResetPin( uint pin ) { this.Control[pin].PinStatus = false; } } [Simulator.PeripheralRange(Base=0x38090000U,Length=0x00000080U,ReadLatency=1,WriteLatency=2)] public class SECURITYKEY : Simulator.Peripheral { public class BYTE : Simulator.Peripheral { [Simulator.LinkToContainer() ] public SECURITYKEY Parent; [Simulator.Register(Offset=0x00000000U)] public byte Data8; } //--// [Simulator.Register(Offset=0x00000000U,Size=4,Instances=32)] public BYTE[] Key; } [Simulator.PeripheralRange(Base=0x380A0000U,Length=0x00000014U,ReadLatency=1,WriteLatency=2)] public class MWSPI : Simulator.Peripheral, Hosting.ISynchronousSerialInterfaceController { public const uint c_MS1LE = GPIO.c_Pin_07; public const uint c_MSK = GPIO.c_Pin_16; public const uint c_MDIDO = GPIO.c_Pin_17; public const uint c_MDODI = GPIO.c_Pin_18; public const uint c_MSC0LE = GPIO.c_Pin_19; //--// public const ushort MWnCTL1__MWEN = 0x0001; public const ushort MWnCTL1__MNS_SLAVE = 0x0000; public const ushort MWnCTL1__MNS_MASTER = 0x0002; public const ushort MWnCTL1__MOD_8 = 0x0000; public const ushort MWnCTL1__MOD_16 = 0x0004; public const ushort MWnCTL1__ECHO = 0x0008; public const ushort MWnCTL1__EIF = 0x0010; public const ushort MWnCTL1__EIR = 0x0020; public const ushort MWnCTL1__EIW = 0x0040; public const ushort MWnCTL1__SCM_NORMAL = 0x0000; public const ushort MWnCTL1__SCM_ALTERNATE = 0x0080; public const ushort MWnCTL1__SCIDL_MSK0 = 0x0000; public const ushort MWnCTL1__SCIDL_MSK1 = 0x0100; public static ushort MWnCTL1__SCDV__set( uint d ) { return (ushort)((d & 0x7F) << 9); } public static uint MWnCTL1__SCDV__get( ushort d ) { return ((uint)d >> 9) & 0x7F; } public const ushort MWnSTAT__TBF = 0x0001; public const ushort MWnSTAT__RBF = 0x0002; public const ushort MWnSTAT__OVR = 0x0004; public const ushort MWnSTAT__UDR = 0x0008; public const ushort MWnSTAT__BSY = 0x0010; public const ushort MWnCTL2__EDR = 0x0001; public const ushort MWnCTL2__EDW = 0x0002; public const ushort MWnCTL2__LEE0 = 0x0004; public const ushort MWnCTL2__LEE1 = 0x0008; public const ushort MWnCTL2__LEMD0 = 0x0010; public const ushort MWnCTL2__LEMD1 = 0x0020; public const ushort MWnCTL2__LEPL0 = 0x0040; public const ushort MWnCTL2__LEPL1 = 0x0080; public const ushort MWnCTL2__DTMD_mask = 0x0300; public const ushort MWnCTL2__DTMD_FULL_DUPLEX = 0x0000; public const ushort MWnCTL2__DTMD_READ_ONLY = 0x0100; public const ushort MWnCTL2__DTMD_WRITE_ONLY = 0x0200; public const ushort MWnCTL2__FNCLE = 0x0400; public const ushort MWnCTL2__CNTLE = 0x0800; //--// [Simulator.LinkToPeripheral() ] public INTC InterruptController; [Simulator.LinkToPeripheral() ] public CMU ClockController; [Simulator.LinkToPeripheral() ] public GPIO InputOutput; [Simulator.Register(Offset=0x00000000U)] public ushort MWnDAT { get { if(this.IsClockEnabled) { ushort res = m_readBuffer; if(m_owner.AreTimingUpdatesEnabled) { this.ReadBufferFull = false; Emulation.Hosting.MonitorExecution svcME; if(m_owner.GetHostingService( out svcME ) && svcME.MonitorOpcodes) { Hosting.OutputSink sink; if(m_owner.GetHostingService( out sink )) { sink.OutputLine( "SPI READ: {0} {1:X4}", m_owner.ClockTicks, res ); } } } return res; } else { return 0; } } set { if(this.IsClockEnabled) { if(m_owner.AreTimingUpdatesEnabled) { if(this.IsEnabled) { Emulation.Hosting.MonitorExecution svcME; if(m_owner.GetHostingService( out svcME ) && svcME.MonitorOpcodes) { Hosting.OutputSink sink; if(m_owner.GetHostingService( out sink )) { sink.OutputLine( "SPI WRITE: {0} {1:X4}", m_owner.ClockTicks, value ); } } m_transmitBuffer = value; this.TransmitBufferFull = true; } } } } } [Simulator.Register(Offset=0x00000004U)] public ushort MWnCTL1 { get { if(this.IsClockEnabled) { return m_state_MWnCTL1; } else { return 0; } } set { if(this.IsClockEnabled) { if(m_owner.AreTimingUpdatesEnabled) { bool fNotify = false; m_state_MWnCTL1 = value; if(this.IsEnabled == false) { ClearBitField( ref m_state_MWnSTAT, MWnSTAT__BSY | MWnSTAT__UDR | MWnSTAT__OVR | MWnSTAT__RBF | MWnSTAT__TBF ); } else { fNotify = (this.IsMasterMode == false); } if(fNotify) { this.InputOutput.Register( c_MSC0LE, NotifyChipSelect ); } else { this.InputOutput.Unregister( c_MSC0LE, NotifyChipSelect ); } } } } } [Simulator.Register(Offset=0x00000008U)] public ushort MWnSTAT { get { if(this.IsClockEnabled) { return m_state_MWnSTAT; } else { return 0; } } set { if(this.IsClockEnabled) { if(m_owner.AreTimingUpdatesEnabled) { if(TestBitField( value, MWnSTAT__OVR )) { ClearBitField( ref m_state_MWnSTAT, MWnSTAT__OVR ); } if(TestBitField( value, MWnSTAT__UDR )) { ClearBitField( ref m_state_MWnSTAT, MWnSTAT__UDR ); } UpdateInterruptStatus(); } } } } [Simulator.Register(Offset=0x0000000CU)] public ushort MWnCTL2 { get { if(this.IsClockEnabled) { return m_state_MWnCTL2; } else { return 0; } } set { if(this.IsClockEnabled) { const ushort unsupported = MWnCTL2__EDR | MWnCTL2__EDW | MWnCTL2__LEE0 | MWnCTL2__LEE1 | MWnCTL2__LEMD0 | MWnCTL2__LEMD1 | MWnCTL2__LEPL0 | MWnCTL2__LEPL1 | MWnCTL2__FNCLE | MWnCTL2__CNTLE; if(TestBitField( value, unsupported )) { throw new NotSupportedException( string.Format( "Unsupported use of {0}", this.GetType() ) ); } m_state_MWnCTL2 = value; } } } [Simulator.Register(Offset=0x00000010U)] public ushort MWnTEST; ushort m_state_MWnCTL1; ushort m_state_MWnSTAT; ushort m_state_MWnCTL2; ushort m_shiftRegister; bool m_shiftRegisterTX; bool m_shiftRegisterRX; ushort m_readBuffer; ushort m_transmitBuffer; bool m_fAdvancingStateMachine; //--// // // Interface Methods // uint Hosting.ISynchronousSerialInterfaceController.ShiftData( uint value , int bitSize , int clockFrequency ) { uint res = 0; if(this.IsClockEnabled && this.IsEnabled) { if(this.IsMasterMode == false) { if(m_shiftRegisterTX == false) { SetBitField( ref m_state_MWnSTAT, MWnSTAT__UDR ); } res = m_shiftRegister; m_shiftRegisterTX = false; this.ShiftRegisterBusy = true; this.TransmitBufferFull = false; long delay = (long)((double)bitSize * m_owner.ClockFrequency / clockFrequency); Hosting.DeviceClockTicksTracking svc; m_owner.GetHostingService( out svc ); svc.RequestRelativeClockTickCallback( delay, delegate() { Emulation.Hosting.MonitorExecution svcME; if(m_owner.GetHostingService( out svcME ) && svcME.MonitorOpcodes) { Hosting.OutputSink sink; if(m_owner.GetHostingService( out sink )) { sink.OutputLine( "SHIFT END: {0}", m_owner.ClockTicks ); } } if(this.ShiftRegisterBusy) { m_shiftRegister = (ushort)value; m_shiftRegisterRX = true; this.ShiftRegisterBusy = false; AdvanceStateMachine(); } } ); AdvanceStateMachine(); } } return res; } void Hosting.ISynchronousSerialInterfaceController.StartTransaction() { this.InputOutput.ResetPin( c_MSC0LE ); } void Hosting.ISynchronousSerialInterfaceController.EndTransaction() { this.InputOutput.SetPin( c_MSC0LE ); } // // Helper Methods // private void NotifyChipSelect( uint index , bool fSet ) { } private void AdvanceStateMachine() { if(this.IsClockEnabled && this.IsEnabled) { if(this.ShiftRegisterBusy) { // // Wait for the transfer to finish. // } else { // // Prevent recursion. // if(m_fAdvancingStateMachine == false) { m_fAdvancingStateMachine = true; if(this.IsMasterMode) { AdvanceStateMachine_Master(); } else { AdvanceStateMachine_Slave(); } m_fAdvancingStateMachine = false; } } UpdateInterruptStatus(); } } private void AdvanceStateMachine_Master() { if(m_shiftRegisterRX) { if(this.IsReadMode) { m_readBuffer = m_shiftRegister; this.ReadBufferFull = true; } m_shiftRegisterRX = false; } if(m_shiftRegisterTX == false) { if(this.TransmitBufferFull) { if(this.IsReadMode) { if(this.ReadBufferFull) { // // Read buffer is full, we cannot start a new transfer. // return; } } if(this.IsWriteMode) { m_shiftRegister = m_transmitBuffer; } m_shiftRegisterTX = true; this.TransmitBufferFull = false; } } if(m_shiftRegisterTX) { this.ShiftRegisterBusy = true; int bitSize = TestBitField( m_state_MWnCTL1, MWnCTL1__MOD_16 ) ? 16 : 8; uint delay = Math.Max( MWnCTL1__SCDV__get( m_state_MWnCTL1 ), 2 ); Hosting.DeviceClockTicksTracking svc; m_owner.GetHostingService( out svc ); svc.RequestRelativeClockTickCallback( delay * bitSize, delegate() { if(this.IsClockEnabled && this.IsEnabled) { Hosting.ISynchronousSerialInterfaceBus bus; if(m_owner.GetHostingService( out bus )) { m_shiftRegister = (ushort)bus.ShiftData( m_shiftRegister, bitSize, 0 ); } m_shiftRegisterTX = false; m_shiftRegisterRX = true; this.ShiftRegisterBusy = false; AdvanceStateMachine(); } } ); } } private void AdvanceStateMachine_Slave() { if(m_shiftRegisterRX) { if(this.IsReadMode) { if(this.ReadBufferFull) { // // Read buffer is still full, new data is lost. // SetBitField( ref m_state_MWnSTAT, MWnSTAT__OVR ); } else { m_readBuffer = m_shiftRegister; this.ReadBufferFull = true; } } m_shiftRegisterRX = false; } if(m_shiftRegisterTX == false) { if(this.IsWriteMode) { if(this.TransmitBufferFull) { m_shiftRegister = m_transmitBuffer; m_shiftRegisterTX = true; this.ShiftRegisterBusy = true; // Slave transmits are not double buffered... //this.TransmitBufferFull = false; } } } } private void UpdateInterruptStatus() { bool fAssertInterrupt = false; if(this.IsClockEnabled && this.IsEnabled) { if(TestBitField( m_state_MWnCTL1, MWnCTL1__EIW )) { if(this.TransmitBufferFull == false) { fAssertInterrupt = true; } } if(TestBitField( m_state_MWnCTL1, MWnCTL1__EIR )) { if(this.ReadBufferFull) { fAssertInterrupt = true; } } if(TestBitField( m_state_MWnCTL1, MWnCTL1__EIF )) { if(TestBitField( m_state_MWnSTAT, MWnSTAT__OVR )) { fAssertInterrupt = true; } } } if(fAssertInterrupt) { this.InterruptController.Set( INTC.IRQ_INDEX_MicroWire ); } else { this.InterruptController.Reset( INTC.IRQ_INDEX_MicroWire ); } } // // Access Methods // public bool IsClockEnabled { get { return (this.ClockController.CLK_EN_REG & CMU.MCLK_EN__UWIRE) != 0; } } public bool IsEnabled { get { return TestBitField( m_state_MWnCTL1, MWnCTL1__MWEN ); } } public bool IsMasterMode { get { return TestBitField( m_state_MWnCTL1, MWnCTL1__MNS_MASTER ); } } public bool IsReadMode { get { switch(m_state_MWnCTL2 & MWnCTL2__DTMD_mask) { case MWnCTL2__DTMD_FULL_DUPLEX: case MWnCTL2__DTMD_READ_ONLY: return true; } return false; } } public bool IsWriteMode { get { switch(m_state_MWnCTL2 & MWnCTL2__DTMD_mask) { case MWnCTL2__DTMD_FULL_DUPLEX: case MWnCTL2__DTMD_WRITE_ONLY: return true; } return false; } } //--// public bool TransmitBufferFull { get { return TestBitField( m_state_MWnSTAT, MWnSTAT__TBF ); } private set { UpdateBitField( ref m_state_MWnSTAT, MWnSTAT__TBF, value ); UpdateInterruptStatus(); AdvanceStateMachine(); } } public bool ReadBufferFull { get { return TestBitField( m_state_MWnSTAT, MWnSTAT__RBF ); } private set { UpdateBitField( ref m_state_MWnSTAT, MWnSTAT__RBF, value ); UpdateInterruptStatus(); AdvanceStateMachine(); } } public bool ShiftRegisterBusy { get { return TestBitField( m_state_MWnSTAT, MWnSTAT__BSY ); } private set { UpdateBitField( ref m_state_MWnSTAT, MWnSTAT__BSY, value ); } } } [Simulator.PeripheralRange(Base=0x380B0000U,Length=0x00000018U,ReadLatency=1,WriteLatency=2)] public class CMU : Simulator.Peripheral { public enum PERF_LEVEL : uint { CLK_SEL__DIV_FAST = 0xFF, CLK_SEL__DIV_1 = 0xFF, CLK_SEL__DIV_2 = 0x7F, CLK_SEL__DIV_3 = 0x3F, CLK_SEL__DIV_4 = 0x1F, CLK_SEL__DIV_6 = 0x0F, CLK_SEL__DIV_12 = 0x07, CLK_SEL__DIV_24 = 0x03, CLK_SEL__DIV_SLOW = 0x03, CLK_SEL__CPU_CK_SLOW = 0x01, CLK_SEL__OFF = 0x00, } //--// public const uint CLK_SEL__APC_EN = 0x00000001; public const uint CLK_SEL__PU_DIS = 0x00000002; public const uint CLK_SEL__CKOUTEN = 0x00000020; public const uint CLK_SEL__EXTSLOW = 0x00000040; public const uint CLK_SEL__XTALDIS = 0x00000080; public const uint CLK_SEL__48M_EN = 0x00000100; public const uint CLK_SEL__NOPCU = 0x00000200; public const uint CLK_SEL__CLKSEL_RO = 0x00003000; public const uint CLK_SEL__BOOT = 0x0000C000; public const uint CLK_SEL__MASK = 0x0000F3FF; public const uint MCLK_EN__DMAC = 0x00000001; public const uint MCLK_EN__VITERBI = 0x00000002; public const uint MCLK_EN__FILTER = 0x00000004; public const uint MCLK_EN__APC = 0x00000008; public const uint MCLK_EN__ARMTIM = 0x00000010; public const uint MCLK_EN__VTU32 = 0x00000020; public const uint MCLK_EN__USART0 = 0x00000040; public const uint MCLK_EN__USART1 = 0x00000080; public const uint MCLK_EN__RESERVED2 = 0x00000100; public const uint MCLK_EN__GPIO = 0x00000200; public const uint MCLK_EN__UWIRE = 0x00000400; public const uint MCLK_EN__USB = 0x00000800; public const uint MCLK_EN__ALL = 0x0000FFFF; public static uint PLLNMP__set( uint N , uint M , uint P ) { return ((P & 0x03) << 13) | ((M & 0x1F) << 8) | (N & 0x7F); } //--// [Simulator.Register(Offset=0x00000000U)] public uint PERF_LVL; [Simulator.Register(Offset=0x00000004U)] public uint CLK_SEL; [Simulator.Register(Offset=0x00000008U)] public byte REF_REG; [Simulator.Register(Offset=0x0000000CU)] public uint MCLK_EN { get { return m_state_MCLK_EN; } set { m_state_MCLK_EN = value; // // It takes 256 clock cycles to update CLK_EN_REG register. // Hosting.DeviceClockTicksTracking svc; m_owner.GetHostingService( out svc ); svc.RequestRelativeClockTickCallback( 256, delegate() { this.CLK_EN_REG = value; } ); } } [Simulator.Register(Offset=0x00000010U)] public uint CLK_EN_REG; [Simulator.Register(Offset=0x00000014U)] public uint PLLNMP; uint m_state_MCLK_EN; } [Simulator.PeripheralRange(Base=0x380C0000U,Length=0x00000020U,ReadLatency=1,WriteLatency=2)] public class RTC : Simulator.Peripheral { public const uint WDCTL__DIS = 0x00000000; public const uint WDCTL__EN = 0x00000001; public const uint WDCTL__LK = 0x00000002; public const uint WDCTL__IEN = 0x00000004; public const uint WDCTL__REN = 0x00000008; public const uint WDCTL__WDOG_PIN_DISABLED = 0x00000000; public const uint WDCTL__WDOG_PIN_ACTIVE = 0x00000010; public const uint WDCTL__WDOG_PIN_OPEN_DRAIN = 0x00000020; public const uint WDCTL__WDOG_PIN_OPEN_DRAIN_PULLUP = 0x00000030; public const uint WDDLY__RESET_CLOCK_DELAY = 512; public const uint WDDLY__READ_HREG = 12; public const uint WDRST__KEY = 0x0000005C; //--// [Simulator.LinkToPeripheral() ] public INTC InterruptController; [Simulator.Register(Offset=0x00000000U)] public uint HREG_low { get { return m_state_HREG_low; } set { m_state_HREG_low = value; } } [Simulator.Register(Offset=0x00000004U)] public uint HREG_high { get { return m_state_HREG_high; } set { m_state_HREG_high = value; m_base = Get64BitValue( m_state_HREG_low, m_state_HREG_high ) - GetCurrentTime(); Evaluate(); } } [Simulator.Register(Offset=0x00000008U)] public uint COMP_low { get { return m_state_COMP_low; } set { m_state_COMP_low = value; // // A write to the first part of COMP disables interrupts. // m_fInterruptDisable = true; Evaluate(); } } [Simulator.Register(Offset=0x0000000CU)] public uint COMP_high { get { return m_state_COMP_high; } set { m_state_COMP_high = value; // // A write to the second part of COMP triggers the reload of the compare register. // m_compare = Get64BitValue( m_state_COMP_low, m_state_COMP_high ); m_fInterruptDisable = false; Evaluate(); } } [Simulator.Register(Offset=0x00000010U)] public uint LD_HREG { set { // // Any value write cause the load to holding register. // Set64BitValue( GetCounterValue(), out m_state_HREG_low, out m_state_HREG_high ); } } [Simulator.Register(Offset=0x00000014U)] public uint WDCTL; [Simulator.Register(Offset=0x00000018U)] public uint WDDLY; [Simulator.Register(Offset=0x0000001CU)] public uint WDRST; //--// // // State // uint m_state_HREG_low; uint m_state_HREG_high; uint m_state_COMP_low; uint m_state_COMP_high; double m_convertFromCpuTicks; double m_convertToCpuTicks; ulong m_compare = 0x0000FFFFFFFFFFFFU; ulong m_base = 0; bool m_fInterruptDisable = false; // // Getter/Setter Methods // public override void OnConnected() { base.OnConnected(); Cfg.ProcessorCategory proc = m_owner.Product.SearchValue< Cfg.ProcessorCategory >(); m_convertFromCpuTicks = (double)proc.RealTimeClockFrequency / (double)proc.CoreClockFrequency; m_convertToCpuTicks = (double)proc.CoreClockFrequency / (double)proc.RealTimeClockFrequency; } //--// // // Helper Methods // ulong GetCurrentTime() { return ConvertFromCpuTicks( m_owner.ClockTicks ); } ulong GetCounterValue() { return GetCurrentTime() + m_base; } void Evaluate() { Hosting.DeviceClockTicksTracking svc; m_owner.GetHostingService( out svc ); svc.CancelClockTickCallback( Callback ); if(m_fInterruptDisable) { this.InterruptController.Reset( INTC.IRQ_INDEX_Real_Time_Clock ); } else { long diff = (long)(m_compare - GetCounterValue()); if(diff > 0) { this.InterruptController.Reset( INTC.IRQ_INDEX_Real_Time_Clock ); svc.RequestRelativeClockTickCallback( ConvertToCpuTicks( diff ), Callback ); } else { this.InterruptController.Set( INTC.IRQ_INDEX_Real_Time_Clock ); } } } void Callback() { Evaluate(); } //--// private ulong ConvertFromCpuTicks( ulong ticks ) { return (ulong)(ticks * m_convertFromCpuTicks); } private long ConvertToCpuTicks( long ticks ) { return (long)(ticks * m_convertToCpuTicks); } // // Access Methods // public ulong CompareTime { get { return m_compare; } } } [Simulator.PeripheralRange(Base=0x380D0000U,Length=0x00000004U,ReadLatency=1,WriteLatency=2)] public class EDMAIF : Simulator.Peripheral { [Simulator.Register(Offset=0x00000000U)] public uint EMDAIF_Control; } [Simulator.PeripheralRange(Base=0x380E0000U,Length=0x00000020U,ReadLatency=1,WriteLatency=2)] public class PCU : Simulator.Peripheral { public const uint PCU_STATUS__LN2 = 0x00000040; public const uint PCU_STATUS__LN1 = 0x00000020; public const uint PCU_STATUS__SW1 = 0x00000010; public const uint PCU_STATUS__OTHER = 0x00000008; public const uint PCU_STATUS__RESET = 0x00000004; public const uint PCU_STATUS__DEAD = 0x00000002; public const uint PCU_STATUS__OFF = 0x00000001; [Simulator.Register(Offset=0x00000000U)] public uint CLR_SW1; [Simulator.Register(Offset=0x00000004U)] public uint SET_SW1; [Simulator.Register(Offset=0x00000008U)] public uint CLR_LN1; [Simulator.Register(Offset=0x0000000CU)] public uint SET_LN1; [Simulator.Register(Offset=0x00000010U)] public uint CLR_LN2; [Simulator.Register(Offset=0x00000014U)] public uint SET_LN2; [Simulator.Register(Offset=0x00000018U)] public uint SW_RESET; [Simulator.Register(Offset=0x0000001CU)] public uint PCU_STATUS; [Simulator.Register(Offset=0x00000020U)] public byte CLR_SW1_CNT; [Simulator.Register(Offset=0x00000024U)] public byte SET_SW1_CNT; [Simulator.Register(Offset=0x00000028U)] public byte CLR_LN1_CNT; [Simulator.Register(Offset=0x0000002CU)] public byte SET_LN1_CNT; [Simulator.Register(Offset=0x00000030U)] public byte CLR_LN2_CNT; [Simulator.Register(Offset=0x00000034U)] public byte SET_LN2_CNT; } // // Advanced Power Control // [Simulator.PeripheralRange(Base=0x380F0000U,Length=0x00000020U,ReadLatency=1,WriteLatency=2)] public class APC { [Simulator.Register(Offset=0x00000000U)] public byte APC_PWICMD; [Simulator.Register(Offset=0x00000004U)] public byte APC_PWIDATAWR; [Simulator.Register(Offset=0x00000008U)] public byte APC_PWIDATAWD; [Simulator.Register(Offset=0x00000010U)] public byte APC_CONTROL; [Simulator.Register(Offset=0x00000014U)] public byte APC_STATUS; [Simulator.Register(Offset=0x00000018U)] public byte APC_MINVDD_LIMIT; [Simulator.Register(Offset=0x0000001CU)] public byte APC_VDDCHK; [Simulator.Register(Offset=0x00000020U)] public byte APC_VDDCHKD; [Simulator.Register(Offset=0x00000024U)] public byte APC_PREDLYSEL; [Simulator.Register(Offset=0x00000028U)] public byte APC_IMASK; [Simulator.Register(Offset=0x0000002CU)] public byte APC_ISTATUS; [Simulator.Register(Offset=0x00000030U)] public byte APC_ICLEAR; [Simulator.Register(Offset=0x00000034U)] public byte APC_UNSH_NOISE; [Simulator.Register(Offset=0x00000038U)] public byte APC_WKUP_DLY; [Simulator.Register(Offset=0x0000003CU)] public byte APC_SLK_SMP; [Simulator.Register(Offset=0x00000040U)] public byte APC_CLKDIV_PWICLK; [Simulator.Register(Offset=0x00000050U)] public byte APC_OVSHT_LMT; [Simulator.Register(Offset=0x00000054U)] public byte APC_CLP_CTRL; [Simulator.Register(Offset=0x00000058U)] public byte APC_SS_SRATE; [Simulator.Register(Offset=0x0000005CU)] public byte APC_IGAIN4; [Simulator.Register(Offset=0x00000060U)] public byte APC_IGAIN1; [Simulator.Register(Offset=0x00000064U)] public byte APC_IGAIN2; [Simulator.Register(Offset=0x00000068U)] public byte APC_IGAIN3; [Simulator.Register(Offset=0x0000006CU)] public byte APC_ITSTCTRL; [Simulator.Register(Offset=0x00000070U)] public byte APC_ITSTIP1; [Simulator.Register(Offset=0x00000074U)] public byte APC_ITSTIP2; [Simulator.Register(Offset=0x00000078U)] public byte APC_ITSTOP1; [Simulator.Register(Offset=0x0000007CU)] public byte APC_ITSTOP2; [Simulator.Register(Offset=0x00000080U)] public byte APC_PL1_CALCODE; [Simulator.Register(Offset=0x00000084U)] public byte APC_PL2_CALCODE; [Simulator.Register(Offset=0x00000088U)] public byte APC_PL3_CALCODE; [Simulator.Register(Offset=0x0000008CU)] public byte APC_PL4_CALCODE; [Simulator.Register(Offset=0x00000090U)] public byte APC_PL5_CALCODE; [Simulator.Register(Offset=0x00000094U)] public byte APC_PL6_CALCODE; [Simulator.Register(Offset=0x00000098U)] public byte APC_PL7_CALCODE; [Simulator.Register(Offset=0x0000009CU)] public byte APC_PL8_CALCODE; [Simulator.Register(Offset=0x000000A0U)] public byte APC_PL1_COREVDD; [Simulator.Register(Offset=0x000000A4U)] public byte APC_PL2_COREVDD; [Simulator.Register(Offset=0x000000A8U)] public byte APC_PL3_COREVDD; [Simulator.Register(Offset=0x000000ACU)] public byte APC_PL4_COREVDD; [Simulator.Register(Offset=0x000000B0U)] public byte APC_PL5_COREVDD; [Simulator.Register(Offset=0x000000B4U)] public byte APC_PL6_COREVDD; [Simulator.Register(Offset=0x000000B8U)] public byte APC_PL7_COREVDD; [Simulator.Register(Offset=0x000000BCU)] public byte APC_PL8_COREVDD; [Simulator.Register(Offset=0x000000C0U)] public byte APC_RET_VDD; [Simulator.Register(Offset=0x000000C4U)] public byte APC_INTEGRATION_TEST_REG; [Simulator.Register(Offset=0x000000E0U)] public byte APC_DBG_DLYCODE; [Simulator.Register(Offset=0x000000FCU)] public byte APC_REV; } // // Internal memory. // public class RamMemoryHandler : Simulator.MemoryHandler { // // State // private ulong m_lastWrite = 0; // // Constructor Methods // public RamMemoryHandler() { } //--// // // Helper Methods // public override void Initialize( Simulator owner , ulong rangeLength , uint rangeWidth , uint readLatency , uint writeLatency ) { base.Initialize( owner, rangeLength, rangeWidth, readLatency, writeLatency ); for(int i = 0; i < m_target.Length; i++) { m_target[i] = 0xDEADBEEF; } } public override void UpdateClockTicksForLoad( uint address , TargetAdapterAbstractionLayer.MemoryAccessType kind ) { uint latency = m_readLatency; if(m_owner.ClockTicks == m_lastWrite) latency++; // See Ollie Spec on Read-After-Write. UpdateClocks( latency, kind ); } public override void UpdateClockTicksForStore( uint address , TargetAdapterAbstractionLayer.MemoryAccessType kind ) { m_lastWrite = m_owner.ClockTicks + 1; UpdateClocks( m_writeLatency, kind ); } } // // 16KB cache memory // public class CacheMemoryHandler : Simulator.AddressSpaceBusHandler { const uint CacheableMask = 0x80000000u; const uint FlushMask = 0x40000000u; const int c_Ways_Log = 2; const int c_SetSize_Log = 8; // 16KB - Use 7 for 8KB. const int c_LineSize_Log = 2; // 4 words const int c_WordSize_Log = 2; const int c_LruSize_Log = 2; const int c_WaySize_Log = (c_SetSize_Log + c_LineSize_Log); const int c_Ways = (1 << c_Ways_Log ); const uint c_WordsInLine = (1u << c_LineSize_Log); const uint c_WaySize_Mask = ((1u << c_WaySize_Log ) - 1u); const uint c_SetSize_Mask = ((1u << c_SetSize_Log ) - 1u); const uint c_LineSize_Mask = ((1u << c_LineSize_Log) - 1u); const uint c_WordSize_Mask = ((1u << c_WordSize_Log) - 1u); const uint c_LruSize_Mask = ((1u << c_LruSize_Log ) - 1u); // // State // private bool m_fEnabled; private bool m_fFlushEnabled; private bool m_fResettingTags; private ulong[] m_cacheReady; private uint[] m_cacheData; private uint[] m_cacheTag; private uint[] m_cacheLRU; private uint[] m_cacheMap_LRUxWAY_LRU; private uint[] m_cacheMap_LRU_WAY; private ulong m_cache_LastBusActivity; // // Constructor Methods // public CacheMemoryHandler() { ResetCache(); } //--// // // Helper Methods // public override bool CanAccess( uint address , uint relativeAddress , TargetAdapterAbstractionLayer.MemoryAccessType kind ) { uint uncachedAddress = GetUncacheableAddress( address ); return base.CanAccess( uncachedAddress, uncachedAddress, kind ); } public override uint Read( uint address , uint relativeAddress , TargetAdapterAbstractionLayer.MemoryAccessType kind ) { uint uncachedAddress = GetUncacheableAddress( address ); uint res; if(m_owner.AreTimingUpdatesEnabled) { if(m_fEnabled && uncachedAddress != address) { if(m_fFlushEnabled) { if((address & FlushMask) != 0) { return 0; } } uint latency = ComputeCacheLatency( address, out res ); // // If there's a detour installed at this spot, read the redirected value!! // if(res == Simulator.TrackDetour.c_DetourOpcode && kind != TargetAdapterAbstractionLayer.MemoryAccessType.FETCH) { res = m_owner.HandleDetour( address , res ); res = m_owner.HandleDetour( uncachedAddress, res ); } UpdateClocks( latency, TargetAdapterAbstractionLayer.MemoryAccessType.UINT32 ); switch(kind) { case TargetAdapterAbstractionLayer.MemoryAccessType.UINT8: { uint shift = (address % 4) * 8; return (uint)((byte)(res >> (int)shift)); } case TargetAdapterAbstractionLayer.MemoryAccessType.UINT16: { uint shift = (address % 4) * 8; return (uint)((ushort)(res >> (int)shift)); } case TargetAdapterAbstractionLayer.MemoryAccessType.UINT32: case TargetAdapterAbstractionLayer.MemoryAccessType.SINT32: case TargetAdapterAbstractionLayer.MemoryAccessType.FETCH: { return res; } case TargetAdapterAbstractionLayer.MemoryAccessType.SINT8: { uint shift = (address % 4) * 8; return (uint)(int)((sbyte)(res >> (int)shift)); } case TargetAdapterAbstractionLayer.MemoryAccessType.SINT16: { uint shift = (address % 4) * 8; return (uint)(int)((short)(res >> (int)shift)); } default: throw new NotSupportedException(); } } } res = base.Read( uncachedAddress, uncachedAddress, kind ); // // If there's a detour installed at this spot, read the redirected value!! // if(res == Simulator.TrackDetour.c_DetourOpcode && kind != TargetAdapterAbstractionLayer.MemoryAccessType.FETCH) { res = m_owner.HandleDetour( address , res ); res = m_owner.HandleDetour( uncachedAddress, res ); } return res; } public override void Write( uint address , uint relativeAddress , uint value , TargetAdapterAbstractionLayer.MemoryAccessType kind ) { uint uncachedAddress = GetUncacheableAddress( address ); if(m_owner.AreTimingUpdatesEnabled) { if(m_fResettingTags) { // // The Cache Tag Reset bit resets to 1. This control bit is active low. // A 1 indicates normal cache tag operation. // When 0, indicates that a cache tag initialization is in progress. // Software should set this bit to 0 to enable resetting of the cache tags and then set this back to a 1 to resume normal operation. // Setting this bit to zero remaps memory byte writes to addresses tarting at 0x0000_0000 to write to the cache tag memory rather // than to normal memory. All four tag lines in a set are reset on carrying out a single write. // switch(kind) { case TargetAdapterAbstractionLayer.MemoryAccessType.UINT8: case TargetAdapterAbstractionLayer.MemoryAccessType.SINT8: // // Absorb byte writes. // UpdateClockTicksForStore( address, kind ); return; } } if(m_fEnabled && uncachedAddress != address) { if(m_fFlushEnabled) { if((address & FlushMask) != 0) { FlushAddress( address ); return; } } uint data; uint latency = ComputeCacheLatency( address, out data ); Simulator.TimingState backup = new Simulator.TimingState(); m_owner.SuspendTimingUpdates( ref backup ); UpdateCacheValue( address, value ); base.Write( uncachedAddress, uncachedAddress, value, kind ); m_owner.ResumeTimingUpdates( ref backup ); UpdateClocks( latency, TargetAdapterAbstractionLayer.MemoryAccessType.UINT32 ); return; } } if(uncachedAddress != address) { UpdateCacheValue( address, value ); } base.Write( uncachedAddress, uncachedAddress, value, kind ); } public override uint GetPhysicalAddress( uint address ) { return GetUncacheableAddress( address ); } //--// private void ResetCache() { m_cacheReady = new ulong[1 << (c_Ways_Log + c_SetSize_Log + c_LineSize_Log)]; m_cacheData = new uint [1 << (c_Ways_Log + c_SetSize_Log + c_LineSize_Log)]; m_cacheTag = new uint [1 << (c_Ways_Log + c_SetSize_Log )]; m_cacheLRU = new uint [1 << ( c_SetSize_Log )]; m_cacheMap_LRUxWAY_LRU = new uint [1 << (c_Ways_Log + c_LruSize_Log * c_Ways )]; m_cacheMap_LRU_WAY = new uint [1 << ( c_LruSize_Log * c_Ways )]; for(int i = 0 ; i < m_cacheTag.Length; i++) { m_cacheTag[i] = 0xFFFFFFFFu; } for(int i = 0 ; i < m_cacheMap_LRUxWAY_LRU.Length; i++) { m_cacheMap_LRUxWAY_LRU[i] = 0xFFFFFFFFu; } for(int i = 0 ; i < m_cacheMap_LRU_WAY.Length; i++) { m_cacheMap_LRU_WAY[i] = 0xFFFFFFFFu; } } private uint ComputeCacheLatency( uint address , out uint result ) { // // Align to word boundary. // address = address & ~(4u-1u); uint wordAddress = address >> c_WordSize_Log; uint tagAddress = ExtractTagAddress( wordAddress ); uint tag = ExtractTag ( wordAddress ); uint tagIdx = tagAddress << c_Ways_Log; int way; // // Do we have a hit? // for(way = 0; way < c_Ways; way++) { if(m_cacheTag[tagIdx + way] == tag) { // // Hit. // uint cacheAddress = ExtractCacheAddress( wordAddress, way ); long diff = (long)m_cacheReady[cacheAddress] - (long)m_owner.ClockTicks; result = m_cacheData[cacheAddress]; // // Update LRU // UpdateLRU( ref m_cacheLRU[tagAddress], way ); // // Already filled. // if(diff <= 0) { return 1; } else { return (uint)diff; } } } //--// // // Select LRU way. // SelectWay( ref m_cacheLRU[tagAddress], out way ); // // Update memories. // //// if(m_cacheTag[tagIdx + way] != 0xFFFFFFFFu) //// { //// Hosting.OutputSink sink; m_owner.GetHostingService( out sink ); //// if(sink != null) //// { //// uint oldLine; //// uint newLine; //// //// oldLine = m_cacheTag[tagIdx + way] << (c_WaySize_Log + c_WordSize_Log); //// oldLine |= tagAddress << (c_LineSize_Log + c_WordSize_Log); //// //// newLine = tag << (c_WaySize_Log + c_WordSize_Log); //// newLine |= tagAddress << (c_LineSize_Log + c_WordSize_Log); //// //// sink.OutputLine( "Evicting {0:X8} for {1:X8} at {2}", oldLine, newLine, m_owner.ClockTicks ); //// } //// } m_cacheTag[tagIdx + way] = tag; { uint cacheAddress = ExtractCacheAddress( wordAddress, way ); ulong ready = m_owner.ClockTicks; if(ready < m_cache_LastBusActivity) ready = m_cache_LastBusActivity; uint waitStates = 0; Simulator.TimingState backup = new Simulator.TimingState(); m_owner.SaveTimingUpdates( ref backup ); result = 0; for(int word = 0; word < c_WordsInLine; word++) { ulong clockStart = m_owner.ClockTicks; uint data = m_owner.Load( GetUncacheableAddress( address ), TargetAdapterAbstractionLayer.MemoryAccessType.UINT32 ); uint accessTime = (uint)(m_owner.ClockTicks - clockStart); if(word == 0) { waitStates = accessTime; result = data; } ready += accessTime; m_cacheReady[cacheAddress] = ready; m_cacheData [cacheAddress] = data; address = WrapAddress( address , 4, 4 * c_WordsInLine ); cacheAddress = WrapAddress( cacheAddress, 1, c_WordsInLine ); } m_owner.RestoreTimingUpdates( ref backup ); m_cache_LastBusActivity = ready; return waitStates; } } private void FlushAddress( uint address ) { if(m_owner.AreTimingUpdatesEnabled == false) { return; } uint wordAddress = address >> c_WordSize_Log; uint tagAddress = ExtractTagAddress( wordAddress ); uint tag = ExtractTag ( wordAddress ); uint tagIdx = tagAddress << c_Ways_Log; int way; // // Do we have a hit? // for(way = 0; way < c_Ways; way++) { if(m_cacheTag[tagIdx + way] == tag) { // // Invalidate line. // m_cacheTag[tagIdx + way] = 0xFFFFFFFFu; break; } } } private void UpdateCacheValue( uint address , uint value ) { // // Align to word boundary. // address = address & ~(4u-1u); uint wordAddress = address >> c_WordSize_Log; uint tagAddress = ExtractTagAddress( wordAddress ); uint tag = ExtractTag ( wordAddress ); uint tagIdx = tagAddress << c_Ways_Log; int way; // // Do we have a hit? // for(way = 0; way < c_Ways; way++) { if(m_cacheTag[tagIdx + way] == tag) { // // Hit. // uint cacheAddress = ExtractCacheAddress( wordAddress, way ); m_cacheData[cacheAddress] = value; } } } private void SelectWay( ref uint LRU , out int way ) { #if OLLIE_USE_CACHE_PSEUDO_LRU SelectWay__PseudoLRU( ref LRU, out way ); #else SelectWay__ReadLRU( ref LRU, out way ); #endif } private void SelectWay__PseudoLRU( ref uint LRU , out int way ) { // bit 5 = A or B // bit 4 = A or C // bit 3 = A or D // bit 2 = B or C // bit 1 = B or D // bit 0 = C or D // If there's an access to A, you write "000xxx". (fifth bit, fourth bit, ... zeroth bit) // If there's an access to B, you write "1xx00x". // If there's an access to C, you write "x1x1x0". // If there's an access to D, you write "xx1x11". // // Then at cache-miss, you use sets of 3 bits to determine the LRU // there should not be ambiguity, but we don't check that // uint localLRU = LRU; if ((localLRU & 0x38) == 0x38) way = 0; // LRU == A else if((localLRU & 0x26) == 0x06) way = 1; else if((localLRU & 0x15) == 0x01) way = 2; else if((localLRU & 0x0B) == 0x00) way = 3; else way = 0; UpdateLRU__PseudoLRU( ref LRU, way ); } private void SelectWay__ReadLRU( ref uint LRU , out int way ) { uint newLRU = m_cacheMap_LRU_WAY[LRU]; if(newLRU == 0xFFFFFFFF) { uint minLRU = c_LruSize_Mask + 1; int minWay = 0; int idxWay; newLRU = 0; for(idxWay = 0; idxWay < c_Ways; idxWay++) { uint count = ExtractLRU( LRU, idxWay ); if(count < minLRU) { minLRU = count; minWay = idxWay; } } newLRU = (uint)(minWay << (c_LruSize_Log * c_Ways)); for(idxWay = 0; idxWay < c_Ways; idxWay++) { uint count = ExtractLRU( LRU, idxWay ); if(idxWay == minWay) { count = c_LruSize_Mask; } else if(count != 0 && count >= minLRU) { count--; } newLRU |= InsertLRU( count, idxWay ); } m_cacheMap_LRU_WAY[LRU] = newLRU; } way = (int)(newLRU >> (c_LruSize_Log * c_Ways)); LRU = newLRU & ((1 << (c_LruSize_Log * c_Ways)) - 1); } private void UpdateLRU( ref uint LRU , int way ) { #if OLLIE_USE_CACHE_PSEUDO_LRU UpdateLRU__PseudoLRU( ref LRU, way ); #else UpdateLRU__RealLRU( ref LRU, way ); #endif } private void UpdateLRU__PseudoLRU( ref uint LRU , int way ) { // bit 5 = A or B // bit 4 = A or C // bit 3 = A or D // bit 2 = B or C // bit 1 = B or D // bit 0 = C or D // If there's an access to A, you write "000xxx". (fifth bit, fourth bit, ... zeroth bit) // If there's an access to B, you write "1xx00x". // If there's an access to C, you write "x1x1x0". // If there's an access to D, you write "xx1x11". // uint newLRU = LRU; switch(way) { case 0: newLRU &= ~(0x38u); newLRU |= 0x00; break; case 1: newLRU &= ~(0x26u); newLRU |= 0x20; break; case 2: newLRU &= ~(0x15u); newLRU |= 0x14; break; case 3: newLRU &= ~(0x0Bu); newLRU |= 0x0B; break; } LRU = newLRU; } private void UpdateLRU__RealLRU( ref uint LRU , int way ) { uint newLRU = m_cacheMap_LRUxWAY_LRU[LRU | (uint)(way << (c_LruSize_Log * c_Ways))]; if(newLRU == 0xFFFFFFFF) { uint minLRU = ExtractLRU( LRU, way ); int idxWay; newLRU = 0; for(idxWay = 0; idxWay < c_Ways; idxWay++) { uint count = ExtractLRU( LRU, idxWay ); if(idxWay == way) { count = c_LruSize_Mask; } else if(count != 0 && count >= minLRU) { count--; } newLRU |= InsertLRU( count, idxWay ); } m_cacheMap_LRUxWAY_LRU[LRU | (uint)(way << (c_LruSize_Log * c_Ways))] = newLRU; } LRU = newLRU & ((1 << (c_LruSize_Log * c_Ways)) - 1); } //--// public static uint GetUncacheableAddress( uint address ) { return address & ~CacheableMask; } public static uint GetCacheableAddress( uint address ) { return address | CacheableMask; } private static uint ExtractTag( uint address ) { return (address >> (c_WaySize_Log)); } private static uint ExtractTagAddress( uint address ) { return ((address >> (c_LineSize_Log)) & c_SetSize_Mask); } private static uint ExtractCacheAddress( uint address , int way ) { return ((address & c_WaySize_Mask) + (uint)(way << c_WaySize_Log)); } private static uint WrapAddress( uint address , uint increment , uint maskSize ) { return (address & ~(maskSize-1)) | ((address + increment) & (maskSize-1)); } private static uint ExtractLRU( uint lru , int way ) { return ((lru >> (way * c_LruSize_Log)) & c_LruSize_Mask); } private static uint InsertLRU( uint lru , int way ) { return ((lru & c_LruSize_Mask) << (way * c_LruSize_Log)); } // // Access Methods // public bool Enabled { set { m_fEnabled = value; } } public bool ResettingTags { set { m_fResettingTags = value; if(m_fResettingTags) { ResetCache(); } } } public bool FlushEnabled { set { m_fFlushEnabled = value; } } } } } ================================================ FILE: Zelig/Zelig/DebugTime/ArmProcessorEmulation/Models/Chipset/PXA27x.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // namespace Microsoft.Zelig.Emulation.ArmProcessor.Chipset { using System; using System.Threading; using System.Collections.Generic; using EncDef = Microsoft.Zelig.TargetModel.ArmProcessor.EncodingDefinition; using ElementTypes = Microsoft.Zelig.MetaData.ElementTypes; using Cfg = Microsoft.Zelig.Configuration.Environment; public static partial class PXA27x { [Simulator.PeripheralRange( Base = 0x48000000U, Length = 0x00000068U, ReadLatency = 1, WriteLatency = 2 )] public class MCU : Simulator.Peripheral { public override void Write( uint address, uint relativeAddress, uint value, TargetAdapterAbstractionLayer.MemoryAccessType kind ) { } public override uint Read( uint address, uint relativeAddress, TargetAdapterAbstractionLayer.MemoryAccessType kind ) { return 0; } } [Simulator.PeripheralRange( Base = 0x44000000U, Length = 0x04000058U, ReadLatency = 1, WriteLatency = 2 )] public class LCD : Simulator.Peripheral { public override void Write( uint address, uint relativeAddress, uint value, TargetAdapterAbstractionLayer.MemoryAccessType kind ) { } public override uint Read( uint address, uint relativeAddress, TargetAdapterAbstractionLayer.MemoryAccessType kind ) { return 0; } } [Simulator.PeripheralRange( Base = 0x4C000000U, Length = 0x00000070U, ReadLatency = 1, WriteLatency = 2 )] public class USBHost : Simulator.Peripheral { public override void Write( uint address, uint relativeAddress, uint value, TargetAdapterAbstractionLayer.MemoryAccessType kind ) { } public override uint Read( uint address, uint relativeAddress, TargetAdapterAbstractionLayer.MemoryAccessType kind ) { return 0; } } [Simulator.PeripheralRange( Base = 0x50000000U, Length = 0x0000003CU, ReadLatency = 1, WriteLatency = 2 )] public class QuickCapture : Simulator.Peripheral { public override void Write( uint address, uint relativeAddress, uint value, TargetAdapterAbstractionLayer.MemoryAccessType kind ) { } public override uint Read( uint address, uint relativeAddress, TargetAdapterAbstractionLayer.MemoryAccessType kind ) { return 0; } } [Simulator.PeripheralRange( Base = 0x40000000U, Length = 0x0000112CU, ReadLatency = 1, WriteLatency = 2 )] public class DMA : Simulator.Peripheral { public override void Write( uint address, uint relativeAddress, uint value, TargetAdapterAbstractionLayer.MemoryAccessType kind ) { } public override uint Read( uint address, uint relativeAddress, TargetAdapterAbstractionLayer.MemoryAccessType kind ) { return 0; } } [Simulator.PeripheralRange( Base = 0x40100000U, Length = 0x00000030U, ReadLatency = 1, WriteLatency = 2 )] public class FFUART : Simulator.Peripheral { public override void Write( uint address, uint relativeAddress, uint value, TargetAdapterAbstractionLayer.MemoryAccessType kind ) { } public override uint Read( uint address, uint relativeAddress, TargetAdapterAbstractionLayer.MemoryAccessType kind ) { return 0; } } [Simulator.PeripheralRange( Base = 0x40200000U, Length = 0x00000030U, ReadLatency = 1, WriteLatency = 2 )] public class BTUART : Simulator.Peripheral { public override void Write( uint address, uint relativeAddress, uint value, TargetAdapterAbstractionLayer.MemoryAccessType kind ) { } public override uint Read( uint address, uint relativeAddress, TargetAdapterAbstractionLayer.MemoryAccessType kind ) { return 0; } } [Simulator.PeripheralRange( Base = 0x40301680U, Length = 0x00000028U, ReadLatency = 1, WriteLatency = 2 )] public class I2C : Simulator.Peripheral { public override void Write( uint address, uint relativeAddress, uint value, TargetAdapterAbstractionLayer.MemoryAccessType kind ) { } public override uint Read( uint address, uint relativeAddress, TargetAdapterAbstractionLayer.MemoryAccessType kind ) { return 0; } } [Simulator.PeripheralRange( Base = 0x40400000U, Length = 0x00000084U, ReadLatency = 1, WriteLatency = 2 )] public class I2S : Simulator.Peripheral { public override void Write( uint address, uint relativeAddress, uint value, TargetAdapterAbstractionLayer.MemoryAccessType kind ) { } public override uint Read( uint address, uint relativeAddress, TargetAdapterAbstractionLayer.MemoryAccessType kind ) { return 0; } } [Simulator.PeripheralRange( Base = 0x40500000U, Length = 0x00000600U, ReadLatency = 1, WriteLatency = 2 )] public class AC : Simulator.Peripheral { public override void Write( uint address, uint relativeAddress, uint value, TargetAdapterAbstractionLayer.MemoryAccessType kind ) { } public override uint Read( uint address, uint relativeAddress, TargetAdapterAbstractionLayer.MemoryAccessType kind ) { return 0; } } [Simulator.PeripheralRange( Base = 0x40600000U, Length = 0x00000460U, ReadLatency = 1, WriteLatency = 2 )] public class USBClient : Simulator.Peripheral { public override void Write( uint address, uint relativeAddress, uint value, TargetAdapterAbstractionLayer.MemoryAccessType kind ) { } public override uint Read( uint address, uint relativeAddress, TargetAdapterAbstractionLayer.MemoryAccessType kind ) { return 0; } } [Simulator.PeripheralRange( Base = 0x40700000U, Length = 0x00000030U, ReadLatency = 1, WriteLatency = 2 )] public class UART : Simulator.Peripheral { public override void Write( uint address, uint relativeAddress, uint value, TargetAdapterAbstractionLayer.MemoryAccessType kind ) { } public override uint Read( uint address, uint relativeAddress, TargetAdapterAbstractionLayer.MemoryAccessType kind ) { return 0; } } [Simulator.PeripheralRange( Base = 0x40800000U, Length = 0x00000020U, ReadLatency = 1, WriteLatency = 2 )] public class IR : Simulator.Peripheral { public override void Write( uint address, uint relativeAddress, uint value, TargetAdapterAbstractionLayer.MemoryAccessType kind ) { } public override uint Read( uint address, uint relativeAddress, TargetAdapterAbstractionLayer.MemoryAccessType kind ) { return 0; } } [Simulator.PeripheralRange( Base = 0x40900000U, Length = 0x0000003CU, ReadLatency = 1, WriteLatency = 2 )] public class RTC : Simulator.Peripheral { public override void Write( uint address, uint relativeAddress, uint value, TargetAdapterAbstractionLayer.MemoryAccessType kind ) { } public override uint Read( uint address, uint relativeAddress, TargetAdapterAbstractionLayer.MemoryAccessType kind ) { return 0; } } [Simulator.PeripheralRange( Base = 0x40A00000U, Length = 0x000000E0U, ReadLatency = 1, WriteLatency = 2 )] public class Timers : Simulator.Peripheral { public class TimerCntReg : Simulator.Peripheral { [Simulator.LinkToContainer] public Timers Parent; [Simulator.Register( Offset = 0x00000000U )] public virtual uint Counter { get { return (uint)(Parent.GetCurrentTime() - m_base); } set { m_base = Parent.GetCurrentTime() - value; Parent.Evaluate(); } } protected ulong m_base; } public class TimerCnt0Reg : TimerCntReg { [Simulator.Register( Offset = 0x00000000U )] public override uint Counter { get { return (uint)( Parent.GetCurrentTicks() - m_base ); } set { m_base = Parent.GetCurrentTicks() - value; Parent.Evaluate(); } } } public class TimerMchReg : Simulator.Peripheral { [Simulator.LinkToContainer] public Timers Parent; [Simulator.Register( Offset = 0x00000000U )] public uint Match { get { return m_match; } set { m_isMatched = false; m_isEnabled = false; m_match = value; Parent.Evaluate(); } } public void RegisterForCallback( Hosting.DeviceClockTicksTracking svc, long matchValue ) { m_isEnabled = true; //svc.CancelClockTickCallback( Callback ); svc.RequestRelativeClockTickCallback( matchValue, Callback ); } public void CancelCallback( Hosting.DeviceClockTicksTracking svc ) { m_isEnabled = false; svc.CancelClockTickCallback( Callback ); } private void Callback() { m_isMatched = true; Parent.Evaluate(); } public bool IsMatched { get { return m_isMatched; } set { m_isMatched = value; } } public bool IsEnabled { get { return m_isEnabled; } } private bool m_isMatched; private bool m_isEnabled; private uint m_match; } public class TimerCtrlReg : Simulator.Peripheral { [Simulator.LinkToContainer] public Timers Parent; [Simulator.Register( Offset = 0x00000000U )] public uint Control { get { return m_control; } set { m_control = value; Parent.Evaluate(); } } private uint m_control; } int[] m_interruptIndexTable = new int[12]; uint m_timerIntEnable = 0; uint m_status = 0; double m_convertFromCpuTicks; double m_convertToCpuTicks; bool m_fInterruptDisable = false; [Simulator.LinkToPeripheral()] public INTC InterruptController; [Simulator.Register( Offset = 0x00000000U, Size = 0x04U, Instances = 4 )] public TimerMchReg[] OSMR0; [Simulator.Register( Offset = 0x00000010U, Size = 0x04U, Instances = 1 )] public TimerCnt0Reg[] OSCR0; // Main count register (for OSMR0-3) [Simulator.Register( Offset = 0x00000014U )] public uint OSSR // Status register { get { return m_status; } set { // status register for all counters m_status &= ~value; uint val = value; int idx = -1; while(val != 0) { idx++; val >>= 1; } if(idx < 0 || idx >= OSMR.Length) return; if(idx < 4) { OSMR0[idx].IsMatched = false; } else { OSMR[idx - 4].IsMatched = false; } InterruptController.Reset( m_interruptIndexTable[idx] ); Evaluate(); } } [Simulator.Register( Offset = 0x00000018U )] public uint OWER; // Watchdog enable register [Simulator.Register( Offset = 0x0000001CU )] public uint OIER // interrupt enable register { get { return m_timerIntEnable; } set { m_timerIntEnable = value; Evaluate(); } } [Simulator.Register( Offset = 0x00000020U )] public uint OSNR; // snapshot register [Simulator.Register( Offset = 0x00000040U, Size = 0x04U, Instances = 8 )] public TimerCntReg[] OSCR; [Simulator.Register( Offset = 0x00000080U, Size = 0x04U, Instances = 8)] public TimerMchReg[] OSMR; [Simulator.Register( Offset = 0x000000C0U, Size = 0x04U, Instances = 8 )] public TimerCtrlReg[] OMCR; public Timers() { int []timerInts = new int[] { (int)INTC.c_IRQ_INDEX_OS_TIMER0, (int)INTC.c_IRQ_INDEX_OS_TIMER1, (int)INTC.c_IRQ_INDEX_OS_TIMER2, (int)INTC.c_IRQ_INDEX_OS_TIMER3, }; for(int i = 0; i < m_interruptIndexTable.Length; i++) { if(i < timerInts.Length) { m_interruptIndexTable[i] = timerInts[i]; } else { m_interruptIndexTable[i] = (int)INTC.c_IRQ_INDEX_OS_TIMER; } } } public override void OnConnected() { base.OnConnected(); Cfg.ProcessorCategory proc = m_owner.Product.SearchValue(); m_convertFromCpuTicks = (double)proc.RealTimeClockFrequency / (double)proc.CoreClockFrequency; m_convertToCpuTicks = (double)proc.CoreClockFrequency / (double)proc.RealTimeClockFrequency; } internal ulong GetCurrentTicks() { return m_owner.ClockTicks; } internal ulong GetCurrentTime() { return ConvertFromCpuTicks( m_owner.ClockTicks ); } internal void Evaluate() { if(m_fInterruptDisable) { this.InterruptController.Reset( 0 ); } else { Hosting.DeviceClockTicksTracking svc; m_owner.GetHostingService( out svc ); for(int i = 0; i < 12; i++) { TimerMchReg regMatch = i < 4 ? OSMR0[i] : OSMR[i-4]; if(0 != ( m_timerIntEnable & ( 1u << i ) )) { TimerCntReg regCount; if(i < 4) { regCount = OSCR0[0]; } else if(i < 8) { if(( OMCR[i - 4].Control & ( 1u << 7 ) ) == 0) { regCount = OSCR[0]; } else { regCount = OSCR[i - 4]; } } else { if(( OMCR[i - 4].Control & ( 1u << 7 ) ) == 0) { regCount = OSCR[8 - 4]; } else { regCount = OSCR[i - 4]; } } if(regMatch.IsMatched || !regMatch.IsEnabled) { int diff = (int)( regMatch.Match - regCount.Counter ); if(regMatch.IsMatched || diff == 0) { m_status |= 1u << i; regMatch.IsMatched = false; this.InterruptController.Set( m_interruptIndexTable[i] ); } if(diff <= 0) { if(!regMatch.IsEnabled) // overlap { if(i < 4) { regMatch.RegisterForCallback( svc, regCount.Counter - regMatch.Match + uint.MaxValue ); } else { regMatch.RegisterForCallback( svc, ConvertToCpuTicks( uint.MaxValue - ( regCount.Counter - regMatch.Match ) ) ); } } } else if(!regMatch.IsEnabled) { this.InterruptController.Reset( m_interruptIndexTable[i] ); if(i < 4) { regMatch.RegisterForCallback( svc, diff ); } else { regMatch.RegisterForCallback( svc, ConvertToCpuTicks( diff ) ); } } } } else if(regMatch.IsEnabled) { regMatch.CancelCallback( svc ); } } } } //--// private ulong ConvertFromCpuTicks( ulong ticks ) { return (ulong)( ticks * m_convertFromCpuTicks ); } private long ConvertToCpuTicks( long ticks ) { return (long)( ticks * m_convertToCpuTicks ); } } [Simulator.PeripheralRange( Base = 0x40B00000U, Length = 0x00000020U, ReadLatency = 1, WriteLatency = 2 )] public class PWM : Simulator.Peripheral { public override void Write( uint address, uint relativeAddress, uint value, TargetAdapterAbstractionLayer.MemoryAccessType kind ) { } public override uint Read( uint address, uint relativeAddress, TargetAdapterAbstractionLayer.MemoryAccessType kind ) { return 0; } } [Simulator.PeripheralRange( Base = 0x40D00000U, Length = 0x000000D0U, ReadLatency = 1, WriteLatency = 2 )] public class INTC : Simulator.Peripheral { public const uint c_IRQ_INDEX_SSP_3 = 0; public const uint c_IRQ_INDEX_MSL = 1; public const uint c_IRQ_INDEX_USB_HOST_2 = 2; public const uint c_IRQ_INDEX_USB_HOST_1 = 3; public const uint c_IRQ_INDEX_KEYPAD_CTRL = 4; public const uint c_IRQ_INDEX_MEMORY_STICK = 5; public const uint c_IRQ_INDEX_PWR_I2C = 6; public const uint c_IRQ_INDEX_OS_TIMER = 7; public const uint c_IRQ_INDEX_GPIO0 = 8; public const uint c_IRQ_INDEX_GPIO1 = 9; public const uint c_IRQ_INDEX_GPIOx = 10; public const uint c_IRQ_INDEX_USB_CLIENT = 11; public const uint c_IRQ_INDEX_PMU = 12; public const uint c_IRQ_INDEX_I2S = 13; public const uint c_IRQ_INDEX_AC97 = 14; public const uint c_IRQ_INDEX_USIM = 15; public const uint c_IRQ_INDEX_SSP_2 = 16; public const uint c_IRQ_INDEX_LCD = 17; public const uint c_IRQ_INDEX_I2C = 18; public const uint c_IRQ_INDEX_INFRA_RED_COM = 19; public const uint c_IRQ_INDEX_STUART = 20; public const uint c_IRQ_INDEX_BTUART = 21; public const uint c_IRQ_INDEX_FFUART = 22; public const uint c_IRQ_INDEX_FLASH_CARD = 23; public const uint c_IRQ_INDEX_SSP_1 = 24; public const uint c_IRQ_INDEX_DMA_CTRL = 25; public const uint c_IRQ_INDEX_OS_TIMER0 = 26; public const uint c_IRQ_INDEX_OS_TIMER1 = 27; public const uint c_IRQ_INDEX_OS_TIMER2 = 28; public const uint c_IRQ_INDEX_OS_TIMER3 = 29; public const uint c_IRQ_INDEX_RTC_1HZ_TIC = 30; public const uint c_IRQ_INDEX_RTC_ALARM = 31; public const uint c_IRQ_INDEX_TRUSTED_PLFM = 32; public const uint c_IRQ_INDEX_QK_CAP = 33; private uint m_inputStatus1 = 0; private uint m_inputStatus2 = 0; private uint m_irqMask1 = 0; private uint m_irqMask2 = 0; private uint m_levelInt1 = 0; private uint m_levelInt2 = 0; public class INTCPriReg : Simulator.Peripheral { [Simulator.LinkToContainer] public INTC Parent; [Simulator.Register( Offset = 0x00000000U )] public uint Priority; } public void Set( int index ) { if(index > 31) { index -= 32; uint oldStatus = m_inputStatus2; m_inputStatus2 |= 1U << index; if(m_inputStatus2 != oldStatus) { Evaluate(m_inputStatus2); } } else { uint oldStatus = m_inputStatus1; m_inputStatus1 |= 1U << index; if(m_inputStatus1 != oldStatus) { Evaluate(m_inputStatus1); } } } public void Reset( int index ) { if(index > 31) { index -= 32; uint oldStatus = m_inputStatus2; m_inputStatus2 &= ~(1U << index); if(m_inputStatus2 != oldStatus) { Evaluate( m_inputStatus2 ); } } else { uint oldStatus = m_inputStatus1; m_inputStatus1 &= ~( 1U << index ); if(m_inputStatus1 != oldStatus) { Evaluate( m_inputStatus1 ); } } } public void Evaluate(uint status) { m_owner.SetIrqStatus( status != 0 ); } [Simulator.Register( Offset = 0x00000000U )] public uint ICIP // IRQ Pending register { get { return m_irqMask1 & m_inputStatus1; } } [Simulator.Register( Offset = 0x00000004U )] public uint ICMR // Mask register { get { return m_irqMask1; } set { // status register for all counters m_irqMask1 = value; Evaluate( m_irqMask1 & m_inputStatus1 ); } } [Simulator.Register( Offset = 0x00000008U )] public uint ICLR // level register { get { return m_levelInt1; } set { uint old = m_levelInt1; m_levelInt1 = value; old ^= m_levelInt1; int idx = 0; while(old != 0) { if(0 != ( old & 1 )) Set( idx ); idx++; old >>= 1; } } } [Simulator.Register( Offset = 0x0000000CU )] public uint ICFP; // FIQ pending register [Simulator.Register( Offset = 0x00000010U )] public uint ICPR; // IRQ pending register [Simulator.Register( Offset = 0x00000014U )] public uint ICCR; // control register [Simulator.Register( Offset = 0x00000018U )] public uint ICHP // Highest Priority register { get { if(( m_irqMask1 & m_inputStatus1 ) != 0) { uint ichp = 0x80000000; int i = 0; while(0 == ( ( 1u << i ) & m_inputStatus1 )) i++; ichp |= (uint)i << 16; m_inputStatus1 &= ~( 1u << i ); m_owner.SetIrqStatus( m_inputStatus1 != 0 && m_inputStatus2 != 0 ); return ichp; } else if(( m_irqMask2 & m_inputStatus2 ) != 0) { uint ichp = 0x80000000; int i = 0; while(0 == ( ( 1u << i ) & m_inputStatus2 )) i++; ichp |= (uint)( i + 32 ) << 16; m_inputStatus2 &= ~( 1u << i ); m_owner.SetIrqStatus( m_inputStatus1 != 0 && m_inputStatus2 != 0 ); return ichp; } else { UpdateClocks( 8000, TargetAdapterAbstractionLayer.MemoryAccessType.FETCH ); } return 0; } } [Simulator.Register( Offset = 0x0000001CU, Size = 0x04U, Instances = 32 )] public INTCPriReg[] IPR; // IRQ pending register [Simulator.Register( Offset = 0x0000009CU )] public uint ICIP2 // IRQ pending register 2 { get { return m_irqMask2 & m_inputStatus2; } } [Simulator.Register( Offset = 0x000000A0U )] public uint ICMR2 // Mask register 2 { get { return m_irqMask2; } set { // status register for all counters m_irqMask2 = value; Evaluate( m_irqMask2 & m_inputStatus2 ); } } [Simulator.Register( Offset = 0x000000A4U )] public uint ICLR2 // Level register 2 { get { return m_levelInt2; } set { uint old = m_levelInt2; m_levelInt2 = value; old ^= m_levelInt2; int idx = 0; while(old != 0) { if(0 != ( old & 1 )) Set( idx ); idx++; old >>= 1; } } } [Simulator.Register( Offset = 0x000000A8U )] public uint ICFP2; // FIQ pending register 2 [Simulator.Register( Offset = 0x000000ACU )] public uint ICPR2; // IRQ pending register 2 [Simulator.Register( Offset = 0x000000B0U, Size = 0x04U, Instances = 8 )] public INTCPriReg IPR2; // Priority register 2 } [Simulator.PeripheralRange( Base = 0x40E00000U, Length = 0x0000014CU, ReadLatency = 1, WriteLatency = 2 )] public class GPIO : Simulator.Peripheral { public override void Write( uint address, uint relativeAddress, uint value, TargetAdapterAbstractionLayer.MemoryAccessType kind ) { } public override uint Read( uint address, uint relativeAddress, TargetAdapterAbstractionLayer.MemoryAccessType kind ) { return 0; } } [Simulator.PeripheralRange( Base = 0x40F00000U, Length = 0x00000100U, ReadLatency = 1, WriteLatency = 2 )] public class PMR : Simulator.Peripheral { public override void Write( uint address, uint relativeAddress, uint value, TargetAdapterAbstractionLayer.MemoryAccessType kind ) { } public override uint Read( uint address, uint relativeAddress, TargetAdapterAbstractionLayer.MemoryAccessType kind ) { return 0; } } [Simulator.PeripheralRange( Base = 0x41300000U, Length = 0x00000010U, ReadLatency = 1, WriteLatency = 2 )] public class ClockMgr : Simulator.Peripheral { [Simulator.Register( Offset = 0x00000000U )] public uint CCCR; // Core clock configation register [Simulator.Register( Offset = 0x00000004U )] public uint CKEN; // Clock enable register [Simulator.Register( Offset = 0x00000008U )] public uint OSCC; // Oscillator configuration register const uint CCSR__CPLCK = 0x20000000; // Core PLL lock const uint CCSR__PPLCK = 0x10000000; // Peripheral PLL lock [Simulator.Register( Offset = 0x0000000CU )] public uint CCSR = CCSR__CPLCK | CCSR__PPLCK; // Clock enable register public override void OnConnected() { base.OnConnected(); // // Map FLASH to 0x00000000. Clock is enabled early so do the remap here // Simulator.AddressSpaceHandler hnd = m_owner.FindMemoryAtAddress( 0x5c000000u ); if(hnd != null) { hnd.LinkAtAddress( 0 ); } } } // // Internal memory. // public class RamMemoryHandler : Simulator.MemoryHandler { // // State // private ulong m_lastWrite = 0; // // Constructor Methods // public RamMemoryHandler() { } //--// // // Helper Methods // public override void Initialize( Simulator owner, ulong rangeLength, uint rangeWidth, uint readLatency, uint writeLatency ) { base.Initialize( owner, rangeLength, rangeWidth, readLatency, writeLatency ); for(int i = 0; i < m_target.Length; i++) { m_target[i] = 0xDEADBEEF; } } public override void UpdateClockTicksForLoad( uint address, TargetAdapterAbstractionLayer.MemoryAccessType kind ) { uint latency = m_readLatency; if(m_owner.ClockTicks == m_lastWrite) latency++; // See Ollie Spec on Read-After-Write. UpdateClocks( latency, kind ); } public override void UpdateClockTicksForStore( uint address, TargetAdapterAbstractionLayer.MemoryAccessType kind ) { m_lastWrite = m_owner.ClockTicks + 1; UpdateClocks( m_writeLatency, kind ); } } // // FAKE cache memory // public class CacheMemoryHandler : Simulator.AddressSpaceBusHandler { const uint CacheableMask = 0x80000000u; // // Constructor Methods // public CacheMemoryHandler() { } //--// // // Helper Methods // public override bool CanAccess( uint address, uint relativeAddress, TargetAdapterAbstractionLayer.MemoryAccessType kind ) { uint uncachedAddress = GetUncacheableAddress( address ); return base.CanAccess( uncachedAddress, uncachedAddress, kind ); } public override uint Read( uint address, uint relativeAddress, TargetAdapterAbstractionLayer.MemoryAccessType kind ) { uint uncachedAddress = GetUncacheableAddress( address ); return base.Read( uncachedAddress, uncachedAddress, kind ); } public override void Write( uint address, uint relativeAddress, uint value, TargetAdapterAbstractionLayer.MemoryAccessType kind ) { uint uncachedAddress = GetUncacheableAddress( address ); base.Write( uncachedAddress, uncachedAddress, value, kind ); } public override uint GetPhysicalAddress( uint address ) { return GetUncacheableAddress( address ); } public static uint GetUncacheableAddress( uint address ) { return address & ~CacheableMask; } public static uint GetCacheableAddress( uint address ) { return address | CacheableMask; } } } } ================================================ FILE: Zelig/Zelig/DebugTime/ArmProcessorEmulation/Models/Display/SED15E0.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // #define PROFILE_FRAMERATE namespace Microsoft.Zelig.Emulation.ArmProcessor.Display { using System; using System.Collections.Generic; using EncDef = Microsoft.Zelig.TargetModel.ArmProcessor.EncodingDefinition; using ElementTypes = Microsoft.Zelig.MetaData.ElementTypes; //--// [Simulator.PeripheralRange(Base=0x20000000U,Length=0x00020000U,Latency=3)] [Simulator.PeripheralRange(Base=0xA0000000U,Length=0x00020000U,Latency=3)] public class SED15E0 : Simulator.Peripheral { public const uint CONTROL_DISPLAY_OFF = 0xAE; public const uint CONTROL_DISPLAY_ON = 0xAF; public const uint CONTROL_START_LINE_SET = 0x8A; // following by control write of start line 0-95 decimal public const uint CONTROL_PAGE_ADDRESS_SET = 0xB0; // with page address 0-12 in lower 4 bits public const uint CONTROL_COLUMN_ADDRESS_HI_NIBBLE_SET = 0x10; public const uint CONTROL_COLUMN_ADDRESS_LO_NIBBLE_SET = 0x00; // in sequence, high nibble, low nibble public const uint CONTROL_ADC_NORMAL = 0xA0; public const uint CONTROL_ADC_REVERSE = 0xA1; public const uint CONTROL_COMMON_SCAN_MODE_NORMAL = 0xC0; public const uint CONTROL_COMMON_SCAN_MODE_REVERSE = 0xC8; public const uint CONTROL_DISPLAY_NORMAL = 0xA6; public const uint CONTROL_DISPLAY_REVERSE = 0xA7; public const uint CONTROL_DISPLAY_ALL_POINTS_OFF = 0xA4; public const uint CONTROL_DISPLAY_ALL_POINTS_ON = 0xA5; public const uint CONTROL_nLINE_INVERSION_DRIVE = 0x30; // lower 4 bits are No. of inverse lines, 0,8,12,...60,64 for 0-15 value public const uint CONTROL_nLINE_INVERSION_CANCEL = 0xE4; public const uint CONTROL_DUTY_RATIO_SET = 0x60; // lower 5 bits are duty ratio, from 0=1/8 to 0x18=1/100 // 1/100 is default after reset //// public const uint DUTY_RATIO(r) ((r >> 2) - 1) public const uint DUTY_RATIO_008_TO_1 = 0x01; public const uint DUTY_RATIO_012_TO_1 = 0x02; public const uint DUTY_RATIO_016_TO_1 = 0x03; public const uint DUTY_RATIO_020_TO_1 = 0x04; public const uint DUTY_RATIO_024_TO_1 = 0x05; public const uint DUTY_RATIO_028_TO_1 = 0x06; public const uint DUTY_RATIO_032_TO_1 = 0x07; public const uint DUTY_RATIO_036_TO_1 = 0x08; public const uint DUTY_RATIO_040_TO_1 = 0x09; public const uint DUTY_RATIO_044_TO_1 = 0x0A; public const uint DUTY_RATIO_048_TO_1 = 0x0B; public const uint DUTY_RATIO_052_TO_1 = 0x0C; public const uint DUTY_RATIO_056_TO_1 = 0x0D; public const uint DUTY_RATIO_060_TO_1 = 0x0E; public const uint DUTY_RATIO_064_TO_1 = 0x0F; public const uint DUTY_RATIO_068_TO_1 = 0x10; public const uint DUTY_RATIO_072_TO_1 = 0x11; public const uint DUTY_RATIO_076_TO_1 = 0x12; public const uint DUTY_RATIO_080_TO_1 = 0x13; public const uint DUTY_RATIO_084_TO_1 = 0x14; public const uint DUTY_RATIO_088_TO_1 = 0x15; public const uint DUTY_RATIO_092_TO_1 = 0x16; public const uint DUTY_RATIO_096_TO_1 = 0x17; public const uint DUTY_RATIO_100_TO_1 = 0x18; // then followed by Starting Point Block Register Set, // lower 5 bits are used only, 0 = COM0 to 3, 0x17=COM92 to 95 public const uint CONTROL_READ_MODIFY_WRITE = 0xE0; public const uint CONTROL_READ_MODIFY_WRITE_END = 0xEE; public const uint CONTROL_POWER_CONTROL_SET = 0x20; // lower 4 bits are: public const uint POWER_BOOSTER_CIRCUIT_DISABLED = 0x08; public const uint POWER_FIRST_BOOSTER_CIRCUIT_ON = 0x04; public const uint POWER_VLCD_REGULATOR_CIRCUIT_ON = 0x02; public const uint POWER_VLCD_OUTPUT_ON = 0x01; public const uint CONTROL_ELECTRONIC_VOLUME_MODE_SET = 0x81; // next byte is the volume, from 0x00 (small) to 0x7f (large) public const uint CONTROL_DISCHARGE_ON = 0xEA; public const uint CONTROL_DISCHARGE_OFF = 0xEB; public const uint CONTROL_POWER_SAVE_ON = 0xA9; public const uint CONTROL_POWER_SAVE_OFF = 0xE1; public const uint CONTROL_OSCILLATOR_CIRCUIT_OFF = 0xAA; public const uint CONTROL_OSCILLATOR_CIRCUIT_ON = 0xAB; public const uint CONTROL_OSCILLATOR_FREQUENCY_SET = 0x50; // lower 4 bits are 1 of 16 frequencies from 0=40kHz, to 0x0f=24.5kHz public const uint OSCILLATOR_FREQUENCY_400 = 0x00; public const uint OSCILLATOR_FREQUENCY_330 = 0x01; public const uint OSCILLATOR_FREQUENCY_284 = 0x02; public const uint OSCILLATOR_FREQUENCY_245 = 0x03; // fOSC/2 public const uint OSCILLATOR_FREQUENCY_200 = 0x04; public const uint OSCILLATOR_FREQUENCY_165 = 0x05; public const uint OSCILLATOR_FREQUENCY_142 = 0x06; public const uint OSCILLATOR_FREQUENCY_123 = 0x07; // fOSC/4 public const uint OSCILLATOR_FREQUENCY_100 = 0x08; public const uint OSCILLATOR_FREQUENCY_082 = 0x09; public const uint OSCILLATOR_FREQUENCY_071 = 0x0A; public const uint OSCILLATOR_FREQUENCY_061 = 0x0B; // fOSC/8 public const uint OSCILLATOR_FREQUENCY_050 = 0x0C; public const uint OSCILLATOR_FREQUENCY_041 = 0x0D; public const uint OSCILLATOR_FREQUENCY_036 = 0x0E; public const uint OSCILLATOR_FREQUENCY_031 = 0x0F; public const uint CONTROL_TEMPERATURE_GRADIENT_SET = 0x40; // lower 3 bits are 1 of 8 gradients from 0=-0.06%/C, to 0x07=-0.18%/C public const uint TEMPERATURE_GRADIENT_06 = 0x00; public const uint TEMPERATURE_GRADIENT_08 = 0x01; public const uint TEMPERATURE_GRADIENT_10 = 0x02; public const uint TEMPERATURE_GRADIENT_11 = 0x03; public const uint TEMPERATURE_GRADIENT_13 = 0x04; public const uint TEMPERATURE_GRADIENT_15 = 0x05; public const uint TEMPERATURE_GRADIENT_17 = 0x06; public const uint TEMPERATURE_GRADIENT_18 = 0x07; public const uint CONTROL_RESET = 0xE2; public const uint CONTROL_NOOP = 0xE3; public const uint STARTING_BLOCK = 0x00; public const uint START_LINE = 0x00; //--// const int SCREEN_WIDTH = 120; const int SCREEN_HEIGHT = 96; const int c_WidthInWords = (SCREEN_WIDTH + 31) / 32; const int c_SizeInWords = (SCREEN_WIDTH + 31) / 32 * SCREEN_HEIGHT; //--// [Simulator.Register(Offset=0)] public byte Control { set { switch(value & 0xF0u) { case CONTROL_PAGE_ADDRESS_SET: m_page = (int)(value & 0x0F); #if PROFILE_FRAMERATE if(m_page == 0) { Hosting.OutputSink sink; if(m_owner.GetHostingService( out sink )) { sink.OutputLine( "Clocks per iteration: {0}", m_owner.ClockTicks - lastPass ); } lastPass = m_owner.ClockTicks; } #endif break; case CONTROL_COLUMN_ADDRESS_HI_NIBBLE_SET: m_column = (m_column & 0x0F) | (int)((value & 0x0F) << 4); break; case CONTROL_COLUMN_ADDRESS_LO_NIBBLE_SET: m_column = (m_column & 0xF0) | (int)((value & 0x0F) << 0); break; } } } [Simulator.Register(Offset=1)] public byte Data { set { int offset = m_page * c_WidthInWords * 8 + (m_column / 32); uint maskBit = 1U << (m_column % 32); for(int pos = 0; pos < 8; pos++) { if((value & (1 << pos)) != 0) { m_buffer[offset] |= maskBit; } else { m_buffer[offset] &= ~maskBit; } offset += c_WidthInWords; } if((++m_column % 8) == 0) { Hosting.SED15E0Sink sink; if(m_owner.GetHostingService( out sink )) { sink.NewScreenShot( m_buffer, SCREEN_WIDTH, SCREEN_HEIGHT ); } } } } //--// // // State // private int m_page = 0; private int m_column = 0; private uint[] m_buffer = new uint[c_SizeInWords]; #if PROFILE_FRAMERATE static ulong lastPass; #endif } } ================================================ FILE: Zelig/Zelig/DebugTime/ArmProcessorEmulation/Models/FlashMemory/S29WS064.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // namespace Microsoft.Zelig.Emulation.ArmProcessor.FlashMemory { using System; using System.Collections.Generic; using EncDef = Microsoft.Zelig.TargetModel.ArmProcessor.EncodingDefinition; using ElementTypes = Microsoft.Zelig.MetaData.ElementTypes; //--// public class S29WS064 : Simulator.MemoryHandler { const uint Sector4KWord = 4 * 1024 * sizeof(ushort); const uint Sector32KWord = 32 * 1024 * sizeof(ushort); const uint ChipSize = 8 * 1024 * 1024; //--// static ushort[] sequence_CFI = new ushort[] { 0x055, 0x0098 }; static ushort[] sequence_PROGRAM = new ushort[] { 0x555, 0x00AA , 0x2AA, 0x0055 , 0x555, 0x00A0 }; static ushort[] sequence_ERASE = new ushort[] { 0x555, 0x00AA , 0x2AA, 0x0055 , 0x555, 0x0080 , 0x555, 0x00AA , 0x2AA, 0x0055 }; enum Mode { Normal , Query , Program, Erase , } class SequenceTracker { // // State // internal ushort[] m_sequence; internal int m_pos; internal ulong m_lastWrite; // // Constructor Methods // internal SequenceTracker( ushort[] sequence ) { m_sequence = sequence; m_pos = 0; } // // Helper Methods // internal void Reset() { m_pos = 0; } internal void Advance( uint relativeAddress , ushort value , Simulator owner ) { // // If the writes are too spaced out, abort. // if(m_pos > 0 && owner.ClockTicks - m_lastWrite > 5 * 30) { Reset(); return; } if(IsMatch( relativeAddress, value, m_sequence, m_pos ) == false) { Reset(); return; } m_pos += 2; m_lastWrite = owner.ClockTicks; } private static bool IsMatch( uint relativeAddress , ushort value , ushort[] sequence , int pos ) { return (sequence[pos ] == relativeAddress / sizeof(ushort) && sequence[pos+1] == value ); } // // Access Methods // internal bool IsRecognized { get { return m_pos == m_sequence.Length; } } } class BankState { static ushort[] query_results = new ushort[] { 0x10, 0x0051, // 0x11, 0x0052, // Query Unique ASCII string "QRY" 0x12, 0x0059, // 0x13, 0x0002, // Primary OEM Command Set 0x14, 0x0000, // 0x15, 0x0040, // Address for Primary Extended Table 0x16, 0x0000, // 0x17, 0x0000, // Alternate OEM Command Set 0x18, 0x0000, // 0x2C, 0x0003, // Number of Erase Block Regions within device. 0x2D, 0x0007, // Erase Block Region 1 Information 0x2E, 0x0000, // 0x2F, 0x0020, // 0x30, 0x0000, // 0x31, 0x007D, // Erase Block Region 2 Information 0x32, 0x0000, // 0x33, 0x0000, // 0x34, 0x0001, // 0x35, 0x0007, // Erase Block Region 3 Information 0x36, 0x0000, // 0x37, 0x0020, // 0x38, 0x0000, // }; const ushort resetCommand = 0x00F0; const ushort eraseCommand = 0x0030; const ushort c_DQ7 = (ushort)(1u << 7); const ushort c_DQ6 = (ushort)(1u << 6); const ushort c_DQ3 = (ushort)(1u << 3); const ushort c_DQ2 = (ushort)(1u << 2); // // State // internal uint m_addressStart; internal uint m_addressEnd; internal uint[] m_sectorSizes; internal Mode m_mode; internal ushort m_lastStatusValue; internal ulong m_timer; internal int m_erasingSectorIndex; internal uint m_programmingAddress; internal ushort m_programmingValue; // // Constructor Methods // internal BankState( uint addressStart , params uint[] sectorDefinition ) { uint totalSize = 0; uint totalSectors = 0; for(int i = 0; i < sectorDefinition.Length; i += 2) { uint sectorSize = sectorDefinition[i ]; uint sectorNum = sectorDefinition[i+1]; totalSectors += sectorNum; totalSize += sectorNum * sectorSize; } m_addressStart = addressStart; m_addressEnd = addressStart + totalSize; m_sectorSizes = new uint[totalSectors]; m_mode = Mode.Normal; uint offset = 0; for(int i = 0; i < sectorDefinition.Length; i += 2) { uint sectorSize = sectorDefinition[i ]; uint sectorNum = sectorDefinition[i+1]; while(sectorNum-- > 0) { m_sectorSizes[offset++] = sectorSize; } } } // // Helper Methods // internal void HandleWrite( Simulator owner , uint address , ushort value ) { switch(m_mode) { case Mode.Normal: break; case Mode.Query: if(address == 0 && value == resetCommand) { m_mode = Mode.Normal; } break; case Mode.Program: m_programmingAddress = address; m_programmingValue = value; m_timer = owner.ClockTicks + 10 * 30; // BUGBUG: We need a way to convert from Ticks to Time. m_lastStatusValue = (ushort)(~value & c_DQ7); // DQ7# break; case Mode.Erase: uint offset = address - m_addressStart; for(int i = 0; i < m_sectorSizes.Length; i++) { if(offset < m_sectorSizes[i]) { m_erasingSectorIndex = i; break; } offset -= m_sectorSizes[i]; } //m_timer = owner.ClockTicks + 400 * 1000 * 30; // BUGBUG: We need a way to convert from Ticks to Time. m_timer = owner.ClockTicks + 40 * 30; // BUGBUG: We need a way to convert from Ticks to Time. m_lastStatusValue = c_DQ3; break; } } internal bool HandleRead( Simulator owner , uint address , out ushort value ) { switch(m_mode) { case Mode.Normal: break; case Mode.Query: for(int i = 0; i < query_results.Length; i += 2) { if(query_results[i] == address / sizeof(ushort)) { value = query_results[i+1]; return true; } } value = 0xFFFF; return true; case Mode.Program: if(owner.ClockTicks < m_timer) { value = m_lastStatusValue; m_lastStatusValue ^= c_DQ6; // Toggle DQ6. return true; } m_mode = Mode.Normal; break; case Mode.Erase: if(owner.ClockTicks < m_timer) { value = m_lastStatusValue; m_lastStatusValue ^= c_DQ6 | c_DQ2; // Toggle DQ6 and DQ2. return true; } m_mode = Mode.Normal; break; } value = 0xFFFF; return false; } internal bool FindSector( uint address , out uint sectorStart , out uint sectorEnd ) { if(m_addressStart <= address && address < m_addressEnd) { uint sector = m_addressStart; foreach(uint sectorSize in m_sectorSizes) { uint sectorNext = sector + sectorSize; if(sector <= address && address < sectorNext) { sectorStart = sector; sectorEnd = sectorNext; return true; } sector = sectorNext; } } sectorStart = 0; sectorEnd = 0; return false; } } // // State // BankState[] m_banks; Mode m_mode; SequenceTracker m_sequenceTracker_CFI; SequenceTracker m_sequenceTracker_Program; SequenceTracker m_sequenceTracker_Erase; // // Constructor Methods // public S29WS064() { m_banks = new BankState[4]; m_mode = Mode.Normal; // // Bank A // m_banks[0] = new BankState( 0, Sector4KWord, 8, Sector32KWord, 15 ); // // Bank B // m_banks[1] = new BankState( m_banks[0].m_addressEnd, Sector32KWord, 48 ); // // Bank C // m_banks[2] = new BankState( m_banks[1].m_addressEnd, Sector32KWord, 48 ); // // Bank D // m_banks[3] = new BankState( m_banks[2].m_addressEnd, Sector32KWord, 48, Sector4KWord, 8 ); //--// m_sequenceTracker_CFI = new SequenceTracker( sequence_CFI ); m_sequenceTracker_Program = new SequenceTracker( sequence_PROGRAM ); m_sequenceTracker_Erase = new SequenceTracker( sequence_ERASE ); } // // Helper Methods // public override void Initialize( Simulator owner , ulong rangeLength , uint rangeWidth , uint readLatency , uint writeLatency ) { base.Initialize( owner, rangeLength, rangeWidth, readLatency, writeLatency ); // // Erase the whole chip. // for(int i = 0; i < m_target.Length; i++) { m_target[i] = 0xFFFFFFFF; } } public override uint Read( uint address , uint relativeAddress , TargetAdapterAbstractionLayer.MemoryAccessType kind ) { if(m_owner.AreTimingUpdatesEnabled) { BankState bank; uint sectorStart; uint sectorEnd; if(FindSector( relativeAddress, out bank, out sectorStart, out sectorEnd )) { ushort value; if(bank.HandleRead( m_owner, relativeAddress, out value )) { UpdateClockTicksForLoad( address, kind ); return value; } } } return base.Read( address, relativeAddress, kind ); } public override void Write( uint address , uint relativeAddress , uint value , TargetAdapterAbstractionLayer.MemoryAccessType kind ) { if(m_owner.AreTimingUpdatesEnabled) { BankState bank; uint sectorStart; uint sectorEnd; if(kind != TargetAdapterAbstractionLayer.MemoryAccessType.UINT16) { throw new TargetAdapterAbstractionLayer.BusErrorException( address, kind ); } UpdateClockTicksForStore( address, kind ); ushort valueShort = (ushort)value; if(m_mode == Mode.Normal) { m_sequenceTracker_CFI .Advance( relativeAddress, valueShort, m_owner ); m_sequenceTracker_Program.Advance( relativeAddress, valueShort, m_owner ); m_sequenceTracker_Erase .Advance( relativeAddress, valueShort, m_owner ); if(m_sequenceTracker_CFI.IsRecognized) { foreach(var bank2 in m_banks) { bank2.m_mode = Mode.Query; } m_mode = Mode.Query; return; } if(m_sequenceTracker_Program.IsRecognized) { m_mode = Mode.Program; return; } if(m_sequenceTracker_Erase.IsRecognized) { m_mode = Mode.Erase; return; } } if(m_mode != Mode.Normal) { m_sequenceTracker_CFI .Reset(); m_sequenceTracker_Program.Reset(); m_sequenceTracker_Erase .Reset(); if(FindSector( relativeAddress, out bank, out sectorStart, out sectorEnd )) { bank.m_mode = m_mode; bank.HandleWrite( m_owner, relativeAddress, valueShort ); switch(m_mode) { case Mode.Query: if(bank.m_mode == Mode.Normal) { foreach(var bank2 in m_banks) { bank2.m_mode = Mode.Normal; } m_mode = Mode.Normal; } break; case Mode.Program: base.Write( relativeAddress, relativeAddress, value, kind ); m_mode = Mode.Normal; break; case Mode.Erase: while(sectorStart < sectorEnd) { base.Write( sectorStart, sectorStart, 0xFFFF, TargetAdapterAbstractionLayer.MemoryAccessType.UINT16 ); sectorStart += sizeof(ushort); } m_mode = Mode.Normal; break; } } } return; } base.Write( address, relativeAddress, value, kind ); } //--// bool FindSector( uint address , out BankState bank , out uint sectorStart , out uint sectorEnd ) { foreach(BankState bank2 in m_banks) { if(bank2.FindSector( address, out sectorStart, out sectorEnd )) { bank = bank2; return true; } } bank = null; sectorStart = 0; sectorEnd = 0; return false; } } } ================================================ FILE: Zelig/Zelig/DebugTime/ArmProcessorEmulation/Models/FlashMemory/S29WS128N.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // namespace Microsoft.Zelig.Emulation.ArmProcessor.FlashMemory { using System; using System.Collections.Generic; using EncDef = Microsoft.Zelig.TargetModel.ArmProcessor.EncodingDefinition; using ElementTypes = Microsoft.Zelig.MetaData.ElementTypes; //--// public class S29WS128N : Simulator.MemoryHandler { const uint Sector16KWord = 16 * 1024 * sizeof(ushort); const uint Sector64KWord = 64 * 1024 * sizeof(ushort); const uint ChipSize = 16 * 1024 * 1024; //--// static ushort[] sequence_CFI = new ushort[] { 0x555, 0x0098 }; static ushort[] sequence_PROGRAM = new ushort[] { 0x555, 0x00AA , 0x2AA, 0x0055 , 0x555, 0x00A0 }; static ushort[] sequence_ERASE = new ushort[] { 0x555, 0x00AA , 0x2AA, 0x0055 , 0x555, 0x0080 , 0x555, 0x00AA , 0x2AA, 0x0055 }; enum Mode { Normal , Query , Program, Erase , } class SequenceTracker { // // State // internal ushort[] m_sequence; internal int m_pos; internal ulong m_lastWrite; // // Constructor Methods // internal SequenceTracker( ushort[] sequence ) { m_sequence = sequence; m_pos = 0; } // // Helper Methods // internal void Reset() { m_pos = 0; } internal void Advance( uint relativeAddress , ushort value , Simulator owner ) { // // If the writes are too spaced out, abort. // if(m_pos > 0 && owner.ClockTicks - m_lastWrite > 5 * 30) { Reset(); return; } if(IsMatch( relativeAddress, value, m_sequence, m_pos ) == false) { Reset(); return; } m_pos += 2; m_lastWrite = owner.ClockTicks; } private static bool IsMatch( uint relativeAddress , ushort value , ushort[] sequence , int pos ) { return (sequence[pos ] == relativeAddress / sizeof(ushort) && sequence[pos+1] == value ); } // // Access Methods // internal bool IsRecognized { get { return m_pos == m_sequence.Length; } } } class BankState { static ushort[] query_results = new ushort[] { 0x10, 0x0051, // 0x11, 0x0052, // Query Unique ASCII string "QRY" 0x12, 0x0059, // 0x13, 0x0002, // Primary OEM Command Set 0x14, 0x0000, // 0x15, 0x0040, // Address for Primary Extended Table 0x16, 0x0000, // 0x17, 0x0000, // Alternate OEM Command Set 0x18, 0x0000, // 0x2C, 0x0003, // Number of Erase Block Regions within device. 0x2D, 0x0003, // Erase Block Region 1 Information 0x2E, 0x0000, // 0x2F, 0x0080, // 0x30, 0x0000, // 0x31, 0x007D, // Erase Block Region 2 Information 0x32, 0x0000, // 0x33, 0x0000, // 0x34, 0x0002, // 0x35, 0x0003, // Erase Block Region 3 Information 0x36, 0x0000, // 0x37, 0x0080, // 0x38, 0x0000, // }; const ushort resetCommand = 0x00F0; const ushort eraseCommand = 0x0030; const ushort c_DQ7 = (ushort)(1u << 7); const ushort c_DQ6 = (ushort)(1u << 6); const ushort c_DQ3 = (ushort)(1u << 3); const ushort c_DQ2 = (ushort)(1u << 2); // // State // internal uint m_addressStart; internal uint m_addressEnd; internal uint[] m_sectorSizes; internal Mode m_mode; internal ushort m_lastStatusValue; internal ulong m_timer; internal int m_erasingSectorIndex; internal uint m_programmingAddress; internal ushort m_programmingValue; // // Constructor Methods // internal BankState( uint addressStart , params uint[] sectorDefinition ) { uint totalSize = 0; uint totalSectors = 0; for(int i = 0; i < sectorDefinition.Length; i += 2) { uint sectorSize = sectorDefinition[i ]; uint sectorNum = sectorDefinition[i+1]; totalSectors += sectorNum; totalSize += sectorNum * sectorSize; } m_addressStart = addressStart; m_addressEnd = addressStart + totalSize; m_sectorSizes = new uint[totalSectors]; m_mode = Mode.Normal; uint offset = 0; for(int i = 0; i < sectorDefinition.Length; i += 2) { uint sectorSize = sectorDefinition[i ]; uint sectorNum = sectorDefinition[i+1]; while(sectorNum-- > 0) { m_sectorSizes[offset++] = sectorSize; } } } // // Helper Methods // internal void HandleWrite( Simulator owner , uint address , ushort value ) { switch(m_mode) { case Mode.Normal: break; case Mode.Query: if(address == 0 && value == resetCommand) { m_mode = Mode.Normal; } break; case Mode.Program: m_programmingAddress = address; m_programmingValue = value; m_timer = owner.ClockTicks + 10 * 30; // BUGBUG: We need a way to convert from Ticks to Time. m_lastStatusValue = (ushort)(~value & c_DQ7); // DQ7# break; case Mode.Erase: uint offset = address - m_addressStart; for(int i = 0; i < m_sectorSizes.Length; i++) { if(offset < m_sectorSizes[i]) { m_erasingSectorIndex = i; break; } offset -= m_sectorSizes[i]; } //m_timer = owner.ClockTicks + 400 * 1000 * 30; // BUGBUG: We need a way to convert from Ticks to Time. m_timer = owner.ClockTicks + 40 * 30; // BUGBUG: We need a way to convert from Ticks to Time. m_lastStatusValue = c_DQ3; break; } } internal bool HandleRead( Simulator owner , uint address , out ushort value ) { switch(m_mode) { case Mode.Normal: break; case Mode.Query: for(int i = 0; i < query_results.Length; i += 2) { if(query_results[i] == address / sizeof(ushort)) { value = query_results[i+1]; return true; } } value = 0xFFFF; return true; case Mode.Program: if(owner.ClockTicks < m_timer) { value = m_lastStatusValue; m_lastStatusValue ^= c_DQ6; // Toggle DQ6. return true; } m_mode = Mode.Normal; break; case Mode.Erase: if(owner.ClockTicks < m_timer) { value = m_lastStatusValue; m_lastStatusValue ^= c_DQ6 | c_DQ2; // Toggle DQ6 and DQ2. return true; } m_mode = Mode.Normal; break; } value = 0xFFFF; return false; } internal bool FindSector( uint address , out uint sectorStart , out uint sectorEnd ) { if(m_addressStart <= address && address < m_addressEnd) { uint sector = m_addressStart; foreach(uint sectorSize in m_sectorSizes) { uint sectorNext = sector + sectorSize; if(sector <= address && address < sectorNext) { sectorStart = sector; sectorEnd = sectorNext; return true; } sector = sectorNext; } } sectorStart = 0; sectorEnd = 0; return false; } } // // State // BankState[] m_banks; Mode m_mode; SequenceTracker m_sequenceTracker_CFI; SequenceTracker m_sequenceTracker_Program; SequenceTracker m_sequenceTracker_Erase; // // Constructor Methods // public S29WS128N() { m_banks = new BankState[16]; m_mode = Mode.Normal; // // Bank 0 // m_banks[0] = new BankState( 0, Sector16KWord, 4, Sector64KWord, 7 ); // // Bank 1-14 // for(int bank = 1; bank <= 14; bank++) { m_banks[bank] = new BankState( m_banks[bank-1].m_addressEnd, Sector64KWord, 8 ); } // // Bank 15 // m_banks[15] = new BankState( m_banks[14].m_addressEnd, Sector64KWord, 7, Sector16KWord, 4 ); //--// m_sequenceTracker_CFI = new SequenceTracker( sequence_CFI ); m_sequenceTracker_Program = new SequenceTracker( sequence_PROGRAM ); m_sequenceTracker_Erase = new SequenceTracker( sequence_ERASE ); } // // Helper Methods // public override void Initialize( Simulator owner , ulong rangeLength , uint rangeWidth , uint readLatency , uint writeLatency ) { base.Initialize( owner, rangeLength, rangeWidth, readLatency, writeLatency ); // // Erase the whole chip. // for(int i = 0; i < m_target.Length; i++) { m_target[i] = 0xFFFFFFFF; } } public override uint Read( uint address , uint relativeAddress , TargetAdapterAbstractionLayer.MemoryAccessType kind ) { if(m_owner.AreTimingUpdatesEnabled) { BankState bank; uint sectorStart; uint sectorEnd; if(FindSector( relativeAddress, out bank, out sectorStart, out sectorEnd )) { ushort value; if(bank.HandleRead( m_owner, relativeAddress, out value )) { UpdateClockTicksForLoad( address, kind ); return value; } } } return base.Read( address, relativeAddress, kind ); } public override void Write( uint address , uint relativeAddress , uint value , TargetAdapterAbstractionLayer.MemoryAccessType kind ) { if(m_owner.AreTimingUpdatesEnabled) { BankState bank; uint sectorStart; uint sectorEnd; if(kind != TargetAdapterAbstractionLayer.MemoryAccessType.UINT16) { throw new TargetAdapterAbstractionLayer.BusErrorException( address, kind ); } UpdateClockTicksForStore( address, kind ); ushort valueShort = (ushort)value; if(m_mode == Mode.Normal) { m_sequenceTracker_CFI .Advance( relativeAddress, valueShort, m_owner ); m_sequenceTracker_Program.Advance( relativeAddress, valueShort, m_owner ); m_sequenceTracker_Erase .Advance( relativeAddress, valueShort, m_owner ); if(m_sequenceTracker_CFI.IsRecognized) { foreach(var bank2 in m_banks) { bank2.m_mode = Mode.Query; } m_mode = Mode.Query; return; } if(m_sequenceTracker_Program.IsRecognized) { m_mode = Mode.Program; return; } if(m_sequenceTracker_Erase.IsRecognized) { m_mode = Mode.Erase; return; } } if(m_mode != Mode.Normal) { m_sequenceTracker_CFI .Reset(); m_sequenceTracker_Program.Reset(); m_sequenceTracker_Erase .Reset(); if(FindSector( relativeAddress, out bank, out sectorStart, out sectorEnd )) { bank.m_mode = m_mode; bank.HandleWrite( m_owner, relativeAddress, valueShort ); switch(m_mode) { case Mode.Query: if(bank.m_mode == Mode.Normal) { foreach(var bank2 in m_banks) { bank2.m_mode = Mode.Normal; } m_mode = Mode.Normal; } break; case Mode.Program: ushort lastValueShort = (ushort)base.Read( address, relativeAddress, kind ); // // Only update the flash if the new value doesn't include any 0 -> 1 transitions, which can only happens through an erase. // if((~lastValueShort & valueShort) == 0) { base.Write( address, relativeAddress, value, kind ); } m_mode = Mode.Normal; break; case Mode.Erase: while(sectorStart < sectorEnd) { base.Write( sectorStart, sectorStart, 0xFFFF, TargetAdapterAbstractionLayer.MemoryAccessType.UINT16 ); sectorStart += sizeof(ushort); } m_mode = Mode.Normal; break; } } } return; } base.Write( address, relativeAddress, value, kind ); } //--// bool FindSector( uint address , out BankState bank , out uint sectorStart , out uint sectorEnd ) { foreach(BankState bank2 in m_banks) { if(bank2.FindSector( address, out sectorStart, out sectorEnd )) { bank = bank2; return true; } } bank = null; sectorStart = 0; sectorEnd = 0; return false; } } } ================================================ FILE: Zelig/Zelig/DebugTime/ArmProcessorEmulation/Models/VoxSoloFormFactor/Interops.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // namespace Microsoft.Zelig.Emulation.ArmProcessor.VoxSoloFormFactor { using System; using System.Collections.Generic; using EncDef = Microsoft.Zelig.TargetModel.ArmProcessor.EncodingDefinition; using ElementTypes = Microsoft.Zelig.MetaData.ElementTypes; //--// public static class Interop { // // WARNING: This interop has been disabled because we need to spin the idle thread in order to pump the DCC queues. // //[Simulator.Interop(Function="void Microsoft.VoxSoloFormFactor.Peripherals::WaitForInterrupt()")] class InteropHandler_WaitForInterrupt : Simulator.InteropHandler { protected override Hosting.Interop.CallbackResponse PerformInterop() { m_owner.SpinUntilInterrupts(); return m_owner.Interop_GenericSkipCall(); } } } } ================================================ FILE: Zelig/Zelig/DebugTime/ArmProcessorEmulation/Properties/AssemblyInfo.cs ================================================ using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; // General Information about an assembly is controlled through the following // set of attributes. Change these attribute values to modify the information // associated with an assembly. [assembly: AssemblyTitle( "Microsoft.Zelig.Emulation.ArmProcessor" )] [assembly: AssemblyDescription( "" )] [assembly: AssemblyConfiguration( "" )] [assembly: AssemblyCompany( "Microsoft" )] [assembly: AssemblyProduct( "Microsoft.Zelig.Emulation.ArmProcessor" )] [assembly: AssemblyCopyright( "Copyright © Microsoft 2006" )] [assembly: AssemblyTrademark( "" )] [assembly: AssemblyCulture( "" )] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible( false )] //// The following GUID is for the ID of the typelib if this project is exposed to COM //[assembly: Guid( "57de0ebe-e971-4cb9-8985-5f6b66934a91" )] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Revision and Build Numbers // by using the '*' as shown below: [assembly: AssemblyVersion( "1.0.0.0" )] [assembly: AssemblyFileVersion( "1.0.0.0" )] ================================================ FILE: Zelig/Zelig/DebugTime/ArmProcessorEmulation/SRecordParser.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // namespace Microsoft.Zelig.Emulation.ArmProcessor { using System; using System.Collections.Generic; using System.IO; using System.Text; public static class SRecordParser { public class Block { // // State // public uint address; public MemoryStream data; } public static uint Parse( string file , List< Block > blocks ) { if(System.IO.File.Exists( file ) == false) { throw new System.IO.FileNotFoundException( String.Format( "Cannot find {0}", file ) ); } using(System.IO.StreamReader reader = new StreamReader( file )) { return Parse( reader, file, blocks ); } } public static uint Parse( System.IO.StreamReader reader , string fileName , List< Block > blocks ) { string line; int lineNum = 0; uint entrypoint = 0; while((line = reader.ReadLine()) != null) { char[] lineBytes = line.ToCharArray(); int len = lineBytes.Length; int i; lineNum++; if(len == 0) continue; if((lineBytes[0] != 'S' && lineBytes[0] != 's') || (lineBytes[1] != '3' && lineBytes[1] != '7') ) { throw new System.ArgumentException( String.Format( "Unknown format at line {0} of {1}:\n {2}", lineNum, fileName, line ) ); } int num = Byte.Parse( new string( lineBytes, 2, 2 ), System.Globalization.NumberStyles.HexNumber ); if(num != ((len / 2) - 2)) { throw new System.ArgumentException( String.Format( "Incorrect length at line {0} of {1}: {2}", lineNum, fileName, num ) ); } byte crc = (byte)num; for(i = 4; i> 0); crc += (byte)(address >> 8); crc += (byte)(address >> 16); crc += (byte)(address >> 24); writer.WriteLine( "{0:X2}", (byte)~crc ); writer.Flush(); } public static void Encode( Stream stream , byte[] buf , uint address ) { StreamWriter writer = new StreamWriter( stream, Encoding.ASCII ); uint len = (uint)buf.Length; int offset = 0; while(len > 0) { uint size = len > 16 ? 16 : len; byte crc = (byte)(size + 5); writer.Write( "S3{0:X2}{1:X8}", size + 5, address ); crc += (byte)(address >> 0); crc += (byte)(address >> 8); crc += (byte)(address >> 16); crc += (byte)(address >> 24); for(uint i=0; i image , ProgressCallback callback ) { m_owner.DeployImage( image, callback ); } public override void StartPlugIns( List< Type > extraHandlers ) { m_owner.StartPlugIns( m_owner.m_product, extraHandlers ); } public override void StopPlugIns() { m_owner.StopPlugIns(); } public override void Execute( List< Hosting.Breakpoint > breakpoints ) { m_owner.Execute( breakpoints ); } public override void ExecuteStep( List< Hosting.Breakpoint > breakpoints ) { m_owner.ExecuteStep( breakpoints ); } // // Access Methods // public override bool StopExecution { get { return m_owner.m_fStopExecution; } set { m_owner.m_fStopExecution = value; } } } sealed class ProcessorStatusImpl : Emulation.Hosting.ProcessorStatus { // // State // Simulator m_owner; // // Constructor Methods // internal ProcessorStatusImpl( Simulator owner ) { m_owner = owner; m_owner.RegisterService( typeof(Emulation.Hosting.ProcessorStatus), this ); } // // Helper Methods // internal void ResetState() { m_eventExternalProgramFlowChange = null; } public override Emulation.Hosting.BinaryBlob GetRegister( IR.Abstractions.RegisterDescriptor reg ) { uint idx = reg.Encoding; switch(idx) { case EncDef.c_register_pc: return Emulation.Hosting.BinaryBlob.Wrap( m_owner.m_pc ); case EncDef.c_register_cpsr: return Emulation.Hosting.BinaryBlob.Wrap( m_owner.m_cpsr ); default: return Emulation.Hosting.BinaryBlob.Wrap( m_owner.GetRegister( idx ) ); } } public override bool SetRegister( IR.Abstractions.RegisterDescriptor reg , Emulation.Hosting.BinaryBlob bb ) { uint val = bb.ReadUInt32( 0 ); uint idx = reg.Encoding; switch(idx) { case EncDef.c_register_pc: m_owner.m_pc = val; break; case EncDef.c_register_cpsr: m_owner.m_cpsr = val; break; default: m_owner.SetRegister( idx, val ); break; } return true; } //--// // // Access Methods // public override uint ProgramCounter { get { return m_owner.m_pc; } set { m_owner.m_pc = value; } } public override uint StackPointer { get { return m_owner.GetRegister( EncDef.c_register_sp ); } set { m_owner.SetRegister( EncDef.c_register_sp, value ); } } } sealed class ProcessorPerformanceImpl : Emulation.Hosting.ProcessorPerformance { // // State // Simulator m_owner; TimingState m_timingState; // // Constructor Methods // internal ProcessorPerformanceImpl( Simulator owner ) { m_owner = owner; m_owner.RegisterService( typeof(Emulation.Hosting.ProcessorPerformance), this ); } // // Helper Methods // public override void SuspendTimingUpdates() { m_owner.SuspendTimingUpdates( ref m_timingState ); } public override void ResumeTimingUpdates() { m_owner.ResumeTimingUpdates( ref m_timingState ); } // // Access Methods // public override ulong ClockCycles { get { return m_owner.m_clockTicks; } } public override ulong WaitStates { get { return m_owner.m_busAccess_WaitStates; } } } sealed class MonitorExecutionImpl : Emulation.Hosting.MonitorExecution { // // State // Simulator m_owner; // // Constructor Methods // internal MonitorExecutionImpl( Simulator owner ) { m_owner = owner; m_owner.RegisterService( typeof(Emulation.Hosting.MonitorExecution), this ); } // // Access Methods // public override bool MonitorMemory { get { return m_owner.m_fMonitorMemory; } set { m_owner.m_fMonitorMemory = value; } } public override bool MonitorRegisters { get { return m_owner.m_fMonitorRegisters; } set { m_owner.m_fMonitorRegisters = value; } } public override bool MonitorOpcodes { get { return m_owner.m_fMonitorOpcodes; } set { m_owner.m_fMonitorOpcodes = value; } } public override bool MonitorCalls { get { return m_owner.m_fMonitorCalls; } set { m_owner.m_fMonitorCalls = value; if(m_owner.m_fMonitorCalls == false) { m_owner.m_registers_Mode_USER .m_callQueue.Clear(); m_owner.m_registers_Mode_FIQ .m_callQueue.Clear(); m_owner.m_registers_Mode_IRQ .m_callQueue.Clear(); m_owner.m_registers_Mode_SVC .m_callQueue.Clear(); m_owner.m_registers_Mode_ABORT.m_callQueue.Clear(); m_owner.m_registers_Mode_UNDEF.m_callQueue.Clear(); } } } public override bool MonitorInterrupts { get { return m_owner.m_fMonitorInterrupts; } set { m_owner.m_fMonitorInterrupts = value; } } public override bool MonitorInterruptDisabling { get { return m_owner.m_fMonitorInterruptDisabling; } set { m_owner.m_fMonitorInterruptDisabling = value; } } public override bool NoSleep { get { return m_owner.m_fNoSleep; } set { m_owner.m_fNoSleep = value; } } } sealed class CodeCoverageImpl : Hosting.CodeCoverage { // // State // Simulator m_owner; // // Constructor Methods // internal CodeCoverageImpl( Simulator owner ) { m_owner = owner; m_owner.RegisterService( typeof(Hosting.CodeCoverage), this ); } // // Helper Methods // public override void Reset() { m_owner.m_codeCoverageClusters.Reset(); } //--// public override void Dump() { Hosting.OutputSink sink; if(m_owner.GetHostingService( out sink )) { Dictionary< uint, ulong > blocks = new Dictionary< uint, ulong >(); Dictionary< uint, ulong > blocksHits = new Dictionary< uint, ulong >(); Dictionary< uint, ulong > blocksWS = new Dictionary< uint, ulong >(); Dictionary< uint, ulong > blocksOpcodes = new Dictionary< uint, ulong >(); m_owner.m_codeCoverageClusters.Enumerate( delegate( uint address, uint hits, uint cycles, uint waitStates ) { uint context; if(cycles != 0 && m_owner.GetContext( address, out context )) { if(context == address) { blocksHits[context] = hits; } AddToBlocks( blocks , context, cycles ); AddToBlocks( blocksWS , context, waitStates ); AddToBlocks( blocksOpcodes, context, hits ); } } ); sink.OutputLine( "Address\tClock_Cycles\tWait_States\tNumber_of_Opcodes\tNumber_of_Invocations\tClass\tFunction\tModifier" ); foreach(uint address in blocks.Keys) { string strClass; string strFunction; string strModifier; SymDef.Unmangle( m_owner.m_symdef_Inverse[address], out strClass, out strFunction, out strModifier ); ulong clockCycles = blocks [address]; ulong waitStates = blocksWS [address]; ulong opcodes = blocksOpcodes[address]; ulong hits; if(blocksHits.TryGetValue( address, out hits ) == false) { hits = 1; } sink.OutputLine( "0x{0:X8}\t{1}\t{2}\t{3}\t{4}\t{5}\t{6}\t{7}", address, clockCycles, waitStates, opcodes, hits, strClass, strFunction, strModifier ); } } } private void AddToBlocks( Dictionary< uint, ulong > block , uint context , ulong amount ) { ulong total; if(block.TryGetValue( context, out total )) { total += amount; } else { total = amount; } block[context] = total; } public override void Enumerate( EnumerationCallback dlg ) { m_owner.m_codeCoverageClusters.Enumerate( delegate( uint address, uint hits, uint cycles, uint waitStates ) { dlg( address, hits, cycles, waitStates ); } ); } public override void SetSymbols( SymDef.SymbolToAddressMap symdef , SymDef.AddressToSymbolMap symdef_Inverse ) { m_owner.SetSymbols( symdef, symdef_Inverse ); } // // Access Methods // public override bool Enable { get { return m_owner.m_fMonitorCoverage; } set { m_owner.m_fMonitorCoverage = value; } } } sealed class InteropImpl : Hosting.Interop { // // State // Simulator m_owner; // // Constructor Methods // internal InteropImpl( Simulator owner ) { m_owner = owner; m_owner.RegisterService( typeof(Hosting.Interop), this ); } // // Helper Methods // public override Registration SetInterop( uint pc , bool fHead , bool fPostProcessing , Hosting.Interop.Callback ftn ) { return m_owner.SetInterop( pc, ftn, fHead, fPostProcessing ); } public override void RemoveInterop( Registration reg ) { m_owner.RemoveInterop( reg ); } } sealed class DeviceClockTicksTrackingImpl : Hosting.DeviceClockTicksTracking { // // State // Simulator m_owner; // // Constructor Methods // internal DeviceClockTicksTrackingImpl( Simulator owner ) { m_owner = owner; m_owner.RegisterService( typeof(Hosting.DeviceClockTicksTracking), this ); } // // Helper Methods // public override bool GetAbsoluteTime( out ulong clockTicks , out ulong nanoseconds ) { clockTicks = m_owner.m_executionTimingState.m_clockTicks; nanoseconds = (ulong)(m_owner.m_executionTimingState.m_clockTicks * 1E9 / this.ClockFrequency); return true; } public override IDisposable SuspendTiming() { return new TimingStateSmartHandler( m_owner ); } protected override void NotifyActivity() { } // // Access Methods // public override ulong ClockTicks { get { return m_owner.m_clockTicks; } } protected override object LockRoot { get { return m_owner; } } } //--// [AttributeUsageAttribute(AttributeTargets.Class, Inherited=true, AllowMultiple=true)] public class InteropAttribute : Attribute { // // State // public string Function; } public abstract class InteropHandler { public static readonly InteropHandler[] SharedEmptyArray = new InteropHandler[0]; // // State // protected Simulator m_owner; private TimingState m_backup; //--// // // Helper Methods // internal void CreateInterop( Simulator owner ) { m_owner = owner; foreach(InteropAttribute ia in ReflectionHelper.GetAttributes< InteropAttribute >( this, true )) { m_owner.SetInterop( ia.Function, PerformInterop, false ); } } protected virtual Hosting.Interop.CallbackResponse PerformInterop() { return m_owner.Interop_GenericSkipCall(); } protected void SaveState() { m_owner.SuspendTimingUpdates( ref m_backup ); } protected void RestoreState() { m_owner.ResumeTimingUpdates( ref m_backup ); } } //--// public class AddressSpaceMapping { public static readonly AddressSpaceMapping[] SharedEmptyArray = new AddressSpaceMapping[0]; // // State // public AddressSpaceHandler Target; public uint RangeBase; public ulong RangeLength; // // Helper Methods // // // Debug Methods // public override string ToString() { return this.Target.ToString(); } } public abstract class AddressSpaceHandler { // // State // protected Simulator m_owner; protected AddressSpaceBusHandler m_parent; protected ulong m_rangeLength; protected uint m_rangeWidth; protected uint m_readLatency; protected uint m_writeLatency; // // Constructor Methods // protected AddressSpaceHandler() { } // // Helper Methods // public virtual void Initialize( Simulator owner , ulong rangeLength , uint rangeWidth , uint readLatency , uint writeLatency ) { if(rangeWidth == 0) rangeWidth = 32; m_owner = owner; m_rangeLength = rangeLength; m_rangeWidth = rangeWidth; m_readLatency = readLatency; m_writeLatency = writeLatency; } internal virtual void LinkToBus( AddressSpaceBusHandler parent ) { CHECKS.ASSERT( m_parent == null || m_parent == parent, "Cannot move an address space handler '{0}' from one bus to another!", this ); m_parent = parent; } internal virtual void UnlinkFromBus() { m_parent = null; } public void LinkAtAddress( uint address ) { m_parent.AttachHandlerToBus( this, address ); } //--// public abstract bool CanAccess( uint address , uint relativeAddress , TargetAdapterAbstractionLayer.MemoryAccessType kind ); //--// public ulong Read64bit( uint address , uint relativeAddress ) { return (ulong)Read( address , relativeAddress , TargetAdapterAbstractionLayer.MemoryAccessType.UINT32 ) | (ulong)Read( address + sizeof(uint), relativeAddress + sizeof(uint), TargetAdapterAbstractionLayer.MemoryAccessType.UINT32 ) << 32 ; } public abstract uint Read( uint address , uint relativeAddress , TargetAdapterAbstractionLayer.MemoryAccessType kind ); public void Write64bit( uint address , uint relativeAddress , ulong value ) { Write( address , relativeAddress , (uint) value , TargetAdapterAbstractionLayer.MemoryAccessType.UINT32 ); Write( address + sizeof(uint), relativeAddress + sizeof(uint), (uint)(value >> 32), TargetAdapterAbstractionLayer.MemoryAccessType.UINT32 ); } public abstract void Write( uint address , uint relativeAddress , uint value , TargetAdapterAbstractionLayer.MemoryAccessType kind ); public abstract uint GetPhysicalAddress( uint address ); //--// public virtual void UpdateClockTicksForLoad( uint address , TargetAdapterAbstractionLayer.MemoryAccessType kind ) { UpdateClocks( m_readLatency, kind ); } public virtual void UpdateClockTicksForStore( uint address , TargetAdapterAbstractionLayer.MemoryAccessType kind ) { UpdateClocks( m_writeLatency, kind ); } //--// protected void UpdateClocks( uint clockTicks , TargetAdapterAbstractionLayer.MemoryAccessType kind ) { if(m_owner.AreTimingUpdatesEnabled) { uint width; switch(kind) { case TargetAdapterAbstractionLayer.MemoryAccessType.UINT8: case TargetAdapterAbstractionLayer.MemoryAccessType.SINT8: width = 8; break; case TargetAdapterAbstractionLayer.MemoryAccessType.UINT16: case TargetAdapterAbstractionLayer.MemoryAccessType.SINT16: width = 16; break; case TargetAdapterAbstractionLayer.MemoryAccessType.UINT32: case TargetAdapterAbstractionLayer.MemoryAccessType.SINT32: case TargetAdapterAbstractionLayer.MemoryAccessType.FETCH: width = 32; break; default: return; } while(true) { m_owner.m_clockTicks += clockTicks; m_owner.m_busAccess_WaitStates += clockTicks - 1; if(m_rangeWidth >= width) { break; } width -= m_rangeWidth; } } } //--// // // Access Methods // public ulong RangeLength { get { return m_rangeLength; } } public uint ReadLatency { get { return m_readLatency; } } public uint WriteLatency { get { return m_writeLatency; } } } public abstract class AddressSpaceBusHandler : AddressSpaceHandler { // // State // protected AddressSpaceMapping[] m_children; // // Constructor Methods // protected AddressSpaceBusHandler() { m_children = AddressSpaceMapping.SharedEmptyArray; } // // Helper Methods // public AddressSpaceHandler FindHandlerAtAddress( uint address ) { foreach(AddressSpaceMapping mapper in m_children) { AddressSpaceHandler hnd = mapper.Target; if(mapper.RangeBase == address) { return hnd; } AddressSpaceBusHandler hndBus = hnd as AddressSpaceBusHandler; if(hndBus != null) { AddressSpaceHandler res = hndBus.FindHandlerAtAddress( address - mapper.RangeBase ); if(res != null) { return res; } } } return null; } public AddressSpaceHandler FindHandler( Type cls ) { foreach(AddressSpaceMapping mapper in m_children) { AddressSpaceHandler hnd = mapper.Target; if(hnd.GetType() == cls) { return hnd; } AddressSpaceBusHandler hndBus = hnd as AddressSpaceBusHandler; if(hndBus != null) { AddressSpaceHandler res = hndBus.FindHandler( cls ); if(res != null) { return res; } } } return null; } public object FindInterface( Type itf ) { foreach(var res in FindInterfaces( itf )) { return res; } return null; } public IEnumerable FindInterfaces( Type itf ) { foreach(AddressSpaceMapping mapper in m_children) { AddressSpaceHandler hnd = mapper.Target; if(itf.IsInstanceOfType( hnd )) { yield return hnd; } AddressSpaceBusHandler hndBus = hnd as AddressSpaceBusHandler; if(hndBus != null) { foreach(var res in hndBus.FindInterfaces( itf )) { yield return res; } } } } //--// internal void AttachHandlerToBus( AddressSpaceHandler memory , uint rangeBase ) { m_owner.SuspendInterops(); foreach(AddressSpaceMapping mapper in m_children) { if(mapper.RangeBase == rangeBase) { m_children = ArrayUtility.RemoveUniqueFromNotNullArray( m_children, mapper ); } } AddressSpaceMapping newMapper = new AddressSpaceMapping(); newMapper.Target = memory; newMapper.RangeBase = rangeBase; newMapper.RangeLength = memory.RangeLength; m_children = ArrayUtility.AppendToNotNullArray( m_children, newMapper ); memory.LinkToBus( this ); m_owner.ApplyInterops(); } internal override void UnlinkFromBus() { base.UnlinkFromBus(); foreach(AddressSpaceMapping mapper in m_children) { mapper.Target.UnlinkFromBus(); } m_children = AddressSpaceMapping.SharedEmptyArray; } //--// public override bool CanAccess( uint address , uint relativeAddress , TargetAdapterAbstractionLayer.MemoryAccessType kind ) { foreach(AddressSpaceMapping mapper in m_children) { uint relativeSubAddress = relativeAddress - mapper.RangeBase; if(relativeSubAddress < mapper.RangeLength) { AddressSpaceHandler hnd = mapper.Target; return hnd.CanAccess( address, relativeSubAddress, kind ); } } return false; } public override uint Read( uint address , uint relativeAddress , TargetAdapterAbstractionLayer.MemoryAccessType kind ) { foreach(AddressSpaceMapping mapper in m_children) { uint relativeSubAddress = relativeAddress - mapper.RangeBase; if(relativeSubAddress < mapper.RangeLength) { AddressSpaceHandler hnd = mapper.Target; return hnd.Read( address, relativeSubAddress, kind ); } } throw new TargetAdapterAbstractionLayer.BusErrorException( address, kind ); } public override void Write( uint address , uint relativeAddress , uint value , TargetAdapterAbstractionLayer.MemoryAccessType kind ) { foreach(AddressSpaceMapping mapper in m_children) { uint relativeSubAddress = relativeAddress - mapper.RangeBase; if(relativeSubAddress < mapper.RangeLength) { AddressSpaceHandler hnd = mapper.Target; hnd.Write( address, relativeSubAddress, value, kind ); return; } } throw new TargetAdapterAbstractionLayer.BusErrorException( address, kind ); } public override uint GetPhysicalAddress( uint address ) { foreach(AddressSpaceMapping mapper in m_children) { uint relativeAddress = address - mapper.RangeBase; if(relativeAddress < mapper.RangeLength) { AddressSpaceHandler hnd = mapper.Target; return hnd.GetPhysicalAddress( address ); } } return address; } //--// // // Access Methods // public AddressSpaceMapping[] AttachedHandlers { get { return m_children; } } } //--// public class MemoryHandler : AddressSpaceHandler { // // State // protected uint[] m_target; protected bool m_fMonitorAccesses; // // Constructor Methods // public MemoryHandler() { m_fMonitorAccesses = true; } // // Helper Methods // public override void Initialize( Simulator owner , ulong rangeLength , uint rangeWidth , uint readLatency , uint writeLatency ) { base.Initialize( owner, rangeLength, rangeWidth, readLatency, writeLatency ); m_target = new uint[rangeLength / sizeof(uint)]; } //--// public override bool CanAccess( uint address , uint relativeAddress , TargetAdapterAbstractionLayer.MemoryAccessType kind ) { return relativeAddress < m_rangeLength; } public override uint Read( uint address , uint relativeAddress , TargetAdapterAbstractionLayer.MemoryAccessType kind ) { uint value = m_target[relativeAddress / sizeof(uint)]; // // If there's a detour installed at this spot, read the redirected value!! // if(value == TrackDetour.c_DetourOpcode && kind != TargetAdapterAbstractionLayer.MemoryAccessType.FETCH) { value = m_owner.HandleDetour( address, value ); } UpdateClockTicksForLoad( address, kind ); switch(kind) { case TargetAdapterAbstractionLayer.MemoryAccessType.UINT8: { uint shift = (address % 4) * 8; return (uint)((byte)(value >> (int)shift)); } case TargetAdapterAbstractionLayer.MemoryAccessType.UINT16: { uint shift = (address % 4) * 8; return (uint)((ushort)(value >> (int)shift)); } case TargetAdapterAbstractionLayer.MemoryAccessType.UINT32: case TargetAdapterAbstractionLayer.MemoryAccessType.SINT32: { return value; } case TargetAdapterAbstractionLayer.MemoryAccessType.SINT8: { uint shift = (address % 4) * 8; return (uint)(int)((sbyte)(value >> (int)shift)); } case TargetAdapterAbstractionLayer.MemoryAccessType.SINT16: { uint shift = (address % 4) * 8; return (uint)(int)((short)(value >> (int)shift)); } case TargetAdapterAbstractionLayer.MemoryAccessType.FETCH: { return value; } default: throw new NotSupportedException(); } } public override void Write( uint address , uint relativeAddress , uint value , TargetAdapterAbstractionLayer.MemoryAccessType kind ) { WriteInner( address, relativeAddress, value, kind, ref m_target[relativeAddress / sizeof(uint)] ); } public override uint GetPhysicalAddress( uint address ) { return address; } //--// private void WriteInner( uint address , uint relativeAddress , uint value , TargetAdapterAbstractionLayer.MemoryAccessType kind , ref uint target ) { UpdateClockTicksForStore( address, kind ); uint oldValue = target; uint newValue; switch(kind) { case TargetAdapterAbstractionLayer.MemoryAccessType.UINT8: case TargetAdapterAbstractionLayer.MemoryAccessType.SINT8: newValue = Insert( target, value, 0x000000FF, (int)(address % 4) * 8 ); break; case TargetAdapterAbstractionLayer.MemoryAccessType.UINT16: case TargetAdapterAbstractionLayer.MemoryAccessType.SINT16: newValue = Insert( target, value, 0x0000FFFF, (int)(address % 4) * 8 ); break; case TargetAdapterAbstractionLayer.MemoryAccessType.UINT32: case TargetAdapterAbstractionLayer.MemoryAccessType.SINT32: case TargetAdapterAbstractionLayer.MemoryAccessType.FETCH: newValue = value; break; default: throw new NotSupportedException(); } // // If there's a detour installed at this spot, don't overwrite it!! // if(oldValue == TrackDetour.c_DetourOpcode) { if(m_owner.UpdateDetour( address, newValue )) { return; } } target = newValue; if(m_fMonitorAccesses && m_owner.m_fMonitorMemory) { if(oldValue != newValue) { int shift; uint mask; switch(kind) { case TargetAdapterAbstractionLayer.MemoryAccessType.UINT8: case TargetAdapterAbstractionLayer.MemoryAccessType.SINT8: mask = 0x000000FF; shift = (int)(address % 4) * 8; break; case TargetAdapterAbstractionLayer.MemoryAccessType.UINT16: case TargetAdapterAbstractionLayer.MemoryAccessType.SINT16: mask = 0x0000FFFF; shift = (int)(address % 2) * 8; break; default: mask = 0xFFFFFFFF; shift = 0; break; } oldValue = (oldValue >> shift) & mask; newValue = (newValue >> shift) & mask; Hosting.OutputSink sink; if(m_owner.GetHostingService( out sink )) { sink.OutputLine( " {0} MEM : 0x{1:X8} -> 0x{2:X8} [{3:X8}]", new string( ' ', 80 ), oldValue, newValue, address ); } } } } private static uint Insert( uint oldValue , uint newValue , uint mask , int shift ) { mask <<= shift; newValue <<= shift; return (oldValue & ~mask) | (newValue & mask); } } //--// [AttributeUsageAttribute(AttributeTargets.Class, Inherited=true, AllowMultiple=true)] public class PeripheralRangeAttribute : Attribute { // // State // public uint Base; public uint Length; public uint WordSize; public uint Latency; public uint ReadLatency; public uint WriteLatency; } [AttributeUsageAttribute(AttributeTargets.Field | AttributeTargets.Property, Inherited=true, AllowMultiple=false)] public class RegisterAttribute : Attribute { // // State // public uint Offset; public uint Size; public int Instances; } [AttributeUsageAttribute(AttributeTargets.Field, Inherited=false, AllowMultiple=false)] public class LinkToPeripheralAttribute : Attribute { } [AttributeUsageAttribute(AttributeTargets.Field, Inherited=false, AllowMultiple=false)] public class LinkToContainerAttribute : Attribute { } [AttributeUsageAttribute(AttributeTargets.Method, Inherited=false, AllowMultiple=false)] public class NotifyOnConnectionToPeripheralAttribute : Attribute { // // State // public string RegisterName; } public abstract class Peripheral : AddressSpaceBusHandler { internal class FieldRegisterDescriptor : AddressSpaceHandler { delegate uint Reader( ); delegate void Writer( uint val ); // // State // private object m_target; private System.Reflection.MemberInfo m_mi; private Reader m_reader; private Writer m_writer; // // Helper Methods // public override bool CanAccess( uint address , uint relativeAddress , TargetAdapterAbstractionLayer.MemoryAccessType kind ) { return true; } public override uint Read( uint address , uint relativeAddress , TargetAdapterAbstractionLayer.MemoryAccessType kind ) { ulong clockTicks = m_owner.ClockTicks; uint value = m_reader(); // // If not handled, update the clock ticks here. // if(clockTicks == m_owner.ClockTicks) { UpdateClockTicksForLoad( address, kind ); } return value; } public override void Write( uint address , uint relativeAddress , uint value , TargetAdapterAbstractionLayer.MemoryAccessType kind ) { ulong clockTicks = m_owner.ClockTicks; m_writer( value ); // // If not handled, update the clock ticks here. // if(clockTicks == m_owner.ClockTicks) { UpdateClockTicksForStore( address, kind ); } } public override uint GetPhysicalAddress( uint address ) { return address; } //--// internal void Connect( Peripheral target , System.Reflection.MemberInfo mi , Type fieldType ) { m_target = target; m_mi = mi; //--// var fi = mi as System.Reflection.FieldInfo; if(fi != null) { if(fieldType == typeof(byte)) { m_reader = delegate( ) { return (uint)(byte)fi.GetValue( m_target ); }; m_writer = delegate( uint val ) { fi.SetValue( m_target, (byte)val ); }; } else if(fieldType == typeof(ushort)) { m_reader = delegate( ) { return (uint)(ushort)fi.GetValue( m_target ); }; m_writer = delegate( uint val ) { fi.SetValue( m_target, (ushort)val ); }; } else if(fieldType == typeof(uint)) { m_reader = delegate( ) { return (uint) fi.GetValue( m_target ); }; m_writer = delegate( uint val ) { fi.SetValue( m_target, val ); }; } } var pi = mi as System.Reflection.PropertyInfo; if(pi != null) { if(fieldType == typeof(byte)) { m_reader = delegate( ) { return pi.CanRead ? (uint)(byte )pi.GetValue( m_target , null ) : 0; }; m_writer = delegate( uint val ) { if( pi.CanWrite ) pi.SetValue( m_target, (byte )val, null ) ; }; } else if(fieldType == typeof(ushort)) { m_reader = delegate( ) { return pi.CanRead ? (uint)(ushort)pi.GetValue( m_target , null ) : 0; }; m_writer = delegate( uint val ) { if( pi.CanWrite ) pi.SetValue( m_target, (ushort)val, null ) ; }; } else if(fieldType == typeof(uint)) { m_reader = delegate( ) { return pi.CanRead ? (uint) pi.GetValue( m_target , null ) : 0; }; m_writer = delegate( uint val ) { if( pi.CanWrite ) pi.SetValue( m_target, val, null ) ; }; } } } } // // Constructor Methods // protected Peripheral() { } //--// // // Helper Methods // public virtual void OnConnected() { } public virtual void OnDisconnected() { } internal override void LinkToBus( AddressSpaceBusHandler bus ) { base.LinkToBus( bus ); foreach(var fi in ReflectionHelper.GetAllInstanceFields( this.GetType() )) { ProcessMember( bus, fi, fi.FieldType ); } foreach(var pi in ReflectionHelper.GetAllInstanceProperties( this.GetType() )) { ProcessMember( bus, pi, pi.PropertyType ); } m_owner.QueueLinkToPeripheral( null, null, this ); } internal override void UnlinkFromBus() { base.UnlinkFromBus(); OnDisconnected(); } private void ProcessMember( AddressSpaceBusHandler bus , System.Reflection.MemberInfo mi , Type fieldType ) { foreach(RegisterAttribute attrib in ReflectionHelper.GetAttributes< RegisterAttribute >( mi, false )) { uint offset = attrib.Offset; if(fieldType == typeof(byte)) { AddRegisterHandler( mi, fieldType, offset, sizeof(byte) ); } else if(fieldType == typeof(ushort)) { AddRegisterHandler( mi, fieldType, offset, sizeof(ushort) ); } else if(fieldType == typeof(uint)) { AddRegisterHandler( mi, fieldType, offset, sizeof(uint) ); } else if(fieldType.IsArray) { Type subType = fieldType.GetElementType(); if(subType.IsSubclassOf( typeof(Peripheral) )) { Array array = Array.CreateInstance( subType, attrib.Instances ); SetRegisterValue( mi, array ); for(int i = 0; i < attrib.Instances; i++) { Peripheral subPeripheral = AddSubHandler( subType, offset, attrib.Size, m_rangeWidth ); array.SetValue( subPeripheral, i ); offset += attrib.Size; } } } else if(fieldType.IsSubclassOf( typeof(Peripheral) )) { Peripheral subPeripheral = AddSubHandler( fieldType, offset, attrib.Size, m_rangeWidth ); SetRegisterValue( mi, subPeripheral ); } } if(ReflectionHelper.HasAttribute< LinkToContainerAttribute >( mi, false )) { Type typeParent = m_parent.GetType(); if(fieldType.IsAssignableFrom( typeParent )) { SetRegisterValue( mi, m_parent ); } else { throw TypeConsistencyErrorException.Create( "Field {0} has a type incompatible with the one of its container {1}", mi, m_parent.GetType() ); } } if(ReflectionHelper.HasAttribute< LinkToPeripheralAttribute >( mi, false )) { m_owner.QueueLinkToPeripheral( mi, fieldType, this ); } } internal void SetRegisterValue( MemberInfo mi , object value ) { var fi = mi as System.Reflection.FieldInfo; if(fi != null) { fi.SetValue( this, value ); return; } var pi = mi as System.Reflection.PropertyInfo; if(pi != null) { pi.SetValue( this, value, null ); return; } throw new NotSupportedException( string.Format( "No valid setter for '{0}'", mi ) ); } private object GetRegisterValue( MemberInfo mi ) { var fi = mi as System.Reflection.FieldInfo; if(fi != null) { return fi.GetValue( this ); } var pi = mi as System.Reflection.PropertyInfo; if(pi != null) { return pi.GetValue( this, null ); } throw new NotSupportedException( string.Format( "No valid getter for '{0}'", mi ) ); } private void AddRegisterHandler( System.Reflection.MemberInfo mi , Type fieldType , uint offset , uint size ) { FieldRegisterDescriptor rd = new FieldRegisterDescriptor(); rd.Initialize( m_owner, size, 0, m_readLatency, m_writeLatency ); rd.Connect( this, mi, fieldType ); AttachHandlerToBus( rd, offset ); } private Peripheral AddSubHandler( Type subType , uint offset , uint size , uint width ) { Peripheral sub = (Peripheral)Activator.CreateInstance( subType ); sub.Initialize( m_owner, size, width, m_readLatency, m_writeLatency ); AttachHandlerToBus( sub, offset ); return sub; } //--// internal void LinkedTo( System.Reflection.MemberInfo mi ) { foreach(var mi2 in ReflectionHelper.GetAllInstanceMethods( this.GetType() )) { foreach(var attrib in ReflectionHelper.GetAttributes< NotifyOnConnectionToPeripheralAttribute >( mi2, false )) { if(attrib.RegisterName == mi.Name) { mi2.Invoke( this, new object[0] ); } } } } //--// protected ulong Get64BitValue( uint low , uint high ) { return (ulong)low | ((ulong)high << 32); } protected void Set64BitValue( ulong value , out uint low , out uint high ) { low = (uint)(value ); high = (uint)(value >> 32); } //--// public static bool TestBitField( ushort val , ushort bitField ) { return (val & bitField) != 0; } public static bool TestBitField( uint val , uint bitField ) { return (val & bitField) != 0; } //--// public static void SetBitField( ref byte val , byte bitField ) { val |= bitField; } public static void SetBitField( ref ushort val , ushort bitField ) { val |= bitField; } public static void SetBitField( ref uint val , uint bitField ) { val |= bitField; } //--// public static void ClearBitField( ref byte val , byte bitField ) { val &= (byte)~bitField; } public static void ClearBitField( ref ushort val , ushort bitField ) { val &= (ushort)~bitField; } public static void ClearBitField( ref uint val , uint bitField ) { val &= ~bitField; } //--// public static void MaskedUpdateBitField( ref byte val , byte newVal , byte mask ) { val = (byte)((val & ~mask) | (newVal & mask)); } public static void MaskedUpdateBitField( ref ushort val , ushort newVal , ushort mask ) { val = (ushort)((val & ~mask) | (newVal & mask)); } public static void MaskedUpdateBitField( ref uint val , uint newVal , uint mask ) { val = (val & ~mask) | (newVal & mask); } //--// public static void UpdateBitField( ref byte val , byte bitField , bool fSet ) { if(fSet) { SetBitField( ref val, bitField ); } else { ClearBitField( ref val, bitField ); } } public static void UpdateBitField( ref ushort val , ushort bitField , bool fSet ) { if(fSet) { SetBitField( ref val, bitField ); } else { ClearBitField( ref val, bitField ); } } public static void UpdateBitField( ref uint val , uint bitField , bool fSet ) { if(fSet) { SetBitField( ref val, bitField ); } else { ClearBitField( ref val, bitField ); } } } class TopAddressSpaceBusHandler : AddressSpaceBusHandler { // // Constructor Methods // internal TopAddressSpaceBusHandler( Simulator owner ) { m_owner = owner; } } //--// public delegate void TrackLoad ( uint address, TargetAdapterAbstractionLayer.MemoryAccessType kind ); public delegate void TrackStore( uint address, uint value, TargetAdapterAbstractionLayer.MemoryAccessType kind ); public class TrackDetour { public const uint c_DetourOpcode = (EncDef.c_cond_AL << 28) | EncDef.op_Undefined; public static readonly Hosting.Interop.Callback[] SharedEmtpyArray = new Hosting.Interop.Callback[0]; // // State // public uint m_pc; public uint m_op; public bool m_active; public Hosting.Interop.Callback[] m_callsPre; public Hosting.Interop.Callback[] m_callsPost; // // Constructor Methods // public TrackDetour( uint pc ) { m_pc = pc; m_op = c_DetourOpcode; m_callsPre = SharedEmtpyArray; m_callsPost = SharedEmtpyArray; } } class TrackBreakpoint { // // State // internal readonly uint m_address; internal readonly Hosting.Interop.Callback m_call; private Hosting.Interop.Registration m_reg; // // Constructor Methods // internal TrackBreakpoint( uint address ) { m_address = address; m_call = this.Callback; } // // Helper Methods // private Hosting.Interop.CallbackResponse Callback() { return Hosting.Interop.CallbackResponse.StopExecution; } internal void Enable( Simulator owner ) { if(m_reg == null) { m_reg = owner.SetInterop( m_address, m_call, true, false ); } } internal void Disable( Simulator owner ) { if(m_reg != null) { owner.RemoveInterop( m_reg ); m_reg = null; } } } class InterruptHistory { class Context { // // State // internal uint m_programCounter; internal uint m_hits; internal GrowOnlyHashTable< uint, uint > m_ticksSpread; internal uint m_min; internal uint m_avg; internal uint m_max; // // Constructor Methods // internal Context( uint programCounter ) { m_programCounter = programCounter; m_ticksSpread = HashTableFactory.New< uint, uint >(); } // // Helper Methods // internal void Update( uint ticks ) { m_hits++; if(m_ticksSpread.ContainsKey( ticks )) { m_ticksSpread[ticks] += 1; } else { m_ticksSpread[ticks] = 1; } } internal void ComputeStatistics() { m_min = uint.MaxValue; m_max = uint.MinValue; uint sum = 0; uint tot = 0; foreach(uint ticks in m_ticksSpread.Keys) { uint count = m_ticksSpread[ticks]; m_min = Math.Min( ticks, m_min ); m_max = Math.Max( ticks, m_max ); sum += ticks * count; tot += count; } m_avg = sum / tot; } } // // State // uint m_mask; string m_id; ulong m_startClockTicks; uint m_startProgramCounter; GrowOnlyHashTable< uint, Context > m_locations; // // Constructor Methods // internal InterruptHistory( uint mask , string id ) { m_mask = mask; m_id = id; m_locations = HashTableFactory.New< uint, Context >(); } // // Helper Methods // internal void Process( Simulator owner , uint diff , uint cpsr ) { if((diff & m_mask) != 0) { if((cpsr & m_mask) != 0) { m_startClockTicks = owner.m_clockTicks; m_startProgramCounter = owner.m_pc - 4; } else if(m_startClockTicks != 0) { Context ctx; if(m_locations.TryGetValue( m_startProgramCounter, out ctx ) == false) { ctx = new Context( m_startProgramCounter ); m_locations[m_startProgramCounter] = ctx; } uint ticks = (uint)(owner.m_clockTicks - m_startClockTicks); ctx.Update( ticks ); } } } internal void Dump( Simulator owner ) { Hosting.OutputSink sink; if(owner.GetHostingService( out sink )) { if(m_locations.Count > 0) { Context[] locations = m_locations.ValuesToArray(); foreach(Context ctx in locations) { ctx.ComputeStatistics(); } sink.OutputLine( "Sites for {0} disabling:", m_id ); sink.OutputLine( "
// " ); sink.OutputLine( "" ); Array.Sort( locations, delegate( Context left, Context right ) { return - left.m_max.CompareTo( right.m_max ); } ); foreach(Context ctx in locations) { uint context; string fmt; string name; if(owner.GetContext( ctx.m_programCounter, out context )) { fmt = " 0x{0:X8} {1,4}/{2,4}/{3,4} {4}"; name = owner.m_symdef_Inverse[context]; } else { fmt = " 0x{0:X8} {1,4}/{2,4}/{3,4}"; name = ""; } sink.OutputLine( fmt, ctx.m_programCounter, ctx.m_min, ctx.m_avg, ctx.m_max, name ); } sink.OutputLine( "" ); } } } } //--// public delegate void CodeCoverageEnumeration( uint address , uint hits , uint cycles , uint waitStates ); private class CodeCoverageCluster { internal struct Entry { // // State // internal uint m_hits; internal uint m_cycles; internal uint m_waitStates; // // Helper Methods // internal void Update( uint cycles , uint waitStates ) { m_hits += 1; m_cycles += cycles; m_waitStates += waitStates; } internal void Enumerate( uint address , CodeCoverageEnumeration callback ) { if(m_hits != 0) { callback( address, m_hits, m_cycles, m_waitStates ); } } } // // State // const int c_ClusterSize = 512; internal SortedDictionary< uint, Entry[] > m_clusters; internal uint m_lastClusterIndex; internal Entry[] m_lastCluster; // // Constructor Methods // internal CodeCoverageCluster() { m_clusters = new SortedDictionary< uint, Entry[] >(); Reset(); } // // Helper Methods // internal void Reset() { m_clusters.Clear(); // // Initialize at least one cluster, so lastCluster is always valid. // m_lastClusterIndex = 0; m_lastCluster = new Entry[c_ClusterSize]; m_clusters.Add( m_lastClusterIndex, m_lastCluster ); } internal void Update( uint address , uint cycles , uint waitStates ) { Entry[] cluster; uint word = address / sizeof(uint); uint index = word / c_ClusterSize; uint offset = word % c_ClusterSize; if(m_lastClusterIndex == index) { cluster = m_lastCluster; } else { if(m_clusters.TryGetValue( index, out cluster ) == false) { cluster = new Entry[c_ClusterSize]; m_clusters.Add( index, cluster ); } m_lastClusterIndex = index; m_lastCluster = cluster; } cluster[offset].Update( cycles, waitStates ); } internal void Enumerate( CodeCoverageEnumeration callback ) { foreach(KeyValuePair< uint, Entry[] > pair in m_clusters) { uint address = pair.Key * c_ClusterSize * sizeof(uint); Entry[] cluster = pair.Value; for(uint offset = 0; offset < c_ClusterSize; offset++, address += sizeof(uint)) { cluster[offset].Enumerate( address, callback ); } } } } private class PendingLinkToPeripheral { // // State // internal System.Reflection.MemberInfo m_mi; internal Type m_fieldType; internal Peripheral m_peripheral; // // Constructor Methods // internal PendingLinkToPeripheral( System.Reflection.MemberInfo mi , Type fieldType , Peripheral peripheral ) { m_mi = mi; m_fieldType = fieldType; m_peripheral = peripheral; } } private class PendingLinkToBus { // // State // internal Cfg.BusAttachedCategory m_category; internal AddressSpaceHandler m_handler; internal uint m_address; // // Constructor Methods // internal PendingLinkToBus( Cfg.BusAttachedCategory category , AddressSpaceHandler handler , uint address ) { m_category = category; m_handler = handler; m_address = address; } } // // State // protected bool m_fMonitorMemory; protected bool m_fMonitorRegisters; protected bool m_fMonitorOpcodes; protected bool m_fMonitorCalls; protected bool m_fMonitorInterrupts; protected bool m_fMonitorInterruptDisabling; protected bool m_fMonitorCoverage; protected bool m_fNoSleep; protected volatile bool m_fStopExecution; protected bool m_fRollbackFetch; protected AddressSpaceBusHandler m_topAddressSpaceHandler; protected InteropHandler[] m_interopHandlers; private List < PendingLinkToBus > m_pendingLinkToBus; private Queue< PendingLinkToPeripheral > m_pendingLinkToPeripheral; private ProcessorControlImpl m_implProcessorControl; private ProcessorStatusImpl m_implProcessorStatus; private ProcessorPerformanceImpl m_implProcessorPerformance; private MonitorExecutionImpl m_implMonitorExecution; private DeviceClockTicksTrackingImpl m_implDeviceClockTicksTracking; protected TimingState m_executionTimingState; private Hosting.OutputSink m_execution_OutputSink; // // Code coverage fields. // private CodeCoverageImpl m_implCodeCoverage; private CodeCoverageCluster m_codeCoverageClusters; // // Register monitoring fields. // private uint[] m_registersBefore = new uint[16]; // // Interrupt disabling history fields. // private InterruptHistory m_IRQ_history; private InterruptHistory m_FIQ_history; //--// private InteropImpl m_implInterop; protected Dictionary< uint, TrackDetour > m_detours; protected TrackLoad m_eventTrackLoad; protected TrackStore m_eventTrackStore; //--// protected SymDef.SymbolToAddressMap m_symdef; protected SymDef.AddressToSymbolMap m_symdef_Inverse; protected SymDef.AddressToSymbolMap m_symdef_Inverse_PhysicalAddress; // // Constructor Methods // public Simulator(InstructionSet iset) : base(iset) { m_fMonitorMemory = false; m_fMonitorRegisters = false; m_fMonitorOpcodes = false; m_fMonitorCalls = false; m_fStopExecution = false; m_topAddressSpaceHandler = new TopAddressSpaceBusHandler( this ); m_interopHandlers = InteropHandler.SharedEmptyArray; m_pendingLinkToBus = new List < PendingLinkToBus >(); m_pendingLinkToPeripheral = new Queue< PendingLinkToPeripheral >(); m_codeCoverageClusters = new CodeCoverageCluster(); m_detours = new Dictionary< uint, TrackDetour >(); //--// m_implProcessorControl = new ProcessorControlImpl ( this ); m_implProcessorPerformance = new ProcessorPerformanceImpl ( this ); m_implProcessorStatus = new ProcessorStatusImpl ( this ); m_implMonitorExecution = new MonitorExecutionImpl ( this ); m_implDeviceClockTicksTracking = new DeviceClockTicksTrackingImpl( this ); m_implCodeCoverage = new CodeCoverageImpl ( this ); m_implInterop = new InteropImpl ( this ); this.RegisterService( typeof(Simulator), this ); } // // Helper Methods // void PrepareHardwareModels( Cfg.ProductCategory product ) { SetHardwareModel( product ); } void DeployImage( List< Configuration.Environment.ImageSection > image , Emulation.Hosting.ProcessorControl.ProgressCallback callback ) { foreach(var section in image) { if(section.NeedsRelocation == false) { if(CanAccess( section.Address, TargetAdapterAbstractionLayer.MemoryAccessType.UINT32 )) { LoadMemoryBlock( section.Address, section.Payload ); } } } } //--// public override void Reset() { m_topAddressSpaceHandler.UnlinkFromBus(); base.Reset(); m_fStopExecution = false; m_topAddressSpaceHandler = new TopAddressSpaceBusHandler( this ); m_interopHandlers = InteropHandler.SharedEmptyArray; m_detours .Clear(); m_eventTrackLoad = null; m_eventTrackStore = null; m_implProcessorStatus .ResetState(); m_implDeviceClockTicksTracking.ResetState(); m_symdef = null; m_symdef_Inverse = null; m_symdef_Inverse_PhysicalAddress = null; m_executionTimingState = new TimingState(); m_execution_OutputSink = null; m_IRQ_history = new InterruptHistory( EncDef.c_psr_I, "IRQ" ); m_FIQ_history = new InterruptHistory( EncDef.c_psr_F, "FIQ" ); SuspendTimingUpdates( ref m_executionTimingState ); } //--// public virtual void SetSymbols( SymDef.SymbolToAddressMap symdef , SymDef.AddressToSymbolMap symdef_Inverse ) { m_symdef = symdef; m_symdef_Inverse = symdef_Inverse; m_symdef_Inverse_PhysicalAddress = null; } public void LoadMemoryBlock( uint address , byte[] data ) { for(int i = 0; i < data.Length; i++) { if((address % 4) == 0 && i + 4 <= data.Length) { uint value = (uint)(data[i+0] ) | (uint)(data[i+1] << 8) | (uint)(data[i+2] << 16) | (uint)(data[i+3] << 24) ; Store( address, value, TargetAdapterAbstractionLayer.MemoryAccessType.UINT32 ); address += 4; i += 3; } else { Store( address, data[i], TargetAdapterAbstractionLayer.MemoryAccessType.UINT8 ); address += 1; } } } //--// public virtual void SpinUntilInterrupts() { while(m_fStopExecution == false) { while(m_implDeviceClockTicksTracking.ShouldProcessClockTicksCallback( m_clockTicks )) { m_implDeviceClockTicksTracking.ProcessClockTicksCallback(); if(m_fStopExecution) { return; } } if(m_interruptStatus != 0) { break; } long sleepClockTicks = m_implDeviceClockTicksTracking.TimeToNextCallback( m_clockTicks ); TimeSpan tm = sleepClockTicks < 0 ? TimeSpan.FromMilliseconds( 1000 ) : ClockTicksToTime( sleepClockTicks ); DateTime start = DateTime.Now; if(m_fNoSleep || tm.TotalMilliseconds < 0.5) { // // Skip the sleep. // } else { Hosting.SimulatorControl sink; if(this.GetHostingService( out sink )) { sink.Wait( tm ); TimeSpan slept = DateTime.Now - start; if(slept < tm) { sleepClockTicks = TimeToClockTicks( slept ); } } } UpdateSleepTicks( sleepClockTicks ); } } //--// protected override void SetHardwareModel( Cfg.ProductCategory product ) { base.SetHardwareModel( product ); m_implDeviceClockTicksTracking.ClockFrequency = m_clockFrequency; foreach(Cfg.AbstractCategory.ValueContext ctx in product.SearchValues( typeof(Cfg.AbstractCategory) )) { var category = ctx.Value as Cfg.AbstractCategory; if(category != null) { Type t = category.Model; if(t != null) { if(category is Cfg.MemoryCategory) { CreateMemory( (Cfg.MemoryCategory)category ); } if(category is Cfg.PeripheralCategory) { CreatePeripheral( (Cfg.PeripheralCategory)category ); } if(category is Cfg.InteropCategory) { CreateInterop( (Cfg.InteropCategory)category ); } } } } do { ProcessPendingLinkToBus(); ProcessPendingLinkToPeripheral(); } while(m_pendingLinkToBus.Count > 0); if(m_symdef_Inverse != null && m_symdef_Inverse_PhysicalAddress == null) { m_symdef_Inverse_PhysicalAddress = new SymDef.AddressToSymbolMap(); foreach(uint address in m_symdef_Inverse.Keys) { m_symdef_Inverse_PhysicalAddress[GetPhysicalAddress(address)] = m_symdef_Inverse[address]; } } } private void QueueLinkToBus( Cfg.BusAttachedCategory category , AddressSpaceHandler handler , uint address ) { if(category.ConnectedToBus != null) { m_pendingLinkToBus.Add( new PendingLinkToBus( category, handler, address ) ); } } private void ProcessPendingLinkToBus() { for(int i = 0; i < m_pendingLinkToBus.Count; ) { PendingLinkToBus link = m_pendingLinkToBus[i]; Type t = link.m_category.ConnectedToBus; AddressSpaceBusHandler bus = null; // // The 'ConnectedToBus' field refers to the definition type, we need to find the actual model. // foreach(Cfg.HardwareModelAttribute attrib in ReflectionHelper.GetAttributes< Cfg.HardwareModelAttribute >( t, true )) { bus = m_topAddressSpaceHandler.FindHandler( attrib.Target ) as AddressSpaceBusHandler; if(bus != null) { break; } } if(bus == null) { if(t.IsSubclassOf( typeof(Cfg.ProcessorCategory) )) { bus = m_topAddressSpaceHandler; } else { bus = m_topAddressSpaceHandler.FindHandler( t ) as AddressSpaceBusHandler; } } if(bus != null) { bus.AttachHandlerToBus( link.m_handler, link.m_address ); m_pendingLinkToBus.RemoveAt( i ); i = 0; } else { i++; } } if(m_pendingLinkToBus.Count != 0) { // // More than one model might be broken, just report the first one. // PendingLinkToBus link = m_pendingLinkToBus[0]; throw new NotSupportedException( string.Format( "Failed to initialize model '{0}': bus '{1}' does not exist", link.m_handler, link.m_category.ConnectedToBus ) ); } } //--// public void FindMemory( out T res ) where T : AddressSpaceHandler { res = (T)m_topAddressSpaceHandler.FindHandler( typeof(T) ); } public AddressSpaceHandler FindMemoryAtAddress( uint address ) { return m_topAddressSpaceHandler.FindHandlerAtAddress( address ); } private void CreateMemory( Cfg.MemoryCategory mem ) { Type t = mem.Model; if(t != null) { if(t.IsSubclassOf( typeof(AddressSpaceHandler) )) { var handler = (AddressSpaceHandler)Activator.CreateInstance( t ); uint latency = mem.WaitStates + 1; handler.Initialize( this, mem.SizeInBytes, mem.WordSize, latency, latency ); QueueLinkToBus( mem, handler, mem.BaseAddress ); return; } } throw TypeConsistencyErrorException.Create( "Unrecognized handler for {0}", mem ); } //--// public T FindInterface() where T : class { return (T)m_topAddressSpaceHandler.FindInterface( typeof(T) ); } public IEnumerable FindInterfaces() where T : class { foreach(var res in m_topAddressSpaceHandler.FindInterfaces( typeof(T) )) { yield return (T)res; } } //--// public Peripheral FindPeripheral( Type cls ) { return (Peripheral)m_topAddressSpaceHandler.FindHandler( cls ); } public void FindPeripheral( out T res ) where T : Peripheral { res = (T)FindPeripheral( typeof(T) ); } private void CreatePeripheral( Cfg.PeripheralCategory category ) { Peripheral peripheral = null; foreach(PeripheralRangeAttribute attrib in ReflectionHelper.GetAttributes< PeripheralRangeAttribute >( category.Model, true )) { if(peripheral == null) { peripheral = (Peripheral)Activator.CreateInstance( category.Model ); uint readLatency = 1; uint writeLatency = 1; if(attrib.Latency != 0) { readLatency = attrib.Latency; writeLatency = attrib.Latency; } if(attrib.ReadLatency != 0) { readLatency = attrib.ReadLatency; } if(attrib.WriteLatency != 0) { writeLatency = attrib.WriteLatency; } peripheral.Initialize( this, attrib.Length, attrib.WordSize, readLatency, writeLatency ); } QueueLinkToBus( category, peripheral, attrib.Base ); } if(peripheral == null) { throw new NotSupportedException( string.Format( "{0} does not have any PeripheralRange attribute", category.Model ) ); } } public void QueueLinkToPeripheral( System.Reflection.MemberInfo mi , Type fieldType , Peripheral peripheral ) { m_pendingLinkToPeripheral.Enqueue( new PendingLinkToPeripheral( mi, fieldType, peripheral ) ); } protected void ProcessPendingLinkToPeripheral() { while(m_pendingLinkToPeripheral.Count > 0) { PendingLinkToPeripheral link = m_pendingLinkToPeripheral.Dequeue(); System.Reflection.MemberInfo mi = link.m_mi; Type fieldType = link.m_fieldType; Peripheral peripheral = link.m_peripheral; if(mi == null) { peripheral.OnConnected(); } else { Peripheral target = FindPeripheral( fieldType ); if(target != null) { peripheral.SetRegisterValue( mi, target ); peripheral.LinkedTo( mi ); } else { throw TypeConsistencyErrorException.Create( "Cannot resolve link to peripheral {0} from {1}::{2}", fieldType, peripheral.GetType(), mi.Name ); } } } } //--// private void CreateInterop( Cfg.InteropCategory category ) { var interop = (InteropHandler)Activator.CreateInstance( category.Model ); interop.CreateInterop( this ); m_interopHandlers = ArrayUtility.AppendToNotNullArray( m_interopHandlers, interop ); } //--// public override bool CanAccess( uint address , TargetAdapterAbstractionLayer.MemoryAccessType kind ) { return m_topAddressSpaceHandler.CanAccess( address, address, kind ); } public override uint Load( uint address , TargetAdapterAbstractionLayer.MemoryAccessType kind ) { m_busAccess_Read++; if(m_eventTrackLoad != null) { m_eventTrackLoad( address, kind ); } //// if((address & 0xFFFFFF00) == 0xDEADBE00) //// { //// throw new DataAbortException( address, kind ); //// } return m_topAddressSpaceHandler.Read( address, address, kind ); } public override void Store( uint address , uint value , TargetAdapterAbstractionLayer.MemoryAccessType kind ) { m_busAccess_Write++; if(m_eventTrackStore != null) { m_eventTrackStore( address, value, kind ); } //// if((address & 0xFFFFFF00) == 0xDEADBE00) //// { //// throw new DataAbortException( address, kind ); //// } m_topAddressSpaceHandler.Write( address, address, value, kind ); } public override uint TimeMemoryAccess( uint address , TargetAdapterAbstractionLayer.MemoryAccessType kind ) { var backup = new TimingState(); SuspendTimingUpdates( ref backup ); Load( address, kind ); uint res = (uint)(m_clockTicks - backup.m_clockTicks); ResumeTimingUpdates( ref backup ); return res; } public override uint GetPhysicalAddress( uint address ) { return m_topAddressSpaceHandler.GetPhysicalAddress( address ); } //--// public virtual void Execute( List< Hosting.Breakpoint > breakpoints ) { List< TrackBreakpoint > res = PrepareToExecute( breakpoints ); #if TRACK_EMULATOR_PERFORMANCE DateTime start = DateTime.Now; ulong clockTicks = m_clockTicks; ulong count = 1; Hosting.OutputSink sink; this.GetHostingService( out sink ); #endif ResumeTimingUpdates( ref m_executionTimingState ); this.GetHostingService( out m_execution_OutputSink ); m_implProcessorControl.Notify( Hosting.ProcessorControl.State.Stopped , Hosting.ProcessorControl.State.Starting ); m_implProcessorControl.Notify( Hosting.ProcessorControl.State.Starting, Hosting.ProcessorControl.State.Executing ); //--// while(m_fStopExecution == false) { #if TRACK_EMULATOR_PERFORMANCE const uint stepMonitor = 1024 * 1024; if((count % stepMonitor) == 0) { if(sink != null) { TimeSpan diff = DateTime.Now - start; double seconds = diff.TotalSeconds; double realTicks = TimeToClockTicks( diff ); sink.OutputLine( "#### {0} ops, {1:F1} slowdown ratio", (int)(stepMonitor / seconds), realTicks / (m_clockTicks - clockTicks) ); start = DateTime.Now; clockTicks = m_clockTicks; } } count++; #endif ExecuteStepInner(); } //--// m_implProcessorControl.Notify( Hosting.ProcessorControl.State.Executing, Hosting.ProcessorControl.State.Stopping ); SuspendTimingUpdates( ref m_executionTimingState ); CleanupAfterExecution( res ); m_implProcessorControl.Notify( Hosting.ProcessorControl.State.Stopping, Hosting.ProcessorControl.State.Stopped ); } public virtual void ExecuteStep( List< Hosting.Breakpoint > breakpoints ) { List< TrackBreakpoint > res = PrepareToExecute( breakpoints ); ResumeTimingUpdates( ref m_executionTimingState ); this.GetHostingService( out m_execution_OutputSink ); m_implProcessorControl.Notify( Hosting.ProcessorControl.State.Stopped , Hosting.ProcessorControl.State.Starting ); m_implProcessorControl.Notify( Hosting.ProcessorControl.State.Starting, Hosting.ProcessorControl.State.Executing ); //--// ExecuteStepInner(); //--// m_implProcessorControl.Notify( Hosting.ProcessorControl.State.Executing, Hosting.ProcessorControl.State.Stopping ); SuspendTimingUpdates( ref m_executionTimingState ); CleanupAfterExecution( res ); m_implProcessorControl.Notify( Hosting.ProcessorControl.State.Stopping, Hosting.ProcessorControl.State.Stopped ); } private List< TrackBreakpoint > PrepareToExecute( List< Hosting.Breakpoint > breakpoints ) { var res = new List< TrackBreakpoint >(); foreach(var bp in breakpoints) { var track = new TrackBreakpoint( bp.Address ); track.Enable( this ); res.Add( track ); } // // Prepare Interop detours. // ApplyInterops(); Hosting.OutputSink sink; if(this.GetHostingService( out sink )) { sink.StartOutput(); } return res; } private void CleanupAfterExecution( List< TrackBreakpoint > res ) { foreach(TrackBreakpoint track in res) { track.Disable( this ); } if(m_fMonitorInterruptDisabling) { m_IRQ_history.Dump( this ); m_FIQ_history.Dump( this ); } } private void ExecuteStepInner() { while(m_implDeviceClockTicksTracking.ShouldProcessClockTicksCallback( m_clockTicks )) { m_implDeviceClockTicksTracking.ProcessClockTicksCallback(); if(m_fStopExecution) { return; } } uint interruptMask = (m_interruptStatus & ~m_cpsr); if(interruptMask != 0) { uint cpsrPost = m_cpsr & ~EncDef.c_psr_mode; uint targetPC; if((interruptMask & EncDef.c_psr_F) != 0) { if(m_fMonitorInterrupts) { if(m_execution_OutputSink != null) { m_execution_OutputSink.OutputLine( "#### Dispatching FIQ interrupt" ); } } cpsrPost |= EncDef.c_psr_mode_FIQ; cpsrPost |= EncDef.c_psr_F; cpsrPost |= EncDef.c_psr_I; targetPC = 0x0000001C; } else { if(m_fMonitorInterrupts) { if(m_execution_OutputSink != null) { m_execution_OutputSink.OutputLine( "#### Dispatching IRQ interrupt" ); } } cpsrPost |= EncDef.c_psr_mode_IRQ; cpsrPost |= EncDef.c_psr_I; targetPC = 0x00000018; } uint spsr = m_cpsr; SwitchMode( cpsrPost ); SetRegister( RegisterLookup.SPSR , spsr ); SetRegister( EncDef.c_register_lr, m_pc + 4 ); m_pc = targetPC; } //--// uint pc = m_pc; uint instructionStart_clockTicks = (uint)m_clockTicks; uint instructionStart_busAccess_WaitStates = (uint)m_busAccess_WaitStates; uint instruction; try { instruction = Load( pc, TargetAdapterAbstractionLayer.MemoryAccessType.FETCH ); } catch(Exception e) { if(m_execution_OutputSink != null) { m_execution_OutputSink.OutputLine( "FETCH ABORT at 0x{0:x8} for {1}", pc, e ); } m_fStopExecution = true; throw; } if(m_fMonitorCalls) { SniffForCallPop( m_currentBank.m_mode, m_currentBank.m_mode ); SniffForCallPush(); } //--//--//--//--//--//--//--//--//--//--//--// #if ARMEMULATOR_VERIFY_ENCODING try { uint instruction2 = Load( pc, MemoryAccessType.UINT32 ); InstructionSet.Opcode op = m_instructionSet.Decode( instruction2 ); uint instruction3 = op.Encode(); if(instruction != instruction2) { uint target; bool targetIsCode; string res = m_instructionSet.DecodeAndPrint( pc, instruction, out target, out targetIsCode ); if(m_execution_OutputSink != null) { m_execution_OutputSink.OutputLine( "MISMATCH: {0:X8} != {1:X8} 0x{2:X8}: {3}", instruction2, instruction3, pc, res ); } } } catch { } #endif if(m_fMonitorOpcodes) { uint opcode = instruction; if(opcode == TrackDetour.c_DetourOpcode) { opcode = m_detours[ pc ].m_op; } try { InstructionSet.Opcode op = m_instructionSet.Decode( opcode ); bool fExecuted = CheckConditions( op.ConditionCodes ); uint target; bool targetIsCode; string res = m_instructionSet.DecodeAndPrint( pc, opcode, out target, out targetIsCode ); if(m_execution_OutputSink != null) { m_execution_OutputSink.OutputLine( "{0,-9} 0x{1:X8}: {2:X8} {3}{4}{5}{6} {7} {8}", instructionStart_clockTicks, pc, opcode, Negative() != 0 ? 'N' : '-', Zero() != 0 ? 'Z' : '-', Carry() != 0 ? 'C' : '-', Overflow() != 0 ? 'V' : '-', fExecuted ? ' ' : '*', res ); } } catch(Exception e) { if(m_execution_OutputSink != null) { m_execution_OutputSink.OutputLine( "DECODE ABORT at 0x{0:X8} for {1}", pc, e ); } throw; } } try { if(m_fMonitorRegisters) { for(uint reg = EncDef.c_register_r0; reg < EncDef.c_register_r15; reg++) { m_registersBefore[reg] = GetRegister( reg ); } Execute( instruction ); for(uint reg = EncDef.c_register_r0; reg < EncDef.c_register_r15; reg++) { if(m_registersBefore[reg] != GetRegister( reg )) { if(m_execution_OutputSink != null) { m_execution_OutputSink.OutputLine( " {0} {1,-4} : 0x{2:X8} -> 0x{3:X8}", new string( ' ', 80 ), InstructionSet.Opcode.DumpRegister( reg ), m_registersBefore[reg], GetRegister( reg ) ); } } } } else { Execute( instruction ); } if(m_fRollbackFetch) { m_clockTicks = instructionStart_clockTicks; m_busAccess_WaitStates = instructionStart_busAccess_WaitStates; m_fRollbackFetch = false; } } catch(Exception e) { if(m_execution_OutputSink != null) { m_execution_OutputSink.OutputLine( "EXECUTION ABORT at 0x{0:X8} for {1}", pc, e ); } throw; } if(m_fMonitorCoverage) { uint cycles = (uint)m_clockTicks - instructionStart_clockTicks; uint waitStates = (uint)m_busAccess_WaitStates - instructionStart_busAccess_WaitStates; m_codeCoverageClusters.Update( pc, cycles, waitStates ); } } public override void SwitchMode( uint mode ) { BankedRegisters from = GetShadowRegisters( m_cpsr ); BankedRegisters to = GetShadowRegisters( mode ); if(m_fMonitorInterrupts && from != to) { if(m_execution_OutputSink != null) { m_execution_OutputSink.OutputLine( "#### Leaving mode {0}, PC={1:X8}, LR={2:X8}" , InstructionSet.DumpMode( m_cpsr ), m_pc, GetRegister( EncDef.c_register_lr ) ); } } if(m_fMonitorCalls) { SniffForCallPop( from.m_mode, to.m_mode ); } base.SwitchMode( mode ); if(m_fMonitorInterrupts && from != to) { if(m_execution_OutputSink != null) { m_execution_OutputSink.OutputLine( "#### Entering mode {0}, PC={1:X8}, LR={2:X8}" , InstructionSet.DumpMode( m_cpsr ), m_pc, GetRegister( EncDef.c_register_lr ) ); } } } //--// protected override void ProcessInterruptDisabling( uint cpsrPre , uint cpsrPost ) { if(m_fMonitorInterruptDisabling) { uint diff = (cpsrPre ^ cpsrPost); if((diff & (EncDef.c_psr_I | EncDef.c_psr_F)) != 0) { m_IRQ_history.Process( this, diff, cpsrPost ); m_FIQ_history.Process( this, diff, cpsrPost ); } } } protected override bool ProcessUnsupportedOperation( uint op ) { if(op == TrackDetour.c_DetourOpcode) { m_pc -= 4; // // Copy, not reference, the entry can be removed from the map by the interop code. // TrackDetour detour = m_detours[ m_pc ]; var res = ProcessDetour( detour, detour.m_callsPre, false ); if((res & Hosting.Interop.CallbackResponse.StopExecution) != 0) { m_fStopExecution = true; m_fRollbackFetch = true; // We need to rollback the fetch, to get accurate timing. return true; } if((res & Hosting.Interop.CallbackResponse.NextInstruction) != 0) { return true; } Execute( detour.m_op ); res = ProcessDetour( detour, detour.m_callsPost, true ); if((res & Hosting.Interop.CallbackResponse.StopExecution) != 0) { m_fStopExecution = true; return true; } return true; } return false; } //--// internal void SuspendInterops() { foreach(TrackDetour detour in m_detours.Values) { SuspendInterop( detour ); } } internal void SuspendInterop( TrackDetour detour ) { if(detour.m_active) { detour.m_active = false; TimingState state = new TimingState(); SuspendTimingUpdates( ref state ); Store( detour.m_pc, detour.m_op, TargetAdapterAbstractionLayer.MemoryAccessType.FETCH ); ResumeTimingUpdates( ref state ); } } private void ApplyInterops() { foreach(TrackDetour detour in m_detours.Values) { ApplyInterop( detour ); } } private void ApplyInterop( TrackDetour detour ) { if(detour.m_active == false) { if(CanAccess( detour.m_pc, TargetAdapterAbstractionLayer.MemoryAccessType.FETCH )) { TimingState state = new TimingState(); SuspendTimingUpdates( ref state ); uint mem = Load( detour.m_pc, TargetAdapterAbstractionLayer.MemoryAccessType.FETCH ); if(mem != TrackDetour.c_DetourOpcode) { detour.m_op = mem; Store( detour.m_pc, TrackDetour.c_DetourOpcode, TargetAdapterAbstractionLayer.MemoryAccessType.FETCH ); detour.m_active = true; } ResumeTimingUpdates( ref state ); } } } private Hosting.Interop.CallbackResponse ProcessDetour( TrackDetour detour , Hosting.Interop.Callback[] calls , bool fPostProcessing ) { foreach(Hosting.Interop.Callback ftn in calls) { var res = ftn(); if((res & Hosting.Interop.CallbackResponse.RemoveDetour) != 0) { res &= ~Hosting.Interop.CallbackResponse.RemoveDetour; RemoveInterop( new Hosting.Interop.Registration( detour.m_pc, fPostProcessing, ftn ) ); } if(res != Hosting.Interop.CallbackResponse.DoNothing) { return res; } } return Hosting.Interop.CallbackResponse.DoNothing; } private void RemoveDetour( TrackDetour detour ) { m_detours.Remove( detour.m_pc ); if(detour.m_op != TrackDetour.c_DetourOpcode) { Store( detour.m_pc, detour.m_op, TargetAdapterAbstractionLayer.MemoryAccessType.FETCH ); } } public uint HandleDetour( uint address , uint value ) { TrackDetour detour; if(m_detours.TryGetValue( address, out detour )) { if(detour.m_active) { return detour.m_op; } } return value; } public bool UpdateDetour( uint address , uint newValue ) { TrackDetour detour; if(m_detours.TryGetValue( address, out detour )) { if(detour.m_active) { detour.m_op = newValue; return true; } } return false; } //--// public void RemoveInterop( Hosting.Interop.Registration reg ) { TrackDetour detour; if(m_detours.TryGetValue( reg.Address, out detour )) { Hosting.Interop.Callback[] calls = reg.IsPostProcessing ? detour.m_callsPost : detour.m_callsPre; calls = ArrayUtility.RemoveUniqueFromNotNullArray( calls, reg.Target ); if(reg.IsPostProcessing) { detour.m_callsPost = calls; } else { detour.m_callsPre = calls; } if(detour.m_callsPre .Length == 0 && detour.m_callsPost.Length == 0 ) { RemoveDetour( detour ); } } } public void SetInterop( string name , Hosting.Interop.Callback ftn , bool fPostProcessing ) { uint pc; if(m_symdef.TryGetValue( name, out pc )) { SetInterop( pc, ftn, false, fPostProcessing ); } } public Hosting.Interop.Registration SetInterop( uint pc , Hosting.Interop.Callback ftn , bool fHead , bool fPostProcessing ) { TrackDetour detour; if(m_detours.TryGetValue( pc, out detour ) == false) { detour = new TrackDetour( pc ); m_detours[pc] = detour; ApplyInterop( detour ); } Hosting.Interop.Callback[] calls = fPostProcessing ? detour.m_callsPost : detour.m_callsPre; if(ArrayUtility.FindInNotNullArray( calls, ftn ) < 0) { if(fHead) { calls = ArrayUtility.InsertAtHeadOfNotNullArray( calls, ftn ); } else { calls = ArrayUtility.AppendToNotNullArray( calls, ftn ); } if(fPostProcessing) { detour.m_callsPost = calls; } else { detour.m_callsPre = calls; } } return new Hosting.Interop.Registration( pc, fPostProcessing, ftn ); } public string GetContext() { uint context; if(GetContext( m_pc, out context )) { return m_symdef_Inverse[context]; } else { return "??"; } } public bool GetContext( uint address , out uint context ) { SymDef.AddressToSymbolMap map; uint closestAddress; context = 0; if(m_symdef_Inverse_PhysicalAddress != null) { map = m_symdef_Inverse_PhysicalAddress; address = GetPhysicalAddress( address ); } else { map = m_symdef_Inverse; } if(map.FindClosestAddress( address, out closestAddress )) { string symbol = map[closestAddress]; return m_symdef.TryGetValue( symbol, out context ); } return false; } //--//--// private void SniffForCallPush() { uint pc = m_pc; uint context; if(GetContext( pc, out context ) && pc == context) { List< TrackCall > callQueue = m_currentBank.m_callQueue; int pos = callQueue.Count; uint sp = GetRegister( EncDef.c_register_sp ); string name = m_symdef_Inverse[ context ]; while(true) { if(name == "NoClearZI_ER_RAM") break; if(name == "ClearZI_ER_RAM" ) break; if(name == "ARM_Vectors" ) break; if(name == "IRQ_VECTOR" ) break; TrackCall tc = new TrackCall(); tc.m_pc = pc; tc.m_lr = GetRegister( EncDef.c_register_lr ); tc.m_sp = sp; tc.m_name = name; tc.m_te.Start( this ); callQueue.Add( tc ); if(m_execution_OutputSink != null) { m_execution_OutputSink.OutputLine( "{0}>>>> CALL {1} {2}", new string( ' ', pos ), tc.m_name, m_clockTicks ); } break; } } } private void SniffForCallPop( uint psrFrom , uint psrTo ) { List< TrackCall > callQueue = m_currentBank.m_callQueue; int pos = callQueue.Count; uint pc = m_pc; uint sp = GetRegister( EncDef.c_register_sp ); for(int pos2 = pos; pos2-- > 0; ) { TrackCall tc = callQueue[pos2]; if(tc.m_lr == pc && tc.m_sp == sp) { } else if(tc.m_sp != 0 && tc.m_sp < sp) { } else if(tc.m_sp == sp && psrFrom != psrTo && (psrFrom == EncDef.c_psr_mode_IRQ || psrFrom == EncDef.c_psr_mode_FIQ ) ) { } else { return; } while(pos-- > pos2) { TrackCall tc2 = callQueue[pos]; tc2.m_te.End( this ); if(m_execution_OutputSink != null) { m_execution_OutputSink.OutputLine( "{0}<<<< CALL {1} ({2}) {3}", new string( ' ', pos ), tc2.m_name, tc2.m_te.ToString(), m_clockTicks ); } callQueue.RemoveAt( pos ); } pos++; } } //--//--// public Hosting.Interop.CallbackResponse Interop_GenericSkipCall() { // // Force return from function. // m_pc = GetRegister( EncDef.c_register_lr ); m_implProcessorStatus.RaiseExternalProgramFlowChange(); return Hosting.Interop.CallbackResponse.NextInstruction; } //--// // // Access Methods // public event TrackLoad NotifyOnLoad { add { m_eventTrackLoad += value; } remove { m_eventTrackLoad -= value; } } public event TrackStore NotifyOnStore { add { m_eventTrackStore += value; } remove { m_eventTrackStore -= value; } } } } ================================================ FILE: Zelig/Zelig/DebugTime/ArmProcessorEmulation/SimulatorCore.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // namespace Microsoft.Zelig.Emulation.ArmProcessor { using System; using System.Collections.Generic; using System.Threading; using Microsoft.Zelig.TargetModel.ArmProcessor; using Cfg = Microsoft.Zelig.Configuration.Environment; using EncDef = Microsoft.Zelig.TargetModel.ArmProcessor.EncodingDefinition_ARM; public abstract class SimulatorCore : Hosting.AbstractEngine { private static EncodingDefinition_ARM s_Encoding = (EncodingDefinition_ARM)CurrentInstructionSetEncoding.GetEncoding(); private static EncodingDefinition_VFP_ARM s_EncodingVFP = (EncodingDefinition_VFP_ARM)CurrentInstructionSetEncoding.GetVFPEncoding(); public delegate bool ProcessCoprocessorRegisterTransfer( ref uint value , bool fFromCoprocessor , uint CRn , uint CRm , uint Op1 , uint Op2 ); public delegate bool ProcessCoprocessorDataTransfer( uint address , uint CRd , bool fIsLoad , bool fLong ); public delegate bool ProcessCoprocessorDataOperation( uint CRn , uint CRm , uint CRd , uint Op1 , uint Op2 ); //--// class DebugCommunicationChannelImpl : Emulation.Hosting.DebugCommunicationChannel { const uint c_ProcessorHasData = 0x1; const uint c_DebuggerHasData = 0x2; // // State // SimulatorCore m_owner; uint m_status; Queue< uint > m_fromProcessor; Queue< uint > m_fromDebugger; uint m_coproc; int m_fromDebugger_Read_Pending; bool m_fromDebugger_Read_Abort; AutoResetEvent m_dataAvailableForDebuggerToRead; AutoResetEvent m_dataAvailableForDebuggerToWrite; // // Constructor Methods // internal DebugCommunicationChannelImpl( uint coproc, SimulatorCore owner ) { m_owner = owner; m_coproc = coproc; m_fromProcessor = new Queue< uint >(); m_fromDebugger = new Queue< uint >(); m_dataAvailableForDebuggerToRead = new AutoResetEvent( false ); m_dataAvailableForDebuggerToWrite = new AutoResetEvent( false ); m_owner.RegisterService( typeof(Emulation.Hosting.DebugCommunicationChannel), this ); } // // Helper Methods // internal void Attach() { m_owner.RegisterCoprocessorRegisterTransfer( m_coproc, ProcessCoprocessor_RegisterTransfer ); } public override bool ReadFromProcessor( out uint value ) { lock(this) { if(m_fromDebugger.Count > 0) { value = m_fromDebugger.Dequeue(); m_dataAvailableForDebuggerToWrite.Set(); if(m_fromDebugger.Count == 0) { m_status &= ~c_ProcessorHasData; } return true; } value = 0; return false; } } public override bool WriteFromProcessor( uint value ) { lock(this) { m_fromProcessor.Enqueue( value ); m_status |= c_DebuggerHasData; m_dataAvailableForDebuggerToRead.Set(); return true; } } public override bool ReadFromDebugger( out uint value , int timeout ) { while(true) { lock(this) { if(m_fromProcessor.Count > 0) { value = m_fromProcessor.Dequeue(); if(m_fromProcessor.Count == 0) { m_status &= ~c_DebuggerHasData; } return true; } if(m_fromDebugger_Read_Abort) { if(m_fromDebugger_Read_Pending == 0) { m_fromDebugger_Read_Abort = false; } break; } m_fromDebugger_Read_Pending++; } bool fSignaled = m_dataAvailableForDebuggerToRead.WaitOne( timeout, false ); lock(this) { m_fromDebugger_Read_Pending--; if(m_fromDebugger_Read_Abort) { if(m_fromDebugger_Read_Pending == 0) { m_fromDebugger_Read_Abort = false; } break; } } if(fSignaled == false) { break; } } value = 0; return false; } public override bool WriteFromDebugger( uint value , int timeout ) { lock(this) { m_fromDebugger.Enqueue( value ); m_status |= c_ProcessorHasData; return true; } } public override void AbortDebuggerRead() { lock(this) { m_fromDebugger_Read_Abort = true; m_dataAvailableForDebuggerToRead.Set(); } } public override void AbortDebuggerWrite() { // // Nothing to do, debugger writes are non-blocking. // } //--// private bool ProcessCoprocessor_RegisterTransfer( ref uint value , bool fFromCoprocessor , uint CRn , uint CRm , uint Op1 , uint Op2 ) { if(fFromCoprocessor) { if(Op1 == 0 && CRn == 1 && CRm == 0 && Op2 == 0) { ReadFromProcessor( out value ); return true; } if(Op1 == 0 && CRn == 0 && CRm == 0 && Op2 == 0) { value = m_status; return true; } if(m_coproc == 15) { // TODO: Add support for this option (used by iMote) //if(Op1 == 0 && CRn == 2 && CRm == 0 && Op2 == 0) return true; } } else { if(Op1 == 0 && CRn == 1 && CRm == 0 && Op2 == 0) { WriteFromProcessor( value ); return true; } // TODO: Add support for Coproc 15 - cache (used by iMote) if(m_coproc == 15) { // 7, 5, 0, 0 // 8, 7, 0, 0 return true; } // TODO: Add support for this option (used by iMote) else if(CRn == 6) { // coproc14 - 0, 6, 0 , 0, 3 - enable turbo return true; } } return false; } } class MemoryProviderImpl : Emulation.Hosting.MemoryProvider { // // State // SimulatorCore m_owner; // // Constructor Methods // internal MemoryProviderImpl( SimulatorCore owner , Cfg.CacheControllerCategory cache ) : base( owner, cache ) { m_owner = owner; } // // Helper Methods // protected override bool CanAccessUInt8( uint address ) { return m_owner.CanAccess( address, TargetAdapterAbstractionLayer.MemoryAccessType.UINT8 ); } protected override bool CanAccessUInt16( uint address ) { return m_owner.CanAccess( address, TargetAdapterAbstractionLayer.MemoryAccessType.UINT16 ); } protected override bool CanAccessUInt32( uint address ) { return m_owner.CanAccess( address, TargetAdapterAbstractionLayer.MemoryAccessType.UINT32 ); } protected override bool CanAccessUInt64( uint address ) { if(m_owner.CanAccess( address , TargetAdapterAbstractionLayer.MemoryAccessType.UINT32 ) && m_owner.CanAccess( address + sizeof(uint), TargetAdapterAbstractionLayer.MemoryAccessType.UINT32 ) ) { return true; } return false; } //--// protected override byte ReadUInt8( uint address ) { return (byte)m_owner.Load( address, TargetAdapterAbstractionLayer.MemoryAccessType.UINT8 ); } protected override ushort ReadUInt16( uint address ) { return (ushort)m_owner.Load( address, TargetAdapterAbstractionLayer.MemoryAccessType.UINT16 ); } protected override uint ReadUInt32( uint address ) { return m_owner.Load( address, TargetAdapterAbstractionLayer.MemoryAccessType.UINT32 ); } protected override ulong ReadUInt64( uint address ) { uint resultLow = m_owner.Load( address , TargetAdapterAbstractionLayer.MemoryAccessType.UINT32 ); uint resultHigh = m_owner.Load( address + sizeof(uint), TargetAdapterAbstractionLayer.MemoryAccessType.UINT32 ); return (ulong)resultHigh << 32 | resultLow; } protected override byte[] ReadBlock( uint address , int size , uint alignment ) { byte[] res = new byte[size]; if(alignment == 4) { uint[] tmp = new uint[size / sizeof(uint)]; for(uint pos = 0; pos < tmp.Length; pos++) { tmp[pos] = m_owner.Load( address + pos * sizeof(uint), TargetAdapterAbstractionLayer.MemoryAccessType.UINT32 ); } Buffer.BlockCopy( tmp, 0, res, 0, size ); } else { for(uint pos = 0; pos < size; pos++) { res[pos] = (byte)m_owner.Load( address + pos * sizeof(byte), TargetAdapterAbstractionLayer.MemoryAccessType.UINT8 ); } } return res; } //--// protected override void WriteUInt8( uint address , byte result ) { m_owner.Store( address, result, TargetAdapterAbstractionLayer.MemoryAccessType.UINT8 ); } protected override void WriteUInt16( uint address , ushort result ) { m_owner.Store( address, result, TargetAdapterAbstractionLayer.MemoryAccessType.UINT16 ); } protected override void WriteUInt32( uint address , uint result ) { m_owner.Store( address, result, TargetAdapterAbstractionLayer.MemoryAccessType.UINT32 ); } protected override void WriteUInt64( uint address , ulong result ) { m_owner.Store( address , (uint) result , TargetAdapterAbstractionLayer.MemoryAccessType.UINT32 ); m_owner.Store( address + sizeof(uint), (uint)(result >> 32), TargetAdapterAbstractionLayer.MemoryAccessType.UINT32 ); } protected override void WriteBlock( uint address , byte[] result , uint alignment ) { int size = result.Length; if(alignment == 4) { uint[] tmp = new uint[size / sizeof(uint)]; Buffer.BlockCopy( result, 0, tmp, 0, size ); for(uint pos = 0; pos < tmp.Length; pos++) { m_owner.Store( address + pos * sizeof(uint), tmp[pos], TargetAdapterAbstractionLayer.MemoryAccessType.UINT32 ); } } else { for(uint pos = 0; pos < size; pos++) { m_owner.Store( address + pos * sizeof(byte), result[pos], TargetAdapterAbstractionLayer.MemoryAccessType.UINT8 ); } } } } //--// public struct TimingState { // // State // internal int m_recursionCount; internal ulong m_clockTicks; internal ulong m_sleepTicks; internal ulong m_busAccess_Read; internal ulong m_busAccess_Write; internal ulong m_busAccess_WaitStates; } public class TimingStateSmartHandler : IDisposable { // // State // SimulatorCore m_owner; TimingState m_backup; // // Constructor Methods // internal TimingStateSmartHandler( SimulatorCore owner ) { m_owner = owner; owner.SuspendTimingUpdates( ref m_backup ); } // // Helper Methods // public void Dispose() { m_owner.ResumeTimingUpdates( ref m_backup ); } } protected struct TrackExecution { // // State // ulong m_clockTicks; ulong m_busAccess_Read; ulong m_busAccess_Write; ulong m_busAccess_WaitStates; //--// internal void Start( Simulator st ) { m_clockTicks = st.m_clockTicks ; m_busAccess_Read = st.m_busAccess_Read ; m_busAccess_Write = st.m_busAccess_Write ; m_busAccess_WaitStates = st.m_busAccess_WaitStates; } internal void End( Simulator st ) { m_clockTicks = st.m_clockTicks - m_clockTicks ; m_busAccess_Read = st.m_busAccess_Read - m_busAccess_Read ; m_busAccess_Write = st.m_busAccess_Write - m_busAccess_Write ; m_busAccess_WaitStates = st.m_busAccess_WaitStates - m_busAccess_WaitStates; } public override string ToString() { return String.Format( "C:{0} R:{1} W:{2} WS:{3}", m_clockTicks, m_busAccess_Read, m_busAccess_Write, m_busAccess_WaitStates ); } } protected class TrackCall { // // State // internal uint m_pc; internal uint m_lr; internal uint m_sp; internal string m_name; internal TrackExecution m_te; } //--// protected enum RegisterLookup : uint { R0 = EncDef.c_register_r0 , R1 = EncDef.c_register_r1 , R2 = EncDef.c_register_r2 , R3 = EncDef.c_register_r3 , R4 = EncDef.c_register_r4 , R5 = EncDef.c_register_r5 , R6 = EncDef.c_register_r6 , R7 = EncDef.c_register_r7 , R8 = EncDef.c_register_r8 , R9 = EncDef.c_register_r9 , R10 = EncDef.c_register_r10, R11 = EncDef.c_register_r11, R12 = EncDef.c_register_r12, R13 = EncDef.c_register_r13, R14 = EncDef.c_register_r14, PC = EncDef.c_register_r15, CPSR = EncDef.c_register_cpsr, SPSR = EncDef.c_register_spsr, R13_svc , R14_svc , SPSR_svc, R13_abt , R14_abt , SPSR_abt, R13_und , R14_und , SPSR_und, R13_irq , R14_irq , SPSR_irq, R8_fiq , R9_fiq , R10_fiq , R11_fiq , R12_fiq , R13_fiq , R14_fiq , SPSR_fiq, REALMAX = SPSR + 1, TOTAL = SPSR_fiq + 1, } protected class BankedRegisters { internal uint m_mode; internal uint[] m_lookup; internal List< TrackCall > m_callQueue; // // Constructor Methods // internal BankedRegisters( uint mode ) { m_mode = mode; m_lookup = new uint[(int)RegisterLookup.REALMAX]; m_callQueue = new List< TrackCall >(); for(RegisterLookup idx = RegisterLookup.R0; idx < RegisterLookup.REALMAX; idx++) { SetLookup( idx, idx ); } switch(mode) { case EncDef.c_psr_mode_USER: return; case EncDef.c_psr_mode_FIQ: SetLookup( RegisterLookup.R8 , RegisterLookup.R8_fiq ); SetLookup( RegisterLookup.R9 , RegisterLookup.R9_fiq ); SetLookup( RegisterLookup.R10 , RegisterLookup.R10_fiq ); SetLookup( RegisterLookup.R11 , RegisterLookup.R11_fiq ); SetLookup( RegisterLookup.R12 , RegisterLookup.R12_fiq ); SetLookup( RegisterLookup.R13 , RegisterLookup.R13_fiq ); SetLookup( RegisterLookup.R14 , RegisterLookup.R14_fiq ); SetLookup( RegisterLookup.SPSR, RegisterLookup.SPSR_fiq ); break; case EncDef.c_psr_mode_IRQ: SetLookup( RegisterLookup.R13 , RegisterLookup.R13_irq ); SetLookup( RegisterLookup.R14 , RegisterLookup.R14_irq ); SetLookup( RegisterLookup.SPSR, RegisterLookup.SPSR_irq ); break; case EncDef.c_psr_mode_SVC: SetLookup( RegisterLookup.R13 , RegisterLookup.R13_svc ); SetLookup( RegisterLookup.R14 , RegisterLookup.R14_svc ); SetLookup( RegisterLookup.SPSR, RegisterLookup.SPSR_svc ); break; case EncDef.c_psr_mode_ABORT: SetLookup( RegisterLookup.R13 , RegisterLookup.R13_abt ); SetLookup( RegisterLookup.R14 , RegisterLookup.R14_abt ); SetLookup( RegisterLookup.SPSR, RegisterLookup.SPSR_abt ); break; case EncDef.c_psr_mode_UNDEF: SetLookup( RegisterLookup.R13 , RegisterLookup.R13_und ); SetLookup( RegisterLookup.R14 , RegisterLookup.R14_und ); SetLookup( RegisterLookup.SPSR, RegisterLookup.SPSR_und ); break; } } // // Helper Methods // private void SetLookup( RegisterLookup realRegister , RegisterLookup bankedRegister ) { m_lookup[(uint)realRegister] = (uint)bankedRegister; } } // // State // protected Cfg.ProductCategory m_product; protected ulong m_clockFrequency; protected int m_suspendCount; protected ulong m_clockTicks; protected ulong m_sleepTicks; protected ulong m_busAccess_Read; protected ulong m_busAccess_Write; protected ulong m_busAccess_WaitStates; protected uint m_pc; private uint[] m_registerFile = new uint[(int)RegisterLookup.TOTAL]; protected uint m_cpsr; protected uint m_interruptStatus; protected BankedRegisters m_currentBank; protected BankedRegisters m_registers_Mode_USER = new BankedRegisters( EncDef.c_psr_mode_USER ); protected BankedRegisters m_registers_Mode_FIQ = new BankedRegisters( EncDef.c_psr_mode_FIQ ); protected BankedRegisters m_registers_Mode_IRQ = new BankedRegisters( EncDef.c_psr_mode_IRQ ); protected BankedRegisters m_registers_Mode_SVC = new BankedRegisters( EncDef.c_psr_mode_SVC ); protected BankedRegisters m_registers_Mode_ABORT = new BankedRegisters( EncDef.c_psr_mode_ABORT ); protected BankedRegisters m_registers_Mode_UNDEF = new BankedRegisters( EncDef.c_psr_mode_UNDEF ); protected uint[] m_lookupConditions = new uint[EncDef.c_psr_cc_num]; private DebugCommunicationChannelImpl m_implDebugCommunicationChannel; private DebugCommunicationChannelImpl m_implDebugCommunicationChannel2; private MemoryProviderImpl m_memoryProviderImpl; private GrowOnlyHashTable< uint, ProcessCoprocessorRegisterTransfer > m_coprocessorsRegisterTransfer = HashTableFactory.New< uint, ProcessCoprocessorRegisterTransfer >(); private GrowOnlyHashTable< uint, ProcessCoprocessorDataTransfer > m_coprocessorsDataTransfer = HashTableFactory.New< uint, ProcessCoprocessorDataTransfer >(); private GrowOnlyHashTable< uint, ProcessCoprocessorDataOperation > m_coprocessorsDataOperation = HashTableFactory.New< uint, ProcessCoprocessorDataOperation >(); // // Constructor Methods // protected SimulatorCore(InstructionSet iset) : base(iset) { m_pc = 0; m_cpsr = EncDef.c_psr_I | EncDef.c_psr_F | EncDef.c_psr_mode_SVC; m_currentBank = m_registers_Mode_SVC; // // Precompute a lookup table for condition codes. // for(int value = 0; value < EncDef.c_psr_cc_num; value++) { uint res = 0; uint psr = (uint)(value << (int)EncDef.c_psr_bit_V); if(Zero(psr) != 0) res |= 1U << (int)EncDef.c_cond_EQ; if(Zero(psr) == 0) res |= 1U << (int)EncDef.c_cond_NE; if(Carry(psr) != 0) res |= 1U << (int)EncDef.c_cond_CS; if(Carry(psr) == 0) res |= 1U << (int)EncDef.c_cond_CC; if(Negative(psr) != 0) res |= 1U << (int)EncDef.c_cond_MI; if(Negative(psr) == 0) res |= 1U << (int)EncDef.c_cond_PL; if(Overflow(psr) != 0) res |= 1U << (int)EncDef.c_cond_VS; if(Overflow(psr) == 0) res |= 1U << (int)EncDef.c_cond_VC; if(Zero(psr) == 0 && Carry(psr) != 0) res |= 1U << (int)EncDef.c_cond_HI; if(Zero(psr) != 0 || Carry(psr) == 0) res |= 1U << (int)EncDef.c_cond_LS; if(Negative(psr) == Overflow(psr)) res |= 1U << (int)EncDef.c_cond_GE; if(Negative(psr) != Overflow(psr)) res |= 1U << (int)EncDef.c_cond_LT; if(Zero(psr) == 0 && Negative(psr) == Overflow(psr)) res |= 1U << (int)EncDef.c_cond_GT; if(Zero(psr) != 0 || Negative(psr) != Overflow(psr)) res |= 1U << (int)EncDef.c_cond_LE; res |= 1U << (int)EncDef.c_cond_AL; m_lookupConditions[value] = res; } m_implDebugCommunicationChannel = new DebugCommunicationChannelImpl(14, this); m_implDebugCommunicationChannel2 = new DebugCommunicationChannelImpl(15, this); m_memoryProviderImpl = new MemoryProviderImpl(this, null); } //--// // // Helper Methods // //--// public abstract bool CanAccess ( uint address, TargetAdapterAbstractionLayer.MemoryAccessType kind ); public abstract uint Load ( uint address, TargetAdapterAbstractionLayer.MemoryAccessType kind ); public abstract void Store ( uint address, uint value, TargetAdapterAbstractionLayer.MemoryAccessType kind ); public abstract uint TimeMemoryAccess ( uint address , TargetAdapterAbstractionLayer.MemoryAccessType kind ); public abstract uint GetPhysicalAddress( uint address ); //--// protected virtual void SetHardwareModel( Cfg.ProductCategory product ) { m_product = product; Cfg.ProcessorCategory proc = product.SearchValue< Cfg.ProcessorCategory >(); m_clockFrequency = proc.CoreClockFrequency; } public virtual void Reset() { StopPlugIns(); //--// ResetClockTicks(); m_pc = 0; m_cpsr = EncDef.c_psr_I | EncDef.c_psr_F | EncDef.c_psr_mode_SVC; Array.Clear( m_registerFile, 0, m_registerFile.Length ); m_coprocessorsRegisterTransfer.Clear(); m_coprocessorsDataTransfer .Clear(); m_coprocessorsDataOperation .Clear(); SetRegisterDirect( RegisterLookup.SPSR , m_cpsr ); SetRegisterDirect( RegisterLookup.SPSR_fiq, m_cpsr ); SetRegisterDirect( RegisterLookup.SPSR_irq, m_cpsr ); SetRegisterDirect( RegisterLookup.SPSR_svc, m_cpsr ); SetRegisterDirect( RegisterLookup.SPSR_abt, m_cpsr ); SetRegisterDirect( RegisterLookup.SPSR_und, m_cpsr ); m_implDebugCommunicationChannel.Attach(); m_implDebugCommunicationChannel2.Attach(); } //--// public void UpdateSleepTicks( long slept ) { if(this.AreTimingUpdatesEnabled) { m_sleepTicks += (ulong)slept; m_clockTicks += (ulong)slept; } } //--// public uint GetRegister( uint idx ) { return m_registerFile[ m_currentBank.m_lookup[ idx ] ]; } public void SetRegister( uint idx , uint value ) { m_registerFile[ m_currentBank.m_lookup[ idx ] ] = value; } //--// protected uint GetRegister( RegisterLookup idx ) { return GetRegister( (uint)idx ); } protected void SetRegister( RegisterLookup idx , uint value ) { SetRegister( (uint)idx, value ); } protected uint GetRegisterDirect( RegisterLookup reg ) { return m_registerFile[(int)reg]; } protected void SetRegisterDirect( RegisterLookup reg , uint value ) { m_registerFile[(int)reg] = value; } //--// public void SetIrqStatus( bool fActive ) { if(fActive) m_interruptStatus |= EncDef.c_psr_I; else m_interruptStatus &= ~EncDef.c_psr_I; } public void SetFiqStatus( bool fActive ) { if(fActive) m_interruptStatus |= EncDef.c_psr_F; else m_interruptStatus &= ~EncDef.c_psr_F; } public void SetResetVector( uint resetVector ) { m_pc = resetVector; } public virtual void SwitchMode( uint mode ) { m_currentBank = GetShadowRegisters( mode ); m_cpsr = mode; } //--// protected BankedRegisters GetShadowRegisters( uint mode ) { switch(mode & EncDef.c_psr_mode) { case EncDef.c_psr_mode_FIQ : return m_registers_Mode_FIQ; case EncDef.c_psr_mode_IRQ : return m_registers_Mode_IRQ; case EncDef.c_psr_mode_SVC : return m_registers_Mode_SVC; case EncDef.c_psr_mode_ABORT: return m_registers_Mode_ABORT; case EncDef.c_psr_mode_UNDEF: return m_registers_Mode_UNDEF; } return m_registers_Mode_USER; } //--// public bool CheckConditions( uint conditionField ) { return (m_lookupConditions[ (m_cpsr >> EncDef.c_psr_cc_shift) & EncDef.c_psr_cc_mask ] & (1 << (int)conditionField )) != 0; } public static uint Negative( uint psr ) { return EncDef.OPCODE_DECODE_EXTRACTFIELD( psr, EncDef.c_psr_bit_N, 1 ); } public static uint Zero ( uint psr ) { return EncDef.OPCODE_DECODE_EXTRACTFIELD( psr, EncDef.c_psr_bit_Z, 1 ); } public static uint Carry ( uint psr ) { return EncDef.OPCODE_DECODE_EXTRACTFIELD( psr, EncDef.c_psr_bit_C, 1 ); } public static uint Overflow( uint psr ) { return EncDef.OPCODE_DECODE_EXTRACTFIELD( psr, EncDef.c_psr_bit_V, 1 ); } public uint Negative() { return Negative( m_cpsr ); } public uint Zero () { return Zero ( m_cpsr ); } public uint Carry () { return Carry ( m_cpsr ); } public uint Overflow() { return Overflow( m_cpsr ); } //--// public void SaveTimingUpdates( ref TimingState state ) { state.m_clockTicks = m_clockTicks ; state.m_sleepTicks = m_sleepTicks ; state.m_busAccess_Read = m_busAccess_Read ; state.m_busAccess_Write = m_busAccess_Write ; state.m_busAccess_WaitStates = m_busAccess_WaitStates; } public void RestoreTimingUpdates( ref TimingState state ) { m_clockTicks = state.m_clockTicks ; m_sleepTicks = state.m_sleepTicks ; m_busAccess_Read = state.m_busAccess_Read ; m_busAccess_Write = state.m_busAccess_Write ; m_busAccess_WaitStates = state.m_busAccess_WaitStates; } public void SuspendTimingUpdates( ref TimingState state ) { if(state.m_recursionCount++ == 0) { SaveTimingUpdates( ref state ); } m_suspendCount++; } public void ResumeTimingUpdates( ref TimingState state ) { m_suspendCount--; if(--state.m_recursionCount == 0) { RestoreTimingUpdates( ref state ); } } protected void ResetClockTicks() { m_suspendCount = 0; m_clockTicks = 0; m_sleepTicks = 0; m_busAccess_Read = 0; m_busAccess_Write = 0; m_busAccess_WaitStates = 0; } protected void Execute( uint op ) { uint Operand2; uint shifterCarry; uint shiftType; uint dataPointer; TargetAdapterAbstractionLayer.MemoryAccessType kind; { uint pcNext = m_pc + 4; m_pc = pcNext; m_registerFile[EncDef.c_register_pc] = pcNext + 4; } if(CheckConditions( s_Encoding.get_ConditionCodes( op ) ) == false) { return; } switch(EncDef.OPCODE_DECODE_EXTRACTFIELD( op, 25, 3 )) { case 0: // 00000000[0E000000] //PARTIAL HIT MRS: //PARTIAL HIT MSR_1: //PARTIAL HIT DataProcessing_2: //PARTIAL HIT DataProcessing_3: //PARTIAL HIT Multiply: //PARTIAL HIT MultiplyLong: //PARTIAL HIT SingleDataSwap: //PARTIAL HIT BranchAndExchange: //PARTIAL HIT HalfwordDataTransfer_1: //PARTIAL HIT HalfwordDataTransfer_2: switch(EncDef.OPCODE_DECODE_EXTRACTFIELD(op,4,4)) { case 0: // 00000000[0e0000f0] //PARTIAL HIT MRS: //PARTIAL HIT MSR_1: //PARTIAL HIT DataProcessing_2: if((op & EncDef.opmask_MRS ) == EncDef.op_MRS ) goto parse_MRS; if((op & EncDef.opmask_MSR_1) == EncDef.op_MSR_1) goto parse_MSR_1; goto parse_DataProcessing_2; case 1: // 00000010[0e0000f0] //PARTIAL HIT DataProcessing_3: //PARTIAL HIT BranchAndExchange: if((op & EncDef.opmask_BranchAndExchange) == EncDef.op_BranchAndExchange) goto parse_BranchAndExchange; goto parse_DataProcessing_3; case 2: // 00000020[0e0000f0] case 4: // 00000040[0e0000f0] case 6: // 00000060[0e0000f0] case 8: // 00000080[0e0000f0] case 10: // 000000a0[0e0000f0] case 12: // 000000c0[0e0000f0] case 14: // 000000e0[0e0000f0] //HIT DataProcessing_2: goto parse_DataProcessing_2; case 3: // 00000030[0e0000f0] case 5: // 00000050[0e0000f0] //HIT DataProcessing_3: goto parse_DataProcessing_3; case 7: // 00000070[0e0000f0] //PARTIAL HIT DataProcessing_3: //PARTIAL HIT Breakpoint: if((op & EncDef.opmask_Breakpoint) == EncDef.op_Breakpoint) goto parse_Breakpoint; //HIT DataProcessing_3: goto parse_DataProcessing_3; case 9: // 00000090[0e0000f0] //PARTIAL HIT Multiply: //PARTIAL HIT MultiplyLong: //PARTIAL HIT SingleDataSwap: // +---------+---+---+---#########---+---+---+---------+---------+---------+---+---+---+---+---------+ // | Cond | 0 | 0 | 0 # 0 | 0 # 0 | A | S | Rd | Rn | Rs | 1 | 0 | 0 | 1 | Rm | Multiply // +---------+---+---+---#---+---#---+---+---+---------+---------+---------+---+---+---+---+---------+ // | Cond | 0 | 0 | 0 # 0 | 1 # U | A | S | RdHi | RdLo | Rn | 1 | 0 | 0 | 1 | Rm | Multiply Long // +---------+---+---+---#---+---#---+---+---+---------+---------+---------+---+---+---+---+---------+ // | Cond | 0 | 0 | 0 # 1 | 0 # B | 0 | 0 | Rn | Rd | 0 0 0 0 | 1 | 0 | 0 | 1 | Rm | Single Data Swap // +---------+---+---+---#########---+---+---+---------+---------+---------+---+---+---+---+---------+ switch(EncDef.OPCODE_DECODE_EXTRACTFIELD( op, 23, 2 )) { case 0: // 00000090[0f8000f0] //HIT Multiply: goto parse_Multiply; case 1: // 00800090[0f8000f0] //HIT MultiplyLong: goto parse_MultiplyLong; case 2: // 01000090[0f8000f0] //HIT SingleDataSwap: goto parse_SingleDataSwap; case 3: // 01800090[0f8000f0] //UNDEFINED break; } break; case 11: // 000000b0[0e0000f0] case 13: // 000000d0[0e0000f0] case 15: // 000000f0[0e0000f0] //PARTIAL HIT HalfwordDataTransfer_1: //PARTIAL HIT HalfwordDataTransfer_2: { // +---------+---+---+---+---+---#####---+---+---------+---------+---------+---+---+---+---+---------+ // | Cond | 0 | 0 | 0 | P | U # 0 # W | L | Rn | Rd | 0 0 0 0 | 1 | S | H | 1 | Rm | Halfword Data Transfer: register offset // +---------+---+---+---+---+---#####---+---+---------+---------+---------+---+---+---+---+---------+ // | Cond | 0 | 0 | 0 | P | U # 1 # W | L | Rn | Rd | Offset | 1 | S | H | 1 | Offset | Halfword Data Transfer: immediate offset // +---------+---+---+---+---+---#####---+---+---------+---------+---------+---+---+---+---+---------+ if(EncDef.OPCODE_DECODE_CHECKFLAG( op, 22 )) { Operand2 = s_Encoding.get_HalfWordDataTransfer_Offset( op ); } else { Operand2 = GetRegister( s_Encoding.get_Register4( op ) ); } goto parse_HalfwordDataTransfer; } } break; case 1: // 02000000[0E000000] //PARTIAL HIT MSR_2: //PARTIAL HIT DataProcessing_1: if((op & EncDef.opmask_MSR_2) == EncDef.op_MSR_2) goto parse_MSR_2; goto parse_DataProcessing_1; case 2: // 04000000[0E000000] //HIT SingleDataTransfer_1: goto parse_SingleDataTransfer_1; case 3: // 06000000[0E000000] //PARTIAL HIT SingleDataTransfer_2: //PARTIAL HIT SingleDataTransfer_3: //PARTIAL HIT Undefined: if((op & EncDef.opmask_SingleDataTransfer_2) == EncDef.op_SingleDataTransfer_2) goto parse_SingleDataTransfer_2; if((op & EncDef.opmask_SingleDataTransfer_3) == EncDef.op_SingleDataTransfer_3) goto parse_SingleDataTransfer_3; if((op & EncDef.opmask_Undefined ) == EncDef.op_Undefined ) goto parse_Undefined; break; case 4: // 08000000[0E000000] //HIT BlockDataTransfer: goto parse_BlockDataTransfer; case 5: // 0A000000[0E000000] //HIT Branch: goto parse_Branch; case 6: // 0C000000[0E000000] //HIT CoprocDataTransfer: goto parse_CoprocDataTransfer; case 7: // 0E000000[0E000000] //PARTIAL HIT CoprocDataOperation: //PARTIAL HIT CoprocRegisterTransfer: //PARTIAL HIT SoftwareInterrupt: if((op & EncDef.opmask_CoprocDataOperation ) == EncDef.op_CoprocDataOperation ) goto parse_CoprocDataOperation; if((op & EncDef.opmask_CoprocRegisterTransfer) == EncDef.op_CoprocRegisterTransfer) goto parse_CoprocRegisterTransfer; if((op & EncDef.opmask_SoftwareInterrupt ) == EncDef.op_SoftwareInterrupt ) goto parse_SoftwareInterrupt; break; } throw new NotSupportedException(); //--// parse_MRS: { uint res; if(s_Encoding.get_StatusRegister_IsSPSR( op )) { res = GetRegister( RegisterLookup.SPSR ); } else { res = m_cpsr; } SetRegister( s_Encoding.get_Register2( op ), res ); return; } parse_MSR_1: { Operand2 = GetRegister( s_Encoding.get_Register4( op ) ); goto parse_MSR; } parse_MSR_2: { Operand2 = s_Encoding.get_DataProcessing_ImmediateValue( op ); goto parse_MSR; } parse_MSR: { uint fields = s_Encoding.get_StatusRegister_Fields( op ); if(s_Encoding.get_StatusRegister_IsSPSR( op )) { uint psr = GetRegister( RegisterLookup.SPSR ); psr = Execute_MSR( psr, Operand2, fields ); SetRegister( RegisterLookup.SPSR, psr ); } else { if((m_cpsr & EncDef.c_psr_mode) == EncDef.c_psr_mode_USER) { // // Things not allowed in user mode. // if((fields & (EncDef.c_psr_field_c | EncDef.c_psr_field_x | EncDef.c_psr_field_s)) != 0) { throw new NotSupportedException(); } } uint cpsr = Execute_MSR( m_cpsr, Operand2, fields ); ProcessInterruptDisabling( m_cpsr, cpsr ); SwitchMode( cpsr ); } return; } //--// parse_DataProcessing_1: { Operand2 = s_Encoding.get_DataProcessing_ImmediateValue ( op ); shifterCarry = s_Encoding.get_DataProcessing_ImmediateRotation( op ) != 0 ? (Operand2 >> 31) : this.Carry(); goto parse_DataProcessing; } parse_DataProcessing_2: { shiftType = s_Encoding.get_Shift_Type ( op ); Operand2 = s_Encoding.get_Shift_Immediate( op ); if(Operand2 == 0) { switch(shiftType) { case EncDef.c_shift_LSR: case EncDef.c_shift_ASR: Operand2 = 32; break; case EncDef.c_shift_ROR: Operand2 = 1; shiftType = EncDef.c_shift_RRX; break; } } goto parse_DataProcessing_2and3; } parse_DataProcessing_3: { shiftType = s_Encoding.get_Shift_Type ( op ); Operand2 = GetRegister( s_Encoding.get_Shift_Register( op ) ); // // Extra internal cycle. // m_clockTicks++; goto parse_DataProcessing_2and3; } parse_DataProcessing_2and3: { uint shift = Operand2; Operand2 = GetRegister( s_Encoding.get_Register4( op ) ); shifterCarry = this.Carry(); if(shift != 0) { switch(shiftType) { case EncDef.c_shift_LSL: if(shift < 32) { shifterCarry = (Operand2 >> (int)(32 - shift)) & 1; Operand2 = (Operand2 << (int) shift ) ; } else if(shift == 32) { shifterCarry = Operand2 & 1; Operand2 = 0; } else { shifterCarry = 0; Operand2 = 0; } break; case EncDef.c_shift_LSR: if(shift < 32) { shifterCarry = (Operand2 >> (int)(shift - 1)) & 1; Operand2 = (Operand2 >> (int) shift ) ; } else if(shift == 32) { shifterCarry = (Operand2 >> 31) & 1; Operand2 = 0; } else { shifterCarry = 0; Operand2 = 0; } break; case EncDef.c_shift_ASR: if(shift < 32) { shifterCarry = ( Operand2 >> (int)(shift - 1)) & 1; Operand2 = (uint)(((int)Operand2) >> (int) shift ) ; } else { shifterCarry = (Operand2 >> 31) & 1; Operand2 = shifterCarry != 0 ? 0xFFFFFFFF : 0x0; } break; case EncDef.c_shift_ROR: shift %= 32; shifterCarry = (Operand2 >> (int)(shift - 1)) & 1; Operand2 = (Operand2 >> (int) shift ) | (Operand2 << (int)(32 - shift)); break; case EncDef.c_shift_RRX: shifterCarry = (Operand2 & 1); Operand2 = (this.Carry() != 0 ? 0x80000000 : 0) | (Operand2 >> 1); break; } } goto parse_DataProcessing; } parse_DataProcessing: { uint Operand1 = GetRegister( s_Encoding.get_Register1( op ) ); uint dst = s_Encoding.get_Register2( op ); uint overflow = this.Overflow(); uint carry = this.Carry (); uint res; switch(s_Encoding.get_DataProcessing_Operation( op )) { case EncDef.c_operation_TST: dst = 16; goto case EncDef.c_operation_AND; case EncDef.c_operation_AND: res = Operand1 & Operand2; carry = shifterCarry; break; case EncDef.c_operation_TEQ: dst = 16; goto case EncDef.c_operation_EOR; case EncDef.c_operation_EOR: res = Operand1 ^ Operand2; carry = shifterCarry; break; case EncDef.c_operation_CMP: dst = 16; goto case EncDef.c_operation_SUB; case EncDef.c_operation_SUB: carry = 1; goto case EncDef.c_operation_SBC; case EncDef.c_operation_SBC: { ulong res64 = (ulong)Operand1 - (ulong)Operand2; if(carry == 0) res64--; carry = (uint)(res64 >> 32) ^ 1; res = (uint) res64; overflow = ((Operand1 ^ Operand2) & (Operand1 ^ res)) >> 31; } break; case EncDef.c_operation_RSB: carry = 1; goto case EncDef.c_operation_RSC; case EncDef.c_operation_RSC: { ulong res64 = (ulong)Operand2 - (ulong)Operand1; if(carry == 0) res64--; carry = (uint)(res64 >> 32) ^ 1; res = (uint) res64; overflow = ((Operand1 ^ Operand2) & (Operand2 ^ res)) >> 31; } break; case EncDef.c_operation_CMN: dst = 16; goto case EncDef.c_operation_ADD; case EncDef.c_operation_ADD: carry = 0; goto case EncDef.c_operation_ADC; case EncDef.c_operation_ADC: { ulong res64 = (ulong)Operand2 + (ulong)Operand1; if(carry != 0) res64++; carry = (uint)(res64 >> 32); res = (uint) res64; overflow = (~(Operand1 ^ Operand2) & (Operand1 ^ res)) >> 31; } break; case EncDef.c_operation_ORR: res = Operand1 | Operand2; carry = shifterCarry; break; case EncDef.c_operation_BIC: res = Operand1 & ~Operand2; carry = shifterCarry; break; case EncDef.c_operation_MOV: res = Operand2; carry = shifterCarry; break; case EncDef.c_operation_MVN: res = ~Operand2; carry = shifterCarry; break; default: throw new NotSupportedException(); } switch(dst) { case 16: break; case EncDef.c_register_pc: SimulatePipelineMiss(); m_pc = res; break; default: SetRegister( dst, res ); break; } if(s_Encoding.get_ShouldSetConditions( op )) { if(dst == EncDef.c_register_pc) { SwitchMode( GetRegister( RegisterLookup.SPSR ) ); } else { uint psr = m_cpsr & ~(EncDef.c_psr_V | EncDef.c_psr_C | EncDef.c_psr_Z | EncDef.c_psr_N); if((int) res < 0) psr |= EncDef.c_psr_N; if( res == 0) psr |= EncDef.c_psr_Z; if((carry & 1) != 0) psr |= EncDef.c_psr_C; if((overflow & 1) != 0) psr |= EncDef.c_psr_V; m_cpsr = psr; } } return; } //--// parse_Multiply: { uint Op1 = GetRegister( s_Encoding.get_Register3( op ) ); uint Op2 = GetRegister( s_Encoding.get_Register4( op ) ); uint res; { uint mCycles; if ((Op1 & 0xFFFFFF00) == 0) mCycles = 1; else if((Op1 & 0xFFFF0000) == 0) mCycles = 2; else if((Op1 & 0xFF000000) == 0) mCycles = 3; else mCycles = 4; m_clockTicks += mCycles; } res = Op1 * Op2; if(s_Encoding.get_Multiply_IsAccumulate( op )) { res += GetRegister( s_Encoding.get_Register2( op ) ); // // Extra internal cycle. // m_clockTicks++; } SetRegister( s_Encoding.get_Register1( op ), res ); if(s_Encoding.get_ShouldSetConditions( op )) { uint psr = m_cpsr & ~(EncDef.c_psr_Z | EncDef.c_psr_N); if((int)res < 0) psr |= EncDef.c_psr_N; if( res == 0) psr |= EncDef.c_psr_Z; m_cpsr = psr; } return; } parse_MultiplyLong: { uint Op1 = GetRegister( s_Encoding.get_Register3( op ) ); uint Op2 = GetRegister( s_Encoding.get_Register4( op ) ); ulong res; { uint mCycles; if ((Op1 & 0xFFFFFF00) == 0) mCycles = 2; else if((Op1 & 0xFFFF0000) == 0) mCycles = 3; else if((Op1 & 0xFF000000) == 0) mCycles = 4; else mCycles = 5; m_clockTicks += mCycles; } if(s_Encoding.get_Multiply_IsSigned( op )) { res = (ulong)((long)(int)Op1 * (long)(int)Op2); } else { res = (ulong)Op1 * (ulong)Op2; } res = Execute_AccumulateAndStore( res, s_Encoding.get_Register1( op ), s_Encoding.get_Register2( op ), s_Encoding.get_Multiply_IsAccumulate( op ) ); if(s_Encoding.get_ShouldSetConditions( op )) { uint psr = m_cpsr & ~(EncDef.c_psr_Z | EncDef.c_psr_N); if((long)res < 0) psr |= EncDef.c_psr_N; if( res == 0) psr |= EncDef.c_psr_Z; m_cpsr = psr; } return; } //--// parse_BranchAndExchange: { uint reg = s_Encoding.get_Register4( op ); uint lr = GetRegister( reg ); SimulatePipelineMiss(); m_pc = lr; return; } parse_Branch: { uint pc = GetRegister( EncDef.c_register_pc ); if(s_Encoding.get_Branch_IsLink( op )) { SetRegister( EncDef.c_register_lr, pc - 4 ); // R15 contains PC+8, LR has to point to PC+4; } pc = (uint)((int)pc + s_Encoding.get_Branch_Offset( op )); SimulatePipelineMiss(); m_pc = pc; return; } //--// parse_SingleDataSwap: { // Not supported for now. throw new NotSupportedException(); } parse_SingleDataTransfer_1: { Operand2 = s_Encoding.get_DataTransfer_Offset( op ); goto parse_SingleDataTransfer; } parse_SingleDataTransfer_2: { shiftType = s_Encoding.get_Shift_Type ( op ); Operand2 = s_Encoding.get_Shift_Immediate( op ); if(Operand2 == 0) { switch(shiftType) { case EncDef.c_shift_LSR: case EncDef.c_shift_ASR: Operand2 = 32; break; case EncDef.c_shift_ROR: Operand2 = 1; shiftType = EncDef.c_shift_RRX; break; } } goto parse_SingleDataTransfer_2and3; } parse_SingleDataTransfer_3: { shiftType = s_Encoding.get_Shift_Type ( op ); Operand2 = GetRegister( s_Encoding.get_Shift_Register( op ) ); goto parse_SingleDataTransfer_2and3; } parse_SingleDataTransfer_2and3: { uint shift = Operand2; Operand2 = GetRegister( s_Encoding.get_Register4( op ) ); if(shift != 0) { switch(shiftType) { case EncDef.c_shift_LSL: Operand2 = ( Operand2 << (int)shift ) ; break; case EncDef.c_shift_LSR: Operand2 = ( Operand2 >> (int)shift ) ; break; case EncDef.c_shift_ASR: Operand2 = (uint)(((int)Operand2) >> (int)shift ) ; break; case EncDef.c_shift_ROR: Operand2 = ( Operand2 >> (int)shift ) | (Operand2 << (int)(32 - shift)); break; } } goto parse_SingleDataTransfer; } parse_SingleDataTransfer: { dataPointer = s_Encoding.get_Register2 ( op ); kind = s_Encoding.get_DataTransfer_IsByteTransfer( op ) ? TargetAdapterAbstractionLayer.MemoryAccessType.UINT8 : TargetAdapterAbstractionLayer.MemoryAccessType.UINT32; goto parse_DataTransfer; } parse_BlockDataTransfer: { uint address = GetRegister( s_Encoding.get_Register1( op ) ); uint addressNext; uint Rd = 0; uint Num = 0; uint Lst; Lst = s_Encoding.get_BlockDataTransfer_RegisterList( op ); while(Lst != 0) { if((Lst & 1) != 0) Num++; Lst >>= 1; } bool load = s_Encoding.get_DataTransfer_IsLoad ( op ); bool preIndex = s_Encoding.get_DataTransfer_IsPreIndexing( op ); bool up = s_Encoding.get_DataTransfer_IsUp ( op ); if(up) { addressNext = address; if(preIndex) addressNext += 4; } else { addressNext = address - Num * 4; if(!preIndex) addressNext += 4; } if(load) { // // Extra internal cycle. // m_clockTicks++; } Lst = s_Encoding.get_BlockDataTransfer_RegisterList( op ); while(Lst != 0) { if((Lst & 1) != 0) { if(load) { SetRegister( Rd, Load( addressNext, TargetAdapterAbstractionLayer.MemoryAccessType.UINT32 ) ); if(Rd == EncDef.c_register_pc) { SimulatePipelineMiss(); m_pc = GetRegister( EncDef.c_register_pc ); } } else { Store( addressNext, GetRegister( Rd ), TargetAdapterAbstractionLayer.MemoryAccessType.UINT32 ); } addressNext += 4; } Rd++; Lst >>= 1; } if(s_Encoding.get_DataTransfer_ShouldWriteBack( op )) { if(up) address += 4 * Num; else address -= 4 * Num; SetRegister( s_Encoding.get_Register1( op ), address ); } if(s_Encoding.get_BlockDataTransfer_LoadPSR( op )) { SwitchMode( GetRegister( RegisterLookup.SPSR ) ); } return; } parse_HalfwordDataTransfer: { switch(s_Encoding.get_HalfWordDataTransfer_Kind( op )) { case EncDef.c_halfwordkind_U2: kind = TargetAdapterAbstractionLayer.MemoryAccessType.UINT16; break; case EncDef.c_halfwordkind_I1: kind = TargetAdapterAbstractionLayer.MemoryAccessType.SINT8 ; break; case EncDef.c_halfwordkind_I2: kind = TargetAdapterAbstractionLayer.MemoryAccessType.SINT16; break; default: throw new NotSupportedException(); } dataPointer = s_Encoding.get_Register2( op ); goto parse_DataTransfer; } parse_DataTransfer: { uint address = GetRegister( s_Encoding.get_Register1( op ) ); uint addressPost; bool load = s_Encoding.get_DataTransfer_IsLoad ( op ); bool preIndex = s_Encoding.get_DataTransfer_IsPreIndexing( op ); bool up = s_Encoding.get_DataTransfer_IsUp ( op ); if(up) addressPost = address + Operand2; else addressPost = address - Operand2; if(preIndex) address = addressPost; if(load) { SetRegister( dataPointer, Load( address, kind ) ); // // Extra internal cycle. // m_clockTicks++; if(dataPointer == EncDef.c_register_pc) { SimulatePipelineMiss(); m_pc = GetRegister( dataPointer ); } } else { Store( address, GetRegister( dataPointer ), kind ); } if(s_Encoding.get_DataTransfer_ShouldWriteBack( op ) || preIndex == false) { SetRegister( s_Encoding.get_Register1( op ), addressPost ); } return; } parse_CoprocRegisterTransfer: { uint CpNum = s_Encoding.get_Coproc_CpNum ( op ); uint Op1 = s_Encoding.get_CoprocRegisterTransfer_Op1 ( op ); uint Rd = s_Encoding.get_CoprocRegisterTransfer_Rd ( op ); uint CRn = s_Encoding.get_CoprocRegisterTransfer_CRn ( op ); uint CRm = s_Encoding.get_CoprocRegisterTransfer_CRm ( op ); uint Op2 = s_Encoding.get_CoprocRegisterTransfer_Op2 ( op ); bool fFromCoproc = s_Encoding.get_CoprocRegisterTransfer_IsMRC( op ); ProcessCoprocessorRegisterTransfer dlg; if(m_coprocessorsRegisterTransfer.TryGetValue( CpNum, out dlg )) { uint value; if(fFromCoproc) { value = 0; } else { value = GetRegister( Rd ); } if(dlg( ref value, fFromCoproc, CRn, CRm, Op1, Op2 )) { if(fFromCoproc) { SetRegister( Rd, value ); } return; } } if(ProcessUnsupportedOperation( op )) { return; } throw new NotImplementedException(); } parse_CoprocDataTransfer: { uint CpNum = s_Encoding.get_Coproc_CpNum( op ); ProcessCoprocessorDataTransfer dlg; if(m_coprocessorsDataTransfer.TryGetValue( CpNum, out dlg )) { uint address = GetRegister( s_Encoding.get_CoprocDataTransfer_Rn( op ) ); uint offset = s_Encoding.get_CoprocDataTransfer_Offset( op ) * 4; uint addressPost; uint CRd = s_Encoding.get_CoprocDataTransfer_CRd ( op ); bool load = s_Encoding.get_CoprocDataTransfer_IsLoad ( op ); bool preIndex = s_Encoding.get_CoprocDataTransfer_IsPreIndexing( op ); bool up = s_Encoding.get_CoprocDataTransfer_IsUp ( op ); bool wide = s_Encoding.get_CoprocDataTransfer_IsWide ( op ); if(up) addressPost = address + offset; else addressPost = address - offset; if(preIndex) address = addressPost; if(dlg( address, CRd, load, wide )) { return; } if(s_Encoding.get_CoprocDataTransfer_ShouldWriteBack( op ) || preIndex == false) { SetRegister( s_Encoding.get_CoprocDataTransfer_Rn( op ), addressPost ); } return; } if(ProcessUnsupportedOperation( op )) { return; } throw new NotImplementedException(); } parse_CoprocDataOperation: { uint CpNum = s_Encoding.get_Coproc_CpNum( op ); ProcessCoprocessorDataOperation dlg; if(m_coprocessorsDataOperation.TryGetValue( CpNum, out dlg )) { uint Op1 = s_Encoding.get_CoprocDataOperation_Op1( op ); uint CRd = s_Encoding.get_CoprocDataOperation_CRd( op ); uint CRn = s_Encoding.get_CoprocDataOperation_CRn( op ); uint CRm = s_Encoding.get_CoprocDataOperation_CRm( op ); uint Op2 = s_Encoding.get_CoprocDataOperation_Op2( op ); if(dlg( CRn, CRm, CRd, Op1, Op2 )) { return; } } if(ProcessUnsupportedOperation( op )) { return; } throw new NotImplementedException(); } parse_SoftwareInterrupt: { uint cpsrPost = m_cpsr & ~EncDef.c_psr_mode; cpsrPost |= EncDef.c_psr_mode_SVC; cpsrPost |= EncDef.c_psr_I; SwitchMode( cpsrPost ); SetRegister( EncDef.c_register_lr, m_pc ); m_pc = 0x00000008; return; } parse_Breakpoint: { if(ProcessUnsupportedOperation( op )) { return; } throw new NotImplementedException(); } parse_Undefined: { if(ProcessUnsupportedOperation( op )) { return; } throw new NotImplementedException(); } } protected abstract void ProcessInterruptDisabling( uint cpsrPre , uint cpsrPost ); protected abstract bool ProcessUnsupportedOperation( uint op ); //--// public TimeSpan ClockTicksToTime( long clockTicks ) { double val = clockTicks; return new TimeSpan( (long)(val * TimeSpan.TicksPerSecond / m_clockFrequency) ); } public long TimeToClockTicks( TimeSpan time ) { double val = (double)time.Ticks; return (long)(val * m_clockFrequency / TimeSpan.TicksPerSecond); } //--// public void RegisterCoprocessorRegisterTransfer( uint cpNum , ProcessCoprocessorRegisterTransfer dlg ) { m_coprocessorsRegisterTransfer[cpNum] = dlg; } public void RegisterCoprocessorDataTransfer( uint cpNum , ProcessCoprocessorDataTransfer dlg ) { m_coprocessorsDataTransfer[cpNum] = dlg; } public void RegisterCoprocessorDataOperation( uint cpNum , ProcessCoprocessorDataOperation dlg ) { m_coprocessorsDataOperation[cpNum] = dlg; } //--// private uint Execute_MSR( uint psr , uint operand , uint fields ) { uint mask = 0; if((fields & EncDef.c_psr_field_c) != 0) mask |= 0x000000FF; if((fields & EncDef.c_psr_field_x) != 0) mask |= 0x0000FF00; if((fields & EncDef.c_psr_field_s) != 0) mask |= 0x00FF0000; if((fields & EncDef.c_psr_field_f) != 0) mask |= 0xFF000000; operand = (psr & ~mask) | (operand & mask); return operand; } private ulong Execute_AccumulateAndStore( ulong res , uint RdHiIdx , uint RdLoIdx , bool accumulate ) { if(accumulate) { res += (ulong)GetRegister( RdHiIdx ) << 32 | (ulong)GetRegister( RdLoIdx ); // // Extra internal cycle. // m_clockTicks++; } SetRegister( RdHiIdx, (uint)(res >> 32) ); SetRegister( RdLoIdx, (uint) res ); return res; } private void SimulatePipelineMiss() { uint wasteCycle; wasteCycle = Load( m_pc , TargetAdapterAbstractionLayer.MemoryAccessType.FETCH ); wasteCycle = Load( m_pc+4, TargetAdapterAbstractionLayer.MemoryAccessType.FETCH ); } // // Access Methods // public bool AreTimingUpdatesEnabled { get { return m_suspendCount == 0; } } public Cfg.ProductCategory Product { get { return m_product; } } public ulong ClockFrequency { get { return m_clockFrequency; } } public ulong ClockTicks { get { return m_clockTicks; } } public ulong SleepTicks { get { return m_sleepTicks; } } } } ================================================ FILE: Zelig/Zelig/DebugTime/ArmProcessorEmulation/SymDef.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // namespace Microsoft.Zelig.Emulation.ArmProcessor { using System; using System.Collections.Generic; using System.IO; using System.Text; using System.Text.RegularExpressions; public static class SymDef { public class SymbolToAddressMap : Dictionary< string, uint > { } public class AddressToSymbolMap : Dictionary< uint, string > { class AddressComparer : IComparer< KeyValuePair< uint, string > > { public int Compare( KeyValuePair< uint, string > x , KeyValuePair< uint, string > y ) { return x.Key.CompareTo( y.Key ); } } // // State // AddressComparer m_comparer; KeyValuePair< uint, string >[] m_sorted; //--/// public bool FindClosestAddress( uint address , out uint context ) { if(m_comparer == null) { m_comparer = new AddressComparer(); } if(m_sorted == null) { m_sorted = new KeyValuePair[this.Count]; int pos = 0; foreach(KeyValuePair< uint, string> kvp in this) { m_sorted[pos++] = kvp; } Array.Sort( m_sorted, m_comparer ); } if(m_sorted.Length > 0) { int i = Array.BinarySearch( m_sorted, new KeyValuePair< uint, string >( address, null ), m_comparer ); if(i >= 0) { context = address; return true; } i = ~i - 1; if(i >= 0 && i < m_sorted.Length) { context = m_sorted[i].Key; return true; } } context = 0; return false; } } //--// public static void Parse( string file , SymDef.SymbolToAddressMap symdef , SymDef.AddressToSymbolMap symdef_Inverse ) { if(System.IO.File.Exists( file ) == false) { throw new System.IO.FileNotFoundException( String.Format( "Cannot find {0}", file ) ); } using(System.IO.StreamReader reader = new StreamReader( file )) { Regex reMatch1 = new Regex( "^0x([0-9a-fA-F]*) ([A-D]) (.*)" ); Regex reMatch2 = new Regex( "^ 0x([0-9a-fA-F]*): ([0-9a-fA-F]*) " ); Regex reMatch3 = new Regex( "^ ([^ ]+)$" ); string lastName = null; string line; while((line = reader.ReadLine()) != null) { if(reMatch1.IsMatch( line )) { GroupCollection group = reMatch1.Match( line ).Groups; uint address = UInt32.Parse( group[1].Value, System.Globalization.NumberStyles.HexNumber ); string symbol = group[3].Value; symdef [symbol ] = address; symdef_Inverse[address] = symbol; } else if(reMatch2.IsMatch( line )) { GroupCollection group = reMatch2.Match( line ).Groups; if(lastName != null) { uint address = UInt32.Parse( group[1].Value, System.Globalization.NumberStyles.HexNumber ); symdef [lastName] = address; symdef_Inverse[address ] = lastName; lastName = null; } } else if(reMatch3.IsMatch( line )) { GroupCollection group = reMatch3.Match( line ).Groups; string name = group[1].Value; switch(name) { case ".text": case "$a": case "$d": case "$p": break; default: if(name.StartsWith( "i." )) { name = name.Substring( 2 ); } lastName = name; break; } } } } } //--// private static bool Unmangle_ClassName( string symbol , ref int index , StringBuilder name ) { if(symbol[index] == 'Q' && char.IsDigit( symbol, index+1 )) { int times = symbol[index+1] - '0'; index += 2; while(times-- > 0) { if(Unmangle_ClassName( symbol, ref index, name ) == false) return false; if(times > 0) { name.Append( "::" ); } } } else if(char.IsDigit( symbol, index )) { int len = 0; while(index < symbol.Length && char.IsDigit( symbol, index )) { len = len * 10 + symbol[index] - '0'; index++; } if(len == 0 || len + index > symbol.Length) return false; name.Append( symbol, index, len ); index += len; } return true; } private static bool Unmangle_Parameter( string symbol , ref int index , List parameters ) { int len = parameters.Count; switch(symbol[index++]) { case 'i': parameters.Add( "int" ); return true; case 's': parameters.Add( "short" ); return true; case 'l': parameters.Add( "long" ); return true; case 'x': parameters.Add( "long long" ); return true; case 'c': parameters.Add( "char" ); return true; case 'b': parameters.Add( "bool" ); return true; case 'f': parameters.Add( "float" ); return true; case 'd': parameters.Add( "double" ); return true; case 'v': parameters.Add( "void" ); return true; case 'e': parameters.Add( "..." ); return true; //--// case 'N': // N = Repeat parameter times. if(char.IsDigit( symbol, index )) { int num = symbol[index++] - '0'; if(char.IsDigit( symbol, index )) { int pos = symbol[index++] - '0' - 1; if(pos < len) { while(num-- > 0) { parameters.Add( parameters[pos] ); } return true; } } } break; case 'T': // T = Repeat parameter if(char.IsDigit( symbol, index )) { int pos = symbol[index++] - '0' - 1; if(pos < len) { parameters.Add( parameters[pos] ); return true; } } break; case 'P': // P = pointer if(Unmangle_Parameter( symbol, ref index, parameters )) { parameters[len] += "*"; return true; } break; case 'R': // R = reference if(Unmangle_Parameter( symbol, ref index, parameters )) { parameters[len] += "&"; return true; } break; case 'C': // C = const // // CP => * const // PC => const * // if(Unmangle_Parameter( symbol, ref index, parameters )) { parameters[len] = "const " + parameters[len]; return true; } break; case 'U': // U = unsigned if(Unmangle_Parameter( symbol, ref index, parameters )) { parameters[len] = "unsigned " + parameters[len]; return true; } break; case 'Q': case '1': case '2': case '3': case '4': case '5': case '6': case '7': case '8': case '9': { StringBuilder sb = new StringBuilder(); index--; if(Unmangle_ClassName( symbol, ref index, sb )) { parameters.Add( sb.ToString() ); return true; } } break; } return false; } private static void Unmangle_SkipPrefix( string symbol , ref int index , ref string dst , string prefix , string substitute ) { if(index + prefix.Length <= symbol.Length) { if(symbol.Substring( index, prefix.Length ) == prefix) { index += prefix.Length; dst += substitute; } } } public static void Unmangle( string name , out string strClass , out string strFunction , out string strModifier ) { int index = 0; StringBuilder functionName = new StringBuilder(); StringBuilder className = new StringBuilder(); strClass = string.Empty; strFunction = string.Empty; strModifier = string.Empty; Unmangle_SkipPrefix( name, ref index, ref strModifier, "$Ven$AA$L$$", "veneer " ); Unmangle_SkipPrefix( name, ref index, ref strModifier, "i." , "inline " ); name = name.Substring( index ); index = 0; if(name.Contains( "::" )) { strClass = "C# function"; strFunction = name; return; } if(name.Contains( "Jitter#" )) { strClass = "Jitter"; strFunction = name.Substring( "Jitter#".Length ); return; } while(index < name.Length) { if(name[index] == '_' && index + 1 < name.Length && name[index+1] == '_') { int index2 = index + 2; className.Length = 0; if(Unmangle_ClassName( name, ref index2, className )) { //// bool fStatic = false; bool fConst = false; while(index2 < name.Length) { if(name[index2] == 'S') { index2++; //// fStatic = true; continue; } if(name[index2] == 'C') { index2++; fConst = true; continue; } break; } if(index2 < name.Length && name[index2++] == 'F') { List parameters = new List(); bool fOk = true; while(fOk && index2 < name.Length) { fOk = Unmangle_Parameter( name, ref index2, parameters ); } if(fOk) { if(className.Length > 0) { strClass = className.ToString(); } else { strClass = "C++ function"; } functionName.Append( "( " ); for(int i = 0; i < parameters.Count; i++) { if(i != 0) functionName.Append( ", " ); functionName.Append( parameters[i] ); } functionName.Append( " )" ); if(fConst ) functionName.Append( " const" ); //// if(fStatic) functionName.Append( " static" ); strFunction = functionName.ToString(); return; } } } } functionName.Append( name[index++] ); } strClass = "C function"; strFunction = functionName.ToString(); } } } ================================================ FILE: Zelig/Zelig/DebugTime/Debugger/Debugger.csproj ================================================  Debug AnyCPU 9.0.30729 2.0 {186F31A3-EF89-4A25-B2D5-20070430AA01} WinExe Properties Microsoft.Zelig.Debugger.ArmProcessor Microsoft.Zelig.Debugger.ArmProcessor $(LlilumBuildRoot)\Host\obj\$(MSBuildProjectName)\ v4.5 true full false $(LlilumBuildRoot)\Host\bin\$(Configuration)\ DEBUG;TRACE prompt 4 true true AllRules.ruleset AnyCPU false pdbonly true $(LlilumBuildRoot)\Host\bin\$(Configuration)\ TRACE prompt 4 true true AllRules.ruleset AnyCPU false $(LlilumBuildRoot)\Host\bin\$(Configuration)\ AnyCPU DEBUG;TRACE true true false False ..\..\External\Binaries\CSharpParser\Debug\CSharpParser.dll 3.5 False ..\..\External\Binaries\JTAG\Debug\TargetAdapterAbstractionLayer.dll Form EnvironmentForm.cs Form InputForm.cs Form ProfilerMainForm.cs Form SessionManager.cs UserControl BreakpointsView.cs UserControl CodeView.cs CodeView.cs UserControl Form DebuggerMainForm.cs Form DebuggerMainForm.cs DebuggerMainForm.cs Form Form DisplayForm.cs UserControl LocalsView.cs Form OutputForm.cs Designer EnvironmentForm.cs InputForm.cs Designer ProfilerMainForm.cs Designer Designer SessionManager.cs Designer BreakpointsView.cs Designer CodeView.cs Designer DebuggerMainForm.cs Designer DisplayForm.cs Designer LocalsView.cs Designer OutputForm.cs ResXFileCodeGenerator Resources.Designer.cs Designer Designer MemoryView.cs Designer RegistersView.cs Designer StackTraceView.cs ThreadsView.cs Designer TreeBasedGridView.cs Designer True Resources.resx True SettingsSingleFileGenerator Settings.Designer.cs True Settings.settings True UserControl MemoryView.cs UserControl RegistersView.cs UserControl StackTraceView.cs UserControl ThreadsView.cs UserControl TreeBasedGridView.cs Code {186F31A3-EF89-4A25-B2D5-20070222AA01} CodeTransformation False {186F31A3-EF89-4A25-B2D5-20060603AA01} IntermediateRepresentation False {186F31A3-EF89-4A25-B2D5-20070519AA01} ArmProcessor False {186F31A3-EF89-4A25-B2D5-20070606AA01} ProductConfiguration False {186F31A3-EF89-4A25-B2D5-20070601AA01} CommonPC False {186F31A3-EF89-4A25-B2D5-20061218AA01} Common False {186F31A3-EF89-4A25-B2D5-20060509AA01} Kernel False {186F31A3-EF89-4A25-B2D5-20060720AA01} TypeSystem False {186F31A3-EF89-4A25-B2D5-20060704AA01} ArmProcessorEmulation False ================================================ FILE: Zelig/Zelig/DebugTime/Debugger/Execution/DebugGarbageColllection.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // //#define DEBUG_BRICKTABLE namespace Microsoft.Zelig.Debugger.ArmProcessor { using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Text; using System.IO; using System.Windows.Forms; using System.Threading; using EncDef = Microsoft.Zelig.TargetModel.ArmProcessor.EncodingDefinition; using EncDef_VFP = Microsoft.Zelig.TargetModel.ArmProcessor.EncodingDefinition_VFP; using InstructionSet = Microsoft.Zelig.TargetModel.ArmProcessor.InstructionSet; using IR = Microsoft.Zelig.CodeGeneration.IR; using RT = Microsoft.Zelig.Runtime; using TS = Microsoft.Zelig.Runtime.TypeSystem; using Cfg = Microsoft.Zelig.Configuration.Environment; public class DebugGarbageColllection { class ProhibitedRange { // // State // internal uint m_addressStart; internal uint m_addressEnd; // // Constructor Methods // internal ProhibitedRange( uint addressStart , uint addressEnd ) { m_addressStart = addressStart; m_addressEnd = addressEnd; } // // Helper Methods // internal int Compare( uint addressStart , uint addressEnd ) { if(m_addressStart >= addressEnd) { return 1; } else if(m_addressEnd <= addressStart) { return -1; } else { return 0; } } // // Debug Methods // public override string ToString() { return string.Format( "[{0:X8}-{1:X8}]", m_addressStart, m_addressEnd ); } } // // State // private MemoryDelta m_memDelta; private bool m_fVerbose; private InteropHelper m_ih; private Emulation.ArmProcessor.Simulator m_simulator; private List< ProhibitedRange > m_freeRanges = new List< ProhibitedRange >(); private int m_suspendCount; // // Constructor Methods // public DebugGarbageColllection( MemoryDelta memDelta , bool fVerbose ) { m_memDelta = memDelta; m_fVerbose = fVerbose; m_ih = new InteropHelper( memDelta.ImageInformation, memDelta.Host ); memDelta.Host.GetHostingService( out this.m_simulator ); if(memDelta.ImageInformation.TypeSystem != null && this.m_simulator != null) { RegisterInterops(); } } // // Helper Methods // void RegisterInterops() { this.m_simulator.NotifyOnStore += delegate( uint address, uint value, TargetAdapterAbstractionLayer.MemoryAccessType kind ) { CheckAccess( address, value == 0xDEADBEEF ); }; m_ih.SetInteropOnWellKnownMethod( "DebugGC_MemorySegment_Initialize", false, delegate() { m_suspendCount++; m_ih.SetTemporaryInteropOnReturn( delegate() { m_suspendCount--; return Emulation.Hosting.Interop.CallbackResponse.DoNothing; } ); return Emulation.Hosting.Interop.CallbackResponse.DoNothing; } ); m_ih.SetInteropOnWellKnownMethod( "DebugGC_MemorySegment_LinkNewFreeBlock", false, delegate() { m_suspendCount++; m_ih.SetTemporaryInteropOnReturn( delegate() { m_suspendCount--; return Emulation.Hosting.Interop.CallbackResponse.DoNothing; } ); return Emulation.Hosting.Interop.CallbackResponse.DoNothing; } ); m_ih.SetInteropOnWellKnownMethod( "DebugGC_MemorySegment_RemoveFreeBlock", false, delegate() { uint ptr = m_ih.GetRegisterUInt32( EncDef.c_register_r1 ); int pos = FindRange( m_freeRanges, ptr ); if(pos < 0) { ReportProblem( "Expecting a free block at 0x{0:X8}", ptr ); } else { m_freeRanges.RemoveAt( pos ); } return Emulation.Hosting.Interop.CallbackResponse.DoNothing; } ); m_ih.SetInteropOnWellKnownMethod( "DebugGC_MemoryFreeBlock_ZeroFreeMemory", false, delegate() { m_suspendCount++; m_ih.SetTemporaryInteropOnReturn( delegate() { m_suspendCount--; return Emulation.Hosting.Interop.CallbackResponse.DoNothing; } ); return Emulation.Hosting.Interop.CallbackResponse.DoNothing; } ); m_ih.SetInteropOnWellKnownMethod( "DebugGC_MemoryFreeBlock_DirtyFreeMemory", false, delegate() { m_suspendCount++; m_ih.SetTemporaryInteropOnReturn( delegate() { m_suspendCount--; return Emulation.Hosting.Interop.CallbackResponse.DoNothing; } ); return Emulation.Hosting.Interop.CallbackResponse.DoNothing; } ); m_ih.SetInteropOnWellKnownMethod( "DebugGC_MemoryFreeBlock_InitializeFromRawMemory", false, delegate() { uint baseAddress = m_ih.GetRegisterUInt32( EncDef.c_register_r1 ); uint sizeInBytes = m_ih.GetRegisterUInt32( EncDef.c_register_r2 ); m_ih.SetTemporaryInteropOnReturn( delegate() { AddRange( baseAddress, baseAddress + sizeInBytes ); return Emulation.Hosting.Interop.CallbackResponse.DoNothing; } ); return Emulation.Hosting.Interop.CallbackResponse.DoNothing; } ); m_ih.SetInteropOnWellKnownMethod( "DebugGC_ObjectHeader_InsertPlug", false, delegate() { uint pThis = m_ih.GetRegisterUInt32( EncDef.c_register_r0 ); uint size = m_ih.GetRegisterUInt32( EncDef.c_register_r1 ); m_suspendCount++; m_ih.SetTemporaryInteropOnReturn( delegate() { m_suspendCount--; if(FindRange( m_freeRanges, pThis ) < 0) { AddRange( pThis, pThis + size ); } return Emulation.Hosting.Interop.CallbackResponse.DoNothing; } ); return Emulation.Hosting.Interop.CallbackResponse.DoNothing; } ); if(m_fVerbose) { m_ih.SetInteropOnWellKnownMethod( "DebugGC_DefaultTypeSystemManager_AllocateInner", false, delegate() { uint vTable = m_ih.GetRegisterUInt32( EncDef.c_register_r1 ); uint size = m_ih.GetRegisterUInt32( EncDef.c_register_r2 ); m_ih.SetTemporaryInteropOnReturn( delegate() { uint ptr = m_ih.GetRegisterUInt32( EncDef.c_register_r0 ); if(ptr != 0) { var td = m_memDelta.ImageInformation.GetTypeFromVirtualTable( vTable ); if(td == null) { ReportProblem( "Cannot decode vTable at {0:X8}", vTable ); } else { ReportInfo( "NewObject: {0:X8} {1} bytes, {2}", ptr, size, td.FullNameWithAbbreviation ); } } return Emulation.Hosting.Interop.CallbackResponse.DoNothing; } ); return Emulation.Hosting.Interop.CallbackResponse.DoNothing; } ); } m_ih.SetInteropOnWellKnownMethod( "DebugGC_MemoryFreeBlock_Allocate", false, delegate() { uint size = m_ih.GetRegisterUInt32( EncDef.c_register_r2 ); m_suspendCount++; var freeRangesOld = new List< ProhibitedRange >( m_freeRanges.ToArray() ); m_ih.SetTemporaryInteropOnReturn( delegate() { m_suspendCount--; uint ptr = m_ih.GetRegisterUInt32( EncDef.c_register_r0 ); if(ptr != 0) { int pos; pos = FindRange( freeRangesOld, ptr ); if(pos < 0) { ReportProblem( "Allocated memory from a non-free range: 0x{0:X8}, {1} bytes", ptr, size ); } pos = FindRange( m_freeRanges, ptr ); if(pos >= 0) { ProhibitedRange rng = m_freeRanges[pos]; if(rng.m_addressEnd == ptr + size) { rng.m_addressEnd = ptr; } else { ReportProblem( "Memory still free after allocation: 0x{0:X8}, {1} bytes", ptr, size ); } } } return Emulation.Hosting.Interop.CallbackResponse.DoNothing; } ); return Emulation.Hosting.Interop.CallbackResponse.DoNothing; } ); #if DEBUG_BRICKTABLE m_ih.SetInteropOnWellKnownMethod( "DebugBrickTable_VerifyBrickTable", false, delegate() { ReportInfo( "Verify" ); m_ih.SetTemporaryInteropOnReturn( delegate() { ReportInfo( "Verify Done" ); return Emulation.Hosting.Interop.CallbackResponse.DoNothing; } ); return Emulation.Hosting.Interop.CallbackResponse.DoNothing; } ); m_ih.SetInteropOnWellKnownMethod( "DebugBrickTable_Reset", false, delegate() { ReportInfo( "Reset" ); return Emulation.Hosting.Interop.CallbackResponse.DoNothing; } ); m_ih.SetInteropOnWellKnownMethod( "DebugBrickTable_MarkObject", false, delegate() { uint objectPtr = m_ih.GetRegisterUInt32( EncodingDefinition.c_register_r1 ); uint objectSize = m_ih.GetRegisterUInt32( EncodingDefinition.c_register_r2 ); ReportInfo( "Mark {0:X8}[{2:X8}] {1}", objectPtr, objectSize, objectPtr - 0x080008AC ); return Emulation.Hosting.Interop.CallbackResponse.DoNothing; } ); m_ih.SetInteropOnWellKnownMethod( "DebugBrickTable_FindLowerBoundForObjectPointer", false, delegate() { uint interiorPtr = m_ih.GetRegisterUInt32( EncodingDefinition.c_register_r1 ); m_ih.SetTemporaryInteropOnReturn( delegate() { uint res = m_ih.GetRegisterUInt32( EncodingDefinition.c_register_r0 ); ReportInfo( "Find {0:X8}[{2:X8}] {1:X8}", interiorPtr, res, interiorPtr - 0x080008AC ); return Emulation.Hosting.Interop.CallbackResponse.DoNothing; } ); return Emulation.Hosting.Interop.CallbackResponse.DoNothing; } ); #endif } //--// private void CheckAccess( uint address , bool fDirty ) { if(m_suspendCount == 0 && this.m_simulator.AreTimingUpdatesEnabled) { int pos = FindRange( m_freeRanges, address ); if(pos >= 0) { if(fDirty) { // It's OK to overwrite a free block with dirty patterns. } else { ProhibitedRange rng = m_freeRanges[pos]; //// if(CheckStackTrace( "HeapInitialization" )) //// { //// return; //// } ReportProblem( "Bad access: 0x{0:X8}", address ); } } } } private void RemoveRange( uint addressStart , uint addressEnd ) { while(true) { int pos = FindRange( m_freeRanges, addressStart, addressEnd ); if(pos < 0) { return; } ProhibitedRange rng = m_freeRanges[pos]; bool fChunkOnLeft = rng.m_addressStart < addressStart; bool fChunkOnRight = rng.m_addressEnd > addressEnd; if(fChunkOnLeft) { if(fChunkOnRight) { var rng2 = new ProhibitedRange( addressEnd, rng.m_addressEnd ); m_freeRanges.Insert( pos + 1, rng2 ); rng.m_addressEnd = addressStart; } else { rng.m_addressEnd = addressStart; } } else { if(fChunkOnRight) { rng.m_addressStart = addressStart; } else { m_freeRanges.RemoveAt( pos ); } } } } private void AddRange( uint addressStart , uint addressEnd ) { RemoveRange( addressStart, addressEnd ); int pos = FindRange( m_freeRanges, addressStart, addressEnd ); if(pos < 0) { pos = ~pos; ProhibitedRange rng = new ProhibitedRange( addressStart, addressEnd ); m_freeRanges.Insert( pos, rng ); if(pos > 0) { ProhibitedRange rngPre = m_freeRanges[pos-1]; if(rngPre.m_addressEnd == rng.m_addressStart) { rngPre.m_addressEnd = rng.m_addressEnd; m_freeRanges.RemoveAt( pos ); rng = rngPre; pos--; } } while(pos < m_freeRanges.Count - 1) { ProhibitedRange rngPost = m_freeRanges[pos+1]; if(rngPost.m_addressStart > rng.m_addressEnd) { break; } rng.m_addressEnd = rngPost.m_addressEnd; m_freeRanges.RemoveAt( pos+1 ); } } else { ReportProblem( "Already a free range: 0x{0:X8}-0x{1:X8}", addressStart, addressEnd ); } } private bool CheckStackTrace( params string[] methods ) { m_memDelta.FlushCache(); ThreadStatus ts = ThreadStatus.GetCurrent( m_memDelta ); foreach(StackFrame sf in ts.StackTrace) { var methodName = sf.Method.ToShortString(); foreach(var method in methods) { if(methodName.Contains( method )) { return true; } } } return false; } private void ReportProblem( string fmt , params object[] parms ) { string issue = string.Format( fmt, parms ); m_memDelta.FlushCache(); ThreadStatus ts = ThreadStatus.GetCurrent( m_memDelta ); Emulation.Hosting.OutputSink sink; if(m_memDelta.Host.GetHostingService( out sink )) { sink.OutputLine( issue ); foreach(StackFrame sf in ts.StackTrace) { sink.OutputLine( "#### {0}", sf ); } } Emulation.Hosting.ProcessorControl svcPC; m_memDelta.Host.GetHostingService( out svcPC ); svcPC.StopExecution = true; } private void ReportInfo( string fmt , params object[] parms ) { string issue = string.Format( fmt, parms ); Emulation.Hosting.OutputSink sink; if(m_memDelta.Host.GetHostingService( out sink )) { sink.OutputLine( issue ); } } private static int FindRange( List< ProhibitedRange > freeRanges , uint address ) { return FindRange( freeRanges, address, address + 1 ); } private static int FindRange( List< ProhibitedRange > freeRanges , uint addressStart , uint addressEnd ) { int lo = 0; int hi = freeRanges.Count - 1; while(lo <= hi) { int mid = (lo + hi) / 2; int order = freeRanges[mid].Compare( addressStart, addressEnd ); if(order < 0) { lo = mid + 1; } else if(order > 0) { hi = mid - 1; } else { return mid; } } return ~lo; } } } ================================================ FILE: Zelig/Zelig/DebugTime/Debugger/Execution/ImageInformation.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // namespace Microsoft.Zelig.Debugger.ArmProcessor { using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Text; using System.IO; using System.Windows.Forms; using System.Threading; using Microsoft.Zelig.TargetModel.ArmProcessor; using EncDef = Microsoft.Zelig.TargetModel.ArmProcessor.EncodingDefinition_ARM; using EncDef_VFP = Microsoft.Zelig.TargetModel.ArmProcessor.EncodingDefinition_VFP_ARM; using InstructionSet = Microsoft.Zelig.TargetModel.ArmProcessor.InstructionSet; using IR = Microsoft.Zelig.CodeGeneration.IR; using RT = Microsoft.Zelig.Runtime; using TS = Microsoft.Zelig.Runtime.TypeSystem; using Cfg = Microsoft.Zelig.Configuration.Environment; using Microsoft.Zelig.CodeGeneration.IR; public class ImageInformation { private static EncDef s_Encoding = (EncodingDefinition_ARM)CurrentInstructionSetEncoding.GetEncoding(); //--// private class TypeSystemForExecution : IR.TypeSystemForCodeTransformation { internal TypeSystemForExecution() : base( null ) { } } public class PointerContext { // // State // private readonly ImageInformation m_owner; private readonly MemoryDelta m_mem; private readonly uint m_baseAddress; private readonly TS.TypeRepresentation m_baseType; private readonly TS.FieldRepresentation[] m_path; // // Constructor Methods // private PointerContext( ImageInformation owner , MemoryDelta mem , uint baseAddress , TS.TypeRepresentation baseType , TS.FieldRepresentation[] path ) { if(path == null) { path = TS.FieldRepresentation.SharedEmptyArray; } m_owner = owner; m_mem = mem; m_baseAddress = baseAddress; m_baseType = baseType; m_path = path; } // // Helper Methods // public static PointerContext Create( ImageInformation owner , MemoryDelta mem , IR.ImageBuilders.SequentialRegion reg ) { IR.DataManager.DataDescriptor dd = (IR.DataManager.DataDescriptor)reg.Context; return new PointerContext( owner, mem, reg.ExternalAddress, dd.Context, null ); } public PointerContext AccessField( TS.FieldRepresentation fd ) { if(fd.FieldType is TS.ValueTypeRepresentation) { return new PointerContext( m_owner, m_mem, m_baseAddress, m_baseType, ArrayUtility.AppendToNotNullArray( m_path, fd ) ); } else { uint address = this.Address + (uint)fd.Offset; uint ptr; if(m_mem.GetUInt32( address, out ptr )) { TS.TypeRepresentation td = m_owner.VerifyPresenceOfVirtualTable( m_mem, ptr ); if(td != null) { return new PointerContext( m_owner, m_mem, ptr, td, null ); } } } return null; } public PointerContext AccessField( string name ) { TS.TypeRepresentation td = this.Type; while(td != null) { foreach(TS.FieldRepresentation fd in td.Fields) { if(fd.Name == name) { return AccessField( fd ); } } td = td.Extends; } return null; } public PointerContext AccessField( params string[] path ) { PointerContext ptr = this; foreach(string name in path) { ptr = ptr.AccessField( name ); if(ptr == null) { break; } } return ptr; } public object AccessFieldValue( params string[] path ) { PointerContext ptr = this.AccessField( path ); return (ptr != null) ? ptr.Value : null; } //--// public override bool Equals( Object obj ) { if(obj is PointerContext) { PointerContext other = (PointerContext)obj; return this.Address == other.Address; } return false; } public override int GetHashCode() { return base.GetHashCode(); } public static bool operator ==( PointerContext a , PointerContext b ) { if((object)a == null && (object)b == null) { return true; } if((object)a != null && (object)b != null) { return a.Address == b.Address; } return false; } public static bool operator !=( PointerContext a , PointerContext b ) { return !(a == b); } // // Access Methods // public MemoryDelta MemoryDelta { get { return this.m_mem; } } public TS.TypeRepresentation Type { get { if(m_path.Length > 0) { return m_path[m_path.Length - 1].FieldType; } return m_baseType; } } public uint Address { get { uint address = m_baseAddress; foreach(TS.FieldRepresentation fd in m_path) { address += (uint)fd.Offset; } return address; } } public object Value { get { TS.TypeRepresentation td = this.Type; if(td is TS.ScalarTypeRepresentation) { uint size = td.SizeOfHoldingVariable; switch(size) { case 1: { byte val; if(m_mem.GetUInt8( this.Address, out val )) { if(td.IsSigned) { return (sbyte)val; } else { return val; } } } break; case 2: { ushort val; if(m_mem.GetUInt16( this.Address, out val )) { if(td.IsSigned) { return (short)val; } else { return val; } } } break; case 4: { uint val; if(m_mem.GetUInt32( this.Address, out val )) { if(td.IsInteger) { if(td.IsSigned) { return (int)val; } else { return val; } } else { return DataConversion.GetFloatFromBytes( val ); } } } break; case 8: { ulong val; if(m_mem.GetUInt64( this.Address, out val )) { if(td.IsInteger) { if(td.IsSigned) { return (long)val; } else { return val; } } else { return DataConversion.GetDoubleFromBytes( val ); } } } break; } } return null; } } } public class RangeToSourceCode { public class CodeCoverage { // // State // public ulong Hits; public ulong Cycles; public ulong WaitStates; } public class DebugInfoPlusBasicBlock { public Debugging.DebugInfo Info; public IR.BasicBlock Owner; public DebugInfoPlusBasicBlock( Debugging.DebugInfo info , IR.BasicBlock bb ) { this.Info = info; this.Owner = bb; } } // // State // public uint BaseAddress; public uint EndAddress; public IR.ImageBuilders.SequentialRegion Region; public List< DebugInfoPlusBasicBlock > DebugInfos = new List< DebugInfoPlusBasicBlock >(); public CodeCoverage Profile; // // Constructor Methods // public RangeToSourceCode( IR.ImageBuilders.SequentialRegion region , uint baseAddress ) { this.BaseAddress = baseAddress; this.EndAddress = baseAddress; this.Region = region; } // // Helper Methods // public bool Contains( uint address ) { return (this.BaseAddress <= address && address < this.EndAddress); } public int CompareTo( RangeToSourceCode other ) { int res = this.BaseAddress.CompareTo( other.BaseAddress ); if(res == 0) { res = this.EndAddress.CompareTo( other.EndAddress ); } return res; } public static int Compare( RangeToSourceCode left, RangeToSourceCode right ) { return left.CompareTo( right ); } public void AddDebugInfo( Debugging.DebugInfo di , IR.BasicBlock bb ) { if(di.Equals( this.LastDebugInfo ) == false) { this.DebugInfos.Add( new DebugInfoPlusBasicBlock( di, bb ) ); } } // // Access Methods // public bool IsEmpty { get { return this.BaseAddress == this.EndAddress; } } public Debugging.DebugInfo FirstDebugInfo { get { return this.DebugInfos.Count > 0 ? this.DebugInfos[0].Info : null; } } public Debugging.DebugInfo LastDebugInfo { get { return this.DebugInfos.Count > 0 ? this.DebugInfos[this.DebugInfos.Count-1].Info : null; } } // // Debug Methods // public override string ToString() { string fmt; if(this.FirstDebugInfo != null) { fmt = "0x{0:X8}-0x{1:X8} for {2} - {3}"; } else { fmt = "0x{0:X8}-0x{1:X8} for {2}"; } return string.Format( fmt, this.BaseAddress, this.EndAddress, this.Region, this.FirstDebugInfo ); } } public class DisassemblyLine { // // State // public readonly uint Address; public readonly string Text; // // Constructor Methods // public DisassemblyLine( uint address , string format , params object[] args ) { this.Address = address; this.Text = string.Format( format, args ); } } class TypeSystemImpl : Emulation.Hosting.TypeSystem { // // State // ImageInformation m_owner; Emulation.Hosting.AbstractHost m_host; // // Constructor Methods // internal TypeSystemImpl( ImageInformation owner , Emulation.Hosting.AbstractHost host ) { m_owner = owner; m_host = host; m_host.RegisterService( typeof(Emulation.Hosting.TypeSystem), this ); } // // Helper Methods // public override string FetchString( uint address ) { ProcessorHost processorHost; m_host.GetHostingService( out processorHost ); MemoryDelta memDelta = new MemoryDelta( m_owner, processorHost ); return m_owner.GetStringFromMemory( memDelta, address ); } } // // State // public string ImageFile; public Emulation.ArmProcessor.SymDef.SymbolToAddressMap SymbolToAddressMap; public Emulation.ArmProcessor.SymDef.AddressToSymbolMap AddressToSymbolMap; public List< Configuration.Environment.ImageSection > PhysicalImage; public uint ResetVector; public Cfg.ProductCategory Configuration; public IR.TypeSystemForCodeTransformation TypeSystem; public IR.ImageBuilders.Core ImageBuilder; public TS.CodeMap.ReverseIndex[] ReverseCodeMapIndex; public GrowOnlyHashTable< Debugging.DebugInfo, List< RangeToSourceCode > > SourceCodeToCodeLookup; public GrowOnlyHashTable< string , List< RangeToSourceCode > > FileToCodeLookup; public GrowOnlySet < string > SourceCodeFiles; public GrowOnlyHashTable< string , List< IR.ControlFlowGraphStateForCodeTransformation > > NameToCfg; public GrowOnlyHashTable< uint , TS.VTable > AddressToVirtualTable; public GrowOnlyHashTable< IR.BasicBlock , IR.BasicBlock > ResolveMethodWrappers; public RangeToSourceCode[] SortedRangesToSourceCode; public bool DisplayWrapper; private TypeSystemImpl m_implTypeSystem; // // Constructor Methods // public ImageInformation( string file ) { this.ImageFile = file; this.SymbolToAddressMap = new Emulation.ArmProcessor.SymDef.SymbolToAddressMap(); this.AddressToSymbolMap = new Emulation.ArmProcessor.SymDef.AddressToSymbolMap(); this.SourceCodeToCodeLookup = HashTableFactory.New < Debugging.DebugInfo, List< RangeToSourceCode > >(); this.FileToCodeLookup = HashTableFactory.New < string , List< RangeToSourceCode > >(); this.SourceCodeFiles = SetFactory .New < string >(); this.NameToCfg = HashTableFactory.New < string , List< IR.ControlFlowGraphStateForCodeTransformation > >(); this.AddressToVirtualTable = HashTableFactory.New < uint , TS.VTable >(); this.ResolveMethodWrappers = HashTableFactory.NewWithReferenceEquality< IR.BasicBlock , IR.BasicBlock >(); } // // Helper Methods // public void ApplyToProcessorHost( Emulation.Hosting.AbstractHost host , Cfg.ProductCategory configuration ) { this.Configuration = configuration; m_implTypeSystem = new TypeSystemImpl( this, host ); //--// Emulation.Hosting.ProcessorControl svcPC; host.GetHostingService( out svcPC ); svcPC.ResetState( configuration ); { Emulation.Hosting.CodeCoverage svcCC; if(host.GetHostingService( out svcCC )) { svcCC.SetSymbols( this.SymbolToAddressMap, this.AddressToSymbolMap ); } } svcPC.PrepareHardwareModels( configuration ); { Emulation.Hosting.ProcessorStatus svcPS; host.GetHostingService( out svcPS ); svcPS.ProgramCounter = this.ResetVector; } } public void DeployImage( Emulation.Hosting.AbstractHost host , Emulation.Hosting.ProcessorControl.ProgressCallback callback ) { Emulation.Hosting.ProcessorControl svcPC; host.GetHostingService( out svcPC ); svcPC.DeployImage( this.PhysicalImage, callback ); } public void InitializePlugIns( Emulation.Hosting.AbstractHost host , List< Type > extraHandlers ) { Emulation.Hosting.ProcessorControl svcPC; host.GetHostingService( out svcPC ); svcPC.StartPlugIns( extraHandlers ); } //--// public bool TryReadUInt32FromPhysicalImage( uint address, out uint value ) { foreach(var section in this.PhysicalImage) { if(section.InRange( address )) { value = BitConverter.ToUInt32( section.Payload, (int)(address - section.Address) ); return true; } } value = 0; return false; } public IR.ImageBuilders.SequentialRegion ResolveMethodToRegion( TS.MethodRepresentation md ) { if(md != null) { IR.ControlFlowGraphStateForCodeTransformation cfg = IR.TypeSystemForCodeTransformation.GetCodeForMethod( md ); if(cfg != null) { IR.ImageBuilders.SequentialRegion reg = this.TypeSystem.ImageBuilder.GetAssociatedRegion( cfg ); if(reg != null) { return reg; } } } return null; } public TS.CodeMap ResolveAddressToCodeMap( uint address ) { return TS.CodeMap.ResolveAddressToCodeMap( new UIntPtr( address ), this.ReverseCodeMapIndex ); } //--// public void CollectCodeCoverage( Emulation.Hosting.AbstractHost host ) { RangeToSourceCode lastRange = null; foreach(RangeToSourceCode rng in this.SortedRangesToSourceCode) { rng.Profile = null; } Emulation.Hosting.CodeCoverage svc; if(host.GetHostingService( out svc )) { svc.Enumerate( delegate( uint address, uint hits, uint cycles, uint waitStates ) { if(lastRange == null || !(lastRange.BaseAddress <= address && address < lastRange.EndAddress)) { uint offset; lastRange = FindSourceCode( address, out offset ); if(lastRange == null) { return; } } RangeToSourceCode.CodeCoverage profile = lastRange.Profile; if(profile == null) { profile = new RangeToSourceCode.CodeCoverage(); lastRange.Profile = profile; } profile.Hits += hits; profile.Cycles += cycles; profile.WaitStates += waitStates; } ); } } public RangeToSourceCode FindSourceCode( uint address , out uint offset ) { RangeToSourceCode[] array = this.SortedRangesToSourceCode; int low = 0; int high = array.Length - 1; while(low <= high) { int mid = (high + low) / 2; RangeToSourceCode rng = array[mid]; if(address < rng.BaseAddress) { high = mid - 1; } else if(address >= rng.EndAddress) { low = mid + 1; } else { offset = address - rng.BaseAddress; return rng; } } offset = 0; return null; } public IR.ImageBuilders.SequentialRegion FindRegion( uint address , out uint offset ) { RangeToSourceCode rng = FindSourceCode( address, out offset ); return rng != null ? rng.Region : null; } //--// private void SetTypeSystem( IR.TypeSystemForCodeTransformation ts ) { ts.BuildHierarchyTables(); IR.ImageBuilders.Core ib = ts.ImageBuilder; this.TypeSystem = ts; this.ImageBuilder = ib; this.ReverseCodeMapIndex = ib.ReverseCodeMapIndex; this.PhysicalImage = ts.Image; //--// ts.EnumerateFlowGraphs( delegate( IR.ControlFlowGraphStateForCodeTransformation cfg ) { var bbEnter = cfg.NormalizedEntryBasicBlock; var bbExit = cfg.NormalizedExitBasicBlock; var dominance = cfg.DataFlow_Dominance; var immediateDominators = cfg.DataFlow_ImmediateDominators; foreach(var bb in cfg.DataFlow_SpanningTree_BasicBlocks) { IR.BasicBlock bbMapsTo; if(bb == bbEnter) { bbMapsTo = bb; } else if(bbEnter.IsDominatedBy( bb, dominance )) { bbMapsTo = bbEnter; } else if(bb == bbExit) { bbMapsTo = bbExit; } else if(bbExit != null && bb.IsDominatedBy( bbExit, dominance )) { bbMapsTo = immediateDominators[bbExit.SpanningTreeIndex]; } else { bbMapsTo = bb; } this.ResolveMethodWrappers[bb] = bbMapsTo; } } ); ComputeRangeToSourceCode( ib ); this.ResetVector = ib.Bootstrap.ExternalAddress; } private void ComputeRangeToSourceCode( IR.ImageBuilders.Core ib ) { List< RangeToSourceCode > ranges = new List< RangeToSourceCode >(); RangeToSourceCode lastRange = null; foreach(IR.ImageBuilders.SequentialRegion reg in ib.SortedRegions) { object regCtx = reg.Context; if(regCtx is IR.BasicBlock) { IR.BasicBlock bb = (IR.BasicBlock)regCtx; IR.ControlFlowGraphStateForCodeTransformation cfg = (IR.ControlFlowGraphStateForCodeTransformation)bb.Owner; string txt = cfg.Method.ToShortString(); uint address = reg.BaseAddress.ToUInt32(); if(bb is IR.EntryBasicBlock) { this.SymbolToAddressMap[txt] = address; HashTableWithListFactory.AddUnique( this.NameToCfg, txt, cfg ); } this.AddressToSymbolMap[address] = txt; //--// if(lastRange != null) { if(lastRange.EndAddress == address && lastRange.IsEmpty) { lastRange.Region = reg; } else { lastRange = null; } } if(lastRange == null) { lastRange = new RangeToSourceCode( reg, address ); ranges.Add( lastRange ); } foreach(IR.ImageBuilders.ImageAnnotation an in reg.AnnotationList) { IR.Operator op = an.Target as IR.Operator; if(op != null) { Debugging.DebugInfo di = op.DebugInfo; if(di != null) { string fileName = di.SrcFileName; uint baseAddress = an.InsertionAddress; bool fNewRange; bool fUpdateDI; this.SourceCodeFiles.Insert( fileName ); if(lastRange.IsEmpty && lastRange.EndAddress == baseAddress) { fNewRange = false; fUpdateDI = true; } else if(lastRange.LastDebugInfo == null) { fNewRange = false; fUpdateDI = true; } else if(di.Equals( lastRange.LastDebugInfo )) { fNewRange = false; fUpdateDI = false; } else { fNewRange = true; fUpdateDI = true; } if(fNewRange) { if(lastRange != null) { lastRange.EndAddress = baseAddress; } lastRange = new RangeToSourceCode( reg, baseAddress ); ranges.Add( lastRange ); } if(fUpdateDI) { lastRange.AddDebugInfo( di, bb ); HashTableWithListFactory.AddUnique( this.SourceCodeToCodeLookup, di , lastRange ); HashTableWithListFactory.AddUnique( this.FileToCodeLookup , fileName.ToUpper(), lastRange ); } lastRange.EndAddress = baseAddress; } } } lastRange.EndAddress = reg.EndAddress.ToUInt32(); } else if(regCtx is IR.DataManager.ObjectDescriptor) { IR.DataManager.ObjectDescriptor od = regCtx as IR.DataManager.ObjectDescriptor; if(od != null) { TS.VTable vTable = od.Source as TS.VTable; if(vTable != null) { this.AddressToVirtualTable[ reg.ExternalAddress ] = vTable; } } lastRange = null; } } this.SortedRangesToSourceCode = ranges.ToArray(); Array.Sort( this.SortedRangesToSourceCode, RangeToSourceCode.Compare ); } //--//--//--// public bool LocateFirstSourceCode( uint pc , out IR.ImageBuilders.SequentialRegion reg , out uint offset , out Debugging.DebugInfo di ) { List< Debugging.DebugInfo > diLst; uint rgnOffset; if(LocateSourceCode( pc, out reg, out offset, out rgnOffset, out diLst ) && diLst.Count > 0) { di = diLst[0]; return true; } else { di = null; return false; } } public bool LocateFirstSourceCode( IR.ImageBuilders.SequentialRegion reg , uint offset , out Debugging.DebugInfo di ) { List< Debugging.DebugInfo > diLst; if(LocateSourceCode( reg, offset, out diLst ) && diLst.Count > 0) { di = diLst[0]; return true; } else { di = null; return false; } } public bool LocateSourceCode( IR.ImageBuilders.SequentialRegion reg , uint offset , out List< Debugging.DebugInfo > di ) { uint rangeOffset; return LocateSourceCode( reg.ExternalAddress + offset, out reg, out offset, out rangeOffset, out di ); } public bool LocateSourceCode( uint pc , out IR.ImageBuilders.SequentialRegion reg , out uint offset , out uint rngOffset, out List< Debugging.DebugInfo > di ) { di = new List< Debugging.DebugInfo >(); RangeToSourceCode rng = FindSourceCode( pc, out offset ); rngOffset = 0; if(rng != null) { reg = rng.Region; var bb = reg.Context as IR.BasicBlock; IR.BasicBlock bbReal = null; if(bb != null && this.DisplayWrapper == false) { this.ResolveMethodWrappers.TryGetValue( bb, out bbReal ); } if(bbReal != null && bbReal != bb) { var reg2 = this.ImageBuilder.GetAssociatedRegion( bbReal ); if(reg2 != null) { uint offset2; RangeToSourceCode rng2 = FindSourceCode( reg2.BaseAddress.ToUInt32(), out offset2 ); if(rng2 != null) { // // We are currently in a method wrapper. We just need to look for the first DebugInfo in the real code. // foreach(var pair in rng2.DebugInfos) { IR.BasicBlock bb3; this.ResolveMethodWrappers.TryGetValue( pair.Owner, out bb3 ); if(bb3 == pair.Owner) { di.Add( pair.Info ); return true; } } } } } if(rng.BaseAddress == pc) { // // If PC points to the beginning of a range, let's add all the DebugInfo for the range. // foreach(var pair in rng.DebugInfos) { IR.BasicBlock bb3; this.ResolveMethodWrappers.TryGetValue( pair.Owner, out bb3 ); if(bb3 == pair.Owner || this.DisplayWrapper) { di.Add( pair.Info ); } } } else if(rng.LastDebugInfo != null) { // // Otherwise only add the last one. // di.Add( rng.LastDebugInfo ); } rngOffset = rng.BaseAddress - reg.BaseAddress.ToUInt32(); offset += rngOffset; if(di.Count == 0) { di.Add( FindAnyDebugInfo( reg ) ); } return di.Count > 0; } else { reg = null; } return di.Count != 0; } //--//--//--// public void DisassembleBlock( MemoryDelta memDelta , List< DisassemblyLine > disasm , uint addressStart , uint addressCurrent , uint addressEnd ) { InstructionSet encoder = (InstructionSet)this.TypeSystem.PlatformAbstraction.GetInstructionSetProvider(); for(uint diff = addressEnd - addressStart; diff > 0; addressStart += sizeof(uint), diff -= sizeof(uint)) { uint opcode; if(memDelta.GetUInt32( addressStart, out opcode )) { uint target; bool targetIsCode; string res = encoder.DecodeAndPrint( addressStart, opcode, out target, out targetIsCode ); disasm.Add( new DisassemblyLine( addressStart, "0x{0:X8}:{1} {2:X8} {3}", addressStart, addressCurrent == addressStart ? "*" : " ", opcode, res ) ); } else { disasm.Add( new DisassemblyLine( addressStart, "0x{0:X8}:{1} ????????", addressStart, addressCurrent == addressStart ? "*" : " " ) ); } } } //--//--//--// public void FetchCurrentStackTrace( List< StackFrame > lst , MemoryDelta memDelta , Emulation.Hosting.Breakpoint[] breakpoints , RegisterContext regs ) { Emulation.Hosting.DeviceClockTicksTracking svc; memDelta.Host.GetHostingService( out svc ); using(var hnd = svc.SuspendTiming()) { lst.Clear(); int depth = 0; while(true) { uint pc = regs.ProgramCounter; uint rngOffset = 0; TS.CodeMap codeMap = ResolveAddressToCodeMap( pc ); var sf = new StackFrame(); sf.Depth = depth++; sf.CodeMapOfTarget = codeMap; sf.RegisterContext = regs; lst.Add( sf ); if(codeMap == null) { break; } regs = new RegisterContext( regs ); // // Instead of the return address, let's use the call site address. // if(sf.Depth > 0) { pc -= sizeof(uint); } LocateSourceCode( pc, out sf.Region, out sf.RegionOffset, out rngOffset, out sf.DebugInfos ); if(sf.Depth > 0) { sf.MoveToLastDebugInfo(); } else if(breakpoints != null) { foreach(var bp in breakpoints) { if(bp.WasHit && bp.Address == pc) { sf.MoveForwardToDebugInfo( bp.DebugInfo ); } } } if(Unwind( memDelta, codeMap, regs, rngOffset) == false) { break; } } } } private bool Unwind( MemoryDelta memDelta , TS.CodeMap codeMap , RegisterContext regs , uint rngOffset) { const uint c_STMFD_Mask = 0xFFFF0000; const uint c_STMFD_Opcode = 0xE92D0000; const uint c_FSTMFDD_Mask = 0xFFFF0F00; const uint c_FSTMFDD_Opcode = 0xED2D0B00; const uint c_SUBSP_Mask = 0xFFFFF000; const uint c_SUBSP_Opcode = 0xE24DD000; //--// const uint c_FLDMFDD_Mask = 0xFFFF0F00; const uint c_FLDMFDD_Opcode = 0xECBD0B00; const uint c_LDMFD_Mask = 0xFFFF0000; const uint c_LDMFD_Opcode = 0xE8BD0000; //--// uint pc = regs.ProgramCounter; for(int i = 0; i < codeMap.Ranges.Length; i++) { TS.CodeMap.Range rng = codeMap.Ranges[i]; if((rng.Flags & TS.CodeMap.Flags.EntryPoint) != 0) { if((rng.Flags & TS.CodeMap.Flags.BottomOfCallStack) != 0) { return false; } uint address = rng.Start.ToUInt32(); uint regRestoreMap = 0; uint regFpRestore = 0; uint regFpRestoreCount = 0; uint stackAdjustment = 0; bool fReturnAddressinLR = false; bool fDone = false; uint sp = regs.StackPointer; bool fIsImport = (0 != ( codeMap.Target.BuildTimeFlags & TS.MethodRepresentation.BuildTimeAttributes.Imported )); if(fIsImport) { address += rngOffset; } if(pc == address) { // // We are at the beginning of a method, the return address is in LR for sure. // fReturnAddressinLR = true; // // The PC has not executed the next prologue instruction, stop processing. // fDone = true; } if(fDone == false) { if((rng.Flags & TS.CodeMap.Flags.HasIntRegisterSave) != 0) { uint opcode_STMFD; if(memDelta.GetUInt32( address, out opcode_STMFD )) { if((opcode_STMFD & c_STMFD_Mask) == c_STMFD_Opcode) { regRestoreMap = opcode_STMFD & 0xFFFF; } else { //CHECKS.ASSERT( false, "Expecting a STMFD opcode, got 0x{0:X8}", opcode_STMFD ); return false; } } else { //CHECKS.ASSERT( false, "Cannot access method entrypoint at 0x{0:X8}", address ); return false; } address += sizeof(uint); } else if(fIsImport) { uint opcode_STMFD; if(memDelta.GetUInt32( address, out opcode_STMFD )) { if(( opcode_STMFD & c_STMFD_Mask ) == c_STMFD_Opcode) { regRestoreMap = opcode_STMFD & 0xFFFF; address += sizeof( uint ); } else { fReturnAddressinLR = true; } } } else { // // No register push, the return address is in LR for sure. // fReturnAddressinLR = true; } } if(pc == address) { // // The PC has not executed the next prologue instruction, stop processing. // fDone = true; } if(fDone == false) { if((rng.Flags & TS.CodeMap.Flags.HasFpRegisterSave) != 0) { uint opcode_FSTMFDD; if(memDelta.GetUInt32( address, out opcode_FSTMFDD )) { if((opcode_FSTMFDD & c_FSTMFDD_Mask) == c_FSTMFDD_Opcode) { regFpRestore = ((opcode_FSTMFDD & 0x0000F000) >> 12) * 2; regFpRestoreCount = (opcode_FSTMFDD & 0x000000FF); } else { //CHECKS.ASSERT( false, "Expecting a FSTMFDD opcode, got 0x{0:X8}", opcode_FSTMFDD ); return false; } } else { //CHECKS.ASSERT( false, "Cannot access method entrypoint at 0x{0:X8}", address ); return false; } address += sizeof(uint); } else if(fIsImport) { uint opcode_FSTMFDD; if(memDelta.GetUInt32( address, out opcode_FSTMFDD )) { if(( opcode_FSTMFDD & c_FSTMFDD_Mask ) == c_FSTMFDD_Opcode) { regFpRestore = ( ( opcode_FSTMFDD & 0x0000F000 ) >> 12 ) * 2; regFpRestoreCount = ( opcode_FSTMFDD & 0x000000FF ); address += sizeof( uint ); } } } } if(pc == address) { // // The PC has not executed the next prologue instruction, stop processing. // fDone = true; } if(fDone == false) { if((rng.Flags & TS.CodeMap.Flags.HasStackAdjustment) != 0) { uint opcode_SUBSP; if(memDelta.GetUInt32( address, out opcode_SUBSP )) { if((opcode_SUBSP & c_SUBSP_Mask) == c_SUBSP_Opcode) { stackAdjustment = s_Encoding.get_DataProcessing_ImmediateValue( opcode_SUBSP ); } else { //CHECKS.ASSERT( false, "Expecting a SUBSP opcode, got 0x{0:X8}", opcode_SUBSP ); return false; } } else { //CHECKS.ASSERT( false, "Cannot access method entrypoint at 0x{0:X8}", address ); return false; } } else if(fIsImport) { uint opcode_SUBSP; if(memDelta.GetUInt32( address, out opcode_SUBSP )) { if(( opcode_SUBSP & c_SUBSP_Mask ) == c_SUBSP_Opcode) { stackAdjustment = s_Encoding.get_DataProcessing_ImmediateValue( opcode_SUBSP ); } } } } //--// // // Deal with method epilogue: if we are on one of the return instructions, we need to restore less state. // uint opcode; if(memDelta.GetUInt32( pc, out opcode ) == false) { return false; } if((opcode & c_FLDMFDD_Mask) == c_FLDMFDD_Opcode) { stackAdjustment = 0; } if((opcode & c_LDMFD_Mask) == c_LDMFD_Opcode) { stackAdjustment = 0; regFpRestoreCount = 0; } //--// sp += stackAdjustment; if(fReturnAddressinLR) { //TODO: Why does the condition happen where we need to do this? //fmegen: sanity check uint newpc = regs.GetValueAsUInt( EncDef.c_register_lr ); if (pc == newpc) return false; pc = newpc; } else { while(regFpRestoreCount > 0) { regs.SetLocationInMemory( EncDef_VFP.c_register_d0 + regFpRestore / 2, memDelta, sp ); regs.SetLocationInMemory( EncDef_VFP.c_register_s0 + regFpRestore , memDelta, sp ); regs.SetLocationInMemory( EncDef_VFP.c_register_s1 + regFpRestore , memDelta, sp + sizeof(uint) ); sp += 2 * sizeof(uint); regFpRestore += 2; regFpRestoreCount -= 2; } for(uint regIdx = 0; regIdx < 16; regIdx++) { if((regRestoreMap & (1u << (int)regIdx)) != 0) { if(regIdx == EncDef.c_register_lr) { memDelta.GetUInt32( sp, out pc ); } else { regs.SetLocationInMemory( regIdx, memDelta, sp ); } sp += sizeof(uint); } } } regs.UpdateStackFrame( pc, sp ); return true; } } //CHECKS.ASSERT( false, "Cannot unwind {0}", codeMap.Target ); return false; } //--// public Debugging.DebugInfo FindAnyDebugInfo( IR.ImageBuilders.SequentialRegion reg ) { IR.BasicBlock bb = reg.Context as IR.BasicBlock; if(bb != null) { GrowOnlySet< IR.BasicBlock > visited = SetFactory.NewWithReferenceEquality< IR.BasicBlock >(); Debugging.DebugInfo di = FindAnyDebugInfo( reg.Owner, bb, visited, false ); if(di == null) { visited.Clear(); di = FindAnyDebugInfo( reg.Owner, bb, visited, true ); } return di; } return null; } private Debugging.DebugInfo FindAnyDebugInfo( IR.ImageBuilders.Core ib , IR.BasicBlock bb , GrowOnlySet< IR.BasicBlock > visited , bool fForward ) { if(visited.Insert( bb ) == false) { Debugging.DebugInfo di; IR.BasicBlockEdge[] array = fForward ? bb.Successors : bb.Predecessors; for(int pass = 0; pass < 2; pass++) { foreach(IR.BasicBlockEdge edge in array) { IR.BasicBlock bbNext = fForward ? edge.Successor : edge.Predecessor; if(pass == 0) { IR.ImageBuilders.SequentialRegion reg = ib.GetAssociatedRegion( bbNext ); if(reg != null) { List< IR.ImageBuilders.ImageAnnotation > lst = reg.AnnotationList; for(int pos = 0; pos < lst.Count; pos++) { IR.ImageBuilders.ImageAnnotation an = lst[fForward ? pos : (lst.Count-1) - pos]; IR.Operator op = an.Target as IR.Operator; if(op != null) { di = op.DebugInfo; if(di != null) { return di; } } } } } else { di = FindAnyDebugInfo( ib, bbNext, visited, fForward ); if(di != null) { return di; } } } } } return null; } //--// public IR.LowLevelVariableExpression[] AliveVariables( IR.ImageBuilders.SequentialRegion reg , uint offset ) { if(reg == null) { return new IR.LowLevelVariableExpression[0]; } GrowOnlyHashTable< IR.LowLevelVariableExpression, bool > liveness = HashTableFactory.NewWithReferenceEquality< IR.LowLevelVariableExpression, bool >(); foreach(IR.ImageBuilders.ImageAnnotation an in reg.AnnotationList) { if(an.Offset > offset) { break; } IR.ImageBuilders.TrackVariableLifetime tvl = an as IR.ImageBuilders.TrackVariableLifetime; if(tvl != null) { IR.LowLevelVariableExpression var = (IR.LowLevelVariableExpression)tvl.Target; liveness[var] = tvl.IsAlive; } } List< IR.LowLevelVariableExpression > livenessLst = new List< IR.LowLevelVariableExpression >(); foreach(IR.LowLevelVariableExpression var in liveness.Keys) { if(liveness[var]) { livenessLst.Add( var ); } } IR.LowLevelVariableExpression[] livenessArray = livenessLst.ToArray(); Array.Sort( livenessArray, delegate( IR.LowLevelVariableExpression x , IR.LowLevelVariableExpression y ) { int xKind = x.GetVariableKind(); int yKind = y.GetVariableKind(); if(xKind < yKind) return -1; if(xKind > yKind) return 1; return x.Number - y.Number; } ); return livenessArray; } //--// public PointerContext ResolveCostantExpression( MemoryDelta mem , IR.ConstantExpression ex ) { IR.ImageBuilders.SequentialRegion reg = this.ImageBuilder.GetAssociatedRegion( ex ); if(reg != null) { return PointerContext.Create( this, mem, reg ); } return null; } public PointerContext ResolveSingleton( MemoryDelta mem , TS.TypeRepresentation td ) { td = this.TypeSystem.FindActualSingleton( td ); IR.DataManager.ObjectDescriptor od = this.TypeSystem.GetSingleton( td ); if(od != null) { IR.ImageBuilders.SequentialRegion reg = this.ImageBuilder.GetAssociatedRegion( od ); if(reg != null) { if(VerifyPresenceOfVirtualTable( mem, reg.ExternalAddress ) != null) { return PointerContext.Create( this, mem, reg ); } } } return null; } public TS.TypeRepresentation VerifyPresenceOfVirtualTable( MemoryDelta mem , uint address ) { if(address != 0) { address = GetVirtualTablePointerAddress( address ); if(address != 0) { uint vTableAddress; if(mem.GetUInt32( address, out vTableAddress )) { return GetTypeFromVirtualTable( vTableAddress ); } } } return null; } //--// public uint GetVirtualTablePointerAddress( uint address ) { IR.TypeSystemForCodeTransformation ts = this.TypeSystem; TS.TypeRepresentation ohTd = ts.WellKnownTypes .Microsoft_Zelig_Runtime_ObjectHeader; TS.FieldRepresentation vtFd = ts.WellKnownFields.ObjectHeader_VirtualTable; if(ohTd == null || vtFd == null) { return 0; } address -= ohTd.VirtualTable.BaseSize; address += (uint)vtFd.Offset; return address; } public TS.TypeRepresentation GetTypeFromVirtualTable( uint vTableAddress ) { TS.VTable vTable; if(this.AddressToVirtualTable.TryGetValue( vTableAddress, out vTable )) { return vTable.TypeInfo; } return null; } public string GetStringFromMemory( MemoryDelta memDelta , uint address ) { if(address != 0) { IR.TypeSystemForCodeTransformation ts = this.TypeSystem; uint len; if(memDelta.GetUInt32( (uint)(address + ts.WellKnownFields.StringImpl_StringLength.Offset), out len ) && len < 8192) { char[] data = new char[len]; for(int pos = 0; pos < len; pos++) { ushort val; char ch; if(memDelta.GetUInt16( (uint)(address + ts.WellKnownFields.StringImpl_FirstChar.Offset + pos * sizeof(char)), out val ) == false) { ch = '?'; } else { ch = (char)val; switch(Char.GetUnicodeCategory( ch )) { case System.Globalization.UnicodeCategory.Surrogate : case System.Globalization.UnicodeCategory.OtherNotAssigned: ch = '?'; break; } } data[pos] = ch; } return new string( data ); } } return null; } //--// public static ImageInformation LoadZeligImage( string file , Emulation.Hosting.ProcessorControl.ProgressCallback callback ) { var imageInformation = new ImageInformation( file ); using(System.IO.Stream serializedStream = new System.IO.FileStream( file, System.IO.FileMode.Open )) { IR.TypeSystemSerializer.CreateInstance dlgCreateInstance = delegate( Type t ) { if(t == typeof(IR.TypeSystemForCodeTransformation)) { return new TypeSystemForExecution(); } return null; }; IR.TypeSystemSerializer.ProgressCallback dlgProgress = delegate( long pos, long total ) { callback( "Loading {0}%", (uint)(pos * 100.0 / total + 0.5) ); }; var ts = IR.TypeSystemSerializer.Deserialize( serializedStream, dlgCreateInstance, dlgProgress, 10000 ); imageInformation.SetTypeSystem( ts ); } return imageInformation; } public static ImageInformation LoadHexImage( string file ) { ImageInformation imageInformation = new ImageInformation( file ); imageInformation.ResetVector = 0x10300000; var blocks = new List< Emulation.ArmProcessor.SRecordParser.Block >(); Emulation.ArmProcessor.SRecordParser.Parse( file, blocks ); imageInformation.ConvertFromBlocksToImage( blocks ); return imageInformation; } public static ImageInformation LoadAdsImage( string file ) { ImageInformation imageInformation = new ImageInformation( file ); string prefix = Path.GetDirectoryName( file ) + Path.DirectorySeparatorChar + Path.GetFileNameWithoutExtension( file ); //// root = @"S:\enlistments\local\main\client_BUILD\arm\FLASH\release\P3B_STUB\bin"; // Live depoth //// root = Environment.ExpandEnvironmentVariables( @"%DEPOTROOT%\Zelig\Test\ArmEmulator\P3B_STUB\bin" ); //// root = Environment.ExpandEnvironmentVariables( @"%DEPOTROOT%\Zelig\Test\ArmEmulator\ZeligVsZenith" ); Emulation.ArmProcessor.SymDef.Parse( prefix + ".axfdump", imageInformation.SymbolToAddressMap, imageInformation.AddressToSymbolMap ); Emulation.ArmProcessor.SymDef.Parse( prefix + ".symdefs", imageInformation.SymbolToAddressMap, imageInformation.AddressToSymbolMap ); uint resetVector; if(imageInformation.SymbolToAddressMap.TryGetValue( "EntryPoint", out resetVector ) == false) { imageInformation.SymbolToAddressMap.TryGetValue( "EntryPoint__Fv", out resetVector ); } imageInformation.ResetVector = resetVector; var blocks = new List< Emulation.ArmProcessor.SRecordParser.Block >(); Emulation.ArmProcessor.SRecordParser.Parse( prefix + @".hex\ER_FLASH", blocks ); Emulation.ArmProcessor.SRecordParser.Parse( prefix + @".hex\ER_DAT" , blocks ); imageInformation.ConvertFromBlocksToImage( blocks ); return imageInformation; } private void ConvertFromBlocksToImage( List< Emulation.ArmProcessor.SRecordParser.Block > blocks ) { this.PhysicalImage = new List< Configuration.Environment.ImageSection >(); foreach(Emulation.ArmProcessor.SRecordParser.Block block in blocks) { this.PhysicalImage.Add( new Configuration.Environment.ImageSection( block.address, block.data.ToArray(), null, 0, 0 ) ); } } } } ================================================ FILE: Zelig/Zelig/DebugTime/Debugger/Execution/InteropHelper.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // namespace Microsoft.Zelig.Debugger.ArmProcessor { using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Text; using System.IO; using System.Windows.Forms; using System.Threading; using EncDef = Microsoft.Zelig.TargetModel.ArmProcessor.EncodingDefinition; using InstructionSet = Microsoft.Zelig.TargetModel.ArmProcessor.InstructionSet; using IR = Microsoft.Zelig.CodeGeneration.IR; using RT = Microsoft.Zelig.Runtime; using TS = Microsoft.Zelig.Runtime.TypeSystem; public class InteropHelper { // // State // private ImageInformation m_imageInformation; private Emulation.Hosting.AbstractHost m_host; private IR.TypeSystemForCodeTransformation m_typeSystem; // // Constructor Methods // public InteropHelper( ImageInformation imageInformation , Emulation.Hosting.AbstractHost host ) { m_imageInformation = imageInformation; m_host = host; m_typeSystem = imageInformation.TypeSystem; } // // Helper Methods // public void SetInteropOnWellKnownMethod( string name , bool fPostProcessing , Emulation.Hosting.Interop.Callback ftn ) { TS.MethodRepresentation md = m_typeSystem.GetWellKnownMethodNoThrow( name ); if(md is TS.VirtualMethodRepresentation) { for(TS.TypeRepresentation td = m_typeSystem.FindSingleConcreteImplementation( md.OwnerType ); td != null; td = td.Extends) { TS.MethodRepresentation md2 = td.FindMatch( md, null ); if(md2 != null) { md = md2; break; } } } if(md != null) { IR.ImageBuilders.SequentialRegion reg = m_imageInformation.ResolveMethodToRegion( md ); if(reg != null) { Emulation.Hosting.Interop svc; if(m_host.GetHostingService( out svc )) { svc.SetInterop( reg.ExternalAddress, true, fPostProcessing, ftn ); } } } } public bool SetInteropOnAddress( uint pc , Emulation.Hosting.Interop.Callback ftn ) { Emulation.Hosting.Interop svc; if(m_host.GetHostingService( out svc )) { svc.SetInterop( pc, true, false, ftn ); return true; } return false; } public bool SetTemporaryInteropOnReturn( Emulation.Hosting.Interop.Callback ftn ) { Emulation.Hosting.Interop svc; if(m_host.GetHostingService( out svc )) { uint lr = GetRegisterUInt32( EncDef.c_register_lr ); uint sp = GetRegisterUInt32( EncDef.c_register_sp ); svc.SetInterop( lr, true, false, delegate() { if(sp == GetRegisterUInt32( EncDef.c_register_sp )) { return ftn() | Emulation.Hosting.Interop.CallbackResponse.RemoveDetour; } return Emulation.Hosting.Interop.CallbackResponse.DoNothing; } ); return true; } return false; } public Emulation.Hosting.Interop.CallbackResponse SkipCall() { uint pc = GetRegisterUInt32( EncDef.c_register_lr ); Emulation.Hosting.ProcessorStatus svc; m_host.GetHostingService( out svc ); svc.ProgramCounter = pc; svc.RaiseExternalProgramFlowChange(); return Emulation.Hosting.Interop.CallbackResponse.NextInstruction; } public uint GetRegisterUInt32( uint idx ) { Emulation.Hosting.ProcessorStatus svc; m_host.GetHostingService( out svc ); var bb = svc.GetRegister( m_imageInformation.TypeSystem.PlatformAbstraction.GetRegisterForEncoding( idx ) ); return bb != null ? bb.ReadUInt32( 0 ) : 0; } } } ================================================ FILE: Zelig/Zelig/DebugTime/Debugger/Execution/MemoryDelta.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // //#define DEBUG_MEMORYDELTA_PREFETCHES namespace Microsoft.Zelig.Debugger.ArmProcessor { using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Text; using System.IO; using System.Windows.Forms; using System.Threading; using EncDef = Microsoft.Zelig.TargetModel.ArmProcessor.EncodingDefinition; using InstructionSet = Microsoft.Zelig.TargetModel.ArmProcessor.InstructionSet; using IR = Microsoft.Zelig.CodeGeneration.IR; using RT = Microsoft.Zelig.Runtime; using TS = Microsoft.Zelig.Runtime.TypeSystem; using Cfg = Microsoft.Zelig.Configuration.Environment; public class MemoryDelta { class Cluster { // // State // internal const int c_Size = 512; internal bool[] m_valid; internal byte[] m_data; // // Constructor Methods // internal Cluster() { m_valid = new bool[c_Size]; m_data = new byte[c_Size]; } internal Cluster( byte[] data ) { m_valid = new bool[c_Size]; m_data = data; for(int i = 0 ; i < c_Size; i++) { m_valid[i] = true; } } // // Helper Methods // internal static uint GetBase( uint address ) { return address & ~(uint)(c_Size - 1); } internal static uint GetOffset( uint address ) { return address % (uint)c_Size; } internal static Cluster GetCluster( GrowOnlyHashTable< uint, Cluster > ht , uint address , bool fCreate ) { Cluster res; uint index = address / c_Size; if(ht.TryGetValue( index, out res ) == false) { if(fCreate) { res = new Cluster(); ht[index] = res; } } return res; } internal static void SetCluster( GrowOnlyHashTable< uint, Cluster > ht , uint address , byte[] data ) { DumpCluster( address, data ); uint index = address / c_Size; ht[index] = new Cluster( data ); } internal bool IsValid( uint address ) { uint offset = GetOffset( address ); return m_valid[offset]; } [System.Diagnostics.Conditional( "DEBUG_MEMORYDELTA_PREFETCHES" )] private static void DumpCluster( uint address , byte[] data ) { Console.WriteLine( "GetCluster" ); for(int i = 0; i < data.Length; i += 4) { if(i % 32 == 0) { Console.Write( "0x{0:X8}: ", address + i ); } Console.Write( "0x{0:X2}{1:X2}{2:X2}{3:X2}, ", data[i+3], data[i+2], data[i+1], data[i] ); if(i % 32 == 32 - 4) { Console.WriteLine( "" ); } } Console.WriteLine( "" ); } // // Access Methods // internal byte this[uint address] { get { uint offset = GetOffset( address ); return m_data[offset]; } set { uint offset = GetOffset( address ); m_data [offset] = value; m_valid[offset] = true; } } } // // State // ImageInformation m_imageInformation; Emulation.Hosting.AbstractHost m_host; Emulation.Hosting.MemoryProvider m_mem; bool m_fRunning; GrowOnlyHashTable< uint, Cluster > m_snapshot; GrowOnlyHashTable< uint, Cluster > m_snapshotPrevious; // // Constructor Methods // internal MemoryDelta( ImageInformation imageInformation , Emulation.Hosting.AbstractHost host ) { Synchronize( imageInformation, host ); } // // Helper Methods // public void RegisterForNotification( bool fEntering , bool fExiting ) { ProcessorHost svc; if(m_host.GetHostingService( out svc )) { svc.RegisterForNotification( this, fEntering, fExiting ); } } public void UnregisterForNotification( bool fEntering , bool fExiting ) { ProcessorHost svc; if(m_host.GetHostingService( out svc )) { svc.UnregisterForNotification( this, fEntering, fExiting ); } } internal void EnteringExecuting() { m_fRunning = true; } internal void ExitingRunning() { CopyPreviousValues(); m_snapshot = HashTableFactory.New< uint, Cluster >(); m_fRunning = false; } //--// public void FlushCache() { m_snapshot.Clear(); } //--// public bool GetUInt8( uint address , out byte result ) { bool fChanged; return GetUInt8( address, true, out result, out fChanged ); } public bool GetUInt8( uint address , bool fUpdateHistory , out byte result , out bool fChanged ) { fChanged = false; TryToLookAhead( m_snapshot, address, address + 128 ); if(ReadSnapshot( address, out result, m_snapshot ) == false) { if(m_fRunning) { return false; } if(m_mem.GetUInt8( address, out result ) == false) { return false; } if(fUpdateHistory) { WriteSnapshot( address, result, m_snapshot ); } } byte previousResult; if(ReadSnapshot( address, out previousResult, m_snapshotPrevious ) && previousResult != result) { fChanged = true; } return true; } //--// public bool GetUInt16( uint address , out ushort result ) { bool fChanged; return GetUInt16( address, true, out result, out fChanged ); } public bool GetUInt16( uint address , bool fUpdateHistory , out ushort result , out bool fChanged ) { fChanged = false; TryToLookAhead( m_snapshot, address, address + 128 ); if(ReadSnapshot( address, out result, m_snapshot ) == false) { if(m_fRunning) { return false; } if(m_mem.GetUInt16( address, out result ) == false) { return false; } if(fUpdateHistory) { WriteSnapshot( address, result, m_snapshot ); } } ushort previousResult; if(ReadSnapshot( address, out previousResult, m_snapshotPrevious ) && previousResult != result) { fChanged = true; } return true; } //--// public bool GetUInt32( uint address , out uint result ) { bool fChanged; return GetUInt32( address, true, out result, out fChanged ); } public bool GetUInt32( uint address , bool fUpdateHistory , out uint result , out bool fChanged ) { fChanged = false; TryToLookAhead( m_snapshot, address, address + 128 ); if(ReadSnapshot( address, out result, m_snapshot ) == false) { if(m_fRunning) { return false; } if(m_mem.GetUInt32( address, out result ) == false) { return false; } if(fUpdateHistory) { WriteSnapshot( address, result, m_snapshot ); } } uint previousResult; if(ReadSnapshot( address, out previousResult, m_snapshotPrevious ) && previousResult != result) { fChanged = true; } return true; } //--// public bool GetUInt64( uint address , out ulong result ) { bool fChanged; return GetUInt64( address, true, out result, out fChanged ); } public bool GetUInt64( uint address , bool fUpdateHistory , out ulong result , out bool fChanged ) { fChanged = false; TryToLookAhead( m_snapshot, address, address + 128 ); if(ReadSnapshot( address, out result, m_snapshot ) == false) { if(m_fRunning) { return false; } if(m_mem.GetUInt64( address, out result ) == false) { return false; } if(fUpdateHistory) { WriteSnapshot( address, result, m_snapshot ); } } ulong previousResult; if(ReadSnapshot( address, out previousResult, m_snapshotPrevious ) && previousResult != result) { fChanged = true; } return true; } //--// public bool GetBlock( uint address , int size , out byte[] result ) { bool fChanged; return GetBlock( address, size, true, out result, out fChanged ); } public bool GetBlock( uint address , int size , bool fUpdateHistory , out byte[] result , out bool fChanged ) { fChanged = false; result = new byte[size]; for(int pos = 0; pos < size; pos++) { bool fChangedVal; if(GetUInt8( address, fUpdateHistory, out result[pos], out fChangedVal ) == false) { return false; } address += sizeof(byte); } return true; } //--// public bool SetUInt8( uint address , byte result ) { if(m_fRunning) { return false; } if(m_mem.SetUInt8( address, result ) == false) { return false; } // // Mark the address as changed. // WriteSnapshot( address, result, m_snapshot ); WriteSnapshot( address, (byte)~result, m_snapshotPrevious ); return true; } public bool SetUInt16( uint address , ushort result ) { if(m_fRunning) { return false; } if(m_mem.SetUInt16( address, result ) == false) { return false; } // // Mark the address as changed. // WriteSnapshot( address, result, m_snapshot ); WriteSnapshot( address, (ushort)~result, m_snapshotPrevious ); return true; } public bool SetUInt32( uint address , uint result ) { if(m_fRunning) { return false; } if(m_mem.SetUInt32( address, result ) == false) { return false; } // // Mark the address as changed. // WriteSnapshot( address, result, m_snapshot ); WriteSnapshot( address, (uint)~result, m_snapshotPrevious ); return true; } public bool SetUInt64( uint address , ulong result ) { if(m_fRunning) { return false; } if(m_mem.SetUInt64( address, result ) == false) { return false; } // // Mark the address as changed. // WriteSnapshot( address, result, m_snapshot ); WriteSnapshot( address, (ulong)~result, m_snapshotPrevious ); return true; } //--// public bool SetBlock( uint address , byte[] result ) { for(int pos = 0; pos < result.Length; pos++) { if(SetUInt8( address, result[pos] ) == false) { return false; } address += sizeof(byte); } return true; } //--// private static void WriteSnapshot( uint address , byte value , GrowOnlyHashTable< uint, Cluster > ht ) { var cluster = Cluster.GetCluster( ht, address, true ); cluster[address] = value; } private static void WriteSnapshot( uint address , ushort value , GrowOnlyHashTable< uint, Cluster > ht ) { WriteSnapshot( address , (byte)(value ), ht ); WriteSnapshot( address + sizeof(byte), (byte)(value >> 8), ht ); } private static void WriteSnapshot( uint address , uint value , GrowOnlyHashTable< uint, Cluster > ht ) { WriteSnapshot( address , (ushort)(value ), ht ); WriteSnapshot( address + sizeof(ushort), (ushort)(value >> 16), ht ); } private static void WriteSnapshot( uint address , ulong value , GrowOnlyHashTable< uint, Cluster > ht ) { WriteSnapshot( address , (uint)(value ), ht ); WriteSnapshot( address + sizeof(uint), (uint)(value >> 32), ht ); } //--// private void TryToLookAhead( GrowOnlyHashTable< uint, Cluster > ht , uint startAddress , uint endAddress ) { if(m_fRunning == false) { startAddress = Cluster.GetBase( startAddress ); while(startAddress < endAddress) { var cluster = Cluster.GetCluster( ht, startAddress, false ); if(cluster == null) { bool fOk = false; foreach(Cfg.MemoryCategory mem in m_imageInformation.Configuration.SearchValues< Cfg.MemoryCategory >()) { if((mem.Characteristics & RT.MemoryAttributes.RandomAccessMemory) != 0) { if(startAddress >= mem.BaseAddress && startAddress < mem.BaseAddress + mem.SizeInBytes) { fOk = true; break; } } } if(fOk) { byte[] res; if(m_mem.GetBlock( startAddress, Cluster.c_Size, sizeof(uint), out res )) { Cluster.SetCluster( ht, startAddress, res ); } } } startAddress += Cluster.c_Size; } } } private bool ReadSnapshot( uint address , out byte value , GrowOnlyHashTable< uint, Cluster > ht ) { var cluster = Cluster.GetCluster( ht, address, false ); if(cluster != null) { if(cluster.IsValid( address )) { value = cluster[address]; return true; } } value = 0; return false; } private bool ReadSnapshot( uint address , out ushort value , GrowOnlyHashTable< uint, Cluster > ht ) { byte partLo; byte partHi; if(ReadSnapshot( address , out partLo, ht ) && ReadSnapshot( address + sizeof(byte), out partHi, ht ) ) { value = (ushort)(((uint)partHi << 8) | (uint)partLo); return true; } value = 0; return false; } private bool ReadSnapshot( uint address , out uint value , GrowOnlyHashTable< uint, Cluster > ht ) { ushort partLo; ushort partHi; if(ReadSnapshot( address , out partLo, ht ) && ReadSnapshot( address + sizeof(ushort), out partHi, ht ) ) { value = (((uint)partHi << 16) | (uint)partLo); return true; } value = 0; return false; } private bool ReadSnapshot( uint address , out ulong value , GrowOnlyHashTable< uint, Cluster > ht ) { uint partLo; uint partHi; if(ReadSnapshot( address , out partLo, ht ) && ReadSnapshot( address + sizeof(uint), out partHi, ht ) ) { value = (((ulong)partHi << 32) | (ulong)partLo); return true; } value = 0; return false; } //--// internal void Synchronize( ImageInformation imageInformation , Emulation.Hosting.AbstractHost host ) { if(m_imageInformation != imageInformation || m_host != host ) { m_imageInformation = imageInformation; m_host = host; host.GetHostingService( out m_mem ); m_snapshot = HashTableFactory.New< uint, Cluster >(); CopyPreviousValues(); } } private void CopyPreviousValues() { m_snapshotPrevious = m_snapshot; } //--// public TS.TypeRepresentation LocateType( ref uint address ) { IR.ImageBuilders.SequentialRegion reg; uint offset; reg = m_imageInformation.FindRegion( address - sizeof(uint), out offset ); if(reg != null) { IR.DataManager.DataDescriptor dd = reg.Context as IR.DataManager.DataDescriptor; if(dd != null) { address = reg.ExternalAddress; return dd.Context; } else { foreach(IR.ImageBuilders.ImageAnnotation an in reg.AnnotationList) { if(an.Offset == offset && an.Target is TS.FieldRepresentation) { TS.FieldRepresentation fd = (TS.FieldRepresentation)an.Target; return fd.FieldType; } } } } return null; } public TS.TypeRepresentation LookForVirtualTable( uint address ) { uint addressHeader = m_imageInformation.GetVirtualTablePointerAddress( address ); if(addressHeader != 0) { uint vTableAddress; bool fChanged; if(GetUInt32( addressHeader, false, out vTableAddress, out fChanged )) { return m_imageInformation.GetTypeFromVirtualTable( vTableAddress ); } } return null; } public string ExtractString( uint address ) { return m_imageInformation.GetStringFromMemory( this, address ); } // // Access Methods // public ImageInformation ImageInformation { get { return m_imageInformation; } } public Emulation.Hosting.AbstractHost Host { get { return m_host; } } } } ================================================ FILE: Zelig/Zelig/DebugTime/Debugger/Execution/PerformanceCounter.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // namespace Microsoft.Zelig.Debugger.ArmProcessor { using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Text; using System.IO; using System.Windows.Forms; using System.Threading; using EncDef = Microsoft.Zelig.TargetModel.ArmProcessor.EncodingDefinition; using InstructionSet = Microsoft.Zelig.TargetModel.ArmProcessor.InstructionSet; using IR = Microsoft.Zelig.CodeGeneration.IR; using RT = Microsoft.Zelig.Runtime; using TS = Microsoft.Zelig.Runtime.TypeSystem; public struct PerformanceCounter { // // State // public uint Hits; public ulong TotalTime; // // Helper Methods // public void Fetch( ImageInformation.PointerContext pc ) { if(pc != null) { ImageInformation.PointerContext pcHits = pc.AccessField( "m_hits" ); if(pcHits != null) { this.Hits = (uint)pcHits.Value; } ImageInformation.PointerContext pcTime = pc.AccessField( "m_total" ); if(pcTime != null) { this.TotalTime = (ulong)pcTime.Value; } } } } } ================================================ FILE: Zelig/Zelig/DebugTime/Debugger/Execution/ProcessorHost.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // namespace Microsoft.Zelig.Debugger.ArmProcessor { using System; using System.Collections.Generic; using System.Text; using System.IO; using System.Drawing; using System.Drawing.Imaging; using System.Threading; using System.Windows.Forms; using System.Runtime.CompilerServices; using Microsoft.Zelig.TargetModel.ArmProcessor; using Microsoft.Zelig.CodeGeneration.IR.Abstractions; using EncDef = Microsoft.Zelig.TargetModel.ArmProcessor.EncodingDefinition_ARM; using Cfg = Microsoft.Zelig.Configuration.Environment; using IR = Microsoft.Zelig.CodeGeneration.IR; public class ProcessorHost : Emulation.Hosting.AbstractHost { class MemoryDeltaHolder : IDisposable { // // State // ProcessorHost m_host; // // Constructor Methods // internal MemoryDeltaHolder( ProcessorHost host ) { m_host = host; lock(m_host) { foreach(var memDelta in m_host.m_notifyOnEnteringExecuting.ToArray()) { memDelta.EnteringExecuting(); } } } // // Helper Methods // public void Dispose() { lock(m_host) { foreach(var memDelta in m_host.m_notifyOnExitingRunning.ToArray()) { memDelta.ExitingRunning(); } } } } class SimulatorControlImpl : Emulation.Hosting.SimulatorControl { // // State // ProcessorHost m_host; // // Constructor Methods // internal SimulatorControlImpl( ProcessorHost host ) { m_host = host; m_host.RegisterService( typeof(Emulation.Hosting.SimulatorControl), this ); } // // Helper Methods // public override void Wait( TimeSpan tm ) { double span = tm.TotalMilliseconds; int val = (span > 0 && span < int.MaxValue) ? (int)span : int.MaxValue; if(val > 100) { val = 100; } m_host.m_implHalEvents.m_systemEvent.WaitOne( val, false ); } } //--// class HalButtonsImpl : Emulation.Hosting.HalButtons { struct ButtonRecord { // // State // internal uint m_buttonsPressed; internal uint m_buttonsReleased; } // // State // ProcessorHost m_host; Queue m_buttonQueue = new Queue(); // // Constructor Methods // internal HalButtonsImpl( ProcessorHost host ) { m_host = host; m_host.RegisterService( typeof(Emulation.Hosting.HalButtons), this ); } // // Helper Methods // public override bool GetNextStateChange( out uint buttonsPressed , out uint buttonsReleased ) { lock(this) { if(m_buttonQueue.Count > 0) { ButtonRecord br = m_buttonQueue.Dequeue(); buttonsPressed = br.m_buttonsPressed; buttonsReleased = br.m_buttonsReleased; return true; } buttonsPressed = 0; buttonsReleased = 0; return false; } } public override void QueueNextStateChange( uint buttonsPressed , uint buttonsReleased ) { lock(this) { ButtonRecord br; br.m_buttonsPressed = buttonsPressed; br.m_buttonsReleased = buttonsReleased; m_buttonQueue.Enqueue( br ); m_host.m_implHalEvents.Set( Emulation.Hosting.HalEvents.SYSTEM_EVENT_FLAG_BUTTON ); } } } //--// class HalEventsImpl : Emulation.Hosting.HalEvents { // // State // private ProcessorHost m_host; internal AutoResetEvent m_systemEvent = new AutoResetEvent( false ); internal uint m_systemFlags = 0; // // Constructor Methods // internal HalEventsImpl( ProcessorHost host ) { m_host = host; m_host.RegisterService( typeof(Emulation.Hosting.HalEvents), this ); } // // Helper Methods // public override void Clear( uint mask ) { lock(this) { m_systemFlags &= ~mask; } } public override void Set( uint mask ) { lock(this) { m_systemFlags |= mask; m_systemEvent.Set(); } } public override uint Get( uint mask ) { lock(this) { uint res = m_systemFlags & mask; m_systemFlags &= ~mask; return res; } } public override uint MaskedRead( uint mask ) { lock(this) { return m_systemFlags & mask; } } } //--// // // State // DebuggerMainForm m_owner; Emulation.Hosting.AbstractEngine m_activeEngine; Dictionary m_engines; List< Emulation.Hosting.Breakpoint > m_breakpoints; SimulatorControlImpl m_implSimulatorControl; HalButtonsImpl m_implHalButtons; HalEventsImpl m_implHalEvents; MemoryDelta m_memoryDelta; List< MemoryDelta > m_notifyOnEnteringExecuting; List< MemoryDelta > m_notifyOnExitingRunning; uint m_softBreakpointTableAddress; // // Constructor Methods // public ProcessorHost( DebuggerMainForm owner ) { this.RegisterService( typeof(Emulation.Hosting.AbstractHost), this ); this.RegisterService( typeof(ProcessorHost ), this ); //--// m_owner = owner; m_engines = new Dictionary< Type, Emulation.Hosting.AbstractEngine >(); m_breakpoints = new List< Emulation.Hosting.Breakpoint >(); m_implSimulatorControl = new SimulatorControlImpl( this ); m_implHalButtons = new HalButtonsImpl ( this ); m_implHalEvents = new HalEventsImpl ( this ); m_notifyOnEnteringExecuting = new List< MemoryDelta >(); m_notifyOnExitingRunning = new List< MemoryDelta >(); } public void SelectEngine(Cfg.EngineCategory category, InstructionSet iset) { m_softBreakpointTableAddress = 0; this.Unlink( m_activeEngine ); bool match = false; if(m_engines.TryGetValue(category.GetType(), out m_activeEngine) == true) { if(m_activeEngine.InstructionSet == iset) { match = true; } else { m_engines.Remove(category.GetType()); } } if(!match) { m_activeEngine = category.Instantiate(iset) as Emulation.Hosting.AbstractEngine; if(m_activeEngine == null) { throw TypeConsistencyErrorException.Create("Unrecognized engine: {0}", category); } m_engines[category.GetType()] = m_activeEngine; } this.Link( m_activeEngine ); //--// m_breakpoints.Clear(); } // // Helper Methods // internal bool GetAbsoluteTime( out ulong clockTicks , out ulong nanoseconds ) { Emulation.Hosting.DeviceClockTicksTracking svc; GetHostingService( out svc ); if(svc == null) { clockTicks = 0; nanoseconds = 0; return false; } return svc.GetAbsoluteTime( out clockTicks, out nanoseconds ); } public void Execute( ImageInformation imageInformation , Cfg.ProductCategory product ) { ExecuteInner( imageInformation, product, false ); } public void ExecuteStep( ImageInformation imageInformation , Cfg.ProductCategory product ) { ExecuteInner( imageInformation, product, true ); } void ExecuteInner( ImageInformation imageInformation , Cfg.ProductCategory product , bool fSingleStep ) { Emulation.Hosting.ProcessorStatus svcPS; this.GetHostingService( out svcPS ); Emulation.Hosting.ProcessorControl svcPC; this.GetHostingService( out svcPC ); Emulation.Hosting.MemoryProvider svcMP; this.GetHostingService( out svcMP ); Emulation.Hosting.JTagConnector svcJTAG; this.GetHostingService( out svcJTAG ); var lst = new List< Emulation.Hosting.Breakpoint >(); object softBreakpointOpcode; int maxHardBreakpoints; svcPC.GetBreakpointCapabilities( out softBreakpointOpcode, out maxHardBreakpoints ); var cleanup = HashTableFactory.New< uint, uint >(); while(true) { lst.Clear(); uint pc = svcPS.ProgramCounter; bool fStep = fSingleStep; foreach(var bp in m_breakpoints) { fStep |= bp.ShouldStopOverStatement( pc ); bp.SetAs = Emulation.Hosting.Breakpoint.Status.NotSet; } cleanup.Clear(); for(int pass = 0; pass < 3; pass++) { bool fForceHardware = (pass == 0); bool fIncludeOptional = (pass == 2); foreach(var bp in m_breakpoints) { if(bp.IsActive && bp.ShouldIgnoreOnce == false && bp.ShouldImplementInHardware == fForceHardware && bp.IsOptional == fIncludeOptional ) { uint address = bp.Address; if(bp.ShouldImplementInHardware == false) { if(product != null && softBreakpointOpcode is uint) { var mem = product.FindMemory( address ); if(mem != null && mem.IsRAM) { if(cleanup.ContainsKey( address ) == false) { uint val; if(svcMP.GetUInt32( address, out val )) { uint expectedVal; if(imageInformation.TryReadUInt32FromPhysicalImage( address, out expectedVal ) && expectedVal == val) { cleanup[address] = val; svcMP.SetUInt32( address, (uint)softBreakpointOpcode ); bp.SetAs = Emulation.Hosting.Breakpoint.Status.SoftBreakpoint; continue; } } } } } } if(lst.Count < maxHardBreakpoints) { lst.Add( bp ); bp.SetAs = Emulation.Hosting.Breakpoint.Status.HardBreakpoint; } } } } if(cleanup.Count > 0 && svcJTAG != null) { PublishSoftBreakpoints( imageInformation, product, svcMP, svcJTAG, cleanup ); FlushCache( imageInformation, product, svcMP, svcJTAG ); } //--// svcPC.StopExecution = false; if(fStep) { svcPC.ExecuteStep( lst ); } else { svcPC.Execute( lst ); } if(cleanup.Count > 0) { FlushSoftBreakpoints( svcMP ); foreach(uint address in cleanup.Keys) { svcMP.SetUInt32( address, cleanup[address] ); } } pc = svcPS.ProgramCounter; Emulation.Hosting.Breakpoint.Response res = Emulation.Hosting.Breakpoint.Response.DoNothing; foreach(var bp in m_breakpoints.ToArray()) { if(bp.IsActive && bp.ShouldIgnoreOnce == false ) { if(bp.Address == pc) { res |= bp.Hit(); } } bp.ClearIgnoreFlag(); } if(fSingleStep) { break; } if((res & Emulation.Hosting.Breakpoint.Response.StopExecution) != 0) { break; } if((res & Emulation.Hosting.Breakpoint.Response.NextInstruction) != 0) { continue; } if(fStep) { continue; } break; } RemoveTemporaryBreakpoints(); } private void PublishSoftBreakpoints( ImageInformation imageInformation , Cfg.ProductCategory product , Emulation.Hosting.MemoryProvider svcMP , Emulation.Hosting.JTagConnector svcJTAG , GrowOnlyHashTable< uint, uint > cleanup ) { if(m_softBreakpointTableAddress == 0) { var md = imageInformation.TypeSystem.TryGetHandler( Runtime.DebuggerHook.GetSoftBreakpointTable ); if(md != null) { var reg = imageInformation.ResolveMethodToRegion( md ); if(reg != null) { var mem = product.FindAnyBootstrapRAM(); if(mem != null) { uint blockEnd = mem.EndAddress; uint blockStart = blockEnd - 128; byte[] oldState; svcMP.GetBlock( blockStart, 128, 4, out oldState ); var input = new [] { new Emulation.Hosting.JTagConnector.RegisterSet { Name = "CPSR" , Value = EncDef.c_psr_I | EncDef.c_psr_F | EncDef.c_psr_mode_SVC }, new Emulation.Hosting.JTagConnector.RegisterSet { Name = "PC" , Value = reg.ExternalAddress }, new Emulation.Hosting.JTagConnector.RegisterSet { Name = "Svc_R13", Value = blockEnd }, }; var output = new [] { new Emulation.Hosting.JTagConnector.RegisterSet { Name = "R0" }, }; svcJTAG.ExecuteCode( 1000, input, output ); svcMP.SetBlock( blockStart, oldState, 4 ); if(output[0].Value is uint) { m_softBreakpointTableAddress = (uint)output[0].Value; } } } } } if(m_softBreakpointTableAddress != 0) { uint len; if(svcMP.GetUInt32( m_softBreakpointTableAddress, out len )) { uint pos = 0; foreach(var address in cleanup.Keys) { if(pos < len) { svcMP.SetUInt32( m_softBreakpointTableAddress + sizeof(uint) + pos * 8 , address ); svcMP.SetUInt32( m_softBreakpointTableAddress + sizeof(uint) + pos * 8 + 4, cleanup[address] ); } pos++; } } } } private void FlushSoftBreakpoints( Emulation.Hosting.MemoryProvider svcMP ) { if(m_softBreakpointTableAddress != 0) { uint len; if(svcMP.GetUInt32( m_softBreakpointTableAddress, out len )) { if(len > 0) { svcMP.SetUInt32( m_softBreakpointTableAddress + sizeof(uint), 0 ); } } } } private static void FlushCache( ImageInformation imageInformation , Cfg.ProductCategory product , Emulation.Hosting.MemoryProvider svcMP , Emulation.Hosting.JTagConnector svcJTAG ) { var md = imageInformation.TypeSystem.TryGetHandler( Runtime.DebuggerHook.FlushInstructionCache ); if(md != null) { var reg = imageInformation.ResolveMethodToRegion( md ); if(reg != null) { var mem = product.FindAnyBootstrapRAM(); if(mem != null) { uint blockEnd = mem.EndAddress; uint blockStart = blockEnd - 128; byte[] oldState; svcMP.GetBlock( blockStart, 128, 4, out oldState ); var input = new [] { new Emulation.Hosting.JTagConnector.RegisterSet { Name = "CPSR" , Value = EncDef.c_psr_I | EncDef.c_psr_F | EncDef.c_psr_mode_SVC }, new Emulation.Hosting.JTagConnector.RegisterSet { Name = "PC" , Value = reg.ExternalAddress }, new Emulation.Hosting.JTagConnector.RegisterSet { Name = "Svc_R13", Value = blockEnd }, }; svcJTAG.ExecuteCode( 1000, input, null ); svcMP.SetBlock( blockStart, oldState, 4 ); } } } } //--// internal void RegisterForNotification( MemoryDelta memDelta , bool fEntering , bool fExiting ) { if(fEntering) { if(m_notifyOnEnteringExecuting.Contains( memDelta ) == false) { m_notifyOnEnteringExecuting.Add( memDelta ); } } if(fExiting) { if(m_notifyOnExitingRunning.Contains( memDelta ) == false) { m_notifyOnExitingRunning.Add( memDelta ); } } } internal void UnregisterForNotification( MemoryDelta memDelta , bool fEntering , bool fExiting ) { if(fEntering) { m_notifyOnEnteringExecuting.Remove( memDelta ); } if(fExiting) { m_notifyOnExitingRunning.Remove( memDelta ); } } public IDisposable SuspendMemoryDeltaUpdates() { return new MemoryDeltaHolder( this ); } //--// private void RemoveTemporaryBreakpoints() { for(int pos = m_breakpoints.Count; --pos >= 0; ) { Emulation.Hosting.Breakpoint bp = m_breakpoints[pos]; if(bp.IsTemporary) { m_breakpoints.RemoveAt( pos ); } } } public Emulation.Hosting.Breakpoint CreateBreakpoint( uint address , Debugging.DebugInfo di , Emulation.Hosting.Breakpoint.Callback target ) { foreach(var bp in m_breakpoints) { if(bp.Address == address && bp.DebugInfo == di && bp.Target == target ) { return bp; } } var bpNew = new Emulation.Hosting.Breakpoint( address, di, target ); m_breakpoints.Add( bpNew ); return bpNew; } public void RestoreBreakpoint( Emulation.Hosting.Breakpoint bp ) { m_breakpoints.Remove( bp ); m_breakpoints.Add ( bp ); } public void RemoveBreakpoint( Emulation.Hosting.Breakpoint bp ) { m_breakpoints.Remove( bp ); } // // Access Methods // public Emulation.Hosting.Breakpoint[] Breakpoints { get { return m_breakpoints.ToArray(); } } public MemoryDelta MemoryDelta { get { lock(this) { if(m_memoryDelta == null) { m_memoryDelta = new MemoryDelta( m_owner.ImageInformation, this ); RegisterForNotification( m_memoryDelta, true, true ); } else { m_memoryDelta.Synchronize( m_owner.ImageInformation, this ); } } return m_memoryDelta; } } } } ================================================ FILE: Zelig/Zelig/DebugTime/Debugger/Execution/Profiler.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // namespace Microsoft.Zelig.Debugger.ArmProcessor { using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Text; using System.IO; using System.Windows.Forms; using System.Threading; using EncDef = Microsoft.Zelig.TargetModel.ArmProcessor.EncodingDefinition; using EncDef_VFP = Microsoft.Zelig.TargetModel.ArmProcessor.EncodingDefinition_VFP; using InstructionSet = Microsoft.Zelig.TargetModel.ArmProcessor.InstructionSet; using IR = Microsoft.Zelig.CodeGeneration.IR; using RT = Microsoft.Zelig.Runtime; using TS = Microsoft.Zelig.Runtime.TypeSystem; using Cfg = Microsoft.Zelig.Configuration.Environment; public class Profiler { public class AllocationEntry { // // State // public readonly CallEntry Context; public readonly ulong AbsoluteClockTicks; public readonly TS.TypeRepresentation Type; public readonly int ArraySize; // // Constructor Methods // internal AllocationEntry( CallEntry context , ulong absoluteClockTicks , TS.TypeRepresentation type , int arraySize ) { this.Context = context; this.Type = type; this.AbsoluteClockTicks = absoluteClockTicks; this.ArraySize = arraySize; } // // Helper Methods // //--// public int TotalByteSize { get { var vtbl = this.Type.VirtualTable; return (int)(vtbl.BaseSize + vtbl.ElementSize * this.ArraySize); } } } public class CallEntry { // // State // public readonly ThreadContext Owner; public readonly TS.MethodRepresentation Method; public readonly CallEntry Parent; public CallList Children; public AllocationList MemoryAllocations; public ulong AbsoluteClockCycles; public long InclusiveClockCycles; public long InclusiveWaitStates; internal ulong m_startCycles; internal ulong m_startWaitStates; internal bool m_visited; // // Constructor Methods // public CallEntry( ThreadContext tc , CallEntry parent , TS.MethodRepresentation method ) { this.Owner = tc; this.Method = method; this.Parent = parent; if(parent != null) { tc.Push( this ); } } // // Helper Methods // internal void AddSubCall( CallEntry en ) { var lst = this.Children; if(lst == null) { lst = new CallList(); this.Children = lst; } lst.Add( en ); } internal IEnumerable< CallEntry > EnumerateChildren() { var lst = this.Children; if(lst != null) { foreach(var en in lst) { yield return en; foreach(var enSub in en.EnumerateChildren()) { yield return enSub; } } } } internal void ResetVisitedFlag() { m_visited = false; var lst = this.Children; if(lst != null) { foreach(var en in lst) { en.ResetVisitedFlag(); } } } internal long ComputeExactInclusiveClockCycles() { if(m_visited) { return 0; } m_visited = true; long res = this.ExclusiveClockCycles; if(this.Children != null) { foreach(var sub in this.Children) { res += sub.ComputeExactInclusiveClockCycles(); } } return res; } internal long ComputeExactAllocatedBytes() { if(m_visited) { return 0; } m_visited = true; long res = this.ExclusiveAllocatedBytes; if(this.Children != null) { foreach(var sub in this.Children) { res += sub.ComputeExactAllocatedBytes(); } } return res; } // // Access Methods // public int Depth { get { int res = 0; var en = this; while((en = en.Parent) != null) { res++; } return res; } } public long ExclusiveClockCycles { get { long res = this.InclusiveClockCycles; if(this.Children != null) { foreach(var sub in this.Children) { res -= sub.InclusiveClockCycles; } } return res; } } public long ExclusiveWaitStates { get { long res = this.InclusiveWaitStates; if(this.Children != null) { foreach(var sub in this.Children) { res -= sub.InclusiveWaitStates; } } return res; } } public long InclusiveAllocatedBytes { get { long total = this.ExclusiveAllocatedBytes; if(this.Children != null) { foreach(var sub in this.Children) { total += sub.InclusiveAllocatedBytes; } } return total; } } public long ExclusiveAllocatedBytes { get { long total = 0; int headerSize = this.Owner.m_owner.m_objectHeaderSize; if(this.MemoryAllocations != null) { foreach(var memAlloc in this.MemoryAllocations) { total += memAlloc.TotalByteSize + headerSize; } } return total; } } // // Debug Methods // public override string ToString() { return string.Format( "[Thread:{0}] {1}{2}: {3} clock cycles [{4} exclusive] - {5} bytes allocated", this.Owner.ManagedThreadId, new string( ' ', this.Depth + 1 ), this.Method.ToShortString(), this.InclusiveClockCycles, this.ExclusiveClockCycles, this.InclusiveAllocatedBytes ); } } public class ThreadContext { // // State // internal readonly Profiler m_owner; private CallEntry m_activeEntry; public readonly int ManagedThreadId; public readonly ThreadStatus.Kind ThreadKind; public readonly CallEntry TopLevel; // // Constructor Methods // internal ThreadContext( Profiler owner , int id , ThreadStatus.Kind kind ) { m_owner = owner; this.ManagedThreadId = id; this.ThreadKind = kind; this.TopLevel = new CallEntry( this, null, null ); m_activeEntry = this.TopLevel; } // // Helper Methods // internal void Activate() { var perf = m_owner.m_svcPerf; if(perf != null) { ulong cycles = perf.ClockCycles; ulong waitStates = perf.WaitStates; for(var en = this.ActiveEntry; en != null; en = en.Parent) { en.m_startCycles = cycles; en.m_startWaitStates = waitStates; } } } internal void Deactivate() { var perf = m_owner.m_svcPerf; if(perf != null) { ulong cycles = perf.ClockCycles; ulong waitStates = perf.WaitStates; for(var en = this.ActiveEntry; en != null; en = en.Parent) { en.InclusiveClockCycles += (long)(cycles - en.m_startCycles ); en.InclusiveWaitStates += (long)(waitStates - en.m_startWaitStates); } } } internal void Push( CallEntry en ) { m_activeEntry.AddSubCall( en ); m_activeEntry = en; var perf = m_owner.m_svcPerf; if(perf != null) { ulong cycles = perf.ClockCycles; ulong waitStates = perf.WaitStates; en.AbsoluteClockCycles = cycles; en.m_startCycles = cycles; en.m_startWaitStates = waitStates; } } internal void Pop() { if(this.IsActive) { var en = m_activeEntry; m_activeEntry = en.Parent; var perf = m_owner.m_svcPerf; if(perf != null) { ulong cycles = perf.ClockCycles; ulong waitStates = perf.WaitStates; en.InclusiveClockCycles += (long)(cycles - en.m_startCycles ); en.InclusiveWaitStates += (long)(waitStates - en.m_startWaitStates); } } } internal void AddAllocation( TS.TypeRepresentation td , int arraySize ) { var perf = m_owner.m_svcPerf; ulong cycles = (perf != null) ? perf.ClockCycles : 0; //--// var en = this.ActiveEntry; var mat = en.MemoryAllocations; if(mat == null) { mat = new AllocationList(); en.MemoryAllocations = mat; } mat.Add( new AllocationEntry( en, cycles, td, arraySize ) ); } // // Access Methods // public CallEntry ActiveEntry { get { return m_activeEntry; } } public bool IsActive { get { return this.ActiveEntry != this.TopLevel; } } } //--// public class CallList : GrowOnlyList< CallEntry > { // // Helper Methods // public long ComputeExactInclusiveClockCycles() { foreach(var en in this) { en.ResetVisitedFlag(); } long res = 0; foreach(var en in this) { res += en.ComputeExactInclusiveClockCycles(); } return res; } public long ComputeExactAllocatedBytes() { foreach(var en in this) { en.ResetVisitedFlag(); } long res = 0; foreach(var en in this) { res += en.ComputeExactAllocatedBytes(); } return res; } // // Access Methods // public long ExclusiveClockCycles { get { long res = 0; foreach(var en in this) { res += en.ExclusiveClockCycles; } return res; } } public long InclusiveClockCycles { get { long res = 0; foreach(var en in this) { res += en.InclusiveClockCycles; } return res; } } public long AllocatedBytes { get { long res = 0; foreach(var en in this) { res += en.ExclusiveAllocatedBytes; } return res; } } } public class CallsByType : GrowOnlyHashTable< TS.TypeRepresentation, CallList > { // // Helper Method // internal void AddCall( CallEntry en ) { var td = en.Method.OwnerType; CallList coll; if(this.TryGetValue( td, out coll ) == false) { coll = new CallList(); this[td] = coll; } coll.Add( en ); } // // Access Methods // public long ExclusiveClockCycles { get { long res = 0; foreach(var md in this.Keys) { res += this[md].ExclusiveClockCycles; } return res; } } public long InclusiveClockCycles { get { long res = 0; foreach(var md in this.Keys) { res += this[md].InclusiveClockCycles; } return res; } } public long AllocatedBytes { get { long res = 0; foreach(var md in this.Keys) { res += this[md].AllocatedBytes; } return res; } } } public class CallsByMethod : GrowOnlyHashTable< TS.MethodRepresentation, CallList > { // // Helper Method // internal void AddCall( CallEntry en ) { var md = en.Method; CallList coll; if(this.TryGetValue( md, out coll ) == false) { coll = new CallList(); this[md] = coll; } coll.Add( en ); } // // Access Methods // public long TotalCalls { get { long res = 0; foreach(var key in this.Keys) { res += this[key].Count; } return res; } } public long ExclusiveClockCycles { get { long res = 0; foreach(var key in this.Keys) { res += this[key].ExclusiveClockCycles; } return res; } } public long InclusiveClockCycles { get { long res = 0; foreach(var key in this.Keys) { res += this[key].InclusiveClockCycles; } return res; } } public long AllocatedBytes { get { long res = 0; foreach(var td in this.Keys) { res += this[td].AllocatedBytes; } return res; } } } public class CallsByTypeAndMethod : GrowOnlyHashTable< TS.TypeRepresentation, CallsByMethod > { // // Helper Method // internal void AddCall( CallEntry en ) { var td = en.Method.OwnerType; CallsByMethod coll; if(this.TryGetValue( td, out coll ) == false) { coll = new CallsByMethod(); this[td] = coll; } coll.AddCall( en ); } } public class Callers : GrowOnlyHashTable< TS.MethodRepresentation, CallsByMethod > { // // Helper Method // internal void AddCall( CallEntry en ) { var md = en.Method; if(md != null) { var enParent = en.Parent; if(enParent != null && enParent.Method != null) { CallsByMethod coll; if(this.TryGetValue( md, out coll ) == false) { coll = new CallsByMethod(); this[md] = coll; } coll.AddCall( enParent ); } } } } public class Callees : GrowOnlyHashTable< TS.MethodRepresentation, CallsByMethod > { // // Helper Method // internal void AddCall( CallEntry en ) { if(en.Children != null) { var md = en.Method; if(md != null) { CallsByMethod coll; if(this.TryGetValue( md, out coll ) == false) { coll = new CallsByMethod(); this[md] = coll; } foreach(var child in en.Children) { coll.AddCall( child ); } } } } } public class CallsByMethodAndType : GrowOnlyHashTable< TS.MethodRepresentation, CallsByType > { // // Helper Method // internal void AddCall( CallEntry en ) { var md = en.Method; CallsByType coll; if(this.TryGetValue( md, out coll ) == false) { coll = new CallsByType(); this[md] = coll; } coll.AddCall( en ); } } //--// public class AllocationList : GrowOnlyList< AllocationEntry > { // // Access Methods // public long AllocatedBytes { get { long res = 0; foreach(var mem in this) { res += mem.TotalByteSize; } return res; } } public long AllocatedInstances { get { return this.Count; } } } public class AllocationsByType : GrowOnlyHashTable< TS.TypeRepresentation, AllocationList > { // // Helper Method // internal void AddAllocation( AllocationEntry en ) { var td = en.Type; AllocationList coll; if(this.TryGetValue( td, out coll ) == false) { coll = new AllocationList(); this[td] = coll; } coll.Add( en ); } // // Access Methods // public long AllocatedBytes { get { long res = 0; foreach(var td in this.Keys) { res += this[td].AllocatedBytes; } return res; } } } public class AllocationsByMethod : GrowOnlyHashTable< TS.MethodRepresentation, AllocationList > { // // Helper Method // internal void AddAllocation( AllocationEntry en ) { var md = en.Context.Method; AllocationList coll; if(this.TryGetValue( md, out coll ) == false) { coll = new AllocationList(); this[md] = coll; } coll.Add( en ); } // // Access Methods // public long AllocatedBytes { get { long res = 0; foreach(var md in this.Keys) { res += this[md].AllocatedBytes; } return res; } } public long AllocatedInstances { get { long res = 0; foreach(var md in this.Keys) { res += this[md].AllocatedInstances; } return res; } } } public class AllocationsByTypeAndMethod : GrowOnlyHashTable< TS.TypeRepresentation, AllocationsByMethod > { // // Helper Method // internal void AddAllocation( AllocationEntry en ) { var td = en.Type; AllocationsByMethod coll; if(this.TryGetValue( td, out coll ) == false) { coll = new AllocationsByMethod(); this[td] = coll; } coll.AddAllocation( en ); } // // Access Methods // public long AllocatedBytes { get { long res = 0; foreach(var td in this.Keys) { res += this[td].AllocatedBytes; } return res; } } public long AllocatedInstances { get { long res = 0; foreach(var td in this.Keys) { res += this[td].AllocatedInstances; } return res; } } } //--// // // State // private MemoryDelta m_memDelta; private Emulation.Hosting.Interop m_svcInterop; private Emulation.Hosting.ProcessorPerformance m_svcPerf; private Emulation.Hosting.ProcessorStatus m_svcStatus; private Dictionary< int, ThreadContext > m_threads; private ThreadContext m_activeContext; private List< Emulation.Hosting.Interop.Registration > m_interopsForCalls; private List< Emulation.Hosting.Interop.Registration > m_interopsForAllocations; private bool m_fCollectAllocationData; private bool m_fAttachedForCalls; private bool m_fAttachedForAllocations; private int m_objectHeaderSize; // // Constructor Methods // public Profiler( MemoryDelta memDelta ) { m_memDelta = memDelta; m_threads = new Dictionary< int, ThreadContext >(); m_interopsForCalls = new List< Emulation.Hosting.Interop.Registration >(); m_interopsForAllocations = new List< Emulation.Hosting.Interop.Registration >(); m_objectHeaderSize = (int)memDelta.ImageInformation.TypeSystem.WellKnownTypes.Microsoft_Zelig_Runtime_ObjectHeader.Size; } // // Helper Methods // internal IEnumerable< CallEntry > EnumerateCalls() { foreach(var tc in m_threads.Values) { foreach(var en in tc.TopLevel.EnumerateChildren()) { yield return en; } } } public CallsByTypeAndMethod GetCallsByType() { var res = new CallsByTypeAndMethod(); foreach(var en in this.EnumerateCalls()) { res.AddCall( en ); } return res; } public CallsByMethodAndType GetCallsByMethod() { var res = new CallsByMethodAndType(); foreach(var en in this.EnumerateCalls()) { res.AddCall( en ); } return res; } public void GetCallersAndCallees( out Callers callers , out Callees callees ) { callers = new Callers(); callees = new Callees(); foreach(var en in this.EnumerateCalls()) { callers.AddCall( en ); callees.AddCall( en ); } } public AllocationsByType GetAllocationsByType() { var res = new AllocationsByType(); foreach(var en in this.EnumerateCalls()) { if(en.MemoryAllocations != null) { foreach(var mem in en.MemoryAllocations) { res.AddAllocation( mem ); } } } return res; } public AllocationsByMethod GetAllocationsByMethod() { var res = new AllocationsByMethod(); foreach(var en in this.EnumerateCalls()) { if(en.MemoryAllocations != null) { foreach(var mem in en.MemoryAllocations) { res.AddAllocation( mem ); } } } return res; } public AllocationsByTypeAndMethod GetAllocationsByTypeAndMethod() { var res = new AllocationsByTypeAndMethod(); foreach(var en in this.EnumerateCalls()) { if(en.MemoryAllocations != null) { foreach(var mem in en.MemoryAllocations) { res.AddAllocation( mem ); } } } return res; } //--// public void Attach() { if(m_fAttachedForCalls == false) { var host = m_memDelta.Host; if(host.GetHostingService( out m_svcInterop ) && host.GetHostingService( out m_svcStatus ) ) { host.GetHostingService( out m_svcPerf ); Attach_Calls(); if(m_fCollectAllocationData) { Attach_Allocations(); } SwitchToNewThread(); } m_fAttachedForCalls = true; } } private void Attach_Calls() { m_svcStatus.NotifyOnExternalProgramFlowChange += Unwind; m_memDelta.ImageInformation.ImageBuilder.EnumerateImageAnnotations( an => { if(an.Target is Runtime.ActivationRecordEvents) { switch((Runtime.ActivationRecordEvents)an.Target) { case Runtime.ActivationRecordEvents.Constructing: AttachProfiler_Enter( an ); break; case Runtime.ActivationRecordEvents.ReturnToCaller: AttachProfiler_Exit( an ); break; case Runtime.ActivationRecordEvents.ReturnFromException: AttachProfiler_ExitFromException( an ); break; case Runtime.ActivationRecordEvents.LongJump: AttachProfiler_LongJump( an ); break; } } return true; } ); } private void Attach_Allocations() { if(m_fAttachedForAllocations == false) { var ts = m_memDelta.ImageInformation.TypeSystem; if(ts != null) { var wkm = ts.WellKnownMethods; SetInteropForVirtualMethod( ts, wkm.TypeSystemManager_AllocateObject, delegate() { RecordAllocation_Object( EncDef.c_register_r1 ); return Emulation.Hosting.Interop.CallbackResponse.DoNothing; } ); SetInteropForVirtualMethod( ts, wkm.TypeSystemManager_AllocateArray, delegate() { RecordAllocation_Array( EncDef.c_register_r1, EncDef.c_register_r2 ); return Emulation.Hosting.Interop.CallbackResponse.DoNothing; } ); SetInteropForVirtualMethod( ts, wkm.TypeSystemManager_AllocateArrayNoClear, delegate() { RecordAllocation_Array( EncDef.c_register_r1, EncDef.c_register_r2 ); return Emulation.Hosting.Interop.CallbackResponse.DoNothing; } ); SetInteropForVirtualMethod( ts, wkm.TypeSystemManager_AllocateString, delegate() { RecordAllocation_Array( EncDef.c_register_r1, EncDef.c_register_r2 ); return Emulation.Hosting.Interop.CallbackResponse.DoNothing; } ); } m_fAttachedForAllocations = true; } } private void RecordAllocation_Object( uint encodingVTable ) { var td = ExtractType( encodingVTable ); if(td != null) { m_activeContext.AddAllocation( td, 0 ); } } private void RecordAllocation_Array( uint encodingVTable , uint encodingLength ) { var td = ExtractType( encodingVTable ); if(td != null) { var bb = ReadRegister( encodingLength ); if(bb != null) { m_activeContext.AddAllocation( td, (int)bb.ReadUInt32( 0 ) ); } } } //--// public void Detach() { Detach_Allocations(); Detach_Calls(); if(m_activeContext != null) { m_activeContext.Deactivate(); m_activeContext = null; } } private void Detach_Calls() { if(m_fAttachedForCalls) { m_svcStatus.NotifyOnExternalProgramFlowChange -= Unwind; foreach(var reg in m_interopsForCalls) { m_svcInterop.RemoveInterop( reg ); } m_interopsForCalls.Clear(); m_fAttachedForCalls = false; } } private void Detach_Allocations() { if(m_fAttachedForAllocations) { foreach(var reg in m_interopsForAllocations) { m_svcInterop.RemoveInterop( reg ); } m_interopsForAllocations.Clear(); m_fAttachedForAllocations = false; } } //--// private TS.TypeRepresentation ExtractType( uint encoding ) { var bb = ReadRegister( EncDef.c_register_r1 ); if(bb != null) { uint vTablePtr = bb.ReadUInt32( 0 ); return m_memDelta.ImageInformation.GetTypeFromVirtualTable( vTablePtr ); } return null; } private Emulation.Hosting.BinaryBlob ReadRegister( uint encoding ) { return m_svcStatus.GetRegister( m_memDelta.ImageInformation.TypeSystem.PlatformAbstraction.GetRegisterForEncoding( encoding ) ); } private void SetInteropForCall( uint pc , bool fPostProcessing , Emulation.Hosting.Interop.Callback ftn ) { m_interopsForCalls.Add( m_svcInterop.SetInterop( pc, true, fPostProcessing, ftn ) ); } private void SetInteropForVirtualMethod( IR.TypeSystemForCodeTransformation ts , TS.MethodRepresentation md , Emulation.Hosting.Interop.Callback ftn ) { if(md is TS.VirtualMethodRepresentation) { for(TS.TypeRepresentation td = ts.FindSingleConcreteImplementation( md.OwnerType ); td != null; td = td.Extends) { TS.MethodRepresentation md2 = td.FindMatch( md, null ); if(md2 != null) { md = md2; break; } } } if(md != null) { IR.ImageBuilders.SequentialRegion reg = m_memDelta.ImageInformation.ResolveMethodToRegion( md ); if(reg != null) { m_interopsForAllocations.Add( m_svcInterop.SetInterop( reg.ExternalAddress, true, false, ftn ) ); } } } private CallEntry CreateNewEntry( TS.MethodRepresentation md ) { var en = new CallEntry( m_activeContext, m_activeContext.ActiveEntry, md ); return en; } private TS.MethodRepresentation GetMethod( IR.ImageBuilders.ImageAnnotation an ) { var bb = (IR.BasicBlock)an.Region.Context; return bb.Owner.Method; } private ThreadStatus AnalyzeStackFrame( out List< ThreadStatus > lst ) { StopTiming(); lst = new List< ThreadStatus >(); m_memDelta.FlushCache(); var ts = ThreadStatus.Analyze( lst, m_memDelta, null ); RestartTiming(); return ts; } private void SwitchToNewThread() { List< ThreadStatus > lst; var ts = AnalyzeStackFrame( out lst ); //--// if(m_activeContext != null) { m_activeContext.Deactivate(); } var tc = FindThread( ts ); if(tc == null) { int id = ts.ManagedThreadId; tc = new ThreadContext( this, id, ts.ThreadKind ); m_threads[id] = tc; } m_activeContext = tc; tc.Activate(); if(tc.IsActive == false) { var md = ts.TopMethod; // // If we switch to the beginning of a method, we don't need to create an entry, it will be created as part of the normal interop sequence. // if(ts.ProgramCounter != m_memDelta.ImageInformation.ResolveMethodToRegion( md ).ExternalAddress) { CreateNewEntry( ts.TopMethod ); } } } private void Unwind() { List< ThreadStatus > lst; var ts = AnalyzeStackFrame( out lst ); var md = ts.TopMethod; while(true) { var en = m_activeContext.ActiveEntry; if(en == m_activeContext.TopLevel) { break; } if(en.Method == md) { break; } m_activeContext.Pop(); } if(m_activeContext.IsActive == false) { CreateNewEntry( md ); } } private ThreadContext FindThread( ThreadStatus ts ) { ThreadContext res; m_threads.TryGetValue( ts.ManagedThreadId, out res ); return res; } private void StopTiming() { if(m_svcPerf != null) { m_svcPerf.SuspendTimingUpdates(); } } private void RestartTiming() { if(m_svcPerf != null) { m_svcPerf.ResumeTimingUpdates(); } } //--// private void AttachProfiler_Enter( IR.ImageBuilders.ImageAnnotation an ) { var md = GetMethod( an ); switch(m_memDelta.ImageInformation.TypeSystem.ExtractHardwareExceptionSettingsForMethod( md )) { case Runtime.HardwareException.UndefinedInstruction: case Runtime.HardwareException.PrefetchAbort : case Runtime.HardwareException.DataAbort : case Runtime.HardwareException.Interrupt : case Runtime.HardwareException.FastInterrupt : case Runtime.HardwareException.SoftwareInterrupt : SetInteropForCall( an.InsertionAddress, false, delegate() { SwitchToNewThread(); CreateNewEntry( md ); return Emulation.Hosting.Interop.CallbackResponse.DoNothing; } ); break; default: SetInteropForCall( an.InsertionAddress, false, delegate() { CreateNewEntry( md ); return Emulation.Hosting.Interop.CallbackResponse.DoNothing; } ); break; } } private void AttachProfiler_Exit( IR.ImageBuilders.ImageAnnotation an ) { SetInteropForCall( an.InsertionAddress, true, delegate() { m_activeContext.Pop(); return Emulation.Hosting.Interop.CallbackResponse.DoNothing; } ); } private void AttachProfiler_ExitFromException( IR.ImageBuilders.ImageAnnotation an ) { SetInteropForCall( an.InsertionAddress, true, delegate() { m_activeContext.Pop(); SwitchToNewThread(); return Emulation.Hosting.Interop.CallbackResponse.DoNothing; } ); } private void AttachProfiler_LongJump( IR.ImageBuilders.ImageAnnotation an ) { SetInteropForCall( an.InsertionAddress, true, delegate() { m_activeContext.Pop(); Unwind(); return Emulation.Hosting.Interop.CallbackResponse.DoNothing; } ); } // // Access Methods // public bool IsActive { get { return m_fAttachedForCalls; } } public bool CollectAllocationData { get { return m_fCollectAllocationData; } set { if(m_fCollectAllocationData != value) { m_fCollectAllocationData = value; if(m_fAttachedForCalls) { if(value) { Attach_Allocations(); } else { Detach_Allocations(); } } } } } public ThreadContext[] Threads { get { var values = m_threads.Values; var res = new ThreadContext[values.Count]; m_threads.Values.CopyTo( res, 0 ); return res; } } } } ================================================ FILE: Zelig/Zelig/DebugTime/Debugger/Execution/RegisterContext.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // namespace Microsoft.Zelig.Debugger.ArmProcessor { using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Text; using System.IO; using System.Windows.Forms; using System.Threading; using EncDef = Microsoft.Zelig.TargetModel.ArmProcessor.EncodingDefinition; using InstructionSet = Microsoft.Zelig.TargetModel.ArmProcessor.InstructionSet; using IR = Microsoft.Zelig.CodeGeneration.IR; using RT = Microsoft.Zelig.Runtime; using TS = Microsoft.Zelig.Runtime.TypeSystem; public class RegisterContext { public abstract class AbstractValue { // // State // protected readonly RegisterContext m_owner; public readonly IR.Abstractions.RegisterDescriptor Register; // // Constructor Methods // protected AbstractValue( RegisterContext owner , IR.Abstractions.RegisterDescriptor reg ) { this.m_owner = owner; this.Register = reg; } // // Helper Methods // internal abstract AbstractValue Clone( RegisterContext context ); public abstract Emulation.Hosting.BinaryBlob GetValue(); public abstract bool SetValue( Emulation.Hosting.BinaryBlob bb ); // // Access Methods // public bool IsAvailable { get { return m_owner.IsAvailable( this.Register ); } } public abstract bool CanUpdate { get; } } public class ValueInProcessorRegister : AbstractValue { // // State // private readonly GrowOnlyHashTable< uint, uint > m_physicalRegisterSet; // // Constructor Methods // internal ValueInProcessorRegister( RegisterContext owner , IR.Abstractions.RegisterDescriptor reg , GrowOnlyHashTable< uint, uint > physicalRegisterSet ) : base( owner, reg ) { m_physicalRegisterSet = physicalRegisterSet; } // // Helper Methods // internal override AbstractValue Clone( RegisterContext owner ) { return new ValueInProcessorRegister( owner, this.Register, m_physicalRegisterSet ); } //--// public override Emulation.Hosting.BinaryBlob GetValue() { var reg = this.Register; var bb = new Emulation.Hosting.BinaryBlob( (int)(reg.PhysicalStorageSize * sizeof(uint)) ); for(uint pos = 0; pos < reg.PhysicalStorageSize; pos++) { bb.WriteUInt32( m_physicalRegisterSet[reg.PhysicalStorageOffset + pos], (int)(pos * sizeof(uint)) ); } return bb; } public override bool SetValue( Emulation.Hosting.BinaryBlob bb ) { var reg = this.Register; for(uint pos = 0; pos < reg.PhysicalStorageSize; pos++) { m_physicalRegisterSet[reg.PhysicalStorageOffset + pos] = bb != null ? bb.ReadUInt32( (int)(pos * sizeof(uint)) ) : 0; } if(m_owner.m_svc != null) { m_owner.m_svc.SetRegister( reg, bb ); } return true; } // // Access Methods // public override bool CanUpdate { get { return this.IsAvailable; } } } public class ValueInMemory : AbstractValue { // // State // private readonly MemoryDelta m_memDelta; private readonly uint m_address; // // Constructor Methods // internal ValueInMemory( RegisterContext owner , IR.Abstractions.RegisterDescriptor reg , MemoryDelta memDelta , uint address ) : base( owner, reg ) { m_memDelta = memDelta; m_address = address; } // // Helper Methods // internal override AbstractValue Clone( RegisterContext owner ) { return new ValueInMemory( owner, this.Register, m_memDelta, m_address ); } //--// public override Emulation.Hosting.BinaryBlob GetValue() { var reg = this.Register; var bb = new Emulation.Hosting.BinaryBlob( (int)(reg.PhysicalStorageSize * sizeof(uint)) ); for(uint pos = 0; pos < reg.PhysicalStorageSize; pos++) { uint val; if(m_memDelta.GetUInt32( m_address + pos * sizeof(uint), out val ) == false) { return null; } bb.WriteUInt32( val, (int)(pos * sizeof(uint)) ); } return bb; } public override bool SetValue( Emulation.Hosting.BinaryBlob bb ) { var reg = this.Register; for(uint pos = 0; pos < reg.PhysicalStorageSize; pos++) { uint val = bb.ReadUInt32( (int)(pos * sizeof(uint)) ); if(m_memDelta.SetUInt32( m_address + pos * sizeof(uint), val ) == false) { return false; } } return true; } // // Access Methods // public override bool CanUpdate { get { return this.IsAvailable; } } } internal class RegisterValue_ReadOnly : AbstractValue { // // State // private readonly Emulation.Hosting.BinaryBlob m_bb; // // Constructor Methods // internal RegisterValue_ReadOnly( RegisterContext owner , IR.Abstractions.RegisterDescriptor reg , Emulation.Hosting.BinaryBlob bb ) : base( owner, reg ) { m_bb = bb; } // // Helper Methods // internal override AbstractValue Clone( RegisterContext owner ) { return new RegisterValue_ReadOnly( owner, this.Register, m_bb ); } //--// public override Emulation.Hosting.BinaryBlob GetValue() { return m_bb; } public override bool SetValue( Emulation.Hosting.BinaryBlob bb ) { return false; } // // Access Methods // public override bool CanUpdate { get { return false; } } } // // State // private readonly IR.TypeSystemForCodeTransformation m_typeSystem; private Emulation.Hosting.ProcessorStatus m_svc; private readonly IR.Abstractions.RegisterDescriptor[] m_registers; private readonly GrowOnlyHashTable< uint , uint > m_physicalRegisterSet; private readonly GrowOnlyHashTable< IR.Abstractions.RegisterDescriptor, AbstractValue > m_lookup; private readonly RegisterContext m_previousContext; // // Constructor Methods // public RegisterContext( IR.TypeSystemForCodeTransformation typeSystem ) { m_typeSystem = typeSystem; m_registers = typeSystem.PlatformAbstraction.GetRegisters(); m_physicalRegisterSet = HashTableFactory.New < uint , uint >(); m_lookup = HashTableFactory.NewWithReferenceEquality< IR.Abstractions.RegisterDescriptor, AbstractValue >(); foreach(var regDesc in m_registers) { for(uint pos = 0; pos < regDesc.PhysicalStorageSize; pos++) { m_physicalRegisterSet[regDesc.PhysicalStorageOffset + pos] = 0; } SetLocationInProcessor( regDesc ); } } public RegisterContext( RegisterContext other ) { m_typeSystem = other.m_typeSystem; m_svc = other.m_svc; m_registers = other.m_registers; m_physicalRegisterSet = other.m_physicalRegisterSet.Clone(); m_lookup = other.m_lookup .CloneSettings(); m_previousContext = other; foreach(var key in other.m_lookup.Keys) { m_lookup[key] = other.m_lookup[key].Clone( this ); } } // // Helper Methods // public void UpdateStackFrame( uint pc , uint sp ) { UpdateReadOnlyValue( this.InnerPC, pc ); UpdateReadOnlyValue( this.InnerSP, sp ); } private void UpdateReadOnlyValue( IR.Abstractions.RegisterDescriptor regDesc , uint value ) { m_lookup[regDesc] = new RegisterValue_ReadOnly( this, regDesc, Emulation.Hosting.BinaryBlob.Wrap( value ) ); } public void SetLocationInProcessor( IR.Abstractions.RegisterDescriptor regDesc ) { m_lookup[regDesc] = new ValueInProcessorRegister( this, regDesc, m_physicalRegisterSet ); } public void SetLocationInMemory( uint encoding , MemoryDelta memDelta , uint address ) { SetLocationInMemory( GetRegisterDescriptor( encoding ), memDelta, address ); } public void SetLocationInMemory( IR.Abstractions.RegisterDescriptor regDesc , MemoryDelta memDelta , uint address ) { m_lookup[regDesc] = new ValueInMemory( this, regDesc, memDelta, address ); } //--// public bool IsAvailable( IR.Abstractions.RegisterDescriptor regDesc ) { if(m_lookup.ContainsKey( regDesc ) == false) { return false; } // // Registers from top-level frames are always available. // if(m_previousContext == null) { return true; } if((regDesc.PhysicalClass & IR.Abstractions.RegisterClass.StatusRegister) != 0) { return false; } if(m_typeSystem.CallingConvention.ShouldSaveRegister( regDesc )) { if(regDesc.IsLinkAddress) { return false; } return true; } if(regDesc.IsSpecial) { return true; } return false; } //--// public uint GetValueAsUInt( uint encoding ) { return GetValueAsUInt( GetRegisterDescriptor( encoding ) ); } public uint GetValueAsUInt( IR.Abstractions.RegisterDescriptor regDesc ) { var av = GetValue( regDesc ); if(av != null) { var bb = av.GetValue(); if(bb != null) { return bb.ReadUInt32( 0 ); } } return 0; } //--// public AbstractValue GetValue( uint encoding ) { return GetValue( GetRegisterDescriptor( encoding ) ); } public AbstractValue GetValue( IR.Abstractions.RegisterDescriptor regDesc ) { AbstractValue val; m_lookup.TryGetValue( regDesc, out val ); return val; } //--// public bool SetValue( uint encoding , Emulation.Hosting.BinaryBlob bb ) { return SetValue( GetRegisterDescriptor( encoding ), bb ); } public bool SetValue( IR.Abstractions.RegisterDescriptor regDesc , Emulation.Hosting.BinaryBlob bb ) { AbstractValue val; if(m_lookup.TryGetValue( regDesc, out val )) { return val.SetValue( bb ); } return false; } //--// public static bool IsValueCompatible( IR.Abstractions.RegisterDescriptor regDesc , object value ) { if(regDesc == null) { return false; } if(regDesc.InFloatingPointRegisterFile) { if(regDesc.IsDoublePrecision) { if(!(value is double)) { return false; } } else { if(!(value is float)) { return false; } } } else { if(!(value is uint)) { return false; } } return true; } //--// public IR.Abstractions.RegisterDescriptor GetRegisterDescriptor( uint encoding ) { foreach(IR.Abstractions.RegisterDescriptor regDesc in m_registers) { if(regDesc.Encoding == encoding) { return regDesc; } } return null; } //--// // // Access Methods // internal Emulation.Hosting.ProcessorStatus ProcessorStatus { set { m_svc = value; } } public uint ProgramCounter { get { return GetValueAsUInt( this.InnerPC ); } } public uint StackPointer { get { return GetValueAsUInt( this.InnerSP ); } } public IR.Abstractions.RegisterDescriptor[] Keys { get { return m_registers; } } private IR.Abstractions.RegisterDescriptor InnerPC { get { foreach(IR.Abstractions.RegisterDescriptor regDesc in m_registers) { if((regDesc.PhysicalClass & IR.Abstractions.RegisterClass.ProgramCounter) != 0) { return regDesc; } } return null; } } private IR.Abstractions.RegisterDescriptor InnerSP { get { foreach(IR.Abstractions.RegisterDescriptor regDesc in m_registers) { if((regDesc.PhysicalClass & IR.Abstractions.RegisterClass.StackPointer) != 0) { return regDesc; } } return null; } } } } ================================================ FILE: Zelig/Zelig/DebugTime/Debugger/Execution/Session.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // namespace Microsoft.Zelig.Debugger.ArmProcessor { using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Text; using System.IO; using System.Windows.Forms; using System.Threading; using EncDef = Microsoft.Zelig.TargetModel.ArmProcessor.EncodingDefinition; using InstructionSet = Microsoft.Zelig.TargetModel.ArmProcessor.InstructionSet; using IR = Microsoft.Zelig.CodeGeneration.IR; using RT = Microsoft.Zelig.Runtime; using TS = Microsoft.Zelig.Runtime.TypeSystem; using Cfg = Microsoft.Zelig.Configuration.Environment; public class Session { // // State // public string m_settingsFile; public bool m_dirty; public bool m_temporary; public Guid m_id; public string m_displayName; public DateTime m_lastModified; public Cfg.EngineCategory m_selectedEngine; public Cfg.ProductCategory m_selectedProduct; public string m_imageToLoad; public bool m_displayDisassembly; public uint m_pastOpcodesToDisassembly = 5; public uint m_futureOpcodesToDisassembly = 5; // // Constructor Methods // public Session() { m_id = Guid.NewGuid(); m_lastModified = DateTime.Now; } public Session( Session session ) : this() { m_selectedEngine = session.m_selectedEngine; m_selectedProduct = session.m_selectedProduct; m_imageToLoad = session.m_imageToLoad; m_displayDisassembly = session.m_displayDisassembly; m_pastOpcodesToDisassembly = session.m_pastOpcodesToDisassembly; m_futureOpcodesToDisassembly = session.m_futureOpcodesToDisassembly; } // // Helper Methods // public byte[] ToArray() { using(MemoryStream stream = new MemoryStream()) { Save( stream ); return stream.ToArray(); } } public void Save( string file , bool fUpdate ) { using(Stream stream = new FileStream( file, FileMode.Create, FileAccess.Write )) { if(fUpdate) { m_settingsFile = file; } Save( stream ); } } public void Save( Stream stream ) { System.Xml.XmlDocument doc = new System.Xml.XmlDocument(); System.Xml.XmlElement root = XmlHelper.AddElement( doc, "Session" ); System.Xml.XmlElement node; XmlHelper.AddAttribute( root, "Id" , m_id ); XmlHelper.AddAttribute( root, "Name" , m_displayName ); XmlHelper.AddAttribute( root, "LastModified", m_lastModified ); XmlHelper.AddAttribute( root, "DisplayDisassembly" , m_displayDisassembly ); XmlHelper.AddAttribute( root, "PastOpcodesToDisassembly" , m_pastOpcodesToDisassembly ); XmlHelper.AddAttribute( root, "FutureOpcodesToDisassembly", m_futureOpcodesToDisassembly ); node = XmlHelper.AddElement( root, "Engine" ); Cfg.Manager.Serialize( node, m_selectedEngine ); node = XmlHelper.AddElement( root, "Product" ); Cfg.Manager.Serialize( node, m_selectedProduct ); node = XmlHelper.AddElement( root, "Image" ); XmlHelper.AddAttribute( node, "File", m_imageToLoad ); doc.Save( stream ); m_dirty = false; } //--// public static Session Load( string file ) { using(Stream stream = new FileStream( file, FileMode.Open, FileAccess.Read )) { Session session = new Session(); session.Load( stream ); return session; } } public static Session LoadAndSetOrigin( string file ) { Session session = Load( file ); session.SettingsFile = file; return session; } public static Session Load( byte[] blob ) { using(Stream stream = new MemoryStream( blob )) { Session session = new Session(); session.Load( stream ); return session; } } public void Load( Stream stream ) { System.Xml.XmlDocument doc = new System.Xml.XmlDocument(); System.Xml.XmlNode root; m_dirty = false; doc.Load( stream ); root = doc.SelectSingleNode( "Session" ); if(root != null) { m_id = XmlHelper .GetAttribute( root, "Id" , Guid.NewGuid() ); m_displayName = XmlHelper .GetAttribute( root, "Name" ); m_lastModified = XmlHelper .GetAttribute( root, "LastModified" , DateTime.Now ); m_displayDisassembly = XmlHelper .GetAttribute( root, "DisplayDisassembly" , false ); m_pastOpcodesToDisassembly = XmlHelper .GetAttribute( root, "PastOpcodesToDisassembly" , 5u ); m_futureOpcodesToDisassembly = XmlHelper .GetAttribute( root, "FutureOpcodesToDisassembly", 5u ); m_selectedEngine = (Cfg.EngineCategory )Cfg.Manager.Deserialize ( root.SelectSingleNode( "Engine" ) ); m_selectedProduct = (Cfg.ProductCategory)Cfg.Manager.Deserialize ( root.SelectSingleNode( "Product" ) ); m_imageToLoad = XmlHelper .GetAttribute( root.SelectSingleNode( "Image" ), "File" ); } } // // Access Methods // public string SettingsFile { get { return m_settingsFile; } set { m_settingsFile = value; this.Dirty = true; } } public bool Dirty { get { return m_dirty; } set { m_dirty = value; if(value) { m_lastModified = DateTime.Now; } } } public bool IsTemporary { get { return m_temporary; } set { m_temporary = value; if(m_temporary) { m_id = Guid.NewGuid(); } } } public Guid Id { get { return m_id; } } public string DisplayName { get { return m_displayName; } set { m_displayName = value; this.Dirty = true; } } public DateTime LastModified { get { return m_lastModified; } } public Cfg.EngineCategory SelectedEngine { get { return m_selectedEngine; } set { m_selectedEngine = value; this.Dirty = true; } } public Cfg.ProductCategory SelectedProduct { get { return m_selectedProduct; } set { m_selectedProduct = value; this.Dirty = true; } } public string ImageToLoad { get { return m_imageToLoad; } set { m_imageToLoad = value; this.Dirty = true; } } public bool DisplayDisassembly { get { return m_displayDisassembly; } set { m_displayDisassembly = value; this.Dirty = true; } } public uint PastOpcodesToDisassembly { get { return m_pastOpcodesToDisassembly; } } public uint FutureOpcodesToDisassembly { get { return m_futureOpcodesToDisassembly; } } } } ================================================ FILE: Zelig/Zelig/DebugTime/Debugger/Execution/StackFrame.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // namespace Microsoft.Zelig.Debugger.ArmProcessor { using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Text; using System.IO; using System.Windows.Forms; using System.Threading; using EncDef = Microsoft.Zelig.TargetModel.ArmProcessor.EncodingDefinition; using InstructionSet = Microsoft.Zelig.TargetModel.ArmProcessor.InstructionSet; using IR = Microsoft.Zelig.CodeGeneration.IR; using RT = Microsoft.Zelig.Runtime; using TS = Microsoft.Zelig.Runtime.TypeSystem; public class StackFrame { // // State // public ThreadStatus Thread; public int Depth; public TS.CodeMap CodeMapOfTarget; public RegisterContext RegisterContext; public IR.ImageBuilders.SequentialRegion Region; public uint RegionOffset; public List< Debugging.DebugInfo > DebugInfos; public int DebugInfoOffset; // // Helper Methods // public List< ImageInformation.DisassemblyLine > DisassembleBlock( MemoryDelta memDelta , uint pastOpcodesToDisassembly , uint futureOpcodesToDisassembly ) { var disasm = new List< ImageInformation.DisassemblyLine >(); var reg = this.Region; uint offset = this.RegionOffset; var imageInformation = memDelta.ImageInformation; var bb = reg.Context as IR.BasicBlock; if(bb != null) { uint address = reg.BaseAddress.ToUInt32() + offset; uint addressStart = FindBoundary( imageInformation, bb.Owner.Method, address, pastOpcodesToDisassembly , -sizeof(uint) ); uint addressEnd = FindBoundary( imageInformation, bb.Owner.Method, address, futureOpcodesToDisassembly, sizeof(uint) ) + sizeof(uint); disasm.Add( new ImageInformation.DisassemblyLine( uint.MaxValue, "{0} [BasicBlock #{1}]", bb.Owner.Method.ToShortString(), bb.SpanningTreeIndex ) ); imageInformation.DisassembleBlock( memDelta, disasm, addressStart, address, addressEnd ); } return disasm; } private static uint FindBoundary( ImageInformation imageInformation , TS.MethodRepresentation md , uint address , uint steps , int stepAmount ) { while(steps-- > 0) { uint nextAddress = (uint)(address + stepAmount); TS.CodeMap cm = imageInformation.ResolveAddressToCodeMap( nextAddress ); if(cm == null || cm.Target != md) { break; } address = nextAddress; } return address; } public bool AdvanceToNextDebugInfo() { if(this.DebugInfos != null && (this.DebugInfoOffset + 1) < this.DebugInfos.Count) { this.DebugInfoOffset++; return true; } return false; } public bool MoveForwardToDebugInfo( Debugging.DebugInfo debugInfo ) { if(debugInfo != null && this.DebugInfos != null) { for(int i = this.DebugInfoOffset + 1; i < this.DebugInfos.Count; i++) { if(this.DebugInfos[i] == debugInfo) { this.DebugInfoOffset = i; return true; } } } return false; } public void MoveToLastDebugInfo() { if(this.DebugInfos != null && this.DebugInfos.Count > 0) { this.DebugInfoOffset = this.DebugInfos.Count - 1; } } // // Access Methods // public uint ProgramCounter { get { return this.RegisterContext.ProgramCounter; } } public uint StackPointer { get { return this.RegisterContext.StackPointer; } } public TS.MethodRepresentation Method { get { var reg = this.Region; if(reg != null) { var bb = reg.Context as IR.BasicBlock; if(bb != null) { return bb.Owner.Method; } } return null; } } public Debugging.DebugInfo DebugInfo { get { if(this.DebugInfos != null && this.DebugInfoOffset < this.DebugInfos.Count) { return this.DebugInfos[ this.DebugInfoOffset ]; } return null; } } // // Debug Methods // public override string ToString() { var md = this.Method; if(md != null) { return md.ToShortString(); } var reg = this.Region; if(reg != null) { return string.Format( "0x{0:X8}", reg.ExternalAddress ); } return string.Format( "0x{0:X8}", this.ProgramCounter ); } } } ================================================ FILE: Zelig/Zelig/DebugTime/Debugger/Execution/ThreadStatus.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // namespace Microsoft.Zelig.Debugger.ArmProcessor { using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Text; using System.IO; using System.Windows.Forms; using System.Threading; using EncDef = Microsoft.Zelig.TargetModel.ArmProcessor.EncodingDefinition_ARM; using InstructionSet = Microsoft.Zelig.TargetModel.ArmProcessor.InstructionSet; using IR = Microsoft.Zelig.CodeGeneration.IR; using RT = Microsoft.Zelig.Runtime; using TS = Microsoft.Zelig.Runtime.TypeSystem; public class ThreadStatus { public enum Kind { Bootstrap , ApplicationThread , IdleThread , InterruptThread , FastInterruptThread, } // // State // public uint ProgramCounter; public uint StackPointer; public List< StackFrame > StackTrace = new List< StackFrame >(); public StackFrame StackFrame; public int ManagedThreadId = -1; public ImageInformation.PointerContext ThreadObject; public Kind ThreadKind; public TS.MethodRepresentation TopMethod; public PerformanceCounter ActiveTime; // // Constructor Methods // private ThreadStatus( MemoryDelta memDelta , Emulation.Hosting.Breakpoint[] breakpoints ) { Emulation.Hosting.ProcessorStatus svc; memDelta.Host.GetHostingService( out svc ); // // Get local copy of register state. // var regs = new RegisterContext( memDelta.ImageInformation.TypeSystem ); foreach(var reg in regs.Keys) { regs.SetValue( reg, svc.GetRegister( reg ) ); } // // Set the processor status property, so that register context updates are reflected in the actual processor state. // regs.ProcessorStatus = svc; FetchStackFrace( memDelta, breakpoints, regs ); var sf = this.TopStackFrame; if(sf != null) { this.TopMethod = sf.Method; } } private ThreadStatus( MemoryDelta memDelta , Emulation.Hosting.Breakpoint[] breakpoints , ImageInformation.PointerContext registersContext ) { // // Get local copy of register state. // var regs = new RegisterContext( memDelta.ImageInformation.TypeSystem ); foreach(var reg in regs.Keys) { string name; switch(reg.Encoding) { case EncDef.c_register_r0 : name = "R0" ; break; case EncDef.c_register_r1 : name = "R1" ; break; case EncDef.c_register_r2 : name = "R2" ; break; case EncDef.c_register_r3 : name = "R3" ; break; case EncDef.c_register_r4 : name = "R4" ; break; case EncDef.c_register_r5 : name = "R5" ; break; case EncDef.c_register_r6 : name = "R6" ; break; case EncDef.c_register_r7 : name = "R7" ; break; case EncDef.c_register_r8 : name = "R8" ; break; case EncDef.c_register_r9 : name = "R9" ; break; case EncDef.c_register_r10 : name = "R10" ; break; case EncDef.c_register_r11 : name = "R11" ; break; case EncDef.c_register_r12 : name = "R12" ; break; case EncDef.c_register_r13 : name = "SP" ; break; case EncDef.c_register_r14 : name = "LR" ; break; case EncDef.c_register_r15 : name = "PC" ; break; case EncDef.c_register_cpsr: name = "CPSR"; break; default: name = null ; break; } if(name != null) { ImageInformation.PointerContext pc = registersContext.AccessField( name ); if(pc != null && pc.Value is uint) { regs.SetLocationInMemory( reg, memDelta, pc.Address ); } } } FetchStackFrace( memDelta, breakpoints, regs ); } // // Helper Methods // private void FetchStackFrace( MemoryDelta memDelta , Emulation.Hosting.Breakpoint[] breakpoints , RegisterContext regs ) { this.ProgramCounter = regs.ProgramCounter; this.StackPointer = regs.StackPointer; memDelta.ImageInformation.FetchCurrentStackTrace( this.StackTrace, memDelta, breakpoints, regs ); this.StackFrame = this.TopStackFrame; foreach(StackFrame sf in this.StackTrace) { sf.Thread = this; } } public static ThreadStatus GetCurrent( MemoryDelta memDelta ) { return new ThreadStatus( memDelta, null ); } public static ThreadStatus Analyze( List< ThreadStatus > lst , MemoryDelta memDelta , Emulation.Hosting.Breakpoint[] breakpoints ) { var imageInformation = memDelta.ImageInformation; var tsActive = new ThreadStatus( memDelta, breakpoints ); tsActive.ThreadKind = Kind.Bootstrap; lst.Clear(); IR.TypeSystemForCodeTransformation typeSystem = imageInformation.TypeSystem; if(typeSystem != null) { ImageInformation.PointerContext pcThreadManager = imageInformation.ResolveSingleton( memDelta, typeSystem.WellKnownTypes.Microsoft_Zelig_Runtime_ThreadManager ); if(pcThreadManager != null) { ImageInformation.PointerContext pcAllThreads = pcThreadManager.AccessField( "m_allThreads" ); ImageInformation.PointerContext pcRunningThread = pcThreadManager.AccessField( "m_runningThread" ); ImageInformation.PointerContext pcIdleThread = pcThreadManager.AccessField( "m_idleThread" ); ImageInformation.PointerContext pcInterruptThread = pcThreadManager.AccessField( "m_interruptThread" ); ImageInformation.PointerContext pcFastInterruptThread = pcThreadManager.AccessField( "m_fastInterruptThread" ); PerformanceCounter deadTime = new PerformanceCounter(); deadTime.Fetch( pcThreadManager.AccessField( "m_deadThreadsTime" ) ); if(pcAllThreads != null) { ImageInformation.PointerContext pcHead = pcAllThreads.AccessField( "m_head" ); ImageInformation.PointerContext pcTail = pcAllThreads.AccessField( "m_tail" ); if(pcHead != null) { ImageInformation.PointerContext pcNode = pcHead.AccessField( "m_next" ); var regCtx = tsActive.TopStackFrame.RegisterContext; uint cpsr = regCtx.GetValueAsUInt( regCtx.GetRegisterDescriptor( EncDef.c_register_cpsr ) ); switch(cpsr & EncDef.c_psr_mode) { case EncDef.c_psr_mode_IRQ: pcRunningThread = pcInterruptThread; break; case EncDef.c_psr_mode_FIQ: pcRunningThread = pcFastInterruptThread; break; } while(pcNode != null && pcNode != pcTail) { ImageInformation.PointerContext pcThread = pcNode.AccessField( "m_target" ); if(pcThread != null) { ThreadStatus ts = null; if(pcThread == pcRunningThread) { ts = tsActive; } else { ImageInformation.PointerContext pcContext = pcThread.AccessField( "m_swappedOutContext" ); if(pcContext != null) { ImageInformation.PointerContext pcRegisters = pcContext.AccessField( "Registers" ); if(pcRegisters != null) { ts = new ThreadStatus( memDelta, null, pcRegisters ); } } } if(ts != null) { lst.Add( ts ); ts.ThreadObject = pcThread; var pcManagedThreadId = pcThread.AccessField( "m_managedThreadId" ); if(pcManagedThreadId != null) { var val = pcManagedThreadId.Value; if(val is int) { ts.ManagedThreadId = (int)val; } } ts.ActiveTime.Fetch( pcThread.AccessField( "m_activeTime" ) ); TS.CodeMap codeMap = imageInformation.ResolveAddressToCodeMap( ts.ProgramCounter ); if(codeMap != null) { ts.TopMethod = codeMap.Target; } if(pcThread == pcInterruptThread) { ts.ThreadKind = Kind.InterruptThread; } else if(pcThread == pcFastInterruptThread) { ts.ThreadKind = Kind.FastInterruptThread; } else if(pcThread == pcIdleThread) { ts.ThreadKind = Kind.IdleThread; } else { ts.ThreadKind = Kind.ApplicationThread; } } } pcNode = pcNode.AccessField( "m_next" ); } } } } } if(lst.Count == 0) { lst.Add( tsActive ); } return tsActive; } // // Access Methods // public StackFrame TopStackFrame { get { if(this.StackTrace.Count > 0) { return this.StackTrace[0]; } return null; } } public StackFrame PreviousStackFrame { get { StackFrame currentStackFrame = this.StackFrame; if(currentStackFrame != null) { foreach(StackFrame sf in this.StackTrace) { if(sf.Depth == currentStackFrame.Depth + 1) { return sf; } } } return null; } } // // Debug Methods // public override string ToString() { StringBuilder sb = new StringBuilder(); bool fFirst = true; foreach(StackFrame sf in this.StackTrace) { if(fFirst) { fFirst = false; } else { sb.Append( Environment.NewLine ); } sb.Append( sf ); } return sb.ToString(); } } } ================================================ FILE: Zelig/Zelig/DebugTime/Debugger/Execution/ValueHandles/AbstractValueHandle.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // namespace Microsoft.Zelig.Debugger.ArmProcessor { using System; using System.Collections.Generic; using IR = Microsoft.Zelig.CodeGeneration.IR; using RT = Microsoft.Zelig.Runtime; using TS = Microsoft.Zelig.Runtime.TypeSystem; public abstract class AbstractValueHandle { // // State // public readonly TS.TypeRepresentation Type; public readonly TS.CustomAttributeRepresentation MemoryMappedPeripheral; public readonly TS.CustomAttributeRepresentation MemoryMappedRegister; public readonly bool AsHoldingVariable; // // Contructor Methods // protected AbstractValueHandle( TS.TypeRepresentation type , TS.CustomAttributeRepresentation caMemoryMappedPeripheral , TS.CustomAttributeRepresentation caMemoryMappedRegister , bool fAsHoldingVariable ) { this.Type = AdjustTypeForScalars( type ); this.MemoryMappedPeripheral = caMemoryMappedPeripheral; this.MemoryMappedRegister = caMemoryMappedRegister; this.AsHoldingVariable = fAsHoldingVariable; } // // Helper Methods // public static TS.TypeRepresentation AdjustTypeForScalars( TS.TypeRepresentation td ) { var tdS = td as TS.ScalarTypeRepresentation; if(tdS != null) { return tdS; } if(td is TS.ValueTypeRepresentation) { // // Is this a value type with only one instance, scalar field? If so, display the value directly. // foreach(TS.FieldRepresentation fd in td.Fields) { if(fd is TS.InstanceFieldRepresentation) { if(tdS != null) { // // More than one field, fail. // return td; } tdS = fd.FieldType as TS.ScalarTypeRepresentation; if(tdS == null) { // // Not a scalar, fail. // return td; } if(fd.Offset != 0) { // // Not aligned, fail. // return td; } } } if(tdS != null) { return tdS; } } return td; } //--// public abstract bool IsEquivalent( AbstractValueHandle abstractValueHandle ); //--// public Emulation.Hosting.BinaryBlob Read( out bool fChanged ) { return Read( 0, this.Size, out fChanged ); } public abstract Emulation.Hosting.BinaryBlob Read( int offset , int count , out bool fChanged ); //--// public bool Write( Emulation.Hosting.BinaryBlob bb ) { return Write( bb, 0, this.Size ); } public abstract bool Write( Emulation.Hosting.BinaryBlob bb , int offset , int count ); //--// public virtual AbstractValueHandle AccessField( TS.InstanceFieldRepresentation fd , TS.CustomAttributeRepresentation caMemoryMappedPeripheral , TS.CustomAttributeRepresentation caMemoryMappedRegister ) { bool fAsHoldingVariable = (caMemoryMappedRegister == null); var fdType = fd.FieldType; uint size; if(fAsHoldingVariable) { size = fdType.SizeOfHoldingVariable; } else { if(fdType is TS.ArrayReferenceTypeRepresentation) { int len = caMemoryMappedRegister.GetNamedArg< int >( "Instances" ); size = fdType.ContainedType.Size * (uint)len; } else { size = fdType.Size; } } return new SlicedValueHandle( fd.FieldType, caMemoryMappedPeripheral, caMemoryMappedRegister, fAsHoldingVariable, this, fd.Offset, (int)size ); } public AbstractValueHandle AccessBitField( TS.InstanceFieldRepresentation fd , TS.CustomAttributeRepresentation caMemoryMappedPeripheral , TS.CustomAttributeRepresentation caMemoryMappedRegister , IR.BitFieldDefinition bfDef ) { return new BitFieldValueHandle( fd.FieldType, caMemoryMappedPeripheral, caMemoryMappedRegister, this, fd.OwnerType, bfDef ); } // // Access Methods // public virtual int Size { get { return (int)(this.AsHoldingVariable ? this.Type.SizeOfHoldingVariable: this.Type.Size); } } public abstract bool CanUpdate { get; } public abstract bool HasAddress { get; } public abstract uint Address { get; } } } ================================================ FILE: Zelig/Zelig/DebugTime/Debugger/Execution/ValueHandles/BitFieldValueHandle.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // namespace Microsoft.Zelig.Debugger.ArmProcessor { using System; using System.Collections.Generic; using IR = Microsoft.Zelig.CodeGeneration.IR; using RT = Microsoft.Zelig.Runtime; using TS = Microsoft.Zelig.Runtime.TypeSystem; internal sealed class BitFieldValueHandle : AbstractValueHandle { // // State // private readonly AbstractValueHandle m_value; private readonly TS.TypeRepresentation m_ownerType; private readonly IR.BitFieldDefinition m_bfDef; // // Contructor Methods // internal BitFieldValueHandle( TS.TypeRepresentation type , TS.CustomAttributeRepresentation caMemoryMappedPeripheral , TS.CustomAttributeRepresentation caMemoryMappedRegister , AbstractValueHandle value , TS.TypeRepresentation ownerType , IR.BitFieldDefinition bfDef ) : base( type, caMemoryMappedPeripheral, caMemoryMappedRegister, true ) { m_value = value; m_ownerType = ownerType; m_bfDef = bfDef; } // // Helper Methods // public override bool IsEquivalent( AbstractValueHandle abstractValueHandle ) { var other = abstractValueHandle as BitFieldValueHandle; if(other != null) { if(this.m_ownerType == other.m_ownerType && this.m_bfDef == other.m_bfDef ) { return this.m_value.IsEquivalent( other.m_value ); } } return false; } public override Emulation.Hosting.BinaryBlob Read( int offset , int count , out bool fChanged ) { ulong rebuiltValue; if(ExtractValue( out rebuiltValue, out fChanged ) == false) { return null; } var bbRebuiltValue = new Emulation.Hosting.BinaryBlob( (int)m_ownerType.Size ); bbRebuiltValue.WriteUInt64( rebuiltValue, 0 ); return bbRebuiltValue.Extract( offset, count ); } public override bool Write( Emulation.Hosting.BinaryBlob bb , int offset , int count ) { ulong rebuiltValue; bool fChanged; if(ExtractValue( out rebuiltValue, out fChanged ) == false) { return false; } var bbRebuiltValue = new Emulation.Hosting.BinaryBlob( (int)m_ownerType.Size ); bbRebuiltValue.WriteUInt64( rebuiltValue, 0 ); bbRebuiltValue.Insert( bb, offset, count ); ulong rebuildValueNew = bbRebuiltValue.ReadUInt64( 0 ); return InsertValue( rebuildValueNew ); } //--// private bool ExtractValue( out ulong value , out bool fChanged ) { value = 0; var bbOwner = m_value.Read( out fChanged ); if(bbOwner == null) { return false; } ulong rawValue = bbOwner.ReadUInt64( 0 ); ulong rebuiltValue = 0; foreach(var section in m_bfDef.Sections) { rebuiltValue |= ((rawValue >> (int)section.Position) & ((1ul << (int)section.Size) - 1)) << (int)section.Offset; } if(this.Type.IsSigned) { int unusedBits = (64 - (int)m_bfDef.TotalSize); long signedValue = (long)(rebuiltValue << unusedBits); rebuiltValue = (ulong)(signedValue >> unusedBits); } value = rebuiltValue; return true; } private bool InsertValue( ulong value ) { bool fChanged; var bbOwner = m_value.Read( out fChanged ); if(bbOwner == null) { return false; } ulong rawValue = bbOwner.ReadUInt64( 0 ); foreach(var section in m_bfDef.Sections) { ulong mask = ((1ul << (int)section.Size) - 1); rawValue &= ~( mask << (int)section.Position); rawValue |= ((value >> (int)section.Offset) & mask) << (int)section.Position ; } bbOwner.WriteUInt64( rawValue, 0 ); return m_value.Write( bbOwner ); } // // Access Methods // public override bool CanUpdate { get { return m_value.CanUpdate; } } public override bool HasAddress { get { return m_value.HasAddress; } } public override uint Address { get { return m_value.Address; } } } } ================================================ FILE: Zelig/Zelig/DebugTime/Debugger/Execution/ValueHandles/CompoundValueHandle.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // namespace Microsoft.Zelig.Debugger.ArmProcessor { using System; using System.Collections.Generic; using IR = Microsoft.Zelig.CodeGeneration.IR; using RT = Microsoft.Zelig.Runtime; using TS = Microsoft.Zelig.Runtime.TypeSystem; public sealed class CompoundValueHandle : AbstractValueHandle { public struct Fragment { // // State // public AbstractValueHandle Component; public int Offset; // // Contructor Methods // public Fragment( AbstractValueHandle component , int offset ) { this.Component = component; this.Offset = offset; } // // Helper Methods // internal bool IsEquivalent( ref Fragment other ) { if(this.Offset == other.Offset) { if(this.Component.IsEquivalent( other.Component )) { return true; } } return false; } internal bool Read( Emulation.Hosting.BinaryBlob bb , int offset , int count , out bool fChanged ) { if(this.Component == null) { fChanged = false; return false; } int start = Math.Max( offset , this.Offset ); int end = Math.Min( offset + count, this.Offset + this.Component.Size ); if(start >= end) { // // Non-overlapping regions. // fChanged = false; return true; } var bbSub = this.Component.Read( start - this.Offset, end - start, out fChanged ); if(bbSub != null) { bb.Insert( bbSub, start - offset ); return true; } return false; } internal bool Write( Emulation.Hosting.BinaryBlob bb , int offset , int count ) { if(this.Component == null) { return false; } int start = Math.Max( offset , this.Offset ); int end = Math.Min( offset + count, this.Offset + this.Component.Size ); if(start >= end) { // // Non-overlapping regions. // return true; } var bbSub = bb.Extract( start - offset, end - start ); return this.Component.Write( bbSub, start - this.Offset, end - start ); } } // // State // public readonly Fragment[] Fragments; // // Contructor Methods // public CompoundValueHandle( TS.TypeRepresentation type , bool fAsHoldingVariable , params Fragment[] fragments ) : base( type, null, null, fAsHoldingVariable ) { this.Fragments = fragments; } // // Helper Methods // public override bool IsEquivalent( AbstractValueHandle abstractValueHandle ) { var other = abstractValueHandle as CompoundValueHandle; if(other != null) { if(this.Fragments.Length == other.Fragments.Length) { for(int i = 0; i < this.Fragments.Length; i++) { if(this.Fragments[i].IsEquivalent( ref other.Fragments[i] ) == false) { return false; } } return true; } } return false; } public override Emulation.Hosting.BinaryBlob Read( int offset , int count , out bool fChanged ) { var bb = new Emulation.Hosting.BinaryBlob( count ); fChanged = false; foreach(var fragment in this.Fragments) { bool fChangedFragment; if(fragment.Read( bb, offset, count, out fChangedFragment ) == false) { return null; } fChanged |= fChangedFragment; } return bb; } public override bool Write( Emulation.Hosting.BinaryBlob bb , int offset , int count ) { foreach(var fragment in this.Fragments) { if(fragment.Write( bb, offset, count ) == false) { return false; } } return true; } public override AbstractValueHandle AccessField( TS.InstanceFieldRepresentation fd , TS.CustomAttributeRepresentation caMemoryMappedPeripheral , TS.CustomAttributeRepresentation caMemoryMappedRegister ) { int offset = fd.Offset; int size = (int)fd.FieldType.SizeOfHoldingVariable; foreach(var fragment in this.Fragments) { if(fragment.Offset == offset) { var subLoc = fragment.Component; if(subLoc != null && subLoc.Size == size) { return subLoc; } } } return base.AccessField( fd, caMemoryMappedPeripheral, caMemoryMappedRegister ); } // // Access Methods // public override bool CanUpdate { get { foreach(var fragment in this.Fragments) { if(fragment.Component == null) { return false; } if(fragment.Component.CanUpdate == false) { return false; } } return true; } } public override bool HasAddress { get { return false; } } public override uint Address { get { return 0; } } } } ================================================ FILE: Zelig/Zelig/DebugTime/Debugger/Execution/ValueHandles/MemoryValueHandle.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // namespace Microsoft.Zelig.Debugger.ArmProcessor { using System; using System.Collections.Generic; using IR = Microsoft.Zelig.CodeGeneration.IR; using RT = Microsoft.Zelig.Runtime; using TS = Microsoft.Zelig.Runtime.TypeSystem; public sealed class MemoryValueHandle : AbstractValueHandle { // // State // public readonly MemoryDelta MemoryDelta; private readonly uint m_address; // // Contructor Methods // public MemoryValueHandle( ImageInformation.PointerContext pc , bool fAsHoldingVariable ) : this( pc.Type, null, null, fAsHoldingVariable, pc.MemoryDelta, pc.Address ) { } public MemoryValueHandle( TS.TypeRepresentation type , TS.CustomAttributeRepresentation caMemoryMappedPeripheral , TS.CustomAttributeRepresentation caMemoryMappedRegister , bool fAsHoldingVariable , MemoryDelta memoryDelta , uint address ) : base( type, caMemoryMappedPeripheral, caMemoryMappedRegister, fAsHoldingVariable ) { this.MemoryDelta = memoryDelta; this.m_address = address; } // // Helper Methods // public override bool IsEquivalent( AbstractValueHandle abstractValueHandle ) { var other = abstractValueHandle as MemoryValueHandle; if(other != null) { if(this.m_address == other.m_address) { return true; } } return false; } public override Emulation.Hosting.BinaryBlob Read( int offset , int count , out bool fChanged ) { var memoryDelta = this.MemoryDelta; uint address = m_address + (uint)offset; switch(count) { case 1: { byte result; if(memoryDelta.GetUInt8( address, true, out result, out fChanged )) { return Emulation.Hosting.BinaryBlob.Wrap( result ); } } break; case 2: { ushort result; if(memoryDelta.GetUInt16( address, true, out result, out fChanged )) { return Emulation.Hosting.BinaryBlob.Wrap( result ); } } break; case 4: { uint result; if(memoryDelta.GetUInt32( address, true, out result, out fChanged )) { return Emulation.Hosting.BinaryBlob.Wrap( result ); } } break; case 8: { ulong result; if(memoryDelta.GetUInt64( address, true, out result, out fChanged )) { return Emulation.Hosting.BinaryBlob.Wrap( result ); } } break; default: { byte[] result; if(memoryDelta.GetBlock( address, count, true, out result, out fChanged )) { return new Emulation.Hosting.BinaryBlob( result ); } } break; } fChanged = false; return null; } public override bool Write( Microsoft.Zelig.Emulation.Hosting.BinaryBlob bb , int offset , int count ) { var memoryDelta = this.MemoryDelta; uint address = m_address + (uint)offset; switch(count) { case 1: { byte result = bb.ReadUInt8( 0 ); return memoryDelta.SetUInt8( address, result ); } case 2: { ushort result = bb.ReadUInt16( 0 ); return memoryDelta.SetUInt16( address, result ); } case 4: { uint result = bb.ReadUInt32( 0 ); return memoryDelta.SetUInt32( address, result ); } case 8: { ulong result = bb.ReadUInt64( 0 ); return memoryDelta.SetUInt64( address, result ); } default: { byte[] result = bb.ReadBlock( 0, count ); return memoryDelta.SetBlock( address, result ); } } } // // Access Methods // public override bool CanUpdate { get { foreach(var block in this.MemoryDelta.ImageInformation.ImageBuilder.MemoryBlocks) { if(block.Contains( this.Address )) { switch(block.Attributes & RT.MemoryAttributes.LocationMask) { case RT.MemoryAttributes.FLASH: case RT.MemoryAttributes.ROM: return false; } } } return true; } } public override bool HasAddress { get { return true; } } public override uint Address { get { return m_address; } } } } ================================================ FILE: Zelig/Zelig/DebugTime/Debugger/Execution/ValueHandles/RegisterValueHandle.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // namespace Microsoft.Zelig.Debugger.ArmProcessor { using System; using System.Collections.Generic; using IR = Microsoft.Zelig.CodeGeneration.IR; using RT = Microsoft.Zelig.Runtime; using TS = Microsoft.Zelig.Runtime.TypeSystem; public sealed class RegisterValueHandle : AbstractValueHandle { // // State // public readonly RegisterContext.AbstractValue RegisterValue; // // Contructor Methods // public RegisterValueHandle( RegisterContext.AbstractValue registerValue , TS.TypeRepresentation type , bool fAsHoldingVariable ) : base( type, null, null, fAsHoldingVariable ) { this.RegisterValue = registerValue; } // // Helper Methods // public override bool IsEquivalent( AbstractValueHandle abstractValueHandle ) { var other = abstractValueHandle as RegisterValueHandle; if(other != null) { if(this.RegisterValue.Register == other.RegisterValue.Register) { return true; } } return false; } public override Emulation.Hosting.BinaryBlob Read( int offset , int count , out bool fChanged ) { // // TODO: Move this to register context // fChanged = false; if(this.RegisterValue.IsAvailable == false) { return null; } var bb = this.RegisterValue.GetValue(); return bb.Extract( offset, count ); } public override bool Write( Emulation.Hosting.BinaryBlob bb , int offset , int count ) { var bbReg = this.RegisterValue.GetValue(); bbReg.Insert( bb, offset, count ); return this.RegisterValue.SetValue( bbReg ); } // // Access Methods // public override bool CanUpdate { get { return this.RegisterValue.CanUpdate; } } public override bool HasAddress { get { return false; } } public override uint Address { get { return 0; } } } } ================================================ FILE: Zelig/Zelig/DebugTime/Debugger/Execution/ValueHandles/SlicedValueHandle.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // namespace Microsoft.Zelig.Debugger.ArmProcessor { using System; using System.Collections.Generic; using IR = Microsoft.Zelig.CodeGeneration.IR; using RT = Microsoft.Zelig.Runtime; using TS = Microsoft.Zelig.Runtime.TypeSystem; internal sealed class SlicedValueHandle : AbstractValueHandle { // // State // private readonly AbstractValueHandle m_value; private readonly int m_offset; private readonly int m_count; // // Contructor Methods // internal SlicedValueHandle( TS.TypeRepresentation type , TS.CustomAttributeRepresentation caMemoryMappedPeripheral , TS.CustomAttributeRepresentation caMemoryMappedRegister , bool fAsHoldingVariable , AbstractValueHandle value , int offset , int count ) : base( type, caMemoryMappedPeripheral, caMemoryMappedRegister, fAsHoldingVariable ) { m_value = value; m_offset = offset; m_count = count; } // // Helper Methods // public override bool IsEquivalent( AbstractValueHandle abstractValueHandle ) { var other = abstractValueHandle as SlicedValueHandle; if(other != null) { if(this.m_offset == other.m_offset && this.m_count == other.m_count ) { return this.m_value.IsEquivalent( other.m_value ); } } return false; } public override Emulation.Hosting.BinaryBlob Read( int offset , int count , out bool fChanged ) { var bb = new Emulation.Hosting.BinaryBlob( count ); int offsetSub = offset + m_offset; int countSub = count; int start = Math.Max( offsetSub , m_offset ); int end = Math.Min( offsetSub + countSub, m_offset + m_count ); if(start >= end) { // // Non-overlapping regions. // fChanged = false; return null; } var bbSub = m_value.Read( start, end - start, out fChanged ); if(bbSub == null) { return null; } bb.Insert( bbSub, start - offsetSub ); return bb; } public override bool Write( Emulation.Hosting.BinaryBlob bb , int offset , int count ) { int offsetSub = offset + m_offset; int countSub = count; int start = Math.Max( offsetSub , m_offset ); int end = Math.Min( offsetSub + countSub, m_offset + m_count ); if(start >= end) { // // Non-overlapping regions. // return true; } var bbSub = bb.Extract( start - m_offset, end - start ); return m_value.Write( bbSub, start, end - start ); } // // Access Methods // public override bool CanUpdate { get { return m_value.CanUpdate; } } public override bool HasAddress { get { return m_value.HasAddress; } } public override uint Address { get { return (uint)(m_value.Address + m_offset); } } } } ================================================ FILE: Zelig/Zelig/DebugTime/Debugger/Execution/WatchHelper.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // namespace Microsoft.Zelig.Debugger.ArmProcessor { using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Text; using System.IO; using System.Windows.Forms; using System.Threading; using EncDef = Microsoft.Zelig.TargetModel.ArmProcessor.EncodingDefinition_ARM; using InstructionSet = Microsoft.Zelig.TargetModel.ArmProcessor.InstructionSet; using IR = Microsoft.Zelig.CodeGeneration.IR; using RT = Microsoft.Zelig.Runtime; using TS = Microsoft.Zelig.Runtime.TypeSystem; public class WatchHelper { public class PointerContext { // // State // private uint m_address; private TS.TypeRepresentation m_type; private bool m_fCheckVirtualTable; // // Constructor Methods // public PointerContext( uint address , TS.TypeRepresentation td , bool checkVirtualTable ) { m_address = address; m_type = td; m_fCheckVirtualTable = checkVirtualTable; } // // Helper Methods // public PointerContext FixType( MemoryDelta memoryDelta ) { uint address = m_address; TS.TypeRepresentation td = m_type ?? memoryDelta.LocateType( ref address ); if(m_fCheckVirtualTable) { if(td is TS.ReferenceTypeRepresentation) { TS.TypeRepresentation tdFromVtable = memoryDelta.LookForVirtualTable( address ); if(tdFromVtable != null) { td = tdFromVtable; } } } if(td == null) { td = memoryDelta.LookForVirtualTable( address ); } if(td == m_type && address == m_address) { return this; } return new PointerContext( address, td, false ); } // // Access Methods // public uint Address { get { return m_address; } set { m_address = value; } } public TS.TypeRepresentation Type { get { return m_type; } } public bool CheckVirtualTable { get { return m_fCheckVirtualTable; } } } //--// public sealed class ItemDescriptor { // // State // public readonly WatchHelper Owner; public readonly string Name; public readonly TS.TypeRepresentation Type; public AbstractValueHandle Location; private string m_valueText; private string m_typeDescriptor; private AbstractValueHandle m_subLocation; private bool m_fTopView; private TreeBasedGridView.GridNode m_node; // // Constructor Methods // public ItemDescriptor( WatchHelper owner , string name , TS.TypeRepresentation type , AbstractValueHandle location ) : this( owner, name, type, location, type.FullNameWithAbbreviation ) { } public ItemDescriptor( WatchHelper owner , string name , TS.TypeRepresentation type , AbstractValueHandle location , string typeDescriptor ) { this.Owner = owner; this.Name = name; this.Type = type; this.Location = location; m_typeDescriptor = typeDescriptor; m_fTopView = true; } // // Helper Methods // internal void AttachToView( TreeBasedGridView.GridNode parentNode , LinkedListNode< TreeBasedGridView.GridNode > anchor , Icon icon ) { bool fChanged; this.ConvertToText( out fChanged ); TreeBasedGridView.GridNode newNode; if(anchor != null) { newNode = anchor.Value.AddBefore( Name, m_valueText, m_typeDescriptor ); } else { newNode = parentNode.AddChild( Name, m_valueText, m_typeDescriptor ); } m_node = newNode; newNode.Tag = this; newNode.Icon = icon; newNode.HasChanged = fChanged; if(m_subLocation != null) { newNode.ExpandCallback = this.Owner.ExpandValue; } if(CanDisplayAsSingleItem( this.Type )) { var loc = this.Location; if(loc != null && loc.CanUpdate) { newNode.UpdateCallback = this.Owner.UpdateValue; } } } internal bool IsEquivalent( ItemDescriptor item ) { if(this.Name == item.Name && this.Type == item.Type ) { if(this.Location.IsEquivalent( item.Location )) { return true; } } return false; } internal void UpdateText() { bool fChanged; this.ConvertToText( out fChanged ); if(m_node != null) { m_node[1] = m_valueText; m_node.HasChanged = fChanged; } } internal void CollapseIfChanged() { if(m_node != null) { bool fChanged; var previousText = m_valueText; this.ConvertToText( out fChanged ); if(fChanged || previousText != m_valueText) { m_node.Invalidate(); m_node[1] = m_valueText; if(m_subLocation != null) { m_node.ExpandCallback = this.Owner.ExpandValue; } else { m_node.ExpandCallback = null; } } m_node.HasChanged = fChanged; } } //--// public void ConvertToText( out bool fChanged ) { m_subLocation = null; if(CanDisplayAsSingleItem( this.Type )) { var locReg = this.Location as RegisterValueHandle; if(locReg != null) { if((locReg.RegisterValue.Register.PhysicalClass & IR.Abstractions.RegisterClass.StatusRegister) != 0) { var bb = locReg.Read( out fChanged ); m_valueText = (bb == null) ? "" : DecodePSR( bb.ReadUInt32( 0 ) ); return; } } if(FormatItem( out fChanged ) == false) { if(locReg != null) { m_valueText = ""; } else { m_valueText = ""; } } return; } fChanged = false; m_subLocation = this.Location; return; } public bool ConvertFromText( string value ) { if(CanDisplayAsSingleItem( this.Type )) { var locReg = this.Location as RegisterValueHandle; if(locReg != null) { if((locReg.RegisterValue.Register.PhysicalClass & IR.Abstractions.RegisterClass.StatusRegister) != 0) { return false; } } if(ParseItem( value )) { return true; } } return false; } //--// private static string DecodePSR( uint psr ) { var sb = new StringBuilder(); sb.AppendFormat( "<{0}>", InstructionSet.DumpMode( psr ) ); if((psr & EncDef.c_psr_N) != 0) sb.Append( " N" ); if((psr & EncDef.c_psr_Z) != 0) sb.Append( " Z" ); if((psr & EncDef.c_psr_C) != 0) sb.Append( " C" ); if((psr & EncDef.c_psr_V) != 0) sb.Append( " V" ); if((psr & EncDef.c_psr_T) != 0) sb.Append( " " ); if((psr & EncDef.c_psr_F) != 0) sb.Append( " " ); if((psr & EncDef.c_psr_I) != 0) sb.Append( " " ); return sb.ToString(); } //--// private static bool CanDisplayAsSingleItem( TS.TypeRepresentation td ) { if(td.IsNumeric || td is TS.EnumerationTypeRepresentation) { return true; } if(td is TS.PointerTypeRepresentation || td is TS.BoxedValueTypeRepresentation ) { return true; } if(td is TS.ValueTypeRepresentation) { return false; } if(td is TS.ReferenceTypeRepresentation) { return true; } return false; } private bool ParseItem( string value ) { var td = this.Type; if(td is TS.EnumerationTypeRepresentation) { var tdEnum = (TS.EnumerationTypeRepresentation)td; var tdVal = tdEnum.UnderlyingType; if(!this.ShowHex) { //// var bb = this.Location.Read( out fChanged ); //// if(bb == null) //// { //// return false; //// } //// //// switch(tdVal.BuiltInType) //// { //// case TS.TypeRepresentation.BuiltInTypes.CHAR: FormatEnum( tdEnum, (char )bb.ReadUInt16( 0 ) ); return true; //// case TS.TypeRepresentation.BuiltInTypes.I1 : FormatEnum( tdEnum, (sbyte)bb.ReadUInt8 ( 0 ) ); return true; //// case TS.TypeRepresentation.BuiltInTypes.U1 : FormatEnum( tdEnum, bb.ReadUInt8 ( 0 ) ); return true; //// case TS.TypeRepresentation.BuiltInTypes.I2 : FormatEnum( tdEnum, (short)bb.ReadUInt16( 0 ) ); return true; //// case TS.TypeRepresentation.BuiltInTypes.U2 : FormatEnum( tdEnum, bb.ReadUInt16( 0 ) ); return true; //// case TS.TypeRepresentation.BuiltInTypes.I4 : FormatEnum( tdEnum, (int )bb.ReadUInt32( 0 ) ); return true; //// case TS.TypeRepresentation.BuiltInTypes.U4 : FormatEnum( tdEnum, bb.ReadUInt32( 0 ) ); return true; //// case TS.TypeRepresentation.BuiltInTypes.I8 : FormatEnum( tdEnum, (long )bb.ReadUInt64( 0 ) ); return true; //// case TS.TypeRepresentation.BuiltInTypes.U8 : FormatEnum( tdEnum, bb.ReadUInt64( 0 ) ); return true; //// } return false; } // // Fallback to scalar view. // td = tdVal; } value = value.Trim(); if(value.ToLower().StartsWith( "0x" )) { value = value.Substring( 2 ); if(td.IsNumeric) { switch(td.BuiltInType) { case TS.TypeRepresentation.BuiltInTypes.BOOLEAN: { uint val; if(uint.TryParse( value, System.Globalization.NumberStyles.HexNumber, null, out val )) { return WriteDirect( val ); } } break; case TS.TypeRepresentation.BuiltInTypes.CHAR: { ushort val; if(ushort.TryParse( value, System.Globalization.NumberStyles.HexNumber, null, out val )) { return WriteDirect( val ); } } break; case TS.TypeRepresentation.BuiltInTypes.I1: { sbyte val; if(sbyte.TryParse( value, System.Globalization.NumberStyles.HexNumber, null, out val )) { return WriteDirect( val ); } } break; case TS.TypeRepresentation.BuiltInTypes.U1: { byte val; if(byte.TryParse( value, System.Globalization.NumberStyles.HexNumber, null, out val )) { return WriteDirect( val ); } } break; case TS.TypeRepresentation.BuiltInTypes.I2: { short val; if(short.TryParse( value, System.Globalization.NumberStyles.HexNumber, null, out val )) { return WriteDirect( val ); } } break; case TS.TypeRepresentation.BuiltInTypes.U2: { ushort val; if(ushort.TryParse( value, System.Globalization.NumberStyles.HexNumber, null, out val )) { return WriteDirect( val ); } } break; case TS.TypeRepresentation.BuiltInTypes.I4: { int val; if(int.TryParse( value, System.Globalization.NumberStyles.HexNumber, null, out val )) { return WriteDirect( val ); } } break; case TS.TypeRepresentation.BuiltInTypes.U4: { uint val; if(uint.TryParse( value, System.Globalization.NumberStyles.HexNumber, null, out val )) { return WriteDirect( val ); } } break; case TS.TypeRepresentation.BuiltInTypes.I8: { long val; if(long.TryParse( value, System.Globalization.NumberStyles.HexNumber, null, out val )) { return WriteDirect( val ); } } break; case TS.TypeRepresentation.BuiltInTypes.U8: { ulong val; if(ulong.TryParse( value, System.Globalization.NumberStyles.HexNumber, null, out val )) { return WriteDirect( val ); } } break; case TS.TypeRepresentation.BuiltInTypes.R4: { uint val; if(uint.TryParse( value, System.Globalization.NumberStyles.HexNumber, null, out val )) { return WriteDirect( val ); } } break; case TS.TypeRepresentation.BuiltInTypes.R8: { ulong val; if(ulong.TryParse( value, System.Globalization.NumberStyles.HexNumber, null, out val )) { return WriteDirect( val ); } } break; case TS.TypeRepresentation.BuiltInTypes.I: case TS.TypeRepresentation.BuiltInTypes.U: { uint val; if(uint.TryParse( value, System.Globalization.NumberStyles.HexNumber, null, out val )) { return WriteDirect( val ); } } break; } return false; } if(td is TS.PointerTypeRepresentation || td is TS.BoxedValueTypeRepresentation || td is TS.ReferenceTypeRepresentation ) { uint val; if(uint.TryParse( value, System.Globalization.NumberStyles.HexNumber, null, out val )) { return WriteDirect( val ); } return false; } } else { if(td.IsNumeric) { switch(td.BuiltInType) { case TS.TypeRepresentation.BuiltInTypes.BOOLEAN: { bool val; if(bool.TryParse( value, out val )) { return WriteDirect( val ); } } break; case TS.TypeRepresentation.BuiltInTypes.CHAR: { char val; if(char.TryParse( value, out val )) { return WriteDirect( val ); } } break; case TS.TypeRepresentation.BuiltInTypes.I1: { sbyte val; if(sbyte.TryParse( value, out val )) { return WriteDirect( val ); } } break; case TS.TypeRepresentation.BuiltInTypes.U1: { byte val; if(byte.TryParse( value, out val )) { return WriteDirect( val ); } } break; case TS.TypeRepresentation.BuiltInTypes.I2: { short val; if(short.TryParse( value, out val )) { return WriteDirect( val ); } } break; case TS.TypeRepresentation.BuiltInTypes.U2: { ushort val; if(ushort.TryParse( value, out val )) { return WriteDirect( val ); } } break; case TS.TypeRepresentation.BuiltInTypes.I4: { int val; if(int.TryParse( value, out val )) { return WriteDirect( val ); } } break; case TS.TypeRepresentation.BuiltInTypes.U4: { uint val; if(uint.TryParse( value, out val )) { return WriteDirect( val ); } } break; case TS.TypeRepresentation.BuiltInTypes.I8: { long val; if(long.TryParse( value, out val )) { return WriteDirect( val ); } } break; case TS.TypeRepresentation.BuiltInTypes.U8: { ulong val; if(ulong.TryParse( value, out val )) { return WriteDirect( val ); } } break; case TS.TypeRepresentation.BuiltInTypes.R4: { float val; if(float.TryParse( value, out val )) { return WriteDirect( val ); } } break; case TS.TypeRepresentation.BuiltInTypes.R8: { double val; if(double.TryParse( value, out val )) { return WriteDirect( val ); } } break; } } } return false; } private bool WriteDirect( object val ) { return this.Location.Write( Emulation.Hosting.BinaryBlob.Wrap( val ) ); } private bool FormatItem( out bool fChanged ) { var td = this.Type; var loc = this.Location; if(td is TS.EnumerationTypeRepresentation) { var tdEnum = (TS.EnumerationTypeRepresentation)td; var tdVal = tdEnum.UnderlyingType; if(!this.ShowHex) { var bb = loc.Read( out fChanged ); if(bb == null) { return false; } switch(tdVal.BuiltInType) { case TS.TypeRepresentation.BuiltInTypes.CHAR: FormatEnum( tdEnum, (char )bb.ReadUInt16( 0 ) ); return true; case TS.TypeRepresentation.BuiltInTypes.I1 : FormatEnum( tdEnum, (sbyte)bb.ReadUInt8 ( 0 ) ); return true; case TS.TypeRepresentation.BuiltInTypes.U1 : FormatEnum( tdEnum, bb.ReadUInt8 ( 0 ) ); return true; case TS.TypeRepresentation.BuiltInTypes.I2 : FormatEnum( tdEnum, (short)bb.ReadUInt16( 0 ) ); return true; case TS.TypeRepresentation.BuiltInTypes.U2 : FormatEnum( tdEnum, bb.ReadUInt16( 0 ) ); return true; case TS.TypeRepresentation.BuiltInTypes.I4 : FormatEnum( tdEnum, (int )bb.ReadUInt32( 0 ) ); return true; case TS.TypeRepresentation.BuiltInTypes.U4 : FormatEnum( tdEnum, bb.ReadUInt32( 0 ) ); return true; case TS.TypeRepresentation.BuiltInTypes.I8 : FormatEnum( tdEnum, (long )bb.ReadUInt64( 0 ) ); return true; case TS.TypeRepresentation.BuiltInTypes.U8 : FormatEnum( tdEnum, bb.ReadUInt64( 0 ) ); return true; } } // // Fallback to scalar view. // td = tdVal; } if(td.IsNumeric) { var bb = loc.Read( out fChanged ); if(bb == null) { return false; } switch(td.BuiltInType) { case TS.TypeRepresentation.BuiltInTypes.BOOLEAN: { byte val = bb.ReadUInt8( 0 ); m_valueText = string.Format( this.ShowHex ? "0x{1:X2}" : "{0}", val != 0, val ); return true; } case TS.TypeRepresentation.BuiltInTypes.CHAR: { ushort val = bb.ReadUInt16( 0 ); m_valueText = string.Format( this.ShowHex ? "0x{1:X4}" : "'{0}' 0x{1:X4}", (char)val, val ); return true; } case TS.TypeRepresentation.BuiltInTypes.I1: { byte val = bb.ReadUInt8( 0 ); m_valueText = string.Format( this.ShowHex ? "0x{1:X2}" : "{0}", (sbyte)val, val ); return true; } case TS.TypeRepresentation.BuiltInTypes.U1: { byte val = bb.ReadUInt8( 0 ); m_valueText = string.Format( this.ShowHex ? "0x{1:X2}" : "{0}", val, val ); return true; } case TS.TypeRepresentation.BuiltInTypes.I2: { ushort val = bb.ReadUInt16( 0 ); m_valueText = string.Format( this.ShowHex ? "0x{1:X4}" : "{0}", (short)val, val ); return true; } case TS.TypeRepresentation.BuiltInTypes.U2: { ushort val = bb.ReadUInt16( 0 ); m_valueText = string.Format( this.ShowHex ? "0x{1:X4}" : "{0}", val, val ); return true; } case TS.TypeRepresentation.BuiltInTypes.I4: { uint val = bb.ReadUInt32( 0 ); m_valueText = string.Format( this.ShowHex ? "0x{1:X8}" : "{0}", (int)val, val ); return true; } case TS.TypeRepresentation.BuiltInTypes.U4: { uint val = bb.ReadUInt32( 0 ); m_valueText = string.Format( this.ShowHex ? "0x{1:X8}" : "{0}", val, val ); return true; } case TS.TypeRepresentation.BuiltInTypes.I8: { ulong val = bb.ReadUInt64( 0 ); m_valueText = string.Format( this.ShowHex ? "0x{1:X16}" : "{0}", (long)val, val ); return true; } case TS.TypeRepresentation.BuiltInTypes.U8: { ulong val = bb.ReadUInt64( 0 ); m_valueText = string.Format( this.ShowHex ? "0x{1:X16}" : "{0}", val, val ); return true; } case TS.TypeRepresentation.BuiltInTypes.R4: { uint val = bb.ReadUInt32( 0 ); m_valueText = string.Format( this.ShowHex ? "0x{1:X4}" : "{0} (0x{1:X8})", DataConversion.GetFloatFromBytes( val ), val ); return true; } case TS.TypeRepresentation.BuiltInTypes.R8: { ulong val = bb.ReadUInt64( 0 ); m_valueText = string.Format( this.ShowHex ? "0x{1:X16}" : "{0} (0x{1:X16})", DataConversion.GetDoubleFromBytes( val ), val ); return true; } case TS.TypeRepresentation.BuiltInTypes.I: case TS.TypeRepresentation.BuiltInTypes.U: { uint val = bb.ReadUInt32( 0 ); m_valueText = string.Format( "0x{0:X8}", val ); return true; } } m_valueText = ""; return false; } if(td is TS.PointerTypeRepresentation || td is TS.BoxedValueTypeRepresentation ) { var bb = loc.Read( out fChanged ); if(bb == null) { return false; } uint address = bb.ReadUInt32( 0 ); if(address == 0) { m_valueText = ""; return true; } m_valueText = string.Format( "0x{0:X8}", address ); m_subLocation = new MemoryValueHandle( td.UnderlyingType, null, null, false, this.Owner.MemoryDelta, address ); return true; } if(td is TS.ValueTypeRepresentation) { m_valueText = ""; m_subLocation = loc; fChanged = false; return true; } if(td is TS.ReferenceTypeRepresentation) { if(loc.MemoryMappedRegister != null) { m_subLocation = loc; fChanged = false; return true; } else { var bb = loc.Read( out fChanged ); if(bb == null) { return false; } uint address = bb.ReadUInt32( 0 ); if(address == 0 || address == 0xdeadbeef) { m_valueText = ""; return true; } td = FixType( td, ref address ); m_subLocation = new MemoryValueHandle( td, null, null, false, this.Owner.MemoryDelta, address ); if(td == this.Owner.ImageInformation.TypeSystem.WellKnownTypes.System_String) { m_valueText = this.Owner.MemoryDelta.ExtractString( address ); if(m_valueText != null) { m_valueText = '"' + m_valueText + '"'; return true; } } m_valueText = string.Format( "0x{0:X8}", address ); return true; } } m_valueText = ""; fChanged = false; return true; } public TS.TypeRepresentation FixType( TS.TypeRepresentation td , ref uint address ) { var memoryDelta = this.Owner.MemoryDelta; if(td == null) { td = memoryDelta.LocateType( ref address ); } if(td is TS.ReferenceTypeRepresentation && 0 == (td.ExpandedBuildTimeFlags & TS.TypeRepresentation.BuildTimeAttributes.NoVTable) ) { TS.TypeRepresentation tdFromVtable = memoryDelta.LookForVirtualTable( address ); if(tdFromVtable != null) { td = tdFromVtable; } } if(td == null) { td = memoryDelta.LookForVirtualTable( address ); } return td; } private void FormatEnum( TS.EnumerationTypeRepresentation td , object val ) { m_valueText = td.FormatValue( val ); } // // Access Methods // public string ValueText { get { return m_valueText; } } public string TypeDescriptor { get { return m_typeDescriptor; } set { m_typeDescriptor = value; } } public TreeBasedGridView.GridNode Node { get { return m_node; } } public AbstractValueHandle SubLocation { get { return m_subLocation; } set { m_subLocation = value; } } public bool IsTopView { get { return m_fTopView; } set { m_fTopView = value; } } public bool ShowHex { get { return this.Owner.HexadecimalDisplay; } } } // // State // const int MaxArrayDisplay = 32; public readonly ImageInformation ImageInformation; public readonly MemoryDelta MemoryDelta; public readonly TreeBasedGridView.GridNode RootNode; private bool m_fHexadecimalDisplay; private TreeBasedGridView.GridNode m_staticNode; private TreeBasedGridView.GridNode m_singletonNode; // // Constructor Methods // private WatchHelper( MemoryDelta memoryDelta , TreeBasedGridView.GridNode rootNode ) { this.ImageInformation = memoryDelta.ImageInformation; this.MemoryDelta = memoryDelta; this.RootNode = rootNode; } // // Helper Methods // public static void Synchronize( ref WatchHelper wh , MemoryDelta memoryDelta , TreeBasedGridView.GridNode rootNode , bool fAddStaticFields , bool fAddSingletonFields ) { var imageInformation = memoryDelta.ImageInformation; if(imageInformation == null) { rootNode.Clear(); wh = null; return; } if(wh == null || wh.ImageInformation != imageInformation || wh.RootNode != rootNode) { rootNode.Clear(); wh = new WatchHelper( memoryDelta, rootNode ); if(fAddStaticFields) { wh.AddStaticFields( wh.RootNode ); } if(fAddSingletonFields) { wh.AddSingletonFields( wh.RootNode ); } } } //--// public static void SetColumns( TreeBasedGridView treeBasedGridView ) { treeBasedGridView.SetColumns( new TreeBasedGridView.GridColumnDefinition( "Name" , DataGridViewContentAlignment.MiddleLeft, true , false, false ) , new TreeBasedGridView.GridColumnDefinition( "Value", DataGridViewContentAlignment.MiddleLeft, false, true , true ) , new TreeBasedGridView.GridColumnDefinition( "Type" , DataGridViewContentAlignment.MiddleLeft, false, false, false ) ); } static bool UpdateText( TreeBasedGridView.GridNode node ) { var item = node.Tag as ItemDescriptor; if(item != null) { item.UpdateText(); } return true; } static bool CollapseIfChanged( TreeBasedGridView.GridNode node ) { var item = node.Tag as ItemDescriptor; if(item != null) { item.CollapseIfChanged(); } return true; } //--// public void Update( List< ItemDescriptor > lst , bool fTryToPreserve ) { foreach(var node in this.RootNode.ArrayOfChildNodesNoPopulate) { if(node == m_staticNode ) continue; if(node == m_singletonNode) continue; bool fRemove = true; if(fTryToPreserve) { var item = node.Tag as ItemDescriptor; if(item != null) { foreach(var itemNew in lst) { if(item.IsEquivalent( itemNew )) { item.Location = itemNew.Location; lst.Remove( itemNew ); fRemove = false; break; } } } } if(fRemove) { node.Remove(); } } var anchor = this.RootNode.ChildNodesNoPopulate.First; foreach(var item in lst) { item.AttachToView( this.RootNode, anchor, Properties.Resources.LocalVariable ); } //--// var ctrl = this.RootNode.Owner; ctrl.StartTreeUpdate(); ctrl.EnumerateNodesPreOrder( CollapseIfChanged ); ctrl.EndTreeUpdate(); } //--// private void AddStaticFields( TreeBasedGridView.GridNode node ) { var exGlobalRoot = this.ImageInformation.TypeSystem.GlobalRoot; var pc = this.ImageInformation.ResolveCostantExpression( this.MemoryDelta, exGlobalRoot ); if(pc != null) { var set = SetFactory.NewWithReferenceEquality< TS.TypeRepresentation >(); foreach(TS.InstanceFieldRepresentation fd in exGlobalRoot.Type.Fields) { var fd2 = fd.ImplementationOf; if(fd2 != null) { set.Insert( fd2.OwnerType ); } } if(set.Count > 0) { var valHandleGlobalRoot = new MemoryValueHandle( pc, false ); m_staticNode = node.AddChild( "Static Fields", "", "" ); m_staticNode.Icon = Properties.Resources.StaticMembers; foreach(var td in set) { TreeBasedGridView.GridNode staticNode2 = m_staticNode.AddChild( td.FullNameWithAbbreviation, "", "" ); staticNode2.Icon = Properties.Resources.StaticMembers; foreach(TS.InstanceFieldRepresentation fd in exGlobalRoot.Type.Fields) { var fd2 = fd.ImplementationOf; if(fd2 != null && fd2.OwnerType == td) { AddField( staticNode2, valHandleGlobalRoot, fd, fd2.Name ); } } } } } } private void AddSingletonFields( TreeBasedGridView.GridNode node ) { var exGlobalRoot = this.ImageInformation.TypeSystem.GlobalRoot; var pc = this.ImageInformation.ResolveCostantExpression( this.MemoryDelta, exGlobalRoot ); if(pc != null) { var valHandleGlobalRoot = new MemoryValueHandle( pc, false ); foreach(TS.InstanceFieldRepresentation fd in exGlobalRoot.Type.Fields) { if(fd.ImplementationOf == null) { if(m_singletonNode == null) { m_singletonNode = node.AddChild( "Singletons", "", "" ); m_singletonNode.Icon = Properties.Resources.StaticMembers; } AddField( m_singletonNode, valHandleGlobalRoot, fd, fd.FieldType.FullNameWithAbbreviation ); } } } } //--// private bool UpdateValue( TreeBasedGridView.GridNode node , string proposedValue , int index ) { var item = (ItemDescriptor)node.Tag; if(index == 1) { if(item.ConvertFromText( proposedValue )) { item.CollapseIfChanged(); } } return false; } private void ExpandValue( TreeBasedGridView.GridNode node ) { var item = (ItemDescriptor)node.Tag; var loc = item.SubLocation; if(loc == null) { return; } TS.TypeRepresentation td = loc.Type; if(td is TS.ArrayReferenceTypeRepresentation) { if(loc.MemoryMappedRegister != null) { ExpandArray( node, item, td.ContainedType, 0, (uint)loc.MemoryMappedRegister.GetNamedArg< int >( "Instances" ) ); } else { bool fChanged; var bb = loc.Read( 0, sizeof(uint), out fChanged ); if(bb != null) { uint length = bb.ReadUInt32( 0 ); ExpandArray( node, item, td.ContainedType, 0, length ); } } } else { var exGlobalRoot = this.ImageInformation.TypeSystem.GlobalRoot; if(loc.HasAddress) { uint address = loc.Address; if(item.IsTopView) { uint addressFixed = address; var tdFixed = item.FixType( td, ref addressFixed ); if(tdFixed != td) { CreateSubView( node, string.Format( "[{0}]", tdFixed.FullNameWithAbbreviation ), addressFixed, tdFixed, loc.MemoryMappedPeripheral, loc.MemoryMappedRegister ); } } TS.TypeRepresentation tdExtends = td.Extends; if(tdExtends != null) { if(HasFieldsToDisplay( tdExtends, exGlobalRoot )) { CreateSubView( node, "Base Members", address, tdExtends, loc.MemoryMappedPeripheral, loc.MemoryMappedRegister ); } } } var pc = this.ImageInformation.ResolveCostantExpression( this.MemoryDelta, exGlobalRoot ); if(pc != null) { var valHandleGlobalRoot = new MemoryValueHandle( pc, false ); TreeBasedGridView.GridNode staticNode = null; foreach(TS.InstanceFieldRepresentation fd in exGlobalRoot.Type.Fields) { var fd2 = fd.ImplementationOf; if(fd2 != null && fd2.OwnerType == td) { if(staticNode == null) { staticNode = node.AddChild( "Static Members", "", "" ); staticNode.Icon = Properties.Resources.StaticMembers; } AddField( staticNode, valHandleGlobalRoot, fd, fd2.Name ); } } } bool fAddRawView = false; foreach(TS.FieldRepresentation fd in td.Fields) { var fd2 = fd as TS.InstanceFieldRepresentation; if(fd2 != null) { bool fIsBitField; AddField( node, loc, fd2, fd2.Name, out fIsBitField ); fAddRawView |= fIsBitField; } } if(fAddRawView) { var wkt = this.ImageInformation.TypeSystem.WellKnownTypes; TS.TypeRepresentation rawTd; switch(loc.Size) { case 1: rawTd = wkt.System_Byte; break; case 2: rawTd = wkt.System_UInt16; break; case 4: rawTd = wkt.System_UInt32; break; case 8: rawTd = wkt.System_UInt64; break; default: rawTd = null; break; } if(rawTd != null) { var rawLoc = new CompoundValueHandle( rawTd, false, new CompoundValueHandle.Fragment( loc, 0 ) ); var subItem = new ItemDescriptor( this, "[Raw Value]", rawLoc.Type, rawLoc ); subItem.AttachToView( node, null, Properties.Resources.StaticMembers ); } } } } private void CreateSubView( TreeBasedGridView.GridNode node , string text , uint address , TS.TypeRepresentation td , TS.CustomAttributeRepresentation caMemoryMappedPeripheral , TS.CustomAttributeRepresentation caMemoryMappedRegister ) { var subNode = node.AddChild( text, "", td.FullNameWithAbbreviation ); subNode.Icon = Properties.Resources.LocalVariable; subNode.ExpandCallback = this.ExpandValue; var valueHandle = new MemoryValueHandle( td, caMemoryMappedPeripheral, caMemoryMappedRegister, false, this.MemoryDelta, address ); var item = new ItemDescriptor( this, null, td, valueHandle ); item .SubLocation = valueHandle; item .IsTopView = false; subNode.Tag = item; } private void ExpandArray( TreeBasedGridView.GridNode node , ItemDescriptor item , TS.TypeRepresentation td , uint startIndex , uint endIndex ) { uint length = endIndex - startIndex; // // Protect against overflows. // length = Math.Min( length, uint.MaxValue / MaxArrayDisplay / 2 ); if(length > MaxArrayDisplay) { uint scale = MaxArrayDisplay; while(scale * MaxArrayDisplay < length) { scale *= MaxArrayDisplay; } for(uint pos = startIndex; pos < endIndex; pos += scale) { uint newStartIndex = pos; uint newEndIndex = Math.Min( pos + scale, endIndex ); var newNode = node.AddChild( string.Format( "[{0}-{1}]", newStartIndex, newEndIndex - 1 ), "...", "" ); newNode.Tag = item; newNode.ExpandCallback = (nodeSub => this.ExpandArray( nodeSub, item, td, newStartIndex, newEndIndex )); } } else { var loc = item.SubLocation; bool fAsHoldingVariable = (loc.MemoryMappedRegister == null); uint address = loc.Address; uint step; if(fAsHoldingVariable) { var fd = this.ImageInformation.TypeSystem.WellKnownFields.ArrayImpl_m_numElements; address += (uint)fd.Offset + fd.FieldType.SizeOfHoldingVariable; step = td.SizeOfHoldingVariable; } else { step = td.Size; } for(uint pos = startIndex; pos < endIndex; pos++) { var name = string.Format( "[{0}]", pos ); var valueHandle = new MemoryValueHandle( td, null, null, fAsHoldingVariable, this.MemoryDelta, address + pos * step ); var itemSub = new ItemDescriptor( this, name, td, valueHandle ); itemSub.AttachToView( node, null, Properties.Resources.LocalVariable ); } } } private static bool HasFieldsToDisplay( TS.TypeRepresentation td , IR.ConstantExpression exGlobalRoot ) { foreach(TS.InstanceFieldRepresentation fd in exGlobalRoot.Type.Fields) { var fd2 = fd.ImplementationOf; if(fd2 != null && fd2.OwnerType == td) { return true; } } foreach(TS.FieldRepresentation fd in td.Fields) { if(fd is TS.InstanceFieldRepresentation) { return true; } } TS.TypeRepresentation tdExtends = td.Extends; if(tdExtends != null) { if(HasFieldsToDisplay( tdExtends, exGlobalRoot )) { return true; } } return false; } private void AddField( TreeBasedGridView.GridNode node , AbstractValueHandle valHandle , TS.InstanceFieldRepresentation fd , string name ) { bool fIsBitField; AddField( node, valHandle, fd, name, out fIsBitField ); } private void AddField( TreeBasedGridView.GridNode node , AbstractValueHandle valHandle , TS.InstanceFieldRepresentation fd , string name , out bool fIsBitField ) { AbstractValueHandle subVal; Icon icon; IR.BitFieldDefinition bfDef; var ts = this.ImageInformation.TypeSystem; var caTd = ts.MemoryMappedPeripherals.GetValue( fd.OwnerType ); var caFd = ts.RegisterAttributes .GetValue( fd ); switch(fd.Flags & TS.FieldRepresentation.Attributes.FieldAccessMask) { case TS.FieldRepresentation.Attributes.Public: icon = Properties.Resources.PublicMember; break; default: icon = Properties.Resources.PrivateMember; break; } fIsBitField = ts.BitFieldRegisterAttributes.TryGetValue( fd, out bfDef ); if(fIsBitField) { subVal = valHandle.AccessBitField( fd, caTd, caFd, bfDef ); } else { subVal = valHandle.AccessField( fd, caTd, caFd ); } //--// var item = new ItemDescriptor( this, name, subVal.Type, subVal ); item.AttachToView( node, null, icon ); } // // Access Methods // public bool HexadecimalDisplay { get { return m_fHexadecimalDisplay; } set { if(m_fHexadecimalDisplay != value) { m_fHexadecimalDisplay = value; var ctrl = this.RootNode.Owner; ctrl.StartTreeUpdate(); ctrl.EnumerateNodesPreOrder( UpdateText ); ctrl.EndTreeUpdate(); } } } } } ================================================ FILE: Zelig/Zelig/DebugTime/Debugger/Forms/DebuggerMainForm.Actions.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // namespace Microsoft.Zelig.Debugger.ArmProcessor { using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Text; using System.IO; using System.Windows.Forms; using System.Threading; using IR = Microsoft.Zelig.CodeGeneration.IR; using RT = Microsoft.Zelig.Runtime; using TS = Microsoft.Zelig.Runtime.TypeSystem; using Cfg = Microsoft.Zelig.Configuration.Environment; using Hst = Microsoft.Zelig.Emulation.Hosting; using Microsoft.Zelig.TargetModel.ArmProcessor; using Microsoft.Zelig.CodeGeneration.IR.Abstractions; public partial class DebuggerMainForm : Form { // // Helper Methods // private void InnerAction_StopExecution() { Emulation.Hosting.ProcessorControl svcPC; if(m_processorHost.GetHostingService( out svcPC )) { svcPC.StopExecution = true; } } //--// private void InnerAction_SaveSession( string file ) { m_currentSession.Save( file, true ); } private void InnerAction_LoadSession( string file ) { m_currentSession = m_sessionManagerForm.LoadSession( file ); InnerAction_LoadImage(); } //--// private bool InnerAction_LoadImage() { if(m_currentSession == null) { return false; } if(string.IsNullOrEmpty( m_currentSession.ImageToLoad )) { return false; } InnerAction_SynchronousStopExecution(); string file = m_currentSession.ImageToLoad; ExecuteInWorkerThread( Hst.Forms.HostingSite.ExecutionState.Loading, delegate() { try { using(m_processorHost.SuspendMemoryDeltaUpdates()) { Emulation.Hosting.Breakpoint[] oldBreakpoints = null; if(m_imageInformation != null) { if(file == m_imageInformation.ImageFile) { oldBreakpoints = m_processorHost.Breakpoints; } else { m_imageInformation = null; } } if(m_imageInformation == null) { if(file.EndsWith( ".axfdump" )) { m_imageInformation = ImageInformation.LoadAdsImage( file ); } else if(file.EndsWith( ".hex" )) { m_imageInformation = ImageInformation.LoadHexImage( file ); } else { m_imageInformation = ImageInformation.LoadZeligImage( file, delegate( string format, object[] args ) { ExecuteInFormThread( delegate() { toolStripStatus_ExecutionState.Text = string.Format( format, args ); } ); } ); } } m_processorHost.RegisterService( typeof(ImageInformation), m_imageInformation ); //--// ExecuteInFormThread( delegate() { toolStripStatus_ExecutionState.Text = "Connecting to target..."; } ); InstructionSet iset = m_imageInformation.ImageBuilder.TypeSystem.PlatformAbstraction.GetInstructionSetProvider(); m_processorHost.SelectEngine(m_currentSession.SelectedEngine, iset); m_imageInformation.ApplyToProcessorHost( m_processorHost, m_currentSession.SelectedProduct ); ExecuteInFormThread( Hst.Forms.HostingSite.ExecutionState.Deploying, null ); m_imageInformation.DeployImage( m_processorHost, delegate( string format, object[] args ) { ExecuteInFormThread( delegate() { toolStripStatus_ExecutionState.Text = string.Format( format, args ); } ); } ); m_imageInformation.InitializePlugIns( m_processorHost, m_arguments.m_handlers ); if(DebugGC) { m_debugGC = new DebugGarbageColllection( new MemoryDelta( m_imageInformation, m_processorHost ), DebugGCVerbose ); } ExecuteInFormThread( Hst.Forms.HostingSite.ExecutionState.Loaded, delegate() { if(oldBreakpoints != null) { foreach(Emulation.Hosting.Breakpoint bp in oldBreakpoints) { m_processorHost.RestoreBreakpoint( bp ); } } if(m_imageInformation.TypeSystem != null) { //AddBreakpointOnDebugMethod( "TypeSystemManager_Throw" , null ); AddBreakpointOnDebugMethod( "TypeSystemManager_Rethrow__Exception" , null ); AddBreakpointOnDebugMethod( "ThreadImpl_ThrowNullException" , null ); AddBreakpointOnDebugMethod( "ThreadImpl_ThrowIndexOutOfRangeException", null ); AddBreakpointOnDebugMethod( "ThreadImpl_ThrowOverflowException" , null ); AddBreakpointOnDebugMethod( "ThreadImpl_ThrowNotImplementedException" , null ); AddBreakpointOnDebugMethod( "BugCheck_Raise" , null ); // // To properly set soft breakpoints, we need to wait until all the code has been relocated to its final location. // We set a temporary breakpoint on this method because it's the first program point where relocation is guaranteed to have occurred. // { var bp = AddBreakpointOnDebugMethod( "Bootstrap_Initialization", delegate( Emulation.Hosting.Breakpoint bpHit ) { return Emulation.Hosting.Breakpoint.Response.NextInstruction; } ); if(bp != null) { bp.ShouldImplementInHardware = true; bp.IsOptional = false; bp.IsTemporary = true; } } { var memDelta = new MemoryDelta ( m_imageInformation, m_processorHost ); var ih = new InteropHelper( m_imageInformation, m_processorHost ); ih.SetInteropOnWellKnownMethod( "BugCheck_WriteLine", false, delegate() { uint textAddress = ih.GetRegisterUInt32( Microsoft.Zelig.TargetModel.ArmProcessor.EncodingDefinition.c_register_r1 ); memDelta.FlushCache(); var text = m_imageInformation.GetStringFromMemory( memDelta, textAddress ); if(text != null) { Hst.OutputSink svc; if(m_processorHost.GetHostingService( out svc )) { svc.OutputLine( text ); } } return ih.SkipCall(); } ); } } m_baseSample_clockTicks = 0; m_baseSample_nanoseconds = 0; m_lastSample_clockTicks = m_baseSample_clockTicks; m_lastSample_nanoseconds = m_baseSample_nanoseconds; ExitingState_Running( null ); } ); } } catch(Emulation.Hosting.AbstractEngineException ex) { ExecuteInFormThread( Hst.Forms.HostingSite.ExecutionState.Idle, delegate() { Hst.OutputSink svc; if(m_processorHost.GetHostingService( out svc )) { svc.OutputLine( "Caught exception while loading {0}: {1}", file, ex ); } MessageBox.Show( string.Format( "Exception caught while loading {0}:\r\n\r\nPhase:{1}\r\n\r\n{2}", file, ex.Reason, ex.Message ), "Image Load Error", MessageBoxButtons.OK ); } ); } catch(Exception ex) { ExecuteInFormThread( Hst.Forms.HostingSite.ExecutionState.Idle, delegate() { Hst.OutputSink svc; if(m_processorHost.GetHostingService( out svc )) { svc.OutputLine( "Caught exception while loading {0}: {1}", file, ex ); } MessageBox.Show( string.Format( "Exception caught while loading {0}:\r\n\r\n{1}", file, ex ), "Image Load Error", MessageBoxButtons.OK ); } ); } } ); return true; } //--// private void InnerAction_Execute( StackFrame startStackFrame , bool fAssemblyGranularity , bool fStep , bool fSkipMethodCalls ) { Emulation.Hosting.ProcessorControl svcPC; m_processorHost.GetHostingService( out svcPC ); MemoryDelta memDelta = new MemoryDelta( m_imageInformation, m_processorHost ); try { using(m_processorHost.SuspendMemoryDeltaUpdates()) { Debugging.DebugInfo diTarget = null; if(fStep) { if(fAssemblyGranularity) { m_processorHost.ExecuteStep( m_imageInformation, m_currentSession.SelectedProduct ); if(fSkipMethodCalls) { memDelta.FlushCache(); ThreadStatus ts = ThreadStatus.GetCurrent( memDelta ); // // Did we enter a new method? Then create a temporary breakpoint and run until we hit it. // if(DidWeFollowAMethodCall( startStackFrame, ts.StackTrace )) { RunToAddress( ts.StackTrace[1].ProgramCounter ); m_processorHost.Execute( m_imageInformation, m_currentSession.SelectedProduct ); } } } else { bool fSingleStep = true; bool fHitBreakpoint = false; while(true) { if(fSingleStep) { m_processorHost.ExecuteStep( m_imageInformation, m_currentSession.SelectedProduct ); } else { m_processorHost.Execute( m_imageInformation, m_currentSession.SelectedProduct ); } if(svcPC.StopExecution) { if(fHitBreakpoint) { fHitBreakpoint = false; svcPC.StopExecution = false; } else { break; } } memDelta.FlushCache(); ThreadStatus ts = ThreadStatus.GetCurrent( memDelta ); if(ts.StackTrace.Count == 0) { break; } StackFrame topStackFrame = ts.StackTrace[0]; if(startStackFrame != null) { if(fSkipMethodCalls) { bool fMovedOneOpcode = (startStackFrame.ProgramCounter + sizeof(uint) == topStackFrame.ProgramCounter); if(fMovedOneOpcode == false && DidWeFollowAMethodCall( startStackFrame, ts.StackTrace )) { RunToAddress( ts.StackTrace[1].ProgramCounter, null, delegate( Emulation.Hosting.Breakpoint bp ) { fHitBreakpoint = true; return Emulation.Hosting.Breakpoint.Response.StopExecution; } ); fSingleStep = false; continue; } } if(startStackFrame.DebugInfo != topStackFrame.DebugInfo) { diTarget = topStackFrame.DebugInfo; break; } // // If the top stack frame has multiple DebugInfo associated with its current program counter, // pretend to execute the step and just update the UI. // if(topStackFrame.AdvanceToNextDebugInfo()) { if(startStackFrame.DebugInfo != topStackFrame.DebugInfo) { diTarget = topStackFrame.DebugInfo; break; } } } startStackFrame = topStackFrame; fSingleStep = true; } } } else { m_processorHost.Execute( m_imageInformation, m_currentSession.SelectedProduct ); } ExecuteInFormThread( Hst.Forms.HostingSite.ExecutionState.Paused, delegate() { ExitingState_Running( diTarget ); } ); } } catch(Exception ex) { ExecuteInFormThread( Hst.Forms.HostingSite.ExecutionState.Paused, delegate() { Hst.OutputSink svc; if(m_processorHost.GetHostingService( out svc )) { svc.OutputLine( "Caught exception while executing code: {0}", ex ); } //MessageBox.Show( string.Format( "Exception caught while executing code:\r\n{0}", ex ), "Image Load Error", MessageBoxButtons.OK ); ExitingState_Running( null ); } ); } svcPC.StopExecution = false; } private bool DidWeFollowAMethodCall( StackFrame sf , List< StackFrame > stackTrace ) { if(stackTrace.Count > 1) { StackFrame previousStackFrame = stackTrace[1]; if(sf.CodeMapOfTarget == previousStackFrame.CodeMapOfTarget && sf.StackPointer == previousStackFrame.StackPointer ) { return true; } } return false; } private void RunToAddress( uint address ) { RunToAddress( address, null, delegate( Emulation.Hosting.Breakpoint bp ) { return Emulation.Hosting.Breakpoint.Response.StopExecution; } ); } private Emulation.Hosting.Breakpoint RunToAddress( uint address , Debugging.DebugInfo di , Emulation.Hosting.Breakpoint.Callback callback ) { var bp = Action_SetBreakpoint( address, di, false, false, callback ); bp.IsTemporary = true; return bp; } private Emulation.Hosting.Breakpoint AddBreakpointOnDebugMethod( string name , Emulation.Hosting.Breakpoint.Callback target ) { TS.MethodRepresentation md = m_imageInformation.TypeSystem.GetWellKnownMethodNoThrow( name ); if(md != null) { IR.ImageBuilders.SequentialRegion reg; reg = m_imageInformation.ResolveMethodToRegion( md ); if(reg != null) { return Action_SetBreakpoint( reg.ExternalAddress, null, false, true, target ); } } return null; } //--// private void InnerAction_SynchronizeWithWorker() { bool fAcknowledged = false; ExecuteInWorkerThread( Hst.Forms.HostingSite.ExecutionState.Invalid, delegate() { ExecuteInFormThread( Hst.Forms.HostingSite.ExecutionState.Invalid, delegate() { fAcknowledged = true; } ); } ); while(!fAcknowledged) { Application.DoEvents(); Thread.Sleep( 10 ); } } private void InnerAction_SynchronousStopExecution() { Emulation.Hosting.ProcessorControl svcPC; if(m_processorHost.GetHostingService( out svcPC ) && svcPC.StopExecution == false) { InnerAction_StopExecution(); InnerAction_SynchronizeWithWorker(); svcPC.StopExecution = false; } } //--// public DialogResult Action_EnsureConfiguration() { if(m_currentSession == null) { return DialogResult.Cancel; } m_environmentForm.SelectedEngine = m_currentSession.SelectedEngine; m_environmentForm.SelectedProduct = m_currentSession.SelectedProduct; if(m_environmentForm.IsConfigured) { return DialogResult.OK; } return Action_EditConfiguration(); } public DialogResult Action_EditConfiguration() { if(m_currentSession == null) { return DialogResult.Cancel; } return Action_EditConfiguration( m_currentSession ); } public DialogResult Action_EditConfiguration( Session session ) { m_environmentForm.SelectedEngine = session.SelectedEngine; m_environmentForm.SelectedProduct = session.SelectedProduct; DialogResult res = m_environmentForm.ShowDialog(); if(res == DialogResult.OK) { session.SelectedEngine = m_environmentForm.SelectedEngine; session.SelectedProduct = m_environmentForm.SelectedProduct; } return res; } //--// public string Action_SelectSessionToLoad( string file ) { if(file != null) { sessionOpenFileDialog.FileName = file; } if(sessionOpenFileDialog.ShowDialog() == DialogResult.OK) { return sessionOpenFileDialog.FileName; } return null; } public void Action_LoadSession() { string file = Action_SelectSessionToLoad( null ); if(file != null) { try { InnerAction_LoadSession( file ); } catch(Exception ex) { MessageBox.Show( string.Format( "Exception caught while loading {0}:\r\n{1}", file, ex ), "Session Load Error", MessageBoxButtons.OK ); } } } public string Action_SelectSessionToSave( string file ) { if(file != null) { sessionSaveFileDialog.FileName = file; } if(sessionSaveFileDialog.ShowDialog() == DialogResult.OK) { return sessionSaveFileDialog.FileName; } return null; } public void Action_SaveSession() { string file = Action_SelectSessionToSave( m_currentSession.SettingsFile ); if(file != null) { Action_SaveSession( file ); } } public void Action_SaveSession( string file ) { try { InnerAction_SaveSession( file ); } catch(Exception ex) { MessageBox.Show( string.Format( "Exception caught while saving {0}:\r\n{1}", file, ex ), "Session Save Error", MessageBoxButtons.OK ); } } //--// public void Action_ResetAbsoluteTime() { if(m_processorHost.GetAbsoluteTime( out m_baseSample_clockTicks, out m_baseSample_nanoseconds )) { m_currentSample_clockTicks = m_baseSample_clockTicks; m_currentSample_nanoseconds = m_baseSample_nanoseconds; m_lastSample_clockTicks = m_baseSample_clockTicks; m_lastSample_nanoseconds = m_baseSample_nanoseconds; } } public void Action_LoadImage() { if(Action_EnsureConfiguration() == DialogResult.OK) { if(imageOpenFileDialog.ShowDialog() == DialogResult.OK) { m_currentSession.ImageToLoad = imageOpenFileDialog.FileName; InnerAction_LoadImage(); } } } public void Action_Run() { if(this.IsIdle) { StackFrame currentStackFrame = m_activeThread.StackFrame; if(ShouldExecuteForReal( currentStackFrame )) { ExecuteInWorkerThread( Hst.Forms.HostingSite.ExecutionState.Running, delegate() { InnerAction_Execute( null, false, false, false ); } ); } } } public void Action_Start() { if(this.IsIdle) { //// InnerAction_SynchronousStopExecution(); Action_Run(); } } public void Action_BreakAll() { if(!this.IsIdle) { InnerAction_SynchronousStopExecution(); } } public void Action_StopDebugging() { InnerAction_LoadImage(); } public void Action_Restart() { InnerAction_LoadImage(); InnerAction_SynchronizeWithWorker(); Action_Run(); } public void Action_StepInto() { if(this.IsIdle) { InnerAction_SynchronousStopExecution(); bool fUseAssemblyGranularity = m_currentSession.DisplayDisassembly; StackFrame currentStackFrame = m_activeThread.StackFrame; if(ShouldStepForReal( currentStackFrame )) { ExecuteInWorkerThread( Hst.Forms.HostingSite.ExecutionState.Running, delegate() { InnerAction_Execute( currentStackFrame, fUseAssemblyGranularity, true, false ); } ); } } } public void Action_StepOver() { if(this.IsIdle) { InnerAction_SynchronousStopExecution(); bool fUseAssemblyGranularity = m_currentSession.DisplayDisassembly; StackFrame currentStackFrame = m_activeThread.StackFrame; /// /// TODO: allow step over to step over inlined methods /// if(ShouldStepForReal( currentStackFrame )) { ExecuteInWorkerThread( Hst.Forms.HostingSite.ExecutionState.Running, delegate() { InnerAction_Execute( currentStackFrame, fUseAssemblyGranularity, true, true ); } ); } } } public void Action_StepOut() { if(this.IsIdle) { InnerAction_SynchronousStopExecution(); if(m_activeThread.StackTrace.Count > 1) { StackFrame sf = m_activeThread.StackTrace[1]; RunToAddress( sf.ProgramCounter ); Action_Run(); } } } private bool ShouldExecuteForReal( StackFrame currentStackFrame ) { // // If the top stack frame has multiple DebugInfo associated with its current program counter, // pretend to execute the step and just update the UI. // if(currentStackFrame != null) { bool fGot = false; uint pc = currentStackFrame.ProgramCounter; foreach(var bp in m_processorHost.Breakpoints) { if(bp.IsActive && bp.Address == pc) { if(currentStackFrame.MoveForwardToDebugInfo( bp.DebugInfo )) { fGot = true; bp.Hit(); } } } if(fGot) { UpdateDisplay( false ); UpdateExecutionState( Hst.Forms.HostingSite.ExecutionState.Paused ); return false; } } return true; } private bool ShouldStepForReal( StackFrame currentStackFrame ) { // // If the top stack frame has multiple DebugInfo associated with its current program counter, // pretend to execute the step and just update the UI. // if(currentStackFrame != null && currentStackFrame.AdvanceToNextDebugInfo()) { UpdateDisplay( false ); UpdateExecutionState( Hst.Forms.HostingSite.ExecutionState.Paused ); return false; } return true; } //--// public void Action_SetBreakpoint( uint pc , Debugging.DebugInfo di ) { Action_SetBreakpoint( pc, di, true ); } public void Action_SetBreakpoint( uint pc , Debugging.DebugInfo di , bool fVisible ) { Action_SetBreakpoint( pc, di, fVisible, false, null ); } public Emulation.Hosting.Breakpoint Action_SetBreakpoint( uint pc , Debugging.DebugInfo di , bool fVisible , bool fIsOptional , Emulation.Hosting.Breakpoint.Callback target ) { if(target == null) { target = delegate( Emulation.Hosting.Breakpoint bpHit ) { return Emulation.Hosting.Breakpoint.Response.StopExecution; }; } var bp = m_processorHost.CreateBreakpoint( pc, di, target ); m_versionBreakpoints++; bp.IsOptional = fIsOptional; bp.ShowInUI = fVisible; Action_ActivateBreakpoint( bp ); return bp; } public void Action_ActivateBreakpoint( Emulation.Hosting.Breakpoint bp ) { if(bp.IsActive == false) { bp.IsActive = true; SynchronizeBreakpointsUI(); } } public void Action_RemoveBreakpoint( Emulation.Hosting.Breakpoint bp ) { m_processorHost.RemoveBreakpoint( bp ); m_versionBreakpoints++; SynchronizeBreakpointsUI(); } public void Action_RefreshBreakpoints() { SynchronizeBreakpointsUI(); } public void Action_DeleteAllBreakpoints() { foreach(Emulation.Hosting.Breakpoint bp in m_processorHost.Breakpoints) { if(bp.ShowInUI) { m_processorHost.RemoveBreakpoint( bp ); } } m_versionBreakpoints++; SynchronizeBreakpointsUI(); } //--// public void Action_ToggleDisassembly() { if(this.IsIdle) { m_currentSession.DisplayDisassembly = !m_currentSession.DisplayDisassembly; if(this.SelectedStackFrame != null) { VisualizeStackFrame( this.SelectedStackFrame ); } } } public void Action_ToggleWrapper() { if(this.IsIdle) { m_imageInformation.DisplayWrapper = !m_imageInformation.DisplayWrapper; Debugging.DebugInfo diTarget = null; if(m_activeThread != null) { if(m_activeThread.TopStackFrame != null) { diTarget = m_activeThread.TopStackFrame.DebugInfo; } } ExitingState_Running( diTarget ); } } //--// public void Action_MoveInTheStackTrace( int direction ) { if(this.IsIdle) { if(this.SelectedStackFrame != null) { int pos = this.SelectedThread.StackTrace.IndexOf( this.SelectedStackFrame ); if(pos >= 0) { Action_SelectStackFrame( pos + direction ); } } } } public void Action_SelectStackFrame( int depth ) { foreach(StackFrame sf in this.SelectedThread.StackTrace) { if(sf.Depth == depth) { CHECKS.ASSERT( m_imageInformation != null, "Missing ImageInformation" ); VisualizeStackFrame( sf ); break; } } } //--// public void Action_MoveInTheThreadList( int direction ) { if(this.IsIdle) { if(this.SelectedThread != null) { int pos = this.Threads.IndexOf( this.SelectedThread ); if(pos >= 0) { Action_SelectThread( pos + direction ); } } } } public void Action_SelectThread( int idx ) { if(idx >= 0 && idx < m_threads.Count) { m_selectedThread = m_threads[idx]; UpdateDisplay( false ); } } } } ================================================ FILE: Zelig/Zelig/DebugTime/Debugger/Forms/DebuggerMainForm.Designer.cs ================================================ namespace Microsoft.Zelig.Debugger.ArmProcessor { partial class DebuggerMainForm { /// /// Required designer variable. /// private System.ComponentModel.IContainer components = null; /// /// Clean up any resources being used. /// /// true if managed resources should be disposed; otherwise, false. protected override void Dispose( bool disposing ) { if(disposing && (components != null)) { components.Dispose(); } base.Dispose( disposing ); } #region Windows Form Designer generated code /// /// Required method for Designer support - do not modify /// the contents of this method with the code editor. /// private void InitializeComponent() { System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager( typeof( DebuggerMainForm ) ); this.menuStrip1 = new System.Windows.Forms.MenuStrip(); this.toolStripMenuItem_File = new System.Windows.Forms.ToolStripMenuItem(); this.toolStripSeparator4 = new System.Windows.Forms.ToolStripSeparator(); this.toolStripMenuItem_File_Open = new System.Windows.Forms.ToolStripMenuItem(); this.toolStripMenuItem_File_Open_Image = new System.Windows.Forms.ToolStripMenuItem(); this.toolStripMenuItem_File_Open_Session = new System.Windows.Forms.ToolStripMenuItem(); this.toolStripSeparator6 = new System.Windows.Forms.ToolStripSeparator(); this.toolStripMenuItem_File_Session = new System.Windows.Forms.ToolStripMenuItem(); this.toolStripMenuItem_File_Session_Load = new System.Windows.Forms.ToolStripMenuItem(); this.toolStripMenuItem_File_Session_Edit = new System.Windows.Forms.ToolStripMenuItem(); this.toolStripMenuItem_File_Session_Save = new System.Windows.Forms.ToolStripMenuItem(); this.toolStripMenuItem_File_Session_SaveAs = new System.Windows.Forms.ToolStripMenuItem(); this.toolStripSeparator1 = new System.Windows.Forms.ToolStripSeparator(); this.toolStripMenuItem_File_Exit = new System.Windows.Forms.ToolStripMenuItem(); this.toolStripMenuItem_View = new System.Windows.Forms.ToolStripMenuItem(); this.toolStripMenuItem_Tools = new System.Windows.Forms.ToolStripMenuItem(); this.toolStripMenuItem_Tools_SessionManager = new System.Windows.Forms.ToolStripMenuItem(); this.toolStripSeparator_Tools_Top = new System.Windows.Forms.ToolStripSeparator(); this.toolStripSeparator_Tools_Bottom = new System.Windows.Forms.ToolStripSeparator(); this.toolStripMenuItem_Tools_Customize = new System.Windows.Forms.ToolStripMenuItem(); this.toolStripMenuItem_Tools_Options = new System.Windows.Forms.ToolStripMenuItem(); this.toolStripMenuItem_Windows = new System.Windows.Forms.ToolStripMenuItem(); this.toolStripSeparator_Files = new System.Windows.Forms.ToolStripSeparator(); this.toolStripMenuItem_Help = new System.Windows.Forms.ToolStripMenuItem(); this.toolStripMenuItem_Help_Contents = new System.Windows.Forms.ToolStripMenuItem(); this.toolStripMenuItem_Help_Index = new System.Windows.Forms.ToolStripMenuItem(); this.toolStripMenuItem_Help_Search = new System.Windows.Forms.ToolStripMenuItem(); this.toolStripSeparator5 = new System.Windows.Forms.ToolStripSeparator(); this.toolStripMenuItem_Help_About = new System.Windows.Forms.ToolStripMenuItem(); this.statusStrip1 = new System.Windows.Forms.StatusStrip(); this.toolStripStatus_ExecutionState = new System.Windows.Forms.ToolStripStatusLabel(); this.toolStripStatus_AbsoluteTime = new System.Windows.Forms.ToolStripStatusLabel(); this.toolStripStatus_CurrentMethod = new System.Windows.Forms.ToolStripStatusLabel(); this.imageOpenFileDialog = new System.Windows.Forms.OpenFileDialog(); this.toolStrip1 = new System.Windows.Forms.ToolStrip(); this.toolStripButton_Open = new System.Windows.Forms.ToolStripButton(); this.toolStripSeparator = new System.Windows.Forms.ToolStripSeparator(); this.toolStripButton_Start = new System.Windows.Forms.ToolStripButton(); this.toolStripButton_BreakAll = new System.Windows.Forms.ToolStripButton(); this.toolStripButton_StopDebugging = new System.Windows.Forms.ToolStripButton(); this.toolStripButton_Restart = new System.Windows.Forms.ToolStripButton(); this.toolStripSeparator2 = new System.Windows.Forms.ToolStripSeparator(); this.toolStripButton_ShowNextStatement = new System.Windows.Forms.ToolStripButton(); this.toolStripButton_StepInto = new System.Windows.Forms.ToolStripButton(); this.toolStripButton_StepOver = new System.Windows.Forms.ToolStripButton(); this.toolStripButton_StepOut = new System.Windows.Forms.ToolStripButton(); this.toolStripSeparator3 = new System.Windows.Forms.ToolStripSeparator(); this.toolStripButton_ToggleDisassembly = new System.Windows.Forms.ToolStripButton(); this.splitContainer1 = new System.Windows.Forms.SplitContainer(); this.codeView1 = new Microsoft.Zelig.Debugger.ArmProcessor.CodeView(); this.tabControl_Data = new System.Windows.Forms.TabControl(); this.tabPage_Locals = new System.Windows.Forms.TabPage(); this.localsView1 = new Microsoft.Zelig.Debugger.ArmProcessor.LocalsView(); this.tabPage_Registers = new System.Windows.Forms.TabPage(); this.registersView1 = new Microsoft.Zelig.Debugger.ArmProcessor.RegistersView(); this.tabPage_StackTrace = new System.Windows.Forms.TabPage(); this.stackTraceView1 = new Microsoft.Zelig.Debugger.ArmProcessor.StackTraceView(); this.tabPage_Threads = new System.Windows.Forms.TabPage(); this.threadsView1 = new Microsoft.Zelig.Debugger.ArmProcessor.ThreadsView(); this.tabPage_Memory = new System.Windows.Forms.TabPage(); this.memoryView1 = new Microsoft.Zelig.Debugger.ArmProcessor.MemoryView(); this.tabPage_Breakpoints = new System.Windows.Forms.TabPage(); this.breakpointsView1 = new Microsoft.Zelig.Debugger.ArmProcessor.BreakpointsView(); this.sessionSaveFileDialog = new System.Windows.Forms.SaveFileDialog(); this.sessionOpenFileDialog = new System.Windows.Forms.OpenFileDialog(); this.toolStripButton_ToggleWrapper = new System.Windows.Forms.ToolStripButton(); this.menuStrip1.SuspendLayout(); this.statusStrip1.SuspendLayout(); this.toolStrip1.SuspendLayout(); this.splitContainer1.Panel1.SuspendLayout(); this.splitContainer1.Panel2.SuspendLayout(); this.splitContainer1.SuspendLayout(); this.tabControl_Data.SuspendLayout(); this.tabPage_Locals.SuspendLayout(); this.tabPage_Registers.SuspendLayout(); this.tabPage_StackTrace.SuspendLayout(); this.tabPage_Threads.SuspendLayout(); this.tabPage_Memory.SuspendLayout(); this.tabPage_Breakpoints.SuspendLayout(); this.SuspendLayout(); // // menuStrip1 // this.menuStrip1.Items.AddRange( new System.Windows.Forms.ToolStripItem[] { this.toolStripMenuItem_File, this.toolStripMenuItem_View, this.toolStripMenuItem_Tools, this.toolStripMenuItem_Windows, this.toolStripMenuItem_Help} ); this.menuStrip1.Location = new System.Drawing.Point( 0, 0 ); this.menuStrip1.Name = "menuStrip1"; this.menuStrip1.Size = new System.Drawing.Size( 1006, 24 ); this.menuStrip1.TabIndex = 0; this.menuStrip1.Text = "menuStrip1"; // // toolStripMenuItem_File // this.toolStripMenuItem_File.DropDownItems.AddRange( new System.Windows.Forms.ToolStripItem[] { this.toolStripSeparator4, this.toolStripMenuItem_File_Open, this.toolStripSeparator6, this.toolStripMenuItem_File_Session, this.toolStripSeparator1, this.toolStripMenuItem_File_Exit} ); this.toolStripMenuItem_File.Name = "toolStripMenuItem_File"; this.toolStripMenuItem_File.Size = new System.Drawing.Size( 35, 20 ); this.toolStripMenuItem_File.Text = "&File"; // // toolStripSeparator4 // this.toolStripSeparator4.Name = "toolStripSeparator4"; this.toolStripSeparator4.Size = new System.Drawing.Size( 118, 6 ); // // toolStripMenuItem_File_Open // this.toolStripMenuItem_File_Open.DropDownItems.AddRange( new System.Windows.Forms.ToolStripItem[] { this.toolStripMenuItem_File_Open_Image, this.toolStripMenuItem_File_Open_Session} ); this.toolStripMenuItem_File_Open.Image = global::Microsoft.Zelig.Debugger.ArmProcessor.Properties.Resources.Open; this.toolStripMenuItem_File_Open.ImageTransparentColor = System.Drawing.Color.Magenta; this.toolStripMenuItem_File_Open.Name = "toolStripMenuItem_File_Open"; this.toolStripMenuItem_File_Open.Size = new System.Drawing.Size( 121, 22 ); this.toolStripMenuItem_File_Open.Text = "&Open"; // // toolStripMenuItem_File_Open_Image // this.toolStripMenuItem_File_Open_Image.Name = "toolStripMenuItem_File_Open_Image"; this.toolStripMenuItem_File_Open_Image.ShortcutKeys = ((System.Windows.Forms.Keys)((System.Windows.Forms.Keys.Control | System.Windows.Forms.Keys.O))); this.toolStripMenuItem_File_Open_Image.Size = new System.Drawing.Size( 167, 22 ); this.toolStripMenuItem_File_Open_Image.Text = "&Image..."; this.toolStripMenuItem_File_Open_Image.Click += new System.EventHandler( this.toolStripMenuItem_File_Open_Click ); // // toolStripMenuItem_File_Open_Session // this.toolStripMenuItem_File_Open_Session.Name = "toolStripMenuItem_File_Open_Session"; this.toolStripMenuItem_File_Open_Session.Size = new System.Drawing.Size( 167, 22 ); this.toolStripMenuItem_File_Open_Session.Text = "&Session..."; this.toolStripMenuItem_File_Open_Session.Click += new System.EventHandler( this.toolStripMenuItem_File_Session_Load_Click ); // // toolStripSeparator6 // this.toolStripSeparator6.Name = "toolStripSeparator6"; this.toolStripSeparator6.Size = new System.Drawing.Size( 118, 6 ); // // toolStripMenuItem_File_Session // this.toolStripMenuItem_File_Session.DropDownItems.AddRange( new System.Windows.Forms.ToolStripItem[] { this.toolStripMenuItem_File_Session_Load, this.toolStripMenuItem_File_Session_Edit, this.toolStripMenuItem_File_Session_Save, this.toolStripMenuItem_File_Session_SaveAs} ); this.toolStripMenuItem_File_Session.Name = "toolStripMenuItem_File_Session"; this.toolStripMenuItem_File_Session.Size = new System.Drawing.Size( 121, 22 ); this.toolStripMenuItem_File_Session.Text = "Session"; // // toolStripMenuItem_File_Session_Load // this.toolStripMenuItem_File_Session_Load.Name = "toolStripMenuItem_File_Session_Load"; this.toolStripMenuItem_File_Session_Load.Size = new System.Drawing.Size( 171, 22 ); this.toolStripMenuItem_File_Session_Load.Text = "&Load..."; this.toolStripMenuItem_File_Session_Load.Click += new System.EventHandler( this.toolStripMenuItem_File_Session_Load_Click ); // // toolStripMenuItem_File_Session_Edit // this.toolStripMenuItem_File_Session_Edit.Name = "toolStripMenuItem_File_Session_Edit"; this.toolStripMenuItem_File_Session_Edit.Size = new System.Drawing.Size( 171, 22 ); this.toolStripMenuItem_File_Session_Edit.Text = "&Edit Configuration"; this.toolStripMenuItem_File_Session_Edit.Click += new System.EventHandler( this.toolStripMenuItem_File_Session_Edit_Click ); // // toolStripMenuItem_File_Session_Save // this.toolStripMenuItem_File_Session_Save.Name = "toolStripMenuItem_File_Session_Save"; this.toolStripMenuItem_File_Session_Save.Size = new System.Drawing.Size( 171, 22 ); this.toolStripMenuItem_File_Session_Save.Text = "&Save"; this.toolStripMenuItem_File_Session_Save.Click += new System.EventHandler( this.toolStripMenuItem_File_Session_Save_Click ); // // toolStripMenuItem_File_Session_SaveAs // this.toolStripMenuItem_File_Session_SaveAs.Name = "toolStripMenuItem_File_Session_SaveAs"; this.toolStripMenuItem_File_Session_SaveAs.Size = new System.Drawing.Size( 171, 22 ); this.toolStripMenuItem_File_Session_SaveAs.Text = "Save &As..."; this.toolStripMenuItem_File_Session_SaveAs.Click += new System.EventHandler( this.toolStripMenuItem_File_Session_SaveAs_Click ); // // toolStripSeparator1 // this.toolStripSeparator1.Name = "toolStripSeparator1"; this.toolStripSeparator1.Size = new System.Drawing.Size( 118, 6 ); // // toolStripMenuItem_File_Exit // this.toolStripMenuItem_File_Exit.Name = "toolStripMenuItem_File_Exit"; this.toolStripMenuItem_File_Exit.Size = new System.Drawing.Size( 121, 22 ); this.toolStripMenuItem_File_Exit.Text = "E&xit"; this.toolStripMenuItem_File_Exit.Click += new System.EventHandler( this.toolStripMenuItem_File_Exit_Click ); // // toolStripMenuItem_View // this.toolStripMenuItem_View.Name = "toolStripMenuItem_View"; this.toolStripMenuItem_View.Size = new System.Drawing.Size( 41, 20 ); this.toolStripMenuItem_View.Text = "&View"; // // toolStripMenuItem_Tools // this.toolStripMenuItem_Tools.DropDownItems.AddRange( new System.Windows.Forms.ToolStripItem[] { this.toolStripMenuItem_Tools_SessionManager, this.toolStripSeparator_Tools_Top, this.toolStripSeparator_Tools_Bottom, this.toolStripMenuItem_Tools_Customize, this.toolStripMenuItem_Tools_Options} ); this.toolStripMenuItem_Tools.Name = "toolStripMenuItem_Tools"; this.toolStripMenuItem_Tools.Size = new System.Drawing.Size( 44, 20 ); this.toolStripMenuItem_Tools.Text = "&Tools"; // // toolStripMenuItem_Tools_SessionManager // this.toolStripMenuItem_Tools_SessionManager.Name = "toolStripMenuItem_Tools_SessionManager"; this.toolStripMenuItem_Tools_SessionManager.Size = new System.Drawing.Size( 178, 22 ); this.toolStripMenuItem_Tools_SessionManager.Text = "&Session Manager..."; this.toolStripMenuItem_Tools_SessionManager.Click += new System.EventHandler( this.toolStripMenuItem_Tools_SessionManager_Click ); // // toolStripSeparator_Tools_Top // this.toolStripSeparator_Tools_Top.Name = "toolStripSeparator_Tools_Top"; this.toolStripSeparator_Tools_Top.Size = new System.Drawing.Size( 175, 6 ); // // toolStripSeparator_Tools_Bottom // this.toolStripSeparator_Tools_Bottom.Name = "toolStripSeparator_Tools_Bottom"; this.toolStripSeparator_Tools_Bottom.Size = new System.Drawing.Size( 175, 6 ); this.toolStripSeparator_Tools_Bottom.Visible = false; // // toolStripMenuItem_Tools_Customize // this.toolStripMenuItem_Tools_Customize.Name = "toolStripMenuItem_Tools_Customize"; this.toolStripMenuItem_Tools_Customize.Size = new System.Drawing.Size( 178, 22 ); this.toolStripMenuItem_Tools_Customize.Text = "&Customize"; // // toolStripMenuItem_Tools_Options // this.toolStripMenuItem_Tools_Options.Name = "toolStripMenuItem_Tools_Options"; this.toolStripMenuItem_Tools_Options.Size = new System.Drawing.Size( 178, 22 ); this.toolStripMenuItem_Tools_Options.Text = "&Options"; // // toolStripMenuItem_Windows // this.toolStripMenuItem_Windows.DropDownItems.AddRange( new System.Windows.Forms.ToolStripItem[] { this.toolStripSeparator_Files} ); this.toolStripMenuItem_Windows.Name = "toolStripMenuItem_Windows"; this.toolStripMenuItem_Windows.Size = new System.Drawing.Size( 62, 20 ); this.toolStripMenuItem_Windows.Text = "&Windows"; // // toolStripSeparator_Files // this.toolStripSeparator_Files.Name = "toolStripSeparator_Files"; this.toolStripSeparator_Files.Size = new System.Drawing.Size( 57, 6 ); this.toolStripSeparator_Files.Visible = false; // // toolStripMenuItem_Help // this.toolStripMenuItem_Help.DropDownItems.AddRange( new System.Windows.Forms.ToolStripItem[] { this.toolStripMenuItem_Help_Contents, this.toolStripMenuItem_Help_Index, this.toolStripMenuItem_Help_Search, this.toolStripSeparator5, this.toolStripMenuItem_Help_About} ); this.toolStripMenuItem_Help.Name = "toolStripMenuItem_Help"; this.toolStripMenuItem_Help.Size = new System.Drawing.Size( 40, 20 ); this.toolStripMenuItem_Help.Text = "&Help"; // // toolStripMenuItem_Help_Contents // this.toolStripMenuItem_Help_Contents.Name = "toolStripMenuItem_Help_Contents"; this.toolStripMenuItem_Help_Contents.Size = new System.Drawing.Size( 129, 22 ); this.toolStripMenuItem_Help_Contents.Text = "&Contents"; // // toolStripMenuItem_Help_Index // this.toolStripMenuItem_Help_Index.Name = "toolStripMenuItem_Help_Index"; this.toolStripMenuItem_Help_Index.Size = new System.Drawing.Size( 129, 22 ); this.toolStripMenuItem_Help_Index.Text = "&Index"; // // toolStripMenuItem_Help_Search // this.toolStripMenuItem_Help_Search.Name = "toolStripMenuItem_Help_Search"; this.toolStripMenuItem_Help_Search.Size = new System.Drawing.Size( 129, 22 ); this.toolStripMenuItem_Help_Search.Text = "&Search"; // // toolStripSeparator5 // this.toolStripSeparator5.Name = "toolStripSeparator5"; this.toolStripSeparator5.Size = new System.Drawing.Size( 126, 6 ); // // toolStripMenuItem_Help_About // this.toolStripMenuItem_Help_About.Name = "toolStripMenuItem_Help_About"; this.toolStripMenuItem_Help_About.Size = new System.Drawing.Size( 129, 22 ); this.toolStripMenuItem_Help_About.Text = "&About..."; // // statusStrip1 // this.statusStrip1.Items.AddRange( new System.Windows.Forms.ToolStripItem[] { this.toolStripStatus_ExecutionState, this.toolStripStatus_AbsoluteTime, this.toolStripStatus_CurrentMethod} ); this.statusStrip1.Location = new System.Drawing.Point( 0, 511 ); this.statusStrip1.Name = "statusStrip1"; this.statusStrip1.Size = new System.Drawing.Size( 1006, 22 ); this.statusStrip1.TabIndex = 1; this.statusStrip1.Text = "statusStrip1"; this.statusStrip1.DoubleClick += new System.EventHandler( this.statusTrip1_DoubleClick ); // // toolStripStatus_ExecutionState // this.toolStripStatus_ExecutionState.Name = "toolStripStatus_ExecutionState"; this.toolStripStatus_ExecutionState.Size = new System.Drawing.Size( 25, 17 ); this.toolStripStatus_ExecutionState.Text = "Idle"; // // toolStripStatus_AbsoluteTime // this.toolStripStatus_AbsoluteTime.Name = "toolStripStatus_AbsoluteTime"; this.toolStripStatus_AbsoluteTime.Size = new System.Drawing.Size( 0, 17 ); // // toolStripStatus_CurrentMethod // this.toolStripStatus_CurrentMethod.Name = "toolStripStatus_CurrentMethod"; this.toolStripStatus_CurrentMethod.Size = new System.Drawing.Size( 0, 17 ); // // imageOpenFileDialog // this.imageOpenFileDialog.Filter = "Zelig Image|*.ZeligImage|Hex files|*.hex|ADS images|*.axfdump"; // // toolStrip1 // this.toolStrip1.Items.AddRange( new System.Windows.Forms.ToolStripItem[] { this.toolStripButton_Open, this.toolStripSeparator, this.toolStripButton_Start, this.toolStripButton_BreakAll, this.toolStripButton_StopDebugging, this.toolStripButton_Restart, this.toolStripSeparator2, this.toolStripButton_ShowNextStatement, this.toolStripButton_StepInto, this.toolStripButton_StepOver, this.toolStripButton_StepOut, this.toolStripSeparator3, this.toolStripButton_ToggleDisassembly, this.toolStripButton_ToggleWrapper} ); this.toolStrip1.Location = new System.Drawing.Point( 0, 24 ); this.toolStrip1.Name = "toolStrip1"; this.toolStrip1.Size = new System.Drawing.Size( 1006, 25 ); this.toolStrip1.TabIndex = 3; this.toolStrip1.Text = "toolStrip1"; // // toolStripButton_Open // this.toolStripButton_Open.DisplayStyle = System.Windows.Forms.ToolStripItemDisplayStyle.Image; this.toolStripButton_Open.Image = global::Microsoft.Zelig.Debugger.ArmProcessor.Properties.Resources.Open; this.toolStripButton_Open.ImageTransparentColor = System.Drawing.Color.Magenta; this.toolStripButton_Open.Name = "toolStripButton_Open"; this.toolStripButton_Open.Size = new System.Drawing.Size( 23, 22 ); this.toolStripButton_Open.Text = "Open (Ctrl+O)"; this.toolStripButton_Open.Click += new System.EventHandler( this.toolStripMenuItem_File_Open_Click ); // // toolStripSeparator // this.toolStripSeparator.Name = "toolStripSeparator"; this.toolStripSeparator.Size = new System.Drawing.Size( 6, 25 ); // // toolStripButton_Start // this.toolStripButton_Start.DisplayStyle = System.Windows.Forms.ToolStripItemDisplayStyle.Image; this.toolStripButton_Start.Image = global::Microsoft.Zelig.Debugger.ArmProcessor.Properties.Resources.Start; this.toolStripButton_Start.ImageTransparentColor = System.Drawing.Color.Magenta; this.toolStripButton_Start.Name = "toolStripButton_Start"; this.toolStripButton_Start.Size = new System.Drawing.Size( 23, 22 ); this.toolStripButton_Start.Text = "Start / Continue (F5)"; this.toolStripButton_Start.Click += new System.EventHandler( this.toolStripButton_Start_Click ); // // toolStripButton_BreakAll // this.toolStripButton_BreakAll.DisplayStyle = System.Windows.Forms.ToolStripItemDisplayStyle.Image; this.toolStripButton_BreakAll.Enabled = false; this.toolStripButton_BreakAll.Image = global::Microsoft.Zelig.Debugger.ArmProcessor.Properties.Resources.BreakAll; this.toolStripButton_BreakAll.ImageTransparentColor = System.Drawing.Color.Magenta; this.toolStripButton_BreakAll.Name = "toolStripButton_BreakAll"; this.toolStripButton_BreakAll.Size = new System.Drawing.Size( 23, 22 ); this.toolStripButton_BreakAll.Text = "Break All (Ctrl+Alt+Break)"; this.toolStripButton_BreakAll.Click += new System.EventHandler( this.toolStripButton_BreakAll_Click ); // // toolStripButton_StopDebugging // this.toolStripButton_StopDebugging.DisplayStyle = System.Windows.Forms.ToolStripItemDisplayStyle.Image; this.toolStripButton_StopDebugging.Enabled = false; this.toolStripButton_StopDebugging.Image = global::Microsoft.Zelig.Debugger.ArmProcessor.Properties.Resources.StopDebugging; this.toolStripButton_StopDebugging.ImageTransparentColor = System.Drawing.Color.Magenta; this.toolStripButton_StopDebugging.Name = "toolStripButton_StopDebugging"; this.toolStripButton_StopDebugging.Size = new System.Drawing.Size( 23, 22 ); this.toolStripButton_StopDebugging.Text = "Stop Debugging (Shift+F5)"; this.toolStripButton_StopDebugging.Click += new System.EventHandler( this.toolStripButton_StopDebugging_Click ); // // toolStripButton_Restart // this.toolStripButton_Restart.DisplayStyle = System.Windows.Forms.ToolStripItemDisplayStyle.Image; this.toolStripButton_Restart.Enabled = false; this.toolStripButton_Restart.Image = global::Microsoft.Zelig.Debugger.ArmProcessor.Properties.Resources.Restart; this.toolStripButton_Restart.ImageTransparentColor = System.Drawing.Color.Magenta; this.toolStripButton_Restart.Name = "toolStripButton_Restart"; this.toolStripButton_Restart.Size = new System.Drawing.Size( 23, 22 ); this.toolStripButton_Restart.Text = "Restart (Ctrl+Shift+F5)"; this.toolStripButton_Restart.Click += new System.EventHandler( this.toolStripButton_Restart_Click ); // // toolStripSeparator2 // this.toolStripSeparator2.Name = "toolStripSeparator2"; this.toolStripSeparator2.Size = new System.Drawing.Size( 6, 25 ); // // toolStripButton_ShowNextStatement // this.toolStripButton_ShowNextStatement.DisplayStyle = System.Windows.Forms.ToolStripItemDisplayStyle.Image; this.toolStripButton_ShowNextStatement.Enabled = false; this.toolStripButton_ShowNextStatement.Image = global::Microsoft.Zelig.Debugger.ArmProcessor.Properties.Resources.ShowNextStatement; this.toolStripButton_ShowNextStatement.ImageTransparentColor = System.Drawing.Color.Magenta; this.toolStripButton_ShowNextStatement.Name = "toolStripButton_ShowNextStatement"; this.toolStripButton_ShowNextStatement.Size = new System.Drawing.Size( 23, 22 ); this.toolStripButton_ShowNextStatement.Text = "Show Next Statement"; this.toolStripButton_ShowNextStatement.Click += new System.EventHandler( this.toolStripButton_ShowNextStatement_Click ); // // toolStripButton_StepInto // this.toolStripButton_StepInto.DisplayStyle = System.Windows.Forms.ToolStripItemDisplayStyle.Image; this.toolStripButton_StepInto.Image = global::Microsoft.Zelig.Debugger.ArmProcessor.Properties.Resources.StepInto; this.toolStripButton_StepInto.ImageTransparentColor = System.Drawing.Color.Magenta; this.toolStripButton_StepInto.Name = "toolStripButton_StepInto"; this.toolStripButton_StepInto.Size = new System.Drawing.Size( 23, 22 ); this.toolStripButton_StepInto.Text = "Step Into (F11)"; this.toolStripButton_StepInto.Click += new System.EventHandler( this.toolStripButton_StepInto_Click ); // // toolStripButton_StepOver // this.toolStripButton_StepOver.DisplayStyle = System.Windows.Forms.ToolStripItemDisplayStyle.Image; this.toolStripButton_StepOver.Image = global::Microsoft.Zelig.Debugger.ArmProcessor.Properties.Resources.StepOver; this.toolStripButton_StepOver.ImageTransparentColor = System.Drawing.Color.Magenta; this.toolStripButton_StepOver.Name = "toolStripButton_StepOver"; this.toolStripButton_StepOver.Size = new System.Drawing.Size( 23, 22 ); this.toolStripButton_StepOver.Text = "Step Over (F10)"; this.toolStripButton_StepOver.Click += new System.EventHandler( this.toolStripButton_StepOver_Click ); // // toolStripButton_StepOut // this.toolStripButton_StepOut.DisplayStyle = System.Windows.Forms.ToolStripItemDisplayStyle.Image; this.toolStripButton_StepOut.Enabled = false; this.toolStripButton_StepOut.Image = global::Microsoft.Zelig.Debugger.ArmProcessor.Properties.Resources.StepOut; this.toolStripButton_StepOut.ImageTransparentColor = System.Drawing.Color.Magenta; this.toolStripButton_StepOut.Name = "toolStripButton_StepOut"; this.toolStripButton_StepOut.Size = new System.Drawing.Size( 23, 22 ); this.toolStripButton_StepOut.Text = "Step Out (Shift+F11)"; this.toolStripButton_StepOut.Click += new System.EventHandler( this.toolStripButton_StepOut_Click ); // // toolStripSeparator3 // this.toolStripSeparator3.Name = "toolStripSeparator3"; this.toolStripSeparator3.Size = new System.Drawing.Size( 6, 25 ); // // toolStripButton_ToggleDisassembly // this.toolStripButton_ToggleDisassembly.DisplayStyle = System.Windows.Forms.ToolStripItemDisplayStyle.Image; this.toolStripButton_ToggleDisassembly.Image = global::Microsoft.Zelig.Debugger.ArmProcessor.Properties.Resources.ToggleDisassembly; this.toolStripButton_ToggleDisassembly.ImageTransparentColor = System.Drawing.Color.Magenta; this.toolStripButton_ToggleDisassembly.Name = "toolStripButton_ToggleDisassembly"; this.toolStripButton_ToggleDisassembly.Size = new System.Drawing.Size( 23, 22 ); this.toolStripButton_ToggleDisassembly.Text = "Toggle Disassembly (Ctrl+F11)"; this.toolStripButton_ToggleDisassembly.Click += new System.EventHandler( this.toolStripButton_ToggleDisassembly_Click ); // // splitContainer1 // this.splitContainer1.Anchor = ((System.Windows.Forms.AnchorStyles)((((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Bottom) | System.Windows.Forms.AnchorStyles.Left) | System.Windows.Forms.AnchorStyles.Right))); this.splitContainer1.Location = new System.Drawing.Point( 0, 52 ); this.splitContainer1.Name = "splitContainer1"; // // splitContainer1.Panel1 // this.splitContainer1.Panel1.Controls.Add( this.codeView1 ); // // splitContainer1.Panel2 // this.splitContainer1.Panel2.Controls.Add( this.tabControl_Data ); this.splitContainer1.Size = new System.Drawing.Size( 1006, 456 ); this.splitContainer1.SplitterDistance = 473; this.splitContainer1.TabIndex = 2; // // codeView1 // this.codeView1.AutoScroll = true; this.codeView1.DefaultHitSink = null; this.codeView1.Dock = System.Windows.Forms.DockStyle.Fill; this.codeView1.FallbackHitSink = null; this.codeView1.Font = new System.Drawing.Font( "Courier New", 9F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)) ); this.codeView1.Location = new System.Drawing.Point( 0, 0 ); this.codeView1.Name = "codeView1"; this.codeView1.Size = new System.Drawing.Size( 473, 456 ); this.codeView1.TabIndex = 0; // // tabControl_Data // this.tabControl_Data.Controls.Add( this.tabPage_Locals ); this.tabControl_Data.Controls.Add( this.tabPage_Registers ); this.tabControl_Data.Controls.Add( this.tabPage_StackTrace ); this.tabControl_Data.Controls.Add( this.tabPage_Threads ); this.tabControl_Data.Controls.Add( this.tabPage_Memory ); this.tabControl_Data.Controls.Add( this.tabPage_Breakpoints ); this.tabControl_Data.Dock = System.Windows.Forms.DockStyle.Fill; this.tabControl_Data.Location = new System.Drawing.Point( 0, 0 ); this.tabControl_Data.Name = "tabControl_Data"; this.tabControl_Data.SelectedIndex = 0; this.tabControl_Data.ShowToolTips = true; this.tabControl_Data.Size = new System.Drawing.Size( 529, 456 ); this.tabControl_Data.TabIndex = 0; // // tabPage_Locals // this.tabPage_Locals.Controls.Add( this.localsView1 ); this.tabPage_Locals.Location = new System.Drawing.Point( 4, 22 ); this.tabPage_Locals.Name = "tabPage_Locals"; this.tabPage_Locals.Padding = new System.Windows.Forms.Padding( 3 ); this.tabPage_Locals.Size = new System.Drawing.Size( 521, 430 ); this.tabPage_Locals.TabIndex = 1; this.tabPage_Locals.Text = "Locals"; this.tabPage_Locals.UseVisualStyleBackColor = true; // // localsView1 // this.localsView1.AutoScroll = true; this.localsView1.Dock = System.Windows.Forms.DockStyle.Fill; this.localsView1.Location = new System.Drawing.Point( 3, 3 ); this.localsView1.Name = "localsView1"; this.localsView1.Size = new System.Drawing.Size( 515, 424 ); this.localsView1.TabIndex = 0; // // tabPage_Registers // this.tabPage_Registers.Controls.Add( this.registersView1 ); this.tabPage_Registers.Location = new System.Drawing.Point( 4, 22 ); this.tabPage_Registers.Name = "tabPage_Registers"; this.tabPage_Registers.Padding = new System.Windows.Forms.Padding( 3 ); this.tabPage_Registers.Size = new System.Drawing.Size( 521, 430 ); this.tabPage_Registers.TabIndex = 2; this.tabPage_Registers.Text = "Registers"; this.tabPage_Registers.UseVisualStyleBackColor = true; // // registersView1 // this.registersView1.AutoScroll = true; this.registersView1.Dock = System.Windows.Forms.DockStyle.Fill; this.registersView1.Location = new System.Drawing.Point( 3, 3 ); this.registersView1.Name = "registersView1"; this.registersView1.Size = new System.Drawing.Size( 515, 424 ); this.registersView1.TabIndex = 0; // // tabPage_StackTrace // this.tabPage_StackTrace.Controls.Add( this.stackTraceView1 ); this.tabPage_StackTrace.Location = new System.Drawing.Point( 4, 22 ); this.tabPage_StackTrace.Name = "tabPage_StackTrace"; this.tabPage_StackTrace.Padding = new System.Windows.Forms.Padding( 3 ); this.tabPage_StackTrace.Size = new System.Drawing.Size( 521, 430 ); this.tabPage_StackTrace.TabIndex = 3; this.tabPage_StackTrace.Text = "Stack Trace"; this.tabPage_StackTrace.ToolTipText = "Use Ctrl+Up and Ctrl+Down to switch between stack frames"; this.tabPage_StackTrace.UseVisualStyleBackColor = true; // // stackTraceView1 // this.stackTraceView1.AutoScroll = true; this.stackTraceView1.AutoSize = true; this.stackTraceView1.AutoSizeMode = System.Windows.Forms.AutoSizeMode.GrowAndShrink; this.stackTraceView1.Dock = System.Windows.Forms.DockStyle.Fill; this.stackTraceView1.Location = new System.Drawing.Point( 3, 3 ); this.stackTraceView1.Name = "stackTraceView1"; this.stackTraceView1.Size = new System.Drawing.Size( 515, 424 ); this.stackTraceView1.TabIndex = 0; // // tabPage_Threads // this.tabPage_Threads.Controls.Add( this.threadsView1 ); this.tabPage_Threads.Location = new System.Drawing.Point( 4, 22 ); this.tabPage_Threads.Name = "tabPage_Threads"; this.tabPage_Threads.Padding = new System.Windows.Forms.Padding( 3 ); this.tabPage_Threads.Size = new System.Drawing.Size( 521, 430 ); this.tabPage_Threads.TabIndex = 4; this.tabPage_Threads.Text = "Threads"; this.tabPage_Threads.UseVisualStyleBackColor = true; // // threadsView1 // this.threadsView1.AutoScroll = true; this.threadsView1.AutoSize = true; this.threadsView1.AutoSizeMode = System.Windows.Forms.AutoSizeMode.GrowAndShrink; this.threadsView1.Dock = System.Windows.Forms.DockStyle.Fill; this.threadsView1.Location = new System.Drawing.Point( 3, 3 ); this.threadsView1.Name = "threadsView1"; this.threadsView1.Size = new System.Drawing.Size( 515, 424 ); this.threadsView1.TabIndex = 0; // // tabPage_Memory // this.tabPage_Memory.Controls.Add( this.memoryView1 ); this.tabPage_Memory.Location = new System.Drawing.Point( 4, 22 ); this.tabPage_Memory.Name = "tabPage_Memory"; this.tabPage_Memory.Padding = new System.Windows.Forms.Padding( 3 ); this.tabPage_Memory.Size = new System.Drawing.Size( 521, 430 ); this.tabPage_Memory.TabIndex = 5; this.tabPage_Memory.Text = "Memory"; this.tabPage_Memory.UseVisualStyleBackColor = true; // // memoryView1 // this.memoryView1.AutoSize = true; this.memoryView1.AutoSizeMode = System.Windows.Forms.AutoSizeMode.GrowAndShrink; this.memoryView1.Dock = System.Windows.Forms.DockStyle.Fill; this.memoryView1.Location = new System.Drawing.Point( 3, 3 ); this.memoryView1.Name = "memoryView1"; this.memoryView1.Size = new System.Drawing.Size( 515, 424 ); this.memoryView1.TabIndex = 0; // // tabPage_Breakpoints // this.tabPage_Breakpoints.Controls.Add( this.breakpointsView1 ); this.tabPage_Breakpoints.Location = new System.Drawing.Point( 4, 22 ); this.tabPage_Breakpoints.Name = "tabPage_Breakpoints"; this.tabPage_Breakpoints.Padding = new System.Windows.Forms.Padding( 3 ); this.tabPage_Breakpoints.Size = new System.Drawing.Size( 521, 430 ); this.tabPage_Breakpoints.TabIndex = 6; this.tabPage_Breakpoints.Text = "Breakpoints"; this.tabPage_Breakpoints.UseVisualStyleBackColor = true; // // breakpointsView1 // this.breakpointsView1.AutoScroll = true; this.breakpointsView1.AutoSize = true; this.breakpointsView1.AutoSizeMode = System.Windows.Forms.AutoSizeMode.GrowAndShrink; this.breakpointsView1.Dock = System.Windows.Forms.DockStyle.Fill; this.breakpointsView1.Location = new System.Drawing.Point( 3, 3 ); this.breakpointsView1.Name = "breakpointsView1"; this.breakpointsView1.Size = new System.Drawing.Size( 515, 424 ); this.breakpointsView1.TabIndex = 0; // // sessionSaveFileDialog // this.sessionSaveFileDialog.Filter = "Zelig Debug Session|*.ZeligDebugSession"; this.sessionSaveFileDialog.Title = "Save Session"; // // sessionOpenFileDialog // this.sessionOpenFileDialog.Filter = "Zelig Debug Session|*.ZeligDebugSession"; this.sessionOpenFileDialog.Title = "Open Session"; // // toolStripButton_ToggleWrapper // this.toolStripButton_ToggleWrapper.DisplayStyle = System.Windows.Forms.ToolStripItemDisplayStyle.Image; this.toolStripButton_ToggleWrapper.Image = ((System.Drawing.Image)(resources.GetObject( "toolStripButton_ToggleWrapper.Image" ))); this.toolStripButton_ToggleWrapper.ImageTransparentColor = System.Drawing.Color.Magenta; this.toolStripButton_ToggleWrapper.Name = "toolStripButton_ToggleWrapper"; this.toolStripButton_ToggleWrapper.Size = new System.Drawing.Size( 23, 22 ); this.toolStripButton_ToggleWrapper.Text = "toolStripButton1"; this.toolStripButton_ToggleWrapper.Click += new System.EventHandler( this.toolStripButton_ToggleWrapper_Click ); // // DebuggerMainForm // this.AutoScaleDimensions = new System.Drawing.SizeF( 6F, 13F ); this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font; this.ClientSize = new System.Drawing.Size( 1006, 533 ); this.Controls.Add( this.toolStrip1 ); this.Controls.Add( this.splitContainer1 ); this.Controls.Add( this.statusStrip1 ); this.Controls.Add( this.menuStrip1 ); this.DoubleBuffered = true; this.KeyPreview = true; this.MainMenuStrip = this.menuStrip1; this.Name = "DebuggerMainForm"; this.Text = "Zelig Debugger"; this.Load += new System.EventHandler( this.DebuggerMainForm_Load ); this.FormClosing += new System.Windows.Forms.FormClosingEventHandler( this.DebuggerMainForm_FormClosing ); this.KeyDown += new System.Windows.Forms.KeyEventHandler( this.DebuggerMainForm_KeyDown ); this.menuStrip1.ResumeLayout( false ); this.menuStrip1.PerformLayout(); this.statusStrip1.ResumeLayout( false ); this.statusStrip1.PerformLayout(); this.toolStrip1.ResumeLayout( false ); this.toolStrip1.PerformLayout(); this.splitContainer1.Panel1.ResumeLayout( false ); this.splitContainer1.Panel2.ResumeLayout( false ); this.splitContainer1.ResumeLayout( false ); this.tabControl_Data.ResumeLayout( false ); this.tabPage_Locals.ResumeLayout( false ); this.tabPage_Registers.ResumeLayout( false ); this.tabPage_StackTrace.ResumeLayout( false ); this.tabPage_StackTrace.PerformLayout(); this.tabPage_Threads.ResumeLayout( false ); this.tabPage_Threads.PerformLayout(); this.tabPage_Memory.ResumeLayout( false ); this.tabPage_Memory.PerformLayout(); this.tabPage_Breakpoints.ResumeLayout( false ); this.tabPage_Breakpoints.PerformLayout(); this.ResumeLayout( false ); this.PerformLayout(); } #endregion private CodeView codeView1; private LocalsView localsView1; private RegistersView registersView1; private StackTraceView stackTraceView1; private ThreadsView threadsView1; private BreakpointsView breakpointsView1; private MemoryView memoryView1; private System.Windows.Forms.MenuStrip menuStrip1; private System.Windows.Forms.ToolStripMenuItem toolStripMenuItem_File; private System.Windows.Forms.ToolStripSeparator toolStripSeparator4; private System.Windows.Forms.ToolStripMenuItem toolStripMenuItem_File_Open; private System.Windows.Forms.ToolStripMenuItem toolStripMenuItem_File_Open_Image; private System.Windows.Forms.ToolStripMenuItem toolStripMenuItem_File_Open_Session; private System.Windows.Forms.ToolStripMenuItem toolStripMenuItem_File_Session; private System.Windows.Forms.ToolStripMenuItem toolStripMenuItem_File_Session_Load; private System.Windows.Forms.ToolStripMenuItem toolStripMenuItem_File_Session_Edit; private System.Windows.Forms.ToolStripMenuItem toolStripMenuItem_File_Session_Save; private System.Windows.Forms.ToolStripMenuItem toolStripMenuItem_File_Session_SaveAs; private System.Windows.Forms.ToolStripSeparator toolStripSeparator1; private System.Windows.Forms.ToolStripMenuItem toolStripMenuItem_File_Exit; private System.Windows.Forms.ToolStripMenuItem toolStripMenuItem_Tools; private System.Windows.Forms.ToolStripMenuItem toolStripMenuItem_Tools_SessionManager; private System.Windows.Forms.ToolStripMenuItem toolStripMenuItem_Tools_Customize; private System.Windows.Forms.ToolStripMenuItem toolStripMenuItem_Tools_Options; private System.Windows.Forms.ToolStripMenuItem toolStripMenuItem_Help; private System.Windows.Forms.ToolStripMenuItem toolStripMenuItem_Help_Contents; private System.Windows.Forms.ToolStripMenuItem toolStripMenuItem_Help_Index; private System.Windows.Forms.ToolStripMenuItem toolStripMenuItem_Help_Search; private System.Windows.Forms.ToolStripSeparator toolStripSeparator5; private System.Windows.Forms.ToolStripMenuItem toolStripMenuItem_Help_About; private System.Windows.Forms.ToolStripMenuItem toolStripMenuItem_Windows; private System.Windows.Forms.StatusStrip statusStrip1; private System.Windows.Forms.SplitContainer splitContainer1; private System.Windows.Forms.TabControl tabControl_Data; private System.Windows.Forms.TabPage tabPage_Locals; private System.Windows.Forms.TabPage tabPage_Registers; private System.Windows.Forms.TabPage tabPage_StackTrace; private System.Windows.Forms.TabPage tabPage_Threads; private System.Windows.Forms.TabPage tabPage_Memory; private System.Windows.Forms.TabPage tabPage_Breakpoints; private System.Windows.Forms.ToolStrip toolStrip1; private System.Windows.Forms.ToolStripButton toolStripButton_Open; private System.Windows.Forms.ToolStripSeparator toolStripSeparator; private System.Windows.Forms.ToolStripButton toolStripButton_Start; private System.Windows.Forms.ToolStripButton toolStripButton_ShowNextStatement; private System.Windows.Forms.ToolStripButton toolStripButton_StopDebugging; private System.Windows.Forms.ToolStripButton toolStripButton_Restart; private System.Windows.Forms.ToolStripSeparator toolStripSeparator2; private System.Windows.Forms.ToolStripButton toolStripButton_BreakAll; private System.Windows.Forms.ToolStripButton toolStripButton_StepInto; private System.Windows.Forms.ToolStripButton toolStripButton_StepOver; private System.Windows.Forms.ToolStripButton toolStripButton_StepOut; private System.Windows.Forms.ToolStripSeparator toolStripSeparator3; private System.Windows.Forms.ToolStripButton toolStripButton_ToggleDisassembly; private System.Windows.Forms.ToolStripSeparator toolStripSeparator6; private System.Windows.Forms.ToolStripStatusLabel toolStripStatus_ExecutionState; private System.Windows.Forms.ToolStripStatusLabel toolStripStatus_CurrentMethod; private System.Windows.Forms.ToolStripStatusLabel toolStripStatus_AbsoluteTime; private System.Windows.Forms.OpenFileDialog imageOpenFileDialog; private System.Windows.Forms.SaveFileDialog sessionSaveFileDialog; private System.Windows.Forms.OpenFileDialog sessionOpenFileDialog; private System.Windows.Forms.ToolStripSeparator toolStripSeparator_Files; private System.Windows.Forms.ToolStripMenuItem toolStripMenuItem_View; private System.Windows.Forms.ToolStripSeparator toolStripSeparator_Tools_Top; private System.Windows.Forms.ToolStripSeparator toolStripSeparator_Tools_Bottom; private System.Windows.Forms.ToolStripButton toolStripButton_ToggleWrapper; } } ================================================ FILE: Zelig/Zelig/DebugTime/Debugger/Forms/DebuggerMainForm.Worker.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // namespace Microsoft.Zelig.Debugger.ArmProcessor { using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Text; using System.IO; using System.Windows.Forms; using System.Threading; using IR = Microsoft.Zelig.CodeGeneration.IR; using RT = Microsoft.Zelig.Runtime; using TS = Microsoft.Zelig.Runtime.TypeSystem; using Hst = Microsoft.Zelig.Emulation.Hosting; public partial class DebuggerMainForm : Form { private delegate void WorkerWorkItem(); private delegate void WorkerWorkItemReply( Emulation.Hosting.Forms.HostingSite.ExecutionState state, WorkerWorkItem msg ); // // Helper Methods // private void ExecuteInWorkerThread( Emulation.Hosting.Forms.HostingSite.ExecutionState state , WorkerWorkItem msg ) { if(state == Hst.Forms.HostingSite.ExecutionState.Running) { EnteringState_Running(); } if(state != Hst.Forms.HostingSite.ExecutionState.Invalid) { UpdateExecutionState( state ); } lock(m_processorWorkerRequests) { m_processorWorkerRequests.Enqueue( msg ); m_processorWorkerSignal.Set(); } } private void ExecuteInFormThread( WorkerWorkItem msg ) { ExecuteInFormThread( Hst.Forms.HostingSite.ExecutionState.Invalid, msg ); } private void ExecuteInFormThread( Emulation.Hosting.Forms.HostingSite.ExecutionState state , WorkerWorkItem msg ) { if(this.InvokeRequired) { WorkerWorkItemReply dlg = ReplyFromWorker; this.BeginInvoke( dlg, state, msg ); } else { ReplyFromWorker( state, msg ); } } private void ReplyFromWorker( Emulation.Hosting.Forms.HostingSite.ExecutionState state , WorkerWorkItem msg ) { if(msg != null) { msg(); } if(state != Hst.Forms.HostingSite.ExecutionState.Invalid) { UpdateExecutionState( state ); } if(m_fFullyInitialized == false) { m_fFullyInitialized = true; FullyInitialized(); } } private void ProcessorWorker() { ExecuteInFormThread( Hst.Forms.HostingSite.ExecutionState.Idle, null ); while(true) { m_processorWorkerSignal.WaitOne(); while(true) { WorkerWorkItem msg; lock(this) { if(m_processorWorkerRequests.Count == 0) { break; } msg = m_processorWorkerRequests.Dequeue(); } msg(); if(m_processorWorkerExit) { try { Emulation.Hosting.ProcessorControl svcPC; if(m_processorHost.GetHostingService( out svcPC )) { svcPC.Shutdown(); } } catch { } return; } } } } } } ================================================ FILE: Zelig/Zelig/DebugTime/Debugger/Forms/DebuggerMainForm.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // namespace Microsoft.Zelig.Debugger.ArmProcessor { using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Text; using System.IO; using System.Windows.Forms; using System.Threading; using IR = Microsoft.Zelig.CodeGeneration.IR; using RT = Microsoft.Zelig.Runtime; using TS = Microsoft.Zelig.Runtime.TypeSystem; using Cfg = Microsoft.Zelig.Configuration.Environment; using Hst = Microsoft.Zelig.Emulation.Hosting; public partial class DebuggerMainForm : Form, IMainForm { class ViewEntry { // // State // internal readonly Hst.Forms.BaseDebuggerForm Form; internal readonly Hst.Forms.HostingSite.PublicationMode Mode; internal readonly ToolStripMenuItem MenuItem; // // Constructor Methods // internal ViewEntry( Hst.Forms.BaseDebuggerForm form , Hst.Forms.HostingSite.PublicationMode mode ) { var item = new ToolStripMenuItem(); this.Mode = mode; this.Form = form; this.MenuItem = item; //--// var image = form.ViewImage; var title = form.ViewTitle; item.Text = (title != null) ? title : form.GetType().FullName; item.DisplayStyle = (image != null) ? ToolStripItemDisplayStyle.ImageAndText : ToolStripItemDisplayStyle.Text; item.Image = image; item.Tag = this; item.ImageAlign = ContentAlignment.MiddleLeft; item.TextAlign = ContentAlignment.MiddleRight; item.Click += new System.EventHandler( delegate( object sender, EventArgs e ) { if(this.MenuItem.Checked) { this.Form.Hide(); } else { this.Form.Show(); } } ); } // // Helper Methods // internal static ViewEntry Find( List< ViewEntry > lst , Hst.Forms.BaseDebuggerForm form , Hst.Forms.HostingSite.PublicationMode mode ) { foreach(var item in lst) { if(item.Form == form && item.Mode == mode) { return item; } } return null; } } class HostingSiteImpl : Hst.Forms.HostingSite { // // State // DebuggerMainForm m_owner; // // Constructor Methods // internal HostingSiteImpl( DebuggerMainForm owner ) { m_owner = owner; } // // Helper Methods // public override void ProcessKeyDownEvent( KeyEventArgs e ) { m_owner.ProcessKeyDownEvent( e ); } public override void ProcessKeyUpEvent( KeyEventArgs e ) { m_owner.ProcessKeyUpEvent( e ); } public override void ReportFormStatus( Hst.Forms.BaseDebuggerForm form , bool fOpened ) { m_owner.ReportFormStatus( form, fOpened ); } public override void RegisterView( Hst.Forms.BaseDebuggerForm form , Hst.Forms.HostingSite.PublicationMode mode ) { m_owner.RegisterView( form, mode ); } public override void UnregisterView( Hst.Forms.BaseDebuggerForm form , Hst.Forms.HostingSite.PublicationMode mode ) { m_owner.UnregisterView( form, mode ); } public override void VisualizeDebugInfo( Debugging.DebugInfo di ) { m_owner.VisualizeDebugInfo( di ); } public override object GetHostingService( Type t ) { return m_owner.Host.GetHostingService( t ); } public override void RegisterService( Type type , object impl ) { m_owner.Host.RegisterService( type, impl ); } public override void UnregisterService( object impl ) { m_owner.Host.UnregisterService( impl ); } // // Access Methods // public override bool IsIdle { get { return m_owner.IsIdle; } } } class ApplicationArguments { // // State // internal string[] m_arguments; internal string m_sessionName; internal string m_sessionFile; internal string m_imageFile; internal List< string > m_breakpoints = new List< string >(); internal List< System.Reflection.Assembly > m_asssemblies = new List< System.Reflection.Assembly >(); internal List< Type > m_handlers = new List< Type >(); // // Constructor Methods // internal ApplicationArguments( string[] args ) { m_arguments = args; } // // Helper Methods // internal bool Parse() { return Parse( m_arguments ); } private bool Parse( string line ) { List< string > args = new List< string >(); for(int pos = 0; pos < line.Length; ) { char c = line[pos++]; switch(c) { case ' ': case '\t': break; case '\'': case '"': { StringBuilder sb = new StringBuilder(); int pos2 = pos; bool fAdd = false; while(pos2 < line.Length) { char c2 = line[pos2++]; if(fAdd == false) { if(c2 == c) { break; } if(c2 == '\\') { fAdd = true; continue; } } sb.Append( c2 ); fAdd = false; } pos = pos2; args.Add( sb.ToString() ); } break; default: { StringBuilder sb = new StringBuilder(); int pos2 = pos; sb.Append( c ); while(pos2 < line.Length) { char c2 = line[pos2++]; if(c2 == ' ' || c2 == '\t' ) { break; } sb.Append( c2 ); } pos = pos2; args.Add( sb.ToString() ); } break; } } if(args.Count == 0) { return true; } return Parse( args.ToArray() ); } private bool Parse( string[] args ) { if(args != null) { for(int i = 0; i < args.Length; i++) { string arg = args[i]; if(arg == string.Empty) { continue; } if(arg.StartsWith( "/" ) || arg.StartsWith( "-" ) ) { string option = arg.Substring( 1 ); if(IsMatch( option, "Cfg" )) { string file; if(!GetArgument( arg, args, true, ref i, out file )) { return false; } using(System.IO.StreamReader stream = new System.IO.StreamReader( file )) { string line; while((line = stream.ReadLine()) != null) { if(line.StartsWith( "#" )) { continue; } if(Parse( line ) == false) { return false; } } } } else if(IsMatch( option, "Session" )) { if(!GetArgument( arg, args, false, ref i, out m_sessionName )) { return false; } } else if(IsMatch( option, "SessionFile" )) { if(!GetArgument( arg, args, true, ref i, out m_sessionFile )) { return false; } } else if(IsMatch( option, "ImageFile" )) { if(!GetArgument( arg, args, true, ref i, out m_imageFile )) { return false; } } else if(IsMatch( option, "Breakpoint" )) { string str; if(!GetArgument( arg, args, false, ref i, out str )) { return false; } m_breakpoints.Add( str ); } else if(IsMatch( option, "LoadAssembly" )) { string file; if(!GetArgument( arg, args, true, ref i, out file )) { return false; } try { m_asssemblies.Add( System.Reflection.Assembly.LoadFrom( file ) ); // // The plug-ins will come from a different directory structure. // But the loader won't resolve assembly names to assemblies outside the application directory structure, // even if the assemblies are already loaded in the current AppDomain. // // Let's register with the AppDomain, so we can check if an assembly has already been loaded, and // just override the loader policy. // if(m_asssemblies.Count == 1) { AppDomain.CurrentDomain.AssemblyResolve += delegate( object sender, ResolveEventArgs args2 ) { foreach(System.Reflection.Assembly asm in AppDomain.CurrentDomain.GetAssemblies()) { if(asm.FullName == args2.Name) { return asm; } } return null; }; } } catch(Exception ex) { MessageBox.Show( string.Format( "Exception caught while loading assembly from file {0}:\r\n{1}", file, ex ), "Type Load Error", MessageBoxButtons.OK ); return false; } } else if(IsMatch( option, "AddHandler" )) { string cls; if(!GetArgument( arg, args, false, ref i, out cls )) { return false; } Type t = Type.GetType( cls ); if(t == null) { foreach(System.Reflection.Assembly asm in AppDomain.CurrentDomain.GetAssemblies()) { t = asm.GetType( cls ); if(t != null) { break; } } } if(t == null) { MessageBox.Show( string.Format( "Cannot find type for handler '{0}'", cls ), "Type Load Error", MessageBoxButtons.OK ); return false; } m_handlers.Add( t ); } //// else if(IsMatch( option, "DumpIR" )) //// { //// m_fDumpIR = true; //// } //// else if(IsMatch( option, "DumpASM" )) //// { //// m_fDumpASM = true; //// } //// else if(IsMatch( option, "DumpHEX" )) //// { //// m_fDumpHEX = true; //// } else { MessageBox.Show( string.Format( "Unrecognized option: {0}", option ) ); return false; } } //// else //// { //// arg = Expand( arg ); //// if(File.Exists( arg ) == false) //// { //// Console.WriteLine( "Cannot find '{0}'", arg ); //// return false; //// } //// //// if(m_targetFile != null) //// { //// Console.WriteLine( "ERROR: Only one target file per compilation." ); //// } //// //// m_targetFile = arg; //// //// m_searchOrder.Insert( 0, System.IO.Path.GetDirectoryName( arg ) ); //// } } return true; } return false; } private static bool IsMatch( string arg , string cmd ) { return arg.ToUpper().CompareTo( cmd.ToUpper() ) == 0; } private static bool GetArgument( string arg , string[] args , bool fExpandEnvVar , ref int i , out string value ) { if(i + 1 < args.Length) { i++; value = args[i]; if(fExpandEnvVar) { value = Expand( value ); } return true; } MessageBox.Show( string.Format( "Option '{0}' needs an argument", arg ) ); value = null; return false; } private static string Expand( string str ) { return Environment.ExpandEnvironmentVariables( str ); } } //--// const int c_visualEffect_Depth_CurrentStatement = 1; const int c_visualEffect_Depth_OnTheStackTrace = 2; const int c_visualEffect_Depth_Breakpoint = 3; const int c_visualEffect_Depth_Disassembly = 4; const int c_visualEffect_Depth_Profile = 5; // // State // ApplicationArguments m_arguments; bool m_fFullyInitialized; ProfilerMainForm m_profilerForm; DisplayForm m_displayForm; OutputForm m_outputForm; EnvironmentForm m_environmentForm; SessionManagerForm m_sessionManagerForm; List< Hst.AbstractUIPlugIn > m_plugIns = new List< Hst.AbstractUIPlugIn >(); Hst.Forms.HostingSite.ExecutionState m_currentState; HostingSiteImpl m_hostingSiteImpl; ProcessorHost m_processorHost; int m_versionBreakpoints; ulong m_baseSample_clockTicks; ulong m_baseSample_nanoseconds; ulong m_currentSample_clockTicks; ulong m_currentSample_nanoseconds; ulong m_lastSample_clockTicks; ulong m_lastSample_nanoseconds; ImageInformation m_imageInformation; int m_versionStackTrace; List< ThreadStatus > m_threads; ThreadStatus m_activeThread; ThreadStatus m_selectedThread; Thread m_processorWorker; AutoResetEvent m_processorWorkerSignal; Queue< WorkerWorkItem > m_processorWorkerRequests; bool m_processorWorkerExit; DebugGarbageColllection m_debugGC; //--// List< VisualTreeInfo > m_visualTreesList; List< ViewEntry > m_viewEntriesList; //--// Session m_currentSession; Cfg.Manager m_configurationManager; Brush m_brush_CurrentPC = new SolidBrush( Color.FromArgb( 255, 238, 98 ) ); Brush m_brush_PastPC = new SolidBrush( Color.FromArgb( 180, 228, 180 ) ); Brush m_brush_Breakpoint = new SolidBrush( Color.FromArgb( 150, 58, 70 ) ); Pen m_pen_Breakpoint = new Pen ( Color.FromArgb( 150, 58, 70 ) ); Icon m_icon_Breakpoint = Properties.Resources.Breakpoint; Icon m_icon_BreakpointDisabled = Properties.Resources.BreakpointDisabled; Icon m_icon_CurrentStatement = Properties.Resources.CurrentStatement; Icon m_icon_StackFrame = Properties.Resources.StackFrame; //--// public bool DebugGC = false; public bool DebugGCVerbose = false; //--// // // Constructor Methods // public DebuggerMainForm( string[] args ) { InitializeComponent(); //--// m_arguments = new ApplicationArguments( args ); m_configurationManager = new Cfg.Manager(); m_configurationManager.AddAllAssemblies( null ); m_configurationManager.ComputeAllPossibleValuesForFields(); //--// m_currentState = Hst.Forms.HostingSite.ExecutionState.Invalid; m_threads = new List< ThreadStatus >(); m_processorWorker = new Thread( ProcessorWorker ); m_processorWorkerSignal = new AutoResetEvent( false ); m_processorWorkerRequests = new Queue< WorkerWorkItem >(); m_visualTreesList = new List< VisualTreeInfo >(); m_viewEntriesList = new List< ViewEntry >(); //--// m_hostingSiteImpl = new HostingSiteImpl( this ); m_processorHost = new ProcessorHost ( this ); m_profilerForm = new ProfilerMainForm ( m_hostingSiteImpl ); m_displayForm = new DisplayForm ( m_hostingSiteImpl ); m_outputForm = new OutputForm ( m_hostingSiteImpl ); m_environmentForm = new EnvironmentForm ( this ); m_sessionManagerForm = new SessionManagerForm( this ); //--// codeView1.DefaultHitSink = codeView1_HitSink; localsView1 .Link( this ); stackTraceView1 .Link( this ); threadsView1 .Link( this ); registersView1 .Link( this ); breakpointsView1.Link( this ); memoryView1 .Link( this ); } // // Helper Methods // private void FullyInitialized() { if(m_arguments.Parse() == false) { Application.Exit(); } string name = m_arguments.m_sessionName; if(name != null) { m_currentSession = m_sessionManagerForm.FindSession( name ); if(m_currentSession == null) { MessageBox.Show( string.Format( "Cannot find session '{0}'", name ) ); Application.Exit(); } } string file = m_arguments.m_sessionFile; if(file != null) { m_currentSession = m_sessionManagerForm.LoadSession( file, true ); if(m_currentSession == null) { MessageBox.Show( string.Format( "Cannot load session file '{0}'", file ) ); Application.Exit(); } } if(m_currentSession != null) { m_sessionManagerForm.SelectSession( m_currentSession ); if(m_arguments.m_imageFile != null) { m_currentSession.ImageToLoad = m_arguments.m_imageFile; } } foreach(Type t in m_arguments.m_handlers) { if(t.IsSubclassOf( typeof(Hst.AbstractUIPlugIn) )) { Hst.AbstractUIPlugIn plugIn = (Hst.AbstractUIPlugIn)Activator.CreateInstance( t, m_hostingSiteImpl ); m_plugIns.Add( plugIn ); plugIn.Start(); } } if(m_currentSession == null) { m_currentSession = m_sessionManagerForm.SelectSession( true ); } if(m_arguments.m_breakpoints.Count > 0) { m_hostingSiteImpl.NotifyOnExecutionStateChange += delegate( Hst.Forms.HostingSite host, Hst.Forms.HostingSite.ExecutionState oldState, Hst.Forms.HostingSite.ExecutionState newState ) { if(newState != Hst.Forms.HostingSite.ExecutionState.Loaded) { return Hst.Forms.HostingSite.NotificationResponse.DoNothing; } tabControl_Data.SelectedTab = tabPage_Breakpoints; foreach(string breakpoint in m_arguments.m_breakpoints) { breakpointsView1.Set( breakpoint ); } return Hst.Forms.HostingSite.NotificationResponse.RemoveFromNotificationList; }; } m_hostingSiteImpl.NotifyOnExecutionStateChange += delegate( Hst.Forms.HostingSite host, Hst.Forms.HostingSite.ExecutionState oldState, Hst.Forms.HostingSite.ExecutionState newState ) { if(newState == Hst.Forms.HostingSite.ExecutionState.Loaded) { Action_ResetAbsoluteTime(); } if(newState == Hst.Forms.HostingSite.ExecutionState.Paused) { if(m_processorHost.GetAbsoluteTime( out m_currentSample_clockTicks, out m_currentSample_nanoseconds )) { DisplayExecutionTime(); } else { toolStripStatus_AbsoluteTime.Text = ""; } } else { m_lastSample_clockTicks = m_currentSample_clockTicks; m_lastSample_nanoseconds = m_currentSample_nanoseconds; toolStripStatus_AbsoluteTime.Text = ""; } return Hst.Forms.HostingSite.NotificationResponse.DoNothing; }; m_hostingSiteImpl.NotifyOnVisualizationEvent += delegate( Hst.Forms.HostingSite host, Hst.Forms.HostingSite.VisualizationEvent e ) { switch(e) { case Hst.Forms.HostingSite.VisualizationEvent.NewStackFrame: UpdateCurrentMethod(); break; } return Hst.Forms.HostingSite.NotificationResponse.DoNothing; }; InnerAction_LoadImage(); } private void UpdateCurrentMethod() { string txt = ""; while(true) { var th = m_selectedThread ; if(th == null) break; var stackFrame = m_selectedThread.StackFrame; if(stackFrame == null) break; var cm = stackFrame.CodeMapOfTarget ; if(cm == null) break; var md = cm.Target ; if(md == null) break; txt = string.Format( "{0}", md.ToShortString() ); break; } toolStripStatus_CurrentMethod.Text = txt; } //--// public static void SetPanelHeight( Panel panel , int height ) { Size size = panel.Size; if(size.Height != height) { size.Height = height; panel.Size = size; } } internal void ReportFormStatus( Form form , bool fOpened ) { foreach(var item in m_viewEntriesList) { if(item.Form == form) { item.MenuItem.Checked = fOpened; } } } private void RegisterView( Hst.Forms.BaseDebuggerForm form , Hst.Forms.HostingSite.PublicationMode mode ) { if(ViewEntry.Find( m_viewEntriesList, form, mode ) == null) { var item = new ViewEntry( form, mode ); m_viewEntriesList.Add( item ); switch(mode) { case Hst.Forms.HostingSite.PublicationMode.Window: { var items = this.toolStripMenuItem_Windows.DropDownItems; var index = items.IndexOf( this.toolStripSeparator_Files ); items.Insert( index, item.MenuItem ); } break; case Hst.Forms.HostingSite.PublicationMode.View: { var items = this.toolStripMenuItem_View.DropDownItems; items.Add( item.MenuItem ); } break; case Hst.Forms.HostingSite.PublicationMode.Tools: { var items = this.toolStripMenuItem_Tools.DropDownItems; var indexTop = items.IndexOf( this.toolStripSeparator_Tools_Top ); var indexBottom = items.IndexOf( this.toolStripSeparator_Tools_Bottom ); items.Insert( indexBottom, item.MenuItem ); this.toolStripSeparator_Tools_Bottom.Visible = true; } break; } } } private void UnregisterView( Hst.Forms.BaseDebuggerForm form , Hst.Forms.HostingSite.PublicationMode mode ) { var item = ViewEntry.Find( m_viewEntriesList, form, mode ); if(item != null) { m_viewEntriesList.Remove( item ); var menu = item.MenuItem; var menuOwner = (ToolStripMenuItem)menu.OwnerItem; menuOwner.DropDownItems.Remove( menu ); switch(mode) { case Hst.Forms.HostingSite.PublicationMode.Window: { var items = this.toolStripMenuItem_Windows.DropDownItems; var index = items.IndexOf( this.toolStripSeparator_Files ); if(index == 0) { this.toolStripSeparator_Files.Visible = false; } } break; case Hst.Forms.HostingSite.PublicationMode.View: { } break; case Hst.Forms.HostingSite.PublicationMode.Tools: { var items = this.toolStripMenuItem_Tools.DropDownItems; var indexTop = items.IndexOf( this.toolStripSeparator_Tools_Top ); var indexBottom = items.IndexOf( this.toolStripSeparator_Tools_Bottom ); if(indexTop + 1 == indexBottom) { this.toolStripSeparator_Tools_Bottom.Visible = false; } } break; } } } //--// private void SetWaitCursor( Hst.Forms.HostingSite.ExecutionState state ) { switch(state) { case Hst.Forms.HostingSite.ExecutionState.Idle : case Hst.Forms.HostingSite.ExecutionState.Loaded : case Hst.Forms.HostingSite.ExecutionState.Running: case Hst.Forms.HostingSite.ExecutionState.Paused : this.UseWaitCursor = false; break; default: this.UseWaitCursor = false; break; } } private void UpdateExecutionState( Hst.Forms.HostingSite.ExecutionState state ) { toolStripButton_Start .Enabled = state == Hst.Forms.HostingSite.ExecutionState.Loaded || state == Hst.Forms.HostingSite.ExecutionState.Paused ; toolStripButton_BreakAll .Enabled = state == Hst.Forms.HostingSite.ExecutionState.Running; toolStripButton_StopDebugging .Enabled = state == Hst.Forms.HostingSite.ExecutionState.Paused || state == Hst.Forms.HostingSite.ExecutionState.Running; toolStripButton_ShowNextStatement.Enabled = state == Hst.Forms.HostingSite.ExecutionState.Paused ; toolStripButton_Restart .Enabled = state == Hst.Forms.HostingSite.ExecutionState.Paused ; toolStripButton_StepInto .Enabled = state == Hst.Forms.HostingSite.ExecutionState.Loaded || state == Hst.Forms.HostingSite.ExecutionState.Paused ; toolStripButton_StepOver .Enabled = state == Hst.Forms.HostingSite.ExecutionState.Paused ; toolStripButton_StepOut .Enabled = m_activeThread != null && m_activeThread.StackTrace.Count > 1; toolStripStatus_ExecutionState.Text = state.ToString(); SetWaitCursor( state ); var oldState = m_currentState; m_currentState = state; m_hostingSiteImpl.RaiseNotification( oldState, state ); } private void DisplayExecutionTime() { ulong diff_clockTicks = m_currentSample_clockTicks - m_lastSample_clockTicks; ulong diff_nanoseconds = m_currentSample_nanoseconds - m_lastSample_nanoseconds; ulong base_clockTicks = m_currentSample_clockTicks - m_baseSample_clockTicks; ulong base_nanoseconds = m_currentSample_nanoseconds - m_baseSample_nanoseconds; // // \u0393 = Greek Delta // \u00b5 = Greek micro // toolStripStatus_AbsoluteTime.Text = string.Format( "Clks={0} (\u0394={2}) \u00B5Sec={1} (\u0394={3})", base_clockTicks, (double)base_nanoseconds / 1000.0, diff_clockTicks, (double)diff_nanoseconds / 1000.0 ); } private void EnteringState_Running() { m_threads.Clear(); m_activeThread = null; m_selectedThread = null; ResetVisualEffects(); SwitchToFile( null, null ); } private void ExitingState_Running( Debugging.DebugInfo diTarget ) { if(m_imageInformation != null) { m_activeThread = ThreadStatus.Analyze( m_threads, m_processorHost.MemoryDelta, m_processorHost.Breakpoints ); m_selectedThread = m_activeThread; if(diTarget != null) { m_activeThread.TopStackFrame.MoveForwardToDebugInfo( diTarget ); } UpdateDisplay( true ); } } private void ProcessCodeCoverage() { Emulation.Hosting.CodeCoverage svc; if(m_processorHost.GetHostingService( out svc )) { if(svc.Enable) { m_imageInformation.CollectCodeCoverage( m_processorHost ); foreach(VisualTreeInfo vti in m_visualTreesList) { List < ImageInformation.RangeToSourceCode > lst; GrowOnlyHashTable< Debugging.DebugInfo, ulong > ht = HashTableFactory.New< Debugging.DebugInfo, ulong >(); if(m_imageInformation.FileToCodeLookup.TryGetValue( vti.Input.File.ToUpper(), out lst )) { foreach(ImageInformation.RangeToSourceCode rng in lst) { ImageInformation.RangeToSourceCode.CodeCoverage profile = rng.Profile; if(profile != null) { foreach(var pair in rng.DebugInfos) { ulong count; ht.TryGetValue( pair.Info, out count ); count += profile.Cycles; ht[pair.Info] = count; } } } } ulong max = 0; foreach(Debugging.DebugInfo di in ht.Keys) { max = Math.Max( ht[di], max ); } if(max != 0) { double scale = 1.0 / max; foreach(Debugging.DebugInfo di in ht.Keys) { double ratio = ht[di] * scale; Brush brush = new SolidBrush( Color.FromArgb( (int)(255 * ratio), 255, 0, 0 ) ); vti.HighlightSourceCode( codeView1, uint.MaxValue, di, null, null, brush, c_visualEffect_Depth_Profile ); } } } } } } //--// public bool LocateVisualTreeForDebugInfo( Debugging.DebugInfo di , out VisualTreeInfo vti , out VisualItem bringIntoView ) { vti = null; bringIntoView = null; if(di != null) { string file = di.SrcFileName; vti = codeView1.CreateVisualTree( m_imageInformation, file, file ); if(vti != null) { for(int lineNum = di.BeginLineNumber; lineNum <= di.EndLineNumber; lineNum++) { bringIntoView = vti.FindLine( lineNum ); if(bringIntoView != null) { break; } } return true; } } return false; } public void VisualizeFile( string file ) { VisualTreeInfo vti = codeView1.CreateVisualTree( m_imageInformation, file, file ); if(vti != null) { SwitchToFile( vti, null ); } } public void VisualizeDebugInfo( Debugging.DebugInfo di ) { VisualTreeInfo vti; VisualItem bringIntoView; if(LocateVisualTreeForDebugInfo( di, out vti, out bringIntoView )) { SwitchToFile( vti, bringIntoView ); this.BringToFront(); } } public void VisualizeStackFrame( StackFrame sf ) { VisualTreeInfo vti; VisualItem bringIntoView; m_selectedThread = sf.Thread; m_selectedThread.StackFrame = sf; LocateVisualTreeForDebugInfo( sf.DebugInfo, out vti, out bringIntoView ); PrepareDisplay( vti, sf, bringIntoView ); NotifyNewStackFrame(); } private void SwitchToFile( VisualTreeInfo vti , VisualItem bringIntoView ) { if(vti != null) { m_visualTreesList.Remove( vti ); m_visualTreesList.Insert( 0, vti ); UpdateCheckedStatusForFiles( vti ); codeView1.InstallVisualTree( vti, bringIntoView ); } else { codeView1.RefreshVisualTree(); } } private void UpdateCheckedStatusForFiles( VisualTreeInfo vti ) { ToolStripItemCollection coll = toolStripMenuItem_Windows.DropDownItems; // // Remove previous files. // int index = coll.IndexOf( this.toolStripSeparator_Files ); while(index + 1 < coll.Count) { coll.RemoveAt( index + 1 ); } // // Have separator only if there are open files. // this.toolStripSeparator_Files.Visible = index > 0 && (m_visualTreesList.Count != 0); for(int pos = 0; pos < m_visualTreesList.Count; pos++) { VisualTreeInfo vti2 = m_visualTreesList[pos]; ToolStripMenuItem newItem = new ToolStripMenuItem(); int fileIdx = pos + 1; IR.SourceCodeTracker.SourceCode srcFile = vti2.Input; newItem.Text = string.Format( fileIdx < 10 ? "&{0} {1}{2}" : "{0} {1}{2}", fileIdx, vti2.DisplayName, (srcFile != null && srcFile.UsingCachedValues) ? " " : "" ); newItem.Tag = vti2; newItem.Checked = (vti2 == vti); newItem.Click += new System.EventHandler( delegate( object sender, EventArgs e ) { SwitchToFile( vti2, null ); } ); coll.Add( newItem ); } } //--// private void UpdateDisplay( bool fProcessCodeCoverage ) { ResetVisualEffects(); if(fProcessCodeCoverage) { ProcessCodeCoverage(); } VisualTreeInfo switchToVti; VisualItem bringIntoView; CreateVisualEffects( out switchToVti, out bringIntoView ); PrepareDisplay( switchToVti, m_selectedThread.StackFrame, bringIntoView ); SynchronizeBreakpointsUI(); NotifyNewStackFrame(); } private void ResetVisualEffects() { foreach(VisualTreeInfo vti in codeView1.VisualTrees.Values) { vti.EnumerateVisualEffects( delegate( VisualEffect ve ) { if(ve is VisualEffect.InlineDisassembly) { return VisualTreeInfo.CallbackResult.Delete; } if(ve is VisualEffect.SourceCodeHighlight) { if(ve.Context == null) { return VisualTreeInfo.CallbackResult.Delete; } } return VisualTreeInfo.CallbackResult.Keep; } ); } } private void CreateVisualEffects( out VisualTreeInfo switchToVti , out VisualItem bringIntoView ) { GrowOnlySet< Debugging.DebugInfo > visited = SetFactory.NewWithReferenceEquality< Debugging.DebugInfo >(); switchToVti = null; bringIntoView = null; m_versionStackTrace++; foreach(StackFrame sf in m_selectedThread.StackTrace) { Debugging.DebugInfo di = sf.DebugInfo; if(di != null) { string file = di.SrcFileName; VisualTreeInfo vti = codeView1.CreateVisualTree( m_imageInformation, file, file ); if(vti != null) { VisualEffect.SourceCodeHighlight ve; if(sf.Depth == 0) { ve = vti.HighlightSourceCode( codeView1, sf.ProgramCounter, di, m_icon_CurrentStatement, null, m_brush_CurrentPC, c_visualEffect_Depth_CurrentStatement ); } else { if(visited.Contains( di ) == false) { ve = vti.HighlightSourceCode( codeView1, sf.ProgramCounter, di, m_icon_StackFrame, null, m_brush_PastPC, c_visualEffect_Depth_OnTheStackTrace ); } else { ve = null; } } if(ve != null && sf == m_selectedThread.StackFrame) { switchToVti = vti; bringIntoView = ve.TopSelectedLine; } } visited.Insert( di ); } } } private void PrepareDisplay( VisualTreeInfo vti , StackFrame sf , VisualItem bringIntoView ) { if(vti == null) { vti = codeView1.CreateEmptyVisualTree( "" ); } vti.ClearVisualEffects( typeof(VisualEffect.InlineDisassembly) ); if(m_currentSession.DisplayDisassembly || sf == null) { InstallDisassemblyBlock( vti, sf ); } SwitchToFile( vti, bringIntoView ); } private void InstallDisassemblyBlock( VisualTreeInfo vti , StackFrame sf ) { List< ImageInformation.DisassemblyLine > disasm; ContainerVisualItem line = null; uint pastOpcodesToDisassembly = m_currentSession.PastOpcodesToDisassembly; uint futureOpcodesToDisassembly = m_currentSession.FutureOpcodesToDisassembly; if(sf != null && sf.Region != null && sf.DebugInfo != null) { disasm = sf.DisassembleBlock( m_processorHost.MemoryDelta, pastOpcodesToDisassembly, futureOpcodesToDisassembly ); line = vti.FindLine( sf.DebugInfo.EndLineNumber ); } else { ContainerVisualItem topElement = vti.VisualTreeRoot; GraphicsContext ctx = codeView1.CtxForLayout; topElement.Clear(); line = new ContainerVisualItem( null ); topElement.Add( line ); TextVisualItem item = new TextVisualItem( null, "" ); item.PrepareText( ctx ); line.Add( item ); //--// disasm = new List< ImageInformation.DisassemblyLine >(); Emulation.Hosting.ProcessorStatus svc; m_processorHost.GetHostingService( out svc ); uint address = svc.ProgramCounter; uint addressStart = address - 3 * pastOpcodesToDisassembly * sizeof(uint); uint addressEnd = address + 3 * futureOpcodesToDisassembly * sizeof(uint); m_imageInformation.DisassembleBlock( m_processorHost.MemoryDelta, disasm, addressStart, address, addressEnd ); } if(disasm.Count > 0) { vti.InstallDisassemblyBlock( line, codeView1, disasm.ToArray(), c_visualEffect_Depth_Disassembly ); SynchronizeBreakpointsUI(); } } //--// public static void GrayOutRowInDataGridView( DataGridViewRow row ) { foreach(DataGridViewCell cell in row.Cells) { cell.Style.SelectionBackColor = SystemColors.Window; cell.Style.SelectionForeColor = SystemColors.GrayText; cell.Style.ForeColor = SystemColors.GrayText; } } public static void GrayOutRowsInDataGridView( DataGridViewRowCollection rows ) { foreach(DataGridViewRow row in rows) { GrayOutRowInDataGridView( row ); } } //--// void ProcessKeyDownEvent( KeyEventArgs e ) { if(e.Handled == false) { bool fGot = false; switch(e.KeyCode) { case Keys.Up: switch(e.Modifiers) { case Keys.Control: Action_MoveInTheStackTrace( -1 ); fGot = true; break; } break; case Keys.Down: switch(e.Modifiers) { case Keys.Control: Action_MoveInTheStackTrace( 1 ); fGot = true; break; } break; case Keys.Left: switch(e.Modifiers) { case Keys.Control: Action_MoveInTheThreadList( -1 ); fGot = true; break; } break; case Keys.Right: switch(e.Modifiers) { case Keys.Control: Action_MoveInTheThreadList( 1 ); fGot = true; break; } break; case Keys.F5: switch(e.Modifiers) { case Keys.Control | Keys.Shift: Action_Restart(); fGot = true; break; case Keys.Shift: Action_StopDebugging(); fGot = true; break; case Keys.None: Action_Start(); fGot = true; break; } break; case Keys.Cancel: switch(e.Modifiers) { case Keys.Control | Keys.Alt: Action_BreakAll(); fGot = true; break; } break; case Keys.F10: switch(e.Modifiers) { case Keys.None: Action_StepOver(); fGot = true; break; } break; case Keys.F11: switch(e.Modifiers) { case Keys.None: Action_StepInto(); fGot = true; break; case Keys.Control: Action_ToggleDisassembly(); fGot = true; break; case Keys.Shift: Action_StepOut(); fGot = true; break; } break; } if(fGot) { e.Handled = true; e.SuppressKeyPress = true; } } } void ProcessKeyUpEvent( KeyEventArgs e ) { } //--// private void NotifyNewStackFrame() { ExecuteInFormThread( delegate() { m_hostingSiteImpl.RaiseNotification( Hst.Forms.HostingSite.VisualizationEvent.NewStackFrame ); } ); } private void SynchronizeBreakpointsUI() { ExecuteInFormThread( delegate() { foreach(VisualTreeInfo vti in codeView1.VisualTrees.Values) { vti.EnumerateVisualEffects( delegate( VisualEffect ve ) { if(ve is VisualEffect.SourceCodeHighlight) { if(ve.Context is Emulation.Hosting.Breakpoint) { return VisualTreeInfo.CallbackResult.Delete; } } return VisualTreeInfo.CallbackResult.Keep; } ); } foreach(Emulation.Hosting.Breakpoint bp in m_processorHost.Breakpoints) { if(bp.ShowInUI) { IR.ImageBuilders.SequentialRegion reg; uint offset; Debugging.DebugInfo di; if(m_imageInformation.LocateFirstSourceCode( bp.Address, out reg, out offset, out di )) { if(bp.DebugInfo != null) { di = bp.DebugInfo; } if(di != null) { string file = di.SrcFileName; VisualTreeInfo vti = codeView1.GetVisualTree( file ); if(vti != null) { VisualEffect.SourceCodeHighlight ve; if(bp.IsActive) { ve = vti.HighlightSourceCode( codeView1, uint.MaxValue, di, m_icon_Breakpoint, null, m_brush_Breakpoint, c_visualEffect_Depth_Breakpoint ); } else { ve = vti.HighlightSourceCode( codeView1, uint.MaxValue, di, m_icon_BreakpointDisabled, m_pen_Breakpoint, null, c_visualEffect_Depth_Breakpoint ); } ve.Context = bp; ve.Version = bp.Version; } } } foreach(VisualTreeInfo vti in codeView1.VisualTrees.Values) { VisualEffect.SourceCodeHighlight ve; if(bp.IsActive) { ve = vti.HighlightSourceCode( codeView1, bp.Address, null, m_icon_Breakpoint, null, m_brush_Breakpoint, c_visualEffect_Depth_Breakpoint ); } else { ve = vti.HighlightSourceCode( codeView1, bp.Address, null, m_icon_BreakpointDisabled, m_pen_Breakpoint, null, c_visualEffect_Depth_Breakpoint ); } ve.Context = bp; ve.Version = bp.Version; } } } codeView1.RefreshVisualTree(); m_hostingSiteImpl.RaiseNotification( Hst.Forms.HostingSite.VisualizationEvent.BreakpointsChange ); } ); } // // Access Methods // public Hst.Forms.HostingSite HostingSite { get { return m_hostingSiteImpl; } } public Hst.AbstractHost Host { get { return m_processorHost; } } public MemoryDelta MemoryDelta { get { return m_processorHost.MemoryDelta; } } public ImageInformation ImageInformation { get { return m_imageInformation; } } public int VersionBreakpoints { get { return m_versionBreakpoints; } } //--// public Hst.Forms.HostingSite.ExecutionState CurrentState { get { return m_currentState; } } public Session CurrentSession { get { return m_currentSession; } set { m_currentSession = value; InnerAction_LoadImage(); } } //--// public List< ThreadStatus > Threads { get { return m_threads; } } public ThreadStatus ActiveThread { get { return m_activeThread; } } public ThreadStatus SelectedThread { get { return m_selectedThread; } } public StackFrame SelectedStackFrame { get { if(m_selectedThread != null) { return m_selectedThread.StackFrame; } return null; } } public int VersionStackTrace { get { return m_versionStackTrace; } } //--// public Configuration.Environment.Manager ConfigurationManager { get { return m_configurationManager; } } //--// public bool IsIdle { get { switch(m_currentState) { case Hst.Forms.HostingSite.ExecutionState.Idle: case Hst.Forms.HostingSite.ExecutionState.Loaded: case Hst.Forms.HostingSite.ExecutionState.Paused: return true; } return false; } } // // Event Methods // private void codeView1_HitSink( CodeView owner , VisualItem origin , PointF relPos , MouseEventArgs e , bool fDown , bool fUp ) { VisualTreeInfo vti = codeView1.ActiveVisualTree; if(vti != null) { if(fDown && e.Clicks >= 2) { Debugging.DebugInfo diTarget = origin.Context as Debugging.DebugInfo; if(diTarget != null) { List< ImageInformation.RangeToSourceCode > lst; Debugging.DebugInfo diTargetLine; Debugging.DebugInfo diClosest = null; bool fClosestIntersects = false; string fileName = vti.Input.File; diTargetLine = Debugging.DebugInfo.CreateMarkerForLine( diTarget.SrcFileName, diTarget.MethodName, diTarget.BeginLineNumber ); if(m_imageInformation.FileToCodeLookup.TryGetValue( fileName.ToUpper(), out lst )) { foreach(ImageInformation.RangeToSourceCode rng in lst) { foreach(var pair in rng.DebugInfos) { Debugging.DebugInfo di = pair.Info; if(di.SrcFileName == fileName) { Debugging.DebugInfo diLine = diTargetLine.ComputeIntersection( di ); if(diLine != null) { Debugging.DebugInfo diIntersection = diTarget.ComputeIntersection( di ); if(diIntersection != null) { if(diClosest == null || di.IsContainedIn( diClosest ) || fClosestIntersects == false) { diClosest = di; fClosestIntersects = true; } } else { if(diClosest == null) { diClosest = di; } else if(fClosestIntersects == false) { int diff1 = Math.Abs( di .BeginColumn - diTarget.BeginColumn ); int diff2 = Math.Abs( diClosest.BeginColumn - diTarget.BeginColumn ); if(diff1 < diff2) { diClosest = di; } } } } } } } } if(diClosest != null) { // // Remove all the existing break points having the same DebugInfo. // bool fAdd = true; foreach(Emulation.Hosting.Breakpoint bp in m_processorHost.Breakpoints) { IR.ImageBuilders.SequentialRegion reg; uint offset; Debugging.DebugInfo di; bool fDelete = false; if(bp.DebugInfo == diClosest) { fDelete = true; } else { if(m_imageInformation.LocateFirstSourceCode( bp.Address, out reg, out offset, out di )) { if(di == diClosest) { fDelete = true; } } } if(fDelete) { Action_RemoveBreakpoint( bp ); fAdd = false; } } if(fAdd && m_imageInformation.SourceCodeToCodeLookup.TryGetValue( diClosest, out lst )) { foreach(ImageInformation.RangeToSourceCode rng in lst) { Action_SetBreakpoint( rng.BaseAddress, diClosest, true, false, null ); break; } } } } var disasm = origin.Context as ImageInformation.DisassemblyLine; if(disasm != null) { IR.ImageBuilders.SequentialRegion reg; uint offset; Debugging.DebugInfo di; if(m_imageInformation.LocateFirstSourceCode( disasm.Address, out reg, out offset, out di )) { // // Remove all the existing break points having the same DebugInfo. // bool fAdd = true; foreach(Emulation.Hosting.Breakpoint bp in m_processorHost.Breakpoints) { if(disasm.Address == bp.Address) { Action_RemoveBreakpoint( bp ); fAdd = false; } } if(fAdd) { Action_SetBreakpoint( disasm.Address, di, true, false, null ); } } } } } } private void DebuggerMainForm_Load( object sender, EventArgs e ) { m_processorWorker.Start(); } private void DebuggerMainForm_KeyDown( object sender , KeyEventArgs e ) { ProcessKeyDownEvent( e ); } private void DebuggerMainForm_FormClosing( object sender , FormClosingEventArgs e ) { foreach(Hst.AbstractUIPlugIn plugIn in m_plugIns) { plugIn.Stop(); } ExecuteInWorkerThread( Hst.Forms.HostingSite.ExecutionState.Invalid, delegate() { m_processorWorkerExit = true; } ); InnerAction_StopExecution(); m_processorWorker.Join(); m_sessionManagerForm.SaveSessions(); } //--// private void toolStripMenuItem_File_Open_Click( object sender , EventArgs e ) { Action_LoadImage(); } private void toolStripMenuItem_File_Session_Load_Click( object sender , EventArgs e ) { Action_LoadSession(); } private void toolStripMenuItem_File_Session_Edit_Click( object sender , EventArgs e ) { Action_EditConfiguration(); } private void toolStripMenuItem_File_Session_Save_Click( object sender , EventArgs e ) { if(m_currentSession.SettingsFile != null) { Action_SaveSession( m_currentSession.SettingsFile ); } } private void toolStripMenuItem_File_Session_SaveAs_Click( object sender , EventArgs e ) { Action_SaveSession(); } private void toolStripMenuItem_File_Exit_Click( object sender , EventArgs e ) { this.Close(); } //--// private void toolStripMenuItem_Tools_SessionManager_Click( object sender , EventArgs e ) { Session session = m_sessionManagerForm.SelectSession( false ); if(session != null && session != m_currentSession) { m_currentSession = session; if(InnerAction_LoadImage() == false) { m_imageInformation = null; } } } //--// private void toolStripButton_Start_Click( object sender , EventArgs e ) { Action_Start(); } private void toolStripButton_BreakAll_Click( object sender , EventArgs e ) { Action_BreakAll(); } private void toolStripButton_StopDebugging_Click( object sender , EventArgs e ) { Action_StopDebugging(); } private void toolStripButton_Restart_Click( object sender , EventArgs e ) { Action_Restart(); } private void toolStripButton_ShowNextStatement_Click( object sender , EventArgs e ) { if(m_activeThread != null) { m_selectedThread = m_activeThread; m_activeThread.StackFrame = m_activeThread.TopStackFrame; Action_SelectThread( this.Threads.IndexOf( m_activeThread ) ); } } private void toolStripButton_StepInto_Click( object sender , EventArgs e ) { Action_StepInto(); } private void toolStripButton_StepOver_Click( object sender, EventArgs e ) { Action_StepOver(); } private void toolStripButton_StepOut_Click( object sender, EventArgs e ) { Action_StepOut(); } private void toolStripButton_ToggleDisassembly_Click( object sender, EventArgs e ) { Action_ToggleDisassembly(); } private void toolStripButton_ToggleWrapper_Click( object sender, EventArgs e ) { Action_ToggleWrapper(); } //--// private void statusTrip1_DoubleClick( object sender, EventArgs e ) { if(this.IsIdle) { Action_ResetAbsoluteTime(); DisplayExecutionTime(); } } } } ================================================ FILE: Zelig/Zelig/DebugTime/Debugger/Forms/DebuggerMainForm.resx ================================================ text/microsoft-resx 2.0 System.Resources.ResXResourceReader, System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 System.Resources.ResXResourceWriter, System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 17, 17 126, 17 335, 17 236, 17 iVBORw0KGgoAAAANSUhEUgAAABAAAAAQCAYAAAAf8/9hAAAAAXNSR0IArs4c6QAAAARnQU1BAACxjwv8 YQUAAAAgY0hSTQAAeiYAAICEAAD6AAAAgOgAAHUwAADqYAAAOpgAABdwnLpRPAAAAgxJREFUOE+lkvtL U2EYx+0PEbtpFwnBKPGKiJImGP0gYhIYs1E5GF5gIxkpA00JRSmMEF0ohMh+GaRWYlqabMVcNdS2QpaI VqiDIYhk397vA6fXhCjyhYdzeM/5fp7vczkAdeL2cwho7v/wWzT1zcN+Pwhr51uY2/y41PQaF+wzKKiZ QvaN58g0jyLd5KEUcQbg+84P/Cm2tncQjW3j68YWIqubCC3FcOJc478BAuGoZM6zvoRnakXEruEIjhc4 /g5gZop9c+voGAyLbQIfeBZxLL9BA1jzXvuGbWamuKh+GmmVbswE19A59FEBbmoAG7YbsLtm2mZmiml9 cvabNDwpz6YB7LYBoMXCumkJr7LOmnnHzBQ/9X2Bo2cOibm1GsBREbAQiYmw/8lnuCeWkVzcgnZlnw1j 3HV/wuNXK6i/9x5Hc6wawDlTXHbLJ+LZUBQPRyKwdQdxutwl1h+NLXHh5Ht1ewBHsiwawCW57HyDAfWR dvl0uhZQ1eqX8aVc7EKLqrum651ATLf9OJx5XQM4KmY0xPzZ0hFAiQJnXB0WwME0E3IsL5B17ZlADqWb NYDrOepdlcysmTWWOrxqbceRWtaLk0VO1XW72D5Vckd2gMBfq8zdpmUG62NJvKM4+XyziDk24xmfWoGE s1c0gHPmbrPTpHNJKOCo2G1mZs20zcwUJ5yp1AB5+8/zEwgF5GMVDxh4AAAAAElFTkSuQmCC 653, 17 491, 17 71 ================================================ FILE: Zelig/Zelig/DebugTime/Debugger/Forms/DisplayForm.Designer.cs ================================================ namespace Microsoft.Zelig.Debugger.ArmProcessor { partial class DisplayForm { /// /// Required designer variable. /// private System.ComponentModel.IContainer components = null; /// /// Clean up any resources being used. /// /// true if managed resources should be disposed; otherwise, false. protected override void Dispose( bool disposing ) { if(disposing && (components != null)) { components.Dispose(); } base.Dispose( disposing ); } #region Windows Form Designer generated code /// /// Required method for Designer support - do not modify /// the contents of this method with the code editor. /// private void InitializeComponent() { this.components = new System.ComponentModel.Container(); this.button_Spare = new System.Windows.Forms.Button(); this.button_Channel = new System.Windows.Forms.Button(); this.button_Backlight = new System.Windows.Forms.Button(); this.button_Down = new System.Windows.Forms.Button(); this.button_Enter = new System.Windows.Forms.Button(); this.button_Up = new System.Windows.Forms.Button(); this.pictureBox_LCD = new System.Windows.Forms.PictureBox(); this.timer1 = new System.Windows.Forms.Timer( this.components ); ((System.ComponentModel.ISupportInitialize)(this.pictureBox_LCD)).BeginInit(); this.SuspendLayout(); // // button_Spare // this.button_Spare.Location = new System.Drawing.Point( 11, 50 ); this.button_Spare.Name = "button_Spare"; this.button_Spare.Size = new System.Drawing.Size( 75, 23 ); this.button_Spare.TabIndex = 21; this.button_Spare.Text = "Spare"; this.button_Spare.UseVisualStyleBackColor = true; this.button_Spare.Click += new System.EventHandler( this.button_Spare_Click ); // // button_Channel // this.button_Channel.Location = new System.Drawing.Point( 12, 88 ); this.button_Channel.Name = "button_Channel"; this.button_Channel.Size = new System.Drawing.Size( 75, 23 ); this.button_Channel.TabIndex = 20; this.button_Channel.Text = "Channel"; this.button_Channel.UseVisualStyleBackColor = true; this.button_Channel.Click += new System.EventHandler( this.button_Channel_Click ); // // button_Backlight // this.button_Backlight.Location = new System.Drawing.Point( 11, 12 ); this.button_Backlight.Name = "button_Backlight"; this.button_Backlight.Size = new System.Drawing.Size( 75, 23 ); this.button_Backlight.TabIndex = 19; this.button_Backlight.Text = "Backlight"; this.button_Backlight.UseVisualStyleBackColor = true; this.button_Backlight.Click += new System.EventHandler( this.button_Backlight_Click ); // // button_Down // this.button_Down.Location = new System.Drawing.Point( 261, 88 ); this.button_Down.Name = "button_Down"; this.button_Down.Size = new System.Drawing.Size( 75, 23 ); this.button_Down.TabIndex = 18; this.button_Down.Text = "Down"; this.button_Down.UseVisualStyleBackColor = true; this.button_Down.Click += new System.EventHandler( this.button_Down_Click ); // // button_Enter // this.button_Enter.Location = new System.Drawing.Point( 261, 50 ); this.button_Enter.Name = "button_Enter"; this.button_Enter.Size = new System.Drawing.Size( 75, 23 ); this.button_Enter.TabIndex = 17; this.button_Enter.Text = "Enter"; this.button_Enter.UseVisualStyleBackColor = true; this.button_Enter.Click += new System.EventHandler( this.button_Enter_Click ); // // button_Up // this.button_Up.Location = new System.Drawing.Point( 261, 12 ); this.button_Up.Name = "button_Up"; this.button_Up.Size = new System.Drawing.Size( 75, 23 ); this.button_Up.TabIndex = 16; this.button_Up.Text = "Up"; this.button_Up.UseVisualStyleBackColor = true; this.button_Up.Click += new System.EventHandler( this.button_Up_Click ); // // pictureBox_LCD // this.pictureBox_LCD.BorderStyle = System.Windows.Forms.BorderStyle.Fixed3D; this.pictureBox_LCD.Location = new System.Drawing.Point( 119, 12 ); this.pictureBox_LCD.Name = "pictureBox_LCD"; this.pictureBox_LCD.Size = new System.Drawing.Size( 120, 96 ); this.pictureBox_LCD.TabIndex = 15; this.pictureBox_LCD.TabStop = false; // // timer1 // this.timer1.Interval = 50; // // DisplayForm // this.AutoScaleDimensions = new System.Drawing.SizeF( 6F, 13F ); this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font; this.ClientSize = new System.Drawing.Size( 350, 124 ); this.Controls.Add( this.button_Spare ); this.Controls.Add( this.button_Channel ); this.Controls.Add( this.button_Backlight ); this.Controls.Add( this.button_Down ); this.Controls.Add( this.button_Enter ); this.Controls.Add( this.button_Up ); this.Controls.Add( this.pictureBox_LCD ); this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.FixedSingle; this.KeyPreview = true; this.MaximizeBox = false; this.MaximumSize = new System.Drawing.Size( 356, 156 ); this.MinimizeBox = false; this.MinimumSize = new System.Drawing.Size( 356, 156 ); this.Name = "DisplayForm"; this.ShowIcon = false; this.ShowInTaskbar = false; this.Text = "Watch UI"; this.TopMost = true; ((System.ComponentModel.ISupportInitialize)(this.pictureBox_LCD)).EndInit(); this.ResumeLayout( false ); } #endregion private System.Windows.Forms.Button button_Spare; private System.Windows.Forms.Button button_Channel; private System.Windows.Forms.Button button_Backlight; private System.Windows.Forms.Button button_Down; private System.Windows.Forms.Button button_Enter; private System.Windows.Forms.Button button_Up; private System.Windows.Forms.PictureBox pictureBox_LCD; private System.Windows.Forms.Timer timer1; } } ================================================ FILE: Zelig/Zelig/DebugTime/Debugger/Forms/DisplayForm.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // namespace Microsoft.Zelig.Debugger.ArmProcessor { using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Text; using System.Windows.Forms; public partial class DisplayForm : Emulation.Hosting.Forms.BaseDebuggerForm { class SED15E0SinkImpl : Emulation.Hosting.SED15E0Sink { // // State // DisplayForm m_owner; // // Constructor Methods // internal SED15E0SinkImpl( DisplayForm owner ) { m_owner = owner; //--// owner.Host.RegisterService( typeof(Emulation.Hosting.SED15E0Sink), this ); } // // Helper Methods // public override void NewScreenShot( uint[] buffer , int width , int height ) { Emulation.Hosting.ProcessorControl svcPC; m_owner.Host.GetHostingService( out svcPC ); if(svcPC.StopExecution) return; m_owner.SendScreenShot( buffer, width, height ); } } // // State // uint[] m_buffer; int m_buffer_width; int m_buffer_height; SED15E0SinkImpl m_implSED15E0Sink; // // Constructor Methods // public DisplayForm( Emulation.Hosting.Forms.HostingSite site ) : base( site ) { InitializeComponent(); //--// m_implSED15E0Sink = new SED15E0SinkImpl( this ); //--// timer1.Tick += new EventHandler( UpdateTimerCallback ); //--// site.RegisterView( this, Emulation.Hosting.Forms.HostingSite.PublicationMode.Tools ); } // // Helper Methods // protected override void NotifyChangeInVisibility( bool fVisible ) { if(fVisible) { timer1.Start(); } else { timer1.Stop(); } } protected override bool ProcessKeyDown( KeyEventArgs e ) { uint mask = 0; switch(e.KeyCode) { case Keys.Down : mask = Emulation.Hosting.HalButtons.BUTTON_B5; break; case Keys.Up : mask = Emulation.Hosting.HalButtons.BUTTON_B2; break; case Keys.Left : mask = Emulation.Hosting.HalButtons.BUTTON_B1; break; case Keys.Right: mask = Emulation.Hosting.HalButtons.BUTTON_B4; break; } if(mask != 0) { Emulation.Hosting.HalButtons svc; if(this.Host.GetHostingService( out svc )) { svc.QueueNextStateChange( mask, 0 ); } return true; } return false; } protected override bool ProcessKeyUp( KeyEventArgs e ) { uint mask = 0; switch(e.KeyCode) { case Keys.Down : mask = Emulation.Hosting.HalButtons.BUTTON_B5; break; case Keys.Up : mask = Emulation.Hosting.HalButtons.BUTTON_B2; break; case Keys.Left : mask = Emulation.Hosting.HalButtons.BUTTON_B1; break; case Keys.Right: mask = Emulation.Hosting.HalButtons.BUTTON_B4; break; } if(mask != 0) { Emulation.Hosting.HalButtons svc; if(this.Host.GetHostingService( out svc )) { svc.QueueNextStateChange( 0, mask ); } return true; } return false; } //--// public void SendScreenShot( uint[] buffer , int width , int height ) { lock(this) { m_buffer = buffer; m_buffer_width = width; m_buffer_height = height; } } private void UpdateTimerCallback( object sender , EventArgs e ) { uint[] buffer; int width; int height; lock(this) { buffer = m_buffer; width = m_buffer_width; height = m_buffer_height; m_buffer = null; } if(buffer != null) { UpdateScreen( buffer, width, height ); } } private void UpdateScreen( uint[] buffer , int width , int height ) { pictureBox_LCD.Image = ConvertBufferToBitmap( buffer, width, height ); } //--// private static uint[] Adjust1bppOrientation( uint[] buf ) { //CLR_GFX_Bitmap::AdjustBitOrientation //The TinyCLR treats 1bpp bitmaps reversed from Windows //And most likely every other 1bpp format as well byte[] reverseTable = new byte[] { 0x00, 0x80, 0x40, 0xC0, 0x20, 0xA0, 0x60, 0xE0, 0x10, 0x90, 0x50, 0xD0, 0x30, 0xB0, 0x70, 0xF0, 0x08, 0x88, 0x48, 0xC8, 0x28, 0xA8, 0x68, 0xE8, 0x18, 0x98, 0x58, 0xD8, 0x38, 0xB8, 0x78, 0xF8, 0x04, 0x84, 0x44, 0xC4, 0x24, 0xA4, 0x64, 0xE4, 0x14, 0x94, 0x54, 0xD4, 0x34, 0xB4, 0x74, 0xF4, 0x0C, 0x8C, 0x4C, 0xCC, 0x2C, 0xAC, 0x6C, 0xEC, 0x1C, 0x9C, 0x5C, 0xDC, 0x3C, 0xBC, 0x7C, 0xFC, 0x02, 0x82, 0x42, 0xC2, 0x22, 0xA2, 0x62, 0xE2, 0x12, 0x92, 0x52, 0xD2, 0x32, 0xB2, 0x72, 0xF2, 0x0A, 0x8A, 0x4A, 0xCA, 0x2A, 0xAA, 0x6A, 0xEA, 0x1A, 0x9A, 0x5A, 0xDA, 0x3A, 0xBA, 0x7A, 0xFA, 0x06, 0x86, 0x46, 0xC6, 0x26, 0xA6, 0x66, 0xE6, 0x16, 0x96, 0x56, 0xD6, 0x36, 0xB6, 0x76, 0xF6, 0x0E, 0x8E, 0x4E, 0xCE, 0x2E, 0xAE, 0x6E, 0xEE, 0x1E, 0x9E, 0x5E, 0xDE, 0x3E, 0xBE, 0x7E, 0xFE, 0x01, 0x81, 0x41, 0xC1, 0x21, 0xA1, 0x61, 0xE1, 0x11, 0x91, 0x51, 0xD1, 0x31, 0xB1, 0x71, 0xF1, 0x09, 0x89, 0x49, 0xC9, 0x29, 0xA9, 0x69, 0xE9, 0x19, 0x99, 0x59, 0xD9, 0x39, 0xB9, 0x79, 0xF9, 0x05, 0x85, 0x45, 0xC5, 0x25, 0xA5, 0x65, 0xE5, 0x15, 0x95, 0x55, 0xD5, 0x35, 0xB5, 0x75, 0xF5, 0x0D, 0x8D, 0x4D, 0xCD, 0x2D, 0xAD, 0x6D, 0xED, 0x1D, 0x9D, 0x5D, 0xDD, 0x3D, 0xBD, 0x7D, 0xFD, 0x03, 0x83, 0x43, 0xC3, 0x23, 0xA3, 0x63, 0xE3, 0x13, 0x93, 0x53, 0xD3, 0x33, 0xB3, 0x73, 0xF3, 0x0B, 0x8B, 0x4B, 0xCB, 0x2B, 0xAB, 0x6B, 0xEB, 0x1B, 0x9B, 0x5B, 0xDB, 0x3B, 0xBB, 0x7B, 0xFB, 0x07, 0x87, 0x47, 0xC7, 0x27, 0xA7, 0x67, 0xE7, 0x17, 0x97, 0x57, 0xD7, 0x37, 0xB7, 0x77, 0xF7, 0x0F, 0x8F, 0x4F, 0xCF, 0x2F, 0xAF, 0x6F, 0xEF, 0x1F, 0x9F, 0x5F, 0xDF, 0x3F, 0xBF, 0x7F,0xFF, }; unsafe { uint[] res = new uint[buf.Length]; fixed(uint* pSrc = buf) { fixed(uint* pDst = res) { byte* ptrSrc = (byte*)pSrc; byte* ptrDst = (byte*)pDst; for(int i = buf.Length * 4; i > 0; i--) { *ptrDst++ = reverseTable[*ptrSrc++]; } } } return res; } } private static Bitmap ConvertBufferToBitmap( uint[] buffer , int width , int height ) { buffer = Adjust1bppOrientation( buffer ); Bitmap bmp = null; System.Drawing.Imaging.BitmapData bitmapData = null; try { bmp = new Bitmap( width, height, System.Drawing.Imaging.PixelFormat.Format1bppIndexed ); Rectangle rect = new Rectangle( 0, 0, width, height ); System.Drawing.Imaging.ColorPalette palette = bmp.Palette; palette.Entries[0] = System.Drawing.Color.White; palette.Entries[1] = System.Drawing.Color.Black; bmp.Palette = palette; bitmapData = bmp.LockBits( rect, System.Drawing.Imaging.ImageLockMode.WriteOnly, System.Drawing.Imaging.PixelFormat.Format1bppIndexed ); IntPtr data = bitmapData.Scan0; unsafe { fixed(uint* pbuf = buffer) { uint* src = (uint*)pbuf; uint* dst = (uint*)data.ToPointer(); for(int i = buffer.Length; i > 0; i--) { *dst = *src; dst++; src++; } } } } finally { if(bitmapData != null) { bmp.UnlockBits( bitmapData ); } } return bmp; } private void QueueButton( uint mask ) { Emulation.Hosting.HalButtons svc; if(this.Host.GetHostingService( out svc )) { svc.QueueNextStateChange( mask, 0 ); } } // // Access Methods // public override string ViewTitle { get { return "&Watch UI"; } } // // Event Methods // private void button_Up_Click( object sender , EventArgs e ) { QueueButton( Emulation.Hosting.HalButtons.BUTTON_B2 ); } private void button_Down_Click( object sender , EventArgs e ) { QueueButton( Emulation.Hosting.HalButtons.BUTTON_B5 ); } private void button_Enter_Click( object sender , EventArgs e ) { QueueButton( Emulation.Hosting.HalButtons.BUTTON_B4 ); } private void button_Channel_Click( object sender , EventArgs e ) { QueueButton( Emulation.Hosting.HalButtons.BUTTON_B1 ); } private void button_Backlight_Click( object sender , EventArgs e ) { QueueButton( Emulation.Hosting.HalButtons.BUTTON_B0 ); } private void button_Spare_Click( object sender , EventArgs e ) { QueueButton( Emulation.Hosting.HalButtons.BUTTON_B3 ); } } } ================================================ FILE: Zelig/Zelig/DebugTime/Debugger/Forms/DisplayForm.resx ================================================ text/microsoft-resx 2.0 System.Resources.ResXResourceReader, System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 System.Resources.ResXResourceWriter, System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 17, 17 ================================================ FILE: Zelig/Zelig/DebugTime/Debugger/Forms/EnvironmentForm.Designer.cs ================================================ namespace Microsoft.Zelig.Debugger.ArmProcessor { partial class EnvironmentForm { /// /// Required designer variable. /// private System.ComponentModel.IContainer components = null; /// /// Clean up any resources being used. /// /// true if managed resources should be disposed; otherwise, false. protected override void Dispose( bool disposing ) { if(disposing && (components != null)) { components.Dispose(); } base.Dispose( disposing ); } #region Windows Form Designer generated code /// /// Required method for Designer support - do not modify /// the contents of this method with the code editor. /// private void InitializeComponent() { this.comboBox_Engine = new System.Windows.Forms.ComboBox(); this.label1 = new System.Windows.Forms.Label(); this.button_Ok = new System.Windows.Forms.Button(); this.button_Cancel = new System.Windows.Forms.Button(); this.label2 = new System.Windows.Forms.Label(); this.comboBox_Processor = new System.Windows.Forms.ComboBox(); this.label3 = new System.Windows.Forms.Label(); this.comboBox_Display = new System.Windows.Forms.ComboBox(); this.label4 = new System.Windows.Forms.Label(); this.comboBox_RAM = new System.Windows.Forms.ComboBox(); this.label5 = new System.Windows.Forms.Label(); this.comboBox_FLASH = new System.Windows.Forms.ComboBox(); this.comboBox_Product = new System.Windows.Forms.ComboBox(); this.label6 = new System.Windows.Forms.Label(); this.SuspendLayout(); // // comboBox_Engine // this.comboBox_Engine.DropDownStyle = System.Windows.Forms.ComboBoxStyle.DropDownList; this.comboBox_Engine.FormattingEnabled = true; this.comboBox_Engine.Location = new System.Drawing.Point(76, 12); this.comboBox_Engine.Name = "comboBox_Engine"; this.comboBox_Engine.Size = new System.Drawing.Size(698, 21); this.comboBox_Engine.TabIndex = 1; this.comboBox_Engine.SelectedIndexChanged += new System.EventHandler(this.comboBox_Engine_SelectedIndexChanged); // // label1 // this.label1.AutoSize = true; this.label1.Location = new System.Drawing.Point(13, 15); this.label1.Name = "label1"; this.label1.Size = new System.Drawing.Size(43, 13); this.label1.TabIndex = 2; this.label1.Text = "Engine:"; // // button_Ok // this.button_Ok.Enabled = false; this.button_Ok.Location = new System.Drawing.Point(12, 182); this.button_Ok.Name = "button_Ok"; this.button_Ok.Size = new System.Drawing.Size(75, 23); this.button_Ok.TabIndex = 7; this.button_Ok.Text = "Ok"; this.button_Ok.UseVisualStyleBackColor = true; this.button_Ok.Click += new System.EventHandler(this.button_Ok_Click); // // button_Cancel // this.button_Cancel.DialogResult = System.Windows.Forms.DialogResult.Cancel; this.button_Cancel.Location = new System.Drawing.Point(699, 182); this.button_Cancel.Name = "button_Cancel"; this.button_Cancel.Size = new System.Drawing.Size(75, 23); this.button_Cancel.TabIndex = 8; this.button_Cancel.Text = "Cancel"; this.button_Cancel.UseVisualStyleBackColor = true; this.button_Cancel.Click += new System.EventHandler(this.button_Cancel_Click); // // label2 // this.label2.AutoSize = true; this.label2.Location = new System.Drawing.Point(13, 69); this.label2.Name = "label2"; this.label2.Size = new System.Drawing.Size(57, 13); this.label2.TabIndex = 5; this.label2.Text = "Processor:"; // // comboBox_Processor // this.comboBox_Processor.DropDownStyle = System.Windows.Forms.ComboBoxStyle.DropDownList; this.comboBox_Processor.FormattingEnabled = true; this.comboBox_Processor.Location = new System.Drawing.Point(76, 66); this.comboBox_Processor.Name = "comboBox_Processor"; this.comboBox_Processor.Size = new System.Drawing.Size(698, 21); this.comboBox_Processor.TabIndex = 3; this.comboBox_Processor.SelectedIndexChanged += new System.EventHandler(this.comboBox_Processor_SelectedIndexChanged); // // label3 // this.label3.AutoSize = true; this.label3.Location = new System.Drawing.Point(13, 96); this.label3.Name = "label3"; this.label3.Size = new System.Drawing.Size(44, 13); this.label3.TabIndex = 7; this.label3.Text = "Display:"; // // comboBox_Display // this.comboBox_Display.DropDownStyle = System.Windows.Forms.ComboBoxStyle.DropDownList; this.comboBox_Display.FormattingEnabled = true; this.comboBox_Display.Location = new System.Drawing.Point(76, 93); this.comboBox_Display.Name = "comboBox_Display"; this.comboBox_Display.Size = new System.Drawing.Size(698, 21); this.comboBox_Display.TabIndex = 4; this.comboBox_Display.SelectedIndexChanged += new System.EventHandler(this.comboBox_Display_SelectedIndexChanged); // // label4 // this.label4.AutoSize = true; this.label4.Location = new System.Drawing.Point(13, 123); this.label4.Name = "label4"; this.label4.Size = new System.Drawing.Size(34, 13); this.label4.TabIndex = 9; this.label4.Text = "RAM:"; // // comboBox_RAM // this.comboBox_RAM.DropDownStyle = System.Windows.Forms.ComboBoxStyle.DropDownList; this.comboBox_RAM.FormattingEnabled = true; this.comboBox_RAM.Location = new System.Drawing.Point(76, 120); this.comboBox_RAM.Name = "comboBox_RAM"; this.comboBox_RAM.Size = new System.Drawing.Size(698, 21); this.comboBox_RAM.TabIndex = 5; this.comboBox_RAM.SelectedIndexChanged += new System.EventHandler(this.comboBox_RAM_SelectedIndexChanged); // // label5 // this.label5.AutoSize = true; this.label5.Location = new System.Drawing.Point(13, 150); this.label5.Name = "label5"; this.label5.Size = new System.Drawing.Size(44, 13); this.label5.TabIndex = 11; this.label5.Text = "FLASH:"; // // comboBox_FLASH // this.comboBox_FLASH.DropDownStyle = System.Windows.Forms.ComboBoxStyle.DropDownList; this.comboBox_FLASH.FormattingEnabled = true; this.comboBox_FLASH.Location = new System.Drawing.Point(76, 147); this.comboBox_FLASH.Name = "comboBox_FLASH"; this.comboBox_FLASH.Size = new System.Drawing.Size(698, 21); this.comboBox_FLASH.TabIndex = 6; this.comboBox_FLASH.SelectedIndexChanged += new System.EventHandler(this.comboBox_FLASH_SelectedIndexChanged); // // comboBox_Product // this.comboBox_Product.DropDownStyle = System.Windows.Forms.ComboBoxStyle.DropDownList; this.comboBox_Product.FormattingEnabled = true; this.comboBox_Product.Location = new System.Drawing.Point(76, 39); this.comboBox_Product.Name = "comboBox_Product"; this.comboBox_Product.Size = new System.Drawing.Size(698, 21); this.comboBox_Product.TabIndex = 2; this.comboBox_Product.SelectedIndexChanged += new System.EventHandler(this.comboBox_Product_SelectedIndexChanged); // // label6 // this.label6.AutoSize = true; this.label6.Location = new System.Drawing.Point(13, 42); this.label6.Name = "label6"; this.label6.Size = new System.Drawing.Size(47, 13); this.label6.TabIndex = 13; this.label6.Text = "Product:"; // // EnvironmentForm // this.AcceptButton = this.button_Ok; this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F); this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font; this.CancelButton = this.button_Cancel; this.ClientSize = new System.Drawing.Size(791, 218); this.ControlBox = false; this.Controls.Add(this.comboBox_Product); this.Controls.Add(this.label6); this.Controls.Add(this.comboBox_FLASH); this.Controls.Add(this.label5); this.Controls.Add(this.comboBox_RAM); this.Controls.Add(this.label4); this.Controls.Add(this.comboBox_Display); this.Controls.Add(this.label3); this.Controls.Add(this.comboBox_Processor); this.Controls.Add(this.label2); this.Controls.Add(this.button_Cancel); this.Controls.Add(this.button_Ok); this.Controls.Add(this.label1); this.Controls.Add(this.comboBox_Engine); this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.FixedSingle; this.Name = "EnvironmentForm"; this.ShowIcon = false; this.ShowInTaskbar = false; this.Text = "Select Environment"; this.ResumeLayout(false); this.PerformLayout(); } #endregion private System.Windows.Forms.ComboBox comboBox_Engine; private System.Windows.Forms.Label label1; private System.Windows.Forms.Button button_Ok; private System.Windows.Forms.Button button_Cancel; private System.Windows.Forms.Label label2; private System.Windows.Forms.ComboBox comboBox_Processor; private System.Windows.Forms.Label label3; private System.Windows.Forms.ComboBox comboBox_Display; private System.Windows.Forms.Label label4; private System.Windows.Forms.ComboBox comboBox_RAM; private System.Windows.Forms.Label label5; private System.Windows.Forms.ComboBox comboBox_FLASH; private System.Windows.Forms.ComboBox comboBox_Product; private System.Windows.Forms.Label label6; } } ================================================ FILE: Zelig/Zelig/DebugTime/Debugger/Forms/EnvironmentForm.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // namespace Microsoft.Zelig.Debugger.ArmProcessor { using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Text; using System.Windows.Forms; using Cfg = Microsoft.Zelig.Configuration.Environment; public partial class EnvironmentForm : Form { internal class SelectionHolder { // // State // internal List< Cfg.AbstractCategory.ValueContext[] > m_choices; internal SelectionCombination[] m_combinations; internal int[] m_selected; // // Constructor Methods // internal SelectionHolder( Cfg.ProductCategory selectedProduct , Type filter ) { m_choices = new List< Cfg.AbstractCategory.ValueContext[] >(); foreach(Cfg.AbstractCategory.ValueContext ctx in selectedProduct.SearchPossibleValues( filter )) { bool fGot = false; for(int i = 0; i < m_choices.Count; i++) { var ctxArray = m_choices[i]; var ctxOld = ctxArray[0]; if(ctxOld.Holder == ctx.Holder && ctxOld.Field == ctx.Field ) { m_choices[i] = ArrayUtility.AppendToNotNullArray( ctxArray, ctx ); fGot = true; break; } } if(fGot == false) { m_choices.Add( new Cfg.AbstractCategory.ValueContext[] { ctx } ); } } } // // Helper Methods // internal void ApplyToComboBox( ComboBox comboBox ) { ComboBox.ObjectCollection items = comboBox.Items; items.Clear(); if(m_choices.Count == 0) { items.Add( "" ); comboBox.Enabled = false; m_combinations = null; m_selected = null; } else { int cols = m_choices.Count; int rows = 1; for(int col = 0; col < cols; col++) { rows *= m_choices[col].Length; } m_combinations = new SelectionCombination[rows]; for(int row = 0; row < rows; row++) { int[] indices = new int[cols]; int val = row; for(int col = 0; col < cols; col++) { int num = m_choices[col].Length; indices[col] = val % num; val /= num; } SelectionCombination comb = new SelectionCombination( this, indices ); m_combinations[row] = comb; items.Add( comb ); } if(rows == 1) { if(comboBox.SelectedIndex != 0) { comboBox.SelectedIndex = 0; } comboBox.Enabled = false; } else { comboBox.Enabled = true; } } } internal bool SameSelections( SelectionHolder other ) { if(this.m_choices.Count != other.m_choices.Count) { return false; } for(int i = 0; i < this.m_choices.Count; i++) { Cfg.AbstractCategory.ValueContext[] arrayThis = this .m_choices[i]; Cfg.AbstractCategory.ValueContext[] arrayOther = other.m_choices[i]; if(arrayThis.Length != arrayOther.Length) { return false; } for(int j = 0; j < arrayThis.Length; j++) { if(arrayThis[j].Equals( arrayOther[j] ) == false) { return false; } } } return true; } // // Access Methods // internal bool IsSelected { get { return m_combinations == null || m_selected != null; } } } internal class SelectionCombination { // // State // private SelectionHolder m_holder; private int[] m_indices; // // Constructor Methods // internal SelectionCombination( SelectionHolder holder , int[] indices ) { m_holder = holder; m_indices = indices; } // // Helper Methods // internal void ApplySelection() { Cfg.AbstractCategory.ValueContext[] res = new Cfg.AbstractCategory.ValueContext[m_indices.Length]; for(int i = 0; i < m_indices.Length; i++) { Cfg.AbstractCategory.ValueContext ctx = m_holder.m_choices[i][m_indices[i]]; Cfg.AbstractCategory holder = ctx.Holder; if(holder != null) { ctx.Field.SetValue( holder, ctx.Value ); } Cfg.AbstractCategory selected = ctx.Value as Cfg.AbstractCategory; if(selected != null) { selected.ApplyDefaultValues(); } } m_holder.m_selected = m_indices; } // // Debug Methods // public override string ToString() { StringBuilder sb = new StringBuilder(); for(int i = 0; i < m_indices.Length; i++) { if(i != 0) { sb.Append( " , " ); } sb.Append( m_holder.m_choices[i][m_indices[i]].ToString() ); } return sb.ToString(); } } // // State // IMainForm m_owner; Cfg.EngineCategory m_selectedEngine; Cfg.ProductCategory m_selectedProduct; SelectionHolder m_selectedProcessor; SelectionHolder m_selectedDisplay; SelectionHolder m_selectedRAM; SelectionHolder m_selectedFLASH; // // Constructor Methods // public EnvironmentForm( IMainForm owner ) { m_owner = owner; InitializeComponent(); //--// Cfg.Manager manager = owner.ConfigurationManager; foreach(Cfg.AbstractCategory value in manager.AllValues) { if(value is Cfg.EngineCategory) { comboBox_Engine.Items.Add( value ); } if(value is Cfg.ProductCategory) { comboBox_Product.Items.Add( value ); } } SetStatus(); } // // Helper Methods // private void SetStatus() { if(m_selectedProduct != null) { UpdateChoices(); } SetComboBoxStatus( comboBox_Engine ); SetComboBoxStatus( comboBox_Product ); button_Ok.Enabled = this.IsConfigured; } private void UpdateChoices() { UpdateIfChanged( comboBox_Processor, ref m_selectedProcessor, new SelectionHolder( m_selectedProduct, typeof(Cfg.ProcessorCategory ) ) ); UpdateIfChanged( comboBox_Display , ref m_selectedDisplay , new SelectionHolder( m_selectedProduct, typeof(Cfg.DisplayCategory ) ) ); UpdateIfChanged( comboBox_RAM , ref m_selectedRAM , new SelectionHolder( m_selectedProduct, typeof(Cfg.RamMemoryCategory ) ) ); UpdateIfChanged( comboBox_FLASH , ref m_selectedFLASH , new SelectionHolder( m_selectedProduct, typeof(Cfg.FlashMemoryCategory) ) ); } private void UpdateIfChanged( ComboBox comboBox , ref SelectionHolder holderOld , SelectionHolder holderNew ) { if(holderOld != null) { if(holderOld.SameSelections( holderNew )) { return; } } holderOld = holderNew; holderOld.ApplyToComboBox( comboBox ); } private void SetComboBoxStatus( ComboBox comboBox ) { switch(comboBox.Items.Count) { case 0: comboBox.Enabled = false; break; case 1: if(comboBox.SelectedIndex != 0) { comboBox.SelectedIndex = 0; } comboBox.Enabled = false; break; default: comboBox.Enabled = true; break; } } //--// private void ApplyChoice( ComboBox comboBox ) { SelectionCombination combination = (SelectionCombination)comboBox.SelectedItem; combination.ApplySelection(); SetStatus(); } // // Access Methods // public bool IsConfigured { get { if(m_selectedEngine != null && m_selectedProduct != null ) { if(m_selectedProcessor.IsSelected && m_selectedDisplay .IsSelected && m_selectedRAM .IsSelected && m_selectedFLASH .IsSelected ) { return true; } } return false; } } public Cfg.EngineCategory SelectedEngine { get { return m_selectedEngine; } set { m_selectedEngine = value; SetStatus(); } } public Cfg.ProductCategory SelectedProduct { get { return m_selectedProduct; } set { m_selectedProduct = value; SetStatus(); } } // // Event Methods // private void comboBox_Engine_SelectedIndexChanged( object sender , EventArgs e ) { m_selectedEngine = (Cfg.EngineCategory)comboBox_Engine.SelectedItem; SetStatus(); } private void comboBox_Product_SelectedIndexChanged( object sender , EventArgs e ) { m_selectedProduct = (Cfg.ProductCategory)comboBox_Product.SelectedItem; m_selectedProduct.ApplyDefaultValues(); SetStatus(); } private void comboBox_Processor_SelectedIndexChanged( object sender , EventArgs e ) { ApplyChoice( comboBox_Processor ); } private void comboBox_Display_SelectedIndexChanged( object sender , EventArgs e ) { ApplyChoice( comboBox_Display ); } private void comboBox_RAM_SelectedIndexChanged( object sender , EventArgs e ) { ApplyChoice( comboBox_RAM ); } private void comboBox_FLASH_SelectedIndexChanged( object sender , EventArgs e ) { ApplyChoice( comboBox_FLASH ); } //--// private void button_Cancel_Click( object sender, EventArgs e ) { this.DialogResult = DialogResult.Cancel; this.Close(); } private void button_Ok_Click( object sender, EventArgs e ) { this.DialogResult = DialogResult.OK; this.Close(); } } } ================================================ FILE: Zelig/Zelig/DebugTime/Debugger/Forms/EnvironmentForm.resx ================================================ text/microsoft-resx 2.0 System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 ================================================ FILE: Zelig/Zelig/DebugTime/Debugger/Forms/IMainForm.cs ================================================ namespace Microsoft.Zelig.Debugger.ArmProcessor { public interface IMainForm { Microsoft.Zelig.Configuration.Environment.Manager ConfigurationManager { get; } } } ================================================ FILE: Zelig/Zelig/DebugTime/Debugger/Forms/InputForm.Designer.cs ================================================ namespace Microsoft.Zelig.Debugger.ArmProcessor { partial class InputForm { /// /// Required designer variable. /// private System.ComponentModel.IContainer components = null; /// /// Clean up any resources being used. /// /// true if managed resources should be disposed; otherwise, false. protected override void Dispose( bool disposing ) { if(disposing && (components != null)) { components.Dispose(); } base.Dispose( disposing ); } #region Windows Form Designer generated code /// /// Required method for Designer support - do not modify /// the contents of this method with the code editor. /// private void InitializeComponent() { this.textBoxInput = new System.Windows.Forms.TextBox(); this.buttonOk = new System.Windows.Forms.Button(); this.buttonCancel = new System.Windows.Forms.Button(); this.SuspendLayout(); // // textBoxOutputFile // this.textBoxInput.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Left) | System.Windows.Forms.AnchorStyles.Right))); this.textBoxInput.Location = new System.Drawing.Point( 12, 12 ); this.textBoxInput.Name = "textBoxOutputFile"; this.textBoxInput.Size = new System.Drawing.Size( 355, 20 ); this.textBoxInput.TabIndex = 15; // // buttonOk // this.buttonOk.Location = new System.Drawing.Point( 12, 45 ); this.buttonOk.Name = "buttonOk"; this.buttonOk.Size = new System.Drawing.Size( 75, 23 ); this.buttonOk.TabIndex = 16; this.buttonOk.Text = "Ok"; this.buttonOk.UseVisualStyleBackColor = true; this.buttonOk.Click += new System.EventHandler( this.buttonOk_Click ); // // buttonCancel // this.buttonCancel.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Right))); this.buttonCancel.DialogResult = System.Windows.Forms.DialogResult.Cancel; this.buttonCancel.Location = new System.Drawing.Point( 292, 45 ); this.buttonCancel.Name = "buttonCancel"; this.buttonCancel.Size = new System.Drawing.Size( 75, 23 ); this.buttonCancel.TabIndex = 17; this.buttonCancel.Text = "Cancel"; this.buttonCancel.UseVisualStyleBackColor = true; this.buttonCancel.Click += new System.EventHandler( this.buttonCancel_Click ); // // InputForm // this.AcceptButton = this.buttonOk; this.AutoScaleDimensions = new System.Drawing.SizeF( 6F, 13F ); this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font; this.CancelButton = this.buttonCancel; this.ClientSize = new System.Drawing.Size( 379, 80 ); this.ControlBox = false; this.Controls.Add( this.buttonCancel ); this.Controls.Add( this.buttonOk ); this.Controls.Add( this.textBoxInput ); this.Name = "InputForm"; this.ShowIcon = false; this.ShowInTaskbar = false; this.Text = "Rename"; this.ResumeLayout( false ); this.PerformLayout(); } #endregion private System.Windows.Forms.TextBox textBoxInput; private System.Windows.Forms.Button buttonOk; private System.Windows.Forms.Button buttonCancel; } } ================================================ FILE: Zelig/Zelig/DebugTime/Debugger/Forms/InputForm.cs ================================================ using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Text; using System.Windows.Forms; namespace Microsoft.Zelig.Debugger.ArmProcessor { public partial class InputForm : Form { // // State // // // Constructor Methods // public InputForm( string title , string text ) { InitializeComponent(); //--// this.Text = title; textBoxInput.Text = text; } // // Helper Methods // // // Access Methods // public string Result { get { return textBoxInput.Text; } } // // Event Methods // private void buttonOk_Click( object sender , EventArgs e ) { this.DialogResult = DialogResult.OK; this.Close(); } private void buttonCancel_Click( object sender , EventArgs e ) { this.DialogResult = DialogResult.Cancel; this.Close(); } } } ================================================ FILE: Zelig/Zelig/DebugTime/Debugger/Forms/InputForm.resx ================================================ text/microsoft-resx 2.0 System.Resources.ResXResourceReader, System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 System.Resources.ResXResourceWriter, System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 ================================================ FILE: Zelig/Zelig/DebugTime/Debugger/Forms/OutputForm.Designer.cs ================================================ namespace Microsoft.Zelig.Debugger.ArmProcessor { partial class OutputForm { /// /// Required designer variable. /// private System.ComponentModel.IContainer components = null; /// /// Clean up any resources being used. /// /// true if managed resources should be disposed; otherwise, false. protected override void Dispose( bool disposing ) { if(disposing && (components != null)) { components.Dispose(); } base.Dispose( disposing ); } #region Windows Form Designer generated code /// /// Required method for Designer support - do not modify /// the contents of this method with the code editor. /// private void InitializeComponent() { this.components = new System.ComponentModel.Container(); this.checkBoxFileOnly = new System.Windows.Forms.CheckBox(); this.checkBoxNoSleep = new System.Windows.Forms.CheckBox(); this.checkBoxCalls = new System.Windows.Forms.CheckBox(); this.checkBoxInstructions = new System.Windows.Forms.CheckBox(); this.checkBoxRegisters = new System.Windows.Forms.CheckBox(); this.checkBoxMemory = new System.Windows.Forms.CheckBox(); this.buttonLoggingClear = new System.Windows.Forms.Button(); this.richTextBoxOutput = new System.Windows.Forms.RichTextBox(); this.buttonOutputBrowse = new System.Windows.Forms.Button(); this.textBoxOutputFile = new System.Windows.Forms.TextBox(); this.label2 = new System.Windows.Forms.Label(); this.timer1 = new System.Windows.Forms.Timer( this.components ); this.saveLoggingOutputDialog1 = new System.Windows.Forms.SaveFileDialog(); this.checkBoxInterrupts = new System.Windows.Forms.CheckBox(); this.groupBox1 = new System.Windows.Forms.GroupBox(); this.checkBoxCodeCoverage = new System.Windows.Forms.CheckBox(); this.buttonResetCodeCoverage = new System.Windows.Forms.Button(); this.buttonDumpCodeCoverage = new System.Windows.Forms.Button(); this.groupBox1.SuspendLayout(); this.SuspendLayout(); // // checkBoxFileOnly // this.checkBoxFileOnly.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Right))); this.checkBoxFileOnly.AutoSize = true; this.checkBoxFileOnly.Location = new System.Drawing.Point( 539, 9 ); this.checkBoxFileOnly.Name = "checkBoxFileOnly"; this.checkBoxFileOnly.Size = new System.Drawing.Size( 117, 17 ); this.checkBoxFileOnly.TabIndex = 24; this.checkBoxFileOnly.Text = "Output To File Only"; this.checkBoxFileOnly.UseVisualStyleBackColor = true; // // checkBoxNoSleep // this.checkBoxNoSleep.AutoSize = true; this.checkBoxNoSleep.Location = new System.Drawing.Point( 226, 55 ); this.checkBoxNoSleep.Name = "checkBoxNoSleep"; this.checkBoxNoSleep.Size = new System.Drawing.Size( 103, 17 ); this.checkBoxNoSleep.TabIndex = 23; this.checkBoxNoSleep.Text = "Skip Sleep Time"; this.checkBoxNoSleep.UseVisualStyleBackColor = true; this.checkBoxNoSleep.CheckedChanged += new System.EventHandler( this.checkBoxNoSleep_CheckedChanged ); // // checkBoxCalls // this.checkBoxCalls.AutoSize = true; this.checkBoxCalls.Location = new System.Drawing.Point( 15, 32 ); this.checkBoxCalls.Name = "checkBoxCalls"; this.checkBoxCalls.Size = new System.Drawing.Size( 79, 17 ); this.checkBoxCalls.TabIndex = 22; this.checkBoxCalls.Text = "Trace Calls"; this.checkBoxCalls.UseVisualStyleBackColor = true; this.checkBoxCalls.CheckedChanged += new System.EventHandler( this.checkBoxCalls_CheckedChanged ); // // checkBoxInstructions // this.checkBoxInstructions.AutoSize = true; this.checkBoxInstructions.Location = new System.Drawing.Point( 111, 55 ); this.checkBoxInstructions.Name = "checkBoxInstructions"; this.checkBoxInstructions.Size = new System.Drawing.Size( 111, 17 ); this.checkBoxInstructions.TabIndex = 21; this.checkBoxInstructions.Text = "Trace Instructions"; this.checkBoxInstructions.UseVisualStyleBackColor = true; this.checkBoxInstructions.CheckedChanged += new System.EventHandler( this.checkBoxInstructions_CheckedChanged ); // // checkBoxRegisters // this.checkBoxRegisters.AutoSize = true; this.checkBoxRegisters.Location = new System.Drawing.Point( 111, 32 ); this.checkBoxRegisters.Name = "checkBoxRegisters"; this.checkBoxRegisters.Size = new System.Drawing.Size( 101, 17 ); this.checkBoxRegisters.TabIndex = 20; this.checkBoxRegisters.Text = "Trace Registers"; this.checkBoxRegisters.UseVisualStyleBackColor = true; this.checkBoxRegisters.CheckedChanged += new System.EventHandler( this.checkBoxRegisters_CheckedChanged ); // // checkBoxMemory // this.checkBoxMemory.AutoSize = true; this.checkBoxMemory.Location = new System.Drawing.Point( 15, 55 ); this.checkBoxMemory.Name = "checkBoxMemory"; this.checkBoxMemory.Size = new System.Drawing.Size( 94, 17 ); this.checkBoxMemory.TabIndex = 19; this.checkBoxMemory.Text = "Trace Memory"; this.checkBoxMemory.UseVisualStyleBackColor = true; this.checkBoxMemory.CheckedChanged += new System.EventHandler( this.checkBoxMemory_CheckedChanged ); // // buttonLoggingClear // this.buttonLoggingClear.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Right))); this.buttonLoggingClear.Location = new System.Drawing.Point( 581, 430 ); this.buttonLoggingClear.Name = "buttonLoggingClear"; this.buttonLoggingClear.Size = new System.Drawing.Size( 75, 23 ); this.buttonLoggingClear.TabIndex = 18; this.buttonLoggingClear.Text = "Clear"; this.buttonLoggingClear.UseVisualStyleBackColor = true; this.buttonLoggingClear.Click += new System.EventHandler( this.buttonLoggingClear_Click ); // // richTextBoxOutput // this.richTextBoxOutput.Anchor = ((System.Windows.Forms.AnchorStyles)((((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Bottom) | System.Windows.Forms.AnchorStyles.Left) | System.Windows.Forms.AnchorStyles.Right))); this.richTextBoxOutput.Font = new System.Drawing.Font( "Courier New", 8F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)) ); this.richTextBoxOutput.Location = new System.Drawing.Point( 12, 95 ); this.richTextBoxOutput.Name = "richTextBoxOutput"; this.richTextBoxOutput.Size = new System.Drawing.Size( 644, 329 ); this.richTextBoxOutput.TabIndex = 17; this.richTextBoxOutput.Text = ""; this.richTextBoxOutput.WordWrap = false; // // buttonOutputBrowse // this.buttonOutputBrowse.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Right))); this.buttonOutputBrowse.Location = new System.Drawing.Point( 469, 5 ); this.buttonOutputBrowse.Name = "buttonOutputBrowse"; this.buttonOutputBrowse.Size = new System.Drawing.Size( 64, 23 ); this.buttonOutputBrowse.TabIndex = 16; this.buttonOutputBrowse.Text = "Browse ..."; this.buttonOutputBrowse.UseVisualStyleBackColor = true; this.buttonOutputBrowse.Click += new System.EventHandler( this.buttonOutputBrowse_Click ); // // textBoxOutputFile // this.textBoxOutputFile.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Left) | System.Windows.Forms.AnchorStyles.Right))); this.textBoxOutputFile.Location = new System.Drawing.Point( 76, 6 ); this.textBoxOutputFile.Name = "textBoxOutputFile"; this.textBoxOutputFile.Size = new System.Drawing.Size( 387, 20 ); this.textBoxOutputFile.TabIndex = 15; // // label2 // this.label2.AutoSize = true; this.label2.Location = new System.Drawing.Point( 12, 9 ); this.label2.Name = "label2"; this.label2.Size = new System.Drawing.Size( 58, 13 ); this.label2.TabIndex = 14; this.label2.Text = "Output file:"; // // timer1 // this.timer1.Interval = 50; // // checkBoxInterrupts // this.checkBoxInterrupts.AutoSize = true; this.checkBoxInterrupts.Location = new System.Drawing.Point( 226, 32 ); this.checkBoxInterrupts.Name = "checkBoxInterrupts"; this.checkBoxInterrupts.Size = new System.Drawing.Size( 101, 17 ); this.checkBoxInterrupts.TabIndex = 25; this.checkBoxInterrupts.Text = "Trace Interrupts"; this.checkBoxInterrupts.UseVisualStyleBackColor = true; this.checkBoxInterrupts.CheckedChanged += new System.EventHandler( this.checkBoxInterrupts_CheckedChanged ); // // groupBox1 // this.groupBox1.Controls.Add( this.checkBoxCodeCoverage ); this.groupBox1.Controls.Add( this.buttonResetCodeCoverage ); this.groupBox1.Controls.Add( this.buttonDumpCodeCoverage ); this.groupBox1.Location = new System.Drawing.Point( 349, 33 ); this.groupBox1.Name = "groupBox1"; this.groupBox1.Size = new System.Drawing.Size( 307, 56 ); this.groupBox1.TabIndex = 26; this.groupBox1.TabStop = false; this.groupBox1.Text = "Code Coverage"; // // checkBoxCodeCoverage // this.checkBoxCodeCoverage.AutoSize = true; this.checkBoxCodeCoverage.Location = new System.Drawing.Point( 7, 22 ); this.checkBoxCodeCoverage.Name = "checkBoxCodeCoverage"; this.checkBoxCodeCoverage.Size = new System.Drawing.Size( 84, 17 ); this.checkBoxCodeCoverage.TabIndex = 2; this.checkBoxCodeCoverage.Text = "Collect Data"; this.checkBoxCodeCoverage.UseVisualStyleBackColor = true; this.checkBoxCodeCoverage.CheckedChanged += new System.EventHandler( this.checkBoxCodeCoverage_CheckedChanged ); // // buttonResetCodeCoverage // this.buttonResetCodeCoverage.Enabled = false; this.buttonResetCodeCoverage.Location = new System.Drawing.Point( 109, 18 ); this.buttonResetCodeCoverage.Name = "buttonResetCodeCoverage"; this.buttonResetCodeCoverage.Size = new System.Drawing.Size( 75, 23 ); this.buttonResetCodeCoverage.TabIndex = 0; this.buttonResetCodeCoverage.Text = "Reset"; this.buttonResetCodeCoverage.UseVisualStyleBackColor = true; this.buttonResetCodeCoverage.Click += new System.EventHandler( this.buttonResetCodeCoverage_Click ); // // buttonDumpCodeCoverage // this.buttonDumpCodeCoverage.Enabled = false; this.buttonDumpCodeCoverage.Location = new System.Drawing.Point( 190, 18 ); this.buttonDumpCodeCoverage.Name = "buttonDumpCodeCoverage"; this.buttonDumpCodeCoverage.Size = new System.Drawing.Size( 75, 23 ); this.buttonDumpCodeCoverage.TabIndex = 1; this.buttonDumpCodeCoverage.Text = "Dump"; this.buttonDumpCodeCoverage.UseVisualStyleBackColor = true; this.buttonDumpCodeCoverage.Click += new System.EventHandler( this.buttonDumpCodeCoverage_Click ); // // OutputForm // this.AutoScaleDimensions = new System.Drawing.SizeF( 6F, 13F ); this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font; this.ClientSize = new System.Drawing.Size( 668, 465 ); this.Controls.Add( this.groupBox1 ); this.Controls.Add( this.checkBoxInterrupts ); this.Controls.Add( this.checkBoxFileOnly ); this.Controls.Add( this.checkBoxNoSleep ); this.Controls.Add( this.checkBoxCalls ); this.Controls.Add( this.checkBoxInstructions ); this.Controls.Add( this.checkBoxRegisters ); this.Controls.Add( this.checkBoxMemory ); this.Controls.Add( this.buttonLoggingClear ); this.Controls.Add( this.richTextBoxOutput ); this.Controls.Add( this.buttonOutputBrowse ); this.Controls.Add( this.textBoxOutputFile ); this.Controls.Add( this.label2 ); this.KeyPreview = true; this.Name = "OutputForm"; this.Text = "Debug Output"; this.groupBox1.ResumeLayout( false ); this.groupBox1.PerformLayout(); this.ResumeLayout( false ); this.PerformLayout(); } #endregion private System.Windows.Forms.CheckBox checkBoxFileOnly; private System.Windows.Forms.CheckBox checkBoxNoSleep; private System.Windows.Forms.CheckBox checkBoxCalls; private System.Windows.Forms.CheckBox checkBoxInstructions; private System.Windows.Forms.CheckBox checkBoxRegisters; private System.Windows.Forms.CheckBox checkBoxMemory; private System.Windows.Forms.Button buttonLoggingClear; private System.Windows.Forms.RichTextBox richTextBoxOutput; private System.Windows.Forms.Button buttonOutputBrowse; private System.Windows.Forms.TextBox textBoxOutputFile; private System.Windows.Forms.Label label2; private System.Windows.Forms.Timer timer1; private System.Windows.Forms.SaveFileDialog saveLoggingOutputDialog1; private System.Windows.Forms.CheckBox checkBoxInterrupts; private System.Windows.Forms.GroupBox groupBox1; private System.Windows.Forms.CheckBox checkBoxCodeCoverage; private System.Windows.Forms.Button buttonResetCodeCoverage; private System.Windows.Forms.Button buttonDumpCodeCoverage; } } ================================================ FILE: Zelig/Zelig/DebugTime/Debugger/Forms/OutputForm.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // namespace Microsoft.Zelig.Debugger.ArmProcessor { using System; using System.Collections.Generic; using System.ComponentModel; using System.IO; using System.Data; using System.Drawing; using System.Text; using System.Windows.Forms; public partial class OutputForm : Emulation.Hosting.Forms.BaseDebuggerForm { class OutputSinkImpl : Emulation.Hosting.OutputSink { const int c_RedirectLinesPerFile = 100000; // // State // OutputForm m_owner; System.IO.TextWriter m_output; string m_outputFile; bool m_outputEnabled = false; int m_outputLines; int m_outputNum; // // Constructor Methods // internal OutputSinkImpl( OutputForm owner ) { m_owner = owner; m_owner.Host.RegisterService( typeof(Emulation.Hosting.OutputSink), this ); } // // Helper Methods // public void CloseOutput() { if(m_output != null) { m_output.Close(); m_output = null; } } private void OpenOutput() { if(c_RedirectLinesPerFile > 0) { if(m_outputLines >= c_RedirectLinesPerFile) { m_output.Close(); m_output = null; } } if(m_output == null) { string file = m_outputFile; if(c_RedirectLinesPerFile > 0) { file = String.Format( "{0}.{1:D8}", file, m_outputNum++ ); } Directory.CreateDirectory( Path.GetDirectoryName( file ) ); m_output = new System.IO.StreamWriter( file ); m_outputLines = 0; } } //--// public override void SetOutput( string file ) { m_outputFile = Environment.ExpandEnvironmentVariables( file ); m_outputNum = 0; m_outputLines = 0; CloseOutput(); } public override void StartOutput() { m_outputEnabled = true; } public override void OutputLine( string format , params object[] args ) { if(!m_outputEnabled) return; OpenOutput(); try { if(args.Length > 0) { m_output.WriteLine( format, args ); } else { m_output.WriteLine( format ); } m_output.Flush(); m_outputLines++; m_owner.OutputLine( format, args ); } catch { } } public override void OutputChar( char c ) { if(!m_outputEnabled) return; OpenOutput(); m_output.Write( "{0}", c ); m_output.Flush(); if(c == '\n') { m_outputLines++; } m_owner.OutputChar( c ); } } // // State // Queue< string > m_output; OutputSinkImpl m_implOutputSink; // // Constructor Methods // public OutputForm( Emulation.Hosting.Forms.HostingSite site ) : base( site ) { InitializeComponent(); //--// m_output = new Queue(); //--// const string outputFile = @"%DEPOTROOT%\ZeligUnitTestResults\ArmEmulator\log.txt"; textBoxOutputFile.Text = outputFile; m_implOutputSink = new OutputSinkImpl( this ); m_implOutputSink.SetOutput( outputFile ); //--// timer1.Tick += new EventHandler( UpdateTimerCallback ); //--// site.RegisterView( this, Emulation.Hosting.Forms.HostingSite.PublicationMode.View ); } // // Helper Methods // protected override void NotifyChangeInVisibility( bool fVisible ) { if(fVisible) { timer1.Start(); } else { timer1.Stop(); } } void OutputLine( string format , params object[] args ) { if(checkBoxFileOnly.Checked) { return; } string text = args.Length > 0 ? String.Format( format, args ) : format; OutputText( text + "\r\n" ); } void OutputChar( char c ) { OutputText( new string( c, 1 ) ); } void OutputText( string text ) { lock(this) { m_output.Enqueue( text ); } } // // Access Methods // public override string ViewTitle { get { return "&Output"; } } // // Event Methods // private void UpdateTimerCallback( object sender , EventArgs e ) { StringBuilder sb = null; lock(this) { if(m_output.Count > 0) { sb = new StringBuilder(); while(m_output.Count > 0) { sb.Append( m_output.Dequeue() ); } } } if(sb != null) { richTextBoxOutput.AppendText( sb.ToString() ); if(richTextBoxOutput.Focused == false) { richTextBoxOutput.ScrollToCaret(); } } } private void buttonLoggingClear_Click( object sender , EventArgs e ) { richTextBoxOutput.Clear(); } private void buttonOutputBrowse_Click( object sender , EventArgs e ) { saveLoggingOutputDialog1.FileName = Environment.ExpandEnvironmentVariables( textBoxOutputFile.Text ); if(saveLoggingOutputDialog1.ShowDialog() == DialogResult.OK) { textBoxOutputFile.Text = saveLoggingOutputDialog1.FileName; Emulation.Hosting.OutputSink sink; if(this.Host.GetHostingService( out sink )) { sink.SetOutput( textBoxOutputFile.Text ); } } } private void checkBoxCalls_CheckedChanged( object sender , EventArgs e ) { Emulation.Hosting.MonitorExecution svcME; if(this.Host.GetHostingService( out svcME )) { svcME.MonitorCalls = checkBoxCalls.Checked; } } private void checkBoxMemory_CheckedChanged( object sender , EventArgs e ) { Emulation.Hosting.MonitorExecution svcME; if(this.Host.GetHostingService( out svcME )) { svcME.MonitorMemory = checkBoxMemory.Checked; } } private void checkBoxRegisters_CheckedChanged( object sender , EventArgs e ) { Emulation.Hosting.MonitorExecution svcME; if(this.Host.GetHostingService( out svcME )) { svcME.MonitorRegisters = checkBoxRegisters.Checked; } } private void checkBoxInstructions_CheckedChanged( object sender , EventArgs e ) { Emulation.Hosting.MonitorExecution svcME; if(this.Host.GetHostingService( out svcME )) { svcME.MonitorOpcodes = checkBoxInstructions.Checked; } } private void checkBoxInterrupts_CheckedChanged( object sender , EventArgs e ) { Emulation.Hosting.MonitorExecution svcME; if(this.Host.GetHostingService( out svcME )) { svcME.MonitorInterrupts = checkBoxInterrupts.Checked; } } private void checkBoxNoSleep_CheckedChanged( object sender , EventArgs e ) { Emulation.Hosting.MonitorExecution svcME; if(this.Host.GetHostingService( out svcME )) { svcME.NoSleep = checkBoxNoSleep.Checked; } } private void checkBoxCodeCoverage_CheckedChanged( object sender , EventArgs e ) { bool fEnable = checkBoxCodeCoverage.Checked; Emulation.Hosting.CodeCoverage svc; if(this.Host.GetHostingService( out svc )) { svc.Enable = fEnable; } buttonDumpCodeCoverage .Enabled = fEnable; buttonResetCodeCoverage.Enabled = fEnable; } private void buttonResetCodeCoverage_Click( object sender , EventArgs e ) { if(this.Host.IsIdle) { Emulation.Hosting.CodeCoverage svc; if(this.Host.GetHostingService( out svc )) { svc.Reset(); } } } private void buttonDumpCodeCoverage_Click( object sender , EventArgs e ) { if(this.Host.IsIdle) { Emulation.Hosting.CodeCoverage svc; if(this.Host.GetHostingService( out svc )) { svc.Dump(); } } } } } ================================================ FILE: Zelig/Zelig/DebugTime/Debugger/Forms/OutputForm.resx ================================================ text/microsoft-resx 2.0 System.Resources.ResXResourceReader, System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 System.Resources.ResXResourceWriter, System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 17, 17 285, 17 ================================================ FILE: Zelig/Zelig/DebugTime/Debugger/Forms/ProfilerMainForm.Designer.cs ================================================ namespace Microsoft.Zelig.Debugger.ArmProcessor { partial class ProfilerMainForm { /// /// Required designer variable. /// private System.ComponentModel.IContainer components = null; /// /// Clean up any resources being used. /// /// true if managed resources should be disposed; otherwise, false. protected override void Dispose( bool disposing ) { if(disposing && (components != null)) { components.Dispose(); } base.Dispose( disposing ); } #region Windows Form Designer generated code /// /// Required method for Designer support - do not modify /// the contents of this method with the code editor. /// private void InitializeComponent() { this.panelTop = new System.Windows.Forms.Panel(); this.toolStrip1 = new System.Windows.Forms.ToolStrip(); this.toolStripButton_New = new System.Windows.Forms.ToolStripButton(); this.toolStripButton_Start = new System.Windows.Forms.ToolStripButton(); this.toolStripButton_Stop = new System.Windows.Forms.ToolStripButton(); this.toolStripComboBox_Mode = new System.Windows.Forms.ToolStripComboBox(); this.toolStripSeparator1 = new System.Windows.Forms.ToolStripSeparator(); this.toolStripComboBox_View = new System.Windows.Forms.ToolStripComboBox(); this.panelBottom = new System.Windows.Forms.Panel(); this.panelTop.SuspendLayout(); this.toolStrip1.SuspendLayout(); this.SuspendLayout(); // // panelTop // this.panelTop.Controls.Add( this.toolStrip1 ); this.panelTop.Dock = System.Windows.Forms.DockStyle.Top; this.panelTop.Location = new System.Drawing.Point( 0, 0 ); this.panelTop.Name = "panelTop"; this.panelTop.Size = new System.Drawing.Size( 668, 25 ); this.panelTop.TabIndex = 0; // // toolStrip1 // this.toolStrip1.GripStyle = System.Windows.Forms.ToolStripGripStyle.Hidden; this.toolStrip1.Items.AddRange( new System.Windows.Forms.ToolStripItem[] { this.toolStripButton_New, this.toolStripButton_Start, this.toolStripButton_Stop, this.toolStripComboBox_Mode, this.toolStripSeparator1, this.toolStripComboBox_View} ); this.toolStrip1.Location = new System.Drawing.Point( 0, 0 ); this.toolStrip1.Name = "toolStrip1"; this.toolStrip1.Size = new System.Drawing.Size( 668, 25 ); this.toolStrip1.TabIndex = 4; this.toolStrip1.Text = "toolStrip1"; // // toolStripButton_New // this.toolStripButton_New.DisplayStyle = System.Windows.Forms.ToolStripItemDisplayStyle.Image; this.toolStripButton_New.Image = global::Microsoft.Zelig.Debugger.ArmProcessor.Properties.Resources.NewSession; this.toolStripButton_New.ImageTransparentColor = System.Drawing.Color.Transparent; this.toolStripButton_New.Name = "toolStripButton_New"; this.toolStripButton_New.Size = new System.Drawing.Size( 23, 22 ); this.toolStripButton_New.Text = "New"; this.toolStripButton_New.ToolTipText = "Create New Profiling Session"; this.toolStripButton_New.Click += new System.EventHandler( this.toolStripButton_New_Click ); // // toolStripButton_Start // this.toolStripButton_Start.DisplayStyle = System.Windows.Forms.ToolStripItemDisplayStyle.Image; this.toolStripButton_Start.Image = global::Microsoft.Zelig.Debugger.ArmProcessor.Properties.Resources.StartSession; this.toolStripButton_Start.ImageTransparentColor = System.Drawing.Color.Transparent; this.toolStripButton_Start.Name = "toolStripButton_Start"; this.toolStripButton_Start.Size = new System.Drawing.Size( 23, 22 ); this.toolStripButton_Start.Text = "Start"; this.toolStripButton_Start.ToolTipText = "Start Collecting Data"; this.toolStripButton_Start.Click += new System.EventHandler( this.toolStripButton_Start_Click ); // // toolStripButton_Stop // this.toolStripButton_Stop.DisplayStyle = System.Windows.Forms.ToolStripItemDisplayStyle.Image; this.toolStripButton_Stop.Image = global::Microsoft.Zelig.Debugger.ArmProcessor.Properties.Resources.StopSession; this.toolStripButton_Stop.ImageTransparentColor = System.Drawing.Color.Transparent; this.toolStripButton_Stop.Name = "toolStripButton_Stop"; this.toolStripButton_Stop.Size = new System.Drawing.Size( 23, 22 ); this.toolStripButton_Stop.Text = "Stop"; this.toolStripButton_Stop.ToolTipText = "Stop Collecting Data"; this.toolStripButton_Stop.Click += new System.EventHandler( this.toolStripButton_Stop_Click ); // // toolStripComboBox_Mode // this.toolStripComboBox_Mode.DropDownStyle = System.Windows.Forms.ComboBoxStyle.DropDownList; this.toolStripComboBox_Mode.Items.AddRange( new object[] { "Calls Only", "Calls and Allocations"} ); this.toolStripComboBox_Mode.Name = "toolStripComboBox_Mode"; this.toolStripComboBox_Mode.Size = new System.Drawing.Size( 121, 25 ); // // toolStripSeparator1 // this.toolStripSeparator1.Name = "toolStripSeparator1"; this.toolStripSeparator1.Size = new System.Drawing.Size( 6, 25 ); // // toolStripComboBox_View // this.toolStripComboBox_View.DropDownStyle = System.Windows.Forms.ComboBoxStyle.DropDownList; this.toolStripComboBox_View.Items.AddRange( new object[] { "Call Tree", "Functions", "Classes", "Caller / Callee", "Memory Allocations"} ); this.toolStripComboBox_View.Name = "toolStripComboBox_View"; this.toolStripComboBox_View.Size = new System.Drawing.Size( 121, 25 ); this.toolStripComboBox_View.SelectedIndexChanged += new System.EventHandler( this.toolStripComboBox_View_SelectedIndexChanged ); // // panelBottom // this.panelBottom.Dock = System.Windows.Forms.DockStyle.Fill; this.panelBottom.Location = new System.Drawing.Point( 0, 25 ); this.panelBottom.Name = "panelBottom"; this.panelBottom.Size = new System.Drawing.Size( 668, 440 ); this.panelBottom.TabIndex = 1; // // ProfilerMainForm // this.AutoScaleDimensions = new System.Drawing.SizeF( 6F, 13F ); this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font; this.ClientSize = new System.Drawing.Size( 668, 465 ); this.Controls.Add( this.panelBottom ); this.Controls.Add( this.panelTop ); this.KeyPreview = true; this.Name = "ProfilerMainForm"; this.Text = "Profiler Control"; this.panelTop.ResumeLayout( false ); this.panelTop.PerformLayout(); this.toolStrip1.ResumeLayout( false ); this.toolStrip1.PerformLayout(); this.ResumeLayout( false ); } #endregion private System.Windows.Forms.Panel panelTop; private System.Windows.Forms.Panel panelBottom; private System.Windows.Forms.ToolStrip toolStrip1; private System.Windows.Forms.ToolStripButton toolStripButton_New; private System.Windows.Forms.ToolStripButton toolStripButton_Start; private System.Windows.Forms.ToolStripButton toolStripButton_Stop; private System.Windows.Forms.ToolStripComboBox toolStripComboBox_Mode; private System.Windows.Forms.ToolStripSeparator toolStripSeparator1; private System.Windows.Forms.ToolStripComboBox toolStripComboBox_View; } } ================================================ FILE: Zelig/Zelig/DebugTime/Debugger/Forms/ProfilerMainForm.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // namespace Microsoft.Zelig.Debugger.ArmProcessor { using System; using System.Collections.Generic; using System.ComponentModel; using System.IO; using System.Data; using System.Drawing; using System.Text; using System.Windows.Forms; using IR = Microsoft.Zelig.CodeGeneration.IR; using RT = Microsoft.Zelig.Runtime; using TS = Microsoft.Zelig.Runtime.TypeSystem; using Hst = Microsoft.Zelig.Emulation.Hosting; public partial class ProfilerMainForm : Emulation.Hosting.Forms.BaseDebuggerForm { // // State // private Profiler m_profiler; private Profiler.Callers m_profiler_Callers; private Profiler.Callees m_profiler_Callees; private Profiler.CallsByMethodAndType m_profiler_CallsByMethodAndType; private Emulation.Hosting.DeviceClockTicksTracking m_svcTiming; private TS.MethodRepresentation m_selectedMethod; private int m_verProfiler = 1; private int m_verCallTree; private int m_verFunctions; private int m_verClasses; private int m_verAllocations; private TreeBasedGridView m_treeBasedGridView_CallTree; private TreeBasedGridView m_treeBasedGridView_Functions; private TreeBasedGridView m_treeBasedGridView_Classes; private TS.MethodRepresentation m_treeBasedGridView_CallerCallee_Method; private SplitContainer m_treeBasedGridView_CallerCallee_Top; private SplitContainer m_treeBasedGridView_CallerCallee_Bottom; private TreeBasedGridView m_treeBasedGridView_CallerCallee_Callers; private TreeBasedGridView m_treeBasedGridView_CallerCallee; private TreeBasedGridView m_treeBasedGridView_CallerCallee_Callees; private TreeBasedGridView m_treeBasedGridView_Allocations; // // Constructor Methods // public ProfilerMainForm( Emulation.Hosting.Forms.HostingSite site ) : base( site ) { InitializeComponent(); //--// UpdateButtonState(); toolStripComboBox_Mode.SelectedIndex = 0; toolStripComboBox_View.SelectedIndex = 0; //--// site.RegisterView( this, Emulation.Hosting.Forms.HostingSite.PublicationMode.Tools ); site.NotifyOnExecutionStateChange += delegate( Hst.Forms.HostingSite host , Hst.Forms.HostingSite.ExecutionState oldState , Hst.Forms.HostingSite.ExecutionState newState ) { if(newState == Hst.Forms.HostingSite.ExecutionState.Loaded) { DeallocateProfiler(); } UpdateButtonState(); return Hst.Forms.HostingSite.NotificationResponse.DoNothing; }; } // // Helper Methods // private void AllocateProfiler() { if(m_profiler == null) { ImageInformation imageInformation; this.Host.GetHostingService( out imageInformation ); Emulation.Hosting.AbstractHost host; this.Host.GetHostingService( out host ); MemoryDelta memDelta = new MemoryDelta( imageInformation, host ); memDelta.RegisterForNotification( false, true ); m_profiler = new Profiler( memDelta ); host.GetHostingService( out m_svcTiming ); } } private void DeallocateProfiler() { if(m_profiler != null) { m_profiler.Detach(); m_profiler = null; UpdateUI(); } } private void UpdateButtonState() { if(this.Host.IsIdle) { if(m_profiler != null && m_profiler.IsActive) { toolStripButton_New .Enabled = false; toolStripButton_Start.Enabled = false; toolStripButton_Stop .Enabled = true; } else { toolStripButton_New .Enabled = true; toolStripButton_Start.Enabled = true; toolStripButton_Stop .Enabled = false; } } else { toolStripButton_New .Enabled = false; toolStripButton_Start.Enabled = false; toolStripButton_Stop .Enabled = false; } } private void SwitchToViewMode( Control ctrl ) { this.panelBottom.SuspendLayout(); this.panelBottom.Controls.Clear(); if(ctrl != null) { this.panelBottom.Controls.Add( ctrl ); } this.panelBottom.ResumeLayout(); } private void UpdateUI() { if(m_profiler == null) { SwitchToViewMode( null ); } else { switch(toolStripComboBox_View.SelectedIndex) { //// Call Tree case 0: BuildUI_CallTree(); break; //// Functions case 1: BuildUI_Functions(); break; //// Classes case 2: BuildUI_Classes(); break; //// Caller / Callee case 3: BuildUI_CallerCallee(); break; //// Memory Allocations case 4: BuildUI_Allocations(); break; } } } //--// private void BuildUI_CallTree() { if(m_treeBasedGridView_CallTree == null) { var tree = BuildTree_Call(); m_treeBasedGridView_CallTree = tree; tree.NodeMouseClick += treeBasedGridView_NodeMouseClick; tree.NodeMouseDoubleClick += treeBasedGridView_NodeMouseDoubleClick; } if(m_verCallTree != m_verProfiler) { m_verCallTree = m_verProfiler; var root = m_treeBasedGridView_CallTree.RootNode; root.Clear(); long inclusiveCycles = ComputeTotalInclusiveCycles(); foreach(var tc in m_profiler.Threads) { var en = tc.TopLevel; if(en.Children != null) { string fmt; switch(tc.ThreadKind) { case ThreadStatus.Kind.Bootstrap : fmt = "Bootstrap" ; break; case ThreadStatus.Kind.IdleThread : fmt = "Idle Thread"; break; case ThreadStatus.Kind.InterruptThread : fmt = "IRQ Thread" ; break; case ThreadStatus.Kind.FastInterruptThread: fmt = "FIQ Thread" ; break; default : fmt = "Thread {0}" ; break; } var node = root.AddChild( string.Format( fmt, tc.ManagedThreadId ), en.InclusiveAllocatedBytes.ToString(), PrintNumber( en.InclusiveClockCycles ), PrintTime( en.InclusiveClockCycles ), PrintPercentage( en.InclusiveClockCycles, inclusiveCycles ) ); node.Tag = tc; node.ExpandCallback = ExpandNode_CallTree; } } } SwitchToViewMode( m_treeBasedGridView_CallTree ); } private void ExpandNode_CallTree( TreeBasedGridView.GridNode node ) { Profiler.CallEntry en; if(node.Tag is Profiler.ThreadContext) { var tc = (Profiler.ThreadContext)node.Tag; en = tc.TopLevel; } else { en = (Profiler.CallEntry)node.Tag; } if(en.Children != null) { ExpandNode_CallTree( node, en, 0, en.Children.Count ); } } private void ExpandNode_CallTree( TreeBasedGridView.GridNode node , Profiler.CallEntry en , int startIndex , int endIndex ) { const int MaxArrayDisplay = 100; int length = endIndex - startIndex; if(length > MaxArrayDisplay) { int scale = MaxArrayDisplay; while(scale * MaxArrayDisplay < length) { scale *= MaxArrayDisplay; } for(int pos = startIndex; pos < endIndex; pos += scale) { int newStartIndex = pos; int newEndIndex = Math.Min( pos + scale, endIndex ); long inclusiveCycles = 0; long inclusiveAllocatedBytes = 0; for(int pos2 = newStartIndex; pos2 < newEndIndex; pos2++) { var subEn = en.Children[pos2]; inclusiveCycles += subEn.InclusiveClockCycles; inclusiveAllocatedBytes += subEn.InclusiveAllocatedBytes; } var newNode = node.AddChild( string.Format( "[Calls {0}-{1}]", newStartIndex + 1, newEndIndex ), inclusiveAllocatedBytes.ToString(), PrintNumber( inclusiveCycles ), PrintTime( inclusiveCycles ), PrintPercentage( inclusiveCycles, en.Owner.TopLevel.InclusiveClockCycles ) ); newNode.ExpandCallback = delegate( TreeBasedGridView.GridNode nodeSub ) { ExpandNode_CallTree( nodeSub, en, newStartIndex, newEndIndex ); }; } } else { for(int pos = startIndex; pos < endIndex; pos++) { var subEn = en.Children[pos]; AddEntry_CallTree( node, subEn ); } } } private void AddEntry_CallTree( TreeBasedGridView.GridNode node , Profiler.CallEntry en ) { var subNode = node.AddChild( en.Method.ToShortStringNoReturnValue(), en.InclusiveAllocatedBytes.ToString(), PrintNumber( en.InclusiveClockCycles ), PrintTime( en.InclusiveClockCycles ), PrintPercentage( en.InclusiveClockCycles, en.Owner.TopLevel.InclusiveClockCycles ), PrintNumber( en.ExclusiveClockCycles ), PrintTime( en.ExclusiveClockCycles ), PrintPercentage( en.ExclusiveClockCycles, en.Owner.TopLevel.InclusiveClockCycles ) ); subNode.Tag = en; subNode.ExpandCallback = ExpandNode_CallTree; } //--// private void BuildUI_Functions() { if(m_treeBasedGridView_Functions == null) { var tree = BuildTree_Function(); m_treeBasedGridView_Functions = tree; tree.NodeMouseClick += treeBasedGridView_NodeMouseClick; tree.NodeMouseDoubleClick += treeBasedGridView_NodeMouseDoubleClick; } if(m_verFunctions != m_verProfiler) { m_verFunctions = m_verProfiler; var coll = CacheGetCallsByMethodAndType(); var root = m_treeBasedGridView_Functions.RootNode; root.Clear(); long totalCycles = ComputeTotalInclusiveCycles(); var array = coll.ToArray(); Array.Sort( array, (x, y) => { return y.Value.ExclusiveClockCycles.CompareTo( x.Value.ExclusiveClockCycles ); } ); foreach(var pair in array) { var md = pair.Key; var collByMethod = pair.Value; var callsByMethod = collByMethod[md.OwnerType].Count; var clockCyclesByMethod = collByMethod.ExclusiveClockCycles; var allocatedBytesByMethod = collByMethod.AllocatedBytes; var nodeByMethod = root.AddChild( md.ToShortStringNoReturnValue(), allocatedBytesByMethod.ToString(), callsByMethod.ToString(), PrintNumber ( clockCyclesByMethod ), PrintFraction( clockCyclesByMethod, callsByMethod ), PrintTime ( clockCyclesByMethod ), PrintTime ( clockCyclesByMethod, callsByMethod ), PrintPercentage( clockCyclesByMethod, totalCycles ) ); nodeByMethod.Tag = md; //// nodeByMethod.ExpandCallback = delegate( TreeBasedGridView.GridNode nodeSub ) //// { //// foreach(var td in collByMethod.Keys) //// { //// var collByType = collByMethod[td]; //// var clockCyclesByType = collByType.ClockCycles; //// var allocatedBytesByType = collByType.AllocatedBytes; //// //// var nodeByType = nodeByMethod.AddChild( td.FullNameWithAbbreviation, allocatedBytesByType.ToString(), //// PrintNumber( clockCyclesByType ), PrintTime( clockCyclesByType ), PrintPercentage( clockCyclesByType, clockCyclesByMethod ) ); //// //// } //// }; } } SwitchToViewMode( m_treeBasedGridView_Functions ); } //--// private long ComputeTotalInclusiveCycles() { long totalCycles = 0; foreach(var tc in m_profiler.Threads) { var en = tc.TopLevel; totalCycles += en.InclusiveClockCycles; } return totalCycles; } private Profiler.CallsByMethodAndType CacheGetCallsByMethodAndType() { if(m_profiler_CallsByMethodAndType == null) { m_profiler_CallsByMethodAndType = m_profiler.GetCallsByMethod(); } return m_profiler_CallsByMethodAndType; } private Profiler.Callers CacheGetCallers() { if(m_profiler_Callers == null) { m_profiler.GetCallersAndCallees( out m_profiler_Callers, out m_profiler_Callees ); } return m_profiler_Callers; } private Profiler.Callees CacheGetCallees() { if(m_profiler_Callees == null) { m_profiler.GetCallersAndCallees( out m_profiler_Callers, out m_profiler_Callees ); } return m_profiler_Callees; } //--// private void BuildUI_Classes() { if(m_treeBasedGridView_Classes == null) { var tree = BuildTree(); m_treeBasedGridView_Classes = tree; tree.NodeMouseClick += treeBasedGridView_NodeMouseClick; tree.NodeMouseDoubleClick += treeBasedGridView_NodeMouseDoubleClick; tree.SetColumns( new TreeBasedGridView.GridColumnDefinition( "Class" , DataGridViewContentAlignment.MiddleLeft , false, false, false ), new TreeBasedGridView.GridColumnDefinition( "Allocated Bytes" , DataGridViewContentAlignment.MiddleRight, false, false, false ), new TreeBasedGridView.GridColumnDefinition( "Exclusive Cycles", DataGridViewContentAlignment.MiddleRight, false, false, false ), new TreeBasedGridView.GridColumnDefinition( "Exclusive Time" , DataGridViewContentAlignment.MiddleRight, false, false, false ), new TreeBasedGridView.GridColumnDefinition( "Exclusive CPU%" , DataGridViewContentAlignment.MiddleRight, false, false, false ) ); } if(m_verClasses != m_verProfiler) { m_verClasses = m_verProfiler; var coll = m_profiler.GetCallsByType(); var root = m_treeBasedGridView_Classes.RootNode; root.Clear(); long totalCycles = ComputeTotalInclusiveCycles(); var array = coll.ToArray(); Array.Sort( array, (x, y) => { return y.Value.ExclusiveClockCycles.CompareTo( x.Value.ExclusiveClockCycles ); } ); foreach(var pair in array) { var td = pair.Key; var collByType = pair.Value; var clockCyclesByType = collByType.ExclusiveClockCycles; var allocatedBytesByType = collByType.AllocatedBytes; var nodeByType = root.AddChild( td.FullNameWithAbbreviation, allocatedBytesByType.ToString(), PrintNumber( clockCyclesByType ), PrintTime( clockCyclesByType ), PrintPercentage( clockCyclesByType, totalCycles ) ); nodeByType.ExpandCallback = delegate( TreeBasedGridView.GridNode nodeSub ) { foreach(var md in collByType.Keys) { var collByMethod = collByType[md]; var clockCyclesByMethod = collByMethod.ExclusiveClockCycles; var allocatedBytesByMethod = collByMethod.AllocatedBytes; var nodeByMethod = nodeByType.AddChild( md.ToShortStringNoReturnValue(), allocatedBytesByMethod.ToString(), PrintNumber( clockCyclesByMethod ), PrintTime( clockCyclesByMethod ), PrintPercentage( clockCyclesByMethod, clockCyclesByType ) ); nodeByMethod.Tag = md; } }; } } SwitchToViewMode( m_treeBasedGridView_Classes ); } //--// private void BuildUI_CallerCallee() { if(m_treeBasedGridView_CallerCallee == null) { m_treeBasedGridView_CallerCallee_Callers = BuildTree_FunctionGeneric( "Callers", "# of Calls to Target" ); m_treeBasedGridView_CallerCallee = BuildTree_FunctionGeneric( "Target" , "# of Calls to Target" ); m_treeBasedGridView_CallerCallee_Callees = BuildTree_FunctionGeneric( "Callees", "# of Calls from Target" ); m_treeBasedGridView_CallerCallee_Top = new SplitContainer { Orientation = Orientation.Horizontal, Dock = DockStyle.Fill, Size = new System.Drawing.Size( 668, 440 ), SplitterDistance = 220, FixedPanel = FixedPanel.Panel1, }; m_treeBasedGridView_CallerCallee_Bottom = new SplitContainer { Orientation = Orientation.Horizontal, Dock = DockStyle.Fill, Size = new System.Drawing.Size( 668, 220 ), SplitterDistance = 70, FixedPanel = FixedPanel.Panel1, }; m_treeBasedGridView_CallerCallee_Top .Panel1.Controls.Add( m_treeBasedGridView_CallerCallee_Callers ); m_treeBasedGridView_CallerCallee_Top .Panel2.Controls.Add( m_treeBasedGridView_CallerCallee_Bottom ); m_treeBasedGridView_CallerCallee_Bottom.Panel1.Controls.Add( m_treeBasedGridView_CallerCallee ); m_treeBasedGridView_CallerCallee_Bottom.Panel2.Controls.Add( m_treeBasedGridView_CallerCallee_Callees ); TreeBasedGridView.NodeMouseEventHandler callback = delegate( object sender , TreeBasedGridView.NodeMouseEventArgs e ) { var md2 = GetSelectedMethod( e ); if(md2 != null) { m_selectedMethod = md2; BuildUI_CallerCallee(); } }; m_treeBasedGridView_CallerCallee_Callers.NodeMouseDoubleClick += callback; m_treeBasedGridView_CallerCallee .NodeMouseDoubleClick += treeBasedGridView_NodeMouseDoubleClick; m_treeBasedGridView_CallerCallee_Callees.NodeMouseDoubleClick += callback; } var md = m_selectedMethod; if(md != null && m_treeBasedGridView_CallerCallee_Method != md) { m_treeBasedGridView_CallerCallee_Method = md; long totalCycles = ComputeTotalInclusiveCycles(); { var root = m_treeBasedGridView_CallerCallee_Callers.RootNode; root.Clear(); var coll = CacheGetCallers(); Profiler.CallsByMethod calls; if(coll.TryGetValue( md, out calls )) { var array = calls.ToArray(); Array.Sort( array, (x, y) => { return y.Value.ComputeExactInclusiveClockCycles().CompareTo( x.Value.ComputeExactInclusiveClockCycles() ); } ); foreach(var pair in array) { var md2 = pair.Key; var collByMethod = pair.Value; var callsByMethod = collByMethod.Count; var clockCyclesByMethod = collByMethod.ComputeExactInclusiveClockCycles(); var allocatedBytesByMethod = collByMethod.ComputeExactAllocatedBytes (); var nodeByMethod = root.AddChild( md2.ToShortStringNoReturnValue(), allocatedBytesByMethod.ToString(), callsByMethod.ToString(), PrintNumber ( clockCyclesByMethod ), PrintFraction( clockCyclesByMethod, callsByMethod ), PrintTime ( clockCyclesByMethod ), PrintTime ( clockCyclesByMethod, callsByMethod ), PrintPercentage( clockCyclesByMethod, totalCycles ) ); nodeByMethod.Tag = md2; } } } { var root = m_treeBasedGridView_CallerCallee.RootNode; root.Clear(); long callsByMethod; long clockCyclesByMethod; long allocatedBytesByMethod; { var coll = CacheGetCallers(); Profiler.CallsByMethod calls; if(coll.TryGetValue( md, out calls )) { callsByMethod = calls.TotalCalls; } else { callsByMethod = 1; } } { var coll = CacheGetCallsByMethodAndType(); Profiler.CallsByType calls; if(coll.TryGetValue( md, out calls )) { clockCyclesByMethod = calls.InclusiveClockCycles; allocatedBytesByMethod = calls.AllocatedBytes; } else { clockCyclesByMethod = 0; allocatedBytesByMethod = 0; } } var nodeByMethod = root.AddChild( md.ToShortStringNoReturnValue(), allocatedBytesByMethod.ToString(), callsByMethod.ToString(), PrintNumber ( clockCyclesByMethod ), PrintFraction( clockCyclesByMethod, callsByMethod ), PrintTime ( clockCyclesByMethod ), PrintTime ( clockCyclesByMethod, callsByMethod ), PrintPercentage( clockCyclesByMethod, totalCycles ) ); nodeByMethod.Tag = md; } { var root = m_treeBasedGridView_CallerCallee_Callees.RootNode; root.Clear(); var coll = CacheGetCallees(); Profiler.CallsByMethod calls; if(coll.TryGetValue( md, out calls )) { var array = calls.ToArray(); Array.Sort( array, (x, y) => { return y.Value.InclusiveClockCycles.CompareTo( x.Value.InclusiveClockCycles ); } ); foreach(var pair in array) { var md2 = pair.Key; var collByMethod = pair.Value; var callsByMethod = collByMethod.Count; var clockCyclesByMethod = collByMethod.ComputeExactInclusiveClockCycles(); var allocatedBytesByMethod = collByMethod.ComputeExactAllocatedBytes (); var nodeByMethod = root.AddChild( md2.ToShortStringNoReturnValue(), allocatedBytesByMethod.ToString(), callsByMethod.ToString(), PrintNumber ( clockCyclesByMethod ), PrintFraction( clockCyclesByMethod, callsByMethod ), PrintTime ( clockCyclesByMethod ), PrintTime ( clockCyclesByMethod, callsByMethod ), PrintPercentage( clockCyclesByMethod, totalCycles ) ); nodeByMethod.Tag = md2; } } } } SwitchToViewMode( m_treeBasedGridView_CallerCallee_Top ); } //--// private void BuildUI_Allocations() { if(m_treeBasedGridView_Allocations == null) { var tree = BuildTree(); m_treeBasedGridView_Allocations = tree; tree.NodeMouseDoubleClick += treeBasedGridView_NodeMouseDoubleClick; tree.SetColumns( new TreeBasedGridView.GridColumnDefinition( "Type" , DataGridViewContentAlignment.MiddleLeft , false, false, false ), new TreeBasedGridView.GridColumnDefinition( "Allocated Bytes" , DataGridViewContentAlignment.MiddleRight, false, false, false ), new TreeBasedGridView.GridColumnDefinition( "Allocated Bytes %" , DataGridViewContentAlignment.MiddleRight, false, false, false ), new TreeBasedGridView.GridColumnDefinition( "Allocated Instances" , DataGridViewContentAlignment.MiddleRight, false, false, false ), new TreeBasedGridView.GridColumnDefinition( "Allocated Instances %", DataGridViewContentAlignment.MiddleRight, false, false, false ) ); } if(m_verAllocations != m_verProfiler) { m_verAllocations = m_verProfiler; var coll = m_profiler.GetAllocationsByTypeAndMethod(); var root = m_treeBasedGridView_Allocations.RootNode; root.Clear(); long totalAllocatedBytes = coll.AllocatedBytes; long totalAllocatedInstances = coll.AllocatedInstances; var array = coll.ToArray(); Array.Sort( array, (x, y) => { return y.Value.AllocatedBytes.CompareTo( x.Value.AllocatedBytes ); } ); foreach(var pair in array) { var td = pair.Key; var collByType = pair.Value; var allocatedBytesByType = collByType.AllocatedBytes; var allocatedInstancesByType = collByType.AllocatedInstances; var nodeByType = root.AddChild( td.FullNameWithAbbreviation, PrintNumber( allocatedBytesByType ), PrintPercentage( allocatedBytesByType , totalAllocatedBytes ), PrintNumber( allocatedInstancesByType ), PrintPercentage( allocatedInstancesByType, totalAllocatedInstances ) ); nodeByType.ExpandCallback = delegate( TreeBasedGridView.GridNode nodeSub ) { foreach(var md in collByType.Keys) { var collByMethod = collByType[md]; var allocatedBytesByMethod = collByMethod.AllocatedBytes; var allocatedInstancesByMethod = collByMethod.AllocatedInstances; var nodeByMethod = nodeByType.AddChild( md.ToShortStringNoReturnValue(), PrintNumber( allocatedBytesByMethod ), PrintPercentage( allocatedBytesByMethod , allocatedBytesByType ), PrintNumber( allocatedInstancesByMethod ), PrintPercentage( allocatedInstancesByMethod, allocatedInstancesByType ) ); nodeByMethod.Tag = md; } }; } } SwitchToViewMode( m_treeBasedGridView_Allocations ); } //--// private string PrintTime( long cycles ) { if(m_svcTiming != null) { var time = m_svcTiming.ClockTicksToTime( cycles ); // // \u00b5 = Greek micro // return string.Format( "{0:F3}\u00B5Sec", time.TotalSeconds * 1E6 ); } else { return "n/a"; } } private string PrintTime( long cycles , long divider ) { if(m_svcTiming != null && divider != 0) { var time = m_svcTiming.ClockTicksToTime( cycles ); // // \u00b5 = Greek micro // return string.Format( "{0:F3}\u00B5Sec", time.TotalSeconds * 1E6 / divider ); } else { return "n/a"; } } private string PrintNumber( long val ) { return string.Format( "{0}", val ); } private string PrintPercentage( long val , long total ) { if(total != 0) { return string.Format( "{0:F2}%", 100.00 * val / total ); } else { return "n/a"; } } private string PrintFraction( long val , long total ) { if(total != 0) { return string.Format( "{0:F2}", (double)val / total ); } else { return "n/a"; } } //--// private static TreeBasedGridView BuildTree() { var tree = new TreeBasedGridView { BorderStyle = BorderStyle.Fixed3D, Dock = DockStyle.Fill, Location = new Point( 0, 0 ), TabIndex = 0, }; return tree; } private static TreeBasedGridView BuildTree_Call() { var tree = BuildTree(); tree.SetColumns( new TreeBasedGridView.GridColumnDefinition( "Entry" , DataGridViewContentAlignment.MiddleLeft , false, false, false ), new TreeBasedGridView.GridColumnDefinition( "Allocated Bytes" , DataGridViewContentAlignment.MiddleRight, false, false, false ), new TreeBasedGridView.GridColumnDefinition( "Inclusive Cycles", DataGridViewContentAlignment.MiddleRight, false, false, false ), new TreeBasedGridView.GridColumnDefinition( "Inclusive Time" , DataGridViewContentAlignment.MiddleRight, false, false, false ), new TreeBasedGridView.GridColumnDefinition( "Inclusive CPU%" , DataGridViewContentAlignment.MiddleRight, false, false, false ), new TreeBasedGridView.GridColumnDefinition( "Exclusive Cycles", DataGridViewContentAlignment.MiddleRight, false, false, false ), new TreeBasedGridView.GridColumnDefinition( "Exclusive Time" , DataGridViewContentAlignment.MiddleRight, false, false, false ), new TreeBasedGridView.GridColumnDefinition( "Exclusive CPU%" , DataGridViewContentAlignment.MiddleRight, false, false, false ) ); return tree; } private static TreeBasedGridView BuildTree_Function() { return BuildTree_FunctionGeneric( "Function", "# of Calls" ); } private static TreeBasedGridView BuildTree_FunctionGeneric( string function , string numberOfCalls ) { var tree = BuildTree(); tree.SetColumns( new TreeBasedGridView.GridColumnDefinition( function , DataGridViewContentAlignment.MiddleLeft , false, false, false ), new TreeBasedGridView.GridColumnDefinition( "Allocated Bytes" , DataGridViewContentAlignment.MiddleRight, false, false, false ), new TreeBasedGridView.GridColumnDefinition( numberOfCalls , DataGridViewContentAlignment.MiddleRight, false, false, false ), new TreeBasedGridView.GridColumnDefinition( "Cycles" , DataGridViewContentAlignment.MiddleRight, false, false, false ), new TreeBasedGridView.GridColumnDefinition( "Cycles/Call" , DataGridViewContentAlignment.MiddleRight, false, false, false ), new TreeBasedGridView.GridColumnDefinition( "Time" , DataGridViewContentAlignment.MiddleRight, false, false, false ), new TreeBasedGridView.GridColumnDefinition( "Time/Call" , DataGridViewContentAlignment.MiddleRight, false, false, false ), new TreeBasedGridView.GridColumnDefinition( "CPU%" , DataGridViewContentAlignment.MiddleRight, false, false, false ) ); return tree; } //--// private void ShowMethod( TS.MethodRepresentation md ) { var cfg = IR.TypeSystemForCodeTransformation.GetCodeForMethod( md ); if(cfg != null) { ImageInformation imageInformation; this.Host.GetHostingService( out imageInformation ); IR.ImageBuilders.SequentialRegion reg = imageInformation.ImageBuilder.GetAssociatedRegion( cfg ); if(reg != null) { Debugging.DebugInfo di; if(imageInformation.LocateFirstSourceCode( reg, 0, out di )) { this.Host.VisualizeDebugInfo( di ); } } } } private static TS.MethodRepresentation GetSelectedMethod( TreeBasedGridView.NodeMouseEventArgs e ) { if(e.SelectedColumn == 0) { var node = e.SelectedNode; if(node != null) { var tag = node.Tag; if(tag is Profiler.CallEntry) { Profiler.CallEntry en = (Profiler.CallEntry)tag; return en.Method; } else if(tag is TS.MethodRepresentation) { TS.MethodRepresentation md = (TS.MethodRepresentation)tag; return md; } } } return null; } // // Access Methods // public override string ViewTitle { get { return "&Profiler"; } } // // Event Methods // private void toolStripButton_New_Click( object sender , EventArgs e ) { DeallocateProfiler(); UpdateButtonState(); } private void toolStripButton_Start_Click( object sender , EventArgs e ) { AllocateProfiler(); m_profiler.CollectAllocationData = (toolStripComboBox_Mode.SelectedIndex == 1); m_profiler.Attach(); UpdateButtonState(); } private void toolStripButton_Stop_Click( object sender , EventArgs e ) { if(m_profiler != null) { m_profiler.Detach(); m_verProfiler++; m_profiler_CallsByMethodAndType = null; m_profiler_Callers = null; m_profiler_Callees = null; UpdateUI(); } UpdateButtonState(); } private void toolStripComboBox_View_SelectedIndexChanged( object sender , EventArgs e ) { if(m_profiler != null && m_profiler.IsActive == false) { UpdateUI(); } } void treeBasedGridView_NodeMouseClick( object sender , TreeBasedGridView.NodeMouseEventArgs e ) { var md = GetSelectedMethod( e ); if(md != null) { m_selectedMethod = md; } } void treeBasedGridView_NodeMouseDoubleClick( object sender , TreeBasedGridView.NodeMouseEventArgs e ) { var md = GetSelectedMethod( e ); if(md != null) { ShowMethod( md ); } } } } ================================================ FILE: Zelig/Zelig/DebugTime/Debugger/Forms/ProfilerMainForm.resx ================================================ text/microsoft-resx 2.0 System.Resources.ResXResourceReader, System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 System.Resources.ResXResourceWriter, System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 470, 17 ================================================ FILE: Zelig/Zelig/DebugTime/Debugger/Forms/SessionManager.Designer.cs ================================================ namespace Microsoft.Zelig.Debugger.ArmProcessor { partial class SessionManagerForm { /// /// Required designer variable. /// private System.ComponentModel.IContainer components = null; /// /// Clean up any resources being used. /// /// true if managed resources should be disposed; otherwise, false. protected override void Dispose( bool disposing ) { if(disposing && (components != null)) { components.Dispose(); } base.Dispose( disposing ); } #region Windows Form Designer generated code /// /// Required method for Designer support - do not modify /// the contents of this method with the code editor. /// private void InitializeComponent() { this.listView1 = new System.Windows.Forms.ListView(); this.columnHeaderName = new System.Windows.Forms.ColumnHeader(); this.columnHeaderDate = new System.Windows.Forms.ColumnHeader(); this.columnHeaderEngine = new System.Windows.Forms.ColumnHeader(); this.columnHeaderProduct = new System.Windows.Forms.ColumnHeader(); this.columnHeaderImage = new System.Windows.Forms.ColumnHeader(); this.buttonSelect = new System.Windows.Forms.Button(); this.buttonRemove = new System.Windows.Forms.Button(); this.buttonCancel = new System.Windows.Forms.Button(); this.buttonNew = new System.Windows.Forms.Button(); this.buttonSave = new System.Windows.Forms.Button(); this.buttonBrowse = new System.Windows.Forms.Button(); this.buttonClone = new System.Windows.Forms.Button(); this.buttonRename = new System.Windows.Forms.Button(); this.buttonExport = new System.Windows.Forms.Button(); this.SuspendLayout(); // // listView1 // this.listView1.Anchor = ((System.Windows.Forms.AnchorStyles)((((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Bottom) | System.Windows.Forms.AnchorStyles.Left) | System.Windows.Forms.AnchorStyles.Right))); this.listView1.Columns.AddRange( new System.Windows.Forms.ColumnHeader[] { this.columnHeaderName, this.columnHeaderEngine, this.columnHeaderProduct, this.columnHeaderDate, this.columnHeaderImage} ); this.listView1.FullRowSelect = true; this.listView1.GridLines = true; this.listView1.HideSelection = false; this.listView1.Location = new System.Drawing.Point( 12, 12 ); this.listView1.MultiSelect = false; this.listView1.Name = "listView1"; this.listView1.Size = new System.Drawing.Size( 855, 235 ); this.listView1.Sorting = System.Windows.Forms.SortOrder.Ascending; this.listView1.TabIndex = 0; this.listView1.UseCompatibleStateImageBehavior = false; this.listView1.View = System.Windows.Forms.View.Details; this.listView1.DoubleClick += new System.EventHandler( this.listView1_DoubleClick ); this.listView1.ItemSelectionChanged += new System.Windows.Forms.ListViewItemSelectionChangedEventHandler( this.listView1_ItemSelectionChanged ); // // columnHeaderName // this.columnHeaderName.Text = "Name"; this.columnHeaderName.Width = 140; // // columnHeaderDate // this.columnHeaderDate.Text = "Last Modified"; this.columnHeaderDate.Width = 135; // // columnHeaderEngine // this.columnHeaderEngine.Text = "Engine"; this.columnHeaderEngine.Width = 103; // // columnHeaderProduct // this.columnHeaderProduct.Text = "Product"; this.columnHeaderProduct.Width = 158; // // columnHeaderImage // this.columnHeaderImage.Text = "Image"; this.columnHeaderImage.Width = 303; // // buttonSelect // this.buttonSelect.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Left))); this.buttonSelect.Location = new System.Drawing.Point( 12, 260 ); this.buttonSelect.Name = "buttonSelect"; this.buttonSelect.Size = new System.Drawing.Size( 75, 23 ); this.buttonSelect.TabIndex = 1; this.buttonSelect.Text = "Select"; this.buttonSelect.UseVisualStyleBackColor = true; this.buttonSelect.Click += new System.EventHandler( this.buttonSelect_Click ); // // buttonRemove // this.buttonRemove.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Left))); this.buttonRemove.Location = new System.Drawing.Point( 353, 260 ); this.buttonRemove.Name = "buttonRemove"; this.buttonRemove.Size = new System.Drawing.Size( 75, 23 ); this.buttonRemove.TabIndex = 2; this.buttonRemove.Text = "Remove"; this.buttonRemove.UseVisualStyleBackColor = true; this.buttonRemove.Click += new System.EventHandler( this.buttonRemove_Click ); // // buttonCancel // this.buttonCancel.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Right))); this.buttonCancel.DialogResult = System.Windows.Forms.DialogResult.Cancel; this.buttonCancel.Location = new System.Drawing.Point( 792, 260 ); this.buttonCancel.Name = "buttonCancel"; this.buttonCancel.Size = new System.Drawing.Size( 75, 23 ); this.buttonCancel.TabIndex = 3; this.buttonCancel.Text = "Cancel"; this.buttonCancel.UseVisualStyleBackColor = true; this.buttonCancel.Click += new System.EventHandler( this.buttonCancel_Click ); // // buttonNew // this.buttonNew.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Left))); this.buttonNew.Location = new System.Drawing.Point( 110, 260 ); this.buttonNew.Name = "buttonNew"; this.buttonNew.Size = new System.Drawing.Size( 75, 23 ); this.buttonNew.TabIndex = 4; this.buttonNew.Text = "New"; this.buttonNew.UseVisualStyleBackColor = true; this.buttonNew.Click += new System.EventHandler( this.buttonNew_Click ); // // buttonSave // this.buttonSave.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Left))); this.buttonSave.Location = new System.Drawing.Point( 434, 260 ); this.buttonSave.Name = "buttonSave"; this.buttonSave.Size = new System.Drawing.Size( 75, 23 ); this.buttonSave.TabIndex = 5; this.buttonSave.Text = "Save"; this.buttonSave.UseVisualStyleBackColor = true; this.buttonSave.Click += new System.EventHandler( this.buttonSave_Click ); // // buttonBrowse // this.buttonBrowse.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Right))); this.buttonBrowse.DialogResult = System.Windows.Forms.DialogResult.Cancel; this.buttonBrowse.Location = new System.Drawing.Point( 688, 260 ); this.buttonBrowse.Name = "buttonBrowse"; this.buttonBrowse.Size = new System.Drawing.Size( 75, 23 ); this.buttonBrowse.TabIndex = 6; this.buttonBrowse.Text = "Browse..."; this.buttonBrowse.UseVisualStyleBackColor = true; this.buttonBrowse.Click += new System.EventHandler( this.buttonBrowse_Click ); // // buttonClone // this.buttonClone.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Left))); this.buttonClone.Location = new System.Drawing.Point( 272, 260 ); this.buttonClone.Name = "buttonClone"; this.buttonClone.Size = new System.Drawing.Size( 75, 23 ); this.buttonClone.TabIndex = 7; this.buttonClone.Text = "Clone"; this.buttonClone.UseVisualStyleBackColor = true; this.buttonClone.Click += new System.EventHandler( this.buttonClone_Click ); // // buttonRename // this.buttonRename.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Left))); this.buttonRename.Location = new System.Drawing.Point( 191, 260 ); this.buttonRename.Name = "buttonRename"; this.buttonRename.Size = new System.Drawing.Size( 75, 23 ); this.buttonRename.TabIndex = 8; this.buttonRename.Text = "Rename"; this.buttonRename.UseVisualStyleBackColor = true; this.buttonRename.Click += new System.EventHandler( this.buttonRename_Click ); // // buttonExport // this.buttonExport.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Left))); this.buttonExport.Location = new System.Drawing.Point( 515, 260 ); this.buttonExport.Name = "buttonExport"; this.buttonExport.Size = new System.Drawing.Size( 75, 23 ); this.buttonExport.TabIndex = 9; this.buttonExport.Text = "Export..."; this.buttonExport.UseVisualStyleBackColor = true; this.buttonExport.Click += new System.EventHandler( this.buttonExport_Click ); // // SessionManagerForm // this.AcceptButton = this.buttonSelect; this.AutoScaleDimensions = new System.Drawing.SizeF( 6F, 13F ); this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font; this.CancelButton = this.buttonCancel; this.ClientSize = new System.Drawing.Size( 879, 295 ); this.ControlBox = false; this.Controls.Add( this.buttonExport ); this.Controls.Add( this.buttonRename ); this.Controls.Add( this.buttonClone ); this.Controls.Add( this.buttonBrowse ); this.Controls.Add( this.buttonSave ); this.Controls.Add( this.buttonNew ); this.Controls.Add( this.buttonSelect ); this.Controls.Add( this.buttonCancel ); this.Controls.Add( this.listView1 ); this.Controls.Add( this.buttonRemove ); this.Name = "SessionManagerForm"; this.ShowIcon = false; this.ShowInTaskbar = false; this.Text = "Session Manager"; this.Load += new System.EventHandler( this.SessionManagerForm_Load ); this.ResumeLayout( false ); } #endregion private System.Windows.Forms.ListView listView1; private System.Windows.Forms.ColumnHeader columnHeaderName; private System.Windows.Forms.ColumnHeader columnHeaderDate; private System.Windows.Forms.ColumnHeader columnHeaderImage; private System.Windows.Forms.ColumnHeader columnHeaderEngine; private System.Windows.Forms.ColumnHeader columnHeaderProduct; private System.Windows.Forms.Button buttonSelect; private System.Windows.Forms.Button buttonRemove; private System.Windows.Forms.Button buttonCancel; private System.Windows.Forms.Button buttonNew; private System.Windows.Forms.Button buttonSave; private System.Windows.Forms.Button buttonBrowse; private System.Windows.Forms.Button buttonClone; private System.Windows.Forms.Button buttonRename; private System.Windows.Forms.Button buttonExport; } } ================================================ FILE: Zelig/Zelig/DebugTime/Debugger/Forms/SessionManager.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // namespace Microsoft.Zelig.Debugger.ArmProcessor { using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Text; using System.IO; using System.Windows.Forms; using System.Threading; using IR = Microsoft.Zelig.CodeGeneration.IR; using RT = Microsoft.Zelig.Runtime; using TS = Microsoft.Zelig.Runtime.TypeSystem; using Cfg = Microsoft.Zelig.Configuration.Environment; public partial class SessionManagerForm : Form { const string c_registry_RootKey = "SessionManager"; const string c_registry_LastSession = "LastSession"; const string c_file_Sessions = "Sessions"; const string c_file_Extension = "zeligsession"; const string c_file_SearchPattern = "*." + c_file_Extension; // // State // DebuggerMainForm m_owner; List< Session > m_sessions; Session m_defaultSession; Session m_selectedSession; // // Constructor Methods // public SessionManagerForm( DebuggerMainForm owner ) { m_owner = owner; InitializeComponent(); //--// m_sessions = new List< Session >(); LoadSessions(); } // // Helper Methods // private DirectoryInfo GetDataPath() { return new DirectoryInfo( Path.Combine( Application.UserAppDataPath, c_file_Sessions ) ); } public void SaveSessions() { Win32.RegistryKey rootKey = Application.UserAppDataRegistry; Win32.RegistryKey nodeKey = rootKey.CreateSubKey( c_registry_RootKey ); if(nodeKey != null) { if(m_defaultSession != null && m_defaultSession.IsTemporary == false) { nodeKey.SetValue( c_registry_LastSession, m_defaultSession.Id.ToString(), Microsoft.Win32.RegistryValueKind.String ); } nodeKey.Close(); } var di = GetDataPath(); if(!di.Exists) { di.Create(); } foreach(Session session in m_sessions) { if(session.IsTemporary == false) { if(session.Dirty) { if(session.SettingsFile != null) { if(MessageBox.Show( string.Format( "Save session '{0}'?", session.SettingsFile ), "Workplace", MessageBoxButtons.YesNo ) == DialogResult.Yes) { try { session.Save( session.SettingsFile, false ); } catch { } } } else { try { string file = Path.Combine( di.FullName, string.Format( "{0}.{1}", session.Id, c_file_Extension ) ); session.Save( file, false ); } catch { } } } } } } private void LoadSessions() { string defaultSessionId = null; Win32.RegistryKey rootKey = Application.UserAppDataRegistry; Win32.RegistryKey nodeKey = rootKey.OpenSubKey( c_registry_RootKey ); if(nodeKey != null) { defaultSessionId = nodeKey.GetValue( c_registry_LastSession, null, Microsoft.Win32.RegistryValueOptions.DoNotExpandEnvironmentNames ) as string; nodeKey.Close(); } var di = GetDataPath(); if(di.Exists) { foreach(var fi in di.GetFiles( c_file_SearchPattern )) { try { AddSession( Session.Load( fi.FullName ), defaultSessionId ); } catch { } } } } public Session LoadSession( string file ) { Session session = Session.LoadAndSetOrigin( file ); InsertUniqueSession( session ); return session; } public void SelectSession( Session session ) { m_selectedSession = session; UpdateList(); } public Session SelectSession( bool fSetDefault ) { if(m_sessions.Count > 0) { if(fSetDefault) { SelectSession( m_defaultSession ); } if(this.ShowDialog() != DialogResult.OK) { return null; } } else { Session session = new Session(); InputForm form = new InputForm( "Enter Name For New Session", session.DisplayName ); if(form.ShowDialog() == DialogResult.OK) { session.DisplayName = form.Result; if(m_owner.Action_EditConfiguration( session ) == DialogResult.OK) { InsertUniqueSession( session ); SelectSession( session ); } } } m_defaultSession = m_selectedSession; return m_defaultSession; } public Session FindSession( string name ) { foreach(Session session in m_sessions) { if(session.DisplayName == name) { return session; } } return null; } public Session LoadSession( string file , bool fTemporary ) { Session session = Session.LoadAndSetOrigin( file ); session.IsTemporary = fTemporary; InsertUniqueSession( session ); return session; } //--// private void AddSession( Session session , string defaultSessionId ) { InsertUniqueSession( session ); if(session.Id.ToString() == defaultSessionId) { m_defaultSession = session; } } private void InsertUniqueSession( Session newSession ) { for(int i = 0; i < m_sessions.Count; i++) { Session session = m_sessions[i]; if(session.Id == newSession.Id) { m_sessions[i] = newSession; return; } } m_sessions.Add( newSession ); } private void UpdateList() { ListView.ListViewItemCollection items = listView1.Items; ListViewItem itemToSelect = null; items.Clear(); foreach(Session session in m_sessions) { string name = session.DisplayName; if(string.IsNullOrEmpty( name )) { name = ""; } var item = new ListViewItem( name ); item.Tag = session; item.SubItems.Add( session.SelectedEngine .ToString() ); item.SubItems.Add( session.SelectedProduct.ToString() ); item.SubItems.Add( session.LastModified .ToString() ); item.SubItems.Add( session.ImageToLoad ); items.Add( item ); if(m_selectedSession == session) { itemToSelect = item; } } if(itemToSelect != null) { itemToSelect.Selected = true; listView1.Focus(); } UpdateButtons(); } private void UpdateButtons() { bool fEnable = (m_selectedSession != null); buttonSelect.Enabled = fEnable; buttonClone .Enabled = fEnable; buttonRemove.Enabled = fEnable; buttonSave .Enabled = fEnable; } // // Access Methods // // // Event Methods // private void SessionManagerForm_Load( object sender , EventArgs e ) { UpdateList(); } private void buttonSelect_Click( object sender , EventArgs e ) { this.DialogResult = DialogResult.OK; this.Close(); } private void buttonNew_Click( object sender , EventArgs e ) { Session session = new Session(); InputForm form = new InputForm( "Enter Name For Session", session.DisplayName ); if(form.ShowDialog() == DialogResult.OK) { session.DisplayName = form.Result; if(m_owner.Action_EditConfiguration( session ) == DialogResult.OK) { InsertUniqueSession( session ); SelectSession( session ); } } } private void buttonRename_Click( object sender , EventArgs e ) { InputForm form = new InputForm( "Enter Name For Session", m_selectedSession.DisplayName ); if(form.ShowDialog() == DialogResult.OK) { m_selectedSession.DisplayName = form.Result; UpdateList(); } } private void buttonClone_Click( object sender , EventArgs e ) { Session session = new Session( m_selectedSession ); InsertUniqueSession( session ); SelectSession( session ); } private void buttonRemove_Click( object sender , EventArgs e ) { var session = m_selectedSession; if(session != null) { if(session.SettingsFile != null) { if(MessageBox.Show( string.Format( "Delete session file '{0}'?", session.SettingsFile ), "Workplace", MessageBoxButtons.YesNo ) == DialogResult.Yes) { try { File.Delete( session.SettingsFile ); } catch { } } } try { var di = GetDataPath(); if(di.Exists) { string file = Path.Combine( di.FullName, string.Format( "{0}.{1}", session.Id, c_file_Extension ) ); File.Delete( file ); } } catch { } //--// m_sessions.Remove( session ); m_selectedSession = null; } UpdateList(); } private void buttonSave_Click( object sender , EventArgs e ) { if(m_selectedSession.Dirty) { string file = m_owner.Action_SelectSessionToSave( m_selectedSession.SettingsFile ); if(file != null) { m_selectedSession.Save( file, false ); UpdateList(); } } } private void buttonExport_Click( object sender, EventArgs e ) { if(m_selectedSession != null) { string file = m_owner.Action_SelectSessionToSave( null ); if(file != null) { m_selectedSession.Save( file, false ); UpdateList(); } } } private void buttonBrowse_Click( object sender , EventArgs e ) { string file = m_owner.Action_SelectSessionToLoad( null ); if(file != null) { SelectSession( LoadSession( file ) ); } } private void buttonCancel_Click( object sender , EventArgs e ) { this.DialogResult = DialogResult.Cancel; this.Close(); } //--// private void listView1_ItemSelectionChanged( object sender , ListViewItemSelectionChangedEventArgs e ) { if(e.IsSelected) { m_selectedSession = (Session)e.Item.Tag; } else { m_selectedSession = null; } UpdateButtons(); } private void listView1_DoubleClick( object sender , EventArgs e ) { if(m_selectedSession != null) { this.DialogResult = DialogResult.OK; this.Close(); } } } } ================================================ FILE: Zelig/Zelig/DebugTime/Debugger/Forms/SessionManager.resx ================================================ text/microsoft-resx 2.0 System.Resources.ResXResourceReader, System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 System.Resources.ResXResourceWriter, System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 ================================================ FILE: Zelig/Zelig/DebugTime/Debugger/Program.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // namespace Microsoft.Zelig.Debugger.ArmProcessor { using System; using System.Collections.Generic; using System.Windows.Forms; static class Program { /// /// The main entry point for the application. /// [STAThread] static void Main( string[] args ) { Application.EnableVisualStyles(); Application.SetCompatibleTextRenderingDefault( false ); Application.Run( new DebuggerMainForm( args ) ); } } } ================================================ FILE: Zelig/Zelig/DebugTime/Debugger/Properties/AssemblyInfo.cs ================================================ using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; // General Information about an assembly is controlled through the following // set of attributes. Change these attribute values to modify the information // associated with an assembly. [assembly: AssemblyTitle( "Microsoft.Zelig.Debugger.ArmProcessor" )] [assembly: AssemblyDescription( "" )] [assembly: AssemblyConfiguration( "" )] [assembly: AssemblyCompany( "Microsoft" )] [assembly: AssemblyProduct( "Microsoft.Zelig.Debugger.ArmProcessor" )] [assembly: AssemblyCopyright( "Copyright © Microsoft 2007" )] [assembly: AssemblyTrademark( "" )] [assembly: AssemblyCulture( "" )] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible( false )] // The following GUID is for the ID of the typelib if this project is exposed to COM [assembly: Guid( "f4a6296e-dae3-4e99-a48d-2f911333e11f" )] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // [assembly: AssemblyVersion( "1.0.0.0" )] [assembly: AssemblyFileVersion( "1.0.0.0" )] ================================================ FILE: Zelig/Zelig/DebugTime/Debugger/Properties/Resources.Designer.cs ================================================ //------------------------------------------------------------------------------ // // This code was generated by a tool. // Runtime Version:4.0.30319.34209 // // Changes to this file may cause incorrect behavior and will be lost if // the code is regenerated. // //------------------------------------------------------------------------------ namespace Microsoft.Zelig.Debugger.ArmProcessor.Properties { using System; /// /// A strongly-typed resource class, for looking up localized strings, etc. /// // This class was auto-generated by the StronglyTypedResourceBuilder // class via a tool like ResGen or Visual Studio. // To add or remove a member, edit your .ResX file then rerun ResGen // with the /str option, or rebuild your VS project. [global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Resources.Tools.StronglyTypedResourceBuilder", "4.0.0.0")] [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] [global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()] internal class Resources { private static global::System.Resources.ResourceManager resourceMan; private static global::System.Globalization.CultureInfo resourceCulture; [global::System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")] internal Resources() { } /// /// Returns the cached ResourceManager instance used by this class. /// [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)] internal static global::System.Resources.ResourceManager ResourceManager { get { if (object.ReferenceEquals(resourceMan, null)) { global::System.Resources.ResourceManager temp = new global::System.Resources.ResourceManager("Microsoft.Zelig.Debugger.ArmProcessor.Properties.Resources", typeof(Resources).Assembly); resourceMan = temp; } return resourceMan; } } /// /// Overrides the current thread's CurrentUICulture property for all /// resource lookups using this strongly typed resource class. /// [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)] internal static global::System.Globalization.CultureInfo Culture { get { return resourceCulture; } set { resourceCulture = value; } } /// /// Looks up a localized resource of type System.Drawing.Bitmap. /// internal static System.Drawing.Bitmap BreakAll { get { object obj = ResourceManager.GetObject("BreakAll", resourceCulture); return ((System.Drawing.Bitmap)(obj)); } } /// /// Looks up a localized resource of type System.Drawing.Icon similar to (Icon). /// internal static System.Drawing.Icon Breakpoint { get { object obj = ResourceManager.GetObject("Breakpoint", resourceCulture); return ((System.Drawing.Icon)(obj)); } } /// /// Looks up a localized resource of type System.Drawing.Icon similar to (Icon). /// internal static System.Drawing.Icon BreakpointDisabled { get { object obj = ResourceManager.GetObject("BreakpointDisabled", resourceCulture); return ((System.Drawing.Icon)(obj)); } } /// /// Looks up a localized resource of type System.Drawing.Icon similar to (Icon). /// internal static System.Drawing.Icon CurrentStatement { get { object obj = ResourceManager.GetObject("CurrentStatement", resourceCulture); return ((System.Drawing.Icon)(obj)); } } /// /// Looks up a localized resource of type System.Drawing.Icon similar to (Icon). /// internal static System.Drawing.Icon Delete { get { object obj = ResourceManager.GetObject("Delete", resourceCulture); return ((System.Drawing.Icon)(obj)); } } /// /// Looks up a localized resource of type System.Drawing.Icon similar to (Icon). /// internal static System.Drawing.Icon DeleteAllBreakpoints { get { object obj = ResourceManager.GetObject("DeleteAllBreakpoints", resourceCulture); return ((System.Drawing.Icon)(obj)); } } /// /// Looks up a localized resource of type System.Drawing.Icon similar to (Icon). /// internal static System.Drawing.Icon EmptyIcon { get { object obj = ResourceManager.GetObject("EmptyIcon", resourceCulture); return ((System.Drawing.Icon)(obj)); } } /// /// Looks up a localized resource of type System.Drawing.Icon similar to (Icon). /// internal static System.Drawing.Icon LocalVariable { get { object obj = ResourceManager.GetObject("LocalVariable", resourceCulture); return ((System.Drawing.Icon)(obj)); } } /// /// Looks up a localized resource of type System.Drawing.Bitmap. /// internal static System.Drawing.Bitmap NewSession { get { object obj = ResourceManager.GetObject("NewSession", resourceCulture); return ((System.Drawing.Bitmap)(obj)); } } /// /// Looks up a localized resource of type System.Drawing.Icon similar to (Icon). /// internal static System.Drawing.Icon NodeCollapsed { get { object obj = ResourceManager.GetObject("NodeCollapsed", resourceCulture); return ((System.Drawing.Icon)(obj)); } } /// /// Looks up a localized resource of type System.Drawing.Icon similar to (Icon). /// internal static System.Drawing.Icon NodeExpanded { get { object obj = ResourceManager.GetObject("NodeExpanded", resourceCulture); return ((System.Drawing.Icon)(obj)); } } /// /// Looks up a localized resource of type System.Drawing.Bitmap. /// internal static System.Drawing.Bitmap Open { get { object obj = ResourceManager.GetObject("Open", resourceCulture); return ((System.Drawing.Bitmap)(obj)); } } /// /// Looks up a localized resource of type System.Drawing.Icon similar to (Icon). /// internal static System.Drawing.Icon PrivateMember { get { object obj = ResourceManager.GetObject("PrivateMember", resourceCulture); return ((System.Drawing.Icon)(obj)); } } /// /// Looks up a localized resource of type System.Drawing.Icon similar to (Icon). /// internal static System.Drawing.Icon Property { get { object obj = ResourceManager.GetObject("Property", resourceCulture); return ((System.Drawing.Icon)(obj)); } } /// /// Looks up a localized resource of type System.Drawing.Icon similar to (Icon). /// internal static System.Drawing.Icon PublicMember { get { object obj = ResourceManager.GetObject("PublicMember", resourceCulture); return ((System.Drawing.Icon)(obj)); } } /// /// Looks up a localized resource of type System.Drawing.Bitmap. /// internal static System.Drawing.Bitmap Restart { get { object obj = ResourceManager.GetObject("Restart", resourceCulture); return ((System.Drawing.Bitmap)(obj)); } } /// /// Looks up a localized resource of type System.Drawing.Bitmap. /// internal static System.Drawing.Bitmap ShowNextStatement { get { object obj = ResourceManager.GetObject("ShowNextStatement", resourceCulture); return ((System.Drawing.Bitmap)(obj)); } } /// /// Looks up a localized resource of type System.Drawing.Icon similar to (Icon). /// internal static System.Drawing.Icon StackFrame { get { object obj = ResourceManager.GetObject("StackFrame", resourceCulture); return ((System.Drawing.Icon)(obj)); } } /// /// Looks up a localized resource of type System.Drawing.Bitmap. /// internal static System.Drawing.Bitmap Start { get { object obj = ResourceManager.GetObject("Start", resourceCulture); return ((System.Drawing.Bitmap)(obj)); } } /// /// Looks up a localized resource of type System.Drawing.Bitmap. /// internal static System.Drawing.Bitmap StartSession { get { object obj = ResourceManager.GetObject("StartSession", resourceCulture); return ((System.Drawing.Bitmap)(obj)); } } /// /// Looks up a localized resource of type System.Drawing.Icon similar to (Icon). /// internal static System.Drawing.Icon StaticMembers { get { object obj = ResourceManager.GetObject("StaticMembers", resourceCulture); return ((System.Drawing.Icon)(obj)); } } /// /// Looks up a localized resource of type System.Drawing.Bitmap. /// internal static System.Drawing.Bitmap StepInto { get { object obj = ResourceManager.GetObject("StepInto", resourceCulture); return ((System.Drawing.Bitmap)(obj)); } } /// /// Looks up a localized resource of type System.Drawing.Bitmap. /// internal static System.Drawing.Bitmap StepOut { get { object obj = ResourceManager.GetObject("StepOut", resourceCulture); return ((System.Drawing.Bitmap)(obj)); } } /// /// Looks up a localized resource of type System.Drawing.Bitmap. /// internal static System.Drawing.Bitmap StepOver { get { object obj = ResourceManager.GetObject("StepOver", resourceCulture); return ((System.Drawing.Bitmap)(obj)); } } /// /// Looks up a localized resource of type System.Drawing.Bitmap. /// internal static System.Drawing.Bitmap StopDebugging { get { object obj = ResourceManager.GetObject("StopDebugging", resourceCulture); return ((System.Drawing.Bitmap)(obj)); } } /// /// Looks up a localized resource of type System.Drawing.Bitmap. /// internal static System.Drawing.Bitmap StopSession { get { object obj = ResourceManager.GetObject("StopSession", resourceCulture); return ((System.Drawing.Bitmap)(obj)); } } /// /// Looks up a localized resource of type System.Drawing.Icon similar to (Icon). /// internal static System.Drawing.Icon ToggleAllBreakpoints { get { object obj = ResourceManager.GetObject("ToggleAllBreakpoints", resourceCulture); return ((System.Drawing.Icon)(obj)); } } /// /// Looks up a localized resource of type System.Drawing.Bitmap. /// internal static System.Drawing.Bitmap ToggleDisassembly { get { object obj = ResourceManager.GetObject("ToggleDisassembly", resourceCulture); return ((System.Drawing.Bitmap)(obj)); } } } } ================================================ FILE: Zelig/Zelig/DebugTime/Debugger/Properties/Resources.resx ================================================  text/microsoft-resx 2.0 System.Resources.ResXResourceReader, System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 System.Resources.ResXResourceWriter, System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 iVBORw0KGgoAAAANSUhEUgAAABAAAAAQCAYAAAAf8/9hAAAAAXNSR0IArs4c6QAAAARnQU1BAACxjwv8 YQUAAAAgY0hSTQAAeiYAAICEAAD6AAAAgOgAAHUwAADqYAAAOpgAABdwnLpRPAAAAG9JREFUOE9jYBgF GCEw88z//yCcBiRAkuh8gkEG0nDmzf//xmkIA5D5RBnw8eNHoAEz4S5A5hM2YCbUBcZQA9D4RBvAgGYA jE+cAcBwQDEAiU/QAFDoLzv1AW4AOp8+BoCdDw0DcHpA4hN0wdBTAACiYpnDMV3rqAAAAABJRU5ErkJg gg== AAABAAEAEBAAAAAACABoBQAAFgAAACgAAAAQAAAAIAAAAAEACAAAAAAAAAEAAAAAAAAAAAAAAAEAAAAB AAAAAAAAAACAAACAAAAAgIAAgAAAAIAAgACAgAAAwMDAAMDcwADwyqYABAQEAAgICAAMDAwAERERABYW FgAcHBwAIiIiACkpKQBVVVUATU1NAEJCQgA5OTkAgHz/AFBQ/wCTANYA/+zMAMbW7wDW5+cAkKmtAAAA MwAAAGYAAACZAAAAzAAAMwAAADMzAAAzZgAAM5kAADPMAAAz/wAAZgAAAGYzAABmZgAAZpkAAGbMAABm /wAAmQAAAJkzAACZZgAAmZkAAJnMAACZ/wAAzAAAAMwzAADMZgAAzJkAAMzMAADM/wAA/2YAAP+ZAAD/ zAAzAAAAMwAzADMAZgAzAJkAMwDMADMA/wAzMwAAMzMzADMzZgAzM5kAMzPMADMz/wAzZgAAM2YzADNm ZgAzZpkAM2bMADNm/wAzmQAAM5kzADOZZgAzmZkAM5nMADOZ/wAzzAAAM8wzADPMZgAzzJkAM8zMADPM /wAz/zMAM/9mADP/mQAz/8wAM///AGYAAABmADMAZgBmAGYAmQBmAMwAZgD/AGYzAABmMzMAZjNmAGYz mQBmM8wAZjP/AGZmAABmZjMAZmZmAGZmmQBmZswAZpkAAGaZMwBmmWYAZpmZAGaZzABmmf8AZswAAGbM MwBmzJkAZszMAGbM/wBm/wAAZv8zAGb/mQBm/8wAzAD/AP8AzACZmQAAmTOZAJkAmQCZAMwAmQAAAJkz MwCZAGYAmTPMAJkA/wCZZgAAmWYzAJkzZgCZZpkAmWbMAJkz/wCZmTMAmZlmAJmZmQCZmcwAmZn/AJnM AACZzDMAZsxmAJnMmQCZzMwAmcz/AJn/AACZ/zMAmcxmAJn/mQCZ/8wAmf//AMwAAACZADMAzABmAMwA mQDMAMwAmTMAAMwzMwDMM2YAzDOZAMwzzADMM/8AzGYAAMxmMwCZZmYAzGaZAMxmzACZZv8AzJkAAMyZ MwDMmWYAzJmZAMyZzADMmf8AzMwAAMzMMwDMzGYAzMyZAMzMzADMzP8AzP8AAMz/MwCZ/2YAzP+ZAMz/ zADM//8AzAAzAP8AZgD/AJkAzDMAAP8zMwD/M2YA/zOZAP8zzAD/M/8A/2YAAP9mMwDMZmYA/2aZAP9m zADMZv8A/5kAAP+ZMwD/mWYA/5mZAP+ZzAD/mf8A/8wAAP/MMwD/zGYA/8yZAP/MzAD/zP8A//8zAMz/ ZgD//5kA///MAGZm/wBm/2YAZv//AP9mZgD/Zv8A//9mACEApQBfX18Ad3d3AIaGhgCWlpYAy8vLALKy sgDX19cA3d3dAOPj4wDq6uoA8fHxAPj4+ADw+/8ApKCgAICAgAAAAP8AAP8AAAD//wD/AAAA/wD/AP// AAD///8ACgoKCgoKCgoKCgoKCgoKCgoKCgoK824BAQFu8QoKCgoKCgoKk+lGRkZG6QGNCgoKCgoKk0ZM b29MRkZGAe0KCgoK80Zvb29vb29MRkYB8goKCpNvFhYWFm9vb0xG6W4KCgpvFhYWFhYWFm9vRkYBCgoK bxaUlJSUlBYWb29GAQoKCm+UlJSUlJSUFm9vRkUKCgqTlJSampSUlBZvb0ZuCgoK9HSUmr2alJQWb29F 8woKCgoHk5SUlJSUFm9GkwoKCgoKChoWlJSUFm9GkwoKCgoKCgoK9JN0b2+T9AoKCgoKCgoKCgoKCgoK CgoKCgoKCgoKCgoKCgoKCgoKCgoKCv//AAD4DwAA8AcAAOADAADAAQAAwAEAAMABAADAAQAAwAEAAMAB AADAAQAA4AMAAPAHAAD4DwAA//8AAP//AAA= AAABAAEAEBAAAAAACABoBQAAFgAAACgAAAAQAAAAIAAAAAEACAAAAAAAAAEAAAAAAAAAAAAAAAEAAAAB AAAAAAAAAACAAACAAAAAgIAAgAAAAIAAgACAgAAAwMDAAMDcwADwyqYABAQEAAgICAAMDAwAERERABYW FgAcHBwAIiIiACkpKQBVVVUATU1NAEJCQgA5OTkAgHz/AFBQ/wCTANYA/+zMAMbW7wDW5+cAkKmtAAAA MwAAAGYAAACZAAAAzAAAMwAAADMzAAAzZgAAM5kAADPMAAAz/wAAZgAAAGYzAABmZgAAZpkAAGbMAABm /wAAmQAAAJkzAACZZgAAmZkAAJnMAACZ/wAAzAAAAMwzAADMZgAAzJkAAMzMAADM/wAA/2YAAP+ZAAD/ zAAzAAAAMwAzADMAZgAzAJkAMwDMADMA/wAzMwAAMzMzADMzZgAzM5kAMzPMADMz/wAzZgAAM2YzADNm ZgAzZpkAM2bMADNm/wAzmQAAM5kzADOZZgAzmZkAM5nMADOZ/wAzzAAAM8wzADPMZgAzzJkAM8zMADPM /wAz/zMAM/9mADP/mQAz/8wAM///AGYAAABmADMAZgBmAGYAmQBmAMwAZgD/AGYzAABmMzMAZjNmAGYz mQBmM8wAZjP/AGZmAABmZjMAZmZmAGZmmQBmZswAZpkAAGaZMwBmmWYAZpmZAGaZzABmmf8AZswAAGbM MwBmzJkAZszMAGbM/wBm/wAAZv8zAGb/mQBm/8wAzAD/AP8AzACZmQAAmTOZAJkAmQCZAMwAmQAAAJkz MwCZAGYAmTPMAJkA/wCZZgAAmWYzAJkzZgCZZpkAmWbMAJkz/wCZmTMAmZlmAJmZmQCZmcwAmZn/AJnM AACZzDMAZsxmAJnMmQCZzMwAmcz/AJn/AACZ/zMAmcxmAJn/mQCZ/8wAmf//AMwAAACZADMAzABmAMwA mQDMAMwAmTMAAMwzMwDMM2YAzDOZAMwzzADMM/8AzGYAAMxmMwCZZmYAzGaZAMxmzACZZv8AzJkAAMyZ MwDMmWYAzJmZAMyZzADMmf8AzMwAAMzMMwDMzGYAzMyZAMzMzADMzP8AzP8AAMz/MwCZ/2YAzP+ZAMz/ zADM//8AzAAzAP8AZgD/AJkAzDMAAP8zMwD/M2YA/zOZAP8zzAD/M/8A/2YAAP9mMwDMZmYA/2aZAP9m zADMZv8A/5kAAP+ZMwD/mWYA/5mZAP+ZzAD/mf8A/8wAAP/MMwD/zGYA/8yZAP/MzAD/zP8A//8zAMz/ ZgD//5kA///MAGZm/wBm/2YAZv//AP9mZgD/Zv8A//9mACEApQBfX18Ad3d3AIaGhgCWlpYAy8vLALKy sgDX19cA3d3dAOPj4wDq6uoA8fHxAPj4+ADw+/8ApKCgAICAgAAAAP8AAP8AAAD//wD/AAAA/wD/AP// AAD///8ACgoKCgoKCgoKCgoKCgoKCgoKCgoKCm5ERGgKCgoKCgoKCgoKbm5uRURobmgKCgoKCgoKbm6T CgoKCm5oRAoKCgoKk5MKCgoKCgoKCmhoCgoKCpOTCgoKCgoKCgpubgoKCpOTCgoKCgoKCgoKCmhoCgqT kwoKCgoKCgoKCgpERAoKk5MKCgoKCgoKCgoKRUQKCpOTCgoKCgoKCgoKCm5uCgoKmRoKCgoKCgoKCpNu CgoKCpOTCgoKCgoKCgpubgoKCgoKk5MaCgoKCpOTbgoKCgoKCgqTmZOTk5OTkwoKCgoKCgoKCgqTk5OT CgoKCgoKCgoKCgoKCgoKCgoKCgoKCv//AAD8PwAA8A8AAOPHAADP8wAAz/MAAJ/5AACf+QAAn/kAAJ/5 AADP8wAAz/MAAOPHAADwDwAA/D8AAP//AAA= AAABAAEAEBAAAAAACABoBQAAFgAAACgAAAAQAAAAIAAAAAEACAAAAAAAAAEAAAAAAAAAAAAAAAEAAAAB AAAAAAAAAACAAACAAAAAgIAAgAAAAIAAgACAgAAAwMDAAMDcwADwyqYABAQEAAgICAAMDAwAERERABYW FgAcHBwAIiIiACkpKQBVVVUATU1NAEJCQgA5OTkAgHz/AFBQ/wCTANYA/+zMAMbW7wDW5+cAkKmtAAAA MwAAAGYAAACZAAAAzAAAMwAAADMzAAAzZgAAM5kAADPMAAAz/wAAZgAAAGYzAABmZgAAZpkAAGbMAABm /wAAmQAAAJkzAACZZgAAmZkAAJnMAACZ/wAAzAAAAMwzAADMZgAAzJkAAMzMAADM/wAA/2YAAP+ZAAD/ zAAzAAAAMwAzADMAZgAzAJkAMwDMADMA/wAzMwAAMzMzADMzZgAzM5kAMzPMADMz/wAzZgAAM2YzADNm ZgAzZpkAM2bMADNm/wAzmQAAM5kzADOZZgAzmZkAM5nMADOZ/wAzzAAAM8wzADPMZgAzzJkAM8zMADPM /wAz/zMAM/9mADP/mQAz/8wAM///AGYAAABmADMAZgBmAGYAmQBmAMwAZgD/AGYzAABmMzMAZjNmAGYz mQBmM8wAZjP/AGZmAABmZjMAZmZmAGZmmQBmZswAZpkAAGaZMwBmmWYAZpmZAGaZzABmmf8AZswAAGbM MwBmzJkAZszMAGbM/wBm/wAAZv8zAGb/mQBm/8wAzAD/AP8AzACZmQAAmTOZAJkAmQCZAMwAmQAAAJkz MwCZAGYAmTPMAJkA/wCZZgAAmWYzAJkzZgCZZpkAmWbMAJkz/wCZmTMAmZlmAJmZmQCZmcwAmZn/AJnM AACZzDMAZsxmAJnMmQCZzMwAmcz/AJn/AACZ/zMAmcxmAJn/mQCZ/8wAmf//AMwAAACZADMAzABmAMwA mQDMAMwAmTMAAMwzMwDMM2YAzDOZAMwzzADMM/8AzGYAAMxmMwCZZmYAzGaZAMxmzACZZv8AzJkAAMyZ MwDMmWYAzJmZAMyZzADMmf8AzMwAAMzMMwDMzGYAzMyZAMzMzADMzP8AzP8AAMz/MwCZ/2YAzP+ZAMz/ zADM//8AzAAzAP8AZgD/AJkAzDMAAP8zMwD/M2YA/zOZAP8zzAD/M/8A/2YAAP9mMwDMZmYA/2aZAP9m zADMZv8A/5kAAP+ZMwD/mWYA/5mZAP+ZzAD/mf8A/8wAAP/MMwD/zGYA/8yZAP/MzAD/zP8A//8zAMz/ ZgD//5kA///MAGZm/wBm/2YAZv//AP9mZgD/Zv8A//9mACEApQBfX18Ad3d3AIaGhgCWlpYAy8vLALKy sgDX19cA3d3dAOPj4wDq6uoA8fHxAPj4+ADw+/8ApKCgAICAgAAAAP8AAP8AAAD//wD/AAAA/wD/AP// AAD///8AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA9AAAAAAAAAAAAAAAAAAAACpSAAAAAAAAAAAAAAAA AAAwOFEAAAAAAAAAAAAAAAAAMPs4UgAAAAAAAJlSUlJSUlheXjhSAAAAAAB5euVeXl5eXl5eOFEAAAAA eaCg5eXl5eVeXl44cwAAAHmgoKCgoOXl5eVeUgAAAACZWHl5eXl5oOVeeQAAAAAAAAAAAAAAWKDleQAA AAAAAAAAAAAAAFigeQAAAAAAAAAAAAAAAAA3eQAAAAAAAAAAAAAAAAAA9gAAAAAAAAAAAAAAAAAAAAAA AAAAAAAAAAAAAAAAAAAAAAAAAAAAAP//AAD/fwAA/z8AAP8fAAD/DwAAwAcAAMADAADAAQAAwAMAAMAH AAD/DwAA/x8AAP8/AAD/fwAA//8AAP//AAA= AAABAAEAEBAAAAAACABoBQAAFgAAACgAAAAQAAAAIAAAAAEACAAAAAAAAAEAAAAAAAAAAAAAAAEAAAAB AAAAAAAAAACAAACAAAAAgIAAgAAAAIAAgACAgAAAwMDAAMDcwADwyqYABAQEAAgICAAMDAwAERERABYW FgAcHBwAIiIiACkpKQBVVVUATU1NAEJCQgA5OTkAgHz/AFBQ/wCTANYA/+zMAMbW7wDW5+cAkKmtAAAA MwAAAGYAAACZAAAAzAAAMwAAADMzAAAzZgAAM5kAADPMAAAz/wAAZgAAAGYzAABmZgAAZpkAAGbMAABm /wAAmQAAAJkzAACZZgAAmZkAAJnMAACZ/wAAzAAAAMwzAADMZgAAzJkAAMzMAADM/wAA/2YAAP+ZAAD/ zAAzAAAAMwAzADMAZgAzAJkAMwDMADMA/wAzMwAAMzMzADMzZgAzM5kAMzPMADMz/wAzZgAAM2YzADNm ZgAzZpkAM2bMADNm/wAzmQAAM5kzADOZZgAzmZkAM5nMADOZ/wAzzAAAM8wzADPMZgAzzJkAM8zMADPM /wAz/zMAM/9mADP/mQAz/8wAM///AGYAAABmADMAZgBmAGYAmQBmAMwAZgD/AGYzAABmMzMAZjNmAGYz mQBmM8wAZjP/AGZmAABmZjMAZmZmAGZmmQBmZswAZpkAAGaZMwBmmWYAZpmZAGaZzABmmf8AZswAAGbM MwBmzJkAZszMAGbM/wBm/wAAZv8zAGb/mQBm/8wAzAD/AP8AzACZmQAAmTOZAJkAmQCZAMwAmQAAAJkz MwCZAGYAmTPMAJkA/wCZZgAAmWYzAJkzZgCZZpkAmWbMAJkz/wCZmTMAmZlmAJmZmQCZmcwAmZn/AJnM AACZzDMAZsxmAJnMmQCZzMwAmcz/AJn/AACZ/zMAmcxmAJn/mQCZ/8wAmf//AMwAAACZADMAzABmAMwA mQDMAMwAmTMAAMwzMwDMM2YAzDOZAMwzzADMM/8AzGYAAMxmMwCZZmYAzGaZAMxmzACZZv8AzJkAAMyZ MwDMmWYAzJmZAMyZzADMmf8AzMwAAMzMMwDMzGYAzMyZAMzMzADMzP8AzP8AAMz/MwCZ/2YAzP+ZAMz/ zADM//8AzAAzAP8AZgD/AJkAzDMAAP8zMwD/M2YA/zOZAP8zzAD/M/8A/2YAAP9mMwDMZmYA/2aZAP9m zADMZv8A/5kAAP+ZMwD/mWYA/5mZAP+ZzAD/mf8A/8wAAP/MMwD/zGYA/8yZAP/MzAD/zP8A//8zAMz/ ZgD//5kA///MAGZm/wBm/2YAZv//AP9mZgD/Zv8A//9mACEApQBfX18Ad3d3AIaGhgCWlpYAy8vLALKy sgDX19cA3d3dAOPj4wDq6uoA8fHxAPj4+ADw+/8ApKCgAICAgAAAAP8AAP8AAAD//wD/AAAA/wD/AP// AAD///8ACgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCu/q9wkKCgoKCgoKCQoKCgrrDhO7 CgoKCgoK7LUKCgoK9w8R7AkKCgoKuxW7CgoKCgltERS7CgoJCRPrCgoKCgoKuxQQEgkJCesVuwoKCgoK Cgq7FBHqtRJD7AoKCgoKCgoKCrsUQ0MVFAoKCgoKCgoKCgoK70MUFAkKCgoKCgoKCgoKB+oVFRXqCQoK CgoKCgoK7RQU7AfsFOsJCgoKCgm1bRQU7AkKCesU6wkKCgr3bRUU7QoKCgoJtRLrCgoK9xQTtQoKCgoK CgoJ7QoKCrvrtQoKCgoKCgoKCgoKCv//AAD//wAAw/sAAMPzAADB4wAAwYcAAOAHAADwDwAA+B8AAPwf AAD4DwAA8AcAAICDAACDwwAAh/MAAI//AAA= AAABAAEAEBAAAAAACABoBQAAFgAAACgAAAAQAAAAIAAAAAEACAAAAAAAAAEAAAAAAAAAAAAAAAEAAAAB AAAAAAAAAACAAACAAAAAgIAAgAAAAIAAgACAgAAAwMDAAMDcwADwyqYABAQEAAgICAAMDAwAERERABYW FgAcHBwAIiIiACkpKQBVVVUATU1NAEJCQgA5OTkAgHz/AFBQ/wCTANYA/+zMAMbW7wDW5+cAkKmtAAAA MwAAAGYAAACZAAAAzAAAMwAAADMzAAAzZgAAM5kAADPMAAAz/wAAZgAAAGYzAABmZgAAZpkAAGbMAABm /wAAmQAAAJkzAACZZgAAmZkAAJnMAACZ/wAAzAAAAMwzAADMZgAAzJkAAMzMAADM/wAA/2YAAP+ZAAD/ zAAzAAAAMwAzADMAZgAzAJkAMwDMADMA/wAzMwAAMzMzADMzZgAzM5kAMzPMADMz/wAzZgAAM2YzADNm ZgAzZpkAM2bMADNm/wAzmQAAM5kzADOZZgAzmZkAM5nMADOZ/wAzzAAAM8wzADPMZgAzzJkAM8zMADPM /wAz/zMAM/9mADP/mQAz/8wAM///AGYAAABmADMAZgBmAGYAmQBmAMwAZgD/AGYzAABmMzMAZjNmAGYz mQBmM8wAZjP/AGZmAABmZjMAZmZmAGZmmQBmZswAZpkAAGaZMwBmmWYAZpmZAGaZzABmmf8AZswAAGbM MwBmzJkAZszMAGbM/wBm/wAAZv8zAGb/mQBm/8wAzAD/AP8AzACZmQAAmTOZAJkAmQCZAMwAmQAAAJkz MwCZAGYAmTPMAJkA/wCZZgAAmWYzAJkzZgCZZpkAmWbMAJkz/wCZmTMAmZlmAJmZmQCZmcwAmZn/AJnM AACZzDMAZsxmAJnMmQCZzMwAmcz/AJn/AACZ/zMAmcxmAJn/mQCZ/8wAmf//AMwAAACZADMAzABmAMwA mQDMAMwAmTMAAMwzMwDMM2YAzDOZAMwzzADMM/8AzGYAAMxmMwCZZmYAzGaZAMxmzACZZv8AzJkAAMyZ MwDMmWYAzJmZAMyZzADMmf8AzMwAAMzMMwDMzGYAzMyZAMzMzADMzP8AzP8AAMz/MwCZ/2YAzP+ZAMz/ zADM//8AzAAzAP8AZgD/AJkAzDMAAP8zMwD/M2YA/zOZAP8zzAD/M/8A/2YAAP9mMwDMZmYA/2aZAP9m zADMZv8A/5kAAP+ZMwD/mWYA/5mZAP+ZzAD/mf8A/8wAAP/MMwD/zGYA/8yZAP/MzAD/zP8A//8zAMz/ ZgD//5kA///MAGZm/wBm/2YAZv//AP9mZgD/Zv8A//9mACEApQBfX18Ad3d3AIaGhgCWlpYAy8vLALKy sgDX19cA3d3dAOPj4wDq6uoA8fHxAPj4+ADw+/8ApKCgAICAgAAAAP8AAP8AAAD//wD/AAAA/wD/AP// AAD///8AvEdGvAAHbwoKCgoKCgoKCpMmR5MARiAKCgoKCgoKCgq840fjb0dvCgoKCgoKCgoKCgoWTUfj CgoKCgoKCgoKCgoKk+NNkwoK725ERG73CgoKlOMWFuOT90VFRUVFROwKFuN1AO9vb0VGTExGRkVE9xZ1 vPdFRW9vb29vb0xGRW4KCgduRkxvbxaTFm9vRkVECgrvb29vb2+UlJSTb29FRAoKk28Wk5OTlJqalHRv RW4KCpN0lJSUk5SalJRvTGj3CgoHk5SampOTk5Nvb273CgoKvJOUmpSUdG9vk5MHCgoKCgoHk5OTdG9u BwoKCgoKCgoKCrwHk5OTBwoKCgoKCgn/AAAJ/wAAAf8AAMP/AADDAwAAgAEAABAAAAAAAAAAwAAAAMAA AADAAAAAwAAAAMABAADAAwAA4B8AAPA/AAA= AAABAAEAEBAAAAAACABoBQAAFgAAACgAAAAQAAAAIAAAAAEACAAAAAAAAAEAAAAAAAAAAAAAAAEAAAAB AAAAAAAAAACAAACAAAAAgIAAgAAAAIAAgACAgAAAwMDAAMDcwADwyqYABAQEAAgICAAMDAwAERERABYW FgAcHBwAIiIiACkpKQBVVVUATU1NAEJCQgA5OTkAgHz/AFBQ/wCTANYA/+zMAMbW7wDW5+cAkKmtAAAA MwAAAGYAAACZAAAAzAAAMwAAADMzAAAzZgAAM5kAADPMAAAz/wAAZgAAAGYzAABmZgAAZpkAAGbMAABm /wAAmQAAAJkzAACZZgAAmZkAAJnMAACZ/wAAzAAAAMwzAADMZgAAzJkAAMzMAADM/wAA/2YAAP+ZAAD/ zAAzAAAAMwAzADMAZgAzAJkAMwDMADMA/wAzMwAAMzMzADMzZgAzM5kAMzPMADMz/wAzZgAAM2YzADNm ZgAzZpkAM2bMADNm/wAzmQAAM5kzADOZZgAzmZkAM5nMADOZ/wAzzAAAM8wzADPMZgAzzJkAM8zMADPM /wAz/zMAM/9mADP/mQAz/8wAM///AGYAAABmADMAZgBmAGYAmQBmAMwAZgD/AGYzAABmMzMAZjNmAGYz mQBmM8wAZjP/AGZmAABmZjMAZmZmAGZmmQBmZswAZpkAAGaZMwBmmWYAZpmZAGaZzABmmf8AZswAAGbM MwBmzJkAZszMAGbM/wBm/wAAZv8zAGb/mQBm/8wAzAD/AP8AzACZmQAAmTOZAJkAmQCZAMwAmQAAAJkz MwCZAGYAmTPMAJkA/wCZZgAAmWYzAJkzZgCZZpkAmWbMAJkz/wCZmTMAmZlmAJmZmQCZmcwAmZn/AJnM AACZzDMAZsxmAJnMmQCZzMwAmcz/AJn/AACZ/zMAmcxmAJn/mQCZ/8wAmf//AMwAAACZADMAzABmAMwA mQDMAMwAmTMAAMwzMwDMM2YAzDOZAMwzzADMM/8AzGYAAMxmMwCZZmYAzGaZAMxmzACZZv8AzJkAAMyZ MwDMmWYAzJmZAMyZzADMmf8AzMwAAMzMMwDMzGYAzMyZAMzMzADMzP8AzP8AAMz/MwCZ/2YAzP+ZAMz/ zADM//8AzAAzAP8AZgD/AJkAzDMAAP8zMwD/M2YA/zOZAP8zzAD/M/8A/2YAAP9mMwDMZmYA/2aZAP9m zADMZv8A/5kAAP+ZMwD/mWYA/5mZAP+ZzAD/mf8A/8wAAP/MMwD/zGYA/8yZAP/MzAD/zP8A//8zAMz/ ZgD//5kA///MAGZm/wBm/2YAZv//AP9mZgD/Zv8A//9mACEApQBfX18Ad3d3AIaGhgCWlpYAy8vLALKy sgDX19cA3d3dAOPj4wDq6uoA8fHxAPj4+ADw+/8ApKCgAICAgAAAAP8AAP8AAAD//wD/AAAA/wD/AP// AAD///8AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA AAAAAAAAAAAAAAAAAAAAAAAAAAAAAP//AAD//wAA//8AAP//AAD//wAA//8AAP//AAD//wAA//8AAP// AAD//wAA//8AAP//AAD//wAA//8AAP//AAA= AAABAAEAEBAAAAAAGABoAwAAFgAAACgAAAAQAAAAIAAAAAEAGAAAAAAAAAMAAAAAAAAAAAAAAAAAAAAA AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAD/zMyZMwDMzJkAAAAA AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAD/zMzMmWaZMwCZMwDMzMwAAAAAAAAAAAAAAAAA AAAAAAAAAAAAAAAAAAAAAAD/zMzMmWbMmWaZMwCZMwCZMwDMzMwAAAAAAAAAAAAAAAAAAAAAAAAAAAAA AAAAAADMmWbMmWbMmWaZMwCZMwCZMwCZMwDMzMwAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAADMmWbMmWb/ zGb/zJnMZjOZMwCZMwCZMwAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAADMmWb/zJn/zMz/zJn/zMyZZjOZ MwCZMwAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAADMzGb/zJn/zJn/zJn/zJn/zMyZMzOZMwAAAAAAAAAA AAAAAAAAAAAAAAAAAAAAAAD//8zMzGb/zJn/zJn/zJn/zJn/zJnMZjMAAAAAAAAAAAAAAAAAAAAAAAAA AAAAAAAAAAD/zMzMzGb/zJn/zJn/zJnMzGb/zMwAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAD/ zMzMmWb/zJnMzGbs7OwAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAD/zMzMzGb/+PAA AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAD//wAA//8AAP// AAD+PwAA/B8AAPgPAAD4BwAA+AcAAPgHAAD4BwAA+AcAAPwHAAD+DwAA/x8AAP//AAD//wAA Qk02AwAAAAAAADYAAAAoAAAAEAAAABAAAAABABgAAAAAAAAAAADEDgAAxA4AAAAAAAAAAAAA//////// ////////hHJii3hnhnFhiXRjh3Fhh3FhiHJihW5eiXJhhWxbjnVic1tI////////t6KTY0k1sZqN+u7o +ezl18e/+Ojg+Obf0b+19uLZ9uDXy7as9d3Rd2Jm////////t6KT9+XcgXrVTlL/3tfv2svE+u3n+evk 1MO6+Ofg9+XdzruwwLPkVFHP////////t6KT+eniwa2irKXiTlL/v7XU3M3G0cTH18e/1cW808G5z762 X2D0dGSO////////t6KT+e7ozLqx/fr5x8b5WVz7rav4YGP9l5Hh+vHt+/DqnJTXenn4jnRb//////// t6KT+/Lt2crC//39//z7v7jfW1/+v735YGH4tLH39OzxXF742NHwiXJg////////t6KT/Pbz3tLL6+Pg 6eHc597a5dvW5NjTzMLWW136gX7sfXvr2MnChnNf////////uqWW/fn25NrU//7+//7+6uLf//7+//7+ 5drU2dj8Ymb+yL3T/fn2hHJf////////vqma/vz76uLd//7+//7+7ufj//7+//7+6N/a//7///7+4dbP //z7kXlpdMbhhNfugdfmO8DomdjfitbqeMTb593Z5drU4tbQ3tHL3M7H2cnC1sa908K40L20neL0MLff fen9Xcbmk/D/L7bfoOf4/vv6/fn3/Pbz+/Tvt6KTt6KTZEo2////////l+r6k/H/v/j/r+j0x/v/k/H/ n/D///7+/vv7/fn4t6KTZEo2ZEo2ZEo2////////IqvZU7/hr+j08P/9tOv2U7/hNrvl//7+//7+/vz7 uaSV1MW6Y0k1uayi////////mOv7lvP/x/v/reXzw/v/lvP/n/D/8P/98P/9//7+wKucY0k1uq2i//// ////////oOT2MbjgjPH/WMLjkPH/L7bfjcrU2MKy1L6uz7mpybOk2M7H////////////////bcbjidvx muz7Jq/bker8mOL0i9Dn//////////////////////////////////// AAABAAEAEBAAAAAAGABoAwAAFgAAACgAAAAQAAAAIAAAAAEAGAAAAAAAAAMAAAAAAAAAAAAAAAAAAAAA AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA AAAAAAAAAAAAAAAAAAAAAAAAAAAAAADTwrC1mHi1mHi1mHi1mHi1mHi1mHi1mHjTwrAAAAAAAAAAAAAA AAAAAAAAAAAAAAC1mHi/zNKuvsaouMKnuMGnuMGmt8CqusO1mHgAAAAAAAAAAAAAAAAAAAAAAAAAAAC1 mHjZ4eTP2NzJ09gAAADG0dbAzNK7yM+1mHgAAAAAAAAAAAAAAAAAAAAAAAAAAAC1mHju8vLs8PDn7e0A AADj6erZ4OPM1tu1mHgAAAAAAAAAAAAAAAAAAAAAAAAAAAC1mHjx9fUAAAAAAAAAAAAAAAAAAADS29+1 mHgAAAAAAAAAAAAAAAAAAAAAAAAAAAC1mHj19/f19/f09/cAAAD09vbr8PHa4eW1mHgAAAAAAAAAAAAA AAAAAAAAAAAAAAC1mHj7/Pz7/f37/f0AAAD7/Pz6/Pzz9ve1mHgAAAAAAAAAAAAAAAAAAAAAAAAAAAC1 mHj///////////////////////////+1mHgAAAAAAAAAAAAAAAAAAAAAAAAAAADTwrC1mHi1mHi1mHi1 mHi1mHi1mHi1mHjTwrAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAD//wAA//8AAP// AAD//wAA4A8AAOAPAADgDwAA4A8AAOAPAADgDwAA4A8AAOAPAADgDwAA//8AAP//AAD//wAA AAABAAEAEBAAAAAAGABoAwAAFgAAACgAAAAQAAAAIAAAAAEAGAAAAAAAAAMAAAAAAAAAAAAAAAAAAAAA AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA AAAAAAAAAAAAAAAAAAAAAAAAAAAAAADTwrC1mHi1mHi1mHi1mHi1mHi1mHi1mHjTwrAAAAAAAAAAAAAA AAAAAAAAAAAAAAC1mHi/zNKuvsaouMKnuMGnuMGmt8CqusO1mHgAAAAAAAAAAAAAAAAAAAAAAAAAAAC1 mHjZ4eTP2NzJ09jH0tfG0dbAzNK7yM+1mHgAAAAAAAAAAAAAAAAAAAAAAAAAAAC1mHju8vLs8PDn7e3m 6+zj6erZ4OPM1tu1mHgAAAAAAAAAAAAAAAAAAAAAAAAAAAC1mHjx9fUAAAAAAAAAAAAAAAAAAADS29+1 mHgAAAAAAAAAAAAAAAAAAAAAAAAAAAC1mHj19/f19/f09/f09/f09vbr8PHa4eW1mHgAAAAAAAAAAAAA AAAAAAAAAAAAAAC1mHj////////////////7/Pz6/Pzz9ve1mHgAAAAAAAAAAAAAAAAAAAAAAAAAAAC1 mHj///////////////////////////+1mHgAAAAAAAAAAAAAAAAAAAAAAAAAAADTwrC1mHi1mHi1mHi1 mHi1mHi1mHi1mHjTwrAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAD//wAA//8AAP// AAD//wAA4A8AAOAPAADgDwAA4A8AAOAPAADgDwAA4A8AAOAPAADgDwAA//8AAP//AAD//wAA iVBORw0KGgoAAAANSUhEUgAAABAAAAAQCAYAAAAf8/9hAAAAAXNSR0IArs4c6QAAAARnQU1BAACxjwv8 YQUAAAAgY0hSTQAAeiYAAICEAAD6AAAAgOgAAHUwAADqYAAAOpgAABdwnLpRPAAAAlpJREFUOE+tk21I k1EYhif0oyA0sqIQCix/+GcQFFH9CCmiUBTLLEjShJofVBgL2fxoU9Pp5ubUlS5rU9f8rCyjsA+pUCRC TR1ppmVFUSlmhq78unrnQF1KGHTg/nEOz30993PO+7qJFrmUeiv2n+Mij+XLRLLYULdF2pxlEVIDcw0p AsyxD5fmI/rQ94pqi26eOlsfuZj+7BgSm01QdA4ih7m73Yx9qGpavwatjPebqCzOprPt8YKQgzFagqL0 BEjyEFWVaBkdLHMxT34uYNwWR9nVTEoL0zHlp2DMSeaSRk6eKt4VWm5WM/rVPNN5SjDTLQebZEHNA1wr UvHjk3E6tsNcV62e1r3KLGqtKm6WplNpSsVqVFJsOM8VfSKFWjkGtcyZptSYzvC7XByx3zQoqCnTMvlG CX1prnornPUmQJcUXsbSVhGK5bIOkcmQyveeTHiv4VZ5Nk33Nc6iuSO8CIfmECYa/bE/8ON1iRipJNh5 F0V6Bd86lfQ1JlFj1TDVq4COKCegLVIwHmGiKRB7/V6G7+5koHozymgfYRy5E1CgTWKgXcZ1i5qWp0KS rjgBcAJawph6FszYk/2M1O1isGYLX8p9ab6wgqP+3rMvYciS01GfzA1LFvQkQ6sQ9/khxhoCGHnox1Dt NvorxXw0b8Km8UQh2cip6GOzgNyMeKqKM7HdjqFZJ5pRk2YJ9aql3EnxoCJxNaZ4Ly6e3UDY3O6OEXRp 59ApTpIhiyDh9GHORAZyPHQPB/ZtZ/cOMVvFPvh6e7F+3SrWrHRnraf7Xz/xf/rJ/kvxb84I3U1y+9/W AAAAAElFTkSuQmCC AAABAAEAEBAAAAAAGABoAwAAFgAAACgAAAAQAAAAIAAAAAEAGAAAAAAAAAMAAAAAAAAAAAAAAAAAAAAA AAAAAACchXWWf22Qd2eJcF6Cald8Y08AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAADCq6De0crazMTW x77SwbjOu7LLt6t7Yk8AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAADLt6zq49/ZzshYS0HZzsjZzsjOu7KB aFUAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAADUw7vq499YS0FYS0FYS0Hi19LSwLiHb12ZMwDevawAAAAA AAAAAAAAAAAAAAAAAADd0Mnq49/q49/q49/q49/i19LWx76NdWOZMwCZMwDhxLUAAAAAAAAAAAAAAAAA AADq5uMAAAC0npDd0Mnd0MmNdmSOdmTYm1uZMwCZMwCZMwDhxLUAAAAAAAAAAAAAAAAAAADZzMS8p5gA AAAAAADLt6yXgG/Ym1uZMwCZMwCZMwCZMwDly74AAAAAAAAAAAAAAADe0crq49/Lt6zCq6DWxr2hinrp tHz81q+1YzWZMwCZMwCZMwAAAAAAAAAAAAAAAAAAAADe0crSwLjNurHLt6zqt4L72LL+0aP72LKvVyiZ MwCZMwAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAADns3zxw5H+z53/zZn+0J/72LKpTh6ZMwAAAAAAAAAA AAAAAAAAAAAAAAAAAAAAAAD76NXlsnv0wIv/zZn/zZn+0KHyyZ2wWikAAAAAAAAAAAAAAAAAAAAAAAAA AAAAAAAAAAD659PksHn2xJD/zZnzwo7jsHn55tIAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAD5 483jr3juvYrjsHn67d4AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAD45tLlsn378ecA AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAACB/wAAAP8AAAD/ AAAAPwAAAB8AAEAPAACYBwAAgAcAAMAHAAD4BwAA+AcAAPwHAAD+DwAA/x8AAP//AAD//wAA AAABAAEAEBAAAAAAGABoAwAAFgAAACgAAAAQAAAAIAAAAAEAGAAAAAAAAAMAAAAAAAAAAAAAAAAAAAAA AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAB8dXNOS0tUT01U T01UT01WUU1TUExST0tST0xST0tRTktUTkYAAAAAAAAAAAAAAADZz8gAAAD7/f/7/f////b///b///b/ +ez/8OH/6tX/6tJUTkYAAAAAAAAAAAAAAADSyMEAAADEr6LEr6L/+/nEr6LEr6LEr6LEr6LEr6L93stU TkYAAAAAAAAAAAAAAADSyMEAAAD7/f/7/f///vz9+vj79O/77ub66d744tL/4tBUTkYAAAAAAAAAAAAA AADTycIAAADEr6LEr6L///7Er6LEr6LEr6LEr6LEr6L/5dZUTkYAAAAAAAAAAAAAAADRx8AAAAD7/f/7 /f8AAAD+/v3++/j99vL88Oj88Oj/6dxUTkYAAAAAAAAAAAAAAADRyMEAAAD7/f/7/f8AAAAAAAD+/vyw raxBXHLj2dP/7eNUTkYAAAAAAAAAAAAAAADRyMEAAADi6eledYTf5OUAAADCys5KYXAuqdYLEBtdXGCk nZYAAAAAAACkvqccZinfnX3xyrePpKyG0+VLYXCnkolKYXBhwd5XTVkf0P8VJzMQBwoCIS5PVmVZeFsY jDLfnX3/xaTlybmPpKyD4fZLYXB6zeJSYGdo7f9BPVAyst8dmcgVk8QUYo5AZlEplz/fnX3fnX3fnX3a uqqPpKx/4/lThJVo7f8wOk9p2/ZY0vNAw+0xu+oRqOxQkIwynkEAAAAAAAAAAAAAAADn6+1Xa4Bo7f9Y mK5u6/9y4flq3fdWz/JLx+0iuvpfoqZBrFMAAAAAAAAAAAAAAADCyNCw6/pbbX9u6/9u6/9u6/9y4vpn 1/RUvdxRcotpnImFzIUAAAAAAAAAAAAAAACjrLiVuMTU2d2BprWAl6OAlqB6j5lzhZNccYC/yM2ZuJyu waYAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAD//wAAAA8AAEAP AABADwAAQA8AAEAPAABIDwAATA8AAEQMAAAAAAAAAAAAAAAAAADwAAAA8AAAAPAAAAD//wAA AAABAAEAEBAAAAAAGABoAwAAFgAAACgAAAAQAAAAIAAAAAEAGAAAAAAAAAMAAAAAAAAAAAAAAAAAAAAA AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAD/zMyZMwDMzJkAAAAA AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAD/zMzMmWaZMwCZMwDMzMwAAAAAAAAAAAAAAAAA AAAAAAAAAAAAAAAAAAAAAAD/zMzMmWbMmWaZMwCZMwCZMwDMzMwAAAAAAAAAAAAAAAAAAAAAAAAAAAAA AAAAAADMmWbMmWbMmWaZMwCZMwCZMwCZMwDMzMwAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAADMmWbMmWb/ zGb/zJnMZjOZMwCZMwCZMwAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAADMmWb/zJn/zMz/zJn/zMyZZjOZ MwCZMwAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAADMzGb/zJn/zJn/zJn/zJn/zMyZMzOZMwAAAAAAAAAA AAAAAAAAAAAAAAAAAAAAAAD//8zMzGb/zJn/zJn/zJn/zJn/zJnMZjMAAAAAAAAAAAAAAAAAAAAAAAAA AAAAAAAAAAD/zMzMzGb/zJn/zJn/zJnMzGb/zMwAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAD/ zMzMmWb/zJnMzGbs7OwAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAD/zMzMzGb/+PAA AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAD//wAA//8AAP// AAD+PwAA/B8AAPgPAAD4BwAA+AcAAPgHAAD4BwAA+AcAAPwHAAD+DwAA/x8AAP//AAD//wAA iVBORw0KGgoAAAANSUhEUgAAABAAAAAQCAYAAAAf8/9hAAAAAXNSR0IArs4c6QAAAARnQU1BAACxjwv8 YQUAAAAgY0hSTQAAeiYAAICEAAD6AAAAgOgAAHUwAADqYAAAOpgAABdwnLpRPAAAAJZJREFUOE/dk90N gCAMhNmJndiJBRzGdBLig0xQe4XiT4Kojza5xEbua0+ic/+qSMwnRemrgrwwdVPDPM1rEy0V2CDMPhA/ AuScGYUNgqps4KXpA+QgNjAzAEezAvwAkFLSydciiQeAGwGwMrJb2eroNf8doBwukwgjNQJyl+eHgP26 okBg+gww8yvA0YQr069+1b/+nw2qkiqswXftqgAAAABJRU5ErkJggg== iVBORw0KGgoAAAANSUhEUgAAABAAAAAQCAYAAAAf8/9hAAAAAXNSR0IArs4c6QAAAARnQU1BAACxjwv8 YQUAAAAgY0hSTQAAeiYAAICEAAD6AAAAgOgAAHUwAADqYAAAOpgAABdwnLpRPAAAAKNJREFUOE+1k8EN AiEQRbenOXGlGFqglmnAAqiAkwczZ9vQDr7ziavGrAtZIskc3/sfMizLP8/pcseUXzWh1npcQkHO+biE AsCQ0mATAt9DAaAukX4TwrfruaWuIGGYN/GJMe5L1sov+AkSNhOYCpIISinbD6t+15bYUt/JRoHDIYRO Axfwrp8zDG8tDOsOJf/aNgq6tfdWdQqmePovTH2kUfgBlkjDktDac9sAAAAASUVORK5CYII= AAABAAEAEBAAAAAACABoBQAAFgAAACgAAAAQAAAAIAAAAAEACAAAAAAAAAEAAAAAAAAAAAAAAAEAAAAB AAAAAAAAAACAAACAAAAAgIAAgAAAAIAAgACAgAAAwMDAAMDcwADwyqYABAQEAAgICAAMDAwAERERABYW FgAcHBwAIiIiACkpKQBVVVUATU1NAEJCQgA5OTkAgHz/AFBQ/wCTANYA/+zMAMbW7wDW5+cAkKmtAAAA MwAAAGYAAACZAAAAzAAAMwAAADMzAAAzZgAAM5kAADPMAAAz/wAAZgAAAGYzAABmZgAAZpkAAGbMAABm /wAAmQAAAJkzAACZZgAAmZkAAJnMAACZ/wAAzAAAAMwzAADMZgAAzJkAAMzMAADM/wAA/2YAAP+ZAAD/ zAAzAAAAMwAzADMAZgAzAJkAMwDMADMA/wAzMwAAMzMzADMzZgAzM5kAMzPMADMz/wAzZgAAM2YzADNm ZgAzZpkAM2bMADNm/wAzmQAAM5kzADOZZgAzmZkAM5nMADOZ/wAzzAAAM8wzADPMZgAzzJkAM8zMADPM /wAz/zMAM/9mADP/mQAz/8wAM///AGYAAABmADMAZgBmAGYAmQBmAMwAZgD/AGYzAABmMzMAZjNmAGYz mQBmM8wAZjP/AGZmAABmZjMAZmZmAGZmmQBmZswAZpkAAGaZMwBmmWYAZpmZAGaZzABmmf8AZswAAGbM MwBmzJkAZszMAGbM/wBm/wAAZv8zAGb/mQBm/8wAzAD/AP8AzACZmQAAmTOZAJkAmQCZAMwAmQAAAJkz MwCZAGYAmTPMAJkA/wCZZgAAmWYzAJkzZgCZZpkAmWbMAJkz/wCZmTMAmZlmAJmZmQCZmcwAmZn/AJnM AACZzDMAZsxmAJnMmQCZzMwAmcz/AJn/AACZ/zMAmcxmAJn/mQCZ/8wAmf//AMwAAACZADMAzABmAMwA mQDMAMwAmTMAAMwzMwDMM2YAzDOZAMwzzADMM/8AzGYAAMxmMwCZZmYAzGaZAMxmzACZZv8AzJkAAMyZ MwDMmWYAzJmZAMyZzADMmf8AzMwAAMzMMwDMzGYAzMyZAMzMzADMzP8AzP8AAMz/MwCZ/2YAzP+ZAMz/ zADM//8AzAAzAP8AZgD/AJkAzDMAAP8zMwD/M2YA/zOZAP8zzAD/M/8A/2YAAP9mMwDMZmYA/2aZAP9m zADMZv8A/5kAAP+ZMwD/mWYA/5mZAP+ZzAD/mf8A/8wAAP/MMwD/zGYA/8yZAP/MzAD/zP8A//8zAMz/ ZgD//5kA///MAGZm/wBm/2YAZv//AP9mZgD/Zv8A//9mACEApQBfX18Ad3d3AIaGhgCWlpYAy8vLALKy sgDX19cA3d3dAOPj4wDq6uoA8fHxAPj4+ADw+/8ApKCgAICAgAAAAP8AAP8AAAD//wD/AAAA/wD/AP// AAD///8AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAO9tAAAAAAAAAAAAAAAA AADtLUkAAAAAAAAAAAAAAAAA9zQuSQAAAAAAAAAAAADuB/g0Li5PAAAAAAAAAABPLi5VVk8uLkkAAAAA AACYVlZWVlZWTy4uSQAAAAAAVnh4l1ZWVlZVLrwAAAAA81Z4l5dyl1ZWLrwAAAAAAPRWVvIA75eXVbwA AAAAAAD0VpgAAJjkVrwAAAAAAAAA9Vb2AACYVfAAAAAAAAAAAACYCAAAAPUAAAAAAAAAAAAAAAj1AAAA AAAAAAAAAAAAAAAAAAAAAAAAAAAAAP//AAD//wAA/z8AAP8fAAD/DwAA/AcAAPgDAADwAQAA8AEAAOAD AADhBwAA4w8AAOMfAADzvwAA+f8AAP//AAA= iVBORw0KGgoAAAANSUhEUgAAABAAAAAQCAYAAAAf8/9hAAAAAXNSR0IArs4c6QAAAARnQU1BAACxjwv8 YQUAAAAgY0hSTQAAeiYAAICEAAD6AAAAgOgAAHUwAADqYAAAOpgAABdwnLpRPAAAAHJJREFUOE+1090N wCAIBGB2Yid2YhsHYITuYj36k6ZP5UhNTHy5j4go8sfyiNlyzW22EABqyiMAxjZ4BIBFAzHXBHIz19EL QHid0Q81+d6TBB5hqYTx/lnxrFwO38BCqPABCB/OEa7e+T33rTFufSImvAO7DnN9iUwxTQAAAABJRU5E rkJggg== Qk02AwAAAAAAADYAAAAoAAAAEAAAABAAAAABABgAAAAAAAAAAADEDgAAxA4AAAAAAAAAAAAA//////// //////////////////////////////////////////////////////////////////////////////// ////////////////////////////////////////rca+////////////hXNjjHhoh3FhinRkiHFhiHFh iXJihm5einJhhWxbj3VidFxICWMUscnB////////sZqN+u7o+ezl18e/+Ojg+Obf0b+19uLZ9uDXy7as 9d3Rd2JmEWgbBGAPtczF////gXrVTlL/3tfv2svE+u3n+evk1MO6+Ofg9+XdzruwwLPkVFHPGm8kIHMs BGAPus/Izb21rKXiTlL/v7XU3M3G0cTH18e/1cW808G5z762X2D0dGSPI3UuL4M9IHMsBGAP5uXf/fr5 x8b5WVz7rav4YGP9l5Hh+vHt+/DqnJTXenn4jnVcLnw3UKJaL4M9IHMsBGAP3uje//z7v7jfW1/+v735 YGH4tLH39OzxXF742NHwinJhOINBXbBoUKJaL4M9IHMsC2YYy9HC597a5dvW5NjTzMLWW136gX7sfXvr 2MnChnNgQ4pMa792a792UKJaL3Y51u3Z/fr56uLf/fr5/fr55drU2dj8Ymb+yL3T/fn2hHJfS5BTa792 o9qwL3Y5x9jB/fr5/fr57ufj/fr5/fr56N/a/fr5/fr54dbP//z7kXlpUpRao9qwL3Y5w97N8sq36qqL 6qqL6aWE6Z9655du5o5i5YZW431K43ZA4nI5yGIvWJhgL3Y5xODP////6qqL/8Ki/sCf/b2a/LmW+7WQ +rCL+auE+Kd99qJ39Z1xzWUxWJhgxuHP////////6qqL6qqL6qqL6qqL6qaG6aF/6Jt255Rs5o5i5YdY 5IFO4nI5x+LQ//////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////// AAABAAEAEBAAAAAAGABoAwAAFgAAACgAAAAQAAAAIAAAAAEAGAAAAAAAAAMAAAAAAAAAAAAAAAAAAAAA AACwm4yEb159aFZ8Z1WFcV+Hc2GGcWB1X0wAAAAAAAAAAAD47uMAAAAAAAAAAAAAAAC0oZP89O/68ez6 7uj56+X56OH45t17ZVMAAAAAAAD47uOZMwD47uMAAAAAAAAAAAC6p5r9+Pb89vNHR0dHR0dHR0f67OV/ alcAAAD47uO1YzXYm1uZMwD47uMAAAAAAADArqH+/Pv++vj9+PVHR0f88/D78ex7ZlOXgG/Ym1v/zZnp tHzYm1uZMwD47uMAAADGtKgAAAD//v1HR0dHR0f9+Pb99vN+aVcAAAD47uPYm1v/zZnptHzYm1uZMwD4 7uPKuq8AAAAAAAAAAABHR0f+/Pv++vh8Z1UAAAAAAAD47uPYm1v/zZnJc0P47uMAAADOvrMAAAAAAAAA AAAAAAAAAAD+/f2PfGsAAAAAAAAAAAD33uLYm1v47uMAAAAAAADOvrPKuq/GtKjArqK6p5q0oZKwm4ys l4gAAAAAAAD97P2NLYz33uIAAAAAAAAAAAAAAADY7vYOeJ4ctu4OeJ7Y7vYAAACXgG8AAAD97P2zPLLc cNuNLYz97P0AAAAAAADY7vYOeJ5Py/E0wO8vvu8MYoGXgG+XgG+XgG/ZbNj6rfr7mPrccNuNLYz97P0A AAAUquGF4fVr1/RQy/E0wPAdte4MYoHY7vYAAAD97P3TZdL6rfr7mPrccNuNLYz97P3Y7vYUquGG4fVs 1vNQy/I1wPActe0MYoHY7vYAAAD97P3TZdL6rfrTZdL97P0AAAAAAADY7vYUquGF4PVs1vNQy/I0wO8d te0MYoHY7vYAAAD97P3TZdL97P0AAAAAAAAAAAAAAADY7vYUquGG4fRr1vRQy/EXmMjY7vYAAAAAAAAA AAD97P0AAAAAAAAAAAAAAAAAAAAAAADY7vYUquGF4fUXmMjY7vYAAAAAAAAAAAAAAAAAAAAAAAAAAAAA AAAAAAAAAAAAAAAAAADY7vYUquHY7vYAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA7wAAAMcAAACD AAAAAQAAQIAAAHDBAAB84wAAAMcAAIKDAAAAAQAAAIAAAABBAACAIwAAwHcAAOD/AADx/wAA iVBORw0KGgoAAAANSUhEUgAAABAAAAAQCAYAAAAf8/9hAAAAAXNSR0IArs4c6QAAAARnQU1BAACxjwv8 YQUAAAAgY0hSTQAAeiYAAICEAAD6AAAAgOgAAHUwAADqYAAAOpgAABdwnLpRPAAAAIdJREFUOE9jYKAU LDv14X/azDNgbJyGikFiBM2HaZ4JVAwyjKAGdAVpQFtxaWRhYfmPD4PNQjYA7A1SXQIyAKQR5gVYWIBo ZJdhcwnYBSCN4HCAGoQIzJnAQJ1JWpiAbARpgmGQ4bAww+kC5EAFuwJoAFmxQSj6iHIBIUNIlicqHZBs 6vDTAAAyD5dUV+U74QAAAABJRU5ErkJggg== iVBORw0KGgoAAAANSUhEUgAAABAAAAAQCAYAAAAf8/9hAAAAAXNSR0IArs4c6QAAAARnQU1BAACxjwv8 YQUAAAAgY0hSTQAAeiYAAICEAAD6AAAAgOgAAHUwAADqYAAAOpgAABdwnLpRPAAAAIFJREFUOE/lUtsJ wDAIzIcbZSd3coEOUzJMN0g9i9SPtJHQvwaOBPEeSkoJh6X1qtj2o8d6+g2iiXCzOyUk2ojmCAhUFsPU HUSIwA1wIm7UUwLexIiuxFT0SHpyIaL+BuPFEaZxRw2+ecS/lucQHefewSjJkuEy6a8JUv9geatfEU8K RY5hrSJDogAAAABJRU5ErkJggg== iVBORw0KGgoAAAANSUhEUgAAABAAAAAQCAYAAAAf8/9hAAAAAXNSR0IArs4c6QAAAARnQU1BAACxjwv8 YQUAAAAgY0hSTQAAeiYAAICEAAD6AAAAgOgAAHUwAADqYAAAOpgAABdwnLpRPAAAAJZJREFUOE/dk+EJ gCAQhU9wo2umayYboGHCaIGGCBrA7llBQYlH/xIfp+D7POTp+mFJ6zTTOBLpzIOZqGsbd2zLRUJMUFAB VmW6HoL5zei9TyVljki033rroBLw1MlfOuCvb1ALeM0HAJ9yAMCZQqxLwXrsAkHKUY47CBATCKYMuYgl KETFwZZSvMVpRAXc9LlETZDlV27bcKRWlYRMYwAAAABJRU5ErkJggg== iVBORw0KGgoAAAANSUhEUgAAABAAAAAQCAYAAAAf8/9hAAAAAXNSR0IArs4c6QAAAARnQU1BAACxjwv8 YQUAAAAgY0hSTQAAeiYAAICEAAD6AAAAgOgAAHUwAADqYAAAOpgAABdwnLpRPAAAAIpJREFUOE/dUskR gCAMpKf0lJ5owGIcSvEhFWA2HBN5SB6+cGYZZdgjiyHs9cRUykCU9waWzY7PiUFOl4F8H+c9QJzKUiDn rCKWqKlkIY4LAYmsCZpzJVZgBCKnQHd/dYD4LoHJfRToEcBhuPfolqwFrhIMAXNtLESUpwV6BOBUISQQ Zuz16/8yzQMfJO4S6VwGZAAAAABJRU5ErkJggg== Qk02AwAAAAAAADYAAAAoAAAAEAAAABAAAAABABgAAAAAAAAAAADEDgAAxA4AAAAAAAAAAAAA//////// //////////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////////// ////////////////////4pVutmI5sFwzp1MqnUggkj4WiTQNgi0GgSwF//////////////////////// ////45dw87yg16GDzo1twXxZr2tIp2JAm1g3gSwF////////////////////////////55t0+cmv9bWU 7aN+5pVs2oVZznlOrGVDhTAJ////////////////////////////6p54+dC7+L2h9LCQ75955pJo3IRZ tGtIizYP////////////////////////////76N9+9fI+Met97eY8quI7Z965pRtvndVkj4W//////// ////////////////////86iB++HT+c66+L+l87OU8qiF65960I1smkYe//////////////////////// ////9q2G++Xa+9rK+cqz+MKo9raY87OR3KOHok4l////////////////////////////+rCK/OHV++LU +tjG+c25+cqz+cas9budqlUt/////////////////////////////bON+rCK9q2G86iB76N96p5455t0 45dw4pVu//////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////// AAABAAEAEBAAAAAACABoBQAAFgAAACgAAAAQAAAAIAAAAAEACAAAAAAAAAEAAAAAAAAAAAAAAAEAAAAB AAAAAAAAAACAAACAAAAAgIAAgAAAAIAAgACAgAAAwMDAAMDcwADwyqYABAQEAAgICAAMDAwAERERABYW FgAcHBwAIiIiACkpKQBVVVUATU1NAEJCQgA5OTkAgHz/AFBQ/wCTANYA/+zMAMbW7wDW5+cAkKmtAAAA MwAAAGYAAACZAAAAzAAAMwAAADMzAAAzZgAAM5kAADPMAAAz/wAAZgAAAGYzAABmZgAAZpkAAGbMAABm /wAAmQAAAJkzAACZZgAAmZkAAJnMAACZ/wAAzAAAAMwzAADMZgAAzJkAAMzMAADM/wAA/2YAAP+ZAAD/ zAAzAAAAMwAzADMAZgAzAJkAMwDMADMA/wAzMwAAMzMzADMzZgAzM5kAMzPMADMz/wAzZgAAM2YzADNm ZgAzZpkAM2bMADNm/wAzmQAAM5kzADOZZgAzmZkAM5nMADOZ/wAzzAAAM8wzADPMZgAzzJkAM8zMADPM /wAz/zMAM/9mADP/mQAz/8wAM///AGYAAABmADMAZgBmAGYAmQBmAMwAZgD/AGYzAABmMzMAZjNmAGYz mQBmM8wAZjP/AGZmAABmZjMAZmZmAGZmmQBmZswAZpkAAGaZMwBmmWYAZpmZAGaZzABmmf8AZswAAGbM MwBmzJkAZszMAGbM/wBm/wAAZv8zAGb/mQBm/8wAzAD/AP8AzACZmQAAmTOZAJkAmQCZAMwAmQAAAJkz MwCZAGYAmTPMAJkA/wCZZgAAmWYzAJkzZgCZZpkAmWbMAJkz/wCZmTMAmZlmAJmZmQCZmcwAmZn/AJnM AACZzDMAZsxmAJnMmQCZzMwAmcz/AJn/AACZ/zMAmcxmAJn/mQCZ/8wAmf//AMwAAACZADMAzABmAMwA mQDMAMwAmTMAAMwzMwDMM2YAzDOZAMwzzADMM/8AzGYAAMxmMwCZZmYAzGaZAMxmzACZZv8AzJkAAMyZ MwDMmWYAzJmZAMyZzADMmf8AzMwAAMzMMwDMzGYAzMyZAMzMzADMzP8AzP8AAMz/MwCZ/2YAzP+ZAMz/ zADM//8AzAAzAP8AZgD/AJkAzDMAAP8zMwD/M2YA/zOZAP8zzAD/M/8A/2YAAP9mMwDMZmYA/2aZAP9m zADMZv8A/5kAAP+ZMwD/mWYA/5mZAP+ZzAD/mf8A/8wAAP/MMwD/zGYA/8yZAP/MzAD/zP8A//8zAMz/ ZgD//5kA///MAGZm/wBm/2YAZv//AP9mZgD/Zv8A//9mACEApQBfX18Ad3d3AIaGhgCWlpYAy8vLALKy sgDX19cA3d3dAOPj4wDq6uoA8fHxAPj4+ADw+/8ApKCgAICAgAAAAP8AAP8AAAD//wD/AAAA/wD/AP// AAD///8A8P///////////////////2zx//////////////////9sbPH/////7m5FRG4H////bWxs8f// k0VFRUVFRO3//66ubBLtRUVGTExGRkVEB/+urm1FRUVvb29vb0xGRW7/rvhuRkxvbxaTFm9vRkVE/5Hs b29vb2+UlJSTb29FRf+R7G8Wk5OTlJqalHRvRW7/7e10lJSUk5SalJRvTG4H/+33k5SampOTk5Nvb2+T ///395OUmpSUdG9vbpMa////tbX3k5OTb29ubWxs8f///+/vtff3k+3s666ubGzx//+17++19+3tkZGu rq5sbPH/7++177X3ku2Rka6urmxs8AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA= iVBORw0KGgoAAAANSUhEUgAAABAAAAAQCAYAAAAf8/9hAAAAAXNSR0IArs4c6QAAAARnQU1BAACxjwv8 YQUAAAAgY0hSTQAAeiYAAICEAAD6AAAAgOgAAHUwAADqYAAAOpgAABdwnLpRPAAAAT5JREFUOE+VkzFu hDAQRTdn4hycgc5X4CZI7raIcgBOQB05NRUVHdoinGAyb4xtYFlFizTCeGfen/n2fty2x3uRtE7vn7xx WpXPUgLg6/tXfJDn0N/cRVQuFFEABJslmXUM9q8it+BDpKWk8DiOJNuzrqukqCont31rZwUgwzBI3/fa XcgBgP0MYO5rkJdlWWSaJgna4TiOWT0DTLXyx7A9Z6aiTvL9/qkiXg0OBs2AcoybB1pIMYok0S4mMg7F TluNpxVFsokomIlWLKY8z7MVxxELpG3b1wAgGN51XVY3gAbjot40zWtAOi46IpnW493QEdUruxPa5eUI FOM4bjN/ahtQKsYDG2EDHTyAvA+Scb7cRj0FV4kEfXtnJ3P+/zx9m+NmpJqoUde11hfIv4Bzwh7itJu3 ARQAiT54+QMtcAvSGPTnwQAAAABJRU5ErkJggg== ================================================ FILE: Zelig/Zelig/DebugTime/Debugger/Properties/Settings.Designer.cs ================================================ //------------------------------------------------------------------------------ // // This code was generated by a tool. // Runtime Version:4.0.30319.34209 // // Changes to this file may cause incorrect behavior and will be lost if // the code is regenerated. // //------------------------------------------------------------------------------ namespace Microsoft.Zelig.Debugger.ArmProcessor.Properties { [global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()] [global::System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.VisualStudio.Editors.SettingsDesigner.SettingsSingleFileGenerator", "12.0.0.0")] internal sealed partial class Settings : global::System.Configuration.ApplicationSettingsBase { private static Settings defaultInstance = ((Settings)(global::System.Configuration.ApplicationSettingsBase.Synchronized(new Settings()))); public static Settings Default { get { return defaultInstance; } } } } ================================================ FILE: Zelig/Zelig/DebugTime/Debugger/Properties/Settings.settings ================================================  ================================================ FILE: Zelig/Zelig/DebugTime/Debugger/SoloDebugOverDccUI_HW.DebuggerConfig ================================================ -LoadAssembly %DEPOTROOT%\SoloBuild\bin\Debug\DebuggerPlugIn.dll -AddHandler Microsoft.Vox.Solo.Common.Windows.DebuggerPlugIn.UInoData #-AddHandler Microsoft.Vox.Solo.Common.Windows.DebuggerPlugIn.ProtocolOverDcc -AddHandler Microsoft.Vox.Solo.Common.Windows.DebuggerPlugIn.ProtocolOverSPI_DebugOverDCC #-Session "Solo Test NXP HW" -Session "Solo Test FF HW JLink" #-Session "Solo Tester FF HW" ================================================ FILE: Zelig/Zelig/DebugTime/Debugger/SoloOverDccUI.DebuggerConfig ================================================ -LoadAssembly %DEPOTROOT%\SoloBuild\bin\Debug\DebuggerPlugIn.dll -AddHandler Microsoft.Vox.Solo.Common.Windows.DebuggerPlugIn.UIOverDcc -AddHandler Microsoft.Vox.Solo.Common.Windows.DebuggerPlugIn.ProtocolOverDcc -AddHandler Microsoft.Vox.Solo.Common.Windows.DebuggerPlugIn.Interop #-Session "Solo Tester FF" -Session "Solo Test FF" ================================================ FILE: Zelig/Zelig/DebugTime/Debugger/SoloOverDccUI_HW.DebuggerConfig ================================================ -LoadAssembly %DEPOTROOT%\SoloBuild\bin\Debug\DebuggerPlugIn.dll -AddHandler Microsoft.Vox.Solo.Common.Windows.DebuggerPlugIn.UIOverDcc -AddHandler Microsoft.Vox.Solo.Common.Windows.DebuggerPlugIn.ProtocolOverDcc #-AddHandler Microsoft.Vox.Solo.Common.Windows.DebuggerPlugIn.Interop #-Session "Solo Test NXP HW" -Session "Solo Test FF HW" ================================================ FILE: Zelig/Zelig/DebugTime/Debugger/SoloOverSerialUI_HW.DebuggerConfig ================================================ -LoadAssembly %DEPOTROOT%\SoloBuild\bin\Debug\DebuggerPlugIn.dll -AddHandler Microsoft.Vox.Solo.Common.Windows.DebuggerPlugIn.UIOverSerial -AddHandler Microsoft.Vox.Solo.Common.Windows.DebuggerPlugIn.ProtocolOverSerial #-AddHandler Microsoft.Vox.Solo.Common.Windows.DebuggerPlugIn.Interop -Session "Solo Test NXP HW" #-Session "Solo Tester NXP HW" ================================================ FILE: Zelig/Zelig/DebugTime/Debugger/SoloUI.DebuggerConfig ================================================ -LoadAssembly %DEPOTROOT%\SoloBuild\bin\Debug\DebuggerPlugIn.dll -AddHandler Microsoft.Vox.Solo.Common.Windows.DebuggerPlugIn.UIOverDcc #-AddHandler Microsoft.Vox.Solo.Common.Windows.DebuggerPlugIn.Protocol -AddHandler Microsoft.Vox.Solo.Common.Windows.DebuggerPlugIn.ProtocolOverSPI_DebugOverDCC #-AddHandler Microsoft.Vox.Solo.Common.Windows.DebuggerPlugIn.Interop -Session "Solo Test FF" ================================================ FILE: Zelig/Zelig/DebugTime/Debugger/UserControls/BreakpointsView.Designer.cs ================================================ namespace Microsoft.Zelig.Debugger.ArmProcessor { partial class BreakpointsView { /// /// Required designer variable. /// private System.ComponentModel.IContainer components = null; /// /// Clean up any resources being used. /// /// true if managed resources should be disposed; otherwise, false. protected override void Dispose( bool disposing ) { if(disposing && (components != null)) { components.Dispose(); } base.Dispose( disposing ); } #region Component Designer generated code /// /// Required method for Designer support - do not modify /// the contents of this method with the code editor. /// private void InitializeComponent() { System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager( typeof( BreakpointsView ) ); this.panel_Breakpoints_Search = new System.Windows.Forms.Panel(); this.listBox_Breakpoint_SearchResults = new System.Windows.Forms.ListBox(); this.label_Breakpoint_Search = new System.Windows.Forms.Label(); this.textBox_Breakpoint_Search = new System.Windows.Forms.TextBox(); this.dataGridView_Breakpoints = new System.Windows.Forms.DataGridView(); this.toolStrip1 = new System.Windows.Forms.ToolStrip(); this.toolStripButton_DeleteBreakpoint = new System.Windows.Forms.ToolStripButton(); this.toolStripSeparator1 = new System.Windows.Forms.ToolStripSeparator(); this.toolStripButton_DeleteAllBreakpoints = new System.Windows.Forms.ToolStripButton(); this.toolStripButton_ToggleAllBreakpoints = new System.Windows.Forms.ToolStripButton(); this.panel1 = new System.Windows.Forms.Panel(); this.dataGridViewImageColumn_Breakpoints_Status = new System.Windows.Forms.DataGridViewImageColumn(); this.dataGridViewTextBoxColumn_Breakpoints_Method = new System.Windows.Forms.DataGridViewTextBoxColumn(); this.dataGridViewTextBoxColumn_Breakpoints_Condition = new System.Windows.Forms.DataGridViewTextBoxColumn(); this.dataGridViewTextBoxColumn_Breakpoints_HitCount = new System.Windows.Forms.DataGridViewTextBoxColumn(); this.panel_Breakpoints_Search.SuspendLayout(); ((System.ComponentModel.ISupportInitialize)(this.dataGridView_Breakpoints)).BeginInit(); this.toolStrip1.SuspendLayout(); this.panel1.SuspendLayout(); this.SuspendLayout(); // // panel_Breakpoints_Search // this.panel_Breakpoints_Search.Controls.Add( this.listBox_Breakpoint_SearchResults ); this.panel_Breakpoints_Search.Controls.Add( this.label_Breakpoint_Search ); this.panel_Breakpoints_Search.Controls.Add( this.textBox_Breakpoint_Search ); this.panel_Breakpoints_Search.Dock = System.Windows.Forms.DockStyle.Top; this.panel_Breakpoints_Search.Location = new System.Drawing.Point( 0, 0 ); this.panel_Breakpoints_Search.Name = "panel_Breakpoints_Search"; this.panel_Breakpoints_Search.Size = new System.Drawing.Size( 572, 187 ); this.panel_Breakpoints_Search.TabIndex = 1; // // listBox_Breakpoint_SearchResults // this.listBox_Breakpoint_SearchResults.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Left) | System.Windows.Forms.AnchorStyles.Right))); this.listBox_Breakpoint_SearchResults.FormattingEnabled = true; this.listBox_Breakpoint_SearchResults.HorizontalScrollbar = true; this.listBox_Breakpoint_SearchResults.Location = new System.Drawing.Point( 7, 30 ); this.listBox_Breakpoint_SearchResults.Name = "listBox_Breakpoint_SearchResults"; this.listBox_Breakpoint_SearchResults.Size = new System.Drawing.Size( 560, 147 ); this.listBox_Breakpoint_SearchResults.TabIndex = 2; this.listBox_Breakpoint_SearchResults.DoubleClick += new System.EventHandler( this.listBox_Breakpoint_SearchResults_DoubleClick ); this.listBox_Breakpoint_SearchResults.Click += new System.EventHandler( this.listBox_Breakpoint_SearchResults_Click ); // // label_Breakpoint_Search // this.label_Breakpoint_Search.AutoSize = true; this.label_Breakpoint_Search.Location = new System.Drawing.Point( 4, 7 ); this.label_Breakpoint_Search.Name = "label_Breakpoint_Search"; this.label_Breakpoint_Search.Size = new System.Drawing.Size( 44, 13 ); this.label_Breakpoint_Search.TabIndex = 1; this.label_Breakpoint_Search.Text = "Search:"; // // textBox_Breakpoint_Search // this.textBox_Breakpoint_Search.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Left) | System.Windows.Forms.AnchorStyles.Right))); this.textBox_Breakpoint_Search.Location = new System.Drawing.Point( 54, 4 ); this.textBox_Breakpoint_Search.Name = "textBox_Breakpoint_Search"; this.textBox_Breakpoint_Search.Size = new System.Drawing.Size( 513, 20 ); this.textBox_Breakpoint_Search.TabIndex = 0; this.textBox_Breakpoint_Search.TextChanged += new System.EventHandler( this.textBox_Breakpoint_Search_TextChanged ); // // dataGridView_Breakpoints // this.dataGridView_Breakpoints.AllowUserToAddRows = false; this.dataGridView_Breakpoints.AllowUserToDeleteRows = false; this.dataGridView_Breakpoints.AllowUserToResizeRows = false; this.dataGridView_Breakpoints.Anchor = ((System.Windows.Forms.AnchorStyles)((((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Bottom) | System.Windows.Forms.AnchorStyles.Left) | System.Windows.Forms.AnchorStyles.Right))); this.dataGridView_Breakpoints.ColumnHeadersHeightSizeMode = System.Windows.Forms.DataGridViewColumnHeadersHeightSizeMode.AutoSize; this.dataGridView_Breakpoints.Columns.AddRange( new System.Windows.Forms.DataGridViewColumn[] { this.dataGridViewImageColumn_Breakpoints_Status, this.dataGridViewTextBoxColumn_Breakpoints_Method, this.dataGridViewTextBoxColumn_Breakpoints_Condition, this.dataGridViewTextBoxColumn_Breakpoints_HitCount} ); this.dataGridView_Breakpoints.Location = new System.Drawing.Point( 0, 28 ); this.dataGridView_Breakpoints.Name = "dataGridView_Breakpoints"; this.dataGridView_Breakpoints.ReadOnly = true; this.dataGridView_Breakpoints.RowHeadersWidth = 24; this.dataGridView_Breakpoints.Size = new System.Drawing.Size( 572, 254 ); this.dataGridView_Breakpoints.TabIndex = 2; this.dataGridView_Breakpoints.CellClick += new System.Windows.Forms.DataGridViewCellEventHandler( this.dataGridView_Breakpoints_CellContentClick ); this.dataGridView_Breakpoints.CellContentDoubleClick += new System.Windows.Forms.DataGridViewCellEventHandler( this.dataGridView_Breakpoints_CellContentDoubleClick ); this.dataGridView_Breakpoints.CellContentClick += new System.Windows.Forms.DataGridViewCellEventHandler( this.dataGridView_Breakpoints_CellContentClick ); // // toolStrip1 // this.toolStrip1.GripStyle = System.Windows.Forms.ToolStripGripStyle.Hidden; this.toolStrip1.Items.AddRange( new System.Windows.Forms.ToolStripItem[] { this.toolStripButton_DeleteBreakpoint, this.toolStripSeparator1, this.toolStripButton_DeleteAllBreakpoints, this.toolStripButton_ToggleAllBreakpoints} ); this.toolStrip1.Location = new System.Drawing.Point( 0, 0 ); this.toolStrip1.Name = "toolStrip1"; this.toolStrip1.Size = new System.Drawing.Size( 572, 25 ); this.toolStrip1.TabIndex = 3; this.toolStrip1.Text = "toolStrip1"; // // toolStripButton_DeleteBreakpoint // this.toolStripButton_DeleteBreakpoint.DisplayStyle = System.Windows.Forms.ToolStripItemDisplayStyle.Image; this.toolStripButton_DeleteBreakpoint.Enabled = false; this.toolStripButton_DeleteBreakpoint.Image = ((System.Drawing.Image)(resources.GetObject( "toolStripButton_DeleteBreakpoint.Image" ))); this.toolStripButton_DeleteBreakpoint.ImageTransparentColor = System.Drawing.Color.Magenta; this.toolStripButton_DeleteBreakpoint.Name = "toolStripButton_DeleteBreakpoint"; this.toolStripButton_DeleteBreakpoint.Size = new System.Drawing.Size( 23, 22 ); this.toolStripButton_DeleteBreakpoint.ToolTipText = "Delete Breakpoint"; this.toolStripButton_DeleteBreakpoint.Click += new System.EventHandler( this.toolStripButton_DeleteBreakpoint_Click ); // // toolStripSeparator1 // this.toolStripSeparator1.Name = "toolStripSeparator1"; this.toolStripSeparator1.Size = new System.Drawing.Size( 6, 25 ); // // toolStripButton_DeleteAllBreakpoints // this.toolStripButton_DeleteAllBreakpoints.DisplayStyle = System.Windows.Forms.ToolStripItemDisplayStyle.Image; this.toolStripButton_DeleteAllBreakpoints.Enabled = false; this.toolStripButton_DeleteAllBreakpoints.Image = ((System.Drawing.Image)(resources.GetObject( "toolStripButton_DeleteAllBreakpoints.Image" ))); this.toolStripButton_DeleteAllBreakpoints.ImageTransparentColor = System.Drawing.Color.Magenta; this.toolStripButton_DeleteAllBreakpoints.Name = "toolStripButton_DeleteAllBreakpoints"; this.toolStripButton_DeleteAllBreakpoints.Size = new System.Drawing.Size( 23, 22 ); this.toolStripButton_DeleteAllBreakpoints.ToolTipText = "Delete All Breakpoints"; this.toolStripButton_DeleteAllBreakpoints.Click += new System.EventHandler( this.toolStripButton_DeleteAllBreakpoints_Click ); // // toolStripButton_ToggleAllBreakpoints // this.toolStripButton_ToggleAllBreakpoints.DisplayStyle = System.Windows.Forms.ToolStripItemDisplayStyle.Image; this.toolStripButton_ToggleAllBreakpoints.Enabled = false; this.toolStripButton_ToggleAllBreakpoints.Image = ((System.Drawing.Image)(resources.GetObject( "toolStripButton_ToggleAllBreakpoints.Image" ))); this.toolStripButton_ToggleAllBreakpoints.ImageTransparentColor = System.Drawing.Color.Magenta; this.toolStripButton_ToggleAllBreakpoints.Name = "toolStripButton_ToggleAllBreakpoints"; this.toolStripButton_ToggleAllBreakpoints.Size = new System.Drawing.Size( 23, 22 ); this.toolStripButton_ToggleAllBreakpoints.ToolTipText = "Toggle All Breakpoints"; this.toolStripButton_ToggleAllBreakpoints.Click += new System.EventHandler( this.toolStripButton_ToggleAllBreakpoints_Click ); // // panel1 // this.panel1.Controls.Add( this.toolStrip1 ); this.panel1.Controls.Add( this.dataGridView_Breakpoints ); this.panel1.Dock = System.Windows.Forms.DockStyle.Fill; this.panel1.Location = new System.Drawing.Point( 0, 187 ); this.panel1.Name = "panel1"; this.panel1.Size = new System.Drawing.Size( 572, 282 ); this.panel1.TabIndex = 4; // // dataGridViewImageColumn_Breakpoints_Status // this.dataGridViewImageColumn_Breakpoints_Status.HeaderText = ""; this.dataGridViewImageColumn_Breakpoints_Status.Name = "dataGridViewImageColumn_Breakpoints_Status"; this.dataGridViewImageColumn_Breakpoints_Status.ReadOnly = true; this.dataGridViewImageColumn_Breakpoints_Status.Resizable = System.Windows.Forms.DataGridViewTriState.False; this.dataGridViewImageColumn_Breakpoints_Status.Width = 20; // // dataGridViewTextBoxColumn_Breakpoints_Method // this.dataGridViewTextBoxColumn_Breakpoints_Method.HeaderText = "Method"; this.dataGridViewTextBoxColumn_Breakpoints_Method.Name = "dataGridViewTextBoxColumn_Breakpoints_Method"; this.dataGridViewTextBoxColumn_Breakpoints_Method.ReadOnly = true; this.dataGridViewTextBoxColumn_Breakpoints_Method.SortMode = System.Windows.Forms.DataGridViewColumnSortMode.NotSortable; // // dataGridViewTextBoxColumn_Breakpoints_Condition // this.dataGridViewTextBoxColumn_Breakpoints_Condition.HeaderText = "Condition"; this.dataGridViewTextBoxColumn_Breakpoints_Condition.Name = "dataGridViewTextBoxColumn_Breakpoints_Condition"; this.dataGridViewTextBoxColumn_Breakpoints_Condition.ReadOnly = true; this.dataGridViewTextBoxColumn_Breakpoints_Condition.SortMode = System.Windows.Forms.DataGridViewColumnSortMode.NotSortable; // // dataGridViewTextBoxColumn_Breakpoints_HitCount // this.dataGridViewTextBoxColumn_Breakpoints_HitCount.HeaderText = "Hit Count"; this.dataGridViewTextBoxColumn_Breakpoints_HitCount.Name = "dataGridViewTextBoxColumn_Breakpoints_HitCount"; this.dataGridViewTextBoxColumn_Breakpoints_HitCount.ReadOnly = true; this.dataGridViewTextBoxColumn_Breakpoints_HitCount.SortMode = System.Windows.Forms.DataGridViewColumnSortMode.NotSortable; // // BreakpointsView // this.AutoScaleDimensions = new System.Drawing.SizeF( 6F, 13F ); this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font; this.Controls.Add( this.panel1 ); this.Controls.Add( this.panel_Breakpoints_Search ); this.Name = "BreakpointsView"; this.Size = new System.Drawing.Size( 572, 469 ); this.panel_Breakpoints_Search.ResumeLayout( false ); this.panel_Breakpoints_Search.PerformLayout(); ((System.ComponentModel.ISupportInitialize)(this.dataGridView_Breakpoints)).EndInit(); this.toolStrip1.ResumeLayout( false ); this.toolStrip1.PerformLayout(); this.panel1.ResumeLayout( false ); this.panel1.PerformLayout(); this.ResumeLayout( false ); } #endregion private System.Windows.Forms.Panel panel_Breakpoints_Search; private System.Windows.Forms.ListBox listBox_Breakpoint_SearchResults; private System.Windows.Forms.Label label_Breakpoint_Search; private System.Windows.Forms.TextBox textBox_Breakpoint_Search; private System.Windows.Forms.DataGridView dataGridView_Breakpoints; private System.Windows.Forms.ToolStrip toolStrip1; private System.Windows.Forms.ToolStripButton toolStripButton_DeleteBreakpoint; private System.Windows.Forms.ToolStripSeparator toolStripSeparator1; private System.Windows.Forms.ToolStripButton toolStripButton_DeleteAllBreakpoints; private System.Windows.Forms.ToolStripButton toolStripButton_ToggleAllBreakpoints; private System.Windows.Forms.Panel panel1; private System.Windows.Forms.DataGridViewImageColumn dataGridViewImageColumn_Breakpoints_Status; private System.Windows.Forms.DataGridViewTextBoxColumn dataGridViewTextBoxColumn_Breakpoints_Method; private System.Windows.Forms.DataGridViewTextBoxColumn dataGridViewTextBoxColumn_Breakpoints_Condition; private System.Windows.Forms.DataGridViewTextBoxColumn dataGridViewTextBoxColumn_Breakpoints_HitCount; } } ================================================ FILE: Zelig/Zelig/DebugTime/Debugger/UserControls/BreakpointsView.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // namespace Microsoft.Zelig.Debugger.ArmProcessor { using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Text; using System.IO; using System.Windows.Forms; using System.Threading; using IR = Microsoft.Zelig.CodeGeneration.IR; using RT = Microsoft.Zelig.Runtime; using TS = Microsoft.Zelig.Runtime.TypeSystem; using Hst = Microsoft.Zelig.Emulation.Hosting; public partial class BreakpointsView : UserControl { private int c_panel_Breakpoints_Search__Collapsed = 30; private int c_panel_Breakpoints_Search__Expanded = 187; // // State // DebuggerMainForm m_owner; int m_version; List< Emulation.Hosting.Breakpoint > m_breakpoints; Emulation.Hosting.Breakpoint m_selectedBreakpoint; Icon m_icon_Breakpoint = Properties.Resources.Breakpoint; Icon m_icon_BreakpointDisabled = Properties.Resources.BreakpointDisabled; // // Constructor Methods // public BreakpointsView() { InitializeComponent(); //--// m_breakpoints = new List< Emulation.Hosting.Breakpoint >(); DebuggerMainForm.SetPanelHeight( panel_Breakpoints_Search, c_panel_Breakpoints_Search__Collapsed ); } // // Access Methods // public void Link( DebuggerMainForm owner ) { m_owner = owner; m_owner.HostingSite.NotifyOnExecutionStateChange += delegate( Hst.Forms.HostingSite host , Hst.Forms.HostingSite.ExecutionState oldState , Hst.Forms.HostingSite.ExecutionState newState ) { UpdateUI(); return Hst.Forms.HostingSite.NotificationResponse.DoNothing; }; m_owner.HostingSite.NotifyOnVisualizationEvent += delegate( Hst.Forms.HostingSite host , Hst.Forms.HostingSite.VisualizationEvent e ) { if(e == Hst.Forms.HostingSite.VisualizationEvent.BreakpointsChange) { UpdateUI(); } return Hst.Forms.HostingSite.NotificationResponse.DoNothing; }; } public void UpdateUI() { ProcessorHost svc; m_owner.Host.GetHostingService( out svc ); ImageInformation imageInformation = m_owner.ImageInformation; StackFrame currentStackFrame = m_owner.SelectedStackFrame; Emulation.Hosting.Breakpoint[] array = svc.Breakpoints; toolStripButton_DeleteBreakpoint .Enabled = m_selectedBreakpoint != null; toolStripButton_DeleteAllBreakpoints.Enabled = array.Length > 0; toolStripButton_ToggleAllBreakpoints.Enabled = array.Length > 0; //--// dataGridView_Breakpoints.SuspendLayout(); DataGridViewRowCollection rows = dataGridView_Breakpoints.Rows; dataGridView_Breakpoints.Enabled = currentStackFrame != null; if(currentStackFrame == null) { m_version = -1; DebuggerMainForm.GrayOutRowsInDataGridView( rows ); } else { bool fRebuild = (m_version != m_owner.VersionBreakpoints); if(fRebuild) { m_version = m_owner.VersionBreakpoints; rows .Clear(); m_breakpoints.Clear(); } int pos = 0; foreach(Emulation.Hosting.Breakpoint bp in array) { Icon icon; if(bp.ShowInUI == false) { continue; } if(bp.IsActive) { icon = m_icon_Breakpoint; } else { icon = m_icon_BreakpointDisabled; } if(fRebuild) { IR.ImageBuilders.SequentialRegion reg; uint offset; Debugging.DebugInfo di; string location; imageInformation.LocateFirstSourceCode( bp.Address, out reg, out offset, out di ); if(di != null) { location = string.Format( "{0}, line {1} character {2}", Path.GetFileName( di.SrcFileName ), di.BeginLineNumber, di.BeginColumn ); } else if(reg != null && reg.Context is IR.BasicBlock) { location = string.Format( "{0}, offset {1}", reg.Context, offset ); } else { location = string.Format( "Address 0x{0:X8}", bp.Address ); } rows.Add( icon, location, "(no condition)", bp.HitCount ); m_breakpoints.Add( bp ); } else { rows[pos].Cells[0].Value = icon; } pos++; } } dataGridView_Breakpoints.ResumeLayout(); } public void Set( string breakpoint ) { if(CreateBreakpoint( breakpoint ) == false) { ListMatches( breakpoint ); } } //--// private void SelectBreakpoint( int index ) { if(index >= 0 && index < m_breakpoints.Count) { m_selectedBreakpoint = m_breakpoints[index]; } else { m_selectedBreakpoint = null; } } private void ListMatches( string txt ) { listBox_Breakpoint_SearchResults.BeginUpdate(); ListBox.ObjectCollection col = listBox_Breakpoint_SearchResults.Items; col.Clear(); uint res; if(txt.StartsWith( "0x" ) && uint.TryParse( txt.Substring( 2 ), System.Globalization.NumberStyles.AllowHexSpecifier, null, out res )) { col.Add( txt ); } else { ImageInformation imageInformation = m_owner.ImageInformation; txt = txt.ToUpper(); if(imageInformation != null && txt.Length >= 2) { foreach(string methodName in imageInformation.NameToCfg.Keys) { if(methodName.ToUpper().Contains( txt )) { col.Add( methodName ); } } foreach(string fileName in imageInformation.SourceCodeFiles) { if(fileName.ToUpper().Contains( txt )) { col.Add( fileName ); } } } } if(col.Count > 0) { DebuggerMainForm.SetPanelHeight( panel_Breakpoints_Search, c_panel_Breakpoints_Search__Expanded ); } else { DebuggerMainForm.SetPanelHeight( panel_Breakpoints_Search, c_panel_Breakpoints_Search__Collapsed ); } listBox_Breakpoint_SearchResults.EndUpdate(); } private bool CreateBreakpoint( string txt ) { ImageInformation imageInformation = m_owner.ImageInformation; if(imageInformation != null) { if(txt != null) { if(imageInformation.NameToCfg.ContainsKey( txt )) { IR.ImageBuilders.SequentialRegion selectedRegion = null; foreach(IR.ControlFlowGraphStateForCodeTransformation cfg in imageInformation.NameToCfg[txt]) { IR.ImageBuilders.SequentialRegion reg = imageInformation.ImageBuilder.GetAssociatedRegion( cfg ); if(reg != null) { if(selectedRegion != null) { // // TODO: Select one among multiple options. // } selectedRegion = reg; } } if(selectedRegion != null) { m_owner.Action_SetBreakpoint( selectedRegion.ExternalAddress, null ); return true; } } uint address; if(txt.StartsWith( "0x" ) && uint.TryParse( txt.Substring( 2 ), System.Globalization.NumberStyles.AllowHexSpecifier, null, out address )) { m_owner.Action_SetBreakpoint( address, null ); return true; } } } return false; } // // Access Methods // // // Event Methods // private void textBox_Breakpoint_Search_TextChanged( object sender , EventArgs e ) { ListMatches( textBox_Breakpoint_Search.Text ); } private void listBox_Breakpoint_SearchResults_Click( object sender, EventArgs e ) { ImageInformation imageInformation = m_owner.ImageInformation; if(imageInformation != null) { string txt = (string)listBox_Breakpoint_SearchResults.SelectedItem; if(txt != null) { if(imageInformation.NameToCfg.ContainsKey( txt )) { foreach(IR.ControlFlowGraphStateForCodeTransformation cfg in imageInformation.NameToCfg[txt]) { IR.ImageBuilders.SequentialRegion reg = imageInformation.ImageBuilder.GetAssociatedRegion( cfg ); if(reg != null) { IR.ImageBuilders.SequentialRegion reg2; uint offset2; Debugging.DebugInfo di; if(m_owner.ImageInformation.LocateFirstSourceCode( reg.ExternalAddress, out reg2, out offset2, out di )) { m_owner.VisualizeDebugInfo( di ); return; } } } } if(imageInformation.SourceCodeFiles.Contains( txt )) { m_owner.VisualizeFile( txt ); return; } } } } private void listBox_Breakpoint_SearchResults_DoubleClick( object sender, EventArgs e ) { CreateBreakpoint( (string)listBox_Breakpoint_SearchResults.SelectedItem ); } private void dataGridView_Breakpoints_CellContentClick( object sender, DataGridViewCellEventArgs e ) { SelectBreakpoint( e.RowIndex ); UpdateUI(); } private void dataGridView_Breakpoints_CellContentDoubleClick( object sender, DataGridViewCellEventArgs e ) { SelectBreakpoint( e.RowIndex ); if(m_selectedBreakpoint != null) { if(e.ColumnIndex == 0) { m_selectedBreakpoint.IsActive = !m_selectedBreakpoint.IsActive; } else { IR.ImageBuilders.SequentialRegion reg; uint offset; Debugging.DebugInfo di; if(m_owner.ImageInformation.LocateFirstSourceCode( m_selectedBreakpoint.Address, out reg, out offset, out di )) { m_owner.VisualizeDebugInfo( di ); } } } m_owner.Action_RefreshBreakpoints(); } private void toolStripButton_DeleteBreakpoint_Click( object sender, EventArgs e ) { m_owner.Action_RemoveBreakpoint( m_selectedBreakpoint ); } private void toolStripButton_DeleteAllBreakpoints_Click( object sender, EventArgs e ) { m_owner.Action_DeleteAllBreakpoints(); } private void toolStripButton_ToggleAllBreakpoints_Click( object sender, EventArgs e ) { ProcessorHost svc; m_owner.Host.GetHostingService( out svc ); foreach(Emulation.Hosting.Breakpoint bp in svc.Breakpoints) { bp.IsActive = !bp.IsActive; } m_owner.Action_RefreshBreakpoints(); } } } ================================================ FILE: Zelig/Zelig/DebugTime/Debugger/UserControls/BreakpointsView.resx ================================================ text/microsoft-resx 2.0 System.Resources.ResXResourceReader, System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 System.Resources.ResXResourceWriter, System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 True True True True 17, 17 iVBORw0KGgoAAAANSUhEUgAAABAAAAAQCAYAAAAf8/9hAAAAAXNSR0IArs4c6QAAAARnQU1BAACxjwv8 YQUAAAAgY0hSTQAAeiYAAICEAAD6AAAAgOgAAHUwAADqYAAAOpgAABdwnLpRPAAAAQVJREFUOE+tkr0N g0AMRmEJKqrrqElDS095NR0ZgQ0YAYkuRZQmHRNQR8yQGbKBw7vIEQm/kXKShfDZz9/Z9r3hNH0v9+vV M8Z6x+PBx/fTOZ3OkqapZFkmTdPLWvLl9pC6rj9jABRFIUmSONAkYCCSCNxaK2VZfgL0EggArKoqwY8a viTh56v+WaVUH0O6rnOwXclKJCnPc/ckNf5XK3/LadtW4jh+q/kpmbEiGQCmzd01Wk2Oosg9QzsPiF6s QjTZGOPGhWw1uo8SYmYhBDJGKiN/HKgQFm2yA0pjmcIwdIDxDoyrAV1UATkIgtc6L8kcaMBn152x0TSU bI1s637XtP4W9ARGR/xhacsPygAAAABJRU5ErkJggg== iVBORw0KGgoAAAANSUhEUgAAABAAAAAQCAYAAAAf8/9hAAAAAXNSR0IArs4c6QAAAARnQU1BAACxjwv8 YQUAAAAgY0hSTQAAeiYAAICEAAD6AAAAgOgAAHUwAADqYAAAOpgAABdwnLpRPAAAASJJREFUOE+Nk8sR gzAMROGePlKAG6AaV5FDTvTgG4dUQAUU4AbSB3dFu5Yc85mEzGgwsfS0Wpu+2/1yzrKua3d7v+vOer93 wzD0+9zD+7IsklNqIkqOUZIG9n4C0BnFgsj2JKxAGAY/hXn3ClDIVo2+GwiKpum1VVSSY1FgcaqIkCAp 7CAE6KY8npvOrSKsfaQUFKL51Zd5nr+z+swA7hTVMRQQNSoAHoCY9U9I9ERXxKeD0d0B2NBKwSnAGEoj pHF/s9Y9y+EIBFBqmacdhaCqyNZN93oSnNMMdCBMbRW5Mpc+juPxGAnB/Frs5kARpMIwxOkdQHLpHEQ0 CaC/994TYB47WyHvgpl4CcLbFrpSZNJpnIq6BoACd1vXKOJ3cXGMD1R5zv8ih94hAAAAAElFTkSuQmCC iVBORw0KGgoAAAANSUhEUgAAABAAAAAQCAYAAAAf8/9hAAAAAXNSR0IArs4c6QAAAARnQU1BAACxjwv8 YQUAAAAgY0hSTQAAeiYAAICEAAD6AAAAgOgAAHUwAADqYAAAOpgAABdwnLpRPAAAAVVJREFUOE+NkzFu g0AQRSdy4TM41+AsXGF7VzQpqDgC0nYufAJOQJUGIqUKaWjj0lUKF2gzf2YHWOxIRhrNLuy8/3d2eWma JhA/l8srHQ4/kvf7b7rdfmmaJvrc7fCZ6EOTDnVyPh6JvO8DIAiMT6dzqOtawnmv4ZbInAuIcRwDHtoW A9BzEQBVVYWiKGbAtlgAUDVlFM7BKj2H53BRda0s8gBA0VSZFJgQJAtMIQYC/Pr1brUKgNU7AEMSN4BF kGQImANrGNRMWdWjk7UjgWSyrbZt1QG6jGaBHN7KRHneUoTYlnymkDtAYhMLzIU11/oBAIcC+IzLshRi zy9h0UDmSLL1IBa7NUAvCh9Z/Ii8daNzfm9r5i3EW4YzzvNcLpCBFkdaaMVQX5r4zyXBKawd2RjFEJmP 8dH1tI9d10lvUIzC9fElAPsxkiv25ISGYXhy6eNlf75E3BOpDWlzAAAAAElFTkSuQmCC ================================================ FILE: Zelig/Zelig/DebugTime/Debugger/UserControls/CodeView.Designer.cs ================================================ namespace Microsoft.Zelig.Debugger.ArmProcessor { partial class CodeView { /// /// Required designer variable. /// private System.ComponentModel.IContainer components = null; /// /// Clean up any resources being used. /// /// true if managed resources should be disposed; otherwise, false. protected override void Dispose( bool disposing ) { if(disposing && (components != null)) { components.Dispose(); } base.Dispose( disposing ); } #region Component Designer generated code /// /// Required method for Designer support - do not modify /// the contents of this method with the code editor. /// private void InitializeComponent() { this.SuspendLayout(); // // CodeView // this.AutoScaleDimensions = new System.Drawing.SizeF( 7F, 15F ); this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font; this.AutoScroll = true; this.DoubleBuffered = true; this.Font = new System.Drawing.Font( "Courier New", 9F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)) ); this.Name = "CodeView"; this.Size = new System.Drawing.Size( 458, 403 ); this.MouseDown += new System.Windows.Forms.MouseEventHandler( this.CodeView_MouseDown ); this.MouseMove += new System.Windows.Forms.MouseEventHandler( this.CodeView_MouseMove ); this.MouseWheel += new System.Windows.Forms.MouseEventHandler( this.CodeView_MouseMove ); this.MouseUp += new System.Windows.Forms.MouseEventHandler( this.CodeView_MouseUp ); this.ResumeLayout( false ); } #endregion } } ================================================ FILE: Zelig/Zelig/DebugTime/Debugger/UserControls/CodeView.Parsers.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // namespace Microsoft.Zelig.Debugger.ArmProcessor { using System; using System.Collections.Generic; using System.ComponentModel; using System.Drawing; using System.Data; using System.Text; using System.Windows.Forms; using IR = Microsoft.Zelig.CodeGeneration.IR; using System.IO; public partial class CodeView : UserControl { static string[] s_preprocessingDirectives = new string[] { "#if" , "#else" , "#elif" , "#endif" , "#define" , "#undef" , "#warning" , "#error" , "#line" , "#region" , "#endregion", "#pragma" , }; // // Helper Methods // public void RefreshVisualTree() { if(m_activeVisualTree != null) { RectangleF bounds = m_activeVisualTree.VisualTreeRoot.RelativeBounds; this.AutoScrollMinSize = new Size( (int)bounds.Right, (int)bounds.Bottom ); } else { this.AutoScrollMinSize = new Size( 0, 0 ); } m_fInvalidated = true; this.Invalidate(); } public void InstallVisualTree( VisualTreeInfo vti , VisualItem bringIntoView ) { if(m_activeVisualTree != null) { Point pt = this.AutoScrollPosition; // // Maybe there's a bug in the WinForms framework, because AutoScrollPosition returns the mirrored point. // m_activeVisualTree.ScrollPosition.X = -pt.X; m_activeVisualTree.ScrollPosition.Y = -pt.Y; } m_activeVisualTree = vti; RefreshVisualTree(); if(vti != null) { vti.ScrollToItem( bringIntoView, this.DisplayRectangle, new Rectangle( 0, 0, this.Width, this.Height ) ); this.AutoScrollPosition = vti.ScrollPosition; } } //--// public VisualTreeInfo GetVisualTree( string file ) { VisualTreeInfo vti; string key = file.ToUpper(); m_visualTrees.TryGetValue( key, out vti ); return vti; } public VisualTreeInfo CreateEmptyVisualTree( string displayName ) { VisualTreeInfo vti; string key = displayName; if(m_visualTrees.TryGetValue( key, out vti ) == false) { ContainerVisualItem topElement = new ContainerVisualItem( null ); vti = new VisualTreeInfo( displayName, null, topElement ); m_visualTrees[key] = vti; } return vti; } public VisualTreeInfo CreateVisualTree( ImageInformation imageInformation , string displayName , string file ) { VisualTreeInfo vti; string key = file.ToUpper(); if(m_visualTrees.TryGetValue( key, out vti ) == false) { try { IR.SourceCodeTracker.SourceCode sc; if(imageInformation != null && imageInformation.ImageBuilder != null) { sc = imageInformation.ImageBuilder.SourceCodeTracker.GetSourceCode( file ); } else { sc = null; } if(sc == null) { if(!System.IO.File.Exists( file )) { string fileName = Path.GetFileName(file); foreach(string path in m_codeSearchPaths) { string tmp = Path.Combine( path, fileName ); if(File.Exists( tmp )) { file = tmp; break; } } } if(System.IO.File.Exists( file )) { sc = new IR.SourceCodeTracker.SourceCode( file ); } } if(sc != null) { ContainerVisualItem topElement = TokenizeCSharpCode( sc ); vti = new VisualTreeInfo( displayName, sc, topElement ); m_visualTrees[key] = vti; } } catch { vti = null; } } return vti; } private ContainerVisualItem TokenizeCSharpCode( IR.SourceCodeTracker.SourceCode sc ) { ContainerVisualItem topElement = new ContainerVisualItem( sc ); if(sc != null) { Microsoft.CSharp.Token[] tokens = sc.Tokens; Microsoft.CSharp.Token nextToken = null; int idxToken = 0; int lines = sc.Count; ContainerVisualItem lineItem = null; Brush brushComment = new SolidBrush( Color.Green ); Brush brushKeyword = new SolidBrush( Color.Blue ); Brush brushOther = new SolidBrush( Color.Black ); PointF ptLine = new PointF( 0, 0 ); GraphicsContext ctx = this.CtxForLayout; float stepX = ctx.CharSize ( null ); float stepY = ctx.CharHeight( null ); for(int line = 0; line < lines; line++) { string text = sc[line+1]; PointF ptWord = new PointF( 0, 0 ); int pos = 0; Brush lastBrush = null; int lastPos = 0; int lastPosEnd = 0; while(pos < text.Length) { int posEnd = text.Length; Brush brush = brushOther; while(true) { if(nextToken == null) { if(idxToken < tokens.Length) { nextToken = tokens[idxToken++]; } else { break; } } if(nextToken.Position.Line < line) { nextToken = null; continue; } bool fGotBrush; if(pos == 0 && text[0] == '#') { UpdateEndPosOnMatch( text, ref posEnd, s_preprocessingDirectives ); brush = brushKeyword; fGotBrush = true; } else { fGotBrush = false; } if(nextToken.Position.Line > line) { break; } if(pos < nextToken.Position.Column) { posEnd = nextToken.Position.Column; break; } if(nextToken.Type == Microsoft.CSharp.TokenType.Comment) { brush = brushComment; } else if(Microsoft.CSharp.Token.IsKeyword( nextToken.Type )) { brush = brushKeyword; } else if(fGotBrush == false) { brush = brushOther; } nextToken = null; } if(lastBrush != null) { if(lastBrush == brush) { lastPosEnd = posEnd; pos = posEnd; continue; } EmitWordGroup( ctx, topElement, ref lineItem, ref ptLine, stepX, line, lastPos, lastPosEnd, lastBrush, text ); lastBrush = null; } lastPos = pos; lastPosEnd = posEnd; lastBrush = brush; pos = posEnd; } if(lastBrush != null) { EmitWordGroup( ctx, topElement, ref lineItem, ref ptLine, stepX, line, lastPos, lastPosEnd, lastBrush, text ); } lineItem = null; ptLine.Y += stepY; } } return topElement; } private static void UpdateEndPosOnMatch( string text , ref int posEnd , string[] preprocessingDirectives ) { foreach(string preprocessingDirective in preprocessingDirectives) { if(text.StartsWith( preprocessingDirective )) { posEnd = preprocessingDirective.Length; break; } } } private void EmitWordGroup( GraphicsContext ctx , ContainerVisualItem topElement , ref ContainerVisualItem lineItem , ref PointF ptLine , float stepX , int line , int pos , int posEnd , Brush brush , string text ) { if(lineItem == null) { lineItem = new ContainerVisualItem( Debugging.DebugInfo.CreateMarkerForLine( null, null, line + 1 ) ); lineItem.RelativeOrigin = ptLine; topElement.Add( lineItem ); } //--// while(pos < posEnd) { if(text[pos] == ' ') { pos++; continue; } int posEnd2 = text.IndexOf( ' ', pos ); if(posEnd2 < 0) { posEnd2 = posEnd; } TextVisualItem item = new TextVisualItem( new Debugging.DebugInfo( null, line + 1, pos + 1, line + 1, posEnd2 + 1 ), text.Substring( pos, posEnd2 - pos ) ); item.TextBrush = brush; PointF ptWord = new PointF( pos * stepX, 0 ); BaseTextVisualItem.PlaceInALine( ctx, item, ref ptWord, 0, 0 ); lineItem.Add( item ); pos = posEnd2; } } } } ================================================ FILE: Zelig/Zelig/DebugTime/Debugger/UserControls/CodeView.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // namespace Microsoft.Zelig.Debugger.ArmProcessor { using System; using System.Collections.Generic; using System.ComponentModel; using System.Drawing; using System.Data; using System.Text; using System.Windows.Forms; using IR = Microsoft.Zelig.CodeGeneration.IR; using System.Collections.Specialized; public partial class CodeView : UserControl { public delegate void HitCallback( CodeView owner, VisualItem origin, PointF relPos, MouseEventArgs e, bool fDown, bool fUp ); public delegate bool EnumerationCallback( VisualItem item ); // // State // HitCallback m_fallbackHitSink; HitCallback m_defaultHitSink; Rectangle m_lastDisplayRect; Bitmap m_lastCachedDisplay; bool m_fInvalidated; List m_codeSearchPaths; GrowOnlyHashTable< string, VisualTreeInfo > m_visualTrees; VisualTreeInfo m_activeVisualTree; // // Constructor Methods // public CodeView() { InitializeComponent(); //--// m_visualTrees = HashTableFactory.New< string, VisualTreeInfo >(); m_activeVisualTree = null; m_codeSearchPaths = new List(); try { NameValueCollection nvc = System.Configuration.ConfigurationManager.AppSettings; foreach(string key in nvc.AllKeys) { if(key == "SourceCodeSearchPath") { string paths = Environment.ExpandEnvironmentVariables(nvc[key]); m_codeSearchPaths.AddRange( paths.Split( ';' ) ); break; } } } catch { } } // // Helper Methods // protected override void OnPaint( PaintEventArgs pe ) { if(m_activeVisualTree != null) { Rectangle currentDisplayRect = this.DisplayRectangle; if(m_lastDisplayRect != currentDisplayRect) { m_lastDisplayRect = currentDisplayRect; m_fInvalidated = true; } Bitmap bm = m_lastCachedDisplay; if(bm == null || bm.Width != this.Width || bm.Height != this.Height ) { bm = new Bitmap( this.Width, this.Height ); m_lastCachedDisplay = bm; m_fInvalidated = true; } if(m_fInvalidated) { GraphicsContext ctx = new GraphicsContext( this.Font, bm ); ctx.Gfx.Clear( Color.White ); m_activeVisualTree.Draw( ctx, new PointF( m_lastDisplayRect.X, m_lastDisplayRect.Y ) ); m_fInvalidated = false; } pe.Graphics.DrawImage( bm, 0, 0 ); } } protected override void OnPaintBackground( PaintEventArgs pevent ) { if(m_activeVisualTree == null) { base.OnPaintBackground( pevent ); } } //--// private void Notify( MouseEventArgs e , bool fDown , bool fUp ) { VisualTreeInfo vti = m_activeVisualTree; if(vti != null) { PointF testPt; PointF hitPt; VisualItem hit; Rectangle currentDisplayRect = this.DisplayRectangle; testPt = new PointF( e.X - currentDisplayRect.Left, e.Y - currentDisplayRect.Top ); hit = vti.VisualTreeRoot.Contains( testPt, true, out hitPt ); if(hit == null) { //// hit = vti.VisualTreeRoot.Contains( testPt, false, out hitPt ); //// if(hit == null) { float y; hit = vti.VisualTreeRoot.ContainsVertically( testPt.Y, out y ); hitPt.X = -1.0f; hitPt.Y = y; } } HitCallback hitSink = null; if(hit != null) { for(VisualItem item = hit; item != null; item = item.Parent) { if(item.HitSink != null) { hitSink = item.HitSink; break; } } if(hitSink == null) { hitSink = m_defaultHitSink; } } else { hitPt = new PointF( e.X - currentDisplayRect.Left, e.Y - currentDisplayRect.Top ); } if(hitSink == null) { hitSink = m_fallbackHitSink; } if(hitSink != null) { hitSink( this, hit, hitPt, e, fDown, fUp ); } } } //--// // // Access Methods // public GraphicsContext CtxForLayout { get { return new GraphicsContext( this.Font, null ); } } public HitCallback FallbackHitSink { get { return m_fallbackHitSink; } set { m_fallbackHitSink = value; } } public HitCallback DefaultHitSink { get { return m_defaultHitSink; } set { m_defaultHitSink = value; } } public GrowOnlyHashTable< string, VisualTreeInfo > VisualTrees { get { return m_visualTrees; } } public VisualTreeInfo ActiveVisualTree { get { return m_activeVisualTree; } } // // Event Methods // private void CodeView_MouseDown( object sender, MouseEventArgs e ) { Notify( e, true, false ); } private void CodeView_MouseMove( object sender, MouseEventArgs e ) { Notify( e, false, false ); } private void CodeView_MouseUp( object sender, MouseEventArgs e ) { Notify( e, false, true ); } } } ================================================ FILE: Zelig/Zelig/DebugTime/Debugger/UserControls/CodeView.resx ================================================ text/microsoft-resx 2.0 System.Resources.ResXResourceReader, System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 System.Resources.ResXResourceWriter, System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 ================================================ FILE: Zelig/Zelig/DebugTime/Debugger/UserControls/LocalsView.Designer.cs ================================================ namespace Microsoft.Zelig.Debugger.ArmProcessor { partial class LocalsView { /// /// Required designer variable. /// private System.ComponentModel.IContainer components = null; /// /// Clean up any resources being used. /// /// true if managed resources should be disposed; otherwise, false. protected override void Dispose( bool disposing ) { if(disposing && (components != null)) { components.Dispose(); } base.Dispose( disposing ); } #region Component Designer generated code /// /// Required method for Designer support - do not modify /// the contents of this method with the code editor. /// private void InitializeComponent() { this.components = new System.ComponentModel.Container(); this.contextMenuStrip1 = new System.Windows.Forms.ContextMenuStrip( this.components ); this.toolStripMenuItem_HexDisplay = new System.Windows.Forms.ToolStripMenuItem(); this.treeBasedGridView_Locals = new Microsoft.Zelig.Debugger.ArmProcessor.TreeBasedGridView(); this.contextMenuStrip1.SuspendLayout(); this.SuspendLayout(); // // contextMenuStrip1 // this.contextMenuStrip1.Items.AddRange( new System.Windows.Forms.ToolStripItem[] { this.toolStripMenuItem_HexDisplay} ); this.contextMenuStrip1.Name = "contextMenuStrip1"; this.contextMenuStrip1.Size = new System.Drawing.Size( 183, 48 ); // // toolStripMenuItem_HexDisplay // this.toolStripMenuItem_HexDisplay.Name = "toolStripMenuItem_HexDisplay"; this.toolStripMenuItem_HexDisplay.Size = new System.Drawing.Size( 182, 22 ); this.toolStripMenuItem_HexDisplay.Text = "Hexadecimal Display"; this.toolStripMenuItem_HexDisplay.CheckedChanged += new System.EventHandler( this.toolStripMenuItem_HexDisplay_CheckedChanged ); this.toolStripMenuItem_HexDisplay.Click += new System.EventHandler( this.toolStripMenuItem_HexDisplay_Click ); // // treeBasedGridView_Locals // this.treeBasedGridView_Locals.BorderStyle = System.Windows.Forms.BorderStyle.Fixed3D; this.treeBasedGridView_Locals.Dock = System.Windows.Forms.DockStyle.Fill; this.treeBasedGridView_Locals.Location = new System.Drawing.Point( 0, 0 ); this.treeBasedGridView_Locals.Name = "treeBasedGridView_Locals"; this.treeBasedGridView_Locals.Size = new System.Drawing.Size( 644, 520 ); this.treeBasedGridView_Locals.TabIndex = 0; this.treeBasedGridView_Locals.NodeMouseClick += new Microsoft.Zelig.Debugger.ArmProcessor.TreeBasedGridView.NodeMouseEventHandler( this.treeBasedGridView_Locals_CellMouseClick ); // // LocalsView // this.AutoScaleDimensions = new System.Drawing.SizeF( 6F, 13F ); this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font; this.Controls.Add( this.treeBasedGridView_Locals ); this.Name = "LocalsView"; this.Size = new System.Drawing.Size( 644, 520 ); this.contextMenuStrip1.ResumeLayout( false ); this.ResumeLayout( false ); } #endregion private TreeBasedGridView treeBasedGridView_Locals; private System.Windows.Forms.ContextMenuStrip contextMenuStrip1; private System.Windows.Forms.ToolStripMenuItem toolStripMenuItem_HexDisplay; } } ================================================ FILE: Zelig/Zelig/DebugTime/Debugger/UserControls/LocalsView.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // namespace Microsoft.Zelig.Debugger.ArmProcessor { using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Text; using System.IO; using System.Windows.Forms; using System.Threading; using EncDef = Microsoft.Zelig.TargetModel.ArmProcessor.EncodingDefinition; using InstructionSet = Microsoft.Zelig.TargetModel.ArmProcessor.InstructionSet; using IR = Microsoft.Zelig.CodeGeneration.IR; using RT = Microsoft.Zelig.Runtime; using TS = Microsoft.Zelig.Runtime.TypeSystem; using Hst = Microsoft.Zelig.Emulation.Hosting; public partial class LocalsView : UserControl { // // State // DebuggerMainForm m_owner; WatchHelper m_wh; // // Constructor Methods // public LocalsView() { InitializeComponent(); WatchHelper.SetColumns( treeBasedGridView_Locals ); } // // Helper Methods // public void Link( DebuggerMainForm owner ) { m_owner = owner; m_owner.HostingSite.NotifyOnExecutionStateChange += delegate( Hst.Forms.HostingSite host , Hst.Forms.HostingSite.ExecutionState oldState , Hst.Forms.HostingSite.ExecutionState newState ) { UpdateUI(); return Hst.Forms.HostingSite.NotificationResponse.DoNothing; }; m_owner.HostingSite.NotifyOnVisualizationEvent += delegate( Hst.Forms.HostingSite host , Hst.Forms.HostingSite.VisualizationEvent e ) { if(e == Hst.Forms.HostingSite.VisualizationEvent.NewStackFrame) { UpdateUI(); } return Hst.Forms.HostingSite.NotificationResponse.DoNothing; }; } private void UpdateUI() { ImageInformation imageInformation = m_owner.ImageInformation; StackFrame currentStackFrame = m_owner.SelectedStackFrame; //--// WatchHelper.Synchronize( ref m_wh, m_owner.MemoryDelta, treeBasedGridView_Locals.RootNode, true, true ); if(m_wh != null) { m_wh.HexadecimalDisplay = toolStripMenuItem_HexDisplay.Checked; } //--// treeBasedGridView_Locals.StartTreeUpdate(); treeBasedGridView_Locals.Enabled = currentStackFrame != null; if(currentStackFrame == null || m_owner.IsIdle == false) { //DebuggerMainForm.GrayOutRowsInDataGridView( treeBasedGridView_Locals.Rows ); } else { IR.LowLevelVariableExpression[] array = imageInformation.AliveVariables( currentStackFrame.Region, currentStackFrame.RegionOffset ); int lenArray = array.Length; var valArray = new AbstractValueHandle[lenArray]; var nameArray = new string [lenArray]; var peripherals = imageInformation.TypeSystem.MemoryMappedPeripherals; for(int i = 0; i < lenArray; i++) { IR.LowLevelVariableExpression var = array[i]; IR.VariableExpression varSrc = var.SourceVariable; if(varSrc != null && varSrc.DebugName != null) { nameArray[i] = varSrc.DebugName.Name; } if(var is IR.PhysicalRegisterExpression) { var varReg = var as IR.PhysicalRegisterExpression; var regDesc = varReg.RegisterDescriptor; valArray[i] = new RegisterValueHandle( currentStackFrame.RegisterContext.GetValue( regDesc ), varReg.Type, true ); if(nameArray[i] == null) { nameArray[i] = string.Format( "$Reg( {0} )", regDesc.Mnemonic ); } } else if(var is IR.StackLocationExpression) { var varStack = var as IR.StackLocationExpression; uint address = 0; switch(varStack.StackPlacement) { case IR.StackLocationExpression.Placement.In: { StackFrame sf = m_owner.SelectedThread.PreviousStackFrame; if(sf == null) { sf = currentStackFrame; } address = sf.StackPointer + (uint)varStack.Number * sizeof(uint); } break; case IR.StackLocationExpression.Placement.Local: case IR.StackLocationExpression.Placement.Out: { address = currentStackFrame.StackPointer + varStack.AllocationOffset; } break; } valArray[i] = new MemoryValueHandle( varStack.Type, peripherals.GetValue( varStack.Type ), null, true, m_wh.MemoryDelta, address ); if(nameArray[i] == null) { nameArray[i] = string.Format( "$Stack(0x{0:X8})", varStack.AllocationOffset ); } } else { array[i] = null; } } var lst = new List< WatchHelper.ItemDescriptor >(); for(int i = 0; i < lenArray; i++) { IR.LowLevelVariableExpression var = array[i]; if(var != null) { IR.VariableExpression varSrc = var.SourceVariable; string name = nameArray[i]; AbstractValueHandle valCtx = valArray[i]; TS.TypeRepresentation td; if(varSrc != null) { td = varSrc.Type; } else { td = var.Type; } if(td is TS.ValueTypeRepresentation) { if(varSrc != null) { var subLocations = BuildSubLocations( array, valArray, varSrc ); if(subLocations != null) { valCtx = new CompoundValueHandle( td, true, subLocations ); } } } var item = new WatchHelper.ItemDescriptor( m_wh, name, td, valCtx ); lst.Add( item ); } } m_wh.Update( lst, true ); } treeBasedGridView_Locals.EndTreeUpdate(); } private static CompoundValueHandle.Fragment[] BuildSubLocations( IR.LowLevelVariableExpression[] array , AbstractValueHandle[] valArray , IR.VariableExpression varSrc ) { CompoundValueHandle.Fragment[] res = null; for(int i = 0; i < array.Length; i++) { var ex = array[i]; if(ex != null && ex.SourceVariable == varSrc) { res = ArrayUtility.AppendToArray( res, new CompoundValueHandle.Fragment( valArray[i], (int)ex.SourceOffset ) ); array[i] = null; } } return res; } // // Access Methods // private void treeBasedGridView_Locals_CellMouseClick( object sender , TreeBasedGridView.NodeMouseEventArgs e ) { if(e.Button == MouseButtons.Right) { contextMenuStrip1.Show( treeBasedGridView_Locals, e.Location ); } } private void toolStripMenuItem_HexDisplay_CheckedChanged( object sender , EventArgs e ) { if(treeBasedGridView_Locals.Enabled) { m_wh.HexadecimalDisplay = toolStripMenuItem_HexDisplay.Checked; } } private void toolStripMenuItem_HexDisplay_Click( object sender , EventArgs e ) { toolStripMenuItem_HexDisplay.Checked = !toolStripMenuItem_HexDisplay.Checked; } // // Event Methods // } } ================================================ FILE: Zelig/Zelig/DebugTime/Debugger/UserControls/LocalsView.resx ================================================ text/microsoft-resx 2.0 System.Resources.ResXResourceReader, System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 System.Resources.ResXResourceWriter, System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 17, 17 ================================================ FILE: Zelig/Zelig/DebugTime/Debugger/UserControls/MemoryView.Designer.cs ================================================ namespace Microsoft.Zelig.Debugger.ArmProcessor { partial class MemoryView { /// /// Required designer variable. /// private System.ComponentModel.IContainer components = null; /// /// Clean up any resources being used. /// /// true if managed resources should be disposed; otherwise, false. protected override void Dispose( bool disposing ) { if(disposing && (components != null)) { components.Dispose(); } base.Dispose( disposing ); } #region Component Designer generated code /// /// Required method for Designer support - do not modify /// the contents of this method with the code editor. /// private void InitializeComponent() { this.panel1 = new System.Windows.Forms.Panel(); this.checkBox_ShowAsHex = new System.Windows.Forms.CheckBox(); this.label2 = new System.Windows.Forms.Label(); this.comboBox_ViewMode = new System.Windows.Forms.ComboBox(); this.button_Refresh = new System.Windows.Forms.Button(); this.textBox_Address = new System.Windows.Forms.TextBox(); this.label1 = new System.Windows.Forms.Label(); this.codeView1 = new Microsoft.Zelig.Debugger.ArmProcessor.CodeView(); this.panel1.SuspendLayout(); this.SuspendLayout(); // // panel1 // this.panel1.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Left) | System.Windows.Forms.AnchorStyles.Right))); this.panel1.Controls.Add( this.checkBox_ShowAsHex ); this.panel1.Controls.Add( this.label2 ); this.panel1.Controls.Add( this.comboBox_ViewMode ); this.panel1.Controls.Add( this.button_Refresh ); this.panel1.Controls.Add( this.textBox_Address ); this.panel1.Controls.Add( this.label1 ); this.panel1.Location = new System.Drawing.Point( 0, 0 ); this.panel1.Name = "panel1"; this.panel1.Size = new System.Drawing.Size( 648, 65 ); this.panel1.TabIndex = 1; // // checkBox_ShowAsHex // this.checkBox_ShowAsHex.AutoSize = true; this.checkBox_ShowAsHex.Checked = true; this.checkBox_ShowAsHex.CheckState = System.Windows.Forms.CheckState.Checked; this.checkBox_ShowAsHex.Location = new System.Drawing.Point( 189, 34 ); this.checkBox_ShowAsHex.Name = "checkBox_ShowAsHex"; this.checkBox_ShowAsHex.Size = new System.Drawing.Size( 135, 17 ); this.checkBox_ShowAsHex.TabIndex = 5; this.checkBox_ShowAsHex.Text = "Show Numbers As Hex"; this.checkBox_ShowAsHex.UseVisualStyleBackColor = true; this.checkBox_ShowAsHex.CheckedChanged += new System.EventHandler( this.checkBox_ShowAsHex_CheckedChanged ); // // label2 // this.label2.AutoSize = true; this.label2.Location = new System.Drawing.Point( 3, 35 ); this.label2.Name = "label2"; this.label2.Size = new System.Drawing.Size( 48, 13 ); this.label2.TabIndex = 4; this.label2.Text = "View As:"; // // comboBox_ViewMode // this.comboBox_ViewMode.DropDownStyle = System.Windows.Forms.ComboBoxStyle.DropDownList; this.comboBox_ViewMode.FormattingEnabled = true; this.comboBox_ViewMode.Items.AddRange( new object[] { "Bytes", "Shorts", "Words", "Longs", "Chars", "Floats", "Doubles"} ); this.comboBox_ViewMode.Location = new System.Drawing.Point( 57, 32 ); this.comboBox_ViewMode.Name = "comboBox_ViewMode"; this.comboBox_ViewMode.Size = new System.Drawing.Size( 121, 21 ); this.comboBox_ViewMode.TabIndex = 3; this.comboBox_ViewMode.SelectedIndexChanged += new System.EventHandler( this.comboBox_ViewMode_SelectedIndexChanged ); // // button_Refresh // this.button_Refresh.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Right))); this.button_Refresh.Location = new System.Drawing.Point( 560, 6 ); this.button_Refresh.Name = "button_Refresh"; this.button_Refresh.Size = new System.Drawing.Size( 75, 23 ); this.button_Refresh.TabIndex = 2; this.button_Refresh.Text = "Refresh"; this.button_Refresh.UseVisualStyleBackColor = true; this.button_Refresh.Click += new System.EventHandler( this.button_Refresh_Click ); // // textBox_Address // this.textBox_Address.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Left) | System.Windows.Forms.AnchorStyles.Right))); this.textBox_Address.Location = new System.Drawing.Point( 57, 6 ); this.textBox_Address.Name = "textBox_Address"; this.textBox_Address.Size = new System.Drawing.Size( 497, 20 ); this.textBox_Address.TabIndex = 1; this.textBox_Address.KeyDown += new System.Windows.Forms.KeyEventHandler( this.textBox_Address_KeyDown ); // // label1 // this.label1.AutoSize = true; this.label1.Location = new System.Drawing.Point( 3, 9 ); this.label1.Name = "label1"; this.label1.Size = new System.Drawing.Size( 48, 13 ); this.label1.TabIndex = 0; this.label1.Text = "Address:"; // // codeView1 // this.codeView1.Anchor = ((System.Windows.Forms.AnchorStyles)((((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Bottom) | System.Windows.Forms.AnchorStyles.Left) | System.Windows.Forms.AnchorStyles.Right))); this.codeView1.AutoScroll = true; this.codeView1.DefaultHitSink = null; this.codeView1.FallbackHitSink = null; this.codeView1.Font = new System.Drawing.Font( "Courier New", 9F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)) ); this.codeView1.Location = new System.Drawing.Point( 0, 71 ); this.codeView1.Name = "codeView1"; this.codeView1.Size = new System.Drawing.Size( 648, 409 ); this.codeView1.TabIndex = 0; this.codeView1.SizeChanged += new System.EventHandler( this.codeView1_SizeChanged ); // // MemoryView // this.AutoScaleDimensions = new System.Drawing.SizeF( 6F, 13F ); this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font; this.AutoSize = true; this.Controls.Add( this.panel1 ); this.Controls.Add( this.codeView1 ); this.Name = "MemoryView"; this.Size = new System.Drawing.Size( 651, 483 ); this.panel1.ResumeLayout( false ); this.panel1.PerformLayout(); this.ResumeLayout( false ); } #endregion private CodeView codeView1; private System.Windows.Forms.Panel panel1; private System.Windows.Forms.Button button_Refresh; private System.Windows.Forms.TextBox textBox_Address; private System.Windows.Forms.Label label1; private System.Windows.Forms.Label label2; private System.Windows.Forms.ComboBox comboBox_ViewMode; private System.Windows.Forms.CheckBox checkBox_ShowAsHex; } } ================================================ FILE: Zelig/Zelig/DebugTime/Debugger/UserControls/MemoryView.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // namespace Microsoft.Zelig.Debugger.ArmProcessor { using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Text; using System.IO; using System.Windows.Forms; using System.Threading; using EncDef = Microsoft.Zelig.TargetModel.ArmProcessor.EncodingDefinition; using InstructionSet = Microsoft.Zelig.TargetModel.ArmProcessor.InstructionSet; using IR = Microsoft.Zelig.CodeGeneration.IR; using RT = Microsoft.Zelig.Runtime; using TS = Microsoft.Zelig.Runtime.TypeSystem; using Hst = Microsoft.Zelig.Emulation.Hosting; public partial class MemoryView : UserControl { public enum ViewMode { Bytes, Shorts, Words, Longs, Chars, Floats, Doubles, } private class LayoutContext { // // State // MemoryView m_control; MemoryDelta m_memoryDelta; GraphicsContext m_ctx; int m_width; int m_height; float m_stepX; float m_stepY; PointF m_ptLine; PointF m_ptWord; ContainerVisualItem m_topElement; ContainerVisualItem m_lineItem; // // Constructor Methods // internal LayoutContext( MemoryView control , MemoryDelta memoryDelta , ContainerVisualItem topElement ) { m_control = control; m_memoryDelta = memoryDelta; m_ctx = control.codeView1.CtxForLayout; m_width = control.codeView1.Width; m_height = control.codeView1.Height; m_stepX = m_ctx.CharSize ( null ); m_stepY = m_ctx.CharHeight( null ); m_topElement = topElement; } // // Helper Methods // internal void Install( CodeView codeView ) { VisualTreeInfo vti = new VisualTreeInfo( null, null, m_topElement ); codeView.InstallVisualTree( vti, null ); } //--// internal void CreateScalarView( uint address , ViewMode mode ) { uint baseAddress = address; if(CanPlaceLine( 2 )) { ContainerVisualItem lineItemPrevious = m_lineItem; bool fHex = m_control.checkBox_ShowAsHex.Checked; AddText( "Previous", "Click Here To View More...", Brushes.DarkGreen, 2, 2 ); while(CanPlaceLine( 1 )) { AddText( null, string.Format( "0x{0:X8}:", address ), Brushes.Blue, 1, 1 ); while(true) { TextVisualItem item = null; uint size = 4; bool fChanged = false; switch(mode) { case ViewMode.Bytes: { byte result; if(m_memoryDelta.GetUInt8( address, true, out result, out fChanged )) { Brush brush = fChanged ? Brushes.Red : Brushes.Black; item = AddText( null, string.Format( fHex ? "0x{0:X2}" : "{0}", result ), brush, 1, 1 ); size = sizeof(byte); } } break; case ViewMode.Shorts: { ushort result; if(m_memoryDelta.GetUInt16( address, true, out result, out fChanged )) { Brush brush = fChanged ? Brushes.Red : Brushes.Black; item = AddText( null, string.Format( fHex ? "0x{0:X4}" : "{0}", result ), brush, 1, 1 ); size = sizeof(ushort); } } break; case ViewMode.Words: { uint result; if(m_memoryDelta.GetUInt32( address, true, out result, out fChanged )) { Brush brush = fChanged ? Brushes.Red : Brushes.Black; item = AddText( new WatchHelper.PointerContext( result, null, true ), string.Format( fHex ? "0x{0:X8}" : "{0}", result ), brush, 1, 1 ); size = sizeof(uint); } } break; case ViewMode.Longs: { ulong result; if(m_memoryDelta.GetUInt64( address, true, out result, out fChanged )) { Brush brush = fChanged ? Brushes.Red : Brushes.Black; item = AddText( null, string.Format( fHex ? "0x{0:X16}" : "{0}", result ), brush, 1, 1 ); size = sizeof(ulong); } } break; case ViewMode.Floats: { uint result; if(m_memoryDelta.GetUInt32( address, true, out result, out fChanged )) { Brush brush = fChanged ? Brushes.Red : Brushes.Black; item = AddText( null, string.Format( "{0}", DataConversion.GetFloatFromBytes( result ) ), brush, 1, 1 ); size = sizeof(uint); } } break; case ViewMode.Doubles: { ulong result; if(m_memoryDelta.GetUInt64( address, true, out result, out fChanged )) { Brush brush = fChanged ? Brushes.Red : Brushes.Black; item = AddText( null, string.Format( "{0}", DataConversion.GetDoubleFromBytes( result ) ), brush, 1, 1 ); size = sizeof(ulong); } } break; case ViewMode.Chars: { ushort result; char ch; Brush brush; if(m_memoryDelta.GetUInt16( address, true, out result, out fChanged )) { ch = (char)result; if(ch < 20 || ch >= 128) { ch = '.'; } brush = fChanged ? Brushes.Red : Brushes.Black; } else { ch = '?'; brush = Brushes.Red; } item = AddText( null, string.Format( "{0}", ch ), brush, 0, 0.5f ); size = sizeof(ushort); } break; } if(item == null) { item = AddText( null, "????????", Brushes.Red, 0, 1 ); } if(m_ptWord.X >= m_width) { m_lineItem.Remove( item ); break; } address += size; } } PlaceLine(); ContainerVisualItem lineItemNext = m_lineItem; AddText( "Next", "Click Here To View More...", Brushes.DarkGreen, 2, 2 ); //--// uint addressSpan = address - baseAddress; uint previousAddress = baseAddress - (addressSpan) / 2; uint nextAddress = address + (addressSpan) / 2; m_control.codeView1.FallbackHitSink = delegate( CodeView owner, VisualItem origin, PointF relPos, MouseEventArgs e, bool fDown, bool fUp ) { if(ProcessButton( origin, e, fDown, fUp )) { return; } if(e.Delta > 0) { m_control.MoveToAddress( previousAddress, false ); return; } if(e.Delta < 0) { m_control.MoveToAddress( nextAddress, false ); return; } }; lineItemPrevious.HitSink = delegate( CodeView owner, VisualItem origin, PointF relPos, MouseEventArgs e, bool fDown, bool fUp ) { if(fDown) { if((e.Button & MouseButtons.Left) != 0) { m_control.MoveToAddress( previousAddress, false ); } } }; lineItemNext.HitSink = delegate( CodeView owner, VisualItem origin, PointF relPos, MouseEventArgs e, bool fDown, bool fUp ) { if(fDown) { if((e.Button & MouseButtons.Left) != 0) { m_control.MoveToAddress( nextAddress, false ); } } }; } } //--// private bool ProcessButton( VisualItem origin , MouseEventArgs e , bool fDown , bool fUp ) { if(fDown) { if((e.Button & MouseButtons.XButton1) != 0) { m_control.MoveThroughHistory( -1 ); } if((e.Button & MouseButtons.XButton2) != 0) { m_control.MoveThroughHistory( +1 ); } if((e.Button & MouseButtons.Left) != 0) { if(e.Clicks == 2 && origin != null) { WatchHelper.PointerContext ct = origin.Context as WatchHelper.PointerContext; if(ct != null) { m_control.MoveToAddress( ct.Address, true ); return true; } } } } return false; } //--// private void SkipX( float amount ) { m_ptLine.X += m_stepX * amount; } private void SkipY( float amount ) { m_ptLine.Y += m_stepY * amount; } private bool CanPlaceLine( int extraLines ) { if(m_ptLine.Y + (m_stepY * (1 + extraLines)) >= m_height) { return false; } PlaceLine(); return true; } private ContainerVisualItem PlaceLine() { m_lineItem = new ContainerVisualItem( null ); m_lineItem.RelativeOrigin = m_ptLine; m_ptLine.Y += m_stepY; m_ptWord = new PointF(); m_topElement.Add( m_lineItem ); return m_lineItem; } private TextVisualItem AddText( object context , string text , Brush brush ) { return AddText( context, text, brush, 0, 0 ); } private TextVisualItem AddText( object context , string text , Brush brush , float preX , float postX ) { TextVisualItem item = new TextVisualItem( context, text ); item.TextBrush = brush; BaseTextVisualItem.PlaceInALine( m_ctx, item, ref m_ptWord, preX, postX ); m_lineItem.Add( item ); return item; } } // // State // DebuggerMainForm m_owner; ViewMode m_currentViewMode; WatchHelper.PointerContext m_currentPointer; MemoryDelta m_memoryDelta; List< WatchHelper.PointerContext > m_history; int m_historyPosition; // // Constructor Methods // public MemoryView() { InitializeComponent(); //--// m_currentViewMode = ViewMode.Words; m_history = new List< WatchHelper.PointerContext >(); m_historyPosition = -1; comboBox_ViewMode.SelectedIndex = (int)m_currentViewMode; } // // Helper Methods // public void Link( DebuggerMainForm owner ) { m_owner = owner; m_owner.HostingSite.NotifyOnExecutionStateChange += ExecutionStateChangeNotification; } public Hst.Forms.HostingSite.NotificationResponse ExecutionStateChangeNotification( Hst.Forms.HostingSite host , Hst.Forms.HostingSite.ExecutionState oldState , Hst.Forms.HostingSite.ExecutionState newState ) { GenerateView(); return Hst.Forms.HostingSite.NotificationResponse.DoNothing; } private void GenerateView() { if(m_currentPointer != null) { m_memoryDelta = m_owner.MemoryDelta; LayoutContext lc = new LayoutContext( this, m_memoryDelta, new ContainerVisualItem( null ) ); lc.CreateScalarView( m_currentPointer.Address, m_currentViewMode ); lc.Install( codeView1 ); } else { codeView1.InstallVisualTree( null, null ); } } //--// public void MoveThroughHistory( int delta ) { int nextHistoryPosition = m_historyPosition + delta; if(nextHistoryPosition >= 0 && nextHistoryPosition < m_history.Count) { m_currentPointer = m_history[nextHistoryPosition]; m_historyPosition = nextHistoryPosition; GenerateView(); } } public void MoveToAddress( uint address , bool fUpdateHistory ) { if(m_currentPointer != null && m_currentPointer.Address == address ) { return; } if(fUpdateHistory) { int size = m_history.Count; int newSize = m_historyPosition + 1; if(newSize < size) { m_history.RemoveRange( newSize, size - newSize ); } m_currentPointer = null; } if(m_currentPointer == null) { m_currentPointer = new WatchHelper.PointerContext( address, null, false ); m_historyPosition = m_history.Count; m_history.Add( m_currentPointer ); } else { m_currentPointer.Address = address; } GenerateView(); } private void ValidateNewAddress() { uint address; string text = this.textBox_Address.Text; if(text.ToUpper().StartsWith( "0X" )) { if(uint.TryParse( text.Substring( 2 ), System.Globalization.NumberStyles.AllowHexSpecifier, null, out address )) { MoveToAddress( address, true ); return; } } if(uint.TryParse( text, out address )) { MoveToAddress( address, true ); return; } //--// Emulation.Hosting.ProcessorStatus ps; m_owner.Host.GetHostingService( out ps ); Emulation.Hosting.MemoryProvider mem; m_owner.Host.GetHostingService( out mem ); //--// StackFrame currentStackFrame = m_owner.SelectedStackFrame; IR.LowLevelVariableExpression[] array = m_owner.ImageInformation.AliveVariables( currentStackFrame.Region, currentStackFrame.RegionOffset ); foreach(IR.LowLevelVariableExpression var in array) { string name; object val; if(var is IR.PhysicalRegisterExpression) { IR.PhysicalRegisterExpression varReg = var as IR.PhysicalRegisterExpression; if(varReg.RegisterDescriptor.InIntegerRegisterFile == false) { continue; } val = ps.GetRegister( varReg.RegisterDescriptor ); IR.VariableExpression varSrc = var.SourceVariable; if(varSrc != null && varSrc.DebugName != null) { name = varSrc.DebugName.Name; } else { name = string.Format( "$Reg( {0} )", varReg.RegisterDescriptor.Mnemonic ); } } else if(var is IR.StackLocationExpression) { IR.StackLocationExpression varStack = var as IR.StackLocationExpression; uint sp = ps.StackPointer; uint memVal; mem.GetUInt32( sp + varStack.AllocationOffset, out memVal ); val = memVal; IR.VariableExpression varSrc = var.SourceVariable; if(varSrc != null && varSrc.DebugName != null) { name = varSrc.DebugName.Name; } else { name = string.Format( "$Stack(0x{0:X8})", varStack.AllocationOffset ); } } else { continue; } if(name == text && val is uint) { MoveToAddress( (uint)val, true ); return; } } //--// m_currentPointer = null; GenerateView(); this.textBox_Address.Focus(); } private void SwitchViewMode( ViewMode mode ) { m_currentViewMode = mode; comboBox_ViewMode.SelectedIndex = (int)m_currentViewMode; } // // Access Methods // // // Event Methods // private void button_Refresh_Click( object sender, EventArgs e ) { ValidateNewAddress(); } private void codeView1_SizeChanged( object sender, EventArgs e ) { GenerateView(); } private void comboBox_ViewMode_SelectedIndexChanged( object sender, EventArgs e ) { ViewMode newViewMode = (ViewMode)comboBox_ViewMode.SelectedIndex; if(m_currentViewMode != newViewMode) { m_currentViewMode = newViewMode; GenerateView(); codeView1.Focus(); } } private void textBox_Address_KeyDown( object sender, KeyEventArgs e ) { if(e.KeyCode == Keys.Return) { ValidateNewAddress(); } } private void checkBox_ShowAsHex_CheckedChanged( object sender, EventArgs e ) { GenerateView(); } } } ================================================ FILE: Zelig/Zelig/DebugTime/Debugger/UserControls/MemoryView.resx ================================================ text/microsoft-resx 2.0 System.Resources.ResXResourceReader, System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 System.Resources.ResXResourceWriter, System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 ================================================ FILE: Zelig/Zelig/DebugTime/Debugger/UserControls/RegistersView.Designer.cs ================================================ namespace Microsoft.Zelig.Debugger.ArmProcessor { partial class RegistersView { /// /// Required designer variable. /// private System.ComponentModel.IContainer components = null; /// /// Clean up any resources being used. /// /// true if managed resources should be disposed; otherwise, false. protected override void Dispose( bool disposing ) { if(disposing && (components != null)) { components.Dispose(); } base.Dispose( disposing ); } #region Component Designer generated code /// /// Required method for Designer support - do not modify /// the contents of this method with the code editor. /// private void InitializeComponent() { this.components = new System.ComponentModel.Container(); this.contextMenuStrip1 = new System.Windows.Forms.ContextMenuStrip( this.components ); this.toolStripMenuItem_HexDisplay = new System.Windows.Forms.ToolStripMenuItem(); this.treeBasedGridView_Registers = new Microsoft.Zelig.Debugger.ArmProcessor.TreeBasedGridView(); this.contextMenuStrip1.SuspendLayout(); this.SuspendLayout(); // // contextMenuStrip1 // this.contextMenuStrip1.Items.AddRange( new System.Windows.Forms.ToolStripItem[] { this.toolStripMenuItem_HexDisplay} ); this.contextMenuStrip1.Name = "contextMenuStrip1"; this.contextMenuStrip1.Size = new System.Drawing.Size( 183, 48 ); // // toolStripMenuItem_HexDisplay // this.toolStripMenuItem_HexDisplay.Name = "toolStripMenuItem_HexDisplay"; this.toolStripMenuItem_HexDisplay.Size = new System.Drawing.Size( 182, 22 ); this.toolStripMenuItem_HexDisplay.Text = "Hexadecimal Display"; this.toolStripMenuItem_HexDisplay.CheckedChanged += new System.EventHandler( this.toolStripMenuItem_HexDisplay_CheckedChanged ); this.toolStripMenuItem_HexDisplay.Click += new System.EventHandler( this.toolStripMenuItem_HexDisplay_Click ); this.toolStripMenuItem_HexDisplay.Checked = true; // // treeBasedGridView_Registers // this.treeBasedGridView_Registers.BorderStyle = System.Windows.Forms.BorderStyle.Fixed3D; this.treeBasedGridView_Registers.Dock = System.Windows.Forms.DockStyle.Fill; this.treeBasedGridView_Registers.Location = new System.Drawing.Point( 0, 0 ); this.treeBasedGridView_Registers.Name = "treeBasedGridView_Registers"; this.treeBasedGridView_Registers.Size = new System.Drawing.Size( 647, 469 ); this.treeBasedGridView_Registers.TabIndex = 0; this.treeBasedGridView_Registers.NodeMouseClick += new Microsoft.Zelig.Debugger.ArmProcessor.TreeBasedGridView.NodeMouseEventHandler( this.treeBasedGridView_Registers_CellMouseClick ); // // RegistersView // this.AutoScaleDimensions = new System.Drawing.SizeF( 6F, 13F ); this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font; this.Controls.Add( this.treeBasedGridView_Registers ); this.Name = "RegistersView"; this.Size = new System.Drawing.Size( 647, 469 ); this.contextMenuStrip1.ResumeLayout( false ); this.ResumeLayout( false ); } #endregion private TreeBasedGridView treeBasedGridView_Registers; private System.Windows.Forms.ContextMenuStrip contextMenuStrip1; private System.Windows.Forms.ToolStripMenuItem toolStripMenuItem_HexDisplay; } } ================================================ FILE: Zelig/Zelig/DebugTime/Debugger/UserControls/RegistersView.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // namespace Microsoft.Zelig.Debugger.ArmProcessor { using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Text; using System.IO; using System.Windows.Forms; using System.Threading; using EncDef = Microsoft.Zelig.TargetModel.ArmProcessor.EncodingDefinition; using InstructionSet = Microsoft.Zelig.TargetModel.ArmProcessor.InstructionSet; using IR = Microsoft.Zelig.CodeGeneration.IR; using RT = Microsoft.Zelig.Runtime; using TS = Microsoft.Zelig.Runtime.TypeSystem; using Hst = Microsoft.Zelig.Emulation.Hosting; public partial class RegistersView : UserControl { // // State // DebuggerMainForm m_owner; WatchHelper m_wh; // // Constructor Methods // public RegistersView() { InitializeComponent(); WatchHelper.SetColumns( treeBasedGridView_Registers ); } // // Helper Methods // public void Link( DebuggerMainForm owner ) { m_owner = owner; m_owner.HostingSite.NotifyOnExecutionStateChange += delegate( Hst.Forms.HostingSite host , Hst.Forms.HostingSite.ExecutionState oldState , Hst.Forms.HostingSite.ExecutionState newState ) { UpdateUI(); return Hst.Forms.HostingSite.NotificationResponse.DoNothing; }; m_owner.HostingSite.NotifyOnVisualizationEvent += delegate( Hst.Forms.HostingSite host , Hst.Forms.HostingSite.VisualizationEvent e ) { if(e == Hst.Forms.HostingSite.VisualizationEvent.NewStackFrame) { UpdateUI(); } return Hst.Forms.HostingSite.NotificationResponse.DoNothing; }; } private void UpdateUI() { ImageInformation imageInformation = m_owner.ImageInformation; StackFrame currentStackFrame = m_owner.SelectedStackFrame; //--// WatchHelper.Synchronize( ref m_wh, m_owner.MemoryDelta, treeBasedGridView_Registers.RootNode, false, false ); if(m_wh != null) { m_wh.HexadecimalDisplay = toolStripMenuItem_HexDisplay.Checked; } //--// treeBasedGridView_Registers.StartTreeUpdate(); treeBasedGridView_Registers.Enabled = currentStackFrame != null; if(currentStackFrame == null || m_owner.IsIdle == false) { //// DebuggerMainForm.GrayOutRowsInDataGridView( treeBasedGridView_Registers.Rows ); } else { IR.LowLevelVariableExpression[] array = imageInformation.AliveVariables( currentStackFrame.Region, currentStackFrame.RegionOffset ); var ht = HashTableFactory.NewWithReferenceEquality< IR.Abstractions.RegisterDescriptor, IR.PhysicalRegisterExpression >(); foreach(IR.LowLevelVariableExpression var in array) { IR.PhysicalRegisterExpression varReg = var as IR.PhysicalRegisterExpression; if(varReg != null) { ht[varReg.RegisterDescriptor] = varReg; } } var regCtx = currentStackFrame.RegisterContext; var lst = new List< WatchHelper.ItemDescriptor >(); foreach(IR.Abstractions.RegisterDescriptor regDesc in imageInformation.TypeSystem.PlatformAbstraction.GetRegisters()) { TS.TypeRepresentation registerType = null; string typeDescriptor = null; //--// IR.PhysicalRegisterExpression varReg; if(ht.TryGetValue( regDesc, out varReg )) { var varType = varReg.Type; registerType = varType; string typeName = varType.FullNameWithAbbreviation; IR.VariableExpression varSrc = varReg.SourceVariable; if(varSrc != null && varSrc.DebugName != null) { typeDescriptor = string.Format( "{0} {1}", typeName, varSrc.DebugName.Name ); } else { typeDescriptor = string.Format( "{0}", typeName ); } } else { var wkt = imageInformation.TypeSystem.WellKnownTypes; if(regDesc.InIntegerRegisterFile) { switch(regDesc.PhysicalStorageSize) { case 1: registerType = wkt.System_UInt32; break; case 2: registerType = wkt.System_UInt64; break; } } else if(regDesc.InFloatingPointRegisterFile) { switch(regDesc.PhysicalStorageSize) { case 1: registerType = wkt.System_Single; break; case 2: registerType = wkt.System_Double; break; } } if(registerType == null) { registerType = wkt.System_UInt32; } } //--// var valueHandle = new RegisterValueHandle( regCtx.GetValue( regDesc ), registerType, true ); var item = new WatchHelper.ItemDescriptor( m_wh, regDesc.Mnemonic, registerType, valueHandle, typeDescriptor ); lst.Add( item ); } m_wh.Update( lst, false ); } treeBasedGridView_Registers.EndTreeUpdate(); } // // Event Methods // private void treeBasedGridView_Registers_CellMouseClick( object sender , TreeBasedGridView.NodeMouseEventArgs e ) { if(e.Button == MouseButtons.Right) { contextMenuStrip1.Show( treeBasedGridView_Registers, e.Location ); } } private void toolStripMenuItem_HexDisplay_CheckedChanged( object sender , EventArgs e ) { if(treeBasedGridView_Registers.Enabled) { if(m_wh != null) { m_wh.HexadecimalDisplay = toolStripMenuItem_HexDisplay.Checked; } } } private void toolStripMenuItem_HexDisplay_Click( object sender , EventArgs e ) { toolStripMenuItem_HexDisplay.Checked = !toolStripMenuItem_HexDisplay.Checked; } } } ================================================ FILE: Zelig/Zelig/DebugTime/Debugger/UserControls/RegistersView.resx ================================================ text/microsoft-resx 2.0 System.Resources.ResXResourceReader, System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 System.Resources.ResXResourceWriter, System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 17, 17 ================================================ FILE: Zelig/Zelig/DebugTime/Debugger/UserControls/StackTraceView.Designer.cs ================================================ namespace Microsoft.Zelig.Debugger.ArmProcessor { partial class StackTraceView { /// /// Required designer variable. /// private System.ComponentModel.IContainer components = null; /// /// Clean up any resources being used. /// /// true if managed resources should be disposed; otherwise, false. protected override void Dispose( bool disposing ) { if(disposing && (components != null)) { components.Dispose(); } base.Dispose( disposing ); } #region Component Designer generated code /// /// Required method for Designer support - do not modify /// the contents of this method with the code editor. /// private void InitializeComponent() { System.Windows.Forms.DataGridViewCellStyle dataGridViewCellStyle1 = new System.Windows.Forms.DataGridViewCellStyle(); this.dataGridView_StackTrace = new System.Windows.Forms.DataGridView(); this.dataGridViewTextBoxColumn_StackTrace_Flags = new System.Windows.Forms.DataGridViewImageColumn(); this.dataGridViewTextBoxColumn_StackTrace_Method = new System.Windows.Forms.DataGridViewTextBoxColumn(); this.dataGridViewTextBoxColumn_StackTrace_Depth = new System.Windows.Forms.DataGridViewTextBoxColumn(); ((System.ComponentModel.ISupportInitialize)(this.dataGridView_StackTrace)).BeginInit(); this.SuspendLayout(); // // dataGridView_StackTrace // this.dataGridView_StackTrace.AllowUserToAddRows = false; this.dataGridView_StackTrace.AllowUserToDeleteRows = false; this.dataGridView_StackTrace.ColumnHeadersHeightSizeMode = System.Windows.Forms.DataGridViewColumnHeadersHeightSizeMode.AutoSize; this.dataGridView_StackTrace.Columns.AddRange( new System.Windows.Forms.DataGridViewColumn[] { this.dataGridViewTextBoxColumn_StackTrace_Flags, this.dataGridViewTextBoxColumn_StackTrace_Method, this.dataGridViewTextBoxColumn_StackTrace_Depth} ); this.dataGridView_StackTrace.Dock = System.Windows.Forms.DockStyle.Fill; this.dataGridView_StackTrace.Location = new System.Drawing.Point( 0, 0 ); this.dataGridView_StackTrace.Name = "dataGridView_StackTrace"; this.dataGridView_StackTrace.ReadOnly = true; this.dataGridView_StackTrace.RowHeadersWidth = 4; this.dataGridView_StackTrace.Size = new System.Drawing.Size( 543, 483 ); this.dataGridView_StackTrace.TabIndex = 1; this.dataGridView_StackTrace.CellContentClick += new System.Windows.Forms.DataGridViewCellEventHandler( this.dataGridView_StackTrace_CellContentClick ); // // dataGridViewTextBoxColumn_StackTrace_Flags // this.dataGridViewTextBoxColumn_StackTrace_Flags.AutoSizeMode = System.Windows.Forms.DataGridViewAutoSizeColumnMode.None; dataGridViewCellStyle1.Alignment = System.Windows.Forms.DataGridViewContentAlignment.MiddleCenter; dataGridViewCellStyle1.SelectionBackColor = System.Drawing.Color.White; this.dataGridViewTextBoxColumn_StackTrace_Flags.DefaultCellStyle = dataGridViewCellStyle1; this.dataGridViewTextBoxColumn_StackTrace_Flags.HeaderText = ""; this.dataGridViewTextBoxColumn_StackTrace_Flags.Name = "dataGridViewTextBoxColumn_StackTrace_Flags"; this.dataGridViewTextBoxColumn_StackTrace_Flags.ReadOnly = true; this.dataGridViewTextBoxColumn_StackTrace_Flags.Resizable = System.Windows.Forms.DataGridViewTriState.False; this.dataGridViewTextBoxColumn_StackTrace_Flags.Width = 20; // // dataGridViewTextBoxColumn_StackTrace_Method // this.dataGridViewTextBoxColumn_StackTrace_Method.AutoSizeMode = System.Windows.Forms.DataGridViewAutoSizeColumnMode.Fill; this.dataGridViewTextBoxColumn_StackTrace_Method.HeaderText = "Method"; this.dataGridViewTextBoxColumn_StackTrace_Method.Name = "dataGridViewTextBoxColumn_StackTrace_Method"; this.dataGridViewTextBoxColumn_StackTrace_Method.ReadOnly = true; this.dataGridViewTextBoxColumn_StackTrace_Method.SortMode = System.Windows.Forms.DataGridViewColumnSortMode.NotSortable; // // dataGridViewTextBoxColumn_StackTrace_Depth // this.dataGridViewTextBoxColumn_StackTrace_Depth.AutoSizeMode = System.Windows.Forms.DataGridViewAutoSizeColumnMode.None; this.dataGridViewTextBoxColumn_StackTrace_Depth.HeaderText = "Depth"; this.dataGridViewTextBoxColumn_StackTrace_Depth.Name = "dataGridViewTextBoxColumn_StackTrace_Depth"; this.dataGridViewTextBoxColumn_StackTrace_Depth.ReadOnly = true; this.dataGridViewTextBoxColumn_StackTrace_Depth.SortMode = System.Windows.Forms.DataGridViewColumnSortMode.NotSortable; this.dataGridViewTextBoxColumn_StackTrace_Depth.Width = 50; // // StackTraceView // this.AutoScaleDimensions = new System.Drawing.SizeF( 6F, 13F ); this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font; this.Controls.Add( this.dataGridView_StackTrace ); this.Name = "StackTraceView"; this.Size = new System.Drawing.Size( 543, 483 ); ((System.ComponentModel.ISupportInitialize)(this.dataGridView_StackTrace)).EndInit(); this.ResumeLayout( false ); } #endregion private System.Windows.Forms.DataGridView dataGridView_StackTrace; private System.Windows.Forms.DataGridViewImageColumn dataGridViewTextBoxColumn_StackTrace_Flags; private System.Windows.Forms.DataGridViewTextBoxColumn dataGridViewTextBoxColumn_StackTrace_Method; private System.Windows.Forms.DataGridViewTextBoxColumn dataGridViewTextBoxColumn_StackTrace_Depth; } } ================================================ FILE: Zelig/Zelig/DebugTime/Debugger/UserControls/StackTraceView.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // namespace Microsoft.Zelig.Debugger.ArmProcessor { using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Text; using System.IO; using System.Windows.Forms; using System.Threading; using IR = Microsoft.Zelig.CodeGeneration.IR; using RT = Microsoft.Zelig.Runtime; using TS = Microsoft.Zelig.Runtime.TypeSystem; using Hst = Microsoft.Zelig.Emulation.Hosting; public partial class StackTraceView : UserControl { // // State // DebuggerMainForm m_owner; int m_version; Icon m_icon_CurrentStatement = Properties.Resources.CurrentStatement; Icon m_icon_StackFrame = Properties.Resources.StackFrame; Icon m_icon_EmptyIcon = Properties.Resources.EmptyIcon; // // Constructor Methods // public StackTraceView() { InitializeComponent(); } //--// public void Link( DebuggerMainForm owner ) { m_owner = owner; m_owner.HostingSite.NotifyOnExecutionStateChange += delegate( Hst.Forms.HostingSite host , Hst.Forms.HostingSite.ExecutionState oldState , Hst.Forms.HostingSite.ExecutionState newState ) { UpdateUI(); return Hst.Forms.HostingSite.NotificationResponse.DoNothing; }; m_owner.HostingSite.NotifyOnVisualizationEvent += delegate( Hst.Forms.HostingSite host , Hst.Forms.HostingSite.VisualizationEvent e ) { if(e == Hst.Forms.HostingSite.VisualizationEvent.NewStackFrame) { UpdateUI(); } return Hst.Forms.HostingSite.NotificationResponse.DoNothing; }; } private void UpdateUI() { StackFrame currentStackFrame = m_owner.SelectedStackFrame; //--// dataGridView_StackTrace.SuspendLayout(); DataGridViewRowCollection rows = dataGridView_StackTrace.Rows; dataGridView_StackTrace.Enabled = (currentStackFrame != null); if(currentStackFrame == null || m_owner.IsIdle == false) { m_version = -1; DebuggerMainForm.GrayOutRowsInDataGridView( rows ); } else { bool fRebuild = (m_version != m_owner.VersionStackTrace); if(fRebuild) { m_version = m_owner.VersionStackTrace; rows.Clear(); } foreach(StackFrame sf in m_owner.SelectedThread.StackTrace) { Icon icon; if(sf.Depth == 0) { icon = m_icon_CurrentStatement; } else if(sf == m_owner.SelectedStackFrame) { icon = m_icon_StackFrame; } else { icon = m_icon_EmptyIcon; } if(fRebuild) { var cm = sf.CodeMapOfTarget; if(cm != null) { if(0 != ( cm.Target.BuildTimeFlags & TS.MethodRepresentation.BuildTimeAttributes.Imported )) { string method = sf.DebugInfo.MethodName; if(string.IsNullOrEmpty( method )) { method = cm.Target.ToShortString(); } rows.Add( icon, method, sf.Depth + 1 ); } else { rows.Add( icon, cm.Target.ToShortString(), sf.Depth + 1 ); } } else { rows.Add( icon, string.Format( "0x{0:X8}", sf.ProgramCounter ), sf.Depth + 1 ); } } else { rows[sf.Depth].Cells[0].Value = icon; } } } dataGridView_StackTrace.ResumeLayout(); } // // Access Methods // // // Event Methods // private void dataGridView_StackTrace_CellContentClick( object sender, DataGridViewCellEventArgs e ) { m_owner.Action_SelectStackFrame( e.RowIndex ); } } } ================================================ FILE: Zelig/Zelig/DebugTime/Debugger/UserControls/StackTraceView.resx ================================================ text/microsoft-resx 2.0 System.Resources.ResXResourceReader, System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 System.Resources.ResXResourceWriter, System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 True True True ================================================ FILE: Zelig/Zelig/DebugTime/Debugger/UserControls/ThreadsView.Designer.cs ================================================ namespace Microsoft.Zelig.Debugger.ArmProcessor { partial class ThreadsView { /// /// Required designer variable. /// private System.ComponentModel.IContainer components = null; /// /// Clean up any resources being used. /// /// true if managed resources should be disposed; otherwise, false. protected override void Dispose( bool disposing ) { if(disposing && (components != null)) { components.Dispose(); } base.Dispose( disposing ); } #region Component Designer generated code /// /// Required method for Designer support - do not modify /// the contents of this method with the code editor. /// private void InitializeComponent() { System.Windows.Forms.DataGridViewCellStyle dataGridViewCellStyle1 = new System.Windows.Forms.DataGridViewCellStyle(); this.dataGridView_Threads = new System.Windows.Forms.DataGridView(); this.dataGridViewTextBoxColumn_Threads_Flags = new System.Windows.Forms.DataGridViewImageColumn(); this.dataGridViewTextBoxColumn_Threads_Id = new System.Windows.Forms.DataGridViewTextBoxColumn(); this.dataGridViewTextBoxColumn_Threads_Time = new System.Windows.Forms.DataGridViewTextBoxColumn(); this.dataGridViewTextBoxColumn_Threads_ContextSwitches = new System.Windows.Forms.DataGridViewTextBoxColumn(); this.dataGridViewTextBoxColumn_Threads_Method = new System.Windows.Forms.DataGridViewTextBoxColumn(); ((System.ComponentModel.ISupportInitialize)(this.dataGridView_Threads)).BeginInit(); this.SuspendLayout(); // // dataGridView_Threads // this.dataGridView_Threads.AllowUserToAddRows = false; this.dataGridView_Threads.AllowUserToDeleteRows = false; this.dataGridView_Threads.ColumnHeadersHeightSizeMode = System.Windows.Forms.DataGridViewColumnHeadersHeightSizeMode.AutoSize; this.dataGridView_Threads.Columns.AddRange( new System.Windows.Forms.DataGridViewColumn[] { this.dataGridViewTextBoxColumn_Threads_Flags, this.dataGridViewTextBoxColumn_Threads_Id, this.dataGridViewTextBoxColumn_Threads_Time, this.dataGridViewTextBoxColumn_Threads_ContextSwitches, this.dataGridViewTextBoxColumn_Threads_Method} ); this.dataGridView_Threads.Dock = System.Windows.Forms.DockStyle.Fill; this.dataGridView_Threads.Location = new System.Drawing.Point( 0, 0 ); this.dataGridView_Threads.MultiSelect = false; this.dataGridView_Threads.Name = "dataGridView_Threads"; this.dataGridView_Threads.ReadOnly = true; this.dataGridView_Threads.RowHeadersWidth = 4; this.dataGridView_Threads.Size = new System.Drawing.Size( 543, 483 ); this.dataGridView_Threads.TabIndex = 1; this.dataGridView_Threads.CellContentClick += new System.Windows.Forms.DataGridViewCellEventHandler( this.dataGridView_Threads_CellContentClick ); // // dataGridViewTextBoxColumn_Threads_Flags // this.dataGridViewTextBoxColumn_Threads_Flags.AutoSizeMode = System.Windows.Forms.DataGridViewAutoSizeColumnMode.None; dataGridViewCellStyle1.Alignment = System.Windows.Forms.DataGridViewContentAlignment.MiddleCenter; dataGridViewCellStyle1.SelectionBackColor = System.Drawing.Color.White; this.dataGridViewTextBoxColumn_Threads_Flags.DefaultCellStyle = dataGridViewCellStyle1; this.dataGridViewTextBoxColumn_Threads_Flags.HeaderText = ""; this.dataGridViewTextBoxColumn_Threads_Flags.Name = "dataGridViewTextBoxColumn_Threads_Flags"; this.dataGridViewTextBoxColumn_Threads_Flags.ReadOnly = true; this.dataGridViewTextBoxColumn_Threads_Flags.Resizable = System.Windows.Forms.DataGridViewTriState.False; this.dataGridViewTextBoxColumn_Threads_Flags.Width = 20; // // dataGridViewTextBoxColumn_Threads_Id // this.dataGridViewTextBoxColumn_Threads_Id.AutoSizeMode = System.Windows.Forms.DataGridViewAutoSizeColumnMode.None; this.dataGridViewTextBoxColumn_Threads_Id.HeaderText = "Id"; this.dataGridViewTextBoxColumn_Threads_Id.Name = "dataGridViewTextBoxColumn_Threads_Id"; this.dataGridViewTextBoxColumn_Threads_Id.ReadOnly = true; this.dataGridViewTextBoxColumn_Threads_Id.Width = 80; // // dataGridViewTextBoxColumn_Threads_Time // this.dataGridViewTextBoxColumn_Threads_Time.AutoSizeMode = System.Windows.Forms.DataGridViewAutoSizeColumnMode.ColumnHeader; this.dataGridViewTextBoxColumn_Threads_Time.HeaderText = "CPU %"; this.dataGridViewTextBoxColumn_Threads_Time.Name = "dataGridViewTextBoxColumn_Threads_Time"; this.dataGridViewTextBoxColumn_Threads_Time.ReadOnly = true; this.dataGridViewTextBoxColumn_Threads_Time.Width = 61; // // dataGridViewTextBoxColumn_Threads_ContextSwitches // this.dataGridViewTextBoxColumn_Threads_ContextSwitches.AutoSizeMode = System.Windows.Forms.DataGridViewAutoSizeColumnMode.ColumnHeader; this.dataGridViewTextBoxColumn_Threads_ContextSwitches.HeaderText = "# Context Switches"; this.dataGridViewTextBoxColumn_Threads_ContextSwitches.Name = "dataGridViewTextBoxColumn_Threads_ContextSwitches"; this.dataGridViewTextBoxColumn_Threads_ContextSwitches.ReadOnly = true; this.dataGridViewTextBoxColumn_Threads_ContextSwitches.Width = 114; // // dataGridViewTextBoxColumn_Threads_Method // this.dataGridViewTextBoxColumn_Threads_Method.AutoSizeMode = System.Windows.Forms.DataGridViewAutoSizeColumnMode.Fill; this.dataGridViewTextBoxColumn_Threads_Method.HeaderText = "Method"; this.dataGridViewTextBoxColumn_Threads_Method.Name = "dataGridViewTextBoxColumn_Threads_Method"; this.dataGridViewTextBoxColumn_Threads_Method.ReadOnly = true; // // ThreadsView // this.AutoScaleDimensions = new System.Drawing.SizeF( 6F, 13F ); this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font; this.Controls.Add( this.dataGridView_Threads ); this.Name = "ThreadsView"; this.Size = new System.Drawing.Size( 543, 483 ); ((System.ComponentModel.ISupportInitialize)(this.dataGridView_Threads)).EndInit(); this.ResumeLayout( false ); } #endregion private System.Windows.Forms.DataGridView dataGridView_Threads; private System.Windows.Forms.DataGridViewImageColumn dataGridViewTextBoxColumn_Threads_Flags; private System.Windows.Forms.DataGridViewTextBoxColumn dataGridViewTextBoxColumn_Threads_Id; private System.Windows.Forms.DataGridViewTextBoxColumn dataGridViewTextBoxColumn_Threads_Time; private System.Windows.Forms.DataGridViewTextBoxColumn dataGridViewTextBoxColumn_Threads_ContextSwitches; private System.Windows.Forms.DataGridViewTextBoxColumn dataGridViewTextBoxColumn_Threads_Method; } } ================================================ FILE: Zelig/Zelig/DebugTime/Debugger/UserControls/ThreadsView.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // namespace Microsoft.Zelig.Debugger.ArmProcessor { using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Text; using System.IO; using System.Windows.Forms; using System.Threading; using EncDef = Microsoft.Zelig.TargetModel.ArmProcessor.EncodingDefinition; using IR = Microsoft.Zelig.CodeGeneration.IR; using RT = Microsoft.Zelig.Runtime; using TS = Microsoft.Zelig.Runtime.TypeSystem; using Hst = Microsoft.Zelig.Emulation.Hosting; public partial class ThreadsView : UserControl { // // State // DebuggerMainForm m_owner; Icon m_icon_CurrentStatement = Properties.Resources.CurrentStatement; Icon m_icon_StackFrame = Properties.Resources.StackFrame; Icon m_icon_EmptyIcon = Properties.Resources.EmptyIcon; // // Constructor Methods // public ThreadsView() { InitializeComponent(); } // // Helper Methods // public void Link( DebuggerMainForm owner ) { m_owner = owner; m_owner.HostingSite.NotifyOnExecutionStateChange += ExecutionStateChangeNotification; } public Hst.Forms.HostingSite.NotificationResponse ExecutionStateChangeNotification( Hst.Forms.HostingSite host , Hst.Forms.HostingSite.ExecutionState oldState , Hst.Forms.HostingSite.ExecutionState newState ) { dataGridView_Threads.SuspendLayout(); DataGridViewRowCollection rows = dataGridView_Threads.Rows; dataGridView_Threads.Enabled = (m_owner.ActiveThread != null); if(m_owner.ActiveThread == null || host.IsIdle == false) { DebuggerMainForm.GrayOutRowsInDataGridView( rows ); } else { rows.Clear(); ulong total = 0; foreach(ThreadStatus ts in m_owner.Threads) { total += ts.ActiveTime.TotalTime; } if(total == 0) { total = 1; } foreach(ThreadStatus ts in m_owner.Threads) { Icon icon; string kind; string id; if(ts == m_owner.SelectedThread) { icon = m_icon_CurrentStatement; } else if(ts == m_owner.ActiveThread) { icon = m_icon_StackFrame; } else { icon = m_icon_EmptyIcon; } if(ts.ThreadObject != null) { id = string.Format( ts.ManagedThreadId != -1 ? "{0} [0x{1:X8}]" : "0x{1:X8}", ts.ManagedThreadId, ts.ThreadObject.Address ); } else { id = string.Format( "{0}", ts.ManagedThreadId ); } switch(ts.ThreadKind) { case ThreadStatus.Kind.Bootstrap : kind = " "; break; case ThreadStatus.Kind.InterruptThread : kind = " " ; break; case ThreadStatus.Kind.FastInterruptThread: kind = " " ; break; case ThreadStatus.Kind.IdleThread : kind = " " ; break; default : kind = "" ; break; } if(ts.TopMethod != null) { kind += ts.TopMethod.ToShortString(); } double cpuTime = 100.0 * ts.ActiveTime.TotalTime / total; int rowNum = rows.Add( icon, id, cpuTime.ToString( "###.##" ), ts.ActiveTime.Hits.ToString(), kind ); var row = rows[rowNum]; row.Tag = ts; row.Cells[4].ToolTipText = ts.ToString(); } } dataGridView_Threads.ResumeLayout(); return Hst.Forms.HostingSite.NotificationResponse.DoNothing; } // // Access Methods // // // Event Methods // private void dataGridView_Threads_CellContentClick( object sender , DataGridViewCellEventArgs e ) { var rows = dataGridView_Threads.Rows; if(e.RowIndex >= 0 && e.RowIndex < rows.Count) { var ts = rows[e.RowIndex].Tag as ThreadStatus; if(ts != null) { m_owner.Action_SelectThread( m_owner.Threads.IndexOf( ts ) ); } } } } } ================================================ FILE: Zelig/Zelig/DebugTime/Debugger/UserControls/ThreadsView.resx ================================================ text/microsoft-resx 2.0 System.Resources.ResXResourceReader, System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 System.Resources.ResXResourceWriter, System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 True True ================================================ FILE: Zelig/Zelig/DebugTime/Debugger/UserControls/TreeBasedGridView.Designer.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // namespace Microsoft.Zelig.Debugger.ArmProcessor { partial class TreeBasedGridView { /// /// Required designer variable. /// private System.ComponentModel.IContainer components = null; /// /// Clean up any resources being used. /// /// true if managed resources should be disposed; otherwise, false. protected override void Dispose(bool disposing) { if (disposing && (components != null)) { components.Dispose(); } base.Dispose(disposing); } #region Component Designer generated code /// /// Required method for Designer support - do not modify /// the contents of this method with the code editor. /// private void InitializeComponent() { this.dataGridView1 = new System.Windows.Forms.DataGridView(); ((System.ComponentModel.ISupportInitialize)(this.dataGridView1)).BeginInit(); this.SuspendLayout(); // // dataGridView1 // this.dataGridView1.AllowUserToAddRows = false; this.dataGridView1.AllowUserToDeleteRows = false; this.dataGridView1.AllowUserToResizeRows = false; this.dataGridView1.BorderStyle = System.Windows.Forms.BorderStyle.None; this.dataGridView1.ColumnHeadersBorderStyle = System.Windows.Forms.DataGridViewHeaderBorderStyle.None; this.dataGridView1.ColumnHeadersHeight = 20; this.dataGridView1.ColumnHeadersHeightSizeMode = System.Windows.Forms.DataGridViewColumnHeadersHeightSizeMode.DisableResizing; this.dataGridView1.Dock = System.Windows.Forms.DockStyle.Fill; this.dataGridView1.EditMode = System.Windows.Forms.DataGridViewEditMode.EditProgrammatically; this.dataGridView1.Location = new System.Drawing.Point( 0, 0 ); this.dataGridView1.MultiSelect = false; this.dataGridView1.Name = "dataGridView1"; this.dataGridView1.RowHeadersBorderStyle = System.Windows.Forms.DataGridViewHeaderBorderStyle.Single; this.dataGridView1.RowHeadersWidth = 4; this.dataGridView1.RowHeadersWidthSizeMode = System.Windows.Forms.DataGridViewRowHeadersWidthSizeMode.DisableResizing; this.dataGridView1.RowTemplate.Height = 20; this.dataGridView1.RowTemplate.Resizable = System.Windows.Forms.DataGridViewTriState.False; this.dataGridView1.SelectionMode = System.Windows.Forms.DataGridViewSelectionMode.FullRowSelect; this.dataGridView1.ShowCellErrors = false; this.dataGridView1.ShowEditingIcon = false; this.dataGridView1.ShowRowErrors = false; this.dataGridView1.Size = new System.Drawing.Size( 496, 496 ); this.dataGridView1.TabIndex = 0; this.dataGridView1.ColumnHeaderMouseClick += new System.Windows.Forms.DataGridViewCellMouseEventHandler( this.dataGridView1_ColumnHeaderMouseClick ); this.dataGridView1.ColumnHeaderMouseDoubleClick += new System.Windows.Forms.DataGridViewCellMouseEventHandler( this.dataGridView1_ColumnHeaderMouseDoubleClick ); this.dataGridView1.CellMouseClick += new System.Windows.Forms.DataGridViewCellMouseEventHandler( this.dataGridView1_CellMouseClick ); this.dataGridView1.CellMouseDoubleClick += new System.Windows.Forms.DataGridViewCellMouseEventHandler( this.dataGridView1_CellMouseDoubleClick ); this.dataGridView1.CellEndEdit += new System.Windows.Forms.DataGridViewCellEventHandler( this.dataGridView1_CellEndEdit ); this.dataGridView1.KeyDown += new System.Windows.Forms.KeyEventHandler( this.dataGridView1_KeyDown ); // // TreeBasedGridView // this.AutoScaleDimensions = new System.Drawing.SizeF( 6F, 13F ); this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font; this.BorderStyle = System.Windows.Forms.BorderStyle.Fixed3D; this.Controls.Add( this.dataGridView1 ); this.DoubleBuffered = true; this.Name = "TreeBasedGridView"; this.Size = new System.Drawing.Size( 496, 496 ); ((System.ComponentModel.ISupportInitialize)(this.dataGridView1)).EndInit(); this.ResumeLayout( false ); } #endregion private System.Windows.Forms.DataGridView dataGridView1; } } ================================================ FILE: Zelig/Zelig/DebugTime/Debugger/UserControls/TreeBasedGridView.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // namespace Microsoft.Zelig.Debugger.ArmProcessor { using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Text; using System.IO; using System.Windows.Forms; using System.Threading; using EncDef = Microsoft.Zelig.TargetModel.ArmProcessor.EncodingDefinition; using InstructionSet = Microsoft.Zelig.TargetModel.ArmProcessor.InstructionSet; using IR = Microsoft.Zelig.CodeGeneration.IR; using RT = Microsoft.Zelig.Runtime; using TS = Microsoft.Zelig.Runtime.TypeSystem; public partial class TreeBasedGridView : UserControl { public class NodeMouseEventArgs : System.Windows.Forms.MouseEventArgs { // // State // public readonly GridNode SelectedNode; public readonly int SelectedColumn; // // Constructor Methods // internal NodeMouseEventArgs( GridNode selectedNode , int selectedColumn , MouseButtons button , int clicks , int x , int y , int delta ) : base( button, clicks, x, y, delta ) { this.SelectedNode = selectedNode; this.SelectedColumn = selectedColumn; } // // Access Methods // } public delegate void NodeMouseEventHandler( Object sender, NodeMouseEventArgs e ); //--// public class GridColumnDefinition { // // State // public readonly string Name; public readonly DataGridViewContentAlignment Alignment; public readonly bool UseIcon; public readonly bool IsEditable; public readonly bool HighlightOnChange; // // Constructor Methods // public GridColumnDefinition( string name , DataGridViewContentAlignment alignment , bool useIcon , bool isEditable , bool highlightOnChange ) { this.Name = name; this.Alignment = alignment; this.UseIcon = useIcon; this.IsEditable = isEditable; this.HighlightOnChange = highlightOnChange; } } public class GridNode { public delegate void ExpandDelegate( GridNode node ); public delegate bool UpdateDelegate( GridNode node, string proposedValue, int index ); // // State // private readonly TreeBasedGridView m_owner; private DataGridViewRow m_row; private GridNode m_parent; private LinkedListNode< GridNode > m_parentNode; private readonly LinkedList< GridNode > m_childNodes = new LinkedList< GridNode >(); private int m_depth = -1; private bool m_fPopulated; private Icon m_icon; private readonly string[] m_values; private object m_tag; private bool m_fIsExpanded; private bool m_fChanged; private ExpandDelegate m_expandCallback; private UpdateDelegate m_updateCallback; // // Constructor Methods // internal GridNode( TreeBasedGridView owner ) { m_owner = owner; m_values = new string[owner.m_columnDefinitions.Count]; } internal GridNode( TreeBasedGridView owner , string[] values , GridNode parent , LinkedListNode< GridNode > anchor , bool fAfter ) : this( owner ) { for(int i = 0; i < m_values.Length; i++) { if(i < values.Length) { m_values[i] = values[i]; } else { m_values[i] = ""; } } //--// m_parent = parent; m_depth = parent.Depth + 1; var nodes = parent.m_childNodes; if(anchor != null) { if(fAfter) { m_parentNode = nodes.AddAfter( anchor, this ); } else { m_parentNode = nodes.AddBefore( anchor, this ); } } else { m_parentNode = nodes.AddLast( this ); } this.IsVisible = parent.IsVisible && parent.IsExpanded; } // // Helper Methods // public void Select() { if(m_row != null) { m_owner.dataGridView1.ClearSelection(); m_row.Selected = true; } } public void Remove() { if(m_parentNode != null) { m_parent.m_childNodes.Remove( m_parentNode ); m_parent = null; m_parentNode = null; m_depth = -1; } this.IsVisible = false; } public void Clear() { m_owner.StartTreeUpdate(); while(m_childNodes.First != null) { m_childNodes.First.Value.Remove(); } m_owner.EndTreeUpdate(); } public void Invalidate() { Clear(); m_fPopulated = false; } public GridNode AddChild( params string[] values ) { return new GridNode( m_owner, values, this, null, false ); } public GridNode AddBefore( params string[] values ) { return new GridNode( m_owner, values, m_parent, m_parentNode, false ); } public GridNode AddAfter( params string[] values ) { return new GridNode( m_owner, values, m_parent, m_parentNode, true ); } public bool Enumerate( EnumerateDelegate dlg ) { foreach(var node in GetPreOrderEnumerator()) { if(dlg( node ) == false) { return false; } } return true; } private IEnumerable< GridNode > GetPreOrderEnumerator() { yield return this; var child = m_childNodes.First; while(child != null) { var nextChild = child.Next; foreach(var subNode in child.Value.GetPreOrderEnumerator()) { yield return subNode; } child = nextChild; } } internal void UpdateColor() { if(m_row != null) { var cols = m_owner.m_columnDefinitions; int numCols = cols.Count; for(int i = 0; i < numCols; i++) { if(cols[i].HighlightOnChange) { m_row.Cells[i].Style.ForeColor = m_fChanged ? Color.Red : m_row.Cells[0].Style.ForeColor; } } } } private void EnsurePopulated() { if(m_fPopulated == false) { m_fPopulated = true; if(m_expandCallback != null) { m_expandCallback( this ); } } } // // Access Methods // public ExpandDelegate ExpandCallback { get { return m_expandCallback; } set { m_expandCallback = value; } } public UpdateDelegate UpdateCallback { get { return m_updateCallback; } set { m_updateCallback = value; } } public TreeBasedGridView Owner { get { return m_owner; } } public GridNode Parent { get { return m_parent; } } public LinkedList< GridNode > ChildNodes { get { EnsurePopulated(); return m_childNodes; } } public LinkedList< GridNode > ChildNodesNoPopulate { get { return m_childNodes; } } public GridNode[] ArrayOfChildNodesNoPopulate { get { var lst = this.ChildNodesNoPopulate; var res = new GridNode[lst.Count]; int pos = 0; foreach(var node in lst) { res[pos++] = node; } return res; } } public bool UseIcon { get { return m_owner.m_columnDefinitions[0].UseIcon; } } public Icon Icon { get { return m_icon; } set { m_icon = value; } } public string this[int index] { get { return m_values[index]; } set { if(m_values[index] != value) { m_values[index] = value; if(m_row != null) { m_row.Cells[index].Value = value; } } } } public object Tag { get { return m_tag; } set { m_tag = value; } } public bool HasChanged { get { return m_fChanged; } set { if(m_fChanged != value) { m_fChanged = value; UpdateColor(); } } } public int Depth { get { return m_depth; } } public bool IsExpanded { get { // // The root is always expanded. // if(this.IsRoot) { return true; } return m_fIsExpanded; } set { if(m_fIsExpanded != value) { m_owner.StartTreeUpdate(); m_fIsExpanded = value; foreach(var child in this.ChildNodes) { child.IsVisible = m_fIsExpanded; } m_owner.EndTreeUpdate(); } } } public bool IsRoot { get { return m_owner.m_root == this; } } public bool IsVisible { get { // // Special case for the root: always visible, even if it doesn't have a UI element. // if(this.IsRoot) { return true; } return m_row != null; } internal set { bool fIsVisible = this.IsVisible; if(fIsVisible != value) { m_owner.StartTreeUpdate(); var rows = m_owner.dataGridView1.Rows; if(value) { DataGridViewRow row = new DataGridViewRow(); m_row = row; row.Height = m_owner.dataGridView1.RowTemplate.Height; row.Tag = this; var cols = m_owner.m_columnDefinitions; int numCols = cols.Count; var cells = new DataGridViewCell[ numCols ]; for(int i = 0; i < numCols; i++) { var cell = i == 0 ? new GridNodeCell() : new DataGridViewTextBoxCell(); cells[i] = cell; cell.Value = this[i]; } row.Cells.AddRange( cells ); if(m_fChanged) { UpdateColor(); } //--// var prevNode = this.PreviousVisibleNode; if(prevNode == null) { rows.Add( m_row ); } else if(prevNode.IsRoot) { rows.Insert( 0, m_row ); } else { rows.Insert( prevNode.m_row.Index + 1, m_row ); } //--// if(this.IsExpanded) { foreach(var child in this.ChildNodes) { child.IsVisible = true; } } } else { foreach(var child in this.ChildNodesNoPopulate) { child.IsVisible = false; } rows.Remove( m_row ); m_row = null; } m_owner.EndTreeUpdate(); } } } private GridNode PreviousVisibleNode { get { if(m_parentNode == null) { return null; } var node = m_parentNode.Previous; if(node == null) { return m_parent; } while(true) { var lastChild = node.Value.LastVisibleChild; if(lastChild == null) { return node.Value; } node = lastChild; } } } private LinkedListNode< GridNode > LastVisibleChild { get { var node = m_childNodes.Last; while(node != null) { if(node.Value.IsVisible) { return node; } node = node.Previous; } return null; } } public bool HasNodes { get { return this.ChildNodes.First != null; } } public bool IsUpdatable { get { return (m_updateCallback != null); } } public bool IsLastInList { get { // used for drawing tree lines by cell return m_parentNode.Next == null; } } } class GridNodeCell : DataGridViewTextBoxCell { const int c_IndentationX = 20; const int c_LineOffsetX = 9; const int c_IconSizeX = 16; const int c_IconSizeY = 16; const int c_IconOffsetX = 2; const int c_IconOffsetY = 2; const int c_UserIconOffsetX = 18; const int c_UserIconOffsetY = 2; const int c_TreeIconMarginX = 3; const int c_TreeIconMarginY = 3; const int c_TreeIconSizeX = 9; const int c_TreeIconSizeY = 9; // // Constructor Methods // internal GridNodeCell() { } // // Helper Methods // protected override Rectangle GetContentBounds( Graphics graphics , DataGridViewCellStyle cellStyle , int rowIndex ) { // get the node reference at this row GridNode node = (GridNode)this.DataGridView.Rows[this.RowIndex].Tag; int width = c_IndentationX + (node.UseIcon ? c_IconSizeX : 0); var res = base.GetContentBounds( graphics, cellStyle, rowIndex ); // pad text to include space for tree lines and icons, plus indent to show tree depth res.Inflate( (node.Depth * c_IndentationX) + width, 0 ); return res; } protected override Size GetPreferredSize( Graphics graphics , DataGridViewCellStyle cellStyle , int rowIndex , Size constraintSize ) { // get the node reference at this row GridNode node = (GridNode)this.DataGridView.Rows[this.RowIndex].Tag; int width = c_IndentationX + (node.UseIcon ? c_IconSizeX : 0); Size res = base.GetPreferredSize( graphics, cellStyle, rowIndex, constraintSize ); // pad text to include space for tree lines and icons, plus indent to show tree depth return new Size( res.Width + (node.Depth * c_IndentationX) + width, res.Height ); } protected override void Paint( Graphics graphics , Rectangle clipBounds , Rectangle cellBounds , int rowIndex , DataGridViewElementStates cellState , object value , object formattedValue , string errorText , DataGridViewCellStyle cellStyle , DataGridViewAdvancedBorderStyle advancedBorderStyle , DataGridViewPaintParts paintParts ) { // get the node reference at this row GridNode node = (GridNode)this.DataGridView.Rows[this.RowIndex].Tag; int width = c_IndentationX + (node.UseIcon ? c_IconSizeX : 0); // pad text to include space for tree lines and icons, plus indent to show tree depth cellStyle.Padding = new Padding( cellStyle.Padding.Left + (node.Depth * c_IndentationX) + width, cellStyle.Padding.Top, cellStyle.Padding.Right, cellStyle.Padding.Bottom ); // allow base to paint text base.Paint( graphics, clipBounds, cellBounds, rowIndex, cellState, value, formattedValue, errorText, cellStyle, advancedBorderStyle, paintParts ); // pen for tree lines Pen linePen = new Pen( Brushes.DarkGray ); int xNodeLeft = cellBounds.Left; int yNodeTop = cellBounds.Top; int yNodeBottom = cellBounds.Bottom; int yNodeMiddle = yNodeTop + (yNodeBottom - yNodeTop) / 2; // make sure we aren't drawing tree lines for the root level nodes in the grid if(node.Depth > 0) { // walk up the tree to figure out what lines need to be drawn for the previous levels GridNode tempNode = node.Parent; for(int i = 1; i < node.Depth; i++) { if(tempNode.IsLastInList == false) { int x = xNodeLeft + ((tempNode.Depth - 1) * c_IndentationX) + c_LineOffsetX; // draw line for ancestor that has graphics.DrawLine( linePen, x, yNodeTop, x, yNodeBottom ); } tempNode = tempNode.Parent; } int xNode = xNodeLeft + ((node.Depth - 1) * c_IndentationX) + c_LineOffsetX; // draw the line protruding from parent down to middle of row graphics.DrawLine( linePen, new Point( xNode, yNodeTop ), new Point( xNode, yNodeMiddle ) ); // draw the line from middle of row pointing out to value graphics.DrawLine( linePen, new Point( xNode, yNodeMiddle ), new Point( xNode + c_IndentationX, yNodeMiddle ) ); // draw the line protruding down to the next node if this is not the last in list if(node.IsLastInList == false) { graphics.DrawLine(linePen, new Point( xNode, yNodeMiddle ), new Point( xNode, yNodeBottom ) ); } } { int xNode = xNodeLeft + (node.Depth * c_IndentationX); if(node.Icon != null) { Rectangle variableIconBounds = new Rectangle( xNode + c_UserIconOffsetX, yNodeTop + c_UserIconOffsetY, c_IconSizeX, c_IconSizeY ); graphics.DrawIconUnstretched( node.Icon, variableIconBounds ); } // draw tree expand/collapse icon if this is a parent if(node.HasNodes) { Rectangle treeIconBounds = new Rectangle( xNode + c_IconOffsetX, yNodeTop + c_IconOffsetY, c_IconSizeX, c_IconSizeY ); if(node.IsExpanded) { // draw the line protruding down from the tree graphics.DrawLine( linePen, new Point( xNode + c_LineOffsetX, yNodeMiddle ), new Point( xNode + c_LineOffsetX, yNodeBottom ) ); // draw the icon over the line graphics.DrawIconUnstretched( TreeBasedGridView.NodeExpanded, treeIconBounds ); } else { graphics.DrawIconUnstretched( TreeBasedGridView.NodeCollapsed, treeIconBounds ); } } } // dispose the pen linePen.Dispose(); } internal static bool HitIcon( GridNode node , DataGridViewCellMouseEventArgs e ) { var hit = new Rectangle( c_IconOffsetX + c_TreeIconMarginX + node.Depth * c_IndentationX, c_IconOffsetY + c_TreeIconMarginY, c_TreeIconSizeX, c_TreeIconSizeY ); return hit.Contains( e.X, e.Y ); } } public delegate bool EnumerateDelegate( GridNode node ); //--// // // State // static Icon NodeCollapsed = Properties.Resources.NodeCollapsed; static Icon NodeExpanded = Properties.Resources.NodeExpanded; private GridNode m_root; private int m_suspendCount; private NodeMouseEventHandler m_eventHeaderMouseClick; private NodeMouseEventHandler m_eventHeaderMouseDoubleClick; private NodeMouseEventHandler m_eventNodeMouseClick; private NodeMouseEventHandler m_eventNodeMouseDoubleClick; private readonly List< GridColumnDefinition > m_columnDefinitions = new List< GridColumnDefinition >(); // // Constructor Methods // public TreeBasedGridView() { InitializeComponent(); } // // Helper Methods // public void SetColumns( params GridColumnDefinition[] colDefs ) { m_columnDefinitions.Clear(); this.SuspendLayout(); var columns = this.dataGridView1.Columns; columns.Clear(); foreach(var colDef in colDefs) { var newCol = new DataGridViewTextBoxColumn(); newCol.HeaderText = colDef.Name; newCol.Name = colDef.Name; newCol.SortMode = DataGridViewColumnSortMode.NotSortable; newCol.DefaultCellStyle = new DataGridViewCellStyle(); newCol.DefaultCellStyle.Alignment = colDef.Alignment; columns.Add( newCol ); m_columnDefinitions.Add( colDef ); } this.dataGridView1.Rows.Clear(); this.ResumeLayout( false ); //--// m_root = new GridNode( this ); } public void StartTreeUpdate() { if(m_suspendCount++ == 0) { dataGridView1.SuspendLayout(); } } public void EndTreeUpdate() { if(--m_suspendCount == 0) { dataGridView1.ResumeLayout(); } } public void EnumerateNodesPreOrder( EnumerateDelegate dlg ) { m_root.Enumerate( dlg ); } //--// GridNode GetSelectedNode( DataGridViewCellEventArgs e ) { return GetSelectedNode( e.RowIndex, e.ColumnIndex ); } GridNode GetSelectedNode( DataGridViewCellMouseEventArgs e ) { return GetSelectedNode( e.RowIndex, e.ColumnIndex ); } GridNode GetSelectedNode( int rowIndex , int columnIndex ) { // leave if we are a header row if(rowIndex == -1 || columnIndex == -1) { return null; } var row = dataGridView1.Rows[rowIndex]; return row.Tag as GridNode; } //--// private void NotifyNodeMouseClick( NodeMouseEventHandler eventHeader , GridNode node , MouseEventArgs e , int rowIndex , int columnIndex ) { if(eventHeader != null) { var rec = dataGridView1.GetCellDisplayRectangle( columnIndex, rowIndex, false ); var ev = new NodeMouseEventArgs( node, columnIndex, e.Button, e.Clicks, rec.Left, rec.Top, e.Delta ); eventHeader( this, ev ); } } // // Access Methods // public GridNode RootNode { get { return m_root; } } public DataGridViewRowCollection Rows { get { return dataGridView1.Rows; } } public event NodeMouseEventHandler NodeMouseClick { add { m_eventNodeMouseClick += value; } remove { m_eventNodeMouseClick -= value; } } public event NodeMouseEventHandler NodeMouseDoubleClick { add { m_eventNodeMouseDoubleClick += value; } remove { m_eventNodeMouseDoubleClick -= value; } } public event NodeMouseEventHandler HeaderMouseClick { add { m_eventHeaderMouseClick += value; } remove { m_eventHeaderMouseClick -= value; } } public event NodeMouseEventHandler HeaderMouseDoubleClick { add { m_eventHeaderMouseDoubleClick += value; } remove { m_eventHeaderMouseDoubleClick -= value; } } // // Events Methods // private void dataGridView1_ColumnHeaderMouseClick( object sender , DataGridViewCellMouseEventArgs e ) { NotifyNodeMouseClick( m_eventHeaderMouseClick, null, e, e.RowIndex, e.ColumnIndex ); } private void dataGridView1_ColumnHeaderMouseDoubleClick( object sender , DataGridViewCellMouseEventArgs e ) { NotifyNodeMouseClick( m_eventHeaderMouseDoubleClick, null, e, e.RowIndex, e.ColumnIndex ); } private void dataGridView1_CellMouseClick( object sender , DataGridViewCellMouseEventArgs e ) { GridNode node = GetSelectedNode( e ); if(node != null) { NotifyNodeMouseClick( m_eventNodeMouseClick, node, e, e.RowIndex, e.ColumnIndex ); if(e.ColumnIndex == 0 && GridNodeCell.HitIcon( node, e )) { if(node.HasNodes) { node.IsExpanded = !node.IsExpanded; } } } } private void dataGridView1_CellMouseDoubleClick( object sender , DataGridViewCellMouseEventArgs e ) { GridNode node = GetSelectedNode( e ); // check to see if we are in the value column and initiate editing if(node != null) { NotifyNodeMouseClick( m_eventNodeMouseDoubleClick, node, e, e.RowIndex, e.ColumnIndex ); if(m_columnDefinitions[e.ColumnIndex].IsEditable) { // if we don't have a callback for the update then skip editing if(node.IsUpdatable) { dataGridView1.BeginEdit( true ); } } else if(e.ColumnIndex == 0) { if(node.HasNodes) { node.IsExpanded = !node.IsExpanded; } } } } private void dataGridView1_CellEndEdit( object sender , DataGridViewCellEventArgs e ) { var row = dataGridView1.Rows[e.RowIndex]; GridNode node = (GridNode)row.Tag; int index = e.ColumnIndex; var cell = row.Cells[index]; if(node.UpdateCallback != null) { string proposedValue = (string)cell.Value; if(node.UpdateCallback( node, proposedValue, index )) { node[index] = proposedValue; cell.Value = proposedValue; node.HasChanged = true; return; } } // if there is not an update callback then we will not perform the edit cell.Value = node[index]; } private void dataGridView1_KeyDown( object sender , KeyEventArgs e ) { if(e.Modifiers == Keys.None) { var coll = dataGridView1.SelectedRows; if(coll.Count == 1) { var row = coll[0]; GridNode node = (GridNode)row.Tag; if(e.KeyCode == Keys.Left) { if(node.IsExpanded) { node.IsExpanded = false; } else { var parent = node.Parent; if(parent != null) { parent.Select(); } } e.Handled = true; return; } if(e.KeyCode == Keys.Right) { if(!node.IsExpanded) { node.IsExpanded = true; } else if(node.HasNodes) { var child = node.ChildNodes.First.Value; child.Select(); } e.Handled = true; return; } } } } } } ================================================ FILE: Zelig/Zelig/DebugTime/Debugger/UserControls/TreeBasedGridView.resx ================================================ text/microsoft-resx 2.0 System.Resources.ResXResourceReader, System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 System.Resources.ResXResourceWriter, System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 ================================================ FILE: Zelig/Zelig/DebugTime/Debugger/VisualTree/GraphicsContext.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // namespace Microsoft.Zelig.Debugger.ArmProcessor { using System; using System.Collections.Generic; using System.ComponentModel; using System.Drawing; using System.Data; using System.Text; using System.Windows.Forms; using IR = Microsoft.Zelig.CodeGeneration.IR; public class GraphicsContext { // // State // public Graphics Gfx; public Font DefaultFont; public Brush DefaultBrush; // // Constructor Methods // public GraphicsContext( Font defaultFont , Bitmap bm ) { this.DefaultFont = defaultFont; this.DefaultBrush = SystemBrushes.WindowText; if(bm == null) { bm = new Bitmap( 32, 32 ); } this.Gfx = Graphics.FromImage( bm ); } // // Helper Methods // public void DrawStringWithDefault( string text , Font font , Brush brush , PointF absoluteOrigin ) { if(font == null) { font = this.DefaultFont; } if(brush == null) { brush = this.DefaultBrush; } this.Gfx.DrawString( text, font, brush, absoluteOrigin, StringFormat.GenericTypographic ); } public SizeF MeasureString( string text , Font font ) { if(font == null) { font = this.DefaultFont; } return this.Gfx.MeasureString( text, font, int.MaxValue, StringFormat.GenericTypographic ); } public float CharSize( Font font ) { return this.MeasureString( "A", font ).Width; } public float CharHeight( Font font ) { if(font == null) { font = this.DefaultFont; } return font.Height; } public bool IsVisible( RectangleF bounds ) { return this.Gfx.IsVisible( bounds ); } } } ================================================ FILE: Zelig/Zelig/DebugTime/Debugger/VisualTree/VisualEffects/InlineDisassembly.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // namespace Microsoft.Zelig.Debugger.ArmProcessor { using System; using System.Collections.Generic; using System.ComponentModel; using System.Drawing; using System.Data; using System.Text; using System.Windows.Forms; using IR = Microsoft.Zelig.CodeGeneration.IR; public abstract partial class VisualEffect { public sealed class InlineDisassembly : VisualEffect { // // Constructor Methods // public InlineDisassembly( VisualTreeInfo owner , ContainerVisualItem line , GraphicsContext ctx , ImageInformation.DisassemblyLine[] data , int depth ) : base( owner ) { GenerateView( line, ctx, data, depth ); } // // Helper Methods // public override void Clear() { foreach(VisualItem item in this.Items) { item.RemoveVerticalSpace(); } this.Items.Clear(); } //--// private void GenerateView( ContainerVisualItem line , GraphicsContext ctx , ImageInformation.DisassemblyLine[] data , int depth ) { if(line != null) { ContainerVisualItem box = new ContainerVisualItem( null ); box.BorderPen = Pens.Red; box.BackgroundBrush = Brushes.Pink; box.Depth = depth; PointF ptLine = new PointF( 0, 0 ); float stepY = ctx.CharHeight( null ); for(int i = 0; i < data.Length; i++) { var disasm = data[i]; var item = new TextVisualItem( disasm, " " + disasm.Text ); item.RelativeOrigin = ptLine; item.TextBrush = Brushes.Gray; item.Depth = depth; item.PrepareText( ctx ); ptLine.Y += stepY; box.Add( item ); } line.ExpandVerticalSpaceAfter( box ); this.Items.Add( box ); } } } } } ================================================ FILE: Zelig/Zelig/DebugTime/Debugger/VisualTree/VisualEffects/SourceCodeHighlight.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // namespace Microsoft.Zelig.Debugger.ArmProcessor { using System; using System.Collections.Generic; using System.ComponentModel; using System.Drawing; using System.Data; using System.Text; using System.Windows.Forms; using IR = Microsoft.Zelig.CodeGeneration.IR; public abstract partial class VisualEffect { public sealed class SourceCodeHighlight : VisualEffect { // // State // public ContainerVisualItem TopSelectedLine; // // Constructor Methods // public SourceCodeHighlight( VisualTreeInfo owner , uint address , Debugging.DebugInfo di , Icon icon , Pen backgroundBorder , Brush backgroundFill , int depth ) : base( owner ) { if(di != null) { ContainerVisualItem topLine = null; for(int lineNum = di.BeginLineNumber; lineNum <= di.EndLineNumber; lineNum++) { ContainerVisualItem line = owner.FindLine( lineNum ); if(line != null) { if(topLine == null) { topLine = line; } RectangleF maximumBounds = new RectangleF(); bool fGot = false; line.EnumerateTree( delegate( VisualItem item ) { BaseTextVisualItem lineItem = item as BaseTextVisualItem; if(lineItem != null) { Debugging.DebugInfo di2 = lineItem.Context as Debugging.DebugInfo; if(di2 != null) { Debugging.DebugInfo diIntersection = di.ComputeIntersection( di2 ); if(diIntersection != null) { RectangleF bounds = lineItem.RelativeBounds; PointF absPosItem = lineItem.AbsoluteOrigin; PointF absPosLine = line .AbsoluteOrigin; PointF relPosItem = new PointF(); float step = bounds.Width / (di2.EndColumn - di2.BeginColumn); relPosItem.X = (absPosItem.X - absPosLine.X) + (diIntersection.BeginColumn - di2.BeginColumn) * step; relPosItem.Y = (absPosItem.Y - absPosLine.Y); bounds.Offset( relPosItem ); bounds.Width = (diIntersection.EndColumn - diIntersection.BeginColumn) * step; if(fGot) { maximumBounds = RectangleF.Union( maximumBounds, bounds ); } else { fGot = true; maximumBounds = bounds; } } } } return false; } ); if(fGot) { //maximumBounds.X -= 1; maximumBounds.Y -= 1; //maximumBounds.Width += 2; maximumBounds.Height += 2; if(backgroundBorder != null || backgroundFill != null ) { BackgroundVisualItem highlightItem = new BackgroundVisualItem( di, backgroundBorder, backgroundFill, depth ); PointF relPosItem = new PointF(); relPosItem.X = maximumBounds.X; relPosItem.Y = maximumBounds.Y; highlightItem.RelativeOrigin = relPosItem; maximumBounds.X -= relPosItem.X; maximumBounds.Y -= relPosItem.Y; highlightItem.RelativeBounds = maximumBounds; { int pos = line.Children.Count; while(--pos >= 0) { BackgroundVisualItem item = line.Children[pos] as BackgroundVisualItem; if(item != null && item.Depth > depth) { break; } } line.InsertAt( highlightItem, pos + 1 ); } this.Items.Add( highlightItem ); } //--// if(icon != null) { IconVisualItem iconItem = new IconVisualItem( di, icon, depth ); PointF relPosItem = new PointF(); PointF absOrigin = line.AbsoluteOrigin; relPosItem.X = -absOrigin.X; relPosItem.Y = maximumBounds.Y; iconItem.RelativeOrigin = relPosItem; iconItem.RelativeBounds = new RectangleF( 0, 0, icon.Width, icon.Height ); { int pos = line.Children.Count; while(--pos >= 0) { IconVisualItem item = line.Children[pos] as IconVisualItem; if(item != null && item.Depth > depth) { break; } } line.InsertAt( iconItem, pos + 1 ); } this.Items.Add( iconItem ); } } } } this.TopSelectedLine = topLine; } if(address != uint.MaxValue) { var workList = new List< BaseTextVisualItem >(); owner.VisualTreeRoot.EnumerateTree( delegate( VisualItem item ) { BaseTextVisualItem lineItem = item as BaseTextVisualItem; if(lineItem != null) { var disasm = lineItem.Context as ImageInformation.DisassemblyLine; if(disasm != null && disasm.Address == address) { workList.Add( lineItem ); } } return false; } ); foreach(var lineItem in workList) { var disasm = (ImageInformation.DisassemblyLine)lineItem.Context; RectangleF maximumBounds = lineItem.RelativeBounds; maximumBounds.Offset( lineItem.RelativeOrigin ); //maximumBounds.X -= 1; maximumBounds.Y -= 1; //maximumBounds.Width += 2; maximumBounds.Height += 2; if(icon != null) { IconVisualItem iconItem = new IconVisualItem( disasm, icon, depth ); PointF relPosItem = new PointF(); relPosItem.X = 0; relPosItem.Y = maximumBounds.Y; iconItem.RelativeOrigin = relPosItem; iconItem.RelativeBounds = new RectangleF( 0, 0, icon.Width, icon.Height ); lineItem.Parent.Add( iconItem ); this.Items.Add( iconItem ); } } } } } } } ================================================ FILE: Zelig/Zelig/DebugTime/Debugger/VisualTree/VisualEffects/VisualEffect.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // namespace Microsoft.Zelig.Debugger.ArmProcessor { using System; using System.Collections.Generic; using System.ComponentModel; using System.Drawing; using System.Data; using System.Text; using System.Windows.Forms; using IR = Microsoft.Zelig.CodeGeneration.IR; public abstract partial class VisualEffect { // // State // public int Version; public object Context; public VisualTreeInfo Owner; public List< VisualItem > Items; // // Constructor Methods // protected VisualEffect( VisualTreeInfo owner ) { this.Owner = owner; this.Items = new List< VisualItem >(); owner.VisualEffects.Add( this ); } // // Helper Methods // public virtual void Clear() { foreach(VisualItem item in this.Items) { item.Delete(); } this.Items.Clear(); } } } ================================================ FILE: Zelig/Zelig/DebugTime/Debugger/VisualTree/VisualItems/AddressVisualItem.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // namespace Microsoft.Zelig.Debugger.ArmProcessor { using System; using System.Collections.Generic; using System.ComponentModel; using System.Drawing; using System.Data; using System.Text; using System.Windows.Forms; using IR = Microsoft.Zelig.CodeGeneration.IR; public class AddressVisualItem : BaseTextVisualItem { // // State // uint m_address; // // Constructor Methods // public AddressVisualItem( object context , uint address ) : base( context ) { m_address = address; } // // Helper Methods // public override string ToString( GraphicsContext ctx ) { return String.Format( "[{0,8:X8}]", m_address ); } } } ================================================ FILE: Zelig/Zelig/DebugTime/Debugger/VisualTree/VisualItems/BackgroundVisualItem.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // namespace Microsoft.Zelig.Debugger.ArmProcessor { using System; using System.Collections.Generic; using System.ComponentModel; using System.Drawing; using System.Data; using System.Text; using System.Windows.Forms; using IR = Microsoft.Zelig.CodeGeneration.IR; public class BackgroundVisualItem : VisualItem { // // Constructor Methods // public BackgroundVisualItem( object context , Pen borderPen , Brush backgroundBrush , int depth ) : base( context ) { m_borderPen = borderPen; m_backgroundBrush = backgroundBrush; m_depth = depth; } // // Helper Methods // // // Access Methods // } } ================================================ FILE: Zelig/Zelig/DebugTime/Debugger/VisualTree/VisualItems/BaseTextVisualItem.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // namespace Microsoft.Zelig.Debugger.ArmProcessor { using System; using System.Collections.Generic; using System.ComponentModel; using System.Drawing; using System.Data; using System.Text; using System.Windows.Forms; using IR = Microsoft.Zelig.CodeGeneration.IR; public abstract class BaseTextVisualItem : VisualItem { // // State // protected Font m_font; protected Brush m_brush; protected string m_cachedText; // // Constructor Methods // protected BaseTextVisualItem( object context ) : base( context ) { } // // Helper Methods // public override bool Draw( GraphicsContext ctx , PointF absoluteOrigin , int depth ) { bool isVisible = base.Draw( ctx, absoluteOrigin, depth ); if(isVisible) { if(m_depth == depth) { absoluteOrigin.X += m_relativeOrigin.X; absoluteOrigin.Y += m_relativeOrigin.Y; ctx.DrawStringWithDefault( m_cachedText, m_font, m_brush, absoluteOrigin ); RectangleF bounds = this.RelativeBounds; bounds.Offset( absoluteOrigin ); bounds.Offset( this.RelativeOrigin ); } } return isVisible; } public void PrepareText( GraphicsContext ctx ) { if(m_cachedText == null) { m_cachedText = ToString( ctx ); SizeF size = ctx.MeasureString( m_cachedText, m_font ); this.RelativeBounds = new RectangleF( 0, 0, size.Width, size.Height ); } } public abstract string ToString( GraphicsContext ctx ); //--// public static void PlaceInALine( GraphicsContext ctx , BaseTextVisualItem item , ref PointF pt , float preX , float postX ) { item.PrepareText( ctx ); pt.X += ctx.CharSize( item.TextFont ) * preX; item.RelativeOrigin = pt; pt.X += item.RelativeBounds.Width; pt.X += ctx.CharSize( item.TextFont ) * postX; } // // Access Methods // public Font TextFont { get { return m_font; } set { m_font = value; } } public Brush TextBrush { get { return m_brush; } set { m_brush = value; } } // // Debug Methods // public override string ToString() { return m_cachedText; } } } ================================================ FILE: Zelig/Zelig/DebugTime/Debugger/VisualTree/VisualItems/ByteVisualItem.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // namespace Microsoft.Zelig.Debugger.ArmProcessor { using System; using System.Collections.Generic; using System.ComponentModel; using System.Drawing; using System.Data; using System.Text; using System.Windows.Forms; using IR = Microsoft.Zelig.CodeGeneration.IR; public class ByteVisualItem : BaseTextVisualItem { // // State // byte m_value; // // Constructor Methods // public ByteVisualItem( object context , byte value ) : base( context ) { m_value = value; } // // Helper Methods // public override string ToString( GraphicsContext ctx ) { return String.Format( "{0,2:X2}", m_value ); } } } ================================================ FILE: Zelig/Zelig/DebugTime/Debugger/VisualTree/VisualItems/CharsVisualItem.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // namespace Microsoft.Zelig.Debugger.ArmProcessor { using System; using System.Collections.Generic; using System.ComponentModel; using System.Drawing; using System.Data; using System.Text; using System.Windows.Forms; using IR = Microsoft.Zelig.CodeGeneration.IR; public class CharsVisualItem : BaseTextVisualItem { // // State // string m_text; // // Constructor Methods // public CharsVisualItem( object context , Emulation.Hosting.MemoryProvider memory , uint address , int size ) : base( context ) { char[] buf = new char[size]; for(int i = 0; i < size; i++) { byte c; if(memory.GetUInt8( address++, out c ) == false) { buf[i] = '?'; } else if(c >= 20 && c < 128) { buf[i] = (char)c; } else { buf[i] = '.'; } } m_text = new string( buf ); } // // Helper Methods // public override string ToString( GraphicsContext ctx ) { return m_text; } } } ================================================ FILE: Zelig/Zelig/DebugTime/Debugger/VisualTree/VisualItems/ContainerVisualItem.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // namespace Microsoft.Zelig.Debugger.ArmProcessor { using System; using System.Collections.Generic; using System.ComponentModel; using System.Drawing; using System.Data; using System.Text; using System.Windows.Forms; using IR = Microsoft.Zelig.CodeGeneration.IR; public sealed class ContainerVisualItem : VisualItem { // // State // private List< VisualItem > m_children; private bool m_boundsValid; // // Constructor Methods // public ContainerVisualItem( object context ) : base( context ) { m_children = new List< VisualItem >(); } // // Helper Methods // public override void CollectDepths( GrowOnlySet< int > set ) { set.Insert( m_depth ); foreach(VisualItem child in m_children) { child.CollectDepths( set ); } } public override bool Draw( GraphicsContext ctx , PointF absoluteOrigin , int depth ) { bool isVisible = base.Draw( ctx, absoluteOrigin, depth ); if(isVisible) { absoluteOrigin.X += m_relativeOrigin.X; absoluteOrigin.Y += m_relativeOrigin.Y; foreach(VisualItem child in m_children) { child.Draw( ctx, absoluteOrigin, depth ); } } return isVisible; } public override VisualItem Contains( PointF pt , bool fLeafOnly , out PointF relHitPt ) { if(base.Contains( pt, fLeafOnly, out relHitPt ) != null) { pt.X -= m_relativeOrigin.X; pt.Y -= m_relativeOrigin.Y; foreach(VisualItem child in m_children) { VisualItem hit = child.Contains( pt, fLeafOnly, out relHitPt ); if(hit != null) { return hit; } } if(fLeafOnly == false) { return this; } } return null; } public override VisualItem ContainsVertically( float y , out float relHitY ) { if(base.ContainsVertically( y, out relHitY ) != null) { y -= m_relativeOrigin.Y; foreach(VisualItem child in m_children) { VisualItem hit = child.ContainsVertically( y, out relHitY ); if(hit != null) { return hit; } } } return null; } public override VisualItem FindMatch( object o ) { foreach(VisualItem child in m_children) { VisualItem match = child.FindMatch( o ); if(match != null) { return match; } } return null; } public override bool EnumerateTree( CodeView.EnumerationCallback dlg ) { if(base.EnumerateTree( dlg ) == false) { foreach(VisualItem child in m_children) { if(child.EnumerateTree( dlg )) { return true; } } } return false; } //--// public override void InvalidateBounds() { m_boundsValid = false; base.InvalidateBounds(); } public void InsertAt( VisualItem itemNew , int pos ) { m_children.Insert( pos, itemNew ); itemNew.Parent = this; InvalidateBounds(); } public void Add( VisualItem item ) { m_children.Add( item ); item.Parent = this; InvalidateBounds(); } public void Remove( VisualItem item ) { m_children.Remove( item ); item.Parent = null; InvalidateBounds(); } public void Clear() { m_children.Clear(); InvalidateBounds(); } public void ExpandVerticalSpaceAfter( VisualItem item , VisualItem newItem ) { RectangleF newBounds = newItem.RelativeBounds; RectangleF bounds = item .RelativeBounds; bounds.Offset( item.RelativeOrigin ); newItem.RelativeOrigin = new PointF( bounds.X, bounds.Bottom ); foreach(VisualItem child in m_children) { PointF childPos = child.RelativeOrigin; if(childPos.Y > item.RelativeOrigin.Y) { childPos.Y += newBounds.Height; child.RelativeOrigin = childPos; } } Add( newItem ); } internal void RemoveVerticalSpace( VisualItem item ) { RectangleF bounds = item.RelativeBounds; bounds.Offset( item.RelativeOrigin ); foreach(VisualItem child in m_children) { PointF childPos = child.RelativeOrigin; if(childPos.Y > item.RelativeOrigin.Y) { childPos.Y -= bounds.Height; child.RelativeOrigin = childPos; } } Remove( item ); } // // Access Methods // public override RectangleF RelativeBounds { get { if(m_boundsValid == false) { bool fFirst = true; m_relativeBounds = new RectangleF(); foreach(VisualItem child in m_children) { RectangleF childBounds = child.RelativeBounds; childBounds.Offset( child.RelativeOrigin ); if(fFirst) { fFirst = false; m_relativeBounds = childBounds; } else { m_relativeBounds = RectangleF.Union( m_relativeBounds, childBounds ); } } m_boundsValid = true; } return m_relativeBounds; } } public List< VisualItem > Children { get { return m_children; } } } } ================================================ FILE: Zelig/Zelig/DebugTime/Debugger/VisualTree/VisualItems/IconVisualItem.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // namespace Microsoft.Zelig.Debugger.ArmProcessor { using System; using System.Collections.Generic; using System.ComponentModel; using System.Drawing; using System.Data; using System.Text; using System.Windows.Forms; using IR = Microsoft.Zelig.CodeGeneration.IR; public class IconVisualItem : VisualItem { // // State // protected Icon m_icon; // // Constructor Methods // public IconVisualItem( object context , Icon icon , int depth ) : base( context ) { m_icon = icon; m_depth = depth; } // // Helper Methods // public override bool Draw( GraphicsContext ctx , PointF absoluteOrigin , int depth ) { bool isVisible = base.Draw( ctx, absoluteOrigin, depth ); if(isVisible) { if(m_depth == depth) { absoluteOrigin.X += m_relativeOrigin.X; absoluteOrigin.Y += m_relativeOrigin.Y; ctx.Gfx.DrawIcon( m_icon, (int)absoluteOrigin.X, (int)absoluteOrigin.Y ); } } return isVisible; } // // Access Methods // } } ================================================ FILE: Zelig/Zelig/DebugTime/Debugger/VisualTree/VisualItems/ShortVisualItem.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // namespace Microsoft.Zelig.Debugger.ArmProcessor { using System; using System.Collections.Generic; using System.ComponentModel; using System.Drawing; using System.Data; using System.Text; using System.Windows.Forms; using IR = Microsoft.Zelig.CodeGeneration.IR; public class ShortVisualItem : BaseTextVisualItem { // // State // ushort m_value; // // Constructor Methods // public ShortVisualItem( object context , ushort value ) : base( context ) { m_value = value; } // // Helper Methods // public override string ToString( GraphicsContext ctx ) { return String.Format( "{0,4:X4}", m_value ); } } } ================================================ FILE: Zelig/Zelig/DebugTime/Debugger/VisualTree/VisualItems/TextVisualItem.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // namespace Microsoft.Zelig.Debugger.ArmProcessor { using System; using System.Collections.Generic; using System.ComponentModel; using System.Drawing; using System.Data; using System.Text; using System.Windows.Forms; using IR = Microsoft.Zelig.CodeGeneration.IR; public class TextVisualItem : BaseTextVisualItem { // // State // protected string m_text; // // Constructor Methods // public TextVisualItem( object context , string text ) : base( context ) { m_text = text; } // // Helper Methods // public override string ToString( GraphicsContext ctx ) { return m_text; } } } ================================================ FILE: Zelig/Zelig/DebugTime/Debugger/VisualTree/VisualItems/VisualItem.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // namespace Microsoft.Zelig.Debugger.ArmProcessor { using System; using System.Collections.Generic; using System.ComponentModel; using System.Drawing; using System.Data; using System.Text; using System.Windows.Forms; using IR = Microsoft.Zelig.CodeGeneration.IR; public abstract class VisualItem { // // State // protected ContainerVisualItem m_parent; protected object m_context; protected Pen m_borderPen; protected Brush m_backgroundBrush; protected PointF m_relativeOrigin; protected RectangleF m_relativeBounds; protected int m_depth; protected CodeView.HitCallback m_hitSink; // // Constructor Methods // protected VisualItem( object context ) { m_context = context; } // // Helper Methods // public virtual void CollectDepths( GrowOnlySet< int > set ) { set.Insert( m_depth ); } public virtual bool Draw( GraphicsContext ctx , PointF absoluteOrigin , int depth ) { RectangleF bounds = this.RelativeBounds; bounds.Offset( absoluteOrigin ); bounds.Offset( this.RelativeOrigin ); if(ctx.IsVisible( bounds )) { if(m_depth == depth) { if(m_backgroundBrush != null) { ctx.Gfx.FillRectangle( m_backgroundBrush, bounds ); } if(m_borderPen != null) { ctx.Gfx.DrawRectangle( m_borderPen, bounds.X, bounds.Y, bounds.Width, bounds.Height ); } } return true; } return false; } public virtual VisualItem Contains( PointF pt , bool fLeafOnly , out PointF relHitPt ) { relHitPt = new PointF( pt.X - m_relativeOrigin.X, pt.Y - m_relativeOrigin.Y ); if(this.RelativeBounds.Contains( relHitPt )) { return this; } return null; } public virtual VisualItem ContainsVertically( float y , out float relHitY ) { relHitY = y - m_relativeOrigin.Y; RectangleF bounds = this.RelativeBounds; if(bounds.Top <= relHitY && relHitY < bounds.Bottom) { return this; } return null; } public virtual VisualItem FindMatch( object o ) { if(o.Equals( m_context )) { return this; } return null; } public virtual bool EnumerateTree( CodeView.EnumerationCallback dlg ) { return dlg( this ); } public virtual void InvalidateBounds() { if(m_parent != null) { m_parent.InvalidateBounds(); } } public void Delete() { if(m_parent != null) { m_parent.Remove( this ); } } public void ExpandVerticalSpaceAfter( VisualItem newItem ) { if(m_parent != null) { m_parent.ExpandVerticalSpaceAfter( this, newItem ); } } public void RemoveVerticalSpace() { if(m_parent != null) { m_parent.RemoveVerticalSpace( this ); } } // // Access Methods // public ContainerVisualItem Parent { get { return m_parent; } internal set { m_parent = value; } } public object Context { get { return m_context; } } public Pen BorderPen { get { return m_borderPen; } set { m_borderPen = value; } } public Brush BackgroundBrush { get { return m_backgroundBrush; } set { m_backgroundBrush = value; } } public PointF AbsoluteOrigin { get { if(m_parent != null) { PointF res = m_parent.AbsoluteOrigin; res.X += m_relativeOrigin.X; res.Y += m_relativeOrigin.Y; return res; } else { return m_relativeOrigin; } } set { m_relativeOrigin = value; InvalidateBounds(); } } public PointF RelativeOrigin { get { return m_relativeOrigin; } set { m_relativeOrigin = value; InvalidateBounds(); } } public virtual RectangleF RelativeBounds { get { return m_relativeBounds; } set { m_relativeBounds = value; InvalidateBounds(); } } public int Depth { get { return m_depth; } set { m_depth = value; } } public CodeView.HitCallback HitSink { get { return m_hitSink; } set { m_hitSink = value; } } } } ================================================ FILE: Zelig/Zelig/DebugTime/Debugger/VisualTree/VisualItems/WordVisualItem.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // namespace Microsoft.Zelig.Debugger.ArmProcessor { using System; using System.Collections.Generic; using System.ComponentModel; using System.Drawing; using System.Data; using System.Text; using System.Windows.Forms; using IR = Microsoft.Zelig.CodeGeneration.IR; public class WordItem : BaseTextVisualItem { // // State // uint m_value; // // Constructor Methods // public WordItem( object context , uint value ) : base( context ) { m_value = value; } // // Helper Methods // public override string ToString( GraphicsContext ctx ) { return String.Format( "{0,8:X8}", m_value ); } } } ================================================ FILE: Zelig/Zelig/DebugTime/Debugger/VisualTree/VisualTreeInfo.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // namespace Microsoft.Zelig.Debugger.ArmProcessor { using System; using System.Collections.Generic; using System.ComponentModel; using System.Drawing; using System.Data; using System.Text; using System.Windows.Forms; using IR = Microsoft.Zelig.CodeGeneration.IR; public class VisualTreeInfo { public enum CallbackResult { Keep , Delete, } public delegate CallbackResult VisualEffectEnumerationCallback( VisualEffect ve ); // // State // public string DisplayName; public IR.SourceCodeTracker.SourceCode Input; public ContainerVisualItem VisualTreeRoot; public List< VisualEffect > VisualEffects; public ContainerVisualItem[] LineLookup; public Point ScrollPosition; // // Constructor Methods // public VisualTreeInfo( string displayName , IR.SourceCodeTracker.SourceCode input , ContainerVisualItem visualTreeRoot ) { this.DisplayName = displayName; this.Input = input; this.VisualTreeRoot = visualTreeRoot; this.VisualEffects = new List< VisualEffect >(); if(input != null) { this.LineLookup = new ContainerVisualItem[input.Count]; visualTreeRoot.EnumerateTree( delegate( VisualItem item ) { ContainerVisualItem lineItem = item as ContainerVisualItem; if(lineItem != null) { Debugging.DebugInfo di = lineItem.Context as Debugging.DebugInfo; if(di != null) { this.LineLookup[di.BeginLineNumber - 1] = lineItem; } } return false; } ); } } // // Helper Methods // public void Draw( GraphicsContext ctx , PointF absoluteOrigin ) { GrowOnlySet< int > set = SetFactory.New< int >(); this.VisualTreeRoot.CollectDepths( set ); int[] array = set.ToArray(); Array.Sort( array ); for(int i = array.Length; --i >= 0; ) { this.VisualTreeRoot.Draw( ctx, absoluteOrigin, array[i] ); } } public void ScrollToItem( VisualItem bringIntoView , Rectangle displayRectangle , Rectangle controlRectangle ) { if(bringIntoView != null) { // // We want to have the selected item away from the window's borders, // so shrink the actual viewport size. // if(controlRectangle.Width > 50) { controlRectangle.X += 25; controlRectangle.Width -= 50; } if(controlRectangle.Height > 50) { controlRectangle.Y += 25; controlRectangle.Height -= 50; } PointF pt = bringIntoView.AbsoluteOrigin; RectangleF rect = bringIntoView.RelativeBounds; int x = (int)(pt.X + rect.Left); int y = (int)(pt.Y + rect.Top ); int dx = x + displayRectangle.X; int dy = y + displayRectangle.Y; Rectangle rectItem = new Rectangle( dx, dy, (int)rect.Width, (int)rect.Height ); // // Only scroll is the item is not fully contained within the current control view. // if(controlRectangle.Contains( rectItem ) == false) { if(dx < controlRectangle.Width) { x = -displayRectangle.X; } // // Center it. // y -= controlRectangle.Height / 2; } else { x = -displayRectangle.X; y = -displayRectangle.Y; } this.ScrollPosition = new Point( x, y ); } } public void ClearAllVisualEffects() { foreach(VisualEffect ve in this.VisualEffects) { ve.Clear(); } this.VisualEffects.Clear(); } public void ClearVisualEffects( Type filter ) { EnumerateVisualEffects( delegate( VisualEffect ve ) { return filter.IsInstanceOfType( ve ) ? CallbackResult.Delete : CallbackResult.Keep; } ); } public void EnumerateVisualEffects( VisualEffectEnumerationCallback dlg ) { for(int i = this.VisualEffects.Count; --i >= 0; ) { VisualEffect ve = this.VisualEffects[i]; switch(dlg( ve )) { case CallbackResult.Delete: ve.Clear(); this.VisualEffects.RemoveAt( i ); break; } } } public ContainerVisualItem FindLine( int line ) { line--; if(line >= 0 && this.LineLookup != null && line < this.LineLookup.Length) { return this.LineLookup[line]; } return null; } public VisualEffect.SourceCodeHighlight HighlightSourceCode( CodeView cv , uint address , Debugging.DebugInfo di , Icon icon , Pen backgroundBorder , Brush backgroundFill , int depth ) { return new VisualEffect.SourceCodeHighlight( this, address, di, icon, backgroundBorder, backgroundFill, depth ); } public VisualEffect.InlineDisassembly InstallDisassemblyBlock( ContainerVisualItem line , CodeView control , ImageInformation.DisassemblyLine[] lines , int depth ) { return new VisualEffect.InlineDisassembly( this, line, control.CtxForLayout, lines, depth ); } } } ================================================ FILE: Zelig/Zelig/DebugTime/Debugger/app.config ================================================ ================================================ FILE: Zelig/Zelig/DebugTime/Debugger/test.DebuggerConfig ================================================ ### ### ### #-session "Unit Test FF" #-session "Unit Test FF HW" #-session "Unit Test NXP HW" #-session "Unit Test PXA HW" #-session "Solo Tester FF HW" #-session "Solo Tester NXP HW" #-session "Tester FF" #-session "Tester FF HW" #-session "Tester PXA HW" #-session "Loader NXP" #-session "Loader iMote2" #-session "Solo Test FF" #-session "Solo Test NXP HW" #-cfg %DEPOTROOT%\Zelig\DebugTime\Debugger\SoloUI.DebuggerConfig #-cfg %DEPOTROOT%\Zelig\DebugTime\Debugger\SoloOverDccUI.DebuggerConfig #-cfg %DEPOTROOT%\Zelig\DebugTime\Debugger\SoloOverDccUI_HW.DebuggerConfig #-cfg %DEPOTROOT%\Zelig\DebugTime\Debugger\SoloDebugOverDccUI_HW.DebuggerConfig #-cfg %DEPOTROOT%\Zelig\DebugTime\Debugger\SoloOverSerialUI_HW.DebuggerConfig #-sessionFile %DEPOTROOT%\Zelig\DebugTime\Debugger\test.ZeligDebugSession #-imageFile %DEPOTROOT%\ZeligUnitTestResults\mscorlib_UnitTest_FF.ZeligImage ================================================ FILE: Zelig/Zelig/DebugTime/Debugger/test.ZeligDebugSession ================================================ ================================================ FILE: Zelig/Zelig/DebugTime/Elf/ElfLib/DebugInfoEntry.cs ================================================ using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Runtime.InteropServices; using System.IO; namespace Microsoft.Zelig.Elf { public struct DebugInfoAbbrevAttrib { public Dwarf2_Attribute Attrib; public Dwarf2_Form Form; public DebugInfoAbbrevAttrib(BinaryReader br) { Attrib = (Dwarf2_Attribute)LEB128.DecodeUnsigned( br ); Form = (Dwarf2_Form )LEB128.DecodeUnsigned( br ); } } public class DebugInfoAbbrevCompUnit { public UInt32 m_index; public Dwarf2_TAG m_tag; public byte m_childLevel; public List m_attribs; public DebugInfoAbbrevCompUnit(uint abbrevCode, BinaryReader br) { m_tag = (Dwarf2_TAG)LEB128.DecodeUnsigned( br ); m_childLevel = br.ReadByte(); m_attribs = new List(); while(true) { DebugInfoAbbrevAttrib attrib = new DebugInfoAbbrevAttrib( br ); if( attrib.Attrib == 0 && attrib.Form == 0 ) break; m_attribs.Add( attrib ); } } } public class DebugInfoAbbrev { public Dictionary m_compUnitEntries; public DebugInfoAbbrevCompUnit this[uint index] { get { if( m_compUnitEntries.ContainsKey( index ) ) { return m_compUnitEntries[index]; } return null; } } public DebugInfoAbbrev() { m_compUnitEntries = new Dictionary(); } public void ParseDebugInfoSection(ElfSection debugInfoSection) { byte[] raw = debugInfoSection.Raw; m_compUnitEntries = new Dictionary(); using(MemoryStream ms = new MemoryStream(raw)) using(BinaryReader br = new BinaryReader(ms)) { while( ms.Position < ms.Length ) { uint abbrevCode = LEB128.DecodeUnsigned( br ); if( abbrevCode != 0 ) { m_compUnitEntries[abbrevCode] = new DebugInfoAbbrevCompUnit( abbrevCode, br ); } } } } } public class DebugInfoCompUnitSection { public uint m_abbrevCode; public Dictionary m_properties; public List m_children; public List m_unresolvedLocal; public List m_unresolvedGlobal; DebugInfoCompUnit m_owner; public DebugInfoCompUnitSection(DebugInfoCompUnit owner) { m_abbrevCode = 0; m_owner = owner; } public DebugInfoCompUnitSection(uint abbrevCode, BinaryReader br, DebugInfoAbbrev abbrev, DebugInfoCompUnit owner, Dictionary addressMap) { m_abbrevCode = abbrevCode; m_properties = new Dictionary(); m_children = new List(); m_unresolvedLocal = new List(); m_unresolvedGlobal = new List(); m_owner = owner; DebugInfoAbbrevCompUnit cu = abbrev[abbrevCode]; if( cu != null ) { //Console.WriteLine( "Tag : " + cu.m_tag ); ParseAttributes( br, cu, owner ); if( cu.m_childLevel != 0 ) { uint childAbbrevCode; do { uint addr = (uint)(br.BaseStream.Position - m_owner.m_streamOffset + owner.m_offset); childAbbrevCode = LEB128.DecodeUnsigned( br ); if( childAbbrevCode != 0 ) { DebugInfoCompUnitSection sec = new DebugInfoCompUnitSection( childAbbrevCode, br, abbrev, owner, addressMap ); m_children.Add( sec ); addressMap[addr] = sec; } else { addressMap[addr] = new DebugInfoCompUnitSection( owner ); } } while( childAbbrevCode != 0 ); } } } private void ParseAttributes(BinaryReader bs, DebugInfoAbbrevCompUnit abbrev, DebugInfoCompUnit owner) { foreach( DebugInfoAbbrevAttrib attrib in abbrev.m_attribs ) { //Console.WriteLine( "Attrib: " + attrib.Attrib.ToString() ); Dwarf2_Form form = attrib.Form; reparse_form: //Console.WriteLine( "Form : " + form.ToString() ); switch( form ) { case Dwarf2_Form.DW_FORM_string: m_properties[attrib.Attrib] = Dwarf_Utility.DwarfReadString( bs ); break; case Dwarf2_Form.DW_FORM_addr: if( owner.m_header.uh_addressSize == 4 ) { m_properties[attrib.Attrib] = bs.ReadUInt32(); } else if( owner.m_header.uh_addressSize == 2 ) { m_properties[attrib.Attrib] = bs.ReadUInt16(); } break; case Dwarf2_Form.DW_FORM_block: { uint size = LEB128.DecodeUnsigned( bs ); m_properties[attrib.Attrib] = size; bs.BaseStream.Seek( size, SeekOrigin.Current ); } break; case Dwarf2_Form.DW_FORM_block1: { uint size = bs.ReadByte(); m_properties[attrib.Attrib] = size; bs.BaseStream.Seek( size, SeekOrigin.Current ); } break; case Dwarf2_Form.DW_FORM_block2: { uint size = bs.ReadUInt16(); m_properties[attrib.Attrib] = size; bs.BaseStream.Seek( size, SeekOrigin.Current ); } break; case Dwarf2_Form.DW_FORM_block4: { uint size = bs.ReadUInt32(); m_properties[attrib.Attrib] = size; bs.BaseStream.Seek( size, SeekOrigin.Current ); } break; case Dwarf2_Form.DW_FORM_data1: m_properties[attrib.Attrib] = bs.ReadByte(); break; case Dwarf2_Form.DW_FORM_data2: m_properties[attrib.Attrib] = bs.ReadInt16(); break; case Dwarf2_Form.DW_FORM_data4: m_properties[attrib.Attrib] = bs.ReadInt32(); break; case Dwarf2_Form.DW_FORM_data8: m_properties[attrib.Attrib] = bs.ReadUInt64(); break; case Dwarf2_Form.DW_FORM_flag: m_properties[attrib.Attrib] = bs.ReadByte(); break; case Dwarf2_Form.DW_FORM_indirect: { form = (Dwarf2_Form)LEB128.DecodeUnsigned( bs ); //Console.WriteLine( "Indir : " + form.ToString() ); goto reparse_form; } case Dwarf2_Form.DW_FORM_ref_addr: // TODO: FIND OUT HOW TO MAKE THIS WORK PROPERLY m_properties[attrib.Attrib] = (uint)(bs.ReadUInt32() + m_owner.m_owner.m_elfOffset); m_unresolvedGlobal.Add( attrib.Attrib ); break; case Dwarf2_Form.DW_FORM_ref_udata: m_properties[attrib.Attrib] = (uint)(LEB128.DecodeUnsigned( bs ) + owner.m_offset); m_unresolvedLocal.Add( attrib.Attrib ); break; case Dwarf2_Form.DW_FORM_ref1: m_properties[attrib.Attrib] = (uint)(bs.ReadByte() + owner.m_offset); m_unresolvedLocal.Add( attrib.Attrib ); break; case Dwarf2_Form.DW_FORM_ref2: m_properties[attrib.Attrib] = (uint)(bs.ReadInt16() + owner.m_offset); m_unresolvedLocal.Add( attrib.Attrib ); break; case Dwarf2_Form.DW_FORM_ref4: m_properties[attrib.Attrib] = (uint)(bs.ReadInt32() + owner.m_offset); m_unresolvedLocal.Add( attrib.Attrib ); break; case Dwarf2_Form.DW_FORM_ref8: m_properties[attrib.Attrib] = (uint)(bs.ReadInt64() + owner.m_offset); m_unresolvedLocal.Add( attrib.Attrib ); break; case Dwarf2_Form.DW_FORM_sdata: m_properties[attrib.Attrib] = LEB128.DecodeSigned( bs ); break; case Dwarf2_Form.DW_FORM_strp: break; case Dwarf2_Form.DW_FORM_udata: m_properties[attrib.Attrib] = LEB128.DecodeUnsigned( bs ); break; case Dwarf2_Form.DW_FORM_sec_offset: m_properties[attrib.Attrib] = LEB128.DecodeUnsigned( bs ); break; case Dwarf2_Form.DW_FORM_exprloc: m_properties[attrib.Attrib] = LEB128.DecodeUnsigned( bs ); break; case Dwarf2_Form.DW_FORM_flag_present: m_properties[attrib.Attrib] = LEB128.DecodeUnsigned( bs ); break; case Dwarf2_Form.DW_FORM_ref_sig8: break; default: break; } //Console.WriteLine( "Value : " + m_properties[attrib.Attrib].ToString() ); //Console.WriteLine(); } } public void ResolveLocalReferences(Dictionary localLookup) { if( m_unresolvedLocal != null ) { foreach( Dwarf2_Attribute unres in m_unresolvedLocal ) { uint addr = (uint)m_properties[unres]; if( localLookup.ContainsKey( addr ) ) { m_properties[unres] = localLookup[addr]; } else { //Console.WriteLine( "Could not resolve: " + unres ); } } } //if(m_children != null) //{ // foreach( DebugInfoCompUnitSection sec in m_children ) // { // sec.ResolveLocalReferences( localLookup ); // } //} } public void ResolveGlobalReferences(Dictionary globalLookup) { if( m_unresolvedGlobal != null ) { foreach( Dwarf2_Attribute unres in m_unresolvedGlobal ) { if(!(m_properties[unres] is DebugInfoCompUnitSection)) { uint addr = (uint)m_properties[unres]; if(globalLookup.ContainsKey( addr )) { m_properties[unres] = globalLookup[addr]; } else { //Console.WriteLine( "Could not resolve: " + unres ); } } } } if( m_children != null ) { foreach( DebugInfoCompUnitSection sec in m_children ) { sec.ResolveGlobalReferences( globalLookup ); } } } } public class DebugInfoCompUnit { public Dwarf2_DebugInfoUnitHeader m_header; public Dictionary m_sections; public uint m_offset, m_streamOffset; public DebugInfoEntry m_owner; public DebugInfoCompUnit(BinaryReader bs, DebugInfoAbbrev abbrev, DebugInfoEntry owner, Dictionary addressMap) { long start = bs.BaseStream.Position; m_header = new Dwarf2_DebugInfoUnitHeader(); m_offset = (uint)( owner.m_elfOffset + bs.BaseStream.Position ); m_streamOffset = (uint)bs.BaseStream.Position; m_header.uh_length = bs.ReadUInt32(); m_header.uh_version = bs.ReadUInt16(); System.Diagnostics.Debug.Assert( m_header.uh_version == 4 ); m_header.uh_abbrevOffset = bs.ReadUInt32(); m_header.uh_addressSize = bs.ReadByte(); m_header.uh_segmentSize = bs.ReadByte(); m_owner = owner; m_sections = new Dictionary(); uint addr = (uint)(owner.m_elfOffset + bs.BaseStream.Position); uint abbrevCode = LEB128.DecodeUnsigned( bs ); while( bs.BaseStream.Position - start < m_header.uh_length ) // abbrevCode != 0 ) { if( abbrevCode != 0 ) { DebugInfoCompUnitSection sec = new DebugInfoCompUnitSection( abbrevCode, bs, abbrev, this, m_sections ); m_sections[abbrevCode] = sec; addressMap[addr] = sec; } else { DebugInfoCompUnitSection sec = new DebugInfoCompUnitSection( this ); addressMap[addr] = sec; } addr = (uint)( owner.m_elfOffset + bs.BaseStream.Position ); abbrevCode = LEB128.DecodeUnsigned( bs ); } foreach( DebugInfoCompUnitSection sec in m_sections.Values ) { sec.ResolveLocalReferences( m_sections ); } } // TODO: use interface for parameter so that dictionary is not modifiable public void ResolveGlobalReferences(Dictionary globalLookup) { foreach( DebugInfoCompUnitSection cus in m_sections.Values ) { cus.ResolveGlobalReferences( globalLookup ); } } } public class DebugInfoEntry { public Dictionary m_entries; public List m_relocations; public string m_name; public long m_elfOffset; public List m_lines; public int m_version; public DebugInfoEntry(ElfSection debugInfoSection, DebugInfoAbbrev abbrev, Dictionary addressMap) { byte[] raw = debugInfoSection.Raw; m_entries = new Dictionary(); m_name = debugInfoSection.Name; m_elfOffset = debugInfoSection.m_elfOffset; m_relocations = new List(); m_lines = new List(); //Console.WriteLine( "Sect : " + debugInfoSection.Name ); using(MemoryStream ms = new MemoryStream(raw)) using(BinaryReader bs = new BinaryReader(ms)) { while( ms.Position < ms.Length ) { DebugInfoCompUnit entry = new DebugInfoCompUnit( bs, abbrev, this, addressMap ); m_version = entry.m_header.uh_version; if( entry.m_header.uh_version != 2 && entry.m_header.uh_version != 3 ) { // // Debug infos for version 4 are not supported // throw new NotSupportedException( "Parsing debug info for DWARF v4 is not supported" ); } m_entries[entry.m_offset] = entry; if( ms.Length > ms.Position && (ms.Length - ms.Position) < Marshal.SizeOf( typeof( Dwarf2_DebugInfoUnitHeader ) ) ) { break; } } } } public void ResolveGlobalReferences(Dictionary sectionMap, Dictionary globalLookup) { foreach( DebugInfoCompUnit cu in m_entries.Values ) { cu.ResolveGlobalReferences( globalLookup ); } } } public class DebugLineEntry { public string m_name; public uint m_index; public Dwarf2_DebugLineHeader m_header; public Dictionary m_opcodLengths; public List m_includeDirs; public List m_files; public List m_opcode; public List m_relocations; public class OpCode { public Dwarf_DebugLineOpCodes Opcode; public Dwarf_DebugLineOpCodesExt OpcodeExt; public object Arg; } public DebugLineEntry(ElfSection debugLineSection) { byte[] raw = debugLineSection.Raw; m_name = debugLineSection.Name; m_index = debugLineSection.m_index; m_header = new Dwarf2_DebugLineHeader(); m_opcodLengths = new Dictionary(); m_includeDirs = new List(); m_files = new List(); m_opcode = new List(); m_relocations = new List(); using( MemoryStream ms = new MemoryStream( raw ) ) using( BinaryReader br = new BinaryReader( ms ) ) { m_header.lh_length = br.ReadUInt32(); m_header.lh_version = br.ReadUInt16(); m_header.lh_headerLen = br.ReadUInt32(); m_header.lh_minInstructionLen = br.ReadByte(); m_header.lh_maxOpsPerInstruction = br.ReadByte(); m_header.lh_defaultStmt = br.ReadByte(); m_header.lh_lineBase = br.ReadSByte(); m_header.lh_lineRange = br.ReadByte(); m_header.lh_opcodeBase = br.ReadByte(); for( int i = 1; i < m_header.lh_opcodeBase; i++ ) { m_opcodLengths[i] = LEB128.DecodeUnsigned( br ); } string incDir = Dwarf_Utility.DwarfReadString( br ); while( !string.IsNullOrEmpty( incDir ) ) { m_includeDirs.Add( incDir ); incDir = Dwarf_Utility.DwarfReadString( br ); } while( ms.Position < ms.Length ) { Dwarf_DebugLineHeaderFile file = new Dwarf_DebugLineHeaderFile(); file.m_name = Dwarf_Utility.DwarfReadString( br ); if( string.IsNullOrEmpty( file.m_name ) ) { break; } file.m_directoryIndex = LEB128.DecodeUnsigned( br ); file.m_fileModTime = LEB128.DecodeUnsigned( br ); file.m_fileLen = LEB128.DecodeUnsigned( br ); m_files.Add( file ); } while( ms.Position < ms.Length ) { OpCode op = new OpCode(); int argSize = 0; op.Opcode = (Dwarf_DebugLineOpCodes) br.ReadByte(); if( op.Opcode == 0 ) { argSize = br.ReadByte() - 1; op.OpcodeExt = (Dwarf_DebugLineOpCodesExt)( br.ReadByte() ); switch( op.OpcodeExt ) { case Dwarf_DebugLineOpCodesExt.DW_LNE_end_sequence: break; case Dwarf_DebugLineOpCodesExt.DW_LNE_set_address: if( argSize == 4 ) { op.Arg = br.ReadUInt32(); } else if( argSize == 2 ) { op.Arg = br.ReadUInt16(); } break; case Dwarf_DebugLineOpCodesExt.DW_LNE_define_file: Dwarf_DebugLineHeaderFile file = new Dwarf_DebugLineHeaderFile(); file.m_name = Dwarf_Utility.DwarfReadString( br ); file.m_directoryIndex = LEB128.DecodeUnsigned( br ); file.m_fileModTime = LEB128.DecodeUnsigned( br ); file.m_fileLen = LEB128.DecodeUnsigned( br ); op.Arg = file; break; default: if( argSize > 0 ) { op.Arg = br.ReadBytes( argSize ); } break; } } else { switch( op.Opcode ) { case Dwarf_DebugLineOpCodes.DW_LNS_copy: case Dwarf_DebugLineOpCodes.DW_LNS_negate_stmt: case Dwarf_DebugLineOpCodes.DW_LNS_set_basic_block: case Dwarf_DebugLineOpCodes.DW_LNS_const_add_pc: case Dwarf_DebugLineOpCodes.DW_LNS_set_prologue_end: case Dwarf_DebugLineOpCodes.DW_LNS_set_epilogue_begin: break; case Dwarf_DebugLineOpCodes.DW_LNS_advance_pc: case Dwarf_DebugLineOpCodes.DW_LNS_set_file: case Dwarf_DebugLineOpCodes.DW_LNS_set_column: case Dwarf_DebugLineOpCodes.DW_LNS_set_isa: op.Arg = LEB128.DecodeUnsigned( br ); break; case Dwarf_DebugLineOpCodes.DW_LNS_advance_line: op.Arg = LEB128.DecodeSigned( br ); break; case Dwarf_DebugLineOpCodes.DW_LNS_fixed_advance_pc: op.Arg = br.ReadUInt16(); break; } } m_opcode.Add( op ); } } } } } ================================================ FILE: Zelig/Zelig/DebugTime/Elf/ElfLib/ElfObject.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // using System; using System.Collections.Generic; using System.Runtime.InteropServices; namespace Microsoft.Zelig.Elf { public partial class ElfObject : IElfElement { // // State // private Elf32_Ehdr m_header; private string m_file; internal List m_sections; internal List m_groups; internal List m_dataEntries; private StringTable m_sectionHeaderStringTable; internal SymbolTable m_symbolTable; private List m_segments; private List m_globalDbgInfo; private UInt16 m_nextSectionIndex; // // Constructor Method // private ElfObject() { m_sections = new List(); m_segments = new List(); m_groups = new List(); m_globalDbgInfo = new List(); m_dataEntries = new List(); m_nextSectionIndex = 0; } // // Helper Methods // public ElfSection AddBinarySection(byte[] raw) { var section = new ElfSection(this, raw); section.m_header.sh_type = sh_type.SHT_PROGBITS; section.m_header.sh_flags = sh_flags.SHF_ALLOC | sh_flags.SHF_EXECINSTR; section.m_header.sh_addralign = 4; AddSection(section); return section; } public RelocationSection AddRelocationSection(ElfSection sectionRef, SymbolTable symTableRef) { var section = new RelocationSection(this, sectionRef, symTableRef); AddSection(section); return section; } private void AddSection(ElfSection section) { if (!m_sections.Contains(section)) { // Increment the number of section headers the Elf knows about m_header.e_shnum++; // Set the index. section.Index = m_nextSectionIndex++; // Add the section to the list m_sections.Add(section); } else { throw new ElfConsistencyException("Cannot add duplicate section to Elf"); } } public ElfSegment AddLoadableSegment(UInt32 addressInMemory) { var segment = new ElfSegment(this, addressInMemory); m_segments.Add(segment); return segment; } private static int CompareSectionsByIndex(ElfSection x, ElfSection y) { if (x == y) { return 0; } if (x.m_index <= y.m_index) { return -1; } return 1; } private static int CompareSegmentsByAddress(ElfSegment x, ElfSegment y) { if (x == y) { return 0; } if (x.m_header.p_vaddr <= y.m_header.p_vaddr) { return -1; } return 1; } // // Access Methods // internal ElfSegment[] GetSortedSegmentList() { var tempList = new List(); foreach (var segment in m_segments) { if (segment.Type == SegmentType.PT_LOAD) { tempList.Add(segment); } } tempList.Sort(CompareSegmentsByAddress); foreach (var segment in m_segments) { if (!tempList.Contains(segment)) { tempList.Add(segment); } } return tempList.ToArray(); } public Elf32_Ehdr Header { get { return m_header; } } public ElfSection[] DataEntries { get { m_dataEntries.Sort( CompareSectionsByIndex ); return m_dataEntries.ToArray(); } } public ElfSection[] Sections { get { m_sections.Sort(CompareSectionsByIndex); return m_sections.ToArray(); } } public ElfSegment[] Segments { get { return m_segments.ToArray(); } } public RelocationSection[] RelocationSections { get { var list = new List(); foreach (var section in m_sections) { if(section is RelocationSection) { list.Add((RelocationSection)section); } } return list.ToArray(); } } public ElfSection this[uint index] { get { foreach (var section in m_sections) { if (section.Index == index) { return section; } } return null; } } public ElfSection this[string name] { get { foreach (var section in m_sections) { if (section.Name == name) { return section; } } return null; } } public string FileName { get { return m_file; } set { m_file = value; } } public UInt32 EntryPoint { get { return m_header.e_entry; } set { m_header.e_entry = value; } } public SymbolTable SymbolTable { get { return m_symbolTable; } set { if (m_symbolTable == null) { m_symbolTable = value; } else { throw new ElfConsistencyException("Elf already contains a symbol table"); } } } internal StringTable SectionHeaderStringTable { get { return m_sectionHeaderStringTable; } set { if (m_sectionHeaderStringTable == null) { m_sectionHeaderStringTable = value; m_header.e_shtrndx = value.Index; value.ElementStatusChangedEvent += SectionStringTableStatusChanged; } else { throw new ElfConsistencyException("Elf already contains a section header string table"); } } } // // Interface Implementations // public void BuildReferences() { Dictionary secMap = new Dictionary(); Dictionary secNameMap = new Dictionary(); Dictionary dbgMap = new Dictionary(); Dictionary dbgNameMap = new Dictionary(); Dictionary dbgLineMap = new Dictionary(); Dictionary globalLookup = new Dictionary(); DebugInfoAbbrev debugAbbrev = new DebugInfoAbbrev(); // Set section header string table reference var tbl = this[m_header.e_shtrndx]; if (tbl != null && tbl is StringTable) { m_sectionHeaderStringTable = (StringTable) tbl; tbl.ElementStatusChangedEvent += SectionStringTableStatusChanged; } // Build all references for all sections foreach (var section in m_sections) { section.BuildReferences(); // Set symboltable reference if we have one if (section is SymbolTable) { m_symbolTable = (SymbolTable) section; } //else if( section.Name.StartsWith( ".debug_abbrev" ) ) //{ // debugAbbrev.ParseDebugInfoSection( section ); //} //else if( section is RelocationSection ) //{ // RelocationSection reloc = (RelocationSection)section; // if( reloc.m_name.Contains( ".debug_info" )) // { // dbgMap[reloc.m_header.sh_info].m_relocations.Add( reloc ); // } // else if( reloc.m_name.Contains( ".debug_line" ) ) // { // dbgLineMap[reloc.m_header.sh_info].m_relocations.Add( reloc ); // } // else if( !section.m_name.Contains( ".debug_" ) ) // { // ElfSection sec = secMap[reloc.m_header.sh_info]; // sec.m_relocations.Add( reloc ); // } //} //else if( section.m_name.StartsWith( ".debug_info" ) ) //{ // string name = section.Name.Replace( ".debug_info", "" ); // name = name.TrimStart( '$' ); // DebugInfoEntry die = new DebugInfoEntry( section, debugAbbrev, globalLookup ); // dbgMap [section.m_index] = die; // dbgNameMap[name ] = die; // if( secNameMap.ContainsKey( name ) ) // { // secNameMap[name].DebugEntries.Add( die ); // } // else // { // m_globalDbgInfo.Add( die ); // } //} //else if( section.Name.StartsWith( ".debug_line" ) ) //{ // string name = section.Name.Replace( ".debug_line", "" ); // DebugLineEntry dle = new DebugLineEntry( section ); // name = name.TrimStart( '$' ); // dbgNameMap[name ].m_lines.Add( dle ); // dbgLineMap[section.m_index] = dle; //} else { secMap[section.m_index] = section; secNameMap[section.m_name] = section; foreach(string alias in section.Aliases.Keys) { secNameMap[alias] = section; } if(section.IsDataSection) { m_dataEntries.Add( section ); } } } foreach(string key in dbgNameMap.Keys) { if(secNameMap.ContainsKey( key )) { if(!secNameMap[key].DebugEntries.Contains(dbgNameMap[key])) { secNameMap[key].DebugEntries.Add( dbgNameMap[key] ); } } } // Rename group sections because they can use the same name as the // symbols (TODO: Fix this later by identifying only symbols not // groups. foreach(ElfSection sec in m_groups) { sec.m_name = ".group." + sec.m_name; } foreach( ElfSection sec in m_sections ) { foreach( RelocationSection rs in sec.m_relocations ) { foreach( RelocationEntry re in rs.Entries ) { if( re.Type != RelocationType.R_ARM_V4BX ) { sec.AddReference( re ); } } } } // build global references foreach( DebugInfoEntry die in dbgMap.Values ) { die.ResolveGlobalReferences( secNameMap, globalLookup ); } // Build all references for all segments foreach (var segment in m_segments) { segment.BuildReferences(); } } private void SectionStringTableStatusChanged(ElfSection section, ElfElementStatus status) { if (status == ElfElementStatus.IndexChanged) { m_header.e_shtrndx = section.Index; } } } } ================================================ FILE: Zelig/Zelig/DebugTime/Elf/ElfLib/ElfObject_Descriptors.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // using System; using System.Runtime.InteropServices; using System.IO; using System.Text; namespace Microsoft.Zelig.Elf { #region Elf Header [StructLayout(LayoutKind.Sequential, Pack = 1)] public struct Elf32_Ehdr { public e_ident e_ident; // The initial bytes mark the file as an object file and provide machine-independent data with which to decode and interpret the file's contents. public e_type e_type; // This member identifies the object file type. public e_machine e_machine; // This member's value specifies the required architecture for an individual file. public e_version e_version; // This member identifies the object file version. public UInt32 e_entry; // This member gives the virtual address to which the system first transfers control, thus starting the process. If the file has no associated entry point, this member holds zero. public UInt32 e_phoff; // This member holds the program header table's file offset in bytes. If the file has no program header table, this member holds zero. public UInt32 e_shoff; // This member holds the section header table's file offset in bytes. If the file has no section header table, this member holds zero. public UInt32 e_flags; // This member holds processor-specific flags associated with the file. Flag names take the form EF_machine_flag. public UInt16 e_ehsize; // This member holds the ELF header's size in bytes. public UInt16 e_phentsize; // This member holds the size in bytes of one entry in the file's program header table; all entries are the same size. public UInt16 e_phnum; // This member holds the number of entries in the program header table. Thus the product of e_phentsize and e_phnum gives the table's size in bytes. If a file has no program header table, e_phnum holds the value zero. public UInt16 e_shentsize; // This member holds a section header's size in bytes. A section header is one entry in the section header table; all entries are the same size. public UInt16 e_shnum; // This member holds the number of entries in the section header table. Thus the product of e_shentsize and e_shnum gives the section header table's size in bytes. If a file has no section header table, e_shnum holds the value zero. public UInt16 e_shtrndx; // This member holds the section header table index of the entry associated with the section name string table. If the file has no section name string table, this member holds the value SHN_UNDEF. } // -- Header IDENT descriptor -- // [StructLayout(LayoutKind.Sequential, Pack = 1)] public struct e_ident { public Byte EI_MAG0; // File identification public Byte EI_MAG1; // File identification public Byte EI_MAG2; // File identification public Byte EI_MAG3; // File identification public EI_CLASS EI_CLASS; // File class public EI_DATA EI_DATA; // Data encoding public Byte EI_VERSION; // File version public EI_OSABI EI_OSABI; // Operating system/ABI identification public Byte EI_ABIVERSION; // ABI version private Byte EI_PAD1; // Start of padding bytes private Byte EI_PAD2; // ... padding bytes private Byte EI_PAD3; // ... padding bytes private Byte EI_PAD4; // ... padding bytes private Byte EI_PAD5; // ... padding bytes private Byte EI_PAD6; // ... padding bytes private Byte EI_PAD7; // ... padding bytes } public enum EI_CLASS : byte { ELFCLASSNONE = 0, // Invalid class ELFCLASS32 = 1, // 32-bit objects ELFCLASS64 = 2, // 64-bit objects } public enum EI_DATA : byte { ELFDATANONE = 0, // Invalid data encoding ELFDATA2LSB = 1, // Encoding ELFDATA2LSB specifies 2's complement values, with the least significant byte occupying the lowest address. ELFDATA2MSB = 2, // Encoding ELFDATA2MSB specifies 2's complement values, with the most significant byte occupying the lowest address. } public enum EI_OSABI : byte { ELFOSABI_NONE = 0, // No extensions or unspecified ELFOSABI_HPUX = 1, // Hewlett-Packard HP-UX ELFOSABI_NETBSD = 2, // NetBSD ELFOSABI_SOLARIS = 6, // Sun Solaris ELFOSABI_AIX = 7, // AIX ELFOSABI_IRIX = 8, // IRIX ELFOSABI_FREEBSD = 9, // FreeBSD ELFOSABI_TRU64 = 10, // Compaq TRU64 UNIX ELFOSABI_MODESTO = 11, // Novell Modesto ELFOSABI_OPENBSD = 12, // Open BSD ELFOSABI_OPENVMS = 13, // Open VMS ELFOSABI_NSK = 14, // Hewlett-Packard Non-Stop Kernel ELFOSABI_AROS = 15, // Amiga Research OS ARCHSPEC64TO255 = 64, // Architecture-specific values ARM = 97, // ARM } // ----------------------------- // public enum e_type : ushort { ET_NONE = 0, // No file type ET_REL = 1, // Relocatable file ET_EXEC = 2, // Executable file ET_DYN = 3, // Shared object file ET_CORE = 4, // Core file ET_LOOS = 0xfe00, // Operating system-specific ET_HIOS = 0xfeff, // Operating system-specific ET_LOPROC = 0xff00, // Processor-specific ET_HIPROC = 0xffff, // Processor-specific } public enum e_machine : ushort { EM_NONE = 0, // No machine EM_M32 = 1, // AT&T WE 32100 EM_SPARC = 2, // SPARC EM_386 = 3, // Intel 80386 EM_68K = 4, // Motorola 68000 EM_88K = 5, // Motorola 88000 RESERVED6 = 6, // Reserved for future use EM_860 = 7, // Intel 80860 EM_MIPS = 8, // MIPS I Architecture RESERVED2 = 9, // Reserved for future use EM_MIPS_RS3_LE = 10, // MIPS RS3000 Little-endian RESERVED11TO14 = 11, // Reserved for future use EM_PARISC = 15, // Hewlett-Packard PA-RISC RESERVED16 = 16, // Reserved for future use EM_VPP500 = 17, // Fujitsu VPP500 EM_SPARC32PLUS = 18, // Enhanced instruction set SPARC EM_960 = 19, // Intel 80960 EM_PPC = 20, // Power PC EM_PPC64 = 21, // 64-bit PowerPC EM_S390 = 22, // IBM System/390 Processor RESERVED23TO35 = 23, // Reserved for future use EM_V800 = 36, // NEC V800 EM_FR20 = 37, // Fujitsu FR20 EM_RH32 = 38, // TRW RH-32 EM_RCE = 39, // Motorola RCE EM_ARM = 40, // Advanced RISC Machines ARM EM_ALPHA = 41, // Digital Alpha EM_SH = 42, // Hitachi SH EM_SPARCV9 = 43, // SPARC Version 9 EM_TRICORE = 44, // Siemens Tricore embedded processor EM_ARC = 45, // Argonaut RISC Core, Argonaut Technologies Inc. EM_H8_300 = 46, // Hitachi H8/300 EM_H8_300H = 47, // Hitachi H8/300H EM_H8S = 48, // Hitachi H8S EM_H8_500 = 49, // Hitachi H8/500 EM_IA_64 = 50, // Intel MercedTM Processor EM_MIPS_X = 51, // Stanford MIPS-X EM_COLDFIRE = 52, // Motorola Coldfire EM_68HC12 = 53, // Motorola M68HC12 } public enum e_version : uint { EV_NONE = 0, // Invalid version EV_CURRENT = 1, // Current version } #endregion ElfHeader #region Elf Section Header public enum NamedIndexes : ushort { SHN_UNDEF = 0, SHN_LORESERVE = 0xff00, // This value specifies the lower bound of the range of reserved indexes. SHN_LOPROC = 0xff00, // Values in this inclusive range are reserved for processor-specific semantics. SHN_HIPROC = 0xff1f, // Values in this inclusive range are reserved for processor-specific semantics. SHN_LOOS = 0xff20, // Values in this inclusive range are reserved for operating system-specific semantics. SHN_HIOS = 0xff3f, // Values in this inclusive range are reserved for operating system-specific semantics. SHN_ABS = 0xfff1, // Symbols defined relative to this section are common symbols, such as FORTRAN COMMON or unallocated C external variables. SHN_COMMON = 0xfff2, // This value specifies absolute values for the corresponding reference. For example, symbols defined relative to section number SHN_ABS have absolute values and are not affected by relocation. SHN_XINDEX = 0xffff, // This value is an escape value. It indicates that the actual section header index is too large to fit in the containing field and is to be found in another location (specific to the structure where it appears). SHN_HIRESERVE = 0xffff, // This value specifies the upper bound of the range of reserved indexes. The system reserves indexes between SHN_LORESERVE and SHN_HIRESERVE, inclusive; the values do not reference the section header table. The section header table does not contain entries for the reserved indexes. } [StructLayout(LayoutKind.Sequential, Pack = 1)] public struct Elf32_Shdr { public UInt32 sh_name; // This member specifies the name of the section. Its value is an index into the section header string table section [see ``String Table'' below], giving the location of a null-terminated string. public sh_type sh_type; // This member categorizes the section's contents and semantics. public sh_flags sh_flags; // Sections support 1-bit flags that describe miscellaneous attributes. public UInt32 sh_addr; // If the section will appear in the memory image of a process, this member gives the address at which the section's first byte should reside. Otherwise, the member contains 0. public UInt32 sh_offset; // This member's value gives the byte offset from the beginning of the file to the first byte in the section. One section type, SHT_NOBITS described below, occupies no space in the file, and its sh_offset member locates the conceptual placement in the file. public UInt32 sh_size; // This member gives the section's size in bytes. Unless the section type is SHT_NOBITS, the section occupies sh_size bytes in the file. A section of type SHT_NOBITS may have a non-zero size, but it occupies no space in the file. public UInt32 sh_link; // This member holds a section header table index link, whose interpretation depends on the section type. A table below describes the values. public UInt32 sh_info; // This member holds extra information, whose interpretation depends on the section type. A table below describes the values. If the sh_flags field for this section header includes the attribute SHF_INFO_LINK, then this member represents a section header table index. public UInt32 sh_addralign; // Some sections have address alignment constraints. For example, if a section holds a doubleword, the system must ensure doubleword alignment for the entire section. The value of sh_addr must be congruent to 0, modulo the value of sh_addralign. Currently, only 0 and positive integral powers of two are allowed. Values 0 and 1 mean the section has no alignment constraints. public UInt32 sh_entsize; // Some sections hold a table of fixed-size entries, such as a symbol table. For such a section, this member gives the size in bytes of each entry. The member contains 0 if the section does not hold a table of fixed-size entries. } public enum sh_type : uint { SHT_NULL = 0, // This value marks the section header as inactive; it does not have an associated section. Other members of the section header have undefined values. SHT_PROGBITS = 1, // The section holds information defined by the program, whose format and meaning are determined solely by the program. SHT_SYMTAB = 2, // These sections hold a symbol table. Currently, an object file may have only one section of each type, but this restriction may be relaxed in the future. Typically, SHT_SYMTAB provides symbols for link editing, though it may also be used for dynamic linking. As a complete symbol table, it may contain many symbols unnecessary for dynamic linking. Consequently, an object file may also contain a SHT_DYNSYM section, which holds a minimal set of dynamic linking symbols, to save space. SHT_STRTAB = 3, // The section holds a string table. An object file may have multiple string table sections. SHT_RELA = 4, // The section holds relocation entries with explicit addends, such as type Elf32_Rela for the 32-bit class of object files or type Elf64_Rela for the 64-bit class of object files. An object file may have multiple relocation sections. SHT_HASH = 5, // The section holds a symbol hash table. Currently, an object file may have only one hash table, but this restriction may be relaxed in the future. SHT_DYNAMIC = 6, // The section holds information for dynamic linking. Currently, an object file may have only one dynamic section, but this restriction may be relaxed in the future. SHT_NOTE = 7, // The section holds information that marks the file in some way. SHT_NOBITS = 8, // A section of this type occupies no space in the file but otherwise resembles SHT_PROGBITS. Although this section contains no bytes, the sh_offset member contains the conceptual file offset. SHT_REL = 9, // The section holds relocation entries without explicit addends, such as type Elf32_Rel for the 32-bit class of object files or type Elf64_Rel for the 64-bit class of object files. An object file may have multiple relocation sections. SHT_SHLIB = 10, // This section type is reserved but has unspecified semantics. SHT_DYNSYM = 11, // These sections hold a symbol table. Currently, an object file may have only one section of each type, but this restriction may be relaxed in the future. Typically, SHT_SYMTAB provides symbols for link editing, though it may also be used for dynamic linking. As a complete symbol table, it may contain many symbols unnecessary for dynamic linking. Consequently, an object file may also contain a SHT_DYNSYM section, which holds a minimal set of dynamic linking symbols, to save space. SHT_INIT_ARRAY = 14, // This section contains an array of pointers to initialization functions, as described in ``Initialization and Termination Functions'' in Chapter 5. Each pointer in the array is taken as a parameterless procedure with a void return. SHT_FINI_ARRAY = 15, // This section contains an array of pointers to termination functions, as described in ``Initialization and Termination Functions'' in Chapter 5. Each pointer in the array is taken as a parameterless procedure with a void return. SHT_PREINIT_ARRAY = 16, // This section contains an array of pointers to functions that are invoked before all other initialization functions, as described in ``Initialization and Termination Functions'' in Chapter 5. Each pointer in the array is taken as a parameterless procedure with a void return. SHT_GROUP = 17, // This section defines a section group. A section group is a set of sections that are related and that must be treated specially by the linker (see below for further details). Sections of type SHT_GROUP may appear only in relocatable objects (objects with the ELF header e_type member set to ET_REL). The section header table entry for a group section must appear in the section header table before the entries for any of the sections that are members of the group. SHT_SYMTAB_SHNDX = 18, // This section is associated with a section of type SHT_SYMTAB and is required if any of the section header indexes referenced by that symbol table contain the escape value SHN_XINDEX. The section is an array of Elf32_Word values. Each value corresponds one to one with a symbol table entry and appear in the same order as those entries. The values represent the section header indexes against which the symbol table entries are defined. Only if corresponding symbol table entry's st_shndx field contains the escape value SHN_XINDEX will the matching Elf32_Word hold the actual section header index; otherwise, the entry must be SHN_UNDEF (0). SHT_LOOS = 0x60000000, // Values in this inclusive range are reserved for operating system-specific semantics. SHT_HIOS = 0x6fffffff, // Values in this inclusive range are reserved for operating system-specific semantics. SHT_LOPROC = 0x70000000, // Values in this inclusive range are reserved for processor-specific semantics. SHT_HIPROC = 0x7fffffff, // Values in this inclusive range are reserved for processor-specific semantics. SHT_LOUSER = 0x80000000, // This value specifies the lower bound of the range of indexes reserved for application programs. SHT_HIUSER = 0xffffffff, // This value specifies the upper bound of the range of indexes reserved for application programs. Section types between SHT_LOUSER and SHT_HIUSER may be used by the application, without conflicting with current or future system-defined section types. } public enum sh_type_ARM : uint { SHT_ARM_EXIDX = 0x70000001, // Exception Index Table SHT_ARM_PREEMPTMAP = 0x70000002, // BPABI DLL dynamic linking pre-emption map SHT_ARM_ATTRIBUTES = 0x70000003, // Object file compatibility attributes SHT_ARM_DEBUGOVERLAY = 0x70000004, // Support for Debugging Overlaid Programs SHT_ARM_OVERLAYSECTION = 0x70000005, // Support for Debugging Overlaid Programs } [Flags] public enum sh_flags : uint { SHF_WRITE = 0x1, // The section contains data that should be writable during process execution. SHF_ALLOC = 0x2, // The section occupies memory during process execution. Some control sections do not reside in the memory image of an object file; this attribute is off for those sections. SHF_EXECINSTR = 0x4, // The section contains executable machine instructions. SHF_MERGE = 0x10, // The data in the section may be merged to eliminate duplication. Unless the SHF_STRINGS flag is also set, the data elements in the section are of a uniform size. The size of each element is specified in the section header's sh_entsize field. If the SHF_STRINGS flag is also set, the data elements consist of null-terminated character strings. The size of each character is specified in the section header's sh_entsize field. SHF_STRINGS = 0x20, // The data elements in the section consist of null-terminated character strings. The size of each character is specified in the section header's sh_entsize field. SHF_INFO_LINK = 0x40, // The sh_info field of this section header holds a section header table index. SHF_LINK_ORDER = 0x80, // This flag adds special ordering requirements for link editors. The requirements apply if the sh_link field of this section's header references another section (the linked-to section). If this section is combined with other sections in the output file, it must appear in the same relative order with respect to those sections, as the linked-to section appears with respect to sections the linked-to section is combined with. SHF_OS_NONCONFORMING = 0x100, // This section requires special OS-specific processing (beyond the standard linking rules) to avoid incorrect behavior. If this section has either an sh_type value or contains sh_flags bits in the OS-specific ranges for those fields, and a link editor processing this section does not recognize those values, then the link editor should reject the object file containing this section with an error. SHF_GROUP = 0x200, // This section is a member (perhaps the only one) of a section group. The section must be referenced by a section of type SHT_GROUP. The SHF_GROUP flag may be set only for sections contained in relocatable objects (objects with the ELF header e_type member set to ET_REL). SHF_TLS = 0x400, // This section holds Thread-Local Storage, meaning that each separate execution flow has its own distinct instance of this data. Implementations need not support this flag. SHF_MASKOS = 0x0ff00000, // All bits included in this mask are reserved for operating system-specific semantics. SHF_MASKPROC = 0xf0000000, // All bits included in this mask are reserved for processor-specific semantics. If meanings are specified, the processor supplement explains them. } #endregion Elf Section Header #region Symbol Table Descriptor [StructLayout(LayoutKind.Sequential, Pack = 1)] public struct Elf32_Sym { public UInt32 st_name; // This member holds an index into the object file's symbol string table, which holds the character representations of the symbol names. If the value is non-zero, it represents a string table index that gives the symbol name. Otherwise, the symbol table entry has no name. public UInt32 st_value; // This member gives the value of the associated symbol. Depending on the context, this may be an absolute value, an address, and so on; details appear below. public UInt32 st_size; // Many symbols have associated sizes. For example, a data object's size is the number of bytes contained in the object. This member holds 0 if the symbol has no size or an unknown size. public Byte st_info; // This member specifies the symbol's type and binding attributes. A list of the values and meanings appears below. public Byte st_other; // This member currently specifies a symbol's visibility. A list of the values and meanings appears below. public UInt16 st_shndx; // Every symbol table entry is defined in relation to some section. This member holds the relevant section header table index. As the sh_link and sh_info interpretation table and the related text describe, some section indexes indicate special meanings. If this member contains SHN_XINDEX, then the actual section header index is too large to fit in this field. The actual value is contained in the associated section of type SHT_SYMTAB_SHNDX. } public enum SymbolType { STT_NOTYPE = 0, // The symbol's type is not specified. STT_OBJECT = 1, // The symbol is associated with a data object, such as a variable, an array, and so on. STT_FUNC = 2, // The symbol is associated with a function or other executable code. STT_SECTION = 3, // The symbol is associated with a section. Symbol table entries of this type exist primarily for relocation and normally have STB_LOCAL binding. STT_FILE = 4, // Conventionally, the symbol's name gives the name of the source file associated with the object file. A file symbol has STB_LOCAL binding, its section index is SHN_ABS, and it precedes the other STB_LOCAL symbols for the file, if it is present. STT_COMMON = 5, // The symbol labels an uninitialized common block. STT_TLS = 6, // The symbol specifies a Thread-Local Storage entity. When defined, it gives the assigned offset for the symbol, not the actual address. Symbols of type STT_TLS can be referenced by only special thread-local storage relocations and thread-local storage relocations can only reference symbols with type STT_TLS. Implementation need not support thread-local storage. STT_LOOS = 10, // Values in this inclusive range are reserved for operating system-specific semantics. STT_HIOS = 12, // Values in this inclusive range are reserved for operating system-specific semantics. STT_LOPROC = 13, // Values in this inclusive range are reserved for processor-specific semantics. If meanings are specified, the processor supplement explains them. STT_HIPROC = 15, // Values in this inclusive range are reserved for processor-specific semantics. If meanings are specified, the processor supplement explains them. } public enum SymbolBinding { STB_LOCAL = 0, // Local symbols are not visible outside the object file containing their definition. Local symbols of the same name may exist in multiple files without interfering with each other. STB_GLOBAL = 1, // Global symbols are visible to all object files being combined. One file's definition of a global symbol will satisfy another file's undefined reference to the same global symbol. STB_WEAK = 2, // Weak symbols resemble global symbols, but their definitions have lower precedence. STB_LOOS = 10, // Values in this inclusive range are reserved for operating system-specific semantics. STB_HIOS = 12, // Values in this inclusive range are reserved for operating system-specific semantics. STB_LOPROC = 13, // Values in this inclusive range are reserved for processor-specific semantics. If meanings are specified, the processor supplement explains them. STB_HIPROC = 15, // Values in this inclusive range are reserved for processor-specific semantics. If meanings are specified, the processor supplement explains them. } public enum SymbolVisibility { STV_DEFAULT = 0, // The visibility of symbols with the STV_DEFAULT attribute is as specified by the symbol's binding type. That is, global and weak symbols are visible outside of their defining component (executable file or shared object). Local symbols are hidden, as described below. Global and weak symbols are also preemptable, that is, they may by preempted by definitions of the same name in another component. STV_INTERNAL = 1, // The meaning of this visibility attribute may be defined by processor supplements to further constrain hidden symbols. A processor supplement's definition should be such that generic tools can safely treat internal symbols as hidden. An internal symbol contained in a relocatable object must be either removed or converted to STB_LOCAL binding by the link-editor when the relocatable object is included in an executable file or shared object. STV_HIDDEN = 2, // A symbol defined in the current component is hidden if its name is not visible to other components. Such a symbol is necessarily protected. This attribute may be used to control the external interface of a component. Note that an object named by such a symbol may still be referenced from another component if its address is passed outside. A hidden symbol contained in a relocatable object must be either removed or converted to STB_LOCAL binding by the link-editor when the relocatable object is included in an executable file or shared object. STV_PROTECTED = 3, // A symbol defined in the current component is protected if it is visible in other components but not preemptable, meaning that any reference to such a symbol from within the defining component must be resolved to the definition in that component, even if there is a definition in another component that would preempt by the default rules. A symbol with STB_LOCAL binding may not have STV_PROTECTED visibility. If a symbol definition with STV_PROTECTED visibility from a shared object is taken as resolving a reference from an executable or another shared object, the SHN_UNDEF symbol table entry created has STV_DEFAULT visibility. } #endregion Symbol Table Descriptor #region Elf Program Header [StructLayout(LayoutKind.Sequential, Pack = 1)] public struct Elf32_Phdr { public SegmentType p_type; // This member tells what kind of segment this array element describes or how to interpret the array element's information. Type values and their meanings appear below. public UInt32 p_offset; // This member gives the offset from the beginning of the file at which the first byte of the segment resides. public UInt32 p_vaddr; // This member gives the virtual address at which the first byte of the segment resides in memory. public UInt32 p_paddr; // On systems for which physical addressing is relevant, this member is reserved for the segment's physical address. Because System V ignores physical addressing for application programs, this member has unspecified contents for executable files and shared objects. public UInt32 p_filesz; // This member gives the number of bytes in the file image of the segment; it may be zero. public UInt32 p_memsz; // This member gives the number of bytes in the memory image of the segment; it may be zero. public SegmentFlag p_flags; // This member gives flags relevant to the segment. Defined flag values appear below. public UInt32 p_align; // As ``Program Loading'' describes in this chapter of the processor supplement, loadable process segments must have congruent values for p_vaddr and p_offset, modulo the page size. This member gives the value to which the segments are aligned in memory and in the file. Values 0 and 1 mean no alignment is required. Otherwise, p_align should be a positive, integral power of 2, and p_vaddr should equal p_offset, modulo p_align. } public enum SegmentType : uint { PT_NULL = 0, // The array element is unused; other members' values are undefined. This type lets the program header table have ignored entries. PT_LOAD = 1, // The array element specifies a loadable segment, described by p_filesz and p_memsz. The bytes from the file are mapped to the beginning of the memory segment. If the segment's memory size (p_memsz) is larger than the file size (p_filesz), the ``extra'' bytes are defined to hold the value 0 and to follow the segment's initialized area. The file size may not be larger than the memory size. Loadable segment entries in the program header table appear in ascending order, sorted on the p_vaddr member. PT_DYNAMIC = 2, // The array element specifies dynamic linking information. See ``Dynamic Section'' below for more information. PT_INTERP = 3, // The array element specifies the location and size of a null-terminated path name to invoke as an interpreter. This segment type is meaningful only for executable files (though it may occur for shared objects); it may not occur more than once in a file. If it is present, it must precede any loadable segment entry. See ``Program Interpreter'' below for more information. PT_NOTE = 4, // The array element specifies the location and size of auxiliary information. See ``Note Section'' below for more information. PT_SHLIB = 5, // This segment type is reserved but has unspecified semantics. Programs that contain an array element of this type do not conform to the ABI. PT_PHDR = 6, // The array element, if present, specifies the location and size of the program header table itself, both in the file and in the memory image of the program. This segment type may not occur more than once in a file. Moreover, it may occur only if the program header table is part of the memory image of the program. If it is present, it must precede any loadable segment entry. See ``Program Interpreter'' below for more information. PT_TLS = 7, // The array element specifies the Thread-Local Storage template. Implementations need not support this program table entry. See ``Thread-Local Storage'' below for more information. PT_LOOS = 0x60000000, // Values in this inclusive range are reserved for operating system-specific semantics. PT_HIOS = 0x6fffffff, // Values in this inclusive range are reserved for operating system-specific semantics. PT_LOPROC = 0x70000000, // Values in this inclusive range are reserved for processor-specific semantics. If meanings are specified, the processor supplement explains them. PT_HIPROC = 0x7fffffff, // Values in this inclusive range are reserved for processor-specific semantics. If meanings are specified, the processor supplement explains them. } [Flags] public enum SegmentFlag : uint { PF_X = 0x1, // Execute PF_W = 0x2, // Write PF_R = 0x4, // Read PF_MASKOS = 0x0ff00000, // Unspecified PF_MASKPROC = 0xf0000000, // Unspecified } #endregion Elf Program Header #region Relocation Table Description [StructLayout(LayoutKind.Sequential, Pack = 1)] public struct Elf32_Rel { public UInt32 r_offset; public UInt32 r_info; } [StructLayout( LayoutKind.Sequential, Pack = 1 )] public struct Elf32_Rela { public UInt32 r_offset; public UInt32 r_info; public Int32 r_addend; } public enum RelocationType : byte { R_ARM_NONE, R_ARM_PC24, R_ARM_ABS32, R_ARM_REL32 , R_ARM_LDR_PC_G0 , R_ARM_ABS16 , R_ARM_ABS12 , R_ARM_THM_ABS5 , R_ARM_ABS8 , R_ARM_SBREL32 , R_ARM_THM_CALL , R_ARM_THM_PC8 , R_ARM_BREL_ADJ , R_ARM_TLS_DESC , R_ARM_THM_SWI8 , R_ARM_XPC25 , R_ARM_THM_XPC22 , R_ARM_TLS_DTPMOD32 , R_ARM_TLS_DTPOFF32 , R_ARM_TLS_TPOFF32 , R_ARM_COPY , R_ARM_GLOB_DAT , R_ARM_JUMP_SLOT , R_ARM_RELATIVE , R_ARM_GOTOFF32 , R_ARM_BASE_PREL , R_ARM_GOT_BREL , R_ARM_PLT32 , R_ARM_CALL , R_ARM_JUMP24, R_ARM_THM_JUMP24 , R_ARM_BASE_ABS , R_ARM_ALU_PCREL_7_0 , R_ARM_ALU_PCREL_15_8 , R_ARM_ALU_PCREL_23_15 , R_ARM_LDR_SBREL_11_0_NC , R_ARM_ALU_SBREL_19_12_NC, R_ARM_ALU_SBREL_27_20_CK, R_ARM_TARGET1 , R_ARM_SBREL31 , R_ARM_V4BX , R_ARM_TARGET2 , R_ARM_PREL31 , R_ARM_MOVW_ABS_NC , R_ARM_MOVT_ABS , R_ARM_MOVW_PREL_NC , R_ARM_MOVT_PREL , R_ARM_THM_MOVW_ABS_NC , R_ARM_THM_MOVT_ABS , R_ARM_THM_MOVW_PREL_NC , R_ARM_THM_MOVT_PREL , R_ARM_THM_JUMP19 , R_ARM_THM_JUMP6 , R_ARM_THM_ALU_PREL_11_0 , R_ARM_THM_PC12 , R_ARM_ABS32_NOI , R_ARM_REL32_NOI , R_ARM_ALU_PC_G0_NC , R_ARM_ALU_PC_G0 , R_ARM_ALU_PC_G1_NC , R_ARM_ALU_PC_G1 , R_ARM_ALU_PC_G2 , R_ARM_LDR_PC_G1 , R_ARM_LDR_PC_G2 , R_ARM_LDRS_PC_G0 , R_ARM_LDRS_PC_G1 , R_ARM_LDRS_PC_G2 , R_ARM_LDC_PC_G0 , R_ARM_LDC_PC_G1 , R_ARM_LDC_PC_G2 , R_ARM_ALU_SB_G0_NC , R_ARM_ALU_SB_G0 , R_ARM_ALU_SB_G1_NC , R_ARM_ALU_SB_G1 , R_ARM_ALU_SB_G2 , R_ARM_LDR_SB_G0 , R_ARM_LDR_SB_G1 , R_ARM_LDR_SB_G2 , R_ARM_LDRS_SB_G0 , R_ARM_LDRS_SB_G1 , R_ARM_LDRS_SB_G2 , R_ARM_LDC_SB_G0 , R_ARM_LDC_SB_G1 , R_ARM_LDC_SB_G2 , R_ARM_MOVW_BREL_NC , R_ARM_MOVT_BREL , R_ARM_MOVW_BREL , R_ARM_THM_MOVW_BREL_NC , R_ARM_THM_MOVT_BREL , R_ARM_THM_MOVW_BREL , R_ARM_TLS_GOTDESC , R_ARM_TLS_CALL , R_ARM_TLS_DESCSEQ , R_ARM_THM_TLS_CALL , R_ARM_PLT32_ABS , R_ARM_GOT_ABS , R_ARM_GOT_PREL , R_ARM_GOT_BREL12 , R_ARM_GOTOFF12 , R_ARM_GOTRELAX , R_ARM_GNU_VTENTRY , R_ARM_GNU_VTINHERIT , R_ARM_THM_JUMP11 , R_ARM_THM_JUMP8 , R_ARM_TLS_GD32 , R_ARM_TLS_LDM32 , R_ARM_TLS_LDO32 , R_ARM_TLS_IE32 , R_ARM_TLS_LE32 , R_ARM_TLS_LDO12 , R_ARM_TLS_LE12 , R_ARM_TLS_IE12GP , } #endregion Relocation Table Description public static class LEB128 { public static uint DecodeUnsigned(BinaryReader br) { uint result = 0; int shift = 0; while(true) { byte by = br.ReadByte(); result |= ((uint)(0x7F & by) << shift); if ((0x80 & by) == 0) break; shift += 7; } return result; } public static int DecodeSigned(BinaryReader br) { int result = 0; int shift = 0; int size = sizeof(int); byte by; while( true ) { by = br.ReadByte(); result |= ( (int)( 0x7F & by ) << shift ); if( ( 0x80 & by ) == 0 ) break; shift += 7; } if( ( shift < size ) && 0 != ( 0x80 & by ) ) { result |= -( 1 << shift ); } return result; } } [StructLayout( LayoutKind.Sequential, Pack = 1 )] public struct Dwarf2_DebugInfoUnitHeader { public UInt32 uh_length; public UInt16 uh_version; public UInt32 uh_abbrevOffset; public byte uh_addressSize; public byte uh_segmentSize; } public enum Dwarf2_TAG : uint { DW_TAG_array_type = 0x01, DW_TAG_class_type = 0x02, DW_TAG_entry_point = 0x03, DW_TAG_enumeration_type = 0x04, DW_TAG_formal_parameter = 0x05, DW_TAG_imported_declaration = 0x08, DW_TAG_label = 0x0a, DW_TAG_lexical_block = 0x0b, DW_TAG_member = 0x0d, DW_TAG_pointer_type = 0x0f, DW_TAG_reference_type = 0x10, DW_TAG_compile_unit = 0x11, DW_TAG_string_type = 0x12, DW_TAG_structure_type = 0x13, DW_TAG_subroutine_type = 0x15, DW_TAG_typedef = 0x16, DW_TAG_union_type = 0x17, DW_TAG_unspecified_parameters = 0x18, DW_TAG_variant = 0x19, DW_TAG_common_block = 0x1a, DW_TAG_common_inclusion = 0x1b, DW_TAG_inheritance = 0x1c, DW_TAG_inlined_subroutine = 0x1d, DW_TAG_module = 0x1e, DW_TAG_ptr_to_member_type = 0x1f, DW_TAG_set_type = 0x20, DW_TAG_subrange_type = 0x21, DW_TAG_with_stmt = 0x22, DW_TAG_access_declaration = 0x23, DW_TAG_base_type = 0x24, DW_TAG_catch_block = 0x25, DW_TAG_const_type = 0x26, DW_TAG_constant = 0x27, DW_TAG_enumerator = 0x28, DW_TAG_file_type = 0x29, DW_TAG_friend = 0x2a, DW_TAG_namelist = 0x2b, DW_TAG_namelist_item = 0x2c, DW_TAG_packed_type = 0x2d, DW_TAG_subprogram = 0x2e, DW_TAG_template_type_param = 0x2f, DW_TAG_template_value_param = 0x30, DW_TAG_thrown_type = 0x31, DW_TAG_try_block = 0x32, DW_TAG_variant_part = 0x33, DW_TAG_variable = 0x34, DW_TAG_volatile_type = 0x35, DW_TAG_lo_user = 0x4080, DW_TAG_hi_user = 0xffff, } public enum Dwarf2_Attribute : uint { DW_AT_sibling = 0x01, // reference DW_AT_location = 0x02, // block, constant DW_AT_name = 0x03, // string DW_AT_ordering = 0x09, // constant DW_AT_byte_size = 0x0b, // constant DW_AT_bit_offset = 0x0c, // constant DW_AT_bit_size = 0x0d, // constant DW_AT_stmt_list = 0x10, // constant DW_AT_low_pc = 0x11, // address DW_AT_high_pc = 0x12, // address DW_AT_language = 0x13, // constant DW_AT_discr = 0x15, // reference DW_AT_discr_value = 0x16, // constant DW_AT_visibility = 0x17, // constant DW_AT_import = 0x18, // reference DW_AT_string_length = 0x19, // block, constant DW_AT_common_reference = 0x1a, // reference DW_AT_comp_dir = 0x1b, // string DW_AT_const_value = 0x1c, // string, constant, block DW_AT_containing_type = 0x1d, // reference DW_AT_default_value = 0x1e, // reference DW_AT_inline = 0x20, // constant DW_AT_is_optional = 0x21, // flag DW_AT_lower_bound = 0x22, // constant, reference DW_AT_producer = 0x25, // string DW_AT_prototyped = 0x27, // flag DW_AT_return_addr = 0x2a, // block, constant DW_AT_start_scope = 0x2c, // constant DW_AT_stride_size = 0x2e, // constant DW_AT_upper_bound = 0x2f, // constant, reference DW_AT_abstract_origin = 0x31, // reference DW_AT_accessibility = 0x32, // constant DW_AT_address_class = 0x33, // constant DW_AT_artificial = 0x34, // flag DW_AT_base_types = 0x35, // reference DW_AT_calling_convention = 0x36, // constant DW_AT_count = 0x37, // constant, reference DW_AT_data_member_location = 0x38, // block, reference DW_AT_decl_column = 0x39, // constant DW_AT_decl_file = 0x3a, // constant DW_AT_decl_line = 0x3b, // constant DW_AT_declaration = 0x3c, // flag DW_AT_discr_list = 0x3d, // block DW_AT_encoding = 0x3e, // constant DW_AT_external = 0x3f, // flag DW_AT_frame_base = 0x40, // block, constant DW_AT_friend = 0x41, // reference DW_AT_identifier_case = 0x42, // constant DW_AT_macro_info = 0x43, // constant DW_AT_namelist_item = 0x44, // block DW_AT_priority = 0x45, // reference DW_AT_segment = 0x46, // block, constant DW_AT_specification = 0x47, // reference DW_AT_static_link = 0x48, // block, constant DW_AT_type = 0x49, // reference DW_AT_use_location = 0x4a, // block, constant DW_AT_variable_parameter = 0x4b, // flag DW_AT_virtuality = 0x4c, // constant DW_AT_vtable_elem_location = 0x4d, // block, reference //--// DWARF 4 //--// DW_AT_allocated = 0x4e, // constant, exprloc, reference DW_AT_associated = 0x4f, // constant, exprloc, reference DW_AT_data_location = 0x50, // exprloc DW_AT_byte_stride = 0x51, // constant, exprloc, reference DW_AT_entry_pc = 0x52, // address DW_AT_use_UTF8 = 0x53, // flag DW_AT_extension = 0x54, // reference DW_AT_ranges = 0x55, // rangelistptr DW_AT_trampoline = 0x56, // address, flag, reference, string DW_AT_call_column = 0x57, // constant DW_AT_call_file = 0x58, // constant DW_AT_call_line = 0x59, // constant DW_AT_description = 0x5a, // string DW_AT_binary_scale = 0x5b, // constant DW_AT_decimal_scale = 0x5c, // constant DW_AT_small = 0x5d, // reference DW_AT_decimal_sign = 0x5e, // constant DW_AT_digit_count = 0x5f, // constant DW_AT_picture_string = 0x60, // string DW_AT_mutable = 0x61, // flag DW_AT_threads_scaled = 0x62, // flag DW_AT_explicit = 0x63, // flag DW_AT_object_pointer = 0x64, // reference DW_AT_endianity = 0x65, // constant DW_AT_elemental = 0x66, // flag DW_AT_pure = 0x67, // flag DW_AT_recursive = 0x68, // flag DW_AT_signature = 0x69, // reference DW_AT_main_subprogram = 0x6a, // flag DW_AT_data_bit_offset = 0x6b, // constant DW_AT_const_expr = 0x6c, // flag DW_AT_enum_class = 0x6d, // flag DW_AT_linkage_name = 0x6e, // string DW_AT_lo_user = 0x2000, DW_AT_hi_user = 0x3fff } public enum Dwarf2_Form : uint { DW_FORM_addr = 0x01, // address DW_FORM_block2 = 0x03, // block DW_FORM_block4 = 0x04, // block DW_FORM_data2 = 0x05, // constant DW_FORM_data4 = 0x06, // constant DW_FORM_data8 = 0x07, // constant DW_FORM_string = 0x08, // string DW_FORM_block = 0x09, // block DW_FORM_block1 = 0x0a, // block DW_FORM_data1 = 0x0b, // constant DW_FORM_flag = 0x0c, // flag DW_FORM_sdata = 0x0d, // constant DW_FORM_strp = 0x0e, // string DW_FORM_udata = 0x0f, // constant DW_FORM_ref_addr = 0x10, // reference DW_FORM_ref1 = 0x11, // reference DW_FORM_ref2 = 0x12, // reference DW_FORM_ref4 = 0x13, // reference DW_FORM_ref8 = 0x14, // reference DW_FORM_ref_udata = 0x15, // reference DW_FORM_indirect = 0x16, //--// DWARF 4 //--// DW_FORM_sec_offset = 0x17, // lineptr, loclistptr, macptr, rangelistptr DW_FORM_exprloc = 0x18, // exprloc DW_FORM_flag_present= 0x19, // flag DW_FORM_ref_sig8 = 0x20, // reference } [StructLayout( LayoutKind.Sequential, Pack = 1 )] public struct Dwarf2_DebugLineHeader { public UInt32 lh_length; public UInt16 lh_version; public UInt32 lh_headerLen; public byte lh_minInstructionLen; public byte lh_maxOpsPerInstruction; public byte lh_defaultStmt; public sbyte lh_lineBase; public byte lh_lineRange; public byte lh_opcodeBase; } public class Dwarf_DebugLineHeaderFile { public string m_name; public uint m_directoryIndex; public uint m_fileModTime; public uint m_fileLen; } public static class Dwarf_Utility { public static string DwarfReadString(BinaryReader bs) { StringBuilder name = new StringBuilder(); char c; while( '\0' != ( c = (char)bs.ReadByte() ) ) { name.Append( c ); } return name.ToString(); } } public enum Dwarf_DebugLineOpCodes : byte { DW_LNS_copy = 1, DW_LNS_advance_pc, DW_LNS_advance_line, DW_LNS_set_file, DW_LNS_set_column, DW_LNS_negate_stmt, DW_LNS_set_basic_block, DW_LNS_const_add_pc, DW_LNS_fixed_advance_pc, DW_LNS_set_prologue_end, DW_LNS_set_epilogue_begin, DW_LNS_set_isa, } public enum Dwarf_DebugLineOpCodesExt : byte { DW_LNE_end_sequence = 1, DW_LNE_set_address, DW_LNE_define_file, } } ================================================ FILE: Zelig/Zelig/DebugTime/Elf/ElfLib/ElfObject_Factory.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // namespace Microsoft.Zelig.Elf { using System.Runtime.InteropServices; public partial class ElfObject { public static ElfObject CreateNew(ElfType type) { ElfObject obj = new ElfObject(); ElfSection section; obj.m_header = GenerateElfHeader(type); obj.AddSection(new ElfSection(obj, GenerateSectionZeroHeader())); // -- // section = new StringTable(obj); obj.AddSection(section); // We can't add names to sections until we set this property obj.SectionHeaderStringTable = (StringTable)section; section.Name = ".shstrtab"; // -- // section = new StringTable(obj); obj.AddSection(section); section.Name = ".strtab"; // -- // section = new SymbolTable(obj, (StringTable)section); obj.AddSection(section); section.Name = ".symtab"; obj.SymbolTable = (SymbolTable)section; InsertSymbolZeroEntry((SymbolTable) section); // -- // return obj; } private static Elf32_Ehdr GenerateElfHeader(ElfType type) { Elf32_Ehdr hdr = new Elf32_Ehdr(); hdr.e_type = (e_type)type; // At this time we are only supporting generation of ARM, 32-bit files. hdr.e_ident.EI_MAG0 = 0x7f; hdr.e_ident.EI_MAG1 = (byte)'E'; hdr.e_ident.EI_MAG2 = (byte)'L'; hdr.e_ident.EI_MAG3 = (byte)'F'; hdr.e_ident.EI_CLASS = EI_CLASS.ELFCLASS32; hdr.e_ident.EI_DATA = EI_DATA.ELFDATA2LSB; hdr.e_ident.EI_VERSION = (byte)e_version.EV_CURRENT; hdr.e_ident.EI_OSABI = EI_OSABI.ARM; hdr.e_ident.EI_ABIVERSION = 0; hdr.e_machine = e_machine.EM_ARM; hdr.e_version = e_version.EV_CURRENT; hdr.e_ehsize = (ushort)Marshal.SizeOf(typeof(Elf32_Ehdr)); hdr.e_phentsize = (ushort)Marshal.SizeOf(typeof(Elf32_Phdr)); hdr.e_shentsize = (ushort)Marshal.SizeOf(typeof(Elf32_Shdr)); return hdr; } private static Elf32_Shdr GenerateSectionZeroHeader() { // The section entry for index 0 is reserved, it holds the following // Name Value Note // sh_name 0 No name // sh_type SHT_NULL Inactive // sh_flags 0 No flags // sh_addr 0 No address // sh_offset 0 No offset // sh_size Unspecified If non-zero, the actual number of section header entries // sh_link Unspecified If non-zero, the index of the section header string table section // sh_info 0 No auxiliary information // sh_addralign 0 No alignment // sh_entsize 0 No entries Elf32_Shdr hdr = new Elf32_Shdr(); hdr.sh_name = 0; hdr.sh_type = sh_type.SHT_NULL; hdr.sh_flags = 0; hdr.sh_addr = 0; hdr.sh_offset = 0; hdr.sh_size = 0; hdr.sh_link = 0; hdr.sh_info = 0; hdr.sh_addralign = 0; hdr.sh_entsize = 0; return hdr; } private static void InsertSymbolZeroEntry(SymbolTable tbl) { // The symbol table entry for index 0 is reserved, it holds the following // Name Value Note // st_name 0 No name // st_value 0 Zero value // st_size 0 No size // st_info 0 No type, local binding // st_other 0 Default visibility // st_shndx SHN_UNDEF No section tbl.AddSymbol("", 0, 0, SymbolType.STT_NOTYPE, SymbolBinding.STB_LOCAL, SymbolVisibility.STV_DEFAULT, null); } } } ================================================ FILE: Zelig/Zelig/DebugTime/Elf/ElfLib/ElfObject_FileUtil.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // namespace Microsoft.Zelig.Elf { using System; using System.Collections.Generic; using System.IO; using System.Runtime.InteropServices; using System.Text.RegularExpressions; public partial class ElfObject { public enum LibraryProvider { RVCT, GCC, GCCOP, } public enum SystemArchitecture { ArmV4, ThumbV4, ArmV5, Thumb2, Thumb1 } public enum FloatingPointUnit { None, SoftVFP, VFP, } public enum Endian { Big, Little, } public abstract class DeviceType { public abstract LibraryProvider Provider {get;} public abstract SystemArchitecture Architecture {get;} public abstract FloatingPointUnit FPU {get;} public abstract Endian Endianness {get;} public virtual bool CheckFile( string filePath ) { return true; } } public class RvctDeviceType : DeviceType { SystemArchitecture m_architecture; FloatingPointUnit m_FPU; Endian m_endianness; public override LibraryProvider Provider { get { return LibraryProvider.RVCT; } } public override SystemArchitecture Architecture { get { return m_architecture; } } public override FloatingPointUnit FPU { get { return m_FPU; } } public override Endian Endianness { get { return m_endianness; } } enum RootFile { c, // ISO C and C++ basic runtime support. f, // IEEE compliant library with a fixed rounding mode (Round to nearest) and no inexact exceptions. fj, // IEEE compliant library with a fixed rounding mode (Round to nearest) and no exceptions (--fpmode ieee_no_fenv). fz, // Behaves like the fj library, but additionally flushes denormals and infinities to zero (--fpmode std and --fpmode fast). // This library behaves like the ARM VFP in Fast mode. This is the default. g, // IEEE compliant library with configurable rounding mode and all IEEE exceptions. m, // Transcendental math functions. h, // Compiler support (helper) library. See Helper libraries. cpp, // Rogue Wave C++ library. cpprt,// The ARM C++ runtime libraries. mc, // Non compliant ISO C micro-library basic runtime support. mf, // Non compliant IEEE 754 micro-library support. } public RvctDeviceType( SystemArchitecture arch, FloatingPointUnit fpu, Endian endian ) { m_architecture = arch; m_FPU = fpu; m_endianness = endian; } public RvctDeviceType() { m_architecture = SystemArchitecture.ArmV5; m_FPU = FloatingPointUnit.None; m_endianness = Endian.Little; } public override bool CheckFile(string filePath) { //root_. string test = Path.GetFileName(filePath.ToLower()); bool isPossibleArmFile = false; foreach(string en in Enum.GetNames( typeof(RootFile) )) { if(test.StartsWith( en + "_" )) { isPossibleArmFile = true; break; } } if(!isPossibleArmFile) return true; string arch = ""; string fpu = ""; string end = ""; switch(m_architecture) { case SystemArchitecture.ArmV4: arch = "[4|a]?"; break; case SystemArchitecture.ThumbV4: arch = "t?"; break; case SystemArchitecture.ArmV5: arch = "5?"; break; case SystemArchitecture.Thumb2: arch = "w?"; break; case SystemArchitecture.Thumb1: arch = "p?"; break; } switch(m_FPU) { case FloatingPointUnit.VFP: fpu = "v?"; break; case FloatingPointUnit.SoftVFP: fpu = "s?"; break; } switch(m_endianness) { case Endian.Big: end = "b"; break; case Endian.Little: end = "l"; break; } //root_. string c_Fmt = ".*_" + arch + fpu + "u?" + "e?" + "\\." + end; Regex reg = new Regex(c_Fmt); return reg.IsMatch(test); } } public class FileUtil { public static DeviceType DeviceConfiguration = new RvctDeviceType(); public static ElfObject[] Parse(string path) { List elfs = new List(); FileStream fs; long elfOffset = 0; if(!DeviceConfiguration.CheckFile( path )) return elfs.ToArray(); try { fs = File.OpenRead(path); while( SeekToElfHeader( fs ) ) { var elf = new ElfObject(); elf.m_file = path; elf.m_header = ReadElfHeader( fs, ref elfOffset ); if( elf.m_header.e_ident.EI_DATA != EI_DATA.ELFDATA2LSB ) break; if( elf.m_header.e_machine != e_machine.EM_ARM ) break; //if( elf.m_header.e_type != e_type.ET_REL ) break; // Process Section Headers var shdrs = ReadSectionHeaders( elf.m_header, fs, elfOffset ); for( UInt16 i = 0; i < shdrs.Length; i++ ) { switch( shdrs[i].sh_type ) { case sh_type.SHT_NOBITS: elf.m_sections.Add( new ElfSection( elf, shdrs[i], i, new byte[shdrs[i].sh_size], shdrs[i].sh_offset ) ); break; case sh_type.SHT_GROUP: //TODO: Better handle GROUPS (since they can share the same symbol name) ElfSection sec = new ElfSection( elf, shdrs[i], i, ReadSectionData( shdrs[i], fs, elfOffset ), shdrs[i].sh_offset ); elf.m_groups.Add( sec ); elf.m_sections.Add( sec ); break; case sh_type.SHT_SYMTAB: elf.m_sections.Add( new SymbolTable( elf, shdrs[i], i, ReadSectionEntries( shdrs[i], fs, elfOffset ) ) ); break; case sh_type.SHT_STRTAB: elf.m_sections.Add( new StringTable( elf, shdrs[i], i, ReadSectionData( shdrs[i], fs, elfOffset ) ) ); break; case sh_type.SHT_REL: if( shdrs[i].sh_entsize == Marshal.SizeOf( typeof( Elf32_Rel ) ) ) { elf.m_sections.Add( new RelocationSection( elf, shdrs[i], i, ReadSectionEntries( shdrs[i], fs, elfOffset ) ) ); } else { elf.m_sections.Add( new RelocationSection( elf, shdrs[i], i, ReadSectionEntries( shdrs[i], fs, elfOffset ) ) ); } break; default: elf.m_sections.Add( new ElfSection( elf, shdrs[i], i, ReadSectionData( shdrs[i], fs, elfOffset ), shdrs[i].sh_offset ) ); break; } } elf.m_nextSectionIndex = (UInt16)shdrs.Length; // Process Program Headers if( elf.m_header.e_phnum > 0 ) { foreach( var phdr in ReadProgramHeaders( elf.m_header, fs, elfOffset ) ) { elf.m_segments.Add( new ElfSegment( elf, phdr ) ); } } elf.BuildReferences(); if( elf.m_symbolTable.BuildAttributes.Count == 0 || //(elf.m_symbolTable.BuildAttributes.Contains( "ARM_ISAv4" ) && !elf.m_symbolTable.BuildAttributes.Contains( "RWPI" ) && !elf.m_symbolTable.BuildAttributes.Contains( "FPIC" )// && //!elf.m_symbolTable.BuildAttributes.Contains( "VFPv2" ) && //!elf.m_symbolTable.BuildAttributes.Contains( "VFPv3" ) ) //|| //elf.m_symbolTable.BuildAttributes.Contains( "ARM_ISAv5" ) ) { elfs.Add( elf ); } } } catch { } return elfs.ToArray(); } public static void GenerateFile(string path, ElfObject elf) { var ehdrsize = Marshal.SizeOf(typeof (Elf32_Ehdr)); var phdrs = new Elf32_Phdr[elf.m_segments.Count]; var shdrs = new Elf32_Shdr[elf.m_sections.Count]; var raw = new byte[CalcRawByteSize(elf.m_sections)]; int rawIndex = 0; int rawOffset = 0; int i = 0; elf.m_header.e_phnum = (ushort) phdrs.Length; elf.m_header.e_phoff = (phdrs.Length > 0) ? (uint)ehdrsize : 0; rawOffset = ehdrsize + phdrs.Length * elf.m_header.e_phentsize; elf.m_header.e_shnum = (ushort) shdrs.Length; elf.m_header.e_shoff = (uint)(rawOffset + raw.Length); var usedList = new List(); foreach (var segment in elf.GetSortedSegmentList()) { uint segSize = 0; uint segOffset = int.MaxValue; foreach (var section in segment.ReferencedSections) { usedList.Add(section); if (section.Raw.Length > 0) { Buffer.BlockCopy(section.Raw, 0, raw, rawIndex, section.Raw.Length); section.m_header.sh_offset = (uint)(rawOffset + rawIndex); section.m_header.sh_size = (uint) section.Raw.Length; segSize += (uint)section.Raw.Length; rawIndex += section.Raw.Length; segOffset = Math.Min(segOffset, section.m_header.sh_offset); } } segment.m_header.p_filesz = segSize; segment.m_header.p_memsz = segSize; segment.m_header.p_offset = segOffset; phdrs[i] = segment.m_header; i++; } i = 0; foreach (var section in elf.Sections) { if (!usedList.Contains(section)) { Buffer.BlockCopy(section.Raw, 0, raw, rawIndex, section.Raw.Length); section.m_header.sh_offset = (uint)(rawOffset + rawIndex); section.m_header.sh_size = (uint) section.Raw.Length; rawIndex += section.Raw.Length; } shdrs[i] = section.m_header; i++; } FileStream fs = null; try { fs = File.Open(path, FileMode.Create); WriteElfHeader( elf.m_header, fs ); //WriteStructureArray(phdrs, fs); foreach (var phdr in phdrs) { WriteStructure(phdr, fs); } fs.Write(raw, 0, raw.Length); //WriteStructureArray(shdrs, fs); foreach (var shdr in shdrs) { WriteStructure(shdr, fs); } fs.Close(); } finally { if (fs != null) { fs.Dispose(); } } } private static uint CalcRawByteSize(IEnumerable sections) { uint total = 0; foreach (var section in sections) { total += (uint)section.Raw.Length; } return total; } internal static bool SeekToElfHeader(Stream reader) { bool foundElf = false; int state = 0; int by; while( !foundElf && -1 != ( by = reader.ReadByte() ) ) { switch( by ) { case 0x7F: state = ( state == 0 ) ? state + 1 : 0; break; case 0x45: state = ( state == 1 ) ? state + 1 : 0; break; case 0x4C: state = ( state == 2 ) ? state + 1 : 0; break; case 0x46: if( state == 3 ) { foundElf = true; reader.Seek( -4, SeekOrigin.Current ); } else { state = 0; } break; default: state = 0; break; } } return foundElf; } internal static Elf32_Ehdr ReadElfHeader(Stream reader, ref long elfOffset) { if( !SeekToElfHeader(reader)) throw new ArgumentException(); elfOffset = reader.Position; var size = Marshal.SizeOf(typeof (Elf32_Ehdr)); var ptr = Marshal.AllocHGlobal(size); var buff = new byte[size]; reader.Read(buff, 0, buff.Length); Marshal.Copy(buff, 0, ptr, buff.Length); var hdr = (Elf32_Ehdr)Marshal.PtrToStructure(ptr, typeof (Elf32_Ehdr)); Marshal.FreeHGlobal(ptr); return hdr; } internal static void WriteElfHeader(Elf32_Ehdr hdr, Stream writer) { var size = Marshal.SizeOf(typeof (Elf32_Ehdr)); writer.Seek(0, SeekOrigin.Begin); var ptr = Marshal.AllocHGlobal(size); Marshal.StructureToPtr(hdr, ptr, false); var raw = new byte[size]; Marshal.Copy(ptr, raw, 0, size); writer.Write(raw, 0, raw.Length); Marshal.FreeHGlobal(ptr); } internal static void WriteStructure(T val, Stream writer) where T : struct { var size = Marshal.SizeOf(typeof (T)); var ptr = Marshal.AllocHGlobal(size); Marshal.StructureToPtr(val, ptr, false); var raw = new byte[size]; Marshal.Copy(ptr, raw, 0, size); writer.Write(raw, 0, raw.Length); Marshal.FreeHGlobal(ptr); } //internal static void WriteStructureArray(T[] arr, Stream writer) // where T : struct //{ // var size = Marshal.SizeOf( typeof(T)) * arr.Length; // var ptr = Marshal.AllocHGlobal(size); // Marshal.StructureToPtr(arr[0], ptr, false); // var raw = new byte[size]; // Marshal.Copy(ptr, raw, 0, size); // writer.Write(raw, 0, raw.Length); // //test // var copyback = new T[arr.Length]; // var handle = GCHandle.Alloc(copyback, GCHandleType.Pinned); // var ptr2 = handle.AddrOfPinnedObject(); // var buff = new byte[size]; // Marshal.Copy(raw, // 0, // ptr2, // buff.Length); // handle.Free(); // // end test // Marshal.FreeHGlobal(ptr); //} internal static Elf32_Phdr[] ReadProgramHeaders(Elf32_Ehdr hdr, Stream reader, long elfOffset) { if( hdr.e_phnum == 0 ) return new Elf32_Phdr[0]; var hdrs = new Elf32_Phdr[hdr.e_phnum]; var handle = GCHandle.Alloc(hdrs, GCHandleType.Pinned); var ptr = handle.AddrOfPinnedObject(); var buff = new byte[hdr.e_phentsize * hdr.e_phnum]; reader.Seek(hdr.e_phoff + elfOffset, SeekOrigin.Begin); reader.Read(buff, 0, buff.Length); Marshal.Copy(buff, 0, ptr, buff.Length); handle.Free(); return hdrs; } internal static Elf32_Shdr[] ReadSectionHeaders(Elf32_Ehdr hdr, Stream reader, long elfOffset) { var sections = new Elf32_Shdr[hdr.e_shnum]; var handle = GCHandle.Alloc(sections, GCHandleType.Pinned); var ptr = handle.AddrOfPinnedObject(); var buff = new byte[hdr.e_shentsize * hdr.e_shnum]; reader.Seek(hdr.e_shoff + elfOffset, SeekOrigin.Begin); reader.Read(buff, 0, buff.Length); Marshal.Copy(buff, 0, ptr, buff.Length); handle.Free(); return sections; } internal static T[] ReadSectionEntries(Elf32_Shdr hdr, Stream reader, long elfOffset) { var entries = new T[hdr.sh_size / hdr.sh_entsize]; var handle = GCHandle.Alloc(entries, GCHandleType.Pinned); var ptr = handle.AddrOfPinnedObject(); var buff = new byte[hdr.sh_size]; reader.Seek(hdr.sh_offset + elfOffset, SeekOrigin.Begin); reader.Read(buff, 0, buff.Length); Marshal.Copy(buff, 0, ptr, buff.Length); handle.Free(); return entries; } internal static byte[] ReadSectionData(Elf32_Shdr hdr, Stream reader, long elfOffset) { var buff = new byte[hdr.sh_size]; reader.Seek(hdr.sh_offset + elfOffset, SeekOrigin.Begin); reader.Read(buff, 0, buff.Length); return buff; } } } } ================================================ FILE: Zelig/Zelig/DebugTime/Elf/ElfLib/ElfObject_HelperTypes.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // namespace Microsoft.Zelig.Elf { using System; // // Enum Definitions // public enum ElfType { Linking = e_type.ET_REL, Execution = e_type.ET_EXEC, } public enum ElfElementStatus { Added , Removed , IndexChanged, AddressChanged, } // // Interface Definitions // internal interface IElfElement { void BuildReferences(); } internal interface IElfElementStatusPublisher { event Action ElementStatusChangedEvent; } // // Exception Definitions // public class ElfConsistencyException : Exception { public ElfConsistencyException( string message ) : base( message ) { } } } ================================================ FILE: Zelig/Zelig/DebugTime/Elf/ElfLib/ElfSection.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // namespace Microsoft.Zelig.Elf { using System; using System.Collections.Generic; public class ElfSection : IElfElement, IElfElementStatusPublisher { // // State // internal ElfObject m_parent; internal string m_name; internal Elf32_Shdr m_header; internal UInt16 m_index; internal long m_elfOffset; protected byte[] m_raw; internal List m_relocations; internal List m_dbgInfo; internal List m_references; internal Dictionary m_aliases; // // Constructor Methods // internal ElfSection(ElfObject parent, Elf32_Shdr hdr, UInt16 index) : this(parent, hdr, index, new byte[0], 0) { } internal ElfSection(ElfObject parent, Elf32_Shdr hdr, UInt16 index, byte[] raw, long elfOffset) : this(parent, raw) { m_header = hdr; m_index = index; m_elfOffset = elfOffset; } internal ElfSection(ElfObject parent, Elf32_Shdr hdr) : this(parent, new byte[0]) { m_header = hdr; } internal ElfSection(ElfObject parent, byte[] raw) : this(parent) { m_raw = raw; } internal ElfSection(ElfObject parent) { m_parent = parent; m_relocations = new List(); m_dbgInfo = new List(); m_references = new List(); m_aliases = new Dictionary(); } // // Access Methods // public List DebugEntries { get { return m_dbgInfo; } } public List References { get { return m_references; } } public List Relocations { get { return m_relocations; } } public Dictionary Aliases { get { return m_aliases; } } public ElfObject Parent { get { return m_parent; } } public string Name { get { return m_name; } set { var tbl = m_parent.SectionHeaderStringTable; if (tbl != null) { m_header.sh_name = tbl.AddString(value); m_name = value; } else { throw new ElfConsistencyException("Missing string table"); } } } public Elf32_Shdr Header { get { return m_header; } } public UInt32 AddressInMemory { get { return m_header.sh_addr; } set { m_header.sh_addr = value; if( ElementStatusChangedEvent != null ) { ElementStatusChangedEvent( this, ElfElementStatus.AddressChanged ); } } } public bool IsDataSection { get { sh_flags flags = ~(sh_flags.SHF_WRITE | sh_flags.SHF_MERGE | sh_flags.SHF_STRINGS); return sh_flags.SHF_ALLOC == ( m_header.sh_flags & flags ); } } internal UInt16 Index { get { return m_index; } set { m_index = value; // Update subcribers about index change if (ElementStatusChangedEvent != null) { ElementStatusChangedEvent(this, ElfElementStatus.IndexChanged); } } } public virtual byte[] Raw { get { return m_raw; } } public void AddReference(RelocationEntry entry) { bool fAdded = false; foreach( SectionReference sr in m_references ) { if( entry.m_symbolRef.m_sectionRef != null ) { int refIndex = entry.m_symbolRef.m_sectionRef.m_index; if( refIndex == sr.Section.m_index && refIndex != 0 && sr.Section.m_name == entry.m_symbolRef.Name ) { sr.CallOffsets.Add( new SectionReference.SymbolReference( entry.SectionOffset, entry, sr ) ); fAdded = true; break; } } } if( !fAdded ) { if(entry.m_symbolRef.m_sectionRef != null) { m_references.Add( new SectionReference( m_parent.Sections[entry.m_symbolRef.m_sectionRef.m_index], entry, entry.SectionOffset ) ); } else { m_references.Add( new SectionReference( m_parent.Sections[0], entry, entry.SectionOffset ) ); } } } // // Interface Implementation // public event Action ElementStatusChangedEvent; public virtual void BuildReferences() { var tbl = m_parent.SectionHeaderStringTable; if (tbl != null) { m_name = tbl.GetString(m_header.sh_name); } else { throw new ElfConsistencyException("Missing string table"); } } } } ================================================ FILE: Zelig/Zelig/DebugTime/Elf/ElfLib/ElfSegment.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // namespace Microsoft.Zelig.Elf { using System; using System.Collections.Generic; // // We assume that our ELF file has section headers, even for an 'EXEC' type file. // We use section references to build up our view of what a segment contains. // It is possible to have ELF 'EXEC' type files without any section headers. Although // in practice it is not normally seen. Be aware of this fact when building en execution // view ELF file. Build the binary portion of the file out of sections that get // referenced by the segments, even if the sections serve no other purpose. // public class ElfSegment : IElfElement { private ElfObject m_parent; internal Elf32_Phdr m_header; internal List m_sectionRefs; internal ElfSegment(ElfObject parent, UInt32 addressInMemory) : this() { m_parent = parent; m_header.p_vaddr = addressInMemory; m_header.p_paddr = addressInMemory; m_header.p_type = SegmentType.PT_LOAD; m_header.p_flags = SegmentFlag.PF_R & SegmentFlag.PF_W & SegmentFlag.PF_X; } internal ElfSegment(ElfObject parent, Elf32_Phdr hdr) : this() { m_parent = parent; m_header = hdr; } private ElfSegment() { m_sectionRefs = new List(); } public void AddReferencedSection(ElfSection section) { if (!m_sectionRefs.Contains(section)) { m_sectionRefs.Add(section); } } public Elf32_Phdr Header { get { return m_header; } } public SegmentType Type { get { return m_header.p_type; } } public UInt32 AddressInMemory { get { return m_header.p_vaddr; } set { m_header.p_vaddr = value; m_header.p_paddr = value; } } public ElfSection[] ReferencedSections { get { m_sectionRefs.Sort(CompareReferencedSectionsByAddress); return m_sectionRefs.ToArray(); } } internal static int CompareReferencedSectionsByAddress(ElfSection x, ElfSection y) { if (x == y) { return 0; } if (x.m_header.sh_addr <= y.m_header.sh_addr) { return -1; } return 1; } public void BuildReferences() { // Build list of referenced sections foreach (var section in m_parent.Sections) { // Compare allocated sections by VMA if ((section.Header.sh_flags & sh_flags.SHF_ALLOC) != 0) { if (section.m_header.sh_addr >= m_header.p_vaddr && (section.m_header.sh_addr + section.m_header.sh_size) <= (m_header.p_vaddr + m_header.p_memsz)) { m_sectionRefs.Add(section); } } // Otherwise, compare by file offsets else { if (section.m_header.sh_offset >= m_header.p_offset && (section.m_header.sh_offset + section.m_header.sh_size) <= (m_header.p_offset + m_header.p_filesz)) { m_sectionRefs.Add(section); } } } } } } ================================================ FILE: Zelig/Zelig/DebugTime/Elf/ElfLib/Elflib.csproj ================================================  Debug AnyCPU 9.0.30729 2.0 {37193A86-BA04-4A3E-9DF8-656DF455E952} Library Properties Microsoft.Zelig.Elf Microsoft.Zelig.Elf.Elflib v4.5 512 true full false ..\..\..\..\ZeligBuild\Host\bin\Debug\ DEBUG;TRACE prompt 4 AllRules.ruleset AnyCPU false pdbonly true ..\..\..\..\ZeligBuild\Host\bin\Release\ TRACE prompt 4 AllRules.ruleset AnyCPU false true bin\Instrumentation\ DEBUG;TRACE full AnyCPU prompt AllRules.ruleset false 3.5 ================================================ FILE: Zelig/Zelig/DebugTime/Elf/ElfLib/OutputFormatter.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // namespace Microsoft.Zelig.Elf { using System; using System.Collections.Generic; using System.Text; using System.Text.RegularExpressions; using System.Runtime.InteropServices; using Microsoft.Zelig.Elf; public class OutputFormatter { class TypeSizeComparerHighToLow : IComparer { public int Compare( NameSizePair x, NameSizePair y ) { int res = y.SizeInBytes.CompareTo( x.SizeInBytes ); if(res == 0) { return 1; // Handle equality as beeing greater, so that multipe values with same key will fit } return res; } } class MethodSizeComparerHighToLow : IComparer { public int Compare( NameSizeQuadruple x, NameSizeQuadruple y ) { int res = y.SizeInBytes.CompareTo( x.SizeInBytes ); if(res == 0) { return 1; // Handle equality as beeing greater, so that multipe values with same key will fit } return res; } } class MethodNameComparer : IComparer { public int Compare( NameSizeQuadruple x, NameSizeQuadruple y ) { int res = x.DecoratedMethodName.CompareTo( y.DecoratedMethodName ); if(res == 0) { return 1; // Handle equality as beeing greater, so that multipe values with same key will fit } return res; } } //--// public class NameSizePair { public string Name; public uint SizeInBytes; } public class NameSizeQuadruple { public string MethodName; public string DecoratedMethodName; public string OwnerType; public uint SizeInBytes; } //--// //--// //--// public static OutputFormatter.NameSizePair[] ComputeAllSizes( SymbolTable symbols ) { var nameSizePairs = new List(); uint totalSizeFunctions = 0; uint totalSizeZeligMethods = 0; uint totalSizeObjects = 0; Array.ForEach( symbols.Symbols, s => { if(s.Type == SymbolType.STT_FUNC) { totalSizeFunctions += s.SymbolDef.st_size; } } ); Array.ForEach( symbols.Symbols, s => { if(s.Type == SymbolType.STT_FUNC) { if(s.ReferencedSection.Name.Contains( ".llilum" )) { totalSizeZeligMethods += s.SymbolDef.st_size; } } } ); Array.ForEach( symbols.Symbols, s => { if(s.Type == SymbolType.STT_OBJECT && s.ReferencedSection.Name.Contains( ".llilum" )) { totalSizeObjects += s.SymbolDef.st_size; } } ); nameSizePairs.Add( new OutputFormatter.NameSizePair( ) { Name = "All Code " , SizeInBytes = totalSizeFunctions } ); nameSizePairs.Add( new OutputFormatter.NameSizePair( ) { Name = "Zelig Methods" , SizeInBytes = totalSizeZeligMethods } ); nameSizePairs.Add( new OutputFormatter.NameSizePair( ) { Name = "Objects " , SizeInBytes = totalSizeObjects } ); return nameSizePairs.ToArray( ); } public static uint ComputeAllSizesMethodByMethod( SymbolTable symbols, Dictionary lillumTypes, List lillumMethods, List otherFunctions ) { uint totalSize = 0; Array.ForEach( symbols.Symbols, s => { totalSize += s.SymbolDef.st_size; if(s.Type == SymbolType.STT_FUNC) { string typeName = "???"; string methodName = "???"; string decoratedMethodName = "???"; bool parsed = ParseTypeAndMethodName( s, ref methodName, ref decoratedMethodName, ref typeName ); var methodEntry = new OutputFormatter.NameSizeQuadruple( ) { MethodName = methodName, DecoratedMethodName = decoratedMethodName, OwnerType = typeName, SizeInBytes = s.SymbolDef.st_size }; if( s.ReferencedSection.Name.Contains( ".llilum" ) && parsed ) { lillumMethods.Add( methodEntry ); if(lillumTypes.ContainsKey( typeName ) == false) { lillumTypes.Add( typeName, new OutputFormatter.NameSizePair( ) { Name = typeName, SizeInBytes = s.SymbolDef.st_size } ); } lillumTypes[ typeName ].SizeInBytes += s.SymbolDef.st_size; } else { otherFunctions.Add( methodEntry ); } } }); return totalSize; } //--// //--// //--// public static string PrintElfHeader( Elf32_Ehdr hdr ) { var sb = new StringBuilder(); sb.AppendLine( "============================================================================================" ); sb.AppendLine( "ELF Header:" ); sb.AppendLine( ); // -- print Ident section e.g. "Magic Numbers" -- // var raw = new byte[Marshal.SizeOf(hdr.e_ident)]; var handle = GCHandle.Alloc(raw, GCHandleType.Pinned); var ptr = handle.AddrOfPinnedObject(); Marshal.StructureToPtr( hdr.e_ident, ptr, false ); handle.Free( ); sb.AppendLine( "Magic: " + BitConverter.ToString( raw ) ); // --------------------------------------------- // var val = (EI_CLASS) hdr.e_ident.EI_CLASS; var val2 = (EI_DATA) hdr.e_ident.EI_DATA; var val3 = (e_version) hdr.e_ident.EI_VERSION; var val4 = (EI_OSABI) hdr.e_ident.EI_OSABI; var val5 = (e_type) hdr.e_type; var val6 = (e_machine) hdr.e_machine; sb.AppendLine( "Class: " + val ); sb.AppendLine( "Data: " + val2 ); sb.AppendLine( "Version: " + val3 ); sb.AppendLine( "OS/ABI: " + val4 ); sb.AppendLine( "ABI Version: " + hdr.e_ident.EI_ABIVERSION ); sb.AppendLine( "Type: " + val5 ); sb.AppendLine( "Machine: " + val6 ); sb.AppendLine( "Version: " + "0x" + hdr.e_version.ToString( "X" ) ); sb.AppendLine( "Entry point address: " + "0x" + hdr.e_entry.ToString( "X" ) ); sb.AppendLine( "Start of program headers: " + hdr.e_phoff + " (bytes into file)" ); sb.AppendLine( "Start of section headers: " + hdr.e_shoff + " (bytes into file)" ); sb.AppendLine( "Flags: " + "0x" + hdr.e_flags.ToString( "X" ) ); sb.AppendLine( "Size of this header: " + hdr.e_ehsize + " (bytes)" ); sb.AppendLine( "Size of program headers: " + hdr.e_phentsize + " (bytes)" ); sb.AppendLine( "Number of program headers: " + hdr.e_phnum ); sb.AppendLine( "Size of section hdeaders: " + hdr.e_shentsize + " (bytes)" ); sb.AppendLine( "Number of section headers: " + hdr.e_shnum ); sb.AppendLine( "Section header string table index: " + hdr.e_shtrndx ); sb.AppendLine( ); return sb.ToString( ); } public static string PrintSectionHeaders( ElfSection[] sections ) { var sb = new StringBuilder(); sb.AppendLine( "============================================================================================" ); sb.AppendLine( "Section Headers:" ); sb.AppendLine( ); sb.AppendLine( "[Nr] Name Type Addr Off Size ES Flg Lk Inf Al" ); int longestSectionNameLength = 0; foreach(var section in sections) { if(section.Name?.Length > longestSectionNameLength) { longestSectionNameLength = section.Name.Length; } } for(int i = 0; i < sections.Length; i++) { var shdr = sections[i].Header; sb.Append( "[" + i.ToString( "D2" ) + "] " ); sb.Append( sections[ i ].Name.PadRight( longestSectionNameLength + 3 ) ); sb.Append( ( (sh_type)shdr.sh_type ).ToString( ).PadRight( 16 ) ); sb.Append( shdr.sh_addr.ToString( "X8" ).PadRight( 9 ) ); sb.Append( shdr.sh_offset.ToString( "X6" ).PadRight( 7 ) ); sb.Append( shdr.sh_size.ToString( "X6" ).PadRight( 7 ) ); sb.Append( shdr.sh_entsize.ToString( "X2" ).PadRight( 3 ) ); string displayFormat = "WAXMSILOGxop"; string output = ""; uint flags = (uint)shdr.sh_flags; int x = 0; while(x < 9) { if(( flags & 1 ) > 0) { output += displayFormat.Substring( x, 1 ); } if(x == 2) { flags >>= 2; } else if(x == 8) { flags >>= 4; } else { flags >>= 1; } x++; } if(( shdr.sh_flags & sh_flags.SHF_MASKOS ) > 0) { output += "o"; } if(( shdr.sh_flags & sh_flags.SHF_MASKPROC ) > 0) { output += "p"; } sb.Append( output.PadLeft( 3 ).PadRight( 4 ) ); sb.Append( shdr.sh_link.ToString( "D2" ).PadRight( 3 ) ); sb.Append( shdr.sh_info.ToString( "D2" ).PadLeft( 3 ) ); sb.Append( shdr.sh_addralign.ToString( "X1" ).PadLeft( 3 ) ); sb.AppendLine( ); } sb.AppendLine( "Key to Flags:" ); sb.AppendLine( "W (write), A (alloc), X (execute), M (merge), S (strings)" ); sb.AppendLine( "I (info), L (link order), G (group), x (unknown)" ); sb.AppendLine( "0 (extra OS processing required), o (OS specific), p (processor specific)" ); sb.AppendLine( ); return sb.ToString( ); } public static string PrintAllSizes( NameSizePair[] pairs ) { var sb = new StringBuilder(); sb.AppendLine( "============================================================================================" ); sb.AppendLine( "Object Sizes" ); sb.AppendLine( ); foreach(var pair in pairs) { sb.AppendLine( String.Format( "-- {0}: ==> {1} bytes", pair.Name, pair.SizeInBytes ) ); } sb.AppendLine( ); return sb.ToString( ); } public static string PrintTotalSizeMethodByMethod( uint totalSize ) { var sb = new StringBuilder(); sb.AppendLine( "============================================================================================" ); sb.AppendLine( $"Total size: {totalSize}" ); sb.AppendLine( ); return sb.ToString( ); } public static string PrintAllTypesSizes( Dictionary llilumTypes, List otherFunctions ) { var typesBySize = new SortedSet( new TypeSizeComparerHighToLow() ); foreach(var type in llilumTypes.Values) { typesBySize.Add( type ); } var sb = new StringBuilder(); sb.AppendLine( "============================================================================================" ); sb.AppendLine( "Types size (types with methods)" ); sb.AppendLine( ); sb.AppendLine( "types count: " + typesBySize.Count ); sb.AppendLine( ); foreach(var type in typesBySize) { sb.AppendLine( String.Format( "{0} => {1} bytes", type.Name, type.SizeInBytes ) ); } sb.AppendLine( ); return sb.ToString( ); } public static string PrintAllMethodsSizes( List lillumMethods, List otherFunctions, bool bySizeOrder ) { SortedSet methods; if(bySizeOrder) { methods = new SortedSet( new MethodSizeComparerHighToLow( ) ); } else { methods = new SortedSet( new MethodNameComparer( ) ); } foreach(var type in lillumMethods) { methods.Add( type ); } var sb = new StringBuilder(); sb.AppendLine( "============================================================================================" ); sb.AppendLine( String.Format("Methods sizes ({0})", bySizeOrder? "size order" : "alphabetical order") ); sb.AppendLine( ); sb.AppendLine( "Methods count: " + methods.Count ); sb.AppendLine( ); foreach(var method in methods) { sb.AppendLine( String.Format( "{0}::{1} ({2}) ==> {3} bytes", method.OwnerType, method.MethodName, method.DecoratedMethodName, method.SizeInBytes ) ); } sb.AppendLine( ); return sb.ToString( ); } public static string PrintSymbolTable( SymbolTable tbl ) { var sb = new StringBuilder(); sb.AppendLine( "============================================================================================" ); sb.AppendLine( "Symbol table '" + tbl.Name + "' containts " + tbl.Symbols.Length + " entries:" ); sb.AppendLine( ); sb.AppendLine( " Num: Value Size Type Bind Vis Ndx Name" ); for(UInt16 i = 0; i < tbl.Symbols.Length; i++) { var symbol = tbl[i]; sb.Append( ( i + ": " ).PadLeft( 8 ) ); sb.Append( symbol.SymbolDef.st_value.ToString( "X8" ).PadRight( 9 ) ); sb.Append( symbol.SymbolDef.st_size.ToString( ).PadLeft( 5 ).PadRight( 6 ) ); sb.Append( symbol.Type.ToString( ).Substring( symbol.Type.ToString( ).IndexOf( "_" ) + 1 ).PadRight( 8 ) ); sb.Append( symbol.Binding.ToString( ).Substring( symbol.Binding.ToString( ).IndexOf( "_" ) + 1 ).PadRight( 7 ) ); sb.Append( symbol.Visibility.ToString( ).Substring( symbol.Visibility.ToString( ).IndexOf( "_" ) + 1 ).PadRight( 9 ) ); if(symbol.SymbolDef.st_shndx == (ushort)NamedIndexes.SHN_UNDEF) { sb.Append( "UND".PadRight( 4 ) ); } else if(symbol.SymbolDef.st_shndx == (ushort)NamedIndexes.SHN_ABS) { sb.Append( "ABS".PadRight( 4 ) ); } else { sb.Append( symbol.SymbolDef.st_shndx.ToString( ).PadLeft( 3 ).PadRight( 4 ) ); } sb.Append( symbol.Name ); sb.AppendLine( ); } sb.AppendLine( ); return sb.ToString( ); } public static string PrintProgramHeaders( ElfObject elf ) { var sb = new StringBuilder(); var ehdr = elf.Header; sb.AppendLine( "============================================================================================" ); sb.AppendLine( "Elf file type is " + ( (e_type)ehdr.e_type ) ); sb.AppendLine( "Entry point 0x" + ehdr.e_entry.ToString( "X8" ) ); sb.AppendLine( "There are " + ehdr.e_phnum + " program headers, starting at offset " + ehdr.e_phoff ); sb.AppendLine( ); sb.AppendLine( "Program headers:" ); sb.AppendLine( " Type Offset VirtAddr PhysAddr FileSiz MemSiz Flg Align" ); var segments = elf.Segments; foreach(var segment in segments) { sb.Append( " " + ( (SegmentType)segment.Header.p_type ).ToString( ).PadRight( 15 ) ); sb.Append( "0x" + segment.Header.p_offset.ToString( "X6" ) + " " ); sb.Append( "0x" + segment.Header.p_vaddr.ToString( "X8" ) + " " ); sb.Append( "0x" + segment.Header.p_paddr.ToString( "X8" ) + " " ); sb.Append( "0x" + segment.Header.p_filesz.ToString( "X5" ) + " " ); sb.Append( "0x" + segment.Header.p_memsz.ToString( "X5" ) + " " ); var flag = ((segment.Header.p_flags & SegmentFlag.PF_R) != 0) ? "R" : " "; flag += ( ( segment.Header.p_flags & SegmentFlag.PF_W ) != 0 ) ? "W" : " "; flag += ( ( segment.Header.p_flags & SegmentFlag.PF_X ) != 0 ) ? "E" : " "; sb.Append( flag + " " ); sb.Append( "0x" + segment.Header.p_align.ToString( "X" ) ); sb.AppendLine( ); } sb.AppendLine( ); sb.AppendLine( " Section to Segment mapping:" ); sb.AppendLine( " Segment Sections..." ); for(int i = 0; i < segments.Length; i++) { sb.Append( " " + i.ToString( "D2" ) + " " ); foreach(var section in segments[ i ].ReferencedSections) { sb.Append( section.Name + " " ); } sb.AppendLine( ); } sb.AppendLine( ); return sb.ToString( ); } public static string PrintRelocationEntries( RelocationSection[] sections ) { var sb = new StringBuilder(); sb.AppendLine( "============================================================================================" ); sb.AppendLine( ); foreach(var section in sections) { sb.AppendLine( "Relocation section '" + section.Name + "' at offset 0x" + section.Header.sh_offset.ToString( "X3" ) + " contains " + section.Entries.Length + " entries:" ); sb.AppendLine( " Offset Info Type Sym.Value Sym.Name" ); foreach(var entry in section.Entries) { sb.Append( entry.EntryDef.r_offset.ToString( "X8" ).PadRight( 10 ) ); sb.Append( entry.EntryDef.r_info.ToString( "X8" ).PadRight( 9 ) ); sb.Append( entry.Type.ToString( ).PadRight( 17 ) ); sb.Append( entry.ReferencedSymbol.SymbolDef.st_value.ToString( "X8" ).PadRight( 11 ) ); if(entry.ReferencedSymbol.Name != "") { sb.Append( entry.ReferencedSymbol.Name ); } else { sb.Append( entry.ReferencedSymbol.ReferencedSection.Name ); } sb.AppendLine( ); } sb.AppendLine( ); } sb.AppendLine( ); return sb.ToString( ); } //--// //--// //--// // // A method is defined in LLVM as follows: // 'define internal void @"Thread::Yield#5079"() #1 section ".text.llilum" { < method body > }' // The decorated name is 'Thread::Yield#5079', and the name is simply 'Yield'. // private static Regex decoratedNameModel = new Regex("([a-zA-Z0-9_@`.<>]+)::([a-zA-Z0-9._@]+)#([0-9])"); private static bool ParseTypeAndMethodName( Symbol s, ref string methodName, ref string decoratedMethodName, ref string typeName ) { decoratedMethodName = s.Name; if(decoratedNameModel.IsMatch( s.Name )) { Match m = decoratedNameModel.Match( s.Name ); typeName = m.Groups[ 1 ].Captures[ 0 ].Value; methodName = m.Groups[ 2 ].Captures[ 0 ].Value; return true; } return false; } } } ================================================ FILE: Zelig/Zelig/DebugTime/Elf/ElfLib/Properties/AssemblyInfo.cs ================================================ using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; // General Information about an assembly is controlled through the following // set of attributes. Change these attribute values to modify the information // associated with an assembly. [assembly: AssemblyTitle( "elflib" )] [assembly: AssemblyDescription( "" )] [assembly: AssemblyConfiguration( "" )] [assembly: AssemblyCompany( "MSIT" )] [assembly: AssemblyProduct( "Microsoft.Zelig.Elf.Elflib" )] [assembly: AssemblyCopyright( "Copyright © MSIT 2008" )] [assembly: AssemblyTrademark( "" )] [assembly: AssemblyCulture( "" )] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible( false )] // The following GUID is for the ID of the typelib if this project is exposed to COM [assembly: Guid( "edf2f76e-7643-4139-9d17-e404c05aad26" )] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Build and Revision Numbers // by using the '*' as shown below: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion( "1.0.0.0" )] [assembly: AssemblyFileVersion( "1.0.0.0" )] ================================================ FILE: Zelig/Zelig/DebugTime/Elf/ElfLib/RelocationEntry.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // namespace Microsoft.Zelig.Elf { using System; using System.Linq; public class RelocationEntry : IElfElement { internal Elf32_Rela m_entryDef; internal Symbol m_symbolRef; internal RelocationSection m_parent; internal RelocationEntry(RelocationSection parent, RelocationType type, Symbol symRef, UInt32 sectionOffset) { m_parent = parent; m_symbolRef = symRef; m_entryDef.r_offset = sectionOffset; m_entryDef.r_info = (uint)((symRef.m_index << 8) + (uint)type); m_symbolRef.ElementStatusChangedEvent += ReferencedSymbolStatusChanged; } internal RelocationEntry(RelocationSection parent, Elf32_Rel def) { m_parent = parent; m_entryDef.r_info = def.r_info; m_entryDef.r_offset = def.r_offset; m_entryDef.r_addend = 0; } internal RelocationEntry(RelocationSection parent, Elf32_Rela def) { m_parent = parent; m_entryDef = def; } public Elf32_Rela EntryDef { get { return m_entryDef; } } public RelocationType Type { get { return (RelocationType) m_entryDef.r_info; } } public UInt16 SymbolIndex { get { return (UInt16)(m_entryDef.r_info >> 8); } } public UInt32 SectionOffset { get { return m_entryDef.r_offset; } } public Symbol ReferencedSymbol { get { return m_symbolRef; } } // // Interface Implementation Methods // public void BuildReferences() { var symbol = m_parent.ReferencedSymbolTable[SymbolIndex]; if (symbol != null) { m_symbolRef = symbol; m_symbolRef.ElementStatusChangedEvent += ReferencedSymbolStatusChanged; } } // // Event Notification Methods // private void ReferencedSymbolStatusChanged(Symbol symbol, ElfElementStatus status) { if (status == ElfElementStatus.IndexChanged) { m_entryDef.r_info = (UInt32) ((symbol.Index << 8) + (m_entryDef.r_info & -0xFF)); } } } } ================================================ FILE: Zelig/Zelig/DebugTime/Elf/ElfLib/RelocationSection.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // namespace Microsoft.Zelig.Elf { using System; using System.Collections.Generic; using System.Runtime.InteropServices; public class RelocationSection : ElfSection { internal List m_relocationEntries; internal ElfSection m_sectionRef; internal SymbolTable m_symTableRef; protected bool m_fDirtyRaw; internal RelocationSection(ElfObject parent, ElfSection sectionRef, SymbolTable symTableRef) : base(parent) { m_relocationEntries = new List(); m_sectionRef = sectionRef; m_sectionRef.ElementStatusChangedEvent += ReferencedSectionStatusChanged; m_symTableRef = symTableRef; m_symTableRef.ElementStatusChangedEvent += SymbolTableStatusChanged; m_header.sh_type = sh_type.SHT_REL; m_header.sh_entsize = (uint) Marshal.SizeOf(typeof (Elf32_Rel)); m_header.sh_link = m_symTableRef.m_index; m_header.sh_info = m_sectionRef.m_index; m_fDirtyRaw = true; } internal RelocationSection(ElfObject parent, Elf32_Shdr hdr, UInt16 index, Elf32_Rel[] entries) : base(parent, hdr, index) { m_relocationEntries = new List(); for (int i = 0; i < entries.Length; i++) { m_relocationEntries.Add(new RelocationEntry(this, entries[i])); } m_fDirtyRaw = true; } internal RelocationSection(ElfObject parent, Elf32_Shdr hdr, UInt16 index, Elf32_Rela[] entries) : base(parent, hdr, index) { m_relocationEntries = new List(); for (int i = 0; i < entries.Length; i++) { m_relocationEntries.Add(new RelocationEntry(this, entries[i])); } m_fDirtyRaw = true; } public RelocationEntry AddRelocationEntry(RelocationType type, Symbol symRef, UInt32 sectionOffset) { var entry = new RelocationEntry(this, type, symRef, sectionOffset); m_relocationEntries.Add(entry); m_fDirtyRaw = true; return entry; } public ElfSection ReferencedSection { get { return m_sectionRef; } } public SymbolTable ReferencedSymbolTable { get { return m_symTableRef; } } public RelocationEntry[] Entries { get { return m_relocationEntries.ToArray(); } } public override byte[] Raw { get { if (!m_fDirtyRaw && (m_raw != null)) { return m_raw; } var symSize = Marshal.SizeOf(typeof (Elf32_Rel)); var raw = new byte[symSize * m_relocationEntries.Count]; var ptr = Marshal.AllocHGlobal(symSize); for (int i = 0; i < m_relocationEntries.Count; i++) { Marshal.StructureToPtr(m_relocationEntries[i].m_entryDef, ptr, false); Marshal.Copy(ptr, raw, i * symSize, symSize); } Marshal.FreeHGlobal(ptr); m_fDirtyRaw = false; return m_raw = raw; } } // // Interface Implementation Methods // public override void BuildReferences() { // Set symbol table reference var tbl = m_parent[m_header.sh_link]; if (tbl != null && tbl is SymbolTable) { m_symTableRef = (SymbolTable) tbl; tbl.ElementStatusChangedEvent += SymbolTableStatusChanged; } // Set section table reference var section = m_parent[m_header.sh_info]; if (section != null) { m_sectionRef = section; section.ElementStatusChangedEvent += ReferencedSectionStatusChanged; } // Build all references for all relocation entries foreach (var entry in m_relocationEntries) { entry.BuildReferences(); } base.BuildReferences(); } // // Event Notification Methods // private void SymbolTableStatusChanged(ElfSection section, ElfElementStatus status) { if (status == ElfElementStatus.IndexChanged) { m_header.sh_link = section.Index; } } private void ReferencedSectionStatusChanged(ElfSection section, ElfElementStatus status) { if (status == ElfElementStatus.IndexChanged) { m_header.sh_info = section.Index; } } } } ================================================ FILE: Zelig/Zelig/DebugTime/Elf/ElfLib/SectionReference.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // namespace Microsoft.Zelig.Elf { using System; using System.Collections.Generic; public class SectionReference { public class SymbolReference { public uint Offset; public RelocationEntry RelocationRef; public SectionReference Owner; public SymbolReference(uint offset, RelocationEntry relocationRef, SectionReference owner) { Offset = offset; RelocationRef = relocationRef; Owner = owner; } } internal SectionReference(ElfSection sec, RelocationEntry relocRef, uint callOffset) : this( sec, relocRef, callOffset, 0 ) { } internal SectionReference(ElfSection sec, RelocationEntry relocRef, uint callOffset, uint sectionOffset) { Section = sec; SectionName = relocRef.m_symbolRef.Name; SectionOffset = sectionOffset; CallOffsets = new List(); FinalAddress = 0; DataBaseOffset = callOffset; CallOffsets.Add( new SymbolReference( callOffset, relocRef, this ) ); sec.ElementStatusChangedEvent += new Action( sec_ElementStatusChangedEvent ); } void sec_ElementStatusChangedEvent(ElfSection section, ElfElementStatus action) { if( action == ElfElementStatus.AddressChanged ) { FinalAddress = section.Header.sh_addr; } } public ElfSection Section; public string SectionName; public uint SectionOffset; public readonly uint DataBaseOffset; public List CallOffsets; public uint FinalAddress; } } ================================================ FILE: Zelig/Zelig/DebugTime/Elf/ElfLib/StringTable.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // namespace Microsoft.Zelig.Elf { using System; using System.Text; public class StringTable : ElfSection { internal StringTable(ElfObject parent) : base(parent, new byte[1]{0}) { m_header.sh_type = sh_type.SHT_STRTAB; } internal StringTable(ElfObject parent, Elf32_Shdr hdr, UInt16 index, byte[] raw) : base(parent, hdr, index, raw, 0) { } public string GetString(uint index) { if (m_raw == null || index >= m_raw.Length) { return ""; } var sb = new StringBuilder(); while (m_raw[index] != 0) { sb.Append((char)m_raw[index]); index++; } return sb.ToString(); } public uint AddString(string val) { uint index = 0; // First see if we already have this string in the table and reuse it if (m_raw != null && m_raw.Length > 0) { var sb = new StringBuilder(); while (true) { while (m_raw[index] != 0) { sb.Append((char)m_raw[index]); index++; } var str = sb.ToString(); // We need to check for matching suffix strings and use // one if we find one. for (int i = 0; i < str.Length; i++) { if (str.Substring(i) == val) { return index - (uint)(str.Length - i); } } //if (sb.ToString() == val) //{ // return index - (uint)sb.Length; //} if (++index >= m_raw.Length) { break; } sb = new StringBuilder(); } } // We don't already have the string in the table. Resize the table, and add it. index = (uint)m_raw.Length; Array.Resize(ref m_raw, m_raw.Length + val.Length + 1); var enc = new ASCIIEncoding(); Buffer.BlockCopy(enc.GetBytes(val), 0, m_raw, (int)index, val.Length); m_raw[m_raw.Length - 1] = 0; return index; } } } ================================================ FILE: Zelig/Zelig/DebugTime/Elf/ElfLib/Symbol.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // namespace Microsoft.Zelig.Elf { using System; public class Symbol : IElfElement, IElfElementStatusPublisher { internal string m_name; internal UInt16 m_index; internal Elf32_Sym m_symbolDef; internal ElfSection m_sectionRef; internal SymbolTable m_parent; internal Symbol(SymbolTable parent, string name, UInt32 value, UInt32 size, SymbolType type, SymbolBinding binding, SymbolVisibility visibility, ElfSection sectionRef) { m_parent = parent; Name = name; m_symbolDef.st_value = value; m_symbolDef.st_size = size; m_symbolDef.st_info = (byte)(((byte)binding << 4) + (byte)type); m_symbolDef.st_other = (byte)visibility; if (sectionRef != null) { m_symbolDef.st_shndx = sectionRef.Index; m_sectionRef = sectionRef; sectionRef.ElementStatusChangedEvent += SectionReferenceStatusChanged; } } internal Symbol(SymbolTable parent, Elf32_Sym def, UInt16 index) { m_parent = parent; m_symbolDef = def; m_index = index; } public string Name { get { return m_name; } set { var tbl = m_parent.StringTable; if (tbl != null) { m_symbolDef.st_name = m_parent.m_stringTable.AddString(value); m_name = value; } else { throw new ElfConsistencyException("Missing string table"); } } } public UInt16 Index { get { return m_index; } set { m_index = value; // Update subcribers about index change if (ElementStatusChangedEvent != null) { ElementStatusChangedEvent(this, ElfElementStatus.IndexChanged); } } } public Elf32_Sym SymbolDef { get { return m_symbolDef; } } public SymbolType Type { get { return (SymbolType)(m_symbolDef.st_info & 0xf); } } public SymbolBinding Binding { get { return (SymbolBinding)(m_symbolDef.st_info >> 4); } } public SymbolVisibility Visibility { get { return (SymbolVisibility)(m_symbolDef.st_other & 0x3); } } public ElfSection ReferencedSection { get { return m_sectionRef; } } // // Interface Implementation Methods // public event Action ElementStatusChangedEvent; public void BuildReferences() { // Set name var tbl = m_parent.StringTable; if (tbl != null) { m_name = tbl.GetString(m_symbolDef.st_name); } else { throw new ElfConsistencyException("Missing string table"); } // Set referenced section m_sectionRef = m_parent.m_parent[m_symbolDef.st_shndx]; if (m_sectionRef != null) { m_sectionRef.ElementStatusChangedEvent += SectionReferenceStatusChanged; } } // // Event Notification Methods // private void SectionReferenceStatusChanged(ElfSection section, ElfElementStatus status) { if (status == ElfElementStatus.IndexChanged) { m_symbolDef.st_shndx = section.Index; } } } } ================================================ FILE: Zelig/Zelig/DebugTime/Elf/ElfLib/SymbolTable.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // namespace Microsoft.Zelig.Elf { using System; using System.Collections.Generic; using System.Runtime.InteropServices; public class SymbolTable : ElfSection { internal List m_symbols; internal List m_buildAttribs; internal StringTable m_stringTable; private UInt16 m_nextSymbolIndex; protected bool m_fDirtyRaw; internal SymbolTable(ElfObject parent, StringTable stringTable) : base(parent) { m_symbols = new List(); m_buildAttribs = new List(); m_header.sh_type = sh_type.SHT_SYMTAB; m_header.sh_link = stringTable.Index; m_header.sh_entsize = (uint) Marshal.SizeOf(typeof (Elf32_Sym)); m_stringTable = stringTable; m_stringTable.ElementStatusChangedEvent += StringTableStatusChanged; m_nextSymbolIndex = 0; m_fDirtyRaw = true; } internal SymbolTable(ElfObject parent, Elf32_Shdr hdr, UInt16 index, Elf32_Sym[] symbolDefs) : base(parent, hdr, index) { m_symbols = new List(); for (UInt16 i = 0; i < symbolDefs.Length; i++) { m_symbols.Add(new Symbol(this, symbolDefs[i], i)); } m_nextSymbolIndex = (UInt16)symbolDefs.Length; m_buildAttribs = new List(); m_fDirtyRaw = true; } public Symbol AddSymbol(string name, UInt32 value, UInt32 size, SymbolType type, SymbolBinding binding, SymbolVisibility visibility, ElfSection sectionRef) { var symbol = new Symbol(this, name, value, size, type, binding, visibility, sectionRef); symbol.m_index = m_nextSymbolIndex++; m_symbols.Add(symbol); m_fDirtyRaw = true; return symbol; } public Symbol[] Symbols { get { m_symbols.Sort(CompareSymbolsByIndex); return m_symbols.ToArray(); } } public List BuildAttributes { get { return m_buildAttribs; } } public Symbol this[UInt16 index] { get { foreach (var symbol in m_symbols) { if (symbol.Index == index) { return symbol; } } return null; } } public StringTable StringTable { get { return m_stringTable; } } public override byte[] Raw { get { if (!m_fDirtyRaw && (m_raw != null)) { return m_raw; } var symSize = Marshal.SizeOf(typeof (Elf32_Sym)); var raw = new byte[symSize * m_symbols.Count]; var ptr = Marshal.AllocHGlobal(symSize); for (int i = 0; i < m_symbols.Count; i++) { Marshal.StructureToPtr(m_symbols[i].m_symbolDef, ptr, false); Marshal.Copy(ptr, raw, i * symSize, symSize); } Marshal.FreeHGlobal(ptr); m_fDirtyRaw = false; return m_raw = raw; } } internal static int CompareSymbolsByIndex(Symbol x, Symbol y) { if (x == y) { return 0; } if (x.m_index <= y.m_index) { return -1; } return 1; } // // Interface Implementation Methods // public override void BuildReferences() { // Set string table reference var tbl = m_parent[m_header.sh_link]; if (tbl != null && tbl is StringTable) { m_stringTable = (StringTable) tbl; tbl.ElementStatusChangedEvent += StringTableStatusChanged; } // Build all references for all symbols foreach (var symbol in m_symbols) { symbol.BuildReferences(); if( symbol.Name.StartsWith( "BuildAttributes" ) ) { m_buildAttribs.AddRange( symbol.Name.Split( new char[] { '$' }, StringSplitOptions.RemoveEmptyEntries ) ); } if( symbol.m_sectionRef != null && symbol.m_sectionRef.m_index != 0 && symbol.m_sectionRef.m_name != symbol.Name) { symbol.m_sectionRef.Aliases[symbol.Name] = symbol.SymbolDef.st_value; } } base.BuildReferences(); } // // Event Notification Methods // private void StringTableStatusChanged(ElfSection section, ElfElementStatus status) { if (status == ElfElementStatus.IndexChanged) { m_header.sh_link = section.Index; } } } } ================================================ FILE: Zelig/Zelig/DebugTime/Elf/ReadElf/Program.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // namespace Microsoft.Zelig.Elf { using System; using System.IO; using System.Collections.Generic; class Program { static void Main( string[] args ) { bool fPrintAllSizes = false; bool fDisplayFileHeader = false; bool fDisplayProgramHeaders = false; bool fDisplaySectionHeaders = false; bool fDisplaySymbolTable = false; bool fDisplayRelocations = false; var files = new List(); // No options provided if(args.Length == 0 || !args[0].StartsWith("-")) { DisplayUsage(); } RESTART: if(args == null || args.Length == 0) { if( System.Diagnostics.Debugger.IsAttached ) { Console.Write( ">" ); args = Console.ReadLine().Split( new char[]{ ' ' }, StringSplitOptions.RemoveEmptyEntries ); } if( args == null || args.Length == 0 ) { return; } } int index = 0; while (args[index].StartsWith("-")) { var str = args[index]; switch (str.Substring(1)) { case "a": fPrintAllSizes = true; fDisplayFileHeader = true; fDisplayProgramHeaders = true; fDisplaySectionHeaders = true; fDisplaySymbolTable = true; fDisplayRelocations = true; break; case "z": fDisplayFileHeader = true; fDisplayProgramHeaders = true; fPrintAllSizes = true; break; case "e": fDisplayFileHeader = true; fDisplayProgramHeaders = true; fDisplaySectionHeaders = true; break; case "h": fDisplayFileHeader = true; break; case "l": fDisplayProgramHeaders = true; break; case "S": fDisplaySectionHeaders = true; break; case "s": fDisplaySymbolTable = true; break; case "r": fDisplayRelocations = true; break; case "?": DisplayUsage(); if( System.Diagnostics.Debugger.IsAttached ) { args = null; goto RESTART; } return; } index++; // No files provided if (index >= args.Length) { DisplayUsage(); if( System.Diagnostics.Debugger.IsAttached ) { args = null; goto RESTART; } return; } } while (index < args.Length) { files.Add(args[index]); index++; } foreach (var file in files) { ElfObject[] objs; if( !File.Exists( file ) ) continue; objs = ElfObject.FileUtil.Parse(file); if(objs == null) { Console.WriteLine("Could not open file {0}", file); continue; } foreach( ElfObject obj in objs ) { if( fDisplayFileHeader ) { Console.WriteLine( OutputFormatter.PrintElfHeader( obj.Header ) ); } if( fDisplaySectionHeaders ) { Console.WriteLine( OutputFormatter.PrintSectionHeaders( obj.Sections ) ); } if( fDisplayProgramHeaders ) { Console.WriteLine( OutputFormatter.PrintProgramHeaders( obj ) ); } if( fDisplaySymbolTable ) { Console.WriteLine( OutputFormatter.PrintSymbolTable( obj.SymbolTable ) ); } if(fDisplayRelocations) { Console.WriteLine( OutputFormatter.PrintRelocationEntries( obj.RelocationSections ) ); } if( fPrintAllSizes ) { Console.WriteLine( OutputFormatter.PrintAllSizes( OutputFormatter.ComputeAllSizes( obj.SymbolTable ) ) ); var llilumTypes = new Dictionary(); var lillumMethods = new List(); var otherFunctions = new List(); OutputFormatter.ComputeAllSizesMethodByMethod( obj.SymbolTable, llilumTypes, lillumMethods, otherFunctions ); Console.WriteLine( OutputFormatter.PrintAllTypesSizes ( llilumTypes , otherFunctions ) ); Console.WriteLine( OutputFormatter.PrintAllMethodsSizes( lillumMethods, otherFunctions, bySizeOrder: false ) ); Console.WriteLine( OutputFormatter.PrintAllMethodsSizes( lillumMethods, otherFunctions, bySizeOrder: true ) ); } } } if( System.Diagnostics.Debugger.IsAttached ) { args = null; files.Clear(); goto RESTART; } } private static void DisplayUsage() { Console.WriteLine("Usage: readelf elf-file(s)"); Console.WriteLine(" Display information about the contents of ELF format files"); Console.WriteLine(" Options are:"); Console.WriteLine(" -a Equivalent to: -h -l -S -s -r"); Console.WriteLine(" -z Display sections *.llilum* object sizes and ELF, program and section headers"); Console.WriteLine(" -h Display the ELF file header"); Console.WriteLine(" -l Display the program headers"); Console.WriteLine(" -S Display the section headers"); Console.WriteLine(" -e Equivalent to -h -l -S"); Console.WriteLine(" -s Display the symbol table"); Console.WriteLine(" -r Display the relocations (if present)"); Console.WriteLine(" -H Display this information"); Console.WriteLine(); } } } ================================================ FILE: Zelig/Zelig/DebugTime/Elf/ReadElf/Properties/AssemblyInfo.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; // General Information about an assembly is controlled through the following // set of attributes. Change these attribute values to modify the information // associated with an assembly. [assembly: AssemblyTitle( "readelf" )] [assembly: AssemblyDescription( "" )] [assembly: AssemblyConfiguration( "" )] [assembly: AssemblyCompany( "MSIT" )] [assembly: AssemblyProduct( "readelf" )] [assembly: AssemblyCopyright( "Copyright © MSIT 2008" )] [assembly: AssemblyTrademark( "" )] [assembly: AssemblyCulture( "" )] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible( false )] // The following GUID is for the ID of the typelib if this project is exposed to COM [assembly: Guid( "c4b2dfd5-b59a-46c3-95ea-f4519840b250" )] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Build and Revision Numbers // by using the '*' as shown below: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion( "1.0.0.0" )] [assembly: AssemblyFileVersion( "1.0.0.0" )] ================================================ FILE: Zelig/Zelig/DebugTime/Elf/ReadElf/ReadElf.csproj ================================================  Debug AnyCPU 9.0.21022 2.0 {A4CB8DA8-AB1A-4977-B1C5-9AE27EBB6FC7} Exe Properties Microsoft.Zelig.Elf ReadElf v4.5 512 true full false ..\..\..\..\ZeligBuild\Host\bin\Debug\ DEBUG;TRACE prompt 4 AllRules.ruleset AnyCPU false pdbonly true ..\..\..\..\ZeligBuild\Host\bin\Release\ TRACE prompt 4 AllRules.ruleset AnyCPU false true bin\Instrumentation\ DEBUG;TRACE full AnyCPU prompt AllRules.ruleset false 3.5 {37193A86-BA04-4A3E-9DF8-656DF455E952} Elflib False ================================================ FILE: Zelig/Zelig/DebugTime/Loader/Loader.Designer.cs ================================================ namespace Microsoft.Zelig.Loader { partial class Loader { /// /// Required designer variable. /// private System.ComponentModel.IContainer components = null; /// /// Clean up any resources being used. /// /// true if managed resources should be disposed; otherwise, false. protected override void Dispose(bool disposing) { if (disposing && (components != null)) { components.Dispose(); } base.Dispose(disposing); } #region Windows Form Designer generated code /// /// Required method for Designer support - do not modify /// the contents of this method with the code editor. /// private void InitializeComponent() { this.btnLoad = new System.Windows.Forms.Button(); this.statusStrip = new System.Windows.Forms.StatusStrip(); this.StatusLabel = new System.Windows.Forms.ToolStripStatusLabel(); this.openFileDialog1 = new System.Windows.Forms.OpenFileDialog(); this.btnConfig = new System.Windows.Forms.Button(); this.btnFile = new System.Windows.Forms.Button(); this.statusStrip.SuspendLayout(); this.SuspendLayout(); // // btnLoad // this.btnLoad.Location = new System.Drawing.Point(175, 12); this.btnLoad.Name = "btnLoad"; this.btnLoad.Size = new System.Drawing.Size(75, 23); this.btnLoad.TabIndex = 0; this.btnLoad.Text = "Load / Exec"; this.btnLoad.UseVisualStyleBackColor = true; this.btnLoad.Click += new System.EventHandler(this.btnLoad_Click); // // statusStrip // this.statusStrip.Items.AddRange(new System.Windows.Forms.ToolStripItem[] { this.StatusLabel}); this.statusStrip.Location = new System.Drawing.Point(0, 45); this.statusStrip.Name = "statusStrip"; this.statusStrip.Size = new System.Drawing.Size(263, 22); this.statusStrip.TabIndex = 1; this.statusStrip.Text = "statusStrip1"; // // StatusLabel // this.StatusLabel.Name = "StatusLabel"; this.StatusLabel.Size = new System.Drawing.Size(26, 17); this.StatusLabel.Text = "Idle"; // // btnConfig // this.btnConfig.Location = new System.Drawing.Point(13, 12); this.btnConfig.Name = "btnConfig"; this.btnConfig.Size = new System.Drawing.Size(75, 23); this.btnConfig.TabIndex = 2; this.btnConfig.Text = "Config"; this.btnConfig.UseVisualStyleBackColor = true; this.btnConfig.Click += new System.EventHandler(this.btnConfig_Click); // // btnFile // this.btnFile.Location = new System.Drawing.Point(94, 12); this.btnFile.Name = "btnFile"; this.btnFile.Size = new System.Drawing.Size(75, 23); this.btnFile.TabIndex = 3; this.btnFile.Text = "Choose File"; this.btnFile.UseVisualStyleBackColor = true; this.btnFile.Click += new System.EventHandler(this.btnFile_Click); // // Loader // this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F); this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font; this.ClientSize = new System.Drawing.Size(263, 67); this.Controls.Add(this.btnFile); this.Controls.Add(this.btnConfig); this.Controls.Add(this.statusStrip); this.Controls.Add(this.btnLoad); this.Name = "Loader"; this.Text = "Loader"; this.statusStrip.ResumeLayout(false); this.statusStrip.PerformLayout(); this.ResumeLayout(false); this.PerformLayout(); } #endregion private System.Windows.Forms.Button btnLoad; private System.Windows.Forms.StatusStrip statusStrip; private System.Windows.Forms.ToolStripStatusLabel StatusLabel; private System.Windows.Forms.OpenFileDialog openFileDialog1; private System.Windows.Forms.Button btnConfig; private System.Windows.Forms.Button btnFile; } } ================================================ FILE: Zelig/Zelig/DebugTime/Loader/Loader.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // namespace Microsoft.Zelig.Loader { using System; using System.Collections.Generic; using System.Threading; using System.Windows.Forms; using Microsoft.Zelig.Debugger.ArmProcessor; using Microsoft.Zelig.Emulation.Hosting; using Microsoft.Zelig.Runtime; using Cfg = Microsoft.Zelig.Configuration.Environment; using Microsoft.Zelig.Elf; public partial class Loader : Form, IMainForm { Cfg.Manager m_configurationManager; Cfg.ProductCategory m_product; Cfg.EngineCategory m_engine; EnvironmentForm m_environmentForm; String m_imageFile; Thread m_worker; public Loader() { InitializeComponent(); //--// m_configurationManager = new Cfg.Manager(); m_configurationManager.AddAllAssemblies( null ); m_configurationManager.ComputeAllPossibleValuesForFields(); //--// m_environmentForm = new EnvironmentForm( this ); } //--// public Cfg.Manager ConfigurationManager { get { return m_configurationManager; } } //--// private void btnConfig_Click(object sender, EventArgs e) { DialogResult res = m_environmentForm.ShowDialog(); if (res == DialogResult.OK) { m_engine = m_environmentForm.SelectedEngine; m_product = m_environmentForm.SelectedProduct; } } private void btnFile_Click(object sender, EventArgs e) { DialogResult res = openFileDialog1.ShowDialog(); if (res == DialogResult.OK) { m_imageFile = openFileDialog1.FileName; } } private void btnLoad_Click(object sender, EventArgs e) { m_worker = new Thread(LoadImageAndExecute); m_worker.IsBackground = true; m_worker.Start(); } //--// private void LoadImageAndExecute() { // // Open ELF and see if it is valid // ElfObject[] elfs = ElfObject.FileUtil.Parse( m_imageFile ); uint entryPoint = 0; if(elfs == null) { throw TypeConsistencyErrorException.Create( "Unrecognized file: {0}", m_imageFile ); } var sections = new List(); foreach(ElfObject elf in elfs) { if(elf.Header.e_type != e_type.ET_EXEC) { throw TypeConsistencyErrorException.Create( "ELf is not an exec file: {0}", m_imageFile ); } // // Create list of ImageSections // foreach(var segment in elf.Segments) { if(segment.Type == SegmentType.PT_LOAD) { foreach(var section in segment.ReferencedSections) { sections.Add( new Cfg.ImageSection( section.AddressInMemory, section.Raw, section.Name, 0, MemoryUsage.Relocation ) ); } } } entryPoint = elf.EntryPoint; } //--// var engine = m_engine.Instantiate(null) as AbstractHost; if(engine == null) { throw TypeConsistencyErrorException.Create( "Unrecognized engine: {0}", m_engine ); } ProcessorControl svcPC; engine.GetHostingService( out svcPC ); svcPC.ResetState( m_product ); svcPC.PrepareHardwareModels( m_product ); ProcessorStatus svcPS; engine.GetHostingService( out svcPS ); svcPC.DeployImage( sections, delegate( string format, object[] args ) { this.BeginInvoke( (MethodInvoker)delegate() { StatusLabel.Text = string.Format( format, args ); } ); } ); svcPS.ProgramCounter = entryPoint; this.BeginInvoke( (MethodInvoker)delegate() { StatusLabel.Text = "Deployed and running"; } ); svcPC.Execute( new List() ); } //--// } } ================================================ FILE: Zelig/Zelig/DebugTime/Loader/Loader.csproj ================================================  Debug AnyCPU 9.0.30729 2.0 {F1829F0B-1A0E-4844-BF44-106F3ADDF157} WinExe Properties Microsoft.Zelig.Loader Microsoft.Zelig.Loader $(LlilumBuildRoot)\Host\obj\$(MSBuildProjectName)\ v4.5 512 true full false $(LlilumBuildRoot)\Host\bin\$(Configuration)\ DEBUG;TRACE prompt 4 AllRules.ruleset AnyCPU false pdbonly true $(LlilumBuildRoot)\Host\bin\$(Configuration)\ TRACE prompt 4 AllRules.ruleset AnyCPU false $(LlilumBuildRoot)\Host\bin\$(Configuration)\ TRACE;DEBUG AnyCPU false false 3.5 Form Loader.cs Loader.cs ResXFileCodeGenerator Resources.Designer.cs Designer True Resources.resx True SettingsSingleFileGenerator Settings.Designer.cs True Settings.settings True {186F31A3-EF89-4A25-B2D5-20070606AA01} ProductConfiguration {186F31A3-EF89-4A25-B2D5-20061218AA01} Common {186F31A3-EF89-4A25-B2D5-20060704AA01} ArmProcessorEmulation {186F31A3-EF89-4A25-B2D5-20070430AA01} Debugger {186F31A3-EF89-4A25-B2D5-20070519AA01} ArmProcessor {37193a86-ba04-4a3e-9df8-656df455e952} Elflib ================================================ FILE: Zelig/Zelig/DebugTime/Loader/Loader.resx ================================================ text/microsoft-resx 2.0 System.Resources.ResXResourceReader, System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 System.Resources.ResXResourceWriter, System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 17, 17 126, 17 ================================================ FILE: Zelig/Zelig/DebugTime/Loader/Program.cs ================================================ using System; using System.Collections.Generic; using System.Windows.Forms; namespace Microsoft.Zelig.Loader { static class Program { /// /// The main entry point for the application. /// [STAThread] static void Main() { Application.EnableVisualStyles(); Application.SetCompatibleTextRenderingDefault(false); Application.Run(new Loader()); } } } ================================================ FILE: Zelig/Zelig/DebugTime/Loader/Properties/AssemblyInfo.cs ================================================ using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; // General Information about an assembly is controlled through the following // set of attributes. Change these attribute values to modify the information // associated with an assembly. [assembly: AssemblyTitle("Loader")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("MSIT")] [assembly: AssemblyProduct("Loader")] [assembly: AssemblyCopyright("Copyright © MSIT 2009")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible(false)] // The following GUID is for the ID of the typelib if this project is exposed to COM [assembly: Guid("afff9677-6615-46b6-b64d-5070057b0197")] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Build and Revision Numbers // by using the '*' as shown below: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("1.0.0.0")] [assembly: AssemblyFileVersion("1.0.0.0")] ================================================ FILE: Zelig/Zelig/DebugTime/Loader/Properties/Resources.Designer.cs ================================================ //------------------------------------------------------------------------------ // // This code was generated by a tool. // Runtime Version:4.0.30319.34209 // // Changes to this file may cause incorrect behavior and will be lost if // the code is regenerated. // //------------------------------------------------------------------------------ namespace Microsoft.Zelig.Loader.Properties { using System; /// /// A strongly-typed resource class, for looking up localized strings, etc. /// // This class was auto-generated by the StronglyTypedResourceBuilder // class via a tool like ResGen or Visual Studio. // To add or remove a member, edit your .ResX file then rerun ResGen // with the /str option, or rebuild your VS project. [global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Resources.Tools.StronglyTypedResourceBuilder", "4.0.0.0")] [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] [global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()] internal class Resources { private static global::System.Resources.ResourceManager resourceMan; private static global::System.Globalization.CultureInfo resourceCulture; [global::System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")] internal Resources() { } /// /// Returns the cached ResourceManager instance used by this class. /// [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)] internal static global::System.Resources.ResourceManager ResourceManager { get { if (object.ReferenceEquals(resourceMan, null)) { global::System.Resources.ResourceManager temp = new global::System.Resources.ResourceManager("Microsoft.Zelig.Loader.Properties.Resources", typeof(Resources).Assembly); resourceMan = temp; } return resourceMan; } } /// /// Overrides the current thread's CurrentUICulture property for all /// resource lookups using this strongly typed resource class. /// [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)] internal static global::System.Globalization.CultureInfo Culture { get { return resourceCulture; } set { resourceCulture = value; } } } } ================================================ FILE: Zelig/Zelig/DebugTime/Loader/Properties/Resources.resx ================================================  text/microsoft-resx 2.0 System.Resources.ResXResourceReader, System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 System.Resources.ResXResourceWriter, System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 ================================================ FILE: Zelig/Zelig/DebugTime/Loader/Properties/Settings.Designer.cs ================================================ //------------------------------------------------------------------------------ // // This code was generated by a tool. // Runtime Version:4.0.30319.34209 // // Changes to this file may cause incorrect behavior and will be lost if // the code is regenerated. // //------------------------------------------------------------------------------ namespace Microsoft.Zelig.Loader.Properties { [global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()] [global::System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.VisualStudio.Editors.SettingsDesigner.SettingsSingleFileGenerator", "12.0.0.0")] internal sealed partial class Settings : global::System.Configuration.ApplicationSettingsBase { private static Settings defaultInstance = ((Settings)(global::System.Configuration.ApplicationSettingsBase.Synchronized(new Settings()))); public static Settings Default { get { return defaultInstance; } } } } ================================================ FILE: Zelig/Zelig/DebugTime/Loader/Properties/Settings.settings ================================================  ================================================ FILE: Zelig/Zelig/FileSystemTest/Directory/CreateDirectory.cs ================================================ //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // Copyright (c) Microsoft Corporation. All rights reserved. //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// using System; using System.IO; namespace FileSystemTest { public class CreateDirectory : IMFTestInterface { [SetUp] public InitializeResult Initialize() { Log.Comment("Adding set up for the tests."); try { IOTests.IntializeVolume(); Directory.CreateDirectory("CreateDirectory"); } catch (Exception ex) { Log.Exception("Skipping: Unable to initialize file system", ex); return InitializeResult.Skip; } // Add your functionality here. return InitializeResult.ReadyToGo; } [TearDown] public void CleanUp() { } #region Helper Functions private string GetDir(params string[] args) { string dir = IOTests.Volume.RootDirectory; for (int i = 0; i < args.Length; i++) { dir += @"\" + args[i]; } return dir; } private bool TestCreateDirectory(string path) { DirectoryInfo dir = Directory.CreateDirectory(path); // Append current dir if not rooted if (path.Substring(0, 1) != @"\") { path = Directory.GetCurrentDirectory() + "\\" + path; } Log.Comment("Path: '" + path + "'"); if (dir.FullName != path) { Log.Exception("Got: '" + dir.FullName + "'"); return false; } return VerifyDirectory(path); } private bool VerifyDirectory(string path) { string parent = GetParentDirectory(path, 1); string[] validate = Directory.GetDirectories(parent); foreach (string vpath in validate) { // check case insensitive if (vpath.ToLower() == path.ToLower()) return true; } Log.Exception("Did not find " + path + " after creation."); return false; } private String GetParentDirectory(String strDirName, int iNumUpFolder) { string parentDir = iNumUpFolder > 0 ? strDirName : ""; // make sure we account for file name if(File.Exists( strDirName )) { parentDir = Path.GetDirectoryName( strDirName ); } while(iNumUpFolder > 0) { parentDir = Path.GetDirectoryName( parentDir ); iNumUpFolder--; } return parentDir; //int iIndex = 0; //while (iNumUpFolder != 0) //{ // if (strDirName.IndexOf('\\') > -1 || strDirName.IndexOf('/') > -1) // { // iIndex = strDirName.LastIndexOf('\\'); // if (iIndex == -1) // iIndex = strDirName.IndexOf('/'); // if (iIndex != -1) // strDirName = strDirName.Substring(0, iIndex); // } // iNumUpFolder--; //} //return strDirName; } #endregion #region Test Cases [TestMethod] public MFTestResults InvalidArguments() { DirectoryInfo dir; MFTestResults result = MFTestResults.Pass; try { try { Log.Comment("Null Constructor"); dir = Directory.CreateDirectory(null); Log.Exception( "Expected ArgumentNullException, but got " + dir.FullName ); return MFTestResults.Fail; } catch (ArgumentNullException ane) { /* pass case */ Log.Comment( "Got correct exception: " + ane.Message ); result = MFTestResults.Pass; } try { Log.Comment("String.Empty Constructor"); dir = Directory.CreateDirectory(String.Empty); Log.Exception( "Expected ArgumentException, but got " + dir.FullName ); return MFTestResults.Fail; } catch (ArgumentException ae) { /* pass case */ Log.Comment( "Got correct exception: " + ae.Message ); result = MFTestResults.Pass; } try { Log.Comment("White Space Constructor"); dir = Directory.CreateDirectory(" "); Log.Exception( "Expected ArgumentException, but got " + dir.FullName ); return MFTestResults.Fail; } catch (ArgumentException ae2) { /* pass case */ Log.Comment( "Got correct exception: " + ae2.Message ); result = MFTestResults.Pass; } Log.Comment("Colon test cases"); string[] values = new string[] { ":", ":t", ":test", "te:", "test:", "te:st"}; foreach (string value in values) { try { Log.Comment("Testing for exception: " + value); dir = new DirectoryInfo(value); Log.Exception( "Expected ArgumentException, but got " + dir.FullName ); return MFTestResults.Fail; } catch (ArgumentException ae3) { /* pass case */ Log.Comment( "Got correct exception: " + ae3.Message ); result = MFTestResults.Pass; } } } catch (Exception ex) { Log.Exception("Unexpected exception: " + ex.Message); return MFTestResults.Fail; } return result; } [TestMethod] public MFTestResults NewLineTabs() { MFTestResults result = MFTestResults.Pass; try { Log.Comment("Verify tabs/newlines truncated"); try { Directory.CreateDirectory("TabNLTest1\t"); } catch (ArgumentException ae) { /* pass case */ Log.Comment( "Got correct exception: " + ae.Message ); result = MFTestResults.Pass; } if (VerifyDirectory(IOTests.Volume.RootDirectory + "\\TabNLTest1")) return MFTestResults.Fail; Log.Comment("Verify tabs/newlines truncated"); try { Directory.CreateDirectory("TabNLTest2\t\t\t\t\t\t"); } catch (ArgumentException ae1) { /* pass case */ Log.Comment( "Got correct exception: " + ae1.Message ); result = MFTestResults.Pass; } if (VerifyDirectory(IOTests.Volume.RootDirectory + "\\TabNLTest2")) return MFTestResults.Fail; Log.Comment("Verify tabs/newlines truncated"); try { Directory.CreateDirectory("TabNLTest3\n"); } catch (ArgumentException ae2) { /* pass case */ Log.Comment( "Got correct exception: " + ae2.Message ); result = MFTestResults.Pass; } if (VerifyDirectory(IOTests.Volume.RootDirectory + "\\TabNLTest3")) return MFTestResults.Fail; try { Directory.CreateDirectory("TabNLTest4\n\n\n\n\n\n\n"); } catch (ArgumentException ae3) { /* pass case */ Log.Comment( "Got correct exception: " + ae3.Message ); result = MFTestResults.Pass; } if (VerifyDirectory(IOTests.Volume.RootDirectory + "\\TabNLTest4")) return MFTestResults.Fail; try { Directory.CreateDirectory("TabNLTest5\n\n\t\t\n\n\t"); } catch (ArgumentException ae4) { /* pass case */ Log.Comment( "Got correct exception: " + ae4.Message ); result = MFTestResults.Pass; } if (VerifyDirectory(IOTests.Volume.RootDirectory + "\\TabNLTest5")) return MFTestResults.Fail; } catch (Exception ex) { Log.Exception("Unexpected exception: " + ex.Message); return MFTestResults.Fail; } return result; } [TestMethod] public MFTestResults Dots() { MFTestResults result = MFTestResults.Pass; try { DirectoryInfo dir; Directory.SetCurrentDirectory( IOTests.Volume.RootDirectory ); try { Log.Comment( "Create current dir . (no-op)" ); dir = Directory.CreateDirectory( "." ); if(dir.FullName != Directory.GetCurrentDirectory()) { Log.Exception( "Expected no-op create current dir, but got: " + dir.FullName ); return MFTestResults.Fail; } } catch(ArgumentException ioex) { /* pass case */ Log.Comment( "Got correct exception: " + ioex.Message ); result = MFTestResults.Pass; } Log.Comment("Create parent dir .. (no-op)"); try { dir = Directory.CreateDirectory(".."); Log.Exception( "Expected IOException, but got: " + dir.FullName ); return MFTestResults.Fail; } catch (IOException ioe) { /* pass case */ Log.Comment( "Got correct exception: " + ioe.Message ); result = MFTestResults.Pass; } Log.Comment("Create directory starting in ."); if (!TestCreateDirectory(".StartDotDirectory")) return MFTestResults.Fail; Log.Comment("Create directory ending in ."); dir = Directory.CreateDirectory("DotDirectory."); if (!VerifyDirectory(Directory.GetCurrentDirectory() + @"\DotDirectory")) { Log.Exception( "Expected no-op create current dir, but got: " + dir.FullName ); return MFTestResults.Fail; } Log.Comment("Create directory ending in .."); dir = Directory.CreateDirectory("DoubleDotDirectory.."); if (!VerifyDirectory(Directory.GetCurrentDirectory() + @"\DoubleDotDirectory")) { Log.Exception( "Expected no-op create current dir, but got: " + dir.FullName ); return MFTestResults.Fail; } Log.Comment("Create directory ending in ..."); dir = Directory.CreateDirectory("TripleDotDirectory..."); if (!VerifyDirectory(Directory.GetCurrentDirectory() + @"\TripleDotDirectory")) { Log.Exception( "Expected no-op create current dir, but got: " + dir.FullName ); return MFTestResults.Fail; } } catch (Exception ex) { Log.Exception("Unexpected exception: " + ex.Message); return MFTestResults.Fail; } return result; } [TestMethod] public MFTestResults TooLongPath() { // Desktop throws TooLongException for these cases. Currently test expects ArgumentException, but throws generic Exception. MFTestResults result = MFTestResults.Pass; DirectoryInfo dir; try { string longBlock = new string('y', 135); try { Log.Comment("Too long single dir"); dir = Directory.CreateDirectory(longBlock + longBlock); Log.Exception("Expected ArgumentException exception, but got: " + dir.FullName); return MFTestResults.Fail; } catch (IOException ioe) { /* Pass Case */ Log.Comment( "Got correct exception: " + ioe.Message ); result = MFTestResults.Pass; } // PathTooLong try { Log.Comment("Too long dir in path"); dir = Directory.CreateDirectory(@"\sd1\" + longBlock + "\\" + longBlock + "\\" + longBlock + longBlock + "\\dir"); Log.Exception("Expected NullArgument exception, but got: " + dir.FullName); return MFTestResults.Fail; } catch (IOException ioe1) { /* Pass Case */ Log.Comment( "Got correct exception: " + ioe1.Message ); result = MFTestResults.Pass; } // PathTooLong try { Log.Comment("Max lengh"); dir = Directory.CreateDirectory(new string('a', (int)UInt16.MaxValue + 1)); Log.Exception("Expected NullArgument exception, but got: " + dir.FullName); return MFTestResults.Fail; } catch (IOException ioe2) { /* Pass Case */ Log.Comment( "Got correct exception: " + ioe2.Message ); result = MFTestResults.Pass; } // PathTooLong Log.Comment("first phase complete."); // chech bounds string currDir = Directory.GetCurrentDirectory(); int len = currDir.Length; if (currDir.Substring(currDir.Length - 1) != (Path.DirectorySeparatorChar.ToString())) len++; Log.Comment("second phase started"); /// Problem here is while path is less than 260 in code below, ultimate /// path in emulator is well above 260, causing exception from emulator. if (IOTests.Volume.FileSystem.ToUpper() != "WINFS") { for (int i = 225 - len; i < 275 - len; i++) { Log.Comment("Trying length " + i); try { String str1 = new String('a', i); dir = Directory.CreateDirectory(str1); if (dir.Name.Length >= IOTests.Volume.RootDirectory.Length + 258 /*(FSMaxPathLength)*/) { Log.Exception( "Didn't Throw: " + ( i + len ) + " - " + dir.Name.Length ); return MFTestResults.Fail; } // Delete the directory we just created so we won't fail because of a limitation on number of // entries in a directory (i.e. the root directory in FAT16) Directory.Delete(str1); } catch (IOException) { if ((len + i) >= IOTests.Volume.RootDirectory.Length + 246 /*(FS_MAX_DIRECTORY_LENGTH)*/) { // Expected, directory path is too long } else if ((len + i) < 260) { Log.Exception("Threw too early: " + (i + len)); return MFTestResults.Fail; } } } } } catch (Exception ex) { Log.Exception("Unexpected exception: " + ex.Message); return MFTestResults.Fail; } return result; } [TestMethod] public MFTestResults ArgumentExceptionTests() { MFTestResults result = MFTestResults.Pass; try { foreach (char invalidChar in Path.GetInvalidPathChars()) { try { Log.Comment("Invalid char ascii val = " + (int)invalidChar); string path = new string(new char[] { 'b', 'a', 'd', '\\', invalidChar, 'p', 'a', 't', 'h', invalidChar, '.', 't', 'x', 't' }); DirectoryInfo dir = Directory.CreateDirectory(path); if (invalidChar == 0) { Log.Exception("[Known issue for '\\0' char] Expected Argument exception for for '" + path + "' but got: '" + dir + "'"); } else { Log.Exception("Expected Argument exception for '" + path + "' but got: '" + dir.FullName + "'"); return MFTestResults.Fail; } } catch (ArgumentException ae) { /* Pass Case */ Log.Comment( "Got correct exception: " + ae.Message ); result = MFTestResults.Pass; } } } catch (Exception ex) { Log.Exception("Unexpected exception: " + ex.Message); return MFTestResults.Fail; } return result; } [TestMethod] public MFTestResults CreateExistingDirectory() { MFTestResults result = MFTestResults.Pass; try { /// Creating existing directory should not fail. DirectoryInfo dir1 = Directory.CreateDirectory(IOTests.Volume.RootDirectory + "\\CreateDirectory"); DirectoryInfo dir2 = Directory.CreateDirectory(IOTests.Volume.RootDirectory + "\\CreateDirectory"); } catch (Exception ex) { Log.Exception("Unexpected exception: " + ex.Message); return MFTestResults.Fail; } return result; } [TestMethod] public MFTestResults ValidCases() { MFTestResults result = MFTestResults.Pass; try { Directory.SetCurrentDirectory(IOTests.Volume.RootDirectory); if (!TestCreateDirectory("ValidTestDir1")) return MFTestResults.Fail; if (!TestCreateDirectory(IOTests.Volume.RootDirectory + "\\ValidTestDir2")) return MFTestResults.Fail; if (!TestCreateDirectory(@"ValidTestDir3\test\TesT")) return MFTestResults.Fail; // fails because GetDirectories has bug if (!TestCreateDirectory(@"ValidTestDir3\test\TesT2")) return MFTestResults.Fail; if (!TestCreateDirectory(@"ValidTestDir3\test\TesT3")) return MFTestResults.Fail; if (!TestCreateDirectory(IOTests.Volume.RootDirectory + "\\ValidTestDir3\\test2\\TesT")) return MFTestResults.Fail; if (!TestCreateDirectory(IOTests.Volume.RootDirectory + "\\ValidTestDir4\\test\\TesT")) return MFTestResults.Fail; // relative Directory.SetCurrentDirectory(IOTests.Volume.RootDirectory + "\\ValidTestDir1"); if (Directory.GetCurrentDirectory() != IOTests.Volume.RootDirectory + "\\ValidTestDir1") { Log.Exception("Failed to set current directory. Relative tests are not accurate"); return MFTestResults.Fail; } if (!TestCreateDirectory("RelTestDir1")) return MFTestResults.Fail; if (!TestCreateDirectory("RelTestDir2")) return MFTestResults.Fail; if (!TestCreateDirectory(@"ValidTestDir2\test")) return MFTestResults.Fail; } catch (Exception ex) { Log.Exception("Unexpected exception: " + ex.Message); return MFTestResults.Fail; } return result; } #endregion Test Cases public MFTestMethod[] Tests { get { return new MFTestMethod[] { new MFTestMethod( ArgumentExceptionTests, "ArgumentExceptionTests" ), new MFTestMethod( ValidCases, "ValidCases" ), new MFTestMethod( NewLineTabs, "NewLineTabs" ), new MFTestMethod( Dots, "Dots" ), new MFTestMethod( TooLongPath, "TooLongPath" ), new MFTestMethod( CreateExistingDirectory, "CreateExistingDirectory" ), new MFTestMethod( InvalidArguments, "InvalidArguments" ), }; } } } } ================================================ FILE: Zelig/Zelig/FileSystemTest/Directory/DI_Constructor.cs ================================================ //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // Copyright (c) Microsoft Corporation. All rights reserved. //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// using System; using System.IO; namespace FileSystemTest { public class DI_Constructor : IMFTestInterface { #region internal vars private const string DIRA = @"DirA"; private const string DIRB = @"DirB"; private const string DIR1 = @"Dir1"; private const string DIR2 = @"Dir2"; #endregion [SetUp] public InitializeResult Initialize() { // These tests rely on underlying file system so we need to make // sure we can format it before we start the tests. If we can't // format it, then we assume there is no FS to test on this platform. // delete the directory DOTNETMF_FS_EMULATION try { IOTests.IntializeVolume(); Directory.CreateDirectory(GetDir(DIRA, DIR1)); Directory.CreateDirectory(GetDir(DIRA, DIR2)); Directory.CreateDirectory(GetDir(DIRB, DIR1)); Directory.CreateDirectory(GetDir(DIRB, DIR2)); } catch (Exception ex) { Log.Exception("Skipping: Unable to initialize file system", ex); return InitializeResult.Skip; } return InitializeResult.ReadyToGo; } [TearDown] public void CleanUp() { } #region Helper Functions private string GetDir(params string[] args) { string dir = IOTests.Volume.RootDirectory; for (int i = 0; i < args.Length; i++) { dir += @"\" + args[i]; } return dir; } private bool TestDirectoryInfo(string path) { DirectoryInfo dir = new DirectoryInfo(path); path = RelativePath(path); Log.Comment("Path: '" + path + "'"); if (dir.FullName != path) { Log.Exception("Got: '" + dir.FullName + "'"); return false; } return true; } private string RelativePath(string path) { // rooted if (path.Substring(0,1) == "\\") return path; return Directory.GetCurrentDirectory() + "\\" + path; } #endregion #region Test Cases [TestMethod] public MFTestResults NullArguments() { DirectoryInfo dir; MFTestResults result = MFTestResults.Pass; try { try { Log.Comment("Null Constructor"); dir = new DirectoryInfo(null); Log.Exception( "Expected Argument exception, but got " + dir.FullName ); return MFTestResults.Fail; } catch (ArgumentException ae) { /* pass case */ Log.Comment( "Got correct exception: " + ae.Message ); result = MFTestResults.Pass; } try { Log.Comment("String.Empty Constructor"); dir = new DirectoryInfo(String.Empty); Log.Exception( "Expected Argument exception, but got " + dir.FullName ); return MFTestResults.Fail; } catch (ArgumentException ae1) { /* pass case */ Log.Comment( "Got correct exception: " + ae1.Message ); result = MFTestResults.Pass; } try { Log.Comment("White Space Constructor"); dir = new DirectoryInfo(" "); Log.Exception( "Expected Argument exception, but got " + dir.FullName ); return MFTestResults.Fail; } catch (ArgumentException ae2) { /* pass case */ Log.Comment( "Got correct exception: " + ae2.Message ); result = MFTestResults.Pass; } // Try above root Directory.SetCurrentDirectory(IOTests.Volume.RootDirectory); try { Log.Comment(".. above root Constructor"); /// .. is a valid location, while ..\\.. is not. dir = new DirectoryInfo("..\\.."); Log.Exception( "Expected Argument exception, but got " + dir.FullName ); return MFTestResults.Fail; } catch (ArgumentException ae3) { /* pass case */ Log.Comment( "Got correct exception: " + ae3.Message ); result = MFTestResults.Pass; } } catch (Exception ex) { Log.Exception("Unexpected exception: " + ex.Message); return MFTestResults.Fail; } return result; } [TestMethod] public MFTestResults ValidCases() { MFTestResults result = MFTestResults.Pass; try { Log.Comment("root"); if (!TestDirectoryInfo(Directory.GetCurrentDirectory())) { return MFTestResults.Fail; } Log.Comment("test created dirs"); if (!TestDirectoryInfo(GetDir(DIRA))) { return MFTestResults.Fail; } if (!TestDirectoryInfo(GetDir(DIRB))) { return MFTestResults.Fail; } if (!TestDirectoryInfo(GetDir(DIRA,DIR1))) { return MFTestResults.Fail; } if (!TestDirectoryInfo(GetDir(DIRA, DIR2))) { return MFTestResults.Fail; } if (!TestDirectoryInfo(GetDir(DIRB, DIR1))) { return MFTestResults.Fail; } if (!TestDirectoryInfo(GetDir(DIRB, DIR2))) { return MFTestResults.Fail; } Log.Comment("Case insensitive"); if (!TestDirectoryInfo(GetDir(DIRA.ToLower()))) { return MFTestResults.Fail; } if (!TestDirectoryInfo(GetDir(DIRB.ToUpper()))) { return MFTestResults.Fail; } Log.Comment("Relative - set current dir to DirB"); Directory.SetCurrentDirectory(GetDir(DIRB)); if (!TestDirectoryInfo(DIR1)) { return MFTestResults.Fail; } if (!TestDirectoryInfo(DIR2)) { return MFTestResults.Fail; } } catch (Exception ex) { Log.Exception("Unexpected exception: " + ex.Message); return MFTestResults.Fail; } return result; } [TestMethod] public MFTestResults ArgumentExceptionTests() { MFTestResults result = MFTestResults.Pass; DirectoryInfo dir; try { foreach (char invalidChar in Path.GetInvalidPathChars()) { try { Log.Comment("Invalid char ascii val = " + (int)invalidChar); string path = new string(new char[] { 'b', 'a', 'd', '\\', invalidChar, 'p', 'a', 't', 'h', invalidChar, '.', 't', 'x', 't' }); dir = Directory.CreateDirectory(path); if (invalidChar == 0) { Log.Exception("[Known issue for '\\0' char] Expected Argument exception for for '" + path + "' but got: '" + dir + "'"); } else { Log.Exception("Expected Argument exception for '" + path + "' but got: '" + dir.FullName + "'"); return MFTestResults.Fail; } } catch (ArgumentException ae) { /* Pass Case */ Log.Comment( "Got correct exception: " + ae.Message ); result = MFTestResults.Pass; } } } catch (Exception ex) { Log.Exception("Unexpected exception: " + ex.Message); return MFTestResults.Fail; } return result; } #endregion Test Cases public MFTestMethod[] Tests { get { return new MFTestMethod[] { new MFTestMethod( NullArguments, "NullArguments" ), new MFTestMethod( ValidCases, "ValidCases" ), new MFTestMethod( ArgumentExceptionTests, "ArgumentExceptionTests" ), }; } } } } ================================================ FILE: Zelig/Zelig/FileSystemTest/Directory/Delete.cs ================================================ //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // Copyright (c) Microsoft Corporation. All rights reserved. //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// using System; using System.IO; namespace FileSystemTest { public class Delete : IMFTestInterface { [SetUp] public InitializeResult Initialize() { Log.Comment("Adding set up for the tests."); // Add your functionality here. try { IOTests.IntializeVolume(); Directory.CreateDirectory("CreateDirectory"); } catch (Exception ex) { Log.Exception("Skipping: Unable to initialize file system", ex); return InitializeResult.Skip; } return InitializeResult.ReadyToGo; } [TearDown] public void CleanUp() { } #region Local vars private const string DIR = @"DelDir"; private bool createFile = false; #endregion Local vars #region Helper functions private bool TestDelete(string delete) { return TestDelete(delete, delete); } private bool TestDelete(string delete, bool recursive) { return TestDelete(delete, delete, recursive); } private bool TestDelete(string delete, string create) { Log.Comment("Delete dir: " + delete); if (!CreateDir(create)) return false; Directory.Delete(delete); return VerifyDelete(delete); } private bool TestDelete(string delete, string create, bool recursive) { Log.Comment("Delete dir: " + delete); if (!CreateDir(create)) return false; try { Directory.Delete(delete, recursive); } catch (IOException ex) { if (recursive && IOTests.Volume.FileSystem == "WINFS") { Log.Exception("WINFS has bug where recurisve may fail if indexer or Virus has handle open. Wait and try again."); for (int i = 0; i < 10; i++) { System.Threading.Thread.Sleep(1000); try { Directory.Delete(DIR, true); } catch { } if (VerifyDelete(DIR)) { return true; } } } throw ex; } return VerifyDelete(delete); } private bool VerifyDelete(string path) { if (Directory.Exists(path)) { Log.Exception("Failed to Delete " + path); return false; } return true; } private bool CreateDir(string path) { DirectoryInfo dir2 = Directory.CreateDirectory(path); if (!Directory.Exists(path)) { Log.Exception("Failed to Create " + dir2.FullName); return false; } if (createFile) { using (FileStream fs = new FileStream(dir2.FullName + @"\temp.txt", FileMode.Create)) { } if (!File.Exists(dir2.FullName + @"\temp.txt")) { Log.Exception("Failed to create file"); return false; } } return true; } #endregion Helper functions #region Test Cases [TestMethod] public MFTestResults DelCurrentDir() { MFTestResults result = MFTestResults.Pass; try { try { //Currently this causes hang Directory.Delete(".", false); Log.Exception("Should not be able to delete current directory"); return MFTestResults.Fail; } catch (IOException ioe) {/* pass case */ Log.Comment( "Got correct exception: " + ioe.Message ); result = MFTestResults.Pass; } } catch (Exception ex) { Log.Exception("Unexpected exception", ex); return MFTestResults.Fail; } return result; } [TestMethod] public MFTestResults DelNonExistent() { MFTestResults result = MFTestResults.Pass; try { try { Directory.Delete("ThisDoesNotExist"); Log.Exception("Should not be able to delete nonexistent directory"); return MFTestResults.Fail; } catch (IOException ioe) {/* pass case */ Log.Comment( "Got correct exception: " + ioe.Message ); result = MFTestResults.Pass; } try { Directory.Delete("ThisDoesNotExist", false); Log.Exception("Should not be able to delete nonexistent directory"); return MFTestResults.Fail; } catch (IOException ioe1) {/* pass case */ Log.Comment( "Got correct exception: " + ioe1.Message ); result = MFTestResults.Pass; } try { Directory.Delete("ThisDoesNotExist", true); Log.Exception("Should not be able to delete nonexistent directory"); return MFTestResults.Fail; } catch (IOException ioe2) {/* pass case */ Log.Comment( "Got correct exception: " + ioe2.Message ); result = MFTestResults.Pass; } } catch (Exception ex) { Log.Exception("Unexpected exception", ex); return MFTestResults.Fail; } return result; } [TestMethod] public MFTestResults DeleteDirNoSub() { MFTestResults result = MFTestResults.Pass; createFile = false; try { Log.Comment("Delete"); if (!TestDelete(DIR)) return MFTestResults.Fail; Log.Comment("Delete non-recursive"); if (!TestDelete(DIR, false)) return MFTestResults.Fail; Log.Comment("Delete recursive"); if (!TestDelete(DIR, true)) return MFTestResults.Fail; } catch (Exception ex) { Log.Exception("Unexpected exception", ex); return MFTestResults.Fail; } return result; } [TestMethod] public MFTestResults DeleteDirSub() { MFTestResults result = MFTestResults.Pass; createFile = false; try { Log.Comment("Delete - should throw IOException"); try { TestDelete(DIR, DIR + @"\SubTest1"); Log.Comment("Expected IO Exception because of subdir"); return MFTestResults.Fail; } catch (IOException ioe) {/* pass case */ Log.Comment( "Got correct exception: " + ioe.Message ); result = MFTestResults.Pass; } Log.Comment("Delete non-recursive - should throw IOException"); try { TestDelete(DIR, DIR + @"\SubTest2", false); Log.Comment("Expected IO Exception because of subdir"); return MFTestResults.Fail; } catch (IOException ioe1) {/* pass case */ Log.Comment( "Got correct exception: " + ioe1.Message ); result = MFTestResults.Pass; } Log.Comment("Delete recursive"); if (!TestDelete(DIR, DIR + @"\SubTest3", true)) return MFTestResults.Fail; } catch (Exception ex) { Log.Exception("Unexpected exception", ex); return MFTestResults.Fail; } return result; } [TestMethod] public MFTestResults DeleteDirNoSubWithFile() { MFTestResults result = MFTestResults.Pass; createFile = true; try { try { Log.Comment("Delete"); TestDelete(DIR); Log.Comment("Expected IO Exception because of subdir"); return MFTestResults.Fail; } catch (IOException ioe) {/* pass case */ Log.Comment( "Got correct exception: " + ioe.Message ); result = MFTestResults.Pass; } try { Log.Comment("Delete non-recursive"); TestDelete(DIR, false); Log.Comment("Expected IO Exception because of subdir"); return MFTestResults.Fail; } catch (IOException ioe1) {/* pass case */ Log.Comment( "Got correct exception: " + ioe1.Message ); result = MFTestResults.Pass; } Log.Comment("Delete recursive"); if (!TestDelete(DIR, true)) return MFTestResults.Fail; } catch (Exception ex) { Log.Exception("Unexpected exception", ex); return MFTestResults.Fail; } return result; } [TestMethod] public MFTestResults DeleteDirSubWithFiles() { MFTestResults result = MFTestResults.Pass; createFile = true; try { Log.Comment("Delete - should throw IOException"); try { TestDelete(DIR, DIR + @"\SubFileTest1"); Log.Comment("Expected IO Exception because of subdir"); return MFTestResults.Fail; } catch (IOException ioe) {/* pass case */ Log.Comment( "Got correct exception: " + ioe.Message ); result = MFTestResults.Pass; } Log.Comment("Delete non-recursive - should throw IOException"); try { TestDelete(DIR, DIR + @"\SubFileTest2", false); Log.Comment("Expected IO Exception because of subdir"); return MFTestResults.Fail; } catch (IOException ioe1) {/* pass case */ Log.Comment( "Got correct exception: " + ioe1.Message ); result = MFTestResults.Pass; } Log.Comment("Delete recursive"); if (!TestDelete(DIR, DIR + @"\SubFileTest3", true)) return MFTestResults.Fail; Log.Comment("Delete deep recursive"); CreateDir(DIR + @"\SubFileTest4"); CreateDir(DIR + @"\SubFileTest4\Level1a"); CreateDir(DIR + @"\SubFileTest4\Level1b"); CreateDir(DIR + @"\SubFileTest4\Level1a\sub1\deep1"); if (!TestDelete(DIR, DIR + @"\SubFileTest4\Level1a\sub1\deep2", true)) return MFTestResults.Fail; } catch (Exception ex) { Log.Exception("Unexpected exception", ex); return MFTestResults.Fail; } return result; } [TestMethod] public MFTestResults DeleteFileInUse() { MFTestResults result = MFTestResults.Pass; createFile = false; Log.Comment("Try to delete dir with file in use"); string dir = IOTests.Volume.RootDirectory + @"\DeleteFileInUse"; if (!CreateDir(dir)) return MFTestResults.Fail; FileStream fs = new FileStream(dir + @"\temp.txt", FileMode.Create); try { Directory.Delete(dir, true); Log.Exception("Expected IOException because file was in use"); } catch (IOException ioe) { /*pass case*/ Log.Comment( "Got correct exception: " + ioe.Message ); } catch (Exception ex) { Log.Exception("Unexpected exception: " + ex.Message); return MFTestResults.Fail; } Log.Comment("Close file and delete dir"); fs.Close(); try { Directory.Delete(dir, true); if (!VerifyDelete(dir)) return MFTestResults.Fail; } catch (Exception ex) { Log.Exception("Unexpected exception", ex); return MFTestResults.Fail; } return result; } // Need attribute support to finish [TestMethod] public MFTestResults DeleteReadOnlyDir() { MFTestResults result = MFTestResults.Pass; createFile = false; string dir = IOTests.Volume.RootDirectory + @"\DeleteReadOnlyDir"; DirectoryInfo dir2 = Directory.CreateDirectory(dir); File.SetAttributes(dir, FileAttributes.ReadOnly); try { try { Directory.Delete(dir); Log.Exception("Shouldn't be able to delete ReadOnly directory"); return MFTestResults.Fail; } catch (IOException ioe) { /*pass case*/ Log.Comment( "Got correct exception: " + ioe.Message ); } try { Directory.Delete(dir, true); Log.Exception("Shouldn't be able to delete ReadOnly directory"); return MFTestResults.Fail; } catch (IOException) { /*pass case*/ } try { Directory.Delete(dir, false); Log.Exception("Shouldn't be able to delete ReadOnly directory"); return MFTestResults.Fail; } catch (IOException ioe) { /*pass case*/ Log.Comment( "Got correct exception: " + ioe.Message ); } } catch (Exception ex) { Log.Exception("Unexpected exception", ex); return MFTestResults.Fail; } finally { File.SetAttributes(dir, FileAttributes.Normal); } return result; } [TestMethod] public MFTestResults DeleteHiddenDir() { MFTestResults result = MFTestResults.Pass; createFile = false; DirectoryInfo dir2; try { string dirName = DIR + @"\HiddenDir1"; dir2 = Directory.CreateDirectory(dirName); File.SetAttributes(dirName, FileAttributes.Hidden); Directory.Delete(dirName); if (!VerifyDelete(dirName)) return MFTestResults.Fail; dir2 = Directory.CreateDirectory(dirName); File.SetAttributes(dirName, FileAttributes.Hidden); Directory.Delete(dirName, true); if (!VerifyDelete(dirName)) return MFTestResults.Fail; dir2 = Directory.CreateDirectory(dirName); File.SetAttributes(dirName, FileAttributes.Hidden); Directory.Delete(dirName, false); if (!VerifyDelete(dirName)) return MFTestResults.Fail; } catch (Exception ex) { Log.Exception("Unexpected exception", ex); return MFTestResults.Fail; } return result; } #endregion Test Cases public MFTestMethod[] Tests { get { return new MFTestMethod[] { new MFTestMethod( DelCurrentDir, "DelCurrentDir" ), new MFTestMethod( DelNonExistent, "DelNonExistent" ), new MFTestMethod( DeleteDirNoSub, "DeleteDirNoSub" ), new MFTestMethod( DeleteDirSub, "DeleteDirSub" ), new MFTestMethod( DeleteDirNoSubWithFile, "DeleteDirNoSubWithFile" ), new MFTestMethod( DeleteDirSubWithFiles, "DeleteDirSubWithFiles" ), new MFTestMethod( DeleteFileInUse, "DeleteFileInUse" ), new MFTestMethod( DeleteReadOnlyDir, "DeleteReadOnlyDir" ), new MFTestMethod( DeleteHiddenDir, "DeleteHiddenDir" ), }; } } } } ================================================ FILE: Zelig/Zelig/FileSystemTest/Directory/DirectoryInfoTests.cs ================================================ /*--------------------------------------------------------------------- * FileTests.cs - file description * Version: 1.0 * Author: REDMOND\a-grchat * Created: 9/12/2007 4:51:10 PM * * Tests the basic functionality of Socket objects * ---------------------------------------------------------------------*/ using System; using System.Reflection; using System.IO; namespace FileSystemTest { public class DirectoryInfoTests : IMFTestInterface { [SetUp] public InitializeResult Initialize() { Log.Comment("Adding set up for the tests."); // Add your functionality here. try { IOTests.IntializeVolume(); } catch { Log.Comment("Unable to format media, skipping class tests."); return InitializeResult.Skip; } return InitializeResult.ReadyToGo; } [TearDown] public void CleanUp() { } /// /// Make sure DirectoryInfo could be constructed even when directory itself does not exist. /// /// [TestMethod] public MFTestResults DirectoryInfoTest_Constructor0() { bool testResult = false; try { DirectoryInfo di = new DirectoryInfo("DirectoryDoesntExist"); testResult = true; } catch (Exception ex) { Log.Exception("Unexpected Exception", ex); } return (testResult ? MFTestResults.Pass : MFTestResults.Fail); } /// /// Try creating with a bad path. /// /// [TestMethod] public MFTestResults DirectoryInfoTest_Constructor1() { bool testResult = true; try { DirectoryInfo di = new DirectoryInfo("*2%&^$%#^%?"); testResult = false; } catch (Exception ex) { Log.Exception("Expected Exception", ex); testResult = true; // ZeligBUG - with out this line testResult = false } return (testResult ? MFTestResults.Pass : MFTestResults.Fail); } /// /// Validate Name property /// /// [TestMethod] public MFTestResults DirectoryInfoTest_Name0() { MFTestResults testResult = MFTestResults.Pass; try { DirectoryInfo di = new DirectoryInfo(IOTests.Volume.RootDirectory + "\\dir1\\dir2"); if (!String.Equals(di.Name, "dir2")) testResult = MFTestResults.Fail; if (!String.Equals(di.FullName, IOTests.Volume.RootDirectory + "\\dir1\\dir2")) testResult = MFTestResults.Fail; } catch (Exception ex) { Log.Exception("Unexpected Exception", ex); testResult = MFTestResults.Pass; } return testResult; } /// /// Validate Parent property /// /// [TestMethod] public MFTestResults DirectoryInfoTest_Parent0() { bool testResult = true; try { DirectoryInfo di = new DirectoryInfo(IOTests.Volume.RootDirectory + "\\dir1\\dir2"); testResult = (di.Parent != null); } catch (Exception ex) { Log.Exception("Unexpected Exception", ex); } return (testResult ? MFTestResults.Pass : MFTestResults.Fail); } /// /// Validate Name property /// /// [TestMethod] public MFTestResults DirectoryInfoTest_Parent1() { bool testResult = true; try { DirectoryInfo di = new DirectoryInfo(IOTests.Volume.RootDirectory + "\\dir1\\dir2"); testResult = String.Equals(di.Parent.FullName, IOTests.Volume.RootDirectory + "\\dir1"); } catch (Exception ex) { Log.Exception("Unexpected Exception", ex); } return (testResult ? MFTestResults.Pass : MFTestResults.Fail); } [TestMethod] public MFTestResults DirectoryInfoTest_SubDirectory0() { bool testResult = true; try { DirectoryInfo di = new DirectoryInfo(IOTests.Volume.RootDirectory); di.CreateSubdirectory("DirectoryInfoTest_SubDirectory0"); testResult = Directory.Exists(IOTests.Volume.RootDirectory + "\\DirectoryInfoTest_SubDirectory0"); } catch (Exception ex) { Log.Exception("Unexpected Exception", ex); } return (testResult ? MFTestResults.Pass : MFTestResults.Fail); } [TestMethod] public MFTestResults DirectoryInfoTest_Create0() { bool testResult = true; try { DirectoryInfo di = new DirectoryInfo(IOTests.Volume.RootDirectory + "\\DirectoryInfoTest_Create0"); di.Create(); testResult = Directory.Exists(IOTests.Volume.RootDirectory + "\\DirectoryInfoTest_Create0"); } catch (Exception ex) { Log.Exception("Unexpected Exception", ex); } return (testResult ? MFTestResults.Pass : MFTestResults.Fail); } [TestMethod] public MFTestResults DirectoryInfoTest_Exists0() { bool testResult = true; try { Directory.CreateDirectory("DirectoryInfoTest_Exists0"); DirectoryInfo di = new DirectoryInfo("DirectoryInfoTest_Exists0"); testResult = di.Exists; } catch (Exception ex) { Log.Exception("Unexpected Exception", ex); } return (testResult ? MFTestResults.Pass : MFTestResults.Fail); } [TestMethod] public MFTestResults DirectoryInfoTest_Exists1() { bool testResult = true; try { DirectoryInfo di = new DirectoryInfo("DirectoryInfoTest_Exists1"); testResult = !di.Exists; } catch (Exception ex) { Log.Exception("Unexpected Exception", ex); } return (testResult ? MFTestResults.Pass : MFTestResults.Fail); } [TestMethod] public MFTestResults DirectoryInfoTest_Delete0() { bool testResult = true; try { Directory.CreateDirectory("DirectoryInfoTest_Delete0"); DirectoryInfo di = new DirectoryInfo("DirectoryInfoTest_Delete0"); testResult = di.Exists; di.Delete(); testResult = !di.Exists; } catch (Exception ex) { Log.Exception("Unexpected Exception", ex); } return (testResult ? MFTestResults.Pass : MFTestResults.Fail); } [TestMethod] public MFTestResults DirectoryInfoTest_Delete1() { bool testResult = true; try { Directory.CreateDirectory("DirectoryInfoTest_Delete1"); FileStream file = File.Create("DirectoryInfoTest_Delete1\\file-1.txt"); file.Close(); DirectoryInfo di = new DirectoryInfo("DirectoryInfoTest_Delete1"); testResult = di.Exists; di.Delete(true); testResult = !di.Exists; } catch (Exception ex) { Log.Exception("Unexpected Exception", ex); } return (testResult ? MFTestResults.Pass : MFTestResults.Fail); } [TestMethod] public MFTestResults DirectoryInfoTest_Attribute0() { bool testResult = true; try { Directory.CreateDirectory("DirectoryInfoTest_Attribute0"); DirectoryInfo di = new DirectoryInfo("DirectoryInfoTest_Attribute0"); testResult = ((di.Attributes & FileAttributes.Directory) != 0); } catch (Exception ex) { Log.Exception("Unexpected Exception", ex); } return (testResult ? MFTestResults.Pass : MFTestResults.Fail); } [TestMethod] public MFTestResults DirectoryInfoTest_CreationTime0() { bool testResult = false; try { Directory.CreateDirectory("DirectoryInfoTest_CreationTime0"); DirectoryInfo fi = new DirectoryInfo("DirectoryInfoTest_CreationTime0"); testResult = (fi.CreationTime.Ticks != 0); } catch (Exception ex) { Log.Exception("Unexpected Exception", ex); } return (testResult ? MFTestResults.Pass : MFTestResults.Fail); } [TestMethod] public MFTestResults DirectoryInfoTest_LastAccessTime0() { // do not run on Windows //if (Directory.GetCurrentDirectory().StartsWith("WINFS")) //{ // return MFTestResults.Skip; //} bool testResult = false; DirectoryInfo fi1, fi2; string dirName = "DirectoryInfoTest_LastAccessTime" + Guid.NewGuid().ToString() + "_0"; fi1 = Directory.CreateDirectory(dirName); testResult = (fi1.LastAccessTime.Ticks != 0); // add one day //Microsoft.SPOT.Hardware.Utility.SetLocalTime(DateTime.Now.AddDays(1)); fi1.CreateSubdirectory("AnotherDir" + Guid.NewGuid().ToString()); fi2 = new DirectoryInfo(dirName); testResult = (fi2.LastAccessTime - fi1.LastAccessTime >= new TimeSpan(1,0,0,0)); Log.Comment("First access : " + fi1.LastAccessTime.ToString()); Log.Comment("Second access: " + fi2.LastAccessTime.ToString()); return (testResult ? MFTestResults.Pass : MFTestResults.KnownFailure); } [TestMethod] public MFTestResults DirectoryInfoTest_LastWriteTime0() { bool testResult = false; DirectoryInfo di, fi1, fi2; int sleep = 2000; try { { di = Directory.CreateDirectory("DirectoryInfoTest_LastWriteTime0"); fi1 = new DirectoryInfo("DirectoryInfoTest_LastWriteTime0"); testResult = (fi1.LastWriteTime.Ticks != 0); } System.Threading.Thread.Sleep(sleep); { di.CreateSubdirectory("AnotherDirectory" + Guid.NewGuid().ToString()); fi2 = new DirectoryInfo("DirectoryInfoTest_LastWriteTime0"); testResult = (fi2.LastWriteTime - fi1.LastWriteTime >= new TimeSpan(0, 0, 0, 0, 2000)); } Log.Comment("First write : " + fi1.LastWriteTime.ToString()); Log.Comment("Second write: " + fi2.LastWriteTime.ToString()); } catch (Exception ex) { Log.Exception("Unexpected Exception", ex); } return (testResult ? MFTestResults.Pass : MFTestResults.Fail); } [TestMethod] public MFTestResults DirectoryInfoTest_GetFiles0() { bool testResult = false; try { Directory.CreateDirectory("DirectoryInfoTest_GetFiles0"); FileStream fooclose_test1 = File.Create("DirectoryInfoTest_GetFiles0\\file-1.txt"); fooclose_test1.Close(); FileStream fooclose_test2 = File.Create("DirectoryInfoTest_GetFiles0\\file-2.txt"); fooclose_test2.Close(); FileStream fooclose_test3 = File.Create("DirectoryInfoTest_GetFiles0\\file-3.txt"); fooclose_test3.Close(); DirectoryInfo di = new DirectoryInfo("DirectoryInfoTest_GetFiles0"); FileInfo[] files = di.GetFiles(); if (files.Length != 3) throw new Exception("Incorrect number of files"); testResult = true; testResult = testResult && (String.Equals(files[0].FullName, IOTests.Volume.RootDirectory + "\\DirectoryInfoTest_GetFiles0\\file-1.txt")); testResult = testResult && (String.Equals(files[1].FullName, IOTests.Volume.RootDirectory + "\\DirectoryInfoTest_GetFiles0\\file-2.txt")); testResult = testResult && (String.Equals(files[2].FullName, IOTests.Volume.RootDirectory + "\\DirectoryInfoTest_GetFiles0\\file-3.txt")); } catch (Exception ex) { Log.Exception("Unexpected Exception", ex); } return (testResult ? MFTestResults.Pass : MFTestResults.Fail); } public MFTestMethod[] Tests { get { return new MFTestMethod[] { new MFTestMethod( DirectoryInfoTest_Constructor0, "DirectoryInfoTest_Constructor0" ), new MFTestMethod( DirectoryInfoTest_Constructor1, "DirectoryInfoTest_Constructor1" ), new MFTestMethod( DirectoryInfoTest_Name0, "DirectoryInfoTest_Name0" ), new MFTestMethod( DirectoryInfoTest_Parent0, "DirectoryInfoTest_Parent0" ), new MFTestMethod( DirectoryInfoTest_Parent1, "DirectoryInfoTest_Parent1" ), new MFTestMethod( DirectoryInfoTest_SubDirectory0, "DirectoryInfoTest_SubDirectory0" ), new MFTestMethod( DirectoryInfoTest_Create0, "DirectoryInfoTest_Create0" ), new MFTestMethod( DirectoryInfoTest_Exists0, "DirectoryInfoTest_Exists0" ), new MFTestMethod( DirectoryInfoTest_Exists1, "DirectoryInfoTest_Exists1" ), new MFTestMethod( DirectoryInfoTest_Delete0, "DirectoryInfoTest_Delete0" ), new MFTestMethod( DirectoryInfoTest_Delete1, "DirectoryInfoTest_Delete1" ), new MFTestMethod( DirectoryInfoTest_Attribute0, "DirectoryInfoTest_Attribute0" ), new MFTestMethod( DirectoryInfoTest_CreationTime0, "DirectoryInfoTest_CreationTime0" ), new MFTestMethod( DirectoryInfoTest_LastAccessTime0, "DirectoryInfoTest_LastAccessTime0" ), new MFTestMethod( DirectoryInfoTest_LastWriteTime0, "DirectoryInfoTest_LastWriteTime0" ), new MFTestMethod( DirectoryInfoTest_GetFiles0, "DirectoryInfoTest_GetFiles0" ), }; } } } } ================================================ FILE: Zelig/Zelig/FileSystemTest/Directory/DirectoryTests.cs ================================================ /*--------------------------------------------------------------------- * FileTests.cs - file description * Version: 1.0 * Author: REDMOND\a-grchat * Created: 9/12/2007 4:51:10 PM * * Tests the basic functionality of Socket objects * ---------------------------------------------------------------------*/ using System; using System.Reflection; using System.IO; namespace FileSystemTest { public class DirectoryTests : IMFTestInterface { [SetUp] public InitializeResult Initialize() { Log.Comment("Adding set up for the tests."); // Add your functionality here. try { IOTests.IntializeVolume(); } catch { Log.Comment("Unable to format media, skipping class tests."); return InitializeResult.Skip; } return InitializeResult.ReadyToGo; } [TearDown] public void CleanUp() { } [TestMethod] public MFTestResults DirectoryTest0_CreateDirectory() { bool testResult = false; try { DirectoryInfo di = Directory.CreateDirectory("DirectoryTest0_CreateDirectory"); if (!Directory.Exists("DirectoryTest0_CreateDirectory")) { throw new IOException("Directory not found"); } testResult = true; Directory.Delete("DirectoryTest0_CreateDirectory"); } catch (Exception ex) { Log.Exception("Unexpected Exception", ex); } return (testResult ? MFTestResults.Pass : MFTestResults.Fail); } [TestMethod] public MFTestResults DirectorytTest1_CreateAndDeleteDirectory() { bool testResult = false; try { DirectoryInfo di = Directory.CreateDirectory("DirectorytTest1_CreateAndDeleteDirectory"); if (!Directory.Exists("DirectorytTest1_CreateAndDeleteDirectory")) { throw new IOException("Directory not found"); } Directory.Delete("DirectorytTest1_CreateAndDeleteDirectory"); if (File.Exists("DirectorytTest1_CreateAndDeleteDirectory.txt")) { throw new IOException("Directory was not deleted"); } testResult = true; } catch (Exception ex) { Log.Exception("Unexpected Exception", ex); } return (testResult ? MFTestResults.Pass : MFTestResults.Fail); } [TestMethod] public MFTestResults DirectoryTest2_CreateExistingDirectory() { bool testResult = false; try { DirectoryInfo di = Directory.CreateDirectory("DirectoryTest2_CreateExistingDirectory"); if (!Directory.Exists("DirectoryTest2_CreateExistingDirectory")) { throw new IOException("Directory not found"); } try { DirectoryInfo di1 = Directory.CreateDirectory("DirectoryTest2_CreateExistingDirectory"); testResult = true; } finally { Directory.Delete("DirectoryTest2_CreateExistingDirectory"); } } catch (Exception ex) { Log.Exception("Unexpected Exception", ex); } return (testResult ? MFTestResults.Pass : MFTestResults.Fail); } /// /// Attempt creating a directory when a file with same name exists. /// /// [TestMethod] public MFTestResults DirectoryTest_CreateDirectory1() { bool testResult = false; try { FileStream fooclose_test1 = File.Create("DirectoryTest_CreateDirectory1"); fooclose_test1.Close(); try { Directory.CreateDirectory("DirectoryTest_CreateDirectory1"); throw new Exception("Non empty directory deleted."); } catch (Exception) { testResult = true; } } catch (Exception ex) { Log.Exception("Unexpected Exception", ex); } return (testResult ? MFTestResults.Pass : MFTestResults.Fail); } /// /// Attempt deleting non empty directory. /// /// [TestMethod] public MFTestResults DirectoryTest_DeleteDirectory1() { bool testResult = false; try { DirectoryInfo di = Directory.CreateDirectory("DirectoryTest_DeleteDirectory1"); FileStream fooclose_test1 = File.Create("DirectoryTest_DeleteDirectory1\\file-1.txt"); fooclose_test1.Close(); try { Directory.Delete("DirectoryTest_DeleteDirectory1"); throw new Exception("Non empty directory deleted."); } catch (Exception) { testResult = true; } } catch (Exception ex) { Log.Exception("Unexpected Exception", ex); } return (testResult ? MFTestResults.Pass : MFTestResults.Fail); } /// /// Attempt deleting directory with sub directory. /// /// [TestMethod] public MFTestResults DirectoryTest_DeleteDirectory2() { bool testResult = false; try { Directory.CreateDirectory("DirectoryTest_DeleteDirectory2"); Directory.CreateDirectory("DirectoryTest_DeleteDirectory2\\SubDir"); try { Directory.Delete("DirectoryTest_DeleteDirectory2"); throw new Exception("Non empty directory deleted."); } catch (Exception) { testResult = true; } } catch (Exception ex) { Log.Exception("Unexpected Exception", ex); } return (testResult ? MFTestResults.Pass : MFTestResults.Fail); } [TestMethod] public MFTestResults DirectoryTest_DeleteDirectory3() { bool testResult = false; try { Directory.CreateDirectory("DirectoryTest_DeleteDirectory3"); Directory.CreateDirectory("DirectoryTest_DeleteDirectory3\\SubDir1"); Directory.CreateDirectory("DirectoryTest_DeleteDirectory3\\SubDir2"); FileStream fooclose_test1 = File.Create("DirectoryTest_DeleteDirectory3\\SubDir1\\file-1.txt"); fooclose_test1.Close(); FileStream fooclose_test2 = File.Create("DirectoryTest_DeleteDirectory3\\SubDir2\\file-2.txt"); fooclose_test2.Close(); Directory.Delete("DirectoryTest_DeleteDirectory3", true); testResult = true; } catch (Exception ex) { Log.Exception("Unexpected Exception", ex); } return (testResult ? MFTestResults.Pass : MFTestResults.Fail); } /// /// Delete a directory that does not exist. /// /// [TestMethod] public MFTestResults DirectoryTest_DeleteDirectory4() { bool testResult = true; try { Directory.Delete("DirectoryTest_DeleteDirectory4"); testResult = false; } catch (Exception ex) { Log.Exception("Got correct exception", ex); testResult = true; // ZeligBUG - remove this line and testResult is always false; } return (testResult ? MFTestResults.Pass : MFTestResults.Fail); } /// /// Simple move empty directory. /// /// [TestMethod] public MFTestResults DirectoryTest_MoveDirectory0() { bool testResult = true; try { Directory.CreateDirectory("DirectoryTest_MoveDirectory0"); Directory.Move("DirectoryTest_MoveDirectory0", "DirectoryTest_MoveDirectory0-1"); if (Directory.Exists("DirectoryTest_MoveDirectory0")) throw new IOException("Source not moved"); if (!Directory.Exists("DirectoryTest_MoveDirectory0-1")) throw new IOException("Destination not found"); } catch (Exception ex) { testResult = false; Log.Exception("Unexpected Exception", ex); } return (testResult ? MFTestResults.Pass : MFTestResults.Fail); } /// /// Simple move directory with files. /// /// [TestMethod] public MFTestResults DirectoryTest_MoveDirectory1() { bool testResult = true; try { Directory.CreateDirectory("DirectoryTest_MoveDirectory1"); FileStream fooclose_test1 = File.Create("DirectoryTest_MoveDirectory1\\file-1.txt"); fooclose_test1.Close(); Directory.Move("DirectoryTest_MoveDirectory1", "DirectoryTest_MoveDirectory1-1"); if (Directory.Exists("DirectoryTest_MoveDirectory1")) throw new IOException("Source not moved"); if (!Directory.Exists("DirectoryTest_MoveDirectory1-1")) throw new IOException("Destination not found"); } catch (Exception ex) { testResult = false; Log.Exception("Unexpected Exception", ex); } return (testResult ? MFTestResults.Pass : MFTestResults.Fail); } /// /// Simple move directory with directory substructure. /// /// [TestMethod] public MFTestResults DirectoryTest_MoveDirectory2() { bool testResult = true; try { Directory.CreateDirectory("DirectoryTest_MoveDirectory2"); Directory.CreateDirectory("DirectoryTest_MoveDirectory2\\sub1"); Directory.CreateDirectory("DirectoryTest_MoveDirectory2\\sub2"); FileStream fooclose_test1 = File.Create("DirectoryTest_MoveDirectory2\\sub1\\file-1.txt"); fooclose_test1.Close(); Directory.Move("DirectoryTest_MoveDirectory2", "DirectoryTest_MoveDirectory2-1"); if (Directory.Exists("DirectoryTest_MoveDirectory2")) throw new IOException("Source not moved"); if (!Directory.Exists("DirectoryTest_MoveDirectory2-1")) throw new IOException("Destination not found"); } catch (Exception ex) { testResult = false; Log.Exception("Unexpected Exception", ex); } return (testResult ? MFTestResults.Pass : MFTestResults.Fail); } /// /// Create-Move-ReCreate directory. /// /// [TestMethod] public MFTestResults DirectoryTest_MoveDirectory3() { bool testResult = true; try { Directory.CreateDirectory("DirectoryTest_MoveDirectory3"); Directory.Move("DirectoryTest_MoveDirectory3", "DirectoryTest_MoveDirectory3-1"); Directory.CreateDirectory("DirectoryTest_MoveDirectory3"); } catch (Exception ex) { testResult = false; Log.Exception("Unexpected Exception", ex); } return (testResult ? MFTestResults.Pass : MFTestResults.Fail); } /// /// Move dir when target exists. /// /// [TestMethod] public MFTestResults DirectoryTest_MoveDirectory4() { bool testResult = true; try { Directory.CreateDirectory("DirectoryTest_MoveDirectory4"); Directory.CreateDirectory("DirectoryTest_MoveDirectory4-1"); try { Directory.Move("DirectoryTest_MoveDirectory4", "DirectoryTest_MoveDirectory4-1"); testResult = false; } catch (IOException ioe) { /* pass case */ Log.Comment( "Got correct exception: " + ioe.Message ); testResult = true; // ZeligBUG - remove this line and testResult = false } } catch (Exception ex) { testResult = false; Log.Exception("Unexpected Exception", ex); } return (testResult ? MFTestResults.Pass : MFTestResults.Fail); } /// /// Move dir when source does not exist. /// /// [TestMethod] public MFTestResults DirectoryTest_MoveDirectory5() { bool testResult = true; try { try { Directory.Move("DirectoryTest_MoveDirectory5", "DirectoryTest_MoveDirectory5-1"); testResult = false; } catch (IOException ioe) { /* pass case */ Log.Comment( "Got correct exception: " + ioe.Message ); testResult = true; // ZeligBUG - remove this line and testResult = false } } catch (Exception ex) { testResult = false; Log.Exception("Unexpected Exception", ex); } return (testResult ? MFTestResults.Pass : MFTestResults.Fail); } /// /// Move dir when source exists as a file. /// /// [TestMethod] public MFTestResults DirectoryTest_MoveDirectory6() { bool testResult = true; try { FileStream fooclose_test1 = File.Create("DirectoryTest_MoveDirectory6"); fooclose_test1.Close(); try { Directory.Move("DirectoryTest_MoveDirectory6", "DirectoryTest_MoveDirectory6-1"); /// ISSUE: This appears to succeed, need to verify whether this is by design. testResult = false; } catch (IOException ioe) { /* pass case */ Log.Comment( "Got correct exception: " + ioe.Message ); testResult = true; // ZeligBUG - remove this line and testResult = false } } catch (Exception ex) { testResult = false; Log.Exception("Unexpected Exception", ex); } return (testResult ? MFTestResults.Pass : MFTestResults.Fail); } /// /// Move dir when destination exists as a file. /// /// [TestMethod] public MFTestResults DirectoryTest_MoveDirectory7() { bool testResult = true; try { FileStream fooclose_test1 = File.Create("DirectoryTest_MoveDirectory7-1"); fooclose_test1.Close(); try { Directory.Move("DirectoryTest_MoveDirectory7", "DirectoryTest_MoveDirectory7-1"); testResult = false; } catch (IOException ioe) { /* pass case */ Log.Comment( "Got correct exception: " + ioe.Message ); testResult = true; // ZeligBUG - remove this line and testResult = false } } catch (Exception ex) { testResult = false; Log.Exception("Unexpected Exception", ex); } return (testResult ? MFTestResults.Pass : MFTestResults.Fail); } [TestMethod] public MFTestResults DirectoryTest_Exist1() { bool testResult = false; try { testResult = !Directory.Exists("DirectoryTest_Exist1"); } catch (Exception ex) { Log.Exception("Unexpected Exception", ex); } return (testResult ? MFTestResults.Pass : MFTestResults.Fail); } [TestMethod] public MFTestResults DirectoryTest_Exist2() { bool testResult = false; try { testResult = Directory.Exists("\\"); } catch (Exception ex) { Log.Exception("Unexpected Exception", ex); } return (testResult ? MFTestResults.Pass : MFTestResults.Fail); } [TestMethod] public MFTestResults DirectoryTest_Exist3() { bool testResult = false; try { testResult = Directory.Exists(IOTests.Volume.RootDirectory); } catch (Exception ex) { Log.Exception("Unexpected Exception", ex); } return (testResult ? MFTestResults.Pass : MFTestResults.Fail); } [TestMethod] public MFTestResults DirectoryTest_GetFiles() { bool testResult = false; try { Directory.CreateDirectory("DirectoryTest_GetFiles"); FileStream fooclose_test1 = File.Create("DirectoryTest_GetFiles\\file-1.txt"); fooclose_test1.Close(); FileStream fooclose_test2 = File.Create("DirectoryTest_GetFiles\\file-2.txt"); fooclose_test2.Close(); FileStream fooclose_test3 = File.Create("DirectoryTest_GetFiles\\file-3.txt"); fooclose_test3.Close(); string[] files = Directory.GetFiles("DirectoryTest_GetFiles"); if (files.Length != 3) throw new Exception("Incorrect number of files"); testResult = true; testResult = testResult && (String.Equals(files[0], IOTests.Volume.RootDirectory + "\\DirectoryTest_GetFiles\\file-1.txt")); testResult = testResult && (String.Equals(files[1], IOTests.Volume.RootDirectory + "\\DirectoryTest_GetFiles\\file-2.txt")); testResult = testResult && (String.Equals(files[2], IOTests.Volume.RootDirectory + "\\DirectoryTest_GetFiles\\file-3.txt")); } catch (Exception ex) { Log.Exception("Unexpected Exception", ex); } return (testResult ? MFTestResults.Pass : MFTestResults.Fail); } [TestMethod] public MFTestResults DirectoryTest_GetCurrentDirectory() { bool testResult = false; try { string curDir = Directory.GetCurrentDirectory(); testResult = String.Equals(curDir, IOTests.Volume.RootDirectory); } catch (Exception ex) { Log.Exception("Unexpected Exception", ex); } return (testResult ? MFTestResults.Pass : MFTestResults.Fail); } [TestMethod] public MFTestResults DirectoryTest_SetCurrentDirectory0() { bool testResult = false; try { Directory.CreateDirectory(IOTests.Volume.RootDirectory + "\\DirectoryTest_SetCurrentDirectory0"); Directory.SetCurrentDirectory(IOTests.Volume.RootDirectory + "\\DirectoryTest_SetCurrentDirectory0"); string curDir = Directory.GetCurrentDirectory(); testResult = String.Equals(curDir, IOTests.Volume.RootDirectory + "\\DirectoryTest_SetCurrentDirectory0"); } catch (Exception ex) { Log.Exception("Unexpected Exception", ex); } return (testResult ? MFTestResults.Pass : MFTestResults.Fail); } /// /// Set current directory to a non existent one. /// /// [TestMethod] public MFTestResults DirectoryTest_SetCurrentDirectory1() { bool testResult = true; try { Directory.SetCurrentDirectory(IOTests.Volume.RootDirectory + "\\DirectoryTest_SetCurrentDirectory1"); testResult = false; } catch (Exception ex) { Log.Exception("Got correct exception", ex); testResult = true; // ZeligBUG - remove this line and testResult = false } return (testResult ? MFTestResults.Pass : MFTestResults.Fail); } public MFTestMethod[] Tests { get { return new MFTestMethod[] { new MFTestMethod( DirectoryTest0_CreateDirectory, "DirectoryTest0_CreateDirectory" ), new MFTestMethod( DirectorytTest1_CreateAndDeleteDirectory, "DirectorytTest1_CreateAndDeleteDirectory" ), new MFTestMethod( DirectoryTest2_CreateExistingDirectory, "DirectoryTest2_CreateExistingDirectory" ), new MFTestMethod( DirectoryTest_CreateDirectory1, "DirectoryTest_CreateDirectory1" ), new MFTestMethod( DirectoryTest_DeleteDirectory1, "DirectoryTest_DeleteDirectory1" ), new MFTestMethod( DirectoryTest_DeleteDirectory2, "DirectoryTest_DeleteDirectory2" ), new MFTestMethod( DirectoryTest_DeleteDirectory3, "DirectoryTest_DeleteDirectory3" ), new MFTestMethod( DirectoryTest_DeleteDirectory4, "DirectoryTest_DeleteDirectory4" ), new MFTestMethod( DirectoryTest_MoveDirectory0, "DirectoryTest_MoveDirectory0" ), new MFTestMethod( DirectoryTest_MoveDirectory1, "DirectoryTest_MoveDirectory1" ), new MFTestMethod( DirectoryTest_MoveDirectory2, "DirectoryTest_MoveDirectory2" ), new MFTestMethod( DirectoryTest_MoveDirectory3, "DirectoryTest_MoveDirectory3" ), new MFTestMethod( DirectoryTest_MoveDirectory4, "DirectoryTest_MoveDirectory4" ), new MFTestMethod( DirectoryTest_MoveDirectory5, "DirectoryTest_MoveDirectory5" ), new MFTestMethod( DirectoryTest_MoveDirectory6, "DirectoryTest_MoveDirectory6" ), new MFTestMethod( DirectoryTest_MoveDirectory7, "DirectoryTest_MoveDirectory7" ), new MFTestMethod( DirectoryTest_Exist1, "DirectoryTest_Exist1" ), new MFTestMethod( DirectoryTest_Exist2, "DirectoryTest_Exist2" ), new MFTestMethod( DirectoryTest_Exist3, "DirectoryTest_Exist3" ), new MFTestMethod( DirectoryTest_GetFiles, "DirectoryTest_GetFiles" ), new MFTestMethod( DirectoryTest_GetCurrentDirectory, "DirectoryTest_GetCurrentDirectory" ), new MFTestMethod( DirectoryTest_SetCurrentDirectory0, "DirectoryTest_SetCurrentDirectory0" ), new MFTestMethod( DirectoryTest_SetCurrentDirectory1, "DirectoryTest_SetCurrentDirectory1" ), }; } } } } ================================================ FILE: Zelig/Zelig/FileSystemTest/Directory/Exists.cs ================================================ //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // Copyright (c) Microsoft Corporation. All rights reserved. //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// using System; using System.IO; namespace FileSystemTest { public class Exists : IMFTestInterface { [SetUp] public InitializeResult Initialize() { Log.Comment("Adding set up for the tests."); // Add your functionality here. try { IOTests.IntializeVolume(); Directory.CreateDirectory(TestDir); } catch (Exception ex) { Log.Comment("Skipping: Unable to initialize file system" + ex.Message); return InitializeResult.Skip; } return InitializeResult.ReadyToGo; } [TearDown] public void CleanUp() { } #region local vars private const string TestDir = "ExistsDirectory"; #endregion local vars #region Helper functions private bool TestExists(string path, bool exists) { Log.Comment("Checking for " + path); if (Directory.Exists(path) != exists) { Log.Exception("Expeceted " + exists + " but got " + !exists); return false; } return true; } #endregion Helper functions #region Test Cases [TestMethod] public MFTestResults InvalidArguments() { bool dir; MFTestResults result = MFTestResults.Pass; try { try { Log.Comment("Null"); dir = Directory.Exists(null); Log.Exception( "Expected ArgumentNullException, but got " + dir ); return MFTestResults.Fail; } catch (ArgumentNullException ane) { /* pass case */ Log.Comment( "Got correct exception: " + ane.Message ); result = MFTestResults.Pass; } try { Log.Comment("String.Empty"); dir = Directory.Exists(String.Empty); Log.Exception( "Expected ArgumentException, but got " + dir ); return MFTestResults.Fail; } catch (ArgumentException ae) { /* pass case */ Log.Comment( "Got correct exception: " + ae.Message ); result = MFTestResults.Pass; } try { Log.Comment("White Space"); dir = Directory.Exists(" "); Log.Exception( "Expected ArgumentException, but got " + dir ); return MFTestResults.Fail; } catch (ArgumentException ae1) { /* pass case */ Log.Comment( "Got correct exception: " + ae1.Message ); result = MFTestResults.Pass; } } catch (Exception ex) { Log.Exception("Unexpected exception: " + ex.Message); return MFTestResults.Fail; } return result; } [TestMethod] public MFTestResults CurrentDirectory() { MFTestResults result = MFTestResults.Pass; try { if (!TestExists(".", true)) return MFTestResults.Fail; if (!TestExists("..", true)) return MFTestResults.Fail; if (!TestExists(Directory.GetCurrentDirectory(), true)) return MFTestResults.Fail; Log.Comment("Set relative Directory"); Directory.SetCurrentDirectory(TestDir); if (!TestExists(".", true)) return MFTestResults.Fail; if (!TestExists(Directory.GetCurrentDirectory(), true)) return MFTestResults.Fail; if (!TestExists("..", true)) return MFTestResults.Fail; } catch (Exception ex) { Log.Exception("Unexpected exception: " + ex.Message); return MFTestResults.Fail; } return result; } [TestMethod] public MFTestResults NonExistentDirs() { MFTestResults result = MFTestResults.Pass; try { if (!TestExists("unknown directory", false)) return MFTestResults.Fail; if (!TestExists(IOTests.Volume.RootDirectory + @"\Dir1\dir2", false)) result = MFTestResults.Fail; if (!TestExists(@"BAR\", false)) return MFTestResults.Fail; try { bool test = TestExists("XX:\\", false); Log.Comment("Expected ArgumentException, got " + test); return MFTestResults.Fail; } catch (ArgumentException ae) { /* pass case */ Log.Comment( "Got correct exception: " + ae.Message ); result = MFTestResults.Pass; } } catch (Exception ex) { Log.Exception("Unexpected exception: " + ex.Message); return MFTestResults.Fail; } return result; } [TestMethod] public MFTestResults PathTooLong() { MFTestResults result = MFTestResults.Pass; try { string path = new string('x', 500); bool exists = Directory.Exists(path); Log.Exception("Expected IOException, got " + exists); return MFTestResults.Fail; } catch (IOException ioe) { /* pass case */ Log.Comment( "Got correct exception: " + ioe.Message ); result = MFTestResults.Pass; } // PathTooLong catch (Exception ex) { Log.Exception("Unexpected exception: " + ex.Message); return MFTestResults.Fail; } return result; } [TestMethod] public MFTestResults CaseInsensitive() { MFTestResults result = MFTestResults.Pass; try { Directory.CreateDirectory(TestDir); if (!TestExists(TestDir.ToLower(), true)) return MFTestResults.Fail; if (!TestExists(TestDir.ToUpper(), true)) return MFTestResults.Fail; } catch (Exception ex) { Log.Exception("Unexpected exception: " + ex.Message); return MFTestResults.Fail; } return result; } [TestMethod] public MFTestResults MultiSpaceExists() { MFTestResults result = MFTestResults.Pass; try { string dir = Directory.GetCurrentDirectory() + @"\Microsoft Visual Studio .NET\Frame work\V1.0.0.0000"; Directory.CreateDirectory(dir); if (!TestExists(dir, true)) return MFTestResults.Fail; } catch (Exception ex) { Log.Exception("Unexpected exception: " + ex.Message); return MFTestResults.Fail; } return result; } #endregion Test Cases public MFTestMethod[] Tests { get { return new MFTestMethod[] { new MFTestMethod( InvalidArguments, "InvalidArguments" ), new MFTestMethod( CurrentDirectory, "CurrentDirectory" ), new MFTestMethod( NonExistentDirs, "NonExistentDirs" ), new MFTestMethod( PathTooLong, "PathTooLong" ), new MFTestMethod( CaseInsensitive, "CaseInsensitive" ), new MFTestMethod( MultiSpaceExists, "MultiSpaceExists" ), }; } } } } ================================================ FILE: Zelig/Zelig/FileSystemTest/Directory/GetDirectories.cs ================================================ //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // Copyright (c) Microsoft Corporation. All rights reserved. //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// using System; using System.Collections; using System.IO; using System.Collections.Generic; namespace FileSystemTest { public class GetDirectories : IMFTestInterface { [SetUp] public InitializeResult Initialize() { Log.Comment("The following tests are located in FileTests.cs"); try { IOTests.IntializeVolume(); AddDir(IOTests.Volume.RootDirectory + "\\" + TestDir + "\\" + Mid1 + "\\" + Tail1); AddDir(IOTests.Volume.RootDirectory + "\\" + TestDir + "\\" + Mid1 + "\\" + Tail2); AddDir(IOTests.Volume.RootDirectory + "\\" + TestDir + "\\" + Mid2 + "\\" + Tail1); } catch (Exception ex) { Log.Exception("Skipping: Unable to initialize file system.", ex); return InitializeResult.Skip; } return InitializeResult.ReadyToGo; } [TearDown] public void CleanUp() { } #region local vars private List validDirs = new List(); private char[] special = new char[] { '!', '#', '$', '%', '\'', '(', ')', '+', '-', '.', '@', '[', ']', '_', '`', '{', '}', '~' }; private const string TestDir = "GetDirectory"; private const string Mid1 = "Mid1"; private const string Mid2 = "Mid2"; private const string Tail1 = "Tail1"; private const string Tail2 = "Tail2"; #endregion local vars #region Helper functions private void AddDir(string path) { Log.Comment("Adding Directory: " + path); try { path = Path.GetFullPath(path); if (!validDirs.Contains(path)) { // create full path Directory.CreateDirectory(path); while (!validDirs.Contains(path) && path != "\\" && path != null) { validDirs.Add(path); path = Path.GetFullPath(path + @"\.."); } } } catch { Log.Exception("Failed to create directory"); } } private string StrArrayToStr(string[] list) { string result = ""; foreach (string item in list) { result += item + ", "; } return result.TrimEnd(',', ' '); } private bool TestGetDirectoryEnum(int expected, params string[] nodes) { return VerifyEnum(expected, GetPath(nodes), Directory.EnumerateDirectories(GetPath(nodes))); } private bool VerifyEnum(int expected, string path, IEnumerable result) { bool success = true; int cnt = 0; foreach (string dir in result) { if (!validDirs.Contains(dir)) { Log.Exception("Unexpected directory found: " + dir); success = false; } cnt++; } if (cnt != expected) { Log.Exception("Expected " + expected + " directories, got " + cnt); success = false; } return success; } private bool TestGetDirectories(int expected, params string[] nodes) { return Verify(expected, Directory.GetDirectories(GetPath(nodes))); } private bool Verify(int expected, string[] result) { bool success = true; if (result.Length != expected) { Log.Exception("Expected " + expected + " directories, got " + result.Length); success = false; } foreach (string dir in result) { if (!validDirs.Contains(dir)) { Log.Exception("Unexpected directory found: " + dir); success = false; } } return success; } private string GetPath(string[] nodes) { string path = ""; if (nodes.Length > 0) { path = nodes[0]; for (int i = 1; i < nodes.Length; i++) { path += "\\" + nodes[i]; } } Log.Comment("Path: " + path); return path; } private string RandDirName(int length) { char[] chars = new char[length]; Random random = new Random(); for (int i = 0; i < length; i++) { switch (random.Next(4)) { // 0 = specal chars case 0: int x = random.Next(special.Length); chars[i] = special[x]; break; // 1 = numbers case 1: chars[i] = (char)((int)'0' + random.Next(10)); break; // 2 = upper case case 2: chars[i] = (char)((int)'A' + random.Next(26)); break; // 3 = lower case case 3: chars[i] = (char)((int)'a' + random.Next(26)); break; default: throw new ArgumentException("Expected 0-3"); } } return new string(chars); } #endregion Helper functions #region Test Cases [TestMethod] public MFTestResults InvalidArguments() { string[] dirs; MFTestResults result = MFTestResults.Pass; try { // null cases try { Log.Comment("Null"); dirs = Directory.GetDirectories(null); Log.Exception( "Expected ArgumentNullException, but got " + StrArrayToStr( dirs ) ); return MFTestResults.Fail; } catch (ArgumentNullException ane) { /* pass case */ Log.Comment( "Got correct exception: " + ane.Message ); result = MFTestResults.Pass; } // string.empty cases try { Log.Comment("String.Empty"); dirs = Directory.GetDirectories(String.Empty); Log.Exception( "Expected ArgumentException, but got " + StrArrayToStr( dirs ) ); return MFTestResults.Fail; } catch (ArgumentException ae) { /* pass case */ Log.Comment( "Got correct exception: " + ae.Message ); result = MFTestResults.Pass; } // whitespace cases try { Log.Comment("White Space"); dirs = Directory.GetDirectories(" "); Log.Exception( "Expected ArgumentException, but got " + StrArrayToStr( dirs ) ); return MFTestResults.Fail; } catch (ArgumentException ae1) { /* pass case */ Log.Comment( "Got correct exception: " + ae1.Message ); result = MFTestResults.Pass; } // New lines try { Log.Comment("\\n"); dirs = Directory.GetDirectories("\n"); Log.Exception( "Expected ArgumentException, but got " + StrArrayToStr( dirs ) ); return MFTestResults.Fail; } catch (ArgumentException ae2) { /* pass case */ Log.Comment( "Got correct exception: " + ae2.Message ); result = MFTestResults.Pass; } // Filter as path try { Log.Comment("*"); dirs = Directory.GetDirectories("*"); Log.Exception( "Expected ArgumentException, but got " + StrArrayToStr( dirs ) ); return MFTestResults.Fail; } catch (ArgumentException ae3) { /* pass case */ Log.Comment( "Got correct exception: " + ae3.Message ); result = MFTestResults.Pass; } } catch (Exception ex) { Log.Exception("Unexpected exception: " + ex.Message); return MFTestResults.Fail; } return result; } [TestMethod] public MFTestResults ValidCasesNoFilter() { MFTestResults result = MFTestResults.Pass; try { // relative Directory.SetCurrentDirectory(IOTests.Volume.RootDirectory); if (!TestGetDirectories(0, TestDir, Mid1, Tail2)) return MFTestResults.Fail; if (!TestGetDirectories(0, TestDir, Mid2, Tail1)) return MFTestResults.Fail; if (!TestGetDirectories(2, TestDir, Mid1)) return MFTestResults.Fail; if (!TestGetDirectories(1, TestDir, Mid2)) return MFTestResults.Fail; if (!TestGetDirectories(2, TestDir)) return MFTestResults.Fail; if (!TestGetDirectories(1, ".")) return MFTestResults.Fail; if (!TestGetDirectories(0, TestDir, Mid1, "." , Tail1, "..", Tail1, "..", "..", Mid2, Tail1)) return MFTestResults.Fail; // Move up tree where there is more directories Directory.SetCurrentDirectory(TestDir); if (!TestGetDirectories(2, ".")) return MFTestResults.Fail; if (!TestGetDirectories(1, "..")) return MFTestResults.Fail; // absolute if (!TestGetDirectories(0, IOTests.Volume.RootDirectory, TestDir, Mid1, Tail1)) return MFTestResults.Fail; if (!TestGetDirectories(0, IOTests.Volume.RootDirectory, TestDir, Mid2, Tail1)) return MFTestResults.Fail; if (!TestGetDirectories(1, IOTests.Volume.RootDirectory, TestDir, Mid2)) return MFTestResults.Fail; if (!TestGetDirectories(2, IOTests.Volume.RootDirectory, TestDir, Mid1)) return MFTestResults.Fail; if (!TestGetDirectories(2, IOTests.Volume.RootDirectory, TestDir)) return MFTestResults.Fail; if (!TestGetDirectories(1, IOTests.Volume.RootDirectory)) return MFTestResults.Fail; if (!TestGetDirectories(0, IOTests.Volume.RootDirectory, TestDir, Mid1, ".", Tail1, "..", Tail1, "..", "..", Mid2, Tail1, ".")) return MFTestResults.Fail; } catch (Exception ex) { Log.Exception("Unexpected exception: " + ex.Message); return MFTestResults.Fail; } return result; } [TestMethod] public MFTestResults DirectoryEnumTest() { MFTestResults result = MFTestResults.Pass; try { // relative Directory.SetCurrentDirectory(IOTests.Volume.RootDirectory); if (!TestGetDirectoryEnum(0, TestDir, Mid1, Tail2)) return MFTestResults.Fail; if (!TestGetDirectoryEnum(0, TestDir, Mid2, Tail1)) return MFTestResults.Fail; if (!TestGetDirectoryEnum(2, TestDir, Mid1)) return MFTestResults.Fail; if (!TestGetDirectoryEnum(1, TestDir, Mid2)) return MFTestResults.Fail; if (!TestGetDirectoryEnum(2, TestDir)) return MFTestResults.Fail; if (!TestGetDirectoryEnum(1, ".")) return MFTestResults.Fail; if (!TestGetDirectoryEnum(0, TestDir, Mid1, ".", Tail1, "..", Tail1, "..", "..", Mid2, Tail1)) return MFTestResults.Fail; // Move up tree where there is more directories Directory.SetCurrentDirectory(TestDir); if (!TestGetDirectoryEnum(2, ".")) return MFTestResults.Fail; if (!TestGetDirectoryEnum(1, "..")) return MFTestResults.Fail; // absolute if (!TestGetDirectoryEnum(0, IOTests.Volume.RootDirectory, TestDir, Mid1, Tail1)) return MFTestResults.Fail; if (!TestGetDirectoryEnum(0, IOTests.Volume.RootDirectory, TestDir, Mid2, Tail1)) return MFTestResults.Fail; if (!TestGetDirectoryEnum(1, IOTests.Volume.RootDirectory, TestDir, Mid2)) return MFTestResults.Fail; if (!TestGetDirectoryEnum(2, IOTests.Volume.RootDirectory, TestDir, Mid1)) return MFTestResults.Fail; if (!TestGetDirectoryEnum(2, IOTests.Volume.RootDirectory, TestDir)) return MFTestResults.Fail; if (!TestGetDirectoryEnum(1, IOTests.Volume.RootDirectory)) return MFTestResults.Fail; if (!TestGetDirectoryEnum(0, IOTests.Volume.RootDirectory, TestDir, Mid1, ".", Tail1, "..", Tail1, "..", "..", Mid2, Tail1, ".")) return MFTestResults.Fail; } catch (Exception ex) { Log.Exception("Unexpected exception: " + ex.Message); return MFTestResults.Fail; } return result; } [TestMethod] public MFTestResults SpecialDirNames() { MFTestResults result = MFTestResults.Pass; try { Log.Comment("Find file each with special char file names"); string specialdir = IOTests.Volume.RootDirectory + "\\" + TestDir + "\\SpecialFileNames"; AddDir(specialdir); for (int i = 0; i < special.Length; i++) { string dir = i + "_" + new string(new char[] { special[i] }) + "_zDirectory"; AddDir(specialdir + "\\" + dir); } if (!TestGetDirectories(special.Length, specialdir)) return MFTestResults.Fail; } catch (Exception ex) { Log.Exception("Unexpected exception: " + ex.Message); return MFTestResults.Fail; } return result; } [TestMethod] public MFTestResults RandomDirectoryNames() { MFTestResults result = MFTestResults.Pass; try { Log.Comment("Light stress with 100 random directory names"); Random random = new Random(); string randdir = IOTests.Volume.RootDirectory + "\\" + TestDir + "\\RandomFileNames"; AddDir(randdir); for (int i = 0; i < 100; i++) { string dir = i + "_" + RandDirName(random.Next(50) + 1); // Don't end with period. if (dir[dir.Length - 1] == '.') { dir += "c"; } AddDir(randdir + "\\" + dir); } if (!TestGetDirectories(100, randdir)) return MFTestResults.Fail; } catch (Exception ex) { Log.Exception("Unexpected exception: " + ex.Message); return MFTestResults.Fail; } return result; } [TestMethod] public MFTestResults GetDirectoriesBadPath() { MFTestResults result = MFTestResults.Pass; try { Directory.GetDirectories(IOTests.Volume.RootDirectory + "\\_DIR_NOT_EXIST"); return MFTestResults.Fail; } catch (IOException e1) { if((IOExceptionErrorCode)e1.ErrorCode != IOExceptionErrorCode.DirectoryNotFound) return MFTestResults.Fail; } // make sure the directory was not created try { Directory.GetDirectories(IOTests.Volume.RootDirectory + "\\_DIR_NOT_EXIST"); return MFTestResults.Fail; } catch (IOException e1) { if((IOExceptionErrorCode)e1.ErrorCode != IOExceptionErrorCode.DirectoryNotFound) return MFTestResults.Fail; } try { Directory.GetFiles(IOTests.Volume.RootDirectory + "\\_DIR_NOT_EXIST"); return MFTestResults.Fail; } catch (IOException e1) { if((IOExceptionErrorCode)e1.ErrorCode != IOExceptionErrorCode.DirectoryNotFound) return MFTestResults.Fail; } // make sure the path was not created try { Directory.GetFiles(IOTests.Volume.RootDirectory + "\\_DIR_NOT_EXIST"); return MFTestResults.Fail; } catch (IOException e1) { if((IOExceptionErrorCode)e1.ErrorCode != IOExceptionErrorCode.DirectoryNotFound) return MFTestResults.Fail; } try { foreach(string file in Directory.EnumerateFileSystemEntries(IOTests.Volume.RootDirectory + "\\_DIR_NOT_EXIST")) { Log.Comment(file); } return MFTestResults.Fail; } catch (IOException e1) { if((IOExceptionErrorCode)e1.ErrorCode != IOExceptionErrorCode.DirectoryNotFound) return MFTestResults.Fail; } // make sure the directory was not created try { foreach (string file in Directory.EnumerateFileSystemEntries(IOTests.Volume.RootDirectory + "\\_DIR_NOT_EXIST")) { Log.Comment(file); } return MFTestResults.Fail; } catch (IOException e1) { if((IOExceptionErrorCode)e1.ErrorCode != IOExceptionErrorCode.DirectoryNotFound) return MFTestResults.Fail; } return result; } #endregion Test Cases public MFTestMethod[] Tests { get { return new MFTestMethod[] { new MFTestMethod( InvalidArguments, "InvalidArguments" ), new MFTestMethod( ValidCasesNoFilter, "ValidCasesNoFilter" ), new MFTestMethod( DirectoryEnumTest, "DirectoryEnumTest" ), new MFTestMethod( SpecialDirNames, "SpecialDirNames" ), new MFTestMethod( RandomDirectoryNames, "RandomDirectoryNames" ), new MFTestMethod( GetDirectoriesBadPath, "GetDirectoriesBadPath" ), }; } } } } ================================================ FILE: Zelig/Zelig/FileSystemTest/Directory/GetFiles.cs ================================================ //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // Copyright (c) Microsoft Corporation. All rights reserved. //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// using System; using System.Collections; using System.IO; using System.Collections.Generic; namespace FileSystemTest { public class GetFiles : IMFTestInterface { [SetUp] public InitializeResult Initialize() { // These tests rely on underlying file system so we need to make // sure we can format it before we start the tests. If we can't // format it, then we assume there is no FS to test on this platform. // delete the directory DOTNETMF_FS_EMULATION try { IOTests.IntializeVolume(); List list = new List(); list.Add(IOTests.Volume.RootDirectory + "\\" + TestDir + "\\" + Mid1); list.Add(IOTests.Volume.RootDirectory + "\\" + TestDir + "\\" + Mid2); validDirMap[TestDir] = list; list = new List(); list.Add(IOTests.Volume.RootDirectory + "\\" + TestDir + "\\" + Mid1 + "\\" + Tail1); list.Add(IOTests.Volume.RootDirectory + "\\" + TestDir + "\\" + Mid1 + "\\" + Tail2); validDirMap[TestDir + "\\" + Mid1] = list; list = new List(); list.Add(IOTests.Volume.RootDirectory + "\\" + TestDir + "\\" + Mid2 + "\\" + Tail1); validDirMap[TestDir + "\\" + Mid2] = list; Directory.CreateDirectory(TestDir + "\\" + Mid1 + "\\" + Tail1); Directory.CreateDirectory(TestDir + "\\" + Mid1 + "\\" + Tail2); Directory.CreateDirectory(TestDir + "\\" + Mid2 + "\\" + Tail1); // [Dir] [file count] // TestDir 0 // Mid1 0 // Mid1/Tail1 4 // Mid1/Tail2 1 // Mid2 3 // Mid2/Tail1 2 list = new List(); list.Add(IOTests.Volume.RootDirectory + "\\" + TestDir); validDirMap[IOTests.Volume.RootDirectory] = list; list = new List(); list.Add(IOTests.Volume.RootDirectory + "\\" + TestDir + "\\" + Mid1); list.Add(IOTests.Volume.RootDirectory + "\\" + TestDir + "\\" + Mid2); validDirMap[IOTests.Volume.RootDirectory + "\\" + TestDir] = list; list = new List(); list.Add(IOTests.Volume.RootDirectory + "\\" + TestDir + "\\" + Mid1 + "\\" + Tail1); list.Add(IOTests.Volume.RootDirectory + "\\" + TestDir + "\\" + Mid1 + "\\" + Tail2); validDirMap[IOTests.Volume.RootDirectory + "\\" + TestDir + "\\" + Mid1] = list; list = new List(); list.Add(IOTests.Volume.RootDirectory + "\\" + TestDir + "\\" + Mid2 + "\\" + Tail1); validDirMap[IOTests.Volume.RootDirectory + "\\" + TestDir + "\\" + Mid2] = list; AddFile(IOTests.Volume.RootDirectory + "\\" + TestDir + "\\" + Mid1 + "\\" + Tail1 + "\\TestFile1.txt"); AddFile(IOTests.Volume.RootDirectory + "\\" + TestDir + "\\" + Mid1 + "\\" + Tail1 + "\\TestFile2.txt"); AddFile(IOTests.Volume.RootDirectory + "\\" + TestDir + "\\" + Mid1 + "\\" + Tail1 + "\\FileTest1.txt"); AddFile(IOTests.Volume.RootDirectory + "\\" + TestDir + "\\" + Mid1 + "\\" + Tail1 + "\\FileTest2.txt"); AddFile(IOTests.Volume.RootDirectory + "\\" + TestDir + "\\" + Mid1 + "\\" + Tail2 + "\\TestFile1.txt"); AddFile(IOTests.Volume.RootDirectory + "\\" + TestDir + "\\" + Mid2 + "\\HeadMidFile1.jpg"); AddFile(IOTests.Volume.RootDirectory + "\\" + TestDir + "\\" + Mid2 + "\\TailMidFile2.txt"); AddFile(IOTests.Volume.RootDirectory + "\\" + TestDir + "\\" + Mid2 + "\\TailMidFile3.exe"); AddFile(IOTests.Volume.RootDirectory + "\\" + TestDir + "\\" + Mid2 + "\\" + Tail1 + "\\FileTest1.txt"); AddFile(IOTests.Volume.RootDirectory + "\\" + TestDir + "\\" + Mid2 + "\\" + Tail1 + "\\FileTest2.txt"); } catch (Exception ex) { Log.Exception("Skipping: Unable to initialize file system", ex); return InitializeResult.Skip; } return InitializeResult.ReadyToGo; } [TearDown] public void CleanUp() { } #region local vars private List validFiles = new List(); private Dictionary> validDirMap = new Dictionary>(); private const string TestDir = "GetFiles"; private const string Mid1 = "Mid1"; private const string Mid2 = "Mid2"; private const string Tail1 = "Tail1"; private const string Tail2 = "Tail2"; private char[] special = new char[] { '!', '#', '$', '%', '\'', '(', ')', '+', '-', '.', '@', '[', ']', '_', '`', '{', '}', '~' }; #endregion local vars #region Helper functions private void AddFile(string path) { Log.Comment("Adding file: " + path); try { new FileInfo(path).Create().Close(); validFiles.Add(path); } catch { Log.Exception("Failed to create file"); } } private string StrArrayToStr(string[] list) { string result = ""; foreach (string item in list) { result += item + ", "; } return result.TrimEnd(',', ' '); } private bool TestGetFilesAndDirsEnum(int expected, params string[] nodes) { return VerifyFilesAndDirsEnum(expected, GetPath(nodes), Directory.EnumerateFileSystemEntries(GetPath(nodes))); } private bool VerifyFilesAndDirsEnum(int expected, string path, IEnumerable results) { bool valid = true; int cnt = 0; path = Path.GetFullPath(path); List list = null; if(validDirMap.ContainsKey(path)) list = validDirMap[path]; foreach (string file in results) { if (!(validFiles.Contains(file) || (list != null && list.Contains(file)))) { Log.Exception("Unexpected file found: " + file); valid = false; } cnt++; } valid &= cnt == expected; return valid; } private bool TestGetFilesEnum(int expected, params string[] nodes) { return VerifyEnum(expected, Directory.EnumerateFiles(GetPath(nodes))); } private bool VerifyEnum(int expected, IEnumerable results) { int cnt = 0; bool valid = true; foreach (string file in results) { if (!validFiles.Contains(file)) { Log.Exception("Unexpected file found: " + file); valid = false; } cnt++; } valid &= cnt == expected; return valid; } private bool TestGetFiles(int expected, params string[] nodes) { return Verify(expected, Directory.GetFiles(GetPath(nodes))); } private bool Verify(int expected, string[] results) { bool valid = true; Log.Comment("Got " + StrArrayToStr(results)); if (results.Length != expected) { Log.Exception("Expected " + expected + " files, got " + results.Length); valid = false; } foreach (string file in results) { if (!validFiles.Contains(file)) { Log.Exception("Unexpected file found: " + file); valid = false; } } return valid; } private string GetPath(string[] nodes) { string path = ""; if (nodes.Length > 0) { path = nodes[0]; for (int i = 1; i < nodes.Length; i++) { path += "\\" + nodes[i]; } } Log.Comment("Path: " + path); return path; } private string RandFileName(int length) { char[] chars = new char[length]; Random random = new Random(); for (int i = 0; i < length; i++) { switch (random.Next(4)) { // 0 = specal chars case 0: int x = random.Next(special.Length); chars[i] = special[x]; break; // 1 = numbers case 1: chars[i] = (char)((int)'0' + random.Next(10)); break; // 2 = upper case case 2: chars[i] = (char)((int)'A' + random.Next(26)); break; // 3 = lower case case 3: chars[i] = (char)((int)'a' + random.Next(26)); break; default: throw new ArgumentException("Expected 0-3"); } } return new string(chars); } #endregion Helper functions #region Test Cases [TestMethod] public MFTestResults InvalidArguments() { string[] dirs; MFTestResults result = MFTestResults.Pass; try { // null cases try { Log.Comment("Null"); dirs = Directory.GetFiles(null); Log.Exception( "Expected ArgumentNullException, but got " + StrArrayToStr( dirs ) ); return MFTestResults.Fail; } catch (ArgumentNullException ane) { /* pass case */ Log.Comment( "Got correct exception: " + ane.Message ); result = MFTestResults.Pass; } // string.empty cases try { Log.Comment("String.Empty"); dirs = Directory.GetFiles(String.Empty); Log.Exception( "Expected ArgumentException, but got " + StrArrayToStr( dirs ) ); return MFTestResults.Fail; } catch (ArgumentException ae) { /* pass case */ Log.Comment( "Got correct exception: " + ae.Message ); result = MFTestResults.Pass; } // whitespace cases try { Log.Comment("White Space"); dirs = Directory.GetFiles(" "); Log.Exception( "Expected ArgumentException, but got " + StrArrayToStr( dirs ) ); return MFTestResults.Fail; } catch (ArgumentException ae1) { /* pass case */ Log.Comment( "Got correct exception: " + ae1.Message ); result = MFTestResults.Pass; } // New lines try { Log.Comment("\\n"); dirs = Directory.GetFiles("\n"); Log.Exception( "Expected ArgumentException, but got " + StrArrayToStr( dirs ) ); return MFTestResults.Fail; } catch (ArgumentException ae2) { /* pass case */ Log.Comment( "Got correct exception: " + ae2.Message ); result = MFTestResults.Pass; } // Filter as path try { Log.Comment("*"); dirs = Directory.GetFiles("*"); Log.Exception( "Expected ArgumentException, but got " + StrArrayToStr( dirs ) ); return MFTestResults.Fail; } catch(ArgumentException ae3) { /* pass case */ Log.Comment( "Got correct exception: " + ae3.Message ); result = MFTestResults.Pass; } } catch (Exception ex) { Log.Exception("Unexpected exception: " + ex.Message); return MFTestResults.Fail; } return result; } [TestMethod] public MFTestResults ValidCasesNoFilter() { MFTestResults result = MFTestResults.Pass; try { // relative Directory.SetCurrentDirectory(IOTests.Volume.RootDirectory); if (!TestGetFiles(0, ".")) return MFTestResults.Fail; if (!TestGetFiles(0, TestDir)) return MFTestResults.Fail; if (!TestGetFiles(0, TestDir, Mid1)) return MFTestResults.Fail; if (!TestGetFiles(4, TestDir, Mid1, Tail1)) return MFTestResults.Fail; if (!TestGetFiles(1, TestDir, Mid1, Tail2)) return MFTestResults.Fail; if (!TestGetFiles(3, TestDir, Mid2)) return MFTestResults.Fail; if (!TestGetFiles(2, TestDir, Mid2, Tail1)) return MFTestResults.Fail; if (!TestGetFiles(2, TestDir, Mid1, ".", Tail1, "..", Tail1, "..", "..", Mid2, Tail1)) return MFTestResults.Fail; // Move up tree where there is more directories Directory.SetCurrentDirectory(TestDir + "\\" + Mid2); if (!TestGetFiles(3, ".")) return MFTestResults.Fail; if (!TestGetFiles(0, "..")) return MFTestResults.Fail; // absolute if (!TestGetFiles(4, IOTests.Volume.RootDirectory, TestDir, Mid1, Tail1)) return MFTestResults.Fail; if (!TestGetFiles(2, IOTests.Volume.RootDirectory, TestDir, Mid2, Tail1)) return MFTestResults.Fail; if (!TestGetFiles(3, IOTests.Volume.RootDirectory, TestDir, Mid2)) return MFTestResults.Fail; if (!TestGetFiles(0, IOTests.Volume.RootDirectory, TestDir, Mid1)) return MFTestResults.Fail; if (!TestGetFiles(0, IOTests.Volume.RootDirectory, TestDir)) return MFTestResults.Fail; if (!TestGetFiles(0, IOTests.Volume.RootDirectory)) return MFTestResults.Fail; if (!TestGetFiles(2, IOTests.Volume.RootDirectory, TestDir, Mid1, ".", Tail1, "..", Tail1, "..", "..", Mid2, Tail1, ".")) return MFTestResults.Fail; } catch (Exception ex) { Log.Exception("Unexpected exception: " + ex.Message); return MFTestResults.Fail; } return result; } [TestMethod] public MFTestResults GetFilesEnum() { MFTestResults result = MFTestResults.Pass; try { // relative Directory.SetCurrentDirectory(IOTests.Volume.RootDirectory); if (!TestGetFilesEnum(0, ".")) return MFTestResults.Fail; if (!TestGetFilesEnum(0, TestDir)) return MFTestResults.Fail; if (!TestGetFilesEnum(0, TestDir, Mid1)) return MFTestResults.Fail; if (!TestGetFilesEnum(4, TestDir, Mid1, Tail1)) return MFTestResults.Fail; if (!TestGetFilesEnum(1, TestDir, Mid1, Tail2)) return MFTestResults.Fail; if (!TestGetFilesEnum(3, TestDir, Mid2)) return MFTestResults.Fail; if (!TestGetFilesEnum(2, TestDir, Mid2, Tail1)) return MFTestResults.Fail; if (!TestGetFilesEnum(2, TestDir, Mid1, ".", Tail1, "..", Tail1, "..", "..", Mid2, Tail1)) return MFTestResults.Fail; // Move up tree where there is more directories Directory.SetCurrentDirectory(TestDir + "\\" + Mid2); if (!TestGetFilesEnum(3, ".")) return MFTestResults.Fail; if (!TestGetFilesEnum(0, "..")) return MFTestResults.Fail; // absolute if (!TestGetFilesEnum(4, IOTests.Volume.RootDirectory, TestDir, Mid1, Tail1)) return MFTestResults.Fail; if (!TestGetFilesEnum(2, IOTests.Volume.RootDirectory, TestDir, Mid2, Tail1)) return MFTestResults.Fail; if (!TestGetFilesEnum(3, IOTests.Volume.RootDirectory, TestDir, Mid2)) return MFTestResults.Fail; if (!TestGetFilesEnum(0, IOTests.Volume.RootDirectory, TestDir, Mid1)) return MFTestResults.Fail; if (!TestGetFilesEnum(0, IOTests.Volume.RootDirectory, TestDir)) return MFTestResults.Fail; if (!TestGetFilesEnum(0, IOTests.Volume.RootDirectory)) return MFTestResults.Fail; if (!TestGetFilesEnum(2, IOTests.Volume.RootDirectory, TestDir, Mid1, ".", Tail1, "..", Tail1, "..", "..", Mid2, Tail1, ".")) return MFTestResults.Fail; } catch (Exception ex) { Log.Exception("Unexpected exception: " + ex.Message); return MFTestResults.Fail; } return result; } [TestMethod] public MFTestResults GetFilesAndDirectoriesEnum() { MFTestResults result = MFTestResults.Pass; try { // relative Directory.SetCurrentDirectory(IOTests.Volume.RootDirectory); if (!TestGetFilesAndDirsEnum(1, ".")) return MFTestResults.Fail; if (!TestGetFilesAndDirsEnum(2, TestDir)) return MFTestResults.Fail; if (!TestGetFilesAndDirsEnum(2, TestDir, Mid1)) return MFTestResults.Fail; if (!TestGetFilesAndDirsEnum(4, TestDir, Mid1, Tail1)) return MFTestResults.Fail; if (!TestGetFilesAndDirsEnum(1, TestDir, Mid1, Tail2)) return MFTestResults.Fail; if (!TestGetFilesAndDirsEnum(4, TestDir, Mid2)) return MFTestResults.Fail; if (!TestGetFilesAndDirsEnum(2, TestDir, Mid2, Tail1)) return MFTestResults.Fail; if (!TestGetFilesAndDirsEnum(2, TestDir, Mid1, ".", Tail1, "..", Tail1, "..", "..", Mid2, Tail1)) return MFTestResults.Fail; // Move up tree where there is more directories Directory.SetCurrentDirectory(TestDir + "\\" + Mid2); if (!TestGetFilesAndDirsEnum(4, ".")) return MFTestResults.Fail; if (!TestGetFilesAndDirsEnum(2, "..")) return MFTestResults.Fail; // absolute if (!TestGetFilesAndDirsEnum(4, IOTests.Volume.RootDirectory, TestDir, Mid1, Tail1)) return MFTestResults.Fail; if (!TestGetFilesAndDirsEnum(2, IOTests.Volume.RootDirectory, TestDir, Mid2, Tail1)) return MFTestResults.Fail; if (!TestGetFilesAndDirsEnum(4, IOTests.Volume.RootDirectory, TestDir, Mid2)) return MFTestResults.Fail; if (!TestGetFilesAndDirsEnum(2, IOTests.Volume.RootDirectory, TestDir, Mid1)) return MFTestResults.Fail; if (!TestGetFilesAndDirsEnum(2, IOTests.Volume.RootDirectory, TestDir)) return MFTestResults.Fail; if (!TestGetFilesAndDirsEnum(1, IOTests.Volume.RootDirectory)) return MFTestResults.Fail; if (!TestGetFilesAndDirsEnum(2, IOTests.Volume.RootDirectory, TestDir, Mid1, ".", Tail1, "..", Tail1, "..", "..", Mid2, Tail1, ".")) return MFTestResults.Fail; } catch (Exception ex) { Log.Exception("Unexpected exception: " + ex.Message); return MFTestResults.Fail; } return result; } [TestMethod] private MFTestResults RandomFileNames() { MFTestResults result = MFTestResults.Pass; try { Log.Comment("Light stress with 100 random file names"); Random random = new Random(); string randdir = IOTests.Volume.RootDirectory + "\\" + TestDir + "\\RandomFileNames"; Directory.CreateDirectory(randdir); for (int i = 0; i < 100; i++) { AddFile(randdir + "\\" + i + "_" + RandFileName(random.Next(100))); } if (!TestGetFiles(100, randdir)) return MFTestResults.Fail; } catch (Exception ex) { Log.Exception("Unexpected exception: " + ex.Message); return MFTestResults.Fail; } return result; } [TestMethod] public MFTestResults SpecialFileNames() { MFTestResults result = MFTestResults.Pass; try { Log.Comment("Find file each with special char file names"); string specialdir = IOTests.Volume.RootDirectory + "\\" + TestDir + "\\SpecialFileNames"; Directory.CreateDirectory(specialdir); for (int i = 0; i < special.Length; i++) { string file = i + "_" + new string(new char[] { special[i] }) + "_z.file"; AddFile(specialdir + "\\" + file); } if (!TestGetFiles(special.Length, specialdir)) return MFTestResults.Fail; } catch (Exception ex) { Log.Exception("Unexpected exception: " + ex.Message); return MFTestResults.Fail; } return result; } #endregion Test Cases public MFTestMethod[] Tests { get { return new MFTestMethod[] { new MFTestMethod( InvalidArguments, "InvalidArguments" ), new MFTestMethod( ValidCasesNoFilter, "ValidCasesNoFilter" ), new MFTestMethod( GetFilesEnum, "GetFilesEnum" ), new MFTestMethod( GetFilesAndDirectoriesEnum, "GetFilesAndDirectoriesEnum" ), new MFTestMethod( SpecialFileNames, "SpecialFileNames" ), }; } } } } ================================================ FILE: Zelig/Zelig/FileSystemTest/Directory/GetSetCurrentDirectory.cs ================================================ //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // Copyright (c) Microsoft Corporation. All rights reserved. //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// using System; using System.IO; namespace FileSystemTest { public class GetSetCurrentDirectory : IMFTestInterface { [SetUp] public InitializeResult Initialize() { // These tests rely on underlying file system so we need to make // sure we can format it before we start the tests. If we can't // format it, then we assume there is no FS to test on this platform. // delete the directory DOTNETMF_FS_EMULATION try { IOTests.IntializeVolume(); Directory.CreateDirectory(TestDir + "\\" + Mid1 + "\\" + Tail1); Directory.CreateDirectory(TestDir + "\\" + Mid1 + "\\" + Tail2); Directory.CreateDirectory(TestDir + "\\" + Mid2 + "\\" + Tail1); Directory.CreateDirectory(TestDir + "\\" + Mid2 + "\\" + Tail2); } catch (Exception ex) { Log.Comment("Skipping: Unable to initialize file system" + ex.Message); return InitializeResult.Skip; } return InitializeResult.ReadyToGo; } [TearDown] public void CleanUp() { } #region local vars private const string TestDir = "ExistsDirectory"; private const string Mid1 = "Mid1"; private const string Mid2 = "Mid2"; private const string Tail1 = "Tail1"; private const string Tail2 = "Tail2"; #endregion local vars #region Helper functions private bool TestGetSet(params string[] nodes) { string path = ""; if (nodes.Length > 0) { path = nodes[0]; for (int i = 1; i < nodes.Length; i++) { path += "\\" + nodes[i]; } } string expected = NormalizePath(path); Log.Comment("Changing path to " + path); Directory.SetCurrentDirectory(path); string result = Directory.GetCurrentDirectory(); if (result != expected) { Log.Exception("Set failed. Current directory is " + result); Log.Exception("Expected " + expected); return false; } return true; } private string NormalizePath(string newpath) { // Not rooted - get full path from Relative if (!(newpath.Substring(0, 1) == @"\")) { newpath = Directory.GetCurrentDirectory() + @"\" + newpath; } string path = ""; int skipCount = 0; string[] nodes = newpath.Split('\\'); // first node is always empty since we are rooted, so stop at 2nd node (i=1) for (int i = nodes.Length - 1; i > 0; i--) { // Drop . nodes (current) if (!(nodes[i] == ".")) { if (nodes[i] == "..") { skipCount++; } else { if (skipCount == 0) //append node path = @"\" + nodes[i] + path; else //skip node skipCount--; } } } return path; } #endregion Helper functions #region Test Cases [TestMethod] public MFTestResults GetSetRelative() { MFTestResults result = MFTestResults.Pass; try { Directory.SetCurrentDirectory(IOTests.Volume.RootDirectory); Log.Comment("Walk tree using relative path"); if (!TestGetSet(TestDir)) return MFTestResults.Fail; if (!TestGetSet(Mid1)) return MFTestResults.Fail; if (!TestGetSet(Tail1)) return MFTestResults.Fail; if (!TestGetSet(".")) return MFTestResults.Fail; if (!TestGetSet("..")) return MFTestResults.Fail; if (!TestGetSet(Tail2)) return MFTestResults.Fail; if (!TestGetSet(@"..\..")) return MFTestResults.Fail; if (!TestGetSet(Mid2, Tail2)) return MFTestResults.Fail; if (!TestGetSet(@"..\..\..")) return MFTestResults.Fail; // Complex path, should result in path to Tail2 if (!TestGetSet(TestDir, ".", Mid2, "..", Mid2, ".", Tail2)) return MFTestResults.Fail; if (!TestGetSet("..", "..", Mid1, Tail1)) return MFTestResults.Fail; } catch (Exception ex) { Log.Exception("Unexpected exception: " + ex.Message); return MFTestResults.Fail; } return result; } [TestMethod] public MFTestResults GetSetAboslute() { MFTestResults result = MFTestResults.Pass; try { Log.Comment("Walk tree using absolute path"); if (!TestGetSet(IOTests.Volume.RootDirectory, TestDir)) return MFTestResults.Fail; if (!TestGetSet(IOTests.Volume.RootDirectory, TestDir, Mid1)) return MFTestResults.Fail; if (!TestGetSet(IOTests.Volume.RootDirectory, TestDir, Mid2, Tail2)) return MFTestResults.Fail; if (!TestGetSet(IOTests.Volume.RootDirectory, TestDir, ".")) return MFTestResults.Fail; if (!TestGetSet(IOTests.Volume.RootDirectory, TestDir, "..")) return MFTestResults.Fail; if (!TestGetSet(IOTests.Volume.RootDirectory, TestDir, Mid2, Tail2, @"..\..", Mid2, Tail2)) return MFTestResults.Fail; // Complex path, should result in path to Tail2 if (!TestGetSet(IOTests.Volume.RootDirectory, TestDir, ".", Mid2, "..", Mid2, ".", Tail2)) return MFTestResults.Fail; if (!TestGetSet(IOTests.Volume.RootDirectory)) return MFTestResults.Fail; } catch (Exception ex) { Log.Exception("Unexpected exception: " + ex.Message); return MFTestResults.Fail; } return result; } [TestMethod] public MFTestResults InvalidArgs() { MFTestResults result = MFTestResults.Pass; try { try { Log.Comment("null"); Directory.SetCurrentDirectory(null); Log.Exception( "Expected ArgumentNullException got " + Directory.GetCurrentDirectory() ); return MFTestResults.Fail; } catch(ArgumentNullException ane) { /* pass case */ Log.Comment( "Got correct exception: " + ane.Message ); result = MFTestResults.Pass; } try { Log.Comment("String.Empty"); Directory.SetCurrentDirectory(string.Empty); Log.Exception( "Expected ArgumentException got " + Directory.GetCurrentDirectory() ); return MFTestResults.Fail; } catch(ArgumentException ae) { /* pass case */ Log.Comment( "Got correct exception: " + ae.Message ); result = MFTestResults.Pass; } try { Log.Comment("Whitespace"); Directory.SetCurrentDirectory(" "); Log.Exception( "Expected ArgumentException got " + Directory.GetCurrentDirectory() ); return MFTestResults.Fail; } catch(ArgumentException ae1) { /* pass case */ Log.Comment( "Got correct exception: " + ae1.Message ); result = MFTestResults.Pass; } } catch (Exception ex) { Log.Exception("Unexpected exception: " + ex.Message); return MFTestResults.Fail; } return result; } [TestMethod] public MFTestResults InvalidCases() { MFTestResults result = MFTestResults.Pass; try { try { Log.Comment("NonExistentDir"); Directory.SetCurrentDirectory("NonExistentDir"); Log.Exception( "Expected ArgumentException got " + Directory.GetCurrentDirectory() ); return MFTestResults.Fail; } catch(IOException ioe) { /* pass case, DirectoryNotFound */ Log.Comment( "Got correct exception: " + ioe.Message ); } try { Log.Comment(@"non exist mount \foo"); Directory.SetCurrentDirectory(@"\foo"); Log.Exception( "Expected ArgumentException got " + Directory.GetCurrentDirectory() ); return MFTestResults.Fail; } catch(IOException ioe1) { /* pass case */ Log.Comment( "Got correct exception: " + ioe1.Message ); result = MFTestResults.Pass; } try { Log.Comment(@"Move before root - ..\..\..\..\.."); Directory.SetCurrentDirectory(@"..\..\..\..\.."); Log.Exception( "Expected ArgumentException got " + Directory.GetCurrentDirectory() ); return MFTestResults.Fail; } catch(ArgumentException ae) { /* pass case */ Log.Comment( "Got correct exception: " + ae.Message ); result = MFTestResults.Pass; } } catch (Exception ex) { Log.Exception("Unexpected exception: " + ex.Message); return MFTestResults.Fail; } return result; } #endregion Test Cases public MFTestMethod[] Tests { get { return new MFTestMethod[] { new MFTestMethod( GetSetRelative, "GetSetRelative" ), new MFTestMethod( GetSetAboslute, "GetSetAboslute" ), new MFTestMethod( InvalidArgs, "InvalidArgs" ), new MFTestMethod( InvalidCases, "InvalidCases" ), }; } } } } ================================================ FILE: Zelig/Zelig/FileSystemTest/Directory/Move.cs ================================================ //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // Copyright (c) Microsoft Corporation. All rights reserved. //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// using System; using System.Collections; using System.IO; using System.Collections.Generic; namespace FileSystemTest { public class Move : IMFTestInterface { [SetUp] public InitializeResult Initialize() { // These tests rely on underlying file system so we need to make // sure we can format it before we start the tests. If we can't // format it, then we assume there is no FS to test on this platform. // delete the directory DOTNETMF_FS_EMULATION try { IOTests.IntializeVolume(); AddDir(IOTests.Volume.RootDirectory + "\\" + TestDir1 + "\\" + Mid1 + "\\" + Tail1); AddDir(IOTests.Volume.RootDirectory + "\\" + TestDir1 + "\\" + Mid1 + "\\" + Tail2); AddDir(IOTests.Volume.RootDirectory + "\\" + TestDir1 + "\\" + Mid2 + "\\" + Tail1); AddDir(IOTests.Volume.RootDirectory + "\\" + TestDir2); } catch (Exception ex) { Log.Exception("Skipping: Unable to initialize file system", ex); return InitializeResult.Skip; } return InitializeResult.ReadyToGo; } [TearDown] public void CleanUp() { } #region local vars private List validDirs = new List(); private const string TestDir1 = "MoveDirectory1"; private const string TestDir2 = "MoveDirectory2"; private const string TestDir3 = "MoveDirectory3"; private const string Mid1 = "Mid1"; private const string Mid2 = "Mid2"; private const string Tail1 = "Tail1"; private const string Tail2 = "Tail2"; #endregion local vars #region Helper functions private void AddDir(string path) { Log.Comment("Adding Directory: " + path); try { path = Path.GetFullPath(path); if (!validDirs.Contains(path)) { // create full path Directory.CreateDirectory(path); while (!validDirs.Contains(path) & path != @"\") { validDirs.Add(path); path = Path.GetFullPath(path + @"\.."); } } } catch { Log.Exception("Failed to create directory"); } } private string GetPath(params string[] nodes) { string path = ""; if (nodes.Length > 0) { path = nodes[0]; for (int i = 1; i < nodes.Length; i++) { path += "\\" + nodes[i]; } } return path; } private string StrArrayToStr(string[] list) { string result = ""; foreach (string item in list) { result += item + ", "; } return result.TrimEnd(',', ' '); } private int CountChildern(string path) { int count = 0; string[] childern = Directory.GetDirectories(Path.GetFullPath(path)); count += childern.Length; foreach (string child in childern) { count += CountChildern(child); } return count; } private bool TestMove(string source, string destination) { bool success = true; int sourceChildren = CountChildern(source); Log.Comment("Source: " + source); Log.Comment("Destination: " + destination); Log.Comment("Children: " + sourceChildren); // Move Directory.Move(source, destination); if (Directory.Exists(source)) { Log.Exception("Old directory not gone - " + source); success = false; } if (!Directory.Exists(destination)) { Log.Exception("Source not found at destination - " + destination); return false; } // verify children int destChildren = CountChildern(destination); if (sourceChildren != destChildren) { Log.Exception("Lost children! Destination Children: " + destChildren); return false; } return success; } #endregion Helper functions #region Test Cases [TestMethod] public MFTestResults InvalidArguments() { MFTestResults result = MFTestResults.Pass; try { // null cases string localdir = Directory.GetCurrentDirectory(); try { Log.Comment("Null, local"); Directory.Move(null, localdir); Log.Exception( "Expected ArgumentNullException" ); return MFTestResults.Fail; } catch(ArgumentNullException ane) { /* pass case */ Log.Comment( "Got correct exception: " + ane.Message ); result = MFTestResults.Pass; } try { Log.Comment("local, Null"); Directory.Move(localdir, null); Log.Exception( "Expected ArgumentNullException" ); return MFTestResults.Fail; } catch(ArgumentNullException ane1) { /* pass case */ Log.Comment( "Got correct exception: " + ane1.Message ); result = MFTestResults.Pass; } // string.empty cases try { Log.Comment("String.Empty, local"); Directory.Move(String.Empty, localdir); Log.Exception( "Expected ArgumentException" ); return MFTestResults.Fail; } catch(ArgumentException ae) { /* pass case */ Log.Comment( "Got correct exception: " + ae.Message ); result = MFTestResults.Pass; } try { Log.Comment("local, String.Empty"); Directory.Move(localdir, String.Empty); Log.Exception( "Expected ArgumentException" ); return MFTestResults.Fail; } catch(ArgumentException ae1) { /* pass case */ Log.Comment( "Got correct exception: " + ae1.Message ); result = MFTestResults.Pass; } // whitespace cases try { Log.Comment("White Space, Local"); Directory.Move(" ", localdir); Log.Exception( "Expected ArgumentException" ); return MFTestResults.Fail; } catch(ArgumentException ae2) { /* pass case */ Log.Comment( "Got correct exception: " + ae2.Message ); result = MFTestResults.Pass; } try { Log.Comment("local, White Space"); Directory.Move(localdir, " "); Log.Exception( "Expected ArgumentException" ); return MFTestResults.Fail; } catch(ArgumentException ae3) { /* pass case */ Log.Comment( "Got correct exception: " + ae3.Message ); result = MFTestResults.Pass; } // Non-existant dirs try { Log.Comment("Nonexistent, Local"); Directory.Move("Nonexistent", localdir); Log.Exception( "Expected IOException" ); return MFTestResults.Fail; } catch (IOException io) { /* pass case - Directory not found */ Log.Comment( "Got correct exception: " + io.Message ); result = MFTestResults.Pass; } try { Log.Comment("local, Nonexistent"); Directory.Move(localdir, "Nonexistent"); Log.Exception( "Expected IOException" ); return MFTestResults.Fail; } catch(IOException ioe1) { /* pass case - Directory not found */ Log.Comment( "Got correct exception: " + ioe1.Message ); result = MFTestResults.Pass; } // wildchar in directory try { Log.Comment("TestDir, *"); Directory.Move(TestDir1, "*"); Log.Exception( "Expected ArgumentException" ); return MFTestResults.Fail; } catch(ArgumentException ae4) { /* pass case */ Log.Comment( "Got correct exception: " + ae4.Message ); result = MFTestResults.Pass; } try { Log.Comment("*, TestDir"); Directory.Move("*", TestDir1); Log.Exception( "Expected ArgumentException" ); return MFTestResults.Fail; } catch(ArgumentException ae5) { /* pass case */ Log.Comment( "Got correct exception: " + ae5.Message ); result = MFTestResults.Pass; } // Move parent Dir try { Log.Comment(".., TestDir"); Directory.Move("..", TestDir1); Log.Exception( "Expected IOException" ); return MFTestResults.Fail; } catch(IOException io2) { /* pass case */ Log.Comment( "Got correct exception: " + io2.Message ); result = MFTestResults.Pass; } } catch (Exception ex) { Log.Exception("Unexpected exception: " + ex.Message); return MFTestResults.Fail; } return result; } [TestMethod] public MFTestResults TailRename() { MFTestResults result = MFTestResults.Pass; try { Log.Comment("rename Tail1 to Tail2"); if (!TestMove(GetPath(IOTests.Volume.RootDirectory, TestDir1, Mid2, Tail1), GetPath(IOTests.Volume.RootDirectory, TestDir1, Mid2, Tail2))) return MFTestResults.Fail; Log.Comment("move Back"); if (!TestMove(GetPath(IOTests.Volume.RootDirectory, TestDir1, Mid2, Tail2), GetPath(IOTests.Volume.RootDirectory, TestDir1, Mid2, Tail1))) return MFTestResults.Fail; } catch (Exception ex) { Log.Exception("Unexpected exception: " + ex.Message); return MFTestResults.Fail; } return result; } [TestMethod] public MFTestResults TopRename() { MFTestResults result = MFTestResults.Pass; try { Log.Comment("rename TestDir1 to TestDir3"); if (!TestMove(GetPath(IOTests.Volume.RootDirectory, TestDir1), GetPath(IOTests.Volume.RootDirectory, TestDir3))) return MFTestResults.Fail; Log.Comment("move Back"); if (!TestMove(GetPath(IOTests.Volume.RootDirectory, TestDir3), GetPath(IOTests.Volume.RootDirectory, TestDir1))) return MFTestResults.Fail; } catch (Exception ex) { Log.Exception("Unexpected exception: " + ex.Message); return MFTestResults.Fail; } return result; } [TestMethod] public MFTestResults TailMoveRoot() { MFTestResults result = MFTestResults.Pass; try { Log.Comment("move root Tail1 to TestDir2"); if (!TestMove(GetPath(IOTests.Volume.RootDirectory, TestDir1, Mid1, Tail1), GetPath(IOTests.Volume.RootDirectory, TestDir2, Tail1))) return MFTestResults.Fail; Log.Comment("move Back"); if (!TestMove(GetPath(IOTests.Volume.RootDirectory, TestDir2, Tail1), GetPath(IOTests.Volume.RootDirectory, TestDir1, Mid1, Tail1))) return MFTestResults.Fail; } catch (Exception ex) { Log.Exception("Unexpected exception: " + ex.Message); return MFTestResults.Fail; } return result; } [TestMethod] public MFTestResults TopMoveRoot() { MFTestResults result = MFTestResults.Pass; try { Log.Comment("move root TestDir1 to TestDir2"); if (!TestMove(GetPath(IOTests.Volume.RootDirectory, TestDir1), GetPath(IOTests.Volume.RootDirectory, TestDir2, TestDir1))) return MFTestResults.Fail; Log.Comment("move back"); if (!TestMove(GetPath(IOTests.Volume.RootDirectory, TestDir2, TestDir1), GetPath(IOTests.Volume.RootDirectory, TestDir1))) return MFTestResults.Fail; } catch (Exception ex) { Log.Exception("Unexpected exception: " + ex.Message); return MFTestResults.Fail; } return result; } #endregion Test Cases public MFTestMethod[] Tests { get { return new MFTestMethod[] { new MFTestMethod( InvalidArguments, "InvalidArguments" ), new MFTestMethod( TailRename, "TailRename" ), new MFTestMethod( TopRename, "TopRename" ), new MFTestMethod( TailMoveRoot, "TailMoveRoot" ), new MFTestMethod( TopMoveRoot, "TopMoveRoot" ), }; } } } } ================================================ FILE: Zelig/Zelig/FileSystemTest/File/Copy.cs ================================================ //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // Copyright (c) Microsoft Corporation. All rights reserved. //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// using System; using System.IO; namespace FileSystemTest { public class Copy : IMFTestInterface { [SetUp] public InitializeResult Initialize() { Log.Comment("Adding set up for the tests."); try { IOTests.IntializeVolume(); Directory.CreateDirectory(sourceDir); Directory.CreateDirectory(destDir); Directory.SetCurrentDirectory(sourceDir); file1 = new FileInfo(file1Name); file2 = new FileInfo(file2Name); } catch (Exception ex) { Log.Comment("Skipping: Unable to initialize file system" + ex.Message); return InitializeResult.Skip; } // Add your functionality here. return InitializeResult.ReadyToGo; } [TearDown] public void CleanUp() { Log.Comment("Cleaning up after the tests."); // TODO: Add your clean up steps here. } #region Local vars private const string file1Name = "file1.tmp"; private const string file2Name = "file2.txt"; private const string sourceDir = "source"; private const string destDir = "destination"; private FileInfo file1; private FileInfo file2; #endregion Local vars #region Helper methods private bool TestCopy(string source, string destination) { bool success = true; Log.Comment("Copy " + source + " to " + destination); try { success = CreateFile(source); if (success) { File.Copy(source, destination); if (!VerifyExist(source)) success = false; if (!VerifyExist(destination)) success = false; } else { Log.Exception("Unable to create file!"); } } finally { File.Delete(source); File.Delete(destination); } return success; } private bool TestCopy(string source, string destination, bool overwrite) { bool success = true; Log.Comment("Copy " + source + " to " + destination + " with overwrite " + overwrite); try { success = CreateFile(source); success = CreateFile(destination); if (success) { try { File.Copy(source, destination, overwrite); } catch (IOException ex) { if (overwrite) { Log.Exception("Unexpected exception when overwrite set to true"); throw ex; } } success = VerifyExist(source); success = VerifyExist(destination); } else { Log.Exception("Unable to create file!"); } } finally { File.Delete(source); File.Delete(destination); } return success; } private bool CreateFile(string file) { File.Create(file).Close(); return VerifyExist(file); } private bool VerifyExist(string file) { FileInfo fileinfo = new FileInfo(file); if (fileinfo.Exists) return true; Log.Exception("File does not exist: " + file); return false; } #endregion Helper methods #region Test Cases [TestMethod] public MFTestResults ArgumentExceptionTests() { MFTestResults result = MFTestResults.Pass; try { Log.Comment(Directory.GetCurrentDirectory()); try { File.Create(file1Name).Close(); Log.Comment("Null Source Constructor"); File.Copy(null, file2.Name); Log.Exception( "Expected ArgumentException" ); return MFTestResults.Fail; } catch(ArgumentException ae) { /* pass case */ Log.Comment( "Got correct exception: " + ae.Message ); result = MFTestResults.Pass; } finally { File.Delete(file1Name); } try { File.Create(file1Name).Close(); Log.Comment("Null Destination Constructor"); File.Copy(file1.Name, null); Log.Exception( "Expected ArgumentException" ); return MFTestResults.Fail; } catch(ArgumentException ae1) { /* pass case */ Log.Comment( "Got correct exception: " + ae1.Message ); result = MFTestResults.Pass; } finally { File.Delete(file1Name); } try { File.Create(file1Name).Close(); Log.Comment("String.Empty Source Constructor"); File.Copy(string.Empty, file2.Name); Log.Exception( "Expected ArgumentException" ); return MFTestResults.Fail; } catch(ArgumentException ae2) { /* pass case */ Log.Comment( "Got correct exception: " + ae2.Message ); result = MFTestResults.Pass; } finally { File.Delete(file1Name); } try { File.Create(file1Name).Close(); Log.Comment("String.Empty Destination Constructor"); File.Copy(file1.Name, string.Empty); Log.Exception( "Expected ArgumentException" ); return MFTestResults.Fail; } catch(ArgumentException ae3) { /* pass case */ Log.Comment( "Got correct exception: " + ae3.Message ); result = MFTestResults.Pass; } finally { File.Delete(file1Name); } try { File.Create(file1Name).Close(); Log.Comment("Whitespace Source Constructor"); File.Copy(" ", file2.Name); Log.Exception( "Expected ArgumentException" ); return MFTestResults.Fail; } catch(ArgumentException ae4) { /* pass case */ Log.Comment( "Got correct exception: " + ae4.Message ); result = MFTestResults.Pass; } finally { File.Delete(file1Name); } try { File.Create(file1Name).Close(); Log.Comment("Whitespace Destination Constructor"); File.Copy(file1.Name, " "); Log.Exception( "Expected ArgumentException" ); return MFTestResults.Fail; } catch(ArgumentException ae5) { /* pass case */ Log.Comment( "Got correct exception: " + ae5.Message ); result = MFTestResults.Pass; } finally { File.Delete(file1Name); } } catch (Exception ex) { Log.Exception("Unexpected exception: " + ex.Message); return MFTestResults.Fail; } return result; } [TestMethod] public MFTestResults IOExceptionTests() { MFTestResults result = MFTestResults.Pass; try { try { File.Create(file1Name).Close(); Log.Comment("Relative Copy to '.'"); File.Copy(file1Name, "."); Log.Exception( "Expected IOException" ); return MFTestResults.Fail; } catch (IOException ioe) { /* pass case */ Log.Comment( "Got correct exception: " + ioe.Message ); result = MFTestResults.Pass; } /// We throw System.Exception with error code access_denied. finally { File.Delete(file1Name); } try { File.Create(file1.FullName).Close(); Log.Comment("Absolute Copy to '.'"); File.Copy(file1.FullName, "."); Log.Exception( "Expected IOException" ); return MFTestResults.Fail; } catch (IOException ioe) { /* pass case */ Log.Comment( "Got correct exception: " + ioe.Message ); result = MFTestResults.Pass; } finally { File.Delete(file1.FullName); } try { File.Create(file1Name).Close(); Log.Comment("Relative Copy to Directory"); File.Copy(file1Name, Path.Combine(IOTests.Volume.RootDirectory, sourceDir)); Log.Exception( "Expected IOException" ); return MFTestResults.Fail; } catch (IOException ioe) { /* pass case */ Log.Comment( "Got correct exception: " + ioe.Message ); result = MFTestResults.Pass; } finally { File.Delete(file1Name); } try { File.Create(file1.FullName).Close(); Log.Comment("Absolute Copy to Directory"); File.Copy(file1.FullName, Path.Combine(IOTests.Volume.RootDirectory, sourceDir)); Log.Exception( "Expected IOException" ); return MFTestResults.Fail; } catch (IOException ioe) { /* pass case */ Log.Comment( "Got correct exception: " + ioe.Message ); result = MFTestResults.Pass; } finally { File.Delete(file1.FullName); } try { File.Create(file1Name).Close(); Log.Comment("Relative Copy to self"); File.Copy(file1Name, file1Name); Log.Exception( "Expected IOException" ); return MFTestResults.Fail; } catch (IOException ioe) { /* pass case */ Log.Comment( "Got correct exception: " + ioe.Message ); result = MFTestResults.Pass; } finally { File.Delete(file1Name); } try { File.Create(file1.FullName).Close(); Log.Comment("Absolute Copy to self"); File.Copy(file1.FullName, file1.FullName); Log.Exception( "Expected IOException" ); return MFTestResults.Fail; } catch (IOException ioe) { /* pass case */ Log.Comment( "Got correct exception: " + ioe.Message ); result = MFTestResults.Pass; } finally { File.Delete(file1.FullName); } } catch (Exception ex) { Log.Exception("Unexpected exception: " + ex.Message); return MFTestResults.Fail; } return result; } [TestMethod] public MFTestResults ValidCases() { MFTestResults result = MFTestResults.Pass; string rootedSrcDir = Path.Combine(IOTests.Volume.RootDirectory, sourceDir); string rootedDstDir = Path.Combine(IOTests.Volume.RootDirectory, destDir); string file1Dir1 = Path.Combine(rootedSrcDir, file1Name); string file1Dir2 = Path.Combine(rootedDstDir, file1Name); string file2Dir1 = Path.Combine(rootedSrcDir, file2Name); string file2Dir2 = Path.Combine(rootedDstDir, file2Name); try { // relative copy if (!TestCopy(file1Name, file2Name)) return MFTestResults.Fail; // abosulte copy if (!TestCopy(file1Dir1, file2Dir1)) return MFTestResults.Fail; // copy dir1 to dir2 if (!TestCopy(file2Dir1, file1Dir2)) return MFTestResults.Fail; // relative copy if (!TestCopy(file2Dir1, @"..\" + file1Name)) return MFTestResults.Fail; // copy file1dir1 to file2dir2 if (!TestCopy(file2Dir1, file2Dir2)) return MFTestResults.Fail; if (result == MFTestResults.Pass) { Log.Exception("Copy cases are now working! Test needs to finish cases."); result = MFTestResults.KnownFailure; } } catch (Exception ex) { Log.Exception("Unexpected exception: " + ex.Message); return MFTestResults.Fail; } return result; } #endregion Test Cases public MFTestMethod[] Tests { get { return new MFTestMethod[] { new MFTestMethod( ArgumentExceptionTests, "ArgumentExceptionTests" ), new MFTestMethod( IOExceptionTests, "IOExceptionTests" ), new MFTestMethod( ValidCases, "ValidCases" ), }; } } } } ================================================ FILE: Zelig/Zelig/FileSystemTest/File/Create.cs ================================================ //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // Copyright (c) Microsoft Corporation. All rights reserved. //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// using System; using System.IO; namespace FileSystemTest { public class Create : IMFTestInterface { [SetUp] public InitializeResult Initialize() { // These tests rely on underlying file system so we need to make // sure we can format it before we start the tests. If we can't // format it, then we assume there is no FS to test on this platform. // delete the directory DOTNETMF_FS_EMULATION try { IOTests.IntializeVolume(); Directory.CreateDirectory(sourceDir); Directory.CreateDirectory("Test " + sourceDir); Directory.SetCurrentDirectory(sourceDir); } catch (Exception ex) { Log.Comment("Skipping: Unable to initialize file system" + ex.Message); return InitializeResult.Skip; } return InitializeResult.ReadyToGo; } [TearDown] public void CleanUp() { } #region Local vars private const string file1Name = "File1.tmp"; private const string sourceDir = "source"; #endregion Local vars #region Helper methods private bool TestCreate(string file) { return TestCreate(file, 1000); } private bool TestCreate(string file, int buffer) { bool success = true; Log.Comment("Create " + file + " of size " + buffer); if (File.Exists(file)) { Log.Exception("Test space dirty, cleaning up!"); File.Delete(file); } string dir = Path.GetDirectoryName(Path.GetFullPath(file)); if(( dir != null ) && ( dir.Length > 0 ) && !Directory.Exists(dir)) { Directory.CreateDirectory( dir ); } FileStream fs = null; try { fs = File.Create(file, buffer); if (!File.Exists(file)) { Log.Exception("Could not find file after creation!"); success = false; } if (fs.Length != 0) { Log.Exception("Incorrect file length == " + fs.Length); success = false; } if (fs.Position != 0) { Log.Exception("Incorrect file postion == " + fs.Position); success = false; } } finally { if (fs != null) fs.Close(); File.Delete(file); } return success; } #endregion Helper methods #region Test Cases [TestMethod] public MFTestResults ArgumentExceptionTests() { MFTestResults result = MFTestResults.Pass; try { Log.Comment("Current Directory: " + Directory.GetCurrentDirectory()); try { Log.Comment("Null Constructor"); FileStream fs = File.Create(null); Log.Exception( "Expected ArgumentException" ); fs.Close(); return MFTestResults.Fail; } catch (ArgumentException ae) { /* pass case */ Log.Comment( "Got correct exception: " + ae.Message ); result = MFTestResults.Pass; } try { Log.Comment("String.Empty Constructor"); FileStream fs = File.Create(string.Empty); Log.Exception( "Expected ArgumentException" ); fs.Close(); return MFTestResults.Fail; } catch (ArgumentException ae) { /* pass case */ Log.Comment( "Got correct exception: " + ae.Message ); result = MFTestResults.Pass; } try { Log.Comment("Whitespace Constructor"); FileStream fs = File.Create(" "); Log.Exception( "Expected ArgumentException" ); fs.Close(); return MFTestResults.Fail; } catch (ArgumentException ae) { /* pass case */ Log.Comment( "Got correct exception: " + ae.Message ); result = MFTestResults.Pass; } try { Log.Comment("Negative buffer Constructor"); FileStream fs = File.Create(file1Name, -10); Log.Exception( "Expected ArgumentException" ); fs.Close(); return MFTestResults.Fail; } catch (ArgumentException ae) { /* pass case */ Log.Comment( "Got correct exception: " + ae.Message ); result = MFTestResults.Pass; } try { Log.Comment("Current dir '.' Constructor"); FileStream fs = File.Create("."); Log.Exception( "Expected ArgumentException" ); fs.Close(); return MFTestResults.Fail; } catch (IOException ioe) { /* pass case */ Log.Comment( "Got correct exception: " + ioe.Message ); result = MFTestResults.Pass; } // UnauthorizedAccess } catch (Exception ex) { Log.Exception("Unexpected exception: " + ex.Message); return MFTestResults.Fail; } return result; } [TestMethod] public MFTestResults ValidCases() { MFTestResults result = MFTestResults.Pass; string file1Dir1 = Path.Combine(Path.Combine(IOTests.Volume.RootDirectory, sourceDir), file1Name); string filedirspace = Path.Combine(Path.Combine(IOTests.Volume.RootDirectory, "Test " + sourceDir), "Test " + file1Name); try { Log.Comment("relative create"); if (!TestCreate(file1Name)) return MFTestResults.Fail; Log.Comment("absolute create"); if (!TestCreate(file1Dir1)) return MFTestResults.Fail; Log.Comment("elative .. Create"); if (!TestCreate(@"..\" + file1Name)) return MFTestResults.Fail; Log.Comment("relative . Create"); if (!TestCreate(@".\" + file1Name)) return MFTestResults.Fail; Log.Comment("Create at root"); if (!TestCreate(Path.Combine(IOTests.Volume.RootDirectory, file1Name))) return MFTestResults.Fail; Log.Comment("white space in file name"); if (!TestCreate(@"test " + file1Name)) return MFTestResults.Fail; Log.Comment("white space in path & file name"); if (!TestCreate(filedirspace)) return MFTestResults.Fail; Log.Comment("max int buffer"); if (!TestCreate(file1Name, int.MaxValue)) return MFTestResults.Fail; Log.Comment("1 int buffer"); if (!TestCreate(file1Name, 1)) return MFTestResults.Fail; Log.Comment("0 int buffer"); if (!TestCreate(file1Name, 0)) return MFTestResults.Fail; } catch (Exception ex) { Log.Exception("Unexpected exception: " + ex.Message); return MFTestResults.Fail; } return result; } [TestMethod] public MFTestResults CaseInsensitive() { MFTestResults result = MFTestResults.Pass; string file1Dir1 = Path.Combine(Path.Combine(IOTests.Volume.RootDirectory, sourceDir.ToLower()), file1Name.ToLower()); string filedirspace = Path.Combine(Path.Combine(IOTests.Volume.RootDirectory, "Test " + sourceDir.ToUpper()), "Test " + file1Name.ToUpper()); try { // to lower if (!TestCreate(file1Dir1)) return MFTestResults.Fail; // to upper if (!TestCreate(filedirspace)) return MFTestResults.Fail; if (!TestCreate(file1Dir1.ToLower())) return MFTestResults.Fail; if (!TestCreate(file1Dir1.ToUpper())) return MFTestResults.Fail; } catch (Exception ex) { Log.Exception("Unexpected exception: " + ex.Message); return MFTestResults.Fail; } return result; } [TestMethod] public MFTestResults SpecialFileNames() { MFTestResults result = MFTestResults.Pass; char[] special = new char[] { '!', '#', '$', '%', '\'', '(', ')', '+', '-', '.', '@', '[', ']', '_', '`', '{', '}', '~' }; try { Log.Comment("Create file each with special char file names"); for (int i = 0; i < special.Length; i++) { string file = i + "_" + new string(new char[] { special[i] }) + "_z.file"; if (!TestCreate(file)) return MFTestResults.Fail; } } catch (Exception ex) { Log.Exception("Unexpected exception: " + ex.Message); return MFTestResults.Fail; } return result; } [TestMethod] public MFTestResults InvalidPathChars() { MFTestResults result = MFTestResults.Pass; try { foreach (char invalidChar in Path.GetInvalidPathChars()) { try { Log.Comment("Invalid char ascii val = " + (int)invalidChar); string file = new string(new char[] { 'b', 'a', 'd', invalidChar, 'f', 'i', 'l', 'e', invalidChar, '.', 't', 'x', 't' }); FileStream fs = File.Create(file); if (invalidChar == 0) { Log.Exception("Known failure for null"); result = MFTestResults.KnownFailure; } else { Log.Exception( "Expected Argument exception for '" + file + "' but got: '" + fs.Name + "'" ); fs.Close(); File.Delete( file ); return MFTestResults.Fail; } fs.Close(); File.Delete(file); } catch (ArgumentException ae) { /* pass case */ Log.Comment( "Got correct exception: " + ae.Message ); result = MFTestResults.Pass; } } } catch (Exception ex) { Log.Exception("Unexpected exception: " + ex.Message); return MFTestResults.Fail; } return result; } #endregion Test Cases public MFTestMethod[] Tests { get { return new MFTestMethod[] { new MFTestMethod( ArgumentExceptionTests, "ArgumentExceptionTests" ), new MFTestMethod( ValidCases, "ValidCases" ), new MFTestMethod( CaseInsensitive, "CaseInsensitive" ), new MFTestMethod( SpecialFileNames, "SpecialFileNames" ), new MFTestMethod( InvalidPathChars, "InvalidPathChars" ), }; } } } } ================================================ FILE: Zelig/Zelig/FileSystemTest/File/Delete.cs ================================================ //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // Copyright (c) Microsoft Corporation. All rights reserved. //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// using System; using System.IO; using System.Text; namespace FileSystemTest { public class FileDelete : IMFTestInterface { [SetUp] public InitializeResult Initialize() { Log.Comment("Adding set up for the tests."); // Add your functionality here. try { IOTests.IntializeVolume(); Directory.CreateDirectory(sourceDir); Directory.CreateDirectory("Test " + sourceDir); Directory.SetCurrentDirectory(sourceDir); } catch (Exception ex) { Log.Comment("Skipping: Unable to initialize file system" + ex.Message); return InitializeResult.Skip; } return InitializeResult.ReadyToGo; } [TearDown] public void CleanUp() { } #region Local vars private const string file1Name = "file1.tmp"; private const string file2Name = "file2.txt"; private const string sourceDir = "source"; #endregion Local vars #region Helper methods private bool TestDelete(string file) { bool success = true; Log.Comment("Deleting " + file); if (!File.Exists(file)) { Log.Comment("Create " + file); File.Create(file).Close(); if (!File.Exists(file)) { Log.Exception("Could not find file after creation!"); success = false; } } File.Delete(file); if (File.Exists(file)) { Log.Exception("File still exists after delete!"); success = false; } return success; } #endregion Helper methods #region Test Cases [TestMethod] public MFTestResults ArgumentExceptionTests() { MFTestResults result = MFTestResults.Pass; try { Log.Comment("Current Directory: " + Directory.GetCurrentDirectory()); try { Log.Comment("Null argument"); File.Delete(null); Log.Exception( "Expected ArgumentException" ); return MFTestResults.Fail; } catch (ArgumentNullException ane) { /* pass case */ Log.Comment( "Got correct exception: " + ane.Message ); result = MFTestResults.Pass; } try { Log.Comment("String.Empty argument"); File.Delete(string.Empty); Log.Exception( "Expected ArgumentException" ); return MFTestResults.Fail; } catch (ArgumentException ae) { /* pass case */ Log.Comment( "Got correct exception: " + ae.Message ); result = MFTestResults.Pass; } try { Log.Comment("Whitespace argument"); File.Delete(" "); Log.Exception( "Expected ArgumentException" ); return MFTestResults.Fail; } catch (ArgumentException ae) { /* pass case */ Log.Comment( "Got correct exception: " + ae.Message ); result = MFTestResults.Pass; } try { Log.Comment("*.* argument"); File.Delete("*.*"); Log.Exception( "Expected ArgumentException" ); return MFTestResults.Fail; } catch (ArgumentException ae) { /* pass case */ Log.Comment( "Got correct exception: " + ae.Message ); result = MFTestResults.Pass; } try { Log.Comment("Current dir '.' argument"); File.Delete("."); Log.Exception( "Expected ArgumentException" ); return MFTestResults.Fail; } catch (IOException ioe) { /* pass case */ Log.Comment( "Got correct exception: " + ioe.Message ); result = MFTestResults.Pass; } // UnauthorizedAccess try { Log.Comment("parent dir '..' argument"); File.Delete(".."); Log.Exception( "Expected ArgumentException" ); return MFTestResults.Fail; } catch (IOException ioe) { /* pass case */ Log.Comment( "Got correct exception: " + ioe.Message ); result = MFTestResults.Pass; } // UnauthorizedAccess } catch (Exception ex) { Log.Exception("Unexpected exception: " + ex.Message); return MFTestResults.Fail; } return result; } [TestMethod] public MFTestResults IOExceptionTests() { MFTestResults result = MFTestResults.Pass; FileStream fs = null; try { Log.Comment("Current Directory: " + Directory.GetCurrentDirectory()); try { Log.Comment("non-existent file"); File.Delete("non-existent.file"); /// No exception is thrown for non existent file. } catch (IOException) { Log.Exception( "Unexpected IOException" ); return MFTestResults.Fail; } try { Log.Comment("Read only file"); File.Create(file1Name).Close(); File.SetAttributes(file1Name, FileAttributes.ReadOnly); File.Delete(file1Name); Log.Exception( "Expected IOException" ); return MFTestResults.Fail; } catch (IOException ioe) { /* pass case */ Log.Comment( "Got correct exception: " + ioe.Message ); result = MFTestResults.Pass; } // UnauthorizedAccess finally { if (File.Exists(file1Name)) { Log.Comment("Clean up read only file"); File.SetAttributes(file1Name, FileAttributes.Normal); File.Delete(file1Name); } } try { Log.Comment("file in use"); fs = File.Create(file1Name); File.Delete(file1Name); Log.Exception( "Expected IOException" ); return MFTestResults.Fail; } catch (IOException ioe) { /* pass case */ Log.Comment( "Got correct exception: " + ioe.Message ); result = MFTestResults.Pass; } finally { if (fs != null) { Log.Comment("Clean up file in use"); fs.Close(); File.Delete(file1Name); } } } catch (Exception ex) { Log.Exception("Unexpected exception: " + ex.Message); return MFTestResults.Fail; } return result; } [TestMethod] public MFTestResults ValidCases() { MFTestResults result = MFTestResults.Pass; FileStream fs = null; try { Log.Comment("Current Directory: " + Directory.GetCurrentDirectory()); Log.Comment("relative delete"); if (!TestDelete(file1Name)) return MFTestResults.Fail; Log.Comment("absolute delete"); if (!TestDelete(Directory.GetCurrentDirectory() + "\\" + file1Name)) return MFTestResults.Fail; Log.Comment("Case insensitive lower delete"); File.Create(file1Name).Close(); if (!TestDelete(file1Name.ToLower())) return MFTestResults.Fail; Log.Comment("Case insensitive UPPER delete"); File.Create(file2Name).Close(); if (!TestDelete(file2Name.ToUpper())) return MFTestResults.Fail; Log.Comment("Write content to file"); byte[] hello = UTF8Encoding.UTF8.GetBytes("Hello world!"); fs = File.Create(file1Name); fs.Write(hello, 0, hello.Length); fs.Close(); if (!TestDelete(file1Name)) return MFTestResults.Fail; Log.Comment("relative . delete"); File.Create(file2Name).Close(); if (!TestDelete(@".\" + file2Name)) return MFTestResults.Fail; Log.Comment("relative .. delete"); File.Create(Path.Combine(IOTests.Volume.RootDirectory, file2Name)).Close(); if (!TestDelete(@"..\" + file2Name)) return MFTestResults.Fail; Log.Comment("hidden file delete"); File.Create(file1Name).Close(); File.SetAttributes(file1Name, FileAttributes.Hidden); if (!TestDelete(file1Name)) return MFTestResults.Fail; } catch (Exception ex) { Log.Exception("Unexpected exception: " + ex.Message); return MFTestResults.Fail; } return result; } [TestMethod] public MFTestResults SpecialFileNames() { MFTestResults result = MFTestResults.Pass; char[] special = new char[] { '!', '#', '$', '%', '\'', '(', ')', '+', '-', '.', '@', '[', ']', '_', '`', '{', '}', '~' }; try { Log.Comment("Create file each with special char file names"); for (int i = 0; i < special.Length; i++) { string file = i + "_" + new string(new char[] { special[i] }) + "_z.file"; if (!TestDelete(file)) return MFTestResults.Fail; } } catch (Exception ex) { Log.Exception("Unexpected exception: " + ex.Message); return MFTestResults.Fail; } return result; } #endregion Test Cases public MFTestMethod[] Tests { get { return new MFTestMethod[] { new MFTestMethod( ArgumentExceptionTests, "ArgumentExceptionTests" ), new MFTestMethod( IOExceptionTests, "IOExceptionTests" ), new MFTestMethod( ValidCases, "ValidCases" ), new MFTestMethod( SpecialFileNames, "SpecialFileNames" ), }; } } } } ================================================ FILE: Zelig/Zelig/FileSystemTest/File/Exists.cs ================================================ //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // Copyright (c) Microsoft Corporation. All rights reserved. //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// using System; using System.IO; namespace FileSystemTest { public class FileExists : IMFTestInterface { [SetUp] public InitializeResult Initialize() { Log.Comment("Adding set up for the tests."); // Add your functionality here. try { IOTests.IntializeVolume(); Directory.CreateDirectory(testDir); Directory.SetCurrentDirectory(testDir); File.Create(file1Name).Close(); File.Create(IOTests.Volume.RootDirectory + "\\" + file2Name).Close(); } catch (Exception ex) { Log.Comment("Skipping: Unable to initialize file system" + ex.Message); return InitializeResult.Skip; } return InitializeResult.ReadyToGo; } [TearDown] public void CleanUp() { } #region Local vars private const string file1Name = "File1.tmp"; private const string file2Name = "File2.txt"; private const string testDir = "ExistsDir"; #endregion Local vars #region Helper methods private bool TestExists(string path, bool exists) { Log.Comment("Checking for " + path); if (File.Exists(path) != exists) { Log.Exception("Expeceted " + exists + " but got " + !exists); return false; } return true; } #endregion Helper methods #region Test Cases [TestMethod] public MFTestResults InvalidArguments() { bool file; MFTestResults result = MFTestResults.Pass; try { try { Log.Comment("Null"); file = File.Exists(null); /// MSDN: No exception thrown. } catch (ArgumentNullException) { return MFTestResults.Fail; } try { Log.Comment("String.Empty"); file = File.Exists(String.Empty); } catch (ArgumentNullException) { return MFTestResults.Fail; } try { Log.Comment("White Space"); file = File.Exists(" "); } catch (ArgumentNullException) { return MFTestResults.Fail; } } catch (Exception ex) { Log.Exception("Unexpected exception: " + ex.Message); return MFTestResults.Fail; } return result; } [TestMethod] public MFTestResults ValidCases() { MFTestResults result = MFTestResults.Pass; try { Log.Comment("relative to current"); if (!TestExists(file1Name, true)) return MFTestResults.Fail; Log.Comment(". current directory"); if (!TestExists(@".\" + file1Name, true)) return MFTestResults.Fail; Log.Comment(".. parent directory"); if (!TestExists(@"..\" + file2Name, true)) return MFTestResults.Fail; Log.Comment("absolute path"); if (!TestExists(Directory.GetCurrentDirectory() + "\\" + file1Name, true)) return MFTestResults.Fail; Log.Comment("current directory name"); if (!TestExists(Directory.GetCurrentDirectory(), false)) return MFTestResults.Fail; Log.Comment("Set to root"); Directory.SetCurrentDirectory(IOTests.Volume.RootDirectory); Log.Comment(". current directory"); if (!TestExists(@".\" + file2Name, true)) return MFTestResults.Fail; Log.Comment("relative child"); if (!TestExists(testDir + "\\" + file1Name, true)) return MFTestResults.Fail; Log.Comment("child directory name"); if (!TestExists(testDir, false)) return MFTestResults.Fail; } catch (Exception ex) { Log.Exception("Unexpected exception: " + ex.Message); return MFTestResults.Fail; } return result; } [TestMethod] public MFTestResults NonExistentFiles() { MFTestResults result = MFTestResults.Pass; try { Directory.SetCurrentDirectory(IOTests.Volume.RootDirectory); Log.Comment("Current directory: " + Directory.GetCurrentDirectory()); Log.Comment("Non-exist at root"); if (!TestExists(@"..\" + file1Name, false)) return MFTestResults.Fail; Log.Comment("Dot - ."); if (!TestExists("." + file1Name, false)) return MFTestResults.Fail; Log.Comment("Double dot - .."); if (!TestExists(".." + file1Name, false)) return MFTestResults.Fail; Log.Comment("Non-exist relative"); if (!TestExists(file1Name, false)) return MFTestResults.Fail; Log.Comment("Non-exist in child dir"); if (!TestExists(testDir + "\\" + file2Name, false)) return MFTestResults.Fail; Log.Comment("Non-exist absolute"); if (!TestExists(IOTests.Volume.RootDirectory + "\\" + testDir + "\\" + file2Name, false)) return MFTestResults.Fail; Log.Comment("Non-exist directory absolute"); if (!TestExists(IOTests.Volume.RootDirectory + "\\" + testDir + "\\non-existent\\" + file2Name, false)) return MFTestResults.Fail; Log.Comment("Wild card - *" + file1Name); if (!TestExists("*" + file1Name, false)) return MFTestResults.Fail; Log.Comment("Wild card - *"); if (!TestExists("*", false)) return MFTestResults.Fail; } catch (Exception ex) { Log.Exception("Unexpected exception: " + ex.Message); return MFTestResults.Fail; } return result; } [TestMethod] public MFTestResults PathTooLong() { MFTestResults result = MFTestResults.Pass; try { string path = new string('x', 500); bool exists = File.Exists(path); } catch (Exception ex) { Log.Exception("Unexpected exception: " + ex.Message); return MFTestResults.Fail; } return result; } [TestMethod] public MFTestResults CaseInsensitive() { Directory.SetCurrentDirectory(IOTests.Volume.RootDirectory + "\\" + testDir); Log.Comment("Current directory: " + Directory.GetCurrentDirectory()); MFTestResults result = MFTestResults.Pass; try { if (!TestExists(file1Name.ToLower(), true)) return MFTestResults.Fail; if (!TestExists(file1Name.ToUpper(), true)) return MFTestResults.Fail; if (!TestExists(IOTests.Volume.RootDirectory + "\\" + testDir.ToLower() + "\\" + file1Name.ToLower(), true)) return MFTestResults.Fail; if (!TestExists(IOTests.Volume.RootDirectory + "\\" + testDir.ToUpper() + "\\" + file1Name.ToUpper(), true)) return MFTestResults.Fail; } catch (Exception ex) { Log.Exception("Unexpected exception: " + ex.Message); return MFTestResults.Fail; } return result; } [TestMethod] public MFTestResults MultiSpaceExists() { MFTestResults result = MFTestResults.Pass; try { string dir = Directory.GetCurrentDirectory() + @"\Microsoft Visual Studio .NET\Frame work\V1.0.0.0000"; Directory.CreateDirectory(dir); string fileName = dir + "\\test file with spaces.txt"; File.Create(fileName).Close(); if (!TestExists(fileName, true)) return MFTestResults.Fail; } catch (Exception ex) { Log.Exception("Unexpected exception: " + ex.Message); return MFTestResults.Fail; } return result; } #endregion Test Cases public MFTestMethod[] Tests { get { return new MFTestMethod[] { new MFTestMethod( InvalidArguments, "InvalidArguments" ), new MFTestMethod( ValidCases, "ValidCases" ), new MFTestMethod( NonExistentFiles, "NonExistentFiles" ), new MFTestMethod( PathTooLong, "PathTooLong" ), new MFTestMethod( CaseInsensitive, "CaseInsensitive" ), new MFTestMethod( MultiSpaceExists, "MultiSpaceExists" ), }; } } } } ================================================ FILE: Zelig/Zelig/FileSystemTest/File/FileInfoTests.cs ================================================ /*--------------------------------------------------------------------- * FileTests.cs - file description * Version: 1.0 * Author: REDMOND\a-grchat * Created: 9/12/2007 4:51:10 PM * * Tests the basic functionality of Socket objects * ---------------------------------------------------------------------*/ using System; using System.Reflection; using System.IO; namespace FileSystemTest { public class FileInfoTests : IMFTestInterface { [SetUp] public InitializeResult Initialize() { Log.Comment("Adding set up for the tests."); // Add your functionality here. try { IOTests.IntializeVolume(); } catch { Log.Comment("Unable to format media, skipping class tests."); return InitializeResult.Skip; } return InitializeResult.ReadyToGo; } [TearDown] public void CleanUp() { } /// /// Try with a file that does not exist. /// /// [TestMethod] public MFTestResults FileInfoTest_Constructor0() { bool testResult = false; try { FileInfo fi = new FileInfo("FileThatNeverExists.txt"); testResult = true; } catch (Exception ex) { Log.Exception("Unexpected Exception", ex); } return (testResult ? MFTestResults.Pass : MFTestResults.Fail); } /// /// Bad file name. /// /// [TestMethod] public MFTestResults FileInfoTest_Constructor1() { bool testResult = true; try { FileInfo fi = new FileInfo("%$^%^%&**?"); testResult = false; } catch (Exception ex) { Log.Exception("Expected Exception", ex); testResult = true; // ZeligBUG - testResult = false if this line is moved } return (testResult ? MFTestResults.Pass : MFTestResults.Fail); } /// /// Validate Name property. /// /// [TestMethod] public MFTestResults FileInfoTest_Name() { bool testResult = false; try { FileInfo fi = new FileInfo(IOTests.Volume.RootDirectory + "\\dir\\FileName.txt"); testResult = String.Equals(fi.Name, "FileName.txt"); } catch (Exception ex) { Log.Exception("Unexpected Exception", ex); } return (testResult ? MFTestResults.Pass : MFTestResults.Fail); } /// /// Validate a zero lengthed file. /// /// [TestMethod] public MFTestResults FileInfoTest_Length0() { bool testResult = false; try { FileStream file = File.Create("FileInfoTest_Length0.txt"); file.Close(); FileInfo fi = new FileInfo("FileInfoTest_Length0.txt"); testResult = (fi.Length == 0); } catch (Exception ex) { Log.Exception("Unexpected Exception", ex); } return (testResult ? MFTestResults.Pass : MFTestResults.Fail); } /// /// Validate a non-zero lengthed file. /// /// [TestMethod] public MFTestResults FileInfoTest_Length1() { bool testResult = false; try { FileStream file = File.Create("FileInfoTest_Length1.txt"); file.Close(); /// FUTURE: This will be done once Read/Write starts working. FileInfo fi = new FileInfo("FileInfoTest_Length1.txt"); testResult = (fi.Length == 0); } catch (Exception ex) { Log.Exception("Unexpected Exception", ex); } return (testResult ? MFTestResults.Pass : MFTestResults.Fail); } /// /// Get length of a file that does not exist. /// /// [TestMethod] public MFTestResults FileInfoTest_Length2() { bool testResult = false; try { FileInfo fi = new FileInfo("FileInfoTest_Length2.txt"); testResult = (fi.Length == -1); } catch (IOException) { testResult = true; } catch (Exception ex) { Log.Exception("Unexpected Exception", ex); } return (testResult ? MFTestResults.Pass : MFTestResults.Fail); } /// /// Validate DirectoryName property. /// /// [TestMethod] public MFTestResults FileInfoTest_DirectoryName() { bool testResult = false; try { FileInfo fi = new FileInfo(IOTests.Volume.RootDirectory + "\\dir\\FileName.txt"); testResult = String.Equals(fi.DirectoryName, IOTests.Volume.RootDirectory + "\\dir"); } catch (Exception ex) { Log.Exception("Unexpected Exception", ex); } return (testResult ? MFTestResults.Pass : MFTestResults.Fail); } /// /// Validate Directory property is non-null. /// /// [TestMethod] public MFTestResults FileInfoTest_Directory() { bool testResult = false; try { FileInfo fi = new FileInfo(IOTests.Volume.RootDirectory + "\\dir\\FileName.txt"); DirectoryInfo di = fi.Directory; testResult = (di != null); } catch (Exception ex) { Log.Exception("Unexpected Exception", ex); } return (testResult ? MFTestResults.Pass : MFTestResults.Fail); } /// /// Validate Directory property is points to valid structure. /// /// [TestMethod] public MFTestResults FileInfoTest_Directory1() { bool testResult = false; try { FileInfo fi = new FileInfo(IOTests.Volume.RootDirectory + "\\dir\\FileName.txt"); DirectoryInfo di = fi.Directory; testResult = String.Equals(di.FullName, IOTests.Volume.RootDirectory + "\\dir"); } catch (Exception ex) { Log.Exception("Unexpected Exception", ex); } return (testResult ? MFTestResults.Pass : MFTestResults.Fail); } /// /// Validate file is created. /// /// [TestMethod] public MFTestResults FileInfoTest_Create0() { bool testResult = false; try { string fullPath = Path.GetFullPath("FileInfoTest_Create0.txt"); Log.Exception("FullPath = " + fullPath); FileInfo fi = new FileInfo("FileInfoTest_Create0.txt"); FileStream fs = fi.Create(); fs.Close(); testResult = true; testResult = File.Exists("FileInfoTest_Create0.txt"); } catch (Exception ex) { Log.Exception("Unexpected Exception", ex); } return (testResult ? MFTestResults.Pass : MFTestResults.Fail); } /// /// Validate file created file is deleted. /// /// [TestMethod] public MFTestResults FileInfoTest_Delete0() { bool testResult = false; try { FileInfo fi = new FileInfo("FileInfoTest_Delete0.txt"); FileStream fs = fi.Create(); fs.Close(); testResult = File.Exists("FileInfoTest_Delete0.txt"); if (!testResult) throw new IOException(); fi.Delete(); testResult = !File.Exists("FileInfoTest_Delete0.txt"); } catch (Exception ex) { Log.Exception("Unexpected Exception", ex); } return (testResult ? MFTestResults.Pass : MFTestResults.Fail); } /// /// Validate existence check. /// /// [TestMethod] public MFTestResults FileInfoTest_Exists0() { bool testResult = false; try { FileStream file = File.Create("FileInfoTest_Exists0.txt"); file.Close(); FileInfo fi = new FileInfo("FileInfoTest_Exists0.txt"); testResult = fi.Exists; } catch (Exception ex) { Log.Exception("Unexpected Exception", ex); } return (testResult ? MFTestResults.Pass : MFTestResults.Fail); } /// /// Validate not existence check. /// /// [TestMethod] public MFTestResults FileInfoTest_Exists1() { bool testResult = false; try { FileInfo fi = new FileInfo("FileInfoTest_Exists1.txt"); testResult = !fi.Exists; } catch (Exception ex) { Log.Exception("Unexpected Exception", ex); } return (testResult ? MFTestResults.Pass : MFTestResults.Fail); } [TestMethod] public MFTestResults FileInfoTest_Attributes0() { bool testResult = false; try { FileStream file = File.Create("FileInfoTest_Attributes0.txt"); file.Close(); FileInfo fi = new FileInfo("FileInfoTest_Attributes0.txt"); testResult = ((fi.Attributes & FileAttributes.Directory) == 0); } catch (Exception ex) { Log.Exception("Unexpected Exception", ex); } return (testResult ? MFTestResults.Pass : MFTestResults.Fail); } [TestMethod] public MFTestResults FileInfoTest_CreationTime0() { // do not run on Windows //if (Directory.GetCurrentDirectory().IndexOf("WINFS") != -1) //{ // return MFTestResults.Skip; //} bool testResult = false; try { string name = "FileInfoTest_CreationTime" + Guid.NewGuid().ToString() + "_0.txt"; DateTime now = DateTime.Now; // Creation time is limited to every 2 seconds System.Threading.Thread.Sleep(4000); FileStream file = File.Create(name); file.Close(); FileInfo fi = new FileInfo(name); testResult = (fi.CreationTime >= now); Log.Comment("Time at creation: " + now.ToString()); Log.Comment("Creation time : " + fi.CreationTime.ToString()); } catch (Exception ex) { Log.Exception("Unexpected Exception", ex); } return (testResult ? MFTestResults.Pass : MFTestResults.Fail); } [TestMethod] public MFTestResults FileInfoTest_LastAccessTime0() { // do not run on Windows //if (Directory.GetCurrentDirectory().IndexOf("WINFS") != -1) //{ // return MFTestResults.Skip; //} bool testResult = false; try { FileInfo fi1, fi2; string name = "FileInfoTest_LastAccessTime" + Guid.NewGuid().ToString() + "_0.txt"; using (FileStream file = File.Create(name)) { file.Close(); fi1 = new FileInfo(name); testResult = (fi1.LastAccessTime.Ticks != 0); } // add one day //Microsoft.SPOT.Hardware.Utility.SetLocalTime(DateTime.Now.AddDays(1)); using (FileStream again = File.Create(name)) { again.Close(); fi2 = new FileInfo(name); testResult = (fi2.LastAccessTime - fi1.LastAccessTime >= new TimeSpan(1,0,0,0)); } Log.Comment("First access : " + fi1.LastAccessTime.ToString()); Log.Comment("Second access: " + fi2.LastAccessTime.ToString()); } catch (Exception ex) { Log.Exception("Unexpected Exception", ex); } return (testResult ? MFTestResults.Pass : MFTestResults.KnownFailure); } [TestMethod] public MFTestResults FileInfoTest_LastWriteTime0() { bool testResult = false; int sleep = 2000; // 2 secs try { FileInfo fi1, fi2; string name = "FileInfoTest_LastWriteTime" + Guid.NewGuid().ToString() + "_0.txt"; using (FileStream file = File.Create(name)) { file.WriteByte( 0x33 ); file.WriteByte( 0x34 ); file.WriteByte( 0x35 ); file.Close(); fi1 = new FileInfo(name); testResult = (fi1.LastWriteTime.Ticks != 0); } System.Threading.Thread.Sleep(sleep); using (FileStream again = File.Open(name, FileMode.Append)) { again.WriteByte(0x33); again.Close(); fi2 = new FileInfo(name); testResult = (fi2.LastWriteTime - fi1.LastWriteTime >= new TimeSpan(0, 0, 0, 0, 2000)); } Log.Comment("First write : " + fi1.LastWriteTime.ToString()); Log.Comment("Second write: " + fi2.LastWriteTime.ToString()); } catch (Exception ex) { Log.Exception("Unexpected Exception", ex); } return (testResult ? MFTestResults.Pass : MFTestResults.Fail); } public MFTestMethod[] Tests { get { return new MFTestMethod[] { new MFTestMethod( FileInfoTest_Constructor0, "FileInfoTest_Constructor0" ), new MFTestMethod( FileInfoTest_Constructor1, "FileInfoTest_Constructor1" ), new MFTestMethod( FileInfoTest_Name, "FileInfoTest_Name" ), new MFTestMethod( FileInfoTest_Length0, "FileInfoTest_Length0" ), new MFTestMethod( FileInfoTest_Length1, "FileInfoTest_Length1" ), new MFTestMethod( FileInfoTest_Length2, "FileInfoTest_Length2" ), new MFTestMethod( FileInfoTest_DirectoryName, "FileInfoTest_DirectoryName" ), new MFTestMethod( FileInfoTest_Directory, "FileInfoTest_Directory" ), new MFTestMethod( FileInfoTest_Directory1, "FileInfoTest_Directory1" ), new MFTestMethod( FileInfoTest_Create0, "FileInfoTest_Create0" ), new MFTestMethod( FileInfoTest_Delete0, "FileInfoTest_Delete0" ), new MFTestMethod( FileInfoTest_Exists0, "FileInfoTest_Exists0" ), new MFTestMethod( FileInfoTest_Exists1, "FileInfoTest_Exists1" ), new MFTestMethod( FileInfoTest_Attributes0, "FileInfoTest_Attributes0" ), new MFTestMethod( FileInfoTest_CreationTime0, "FileInfoTest_CreationTime0" ), new MFTestMethod( FileInfoTest_LastAccessTime0, "FileInfoTest_LastAccessTime0" ), new MFTestMethod( FileInfoTest_LastWriteTime0, "FileInfoTest_LastWriteTime0" ), }; } } } } ================================================ FILE: Zelig/Zelig/FileSystemTest/File/FileTests.cs ================================================ /*--------------------------------------------------------------------- * FileTests.cs - file description * Version: 1.0 * Author: REDMOND\a-grchat * Created: 9/12/2007 4:51:10 PM * * Tests the basic functionality of Socket objects * ---------------------------------------------------------------------*/ using System; using System.Reflection; using System.IO; using System.Diagnostics; namespace FileSystemTest { public class FileTests : IMFTestInterface { [SetUp] public InitializeResult Initialize() { Log.Comment("The following tests are located in FileTests.cs"); // delete the directory DOTNETMF_FS_EMULATION try { IOTests.IntializeVolume(); } catch { Log.Comment("Unable to format media, skipping class tests."); return InitializeResult.Skip; } return InitializeResult.ReadyToGo; } [TearDown] public void CleanUp() { } [TestMethod] public MFTestResults FiletTest_CreateFile0() { bool testResult = true; try { if (File.Exists("fooclose_test0.txt")) { Debug.Print( "hello " ); } FileStream fooclose_test0 = File.Create("fooclose_test0.txt"); fooclose_test0.Close(); if (!File.Exists("fooclose_test0.txt")) { throw new IOException("File not found"); } FileStream foodispose_test0 = File.Create("foodispose_test0.txt"); foodispose_test0.Dispose(); if (!File.Exists("foodispose_test0.txt")) { throw new IOException("File not found"); } } catch (Exception ex) { testResult = false; Log.Exception("Unexpected Exception", ex); } return (testResult ? MFTestResults.Pass : MFTestResults.Fail); } /// /// Create twice. /// /// [TestMethod] public MFTestResults FiletTest_CreateFile1() { bool testResult = true; try { FileStream fooclose_test1 = File.Create("FiletTest_CreateFile1.txt"); try { FileStream fooclose_test2 = File.Create("FiletTest_CreateFile1.txt"); testResult = false; } catch (IOException) { } fooclose_test1.Close(); } catch (Exception ex) { testResult = false; Log.Exception("Unexpected Exception", ex); } return (testResult ? MFTestResults.Pass : MFTestResults.Fail); } /// /// Close twice. This should not throw exception. /// /// [TestMethod] public MFTestResults FiletTest_CloseFile0() { bool testResult = true; try { FileStream fooclose_test0 = File.Create("fooclose_test0.txt"); fooclose_test0.Close(); fooclose_test0.Close(); } catch (Exception ex) { testResult = false; Log.Exception("Unexpected Exception", ex); } return (testResult ? MFTestResults.Pass : MFTestResults.Fail); } /// /// Creat-close-delete many times. /// /// [TestMethod] public MFTestResults FiletTest_CloseFile1() { bool testResult = true; try { int i = 0; for (i = 0; i < 10; i++) { FileStream fooclose_test0 = File.Create("fooclose_test0.txt"); fooclose_test0.Close(); File.Delete("fooclose_test0.txt"); } } catch (Exception ex) { testResult = false; Log.Exception("Unexpected Exception", ex); } return (testResult ? MFTestResults.Pass : MFTestResults.Fail); } [TestMethod] public MFTestResults FiletTest1_CreateAndDeleteFile() { bool testResult = true; try { FileStream fooclose_test1 = File.Create("fooclose_test1.txt"); fooclose_test1.Close(); if (!File.Exists("fooclose_test1.txt")) { throw new IOException("File not found"); } File.Delete("fooclose_test1.txt"); if (File.Exists("fooclose_test1.txt")) { throw new IOException("File was not deleted"); } } catch (Exception ex) { testResult = false; Log.Exception("Unexpected Exception", ex); } return (testResult ? MFTestResults.Pass : MFTestResults.Fail); } [TestMethod] public MFTestResults FiletTest2_CreateAndDeleteFileInUse() { bool testResult = true; try { FileStream fooclose_test2 = File.Create("fooclose_test2.txt"); if (!File.Exists("fooclose_test2.txt")) { throw new IOException("File not found"); } /// This delete attempt should fail. try { File.Delete("fooclose_test2.txt"); testResult = false; Log.Exception("In use file was deleted"); } catch (IOException) { testResult = true; } fooclose_test2.Close(); } catch (Exception ex) { testResult = false; Log.Exception("Unexpected Exception", ex); } return (testResult ? MFTestResults.Pass : MFTestResults.Fail); } /// /// Delete non existent file. /// /// [TestMethod] public MFTestResults FiletTest_DeleteFile1() { bool testResult = true; try { Log.Comment("Delete non-existing file should not throw"); File.Delete("FiletTest_DeleteFile1.txt"); } catch (Exception ex) { testResult = false; Log.Exception("Unexpected Exception", ex); } return (testResult ? MFTestResults.Pass : MFTestResults.Fail); } /// /// Delete file in non existent directory. /// /// [TestMethod] public MFTestResults FiletTest_DeleteFile2() { bool testResult = true; try { if (Directory.Exists("Del2")) throw new IOException("Del2 dir not supposed to exist."); /// This delete attempt should fail. Bug # 22012 try { File.Delete("Del2\\FiletTest_DeleteFile2.txt"); testResult = false; Log.Exception("File deleted when parent directory does not exist"); } catch (IOException) { testResult = true; } } catch (Exception ex) { testResult = false; Log.Exception("Unexpected Exception", ex); } return (testResult ? MFTestResults.Pass : MFTestResults.Fail); } /// /// Gentle move file (valid source and destination). /// /// [TestMethod] public MFTestResults FiletTest_MoveFile0() { bool testResult = true; try { FileStream fooclose_test1 = File.Create("fooclose_test3-1.txt"); fooclose_test1.Close(); if (!File.Exists("fooclose_test3-1.txt")) { throw new IOException("File not found"); } File.Move("fooclose_test3-1.txt", "fooclose_test3-2.txt"); if (!File.Exists("fooclose_test3-2.txt")) { throw new IOException("Moved file not found"); } } catch (Exception ex) { testResult = false; Log.Exception("Unexpected Exception", ex); } return (testResult ? MFTestResults.Pass : MFTestResults.Fail); } /// /// Source file does not exist. /// /// [TestMethod] public MFTestResults FiletTest_MoveFile1() { bool testResult = true; try { if (File.Exists("fooclose_test4-1.txt")) throw new IOException("fooclose_test4-1.txt not supposed to exist."); try { File.Move("fooclose_test4-1.txt", "fooclose_test4-2.txt"); /// File.Move should fail above. } catch (IOException) { testResult = true; } } catch (Exception ex) { testResult = false; Log.Exception("Unexpected Exception", ex); } return (testResult ? MFTestResults.Pass : MFTestResults.Fail); } /// /// Destination path does not exist. /// /// [TestMethod] public MFTestResults FiletTest_MoveFile2() { bool testResult = true; try { FileStream fooclose_test1 = File.Create("fooclose_test5-1.txt"); fooclose_test1.Close(); if (!File.Exists("fooclose_test5-1.txt")) { throw new IOException("File not found"); } try { File.Move("fooclose_test5-1.txt", "dir5\\fooclose_test5-2.txt"); if (File.Exists("fooclose_test5-2.txt")) { testResult = false; Log.Exception("Moved to non existent directory"); } } catch (IOException) { } } catch (Exception ex) { testResult = false; Log.Exception("Unexpected Exception", ex); } return (testResult ? MFTestResults.Pass : MFTestResults.Fail); } /// /// Source file is in use. /// /// [TestMethod] public MFTestResults FiletTes_MoveFile3() { bool testResult = true; try { FileStream fooclose_test1 = File.Create("fooclose_test6-1.txt"); if (!File.Exists("fooclose_test6-1.txt")) { throw new IOException("File not found"); } try { File.Move("fooclose_test6-1.txt", "fooclose_test6-2.txt"); } catch (IOException) { } if (!File.Exists("fooclose_test6-1.txt")) { throw new IOException("File in use moved."); } fooclose_test1.Close(); } catch (Exception ex) { testResult = false; Log.Exception("Unexpected Exception", ex); } return (testResult ? MFTestResults.Pass : MFTestResults.Fail); } /// /// Destination file already exists. /// /// [TestMethod] public MFTestResults FiletTest_MoveFile4() { bool testResult = true; try { FileStream fooclose_test1 = File.Create("fooclose_test7-1.txt"); fooclose_test1.Close(); FileStream fooclose_test2 = File.Create("fooclose_test7-2.txt"); fooclose_test2.Close(); if (!File.Exists("fooclose_test7-1.txt")) { throw new IOException("File not found"); } try { File.Move("fooclose_test7-1.txt", "fooclose_test7-2.txt"); } catch (IOException) { testResult = true; } if (!File.Exists("fooclose_test7-1.txt")) { throw new IOException("File in use moved."); } } catch (Exception ex) { testResult = false; Log.Exception("Unexpected Exception", ex); } return (testResult ? MFTestResults.Pass : MFTestResults.Fail); } /// /// Create-Move-Delete-then create both again. /// /// [TestMethod] public MFTestResults FiletTest_MoveFile6() { bool testResult = true; try { FileStream fooclose_test1 = File.Create("FiletTest_MoveFile6-1.txt"); fooclose_test1.Close(); File.Move("FiletTest_MoveFile6-1.txt", "FiletTest_MoveFile6-2.txt"); File.Delete("FiletTest_MoveFile6-2.txt"); FileStream fooclose_test2 = File.Create("FiletTest_MoveFile6-2.txt"); fooclose_test2.Close(); FileStream fooclose_test3 = File.Create("FiletTest_MoveFile6-1.txt"); fooclose_test3.Close(); } catch (Exception ex) { testResult = false; Log.Exception("Unexpected Exception", ex); } return (testResult ? MFTestResults.Pass : MFTestResults.Fail); } public MFTestMethod[] Tests { get { return new MFTestMethod[] { new MFTestMethod( FiletTest_CreateFile0, "FiletTest_CreateFile0" ), new MFTestMethod( FiletTest_CreateFile1, "FiletTest_CreateFile1" ), new MFTestMethod( FiletTest_CloseFile0, "FiletTest_CloseFile0" ), new MFTestMethod( FiletTest_CloseFile1, "FiletTest_CloseFile1" ), new MFTestMethod( FiletTest1_CreateAndDeleteFile, "FiletTest1_CreateAndDeleteFile" ), new MFTestMethod( FiletTest2_CreateAndDeleteFileInUse, "FiletTest2_CreateAndDeleteFileInUse" ), new MFTestMethod( FiletTest_DeleteFile1, "FiletTest_DeleteFile1" ), new MFTestMethod( FiletTest_DeleteFile2, "FiletTest_DeleteFile2" ), new MFTestMethod( FiletTest_MoveFile0, "FiletTest_MoveFile0" ), new MFTestMethod( FiletTest_MoveFile1, "FiletTest_MoveFile1" ), new MFTestMethod( FiletTest_MoveFile2, "FiletTest_MoveFile2" ), new MFTestMethod( FiletTes_MoveFile3, "FiletTes_MoveFile3" ), new MFTestMethod( FiletTest_MoveFile4, "FiletTest_MoveFile4" ), new MFTestMethod( FiletTest_MoveFile6, "FiletTest_MoveFile6" ), }; } } } } ================================================ FILE: Zelig/Zelig/FileSystemTest/File/GetSetAttributes.cs ================================================ //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // Copyright (c) Microsoft Corporation. All rights reserved. //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// using System; using System.IO; namespace FileSystemTest { public class GetSetAttributes : IMFTestInterface { [SetUp] public InitializeResult Initialize() { // These tests rely on underlying file system so we need to make // sure we can format it before we start the tests. If we can't // format it, then we assume there is no FS to test on this platform. // delete the directory DOTNETMF_FS_EMULATION try { IOTests.IntializeVolume(); Directory.CreateDirectory(testDir); Directory.SetCurrentDirectory(testDir); File.Create(file1Name).Close(); } catch (Exception ex) { Log.Comment("Skipping: Unable to initialize file system" + ex.Message); return InitializeResult.Skip; } return InitializeResult.ReadyToGo; } [TearDown] public void CleanUp() { } #region Local vars private const string file1Name = "File1.tmp"; private const string testDir = "GetAttributesDir"; #endregion Local vars #region Helper methods private bool TestSetGetAttributes(string path, FileAttributes expected) { Log.Comment("Setting file " + path + " to attribute " + expected); File.SetAttributes(path, expected); return TestGetAttributes(path, expected); } private bool TestGetAttributes(string path, FileAttributes expected) { Log.Comment("Checking file " + path + " for attribute " + expected); FileAttributes fa = File.GetAttributes(path); if (fa != expected) { Log.Exception("Unexpected value - got " + fa); return false; } return true; } #endregion Helper methods #region Test Cases [TestMethod] public MFTestResults InvalidArguments() { FileAttributes file; MFTestResults result = MFTestResults.Pass; try { try { Log.Comment("Get Null"); file = File.GetAttributes(null); Log.Exception( "Expected ArgumentException, but got " + file ); return MFTestResults.Fail; } catch (ArgumentException ae) { /* pass case */ Log.Comment( "Got correct exception: " + ae.Message ); result = MFTestResults.Pass; } try { Log.Comment("Get String.Empty"); file = File.GetAttributes(String.Empty); Log.Exception( "Expected ArgumentException, but got " + file ); return MFTestResults.Fail; } catch (ArgumentException ae) { /* pass case */ Log.Comment( "Got correct exception: " + ae.Message ); result = MFTestResults.Pass; } try { Log.Comment("Get White Space"); file = File.GetAttributes(" "); Log.Exception( "Expected ArgumentException, but got " + file ); return MFTestResults.Fail; } catch (ArgumentException ae) { /* pass case */ Log.Comment( "Got correct exception: " + ae.Message ); result = MFTestResults.Pass; } try { Log.Comment("Set Null"); File.SetAttributes(null, FileAttributes.Normal); Log.Exception( "Expected ArgumentException" ); return MFTestResults.Fail; } catch (ArgumentException ae) { /* pass case */ Log.Comment( "Got correct exception: " + ae.Message ); result = MFTestResults.Pass; } try { Log.Comment("Set String.Empty"); File.SetAttributes(String.Empty, FileAttributes.Normal); Log.Exception( "Expected ArgumentException" ); return MFTestResults.Fail; } catch (ArgumentException ae) { /* pass case */ Log.Comment( "Got correct exception: " + ae.Message ); result = MFTestResults.Pass; } try { Log.Comment("Set White Space"); File.SetAttributes(" ", FileAttributes.Normal); Log.Exception( "Expected ArgumentException" ); return MFTestResults.Fail; } catch (ArgumentException ae) { /* pass case */ Log.Comment( "Got correct exception: " + ae.Message ); result = MFTestResults.Pass; } } catch (Exception ex) { Log.Exception("Unexpected exception: " + ex.Message); return MFTestResults.Fail; } return result; } [TestMethod] public MFTestResults IOExceptions() { FileAttributes file; MFTestResults result = MFTestResults.Pass; try { Log.Comment("Get Check Directory"); file = File.GetAttributes(Directory.GetCurrentDirectory()); try { Log.Comment("Get non-existent file"); file = File.GetAttributes("non-existent"); return MFTestResults.Fail; } catch (IOException ioe) { /* pass case */ Log.Comment( "Got correct exception: " + ioe.Message ); result = MFTestResults.Pass; } // FileNotFound Log.Comment("Set Check Directory"); File.SetAttributes(Directory.GetCurrentDirectory(), FileAttributes.Normal); try { Log.Comment("Set non-existent file"); File.SetAttributes("non-existent", FileAttributes.Normal); Log.Exception( "Expected IOException" ); return MFTestResults.Fail; } catch (IOException ioe) { /* pass case */ Log.Comment( "Got correct exception: " + ioe.Message ); result = MFTestResults.Pass; } Log.Comment("Set Directory"); File.SetAttributes(file1Name, FileAttributes.Directory); Log.Comment("Set Normal | ReadOnly"); File.SetAttributes(file1Name, FileAttributes.Normal | FileAttributes.ReadOnly); Log.Comment("Set Normal | Hidden"); File.SetAttributes(file1Name, FileAttributes.Normal | FileAttributes.Hidden); result = MFTestResults.Pass; } catch (Exception ex) { Log.Exception("Unexpected exception: " + ex.Message); return MFTestResults.Fail; } return result; } [TestMethod] public MFTestResults ValidCases() { MFTestResults result = MFTestResults.Pass; try { /// Initial status is Hidden because of the test above. /// Log.Comment("Default Normal attribute"); /// if (!TestGetAttributes(file1Name, FileAttributes.Normal)) /// return MFTestResults.Fail; Log.Comment("Read Only attribute"); if (!TestSetGetAttributes(file1Name, FileAttributes.ReadOnly)) return MFTestResults.Fail; Log.Comment("Hidden attribute"); if (!TestSetGetAttributes(file1Name, FileAttributes.Hidden)) return MFTestResults.Fail; Log.Comment("ReadOnly & Hidden attribute"); if (!TestSetGetAttributes(file1Name, FileAttributes.Hidden | FileAttributes.ReadOnly)) return MFTestResults.Fail; Log.Comment("Back to Normal attribute"); if (!TestSetGetAttributes(file1Name, FileAttributes.Normal)) return MFTestResults.Fail; } catch (Exception ex) { Log.Exception("Unexpected exception: " + ex.Message); return MFTestResults.Fail; } return result; } #endregion Test Cases public MFTestMethod[] Tests { get { return new MFTestMethod[] { new MFTestMethod( InvalidArguments, "InvalidArguments" ), new MFTestMethod( IOExceptions, "IOExceptions" ), new MFTestMethod( ValidCases, "ValidCases" ), }; } } } } ================================================ FILE: Zelig/Zelig/FileSystemTest/File/OpenRead.cs ================================================ //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // Copyright (c) Microsoft Corporation. All rights reserved. //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// using System; using System.IO; using System.Text; namespace FileSystemTest { public class OpenRead : IMFTestInterface { [SetUp] public InitializeResult Initialize() { // These tests rely on underlying file system so we need to make // sure we can format it before we start the tests. If we can't // format it, then we assume there is no FS to test on this platform. // delete the directory DOTNETMF_FS_EMULATION try { IOTests.IntializeVolume(); Directory.CreateDirectory(testDir); Directory.SetCurrentDirectory(testDir); } catch (Exception ex) { Log.Comment("Skipping: Unable to initialize file system" + ex.Message); return InitializeResult.Skip; } return InitializeResult.ReadyToGo; } [TearDown] public void CleanUp() { } #region Local vars private const string file1Name = "file1.tmp"; private const string file2Name = "file2.txt"; private const string testDir = "OpenRead"; #endregion Local vars #region Test Cases [TestMethod] public MFTestResults InvalidArguments() { MFTestResults result = MFTestResults.Pass; FileStream file = null; try { try { Log.Comment("Null"); file = File.OpenRead(null); Log.Exception( "Expected ArgumentException, but got " + file.Name ); return MFTestResults.Fail; } catch (ArgumentException ae) { /* pass case */ Log.Comment( "Got correct exception: " + ae.Message ); result = MFTestResults.Pass; } try { Log.Comment("String.Empty"); file = File.OpenRead(String.Empty); Log.Exception( "Expected ArgumentException, but got " + file.Name ); return MFTestResults.Fail; } catch (ArgumentException ae) { /* pass case */ Log.Comment( "Got correct exception: " + ae.Message ); result = MFTestResults.Pass; } try { Log.Comment("White Space"); file = File.OpenRead(" "); Log.Exception( "Expected ArgumentException, but got " + file.Name ); return MFTestResults.Fail; } catch (ArgumentException ae) { /* pass case */ Log.Comment( "Got correct exception: " + ae.Message ); result = MFTestResults.Pass; } } catch (Exception ex) { Log.Exception("Unexpected exception: " + ex.Message); return MFTestResults.Fail; } finally { if (file != null) file.Close(); } return result; } [TestMethod] public MFTestResults IOExceptionTests() { MFTestResults result = MFTestResults.Pass; FileStream fs = null; try { Log.Comment("Current Directory: " + Directory.GetCurrentDirectory()); try { Log.Comment("non-existent file"); fs = File.OpenRead("non-existent.file"); Log.Exception( "Expected IOException" ); return MFTestResults.Fail; } catch (IOException ioe) { /* pass case */ Log.Comment( "Got correct exception: " + ioe.Message ); result = MFTestResults.Pass; } } catch (Exception ex) { Log.Exception("Unexpected exception: " + ex.Message); return MFTestResults.Fail; } return result; } [TestMethod] public MFTestResults ValidCase() { MFTestResults result = MFTestResults.Pass; FileStream fs1 = null; byte[] writebytes = Encoding.UTF8.GetBytes(file2Name); byte[] readbytes = new byte[writebytes.Length + 10]; try { Log.Comment("Create file, and write string to it"); fs1 = new FileStream(file2Name, FileMode.Create); fs1.Write(writebytes, 0, writebytes.Length); fs1.Close(); Log.Comment("OpenRead file"); fs1 = File.OpenRead(file2Name); Log.Comment("Try to read from file"); if (!fs1.CanRead) { Log.Exception( "Expected CanRead to be true!" ); return MFTestResults.Fail; } int read = fs1.Read(readbytes, 0, readbytes.Length); if (read != writebytes.Length) { Log.Exception( "Expected " + writebytes.Length + " bytes, but read " + read + " bytes" ); return MFTestResults.Fail; } string readStr = new string(UTF8Encoding.UTF8.GetChars(readbytes, 0, read)); if (file2Name != readStr) { Log.Exception( "Unexpected read data string: " + readStr + " - Expected: " + file2Name ); return MFTestResults.Fail; } Log.Comment("Try to write to file"); if (fs1.CanWrite) { Log.Exception( "Expected CanWrite to be false!" ); return MFTestResults.Fail; } try { fs1.Write(writebytes, 0, writebytes.Length); Log.Exception( "Expected IOException" ); return MFTestResults.Fail; } catch (NotSupportedException nse) { /* pass case */ Log.Comment( "Got correct exception: " + nse.Message ); result = MFTestResults.Pass; } } catch (Exception ex) { Log.Exception("Unexpected exception: " + ex.Message); Log.Exception("Stack: " + ex.Message); return MFTestResults.Fail; } finally { if (fs1 != null) fs1.Close(); } return result; } #endregion Test Cases public MFTestMethod[] Tests { get { return new MFTestMethod[] { new MFTestMethod( InvalidArguments, "InvalidArguments" ), new MFTestMethod( IOExceptionTests, "IOExceptionTests" ), new MFTestMethod( ValidCase, "ValidCase" ), }; } } } } ================================================ FILE: Zelig/Zelig/FileSystemTest/File/OpenWrite.cs ================================================ //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // Copyright (c) Microsoft Corporation. All rights reserved. //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// using System; using System.IO; using System.Text; namespace FileSystemTest { public class OpenWrite : IMFTestInterface { [SetUp] public InitializeResult Initialize() { // These tests rely on underlying file system so we need to make // sure we can format it before we start the tests. If we can't // format it, then we assume there is no FS to test on this platform. // delete the directory DOTNETMF_FS_EMULATION try { IOTests.IntializeVolume(); Directory.CreateDirectory(testDir); Directory.SetCurrentDirectory(testDir); } catch (Exception ex) { Log.Comment("Skipping: Unable to initialize file system" + ex.Message); return InitializeResult.Skip; } return InitializeResult.ReadyToGo; } [TearDown] public void CleanUp() { } #region Local vars private const string file1Name = "file1.tmp"; private const string file2Name = "file2.txt"; private const string testDir = "OpenWrite"; #endregion Local vars #region Test Cases [TestMethod] public MFTestResults InvalidArguments() { MFTestResults result = MFTestResults.Pass; FileStream file = null; try { try { Log.Comment("Null"); file = File.OpenWrite(null); Log.Exception( "Expected ArgumentException, but got " + file.Name ); return MFTestResults.Fail; } catch (ArgumentException ae) { /* pass case */ Log.Comment( "Got correct exception: " + ae.Message ); result = MFTestResults.Pass; } try { Log.Comment("String.Empty"); file = File.OpenWrite(String.Empty); Log.Exception( "Expected ArgumentException, but got " + file.Name ); return MFTestResults.Fail; } catch (ArgumentException ae) { result = MFTestResults.Pass; /* pass case */ Log.Comment( "Got correct exception: " + ae.Message ); } try { Log.Comment("White Space"); file = File.OpenWrite(" "); Log.Exception( "Expected ArgumentException, but got " + file.Name ); return MFTestResults.Fail; } catch (ArgumentException ae) { result = MFTestResults.Pass; /* pass case */ Log.Comment( "Got correct exception: " + ae.Message ); } } catch (Exception ex) { Log.Exception("Unexpected exception: " + ex.Message); return MFTestResults.Fail; } finally { if (file != null) file.Close(); } return result; } [TestMethod] public MFTestResults IOExceptionTests() { MFTestResults result = MFTestResults.Pass; new FileStream(file1Name, FileMode.Create).Close(); try { Log.Comment("Current Directory: " + Directory.GetCurrentDirectory()); try { Log.Comment("ReadOnly file"); File.SetAttributes(file1Name, FileAttributes.ReadOnly); FileStream fs = File.OpenWrite(file1Name); Log.Exception( "Expected IOException" ); fs.Close(); return MFTestResults.Fail; } catch (IOException ex1) { Log.Comment( "Got correct exception: " + ex1.Message ); /// Validate IOException.ErrorCode. result = MFTestResults.Pass; } } catch (Exception ex) { Log.Exception("Unexpected exception: " + ex.Message); return MFTestResults.Fail; } finally { // clean up File.SetAttributes(file1Name, FileAttributes.Normal); File.Delete(file1Name); } return result; } [TestMethod] public MFTestResults ValidCase() { MFTestResults result = MFTestResults.Pass; FileStream fs1 = null; byte[] writebytes = Encoding.UTF8.GetBytes(file2Name); byte[] readbytes = new byte[writebytes.Length + 10]; try { // Clean up if (File.Exists(file2Name)) File.Delete(file2Name); Log.Comment("OpenWrite file"); fs1 = File.OpenWrite(file2Name); Log.Comment("Try to write to file"); if (!fs1.CanWrite) { Log.Exception( "Expected CanWrite to be true!" ); return MFTestResults.Fail; } fs1.Write(writebytes, 0, writebytes.Length); Log.Comment("Try to read from file"); if (fs1.CanRead) { Log.Exception( "Expected CanRead to be false!" ); return MFTestResults.Fail; } try { fs1.Read(readbytes, 0, readbytes.Length); Log.Exception( "Expected IOException" ); return MFTestResults.Fail; } catch (NotSupportedException nse) { /* pass case */ Log.Comment( "Got correct exception: " + nse.Message ); result = MFTestResults.Pass; } } catch (Exception ex) { Log.Exception("Unexpected exception: " + ex.Message); Log.Exception("Stack: " + ex.Message); return MFTestResults.Fail; } finally { if (fs1 != null) fs1.Close(); } return result; } #endregion Test Cases public MFTestMethod[] Tests { get { return new MFTestMethod[] { new MFTestMethod( InvalidArguments, "InvalidArguments" ), new MFTestMethod( IOExceptionTests, "IOExceptionTests" ), new MFTestMethod( ValidCase, "ValidCase" ), }; } } } } ================================================ FILE: Zelig/Zelig/FileSystemTest/File/Open_FM.cs ================================================ //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // Copyright (c) Microsoft Corporation. All rights reserved. //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// using System; using System.IO; using System.Text; namespace FileSystemTest { public class Open_FM : IMFTestInterface { [SetUp] public InitializeResult Initialize() { // These tests rely on underlying file system so we need to make // sure we can format it before we start the tests. If we can't // format it, then we assume there is no FS to test on this platform. // delete the directory DOTNETMF_FS_EMULATION try { IOTests.IntializeVolume(); Directory.CreateDirectory(testDir); Directory.SetCurrentDirectory(testDir); } catch (Exception ex) { Log.Comment("Skipping: Unable to initialize file system" + ex.Message); return InitializeResult.Skip; } return InitializeResult.ReadyToGo; } [TearDown] public void CleanUp() { } #region Local vars private const string fileName = "file1.tmp"; private const string file2Name = "file2.txt"; private const string testDir = "Open_FM"; #endregion Local vars #region Helper methods private MFTestResults TestMethod(FileMode fm) { Log.Comment("Starting tests in FileMode: " + fm.ToString()); FileInfo fil2; StreamWriter sw2; Stream fs2 = null; String str2; int iCountErrors = 0; if (File.Exists(fileName)) File.Delete(fileName); Log.Comment("File does not exist"); //------------------------------------------------------------------ fil2 = new FileInfo(fileName); switch (fm) { case FileMode.CreateNew: case FileMode.Create: case FileMode.OpenOrCreate: try { Log.Comment( "With a null string" ); iCountErrors = 0; // ZeligBUG not resetting the value here leads to uninit iCountErrors value fs2 = File.Open( null, fm ); if(!File.Exists( fileName )) { iCountErrors++; Log.Exception( "File not created, FileMode==" + fm.ToString() ); } } catch (ArgumentException ex) { Log.Comment("Expected exception thrown :: " + ex.Message); } catch (Exception ex) { iCountErrors = 1; Log.Exception("Unexpected exception thrown :: " + ex.ToString()); } Log.Comment("with an empty string"); try { fs2 = File.Open("", fm); if (!File.Exists(fileName)) { iCountErrors++; Log.Exception("File not created, FileMode==" + fm.ToString()); } } catch (ArgumentException ex) { Log.Comment("Expected exception thrown :: " + ex.Message); } catch (Exception ex) { iCountErrors++; Log.Exception("Unexpected exception thrown :: " + ex.ToString()); } fs2 = File.Open(fileName, fm); if (!File.Exists(fileName)) { iCountErrors++; Log.Exception("File not created, FileMode==" + fm.ToString()); } fs2.Close(); break; case FileMode.Open: case FileMode.Truncate: try { Log.Comment( "Open or Truncate" ); iCountErrors = 0; // ZeligBUG not resetting the value here leads to uninit iCountErrors value fs2 = File.Open( fileName, fm ); iCountErrors++; Log.Exception("Expected exception not thrown"); fs2.Close(); } catch (IOException fexc) { Log.Comment("Caught expected exception, fexc==" + fexc.Message); iCountErrors = 0; } catch (Exception exc) { iCountErrors = 1; Log.Exception("Incorrect exception thrown, exc==" + exc.ToString()); } break; case FileMode.Append: try { Log.Comment( "Append" ); fs2 = File.Open(fileName, fm); fs2.Write(new Byte[] { 54, 65, 54, 90 }, 0, 4); if (fs2.Length != 4) { iCountErrors++; Log.Exception("Unexpected file length .... " + fs2.Length); } fs2.Close(); iCountErrors = 0; // ZeligBUG not resetting the value here leads to uninit iCountErrors value } catch (Exception exc) { iCountErrors = 1; Log.Exception("Incorrect exception thrown, exc==" + exc.ToString()); } break; default: iCountErrors = 1; Log.Exception("Invalid mode."); break; } if (File.Exists(fileName)) File.Delete(fileName); if(iCountErrors > 0) return MFTestResults.Fail; //------------------------------------------------------------------ Log.Comment("File already exists"); //------------------------------------------------------------------ sw2 = new StreamWriter(fileName); str2 = "Du er en ape"; sw2.Write(str2); sw2.Close(); switch (fm) { case FileMode.CreateNew: try { fs2 = File.Open( fileName, fm ); iCountErrors++; Log.Exception("Expected exception not thrown"); fs2.Close(); } catch (IOException aexc) { Log.Comment("Caught expected exception, aexc==" + aexc.Message); } catch (Exception exc) { iCountErrors++; Log.Exception("Incorrect exception thrown, exc==" + exc.ToString()); } break; case FileMode.Create: fs2 = File.Open(fileName, fm); if (fs2.Length != 0) { iCountErrors++; Log.Exception("Incorrect length of file==" + fil2.Length); } fs2.Close(); break; case FileMode.OpenOrCreate: case FileMode.Open: fs2 = File.Open(fileName, fm); if (fs2.Length != str2.Length) { iCountErrors++; Log.Exception("Incorrect length on file==" + fil2.Length); } fs2.Close(); break; case FileMode.Truncate: fs2 = File.Open(fileName, fm); if (fs2.Length != 0) { iCountErrors++; Log.Exception("Incorrect length on file==" + fil2.Length); } fs2.Close(); break; case FileMode.Append: try { fs2 = File.Open(fileName, fm); fs2.Write(new Byte[] { 54, 65, 54, 90 }, 0, 4); if (fs2.Length != 16) { // already 12 characters are written to the file. iCountErrors++; Log.Exception("Unexpected file length .... " + fs2.Length); } fs2.Close(); } catch (Exception exc) { iCountErrors++; Log.Exception("Incorrect exception thrown, exc==" + exc.ToString()); } break; default: iCountErrors++; Log.Exception("Invalid mode."); break; } if (File.Exists(fileName)) File.Delete(fileName); return iCountErrors == 0 ? MFTestResults.Pass : MFTestResults.Fail; } #endregion Helper methods #region Test Cases [TestMethod] public MFTestResults FileMode_Append() { return TestMethod(FileMode.Append); } [TestMethod] public MFTestResults FileMode_Create() { return TestMethod(FileMode.Create); } [TestMethod] public MFTestResults FileMode_CreateNew() { return TestMethod(FileMode.CreateNew); } [TestMethod] public MFTestResults FileMode_Open() { return TestMethod(FileMode.Open); } [TestMethod] public MFTestResults FileMode_OpenOrCreate() { return TestMethod(FileMode.OpenOrCreate); } [TestMethod] public MFTestResults FileMode_Truncate() { return TestMethod(FileMode.Truncate); } [TestMethod] public MFTestResults Invalid_FileMode() { MFTestResults result = MFTestResults.Pass; try { // Cleanup if (File.Exists(file2Name)) File.Delete(file2Name); try { Log.Comment("-1 FileMode"); File.Open(file2Name, (FileMode)(-1)); Log.Exception( "Unexpected FileMode" ); return MFTestResults.Fail; } catch (ArgumentException ae) { /* pass case */ Log.Comment( "Got correct exception: " + ae.Message ); result = MFTestResults.Pass; } try { Log.Comment("0 FileMode"); File.Open(file2Name, 0); Log.Exception( "Unexpected FileMode" ); return MFTestResults.Fail; } catch (ArgumentException ae) { /* pass case */ Log.Comment( "Got correct exception: " + ae.Message ); result = MFTestResults.Pass; } try { Log.Comment("7 FileMode"); File.Open(file2Name, (FileMode)7); Log.Exception( "Unexpected FileMode" ); return MFTestResults.Fail; } catch (ArgumentException ae) { /* pass case */ Log.Comment( "Got correct exception: " + ae.Message ); result = MFTestResults.Pass; } } catch (Exception ex) { Log.Exception("Unexpected exception: " + ex.Message); return MFTestResults.Fail; } Log.Comment("Verify no file created"); if (File.Exists(file2Name)) { Log.Exception( "Unexpected file found" ); return MFTestResults.Fail; } return result; } [TestMethod] public MFTestResults Invalid_FileAccess() { MFTestResults result = MFTestResults.Pass; try { // Cleanup if (File.Exists(file2Name)) File.Delete(file2Name); try { Log.Comment("-1 FileAccess"); File.Open(file2Name, FileMode.OpenOrCreate, (FileAccess)(-1)); Log.Exception( "Unexpected FileAccess" ); return MFTestResults.Fail; } catch (ArgumentException ae) { /* pass case */ Log.Comment( "Got correct exception: " + ae.Message ); result = MFTestResults.Pass; } try { Log.Comment("0 FileAccess"); File.Open(file2Name, FileMode.OpenOrCreate, (FileAccess)0); Log.Exception( "Unexpected FileAccess" ); return MFTestResults.Fail; } catch (ArgumentException ae) { /* pass case */ Log.Comment( "Got correct exception: " + ae.Message ); result = MFTestResults.Pass; } try { Log.Comment("4 FileAccess"); File.Open(file2Name, FileMode.OpenOrCreate, (FileAccess)4); Log.Exception( "Unexpected FileAccess" ); return MFTestResults.Fail; } catch (ArgumentException ae) { /* pass case */ Log.Comment( "Got correct exception: " + ae.Message ); result = MFTestResults.Pass; } } catch (Exception ex) { Log.Exception("Unexpected exception: " + ex.Message); return MFTestResults.Fail; } Log.Comment("Verify no file created"); if (File.Exists(file2Name)) { Log.Exception( "Unexpected file found" ); return MFTestResults.Fail; } return result; } [TestMethod] public MFTestResults Invalid_FileShare() { MFTestResults result = MFTestResults.Pass; try { // Cleanup if (File.Exists(file2Name)) File.Delete(file2Name); try { Log.Comment("-1 FileShare"); File.Open(file2Name, FileMode.OpenOrCreate, FileAccess.ReadWrite, (FileShare)(-1)); Log.Exception( "Unexpected FileShare" ); return MFTestResults.Fail; } catch (ArgumentException ae) { /* pass case */ Log.Comment( "Got correct exception: " + ae.Message ); result = MFTestResults.Pass; } try { Log.Comment("74 FileShare"); File.Open(file2Name, FileMode.OpenOrCreate, FileAccess.ReadWrite, (FileShare)5); Log.Exception( "Unexpected FileShare" ); return MFTestResults.Fail; } catch (ArgumentException ae) { /* pass case */ Log.Comment( "Got correct exception: " + ae.Message ); result = MFTestResults.Pass; } } catch (Exception ex) { Log.Exception("Unexpected exception: " + ex.Message); return MFTestResults.Fail; } Log.Comment("Verify no file created"); if (File.Exists(file2Name)) { Log.Exception( "Unexpected file found" ); return MFTestResults.Fail; } return result; } #endregion Test Cases public MFTestMethod[] Tests { get { return new MFTestMethod[] { new MFTestMethod( FileMode_Append, "FileMode_Append" ), new MFTestMethod( FileMode_Create, "FileMode_Create" ), new MFTestMethod( FileMode_CreateNew, "FileMode_CreateNew" ), new MFTestMethod( FileMode_Open, "FileMode_Open" ), new MFTestMethod( FileMode_OpenOrCreate, "FileMode_OpenOrCreate" ), new MFTestMethod( FileMode_Truncate, "FileMode_Truncate" ), new MFTestMethod( Invalid_FileMode, "Invalid_FileMode" ), new MFTestMethod( Invalid_FileAccess, "Invalid_FileAccess" ), new MFTestMethod( Invalid_FileShare, "Invalid_FileShare" ), }; } } } } ================================================ FILE: Zelig/Zelig/FileSystemTest/File/Open_FM_FA.cs ================================================ //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // Copyright (c) Microsoft Corporation. All rights reserved. //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// using System; using System.IO; using System.Text; namespace FileSystemTest { public class Open_FM_FA : IMFTestInterface { [SetUp] public InitializeResult Initialize() { // These tests rely on underlying file system so we need to make // sure we can format it before we start the tests. If we can't // format it, then we assume there is no FS to test on this platform. // delete the directory DOTNETMF_FS_EMULATION try { IOTests.IntializeVolume(); Directory.CreateDirectory(testDir); Directory.SetCurrentDirectory(testDir); } catch (Exception ex) { Log.Comment("Skipping: Unable to initialize file system" + ex.Message); return InitializeResult.Skip; } return InitializeResult.ReadyToGo; } [TearDown] public void CleanUp() { } #region Local vars private const string fileName = "file1.tmp"; private const string file2Name = "file2.txt"; private const string testDir = "Open_FM_FA"; #endregion Local vars #region Helper Methods private MFTestResults TestMethod(FileMode fm, FileAccess fa) { Log.Comment("Starting tests in FileMode: " + fm.ToString() + " with FileAccess: " + fa.ToString()); int iCountErrors = 0; String fileName = "TestFile"; StreamWriter sw2; FileStream fs2; String str2; if (File.Exists(fileName)) File.Delete(fileName); Log.Comment("File does not exist"); //------------------------------------------------------------------ switch (fm) { case FileMode.CreateNew: case FileMode.Create: case FileMode.OpenOrCreate: try { Log.Comment( "null path" ); iCountErrors = 0; // ZeligBUG not resetting the value here leads to uninit iCountErrors value fs2 = File.Open( null, fm, fa ); if (!File.Exists(fileName)) { iCountErrors++; Log.Exception("File not created, FileMode==" + fm.ToString()); } fs2.Close(); } catch (ArgumentException aexc) { Log.Comment("Caught expected exception, aexc==" + aexc.Message); iCountErrors = 0; } catch (Exception exc) { iCountErrors = 1; Log.Exception("Incorrect exception thrown, exc==" + exc); } try { Log.Comment("string empty path"); fs2 = File.Open("", fm, fa); if (!File.Exists(fileName)) { iCountErrors++; Log.Exception("File not created, FileMode==" + fm.ToString()); } fs2.Close(); } catch (ArgumentException aexc) { iCountErrors = 0; Log.Comment( "Caught expected exception, aexc==" + aexc.Message ); } catch (Exception exc) { iCountErrors++; Log.Exception("Incorrect exception thrown, exc==" + exc); } try { Log.Comment("string:" + fileName); fs2 = File.Open(fileName, fm, fa); if (!File.Exists(fileName)) { iCountErrors++; Log.Exception("File not created, FileMode==" + fm.ToString()); } fs2.Close(); } catch (ArgumentException aexc) { if ((fm == FileMode.Create && fa == FileAccess.Read) || (fm == FileMode.CreateNew && fa == FileAccess.Read)) { iCountErrors = 0; Log.Comment( "Caught expected exception, aexc==" + aexc.Message ); } else { iCountErrors++; Log.Exception("Unexpected exception, aexc==" + aexc); } } catch (Exception exc) { iCountErrors++; Log.Exception("Incorrect exception thrown, exc==" + exc); } break; case FileMode.Open: case FileMode.Truncate: try { Log.Comment( "null path" ); iCountErrors = 0; // ZeligBUG not resetting the value here leads to uninit iCountErrors value fs2 = File.Open( null, fm, fa ); iCountErrors++; Log.Exception("Expected exception not thrown"); fs2.Close(); } catch (IOException fexc) { iCountErrors = 0; Log.Comment( "Caught expected exception, fexc==" + fexc.Message ); } catch (ArgumentException aexc) { iCountErrors = 0; Log.Comment( "Caught expected exception, aexc==" + aexc.Message ); } catch (Exception exc) { iCountErrors = 1; Log.Exception("Incorrect exception thrown, exc==" + exc.ToString()); } try { Log.Comment("string empty path"); fs2 = File.Open("", fm, fa); iCountErrors++; Log.Exception("Expected exception not thrown"); fs2.Close(); } catch (IOException fexc) { iCountErrors = 0; Log.Comment( "Caught expected exception, fexc==" + fexc.Message ); } catch (ArgumentException aexc) { iCountErrors = 0; Log.Comment( "Caught expected exception, aexc==" + aexc.Message ); } catch (Exception exc) { iCountErrors++; Log.Exception("Incorrect exception thrown, exc==" + exc.ToString()); } try { fs2 = File.Open(fileName, fm, fa); iCountErrors++; Log.Exception("Expected exception not thrown"); fs2.Close(); } catch (IOException fexc) { iCountErrors = 0; Log.Comment( "Caught expected exception, fexc==" + fexc.Message ); } catch (ArgumentException aexc) { if(fa == FileAccess.Read) { iCountErrors = 0; Log.Comment( "Caught expected exception, aexc==" + aexc.Message ); } else { iCountErrors++; Log.Exception( "Unexpected exception thrown, aexc==" + aexc ); } } catch (Exception exc) { iCountErrors++; Log.Exception("Incorrect exception thrown, exc==" + exc.ToString()); } break; case FileMode.Append: if (fa == FileAccess.Write) { Log.Comment( "FileAccess.Write" ); iCountErrors = 0; // ZeligBUG not resetting the value here leads to uninit iCountErrors value fs2 = File.Open( fileName, fm, fa ); if (!File.Exists(fileName)) { iCountErrors = 1; Log.Exception("File not created"); } fs2.Close(); } else { try { Log.Comment( "FileAccess != Write" ); iCountErrors = 0; // ZeligBUG not resetting the value here leads to uninit iCountErrors value fs2 = File.Open( fileName, fm, fa ); iCountErrors++; Log.Exception("Expected exception not thrown"); fs2.Close(); } catch (ArgumentException aexc) { iCountErrors = 0; Log.Comment( "Caught expected exception, aexc==" + aexc.Message ); } catch (Exception exc) { iCountErrors = 1; Log.Exception("Incorrect exception thrown, exc==" + exc.ToString()); } } break; default: iCountErrors = 1; Log.Exception("Invalid FileMode."); break; } if (File.Exists(fileName)) File.Delete(fileName); if(iCountErrors > 0) return MFTestResults.Fail; //------------------------------------------------------------------ Log.Comment("File already exists"); //------------------------------------------------------------------ sw2 = new StreamWriter(fileName); str2 = "Du er en ape"; sw2.Write(str2); sw2.Close(); switch (fm) { case FileMode.CreateNew: try { fs2 = File.Open(null, fm, fa); iCountErrors++; Log.Exception("Expected exception not thrown"); fs2.Close(); } catch (ArgumentException aexc) { iCountErrors = 0; Log.Comment( "Caught expected exception, aexc==" + aexc.Message ); } catch (IOException aexc) { iCountErrors = 0; Log.Comment( "Caught expected exception, aexc==" + aexc.Message ); } catch (Exception exc) { iCountErrors++; Log.Exception("Incorrect exception thrown, exc==" + exc.ToString()); } try { fs2 = File.Open("", fm, fa); iCountErrors++; Log.Exception("Expected exception not thrown"); fs2.Close(); } catch (ArgumentException aexc) { iCountErrors = 0; Log.Comment( "Caught expected exception, aexc==" + aexc.Message ); } catch (IOException aexc) { iCountErrors = 0; Log.Comment( "Caught expected exception, aexc==" + aexc.Message ); } catch (Exception exc) { iCountErrors++; Log.Exception("Incorrect exception thrown, exc==" + exc.ToString()); } try { fs2 = File.Open(fileName, fm, fa); iCountErrors++; Log.Exception("Expected exception not thrown"); fs2.Close(); } catch (ArgumentException aexc) { if (fa == FileAccess.Read) { iCountErrors = 0; Log.Comment( "Caught expected exception, aexc==" + aexc.Message ); } else { iCountErrors++; Log.Exception("Unexpected exception, aexc==" + aexc); } } catch (IOException aexc) { iCountErrors = 0; Log.Comment( "Caught expected exception, aexc==" + aexc.Message ); } catch (Exception exc) { iCountErrors++; Log.Exception("Incorrect exception thrown, exc==" + exc.ToString()); } break; case FileMode.Create: try { fs2 = File.Open(fileName, fm, fa); if (fs2.Length != 0) { iCountErrors++; Log.Exception("Incorrect length of file==" + fs2.Length); } fs2.Close(); } catch (ArgumentException aexc) { if (fa == FileAccess.Read) { iCountErrors = 0; Log.Comment( "Caught expected exception, aexc==" + aexc.Message ); } else { iCountErrors++; Log.Exception("Unexpected exception, aexc==" + aexc); } } catch (Exception exc) { iCountErrors++; Log.Exception("Incorrect exception thrown, exc==" + exc.ToString()); } break; case FileMode.OpenOrCreate: case FileMode.Open: iCountErrors = 0; fs2 = File.Open(fileName, fm, fa); if (fs2.Length != str2.Length) { iCountErrors++; Log.Exception("Incorrect length on file==" + fs2.Length); } fs2.Close(); break; case FileMode.Truncate: if (fa == FileAccess.Read) { try { fs2 = File.Open(fileName, fm, fa); iCountErrors++; Log.Exception("Expected exception not thrown"); } catch (ArgumentException iexc) { iCountErrors = 0; Log.Comment( "Caught expected exception, iexc==" + iexc.Message ); } catch (Exception exc) { iCountErrors++; Log.Exception("Incorrect exception thrown, exc==" + exc.ToString()); } } else { fs2 = File.Open(fileName, fm, fa); iCountErrors = 0; if(fs2.Length != 0) { iCountErrors++; Log.Exception("Incorrect length on file==" + fs2.Length); } fs2.Close(); } break; case FileMode.Append: if (fa == FileAccess.Write) { iCountErrors = 0; fs2 = File.Open( fileName, fm, fa ); if (!File.Exists(fileName)) { iCountErrors++; Log.Exception("File not created"); } fs2.Close(); } else { try { fs2 = File.Open(fileName, fm, fa); iCountErrors++; Log.Exception("Expected exception not thrown"); fs2.Close(); } catch (ArgumentException aexc) { iCountErrors = 0; Log.Comment( "Caught expected exception, aexc==" + aexc.Message ); } catch (Exception exc) { iCountErrors++; Log.Exception("Incorrect exception thrown, exc==" + exc.ToString()); } } break; default: iCountErrors++; Log.Exception("Invalid file mode"); break; } return iCountErrors == 0 ? MFTestResults.Pass : MFTestResults.Fail; } #endregion Helper Methods #region Test Cases [TestMethod] public MFTestResults FileMode_CreateNew_FileAccess_Read() { return TestMethod(FileMode.CreateNew, FileAccess.Read); } [TestMethod] public MFTestResults FileMode_CreateNew_FileAccess_Write() { return TestMethod(FileMode.CreateNew, FileAccess.Write); } [TestMethod] public MFTestResults FileMode_CreateNew_FileAccess_ReadWrite() { return TestMethod(FileMode.CreateNew, FileAccess.ReadWrite); } [TestMethod] public MFTestResults FileMode_Create_FileAccess_Read() { return TestMethod(FileMode.Create, FileAccess.Read); } [TestMethod] public MFTestResults FileMode_Create_FileAccess_Write() { return TestMethod(FileMode.Create, FileAccess.Write); } [TestMethod] public MFTestResults FileMode_Create_FileAccess_ReadWrite() { return TestMethod(FileMode.Create, FileAccess.ReadWrite); } [TestMethod] public MFTestResults FileMode_Open_FileAccess_Read() { return TestMethod(FileMode.Open, FileAccess.Read); } [TestMethod] public MFTestResults FileMode_Open_FileAccess_Write() { return TestMethod(FileMode.Open, FileAccess.Write); } [TestMethod] public MFTestResults FileMode_Open_FileAccess_ReadWrite() { return TestMethod(FileMode.Open, FileAccess.ReadWrite); } [TestMethod] public MFTestResults FileMode_OpenOrCreate_FileAccess_Read() { return TestMethod(FileMode.OpenOrCreate, FileAccess.Read); } [TestMethod] public MFTestResults FileMode_OpenOrCreate_FileAccess_Write() { return TestMethod(FileMode.OpenOrCreate, FileAccess.Write); } [TestMethod] public MFTestResults FileMode_OpenOrCreate_FileAccess_ReadWrite() { return TestMethod(FileMode.OpenOrCreate, FileAccess.ReadWrite); } [TestMethod] public MFTestResults FileMode_Truncate_FileAccess_Read() { return TestMethod(FileMode.Truncate, FileAccess.Read); } [TestMethod] public MFTestResults FileMode_Truncate_FileAccess_Write() { return TestMethod(FileMode.Truncate, FileAccess.Write); } [TestMethod] public MFTestResults FileMode_Truncate_FileAccess_ReadWrite() { return TestMethod(FileMode.Truncate, FileAccess.ReadWrite); } [TestMethod] public MFTestResults FileMode_Append_FileAccess_Read() { return TestMethod(FileMode.Append, FileAccess.Read); } [TestMethod] public MFTestResults FileMode_Append_FileAccess_Write() { return TestMethod(FileMode.Append, FileAccess.Write); } [TestMethod] public MFTestResults FileMode_Append_FileAccess_ReadWrite() { return TestMethod(FileMode.Append, FileAccess.ReadWrite); } #endregion Test Cases public MFTestMethod[] Tests { get { return new MFTestMethod[] { new MFTestMethod( FileMode_CreateNew_FileAccess_Read, "FileMode_CreateNew_FileAccess_Read" ), new MFTestMethod( FileMode_CreateNew_FileAccess_Write, "FileMode_CreateNew_FileAccess_Write" ), new MFTestMethod( FileMode_CreateNew_FileAccess_ReadWrite, "FileMode_CreateNew_FileAccess_ReadWrite" ), new MFTestMethod( FileMode_Create_FileAccess_Read, "FileMode_Create_FileAccess_Read" ), new MFTestMethod( FileMode_Create_FileAccess_Write, "FileMode_Create_FileAccess_Write" ), new MFTestMethod( FileMode_Create_FileAccess_ReadWrite, "FileMode_Create_FileAccess_ReadWrite" ), new MFTestMethod( FileMode_Open_FileAccess_Read, "FileMode_Open_FileAccess_Read" ), new MFTestMethod( FileMode_Open_FileAccess_Write, "FileMode_Open_FileAccess_Write" ), new MFTestMethod( FileMode_Open_FileAccess_ReadWrite, "FileMode_Open_FileAccess_ReadWrite" ), new MFTestMethod( FileMode_OpenOrCreate_FileAccess_Read, "FileMode_OpenOrCreate_FileAccess_Read" ), new MFTestMethod( FileMode_OpenOrCreate_FileAccess_Write, "FileMode_OpenOrCreate_FileAccess_Write" ), new MFTestMethod( FileMode_OpenOrCreate_FileAccess_ReadWrite, "FileMode_OpenOrCreate_FileAccess_ReadWrite" ), new MFTestMethod( FileMode_Truncate_FileAccess_Read, "FileMode_Truncate_FileAccess_Read" ), new MFTestMethod( FileMode_Truncate_FileAccess_Write, "FileMode_Truncate_FileAccess_Write" ), new MFTestMethod( FileMode_Truncate_FileAccess_ReadWrite, "FileMode_Truncate_FileAccess_ReadWrite" ), new MFTestMethod( FileMode_Append_FileAccess_Read, "FileMode_Append_FileAccess_Read" ), new MFTestMethod( FileMode_Append_FileAccess_Write, "FileMode_Append_FileAccess_Write" ), new MFTestMethod( FileMode_Append_FileAccess_ReadWrite, "FileMode_Append_FileAccess_ReadWrite" ), }; } } } } ================================================ FILE: Zelig/Zelig/FileSystemTest/File/Open_FM_FA_FS.cs ================================================ //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // Copyright (c) Microsoft Corporation. All rights reserved. //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// using System; using System.IO; using System.Text; namespace FileSystemTest { public class Open_FM_FA_FS : IMFTestInterface { [SetUp] public InitializeResult Initialize() { // These tests rely on underlying file system so we need to make // sure we can format it before we start the tests. If we can't // format it, then we assume there is no FS to test on this platform. // delete the directory DOTNETMF_FS_EMULATION try { IOTests.IntializeVolume(); Directory.CreateDirectory(testDir); Directory.SetCurrentDirectory(testDir); } catch (Exception ex) { Log.Comment("Skipping: Unable to initialize file system" + ex.Message); return InitializeResult.Skip; } return InitializeResult.ReadyToGo; } [TearDown] public void CleanUp() { } #region Local vars private const string fileName = "file1.tmp"; private const string file2Name = "file2.txt"; private const string testDir = "Open_FM_FA_FS"; #endregion Local vars #region Test Cases [TestMethod] public MFTestResults FilesShare_None() { MFTestResults result = MFTestResults.Pass; FileStream fs1 = null; FileStream fs2 = null; try { // Clean up if (File.Exists(file2Name)) File.Delete(file2Name); fs1 = File.Open(file2Name, FileMode.Create, FileAccess.ReadWrite, FileShare.None); try { fs2 = File.Open(file2Name, FileMode.Open); Log.Exception( "Should not be able to open file with FileShare.None" ); return MFTestResults.Fail; } catch (IOException) { /* pass case */ result = MFTestResults.Pass; // ZeligBUG - result is corrupted if it is not used here } } catch (Exception ex) { Log.Exception("Unexpected exception: " + ex.Message); Log.Exception("Stack: " + ex.Message); return MFTestResults.Fail; } finally { if (fs1 != null) fs1.Close(); if (fs2 != null) fs2.Close(); } return result; } [TestMethod] public MFTestResults FilesShare_Read() { MFTestResults result = MFTestResults.Pass; FileStream fs1 = null; FileStream fs2 = null; try { byte[] bufferWrite = new byte[] { 10, 98 }; byte[] bufferRead = new byte[2]; // Clean up if (File.Exists(file2Name)) File.Delete(file2Name); fs1 = File.Open(file2Name, FileMode.Create, FileAccess.ReadWrite, FileShare.Read); Log.Comment("open 2nd filestream read"); fs2 = File.Open(file2Name, FileMode.Open, FileAccess.Read, FileShare.ReadWrite); Log.Comment("write to 1st filestream"); fs1.Write(bufferWrite, 0, 2); fs1.Flush(); Log.Comment("read from 2nd filestream"); fs2.Read(bufferRead, 0, 2); // Verify content if (bufferRead[0] != bufferWrite[0] || bufferRead[1] != bufferWrite[1]) { return MFTestResults.Fail; } try { Log.Comment("verify 2nd filestream can't write"); fs2.Write(new byte[] { 10 }, 0, 1); Log.Exception( "Should not be able to open file with FileShare.None" ); return MFTestResults.Fail; } catch (NotSupportedException) { /* pass case */ result = MFTestResults.Pass; // ZeligBUG - result is corrupted if it is not used here } } catch (Exception ex) { Log.Exception("Unexpected exception: " + ex.Message); Log.Exception("Stack: " + ex.Message); return MFTestResults.Fail; } finally { if (fs1 != null) fs1.Close(); if (fs2 != null) fs2.Close(); } return result; } [TestMethod] public MFTestResults FilesShare_Write() { MFTestResults result = MFTestResults.Pass; FileStream fs1 = null; FileStream fs2 = null; try { // Clean up if (File.Exists(file2Name)) File.Delete(file2Name); fs1 = File.Open(file2Name, FileMode.Create, FileAccess.ReadWrite, FileShare.Write); fs2 = File.Open(file2Name, FileMode.Open, FileAccess.Write, FileShare.ReadWrite); fs2.Write(new byte[] { 1, 2 }, 0, 2); fs1.Write(new byte[] { 3, 4 }, 0, 2); } catch (Exception ex) { Log.Exception("Unexpected exception: " + ex.Message); Log.Exception("Stack: " + ex.Message); return MFTestResults.Fail; } finally { if (fs1 != null) fs1.Close(); if (fs2 != null) fs2.Close(); } try { byte[] buffer = File.ReadAllBytes(file2Name); if (buffer.Length != 2 || buffer[0] != 3 || buffer[1] != 4) { return MFTestResults.Fail; } } catch (Exception ex) { Log.Exception("Unexpected exception: " + ex.Message); Log.Exception("Stack: " + ex.Message); return MFTestResults.Fail; } return result; } public MFTestResults FilesShare_ReadWrite() { MFTestResults result = MFTestResults.Pass; FileStream fs1 = null; FileStream fs2 = null; FileStream fs3 = null; try { // Clean up if (File.Exists(file2Name)) File.Delete(file2Name); fs1 = File.Open(file2Name, FileMode.Create, FileAccess.ReadWrite, FileShare.ReadWrite); fs2 = File.Open(file2Name, FileMode.Open, FileAccess.Write, FileShare.ReadWrite); fs1.Write(new byte[] { 1 }, 0, 1); fs3 = File.Open(file2Name, FileMode.Open, FileAccess.Read, FileShare.ReadWrite); fs2.Write(new byte[] { 2 }, 0, 1); fs1.Write(new byte[] { 3 }, 0, 1); fs2.Flush(); fs1.Flush(); fs3.Read(new byte[3], 0, 3); fs1.Read(new byte[3], 0, 3); } catch (Exception ex) { Log.Exception("Unexpected exception: " + ex.Message); Log.Exception("Stack: " + ex.Message); return MFTestResults.Fail; } finally { if (fs1 != null) fs1.Close(); if (fs2 != null) fs2.Close(); if (fs3 != null) fs3.Close(); } return result; } #endregion Test Cases public MFTestMethod[] Tests { get { return new MFTestMethod[] { new MFTestMethod( FilesShare_None, "FilesShare_None" ), new MFTestMethod( FilesShare_Read, "FilesShare_Read" ), new MFTestMethod( FilesShare_Write, "FilesShare_Write" ), new MFTestMethod( FilesShare_ReadWrite, "FilesShare_ReadWrite" ), }; } } } } ================================================ FILE: Zelig/Zelig/FileSystemTest/File/ReadAllBytes.cs ================================================ //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // Copyright (c) Microsoft Corporation. All rights reserved. //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// using System; using System.IO; using System.Text; namespace FileSystemTest { public class RWAllBytes : IMFTestInterface { [SetUp] public InitializeResult Initialize() { Log.Comment("Adding set up for the tests"); // These tests rely on underlying file system so we need to make // sure we can format it before we start the tests. If we can't // format it, then we assume there is no FS to test on this platform. // delete the directory DOTNETMF_FS_EMULATION try { IOTests.IntializeVolume(); Directory.CreateDirectory(testDir); Directory.SetCurrentDirectory(testDir); } catch (Exception ex) { Log.Comment("Skipping: Unable to initialize file system" + ex.Message); return InitializeResult.Skip; } return InitializeResult.ReadyToGo; } [TearDown] public void CleanUp() { } #region Local vars private const string file1Name = "file1.tmp"; private const string file2Name = "file2.txt"; private const string testDir = "ReadAllBytes"; #endregion Local vars #region Test Cases [TestMethod] public MFTestResults InvalidArguments() { MFTestResults result = MFTestResults.Pass; byte[] file = null; try { try { Log.Comment("ReadAllBytes Null"); file = File.ReadAllBytes(null); Log.Exception( "Expected ArgumentException, but got " + file.Length ); return MFTestResults.Fail; } catch (ArgumentException ae) { /* pass case */ Log.Comment( "Got correct exception: " + ae.Message ); result = MFTestResults.Pass; } try { Log.Comment("ReadAllBytes String.Empty"); file = File.ReadAllBytes(String.Empty); Log.Exception( "Expected ArgumentException, but got " + file.Length ); return MFTestResults.Fail; } catch (ArgumentException ae) { /* pass case */ Log.Comment( "Got correct exception: " + ae.Message ); result = MFTestResults.Pass; } try { Log.Comment("ReadAllBytes White Space"); file = File.ReadAllBytes(" "); Log.Exception( "Expected ArgumentException, but got " + file.Length ); return MFTestResults.Fail; } catch (ArgumentException ae) { /* pass case */ Log.Comment( "Got correct exception: " + ae.Message ); result = MFTestResults.Pass; } try { Log.Comment("WriteAllBytes Null path"); File.WriteAllBytes(null, new byte[10]); Log.Exception( "Expected ArgumentException, but got " + file.Length ); return MFTestResults.Fail; } catch (ArgumentException ae) { /* pass case */ Log.Comment( "Got correct exception: " + ae.Message ); result = MFTestResults.Pass; } try { Log.Comment("WriteAllBytes Null bytes"); File.WriteAllBytes(file1Name, null); Log.Exception( "Expected ArgumentException, but got " + file.Length ); return MFTestResults.Fail; } catch (ArgumentException ae) { /* pass case */ Log.Comment( "Got correct exception: " + ae.Message ); result = MFTestResults.Pass; } try { Log.Comment("WriteAllBytes String.Empty path"); File.WriteAllBytes(String.Empty, new byte[20]); Log.Exception( "Expected ArgumentException, but got " + file.Length ); return MFTestResults.Fail; } catch (ArgumentException ae) { /* pass case */ Log.Comment( "Got correct exception: " + ae.Message ); result = MFTestResults.Pass; } try { Log.Comment("WriteAllBytes White Space path"); File.WriteAllBytes(" ", new byte[30]); Log.Exception( "Expected ArgumentException, but got " + file.Length ); return MFTestResults.Fail; } catch (ArgumentException ae) { /* pass case */ Log.Comment( "Got correct exception: " + ae.Message ); result = MFTestResults.Pass; } } catch (Exception ex) { Log.Exception("Unexpected exception: " + ex.Message); return MFTestResults.Fail; } return result; } [TestMethod] public MFTestResults IOExceptionTests() { MFTestResults result = MFTestResults.Pass; new FileStream(file1Name, FileMode.Create); Log.Comment("Current Directory: " + Directory.GetCurrentDirectory()); try { try { Log.Comment("non-existent file"); File.ReadAllBytes("non-existent.file"); Log.Exception( "Expected IOException" ); return MFTestResults.Fail; } catch (IOException ioe) { /* pass case */ Log.Comment( "Got correct exception: " + ioe.Message ); result = MFTestResults.Pass; } try { Log.Comment("ReadOnly file"); File.SetAttributes(file1Name, FileAttributes.ReadOnly); File.WriteAllBytes(file1Name, new byte[4]); Log.Exception( "Expected IOException" ); return MFTestResults.Fail; } catch (IOException ioe2) { /// Validate IOException.ErrorCode. Log.Comment( "Got correct exception: " + ioe2.Message ); result = MFTestResults.Pass; } } catch (Exception ex) { Log.Exception("Unexpected exception: " + ex.Message); return MFTestResults.Fail; } return result; } [TestMethod] public MFTestResults ValidCase() { MFTestResults result = MFTestResults.Pass; byte[] writebytes; byte[] readbytes; try { // Clean up if (File.Exists(file2Name)) File.Delete(file2Name); Log.Comment("Create 0 length file"); File.Create(file2Name).Close(); Log.Comment("Read all bytes - expect 0"); readbytes = File.ReadAllBytes(file2Name); if (readbytes.Length != 0) { Log.Exception( "Got " + readbytes.Length + " bytes!" ); return MFTestResults.Fail; } Log.Comment("Write bytes 0-255 to file"); writebytes = new byte[256]; for (int i = 0; i < writebytes.Length; i++) { writebytes[i] = (byte)i; } File.WriteAllBytes(file2Name, writebytes); Log.Comment("Read all bytes - expect 256"); readbytes = File.ReadAllBytes(file2Name); if (readbytes.Length != writebytes.Length) { Log.Exception( "Read unexpected number of bytes: " + readbytes.Length ); return MFTestResults.Fail; } for (int i = 0; i < readbytes.Length; i++) { if (readbytes[i] != i) { Log.Exception( "Expected byte " + i + " but got byte " + readbytes[i] ); return MFTestResults.Fail; } } Log.Comment("Write again, 255-0"); writebytes = new byte[256]; for (int i = 0; i < writebytes.Length; i++) { writebytes[i] = (byte)~(i); } File.WriteAllBytes(file2Name, writebytes); Log.Comment("Read all bytes - expect 256"); readbytes = File.ReadAllBytes(file2Name); if (readbytes.Length != writebytes.Length) { Log.Exception( "Read unexpected number of bytes: " + readbytes.Length ); return MFTestResults.Fail; } for (int i = 0; i < readbytes.Length; i++) { if (readbytes[i] != (byte)~(i)) { Log.Exception( "Expected byte " + (byte)~( i ) + " but got byte " + readbytes[i] ); return MFTestResults.Fail; } } } catch (Exception ex) { Log.Exception("Unexpected exception: " + ex.Message); Log.Exception("Stack: " + ex.Message); return MFTestResults.Fail; } return result; } #endregion Test Cases public MFTestMethod[] Tests { get { return new MFTestMethod[] { new MFTestMethod( InvalidArguments, "InvalidArguments" ), new MFTestMethod( IOExceptionTests, "IOExceptionTests" ), new MFTestMethod( ValidCase, "ValidCase" ), }; } } } } ================================================ FILE: Zelig/Zelig/FileSystemTest/FileStream/CanRead.cs ================================================ //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // Copyright (c) Microsoft Corporation. All rights reserved. //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// using System; using System.IO; namespace FileSystemTest { public class CanRead : IMFTestInterface { [SetUp] public InitializeResult Initialize() { // These tests rely on underlying file system so we need to make // sure we can format it before we start the tests. If we can't // format it, then we assume there is no FS to test on this platform. // delete the directory DOTNETMF_FS_EMULATION try { IOTests.IntializeVolume(); Directory.CreateDirectory(TestDir); Directory.SetCurrentDirectory(TestDir); } catch (Exception ex) { Log.Exception("Skipping: Unable to initialize file system " + ex.Message); return InitializeResult.Skip; } return InitializeResult.ReadyToGo; } [TearDown] public void CleanUp() { } #region local vars private const string TestDir = "CanRead"; private const string fileName = "test.tmp"; private FileStream fs = null; #endregion local vars #region Helper methods private bool TestCanRead(FileAccess access, bool expected) { using (FileStream fs2 = new FileStream(fileName, FileMode.Open, access)) { bool success = (fs2.CanRead == expected); if (!success) { Log.Exception("Unexpected result - Expected " + expected); } return success; } } #endregion Helper methods #region Test Cases [TestMethod] public MFTestResults MainlineCases() { if (File.Exists(fileName)) File.Delete(fileName); fs = new FileStream(fileName, FileMode.Create); fs.Close(); MFTestResults result = MFTestResults.Pass; try { Log.Comment("Open Read, can read"); if (!TestCanRead(FileAccess.Read, true)) return MFTestResults.Fail; Log.Comment("Open Write, can't read"); if (!TestCanRead(FileAccess.Write, false)) return MFTestResults.Fail; Log.Comment("Open Read/Write, can read"); if (!TestCanRead(FileAccess.ReadWrite, true)) return MFTestResults.Fail; Log.Comment("Closed Stream, can't read"); if (fs.CanRead) return MFTestResults.Fail; } catch (Exception ex) { Log.Exception("Unexpected exception: " + ex.Message); return MFTestResults.Fail; } return result; } #endregion Test Cases public MFTestMethod[] Tests { get { return new MFTestMethod[] { new MFTestMethod( MainlineCases, "MainlineCases" ), }; } } } } ================================================ FILE: Zelig/Zelig/FileSystemTest/FileStream/CanSeek.cs ================================================ //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // Copyright (c) Microsoft Corporation. All rights reserved. //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// using System; using System.IO; namespace FileSystemTest { public class CanSeek : IMFTestInterface { [SetUp] public InitializeResult Initialize() { // These tests rely on underlying file system so we need to make // sure we can format it before we start the tests. If we can't // format it, then we assume there is no FS to test on this platform. // delete the directory DOTNETMF_FS_EMULATION try { IOTests.IntializeVolume(); Directory.CreateDirectory(TestDir); Directory.SetCurrentDirectory(TestDir); } catch (Exception ex) { Log.Exception("Skipping: Unable to initialize file system " + ex.Message); return InitializeResult.Skip; } return InitializeResult.ReadyToGo; } [TearDown] public void CleanUp() { } #region local vars private const string TestDir = "CanSeek"; private const string fileName = "test.tmp"; private FileStream fs = null; #endregion local vars #region Helper methods private bool TestCanSeek(FileAccess access, bool expected) { using (FileStream fs2 = new FileStream(fileName, FileMode.Open, access)) { bool success = (fs2.CanSeek == expected); if (!success) { Log.Exception("Unexpected result - Expected " + expected); } return success; } } #endregion Helper methods #region Test Cases [TestMethod] public MFTestResults MainlineCases() { if (File.Exists(fileName)) File.Delete(fileName); fs = new FileStream(fileName, FileMode.Create); fs.Close(); MFTestResults result = MFTestResults.Pass; try { Log.Comment("Open Read, can seek"); if (!TestCanSeek(FileAccess.Read, true)) return MFTestResults.Fail; Log.Comment("Open Write, can seek"); if (!TestCanSeek(FileAccess.Write, true)) return MFTestResults.Fail; Log.Comment("Open Read/Write, can seek"); if (!TestCanSeek(FileAccess.ReadWrite, true)) return MFTestResults.Fail; Log.Comment("Closed Stream, can't seek"); if (fs.CanSeek) return MFTestResults.Fail; } catch (Exception ex) { Log.Exception("Unexpected exception: " + ex.Message); return MFTestResults.Fail; } return result; } #endregion Test Cases public MFTestMethod[] Tests { get { return new MFTestMethod[] { new MFTestMethod( MainlineCases, "MainlineCases" ), }; } } } } ================================================ FILE: Zelig/Zelig/FileSystemTest/FileStream/CanWrite.cs ================================================ //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // Copyright (c) Microsoft Corporation. All rights reserved. //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// using System; using System.IO; namespace FileSystemTest { public class CanWrite : IMFTestInterface { [SetUp] public InitializeResult Initialize() { // These tests rely on underlying file system so we need to make // sure we can format it before we start the tests. If we can't // format it, then we assume there is no FS to test on this platform. // delete the directory DOTNETMF_FS_EMULATION try { IOTests.IntializeVolume(); Directory.CreateDirectory(TestDir); Directory.SetCurrentDirectory(TestDir); } catch (Exception ex) { Log.Exception("Skipping: Unable to initialize file system " + ex.Message); return InitializeResult.Skip; } return InitializeResult.ReadyToGo; } [TearDown] public void CleanUp() { } #region local vars private const string TestDir = "CanWrite"; private const string fileName = "test.tmp"; private FileStream fs = null; #endregion local vars #region Helper methods private bool TestCanWrite(FileAccess access, bool expected) { using (FileStream fs2 = new FileStream(fileName, FileMode.Open, access)) { bool success = (fs2.CanWrite == expected); if (!success) { Log.Exception("Unexpected result - Expected " + expected); } return success; } } #endregion Helper methods #region Test Cases [TestMethod] public MFTestResults MainlineCases() { if (File.Exists(fileName)) File.Delete(fileName); fs = new FileStream(fileName, FileMode.Create); fs.Close(); MFTestResults result = MFTestResults.Pass; try { Log.Comment("Open Read, can't write"); if (!TestCanWrite(FileAccess.Read, false)) return MFTestResults.Fail; Log.Comment("Open Write, can write"); if (!TestCanWrite(FileAccess.Write, true)) return MFTestResults.Fail; Log.Comment("Open Read/Write, can write"); if (!TestCanWrite(FileAccess.ReadWrite, true)) return MFTestResults.Fail; Log.Comment("Closed Stream, can't write"); if (fs.CanWrite) return MFTestResults.Fail; } catch (Exception ex) { Log.Exception("Unexpected exception: " + ex.Message); return MFTestResults.Fail; } return result; } #endregion Test Cases public MFTestMethod[] Tests { get { return new MFTestMethod[] { new MFTestMethod( MainlineCases, "MainlineCases" ), }; } } } } ================================================ FILE: Zelig/Zelig/FileSystemTest/FileStream/Constructors_FileAccess.cs ================================================ //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // Copyright (c) Microsoft Corporation. All rights reserved. //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// using System; using System.IO; namespace FileSystemTest { public class Constructors_FileAccess : IMFTestInterface { [SetUp] public InitializeResult Initialize() { // These tests rely on underlying file system so we need to make // sure we can format it before we start the tests. If we can't // format it, then we assume there is no FS to test on this platform. // delete the directory DOTNETMF_FS_EMULATION try { IOTests.IntializeVolume(); Directory.CreateDirectory(TestDir); Directory.SetCurrentDirectory(TestDir); } catch (Exception ex) { Log.Exception("Skipping: Unable to initialize file system " + ex.Message); return InitializeResult.Skip; } return InitializeResult.ReadyToGo; } [TearDown] public void CleanUp() { } #region local vars private const string TestDir = "FileAccess"; private const string fileName = "test.tmp"; #endregion local vars #region Test Cases [TestMethod] public MFTestResults InvalidArguments() { MFTestResults result = MFTestResults.Pass; try { try { Log.Comment("Bad fileaccess -1"); using (FileStream fs = new FileStream(fileName, FileMode.Create, (FileAccess)(-1))) { } Log.Exception( "Expected ArgumentException" ); return MFTestResults.Fail; } catch (ArgumentException ae) { /* pass case */ Log.Comment( "Got correct exception: " + ae.Message ); result = MFTestResults.Pass; } try { Log.Comment("Bad fileaccess 10"); using (FileStream fs = new FileStream(fileName, FileMode.Create, (FileAccess)(10))) { } Log.Exception( "Expected ArgumentException" ); return MFTestResults.Fail; } catch (ArgumentException ae) { /* pass case */ Log.Comment( "Got correct exception: " + ae.Message ); result = MFTestResults.Pass; } } catch (Exception ex) { Log.Exception("Unexpected exception: " + ex.Message); return MFTestResults.Fail; } return result; } [TestMethod] public MFTestResults FileAccess_Read() { // Clean up incase file exists if (File.Exists(fileName)) File.Delete(fileName); MFTestResults result = MFTestResults.Pass; try { // From MSDN: // Read access to the file. Data can be read from the file. // Combine with Write for read/write access. Log.Comment("Create file for testing"); using (FileStream fs = new FileStream(fileName, FileMode.CreateNew)) { FileStreamHelper.WriteReadEmpty(fs); } using (FileStream fs = new FileStream(fileName, FileMode.Open, FileAccess.Read)) { Log.Comment("Should be able to read"); if (!FileStreamHelper.VerifyRead(fs)) return MFTestResults.Fail; Log.Comment("Shouldn't be able to write"); try { fs.Write(new byte[] { 1, 2, 3 }, 0, 3); Log.Exception( "Expected NotSupportedException" ); return MFTestResults.Fail; } catch (NotSupportedException nse) { /* pass case */ Log.Comment( "Got correct exception: " + nse.Message ); result = MFTestResults.Pass; } } } catch (Exception ex) { Log.Exception("Unexpected exception: " + ex.Message); return MFTestResults.Fail; } return result; } [TestMethod] public MFTestResults FileAccess_Write() { // Clean up incase file exists if (File.Exists(fileName)) File.Delete(fileName); MFTestResults result = MFTestResults.Pass; try { // From MSDN: // Write access to the file. Data can be written to the file. // Combine with Read for read/write access. Log.Comment("Create file for testing"); using (FileStream fs = new FileStream(fileName, FileMode.CreateNew)) { FileStreamHelper.WriteReadEmpty(fs); } using (FileStream fs = new FileStream(fileName, FileMode.Open, FileAccess.Write)) { Log.Comment("Should be able to write"); if (!FileStreamHelper.Write(fs, 1000)) return MFTestResults.Fail; if (!FileStreamHelper.Write(fs, 500)) return MFTestResults.Fail; Log.Comment("Shouldn't be able to read"); try { fs.Seek(0, SeekOrigin.Begin); int data = fs.ReadByte(); Log.Exception( "Expected NotSupportedException" ); return MFTestResults.Fail; } catch (NotSupportedException nse) { /* pass case */ Log.Comment( "Got correct exception: " + nse.Message ); result = MFTestResults.Pass; } } // 300 bytes original + 1000 bytes + 500 bytes if (!FileStreamHelper.VerifyFile(fileName, 1800)) return MFTestResults.Fail; } catch (Exception ex) { Log.Exception("Unexpected exception: " + ex.Message); return MFTestResults.Fail; } return result; } [TestMethod] public MFTestResults FileAccess_ReadWrite() { // Clean up incase file exists if (File.Exists(fileName)) File.Delete(fileName); MFTestResults result = MFTestResults.Pass; try { // From MSDN: // Write access to the file. Data can be written to the file. // Combine with Read for read/write access. Log.Comment("Create file for testing"); using (FileStream fs = new FileStream(fileName, FileMode.CreateNew)) { FileStreamHelper.WriteReadEmpty(fs); } using (FileStream fs = new FileStream(fileName, FileMode.Open, FileAccess.ReadWrite)) { Log.Comment("Should be able to write"); if (!FileStreamHelper.Write(fs, 1000)) return MFTestResults.Fail; Log.Comment("Should be able to read"); fs.Seek(0, SeekOrigin.Begin); if (!FileStreamHelper.VerifyRead(fs)) return MFTestResults.Fail; Log.Comment("Write after read"); fs.Seek(0, SeekOrigin.End); if (!FileStreamHelper.Write(fs, 500)) return MFTestResults.Fail; } // 300 bytes original + 1000 bytes + 500 bytes if (!FileStreamHelper.VerifyFile(fileName, 1800)) return MFTestResults.Fail; } catch (Exception ex) { Log.Exception("Unexpected exception: " + ex.Message); return MFTestResults.Fail; } return result; } #endregion Test Cases public MFTestMethod[] Tests { get { return new MFTestMethod[] { new MFTestMethod( InvalidArguments, "InvalidArguments" ), new MFTestMethod( FileAccess_Read, "FileAccess_Read" ), new MFTestMethod( FileAccess_Write, "FileAccess_Write" ), new MFTestMethod( FileAccess_ReadWrite, "FileAccess_ReadWrite" ), }; } } } } ================================================ FILE: Zelig/Zelig/FileSystemTest/FileStream/Constructors_FileMode.cs ================================================ //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // Copyright (c) Microsoft Corporation. All rights reserved. //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// using System; using System.IO; namespace FileSystemTest { public class Constructors_FileMode : IMFTestInterface { [SetUp] public InitializeResult Initialize() { // These tests rely on underlying file system so we need to make // sure we can format it before we start the tests. If we can't // format it, then we assume there is no FS to test on this platform. // delete the directory DOTNETMF_FS_EMULATION try { IOTests.IntializeVolume(); Directory.CreateDirectory(TestDir); Directory.SetCurrentDirectory(TestDir); } catch (Exception ex) { Log.Exception("Skipping: Unable to initialize file system " + ex.Message); return InitializeResult.Skip; } return InitializeResult.ReadyToGo; } [TearDown] public void CleanUp() { } #region local vars private const string TestDir = "FileMode"; private const string fileName = "test.tmp"; #endregion local vars #region Helper Methods #endregion Helper Methods #region Test Cases [TestMethod] public MFTestResults InvalidArguments() { MFTestResults result = MFTestResults.Pass; try { try { Log.Comment("Null Filename"); using (FileStream fs = new FileStream(null, FileMode.Create)) { } Log.Exception( "Expected ArgumentNullException" ); return MFTestResults.Fail; } catch (ArgumentNullException ane) { /* pass case */ Log.Comment( "Got correct exception: " + ane.Message ); result = MFTestResults.Pass; } try { Log.Comment("String.Empty Filename"); using (FileStream fs = new FileStream(String.Empty, FileMode.Create)) { } Log.Exception( "Expected ArgumentException" ); return MFTestResults.Fail; } catch (ArgumentException ae) { /* pass case */ Log.Comment( "Got correct exception: " + ae.Message ); result = MFTestResults.Pass; } try { Log.Comment("White Space FileName"); using (FileStream fs = new FileStream(" ", FileMode.Create)) { } Log.Exception( "Expected ArgumentException" ); return MFTestResults.Fail; } catch (ArgumentException ae) { /* pass case */ Log.Comment( "Got correct exception: " + ae.Message ); result = MFTestResults.Pass; } try { Log.Comment(". FileName"); using (FileStream fs = new FileStream(".", FileMode.Create)) { } Log.Exception( "Expected ArgumentException" ); return MFTestResults.Fail; } catch (IOException ioe) { /* pass case */ Log.Comment( "Got correct exception: " + ioe.Message ); result = MFTestResults.Pass; } try { Log.Comment("Use Directory for FileName"); using (FileStream fs = new FileStream(IOTests.Volume.RootDirectory + @"\" + TestDir, FileMode.Create)) { } Log.Exception( "Expected ArgumentException" ); return MFTestResults.Fail; } catch (IOException ioe) { /* pass case */ Log.Comment( "Got correct exception: " + ioe.Message ); result = MFTestResults.Pass; } try { Log.Comment("Bad filemode -1"); using (FileStream fs = new FileStream(fileName, (FileMode)(-1))) { } Log.Exception( "Expected ArgumentException" ); return MFTestResults.Fail; } catch (ArgumentException ae) { /* pass case */ Log.Comment( "Got correct exception: " + ae.Message ); result = MFTestResults.Pass; } try { Log.Comment("Bad filemode 10"); using (FileStream fs = new FileStream(fileName, (FileMode)(10))) { } Log.Exception( "Expected ArgumentException" ); return MFTestResults.Fail; } catch (ArgumentException ae) { /* pass case */ Log.Comment( "Got correct exception: " + ae.Message ); result = MFTestResults.Pass; } try { Log.Comment("Negative buffer"); using (FileStream fs = new FileStream(fileName, FileMode.Create, FileAccess.ReadWrite, FileShare.ReadWrite, -1)) { } Log.Exception( "Expected ArgumentException" ); return MFTestResults.Fail; } catch (ArgumentException ae) { /* pass case */ Log.Comment( "Got correct exception: " + ae.Message ); result = MFTestResults.Pass; } } catch (Exception ex) { Log.Exception("Unexpected exception: " + ex.Message); return MFTestResults.Fail; } return result; } [TestMethod] public MFTestResults FileMode_Append() { // Clean up incase file exists if (File.Exists(fileName)) File.Delete(fileName); MFTestResults result = MFTestResults.Pass; try { // From MSDN: // Opens the file if it exists and seeks to the end of the file, // or creates a new file. FileMode.Append can only be used in // conjunction with FileAccess.Write. Attempting to seek to a position // before the end of the file will throw an IOException and any attempt // to read fails and throws an NotSupportedException. Log.Comment("Non-existent file, should create file"); using (FileStream fs = new FileStream(fileName, FileMode.Append)) { fs.WriteByte((byte)0); fs.WriteByte((byte)1); fs.WriteByte((byte)2); } Log.Comment("Existing file, should seek to end on open"); using (FileStream fs = new FileStream(fileName, FileMode.Append)) { if (fs.Position != 3) { Log.Exception( "Expected postion 3, but got " + fs.Position ); return MFTestResults.Fail; } Log.Comment("Try to Seek before append"); try { fs.Seek(1, SeekOrigin.Begin); Log.Exception( "Unexpectedly able to seek" ); return MFTestResults.Fail; } catch (IOException ioe) { /* pass case */ Log.Comment( "Got correct exception: " + ioe.Message ); result = MFTestResults.Pass; } Log.Comment("Try to read"); try { byte[] buff = new byte[1]; fs.Read(buff, 0, buff.Length); Log.Exception( "Unexpectedly able to read" ); return MFTestResults.Fail; } catch (NotSupportedException nse) { /* pass case */ Log.Comment( "Got correct exception: " + nse.Message ); result = MFTestResults.Pass; } Log.Comment("append to file"); fs.WriteByte((byte)3); fs.WriteByte((byte)4); fs.WriteByte((byte)5); Log.Comment("try to seek to start of append"); fs.Seek(-3, SeekOrigin.End); } if (!FileStreamHelper.VerifyFile(fileName, 6)) return MFTestResults.Fail; } catch (Exception ex) { Log.Exception("Unexpected exception: " + ex.Message); return MFTestResults.Fail; } return result; } [TestMethod] public MFTestResults FileMode_Create() { // Clean up incase file exists if (File.Exists(fileName)) File.Delete(fileName); MFTestResults result = MFTestResults.Pass; try { // From MSDN: // Specifies that the operating system should create a new file. // If the file already exists, it will be overwritten. This requires // FileIOPermissionAccess..::.Write. System.IO.FileMode.Create is // equivalent to requesting that if the file does not exist, use // CreateNew; otherwise, use Truncate. Log.Comment("Non-existent file, should create file"); using (FileStream fs = new FileStream(fileName, FileMode.Create)) { if (!FileStreamHelper.WriteReadEmpty(fs)) return MFTestResults.Fail; // add additional 50 bytes, to test that truncation really happens FileStreamHelper.Write(fs, 50); } Log.Comment("Add Attribute, to verify Truncate behavior"); File.SetAttributes(fileName, FileAttributes.Hidden); Log.Comment("Existing file, should treat as truncate"); using (FileStream fs = new FileStream(fileName, FileMode.Create)) { if (!FileStreamHelper.Write(fs, 300)) return MFTestResults.Fail; Log.Comment("Trying to read file while its open Truncate should fail"); try { using (FileStream fs2 = new FileStream(fileName, FileMode.Open, FileAccess.Read)) { } Log.Exception( "Unexpectedly able to read file" ); return MFTestResults.Fail; } catch (IOException ioe) { /* pass case */ Log.Comment( "Got correct exception: " + ioe.Message ); result = MFTestResults.Pass; } } Log.Comment("Verify hidden property is still set"); FileAttributes fa = File.GetAttributes(fileName); if ((fa & FileAttributes.Hidden) == 0) { Log.Exception( "Expected hidden attribute, but got " + fa ); return MFTestResults.Fail; } // Verify the 300 bytes we wrote (not original 350) if (!FileStreamHelper.VerifyFile(fileName, 300)) return MFTestResults.Fail; } catch (Exception ex) { Log.Exception("Unexpected exception: " + ex.Message); return MFTestResults.Fail; } return result; } [TestMethod] public MFTestResults FileMode_CreateNew() { // Clean up incase file exists if (File.Exists(fileName)) File.Delete(fileName); MFTestResults result = MFTestResults.Pass; try { // From MSDN: // Specifies that the operating system should create a new file. // This requires FileIOPermissionAccess..::.Write. If the file // already exists, an IOException is thrown. Log.Comment("Non-existent file, should create file"); using (FileStream fs = new FileStream(fileName, FileMode.CreateNew)) { if (!FileStreamHelper.WriteReadEmpty(fs)) return MFTestResults.Fail; } if (!FileStreamHelper.VerifyFile(fileName, 300)) return MFTestResults.Fail; try { Log.Comment("Exists file CreateNew"); using (FileStream fs = new FileStream(fileName, FileMode.CreateNew)) { } Log.Exception( "Expected IOException" ); return MFTestResults.Fail; } catch (IOException ioe) { /* pass case */ Log.Comment( "Got correct exception: " + ioe.Message ); result = MFTestResults.Pass; } } catch (Exception ex) { Log.Exception("Unexpected exception: " + ex.Message); return MFTestResults.Fail; } return result; } [TestMethod] public MFTestResults FileMode_Open() { // Clean up incase file exists if (File.Exists(fileName)) File.Delete(fileName); MFTestResults result = MFTestResults.Pass; try { // From MSDN: // Specifies that the operating system should open an existing file. // The ability to open the file is dependent on the value specified // by FileAccess. A System.IO..::.FileNotFoundException is thrown // if the file does not exist. try { Log.Comment("Non-existent file open should throw"); using (FileStream fs = new FileStream(fileName, FileMode.Open)) { } Log.Exception( "Expected IOException" ); return MFTestResults.Fail; } catch (IOException ioe) { /* pass case */ Log.Comment( "Got correct exception: " + ioe.Message ); result = MFTestResults.Pass; } // Create file File.Create(fileName).Close(); Log.Comment("Open existing file"); using (FileStream fs = new FileStream(fileName, FileMode.Open)) { if (!FileStreamHelper.WriteReadEmpty(fs)) return MFTestResults.Fail; } if (!FileStreamHelper.VerifyFile(fileName, 300)) return MFTestResults.Fail; } catch (Exception ex) { Log.Exception("Unexpected exception: " + ex.Message); return MFTestResults.Fail; } return result; } [TestMethod] public MFTestResults FileMode_OpenOrCreate() { // Clean up incase file exists if (File.Exists(fileName)) File.Delete(fileName); MFTestResults result = MFTestResults.Pass; try { // From MSDN: // Specifies that the operating system should open a file if it exists; otherwise, // a new file should be created. If the file is opened with FileAccess.Read, // FileIOPermissionAccess..::.Read is required. If the file access is // FileAccess.Write then FileIOPermissionAccess..::.Write is required. If the file // is opened with FileAccess.ReadWrite, both FileIOPermissionAccess..::.Read and // FileIOPermissionAccess..::.Write are required. If the file access is // FileAccess.Append, then FileIOPermissionAccess..::.Append is required. Log.Comment("Non-existent file, should create file"); using (FileStream fs = new FileStream(fileName, FileMode.OpenOrCreate)) { if (!FileStreamHelper.WriteReadEmpty(fs)) return MFTestResults.Fail; } Log.Comment("Open existing file"); using (FileStream fs = new FileStream(fileName, FileMode.OpenOrCreate)) { if (!FileStreamHelper.WriteReadVerify(fs)) return MFTestResults.Fail; } if (!FileStreamHelper.VerifyFile(fileName, 600)) return MFTestResults.Fail; } catch (Exception ex) { Log.Exception("Unexpected exception: " + ex.Message); return MFTestResults.Fail; } return result; } [TestMethod] public MFTestResults FileMode_Truncate() { // Clean up incase file exists if (File.Exists(fileName)) File.Delete(fileName); MFTestResults result = MFTestResults.Pass; try { // From MSDN: // Specifies that the operating system should open an existing file. // Once opened, the file should be truncated so that its size is zero // bytes. This requires FileIOPermissionAccess..::.Write. Attempts to // read from a file opened with Truncate cause an exception. try { Log.Comment("Non-existent file truncate"); using (FileStream fs = new FileStream(fileName, FileMode.Truncate)) { } Log.Exception( "Expected IOException" ); return MFTestResults.Fail; } catch (IOException ioe) { /* pass case */ Log.Comment( "Got correct exception: " + ioe.Message ); result = MFTestResults.Pass; } Log.Comment("Create a new file and populate"); using (FileStream fs = new FileStream(fileName, FileMode.CreateNew)) { if (!FileStreamHelper.WriteReadVerify(fs)) return MFTestResults.Fail; // add extra bytes, to make sure we really truncate FileStreamHelper.Write(fs, 50); } Log.Comment("Add Attribute, to verify Truncate behavior"); File.SetAttributes(fileName, FileAttributes.Hidden); Log.Comment("Open Truncate"); using (FileStream fs = new FileStream(fileName, FileMode.Truncate)) { if (!FileStreamHelper.WriteReadEmpty(fs)) return MFTestResults.Fail; Log.Comment("Trying to read file while its open Truncate should fail"); try { using (FileStream fs2 = new FileStream(fileName, FileMode.Open, FileAccess.Read)) {} Log.Exception( "Unexpectedly able to read file" ); return MFTestResults.Fail; } catch (IOException ioe) { /* pass case */ Log.Comment( "Got correct exception: " + ioe.Message ); result = MFTestResults.Pass; } } Log.Comment("Verify hidden property is still set"); FileAttributes fa = File.GetAttributes(fileName); if ((fa & FileAttributes.Hidden) == 0) { Log.Exception( "Expected hidden attribute, but got " + fa ); return MFTestResults.Fail; } if (!FileStreamHelper.VerifyFile(fileName, 300)) return MFTestResults.Fail; } catch (Exception ex) { Log.Exception("Unexpected exception: " + ex.Message); return MFTestResults.Fail; } return result; } #endregion Test Cases public MFTestMethod[] Tests { get { return new MFTestMethod[] { new MFTestMethod( InvalidArguments, "InvalidArguments" ), new MFTestMethod( FileMode_Append, "FileMode_Append" ), new MFTestMethod( FileMode_Create, "FileMode_Create" ), new MFTestMethod( FileMode_CreateNew, "FileMode_CreateNew" ), new MFTestMethod( FileMode_Open, "FileMode_Open" ), new MFTestMethod( FileMode_OpenOrCreate, "FileMode_OpenOrCreate" ), new MFTestMethod( FileMode_Truncate, "FileMode_Truncate" ), }; } } } } ================================================ FILE: Zelig/Zelig/FileSystemTest/FileStream/Constructors_FileShare.cs ================================================ //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // Copyright (c) Microsoft Corporation. All rights reserved. //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// using System; using System.IO; using System.Threading; namespace FileSystemTest { public class Constructors_FileShare : IMFTestInterface { [SetUp] public InitializeResult Initialize() { // These tests rely on underlying file system so we need to make // sure we can format it before we start the tests. If we can't // format it, then we assume there is no FS to test on this platform. // delete the directory DOTNETMF_FS_EMULATION try { IOTests.IntializeVolume(); Directory.CreateDirectory(TestDir); Directory.SetCurrentDirectory(TestDir); } catch (Exception ex) { Log.Exception("Skipping: Unable to initialize file system " + ex.Message); return InitializeResult.Skip; } return InitializeResult.ReadyToGo; } [TearDown] public void CleanUp() { } #region local vars private const string TestDir = "FileShare"; private const string fileName = "test.tmp"; private bool threadResult; private bool restricted; public struct MatrixTestCase { public FileShare previousShare; public FileAccess requestedAccess; public FileShare requestedShare; public bool expectSuccess; public MatrixTestCase(FileShare PreviousShare, FileAccess RequestedAccess, FileShare RequestedShare, bool ExpectSuccess) { previousShare = PreviousShare; requestedAccess = RequestedAccess; requestedShare = RequestedShare; expectSuccess = ExpectSuccess; } } #endregion local vars #region Helper methods private void OpenRestrictedFile() { threadResult = false; try { using (FileStream fs = new FileStream(fileName, FileMode.Open, FileAccess.ReadWrite, FileShare.ReadWrite)) { } Log.Exception("No exception! Expected IOException"); } catch (IOException) { /* pass case */ threadResult = true; } catch (Exception ex) { Log.Exception("Expected IOException, but got " + ex.Message); } } private void OpenRead() { try { threadResult &= FileStreamHelper.VerifyFile(fileName); } catch (IOException) { if (!restricted) { threadResult = false; Log.Exception("Unexpected IOException"); } } catch (Exception ex) { threadResult = false; Log.Exception("Unexpected Exception " + ex.Message); } } private void OpenWrite() { try { using (FileStream fs = new FileStream(fileName, FileMode.Open, FileAccess.Write, FileShare.ReadWrite)) { threadResult &= FileStreamHelper.Write(fs, 200); } } catch (IOException) { if (!restricted) { threadResult = false; Log.Exception("Unexpected IOException"); } } catch (Exception ex) { threadResult = false; Log.Exception("Unexpected Exception " + ex.Message); } } private void OpenReadWrite() { threadResult = true; OpenRead(); OpenWrite(); OpenRead(); } #endregion Helper methods #region Test Cases [TestMethod] public MFTestResults InvalidArguments() { MFTestResults result = MFTestResults.Pass; try { try { Log.Comment("Bad fileshare -1"); using (FileStream fs = new FileStream(fileName, FileMode.Create, FileAccess.ReadWrite, (FileShare)(-1))) { } Log.Exception( "Expected ArgumentException" ); return MFTestResults.Fail; } catch (ArgumentException ae) { /* pass case */ Log.Comment( "Got correct exception: " + ae.Message ); result = MFTestResults.Pass; } try { Log.Comment("Bad fileshare 10"); using (FileStream fs = new FileStream(fileName, FileMode.Create, FileAccess.ReadWrite, (FileShare)(10))) { } Log.Exception( "Expected ArgumentException" ); return MFTestResults.Fail; } catch (ArgumentException ae) { /* pass case */ Log.Comment( "Got correct exception: " + ae.Message ); result = MFTestResults.Pass; } } catch (Exception ex) { Log.Exception("Unexpected exception: " + ex.Message); return MFTestResults.Fail; } return result; } [TestMethod] public MFTestResults FileShare_Open_Matrix() { MFTestResults result = MFTestResults.Pass; try { // Given the previous fileshare info and the requested fileaccess and fileshare // the following is the ONLY combinations that we should allow -- All others // should failed with IOException // (Behavior verified on desktop .NET) // // Previous FileShare Requested FileAccess Requested FileShare // Read Read ReadWrite // Write Write ReadWrite // ReadWrite Read ReadWrite // ReadWrite Write ReadWrite // ReadWrite ReadWrite ReadWrite MatrixTestCase[] testCases = new MatrixTestCase[] { // pass cases new MatrixTestCase(FileShare.Read, FileAccess.Read, FileShare.ReadWrite, true), new MatrixTestCase(FileShare.Write, FileAccess.Write, FileShare.ReadWrite, true), new MatrixTestCase(FileShare.ReadWrite, FileAccess.Read, FileShare.ReadWrite, true), new MatrixTestCase(FileShare.ReadWrite, FileAccess.Write, FileShare.ReadWrite, true), new MatrixTestCase(FileShare.ReadWrite, FileAccess.ReadWrite, FileShare.ReadWrite, true), // fail cases new MatrixTestCase(FileShare.Read, FileAccess.Read, FileShare.Read, false), new MatrixTestCase(FileShare.Read, FileAccess.Read, FileShare.Write, false), new MatrixTestCase(FileShare.Read, FileAccess.Read, FileShare.None, false), new MatrixTestCase(FileShare.Read, FileAccess.Write, FileShare.Read, false), new MatrixTestCase(FileShare.Read, FileAccess.Write, FileShare.Write, false), new MatrixTestCase(FileShare.Read, FileAccess.Write, FileShare.ReadWrite, false), new MatrixTestCase(FileShare.Read, FileAccess.Write, FileShare.None, false), new MatrixTestCase(FileShare.Read, FileAccess.ReadWrite, FileShare.Read, false), new MatrixTestCase(FileShare.Read, FileAccess.ReadWrite, FileShare.Write, false), new MatrixTestCase(FileShare.Read, FileAccess.ReadWrite, FileShare.ReadWrite, false), new MatrixTestCase(FileShare.Read, FileAccess.ReadWrite, FileShare.None, false), new MatrixTestCase(FileShare.Write, FileAccess.Read, FileShare.Read, false), new MatrixTestCase(FileShare.Write, FileAccess.Read, FileShare.Write, false), new MatrixTestCase(FileShare.Write, FileAccess.Read, FileShare.ReadWrite, false), new MatrixTestCase(FileShare.Write, FileAccess.Read, FileShare.None, false), new MatrixTestCase(FileShare.Write, FileAccess.Write, FileShare.Read, false), new MatrixTestCase(FileShare.Write, FileAccess.Write, FileShare.Write, false), new MatrixTestCase(FileShare.Write, FileAccess.Write, FileShare.None, false), new MatrixTestCase(FileShare.Write, FileAccess.ReadWrite, FileShare.Read, false), new MatrixTestCase(FileShare.Write, FileAccess.ReadWrite, FileShare.Write, false), new MatrixTestCase(FileShare.Write, FileAccess.ReadWrite, FileShare.ReadWrite, false), new MatrixTestCase(FileShare.Write, FileAccess.ReadWrite, FileShare.None, false), new MatrixTestCase(FileShare.ReadWrite, FileAccess.Read, FileShare.Read, false), new MatrixTestCase(FileShare.ReadWrite, FileAccess.Read, FileShare.Write, false), new MatrixTestCase(FileShare.ReadWrite, FileAccess.Read, FileShare.None, false), new MatrixTestCase(FileShare.ReadWrite, FileAccess.Write, FileShare.Read, false), new MatrixTestCase(FileShare.ReadWrite, FileAccess.Write, FileShare.Write, false), new MatrixTestCase(FileShare.ReadWrite, FileAccess.Write, FileShare.None, false), new MatrixTestCase(FileShare.ReadWrite, FileAccess.ReadWrite, FileShare.Read, false), new MatrixTestCase(FileShare.ReadWrite, FileAccess.ReadWrite, FileShare.Write, false), new MatrixTestCase(FileShare.ReadWrite, FileAccess.ReadWrite, FileShare.None, false), new MatrixTestCase(FileShare.None, FileAccess.Read, FileShare.Read, false), new MatrixTestCase(FileShare.None, FileAccess.Read, FileShare.Write, false), new MatrixTestCase(FileShare.None, FileAccess.Read, FileShare.ReadWrite, false), new MatrixTestCase(FileShare.None, FileAccess.Read, FileShare.None, false), new MatrixTestCase(FileShare.None, FileAccess.Write, FileShare.Read, false), new MatrixTestCase(FileShare.None, FileAccess.Write, FileShare.Write, false), new MatrixTestCase(FileShare.None, FileAccess.Write, FileShare.ReadWrite, false), new MatrixTestCase(FileShare.None, FileAccess.Write, FileShare.None, false), new MatrixTestCase(FileShare.None, FileAccess.ReadWrite, FileShare.Read, false), new MatrixTestCase(FileShare.None, FileAccess.ReadWrite, FileShare.Write, false), new MatrixTestCase(FileShare.None, FileAccess.ReadWrite, FileShare.ReadWrite, false), new MatrixTestCase(FileShare.None, FileAccess.ReadWrite, FileShare.None, false) }; // create file if it doesn't exist. We are just opening, so worries what it contains if (!File.Exists(fileName)) File.Create(fileName).Close(); foreach (MatrixTestCase testcase in testCases) { Log.Comment("Previous share: " + testcase.previousShare); Log.Comment("Requested access: " + testcase.requestedAccess); Log.Comment("Requested share: " + testcase.requestedShare); try { using (FileStream fs = new FileStream(fileName, FileMode.Open, FileAccess.ReadWrite, testcase.previousShare)) { using (FileStream fs2 = new FileStream(fileName, FileMode.Open, testcase.requestedAccess, testcase.requestedShare)) { } if (!testcase.expectSuccess) { Log.Exception("Unexpected IOException - Expected failure"); return MFTestResults.Fail; } else { Log.Comment("Case passes"); } } } catch (IOException) { if (testcase.expectSuccess) { Log.Exception("Unexpected IOException - Expected success"); return MFTestResults.Fail; } } catch (Exception ex) { Log.Exception("Unexpected exception: " + ex.Message); return MFTestResults.Fail; } } } catch (Exception ex) { Log.Exception("Unexpected exception: " + ex.Message); return MFTestResults.Fail; } return result; } [TestMethod] public MFTestResults FileShare_None() { // Clean up incase file exists if (File.Exists(fileName)) File.Delete(fileName); MFTestResults result = MFTestResults.Pass; try { // From MSDN: // Declines sharing of the current file. Any request to open the file // (by this process or another process) will fail until the file is closed. Log.Comment("Create file for testing"); using (FileStream fs = new FileStream(fileName, FileMode.CreateNew)) { FileStreamHelper.WriteReadEmpty(fs); } using (FileStream fs = new FileStream(fileName, FileMode.Open, FileAccess.ReadWrite, FileShare.None)) { Log.Comment("Should be able to write"); if (!FileStreamHelper.Write(fs, 1000)) return MFTestResults.Fail; Log.Comment("Should be able to read"); fs.Seek(0, SeekOrigin.Begin); if (!FileStreamHelper.VerifyRead(fs)) return MFTestResults.Fail; Log.Comment("Try to open in same thread"); try { using (FileStream fs2 = new FileStream(fileName, FileMode.Open, FileAccess.Read, FileShare.ReadWrite)) { } Log.Exception( "FileAccess.Read - Expected IOException" ); return MFTestResults.Fail; } catch (IOException ioe) { /* pass case */ Log.Comment( "Got correct exception: " + ioe.Message ); result = MFTestResults.Pass; } try { using (FileStream fs2 = new FileStream(fileName, FileMode.Open, FileAccess.Write, FileShare.ReadWrite)) { } Log.Exception( "FileAccess.Write - Expected IOException" ); return MFTestResults.Fail; } catch (IOException ioe) { /* pass case */ Log.Comment( "Got correct exception: " + ioe.Message ); result = MFTestResults.Pass; } Log.Comment( "Try to open in another thread" ); Thread worker = new Thread( OpenRestrictedFile ); worker.Start(); worker.Join(); if(!threadResult) return MFTestResults.Fail; Log.Comment("Write after read other access attempt"); fs.Seek(0, SeekOrigin.End); if (!FileStreamHelper.Write(fs, 500)) return MFTestResults.Fail; } // 300 bytes original + 1000 bytes + 500 bytes if (!FileStreamHelper.VerifyFile(fileName, 1800)) return MFTestResults.Fail; } catch (Exception ex) { Log.Exception("Unexpected exception: " + ex.Message); return MFTestResults.Fail; } return result; } [TestMethod] public MFTestResults FileShare_Read() { // Clean up incase file exists if (File.Exists(fileName)) File.Delete(fileName); MFTestResults result = MFTestResults.Pass; try { // From MSDN: // Declines sharing of the current file. Any request to open the file // (by this process or another process) will fail until the file is closed. Log.Comment("Create file for testing"); using (FileStream fs = new FileStream(fileName, FileMode.CreateNew)) { FileStreamHelper.WriteReadEmpty(fs); } using (FileStream fs = new FileStream(fileName, FileMode.Open, FileAccess.ReadWrite, FileShare.Read)) { Log.Comment("Should be able to write"); if (!FileStreamHelper.Write(fs, 1000)) return MFTestResults.Fail; Log.Comment("Should be able to read"); fs.Seek(0, SeekOrigin.Begin); if (!FileStreamHelper.VerifyRead(fs)) return MFTestResults.Fail; Log.Comment("Try to Read in same thread"); if (!FileStreamHelper.VerifyFile(fileName)) return MFTestResults.Fail; Log.Comment("Try to Read in another thread"); restricted = false; threadResult = true; Thread worker = new Thread( OpenRead ); worker.Start(); worker.Join(); if(!threadResult) return MFTestResults.Fail; Log.Comment("Try to Write in same thread"); try { using (FileStream fs2 = new FileStream(fileName, FileMode.Open, FileAccess.Write, FileShare.ReadWrite)) { } Log.Exception( "Expected IOException" ); return MFTestResults.Fail; } catch (IOException ioe) { /* pass case */ Log.Comment( "Got correct exception: " + ioe.Message ); } Log.Comment("Try to Write in another thread"); restricted = true; threadResult = true; worker = new Thread(OpenWrite); worker.Start(); worker.Join(); if (!threadResult) return MFTestResults.Fail; Log.Comment("Write after read other access attempt"); fs.Seek(0, SeekOrigin.End); if (!FileStreamHelper.Write(fs, 500)) return MFTestResults.Fail; } Log.Comment("Verify file after close - 300 bytes original + 1000 bytes + 500 bytes"); if (!FileStreamHelper.VerifyFile(fileName, 1800)) return MFTestResults.Fail; } catch (Exception ex) { Log.Exception("Unexpected exception: " + ex.Message); return MFTestResults.Fail; } return result; } [TestMethod] public MFTestResults FileShare_ReadWrite() { // Clean up incase file exists if (File.Exists(fileName)) File.Delete(fileName); MFTestResults result = MFTestResults.Pass; try { // From MSDN: // Allows subsequent opening of the file for reading or writing. If this // flag is not specified, any request to open the file for reading or // writing (by this process or another process) will fail until the file // is closed. However, even if this flag is specified, additional // permissions might still be needed to access the file. // 300 bytes Log.Comment("Create file for testing"); using (FileStream fs = new FileStream(fileName, FileMode.CreateNew)) { FileStreamHelper.WriteReadEmpty(fs); } using (FileStream fs = new FileStream(fileName, FileMode.Open, FileAccess.ReadWrite, FileShare.ReadWrite)) { // 1000 bytes Log.Comment("Should be able to write"); if (!FileStreamHelper.Write(fs, 1000)) return MFTestResults.Fail; Log.Comment("Should be able to read"); fs.Seek(0, SeekOrigin.Begin); if (!FileStreamHelper.VerifyRead(fs)) return MFTestResults.Fail; Log.Comment("Try to Read in same thread"); if (!FileStreamHelper.VerifyFile(fileName)) return MFTestResults.Fail; Log.Comment("Try to Read in another thread"); restricted = false; threadResult = true; Thread worker = new Thread( OpenRead ); worker.Start(); worker.Join(); if(!threadResult) return MFTestResults.Fail; // 500 bytes Log.Comment("Try to Write in same thread"); using (FileStream fs2 = new FileStream(fileName, FileMode.Open, FileAccess.Write, FileShare.ReadWrite)) { FileStreamHelper.Write(fs2, 500); } // 200 bytes Log.Comment("Try to Write in another thread"); restricted = false; threadResult = true; worker = new Thread( OpenWrite ); worker.Start(); worker.Join(); if(!threadResult) return MFTestResults.Fail; // 300 bytes Log.Comment("Try to ReadWrite"); using (FileStream fs2 = new FileStream(fileName, FileMode.Open, FileAccess.ReadWrite, FileShare.ReadWrite)) { if (!FileStreamHelper.WriteReadVerify(fs2)) return MFTestResults.Fail; } // 500 bytes Log.Comment("Write after read other access attempt"); fs.Seek(0, SeekOrigin.End); if (!FileStreamHelper.Write(fs, 500)) return MFTestResults.Fail; } // 300 + 1000 + 500 + 200 + 300 + 500 = 2800 Log.Comment("Verify file after close"); if (!FileStreamHelper.VerifyFile(fileName, 2800)) return MFTestResults.Fail; } catch (Exception ex) { Log.Exception("Unexpected exception: " + ex.Message); return MFTestResults.Fail; } return result; } [TestMethod] public MFTestResults FileShare_Write() { // Clean up incase file exists if (File.Exists(fileName)) File.Delete(fileName); MFTestResults result = MFTestResults.Pass; try { // From MSDN: // Allows subsequent opening of the file for writing. If this flag // is not specified, any request to open the file for writing (by // this process or another process) will fail until the file is // closed. However, even if this flag is specified, additional // permissions might still be needed to access the file. // 300 bytes Log.Comment("Create file for testing"); using (FileStream fs = new FileStream(fileName, FileMode.CreateNew)) { FileStreamHelper.WriteReadEmpty(fs); } using (FileStream fs = new FileStream(fileName, FileMode.Open, FileAccess.ReadWrite, FileShare.Write)) { // 1000 bytes Log.Comment("Should be able to write"); if (!FileStreamHelper.Write(fs, 1000)) return MFTestResults.Fail; Log.Comment("Should be able to read"); fs.Seek(0, SeekOrigin.Begin); if (!FileStreamHelper.VerifyRead(fs)) return MFTestResults.Fail; Log.Comment("Try to Read in same thread"); try { using (FileStream fs2 = new FileStream(fileName, FileMode.Open, FileAccess.Read, FileShare.ReadWrite)) { } Log.Exception( "FileAccess.Read - Expected IOException" ); return MFTestResults.Fail; } catch (IOException ioe) { /* pass case */ Log.Comment( "Got correct exception: " + ioe.Message ); } Log.Comment("Try to Read in another thread"); restricted = true; threadResult = true; Thread worker = new Thread( OpenRead ); worker.Start(); worker.Join(); if(!threadResult) return MFTestResults.Fail; // 500 bytes Log.Comment("Try to Write in same thread"); using (FileStream fs2 = new FileStream(fileName, FileMode.Open, FileAccess.Write, FileShare.ReadWrite)) { FileStreamHelper.Write(fs2, 500); } // 200 bytes Log.Comment("Try to Write in another thread"); restricted = false; threadResult = true; worker = new Thread( OpenWrite ); worker.Start(); worker.Join(); if(!threadResult) return MFTestResults.Fail; // 500 bytes Log.Comment("Write after read other access attempt"); fs.Seek(0, SeekOrigin.End); if (!FileStreamHelper.Write(fs, 500)) return MFTestResults.Fail; } // 300 + 1000 + 500 + 200 500 = 2500 Log.Comment("Verify file after close"); if (!FileStreamHelper.VerifyFile(fileName, 2500)) return MFTestResults.Fail; } catch (Exception ex) { Log.Exception("Unexpected exception: " + ex.Message); return MFTestResults.Fail; } return result; } #endregion Test Cases public MFTestMethod[] Tests { get { return new MFTestMethod[] { new MFTestMethod( InvalidArguments, "InvalidArguments" ), new MFTestMethod( FileShare_Open_Matrix, "FileShare_Open_Matrix" ), new MFTestMethod( FileShare_None, "FileShare_None" ), new MFTestMethod( FileShare_Read, "FileShare_Read" ), new MFTestMethod( FileShare_ReadWrite, "FileShare_ReadWrite" ), new MFTestMethod( FileShare_Write, "FileShare_Write" ), }; } } } } ================================================ FILE: Zelig/Zelig/FileSystemTest/FileStream/FileStreamHelper.cs ================================================ //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // Copyright (c) Microsoft Corporation. All rights reserved. //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// using System; using System.IO; namespace FileSystemTest { public class FileStreamHelper { public static bool VerifyFile(string file) { return VerifyFile(file, -1); } public static bool VerifyFile(string file, long length) { bool result = true; Log.Comment("Open file and verify appended data"); using (FileStream fs = new FileStream(file, FileMode.Open, FileAccess.Read, FileShare.ReadWrite)) { // -1 means ignore length check if (length == -1) length = fs.Length; if (fs.Length != length) { result = false; Log.Exception("Expected length of " + length + " but got " + fs.Length); } result &= VerifyRead(fs); } return result; } public static bool WriteReadEmpty(FileStream fs) { bool result = true; if (fs.Position != 0) { result = false; Log.Exception("Expected postion 0, but got " + fs.Position); } if (fs.Length != 0) { result = false; Log.Exception("Expected length 0, but got " + fs.Position); } return WriteReadVerify(fs) & result; } public static bool WriteReadVerify(FileStream fs) { bool result = Write(fs, 300); // Flush writes fs.Flush(); Log.Comment("Seek to start and Read"); fs.Seek(0, SeekOrigin.Begin); result &= VerifyRead(fs); return result; } public static bool Write(FileStream fs, int length) { bool result = true; long startLength = fs.Length; // we can only write 0-255, so mod the // length to figure out next data value byte data = (byte)(startLength & 0xFF); byte[] d2 = new byte[length]; Log.Comment("Seek to end"); fs.Seek(0, SeekOrigin.End); Log.Comment("Write to file"); int j = 0; for (long i = startLength; i < startLength + length; i++) { d2[j++] = (byte)data++; } fs.Write( d2, 0, length ); return result; } public static bool VerifyRead(FileStream fs) { bool result = true; Log.Comment("Verify " + fs.Length + " bytes of data in file"); // we can only read 0-255, so mod the // position to figure out next data value byte nextbyte = (byte)(fs.Position & 0xFF); byte[] data = new byte[fs.Length]; fs.Read( data, 0, (int)fs.Length ); for (int i = 0; i < fs.Length; i++) { int readByte = data[i]; if (readByte != nextbyte) { result = false; Log.Exception("Byte in position " + i + " has wrong value: " + readByte); } nextbyte++; } return result; } } } ================================================ FILE: Zelig/Zelig/FileSystemTest/FileStream/FileStreamTests.cs ================================================ /*--------------------------------------------------------------------- * FileTests.cs - file description * Version: 1.0 * Author: REDMOND\a-grchat * Created: 9/12/2007 4:51:10 PM * * Tests the basic functionality of Socket objects * ---------------------------------------------------------------------*/ using System; using System.Text; using System.Reflection; using System.IO; namespace FileSystemTest { public class FileStreamTests : IMFTestInterface { private const String randomString = @"This is an unusual paragraph. I'm curious how quickly you can find out what is so unusual about it. It looks so plain you would think nothing was wrong with it. In fact, nothing is wrong with it! It is unusual though. Study it, and think about it, but you still may not find anything odd. But if you work at it a bit, you might find out! Try to do so without any coaching! You probably won't, at first, find anything particularly odd or unusual or in any way dissimilar to any ordinary composition. That is not at all surprising, for it is no strain to accomplish in so short a paragraph a stunt similar to that which an author did throughout all of his book, without spoiling a good writing job, and it was no small book at that. By studying this paragraph assiduously, you will shortly, I trust, know what is its distinguishing oddity. Upon locating that 'mark of distinction,' you will probably doubt my story of this author and his book of similar unusuality throughout. It is commonly known among book-conscious folk and proof of it is still around. If you must know, this sort of writing is known as a lipogram, but don't look up that word in any dictionary until you find out what this is all about."; static byte[] randomBytes = System.Text.Encoding.UTF8.GetBytes(randomString); [SetUp] public InitializeResult Initialize() { Log.Comment("The following tests are located in FileStreamTests.cs"); // delete the directory DOTNETMF_FS_EMULATION try { IOTests.IntializeVolume(); } catch { Log.Comment("Unable to format media, skipping class tests."); return InitializeResult.Skip; } return InitializeResult.ReadyToGo; } [TearDown] public void CleanUp() { } private void CreateFile(String path) { FileStream fs = new FileStream(path, FileMode.Create); fs.Write(randomBytes, 0, randomBytes.Length); fs.Close(); } [TestMethod] public MFTestResults Basic_Behavior() { const string file = "foo.txt"; MFTestResults result = MFTestResults.Pass; try { const string content = "Hello, World!"; StreamWriter sw = new StreamWriter(file); sw.Write(content); sw.Close(); try { sw.Write("cannot write this"); return MFTestResults.Fail; } catch (ObjectDisposedException) { result = MFTestResults.Pass; Log.Exception("Disposed Stream cannot be written"); } //--// StreamReader sr = new StreamReader(file); char[] buffer = new char[13]; int read = sr.Read(buffer, 0, buffer.Length); sr.Close(); try { int readAfter = 0; readAfter = sr.Read(buffer, buffer.Length, 1); if (readAfter != 0) { throw new Exception("cannot read after the StreamReader is closed"); } } catch (ObjectDisposedException) { result = MFTestResults.Pass; Log.Exception("Disposed Stream cannot be read"); } string readContent = new string(buffer); if (readContent != content) { result = MFTestResults.Fail; } } catch (Exception ex) { Log.Exception("Unexpected Exception", ex); result = MFTestResults.Fail; } finally { try { File.Delete(file); } catch { } } return result; } //--// [TestMethod] public MFTestResults Basic_Read_Int() { const string file = "foo.txt"; MFTestResults result = MFTestResults.Pass; try { const string content = "Hello, World!"; StreamWriter sw = new StreamWriter(file); sw.Write(content); sw.Close(); //--// StreamReader sr = new StreamReader(file); char[] buffer = new char[13]; int read = sr.Read(buffer, 0, buffer.Length); sr.Close(); result = MFTestResults.Pass; string readContent = new string(buffer); if (readContent != content) { result = MFTestResults.Fail; } } catch (Exception ex) { Log.Exception("Unexpected Exception", ex); result = MFTestResults.Fail; } finally { try { File.Delete(file); } catch { } } return result; } [TestMethod] public MFTestResults Basic_ReadBlock() { const string file = "foo.txt"; MFTestResults result = MFTestResults.Pass; try { const string content = "Hello, World!"; StreamWriter sw = new StreamWriter(file); sw.Write(content); sw.Close(); //--// StreamReader sr = new StreamReader(file); char[] buffer = new char[13]; int read = sr.ReadBlock(buffer, 0, buffer.Length); sr.Close(); string readContent = new string(buffer); result = MFTestResults.Pass; if (readContent != content) { result = MFTestResults.Fail; } } catch (Exception ex) { Log.Exception("Unexpected Exception", ex); result = MFTestResults.Fail; } finally { try { File.Delete(file); } catch { } } return result; } //--// [TestMethod] public MFTestResults Basic_ReadToEnd() { const string file = "foo.txt"; MFTestResults result = MFTestResults.Pass; try { const string content = "Hello, World!"; StreamWriter sw = new StreamWriter(file); sw.Write(content); sw.Close(); //--// StreamReader sr = new StreamReader(file); string readContent = sr.ReadToEnd(); sr.Close(); result = MFTestResults.Pass; if (readContent != content) { result = MFTestResults.Fail; } } catch (Exception ex) { Log.Exception("Unexpected Exception", ex); result = MFTestResults.Fail; } finally { try { File.Delete(file); } catch { } } return result; } [TestMethod] public MFTestResults Basic_ReadToEnd_Long() { const string file = "foo.txt"; MFTestResults result = MFTestResults.Pass; try { string veryShortString = "Hello, World!"; string fourKBString = "This is 4KB long!, This is 4KB long!, This is 4KB long!, This is 4KB long!, This is 4KB long!, This is 4KB long!, This is 4KB long!, This is 4KB long!, This is 4KB long!, This is 4KB long!, This is 4KB long!, This is 4KB long!, This is 4KB long!, This is 4KB long!, This is 4KB long!, This is 4KB long!, This is 4KB long!, This is 4KB long!, This is 4KB long!, This is 4KB long!, This is 4KB long!, This is 4KB long!, This is 4KB long!, This is 4KB long!, This is 4KB long!, This is 4KB long!, This is 4KB long!, This is 4KB long!, This is 4KB long!, This is 4KB long!, This is 4KB long!, This is 4KB long!, This is 4KB long!, This is 4KB long!, This is 4KB long!, This is 4KB long!, This is 4KB long!, This is 4KB long!, This is 4KB long!, This is 4KB long!, This is 4KB long!, This is 4KB long!, This is 4KB long!, This is 4KB long!, This is 4KB long!, This is 4KB long!, This is 4KB long!, This is 4KB long!, This is 4KB long!, This is 4KB long!, This is 4KB long!, This is 4KB long!, This is 4KB long!, This is 4KB long!, This is 4KB long!, This is 4KB long!, This is 4KB long!, This is 4KB long!, This is 4KB long!, This is 4KB long!, This is 4KB long!, This is 4KB long!, This is 4KB long!, This is 4KB long!, This is 4KB long!, This is 4KB long!, This is 4KB long!, This is 4KB long!, This is 4KB long!, This is 4KB long!, This is 4KB long!, This is 4KB long!, This is 4KB long!, This is 4KB long!, This is 4KB long!, This is 4KB long!, This is 4KB long!, This is 4KB long!, This is 4KB long!, This is 4KB long!, This is 4KB long!, This is 4KB long!, This is 4KB long!, This is 4KB long!, This is 4KB long!, This is 4KB long!, This is 4KB long!, This is 4KB long!, This is 4KB long!, This is 4KB long!, This is 4KB long!, This is 4KB long!, This is 4KB long!, This is 4KB long!, This is 4KB long!, This is 4KB long!, This is 4KB long!, This is 4KB long!, This is 4KB long!, This is 4KB long!, This is 4KB long!, This is 4KB long!, This is 4KB long!, This is 4KB long!, This is 4KB long!, This is 4KB long!, This is 4KB long!, This is 4KB long!, This is 4KB long!, This is 4KB long!, This is 4KB long!, This is 4KB long!, This is 4KB long!, This is 4KB long!, This is 4KB long!, This is 4KB long!, This is 4KB long!, This is 4KB long!, This is 4KB long!, This is 4KB long!, This is 4KB long!, This is 4KB long!, This is 4KB long!, This is 4KB long!, This is 4KB long!, This is 4KB long!, This is 4KB long!, This is 4KB long!, This is 4KB long!, This is 4KB long!, This is 4KB long!, This is 4KB long!, This is 4KB long!, This is 4KB long!, This is 4KB long!, This is 4KB long!, This is 4KB long!, This is 4KB long!, This is 4KB long!, This is 4KB long!, This is 4KB long!, This is 4KB long!, This is 4KB long!, This is 4KB long!, This is 4KB long!, This is 4KB long!, This is 4KB long!, This is 4KB long!, This is 4KB long!, This is 4KB long!, This is 4KB long!, This is 4KB long!, This is 4KB long!, This is 4KB long!, This is 4KB long!, This is 4KB long!, This is 4KB long!, This is 4KB long!"; string sixKBStringString = "Instead this one is 6KB long!, Instead this one is 6KB long!, Instead this one is 6KB long!, Instead this one is 6KB long!, Instead this one is 6KB long!, Instead this one is 6KB long!, Instead this one is 6KB long!, Instead this one is 6KB long!, Instead this one is 6KB long!, Instead this one is 6KB long!, Instead this one is 6KB long!, Instead this one is 6KB long!, Instead this one is 6KB long!, Instead this one is 6KB long!, Instead this one is 6KB long!, Instead this one is 6KB long!, Instead this one is 6KB long!, Instead this one is 6KB long!, Instead this one is 6KB long!, Instead this one is 6KB long!, Instead this one is 6KB long!, Instead this one is 6KB long!, Instead this one is 6KB long!, Instead this one is 6KB long!, Instead this one is 6KB long!, Instead this one is 6KB long!, Instead this one is 6KB long!, Instead this one is 6KB long!, Instead this one is 6KB long!, Instead this one is 6KB long!, Instead this one is 6KB long!, Instead this one is 6KB long!, Instead this one is 6KB long!, Instead this one is 6KB long!, Instead this one is 6KB long!, Instead this one is 6KB long!, Instead this one is 6KB long!, Instead this one is 6KB long!, Instead this one is 6KB long!, Instead this one is 6KB long!, Instead this one is 6KB long!, Instead this one is 6KB long!, Instead this one is 6KB long!, Instead this one is 6KB long!, Instead this one is 6KB long!, Instead this one is 6KB long!, Instead this one is 6KB long!, Instead this one is 6KB long!, Instead this one is 6KB long!, Instead this one is 6KB long!, Instead this one is 6KB long!, Instead this one is 6KB long!, Instead this one is 6KB long!, Instead this one is 6KB long!, Instead this one is 6KB long!, Instead this one is 6KB long!, Instead this one is 6KB long!, Instead this one is 6KB long!, Instead this one is 6KB long!, Instead this one is 6KB long!, Instead this one is 6KB long!, Instead this one is 6KB long!, Instead this one is 6KB long!, Instead this one is 6KB long!, Instead this one is 6KB long!, Instead this one is 6KB long!, Instead this one is 6KB long!, Instead this one is 6KB long!, Instead this one is 6KB long!, Instead this one is 6KB long!, Instead this one is 6KB long!, Instead this one is 6KB long!, Instead this one is 6KB long!, Instead this one is 6KB long!, Instead this one is 6KB long!, Instead this one is 6KB long!, Instead this one is 6KB long!, Instead this one is 6KB long!, Instead this one is 6KB long!, Instead this one is 6KB long!, Instead this one is 6KB long!, Instead this one is 6KB long!, Instead this one is 6KB long!, Instead this one is 6KB long!, Instead this one is 6KB long!, Instead this one is 6KB long!, Instead this one is 6KB long!, Instead this one is 6KB long!, Instead this one is 6KB long!, Instead this one is 6KB long!, Instead this one is 6KB long!, Instead this one is 6KB long!, Instead this one is 6KB long!, Instead this one is 6KB long!, Instead this one is 6KB long!, Instead this one is 6KB long!, Instead this one is 6KB long!, Instead this one is 6KB long!, Instead this one is 6KB long!, Instead this one is 6KB long!, Instead this one is 6KB long!, Instead this one is 6KB long!, Instead this one is 6KB long!, Instead this one is 6KB long!, Instead this one is 6KB long!, Instead this one is 6KB long!, Instead this one is 6KB long!, Instead this one is 6KB long!, Instead this one is 6KB long!, Instead this one is 6KB long!, Instead this one is 6KB long!, Instead this one is 6KB long!, Instead this one is 6KB long!, Instead this one is 6KB long!, Instead this one is 6KB long!, Instead this one is 6KB long!, Instead this one is 6KB long!, Instead this one is 6KB long!, Instead this one is 6KB long!, Instead this one is 6KB long!, Instead this one is 6KB long!, Instead this one is 6KB long!, Instead this one is 6KB long!, Instead this one is 6KB long!, Instead this one is 6KB long!, Instead this one is 6KB long!, Instead this one is 6KB long!, Instead this one is 6KB long!, Instead this one is 6KB long!, Instead this one is 6KB long!, Instead this one is 6KB long!, Instead this one is 6KB long!, Instead this one is 6KB long!, Instead this one is 6KB long!, Instead this one is 6KB long!, Instead this one is 6KB long!, Instead this one is 6KB long!, Instead this one is 6KB long!, Instead this one is 6KB long!, Instead this one is 6KB long!, Instead this one is 6KB long!, Instead this one is 6KB long!, Instead this one is 6KB long!, Instead this one is 6KB long!, Instead this one is 6KB long!, Instead this one is 6KB long!, Instead this one is 6KB long!, Instead this one is 6KB long!, Instead this one is 6KB long!, Instead this one is 6KB long!, Instead this one is 6KB long!, Instead this one is 6KB long!"; string all_string_original = veryShortString + fourKBString + sixKBStringString + veryShortString + fourKBString + sixKBStringString + veryShortString + fourKBString + sixKBStringString; FileStream fs = new FileStream(file, FileMode.CreateNew); byte[] veryShortStringBytes = Encoding.UTF8.GetBytes(veryShortString); byte[] fourKBStringBytes = Encoding.UTF8.GetBytes(fourKBString); byte[] sixKBStringBytes = Encoding.UTF8.GetBytes(sixKBStringString); fs.Write(veryShortStringBytes, 0, veryShortStringBytes.Length); fs.Flush(); fs.Write(fourKBStringBytes, 0, fourKBStringBytes.Length); fs.Flush(); fs.Write(sixKBStringBytes, 0, sixKBStringBytes.Length); fs.Flush(); //--// fs.Write(veryShortStringBytes, 0, veryShortStringBytes.Length); fs.Flush(); fs.Write(fourKBStringBytes, 0, fourKBStringBytes.Length); fs.Flush(); fs.Write(sixKBStringBytes, 0, sixKBStringBytes.Length); fs.Flush(); //--// fs.Write(veryShortStringBytes, 0, veryShortStringBytes.Length); fs.Flush(); fs.Write(fourKBStringBytes, 0, fourKBStringBytes.Length); fs.Flush(); fs.Write(sixKBStringBytes, 0, sixKBStringBytes.Length); fs.Flush(); fs.Dispose(); StreamReader sr = new StreamReader(file); string all_text = sr.ReadToEnd(); Log.Comment("all_text length : " + all_text.Length); Log.Comment("all_string_original length: " + all_string_original.Length); result = MFTestResults.Pass; if (all_text != all_string_original) { result = MFTestResults.Fail; } sr.Close(); return result; } catch (OutOfMemoryException ex) { Log.Exception("OutOfMemoryException exception, this device is too small", ex); result = MFTestResults.Pass; } catch (Exception ex) { Log.Exception("Unexpected Exception", ex); result = MFTestResults.Fail; } finally { try { File.Delete(file); } catch { } } return result; } [TestMethod] public MFTestResults Basic_ReadLine() { const string file = "foo.txt"; MFTestResults result = MFTestResults.Pass; try { const string content = "Hello, World!"; StreamWriter sw = new StreamWriter(file); sw.WriteLine(content); sw.Close(); //--// StreamReader sr = new StreamReader(file); string readContent = sr.ReadLine(); sr.Close(); result = MFTestResults.Pass; if (readContent != content) { result = MFTestResults.Fail; } } catch (Exception ex) { Log.Exception("Unexpected Exception", ex); } finally { try { File.Delete(file); } catch { } } return result; } [TestMethod] public MFTestResults FileStreamTest_ReadWrite0a() { Directory.SetCurrentDirectory(IOTests.Volume.RootDirectory); return ReadWrite0(); } private MFTestResults ReadWrite0() { try { FileStream fs = new FileStream("ReadWrite0.txt", FileMode.CreateNew); fs.Write(randomBytes, 0, randomBytes.Length); fs.Close(); fs = new FileStream("ReadWrite0.txt", FileMode.Open); byte[] readBack = new byte[randomBytes.Length]; fs.Read(readBack, 0, randomBytes.Length); fs.Close(); for (int i = 0; i < 50; i++) { if(randomBytes[i] != readBack[i]) { throw new Exception(); } } return MFTestResults.Pass; } catch (Exception ex) { Log.Exception("Unexpected Exception", ex); return MFTestResults.Fail; } } [TestMethod] public MFTestResults FileStreamTest_Seek0() { try { CreateFile("Seek0.txt"); FileStream fs = new FileStream("Seek0.txt", FileMode.Open, FileAccess.Read); byte[] readBack = new byte[10]; int pos = (int)fs.Seek(-20, SeekOrigin.End); if(randomBytes.Length - 20 != pos) throw new Exception(); fs.Read(readBack, 0, 10); for (int i = 0; i < 10; i++) { if(randomBytes[randomBytes.Length - 20 + i] != readBack[i]) throw new Exception(); } pos = (int)fs.Seek(5, SeekOrigin.Current); if(randomBytes.Length - 5 != pos) throw new Exception(); pos = (int)fs.Seek(10, SeekOrigin.Begin); if(10 != pos) throw new Exception(); fs.Read(readBack, 0, 10); for (int i = 0; i < 10; i++) { if(randomBytes[10 + i] != readBack[i]) throw new Exception(); } fs.Close(); return MFTestResults.Pass; } catch (Exception ex) { Log.Exception("Unexpected Exception", ex); return MFTestResults.Fail; } } private class FileAccessAndFileShare { public FileShare File1Share; public FileAccess File2Access; public FileShare File2Share; public bool ShouldPass; public FileAccessAndFileShare(FileShare file1Share, FileAccess file2Access, FileShare file2Share, bool shouldPass) { File1Share = file1Share; File2Access = file2Access; File2Share = file2Share; ShouldPass = shouldPass; } public override string ToString() { return "File1: " + FileShareToString(File1Share) + " File2: " + FileAccessToString(File2Access) + " " + FileShareToString(File2Share); } private String FileShareToString(FileShare fs) { switch (fs) { case FileShare.None: return "FileShare.None"; case FileShare.Read: return "FileShare.Read"; case FileShare.Write: return "FileShare.Write"; case FileShare.ReadWrite: return "FileShare.ReadWrite"; } return ""; } private String FileAccessToString(FileAccess fa) { switch (fa) { case FileAccess.Read: return "FileAccess.Read"; case FileAccess.ReadWrite: return "FileAccess.ReadWrite"; case FileAccess.Write: return "FileAccess.Write"; } return ""; } } [TestMethod] public MFTestResults FileStreamTest_FileAccessAndFileShare() { FileAccessAndFileShare[] fafs = { new FileAccessAndFileShare(FileShare.None, FileAccess.Read, FileShare.None, false), new FileAccessAndFileShare(FileShare.None, FileAccess.Read, FileShare.Read, false), new FileAccessAndFileShare(FileShare.None, FileAccess.Read, FileShare.Write, false), new FileAccessAndFileShare(FileShare.None, FileAccess.Read, FileShare.ReadWrite, false), new FileAccessAndFileShare(FileShare.None, FileAccess.Write, FileShare.None, false), new FileAccessAndFileShare(FileShare.None, FileAccess.Write, FileShare.Read, false), new FileAccessAndFileShare(FileShare.None, FileAccess.Write, FileShare.Write, false), new FileAccessAndFileShare(FileShare.None, FileAccess.Write, FileShare.ReadWrite, false), new FileAccessAndFileShare(FileShare.None, FileAccess.ReadWrite, FileShare.None, false), new FileAccessAndFileShare(FileShare.None, FileAccess.ReadWrite, FileShare.Read, false), new FileAccessAndFileShare(FileShare.None, FileAccess.ReadWrite, FileShare.Write, false), new FileAccessAndFileShare(FileShare.None, FileAccess.ReadWrite, FileShare.ReadWrite, false), new FileAccessAndFileShare(FileShare.Read, FileAccess.Read, FileShare.None, false), new FileAccessAndFileShare(FileShare.Read, FileAccess.Read, FileShare.Read, false), new FileAccessAndFileShare(FileShare.Read, FileAccess.Read, FileShare.Write, false), new FileAccessAndFileShare(FileShare.Read, FileAccess.Read, FileShare.ReadWrite, true), new FileAccessAndFileShare(FileShare.Read, FileAccess.Write, FileShare.None, false), new FileAccessAndFileShare(FileShare.Read, FileAccess.Write, FileShare.Read, false), new FileAccessAndFileShare(FileShare.Read, FileAccess.Write, FileShare.Write, false), new FileAccessAndFileShare(FileShare.Read, FileAccess.Write, FileShare.ReadWrite, false), new FileAccessAndFileShare(FileShare.Read, FileAccess.ReadWrite, FileShare.None, false), new FileAccessAndFileShare(FileShare.Read, FileAccess.ReadWrite, FileShare.Read, false), new FileAccessAndFileShare(FileShare.Read, FileAccess.ReadWrite, FileShare.Write, false), new FileAccessAndFileShare(FileShare.Read, FileAccess.ReadWrite, FileShare.ReadWrite, false), new FileAccessAndFileShare(FileShare.Write, FileAccess.Read, FileShare.None, false), new FileAccessAndFileShare(FileShare.Write, FileAccess.Read, FileShare.Read, false), new FileAccessAndFileShare(FileShare.Write, FileAccess.Read, FileShare.Write, false), new FileAccessAndFileShare(FileShare.Write, FileAccess.Read, FileShare.ReadWrite, false), new FileAccessAndFileShare(FileShare.Write, FileAccess.Write, FileShare.None, false), new FileAccessAndFileShare(FileShare.Write, FileAccess.Write, FileShare.Read, false), new FileAccessAndFileShare(FileShare.Write, FileAccess.Write, FileShare.Write, false), new FileAccessAndFileShare(FileShare.Write, FileAccess.Write, FileShare.ReadWrite, true), new FileAccessAndFileShare(FileShare.Write, FileAccess.ReadWrite, FileShare.None, false), new FileAccessAndFileShare(FileShare.Write, FileAccess.ReadWrite, FileShare.Read, false), new FileAccessAndFileShare(FileShare.Write, FileAccess.ReadWrite, FileShare.Write, false), new FileAccessAndFileShare(FileShare.Write, FileAccess.ReadWrite, FileShare.ReadWrite, false), new FileAccessAndFileShare(FileShare.ReadWrite, FileAccess.Read, FileShare.None, false), new FileAccessAndFileShare(FileShare.ReadWrite, FileAccess.Read, FileShare.Read, false), new FileAccessAndFileShare(FileShare.ReadWrite, FileAccess.Read, FileShare.Write, false), new FileAccessAndFileShare(FileShare.ReadWrite, FileAccess.Read, FileShare.ReadWrite, true), new FileAccessAndFileShare(FileShare.ReadWrite, FileAccess.Write, FileShare.None, false), new FileAccessAndFileShare(FileShare.ReadWrite, FileAccess.Write, FileShare.Read, false), new FileAccessAndFileShare(FileShare.ReadWrite, FileAccess.Write, FileShare.Write, false), new FileAccessAndFileShare(FileShare.ReadWrite, FileAccess.Write, FileShare.ReadWrite, true), new FileAccessAndFileShare(FileShare.ReadWrite, FileAccess.ReadWrite, FileShare.None, false), new FileAccessAndFileShare(FileShare.ReadWrite, FileAccess.ReadWrite, FileShare.Read, false), new FileAccessAndFileShare(FileShare.ReadWrite, FileAccess.ReadWrite, FileShare.Write, false), new FileAccessAndFileShare(FileShare.ReadWrite, FileAccess.ReadWrite, FileShare.ReadWrite, true), }; bool pass = true; for (int i = 0; i < fafs.Length; i++) { FileStream fs1 = null, fs2 = null; try { Log.Comment("Trying " + fafs[i].ToString()); fs1 = new FileStream(IOTests.Volume.RootDirectory + "\\abc.txt", FileMode.OpenOrCreate, FileAccess.ReadWrite, fafs[i].File1Share); fs2 = new FileStream(IOTests.Volume.RootDirectory + "\\abc.txt", FileMode.OpenOrCreate, fafs[i].File2Access, fafs[i].File2Share); if (fafs[i].ShouldPass == false) { Log.Comment("Should fail, but didn't"); pass = false; } } catch (Exception ex) { if (fafs[i].ShouldPass == true) { Log.Exception("Should pass, but didn't", ex); pass = false; } } finally { if (fs1 != null) fs1.Close(); if (fs2 != null) fs2.Close(); } } return (pass)? MFTestResults.Pass : MFTestResults.Fail; } public MFTestMethod[] Tests { get { return new MFTestMethod[] { new MFTestMethod( Basic_Behavior, "Basic_Behavior" ), new MFTestMethod( Basic_Read_Int, "Basic_Read_Int" ), new MFTestMethod( Basic_ReadBlock, "Basic_ReadBlock" ), new MFTestMethod( Basic_ReadToEnd, "Basic_ReadToEnd" ), new MFTestMethod( Basic_ReadToEnd_Long, "Basic_ReadToEnd_Long" ), new MFTestMethod( Basic_ReadLine, "Basic_ReadLine" ), new MFTestMethod( FileStreamTest_ReadWrite0a, "FileStreamTest_ReadWrite0a" ), new MFTestMethod( FileStreamTest_Seek0, "FileStreamTest_Seek0" ), new MFTestMethod( FileStreamTest_FileAccessAndFileShare, "FileStreamTest_FileAccessAndFileShare" ), }; } } } } ================================================ FILE: Zelig/Zelig/FileSystemTest/FileStream/Flush.cs ================================================ //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // Copyright (c) Microsoft Corporation. All rights reserved. //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// using System; using System.IO; namespace FileSystemTest { public class Flush : IMFTestInterface { [SetUp] public InitializeResult Initialize() { // These tests rely on underlying file system so we need to make // sure we can format it before we start the tests. If we can't // format it, then we assume there is no FS to test on this platform. // delete the directory DOTNETMF_FS_EMULATION try { IOTests.IntializeVolume(); Directory.CreateDirectory(TestDir); Directory.SetCurrentDirectory(TestDir); } catch (Exception ex) { Log.Exception("Skipping: Unable to initialize file system " + ex.Message); return InitializeResult.Skip; } return InitializeResult.ReadyToGo; } [TearDown] public void CleanUp() { } #region local vars private const string TestDir = "Flush"; private const string fileName = "test.tmp"; private const string sourceFile = "test.src"; #endregion local vars #region Test Cases [TestMethod] public MFTestResults Flush_Closed() { // Clean up incase file exists if (File.Exists(fileName)) File.Delete(fileName); MFTestResults result = MFTestResults.Pass; try { FileStream fs = new FileStream(fileName, FileMode.Create); FileStreamHelper.Write(fs, 500); fs.Close(); try { fs.Flush(); } catch (ObjectDisposedException ode) { /* pass case */ Log.Comment( "Got correct exception: " + ode.Message ); result = MFTestResults.Pass; } } catch (Exception ex) { // previous Bug# 21655 Log.Exception("Unexpected exception: " + ex.Message); return MFTestResults.Fail; } return result; } [TestMethod] public MFTestResults Flush_WriteByte() { // Clean up incase file exists if (File.Exists(fileName)) File.Delete(fileName); MFTestResults result = MFTestResults.Pass; try { Log.Comment("Verify flush of 5000k using WriteByte"); using (FileStream fs = new FileStream(sourceFile, FileMode.CreateNew)) { FileStreamHelper.Write(fs, 5000); fs.Flush(); if (fs.Length != 5000) { Log.Comment( "Expected 5000 bytes in file" ); return MFTestResults.Fail; } fs.Seek(0, SeekOrigin.Begin); if (!FileStreamHelper.VerifyRead(fs)) return MFTestResults.Fail; } } catch (Exception ex) { Log.Exception("Unexpected exception: " + ex.Message); return MFTestResults.Fail; } return result; } [TestMethod] public MFTestResults Flush_Write() { Log.Comment("This test case requires the previous test case to write a properly formatted 5k file"); if (!FileStreamHelper.VerifyFile(sourceFile, 5000)) return MFTestResults.Skip; MFTestResults result = MFTestResults.Pass; try { // read bytes from source file byte[] data = File.ReadAllBytes(sourceFile); using (FileStream fs = new FileStream(fileName, FileMode.CreateNew)) { fs.Write(data, 0, data.Length); fs.Flush(); if (fs.Length != 5000) { Log.Comment( "Expected 5000 bytes in file" ); return MFTestResults.Fail; } fs.Seek(0, SeekOrigin.Begin); if (!FileStreamHelper.VerifyRead(fs)) return MFTestResults.Fail; } } catch (Exception ex) { Log.Exception("Unexpected exception: " + ex.Message); return MFTestResults.Fail; } return result; } #endregion Test Cases public MFTestMethod[] Tests { get { return new MFTestMethod[] { new MFTestMethod( Flush_Closed, "Flush_Closed" ), new MFTestMethod( Flush_WriteByte, "Flush_WriteByte" ), new MFTestMethod( Flush_Write, "Flush_Write" ), }; } } } } ================================================ FILE: Zelig/Zelig/FileSystemTest/FileStream/PropertyTests.cs ================================================ //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // Copyright (c) Microsoft Corporation. All rights reserved. //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// using System; using System.IO; namespace FileSystemTest { public class PropertyTests : IMFTestInterface { [SetUp] public InitializeResult Initialize() { // These tests rely on underlying file system so we need to make // sure we can format it before we start the tests. If we can't // format it, then we assume there is no FS to test on this platform. // delete the directory DOTNETMF_FS_EMULATION try { IOTests.IntializeVolume(); Directory.CreateDirectory(TestDir); Directory.SetCurrentDirectory(TestDir); } catch (Exception ex) { Log.Exception("Skipping: Unable to initialize file system " + ex.Message); return InitializeResult.Skip; } return InitializeResult.ReadyToGo; } [TearDown] public void CleanUp() { } #region local vars private const string TestDir = "Length"; private const string fileName = "test.tmp"; #endregion local vars #region Helper methods private bool TestLength(FileStream fs, long expectedLength) { if (fs.Length != expectedLength) { Log.Exception("Expected length " + expectedLength + " but got, " + fs.Length); return false; } return true; } private bool TestPosition(FileStream fs, long expectedPosition) { if (fs.Position != expectedPosition) { Log.Exception("Expected position " + expectedPosition + " but got, " + fs.Position); return false; } return true; } #endregion Helper methods #region Test Cases [TestMethod] public MFTestResults ObjectDisposed() { if (File.Exists(fileName)) File.Delete(fileName); FileStream fs = new FileStream(fileName, FileMode.Create); fs.Close(); MFTestResults result = MFTestResults.Pass; try { try { long length = fs.Length; Log.Exception( "Expected ObjectDisposedException, but got length " + length ); return MFTestResults.Fail; } catch (ObjectDisposedException) { /*Pass Case */ result = MFTestResults.Pass; } try { long position = fs.Position; Log.Exception( "Expected ObjectDisposedException, but got position " + position ); return MFTestResults.Fail; } catch (ObjectDisposedException) { /*Pass Case */ result = MFTestResults.Pass; } try { fs.Position = 0; Log.Exception( "Expected ObjectDisposedException, but set position" ); return MFTestResults.Fail; } catch (ObjectDisposedException) { /*Pass Case */ result = MFTestResults.Pass; } } catch (Exception ex) { Log.Exception("Unexpected exception: " + ex.Message); return MFTestResults.Fail; } return result; } [TestMethod] public MFTestResults LengthTests() { MFTestResults result = MFTestResults.Pass; if (File.Exists(fileName)) File.Delete(fileName); try { using (FileStream fs = new FileStream(fileName, FileMode.Create)) { Log.Comment("Set initial length to 50, and position to 50"); fs.SetLength(50); fs.Position = 50; if (!TestLength(fs, 50)) return MFTestResults.Fail; Log.Comment("Write 'foo bar'"); StreamWriter sw = new StreamWriter(fs); sw.Write("foo bar"); sw.Flush(); if (!TestLength(fs, 57)) return MFTestResults.Fail; Log.Comment("Shorten Length to 30"); fs.SetLength(30); if (!TestLength(fs, 30)) return MFTestResults.Fail; Log.Comment("Verify position was adjusted"); if (!TestPosition(fs, 30)) return MFTestResults.Fail; Log.Comment("Extend length to 100"); fs.SetLength(100); if (!TestLength(fs, 100)) return MFTestResults.Fail; } Log.Comment("Verify file is 100 bytes after close"); using (FileStream fs = new FileStream(fileName, FileMode.Open)) { if (!TestLength(fs, 100)) return MFTestResults.Fail; } } catch (Exception ex) { Log.Exception("Unexpected exception: " + ex.Message); return MFTestResults.Fail; } return result; } [TestMethod] public MFTestResults InvalidSetLength() { MFTestResults result = MFTestResults.Pass; if (File.Exists(fileName)) File.Delete(fileName); try { using (FileStream fs = new FileStream(fileName, FileMode.CreateNew)) { try { Log.Comment("-1"); fs.SetLength(-1); Log.Exception( "Expected ArgumentOutOfRangeException, but set length" ); return MFTestResults.Fail; } catch (ArgumentOutOfRangeException aoore) { /* pass case */ Log.Comment( "Got correct exception: " + aoore.Message ); result = MFTestResults.Pass; } try { Log.Comment("-10000"); fs.SetLength(-10000); Log.Exception( "Expected ArgumentOutOfRangeException, but set length" ); return MFTestResults.Fail; } catch (ArgumentOutOfRangeException aoore) { /* pass case */ Log.Comment( "Got correct exception: " + aoore.Message ); result = MFTestResults.Pass; } try { Log.Comment("long.MinValue"); fs.SetLength(long.MinValue); Log.Exception( "Expected ArgumentOutOfRangeException, but set length" ); return MFTestResults.Fail; } catch (ArgumentOutOfRangeException aoore) { /* pass case */ Log.Comment( "Got correct exception: " + aoore.Message ); result = MFTestResults.Pass; } try { Log.Comment("long.MaxValue"); fs.SetLength(long.MaxValue); Log.Exception( "Expected IOException, but set length" ); return MFTestResults.Fail; } catch (ArgumentOutOfRangeException aoore) { /* pass case */ Log.Comment( "Got correct exception: " + aoore.Message ); result = MFTestResults.Pass; } } } catch (Exception ex) { Log.Exception("Unexpected exception: " + ex.Message); return MFTestResults.Fail; } return result; } [TestMethod] public MFTestResults NameTests() { MFTestResults result = MFTestResults.Pass; if (File.Exists(fileName)) File.Delete(fileName); try { FileStream fs = new FileStream(fileName, FileMode.CreateNew); Log.Comment("Verify name while open"); if (fs.Name != Directory.GetCurrentDirectory() + @"\" + fileName) { Log.Exception( "Unexpected File name: " + fs.Name ); return MFTestResults.Fail; } Log.Comment("Verify name after close"); fs.Close(); if (fs.Name != Directory.GetCurrentDirectory() + @"\" + fileName) { Log.Exception( "Unexpected File name: " + fs.Name ); return MFTestResults.Fail; } } catch (Exception ex) { Log.Exception("Unexpected exception: " + ex.Message); return MFTestResults.Fail; } return result; } #endregion Test Cases public MFTestMethod[] Tests { get { return new MFTestMethod[] { new MFTestMethod( ObjectDisposed, "ObjectDisposed" ), new MFTestMethod( LengthTests, "LengthTests" ), new MFTestMethod( InvalidSetLength, "InvalidSetLength" ), new MFTestMethod( NameTests, "NameTests" ), }; } } } } ================================================ FILE: Zelig/Zelig/FileSystemTest/FileStream/Read.cs ================================================ //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // Copyright (c) Microsoft Corporation. All rights reserved. //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// using System; using System.IO; using System.Text; namespace FileSystemTest { public class Read : IMFTestInterface { [SetUp] public InitializeResult Initialize() { // These tests rely on underlying file system so we need to make // sure we can format it before we start the tests. If we can't // format it, then we assume there is no FS to test on this platform. // delete the directory DOTNETMF_FS_EMULATION try { IOTests.IntializeVolume(); Directory.CreateDirectory(TestDir); Directory.SetCurrentDirectory(TestDir); } catch (Exception ex) { Log.Exception("Skipping: Unable to initialize file system " + ex.Message); return InitializeResult.Skip; } return InitializeResult.ReadyToGo; } [TearDown] public void CleanUp() { } #region local vars private const string TestDir = "Read"; private const string fileName = "test.tmp"; #endregion local vars #region Local Helper methods private bool TestRead(FileStream fs, int length) { return TestRead(fs, length, length, length); } private bool TestRead(FileStream fs, int BufferLength, int BytesToRead, int BytesExpected) { bool result = true; byte nextbyte = (byte)(fs.Position & 0xFF); byte[] byteBuffer = new byte[BufferLength]; int bytesRead = fs.Read(byteBuffer, 0, BytesToRead); if (bytesRead != BytesExpected) { result = false; Log.Exception("Expected " + BytesToRead + " bytes, but got " + bytesRead + " bytes"); } for (int i = 0; i < bytesRead; i++) { if (byteBuffer[i] != nextbyte) { result = false; Log.Exception("Byte in position " + i + " has wrong value: " + byteBuffer[i]); } nextbyte++; } return result; } #endregion Local Helper methods #region Test Cases [TestMethod] public MFTestResults InvalidCases() { if (File.Exists(fileName)) File.Delete(fileName); FileStream fs = new FileStream(fileName, FileMode.Create); FileStreamHelper.Write(fs, 1000); fs.Seek(0, SeekOrigin.Begin); byte[] readbuff = new byte[1024]; MFTestResults result = MFTestResults.Pass; try { try { Log.Comment("Read to null buffer"); int read = fs.Read(null, 0, readbuff.Length); Log.Exception( "Expected ArgumentNullException, but got " + read + " + bytes" ); return MFTestResults.Fail; } catch (ArgumentNullException ane) { /* pass case */ Log.Comment( "Got correct exception: " + ane.Message ); result = MFTestResults.Pass; } try { Log.Comment("Read to negative offset"); int read = fs.Read(readbuff, -1, readbuff.Length); Log.Exception( "Expected ArgumentOutOfRangeException, but got " + read + " + bytes" ); return MFTestResults.Fail; } catch (ArgumentOutOfRangeException aoore) { /* pass case */ Log.Comment( "Got correct exception: " + aoore.Message ); result = MFTestResults.Pass; } try { Log.Comment("Read to out of range offset"); int read = fs.Read(readbuff, readbuff.Length + 1, readbuff.Length); Log.Exception( "Expected ArgumentException, but got " + read + " + bytes" ); return MFTestResults.Fail; } catch (ArgumentException ae) { /* pass case */ Log.Comment( "Got correct exception: " + ae.Message ); result = MFTestResults.Pass; } try { Log.Comment("Read negative count"); int read = fs.Read(readbuff, 0, -1); Log.Exception( "Expected ArgumentOutOfRangeException, but got " + read + " + bytes" ); return MFTestResults.Fail; } catch (ArgumentOutOfRangeException aoore) { /* pass case */ Log.Comment( "Got correct exception: " + aoore.Message ); result = MFTestResults.Pass; } try { Log.Comment("Read count larger then buffer"); int read = fs.Read(readbuff, 0, readbuff.Length + 1); Log.Exception( "Expected ArgumentException, but got " + read + " + bytes" ); return MFTestResults.Fail; } catch (ArgumentException ae) { /* pass case */ Log.Comment( "Got correct exception: " + ae.Message ); result = MFTestResults.Pass; } try { Log.Comment("Read closed stream"); fs.Close(); int read = fs.Read(readbuff, 0, readbuff.Length); Log.Exception( "Expected ObjectDisposedException, but got " + read + " + bytes" ); return MFTestResults.Fail; } catch (ObjectDisposedException ode) { /* pass case */ Log.Comment( "Got correct exception: " + ode.Message ); result = MFTestResults.Pass; } try { Log.Comment("Read disposed stream"); fs = new FileStream(fileName, FileMode.Open); fs.Dispose(); int read = fs.Read(readbuff, 0, readbuff.Length); Log.Exception( "Expected ObjectDisposedException, but got " + read + " + bytes" ); return MFTestResults.Fail; } catch (ObjectDisposedException ode) { /* pass case */ Log.Comment( "Got correct exception: " + ode.Message ); result = MFTestResults.Pass; } } catch (Exception ex) { Log.Exception("Unexpected exception: " + ex.Message); return MFTestResults.Fail; } finally { if (fs != null) fs.Dispose(); } return result; } [TestMethod] public MFTestResults VanillaRead() { if (File.Exists(fileName)) File.Delete(fileName); using (FileStream fs = new FileStream(fileName, FileMode.Create)) { FileStreamHelper.Write(fs, 1000); } MFTestResults result = MFTestResults.Pass; try { using (FileStream fs = new FileStream(fileName, FileMode.Open, FileAccess.ReadWrite)) { Log.Comment("Read 256 bytes of data"); if (!TestRead(fs, 256)) return MFTestResults.Fail; Log.Comment("Request less bytes then buffer"); if (!TestRead(fs, 256, 100, 100)) return MFTestResults.Fail; // 1000 - 256 - 100 = 644 Log.Comment("Request more bytes then file"); if (!TestRead(fs, 1000, 1000, 644)) return MFTestResults.Fail; Log.Comment("Request bytes after EOF"); if (!TestRead(fs, 100, 100, 0)) return MFTestResults.Fail; Log.Comment("Rewind and read entire file in one buffer larger then file"); fs.Seek(0, SeekOrigin.Begin); if (!TestRead(fs, 1001, 1001, 1000)) return MFTestResults.Fail; Log.Comment("Verify Read validation with UTF8 string"); fs.SetLength(0); string test = "MFFramework Test"; fs.Write(UTF8Encoding.UTF8.GetBytes(test), 0, test.Length); fs.Flush(); fs.Seek(0, SeekOrigin.Begin); byte[] readbuff = new byte[20]; int readlen = fs.Read(readbuff, 0, readbuff.Length); string testResult = new string(Encoding.UTF8.GetChars(readbuff, 0, readlen)); if (test != testResult) { Log.Comment( "Exepected: " + test + ", but got: " + testResult ); return MFTestResults.Fail; } } } catch (Exception ex) { Log.Exception("Unexpected exception: " + ex.Message); return MFTestResults.Fail; } return result; } #endregion Test Cases public MFTestMethod[] Tests { get { return new MFTestMethod[] { new MFTestMethod( InvalidCases, "InvalidCases" ), new MFTestMethod( VanillaRead, "VanillaRead" ), }; } } } } ================================================ FILE: Zelig/Zelig/FileSystemTest/FileStream/Seek.cs ================================================ //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // Copyright (c) Microsoft Corporation. All rights reserved. //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// using System; using System.IO; namespace FileSystemTest { public class Seek : IMFTestInterface { [SetUp] public InitializeResult Initialize() { // These tests rely on underlying file system so we need to make // sure we can format it before we start the tests. If we can't // format it, then we assume there is no FS to test on this platform. // delete the directory DOTNETMF_FS_EMULATION try { IOTests.IntializeVolume(); Directory.CreateDirectory(TestDir); Directory.SetCurrentDirectory(TestDir); } catch (Exception ex) { Log.Exception("Skipping: Unable to initialize file system " + ex.Message); return InitializeResult.Skip; } return InitializeResult.ReadyToGo; } [TearDown] public void CleanUp() { } #region local vars private const string TestDir = "Seek"; private const string fileName = "test.tmp"; #endregion local vars #region Helper methods private bool TestSeek(FileStream fs, long offset, SeekOrigin origin, long expectedPosition) { bool result = true; long seek = fs.Seek(offset, origin); if (seek != fs.Position && seek != expectedPosition) { result = false; Log.Exception("Unexpected seek results!"); Log.Exception("Expected position: " + expectedPosition); Log.Exception("Seek result: " + seek); Log.Exception("fs.Position: " + fs.Position); } return result; } private bool TestExtend(FileStream fs, long offset, SeekOrigin origin, long expectedPosition, long expectedLength) { bool result = TestSeek(fs, offset, origin, expectedLength); fs.WriteByte(1); if (fs.Length != expectedLength) { result = false; Log.Exception("Expected seek past end to change length to " + expectedLength + ", but its " + fs.Length); } return result; } #endregion Helper methods #region Test Cases [TestMethod] public MFTestResults InvalidCases() { if (File.Exists(fileName)) File.Delete(fileName); FileStream fs = new FileStream(fileName, FileMode.Create); FileStreamHelper.Write(fs, 1000); long seek; MFTestResults result = MFTestResults.Pass; try { try { Log.Comment("Seek -1 from Begin"); seek = fs.Seek(-1, SeekOrigin.Begin); Log.Exception( "Expected IOException, but got position " + seek ); return MFTestResults.Fail; } catch (IOException ioe) { /* pass case */ Log.Comment( "Got correct exception: " + ioe.Message ); result = MFTestResults.Pass; } try { Log.Comment("Seek -1001 from Current - at end from write"); seek = fs.Seek(-1001, SeekOrigin.Current); Log.Exception( "Expected IOException, but got position " + seek ); return MFTestResults.Fail; } catch (IOException ioe) { /* pass case */ Log.Comment( "Got correct exception: " + ioe.Message ); result = MFTestResults.Pass; } try { Log.Comment("Seek -1001 from End"); seek = fs.Seek(-1001, SeekOrigin.End); Log.Exception( "Expected IOException, but got position " + seek ); return MFTestResults.Fail; } catch (IOException ioe) { /* pass case */ Log.Comment( "Got correct exception: " + ioe.Message ); result = MFTestResults.Pass; } try { Log.Comment("Seek invalid -1 origin"); seek = fs.Seek(1, (SeekOrigin)(-1)); Log.Exception( "Expected ArgumentException, but got position " + seek ); return MFTestResults.Fail; } catch (ArgumentException ae) { /* pass case */ Log.Comment( "Got correct exception: " + ae.Message ); result = MFTestResults.Pass; } try { Log.Comment("Seek invalid 10 origin"); seek = fs.Seek(1, (SeekOrigin)10); Log.Exception( "Expected ArgumentException, but got position " + seek ); return MFTestResults.Fail; } catch (ArgumentException ae) { /* pass case */ Log.Comment( "Got correct exception: " + ae.Message ); result = MFTestResults.Pass; } try { Log.Comment("Seek with closed socket"); fs.Close(); seek = fs.Seek(0, SeekOrigin.Begin); Log.Exception( "Expected ObjectDisposedException, but got position " + seek ); return MFTestResults.Fail; } catch (ObjectDisposedException ode) { /* pass case */ Log.Comment( "Got correct exception: " + ode.Message ); result = MFTestResults.Pass; } try { Log.Comment("Seek with disposed socket"); fs.Dispose(); seek = fs.Seek(0, SeekOrigin.End); Log.Exception( "Expected ObjectDisposedException, but got position " + seek ); return MFTestResults.Fail; } catch (ObjectDisposedException ode) { /* pass case */ Log.Comment( "Got correct exception: " + ode.Message ); result = MFTestResults.Pass; } } catch (Exception ex) { Log.Exception("Unexpected exception: " + ex.Message); return MFTestResults.Fail; } finally { if (fs != null) fs.Dispose(); } return result; } [TestMethod] public MFTestResults ValidCases() { MFTestResults result = MFTestResults.Pass; try { if (File.Exists(fileName)) File.Delete(fileName); using (FileStream fs = new FileStream(fileName, FileMode.Create)) { FileStreamHelper.Write(fs, 1000); Log.Comment("Seek to beginning"); if (!TestSeek(fs, 0, SeekOrigin.Begin, 0)) return MFTestResults.Fail; Log.Comment("Seek forward offset from begging"); if (!TestSeek(fs, 10, SeekOrigin.Begin, 0)) return MFTestResults.Fail; Log.Comment("Seek backwards offset from current"); if (!TestSeek(fs, -5, SeekOrigin.Current, 5)) return MFTestResults.Fail; Log.Comment("Seek forwards offset from current"); if (!TestSeek(fs, 20, SeekOrigin.Current, 25)) return MFTestResults.Fail; Log.Comment("Seek to end"); if (!TestSeek(fs, 0, SeekOrigin.End, 1000)) return MFTestResults.Fail; Log.Comment("Seek backwards offset from end"); if (!TestSeek(fs, -35, SeekOrigin.End, 965)) return MFTestResults.Fail; Log.Comment("Seek past end relative to End"); if (!TestExtend(fs, 1, SeekOrigin.End, 1001, 1002)) return MFTestResults.Fail; Log.Comment("Seek past end relative to Begin"); if (!TestExtend(fs, 1002, SeekOrigin.Begin, 1002, 1003)) return MFTestResults.Fail; Log.Comment("Seek past end relative to Current"); if (!TestSeek(fs, 995, SeekOrigin.Begin, 995)) return MFTestResults.Fail; if (!TestExtend(fs, 10, SeekOrigin.Current, 1005, 1006)) return MFTestResults.Fail; // 1000 --123456 // verify 011001 Log.Comment("Verify proper bytes written at end (zero'd bytes from seek beyond end)"); byte[] buff = new byte[6]; byte[] verify = new byte[] { 0, 1, 1, 0, 0, 1 }; fs.Seek(-6, SeekOrigin.End); fs.Read(buff, 0, buff.Length); for (int i = 0; i < buff.Length; i++) { if (buff[i] != verify[i]) { Log.Comment( "Position " + i + ":" + buff[i] + " != " + verify[i] ); return MFTestResults.Fail; } } } } catch (Exception ex) { Log.Exception("Unexpected exception: " + ex.Message); return MFTestResults.Fail; } return result; } #endregion Test Cases public MFTestMethod[] Tests { get { return new MFTestMethod[] { new MFTestMethod( InvalidCases, "InvalidCases" ), new MFTestMethod( ValidCases, "ValidCases" ), }; } } } } ================================================ FILE: Zelig/Zelig/FileSystemTest/FileStream/Write.cs ================================================ //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // Copyright (c) Microsoft Corporation. All rights reserved. //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// using System; using System.Text; using System.IO; namespace FileSystemTest { public class Write : IMFTestInterface { [SetUp] public InitializeResult Initialize() { // These tests rely on underlying file system so we need to make // sure we can format it before we start the tests. If we can't // format it, then we assume there is no FS to test on this platform. // delete the directory DOTNETMF_FS_EMULATION try { IOTests.IntializeVolume(); Directory.CreateDirectory(TestDir); Directory.SetCurrentDirectory(TestDir); } catch (Exception ex) { Log.Exception("Skipping: Unable to initialize file system " + ex.Message); return InitializeResult.Skip; } return InitializeResult.ReadyToGo; } [TearDown] public void CleanUp() { } #region local vars private const string TestDir = "Write"; private const string fileName = "test.tmp"; #endregion local vars #region Local Helper methods private bool TestWrite(FileStream fs, int length) { return TestWrite(fs, length, length, 0); } private bool TestWrite(FileStream fs, int BufferLength, int BytesToWrite, int Offset) { bool result = true; long startLength = fs.Position; byte nextbyte = (byte)(startLength & 0xFF); byte[] byteBuffer = new byte[BufferLength]; for (int i = Offset; i < (Offset + BytesToWrite); i++) { byteBuffer[i] = (byte)nextbyte; nextbyte++; } fs.Write(byteBuffer, Offset, BytesToWrite); fs.Flush(); if ((startLength + BytesToWrite) < fs.Length) { result = false; Log.Exception("Expeceted final length of " + (startLength + BytesToWrite) + " bytes, but got " + fs.Length + " bytes"); } return result; } #endregion Local Helper methods #region Test Cases [TestMethod] public MFTestResults InvalidCases() { if (File.Exists(fileName)) File.Delete(fileName); FileStream fs = new FileStream(fileName, FileMode.Create); byte[] writebuff = new byte[1024]; MFTestResults result = MFTestResults.Pass; try { try { Log.Comment("Write to null buffer"); fs.Write(null, 0, writebuff.Length); Log.Exception( "Expected ArgumentNullException" ); return MFTestResults.Fail; } catch (ArgumentNullException ane) { /* pass case */ Log.Comment( "Got correct exception: " + ane.Message ); result = MFTestResults.Pass; } try { Log.Comment("Write to negative offset"); fs.Write(writebuff, -1, writebuff.Length); Log.Exception( "Expected ArgumentOutOfRangeException" ); return MFTestResults.Fail; } catch (ArgumentOutOfRangeException aoore) { /* pass case */ Log.Comment( "Got correct exception: " + aoore.Message ); result = MFTestResults.Pass; } try { Log.Comment("Write to out of range offset"); fs.Write(writebuff, writebuff.Length + 1, writebuff.Length); Log.Exception( "Expected ArgumentException" ); return MFTestResults.Fail; } catch (ArgumentException ae) { /* pass case */ Log.Comment( "Got correct exception: " + ae.Message ); result = MFTestResults.Pass; } try { Log.Comment("Write negative count"); fs.Write(writebuff, 0, -1); // previous Bug # 21669 Log.Exception( "Expected ArgumentOutOfRangeException" ); return MFTestResults.Fail; } catch (ArgumentOutOfRangeException aoore) { /* pass case */ Log.Comment( "Got correct exception: " + aoore.Message ); result = MFTestResults.Pass; } try { Log.Comment("Write count larger then buffer"); fs.Write(writebuff, 0, writebuff.Length + 1); Log.Exception( "Expected ArgumentException" ); return MFTestResults.Fail; } catch (ArgumentException ae) { /* pass case */ Log.Comment( "Got correct exception: " + ae.Message ); result = MFTestResults.Pass; } try { Log.Comment("Write closed stream"); fs.Close(); fs.Write(writebuff, 0, writebuff.Length); Log.Exception( "Expected ObjectDisposedException" ); return MFTestResults.Fail; } catch (ObjectDisposedException ode) { /* pass case */ Log.Comment( "Got correct exception: " + ode.Message ); result = MFTestResults.Pass; } try { Log.Comment("Write disposed stream"); fs = new FileStream(fileName, FileMode.Open); fs.Dispose(); fs.Write(writebuff, 0, writebuff.Length); Log.Exception( "Expected ObjectDisposedException" ); return MFTestResults.Fail; } catch (ObjectDisposedException ode) { /* pass case */ Log.Comment( "Got correct exception: " + ode.Message ); result = MFTestResults.Pass; } } catch (Exception ex) { Log.Exception("Unexpected exception: " + ex.Message); return MFTestResults.Fail; } finally { if (fs != null) fs.Dispose(); } return result; } [TestMethod] public MFTestResults VanillaWrite() { if (File.Exists(fileName)) File.Delete(fileName); MFTestResults result = MFTestResults.Pass; try { using (FileStream fs = new FileStream(fileName, FileMode.CreateNew)) { Log.Comment("Write 256 bytes of data"); if (!TestWrite(fs, 256)) return MFTestResults.Fail; Log.Comment("Write middle of buffer"); if (!TestWrite(fs, 256, 100, 100)) return MFTestResults.Fail; // 1000 - 256 - 100 = 644 Log.Comment("Write start of buffer"); if (!TestWrite(fs, 1000, 644, 0)) return MFTestResults.Fail; Log.Comment("Write end of buffer"); if (!TestWrite(fs, 1000, 900, 100)) return MFTestResults.Fail; Log.Comment("Rewind and verify all bytes written"); fs.Seek(0, SeekOrigin.Begin); if (!FileStreamHelper.VerifyRead(fs)) return MFTestResults.Fail; Log.Comment("Verify Read validation with UTF8 string"); fs.SetLength(0); string test = "MFFramework Test"; fs.Write(UTF8Encoding.UTF8.GetBytes(test), 0, test.Length); fs.Flush(); fs.Seek(0, SeekOrigin.Begin); byte[] readbuff = new byte[20]; int readlen = fs.Read(readbuff, 0, readbuff.Length); string testResult = new string(Encoding.UTF8.GetChars(readbuff, 0, readlen)); if (test != testResult) { Log.Comment( "Exepected: " + test + ", but got: " + testResult ); return MFTestResults.Fail; } } } catch (Exception ex) { Log.Exception("Unexpected exception: " + ex.Message); return MFTestResults.Fail; } return result; } #endregion Test Cases public MFTestMethod[] Tests { get { return new MFTestMethod[] { new MFTestMethod( InvalidCases, "InvalidCases" ), new MFTestMethod( VanillaWrite, "VanillaWrite" ), }; } } } } ================================================ FILE: Zelig/Zelig/FileSystemTest/FileSystemTest.csproj ================================================  Debug AnyCPU 8.0.30703 2.0 {C165CC46-A458-478B-9167-F073EED35EB2} Exe Properties FileSystemTest FileSystemTest v4.5 512 true full false $(LlilumBuildRoot)\Target\bin\$(Configuration)\ DEBUG;TRACE prompt 4 AnyCPU true true true false pdbonly true $(LlilumBuildRoot)\Target\bin\$(Configuration)\ TRACE prompt 4 true AnyCPU true false $(LlilumBuildRoot)\Target\bin\$(Configuration)\ true DEBUG;TRACE AnyCPU true true false {186F31A3-EF89-4A25-B2D5-20060501AA01} mscorlib False {186F31A3-EF89-4A25-B2D5-20070702AA01} system False {186F31A3-EF89-4A25-B2D5-20061218AA01} Common False {186F31A3-EF89-4A25-B2D5-20060509AA01} Kernel False {186F31A3-EF89-4A25-B2D5-20060720AA01} TypeSystem False ================================================ FILE: Zelig/Zelig/FileSystemTest/IOTestsHelper.cs ================================================ /*--------------------------------------------------------------------- * Master.cs - file description * Main class, responsible for running all of the other *Tests.cs files * Version: 1.0 * Author: REDMOND\a-grchat * Created: 9/4/2007 10:20:51 AM * ---------------------------------------------------------------------*/ using System; using System.IO; using System.Collections; using System.Reflection; using System.Collections.Generic; namespace FileSystemTest { public class SetUp : Attribute { } public class TearDown : Attribute { } public class TestMethod : Attribute { } public delegate MFTestResults MFTestDelegate(); public class MFTestMethod { public MFTestDelegate Test; public string TestName; public MFTestMethod( MFTestDelegate test, string testName ) { Test = test; TestName = testName; } } public interface IMFTestInterface { InitializeResult Initialize(); void CleanUp(); MFTestMethod[] Tests { get; } } public enum InitializeResult { Skip, ReadyToGo, } public enum MFTestResults { Pass, Fail, Skip, KnownFailure } public class Log { public static void Comment( string str ) { Console.WriteLine( "\t\t" + str ); } public static void Exception( string str ) { Console.WriteLine( "\t\tException: " + str ); } public static void Exception( string str, Exception ex ) { Console.WriteLine( "\t\tException: " + str + "\n\t\t" + ex.ToString() ); } public static void FilteredComment( string str ) { Console.WriteLine( "\t\t" + str ); } } public class FormatParameters { public String VolumeName = ""; public uint Parameter = 0; public String Comment = ""; } public class MFUtilities { public static byte[] GetRandomBytes( int bytes ) { byte[] ret = new byte[bytes]; Random rand = new Random(); rand.NextBytes(ret); return ret; } } public class IOTests { static VolumeInfo _volumeInfo = null; static FormatParameters[] _volumes = null; static int _currentVolume = -1; public static void RunTests( IMFTestInterface tst ) { Console.WriteLine( "\n~~~~~ " + tst.GetType().Name + " ~~~~~" ); tst.Initialize(); foreach(MFTestMethod tm in tst.Tests) { try { MFTestResults res = tm.Test(); string resVal = ""; switch(res) { case MFTestResults.Pass: resVal = "\n>>>PASS : "; break; case MFTestResults.Fail: resVal = "\n>>>FAIL : "; break; case MFTestResults.Skip: resVal = "\n>>>SKIP : "; break; case MFTestResults.KnownFailure: resVal = "\n>>>KNOWN FAIL: "; break; default: resVal = "\n>>>BADRESULT: "; break; } Console.WriteLine( resVal + tm.TestName ); } catch { Console.WriteLine( "!!!!!Exception while running test " + tm.TestName + "!!!!!" ); } } tst.CleanUp(); GC.Collect(); } public static void Initialize() { List deviceVolumes = new List(); try { // Get Volumes from device foreach (VolumeInfo volume in VolumeInfo.GetVolumes()) { if (volume.Name == "WINFS") { deviceVolumes.Add(new FormatParameters { VolumeName = "WINFS", Parameter = 0, Comment = "Emulator" }); } else { // Do one pass formating FAT16 and one pass formating FAT32 deviceVolumes.Add(new FormatParameters { VolumeName = volume.Name, Parameter = 1, Comment = "FAT16" }); deviceVolumes.Add(new FormatParameters { VolumeName = volume.Name, Parameter = 2, Comment = "FAT32" }); } } } catch { } _volumes = deviceVolumes.ToArray(); NextVolume(); } public static VolumeInfo Volume { get { return _volumeInfo; } } public static VolumeInfo NextVolume() { _currentVolume++; try { _volumeInfo = new VolumeInfo(_volumes[_currentVolume].VolumeName); Log.Comment("The following tests are running on volume " + _volumeInfo.Name + " [" + _volumes[_currentVolume].Comment + "]"); } catch { _volumeInfo = null; } return _volumeInfo; } public static void IntializeVolume() { Log.Comment("Formatting " + Volume.Name + " in " + Volume.FileSystem + " [" + _volumes[_currentVolume].Comment + "]"); Volume.Format(Volume.FileSystem, _volumes[_currentVolume].Parameter, "TEST_VOL", true); Directory.SetCurrentDirectory(Volume.RootDirectory); Log.Comment("TestVolumeLabel: " + Volume.VolumeLabel); } } } ================================================ FILE: Zelig/Zelig/FileSystemTest/MemoryStream/CanRead.cs ================================================ //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // Copyright (c) Microsoft Corporation. All rights reserved. //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// using System; using System.IO; namespace FileSystemTest { public class MemoryStreamCanRead : IMFTestInterface { [SetUp] public InitializeResult Initialize() { return InitializeResult.ReadyToGo; } [TearDown] public void CleanUp() { } [TestMethod] public MFTestResults CanRead_Default_Ctor() { MFTestResults result = MFTestResults.Pass; try { Log.Comment("Verify CanRead is true for default Ctor"); using (MemoryStream fs = new MemoryStream()) { if (!fs.CanRead) { Log.Exception( "Expected CanRead == true, but got CanRead == false" ); return MFTestResults.Fail; } } } catch (Exception ex) { Log.Exception( "Unexpected exception", ex ); return MFTestResults.Fail; } return result; } [TestMethod] public MFTestResults CanRead_Byte_Ctor() { MFTestResults result = MFTestResults.Pass; try { Log.Comment("Verify CanRead is true for Byte[] Ctor"); byte[] buffer = new byte[1024]; using (MemoryStream fs = new MemoryStream(buffer)) { if (!fs.CanRead) { Log.Exception( "Expected CanRead == true, but got CanRead == false" ); return MFTestResults.Fail; } } } catch (Exception ex) { Log.Exception( "Unexpected exception", ex ); return MFTestResults.Fail; } return result; } public MFTestMethod[] Tests { get { return new MFTestMethod[] { new MFTestMethod( CanRead_Default_Ctor, "CanRead_Default_Ctor" ), new MFTestMethod( CanRead_Byte_Ctor, "CanRead_Byte_Ctor" ), }; } } } } ================================================ FILE: Zelig/Zelig/FileSystemTest/MemoryStream/CanSeek.cs ================================================ //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // Copyright (c) Microsoft Corporation. All rights reserved. //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// using System; using System.IO; namespace FileSystemTest { public class MemoryStreamCanSeek : IMFTestInterface { [SetUp] public InitializeResult Initialize() { return InitializeResult.ReadyToGo; } [TearDown] public void CleanUp() { } [TestMethod] public MFTestResults CanSeek_Default_Ctor() { MFTestResults result = MFTestResults.Pass; try { Log.Comment("Verify CanSeek is true for default Ctor"); using (MemoryStream fs = new MemoryStream()) { if (!fs.CanSeek) { Log.Exception( "Expected CanSeek == true, but got CanSeek == false" ); return MFTestResults.Fail; } } } catch (Exception ex) { Log.Exception( "Unexpected exception", ex ); return MFTestResults.Fail; } return result; } [TestMethod] public MFTestResults CanSeek_Byte_Ctor() { MFTestResults result = MFTestResults.Pass; try { Log.Comment("Verify CanSeek is true for Byte[] Ctor"); byte[] buffer = new byte[1024]; using (MemoryStream fs = new MemoryStream(buffer)) { if (!fs.CanSeek) { Log.Exception( "Expected CanSeek == true, but got CanSeek == false" ); return MFTestResults.Fail; } } } catch (Exception ex) { Log.Exception( "Unexpected exception", ex ); return MFTestResults.Fail; } return result; } public MFTestMethod[] Tests { get { return new MFTestMethod[] { new MFTestMethod( CanSeek_Default_Ctor, "CanSeek_Default_Ctor" ), new MFTestMethod( CanSeek_Byte_Ctor, "CanSeek_Byte_Ctor" ), }; } } } } ================================================ FILE: Zelig/Zelig/FileSystemTest/MemoryStream/CanWrite.cs ================================================ //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // Copyright (c) Microsoft Corporation. All rights reserved. //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// using System; using System.IO; namespace FileSystemTest { public class MemoryStreamCanWrite : IMFTestInterface { [SetUp] public InitializeResult Initialize() { return InitializeResult.ReadyToGo; } [TearDown] public void CleanUp() { } [TestMethod] public MFTestResults CanWrite_Default_Ctor() { MFTestResults result = MFTestResults.Pass; try { Log.Comment("Verify CanWrite is true for default Ctor"); using (MemoryStream fs = new MemoryStream()) { if (!fs.CanWrite) { Log.Exception( "Expected CanWrite == true, but got CanWrite == false" ); return MFTestResults.Fail; } } } catch (Exception ex) { Log.Exception( "Unexpected exception", ex ); return MFTestResults.Fail; } return result; } [TestMethod] public MFTestResults CanWrite_Byte_Ctor() { MFTestResults result = MFTestResults.Pass; try { Log.Comment("Verify CanWrite is true for Byte[] Ctor"); byte[] buffer = new byte[1024]; using (MemoryStream fs = new MemoryStream(buffer)) { if (!fs.CanWrite) { Log.Exception( "Expected CanWrite == true, but got CanWrite == false" ); return MFTestResults.Fail; } } } catch (Exception ex) { Log.Exception( "Unexpected exception", ex ); return MFTestResults.Fail; } return result; } public MFTestMethod[] Tests { get { return new MFTestMethod[] { new MFTestMethod( CanWrite_Default_Ctor, "CanWrite_Default_Ctor" ), new MFTestMethod( CanWrite_Byte_Ctor, "CanWrite_Byte_Ctor" ), }; } } } } ================================================ FILE: Zelig/Zelig/FileSystemTest/MemoryStream/Close.cs ================================================ //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // Copyright (c) Microsoft Corporation. All rights reserved. //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// using System; using System.IO; namespace FileSystemTest { public class Close : IMFTestInterface { [SetUp] public InitializeResult Initialize() { return InitializeResult.ReadyToGo; } [TearDown] public void CleanUp() { } [TestMethod] public MFTestResults VerifyClose() { MFTestResults result = MFTestResults.Pass; try { MemoryStream ms = new MemoryStream(); ms.WriteByte(0); Log.Comment("Close stream"); ms.Close(); try { Log.Comment("Verify actually closed by writing to it"); ms.WriteByte(0); Log.Exception( "Expected ObjectDisposedException" ); return MFTestResults.Fail; } catch (ObjectDisposedException ode) { /* pass case */ Log.Comment( "Got correct exception: " + ode.Message ); result = MFTestResults.Pass; } } catch (Exception ex) { Log.Exception( "Unexpected exception", ex ); return MFTestResults.Fail; } return result; } public MFTestMethod[] Tests { get { return new MFTestMethod[] { new MFTestMethod( VerifyClose, "VerifyClose" ), }; } } } } ================================================ FILE: Zelig/Zelig/FileSystemTest/MemoryStream/Flush.cs ================================================ //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // Copyright (c) Microsoft Corporation. All rights reserved. //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// using System; using System.IO; namespace FileSystemTest { public class MemoryStreamFlush : IMFTestInterface { [SetUp] public InitializeResult Initialize() { return InitializeResult.ReadyToGo; } [TearDown] public void CleanUp() { } [TestMethod] public MFTestResults VerifyFlush() { MFTestResults result = MFTestResults.Pass; try { using (MemoryStream ms = new MemoryStream()) { byte[] data = MFUtilities.GetRandomBytes(5000); ms.Write(data, 0, data.Length); ms.Flush(); if (ms.Length != 5000) { Log.Exception( "Expected 5000 bytes, but got " + ms.Length ); return MFTestResults.Fail; } } } catch (Exception ex) { Log.Exception( "Unexpected exception", ex ); return MFTestResults.Fail; } return result; } public MFTestMethod[] Tests { get { return new MFTestMethod[] { new MFTestMethod( VerifyFlush, "VerifyFlush" ), }; } } } } ================================================ FILE: Zelig/Zelig/FileSystemTest/MemoryStream/Length.cs ================================================ //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // Copyright (c) Microsoft Corporation. All rights reserved. //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// using System; using System.IO; namespace FileSystemTest { public class Length : IMFTestInterface { [SetUp] public InitializeResult Initialize() { Log.Comment("Adding set up for the tests."); // TODO: Add your set up steps here. return InitializeResult.ReadyToGo; } [TearDown] public void CleanUp() { Log.Comment("Cleaning up after the tests."); // TODO: Add your clean up steps here. } #region Helper methods private bool TestLength(MemoryStream ms, long expectedLength) { if (ms.Length != expectedLength) { Log.Exception("Expected length " + expectedLength + " but got, " + ms.Length); return false; } return true; } private bool TestPosition(MemoryStream ms, long expectedPosition) { if (ms.Position != expectedPosition) { Log.Exception("Expected position " + expectedPosition + " but got, " + ms.Position); return false; } return true; } #endregion Helper methods #region Test Cases [TestMethod] public MFTestResults ObjectDisposed() { MFTestResults result = MFTestResults.Pass; try { MemoryStream ms = new MemoryStream(); ms.Close(); try { long length = ms.Length; Log.Exception( "Expected ObjectDisposedException, but got length " + length ); return MFTestResults.Fail; } catch (ObjectDisposedException) { /*Pass Case */ result = MFTestResults.Pass; } } catch (Exception ex) { Log.Exception("Unexpected exception", ex); return MFTestResults.Fail; } return result; } [TestMethod] public MFTestResults LengthTests() { MFTestResults result = MFTestResults.Pass; try { using (MemoryStream ms = new MemoryStream()) { Log.Comment("Set initial length to 50, and position to 50"); ms.SetLength(50); ms.Position = 50; if (!TestLength(ms, 50)) return MFTestResults.Fail; Log.Comment("Write 'foo bar'"); StreamWriter sw = new StreamWriter(ms); sw.Write("foo bar"); sw.Flush(); if (!TestLength(ms, 57)) return MFTestResults.Fail; Log.Comment("Shorten Length to 30"); ms.SetLength(30); if (!TestLength(ms, 30)) return MFTestResults.Fail; Log.Comment("Verify position was adjusted"); if (!TestPosition(ms, 30)) return MFTestResults.Fail; Log.Comment("Extend length to 100"); ms.SetLength(100); if (!TestLength(ms, 100)) return MFTestResults.Fail; } Log.Comment("Verify memorystream is 0 bytes after close"); using (MemoryStream ms = new MemoryStream()) { if (!TestLength(ms, 0)) return MFTestResults.Fail; } } catch (Exception ex) { Log.Exception("Unexpected exception", ex); return MFTestResults.Fail; } return result; } #endregion Test Cases public MFTestMethod[] Tests { get { return new MFTestMethod[] { new MFTestMethod( ObjectDisposed, "ObjectDisposed" ), new MFTestMethod( LengthTests, "LengthTests" ), }; } } } } ================================================ FILE: Zelig/Zelig/FileSystemTest/MemoryStream/MemoryStreamHelper.cs ================================================ //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // Copyright (c) Microsoft Corporation. All rights reserved. //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// using System; using System.IO; namespace FileSystemTest { public class MemoryStreamHelper { public static bool WriteReadEmpty(Stream ms) { bool result = true; if (ms.Position != 0) { result = false; Log.Exception("Expected postion 0, but got " + ms.Position); } if (ms.Length != 0) { result = false; Log.Exception("Expected length 0, but got " + ms.Length); } return WriteReadVerify(ms) & result; } public static bool WriteReadVerify(Stream ms) { bool result = Write(ms, 300); // Flush writes ms.Flush(); Log.Comment("Seek to start and Read"); ms.Seek(0, SeekOrigin.Begin); result &= VerifyRead(ms); return result; } public static bool Write(Stream ms, int length) { bool result = true; long startLength = ms.Length; // we can only write 0-255, so mod the // length to figure out next data value byte data = (byte)(startLength & 0xFF); Log.Comment("Seek to end"); ms.Seek(0, SeekOrigin.End); Log.Comment("Write to file"); for (long i = startLength; i < startLength + length; i++) { ms.WriteByte((byte)data++); } return result; } public static bool VerifyRead(Stream ms) { bool result = true; Log.Comment("Verify " + ms.Length + " bytes of data in file"); // we can only read 0-255, so mod the // position to figure out next data value byte nextbyte = (byte)(ms.Position & 0xFF); for (int i = 0; i < ms.Length; i++) { int readByte = ms.ReadByte(); if (readByte != nextbyte) { result = false; Log.Exception("Byte in position " + i + " has wrong value: " + readByte); } nextbyte++; } return result; } } } ================================================ FILE: Zelig/Zelig/FileSystemTest/MemoryStream/MemoryStream_Ctor.cs ================================================ //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // Copyright (c) Microsoft Corporation. All rights reserved. //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// using System; using System.IO; namespace FileSystemTest { public class MemoryStream_Ctor : IMFTestInterface { [SetUp] public InitializeResult Initialize() { return InitializeResult.ReadyToGo; } [TearDown] public void CleanUp() { } #region Helper methods private bool ValidateMemoryStream(MemoryStream ms, int ExpectedLength) { bool success = true; Log.Comment("Check Length"); if (ms.Length != ExpectedLength) { success = false; Log.Exception("Expected Length 0, but got Length " + ms.Length); } Log.Comment("Check CanSeek"); if (!ms.CanSeek) { success = false; Log.Exception("Expected CanSeek to be true, but was false"); } Log.Comment("Check CanRead"); if (!ms.CanRead) { success = false; Log.Exception("Expected CanRead to be true, but was false"); } Log.Comment("Check CanWrite"); if (!ms.CanWrite) { success = false; Log.Exception("Expected CanWrite to be true, but was false"); } if (ms.Position != 0) { success = false; Log.Exception("Expected Position to be 0, but was " + ms.Position); } return success; } #endregion Helper methods #region Test Cases [TestMethod] public MFTestResults InvalidArguments() { MFTestResults result = MFTestResults.Pass; try { try { Log.Comment("null buffer"); using (MemoryStream fs = new MemoryStream(null)) { } Log.Exception( "Expected ArgumentException" ); return MFTestResults.Fail; } catch (ArgumentException ae) { /* pass case */ Log.Comment( "Got correct exception: " + ae.Message ); result = MFTestResults.Pass; } } catch (Exception ex) { Log.Exception("Unexpected exception", ex); return MFTestResults.Fail; } return result; } [TestMethod] public MFTestResults Valid_Default_Ctor() { MFTestResults result = MFTestResults.Pass; try { using (MemoryStream ms = new MemoryStream()) { if (!ValidateMemoryStream(ms, 0)) return MFTestResults.Fail; } } catch (Exception ex) { Log.Exception("Unexpected exception", ex); return MFTestResults.Fail; } return result; } [TestMethod] public MFTestResults Variable_Buffer_Ctor() { MFTestResults result = MFTestResults.Pass; try { Log.Comment("Verify buffer constructors length 0-100"); for (int i = 0; i < 100; i++) { byte[] buffer = new byte[i]; using (MemoryStream ms = new MemoryStream(buffer)) { if (!ValidateMemoryStream(ms, i)) return MFTestResults.Fail; Log.Comment("Try to extend beyond buffer length"); try { ms.SetLength(i + 1); Log.Exception( "Expected NotSupportedException" ); return MFTestResults.Fail; } catch (NotSupportedException nse) { /* pass case */ Log.Comment( "Got correct exception: " + nse.Message ); result = MFTestResults.Pass; } Log.Comment("Truncate to 0"); for (int j = buffer.Length; j >= 0; j--) { ms.SetLength(j); } } } Log.Comment("Verify 10k buffer constructor"); byte[] largeBuffer = new byte[10000]; using (MemoryStream ms = new MemoryStream(largeBuffer)) { if (!ValidateMemoryStream(ms, largeBuffer.Length)) return MFTestResults.Fail; } } catch (Exception ex) { Log.Exception("Unexpected exception", ex); return MFTestResults.Fail; } return result; } #endregion Test Cases public MFTestMethod[] Tests { get { return new MFTestMethod[] { new MFTestMethod( InvalidArguments, "InvalidArguments" ), new MFTestMethod( Valid_Default_Ctor, "Valid_Default_Ctor" ), new MFTestMethod( Variable_Buffer_Ctor, "Variable_Buffer_Ctor" ), }; } } } } ================================================ FILE: Zelig/Zelig/FileSystemTest/MemoryStream/Position.cs ================================================ //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // Copyright (c) Microsoft Corporation. All rights reserved. //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// using System; using System.IO; namespace FileSystemTest { public class Position : IMFTestInterface { [SetUp] public InitializeResult Initialize() { Log.Comment("Adding set up for the tests."); // TODO: Add your set up steps here. // if (Setup Fails) // return InitializeResult.Skip; return InitializeResult.ReadyToGo; } [TearDown] public void CleanUp() { Log.Comment("Cleaning up after the tests."); // TODO: Add your clean up steps here. } #region Helper methods private bool GetSetPosition(MemoryStream ms, int TestLength) { bool success = true; Log.Comment("Move forwards"); for (int i = 0; i < TestLength; i++) { ms.Position = i; if (ms.Position != i) { success = false; Log.Exception("Expected position " + i + " but got position " + ms.Position); } } Log.Comment("Move backwards"); for (int i = TestLength - 1; i >= 0; i--) { ms.Position = i; if (ms.Position != i) { success = false; Log.Exception("Expected position " + i + " but got position " + ms.Position); } } return success; } #endregion Helper methods #region Test Cases [TestMethod] public MFTestResults ObjectDisposed() { MemoryStream ms = new MemoryStream(); ms.Close(); MFTestResults result = MFTestResults.Pass; try { try { long position = ms.Position; Log.Exception( "Expected ObjectDisposedException, but got position " + position ); return MFTestResults.Fail; } catch (ObjectDisposedException) { /*Pass Case */ result = MFTestResults.Pass; } try { ms.Position = 0; Log.Exception( "Expected ObjectDisposedException, but set position" ); return MFTestResults.Fail; } catch (ObjectDisposedException) { /*Pass Case */ result = MFTestResults.Pass; } } catch (Exception ex) { Log.Exception("Unexpected exception: " + ex.Message); return MFTestResults.Fail; } return result; } [TestMethod] public MFTestResults InvalidRange() { MFTestResults result = MFTestResults.Pass; try { byte[] buffer = new byte[100]; using (MemoryStream ms = new MemoryStream(buffer)) { Log.Comment("Try -1 postion"); try { ms.Position = -1; Log.Exception( "Expected ArgumentOutOfRangeException" ); return MFTestResults.Fail; } catch (ArgumentOutOfRangeException aoore) { /* pass case */ Log.Comment( "Got correct exception: " + aoore.Message ); result = MFTestResults.Pass; } Log.Comment("Try Long.MinValue postion"); try { ms.Position = long.MinValue; Log.Exception( "Expected ArgumentOutOfRangeException" ); return MFTestResults.Fail; } catch (ArgumentOutOfRangeException aoore) { /* pass case */ Log.Comment( "Got correct exception: " + aoore.Message ); result = MFTestResults.Pass; } } } catch (Exception ex) { Log.Exception("Unexpected exception", ex); return MFTestResults.Fail; } return result; } [TestMethod] public MFTestResults GetSetStaticBuffer() { MFTestResults result = MFTestResults.Pass; try { byte[] buffer = new byte[1000]; Log.Comment("Get/Set Position with static buffer"); using (MemoryStream ms = new MemoryStream(buffer)) { if (!GetSetPosition(ms, buffer.Length)) return MFTestResults.Fail; } } catch (Exception ex) { Log.Exception("Unexpected exception", ex); return MFTestResults.Fail; } return result; } [TestMethod] public MFTestResults GetSetDynamicBuffer() { MFTestResults result = MFTestResults.Pass; try { Log.Comment("Get/Set Position with dynamic buffer"); using (MemoryStream ms = new MemoryStream()) { if (!GetSetPosition(ms, 1000)) return MFTestResults.Fail; } } catch (Exception ex) { Log.Exception("Unexpected exception", ex); return MFTestResults.Fail; } return result; } #endregion Test Cases public MFTestMethod[] Tests { get { return new MFTestMethod[] { new MFTestMethod( ObjectDisposed, "ObjectDisposed" ), new MFTestMethod( InvalidRange, "InvalidRange" ), new MFTestMethod( GetSetStaticBuffer, "GetSetStaticBuffer" ), new MFTestMethod( GetSetDynamicBuffer, "GetSetDynamicBuffer" ), }; } } } } ================================================ FILE: Zelig/Zelig/FileSystemTest/MemoryStream/Read.cs ================================================ //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // Copyright (c) Microsoft Corporation. All rights reserved. //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// using System; using System.IO; using System.Text; namespace FileSystemTest { public class MemoryStreamRead : IMFTestInterface { [SetUp] public InitializeResult Initialize() { Log.Comment("Adding set up for the tests."); // TODO: Add your set up steps here. return InitializeResult.ReadyToGo; } [TearDown] public void CleanUp() { Log.Comment("Cleaning up after the tests."); // TODO: Add your clean up steps here. } #region Local Helper methods private bool TestRead(MemoryStream ms, int length) { return TestRead(ms, length, length, length); } private bool TestRead(MemoryStream ms, int BufferLength, int BytesToRead, int BytesExpected) { bool result = true; byte nextbyte = (byte)(ms.Position & 0xFF); byte[] byteBuffer = new byte[BufferLength]; int bytesRead = ms.Read(byteBuffer, 0, BytesToRead); if (bytesRead != BytesExpected) { result = false; Log.Exception("Expected " + BytesToRead + " bytes, but got " + bytesRead + " bytes"); } for (int i = 0; i < bytesRead; i++) { if (byteBuffer[i] != nextbyte) { result = false; Log.Exception("Byte in position " + i + " has wrong value: " + byteBuffer[i]); } nextbyte++; } return result; } #endregion Local Helper methods #region Test Cases [TestMethod] public MFTestResults InvalidCases() { MFTestResults result = MFTestResults.Pass; try { using (MemoryStream ms = new MemoryStream()) { Log.Comment("null Buffer"); try { int read = ms.Read(null, 0, 0); Log.Exception( "Expected ArgumentNullException, but read " + read + " bytes" ); return MFTestResults.Fail; } catch (ArgumentNullException ane) { /* pass case */ Log.Comment( "Got correct exception: " + ane.Message ); result = MFTestResults.Pass; } Log.Comment("negative offset"); try { int read = ms.Read(new byte[]{1}, -1, 0); Log.Exception( "Expected ArgumentOutOfRangeException, but read " + read + " bytes" ); return MFTestResults.Fail; } catch (ArgumentOutOfRangeException aoore) { /* pass case */ Log.Comment( "Got correct exception: " + aoore.Message ); result = MFTestResults.Pass; } Log.Comment("negative count"); try { int read = ms.Read(new byte[] { 1 }, 0, -1); Log.Exception( "Expected ArgumentOutOfRangeException, but read " + read + " bytes" ); return MFTestResults.Fail; } catch (ArgumentOutOfRangeException aoore) { /* pass case */ Log.Comment( "Got correct exception: " + aoore.Message ); result = MFTestResults.Pass; } Log.Comment("offset exceeds buffer size"); try { int read = ms.Read(new byte[] { 1 }, 2, 0); Log.Exception( "Expected ArgumentException, but read " + read + " bytes" ); return MFTestResults.Fail; } catch (ArgumentException ae) { /* pass case */ Log.Comment( "Got correct exception: " + ae.Message ); result = MFTestResults.Pass; } Log.Comment("count exceeds buffer size"); try { int read = ms.Read(new byte[] { 1 }, 0, 2); Log.Exception( "Expected ArgumentException, but read " + read + " bytes" ); return MFTestResults.Fail; } catch (ArgumentException ae) { /* pass case */ Log.Comment( "Got correct exception: " + ae.Message ); result = MFTestResults.Pass; } } MemoryStream ms2 = new MemoryStream(); MemoryStreamHelper.Write(ms2, 100); ms2.Seek(0, SeekOrigin.Begin); ms2.Close(); Log.Comment("Read from closed stream"); try { int readBytes = ms2.Read(new byte[] { 50 }, 0, 50); Log.Exception( "Expected ObjectDisposedException, but read " + readBytes + " bytes" ); return MFTestResults.Fail; } catch (ObjectDisposedException ode) { /* pass case */ Log.Comment( "Got correct exception: " + ode.Message ); result = MFTestResults.Pass; } } catch (Exception ex) { Log.Exception("Unexpected exception", ex); return MFTestResults.Fail; } return result; } [TestMethod] public MFTestResults VanillaRead() { MFTestResults result = MFTestResults.Pass; try { using (MemoryStream ms = new MemoryStream()) { // Write to stream then reset to beginning MemoryStreamHelper.Write(ms, 1000); ms.Seek(0, SeekOrigin.Begin); Log.Comment("Read 256 bytes of data"); if (!TestRead(ms, 256)) return MFTestResults.Fail; Log.Comment("Request less bytes then buffer"); if (!TestRead(ms, 256, 100, 100)) return MFTestResults.Fail; // 1000 - 256 - 100 = 644 Log.Comment("Request more bytes then file"); if (!TestRead(ms, 1000, 1000, 644)) return MFTestResults.Fail; Log.Comment("Request bytes after EOF"); if (!TestRead(ms, 100, 100, 0)) return MFTestResults.Fail; Log.Comment("Rewind and read entire file in one buffer larger then file"); ms.Seek(0, SeekOrigin.Begin); if (!TestRead(ms, 1001, 1001, 1000)) return MFTestResults.Fail; Log.Comment("Rewind and read from middle"); ms.Position = 500; if (!TestRead(ms, 256)) return MFTestResults.Fail; Log.Comment("Read position after EOS"); ms.Position = ms.Length + 10; if (!TestRead(ms, 100, 100, 0)) return MFTestResults.Fail; Log.Comment("Verify Read validation with UTF8 string"); ms.SetLength(0); string test = "MFFramework Test"; ms.Write(UTF8Encoding.UTF8.GetBytes(test), 0, test.Length); ms.Flush(); ms.Seek(0, SeekOrigin.Begin); byte[] readbuff = new byte[20]; int readlen = ms.Read(readbuff, 0, readbuff.Length); string testResult = new string(Encoding.UTF8.GetChars(readbuff, 0, readlen)); if (test != testResult) { Log.Comment( "Exepected: " + test + ", but got: " + testResult ); return MFTestResults.Fail; } } } catch (Exception ex) { Log.Exception("Unexpected exception", ex); return MFTestResults.Fail; } return result; } #endregion Test Cases public MFTestMethod[] Tests { get { return new MFTestMethod[] { new MFTestMethod( InvalidCases, "InvalidCases" ), new MFTestMethod( VanillaRead, "VanillaRead" ), }; } } } } ================================================ FILE: Zelig/Zelig/FileSystemTest/MemoryStream/ReadByte.cs ================================================ //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // Copyright (c) Microsoft Corporation. All rights reserved. //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// using System; using System.IO; namespace FileSystemTest { public class ReadByte : IMFTestInterface { [SetUp] public InitializeResult Initialize() { Log.Comment("Adding set up for the tests."); // TODO: Add your set up steps here. return InitializeResult.ReadyToGo; } [TearDown] public void CleanUp() { Log.Comment("Cleaning up after the tests."); // TODO: Add your clean up steps here. } #region Test Cases [TestMethod] public MFTestResults InvalidCases() { MFTestResults result = MFTestResults.Pass; try { MemoryStream ms2 = new MemoryStream(); MemoryStreamHelper.Write(ms2, 100); ms2.Seek(0, SeekOrigin.Begin); ms2.Close(); Log.Comment("Read from closed stream"); try { int readBytes = ms2.ReadByte(); Log.Exception( "Expected ObjectDisposedException, but read " + readBytes + " bytes" ); return MFTestResults.Fail; } catch (ObjectDisposedException ode) { /* pass case */ Log.Comment( "Got correct exception: " + ode.Message ); } } catch (Exception ex) { Log.Exception("Unexpected exception", ex); return MFTestResults.Fail; } return result; } [TestMethod] public MFTestResults VanillaCases() { MFTestResults result = MFTestResults.Pass; try { using (MemoryStream ms = new MemoryStream()) { MemoryStreamHelper.Write(ms, 256); ms.Position = 0; Log.Comment("ReadBytes and verify"); for (int i = 0; i < 256; i++) { int b = ms.ReadByte(); if (b != i) { Log.Exception( "Expected " + i + " but got " + b ); return MFTestResults.Fail; } } Log.Comment("Bytes past EOS should return -1"); int rb = ms.ReadByte(); if (rb != -1) { Log.Exception( "Expected -1 but got " + rb ); return MFTestResults.Fail; } } } catch (Exception ex) { Log.Exception("Unexpected exception", ex); return MFTestResults.Fail; } return result; } #endregion Test Cases public MFTestMethod[] Tests { get { return new MFTestMethod[] { new MFTestMethod( InvalidCases, "InvalidCases" ), new MFTestMethod( VanillaCases, "VanillaCases" ), }; } } } } ================================================ FILE: Zelig/Zelig/FileSystemTest/MemoryStream/Seek.cs ================================================ //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // Copyright (c) Microsoft Corporation. All rights reserved. //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// using System; using System.IO; namespace FileSystemTest { public class MemoryStreamSeek : IMFTestInterface { [SetUp] public InitializeResult Initialize() { Log.Comment("Adding set up for the tests."); // TODO: Add your set up steps here. return InitializeResult.ReadyToGo; } [TearDown] public void CleanUp() { Log.Comment("Cleaning up after the tests."); // TODO: Add your clean up steps here. } #region Helper methods private bool TestSeek(MemoryStream ms, long offset, SeekOrigin origin, long expectedPosition) { bool result = true; long seek = ms.Seek(offset, origin); if (seek != ms.Position && seek != expectedPosition) { result = false; Log.Exception("Unexpected seek results!"); Log.Exception("Expected position: " + expectedPosition); Log.Exception("Seek result: " + seek); Log.Exception("fs.Position: " + ms.Position); } return result; } private bool TestExtend(MemoryStream ms, long offset, SeekOrigin origin, long expectedPosition, long expectedLength) { bool result = TestSeek(ms, offset, origin, expectedLength); ms.WriteByte(1); if (ms.Length != expectedLength) { result = false; Log.Exception("Expected seek past end to change length to " + expectedLength + ", but its " + ms.Length); } return result; } #endregion Helper methods #region Test Cases [TestMethod] public MFTestResults InvalidCases() { MemoryStream fs = new MemoryStream(); MemoryStreamHelper.Write(fs, 1000); long seek; MFTestResults result = MFTestResults.Pass; try { try { Log.Comment("Seek -1 from Begin"); seek = fs.Seek(-1, SeekOrigin.Begin); Log.Exception( "Expected IOException, but got position " + seek ); return MFTestResults.Fail; } catch (IOException ioe) { /* pass case */ Log.Comment( "Got correct exception: " + ioe.Message ); result = MFTestResults.Pass; } try { Log.Comment("Seek -1001 from Current - at end from write"); seek = fs.Seek(-1001, SeekOrigin.Current); Log.Exception( "Expected IOException, but got position " + seek ); return MFTestResults.Fail; } catch (IOException ioe) { /* pass case */ Log.Comment( "Got correct exception: " + ioe.Message ); result = MFTestResults.Pass; } try { Log.Comment("Seek -1001 from End"); seek = fs.Seek(-1001, SeekOrigin.End); Log.Exception( "Expected IOException, but got position " + seek ); return MFTestResults.Fail; } catch (IOException ioe) { /* pass case */ Log.Comment( "Got correct exception: " + ioe.Message ); result = MFTestResults.Pass; } try { Log.Comment("Seek invalid -1 origin"); seek = fs.Seek(1, (SeekOrigin)(-1)); Log.Exception( "Expected ArgumentException, but got position " + seek ); return MFTestResults.Fail; } catch (ArgumentException ae) { /* pass case */ Log.Comment( "Got correct exception: " + ae.Message ); result = MFTestResults.Pass; } try { Log.Comment("Seek invalid 10 origin"); seek = fs.Seek(1, (SeekOrigin)10); Log.Exception( "Expected ArgumentException, but got position " + seek ); return MFTestResults.Fail; } catch (ArgumentException ae) { /* pass case */ Log.Comment( "Got correct exception: " + ae.Message ); result = MFTestResults.Pass; } try { Log.Comment("Seek with closed stream"); fs.Close(); seek = fs.Seek(0, SeekOrigin.Begin); Log.Exception( "Expected ObjectDisposedException, but got position " + seek ); return MFTestResults.Fail; } catch (ObjectDisposedException ode) { /* pass case */ Log.Comment( "Got correct exception: " + ode.Message ); result = MFTestResults.Pass; } try { Log.Comment("Seek with disposed stream"); fs.Dispose(); seek = fs.Seek(0, SeekOrigin.End); Log.Exception( "Expected ObjectDisposedException, but got position " + seek ); return MFTestResults.Fail; } catch (ObjectDisposedException ode) { /* pass case */ Log.Comment( "Got correct exception: " + ode.Message ); result = MFTestResults.Pass; } } catch (Exception ex) { Log.Exception("Unexpected exception: " + ex.Message); return MFTestResults.Fail; } finally { if (fs != null) fs.Dispose(); } return result; } [TestMethod] public MFTestResults ValidCases() { MFTestResults result = MFTestResults.Pass; try { using (MemoryStream fs = new MemoryStream()) { MemoryStreamHelper.Write(fs, 1000); Log.Comment("Seek to beginning"); if (!TestSeek(fs, 0, SeekOrigin.Begin, 0)) return MFTestResults.Fail; Log.Comment("Seek forward offset from begging"); if (!TestSeek(fs, 10, SeekOrigin.Begin, 0)) return MFTestResults.Fail; Log.Comment("Seek backwards offset from current"); if (!TestSeek(fs, -5, SeekOrigin.Current, 5)) return MFTestResults.Fail; Log.Comment("Seek forwards offset from current"); if (!TestSeek(fs, 20, SeekOrigin.Current, 25)) return MFTestResults.Fail; Log.Comment("Seek to end"); if (!TestSeek(fs, 0, SeekOrigin.End, 1000)) return MFTestResults.Fail; Log.Comment("Seek backwards offset from end"); if (!TestSeek(fs, -35, SeekOrigin.End, 965)) return MFTestResults.Fail; Log.Comment("Seek past end relative to End"); if (!TestExtend(fs, 1, SeekOrigin.End, 1001, 1002)) return MFTestResults.Fail; Log.Comment("Seek past end relative to Begin"); if (!TestExtend(fs, 1002, SeekOrigin.Begin, 1002, 1003)) return MFTestResults.Fail; Log.Comment("Seek past end relative to Current"); if (!TestSeek(fs, 995, SeekOrigin.Begin, 995)) return MFTestResults.Fail; if (!TestExtend(fs, 10, SeekOrigin.Current, 1005, 1006)) return MFTestResults.Fail; // 1000 --123456 // verify 011001 Log.Comment("Verify proper bytes written at end (zero'd bytes from seek beyond end)"); byte[] buff = new byte[6]; byte[] verify = new byte[] { 0, 1, 1, 0, 0, 1 }; fs.Seek(-6, SeekOrigin.End); fs.Read(buff, 0, buff.Length); for (int i = 0; i < buff.Length; i++) { if (buff[i] != verify[i]) { Log.Comment( "Position " + i + ":" + buff[i] + " != " + verify[i] ); return MFTestResults.Fail; } } } } catch (Exception ex) { Log.Exception("Unexpected exception: " + ex.Message); return MFTestResults.Fail; } return result; } #endregion Test Cases public MFTestMethod[] Tests { get { return new MFTestMethod[] { new MFTestMethod( InvalidCases, "InvalidCases" ), new MFTestMethod( ValidCases, "ValidCases" ), }; } } } } ================================================ FILE: Zelig/Zelig/FileSystemTest/MemoryStream/SetLength.cs ================================================ //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // Copyright (c) Microsoft Corporation. All rights reserved. //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// using System; using System.IO; namespace FileSystemTest { public class SetLength : IMFTestInterface { [SetUp] public InitializeResult Initialize() { Log.Comment("Adding set up for the tests."); // TODO: Add your set up steps here. return InitializeResult.ReadyToGo; } [TearDown] public void CleanUp() { Log.Comment("Cleaning up after the tests."); // TODO: Add your clean up steps here. } #region Helper methods private bool TestLength(MemoryStream ms, long expectedLength) { if (ms.Length != expectedLength) { Log.Exception("Expected length " + expectedLength + " but got, " + ms.Length); return false; } return true; } private bool TestPosition(MemoryStream ms, long expectedPosition) { if (ms.Position != expectedPosition) { Log.Exception("Expected position " + expectedPosition + " but got, " + ms.Position); return false; } return true; } #endregion Helper methods #region Test Cases [TestMethod] public MFTestResults ObjectDisposed() { MemoryStream ms = new MemoryStream(); ms.Close(); MFTestResults result = MFTestResults.Pass; try { try { long length = ms.Length; Log.Exception( "Expected ObjectDisposedException, but got length " + length ); return MFTestResults.Fail; } catch (ObjectDisposedException) { /*Pass Case */ result = MFTestResults.Pass; } } catch (Exception ex) { Log.Exception("Unexpected exception: " + ex.Message); return MFTestResults.Fail; } return result; } [TestMethod] public MFTestResults LengthTests() { MFTestResults result = MFTestResults.Pass; try { using (MemoryStream ms = new MemoryStream()) { Log.Comment("Set initial length to 50, and position to 50"); ms.SetLength(50); ms.Position = 50; if (!TestLength(ms, 50)) return MFTestResults.Fail; Log.Comment("Write 'foo bar'"); StreamWriter sw = new StreamWriter(ms); sw.Write("foo bar"); sw.Flush(); if (!TestLength(ms, 57)) return MFTestResults.Fail; Log.Comment("Shorten Length to 30"); ms.SetLength(30); if (!TestLength(ms, 30)) return MFTestResults.Fail; Log.Comment("Verify position was adjusted"); if (!TestPosition(ms, 30)) return MFTestResults.Fail; Log.Comment("Extend length to 100"); ms.SetLength(100); if (!TestLength(ms, 100)) return MFTestResults.Fail; } } catch (Exception ex) { Log.Exception("Unexpected exception: " + ex.Message); return MFTestResults.Fail; } return result; } [TestMethod] public MFTestResults InvalidSetLength() { MFTestResults result = MFTestResults.Pass; try { using (MemoryStream ms = new MemoryStream()) { try { Log.Comment("-1"); ms.SetLength(-1); Log.Exception( "Expected ArgumentOutOfRangeException, but set length" ); return MFTestResults.Fail; } catch (ArgumentOutOfRangeException aoore) { /* pass case */ Log.Comment( "Got correct exception: " + aoore.Message ); result = MFTestResults.Pass; } try { Log.Comment("-10000"); ms.SetLength(-10000); Log.Exception( "Expected ArgumentOutOfRangeException, but set length" ); return MFTestResults.Fail; } catch (ArgumentOutOfRangeException aoore) { /* pass case */ Log.Comment( "Got correct exception: " + aoore.Message ); result = MFTestResults.Pass; } try { Log.Comment("long.MinValue"); ms.SetLength(long.MinValue); Log.Exception( "Expected ArgumentOutOfRangeException, but set length" ); return MFTestResults.Fail; } catch (ArgumentOutOfRangeException aoore) { /* pass case */ Log.Comment( "Got correct exception: " + aoore.Message ); result = MFTestResults.Pass; } try { Log.Comment("long.MaxValue"); ms.SetLength(long.MaxValue); Log.Exception( "Expected IOException, but set length" ); return MFTestResults.Fail; } catch (ArgumentOutOfRangeException aoore) { /* pass case */ Log.Comment( "Got correct exception: " + aoore.Message ); result = MFTestResults.Pass; } } } catch (Exception ex) { Log.Exception("Unexpected exception: " + ex.Message); return MFTestResults.Fail; } return result; } #endregion Test Cases public MFTestMethod[] Tests { get { return new MFTestMethod[] { new MFTestMethod( ObjectDisposed, "ObjectDisposed" ), new MFTestMethod( LengthTests, "LengthTests" ), new MFTestMethod( InvalidSetLength, "InvalidSetLength" ), }; } } } } ================================================ FILE: Zelig/Zelig/FileSystemTest/MemoryStream/ToArray.cs ================================================ //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // Copyright (c) Microsoft Corporation. All rights reserved. //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// using System; using System.IO; namespace FileSystemTest { public class ToArray : IMFTestInterface { [SetUp] public InitializeResult Initialize() { Log.Comment("Adding set up for the tests."); // TODO: Add your set up steps here. return InitializeResult.ReadyToGo; } [TearDown] public void CleanUp() { Log.Comment("Cleaning up after the tests."); // TODO: Add your clean up steps here. } #region Helper methods private bool VerifyArray(byte[] data, int expected) { bool result = true; Log.Comment("Verify Length"); if (data.Length != expected) { result = false; Log.Exception("Expected " + expected + " bytes, but got " + data.Length); } Log.Comment("Verify pattern in array"); int nextbyte = 0; for (int i = 0; i < data.Length; i++) { if (data[i] != nextbyte) { result = false; Log.Exception("Byte in position " + i + " has wrong value: " + data[i]); } // Reset if wraps past 255 if (++nextbyte > 255) nextbyte = 0; } return result; } #endregion Helper methods #region Test Cases [TestMethod] public MFTestResults Ctor_ToArray() { MFTestResults result = MFTestResults.Pass; try { Log.Comment("Dynamic Stream"); using (MemoryStream ms = new MemoryStream()) { byte[] stream = ms.ToArray(); if (stream.Length != 0) { Log.Exception( "Expected length 0, but got length " + stream.Length ); return MFTestResults.Fail; } } Log.Comment("Static Stream"); using (MemoryStream ms = new MemoryStream(new byte[512])) { byte[] stream = ms.ToArray(); if (stream.Length != 512) { Log.Exception( "Expected length 512, but got length " + stream.Length ); return MFTestResults.Fail; } } } catch (Exception ex) { Log.Exception("Unexpected exception", ex); return MFTestResults.Fail; } return result; } [TestMethod] public MFTestResults VerifyValues() { MFTestResults result = MFTestResults.Pass; try { Log.Comment("Verify Data"); using (MemoryStream ms = new MemoryStream()) { Log.Comment("Write 1000 bytes in specific pattern"); MemoryStreamHelper.Write(ms, 1000); byte[] stream = ms.ToArray(); if (!VerifyArray(stream, 1000)) return MFTestResults.Fail; } } catch (Exception ex) { Log.Exception("Unexpected exception", ex); return MFTestResults.Fail; } return result; } [TestMethod] public MFTestResults ChangeLengths() { MFTestResults result = MFTestResults.Pass; try { Log.Comment("Verify array is still valid after truncation (copy array)"); using (MemoryStream ms = new MemoryStream()) { MemoryStreamHelper.Write(ms, 1000); ms.SetLength(200); ms.Flush(); byte[] stream = ms.ToArray(); if (!VerifyArray(stream, 200)) return MFTestResults.Fail; } } catch (Exception ex) { Log.Exception("Unexpected exception", ex); return MFTestResults.Fail; } return result; } #endregion Test Cases public MFTestMethod[] Tests { get { return new MFTestMethod[] { new MFTestMethod( Ctor_ToArray, "Ctor_ToArray" ), new MFTestMethod( VerifyValues, "VerifyValues" ), new MFTestMethod( ChangeLengths, "ChangeLengths" ), }; } } } } ================================================ FILE: Zelig/Zelig/FileSystemTest/MemoryStream/Write.cs ================================================ //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // Copyright (c) Microsoft Corporation. All rights reserved. //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// using System; using System.IO; using System.Text; namespace FileSystemTest { public class MemoryStreamWrite : IMFTestInterface { [SetUp] public InitializeResult Initialize() { Log.Comment("Adding set up for the tests."); // TODO: Add your set up steps here. return InitializeResult.ReadyToGo; } [TearDown] public void CleanUp() { Log.Comment("Cleaning up after the tests."); // TODO: Add your clean up steps here. } //TODO Test with position longer then length #region Local Helper methods private bool TestWrite(MemoryStream ms, int length) { return TestWrite(ms, length, length, 0); } private bool TestWrite(MemoryStream ms, int length, long ExpectedLength) { return TestWrite(ms, length, length, 0, ExpectedLength); } private bool TestWrite(MemoryStream ms, int BufferLength, int BytesToWrite, int Offset) { return TestWrite(ms, BufferLength, BytesToWrite, Offset, ms.Position + BytesToWrite); } private bool TestWrite(MemoryStream ms, int BufferLength, int BytesToWrite, int Offset, long ExpectedLength) { bool result = true; long startLength = ms.Position; byte nextbyte = (byte)(startLength & 0xFF); byte[] byteBuffer = new byte[BufferLength]; for (int i = Offset; i < (Offset + BytesToWrite); i++) { byteBuffer[i] = (byte)nextbyte; nextbyte++; } ms.Write(byteBuffer, Offset, BytesToWrite); ms.Flush(); if (ExpectedLength < ms.Length) { result = false; Log.Exception("Expeceted final length of " + ExpectedLength + " bytes, but got " + ms.Length + " bytes"); } return result; } #endregion Local Helper methods #region Test Cases [TestMethod] public MFTestResults InvalidCases() { MemoryStream fs = new MemoryStream(); byte[] writebuff = new byte[1024]; MFTestResults result = MFTestResults.Pass; try { try { Log.Comment("Write to null buffer"); fs.Write(null, 0, writebuff.Length); Log.Exception( "Expected ArgumentNullException" ); return MFTestResults.Fail; } catch (ArgumentNullException ane) { /* pass case */ Log.Comment( "Got correct exception: " + ane.Message ); result = MFTestResults.Pass; } try { Log.Comment("Write to negative offset"); fs.Write(writebuff, -1, writebuff.Length); Log.Exception( "Expected ArgumentOutOfRangeException" ); return MFTestResults.Fail; } catch (ArgumentOutOfRangeException aoore) { /* pass case */ Log.Comment( "Got correct exception: " + aoore.Message ); result = MFTestResults.Pass; } try { Log.Comment("Write to out of range offset"); fs.Write(writebuff, writebuff.Length + 1, writebuff.Length); Log.Exception( "Expected ArgumentException" ); return MFTestResults.Fail; } catch (ArgumentException ae) { /* pass case */ Log.Comment( "Got correct exception: " + ae.Message ); result = MFTestResults.Pass; } try { Log.Comment("Write negative count"); fs.Write(writebuff, 0, -1); // previous Bug # 21669 Log.Exception( "Expected ArgumentOutOfRangeException" ); return MFTestResults.Fail; } catch (ArgumentOutOfRangeException aoore) { /* pass case */ Log.Comment( "Got correct exception: " + aoore.Message ); result = MFTestResults.Pass; } try { Log.Comment("Write count larger then buffer"); fs.Write(writebuff, 0, writebuff.Length + 1); Log.Exception( "Expected ArgumentException" ); return MFTestResults.Fail; } catch (ArgumentException ae) { /* pass case */ Log.Comment( "Got correct exception: " + ae.Message ); result = MFTestResults.Pass; } try { Log.Comment("Write closed stream"); fs.Close(); fs.Write(writebuff, 0, writebuff.Length); Log.Exception( "Expected ObjectDisposedException" ); return MFTestResults.Fail; } catch (ObjectDisposedException ode) { /* pass case */ Log.Comment( "Got correct exception: " + ode.Message ); result = MFTestResults.Pass; } try { Log.Comment("Write disposed stream"); fs = new MemoryStream(); fs.Dispose(); fs.Write(writebuff, 0, writebuff.Length); Log.Exception( "Expected ObjectDisposedException" ); return MFTestResults.Fail; } catch (ObjectDisposedException ode) { /* pass case */ Log.Comment( "Got correct exception: " + ode.Message ); result = MFTestResults.Pass; } } catch (Exception ex) { Log.Exception("Unexpected exception: " + ex.Message); return MFTestResults.Fail; } finally { if (fs != null) fs.Dispose(); } return result; } [TestMethod] public MFTestResults VanillaWrite_Dynamic_Ctor() { MFTestResults result = MFTestResults.Pass; try { using (MemoryStream ms = new MemoryStream()) { Log.Comment("Write 256 bytes of data"); if (!TestWrite(ms, 256)) return MFTestResults.Fail; Log.Comment("Write middle of buffer"); if (!TestWrite(ms, 256, 100, 100)) return MFTestResults.Fail; // 1000 - 256 - 100 = 644 Log.Comment("Write start of buffer"); if (!TestWrite(ms, 1000, 644, 0)) return MFTestResults.Fail; Log.Comment("Write end of buffer"); if (!TestWrite(ms, 1000, 900, 100)) return MFTestResults.Fail; Log.Comment("Rewind and verify all bytes written"); ms.Seek(0, SeekOrigin.Begin); if (!MemoryStreamHelper.VerifyRead(ms)) return MFTestResults.Fail; Log.Comment("Verify Read validation with UTF8 string"); ms.SetLength(0); string test = "MFFramework Test"; ms.Write(UTF8Encoding.UTF8.GetBytes(test), 0, test.Length); ms.Flush(); ms.Seek(0, SeekOrigin.Begin); byte[] readbuff = new byte[20]; int readlen = ms.Read(readbuff, 0, readbuff.Length); string testResult = new string(Encoding.UTF8.GetChars(readbuff, 0, readlen)); if (test != testResult) { Log.Comment( "Exepected: " + test + ", but got: " + testResult ); return MFTestResults.Fail; } } } catch (Exception ex) { Log.Exception("Unexpected exception: " + ex.Message); return MFTestResults.Fail; } return result; } [TestMethod] public MFTestResults VanillaWrite_Static_Ctor() { MFTestResults result = MFTestResults.Pass; try { byte[] buffer = new byte[1024]; using (MemoryStream ms = new MemoryStream(buffer)) { Log.Comment("Write 256 bytes of data"); if (!TestWrite(ms, 256, 1024)) return MFTestResults.Fail; Log.Comment("Write middle of buffer"); if (!TestWrite(ms, 256, 100, 100, 1024)) return MFTestResults.Fail; // 1000 - 256 - 100 = 644 Log.Comment("Write start of buffer"); if (!TestWrite(ms, 1000, 644, 0, 1024)) return MFTestResults.Fail; Log.Comment("Write past end of buffer"); try { TestWrite(ms, 50, 1024); Log.Exception( "Expected NotSupportedException" ); return MFTestResults.Fail; } catch (NotSupportedException nse) { /* pass case */ Log.Comment( "Got correct exception: " + nse.Message ); result = MFTestResults.Pass; } Log.Comment("Verify failed Write did not move position"); if (ms.Position != 1000) { Log.Comment( "Expected position to be 1000, but it is " + ms.Position ); return MFTestResults.Fail; } Log.Comment("Write final 24 bytes of static buffer"); if (!TestWrite(ms, 24)) return MFTestResults.Fail; Log.Comment("Rewind and verify all bytes written"); ms.Seek(0, SeekOrigin.Begin); if (!MemoryStreamHelper.VerifyRead(ms)) return MFTestResults.Fail; Log.Comment("Verify Read validation with UTF8 string"); ms.SetLength(0); string test = "MFFramework Test"; ms.Write(UTF8Encoding.UTF8.GetBytes(test), 0, test.Length); ms.Flush(); ms.Seek(0, SeekOrigin.Begin); byte[] readbuff = new byte[20]; int readlen = ms.Read(readbuff, 0, readbuff.Length); string testResult = new string(Encoding.UTF8.GetChars(readbuff, 0, readlen)); if (test != testResult) { Log.Comment( "Exepected: " + test + ", but got: " + testResult ); return MFTestResults.Fail; } } } catch (Exception ex) { Log.Exception("Unexpected exception: " + ex.Message); return MFTestResults.Fail; } return result; } [TestMethod] public MFTestResults ShiftBuffer() { MFTestResults result = MFTestResults.Pass; try { int bufSize; int iCountErrors = 0; for (int i = 1; i < 10; i++) { bufSize = i; MemoryStream ms = new MemoryStream(); for (int j = 0; j < bufSize; ++j) ms.WriteByte((byte)j); // Move everything forward by 1 byte ms.Seek(0, SeekOrigin.Begin); byte[] buf = ms.ToArray(); ms.Write(buf, 1, bufSize - 1); ms.Seek(0, SeekOrigin.Begin); //we'll read till one before the last since these should be shifted by 1 for (int j = 0; j < ms.Length - 1; ++j) { int bit = ms.ReadByte(); if (bit != j + 1) { ++iCountErrors; Log.Exception("Err_8324t! Check VSWhdibey #458551, Returned: " + bit + ", Expected: " + (j + 1)); } } //last bit should be the same if (ms.ReadByte() != i - 1) { ++iCountErrors; Log.Exception("Err_32947gs! Last bit is not correct Check VSWhdibey #458551"); } } //Buffer sizes of 9 (10 here since we shift by 1) and above doesn't have the above 'optimization' problem for (int i = 10; i < 64; i++) { bufSize = i; MemoryStream ms = new MemoryStream(); for (int j = 0; j < bufSize; ++j) ms.WriteByte((byte)j); // Move everything forward by 1 byte ms.Seek(0, SeekOrigin.Begin); byte[] buf = ms.ToArray(); ms.Write(buf, 1, bufSize - 1); ms.Seek(0, SeekOrigin.Begin); for (int j = 0; j < ms.Length; ++j) { int bit = ms.ReadByte(); if (j != ms.Length - 1) { if (bit != (j + 1)) { ++iCountErrors; Log.Exception("Err_235radg_" + i + "! Check VSWhdibey #458551, Returned: " + bit + ", Expected: " + (j + 1)); } } else if (bit != j) { ++iCountErrors; Log.Exception("Err_235radg_" + i + "! Check VSWhdibey #458551, Returned: " + bit + ", Expected:" + (j + 1)); } } } if (iCountErrors > 0) return MFTestResults.Fail; } catch (Exception ex) { Log.Exception("Unexpected exception: " + ex.Message); return MFTestResults.Fail; } return result; } [TestMethod] public MFTestResults BoundaryCheck() { MFTestResults result = MFTestResults.Pass; try { for (int i = 250; i < 260; i++) { using (MemoryStream ms = new MemoryStream()) { TestWrite(ms, i); ms.Position = 0; if (!MemoryStreamHelper.VerifyRead(ms)) return MFTestResults.Fail; Log.Comment("Position: " + ms.Position); Log.Comment("Length: " + ms.Length); if (i != ms.Position | i != ms.Length) { Log.Exception( "Expected Position and Length to be " + i ); return MFTestResults.Fail; } } } } catch (Exception ex) { Log.Exception("Unexpected exception: " + ex.Message); return MFTestResults.Fail; } return result; } #endregion Test Cases public MFTestMethod[] Tests { get { return new MFTestMethod[] { new MFTestMethod( InvalidCases, "InvalidCases" ), new MFTestMethod( VanillaWrite_Dynamic_Ctor, "VanillaWrite_Dynamic_Ctor" ), new MFTestMethod( VanillaWrite_Static_Ctor, "VanillaWrite_Static_Ctor" ), new MFTestMethod( ShiftBuffer, "ShiftBuffer" ), new MFTestMethod( BoundaryCheck, "BoundaryCheck" ), }; } } } } ================================================ FILE: Zelig/Zelig/FileSystemTest/MemoryStream/WriteByte.cs ================================================ //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // Copyright (c) Microsoft Corporation. All rights reserved. //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// using System; using System.IO; namespace FileSystemTest { public class WriteByte : IMFTestInterface { [SetUp] public InitializeResult Initialize() { Log.Comment("Adding set up for the tests."); // TODO: Add your set up steps here. return InitializeResult.ReadyToGo; } [TearDown] public void CleanUp() { Log.Comment("Cleaning up after the tests."); // TODO: Add your clean up steps here. } #region Helper methods private bool TestWrite(MemoryStream ms, int BytesToWrite) { return TestWrite(ms, BytesToWrite, ms.Position + BytesToWrite); } private bool TestWrite(MemoryStream ms, int BytesToWrite, long ExpectedLength) { bool result = true; long startLength = ms.Position; byte nextbyte = (byte)(startLength & 0xFF); for (int i = 0; i < BytesToWrite; i++) { ms.WriteByte((byte)nextbyte); nextbyte++; } ms.Flush(); if (ExpectedLength < ms.Length) { result = false; Log.Exception("Expeceted final length of " + ExpectedLength + " bytes, but got " + ms.Length + " bytes"); } return result; } #endregion Helper methods #region Test Cases [TestMethod] public MFTestResults ExtendBuffer() { MFTestResults result = MFTestResults.Pass; try { using (MemoryStream ms = new MemoryStream()) { Log.Comment("Set Position past end of stream"); // Internal buffer is initialized to 256, if this changes, this test is no longer valid. // Exposing capcity would have made this test easier/dynamic. ms.Position = 300; ms.WriteByte(123); if (ms.Length != 301) { Log.Exception( "Expected length 301, got length " + ms.Length ); return MFTestResults.Fail; } ms.Position = 300; int read = ms.ReadByte(); if (read != 123) { Log.Exception( "Expected value 123, but got value " + result ); return MFTestResults.Fail; } } } catch (Exception ex) { Log.Exception("Unexpected exception", ex); return MFTestResults.Fail; } return result; } [TestMethod] public MFTestResults InvalidRange() { MFTestResults result = MFTestResults.Pass; try { byte[] buffer = new byte[100]; using (MemoryStream ms = new MemoryStream(buffer)) { Log.Comment("Set Position past end of static stream"); ms.Position = buffer.Length + 1; try { ms.WriteByte(1); Log.Exception( "Expected NotSupportedException" ); return MFTestResults.Fail; } catch (NotSupportedException nse) { /* pass case */ Log.Comment( "Got correct exception: " + nse.Message ); result = MFTestResults.Pass; } } } catch (Exception ex) { Log.Exception("Unexpected exception", ex); return MFTestResults.Fail; } return result; } [TestMethod] public MFTestResults VanillaWrite() { MFTestResults result = MFTestResults.Pass; try { Log.Comment("Static Buffer"); byte[] buffer = new byte[100]; using (MemoryStream ms = new MemoryStream(buffer)) { Log.Comment("Write 50 bytes of data"); if (!TestWrite(ms, 50, 100)) return MFTestResults.Fail; Log.Comment("Write final 50 bytes of data"); if (!TestWrite(ms, 50, 100)) return MFTestResults.Fail; Log.Comment("Any more bytes written should throw"); try { ms.WriteByte(50); Log.Exception( "Expected NotSupportedException" ); return MFTestResults.Fail; } catch (NotSupportedException nse) { /* pass case */ Log.Comment( "Got correct exception: " + nse.Message ); result = MFTestResults.Pass; } Log.Comment("Rewind and verify all bytes written"); ms.Seek(0, SeekOrigin.Begin); if (!MemoryStreamHelper.VerifyRead(ms)) return MFTestResults.Fail; } Log.Comment("Dynamic Buffer"); using (MemoryStream ms = new MemoryStream()) { Log.Comment("Write 100 bytes of data"); if (!TestWrite(ms, 100)) return MFTestResults.Fail; Log.Comment("Extend internal buffer, write 160"); if (!TestWrite(ms, 160)) return MFTestResults.Fail; Log.Comment("Double extend internal buffer, write 644"); if (!TestWrite(ms, 644)) return MFTestResults.Fail; Log.Comment("write another 1100"); if (!TestWrite(ms, 1100)) return MFTestResults.Fail; Log.Comment("Rewind and verify all bytes written"); ms.Seek(0, SeekOrigin.Begin); if (!MemoryStreamHelper.VerifyRead(ms)) return MFTestResults.Fail; } } catch (Exception ex) { Log.Exception("Unexpected exception", ex); return MFTestResults.Fail; } return result; } [TestMethod] public MFTestResults BoundaryCheck() { MFTestResults result = MFTestResults.Pass; try { for (int i = 250; i < 260; i++) { using (MemoryStream ms = new MemoryStream()) { MemoryStreamHelper.Write(ms, i); ms.Position = 0; if (!MemoryStreamHelper.VerifyRead(ms)) return MFTestResults.Fail; Log.Comment("Position: " + ms.Position); Log.Comment("Length: " + ms.Length); if (i != ms.Position | i != ms.Length) { Log.Exception( "Expected Position and Length to be " + i ); return MFTestResults.Fail; } } } } catch (Exception ex) { Log.Exception("Unexpected exception: " + ex.Message); return MFTestResults.Fail; } return result; } #endregion Test Cases public MFTestMethod[] Tests { get { return new MFTestMethod[] { new MFTestMethod( ExtendBuffer, "ExtendBuffer" ), new MFTestMethod( InvalidRange, "InvalidRange" ), new MFTestMethod( VanillaWrite, "VanillaWrite" ), new MFTestMethod( BoundaryCheck, "BoundaryCheck" ), }; } } } } ================================================ FILE: Zelig/Zelig/FileSystemTest/MemoryStream/WriteTo.cs ================================================ //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // Copyright (c) Microsoft Corporation. All rights reserved. //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// using System; using System.IO; namespace FileSystemTest { public class WriteTo : IMFTestInterface { private bool _fileSystemInit; [SetUp] public InitializeResult Initialize() { // These tests rely on underlying file system so we need to make // sure we can format it before we start the tests. If we can't // format it, then we assume there is no FS to test on this platform. // delete the directory DOTNETMF_FS_EMULATION try { IOTests.IntializeVolume(); _fileSystemInit = true; } catch (Exception ex) { Log.Exception("Skipping: Unable to initialize file system", ex); _fileSystemInit = false; } return InitializeResult.ReadyToGo; } [TearDown] public void CleanUp() { Log.Comment("Cleaning up after the tests."); // TODO: Add your clean up steps here. } #region Test Cases [TestMethod] public MFTestResults InvalidArgs() { MFTestResults result = MFTestResults.Pass; try { using (MemoryStream ms = new MemoryStream()) { Log.Comment("Initialize stream"); MemoryStreamHelper.Write(ms, 1000); try { Log.Comment("null stream"); ms.WriteTo(null); Log.Exception( "Expected ArgumentNullException" ); return MFTestResults.Fail; } catch (ArgumentNullException ane) { /* pass case */ Log.Comment( "Got correct exception: " + ane.Message ); result = MFTestResults.Pass; } if (_fileSystemInit) { try { Log.Comment("pass in read-only stream"); using (FileStream fs = new FileStream("readonly", FileMode.OpenOrCreate, FileAccess.Read)) { ms.WriteTo(fs); } } catch (NotSupportedException nse) { /* pass case */ Log.Comment( "Got correct exception: " + nse.Message ); result = MFTestResults.Pass; } } try { Log.Comment("Target Stream closed"); MemoryStream mst = new MemoryStream(); mst.Close(); ms.WriteTo(mst); Log.Exception( "Expected ObjectDisposedException" ); return MFTestResults.Fail; } catch (ObjectDisposedException ode) { /* pass case */ Log.Comment( "Got correct exception: " + ode.Message ); result = MFTestResults.Pass; } try { Log.Comment("Current Stream closed"); ms.Close(); using (MemoryStream mst = new MemoryStream()) { ms.WriteTo(mst); Log.Exception( "Expected ObjectDisposedException" ); return MFTestResults.Fail; } } catch (ObjectDisposedException ode) { /* pass case */ Log.Comment( "Got correct exception: " + ode.Message ); result = MFTestResults.Pass; } } } catch (Exception ex) { Log.Exception("Unexpected exception", ex); return MFTestResults.Fail; } return result; } [TestMethod] public MFTestResults WriteTo_FileStream() { // Don't run test if no FileSystem if (!_fileSystemInit) return MFTestResults.Skip; MFTestResults result = MFTestResults.Pass; string fileName = "WriteTo_FileStream.txt"; try { using (MemoryStream ms = new MemoryStream()) { Log.Comment("Initialize stream with 1234 bytes"); MemoryStreamHelper.Write(ms, 1234); using (FileStream fs = new FileStream(fileName, FileMode.Create)) { Log.Comment("WriteTo FileStream"); ms.WriteTo(fs); } Log.Comment("Verify closed file"); using (FileStream fs = new FileStream(fileName, FileMode.Open)) { if (fs.Length != 1234) { Log.Exception( "Expected 1234 bytes, but got " + fs.Length ); return MFTestResults.Fail; } if (!MemoryStreamHelper.VerifyRead(fs)) return MFTestResults.Fail; } } } catch (Exception ex) { Log.Exception("Unexpected exception", ex); return MFTestResults.Fail; } return result; } [TestMethod] public MFTestResults WriteTo_MemoryStream() { MFTestResults result = MFTestResults.Pass; try { using (MemoryStream ms = new MemoryStream()) { Log.Comment("Initialize stream with 1234 bytes"); MemoryStreamHelper.Write(ms, 1234); using (MemoryStream ms2 = new MemoryStream()) { Log.Comment("WriteTo MemoryStream"); ms.WriteTo(ms2); Log.Comment("Verify 2nd MemoryStream"); if (ms2.Length != 1234) { Log.Exception( "Expected 1234 bytes, but got " + ms2.Length ); return MFTestResults.Fail; } ms2.Position = 0; if (!MemoryStreamHelper.VerifyRead(ms2)) return MFTestResults.Fail; } } } catch (Exception ex) { Log.Exception("Unexpected exception", ex); return MFTestResults.Fail; } return result; } #endregion Test Cases public MFTestMethod[] Tests { get { return new MFTestMethod[] { new MFTestMethod( InvalidArgs, "InvalidArgs" ), new MFTestMethod( WriteTo_FileStream, "WriteTo_FileStream" ), new MFTestMethod( WriteTo_MemoryStream, "WriteTo_MemoryStream" ), }; } } } } ================================================ FILE: Zelig/Zelig/FileSystemTest/Path/ChangeExtension.cs ================================================ //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // Copyright (c) Microsoft Corporation. All rights reserved. //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// using System; using System.IO; namespace FileSystemTest { public class ChangeExtensions : IMFTestInterface { [SetUp] public InitializeResult Initialize() { Log.Comment("Adding set up for the tests."); // Add your functionality here. return InitializeResult.ReadyToGo; } [TearDown] public void CleanUp() { } #region class vars private const string defaultPath = @"de\\fault.path"; private const string exe = ".exe"; private const string cool = ".cool"; #endregion class vars #region helper funtions private bool TestChangeExtension(String path, String extension) { string expected = ""; int iIndex = path.LastIndexOf('.') ; if(iIndex > -1) { switch(extension) { case null: expected = path.Substring( 0, iIndex ); break; case "": expected = path.Substring( 0, iIndex + 1 ); break; default: expected = path.Substring( 0, iIndex ) + extension; break; } } else if(extension != null) { expected = path + extension; } else { expected = path; } Log.Comment("Original Path: " + path); Log.Comment("Expected Path: " + expected); string result = Path.ChangeExtension(path, extension); if (result != expected) { Log.Exception("Got Path: " + result); return false; } return true; } #endregion helper functions #region Test Cases [TestMethod] public MFTestResults NullArgumentPath() { MFTestResults result = MFTestResults.Pass; try { string strExtension = Path.ChangeExtension(null, exe); Log.Comment("Expect: null"); if (strExtension != null) { Log.Exception("FAIL - Got: " + strExtension); return MFTestResults.Fail; } } catch (Exception ex) { Log.Exception("Unexpected exception: " + ex.Message); return MFTestResults.Fail; } return result; } [TestMethod] public MFTestResults NullArgumentExtension() { MFTestResults result = MFTestResults.Pass; try { if (!TestChangeExtension(defaultPath, null)) { return MFTestResults.Fail; } } catch (Exception ex) { Log.Exception("Unexpected exception: " + ex.Message); return MFTestResults.Fail; } return result; } [TestMethod] public MFTestResults ZeroLengthPath() { MFTestResults result = MFTestResults.Pass; try { string strExtension = Path.ChangeExtension("", exe); Log.Comment("Expect empty result"); if ( strExtension != "") { Log.Exception("Got: '" + strExtension + "'"); return MFTestResults.Fail; } } catch (Exception ex) { Log.Exception("Unexpected exception: " + ex.Message); return MFTestResults.Fail; } return result; } [TestMethod] public MFTestResults ZeroLengthExtension() { MFTestResults result = MFTestResults.Pass; try { if (!TestChangeExtension(defaultPath, "")) { return MFTestResults.Fail; } } catch (Exception ex) { Log.Exception("Unexpected exception: " + ex.Message); return MFTestResults.Fail; } return result; } [TestMethod] public MFTestResults StringEmptyPath() { MFTestResults result = MFTestResults.Pass; try { string strExtension = Path.ChangeExtension("", exe); if (strExtension != String.Empty) { Log.Exception("Got: '" + strExtension + "'"); return MFTestResults.Fail; } } catch (Exception ex) { Log.Exception("Unexpected exception: " + ex.Message); return MFTestResults.Fail; } return result; } [TestMethod] public MFTestResults StringEmptyExtension() { MFTestResults result = MFTestResults.Pass; try { if (!TestChangeExtension(defaultPath, string.Empty)) { return MFTestResults.Fail; } } catch (Exception ex) { Log.Exception("Unexpected exception: " + ex.Message); return MFTestResults.Fail; } return result; } [TestMethod] public MFTestResults WhiteSpace() { MFTestResults result = MFTestResults.Pass; try { string strExtension = Path.ChangeExtension(" ", exe); Log.Comment("BUG? - The Desktop has the same behavior, but this is their test case, so don't know right behavior"); Log.Comment("We will wait to hear back from CLR team to decide what the correct behavior is."); Log.Exception("Expected ArgumentException, got " + strExtension); result = MFTestResults.KnownFailure; } catch (ArgumentException ae) { /* pass case */ Log.Comment( "Got correct exception: " + ae.Message ); result = MFTestResults.Pass; } catch (Exception ex) { Log.Exception("Unexpected exception: " + ex.Message); return MFTestResults.Fail; } return result; } [TestMethod] public MFTestResults InvalidChars() { MFTestResults result = MFTestResults.Pass; foreach (char badChar in Path.InvalidPathChars) { try { string path = new string(new char[] { badChar, 'b', 'a', 'd', badChar, 'p', 'a', 't', 'h', badChar }); Log.FilteredComment("Testing path: " + path); string strExtension = Path.ChangeExtension(path, exe); } catch (ArgumentException ae) { /* pass case */ Log.Comment( "Got correct exception: " + ae.Message ); } catch (Exception ex) { Log.Exception("Unexpected exception: " + ex.Message); return MFTestResults.Fail; } } return result; } [TestMethod] public MFTestResults NoExtensionPath() { MFTestResults result = MFTestResults.Pass; try { string path = "jabba\\de\\hutt"; if (! TestChangeExtension(path, exe)) { return MFTestResults.Fail; } } catch (Exception ex) { Log.Exception("Unexpected exception: " + ex.Message); return MFTestResults.Fail; } return result; } [TestMethod] public MFTestResults MultiDotPath() { MFTestResults result = MFTestResults.Pass; try { string path = "jabba..de..hutt..."; if (!TestChangeExtension(path, exe)) { return MFTestResults.Fail; } } catch (Exception ex) { Log.Exception("Unexpected exception: " + ex.Message); return MFTestResults.Fail; } return result; } [TestMethod] public MFTestResults ValidExtension() { MFTestResults result = MFTestResults.Pass; try { string path = "jabba\\de\\hutt.solo"; if (!TestChangeExtension(path, exe)) { return MFTestResults.Fail; } } catch (Exception ex) { Log.Exception("Unexpected exception: " + ex.Message); return MFTestResults.Fail; } return result; } [TestMethod] public MFTestResults SpecialSymbolPath() { MFTestResults result = MFTestResults.Pass; try { string path = "foo.bar.fkl;fkds92-509450-4359.213213213@*?2-3203-=210"; if (!TestChangeExtension(path, cool)) { return MFTestResults.Fail; } } catch (Exception ex) { Log.Exception("Unexpected exception: " + ex.Message); return MFTestResults.Fail; } return result; } [TestMethod] public MFTestResults SpecialSymbolExtension() { MFTestResults result = MFTestResults.Pass; try { string extension = ".$#@$_)+_)!@@!!@##&_$)#_"; if (!TestChangeExtension(defaultPath, extension)) { return MFTestResults.Fail; } } catch (Exception ex) { Log.Exception("Unexpected exception: " + ex.Message); return MFTestResults.Fail; } return result; } [TestMethod] public MFTestResults LongExtension() { MFTestResults result = MFTestResults.Pass; try { string path = new string('a', 256) + exe; string extension = "." + new string('b', 256); string strExtension = Path.ChangeExtension(path, extension); if (!TestChangeExtension(path, extension)) { return MFTestResults.Fail; } } catch (Exception ex) { Log.Exception("Unexpected exception: " + ex.Message); return MFTestResults.Fail; } return result; } [TestMethod] public MFTestResults OneCharExtension() { MFTestResults result = MFTestResults.Pass; try { string extension = ".z"; if (!TestChangeExtension(defaultPath, extension)) { return MFTestResults.Fail; } } catch (Exception ex) { Log.Exception("Unexpected exception: " + ex.Message); return MFTestResults.Fail; } return result; } #endregion Test Cases public MFTestMethod[] Tests { get { return new MFTestMethod[] { new MFTestMethod( NullArgumentPath, "NullArgumentPath" ), new MFTestMethod( NullArgumentExtension, "NullArgumentExtension" ), new MFTestMethod( ZeroLengthPath, "ZeroLengthPath" ), new MFTestMethod( ZeroLengthExtension, "ZeroLengthExtension" ), new MFTestMethod( StringEmptyPath, "StringEmptyPath" ), new MFTestMethod( StringEmptyExtension, "StringEmptyExtension" ), new MFTestMethod( WhiteSpace, "WhiteSpace" ), new MFTestMethod( InvalidChars, "InvalidChars" ), new MFTestMethod( NoExtensionPath, "NoExtensionPath" ), new MFTestMethod( MultiDotPath, "MultiDotPath" ), new MFTestMethod( ValidExtension, "ValidExtension" ), new MFTestMethod( SpecialSymbolPath, "SpecialSymbolPath" ), new MFTestMethod( SpecialSymbolExtension, "SpecialSymbolExtension" ), new MFTestMethod( LongExtension, "LongExtension" ), new MFTestMethod( OneCharExtension, "OneCharExtension" ), }; } } } } ================================================ FILE: Zelig/Zelig/FileSystemTest/Path/Combine.cs ================================================ //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // Copyright (c) Microsoft Corporation. All rights reserved. //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// using System; using System.IO; namespace FileSystemTest { public class Combine : IMFTestInterface { [SetUp] public InitializeResult Initialize() { Log.Comment("Adding set up for the tests."); // Add your functionality here. return InitializeResult.ReadyToGo; } [TearDown] public void CleanUp() { } #region helper methods private bool TestCombine(string arg1, string arg2, string expected) { string path = Path.Combine(arg1, arg2); Log.Comment("Arg1: '" + arg1 + "'"); Log.Comment("Arg2: '" + arg2 + "'"); Log.Comment("Expected: '" + expected + "'"); if (path != expected) { Log.Exception("Got: '" + path + "'"); return false; } return true; } # endregion helper methods #region Test Cases [TestMethod] public MFTestResults NullArguments() { MFTestResults result = MFTestResults.Pass; try { Log.Comment("null 1st param"); string path = Path.Combine(null, ""); Log.Exception("Expected Argument exception, but got path: " + path); } catch (ArgumentException ae) { /* pass case */ Log.Comment( "Got correct exception: " + ae.Message ); } catch (Exception ex) { Log.Exception("Unexpected exception: " + ex.Message); return MFTestResults.Fail; } try { Log.Comment("null 2nd param"); string path = Path.Combine("", null); Log.Exception("Expected Argument exception, but got path: " + path); } catch (ArgumentException ae) { /* pass case */ Log.Comment( "Got correct exception: " + ae.Message ); } catch (Exception ex) { Log.Exception("Unexpected exception: " + ex.Message); return MFTestResults.Fail; } return result; } [TestMethod] public MFTestResults Root() { MFTestResults result = MFTestResults.Pass; try { string root = "\\"; /// Expected output "\\" or root, See remarks section in MSDN Path.Combine /// http://msdn.microsoft.com/en-us/library/system.io.path.combine.aspx?PHPSESSID=ca9tbhkv7klmem4g3b2ru2q4d4 if (!TestCombine(root, root, root)) { return MFTestResults.Fail; } } catch (Exception ex) { Log.Exception("Unexpected exception: " + ex.Message); return MFTestResults.Fail; } return result; } [TestMethod] public MFTestResults SameRoot() { MFTestResults result = MFTestResults.Pass; try { string root = "\\nand1"; if (!TestCombine(root, root, root)) { return MFTestResults.Fail; } if (!TestCombine(root + "\\dir", root + "\\dir", root + "\\dir")) { return MFTestResults.Fail; } } catch (Exception ex) { Log.Exception("Unexpected exception: " + ex.Message); return MFTestResults.Fail; } return result; } [TestMethod] public MFTestResults EmptyArgs() { MFTestResults result = MFTestResults.Pass; try { string croot = "\\sd1"; if (!TestCombine(croot, "", croot)) { return MFTestResults.Fail; } if (!TestCombine("", croot, croot)) { return MFTestResults.Fail; } if (!TestCombine("", "", "")) { return MFTestResults.Fail; } } catch (Exception ex) { Log.Exception("Unexpected exception: " + ex.Message); return MFTestResults.Fail; } return result; } [TestMethod] public MFTestResults TwoUnique() { MFTestResults result = MFTestResults.Pass; try { if (!TestCombine("Hello", "World", "Hello\\World")) { return MFTestResults.Fail; } } catch (Exception ex) { Log.Exception("Unexpected exception: " + ex.Message); return MFTestResults.Fail; } return result; } [TestMethod] public MFTestResults TwoUniqueWithRoot() { MFTestResults result = MFTestResults.Pass; try { if (!TestCombine("\\sd1\\Hello\\", "World", "\\sd1\\Hello\\World")) { return MFTestResults.Fail; } } catch (Exception ex) { Log.Exception("Unexpected exception: " + ex.Message); return MFTestResults.Fail; } return result; } [TestMethod] public MFTestResults SecondBeginWithSlash() { MFTestResults result = MFTestResults.Pass; try { if (!TestCombine("\\sd1\\Hello", "\\World", "\\World")) { return MFTestResults.Fail; } } catch (Exception ex) { Log.Exception("Unexpected exception: " + ex.Message); return MFTestResults.Fail; } return result; } [TestMethod] public MFTestResults UNCName() { MFTestResults result = MFTestResults.Pass; try { string unc = @"\\\\radt\VbSsDb\VbTests\shadow\FXBCL\test\auto\System_IO\Path\"; if (!TestCombine(unc, "World", unc + "World")) { return MFTestResults.Fail; } if (!TestCombine("\\", unc, unc)) { return MFTestResults.Fail; } } catch (Exception ex) { Log.Exception("Unexpected exception: " + ex.Message); return MFTestResults.Fail; } return result; } [TestMethod] public MFTestResults MultipleSubDirs() { MFTestResults result = MFTestResults.Pass; try { if (!TestCombine("\\MyDir\\Hello\\", "World\\You\\Are\\My\\Creation", "\\MyDir\\Hello\\World\\You\\Are\\My\\Creation")) { return MFTestResults.Fail; } } catch (Exception ex) { Log.Exception("Unexpected exception: " + ex.Message); return MFTestResults.Fail; } return result; } [TestMethod] public MFTestResults FirstRootedSecondNot() { MFTestResults result = MFTestResults.Pass; try { if (!TestCombine("\\sd1\\MyDirectory\\Sample", "Test", "\\sd1\\MyDirectory\\Sample\\Test")) { return MFTestResults.Fail; } } catch (Exception ex) { Log.Exception("Unexpected exception: " + ex.Message); return MFTestResults.Fail; } return result; } [TestMethod] public MFTestResults CombineDot() { MFTestResults result = MFTestResults.Pass; try { if (!TestCombine("\\sd1\\Directory", ".\\SubDir", "\\sd1\\Directory\\.\\SubDir")) { return MFTestResults.Fail; } if (!TestCombine("\\sd1\\Directory\\..", "SubDir", "\\sd1\\Directory\\..\\SubDir")) { return MFTestResults.Fail; } } catch (Exception ex) { Log.Exception("Unexpected exception: " + ex.Message); return MFTestResults.Fail; } return result; } [TestMethod] public MFTestResults WhiteSpace() { MFTestResults result = MFTestResults.Pass; try { //white space inside if (!TestCombine("\\sd1\\Directory Name", "Sub Dir", "\\sd1\\Directory Name\\Sub Dir")) { return MFTestResults.Fail; } //white space end of arg1 /// Since path2 is rooted, it is also the expected result. See MSDN remarks section: /// http://msdn.microsoft.com/en-us/library/system.io.path.combine.aspx?PHPSESSID=ca9tbhkv7klmem4g3b2ru2q4d4 if (!TestCombine("\\sd1\\Directory Name\\ ", "\\Sub Dir", "\\Sub Dir")) { return MFTestResults.Fail; } //white space start of arg2 if (!TestCombine("\\sd1\\Directory Name", " \\Sub Dir", "\\sd1\\Directory Name\\ \\Sub Dir")) { return MFTestResults.Fail; } } catch (Exception ex) { Log.Exception("Unexpected exception: " + ex.Message); return MFTestResults.Fail; } return result; } [TestMethod] public MFTestResults ForwardSlashes() { MFTestResults result = MFTestResults.Pass; try { /// Forward slash is illegal for us, an exception should be thrown. TestCombine("//sd1//Directory Name//", "Sub//Dir", "//sd1//Directory Name//Sub//Dir"); return MFTestResults.Fail; } catch (Exception ex) { Log.Exception("Exception: " + ex.Message); result = MFTestResults.Pass; } return result; } #endregion Test Cases public MFTestMethod[] Tests { get { return new MFTestMethod[] { new MFTestMethod( NullArguments, "NullArguments" ), new MFTestMethod( Root, "Root" ), new MFTestMethod( SameRoot, "SameRoot" ), new MFTestMethod( EmptyArgs, "EmptyArgs" ), new MFTestMethod( TwoUnique, "TwoUnique" ), new MFTestMethod( TwoUniqueWithRoot, "TwoUniqueWithRoot" ), new MFTestMethod( SecondBeginWithSlash, "SecondBeginWithSlash" ), new MFTestMethod( UNCName, "UNCName" ), new MFTestMethod( MultipleSubDirs, "MultipleSubDirs" ), new MFTestMethod( FirstRootedSecondNot, "FirstRootedSecondNot" ), new MFTestMethod( CombineDot, "CombineDot" ), new MFTestMethod( WhiteSpace, "WhiteSpace" ), new MFTestMethod( ForwardSlashes, "ForwardSlashes" ), }; } } } } ================================================ FILE: Zelig/Zelig/FileSystemTest/Path/GetDirectoryName.cs ================================================ //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // Copyright (c) Microsoft Corporation. All rights reserved. //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// using System; using System.IO; namespace FileSystemTest { public class GetDirectoryName : IMFTestInterface { [SetUp] public InitializeResult Initialize() { Log.Comment("Adding set up for the tests"); return InitializeResult.ReadyToGo; } [TearDown] public void CleanUp() { } #region helper methods private bool TestGetDirectoryName(string path, string expected) { string result = Path.GetDirectoryName(path); Log.Comment("Path: '" + path + "'"); Log.Comment("Expected: '" + expected + "'"); if (result != expected) { Log.Exception("Got: '" + result + "'"); return false; } return true; } #endregion helper methods #region Test Cases [TestMethod] public MFTestResults NullPath() { MFTestResults result = MFTestResults.Pass; try { if (!TestGetDirectoryName(null, null)) { return MFTestResults.Fail; } } catch (Exception ex) { Log.Exception("Unexpected exception: " + ex.Message); return MFTestResults.Fail; } return result; } [TestMethod] public MFTestResults Vanilla() { MFTestResults result = MFTestResults.Pass; try { if (!TestGetDirectoryName("Hello\\file.tmp", "Hello")) { return MFTestResults.Fail; } } catch (Exception ex) { Log.Exception("Unexpected exception: " + ex.Message); return MFTestResults.Fail; } return result; } [TestMethod] public MFTestResults StartWithSlash() { MFTestResults result = MFTestResults.Pass; try { //single slash if (!TestGetDirectoryName("\\Root\\File", "\\Root")) { return MFTestResults.Fail; } //root double slash if (!TestGetDirectoryName("\\\\Machine\\Directory\\File", "\\\\Machine\\Directory")) { return MFTestResults.Fail; } //root triple slash, this will throw an exception. try { TestGetDirectoryName("\\\\\\Machine\\Directory\\File", null); return MFTestResults.Fail; } catch (ArgumentException) { result = MFTestResults.Pass; } } catch (Exception ex) { Log.Exception("Unexpected exception: " + ex.Message); return MFTestResults.Fail; } return result; } [TestMethod] public MFTestResults WhiteSpace() { MFTestResults result = MFTestResults.Pass; try { //white space in directory if (!TestGetDirectoryName("\\root\\Directory Name\\Hello.tmp file.tmp", "\\root\\Directory Name")) { return MFTestResults.Fail; } //white space in file if (!TestGetDirectoryName("\\root\\Directory Name\\File Name.tmp file.tmp", "\\root\\Directory Name")) { return MFTestResults.Fail; } //white space at Root if (!TestGetDirectoryName("\\root\\Hello.tmp file.tmp", "\\root")) { return MFTestResults.Fail; } } catch (Exception ex) { Log.Exception("Unexpected exception: " + ex.Message); return MFTestResults.Fail; } return result; } [TestMethod] public MFTestResults ForwardSlashes() { MFTestResults result = MFTestResults.Pass; try { /// Forward slash is invalid. TestGetDirectoryName("//root//Director//file.tmp", "\\root\\Directory"); return MFTestResults.Fail; } catch (ArgumentException) { result = MFTestResults.Pass; } catch (Exception ex) { Log.Exception("Exception: " + ex.Message); return MFTestResults.Fail; } return result; } [TestMethod] public MFTestResults EndingDirectory() { MFTestResults result = MFTestResults.Pass; try { if (!TestGetDirectoryName("\\root\\Dir1\\Dir2\\", "\\root\\Dir1\\Dir2")) { return MFTestResults.Fail; } } catch (Exception ex) { Log.Exception("Unexpected exception: " + ex.Message); return MFTestResults.Fail; } return result; } [TestMethod] public MFTestResults DeepTree() { MFTestResults result = MFTestResults.Pass; try { string deepTree = "\\root\\Dir1\\Dir2\\Dir1\\Dir2\\Dir1\\Dir2\\Dir1\\Dir2\\Dir1\\Dir2\\Dir1\\Dir2\\Dir1\\Dir2\\Dir1\\Dir2\\Dir1\\Dir2\\Dir1\\Dir2\\Dir1\\Dir2\\Dir2\\Dir1\\Dir2\\Dir1\\Dir2"; if (!TestGetDirectoryName(deepTree + "\\File.exe", deepTree)) { return MFTestResults.Fail; } } catch (Exception ex) { Log.Exception("Unexpected exception: " + ex.Message); return MFTestResults.Fail; } return result; } [TestMethod] public MFTestResults RootPath() { MFTestResults result = MFTestResults.Pass; try { if (!TestGetDirectoryName("\\", null)) { return MFTestResults.Fail; } } catch (Exception ex) { Log.Exception("Unexpected exception: " + ex.Message); return MFTestResults.Fail; } return result; } [TestMethod] public MFTestResults UNCPath() { MFTestResults result = MFTestResults.Pass; try { if (!TestGetDirectoryName("\\\\Machine\\Directory\\File", "\\\\Machine\\Directory")) { return MFTestResults.Fail; } } catch (Exception ex) { Log.Exception("Unexpected exception: " + ex.Message); return MFTestResults.Fail; } return result; } [TestMethod] public MFTestResults DotsAtEnd() { MFTestResults result = MFTestResults.Pass; try { if (!TestGetDirectoryName("\\root\\test\\.", "\\root\\test")) { return MFTestResults.Fail; } try { Path.GetDirectoryName("\\root\\test\\ ."); Log.Exception("Expected Argument exception"); return MFTestResults.Fail; } catch (ArgumentException ae) { /* pass case */ Log.Comment( "Got correct exception: " + ae.Message ); result = MFTestResults.Pass; } } catch (Exception ex) { Log.Exception("Unexpected exception: " + ex.Message); return MFTestResults.Fail; } return result; } [TestMethod] public MFTestResults ArgumentExceptionTests() { MFTestResults result = MFTestResults.Pass; try { string[] invalidArgs = { "", " ", " ", "\t", "\n", "\r\n" }; foreach (string path in invalidArgs) { try { string dir = Path.GetDirectoryName(path); Log.Exception("Expected Argument exception for '" + path + "' but got: '" + dir + "'"); return MFTestResults.Fail; } catch (ArgumentException ae) { /* pass case */ Log.Comment( "Got correct exception: " + ae.Message ); } } foreach (char invalidChar in Path.GetInvalidPathChars()) { try { Log.Comment("Invalid char ascii val = " + (int)invalidChar); string path = new string(new char[] { invalidChar, 'b', 'a', 'd', invalidChar, 'p', 'a', 't', 'h', invalidChar }); string dir = Path.GetDirectoryName(path); Log.Exception("Expected Argument exception for '" + path + "' but got: '" + dir + "'"); return MFTestResults.Fail; } catch (ArgumentException ae) { /* pass case */ Log.Comment( "Got correct exception: " + ae.Message ); } } } catch (Exception ex) { Log.Exception("Unexpected exception: " + ex.Message); return MFTestResults.Fail; } return result; } #endregion Test Cases public MFTestMethod[] Tests { get { return new MFTestMethod[] { new MFTestMethod( NullPath, "NullPath" ), new MFTestMethod( Vanilla, "Vanilla" ), new MFTestMethod( StartWithSlash, "StartWithSlash" ), new MFTestMethod( WhiteSpace, "WhiteSpace" ), new MFTestMethod( ForwardSlashes, "ForwardSlashes" ), new MFTestMethod( EndingDirectory, "EndingDirectory" ), new MFTestMethod( DeepTree, "DeepTree" ), new MFTestMethod( RootPath, "RootPath" ), new MFTestMethod( UNCPath, "UNCPath" ), new MFTestMethod( DotsAtEnd, "DotsAtEnd" ), new MFTestMethod( ArgumentExceptionTests, "ArgumentExceptionTests" ), }; } } } } ================================================ FILE: Zelig/Zelig/FileSystemTest/Path/GetExtension.cs ================================================ //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // Copyright (c) Microsoft Corporation. All rights reserved. //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// using System; using System.IO; namespace FileSystemTest { public class GetExtension : IMFTestInterface { [SetUp] public InitializeResult Initialize() { Log.Comment("Adding set up for the tests"); return InitializeResult.ReadyToGo; } [TearDown] public void CleanUp() { } #region helper methods private bool TestGetExtension(string path, string expected) { string result = Path.GetExtension(path); Log.Comment("Path: '" + path + "'"); Log.Comment("Expected: '" + expected + "'"); if (result != expected) { Log.Exception("Got: '" + result + "'"); return false; } return true; } #endregion helper methods #region Test Cases [TestMethod] public MFTestResults Null() { MFTestResults result = MFTestResults.Pass; try { if (!TestGetExtension(null, null)) { return MFTestResults.Fail; } } catch (Exception ex) { Log.Exception("Unexpected exception: " + ex.Message); return MFTestResults.Fail; } return result; } [TestMethod] public MFTestResults StringEmpty() { MFTestResults result = MFTestResults.Pass; try { if (!TestGetExtension(String.Empty, String.Empty)) { return MFTestResults.Fail; } if (!TestGetExtension("", "")) { return MFTestResults.Fail; } } catch (Exception ex) { Log.Exception("Unexpected exception: " + ex.Message); return MFTestResults.Fail; } return result; } [TestMethod] public MFTestResults PathNoExtension() { MFTestResults result = MFTestResults.Pass; try { if (!TestGetExtension("\\jabba\\de\\hutt", "")) { return MFTestResults.Fail; } if (!TestGetExtension("jabba\\de\\hutt", "")) { return MFTestResults.Fail; } } catch (Exception ex) { Log.Exception("Unexpected exception: " + ex.Message); return MFTestResults.Fail; } return result; } [TestMethod] public MFTestResults MultiDots() { MFTestResults result = MFTestResults.Pass; try { if (!TestGetExtension("luke.......sky....", "")) { return MFTestResults.Fail; } if (!TestGetExtension("luke.sky.Walker...", "")) { return MFTestResults.Fail; } if (!TestGetExtension(@"luke.sky.Walker.\..", "")) { return MFTestResults.Fail; } if (!TestGetExtension(@"lukeskyWalker\.", "")) { return MFTestResults.Fail; } if (!TestGetExtension(@"luke.sky.Walker.", "")) { return MFTestResults.Fail; } } catch (Exception ex) { Log.Exception("Unexpected exception: " + ex.Message); return MFTestResults.Fail; } return result; } [TestMethod] public MFTestResults ValidExension() { MFTestResults result = MFTestResults.Pass; try { if (!TestGetExtension(@"dir1\dir2\file.1", ".1")) { return MFTestResults.Fail; } if (!TestGetExtension(@"\sd1\dir1\dir2\file.to", ".to")) { return MFTestResults.Fail; } if (!TestGetExtension(@"\sd1\dir1\dir2\file.txt", ".txt")) { return MFTestResults.Fail; } //File name has special chars, but valid extension if (!TestGetExtension(@"foo.bar.fkl;fkds92-509450-4359.$#%()#%().%#(%)_#(%_).cool", ".cool")) { return MFTestResults.Fail; } //Extension has special chars string extension = ".$#@$_)+_)!@@!!@##&_$)#_"; if (!TestGetExtension("foo" + extension, extension)) { return MFTestResults.Fail; } if (!TestGetExtension(@"\sd1\dir1\dir2\file.longextensionname", ".longextensionname")) { return MFTestResults.Fail; } string verylong = "." + new string('x', 256); if (!TestGetExtension(@"\sd1\dir1\dir2\file" + verylong, verylong)) { return MFTestResults.Fail; } } catch (Exception ex) { Log.Exception("Unexpected exception: " + ex.Message); return MFTestResults.Fail; } return result; } [TestMethod] public MFTestResults ArgumentExceptionTests() { MFTestResults result = MFTestResults.Pass; try { foreach (char invalidChar in Path.GetInvalidPathChars()) { try { Log.Comment("Invalid char ascii val = " + (int)invalidChar); string path = new string(new char[] { invalidChar, 'b', 'a', 'd', '.', invalidChar, 'p', 'a', 't', 'h', invalidChar }); string dir = Path.GetExtension(path); if ((path.Length == 0) && (dir.Length == 0)) { /// If path is empty string, returned value is also empty string (same behavior in desktop) /// no exception thrown. } else { Log.Exception("Expected Argument exception for '" + path + "' but got: '" + dir + "'"); return MFTestResults.Fail; } } catch (ArgumentException ae) { /* pass case */ Log.Comment( "Got correct exception: " + ae.Message ); } } } catch (Exception ex) { Log.Exception("Unexpected exception: " + ex.Message); return MFTestResults.Fail; } return result; } #endregion Test Cases public MFTestMethod[] Tests { get { return new MFTestMethod[] { new MFTestMethod( Null, "Null" ), new MFTestMethod( StringEmpty, "StringEmpty" ), new MFTestMethod( PathNoExtension, "PathNoExtension" ), new MFTestMethod( MultiDots, "MultiDots" ), new MFTestMethod( ValidExension, "ValidExension" ), new MFTestMethod( ArgumentExceptionTests, "ArgumentExceptionTests" ), }; } } } } ================================================ FILE: Zelig/Zelig/FileSystemTest/Path/GetFileName.cs ================================================ //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // Copyright (c) Microsoft Corporation. All rights reserved. //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// using System; using System.IO; namespace FileSystemTest { public class GetFileName : IMFTestInterface { [SetUp] public InitializeResult Initialize() { Log.Comment("Adding set up for the tests"); return InitializeResult.ReadyToGo; } [TearDown] public void CleanUp() { } #region helper methods private bool TestGetFileName(string path, string expected) { string result = Path.GetFileName(path); Log.Comment("Path: '" + path + "'"); Log.Comment("Expected: '" + expected + "'"); if (result != expected) { Log.Exception("Got: '" + result + "'"); return false; } return true; } #endregion helper methods #region Test Cases [TestMethod] public MFTestResults Null() { MFTestResults result = MFTestResults.Pass; try { if (!TestGetFileName(null, null)) { return MFTestResults.Fail; } if (!TestGetFileName("", "")) { return MFTestResults.Fail; } if (!TestGetFileName(string.Empty, string.Empty)) { return MFTestResults.Fail; } } catch (Exception ex) { Log.Exception("Unexpected exception: " + ex.Message); return MFTestResults.Fail; } return result; } [TestMethod] public MFTestResults ValidCases() { MFTestResults result = MFTestResults.Pass; try { if (!TestGetFileName(@"file.tmp", "file.tmp")) { return MFTestResults.Fail; } if (!TestGetFileName(@"directory\file.tmp", "file.tmp")) { return MFTestResults.Fail; } if (!TestGetFileName(@"\directory\file.tmp", "file.tmp")) { return MFTestResults.Fail; } if (!TestGetFileName(@"\\machine\directory\file.tmp", "file.tmp")) { return MFTestResults.Fail; } if (!TestGetFileName(@"\\machine\directory\file", "file")) { return MFTestResults.Fail; } if (!TestGetFileName(@"\\machine\directory\file name", "file name")) { return MFTestResults.Fail; } if (!TestGetFileName(@"\\machine\directory\file.t name.exe", "file.t name.exe")) { return MFTestResults.Fail; } } catch (Exception ex) { Log.Exception("Unexpected exception: " + ex.Message); return MFTestResults.Fail; } return result; } [TestMethod] public MFTestResults ForwardSlash() { MFTestResults result = MFTestResults.Pass; try { TestGetFileName(@"/directory/file.tmp", "file.tmp"); return MFTestResults.Fail; } catch (ArgumentException) { result = MFTestResults.Pass; } catch (Exception ex) { Log.Exception("Unexpected exception: " + ex.Message); return MFTestResults.Fail; } return result; } [TestMethod] public MFTestResults NoFile() { MFTestResults result = MFTestResults.Pass; try { if (!TestGetFileName(@"\sd1\dir\", "")) { return MFTestResults.Fail; } } catch (Exception ex) { Log.Exception("Unexpected exception: " + ex.Message); return MFTestResults.Fail; } return result; } [TestMethod] public MFTestResults ArgumentExceptionTests() { MFTestResults result = MFTestResults.Pass; try { foreach (char invalidChar in Path.GetInvalidPathChars()) { try { Log.Comment("Invalid char ascii val = " + (int)invalidChar); string path = new string(new char[] { invalidChar, 'b', 'a', 'd', '.', invalidChar, 'p', 'a', 't', 'h', invalidChar }); string dir = Path.GetFileName(path); if ((path.Length == 0) && (dir.Length == 0)) { /// If path is empty string, returned value is also empty string (same behavior in desktop) /// no exception thrown. } else { Log.Exception("Expected Argument exception for '" + path + "' but got: '" + dir + "'"); return MFTestResults.Fail; } } catch (ArgumentException ae) { /* pass case */ Log.Comment( "Got correct exception: " + ae.Message ); } } } catch (Exception ex) { Log.Exception("Unexpected exception: " + ex.Message); return MFTestResults.Fail; } return result; } #endregion Test Cases public MFTestMethod[] Tests { get { return new MFTestMethod[] { new MFTestMethod( Null, "Null" ), new MFTestMethod( ValidCases, "ValidCases" ), new MFTestMethod( ForwardSlash, "ForwardSlash" ), new MFTestMethod( NoFile, "NoFile" ), new MFTestMethod( ArgumentExceptionTests, "ArgumentExceptionTests" ), }; } } } } ================================================ FILE: Zelig/Zelig/FileSystemTest/Path/GetFileNameWithoutExtension.cs ================================================ //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // Copyright (c) Microsoft Corporation. All rights reserved. //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// using System; using System.IO; namespace FileSystemTest { public class GetFileNameWithoutExtension : IMFTestInterface { [SetUp] public InitializeResult Initialize() { Log.Comment("Adding set up for the tests"); return InitializeResult.ReadyToGo; } [TearDown] public void CleanUp() { } #region helper methods private bool TestGetFileNameWithoutExtension(string path, string expected) { string result = Path.GetFileNameWithoutExtension(path); Log.Comment("Path: '" + path + "'"); Log.Comment("Expected: '" + expected + "'"); if (result != expected) { Log.Exception("Got: '" + result + "'"); return false; } return true; } #endregion helper methods #region Test Cases [TestMethod] public MFTestResults Null() { MFTestResults result = MFTestResults.Pass; try { if (!TestGetFileNameWithoutExtension(null, null)) { return MFTestResults.Fail; } if (!TestGetFileNameWithoutExtension("", "")) { return MFTestResults.Fail; } if (!TestGetFileNameWithoutExtension(string.Empty, string.Empty)) { return MFTestResults.Fail; } if (!TestGetFileNameWithoutExtension(".ext", "")) { return MFTestResults.Fail; } } catch (Exception ex) { Log.Exception("Unexpected exception: " + ex.Message); return MFTestResults.Fail; } return result; } [TestMethod] public MFTestResults ValidCases() { MFTestResults result = MFTestResults.Pass; try { if (!TestGetFileNameWithoutExtension("file", "file")) { return MFTestResults.Fail; } if (!TestGetFileNameWithoutExtension("file.txt", "file")) { return MFTestResults.Fail; } if (!TestGetFileNameWithoutExtension(@"\sd1\dir1\file.txt", "file")) { return MFTestResults.Fail; } if (!TestGetFileNameWithoutExtension(@"dir1\dir2\file", "file")) { return MFTestResults.Fail; } if (!TestGetFileNameWithoutExtension("file.........ext...", "file.........ext..")) { return MFTestResults.Fail; } string file = "foo.bar.fkl;fkds92-509450-4359.$#%()#%().%#(%)_#(%_)"; if (!TestGetFileNameWithoutExtension(file + ".cool", file)) { return MFTestResults.Fail; } file = new string('x', 256); if (!TestGetFileNameWithoutExtension("cool." + file, "cool")) { return MFTestResults.Fail; } if (!TestGetFileNameWithoutExtension(file + ".c", file)) { return MFTestResults.Fail; } if (!TestGetFileNameWithoutExtension(file + "." + file, file)) { return MFTestResults.Fail; } if (!TestGetFileNameWithoutExtension("file.....ext", "file....")) { return MFTestResults.Fail; } } catch (Exception ex) { Log.Exception("Unexpected exception: " + ex.Message); return MFTestResults.Fail; } return result; } [TestMethod] public MFTestResults ArgumentExceptionTests() { MFTestResults result = MFTestResults.Pass; try { foreach (char invalidChar in Path.GetInvalidPathChars()) { try { Log.Comment("Invalid char ascii val = " + (int)invalidChar); string path = new string(new char[] { invalidChar, 'b', 'a', 'd', '.', invalidChar, 'p', 'a', 't', 'h', invalidChar }); string dir = Path.GetFileNameWithoutExtension(path); if ((path.Length == 0) && (dir.Length == 0)) { /// If path is empty string, returned value is also empty string (same behavior in desktop) /// no exception thrown. } else { Log.Exception("Expected Argument exception for '" + path + "' but got: '" + dir + "'"); return MFTestResults.Fail; } } catch (ArgumentException ae) { /* pass case */ Log.Comment( "Got correct exception: " + ae.Message ); } } } catch (Exception ex) { Log.Exception("Unexpected exception: " + ex.Message); return MFTestResults.Fail; } return result; } #endregion Test Cases public MFTestMethod[] Tests { get { return new MFTestMethod[] { new MFTestMethod( Null, "Null" ), new MFTestMethod( ValidCases, "ValidCases" ), new MFTestMethod( ArgumentExceptionTests, "ArgumentExceptionTests" ), }; } } } } ================================================ FILE: Zelig/Zelig/FileSystemTest/Path/GetFullPath.cs ================================================ //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // Copyright (c) Microsoft Corporation. All rights reserved. //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// using System; using System.IO; namespace FileSystemTest { public class GetFullPath : IMFTestInterface { [SetUp] public InitializeResult Initialize() { Log.Comment("Set up for the tests"); try { IOTests.IntializeVolume(); } catch { return InitializeResult.Skip; } return InitializeResult.ReadyToGo; } [TearDown] public void CleanUp() { } #region helper methods private bool TestGetFullPath(string path, string expected) { string result = Path.GetFullPath(path); Log.Comment("Path: " + path); Log.Comment("Expected: " + expected); if (result != expected) { Log.Exception("Got: " + result); return false; } return true; } #endregion helper methods #region Test Cases [TestMethod] public MFTestResults Null() { MFTestResults result = MFTestResults.Pass; try { try { string path = Path.GetFullPath(""); Log.Exception("Expected ArgumentException exception, but got: " + path); return MFTestResults.Fail; } catch (ArgumentException ae) { /* pass case */ Log.Comment( "Got correct exception: " + ae.Message ); result = MFTestResults.Pass; } try { string path = Path.GetFullPath(string.Empty); Log.Exception("Expected ArgumentException exception, but got: " + path); return MFTestResults.Fail; } catch (ArgumentException ae) { /* pass case */ Log.Comment( "Got correct exception: " + ae.Message ); result = MFTestResults.Pass; } try { string path = Path.GetFullPath(null); Log.Exception("Expected ArgumentNullException exception, but got: " + path); return MFTestResults.Fail; } catch (ArgumentException ae) { /* pass case */ Log.Comment( "Got correct exception: " + ae.Message ); result = MFTestResults.Pass; } } catch (Exception ex) { Log.Exception("Unexpected exception: " + ex.Message); return MFTestResults.Fail; } return result; } [TestMethod] public MFTestResults ValidCases() { MFTestResults result = MFTestResults.Pass; try { if (!TestGetFullPath(@"file.tmp", Directory.GetCurrentDirectory() + @"\file.tmp")) { return MFTestResults.Fail; } // unrooted if (!TestGetFullPath(@"directory\file.tmp", Directory.GetCurrentDirectory() + @"\directory\file.tmp")) { return MFTestResults.Fail; } if (!TestGetFullPath(@"\ROOT\directory\file.tmp", @"\ROOT\directory\file.tmp")) { return MFTestResults.Fail; } // rooted if (!TestGetFullPath(@"\\machine\directory\file.tmp", @"\\machine\directory\file.tmp")) { return MFTestResults.Fail; } if (!TestGetFullPath(@"\sd1\directory\file", @"\sd1\directory\file")) { return MFTestResults.Fail; } if (!TestGetFullPath(@"\nand1\directory name\file name", @"\nand1\directory name\file name")) { return MFTestResults.Fail; } if (!TestGetFullPath(@"\sd1\directory.t name\file.t name.exe", @"\sd1\directory.t name\file.t name.exe")) { return MFTestResults.Fail; } // special - Might need actuall FS access to create directory structures to navigate if (!TestGetFullPath(".", Directory.GetCurrentDirectory())) { return MFTestResults.Fail; } if (!TestGetFullPath(@".\", Directory.GetCurrentDirectory())) { return MFTestResults.Fail; } //if (!TestGetFullPath("..", "")) //{ // return MFTestResults.Fail; //} } catch (Exception ex) { Log.Exception("Unexpected exception: " + ex.Message); return MFTestResults.Fail; } return result; } [TestMethod] public MFTestResults TooLongPath() { MFTestResults result = MFTestResults.Pass; try { string longBlock = new string('y', 135); try { string path = Path.GetFullPath(longBlock + longBlock); Log.Exception("Expected IOException(Path Too Long), but got: " + path); return MFTestResults.Fail; } catch (IOException ioe) { /* pass case */ Log.Comment( "Got correct exception: " + ioe.Message ); } // PathTooLong try { string path = Path.GetFullPath(@"\SD1\" + longBlock + "\\" + longBlock + "\\" + longBlock + longBlock + ".exe"); Log.Exception("Expected IOException(Path Too Long), but got: " + path); return MFTestResults.Fail; } catch (IOException ioe) { /* pass case */ Log.Comment( "Got correct exception: " + ioe.Message ); } //PathTooLong try { string path = Path.GetFullPath(new string('a', (int)UInt16.MaxValue + 1)); Log.Exception("Expected IOException(Path Too Long), but got: " + path); return MFTestResults.Fail; } catch (IOException ioe) { /* pass case */ Log.Comment( "Got correct exception: " + ioe.Message ); } //PathTooLong // chech bounds string boundResult; Directory.SetCurrentDirectory(IOTests.Volume.RootDirectory); string currDir = Directory.GetCurrentDirectory(); int len = currDir.Length; int limit = len + 258; // 258 is the FsMaxPathLength if (currDir.Substring(currDir.Length - 1) != (Path.DirectorySeparatorChar.ToString())) len++; for (int i = 225 - len; i < 275 - len; i++) { try { string str1 = new String('a', 100) + "\\" + new String('a', i- 101); // make a string of i length (need a \ in there so we don't have filename over 255) boundResult = Path.GetFullPath(str1); if (boundResult.Length >= limit) { Log.Exception( "Err_3974g! Didn't Throw: " + ( i + len ) + " - " + boundResult.Length ); return MFTestResults.Fail; } } catch (IOException) // PathTooLong { if ((len + i) < limit) { Log.Exception( "Err_245f! Threw too early: " + ( i + len ) ); return MFTestResults.Fail; } } } } catch (Exception ex) { Log.Exception("Unexpected exception: " + ex.Message); return MFTestResults.Fail; } return result; } [TestMethod] public MFTestResults WildCard() { MFTestResults result = MFTestResults.Pass; try { try { string path = Path.GetFullPath("file*"); Log.Exception("Expected ArgumentException exception, but got: " + path); return MFTestResults.Fail; } catch (ArgumentException ae) { /* pass case */ Log.Comment( "Got correct exception: " + ae.Message ); } try { string path = Path.GetFullPath(@"\sd1\file*"); Log.Exception("Expected ArgumentException exception, but got: " + path); return MFTestResults.Fail; } catch (ArgumentException ae) { /* pass case */ Log.Comment( "Got correct exception: " + ae.Message ); } try { string path = Path.GetFullPath(@"\sd1\file*.txt"); Log.Exception("Expected ArgumentException exception, but got: " + path); return MFTestResults.Fail; } catch (ArgumentException ae) { /* pass case */ Log.Comment( "Got correct exception: " + ae.Message ); } } catch (Exception ex) { Log.Exception("Unexpected exception: " + ex.Message); return MFTestResults.Fail; } return result; } [TestMethod] public MFTestResults ArgumentExceptionTests() { MFTestResults result = MFTestResults.Pass; try { foreach (char invalidChar in Path.GetInvalidPathChars()) { try { Log.Comment("Invalid char ascii val = " + (int)invalidChar); string path = new string(new char[] { 'b', 'a', 'd', '\\', invalidChar, 'p', 'a', 't', 'h', invalidChar, '.', 't', 'x', 't' }); string dir = Path.GetFullPath(path); if (invalidChar == 0) { Log.Exception("[Known issue] Expected Argument exception for for '" + path + "' but got: '" + dir + "'"); result = MFTestResults.KnownFailure; } else { Log.Exception("Expected Argument exception for '" + path + "' but got: '" + dir + "'"); return MFTestResults.Fail; } } catch (ArgumentException ae) { /* pass case */ Log.Comment( "Got correct exception: " + ae.Message ); } catch (Exception) { /// There is one case where String.Split throws System.Exception instead of ArgumentException for certain invalid character. /// Fix String.Split? } } } catch (Exception ex) { Log.Exception("Unexpected exception: " + ex.Message); return MFTestResults.Fail; } return result; } #endregion Test Cases public MFTestMethod[] Tests { get { return new MFTestMethod[] { new MFTestMethod( Null, "Null" ), new MFTestMethod( ValidCases, "ValidCases" ), new MFTestMethod( TooLongPath, "TooLongPath" ), new MFTestMethod( WildCard, "WildCard" ), new MFTestMethod( ArgumentExceptionTests, "ArgumentExceptionTests" ), }; } } } } ================================================ FILE: Zelig/Zelig/FileSystemTest/Path/GetPathRoot.cs ================================================ //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // Copyright (c) Microsoft Corporation. All rights reserved. //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// using System; using System.IO; namespace FileSystemTest { public class GetPathRoot : IMFTestInterface { [SetUp] public InitializeResult Initialize() { Log.Comment("Adding set up for the tests"); return InitializeResult.ReadyToGo; } [TearDown] public void CleanUp() { } #region helper methods private bool TestGetPathRoot(string path, string expected) { string result = Path.GetPathRoot(path); Log.Comment("Path: '" + path + "'"); Log.Comment("Expected: '" + expected + "'"); if (result != expected) { Log.Exception("Got: '" + result + "'"); return false; } return true; } #endregion helper methods #region Test Cases [TestMethod] public MFTestResults Null() { MFTestResults result = MFTestResults.Pass; try { if (!TestGetPathRoot(null, null)) { return MFTestResults.Fail; } if (!TestGetPathRoot(@"sd1\", "")) { return MFTestResults.Fail; } } catch (Exception ex) { Log.Exception("Unexpected exception: " + ex.Message); return MFTestResults.Fail; } return result; } [TestMethod] public MFTestResults ValidCases() { MFTestResults result = MFTestResults.Pass; try { if (!TestGetPathRoot(@"\", @"\")) { return MFTestResults.Fail; } if (!TestGetPathRoot(@"\dir1", @"\")) { return MFTestResults.Fail; } if (!TestGetPathRoot(@"\file.text", @"\")) { return MFTestResults.Fail; } if (!TestGetPathRoot(@"\file\text", @"\")) { return MFTestResults.Fail; } if (!TestGetPathRoot(@"\sd1\\\\dir\\\\\file\\\\\text\\\\", @"\")) { return MFTestResults.Fail; } if (!TestGetPathRoot(@"\\machine\dir1\file.tmp", @"\\machine\dir1")) { return MFTestResults.Fail; } if (!TestGetPathRoot(@"\\machine", @"\\machine")) { return MFTestResults.Fail; } } catch (Exception ex) { Log.Exception("Unexpected exception: " + ex.Message); return MFTestResults.Fail; } return result; } [TestMethod] public MFTestResults StartWithColon() { MFTestResults result = MFTestResults.Pass; try { try { string path = Path.GetFullPath(":file"); Log.Exception("Expected NullArgument exception, but got '" + path + "'"); return MFTestResults.Fail; } catch (ArgumentException ae) { /* pass case */ Log.Comment( "Got correct exception: " + ae.Message ); result = MFTestResults.Pass; } } catch (Exception ex) { Log.Exception("Unexpected exception: " + ex.Message); return MFTestResults.Fail; } return result; } [TestMethod] public MFTestResults ArgumentExceptionTests() { MFTestResults result = MFTestResults.Pass; try { foreach (char invalidChar in Path.GetInvalidPathChars()) { try { Log.Comment("Invalid char ascii val = " + (int)invalidChar); string path = new string(new char[] { invalidChar, 'b', 'a', 'd', '.', invalidChar, 'p', 'a', 't', 'h', invalidChar }); string dir = Path.GetPathRoot(path); if ((path.Length == 0) && (dir.Length == 0)) { /// If path is empty string, returned value is also empty string (same behavior in desktop) /// no exception thrown. } else { Log.Exception("Expected Argument exception for '" + path + "' but got: '" + dir + "'"); return MFTestResults.Fail; } } catch (ArgumentException ae) { /* pass case */ Log.Comment( "Got correct exception: " + ae.Message ); } } } catch (Exception ex) { Log.Exception("Unexpected exception: " + ex.Message); return MFTestResults.Fail; } return result; } #endregion Test Cases public MFTestMethod[] Tests { get { return new MFTestMethod[] { new MFTestMethod( Null, "Null" ), new MFTestMethod( ValidCases, "ValidCases" ), new MFTestMethod( StartWithColon, "StartWithColon" ), new MFTestMethod( ArgumentExceptionTests, "ArgumentExceptionTests" ), }; } } } } ================================================ FILE: Zelig/Zelig/FileSystemTest/Path/HasExtension.cs ================================================ //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // Copyright (c) Microsoft Corporation. All rights reserved. //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// using System; using System.IO; namespace FileSystemTest { public class HasExtension : IMFTestInterface { [SetUp] public InitializeResult Initialize() { Log.Comment("Adding set up for the tests"); return InitializeResult.ReadyToGo; } [TearDown] public void CleanUp() { } #region helper methods private bool expected; private bool TestHasExtension(string path) { Log.Comment("Path: '" + path + "'"); if (Path.HasExtension(path) & expected) return true; Log.Exception("Expected " + expected); return false; } #endregion helper methods [TestMethod] public MFTestResults Negative() { MFTestResults result = MFTestResults.Pass; expected = false; try { if (TestHasExtension(null)) { return MFTestResults.Fail; } if (TestHasExtension("")) { return MFTestResults.Fail; } if (TestHasExtension(string.Empty)) { return MFTestResults.Fail; } if (TestHasExtension(@"\")) { return MFTestResults.Fail; } if (TestHasExtension("file")) { return MFTestResults.Fail; } if (TestHasExtension(@"\sd\file")) { return MFTestResults.Fail; } if (TestHasExtension(@"\\Machine")) { return MFTestResults.Fail; } if (TestHasExtension(@"\\Machine\directory")) { return MFTestResults.Fail; } if (TestHasExtension(@"\\Machine\directory\file")) { return MFTestResults.Fail; } } catch (Exception ex) { Log.Exception("Unexpected exception: " + ex.Message); return MFTestResults.Fail; } return result; } [TestMethod] public MFTestResults Positive() { MFTestResults result = MFTestResults.Pass; expected = true; try { if (!TestHasExtension(".txt")) { return MFTestResults.Fail; } if (!TestHasExtension(@"\file.txt")) { return MFTestResults.Fail; } if (!TestHasExtension("file.x")) { return MFTestResults.Fail; } if (!TestHasExtension(@"\sd\file.comp")) { return MFTestResults.Fail; } if (!TestHasExtension(@"\\Machine\directory.dir")) { return MFTestResults.Fail; } if (!TestHasExtension(@"\\Machine\directory\file.zz")) { return MFTestResults.Fail; } if (!TestHasExtension(@"\sd\file." + new string('f',256))) { return MFTestResults.Fail; } } catch (Exception ex) { Log.Exception("Unexpected exception: " + ex.Message); return MFTestResults.Fail; } return result; } [TestMethod] public MFTestResults ArgumentExceptionTests() { MFTestResults result = MFTestResults.Pass; try { foreach (char invalidChar in Path.GetInvalidPathChars()) { try { Log.Comment("Invalid char ascii val = " + (int)invalidChar); string path = new string(new char[] { invalidChar, 'b', 'a', 'd', '.', invalidChar, 'p', 'a', 't', 'h', invalidChar }); bool dir = Path.HasExtension(path); if ((path.Length == 0) && (dir == false)) { /// If path is empty string, returned value is also empty string (same behavior in desktop) /// no exception thrown. } else { Log.Exception("Expected Argument exception for '" + path + "' but got: '" + dir + "'"); return MFTestResults.Fail; } } catch (ArgumentException ae) { /* pass case */ Log.Comment( "Got correct exception: " + ae.Message ); } } } catch (Exception ex) { Log.Exception("Unexpected exception: " + ex.Message); return MFTestResults.Fail; } return result; } public MFTestMethod[] Tests { get { return new MFTestMethod[] { new MFTestMethod( Negative, "Negative" ), new MFTestMethod( Positive, "Positive" ), new MFTestMethod( ArgumentExceptionTests, "ArgumentExceptionTests" ), }; } } } } ================================================ FILE: Zelig/Zelig/FileSystemTest/Path/IsPathRooted.cs ================================================ //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // Copyright (c) Microsoft Corporation. All rights reserved. //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// using System; using System.IO; namespace FileSystemTest { public class IsPathRooted : IMFTestInterface { [SetUp] public InitializeResult Initialize() { Log.Comment("Adding set up for the tests"); return InitializeResult.ReadyToGo; } [TearDown] public void CleanUp() { Log.Comment("Cleaning up after the tests."); // TODO: Add your clean up steps here. } #region helper methods private bool expected; private bool TestIsPathRooted(string path) { Log.Comment("Path: '" + path + "'"); if (Path.IsPathRooted(path) == expected) return true; Log.Exception("Expected " + expected); return false; } #endregion helper methods [TestMethod] public MFTestResults Negative() { MFTestResults result = MFTestResults.Pass; expected = false; try { if (!TestIsPathRooted(null)) { return MFTestResults.Fail; } if (!TestIsPathRooted("")) { return MFTestResults.Fail; } if (!TestIsPathRooted(string.Empty)) { return MFTestResults.Fail; } if (!TestIsPathRooted("file")) { return MFTestResults.Fail; } if (!TestIsPathRooted(".txt")) { return MFTestResults.Fail; } if (!TestIsPathRooted("file.x")) { return MFTestResults.Fail; } } catch (Exception ex) { Log.Exception("Unexpected exception: " + ex.Message); return MFTestResults.Fail; } return result; } [TestMethod] public MFTestResults Positive() { MFTestResults result = MFTestResults.Pass; expected = true; try { if (!TestIsPathRooted(@"\")) { return MFTestResults.Fail; } if (!TestIsPathRooted(@"\sd\file")) { return MFTestResults.Fail; } if (!TestIsPathRooted(@"\sd\file.comp")) { return MFTestResults.Fail; } if (!TestIsPathRooted(@"\\Machine\directory.dir")) { return MFTestResults.Fail; } if (!TestIsPathRooted(@"\\Machine\directory\file.zz")) { return MFTestResults.Fail; } if (!TestIsPathRooted(@"\sd\file." + new string('f', 256))) { return MFTestResults.Fail; } if (!TestIsPathRooted(@"\\Machine")) { return MFTestResults.Fail; } if (!TestIsPathRooted(@"\\Machine\directory")) { return MFTestResults.Fail; } if (!TestIsPathRooted(@"\\Machine\directory\file")) { return MFTestResults.Fail; } } catch (Exception ex) { Log.Exception("Unexpected exception: " + ex.Message); return MFTestResults.Fail; } return result; } [TestMethod] public MFTestResults ArgumentExceptionTests() { MFTestResults result = MFTestResults.Pass; try { foreach (char invalidChar in Path.GetInvalidPathChars()) { try { Log.Comment("Invalid char ascii val = " + (int)invalidChar); string path = new string(new char[] { invalidChar, 'b', 'a', 'd', '.', invalidChar, 'p', 'a', 't', 'h', invalidChar }); bool dir = Path.IsPathRooted(path); if ((path.Length == 0) && (dir == false)) { /// If path is empty string, returned value is also empty string (same behavior in desktop) /// no exception thrown. } else { Log.Exception("Expected Argument exception for '" + path + "' but got: '" + dir + "'"); return MFTestResults.Fail; } } catch (ArgumentException ae) { /* pass case */ Log.Comment( "Got correct exception: " + ae.Message ); } } } catch (Exception ex) { Log.Exception("Unexpected exception: " + ex.Message); return MFTestResults.Fail; } return result; } public MFTestMethod[] Tests { get { return new MFTestMethod[] { new MFTestMethod( Negative, "Negative" ), new MFTestMethod( Positive, "Positive" ), new MFTestMethod( ArgumentExceptionTests, "ArgumentExceptionTests" ), }; } } } } ================================================ FILE: Zelig/Zelig/FileSystemTest/Path/PathTests.cs ================================================ /*--------------------------------------------------------------------- * PathTests.cs - file description * Version: 1.0 * Author: * Created: * * Tests the basic functionality of Socket objects * ---------------------------------------------------------------------*/ using System; using System.Reflection; using System.IO; namespace FileSystemTest { public class PathTests : IMFTestInterface { [SetUp] public InitializeResult Initialize() { Log.Comment("Adding set up for the tests"); // delete the Path DOTNETMF_FS_EMULATION try { IOTests.IntializeVolume(); } catch { return InitializeResult.Skip; } return InitializeResult.ReadyToGo; } [TearDown] public void CleanUp() { } [TestMethod] public MFTestResults PathTest0_ChangeExtension() { bool testResult = false; try { string newPath = Path.ChangeExtension(@"pathtest\testdir\test.ext1", ".ext2"); testResult = String.Equals(newPath, @"pathtest\testdir\test.ext2"); } catch (Exception ex) { Log.Exception("Unexpected Exception", ex); } return (testResult ? MFTestResults.Pass : MFTestResults.Fail); } /// /// If new extension is null, then file extension should be removed. /// /// [TestMethod] public MFTestResults PathTest_ChangeExtension1() { bool testResult = false; try { string newPath = Path.ChangeExtension(@"pathtest\testdir\test.ext1", null); testResult = String.Equals(newPath, @"pathtest\testdir\test"); } catch (Exception ex) { Log.Exception("Unexpected Exception", ex); } return (testResult ? MFTestResults.Pass : MFTestResults.Fail); } /// /// If path is null, it should be returned unmodified. /// /// [TestMethod] public MFTestResults PathTest_ChangeExtension2() { bool testResult = false; try { string newPath = Path.ChangeExtension(null, ".ext"); testResult = (newPath == null); } catch (Exception ex) { Log.Exception("Unexpected Exception", ex); } return (testResult ? MFTestResults.Pass : MFTestResults.Fail); } /// /// If path is empty, it should be returned unmodified. /// /// [TestMethod] public MFTestResults PathTest_ChangeExtension3() { bool testResult = false; try { string newPath = Path.ChangeExtension("", ".ext"); testResult = (newPath == ""); } catch (Exception ex) { Log.Exception("Unexpected Exception", ex); } return (testResult ? MFTestResults.Pass : MFTestResults.Fail); } /// /// If path is empty, it should be returned unmodified. /// /// [TestMethod] public MFTestResults PathTest_ChangeExtension4() { bool testResult = false; try { string newPath = Path.ChangeExtension("", ".ext"); testResult = (newPath == ""); } catch (Exception ex) { Log.Exception("Unexpected Exception", ex); } return (testResult ? MFTestResults.Pass : MFTestResults.Fail); } /// /// Negative test case, path contains invalid character. /// /// [TestMethod] public MFTestResults PathTest_ChangeExtension5() { bool testResult = true; try { string newPath = Path.ChangeExtension(@"pathtest\testdir\test>.ext1", ".ext"); testResult = false; } catch (Exception ex) { Log.Exception("Expected Exception", ex); testResult = true; } return (testResult ? MFTestResults.Pass : MFTestResults.Fail); } /// /// Extension does not contain dot. /// /// [TestMethod] public MFTestResults PathTest_ChangeExtension6() { bool testResult = false; try { string newPath = Path.ChangeExtension(@"pathtest\testdir\test.ext1", "ext"); testResult = String.Equals(newPath, @"pathtest\testdir\test.ext"); } catch (Exception ex) { Log.Exception("Unexpected Exception", ex); } return (testResult ? MFTestResults.Pass : MFTestResults.Fail); } [TestMethod] public MFTestResults PathTest1_GetDirectoryName() { bool testResult = false; try { string dirName = Path.GetDirectoryName(@"pathtest\testdir\test.ext1"); testResult = String.Equals(dirName, @"pathtest\testdir"); } catch (Exception ex) { Log.Exception("Unexpected Exception", ex); } return (testResult ? MFTestResults.Pass : MFTestResults.Fail); } /// /// Get parent directory name of a directory /// /// [TestMethod] public MFTestResults PathTest_GetDirectoryName1() { bool testResult = false; try { string dirName = Path.GetDirectoryName(@"pathtest\testdir"); testResult = String.Equals(dirName, @"pathtest"); } catch (Exception ex) { Log.Exception("Unexpected Exception", ex); } return (testResult ? MFTestResults.Pass : MFTestResults.Fail); } /// /// Parent of root directory /// /// [TestMethod] public MFTestResults PathTest_GetDirectoryName2() { bool testResult = false; try { string dirName = Path.GetDirectoryName(IOTests.Volume.RootDirectory); testResult = String.Equals(dirName, @"\"); } catch (Exception ex) { Log.Exception("Unexpected Exception", ex); } return (testResult ? MFTestResults.Pass : MFTestResults.Fail); } /// /// Parent of root directory /// /// [TestMethod] public MFTestResults PathTest_GetDirectoryName3() { bool testResult = false; try { string dirName = Path.GetDirectoryName(@""); } catch (ArgumentException) { testResult = true; } catch (Exception ex) { Log.Exception("Unexpected Exception", ex); } return (testResult ? MFTestResults.Pass : MFTestResults.Fail); } /// /// Parent of root directory /// /// [TestMethod] public MFTestResults PathTest_GetDirectoryName4() { bool testResult = false; try { string dirName = Path.GetDirectoryName(null); testResult = (dirName == null); } catch (Exception ex) { Log.Exception("Unexpected Exception", ex); } return (testResult ? MFTestResults.Pass : MFTestResults.Fail); } /// /// Parent of root directory /// /// [TestMethod] public MFTestResults PathTest_GetDirectoryName5() { bool testResult = true; try { string dirName = Path.GetDirectoryName(@"abc\abc>"); testResult = false; } catch (Exception ex) { Log.Exception("Expected Exception", ex); testResult = true; } return (testResult ? MFTestResults.Pass : MFTestResults.Fail); } [TestMethod] public MFTestResults PathTest_GetDirectoryName6() { bool testResult = true; try { string dirName = Path.GetDirectoryName(@"\\\abc\abc>"); testResult = false; } catch (Exception ex) { Log.Exception("Expected Exception", ex); testResult = true; } return (testResult ? MFTestResults.Pass : MFTestResults.Fail); } [TestMethod] public MFTestResults PathTest_GetFullPath0() { bool testResult = false; try { string fullPath = Path.GetFullPath(@"dir1\dir2\file.ext"); testResult = String.Equals(fullPath, IOTests.Volume.RootDirectory + @"\dir1\dir2\file.ext"); Log.Comment(fullPath); } catch (Exception ex) { Log.Exception("Unexpected Exception", ex); } return (testResult ? MFTestResults.Pass : MFTestResults.Fail); } [TestMethod] public MFTestResults PathTest_GetFullPath1() { bool testResult = false; try { string fullPath = Path.GetFullPath(IOTests.Volume.RootDirectory + @"\dir1\dir2\file.ext"); testResult = String.Equals(fullPath, IOTests.Volume.RootDirectory + @"\dir1\dir2\file.ext"); } catch (Exception ex) { Log.Exception("Unexpected Exception", ex); } return (testResult ? MFTestResults.Pass : MFTestResults.Fail); } [TestMethod] public MFTestResults PathTest_GetFullPath2() { bool testResult = false; try { string fullPath = Path.GetFullPath(IOTests.Volume.RootDirectory + @"\dir1\..\dir2\file.ext"); testResult = String.Equals(fullPath, IOTests.Volume.RootDirectory + @"\dir2\file.ext"); } catch (Exception ex) { Log.Exception("Unexpected Exception", ex); } return (testResult ? MFTestResults.Pass : MFTestResults.Fail); } [TestMethod] public MFTestResults PathTest_GetExtension1() { bool testResult = false; try { string ext = Path.GetExtension(@"pathtest\testdir\test"); testResult = String.Equals(ext, ""); } catch (Exception ex) { Log.Exception("Unexpected Exception", ex); } return (testResult ? MFTestResults.Pass : MFTestResults.Fail); } [TestMethod] public MFTestResults PathTest_GetExtension2() { bool testResult = false; try { string ext = Path.GetExtension(null); testResult = (ext == null); } catch (Exception ex) { Log.Exception("Unexpected Exception", ex); } return (testResult ? MFTestResults.Pass : MFTestResults.Fail); } [TestMethod] public MFTestResults PathTest_GetExtension3() { bool testResult = true; try { try { string ext = Path.GetExtension(@"pathtest\testdir\test>.txt"); testResult = false; } catch (ArgumentException ae) { /* pass case */ Log.Comment( "Got correct exception: res=" + testResult.ToString() + ", " + ae.Message ); } } catch (Exception ex) { testResult = false; Log.Exception("Unexpected Exception", ex); } return (testResult ? MFTestResults.Pass : MFTestResults.Fail); } [TestMethod] public MFTestResults PathTest_GetExtension4() { bool testResult = false; try { string ext = Path.GetExtension(@"pathtest\testdir\test.txt.txt2.txt3"); testResult = String.Equals(ext, ".txt3"); } catch (Exception ex) { Log.Exception("Unexpected Exception", ex); } return (testResult ? MFTestResults.Pass : MFTestResults.Fail); } [TestMethod] public MFTestResults PathTest4_GetFileName() { bool testResult = false; try { string fileName = Path.GetFileName(@"pathtest\testdir\test.ext2"); testResult = String.Equals(fileName, "test.ext2"); } catch (Exception ex) { Log.Exception("Unexpected Exception", ex); } return (testResult ? MFTestResults.Pass : MFTestResults.Fail); } [TestMethod] public MFTestResults PathTest_GetFileName1() { bool testResult = false; try { string fileName = Path.GetFileName(@"pathtest\testdir\test.ext2\"); testResult = String.Equals(fileName, ""); } catch (Exception ex) { Log.Exception("Unexpected Exception", ex); } return (testResult ? MFTestResults.Pass : MFTestResults.Fail); } [TestMethod] public MFTestResults PathTest_GetFileName2() { bool testResult = false; try { string fileName = Path.GetFileName(@"pathtest\testdir\test.ext2:"); } catch (ArgumentException) { testResult = true; } catch (Exception ex) { Log.Exception("Unexpected Exception", ex); } return (testResult ? MFTestResults.Pass : MFTestResults.Fail); } [TestMethod] public MFTestResults PathTest_GetFileName3() { bool testResult = false; try { string fileName = Path.GetFileName(null); testResult = (fileName == null); } catch (Exception ex) { Log.Exception("Unexpected Exception", ex); } return (testResult ? MFTestResults.Pass : MFTestResults.Fail); } [TestMethod] public MFTestResults PathTest_GetFileName4() { bool testResult = true; try { string fileName = Path.GetFileName(@"pathtest\testdir\test.ext2>"); testResult = false; } catch (ArgumentException ae) { /* pass case */ Log.Comment( "Got correct exception: res=" + testResult.ToString() + ", " + ae.Message ); } catch (Exception ex) { testResult = false; Log.Exception("Unexpected Exception", ex); } return (testResult ? MFTestResults.Pass : MFTestResults.Fail); } [TestMethod] public MFTestResults PathTest5_GetFileNameWithoutExtension() { bool testResult = false; try { string fileName = Path.GetFileNameWithoutExtension(@"pathtest\testdir\test.ext2"); testResult = String.Equals(fileName, "test"); } catch (Exception ex) { Log.Exception("Unexpected Exception", ex); } return (testResult ? MFTestResults.Pass : MFTestResults.Fail); } [TestMethod] public MFTestResults PathTest_GetFileNameWithoutExtension1() { bool testResult = false; try { string fileName = Path.GetFileNameWithoutExtension(@"pathtest\testdir\test.ext.ext1.ext2"); testResult = String.Equals(fileName, "test.ext.ext1"); } catch (Exception ex) { Log.Exception("Unexpected Exception", ex); } return (testResult ? MFTestResults.Pass : MFTestResults.Fail); } [TestMethod] public MFTestResults PathTest_GetFileNameWithoutExtension2() { bool testResult = false; try { string fileName = Path.GetFileNameWithoutExtension(@"pathtest\testdir\test"); testResult = String.Equals(fileName, "test"); } catch (Exception ex) { Log.Exception("Unexpected Exception", ex); } return (testResult ? MFTestResults.Pass : MFTestResults.Fail); } [TestMethod] public MFTestResults PathTest_GetFileNameWithoutExtension3() { bool testResult = true; try { string fileName = Path.GetFileNameWithoutExtension(@"pathtest\testdir\test>"); testResult = false; } catch (ArgumentException ae) { /* pass case */ Log.Comment( "Got correct exception: res=" + testResult.ToString() + ", " + ae.Message ); } catch (Exception ex) { testResult = false; Log.Exception("Unexpected Exception", ex); } return (testResult ? MFTestResults.Pass : MFTestResults.Fail); } [TestMethod] public MFTestResults PathTest6_GetPathRoot() { bool testResult = false; try { string root = Path.GetPathRoot(@"pathtest\testdir\test.ext2"); testResult = String.Equals(root, ""); } catch (Exception ex) { testResult = false; Log.Exception("Unexpected Exception", ex); } return (testResult ? MFTestResults.Pass : MFTestResults.Fail); } [TestMethod] public MFTestResults PathTest7_HasExtension() { bool testResult = false; try { testResult = Path.HasExtension(@"pathtest\testdir\test.ext2"); } catch (Exception ex) { testResult = false; Log.Exception("Unexpected Exception", ex); } return (testResult ? MFTestResults.Pass : MFTestResults.Fail); } [TestMethod] public MFTestResults PathTest_HasExtension1() { bool testResult = false; try { testResult = !Path.HasExtension(@"pathtest\testdir\test"); } catch (Exception ex) { testResult = false; Log.Exception("Unexpected Exception", ex); } return (testResult ? MFTestResults.Pass : MFTestResults.Fail); } [TestMethod] public MFTestResults PathTest_HasExtension2() { bool testResult = false; try { testResult = !Path.HasExtension(@"pathtest\testdir\test.ext2\"); } catch (Exception ex) { testResult = false; Log.Exception("Unexpected Exception", ex); } return (testResult ? MFTestResults.Pass : MFTestResults.Fail); } [TestMethod] public MFTestResults PathTest8_IsPathRooted() { bool testResult = false; try { testResult = Path.IsPathRooted(@"\pathtest\testdir\test.ext2"); } catch (Exception ex) { testResult = false; Log.Exception("Unexpected Exception", ex); } return (testResult ? MFTestResults.Pass : MFTestResults.Fail); } [TestMethod] public MFTestResults PathTest_IsPathRooted1() { bool testResult = false; try { testResult = !Path.IsPathRooted(@"pathtest\testdir\test"); } catch (Exception ex) { testResult = false; Log.Exception("Unexpected Exception", ex); } return (testResult ? MFTestResults.Pass : MFTestResults.Fail); } [TestMethod] public MFTestResults PathTest_IsPathRooted2() { bool testResult = false; try { /// Weird situation, according to MSDN this may be valid. testResult = Path.IsPathRooted(@"\\\\\\"); } catch (Exception ex) { Log.Exception("Unexpected Exception", ex); } return (testResult ? MFTestResults.Pass : MFTestResults.Fail); } [TestMethod] public MFTestResults PathTest_IsPathRooted3() { bool testResult = false; try { testResult = Path.IsPathRooted(@"\"); } catch (Exception ex) { Log.Exception("Unexpected Exception", ex); } return (testResult ? MFTestResults.Pass : MFTestResults.Fail); } [TestMethod] public MFTestResults PathTest_IsPathRooted4() { bool testResult = false; try { testResult = Path.IsPathRooted(@"\COM1"); } catch (Exception ex) { Log.Exception("Unexpected Exception", ex); } return (testResult ? MFTestResults.Pass : MFTestResults.Fail); } [TestMethod] public MFTestResults PathTest9_Combine() { bool testResult = false; try { string path = Path.Combine(@"pathtest\testdir\test", "test2"); testResult = String.Equals(path, @"pathtest\testdir\test\test2"); } catch (Exception ex) { Log.Exception("Unexpected Exception", ex); } return (testResult ? MFTestResults.Pass : MFTestResults.Fail); } [TestMethod] public MFTestResults PathTest_Combine1() { bool testResult = false; try { string path = Path.Combine(@"pathtest\testdir\test", @"\test2"); testResult = String.Equals(path, @"\test2"); } catch (Exception ex) { Log.Exception("Unexpected Exception", ex); } return (testResult ? MFTestResults.Pass : MFTestResults.Fail); } [TestMethod] public MFTestResults PathTest_Combine2() { bool testResult = false; try { string path = Path.Combine(@"\pathtest\testdir\test", @"\test2"); testResult = String.Equals(path, @"\test2"); } catch (Exception ex) { Log.Exception("Unexpected Exception", ex); } return (testResult ? MFTestResults.Pass : MFTestResults.Fail); } [TestMethod] public MFTestResults PathTest_Combine3() { bool testResult = false; try { string path = Path.Combine(@"\pathtest\testdir\test", @"\test2 "); testResult = String.Equals(path, @"\test2 "); /// Note: There's some difference between MSDN documentation of this case, and actual behavior. Notice /// the whitespace after test2. } catch (Exception ex) { Log.Exception("Unexpected Exception", ex); } return (testResult ? MFTestResults.Pass : MFTestResults.Fail); } [TestMethod] public MFTestResults PathTest_Combine4() { bool testResult = false; try { string path = Path.Combine(@"\pathtest\testdir\test", @"test2*.txt"); testResult = String.Equals(path, @"\pathtest\testdir\test\test2*.txt"); } catch (Exception ex) { Log.Exception("Unexpected Exception", ex); } return (testResult ? MFTestResults.Pass : MFTestResults.Fail); } [TestMethod] public MFTestResults PathTest_Combine5() { bool testResult = false; try { string path = Path.Combine(@"\pathtest\testdir\test", @"..\test2.txt"); testResult = String.Equals(path, @"\pathtest\testdir\test\..\test2.txt"); } catch (Exception ex) { Log.Exception("Unexpected Exception", ex); } return (testResult ? MFTestResults.Pass : MFTestResults.Fail); } [TestMethod] public MFTestResults PathTest_Combine6() { bool testResult = false; try { string path = Path.Combine(@"^*&)(_=@.*(.txt", @"dir\test2.txt"); testResult = String.Equals(path, @"^*&)(_=@.*(.txt\dir\test2.txt"); } catch (Exception ex) { Log.Exception("Unexpected Exception", ex); } return (testResult ? MFTestResults.Pass : MFTestResults.Fail); } [TestMethod] public MFTestResults PathTest_Combine7() { bool testResult = true; try { string path = Path.Combine("//" + IOTests.Volume.Name + "//dir", @"dir\test2.txt"); testResult = false; } catch (Exception ex) { Log.Exception("Expected Exception", ex); testResult = true; } return (testResult ? MFTestResults.Pass : MFTestResults.Fail); } public MFTestMethod[] Tests { get { return new MFTestMethod[] { new MFTestMethod( PathTest0_ChangeExtension, "PathTest0_ChangeExtension" ), new MFTestMethod( PathTest_ChangeExtension1, "PathTest_ChangeExtension1" ), new MFTestMethod( PathTest_ChangeExtension2, "PathTest_ChangeExtension2" ), new MFTestMethod( PathTest_ChangeExtension3, "PathTest_ChangeExtension3" ), new MFTestMethod( PathTest_ChangeExtension4, "PathTest_ChangeExtension4" ), new MFTestMethod( PathTest_ChangeExtension5, "PathTest_ChangeExtension5" ), new MFTestMethod( PathTest_ChangeExtension6, "PathTest_ChangeExtension6" ), new MFTestMethod( PathTest1_GetDirectoryName, "PathTest1_GetDirectoryName" ), new MFTestMethod( PathTest_GetDirectoryName1, "PathTest_GetDirectoryName1" ), new MFTestMethod( PathTest_GetDirectoryName2, "PathTest_GetDirectoryName2" ), new MFTestMethod( PathTest_GetDirectoryName3, "PathTest_GetDirectoryName3" ), new MFTestMethod( PathTest_GetDirectoryName4, "PathTest_GetDirectoryName4" ), new MFTestMethod( PathTest_GetDirectoryName5, "PathTest_GetDirectoryName5" ), new MFTestMethod( PathTest_GetDirectoryName6, "PathTest_GetDirectoryName6" ), new MFTestMethod( PathTest_GetFullPath0, "PathTest_GetFullPath0" ), new MFTestMethod( PathTest_GetFullPath1, "PathTest_GetFullPath1" ), new MFTestMethod( PathTest_GetFullPath2, "PathTest_GetFullPath2" ), new MFTestMethod( PathTest_GetExtension1, "PathTest_GetExtension1" ), new MFTestMethod( PathTest_GetExtension2, "PathTest_GetExtension2" ), new MFTestMethod( PathTest_GetExtension3, "PathTest_GetExtension3" ), new MFTestMethod( PathTest_GetExtension4, "PathTest_GetExtension4" ), new MFTestMethod( PathTest4_GetFileName, "PathTest4_GetFileName" ), new MFTestMethod( PathTest_GetFileName1, "PathTest_GetFileName1" ), new MFTestMethod( PathTest_GetFileName2, "PathTest_GetFileName2" ), new MFTestMethod( PathTest_GetFileName3, "PathTest_GetFileName3" ), new MFTestMethod( PathTest_GetFileName4, "PathTest_GetFileName4" ), new MFTestMethod( PathTest5_GetFileNameWithoutExtension, "PathTest5_GetFileNameWithoutExtension" ), new MFTestMethod( PathTest_GetFileNameWithoutExtension1, "PathTest_GetFileNameWithoutExtension1" ), new MFTestMethod( PathTest_GetFileNameWithoutExtension2, "PathTest_GetFileNameWithoutExtension2" ), new MFTestMethod( PathTest_GetFileNameWithoutExtension3, "PathTest_GetFileNameWithoutExtension3" ), new MFTestMethod( PathTest6_GetPathRoot, "PathTest6_GetPathRoot" ), new MFTestMethod( PathTest7_HasExtension, "PathTest7_HasExtension" ), new MFTestMethod( PathTest_HasExtension1, "PathTest_HasExtension1" ), new MFTestMethod( PathTest_HasExtension2, "PathTest_HasExtension2" ), new MFTestMethod( PathTest8_IsPathRooted, "PathTest8_IsPathRooted" ), new MFTestMethod( PathTest_IsPathRooted1, "PathTest_IsPathRooted1" ), new MFTestMethod( PathTest_IsPathRooted2, "PathTest_IsPathRooted2" ), new MFTestMethod( PathTest_IsPathRooted3, "PathTest_IsPathRooted3" ), new MFTestMethod( PathTest_IsPathRooted4, "PathTest_IsPathRooted4" ), new MFTestMethod( PathTest9_Combine, "PathTest9_Combine" ), new MFTestMethod( PathTest_Combine1, "PathTest_Combine1" ), new MFTestMethod( PathTest_Combine2, "PathTest_Combine2" ), new MFTestMethod( PathTest_Combine3, "PathTest_Combine3" ), new MFTestMethod( PathTest_Combine4, "PathTest_Combine4" ), new MFTestMethod( PathTest_Combine5, "PathTest_Combine5" ), new MFTestMethod( PathTest_Combine6, "PathTest_Combine6" ), new MFTestMethod( PathTest_Combine7, "PathTest_Combine7" ), }; } } } } ================================================ FILE: Zelig/Zelig/FileSystemTest/Program.cs ================================================ using System; using System.Collections.Generic; using System.Text; using System.IO; using RT = Microsoft.Zelig.Runtime; using System.Runtime.InteropServices; using Microsoft.Zelig.Runtime; using System.Reflection; namespace FileSystemTest { [StructLayout( LayoutKind.Explicit )] public struct SYSTEMTIME { [FieldOffset( 0 )] public ushort wYear; [FieldOffset( 2 )] public ushort wMonth; [FieldOffset( 4 )] public ushort wDayOfWeek; [FieldOffset( 6 )] public ushort wDay; [FieldOffset( 8 )] public ushort wHour; [FieldOffset( 10 )] public ushort wMinute; [FieldOffset( 12 )] public ushort wSecond; [FieldOffset( 14 )] public ushort wMilliseconds; }; public class TestApp { [RT.ExportedMethod] public static Int64 _Z17Time_GetLocalTimev() { return DateTime.UtcNow.Ticks; } [RT.ExportedMethod] public static Int64 _Z19Time_FromSystemTimePK10SYSTEMTIME( ref SYSTEMTIME sysTime ) { DateTime dt = new DateTime( sysTime.wYear, sysTime.wMonth, sysTime.wDay, sysTime.wHour, sysTime.wMinute, sysTime.wSecond, sysTime.wMilliseconds, DateTimeKind.Utc ); return dt.Ticks; } [RT.ExportedMethod] public static int _Z17Time_ToSystemTimexP10SYSTEMTIME( Int64 time, ref SYSTEMTIME sysTime ) { DateTime dt = new DateTime( time, DateTimeKind.Utc ); sysTime.wYear = (ushort)dt.Year; sysTime.wMonth = (ushort)dt.Month; sysTime.wDay = (ushort)dt.Day; sysTime.wDayOfWeek = (ushort)dt.DayOfWeek; sysTime.wHour = (ushort)dt.Hour; sysTime.wMinute = (ushort)dt.Minute; sysTime.wSecond = (ushort)dt.Second; sysTime.wMilliseconds = (ushort)dt.Millisecond; return 1; } [RT.ExportedMethod] public static int Extern__Storage_Write( uint address, IntPtr buffer, uint offset, uint len ) { try { byte[] bufTmp = new byte[len]; unsafe { byte* ptr = (byte*)buffer.ToPointer(); int i = 0; uint end = offset + len; for(; offset < end; offset++) { bufTmp[i++] = ptr[offset]; } } return Storage.Instance.Write( new UIntPtr( address ), bufTmp, 0, len ) ? 1 : 0; } catch { return 0; } } [RT.ExportedMethod] public static int Extern__Storage_Read( uint address, IntPtr buffer, uint offset, uint len ) { try { byte[] bufTmp = new byte[len]; Storage.Instance.Read( new UIntPtr( address ), bufTmp, 0, len ); unsafe { byte* ptr = (byte*)buffer.ToPointer(); uint end = offset + len; int i = 0; for(; offset < end; offset++) { ptr[offset] = bufTmp[i++]; } } return 1; } catch { return 0; } } [RT.ExportedMethod] public static int Extern__Storage_Memset( uint address, byte data, int len ) { try { uint dataPair = (uint)data; dataPair |= dataPair << 8; dataPair |= dataPair << 16; while(0 != (address & 0x3) ) { Storage.Instance.WriteByte( new UIntPtr( address ), data ); len -= 1; address += 1; } while(len > 4) { Storage.Instance.WriteWord( new UIntPtr( address ), dataPair ); len -= 4; address += 4; } while(len > 0) { Storage.Instance.WriteByte( new UIntPtr( address ), data ); len -= 1; address += 1; } return 1; } catch { return 0; } } [RT.ExportedMethod] public static int Extern__Storage_IsErased( uint address, int len ) { try { while(len > 0) { UIntPtr ptr = new UIntPtr( address ); if(Storage.Instance.ReadWord( ptr ) != 0xFFFFFFFFu) return 0; address += 4; len -= 4; } return 1; } catch { return 0; } } [RT.ExportedMethod] public static int Extern__Storage_EraseBlock( uint address, int len ) { try { return Storage.Instance.EraseSectors( new UIntPtr( address ), new UIntPtr( address + (uint)len ) ) ? 1 : 0; } catch { return 0; } } static void Main() { string dir = "\\ROOT\\Dir1"; string file = dir + "\\MyF.txt"; DirectoryInfo di; VolumeInfo v = new VolumeInfo( "ROOT" ); if(!v.IsFormatted) { v.Format( 0 ); } if(!Directory.Exists( dir )) { di = Directory.CreateDirectory( dir ); } if(File.Exists( file )) { File.Delete( file ); } using(FileStream fs = new FileStream( file, FileMode.CreateNew, FileAccess.Write )) { byte[] data = UTF8Encoding.UTF8.GetBytes( "Hello World!" ); fs.Write( data, 0, data.Length ); } using(FileStream fsIn = new FileStream( file, FileMode.Open, FileAccess.Read )) { byte[] data = new byte[128]; int len = fsIn.Read( data, 0, data.Length ); string str = UTF8Encoding.UTF8.GetString( data, 0, len ); Console.WriteLine( str ); } FileEnum fe = new FileEnum( dir, FileEnumFlags.Files ); if(fe.MoveNext()) { Console.WriteLine( fe.Current.ToString() ); } IOTests.Initialize(); IOTests.RunTests( new CreateDirectory() ); IOTests.RunTests( new Delete() ); IOTests.RunTests( new DI_Constructor() ); IOTests.RunTests( new DirectoryInfoTests() ); IOTests.RunTests( new DirectoryTests() ); IOTests.RunTests( new Exists() ); IOTests.RunTests( new GetDirectories() ); IOTests.RunTests( new GetFiles() ); IOTests.RunTests( new GetSetCurrentDirectory() ); IOTests.RunTests( new Move() ); IOTests.RunTests( new Copy() ); IOTests.RunTests( new Create() ); IOTests.RunTests( new FileDelete() ); IOTests.RunTests( new FileExists() ); IOTests.RunTests( new FileInfoTests() ); IOTests.RunTests( new FileTests() ); IOTests.RunTests( new GetSetAttributes() ); IOTests.RunTests( new Open_FM() ); IOTests.RunTests( new Open_FM_FA() ); IOTests.RunTests( new Open_FM_FA_FS() ); IOTests.RunTests( new OpenRead() ); IOTests.RunTests( new OpenWrite() ); IOTests.RunTests( new RWAllBytes() ); IOTests.RunTests( new CanRead() ); IOTests.RunTests( new CanSeek() ); IOTests.RunTests( new CanWrite() ); IOTests.RunTests( new Constructors_FileAccess() ); IOTests.RunTests( new Constructors_FileMode() ); IOTests.RunTests( new Constructors_FileShare() ); IOTests.RunTests( new FileStreamTests() ); IOTests.RunTests( new Flush() ); IOTests.RunTests( new PropertyTests() ); IOTests.RunTests( new Read() ); IOTests.RunTests( new Seek() ); IOTests.RunTests( new Write() ); IOTests.RunTests( new MemoryStreamCanRead() ); IOTests.RunTests( new MemoryStreamCanSeek() ); IOTests.RunTests( new MemoryStreamCanWrite() ); IOTests.RunTests( new Close() ); IOTests.RunTests( new MemoryStreamFlush() ); IOTests.RunTests( new Length() ); IOTests.RunTests( new MemoryStream_Ctor() ); IOTests.RunTests( new Position() ); IOTests.RunTests( new MemoryStreamRead() ); IOTests.RunTests( new ReadByte() ); IOTests.RunTests( new MemoryStreamSeek() ); IOTests.RunTests( new SetLength() ); IOTests.RunTests( new ToArray() ); IOTests.RunTests( new MemoryStreamWrite() ); IOTests.RunTests( new WriteByte() ); IOTests.RunTests( new WriteTo() ); IOTests.RunTests( new ChangeExtensions() ); IOTests.RunTests( new Combine() ); IOTests.RunTests( new GetDirectoryName() ); IOTests.RunTests( new GetExtension() ); IOTests.RunTests( new GetFileName() ); IOTests.RunTests( new GetFileNameWithoutExtension() ); IOTests.RunTests( new GetFullPath() ); IOTests.RunTests( new GetPathRoot() ); IOTests.RunTests( new HasExtension() ); IOTests.RunTests( new IsPathRooted() ); IOTests.RunTests( new PathTests() ); IOTests.RunTests( new VolumeLabelTests() ); Log.Comment( "\n\n!!!!!! FINISHED !!!!!!!\n\n" ); } } } ================================================ FILE: Zelig/Zelig/FileSystemTest/Properties/AssemblyInfo.cs ================================================ using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; // General Information about an assembly is controlled through the following // set of attributes. Change these attribute values to modify the information // associated with an assembly. [assembly: AssemblyTitle( "FileSystemTest" )] [assembly: AssemblyDescription( "" )] [assembly: AssemblyConfiguration( "" )] [assembly: AssemblyCompany( "Microsoft" )] [assembly: AssemblyProduct( "FileSystemTest" )] [assembly: AssemblyCopyright( "Copyright © Microsoft 2011" )] [assembly: AssemblyTrademark( "" )] [assembly: AssemblyCulture( "" )] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible( false )] // The following GUID is for the ID of the typelib if this project is exposed to COM [assembly: Guid( "9c59fa27-dd37-46ce-9c36-77b6db62a497" )] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Build and Revision Numbers // by using the '*' as shown below: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion( "1.0.0.0" )] [assembly: AssemblyFileVersion( "1.0.0.0" )] ================================================ FILE: Zelig/Zelig/FileSystemTest/VolumeLabelTests.cs ================================================ /*--------------------------------------------------------------------- * VolumeLabelTests.cs - file description * Version: 1.0 * Author: * Created: * * Tests the basic functionality of file system volumes * ---------------------------------------------------------------------*/ using System; using System.Reflection; using System.IO; namespace FileSystemTest { public class VolumeLabelTests : IMFTestInterface { [SetUp] public InitializeResult Initialize() { Log.Comment("Adding set up for the tests"); return InitializeResult.ReadyToGo; } [TearDown] public void CleanUp() { } [TestMethod] public MFTestResults VolumeLabelTest_SetLabel() { bool testResult = true; VolumeInfo[] volumes = VolumeInfo.GetVolumes(); for (int i = 0; i < volumes.Length; i++) { volumes[i].Format(volumes[i].FileSystem, 0, "Label1", true); testResult &= volumes[i].VolumeLabel == "Label1"; volumes[i].Format(volumes[i].FileSystem, 0, "Label2", true); testResult &= volumes[i].VolumeLabel == "Label2"; } return testResult ? MFTestResults.Pass : MFTestResults.Fail; } public MFTestMethod[] Tests { get { return new MFTestMethod[] { new MFTestMethod( VolumeLabelTest_SetLabel, "VolumeLabelTest_SetLabel" ), }; } } } } ================================================ FILE: Zelig/Zelig/RunTime/DeviceModels/CortexM0OnCMSIS-Core/CortexM0OnCMSIS-Core.csproj ================================================  Debug AnyCPU 9.0.21022 2.0 {B8FE271A-CD41-435E-8766-4DB7609C1007} Library Properties Microsoft.CortexM0OnCMSISCore Microsoft.CortexM0OnCMSISCore $(LlilumBuildRoot)\Target\obj\$(MSBuildProjectName)\ v4.5 512 true full false $(LlilumBuildRoot)\Target\bin\$(Configuration)\ DEBUG;TRACE prompt 4 true true true AllRules.ruleset AnyCPU false pdbonly true $(LlilumBuildRoot)\Target\bin\$(Configuration)\ TRACE prompt 4 true true true AllRules.ruleset AnyCPU false {186F31A3-EF89-4A25-B2D5-20060501AA01} mscorlib False {186F31A3-EF89-4A25-B2D5-20061218AA01} Common False {186F31A3-EF89-4A25-B2D5-20060509AA01} Kernel False {186F31A3-EF89-4A25-B2D5-20060720AA01} TypeSystem False {186f31a3-ef89-4a25-b2d5-20070702aa01} system False {20DC2CF5-8EED-4231-9743-6BAB96BE465C} LlilumOSAbstraction {c3bfafad-a6c6-471d-a059-b3cb7e57a4ab} ModelForCortexM0 {E4C618AF-1785-472E-A070-8068E20582EB} ModelForCortexM ================================================ FILE: Zelig/Zelig/RunTime/DeviceModels/CortexM0OnCMSIS-Core/HardwareModel/Board.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // namespace Microsoft.CortexM0OnCMSISCore { using System.Runtime.CompilerServices; using RT = Microsoft.Zelig.Runtime; using ChipsetModel = Microsoft.DeviceModels.Chipset.CortexM0; public abstract class Board : ChipsetModel.Board { } } ================================================ FILE: Zelig/Zelig/RunTime/DeviceModels/CortexM0OnCMSIS-Core/HardwareModel/Device.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // namespace Microsoft.CortexM0OnCMSISCore { using RT = Microsoft.Zelig.Runtime; public abstract class Device : RT.Device { } } ================================================ FILE: Zelig/Zelig/RunTime/DeviceModels/CortexM0OnCMSIS-Core/HardwareModel/Drivers/ContextSwitchTimer.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // namespace Microsoft.CortexM0OnCMSISCore.Drivers { using ChipsetModel = Microsoft.DeviceModels.Chipset.CortexM0; public abstract class ContextSwitchTimer : ChipsetModel.Drivers.ContextSwitchTimer { } } ================================================ FILE: Zelig/Zelig/RunTime/DeviceModels/CortexM0OnCMSIS-Core/HardwareModel/Drivers/InterruptController.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // namespace Microsoft.CortexM0OnCMSISCore.Drivers { using ChipsetModel = Microsoft.DeviceModels.Chipset.CortexM0; public abstract class InterruptController : ChipsetModel.Drivers.InterruptController { } } ================================================ FILE: Zelig/Zelig/RunTime/DeviceModels/CortexM0OnCMSIS-Core/HardwareModel/HardwareProvider.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // namespace Microsoft.CortexM0OnCMSISCore { using RT = Microsoft.Zelig.Runtime; //--// public abstract class HardwareProvider : RT.HardwareProvider { } } ================================================ FILE: Zelig/Zelig/RunTime/DeviceModels/CortexM0OnCMSIS-Core/HardwareModel/Memory.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // namespace Microsoft.CortexM0OnCMSISCore { using RT = Microsoft.Zelig.Runtime; public abstract class Memory : RT.Memory { } } ================================================ FILE: Zelig/Zelig/RunTime/DeviceModels/CortexM0OnCMSIS-Core/HardwareModel/Peripherals.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // //#define ALLOW_PAUSE namespace Microsoft.CortexM0OnCMSISCore { using RT = Microsoft.Zelig.Runtime; using LLOS = Zelig.LlilumOSAbstraction.HAL; using CMSIS = Microsoft.DeviceModels.Chipset.CortexM; using ARMv6 = Microsoft.Zelig.Runtime.TargetPlatform.ARMv6; public abstract class Peripherals : RT.Peripherals { // // State // // // Helper Methods // public override void Initialize() { RT.BugCheck.AssertInterruptsOff(); // // Faults, never disabled // // nothing to do, on an M0/1 faults are always enabled // // System exceptions // CMSIS.NVIC.SetPriority( (int)ARMv6.ProcessorARMv6M.IRQn_Type.SVCall_IRQn , ARMv6.ProcessorARMv6M.c_Priority__SVCCall ); CMSIS.NVIC.SetPriority( (int)ARMv6.ProcessorARMv6M.IRQn_Type.SysTick_IRQn_Optional, ARMv6.ProcessorARMv6M.c_Priority__SysTick ); CMSIS.NVIC.SetPriority( (int)ARMv6.ProcessorARMv6M.IRQn_Type.PendSV_IRQn , ARMv6.ProcessorARMv6M.c_Priority__PendSV ); } public override void Activate() { CMSIS.Drivers.InterruptController.Instance.Initialize(); CMSIS.Drivers.ContextSwitchTimer .Instance.Initialize(); } public override void EnableInterrupt( uint index ) { } public override void DisableInterrupt( uint index ) { } public override void CauseInterrupt() { ARMv6.ProcessorARMv6M.CompleteContextSwitch( ); //Drivers.InterruptController.Instance.CauseInterrupt( ); } public override void ContinueUnderNormalInterrupt(Continuation dlg) { Drivers.InterruptController.Instance.ContinueUnderNormalInterrupt(dlg); } public override void WaitForInterrupt() { ARMv6.ProcessorARMv6M.WaitForInterrupt( ); } public override void ProcessInterrupt() { using (RT.SmartHandles.SwapCurrentThreadUnderInterrupt hnd = RT.ThreadManager.InstallInterruptThread()) { Drivers.InterruptController.Instance.ProcessInterrupt(); } } [RT.MemoryRequirements(RT.MemoryAttributes.RAM)] public override void ProcessFastInterrupt() { using (RT.SmartHandles.SwapCurrentThreadUnderInterrupt hnd = RT.ThreadManager.InstallFastInterruptThread()) { Drivers.InterruptController.Instance.ProcessFastInterrupt(); } } public override ulong GetPerformanceCounterFrequency() { return LLOS.Clock.LLOS_CLOCK_GetPerformanceCounterFrequency(); } [RT.Inline] [RT.DisableNullChecks()] public override uint ReadPerformanceCounter() { return (uint)LLOS.Clock.LLOS_CLOCK_GetPerformanceCounter(); } } } ================================================ FILE: Zelig/Zelig/RunTime/DeviceModels/CortexM0OnCMSIS-Core/HardwareModel/Processor.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // namespace Microsoft.CortexM0OnCMSISCore { using System; using RT = Microsoft.Zelig.Runtime; using ChipsetModel = Microsoft.DeviceModels.Chipset.CortexM0; using LLOS = Zelig.LlilumOSAbstraction.HAL; public abstract class Processor : ChipsetModel.Processor { public abstract new class Context : RT.TargetPlatform.ARMv6.ProcessorARMv6MForLlvm.Context { // // Constructor Methods // protected Context( RT.ThreadImpl owner ) : base( owner ) { } // // Helper Methods // #region RTOS extensibility protected virtual UIntPtr CreateNativeContext( UIntPtr entryPoint, UIntPtr stack, int stackSize ) { return (UIntPtr)0; } protected virtual void SwitchToContext( UIntPtr thread ) { } protected virtual void Yield( UIntPtr handle ) { } protected virtual void Retire( UIntPtr handle ) { } #endregion // // Access Methods // } // // Helper Methods // public override void InitializeProcessor() { base.InitializeProcessor(); } } //--// //--// //--// [RT.ExtendClass( typeof( Microsoft.Zelig.Runtime.Processor ) )] internal class ProcessorImpl { [RT.MergeWithTargetImplementation] internal ProcessorImpl() { } [RT.NoInline] [RT.MemoryUsage( RT.MemoryUsage.Bootstrap )] public static int Delay( int count ) { LLOS.Clock.LLOS_CLOCK_DelayCycles( (uint)count ); return 0; } } } ================================================ FILE: Zelig/Zelig/RunTime/DeviceModels/CortexM0OnCMSIS-Core/HardwareModel/SerialPortsManager.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // namespace Microsoft.CortexM0OnCMSISCore { using RT = Microsoft.Zelig.Runtime; //--// public abstract class SerialPortsManager : RT.SerialPortsManager { } } ================================================ FILE: Zelig/Zelig/RunTime/DeviceModels/CortexM0OnCMSIS-Core/HardwareModel/Storage.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // namespace Microsoft.CortexM0OnCMSISCore { using System; using RT = Microsoft.Zelig.Runtime; using TS = Microsoft.Zelig.Runtime.TypeSystem; public abstract class Storage : RT.Storage { public override void InitializeStorage( ) { } //--// public override bool EraseSectors( UIntPtr addressStart, UIntPtr addressEnd ) { RT.BugCheck.Raise(RT.BugCheck.StopCode.FailedBootstrap); throw new Exception( "EraseSectors not implemented" ); } public override bool WriteByte( UIntPtr address, byte val ) { RT.BugCheck.Raise(RT.BugCheck.StopCode.FailedBootstrap); throw new Exception( "WriteByte not implemented" ); } public override bool WriteShort( UIntPtr address, ushort val ) { RT.BugCheck.Raise(RT.BugCheck.StopCode.FailedBootstrap); throw new Exception( "WriteShort not implemented" ); } public override bool WriteWord( UIntPtr address, uint val ) { RT.BugCheck.Raise(RT.BugCheck.StopCode.FailedBootstrap); throw new Exception( "WriteWord not implemented" ); } public override bool Write( UIntPtr address, byte[] buffer, uint offset, uint numBytes ) { RT.BugCheck.Raise(RT.BugCheck.StopCode.FailedBootstrap); throw new Exception( "Write not implemented" ); } //--// public override byte ReadByte( UIntPtr address ) { RT.BugCheck.Raise(RT.BugCheck.StopCode.FailedBootstrap); throw new Exception( "ReadByte not implemented" ); } public override ushort ReadShort( UIntPtr address ) { RT.BugCheck.Raise(RT.BugCheck.StopCode.FailedBootstrap); throw new Exception( "ReadShort not implemented" ); } public override uint ReadWord( UIntPtr address ) { RT.BugCheck.Raise(RT.BugCheck.StopCode.FailedBootstrap); throw new Exception( "ReadWord not implemented" ); } public override void Read( UIntPtr address, byte[] buffer, uint offset, uint numBytes ) { RT.BugCheck.Raise(RT.BugCheck.StopCode.FailedBootstrap); throw new Exception( "Read not implemented" ); } public override void SubstituteFirmware( UIntPtr addressDestination, UIntPtr addressSource, uint numBytes ) { RT.BugCheck.Raise(RT.BugCheck.StopCode.FailedBootstrap); throw new Exception( "SubstituteFirmware not implemented" ); } public override void RebootDevice( ) { RT.BugCheck.Raise(RT.BugCheck.StopCode.FailedBootstrap); } } } ================================================ FILE: Zelig/Zelig/RunTime/DeviceModels/CortexM0OnCMSIS-Core/Properties/AssemblyInfo.cs ================================================ using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; // General Information about an assembly is controlled through the following // set of attributes. Change these attribute values to modify the information // associated with an assembly. [assembly: AssemblyTitle( "Microsoft.CortexM0OnCMSISCore" )] [assembly: AssemblyDescription( "" )] [assembly: AssemblyConfiguration( "" )] [assembly: AssemblyCompany( "Microsoft" )] [assembly: AssemblyProduct( "LLILUM" )] [assembly: AssemblyCopyright( "Copyright © Microsoft 2015" )] [assembly: AssemblyTrademark( "" )] [assembly: AssemblyCulture( "" )] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible( false )] // The following GUID is for the ID of the typelib if this project is exposed to COM //[assembly: Guid( "ffacd01c-fa64-4234-9058-1ad866f88c1a" )] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Build and Revision Numbers // by using the '*' as shown below: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion( "1.0.0.0" )] [assembly: AssemblyFileVersion( "1.0.0.0" )] ================================================ FILE: Zelig/Zelig/RunTime/DeviceModels/CortexM0OnCMSIS-Core/SystemServices/GarbageCollectionManager.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // namespace Microsoft.CortexM0OnCMSISCore { using System; using RT = Microsoft.Zelig.Runtime; using PROC = Microsoft.Zelig.Runtime.TargetPlatform.ARMv6; public abstract class GarbageCollectionManager : RT.ConservativeMarkAndSweepCollector { public override uint Collect() { // Snapshot the registers on the current thread PROC.ProcessorARMv6M.RaiseSupervisorCall( PROC.ProcessorARMv6M.SVC_Code.SupervisorCall__SnapshotProcessModeRegisters ); return base.Collect(); } //--// protected override void WalkStackFrames() { // Mark the registers from the snapshot for (uint regNum = 0; regNum < 13; regNum++) { UIntPtr ptr = PROC.ProcessorARMv6MForLlvm.Snapshot.GetRegisterValue(regNum); if (ptr != UIntPtr.Zero) { VisitInternalPointer(ptr); } } base.WalkStackFrames(); } } } ================================================ FILE: Zelig/Zelig/RunTime/DeviceModels/CortexM0OnCMSIS-Core/SystemServices/MemoryManager.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // namespace Microsoft.CortexM0OnCMSISCore { using RT = Microsoft.Zelig.Runtime; public abstract class MemoryManager : RT.LinearMemoryManager { } } ================================================ FILE: Zelig/Zelig/RunTime/DeviceModels/CortexM0OnCMSIS-Core/SystemServices/ThreadManager.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // namespace Microsoft.CortexM0OnCMSISCore { using ChipsetModel = Microsoft.DeviceModels.Chipset.CortexM0; public abstract class ThreadManager : ChipsetModel.Runtime.ThreadManager { } } ================================================ FILE: Zelig/Zelig/RunTime/DeviceModels/CortexM0OnCMSIS-Core/SystemServices/TimerPool.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // namespace Microsoft.CortexM0OnCMSISCore { using RT = Microsoft.Zelig.Runtime; public abstract class TimerPool : RT.TimerImpl.SyncDispatcherTimerPool { } } ================================================ FILE: Zelig/Zelig/RunTime/DeviceModels/CortexM0OnCMSIS-Core/SystemServices/TypeSystemManager.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // namespace Microsoft.CortexM0OnCMSISCore { using RT = Microsoft.Zelig.Runtime; public abstract class TypeSystemManager : RT.DefaultTypeSystemManager { } } ================================================ FILE: Zelig/Zelig/RunTime/DeviceModels/CortexM0OnMBED/CortexM0OnMBED.csproj ================================================  Debug AnyCPU 9.0.21022 2.0 {89EBDBB0-C81F-4611-B719-B385DF215F8D} Library Properties Microsoft.CortexM0OnMBED Microsoft.CortexM0OnMBED $(LlilumBuildRoot)\Target\obj\$(MSBuildProjectName)\ v4.5 512 true full false $(LlilumBuildRoot)\Target\bin\$(Configuration)\ DEBUG;TRACE prompt 4 true true true AllRules.ruleset AnyCPU false pdbonly true $(LlilumBuildRoot)\Target\bin\$(Configuration)\ TRACE prompt 4 true true true AllRules.ruleset AnyCPU false {186F31A3-EF89-4A25-B2D5-20060501AA01} mscorlib False {186F31A3-EF89-4A25-B2D5-20061218AA01} Common False {186F31A3-EF89-4A25-B2D5-20060509AA01} Kernel False {186F31A3-EF89-4A25-B2D5-20060720AA01} TypeSystem False {d68ee51b-a898-4a77-97d8-c61254cac122} Microsoft.Llilum.Devices {186f31a3-ef89-4a25-b2d5-20070702aa01} system False {dc8c38d7-780b-4b13-8ace-9050e39cc51c} Windows {20DC2CF5-8EED-4231-9743-6BAB96BE465C} LlilumOSAbstraction {d7f2bc4e-1406-47aa-90e1-07bc4ce9410f} mbed {e77ac86e-58ab-47b6-bc6d-3c1b4545cdfd} Microsoft.Llilum.Lwip {b8fe271a-cd41-435e-8766-4db7609c1007} CortexM0OnCMSIS-Core {c3bfafad-a6c6-471d-a059-b3cb7e57a4ab} ModelForCortexM0 {e4c618af-1785-472e-a070-8068e20582eb} ModelForCortexM ================================================ FILE: Zelig/Zelig/RunTime/DeviceModels/CortexM0OnMBED/HardwareModel/Board.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // namespace Microsoft.CortexM0OnMBED { using System.Runtime.CompilerServices; using RT = Microsoft.Zelig.Runtime; using ChipsetModel = Microsoft.CortexM0OnCMSISCore; public abstract class Board : ChipsetModel.Board { } } ================================================ FILE: Zelig/Zelig/RunTime/DeviceModels/CortexM0OnMBED/HardwareModel/Device.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // namespace Microsoft.CortexM0OnMBED { using RT = Microsoft.Zelig.Runtime; using RTOS = Microsoft.Zelig.Support.mbed; using ChipsetModel = Microsoft.CortexM0OnCMSISCore; public abstract class Device : ChipsetModel.Device { public override void PreInitializeProcessorAndMemory( ) { RT.BugCheck.Raise( RT.BugCheck.StopCode.FailedBootstrap ); } public override void MoveCodeToProperLocation( ) { RT.BugCheck.Raise( RT.BugCheck.StopCode.FailedBootstrap ); } public override void ProcessBugCheck( RT.BugCheck.StopCode code ) { m_bugCheckCode = code; RT.TargetPlatform.ARMv6.ProcessorARMv6M.Breakpoint( 0x42 ); } public override unsafe void ProcessLog(string format) { fixed (char* pS = format) { uint length = (uint)format.Length; RTOS.Utilities.DebugLog0(pS, length); } } public override unsafe void ProcessLog(string format, int p1) { fixed (char* pS = format) { uint length = (uint)format.Length; RTOS.Utilities.DebugLog1(pS, length, p1); } } public override unsafe void ProcessLog(string format, int p1, int p2) { fixed (char* pS = format) { uint length = (uint)format.Length; RTOS.Utilities.DebugLog2(pS, length, p1, p2); } } public override unsafe void ProcessLog(string format, int p1, int p2, int p3) { fixed (char* pS = format) { uint length = (uint)format.Length; RTOS.Utilities.DebugLog3(pS, length, p1, p2, p3); } } public override unsafe void ProcessLog(string format, int p1, int p2, int p3, int p4) { fixed (char* pS = format) { uint length = (uint)format.Length; RTOS.Utilities.DebugLog4(pS, length, p1, p2, p3, p4); } } public override unsafe void ProcessLog(string format, int p1, int p2, int p3, int p4, int p5) { fixed (char* pS = format) { uint length = (uint)format.Length; RTOS.Utilities.DebugLog5(pS, length, p1, p2, p3, p4, p5); } } } } ================================================ FILE: Zelig/Zelig/RunTime/DeviceModels/CortexM0OnMBED/HardwareModel/Drivers/AdcChannel.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // namespace Microsoft.CortexM0OnMBED.HardwareModel { using System; using System.Runtime.InteropServices; using Runtime = Microsoft.Zelig.Runtime; using LLIO = Zelig.LlilumOSAbstraction.API.IO; public class AdcChannel : Llilum.Devices.Adc.AdcChannel { private unsafe LLIO.AdcContext* m_adc; private int m_pinNumber; internal AdcChannel(int pinNumber) { m_pinNumber = pinNumber; } ~AdcChannel() { Dispose(false); } public override void Dispose() { Dispose(true); } private unsafe void Dispose(bool disposing) { if (m_adc != null) { LLIO.Adc.LLOS_ADC_Uninitialize(m_adc); m_adc = null; if (disposing) { Runtime.HardwareProvider.Instance.ReleasePins(m_pinNumber); GC.SuppressFinalize(this); } } } public override void InitializePin() { unsafe { fixed (LLIO.AdcContext** adc_ptr = &m_adc) { LLIO.Adc.LLOS_ADC_Initialize((uint)m_pinNumber, LLIO.AdcDirection.Input, adc_ptr); } } } public override uint ReadUnsigned() { int value = 0; unsafe { LLIO.Adc.LLOS_ADC_ReadRaw(m_adc, &value); } return (uint)value; } public override float Read() { float result = 0f; unsafe { LLIO.Adc.LLOS_ADC_Read(m_adc, &result); } return result; } } } ================================================ FILE: Zelig/Zelig/RunTime/DeviceModels/CortexM0OnMBED/HardwareModel/Drivers/GpioPin.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // namespace Microsoft.CortexM0OnMBED.HardwareModel { using System; using Llilum = Llilum.Devices.Gpio; using RT = Microsoft.Zelig.Runtime; using M = DeviceModels.Chipset.CortexM; using MBED = CortexM0OnMBED.Drivers; using LLOS = Zelig.LlilumOSAbstraction.API.IO; using LLGPIO = Zelig.LlilumOSAbstraction.API.IO.Gpio; using LLINTC = DeviceModels.Chipset.CortexM0.Drivers.InterruptController; public class GpioPin : Llilum.GpioPin { private readonly int m_pinNumber; private unsafe LLOS.GpioContext* m_gpio; private LLINTC.Handler m_handler; private LLOS.GpioPinEdge m_activeEdge; private LLOS.GpioPinResistor m_pinMode; //-// // // Constructor methods // public static GpioPin Create( int pinNumber ) { return new GpioPin( pinNumber ); } public static void Release( GpioPin pin ) { pin.Dispose(); } internal GpioPin( int pinNumber ) { m_pinNumber = pinNumber; unsafe { fixed (LLOS.GpioContext** gpio_ptr = &m_gpio) { LLGPIO.LLOS_GPIO_AllocatePin( m_pinNumber, gpio_ptr ); } // Default to Rising edge ActivePinEdge = Llilum.PinEdge.RisingEdge; } } ~GpioPin( ) { Dispose( false ); } public override void Dispose( ) { unsafe { if(m_gpio != null) { Dispose( true ); m_gpio = null; GC.SuppressFinalize( this ); } } } // // Helper methods // [RT.Inline] public override int Read( ) { unsafe { return LLGPIO.LLOS_GPIO_Read( m_gpio ); } } [RT.Inline] public override void Write( int value ) { unsafe { LLGPIO.LLOS_GPIO_Write( m_gpio, value ); } } protected override void SetPinMode( Llilum.PinMode pinMode ) { unsafe { m_pinMode = (LLOS.GpioPinResistor)pinMode; LLGPIO.LLOS_GPIO_SetMode( m_gpio, m_pinMode ); } } protected override void SetPinDirection( Llilum.PinDirection pinDirection ) { unsafe { LLGPIO.LLOS_GPIO_SetDirection( m_gpio, pinDirection == Llilum.PinDirection.Input ? LLOS.GpioPinDirection.Input : LLOS.GpioPinDirection.Output ); } } protected override void SetActivePinEdge( Llilum.PinEdge pinEdge ) { m_activeEdge = (LLOS.GpioPinEdge)pinEdge; //if(m_handler != null) //{ // DisableInterrupt( ); // EnableInterrupt( ); //} } protected override void EnableInterrupt( ) { if(m_handler == null) { m_handler = LLINTC.Handler.Create( RT.GpioProvider.Instance.GetGpioPinIRQNumber( m_pinNumber ), M.Drivers.InterruptPriority.Normal, M.Drivers.InterruptSettings.RisingEdge, ProcessGpioInterrupt ); } unsafe { UIntPtr hndPtr = MBED.InterruptController.CastInterruptHandlerAsPtr( m_handler ); LLGPIO.LLOS_GPIO_EnablePin( m_gpio, m_activeEdge, HandleGpioInterruptNative, hndPtr ); } } protected override void DisableInterrupt( ) { unsafe { LLGPIO.LLOS_GPIO_DisablePin( m_gpio ); } } protected void Dispose( bool disposing ) { unsafe { LLGPIO.LLOS_GPIO_FreePin( m_gpio ); } using(RT.SmartHandles.InterruptState.Disable( )) { LLINTC.Instance.Deregister( m_handler ); } if(disposing) { RT.HardwareProvider.Instance.ReleasePins( m_pinNumber ); } } // // Access methods // public override int PinNumber { get { return m_pinNumber; } } //--// private void ProcessGpioInterrupt( LLINTC.InterruptData data ) { SendEventInternal( (Llilum.PinEdge)data.Context ); } private static unsafe void HandleGpioInterruptNative( LLOS.GpioContext* pin, UIntPtr context, LLOS.GpioPinEdge evt ) { LLINTC.InterruptData data; data.Handler = MBED.InterruptController.CastAsInterruptHandler( context ); data.Context = (uint)evt; // // This interrupt handler does not come from the ISR vector table, but rather from the handler set up // by mBed through 'NVIC_SetVector( , (uint32_t)us_ticker_irq_handler)' during initialization. // Therefore we need to wrap this specific handler here, which is where it first shows up. // using(RT.SmartHandles.InterruptState.Disable( )) { using(RT.SmartHandles.SwapCurrentThreadUnderInterrupt hnd = RT.ThreadManager.InstallInterruptThread( )) { CortexM0OnCMSISCore.Drivers.InterruptController.Instance.PostInterrupt( data ); } } } } } ================================================ FILE: Zelig/Zelig/RunTime/DeviceModels/CortexM0OnMBED/HardwareModel/Drivers/I2cChannel.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // namespace Microsoft.CortexM0OnMBED.HardwareModel { using System; using System.Runtime.InteropServices; using Llilum.Devices.I2c; using RT = Microsoft.Zelig.Runtime; using LLOS = Zelig.LlilumOSAbstraction; using LLIO = Zelig.LlilumOSAbstraction.API.IO; public class I2cChannel : Llilum.Devices.I2c.I2cChannel { private unsafe LLIO.I2CContext* m_i2c; private II2cChannelInfo m_channelInfo; public I2cChannel(II2cChannelInfo channelInfo) { m_channelInfo = channelInfo; } ~I2cChannel() { Dispose(false); } public override void Dispose() { Dispose(true); } private unsafe void Dispose(bool disposing) { if (m_i2c != null) { LLIO.I2C.LLOS_I2C_Uninitialize( m_i2c ); m_i2c = null; if (disposing) { RT.HardwareProvider.Instance.ReleasePins(m_channelInfo.SclPin, m_channelInfo.SdaPin); GC.SuppressFinalize(this); } } } public override II2cChannelInfo GetChannelInfo() { return m_channelInfo; } public unsafe override void Initialize(II2cChannelInfo channelInfo) { fixed (LLIO.I2CContext** i2c_ptr = &m_i2c) { LLIO.I2C.LLOS_I2C_Initialize(channelInfo.SdaPin, channelInfo.SclPin, i2c_ptr); } } public unsafe override void SetFrequency(int hz) { LLIO.I2C.LLOS_I2C_SetFrequency(m_i2c, (uint)hz); } public override int Read(byte[] buffer, int deviceAddress, int transactionStartOffset, int transactionLength, bool sendStop) { // Ensure buffer isn't null or empty if (buffer == null || buffer.Length <= 0) { throw new ArgumentException(); } // Ensure accurate bounds for the transaction if (transactionStartOffset < 0 || buffer.Length < (transactionStartOffset + transactionLength)) { throw new ArgumentException(); } unsafe { int bytesRead = transactionLength; fixed (byte* pBuffer = &buffer[0]) { LLOS.LlilumErrors.ThrowOnError( LLIO.I2C.LLOS_I2C_Read( m_i2c, (uint)deviceAddress, pBuffer, transactionStartOffset, &bytesRead, ( sendStop ? 1u : 0u ) ), true ); return bytesRead; } } } public override int Write(byte[] buffer, int deviceAddress, int transactionStartOffset, int transactionLength, bool sendStop) { // Ensure buffer isn't null or empty if (buffer == null || buffer.Length <= 0) { throw new ArgumentException(); } // Ensure accurate bounds for the transaction if (transactionStartOffset < 0 || buffer.Length < (transactionStartOffset + transactionLength)) { throw new ArgumentException(); } unsafe { int bytesWritten = transactionLength; fixed (byte* pBuffer = &buffer[0]) { LLOS.LlilumErrors.ThrowOnError( LLIO.I2C.LLOS_I2C_Write( m_i2c, (uint)deviceAddress, pBuffer, transactionStartOffset, &bytesWritten, ( sendStop ? 1u : 0u ) ), true ); return bytesWritten; } } } } } ================================================ FILE: Zelig/Zelig/RunTime/DeviceModels/CortexM0OnMBED/HardwareModel/Drivers/InterruptController.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // namespace Microsoft.CortexM0OnMBED.Drivers { using System; using TS = Zelig.Runtime.TypeSystem; using RT = Zelig.Runtime; using ChipsetModel = CortexM0OnCMSISCore; public abstract class InterruptController : ChipsetModel.Drivers.InterruptController { // // TODO: If GC compaction is ever supported, we will need to // come up with way to handle this differently. Otherwise, // the object might move while its address is referenced in // native code. // [TS.GenerateUnsafeCast()] internal extern static Handler CastAsInterruptHandler(UIntPtr ptr); [RT.Inline] internal static UIntPtr CastInterruptHandlerAsPtr(Handler hnd) { return ((RT.ObjectImpl)(object)hnd).ToPointer(); } } } ================================================ FILE: Zelig/Zelig/RunTime/DeviceModels/CortexM0OnMBED/HardwareModel/Drivers/PwmChannel.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // namespace Microsoft.CortexM0OnMBED.HardwareModel { using System; using Runtime = Microsoft.Zelig.Runtime; using LLIO = Zelig.LlilumOSAbstraction.API.IO; using Llilum.Devices.Pwm; public class PwmChannel : Llilum.Devices.Pwm.PwmChannel { private unsafe LLIO.PwmContext* m_pwm; private int m_pinNumber; internal PwmChannel(int pinNumber) { m_pinNumber = pinNumber; } ~PwmChannel() { Dispose(false); } public override void Dispose() { Dispose(true); } private unsafe void Dispose(bool disposing) { if (m_pwm != null) { LLIO.Pwm.LLOS_PWM_Uninitialize(m_pwm); m_pwm = null; if (disposing) { Runtime.HardwareProvider.Instance.ReleasePins(m_pinNumber); GC.SuppressFinalize(this); } } } public override void InitializePin() { unsafe { fixed (LLIO.PwmContext** ppAdc = &m_pwm) { LLIO.Pwm.LLOS_PWM_Initialize((uint)m_pinNumber, ppAdc); } } } public unsafe override void SetDutyCycle(float ratio) { ThrowIfDisposed(); LLIO.Pwm.LLOS_PWM_SetDutyCycle(m_pwm, (uint)(ratio * 1024.0), 1024); } public unsafe override void SetPulseWidth(int microSeconds) { ThrowIfDisposed(); LLIO.Pwm.LLOS_PWM_SetPulseWidth(m_pwm, (uint)microSeconds); } public unsafe override void SetPeriod(int microSeconds) { ThrowIfDisposed(); LLIO.Pwm.LLOS_PWM_SetPeriod(m_pwm, (uint)microSeconds); } private unsafe void ThrowIfDisposed() { if(m_pwm == null) { throw new ObjectDisposedException(null); } } public unsafe override void SetPolarity( PwmPolarity polarity ) { ThrowIfDisposed(); LLIO.Pwm.LLOS_PWM_SetPolarity(m_pwm, (LLIO.PwmPolarity)polarity); } public unsafe override void SetPrescaler( PwmPrescaler prescaler ) { ThrowIfDisposed(); LLIO.Pwm.LLOS_PWM_SetPrescaler(m_pwm, (LLIO.PwmPrescaler) prescaler); } public unsafe override void Start( ) { ThrowIfDisposed(); LLIO.Pwm.LLOS_PWM_Start(m_pwm); } public unsafe override void Stop( ) { ThrowIfDisposed(); LLIO.Pwm.LLOS_PWM_Stop(m_pwm); } } } ================================================ FILE: Zelig/Zelig/RunTime/DeviceModels/CortexM0OnMBED/HardwareModel/Drivers/SerialPortsManager.cs ================================================ using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Microsoft.CortexM0OnMBED.HardwareModel.Drivers { using System; using RT = Microsoft.Zelig.Runtime; using TS = Microsoft.Zelig.Runtime.TypeSystem; using Chipset = Microsoft.CortexM0OnCMSISCore; public class SerialPortsManager : Chipset.SerialPortsManager { public override void Initialize() { } public override string[] GetPortNames() { return RT.HardwareProvider.Instance.GetSerialPorts(); } public override System.IO.Ports.SerialStream Open(ref RT.BaseSerialStream.Configuration cfg) { StandardSerialPort port = new StandardSerialPort(ref cfg/*, id, 3*/); port.Open(); return port; } } } ================================================ FILE: Zelig/Zelig/RunTime/DeviceModels/CortexM0OnMBED/HardwareModel/Drivers/SpiChannel.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // namespace Microsoft.CortexM0OnMBED.HardwareModel { using System; using Microsoft.Zelig.Runtime; using Microsoft.Llilum.Devices.Spi; using LlilumGpio = Microsoft.Llilum.Devices.Gpio; using LLOS = Zelig.LlilumOSAbstraction; using LLIO = Zelig.LlilumOSAbstraction.API.IO; public class SpiChannel : Microsoft.Llilum.Devices.Spi.SpiChannel { private unsafe LLIO.SpiContext* m_spi; private unsafe LLIO.SpiConfig* m_spiCfg; private unsafe LlilumGpio.GpioPin m_altCsPin; private ISpiChannelInfo m_channelInfo; //--// public SpiChannel(ISpiChannelInfo info) { m_channelInfo = info; } ~SpiChannel() { Dispose(false); } /// /// Closes resources associated with this SPI device /// public unsafe override void Dispose() { Dispose(true); } /// /// Disposes of all resources associated with this SPI device /// /// True if called from Dispose, false if called from the finalizer. private unsafe void Dispose(bool disposing) { // Native resources need to be freed unconditionally if(m_spi != null) { LLIO.Spi.LLOS_SPI_Uninitialize(m_spi); m_spi = null; } if(disposing) { GC.SuppressFinalize(this); } } /// /// Gets hardware information for this channel /// /// public override ISpiChannelInfo GetChannelInfo() { return m_channelInfo; } /// /// Performs a synchronous transfer over the SpiChannel /// /// Bytes to write. Leave null for read-only /// Offset into the writeBuffer /// Length of the data in bytes to write /// Bytes to read. Leave null for write-only /// Offset into the readBuffer /// Length in bytes to read /// Index of the SPI response at which to start reading bytes into readBuffer at readOffset. This is used if the SPI response requires multiple writes before the response data is ready. public unsafe override void WriteRead( byte[] writeBuffer, int writeOffset, int writeLength, byte[] readBuffer, int readOffset, int readLength, int startReadOffset ) { EnableChipSelect( ); // Are we reading, writing, or both? // We need to be at least one of these if(readBuffer == null && writeBuffer == null) { throw new ArgumentException( ); } ArrayImpl writeImpl = (ArrayImpl)(object)writeBuffer; ArrayImpl readImpl = (ArrayImpl)(object)readBuffer; LLIO.Spi.LLOS_SPI_Transfer( m_spi, (byte*)writeImpl.GetDataPointer( ), writeOffset, writeLength, (byte*)readImpl.GetDataPointer( ), readOffset, readLength, startReadOffset ); DisableChipselect( ); } public unsafe override void Write( byte[] writeBuffer, int writeOffset, int writeLength ) { ArrayImpl writeImpl = (ArrayImpl)(object)writeBuffer; EnableChipSelect( ); LLIO.Spi.LLOS_SPI_Write( m_spi, (byte*)writeImpl.GetDataPointer(), writeOffset, writeLength ); DisableChipselect( ); } public unsafe override void Read( byte[] readBuffer, int readOffset, int readLength ) { ArrayImpl readImpl = (ArrayImpl)(object)readBuffer; EnableChipSelect( ); LLIO.Spi.LLOS_SPI_Read( m_spi, (byte*)readImpl.GetDataPointer(), readOffset, readLength, 0 ); DisableChipselect( ); } public unsafe override void SetupChannel(int bits, SpiMode mode, bool isSlave) { m_spiCfg->Master = isSlave ? 0u : 1u; m_spiCfg->DataWidth = (uint)bits; m_spiCfg->PhaseMode = ( mode == SpiMode.Cpol0Cpha1 || mode == SpiMode.Cpol1Cpha1 ) ? 1u : 0u; m_spiCfg->InversePolarity = ( mode == SpiMode.Cpol1Cpha0 || mode == SpiMode.Cpol1Cpha1 ) ? 1u : 0u; LLIO.Spi.LLOS_SPI_Configure( m_spi, m_spiCfg ); } public unsafe override void SetupTiming(int frequencyInHz, int setupTime, int holdTime) { const int defaultDelayCycles = 100; if (setupTime < 0) { m_spiCfg->ChipSelectSetupCycles = ConvertToCoreClockTicks( defaultDelayCycles, frequencyInHz ); } else { m_spiCfg->ChipSelectSetupCycles = ConvertToCoreClockTicks( setupTime, frequencyInHz ); } if (holdTime < 0) { m_spiCfg->ChipSelectHoldCycles = ConvertToCoreClockTicks( defaultDelayCycles, frequencyInHz ); } else { m_spiCfg->ChipSelectHoldCycles = ConvertToCoreClockTicks( holdTime, frequencyInHz ); } m_spiCfg->ClockRateHz = (uint)frequencyInHz; LLIO.Spi.LLOS_SPI_SetFrequency(m_spi, (uint)frequencyInHz); } /// /// Initializes the mbed SpiChannel with the appropriate pins /// /// SPI channel pin info /// Determines whether this is a write-only SPI channel, in which case the MISO pin is not used. public unsafe override void SetupPins(ISpiChannelInfo channelInfo, bool writeOnly) { fixed (LLIO.SpiContext** spi_ptr = &m_spi) fixed (LLIO.SpiConfig** spicfg_ptr = &m_spiCfg) { LLIO.Spi.LLOS_SPI_Initialize((uint)channelInfo.Mosi, writeOnly ? (uint)HardwareProvider.Instance.InvalidPin : (uint)channelInfo.Miso, (uint)channelInfo.Sclk, (uint)channelInfo.DefaultChipSelect, spi_ptr, spicfg_ptr ); } Initialize( channelInfo ); } /// /// Initializes the mbed SpiChannel with an alternate chip select pin /// /// SPI channel pin info /// Manually toggled CS pin /// Determines whether this is a write-only SPI channel, in which case the MISO pin is not used. public unsafe override void SetupPins(ISpiChannelInfo channelInfo, int alternateCsPin, bool writeOnly) { fixed(LLIO.SpiContext** ppSpi = &m_spi) fixed (LLIO.SpiConfig** spicfg_ptr = &m_spiCfg) { // Since we are using an alternate CS pin, initialize CS with the Invalid Pin LLIO.Spi.LLOS_SPI_Initialize( (uint)channelInfo.Mosi, writeOnly ? (uint)HardwareProvider.Instance.InvalidPin : (uint)channelInfo.Miso, (uint)channelInfo.Sclk, (uint)HardwareProvider.Instance.InvalidPin, ppSpi, spicfg_ptr ); } Initialize( channelInfo ); // Set up the pin, unless it's the invalid pin. It has already been reserved if (alternateCsPin != HardwareProvider.Instance.InvalidPin) { m_altCsPin = GpioPin.TryCreateGpioPin(alternateCsPin); if (m_altCsPin == null) { throw new ArgumentException(); } m_altCsPin.Direction = LlilumGpio.PinDirection.Output; m_altCsPin.Mode = LlilumGpio.PinMode.Default; // Set to high for the lifetime of the SpiChannel (except on transfers) m_altCsPin.Write(m_spiCfg->ActiveLow == 1 ? 1 : 0); } } private unsafe void Initialize(ISpiChannelInfo channelInfo) { // Mbed assumes active low, so we only set up active low/high when using the alternate CS pin m_spiCfg->ActiveLow = channelInfo.ActiveLow ? 1u : 0u; m_spiCfg->BusyPin = (uint)HardwareProvider.Instance.InvalidPin; m_spiCfg->ClockIdleLevel = 0; m_spiCfg->ClockSamplingEdge = 0; m_spiCfg->LoopbackMode = 0; m_spiCfg->MSBTransferMode = 0; m_spiCfg->ChipSelect = (uint)channelInfo.DefaultChipSelect; } private uint ConvertToCoreClockTicks(int spiCycles, int spiFrequencyInHz) { ulong cpu = LLOS.HAL.Clock.LLOS_CLOCK_GetClockFrequency( ); return (uint)( (ulong)spiCycles * cpu / (ulong)spiFrequencyInHz ); } private unsafe void EnableChipSelect() { // Enable the chip select if (m_altCsPin != null) { m_altCsPin.Write(m_spiCfg->ActiveLow == 1 ? 0 : 1); // Setup time in cycles Processor.Delay( (int)m_spiCfg->ChipSelectSetupCycles ); } } private unsafe void DisableChipselect() { // Disable the chip select if (m_altCsPin != null) { // Some boards (K64F) do not support checking if SPI is busy through mbed if (SpiProvider.Instance.SpiBusySupported) { uint isBusy = 0; while( LLOS.LlilumErrors.Succeeded( LLIO.Spi.LLOS_SPI_IsBusy( m_spi, &isBusy ) ) ) { // Spin until transaction is complete if( isBusy == 0 ) { break; } } } // Hold time in cycles Processor.Delay( (int)m_spiCfg->ChipSelectHoldCycles ); m_altCsPin.Write(m_spiCfg->ActiveLow == 1 ? 1 : 0); } } } } ================================================ FILE: Zelig/Zelig/RunTime/DeviceModels/CortexM0OnMBED/HardwareModel/Drivers/StandardSerialPort.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // namespace Microsoft.CortexM0OnMBED.HardwareModel { using System; using System.Threading; using RT = Zelig.Runtime; using TS = Zelig.Runtime.TypeSystem; using LLIO = Zelig.LlilumOSAbstraction.API.IO; using LLOS = Zelig.LlilumOSAbstraction; public class StandardSerialPort : RT.BaseSerialStream { // // State // private int m_stat_OverrunErrors; private AutoResetEvent m_evtTx; private unsafe LLIO.SerialPortContext* m_serial; private unsafe LLIO.SerialPortConfiguration* m_serialCfg; private bool m_disposed; private bool m_shutdown; // // Constructor Methods // internal StandardSerialPort(ref Configuration cfg //, //StandardUART.Id portNo , /*int irq */) : base(ref cfg) { m_disposed = false; m_shutdown = false; // Get pins from Board config int txPin; int rxPin; int ctsPin; int rtsPin; if (!HardwareProvider.Instance.GetSerialPinsFromPortName(cfg.PortName, out txPin, out rxPin, out rtsPin, out ctsPin)) { throw new ArgumentException(); } if (!HardwareProvider.Instance.TryReservePins(txPin, rxPin, ctsPin, rtsPin)) { throw new ArgumentException(); } try { // Set pins onto BaseSerialStream Configuration m_cfg.TxPin = txPin; m_cfg.RxPin = rxPin; m_cfg.CtsPin = ctsPin; m_cfg.RtsPin = rtsPin; int invalidPin = HardwareProvider.Instance.InvalidPin; if (invalidPin != rtsPin) { m_cfg.RtsEnable = true; m_cfg.Handshake = System.IO.Ports.Handshake.RequestToSend; } if (invalidPin != ctsPin) { m_cfg.CtsEnable = true; m_cfg.Handshake = System.IO.Ports.Handshake.RequestToSend; } m_evtTx = new AutoResetEvent(false); } catch { HardwareProvider.Instance.ReleasePins(txPin, rxPin, ctsPin, rtsPin); throw; } } // // Helper Methods // internal unsafe void Open() { fixed (LLIO.SerialPortContext** ppSerial = &m_serial) fixed( LLIO.SerialPortConfiguration** ppCfg = &m_serialCfg) { LLOS.LlilumErrors.ThrowOnError( LLIO.SerialPort.LLOS_SERIAL_Open(m_cfg.RxPin, m_cfg.TxPin, ppCfg, ppSerial), true ); } m_serialCfg->BaudRate = (uint)m_cfg.BaudRate; m_serialCfg->DataBits = (uint)m_cfg.DataBits; m_serialCfg->Parity = (LLIO.SerialPortParity)m_cfg.Parity; m_serialCfg->StopBits = (LLIO.SerialPortStopBits)m_cfg.StopBits; LLIO.SerialPort.LLOS_SERIAL_Configure( m_serial, m_serialCfg ); if (m_cfg.RtsEnable || m_cfg.CtsEnable) { // Splitting Rts/Cts into separate modes is mBed specific int pinRts = -1; int pinCts = -1; if (m_cfg.RtsEnable) { pinRts = m_cfg.RtsPin; } if (m_cfg.CtsEnable) { pinCts = m_cfg.CtsPin; } LLIO.SerialPort.LLOS_SERIAL_SetFlowControl(m_serial, pinRts, pinCts ); } LLIO.SerialPort.LLOS_SERIAL_SetCallback( m_serial, HandleSerialPortInterrupt, ((RT.ObjectImpl)(object)this).ToPointer() ); LLIO.SerialPort.LLOS_SERIAL_Enable( m_serial, LLIO.SerialPortIrq.IrqRx ); LLIO.SerialPort.LLOS_SERIAL_Disable( m_serial, LLIO.SerialPortIrq.IrqTx ); } public override void Close() { Dispose(true); GC.SuppressFinalize(this); } //--// protected override void Dispose(bool disposing) { if (!m_disposed) { m_shutdown = true; // signal write thread to exit m_evtTx.Set(); // // Send a dummy character in case the write thread is waiting on the transmit queue. // using (RT.SmartHandles.InterruptState.Disable()) { m_transmitQueue.EnqueueNonblocking(0); } unsafe { LLIO.SerialPort.LLOS_SERIAL_Disable( m_serial, LLIO.SerialPortIrq.IrqBoth ); } if (disposing) { HardwareProvider.Instance.ReleasePins(m_cfg.TxPin, m_cfg.RxPin, m_cfg.CtsPin, m_cfg.RtsPin); } unsafe { LLIO.SerialPort.LLOS_SERIAL_Close(m_serial); } m_disposed = true; } base.Dispose(disposing); } ~StandardSerialPort() { Dispose(false); } //--// public override int ReadByte(int timeout) { SignalRead(); return base.ReadByte(timeout); } public override int Read(byte[] array, int offset, int count, int timeout) { SignalRead(); return m_receiveQueue.DequeueMultipleBlocking(ref array, offset, count, timeout); } public override void WriteByte(byte value, int timeout) { WriteToTx(value, timeout); } public override void Write(byte[] array, int offset, int count, int timeout) { int end = offset + count; if( offset + count > array.Length ) { throw new ArgumentException(); } while (offset < end && !m_shutdown) { WriteToTx(array[offset++], timeout); } } public override void Flush() { // // This implementation of the serial port does not use a write buffer because it would require // a separate write thread. Therefore, the transmit queue from the base class should be empty. // RT.BugCheck.Assert(m_transmitQueue.IsEmpty, RT.BugCheck.StopCode.IllegalConfiguration); } // // Access Methods // public override int BaudRate { set { m_cfg.BaudRate = value; unsafe { m_serialCfg->BaudRate = (uint)value; LLIO.SerialPort.LLOS_SERIAL_Configure(m_serial, m_serialCfg); } } } public override int BytesToRead { get { return base.BytesToRead; } } public override int DataBits { set { unsafe { m_cfg.DataBits = value; m_serialCfg->DataBits = (uint)value; LLIO.SerialPort.LLOS_SERIAL_Configure(m_serial, m_serialCfg); } } } public override System.IO.Ports.Parity Parity { set { unsafe { m_cfg.Parity = value; m_serialCfg->Parity = (LLIO.SerialPortParity)value; LLIO.SerialPort.LLOS_SERIAL_Configure(m_serial, m_serialCfg); } } } public override System.IO.Ports.StopBits StopBits { set { unsafe { m_cfg.StopBits = value; m_serialCfg->StopBits = (LLIO.SerialPortStopBits)value; LLIO.SerialPort.LLOS_SERIAL_Configure(m_serial, m_serialCfg); } } } public int OverrunErrors { get { return m_stat_OverrunErrors; } } public unsafe override bool IsOpen { get { return m_serial != null; } } // // Helper functions // private unsafe void WriteToTx(byte val, int timeout) { while (!m_shutdown) { uint isWritable = 1; using (RT.SmartHandles.InterruptState.Disable()) { LLIO.SerialPort.LLOS_SERIAL_CanWrite( m_serial, &isWritable ); if (isWritable != 0) { LLIO.SerialPort.LLOS_SERIAL_Write(m_serial, &val, 0, 1); break; } else { // // Enable TX interrupt to wake us up from m_evtTx.WaitOne() below. // LLIO.SerialPort.LLOS_SERIAL_Enable(m_serial, LLIO.SerialPortIrq.IrqTx); } } if (isWritable != 0) { if (!m_evtTx.WaitOne(timeout, false)) { if (timeout == 0) { break; } else { throw new TimeoutException(); } } } } } // // This function kick starts the read if the read buffer was previously filled // while there was still data in the hardware buffer. If this is not done, we // could potentially be leaving data in the hardware and not receiving an RX // interrupt. // private void SignalRead() { if (m_receiveQueue.IsEmpty) { using (RT.SmartHandles.InterruptState.Disable()) { ReadData(); } } } private unsafe void ReadData() { RT.BugCheck.AssertInterruptsOff(); while (true) { uint canRead = 1; LLIO.SerialPort.LLOS_SERIAL_CanRead( m_serial, &canRead ); if ((canRead == 0) || m_receiveQueue.IsFull) { break; } else { byte c; int length = 1; LLOS.LlilumErrors.ThrowOnError( LLIO.SerialPort.LLOS_SERIAL_Read( m_serial, &c, 0, &length), true ); if (!m_receiveQueue.EnqueueNonblocking(c)) { m_stat_OverrunErrors++; break; } } } } [TS.GenerateUnsafeCast()] private extern static StandardSerialPort CastAsSerialPort(UIntPtr ptr); private static unsafe void HandleSerialPortInterrupt(LLIO.SerialPortContext* port, UIntPtr callbackCtx, LLIO.SerialPortEvent serialEvent) { StandardSerialPort sp = CastAsSerialPort(callbackCtx); using (RT.SmartHandles.InterruptState.Disable()) { if (serialEvent == LLIO.SerialPortEvent.Rx) { sp.ReadData(); } else { // // Disable TX interrupts so that we can process the TX // buffer without being interrupted by TX events. // unsafe { LLIO.SerialPort.LLOS_SERIAL_Disable(sp.m_serial, LLIO.SerialPortIrq.IrqTx); } sp.m_evtTx.Set(); } } } } } ================================================ FILE: Zelig/Zelig/RunTime/DeviceModels/CortexM0OnMBED/HardwareModel/Drivers/SystemTimer.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // namespace Microsoft.CortexM0OnMBED.Drivers { using System; using System.Runtime.CompilerServices; using RT = Microsoft.Zelig.Runtime; using LLOS = Zelig.LlilumOSAbstraction; using ChipsetModel = Microsoft.DeviceModels.Chipset.CortexM; /// /// This class implements the internal system timer. All times are in ticks (time agnostic) /// however in practice, and due to limitations of mbed 1 tick is equal to 1 uS (micro second) /// public abstract class SystemTimer { public delegate void Callback(Timer timer, ulong currentTime); public class Timer { // // State // private readonly Callback m_callback; private readonly RT.KernelNode m_node; private readonly SystemTimer m_owner; private ulong m_timeout; // // Constructor Methods // internal Timer(SystemTimer owner, Callback callback) { m_owner = owner; m_node = new RT.KernelNode(this); m_callback = callback; } // // Helper Methods // public void Cancel() { m_owner.Deregister(this); } /// /// Call to the Timer handler /// /// Time in ticks internal void Invoke(ulong currentTime) { m_callback(this, currentTime); } // // Access Methods // internal RT.KernelNode Node { get { return m_node; } } /// /// Set/get the timeout in absolute time /// public ulong Timeout { get { return m_timeout; } set { m_timeout = value; m_owner.Register(this); } } /// /// Set/get the timeout in relation to current time /// public ulong RelativeTimeout { get { return m_timeout - m_owner.CurrentTime; } set { m_timeout = value + m_owner.CurrentTime; m_owner.Register(this); } } } //--// // // System Timer Implementation // public const uint c_MaxCounterValue = uint.MaxValue; public const uint c_HalfCycle = c_MaxCounterValue >> 1; public const uint c_QuarterCycle = c_MaxCounterValue >> 2; public const uint c_ThreeQuarterCycle = c_HalfCycle + c_QuarterCycle; //--// private RT.KernelList m_timers; private InterruptController.Handler m_interrupthandler; private ulong m_accumulator; private uint m_lastAccumulatorUpdate; // This is only used as a placeholder to pass into timer_insert_event private unsafe LLOS.HAL.TimerContext* m_timerEvent; //--// //private static Timer s_guard; public void Initialize() { m_timers = new RT.KernelList(); m_interrupthandler = InterruptController.Handler.Create( Board.Instance.GetSystemTimerIRQ( ) , ChipsetModel.Drivers.InterruptPriority.BelowNormal, ChipsetModel.Drivers.InterruptSettings.Normal , ProcessTimerInterrupt ); m_accumulator = 0; m_lastAccumulatorUpdate = this.Counter; // Allocate our one, and only, timer event unsafe { fixed (LLOS.HAL.TimerContext** timer_ptr = &m_timerEvent) { var callbackContext = InterruptController.CastInterruptHandlerAsPtr( m_interrupthandler ); LLOS.HAL.Timer.LLOS_SYSTEM_TIMER_AllocateTimer( HandleSystemTimerNative, callbackContext, ulong.MaxValue, timer_ptr ); } } ChipsetModel.NVIC.SetPriority( ChipsetModel.Board.Instance.GetSystemTimerIRQ(), RT.TargetPlatform.ARMv6.ProcessorARMv6M.c_Priority__SystemTimer ); // // Set up a guard to never suffer from shutting down the underlying circuitry // //s_guard = CreateTimer( (timer, currentTime) => { timer.RelativeTimeout = QuarterCycle; } ); //s_guard.RelativeTimeout = QuarterCycle; InterruptController.Instance.RegisterAndEnable( m_interrupthandler ); // no need to Refresh because guard causes a refresh already Refresh(); } /// /// Create a new Timer and return to the user /// /// Handler to run on timer expiration /// New Timer instance public Timer CreateTimer(Callback callback) { return new Timer(this, callback); } /// /// Gets the current accumulator time /// public ulong CurrentTime { get { using (RT.SmartHandles.InterruptState.Disable()) { // Current time is the accumulator + time since it was updated return m_accumulator + TimeSinceAccumulatorUpdate( this.Counter ); } } } /// /// Gets the current value of the timer accumulator /// public unsafe uint Counter { [RT.Inline] get { return (uint)LLOS.HAL.Timer.LLOS_SYSTEM_TIMER_GetTicks( m_timerEvent ); } } /// /// Protected constructor to ensure only we can create this /// protected SystemTimer() { } public static extern SystemTimer Instance { [RT.SingletonFactory()] [MethodImpl(MethodImplOptions.InternalCall)] get; } //--// /// /// Handle the timer expiration interrupt /// /// Time when the timer was fired internal void ProcessTimeout(ulong ticks) { // Ensure that lastAccumulatorUpdate is always updated with the accumulator! uint counter = this.Counter; // // BUGBUG: this logic does not cover the case of multiple wraparounds // m_accumulator += TimeSinceAccumulatorUpdate(counter); m_lastAccumulatorUpdate = counter; // we just updated this above, so it will be precise ulong now = m_accumulator; while (true) { RT.KernelNode node = m_timers.StartOfForwardWalk; // If the next node is null, break and call Refresh if (node.IsValidForForwardMove == false) { break; } ulong timeout = node.Target.Timeout; if (timeout > now) { // If we get here, there are no timers that need to be cleared/invoked break; } // The current timeout is for the current node (Timer). Remove from List // so we do not try to Reload its time. node.RemoveFromList(); // Invoke the handler for the expired timer node.Target.Invoke(now); } Refresh(); } /// /// Reload the next expiring timer, if there is one. Otherwise, reload QuarterCycle /// private void Refresh() { ulong absTimeout; Timer target = m_timers.FirstTarget(); ulong now = this.CurrentTime; if(target != null) { absTimeout = target.Timeout; } else { absTimeout = c_QuarterCycle + now; } // // Timeout in the past? Trigger the match immediately by loading 1 // Timeout too far in the future? Generate match for // a fraction of largest counter value, so we have time to handle wraparounds // Reload((now > absTimeout) ? 1 : (absTimeout - now)); } /// /// Place the timer closest to expiration on the mbed queue /// /// private void Reload(ulong remainder) { // trim to quarter cycle, so we have time to handle wraparounds // This is guaranteed to fit in a uint uint trimmed = (uint)Math.Min(remainder, c_QuarterCycle); unsafe { LLOS.HAL.Timer.LLOS_SYSTEM_TIMER_ScheduleTimer( m_timerEvent, trimmed ); } } // // Timer registration // /// /// Add the timer to the queue in the chronologically appropriate position /// /// Timer to add private void Register(Timer timer) { RT.KernelNode node = timer.Node; node.RemoveFromList(); ulong timeout = timer.Timeout; RT.KernelNode node2 = m_timers.StartOfForwardWalk; while (node2.IsValidForForwardMove) { if (node2.Target.Timeout > timeout) { break; } node2 = node2.Next; } node.InsertBefore(node2); Refresh(); } /// /// Remove the timer from the queue /// /// Timer to be removed private void Deregister(Timer timer) { var node = timer.Node; if (node.IsLinked) { node.RemoveFromList(); Refresh(); } } /// /// Gets the difference in ticks between when the accumulator, and its last recorded value /// /// Difference in ticks private uint TimeSinceAccumulatorUpdate( uint current ) { // If the current timer value is greater than last accumulator update, // the counter is still going up. Otherwise, the timer hit its max value // and started counting from 0 return (current >= m_lastAccumulatorUpdate) ? current - m_lastAccumulatorUpdate : c_MaxCounterValue - m_lastAccumulatorUpdate + current; } //--// private static void HandleSystemTimerNative( UIntPtr context, ulong ticks ) { ChipsetModel.Drivers.InterruptController.InterruptData data; data.Context = ticks; data.Handler = InterruptController.CastAsInterruptHandler( context ); // // This interrupt handler does not come from the ISR vector table, but rather from 'us_ticker_irq_handler' // being lazily set through 'NVIC_SetVector( , (uint32_t)us_ticker_irq_handler)' during initialization. // Therefore we need to wrap this specific handler here, which is where it first shows up. // using(RT.SmartHandles.InterruptState.Disable( )) { using(RT.SmartHandles.SwapCurrentThreadUnderInterrupt hnd = RT.ThreadManager.InstallInterruptThread( )) { InterruptController.Instance.PostInterrupt( data ); } } } private void ProcessTimerInterrupt( ChipsetModel.Drivers.InterruptController.InterruptData data ) { using(RT.SmartHandles.InterruptState.Disable()) { SystemTimer.Instance.ProcessTimeout( data.Context ); } } } } ================================================ FILE: Zelig/Zelig/RunTime/DeviceModels/CortexM0OnMBED/HardwareModel/HardwareProvider.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // namespace Microsoft.CortexM0OnMBED.HardwareModel { using GPIO_FRAMEWORK = Windows.Devices.Gpio.Provider; using ChipsetAbstration = Microsoft.DeviceModels.Chipset.CortexM0; using ChipsetModel = Microsoft.CortexM0OnCMSISCore; public class HardwareProvider : ChipsetModel.HardwareProvider { // // Gpio Discovery // public override int PinCount => Board.Instance.PinCount; public override int PinToIndex(int pin) { return Board.Instance.PinToIndex(pin); } public override int InvalidPin { get { return Board.Instance.NCPin; } } // // Serial Discovery // public override string[] GetSerialPorts() { return Board.Instance.GetSerialPorts(); } public override bool GetSerialPinsFromPortName(string portName, out int txPin, out int rxPin, out int rtsPin, out int ctsPin) { ChipsetAbstration.Board.SerialPortInfo portInfo = Board.Instance.GetSerialPortInfo(portName); if (portInfo == null) { int invalidPin = this.InvalidPin; txPin = invalidPin; rxPin = invalidPin; ctsPin = invalidPin; rtsPin = invalidPin; return false; } txPin = portInfo.TxPin; rxPin = portInfo.RxPin; ctsPin = portInfo.CtsPin; rtsPin = portInfo.RtsPin; return true; } } } ================================================ FILE: Zelig/Zelig/RunTime/DeviceModels/CortexM0OnMBED/HardwareModel/HardwareProviders/AdcProvider.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // namespace Microsoft.CortexM0OnMBED.HardwareModel { using Framework = Microsoft.Llilum.Devices.Adc; using RT = Microsoft.Zelig.Runtime; public abstract class AdcProvider : RT.AdcProvider { public override Framework.AdcChannel CreateAdcPin(int pinNumber) { if(!RT.HardwareProvider.Instance.TryReservePins(pinNumber)) { return null; } return new AdcChannel(pinNumber); } } } ================================================ FILE: Zelig/Zelig/RunTime/DeviceModels/CortexM0OnMBED/HardwareModel/HardwareProviders/GpioProvider.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // namespace Microsoft.CortexM0OnMBED.HardwareModel { using Framework = Microsoft.Llilum.Devices.Gpio; using RT = Microsoft.Zelig.Runtime; public abstract class GpioProvider : RT.GpioProvider { public override Framework.GpioPin CreateGpioPin(int pinNumber) { if (!RT.HardwareProvider.Instance.TryReservePins(pinNumber)) { return null; } return new GpioPin(pinNumber); } } } ================================================ FILE: Zelig/Zelig/RunTime/DeviceModels/CortexM0OnMBED/HardwareModel/HardwareProviders/I2cProvider.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // namespace Microsoft.CortexM0OnMBED.HardwareModel { using Framework = Microsoft.Llilum.Devices.I2c; using RT = Microsoft.Zelig.Runtime; public abstract class I2cProvider : RT.I2cProvider { public override Framework.I2cChannel CreateI2cChannel(Framework.II2cChannelInfo channelInfo) { if(!RT.HardwareProvider.Instance.TryReservePins(channelInfo.SclPin, channelInfo.SdaPin)) { return null; } return new I2cChannel(channelInfo); } } } ================================================ FILE: Zelig/Zelig/RunTime/DeviceModels/CortexM0OnMBED/HardwareModel/HardwareProviders/PwmProvider.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // namespace Microsoft.CortexM0OnMBED.HardwareModel { using Framework = Microsoft.Llilum.Devices.Pwm; using Runtime = Microsoft.Zelig.Runtime; public abstract class PwmProvider : Runtime.PwmProvider { public sealed override Framework.PwmChannel TryCreatePwmPin(int pinNumber) { if (!Runtime.HardwareProvider.Instance.TryReservePins(pinNumber)) { return null; } return new PwmChannel(pinNumber); } } } ================================================ FILE: Zelig/Zelig/RunTime/DeviceModels/CortexM0OnMBED/HardwareModel/HardwareProviders/SocketProvider.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // namespace Microsoft.CortexM0OnMBED.HardwareModel { using System; using Zelig.LlilumOSAbstraction.API.IO; using System.Text; using RT = Microsoft.Zelig.Runtime; public abstract class SocketProvider : RT.SocketProvider { // // Socket protocol types (TCP/UDP/RAW) // private const int SOCK_STREAM = 1; private const int SOCK_DGRAM = 2; private const int SOCK_RAW = 3; // // Option flags per-socket. These must match the SOF_ flags in ip.h (checked in init.c) // private const int SO_DEBUG = 0x0001; // Unimplemented: turn on debugging info recording private const int SO_ACCEPTCONN = 0x0002; // socket has had listen() private const int SO_REUSEADDR = 0x0004; // Allow local address reuse private const int SO_KEEPALIVE = 0x0008; // keep connections alive private const int SO_DONTROUTE = 0x0010; // Unimplemented: just use interface addresses private const int SO_BROADCAST = 0x0020; // permit to send and to receive broadcast messages (see IP_SOF_BROADCAST option) private const int SO_USELOOPBACK = 0x0040; // Unimplemented: bypass hardware when possible private const int SO_LINGER = 0x0080; // linger on close if data present private const int SO_OOBINLINE = 0x0100; // Unimplemented: leave received OOB data in line private const int SO_REUSEPORT = 0x0200; // Unimplemented: allow local address & port reuse private const int SO_DONTLINGER = ((int)(~SO_LINGER)); // // Additional options, not kept in so_options. // private const int SO_SNDBUF = 0x1001; // Unimplemented: send buffer size private const int SO_RCVBUF = 0x1002; // receive buffer size private const int SO_SNDLOWAT = 0x1003; // Unimplemented: send low-water mark private const int SO_RCVLOWAT = 0x1004; // Unimplemented: receive low-water mark private const int SO_SNDTIMEO = 0x1005; // Unimplemented: send timeout private const int SO_RCVTIMEO = 0x1006; // receive timeout private const int SO_ERROR = 0x1007; // get error status and clear private const int SO_TYPE = 0x1008; // get socket type private const int SO_CONTIMEO = 0x1009; // Unimplemented: connect timeout private const int SO_NO_CHECK = 0x100a; // don't create UDP checksum // // Level number for (get/set)sockopt() to apply to socket itself. // private const int SOL_SOCKET = 0xfff; // options for socket level private const int AF_UNSPEC = 0; private const int AF_INET = 2; private const int PF_INET = AF_INET; private const int PF_UNSPEC = AF_UNSPEC; private const int IPPROTO_IP = 0; private const int IPPROTO_TCP = 6; private const int IPPROTO_UDP = 17; private const int IPPROTO_UDPLITE = 136; // // Options for level IPPROTO_IP // private const int IP_TOS = 1; private const int IP_TTL = 2; // // Options for level IPPROTO_TCP // private const int TCP_NODELAY = 0x01; // don't delay send to coalesce packets private const int TCP_KEEPALIVE = 0x02; // send KEEPALIVE probes when idle for pcb->keep_idle milliseconds private const int TCP_KEEPIDLE = 0x03; // set pcb->keep_idle - Same as TCP_KEEPALIVE, but use seconds for get/setsockopt private const int TCP_KEEPINTVL = 0x04; // set pcb->keep_intvl - Use seconds for get/setsockopt private const int TCP_KEEPCNT = 0x05; // set pcb->keep_cnt - Use number of probes sent for get/setsockopt // // Options for level IPPROTO_UDPLITE // private const int UDPLITE_SEND_CSCOV = 0x01; // sender checksum coverage private const int UDPLITE_RECV_CSCOV = 0x02; // minimal receiver checksum coverage // // Options and types for UDP multicast traffic handling // private const int IP_ADD_MEMBERSHIP = 3; private const int IP_DROP_MEMBERSHIP = 4; private const int IP_MULTICAST_TTL = 5; private const int IP_MULTICAST_IF = 6; private const int IP_MULTICAST_LOOP = 7; //--// //--// //--// private const int SOCK_SOCK_STREAM = 1; private const int SOCK_SOCK_DGRAM = 2; private const int SOCK_SOCK_RAW = 3; private const int SOCK_SOCK_RDM = 4; private const int SOCK_SOCK_SEQPACKET = 5; private const int SOCK_SOCK_PACK_EX = 6; private const int SOCK_TCP_NODELAY = 0x0001; private const int SOCK_IPPROTO_IP = 0; private const int SOCK_IPPROTO_ICMP = 1; private const int SOCK_IPPROTO_IGMP = 2; private const int SOCK_IPPROTO_IPV4 = 4; // IP-in-IP encapsulation private const int SOCK_IPPROTO_TCP = 6; private const int SOCK_IPPROTO_PUP = 12; private const int SOCK_IPPROTO_UDP = 17; private const int SOCK_IPPROTO_IDP = 22; private const int SOCK_IPPROTO_IPV6 = 41; private const int SOCK_IPPROTO_IPv6RoutingHeader = 43; private const int SOCK_IPPROTO_IPv6FragmentHeader = 44; private const int SOCK_IPPROTO_RDP = 46; private const int SOCK_IPPROTO_GRE = 47; private const int SOCK_IPPROTO_IPSecEncapsulatingSecurityPayload = 50; private const int SOCK_IPPROTO_IPSecAuthenticationHeader = 51; private const int SOCK_IPPROTO_IcmpV6 = 58; private const int SOCK_IPPROTO_IPv6NoNextHeader = 59; private const int SOCK_IPPROTO_IPv6DestinationOptions = 60; private const int SOCK_IPPROTO_ND = 77; private const int SOCK_IPPROTO_OSPF = 89; private const int SOCK_IPPROTO_TPACKET = 127; private const int SOCK_IPPROTO_RAW = 255; private const int SOCK_IPPROTO_IPX = 1000; private const int SOCK_IPPROTO_SPX = 1256; private const int SOCK_IPPROTO_SPXII = 1257; private const int SOCK_SOL_SOCKET = 0xFFFF; // // Option flags per-socket // private const int SOCK_SOCKO_DEBUG = 0x0001; // turn on debugging info recording private const int SOCK_SOCKO_NOCHECKSUM = 0x0001; private const int SOCK_SOCKO_ACCEPTCONNECTION = 0x0002; // socket has had listen() private const int SOCK_SOCKO_REUSEADDRESS = 0x0004; // allow local address reuse private const int SOCK_SOCKO_KEEPALIVE = 0x0008; // keep connections alive private const int SOCK_SOCKO_DONTROUTE = 0x0010; // just use interface addresses private const int SOCK_SOCKO_BROADCAST = 0x0020; // permit sending of broadcast msgs private const int SOCK_SOCKO_USELOOPBACK = 0x0040; // bypass hardware when possible private const int SOCK_SOCKO_LINGER = 0x0080; // linger on close if data present private const int SOCK_SOCKO_OUTOFBANDINLINE = 0x0100; // leave received OOB data in line private const int SOCK_SOCKO_DONTLINGER = ~SOCK_SOCKO_LINGER; private const int SOCK_SOCKO_EXCLUSIVEADDRESSUSE = ~SOCK_SOCKO_REUSEADDRESS; // disallow local address reuse private const int SOCK_SOCKO_SENDBUFFER = 0x1001; // send buffer size private const int SOCK_SOCKO_SNDBUF = SOCK_SOCKO_SENDBUFFER; private const int SOCK_SOCKO_RECEIVEBUFFER = 0x1002; // receive buffer size private const int SOCK_SOCKO_RCVBUF = SOCK_SOCKO_RECEIVEBUFFER; private const int SOCK_SOCKO_SENDLOWWATER = 0x1003; // send low-water mark private const int SOCK_SOCKO_RECEIVELOWWATER = 0x1004; // receive low-water mark private const int SOCK_SOCKO_SENDTIMEOUT = 0x1005; // send timeout private const int SOCK_SOCKO_RECEIVETIMEOUT = 0x1006; // receive timeout private const int SOCK_SOCKO_ERROR = 0x1007; // get error status and clear private const int SOCK_SOCKO_TYPE = 0x1008; // get socket type private const int SOCK_SOCKO_UPDATE_ACCEPT_CTX = 0x700B; // This option updates the properties of the socket which are inherited from the listening socket. private const int SOCK_SOCKO_UPDATE_CONNECT_CTX = 0x7010; // This option updates the properties of the socket after the connection is established. private const int SOCK_SOCKO_MAXCONNECTIONS = 0x7FFFFFFF; // Maximum queue length specifiable by listen. // // Option flags per-IP // private const int SOCK_IPO_OPTIONS = 0x0001; private const int SOCK_IPO_HDRINCL = 0x0002; private const int SOCK_IPO_TOS = 0x0003; private const int SOCK_IPO_TTL = 0x0004; private const int SOCK_IPO_MULTICAST_IF = 0x0009; private const int SOCK_IPO_MULTICAST_TTL = 0x000A; private const int SOCK_IPO_MULTICAST_LOOP = 0x000B; private const int SOCK_IPO_ADD_MEMBERSHIP = 0x000C; private const int SOCK_IPO_DROP_MEMBERSHIP = 0x000D; private const int SOCK_IPO_IP_DONTFRAGMENT = 0x000E; private const int SOCK_IPO_ADD_SOURCE_MEMBERSHIP = 0x000F; private const int SOCK_IPO_DROP_SOURCE_MEMBERSHIP = 0x0010; private const int SOCK_IPO_BLOCK_SOURCE = 0x0011; private const int SOCK_IPO_UBLOCK_SOURCE = 0x0012; private const int SOCK_IPO_PACKET_INFO = 0x0013; private const int SOCK_SOCKET_ERROR = -1; //--// //--// //--// public override int socket(int family, int type, int protocol) { return SocketNative.LLOS_lwip_socket(family, type, protocol); } public override int bind(int socket, byte[] address) { return SocketNative.LLOS_lwip_bind(socket, address); } public unsafe override int connect(int socket, byte[] address, bool fThrowOnWouldBlock) { fixed (byte* addressPtr = address) { return SocketNative.LLOS_lwip_connect(socket, addressPtr, fThrowOnWouldBlock); } } public unsafe override int send(int socket, byte[] buf, int offset, int count, int flags, int timeout_ms) { fixed (byte* buffer = &buf[offset]) { return SocketNative.LLOS_lwip_send(socket, buffer, count, flags, timeout_ms); } } public unsafe override int recv(int socket, byte[] buf, int offset, int count, int flags, int timeout_ms) { fixed (byte* buffer = &buf[offset]) { return SocketNative.LLOS_lwip_recv(socket, buffer, count, flags, timeout_ms); } } public override int close(int socket) { return SocketNative.LLOS_lwip_close(socket); } public override int listen(int socket, int backlog) { return SocketNative.LLOS_lwip_listen(socket, backlog); } public unsafe override int accept(int socket) { byte[] address = new byte[20]; uint* pAddrlen = null; fixed(byte* pAddress = address) { return SocketNative.LLOS_lwip_accept(socket, pAddress, pAddrlen); } } // // No standard non-blocking api // public unsafe override int getaddrinfo(string name, out string canonicalName, out byte[][] addresses) { byte[] canonicalNameArr = new byte[256]; // We know this will be the size of the address object byte[] addressArr = new byte[16]; int result; fixed (char* pName = name.ToCharArray()) { fixed (byte* pCanonicalName = canonicalNameArr) { fixed (byte* pAddress = addressArr) { result = SocketNative.LLOS_lwip_getaddrinfo(pName, (uint)name.Length, pCanonicalName, (uint)canonicalNameArr.Length, pAddress, (uint)addressArr.Length); } } } if(result < 0) { // The format of address in addressArr may not be what DNS wants. Need to verify canonicalName = null; addresses = null; addresses[0] = null; return result; } // The format of address in addressArr may not be what DNS wants. Need to verify canonicalName = ASCIIEncoding.ASCII.GetString(canonicalNameArr); addresses = new byte[1][]; addresses[0] = addressArr; return result; } public unsafe override void shutdown(int socket, int how, out int err) { err = SocketNative.LLOS_lwip_shutdown(socket, how); } public unsafe override int sendto(int socket, byte[] buf, int offset, int count, int flags, int timeout_ms, byte[] address) { fixed(byte* pBuf = &buf[offset]) { fixed(byte* pAddress = address) { return SocketNative.LLOS_lwip_sendto(socket, pBuf, count, flags, timeout_ms, pAddress, (uint)address.Length); } } } public unsafe override int recvfrom(int socket, byte[] buf, int offset, int count, int flags, int timeout_ms, ref byte[] address) { uint fromlen = (uint)address.Length; fixed (byte* pBuf = &buf[offset]) { fixed (byte* pAddress = address) { return SocketNative.LLOS_lwip_recvfrom(socket, pBuf, count, flags, timeout_ms, pAddress, &fromlen); } } } public unsafe override int getpeername(int socket, out byte[] address) { uint namelen = 20; byte[] addressBuffer = new byte[namelen]; int result; fixed(byte* pAddress = addressBuffer) { result = SocketNative.LLOS_lwip_getpeername(socket, pAddress, &namelen); } if(result < 0) { address = null; return result; } address = new byte[namelen]; Array.Copy(addressBuffer, address, (int)namelen); return result; } public unsafe override int getsockname(int socket, out byte[] address) { uint namelen = 20; byte[] addressBuffer = new byte[namelen]; int result; fixed (byte* pAddress = addressBuffer) { result = SocketNative.LLOS_lwip_getsockname(socket, pAddress, &namelen); } if (result < 0) { address = null; return result; } address = new byte[namelen]; Array.Copy(addressBuffer, address, (int)namelen); return result; } public unsafe override int getsockopt(int socket, int level, int optname, byte[] optval, out uint optlen) { int nativeOptionName; int nativeLevel; switch(level) { case SOCK_IPPROTO_IP: nativeLevel = IPPROTO_IP; nativeOptionName = GetNativeIPOption(optname); break; case SOCK_IPPROTO_TCP: nativeLevel = IPPROTO_TCP; nativeOptionName = GetNativeTcpOption(optname); break; case SOCK_IPPROTO_UDP: case SOCK_IPPROTO_ICMP: case SOCK_IPPROTO_IGMP: case SOCK_IPPROTO_IPV4: case SOCK_SOL_SOCKET: nativeLevel = SOL_SOCKET; nativeOptionName = GetNativeSockOption(optname); switch(optname) { // LINGER is not implemented in LWIP case SOCK_SOCKO_LINGER: optval[0] = 0; optlen = 1; return 0; case SOCK_SOCKO_DONTLINGER: optval[0] = 1; optlen = 1; return 0; default: break; } break; default: nativeLevel = level; nativeOptionName = optname; break; } uint optlenInternal = (uint)optval.Length; int result; fixed (byte* pNativeOptval = optval) { result = SocketNative.LLOS_lwip_getsockopt( socket, nativeLevel, nativeOptionName, pNativeOptval, &optlenInternal ); optlen = optlenInternal; if(result == 0) { switch(level) { case SOCK_SOL_SOCKET: switch(optname) { case SOCK_SOCKO_EXCLUSIVEADDRESSUSE: optval[0] = (!( *(int*)pNativeOptval != 0 ) == true) ? (byte)1 : (byte)0; optlen = 1; break; case SOCK_SOCKO_ACCEPTCONNECTION: case SOCK_SOCKO_BROADCAST: case SOCK_SOCKO_KEEPALIVE: optval[0] = (( *(int*)pNativeOptval != 0 ) == true ) ? (byte)1 : (byte)0; optlen = 1; break; } break; } } } return result; } public unsafe override int setsockopt( int socket, int level, int optname, byte[] optval ) { int nativeLevel; int nativeOptionName; int nativeIntValue; fixed (byte* pNativeOptionValue = optval) { switch(level) { case SOCK_IPPROTO_IP: nativeLevel = IPPROTO_IP; nativeOptionName = GetNativeIPOption( optname ); break; case SOCK_IPPROTO_TCP: nativeLevel = IPPROTO_TCP; nativeOptionName = GetNativeTcpOption( optname ); break; case SOCK_IPPROTO_UDP: case SOCK_IPPROTO_ICMP: case SOCK_IPPROTO_IGMP: case SOCK_IPPROTO_IPV4: case SOCK_SOL_SOCKET: nativeLevel = SOL_SOCKET; nativeOptionName = GetNativeSockOption( optname ); switch(optname) { // LINGER is not implemented in LWIP case SOCK_SOCKO_LINGER: if(*(int*)pNativeOptionValue != 0) { //errno = SOCK_ENOPROTOOPT; return SOCK_SOCKET_ERROR; } return 0; case SOCK_SOCKO_DONTLINGER: if(*(int*)pNativeOptionValue == 0) { //errno = SOCK_ENOPROTOOPT; return SOCK_SOCKET_ERROR; } return 0; // ignore this item to enable http to work case SOCK_SOCKO_REUSEADDRESS: return 0; case SOCK_SOCKO_EXCLUSIVEADDRESSUSE: nativeIntValue = *(int*)&pNativeOptionValue[0] == 0 ? 1 : 0; optval[ 0 ] = (byte)nativeIntValue; //pNativeOptionValue = (char*)&nativeIntValue; break; default: break; } break; default: nativeLevel = 0; nativeOptionName = 0; break; } return SocketNative.LLOS_lwip_setsockopt( socket, nativeLevel, nativeOptionName, pNativeOptionValue, (uint)optval.Length ); } } public unsafe override bool poll(int socket, int mode, int microSeconds) { return SocketNative.LLOS_lwip_poll(socket, mode, microSeconds); } public unsafe override int ioctl(int socket, uint cmd, ref uint arg) { fixed (uint* pArg = &arg) { return SocketNative.LLOS_lwip_ioctl(socket, cmd, pArg); } } //--// //--// //--// static private int GetNativeTcpOption( int optname ) { int nativeOptionName = 0; switch(optname) { case SOCK_TCP_NODELAY: nativeOptionName = TCP_NODELAY; break; case SOCK_SOCKO_KEEPALIVE: nativeOptionName = TCP_KEEPALIVE; break; // allow the C# user to specify LWIP options that our managed enum // doesn't support default: nativeOptionName = optname; break; } return nativeOptionName; } static private int GetNativeSockOption( int optname ) { int nativeOptionName = 0; switch(optname) { case SOCK_SOCKO_DONTLINGER: case SOCK_SOCKO_LINGER: nativeOptionName = SO_LINGER; break; case SOCK_SOCKO_SENDTIMEOUT: nativeOptionName = SO_SNDTIMEO; break; case SOCK_SOCKO_RECEIVETIMEOUT: nativeOptionName = SO_RCVTIMEO; break; case SOCK_SOCKO_EXCLUSIVEADDRESSUSE: case SOCK_SOCKO_REUSEADDRESS: nativeOptionName = SO_REUSEADDR; break; case SOCK_SOCKO_KEEPALIVE: nativeOptionName = SO_KEEPALIVE; break; case SOCK_SOCKO_ERROR: nativeOptionName = SO_ERROR; break; case SOCK_SOCKO_BROADCAST: nativeOptionName = SO_BROADCAST; break; case SOCK_SOCKO_RECEIVEBUFFER: nativeOptionName = SO_RCVBUF; break; case SOCK_SOCKO_SENDBUFFER: nativeOptionName = SO_SNDBUF; break; case SOCK_SOCKO_ACCEPTCONNECTION: nativeOptionName = SO_ACCEPTCONN; break; case SOCK_SOCKO_TYPE: nativeOptionName = SO_TYPE; break; case SOCK_SOCKO_USELOOPBACK: nativeOptionName = SO_USELOOPBACK; break; case SOCK_SOCKO_DONTROUTE: nativeOptionName = SO_DONTROUTE; break; case SOCK_SOCKO_OUTOFBANDINLINE: nativeOptionName = SO_OOBINLINE; break; case SOCK_SOCKO_DEBUG: nativeOptionName = SO_DEBUG; break; case SOCK_SOCKO_SENDLOWWATER: nativeOptionName = SO_SNDLOWAT; break; case SOCK_SOCKO_RECEIVELOWWATER: nativeOptionName = SO_RCVLOWAT; break; // case SOCK_SOCKO_MAXCONNECTIONS: //don't support case SOCK_SOCKO_UPDATE_ACCEPT_CTX: case SOCK_SOCKO_UPDATE_CONNECT_CTX: nativeOptionName = 0; break; // allow the C# user to specify LWIP options that our managed enum // doesn't support default: nativeOptionName = optname; break; } return nativeOptionName; } static private int GetNativeIPOption( int optname ) { int nativeOptionName = 0; switch(optname) { case SOCK_IPO_TTL: nativeOptionName = IP_TTL; break; case SOCK_IPO_TOS: nativeOptionName = IP_TOS; break; #if LWIP_IGMP case SOCK_IPO_MULTICAST_IF: nativeOptionName = IP_MULTICAST_IF; break; case SOCK_IPO_MULTICAST_TTL: nativeOptionName = IP_MULTICAST_TTL; break; case SOCK_IPO_MULTICAST_LOOP: nativeOptionName = IP_MULTICAST_LOOP; break; case SOCK_IPO_ADD_MEMBERSHIP: nativeOptionName = IP_ADD_MEMBERSHIP; break; case SOCK_IPO_DROP_MEMBERSHIP: nativeOptionName = IP_DROP_MEMBERSHIP; break; #else case SOCK_IPO_MULTICAST_IF: case SOCK_IPO_MULTICAST_TTL: case SOCK_IPO_MULTICAST_LOOP: case SOCK_IPO_ADD_MEMBERSHIP: case SOCK_IPO_DROP_MEMBERSHIP: #endif case SOCK_IPO_ADD_SOURCE_MEMBERSHIP: case SOCK_IPO_DROP_SOURCE_MEMBERSHIP: case SOCK_IPO_OPTIONS: case SOCK_IPO_HDRINCL: case SOCK_IPO_IP_DONTFRAGMENT: case SOCK_IPO_BLOCK_SOURCE: case SOCK_IPO_UBLOCK_SOURCE: case SOCK_IPO_PACKET_INFO: nativeOptionName = 0; break; // allow the C# user to specify LWIP options that our managed enum // doesn't support default: nativeOptionName = optname; break; } return nativeOptionName; } } } ================================================ FILE: Zelig/Zelig/RunTime/DeviceModels/CortexM0OnMBED/HardwareModel/HardwareProviders/SpiProvider.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // namespace Microsoft.CortexM0OnMBED.HardwareModel { using Framework = Microsoft.Llilum.Devices.Spi; using RT = Microsoft.Zelig.Runtime; public abstract class SpiProvider : RT.SpiProvider { public override Framework.SpiChannel CreateSpiChannel(Framework.ISpiChannelInfo channelInfo) { return new SpiChannel(channelInfo); } } } ================================================ FILE: Zelig/Zelig/RunTime/DeviceModels/CortexM0OnMBED/HardwareModel/Memory.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // namespace Microsoft.CortexM0OnMBED { using System; using RT = Microsoft.Zelig.Runtime; using ChipsetModel = Microsoft.CortexM0OnCMSISCore; public class Memory : ChipsetModel.Memory { public override void InitializeMemory( ) { } } } ================================================ FILE: Zelig/Zelig/RunTime/DeviceModels/CortexM0OnMBED/HardwareModel/Peripherals.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // //#define ALLOW_PAUSE namespace Microsoft.CortexM0OnMBED { using RT = Microsoft.Zelig.Runtime; using ChipsetModel = Microsoft.CortexM0OnCMSISCore; public abstract class Peripherals : ChipsetModel.Peripherals { // // State // // // Helper Methods // public override void Activate() { base.Activate( ); Drivers.SystemTimer.Instance.Initialize(); //Drivers.GPIO.Instance.Initialize(); //Drivers.I2C.Instance.Initialize(); //Drivers.SPI.Instance.Initialize(); } [RT.Inline] [RT.DisableNullChecks()] public override uint ReadPerformanceCounter() { return Drivers.SystemTimer.Instance.Counter; } } } ================================================ FILE: Zelig/Zelig/RunTime/DeviceModels/CortexM0OnMBED/HardwareModel/Processor.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // namespace Microsoft.CortexM0OnMBED { using System; using System.Runtime.InteropServices; using RT = Microsoft.Zelig.Runtime; using ChipsetModel = Microsoft.CortexM0OnCMSISCore; using RTOS = Microsoft.Zelig.Support.mbed; public abstract class Processor : ChipsetModel.Processor { //--// // // Access methods // public static ulong CoreClockFrequency { [RT.ConfigurationOption("System__CoreClockFrequency")] get { RT.BugCheck.Assert( false, RT.BugCheck.StopCode.IllegalConfiguration ); return 0; } } public static ulong RealTimeClockFrequency { [RT.ConfigurationOption("System__RealTimeClockFrequency")] get { RT.BugCheck.Assert( false, RT.BugCheck.StopCode.IllegalConfiguration ); return 0; } } public static uint DefaultThreadPoolThreads { [RT.ConfigurationOption( "System__Runtime_DefaultThreadPoolThreads" )] get { RT.BugCheck.Assert( false, RT.BugCheck.StopCode.IllegalConfiguration ); return 2; } } public static uint DefaultTimerPoolThreads { [RT.ConfigurationOption( "System__Runtime_DefaultThreadPoolThreads" )] get { RT.BugCheck.Assert( false, RT.BugCheck.StopCode.IllegalConfiguration ); return 1; } } //--// [RT.BottomOfCallStack()] [RT.HardwareExceptionHandler(RT.HardwareException.Interrupt)] private static void InterruptHandler( UIntPtr stackPtr ) { s_repeatedAbort = false; Context.InterruptHandlerWithContextSwitch( stackPtr ); } [RT.BottomOfCallStack()] [RT.HardwareExceptionHandler(RT.HardwareException.FastInterrupt)] [RT.MemoryRequirements( RT.MemoryAttributes.RAM )] private static void FastInterruptHandler() { s_repeatedAbort = false; Context.FastInterruptHandlerWithoutContextSwitch(); } [RT.BottomOfCallStack()] [RT.HardwareExceptionHandler(RT.HardwareException.SoftwareInterrupt)] private static void SoftwareInterruptHandler( ref Context.RegistersOnStack registers ) { s_repeatedAbort = false; Context.GenericSoftwareInterruptHandler( ref registers ); } //--// [RT.NoInline] [RT.NoReturn( )] [RT.HardwareExceptionHandler( RT.HardwareException.UndefinedInstruction )] [RT.MemoryUsage( RT.MemoryUsage.Bootstrap )] static void UndefinedInstruction( ) { //////RT.Processor.Instance.Breakpoint(); while(true) { } } [RT.NoInline] [RT.NoReturn( )] [RT.HardwareExceptionHandler( RT.HardwareException.PrefetchAbort )] [RT.MemoryUsage( RT.MemoryUsage.Bootstrap )] static void PrefetchAbort( ) { //////RT.Processor.Instance.Breakpoint(); while(true) { } } private static bool s_repeatedAbort = false; private static int s_abortCount = 0; [RT.NoInline] [RT.NoReturn( )] [RT.HardwareExceptionHandler( RT.HardwareException.DataAbort )] [RT.MemoryUsage( RT.MemoryUsage.Bootstrap )] static void DataAbort( ) { //////bool repeatedAbort = s_repeatedAbort; //////s_repeatedAbort = true; //////s_abortCount++; //////if (repeatedAbort) //////RT.Processor.Instance.Breakpoint(); while(true) { } } } } ================================================ FILE: Zelig/Zelig/RunTime/DeviceModels/CortexM0OnMBED/HardwareModel/Storage.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // namespace Microsoft.CortexM0OnMBED { using System; using RT = Microsoft.Zelig.Runtime; using ChipsetModel = Microsoft.CortexM0OnCMSISCore; public class Storage : ChipsetModel.Storage { } } ================================================ FILE: Zelig/Zelig/RunTime/DeviceModels/CortexM0OnMBED/Properties/AssemblyInfo.cs ================================================ using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; // General Information about an assembly is controlled through the following // set of attributes. Change these attribute values to modify the information // associated with an assembly. [assembly: AssemblyTitle( "Microsoft.CortexM0OnMBED" )] [assembly: AssemblyDescription( "" )] [assembly: AssemblyConfiguration( "" )] [assembly: AssemblyCompany( "Microsoft" )] [assembly: AssemblyProduct( "LLILUM" )] [assembly: AssemblyCopyright( "Copyright © Microsoft 2015" )] [assembly: AssemblyTrademark( "" )] [assembly: AssemblyCulture( "" )] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible( false )] // The following GUID is for the ID of the typelib if this project is exposed to COM //[assembly: Guid( "ffacd01c-fa64-4234-9058-1ad866f88c1a" )] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Build and Revision Numbers // by using the '*' as shown below: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion( "1.0.0.0" )] [assembly: AssemblyFileVersion( "1.0.0.0" )] ================================================ FILE: Zelig/Zelig/RunTime/DeviceModels/CortexM0OnMBED/SystemServices/GarbageCollectionManager.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // namespace Microsoft.CortexM0OnMBED { using ChipsetModel = Microsoft.CortexM0OnCMSISCore; public abstract class GarbageCollectionManager : ChipsetModel.GarbageCollectionManager { } } ================================================ FILE: Zelig/Zelig/RunTime/DeviceModels/CortexM0OnMBED/SystemServices/MemoryManager.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // namespace Microsoft.CortexM0OnMBED { using System; using Zelig; using RT = Microsoft.Zelig.Runtime; using Chipset = Microsoft.CortexM0OnCMSISCore; using LLOS = Zelig.LlilumOSAbstraction; public class MemoryManager : Chipset.MemoryManager { private UIntPtr ManagedHeap; private UIntPtr ManagedHeapEnd; //--// public override unsafe void InitializeMemoryManager( ) { base.InitializeMemoryManager( ); uint heapSize; void *pLlilumHeap; LLOS.LlilumErrors.ThrowOnError( LLOS.API.RuntimeMemory.LLOS_MEMORY_GetMaxHeapSize( out heapSize ), false ); LLOS.LlilumErrors.ThrowOnError( LLOS.API.RuntimeMemory.LLOS_MEMORY_Allocate( heapSize, 0, out pLlilumHeap ), false ); ManagedHeap = (UIntPtr)(pLlilumHeap); ManagedHeapEnd = (UIntPtr)( (uint)pLlilumHeap + heapSize ); var attrs = RT.MemoryAttributes.InternalMemory | RT.MemoryAttributes.RandomAccessMemory | RT.MemoryAttributes.ConfiguredAtEntryPoint ; AddLinearSection( ManagedHeap, ManagedHeapEnd , attrs ); } public override bool RefersToMemory( UIntPtr address ) { if(AddressMath.IsInRange( address, ManagedHeap, ManagedHeapEnd )) { return true; } return false; } } } ================================================ FILE: Zelig/Zelig/RunTime/DeviceModels/CortexM0OnMBED/SystemServices/SchedulerTimeImpl.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // namespace Microsoft.CortexM0OnMBED { using System; using RT = Microsoft.Zelig.Runtime; // // We use the 1MHz timer for the internal time. // [RT.ExtendClass(typeof(RT.SchedulerTime), NoConstructors=true)] public struct SchedulerTimeImpl { // // Helper Methods // private static ulong ConvertFromMillisecondsToUnits( int milliSeconds ) { if(milliSeconds < 0) { return ulong.MaxValue; } else { // // The 1MHz timer. // // => 1000000 / 1000 == 1000 // ulong res = (uint)milliSeconds * 1000; return GetCurrentTime() + res; } } private static ulong ConvertFromTimeSpanTicksToUnits( long ticks ) { if(ticks < 0) { return ulong.MaxValue; } else { ulong res = ConvertFromDateTimeTicksToUnits( ticks ); return GetCurrentTime() + res; } } private static ulong ConvertFromDateTimeTicksToUnits( long ticks ) { return (ulong)((double)ticks * RatioFromDateTimeTicksToUnits); } private static long ConvertFromUnitsToDateTimeTicks( ulong units ) { return (long)((double)units * RatioFromUnitsToDateTimeTicks); } private static ulong GetCurrentTime() { return Drivers.SystemTimer.Instance.CurrentTime; } // // Access Methods // static int HardwareClockFrequency { [RT.Inline] get { return (int)RT.Configuration.RealTimeClockFrequency; } } static double RatioFromMillisecondsToUnits { [RT.Inline] get { return (double)HardwareClockFrequency / (double)1000; } } static double RatioFromDateTimeTicksToUnits { [RT.Inline] get { return (double)HardwareClockFrequency / (double)TimeSpan.TicksPerSecond; } } static double RatioFromUnitsToMilliseconds { [RT.Inline] get { return 1.0 / RatioFromMillisecondsToUnits; } } static double RatioFromUnitsToDateTimeTicks { [RT.Inline] get { return 1.0 / RatioFromDateTimeTicksToUnits; } } } } ================================================ FILE: Zelig/Zelig/RunTime/DeviceModels/CortexM0OnMBED/SystemServices/SchedulerTimeSpanImpl.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // namespace Microsoft.CortexM0OnMBED { using System; using RT = Microsoft.Zelig.Runtime; // // We use the RTC time resolution for the internal time. // [RT.ExtendClass(typeof(RT.SchedulerTimeSpan), NoConstructors=true)] public struct SchedulerTimeSpanImpl { // // Helper Methods // private static long ConvertFromMillisecondsToDeltaUnits( long milliSeconds ) { return (long)((double)milliSeconds * RatioFromMillisecondsToDeltaUnits); } private static long ConvertFromTimeSpanTicksToDeltaUnits( long ticks ) { return (long)((double)ticks * RatioFromTimeSpanTicksToDeltaUnits); } private static long ConvertFromDeltaUnitsToTimeSpanTicks( long deltaUnits ) { return (long)((double)deltaUnits * RatioFromDeltaUnitsToTimeSpanTicks); } private static long ConvertFromDeltaUnitsToMilliseconds( long deltaUnits ) { return (long)((double)deltaUnits * RatioFromDeltaUnitsToMilliseconds); } // // Access Methods // static int HardwareClockFrequency { [RT.Inline] get { return (int)RT.Configuration.RealTimeClockFrequency; } } static double RatioFromMillisecondsToDeltaUnits { [RT.Inline] get { return (double)HardwareClockFrequency / (double)1000; } } static double RatioFromTimeSpanTicksToDeltaUnits { [RT.Inline] get { return (double)HardwareClockFrequency / (double)TimeSpan.TicksPerSecond; } } static double RatioFromDeltaUnitsToMilliseconds { [RT.Inline] get { return 1.0 / RatioFromMillisecondsToDeltaUnits; } } static double RatioFromDeltaUnitsToTimeSpanTicks { [RT.Inline] get { return 1.0 / RatioFromTimeSpanTicksToDeltaUnits; } } } } ================================================ FILE: Zelig/Zelig/RunTime/DeviceModels/CortexM0OnMBED/SystemServices/ThreadManager.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // namespace Microsoft.CortexM0OnMBED { using System; using RT = Microsoft.Zelig.Runtime; using HAL = Microsoft.Zelig.LlilumOSAbstraction.HAL; using ARMv6 = Microsoft.Zelig.Runtime.TargetPlatform.ARMv6; using ChipsetModel = Microsoft.CortexM0OnCMSISCore; public abstract class ThreadManager : ChipsetModel.ThreadManager { // // State // // // BUGBUG: we need to Dispose this object on shutdown !!! // protected Drivers.SystemTimer.Timer m_timerForWaits; protected RT.ThreadImpl m_exceptionThread; //--// // // Helper methods // public override void InitializeAfterStaticConstructors( uint[] systemStack ) { base.InitializeAfterStaticConstructors( systemStack ); // // The exception thread wraps the main stack pointer // m_exceptionThread = new RT.ThreadImpl( RT.Bootstrap.Initialization, GetMainStack( ) ); // // The msp thread is never started, so we have to manually register them, to enable the debugger to see them. // RegisterThread(m_exceptionThread); //--// m_exceptionThread.SetupForExceptionHandling( unchecked((uint)ARMv6.ProcessorARMv6M.IRQn_Type.Reset_IRQn) ); } public override void Activate() { base.Activate( ); m_timerForWaits = Drivers.SystemTimer.Instance.CreateTimer( WaitExpired ); DeviceModels.Chipset.CortexM0.Drivers.InterruptController.Instance.Activate(); } public override void SetNextWaitTimer( RT.SchedulerTime nextTimeout ) { if(nextTimeout != RT.SchedulerTime.MaxValue) { m_timerForWaits.Timeout = nextTimeout.Units; } else { m_timerForWaits.Cancel( ); } } // // Access methods // public override RT.ThreadImpl InterruptThread { get { return m_exceptionThread; } } public override RT.ThreadImpl FastInterruptThread { get { return m_exceptionThread; } } public override RT.ThreadImpl AbortThread { get { return m_exceptionThread; } } //--// protected void WaitExpired( Drivers.SystemTimer.Timer sysTickTimer, ulong currentTime ) { WaitExpired( RT.SchedulerTime.FromUnits( currentTime ) ); } protected uint[] GetMainStack() { // // The main stack address will have to at least additional 12 bytes // to inject the ObjectHeader and the ArrayImpl members. // TODO: find a better way to keep this in sync with ArrayImpl. // uint correction = RT.MemoryFreeBlock.FixedSize(); RT.BugCheck.Assert( correction == 12, RT.BugCheck.StopCode.StackCorruptionDetected ); uint stackAddress = HAL.Thread.LLOS_THREAD_GetMainStackAddress( ) - correction; uint stackSize = HAL.Thread.LLOS_THREAD_GetMainStackSize( ); return RT.ArrayImpl.InitializeFromRawMemory( new UIntPtr( stackAddress ), stackSize ); } } } ================================================ FILE: Zelig/Zelig/RunTime/DeviceModels/CortexM0OnMBED/SystemServices/TimerPool.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // namespace Microsoft.CortexM0OnMBED { using Chipset = Microsoft.CortexM0OnCMSISCore; public abstract class TimerPool : Chipset.TimerPool { } } ================================================ FILE: Zelig/Zelig/RunTime/DeviceModels/CortexM0OnMBED/SystemServices/TypeSystemManager.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // namespace Microsoft.CortexM0OnMBED { using ChipsetModel = Microsoft.CortexM0OnCMSISCore; public class TypeSystemManager : ChipsetModel.TypeSystemManager { } } ================================================ FILE: Zelig/Zelig/RunTime/DeviceModels/CortexM3OnCMSIS-Core/CortexM3OnCMSIS-Core.csproj ================================================  Debug AnyCPU 9.0.21022 2.0 {0B37E5BA-4839-4EC4-9E36-A96BCBEA2400} Library Properties Microsoft.CortexM3OnCMSISCore Microsoft.CortexM3OnCMSISCore $(LlilumBuildRoot)\Target\obj\$(MSBuildProjectName)\ v4.5 512 true full false $(LlilumBuildRoot)\Target\bin\$(Configuration)\ DEBUG;TRACE prompt 4 true true true AllRules.ruleset AnyCPU false pdbonly true $(LlilumBuildRoot)\Target\bin\$(Configuration)\ TRACE prompt 4 true true true AllRules.ruleset AnyCPU false {186F31A3-EF89-4A25-B2D5-20060501AA01} mscorlib False {186F31A3-EF89-4A25-B2D5-20061218AA01} Common False {186F31A3-EF89-4A25-B2D5-20060509AA01} Kernel False {186F31A3-EF89-4A25-B2D5-20060720AA01} TypeSystem False {186f31a3-ef89-4a25-b2d5-20070702aa01} system False {20DC2CF5-8EED-4231-9743-6BAB96BE465C} LlilumOSAbstraction {a30eb003-94f8-4a85-8da1-006f6810a7a4} ModelForCortexM3 {E4C618AF-1785-472E-A070-8068E20582EB} ModelForCortexM ================================================ FILE: Zelig/Zelig/RunTime/DeviceModels/CortexM3OnCMSIS-Core/HardwareModel/Board.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // namespace Microsoft.CortexM3OnCMSISCore { using System.Runtime.CompilerServices; using RT = Microsoft.Zelig.Runtime; using ChipsetModel = Microsoft.DeviceModels.Chipset.CortexM3; public abstract class Board : ChipsetModel.Board { } } ================================================ FILE: Zelig/Zelig/RunTime/DeviceModels/CortexM3OnCMSIS-Core/HardwareModel/Device.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // namespace Microsoft.CortexM3OnCMSISCore { using RT = Microsoft.Zelig.Runtime; public abstract class Device : RT.Device { } } ================================================ FILE: Zelig/Zelig/RunTime/DeviceModels/CortexM3OnCMSIS-Core/HardwareModel/Drivers/ContextSwitchTimer.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // namespace Microsoft.CortexM3OnCMSISCore.Drivers { using ChipsetModel = Microsoft.DeviceModels.Chipset.CortexM3; public abstract class ContextSwitchTimer : ChipsetModel.Drivers.ContextSwitchTimer { } } ================================================ FILE: Zelig/Zelig/RunTime/DeviceModels/CortexM3OnCMSIS-Core/HardwareModel/Drivers/InterruptController.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // namespace Microsoft.CortexM3OnCMSISCore.Drivers { using ChipsetModel = Microsoft.DeviceModels.Chipset.CortexM3; public abstract class InterruptController : ChipsetModel.Drivers.InterruptController { } } ================================================ FILE: Zelig/Zelig/RunTime/DeviceModels/CortexM3OnCMSIS-Core/HardwareModel/HardwareProvider.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // namespace Microsoft.CortexM3OnCMSISCore { using RT = Microsoft.Zelig.Runtime; //--// public abstract class HardwareProvider : RT.HardwareProvider { } } ================================================ FILE: Zelig/Zelig/RunTime/DeviceModels/CortexM3OnCMSIS-Core/HardwareModel/Memory.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // namespace Microsoft.CortexM3OnCMSISCore { using System; using RT = Microsoft.Zelig.Runtime; using TS = Microsoft.Zelig.Runtime.TypeSystem; public abstract class Memory : RT.Memory { } } ================================================ FILE: Zelig/Zelig/RunTime/DeviceModels/CortexM3OnCMSIS-Core/HardwareModel/Peripherals.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // //#define ALLOW_PAUSE namespace Microsoft.CortexM3OnCMSISCore { using Microsoft.Zelig.Runtime.TargetPlatform.ARMv7; using RT = Microsoft.Zelig.Runtime; using CMSIS = Microsoft.DeviceModels.Chipset.CortexM; using LLOS = Zelig.LlilumOSAbstraction.HAL; public abstract class Peripherals : RT.Peripherals { // // State // // // Helper Methods // public override void Initialize() { RT.BugCheck.AssertInterruptsOff(); // // Faults, never disabled // CMSIS.NVIC.SetPriority( (int)ProcessorARMv7M.IRQn_Type.HardFault_IRQn , ProcessorARMv7M.c_Priority__NeverDisabled ); CMSIS.NVIC.SetPriority( (int)ProcessorARMv7M.IRQn_Type.MemoryManagement_IRQn, ProcessorARMv7M.c_Priority__NeverDisabled ); CMSIS.NVIC.SetPriority( (int)ProcessorARMv7M.IRQn_Type.BusFault_IRQn , ProcessorARMv7M.c_Priority__NeverDisabled ); CMSIS.NVIC.SetPriority( (int)ProcessorARMv7M.IRQn_Type.UsageFault_IRQn , ProcessorARMv7M.c_Priority__NeverDisabled ); // // System exceptions // CMSIS.NVIC.SetPriority( (int)ProcessorARMv7M.IRQn_Type.SVCall_IRQn , ProcessorARMv7M.c_Priority__SVCCall ); CMSIS.NVIC.SetPriority( (int)ProcessorARMv7M.IRQn_Type.SysTick_IRQn, ProcessorARMv7M.c_Priority__SysTick ); CMSIS.NVIC.SetPriority( (int)ProcessorARMv7M.IRQn_Type.PendSV_IRQn , ProcessorARMv7M.c_Priority__PendSV ); } public override void Activate() { CMSIS.Drivers.InterruptController.Instance.Initialize(); CMSIS.Drivers.ContextSwitchTimer.Instance.Initialize(); } public override void EnableInterrupt( uint index ) { } public override void DisableInterrupt( uint index ) { } public override void CauseInterrupt() { ProcessorARMv7M.CompleteContextSwitch( ); //Drivers.InterruptController.Instance.CauseInterrupt( ); } public override void ContinueUnderNormalInterrupt(Continuation dlg) { Drivers.InterruptController.Instance.ContinueUnderNormalInterrupt(dlg); } public override void WaitForInterrupt() { while (true) { ProcessorARMv7M.WaitForInterrupt( ); } //while(true) ; } public override void ProcessInterrupt() { using (RT.SmartHandles.SwapCurrentThreadUnderInterrupt hnd = RT.ThreadManager.InstallInterruptThread()) { Drivers.InterruptController.Instance.ProcessInterrupt(); } } [RT.MemoryRequirements(RT.MemoryAttributes.RAM)] public override void ProcessFastInterrupt() { using (RT.SmartHandles.SwapCurrentThreadUnderInterrupt hnd = RT.ThreadManager.InstallFastInterruptThread()) { Drivers.InterruptController.Instance.ProcessFastInterrupt(); } } public override ulong GetPerformanceCounterFrequency() { return LLOS.Clock.LLOS_CLOCK_GetPerformanceCounterFrequency(); } [RT.Inline] [RT.DisableNullChecks()] public override uint ReadPerformanceCounter() { return (uint)LLOS.Clock.LLOS_CLOCK_GetPerformanceCounter(); } } } ================================================ FILE: Zelig/Zelig/RunTime/DeviceModels/CortexM3OnCMSIS-Core/HardwareModel/Processor.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // namespace Microsoft.CortexM3OnCMSISCore { using System; using RT = Microsoft.Zelig.Runtime; using ChipsetModel = Microsoft.DeviceModels.Chipset.CortexM3; using CortexM = Microsoft.DeviceModels.Chipset.CortexM; using LLOS = Zelig.LlilumOSAbstraction.HAL; public abstract class Processor : ChipsetModel.Processor { public abstract new class Context : RT.TargetPlatform.ARMv7.ProcessorARMv7MForLlvm.Context { // // Constructor Methods // public Context(RT.ThreadImpl owner) : base(owner) { } // // Helper Methods // #region RTOS extensibility protected virtual UIntPtr CreateNativeContext( UIntPtr entryPoint, UIntPtr stack, int stackSize ) { return (UIntPtr)0; } protected virtual void SwitchToContext( UIntPtr thread ) { } protected virtual void Yield( UIntPtr handle ) { } protected virtual void Retire( UIntPtr handle ) { } #endregion // // Access Methods // } // // Helper Methods // public override void InitializeProcessor() { base.InitializeProcessor(); // // Reset the priority grouping that we assume not used // CortexM.NVIC.SetPriorityGrouping( 0 ); } protected override unsafe void RemapInterrupt(IRQn_Type IRQn, Action isr) { RT.DelegateImpl dlg = (RT.DelegateImpl)(object)isr; UIntPtr isrPtr = new UIntPtr(dlg.InnerGetCodePointer().Target.ToPointer()); CortexM.NVIC.SetVector((int)IRQn, isrPtr.ToUInt32()); } } //--// //--// //--// [RT.ExtendClass( typeof( Microsoft.Zelig.Runtime.Processor ) )] internal class ProcessorImpl { [RT.MergeWithTargetImplementation] internal ProcessorImpl() { } [RT.NoInline] [RT.MemoryUsage( RT.MemoryUsage.Bootstrap )] public static int Delay( int count ) { LLOS.Clock.LLOS_CLOCK_DelayCycles( (uint)count ); return 0; } } } ================================================ FILE: Zelig/Zelig/RunTime/DeviceModels/CortexM3OnCMSIS-Core/HardwareModel/SerialPortsManager.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // namespace Microsoft.CortexM3OnCMSISCore { using RT = Microsoft.Zelig.Runtime; //--// public abstract class SerialPortsManager : RT.SerialPortsManager { } } ================================================ FILE: Zelig/Zelig/RunTime/DeviceModels/CortexM3OnCMSIS-Core/HardwareModel/Storage.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // namespace Microsoft.CortexM3OnCMSISCore { using System; using RT = Microsoft.Zelig.Runtime; using TS = Microsoft.Zelig.Runtime.TypeSystem; public abstract class Storage : RT.Storage { public override void InitializeStorage( ) { } //--// public override bool EraseSectors( UIntPtr addressStart, UIntPtr addressEnd ) { RT.BugCheck.Raise(RT.BugCheck.StopCode.FailedBootstrap); throw new Exception( "EraseSectors not implemented" ); } public override bool WriteByte( UIntPtr address, byte val ) { RT.BugCheck.Raise(RT.BugCheck.StopCode.FailedBootstrap); throw new Exception( "WriteByte not implemented" ); } public override bool WriteShort( UIntPtr address, ushort val ) { RT.BugCheck.Raise(RT.BugCheck.StopCode.FailedBootstrap); throw new Exception( "WriteShort not implemented" ); } public override bool WriteWord( UIntPtr address, uint val ) { RT.BugCheck.Raise(RT.BugCheck.StopCode.FailedBootstrap); throw new Exception( "WriteWord not implemented" ); } public override bool Write( UIntPtr address, byte[] buffer, uint offset, uint numBytes ) { RT.BugCheck.Raise(RT.BugCheck.StopCode.FailedBootstrap); throw new Exception( "Write not implemented" ); } //--// public override byte ReadByte( UIntPtr address ) { RT.BugCheck.Raise(RT.BugCheck.StopCode.FailedBootstrap); throw new Exception( "ReadByte not implemented" ); } public override ushort ReadShort( UIntPtr address ) { RT.BugCheck.Raise(RT.BugCheck.StopCode.FailedBootstrap); throw new Exception( "ReadShort not implemented" ); } public override uint ReadWord( UIntPtr address ) { RT.BugCheck.Raise(RT.BugCheck.StopCode.FailedBootstrap); throw new Exception( "ReadWord not implemented" ); } public override void Read( UIntPtr address, byte[] buffer, uint offset, uint numBytes ) { RT.BugCheck.Raise(RT.BugCheck.StopCode.FailedBootstrap); throw new Exception( "Read not implemented" ); } public override void SubstituteFirmware( UIntPtr addressDestination, UIntPtr addressSource, uint numBytes ) { RT.BugCheck.Raise(RT.BugCheck.StopCode.FailedBootstrap); throw new Exception( "SubstituteFirmware not implemented" ); } public override void RebootDevice( ) { RT.BugCheck.Raise(RT.BugCheck.StopCode.FailedBootstrap); } } } ================================================ FILE: Zelig/Zelig/RunTime/DeviceModels/CortexM3OnCMSIS-Core/Properties/AssemblyInfo.cs ================================================ using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; // General Information about an assembly is controlled through the following // set of attributes. Change these attribute values to modify the information // associated with an assembly. [assembly: AssemblyTitle( "Microsoft.CortexM3OnCMSISCore" )] [assembly: AssemblyDescription( "" )] [assembly: AssemblyConfiguration( "" )] [assembly: AssemblyCompany( "Microsoft" )] [assembly: AssemblyProduct( "LLILUM" )] [assembly: AssemblyCopyright( "Copyright © Microsoft 2015" )] [assembly: AssemblyTrademark( "" )] [assembly: AssemblyCulture( "" )] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible( false )] // The following GUID is for the ID of the typelib if this project is exposed to COM //[assembly: Guid( "ffacd01c-fa64-4234-9058-1ad866f88c1a" )] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Build and Revision Numbers // by using the '*' as shown below: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion( "1.0.0.0" )] [assembly: AssemblyFileVersion( "1.0.0.0" )] ================================================ FILE: Zelig/Zelig/RunTime/DeviceModels/CortexM3OnCMSIS-Core/SystemServices/GarbageCollectionManager.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // namespace Microsoft.CortexM3OnCMSISCore { using System; using RT = Microsoft.Zelig.Runtime; using PROC = Microsoft.Zelig.Runtime.TargetPlatform.ARMv7; public abstract class GarbageCollectionManager : RT.ConservativeMarkAndSweepCollector { public override uint Collect() { // Snapshot the registers on the current thread PROC.ProcessorARMv7M.RaiseSupervisorCall( PROC.ProcessorARMv7M.SVC_Code.SupervisorCall__SnapshotProcessModeRegisters ); return base.Collect(); } //--// protected override void WalkStackFrames() { // Mark the registers from the snapshot for (uint regNum = 0; regNum < 13; regNum++) { UIntPtr ptr = PROC.ProcessorARMv7MForLlvm.Snapshot.GetRegisterValue(regNum); if (ptr != UIntPtr.Zero) { VisitInternalPointer(ptr); } } base.WalkStackFrames(); } } } ================================================ FILE: Zelig/Zelig/RunTime/DeviceModels/CortexM3OnCMSIS-Core/SystemServices/MemoryManager.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // namespace Microsoft.CortexM3OnCMSISCore { using RT = Microsoft.Zelig.Runtime; public abstract class MemoryManager : RT.LinearMemoryManager { } } ================================================ FILE: Zelig/Zelig/RunTime/DeviceModels/CortexM3OnCMSIS-Core/SystemServices/ThreadManager.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // namespace Microsoft.CortexM3OnCMSISCore { using ChipsetModel = Microsoft.DeviceModels.Chipset.CortexM3; public abstract class ThreadManager : ChipsetModel.Runtime.ThreadManager { } } ================================================ FILE: Zelig/Zelig/RunTime/DeviceModels/CortexM3OnCMSIS-Core/SystemServices/TimerPool.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // namespace Microsoft.CortexM3OnCMSISCore { using RT = Microsoft.Zelig.Runtime; public abstract class TimerPool : RT.TimerImpl.BoundedAsynchTimerPool { } } ================================================ FILE: Zelig/Zelig/RunTime/DeviceModels/CortexM3OnCMSIS-Core/SystemServices/TypeSystemManager.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // namespace Microsoft.CortexM3OnCMSISCore { using RT = Microsoft.Zelig.Runtime; public abstract class TypeSystemManager : RT.DefaultTypeSystemManager { } } ================================================ FILE: Zelig/Zelig/RunTime/DeviceModels/CortexM3OnMBED/CortexM3OnMBED.csproj ================================================  Debug AnyCPU 9.0.21022 2.0 {0C522C6A-0F77-4AF8-AD78-5B2415C98C51} Library Properties Microsoft.CortexM3OnMBED Microsoft.CortexM3OnMBED $(LlilumBuildRoot)\Target\obj\$(MSBuildProjectName)\ v4.5 512 true full false $(LlilumBuildRoot)\Target\bin\$(Configuration)\ DEBUG;TRACE prompt 4 true true true AllRules.ruleset AnyCPU false pdbonly true $(LlilumBuildRoot)\Target\bin\$(Configuration)\ TRACE prompt 4 true true true AllRules.ruleset AnyCPU false {186F31A3-EF89-4A25-B2D5-20060501AA01} mscorlib False {186F31A3-EF89-4A25-B2D5-20061218AA01} Common False {186F31A3-EF89-4A25-B2D5-20060509AA01} Kernel False {186F31A3-EF89-4A25-B2D5-20060720AA01} TypeSystem False {d68ee51b-a898-4a77-97d8-c61254cac122} Microsoft.Llilum.Devices {186f31a3-ef89-4a25-b2d5-20070702aa01} system False {dc8c38d7-780b-4b13-8ace-9050e39cc51c} Windows {0b37e5ba-4839-4ec4-9e36-a96bcbea2400} CortexM3OnCMSIS-Core {20DC2CF5-8EED-4231-9743-6BAB96BE465C} LlilumOSAbstraction {d7f2bc4e-1406-47aa-90e1-07bc4ce9410f} mbed {A30EB003-94F8-4A85-8DA1-006F6810A7A4} ModelForCortexM3 {e77ac86e-58ab-47b6-bc6d-3c1b4545cdfd} Microsoft.Llilum.Lwip {b8fe271a-cd41-435e-8766-4db7609c1007} CortexM0OnCMSIS-Core {89ebdbb0-c81f-4611-b719-b385df215f8d} CortexM0OnMBED {c3bfafad-a6c6-471d-a059-b3cb7e57a4ab} ModelForCortexM0 {e4c618af-1785-472e-a070-8068e20582eb} ModelForCortexM ================================================ FILE: Zelig/Zelig/RunTime/DeviceModels/CortexM3OnMBED/HardwareModel/Board.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // namespace Microsoft.CortexM3OnMBED { using ChipsetModel = Microsoft.CortexM0OnMBED; public abstract class Board : ChipsetModel.Board { } } ================================================ FILE: Zelig/Zelig/RunTime/DeviceModels/CortexM3OnMBED/HardwareModel/Device.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // namespace Microsoft.CortexM3OnMBED { using RT = Microsoft.Zelig.Runtime; using RTOS = Microsoft.Zelig.Support.mbed; using ChipsetModel = Microsoft.CortexM0OnMBED; public abstract class Device : ChipsetModel.Device { } } ================================================ FILE: Zelig/Zelig/RunTime/DeviceModels/CortexM3OnMBED/HardwareModel/Drivers/InterruptController.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // namespace Microsoft.CortexM3OnMBED.Drivers { using System; using Chipset = CortexM0OnMBED; using TS = Zelig.Runtime.TypeSystem; using RT = Zelig.Runtime; public abstract class InterruptController : Chipset.Drivers.InterruptController { } } ================================================ FILE: Zelig/Zelig/RunTime/DeviceModels/CortexM3OnMBED/HardwareModel/Drivers/SerialPortsManager.cs ================================================ namespace Microsoft.CortexM3OnMBED.HardwareModel.Drivers { using ChipsetModel = Microsoft.CortexM0OnMBED; public sealed class SerialPortsManager : ChipsetModel.HardwareModel.Drivers.SerialPortsManager { } } ================================================ FILE: Zelig/Zelig/RunTime/DeviceModels/CortexM3OnMBED/HardwareModel/Drivers/SystemTimer.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // namespace Microsoft.CortexM3OnMBED.Drivers { using ChipsetModel = Microsoft.CortexM0OnMBED; /// /// This class implements the internal system timer. All times are in ticks (time agnostic) /// however in practice, and due to limitations of mbed 1 tick is equal to 1 uS (micro second) /// public abstract class SystemTimer : ChipsetModel.Drivers.SystemTimer { } } ================================================ FILE: Zelig/Zelig/RunTime/DeviceModels/CortexM3OnMBED/HardwareModel/HardwareProvider.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // namespace Microsoft.CortexM3OnMBED.HardwareModel { using ChipsetAbstration = Microsoft.DeviceModels.Chipset.CortexM0; using ChipsetModel = Microsoft.CortexM0OnMBED; public class HardwareProvider : ChipsetModel.HardwareModel.HardwareProvider { } } ================================================ FILE: Zelig/Zelig/RunTime/DeviceModels/CortexM3OnMBED/HardwareModel/HardwareProviders/AdcProvider.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // namespace Microsoft.CortexM3OnMBED.HardwareModel { using ChipsetModel = Microsoft.CortexM0OnMBED; public sealed class AdcProvider : ChipsetModel.HardwareModel.AdcProvider { } } ================================================ FILE: Zelig/Zelig/RunTime/DeviceModels/CortexM3OnMBED/HardwareModel/HardwareProviders/GpioProvider.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // namespace Microsoft.CortexM3OnMBED.HardwareModel { using ChipsetModel = Microsoft.CortexM0OnMBED; public abstract class GpioProvider : ChipsetModel.HardwareModel.GpioProvider { } } ================================================ FILE: Zelig/Zelig/RunTime/DeviceModels/CortexM3OnMBED/HardwareModel/HardwareProviders/I2cProvider.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // namespace Microsoft.CortexM3OnMBED.HardwareModel { using ChipsetModel = Microsoft.CortexM0OnMBED; public abstract class I2cProvider : ChipsetModel.HardwareModel.I2cProvider { } } ================================================ FILE: Zelig/Zelig/RunTime/DeviceModels/CortexM3OnMBED/HardwareModel/HardwareProviders/NetworkInterfaceProvider.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // namespace Microsoft.CortexM3OnMBED.HardwareModel { using Zelig.LlilumOSAbstraction.API.IO; using Microsoft.Llilum.Lwip; using RT = Microsoft.Zelig.Runtime; public abstract class NetworkInterfaceProvider : RT.NetworkInterfaceProvider { public override int Connect(uint timeout) { return EthernetInterface.LLOS_ethernet_connect(timeout); } public override int Disconnect() { return EthernetInterface.LLOS_ethernet_disconnect(); } public override int GetNetworkInterfaceCount() { // TODO: Eventually, we may want to make this extensible return 1; } public unsafe override string GetIPAddress() { char[] address = new char[16]; fixed(char* addr = address) { EthernetInterface.LLOS_ethernet_get_IPv4Address(addr, (uint)address.Length); } return new string(address); } public override int InitializeEthernet() { return EthernetInterface.LLOS_ethernet_dhcp_init(); } public unsafe override int InitializeEthernet(string ipAddress, string mask, string gateway) { char[] ipBytes = ipAddress.ToCharArray(); char[] maskBytes = mask.ToCharArray(); char[] gatewayBytes = gateway.ToCharArray(); fixed (char* ipAddr = ipBytes) { fixed (char* subnetMask = maskBytes) { fixed(char* gatewayAddr = gatewayBytes) { return EthernetInterface.LLOS_ethernet_staticIP_init(ipAddr, (uint)ipAddress.Length, subnetMask, (uint)mask.Length, gatewayAddr, (uint)gateway.Length); } } } } public unsafe override uint IPv4AddressFromString(string ipAddress) { char[] addrArray = ipAddress.ToCharArray(); fixed (char* ipAddr = addrArray) { return EthernetInterface.LLOS_ethernet_address_from_string(ipAddr, (uint)ipAddress.Length); } } public unsafe override string GetMacAddress() { char[] address = new char[20]; fixed (char* addr = address) { EthernetInterface.LLOS_ethernet_get_macAddress(addr, (uint)address.Length); } return new string(address); } public unsafe override string GetGatewayAddress() { char[] address = new char[16]; fixed (char* addr = address) { EthernetInterface.LLOS_ethernet_get_gatewayIPv4Address(addr, (uint)address.Length); } return new string(address); } public unsafe override string GetMask() { char[] address = new char[16]; fixed (char* addr = address) { EthernetInterface.LLOS_ethernet_get_networkIPv4Mask(addr, (uint)address.Length); } return new string(address); } public override string GetDefaultLocalAddress() { NetworkInterface[] interfaces = NetworkInterface.GetAllNetworkInterfaces(); int cnt = interfaces.Length; for (int i = 0; i < cnt; i++) { NetworkInterface ni = interfaces[i]; if (ni.IPAddress != "0.0.0.0" && ni.SubnetMask != "0.0.0.0") { return ni.IPAddress; } } return null; } } } ================================================ FILE: Zelig/Zelig/RunTime/DeviceModels/CortexM3OnMBED/HardwareModel/HardwareProviders/PwmProvider.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // namespace Microsoft.CortexM3OnMBED.HardwareModel { using ChipsetModel = Microsoft.CortexM0OnMBED; public sealed class PwmProvider : ChipsetModel.HardwareModel.PwmProvider { } } ================================================ FILE: Zelig/Zelig/RunTime/DeviceModels/CortexM3OnMBED/HardwareModel/HardwareProviders/SocketProvider.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // namespace Microsoft.CortexM3OnMBED.HardwareModel { using System; using Zelig.LlilumOSAbstraction.API.IO; using System.Text; using RT = Microsoft.Zelig.Runtime; public sealed class SocketProvider : RT.SocketProvider { // // Socket protocol types (TCP/UDP/RAW) // private const int SOCK_STREAM = 1; private const int SOCK_DGRAM = 2; private const int SOCK_RAW = 3; // // Option flags per-socket. These must match the SOF_ flags in ip.h (checked in init.c) // private const int SO_DEBUG = 0x0001; // Unimplemented: turn on debugging info recording private const int SO_ACCEPTCONN = 0x0002; // socket has had listen() private const int SO_REUSEADDR = 0x0004; // Allow local address reuse private const int SO_KEEPALIVE = 0x0008; // keep connections alive private const int SO_DONTROUTE = 0x0010; // Unimplemented: just use interface addresses private const int SO_BROADCAST = 0x0020; // permit to send and to receive broadcast messages (see IP_SOF_BROADCAST option) private const int SO_USELOOPBACK = 0x0040; // Unimplemented: bypass hardware when possible private const int SO_LINGER = 0x0080; // linger on close if data present private const int SO_OOBINLINE = 0x0100; // Unimplemented: leave received OOB data in line private const int SO_REUSEPORT = 0x0200; // Unimplemented: allow local address & port reuse private const int SO_DONTLINGER = ((int)(~SO_LINGER)); // // Additional options, not kept in so_options. // private const int SO_SNDBUF = 0x1001; // Unimplemented: send buffer size private const int SO_RCVBUF = 0x1002; // receive buffer size private const int SO_SNDLOWAT = 0x1003; // Unimplemented: send low-water mark private const int SO_RCVLOWAT = 0x1004; // Unimplemented: receive low-water mark private const int SO_SNDTIMEO = 0x1005; // Unimplemented: send timeout private const int SO_RCVTIMEO = 0x1006; // receive timeout private const int SO_ERROR = 0x1007; // get error status and clear private const int SO_TYPE = 0x1008; // get socket type private const int SO_CONTIMEO = 0x1009; // Unimplemented: connect timeout private const int SO_NO_CHECK = 0x100a; // don't create UDP checksum // // Level number for (get/set)sockopt() to apply to socket itself. // private const int SOL_SOCKET = 0xfff; // options for socket level private const int AF_UNSPEC = 0; private const int AF_INET = 2; private const int PF_INET = AF_INET; private const int PF_UNSPEC = AF_UNSPEC; private const int IPPROTO_IP = 0; private const int IPPROTO_TCP = 6; private const int IPPROTO_UDP = 17; private const int IPPROTO_UDPLITE = 136; // // Options for level IPPROTO_IP // private const int IP_TOS = 1; private const int IP_TTL = 2; // // Options for level IPPROTO_TCP // private const int TCP_NODELAY = 0x01; // don't delay send to coalesce packets private const int TCP_KEEPALIVE = 0x02; // send KEEPALIVE probes when idle for pcb->keep_idle milliseconds private const int TCP_KEEPIDLE = 0x03; // set pcb->keep_idle - Same as TCP_KEEPALIVE, but use seconds for get/setsockopt private const int TCP_KEEPINTVL = 0x04; // set pcb->keep_intvl - Use seconds for get/setsockopt private const int TCP_KEEPCNT = 0x05; // set pcb->keep_cnt - Use number of probes sent for get/setsockopt // // Options for level IPPROTO_UDPLITE // private const int UDPLITE_SEND_CSCOV = 0x01; // sender checksum coverage private const int UDPLITE_RECV_CSCOV = 0x02; // minimal receiver checksum coverage // // Options and types for UDP multicast traffic handling // private const int IP_ADD_MEMBERSHIP = 3; private const int IP_DROP_MEMBERSHIP = 4; private const int IP_MULTICAST_TTL = 5; private const int IP_MULTICAST_IF = 6; private const int IP_MULTICAST_LOOP = 7; //--// //--// //--// private const int SOCK_SOCK_STREAM = 1; private const int SOCK_SOCK_DGRAM = 2; private const int SOCK_SOCK_RAW = 3; private const int SOCK_SOCK_RDM = 4; private const int SOCK_SOCK_SEQPACKET = 5; private const int SOCK_SOCK_PACK_EX = 6; private const int SOCK_TCP_NODELAY = 0x0001; private const int SOCK_IPPROTO_IP = 0; private const int SOCK_IPPROTO_ICMP = 1; private const int SOCK_IPPROTO_IGMP = 2; private const int SOCK_IPPROTO_IPV4 = 4; // IP-in-IP encapsulation private const int SOCK_IPPROTO_TCP = 6; private const int SOCK_IPPROTO_PUP = 12; private const int SOCK_IPPROTO_UDP = 17; private const int SOCK_IPPROTO_IDP = 22; private const int SOCK_IPPROTO_IPV6 = 41; private const int SOCK_IPPROTO_IPv6RoutingHeader = 43; private const int SOCK_IPPROTO_IPv6FragmentHeader = 44; private const int SOCK_IPPROTO_RDP = 46; private const int SOCK_IPPROTO_GRE = 47; private const int SOCK_IPPROTO_IPSecEncapsulatingSecurityPayload = 50; private const int SOCK_IPPROTO_IPSecAuthenticationHeader = 51; private const int SOCK_IPPROTO_IcmpV6 = 58; private const int SOCK_IPPROTO_IPv6NoNextHeader = 59; private const int SOCK_IPPROTO_IPv6DestinationOptions = 60; private const int SOCK_IPPROTO_ND = 77; private const int SOCK_IPPROTO_OSPF = 89; private const int SOCK_IPPROTO_TPACKET = 127; private const int SOCK_IPPROTO_RAW = 255; private const int SOCK_IPPROTO_IPX = 1000; private const int SOCK_IPPROTO_SPX = 1256; private const int SOCK_IPPROTO_SPXII = 1257; private const int SOCK_SOL_SOCKET = 0xFFFF; // // Option flags per-socket // private const int SOCK_SOCKO_DEBUG = 0x0001; // turn on debugging info recording private const int SOCK_SOCKO_NOCHECKSUM = 0x0001; private const int SOCK_SOCKO_ACCEPTCONNECTION = 0x0002; // socket has had listen() private const int SOCK_SOCKO_REUSEADDRESS = 0x0004; // allow local address reuse private const int SOCK_SOCKO_KEEPALIVE = 0x0008; // keep connections alive private const int SOCK_SOCKO_DONTROUTE = 0x0010; // just use interface addresses private const int SOCK_SOCKO_BROADCAST = 0x0020; // permit sending of broadcast msgs private const int SOCK_SOCKO_USELOOPBACK = 0x0040; // bypass hardware when possible private const int SOCK_SOCKO_LINGER = 0x0080; // linger on close if data present private const int SOCK_SOCKO_OUTOFBANDINLINE = 0x0100; // leave received OOB data in line private const int SOCK_SOCKO_DONTLINGER = ~SOCK_SOCKO_LINGER; private const int SOCK_SOCKO_EXCLUSIVEADDRESSUSE = ~SOCK_SOCKO_REUSEADDRESS; // disallow local address reuse private const int SOCK_SOCKO_SENDBUFFER = 0x1001; // send buffer size private const int SOCK_SOCKO_SNDBUF = SOCK_SOCKO_SENDBUFFER; private const int SOCK_SOCKO_RECEIVEBUFFER = 0x1002; // receive buffer size private const int SOCK_SOCKO_RCVBUF = SOCK_SOCKO_RECEIVEBUFFER; private const int SOCK_SOCKO_SENDLOWWATER = 0x1003; // send low-water mark private const int SOCK_SOCKO_RECEIVELOWWATER = 0x1004; // receive low-water mark private const int SOCK_SOCKO_SENDTIMEOUT = 0x1005; // send timeout private const int SOCK_SOCKO_RECEIVETIMEOUT = 0x1006; // receive timeout private const int SOCK_SOCKO_ERROR = 0x1007; // get error status and clear private const int SOCK_SOCKO_TYPE = 0x1008; // get socket type private const int SOCK_SOCKO_UPDATE_ACCEPT_CTX = 0x700B; // This option updates the properties of the socket which are inherited from the listening socket. private const int SOCK_SOCKO_UPDATE_CONNECT_CTX = 0x7010; // This option updates the properties of the socket after the connection is established. private const int SOCK_SOCKO_MAXCONNECTIONS = 0x7FFFFFFF; // Maximum queue length specifiable by listen. // // Option flags per-IP // private const int SOCK_IPO_OPTIONS = 0x0001; private const int SOCK_IPO_HDRINCL = 0x0002; private const int SOCK_IPO_TOS = 0x0003; private const int SOCK_IPO_TTL = 0x0004; private const int SOCK_IPO_MULTICAST_IF = 0x0009; private const int SOCK_IPO_MULTICAST_TTL = 0x000A; private const int SOCK_IPO_MULTICAST_LOOP = 0x000B; private const int SOCK_IPO_ADD_MEMBERSHIP = 0x000C; private const int SOCK_IPO_DROP_MEMBERSHIP = 0x000D; private const int SOCK_IPO_IP_DONTFRAGMENT = 0x000E; private const int SOCK_IPO_ADD_SOURCE_MEMBERSHIP = 0x000F; private const int SOCK_IPO_DROP_SOURCE_MEMBERSHIP = 0x0010; private const int SOCK_IPO_BLOCK_SOURCE = 0x0011; private const int SOCK_IPO_UBLOCK_SOURCE = 0x0012; private const int SOCK_IPO_PACKET_INFO = 0x0013; private const int SOCK_SOCKET_ERROR = -1; //--// //--// //--// public override int socket(int family, int type, int protocol) { return SocketNative.LLOS_lwip_socket(family, type, protocol); } public override int bind(int socket, byte[] address) { return SocketNative.LLOS_lwip_bind(socket, address); } public unsafe override int connect(int socket, byte[] address, bool fThrowOnWouldBlock) { fixed (byte* addressPtr = address) { return SocketNative.LLOS_lwip_connect(socket, addressPtr, fThrowOnWouldBlock); } } public unsafe override int send(int socket, byte[] buf, int offset, int count, int flags, int timeout_ms) { fixed (byte* buffer = &buf[offset]) { return SocketNative.LLOS_lwip_send(socket, buffer, count, flags, timeout_ms); } } public unsafe override int recv(int socket, byte[] buf, int offset, int count, int flags, int timeout_ms) { fixed (byte* buffer = &buf[offset]) { return SocketNative.LLOS_lwip_recv(socket, buffer, count, flags, timeout_ms); } } public override int close(int socket) { return SocketNative.LLOS_lwip_close(socket); } public override int listen(int socket, int backlog) { return SocketNative.LLOS_lwip_listen(socket, backlog); } public unsafe override int accept(int socket) { byte[] address = new byte[20]; uint* pAddrlen = null; fixed(byte* pAddress = address) { return SocketNative.LLOS_lwip_accept(socket, pAddress, pAddrlen); } } // // No standard non-blocking api // public unsafe override int getaddrinfo(string name, out string canonicalName, out byte[][] addresses) { byte[] canonicalNameArr = new byte[256]; // We know this will be the size of the address object byte[] addressArr = new byte[16]; int result; fixed (char* pName = name.ToCharArray()) { fixed (byte* pCanonicalName = canonicalNameArr) { fixed (byte* pAddress = addressArr) { result = SocketNative.LLOS_lwip_getaddrinfo(pName, (uint)name.Length, pCanonicalName, (uint)canonicalNameArr.Length, pAddress, (uint)addressArr.Length); } } } if(result < 0) { // The format of address in addressArr may not be what DNS wants. Need to verify canonicalName = null; addresses = null; addresses[0] = null; return result; } // The format of address in addressArr may not be what DNS wants. Need to verify canonicalName = ASCIIEncoding.ASCII.GetString(canonicalNameArr); addresses = new byte[1][]; addresses[0] = addressArr; return result; } public unsafe override void shutdown(int socket, int how, out int err) { err = SocketNative.LLOS_lwip_shutdown(socket, how); } public unsafe override int sendto(int socket, byte[] buf, int offset, int count, int flags, int timeout_ms, byte[] address) { fixed(byte* pBuf = &buf[offset]) { fixed(byte* pAddress = address) { return SocketNative.LLOS_lwip_sendto(socket, pBuf, count, flags, timeout_ms, pAddress, (uint)address.Length); } } } public unsafe override int recvfrom(int socket, byte[] buf, int offset, int count, int flags, int timeout_ms, ref byte[] address) { uint fromlen = (uint)address.Length; fixed (byte* pBuf = &buf[offset]) { fixed (byte* pAddress = address) { return SocketNative.LLOS_lwip_recvfrom(socket, pBuf, count, flags, timeout_ms, pAddress, &fromlen); } } } public unsafe override int getpeername(int socket, out byte[] address) { uint namelen = 20; byte[] addressBuffer = new byte[namelen]; int result; fixed(byte* pAddress = addressBuffer) { result = SocketNative.LLOS_lwip_getpeername(socket, pAddress, &namelen); } if(result < 0) { address = null; return result; } address = new byte[namelen]; Array.Copy(addressBuffer, address, (int)namelen); return result; } public unsafe override int getsockname(int socket, out byte[] address) { uint namelen = 20; byte[] addressBuffer = new byte[namelen]; int result; fixed (byte* pAddress = addressBuffer) { result = SocketNative.LLOS_lwip_getsockname(socket, pAddress, &namelen); } if (result < 0) { address = null; return result; } address = new byte[namelen]; Array.Copy(addressBuffer, address, (int)namelen); return result; } public unsafe override int getsockopt(int socket, int level, int optname, byte[] optval, out uint optlen) { int nativeOptionName; int nativeLevel; switch(level) { case SOCK_IPPROTO_IP: nativeLevel = IPPROTO_IP; nativeOptionName = GetNativeIPOption(optname); break; case SOCK_IPPROTO_TCP: nativeLevel = IPPROTO_TCP; nativeOptionName = GetNativeTcpOption(optname); break; case SOCK_IPPROTO_UDP: case SOCK_IPPROTO_ICMP: case SOCK_IPPROTO_IGMP: case SOCK_IPPROTO_IPV4: case SOCK_SOL_SOCKET: nativeLevel = SOL_SOCKET; nativeOptionName = GetNativeSockOption(optname); switch(optname) { // LINGER is not implemented in LWIP case SOCK_SOCKO_LINGER: optval[0] = 0; optlen = 1; return 0; case SOCK_SOCKO_DONTLINGER: optval[0] = 1; optlen = 1; return 0; default: break; } break; default: nativeLevel = level; nativeOptionName = optname; break; } uint optlenInternal = (uint)optval.Length; int result; fixed (byte* pNativeOptval = optval) { result = SocketNative.LLOS_lwip_getsockopt( socket, nativeLevel, nativeOptionName, pNativeOptval, &optlenInternal ); optlen = optlenInternal; if(result == 0) { switch(level) { case SOCK_SOL_SOCKET: switch(optname) { case SOCK_SOCKO_EXCLUSIVEADDRESSUSE: optval[0] = (!( *(int*)pNativeOptval != 0 ) == true) ? (byte)1 : (byte)0; optlen = 1; break; case SOCK_SOCKO_ACCEPTCONNECTION: case SOCK_SOCKO_BROADCAST: case SOCK_SOCKO_KEEPALIVE: optval[0] = (( *(int*)pNativeOptval != 0 ) == true ) ? (byte)1 : (byte)0; optlen = 1; break; } break; } } } return result; } public unsafe override int setsockopt( int socket, int level, int optname, byte[] optval ) { int nativeLevel; int nativeOptionName; int nativeIntValue; fixed (byte* pNativeOptionValue = optval) { switch(level) { case SOCK_IPPROTO_IP: nativeLevel = IPPROTO_IP; nativeOptionName = GetNativeIPOption( optname ); break; case SOCK_IPPROTO_TCP: nativeLevel = IPPROTO_TCP; nativeOptionName = GetNativeTcpOption( optname ); break; case SOCK_IPPROTO_UDP: case SOCK_IPPROTO_ICMP: case SOCK_IPPROTO_IGMP: case SOCK_IPPROTO_IPV4: case SOCK_SOL_SOCKET: nativeLevel = SOL_SOCKET; nativeOptionName = GetNativeSockOption( optname ); switch(optname) { // LINGER is not implemented in LWIP case SOCK_SOCKO_LINGER: if(*(int*)pNativeOptionValue != 0) { //errno = SOCK_ENOPROTOOPT; return SOCK_SOCKET_ERROR; } return 0; case SOCK_SOCKO_DONTLINGER: if(*(int*)pNativeOptionValue == 0) { //errno = SOCK_ENOPROTOOPT; return SOCK_SOCKET_ERROR; } return 0; // ignore this item to enable http to work case SOCK_SOCKO_REUSEADDRESS: return 0; case SOCK_SOCKO_EXCLUSIVEADDRESSUSE: nativeIntValue = *(int*)&pNativeOptionValue[0] == 0 ? 1 : 0; optval[ 0 ] = (byte)nativeIntValue; //pNativeOptionValue = (char*)&nativeIntValue; break; default: break; } break; default: nativeLevel = 0; nativeOptionName = 0; break; } return SocketNative.LLOS_lwip_setsockopt( socket, nativeLevel, nativeOptionName, pNativeOptionValue, (uint)optval.Length ); } } public unsafe override bool poll(int socket, int mode, int microSeconds) { return SocketNative.LLOS_lwip_poll(socket, mode, microSeconds); } public unsafe override int ioctl(int socket, uint cmd, ref uint arg) { fixed (uint* pArg = &arg) { return SocketNative.LLOS_lwip_ioctl(socket, cmd, pArg); } } //--// //--// //--// static private int GetNativeTcpOption( int optname ) { int nativeOptionName = 0; switch(optname) { case SOCK_TCP_NODELAY: nativeOptionName = TCP_NODELAY; break; case SOCK_SOCKO_KEEPALIVE: nativeOptionName = TCP_KEEPALIVE; break; // allow the C# user to specify LWIP options that our managed enum // doesn't support default: nativeOptionName = optname; break; } return nativeOptionName; } static private int GetNativeSockOption( int optname ) { int nativeOptionName = 0; switch(optname) { case SOCK_SOCKO_DONTLINGER: case SOCK_SOCKO_LINGER: nativeOptionName = SO_LINGER; break; case SOCK_SOCKO_SENDTIMEOUT: nativeOptionName = SO_SNDTIMEO; break; case SOCK_SOCKO_RECEIVETIMEOUT: nativeOptionName = SO_RCVTIMEO; break; case SOCK_SOCKO_EXCLUSIVEADDRESSUSE: case SOCK_SOCKO_REUSEADDRESS: nativeOptionName = SO_REUSEADDR; break; case SOCK_SOCKO_KEEPALIVE: nativeOptionName = SO_KEEPALIVE; break; case SOCK_SOCKO_ERROR: nativeOptionName = SO_ERROR; break; case SOCK_SOCKO_BROADCAST: nativeOptionName = SO_BROADCAST; break; case SOCK_SOCKO_RECEIVEBUFFER: nativeOptionName = SO_RCVBUF; break; case SOCK_SOCKO_SENDBUFFER: nativeOptionName = SO_SNDBUF; break; case SOCK_SOCKO_ACCEPTCONNECTION: nativeOptionName = SO_ACCEPTCONN; break; case SOCK_SOCKO_TYPE: nativeOptionName = SO_TYPE; break; case SOCK_SOCKO_USELOOPBACK: nativeOptionName = SO_USELOOPBACK; break; case SOCK_SOCKO_DONTROUTE: nativeOptionName = SO_DONTROUTE; break; case SOCK_SOCKO_OUTOFBANDINLINE: nativeOptionName = SO_OOBINLINE; break; case SOCK_SOCKO_DEBUG: nativeOptionName = SO_DEBUG; break; case SOCK_SOCKO_SENDLOWWATER: nativeOptionName = SO_SNDLOWAT; break; case SOCK_SOCKO_RECEIVELOWWATER: nativeOptionName = SO_RCVLOWAT; break; // case SOCK_SOCKO_MAXCONNECTIONS: //don't support case SOCK_SOCKO_UPDATE_ACCEPT_CTX: case SOCK_SOCKO_UPDATE_CONNECT_CTX: nativeOptionName = 0; break; // allow the C# user to specify LWIP options that our managed enum // doesn't support default: nativeOptionName = optname; break; } return nativeOptionName; } static private int GetNativeIPOption( int optname ) { int nativeOptionName = 0; switch(optname) { case SOCK_IPO_TTL: nativeOptionName = IP_TTL; break; case SOCK_IPO_TOS: nativeOptionName = IP_TOS; break; #if LWIP_IGMP case SOCK_IPO_MULTICAST_IF: nativeOptionName = IP_MULTICAST_IF; break; case SOCK_IPO_MULTICAST_TTL: nativeOptionName = IP_MULTICAST_TTL; break; case SOCK_IPO_MULTICAST_LOOP: nativeOptionName = IP_MULTICAST_LOOP; break; case SOCK_IPO_ADD_MEMBERSHIP: nativeOptionName = IP_ADD_MEMBERSHIP; break; case SOCK_IPO_DROP_MEMBERSHIP: nativeOptionName = IP_DROP_MEMBERSHIP; break; #else case SOCK_IPO_MULTICAST_IF: case SOCK_IPO_MULTICAST_TTL: case SOCK_IPO_MULTICAST_LOOP: case SOCK_IPO_ADD_MEMBERSHIP: case SOCK_IPO_DROP_MEMBERSHIP: #endif case SOCK_IPO_ADD_SOURCE_MEMBERSHIP: case SOCK_IPO_DROP_SOURCE_MEMBERSHIP: case SOCK_IPO_OPTIONS: case SOCK_IPO_HDRINCL: case SOCK_IPO_IP_DONTFRAGMENT: case SOCK_IPO_BLOCK_SOURCE: case SOCK_IPO_UBLOCK_SOURCE: case SOCK_IPO_PACKET_INFO: nativeOptionName = 0; break; // allow the C# user to specify LWIP options that our managed enum // doesn't support default: nativeOptionName = optname; break; } return nativeOptionName; } } } ================================================ FILE: Zelig/Zelig/RunTime/DeviceModels/CortexM3OnMBED/HardwareModel/HardwareProviders/SpiProvider.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // namespace Microsoft.CortexM3OnMBED.HardwareModel { using ChipsetModel = Microsoft.CortexM0OnMBED; public abstract class SpiProvider : ChipsetModel.HardwareModel.SpiProvider { } } ================================================ FILE: Zelig/Zelig/RunTime/DeviceModels/CortexM3OnMBED/HardwareModel/Memory.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // namespace Microsoft.CortexM3OnMBED { using System; using RT = Microsoft.Zelig.Runtime; using ChipsetModel = Microsoft.CortexM0OnMBED; public class Memory : ChipsetModel.Memory { } } ================================================ FILE: Zelig/Zelig/RunTime/DeviceModels/CortexM3OnMBED/HardwareModel/Peripherals.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // //#define ALLOW_PAUSE namespace Microsoft.CortexM3OnMBED { using RT = Microsoft.Zelig.Runtime; using ChipsetModel = Microsoft.CortexM0OnMBED; using CMSIS = Microsoft.DeviceModels.Chipset.CortexM; using ARMv7 = Microsoft.Zelig.Runtime.TargetPlatform.ARMv7; public abstract class Peripherals : ChipsetModel.Peripherals { public override void Initialize() { RT.BugCheck.AssertInterruptsOff(); // // Faults, never disabled // // nothing to do, on an M0/1 faults are always enabled // // System exceptions // CMSIS.NVIC.SetPriority( (int)ARMv7.ProcessorARMv7M.IRQn_Type.SVCall_IRQn , ARMv7.ProcessorARMv7M.c_Priority__SVCCall ); CMSIS.NVIC.SetPriority( (int)ARMv7.ProcessorARMv7M.IRQn_Type.SysTick_IRQn, ARMv7.ProcessorARMv7M.c_Priority__SysTick ); CMSIS.NVIC.SetPriority( (int)ARMv7.ProcessorARMv7M.IRQn_Type.PendSV_IRQn , ARMv7.ProcessorARMv7M.c_Priority__PendSV ); } public override void WaitForInterrupt() { ARMv7.ProcessorARMv7M.WaitForInterrupt( ); } public override void CauseInterrupt() { ARMv7.ProcessorARMv7M.CompleteContextSwitch( ); } } } ================================================ FILE: Zelig/Zelig/RunTime/DeviceModels/CortexM3OnMBED/HardwareModel/Processor.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // //#define THREADING_RTOS namespace Microsoft.CortexM3OnMBED { using System; using System.Runtime.InteropServices; using RT = Microsoft.Zelig.Runtime; using ChipsetModel = Microsoft.CortexM3OnCMSISCore; using RTOS = Microsoft.Zelig.Support.mbed; public abstract class Processor : ChipsetModel.Processor { public new abstract class Context : ChipsetModel.Processor.Context { #if THREADING_RTOS // // State // protected UIntPtr m_nativeContext; #endif //--// public Context(RT.ThreadImpl owner) : base(owner) { } // // Extensiblity // #if THREADING_RTOS public override void SwitchTo() { // // When running on a RTOS, we will request the underlying system to choose the next thread // basedon our indications. Need to solve priority and lock contention issues, e.g. priority inversion // issues. // RTOS.Threading.SwitchToContext( m_nativeContext ); } #endif // // RTOS Extensibility // protected override UIntPtr CreateNativeContext( UIntPtr entryPoint, UIntPtr stack, int stackSize ) { return RTOS.Threading.CreateNativeContext( entryPoint, stack, stackSize ); } protected override void SwitchToContext( UIntPtr nativeContext ) { RTOS.Threading.SwitchToContext( nativeContext ); } protected override void Yield( UIntPtr nativeContext ) { RTOS.Threading.Yield( nativeContext ); } protected override void Retire( UIntPtr nativeContext ) { RTOS.Threading.Retire( nativeContext ); } } //--// #if THREADING_RTOS [RT.Inline] public override Microsoft.Zelig.Runtime.Processor.Context AllocateProcessorContext() { return new Context(); } #endif // // Access methods // public static ulong CoreClockFrequency { [RT.ConfigurationOption("System__CoreClockFrequency")] get { RT.BugCheck.Assert( false, RT.BugCheck.StopCode.IllegalConfiguration ); return 0; } } public static ulong RealTimeClockFrequency { [RT.ConfigurationOption("System__RealTimeClockFrequency")] get { RT.BugCheck.Assert( false, RT.BugCheck.StopCode.IllegalConfiguration ); return 0; } } public static uint DefaultThreadPoolThreads { [RT.ConfigurationOption( "System__Runtime_DefaultThreadPoolThreads" )] get { RT.BugCheck.Assert( false, RT.BugCheck.StopCode.IllegalConfiguration ); return 2; } } public static uint DefaultTimerPoolThreads { [RT.ConfigurationOption( "System__Runtime_DefaultThreadPoolThreads" )] get { RT.BugCheck.Assert( false, RT.BugCheck.StopCode.IllegalConfiguration ); return 1; } } //--// //////[RT.BottomOfCallStack()] //////[RT.HardwareExceptionHandler(RT.HardwareException.Interrupt)] //////private static void InterruptHandler( UIntPtr stackPtr ) //////{ ////// s_repeatedAbort = false; ////// Context.InterruptHandlerWithContextSwitch( ref stackPtr ); //////} //--// [RT.NoInline] [RT.NoReturn( )] [RT.HardwareExceptionHandler( RT.HardwareException.UndefinedInstruction )] [RT.MemoryUsage( RT.MemoryUsage.Bootstrap )] static void UndefinedInstruction( ) { //////RT.Processor.Instance.Breakpoint(); while(true) { } } [RT.NoInline] [RT.NoReturn( )] [RT.HardwareExceptionHandler( RT.HardwareException.PrefetchAbort )] [RT.MemoryUsage( RT.MemoryUsage.Bootstrap )] static void PrefetchAbort( ) { //////RT.Processor.Instance.Breakpoint(); while(true) { } } private static bool s_repeatedAbort = false; private static int s_abortCount = 0; [RT.NoInline] [RT.NoReturn( )] [RT.HardwareExceptionHandler( RT.HardwareException.DataAbort )] [RT.MemoryUsage( RT.MemoryUsage.Bootstrap )] static void DataAbort( ) { //////bool repeatedAbort = s_repeatedAbort; //////s_repeatedAbort = true; //////s_abortCount++; //////if (repeatedAbort) //////RT.Processor.Instance.Breakpoint(); while(true) { } } } } ================================================ FILE: Zelig/Zelig/RunTime/DeviceModels/CortexM3OnMBED/HardwareModel/Storage.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // namespace Microsoft.CortexM3OnMBED { using System; using RT = Microsoft.Zelig.Runtime; using ChipsetModel = Microsoft.CortexM0OnMBED; public class Storage : ChipsetModel.Storage { } } ================================================ FILE: Zelig/Zelig/RunTime/DeviceModels/CortexM3OnMBED/Properties/AssemblyInfo.cs ================================================ using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; // General Information about an assembly is controlled through the following // set of attributes. Change these attribute values to modify the information // associated with an assembly. [assembly: AssemblyTitle( "Microsoft.CortexM3OnMBED" )] [assembly: AssemblyDescription( "" )] [assembly: AssemblyConfiguration( "" )] [assembly: AssemblyCompany( "Microsoft" )] [assembly: AssemblyProduct( "LLILUM" )] [assembly: AssemblyCopyright( "Copyright © Microsoft 2015" )] [assembly: AssemblyTrademark( "" )] [assembly: AssemblyCulture( "" )] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible( false )] // The following GUID is for the ID of the typelib if this project is exposed to COM //[assembly: Guid( "ffacd01c-fa64-4234-9058-1ad866f88c1a" )] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Build and Revision Numbers // by using the '*' as shown below: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion( "1.0.0.0" )] [assembly: AssemblyFileVersion( "1.0.0.0" )] ================================================ FILE: Zelig/Zelig/RunTime/DeviceModels/CortexM3OnMBED/SystemServices/GarbageCollectionManager.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // namespace Microsoft.CortexM3OnMBED { using ChipsetModel = Microsoft.CortexM0OnMBED; public abstract class GarbageCollectionManager : ChipsetModel.GarbageCollectionManager { } } ================================================ FILE: Zelig/Zelig/RunTime/DeviceModels/CortexM3OnMBED/SystemServices/MemoryManager.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // namespace Microsoft.CortexM3OnMBED { using ChipsetModel = Microsoft.CortexM0OnMBED; public class MemoryManager : ChipsetModel.MemoryManager { } } ================================================ FILE: Zelig/Zelig/RunTime/DeviceModels/CortexM3OnMBED/SystemServices/ThreadManager.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // namespace Microsoft.CortexM3OnMBED { using System; using RT = Microsoft.Zelig.Runtime; using HAL = Microsoft.Zelig.LlilumOSAbstraction.HAL; using ARMv7 = Microsoft.Zelig.Runtime.TargetPlatform.ARMv7; using ChipsetModel = Microsoft.CortexM3OnCMSISCore; public abstract class ThreadManager : ChipsetModel.ThreadManager { // // State // // // BUGBUG: we need to Dispose this object on shutdown !!! // protected Drivers.SystemTimer.Timer m_timerForWaits; protected RT.ThreadImpl m_exceptionThread; //--// // // Helper methods // public override void InitializeAfterStaticConstructors( uint[] systemStack ) { base.InitializeAfterStaticConstructors( systemStack ); // // The exception thread wraps the main stack pointer // m_exceptionThread = new RT.ThreadImpl( RT.Bootstrap.Initialization, GetMainStack( ) ); // // The msp thread is never started, so we have to manually register them, to enable the debugger to see them. // RegisterThread(m_exceptionThread); //--// m_exceptionThread.SetupForExceptionHandling( unchecked((uint)ARMv7.ProcessorARMv7M.IRQn_Type.Reset_IRQn) ); } public override void Activate() { base.Activate(); m_timerForWaits = Drivers.SystemTimer.Instance.CreateTimer(WaitExpired); DeviceModels.Chipset.CortexM0.Drivers.InterruptController.Instance.Activate(); } public override void SetNextWaitTimer(RT.SchedulerTime nextTimeout) { if (nextTimeout != RT.SchedulerTime.MaxValue) { m_timerForWaits.Timeout = nextTimeout.Units; } else { m_timerForWaits.Cancel(); } } // // Access methods // public override RT.ThreadImpl InterruptThread { get { return m_exceptionThread; } } public override RT.ThreadImpl FastInterruptThread { get { return m_exceptionThread; } } public override RT.ThreadImpl AbortThread { get { return m_exceptionThread; } } //--// protected void WaitExpired(Drivers.SystemTimer.Timer sysTickTimer, ulong currentTime) { WaitExpired(RT.SchedulerTime.FromUnits(currentTime)); } protected uint[] GetMainStack() { // // The main stack address will have to have at least additional 12 bytes // to inject the ObjectHeader and the ArrayImpl members. // TODO: find a better way to keep this in sync with ArrayImpl. // uint correction = RT.MemoryFreeBlock.FixedSize(); RT.BugCheck.Assert( correction == 12, RT.BugCheck.StopCode.StackCorruptionDetected ); uint stackAddress = HAL.Thread.LLOS_THREAD_GetMainStackAddress( ) - correction; uint stackSize = HAL.Thread.LLOS_THREAD_GetMainStackSize( ); return RT.ArrayImpl.InitializeFromRawMemory( new UIntPtr( stackAddress ), stackSize ); } } } ================================================ FILE: Zelig/Zelig/RunTime/DeviceModels/CortexM3OnMBED/SystemServices/TimerPool.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // namespace Microsoft.CortexM3OnMBED { using Chipset = Microsoft.CortexM3OnCMSISCore; public abstract class TimerPool : Chipset.TimerPool { } } ================================================ FILE: Zelig/Zelig/RunTime/DeviceModels/CortexM3OnMBED/SystemServices/TypeSystemManager.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // namespace Microsoft.CortexM3OnMBED { using ChipsetModel = Microsoft.CortexM0OnMBED; public class TypeSystemManager : ChipsetModel.TypeSystemManager { } } ================================================ FILE: Zelig/Zelig/RunTime/DeviceModels/CortexM4OnCMSIS-Core/CortexM4OnCMSIS-Core.csproj ================================================  Debug AnyCPU 9.0.21022 2.0 {7FB3F581-742D-4E12-A36A-BE172C574AB0} Library Properties Microsoft.CortexM4OnCMSISCore Microsoft.CortexM4OnCMSISCore $(LlilumBuildRoot)\Target\obj\$(MSBuildProjectName)\ v4.5 512 true full false $(LlilumBuildRoot)\Target\bin\$(Configuration)\ DEBUG;TRACE prompt 4 true true true AllRules.ruleset AnyCPU false pdbonly true $(LlilumBuildRoot)\Target\bin\$(Configuration)\ TRACE prompt 4 true true true AllRules.ruleset AnyCPU false {186F31A3-EF89-4A25-B2D5-20060501AA01} mscorlib False {186F31A3-EF89-4A25-B2D5-20061218AA01} Common False {186F31A3-EF89-4A25-B2D5-20060509AA01} Kernel False {186F31A3-EF89-4A25-B2D5-20060720AA01} TypeSystem False {186f31a3-ef89-4a25-b2d5-20070702aa01} system False {0b37e5ba-4839-4ec4-9e36-a96bcbea2400} CortexM3OnCMSIS-Core {a30eb003-94f8-4a85-8da1-006f6810a7a4} ModelForCortexM3 {ca8a6d38-528b-4faa-89b6-8fa9178de55d} ModelForCortexM4 {20DC2CF5-8EED-4231-9743-6BAB96BE465C} LlilumOSAbstraction {c3bfafad-a6c6-471d-a059-b3cb7e57a4ab} ModelForCortexM0 {e4c618af-1785-472e-a070-8068e20582eb} ModelForCortexM ================================================ FILE: Zelig/Zelig/RunTime/DeviceModels/CortexM4OnCMSIS-Core/HardwareModel/Board.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // namespace Microsoft.CortexM4OnCMSISCore { using System.Runtime.CompilerServices; using RT = Microsoft.Zelig.Runtime; using ChipsetModel = Microsoft.CortexM3OnCMSISCore; public abstract class Board : ChipsetModel.Board { } } ================================================ FILE: Zelig/Zelig/RunTime/DeviceModels/CortexM4OnCMSIS-Core/HardwareModel/Device.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // namespace Microsoft.CortexM4OnCMSISCore { using RT = Microsoft.Zelig.Runtime; using Chipset = Microsoft.CortexM3OnCMSISCore; public abstract class Device : Chipset.Device { } } ================================================ FILE: Zelig/Zelig/RunTime/DeviceModels/CortexM4OnCMSIS-Core/HardwareModel/Drivers/ContextSwitchTimer.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // namespace Microsoft.CortexM4OnCMSISCore.Drivers { using Chipset = Microsoft.CortexM3OnCMSISCore.Drivers; public abstract class ContextSwitchTimer : Chipset.ContextSwitchTimer { } } ================================================ FILE: Zelig/Zelig/RunTime/DeviceModels/CortexM4OnCMSIS-Core/HardwareModel/Drivers/InterruptController.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // namespace Microsoft.CortexM4OnCMSISCore.Drivers { using Chipset = Microsoft.CortexM3OnCMSISCore.Drivers; public abstract class InterruptController : Chipset.InterruptController { } } ================================================ FILE: Zelig/Zelig/RunTime/DeviceModels/CortexM4OnCMSIS-Core/HardwareModel/HardwareProvider.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // namespace Microsoft.CortexM4OnCMSISCore { using RT = Microsoft.Zelig.Runtime; using Chipset = Microsoft.CortexM3OnCMSISCore; //--// public abstract class HardwareProvider : Chipset.HardwareProvider { } } ================================================ FILE: Zelig/Zelig/RunTime/DeviceModels/CortexM4OnCMSIS-Core/HardwareModel/Memory.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // namespace Microsoft.CortexM4OnCMSISCore { using Chipset = Microsoft.CortexM3OnCMSISCore; public abstract class Memory : Chipset.Memory { } } ================================================ FILE: Zelig/Zelig/RunTime/DeviceModels/CortexM4OnCMSIS-Core/HardwareModel/Peripherals.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // //#define ALLOW_PAUSE namespace Microsoft.CortexM4OnCMSISCore { using Chipset = Microsoft.CortexM3OnCMSISCore; public abstract class Peripherals : Chipset.Peripherals { } } ================================================ FILE: Zelig/Zelig/RunTime/DeviceModels/CortexM4OnCMSIS-Core/HardwareModel/Processor.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // namespace Microsoft.CortexM4OnCMSISCore { using System; using RT = Microsoft.Zelig.Runtime; using ChipsetModel = Microsoft.DeviceModels.Chipset.CortexM4; using CortexM = Microsoft.DeviceModels.Chipset.CortexM; using LLOS = Zelig.LlilumOSAbstraction.HAL; public abstract class Processor : ChipsetModel.Processor { public abstract new class Context : RT.TargetPlatform.ARMv7.ProcessorARMv7MForLlvm_VFP.Context { // // Constructor Methods // public Context(RT.ThreadImpl owner) : base(owner) { } // // Helper Methods // #region RTOS extensibility protected virtual UIntPtr CreateNativeContext( UIntPtr entryPoint, UIntPtr stack, int stackSize ) { return (UIntPtr)0; } protected virtual void SwitchToContext( UIntPtr thread ) { } protected virtual void Yield( UIntPtr handle ) { } protected virtual void Retire( UIntPtr handle ) { } #endregion // // Access Methods // } // // Helper Methods // public override void InitializeProcessor() { base.InitializeProcessor(); // // Reset the priority grouping that we assume not used // CortexM.NVIC.SetPriorityGrouping( 0 ); } protected override unsafe void RemapInterrupt( IRQn_Type IRQn, Action isr ) { RT.DelegateImpl dlg = (RT.DelegateImpl)(object)isr; UIntPtr isrPtr = new UIntPtr( dlg.InnerGetCodePointer().Target.ToPointer() ); CortexM.NVIC.SetVector( (int)IRQn, isrPtr.ToUInt32() ); } } //--// //--// //--// [RT.ExtendClass( typeof( Microsoft.Zelig.Runtime.Processor ) )] internal class ProcessorImpl { [RT.MergeWithTargetImplementation] internal ProcessorImpl() { } [RT.NoInline] [RT.MemoryUsage( RT.MemoryUsage.Bootstrap )] public static int Delay( int count ) { LLOS.Clock.LLOS_CLOCK_DelayCycles( (uint)count ); return 0; } } } ================================================ FILE: Zelig/Zelig/RunTime/DeviceModels/CortexM4OnCMSIS-Core/HardwareModel/Storage.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // namespace Microsoft.CortexM4OnCMSISCore { using System; using RT = Microsoft.Zelig.Runtime; using Chipset = Microsoft.CortexM3OnCMSISCore; public abstract class Storage : Chipset.Storage { } } ================================================ FILE: Zelig/Zelig/RunTime/DeviceModels/CortexM4OnCMSIS-Core/Properties/AssemblyInfo.cs ================================================ using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; // General Information about an assembly is controlled through the following // set of attributes. Change these attribute values to modify the information // associated with an assembly. [assembly: AssemblyTitle( "Microsoft.CortexM3OnCMSISCore" )] [assembly: AssemblyDescription( "" )] [assembly: AssemblyConfiguration( "" )] [assembly: AssemblyCompany( "Microsoft" )] [assembly: AssemblyProduct( "Microsoft.CortexM3OnCMSISCore" )] [assembly: AssemblyCopyright( "Copyright © Microsoft 2015" )] [assembly: AssemblyTrademark( "" )] [assembly: AssemblyCulture( "" )] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible( false )] // The following GUID is for the ID of the typelib if this project is exposed to COM //[assembly: Guid( "ffacd01c-fa64-4234-9058-1ad866f88c1a" )] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Build and Revision Numbers // by using the '*' as shown below: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion( "1.0.0.0" )] [assembly: AssemblyFileVersion( "1.0.0.0" )] ================================================ FILE: Zelig/Zelig/RunTime/DeviceModels/CortexM4OnCMSIS-Core/SystemServices/GarbageCollectionManager.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // namespace Microsoft.CortexM4OnCMSISCore { using Chipset = Microsoft.CortexM3OnCMSISCore; public abstract class GarbageCollectionManager : Chipset.GarbageCollectionManager { } } ================================================ FILE: Zelig/Zelig/RunTime/DeviceModels/CortexM4OnCMSIS-Core/SystemServices/MemoryManager.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // namespace Microsoft.CortexM4OnCMSISCore { using System; using RT = Microsoft.Zelig.Runtime; using Chipset = Microsoft.CortexM3OnCMSISCore; public abstract class MemoryManager : Chipset.MemoryManager { } } ================================================ FILE: Zelig/Zelig/RunTime/DeviceModels/CortexM4OnCMSIS-Core/SystemServices/ThreadManager.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // namespace Microsoft.CortexM4OnCMSISCore { using RT = Microsoft.Zelig.Runtime; using Chipset = Microsoft.CortexM3OnCMSISCore; public abstract class ThreadManager : Chipset.ThreadManager { } } ================================================ FILE: Zelig/Zelig/RunTime/DeviceModels/CortexM4OnCMSIS-Core/SystemServices/TimerPool.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // namespace Microsoft.CortexM4OnCMSISCore { using RT = Microsoft.Zelig.Runtime; public abstract class TimerPool : RT.TimerImpl.UnboundedAsynchTimerPool { } } ================================================ FILE: Zelig/Zelig/RunTime/DeviceModels/CortexM4OnCMSIS-Core/SystemServices/TypeSystemManager.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // namespace Microsoft.CortexM4OnCMSISCore { using System; using RT = Microsoft.Zelig.Runtime; public abstract class TypeSystemManager : Microsoft.CortexM3OnCMSISCore.TypeSystemManager { } } ================================================ FILE: Zelig/Zelig/RunTime/DeviceModels/CortexM4OnMBED/CortexM4OnMBED.csproj ================================================  Debug AnyCPU 9.0.21022 2.0 {65C8EDA6-AC24-4E18-A5B5-216E0F2C3906} Library Properties Microsoft.CortexM4OnMBED Microsoft.CortexM4OnMBED $(LlilumBuildRoot)\Target\obj\$(MSBuildProjectName)\ v4.5 512 true full false $(LlilumBuildRoot)\Target\bin\$(Configuration)\ DEBUG;TRACE prompt 4 true true true AllRules.ruleset AnyCPU false pdbonly true $(LlilumBuildRoot)\Target\bin\$(Configuration)\ TRACE prompt 4 true true true AllRules.ruleset AnyCPU false {186F31A3-EF89-4A25-B2D5-20060501AA01} mscorlib False {186F31A3-EF89-4A25-B2D5-20061218AA01} Common False {186F31A3-EF89-4A25-B2D5-20060509AA01} Kernel False {186F31A3-EF89-4A25-B2D5-20060720AA01} TypeSystem False {d68ee51b-a898-4a77-97d8-c61254cac122} Microsoft.Llilum.Devices {186f31a3-ef89-4a25-b2d5-20070702aa01} system False {dc8c38d7-780b-4b13-8ace-9050e39cc51c} Windows {0b37e5ba-4839-4ec4-9e36-a96bcbea2400} CortexM3OnCMSIS-Core {0c522c6a-0f77-4af8-ad78-5b2415c98c51} CortexM3OnMBED {7fb3f581-742d-4e12-a36a-be172c574ab0} CortexM4OnCMSIS-Core {20DC2CF5-8EED-4231-9743-6BAB96BE465C} LlilumOSAbstraction {d7f2bc4e-1406-47aa-90e1-07bc4ce9410f} mbed {a30eb003-94f8-4a85-8da1-006f6810a7a4} ModelForCortexM3 {ca8a6d38-528b-4faa-89b6-8fa9178de55d} ModelForCortexM4 {B8FE271A-CD41-435E-8766-4DB7609C1007} CortexM0OnCMSIS-Core {89EBDBB0-C81F-4611-B719-B385DF215F8D} CortexM0OnMBED {C3BFAFAD-A6C6-471D-A059-B3CB7E57A4AB} ModelForCortexM0 {e4c618af-1785-472e-a070-8068e20582eb} ModelForCortexM ================================================ FILE: Zelig/Zelig/RunTime/DeviceModels/CortexM4OnMBED/HardwareModel/Board.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // namespace Microsoft.CortexM4OnMBED { using Chipset = Microsoft.CortexM3OnMBED; public abstract class Board : Chipset.Board { } } ================================================ FILE: Zelig/Zelig/RunTime/DeviceModels/CortexM4OnMBED/HardwareModel/Device.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // namespace Microsoft.CortexM4OnMBED { using Chipset = Microsoft.CortexM3OnMBED; public abstract class Device : Chipset.Device { } } ================================================ FILE: Zelig/Zelig/RunTime/DeviceModels/CortexM4OnMBED/HardwareModel/Drivers/InterruptController.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // namespace Microsoft.CortexM4OnMBED.Drivers { using Chipset = Microsoft.CortexM3OnMBED; public abstract class InterruptController : Chipset.Drivers.InterruptController { } } ================================================ FILE: Zelig/Zelig/RunTime/DeviceModels/CortexM4OnMBED/HardwareModel/Drivers/SystemTimer.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // namespace Microsoft.CortexM4OnMBED.Drivers { public abstract class SystemTimer : Microsoft.CortexM3OnMBED.Drivers.SystemTimer { } } ================================================ FILE: Zelig/Zelig/RunTime/DeviceModels/CortexM4OnMBED/HardwareModel/HardwareProvider.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // namespace Microsoft.CortexM4OnMBED.HardwareModel { using Chipset = Microsoft.CortexM3OnMBED; public sealed class HardwareProvider : Chipset.HardwareModel.HardwareProvider { } } ================================================ FILE: Zelig/Zelig/RunTime/DeviceModels/CortexM4OnMBED/HardwareModel/HardwareProviders/GpioProvider.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // namespace Microsoft.CortexM4OnMBED.HardwareModel { using ChipsetModel = Microsoft.CortexM3OnMBED; public abstract class GpioProvider : ChipsetModel.HardwareModel.GpioProvider { } } ================================================ FILE: Zelig/Zelig/RunTime/DeviceModels/CortexM4OnMBED/HardwareModel/HardwareProviders/I2cProvider.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // namespace Microsoft.CortexM4OnMBED.HardwareModel { using ChipsetModel = Microsoft.CortexM3OnMBED; public abstract class I2cProvider : ChipsetModel.HardwareModel.I2cProvider { } } ================================================ FILE: Zelig/Zelig/RunTime/DeviceModels/CortexM4OnMBED/HardwareModel/HardwareProviders/SpiProvider.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // namespace Microsoft.CortexM4OnMBED.HardwareModel { using ChipsetModel = Microsoft.CortexM3OnMBED; public abstract class SpiProvider : ChipsetModel.HardwareModel.SpiProvider { } } ================================================ FILE: Zelig/Zelig/RunTime/DeviceModels/CortexM4OnMBED/HardwareModel/Memory.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // namespace Microsoft.CortexM4OnMBED { using Chipset = Microsoft.CortexM3OnMBED; public sealed class Memory : Chipset.Memory { } } ================================================ FILE: Zelig/Zelig/RunTime/DeviceModels/CortexM4OnMBED/HardwareModel/Peripherals.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // //#define ALLOW_PAUSE namespace Microsoft.CortexM4OnMBED { using Chipset = Microsoft.CortexM3OnMBED; public abstract class Peripherals : Chipset.Peripherals { } } ================================================ FILE: Zelig/Zelig/RunTime/DeviceModels/CortexM4OnMBED/HardwareModel/Processor.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // //#define THREADING_RTOS namespace Microsoft.CortexM4OnMBED { using System; using RT = Microsoft.Zelig.Runtime; using RTOS = Microsoft.Zelig.Support.mbed; using ChipsetModel = Microsoft.CortexM4OnCMSISCore; public abstract class Processor : ChipsetModel.Processor { public new abstract class Context : ChipsetModel.Processor.Context { #if THREADING_RTOS // // State // protected UIntPtr m_nativeContext; #endif //--// public Context(RT.ThreadImpl owner) : base(owner) { } // // Extensibility // #if THREADING_RTOS public override void SwitchTo() { // // When running on a RTOS, we will request the underlying system to choose the next thread // based on our indications. Need to solve priority and lock contention issues, e.g. priority inversion // issues. // RTOS.Threading.SwitchToContext( m_nativeContext ); } #endif // // RTOS Extensibility // protected override UIntPtr CreateNativeContext( UIntPtr entryPoint, UIntPtr stack, int stackSize ) { return RTOS.Threading.CreateNativeContext( entryPoint, stack, stackSize ); } protected override void SwitchToContext( UIntPtr nativeContext ) { RTOS.Threading.SwitchToContext( nativeContext ); } protected override void Yield( UIntPtr nativeContext ) { RTOS.Threading.Yield( nativeContext ); } protected override void Retire( UIntPtr nativeContext ) { RTOS.Threading.Retire( nativeContext ); } } //--// #if THREADING_RTOS [RT.Inline] public override Microsoft.Zelig.Runtime.Processor.Context AllocateProcessorContext() { return new Context(); } #endif // // Access methods // public static ulong CoreClockFrequency { [RT.ConfigurationOption("System__CoreClockFrequency")] get { RT.BugCheck.Assert( false, RT.BugCheck.StopCode.IllegalConfiguration ); return 0; } } public static ulong RealTimeClockFrequency { [RT.ConfigurationOption("System__RealTimeClockFrequency")] get { RT.BugCheck.Assert( false, RT.BugCheck.StopCode.IllegalConfiguration ); return 0; } } public static uint DefaultThreadPoolThreads { [RT.ConfigurationOption( "System__Runtime_DefaultThreadPoolThreads" )] get { RT.BugCheck.Assert( false, RT.BugCheck.StopCode.IllegalConfiguration ); return 3; } } public static uint DefaultTimerPooThreads { [RT.ConfigurationOption( "System__Runtime_DefaultTimerPooThreads" )] get { RT.BugCheck.Assert( false, RT.BugCheck.StopCode.IllegalConfiguration ); return 2; } } //--// //////[RT.BottomOfCallStack()] //////[RT.HardwareExceptionHandler(RT.HardwareException.Interrupt)] //////private static void InterruptHandler( UIntPtr stackPtr ) //////{ ////// s_repeatedAbort = false; ////// Context.InterruptHandlerWithContextSwitch( ref stackPtr ); //////} //////[RT.BottomOfCallStack()] //////[RT.HardwareExceptionHandler(RT.HardwareException.FastInterrupt)] //////[RT.MemoryRequirements( RT.MemoryAttributes.RAM )] //////private static void FastInterruptHandler() //////{ ////// s_repeatedAbort = false; ////// Context.FastInterruptHandlerWithoutContextSwitch(); //////} //////[RT.BottomOfCallStack()] //////[RT.HardwareExceptionHandler(RT.HardwareException.SoftwareInterrupt)] //////private static void SoftwareInterruptHandler( ref Context.RegistersOnStackNoFPContext registers ) //////{ ////// s_repeatedAbort = false; ////// Context.GenericSoftwareInterruptHandler( ref registers ); //////} //--// [RT.NoInline] [RT.NoReturn()] [RT.HardwareExceptionHandler(RT.HardwareException.UndefinedInstruction)] [RT.MemoryUsage(RT.MemoryUsage.Bootstrap)] static void UndefinedInstruction() { //////RT.Processor.Instance.Breakpoint(); while(true) { } } [RT.NoInline] [RT.NoReturn()] [RT.HardwareExceptionHandler(RT.HardwareException.PrefetchAbort)] [RT.MemoryUsage(RT.MemoryUsage.Bootstrap)] static void PrefetchAbort() { //////RT.Processor.Instance.Breakpoint(); while(true) { } } private static bool s_repeatedAbort = false; private static int s_abortCount = 0; [RT.NoInline] [RT.NoReturn()] [RT.HardwareExceptionHandler(RT.HardwareException.DataAbort)] [RT.MemoryUsage(RT.MemoryUsage.Bootstrap)] static void DataAbort() { //////bool repeatedAbort = s_repeatedAbort; //////s_repeatedAbort = true; //////s_abortCount++; //////if (repeatedAbort) //////RT.Processor.Instance.Breakpoint(); while(true) { } } } } ================================================ FILE: Zelig/Zelig/RunTime/DeviceModels/CortexM4OnMBED/HardwareModel/SpiProvider.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // namespace Microsoft.CortexM4OnMBED.HardwareModel { using Chipset = Microsoft.CortexM3OnMBED; public abstract class SpiProvider : Chipset.HardwareModel.SpiProvider { } } ================================================ FILE: Zelig/Zelig/RunTime/DeviceModels/CortexM4OnMBED/HardwareModel/Storage.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // namespace Microsoft.CortexM4OnMBED { using System; using RT = Microsoft.Zelig.Runtime; using ChipsetModel = Microsoft.CortexM3OnMBED; public sealed class Storage : ChipsetModel.Storage { } } ================================================ FILE: Zelig/Zelig/RunTime/DeviceModels/CortexM4OnMBED/Properties/AssemblyInfo.cs ================================================ using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; // General Information about an assembly is controlled through the following // set of attributes. Change these attribute values to modify the information // associated with an assembly. [assembly: AssemblyTitle( "Microsoft.CortexM3OnMBED" )] [assembly: AssemblyDescription( "" )] [assembly: AssemblyConfiguration( "" )] [assembly: AssemblyCompany( "Microsoft" )] [assembly: AssemblyProduct( "Microsoft.CortexM3OnMBED" )] [assembly: AssemblyCopyright( "Copyright © Microsoft 2015" )] [assembly: AssemblyTrademark( "" )] [assembly: AssemblyCulture( "" )] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible( false )] // The following GUID is for the ID of the typelib if this project is exposed to COM //[assembly: Guid( "ffacd01c-fa64-4234-9058-1ad866f88c1a" )] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Build and Revision Numbers // by using the '*' as shown below: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion( "1.0.0.0" )] [assembly: AssemblyFileVersion( "1.0.0.0" )] ================================================ FILE: Zelig/Zelig/RunTime/DeviceModels/CortexM4OnMBED/SystemServices/GarbageCollectionManager.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // namespace Microsoft.CortexM4OnMBED { using Chipset = Microsoft.CortexM3OnMBED; public abstract class GarbageCollectionManager : Chipset.GarbageCollectionManager { } } ================================================ FILE: Zelig/Zelig/RunTime/DeviceModels/CortexM4OnMBED/SystemServices/MemoryManager.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // namespace Microsoft.CortexM4OnMBED { using System; using RT = Microsoft.Zelig.Runtime; using Chipset = Microsoft.CortexM3OnMBED; using MBED = Microsoft.Zelig.Support.mbed; public sealed class MemoryManager : Chipset.MemoryManager { } } ================================================ FILE: Zelig/Zelig/RunTime/DeviceModels/CortexM4OnMBED/SystemServices/ThreadManager.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // namespace Microsoft.CortexM4OnMBED { using RT = Microsoft.Zelig.Runtime; using Chipset = Microsoft.CortexM3OnMBED; public abstract class ThreadManager : Chipset.ThreadManager { } } ================================================ FILE: Zelig/Zelig/RunTime/DeviceModels/CortexM4OnMBED/SystemServices/TimerPool.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // namespace Microsoft.CortexM4OnMBED { using Chipset = Microsoft.CortexM4OnCMSISCore; public abstract class TimerPool : Chipset.TimerPool { } } ================================================ FILE: Zelig/Zelig/RunTime/DeviceModels/CortexM4OnMBED/SystemServices/TypeSystemManager.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // namespace Microsoft.CortexM4OnMBED { using RT = Zelig.Runtime; using Chipset = Microsoft.CortexM3OnMBED; public sealed class TypeSystemManager : Chipset.TypeSystemManager { } } ================================================ FILE: Zelig/Zelig/RunTime/DeviceModels/ExternalLinking_Tester/ExternalLinking_Tester.csproj ================================================  Debug AnyCPU 9.0.21022 2.0 {ACE86CB1-7796-4B5F-96AF-B51595944B66} Exe Properties ExternalLinking_Tester ExternalLinking_Tester v4.5 512 true full false $(LlilumBuildRoot)\Target\bin\$(Configuration)\ DEBUG;TRACE prompt 4 true AllRules.ruleset AnyCPU true false pdbonly true $(LlilumBuildRoot)\Target\bin\$(Configuration)\ TRACE prompt 4 AllRules.ruleset AnyCPU true false $(LlilumBuildRoot)\Target\bin\$(Configuration)\ TRACE;DEBUG AnyCPU true true false {186F31A3-EF89-4A25-B2D5-20060501AA01} mscorlib False {186F31A3-EF89-4A25-B2D5-20070702AA01} system False {186F31A3-EF89-4A25-B2D5-20061218AA01} Common False {186F31A3-EF89-4A25-B2D5-20060509AA01} Kernel False {186F31A3-EF89-4A25-B2D5-20060720AA01} TypeSystem False ================================================ FILE: Zelig/Zelig/RunTime/DeviceModels/ExternalLinking_Tester/Program.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // #define TEST_EXTERNAL_CALL namespace ExternalLinking_Tester { using System; using RT = Microsoft.Zelig.Runtime; using System.Runtime.InteropServices; using System.Threading; class Tester { public static int s_intVal; //static void ThreadFunc() //{ // for(int i=0; i<2; i++) // { // Console.WriteLine( "Testing..." ); // Thread.Sleep( 2000 ); // } //} static void Main() { //Thread th = new Thread( new ThreadStart( ThreadFunc ) ); //th.Start(); //GC.Collect(); //th.Join(); //Console.WriteLine( "Finished" ); Console.WriteLine("Starting tests"); s_intVal = 0; var obj = new TestObj(); s_intVal = obj.Add2Return(1, 2); obj.Add2SetInstance(3, 4); obj.SetStaticOnTester(); TestObj.TestImportedFunctionCall(); Console.WriteLine("Tests finished"); } } class TestObj { const string c_ImportLibrary1 = @"zelig_interop.obj"; const string c_ImportLibrary2 = @"zelig_interop2.obj"; private int m_intVal; [RT.NoInline] public TestObj() { m_intVal = 0; } [RT.NoInline] public int Add2Return(int a, int b) { int val; val = a + b; return val; } [RT.NoInline] public void Add2SetInstance(int a, int b) { int val; val = a + b; m_intVal = val; } [RT.NoInline] public void SetStaticOnTester() { Tester.s_intVal = m_intVal; } [RT.NoInline] public static void TestImportedFunctionCall() { DateTime start = DateTime.Now; Console.WriteLine( start.Second.ToString() ); #if TEST_EXTERNAL_CALL int i; i = ImportedExternalFunction( 3, 7 ); Console.WriteLine( "Expected 47, Got: " + i.ToString() ); i = ImportedExternalFunction2( i ); Console.WriteLine( "Expecting 30, Got: " + i.ToString() ); ExportStruct es = new ExportStruct(); double d = DoubleMultiply( 2.354, 76.66 ); // 180.45764 Console.WriteLine( "Expecting 180.45764, Got: " + d.ToString() ); string str = "Hello World!"; char[] strData = str.ToCharArray(); PassStringArgument( strData, str.Length ); // Console.WriteLine( "Expecting '!dlroW olleH', Got: " + new string(strData) ); byte[] data = new byte[] { 0x1, 0x2, 0x3, 0x4, 0x5, 0x6, 0x7, 0x8 }; PassByteArrayArg( data, data.Length ); // str = ""; for(int j = 0; j < data.Length; j++) { str += data[j].ToString(); } Console.WriteLine( "Expecting '87654321', Got: " + str ); PassStructArg( ref es ); Console.WriteLine( "es.a <123>= " + es.a + " es.b <3.4775>= " + es.b + " es.c <'Z'>= " + es.c ); i = StringLength( str ); Console.WriteLine( "String Len <8>: " + i.ToString() ); #endif return; } [RT.ImportedMethodReference( RT.ImportedMethodReferenceAttribute.InteropFileType.ArmELF, c_ImportLibrary1 )] public static extern int ImportedExternalFunction(int a, int b); [RT.ImportedMethodReference( RT.ImportedMethodReferenceAttribute.InteropFileType.ArmELF, c_ImportLibrary2, "MyExternalFunction" )] public static extern int ImportedExternalFunction2( int a ); [RT.ImportedMethodReference( RT.ImportedMethodReferenceAttribute.InteropFileType.ArmELF, c_ImportLibrary2, "Multiply" )] public static extern double DoubleMultiply( double a, double b ); [RT.ImportedMethodReference( RT.ImportedMethodReferenceAttribute.InteropFileType.ArmELF, c_ImportLibrary2 )] public static extern int PassStringArgument( char[] str, int len ); [RT.ImportedMethodReference( RT.ImportedMethodReferenceAttribute.InteropFileType.ArmELF, c_ImportLibrary2 )] public static extern void PassByteArrayArg( byte[] data, int data_len ); [StructLayout( LayoutKind.Explicit )] internal struct ExportStruct { [FieldOffset( 0 )] public int a; [FieldOffset( 8 )] public double b; [FieldOffset( 16 )] public char c; } [RT.ImportedMethodReference( RT.ImportedMethodReferenceAttribute.InteropFileType.ArmELF, c_ImportLibrary2 )] public static extern void PassStructArg( ref ExportStruct pStruct ); [RT.ImportedMethodReference( RT.ImportedMethodReferenceAttribute.InteropFileType.ArmELF, c_ImportLibrary2 )] public static extern int StringLength( string str ); [RT.ExportedMethod] public static Int64 ExportedInternalFunction(Int64 a) { Console.WriteLine("Exported method called"); return a + a; } [StructLayout( LayoutKind.Explicit )] public struct SYSTEMTIME { [FieldOffset( 0 )] public ushort wYear; [FieldOffset( 2 )] public ushort wMonth; [FieldOffset( 4 )] public ushort wDayOfWeek; [FieldOffset( 6 )] public ushort wDay; [FieldOffset( 8 )] public ushort wHour; [FieldOffset( 10 )] public ushort wMinute; [FieldOffset( 12 )] public ushort wSecond; [FieldOffset( 14 )] public ushort wMilliseconds; }; [RT.ExportedMethod] public static int ExportedStructInt64( Int64 time, ref SYSTEMTIME sysTime ) { DateTime dt = DateTime.Now; dt = new DateTime( dt.Year, dt.Month, dt.Day, dt.Hour, dt.Minute, (int)time ); sysTime.wYear = (ushort)dt.Year; sysTime.wMonth = (ushort)dt.Month; sysTime.wDay = (ushort)dt.Day; sysTime.wDayOfWeek = (ushort)dt.DayOfWeek; sysTime.wHour = (ushort)dt.Hour; sysTime.wMinute = (ushort)dt.Minute; sysTime.wSecond = (ushort)dt.Second; sysTime.wMilliseconds = (ushort)dt.Millisecond; return 1; } } } ================================================ FILE: Zelig/Zelig/RunTime/DeviceModels/ExternalLinking_Tester/Properties/AssemblyInfo.cs ================================================ using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; // General Information about an assembly is controlled through the following // set of attributes. Change these attribute values to modify the information // associated with an assembly. [assembly: AssemblyTitle( "ExternalLinking_Tester" )] [assembly: AssemblyDescription( "" )] [assembly: AssemblyConfiguration( "" )] [assembly: AssemblyCompany( "MSIT" )] [assembly: AssemblyProduct( "ExternalLinking_Tester" )] [assembly: AssemblyCopyright( "Copyright © MSIT 2009" )] [assembly: AssemblyTrademark( "" )] [assembly: AssemblyCulture( "" )] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible( false )] // The following GUID is for the ID of the typelib if this project is exposed to COM [assembly: Guid( "428da4e2-d177-4c39-ae6a-03fd466a86ef" )] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Build and Revision Numbers // by using the '*' as shown below: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion( "1.0.0.0" )] [assembly: AssemblyFileVersion( "1.0.0.0" )] ================================================ FILE: Zelig/Zelig/RunTime/DeviceModels/FileSystemSample/FileSystemSample.csproj ================================================  Debug x86 9.0.21022 2.0 {64874F12-60A0-4B5B-ACC6-616C530F430E} Exe Properties FileSystemSample FileSystemSample v4.5 512 true $(LlilumBuildRoot)\Target\bin\$(Configuration)\ DEBUG;TRACE true true true full AnyCPU prompt MinimumRecommendedRules.ruleset $(LlilumBuildRoot)\Target\bin\$(Configuration)\ TRACE true true true pdbonly AnyCPU prompt MinimumRecommendedRules.ruleset true $(LlilumBuildRoot)\Target\bin\$(Configuration)\ DEBUG;TRACE true true true full AnyCPU MinimumRecommendedRules.ruleset {186F31A3-EF89-4A25-B2D5-20060501AA01} mscorlib False {186F31A3-EF89-4A25-B2D5-20070702AA01} system False {186F31A3-EF89-4A25-B2D5-20061218AA01} Common False {186F31A3-EF89-4A25-B2D5-20060509AA01} Kernel False {186F31A3-EF89-4A25-B2D5-20060720AA01} TypeSystem False ================================================ FILE: Zelig/Zelig/RunTime/DeviceModels/FileSystemSample/Program.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // namespace FileSystemSample { using System; using RT = Microsoft.Zelig.Runtime; using System.Runtime.InteropServices; using System.Threading; using Microsoft.Zelig.Runtime; using System.IO; using System.Text; [StructLayout( LayoutKind.Explicit )] public struct SYSTEMTIME { [FieldOffset( 0 )] public ushort wYear; [FieldOffset( 2 )] public ushort wMonth; [FieldOffset( 4 )] public ushort wDayOfWeek; [FieldOffset( 6 )] public ushort wDay; [FieldOffset( 8 )] public ushort wHour; [FieldOffset( 10 )] public ushort wMinute; [FieldOffset( 12 )] public ushort wSecond; [FieldOffset( 14 )] public ushort wMilliseconds; }; public class FileSystemTest { [RT.ExportedMethod] public static Int64 _Z17Time_GetLocalTimev() { return DateTime.Now.Ticks; } [RT.ExportedMethod] public static Int64 _Z19Time_FromSystemTimePK10SYSTEMTIME( ref SYSTEMTIME sysTime ) { DateTime dt = new DateTime( sysTime.wYear, sysTime.wMonth, sysTime.wDay, sysTime.wHour, sysTime.wMinute, sysTime.wSecond, sysTime.wMilliseconds, DateTimeKind.Utc ); return dt.Ticks; } [RT.ExportedMethod] public static int _Z17Time_ToSystemTimexP10SYSTEMTIME( Int64 time, ref SYSTEMTIME sysTime ) { DateTime dt = new DateTime( time, DateTimeKind.Utc ); sysTime.wYear = (ushort)dt.Year; sysTime.wMonth = (ushort)dt.Month; sysTime.wDay = (ushort)dt.Day; sysTime.wDayOfWeek = (ushort)dt.DayOfWeek; sysTime.wHour = (ushort)dt.Hour; sysTime.wMinute = (ushort)dt.Minute; sysTime.wSecond = (ushort)dt.Second; sysTime.wMilliseconds = (ushort)dt.Millisecond; return 1; } [RT.ExportedMethod] public static int Extern__Storage_Write( uint address, IntPtr buffer, uint offset, uint len ) { try { byte[] bufTmp = new byte[len]; unsafe { byte* ptr = (byte*)buffer.ToPointer(); int i = 0; uint end = offset + len; for(; offset < end; offset++) { bufTmp[i++] = ptr[offset]; } } return Storage.Instance.Write( new UIntPtr( address ), bufTmp, 0, len ) ? 1 : 0; } catch { return 0; } } [RT.ExportedMethod] public static int Extern__Storage_Read( uint address, IntPtr buffer, uint offset, uint len ) { try { byte[] bufTmp = new byte[len]; Storage.Instance.Read( new UIntPtr( address ), bufTmp, 0, len ); unsafe { byte* ptr = (byte*)buffer.ToPointer(); uint end = offset + len; int i = 0; for(; offset < end; offset++) { ptr[offset] = bufTmp[i++]; } } return 1; } catch { return 0; } } [RT.ExportedMethod] public static int Extern__Storage_Memset( uint address, byte data, int len ) { try { uint dataPair = (uint)data; dataPair |= dataPair << 8; dataPair |= dataPair << 16; while(0 != (address & 0x3) ) { Storage.Instance.WriteByte( new UIntPtr( address ), data ); len -= 1; address += 1; } while(len > 4) { Storage.Instance.WriteWord( new UIntPtr( address ), dataPair ); len -= 4; address += 4; } while(len > 0) { Storage.Instance.WriteByte( new UIntPtr( address ), data ); len -= 1; address += 1; } return 1; } catch { return 0; } } [RT.ExportedMethod] public static int Extern__Storage_IsErased( uint address, int len ) { try { while(len > 0) { UIntPtr ptr = new UIntPtr( address ); if(Storage.Instance.ReadWord( ptr ) != 0xFFFFFFFFu) return 0; address += 4; len -= 4; } return 1; } catch { return 0; } } [RT.ExportedMethod] public static int Extern__Storage_EraseBlock( uint address, int len ) { try { return Storage.Instance.EraseSectors( new UIntPtr( address ), new UIntPtr( address + (uint)len ) ) ? 1 : 0; } catch { return 0; } } static void Main() { string dir = "\\ROOT\\Dir1"; string file = dir + "\\MyF.txt"; DirectoryInfo di; VolumeInfo v = new VolumeInfo( "ROOT" ); if(!v.IsFormatted) { v.Format( 0 ); } if(!Directory.Exists( dir )) { di = Directory.CreateDirectory( dir ); } if(File.Exists( file )) { File.Delete( file ); } using(FileStream fs = new FileStream( file, FileMode.CreateNew, FileAccess.Write )) { byte[] data = UTF8Encoding.UTF8.GetBytes( "Hello World!" ); fs.Write( data, 0, data.Length ); } using(FileStream fsIn = new FileStream( file, FileMode.Open, FileAccess.Read )) { byte[] data = new byte[128]; int len = fsIn.Read( data, 0, data.Length ); string str = UTF8Encoding.UTF8.GetString( data, 0, len ); Console.WriteLine( str ); } FileEnum fe = new FileEnum( dir, FileEnumFlags.Files ); if(fe.MoveNext()) { Console.WriteLine( fe.Current.ToString() ); } Console.WriteLine( "Finished" ); } } } ================================================ FILE: Zelig/Zelig/RunTime/DeviceModels/FileSystemSample/Properties/AssemblyInfo.cs ================================================ using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; // General Information about an assembly is controlled through the following // set of attributes. Change these attribute values to modify the information // associated with an assembly. [assembly: AssemblyTitle( "QuickTest" )] [assembly: AssemblyDescription( "" )] [assembly: AssemblyConfiguration( "" )] [assembly: AssemblyCompany( "Microsoft" )] [assembly: AssemblyProduct( "QuickTest" )] [assembly: AssemblyCopyright( "Copyright © Microsoft 2012" )] [assembly: AssemblyTrademark( "" )] [assembly: AssemblyCulture( "" )] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible( false )] // The following GUID is for the ID of the typelib if this project is exposed to COM [assembly: Guid( "387dda81-a5e0-4fc9-ab89-c7ffb8037c4f" )] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Build and Revision Numbers // by using the '*' as shown below: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion( "1.0.0.0" )] [assembly: AssemblyFileVersion( "1.0.0.0" )] ================================================ FILE: Zelig/Zelig/RunTime/DeviceModels/ModelForCortexM/HardwareModel/Board.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // namespace Microsoft.DeviceModels.Chipset.CortexM { using Microsoft.Zelig.Runtime; using System.Runtime.CompilerServices; public abstract class Board { public class SerialPortInfo { public int RxPin; public int TxPin; public int RtsPin; public int CtsPin; } //--// public abstract int PinCount { get; } public abstract int PinToIndex( int pin ); public abstract int NCPin { get; } public abstract int[ ] LedPins { get; } public abstract int[ ] PwmPins { get; } // // Serial Methods // public abstract string[ ] GetSerialPorts( ); public abstract SerialPortInfo GetSerialPortInfo( string portName ); public abstract int GetSerialPortIRQ( string portName ); //////public abstract void RemapSerialPortInterrupts( ); // // System timer // public abstract int GetSystemTimerIRQ( ); //--// // // Factory methods // public static extern Board Instance { [SingletonFactory( )] [MethodImpl( MethodImplOptions.InternalCall )] get; } } } ================================================ FILE: Zelig/Zelig/RunTime/DeviceModels/ModelForCortexM/HardwareModel/ChipSet/StandardPeripherals/NVIC.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // namespace Microsoft.DeviceModels.Chipset.CortexM { using System.Runtime.InteropServices; using RT = Microsoft.Zelig.Runtime; //--// // TODO: put right addresses, and fix code generation for LLVM that does not understand the attribute's constants //[MemoryMappedPeripheral(Base = 0x40D00000U, Length = 0x000000D0U)] public class NVIC { ////// ////// From core_cm3.h in mBed CMSIS support: ////// ////// /** \brief Structure type to access the Nested Vectored Interrupt Controller (NVIC). ////// */ ////// typedef struct ////// { ////// __IO uint32_t ISER[8]; /*!< Offset: 0x000 (R/W) Interrupt Set Enable Register */ ////// uint32_t RESERVED0[24]; ////// __IO uint32_t ICER[8]; /*!< Offset: 0x080 (R/W) Interrupt Clear Enable Register */ ////// uint32_t RSERVED1[24]; ////// __IO uint32_t ISPR[8]; /*!< Offset: 0x100 (R/W) Interrupt Set Pending Register */ ////// uint32_t RESERVED2[24]; ////// __IO uint32_t ICPR[8]; /*!< Offset: 0x180 (R/W) Interrupt Clear Pending Register */ ////// uint32_t RESERVED3[24]; ////// __IO uint32_t IABR[8]; /*!< Offset: 0x200 (R/W) Interrupt Active bit Register */ ////// uint32_t RESERVED4[56]; ////// __IO uint8_t IP[240]; /*!< Offset: 0x300 (R/W) Interrupt Priority Register (8Bit wide) */ ////// uint32_t RESERVED5[644]; ////// __O uint32_t STIR; /*!< Offset: 0xE00 ( /W) Software Trigger Interrupt Register */ ////// } NVIC_Type; ////// ////// ... ////// ... ////// ... ////// ////// #define NVIC ((NVIC_Type *) NVIC_BASE ) /*!< NVIC configuration struct */ ////// private const uint NVIC_ISERx__ENABLE___MASK = 0xFFFFFFFFu; private const int NVIC_ISERx__ENABLE___SHIFT = 0; private const uint NVIC_ISERx__ENABLE___SET_ENABLED = 1u << NVIC_ISERx__ENABLE___SHIFT; private const uint NVIC_ISERx__ENABLE___IS_ENABLED = 1u << NVIC_ISERx__ENABLE___SHIFT; private const uint NVIC_ISERx__ENABLE___IS_DISABLED = 0u << NVIC_ISERx__ENABLE___SHIFT; private const uint NVIC_ICERx__ENABLE___MASK = 0xFFFFFFFFu; private const int NVIC_ICERx__ENABLE___SHIFT = 0; private const uint NVIC_ICERx__ENABLE___SET_DISABLED = 1u << NVIC_ICERx__ENABLE___SHIFT; private const uint NVIC_ICERx__ENABLE___IS_ENABLED = 1u << NVIC_ICERx__ENABLE___SHIFT; private const uint NVIC_ICERx__ENABLE___IS_DISABLED = 0u << NVIC_ICERx__ENABLE___SHIFT; private const uint NVIC_ISPRx__ENABLE___MASK = 0xFFFFFFFFu; private const int NVIC_ISPRx__ENABLE___SHIFT = 0; private const uint NVIC_ISPRx__ENABLE___SET_PENDING = 1u << NVIC_ISPRx__ENABLE___SHIFT; private const uint NVIC_ISPRx__ENABLE___IS_PENDING = 1u << NVIC_ISPRx__ENABLE___SHIFT; private const uint NVIC_ISPRx__ENABLE___IS_NOT_PENDING = 0u << NVIC_ISPRx__ENABLE___SHIFT; private const uint NVIC_ICPRx__ENABLE___MASK = 0xFFFFFFFFu; private const int NVIC_ICPRx__ENABLE___SHIFT = 0; private const uint NVIC_ICPRx__ENABLE___CLEAR_PENDING = 1u << NVIC_ICPRx__ENABLE___SHIFT; private const uint NVIC_ICPRx__ENABLE___IS_PENDING = 1u << NVIC_ICPRx__ENABLE___SHIFT; private const uint NVIC_ICPRx__ENABLE___IS_NOT_PENDING = 0u << NVIC_ICPRx__ENABLE___SHIFT; private const uint NVIC_IABRx__ENABLE___MASK = 0xFFFFFFFFu; private const int NVIC_IABRx__ENABLE___SHIFT = 0; private const uint NVIC_IABRx__ENABLE___IS_ACTIVE = 1u << NVIC_IABRx__ENABLE___SHIFT; private const uint NVIC_IABRx__ENABLE___IS_NOT_ACTIVE = 0u << NVIC_IABRx__ENABLE___SHIFT; private const uint NVIC_STIR__ENABLE___MASK = 0xFFu; private const int NVIC_STIR__ENABLE___SHIFT = 0; //--// public static void EnableInterrupt( int irq ) { RT.BugCheck.Assert( irq >= 0, RT.BugCheck.StopCode.IncorrectArgument ); CMSIS_STUB_NVIC_EnableIRQ( irq ); } public static void DisableInterrupt( int irq ) { RT.BugCheck.Assert( irq >= 0, RT.BugCheck.StopCode.IncorrectArgument ); CMSIS_STUB_NVIC_DisableIRQ( irq ); } public static void SetPriority( int irq, uint pri ) { CMSIS_STUB_NVIC_SetPriority( irq, pri ); } public static uint GetPriority( int irq ) { return CMSIS_STUB_NVIC_GetPriority( irq ); } public static void SetPriorityGrouping( uint split ) { CMSIS_STUB_NVIC_SetPriorityGrouping( split ); } public static void SetPending( int irq ) { CMSIS_STUB_NVIC_SetPendingIRQ( irq ); } public static void ClearPending( int irq ) { CMSIS_STUB_NVIC_ClearPendingIRQ( irq ); } public static uint GetActive(int irq) { return CMSIS_STUB_NVIC_GetActive(irq); } public static uint GetVector( int irq ) { return CMSIS_STUB_NVIC_GetVector( irq ); } public static void SetVector( int irq, uint vector ) { CMSIS_STUB_NVIC_SetVector( irq, vector ); } //--// // // We will implement the internal methods below with CMSIS-Core // [DllImport( "C" )] private static extern void CMSIS_STUB_NVIC_SetPriorityGrouping( uint PriorityGroup ); [DllImport( "C" )] private static extern uint CMSIS_STUB_NVIC_GetPriorityGrouping(); [DllImport( "C" )] private static extern void CMSIS_STUB_NVIC_EnableIRQ( int IRQn ); [DllImport( "C" )] private static extern void CMSIS_STUB_NVIC_DisableIRQ( int IRQn ); [DllImport( "C" )] private static extern uint CMSIS_STUB_NVIC_GetPendingIRQ( int IRQn ); [DllImport( "C" )] private static extern void CMSIS_STUB_NVIC_SetPendingIRQ( int IRQn ); [DllImport( "C" )] private static extern void CMSIS_STUB_NVIC_ClearPendingIRQ( int IRQn ); [DllImport( "C" )] private static extern uint CMSIS_STUB_NVIC_GetActive( int IRQn ); [DllImport("C")] private static extern uint CMSIS_STUB_NVIC_GetVector( int IRQn); [DllImport("C")] private static extern void CMSIS_STUB_NVIC_SetVector( int IRQn, uint vector ); [DllImport( "C" )] private static extern void CMSIS_STUB_NVIC_SetPriority( int IRQn, uint priority ); [DllImport( "C" )] private static extern uint CMSIS_STUB_NVIC_GetPriority( int IRQn ); [DllImport( "C" )] private static extern uint CMSIS_STUB_NVIC_EncodePriority( uint PriorityGroup, uint PreemptPriority, uint SubPriority ); [DllImport( "C" )] private static unsafe extern void CMSIS_STUB_NVIC_DecodePriority( uint Priority, uint PriorityGroup, uint* pPreemptPriority, uint* pSubPriority ); [DllImport( "C" )] private static extern void CMSIS_STUB_NVIC_SystemReset( ); [DllImport( "C" )] private static extern void CUSTOM_STUB_NVIC_RaisePendSV( ); } } ================================================ FILE: Zelig/Zelig/RunTime/DeviceModels/ModelForCortexM/HardwareModel/ChipSet/StandardPeripherals/SysTick.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // namespace Microsoft.DeviceModels.Chipset.CortexM { using System.Runtime.InteropServices; using System.Runtime.CompilerServices; using RT = Microsoft.Zelig.Runtime; //--// // TODO: put right addresses, and fix code generation for LLVM that does not understand the attribute's constants //[MemoryMappedPeripheral(Base = 0x40D00000U, Length = 0x000000D0U)] public class SysTick { ////// ////// From core_cm[x].h in mBed CMSIS support: ////// ////// /** \brief Structure type to access the System Timer (SysTick). ////// */ ////// typedef struct ////// { ////// __IO uint32_t CTRL; /*!< Offset: 0x000 (R/W) SysTick Control and Status Register */ ////// __IO uint32_t LOAD; /*!< Offset: 0x004 (R/W) SysTick Reload Value Register */ ////// __IO uint32_t VAL; /*!< Offset: 0x008 (R/W) SysTick Current Value Register */ ////// __I uint32_t CALIB; /*!< Offset: 0x00C (R/ ) SysTick Calibration Register */ ////// } SysTick_Type; ////// ////// ... ////// ... ////// ... ////// ////// #define SysTick ((SysTick_Type *) SysTick_BASE ) /*!< SysTick configuration struct */ ////// //--// public const uint MaxCounterValue = 0x00FFFFFF; // // SYST_CSR @ address 0xE000E010 // private const int SYST_CSR__MASK = 0x00010007; private const int SYST_CSR__ENABLE___SHIFT = 0; private const uint SYST_CSR__ENABLE___MASK = 0x00000001u << SYST_CSR__ENABLE___SHIFT; private const uint SYST_CSR__ENABLE___ENABLED = 1u << SYST_CSR__ENABLE___SHIFT; private const uint SYST_CSR__ENABLE___DISABLED = 0u << SYST_CSR__ENABLE___SHIFT; private const int SYST_CSR__TICKINT___SHIFT = 1; private const uint SYST_CSR__TICKINT___MASK = 0x00000001u << SYST_CSR__TICKINT___SHIFT; private const uint SYST_CSR__TICKINT___ENABLED = 1u << SYST_CSR__TICKINT___SHIFT; private const uint SYST_CSR__TICKINT___DISABLED = 0u << SYST_CSR__TICKINT___SHIFT; private const int SYST_CSR__CLKSOURCE___SHIFT = 2; private const uint SYST_CSR__CLKSOURCE___MASK = 0x00000001u << SYST_CSR__CLKSOURCE___SHIFT; private const uint SYST_CSR__CLKSOURCE___PROCESSOR = 1u << SYST_CSR__CLKSOURCE___SHIFT; private const uint SYST_CSR__CLKSOURCE___EXTERNAL = 0u << SYST_CSR__CLKSOURCE___SHIFT; private const int SYST_CSR__COUNTFLAG___SHIFT = 16; private const uint SYST_CSR__COUNTFLAG___MASK = 0x00000001u << SYST_CSR__COUNTFLAG___SHIFT; private const uint SYST_CSR__COUNTFLAG___COUNTED = 1u << SYST_CSR__COUNTFLAG___SHIFT; private const uint SYST_CSR__COUNTFLAG___DIDNOTCOUNT = 0u << SYST_CSR__COUNTFLAG___SHIFT; //--// private const uint SYST_CSR__STARTED = SYST_CSR__ENABLE___ENABLED | SYST_CSR__TICKINT___ENABLED | SYST_CSR__CLKSOURCE___PROCESSOR; private const uint SYST_CSR__STOPPED = SYST_CSR__TICKINT___ENABLED | SYST_CSR__CLKSOURCE___PROCESSOR; // // SYST_CSR @ address 0xE000E014 // private const int SYST_RVR__MASK = 0x00FFFFFF; private const int SYST_RVR__RELOAD___MASK = 0x00FFFFFF; private const int SYST_RVR__RELOAD___SHIFT = 0; // // SYST_CVR @ address 0xE000E018 // private const int SYST_CVR__MASK = 0x00FFFFFF; private const int SYST_CVR__CURRENT___MASK = 0x00FFFFFF; private const int SYST_CVR__CURRENT___SHIFT = 0; // // SYST_CALIB @ address 0xE000E01C // private const uint SYST_CALIB__MASK = 0xC0FFFFFF; private const int SYST_CALIB__TENMS___SHIFT = 0; private const uint SYST_CALIB__TENMS___MASK = 0x00FFFFFFu << SYST_CALIB__TENMS___SHIFT; private const int SYST_CALIB__SKEW__SHIFT = 30; private const uint SYST_CALIB__SKEW__MASK = 1u << SYST_CALIB__SKEW__SHIFT; private const uint SYST_CALIB__SKEW__PRECISE = 0u << SYST_CALIB__SKEW__SHIFT; private const uint SYST_CALIB__SKEW__NOTPRECISE = 1u << SYST_CALIB__SKEW__SHIFT; private const int SYST_CALIB__NOREF__SHIFT = 31; private const uint SYST_CALIB__NOREF__MASK = 1u << SYST_CALIB__NOREF__SHIFT; private const uint SYST_CALIB__NOREF__HASREF = 0u << SYST_CALIB__NOREF__SHIFT; private const uint SYST_CALIB__NOREF__NOREF = 1u << SYST_CALIB__NOREF__SHIFT; //--// public uint Match { [RT.Inline] get { return CMSIS_STUB_SysTick_GetLOAD( ); } [RT.Inline] set { RT.BugCheck.Assert( value <= 0x00FFFFFF, RT.BugCheck.StopCode.IncorrectArgument ); CMSIS_STUB_SysTick_SetLOAD( value ); } } public uint Calibration { [RT.Inline] get { return CMSIS_STUB_SysTick_GetCALIB( ); } } public uint Counter { [RT.Inline] get { return CMSIS_STUB_SysTick_GetVAL( ); } [RT.Inline] set { RT.BugCheck.Assert( value <= 0x00FFFFFF, RT.BugCheck.StopCode.IncorrectArgument ); // // writing any value clear the register to zero, and also clears the count flag // CMSIS_STUB_SysTick_SetVAL( value ); } } public bool HasMatched { [RT.Inline] get { uint ctrl = CMSIS_STUB_SysTick_GetCTRL( ); return (( ctrl & SYST_CSR__COUNTFLAG___MASK ) == SYST_CSR__COUNTFLAG___COUNTED); } } [RT.Inline] public void ResetAndClear() { // writing the counter value clear the COUNTFLAG this.Counter = 0; } public bool Enabled { [RT.Inline] set { if(value == true) { // enable SysTick with interrupts from processor clock CMSIS_STUB_SysTick_SetCTRL( SYST_CSR__STARTED ); } else { uint ctrl = CMSIS_STUB_SysTick_GetCTRL( ); ctrl &= ~SYST_CSR__ENABLE___ENABLED; CMSIS_STUB_SysTick_SetCTRL( ctrl ); } } } public uint TenMillisecondsCalibrationValue { get { return CMSIS_STUB_SysTick_GetCALIB( ) & SYST_CALIB__TENMS___MASK; } } public bool HasRef { get { return ((CMSIS_STUB_SysTick_GetCALIB() & SYST_CALIB__NOREF__MASK) == SYST_CALIB__NOREF__HASREF); } } public bool IsPrecise { get { return (CMSIS_STUB_SysTick_GetCALIB() & SYST_CALIB__SKEW__MASK) == SYST_CALIB__SKEW__PRECISE; } } // // Access Methods // public static extern SysTick Instance { [RT.SingletonFactory()] [MethodImpl(MethodImplOptions.InternalCall)] get; } //--// [DllImport( "C" )] private static extern uint CMSIS_STUB_SysTick_GetCTRL( ); [DllImport( "C" )] private static extern uint CMSIS_STUB_SysTick_GetLOAD( ); [DllImport( "C" )] private static extern uint CMSIS_STUB_SysTick_GetVAL( ); [DllImport( "C" )] private static extern uint CMSIS_STUB_SysTick_GetCALIB( ); [DllImport( "C" )] private static extern void CMSIS_STUB_SysTick_SetCTRL( uint value ); [DllImport( "C" )] private static extern void CMSIS_STUB_SysTick_SetLOAD( uint value ); [DllImport( "C" )] private static extern void CMSIS_STUB_SysTick_SetVAL( uint value ); } } ================================================ FILE: Zelig/Zelig/RunTime/DeviceModels/ModelForCortexM/HardwareModel/Drivers/ContextSwitchTimer.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // //#define TIMERS_SELF_TEST namespace Microsoft.DeviceModels.Chipset.CortexM.Drivers { using System.Runtime.CompilerServices; using RT = Microsoft.Zelig.Runtime; using CMSIS = Microsoft.DeviceModels.Chipset.CortexM; using LLOS = Zelig.LlilumOSAbstraction.HAL; public abstract class ContextSwitchTimer { public delegate void Callback(); /// /// Max value that can be assigned for a one shot timer with no wrap around /// public const uint c_MaxCounterValue = 0x00FFFFFF; //--// // // State // //--// private SysTick m_sysTick; private uint m_reload20ms; private uint m_timeout; private bool m_enabled; // // Helper Methods // // // Access Methods // public static extern ContextSwitchTimer Instance { [RT.SingletonFactory()] [MethodImpl( MethodImplOptions.InternalCall )] get; } //--// public void Initialize() { m_sysTick = CMSIS.SysTick.Instance; //--// // Reset HW, stop all SysTick interrupts Cancel(); //--// // // The calibration value is the match value for a 10ms interrupt at 100Mhz // clock, so we have to adjust it accordingly to the system frequency // // The SysTick raises an interrupt on the tick following the reload value // count and we need twice the factory match value. or simply, we can just // count the ticks in a 20 ms interval given the processor core frequency m_reload20ms = GetTicksForQuantumValue( RT.ARMv7ThreadManager.c_TimeQuantumMsec ); #if TIMERS_SELF_TEST ulong now = this.CurrentTime; ulong last = now; int testCount = 20; var testTimer = this.CreateTimer( delegate ( SysTickTimer timer, ulong currentTime ) { testCount--; RT.BugCheck.Log( "[handler] ct=0x%08x%08x, delta=0x%08x%08x", (int)( (currentTime >> 32) & 0xFFFFFFFF), (int)( currentTime & 0xFFFFFFFF), (int)(((currentTime - last) >> 32) & 0xFFFFFFFF), (int)(((currentTime - last) >> 0) & 0xFFFFFFFF) ); last = currentTime; } ); testTimer.RelativeTimeout = m_reload20ms; while( testCount > 0 ) { // // Enable primask in the debugger to fire the exception // } #endif } public void Schedule( uint timeout_ms ) { SetMatchAndStart( GetTicksForQuantumValue( timeout_ms ) ); } public void Cancel( ) { m_sysTick.Enabled = false; m_enabled = false; } public void Reset( ) { if(m_enabled) { // If the timer is already enabled, then only the counter needs to be // reset. m_sysTick.ResetAndClear(); } else { SetMatchAndStart( m_reload20ms ); } } //--// protected virtual uint GetTicksForQuantumValue( uint ms ) { // // We use SysTick and handle wrap around for values larger than 24 bit precision // We will assume the device can be programmed with the calibration value from factory settings // TODO: need to add logic to handle the case where we cannot count in the calibration value // RT.BugCheck.Assert( HasRef() && IsPrecise(), RT.BugCheck.StopCode.FailedBootstrap ); // // match = ( (timerClockMhz * calibration_x10 / 100) - 1 ) * ms ) / 10 // return ( ( ( ( GetTimerClockMhz( ) * GetFactoryCalibrationValue( ) ) / 100 ) - 1 ) * ms) / 10; } //--// // // SysTick helpers // [RT.Inline] private void SetMatchAndStart( uint match ) { // // Restarting causes the match value to be picked up // m_sysTick.Match = match; m_sysTick.Counter = 0; m_sysTick.Enabled = true; m_enabled = true; } [RT.Inline] private unsafe uint GetTimerClockMhz( ) { return (uint)(LLOS.Timer.LLOS_SYSTEM_TIMER_GetTimerFrequency( null ) / 1000000); } [RT.Inline] private uint GetFactoryCalibrationValue( ) { return m_sysTick.TenMillisecondsCalibrationValue; } [RT.Inline] private bool IsPrecise( ) { return m_sysTick.IsPrecise; } [RT.Inline] private bool HasRef( ) { return m_sysTick.HasRef; } //--// [RT.HardwareExceptionHandler( RT.HardwareException.Interrupt )] [RT.ExportedMethod] private static void SysTick_Handler_Zelig( ) { using(RT.SmartHandles.InterruptState.Disable()) { RT.ThreadManager.Instance.TimeQuantumExpired( ); } } } } ================================================ FILE: Zelig/Zelig/RunTime/DeviceModels/ModelForCortexM/HardwareModel/Drivers/InterruptController.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // namespace Microsoft.DeviceModels.Chipset.CortexM.Drivers { using System; using System.Runtime.CompilerServices; using RT = Microsoft.Zelig.Runtime; [Flags] public enum InterruptSettings { Normal = 0x00000000, Fast = 0x00000001, LevelSensitive = 0x00000000, EdgeSensitive = 0x00000002, ActiveLowOrFalling = 0x00000000, ActiveHighOrRising = 0x00000004, ActiveLow = LevelSensitive | ActiveLowOrFalling, ActiveHigh = LevelSensitive | ActiveHighOrRising, FallingEdge = EdgeSensitive | ActiveLowOrFalling, RisingEdge = EdgeSensitive | ActiveHighOrRising, } public enum InterruptPriority { Lowest = 255, BelowNormal = 200, Normal = 127, AboveNormal = 50, Highest = 0, } public abstract class InterruptController { public delegate void Callback( InterruptData data ); /// /// This structure contains the interrupt handler and any data associated with the interrupt. /// Context and Subcontext is interrupt dependent data and is not required to be set. /// public struct InterruptData { public ulong Context; public Handler Handler; } public class Handler { // // State // private readonly int m_index; internal readonly InterruptPriority m_priority; private readonly InterruptSettings m_settings; private readonly Callback m_callback; internal readonly RT.KernelNode< Handler > m_node; // // Constructor Methods // private Handler( int index , InterruptPriority priority , InterruptSettings settings , Callback callback ) { m_index = index; m_priority = priority; m_settings = settings; m_callback = callback; m_node = new RT.KernelNode< Handler >( this ); } // // Helper Methods // public static Handler Create( int index , InterruptPriority priority , InterruptSettings settings , Callback callback ) { return new Handler( index, priority, settings, callback ); } public void Enable() { NVIC.EnableInterrupt( m_index ); } public void Disable() { NVIC.DisableInterrupt( m_index ); } public void Invoke( InterruptData interruptData ) { m_callback( interruptData ); } // // Access Methods // public int Index { get { return m_index; } } public bool IsFastHandler { [RT.Inline] get { return (m_settings & InterruptSettings.Fast) != 0; } } public bool IsEdgeSensitive { [RT.Inline] get { return (m_settings & InterruptSettings.EdgeSensitive) != 0; } } public bool IsActiveHighOrRising { [RT.Inline] get { return (m_settings & InterruptSettings.ActiveHighOrRising) != 0;; } } } //--// static private readonly int c_Invalid = 0xFFFF; // ProcessorARMv[7|6]M.IRQn_Type.Invalid // // State // private RT.KernelList< Handler > m_handlers; private System.Threading.Thread m_interruptThread; private RT.KernelCircularBuffer m_interrupts; // // Helper Methods // public void Initialize() { m_handlers = new RT.KernelList< Handler >(); m_interrupts = new RT.KernelCircularBuffer(32); m_interruptThread = new System.Threading.Thread(DispatchInterrupts); m_interruptThread.Priority = System.Threading.ThreadPriority.Highest; } public void Activate() { m_interruptThread.Start(); } //--// public void RegisterAndEnable( Handler hnd ) { Register( hnd ); hnd.Enable(); } public void Register( Handler hnd ) { RT.BugCheck.AssertInterruptsOff(); var newPriority = hnd.m_priority; int priorityIdx = 0; // // Insert the handler in priority order and rebuild the Interrupt Priority Registers table. // for(RT.KernelNode node = m_handlers.StartOfForwardWalk; ; node = node.Next) { if(hnd != null) { if(node.IsValidForForwardMove == false || node.Target.m_priority < newPriority) { var newNode = hnd.m_node; newNode.InsertBefore( node ); node = newNode; hnd = null; } } if(node.IsValidForForwardMove == false) { break; } NVIC.SetPriority( node.Target.Index, (uint)priorityIdx++ ); } } //--// public void DeregisterAndDisable( Handler hnd ) { RT.BugCheck.AssertInterruptsOff(); hnd.Disable(); Deregister( hnd ); } public void Deregister( Handler hnd ) { RT.BugCheck.AssertInterruptsOff(); hnd.m_node.RemoveFromList(); } //--// public void ProcessInterrupt() { ProcessInterrupt( false ); } public void ProcessFastInterrupt() { ProcessInterrupt( true ); } public void ProcessInterrupt( bool fFastOnly ) { InterruptData data; int activeInterrupt = GetNextActiveInterrupt(); data.Context = 0; while (activeInterrupt != c_Invalid) { RT.KernelNode node = m_handlers.StartOfForwardWalk; while (true) { if (node.IsValidForForwardMove == false) { break; } Handler hnd = node.Target; if (hnd.Index == activeInterrupt) { data.Handler = hnd; if ( hnd.IsFastHandler ) { hnd.Invoke(data); } else { PostInterrupt(data); } } node = node.Next; } ClearInterrupt(activeInterrupt); activeInterrupt = GetNextActiveInterrupt(); } } public virtual int GetNextActiveInterrupt() { return c_Invalid; } public virtual void ClearInterrupt( int interrupt ) { } public void CauseInterrupt() { NVIC.SetPending( Board.Instance.GetSystemTimerIRQ() ); } public void ContinueUnderNormalInterrupt( RT.Peripherals.Continuation dlg ) { } public void PostInterrupt(InterruptData interruptData) { RT.BugCheck.AssertInterruptsOff(); m_interrupts.EnqueueNonblocking(interruptData); } private void DispatchInterrupts() { while (true) { InterruptData intr = m_interrupts.DequeueBlocking(); if (intr.Handler != null) { intr.Handler.Invoke( intr ); } } } // // Access Methods // public static extern InterruptController Instance { [RT.SingletonFactory()] [MethodImpl( MethodImplOptions.InternalCall )] get; } } } ================================================ FILE: Zelig/Zelig/RunTime/DeviceModels/ModelForCortexM/ModelForCortexM.csproj ================================================  Debug AnyCPU 9.0.21022 2.0 {E4C618AF-1785-472E-A070-8068E20582EB} Library Properties Microsoft.DeviceModels.Chipset.CortexM Microsoft.DeviceModels.ModelForCortexM $(LlilumBuildRoot)\Target\obj\$(MSBuildProjectName)\ v4.5 true full false $(LlilumBuildRoot)\Target\bin\$(Configuration)\ DEBUG;TRACE prompt 4 true true true AllRules.ruleset AnyCPU false pdbonly true $(LlilumBuildRoot)\Target\bin\$(Configuration)\ TRACE prompt 4 true true true AllRules.ruleset AnyCPU false true full false $(LlilumBuildRoot)\Target\bin\$(Configuration)\ true AnyCPU DEBUG;TRACE true true false {186F31A3-EF89-4A25-B2D5-20060501AA01} mscorlib False {186F31A3-EF89-4A25-B2D5-20070702AA01} system False {186F31A3-EF89-4A25-B2D5-20061218AA01} Common False {186F31A3-EF89-4A25-B2D5-20060509AA01} Kernel False {186F31A3-EF89-4A25-B2D5-20060720AA01} TypeSystem False {20DC2CF5-8EED-4231-9743-6BAB96BE465C} LlilumOSAbstraction 3.5 ================================================ FILE: Zelig/Zelig/RunTime/DeviceModels/ModelForCortexM/Properties/AssemblyInfo.cs ================================================ using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; // General Information about an assembly is controlled through the following // set of attributes. Change these attribute values to modify the information // associated with an assembly. [assembly: AssemblyTitle( "Microsoft.DeviceModels.ModelForCortexM" )] [assembly: AssemblyDescription( "" )] [assembly: AssemblyConfiguration( "" )] [assembly: AssemblyCompany( "Microsoft" )] [assembly: AssemblyProduct( "Microsoft.DeviceModels.ModelForCortexM" )] [assembly: AssemblyCopyright( "" )] [assembly: AssemblyTrademark( "" )] [assembly: AssemblyCulture( "" )] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible( false )] //// The following GUID is for the ID of the typelib if this project is exposed to COM //[assembly: Guid( "975a7db2-22e5-41c6-9e32-d3f72152d387" )] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Revision and Build Numbers // by using the '*' as shown below: [assembly: AssemblyVersion( "1.0.0.0" )] [assembly: AssemblyFileVersion( "1.0.0.0" )] ================================================ FILE: Zelig/Zelig/RunTime/DeviceModels/ModelForCortexM/SystemServices/ThreadManager.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // namespace Microsoft.DeviceModels.Chipset.CortexM.Runtime { using System; using Microsoft.Zelig.Runtime.TargetPlatform.ARMv7; using RT = Microsoft.Zelig.Runtime; public abstract class ThreadManager : RT.ARMv7ThreadManager { // // State // protected Drivers.ContextSwitchTimer m_contextSwitchTimer; // // Helper Methods // public override void InitializeBeforeStaticConstructors() { base.InitializeBeforeStaticConstructors(); } public override void InitializeAfterStaticConstructors( uint[] systemStack ) { base.InitializeAfterStaticConstructors( systemStack ); } //--// // // Extensibility // public override void Activate() { // // Activate the quantum timer, when the Idle Thread will run will enable exceptions, // thus letting the context switching to start // RT.BugCheck.AssertInterruptsOff( ); m_contextSwitchTimer = Drivers.ContextSwitchTimer.Instance; m_contextSwitchTimer.Reset(); } public override void CancelQuantumTimer() { m_contextSwitchTimer.Cancel(); } public override void SetNextQuantumTimer() { m_contextSwitchTimer.Reset( ); } public override void SetNextQuantumTimer( RT.SchedulerTime nextTimeout ) { DateTime dt = ( DateTime )nextTimeout; const long TicksPerMillisecond = 10000; // Number of 100ns ticks per time unit long ms = dt.Ticks / TicksPerMillisecond; if(ms > Drivers.ContextSwitchTimer.c_MaxCounterValue) { RT.BugCheck.Assert( false, RT.BugCheck.StopCode.IllegalSchedule ); } m_contextSwitchTimer.Schedule( (uint)ms ); } public override void TimeQuantumExpired() { // // this will cause the reschedule // base.TimeQuantumExpired( ); // // stage a PendSV request to complete the ContextSwitch // ProcessorARMv7M.CompleteContextSwitch( ); } } } ================================================ FILE: Zelig/Zelig/RunTime/DeviceModels/ModelForCortexM0/HardwareModel/Board.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // namespace Microsoft.DeviceModels.Chipset.CortexM0 { using ChipsetModel = Microsoft.DeviceModels.Chipset.CortexM; public abstract class Board : ChipsetModel.Board { } } ================================================ FILE: Zelig/Zelig/RunTime/DeviceModels/ModelForCortexM0/HardwareModel/Drivers/ContextSwitchTimer.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // //#define TIMERS_SELF_TEST namespace Microsoft.DeviceModels.Chipset.CortexM0.Drivers { using ChipsetModel = Microsoft.DeviceModels.Chipset.CortexM; public abstract class ContextSwitchTimer : ChipsetModel.Drivers.ContextSwitchTimer { } } ================================================ FILE: Zelig/Zelig/RunTime/DeviceModels/ModelForCortexM0/HardwareModel/Drivers/InterruptController.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // namespace Microsoft.DeviceModels.Chipset.CortexM0.Drivers { using ChipsetModel = Microsoft.DeviceModels.Chipset.CortexM; public abstract class InterruptController : ChipsetModel.Drivers.InterruptController { } } ================================================ FILE: Zelig/Zelig/RunTime/DeviceModels/ModelForCortexM0/HardwareModel/Processor.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // namespace Microsoft.DeviceModels.Chipset.CortexM0 { using System; using RT = Microsoft.Zelig.Runtime; using ChipsetModel = Microsoft.Zelig.Runtime.TargetPlatform.ARMv6; public abstract class Processor : ChipsetModel.ProcessorARMv6MForLlvm { // // Helper Methods // public override void InitializeProcessor() { base.InitializeProcessor(); } } } ================================================ FILE: Zelig/Zelig/RunTime/DeviceModels/ModelForCortexM0/ModelForCortexM0.csproj ================================================  Debug AnyCPU 9.0.21022 2.0 {C3BFAFAD-A6C6-471D-A059-B3CB7E57A4AB} Library Properties Microsoft.DeviceModels.Chipset.CortexM0 Microsoft.DeviceModels.ModelForCortexM0 $(LlilumBuildRoot)\Target\obj\$(MSBuildProjectName)\ v4.5 true full false $(LlilumBuildRoot)\Target\bin\$(Configuration)\ DEBUG;TRACE prompt 4 true true true AllRules.ruleset AnyCPU false pdbonly true $(LlilumBuildRoot)\Target\bin\$(Configuration)\ TRACE prompt 4 true true true AllRules.ruleset AnyCPU false true full false $(LlilumBuildRoot)\Target\bin\$(Configuration)\ true AnyCPU DEBUG;TRACE true true false {186F31A3-EF89-4A25-B2D5-20060501AA01} mscorlib False {186F31A3-EF89-4A25-B2D5-20070702AA01} system False {186F31A3-EF89-4A25-B2D5-20061218AA01} Common False {186F31A3-EF89-4A25-B2D5-20060509AA01} Kernel False {186F31A3-EF89-4A25-B2D5-20060720AA01} TypeSystem False {20DC2CF5-8EED-4231-9743-6BAB96BE465C} LlilumOSAbstraction {e4c618af-1785-472e-a070-8068e20582eb} ModelForCortexM 3.5 ================================================ FILE: Zelig/Zelig/RunTime/DeviceModels/ModelForCortexM0/Properties/AssemblyInfo.cs ================================================ using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; // General Information about an assembly is controlled through the following // set of attributes. Change these attribute values to modify the information // associated with an assembly. [assembly: AssemblyTitle( "Microsoft.DeviceModels.ModelForCortexM" )] [assembly: AssemblyDescription( "" )] [assembly: AssemblyConfiguration( "" )] [assembly: AssemblyCompany( "Microsoft" )] [assembly: AssemblyProduct( "Microsoft.DeviceModels.ModelForCortexM" )] [assembly: AssemblyCopyright( "" )] [assembly: AssemblyTrademark( "" )] [assembly: AssemblyCulture( "" )] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible( false )] //// The following GUID is for the ID of the typelib if this project is exposed to COM //[assembly: Guid( "975a7db2-22e5-41c6-9e32-d3f72152d387" )] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Revision and Build Numbers // by using the '*' as shown below: [assembly: AssemblyVersion( "1.0.0.0" )] [assembly: AssemblyFileVersion( "1.0.0.0" )] ================================================ FILE: Zelig/Zelig/RunTime/DeviceModels/ModelForCortexM0/SystemServices/ThreadManager.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // namespace Microsoft.DeviceModels.Chipset.CortexM0.Runtime { using System; using RT = Microsoft.Zelig.Runtime; // // A cortex M0 does not use the standard thread manager for M3/4 // i.e.: ThreadManager extends the ARMv6 thread manager type, rather than // Microsoft.DeviceModels.Chipset.CortexM.Runtime.ThreadManager // public abstract class ThreadManager : RT.ARMv6ThreadManager { // // State // protected Microsoft.DeviceModels.Chipset.CortexM.Drivers.ContextSwitchTimer m_contextSwitchTimer; // // Helper Methods // public override void InitializeBeforeStaticConstructors() { base.InitializeBeforeStaticConstructors(); } public override void InitializeAfterStaticConstructors(uint[] systemStack) { base.InitializeAfterStaticConstructors(systemStack); } //--// // // Extensibility // public override void Activate() { // // Activate the quantum timer, when the Idle Thread will run will enable exceptions, // thus letting the context switching to start // RT.BugCheck.AssertInterruptsOff(); m_contextSwitchTimer = Drivers.ContextSwitchTimer.Instance; m_contextSwitchTimer.Reset(); } public override void CancelQuantumTimer() { m_contextSwitchTimer.Cancel(); } public override void SetNextQuantumTimer() { m_contextSwitchTimer.Reset(); } public override void SetNextQuantumTimer(RT.SchedulerTime nextTimeout) { DateTime dt = (DateTime)nextTimeout; const long TicksPerMillisecond = 10000; // Number of 100ns ticks per time unit long ms = dt.Ticks / TicksPerMillisecond; if (ms > Drivers.ContextSwitchTimer.c_MaxCounterValue) { RT.BugCheck.Assert(false, RT.BugCheck.StopCode.IllegalSchedule); } m_contextSwitchTimer.Schedule((uint)ms); } public override void TimeQuantumExpired() { // // this will cause the reschedule // base.TimeQuantumExpired(); // // stage a PendSV request to complete the ContextSwitch // RT.TargetPlatform.ARMv6.ProcessorARMv6M.CompleteContextSwitch(); } } } ================================================ FILE: Zelig/Zelig/RunTime/DeviceModels/ModelForCortexM3/HardwareModel/Board.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // namespace Microsoft.DeviceModels.Chipset.CortexM3 { using ChipsetModel = Microsoft.DeviceModels.Chipset.CortexM; public abstract class Board : ChipsetModel.Board { } } ================================================ FILE: Zelig/Zelig/RunTime/DeviceModels/ModelForCortexM3/HardwareModel/Drivers/ContextSwitchTimer.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // //#define TIMERS_SELF_TEST namespace Microsoft.DeviceModels.Chipset.CortexM3.Drivers { using ChipsetModel = Microsoft.DeviceModels.Chipset.CortexM; public abstract class ContextSwitchTimer : ChipsetModel.Drivers.ContextSwitchTimer { } } ================================================ FILE: Zelig/Zelig/RunTime/DeviceModels/ModelForCortexM3/HardwareModel/Drivers/InterruptController.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // namespace Microsoft.DeviceModels.Chipset.CortexM3.Drivers { using ChipsetModel = Microsoft.DeviceModels.Chipset.CortexM; public abstract class InterruptController : ChipsetModel.Drivers.InterruptController { } } ================================================ FILE: Zelig/Zelig/RunTime/DeviceModels/ModelForCortexM3/HardwareModel/Processor.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // namespace Microsoft.DeviceModels.Chipset.CortexM3 { using RT = Microsoft.Zelig.Runtime; using ChipsetModel = Microsoft.Zelig.Runtime.TargetPlatform.ARMv7; public abstract class Processor : ChipsetModel.ProcessorARMv7MForLlvm { // // Helper Methods // public override void InitializeProcessor() { base.InitializeProcessor(); } } } ================================================ FILE: Zelig/Zelig/RunTime/DeviceModels/ModelForCortexM3/ModelForCortexM3.csproj ================================================  Debug AnyCPU 9.0.21022 2.0 {A30EB003-94F8-4A85-8DA1-006F6810A7A4} Library Properties Microsoft.DeviceModels.Chipset.CortexM3 Microsoft.DeviceModels.ModelForCortexM3 $(LlilumBuildRoot)\Target\obj\$(MSBuildProjectName)\ v4.5 true full false $(LlilumBuildRoot)\Target\bin\$(Configuration)\ DEBUG;TRACE prompt 4 true true true AllRules.ruleset AnyCPU false pdbonly true $(LlilumBuildRoot)\Target\bin\$(Configuration)\ TRACE prompt 4 true true true AllRules.ruleset AnyCPU false true full false $(LlilumBuildRoot)\Target\bin\$(Configuration)\ true AnyCPU DEBUG;TRACE true true false {186F31A3-EF89-4A25-B2D5-20060501AA01} mscorlib False {186F31A3-EF89-4A25-B2D5-20070702AA01} system False {186F31A3-EF89-4A25-B2D5-20061218AA01} Common False {186F31A3-EF89-4A25-B2D5-20060509AA01} Kernel False {186F31A3-EF89-4A25-B2D5-20060720AA01} TypeSystem False {20DC2CF5-8EED-4231-9743-6BAB96BE465C} LlilumOSAbstraction {e4c618af-1785-472e-a070-8068e20582eb} ModelForCortexM 3.5 ================================================ FILE: Zelig/Zelig/RunTime/DeviceModels/ModelForCortexM3/Properties/AssemblyInfo.cs ================================================ using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; // General Information about an assembly is controlled through the following // set of attributes. Change these attribute values to modify the information // associated with an assembly. [assembly: AssemblyTitle( "Microsoft.DeviceModels.ModelForCortexM3" )] [assembly: AssemblyDescription( "" )] [assembly: AssemblyConfiguration( "" )] [assembly: AssemblyCompany( "Microsoft" )] [assembly: AssemblyProduct( "LLILUM" )] [assembly: AssemblyCopyright( "Copyright © Microsoft 2015" )] [assembly: AssemblyTrademark( "" )] [assembly: AssemblyCulture( "" )] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible( false )] //// The following GUID is for the ID of the typelib if this project is exposed to COM //[assembly: Guid( "975a7db2-22e5-41c6-9e32-d3f72152d387" )] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Revision and Build Numbers // by using the '*' as shown below: [assembly: AssemblyVersion( "1.0.0.0" )] [assembly: AssemblyFileVersion( "1.0.0.0" )] ================================================ FILE: Zelig/Zelig/RunTime/DeviceModels/ModelForCortexM3/SystemServices/ThreadManager.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // namespace Microsoft.DeviceModels.Chipset.CortexM3.Runtime { using ChipsetModel = Microsoft.DeviceModels.Chipset.CortexM; public abstract class ThreadManager : ChipsetModel.Runtime.ThreadManager { } } ================================================ FILE: Zelig/Zelig/RunTime/DeviceModels/ModelForCortexM4/HardwareModel/Board.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // namespace Microsoft.DeviceModels.Chipset.CortexM4 { public abstract class Board : Microsoft.DeviceModels.Chipset.CortexM3.Board { } } ================================================ FILE: Zelig/Zelig/RunTime/DeviceModels/ModelForCortexM4/HardwareModel/Drivers/ContextSwitchTimer.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // //#define TIMERS_SELF_TEST namespace Microsoft.DeviceModels.Chipset.CortexM4.Drivers { public abstract class ContextSwitchTimer : Microsoft.DeviceModels.Chipset.CortexM3.Drivers.ContextSwitchTimer { } } ================================================ FILE: Zelig/Zelig/RunTime/DeviceModels/ModelForCortexM4/HardwareModel/Drivers/InterruptController.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // namespace Microsoft.DeviceModels.Chipset.CortexM4.Drivers { public abstract class InterruptController : Microsoft.DeviceModels.Chipset.CortexM3.Drivers.InterruptController { } } ================================================ FILE: Zelig/Zelig/RunTime/DeviceModels/ModelForCortexM4/HardwareModel/Processor.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // namespace Microsoft.DeviceModels.Chipset.CortexM4 { using Microsoft.DeviceModels.Chipset.CortexM; using RT = Microsoft.Zelig.Runtime; using ChipsetModel = Microsoft.Zelig.Runtime.TargetPlatform.ARMv7; public abstract class Processor : ChipsetModel.ProcessorARMv7MForLlvm_VFP { // // Helper Methods // public override void InitializeProcessor() { base.InitializeProcessor(); } } } ================================================ FILE: Zelig/Zelig/RunTime/DeviceModels/ModelForCortexM4/ModelForCortexM4.csproj ================================================  Debug AnyCPU 9.0.21022 2.0 {CA8A6D38-528B-4FAA-89B6-8FA9178DE55D} Library Properties Microsoft.DeviceModels.Chipset.CortexM4 Microsoft.DeviceModels.ModelForCortexM4 $(LlilumBuildRoot)\Target\obj\$(MSBuildProjectName)\ v4.5 true full false $(LlilumBuildRoot)\Target\bin\$(Configuration)\ DEBUG;TRACE prompt 4 true true true AllRules.ruleset AnyCPU false pdbonly true $(LlilumBuildRoot)\Target\bin\$(Configuration)\ TRACE prompt 4 true true true AllRules.ruleset AnyCPU false true full false $(LlilumBuildRoot)\Target\bin\$(Configuration)\ true AnyCPU DEBUG;TRACE true true false {186F31A3-EF89-4A25-B2D5-20060501AA01} mscorlib False {186F31A3-EF89-4A25-B2D5-20070702AA01} system False {186F31A3-EF89-4A25-B2D5-20061218AA01} Common False {186F31A3-EF89-4A25-B2D5-20060509AA01} Kernel False {186F31A3-EF89-4A25-B2D5-20060720AA01} TypeSystem False {a30eb003-94f8-4a85-8da1-006f6810a7a4} ModelForCortexM3 {e4c618af-1785-472e-a070-8068e20582eb} ModelForCortexM 3.5 ================================================ FILE: Zelig/Zelig/RunTime/DeviceModels/ModelForCortexM4/Properties/AssemblyInfo.cs ================================================ using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; // General Information about an assembly is controlled through the following // set of attributes. Change these attribute values to modify the information // associated with an assembly. [assembly: AssemblyTitle( "Microsoft.DeviceModels.ModelForLPC3180" )] [assembly: AssemblyDescription( "" )] [assembly: AssemblyConfiguration( "" )] [assembly: AssemblyCompany( "Microsoft" )] [assembly: AssemblyProduct( "Microsoft.DeviceModels.ModelForLPC3180" )] [assembly: AssemblyCopyright( "Copyright © Microsoft 2007" )] [assembly: AssemblyTrademark( "" )] [assembly: AssemblyCulture( "" )] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible( false )] //// The following GUID is for the ID of the typelib if this project is exposed to COM //[assembly: Guid( "975a7db2-22e5-41c6-9e32-d3f72152d387" )] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Revision and Build Numbers // by using the '*' as shown below: [assembly: AssemblyVersion( "1.0.0.0" )] [assembly: AssemblyFileVersion( "1.0.0.0" )] ================================================ FILE: Zelig/Zelig/RunTime/DeviceModels/ModelForCortexM4/SystemServices/ThreadManager.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // namespace Microsoft.DeviceModels.Chipset.CortexM4.Runtime { public abstract class ThreadManager : Microsoft.DeviceModels.Chipset.CortexM3.Runtime.ThreadManager { } } ================================================ FILE: Zelig/Zelig/RunTime/DeviceModels/ModelForLPC3180/HardwareModel/ChipSet/LPC3180/GPDMA.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // namespace Microsoft.DeviceModels.Chipset.LPC3180 { using System; using System.Runtime.CompilerServices; using Microsoft.Zelig.Runtime; [MemoryMappedPeripheral(Base=0x31000000U,Length=0x00000200U)] public class GPDMA { [MemoryMappedPeripheral(Base=0x0000U,Length=0x0020U)] public class Channel { [BitFieldPeripheral(PhysicalType=typeof(uint))] public struct LLI_bitfield { [BitFieldRegister(Position=0)] public bool UseM1; // AHB master select for loading the next LLI: // // 0 - AHB Master 0. // 1 - AHB Master 1. } //--// [BitFieldPeripheral(PhysicalType=typeof(uint))] public struct Control_bitfield { public enum Width { Byte = 0, // 000 - Byte (8-bit) Halfword = 1, // 001 - Halfword (16-bit) Word = 2, // 010 - Word (32-bit) // 011 to 111 - Reserved } public enum BurstSize { Len1 = 0, // 000 - 1 Len4 = 1, // 001 - 4 Len8 = 2, // 010 - 8 Len16 = 3, // 011 - 16 Len32 = 4, // 100 - 32 Len64 = 5, // 101 - 64 Len128 = 6, // 110 - 128 Len256 = 7, // 111 - 256 } [BitFieldRegister(Position=31 )] public bool InterruptEnable; // Terminal count interrupt enable bit. // // 0 - the terminal count interrupt is disabled. // 1 - the terminal count interrupt is enabled. // // [BitFieldRegister(Position=30 )] public bool Cacheable; // Indicates that the access is cacheable or not cacheable: // // 0 - access is not cacheable. // 1 - access is cacheable. // // [BitFieldRegister(Position=29 )] public bool Bufferable; // Indicates that the access is bufferable or not bufferable: // // 0 - access is not bufferable. // 1 - access is bufferable. // // [BitFieldRegister(Position=28 )] public bool PrivilegedMode; // Indicates that the access is in user mode or privileged mode: // // 0 - access is in user mode. // 1 - access is in privileged mode. // // [BitFieldRegister(Position=27 )] public bool DestinationIncrement; // Destination increment: // // 0 - the destination address is not incremented after each transfer. // 1 - the destination address is incremented after each transfer. // // [BitFieldRegister(Position=26 )] public bool SourceIncrement; // Source increment: // // 0 - the source address is not incremented after each transfer. // 1 - the source address is incremented after each transfer. // // [BitFieldRegister(Position=25 )] public bool DestinationUsesM1; // Destination AHB master select: // // 0 - AHB Master 0 selected for destination transfer. // 1 - AHB Master 1 selected for destination transfer. // // [BitFieldRegister(Position=24 )] public bool SourceUsesM1; // Source AHB master select: // // 0 - AHB Master 0 selected for source transfer. // 1 - AHB Master 1 selected for source transfer. // // [BitFieldRegister(Position=21,Size=3)] public Width DWidth; // Destination transfer width. // // Transfers wider than the AHB master bus width are illegal. // The source and destination widths can be different from each other. // The hardware automatically packs and unpacks the data as required. // // [BitFieldRegister(Position=18,Size=3)] public Width SWidth; // Source transfer width. // // Transfers wider than the AHB master bus width are illegal. // The source and destination widths can be different from each other. // The hardware automatically packs and unpacks the data as required. // // [BitFieldRegister(Position=15,Size=3)] public BurstSize DBSize; // Destination burst size. // // Indicates the number of transfers that make up a destination burst request. // This value must be set to the burst size of the destination peripheral, or if the destination is memory, to the memory boundary size. // The burst size is the amount of data that is transferred when the DMACBREQ signal goes active in the destination peripheral. // // [BitFieldRegister(Position=12,Size=3)] public BurstSize SBSize; // Source burst size. // // Indicates the number of transfers that make up a source burst. // This value must be set to the burst size of the source peripheral, or if the source is memory, to the memory boundary size. // The burst size is the amount of data that is transferred when the DMACBREQ signal goes active in the source peripheral. // // [BitFieldRegister(Position= 0,Size=12)] public uint TransferSize; // Transfer size. // // A write to this field sets the size of the transfer when the DMA Controller is the flow controller. // The transfer size value must be set before the channel is enabled. // Transfer size is updated as data transfers are completed. // A read from this field indicates the number of transfers completed on the destination bus. // Reading the register when the channel is active does not give useful information because by the time // that the software has processed the value read, the channel might have progressed. // It is intended to be used only when a channel is enabled and then disabled. // The transfer size value is not used if the DMA Controller is not the flow controller. // } //--// [BitFieldPeripheral(PhysicalType=typeof(uint))] public struct Config_bitfield { public enum FlowControl { M2M_D = 0, // 000 Memory to memory DMA M2P_D = 1, // 001 Memory to peripheral DMA P2M_D = 2, // 010 Peripheral to memory DMA P2P_D = 3, // 011 Source peripheral to destination peripheral DMA P2P_DP = 4, // 100 Source peripheral to destination peripheral Destination peripheral M2P_P = 5, // 101 Memory to peripheral Peripheral P2M_P = 6, // 110 Peripheral to memory Peripheral P2P_SP = 7, // 111 Source peripheral to destination peripheral Source peripheral } public enum Peripheral { SPI1 = 11, // SPI1 receive and transmit Uart7__Rx = 10, // HS-Uart7 receive Uart7__Tx = 9, // HS-Uart7 transmit Uart2__Rx = 8, // HS-Uart2 receive Uart2__Tx = 7, // HS-Uart2 transmit Uart1__Rx = 6, // HS-Uart1 receive Uart1__Tx = 5, // HS-Uart1 transmit SD_Card = 4, // SD Card interface receive and transmit SPI2 = 3, // SPI2 receive and transmit NAND_Flash = 1, // NAND Flash (same as channel 12) } [BitFieldRegister(Position=18 )] public bool H; // Halt: // // 0 = enable DMA requests. // 1 = ignore further source DMA requests. // // The contents of the channel FIFO are drained. // This value can be used with the Active and Channel Enable bits to cleanly disable a DMA channel. // // [BitFieldRegister(Position=17 )] public bool A; // Active: // // 0 = there is no data in the FIFO of the channel. // 1 = the channel FIFO has data. // // This value can be used with the Halt and Channel Enable bits to cleanly disable a DMA channel. // This is a read-only bit. // // [BitFieldRegister(Position=16 )] public bool L; // Lock. // // When set, this bit enables locked transfers. // // [BitFieldRegister(Position=15 )] public bool ITC; // Terminal count interrupt mask. // // When cleared, this bit masks out the terminal count interrupt of the relevant channel. // // [BitFieldRegister(Position=14 )] public bool IE; // Interrupt error mask. // // When cleared, this bit masks out the error interrupt of the relevant channel. // // [BitFieldRegister(Position=11,Size=3)] public FlowControl FlowCntrl; // Flow control and transfer type. // // This value indicates the flow controller and transfer type. // The flow controller can be the DMA Controller, the source peripheral, or the destination peripheral. // The transfer type can be memory-to-memory, memory-to-peripheral, peripheral-to-memory, or peripheral-to-peripheral. // // [BitFieldRegister(Position= 6,Size=5)] public Peripheral DestPeripheral; // Source peripheral. // // This value selects the DMA source request peripheral. This field is ignored if the source of the transfer is from memory. // // [BitFieldRegister(Position= 1,Size=5)] public Peripheral SrcPeripheral; // Source peripheral. // // This value selects the DMA source request peripheral. This field is ignored if the source of the transfer is from memory. // // [BitFieldRegister(Position= 0 )] public bool E; // Channel enable. // // Reading this bit indicates whether a channel is currently enabled or disabled: // // 0 = channel disabled. // 1 = channel enabled. // // The Channel Enable bit status can also be found by reading the DMACEnbldChns Register. // A channel is enabled by setting this bit. // A channel can be disabled by clearing the Enable bit. // This causes the current AHB transfer (if one is in progress) to complete and the channel is then disabled. // Any data in the FIFO of the relevant channel is lost. // Restarting the channel by setting the Channel Enable bit has unpredictable effects, the channel must be fully re-initialized. // The channel is also disabled, and Channel Enable bit cleared, when the last LLI is reached, the DMA transfer is completed, or if a channel error is encountered. // If a channel must be disabled without losing data in the FIFO, the Halt bit must be set so that further DMA requests are ignored. // The Active bit must then be polled until it reaches 0, indicating that there is no data left in the FIFO. // Finally, the Channel Enable bit can be cleared. // } //--// [Register(Offset=0x00U)] public uint SrcAddr; // Source Address Register 0 R/W [Register(Offset=0x04U)] public uint DestAddr; // Destination Address Register 0 R/W [Register(Offset=0x08U)] public LLI_bitfield LLI; // Linked List Item Register 0 R/W [Register(Offset=0x0CU)] public Control_bitfield Control; // Control Register 0 R/W [Register(Offset=0x10U)] public Config_bitfield Config; // Configuration Register 0[1] R/W // // Helper Methods // [Inline] public void WaitForCompletion() { while(this.IsActive) { } } [Inline] public unsafe void CopyMemory( uint* src , uint* dst , uint numOfWords , uint burstSize , bool fSrcIncrement , bool fDstIncrement , bool fUseSameMaster ) { #if USE_CPU Memory.CopyNonOverlapping( new UIntPtr( src ), new UIntPtr( &src[numOfWords] ), new UIntPtr( dst ) ); #else WaitForCompletion(); //--// var ctrl = new Control_bitfield(); ctrl.Cacheable = false; ctrl.Bufferable = false; ctrl.PrivilegedMode = true; ctrl.SWidth = Control_bitfield.Width.Word; ctrl.DWidth = Control_bitfield.Width.Word; if(fUseSameMaster) { ctrl.SourceUsesM1 = false; ctrl.DestinationUsesM1 = false; } else { ctrl.SourceUsesM1 = false; ctrl.DestinationUsesM1 = true; } ctrl.SourceIncrement = fSrcIncrement; ctrl.DestinationIncrement = fDstIncrement; switch(burstSize) { case 1: ctrl.SBSize = Control_bitfield.BurstSize.Len1; ctrl.DBSize = Control_bitfield.BurstSize.Len1; break; case 4: ctrl.SBSize = Control_bitfield.BurstSize.Len4; ctrl.DBSize = Control_bitfield.BurstSize.Len4; break; case 8: ctrl.SBSize = Control_bitfield.BurstSize.Len8; ctrl.DBSize = Control_bitfield.BurstSize.Len8; break; case 16: ctrl.SBSize = Control_bitfield.BurstSize.Len16; ctrl.DBSize = Control_bitfield.BurstSize.Len16; break; case 32: ctrl.SBSize = Control_bitfield.BurstSize.Len32; ctrl.DBSize = Control_bitfield.BurstSize.Len32; break; case 64: ctrl.SBSize = Control_bitfield.BurstSize.Len64; ctrl.DBSize = Control_bitfield.BurstSize.Len64; break; case 128: ctrl.SBSize = Control_bitfield.BurstSize.Len128; ctrl.DBSize = Control_bitfield.BurstSize.Len128; break; case 256: ctrl.SBSize = Control_bitfield.BurstSize.Len256; ctrl.DBSize = Control_bitfield.BurstSize.Len256; break; } ctrl.TransferSize = numOfWords; //--// var config = new Config_bitfield(); config.L = true; config.FlowCntrl = Config_bitfield.FlowControl.M2M_D; config.E = true; //--// this.SrcAddr = (uint)src; this.DestAddr = (uint)dst; this.LLI = new LLI_bitfield(); this.Control = ctrl; this.Config = config; #endif } // // Access Methods // public bool IsActive { [Inline] get { return this.Config.E; } } // // Debug Methods // } //--// [BitFieldPeripheral(PhysicalType=typeof(uint))] public struct DMACConfig_bitfield { [BitFieldRegister(Position=2)] public bool M1_BigEndian; // AHB Master 1 endianness configuration: // // 0 = little-endian mode (default). // 1 = big-endian mode. // // [BitFieldRegister(Position=1)] public bool M0_BigEndian; // AHB Master 0 endianness configuration: // // 0 = little-endian mode (default). // 1 = big-endian mode. // // [BitFieldRegister(Position=0)] public bool E; // DMA Controller enable: // // 0 = disabled (default). Disabling the DMA Controller reduces power consumption. // 1 = enabled. // } //--// [Register(Offset=0x00U)] public uint DMACIntStat; // DMA Interrupt Status Register 0 RO [Register(Offset=0x04U)] public uint DMACIntTCStat; // DMA Interrupt Terminal Count Request Status Register 0 RO [Register(Offset=0x08U)] public uint DMACIntTCClear; // DMA Interrupt Terminal Count Request Clear Register - WO [Register(Offset=0x0CU)] public uint DMACIntErrStat; // DMA Interrupt Error Status Register 0 RO [Register(Offset=0x10U)] public uint DMACIntErrClr; // DMA Interrupt Error Clear Register - WO [Register(Offset=0x14U)] public uint DMACRawIntTCStat; // DMA Raw Interrupt Terminal Count Status Register 0 RO [Register(Offset=0x18U)] public uint DMACRawIntErrStat; // DMA Raw Error Interrupt Status Register 0 RO [Register(Offset=0x1CU)] public uint DMACEnbldChns; // DMA Enabled Channel Register 0 RO [Register(Offset=0x20U)] public uint DMACSoftBReq; // DMA Software Burst Request Register 0 R/W [Register(Offset=0x24U)] public uint DMACSoftSReq; // DMA Software Single Request Register 0 R/W [Register(Offset=0x28U)] public uint DMACSoftLBReq; // DMA Software Last Burst Request Register 0 R/W [Register(Offset=0x2CU)] public uint DMACSoftLSReq; // DMA Software Last Single Request Register 0 R/W [Register(Offset=0x30U)] public DMACConfig_bitfield DMACConfig; // DMA Configuration Register 0 R/W [Register(Offset=0x34U)] public uint DMACSync; // DMA Synchronization Register 0 R/W [Register(Offset=0x00000100U,Instances=8)] public Channel[] Channels; //--// // // Helper Methods // [Inline] public void Enable() { SystemControl.Instance.DMACLK_CTRL.Enable = true; this.DMACConfig.E = true; } [Inline] public void Disable() { this.DMACConfig.E = false; SystemControl.Instance.DMACLK_CTRL.Enable = false; } // // Access Methods // public static extern GPDMA Instance { [SingletonFactory()] [MethodImpl( MethodImplOptions.InternalCall )] get; } } } ================================================ FILE: Zelig/Zelig/RunTime/DeviceModels/ModelForLPC3180/HardwareModel/ChipSet/LPC3180/GPIO.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // namespace Microsoft.DeviceModels.Chipset.LPC3180 { using System.Runtime.CompilerServices; using Microsoft.Zelig.Runtime; [MemoryMappedPeripheral(Base=0x40028000U,Length=0x00000034U)] public class GPIO { [Register(Offset=0x00U)] public uint PIO_INP_STATE; // Input pin state register. Reads the state of input pins. - RO [Register(Offset=0x04U)] public uint PIO_OUTP_SET; // Output pin set register. Allows setting output pin(s). - WO [Register(Offset=0x08U)] public uint PIO_OUTP_CLR; // Output pin clear register. Allows clearing output pin(s). - WO [Register(Offset=0x0CU)] public uint PIO_OUTP_STATE; // Output pin state register. Reads the state of output pins. - RO [Register(Offset=0x10U)] public uint PIO_DIR_SET; // GPIO direction set register. Configures I/O pins as outputs. - WO [Register(Offset=0x14U)] public uint PIO_DIR_CLR; // GPIO direction clear register. Configures I/O pins as inputs. - WO [Register(Offset=0x18U)] public uint PIO_DIR_STATE; // GPIO direction state register. Reads back pin directions. 0 RO [Register(Offset=0x1CU)] public uint PIO_SDINP_STATE; // Input pin state register for SDRAM pins. Reads the state of SDRAM input pins. - RO [Register(Offset=0x20U)] public uint PIO_SDOUTP_SET; // Output pin set register for SDRAM pins. Allows setting SDRAM output pin(s). - WO [Register(Offset=0x24U)] public uint PIO_SDOUTP_CLR; // Output pin clear register for SDRAM pins. Allows clearing SDRAM output pin(s). - WO [Register(Offset=0x28U)] public uint PIO_MUX_SET; // PIO multiplexer control set register. Controls the selection of alternate functions on certain pins. - WO [Register(Offset=0x2CU)] public uint PIO_MUX_CLR; // PIO multiplexer control clear register. Controls the selection of alternate functions on certain pins. - WO [Register(Offset=0x30U)] public uint PIO_MUX_STATE; // PIO multiplexer state register. Reads back the selection of alternate functions on certain pins. 0x00000000 RO //--// // // Helper Methods // [Inline] public void SetGPO( int pin ) { this.PIO_OUTP_SET = 1U << pin; } [Inline] public void ResetGPO( int pin ) { this.PIO_OUTP_CLR = 1U << pin; } // // Access Methods // public static extern GPIO Instance { [SingletonFactory()] [MethodImpl( MethodImplOptions.InternalCall )] get; } } } ================================================ FILE: Zelig/Zelig/RunTime/DeviceModels/ModelForLPC3180/HardwareModel/ChipSet/LPC3180/HighSpeedTimer.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // namespace Microsoft.DeviceModels.Chipset.LPC3180 { using System; using System.Runtime.CompilerServices; using Microsoft.Zelig.Runtime; [MemoryMappedPeripheral(Base=0x40038000U,Length=0x34U)] public class HighSpeedTimer { //// 0x4003 8028 HSTIM_CCR High Speed timer capture control register 0 R/W //// 0x4003 802C HSTIM_CR0 High Speed timer capture 0 register 0 RO //// 0x4003 8030 HSTIM_CR1 High Speed timer capture 1 register 0 RO [BitFieldPeripheral(PhysicalType=typeof(uint))] public struct HSTIM_INT_bitfield { [BitFieldRegister(Position=5)] public bool RTC_TICK; // Reading a 1 indicates an active RTC tick capture status. Write 1 to clear this status. // Note that this status can not generate an ARM interrupt. // The pins can however generate PIO interrupts directly. // [BitFieldRegister(Position=4)] public bool GPI_06; // Reading a 1 indicates an active GPI_06 status. Write 1 to clear this status. // Note that this status can not generate an ARM interrupt. // The pins can however generate PIO interrupts directly. // [BitFieldRegister(Position=2)] public bool MATCH2_INT; // Reading a 1 indicates an active MATCH 2 interrupt. // // Writing a 1 clears the active interrupt status. Writing 0 has no effect. // Note: Remove active match status by writing a new match value before clearing the interrupt. // Otherwise this a new match interrupt may be activated immediately after clearing the match interrupt since the match may still be valid. // [BitFieldRegister(Position=1)] public bool MATCH1_INT; // Reading a 1 indicates an active MATCH 1 interrupt. // // Writing a 1 clears the active interrupt status. Writing 0 has no effect. // Note: Remove active match status by writing a new match value before clearing the interrupt. // Otherwise this a new match interrupt may be activated immediately after clearing the match interrupt since the match may still be valid. // [BitFieldRegister(Position=0)] public bool MATCH0_INT; // Reading a 1 indicates an active MATCH 0 interrupt. // // Writing a 1 clears the active interrupt status. Writing 0 has no effect. // Note: Remove active match status by writing a new match value before clearing the interrupt. // Otherwise this a new match interrupt may be activated immediately after clearing the match interrupt since the match may still be valid. // } //--// [BitFieldPeripheral(PhysicalType=typeof(uint))] public struct HSTIM_CTRL_bitfield { [BitFieldRegister(Position=2)] public bool PAUSE_EN; // *0 = Timer counter continues to run if ARM enters debug mode. // 1 = Timer counter is stopped when the core is in debug mode (DBGACK high). // [BitFieldRegister(Position=1)] public bool RESET_COUNT; // *0 = Timer counter is not reset. // 1 = Timer counter will be reset on next PERIPH_CLK edge. Software must write this bit back to low to release the reset. // [BitFieldRegister(Position=0)] public bool COUNT_ENAB; // *0 = Timer Counter is stopped. // 1 = Timer Counter is enabled. } //--// [BitFieldPeripheral(PhysicalType=typeof(uint))] public struct HSTIM_MCTRL_bitfield { [BitFieldRegister(Position=8)] public bool STOP_COUNT2; // *0 = Disable the stop functionality on Match 2. // 1 = Enable the Timer Counter to be stopped on Match 2. // [BitFieldRegister(Position=7)] public bool RESET_COUNT2; // *0 = Disable reset of Timer Counter on Match 2. // 1 = Enable reset of Timer Counter on Match 2. // [BitFieldRegister(Position=6)] public bool MR2_INT; // *0 = Disable interrupt on the Match 2 register. // 1 = Enable internal interrupt status generation on the Match 2 register. // [BitFieldRegister(Position=5)] public bool STOP_COUNT1; // *0 = Disable the stop functionality on Match 1. // 1 = Enable the Timer Counter to be stopped on Match 1. // [BitFieldRegister(Position=4)] public bool RESET_COUNT1; // *0 = Disable reset of Timer Counter on Match 1. // 1 = Enable reset of Timer Counter on Match 1. // [BitFieldRegister(Position=3)] public bool MR1_INT; // *0 = Disable interrupt on the Match 1 register. // 1 = Enable internal interrupt status generation on the Match 1 register. // [BitFieldRegister(Position=2)] public bool STOP_COUNT0; // *0 = Disable the stop functionality on Match 0. // 1 = Enable the Timer Counter to be stopped on Match 0. // [BitFieldRegister(Position=1)] public bool RESET_COUNT0; // *0 = Disable reset of Timer Counter on Match 0. // 1 = Enable reset of Timer Counter on Match 0. // [BitFieldRegister(Position=0)] public bool MR0_INT; // *0 = Disable interrupt on the Match 0 register. // 1 = Enable internal interrupt status generation on the Match 0 register. } //--// [BitFieldPeripheral(PhysicalType=typeof(uint))] public struct HSTIM_CCR_bitfield { [BitFieldRegister(Position=5)] public bool RTC_TICK_EVENT; // If this bit is set, an interrupt status will be set in the HSTIM_INT register on a capture. // [BitFieldRegister(Position=4)] public bool RTC_TICK_FALL; // If this bit is set, the timer counter will be loaded into the CR1 if a falling edge is detected on RTC_TICK. // [BitFieldRegister(Position=3)] public bool RTC_TICK_RISE; // If this bit is set, the timer counter will be loaded into the CR1 if a rising edge is detected on RTC_TICK. // [BitFieldRegister(Position=2)] public bool GPI_06_EVENT; // If this bit is set, an interrupt status will be set in the HSTIM_INT register on a capture. // [BitFieldRegister(Position=1)] public bool GPI_06_FALL; // If this bit is set, the timer counter will be loaded into the CR0 if a falling edge is detected on GPI_06. // [BitFieldRegister(Position=0)] public bool GPI_06_RISE; // If this bit is set, the timer counter will be loaded into the CR0 if a rising edge is detected on GPI_06 // } //--// [Register(Offset=0x00000000)] public HSTIM_INT_bitfield HSTIM_INT; // High Speed timer interrupt status register 0 R/W [Register(Offset=0x00000004)] public HSTIM_CTRL_bitfield HSTIM_CTRL; // High Speed timer control register 0 R/W [Register(Offset=0x00000008)] public uint HSTIM_COUNTER; // High Speed timer counter value register 0 R/W [Register(Offset=0x0000000C)] public uint HSTIM_PMATCH; // High Speed timer prescale counter match register 0 R/W [Register(Offset=0x00000010)] public uint HSTIM_PCOUNT; // High Speed Timer prescale counter value register 0 R/W [Register(Offset=0x00000014)] public HSTIM_MCTRL_bitfield HSTIM_MCTRL; // High Speed timer match control register 0 R/W [Register(Offset=0x00000018)] public uint HSTIM_MATCH0; // High Speed timer match 0 register 0 R/W [Register(Offset=0x0000001C)] public uint HSTIM_MATCH1; // High Speed timer match 1 register 0 R/W [Register(Offset=0x00000020)] public uint HSTIM_MATCH2; // High Speed timer match 2 register 0 R/W [Register(Offset=0x00000028)] public HSTIM_CCR_bitfield HSTIM_CCR; // High Speed timer capture control register 0 R/W [Register(Offset=0x0000002C)] public uint HSTIM_CR0; // High Speed timer capture 0 register 0 RO [Register(Offset=0x00000030)] public uint HSTIM_CR1; // High Speed timer capture 1 register 0 RO // // Access Methods // public static extern HighSpeedTimer Instance { [SingletonFactory()] [MethodImpl( MethodImplOptions.InternalCall )] get; } } } ================================================ FILE: Zelig/Zelig/RunTime/DeviceModels/ModelForLPC3180/HardwareModel/ChipSet/LPC3180/INTC.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // namespace Microsoft.DeviceModels.Chipset.LPC3180 { using System; using System.Runtime.CompilerServices; using Microsoft.Zelig.Runtime; [MemoryMappedPeripheral(Base=0x40008000U,Length=0x00014000U)] public class INTC { public const int IRQ_INDEX_Sub2FIQn = 0 + 31; // High priority (FIQ) interrupts from SIC2. Active LOW. public const int IRQ_INDEX_Sub1FIQn = 0 + 30; // High priority (FIQ) interrupts from SIC1. Active LOW. public const int IRQ_INDEX_DMAINT = 0 + 28; // General Purpose DMA Controller interrupt. public const int IRQ_INDEX_MSTIMER_INT = 0 + 27; // Match interrupt 0 or 1 from the Millisecond Timer. public const int IRQ_INDEX_IIR1 = 0 + 26; // UART1 interrupt. public const int IRQ_INDEX_IIR2 = 0 + 25; // UART2 interrupt. public const int IRQ_INDEX_IIR7 = 0 + 24; // UART7 interrupt. public const int IRQ_INDEX_SD0_INT = 0 + 15; // Interrupt 0 from the SD Card interface. public const int IRQ_INDEX_SD1_INT = 0 + 13; // Interrupt 1 from the SD Card interface. public const int IRQ_INDEX_FLASH_INT = 0 + 11; // Interrupt from the NAND Flash controller. public const int IRQ_INDEX_IIR6 = 0 + 10; // UART6 interrupt. public const int IRQ_INDEX_IIR5 = 0 + 9; // UART5 interrupt. public const int IRQ_INDEX_IIR4 = 0 + 8; // UART4 interrupt. public const int IRQ_INDEX_IIR3 = 0 + 7; // UART3 interrupt. public const int IRQ_INDEX_WATCH_INT = 0 + 6; // Watchdog Timer interrupt. public const int IRQ_INDEX_HSTIMER_INT = 0 + 5; // Match interrupt from the High Speed Timer. public const int IRQ_INDEX_Sub2IRQn = 0 + 1; // Low priority (FIQ) interrupts from SIC2. Active LOW. public const int IRQ_INDEX_Sub1IRQn = 0 + 0; // Low priority (FIQ) interrupts from SIC1. Active LOW. public const int IRQ_INDEX_USB_i2c_int = 32 + 31; // Interrupt from the USB I2C interface. public const int IRQ_INDEX_USB_dev_hp_int = 32 + 30; // USB high priority interrupt. public const int IRQ_INDEX_USB_dev_lp_int = 32 + 29; // USB low priority interrupt. public const int IRQ_INDEX_USB_dev_dma_int = 32 + 28; // USB DMA interrupt. public const int IRQ_INDEX_USB_host_int = 32 + 27; // USB host interrupt. public const int IRQ_INDEX_USB_otg_atx_int_n = 32 + 26; // External USB transceiver interrupt. Active LOW. public const int IRQ_INDEX_USB_otg_timer_int = 32 + 25; // USB timer interrupt. public const int IRQ_INDEX_SW_INT = 32 + 24; // Software interrupt (caused by bit 0 of the SW_INT register). public const int IRQ_INDEX_SPI1_INT = 32 + 23; // Interrupt from the SPI1 interface. public const int IRQ_INDEX_KEY_IRQ = 32 + 22; // Keyboard scanner interrupt. public const int IRQ_INDEX_RTC_INT = 32 + 20; // Match interrupt 0 or 1 from the RTC. public const int IRQ_INDEX_I2C_1_INT = 32 + 19; // Interrupt from the I2C1 interface. public const int IRQ_INDEX_I2C_2_INT = 32 + 18; // Interrupt from the I2C2 interface. public const int IRQ_INDEX_PLL397_INT = 32 + 17; // Lock interrupt from the 397x PLL. public const int IRQ_INDEX_PLLHCLK_INT = 32 + 14; // Lock interrupt from the HCLK PLL. public const int IRQ_INDEX_PLLUSB_INT = 32 + 13; // Lock interrupt from the USB PLL. public const int IRQ_INDEX_SPI2_INT = 32 + 12; // Interrupt from the SPI2 interface. public const int IRQ_INDEX_ADC_INT = 32 + 7; // A/D Converter interrupt. public const int IRQ_INDEX_GPI_11 = 32 + 4; // Interrupt from the GPI_11 pin. public const int IRQ_INDEX_JTAG_COMM_RX = 32 + 2; // Receiver full interrupt from the JTAG Communication Channel. public const int IRQ_INDEX_JTAG_COMM_TX = 32 + 1; // Transmitter empty interrupt from the JTAG Communication Channel. public const int IRQ_INDEX_SYSCLK_mux = 64 + 31; // Status of the SYSCLK Mux (SYSCLK_CTRL[0]). May be used to begin operations that require a change to the alternate clock source. public const int IRQ_INDEX_GPI_06 = 64 + 28; // Interrupt from the GPI_06 (HSTIM_CAP) pin. public const int IRQ_INDEX_GPI_05 = 64 + 27; // Interrupt from the GPI_05 pin. public const int IRQ_INDEX_GPI_04 = 64 + 26; // Interrupt from the GPI_04 (SPI1_BUSY) pin. public const int IRQ_INDEX_GPI_03 = 64 + 25; // Interrupt from the GPI_03 pin. public const int IRQ_INDEX_GPI_02 = 64 + 24; // Interrupt from the GPI_02 pin. public const int IRQ_INDEX_GPI_01 = 64 + 23; // Interrupt from the GPI_01 (SERVICE_N) pin. public const int IRQ_INDEX_GPI_00 = 64 + 22; // Interrupt from the GPI_00 pin. public const int IRQ_INDEX_SPI1_DATIN = 64 + 20; // Interrupt from the SPI1_DATIN pin. public const int IRQ_INDEX_U5_RX = 64 + 19; // Interrupt from the UART5 RX pin. public const int IRQ_INDEX_SDIO_INT_N = 64 + 18; // Interrupt from the MS_DIO1 pin. Active LOW. public const int IRQ_INDEX_GPI_07 = 64 + 15; // Interrupt from the GPI_07 pin. public const int IRQ_INDEX_U7_HCTS = 64 + 12; // Interrupt from the UART7 HCTS pin. public const int IRQ_INDEX_GPI_10 = 64 + 11; // Interrupt from the GPI_10 (U4_RX) pin. public const int IRQ_INDEX_GPI_09 = 64 + 10; // Interrupt from the GPI_09 (KEY_COL7) pin. public const int IRQ_INDEX_GPI_08 = 64 + 9; // Interrupt from the GPI_08 (KEY_COL6, SPI2_BUSY) pin. public const int IRQ_INDEX_U2_HCTS = 64 + 7; // Interrupt from the UART2 HCTS pin. public const int IRQ_INDEX_SPI2_DATIN = 64 + 6; // Interrupt from the SPI1_DATIN) pin. public const int IRQ_INDEX_GPIO_05 = 64 + 5; // Interrupt from the GPI_05 pin. public const int IRQ_INDEX_GPIO_04 = 64 + 4; // Interrupt from the GPI_04 pin. public const int IRQ_INDEX_GPIO_03 = 64 + 3; // Interrupt from the GPI_03 (KEY_ROW7) pin. public const int IRQ_INDEX_GPIO_02 = 64 + 2; // Interrupt from the GPI_02 (KEY_ROW6) pin. public const int IRQ_INDEX_GPIO_01 = 64 + 1; // Interrupt from the GPI_01 pin. public const int IRQ_INDEX_GPIO_00 = 64 + 0; // Interrupt from the GPI_00 pin. [MemoryMappedPeripheral(Base=0x0000U,Length=0x4000U)] public class Section { [Register(Offset=0x00000000U)] public uint ER; // Enable Register for the Main Interrupt Controller 0 R/W [Register(Offset=0x00000004U)] public uint RSR; // Raw Status Register for the Main Interrupt Controller x R/W [Register(Offset=0x00000008U)] public uint SR; // Status Register for the Main Interrupt Controller 0 RO [Register(Offset=0x0000000CU)] public uint APR; // Activation Polarity select Register for the Main Interrupt Controller 0 R/W [Register(Offset=0x00000010U)] public uint ATR; // Activation Type select Register for the Main Interrupt Controller 0 R/W [Register(Offset=0x00000014U)] public uint ITR; // Interrupt Type select Register for the Main Interrupt Controller 0 R/W } //--// [Register(Offset=0x00000000U,Instances=3)] public Section[] Sections; // // Access Methods // public static extern INTC Instance { [SingletonFactory()] [MethodImpl( MethodImplOptions.InternalCall )] get; } } } ================================================ FILE: Zelig/Zelig/RunTime/DeviceModels/ModelForLPC3180/HardwareModel/ChipSet/LPC3180/MilliSecondTimer.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // namespace Microsoft.DeviceModels.Chipset.LPC3180 { using System; using System.Runtime.CompilerServices; using Microsoft.Zelig.Runtime; [MemoryMappedPeripheral(Base=0x40034000U,Length=0x20U)] public class MilliSecondTimer { [BitFieldPeripheral(PhysicalType=typeof(uint))] public struct MSTIM_INT_bitfield { [BitFieldRegister(Position=1)] public bool MATCH1_INT; // Reading a 1 indicates an active MATCH 1 interrupt. // Writing a 1 clears the active interrupt status. Writing 0 has no effect. // Note: Remove active match status by writing a new match value before clearing the interrupt. // Otherwise a new match interrupt may be activated immediately after clearing the match interrupt since the match may still be valid. // [BitFieldRegister(Position=0)] public bool MATCH0_INT; // Reading a 1 indicates an active MATCH 0 interrupt. // Writing a 1 clears the active interrupt status. Writing 0 has no effect. // Note: Remove active match status by writing a new match value before clearing the interrupt. // Otherwise a new match interrupt may be activated immediately after clearing the match interrupt since the match may still be valid. } //--// [BitFieldPeripheral(PhysicalType=typeof(uint))] public struct MSTIM_CTRL_bitfield { [BitFieldRegister(Position=2)] public bool PAUSE_EN; // *0 = Timer counter continues to run if ARM enters debug mode. // 1 = Timer counter is stopped when the core is in debug mode (DBGACK high). // [BitFieldRegister(Position=1)] public bool RESET_COUNT; // *0 = Timer counter is not reset. // 1 = Timer counter will be reset on next PERIPH_CLK edge. Software must write this bit back to low to release the reset. // [BitFieldRegister(Position=0)] public bool COUNT_ENAB; // *0 = Timer Counter is stopped. // 1 = Timer Counter is enabled. } //--// [BitFieldPeripheral(PhysicalType=typeof(uint))] public struct MSTIM_MCTRL_bitfield { [BitFieldRegister(Position=5)] public bool STOP_COUNT1; // *0 = Disable the stop functionality on Match 1. // 1 = Enable the Timer Counter to be stopped on Match 1. // [BitFieldRegister(Position=4)] public bool RESET_COUNT1; // *0 = Disable reset of Timer Counter on Match 1. // 1 = Enable reset of Timer Counter on Match 1. // [BitFieldRegister(Position=3)] public bool MR1_INT; // *0 = Disable interrupt on the Match 1 register. // 1 = Enable internal interrupt status generation on the Match 1 register. // [BitFieldRegister(Position=2)] public bool STOP_COUNT0; // *0 = Disable the stop functionality on Match 0. // 1 = Enable the Timer Counter to be stopped on Match 0. // [BitFieldRegister(Position=1)] public bool RESET_COUNT0; // *0 = Disable reset of Timer Counter on Match 0. // 1 = Enable reset of Timer Counter on Match 0. // [BitFieldRegister(Position=0)] public bool MR0_INT; // *0 = Disable interrupt on the Match 0 register. // 1 = Enable internal interrupt status generation on the Match 0 register. } //--// [Register(Offset=0x00000000)] public MSTIM_INT_bitfield MSTIM_INT; // Millisecond timer interrupt status register 0 R/W [Register(Offset=0x00000004)] public MSTIM_CTRL_bitfield MSTIM_CTRL; // Millisecond timer control register 0 R/W [Register(Offset=0x00000008)] public uint MSTIM_COUNTER; // Millisecond timer counter value register 0 R/W [Register(Offset=0x00000014)] public MSTIM_MCTRL_bitfield MSTIM_MCTRL; // Millisecond timer match control register 0 R/W [Register(Offset=0x00000018)] public uint MSTIM_MATCH0; // Millisecond timer match 0 register 0 R/W [Register(Offset=0x0000001C)] public uint MSTIM_MATCH1; // Millisecond timer match 1 register 0 R/W // // Access Methods // public static extern MilliSecondTimer Instance { [SingletonFactory()] [MethodImpl( MethodImplOptions.InternalCall )] get; } } } ================================================ FILE: Zelig/Zelig/RunTime/DeviceModels/ModelForLPC3180/HardwareModel/ChipSet/LPC3180/MultiLevelNANDController.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // namespace Microsoft.DeviceModels.Chipset.LPC3180 { using System; using System.Runtime.CompilerServices; using Microsoft.Zelig.Runtime; [MemoryMappedPeripheral(Base=0x200A8000U,Length=0x00010050U)] public class MultiLevelNANDController { public const uint MLC_LOCK_PR__UnlockValue = 0x0000A25E; //--// [BitFieldPeripheral(PhysicalType=typeof(uint))] public struct MLC_ICR_bitfield { public enum Addressing { ThreeWords = 0, FourWords = 1, } [BitFieldRegister(Position=3 )] public bool SoftwareWriteProtection; // 0: Software Write protection disabled. // 1: Software Write protection enabled. // [BitFieldRegister(Position=2 )] public bool LargeBlockDevice; // 0: small block flash device (512 +16 byte pages). // 1: large block flash device (2k + 64 byte pages). // [BitFieldRegister(Position=1,Size=1)] public Addressing ChipWordAddress; // 0: NAND flash address word count 3. // 1: NAND flash address word count 4. // [BitFieldRegister(Position=0 )] public bool Bus16bit; // 0: NAND flash I/O bus with 8-bit. // 1: NAND flash I/O bus with 16-bit (Not supported). } //--// [BitFieldPeripheral(PhysicalType=typeof(uint))] public struct MLC_TIME_REG_bitfield { [BitFieldRegister(Position=24,Size=2)] public uint TCEA_DELAY; // nCE low to dout valid (tCEA) // Default: 0x00 // [BitFieldRegister(Position=19,Size=5)] public uint BUSY_DELAY; // Read/Write high to busy (tWB/tRB) // Default: 0x00 // [BitFieldRegister(Position=16,Size=3)] public uint NAND_TA; // Read high to high impedance (tRHZ) // Default: 0x00 // [BitFieldRegister(Position=12,Size=4)] public uint RD_HIGH; // Read high hold time (tREH) // Default: 0x00 // [BitFieldRegister(Position= 8,Size=4)] public uint RD_LOW; // Read pulse width (tRP) // Default: 0x00 // [BitFieldRegister(Position= 4,Size=4)] public uint WR_HIGH; // Write high hold time (tWH) // Default: 0x00 // [BitFieldRegister(Position= 0,Size=4)] public uint WR_LOW; // Write pulse width (tWP) // Default: 0x07 } //--// [BitFieldPeripheral(PhysicalType=typeof(uint))] public struct MLC_IRQ_MR_bitfield { [BitFieldRegister(Position=5)] public bool NandReady; // NAND Ready (0: Disabled, 1: Enabled) // This interrupt occurs when the NAND flashs Ready/nBusy signal transitions from the Busy state to the Ready state. // This interrupt is delayed by the NAND flashs tWB/tRB parameters. // [BitFieldRegister(Position=4)] public bool ControllerReady; // Controller Ready (0: Disabled, 1: Enabled) // This interrupt indicates that the controller has completed one of the following actions: // 1) Parity read complete // 2) Parity write complete // 3) Auto decode complete // 4) Auto encode complete // [BitFieldRegister(Position=3)] public bool DecodeFailure; // Decode failure (0: Disabled, 1: Enabled) // This interrupt indicates that the R/S ECC decoder has detected errors present in the last decode cycle that cannot be properly corrected // (this indicates that the severity of the error exceeds the correction capability of the decoder). // [BitFieldRegister(Position=2)] public bool DecodeErrorDetected; // Decode error detected (0: Disabled, 1: Enabled) // This interrupt indicates that the R/S ECC decoder has detected (and possibly corrected) errors present in the last decode cycle. // The CPU should read the controllers Status register to determine the severity of the error. // The CPU should also discard the data and read the corrected data from the controllers serial Data Buffer. // [BitFieldRegister(Position=1)] public bool EccReady; // ECC Encode/Decode ready (0: Disabled, 1: Enabled) // This interrupt indicates that the ECC Encoder or Decoder has completed the encoding or decoding process. // For an encode cycle this interrupt occurs after the following actions: // 1) Host begins encoding cycle by accessing the ECC Encode register, // 2) Host writes 518 bytes of NAND data, and // 3) R/S ECC encoding completes. // For a decode cycle this interrupt occurs after the following actions: // 1) Host begins decoding cycle by accessing the ECC Decode register, // 2) Host reads 518/528 bytes of NAND data, and // 3) R/S ECC decoding completes. // [BitFieldRegister(Position=0)] public bool SoftwareWriteProtectionFault; // Software write protection fault (0: Disabled, 1: Enabled) // This interrupt indicates that the last NAND write operation was aborted due to a write protection fault. // This interrupt can occur after the Erase Start (0x60) command or any Auto Program (0x10, 0x11, 0x15) command // is written to the NAND after the previous address data following the Serial Input (0x80) or Auto Erase (0x60) commands // falls within the software protection address range and software write protection is enabled. } //--// [BitFieldPeripheral(PhysicalType=typeof(uint))] public struct MLC_IRQ_SR_bitfield { [BitFieldRegister(Position=5)] public bool NandReady; // NAND Ready (0: Inactive, 1: Active) // This interrupt occurs when the NAND flashs Ready/nBusy signal transitions from the Busy state to the Ready state. // This interrupt is delayed by the NAND flashs tWB/tRB parameters. // [BitFieldRegister(Position=4)] public bool ControllerReady; // Controller Ready (0: Inactive, 1: Active) // This interrupt indicates that the controller has completed one of the following actions: // 1) Parity read complete // 2) Parity write complete // 3) Auto decode complete // 4) Auto encode complete // [BitFieldRegister(Position=3)] public bool DecodeFailure; // Decode failure (0: Inactive, 1: Active) // This interrupt indicates that the R/S ECC decoder has detected errors present in the last decode cycle that cannot be properly corrected // (this indicates that the severity of the error exceeds the correction capability of the decoder). // [BitFieldRegister(Position=2)] public bool DecodeErrorDetected; // Decode error detected (0: Inactive, 1: Active) // This interrupt indicates that the R/S ECC decoder has detected (and possibly corrected) errors present in the last decode cycle. // The CPU should read the controllers Status register to determine the severity of the error. // The CPU should also discard the data and read the corrected data from the controllers serial Data Buffer. // [BitFieldRegister(Position=1)] public bool EccReady; // ECC Encode/Decode ready (0: Inactive, 1: Active) // This interrupt indicates that the ECC Encoder or Decoder has completed the encoding or decoding process. // For an encode cycle this interrupt occurs after the following actions: // 1) Host begins encoding cycle by accessing the ECC Encode register, // 2) Host writes 518 bytes of NAND data, and // 3) R/S ECC encoding completes. // For a decode cycle this interrupt occurs after the following actions: // 1) Host begins decoding cycle by accessing the ECC Decode register, // 2) Host reads 518/528 bytes of NAND data, and // 3) R/S ECC decoding completes. // [BitFieldRegister(Position=0)] public bool SoftwareWriteProtectionFault; // Software write protection fault (0: Inactive, 1: Active) // This interrupt indicates that the last NAND write operation was aborted due to a write protection fault. // This interrupt can occur after the Erase Start (0x60) command or any Auto Program (0x10, 0x11, 0x15) command // is written to the NAND after the previous address data following the Serial Input (0x80) or Auto Erase (0x60) commands // falls within the software protection address range and software write protection is enabled. // } //--// [BitFieldPeripheral(PhysicalType=typeof(uint))] public struct MLC_ISR_bitfield { [BitFieldRegister(Position=6 )] public bool DecoderFailure; // Decoder Failure // This flag indicates that the last R/S Decoding cycle was unsuccessful at correcting errors present in the data. // This indicates that the number of errors in the data exceeds the decoders correction ability (more than 4 symbols). // The host should inspect this flag prior to validating the data read during the last decoding cycle. // [BitFieldRegister(Position=4,Size=2)] public uint SymbolErrors; // Number of R/S symbols errors // This 2-bit field indicates the number of symbol errors detected by the last R/S decoding cycle. // Note that this field is only valid when both the following conditions are met: // 1) Errors Detected flag is set and // 2) Decoder Failure flag is clear. // // 00: One symbol-error detected. // 01: Two symbol-error detected. // 10: Three symbol-error detected. // 11: Four symbol-error detected. // [BitFieldRegister(Position=3 )] public bool ErrorsDetected; // Errors Detected // This flag indicates that the last R/S Decode cycle has detected errors in the page data. // This flag does not indicate error severity but merely indicates that errors have been detected. // [BitFieldRegister(Position=2 )] public bool EccReady; // ECC Ready // This flag indicates the R/S ECC encoding/decoding process has been completed. // The Host must check this flag prior to using data read during a decode cycle. // The CPU can also check the status of an encode cycle prior to accessing the Write Parity register // (this in not necessary since the controller ensures that the R/S encoding has completed before writing any data) // [BitFieldRegister(Position=1 )] public bool ControllerReady; // Controller Ready // This flag indicates that the controller has completed any of the following: // 1) Read parity cycle, // 2) Write parity cycle, // 3) Auto Encode cycle and // 4) Auto Decode cycle. // The flag is cleared when any of the above operations are started. // The flag must be checked by the CPU prior to attempting an access to the corresponding NAND flash device. // Failure to perform the check may result in unexpected operation and/or data loss. // [BitFieldRegister(Position=0 )] public bool NandReady; // NAND Ready // This flag reflects the status of the NAND flashs Ready/nBusy signal. // Note that the CPU need not consider the NAND flashs tWB, tRB timing parameters. // The controller delays the update of the NAND ready flag when data, address, or commands are sent to the NAND flash. // This ensures that the NAND ready flag remains clear until the tWB, tRB time has passed and // the true status of the NAND flashs Ready/nBusy signal can be reported. } //--// [BitFieldPeripheral(PhysicalType=typeof(uint))] public struct MLC_CEH_bitfield { [BitFieldRegister(Position=0)] public bool ForceNotCEAssert; // 0: Force nCE assert // 1: Normal nCE operation (nCE controlled by controller). } //--// [Register(Offset=0x00000000,Instances=32768/sizeof(byte ))] public byte [] MLC_BUFF_8bits; // MLC NAND Data Buffer. - R/W [Register(Offset=0x00000000,Instances=32768/sizeof(ushort))] public ushort[] MLC_BUFF_16bits; // MLC NAND Data Buffer. - R/W [Register(Offset=0x00000000,Instances=32768/sizeof(uint ))] public uint [] MLC_BUFF_32bits; // MLC NAND Data Buffer. - R/W [Register(Offset=0x00008000,Instances=32768/sizeof(byte ))] public byte [] MLC_DATA_8bits; // Start of MLC data buffer - R/W [Register(Offset=0x00008000,Instances=32768/sizeof(ushort))] public ushort[] MLC_DATA_16bits; // Start of MLC data buffer - R/W [Register(Offset=0x00008000,Instances=32768/sizeof(uint ))] public uint [] MLC_DATA_32bits; // Start of MLC data buffer - R/W [Register(Offset=0x00010000 )] public uint MLC_CMD; // MLC NAND Flash Command Register. 0x0 WO [Register(Offset=0x00010004 )] public uint MLC_ADDR; // MLC NAND Flash Address Register. 0x0 WO [Register(Offset=0x00010008 )] public uint MLC_ECC_ENC_REG; // MLC NAND ECC Encode Register. 0x0 WO [Register(Offset=0x0001000C )] public uint MLC_ECC_DEC_REG; // MLC NAND ECC Decode Register. 0x0 WO [Register(Offset=0x00010010 )] public uint MLC_ECC_AUTO_ENC_REG; // MLC NAND ECC Auto Encode Register. 0x0 WO [Register(Offset=0x00010014 )] public uint MLC_ECC_AUTO_DEC_REG; // MLC NAND ECC Auto Decode Register. 0x0 WO [Register(Offset=0x00010018 )] public uint MLC_RPR; // MLC NAND Read Parity Register. 0x0 WO [Register(Offset=0x0001001C )] public uint MLC_WPR; // MLC NAND Write Parity Register. 0x0 WO [Register(Offset=0x00010020 )] public uint MLC_RUBP; // MLC NAND Reset User Buffer Pointer Register. 0x0 WO [Register(Offset=0x00010024 )] public uint MLC_ROBP; // MLC NAND Reset Overhead Buffer Pointer Register. 0x0 WO [Register(Offset=0x00010028 )] public uint MLC_SW_WP_ADD_LOW; // MLC NAND Software Write Protection Address Low Register. 0x0 WO [Register(Offset=0x0001002C )] public uint MLC_SW_WP_ADD_HIG; // MLC NAND Software Write Protection Address High Register. 0x0 WO [Register(Offset=0x00010030 )] public MLC_ICR_bitfield MLC_ICR; // MLC NAND controller Configuration Register. 0x0 WO [Register(Offset=0x00010034 )] public MLC_TIME_REG_bitfield MLC_TIME_REG; // MLC NAND Timing Register. 0x37 WO [Register(Offset=0x00010038 )] public MLC_IRQ_MR_bitfield MLC_IRQ_MR; // MLC NAND Interrupt Mask Register. 0x0 WO [Register(Offset=0x0001003C )] public MLC_IRQ_SR_bitfield MLC_IRQ_SR; // MLC NAND Interrupt Status Register. 0x0 RO [Register(Offset=0x00010044 )] public uint MLC_LOCK_PR; // MLC NAND Lock Protection Register. 0x0 WO [Register(Offset=0x00010048 )] public MLC_ISR_bitfield MLC_ISR; // MLC NAND Status Register. 0x0 RO [Register(Offset=0x0001004C )] public MLC_CEH_bitfield MLC_CEH; // MLC NAND Chip-Enable Host Control Register. 0x0 WO // // Helper Methods // [Inline] public void SetTimingRegister( uint hclkMHz , uint tCEA , uint tWB_RB , uint tRHZ , uint tREH , uint tRP , uint tWH , uint tWP ) { double scale = (hclkMHz * 1E6) / 1E9; var val = new MLC_TIME_REG_bitfield(); val.TCEA_DELAY = Math.Min( (uint)(tCEA * scale + 0.5), 3 ); val.BUSY_DELAY = Math.Min( (uint)(tWB_RB * scale + 0.5), 31 ); val.NAND_TA = Math.Min( (uint)(tRHZ * scale + 0.5), 7 ); val.RD_HIGH = Math.Min( (uint)(tREH * scale + 0.5), 15 ); val.RD_LOW = Math.Min( (uint)(tRP * scale + 0.5), 15 ); val.WR_HIGH = Math.Min( (uint)(tWH * scale + 0.5), 15 ); val.WR_LOW = Math.Min( (uint)(tWP * scale + 0.5), 15 ); this.MLC_LOCK_PR = MLC_LOCK_PR__UnlockValue; this.MLC_TIME_REG = val; } // // Access Methods // public static extern MultiLevelNANDController Instance { [SingletonFactory()] [MethodImpl( MethodImplOptions.InternalCall )] get; } } } ================================================ FILE: Zelig/Zelig/RunTime/DeviceModels/ModelForLPC3180/HardwareModel/ChipSet/LPC3180/SDRAMController.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // namespace Microsoft.DeviceModels.Chipset.LPC3180 { using System; using System.Runtime.CompilerServices; using Microsoft.Zelig.Runtime; [MemoryMappedPeripheral(Base=0x31080000U,Length=0x0000048CU)] public class SDRAMController { [BitFieldPeripheral(PhysicalType=typeof(uint))] public struct MPMCControl_bitfield { [BitFieldRegister(Position=2)] public bool LowPowerMode; // Indicates normal, or low-power mode: // // *0 = normal. // 1 = low-power mode. // // Entering low-power mode reduces memory controller power consumption. // Dynamic memory is refreshed as necessary. // The memory controller returns to normal functional mode by clearing the low-power mode bit (L), or by Reset. // This bit must only be modified when the SDRAM Controller is in idle state. // [BitFieldRegister(Position=0)] public bool SDRAM_Controller_Enable; // Indicates if the SDRAM Controller is enabled or disabled: // // 0 = disabled. // *1 = enabled. // // Disabling the SDRAM Controller reduces power consumption. // When the memory controller is disabled the memory is not refreshed. // The memory controller is enabled by setting the enable bit, or by reset. // This bit must only be modified when the SDRAM Controller is in idle state. // } //--// [BitFieldPeripheral(PhysicalType=typeof(uint))] public struct MPMCStatus_bitfield { [BitFieldRegister(Position=2)] public bool SelfRefreshAcknowledge; // This bit indicates the operating mode of the SDRAM Controller: // // 0 = normal mode // *1 = self-refresh mode. // [BitFieldRegister(Position=0)] public bool Busy; // This bit is used to ensure that the memory controller enters the low-power or disabled mode cleanly by determining if the memory controller is busy or not: // // 0 = SDRAM Controller is idle. // 1* = SDRAM Controller is busy performing memory transactions, commands, auto-refresh cycles, or is in self-refresh mode. // } //--// [BitFieldPeripheral(PhysicalType=typeof(uint))] public struct MPMCConfig_bitfield { [BitFieldRegister(Position=0)] public bool BigEndianMode; // Endian mode: // // *0 = little-endian mode. // 1 = big-endian mode. // // On power-on reset, the value of the endian bit is 0. // All data must be flushed in the SDRAM Controller before switching between little-endian and big-endian modes. // } //--// [BitFieldPeripheral(PhysicalType=typeof(uint))] public struct MPMCDynamicControl_bitfield { public enum Mode : uint { NORMAL = 0, // *00 = issue SDRAM NORMAL operation command. MODE = 1, // 01 = issue SDRAM MODE command.[1] PALL = 2, // 10 = issue SDRAM PALL (precharge all) command. NOP = 3, // 11 = issue SDRAM NOP (no operation) command). } [BitFieldRegister(Position=13 )] public bool DeepSleep; // Low-power SDRAM deep-sleep mode: // // *0 = normal operation. // 1 = enter deep power down mode. // [BitFieldRegister(Position= 7,Size=2)] public Mode Initialization; // SDRAM initialization: // // *00 = issue SDRAM NORMAL operation command. // 01 = issue SDRAM MODE command.[1] // 10 = issue SDRAM PALL (precharge all) command. // 11 = issue SDRAM NOP (no operation) command). // // [BitFieldRegister(Position= 5 )] public bool RAM_CLK; // Memory clock control (MMC): // // *0 = RAM_CLK enabled (POR reset value). // 1 = RAM_CLK disabled. // [BitFieldRegister(Position= 4 )] public bool DDR_nCLK_Disable; // Inverted Memory Clock Control (IMCC): // // *0 = DDR_nCLK enabled. // 1 = DDR_nCLK disabled. // [BitFieldRegister(Position= 3 )] public bool SR_CLK; // Self-Refresh Clock Control (SRMCC): // // *0 = RAM_CLK and DDR_nCLK run continuously during self-refresh mode. // 1 = RAM_CLK and DDR_nCLK run are stopped during self-refresh mode. // [BitFieldRegister(Position= 2 )] public bool SR_REQ; // Self-refresh request, MPMCSREFREQ (SR): // // 0 = normal mode. // *1 = enter self-refresh mode. // // Note: this bit must be written to 0 by software for correct operation. // [BitFieldRegister(Position= 1 )] public bool CS; // Dynamic memory clock control (CS): // // 0 = RAM_CLK stops when all SDRAMs are idle and during self-refresh mode. // *1 = RAM_CLK runs continuously. // // When clock control is LOW the output clock RAM_CLK is stopped when there are no SDRAM transactions. // The clock is also stopped during self-refresh mode. // [BitFieldRegister(Position= 0 )] public bool CE; // Dynamic memory clock enable (CE): // // *0 = clock enable of idle devices are deasserted to save power. // 1 = all clock enables are driven HIGH continuously. // } //--// [BitFieldPeripheral(PhysicalType=typeof(uint))] public struct MPMCDynamicReadConfig_bitfield { public enum CommandStrategy : uint { RAM_CLK = 0, // *00 = clock out delayed strategy, using RAM_CLK (command not delayed, clock out delayed). MPMCCLKDELAY = 1, // 01 = command delayed strategy, using MPMCCLKDELAY (command delayed, clock out not delayed). MPMCCLKDELAYplus1 = 2, // 10 = command delayed strategy plus one clock cycle, using MPMCCLKDELAY (command delayed, clock out not delayed). MPMCCLKDELAYplus2 = 3, // 11 = command delayed strategy plus two clock cycles, using MPMCCLKDELAY (command delayed, clock out not delayed). } [BitFieldRegister(Position=12 )] public bool DRP; // DDR SDRAM read data capture polarity (DRP) // // *0 = data captured on the negative edge of HCLK. // 1 = data captured on the positive edge of HCLK. // [BitFieldRegister(Position= 8,Size=2)] public CommandStrategy DRD; // DDR SDRAM read data strategy (DRD): // // *00 = clock out delayed strategy, using RAM_CLK (command not delayed, clock out delayed). // 01 = command delayed strategy, using MPMCCLKDELAY (command delayed, clock out not delayed). // 10 = command delayed strategy plus one clock cycle, using MPMCCLKDELAY (command delayed, clock out not delayed). // 11 = command delayed strategy plus two clock cycles, using MPMCCLKDELAY (command delayed, clock out not delayed). // [BitFieldRegister(Position= 4 )] public bool SRP; // SDR-SDRAM read data capture polarity (SRP): // // *0 = data captured on the negative edge of HCLK. // 1 = data captured on the positive edge of HCLK. // [BitFieldRegister(Position= 0,Size=2)] public CommandStrategy SRD; // SDR-SDRAM read data strategy (SRD): // // *00 = clock out delayed strategy, using RAM_CLK (command not delayed, clock out delayed). // 01 = command delayed strategy, using MPMCCLKDELAY (command delayed, clock out not delayed). // 10 = command delayed strategy plus one clock cycle, using MPMCCLKDELAY (command delayed, clock out not delayed). // 11 = command delayed strategy plus two clock cycles, using MPMCCLKDELAY (command delayed, clock out not delayed). // } //--// [BitFieldPeripheral(PhysicalType=typeof(uint))] public struct MPMCDynamicConfig0_bitfield { public enum Performance : uint { HighPerf = 0x00, // *00 = high-performance. LowPower = 0x01, // 01 = low-power. } public enum SizeMode : uint { Size_16Mb_2Mx8 = 0x00, // *000 00 16Mb (2Mx8), 2 banks, row length = 11, column length = 9 Size_16Mb_1Mx16 = 0x01, // 000 01 16Mb (1Mx16), 2 banks, row length = 11, column length = 8 Size_64Mb_8Mx8 = 0x04, // 001 00 64Mb (8Mx8), 4 banks, row length = 12, column length = 9 Size_64Mb_4Mx16 = 0x05, // 001 01 64Mb (4Mx16), 4 banks, row length = 12, column length = 8 Size_128Mb_16Mx8 = 0x08, // 010 00 128Mb (16Mx8), 4 banks, row length = 12, column length = 10 Size_128Mb_8Mx16 = 0x09, // 010 01 128Mb (8Mx16), 4 banks, row length = 12, column length = 9 Size_256Mb_32Mx8 = 0x0C, // 011 00 256Mb (32Mx8), 4 banks, row length = 13, column length = 10 Size_256Mb_16Mx16 = 0x0D, // 011 01 256Mb (16Mx16), 4 banks, row length = 13, column length = 9 Size_512Mb_64Mx8 = 0x10, // 100 00 512Mb (64Mx8), 4 banks, row length = 13, column length = 11 Size_512Mb_32Mx16 = 0x11, // 100 01 512Mb (32Mx16), 4 banks, row length = 13, column length = 10 } public enum DeviceKind : uint { SDR = 0x00, // *000 = SDR SDRAM. // 001 = reserved. LP_SDR = 0x02, // 010 = low power SDR SDRAM. // 011 = reserved. DDR = 0x04, // 100 = DDR SDRAM. // 101 = reserved. LP_DDR = 0x06, // 110 = low power DDR SDRAM. // 111 = reserved. } [BitFieldRegister(Position=20 )] public bool WriteProtect; // Write protect (P): // // *0 = writes not protected. // 1 = write protected. // [BitFieldRegister(Position=14 )] public bool Bus32bit; // Address Mapping (AM): external data bus. // // *0 = 16-bit // 1 = 32-bit // [BitFieldRegister(Position=12,Size=2)] public Performance LowPower; // Address Mapping (AM): performance. // [BitFieldRegister(Position= 7,Size=5)] public SizeMode Size; // Address Mapping (AM): size. // [BitFieldRegister(Position= 0,Size=3)] public DeviceKind MemoryDevice; // Memory device (MD): // } //--// [BitFieldPeripheral(PhysicalType=typeof(uint))] public struct MPMCDynamicRasCas0_bitfield { public enum CasLatency : uint { // 0000 = reserved. Latency_HalfClock = 1, // 0001 = one half clock cycle. Latency_1Clock = 2, // 0010 = one clock cycle. Latency_1AndAHalfClocks = 3, // 0011 = one and a half clock cycles. Latency_2Clocks = 4, // 0100 = two clock cycles. Latency_2AndAHalfClocks = 5, // 0101 = two and a half clock cycles. Latency_3Clocks = 6, // *0110 = three clock cycles. Latency_3AndAHalfClocks = 7, // 0111 = three and a half clock cycles. Latency_4Clocks = 8, // 1000 = four clock cycles. Latency_4AndAHalfClocks = 9, // 1001 = four and a half clock cycles. Latency_5Clocks = 10, // 1010 = five clock cycles. Latency_5AndAHalfClocks = 11, // 1011 = five and a half clock cycles. Latency_6Clocks = 12, // 1100 = six clock cycles. Latency_6AndAHalfClocks = 13, // 1101 = six and a half clock cycles. Latency_7Clocks = 14, // 1110 = seven clock cycles. Latency_7AndAHalfClocks = 15, // 1111 = seven and a half clock cycles. } public enum RasLatency : uint { // 0000 = reserved. Latency_1Clock = 1, // 0001 to 1110 = n clock cycles. (Default: 3) Latency_2Clock = 2, // Latency_3Clock = 3, // Latency_4Clock = 4, // Latency_5Clock = 5, // Latency_6Clock = 6, // Latency_7Clock = 7, // Latency_8Clock = 8, // Latency_9Clock = 9, // Latency_0Clock = 10, // Latency_11Clock = 11, // Latency_12Clock = 12, // Latency_13Clock = 13, // Latency_14Clock = 14, // Latency_15Clock = 15, // 1111 = 15 clock cycles. } [BitFieldRegister(Position=7,Size=4)] public CasLatency CAS_Latency; // CAS latency (CAS): // [BitFieldRegister(Position=0,Size=4)] public RasLatency RAS_Latency; // RAS latency (active to read/write delay) (RAS): // } //--// [MemoryMappedPeripheral(Base=0x0000U,Length=0x000CU)] public class Port { [BitFieldPeripheral(PhysicalType=typeof(uint))] public struct Control_bitfield { [BitFieldRegister(Position=0)] public bool BufferEnable; // AHB Port Buffer Enable (E): // // *0 = disable buffer. // 1 = enable buffer. // } [BitFieldPeripheral(PhysicalType=typeof(uint))] public struct Status_bitfield { [BitFieldRegister(Position=1)] public bool BufferStatus; // AHB Port Buffer Status (S): // // 0 = buffer empty. // 1 = buffer contains data. // } //--// [Register(Offset=0x00000000U)] public Control_bitfield Control; // Control register for AHB port x. 0 R/W [Register(Offset=0x00000004U)] public Status_bitfield Status; // Status register for AHB port x. 0 R/W [Register(Offset=0x00000008U)] public uint Timeout; // Timeout register for AHB port x. 0 R/W 0x0 = timeout disabled. 0x001 - 0x1FF = number of AHB cycles before timeout is reached. } [Register(Offset=0x00000000)] public MPMCControl_bitfield MPMCControl; // Controls operation of the memory controller. 0x3 R/W [Register(Offset=0x00000004)] public MPMCStatus_bitfield MPMCStatus; // Provides SDRAM Controller status information. 0x5 RO [Register(Offset=0x00000008)] public MPMCConfig_bitfield MPMCConfig; // Configures operation of the memory controller. 0 R/W [Register(Offset=0x00000020)] public MPMCDynamicControl_bitfield MPMCDynamicControl; // Controls dynamic memory operation. 0x006 R/W [Register(Offset=0x00000024)] public uint MPMCDynamicRefresh; // Configures dynamic memory refresh operation. 0 R/W 0x0 = refresh disabled. (Default) // 0x1 - 0x7FF = n 16 = 16n clocks between SDRAM refresh cycles. [Register(Offset=0x00000028)] public MPMCDynamicReadConfig_bitfield MPMCDynamicReadConfig; // Configures the dynamic memory read strategy. 0 R/W [Register(Offset=0x00000030)] public uint MPMCDynamictRP; // Selects the precharge command period. 0x0F R/W 0x0 - 0x0E = n + 1 clock cycles. 0x0F = 16 clock cycles [Register(Offset=0x00000034)] public uint MPMCDynamictRAS; // Selects the active to precharge command period. 0xF R/W 0x0 - 0x0E = n + 1 clock cycles. 0x0F = 16 clock cycles [Register(Offset=0x00000038)] public uint MPMCDynamictSREX; // Selects the self-refresh exit time. 0xF R/W 0x0 - 0x7E = n + 1 clock cycles. 0x7F = 128 clock cycles. [Register(Offset=0x00000044)] public uint MPMCDynamictWR; // Selects the write recovery time. 0xF R/W 0x0 - 0x0E = n + 1 clock cycles. 0x0F = 16 clock cycles [Register(Offset=0x00000048)] public uint MPMCDynamictRC; // Selects the active to active command period. 0x1F R/W 0x0 - 0x1E = n + 1 clock cycles. 0x1F = 32 clock cycles. [Register(Offset=0x0000004C)] public uint MPMCDynamictRFC; // Selects the auto-refresh period. 0x1F R/W 0x0 - 0x1E = n + 1 clock cycles. 0x1F = 32 clock cycles. [Register(Offset=0x00000050)] public uint MPMCDynamictXSR; // Selects the exit self-refresh to active command time 0x1F R/W 0x0 - 0xFE = n + 1 clock cycles. 0xFF = 256 clock cycles. [Register(Offset=0x00000054)] public uint MPMCDynamictRRD; // Selects the active bank A to active bank B latency 0xF R/W 0x0 - 0x0E = n + 1 clock cycles. 0x0F = 16 clock cycles [Register(Offset=0x00000058)] public uint MPMCDynamictMRD; // Selects the load mode register to active command time 0xF R/W 0x0 - 0x0E = n + 1 clock cycles. 0x0F = 16 clock cycles [Register(Offset=0x0000005C)] public uint MPMCDynamictCDLR; // Selects the last data in to read command time. 0xF R/W 0x0 - 0x0E = n + 1 clock cycles. 0x0F = 16 clock cycles [Register(Offset=0x00000100)] public MPMCDynamicConfig0_bitfield MPMCDynamicConfig0; // Selects the configuration information for the SDRAM. 0 R/W [Register(Offset=0x00000104)] public MPMCDynamicRasCas0_bitfield MPMCDynamicRasCas0; // Selects the RAS and CAS latencies for the SDRAM. 0x303 R/W [Register(Offset=0x00000400)] public Port MPMCAHB_Port0; // AHB port 0. [Register(Offset=0x00000440)] public Port MPMCAHB_Port2; // AHB port 2. [Register(Offset=0x00000460)] public Port MPMCAHB_Port3; // AHB port 3. [Register(Offset=0x00000480)] public Port MPMCAHB_Port4; // AHB port 4. // // Helper Methods // [Inline] public static unsafe void InitializeLowPowerSDR( uint hclkMHz , MPMCDynamicConfig0_bitfield.SizeMode sizeDefinition , bool wideDataBus , uint modeRegister , uint extendedModeRegister ) { var valSDRAMCLK_CTRL = new SystemControl.SDRAMCLK_CTRL_bitfield(); valSDRAMCLK_CTRL.HCLKDELAY_DELAY = 7; SystemControl.Instance.SDRAMCLK_CTRL = valSDRAMCLK_CTRL; var ctrl = SDRAMController.Instance; { var val = new SDRAMController.MPMCControl_bitfield(); val.LowPowerMode = false; val.SDRAM_Controller_Enable = true; ctrl.MPMCControl = val; } { var val = new SDRAMController.MPMCConfig_bitfield(); val.BigEndianMode = false; ctrl.MPMCConfig = val; } { var val = new Port.Control_bitfield(); val.BufferEnable = true; ctrl.MPMCAHB_Port0.Control = val; ctrl.MPMCAHB_Port2.Control = val; ctrl.MPMCAHB_Port3.Control = val; ctrl.MPMCAHB_Port4.Control = val; } { var val = new MPMCDynamicConfig0_bitfield(); val.WriteProtect = false; val.Bus32bit = wideDataBus; val.LowPower = MPMCDynamicConfig0_bitfield.Performance.LowPower; val.Size = sizeDefinition; val.MemoryDevice = MPMCDynamicConfig0_bitfield.DeviceKind.LP_SDR; ctrl.MPMCDynamicConfig0 = val; } //--// // // This value is normally found in SDRAM data sheets as tRCD // // CAS latency(CAS) -> Three clock cycles // { var val = new MPMCDynamicRasCas0_bitfield(); val.CAS_Latency = MPMCDynamicRasCas0_bitfield.CasLatency.Latency_3Clocks; if(hclkMHz <= 39) { val.RAS_Latency = MPMCDynamicRasCas0_bitfield.RasLatency.Latency_1Clock; } else if(hclkMHz <= 91) { val.RAS_Latency = MPMCDynamicRasCas0_bitfield.RasLatency.Latency_2Clock; } else { val.RAS_Latency = MPMCDynamicRasCas0_bitfield.RasLatency.Latency_3Clock; } ctrl.MPMCDynamicRasCas0 = val; } { var val = new MPMCDynamicReadConfig_bitfield(); val.SRD = MPMCDynamicReadConfig_bitfield.CommandStrategy.MPMCCLKDELAY; val.SRP = true; ctrl.MPMCDynamicReadConfig = val; } // // This value is normally found in SDRAM data sheets as tRP // if(hclkMHz <= 39) { ctrl.MPMCDynamictRP = 0; } else if(hclkMHz <= 91) { ctrl.MPMCDynamictRP = 1; } else { ctrl.MPMCDynamictRP = 2; } // // This value is normally found in SDRAM data sheets as tRAS // if(hclkMHz <= 13) { ctrl.MPMCDynamictRAS = 0; } else if(hclkMHz <= 26) { ctrl.MPMCDynamictRAS = 1; } else if(hclkMHz <= 52) { ctrl.MPMCDynamictRAS = 2; } else if(hclkMHz <= 65) { ctrl.MPMCDynamictRAS = 3; } else if(hclkMHz <= 91) { ctrl.MPMCDynamictRAS = 4; } else { ctrl.MPMCDynamictRAS = 5; } // // This value is normally found in SDRAM data sheets as tSREX // For devices without this parameter you use the same value as tXSR // For some DDR-SDRAM data sheets, this parameter is known as tXSNR // if(hclkMHz <= 13) { ctrl.MPMCDynamictSREX = 1; } else if(hclkMHz <= 26) { ctrl.MPMCDynamictSREX = 2; } else if(hclkMHz <= 39) { ctrl.MPMCDynamictSREX = 3; } else if(hclkMHz <= 52) { ctrl.MPMCDynamictSREX = 4; } else if(hclkMHz <= 65) { ctrl.MPMCDynamictSREX = 5; } else if(hclkMHz <= 78) { ctrl.MPMCDynamictSREX = 6; } else if(hclkMHz <= 91) { ctrl.MPMCDynamictSREX = 7; } else { ctrl.MPMCDynamictSREX = 8; } // // This value is normally found in SDRAM data sheets as tWR, tDPL, tRWL, or tRDL // ctrl.MPMCDynamictWR = 1; // // This value is normally found in SDRAM data sheets as tRC // if(hclkMHz <= 13) { ctrl.MPMCDynamictRC = 1; } else if(hclkMHz <= 26) { ctrl.MPMCDynamictRC = 2; } else if(hclkMHz <= 39) { ctrl.MPMCDynamictRC = 3; } else if(hclkMHz <= 52) { ctrl.MPMCDynamictRC = 4; } else if(hclkMHz <= 65) { ctrl.MPMCDynamictRC = 5; } else if(hclkMHz <= 78) { ctrl.MPMCDynamictRC = 6; } else if(hclkMHz <= 91) { ctrl.MPMCDynamictRC = 7; } else { ctrl.MPMCDynamictRC = 8; } // // This value is normally found in SDRAM data sheets as tRFC, or sometimes as tRC // if(hclkMHz <= 13) { ctrl.MPMCDynamictRFC = 1; } else if(hclkMHz <= 26) { ctrl.MPMCDynamictRFC = 2; } else if(hclkMHz <= 39) { ctrl.MPMCDynamictRFC = 3; } else if(hclkMHz <= 52) { ctrl.MPMCDynamictRFC = 4; } else if(hclkMHz <= 65) { ctrl.MPMCDynamictRFC = 5; } else if(hclkMHz <= 78) { ctrl.MPMCDynamictRFC = 6; } else if(hclkMHz <= 91) { ctrl.MPMCDynamictRFC = 7; } else { ctrl.MPMCDynamictRFC = 8; } // // This value is normally found in SDRAM data sheets as tXSR // But it is sometimes called tXSNR in some DDR SDRAM data sheets. // if(hclkMHz <= 91) { ctrl.MPMCDynamictXSR = 1; } else if(hclkMHz <= 26) { ctrl.MPMCDynamictXSR = 2; } else if(hclkMHz <= 39) { ctrl.MPMCDynamictXSR = 3; } else if(hclkMHz <= 52) { ctrl.MPMCDynamictXSR = 4; } else if(hclkMHz <= 65) { ctrl.MPMCDynamictXSR = 5; } else if(hclkMHz <= 78) { ctrl.MPMCDynamictXSR = 6; } else if(hclkMHz <= 91) { ctrl.MPMCDynamictXSR = 7; } else { ctrl.MPMCDynamictXSR = 8; } // This value is normally found in SDRAM data sheets as tRRD if(hclkMHz <= 52) { ctrl.MPMCDynamictRRD = 0; } else { ctrl.MPMCDynamictRRD = 1; } // // This value is normally found in SDRAM data sheets as tMRD, or tRSA // ctrl.MPMCDynamictMRD = 1; // // This value is normally found in SDRAM data sheets as tCDLR // ctrl.MPMCDynamictCDLR = 0; // // All clock enables are driven HIGH continuously // RAM_CLK runs continuously // { var val = new MPMCDynamicControl_bitfield(); val.CE = true; val.CS = true; val.DDR_nCLK_Disable = true; val.Initialization = MPMCDynamicControl_bitfield.Mode.NOP; ctrl.MPMCDynamicControl = val; } Processor.Delay( 100 * 1000, hclkMHz * 1000000 ); // // All clock enables are driven HIGH continuously // RAM_CLK runs continuously // { var val = new MPMCDynamicControl_bitfield(); val.CE = true; val.CS = true; val.DDR_nCLK_Disable = true; val.Initialization = MPMCDynamicControl_bitfield.Mode.PALL; ctrl.MPMCDynamicControl = val; } // 2 x 16 clocks between SDRAM refresh cycles ctrl.MPMCDynamicRefresh = 2; Processor.Delay( 2 * 16 * 1000, hclkMHz * 1000000 ); if(hclkMHz <= 13) { // 12 x 16 clocks between SDRAM refresh cycles ctrl.MPMCDynamicRefresh = 12; } else if(hclkMHz <= 26) { // 25 x 16 clocks between SDRAM refresh cycles ctrl.MPMCDynamicRefresh = 25; } else if(hclkMHz <= 39) { // 35 x 16 clocks between SDRAM refresh cycles ctrl.MPMCDynamicRefresh = 35; } else if(hclkMHz <= 52) { // 51 x 16 clocks between SDRAM refresh cycles ctrl.MPMCDynamicRefresh = 51; } else if(hclkMHz <= 65) { // 64 x 16 clocks between SDRAM refresh cycles ctrl.MPMCDynamicRefresh = 64; } else if(hclkMHz <= 78) { // 77 x 16 clocks between SDRAM refresh cycles ctrl.MPMCDynamicRefresh = 77; } else if(hclkMHz <= 91) { // 89 x 16 clocks between SDRAM refresh cycles ctrl.MPMCDynamicRefresh = 89; } else { // 101 x 16 clocks between SDRAM refresh cycles ctrl.MPMCDynamicRefresh = 101; } //--// // // All clock enables are driven HIGH continuously // RAM_CLK runs continuously // { var val = new MPMCDynamicControl_bitfield(); val.CE = true; val.CS = true; val.DDR_nCLK_Disable = true; val.Initialization = MPMCDynamicControl_bitfield.Mode.MODE; ctrl.MPMCDynamicControl = val; } // Load Mode Register by reading the target location. // Refer to Application Note for detail SetRegister( modeRegister ); // // All clock enables are driven HIGH continuously // RAM_CLK runs continuously // { var val = new MPMCDynamicControl_bitfield(); val.CE = true; val.CS = true; val.DDR_nCLK_Disable = true; val.Initialization = MPMCDynamicControl_bitfield.Mode.MODE; ctrl.MPMCDynamicControl = val; } // Load Extended Mode Register by reading the target location. // Refer to Application Note for detail SetRegister( extendedModeRegister ); // // Clock enable of idle devices are deasserted to save power // RAM_CLK stops when all SDRAMs are idle and during self-refresh mode // { var val = new MPMCDynamicControl_bitfield(); val.CE = false; val.CS = false; val.DDR_nCLK_Disable = true; val.Initialization = MPMCDynamicControl_bitfield.Mode.NORMAL; ctrl.MPMCDynamicControl = val; } //--// ctrl.MPMCAHB_Port0.Timeout = 100; ctrl.MPMCAHB_Port2.Timeout = 400; ctrl.MPMCAHB_Port3.Timeout = 400; ctrl.MPMCAHB_Port4.Timeout = 400; } //// uint* mem = (uint*)0x80000000; //// uint val = 0xAAAA5555; //// //// for(uint i = 0; i < 1024; i++) //// { //// mem[i] = val + i * 0x01020304; //// } //// //// while(true) //// { //// for(uint i = 0; i < 1024; i++) //// { //// if(mem[i] != val + i * 0x01020304) //// { //// while(true); //// } //// } //// } [NoInline] [MemoryUsage(MemoryUsage.Bootstrap)] private static unsafe uint SetRegister( uint register ) { return *(uint*)(0x80000000u + register); } // // Access Methods // public static extern SDRAMController Instance { [SingletonFactory()] [MethodImpl( MethodImplOptions.InternalCall )] get; } } } ================================================ FILE: Zelig/Zelig/RunTime/DeviceModels/ModelForLPC3180/HardwareModel/ChipSet/LPC3180/StandardUART.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // namespace Microsoft.DeviceModels.Chipset.LPC3180 { using System; using System.Runtime.CompilerServices; using Microsoft.Zelig.Runtime; [MemoryMappedPeripheral(Base=0x40080000U,Length=0x00018020U)] public class StandardUART { public enum Id { UART3 = 0, UART4 = 1, UART5 = 2, UART6 = 3, } [BitFieldPeripheral(PhysicalType=typeof(byte))] public struct UnIER_bitfield { [BitFieldRegister(Position=2)] public bool Rx; // Rx Line Status Interrupt Enable // // *0: Disable the Rx line status interrupts. // 1: Enable the Rx line status interrupts. // // This bit enables the UARTn Receiver Line Status interrupt. // This interrupt reflects Overrun Error, Parity Error, Framing Error, and Break conditions. // The status of this interrupt can be read from UnLSR[4:1]. // [BitFieldRegister(Position=1)] public bool THRE; // THRE Interrupt Enable // // *0: Disable the THRE interrupt. // 1: Enable the THRE interrupt. // // This bit enables the Transmit Holding Register Empty (THRE) interrupt for UARTn. // The status of this interrupt can be read from UnLSR[5]. // // [BitFieldRegister(Position=0)] public bool RDAE; // RDA Interrupt Enable // // *0: Disable the RDA interrupt. // 1: Enable the RDA interrupt. // // This bit enables the Receive Data Available (RDA) interrupt for UARTn. // } //--// [BitFieldPeripheral(PhysicalType=typeof(byte))] public struct UnIIR_bitfield { public enum InterruptType : uint { // // // Priority | Interrupt type | Interrupt source | Method of clearing interrupt // ---------+----------------------------------------+------------------------------------------------------------------------------+------------------------------------------- RLS = 0x3, // 1 (High) | Receiver Line Status (RLS) | OE (Overrun Error), PE (Parity Error), FE (Framing Error), or | Read of UnLSR. // | | BI (Break Indication). | // | | Note that an RLS interrupt is asserted immediately rather | // | | than waiting for the corresponding character to reach the top of the FIFO. | // | | | RDA = 0x2, // 2 | Receiver Data Available (RDA) | When the FIFO is turned off (UnFCR[0] = 0), | Read of UnRBR when UnFCR[0] = 0, // | | this interrupt is asserted when receive data is available. | or UARTn FIFO contents go below the trigger level when UnFCR[0] = 1. // | | | // | | When the FIFO is turned on (UnFCR[0] = 1), | // | | this interrupt is asserted when the receive trigger level (as specified by | // | | UnFCR[7:6]) has been reached in the FIFO. | // | | | CTI = 0x6, // 2 | Character Time-out Indication (CTI) | This case occurs when there is at least one character in the Rx FIFO and | Read of UnRBR, or a Stop bit is received. // | | no character has been received or removed from the FIFO | // | | during the last 4 character times. | // | | | THRE = 0x1, // 3 | Transmit Holding Register Empty (THRE) | When the FIFO is turned off (UnFCR[0] = 0), | Read of UnIIR or write to THR. // | | this interrupt is asserted when the transmit holding register is empty. | // | | When the FIFO is turned on (UnFCR[0] = 1), | // | | this interrupt is asserted when the transmit trigger level (as specified by | // | | UnFCR[5:4]) has been reached in the FIFO. | } [BitFieldRegister(Position=1,Size=3)] public InterruptType IntId; // Interrupt Identification // [BitFieldRegister(Position=0 )] public bool NoIntPending; // Interrupt Pending // // This flag indicates when there are no UARTn related interrupts pending. // Note that this bit is active LOW. The pending interrupt can be determined by evaluating UnIIR[3:0]. // // 0: At least one interrupt is pending. // *1: No pending interrupts. // } //--// [BitFieldPeripheral(PhysicalType=typeof(byte))] public struct UnFCR_bitfield { public enum RxTriggerLevel : uint { TriggerAt16 = 0, // *00: trigger level = 16 TriggerAt32 = 1, // 01: trigger level = 32 TriggerAt48 = 2, // 10: trigger level = 48 TriggerAt60 = 3, // 11: trigger level = 60 } public enum TxTriggerLevel : uint { TriggerAt0 = 0, // *00: trigger level = 0 TriggerAt4 = 1, // 01: trigger level = 4 TriggerAt8 = 2, // 10: trigger level = 8 TriggerAt16 = 3, // 11: trigger level = 16 } [BitFieldRegister(Position=6,Size=2)] public RxTriggerLevel RxLvl; // Receiver Trigger Level Select // These two bits determine how many receiver UARTn FIFO characters must be present before an interrupt is activated. // [BitFieldRegister(Position=4,Size=2)] public TxTriggerLevel TxLvl; // Transmitter Trigger Level Select // These two bits determine the level of the UARTn transmitter FIFO causes an interrupt. // [BitFieldRegister(Position=3 )] public bool FIFOControl; // FIFO Control. // // Internal UARTn FIFO control. This bit must be set to 1 for proper FIFO operation (default off) // [BitFieldRegister(Position=2 )] public bool ResetTxFIFO; // Transmitter FIFO Reset // // Writing a logic 1 to UnFCR[2] will clear all bytes in UARTn Tx FIFO and reset the pointer logic. // This bit is self-clearing. // [BitFieldRegister(Position=1 )] public bool ResetRxFIFO; // Receiver FIFO Reset // // Writing a logic 1 to UnFCR[1] will clear all bytes in UARTn Rx FIFO and reset the pointer logic. // This bit is self-clearing. // [BitFieldRegister(Position=0 )] public bool FIFOEnable; // FIFO Enable // // UARTn transmit and receive FIFO enable. // Any transition on this bit will automatically clear the UARTn FIFOs. // // *0: UARTn Rx and Tx FIFOs disabled. // 1: UARTn Rx and Tx FIFOs enabled and other UnFCR bits activated. // } //--// [BitFieldPeripheral(PhysicalType=typeof(byte))] public struct UnLCR_bitfield { public enum ParitySettings : uint { Odd = 0x0, // *00: Odd parity Even = 0x1, // 01: Even parity Forced1 = 0x2, // 10: Forced "1" stick parity Forced0 = 0x3, // 11: Forced "0" stick parity } public enum LengthSettings : uint { Use5bits = 0x0, // *00: 5 bit character length Use6bits = 0x1, // 01: 6 bit character length Use7bits = 0x2, // 10: 7 bit character length Use8bits = 0x3, // 11: 8 bit character length } [BitFieldRegister(Position=7 )] public bool DLAB; // Divisor Latch Access Bit // // Allows access to the alternate registers at address offsets 0 and 4. // // *0: Disable access to the baud rate Divisor Latches, enabling access to UnRBR, UnTHR, and UnIER. // 1: Enable access to the baud rate Divisor Latches, disabling access to UnRBR, UnTHR, and UnIER. // [BitFieldRegister(Position=6 )] public bool Break; // Break Control // // Allows forcing the Un_TX output low in order to generate a break condition. // // *0: Disable break transmission // 1: Enable break transmission. // [BitFieldRegister(Position=4,Size=2)] public ParitySettings Parity; // If bit UnLCR[3] = 1, selects the type of parity used by the UART. // // [BitFieldRegister(Position=3 )] public bool ParityEnable; // Parity Enable // // Selects the whether or not the UART uses parity. // // *0: Disable parity generation and checking // 1: Enable parity generation and checking // [BitFieldRegister(Position=2 )] public bool TwoStopBits; // Stop Bit Select // // Selects the number of stop bits used by the UART. // // *0: 1 stop bit // 1: 2 stop bits (1.5 if UnLCR[1:0] = 00) // [BitFieldRegister(Position=0,Size=2)] public LengthSettings WordLen; // Word Length Select // // Selects the character length (in bits) used by the UART // } //--// [BitFieldPeripheral(PhysicalType=typeof(byte))] public struct UnLSR_bitfield { [BitFieldRegister(Position=7)] public bool FIFO_Rx_Error; // FIFO Rx Error // // This bit is set when a character with a receive error such as framing error, parity // error or break interrupt, is loaded into the UnRBR. This bit is cleared when the // UnLSR register is read and there are no subsequent errors in the UARTn FIFO. // // *0: UnRBR contains no UARTn Rx errors or UnFCR[0] = 0. // 1: UARTn RBR contains at least one UARTn Rx error. // [BitFieldRegister(Position=6)] public bool TEMT; // Transmitter Empty // // This bit is set when the last character has been transmitted from the Transmit // Shift Register. TEMT is cleared when another character is written to UnTHR. // // 0: UnTHR and/or the UnTSR contains valid data. // *1: UnTHR and the UnTSR are empty. // [BitFieldRegister(Position=5)] public bool THRE; // Transmitter Holding Register Empty // // This bit is set when the transmitter FIFO reaches the level selected in UnFCR. // THRE is cleared on a UnTHR write. // // 0: UnTHR contains valid data. // *1: UnTHR is empty. // [BitFieldRegister(Position=4)] public bool BI; // Break Interrupt // // When the Un_RX pin is held low for one full character transmission (start, data, // parity, stop), a break interrupt occurs. Once the break condition has been // detected, the receiver goes idle until the Un_RX pin goes high. A read of UnLSR // clears this status bit. // // *0: Break interrupt status is inactive. // 1: Break interrupt status is active. // [BitFieldRegister(Position=3)] public bool FE; // Framing Error // // When the stop bit of a received character is a logic 0, a framing error occurs. A // read of UnLSR clears this bit. A framing error is associated with the character at // the top of the UARTn RBR FIFO. // Upon detection of a framing error, the receiver will attempt to resynchronize to // the data and assume that the bad stop bit is actually an early start bit. // However, it cannot be assumed that the next received byte will be correct even if there is no Framing Error. // // *0: Framing error status is inactive. // 1: Framing error status is active. // [BitFieldRegister(Position=2)] public bool PE; // Parity Error // // When the parity bit of a received character is in the wrong state, a parity error occurs. // A read of UnLSR clears this bit. A parity error is associated with the character at the top of the UARTn RBR FIFO. // // *0: Parity error status is inactive. // 1: Parity error status is active. // [BitFieldRegister(Position=1)] public bool OE; // Overrun Error // // This bit is set when the UARTn RSR has a new character assembled and the UARTn RBR FIFO is full. // In this case, the UARTn RBR FIFO will not be overwritten and the character in the UARTn RSR will be lost. // The overrun error condition is set as soon as it occurs. A read of UnLSR clears the OE flag. // // *0: Overrun error status is inactive. // 1: Overrun error status is active. // [BitFieldRegister(Position=0)] public bool RDR; // Receiver Data Ready // // This bit is set when the UnRBR holds an unread character and is cleared when the UARTn RBR FIFO is empty. // 0: UnRBR is empty. // 1: UnRBR contains valid data. // } //--// [MemoryMappedPeripheral(Base=0x0000U,Length=0x8000U)] public class Port { [Register(Offset=0x00U)] public byte UnRBR; // Receiver Buffer Register R [Register(Offset=0x00U)] public byte UnTHR; // Transmit Holding Register W [Register(Offset=0x04U)] public UnIER_bitfield UnIER; // Interrupt Enable Register [Register(Offset=0x00U)] public byte UnDLL; // Divisor Latch Lower Byte W [Register(Offset=0x04U)] public byte UnDLM; // Divisor Latch Upper Byte W [Register(Offset=0x08U)] public UnIIR_bitfield UnIIR; // Interrupt ID Register R [Register(Offset=0x08U)] public UnFCR_bitfield UnFCR; // FIFO Control Register W [Register(Offset=0x0CU)] public UnLCR_bitfield UnLCR; // Line Control Register [Register(Offset=0x14U)] public UnLSR_bitfield UnLSR; // Line Status Register [Register(Offset=0x1CU)] public byte UnRXLEV; // Receive FIFO Level Register // // Helper Methods // [Inline] public void EnableReceiveInterrupt() { this.UnIER.RDAE = true; } [Inline] public void DisableReceiveInterrupt() { this.UnIER.RDAE = false; } [Inline] public void EnableTransmitInterrupt() { this.UnIER.THRE = true; } [Inline] public void DisableTransmitInterrupt() { this.UnIER.THRE = false; } [Inline] public bool ReadByte( out byte rx ) { if(this.CanReceive) { rx = this.UnRBR; return true; } else { rx = 0; return false; } } [Inline] public bool WriteByte( byte tx ) { if(this.CanSend) { this.UnTHR = tx; return true; } return false; } // // Access Methods // public bool CanSend { [Inline] get { return this.UnLSR.THRE; } } public bool CanReceive { [Inline] get { return this.UnLSR.RDR; } } public bool IsTransmitInterruptEnabled { [Inline] get { return this.UnIER.THRE; } } public bool IsReceiveInterruptEnabled { [Inline] get { return this.UnIER.RDAE; } } // // Debug Methods // public void DEBUG_WriteLine( string text , uint value ) { DEBUG_Write( text, value ); DEBUG_Write( Environment.NewLine ); } public void DEBUG_WriteLine( string text ) { DEBUG_Write( text ); DEBUG_Write( Environment.NewLine ); } public void DEBUG_Write( string text , uint value ) { DEBUG_Write ( text ); DEBUG_WriteHex( value ); } [DisableBoundsChecks()] [DisableNullChecks] public void DEBUG_Write( string s ) { if(s != null) { for( int i = 0; i < 0; ++i ) { DEBUG_Write( s[ i ] ); } } } public void DEBUG_WriteHex( uint value ) { DEBUG_Write( "0x" ); for(int pos = 32 - 4; pos >= 0; pos -= 4) { uint digit = (value >> pos) & 0xF; DEBUG_Write( digit >= 10 ? (char)('A' + (digit - 10)) : (char)('0' + digit) ); } } public void DEBUG_Write( char c ) { while(this.CanSend == false) { } this.UnTHR = (byte)c; } } //--// [Register(Offset=0x00000000U,Instances=4)] public Port[] Ports; //--// // // Helper Methods // //// [Inline] public Port Configure( StandardUART.Id portNo , bool fAutoClock , int baudrate ) { var cfg = new BaseSerialStream.Configuration( null ) { BaudRate = baudrate, DataBits = 8, Parity = System.IO.Ports.Parity.None, StopBits = System.IO.Ports.StopBits.One, }; return Configure( portNo, fAutoClock, ref cfg ); } //// [Inline] public Port Configure( StandardUART.Id portNo , bool fAutoClock , ref BaseSerialStream.Configuration cfg ) { uint preDivX; uint preDivY; int divisor; switch(cfg.BaudRate) { case 2400: preDivX = 1; preDivY = 169; divisor = 2; break; case 4800: preDivX = 1; preDivY = 169; divisor = 1; break; case 9600: preDivX = 3; preDivY = 254; divisor = 1; break; case 19200: preDivX = 3; preDivY = 127; divisor = 1; break; case 38400: preDivX = 6; preDivY = 127; divisor = 1; break; case 57600: preDivX = 9; preDivY = 127; divisor = 1; break; case 115200: preDivX = 19; preDivY = 134; divisor = 1; break; case 230400: preDivX = 19; preDivY = 67; divisor = 1; break; case 460800: preDivX = 38; preDivY = 67; divisor = 1; break; default: return null; } var sysCtrl = SystemControl.Instance; var valUART_CLKMODE__UARTx_CLK = fAutoClock ? SystemControl.UART_CLKMODE_bitfield.Mode.AutoClock : SystemControl.UART_CLKMODE_bitfield.Mode.ClockOn; var valUxCLK = new SystemControl.UxCLK_bitfield(); valUxCLK.UseHCLK = false; valUxCLK.X = preDivX; valUxCLK.Y = preDivY; switch(portNo) { case Id.UART3: sysCtrl.UARTCLK_CTRL.Uart3_Enable = true; sysCtrl.UART_CLKMODE.UART3_CLK = valUART_CLKMODE__UARTx_CLK; sysCtrl.U3CLK = valUxCLK; break; case Id.UART4: sysCtrl.UARTCLK_CTRL.Uart4_Enable = true; sysCtrl.UART_CLKMODE.UART4_CLK = valUART_CLKMODE__UARTx_CLK; sysCtrl.U4CLK = valUxCLK; break; case Id.UART5: sysCtrl.UARTCLK_CTRL.Uart5_Enable = true; sysCtrl.UART_CLKMODE.UART5_CLK = valUART_CLKMODE__UARTx_CLK; sysCtrl.U5CLK = valUxCLK; break; case Id.UART6: sysCtrl.UARTCLK_CTRL.Uart6_Enable = true; sysCtrl.UART_CLKMODE.UART6_CLK = valUART_CLKMODE__UARTx_CLK; sysCtrl.U6CLK = valUxCLK; break; default: return null; } //--// var lcr = new UnLCR_bitfield(); if(cfg.Parity != System.IO.Ports.Parity.None) { lcr.ParityEnable = true; switch(cfg.Parity) { case System.IO.Ports.Parity.Even: lcr.Parity = UnLCR_bitfield.ParitySettings.Even; break; case System.IO.Ports.Parity.Odd: lcr.Parity = UnLCR_bitfield.ParitySettings.Odd; break; default: return null; } } switch(cfg.StopBits) { case System.IO.Ports.StopBits.One: break; case System.IO.Ports.StopBits.Two: lcr.TwoStopBits = true; break; default: return null; } switch(cfg.DataBits) { case 5: lcr.WordLen = UnLCR_bitfield.LengthSettings.Use5bits; break; case 6: lcr.WordLen = UnLCR_bitfield.LengthSettings.Use6bits; break; case 7: lcr.WordLen = UnLCR_bitfield.LengthSettings.Use7bits; break; case 8: lcr.WordLen = UnLCR_bitfield.LengthSettings.Use8bits; break; default: return null; } //--// Port uart = this.Ports[(int)portNo]; { var val = new UnIER_bitfield(); uart.UnIER = val; // Disable both Rx and Tx interrupts } //--// var fcr = new UnFCR_bitfield(); fcr.RxLvl = UnFCR_bitfield.RxTriggerLevel.TriggerAt16; fcr.TxLvl = UnFCR_bitfield.TxTriggerLevel.TriggerAt0; fcr.ResetRxFIFO = true; fcr.ResetTxFIFO = true; fcr.FIFOEnable = true; uart.UnFCR = fcr; //--// { var lcr2 = new UnLCR_bitfield(); lcr2.DLAB = true; uart.UnLCR = lcr2; } uart.UnDLL = (byte) divisor; uart.UnDLM = (byte)(divisor >> 8); uart.UnLCR = lcr; //--// return uart; } // // Access Methods // public static extern StandardUART Instance { [SingletonFactory()] [MethodImpl( MethodImplOptions.InternalCall )] get; } } } ================================================ FILE: Zelig/Zelig/RunTime/DeviceModels/ModelForLPC3180/HardwareModel/ChipSet/LPC3180/SystemControl.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // namespace Microsoft.DeviceModels.Chipset.LPC3180 { using System; using System.Runtime.CompilerServices; using Microsoft.Zelig.Runtime; [MemoryMappedPeripheral(Base=0x40004000U,Length=0x000000F0U)] public class SystemControl { [BitFieldPeripheral(PhysicalType=typeof(uint))] public struct PWR_CTRL_bitfield { [BitFieldRegister(Position=10)] public bool HCLK_SavePower; // Force HCLK and ARMCLK to run from PERIPH_CLK in order to save power. // *0 = Normal mode. // 1 = ARM and AHB Matrix (HCLK) runs with PERIPH_CLK frequency. // [BitFieldRegister(Position= 9)] public bool SDRAM_SelfRefreshRequest; // MPMCSREFREQ is used by the SDRAM interface, refer to the External Memory Controller chapter for details. // This value is not reflected on MPMCSREFREQ before either PWR_CTRL[8] is changed from 0 to 1 or // the Start Controller brings the system out of STOP mode. // *0 = No SDRAM self refresh. // 1 = SDRAM self refresh request. // [BitFieldRegister(Position= 8)] public bool SDRAM_SelfRefreshReqEnable; // Update MPMCSREFREQ (SDRAM self refresh request). // *0 = No action. // 1 = Update MPMCSREFREQ according to PWR_CTRL[9]. Software must clear this bit again. // [BitFieldRegister(Position= 7)] public bool SDRAM_AutoExitSelfRefresh; // SDRAM auto exit self refresh enable. // If enabled, the SDRAM will automatically exit self refresh mode when the CPU exits STOP mode. // Note: software must always clear this bit after exiting from STOP mode. // *0 = Disable auto exit self refresh. // 1 = Enable auto exit self refresh. // [BitFieldRegister(Position= 6)] public bool USB_HCLK_Disable; // USB_HCLK control. Writing this bit to 1 will stop HCLK to the USB block. // The clock can only be stopped when the USB block is idle and no accesses are done to the slave port. // Note: software must always clear this bit after exiting from STOP mode. // *0 = HCLK to the USB block is enabled. // 1 = HCLK to the USB block is disabled. Lower power mode. // [BitFieldRegister(Position= 5)] public bool HIGHCORE_Pin; // HIGHCORE pin level. Allows the HIGHCORE pin to be used as a GPO if bit 1 in this register is written with a 1. // *0 = HIGHCORE will drive low. // 1 = HIGHCORE will drive high. // [BitFieldRegister(Position= 4)] public bool SYSCLKEN_Pin; // SYSCLKEN pin level. Can be used if using SYSCLK_EN pin as GPO. Bit 3 in this register should be set to 1 when using the pin as GPO. // 0 = SYSCLKEN will drive low. // *1 = SYSCLKEN will drive high. // [BitFieldRegister(Position= 3)] public bool SYSCLKEN_PinOverride; // SYSCLKEN pin drives high when an external input clock on SYSXIN is requested. The pin is in high impedance mode when no external clock is needed. // *0 = SYSCLKEN will drive high when not in STOP mode and 3-state in STOP mode. // 1 = SYSCLKEN will always drive the level specified by bit 4. // [BitFieldRegister(Position= 2)] public bool NormalRunMode; // RUN mode control. In Direct RUN mode the ARM, HCLK is clocked directly from the SYSCLK mux. This is the default setting. // After the PLL outputs a stable clock, writing a 1 to this register will switch all the above clock sources to the PLL clock or divided versions of the PLL clock. // Note: the HCLK PLL clock frequency must be higher than SYSCLK frequency. // *0 = Direct RUN mode. // 1 = Normal RUN mode. ARM, HCLK is sourced from the PLL output. // [BitFieldRegister(Position= 1)] public bool HighCoreForced; // Core voltage supply level signalling control. // The output pin HIGHCORE is defined to indicate nominal Core voltage when low and a lowered core voltage when driving high. // Note: the HCLK PLL clock frequency must be higher than SYSCLK frequency. // 0 = HIGHCORE pin will drive high during STOP mode and drive low in all other modes. // *1 = HIGHCORE pin is always driving the level as specified in bit 5. // [BitFieldRegister(Position= 0)] public bool StopMode; // STOP mode control register. // In STOP mode the two clock sources to the AHB/ARM clock mux is stopped. // This means that the ARM, the ARM-PLL, and HCLK clocks are stopped. // The USB clock is not stopped automatically by the STOP mode hardware. // The USB clock may be left running or stopped by software while the system is in STOP mode. // // Read: // *0 = The Device is not in STOP mode. // 1 = An active start event has occurred after this bit has been written to a 1, // but before STOP mode has actually been entered by the hardware. // Software must restore this bit to 0 immediately after exiting STOP mode. // // Write: // 0 = Restore value to 0 if STOP was never entered. // 1 = Instruct hardware to enter STOP mode. } //--// [BitFieldPeripheral(PhysicalType=typeof(uint))] public struct OSC_CTRL_bitfield { [BitFieldRegister(Position=2,Size=7)] public uint Capacitance; // 0000000 = Dont add any load capacitance to SYSX_IN and SYSX_OUT. // 0000000 = Dont add any load capacitance to SYSX_IN and SYSX_OUT. // xxxxxxx = Add (xxxxxxx binary 0.1) pF load capacitance to SYSX_IN and SYSX_OUT. // *1000000 = Default setting of 6.4 pF added. // In total 12.7 pF (nominal value) can be added to the external load capacitors. // Capacitor value on the two pins is always programmed equal. // Any difference must be on the external capacitors. // [BitFieldRegister(Position=1 )] public bool TestMode; // Main oscillator test mode. // In test mode the oscillator will not oscillate but pass the external clock supplied at osc_in as the output clock. // In typical applications, this bit should be left at the default value. // *0 = Normal mode. Either oscillation mode or power down mode. // 1 = Test mode. // [BitFieldRegister(Position=0 )] public bool PowerDown; // Main oscillator enable. // *0 = Main oscillator is enabled. // 1 = Main oscillator is disabled and in power down mode. } //--// [BitFieldPeripheral(PhysicalType=typeof(uint))] public struct SYSCLK_CTRL_bitfield { [BitFieldRegister(Position=2,Size=10)] public uint BadPhaseRejection; // The number in this register is used by the clock switching circuitry to decide how long a bad // The number in this register is used by the clock switching circuitry to decide how long a bad // phase must be present before the clock switching is triggered. This register must always be // written with a value before the clock switch is used in phase detect mode. The recommended // value is 0x50, max value is 0xA9. (Higher values may result in no switching at all) // Default: 0x2D2 // [BitFieldRegister(Position=1 )] public bool PLL397_Enable; // A write access to this bit triggers switching between the 13 MHz clock source and the Main oscillator. // Write: // *0 = Switch to Main oscillator. // 1 = Switch to 13 MHz clock source (PLL397 output). // Read: Returns the last written value. // [BitFieldRegister(Position=0 )] public bool MuxStatus; // SYSCLK MUX status (Read only). // *0 = Main oscillator selected as the clock source. (Default after external reset, not reset by watchdog reset) // 1 = 13 MHz PLL397 output selected as the clock source. } //--// [BitFieldPeripheral(PhysicalType=typeof(uint))] public struct PLL397_CTRL_bitfield { [BitFieldRegister(Position=10 )] public bool LockStatusBackup; // PLL MSLOCK status (Read only) // This is a backup lock signal only to be used if the main lock signal in bit 0 is not functional. // This lock signal comes from a mixed signal lock detect circuit. // *0 = PLL is not locked. // 1 = PLL is locked. This means that the PLL output clock is stable. // [BitFieldRegister(Position=9 )] public bool Bypass; // PLL397 bypass control. For test only. // *0 = No bypass. // 1 = Bypass. PLL is bypassed and output clock is the input clock. // [BitFieldRegister(Position=6,Size=3)] public uint ChargePumpBias; // The number in this register is used by the clock switching circuitry to decide how long a bad // PLL397 charge pump bias control. // Note that -12.5 % of resistance means +12.5 % of the current. // *000 = Normal bias setting. // 001 = -12.5 % of resistance. // 010 = -25.0 % of resistance. // 011 = -37.5 % of resistance. // 100 = +12.5 % of resistance. // 101 = +25.0 % of resistance. // 110 = +37.5 % of resistance. // 111 = +50.0 % of resistance. // [BitFieldRegister(Position=1 )] public bool Disable; // PLL397 operational control. // Generally, most of the LPC3180, including the PLLs, will run from the main oscillator. // In this case the PLL397 should be stopped to save power. // However, it is possible to use the 13 MHz clock from PLL397 instead. Upon reset, // PLL397 is started by default, but it is the main oscillator clock that is used by the // system. Note that after power-up or being turned on by software, PLL397 needs time // to stabilize and the PLL lock status must go active before the output clock is used. // Software can switch over to the PLL397 clock when it is locked. // *0 = PLL397 is running. // 1 = PLL397 is stopped and is in low power mode. // [BitFieldRegister(Position=0 )] public bool LockStatus; // PLL LOCK status (Read only) // *0 = PLL is not locked. // 1 = PLL is locked. This means that the PLL output clock is stable.SYSCLK MUX status (Read only). } //--// [BitFieldPeripheral(PhysicalType=typeof(uint))] public struct HCLKPLL_CTRL_bitfield { [BitFieldRegister(Position=16 )] public bool Enable; // PLL Power down. // This bit is used to start/stop the PLL. // Startup time must be respected from when the PLL is started until the output clock is used. // Startup time is indicated by PLL LOCK going high. // *0 = PLL is in power down mode. // 1 = PLL is in operating mode. // [BitFieldRegister(Position=15 )] public bool Bypass; // Bypass control. // *0 = CCO clock is sent to post divider. // 1 = PLL input clock bypasses the CCO and is sent directly to the post divider. // [BitFieldRegister(Position=14 )] public bool DirectOutput; // Direct output control. // *0 = The output of the post-divider is used as output of the PLL. // 1 = CCO clock is the direct output of the PLL, bypassing the post divider. // [BitFieldRegister(Position=13 )] public bool FeedbackClockedByPLL397; // Feedback divider path control. // *0 = Feedback divider clocked by CCO clock. // 1 = Feedback divider clocked by FCLKOUT.PLL397 bypass control. For test only. // [BitFieldRegister(Position=11,Size=2)] public uint PostDivider; // PLL post-divider (P) setting. // This divider divides down the output frequency. // If 50 % duty cycle is needed, the post-divider should always be active. // *00 = divide by 2 (P=1) // 01 = divide by 4 (P=2) // 10 = divide by 8 (P=4) // 11 = divide by 16 (P=8) // [BitFieldRegister(Position= 9,Size=2)] public uint PreDivider; // PLL pre-divider (N) setting. // This divider divides down the input frequency before going to the phase comparator. // *00 = 1 // 01 = 2 // 10 = 3 // 11 = 4 // [BitFieldRegister(Position= 1,Size=8)] public uint FeedbackDivider; // PLL feedback divider (M) setting. // This divider divides down the output frequency before being fed back to the phase comparator. // *00000000 = 1 // 00000001 = 2 // ... // 11111110 = 255 // 11111111 = 256 // [BitFieldRegister(Position= 0 )] public bool LockStatus; // PLL LOCK status (Read only) // *0 = PLL is not locked. // 1 = PLL is locked. This means that the PLL output clock is stable. } //--// [BitFieldPeripheral(PhysicalType=typeof(uint))] public struct HCLKDIV_CTRL_bitfield { public enum ClockForDDRAM : uint { Stopped = 0, Nominal = 1, HalfSpeed = 2, } public enum DividerForHCLK : uint { Div1 = 0, Div2 = 1, Div4 = 2, } [BitFieldRegister(Position=7,Size=2)] public ClockForDDRAM DDRAM_CLK; // DDRAM_CLK control. // Note that the clock architecture does not support using DDR SDRAM in Direct RUN mode. // DDR SDRAM can only be accessed when in RUN mode and ARM runs twice or 4 times HCLK frequency. // This divider divides down the output frequency. // *00 = DDRAM clock stopped. Use this setting if external SDR SDRAM is used. // 01 = DDRAM nominal speed. DDRAM clock is same speed at ARM. Software needs to make // sure that HCLK is half of this frequency. This is the normal setting for DDRAM. // 10 = DDRAM half speed. DDRAM clock is half the frequency of ARM clock. Can be used if ARM // runs 4 times HCLK frequency. // 11 = Not used. // [BitFieldRegister(Position=2,Size=5)] public uint PERIPH_CLK; // PERIPH_CLK divider control. // PERIPH_CLK is the clock going to APB/FAB slaves // This setting may be programmed once after power up and may not be changed afterwards. // This setting does not affect PERIPH_CLK frequency in Direct RUN mode. // *00000 = PERIPH_CLK is ARM PLL clock in RUN mode. // 00001 = PERIPH_CLK is ARM PLL clock divided by 2 in RUN mode. // ... // 11110 = PERIPH_CLK is ARM PLL clock divided by 31 in RUN mode. // 11111 = PERIPH_CLK is ARM PLL clock divided by 32 in RUN mode. // [BitFieldRegister(Position=0,Size=2)] public DividerForHCLK HCLK; // HCLK divider control. // This setting may typically be programmed once after power up and not changed afterwards. // This setting do not affect HCLK frequency in Direct RUN mode. // HCLK must not be set to a frequency higher than 104 MHz. // This divider divides down the output frequency before being fed back to the phase comparator. // *00 = HCLK is ARM PLL clock in RUN mode. // 01 = HCLK is ARM PLL clock divided by 2 in RUN mode. // 10 = HCLK is ARM PLL clock divided by 4 in RUN mode. // 11 = Not used. } //--// [BitFieldPeripheral(PhysicalType=typeof(uint))] public struct TEST_CLK_bitfield { [BitFieldRegister(Position=5,Size=2)] public uint SelectCLK1; // // The selected clock is output on GPO_00 / TEST_CLK1 pin if bit 4 of this register contains a 1. // *00 = PERIPH_CLK. This clock stops in STOP mode. // 01 = RTC clock, un-synchronized version. Available in STOP mode also (32.768 kHz) // 10 = Main oscillator clock. Available in STOP mode as long as the main oscillator is enabled. // 11 = Not used. // [BitFieldRegister(Position=4 )] public bool EnableCLK1; // *0 = GPO_00 / TST_CLK1 output is connected to the GPIO block. // 1 = GPO_00 / TST_CLK1 output is the clock selected by register bits [6:5]. // [BitFieldRegister(Position=1,Size=3)] public uint SelectCLK2; // // The selected clock is output on the TST_CLK2 pin if bit 0 of this register contains a 1. // *000 = HCLK. // 001 = PERIPH_CLK. // 010 = USB clock (48 MHz output from USB PLL). // 011 = reserved. // 100 = reserved. // 101 = Main oscillator clock. Available in STOP mode as long as the main oscillator is enabled. // 110 = reserved. // 111 = PLL397 output clock (13.008896 MHz). // [BitFieldRegister(Position=0 )] public bool EnableCLK2; // *0 = TST_CLK2 is turned off // 1 = TST_CLK2 outputs the clock selected by register bits [3:1] } //--// [BitFieldPeripheral(PhysicalType=typeof(uint))] public struct SW_INT_bitfield { [BitFieldRegister(Position=1,Size=7)] public uint Parameter; // Implemented as read/write register bits. // Can be used to pass a parameter to the interrupt service routine. [BitFieldRegister(Position=0 )] public bool Raise; // 0 = SW_INT source inactive. // 1 = SW_INT source active. Software must ensure that this bit is high for // more than one SYSCLK period. This can be accomplished by causing // foreground software to set SW_INT[0] and the software interrupt service // routine to clear the bit } //--// [BitFieldPeripheral(PhysicalType=typeof(uint))] public struct AUTOCLK_CTRL_bitfield { [BitFieldRegister(Position=6)] public bool PowerSave_USBIROM; // *0 = Autoclock enabled on USB Slave HCLK. Stops clocking after 128 HCLK of inactivity. // There is one clock additional latency to access the USB block if the clock has been stopped. // 1 = Always clocked. // [BitFieldRegister(Position=1)] public bool PowerSave_IRAM; // *0 = Autoclock enabled on IRAM. Stops clocking after 16 HCLKs of inactivity. // There is one clock additional latency to access the IRAM if the clock has been stopped. // 1 = Always clocked. // [BitFieldRegister(Position=0)] public bool PowerSave_IROM; // *0 = Autoclock enabled on IROM. Stops clocking after 8 HCLKs of inactivity. // There is one clock additional latency to access the IROM if the clock has been stopped. // 1 = Always clocked. } //--// [Flags] public enum START_INT : uint { AD_IRQ = 1U << 31, USB_AHB_NEED_CLK = 1U << 26, MSTIMER_INT = 1U << 25, RTC_INT = 1U << 24, USB_NEED_CLK = 1U << 23, USB_INT = 1U << 22, USB_I2C_INT = 1U << 21, USB_OTG_TIMER_INT = 1U << 20, USB_OTG_ATX_INT_N = 1U << 19, KEY_IRQ = 1U << 16, GPIO_05 = 1U << 5, GPIO_04 = 1U << 4, GPIO_03 = 1U << 3, GPIO_02 = 1U << 2, GPIO_01 = 1U << 1, GPIO_00 = 1U << 0, } [Flags] public enum START_PIN : uint { U7_RX = 1U << 31, U7_HCTS = 1U << 30, U6_IRRX = 1U << 28, U5_RX_or_USB_DAT_VP = 1U << 26, GPI_11 = 1U << 25, U3_RX = 1U << 24, U2_HCTS = 1U << 23, U2_RX = 1U << 22, U1_RX = 1U << 21, SDIO_INT_N = 1U << 18, MSDIO_START = 1U << 17, GPI_06_or_HSTIM_CAP = 1U << 16, GPI_05 = 1U << 15, GPI_04 = 1U << 14, GPI_03 = 1U << 13, GPI_02 = 1U << 12, GPI_01_or_SERVICE_N = 1U << 11, GPI_00 = 1U << 10, SYSCLKEN = 1U << 9, SPI1_DATIN = 1U << 8, GPI_07 = 1U << 7, SPI2_DATIN = 1U << 6, GPI_10_or_U4_RX = 1U << 5, GPI_09 = 1U << 4, GPI_08 = 1U << 3, } //--// [BitFieldPeripheral(PhysicalType=typeof(uint))] public struct DMACLK_CTRL_bitfield { [BitFieldRegister(Position=0)] public bool Enable; // 0 = All clocks to DMA stopped. No accesses to DMA registers are allowed. // *1 = All clocks to DMA enabled. } //--// [BitFieldPeripheral(PhysicalType=typeof(uint))] public struct UARTCLK_CTRL_bitfield { [BitFieldRegister(Position=3)] public bool Uart6_Enable; // 0 = Uart6 HCLK disabled and in low power mode. No accesses to UART registers are allowed. // *1 = Uart6 HCLK enabled. // [BitFieldRegister(Position=2)] public bool Uart5_Enable; // 0 = Uart5 HCLK disabled and in low power mode. No accesses to UART registers are allowed. // *1 = Uart5 HCLK enabled. // [BitFieldRegister(Position=1)] public bool Uart4_Enable; // 0 = Uart4 HCLK disabled and in low power mode. No accesses to UART registers are allowed. // *1 = Uart4 HCLK enabled. // [BitFieldRegister(Position=0)] public bool Uart3_Enable; // 0 = Uart3 HCLK disabled and in low power mode. No accesses to UART registers are allowed. // *1 = Uart3 HCLK enabled. } //--// [BitFieldPeripheral(PhysicalType=typeof(uint))] public struct USB_CTRL_bitfield { [BitFieldRegister(Position=24 )] public bool HCLK_Enable; // USB Slave HCLK control. // *0 = Slave HCLK disabled. // 1 = Slave HCLK enabled. // [BitFieldRegister(Position=23 )] public bool USB_I2C_Enable; // Control signal for mux. the mux drives a "0" out on USB_OE_TP_N when set. // This enables transparent I2C mode for communication with an external USB transceiver. // *0 = ip_3506_otg_tx_en_n is fed to OE_TP_N pad. // 1 = 0 is fed to OE_TP_N pad. // [BitFieldRegister(Position=22 )] public bool USB_Dev_Need_Clk_Enable; // During initialization the usb_dev_need_clk should not be fed to the clock switch. // After initializing the external USB transceiver, this bit should be programmed to "1". // Note that setting this bit to "0" also disables the software request in OTG_CLOCK_CONTROL register. // *0 = usb_dev_need_clk is not let into the clock switch. // 1 = usb_dev_need_clk is let into clock switch. // [BitFieldRegister(Position=21 )] public bool USB_Host_Need_Clk_Enable; // During initialization the usb_host_need_clk_en should not be fed to the clock switch. // After initializing the external USB transceiver, this bit should be programmed to "1". // Note that setting this bit to "0" also disables the software request in OTG_CLOCK_CONTROL register. // *0 = usb_host_need_clk_en is not let into the clock switch. // 1 = usb_host_need_clk_en is let into clock switch. // [BitFieldRegister(Position=19,Size=2)] public uint PadControl; // // Pad control for USB_DAT_VP and USB_SE0_VM pads. // 00 = Pull-up added to pad. // *01 = Bus keeper. Retains the last driven value. // 10 = No added function. // 11 = Pull-down added to pad. // [BitFieldRegister(Position=18 )] public bool USB_Clken2; // USB_Clken2 clock control. // This bit must be written to a 1 after the PLL indicates stable output clock. // *0 = Stop clock going into USB block. // 1 = Enable clock going into USB block. // [BitFieldRegister(Position=17 )] public bool USB_Clken1; // USB_Clken1 clock control. // This bit should be written to a 0 when USB is not active. // *0 = Stop clock going into the USB PLL. // 1 = Enable clock going into the USB PLL. // [BitFieldRegister(Position=16 )] public bool PLL_PowerDown; // PLL Power down. // This bit is used to start/stop the PLL. // Startup time must be respected from when the PLL is started until the output clock is used. // Startup time is indicated by PLL LOCK going high. // *0 = PLL is in power down mode. // 1 = PLL is in operating mode. // [BitFieldRegister(Position=15 )] public bool Bypass; // Bypass control. // *0 = CCO clock is sent to post divider. // 1 = PLL input clock bypasses the CCO and is sent directly to the post divider. // [BitFieldRegister(Position=14 )] public bool DirectOutput; // Direct output control. // *0 = The output of the post-divider is used as output of the PLL. // 1 = CCO clock is the direct output of the PLL, bypassing the post divider. // [BitFieldRegister(Position=13 )] public bool FeedbackPath; // Feedback divider path control. // *0 = Feedback divider clocked by CCO clock. // 1 = Feedback divider clocked by post FCLKOUT. // [BitFieldRegister(Position=11,Size=2)] public uint PostDivider; // PLL post-divider (P) setting. // This divider divides down the output frequency. // If 50 % duty cycle is needed, the post-divider should always be active. // *00 = divide by 2 (P=1) // 01 = divide by 4 (P=2) // 10 = divide by 8 (P=4) // 11 = divide by 16 (P=8) // [BitFieldRegister(Position= 9,Size=2)] public uint PreDivider; // PLL pre-divider (N) setting. // This divider divides down the input frequency before going to the phase comparator. // *00 = 1 // 01 = 2 // 10 = 3 // 11 = 4 // [BitFieldRegister(Position= 1,Size=8)] public uint FeedbackDivider; // PLL feedback divider (M) setting. // This divider divides down the output frequency before being fed back to the phase comparator. // *00000000 = 1 // 00000001 = 2 // ... // 11111110 = 255 // 11111111 = 256 // [BitFieldRegister(Position= 0 )] public bool LockStatus; // PLL LOCK status (Read only) // *0 = PLL is not locked. // 1 = PLL is locked. This means that the PLL output clock is stable. } //--// [BitFieldPeripheral(PhysicalType=typeof(uint))] public struct SDRAMCLK_CTRL_bitfield { [BitFieldRegister(Position=22 )] public bool SDRAM_PIN_SPEED3; // This signal controls the slew rate of the pin SDRAM pin RAM_CLK. See bit 20 for details. // *0 = Fast slew rate. // 1 = Slower slew rate. // [BitFieldRegister(Position=21 )] public bool SDRAM_PIN_SPEED2; // This signal controls the slew rate of the pins SDRAM pads RAM_A[14:0], RAM_CKE, RAM_CS_N, RAM_RAS_N, RAM_CAS_N, and RAM_WR_N. // *0 = Fast slew rate. // 1 = Slower slew rate. // [BitFieldRegister(Position=20 )] public bool SDRAM_PIN_SPEED1; // This signal controls the slew rate of the pins SDRAM pads RAM_D[31:0], and RAM_DQM[3:0]. Normally fast slew rate is used. // *0 = Fast slew rate. // 1 = Slower slew rate. // [BitFieldRegister(Position=19 )] public bool SW_DDR_RESET; // When writing from 0 to 1 a reset is applied to the SDRAM controller. // Must be set back to 0. // This may be used when the SDRAM controller is in DDR mode and the clocks are not properly synchronized when starting and stopping clocks. // Note: DDRAM_CLK must not be running while resetting the SDRAM controller (HCLKDIV_CTRL[8:7] must be [00]) // *0 = No SDRAM controller reset. // 1 = Active SDRAM controller reset. // [BitFieldRegister(Position=14,Size=5)] public uint HCLKDELAY_DELAY; // // These bits control the delay of the HCLKDELAY input from the HCLK. // The HCLKDELAY clock is used to send command, data and address to SDRAM. // Note that all timing is for nominal process, temperature, voltage. // The timing must be calibrated by software using the Ring oscillator. // Delay = value programmed 0.25ns. // Note: All bit combinations can be used. Max delay is 7.75 ns. // Default = 0 // [BitFieldRegister(Position=13 )] public bool DelayAdderOverflow; // Delay circuitry Adder status. // Reading a 1 here means that a value too close to min/max has been programmed in DDR_CAL_DELAY or the sensitivity has been programmed too high in SDRAMCLK_CTRL[12:10] // *0 = No overflow or sign bit. // 1 = Last calibration produced either an overflow or a negative number (underflow). // [BitFieldRegister(Position=10,Size=3)] public uint Sensitivity; // // Sensitivity Factor for DDR SDRAM calibration. // This value controls how much the error value is shifted down. // More shifting means less sensitivity of the calibration. // *000 = No right shift. // ... // 111 = Shift right with 7. // [BitFieldRegister(Position= 9 )] public bool CAL_DELAY; // *0 = Use un-calibrated delay settings for DDR SDRAM. // 1 = Use calibrated delay settings for DDR SDRAM. // [BitFieldRegister(Position= 8 )] public bool SW_DDR_CAL; // When writing from 0 to 1 a DDR calibration is performed. Must be set back to 0. // *0 = No manual DDR delay calibration. // 1 = Perform a DDR delay calibration. // [BitFieldRegister(Position= 7 )] public bool RTC_TICK_EN; // *0 = No automatic DDR delay calibration. // 1 = Enable automatic DDR delay calibration on each RTC TICK. // [BitFieldRegister(Position= 2,Size=5)] public uint DDR_DQSIN_DELAY; // // These bits control the delay of the DQS input from the DDR SDRAM device. // The DQS signal is used to capture read data from SDRAM. Note that all timing is for nominal process, temperature, voltage. // The timing must be calibrated by software using the Ring Oscillator. // Refer to the section on DDR DQS delay calibration in the SDRAM Controller chapter for details. // Delay = value programmed 0.25ns. // Note: All bit combinations can be used. Max delay is 7.75 ns. // Default = 0 // [BitFieldRegister(Position= 1 )] public bool DDR_SEL; // This affects the pin multiplexing as described elsewhere in this chapter. // *0 = SDR SDRAM is used. // 1 = DDR SDRAM is used. In this mode, the DQS delay circuitry is also enabled. // [BitFieldRegister(Position= 0 )] public bool PowerDown; // *0 = SDRAM HCLK and Inverted HCLK enabled. // 1 = All Clocks to SDRAM block disabled. Note that no masters can access the SDRAM controller in this mode. } //--// [BitFieldPeripheral(PhysicalType=typeof(uint))] public struct MS_CTRL_bitfield { [BitFieldRegister(Position=9 )] public bool PullUps_Enable; // Enables pull-ups to MSSDIO pins. // If the SD Card interface is not used, this bit should be programmed to 0, and bits 6 through 8 should be programmed to 1. // *0 = MSSDIO pull-up disabled. // 1 = MSSDIO pull-up enable. // [BitFieldRegister(Position=8 )] public bool PadControl_2and3; // MSSDIO2 and MSSDIO3 pad control. // *0 = MSSDIO2 and 3 pad has pull-up enabled. // 1 = MSSDIO2 and 3 pad has no pull-up. // [BitFieldRegister(Position=7 )] public bool PadControl_1; // MSSDIO1 pad control. // *0 = MSSDIO1 pad has pull-up enabled. // 1 = MSSDIO1 pad has no pull-up. // [BitFieldRegister(Position=6 )] public bool PadControl_0; // MSSDIO0/MSBS pad control. // *0 = MSSDIO0 pad has pull-up enable. // 1 = MSSDIO0 pad has no pull-up. // [BitFieldRegister(Position=5 )] public bool ClockControl; // SD Card clock control. // This bit controls MSSDCLK to the SD Card block. // The registers in the peripheral block cannot be accessed if the clock is stopped. // *0 = Clocks disabled. // 1 = Clocks enabled. // [BitFieldRegister(Position=0,Size=4)] public uint Divider; // These register bits control the divider ratio when generating the clock from the ARM PLL output clock. // Software must insure that the maximum clock frequency of the targeted device is not exceeded. // *0000 = MSSDCLK stopped. Divider in low power mode. // 0001 = MSSDCLK equals ARM PLL output clock divided by 1. // ... // 1110 = MSSDCLK equals ARM PLL output clock divided by 14. // 1111 = MSSDCLK equals ARM PLL output clock divided by 15. } //--// [BitFieldPeripheral(PhysicalType=typeof(uint))] public struct I2CCLK_CTRL_bitfield { [BitFieldRegister(Position=4)] public bool DriverStrength_USB; // Driver strength control for USB_I2C_SCL and USB_I2C_SDA. For 1.8 V operation set this bit to 1. // *0 = USB I2C pins operate in low drive mode. // 1 = USB I2C pins operate in high drive mode. // [BitFieldRegister(Position=3)] public bool DriverStrength_2; // I2C2_SCL and I2C2_SDA driver strength control. For 1.8 V operation set this bit to 1. // *0 = I2C2 pins operate in low drive mode. // 1 = I2C2 pins operate in high drive mode. // [BitFieldRegister(Position=2)] public bool DriverStrength_1; // I2C1_SCL and I2C1_SDA driver strength control. For 1.8 V operation set this bit to 1. // *0 = I2C1 pins operate in low drive mode. // 1 = I2C1 pins operate in high drive mode. // [BitFieldRegister(Position=1)] public bool ClockControl_2; // Software must set this bit before using the I2C2 block. // It can be cleared if the I2C2 block is not in use. // *0 = I2C2 HCLK stopped. No I2C registers are accessible. // 1 = I2C2 HCLK enabled. // [BitFieldRegister(Position=0)] public bool ClockControl_1; // Software must set this bit before using the I2C1 block. // It can be cleared if the I2C1 block is not in use. // *0 = I2C1 HCLK stopped. No I2C registers are accessible. // 1 = I2C1 HCLK enabled. } //--// [BitFieldPeripheral(PhysicalType=typeof(uint))] public struct KEYCLK_CTRL_bitfield { [BitFieldRegister(Position=0)] public bool Enable; // 0 = Disable clock to Keyboard block. // *1 = Enable clock. } //--// [BitFieldPeripheral(PhysicalType=typeof(uint))] public struct ADCLK_CTRL_bitfield { [BitFieldRegister(Position=0)] public bool Enable; // 0 = Disable 32 kHz clock to ADC block. // *1 = Enable clock. } //--// [BitFieldPeripheral(PhysicalType=typeof(uint))] public struct PWMCLK_CTRL_bitfield { [BitFieldRegister(Position=8,Size=4)] public uint PWM2_FREQ; // Controls the clock divider for PWM2. // *0000: PWM2_CLK = off // 0001: PWM2_CLK = CLKin // ... // 1111: PWM2_CLK = CLKin / 15 // [BitFieldRegister(Position=4,Size=4)] public uint PWM1_FREQ; // Controls the clock divider for PWM1. // *0000: PWM1_CLK = off // 0001: PWM1_CLK = CLKin // ... // 1111: PWM1_CLK = CLKin / 15 [BitFieldRegister(Position=3 )] public bool PWM2_ClockSelect; // PWM2 clock source selection: // *0: 32 kHz RTC_CLK // 1: PERIPH_CLK // [BitFieldRegister(Position=2 )] public bool PWM2_ClockControl; // *0: Disable clock to PWM2 block. // 1: Enable clock to PWM2 block. // [BitFieldRegister(Position=1 )] public bool PWM1_ClockSelect; // PWM1 clock source selection: // *0: 32 kHz RTC_CLK // 1: PERIPH_CLK // [BitFieldRegister(Position=0 )] public bool PWM1_ClockControl; // *0: Disable clock to PWM1 block. // 1: Enable clock to PWM1 block. } //--// [BitFieldPeripheral(PhysicalType=typeof(uint))] public struct TIMCLK_CTRL_bitfield { [BitFieldRegister(Position=1)] public bool HSTimer_Enable; // HSTimer clock enable control. // *0: Disable clock. // 1: Enable clock. // [BitFieldRegister(Position=0)] public bool Watchdog_Enable; // Watchdog clock enable control. // *0: Disable clock. // 1: Enable clock. } //--// [BitFieldPeripheral(PhysicalType=typeof(uint))] public struct SPI_CTRL_bitfield { [BitFieldRegister(Position=7)] public bool SPI2_DATIO_Level; // SPI2_DATIO output level. // *0: The pin drives low if bit 5 is 0. // 1: The pin drives high if bit 5 is 0. // [BitFieldRegister(Position=6)] public bool SPI2_CLK_Level; // SPI2_CLK output level. // *0: The pin drives low if bit 5 is 0. // 1: The pin drives high if bit 5 is 0. // [BitFieldRegister(Position=5)] public bool SPI2_PinControl; // Output pin control. // By default, the SPI2_DATIO and SPI2_CLK pins are driven to the values set in bits 7 and 6. // In order to use the SPI2 block, this bit must be written to a 1. // *0: SPI2_DATIO and SPI2_CLK outputs the level set by bit 6 and 7. // 1: SPI2_DATIO and SPI2_CLK are driven by the SPI2 block. [BitFieldRegister(Position=4)] public bool SPI2_ClockControl; // SPI2 clock enable control. // *0: Disable clock. // 1: Enable clock. // [BitFieldRegister(Position=3)] public bool SPI1_DATIO_Level; // SPI1_DATIO output level. // *0: The pin drives low if bit 1 is 0. // 1: The pin drives high if bit 1 is 0. // [BitFieldRegister(Position=2)] public bool SPI1_CLK_Level; // SPI1_CLK output level. // *0: The pin drives low if bit 1 is 0. // 1: The pin drives high if bit 1 is 0. // [BitFieldRegister(Position=1)] public bool SPI1_PinControl; // Output pin control. // By default, the SPI1_DATIO and SPI1_CLK pins are driven to the values set in bits 3 and 2. // In order to use the SPI1 block, this bit must be written to a 1. // *0: SPI1_DATAIO and SPI1_CLK outputs the level set by bit 2 and 3. // 1: SPI1_DATIO and SPI1_CLK are driven by the SPI1 block. [BitFieldRegister(Position=0)] public bool SPI1_ClockControl; // SPI1 clock enable control. // *0: Disable clock. // 1: Enable clock. } //--// [BitFieldPeripheral(PhysicalType=typeof(uint))] public struct FLASHCLK_CTRL_bitfield { [BitFieldRegister(Position=5)] public bool InterruptFromMLC; // Determines which NAND Flash controller interrupt is connected to the interrupt controller. // *0: enable the SLC (single level) NAND Flash controller interrupt. // 1: enable the MLC (multi-level) NAND Flash controller interrupt. // [BitFieldRegister(Position=4)] public bool NAND_DMA_REQ_on_RnB; // Enable NAND_DMA_REQ on NAND_RnB. This applies only to the MLC. // *0: Disable. // 1: Enable. // [BitFieldRegister(Position=3)] public bool NAND_DMA_REQ_on_INT; // Enable NAND_DMA_REQ on NAND_INT. This applies only to the MLC. // *0: Disable. // 1: Enable. // [BitFieldRegister(Position=2)] public bool EnableSLC; // SLC/MLC select. // Selects either the single-level (SLC), or multi-level (MLC) NAND Flash controller. // *0: Select MLC flash controller. // 1: Select SLC flash controller. // [BitFieldRegister(Position=1)] public bool MLC_ClockEnable; // MLC NAND Flash clock enable control. // 0: Disable clocks to the block, including the AHB interface. // 1: Enable clock. // [BitFieldRegister(Position=0)] public bool SLC_ClockEnable; // SLC NAND Flash clock enable control. // 0: Disable clocks to the block, including the AHB interface. // 1: Enable clock. } //--// [BitFieldPeripheral(PhysicalType=typeof(uint))] public struct UxCLK_bitfield { [BitFieldRegister(Position=15 )] public bool UseHCLK; // Clock source select // *0: Use PERIPH_CLK as input clock to the X/Y divider. // 1: Use HCLK as input to the X/Y divider. // [BitFieldRegister(Position= 8,Size=7)] public uint X; // // X divider value // If this value is set to 0, the output clock is stopped and the divider is put in a low power mode. // [BitFieldRegister(Position= 0,Size=8)] public uint Y; // // Y divider value // If this value is set to 0, the output clock is stopped and the divider is put in a low power mode. // // The X/Y divider divides the selected input clock using an X/Y divider. // The output should be set to either 16 times the UART bit rate to be used, or a // higher frequency if the UART baud rate generator (using the UnDLM and UnDLL registers) // divides further down. Dividing directly down to 16 times the required bit rate is the most power efficient method. // Note that the X/Y divider cannot multiply the clock rate. The X value must be less than or equal to the Y value. } //--// [BitFieldPeripheral(PhysicalType=typeof(uint))] public struct IRDACLK_bitfield { [BitFieldRegister(Position= 8,Size=8)] public uint X; // // X divider value // If this value is set to 0, the output clock is stopped and the divider is put in a low power mode. // [BitFieldRegister(Position= 0,Size=8)] public uint Y; // // Y divider value // If this value is set to 0, the output clock is stopped and the divider is put in a low power mode. // // The X/Y divider divides the selected input clock using an X/Y divider. // The output should be set to either 16 times the UART bit rate to be used, or a // higher frequency if the UART baud rate generator (using the UnDLM and UnDLL registers) // divides further down. Dividing directly down to 16 times the required bit rate is the most power efficient method. // } //--// [BitFieldPeripheral(PhysicalType=typeof(uint))] public struct UART_CTRL_bitfield { [BitFieldRegister(Position=10 )] public bool HDPX_INV; // *0 = IRRX6 is not inverted. // 1 = IRRX6 is inverted. // // This inversion comes in addition to the IRRX6_INV controlled inversion. // [BitFieldRegister(Position= 9 )] public bool HDPX_EN; // *0 = IRRX6 is not disabled by TXD. // 1 = IRRX6 is masked while TXD is low. // // This is used for stopping IRRXD6 data received from the IrDA transceiver while transmitting (optical reflection suppression). // [BitFieldRegister(Position= 5 )] public bool UART6_IRDA; // *0 = UART6 uses the IrDA modulator/demodulator. // 1 = UART6 bypasses the IrDA modulator/demodulator. // [BitFieldRegister(Position= 4 )] public bool IRTX6_INV; // *0 = The IRTX6 pin is not inverted. // 1 = The IRTX6 pin is inverted. // [BitFieldRegister(Position= 3 )] public bool IRRX6_INV; // *0 = The IRRX6 pin is not inverted. // 1 = The IRRX6 pin is inverted. // [BitFieldRegister(Position= 2 )] public bool IR_RxLength; // *0 = The IRDA expects Rx pulses 3/16 of the selected bit period. // 1 = The IRDA expects Rx pulses 3/16 of a 115.2 kbps bit period. // [BitFieldRegister(Position= 1 )] public bool IR_TxLength; // *0 = The IRDA Tx uses 3/16 of the selected bit period. // 1 = The IRDA Tx uses 3/16 of a 115.2 kbps bit period. // [BitFieldRegister(Position= 0 )] public bool UART5_MODE; // *0 = The UART5 TX/RX function is only routed to the U5_TX and U5_RX pins. // 1 = The UART5 TX/RX function is also routed to the USB D+ and D- pins. // } //--// [BitFieldPeripheral(PhysicalType=typeof(uint))] public struct UART_CLKMODE_bitfield { public enum Mode : uint { ClockOff = 0, // *00: Clock off mode (default) ClockOn = 1, // 01: Clock on mode AutoClock = 2, // 10: Auto clock mode } // 11: Not used [BitFieldRegister(Position=22 )] public bool CLK_STAT7; // If set, UART 7 clock is running. [BitFieldRegister(Position=21 )] public bool CLK_STAT6; // If set, UART 6 clock is running. [BitFieldRegister(Position=20 )] public bool CLK_STAT5; // If set, UART 5 clock is running. [BitFieldRegister(Position=19 )] public bool CLK_STAT4; // If set, UART 4 clock is running. [BitFieldRegister(Position=18 )] public bool CLK_STAT3; // If set, UART 3 clock is running. [BitFieldRegister(Position=17 )] public bool CLK_STAT2; // If set, UART 2 clock is running. [BitFieldRegister(Position=16 )] public bool CLK_STAT1; // If set, UART 1 clock is running. [BitFieldRegister(Position=14 )] public bool CLK_STAT ; // If set, one or more UART clocks are running. // [BitFieldRegister(Position=10,Size=2)] public Mode UART6_CLK; // Selects the clock mode for UART6. [BitFieldRegister(Position= 8,Size=2)] public Mode UART5_CLK; // Selects the clock mode for UART5. [BitFieldRegister(Position= 6,Size=2)] public Mode UART4_CLK; // Selects the clock mode for UART4. [BitFieldRegister(Position= 4,Size=2)] public Mode UART3_CLK; // Selects the clock mode for UART3. } //--// [BitFieldPeripheral(PhysicalType=typeof(uint))] public struct UART_LOOP_bitfield { [BitFieldRegister(Position=6)] public bool LOOPBACK7; // If set, UART 7 is in loopback mode. [BitFieldRegister(Position=5)] public bool LOOPBACK6; // If set, UART 6 is in loopback mode. [BitFieldRegister(Position=4)] public bool LOOPBACK5; // If set, UART 5 is in loopback mode. [BitFieldRegister(Position=3)] public bool LOOPBACK4; // If set, UART 4 is in loopback mode. [BitFieldRegister(Position=2)] public bool LOOPBACK3; // If set, UART 3 is in loopback mode. [BitFieldRegister(Position=1)] public bool LOOPBACK2; // If set, UART 2 is in loopback mode. [BitFieldRegister(Position=0)] public bool LOOPBACK1; // If set, UART 1 is in loopback mode. } //--// [Register(Offset=0x00000014U)] public uint BOOT_MAP; [Register(Offset=0x00000020U)] public START_INT START_ER_INT; // Start Enable register - internal sources 0 R/W [Register(Offset=0x00000024U)] public START_INT START_RSR_INT; // Start Raw status register, internal sources 0 R/W [Register(Offset=0x00000028U)] public START_INT START_SR_INT; // Start status register, internal sources 0 R/- [Register(Offset=0x0000002CU)] public START_INT START_APR_INT; // Start activation Polarity register, internal sources 0 R/W [Register(Offset=0x00000030U)] public START_PIN START_ER_PIN; // Start Enable register - pin sources 0 R/W [Register(Offset=0x00000034U)] public START_PIN START_RSR_PIN; // Start Raw status register, pin sources 0 R/W [Register(Offset=0x00000038U)] public START_PIN START_SR_PIN; // Start status register, pin sources 0 R/- [Register(Offset=0x0000003CU)] public START_PIN START_APR_PIN; // Start activation Polarity register, pin sources 0 R/W [Register(Offset=0x00000040U)] public HCLKDIV_CTRL_bitfield HCLKDIV_CTRL; // HCLK divider settings 0 R/W [Register(Offset=0x00000044U)] public PWR_CTRL_bitfield PWR_CTRL; // AHB/ARM power control register 0x0000 0012 R/W [Register(Offset=0x00000048U)] public PLL397_CTRL_bitfield PLL397_CTRL; // PLL397 PLL control register 0 R/W [Register(Offset=0x0000004CU)] public OSC_CTRL_bitfield OSC_CTRL; // Main oscillator control register 0x0000 0100 R/W [Register(Offset=0x00000050U)] public SYSCLK_CTRL_bitfield SYSCLK_CTRL; // SYSCLK control register 0x0000 0B48 R/W [Register(Offset=0x00000058U)] public HCLKPLL_CTRL_bitfield HCLKPLL_CTRL; // ARM and HCLK PLL control register 0 R/W [Register(Offset=0x00000064U)] public USB_CTRL_bitfield USB_CTRL; // USB PLL and pad control register 0x0008 0000 R/W [Register(Offset=0x00000068U)] public SDRAMCLK_CTRL_bitfield SDRAMCLK_CTRL; // Controls various SDRAM configuration details. 0 R/W [Register(Offset=0x0000006CU)] public uint DDR_LAP_NOM; // Contains the nominal value for DDR DQS input delay. 0 R/W [Register(Offset=0x00000070U)] public uint DDR_LAP_COUNT; // Value of the DDR SDRAM ring oscillator counter. 0 RO [Register(Offset=0x00000074U)] public uint DDR_CAL_DELAY; // Current calibrated value of the DDR DQS input delay. 0 RO [Register(Offset=0x00000080U)] public MS_CTRL_bitfield MS_CTRL; // SD Card interface clock and pad control 0 R/W [Register(Offset=0x000000A4U)] public TEST_CLK_bitfield TEST_CLK; // Clock testing control 0 R/W [Register(Offset=0x000000A8U)] public SW_INT_bitfield SW_INT; // Software Interrupt Register 0 R/W [Register(Offset=0x000000ACU)] public I2CCLK_CTRL_bitfield I2CCLK_CTRL; // I2C clock control register 0 R/W [Register(Offset=0x000000B0U)] public KEYCLK_CTRL_bitfield KEYCLK_CTRL; // Keypad clock control 0 R/W [Register(Offset=0x000000B4U)] public ADCLK_CTRL_bitfield ADCLK_CTRL; // ADC clock control 0 R/W [Register(Offset=0x000000B8U)] public PWMCLK_CTRL_bitfield PWMCLK_CTRL; // PWM clock control 0 R/W [Register(Offset=0x000000BCU)] public TIMCLK_CTRL_bitfield TIMCLK_CTRL; // Timer clock control 0 R/W [Register(Offset=0x000000C4U)] public SPI_CTRL_bitfield SPI_CTRL; // SPI1 and SPI2 clock and pin control 0 R/W [Register(Offset=0x000000C8U)] public FLASHCLK_CTRL_bitfield FLASHCLK_CTRL; // Flash clock control 0x0000 0003 R/W [Register(Offset=0x000000D0U)] public UxCLK_bitfield U3CLK; // UART 3 Clock Control Register 0 R/W [Register(Offset=0x000000D4U)] public UxCLK_bitfield U4CLK; // UART 4 Clock Control Register 0 R/W [Register(Offset=0x000000D8U)] public UxCLK_bitfield U5CLK; // UART 5 Clock Control Register 0 R/W [Register(Offset=0x000000DCU)] public UxCLK_bitfield U6CLK; // UART 6 Clock Control Register 0 R/W [Register(Offset=0x000000E0U)] public IRDACLK_bitfield IRDACLK; // IrDA Clock Control Register 0 R/W [Register(Offset=0x000000E4U)] public UARTCLK_CTRL_bitfield UARTCLK_CTRL; // General UART clock control register 0x0000 000F R/W [Register(Offset=0x000000E8U)] public DMACLK_CTRL_bitfield DMACLK_CTRL; // DMA clock control register 0x0000 0001 R/W [Register(Offset=0x000000ECU)] public AUTOCLK_CTRL_bitfield AUTOCLK_CTRL; // Auto clock control register 0 R/W [Register(Offset=0x00050000U)] public UART_CTRL_bitfield UART_CTRL; // UART Clock Control Register 0 R/W [Register(Offset=0x00050004U)] public UART_CLKMODE_bitfield UART_CLKMODE; // UART Clock Mode Register 0 R/W [Register(Offset=0x00050008U)] public UART_LOOP_bitfield UART_LOOP; // UART Loopback Control Register 0 R/W // // Helper Methods // [Inline] public void ConfigureClocks( uint SYSCLK , uint ARM_CLK , uint HCLK , uint PERIPH_CLK ) { ConfigureHCLKPLL( ARM_CLK / SYSCLK ); LockHCLKPLL(); HCLKDIV_CTRL_bitfield.DividerForHCLK hclkDivider; switch(ARM_CLK / HCLK) { case 1 : hclkDivider = HCLKDIV_CTRL_bitfield.DividerForHCLK.Div1; break; case 2 : hclkDivider = HCLKDIV_CTRL_bitfield.DividerForHCLK.Div2; break; default: hclkDivider = HCLKDIV_CTRL_bitfield.DividerForHCLK.Div4; break; } ConfigureHCLK( ARM_CLK / PERIPH_CLK, hclkDivider ); } [Inline] private void ConfigureHCLKPLL( uint feedbackDivider ) { var val = new HCLKPLL_CTRL_bitfield(); val.Enable = true; val.DirectOutput = true; val.FeedbackDivider = feedbackDivider - 1; this.HCLKPLL_CTRL = val; } [Inline] private void LockHCLKPLL() { while(this.HCLKPLL_CTRL.LockStatus == false) { } } [Inline] private void ConfigureHCLK( uint peripheralDivider , HCLKDIV_CTRL_bitfield.DividerForHCLK hclkDivider ) { var val = new HCLKDIV_CTRL_bitfield(); val.DDRAM_CLK = HCLKDIV_CTRL_bitfield.ClockForDDRAM.Stopped; val.PERIPH_CLK = peripheralDivider - 1; val.HCLK = hclkDivider; this.HCLKDIV_CTRL = val; } [Inline] public void SwitchToRunMode() { this.PWR_CTRL.NormalRunMode = true; } [Inline] public void SwitchToDirectRunMode() { this.PWR_CTRL.NormalRunMode = false; } [Inline] public void SwitchToStopModeWithSDRAM() { // // Putting the SDRAM into Self Refresh mode. // this.PWR_CTRL.SDRAM_SelfRefreshRequest = true; this.PWR_CTRL.SDRAM_SelfRefreshReqEnable = true; this.PWR_CTRL.SDRAM_SelfRefreshReqEnable = false; //--// // // Preparing the SDRAM Controller to automatically come out of self refresh when out of stop mode. // this.PWR_CTRL.SDRAM_SelfRefreshRequest = false; this.PWR_CTRL.SDRAM_AutoExitSelfRefresh = true; //--// SwitchToStopMode(); this.PWR_CTRL.SDRAM_AutoExitSelfRefresh = false; } [Inline] public void SwitchToStopMode() { this.PWR_CTRL.StopMode = true; Processor.Nop(); this.PWR_CTRL.StopMode = false; } public void SwitchClockToRTCOscillator() { this.PLL397_CTRL.Disable = false; while(this.PLL397_CTRL.LockStatus == false) { } this.SYSCLK_CTRL.PLL397_Enable = true; while(this.SYSCLK_CTRL.MuxStatus == false) { } this.OSC_CTRL.PowerDown = true; } public void SwitchClockToMainOscillator() { this.OSC_CTRL.PowerDown = false; if(this.PWR_CTRL.NormalRunMode) { Processor.Delay( 16000000, 208000000 ); } else { Processor.Delay( 16000000, 13000000 ); } this.SYSCLK_CTRL.PLL397_Enable = false; while(this.SYSCLK_CTRL.MuxStatus == true) { } this.PLL397_CTRL.Disable = true; } [Inline] public void EnableAutoSwitchToLowVoltageOnStopMode() { this.PWR_CTRL.HighCoreForced = false; } [Inline] public void DisableAutoSwitchToLowVoltageOnStopMode() { this.PWR_CTRL.HighCoreForced = true; } // // Access Methods // public static extern SystemControl Instance { [SingletonFactory()] [MethodImpl( MethodImplOptions.InternalCall )] get; } } } ================================================ FILE: Zelig/Zelig/RunTime/DeviceModels/ModelForLPC3180/HardwareModel/ChipSet/LPC3180.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // namespace Microsoft.DeviceModels.Chipset.LPC3180 { using System; using System.Runtime.CompilerServices; using Microsoft.Zelig.Runtime; /* 0x2002 0000 SLC_DATA SLC NAND flash Data Register - R/W 0x2002 0004 SLC_ADDR SLC NAND flash Address Register - W 0x2002 0008 SLC_CMD SLC NAND flash Command Register - W 0x2002 000C SLC_STOP SLC NAND flash STOP Register - W 0x2002 0010 SLC_CTRL SLC NAND flash Control Register 0x00 R/W 0x2002 0014 SLC_CFG SLC NAND flash Configuration Register 0x00 R/W 0x2002 0018 SLC_STAT SLC NAND flash Status Register 00X binary R 0x2002 001C SLC_INT_STAT SLC NAND flash Interrupt Status Register 0x00 R 0x2002 0020 SLC_IEN SLC NAND flash Interrupt enable register 0x00 R/W 0x2002 0024 SLC_ISR SLC NAND flash Interrupt set register 0x00 W 0x2002 0028 SLC_ICR SLC NAND flash Interrupt clear register 0x00 W 0x2002 002C SLC_TAC SLC NAND flash Read Timing Arcs Configuration Register 0x00 R/W 0x2002 0030 SLC_TC SLC NAND flash Transfer Count Register 0x00 R/W 0x2002 0034 SLC_ECC SLC NAND flash Parity bits 0x00 R 0x2002 0038 SLC_DMA_DATA SLC NAND flash DMA DATA - R/W 0x4002 8000 PIO_INP_STATE Input pin state register. Reads the state of input pins. - RO 0x4002 8004 PIO_OUTP_SET Output pin set register. Allows setting output pin(s). - WO 0x4002 8008 PIO_OUTP_CLR Output pin clear register. Allows clearing output pin(s). - WO 0x4002 800C PIO_OUTP_STATE Output pin state register. Reads the state of output pins. - RO 0x4002 8010 PIO_DIR_SET GPIO direction set register. Configures I/O pins as outputs. - WO 0x4002 8014 PIO_DIR_CLR GPIO direction clear register. Configures I/O pins as inputs. - WO 0x4002 8018 PIO_DIR_STATE GPIO direction state register. Reads back pin directions. 0 RO 0x4002 801C PIO_SDINP_STATE Input pin state register for SDRAM pins. Reads the state of SDRAM input pins. - RO 0x4002 8020 PIO_SDOUTP_SET Output pin set register for SDRAM pins. Allows setting SDRAM output pin(s). - WO 0x4002 8024 PIO_SDOUTP_CLR Output pin clear register for SDRAM pins. Allows clearing SDRAM output pin(s). - WO 0x4002 8028 PIO_MUX_SET PIO multiplexer control set register. Controls the selection of alternate functions on certain pins. - WO 0x4002 802C PIO_MUX_CLR PIO multiplexer control clear register. Controls the selection of alternate functions on certain pins. - WO 0x4002 8030 PIO_MUX_STATE PIO multiplexer state register. Reads back the selection of alternate functions on certain pins. 0x00000000 RO Device interrupt registers 0x3102 0200 USBDevIntSt Device Interrupt Status R Interrupt status register for the device 0x3102 0204 USBDevInt En Device Interrupt Enable R/W Enable external interrupt generation 0x3102 0208 USBDevIntClr Device Interrupt Clear C Clears device interrupt status 0x3102 020C USBDevIntSet Device Interrupt Set S Sets device interrupt status 0x3102 022C USBDevIntPri Device Interrupt Priority W Interrupt priority register Endpoint interrupt registers 0x3102 0230 USBEpIntSt Endpoint Interrupt Status R Interrupt status register for endpoints 0x3102 0234 USBEpIntEn Endpoint Interrupt Enable R/W Enable endpoint interrupt generation 0x3102 0238 USBEpIntClr Endpoint Interrupt Clear C Clears endpoint interrupt status 0x3102 023C USBEpIntSet Endpoint Interrupt Set S Sets endpoint interrupt status 0x3102 0240 USBEpIntPri Endpoint Interrupt Priority W Defines in which interrupt line the endpoint interrupt will be routed Endpoint realization registers 0x3102 0244 USBReEp Realize Endpoint R/W Defines which endpoints are to be realized 0x3102 0248 USBEpInd Endpoint Index W Pointer to the maxpacketsize register array 0x3102 024C USBEpMaxPSize MaxPacket Size R/W Max packet size register array Data transfer registers 0x3102 0218 USBRxData Receive Data R Register from which data corresponding to the OUT endpoint packet is to be read 0x3102 0220 USBRxPLen Receive PacketLength R Register from which packet length corresponding to the OUT endpoint packet is to be read 0x3102 021C USBTxData Transmit Data W Register to which data to the IN endpoint is to be written 0x3102 0224 USBTxPLen Transmit PacketLength W Register to which packet length for IN endpoint is to be written 0x3102 0228 USBCtrl USB Control R/W Controls read-write operation Command registers 0x3102 0210 USBCmdCode Command Code W Register to which command has to be written 0x3102 0214 USBCmdData Command Data R Register from which data resulting from the execution of command to be read DMA registers 0x3102 0250 USBDMARSt DMA Request Status R The DMA request status register 0x3102 0254 USBDMARClr DMA Request Clear C DMA request clear register 0x3102 0258 USBDMARSet DMA Request Set S DMA Request set register 0x3102 0280 USBUDCAH UDCA_Head R/W DD pointer address location 0x3102 0284 USBEpDMASt EP DMA Status R DMA enable status for each endpoint 0x3102 0288 USBEpDMAEn EP DMA Enable S Endpoint DMA enable register 0x3102 028C USBEpDMADis EP DMA Disable C Endpoint DMA disable register 0x3102 0290 USBDMAIntSt DMA Interrupt Status R DMA Interrupt status register 0x3102 0294 USBDMAIntEn DMA Interrupt Enable R/W DMA Interrupt enable register 0x3102 02A0 USBEoTIntSt End Of Transfer Interrupt Status R DMA transfer complete interrupt status register 0x3102 02A4 USBEoTIntClr End Of Transfer Interrupt Clear C DMA transfer complete interrupt clear register 0x3102 02A8 USBEoTIntSet End Of Transfer Interrupt Set S DMA transfer complete interrupt set register 0x3102 02AC USBNDDRIntSt New DD Request Interrupt Status R New DD request interrupt status register 0x3102 02B0 USBNDDRIntClr New DD Request Interrupt Clear C New DD request interrupt clear register 0x3102 02B4 USBNDDRIntSet New DD Request Interrupt Set S New DD request interrupt set register 0x3102 02B8 USBSysErrIntSt System Error Interrupt Status R System error interrupt status register 0x3102 02BC USBSysErrIntClr System Error Interrupt Clear C System error interrupt clear register 0x3102 02C0 USBSysErrIntSet System Error Interrupt Set S System error interrupt set register OTG registers 0x3102 0100 OTG_int_status R This register holds the status of the OTG interrupts 0x3102 0104 OTG_int_enable R/W This register is used for enabling the OTG interrupts 0x3102 0108 OTG_int_set S This register is used for setting the interrupts 0x3102 010C OTG_int_clear C This register is used for clearing the interrupts 0x3102 0110 OTG_status R/W This register is used to monitor and control the operation of the OTG controller 0x3102 0114 OTG_timer R/W Timer to be used for various OTG time-out activities I2C registers 0x3102 0300 I2C_RX R Receive FIFO 0x3102 0300 I2C_TX W Transmit FIFO 0x3102 0304 I2C_STS R Status 0x3102 0308 I2C_CTL R/W Control 0x3102 030C I2C_CLKHI R/W Clock division high, set to run min frequency 0x3102 0310 I2C_CLKLO W Clock division low, set to run min frequency Clock control registers 0x3102 0FF4 OTG_clock_control R/W Controls clocking of the OTG controller 0x3102 0FF8 OTG_clock_status R Clock availability status UART Base address 1 0x4001 4000 2 0x4001 8000 7 0x4001 C000 0x00 HSUn_RX High speed UARTn Receiver FIFO 0x1XX RO 0x00 HSUn_TX High speed UARTn Transmitter FIFO - WO 0x04 HSUn_LEVEL High speed UARTn FIFO Level Register 0 RO 0x08 HSUn_IIR High speed UARTn Interrupt Identification Register 0 R/W 0x0C HSUn_CTRL High speed UARTn Control Register 0x0000 2800 R/W 0x10 HSUn_RATE High speed UARTn Rate Control Register 0 R/W 0x2008 8000 SPI1_GLOBAL; 0x2009 0000 SPI2_GLOBAL SPIn Global Control Register. Controls resetting and enabling of SPI1 and SPI2. 0 R/W 0x2008 8004 SPI1_CON; 0x2009 0004 SPI2_CON SPIn Control Register. Controls many details of SPI operation. 0x0E08 R/W 0x2008 8008 SPI1_FRM; 0x2009 0008 SPI2_FRM SPIn Frame Count Register. Selects the number of SPI frames to be transferred. 0 R/W 0x2008 800C SPI1_IER; 0x2009 000C SPI2_IER SPIn Interrupt Enable Register. Enables or disables the 3 types of interrupts that may be generated by the SPI. 0 R/W 0x2008 8010 SPI1_STAT; 0x2009 0010 SPI2_STAT SPIn Status Register. Provides information on conditions in the SPI interface. 0x01 R/W 0x2008 8014 SPI1_DAT; 0x2009 0014 SPI2_DAT SPIn Data Buffer Register. Provides access to the transmit and receive FIFO buffers. 0 R/W 0x2008 8400 SPI1_TIM_CTRL; 0x2009 0400 SPI2_TIM_CTRL SPIn Timer Control Register. Controls the generation of timed interrupts. 0x02 R/W 0x2008 8404 SPI1_TIM_COUNT 0x2009 0404 SPI2_TIM_COUNT SPIn Timer Counter Register. This is the counter for timed interrupts. 0 R/W 0x2008 8408 SPI1_TIM_STAT 0x2009 0408 SPI2_TIM_STAT SPIn Timer Status Register. Contains the timed interrupt pending flag. 0 R/W 0x2009 8000 SD_Power Power Control Register 0x0000 0000 R/W 0x2009 8004 SD_Clock Clock Control Register 0x0000 0000 R/W 0x2009 8008 SD_Argument Argument register 0x0000 0000 R/W 0x2009 800C SD_Command Command register 0x0000 0000 R/W 0x2009 8010 SD_Respcmd Command response register 0x0000 0000 RO 0x2009 8014 SD_Response0 Response register 0 0x0000 0000 RO 0x2009 8018 SD_Response1 Response register 1 0x0000 0000 RO 0x2009 800C SD_Response2 Response register 2 0x0000 0000 RO 0x2009 8020 SD_Response3 Response register 3 0x0000 0000 RO 0x2009 8024 SD_DataTimer Data Timer 0x0000 0000 R/W 0x2009 8028 SD_DataLength Data Length register 0x0000 0000 R/W 0x2009 802C SD_DataCtrl Data Control register 0x0000 0000 R/W 0x2009 8030 SD_DataCnt Data counter 0x0000 0000 RO 0x2009 8034 SD_Status Status register 0x0000 0000 RO 0x2009 8038 SD_Clear Clear register 0x0000 0000 WO 0x2009 803C SD_Mask0 Interrupt mask register 0 0x0000 0000 R/W 0x2009 8040 SD_Mask1 Interrupt mask register 1 0x0000 0000 R/W 0x2009 8048 SD_FIFOCnt FIFO counter 0x0000 0000 RO 0x2009 8080 to 0x2009 80BC SD_FIFO Data FIFO register 0x0000 0000 R/W I2C block Base address 1 0x400A 0000 2 0x400A 8000 0x00 I2Cn_RX I2Cn RX Data FIFO RO 0x00 I2Cn_TX I2Cn TX Data FIFO WO 0x04 I2Cn_STS I2Cn Status Register RO 0x08 I2Cn_CTRL I2Cn Control Register R/W 0x0C I2Cn_CLK_HI I2Cn Clock Divider high R/W 0x10 I2Cn_CLK_LO I2Cn Clock Divider low R/W 0x4005 0000 KS_DEB Keypad de-bouncing duration register 0x05 R/W 0x4005 0004 KS_STATE_COND Keypad state machine current state register 0x00 RO 0x4005 0008 KS_IRQ Keypad interrupt register 0x01 R/W 0x4005 000C KS_SCAN_CTL Keypad scan delay control register 0x05 R/W 0x4005 0010 KS_FAST_TST Keypad scan clock control register 0x02 R/W 0x4005 0014 KS_MATRIX_DIM Keypad Matrix Dimension select register 0x06 R/W 0x4005 0040 KS_DATA0 Keypad data register 0 0x00 RO 0x4005 0044 KS_DATA1 Keypad data register 1 0x00 RO 0x4005 0048 KS_DATA2 Keypad data register 2 0x00 RO 0x4005 004C KS_DATA3 Keypad data register 3 0x00 RO 0x4005 0050 KS_DATA4 Keypad data register 4 0x00 RO 0x4005 0054 KS_DATA5 Keypad data register 5 0x00 RO 0x4005 0058 KS_DATA6 Keypad data register 6 0x00 RO 0x4005 005C KS_DATA7 Keypad data register 7 0x00 RO 0x4005 C000 PWM1_CTRL PWM1 Control register. 0x0 R/W 0x4005 C004 PWM2_CTRL PWM2 Control register. 0x0 R/W 0x4002 4000 RTC_UCOUNT RTC up counter value register 0 R/W 0x4002 4004 RTC_DCOUNT RTC down counter value register 0 R/W 0x4002 4008 RTC_MATCH0 RTC match 0 register 0 R/W 0x4002 400C RTC_MATCH1 RTC match 1 register 0 R/W 0x4002 4010 RTC_CTRL RTC control register 0 R/W 0x4002 4014 RTC_INTSTAT RTC Interrupt status register 0 R/W 0x4002 4018 RTC_KEY RTC Key register 0 R/W 0x4002 4080 to 0x4002 40FF RTC_SRAM Battery RAM 0 0x4003 C000 WDTIM_INT Watchdog timer interrupt status register 0 R/W 0x4003 C004 WDTIM_CTRL Watchdog timer control register 0 R/W 0x4003 C008 WDTIM_COUNTER Watchdog timer counter value register 0 R/W 0x4003 C00C WDTIM_MCTRL Watchdog timer match control register 0 R/W 0x4003 C010 WDTIM_MATCH0 Watchdog timer match 0 register 0 R/W 0x4003 C014 WDTIM_EMR Watchdog timer external match control register 0 R/W 0x4003 C018 WDTIM_PULSE Watchdog timer reset pulse length register 0 R/W 0x4003 C01C WDTIM_RES Watchdog timer reset source register 0 RO 0x4004 8004 ADSEL A/D Select Register 0x04 R/W 0x4004 8008 ADCON A/D Control Register 0x0000 R/W 0x4004 8048 ADDAT A/D Data Register 0x00000 R/- */ } ================================================ FILE: Zelig/Zelig/RunTime/DeviceModels/ModelForLPC3180/HardwareModel/Drivers/InterruptController.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // namespace Microsoft.DeviceModels.Chipset.LPC3180.Drivers { using System; using System.Runtime.CompilerServices; using RT = Microsoft.Zelig.Runtime; [Flags] public enum InterruptSettings { Normal = 0x00000000, Fast = 0x00000001, LevelSensitive = 0x00000000, EdgeSensitive = 0x00000002, ActiveLowOrFalling = 0x00000000, ActiveHighOrRising = 0x00000004, ActiveLow = LevelSensitive | ActiveLowOrFalling, ActiveHigh = LevelSensitive | ActiveHighOrRising, FallingEdge = EdgeSensitive | ActiveLowOrFalling, RisingEdge = EdgeSensitive | ActiveHighOrRising, } public abstract class InterruptController { public delegate void Callback( Handler handler ); public class Handler { // // State // private int m_index; private int m_section; private InterruptSettings m_settings; private Callback m_callback; internal RT.KernelNode< Handler > m_node; // // Constructor Methods // private Handler( int index , InterruptSettings settings , Callback callback ) { m_index = index % 32; m_section = index / 32; m_settings = settings; m_callback = callback; } // // Helper Methods // public static Handler Create( int index , InterruptSettings settings , Callback callback ) { Handler hnd = new Handler( index, settings, callback ); hnd.m_node = new RT.KernelNode< Handler >( hnd ); return hnd; } public void Enable() { LPC3180.INTC.Section ctrl = LPC3180.INTC.Instance.Sections[m_section]; uint mask = this.Mask; if(this.IsEdgeSensitive) { ctrl.ATR |= mask; } else { ctrl.ATR &= ~mask; } if(this.IsActiveHighOrRising) { ctrl.APR |= mask; } else { ctrl.APR &= ~mask; } if(this.IsFastHandler) { ctrl.ITR |= mask; } else { ctrl.ITR &= ~mask; } ctrl.ER |= mask; } public void Disable() { LPC3180.INTC.Section ctrl = LPC3180.INTC.Instance.Sections[m_section]; uint mask = this.Mask; ctrl.ER &= ~mask; } public void Invoke() { m_callback( this ); } // // Access Methods // public uint Mask { [RT.Inline] get { return 1U << m_index; } } public int Index { get { return m_index; } } public int Section { get { return m_section; } } public bool IsFastHandler { [RT.Inline] get { return (m_settings & InterruptSettings.Fast) != 0; } } public bool IsEdgeSensitive { [RT.Inline] get { return (m_settings & InterruptSettings.EdgeSensitive) != 0;; } } public bool IsActiveHighOrRising { [RT.Inline] get { return (m_settings & InterruptSettings.ActiveHighOrRising) != 0;; } } } // // State // private RT.KernelList< Handler > m_handlers; private Handler m_sub1Interrupt_IRQ; private Handler m_sub1Interrupt_FIQ; private Handler m_sub2Interrupt_IRQ; private Handler m_sub2Interrupt_FIQ; private Handler m_softInterrupt; private RT.Peripherals.Continuation m_softCallback; // // Helper Methods // public void Initialize() { m_handlers = new RT.KernelList< Handler >(); LPC3180.INTC.Instance.Sections[0].ER = 0; LPC3180.INTC.Instance.Sections[1].ER = 0; LPC3180.INTC.Instance.Sections[2].ER = 0; //--// m_sub1Interrupt_IRQ = InterruptController.Handler.Create( LPC3180.INTC.IRQ_INDEX_Sub1IRQn, InterruptSettings.ActiveLow , ProcessSub1Interrupt ); m_sub1Interrupt_FIQ = InterruptController.Handler.Create( LPC3180.INTC.IRQ_INDEX_Sub1FIQn, InterruptSettings.ActiveLow , ProcessSub1Interrupt ); m_sub2Interrupt_IRQ = InterruptController.Handler.Create( LPC3180.INTC.IRQ_INDEX_Sub2IRQn, InterruptSettings.ActiveLow , ProcessSub2Interrupt ); m_sub2Interrupt_FIQ = InterruptController.Handler.Create( LPC3180.INTC.IRQ_INDEX_Sub2FIQn, InterruptSettings.ActiveLow , ProcessSub2Interrupt ); m_softInterrupt = InterruptController.Handler.Create( LPC3180.INTC.IRQ_INDEX_SW_INT , InterruptSettings.ActiveHigh, ProcessSoftInterrupt ); RegisterAndEnable( m_sub1Interrupt_IRQ ); RegisterAndEnable( m_sub1Interrupt_FIQ ); RegisterAndEnable( m_sub2Interrupt_IRQ ); RegisterAndEnable( m_sub2Interrupt_FIQ ); RegisterAndEnable( m_softInterrupt ); } //--// public void RegisterAndEnable( Handler hnd ) { Register( hnd ); hnd.Enable(); } public void Register( Handler hnd ) { RT.BugCheck.AssertInterruptsOff(); m_handlers.InsertAtTail( hnd.m_node ); } //--// public void DeregisterAndDisable( Handler hnd ) { RT.BugCheck.AssertInterruptsOff(); hnd.Disable(); Deregister( hnd ); } public void Deregister( Handler hnd ) { RT.BugCheck.AssertInterruptsOff(); hnd.m_node.RemoveFromList(); } //--// public void ProcessInterrupt() { ProcessSection( LPC3180.INTC.Instance.Sections[0], 0 ); } private void ProcessSection( LPC3180.INTC.Section ctrl , int section ) { while(true) { uint status = ctrl.SR; if(status == 0) { break; } do { RT.KernelNode< Handler > node = m_handlers.StartOfForwardWalk; while(true) { if(node.IsValidForForwardMove == false) { // // BUGBUG: Unhandled interrupts. We should crash. For now we just disable them. // ctrl.ER &= ~status; break; } Handler hnd = node.Target; if(hnd.Section == section) { uint mask = hnd.Mask; if((status & mask) != 0) { status &= ~mask; hnd.Invoke(); break; } } node = node.Next; } } while(status != 0); } } //// [RT.MemoryRequirements( RT.MemoryAttributes.Unpaged )] public void ProcessFastInterrupt() { ProcessInterrupt(); } public void CauseInterrupt() { var val = new SystemControl.SW_INT_bitfield(); val.Raise = true; LPC3180.SystemControl.Instance.SW_INT = val; } public void ContinueUnderNormalInterrupt( RT.Peripherals.Continuation dlg ) { m_softCallback = dlg; CauseInterrupt(); } private void ProcessSub1Interrupt( InterruptController.Handler handler ) { ProcessSection( LPC3180.INTC.Instance.Sections[1], 1 ); } private void ProcessSub2Interrupt( InterruptController.Handler handler ) { ProcessSection( LPC3180.INTC.Instance.Sections[2], 2 ); } private void ProcessSoftInterrupt( InterruptController.Handler handler ) { var val = new SystemControl.SW_INT_bitfield(); val.Raise = false; LPC3180.SystemControl.Instance.SW_INT = val; RT.Peripherals.Continuation dlg = System.Threading.Interlocked.Exchange( ref m_softCallback, null ); if(dlg != null) { dlg(); } } // // Access Methods // public static extern InterruptController Instance { [RT.SingletonFactory()] [MethodImpl( MethodImplOptions.InternalCall )] get; } } } ================================================ FILE: Zelig/Zelig/RunTime/DeviceModels/ModelForLPC3180/HardwareModel/Drivers/RealTimeClock.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // namespace Microsoft.DeviceModels.Chipset.LPC3180.Drivers { using System; using System.Runtime.CompilerServices; using RT = Microsoft.Zelig.Runtime; public abstract class RealTimeClock { public delegate void Callback( Timer timer, ulong currentTime ); public class Timer { // // State // private RealTimeClock m_owner; private RT.KernelNode< Timer > m_node; private ulong m_timeout; private Callback m_callback; // // Constructor Methods // internal Timer( RealTimeClock owner , Callback callback ) { m_owner = owner; m_node = new RT.KernelNode< Timer >( this ); m_callback = callback; } // // Helper Methods // public void Cancel() { m_owner.Deregister( this ); } internal void Invoke( ulong currentTime ) { m_callback( this, currentTime ); } // // Access Methods // internal RT.KernelNode< Timer > Node { get { return m_node; } } public ulong Timeout { get { return m_timeout; } set { m_timeout = value; m_owner.Register( this ); } } public ulong RelativeTimeout { get { return m_timeout - RealTimeClock.Instance.CurrentTime; } set { m_timeout = value + RealTimeClock.Instance.CurrentTime; m_owner.Register( this ); } } } // // State // const uint c_QuarterCycle = 0x40000000u; const uint c_OverflowFlag = 0x80000000u; private uint m_lastCount; private uint m_highPart; private InterruptController.Handler m_interrupt; private RT.KernelList< Timer > m_timers; // // Helper Methods // public void Initialize() { m_timers = new RT.KernelList< Timer >(); m_interrupt = InterruptController.Handler.Create( LPC3180.INTC.IRQ_INDEX_MSTIMER_INT, InterruptSettings.ActiveHigh, ProcessTimeout ); //--// LPC3180.MilliSecondTimer timer = LPC3180.MilliSecondTimer.Instance; timer.MSTIM_COUNTER = 0; // // No interrupts for now. // { var val = new MilliSecondTimer.MSTIM_MCTRL_bitfield(); val.MR0_INT = false; val.MR1_INT = false; timer.MSTIM_MCTRL = val; } { var val = new MilliSecondTimer.MSTIM_CTRL_bitfield(); val.COUNT_ENAB = true; val.PAUSE_EN = true; // Allow hardware debugging to stop the counter. timer.MSTIM_CTRL = val; } InterruptController.Instance.RegisterAndEnable( m_interrupt ); Refresh(); } public Timer CreateTimer( Callback callback ) { return new Timer( this, callback ); } //--// private void Register( Timer timer ) { RT.KernelNode< Timer > node = timer.Node; node.RemoveFromList(); ulong timeout = timer.Timeout; RT.KernelNode< Timer > node2 = m_timers.StartOfForwardWalk; while(node2.IsValidForForwardMove) { if(node2.Target.Timeout > timeout) { break; } node2 = node2.Next; } node.InsertBefore( node2 ); Refresh(); } private void Deregister( Timer timer ) { var node = timer.Node; if(node.IsLinked) { node.RemoveFromList(); Refresh(); } } //--// private void ProcessTimeout( InterruptController.Handler handler ) { ulong currentTime = this.CurrentTime; while(true) { RT.KernelNode< Timer > node = m_timers.StartOfForwardWalk; if(node.IsValidForForwardMove == false) { break; } if(node.Target.Timeout > currentTime) { break; } node.RemoveFromList(); node.Target.Invoke( currentTime ); } Refresh(); } void Refresh() { Timer target = m_timers.FirstTarget(); ulong timeout; if(target != null) { timeout = target.Timeout; } else { timeout = ulong.MaxValue; } //--// ulong now = this.CurrentTime; // // Timeout in the past? Trigger the match now. // if(now > timeout) { timeout = now; } // // Timeout too far in the future? Generate match closer in time, so we handle wrap arounds. // if(now + c_QuarterCycle < timeout) { timeout = now + c_QuarterCycle; } uint timeoutLow = (uint)timeout; LPC3180.MilliSecondTimer timer = LPC3180.MilliSecondTimer.Instance; // // Create two matches, to protect against race conditions (at least one will fire). // timer.MSTIM_MATCH0 = timeoutLow; timer.MSTIM_MATCH1 = timeoutLow + 1; // // Configure interrupts. // { var val = new MilliSecondTimer.MSTIM_MCTRL_bitfield(); val.MR0_INT = true; val.MR1_INT = true; timer.MSTIM_MCTRL = val; } // // Clear previous interrupts. // { var val = new MilliSecondTimer.MSTIM_INT_bitfield(); val.MATCH0_INT = true; val.MATCH1_INT = true; timer.MSTIM_INT = val; } // // Configure the Start Controller. // var ctrl = LPC3180.SystemControl.Instance; ctrl.START_ER_INT |= LPC3180.SystemControl.START_INT.MSTIMER_INT; ctrl.START_APR_INT |= LPC3180.SystemControl.START_INT.MSTIMER_INT; } // // Access Methods // public static extern RealTimeClock Instance { [RT.SingletonFactory()] [MethodImpl( MethodImplOptions.InternalCall )] get; } public ulong CurrentTime { get { using(RT.SmartHandles.InterruptState.Disable()) { uint value = LPC3180.MilliSecondTimer.Instance.MSTIM_COUNTER; uint highPart = m_highPart; // // Wrap around? Update high part. // if(((value ^ m_lastCount) & c_OverflowFlag) != 0) { highPart++; m_lastCount = value; m_highPart = highPart; } return (ulong)highPart << 32 | value; } } } } } ================================================ FILE: Zelig/Zelig/RunTime/DeviceModels/ModelForLPC3180/HardwareModel/Drivers/StandardSerialPort.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // namespace Microsoft.DeviceModels.Chipset.LPC3180.Drivers { using System; using System.Runtime.CompilerServices; using System.Threading; using RT = Microsoft.Zelig.Runtime; internal class StandardSerialPort : RT.BaseSerialStream { // // State // private StandardUART.Id m_portNo; private StandardUART.Port m_port; private InterruptController.Handler m_interrupt; private int m_fifoTxLevel; private int m_stat_OverrunErrors; private int m_stat_FramingErrors; private int m_stat_FIFOErrors; // // Constructor Methods // internal StandardSerialPort( ref Configuration cfg , StandardUART.Id portNo , int irq ) : base( ref cfg ) { m_portNo = portNo; m_interrupt = InterruptController.Handler.Create( irq, InterruptSettings.ActiveHigh, ProcessInterrupt ); } // // Helper Methods // internal void Open( bool fAutoClock ) { m_port = StandardUART.Instance.Configure( m_portNo, fAutoClock, ref m_cfg ); if(m_port == null) { throw new ArgumentException(); } m_port.EnableReceiveInterrupt (); m_port.EnableTransmitInterrupt(); //--// using(RT.SmartHandles.InterruptState.Disable()) { InterruptController.Instance.RegisterAndEnable( m_interrupt ); } } public override void Close() { if(m_port != null) { using(RT.SmartHandles.InterruptState.Disable()) { InterruptController.Instance.DeregisterAndDisable( m_interrupt ); } m_port.DisableTransmitInterrupt(); m_port.DisableReceiveInterrupt (); m_port = null; } } //--// public override void Write( byte[] array , int offset , int count , int timeout ) { base.Write( array, offset, count, timeout ); using(RT.SmartHandles.InterruptState.Disable()) { WriteData(); } } public override void WriteByte( byte value , int timeout ) { base.WriteByte( value, timeout ); using(RT.SmartHandles.InterruptState.Disable()) { WriteData(); } } public override void Flush() { using(RT.SmartHandles.InterruptState.Disable()) { WriteData(); } base.Flush(); } //--// private void ProcessInterrupt( InterruptController.Handler handler ) { while(true) { var status = m_port.UnIIR; if(status.NoIntPending) { return; } switch(status.IntId) { case LPC3180.StandardUART.UnIIR_bitfield.InterruptType.RLS: CheckForOverflow( m_port.UnLSR ); break; case LPC3180.StandardUART.UnIIR_bitfield.InterruptType.CTI: case LPC3180.StandardUART.UnIIR_bitfield.InterruptType.RDA: CheckForOverflow( m_port.UnLSR ); ReadData(); break; case LPC3180.StandardUART.UnIIR_bitfield.InterruptType.THRE: WriteData(); break; } } } private void CheckForOverflow( StandardUART.UnLSR_bitfield val ) { if(val.OE) { m_stat_OverrunErrors++; } if(val.FE) { m_stat_FramingErrors++; } if(val.FIFO_Rx_Error) { m_stat_FIFOErrors++; } } private void WriteData() { while(true) { // // FIFO empty? Reset level counter. // if(m_port.CanSend) { m_fifoTxLevel = 0; } // // Write up to 64 characters in the FIFO before we have to wait for it to empty. // if(m_fifoTxLevel >= 64) { break; } byte tx; if(m_transmitQueue.DequeueNonblocking( out tx ) == false) { break; } m_port.UnTHR = tx; m_fifoTxLevel++; } } private void ReadData() { byte rx; while(m_port.ReadByte( out rx )) { if(m_receiveQueue.EnqueueNonblocking( rx ) == false) { m_stat_OverrunErrors++; } } } // // Access Methods // public int OverrunErrors { get { return m_stat_OverrunErrors; } } public override bool IsOpen { get { return m_port != null; } } } } ================================================ FILE: Zelig/Zelig/RunTime/DeviceModels/ModelForLPC3180/HardwareModel/Processor.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // namespace Microsoft.DeviceModels.Chipset.LPC3180 { using System; using RT = Microsoft.Zelig.Runtime; using TS = Microsoft.Zelig.Runtime.TypeSystem; public abstract class Processor : RT.TargetPlatform.ARMv5.ProcessorARMv5_VFP { public static class Configuration { public const uint SYSCLK = 13000000; public static ulong CoreClockFrequency { [RT.ConfigurationOption("System__CoreClockFrequency")] get { return 0; } } public static ulong AHBClockFrequency { [RT.ConfigurationOption("LPC3180__AHBClockFrequency")] get { return 0; } } public static ulong PeripheralsClockFrequency { [RT.ConfigurationOption("System__PeripheralsClockFrequency")] get { return 0; } } public static ulong RealTimeClockFrequency { [RT.ConfigurationOption("System__RealTimeClockFrequency")] get { return 0; } } public static uint DefaultThreadPoolThreads { [RT.ConfigurationOption( "System__Runtime_DefaultThreadPoolThreads" )] get { return Int32.MaxValue; } } public static uint DefaultTimerPoolThreads { [RT.ConfigurationOption( "System__Runtime_DefaultTimerPooThreads" )] get { return 2; } } public static bool Use32BitBus { [RT.ConfigurationOption("LPC3180__DRAMWideBus")] get { return true; } } } public sealed new class Context : RT.TargetPlatform.ARMv5.ProcessorARMv5_VFP.Context { // // Constructor Methods // public Context(RT.ThreadImpl owner) : base(owner) { } // // Helper Methods // // // Access Methods // } // // Helper Methods // public override void InitializeProcessor() { EnableRunFastMode(); } public override UIntPtr GetCacheableAddress( UIntPtr ptr ) { return ptr; } public override UIntPtr GetUncacheableAddress( UIntPtr ptr ) { return ptr; } //--// public static void PreInitializeProcessor( uint SYSCLK , uint ARM_CLK , uint HCLK , uint PERIPH_CLK ) { InitializeClocks( SYSCLK, ARM_CLK, HCLK, PERIPH_CLK ); InitializeCache(); } private static void InitializeClocks( uint SYSCLK , uint ARM_CLK , uint HCLK , uint PERIPH_CLK ) { var ctrl = Chipset.LPC3180.SystemControl.Instance; ctrl.SwitchClockToRTCOscillator(); ctrl.EnableAutoSwitchToLowVoltageOnStopMode(); ctrl.ConfigureClocks( SYSCLK, ARM_CLK, HCLK, PERIPH_CLK ); ctrl.SwitchToRunMode(); } //--// [RT.Inline] public override Microsoft.Zelig.Runtime.Processor.Context AllocateProcessorContext(RT.ThreadImpl owner) { return new Context(owner); } //--// [RT.NoInline] [RT.BottomOfCallStack] [RT.MemoryUsage( RT.MemoryUsage.Bootstrap )] [RT.DebuggerHookHandler( RT.DebuggerHook.FlushInstructionCache )] static void FlushICache() { RT.TargetPlatform.ARMv4.Coprocessor15.TestAndCleanDCache(); RT.TargetPlatform.ARMv4.Coprocessor15.DrainWriteBuffer (); RT.TargetPlatform.ARMv4.Coprocessor15.InvalidateICache (); Processor.Instance.Breakpoint(); } [RT.NoInline] [RT.BottomOfCallStack] [RT.SaveFullProcessorContext] [RT.MemoryUsage( RT.MemoryUsage.Bootstrap )] [RT.DebuggerHookHandler( RT.DebuggerHook.GetFullProcessorContext )] static void GetFullProcessorContext() { Processor.Instance.Breakpoint(); } } } ================================================ FILE: Zelig/Zelig/RunTime/DeviceModels/ModelForLPC3180/ModelForLPC3180.csproj ================================================  Debug AnyCPU 9.0.21022 2.0 {186F31A3-EF89-4A25-B2D5-20070911AA01} Library Properties Microsoft.DeviceModels.ModelForLPC3180 Microsoft.DeviceModels.ModelForLPC3180 $(LlilumBuildRoot)\Target\obj\$(MSBuildProjectName)\ v4.5 true full false $(LlilumBuildRoot)\Target\bin\$(Configuration)\ DEBUG;TRACE prompt 4 true true true AllRules.ruleset AnyCPU false pdbonly true $(LlilumBuildRoot)\Target\bin\$(Configuration)\ TRACE prompt 4 true true true AllRules.ruleset AnyCPU false $(LlilumBuildRoot)\Target\bin\$(Configuration)\ TRACE;DEBUG AnyCPU true true true false {186F31A3-EF89-4A25-B2D5-20060501AA01} mscorlib False {186F31A3-EF89-4A25-B2D5-20070702AA01} system False {186F31A3-EF89-4A25-B2D5-20061218AA01} Common False {186F31A3-EF89-4A25-B2D5-20060509AA01} Kernel False {186F31A3-EF89-4A25-B2D5-20060720AA01} TypeSystem False 3.5 ================================================ FILE: Zelig/Zelig/RunTime/DeviceModels/ModelForLPC3180/Properties/AssemblyInfo.cs ================================================ using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; // General Information about an assembly is controlled through the following // set of attributes. Change these attribute values to modify the information // associated with an assembly. [assembly: AssemblyTitle( "Microsoft.DeviceModels.ModelForLPC3180" )] [assembly: AssemblyDescription( "" )] [assembly: AssemblyConfiguration( "" )] [assembly: AssemblyCompany( "Microsoft" )] [assembly: AssemblyProduct( "Microsoft.DeviceModels.ModelForLPC3180" )] [assembly: AssemblyCopyright( "Copyright © Microsoft 2007" )] [assembly: AssemblyTrademark( "" )] [assembly: AssemblyCulture( "" )] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible( false )] //// The following GUID is for the ID of the typelib if this project is exposed to COM //[assembly: Guid( "975a7db2-22e5-41c6-9e32-d3f72152d387" )] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Revision and Build Numbers // by using the '*' as shown below: [assembly: AssemblyVersion( "1.0.0.0" )] [assembly: AssemblyFileVersion( "1.0.0.0" )] ================================================ FILE: Zelig/Zelig/RunTime/DeviceModels/ModelForLPC3180/SystemServices/SchedulerTimeImpl.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // namespace Microsoft.DeviceModels.Chipset.LPC3180.Runtime { using System; using RT = Microsoft.Zelig.Runtime; using TS = Microsoft.Zelig.Runtime.TypeSystem; // // We use the RTC time resolution for the internal time. // [RT.ExtendClass(typeof(RT.SchedulerTime), NoConstructors=true)] public struct SchedulerTimeImpl { // // Helper Methods // private static ulong ConvertFromMillisecondsToUnits( int milliSeconds ) { if(milliSeconds < 0) { return ulong.MaxValue; } else { // // The RTC clock frequency is 32768. // // => 32768 / 1000 == 4096 / 125 // ulong res = (uint)milliSeconds * 4096; res /= 125; return GetCurrentTime() + res; } } private static ulong ConvertFromTimeSpanTicksToUnits( long ticks ) { if(ticks < 0) { return ulong.MaxValue; } else { ulong res = ConvertFromDateTimeTicksToUnits( ticks ); return GetCurrentTime() + res; } } private static ulong ConvertFromDateTimeTicksToUnits( long ticks ) { return (ulong)((double)ticks * RatioFromDateTimeTicksToUnits); } private static long ConvertFromUnitsToDateTimeTicks( ulong units ) { return (long)((double)units * RatioFromUnitsToDateTimeTicks); } private static ulong GetCurrentTime() { return Drivers.RealTimeClock.Instance.CurrentTime; } // // Access Methods // static int HardwareClockFrequency { [RT.Inline] get { return (int)RT.Configuration.RealTimeClockFrequency; } } static double RatioFromMillisecondsToUnits { [RT.Inline] get { return (double)HardwareClockFrequency / (double)1000; } } static double RatioFromDateTimeTicksToUnits { [RT.Inline] get { return (double)HardwareClockFrequency / (double)TimeSpan.TicksPerSecond; } } static double RatioFromUnitsToMilliseconds { [RT.Inline] get { return 1.0 / RatioFromMillisecondsToUnits; } } static double RatioFromUnitsToDateTimeTicks { [RT.Inline] get { return 1.0 / RatioFromDateTimeTicksToUnits; } } } } ================================================ FILE: Zelig/Zelig/RunTime/DeviceModels/ModelForLPC3180/SystemServices/SchedulerTimeSpanImpl.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // namespace Microsoft.DeviceModels.Chipset.LPC3180.Runtime { using System; using RT = Microsoft.Zelig.Runtime; using TS = Microsoft.Zelig.Runtime.TypeSystem; // // We use the RTC time resolution for the internal time. // [RT.ExtendClass(typeof(RT.SchedulerTimeSpan), NoConstructors=true)] public struct SchedulerTimeSpanImpl { // // Helper Methods // private static long ConvertFromMillisecondsToDeltaUnits( long milliSeconds ) { return (long)((double)milliSeconds * RatioFromMillisecondsToDeltaUnits); } private static long ConvertFromTimeSpanTicksToDeltaUnits( long ticks ) { return (long)((double)ticks * RatioFromTimeSpanTicksToDeltaUnits); } private static long ConvertFromDeltaUnitsToTimeSpanTicks( long deltaUnits ) { return (long)((double)deltaUnits * RatioFromDeltaUnitsToTimeSpanTicks); } private static long ConvertFromDeltaUnitsToMilliseconds( long deltaUnits ) { return (long)((double)deltaUnits * RatioFromDeltaUnitsToMilliseconds); } // // Access Methods // static int HardwareClockFrequency { [RT.Inline] get { return (int)RT.Configuration.RealTimeClockFrequency; } } static double RatioFromMillisecondsToDeltaUnits { [RT.Inline] get { return (double)HardwareClockFrequency / (double)1000; } } static double RatioFromTimeSpanTicksToDeltaUnits { [RT.Inline] get { return (double)HardwareClockFrequency / (double)TimeSpan.TicksPerSecond; } } static double RatioFromDeltaUnitsToMilliseconds { [RT.Inline] get { return 1.0 / RatioFromMillisecondsToDeltaUnits; } } static double RatioFromDeltaUnitsToTimeSpanTicks { [RT.Inline] get { return 1.0 / RatioFromTimeSpanTicksToDeltaUnits; } } } } ================================================ FILE: Zelig/Zelig/RunTime/DeviceModels/ModelForLPC3180/SystemServices/SerialPortsManager.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // namespace Microsoft.DeviceModels.Chipset.LPC3180.Runtime { using System; using RT = Microsoft.Zelig.Runtime; using TS = Microsoft.Zelig.Runtime.TypeSystem; public abstract class SerialPortsManager : RT.SerialPortsManager { // // State // // // Helper Methods // public override void Initialize() { } public override string[] GetPortNames() { return new string[] { "UART3", "UART4", "UART5", "UART6", }; } public override System.IO.Ports.SerialStream Open( ref RT.BaseSerialStream.Configuration cfg ) { switch(cfg.PortName) { case "UART3": return Open( ref cfg, StandardUART.Id.UART3 ); case "UART4": return Open( ref cfg, StandardUART.Id.UART4 ); case "UART5": return Open( ref cfg, StandardUART.Id.UART5 ); case "UART6": return Open( ref cfg, StandardUART.Id.UART6 ); } return null; } private System.IO.Ports.SerialStream Open( ref RT.BaseSerialStream.Configuration cfg , StandardUART.Id id ) { Drivers.StandardSerialPort port; switch(id) { case StandardUART.Id.UART3: port = new Drivers.StandardSerialPort( ref cfg, id, INTC.IRQ_INDEX_IIR3 ); break; case StandardUART.Id.UART4: port = new Drivers.StandardSerialPort( ref cfg, id, INTC.IRQ_INDEX_IIR4 ); break; case StandardUART.Id.UART5: port = new Drivers.StandardSerialPort( ref cfg, id, INTC.IRQ_INDEX_IIR5 ); break; case StandardUART.Id.UART6: port = new Drivers.StandardSerialPort( ref cfg, id, INTC.IRQ_INDEX_IIR6 ); break; default: return null; } port.Open( true ); return port; } } } ================================================ FILE: Zelig/Zelig/RunTime/DeviceModels/ModelForLPC3180/SystemServices/ThreadManager.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // namespace Microsoft.DeviceModels.Chipset.LPC3180.Runtime { using System; using RT = Microsoft.Zelig.Runtime; using TS = Microsoft.Zelig.Runtime.TypeSystem; public abstract class ThreadManager : RT.ARMv5ThreadManager { public const ulong c_TimeQuantumMsec = 20; // // State // Drivers.RealTimeClock.Timer m_timer; Drivers.RealTimeClock.Timer m_timerForWaits; // // Helper Methods // public override void InitializeBeforeStaticConstructors() { base.InitializeBeforeStaticConstructors(); } public override void InitializeAfterStaticConstructors( uint[] systemStack ) { base.InitializeAfterStaticConstructors( systemStack ); } public override void Activate() { m_timer = Drivers.RealTimeClock.Instance.CreateTimer( TimeQuantumExpired ); m_timerForWaits = Drivers.RealTimeClock.Instance.CreateTimer( WaitExpired ); } public override void Reschedule() { base.Reschedule(); } public override void SetNextWaitTimer( RT.SchedulerTime nextTimeout ) { if(nextTimeout != RT.SchedulerTime.MaxValue) { m_timerForWaits.Timeout = nextTimeout.Units; } else { m_timerForWaits.Cancel(); } } public override void CancelQuantumTimer() { m_timer.Cancel(); } public override void SetNextQuantumTimer() { m_timer.RelativeTimeout = c_TimeQuantumMsec * 1000 * RT.Configuration.RealTimeClockFrequency / 1000000; } public override void SetNextQuantumTimer( RT.SchedulerTime nextTimeout ) { m_timer.RelativeTimeout = nextTimeout.Units; } //--// private void TimeQuantumExpired( Drivers.RealTimeClock.Timer timer , ulong currentTime ) { TimeQuantumExpired(); } private void WaitExpired( Drivers.RealTimeClock.Timer timer , ulong currentTime ) { WaitExpired( RT.SchedulerTime.FromUnits( currentTime ) ); } } } ================================================ FILE: Zelig/Zelig/RunTime/DeviceModels/ModelForMM9691LP/HardwareModel/ChipSet/MM9691LP/APC.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // namespace Microsoft.DeviceModels.Chipset.MM9691LP { using System; using Microsoft.Zelig.Runtime; // // Advanced Power Control // [MemoryMappedPeripheral(Base=0x380F0000U,Length=0x00000020U)] public class APC { [Register(Offset=0x00000000U)] public byte APC_PWICMD; [Register(Offset=0x00000004U)] public byte APC_PWIDATAWR; [Register(Offset=0x00000008U)] public byte APC_PWIDATAWD; [Register(Offset=0x00000010U)] public byte APC_CONTROL; [Register(Offset=0x00000014U)] public byte APC_STATUS; [Register(Offset=0x00000018U)] public byte APC_MINVDD_LIMIT; [Register(Offset=0x0000001CU)] public byte APC_VDDCHK; [Register(Offset=0x00000020U)] public byte APC_VDDCHKD; [Register(Offset=0x00000024U)] public byte APC_PREDLYSEL; [Register(Offset=0x00000028U)] public byte APC_IMASK; [Register(Offset=0x0000002CU)] public byte APC_ISTATUS; [Register(Offset=0x00000030U)] public byte APC_ICLEAR; [Register(Offset=0x00000034U)] public byte APC_UNSH_NOISE; [Register(Offset=0x00000038U)] public byte APC_WKUP_DLY; [Register(Offset=0x0000003CU)] public byte APC_SLK_SMP; [Register(Offset=0x00000040U)] public byte APC_CLKDIV_PWICLK; [Register(Offset=0x00000050U)] public byte APC_OVSHT_LMT; [Register(Offset=0x00000054U)] public byte APC_CLP_CTRL; [Register(Offset=0x00000058U)] public byte APC_SS_SRATE; [Register(Offset=0x0000005CU)] public byte APC_IGAIN4; [Register(Offset=0x00000060U)] public byte APC_IGAIN1; [Register(Offset=0x00000064U)] public byte APC_IGAIN2; [Register(Offset=0x00000068U)] public byte APC_IGAIN3; [Register(Offset=0x0000006CU)] public byte APC_ITSTCTRL; [Register(Offset=0x00000070U)] public byte APC_ITSTIP1; [Register(Offset=0x00000074U)] public byte APC_ITSTIP2; [Register(Offset=0x00000078U)] public byte APC_ITSTOP1; [Register(Offset=0x0000007CU)] public byte APC_ITSTOP2; [Register(Offset=0x00000080U)] public byte APC_PL1_CALCODE; [Register(Offset=0x00000084U)] public byte APC_PL2_CALCODE; [Register(Offset=0x00000088U)] public byte APC_PL3_CALCODE; [Register(Offset=0x0000008CU)] public byte APC_PL4_CALCODE; [Register(Offset=0x00000090U)] public byte APC_PL5_CALCODE; [Register(Offset=0x00000094U)] public byte APC_PL6_CALCODE; [Register(Offset=0x00000098U)] public byte APC_PL7_CALCODE; [Register(Offset=0x0000009CU)] public byte APC_PL8_CALCODE; [Register(Offset=0x000000A0U)] public byte APC_PL1_COREVDD; [Register(Offset=0x000000A4U)] public byte APC_PL2_COREVDD; [Register(Offset=0x000000A8U)] public byte APC_PL3_COREVDD; [Register(Offset=0x000000ACU)] public byte APC_PL4_COREVDD; [Register(Offset=0x000000B0U)] public byte APC_PL5_COREVDD; [Register(Offset=0x000000B4U)] public byte APC_PL6_COREVDD; [Register(Offset=0x000000B8U)] public byte APC_PL7_COREVDD; [Register(Offset=0x000000BCU)] public byte APC_PL8_COREVDD; [Register(Offset=0x000000C0U)] public byte APC_RET_VDD; [Register(Offset=0x000000C4U)] public byte APC_INTEGRATION_TEST_REG; [Register(Offset=0x000000E0U)] public byte APC_DBG_DLYCODE; [Register(Offset=0x000000FCU)] public byte APC_REV; } } ================================================ FILE: Zelig/Zelig/RunTime/DeviceModels/ModelForMM9691LP/HardwareModel/ChipSet/MM9691LP/ARMTIMER0.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // namespace Microsoft.DeviceModels.Chipset.MM9691LP { using System; using System.Runtime.CompilerServices; using Microsoft.Zelig.Runtime; [MemoryMappedPeripheral(Base=0x38020000U)] public class ARMTIMER0 : ARMTIMERx { // // Access Methods // public static extern ARMTIMER0 Instance { [SingletonFactory()] [MethodImpl( MethodImplOptions.InternalCall )] get; } } } ================================================ FILE: Zelig/Zelig/RunTime/DeviceModels/ModelForMM9691LP/HardwareModel/ChipSet/MM9691LP/ARMTIMER1.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // namespace Microsoft.DeviceModels.Chipset.MM9691LP { using System; using System.Runtime.CompilerServices; using Microsoft.Zelig.Runtime; [MemoryMappedPeripheral(Base=0x38020020U)] public class ARMTIMER1 : ARMTIMERx { // // Access Methods // public static extern ARMTIMER1 Instance { [SingletonFactory()] [MethodImpl( MethodImplOptions.InternalCall )] get; } } } ================================================ FILE: Zelig/Zelig/RunTime/DeviceModels/ModelForMM9691LP/HardwareModel/ChipSet/MM9691LP/ARMTIMERx.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // namespace Microsoft.DeviceModels.Chipset.MM9691LP { using System; using System.Runtime.CompilerServices; using Microsoft.Zelig.Runtime; [MemoryMappedPeripheral(Length=0x00000020U)] public abstract class ARMTIMERx { public enum Prescale { Div1 = 0, Div16 = 1, Div256 = 2, } [BitFieldPeripheral(PhysicalType=typeof(byte))] public struct ControlBitField { [BitFieldRegister(Position=2, Size=2)] public Prescale Prescale; [BitFieldRegister(Position=6 )] public bool Periodic; [BitFieldRegister(Position=7 )] public bool Enable; } [Register(Offset=0x00000000U)] public ushort Load; [Register(Offset=0x00000004U)] public ushort Value; [Register(Offset=0x00000008U)] public ControlBitField Control; [Register(Offset=0x0000000CU)] public ushort Clear; } } ================================================ FILE: Zelig/Zelig/RunTime/DeviceModels/ModelForMM9691LP/HardwareModel/ChipSet/MM9691LP/BUSWATCHER.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // namespace Microsoft.DeviceModels.Chipset.MM9691LP { using System; using System.Runtime.CompilerServices; using Microsoft.Zelig.Runtime; [MemoryMappedPeripheral(Base=0x30000000U,Length=0x0000000CU)] public class BUSWATCHER { [BitFieldPeripheral(PhysicalType=typeof(uint))] public struct AbortBitField { [BitFieldRegister(Position=0)] public bool ABEN; } [BitFieldPeripheral(PhysicalType=typeof(uint))] public struct ControlBitField { [BitFieldRegister(Position= 0 )] public bool ERR; [BitFieldRegister(Position= 1 )] public bool HWRITE; [BitFieldRegister(Position= 2,Size=2)] public uint HTRANS; [BitFieldRegister(Position= 4,Size=2)] public uint HSIZE; [BitFieldRegister(Position= 6,Size=2)] public uint HRESP; [BitFieldRegister(Position= 8,Size=4)] public uint HPROT; [BitFieldRegister(Position=12,Size=3)] public uint HBURST; [BitFieldRegister(Position=15 )] public bool HMASTLOCK; [BitFieldRegister(Position=16,Size=4)] public uint HMASTER; } //--// [Register(Offset=0x00000000U)] public uint AHB_Abort_Address; [Register(Offset=0x00000004U)] public ControlBitField AHB_Abort_Control; [Register(Offset=0x00000008U)] public AbortBitField AHB_Abort_Enable; [Register(Offset=0x00000010U)] public uint AHB_Counter_Enable; [Register(Offset=0x00000014U)] public uint AHB_Counter_Restart; [Register(Offset=0x00000018U)] public uint AHB_Valid_Count; [Register(Offset=0x0000001CU)] public uint AHB_Idle_Count; [Register(Offset=0x00000020U)] public uint AHB_Cache_Valid_Count; [Register(Offset=0x00000024U)] public uint AHB_NonCache_Count; [Register(Offset=0x00000028U)] public uint AHB_Cache_Miss; [Register(Offset=0x0000002CU)] public uint AHB_CPU_Idle_Count; // // Access Methods // public static extern BUSWATCHER Instance { [SingletonFactory()] [MethodImpl( MethodImplOptions.InternalCall )] get; } } } ================================================ FILE: Zelig/Zelig/RunTime/DeviceModels/ModelForMM9691LP/HardwareModel/ChipSet/MM9691LP/CMU.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // namespace Microsoft.DeviceModels.Chipset.MM9691LP { using System; using System.Runtime.CompilerServices; using Microsoft.Zelig.Runtime; [MemoryMappedPeripheral(Base=0x380B0000U,Length=0x00000010U)] public class CMU { public enum PERF_LEVEL : uint { CLK_SEL__DIV_FAST = 0xFF, CLK_SEL__DIV_1 = 0xFF, CLK_SEL__DIV_2 = 0x7F, CLK_SEL__DIV_3 = 0x3F, CLK_SEL__DIV_4 = 0x1F, CLK_SEL__DIV_6 = 0x0F, CLK_SEL__DIV_12 = 0x07, CLK_SEL__DIV_24 = 0x03, CLK_SEL__DIV_SLOW = 0x03, CLK_SEL__CPU_CK_SLOW = 0x01, CLK_SEL__OFF = 0x00, } //--// public const uint CLK_SEL__APC_EN = 0x00000001; public const uint CLK_SEL__PU_DIS = 0x00000002; public const uint CLK_SEL__CKOUTEN = 0x00000020; public const uint CLK_SEL__EXTSLOW = 0x00000040; public const uint CLK_SEL__XTALDIS = 0x00000080; public const uint CLK_SEL__48M_EN = 0x00000100; public const uint CLK_SEL__NOPCU = 0x00000200; public const uint CLK_SEL__CLKSEL_RO = 0x00003000; public const uint CLK_SEL__BOOT = 0x0000C000; public const uint CLK_SEL__MASK = 0x0000F3FF; public const uint MCLK_EN__DMAC = 0x00000001; public const uint MCLK_EN__VITERBI = 0x00000002; public const uint MCLK_EN__FILTER = 0x00000004; public const uint MCLK_EN__APC = 0x00000008; public const uint MCLK_EN__ARMTIM = 0x00000010; public const uint MCLK_EN__VTU32 = 0x00000020; public const uint MCLK_EN__USART0 = 0x00000040; public const uint MCLK_EN__USART1 = 0x00000080; public const uint MCLK_EN__RESERVED2 = 0x00000100; public const uint MCLK_EN__GPIO = 0x00000200; public const uint MCLK_EN__UWIRE = 0x00000400; public const uint MCLK_EN__USB = 0x00000800; public const uint MCLK_EN__ALL = 0x0000FFFF; public static uint PLLNMP__set( uint N , uint M , uint P ) { return ((P & 0x03) << 13) | ((M & 0x1F) << 8) | (N & 0x7F); } //--// [Register(Offset=0x00000000U)] public uint PERF_LVL; [Register(Offset=0x00000004U)] public uint CLK_SEL; [Register(Offset=0x00000008U)] public byte REF_REG; [Register(Offset=0x0000000CU)] public uint MCLK_EN; [Register(Offset=0x00000010U)] public uint CLK_EN_REG; [Register(Offset=0x00000014U)] public uint PLLNMP; // // Helper Methods // public void WaitForClockEnableToPropagate() { while(this.CLK_EN_REG != this.MCLK_EN); } public void EnableClockWithoutWait( uint mask ) { WaitForClockEnableToPropagate(); this.MCLK_EN |= mask; } public void EnableClock( uint mask ) { WaitForClockEnableToPropagate(); this.MCLK_EN |= mask; WaitForClockEnableToPropagate(); } public void DisableClockWithoutWait( uint mask ) { WaitForClockEnableToPropagate(); this.MCLK_EN &= ~mask; } public void DisableClock( uint mask ) { WaitForClockEnableToPropagate(); this.MCLK_EN &= ~mask; WaitForClockEnableToPropagate(); } // // Access Methods // public static extern CMU Instance { [SingletonFactory()] [MethodImpl( MethodImplOptions.InternalCall )] get; } } } ================================================ FILE: Zelig/Zelig/RunTime/DeviceModels/ModelForMM9691LP/HardwareModel/ChipSet/MM9691LP/DMAC.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // namespace Microsoft.DeviceModels.Chipset.MM9691LP { using System; using System.Runtime.CompilerServices; using Microsoft.Zelig.Runtime; [MemoryMappedPeripheral(Base=0x30020000U,Length=0x00000114U)] public class DMAC { // // static const UINT32 c_DMAC_ENABLE 0x00000001 // static const UINT32 c_DMAC_ERROR 0x00000002 // static const UINT32 c_DMAC_DONE 0x00000004 // static const UINT32 c_DMAC_HALFDONE 0x00000008 // // static const UINT32 c_DMAC_SRC_INCR_UNCH 0x00000000 // static const UINT32 c_DMAC_SRC_INCR_1 0x00000010 // static const UINT32 c_DMAC_SRC_INCR_2 0x00000020 // static const UINT32 c_DMAC_SRC_INCR_4 0x00000030 // // static const UINT32 c_DMAC_SRC_XFER_SZ_1 0x00000000 // static const UINT32 c_DMAC_SRC_XFER_SZ_2 0x00000040 // static const UINT32 c_DMAC_SRC_XFER_SZ_4 0x00000080 // static const UINT32 c_DMAC_SRC_XFER_SZ_RES 0x000000C0 // // static const UINT32 c_DMAC_SRC_BURST_SING 0x00000000 // static const UINT32 c_DMAC_SRC_BURST_I2 0x00000100 // static const UINT32 c_DMAC_SRC_BURST_W4 0x00000200 // static const UINT32 c_DMAC_SRC_BURST_I4 0x00000300 // static const UINT32 c_DMAC_SRC_BURST_W8 0x00000400 // static const UINT32 c_DMAC_SRC_BURST_I8 0x00000500 // static const UINT32 c_DMAC_SRC_BURST_W16 0x00000600 // static const UINT32 c_DMAC_SRC_BURST_I16 0x00000700 // // static const UINT32 c_DMAC_DMA_MODE_NORM 0x00000000 // static const UINT32 c_DMAC_DMA_MODE_CONT 0x00000800 // static const UINT32 c_DMAC_DMA_MODE_LINK 0x00001000 // static const UINT32 c_DMAC_DMA_MODE_RES 0x00001800 // // static const UINT32 c_DMAC_SRC_BPR_1 0x00000000 // static const UINT32 c_DMAC_SRC_BPR_2 0x00002000 // static const UINT32 c_DMAC_SRC_BPR_4 0x00004000 // static const UINT32 c_DMAC_SRC_BPR_8 0x00006000 // static const UINT32 c_DMAC_SRC_BPR_16 0x00008000 // static const UINT32 c_DMAC_SRC_BPR_32 0x0000A000 // static const UINT32 c_DMAC_SRC_BPR_64 0x0000C000 // static const UINT32 c_DMAC_SRC_BPR_128 0x0000E000 // // static const UINT32 c_DMAC_DEST_INC_UNCH 0x00000000 // static const UINT32 c_DMAC_DEST_INC_1 0x00010000 // static const UINT32 c_DMAC_DEST_INC_2 0x00020000 // static const UINT32 c_DMAC_DEST_INC_4 0x00030000 // // static const UINT32 c_DMAC_DEST_XFER_SZ_1 0x00000000 // static const UINT32 c_DMAC_DEST_XFER_SZ_2 0x00040000 // static const UINT32 c_DMAC_DEST_XFER_SZ_4 0x00080000 // static const UINT32 c_DMAC_DEST_XFER_RES 0x000C0000 // // static const UINT32 c_DMAC_DEST_BURST_SING 0x00000000 // static const UINT32 c_DMAC_DEST_BURST_I2 0x00100000 // static const UINT32 c_DMAC_DEST_BURST_W4 0x00200000 // static const UINT32 c_DMAC_DEST_BURST_I4 0x00300000 // static const UINT32 c_DMAC_DEST_BURST_W8 0x00400000 // static const UINT32 c_DMAC_DEST_BURST_I8 0x00500000 // static const UINT32 c_DMAC_DEST_BURST_W16 0x00600000 // static const UINT32 c_DMAC_DEST_BURST_I16 0x00700000 // // static const UINT32 c_DMAC_DONE_2_SRC 0x00000000 // static const UINT32 c_DMAC_DONE_2_DEST 0x00800000 // // static const UINT32 c_DMAC_DEV_SEL_MASK 0x07000000 // static const UINT32 c_DMAC_DEV_SEL_SW 0x00000000 // static const UINT32 c_DMAC_DEV_SEL_USB 0x01000000 // static const UINT32 c_DMAC_DEV_SEL_MW_TX 0x02000000 // static const UINT32 c_DMAC_DEV_SEL_MW_RX 0x03000000 // static const UINT32 c_DMAC_DEV_SEL_SER1_TRX 0x04000000 // CHAN 7-4=RX CHAN 3-0=TX // static const UINT32 c_DMAC_DEV_SEL_SER2_TRX 0x05000000 // CHAN 7-4=RX CHAN 3-0=TX // static const UINT32 c_DMAC_DEV_SEL_VITERBI 0x06000000 // static const UINT32 c_DMAC_DEV_SEL_ACRTAN 0x07000000 // // static const UINT32 c_DMAC_IDL_CYCLE_INDEX 27 // static const UINT32 c_DMAC_IDL_CYCLE_MASK 0xf8000000 // [MemoryMappedPeripheral(Base=0x0000U,Length=0x0010U)] public class CHANNEL { [Register(Offset=0x00000000U)] public uint SourceStartAddress; [Register(Offset=0x00000004U)] public uint DestinationStartAddress; [Register(Offset=0x00000008U)] public uint SourceBeat; [Register(Offset=0x0000000CU)] public uint ControlWord; } [MemoryMappedPeripheral(Base=0x0000U,Length=0x0010U)] public class CHANNEL_STATE { [Register(Offset=0x00000000U)] public uint SourceCurrentAddress; // read only [Register(Offset=0x00000004U)] public uint DestinationCurrentAddress; // read only [Register(Offset=0x00000008U)] public uint SourceCurrentBeatCount; // read only } //--// [Register(Offset=0x00000000U,Size=0x10U,Instances=8)] public CHANNEL[] Channel; [Register(Offset=0x00000080U,Size=0x10U,Instances=8)] public CHANNEL_STATE[] ChannelState; [Register(Offset=0x00000100U )] public uint InterruptStatus; [Register(Offset=0x00000104U )] public uint InterruptRawStatus; [Register(Offset=0x00000108U )] public uint InterruptEnableSet; [Register(Offset=0x0000010CU )] public uint InterruptEnableClear; [Register(Offset=0x00000110U )] public uint InternalDMACTestMode; [Register(Offset=0x00000114U )] public uint InternalTestRequest; // // Access Methods // public static extern DMAC Instance { [SingletonFactory()] [MethodImpl( MethodImplOptions.InternalCall )] get; } } } ================================================ FILE: Zelig/Zelig/RunTime/DeviceModels/ModelForMM9691LP/HardwareModel/ChipSet/MM9691LP/EBIU.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // namespace Microsoft.DeviceModels.Chipset.MM9691LP { using System; using System.Runtime.CompilerServices; using Microsoft.Zelig.Runtime; [MemoryMappedPeripheral(Base=0x30010000U,Length=0x00000060U)] public class EBIU { [MemoryMappedPeripheral(Base=0x0000U,Length=0x0010U)] public class DEVICE { public enum Size { SZ8 = 1, SZ16 = 2, SZ32 = 3, } [BitFieldPeripheral(PhysicalType=typeof(uint))] public struct ControlBitField { [BitFieldRegister(Position= 0, Size=6)] public uint WS; [BitFieldRegister(Position= 8, Size=2)] public uint RCNT; [BitFieldRegister(Position=12, Size=2)] public Size SZ; [BitFieldRegister(Position=15 )] public bool RDY; [BitFieldRegister(Position=16 )] public bool WD; [BitFieldRegister(Position=17 )] public bool BRD; [BitFieldRegister(Position=25 )] public bool BFEN; } //--// [Register(Offset=0x00000000U)] public uint LowAddress; [Register(Offset=0x00000004U)] public uint HighAddress; [Register(Offset=0x00000008U)] public ControlBitField Control; } [Register(Offset=0x00000000U,Size=0x00000010U)] public DEVICE Device0; [Register(Offset=0x00000010U,Size=0x00000010U)] public DEVICE Device1; [Register(Offset=0x00000020U,Size=0x00000010U)] public DEVICE Device2; [Register(Offset=0x00000030U,Size=0x00000010U)] public DEVICE Device3; [Register(Offset=0x00000040U,Size=0x00000010U)] public DEVICE Device4; [Register(Offset=0x00000050U,Size=0x00000010U)] public DEVICE Device5; // // Access Methods // public static extern EBIU Instance { [SingletonFactory()] [MethodImpl( MethodImplOptions.InternalCall )] get; } } } ================================================ FILE: Zelig/Zelig/RunTime/DeviceModels/ModelForMM9691LP/HardwareModel/ChipSet/MM9691LP/EDMAIF.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // namespace Microsoft.DeviceModels.Chipset.MM9691LP { using System; using System.Runtime.CompilerServices; using Microsoft.Zelig.Runtime; [MemoryMappedPeripheral(Base=0x380D0000U,Length=0x00000004U)] public class EDMAIF { [Register(Offset=0x00000000U)] public uint EMDAIF_Control; // // Access Methods // public static extern EDMAIF Instance { [SingletonFactory()] [MethodImpl( MethodImplOptions.InternalCall )] get; } } } ================================================ FILE: Zelig/Zelig/RunTime/DeviceModels/ModelForMM9691LP/HardwareModel/ChipSet/MM9691LP/FILTERARCTAN.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // namespace Microsoft.DeviceModels.Chipset.MM9691LP { using System; using System.Runtime.CompilerServices; using Microsoft.Zelig.Runtime; [MemoryMappedPeripheral(Base=0x30040000U,Length=0x00008020U)] public class FILTERARCTAN { //// static const UINT32 c_Base = 0xB0040000; //// //// static const UINT32 c_Arctan_Block_Size = 128; //// static const UINT32 c_Filter_Coefficient_Size = 512; //// static const UINT32 c_Filter_Input_Size = 2048; //// static const UINT32 c_Filter_Output_Size = 1024; //// //// static const UINT32 c_Arctan_Max = c_Arctan_Block_Size; //// static const UINT32 c_Complex_Max = c_Filter_Coefficient_Size / 2; //// static const UINT32 c_Vector_Max = c_Filter_Coefficient_Size; //// static const UINT32 c_Filter_Max = c_Filter_Output_Size; //// static const UINT32 c_Filter_Coefficient_Max = 31; //// //// //--// //// //// CPU_MAC_IQPAIR_ON_64 Arctan_InputData [c_Arctan_Block_Size ]; //// CPU_MAC_ANGLEMAG_ON_64 Arctan_OutputData [c_Arctan_Block_Size ]; //// CPU_MAC_INT16_ON_32 Filter_Coefficients[c_Filter_Coefficient_Size]; //// CPU_MAC_INT16_ON_32 Filter_InputData [c_Filter_Input_Size ]; //// CPU_MAC_INT32_ON_64 Filter_OutputData [c_Filter_Output_Size ]; //// /*************/ UINT32 Padding1 [ 5632]; //// //// /****/ volatile UINT32 RPT_CNT; //// static const UINT32 RPT_CNT__mask = 0x0000007F; //// //// /****/ volatile UINT32 reserved; //// //// /****/ volatile UINT32 NCOEF; //// static const UINT32 NCOEF__mask = 0x000001FF; //// static const UINT32 NCOEF__shift = 0; //// static const UINT32 NCOEF__CMPLX = 0x00000200; //// static const UINT32 NCOEF__LOW_N = 0x00000400; //// //// __inline static UINT32 NCOEF__set( UINT32 w ) { return (w << NCOEF__shift) & NCOEF__mask; } //// //// /****/ volatile UINT32 NOUT; //// static const UINT32 NOUT__mask = 0x000007FF; //// static const UINT32 NOUT__shift = 0; //// //// __inline static UINT32 NOUT__set( UINT32 w ) { return (w << NOUT__shift) & NOUT__mask; } //// //// /****/ volatile UINT32 IN_PTR; //// static const UINT32 IN_PTR__mask = 0x000007FF; //// static const UINT32 IN_PTR__shift = 0; //// //// __inline static UINT32 IN_PTR__set( UINT32 w ) { return (w << IN_PTR__shift) & IN_PTR__mask; } //// //// /****/ volatile UINT32 OUT_PTR; //// static const UINT32 OUT_PTR__mask = 0x000007FF; //// static const UINT32 OUT_PTR__shift = 0; //// //// __inline static UINT32 OUT_PTR__set( UINT32 w ) { return (w << OUT_PTR__shift) & OUT_PTR__mask; } //// //// /****/ volatile UINT32 RAM_CONT; //// static const UINT32 RAM_CONT__CPU = 0x00000000; //// static const UINT32 RAM_CONT__MAC = 0x00000001; //// //// /****/ volatile UINT32 CONT; //// static const UINT32 CONT__DONE_ATN = 0x00000001; //// static const UINT32 CONT__DONE_FILT = 0x00000002; //// static const UINT32 CONT__IEN_ATN = 0x00000004; //// static const UINT32 CONT__IEN_FILT = 0x00000008; //// static const UINT32 CONT__DEN_ATN = 0x00000010; //// static const UINT32 CONT__DEN_FILT = 0x00000020; //// static const UINT32 CONT__GO_ATN = 0x00000040; //// static const UINT32 CONT__GO_FILT = 0x00000080; } } ================================================ FILE: Zelig/Zelig/RunTime/DeviceModels/ModelForMM9691LP/HardwareModel/ChipSet/MM9691LP/GPIO.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // namespace Microsoft.DeviceModels.Chipset.MM9691LP { using System; using System.Runtime.CompilerServices; using Microsoft.Zelig.Runtime; [MemoryMappedPeripheral(Base=0x38070000U,Length=0x00000200U)] public class GPIO { [MemoryMappedPeripheral(Base=0x0000U,Length=0x0004U)] public class CW { public const ushort PIN = 0x0001; public const ushort DOUT_IEN = 0x0002; public const ushort RES_DIS = 0x0000; public const ushort RES_EN = 0x0004; public const ushort RES_DIR_PULLDOWN = 0x0000; public const ushort RES_DIR_PULLUP = 0x0008; public const ushort RES_mask = 0x000C; public const ushort MODE_mask = 0x0070; public const ushort MODE_GPIN = 0x0000; public const ushort MODE_GPOUT = 0x0010; public const ushort MODE_ALTA = 0x0020; public const ushort MODE_ALTB = 0x0030; public const ushort MODE_INTRL = 0x0040; public const ushort MODE_INTRH = 0x0050; public const ushort MODE_INTRNE = 0x0060; public const ushort MODE_INTRPE = 0x0070; public const ushort DB_EN = 0x0080; public const ushort INTR_STAT = 0x0100; public const ushort INTR_RAW = 0x0200; [Register(Offset=0x00000000U)] public ushort Data; } [MemoryMappedPeripheral(Base=0x0000U,Length=0x0020U)] public class PIN8 { public const byte DBCLK_SEL__SLOWCLK_DIV_00002 = 0x00; public const byte DBCLK_SEL__SLOWCLK_DIV_00004 = 0x01; public const byte DBCLK_SEL__SLOWCLK_DIV_00008 = 0x02; public const byte DBCLK_SEL__SLOWCLK_DIV_00016 = 0x03; public const byte DBCLK_SEL__SLOWCLK_DIV_00032 = 0x04; public const byte DBCLK_SEL__SLOWCLK_DIV_00064 = 0x05; public const byte DBCLK_SEL__SLOWCLK_DIV_00128 = 0x06; public const byte DBCLK_SEL__SLOWCLK_DIV_00256 = 0x07; public const byte DBCLK_SEL__SLOWCLK_DIV_00512 = 0x08; public const byte DBCLK_SEL__SLOWCLK_DIV_01024 = 0x09; public const byte DBCLK_SEL__SLOWCLK_DIV_02048 = 0x0A; public const byte DBCLK_SEL__SLOWCLK_DIV_04096 = 0x0B; public const byte DBCLK_SEL__SLOWCLK_DIV_08192 = 0x0C; public const byte DBCLK_SEL__SLOWCLK_DIV_16384 = 0x0D; public const byte DBCLK_SEL__SLOWCLK_DIV_32768 = 0x0E; public const byte DBCLK_SEL__SLOWCLK_DIV_65536 = 0x0F; [Register(Offset=0x00000000U)] public byte PIN_DIN8; [Register(Offset=0x00000004U)] public byte DATA_OUT8; [Register(Offset=0x00000008U)] public byte INTR_STAT8; [Register(Offset=0x0000000CU)] public byte INTR_RAW8; [Register(Offset=0x00000010U)] public byte DBCLK_SEL; // only valid in array offset 0 (+0x0110) } public const uint c_Pin_None = 0xFFFFFFFF; public const uint c_Pin_00 = 0; public const uint c_Pin_01 = 1; public const uint c_Pin_02 = 2; public const uint c_Pin_03 = 3; public const uint c_Pin_04 = 4; public const uint c_Pin_05 = 5; public const uint c_Pin_06 = 6; public const uint c_Pin_07 = 7; public const uint c_Pin_08 = 8; public const uint c_Pin_09 = 9; public const uint c_Pin_10 = 10; public const uint c_Pin_11 = 11; public const uint c_Pin_12 = 12; public const uint c_Pin_13 = 13; public const uint c_Pin_14 = 14; public const uint c_Pin_15 = 15; public const uint c_Pin_16 = 16; public const uint c_Pin_17 = 17; public const uint c_Pin_18 = 18; public const uint c_Pin_19 = 19; public const uint c_Pin_20 = 20; public const uint c_Pin_21 = 21; public const uint c_Pin_22 = 22; public const uint c_Pin_23 = 23; public const uint c_Pin_24 = 24; public const uint c_Pin_25 = 25; // 26->31 are not available public const uint c_Pin_32 = 32; public const uint c_Pin_33 = 33; public const uint c_Pin_34 = 34; public const uint c_Pin_35 = 35; public const uint c_Pin_36 = 36; public const uint c_Pin_37 = 37; public const uint c_Pin_38 = 38; public const uint c_Pin_39 = 39; // 40->63 are not available //--// [Register(Offset=0x00000000U,Instances=64)] public CW[] Control; [Register(Offset=0x00000100U,Instances= 8)] public PIN8[] Pin8; // // Helper Methods // [Inline] public uint PinStatus( uint pin ) { return (uint)this.Control[pin].Data & MM9691LP.GPIO.CW.PIN; } // // Access Methods // public static extern GPIO Instance { [SingletonFactory()] [MethodImpl( MethodImplOptions.InternalCall )] get; } } } ================================================ FILE: Zelig/Zelig/RunTime/DeviceModels/ModelForMM9691LP/HardwareModel/ChipSet/MM9691LP/INTC.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // namespace Microsoft.DeviceModels.Chipset.MM9691LP { using System; using System.Runtime.CompilerServices; using Microsoft.Zelig.Runtime; [MemoryMappedPeripheral(Base=0x38000000U,Length=0x00000210U)] public class INTC { public const int IRQ_INDEX_unused0 = 0; public const int IRQ_INDEX_Programmed_Interrupt = 1; public const int IRQ_INDEX_Debug_Channel_Comms_Rx = 2; public const int IRQ_INDEX_Debug_Channel_Comms_Tx = 3; public const int IRQ_INDEX_ARM_Timer_1 = 4; public const int IRQ_INDEX_ARM_Timer_2 = 5; public const int IRQ_INDEX_Versatile_Timer_1 = 6; public const int IRQ_INDEX_Versatile_Timer_2 = 7; public const int IRQ_INDEX_Versatile_Timer_3 = 8; public const int IRQ_INDEX_Versatile_Timer_4 = 9; public const int IRQ_INDEX_Real_Time_Clock = 10; public const int IRQ_INDEX_USB = 11; public const int IRQ_INDEX_USART0_Tx = 12; public const int IRQ_INDEX_USART0_Rx = 13; public const int IRQ_INDEX_USART1_Tx = 14; public const int IRQ_INDEX_USART1_Rx = 15; public const int IRQ_INDEX_GPIO_00_07 = 16; public const int IRQ_INDEX_GPIO_08_15 = 17; public const int IRQ_INDEX_GPIO_16_23 = 18; public const int IRQ_INDEX_GPIO_24_31 = 19; public const int IRQ_INDEX_GPIO_32_39 = 20; public const int IRQ_INDEX_Edge_Detected_Interrupts = 21; public const int IRQ_INDEX_MicroWire = 22; public const int IRQ_INDEX_Watchdog = 23; public const int IRQ_INDEX_USART0_Flow_Control = 24; public const int IRQ_INDEX_USART1_Flow_Control = 25; public const int IRQ_INDEX_unused1 = 26; public const int IRQ_INDEX_APC = 27; public const int IRQ_INDEX_DMA_ALL_Channels = 28; public const int IRQ_INDEX_Viterbi_Processor = 29; public const int IRQ_INDEX_Filter_Processor = 30; public const int IRQ_INDEX_AHB_Write_Error = 31; public const uint IRQ_MASK_unused0 = 1U << IRQ_INDEX_unused0 ; public const uint IRQ_MASK_Programmed_Interrupt = 1U << IRQ_INDEX_Programmed_Interrupt ; public const uint IRQ_MASK_Debug_Channel_Comms_Rx = 1U << IRQ_INDEX_Debug_Channel_Comms_Rx ; public const uint IRQ_MASK_Debug_Channel_Comms_Tx = 1U << IRQ_INDEX_Debug_Channel_Comms_Tx ; public const uint IRQ_MASK_ARM_Timer_1 = 1U << IRQ_INDEX_ARM_Timer_1 ; public const uint IRQ_MASK_ARM_Timer_2 = 1U << IRQ_INDEX_ARM_Timer_2 ; public const uint IRQ_MASK_Versatile_Timer_1 = 1U << IRQ_INDEX_Versatile_Timer_1 ; public const uint IRQ_MASK_Versatile_Timer_2 = 1U << IRQ_INDEX_Versatile_Timer_2 ; public const uint IRQ_MASK_Versatile_Timer_3 = 1U << IRQ_INDEX_Versatile_Timer_3 ; public const uint IRQ_MASK_Versatile_Timer_4 = 1U << IRQ_INDEX_Versatile_Timer_4 ; public const uint IRQ_MASK_Real_Time_Clock = 1U << IRQ_INDEX_Real_Time_Clock ; public const uint IRQ_MASK_USB = 1U << IRQ_INDEX_USB ; public const uint IRQ_MASK_USART0_Tx = 1U << IRQ_INDEX_USART0_Tx ; public const uint IRQ_MASK_USART0_Rx = 1U << IRQ_INDEX_USART0_Rx ; public const uint IRQ_MASK_USART1_Tx = 1U << IRQ_INDEX_USART1_Tx ; public const uint IRQ_MASK_USART1_Rx = 1U << IRQ_INDEX_USART1_Rx ; public const uint IRQ_MASK_GPIO_00_07 = 1U << IRQ_INDEX_GPIO_00_07 ; public const uint IRQ_MASK_GPIO_08_15 = 1U << IRQ_INDEX_GPIO_08_15 ; public const uint IRQ_MASK_GPIO_16_23 = 1U << IRQ_INDEX_GPIO_16_23 ; public const uint IRQ_MASK_GPIO_24_31 = 1U << IRQ_INDEX_GPIO_24_31 ; public const uint IRQ_MASK_GPIO_32_39 = 1U << IRQ_INDEX_GPIO_32_39 ; public const uint IRQ_MASK_Edge_Detected_Interrupts = 1U << IRQ_INDEX_Edge_Detected_Interrupts; public const uint IRQ_MASK_MicroWire = 1U << IRQ_INDEX_MicroWire ; public const uint IRQ_MASK_Watchdog = 1U << IRQ_INDEX_Watchdog ; public const uint IRQ_MASK_USART0_Flow_Control = 1U << IRQ_INDEX_USART0_Flow_Control ; public const uint IRQ_MASK_USART1_Flow_Control = 1U << IRQ_INDEX_USART1_Flow_Control ; public const uint IRQ_MASK_unused1 = 1U << IRQ_INDEX_unused1 ; public const uint IRQ_MASK_APC = 1U << IRQ_INDEX_APC ; public const uint IRQ_MASK_DMA_ALL_Channels = 1U << IRQ_INDEX_DMA_ALL_Channels ; public const uint IRQ_MASK_Viterbi_Processor = 1U << IRQ_INDEX_Viterbi_Processor ; public const uint IRQ_MASK_Filter_Processor = 1U << IRQ_INDEX_Filter_Processor ; public const uint IRQ_MASK_AHB_Write_Error = 1U << IRQ_INDEX_AHB_Write_Error ; public const uint IRQ_MASK_All = 0xFFFFFFFFU; //--// [MemoryMappedPeripheral(Base=0x0000U,Length=0x0020U)] public class IRQ { [Register(Offset=0x00000000U)] public uint Status; [Register(Offset=0x00000004U)] public uint RawStatus; [Register(Offset=0x00000008U)] public uint EnableSet; [Register(Offset=0x0000000CU)] public uint EnableClear; [Register(Offset=0x00000010U)] public uint Soft; [Register(Offset=0x00000014U)] public uint TestSource; [Register(Offset=0x00000018U)] public uint SourceSelect; } [MemoryMappedPeripheral(Base=0x0000U,Length=0x0020U)] public class FIRQ { [Register(Offset=0x00000000U)] public uint Status; [Register(Offset=0x00000004U)] public uint RawStatus; [Register(Offset=0x00000008U)] public uint EnableSet; [Register(Offset=0x0000000CU)] public uint EnableClear; [Register(Offset=0x00000014U)] public uint TestSource; [Register(Offset=0x00000018U)] public uint SourceSelect; [Register(Offset=0x0000001CU)] public int Select; } [Register(Offset=0x00000000U)] public IRQ Irq; [Register(Offset=0x00000020U)] public uint INTOUT_L_EnableSet; [Register(Offset=0x00000024U)] public uint INTOUT_L_EnableClear; [Register(Offset=0x00000100U)] public FIRQ Fiq; [Register(Offset=0x00000200U)] public uint EdgeStatus; [Register(Offset=0x00000204U)] public uint EdgeRawStatus; [Register(Offset=0x00000208U)] public uint EdgeEnable; [Register(Offset=0x0000020CU)] public uint EdgeEnableClear; [Register(Offset=0x00000210U)] public uint EdgeClear; // // Access Methods // public static extern INTC Instance { [SingletonFactory()] [MethodImpl( MethodImplOptions.InternalCall )] get; } } } ================================================ FILE: Zelig/Zelig/RunTime/DeviceModels/ModelForMM9691LP/HardwareModel/ChipSet/MM9691LP/MWSPI.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // namespace Microsoft.DeviceModels.Chipset.MM9691LP { using System; using System.Runtime.CompilerServices; using Microsoft.Zelig.Runtime; [MemoryMappedPeripheral(Base=0x380A0000U,Length=0x00000014U)] public class MWSPI { public enum SPI_CLOCK_RATE { Freq_13800KHZ = 2, // STAN Freq_06900KHZ = 4, Freq_02300KHZ = 12, // ADC7466 Freq_01971KHZ = 14, // AT25HP512 EEPROM Freq_00986KHZ = 28, Freq_00493KHZ = 56, // AT25256 EEPROM Freq_00400KHZ = 69, Freq_00217KHZ = 127, // slowest possible setting } public const uint c_MS1LE = GPIO.c_Pin_07; public const uint c_MSK = GPIO.c_Pin_16; public const uint c_MDIDO = GPIO.c_Pin_17; public const uint c_MDODI = GPIO.c_Pin_18; public const uint c_MSC0LE = GPIO.c_Pin_19; public const ushort MWnCTL1__MWEN = 0x0001; public const ushort MWnCTL1__MNS_SLAVE = 0x0000; public const ushort MWnCTL1__MNS_MASTER = 0x0002; public const ushort MWnCTL1__MOD_8 = 0x0000; public const ushort MWnCTL1__MOD_16 = 0x0004; public const ushort MWnCTL1__ECHO = 0x0008; public const ushort MWnCTL1__EIF = 0x0010; public const ushort MWnCTL1__EIR = 0x0020; public const ushort MWnCTL1__EIW = 0x0040; public const ushort MWnCTL1__SCM_NORMAL = 0x0000; public const ushort MWnCTL1__SCM_ALTERNATE = 0x0080; public const ushort MWnCTL1__SCIDL_MSK0 = 0x0000; public const ushort MWnCTL1__SCIDL_MSK1 = 0x0100; public static ushort MWnCTL1__SCDV__set( uint d ) { return (ushort)((d & 0x7Fu) << 9); } public const ushort MWnSTAT__TBF = 0x0001; public const ushort MWnSTAT__RBF = 0x0002; public const ushort MWnSTAT__OVR = 0x0004; public const ushort MWnSTAT__UDR = 0x0008; public const ushort MWnSTAT__BSY = 0x0010; public const ushort MWnCTL2__EDR = 0x0001; public const ushort MWnCTL2__EDW = 0x0002; public const ushort MWnCTL2__LEE0 = 0x0004; public const ushort MWnCTL2__LEE1 = 0x0008; public const ushort MWnCTL2__LEMD0 = 0x0010; public const ushort MWnCTL2__LEMD1 = 0x0020; public const ushort MWnCTL2__LEPL0 = 0x0040; public const ushort MWnCTL2__LEPL1 = 0x0080; public const ushort MWnCTL2__DTMD_FULL_DUPLEX = 0x0000; public const ushort MWnCTL2__DTMD_READ_ONLY = 0x0100; public const ushort MWnCTL2__DTMD_WRITE_ONLY = 0x0200; public const ushort MWnCTL2__FNCLE = 0x0400; //--// [Register(Offset=0x00000000U)] public ushort MWnDAT; [Register(Offset=0x00000004U)] public ushort MWnCTL1; [Register(Offset=0x00000008U)] public ushort MWnSTAT; [Register(Offset=0x0000000CU)] public ushort MWnCTL2; [Register(Offset=0x00000010U)] public ushort MWnTEST; [Inline] public bool TransmitBufferFull() { return (MWnSTAT & MWnSTAT__TBF) != 0; } [Inline] public bool ReceiveBufferEmpty() { return (MWnSTAT & MWnSTAT__RBF) == 0; } [Inline] public bool ShiftBufferEmpty() { return (MWnSTAT & MWnSTAT__BSY) == 0; } public static uint ConvertClockRateToDivisor( uint Clock_RateKHz ) { const uint SYSTEM_CLOCK_HZ = 27600000; const uint SYSTEM_CLOCK_KHZ = SYSTEM_CLOCK_HZ / 1000; if (Clock_RateKHz >= SYSTEM_CLOCK_KHZ ) return 0; else if(Clock_RateKHz >= SYSTEM_CLOCK_KHZ / (uint)SPI_CLOCK_RATE.Freq_13800KHZ) return (uint)SPI_CLOCK_RATE.Freq_13800KHZ; else if(Clock_RateKHz >= SYSTEM_CLOCK_KHZ / (uint)SPI_CLOCK_RATE.Freq_06900KHZ) return (uint)SPI_CLOCK_RATE.Freq_06900KHZ; else if(Clock_RateKHz >= SYSTEM_CLOCK_KHZ / (uint)SPI_CLOCK_RATE.Freq_02300KHZ) return (uint)SPI_CLOCK_RATE.Freq_02300KHZ; else if(Clock_RateKHz >= SYSTEM_CLOCK_KHZ / (uint)SPI_CLOCK_RATE.Freq_01971KHZ) return (uint)SPI_CLOCK_RATE.Freq_01971KHZ; else if(Clock_RateKHz >= SYSTEM_CLOCK_KHZ / (uint)SPI_CLOCK_RATE.Freq_00986KHZ) return (uint)SPI_CLOCK_RATE.Freq_00986KHZ; else if(Clock_RateKHz >= SYSTEM_CLOCK_KHZ / (uint)SPI_CLOCK_RATE.Freq_00493KHZ) return (uint)SPI_CLOCK_RATE.Freq_00493KHZ; else if(Clock_RateKHz >= SYSTEM_CLOCK_KHZ / (uint)SPI_CLOCK_RATE.Freq_00400KHZ) return (uint)SPI_CLOCK_RATE.Freq_00400KHZ; else return (uint)SPI_CLOCK_RATE.Freq_00217KHZ; } //--// public class SPI_CONFIGURATION { public uint DeviceCS; public bool CS_Active; // False = LOW active, TRUE = HIGH active public bool MSK_IDLE; // False = LOW during idle, TRUE = HIGH during idle public bool MSK_SampleEdge; // False = sample falling edge, TRUE = samples on rising public bool MD_16bits; public uint Clock_RateKHz; public uint CS_Setup_uSecs; public uint CS_Hold_uSecs; public uint SPI_mod; } // only used in 1 place in RTM builds, so inline this for quicker access public static ushort ConfigurationToMode( SPI_CONFIGURATION Configuration ) { ushort Mode; Mode = MWnCTL1__MWEN | MWnCTL1__MNS_MASTER; if(Configuration.MD_16bits) { Mode |= MWnCTL1__MOD_16; } else { Mode |= MWnCTL1__MOD_8; } if(Configuration.MSK_IDLE) { Mode |= MWnCTL1__SCIDL_MSK1; } else { Mode |= MWnCTL1__SCIDL_MSK0; } if(Configuration.MSK_SampleEdge) { Mode |= MWnCTL1__SCM_NORMAL; // sample on rising edge } else { Mode |= MWnCTL1__SCM_ALTERNATE; // sample on falling edge } Mode |= MWnCTL1__SCDV__set( ConvertClockRateToDivisor( Configuration.Clock_RateKHz )); return Mode; } // // Access Methods // public static extern MWSPI Instance { [SingletonFactory()] [MethodImpl( MethodImplOptions.InternalCall )] get; } } } ================================================ FILE: Zelig/Zelig/RunTime/DeviceModels/ModelForMM9691LP/HardwareModel/ChipSet/MM9691LP/PCU.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // namespace Microsoft.DeviceModels.Chipset.MM9691LP { using System; using System.Runtime.CompilerServices; using Microsoft.Zelig.Runtime; [MemoryMappedPeripheral(Base=0x380E0000U,Length=0x00000020U)] public class PCU { public const uint PCU_STATUS__LN2 = 0x00000040; public const uint PCU_STATUS__LN1 = 0x00000020; public const uint PCU_STATUS__SW1 = 0x00000010; public const uint PCU_STATUS__OTHER = 0x00000008; public const uint PCU_STATUS__RESET = 0x00000004; public const uint PCU_STATUS__DEAD = 0x00000002; public const uint PCU_STATUS__OFF = 0x00000001; [Register(Offset=0x00000000U)] public uint CLR_SW1; [Register(Offset=0x00000004U)] public uint SET_SW1; [Register(Offset=0x00000008U)] public uint CLR_LN1; [Register(Offset=0x0000000CU)] public uint SET_LN1; [Register(Offset=0x00000010U)] public uint CLR_LN2; [Register(Offset=0x00000014U)] public uint SET_LN2; [Register(Offset=0x00000018U)] public uint SW_RESET; [Register(Offset=0x0000001CU)] public uint PCU_STATUS; [Register(Offset=0x00000020U)] public byte CLR_SW1_CNT; [Register(Offset=0x00000024U)] public byte SET_SW1_CNT; [Register(Offset=0x00000028U)] public byte CLR_LN1_CNT; [Register(Offset=0x0000002CU)] public byte SET_LN1_CNT; [Register(Offset=0x00000030U)] public byte CLR_LN2_CNT; [Register(Offset=0x00000034U)] public byte SET_LN2_CNT; // // Access Methods // public static extern PCU Instance { [SingletonFactory()] [MethodImpl( MethodImplOptions.InternalCall )] get; } } } ================================================ FILE: Zelig/Zelig/RunTime/DeviceModels/ModelForMM9691LP/HardwareModel/ChipSet/MM9691LP/REMAP_PAUSE.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // namespace Microsoft.DeviceModels.Chipset.MM9691LP { using System; using System.Runtime.CompilerServices; using Microsoft.Zelig.Runtime; [MemoryMappedPeripheral(Base=0x38010000U,Length=0x0000005CU)] public class REMAP_PAUSE { public const uint CacheableAddressMask = 0x80000000; public const uint CacheFlushAddressMask = 0x40000000; public const uint ResetStatus__POR = 0x00000001; [BitFieldPeripheral(PhysicalType=typeof(uint))] public struct SystemConfigurationBitField { [BitFieldRegister(Position=0)] public bool SSPEN ; // Short Circuit Protection for USB Transceiver. [BitFieldRegister(Position=1)] public bool SW_FRZ_EN ; // Software Freeze Enable. [BitFieldRegister(Position=2)] public bool SW_FRZ ; // Software Freeze. [BitFieldRegister(Position=3)] public bool PU_DIS ; // Pullup Disable. [BitFieldRegister(Position=4)] public bool PLL_TST_EN; // PLL Test Enable. } //--// [Register(Offset=0x00000000U)] public uint Pause_AHB; [Register(Offset=0x00000004U)] public uint Pause_CPU; [Register(Offset=0x00000010U)] public uint Identification; [Register(Offset=0x00000020U)] public uint ClearResetMap; [Register(Offset=0x00000030U)] public uint ResetStatus; [Register(Offset=0x00000034U)] public uint ResetStatusClear; [Register(Offset=0x00000040U)] public SystemConfigurationBitField SystemConfiguration; [Register(Offset=0x00000050U)] public uint Cache_Enable; [Register(Offset=0x00000054U)] public uint Cache_Tags_Reset; [Register(Offset=0x00000058U)] public uint Cache_Flush_Enable; // // Helper Methods // [Inline] [DisableNullChecks] public unsafe void InitializeCache() { // // cache initialization (see 2.2.12 usage guidelines pp 68) // this.Cache_Tags_Reset = 0; byte* tagPtr = (byte*)0; for(int i = 0; i <= 256; i++, tagPtr += 1 << 4) { *tagPtr = 0; } this.Cache_Tags_Reset = 1; this.Cache_Enable = 1; this.Cache_Flush_Enable = 1; } // // Access Methods // public static extern REMAP_PAUSE Instance { [SingletonFactory()] [MethodImpl( MethodImplOptions.InternalCall )] get; } } } ================================================ FILE: Zelig/Zelig/RunTime/DeviceModels/ModelForMM9691LP/HardwareModel/ChipSet/MM9691LP/RTC.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // namespace Microsoft.DeviceModels.Chipset.MM9691LP { using System; using System.Runtime.CompilerServices; using Microsoft.Zelig.Runtime; [MemoryMappedPeripheral(Base=0x380C0000U,Length=0x00000020U)] public class RTC { public const uint WDCTL__DIS = 0x00000000; public const uint WDCTL__EN = 0x00000001; public const uint WDCTL__LK = 0x00000002; public const uint WDCTL__IEN = 0x00000004; public const uint WDCTL__REN = 0x00000008; public const uint WDCTL__WDOG_PIN_DISABLED = 0x00000000; public const uint WDCTL__WDOG_PIN_ACTIVE = 0x00000010; public const uint WDCTL__WDOG_PIN_OPEN_DRAIN = 0x00000020; public const uint WDCTL__WDOG_PIN_OPEN_DRAIN_PULLUP = 0x00000030; public const uint WDDLY__RESET_CLOCK_DELAY = 512; public const uint WDDLY__READ_HREG = 12; public const uint WDRST__KEY = 0x0000005C; //--// [Register(Offset=0x00000000U)] public ulong HREG; [Register(Offset=0x00000008U)] public ulong COMP; [Register(Offset=0x00000010U)] public uint LD_HREG; [Register(Offset=0x00000014U)] public uint WDCTL; [Register(Offset=0x00000018U)] public uint WDDLY; [Register(Offset=0x0000001CU)] public uint WDRST; // // Access Methods // public static extern RTC Instance { [SingletonFactory()] [MethodImpl( MethodImplOptions.InternalCall )] get; } } } ================================================ FILE: Zelig/Zelig/RunTime/DeviceModels/ModelForMM9691LP/HardwareModel/ChipSet/MM9691LP/SECURITYKEY.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // namespace Microsoft.DeviceModels.Chipset.MM9691LP { using System; using System.Runtime.CompilerServices; using Microsoft.Zelig.Runtime; [MemoryMappedPeripheral(Base=0x38090000U,Length=0x00000080U)] public class SECURITYKEY { [MemoryMappedPeripheral(Base=0x0000U,Length=0x0004U)] public class BYTE { [Register(Offset=0x00000000U)] public byte Data8; } //--// [Register(Offset=0x00000000U,Instances=32)] public BYTE[] Key; // // Access Methods // public static extern SECURITYKEY Instance { [SingletonFactory()] [MethodImpl( MethodImplOptions.InternalCall )] get; } } } ================================================ FILE: Zelig/Zelig/RunTime/DeviceModels/ModelForMM9691LP/HardwareModel/ChipSet/MM9691LP/USART0.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // namespace Microsoft.DeviceModels.Chipset.MM9691LP { using System; using System.Runtime.CompilerServices; using Microsoft.Zelig.Runtime; [MemoryMappedPeripheral(Base=0x38040000U,Length=0x00010000U)] public class USART0 : USARTx { // // Helper Methods // public static USARTx Initialize( ref BaseSerialStream.Configuration cfg ) { USART0 usart = Instance; return usart.Initialize( 0, ref cfg ) ? usart : null; } // // Access Methods // public static extern USART0 Instance { [SingletonFactory()] [MethodImpl( MethodImplOptions.InternalCall )] get; } } } ================================================ FILE: Zelig/Zelig/RunTime/DeviceModels/ModelForMM9691LP/HardwareModel/ChipSet/MM9691LP/USART1.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // namespace Microsoft.DeviceModels.Chipset.MM9691LP { using System; using System.Runtime.CompilerServices; using Microsoft.Zelig.Runtime; [MemoryMappedPeripheral(Base=0x38050000U,Length=0x00010000U)] public class USART1 : USARTx { // // Helper Methods // public static USARTx Initialize( ref BaseSerialStream.Configuration cfg ) { USART1 usart = Instance; return usart.Initialize( 1, ref cfg ) ? usart : null; } // // Access Methods // public static extern USART1 Instance { [SingletonFactory()] [MethodImpl( MethodImplOptions.InternalCall )] get; } } } ================================================ FILE: Zelig/Zelig/RunTime/DeviceModels/ModelForMM9691LP/HardwareModel/ChipSet/MM9691LP/USARTx.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // namespace Microsoft.DeviceModels.Chipset.MM9691LP { using System; using System.Runtime.CompilerServices; using Microsoft.Zelig.Runtime; [MemoryMappedPeripheral] public abstract class USARTx { public class ComputeBaudRates { static void ComputeBestFit( int clockFrequency, int baudRate, out double bestBaudRate, out int bestO, out int bestN, out int bestP ) { double bestError = baudRate; bestBaudRate = 0; bestO = 0; bestN = 0; bestP = 0; for(int O = 16; O >= 7; O--) { for(int P = 2; P <= 32; P++) { for(int N = 1; N < 1 << 11; N++) { double newBaudRate = clockFrequency * 2.0 / (O * N * P); double error = Math.Abs( newBaudRate - baudRate ); if(error < bestError) { bestBaudRate = newBaudRate; bestError = error; bestO = O; bestN = N; bestP = P; } } } } } public static void BuildTable( int clockFrequency ) { foreach(var baudRate in new int[] { 300, 600, 1200, 1800, 2000, 2400, 3600, 4800, 7200, 9600, 14400, 19200, 38400, 56000, 115200, 128000, 230400, 345600, 460800 }) { double bestBaudRate; int bestO; int bestN; int bestP; ComputeBestFit( clockFrequency, baudRate, out bestBaudRate, out bestO, out bestN, out bestP ); Console.WriteLine( "BaudRate={0} => O={1} N={2} P={3} error = {4,4:F2}%", baudRate, bestO, bestN, bestP / 2.0, Math.Abs( bestBaudRate - baudRate ) * 100.0 / baudRate ); } } } //--// const uint SER1_CLKX = GPIO.c_Pin_00; const uint SER1_TDX = GPIO.c_Pin_01; const uint SER1_RDX = GPIO.c_Pin_02; const uint SER1_RTS = GPIO.c_Pin_03; const uint SER1_CTS = GPIO.c_Pin_04; const uint SER2_CLKX = GPIO.c_Pin_08; const uint SER2_TDX = GPIO.c_Pin_09; const uint SER2_RDX = GPIO.c_Pin_10; const uint SER2_RTS = GPIO.c_Pin_11; const uint SER2_CTS = GPIO.c_Pin_12; //--// public const byte UnICTRL__TBE = 0x01; public const byte UnICTRL__RBF = 0x02; public const byte UnICTRL__DCTS = 0x04; public const byte UnICTRL__CTS = 0x08; public const byte UnICTRL__EFCI = 0x10; public const byte UnICTRL__ETI = 0x20; public const byte UnICTRL__ERI = 0x40; public const byte UnICTRL__EEI = 0x80; public const byte UnICTRL__mask = (UnICTRL__EFCI | UnICTRL__ETI | UnICTRL__ERI | UnICTRL__EEI); public const byte UnSTAT__PE = 0x01; public const byte UnSTAT__FE = 0x02; public const byte UnSTAT__DOE = 0x04; public const byte UnSTAT__ERR = 0x08; public const byte UnSTAT__BKD = 0x10; public const byte UnSTAT__RB9 = 0x20; public const byte UnSTAT__XMIP = 0x40; public const byte UnFRS__CHAR_8 = 0x00; public const byte UnFRS__CHAR_7 = 0x01; public const byte UnFRS__CHAR_9 = 0x02; public const byte UnFRS__CHAR_9_LOOPBACK = 0x03; public const byte UnFRS__STP_1 = 0x00; public const byte UnFRS__STP_2 = 0x04; public const byte UnFRS__XB9_0 = 0x00; public const byte UnFRS__XB9_1 = 0x08; public const byte UnFRS__PSEL_ODD = 0x00; public const byte UnFRS__PSEL_EVEN = 0x10; public const byte UnFRS__PSEL_MARK = 0x20; public const byte UnFRS__PSEL_SPACE = 0x30; public const byte UnFRS__PEN_DISABLED = 0x00; public const byte UnFRS__PEN_ENABLED = 0x40; public const byte UnMDSL1__MOD = 0x01; public const byte UnMDSL1__ATN = 0x02; public const byte UnMDSL1__BRK = 0x04; public const byte UnMDSL1__CKS = 0x08; public const byte UnMDSL1__ETD = 0x10; public const byte UnMDSL1__ERD = 0x20; public const byte UnMDSL1__FCE = 0x40; public const byte UnMDSL1__RTS = 0x80; public static byte UnBAUD__set ( uint a ) { return (byte) ((a-1) & 0x00FF) ; } public static byte UnPSR__DIV__set( uint a ) { return (byte)(((a-1) & 0x0700) >> 8); } public static byte UnPSR__PSC__set( uint a ) { return (byte)(( a & 0x001F) << 3); } public const byte UnPSR__1 = 1; public const byte UnPSR__1p5 = 2; public const byte UnPSR__2 = 3; public const byte UnPSR__2p5 = 4; public const byte UnPSR__3 = 5; public const byte UnPSR__3p5 = 6; public const byte UnPSR__4 = 7; public const byte UnPSR__4p5 = 8; public const byte UnPSR__5 = 9; public const byte UnPSR__5p5 = 10; public const byte UnPSR__6 = 11; public const byte UnPSR__6p5 = 12; public const byte UnPSR__7 = 13; public const byte UnPSR__7p5 = 14; public const byte UnPSR__8 = 15; public const byte UnPSR__8p5 = 16; public const byte UnPSR__9 = 17; public const byte UnPSR__9p5 = 18; public const byte UnPSR__10 = 19; public const byte UnPSR__10p5 = 20; public const byte UnPSR__11 = 21; public const byte UnPSR__11p5 = 22; public const byte UnPSR__12 = 23; public const byte UnPSR__12p5 = 24; public const byte UnPSR__13 = 25; public const byte UnPSR__13p5 = 26; public const byte UnPSR__14 = 27; public const byte UnPSR__14p5 = 28; public const byte UnPSR__15 = 29; public const byte UnPSR__15p5 = 30; public const byte UnPSR__16 = 31; public const byte UnOVSR__7 = 0x07; public const byte UnOVSR__8 = 0x08; public const byte UnOVSR__9 = 0x09; public const byte UnOVSR__10 = 0x0A; public const byte UnOVSR__11 = 0x0B; public const byte UnOVSR__12 = 0x0C; public const byte UnOVSR__13 = 0x0D; public const byte UnOVSR__14 = 0x0E; public const byte UnOVSR__15 = 0x0F; public const byte UnOVSR__16 = 0x00; public static byte UnOVSR__set( uint a ) { return (byte)(a & 0x0F); } public const byte UnMDSL2__SMD = 0x01; //--// [Register(Offset=0x00000000U)] public byte UnTBUF; // Read/Write [Register(Offset=0x00000004U)] public byte UnRBUF; // Read Only [Register(Offset=0x00000008U)] public byte UnICTRL = UnICTRL__TBE; [Register(Offset=0x0000000CU)] public byte UnSTAT; [Register(Offset=0x00000010U)] public byte UnFRS; [Register(Offset=0x00000014U)] public byte UnMDSL1; [Register(Offset=0x00000018U)] public byte UnBAUD; [Register(Offset=0x0000001CU)] public byte UnPSR; [Register(Offset=0x00000020U)] public byte UnOVSR; [Register(Offset=0x00000024U)] public byte UnMDSL2; [Register(Offset=0x00000028U)] public byte UnSPOS; // // Helper Methods // protected bool Initialize( int usartNum , int baudrate ) { var cfg = new BaseSerialStream.Configuration( null ) { BaudRate = baudrate, DataBits = 8, Parity = System.IO.Ports.Parity.None, StopBits = System.IO.Ports.StopBits.One, }; return Initialize( usartNum, ref cfg ); } protected bool Initialize( int usartNum , ref BaseSerialStream.Configuration cfg ) { uint OversampleRate; uint Divisor; uint Prescaler; if(Configuration.CoreClockFrequency == 26000000) { // BaudRate=300 => O=16 N=471 P=11.5 error = 0.00% // BaudRate=600 => O=12 N=314 P=11.5 error = 0.00% // BaudRate=1200 => O=12 N=157 P=11.5 error = 0.00% // BaudRate=1800 => O=8 N=157 P=11.5 error = 0.00% // BaudRate=2000 => O=16 N=325 P=2.5 error = 0.00% // BaudRate=2400 => O=7 N=619 P=2.5 error = 0.01% // BaudRate=3600 => O=15 N=321 P=1.5 error = 0.00% // BaudRate=4800 => O=8 N=677 P=1 error = 0.01% // BaudRate=7200 => O=14 N=258 P=1 error = 0.02% // BaudRate=9600 => O=14 N=129 P=1.5 error = 0.02% // BaudRate=14400 => O=14 N=129 P=1 error = 0.02% // BaudRate=19200 => O=9 N=43 P=3.5 error = 0.02% // BaudRate=38400 => O=11 N=41 P=1.5 error = 0.09% // BaudRate=56000 => O=16 N=29 P=1 error = 0.06% // BaudRate=115200 => O=15 N=15 P=1 error = 0.31% // BaudRate=128000 => O=14 N=1 P=14.5 error = 0.06% // BaudRate=230400 => O=15 N=5 P=1.5 error = 0.31% // BaudRate=345600 => O=15 N=5 P=1 error = 0.31% // BaudRate=460800 => O=16 N=1 P=3.5 error = 0.76% switch(cfg.BaudRate) { case 1200: OversampleRate = UnOVSR__12; Divisor = 157; Prescaler = UnPSR__11p5; break; case 2400: OversampleRate = UnOVSR__7 ; Divisor = 619; Prescaler = UnPSR__2p5 ; break; case 4800: OversampleRate = UnOVSR__8 ; Divisor = 677; Prescaler = UnPSR__1 ; break; case 9600: OversampleRate = UnOVSR__14; Divisor = 129; Prescaler = UnPSR__1p5 ; break; case 19200: OversampleRate = UnOVSR__9 ; Divisor = 43 ; Prescaler = UnPSR__3p5 ; break; case 38400: OversampleRate = UnOVSR__11; Divisor = 41 ; Prescaler = UnPSR__1p5 ; break; case 57600: OversampleRate = UnOVSR__16; Divisor = 29 ; Prescaler = UnPSR__1 ; break; case 115200: OversampleRate = UnOVSR__15; Divisor = 15 ; Prescaler = UnPSR__1 ; break; case 230400: OversampleRate = UnOVSR__15; Divisor = 5 ; Prescaler = UnPSR__1p5 ; break; case 460800: OversampleRate = UnOVSR__16; Divisor = 1 ; Prescaler = UnPSR__3p5 ; break; default: return false; } } else if (Configuration.CoreClockFrequency == 30000000) { //BaudRate=300 => O=16 N=1250 P=5 error = 0.00% //BaudRate=600 => O=16 N=1250 P=2.5 error = 0.00% //*BaudRate=1200 => O=16 N=625 P=2.5 error = 0.00% //BaudRate=1800 => O=13 N=1282 P=1 error = 0.00% //BaudRate=2000 => O=16 N=625 P=1.5 error = 0.00% //*BaudRate=2400 => O=10 N=1250 P=1 error = 0.00% //BaudRate=3600 => O=13 N=641 P=1 error = 0.00% //*BaudRate=4800 => O=10 N=625 P=1 error = 0.00% //BaudRate=7200 => O=9 N=463 P=1 error = 0.01% //*BaudRate=9600 => O=10 N=125 P=2.5 error = 0.00% //BaudRate=14400 => O=7 N=119 P=2.5 error = 0.04% //*BaudRate=19200 => O=11 N=142 P=1 error = 0.03% //*BaudRate=38400 => O=11 N=71 P=1 error = 0.03% //*BaudRate=56000 => O=9 N=17 P=3.5 error = 0.04% //**BaudRate=57600 => O=16 N=13 P=2.5 error = 0.16% //*BaudRate=115200 => O=13 N=20 P=1 error = 0.16% //BaudRate=128000 => O=13 N=18 P=1 error = 0.16% //*BaudRate=230400 => O=13 N=10 P=1 error = 0.16% //BaudRate=345600 => O=7 N=5 P=2.5 error = 0.79% //*BaudRate=460800 => O=13 N=5 P=1 error = 0.16% switch (cfg.BaudRate) { case 1200: OversampleRate = UnOVSR__16; Divisor = 625; Prescaler = UnPSR__2p5; break; case 2400: OversampleRate = UnOVSR__10; Divisor = 1250; Prescaler = UnPSR__1; break; case 4800: OversampleRate = UnOVSR__10; Divisor = 625; Prescaler = UnPSR__1; break; case 9600: OversampleRate = UnOVSR__10; Divisor = 125; Prescaler = UnPSR__2p5; break; case 19200: OversampleRate = UnOVSR__11; Divisor = 142; Prescaler = UnPSR__1; break; case 38400: OversampleRate = UnOVSR__11; Divisor = 71; Prescaler = UnPSR__1; break; //case 57600: OversampleRate = UnOVSR__9; Divisor = 17; Prescaler = UnPSR__3p5; break; case 57600: OversampleRate = UnOVSR__16; Divisor = 13; Prescaler = UnPSR__2p5; break; case 115200: OversampleRate = UnOVSR__13; Divisor = 20; Prescaler = UnPSR__1; break; case 230400: OversampleRate = UnOVSR__13; Divisor = 10; Prescaler = UnPSR__1; break; case 460800: OversampleRate = UnOVSR__13; Divisor = 5; Prescaler = UnPSR__1; break; default: return false; } } else { return false; } //--// byte frs = 0; switch(cfg.DataBits) { case 7: frs |= UnFRS__CHAR_7; break; case 8: frs |= UnFRS__CHAR_8; break; default: return false; } switch(cfg.StopBits) { case System.IO.Ports.StopBits.One: frs |= UnFRS__STP_1; break; case System.IO.Ports.StopBits.Two: frs |= UnFRS__STP_2; break; default: return false; } if(cfg.Parity != System.IO.Ports.Parity.None) { frs |= UnFRS__PEN_ENABLED; switch(cfg.Parity) { case System.IO.Ports.Parity.Even: frs |= UnFRS__PSEL_EVEN; break; case System.IO.Ports.Parity.Odd: frs |= UnFRS__PSEL_ODD; break; default: return false; } } else { frs |= UnFRS__PEN_DISABLED; } GPIO gpio = GPIO.Instance; CMU.Instance.EnableClock( usartNum == 0 ? CMU.MCLK_EN__USART0 : CMU.MCLK_EN__USART1 ); gpio.Control[usartNum == 0 ? SER1_TDX : SER2_TDX].Data = GPIO.CW.MODE_ALTA | GPIO.CW.RES_DIS; gpio.Control[usartNum == 0 ? SER1_RDX : SER2_RDX].Data = GPIO.CW.MODE_ALTA | GPIO.CW.RES_DIS; this.UnFRS = frs; this.UnMDSL1 = 0; this.UnMDSL2 = 0; this.UnOVSR = UnOVSR__set ( OversampleRate ); this.UnPSR = (byte)(UnPSR__DIV__set( Divisor ) | UnPSR__PSC__set( Prescaler )); this.UnBAUD = UnBAUD__set ( Divisor ); this.UnICTRL = (byte)((this.UnICTRL & UnICTRL__mask) | UnICTRL__ETI | UnICTRL__ERI); return true; } } } ================================================ FILE: Zelig/Zelig/RunTime/DeviceModels/ModelForMM9691LP/HardwareModel/ChipSet/MM9691LP/USB.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // namespace Microsoft.DeviceModels.Chipset.MM9691LP { using System; using System.Runtime.CompilerServices; using Microsoft.Zelig.Runtime; [MemoryMappedPeripheral(Base=0x38060000U,Length=0x00000100U)] public class USB { //// struct ENDPNT //// { //// /****/ volatile UINT8 EPCT; //// // for EP0 //// static const UINT8 EPCT__EPC0_MASK = 0xDF; //// static const UINT8 EPCT__EPC0_EP = 0x0F; //// static const UINT8 USB_SETUP_FIX_DIS = 0x10; //// //// static const UINT8 EPCT__EPC0_DEF = 0x40; //// static const UINT8 EPCT__EPC0_STALL = 0x80; //// // for EP1-3 //// static const UINT8 EPCT__EPC_MASK = 0xBF; //// static const UINT8 EPCT__EPC_EP = 0x0F; //// static const UINT8 EPCT__EPC_EP_EN = 0x10; //// static const UINT8 EPCT__EPC_ISO = 0x20; //// static const UINT8 EPCT__EPC_STALL = 0x80; //// /*************/ UINT8 padding1[3]; //// //// /****/ volatile UINT8 TXD; //// static const UINT8 TXD__mask = 0xFF; //// /*************/ UINT8 padding2[3]; //// //// /****/ volatile UINT8 TXS; //// // for EP0 //// static const UINT8 TXS__TXS0_MASK = 0x6F; //// static const UINT8 TXS__TXS0_TCOUNT = 0x0F; //// static const UINT8 TXS__TXS0_TX_DONE = 0x20; //// static const UINT8 TXS__TXS0_ACK_STAT = 0x40; //// // for EP1-3 //// static const UINT8 TXS__TXS_MASK = 0xFF; //// static const UINT8 TXS__TXS_TCOUNT = 0x1F; //// static const UINT8 TXS__TXS_TX_DONE = 0x20; //// static const UINT8 TXS__TXS_ACK_STAT = 0x40; //// static const UINT8 TXS__TXS_TX_URUN = 0x80; //// /*************/ UINT8 padding3[3]; //// //// /****/ volatile UINT8 TXC; //// // for EP0 //// static const UINT8 TXC__TXC0_MASK = 0x14; //// static const UINT8 TXC__TXC0_TX_EN = 0x01; //// static const UINT8 TXC__TXC0_TOGGLE = 0x04; //// static const UINT8 TXC__TXC0_FLUSH = 0x08; //// static const UINT8 TXC__TXC0_IGN_IN = 0x10; //// // for EP1-3 //// static const UINT8 TXC__TXC_MASK = 0xE4; //// static const UINT8 TXC__TXC_TX_EN = 0x01; //// static const UINT8 TXC__TXC_LAST = 0x02; //// static const UINT8 TXC__TXC_TOGGLE = 0x04; //// static const UINT8 TXC__TXC_FLUSH = 0x08; //// static const UINT8 TXC__TXC_RFF = 0x10; //// static const UINT8 TXC__TXC_TFWL = 0x60; //// static const UINT8 TXC__TXC_IGN_ISOMSK = 0x80; //// /*************/ UINT8 padding4[3]; //// //// /****/ volatile UINT8 EPCR; // EPCR use EPCT macro //// /*************/ UINT8 padding5[3]; //// //// /****/ volatile UINT8 RXD; //// static const UINT8 RXD__mask = 0xFF; //// /*************/ UINT8 padding6[3]; //// //// /****/ volatile UINT8 RXS; //// // for EP0 //// static const UINT8 RXS__RXS0_MASK = 0x7F; //// static const UINT8 RXS__RXS0_RCOUNT = 0x0F; //// static const UINT8 RXS__RXS0_RX_LAST = 0x10; //// static const UINT8 RXS__RXS0_TOGGLE = 0x20; //// static const UINT8 RXS__RXS0_SETUP = 0x40; //// // for EP1-3 //// static const UINT8 RXS__RXS_MASK = 0xFF; //// static const UINT8 RXS__RXS_RCOUNT = 0x0F; //// static const UINT8 RXS__RXS_RX_LAST = 0x10; //// static const UINT8 RXS__RXS_TOGGLE = 0x20; //// static const UINT8 RXS__RXS_SETUP = 0x40; //// static const UINT8 RXS__RXS_RX_ERR = 0x80; //// /*************/ UINT8 padding7[3]; //// //// /****/ volatile UINT8 RXC; //// // for EP0 //// static const UINT8 RXC__RXC0_MASK = 0x06; //// static const UINT8 RXC__RXC0_RX_EN = 0x01; //// static const UINT8 RXC__RXC0_IGN_OUT = 0x02; //// static const UINT8 RXC__RXC0_IGN_SETUP = 0x04; //// static const UINT8 RXC__RXC0_FLUSH = 0x08; //// // for EP1-3 //// static const UINT8 RXC__RXC_MASK = 0x64; //// static const UINT8 RXC__RXC_RX_EN = 0x01; //// static const UINT8 RXC__RXC_IGN_SETUP = 0x04; //// static const UINT8 RXC__RXC_FLUSH = 0x08; //// static const UINT8 RXC__RXC_RFWL = 0x60; //// /*************/ UINT8 padding8[3]; //// }; //// //// //--// //// //// static const UINT32 c_Base = 0xB8060000; //// //// //--// //// //// /****/ volatile UINT8 MCNTRL; //// static const UINT8 MCNTRL__MASK = 0x09; //// static const UINT8 MCNTRL__USBEN = 0x01; //// static const UINT8 MCNTRL__DBG = 0x02; //// static const UINT8 MCNTRL__NAT = 0x08; //// /*************/ UINT8 Padding1[3]; //// //// /****/ volatile UINT8 XCVRDIAG; //// /*************/ UINT8 Padding2[3]; //// //// /****/ volatile UINT8 TCR; //// /*************/ UINT8 Padding3[3]; //// //// /****/ volatile UINT8 UTR; //// /*************/ UINT8 Padding4[3]; //// //// /****/ volatile UINT8 FAR_; //// static const UINT8 FAR__FAR_MASK = 0xFF; //// static const UINT8 FAR__FAR_AD = 0x7F; //// static const UINT8 FAR__FAR_AD_EN = 0x80; //// /*************/ UINT8 Padding5[3]; //// //// /****/ volatile UINT8 NFSR; //// static const UINT8 NFSR__STATE_NODE_MASK = 0x03; //// static const UINT8 NFSR__STATE_NODE_RESET = 0x00; //// static const UINT8 NFSR__STATE_NODE_RESUME = 0x01; //// static const UINT8 NFSR__STATE_NODE_OPERATIONAL = 0x02; //// static const UINT8 NFSR__STATE_NODE_SUSPEND = 0x03; //// /*************/ UINT8 Padding6[3]; //// //// /****/ volatile UINT8 MAEV; //// static const UINT8 MAEV__MASK = 0xFF; //// static const UINT8 MAEV__WARN = 0x01; //// static const UINT8 MAEV__ALT = 0x02; //// static const UINT8 MAEV__TX_EV = 0x04; //// static const UINT8 MAEV__FRAME = 0x08; //// static const UINT8 MAEV__NAK = 0x10; //// static const UINT8 MAEV__ULD = 0x20; //// static const UINT8 MAEV__RX_EV = 0x40; //// static const UINT8 MAEV__INTR = 0x80; //// /*************/ UINT8 Padding7[3]; //// //// /****/ volatile UINT8 MAMSK; //// static const UINT8 MAMSK__MASK = 0xFF; //// static const UINT8 MAMSK__WARN = 0x01; //// static const UINT8 MAMSK__ALT = 0x02; //// static const UINT8 MAMSK__TX_EV = 0x04; //// static const UINT8 MAMSK__FRAME = 0x08; //// static const UINT8 MAMSK__NAK = 0x10; //// static const UINT8 MAMSK__ULD = 0x20; //// static const UINT8 MAMSK__RX_EV = 0x40; //// static const UINT8 MAMSK__INTR = 0x80; //// /*************/ UINT8 Padding8[3]; //// //// /****/ volatile UINT8 ALTEV; //// static const UINT8 ALTEV__MASK = 0xFC; //// static const UINT8 ALTEV__DMA = 0x04; //// static const UINT8 ALTEV__EOP = 0x08; //// static const UINT8 ALTEV__SD3 = 0x10; //// static const UINT8 ALTEV__SD5 = 0x20; //// static const UINT8 ALTEV__RESET = 0x40; //// static const UINT8 ALTEV__RESUME = 0x80; //// /*************/ UINT8 Padding9[3]; //// //// /****/ volatile UINT8 ALTMSK; //// static const UINT8 ALTMSK__MASK = 0xFC; //// static const UINT8 ALTMSK__DMA = 0x04; //// static const UINT8 ALTMSK__EOP = 0x08; //// static const UINT8 ALTMSK__SD3 = 0x10; //// static const UINT8 ALTMSK__SD5 = 0x20; //// static const UINT8 ALTMSK__RESET = 0x40; //// static const UINT8 ALTMSK__RESUME = 0x80; //// /*************/ UINT8 Padding10[3]; //// //// /****/ volatile UINT8 TXEV; //// static const UINT8 TXEV__MASK = 0xFF; //// static const UINT8 TXEV__FIFO_ALL = 0x0F; //// static const UINT8 TXEV__FIFO_EP0 = 0x01; //// static const UINT8 TXEV__UNDERRUN_ALL = 0xF0; //// /*************/ UINT8 Padding11[3]; //// //// __inline static UINT8 TXEV__FIFO__set ( UINT32 n ) { return (0x01 << n); } //// __inline static UINT8 TXEV__UNDERRUN__set( UINT32 n ) { return (0x10 << n); } //// //// /****/ volatile UINT8 TXMSK; //// static const UINT8 TXMSK__MASK = 0xFF; //// static const UINT8 TXMSK__FIFO_ALL = 0x0F; //// static const UINT8 TXMSK__FIFO_EP0 = 0x01; //// static const UINT8 TXMSK__UNDERRUN_ALL = 0xF0; //// /*************/ UINT8 Padding12[3]; //// //// __inline static UINT8 TXMSK__FIFO__set ( UINT32 n ) { return (0x01 << n); } //// __inline static UINT8 TXMSK__UNDERRUN__set( UINT32 n ) { return (0x10 << n); } //// //// /****/ volatile UINT8 RXEV; //// static const UINT8 RXEV__MASK = 0xFF; //// static const UINT8 RXEV__FIFO_ALL = 0x0F; //// static const UINT8 RXEV__FIFO_EP0 = 0x01; //// static const UINT8 RXEV__OVERRUN_ALL = 0xF0; //// /*************/ UINT8 Padding13[3]; //// //// __inline static UINT8 RXEV__FIFO__set ( UINT32 n ) { return (0x01 << n); } //// __inline static UINT8 RXEV__OVERRUN__set( UINT32 n ) { return (0x10 << n); } //// //// /****/ volatile UINT8 RXMSK; //// static const UINT8 RXMSK__MASK = 0xFF; //// static const UINT8 RXMSK__FIFO_ALL = 0x0F; //// static const UINT8 RXMSK__FIFO_EP0 = 0x01; //// static const UINT8 RXMSK__OVERRUN_ALL = 0xF0; //// /*************/ UINT8 Padding14[3]; //// //// __inline static UINT8 RXMSK__FIFO__set ( UINT32 n ) { return (0x01 << n); } //// __inline static UINT8 RXMSK__OVERRUN__set( UINT32 n ) { return (0x10 << n); } //// //// /****/ volatile UINT8 NAKEV; //// static const UINT8 NAKEV__MASK = 0xFF; //// static const UINT8 NAKEV__IN_ALL = 0x0F; //// static const UINT8 NAKEV__OUT_ALL = 0xF0; //// /*************/ UINT8 Padding15[3]; //// //// __inline static UINT8 NAKEV__IN__set ( UINT32 n ) { return (0x01 << n); } //// __inline static UINT8 NAKEV__OUT__set( UINT32 n ) { return (0x10 << n); } //// //// /****/ volatile UINT8 NAKMSK; //// static const UINT8 NAKMSK__MASK = 0xFF; //// static const UINT8 NAKMSK__IN_ALL = 0x0F; //// static const UINT8 NAKMSK__OUT_ALL = 0xF0; //// /*************/ UINT8 Padding16[3]; //// //// __inline static UINT8 NAKMSK__IN__set ( UINT32 n ) { return (0x01 << n); } //// __inline static UINT8 NAKMSK__OUT__set( UINT32 n ) { return (0x10 << n); } //// //// /****/ volatile UINT8 FWEV; //// static const UINT8 FWEV__MASK = 0xEE; //// static const UINT8 FWEV__TXWARN = 0x0E; //// static const UINT8 FWEV__RXWARN = 0xE0; //// /*************/ UINT8 Padding17[3]; //// //// /****/ volatile UINT8 FWMSK; //// static const UINT8 FWMSK__MASK = 0xEE; //// static const UINT8 FWMSK__TXWARN = 0x0E; //// static const UINT8 FWMSK__RXWARN = 0xE0; //// /*************/ UINT8 Padding18[3]; //// //// /****/ volatile UINT8 FNH; //// static const UINT8 FNH__MASK = 0xE7; //// static const UINT8 FNH__FN = 0x07; //// static const UINT8 FNH__RFC = 0x20; //// static const UINT8 FNH__UL = 0x40; //// static const UINT8 FNH__MF = 0x80; //// /*************/ UINT8 Padding19[3]; //// //// /****/ volatile UINT8 FNL; //// static const UINT8 FNL__MASK = 0xFF; //// static const UINT8 FNL__FN = 0xFF; //// /*************/ UINT8 Padding20[3]; //// //// /****/ volatile UINT8 DMACNTRL; //// static const UINT8 DMACNTRL__MASK = 0xFF; //// static const UINT8 DMACNTRL__DSRC = 0x07; //// static const UINT8 DMACNTRL__DMOD = 0x08; //// static const UINT8 DMACNTRL__ADMA = 0x10; //// static const UINT8 DMACNTRL__DTGL = 0x20; //// static const UINT8 DMACNTRL__IGNRXTGL = 0x40; //// static const UINT8 DMACNTRL__DEN = 0x80; //// /*************/ UINT8 Padding21[3]; //// //// /****/ volatile UINT8 DMAEV; //// static const UINT8 DMAEV__MASK = 0x3F; //// static const UINT8 DMAEV__DSHLT = 0x01; //// static const UINT8 DMAEV__DERR = 0x02; //// static const UINT8 DMAEV__DCNT = 0x04; //// static const UINT8 DMAEV__DSIZ = 0x08; //// static const UINT8 DMAEV__NTGL = 0x20; //// static const UINT8 USB_DMAEV_ARDY = 0x10; //// /*************/ UINT8 Padding22[3]; //// //// /****/ volatile UINT8 DMAMSK; //// static const UINT8 DMAMSK__MASK = 0x2F; //// static const UINT8 DMAMSK__DSHLT = 0x01; //// static const UINT8 DMAMSK__DERR = 0x02; //// static const UINT8 DMAMSK__DCNT = 0x04; //// static const UINT8 DMAMSK__DSIZ = 0x08; //// static const UINT8 DMAMSK__NTGL = 0x20; //// /*************/ UINT8 Padding23[3]; //// //// /****/ volatile UINT8 MIR; //// static const UINT8 MIR__MASK = 0xFF; //// static const UINT8 MIR__STAT = 0xFF; //// /*************/ UINT8 Padding24[3]; //// //// /****/ volatile UINT8 DMACNT; //// static const UINT8 DMACNT__MASK = 0xFF; //// static const UINT8 DMACNT__DCOUNT = 0xFF; //// /*************/ UINT8 Padding25[3]; //// //// /****/ volatile UINT8 DMAERR; //// static const UINT8 DMAERR__MASK = 0xFF; //// static const UINT8 DMAERR__DMAERRCNT = 0x7F; //// static const UINT8 DMAERR__AEH = 0x80; //// /*************/ UINT8 Padding26[3]; //// //// /****/ volatile UINT8 WAKEUP; //// /*************/ UINT8 Padding27[3]; //// //// /*************/ UINT32 Padding28[5]; //// //// /*************/ ENDPNT EP[4]; } } ================================================ FILE: Zelig/Zelig/RunTime/DeviceModels/ModelForMM9691LP/HardwareModel/ChipSet/MM9691LP/VITERBI.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // namespace Microsoft.DeviceModels.Chipset.MM9691LP { using System; using System.Runtime.CompilerServices; using Microsoft.Zelig.Runtime; [MemoryMappedPeripheral(Base=0x30030000U,Length=0x00008008U)] public class VITERBI { //// //--// //// //// CPU_MAC_INT16_ON_32 InputData[c_Input_Array_Elements]; // 0x0000 +0x0A00 //// /*************/ UINT32 Padding1 [ 64]; // 0x0A00 +0x0200 //// //// CPU_MAC_UINT16_ON_32 OutputData[c_Output_Array_Elements]; // 0x0C00 +0x0050 //// /*************/ UINT32 Padding2 [ 118]; // 0x0C50 +0x03B0 //// //// CPU_MAC_UINT16_ON_32 PathMetrics[c_PathMetrics_Array_Elements]; // 0x1000 +0x0800 //// /*************/ UINT32 Padding3 [ 256]; // 0x1800 +0x0800 //// //// CPU_MAC_UINT16_ON_32 TracebackArray[c_Traceback_Array_Elements]; // 0x2000 +0x5000 //// /*************/ UINT32 Padding4 [ 4608]; // 0x7000 +0x1000 //// //// /****/ volatile UINT32 RamControl; // 0x8000 +0x0004 //// static const UINT32 RamControl__CPU = 0x00000000; //// static const UINT32 RamControl__VITERBI = 0x00000001; //// //// /****/ volatile UINT32 Control; // 0x8004 +0x0004 //// static const UINT32 Control__DONE_ACS = 0x00000001; //// static const UINT32 Control__DONE_TRC = 0x00000002; //// static const UINT32 Control__IEN_ACS = 0x00000004; //// static const UINT32 Control__IEN_TRC = 0x00000008; //// static const UINT32 Control__DEN_ACS = 0x00000010; //// static const UINT32 Control__DEN_TRC = 0x00000020; //// static const UINT32 Control__GO_ACS = 0x00000040; //// static const UINT32 Control__GO_TRC = 0x00000080; //// static const UINT32 Control__GO_BOTH = 0x00000100; } } ================================================ FILE: Zelig/Zelig/RunTime/DeviceModels/ModelForMM9691LP/HardwareModel/ChipSet/MM9691LP/VTU32.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // namespace Microsoft.DeviceModels.Chipset.MM9691LP { using System; using System.Runtime.CompilerServices; using Microsoft.Zelig.Runtime; [MemoryMappedPeripheral(Base=0x38030000U,Length=0x00000050U)] public class VTU32 { [MemoryMappedPeripheral(Base=0x0000U,Length=0x004U)] public class IO_CONTROL { public const uint CxyEDG_000 = 0x00000000; public const uint CxyEDG_001 = 0x00000001; public const uint CxyEDG_010 = 0x00000002; public const uint CxyEDG_011 = 0x00000003; public const uint CxyEDG_100 = 0x00000004; public const uint CxyEDG_101 = 0x00000005; public const uint CxyEDG_110 = 0x00000006; public const uint CxyEDG_111 = 0x00000007; public const uint PxyPOL_RESET = 0x00000000; public const uint PxyPOL_SET = 0x00000008; [Register(Offset=0x00000000U)] public uint Value; // this puts the mode bits M for the chosen timer T (0-1), A/B (0-1) of a pair into the correct nibble/byte public static uint Set( uint T , uint A , uint M ) { return M << (int)(A*4 + T*8); } public static uint Get( uint T , uint A , uint M ) { return (M >> (int)(A*4 + T*8)) & 0x000F; } } [MemoryMappedPeripheral(Base=0x0000U,Length=0x001CU)] public class CHANNEL_PAIR { [MemoryMappedPeripheral(Base=0x0000U,Length=0x000CU)] public class CHANNEL { [Register(Offset=0x00000000U)] public uint Counter; [Register(Offset=0x00000004U)] public uint PeriodCapture; [Register(Offset=0x00000008U)] public uint DutyCycleCapture; }; [Register(Offset=0x00000000U)] public uint ClockPrescalar; [Register(Offset=0x00000004U,Instances=2)] public CHANNEL[] Channel; //--// public uint ClockPrescalar__get( uint T ) { return (ClockPrescalar >> (int)(T*8)) & 0x00FF; } public void ClockPrescalar__set( uint T , uint P ) { uint val = ClockPrescalar; val &= ~( 0x000000FFu << (int)(T*8)); val |= ((P & 0x000000FFu) << (int)(T*8)); ClockPrescalar = val; } } //--// public const uint c_TIO1A = GPIO.c_Pin_20; public const uint c_TIO2A = GPIO.c_Pin_21; public const uint c_TIO3A = GPIO.c_Pin_22; public const uint c_TIO4A = GPIO.c_Pin_23; public const uint c_TIO1B = GPIO.c_Pin_05; public const uint c_TIO2B = GPIO.c_Pin_06; public const uint c_TIO3B = GPIO.c_Pin_13; public const uint c_TIO4B = GPIO.c_Pin_14; //--// public const uint ModeControl__TxARUN = 0x00000001; public const uint ModeControl__TxBRUN = 0x00000002; public const uint ModeControl__TMODx_LOW_POWER = 0x00000000; public const uint ModeControl__TMODx_DUAL_PWM16 = 0x00000004; public const uint ModeControl__TMODx_PWM32 = 0x00000008; public const uint ModeControl__TMODx_CAPTURE = 0x0000000C; public const uint Interrupt__Ix_None = 0x00000000; public const uint Interrupt__Ix_1 = 0x00000001; public const uint Interrupt__Ix_2 = 0x00000002; public const uint Interrupt__Ix_3 = 0x00000004; public const uint Interrupt__Ix_4 = 0x00000008; public const uint Interrupt__Ix_ALL = (Interrupt__Ix_1 | Interrupt__Ix_2 | Interrupt__Ix_3 | Interrupt__Ix_4); public const uint ExternalClockSelectRegister__CK1 = 0x00000001; public const uint ExternalClockSelectRegister__CK2 = 0x00000002; public const uint ExternalClockSelectRegister__CK3 = 0x00000004; public const uint ExternalClockSelectRegister__CK4 = 0x00000008; //--// [Register(Offset=0x00000000U)] public uint ModeControl; [Register(Offset=0x00000004U,Instances=2)] public IO_CONTROL[] IOControl; [Register(Offset=0x0000000CU)] public uint InterruptControl; [Register(Offset=0x00000010U)] public uint InterruptPending; [Register(Offset=0x00000014U,Instances=2)] public CHANNEL_PAIR[] ChannelPair; [Register(Offset=0x0000004CU)] public uint ExternalClockSelectRegister; //--// // this puts the mode bits M for the chosen timer T (0-3) into the correct nibble public static uint ModeControl__set( uint T , uint M ) { return M << (int)(T*4); } public static uint ModeControl__get( uint T , uint M ) { return (M >> (int)(T*4)) & 0x000F; } // this puts the INT bits I for the chosen timer T (0-3) into the correct nibble public static uint Interrupt__set( uint T , uint I ) { return I << (int)(T*4); } public static uint Interrupt__get( uint T , uint I ) { return (I >> (int)(T*4)) & 0x000F; } // // Access Methods // public static extern VTU32 Instance { [SingletonFactory()] [MethodImpl( MethodImplOptions.InternalCall )] get; } } } ================================================ FILE: Zelig/Zelig/RunTime/DeviceModels/ModelForMM9691LP/HardwareModel/Drivers/InterruptController.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // namespace Microsoft.DeviceModels.Chipset.MM9691LP.Drivers { using System; using System.Runtime.CompilerServices; using RT = Microsoft.Zelig.Runtime; public abstract class InterruptController { public delegate void Callback( Handler handler ); public class Handler { // // State // private uint m_mask; private int m_index; private Callback m_callback; internal RT.KernelNode< Handler > m_node; // // Constructor Methods // private Handler( uint mask , Callback callback ) { m_mask = mask; m_callback = callback; } private Handler( int index , Callback callback ) { m_index = index; m_callback = callback; } // // Helper Methods // public static Handler Create( uint mask , Callback callback ) { Handler hnd = new Handler( mask, callback ); hnd.m_node = new RT.KernelNode< Handler >( hnd ); return hnd; } public static Handler CreateFast( int index , Callback callback ) { Handler hnd = new Handler( index, callback ); hnd.m_node = new RT.KernelNode< Handler >( hnd ); return hnd; } public void Enable() { if(this.IsFastHandler) { MM9691LP.INTC.Instance.Fiq.Select = m_index; MM9691LP.INTC.Instance.Fiq.EnableSet = 1u; } else { MM9691LP.INTC.Instance.Irq.EnableSet = m_mask; } } public void Disable() { if(this.IsFastHandler) { MM9691LP.INTC.Instance.Fiq.Select = 0; MM9691LP.INTC.Instance.Fiq.EnableClear = 1u; } else { MM9691LP.INTC.Instance.Irq.EnableClear = m_mask; } } public void Invoke() { m_callback( this ); } // // Access Methods // public uint Mask { get { return m_mask; } } public int Index { get { return m_index; } } public bool IsFastHandler { get { return m_index != 0; } } } // // State // private RT.KernelList< Handler > m_handlers; private Handler m_softInterrupt; private Handler m_fastInterrupt; private RT.Peripherals.Continuation m_softCallback; // // Helper Methods // public void Initialize() { m_handlers = new RT.KernelList< Handler >(); MM9691LP.INTC.Instance.Irq.EnableClear = MM9691LP.INTC.IRQ_MASK_All; MM9691LP.INTC.Instance.Fiq.EnableClear = MM9691LP.INTC.IRQ_MASK_All; //--// m_softInterrupt = InterruptController.Handler.Create( MM9691LP.INTC.IRQ_MASK_Programmed_Interrupt, ProcessSoftInterrupt ); Register( m_softInterrupt ); m_softInterrupt.Enable(); } public void RegisterAndEnable( Handler hnd ) { Register( hnd ); hnd.Enable(); } public void Register( Handler hnd ) { if(hnd.IsFastHandler) { m_fastInterrupt = hnd; } else { m_handlers.InsertAtTail( hnd.m_node ); } } public void Deregister( Handler hnd ) { if(hnd.IsFastHandler) { m_fastInterrupt = null; } else { hnd.m_node.RemoveFromList(); } } public void DeregisterAndDisable( Handler hnd ) { RT.BugCheck.AssertInterruptsOff(); hnd.Disable(); Deregister( hnd ); } public void ProcessInterrupt() { while(true) { uint status = MM9691LP.INTC.Instance.Irq.Status; if(status == 0) { break; } do { RT.KernelNode< Handler > node = m_handlers.StartOfForwardWalk; while(true) { if(node.IsValidForForwardMove == false) { // // BUGBUG: Unhandled interrupts. We should crash. For now we just disable them. // MM9691LP.INTC.Instance.Irq.EnableClear = status; break; } Handler hnd = node.Target; uint mask = hnd.Mask; if((status & mask) != 0) { status &= ~mask; hnd.Invoke(); break; } node = node.Next; } } while(status != 0); } } [RT.MemoryRequirements( RT.MemoryAttributes.RAM )] public void ProcessFastInterrupt() { while(true) { uint status = MM9691LP.INTC.Instance.Fiq.Status; if(status == 0) { break; } Handler hnd = m_fastInterrupt; if(hnd == null) { // // BUGBUG: Unhandled interrupts. We should crash. For now we just disable them. // MM9691LP.INTC.Instance.Fiq.EnableClear = status; break; } hnd.Invoke(); } } public void CauseInterrupt() { MM9691LP.INTC.Instance.Irq.Soft = MM9691LP.INTC.IRQ_MASK_Programmed_Interrupt; } public void ContinueUnderNormalInterrupt( RT.Peripherals.Continuation dlg ) { m_softCallback = dlg; CauseInterrupt(); } private void ProcessSoftInterrupt( InterruptController.Handler handler ) { MM9691LP.INTC.Instance.Irq.Soft = 0; RT.Peripherals.Continuation dlg = System.Threading.Interlocked.Exchange( ref m_softCallback, null ); if(dlg != null) { dlg(); } } // // Access Methods // public static extern InterruptController Instance { [RT.SingletonFactory()] [MethodImpl( MethodImplOptions.InternalCall )] get; } } } ================================================ FILE: Zelig/Zelig/RunTime/DeviceModels/ModelForMM9691LP/HardwareModel/Drivers/RealTimeClock.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // namespace Microsoft.DeviceModels.Chipset.MM9691LP.Drivers { using System; using System.Runtime.CompilerServices; using RT = Microsoft.Zelig.Runtime; public abstract class RealTimeClock { public delegate void Callback( Timer timer, ulong currentTime ); public class Timer { // // State // private RealTimeClock m_owner; private RT.KernelNode< Timer > m_node; private ulong m_timeout; private Callback m_callback; // // Constructor Methods // internal Timer( RealTimeClock owner , Callback callback ) { m_owner = owner; m_node = new RT.KernelNode< Timer >( this ); m_callback = callback; } // // Helper Methods // public void Cancel() { m_owner.Deregister( this ); } internal void Invoke( ulong currentTime ) { m_callback( this, currentTime ); } // // Access Methods // internal RT.KernelNode< Timer > Node { get { return m_node; } } public ulong Timeout { get { return m_timeout; } set { m_timeout = value; m_owner.Register( this ); } } public ulong RelativeTimeout { get { return m_timeout - RealTimeClock.Instance.CurrentTime; } set { m_timeout = value + RealTimeClock.Instance.CurrentTime; m_owner.Register( this ); } } } // // State // private InterruptController.Handler m_interrupt; private RT.KernelList< Timer > m_timers; // // Helper Methods // public void Initialize() { m_timers = new RT.KernelList< Timer >(); m_interrupt = InterruptController.Handler.Create( MM9691LP.INTC.IRQ_MASK_Real_Time_Clock, ProcessTimeout ); InterruptController.Instance.Register( m_interrupt ); } public Timer CreateTimer( Callback callback ) { return new Timer( this, callback ); } //--// private void Register( Timer timer ) { RT.KernelNode< Timer > node = timer.Node; node.RemoveFromList(); ulong timeout = timer.Timeout; RT.KernelNode< Timer > node2 = m_timers.StartOfForwardWalk; while(node2.IsValidForForwardMove) { if(node2.Target.Timeout > timeout) { break; } node2 = node2.Next; } node.InsertBefore( node2 ); Refresh(); } private void Deregister( Timer timer ) { var node = timer.Node; if(node.IsLinked) { node.RemoveFromList(); Refresh(); } } //--// private void ProcessTimeout( InterruptController.Handler handler ) { ulong currentTime = this.CurrentTime; while(true) { RT.KernelNode< Timer > node = m_timers.StartOfForwardWalk; if(node.IsValidForForwardMove == false) { break; } if(node.Target.Timeout > currentTime) { break; } node.RemoveFromList(); node.Target.Invoke( currentTime ); } Refresh(); } void Refresh() { RT.KernelNode< Timer > node = m_timers.FirstNode(); if(node != null) { MM9691LP.RTC.Instance.COMP = node.Target.Timeout; m_interrupt.Enable(); } else { m_interrupt.Disable(); } } // // Access Methods // public static extern RealTimeClock Instance { [RT.SingletonFactory()] [MethodImpl( MethodImplOptions.InternalCall )] get; } public ulong CurrentTime { get { MM9691LP.RTC.Instance.LD_HREG = 1; Processor.Delay( 12 ); return MM9691LP.RTC.Instance.HREG; } } } } ================================================ FILE: Zelig/Zelig/RunTime/DeviceModels/ModelForMM9691LP/HardwareModel/Drivers/SerialPort.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // namespace Microsoft.DeviceModels.Chipset.MM9691LP.Drivers { using System; using System.Runtime.CompilerServices; using RT = Microsoft.Zelig.Runtime; internal class SerialPort : RT.BaseSerialStream { // // State // private int m_usartNum; private Chipset.MM9691LP.USARTx m_core; private InterruptController.Handler m_interruptRx; private InterruptController.Handler m_interruptTx; // // Constructor Methods // internal SerialPort( ref Configuration cfg , int usartNum ) : base( ref cfg ) { m_usartNum = usartNum; uint maskRX; uint maskTX; if(usartNum == 0) { maskRX = MM9691LP.INTC.IRQ_MASK_USART0_Rx; maskTX = MM9691LP.INTC.IRQ_MASK_USART0_Tx; } else { maskRX = MM9691LP.INTC.IRQ_MASK_USART1_Rx; maskTX = MM9691LP.INTC.IRQ_MASK_USART1_Tx; } m_interruptRx = InterruptController.Handler.Create( maskRX, ProcessRX ); m_interruptTx = InterruptController.Handler.Create( maskTX, ProcessTX ); } // // Helper Methods // internal void Open() { if(m_usartNum == 0) { m_core = MM9691LP.USART0.Initialize( ref m_cfg ); } else { m_core = MM9691LP.USART1.Initialize( ref m_cfg ); } if(m_core == null) { throw new ArgumentException(); } using(RT.SmartHandles.InterruptState.Disable()) { InterruptController.Instance.RegisterAndEnable( m_interruptRx ); InterruptController.Instance.Register ( m_interruptTx ); } } public override void Close() { if(m_core != null) { using(RT.SmartHandles.InterruptState.Disable()) { InterruptController.Instance.DeregisterAndDisable( m_interruptRx ); InterruptController.Instance.DeregisterAndDisable( m_interruptTx ); } m_core = null; } } //--// public override void Write( byte[] array , int offset , int count , int timeout ) { base.Write( array, offset, count, timeout ); using(RT.SmartHandles.InterruptState.Disable()) { m_interruptTx.Enable(); } } public override void WriteByte( byte value , int timeout ) { base.WriteByte( value, timeout ); using(RT.SmartHandles.InterruptState.Disable()) { m_interruptTx.Enable(); } } //--// private void ProcessRX( InterruptController.Handler handler ) { byte val = m_core.UnRBUF; if(m_receiveQueue.EnqueueNonblocking( val ) == false) { // // Overflow... // } } private void ProcessTX( InterruptController.Handler handler ) { byte val; if(m_transmitQueue.DequeueNonblocking( out val )) { m_core.UnTBUF = val; } else { m_interruptTx.Disable(); } } //--// public override bool IsOpen { get { return m_core != null; } } } } ================================================ FILE: Zelig/Zelig/RunTime/DeviceModels/ModelForMM9691LP/HardwareModel/Processor.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // namespace Microsoft.DeviceModels.Chipset.MM9691LP { using System; using RT = Microsoft.Zelig.Runtime; using TS = Microsoft.Zelig.Runtime.TypeSystem; public abstract class Processor : RT.TargetPlatform.ARMv4.ProcessorARMv4 { public sealed new class Context : RT.TargetPlatform.ARMv4.ProcessorARMv4.Context { // // Constructor Methods // public Context(RT.ThreadImpl owner) : base(owner) { } // // Helper Methods // // // Access Methods // } // // Helper Methods // public override void InitializeProcessor() { InitializeCache(); } public override UIntPtr GetCacheableAddress( UIntPtr ptr ) { return new UIntPtr( ptr.ToUInt32() | MM9691LP.REMAP_PAUSE.CacheableAddressMask ); } public override UIntPtr GetUncacheableAddress( UIntPtr ptr ) { return new UIntPtr( ptr.ToUInt32() & ~MM9691LP.REMAP_PAUSE.CacheableAddressMask ); } public override unsafe void FlushCacheLine( UIntPtr target ) { uint* ptr = (uint*)(target.ToUInt32() | MM9691LP.REMAP_PAUSE.CacheFlushAddressMask); *ptr = 0; } //--// private unsafe void InitializeCache() { MM9691LP.REMAP_PAUSE remap = MM9691LP.REMAP_PAUSE.Instance; remap.SystemConfiguration.PU_DIS = true; remap.InitializeCache(); } [RT.Inline] public override Microsoft.Zelig.Runtime.Processor.Context AllocateProcessorContext(RT.ThreadImpl owner) { return new Context(owner); } } } ================================================ FILE: Zelig/Zelig/RunTime/DeviceModels/ModelForMM9691LP/ModelForMM9691LP.csproj ================================================  Debug AnyCPU 9.0.21022 2.0 {186F31A3-EF89-4A25-B2D5-20070724AA02} Library Properties Microsoft.DeviceModels.ModelForMM9691LP Microsoft.DeviceModels.ModelForMM9691LP $(LlilumBuildRoot)\Target\obj\$(MSBuildProjectName)\ v4.5 true full false $(LlilumBuildRoot)\Target\bin\$(Configuration)\ DEBUG;TRACE prompt 4 true true true AllRules.ruleset AnyCPU false pdbonly true $(LlilumBuildRoot)\Target\bin\$(Configuration)\ TRACE prompt 4 true true true AllRules.ruleset AnyCPU false $(LlilumBuildRoot)\Target\bin\$(Configuration)\ true DEBUG;TRACE AnyCPU true true false {186F31A3-EF89-4A25-B2D5-20060501AA01} mscorlib False {186F31A3-EF89-4A25-B2D5-20070702AA01} system {186F31A3-EF89-4A25-B2D5-20061218AA01} Common False {186F31A3-EF89-4A25-B2D5-20060509AA01} Kernel False {186F31A3-EF89-4A25-B2D5-20060720AA01} TypeSystem False 3.5 ================================================ FILE: Zelig/Zelig/RunTime/DeviceModels/ModelForMM9691LP/Properties/AssemblyInfo.cs ================================================ using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; // General Information about an assembly is controlled through the following // set of attributes. Change these attribute values to modify the information // associated with an assembly. [assembly: AssemblyTitle( "Microsoft.DeviceModels.ModelForMM9691LP" )] [assembly: AssemblyDescription( "" )] [assembly: AssemblyConfiguration( "" )] [assembly: AssemblyCompany( "Microsoft" )] [assembly: AssemblyProduct( "Microsoft.DeviceModels.ModelForMM9691LP" )] [assembly: AssemblyCopyright( "Copyright © Microsoft 2006" )] [assembly: AssemblyTrademark( "" )] [assembly: AssemblyCulture( "" )] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible( false )] //// The following GUID is for the ID of the typelib if this project is exposed to COM //[assembly: Guid( "975a7db2-22e5-41c6-9e32-d3f72152d387" )] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Revision and Build Numbers // by using the '*' as shown below: [assembly: AssemblyVersion( "1.0.0.0" )] [assembly: AssemblyFileVersion( "1.0.0.0" )] ================================================ FILE: Zelig/Zelig/RunTime/DeviceModels/ModelForMM9691LP/SystemServices/SchedulerTimeImpl.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // namespace Microsoft.DeviceModels.Chipset.MM9691LP.Runtime { using System; using System.Runtime.CompilerServices; using RT = Microsoft.Zelig.Runtime; using TS = Microsoft.Zelig.Runtime.TypeSystem; // // We use the RTC time resolution for the internal time. // [RT.ExtendClass(typeof(RT.SchedulerTime), NoConstructors=true)] public struct SchedulerTimeImpl { // // Helper Methods // private static ulong ConvertFromMillisecondsToUnits( int milliSeconds ) { if(milliSeconds < 0) { return ulong.MaxValue; } else { // // The RTC clock frequency is 32768. // // => 32768 / 1000 == 4096 / 125 // ulong res = (uint)milliSeconds * 4096; res /= 125; return GetCurrentTime() + res; } } private static ulong ConvertFromTimeSpanTicksToUnits( long ticks ) { if(ticks < 0) { return ulong.MaxValue; } else { ulong res = ConvertFromDateTimeTicksToUnits( ticks ); return GetCurrentTime() + res; } } private static ulong ConvertFromDateTimeTicksToUnits( long ticks ) { return (ulong)((double)ticks * RatioFromDateTimeTicksToUnits); } private static long ConvertFromUnitsToDateTimeTicks( ulong units ) { return (long)((double)units * RatioFromUnitsToDateTimeTicks); } private static ulong GetCurrentTime() { return Drivers.RealTimeClock.Instance.CurrentTime; } // // Access Methods // static int HardwareClockFrequency { [RT.Inline] get { return (int)RT.Configuration.RealTimeClockFrequency; } } static double RatioFromMillisecondsToUnits { [RT.Inline] get { return (double)HardwareClockFrequency / (double)1000; } } static double RatioFromDateTimeTicksToUnits { [RT.Inline] get { return (double)HardwareClockFrequency / (double)TimeSpan.TicksPerSecond; } } static double RatioFromUnitsToMilliseconds { [RT.Inline] get { return 1.0 / RatioFromMillisecondsToUnits; } } static double RatioFromUnitsToDateTimeTicks { [RT.Inline] get { return 1.0 / RatioFromDateTimeTicksToUnits; } } } } ================================================ FILE: Zelig/Zelig/RunTime/DeviceModels/ModelForMM9691LP/SystemServices/SchedulerTimeSpanImpl.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // namespace Microsoft.DeviceModels.Chipset.MM9691LP.Runtime { using System; using RT = Microsoft.Zelig.Runtime; using TS = Microsoft.Zelig.Runtime.TypeSystem; // // We use the RTC time resolution for the internal time. // [RT.ExtendClass(typeof(RT.SchedulerTimeSpan), NoConstructors=true)] public struct SchedulerTimeSpanImpl { // // Helper Methods // private static long ConvertFromMillisecondsToDeltaUnits( long milliSeconds ) { return (long)((double)milliSeconds * RatioFromMillisecondsToDeltaUnits); } private static long ConvertFromTimeSpanTicksToDeltaUnits( long ticks ) { return (long)((double)ticks * RatioFromTimeSpanTicksToDeltaUnits); } private static long ConvertFromDeltaUnitsToTimeSpanTicks( long deltaUnits ) { return (long)((double)deltaUnits * RatioFromDeltaUnitsToTimeSpanTicks); } private static long ConvertFromDeltaUnitsToMilliseconds( long deltaUnits ) { return (long)((double)deltaUnits * RatioFromDeltaUnitsToMilliseconds); } // // Access Methods // static int HardwareClockFrequency { [RT.Inline] get { return (int)RT.Configuration.RealTimeClockFrequency; } } static double RatioFromMillisecondsToDeltaUnits { [RT.Inline] get { return (double)HardwareClockFrequency / (double)1000; } } static double RatioFromTimeSpanTicksToDeltaUnits { [RT.Inline] get { return (double)HardwareClockFrequency / (double)TimeSpan.TicksPerSecond; } } static double RatioFromDeltaUnitsToMilliseconds { [RT.Inline] get { return 1.0 / RatioFromMillisecondsToDeltaUnits; } } static double RatioFromDeltaUnitsToTimeSpanTicks { [RT.Inline] get { return 1.0 / RatioFromTimeSpanTicksToDeltaUnits; } } } } ================================================ FILE: Zelig/Zelig/RunTime/DeviceModels/ModelForMM9691LP/SystemServices/SerialPortsManager.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // namespace Microsoft.DeviceModels.Chipset.MM9691LP.Runtime { using System; using RT = Microsoft.Zelig.Runtime; using TS = Microsoft.Zelig.Runtime.TypeSystem; public abstract class SerialPortsManager : RT.SerialPortsManager { // // State // // // Helper Methods // public override void Initialize() { } public override string[] GetPortNames() { return new string[] { "COM1", "COM2", }; } public override System.IO.Ports.SerialStream Open( ref RT.BaseSerialStream.Configuration cfg ) { switch(cfg.PortName) { case "COM1": return Open( ref cfg, 1 ); case "COM2": return Open( ref cfg, 0 ); } return null; } private System.IO.Ports.SerialStream Open( ref RT.BaseSerialStream.Configuration cfg , int usartNum ) { Drivers.SerialPort port; switch(usartNum) { case 0: case 1: port = new Drivers.SerialPort( ref cfg, usartNum ); break; default: return null; } port.Open(); return port; } } } ================================================ FILE: Zelig/Zelig/RunTime/DeviceModels/ModelForMM9691LP/SystemServices/ThreadManager.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // namespace Microsoft.DeviceModels.Chipset.MM9691LP.Runtime { using System; using RT = Microsoft.Zelig.Runtime; using TS = Microsoft.Zelig.Runtime.TypeSystem; public abstract class ThreadManager : RT.ARMv5ThreadManager { const ulong c_TimeQuantumMsec = 20; // // State // Drivers.RealTimeClock.Timer m_timer; Drivers.RealTimeClock.Timer m_timerForWaits; // // Helper Methods // public override void InitializeBeforeStaticConstructors() { base.InitializeBeforeStaticConstructors(); } public override void InitializeAfterStaticConstructors( uint[] systemStack ) { base.InitializeAfterStaticConstructors( systemStack ); } public override void Activate() { m_timer = Drivers.RealTimeClock.Instance.CreateTimer( TimeQuantumExpired ); m_timerForWaits = Drivers.RealTimeClock.Instance.CreateTimer( WaitExpired ); } public override void Reschedule() { base.Reschedule(); } public override void SetNextWaitTimer( RT.SchedulerTime nextTimeout ) { if(nextTimeout != RT.SchedulerTime.MaxValue) { m_timerForWaits.Timeout = nextTimeout.Units; } else { m_timerForWaits.Cancel(); } } public override void CancelQuantumTimer() { m_timer.Cancel(); } public override void SetNextQuantumTimer() { m_timer.RelativeTimeout = c_TimeQuantumMsec * 1000 * RT.Configuration.RealTimeClockFrequency / 1000000; } public override void SetNextQuantumTimer( RT.SchedulerTime nextTimeout ) { m_timer.RelativeTimeout = nextTimeout.Units; } //--// private void TimeQuantumExpired( Drivers.RealTimeClock.Timer timer , ulong currentTime ) { TimeQuantumExpired(); } private void WaitExpired( Drivers.RealTimeClock.Timer timer , ulong currentTime ) { WaitExpired( RT.SchedulerTime.FromUnits( currentTime ) ); } } } ================================================ FILE: Zelig/Zelig/RunTime/DeviceModels/ModelForPXA27x/HardwareModel/ChipSet/PXA27x/ClockManager.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // namespace Microsoft.DeviceModels.Chipset.PXA27x { using System; using System.Runtime.CompilerServices; using Microsoft.Zelig.Runtime; [MemoryMappedPeripheral(Base=0x41300000U,Length=0x00000010U)] public class ClockManager { [BitFieldPeripheral(PhysicalType=typeof(uint))] public struct CCCR_bitfield { [BitFieldRegister(Position=31 )] public bool CPDIS; // Core PLL Output Disable // // 0 = Core PLL is enabled after frequency change. // 1 = Core PLL is disabled after frequency change if not selected as a clock source. // [BitFieldRegister(Position=30 )] public bool PPDIS; // Peripheral PLL Output Disable // // 0 = Peripheral PLL is enabled after frequency change. // 1 = Peripheral PLL is disabled after frequency change if not selected as a clock source. // [BitFieldRegister(Position=27 )] public bool LCD_26; // LCD Clock Frequency in Deep-Idle or 13M Mode // // 0 = LCD clock frequency is 13 MHz. // 1 = LCD clock frequency is 26 MHz. // [BitFieldRegister(Position=26 )] public bool PLL_EARLY_EN; // Early PLL Enable // // In 13M mode, allows software to enable the PLLs ahead of time, while // remaining fully operational in 13M mode. When the core and peripheral // PLLs have locked (CCSR[CPLK] and CCSR[PPLK] set), software can // perform the frequency change. This bit is automatically cleared after a // frequency change exiting from 13M mode. // // 0 = Do not enable the core and peripheral PLLs early. // 1 = Enable the core and peripheral PLLs early (all units and the core remain operational at 13 MHz). // // NOTE: Write to this bit only when the processor is in 13M mode and the // core PLL has been disabled by setting CPDIS. In normal run mode, // writing to this bit causes unpredictable results. // [BitFieldRegister(Position=25 )] public bool A; // Alternate Setting for Memory Controller Clock // // 0 = Memory controller clock (CLK_MEM) clock frequency is as specified in Table 3-7. // 1 = Memory controller clock (CLK_MEM) clock frequency is the same as the system bus frequency. // // NOTE: Refer to section 6.5.1.4 for changing CLK_MEM while SDCLK <1> or <2> is at 104 MHz // [BitFieldRegister(Position=7,Size=3)] public uint N; // Turbo-Mode-to-Run-Mode Ratio, N (Reset value 0b010 for N = 1) // // 0b0000b010 = ratio (N) = 1 // 0b0110b110 = ratio (N) = (2N / 2) // 0b111 = reserved // // NOTE: Program this field with twice the value of N. // [BitFieldRegister(Position=0,Size=5)] public uint L; // Run-Mode-to-Oscillator Ratio (Reset value 0b00111 for L=7) // // 0b000000b00010 = ratio = 2 // 0b000110b11110 = ratio = L // 0b11111 = reserved // } [BitFieldPeripheral(PhysicalType=typeof(uint))] public struct CKEN_bitfield { [BitFieldRegister(Position=31)] public bool EnAC97b; // AC 97 Controller Clock Enable [BitFieldRegister(Position=25)] public bool EnTPM; // TPM Unit Clock Enable [BitFieldRegister(Position=24)] public bool EnQuickCapture; // Quick Capture Interface Clock Enable [BitFieldRegister(Position=23)] public bool EnSSP1; // SSP1 Unit Clock Enable [BitFieldRegister(Position=22)] public bool EnMemoryController; // Memory Controller [BitFieldRegister(Position=21)] public bool EnMemoryStick; // Memory Stick Host Controller [BitFieldRegister(Position=20)] public bool EnInternalMemory; // Internal Memory Clock Enable [BitFieldRegister(Position=19)] public bool EnKeypad; // Keypad Interface Clock Enable [BitFieldRegister(Position=18)] public bool EnUSIM; // USIM Unit Clock Enable [BitFieldRegister(Position=17)] public bool EnMSL; // MSL Interface Unit Clock Enable [BitFieldRegister(Position=16)] public bool EnLCD; // LCD Controller Clock Enable [BitFieldRegister(Position=15)] public bool EnPMI2C; // Power Manager I2C Unit Clock Enable [BitFieldRegister(Position=14)] public bool EnI2C; // I2C Unit Clock Enable [BitFieldRegister(Position=13)] public bool EnIRDA; // Infrared Port Clock Enable [BitFieldRegister(Position=12)] public bool EnMMC; // MMC Controller Clock Enable [BitFieldRegister(Position=11)] public bool EnUSBClient; // USB Client Unit Clock Enable [BitFieldRegister(Position=10)] public bool EnUSBHost; // USB Host Unit Clock Enable [BitFieldRegister(Position=9 )] public bool EnOsTimer; // OS Timer Unit Clock Enable [BitFieldRegister(Position=8 )] public bool EnI2S; // I2S Unit Clock Enable [BitFieldRegister(Position=7 )] public bool EnBTUART; // BTUART Unit Clock Enable [BitFieldRegister(Position=6 )] public bool EnFFUART; // FFUART Unit Clock Enable [BitFieldRegister(Position=5 )] public bool EnSTUART; // STUART Unit Clock Enable [BitFieldRegister(Position=4 )] public bool EnSSP3; // SSP3 Unit Clock Enable [BitFieldRegister(Position=3 )] public bool EnSSP2; // SSP2 Unit Clock Enable [BitFieldRegister(Position=2 )] public bool EnAC97a; // AC 97 Controller Clock Enable [BitFieldRegister(Position=0 )] public bool EnPWM; // PWM Clock Enable } [BitFieldPeripheral(PhysicalType=typeof(uint))] public struct OSCC_bitfield { public enum Stabilization { Delay5ms = 0, // 00 = Approximately 5 ms Delay3ms = 1, // 01 = Approximately 3 ms Delay375us = 2, // 10 = Approximately 375 us Delay1us = 3, // 11 = Approximately 1 us } [BitFieldRegister(Position=5,Size=2)] public Stabilization OSD; // Processor (13-MHz) Oscillator Stabilization Delay // [BitFieldRegister(Position=4 )] public bool CRI; // Clock Request Input (External Processor Oscillator) Status // // 0 = The processor oscillator must be supplied using PXTAL_IN and PXTAL_OUT (the CLK_REQ pin was driven low during hardware or watchdog reset). // 1 = The processor oscillator is supplied externally (the CLK_REQ pin was floated during hardware or watchdog reset). // // NOTE: See the requirements for each of these conditions (listed in Section 3.8.2.3). // [BitFieldRegister(Position=3 )] public bool PIO_EN; // 13-MHz Processor Oscillator Output Enable // // 0 = CLK_PIO is not used; pin can be used as GPIO. // 1 = CLK_PIO is driven at the same frequency as the processor oscillator, regardless of the GPIO configuration. This configuration is ignored if CRI is set. // [BitFieldRegister(Position=2 )] public bool TOUT_EN; // Timekeeping (32.768 kHz) Oscillator Output Enable // // 0 = CLK_TOUT is not used; pin can be used as GPIO. // 1 = CLK_TOUT is driven at the same frequency as the timekeeping oscillator, regardless of the GPIO configuration. If CRI is set, // // TOUT_EN is set out of power-on or hardware reset but can be set or cleared at any time. // [BitFieldRegister(Position=1 )] public bool OON; // Timekeeping (32.768 kHz) Oscillator On (Write once only) // // 0 = The timekeeping oscillator is disabled. // 1 = The timekeeping oscillator is enabled. Once written, OON cannot be cleared except by power-on or hardware reset. // If CRI is set, OON is set out of power-on or hardware reset and cannot be cleared. // [BitFieldRegister(Position=0 )] public bool OOK; // Timekeeping (32.768 kHz) Oscillator OK // // 0 = The timekeeping oscillator is disabled or not stable, and clocks (divided by 112) the RTC and power manager. // 1 = The timekeeping oscillator has been enabled (OON = 1) and stabilized; it clocks the RTC and power manager. // If CRI is set, OOK is set out of power-on or hardware reset. // } [BitFieldPeripheral(PhysicalType=typeof(uint))] public struct CCSR_bitfield { [BitFieldRegister(Position=31 )] public bool CPDIS_S; // Core PLL Output Disable (CPDIS) Status // // Updated from CCCR at frequency change and standby, sleep, or deepsleep exit. // [BitFieldRegister(Position=30 )] public bool PPDIS_S; // Peripheral PLL Output Disable (PPDIS) Status // // Updated from CCCR at frequency change and standby, sleep, or deepsleep exit. // [BitFieldRegister(Position=29 )] public bool CPLCK; // Core PLL Lock // // 0 = Core PLL is not locked. Using it as a clock source incurs a time penalty to make the switch while it locks. // 1 = Core PLL is locked and ready to use. // [BitFieldRegister(Position=28 )] public bool PPLCK; // Peripheral PLL Lock // // 0 = Peripheral PLL is not locked. Using it as a clock source incurs a time penalty to make the switch while it locks. // 1 = Peripheral PLL is locked and ready to use. // [BitFieldRegister(Position=7,Size=3)] public uint N_S; // Turbo-Mode-to-Run-Mode Ratio (N) Status // // Updated from CCCR at frequency change and standby, sleep, or deepsleep exit. (Reset value = 0b010 for N = 1) // // NOTE: The value in this field reflects twice the value of N. // [BitFieldRegister(Position=0,Size=5)] public uint L_S; // Run-Mode to 13-MHz Processor Oscillator Ratio (L) Status // // Updated from CCCR at frequency change and standby, sleep, or deepsleep exit. (Reset value = 0b0_0111 for L = 7) // } [Register(Offset=0x00)] public CCCR_bitfield CCCR; // Core Clock Configuration register | 3-95 [Register(Offset=0x04)] public CKEN_bitfield CKEN; // Clock Enable register | 3-98 [Register(Offset=0x08)] public OSCC_bitfield OSCC; // Oscillator Configuration register | 3-99 [Register(Offset=0x0C)] public CCSR_bitfield CCSR; // Core Clock Status register | 3-101 public void InitializeClocks() { // // Turn off all the clock,except internal memory, let each unit to turn on at its code // this.CKEN = new CKEN_bitfield { EnInternalMemory = true, EnMemoryController = true, EnPMI2C = true, }; // enable TOUT for debugging. this.OSCC.TOUT_EN = true; // // Run freq = 208MHz, turbo = 416MHz, core PLLs must on, CLK_MEM = 208MHz // this.CCCR = new CCCR_bitfield { A = true, N = 4, L = 16, }; // Start frequency change + enable Turbo mode (416 MHz clock) Processor.MoveToCoprocessor ( 14, 0, 6, 0, 0, 3 ); //// CPU_CPWAIT(); Processor.MoveFromCoprocessor( 15, 0, 2, 0, 0 ); // // Wait until clk stable // while(this.CCSR.CPLCK == false) { } while(this.CCSR.PPLCK == false) { } } // // Access Methods // public static extern ClockManager Instance { [SingletonFactory()] [MethodImpl( MethodImplOptions.InternalCall )] get; } } } ================================================ FILE: Zelig/Zelig/RunTime/DeviceModels/ModelForPXA27x/HardwareModel/ChipSet/PXA27x/GPIO.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // namespace Microsoft.DeviceModels.Chipset.PXA27x { using System.Runtime.CompilerServices; using Microsoft.Zelig.Runtime; [MemoryMappedPeripheral(Base=0x40E00000U,Length=0x0000014CU)] public class GPIO { [MemoryMappedPeripheral(Base=0x0U,Length=0x0000004CU)] class Cluster { #pragma warning disable 649 [Register(Offset=0x00U)] internal uint GPLR; // GPIO Pin-Level register [Register(Offset=0x0CU)] internal uint GPDR; // GPIO Pin Direction register [Register(Offset=0x18U)] internal uint GPSR; // GPIO Pin Output Set register [Register(Offset=0x24U)] internal uint GPCR; // GPIO Pin Output Clear register [Register(Offset=0x30U)] internal uint GRER; // GPIO Rising-Edge Detect Enable register [Register(Offset=0x3CU)] internal uint GFER; // GPIO Falling-Edge Detect Enable register [Register(Offset=0x48U)] internal uint GEDR; // GPIO Edge Detect Status register #pragma warning restore 649 // // Helper Methods // [Inline] internal void ConfigureAsInput( int pin ) { uint mask = 1u << (pin & 31); this.GPDR &= ~mask; } [Inline] internal void ConfigureAsOutput( int pin ) { uint mask = 1u << (pin & 31); this.GPDR |= mask; } [Inline] internal void ConfigureInterrupt( int pin , bool raisingEdge , bool fallingEdge ) { uint mask = 1u << (pin & 31); if(raisingEdge) { this.GRER |= mask; } else { this.GRER &= ~mask; } if(fallingEdge) { this.GFER |= mask; } else { this.GFER &= ~mask; } this.GEDR = mask; // Clear any pending interrupt for pin } [Inline] internal bool InterruptPending( int pin , bool clear ) { uint mask = 1u << (pin & 31); var res = this.GEDR & mask; if(res == 0) { return false; } if(clear) { this.GEDR = res; //write with 1-bits clears associated interrupts } return true; } [Inline] internal bool GetState( int pin ) { uint mask = 1u << (pin & 31); return (this.GPLR & mask) != 0; } [Inline] internal void SetState( int pin , bool fSet ) { uint mask = 1u << (pin & 31); if(fSet) { this.GPSR |= mask; } else { this.GPCR |= mask; } } } [MemoryMappedPeripheral(Base=0x0U,Length=0x0000004CU)] class AltFunctionCluster { [Register(Offset=0x00U)] internal uint GAFR_L; // GPIO Alternate Function register [Register(Offset=0x04U)] internal uint GAFR_H; // GPIO Alternate Function register // // Helper Methods // internal void Set( int pin , uint mode ) { pin %= 32; int shift = (pin % 16) * 2; uint mask = 3u << shift; uint val = mode << shift; if(pin < 16) { this.GAFR_L = (this.GAFR_L & ~mask) | (val & mask); } else { this.GAFR_H = (this.GAFR_H & ~mask) | (val & mask); } } } #pragma warning disable 649 [Register(Offset=0x000U)] private Cluster m_pin000_031; [Register(Offset=0x004U)] private Cluster m_pin032_063; [Register(Offset=0x008U)] private Cluster m_pin064_095; [Register(Offset=0x100U)] private Cluster m_pin096_120; [Register(Offset=0x054U)] private AltFunctionCluster m_altFunc000_031; [Register(Offset=0x05CU)] private AltFunctionCluster m_altFunc032_063; [Register(Offset=0x064U)] private AltFunctionCluster m_altFunc064_095; [Register(Offset=0x06CU)] private AltFunctionCluster m_altFunc096_120; #pragma warning restore 649 //--// // // Helper Methods // public void EnableAsInputAlternateFunction( int pin , int mode ) { var altFunc = GetAltFunctionCluster( pin ); altFunc.Set( pin, (uint)mode ); //--// var cls = GetCluster( pin ); cls.ConfigureAsInput( pin ); } public void EnableAsOutputAlternateFunction( int pin , int mode , bool fSet ) { var altFunc = GetAltFunctionCluster( pin ); altFunc.Set( pin, (uint)mode ); //--// var cls = GetCluster( pin ); cls.SetState ( pin, fSet ); cls.ConfigureAsOutput( pin ); } public void EnableAsInputPin( int pin ) { EnableAsInputAlternateFunction( pin, 0 ); } public void EnableAsOutputPin( int pin , bool fSet ) { EnableAsOutputAlternateFunction( pin, 0, fSet ); } public void ConfigureInterrupt( int pin , bool raisingEdge , bool fallingEdge ) { var cls = GetCluster(pin); cls.ConfigureInterrupt( pin, raisingEdge, fallingEdge ); } public bool InterruptPending( int pin , bool clear ) { var cls = GetCluster(pin); return cls.InterruptPending( pin, clear ); } //--// Cluster GetCluster( int pin ) { switch(pin / 32) { case 0: return this.m_pin000_031; case 1: return this.m_pin032_063; case 2: return this.m_pin064_095; case 3: return this.m_pin096_120; } BugCheck.Raise( BugCheck.StopCode.IncorrectArgument ); return null; } AltFunctionCluster GetAltFunctionCluster( int pin ) { switch(pin / 32) { case 0: return this.m_altFunc000_031; case 1: return this.m_altFunc032_063; case 2: return this.m_altFunc064_095; case 3: return this.m_altFunc096_120; } BugCheck.Raise( BugCheck.StopCode.IncorrectArgument ); return null; } // // Access Methods // public static extern GPIO Instance { [SingletonFactory()] [MethodImpl( MethodImplOptions.InternalCall )] get; } public bool this[int pin] { get { var cls = GetCluster( pin ); BugCheck.Assert(null != cls, BugCheck.StopCode.IncorrectArgument); return cls.GetState( pin ); } set { var cls = GetCluster( pin ); BugCheck.Assert(null != cls, BugCheck.StopCode.IncorrectArgument); cls.SetState( pin, value ); } } } } ================================================ FILE: Zelig/Zelig/RunTime/DeviceModels/ModelForPXA27x/HardwareModel/ChipSet/PXA27x/I2C.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // namespace Microsoft.DeviceModels.Chipset.PXA27x { using System.Runtime.CompilerServices; using Microsoft.Zelig.Runtime; /// /// The I2C subsystem of the XScale271 /// /// /// The serial I2C bus has a two-pin interface. The serial data and address (SDA) data pin serves I/O /// functions, and the serial clock line (SCL) clock pin controls and references the I2C bus. The I2C /// interface allows the PXA27x processor to serve as a master and slave device on the I2C bus. /// The I2C interface enables the PXA27x processor to communicate with I2C peripherals and /// microcontrollers for system management functions. The I2C bus requires a minimum of hardware /// to relay status, reliability, and control information between devices. ///

/// The I2C unit includes the following features: /// /// I2C compliant (see the I2C-Bus Specification, Version 2.0) /// Multi-master and arbitration support /// Standard-speed operation at 100 kbps. /// Fast-mode operation at 400 kbps. /// ///

/// I2C Modes of Operation: /// While the I2C interface is idle, it defaults to slave-receive mode. This allows the interface to /// monitor the bus and receive any slave addresses intended for the processor I2C interface. /// When the I2C interface receives an address that matches the seven-bit address in the I2C Slave /// Address register (ISAR) or the general call address (127), the interface either /// remains in slave-receive mode or switches to slave-transmit mode. The Read/Write bit (R/nW) /// determines which mode the interface enters. The R/nW bit is the least significant bit of the byte /// containing the slave address. If R/nW is clear, the master that initiated the transaction intends to /// write data, and the I2C interface remains in slave-receive mode. If the R/nW bit is set, the master /// that initiated the transaction intends to read data, and the I2C interface switches to slave-transmit /// mode. ///

/// When the PXA27x processor initiates a read or write on the I2C bus, it switches the interface from /// the default slave-receive mode to the master-transmit mode. If the transaction is a write, the I2C /// interface remains in master-transmit mode after the address transfer is completed. If the transaction /// is a read, the I2C interface transmits the slave address, then switches to master-receive mode. /// [MemoryMappedPeripheral(Base = 0x40301680U, Length = 0x00002000U)] public class I2C { #region IBMR Bitfield ///

/// This register contains the current (physical) levels /// of the SDA and SCL pins. /// /// /// The I2C Bus Monitor register (IBMR) tracks the status of the SCL and SDA pins. The values of /// these pins are recorded in this read-only IBMR so software can determine when the I2C bus is hung /// and the I2C unit must be reset. /// [BitFieldPeripheral(PhysicalType = typeof(uint))] public struct IBMR_Bitfield { /// /// SCL pin value /// [BitFieldRegister(Position = 1, Modifiers = BitFieldModifier.ReadOnly)] public bool SCL; /// /// SDA pin value /// [BitFieldRegister(Position = 0, Modifiers = BitFieldModifier.ReadOnly)] public bool SDA; } #endregion #region ICR Bitfield /// /// This is the I2C configuration register. /// use it to configure, enable/disable communication speed, /// interrupts, and device state. /// [BitFieldPeripheral(PhysicalType = typeof(uint))] public struct ICR_Bitfield { /// /// Fast Mode. /// /// /// ICR (Standard I2C): /// 0 = 100 kbps operation /// 1 = 400 kbps operation /// [BitFieldRegister(Position = 15)] public bool FM; /// /// unit reset. /// /// /// 0 = No reset. /// 1 = Reset the I2C interface only. /// [BitFieldRegister(Position = 14)] public bool UR; /// /// Slave address detected interupt enable /// /// /// 0 = Disable interrupt. /// 1 = Enables the I2C interface to interrupt the processor upon detecting a /// slave address match or a general call address. /// /// [BitFieldRegister(Position = 13)] public bool SADIE; /// /// Arbitration loss detected interrupt enable /// /// /// 0 = Disable interrupt. /// 1 = Enables the I2C interface to interrupt the processor upon losing /// arbitration while in master mode. /// note: setting this to false will enable the automatic /// arbitration logic in the I2C controller. In case /// of a lost arbitration, it will re-try the operation /// again after the bus has been given up by the winning /// I2C master. /// [BitFieldRegister(Position = 12)] public bool ALDIE; /// /// Slave stop detected interrupt enable /// /// /// 0 = Disable interrupt. /// 1 = Enables the I2C interface to interrupt the processor when it detects a /// STOP condition while in slave mode. /// [BitFieldRegister(Position = 11)] public bool SSDIE; /// /// Bus error interrupt enable /// /// /// 0 = Disable interrupt. /// 1 = Enables the I2C interface to interrupt the processor for the following /// I2C bus errors: /// /// As a master transmitter, no Ack was detected after a byte was sent. /// As a slave receiver, the I2C interface generated a NAK pulse. /// /// NOTE: Software is responsible for guaranteeing that misplaced START /// and STOP conditions do not occur. /// [BitFieldRegister(Position = 10)] public bool BEIE; /// /// Data Buffer Register (IDBR) receive interrupt enable /// /// /// 0 = Disable interrupt. /// 1 = Enables the I2C interface to interrupt the processor when the IDBR /// has received a data byte from the I2C bus. /// [BitFieldRegister(Position = 9)] public bool DRFIE; /// /// IDBR transit empty interrupt enable /// /// /// 0 = Disable interrupt. /// 1 = Enables the I2C interface to interrupt the processor after transmitting /// a byte onto the I2C bus. /// [BitFieldRegister(Position = 8)] public bool ITEIE; /// /// General call disable. /// /// /// 0 = Enable the I2C interface to respond to general call messages (127). /// 1 = Disable I2C interface response to general call messages as a slave. /// This bit must be set when sending a master mode general call message /// from the I2C interface. /// note: appliations should usually set this bit. /// [BitFieldRegister(Position = 7)] public bool GCD; /// /// I2C unit enable /// /// /// 0 = Disables the unit and does not master any transactions or respond to /// any slave transactions. /// 1 = Enables the I2C interface (defaults to slave-receive mode). /// Software must guarantee the I2C bus is idle before setting this bit. /// Software must guarantee that the internal clock to the Power I2C unit is /// enabled (CKEN[15] must be set) before setting or clearing this bit. /// [BitFieldRegister(Position = 6)] public bool IUE; /// /// SCL enable /// /// /// 0 = Disables the I2C interface from driving the SCL line. /// 1 = Enables the I2C clock output for master-mode operation. /// [BitFieldRegister(Position = 5)] public bool SCLE; /// /// MASTER ABORT /// /// /// Used by the I2C interface in master mode to generate a STOP without /// transmitting another data byte: /// 0 = The I2C interface transmits STOP using the ICR[STOP] bit only. /// 1 = The I2C interface sends STOP without data transmission. /// When in master-transmit mode, after transmitting a data byte, the ICR /// transfer byte bit is cleared and IDBR transmit empty bit is set. When no /// more data bytes need to be sent, setting master abort bit sends the STOP. /// The transfer byte bit (03) must remain clear. /// In master-receive mode, when a Nack is sent without a STOP (stopICR bit /// was not set) and the processor does not send a repeated START, setting /// this bit sends the STOP. Once again, the transfer byte bit (03) must remain /// clear. [BitFieldRegister(Position = 4)] public bool MA; /// /// Transfer Byte command /// /// /// Sends or receives a byte on the I2C bus: /// 0 = Cleared by I2C interface when the byte is sent/received. /// 1 = Send/receive a byte. /// The processor can monitor this bit to determine when the byte transfer has /// completed. In master or slave mode, after each byte transfer including /// ACKNOWLEDGE pulse, the I2C interface holds the SCL line low (inserting /// wait states) until TB is set. [BitFieldRegister(Position = 3)] public bool TB; /// /// POS/NEG ACK /// ACK, if true /// NACK, if false /// /// /// Defines the type of ACKNOWLEDGE pulse sent by the I2C interface when /// in master receive mode: /// 0 = Send a positive acknowledge (ACK) pulse after receiving a data byte. /// 1 = Send a negative acknowledge (NAK) pulse after receiving a data /// byte. /// The I2C interface automatically sends an ACK pulse when responding to its /// slave address or when responding in slave-receive mode, regardless of the /// ACKNAK control-bit setting. [BitFieldRegister(Position = 2)] public bool ACKNAK; /// /// Sends STOP indication after next byte in master mode. /// /// /// Initiates a STOP condition after transferring the next data byte on the I2C /// bus when in master mode. In master-receive mode, the ACKNAK control bit /// must be set in conjunction with the STOP bit. See Section 9.4.3.3 for details /// of the STOP state. /// 0 = Do not send a STOP. /// 1 = Send a STOP [BitFieldRegister(Position = 1)] public bool STOP; /// /// Sends START indication in master mode before the next /// byte sent on the I2C bus. /// /// /// Initiates a START condition I2C when in master mode. /// 0 = Do not send a START pulse. /// 1 = Send a START pulse. /// [BitFieldRegister(Position = 0)] public bool START; } #endregion #region ISR Bitfield /// /// This is the I2C status register. /// Use it to retrieve bus error conditions, /// status changes, or clear interrupt conditions. /// /// /// The ISR signals I2C interrupts to the PXA27x processor interrupt controller. Software can use the /// ISR bits to check the status of the I2C unit and bus. ISR bits [9:5] are updated after the ACK/NAK /// bit is completed on the I2C bus. ///

/// The ISR also clears the following interrupts signaled from the I2C interface: /// /// IDBR receive full /// IDBR transmit empty /// Slave-address detected /// Bus error detected /// STOP condition detected /// Arbitration lost /// /// [BitFieldPeripheral(PhysicalType = typeof(uint))] public struct ISR_Bitfield { ///

/// BUS ERROR detected /// /// /// The I2C interface sets this bit when it detects one of the following error conditions: /// /// As a master transmitter, no Ack was detected on the interface after a /// byte was sent. /// As a slave receiver, the I2C interface generates a Nack pulse. /// ///

/// note: When an error occurs, I2C bus transactions continue. Software /// must guarantee that misplaced START and STOP conditions do /// not occur. ///

/// note: This bit is cleared on Read! /// [BitFieldRegister(Position = 10, Modifiers = BitFieldModifier.ReadOnly)] public bool BED; ///

/// Slave address detected /// /// /// The I2C interface detected a seven-bit address that matches the /// general call address or ISAR. An interrupt is signaled when enabled in /// the ICR. ///

/// note: This bit is cleared on Read! /// [BitFieldRegister(Position = 9, Modifiers = BitFieldModifier.ReadOnly)] public bool SAD; ///

/// General call address detected /// /// /// 0 = No general call address received. /// 1 = I2C interface received a general call address (127). ///

/// note: This bit is cleared on Read! /// [BitFieldRegister(Position = 8, Modifiers = BitFieldModifier.ReadOnly)] public bool GCAD; ///

/// receive full indication. /// /// /// 0 = The IDBR has not received a new data byte or the I2C interface is idle. /// 1 = The IDBR register received a new data byte from the I2C bus. An /// interrupt is signaled when enabled in the ICR. ///

/// note: This bit is cleared on Read! /// [BitFieldRegister(Position = 7, Modifiers = BitFieldModifier.ReadOnly)] public bool IRF; ///

/// transmit empty indication. /// /// /// 0 = The data byte is still being transmitted. /// 1 = The I2C interface has finished transmitting a data byte on the I2C bus. /// An interrupt is signaled when enabled in the ICR. ///

/// note: This bit is cleared on Read! /// [BitFieldRegister(Position = 6, Modifiers = BitFieldModifier.ReadOnly)] public bool ITE; ///

/// Arbitration loss detected indication. /// /// /// Used during multi-master operation: /// 0 = Cleared when arbitration is won or never took place. /// 1 = Set when the I2C interface loses arbitration. ///

/// note: This bit is cleared on Read! /// [BitFieldRegister(Position = 5, Modifiers = BitFieldModifier.ReadOnly)] public bool ALD; ///

/// Slave stop detected indication. /// /// /// 0 = No STOP detected. /// 1 = Set when the I2C interface detects a STOP while in slave-receive or /// slave-transmit mode. ///

/// note: This bit is cleared on Read! /// [BitFieldRegister(Position = 4, Modifiers = BitFieldModifier.ReadOnly)] public bool SSD; ///

/// I2C bus busy /// /// /// 0 = I2C bus is idle or the I2C interface is using the bus (unit busy). /// 1 = Set when the I2C bus is busy but the processors I2C interface is not /// involved in the transaction. /// [BitFieldRegister(Position = 3, Modifiers = BitFieldModifier.ReadOnly)] public bool IBB; /// /// Unit busy /// /// /// 0 = I2C interface not busy. /// 1 = Set when the processors I2C interface is busy. This is defined as the /// time between the first START and STOP. /// [BitFieldRegister(Position = 2, Modifiers = BitFieldModifier.ReadOnly)] public bool UB; /// /// ACK/NAK status indication. /// /// /// 0 = The I2C interface received or sent an Ack on the bus. /// 1 = The I2C interface received or sent a Nack. ///

/// Used in slave-transmit mode to determine when the byte transferred is the /// last one. This bit is updated after each byte and Ack/Nack information is /// received. /// [BitFieldRegister(Position = 1, Modifiers = BitFieldModifier.ReadOnly)] public bool ACKNAK; ///

/// read/write mode /// /// /// 0 = The I2C interface is in master-transmit or slave-receive mode. /// 1 = The I2C interface is in master-receive or slave-transmit mode. ///

/// This is the R/nW bit of the slave address. It is automatically cleared by /// hardware after a STOP state. /// [BitFieldRegister(Position = 0, Modifiers = BitFieldModifier.ReadOnly)] public bool RWM; } #endregion #region Register Bank ///

/// I2C Bus Monitor Register /// /// [Register(Offset = 0x00000000U, Instances = 1)] public IBMR_Bitfield IBMR; /// /// Data buffer register. /// valid data is in (IDBR and 0x000000FF) /// /// /// The PXA27x processor uses the I2C Data Buffer register to transmit and receive data from the I2C /// bus. The IDBR is accessed by the programmed I/O on one side and by the I2C shift register on the /// other. The IDBR receives data coming into the I2C unit after a full byte is received and /// acknowledged. The processor core writes data going out of the I2C interface to the IDBR and sends /// it to the serial bus. /// When the I2C interface is in transmit mode (master or slave), the processor writes data to the IDBR /// over the internal bus. The processor writes data to the IDBR when a master transaction is initiated /// or when the IDBR transmit-empty interrupt is signaled. Data moves from the IDBR to the shift /// register when the Transfer Byte bit is set. The IDBR transmit-empty interrupt is signaled (if /// enabled) when a byte is transferred on the I2C bus and the acknowledge cycle is complete. If the /// IDBR is not written by the processor and a STOP condition is not in place before the I2C bus is /// ready to transfer the next byte packet, the I2C unit inserts wait states until the processor writes the /// IDBR and sets the Transfer Byte bit. /// When the I2C interface is in receive mode (master or slave), the processor reads IDBR data over /// the internal bus. The processor reads data from the IDBR when the IDBR receive-full interrupt is /// signaled. The data moves from the shift register to the IDBR when the ACKNOWLEDGE cycle is /// complete. The I2C interface inserts wait states until the IDBR is read. See SlaveMode for more /// information on the ACKNOWLEDGE pulse in receive mode. After the processor reads the IDBR, /// ICR[ACKNAK] and ICR[ACKNAK] are written, allowing the next byte transfer to proceed to the I2C bus. /// [Register(Offset = 0x00000008U, Instances = 1)] public uint IDBR; /// /// The PXA27x processor uses the bits in the I2C Control register (ICR) to control the I2C unit. /// [Register(Offset = 0x00000010U, Instances = 1)] public ICR_Bitfield ICR; /// /// The ISR signals I2C interrupts to the PXA27x processor interrupt controller. Software can use the /// ISR bits to check the status of the I2C unit and bus. ISR bits [9:5] are updated after the ACK/NAK /// bit is completed on the I2C bus. /// [Register(Offset = 0x00000018U, Instances = 1)] public ISR_Bitfield ISR; /// /// Slave address register. /// valid address data is in the lowest 7 bits. /// /// /// The ISAR defines the I2C interfaces seven-bit slave address. In slave-receive /// mode, the PXA27x processor responds when the seven-bit address matches the value in this /// register. The processor writes this register before it enables I2C operations. The ISAR is fully /// programmable (no address is assigned to the I2C interface) so it can be set to a value other than /// those of hard-wired I2C slave peripherals in the system. If the processor is reset, the ISAR is not /// affected. The ISAR register default value is 00000002. /// [Register(Offset = 0x00000020U, Instances = 1)] public uint ISAR; #endregion #region Singleton data /// /// The GPIO pin for the I2C SCL line. /// public const int PIN_I2C_SCL = 117; /// /// The GPIO pin for the SDA SCL line. /// public const int PIN_I2C_SDA = 118; #if TESTMODE_DESKTOP private static I2C s_instance; public static I2C Instance { get { if (null != s_instance) return s_instance; s_instance = new I2C(); s_instance.IBMR = new IBMR_Bitfield(); s_instance.ICR = new ICR_Bitfield(); s_instance.IDBR=0; s_instance.ISAR =2; s_instance.ISR = new ISR_Bitfield(); return s_instance; } } #else /// /// The singleton for the I2C subsystem. /// public static extern I2C Instance { [SingletonFactory()] [MethodImpl(MethodImplOptions.InternalCall)] get; } #endif #endregion } } ================================================ FILE: Zelig/Zelig/RunTime/DeviceModels/ModelForPXA27x/HardwareModel/ChipSet/PXA27x/InterruptController.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // namespace Microsoft.DeviceModels.Chipset.PXA27x { using System; using System.Runtime.CompilerServices; using Microsoft.Zelig.Runtime; [MemoryMappedPeripheral(Base=0x40D00000U,Length=0x000000D0U)] public class InterruptController { public const int IRQ_INDEX_SSP_3 = 0 + 0; public const int IRQ_INDEX_MSL = 0 + 1; public const int IRQ_INDEX_USB_HOST_2 = 0 + 2; public const int IRQ_INDEX_USB_HOST_1 = 0 + 3; public const int IRQ_INDEX_KEYPAD_CTRL = 0 + 4; public const int IRQ_INDEX_MEMORY_STICK = 0 + 5; public const int IRQ_INDEX_PWR_I2C = 0 + 6; public const int IRQ_INDEX_OS_TIMER = 0 + 7; public const int IRQ_INDEX_GPIO0 = 0 + 8; public const int IRQ_INDEX_GPIO1 = 0 + 9; public const int IRQ_INDEX_GPIOx = 0 + 10; public const int IRQ_INDEX_USB_CLIENT = 0 + 11; public const int IRQ_INDEX_PMU = 0 + 12; public const int IRQ_INDEX_I2S = 0 + 13; public const int IRQ_INDEX_AC97 = 0 + 14; public const int IRQ_INDEX_USIM = 0 + 15; public const int IRQ_INDEX_SSP_2 = 0 + 16; public const int IRQ_INDEX_LCD = 0 + 17; public const int IRQ_INDEX_I2C = 0 + 18; public const int IRQ_INDEX_INFRA_RED_COM = 0 + 19; public const int IRQ_INDEX_STUART = 0 + 20; public const int IRQ_INDEX_BTUART = 0 + 21; public const int IRQ_INDEX_FFUART = 0 + 22; public const int IRQ_INDEX_FLASH_CARD = 0 + 23; public const int IRQ_INDEX_SSP_1 = 0 + 24; public const int IRQ_INDEX_DMA_CTRL = 0 + 25; public const int IRQ_INDEX_OS_TIMER0 = 0 + 26; public const int IRQ_INDEX_OS_TIMER1 = 0 + 27; public const int IRQ_INDEX_OS_TIMER2 = 0 + 28; public const int IRQ_INDEX_OS_TIMER3 = 0 + 29; public const int IRQ_INDEX_RTC_1HZ_TIC = 0 + 30; public const int IRQ_INDEX_RTC_ALARM = 0 + 31; public const int IRQ_INDEX_TRUSTED_PLFM = 32 + 0; public const int IRQ_INDEX_QK_CAP = 32 + 1; public const int IRQ_INDEX_MAX = 34; [BitFieldPeripheral(PhysicalType=typeof(uint))] public struct ICCR_bitfield { [BitFieldRegister(Position=0)] public bool DIM; // 0 = Any interrupt in ICPR brings the processor out of idle mode. // 1 = Only active, unmasked interrupts (as defined in the ICMR) bring the processor out of idle mode. Cleared during resets. } [BitFieldPeripheral(PhysicalType=typeof(uint))] public struct ICHP_bitfield { [BitFieldRegister(Position=31 )] public bool VAL_IRQ; // Valid IRQ // // 0 = No valid peripheral ID that is causing an IRQ interrupt. // 1 = Valid peripheral ID is causing an IRQ interrupt. // [BitFieldRegister(Position=16,Size=6)] public uint IRQ; // IRQ Highest Priority Field // // Peripheral ID with the highest IRQ priority. // When no interrupt has occurred, this bit is set to 1. // [BitFieldRegister(Position=15 )] public bool VAL_FIQ; // Valid FIQ // // 0 = No valid peripheral ID that is causing an FIQ interrupt. // 1 = Valid peripheral ID is causing an FIQ interrupt. // [BitFieldRegister(Position= 0,Size=6)] public uint FIQ; // FIQ Highest Priority Field // // Peripheral ID with the highest FIQ priority. // When no interrupt has occurred, this bit is set to 1. // } [BitFieldPeripheral(PhysicalType=typeof(uint))] public struct IPR_bitfield { [BitFieldRegister(Position=31 )] public bool VAL; // Valid Bit // // 0 = Peripheral ID contained in the register is not valid. // 1 = Peripheral ID contained in the register is valid. // [BitFieldRegister(Position=0,Size=6)] public uint PID; // Peripheral ID for this Priority IPR[n] // // Peripheral ID of peripheral with priority n (n=IPR number). Valid IDs: 0 through 39 // } [Register(Offset=0x14U )] public ICCR_bitfield ICCR; // Interrupt Controller Control register | 25-27 [Register(Offset=0x18U )] public ICHP_bitfield ICHP; // Interrupt Controller Highest Priority register | 25-30 [Register(Offset=0x00U )] public uint ICIP; // Interrupt Controller IRQ Pending register | 25-11 [Register(Offset=0x04U )] public uint ICMR; // Interrupt Controller Mask register | 25-20 [Register(Offset=0x08U )] public uint ICLR; // Interrupt Controller Level register | 25-24 [Register(Offset=0x0CU )] public uint ICFP; // Interrupt Controller FIQ Pending register | 25-15 [Register(Offset=0x10U )] public uint ICPR; // Interrupt Controller Pending register | 25-6 [Register(Offset=0x1CU,Instances=32)] public IPR_bitfield[] IPR0_31; // Interrupt Priority registers for Priorities 031 | 25-29 [Register(Offset=0x9CU )] public uint ICIP2; // Interrupt Controller IRQ Pending register 2 | 25-10 [Register(Offset=0xA0U )] public uint ICMR2; // Interrupt Controller Mask register 2 | 25-23 [Register(Offset=0xA4U )] public uint ICLR2; // Interrupt Controller Level register 2 | 25-27 [Register(Offset=0xA8U )] public uint ICFP2; // Interrupt Controller FIQ Pending register 2 | 25-19 [Register(Offset=0xACU )] public uint ICPR2; // Interrupt Controller Pending register 2 | 25-6 [Register(Offset=0xB0U,Instances= 8)] public IPR_bitfield[] IPR32_39; // Interrupt Priority registers for Priorities 3239 | 25-29 // // Helper Methods // [Inline] public void SetPriority( uint irqIndex , int priority ) { if(priority < 32) { this.IPR0_31[priority] = new IPR_bitfield { VAL = true, PID = irqIndex, }; } else if(priority < 64) { this.IPR32_39[priority-32] = new IPR_bitfield { VAL = true, PID = irqIndex, }; } } // // Access Methods // public static extern InterruptController Instance { [SingletonFactory()] [MethodImpl( MethodImplOptions.InternalCall )] get; } } } ================================================ FILE: Zelig/Zelig/RunTime/DeviceModels/ModelForPXA27x/HardwareModel/ChipSet/PXA27x/MemoryController.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // namespace Microsoft.DeviceModels.Chipset.PXA27x { using System; using System.Runtime.CompilerServices; using Microsoft.Zelig.Runtime; [MemoryMappedPeripheral(Base=0x48000000U,Length=0x00000068U)] public class MemoryController { [BitFieldPeripheral(PhysicalType=typeof(uint))] public struct MDCNFG_bitfield { public enum Timing : uint { Setting0 = 0, // tRP = 2 clks, CL = 2, tRCD = 1 clks, tRASMIN = 3 clks, tRC = 4 clks Setting1 = 1, // tRP = 2 clks, CL = 2, tRCD = 2 clks, tRASMIN = 5 clks, tRC = 8 clks Setting2 = 2, // tRP = 3 clks, CL = 3, tRCD = 3 clks, tRASMIN = 7 clks, tRC = 10 clks Setting3 = 3, // tRP = 3 clks, CL = 3, tRCD = 3 clks, tRASMIN = 7 clks, tRC = 11 clks } public enum RowAddress : uint { Use11Bits = 0, // 0b00 = 11 row address bits Use12Bits = 1, // 0b01 = 12 row address bits Use13Bits = 2, // 0b10 = 13 row address bits // 0b11 = reserved } public enum ColumnAddress : uint { Use8Bits = 0, // 0b000 = 8 column address bits Use9Bits = 1, // 0b001 = 9 column address bits Use10Bits = 2, // 0b010 = 10 column address bits Use11Bits = 3, // 0b011 = 11 column address bits Use12Bits = 4, // 0b100 = 12 column address bits } public enum Stack : uint { None , // 0b00 = SDRAM address is placed on MA<24:10>. See Table 6-3, Table 6-5 and Table 6-7. SDRAMplusFLASH, // 0b01 = SDRAM address is placed on MA<24:23,13:1>. Use when flash internal to the PXA271 processor has 16-bit total data bus width on partition 0. See Table 6-4 and Table 6-6. // 0b10 = reserved // 0b11 = reserved } [BitFieldRegister (Position=31 )] public bool MDENX; // SDRAM 1 GB Memory Map Enable // // 0 = Use normal 256-Mbyte memory map. // 1 = Use large 1-Gbyte memory map. // [BitFieldRegister (Position=28 )] public bool DSA1110_2; // SA-1110 Addressing Mode Compatibility // // Use SA-1110 addressing multiplexing mode for pair 2/3. Setting this bit // overrides the addressing bit programmed in MDCNFG[DADDR2] // // For an explanation of how the address is driven onto the address bus in SA- // 1110 addressing mode, see Table 6-7. // // 0 = Use addressing mode specified in MDCNFG[DADDR2]. // 1 = Override the addressing bit programmed in MDCNFG[DADDR2] and use SA-1110 addressing mode. // [BitFieldRegister (Position=27,WritesAs=1 )] public bool SET2; // Set Reserved Bit // Always set this bit // [BitFieldRegister (Position=26 )] public bool DADDR2; // Alternate Addressing Mode // // Ignored if MDCNFG[DSA1110_2] is set. // For an explanation of how the address is driven onto the address bus for the partition pair 2/3 in alternate addressing mode, see Figure 6-3. // // 0 = Use normal addressing mode // 1 = Use alternate addressing mode // [BitFieldRegister (Position=24,Size=2 )] public Timing DTC2; // The AC timing parameters for SDRAM partition pair 2/3 represent the // number of SDCLKs (not memory clocks) for the clocks indicated below. // See the SDRAM data sheet to determine the optimal timings. // See the Intel PXA27x Processor Family EMTS for SDRAM timing diagrams and the effects on AC timings. // For all timing categories, write recovery time (tWR) is hard-coded at 2 clocks. // // NOTE: The CAS latency programmed here is set to 3 if the CAS latency // for SDRAM partition pair 0 (MDCNFG[DTC0] CAS latency) is // programmed to 3. Otherwise, it is set as programmed here. What // this means is that the CAS latency for the two SDRAM partition // pairs is the same and equals the greater of the two programmed // values. If either partition pair is programmed to CAS latency of 3, // then both partition pairs have CAS Latency of 3; otherwise, both // partition pairs have CAS latency of 2. // [BitFieldRegister (Position=23 )] public bool DNB2; // Number of Banks in Partition Pair 2/3 // // 0 = 2 internal SDRAM banks // 1 = 4 internal SDRAM banks // [BitFieldRegister (Position=21,Size=2 )] public RowAddress DRAC2; // SDRAM Row Address Bit Count for Partition Pair 2/3 // [BitFieldSplitRegister(Position=30,Size=1,Offset=2)] // [BitFieldSplitRegister(Position=19,Size=2,Offset=0)] public ColumnAddress DCAC2; // SDRAM Column Address Bits for Partition Pair 2/3 // [BitFieldRegister (Position=18 )] public bool DWID2; // SDRAM Data Bus Width for Partition Pair 2/3 // // 0 = 32 bits // 1 = 16 bits // [BitFieldRegister (Position=17 )] public bool DE3; // SDRAM Enable for Partition 3 // // A single (non-burst) 32-bit (or 16-bit if MDCNFG[DWIDx] = 1) access (read or write) to a disabled SDRAM partition triggers a CBR refresh cycle to all // partitions. When all partitions are disabled, the refresh counter is disabled. // // 0 = SDRAM partition disabled // 1 = SDRAM partition enabled // [BitFieldRegister (Position=16 )] public bool DE2; // SDRAM Enable for Partition 2 // // A single (non-burst) 32-bit (or 16-bit if MDCNFG[DWIDx] = 1) access (read or write) to a disabled SDRAM partition triggers a CBR refresh cycle to all // partitions. When all partitions are disabled, the refresh counter is disabled. // // 0 = SDRAM partition disabled // 1 = SDRAM partition enabled // [BitFieldSplitRegister(Position=15,Size=1,Offset=1)] // [BitFieldSplitRegister(Position=13,Size=1,Offset=0)] public Stack STACK; // The 2-bit STACK field consists of MDCNFG[STACK1] (MSB) and MDCNFG[STACK0] (LSB) to determine the SDRAM address-multiplexing scheme. // This 2-bit setting alters the SDRAM multiplexing scheme for all SDRAM partitions as shown below. // // NOTE: When MDCNFG[STACKx] equals either 0b01 or 0b10, fly-by DMA transfers are not supported, // and SA1110 addressing mode is not supported, DASA1110_0 must be cleared. // [BitFieldRegister (Position=12 )] public bool DSA1110_0; // SA-1110 Addressing Mode Compatibility // // Use SA-1110 addressing multiplexing mode for pair 0/1. Setting this bit overrides the addressing bit programmed in MDCNFG[DADDR0]. // For an explanation of how the address is driven onto the address bus in SA-1110 addressing mode, see Table 6-7. // // 0 = Use addressing mode specified in MDCNFG[DADDR0] // 1 = Use SA-1110 addressing mode // [BitFieldRegister (Position=11,WritesAs=1 )] public bool SET0; // Set Reserved Bit // Always set this bit // [BitFieldRegister (Position=10 )] public bool DADDR0; // Alternate Addressing Mode // // Ignored if MDCNFG[DSA1110_0] is set. // For an explanation of how the address is driven onto the address bus for the partition pair 0/1 in alternate addressing mode, see Figure 6-3. // // 0 = Use normal addressing mode // 1 = Use alternate addressing mode // [BitFieldRegister (Position= 8,Size=2 )] public Timing DTC0; // The AC timing parameters for SDRAM partition pair 0/1 represent the // number of SDCLKs (not memory clocks) for the clocks indicated below. // See the SDRAM data sheet to determine the optimal timings. // See the Intel PXA27x Processor Family EMTS for SDRAM timing diagrams and the effects on AC timings. // For all timing categories, write recovery time (tWR) is hard-coded at 2 clocks. // // NOTE: The CAS latency programmed here is set to 3 if the CAS latency // for SDRAM partition pair 2 (MDCNFG[DTC2] CAS latency) is // programmed to 3. Otherwise, it is set as programmed here. What // this means is that the CAS latency for the two SDRAM partition // pairs is the same and equals the greater of the two programmed // values. If either partition pair is programmed to CAS latency of 3, // then both partition pairs have CAS Latency of 3; otherwise, both // partition pairs have CAS latency of 2. // [BitFieldRegister (Position= 7 )] public bool DNB0; // Number of Banks in Partition Pair 0/1 // // 0 = 2 internal SDRAM banks // 1 = 4 internal SDRAM banks // [BitFieldRegister (Position= 5,Size=2 )] public RowAddress DRAC0; // SDRAM Row Address Bit Count for Partition Pair 0/1 // [BitFieldSplitRegister(Position=14,Size=1,Offset=2)] // [BitFieldSplitRegister(Position= 3,Size=2,Offset=0)] public ColumnAddress DCAC0; // SDRAM Column Address Bits for Partition Pair 0/1 // [BitFieldRegister (Position= 2 )] public bool DWID0; // SDRAM Data Bus Width for Partition Pair 0/1 // // 0 = 32 bits // 1 = 16 bits // [BitFieldRegister (Position= 1 )] public bool DE1; // SDRAM Enable for Partition 1 // // A single (non-burst) 32-bit (or 16-bit if MDCNFG[DWIDx] = 1) access (read or write) to a disabled SDRAM partition triggers a CBR refresh cycle to all // partitions. When all partitions are disabled, the refresh counter is disabled. // // 0 = SDRAM partition disabled // 1 = SDRAM partition enabled // [BitFieldRegister (Position= 0 )] public bool DE0; // SDRAM Enable for Partition 0 // // A single (non-burst) 32-bit (or 16-bit if MDCNFG[DWIDx] = 1) access (read or write) to a disabled SDRAM partition triggers a CBR refresh cycle to all // partitions. When all partitions are disabled, the refresh counter is disabled. // // 0 = SDRAM partition disabled // 1 = SDRAM partition enabled } [BitFieldPeripheral(PhysicalType=typeof(uint))] public struct MDMRS_bitfield { [BitFieldRegister(Position=23,Size=8)] public uint MDMRS2; // The SDRAM MRS bits represent the value driven onto the SDRAM address // bus from MA<24:17> (or MA<24:23,14:9> or MA<24:23,13,8>, depending // on MDCNFG[STACKx] setting) during the MRS command for partition pair 2/3. // [BitFieldRegister(Position=20,Size=3)] public uint MDCL2; // SDRAM MRS bits representing CAS Latency // SDRAM partition pair 2/3 CAS latency is derived from MDCNFG[DTC2]. // Writes are ignored. This bit field represents the value driven onto // MA<16:14> (or MA<8:6> or MA<7:5>, depending on MDCNFG[STACKx] // setting) during the MRS command. // [BitFieldRegister(Position=19 )] public bool MDADD2; // SDRAM MRS bit representing Burst Type // SDRAM partition pair 2/3 burst type. Fix to sequential addressing. This bit // field represents the value driven onto MA<13> (or MA<5> or MA<4>, // depending on MDCNFG[STACKx] setting) during the MRS command. This // field is always zero. // [BitFieldRegister(Position=16,Size=3)] public uint MDBL2; // SDRAM MRS bits representing Burst Length // SDRAM partition pair 2/3 burst length. Fixed to a burst length of four. This // bit field represents the value driven onto the MA<12:10> (or MA<4:2> or // MA<3:1>, depending on MDCNFG[STACKx] setting) during the MRS // command. This field is read as 0b010. // [BitFieldRegister(Position= 7,Size=8)] public uint MDMRS0; // The SDRAM MRS bits represent the value driven onto the SDRAM address // bus from MA<24:17> (or MA<24:23,14:9> or MA<24:23,13,8>, depending // on MDCNFG[STACKx] setting) during the MRS command for partition pair 0/1. // [BitFieldRegister(Position= 4,Size=3)] public uint MDCL0; // SDRAM MRS bits representing CAS Latency // SDRAM partition pair 0/1 CAS latency is derived from MDCNFG[DTC2]. // Writes are ignored. This bit field represents the value driven onto // MA<16:14> (or MA<8:6> or MA<7:5>, depending on MDCNFG[STACKx] // setting) during the MRS command. // [BitFieldRegister(Position= 3 )] public bool MDADD0; // SDRAM MRS bit representing Burst Type // SDRAM partition pair 0/1 burst type. Fix to sequential addressing. This bit // field represents the value driven onto MA<13> (or MA<5> or MA<4>, // depending on MDCNFG[STACKx] setting) during the MRS command. This // field is always zero. // [BitFieldRegister(Position= 0,Size=3)] public uint MDBL0; // SDRAM MRS bits representing Burst Length // SDRAM partition pair 0/1 burst length. Fixed to a burst length of four. This // bit field represents the value driven onto the MA<12:10> (or MA<4:2> or // MA<3:1>, depending on MDCNFG[STACKx] setting) during the MRS // command. This field is read as 0b010. // } [BitFieldPeripheral(PhysicalType=typeof(uint))] public struct MDMRSLP_bitfield { [BitFieldRegister(Position=31 )] public bool MDLPEN2; // Low-Power Enable for Partition Pair 2/3 // Enable bit for low-power MRS value for partition pair 2/3. // [BitFieldRegister(Position=23,Size=15)] public uint MDMRSLP2; // Low-Power MRS Value for Partition Pair 2/3 // Low-power MRS value to be written to SDRAM for partition pair 2/3. // [BitFieldRegister(Position=15 )] public bool MDLPEN0; // Low-Power Enable for Partition Pair 0/1 // Enable bit for low-power MRS value for partition pair 0/1. // [BitFieldRegister(Position= 0,Size=15)] public uint MDMRSLP0; // Low-Power MRS Value for Partition Pair 0/1 // Low-power MRS value to be written to SDRAM for partition pair 0/1. // } [BitFieldPeripheral(PhysicalType=typeof(uint))] public struct MDREFR_bitfield { [BitFieldRegister(Position=31 )] public bool ALTREFA; // Exiting Alternate Bus Master Mode Refresh Control // // 0 = SDRAM refresh is always performed after exiting alternate bus master mode. // 1 = SDRAM refresh is not performed after exiting alternate bus master // mode unless the SDRAM refresh counter has timed out. // MDREFR[ALTREFB] must be clear. The alternate master must // perform a PALL before releasing the external bus. See // Section 6.4.6.2 for more information. // [BitFieldRegister(Position=30 )] public bool ALTREFB; // Entering Alternate Bus Master Mode Refresh Control // // 0 = SDRAM refresh is always performed after entering alternate bus master mode. // 1 = SDRAM refresh is not performed after entering alternate bus master // mode unless the SDRAM refresh counter has timed out. // MDREFR[ALTREFA] must be clear. The alternate master must first // perform a PALL after receiving the bus grant. // See Section 6.4.6 for more information. // [BitFieldRegister(Position=29 )] public bool K0DB4; // Synchronous Static Memory Clock Pin 0 (SDCLK<0> and SDCLK<3>) Divide-by-4 Control/Status // // When set, SDCLK<0> and SDCLK<3> runs at one-fourth of the memory clock frequency, regardless of the value of MDREFR[K0DB2]. // When clear, the SDCLK<0> and SDCLK<3> speed depends on the value programmed in MDREFR[K0DB2]. // // 0 = Use the value programmed in MDREFR[K0DB2] to generate SDCLK<0> and SDCLK<3>. // 1 = Divide CLK_MEM by four to generate SDCLK<0> and SDCLK<3>. K0DB2 is ignored. // [BitFieldRegister(Position=25 )] public bool K2FREE; // SDCLK<2> Free-Running // // When set, it forces SDCLK<2> to be free-running, regardless of the value of the MDREFR[APD] or MDREFR[K2RUN] bits. // The bit resets to 1 so the clock is driven initially, which provides synchronous memory with a clock for // resetting any internal circuitry. // To disable free-running, clear this bit. // // 0 = SDCLK<2> Dependent on MDREFR[K2RUN] // 1 = SDCLK<2> Free-running enabled // [BitFieldRegister(Position=24 )] public bool K1FREE; // SDCLK<1> Free-Running // // When set, it forces SDCLK<1> to be free-running, regardless of the value of the MDREFR[APD] or MDREFR[K1RUN] bits. // This bit resets to 1 so the clock is driven initially. This provides synchronous memory with a clock for // resetting any internal circuitry. // To disable free-running, clear this bit. // // 0 = SDCLK<1> Dependent on MDREFR[K1RUN] // 1 = SDCLK<1> Free-running enabled // [BitFieldRegister(Position=23 )] public bool K0FREE; // SDCLK<0> and SDCLK<3> Free-Running // // When set, forces SDCLK<0> and SDCLK<3> to be free-running, regardless of the value of the MDREFR[APD] or MDREFR[K0RUN] bits. // This bit resets to 1 so the clock is driven initially. This provides synchronous memory with a // clock for resetting any internal circuitry. // To disable free-running, clear this bit. // // 0 = SDCLK<0> and SDCLK<3> dependent on MDREFR[K0RUN] // 1 = SDCLK<0> and SDCLK<3> free-running enabled // [BitFieldRegister(Position=22 )] public bool SLFRSH; // SDRAM Self-Refresh Control/Status // // Control/status bit for entering and exiting SDRAM self-refresh. It is // automatically set upon a hardware or sleep-exit reset. // // Setting the SLFRSH bit forces a self-refresh command. E1PIN does not // have to be cleared. The appropriate clock run bits (K1RUN and/or K2RUN) // must remain set until SDRAM has entered self-refresh and must be set // before exiting self-refresh (clearing SLFRSH). // // NOTE: This capability must be used with extreme caution because the // resulting state prohibits automatic transitions for any commands. // See Section 6.4.2.5. // // Clearing SLFRSH is a part of the hardware or sleep-exit reset procedure for SDRAM. See Section 6.4.10. // // 0 = Self-refresh disabled // 1 = Self-refresh enabled // [BitFieldRegister(Position=20 )] public bool APD; // SDRAM/Synchronous Static Memory Auto-Power-Down Enable // // If APD is set and MDEFR[KxFREE] is cleared, the SDCKE signal and // SDCLK<2:0> clocks are driven low when none of the corresponding // partitions are being accessed. // // If no SDRAM partitions are being accessed, the SDRAM is put into // power-down mode and the SDCKE signal and SDCLK<2:1> clocks are // driven low. // If one SDRAM partition pair is being used and the other pair is not, the // SDCLKx clock to the partition pair that is not being used is driven low. // If synchronous flash memory is installed and not being accessed, the // SDCLK<0> and SDCLK<3> clocks corresponding to static partitions // are driven low and the synchronous flash chips are put into powerdown // mode. (see part datasheets). See Section 6.4.2.5 andSection 6.5.3 // // 0 = APD disabled // 1 = APD enabled // [BitFieldRegister(Position=19 )] public bool K2DB2; // SDRAM Clock Pin 2 (SDCLK<2>) Divide-by-2 Control/Status // // When set, SDCLK<2> runs at one-half the CLK_MEM frequency. // When cleared, SDCLK<2> runs at the memory clock frequency. // This bit is automatically set on hardware or sleep-exit reset. // // 0 = SDCLK<2> equals CLK_MEM // 1 = SDCLK<2> equals CLK_MEM divided by 2 // [BitFieldRegister(Position=18 )] public bool K2RUN; // SDRAM Clock Pin 2 (SDCLK<2>) Run Control/Status // Automatically cleared on hardware or sleep-exit reset. // // NOTE: Use extreme caution when clearing the K1RUN bit because the // resulting state prohibits automatic transitions for any commands. // See Section 6.4.2.5. // // Setting K1RUN or K2RUN is a part of the hardware and sleep-exit reset procedure for SDRAM. See Section 6.4.10. // // 0 = SDCLK<2> Dependent on MDREFR[K2FREE] // 1 = SDCLK<2> Enabled // [BitFieldRegister(Position=17 )] public bool K1DB2; // SDRAM Clock Pin 1 (SDCLK<1>) Divide-by-2 Control/Status // // When set, SDCLK<1> runs at one-half the CLK_MEM frequency. // When cleared, SDCLK<1> runs at the memory clock frequency. // This bit is automatically set on hardware or sleep-exit reset. // // 0 = SDCLK<1> equals CLK_MEM // 1 = SDCLK<1> equals CLK_MEM divided by 2 // [BitFieldRegister(Position=16 )] public bool K1RUN; // SDRAM Clock Pin 1 (SDCLK<1>) Run Control/Status // Automatically cleared on hardware or sleep-exit reset. // // NOTE: Use extreme caution when clearing the K1RUN bit because the // resulting state prohibits automatic transitions for any commands. // See Section 6.4.2.5. // // Setting K1RUN or K2RUN is a part of the hardware and sleep-exit reset procedure for SDRAM. See Section 6.4.10. // // 0 = SDCLK<1> Dependent on MDREFR[K1FREE] // 1 = SDCLK<1> Enabled // [BitFieldRegister(Position=15 )] public bool E1PIN; // SDRAM Clock Enable Pin 1 (SDCKE) Level Control/Status // Automatically cleared on hardware or sleep-exit reset. // // NOTE: Extreme caution must be taken when clearing the E1PIN bit to // cause a power-down command (if K1RUN = 1 and/or K2RUN = 1, // and SLFRSH = 0) because the resulting state prohibits automatic // transitions for mode register set, read, write, and refresh // commands. E1PIN must be set to cause a power-down-exit // command (if K1RUN = 1 and/or K2RUN = 1, and SLFRSH = 0). See Section 6.4.10. // // Setting E1PIN is a part of the hardware reset or sleep-exit reset procedure for SDRAM. See Section 6.4.10. // // 0 = SDCKE Disabled // 1 = SDCKE Enabled // [BitFieldRegister(Position=14 )] public bool K0DB2; // Synchronous Static Memory Clock Pin 0 (SDCLK<0> and SDCLK<3>) Divide-by-2 Control/Status // Second control/status bit for clock divisor of SDCLK<0>. The value // programmed here is only valid when MDREFR[K0DB4] is cleared. // When K0DB2 is set, SDCLK<0> and SDCLK<3> run at one-half the // memory clock frequency. When clear, SDCLK<0> and SDCLK<3> run at // the memory clock frequency. This bit is automatically set on hardware or sleep-exit reset. // // 0 = SDCLK<0> and SDCLK<3> equals CLK_MEM // 1 = SDCLK<0> and SDCLK<3> equals CLK_MEM divided by two // [BitFieldRegister(Position=13 )] public bool K0RUN; // Synchronous Static Memory Clock Pin 0 (SDCLK<0> and SDCLK<3>) Run Control/Status // Set on hardware or sleep-exit reset if static memory partition 0 (boot space) // is configured for synchronous static memory (see Section 6.5.4). // Otherwise, it is cleared on reset. // Use extreme caution when clearing the K0RUN bit because the resulting // state prohibits automatic transitions for any commands. See Section 6.4.10. // // 0 = SDCLK<0> and SDCLK<3> dependent on MDREFR[K0FREE] // 1 = SDCLK<0> and SDCLK<3> enabled // [BitFieldRegister(Position= 0,Size=12)] public uint DRI; // SDRAM Refresh Interval for All Partitions // // The number of memory clock cycles (divided by 32) between auto refresh // (CBR) cycles. One row is refreshed in each SDRAM bank during each CBR // refresh cycle. This interval applies to all SDRAM in the four partitions. // To the refresh interval from this programmed number, multiply it by 32 and add 31. // // The value that must be loaded into this register is calculated as follows: // DRI = (Number of CLK_MEM cycles 31) / 32 = (Refresh time / rows x memory clock frequency 31) / 32. // // This must be programmed to be shared by both partition pairs. Therefore, the worst case number must be programmed. // This number must be less than the tRASMAX for the SDRAM being accessed. // // If all four SDRAM partitions are disabled, the refresh counter is disabled // and refreshes are only performed when a single transaction to a disabled SDRAM partition is requested. // // If the clock frequency is changed, this register must be rewritten, even if the // value has not changed. This causes a refresh and resets the refresh counter to the refresh interval. // // 0x000 = No refreshes are sent to the SDRAM. However, refresh cycles can occur if VLIO cycles are performed. // // NOTE: See the refresh rules for programming limitations in Section 6.5.1.4 // } [BitFieldPeripheral(PhysicalType=typeof(uint))] public struct SXCNFG_bitfield { public enum CasLatency : uint { // 0b0000 = reserved // 0b0001 = reserved CL3 = 2, // 0b0010 = 3 clocks (frequency configuration code = 2) CL4 = 3, // 0b0011 = 4 clocks (frequency configuration code = 3) CL5 = 4, // 0b0100 = 5 clocks (frequency configuration code = 4) CL6 = 5, // 0b0101 = 6 clocks (frequency configuration code = 5) CL7 = 6, // 0b0110 = 7 clocks (frequency configuration code = 6) CL8 = 7, // 0b0111 = 8 clocks (frequency configuration code = 7) CL9 = 8, // 0b1000 = 9 clocks (frequency configuration code = 8) CL10 = 9, // 0b1001 = 10 clocks (frequency configuration code = 9) CL11 = 10, // 0b1010 = 11 clocks (frequency configuration code = 10) CL12 = 11, // 0b1011 = 12 clocks (frequency configuration code = 11) CL13 = 12, // 0b1100 = 13 clocks (frequency configuration code = 12) CL14 = 13, // 0b1101 = 14 clocks (frequency configuration code = 13) CL15 = 14, // 0b1110 = 15 clocks (frequency configuration code = 14) CL16 = 15, // 0b1111 = 16 clocks (frequency configuration code = 15) } public enum MemoryType : uint { // 0b00 = reserved // 0b01 = reserved BurstOf8 = 2, // 0b10 = Synchronous flash memory in burst-of-8 mode BurstOf16 = 3, // 0b11 = Synchronous flash memory in burst-of-16 mode } [BitFieldRegister(Position=30,WritesAs=1 )] public bool Set2; // reserved (set during writes and reads are undefined) // [BitFieldRegister(Position=28,Size=2 )] public MemoryType SXTP2; // SX Memory Type for Partition Pair 2/3 // [BitFieldSplitRegister(Position=31,Size=1,Offset=4)] [BitFieldSplitRegister(Position=18,Size=3,Offset=0)] public CasLatency SXCL2; // CAS Latency for SX Memory Partition Pair 2/3 // // SXCL2 is the number of SDCLK cycles between the time that the read // command is received and the data is latched. The unit size for SXCL2 is the // external SDCLK cycle; when SX memory is run at half the memory clock // frequency (MDREFR[K0DB2] is set), the delay is two CLK_MEM cycles. // // Use in conjunction with SXCNFG[SXCLEXT2] to achieve the following CAS // latencies. The field SXCLEXT2 is added to the beginning of the SXCL2 field // to create the 4 bit values shown below. // // Any frequency configuration code that inserts wait states in the return of the // data from flash memory is not valid. See the appropriate flash datasheets: // // The first access latency count configuration tells the device how many // clocks must elapse from ADV#-inactive (VIH) before the first data word must // be driven onto its data pins. The input clock frequency determines this value. // [BitFieldRegister(Position=17 )] public bool SXEN3; // SX Memory Partition 3 Enable // // 0 = Partition 3 is not enabled as SX memory. // 1 = Partition 3 is enabled as SX memory. // [BitFieldRegister(Position=16 )] public bool SXEN2; // SX Memory Partition 2 Enable // // 0 = Partition 2 is not enabled as SX memory. // 1 = Partition 2 is enabled as SX memory. // // [BitFieldRegister(Position=14,WritesAs=1 )] public bool Set0; // reserved (set during writes and reads are undefined) // [BitFieldRegister(Position=12,Size=2 )] public MemoryType SXTP0; // SX Memory Type for Partition Pair 2/3 // [BitFieldSplitRegister(Position=15,Size=1,Offset=4)] [BitFieldSplitRegister(Position= 2,Size=3,Offset=0)] public CasLatency SXCL0; // CAS Latency for SX Memory Partition Pair 0/1 // // SXCL0 is the number of SDCLK cycles between the time that the read // command is received and the data is latched. The unit size for SXCL0 is the // external SDCLK cycle; when SX memory is run at half the memory clock // frequency (MDREFR[K0DB0] is set), the delay is two CLK_MEM cycles. // // Use in conjunction with SXCNFG[SXCLEXT0] to achieve the following CAS // latencies. The field SXCLEXT0 is added to the beginning of the SXCL0 field // to create the 4 bit values shown below. // // Any frequency configuration code that inserts wait states in the return of the // data from flash memory is not valid. See the appropriate flash datasheets: // // The first access latency count configuration tells the device how many // clocks must elapse from ADV#-inactive (VIH) before the first data word must // be driven onto its data pins. The input clock frequency determines this value. // [BitFieldRegister(Position= 1 )] public bool SXEN1; // SX Memory Partition 1 Enable // // 0 = Partition 1 is not enabled as SX memory. // 1 = Partition 1 is enabled as SX memory. // [BitFieldRegister(Position= 0 )] public bool SXEN0; // SX Memory Partition 0 Enable // // 0 = Partition 0 is not enabled as SX memory. // 1 = Partition 0 is enabled as SX memory. // } [BitFieldPeripheral(PhysicalType=typeof(uint))] public struct MSC_bitfield { public enum Delay : uint { Val0 = 0, Val1 = 1, Val2 = 2, Val3 = 3, Val4 = 4, Val5 = 5, Val6 = 6, Val7 = 7, Val8 = 8, Val9 = 9, Val10 = 10, Val11 = 11, Val15 = 12, Val20 = 13, Val26 = 14, Val30 = 15, } public enum MemType : uint { FlashOrRomNoBurst = 0, // 0b000 = Synchronous flash or non-burst ROM or non-burst flash SRAM = 1, // 0b001 = SRAM FlashOrRomBurstOf4 = 2, // 0b010 = Burst-of-four ROM or burst-of-four flash (with non-burst writes) FlashOrRomBurstOf8 = 3, // 0b011 = Burst-of-eight ROM or burst-of-eight flash (with non-burst writes) VariableLatencyIO = 4, // 0b100 = Variable-latency I/O (VLIO) // 0b101 = reserved // 0b110 = reserved // 0b111 = reserved } [BitFieldRegister(Position=31 )] public bool RBUFF1; // Return Data Buffer vs. Streaming Behavior [BitFieldRegister(Position=15 )] public bool RBUFF0; // // // When slow memory devices are used in the system (VLIO, slow // SRAM/ROM), this bit must be cleared to allow the system to process other // information rather than remain idle while all the data is read from the // device. When this bit is cleared, the system is allowed to process other // information. When the bit is set, the system halts and waits until all data is // returned from the device. // // When synchronous static memory devices have been enabled for a given // bank, this bit defaults to streaming behavior. The register bit is read as 0 // unless it has specifically been programmed to a 1. This behavior cannot // be overridden. // // 0 = Slower device (return data buffer) // 1 = Faster device (streaming behavior) // [BitFieldRegister(Position=28,Size=3)] public uint RRR1; // ROM/SRAM Recovery Time [BitFieldRegister(Position=12,Size=3)] public uint RRR0; // // // The value of this bit is half the number of memory clock cycles from the // time that chip select is de-asserted after a read or write until the next chip // select (of a different static memory bank) or nSDCS is asserted. // // This field must be programmed with the highest of the three values: tOFF // divided by two, write pulse high time (flash memory/SRAM), and write // recovery before read (flash memory). // // tOFF = RRR1 * 2 + 1 // // NOTE: The MSCx[RRR] value (recovery time after chip select deasserted) // must be reprogrammed prior to switching the processor // to deep-idle mode to avoid long times when the MD bus // (MD<31:0>) is in three-state mode after reads. // [BitFieldRegister(Position=24,Size=4)] public Delay RDN1; // ROM Delay Next Access [BitFieldRegister(Position= 8,Size=4)] public Delay RDN0; // // // The RDN field is encoded as follows: // // ENCODED (Programmed) Value -----> DECODED (Actual) Value // 0-11 -----> 0-11 // 12 -----> 15 // 13 -----> 20 // 14 -----> 26 // 15 -----> 30 // // Use the DECODED value in the equations below for RDNx instead of the actual RDNx value. // // For burst ROM or flash memory: // RDNx + 1 = number of MEM_CLKs from Address to Data Valid for subsequent access. // // For flash memory or SRAM: // RDNx + 1 = number of CLK_MEMs nWE is asserted for write accesses // // For VLIO: // RDNx * 2 = amount of time nOE or nPWE is deasserted to address hold and address setup to nOE or nPWE assertion time. // // NOTE: For VLIO, this number must be greater than or equal to 2. The // memory controller substitutes a default value of 2 for values less than 2. // // [BitFieldRegister(Position=20,Size=4)] public Delay RDF1; // ROM Delay First Access [BitFieldRegister(Position= 4,Size=4)] public Delay RDF0; // // // The encoding scheme is: // // ENCODED (programmed) value ------> DECODED (actual) value: // 0-11 ------> 0-11 // 12 ------> 15 // 13 ------> 20 // 14 -----> 26 // 15 ------> 30 // // The DECODED value represents: // Number of memory-clock cycles (minus 2) from address to data valid // for first read access from all devices except VLIO // Number of memory clock cycles (minus 1) from address to data valid // for subsequent read accesses to non-burst devices except VLIO // Number of memory clock cycles (minus 1) of nWE assertion for write // accesses to all types of flash memory // // For variable-latency I/O, this determines the minimum number of memory // clock cycles (minus 1) of nOE (nPWE) assert time for each beat of read (write). // // NOTE: For VLIO, this number must be greater than or equal to 3. The // memory controller substitutes a default value of 3 for values less than 3. // [BitFieldRegister(Position=19 )] public bool RBW1; // ROM Bus Width [BitFieldRegister(Position= 3 )] public bool RBW0; // // // For reset value of RBW0, see Section 6.5.4. // // This value must be programmed, even when using synchronous static memory in banks 0,1,2, or 3. // 0 = 32 bits // 1 = 16 bits // // NOTE: This value must not be changed during normal operation. // [BitFieldRegister(Position=16,Size=3)] public MemType RT1; // ROM Type [BitFieldRegister(Position= 0,Size=3)] public MemType RT0; // } [BitFieldPeripheral(PhysicalType=typeof(uint))] public struct SA1110_bitfield { [BitFieldRegister(Position=13)] public bool SXSTACK_CS1; // If set, nCS<1> contains stacked flash. [BitFieldRegister(Position=12)] public bool SXSTACK_CS0; // If set, nCS<0> contains stacked flash // [BitFieldRegister(Position= 8)] public bool SXENX; // Large Memory Support // // See Figure 6-11 for a diagram. // // 0 = Use six 64 Mbyte chip selects (nCS<5:0> // 1 = Use two 64 Mbyte chip selects (nCS<5:4>) and two 128 Mbyte chip selects (nCS<1:0>). The corresponding SA1110[3:0] bit fields must be cleared. // [BitFieldRegister(Position= 5)] public bool SA1110_5; // If set, SA-1110 Compatibility Mode for Static Memory Partition 5 [BitFieldRegister(Position= 4)] public bool SA1110_4; // If set, SA-1110 Compatibility Mode for Static Memory Partition 4 [BitFieldRegister(Position= 3)] public bool SA1110_3; // If set, SA-1110 Compatibility Mode for Static Memory Partition 3 [BitFieldRegister(Position= 2)] public bool SA1110_2; // If set, SA-1110 Compatibility Mode for Static Memory Partition 2 [BitFieldRegister(Position= 1)] public bool SA1110_1; // If set, SA-1110 Compatibility Mode for Static Memory Partition 1 [BitFieldRegister(Position= 0)] public bool SA1110_0; // If set, SA-1110 Compatibility Mode for Static Memory Partition 0 } [BitFieldPeripheral(PhysicalType=typeof(uint))] public struct BOOT_DEF_bitfield { [BitFieldRegister(Position=3)] public bool PKG_TYPE; // Package Type // // 0 = reserved // 1 = 32-bit package // [BitFieldRegister(Position=0)] public bool BOOT_SEL; // Boot Select // // Contains the input pin BOOT_SEL for the memory controller. See Section 6.4.7 for pin configuration definitions. // // 0 = BOOT_SEL is low (boot from 32-bit memory). // 1 = BOOT_SEL is high (boot from 16-bit memory). // } [BitFieldPeripheral(PhysicalType=typeof(uint))] public struct ARB_CNTRL_bitfield { [BitFieldRegister(Position=31 )] public bool DMA_SLV_park; // 1 = Bus is parked with DMA slave when idle [BitFieldRegister(Position=30 )] public bool CI_park; // 1 = Bus is parked with quick capture interface when idle [BitFieldRegister(Position=29 )] public bool EX_MEM_park; // 1 = Bus is parked with external memory controller when idle [BitFieldRegister(Position=28 )] public bool INT_MEM_park; // 1 = Bus is parked with internal memory controller when idle [BitFieldRegister(Position=27 )] public bool USB_park; // 1 = Bus is parked with USB host controller when idle [BitFieldRegister(Position=26 )] public bool LCD_park; // 1 = Bus is parked with LCD controller when idle [BitFieldRegister(Position=25 )] public bool DMA_park; // 1 = Bus is parked with DMA controller when idle [BitFieldRegister(Position=24 )] public bool Core_park; // 1 = Bus is parked with core when idle [BitFieldRegister(Position=23 )] public bool LOCK_FLAG; // 1 = Only locking masters gain access to the bus // [BitFieldRegister(Position= 8,Size=4)] public uint LCD_Wt; // LCD Priority Value // // Values in this field determine the relative priority of LCD requests for the bus with core and DMA requests. // [BitFieldRegister(Position= 4,Size=4)] public uint DMA_Wt; // DMA Priority Value // // Values in this field determine the relative priority of DMA requests for the bus with core and LCD requests. // [BitFieldRegister(Position= 0,Size=4)] public uint Core_Wt; // Core Priority Value // // Values in this field determine the relative priority of core requests for the bus with DMA and LCD requests. // } [BitFieldPeripheral(PhysicalType=typeof(uint))] public struct BSCNTR0_bitfield { [BitFieldRegister(Position=28,Size=4)] public uint CKE1BS; // SDCKE Buffer Strength Control register [BitFieldRegister(Position=24,Size=4)] public uint CLK2BS; // SDCLK<2> Buffer Strength Control register [BitFieldRegister(Position=20,Size=4)] public uint CLK1BS; // SDCLK<1> Buffer Strength Control register [BitFieldRegister(Position=16,Size=4)] public uint CLK0BS; // SDCLK<0> Buffer Strength Control register [BitFieldRegister(Position=12,Size=4)] public uint RASBS; // SDRAS Buffer Strength Control register [BitFieldRegister(Position= 8,Size=4)] public uint CASBS; // SDCAS Buffer Strength Control register [BitFieldRegister(Position= 4,Size=4)] public uint MDHBS; // MD<31:16> Buffer Strength Control register [BitFieldRegister(Position= 0,Size=4)] public uint MDLBS; // MD<15:0> Buffer Strength Control register } [BitFieldPeripheral(PhysicalType=typeof(uint))] public struct BSCNTR1_bitfield { [BitFieldRegister(Position=28,Size=4)] public uint DQM32BS; // DQM<3:2> Buffer Strength Control register [BitFieldRegister(Position=24,Size=4)] public uint DQM10BS; // DQM<1:0> Buffer Strength Control register [BitFieldRegister(Position=20,Size=4)] public uint SDCS32BS; // SDCS<3:2> Buffer Strength Control register [BitFieldRegister(Position=16,Size=4)] public uint SDCS10BS; // SDCS<1:0> Buffer Strength Control register [BitFieldRegister(Position=12,Size=4)] public uint WEBS; // nWE Buffer Strength Control register [BitFieldRegister(Position= 8,Size=4)] public uint OEBS; // nOE Buffer Strength Control register [BitFieldRegister(Position= 4,Size=4)] public uint SDCAS_DELAY; // SDCAS Return Signal Timing Delay // // 0x5average timing delay // // All other values are not valid. // // NOTE: Do not use this bit field to control the buffer strength for SDCAS. // This bit field is for signal return clock timing only. [BitFieldRegister(Position= 0,Size=4)] public uint RDnWRBS; // RDnWR Buffer Strength Control register } [BitFieldPeripheral(PhysicalType=typeof(uint))] public struct BSCNTR2_bitfield { [BitFieldRegister(Position=28,Size=4)] public uint CS5BS; // nCS<5> Buffer Strength Control register [BitFieldRegister(Position=24,Size=4)] public uint CS4BS; // nCS<4> Buffer Strength Control register [BitFieldRegister(Position=20,Size=4)] public uint CS3BS; // nCS<3> Buffer Strength Control register [BitFieldRegister(Position=16,Size=4)] public uint CS2BS; // nCS<2> Buffer Strength Control register [BitFieldRegister(Position=12,Size=4)] public uint CS1BS; // nCS<1> Buffer Strength Control register [BitFieldRegister(Position= 8,Size=4)] public uint CS0BS; // nCS<0> Buffer Strength Control register [BitFieldRegister(Position= 4,Size=4)] public uint CLK3BS; // SDCLK<3> Buffer Strength Control Bits [BitFieldRegister(Position= 0,Size=4)] public uint MA25BS; // MA<25> Buffer Strength Control register } [BitFieldPeripheral(PhysicalType=typeof(uint))] public struct BSCNTR3_bitfield { [BitFieldRegister(Position=28,Size=4)] public uint MA24BS; // MA<24> Buffer Strength Control register [BitFieldRegister(Position=24,Size=4)] public uint MA23BS; // MA<23> Buffer Strength Control register [BitFieldRegister(Position=20,Size=4)] public uint MA22BS; // MA<22> Buffer Strength Control register [BitFieldRegister(Position=16,Size=4)] public uint MA21BS; // MA<21> Buffer Strength Control register [BitFieldRegister(Position=12,Size=4)] public uint MA2010BS; // MA<20:10> Buffer Strength Control register [BitFieldRegister(Position= 8,Size=4)] public uint MA92BS; // MA<9:2> Buffer Strength Control register [BitFieldRegister(Position= 4,Size=4)] public uint MA1BS; // MA<1> Buffer Strength Control register [BitFieldRegister(Position= 0,Size=4)] public uint MA0BS; // MA<0> Buffer Strength Control register } [Register(Offset=0x00U)] public MDCNFG_bitfield MDCNFG; // SDRAM Configuration register | 6-43 [Register(Offset=0x04U)] public MDREFR_bitfield MDREFR; // SDRAM Refresh Control register | 6-53 [Register(Offset=0x08U)] public MSC_bitfield MSC0; // Static Memory Control register 0 | 6-63 [Register(Offset=0x0CU)] public MSC_bitfield MSC1; // Static Memory Control register 1 | 6-63 [Register(Offset=0x10U)] public MSC_bitfield MSC2; // Static Memory Control register 2 | 6-63 //// [Register(Offset=0x14U)] public uint MECR; // Expansion Memory (PC Card/CompactFlash) Bus Configuration register | 6-79 [Register(Offset=0x1CU)] public SXCNFG_bitfield SXCNFG; // Synchronous Static Memory Configuration register | 6-58 [Register(Offset=0x20U)] public uint FLYCNFG; // Fly-by DMA DVAL<1:0> polarities | 5-39 //// [Register(Offset=0x28U)] public uint MCMEM0; // PC Card Interface Common Memory Space Socket 0 Timing Configuration register | 6-77 //// [Register(Offset=0x2CU)] public uint MCMEM1; // PC Card Interface Common Memory Space Socket 1 Timing Configuration register | 6-77 //// [Register(Offset=0x30U)] public uint MCATT0; // PC Card Interface Attribute Space Socket 0 Timing Configuration register | 6-77 //// [Register(Offset=0x34U)] public uint MCATT1; // PC Card Interface Attribute Space Socket 1 Timing Configuration register | 6-77 //// [Register(Offset=0x38U)] public uint MCIO0; // PC Card Interface I/o Space Socket 0 Timing Configuration register | 6-78 //// [Register(Offset=0x3CU)] public uint MCIO1; // PC Card Interface I/o Space Socket 1 Timing Configuration register | 6-78 [Register(Offset=0x40U)] public MDMRS_bitfield MDMRS; // SDRAM Mode Register Set Configuration register | 6-49 [Register(Offset=0x44U)] public BOOT_DEF_bitfield BOOT_DEF; // Boot Time Default Configuration register | 6-75 [Register(Offset=0x48U)] public ARB_CNTRL_bitfield ARB_CNTL; // Arbiter Control register | 29-2 [Register(Offset=0x4CU)] public BSCNTR0_bitfield BSCNTR0; // System Memory Buffer Strength Control register 0 | 6-81 [Register(Offset=0x50U)] public BSCNTR1_bitfield BSCNTR1; // System Memory Buffer Strength Control register 1 | 6-82 //// [Register(Offset=0x54U)] public uint LCDBSCNTR; // LCD Buffer Strength Control register | 7-102 [Register(Offset=0x58U)] public MDMRSLP_bitfield MDMRSLP; // Special Low Power SDRAM Mode Register Set Configuration register | 6-51 [Register(Offset=0x5CU)] public BSCNTR2_bitfield BSCNTR2; // System Memory Buffer Strength Control register 2 | 6-83 [Register(Offset=0x60U)] public BSCNTR3_bitfield BSCNTR3; // System Memory Buffer Strength Control register 3 | 6-84 [Register(Offset=0x64U)] public SA1110_bitfield SA1110; // SA-1110 Compatibility Mode for Static Memory register | 6-70 // // Helper Methods // [DisableNullChecks] public unsafe void InitializeStackedSDRAM() { // // Set SDRAM configuration // this.MDCNFG = new MDCNFG_bitfield { SET0 = true, SET2 = true, MDENX = false, // normal SDRAM memory map STACK = MDCNFG_bitfield.Stack.SDRAMplusFLASH, DTC0 = MDCNFG_bitfield.Timing.Setting3, // use normal addressing mode, 3CLK cycle, tRP=3, CL=3,tRAS=7,tRC=11 DNB0 = true, // 4 internal bank DRAC0 = MDCNFG_bitfield.RowAddress.Use13Bits, // 13 row address DCAC0 = MDCNFG_bitfield.ColumnAddress.Use9Bits, // 9 col address DWID0 = true, // 16 bit bus }; // // Enable partition 0 clock for synchronous memory // { var mdrefr = this.MDREFR; mdrefr.DRI = 25; // (refresh interval in SDRAM clocks)/32 = ((64mS/8192 rows) * 104 MHz)/32 (rounded down) mdrefr.K0FREE = false; mdrefr.K1FREE = false; mdrefr.K2FREE = false; mdrefr.APD = false; mdrefr.K0DB4 = true; mdrefr.SLFRSH = true; mdrefr.K0RUN = true; this.MDREFR = mdrefr; } { var mdrefr = this.MDREFR; mdrefr.K1DB2 = true; mdrefr.K1RUN = true; this.MDREFR = mdrefr; } this.MDREFR.SLFRSH = false; this.MDREFR.E1PIN = true; // // dummy read for entering NOP state, A20=0 // uint sdramBaseAddress = 0xA0000000u; StackedFlashChip.InitializeSDRAM( sdramBaseAddress ); // delay for 200usec Processor.DelayMicroseconds( 200 ); this.MDCNFG.DE0 = true; // Enable SDRAM // Issue precharge all command. MA10 ( or A20) bit set to high for precharge ALL StackedFlashChip.InitializeSDRAM( sdramBaseAddress + 0x10000 ); // Issue 2 AutoRefresh Command StackedFlashChip.InitializeSDRAM( sdramBaseAddress ); StackedFlashChip.InitializeSDRAM( sdramBaseAddress ); // // Set Mode Register // this.MDMRS.MDMRS0 = 0; // // Issue Extended Mode Register Command, enable Low power, Amibent temp = 70deg cel, Partial array self refresh = four banks. // this.MDMRSLP = new MDMRSLP_bitfield { MDLPEN0 = true, }; // // Set Mode Register, back to NOP // this.MDMRS.MDMRS0 = 0; // // Turn on Auto Power Down // this.MDREFR.APD = true; } [DisableNullChecks] [MemoryRequirements(MemoryAttributes.RAM)] public unsafe void InitializeStackedFLASH() { // // Flash at CS0, no large memory, no byte addressing // this.SA1110 = new SA1110_bitfield { SXSTACK_CS0 = true, }; this.MSC0 = new MSC_bitfield { RT0 = MSC_bitfield.MemType.FlashOrRomBurstOf4, RBW0 = true, // 16 bits RBUFF0 = true, // streaming behavior RDF0 = MSC_bitfield.Delay.Val15, RDN0 = MSC_bitfield.Delay.Val7, RRR0 = 2, // // Keep the other section uninitialized. // RT1 = MSC_bitfield.MemType.FlashOrRomNoBurst, RBW1 = false, RBUFF1 = false, RDF1 = MSC_bitfield.Delay.Val30, RDN1 = MSC_bitfield.Delay.Val30, RRR1 = 7, }; // // Initialize Flash here instead of flash driver, as it must be done from RAM // { ushort flashConfig; flashConfig = StackedFlashChip.FLASH_CONFIG_RESERVED; flashConfig |= StackedFlashChip.FLASH_CONFIG_SYNC; flashConfig |= StackedFlashChip.FLASH_CONFIG_CLK_HI_EDGE; flashConfig |= StackedFlashChip.FLASH_CONFIG_DATA_HOLD_1; flashConfig |= 4 << StackedFlashChip.FLASH_CONFIG_LAT_SHIFT; flashConfig |= StackedFlashChip.FLASH_CONFIG_BURST_16; flashConfig |= StackedFlashChip.FLASH_CONFIG_BURST_WRAP; StackedFlashChip.InitializeFLASH( 0, flashConfig ); } this.SXCNFG = new SXCNFG_bitfield { Set0 = true, Set2 = true, SXTP0 = SXCNFG_bitfield.MemoryType.BurstOf16, SXCL0 = SXCNFG_bitfield.CasLatency.CL5, SXEN0 = true, }; } // // Access Methods // public static extern MemoryController Instance { [SingletonFactory()] [MethodImpl( MethodImplOptions.InternalCall )] get; } } } ================================================ FILE: Zelig/Zelig/RunTime/DeviceModels/ModelForPXA27x/HardwareModel/ChipSet/PXA27x/OSTimers.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // namespace Microsoft.DeviceModels.Chipset.PXA27x { using System; using System.Runtime.CompilerServices; using Microsoft.Zelig.Runtime; [MemoryMappedPeripheral(Base=0x40A00000U,Length=0x000000C0U)] public class OSTimers { [BitFieldPeripheral(PhysicalType=typeof(uint))] public struct OMCR_bitfield { public enum Synchronization { NoSync = 0, // 0b00 = No external synchronization ExySync0 = 1, // 0b01 = Reset OSCRx on the rising edge of EXT_SYNC<0>. ExySync1 = 2, // 0b10 = Reset OSCRx on the rising edge of EXT_SYNC<1>. // 0b11 = reserved } public enum Resolution { Disable = 0, // 0b0000 = The counter is disabled. Freq32KHz = 1, // 0b0001 = 1/32768th of a second Freq1KHz = 2, // 0b0010 = 1 millisecond. The interval between clock increments averages one millisecond, but the time between individual clock increments varies because the counter resolution is derived from the 32.768-kHz clock. Freq1Hz = 3, // 0b0011 = 1 second Freq1MHz = 4, // 0b0100 = 1 microsecond ExtClock = 5, // 0b0101 = Externally supplied clock. The counter resolution is the clock period of the externally supplied clock. FreqSSP1Detect = 6, // 0b0110 = SSP1 Frame Detect. The counter resolution is the SSP1 frame detect rate. FreqSSP2Detect = 7, // 0b0111 = SSP2 Frame Detect. The counter resolution is the SSP2 frame detect rate. FreqSSP3Detect = 8, // 0b1000 = SSP3 Frame Detect. The counter resolution is the SSP3 frame detect rate. FreqUDCDetect = 9, // 0b1001 = UDC Frame Detect. The counter resolution is the UDC frame detect rate. // 0b10100b1111 = reserved } [BitFieldRegister (Position=9 )] public bool N; // Snapshot Mode // // Channel 9: // 0 = Snapshot mode is disabled. // 1 = Read from OSCR9 copies contents of OSCR8 to OSNR. // Channel 11: // 0 = Snapshot mode is disabled. // 1 = Read from OSCR11 copies contents of OSCR10 to OSNR. // [BitFieldRegister (Position=7 )] public bool C; // Channel X Match Against // // X = 4-7 // // 0 = Channel x is compared to OSCR4 and OSCRx is not incremented. // 1 = Channel x is compared to OSCRx and a write to OSCRx starts the channel. // NOTE: For channel 4, the counter always operates as if this bit is set. // // X = 8-11 // // 0 = Channel x is compared to OSCR8 and OSCRx is not incremented. // 1 = Channel x is compared to OSCRx and a write to OSCRx starts the channel. // NOTE: For channel 8, the counter always operates as if this bit is set. // [BitFieldRegister (Position=6 )] public bool P; // Periodic Timer // // 0 = The channel stops incrementing after detecting a match. // 1 = The channel continues incrementing after detecting a match. // [BitFieldRegister (Position=4,Size=2 )] public Synchronization S; // External Synchronization Control // [BitFieldRegister (Position=3 )] public bool R; // Reset OSCRx on Match // // 0 = Do not reset OSCRx on match. // 1 = Reset OSCRx on match. // [BitFieldSplitRegister(Position=8,Size=1,Offset=3)] // [BitFieldSplitRegister(Position=0,Size=3,Offset=0)] public Resolution CRES; // Counter Resolution // // Any channel using a counter that is derived from the 32.768-kHz clock // continues to operate in standby and sleep mode. This applies to the values of CRES between 0x1 and 0x3. // Any channel not using a counter that is derived from the 32.768-kHz clock // stops incrementing in standby, sleep, or deep-sleep mode. This applies to the values of CRES between 0x4 and 0x9 // } [BitFieldPeripheral(PhysicalType=typeof(uint))] public struct OWER_bitfield { [BitFieldRegister(Position=0)] public bool WME; // Watchdog Match Enable // // 0 = OSMR3 match with OSCR0 does not cause a reset of the processor. // 1 = OSMR3 match with OSCR0 causes a reset of the processor. // } #pragma warning disable 649 // private array fields are never assigned [Register(Offset=0x10 )] private uint OSCR0; // OS Timer Counter 0 register | 22-17 [Register(Offset=0x40,Instances=8)] private uint[] OSCR4_11; // OS Timer Counter 4-11 register | 22-17 [Register(Offset=0x14 )] public uint OSSR; // OS Timer Status register (used for all counters) | 22-18 [Register(Offset=0x18 )] public uint OWER; // OS Timer Watchdog Enable register | 22-16 [Register(Offset=0x1C )] public uint OIER; // OS Timer Interrupt Enable register (used for all counters) | 22-16 [Register(Offset=0x20 )] public uint OSNR; // OS Timer Snapshot register | 22-19 [Register(Offset=0x00,Instances=4)] private uint[] OSMR0_3; // OS Timer Match 0-3 register | 22-15 [Register(Offset=0x80,Instances=8)] private uint[] OSMR4_11; // OS Timer Match 4-11 register | 22-15 [Register(Offset=0xC0,Instances=8)] private OMCR_bitfield[] OMCR4_11; // OS Match Control 4-11 register | 22-9 through 22-13 #pragma warning restore 649 // // Helper Methods // [Inline] public void SetControl( int numTimer , OMCR_bitfield val ) { if(numTimer < 4) { // There's no control for these timers. } else if(numTimer < 12) { this.OMCR4_11[numTimer - 4] = val; } } [Inline] public void SetMatch( int numTimer , uint val ) { if(numTimer < 4) { this.OSMR0_3[numTimer] = val; } else if(numTimer < 12) { this.OSMR4_11[numTimer - 4] = val; } } [Inline] public void WriteCounter( int numTimer , uint val ) { if(numTimer < 4) { this.OSCR0 = val; } else if(numTimer < 12) { this.OSCR4_11[numTimer - 4] = val; } } [Inline] public uint ReadCounter( int numTimer ) { if(numTimer < 4) { return this.OSCR0; } else if(numTimer < 12) { return this.OSCR4_11[numTimer - 4]; } else { return 0; } } [Inline] public bool HasFired( int numTimer ) { return (this.OSSR & (1u << numTimer)) != 0; } [Inline] public void ClearFired( int numTimer ) { this.OSSR = (1u << numTimer); } [Inline] public void EnableInterrupt( int numTimer ) { this.OIER |= (1u << numTimer); } [Inline] public void DisableInterrupt( int numTimer ) { this.OIER &= ~(1u << numTimer); } // // Access Methods // public static extern OSTimers Instance { [SingletonFactory()] [MethodImpl( MethodImplOptions.InternalCall )] get; } } } ================================================ FILE: Zelig/Zelig/RunTime/DeviceModels/ModelForPXA27x/HardwareModel/ChipSet/PXA27x/PowerManager.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // namespace Microsoft.DeviceModels.Chipset.PXA27x { using System.Runtime.CompilerServices; using Microsoft.Zelig.Runtime; [MemoryMappedPeripheral(Base=0x40F00000U,Length=0x000001A4U)] public class PowerManager { [BitFieldPeripheral(PhysicalType=typeof(uint))] public struct PSSR_bitfield { [BitFieldRegister(Position=6)] public bool OTGPH; // OTG Peripheral Control Hold // // 0 = OTG pad is not holding its state. // 1 = OTG pad is holding its state. // [BitFieldRegister(Position=5)] public bool RDH; // Read Disable Hold // // 0 = GPIO pins are configured according to their GPIO configuration (see Chapter 24, General-Purpose I/O Controller). // 1 = The receivers of all GPIO pins are disabled. // // If RDH is set as a result of any reset except sleep, resistive pull-downs are enabled until RDH is cleared. // RDH must be cleared by software after the peripheral and GPIO interfaces have been configured but before they are actually used. // [BitFieldRegister(Position=4)] public bool PH; // Peripheral Control Hold // // 0 = GPIO pins are configured according to their GPIO configuration. // 1 = GPIO pins are held in their sleep-mode states. // // PH is set upon entry into sleep or standby mode. // PH must be cleared by software after the peripherals and GPIO interfaces have been configured but before they are actually used. // PH is clear during deep-sleep. // [BitFieldRegister(Position=3)] public bool STS; // Standby Mode Status // // 0 = The processor has not been placed in standby mode by configuring the PWRMODE register since STS was cleared by a reset or by software. // 1 = The processor was placed in standby mode by configuring the PWRMODE register. // [BitFieldRegister(Position=2)] public bool VFS; // VCC Fault Status // // 0 = nVDD_FAULT has not been asserted since it was last cleared by a reset or by software. // 1 = nVDD_FAULT has been asserted and caused the processor to enter deep-sleep mode. // // NOTE: This bit is not set by the assertion of nVDD_FAULT while the processor is in deep-sleep mode. // [BitFieldRegister(Position=1)] public bool BFS; // Battery Fault Status // // 0 = nBATT_FAULT has not been asserted since it was last cleared by a reset or by software. // 1 = nBATT_FAULT has been asserted and caused the processor to enter deep-sleep mode. // [BitFieldRegister(Position=0)] public bool SSS; // Software Sleep Status // // 0 = The processor has not been placed in sleep mode by configuring the PWRMODE register since SSS was last cleared by a reset or by the software. // 1 = The processor was placed in sleep mode by configuring the PWRMODE register. } [Register(Offset=0x0000U )] public uint PMCR; // Power Manager Control register | 3-67 [Register(Offset=0x0004U )] public PSSR_bitfield PSSR; // Power Manager Sleep Status register | 3-69 [Register(Offset=0x0008U )] public uint PSPR; // Power Manager Scratch Pad register | 3-72 [Register(Offset=0x000CU )] public uint PWER; // Power Manager Wake-Up Enable register | 3-73 [Register(Offset=0x0010U )] public uint PRER; // Power Manager Rising-Edge Detect Enable register | 3-77 [Register(Offset=0x0014U )] public uint PFER; // Power Manager Falling-Edge Detect Enable register | 3-78 [Register(Offset=0x0018U )] public uint PEDR; // Power Manager Edge-Detect Status register | 3-79 [Register(Offset=0x001CU )] public uint PCFR; // Power Manager General Configuration register | 3-80 [Register(Offset=0x0020U,Instances=32)] public uint[] PGSR; // Power Manager GPIO Sleep State register for GPIO<120:0> | 3-83 [Register(Offset=0x0030U )] public uint RCSR; // Reset Controller Status register | 3-84 [Register(Offset=0x0034U )] public uint PSLR; // Power Manager Sleep Configuration register | 3-85 [Register(Offset=0x0038U )] public uint PSTR; // Power Manager Standby Configuration register | 3-88 [Register(Offset=0x0040U )] public uint PVCR; // Power Manager Voltage Change Control register | 3-89 [Register(Offset=0x004CU )] public uint PUCR; // Power Manager USIM Card Control/Status register | 3-90 [Register(Offset=0x0050U )] public uint PKWR; // Power Manager Keyboard Wake-Up Enable register | 3-92 [Register(Offset=0x0054U )] public uint PKSR; // Power Manager Keyboard Level-Detect Status register | 3-93 [Register(Offset=0x0080U,Instances=32)] public uint[] PCMD; // Power Manager I2C Command register File | 3-94 //--// // // Helper Methods // public void ReleaseReadDisableHold() { this.PSSR = new PSSR_bitfield{ RDH = true }; } // // Access Methods // public static extern PowerManager Instance { [SingletonFactory()] [MethodImpl( MethodImplOptions.InternalCall )] get; } } } ================================================ FILE: Zelig/Zelig/RunTime/DeviceModels/ModelForPXA27x/HardwareModel/ChipSet/PXA27x/SSP.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // namespace Microsoft.DeviceModels.Chipset.PXA27x { using System.Runtime.CompilerServices; using Microsoft.Zelig.Runtime; /// /// The Synchronous Serial Port (SSP) subsystem of the XScale PXA271 /// /// /// The SSP ports are a synchronous serial interfaces that connect to a variety of external /// devices that use serial protocols for data transfer. The SSP ports provide support for the /// following protocols: /// /// Texas Instruments (TI) Synchronous Serial Protocol /// Motorola Serial Peripheral Interface (SPI) protocol /// National Semiconductor Microwire /// Programmable Serial Protocol (PSP) /// ///

/// The SSP ports operate as full-duplex devices for the TI Synchronous Serial Protocol, SPI, and PSP /// protocols and as a half-duplex device for the Microwire protocol. /// The FIFOs can be loaded or emptied by the CPU using programmed I/O or by DMA burst /// transfers. ///

/// Features /// /// Supports the TI Synchronous Serial Protocol, the Motorola SPI protocol, National /// Semiconductor Microwire, and a Programmable Serial Protocol (PSP) /// One transmit FIFO and one receive FIFO, each 16 samples deep by 32-bits /// wide /// Sample sizes from four to 32-bits /// Bit-rates from 6.3 Kbps (minimum) to 13 Mbps (maximum) /// Master-mode and slave-mode operation /// Receive-without-transmit operation /// Network mode with up to eight time slots and independent transmit/receive /// in any/all/none of the time slotsavailable only with TI Synchronous Serial Protocol and /// Programmable Serial Protocol (PSP) formats /// Audio clock control to provide a 4x output clock and support for selection /// of most standard audio Codec frequencies /// /// [MemoryMappedPeripheral(Base = 0x41000000U, Length = 0x00A00000U)] public class SSP { #region SSCR0 Bitfield ///

/// SSCR0 controls various functions within the SSP port. /// Before enabling the SSP port by setting SSCR0[SSE], /// the desired values for this register must be programmed. /// [BitFieldPeripheral(PhysicalType = typeof(uint))] public struct SSCR0_Bitfield { /// /// Mode /// 0 = Normal SSP port mode /// 1 = Network mode /// /// /// Mode /// 0 = Normal SSP port mode /// 1 = Network mode ///

/// NOTE: When network mode is selected, only use DMA to move data /// to/from the SSP Data register (SSDR). Do not use interrupts or /// CPU polling. ///

/// Set this bit only when using PSP and TI SSP formats. Setting this bit causes /// SSPSCLKx to run continuously (if the SSP port is a master of the clock /// = 0). During network mode, only one SSPSFRMx is /// sent (received) for the number of time slots programmed into the /// field. ///

/// When using the PSP format in network mode, the parameters SFRMDLY, /// STRTDLY, DMYSTP, DMYSTRT must be cleared. Other parameters (such /// as FRMPOL, SCMODE, FSRT, SFRMDWDTH) are programmable. /// [BitFieldRegister(Position = 31)] public bool MOD; ///

/// audio clock select /// /// /// 0 = SSPSCLKx selection is determined by the NCS and ECS bits. /// 1 = Audio Clock (and Audio Clock Divider) creates SSPSCLKx. ///

/// If the ACS bit is set (and the GPIO are properly configured), SSPSYSCLKx /// is continually output (even if the SSP port is disabled). SSPSCLKx is output /// as previously defined (determined by format, SSPSCLKENx, ECRA/ECRB /// functions). /// [BitFieldRegister(Position = 30)] public bool ACS; ///

/// Frame rate divider control /// /// /// Value 0-7 indicates the number of time slots per frame when in network /// mode (the actual number of time slots is FRDC + 1 for 18 time slots) /// [BitFieldRegister(Position = 24, Size=3)] public uint FRDC; /// /// Transmit FIFO underrung interrupt mask /// /// /// 0 = TUR events generate an SSP port interrupt. /// 1 = TUR events do not generate an SSP port interrupt. /// When set, this bit masks the TX FIFO Underrun (TUR) event from /// generating an SSP port interrupt. SSSR will still indicate that a TUR event /// has occurred. This bit can be written to at any time (before or after SSP port /// is enabled). /// [BitFieldRegister(Position = 23)] public bool TIM; /// /// Receive FIFO overrung interrupt mask /// /// /// Receive FIFO Overrun Interrupt Mask /// 0 = ROR events generate an SSP port interrupt. /// 1 = ROR events do not generate an SSP port interrupt. /// When set, this bit masks the RX FIFO Overrun (ROR) event from /// generating an SSP port interrupt. SSSR will still indicate that an ROR /// event has occurred.This bit can be written to at any time (before or after /// SSP port is enabled). /// [BitFieldRegister(Position = 22)] public bool RIM; /// /// Network clock select /// /// /// Used with ECS to select the network clock. /// 0 = The NCS bit determines clock selection. /// 1 = Network Clock creates the SSP ports SSPSCLKx. /// Before setting the NCS bit, first disable the port. The NCS (and ECS) bits /// must be configured before or at the same time that the SSE bit is set. /// [BitFieldRegister(Position = 21)] public bool NCS; /// /// Extended data size select /// /// /// Selects the bit rate of the SSP port when in master mode with respect to /// SSPSCLKx (as defined by ). The maximum bit rate is /// 13 Mbps. The serial-clock generator uses clocks selected by ECS and NCS. /// The selected clock is divided by the value of SCR plus 1 (a range of 1 to /// 4096) to generate SSPSCLKx. ///

/// NOTE: This field is ignored when the SSP port is a slave with respect to /// SSPSCLKx (defined by ) and transmission /// data rates are determined by an external device. ///

/// NOTE: Software must not change SCR when SSPSCLKx is enabled /// (through use of the SSPSCLKEN pin or SSPCR1.ECRA or /// SPCR1.ECRB) because doing so causes the SSPSCLKx /// frequency to immediately change. /// Values (0 to 4095) generate the clock rate of the SSP port. /// Serial bit rate = SSP Port Clock / (SCR + 1), where SCR is a decimal integer /// [BitFieldRegister(Position = 20)] public bool EDSS; ///

/// Serial clock rate /// /// /// Used with DSS to select the size of the data transmitted and received by the /// SSP port. /// 0 = Zero is pre-appended to the DSS value that sets the DSS range from /// 4-16- bits. /// 1 = One is pre-appended to the DSS value that sets the DSS range from /// 17-32-bits. /// [BitFieldRegister(Position = 8, Size = 12)] public uint SCR; /// /// Synchronous serial enable. /// /// /// Enables or disables all SSP port operations. When the port is disabled, all of /// its clocks can be stopped by programmers to minimize power consumption. /// When cleared during active operation, the SSP port is disabled immediately, /// terminating the current frame being transmitted or received. Clearing SSE /// resets the port FIFOs and the status bits; however, the SSP port control /// registers and the receive FIFO overrun status bit are not reset. /// NOTE: After reset or after clearing the SSE, ensure that the SSCR1, /// SSITR, SSTO, and SSPSP control registers are properly reconfigured /// and that the SSSR register is reset before re-enabling /// the SSP port by setting SSE. Also, SSE must be cleared before reconfiguring /// the SSCR0, SSCR1, or SSPSP registers; any or /// all control bits in SSCR0 can be written at the same time as the /// SSE. ///

/// 0 = SSP port operation disabled. /// 1 = SSP port operation enabled. /// [BitFieldRegister(Position = 7)] public bool SSE; ///

/// Extended clock select /// /// /// Used with NCS to select the clock source for the SSP port. /// ECS in conjunction with NCS selects whether the SSP port uses the on-chip /// 13-MHz clock or one of two off-chip clocks supplied by GPIO: the network /// clock (CLK_EXT, described in Chapter 24, General-Purpose I/O /// Controller) or the SSP ports external clock (SSPEXTCLK) produces serial /// transmission rates ranging from 6.3 Kbps (minimum recommended bit rate) /// to a maximum of 13 Mbps. When NCS is cleared, ECS selects between the /// on-chip 13-MHz clock and external clock (SSPEXTCLK). When NCS is set, /// the network clock (CLK_EXT) is selected. The frequency of the off-chip /// clock can be any value up to 13 MHz. ///

/// When the SSP port is a slave with respect to SSPSCLKx (defined by the /// ), this field is ignored and transmission data rates are /// determined by the external device. /// Before setting the ECS bit, first disable the port. The ECS (and NCS) bit /// must be configured before or at the same time that SSE is set. ///

/// When ECS is cleared, SSPEXTCLKx is treated as SSPSCLKENx, a clock /// enable that gates the SSPSCLKx output. When /// the SSPSCLKENx changes, there is a 12 clock lag before SSPSCLKx is /// started or stopped because of internal synchronization delays. ///

/// 0 = On-chip clock produces the SSP ports SSPSCLKx. /// 1 = SSPEXTCLK/GPIO pin creates the SSP ports SSPSCLKx. ///

/// NOTE: The ECS bit for SSP3, SSCR0_3.ECS, should never be set to one /// because the SSP3 does not have an associated SSPEXTCLK. /// [BitFieldRegister(Position = 6)] public bool ECS; ///

/// Frame format /// /// /// Selects which frame format to use. /// /// 0b00 = Motorola Serial Peripheral Interface /// 0b01 = TI Synchronous Serial Protocol /// 0b10 = Microwire /// 0b11 = Programmable Serial Protocol /// /// [BitFieldRegister(Position = 5, Size=2)] public uint FRF; /// /// Data size select /// /// /// Used in conjunction with EDSS to select the size of the data transmitted and /// received by the SSP port. The concatenated 5-bit value of EDSS and DSS /// provides a data range from four to 32-bits in length. ///

/// For the Microwire protocol, DSS and EDSS determine the receive data size. /// The size of the transmitted data is either eight or 16-bits (determined by /// ) and the EDSS bit is ignored. For all modes (including /// Microwire), EDSS and DSS determine the receive data size. ///

/// When data is programmed to be less than 32 bits, data written to the TX /// FIFO must be right-justified. ///

/// Data sizes /// /// EDSS == 0, DSS [0 .. 2] will reserved,undefined /// EDSS == 0, DSS [3 .. 15] will be [4bit .. 16bit] /// EDSS == 1, DSS [0 .. 15] data size will be [17bit .. 32bit] /// /// [BitFieldRegister(Position = 0, Size=4)] public uint DSS; } #endregion #region SSCR1 Bitfield ///

/// SSCR1, controls various SSP /// port functions. Before enabling the port (using /// ), /// the desired values for this register must be set. /// [BitFieldPeripheral(PhysicalType = typeof(uint))] public struct SSCR1_Bitfield { /// /// TXD tristate enable on last phase /// /// /// TTELP is used in conjunction with TTE. When set, TTELP causes /// SSPTXDx to become high impedance 1/2 phase later than specified in /// the TTE bit description under either of the following 2 conditions: 1) the /// format is SSP; or 2) the format is PSP and the SSP port is a slave to /// frame ( is set). For example, when in SSP format, /// with TTELP and TTE set, SSPTXDx goes to high impedance one full /// clock after the clock edge that starts the LSB. /// Ensure if SCLKDIR is set (SSP port is a slave to SSPSCLKx) that the /// device driving SSPSCLKx provides another clock edge. /// NOTE: TTELP must not be set when using Microwire or SPI formats /// 1 = SSPTXDx becomes high impedance one full clock after the clock /// edge that starts the LSB. /// 0 = SSPTXDx becomes high impedance 1/2 clock after the clock /// edge that starts the LSB. /// [BitFieldRegister(Position = 31)] public bool TTELP; /// /// TXD tristate enable /// /// /// If TTE is cleared, SSPTXDx is always driven. When set, TTE causes /// SSPTXDx to become high impedance when the SSP port is not /// transmitting data. The timing for the high impedance enable/disable /// varies according to the different serial formats and frame direction. /// For Microwire format, SSPTXDx is driven on the same clock edge that /// the MSB is driven, and SSPTXDx becomes high impedance one full /// clock after the clock edge that starts the LSB. ///

/// For SPI protocol, SSPTXDx becomes high impedance whenever /// SPSFRMx is deasserted (driven high). ///

/// For TI Synchronous Serial Protocol, SSPTXDx is driven at the first /// rising edge of the SSPSCLKx after SSPSFRMx is asserted (the same /// time the MSB is driven) and continues to be driven until 1/2 clock /// (TTELP = 1) or 1 full clock (TTELP = 0) after the clock edge that starts /// the LSB. ///

/// For PSP format when the SSP port is a slave to frame, SSPTXDx /// becomes high impedance 1/2 clock after the clock edge that starts the /// LSB. For PSP format when the SSP port is a master to frame, /// SSPTXDx becomes high impedance one full clock after the clock edge /// that starts the LSB (even if the SSP port is a master of clock and this /// clock edge does not appear on SSPSCLKx). ///

/// NOTE: TTE must be set when in network mode. /// 0 = SSPTXDx does not become high impedance. /// 1 = SSPTXDx becomes high impedance when not transmitting data. /// [BitFieldRegister(Position = 30)] public bool TTE; ///

/// Enable bit count error interrupt /// /// /// When set, EBCEI enables a bit count error interrupt. A bit count error /// occurs when the SSP port is a slave to SSPSCLKx and/or SSPSFRMx /// and the SSP port detects a new frame before the internal bit counter /// has reached 0 (before the LSB was driven). /// 0 = Interrupt due to a bit count error is disabled. /// 1 = Interrupt due to a bit count error is enabled. /// [BitFieldRegister(Position = 29)] public bool EBCEI; /// /// Slave clock free running /// /// /// In slave mode ( is set), SCFR must be cleared if /// the input clock from the external source is running continuously. /// In master mode ( is cleared), SCFR is ignored. /// Slave mode only: /// 0 = SSPSCLKx is continuously running. /// 1 = SSPSCLKx is active only during transfers. /// [BitFieldRegister(Position = 28)] public bool SCFR; /// /// Enable clock request A /// /// /// 0 = Clock request from another SSP port is disabled. /// 1 = Clock request from another SSP port is enabled. /// [BitFieldRegister(Position = 27)] public bool ECRA; /// /// Enable clock request B /// /// /// 0 = Clock request from another SSP port is disabled. /// 1 = Clock request from another SSP port is enabled. /// [BitFieldRegister(Position = 26)] public bool ECRB; /// /// SSPSCLKx direction /// /// /// SCLKDIR determines whether the port is the master or slave (with /// respect to driving SSPSCLKx). /// Depending on the frame format selected, each transmitted bit is driven /// on either the rising or falling edge of SSPSCLKx, and is sampled on the /// opposite clock edge. When the GPIO alternate function is selected for /// the SSP port, this bit has precedence over the GPIO direction bit. /// SCLKDIR must be written before the GPIO direction bit (to prevent any /// possible contention on SSPSCLKx). /// 0 = Master mode, the port generates SSPSCLKx internally, acts as /// the master, and drives SSPSCLKx. /// 1 = Slave mode, the port acts as a slave, receives SSPSCLKx from /// an external device and uses it to determine when to drive transmit /// data on SSPTXDx and when to sample receive data on /// SSPRXDx. /// NOTE: When SCLKDIR is set, the and /// bits must be cleared. /// [BitFieldRegister(Position = 25)] public bool SCLKDIR; /// /// SSP frame direction /// /// /// SFRMDIR determines whether the SSP port is the master or slave (with /// respect to driving SSPSFRMx). /// NOTE: When the port is configured as a slave to SSPSFRMx, the /// external device driving SSPSFRMx must wait until /// is cleared after enabling the port and before /// asserting SSPSFRMx (no external clock cycles are needed). /// When the GPIO alternate function is selected for the port, /// SFRMDIR has precedence over the GPIO direction bit. /// SFRMDIR must be written before the GPIO direction bit (to /// prevent any possible contention on SSPSFRMx). /// 0 = Master mode, the port generates SSPSFRMx internally, acts as /// the master and drives SSPSFRMx. /// 1 = Slave mode, the port acts as a slave, receives SSPSFRMx from /// an external device. /// [BitFieldRegister(Position = 24)] public bool SFRMDIR; /// /// Receive without transmit /// /// /// RWOT puts the SSP port into a mode similar to half duplex. This allows /// the port to receive data without transmitting data (half-duplex only). /// When the port is in master mode (SCLKDIR cleared) and RWOT is set, /// the port continues to clock in receive data, regardless of data existing in /// the transmit FIFO. Data is sent/received immediately after the port /// enable bit () is set. In this mode, if there /// is no data to send, the DMA service requests and interrupts for the transmit /// FIFO must be disabled (clear both .[TSRE,TIE]). If the transmit FIFO /// is empty, SSPTXDx is driven low. /// The transmit FIFO underrun condition does not occur when RWOT is /// set. When RWOT is set, remains set until software /// clears the RWOT bit. After RWOT is cleared, and extra frame cycle may /// occur due to synchronization delays between the processors clock /// domains. RWOT must not be used when is set. /// 0 = Transmit/receive mode. /// 1 = Receive without transmit mode. /// [BitFieldRegister(Position = 23)] public bool RWOT; /// /// Trailing byte /// /// /// TRAIL configures how trailing bytes are handled ///

/// 0 = Processor based, Trailing bytes are handled by the CPU. /// 1 = DMA based, Trailing bytes are handled by DMA. /// [BitFieldRegister(Position = 22)] public bool TRAIL; ///

/// Transmit service request enable /// /// /// TSRE enables the transmit FIFO DMA Service Request. /// NOTE: Clearing TSRE does not affect the current state of /// or the ability of the transmit FIFO logic to set and /// clear ; it prevents the generation of the DMA /// Service Request. The state of TSRE does not effect the /// generation of the interrupt, which is asserted whenever the /// is set. /// 0 = DMA service request is disabled and the state of the transmit /// FIFO DMA service request is ignored. /// 1 = DMA service request is enabled. /// [BitFieldRegister(Position = 21)] public bool TSRE; /// /// Receive service request enable /// /// /// RSRE enables the Receive FIFO DMA Service Request. /// NOTE: Clearing RSRE does not affect the current state of /// or the ability of the receive FIFO logic to set and /// clear ; it blocks only the generation of the DMA /// Service Request. The state of RFRS does not affect the /// generation of the interrupt, which is asserted whenever /// is set. /// 0 = DMA service request is disabled and the state of the /// is ignored. /// 1 = DMA service request is enabled. /// [BitFieldRegister(Position = 20)] public bool RSRE; /// /// Receiver time-out interrupt enable /// /// /// TINTE enables the receiver time-out interrupt. /// NOTE: Clearing TINTE does not affect the current state of /// or the ability of logic to set and clear /// ; it prevents the generation of the interrupt /// request. /// 0 = Receiver time-out interrupts are disabled. The interrupt is masked /// and the state of is ignored by the interrupt /// controller. /// 1 = Receiver time-out interrupts are enabled. /// [BitFieldRegister(Position = 19)] public bool TINTE; /// /// Peripheral trailing byte interrupt enable /// /// /// PINTE enables the peripheral trailing byte interrupt. /// NOTE: Clearing PINTE does not affect the current state of /// or the ability of logic to set and clear /// ; it prevents the generation of the interrupt /// request. /// 0 = Peripheral trailing byte interrupts are disabled. The interrupt is /// masked and the state of SSSRx.PINT is ignored by the interrupt /// controller. /// 1 = Peripheral trailing byte interrupt are enabled. /// [BitFieldRegister(Position = 18)] public bool PINTE; /// /// Invert frame signal /// /// /// 0 = SSPSFRMx polarity is determined by SSP format and PSP /// polarity bits. /// 1 = SSPSFRMx is inverted from the normal SSP frame signal (as /// defined by the SSP format and PSP polarity bits). /// [BitFieldRegister(Position = 16)] public bool IFS; /// /// Select FIFO for EFWR (test mode bit only) /// /// /// Only when is set, STRF selects whether the transmit /// or the receive FIFO is enabled for writes and reads. /// 0 = Transmit FIFO is selected for both writes and reads through /// SSDR /// 1 = Receive FIFO is selected for both writes and reads through /// SSDR /// [BitFieldRegister(Position = 15)] public bool STRF; /// /// Enable FIFO write/read (test mode bit) /// /// /// Enables test mode for the SSP port. /// When set, the SSP port enters a mode where whenever the CPU reads /// or writes to the SSP Data register, it reads and writes directly to either /// the transmit FIFO or the receive FIFO, depending on the programmed /// state of . /// In EFWR test mode, data is not transmitted on SSPTXDx, data input on /// SSPRXDx is not stored, and the Busy and ROR bits have no effect. /// However, the Interrupt Test register is still functional. Using software, /// this mode can test whether or not the TX FIFO or the RX FIFO operates /// properly as a FIFO memory stack. Verify that the bit has /// gone from set to clear before reading the TX FIFO. This bit must be /// cleared for normal operation. /// When is clear, writes to SSDR are performed on the /// Transmit FIFO, and reads from SSDR read back the data written to /// the TX FIFO in first-in-first-out order. When the STRF is set, writes to /// SSDR are performed on the RX FIFO, and reads from SSDR read /// back the data written to the RX FIFO in first-in-first-out order. /// 0 = FIFO write/read special function is disabled (normal SSP port /// operational mode) /// 1 = FIFO write/read special function is enabled. /// [BitFieldRegister(Position = 14)] public bool EFWR; /// /// Receive FIFO Threshold /// /// /// RFT sets the level at or above which the FIFO controller triggers a DMA /// service request (if enabled) and a CPU interrupt request (if enabled). /// This level must be set to the desired trigger threshold value minus 1. /// NOTE: Do not to set the value of RFT too high for the system; /// otherwise, the receive FIFO can overrun because of the bus /// latencies caused by other internal and external peripherals. /// This is especially important when using interrupts and polled /// modes that require a longer time to service. /// [BitFieldRegister(Position = 10, Size=4)] public uint RFT; /// /// Transmit FIFO Threshold /// /// /// TFT sets the level at or below which the FIFO controller triggers a DMA /// service request (if enabled) and a CPU interrupt request (if enabled). /// This level must be set to the desired trigger threshold value minus 1. /// NOTE: Do not set the value of TFT too low for the system; otherwise, /// the transmit FIFO can underrun because of the bus latencies /// caused by other internal and external peripherals. This is /// especially important when using interrupts and polled modes /// that require a longer time to service. /// [BitFieldRegister(Position = 6, Size=4)] public uint TFT; /// /// Microwire transit data size /// /// /// MWDS selects between an eight bit or 16-bit size for the command /// word transmitted using the Microwire protocol. MWDS is ignored for all /// other frame formats. /// 0 = 8-bit command word is transmitted. /// 1 = 16-bit command word is transmitted. /// [BitFieldRegister(Position = 5)] public bool MWDS; /// /// Motorola SPI SSPSCLKx Phase /// /// /// SPH determines the phase relationship between SSPSCLKx and the /// SSPSFRMx when the Motorola SPI format is selected. When SPH is /// clear, SSPSCLKx remains in its Inactive/Idle state (as determined by /// the setting) for one full cycle after SSPSFRMx is /// asserted low at the beginning of a frame. SSPSCLKx continues to /// toggle for the rest of the frame and is then held in its Inactive state for /// one-half of an SSPSCLKx period before SSPSFRMx is deasserted high /// at the end of the frame. /// When SPH is set, SSPSCLKx remains in its Inactive/Idle state (as /// determined by the bits value) for one-half cycle after /// SSPSFRMx is asserted low at the beginning of a frame. SSPSCLKx /// continues to toggle for the remainder of the frame, and is then held in its /// Inactive state for one full SSPSCLKx period before SSPSFRMx is /// deasserted high at the end of the frame. The combination of the /// bit and bit settings determines when /// SSPSCLKx is active during the assertion of SSPSFRMx, and which /// SSPSCLKx edge transmits and receives data on the SSPTXDx and /// SSPRXDx pins. /// When and are programmed to the /// same value (both clear or both set), SSPTXDx is driven on the falling /// edge of SSPSCLKx, and SSPRXDx is latched on the rising edge of /// SSPSCLKx. When and are /// programmed to opposite values (one clear and the other set), /// SSPTXDx is driven on the rising edge of SSPSCLKx and SSPRXDx is /// latched on the falling edge of SSPSCLKx. /// NOTE: SPH is ignored for all data frame formats except for the /// Motorola SPI format ( and . /// ). /// inverts the polarity of SSPSCLKx, and determines the /// phase relationship between SSPSCLKx and SSPSFRMx, shifting the /// SSPSCLKx one-half phase to the left or right during the assertion of /// SSPSFRMx. /// 0 = SSPSCLKx is inactive one cycle at the start of a frame and 1/2 /// cycle at the end of a frame. /// 1 = SSPSCLKx is inactive 1/2 cycle at the start of a frame and one /// cycle at the end of a frame. /// [BitFieldRegister(Position = 4)] public bool SPH; /// /// Motorol SPI SSPSCLKx Polarity /// /// /// SPO selects the polarity of the inactive state of SSPSCLKx when the /// SPI protocol is selected. /// The programmed setting of SPO alone does not determine which /// SSPSCLKx edge transmits or receives data; SPO in combination with /// does. /// NOTE: is ignored for all data frame formats except for /// SPI protocol ( = 0b00). /// 0 = SSPSCLKx is held low in the inactive or idle state when the SSP /// port is not transmitting/receiving data. /// 1 = SSPSCLKx is held high during the inactive or idle state. /// [BitFieldRegister(Position = 3)] public bool SPO; /// /// Loop-back mode (test-mode bit only) /// /// /// LBM is a test mode bit that enables and disables the ability of the SSP /// ports transmit and receive logic to communicate. /// NOTE: The loop-back mode cannot be used with the Microwire /// protocol since this protocol uses half-duplex master-slave /// message passing. /// 0 = Normal SSP port operation is enabled. /// 1 = Output of transmit serial shifter is internally connected to the input /// of the receive serial shifter. SSPTXDx continues to function /// normally. /// [BitFieldRegister(Position = 2)] public bool LBM; /// /// Transmit FIFO interrupt enable /// /// /// TIE enables the TX FIFO service request interrupt. /// NOTE: Clearing TIE does not affect the current state of /// or the ability of the transmit FIFO logic to set and clear /// it blocks only the generation of the interrupt /// request. Also, the state of TIE does not effect the generation of /// the transmit FIFO DMA service request, which is asserted /// whenever is set. /// 0 = TX FIFO level interrupt is disabled. The interrupt is masked and /// the state of is ignored. /// 1 = TX FIFO level interrupt is enabled. Whenever is /// set, an interrupt request is made to the interrupt controller. /// [BitFieldRegister(Position = 1)] public bool TIE; /// /// Receive FIFO interrupt enable /// /// /// RIE enables the RX FIFO service request interrupt. /// NOTE: Clearing RIE does not affect the current state of /// or the ability of the RX FIFO logic to set and clear /// it blocks only the generation of the interrupt /// request. The state of RIE does not affect the generation of the /// RX FIFO DMA service request, which is asserted whenever /// is set. /// 0 = RX FIFO level interrupt is disabled. The interrupt is masked and /// is ignored. /// 1 = RX FIFO level interrupt is enabled. Whenever is /// set, an interrupt request is made to the interrupt controller. /// [BitFieldRegister(Position = 0)] public bool RIE; } #endregion #region SSSR Bitfield /// /// SSP status register /// /// /// SSSR contains bit fields that signal overrun errors and the transmit and /// receive FIFO DMA service requests. Each of these hardware-detected events signal an interrupt /// request to the interrupt controller. The status register also contains flags that indicate: /// /// When the SSP port is actively transmitting data /// When the TX FIFO is not full /// When the RX FIFO is not empty /// /// One interrupt signal is sent to the interrupt controller for each SSP port. These events can cause an /// interrupt: /// /// End-of-chain /// Receiver time-out /// Peripheral trailing byte /// RX FIFO overrun /// RX FIFO request /// TX FIFO request /// /// An interrupt is signaled as long as the bits are set. The interrupt clears when the bits are cleared. /// Read and write bits are called status bits (status bits are referred to as sticky and once set by /// hardware, they must be cleared by software); read-only bits are called flags. Writing 0b1 to a sticky /// status bit clears it; writing 0b0 has no effect. Read-only flags are set and cleared by hardware; /// writes have no effect. The reset state of read-write bits is zero and all bits return to their reset state /// when is cleared. Additionally, some bits that cause interrupts have /// corresponding mask bits in the control registers. /// [BitFieldPeripheral(PhysicalType = typeof(uint))] public struct SSSR_Bitfield { /// /// Bit count error /// /// /// BCE is a read-write status bit that indicates that the SSP port has /// detected that SSPSFRMx has been asserted at an incorrect time. This /// causes an interrupt (if enabled by ). When set, BCE /// indicates that an error occurred and that to get re-synchronized to the /// master device, the SSP port may disregard both the sample that had /// SSPDFRMx re-asserted in the middle of it AND the next sample. ///

/// NOTE: BCE does not operate in Motorola SPI mode. ///

/// NOTE: To clear BCE, write 0b1 to it. ///

/// 0 = The SSP port has not experienced a bit count error /// 1 = SSPSFRMx has been asserted when the bit counter was not 0 ///

/// note: This bit is cleared on Write! /// [BitFieldRegister(Position = 23)] public bool BCE; ///

/// Clock synchronization status /// /// /// CSS indicates that the SSP port is busy synchronizing the control /// signals into the SSPSCLKx domain. Software only needs to check CSS /// when the SSP port is a slave to SSPSFRMx. Software must wait until /// CSS is cleared before allowing an external device to assert /// SSPSFRMx. ///

/// 0 = The SSP port is ready for slave clock operations /// 1 = The SSP port is currently busy synchronizing slave mode signals /// [BitFieldRegister(Position = 22, Modifiers = BitFieldModifier.ReadOnly)] public bool CSS; ///

/// Transmit FIFO underrung /// /// /// TUR indicates that the transmitter tried to send data from the TX FIFO /// when the TX FIFO was empty. When set, an interrupt is generated to /// the CPU (that can be locally masked by the bit). /// Setting TUR does not generate any DMA service request. TUR remains set /// until cleared by software writing 0b1 to it (which also resets its interrupt /// request). Writing 0b0 to TUR has no effect. /// TUR can be set when the SSP port is a slave to SSPSFRMx /// ( set), or if the SSP port is a master to SSPSFRMx /// and the SSP port is in network mode. TUR is not set if the SSP port is in /// receive-without-transmit mode ( set). /// 0 = TX FIFO has not experienced an underrun /// 1 = Transmitter tried to send data from the TX FIFO when the FIFO /// was empty, an interrupt is signaled ///

/// note: This bit is cleared on Write! /// [BitFieldRegister(Position = 21)] public bool GCAD; ///

/// Endo of chain /// /// /// EOC indicates that the DMA has signaled an end of chain. The end- ofchain /// event indicates that the DMA descriptor for the RX FIFO is /// ending. This event requires software intervention if data remains in the /// RX FIFO. ///

/// NOTE: To clear EOC, write 0b1 to it. /// 0 = DMA has not signaled an end of chain condition. /// 1 = DMA has signaled an end of chain condition. An EOC interrupt is /// only generated when either there are trailing bytes left (the PINT /// bit is set) or there are no trailing bytes (the TINT bit is set). /// EOC bit is always set, but does not generate an interrupt if neither /// of the these conditions are met. ///

/// note: This bit is cleared on Write! /// [BitFieldRegister(Position = 20)] public bool EOC; ///

/// Time-out interrupt /// /// /// TINT indicates that the RX FIFO has been idle (no samples received) /// for the period of time defined by the value programmed within SSTO. /// This interrupt can be masked by . /// NOTE: To clear TINT, write 0b1 to it. /// 0 = No Receiver Time-out has occurred /// 1 = Receiver Time-out has occurred ///

/// note: This bit is cleared on Write! /// [BitFieldRegister(Position = 19)] public bool TINT; ///

/// Peripheral trailing byte interrupt /// /// /// PINT indicates that a DMA end of chain event has occurred and there is /// data within the RX FIFO. This event requires the CPU or DMA to /// transfer the remaining bytes from the RX FIFO. ///

/// This interrupt can be masked by . /// NOTE: To clear PINT, write 0b1 to it. /// 0 = No peripheral trailing byte interrupt is pending. /// 1 = Peripheral trailing byte interrupt is pending ///

/// note: This bit is cleared on Write! /// [BitFieldRegister(Position = 18)] public bool PINT; ///

/// RX FIFO Level /// /// /// RFL is the number of valid entries (minus 1) currently in the RX FIFO. /// NOTE: When the value of 0xF is read, the RX FIFO is either empty or /// full and programmers must refer to the RNE bit. /// [BitFieldRegister(Position = 12, Size=4, Modifiers = BitFieldModifier.ReadOnly)] public uint RFL; /// /// TX FIFO Level /// /// /// TFL is the number of valid entries currently in the TX FIFO. /// NOTE: When the value of 0x0 is read, the TX FIFO is either empty or /// full and programmers must refer to the TNF bit. /// [BitFieldRegister(Position = 8, Size = 4, Modifiers = BitFieldModifier.ReadOnly)] public uint TFL; /// /// RX FIFO Overrun /// /// /// ROR indicates that the Receive logic attempted to place data into the /// RX FIFO after it had been completely filled. When new data is received, /// ROR is asserted and the newly received data is discarded. This /// process is repeated for all new data received until at least one empty /// RX FIFO location exists. /// When set, an interrupt is generated to the CPU that can be locally /// masked by the bit. Setting ROR does not /// generate any DMA service request. Clearing ROR resets its interrupt request. /// NOTE: To clear ROR, write 0b1 to it. /// 0 = RX FIFO has not experienced an overrun /// 1 = Attempted data write to a full RX FIFO, request an interrupt ///

/// note: This bit is cleared on Write! /// [BitFieldRegister(Position = 7)] public bool ROR; ///

/// Receive FIFO Service /// /// /// A RFS request indicates that the RX FIFO requires service to prevent /// an overrun. RFS is set when the number of valid entries in the RX FIFO /// is equal to or greater than the RX FIFO trigger threshold. RFS is cleared /// when the RX FIFO has fewer entries than the trigger threshold. When /// RFS is set, an interrupt is generated if is set. When RFS /// is set, a DMA service request is generated if is set. /// After the CPU or DMA reads the RX FIFO such that it has fewer entries /// than the value of , RFS (and the service request and/or /// interrupt) is automatically cleared. and /// must not both be set. /// 0 = RX FIFO level is less than its trigger threshold or the SSP port is /// disabled /// 1 = RX FIFO level is equal to or above its trigger threshold, an /// interrupt or DMA service request is generated. /// [BitFieldRegister(Position = 6, Modifiers = BitFieldModifier.ReadOnly)] public bool RFS; /// /// Transmit FIFO Service. /// /// /// A TFS request indicates that the TX FIFO requires service to prevent an /// underrun. TFS is set when the number of valid entries in the TX FIFO is /// equal to or less than the TX FIFO trigger threshold. TFS is cleared /// when the TX FIFO has more entries than the trigger threshold. When /// TFS is set, an interrupt is generated if is set. When TFS /// is set, a DMA service request is generated if is set. /// After the CPU or DMA fills the TX FIFO such that it has more entries /// than the value of , TFS (and the service request and/or /// interrupt) is automatically cleared. /// and must not both be set. /// 0 = TX FIFO level exceeds its threshold (TFT + 1) or the SSP port is /// disabled /// 1 = TX FIFO level is at or below its trigger threshold (TFT + 1), an /// interrupt or DMA service request is generated. /// [BitFieldRegister(Position = 5, Modifiers = BitFieldModifier.ReadOnly)] public bool TFS; /// /// Busy /// /// /// BSY is automatically set when the SSP port is actively transmitting /// and/or receiving data and BSY is automatically cleared when the SSP /// port is idle or disabled. BSY does not generate an interrupt. /// NOTE: When the SSP port is a master of a clock, software determines /// if the SSP port is active by monitoring and /// . If the SSP port is a slave to a clock, software /// determines if the SSP port is active by monitoring /// , /// and along with the /// SSTO register. Also, using the time-out feature (the SSTO /// register and ) to handle trailing bytes provides /// an indication of when the master has completed sending data. /// 0 = SSP port is idle or disabled /// 1 = SSP port is actively transmitting or receiving data /// [BitFieldRegister(Position = 4, Modifiers = BitFieldModifier.ReadOnly)] public bool BSY; /// /// RX FIFO not empty /// /// /// RNE indicates that the RX FIFO contains one or more entries of valid /// data. RNE is automatically cleared when the RX FIFO no longer /// contains any valid data. This bit does not generate an interrupt. /// When using programmed I/O, RNE can be polled to remove remaining /// bytes of data from the RX FIFO since CPU interrupt requests are made /// only when the RX FIFO trigger threshold has been met or exceeded. /// 0 = RX FIFO is empty. /// 1 = RX FIFO is not empty. /// [BitFieldRegister(Position = 3, Modifiers = BitFieldModifier.ReadOnly)] public bool RNE; /// /// TX FIFO not full /// /// /// TNF indicates that the TX FIFO contains one or more entries that do not /// contain valid data. TNF is automatically cleared when the TX FIFO is /// completely full. TNF does not generate an interrupt. /// When using programmed I/O, TNF can be polled to fill the TX FIFO /// beyond its trigger threshold. /// 0 = TX FIFO is full /// 1 = TX FIFO is not full /// [BitFieldRegister(Position = 2, Modifiers = BitFieldModifier.ReadOnly)] public bool TNF; } #endregion #region SSITR Bitfield /// /// SSITR, contains bit fields used for testing purposes only. /// /// /// Setting bits in this register causes the SSP port controller to generate interrupts and DMA requests /// if they are enabled. This is useful in testing the ports functionality. /// Setting any of these bits also causes corresponding status bits to be set in . /// The interrupt or DMA service request, caused by the setting of one of these bits remains active until /// the bit is cleared. This register must be 0 for normal operation. /// [BitFieldPeripheral(PhysicalType = typeof(uint))] public struct SSITR1_Bitfield { /// /// Test RX FIFO overrun /// /// /// 0 = No receive FIFO overrun DMA service request is generated. /// 1 = Generates a non-maskable interrupt to the CPU. No DMA request /// is generated. Write 0b0 to clear. /// [BitFieldRegister(Position = 7)] public bool TROR; /// /// Test RX FIFO Service Request /// /// /// 0 = No receive FIFO DMA service request is generated. /// 1 = Generates a non-maskable interrupt to the CPU and a DMA /// request for the RX FIFO. Write 0b0 to clear. /// [BitFieldRegister(Position = 6)] public bool TRFS; /// /// Test TX Service Request /// /// /// 0 = No transmit FIFO DMA service request is generated. /// 1 = Generates a non-maskable interrupt to the CPU and a DMA /// request for the TX FIFO. Write 0b0 to clear. /// [BitFieldRegister(Position = 5)] public bool TTFS; } #endregion #region SSPSP Bitfield /// /// SSITR contains bit fields used for testing purposes only. /// Setting bits in this register causes the SSP port controller to generate interrupts and DMA requests /// if they are enabled. This is useful in testing the ports functionality. /// Setting any of these bits also causes corresponding status bits to be set in . /// The interrupt or DMA service request, caused by the setting of one of these bits remains active until the /// bit is cleared. This register must be 0 for normal operation. /// [BitFieldPeripheral(PhysicalType = typeof(uint))] public struct SSPSP1_Bitfield { /// /// Frame sync relative timing /// /// /// 0 = Next frame is asserted after the end of the T4 timing /// 1 = Next frame is asserted with the LSB of the previous frame /// NOTE: When FSRT is set, SSPSFRMx corresponding to the next /// sample is asserted during the transmission of the LSB from the /// current sample /// [BitFieldRegister(Position = 25)] public bool FSRT; /// /// Dummy stop /// /// /// DMYSTOP determines the number of cycles that SSPSCLKx is active /// following the last bit (bit 0) of transmitted data (SSPTXDx) or received /// data (SSPRXDx). The value must be from 0 to 3. DMYSTOP must be /// cleared when PSP format is used in network mode and/or when FSRT /// is set. /// [BitFieldRegister(Position = 23, Size=2)] public uint DMYSTOP; /// /// Serial Frame Width /// /// /// SFRMWDTH determines the number of SSPSCLKx cycles that /// SSPSFRMx is active. /// The programmed value must not be asserted past the end of /// DMYSTOP. The value must be from 1 to 44. /// In PSP slave mode ( is set), SFRMWDTH is /// ignored. The incoming SSPSFRMx must be asserted for a duration of at /// least one SSPSCLKx cycle for each sample. The incoming SSPSFRMx /// and first data bit of the sample can be asserted at the same time. /// Between samples, the incoming SSPSFRMx must be deasserted for a /// duration of at least one SSPSCLKx cycle. /// [BitFieldRegister(Position = 16, Size=6)] public uint SFRMWDTH; /// /// Serial Frame Delay /// /// /// SFRMDLY determines the number of half SSPSCLKx cycles that /// SSPSFRMx is delayed from the start of the transfer to the time /// SSPSFRMx is asserted. The value must be from 0 to 88. /// [BitFieldRegister(Position = 9, Size=7)] public uint SFRMDLY; /// /// Dummy Start /// /// /// DMYSTRT determines the number of SSPSCLKx cycles after /// STRTDLY and before transmitted data (SSPTXDx) or received data /// (SSPRXDx). /// [BitFieldRegister(Position = 7, Size=2)] public uint DMYSTRT; /// /// Start Delay /// /// /// STRTDLY determines the number of cycles that SSPSCLKx remains in /// its Idle state between data transfers. The STRTDLY field must be /// cleared if the SSPSCLKENx, , /// or /// clock enables are used. The STRTDLY field must be cleared whenever /// SSPSCLKx or SSPSFRMx is configured as an input /// ( or /// are set). The value must be from 0 to 7. /// [BitFieldRegister(Position = 4, Size=3)] public uint STRTDLY; /// /// End-of-Transfer Data State /// /// /// ETDS determines the state of SSPTXDx at the end of a transfer. When /// cleared, the state of SSPTXDx is forced low after the LSB of the frame /// is sent and remains low through the next idle period. When set, the /// state of SSPTXDx retains the value of the LSB through the next idle /// period. /// NOTE: ETDS has no effect if is set. /// NOTE: ETDS bit has no effect when configured in TI Synchronous /// Serial Protocol. /// 0 = Low /// 1 = Last Value <Bit 0> /// [BitFieldRegister(Position = 3)] public bool ETDS; /// /// Serial Frame Polarity /// /// /// SFRMP determines the active state of SSPSFRMx. /// In idle mode or when the SSP port is disabled, SSPSFRMx is in its /// inactive state. In slave mode ( is set), SFRMP /// indicates the polarity of the incoming SSPSFRMx. /// 0 = SSPSFRMx is active low. /// 1 = SSPSFRMx is active high. /// [BitFieldRegister(Position = 2)] public bool SFRMP; /// /// Serial Bit-Rate clock mode /// /// /// SCMODE selects one of four serial clock modes when PSP format is /// used ( = 0b11). /// Its operation is similar to how /// and /// together determine the idle state of SSPSCLKx and on which edges /// data is driven and sampled. /// /// 0b00 = Data Driven (Falling), Data Sampled (Rising), Idle State (Low) /// 0b01 = Data Driven (Rising), Data Sampled (Falling), Idle State (Low) /// 0b10 = Data Driven (Rising), Data Sampled (Falling), Idle State (High) /// 0b11 = Data Driven (Falling), Data Sampled (Rising), Idle State (High) /// /// NOTE: For all selections of SCMODE, the Idle State is high impedance /// when is set. /// [BitFieldRegister(Position = 0, Size=2)] public uint SCMODE; } #endregion #region SSTSS Bitfield /// /// These registers indicate which time slot the SSP port is currently in. SSTSS are ignored when the /// SSP port is not in network mode. /// [BitFieldPeripheral(PhysicalType = typeof(uint))] public struct SSTSS_Bitfield { /// /// Network mode busy /// /// /// Only if the SSP port is in network mode, NMBSY indicates when the SSP /// port is in the middle of a frame. NMBSY can be used by software when a /// clean shutdown of the SSP port is needed. Software must ensure that the /// TX FIFO is either empty (or will be empty at the end of the next frame), /// deactivate the TX DMA requests, clear the bit; /// then software must poll NMBSY until it is 0 before disabling the SSP port (by /// clearing the bit). /// When the SSP port is a master of SSPSFRMx, NMBSY is set. If the SSP /// port is a slave to SSPSFRMx, NMBSY is set only if the current frame /// (number of bits per sample number of time slots per frame) has not expired /// since SSPSFRMx was asserted. /// 0 = No SSPSFRMx is currently asserted (network mode only) /// 1 = SSPSFRMx is currently asserted (network mode only) /// [BitFieldRegister(Position = 31, Modifiers= BitFieldModifier.ReadOnly)] public bool NMBSY; /// /// Time slot status /// /// /// Only if the SSP port is in network mode, the 3-bit TSS value indicates which /// time slot the SSP port is in. Due to synchronization delays between clock /// domains, the TSS value is a delayed version of the actual time slot. /// [BitFieldRegister(Position = 0, Size=3, Modifiers = BitFieldModifier.ReadOnly)] public uint TSS; } #endregion #region SSACD Bitfield /// /// SSACD select which clock frequency is sent to the SSP port and then to SSPSYSCLKx and /// SSPSCLKx. If is not 0, there is no guaranteed phase relationship between /// SSPSYSCLKx and SSPSCLKx. SSPSYSCLKxs frequency is calculated by /// dividing the chosen PLL output clock frequency () by the chosen divider /// (). SSPSYSCLKx is then divided by 4 (or by 1) to get SSPSCLKx /// SSPSFRMxs frequency is calculated by dividing SSPSCLKx by the multiplyproduct /// of data size (.[EDSS, DSS] values) times the number of time slots being used /// ( value). /// [BitFieldPeripheral(PhysicalType = typeof(uint))] public struct SSACD_Bitfield { /// /// Audio Clock PLL select /// /// /// The ACPS value indicates which PLL output clock is sent to the clock /// divider. /// Some combinations of ACPS and ACDS are not valid. /// /// ACPS 0b000 results in PLL output frequency 5.622MHz /// ACPS 0b001 results in PLL output frequency 11.345MHz /// ACPS 0b010 results in PLL output frequency 12.235MHz /// ACPS 0b011 results in PLL output frequency 14.857Hz /// ACPS 0b100 results in PLL output frequency 32.842MHz /// ACPS 0b101 results in PLL output frequency 48.000MHz /// ACPS 0b110 results in PLL output frequency RESERVED /// ACPS 0b111 results in PLL output frequency RESERVED /// /// [BitFieldRegister(Position = 4, Size=3)] public uint ACPS; /// /// SSPSYSCLK divider bypass /// /// /// If SCDB is set and is set, SSPSYSCLKx is divided by 1 to /// become SSPSCLKx. If SCDB is cleared and is set), /// SSPSYSCLKx is divided by 4 to become SSPSCLKx. If is /// cleared, SCDB has no effect. ///

/// 0 = SSPSYSCLKx is divided by 4 to become SSPSCLKx /// 1 = SSPSYSCLKx is divided by 1 to become SSPSCLKx /// [BitFieldRegister(Position = 3)] public bool SCDB; ///

/// Audio clock divider select /// /// /// The ACDS value indicates which divider creates SSPSYSCLKx. /// Some combinations of ACPS and ACDS are not valid. /// /// ACDS 0b000 results in clock divider value 1 /// ACDS 0b001 results in clock divider value 2 /// ACDS 0b010 results in clock divider value 4 /// ACDS 0b011 results in clock divider value 8 /// ACDS 0b100 results in clock divider value 16 /// ACDS 0b101 results in clock divider value 32 /// ACDS 0b110 results in clock divider value RESERVED /// ACDS 0b111 results in clock divider value RESERVED /// /// [BitFieldRegister(Position = 0, Size=3)] public uint ACDS; } #endregion #region SSP channel definition /// /// Aggregation of all registers of a SSP channel. /// [MemoryMappedPeripheral(Base=0, Length = 0x40)] public class SSP_Channel { #region Register Bank /// /// Control register 0 /// /// /// SSCR0 controls various functions within the SSP port. /// Before enabling the SSP port by setting , /// the desired values for this register must be programmed. /// [Register(Offset = 0x00000000U, Instances = 1)] public SSCR0_Bitfield SSCR0;// = new uint[1]; /// /// Control register 1 /// /// /// SSCR1 controls various SSP /// port functions. Before enabling the port (using /// ), the desired values for this register must be set. /// [Register(Offset = 0x00000004U, Instances = 1)] public SSCR1_Bitfield SSCR1;// = new uint[1]; /// /// Status register /// /// /// SSSR contains bit fields that signal overrun errors and the transmit and /// receive FIFO DMA service requests. Each of these hardware-detected events signal an interrupt /// request to the interrupt controller. The status register also contains flags that indicate: /// /// When the SSP port is actively transmitting data /// When the TX FIFO is not full /// When the RX FIFO is not empty /// /// One interrupt signal is sent to the interrupt controller for each SSP port. These events can cause an /// interrupt: /// /// End-of-chain /// Receiver time-out /// Peripheral trailing byte /// RX FIFO overrun /// RX FIFO request /// TX FIFO request /// /// An interrupt is signaled as long as the bits are set. The interrupt clears when the bits are cleared. /// Read and write bits are called status bits (status bits are referred to as sticky and once set by /// hardware, they must be cleared by software); read-only bits are called flags. Writing 0b1 to a sticky /// status bit clears it; writing 0b0 has no effect. Read-only flags are set and cleared by hardware; /// writes have no effect. The reset state of read-write bits is zero and all bits return to their reset state /// when is cleared. Additionally, some bits that cause interrupts have corresponding /// mask bits in the control registers. /// [Register(Offset = 0x00000008U, Instances = 1)] public SSSR_Bitfield SSSR;// = new uint[1]; /// /// Interrupt test register /// /// /// Setting bits in this register causes the SSP port controller to generate interrupts and DMA requests /// if they are enabled. This is useful in testing the ports functionality. /// Setting any of these bits also causes corresponding status bits to be set in . /// The interrupt or DMA service request, caused by the setting of one of these bits remains active until the bit is /// cleared. This register must be 0 for normal operation. /// [Register(Offset = 0x0000000CU, Instances = 1)] public SSITR1_Bitfield SSITR;// = new uint[1]; /// /// Data write register/data read register /// /// /// SSDR is a single address location that is accessed by both read and write /// data transfers. Each SSDR register represents two physical registers: the first register provides /// temporary storage for data on its way to the TX FIFO and the 2nd register provides temporary /// storage for data coming from the RX FIFO. ///

/// As the CPU or DMA accesses the SSDR registers, FIFO control logic transfers data /// automatically between the registers and FIFOs as fast as the CPU or DMA moves it. Data in the /// FIFOs shift up or down to accommodate new word(s), unless attempting a write to a full transmit /// FIFO. Status bits (such as .[TFL, RFL, TNF, RNE]) show if the FIFO is full, above the /// programmable trigger threshold, below the programmable trigger threshold, or empty. /// For transmit data, SSDR can be loaded (written) by the processor (using programmed I/O or /// DMA) anytime the TX FIFO falls below its trigger threshold. ///

/// When a data size of less than 32-bits is selected, do not left-justify transmit data that is written to /// SSDR. Transmit logic left-justifies the data and ignores any unused bits. Received data of less /// than 32-bits is automatically right-justified in the RX FIFO. ///

/// When the SSP port is programmed for the Microwire protocol and the size of the transmit data is /// eight bits ( cleared), the most significant 24-bits are ignored. Similarly, if the /// size for the Transmit data is 16-bits ( set), the most significant 16-bits are /// ignored. controls the Receive data size. ///

/// Both the TX and RX FIFOs are cleared when the SSP port is reset, or by clearing . /// [Register(Offset = 0x00000010U, Instances = 1)] public uint SSDR;// = new uint[1]; ///

/// Time-out register /// /// /// SSTO specifies the time-out value to signal a period of inactivity within the /// receive FIFO. ///

/// The size of this register is 24bits. /// [Register(Offset = 0x00000028U, Instances = 1)] public uint SSTO;// = new uint[1]; ///

/// Programmable serial protocol /// /// /// SSITR contains bit fields used for testing purposes only. /// Setting bits in this register causes the SSP port controller to generate interrupts and DMA requests /// if they are enabled. This is useful in testing the ports functionality. /// Setting any of these bits also causes corresponding status bits to be set in . /// The interrupt or DMA service request, caused by the setting of one of these bits remains active until the bit is /// cleared. This register must be 0 for normal operation. /// [Register(Offset = 0x0000002CU, Instances = 1)] public SSPSP1_Bitfield SSPSP;// = new uint[1]; /// /// TX timeslot active register /// /// /// SSTSA are read-write registers that indicate in which time slot the SSP port transmits data. /// SSTSA are ignored if the SSP port is not in network mode ( = 1). ///

/// Only if the SSP port is in network mode, the 8 TTSA bits indicate in which of /// 8 associated time slots the SSP port transmits. Each TTSA bit selects one /// time slot, respectively. Time slot bits beyond the value are /// ignored (if = 0b011 to select 4 time slots, then TTSA bits /// 7:4 are ignored). If is set, then the SSP port causes /// SSPTXD to be high impedance during time slots where associated TTSA /// bits are programmed to 0. /// 0 = SSP port does not transmit data in this time slot /// 1 = SSP port transmits data in this time slot ///

/// note: valid are the lowest 8 bits. /// [Register(Offset = 0x00000030U, Instances = 1)] public uint SSTSA;// = new uint[1]; ///

/// RX timeslot active register /// /// /// SSRSA are read-write registers that indicate in which time slots the SSP port receives data. /// SSRSA are ignored if the SSP port is not in network mode. ///

/// Only if the SSP port is in network mode, the 8 RTSA bits indicate in which of /// 8 associated time slots the SSP port receives data. Each RTSA bit selects /// one time slot, respectively. Time slot bits beyond the /// value is ignored (if = 0b011 to select 4 time slots, then /// RTSA bits 7:4 are ignored). /// 0 = SP port does not receive data in this time slot /// 1 = SSP port receives data in this time slot ///

/// note: valid are the lowest 8 bits. /// [Register(Offset = 0x00000034U, Instances = 1)] public uint SSRSA;// = new uint[1]; ///

/// Timeslot status register /// /// /// These registers indicate which time slot the SSP port is currently in. SSTSS are ignored when the /// SSP port is not in network mode. /// [Register(Offset = 0x00000038U, Instances = 1)] public SSTSS_Bitfield SSTSS;// = new uint[1]; /// /// Audio clock divider register /// /// /// SSACD select which clock frequency is sent to the SSP port and then to SSPSYSCLKx and /// SSPSCLKx. If is not 0, there is no guaranteed phase relationship between /// SSPSYSCLKx and SSPSCLKx. SSPSYSCLKxs frequency is calculated by /// dividing the chosen PLL output clock frequency () by the chosen divider /// (). SSPSYSCLKx is then divided by 4 (or by 1) to get SSPSCLKx. SSPSFRMxs /// frequency is calculated by dividing SSPSCLKx by the multiplyproduct /// of data size (.[EDSS, DSS] values) times the number of time slots being used /// ( value). /// [Register(Offset = 0x0000003CU, Instances = 1)] public SSACD_Bitfield SSACD;// = new uint[1]; #endregion } #endregion #region Available SSP channels (SSP1 - SSP3) /// /// SSP channel 1 /// [Register(Offset = 0)] public SSP_Channel SSP1; /// /// SSP channel 2 /// [Register(Offset = 0x700000)] public SSP_Channel SSP2; /// /// SSP channel 3 /// [Register(Offset = 0x900000)] public SSP_Channel SSP3; #endregion #region Singleton data #if TESTMODE_DESKTOP private static SSP s_instance; /// /// The singleton for the SSP subsystem. /// public static SSP Instance { get { if (null != s_instance) return s_instance; s_instance = new SSP(); s_instance.SSP1 = new SSP_Channel(); s_instance.SSP1.SSACD = new SSACD_Bitfield(); s_instance.SSP1.SSCR0 = new SSCR0_Bitfield(); s_instance.SSP1.SSCR1 = new SSCR1_Bitfield(); s_instance.SSP1.SSITR = new SSITR1_Bitfield(); s_instance.SSP1.SSPSP = new SSPSP1_Bitfield(); s_instance.SSP1.SSSR = new SSSR_Bitfield(); s_instance.SSP1.SSTSS = new SSTSS_Bitfield(); s_instance.SSP2 = new SSP_Channel(); s_instance.SSP2.SSACD = new SSACD_Bitfield(); s_instance.SSP2.SSCR0 = new SSCR0_Bitfield(); s_instance.SSP2.SSCR1 = new SSCR1_Bitfield(); s_instance.SSP2.SSITR = new SSITR1_Bitfield(); s_instance.SSP2.SSPSP = new SSPSP1_Bitfield(); s_instance.SSP2.SSSR = new SSSR_Bitfield(); s_instance.SSP2.SSTSS = new SSTSS_Bitfield(); s_instance.SSP3 = new SSP_Channel(); s_instance.SSP3.SSACD = new SSACD_Bitfield(); s_instance.SSP3.SSCR0 = new SSCR0_Bitfield(); s_instance.SSP3.SSCR1 = new SSCR1_Bitfield(); s_instance.SSP3.SSITR = new SSITR1_Bitfield(); s_instance.SSP3.SSPSP = new SSPSP1_Bitfield(); s_instance.SSP3.SSSR = new SSSR_Bitfield(); s_instance.SSP3.SSTSS = new SSTSS_Bitfield(); return s_instance; } } #else /// /// The singleton for the SSP subsystem. /// public static extern SSP Instance { [SingletonFactory()] [MethodImpl(MethodImplOptions.InternalCall)] get; } #endif #endregion } } ================================================ FILE: Zelig/Zelig/RunTime/DeviceModels/ModelForPXA27x/HardwareModel/ChipSet/PXA27x/StackedFlashChip.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // namespace Microsoft.DeviceModels.Chipset.PXA27x { using System; using System.Runtime.CompilerServices; using Microsoft.Zelig.Runtime; public static class StackedFlashChip { // the following are the constant for Intel I28F chips public const ushort PROGRAM_WORD = 0x0040; public const ushort BUFFERED_PROGRAM_WORD = 0x00E8; public const ushort BUFFERED_PROGRAM_CONFIRM = 0x00D0; public const ushort READ_STATUS_REGISTER = 0x0070; public const ushort SR_PROTECT_ERROR = 0x0002; public const ushort SR_VPP_ERROR = 0x0008; public const ushort SR_PROGRAM_ERROR = 0x0010; public const ushort SR_ERASE_ERROR = 0x0020; public const ushort SR_ERASE_SUSPENDED = 0x0040; public const ushort SR_WSM_READY = 0x0080; public const ushort CLEAR_STATUS_REGISTER = 0x0050; public const ushort ENTER_READ_ARRAY_MODE = 0x00FF; public const ushort READ_ID = 0x0090; public const ushort LOCK_STATUS_LOCKED = 0x0001; public const ushort LOCK_STATUS_LOCKED_DOWN = 0x0002; public const ushort BLOCK_ERASE_SETUP = 0x0020; public const ushort BLOCK_ERASE_CONFIRM = 0x00D0; public const ushort LOCK_SETUP = 0x0060; public const ushort LOCK_LOCK_BLOCK = 0x0001; public const ushort LOCK_UNLOCK_BLOCK = 0x00D0; public const ushort LOCK_LOCK_DOWN_BLOCK = 0x002F; public const ushort CONFIG_SETUP = 0x0060; // Command to set up configuration word write public const ushort CONFIG_WRITE = 0x0003; // Command to perform configuration word write (from LO 16 address lines) // Read Configuration Register definitions public const ushort FLASH_CONFIG_RESERVED = 0x0580; // Bits which must always be set public const ushort FLASH_CONFIG_ASYNC = 0x8000; // Asynchronous operation public const ushort FLASH_CONFIG_SYNC = 0x0000; // Synchronous operation public const ushort FLASH_CONFIG_LAT_SHIFT = 11; // Shift for read latency (2-7 clocks) public const ushort FLASH_CONFIG_DATA_HOLD_1 = 0x0000; // Data hold for 1 clock public const ushort FLASH_CONFIG_DATA_HOLD_2 = 0x0200; // Data hold for 2 clocks public const ushort FLASH_CONFIG_CLK_HI_EDGE = 0x0040; // Clock active on rising edge public const ushort FLASH_CONFIG_CLK_LW_EDGE = 0x0000; // Clock active on falling edge public const ushort FLASH_CONFIG_BURST_WRAP = 0x0000; // Data burst wraps public const ushort FLASH_CONFIG_NO_WRAP = 0x0008; // Data burst does not wrap public const ushort FLASH_CONFIG_BURST_8 = 0x0002; // Data burst is 8 words long public const ushort FLASH_CONFIG_BURST_16 = 0x0003; // Data burst is 16 words long // // Helper Methods // [DisableNullChecks] [DisableBoundsChecks()] [NoInline] [MemoryRequirements(MemoryAttributes.RAM)] public static unsafe ushort InitializeFLASH( uint address, ushort val ) { ushort* flash = (ushort*)new UIntPtr( address ).ToPointer(); flash[val] = CONFIG_SETUP; flash[val] = CONFIG_WRITE; flash[0] = ENTER_READ_ARRAY_MODE; return flash[0]; } [DisableNullChecks] [DisableBoundsChecks()] [NoInline] [MemoryUsage(MemoryUsage.Bootstrap)] public static unsafe uint InitializeSDRAM( uint address ) { uint* sdram = (uint*)new UIntPtr( address ).ToPointer(); return sdram[0]; } [DisableNullChecks] [DisableBoundsChecks()] [NoInline] [MemoryRequirements(MemoryAttributes.RAM)] public static unsafe void EnterCFI( ushort* sectorStart ) { sectorStart[0x555] = 0x98; } [DisableNullChecks] [DisableBoundsChecks()] [NoInline] [MemoryRequirements(MemoryAttributes.RAM)] public static unsafe void ExitCFI( ushort* sectorStart ) { *sectorStart = ENTER_READ_ARRAY_MODE; } [DisableNullChecks] [DisableBoundsChecks()] [NoInline] [MemoryRequirements(MemoryAttributes.RAM)] public static unsafe void UnlockFlashSector( ushort* sectorStart ) { *sectorStart = LOCK_SETUP; *sectorStart = LOCK_UNLOCK_BLOCK; *sectorStart = ENTER_READ_ARRAY_MODE; } [DisableNullChecks] [DisableBoundsChecks()] [NoInline] [MemoryRequirements(MemoryAttributes.RAM)] public static unsafe uint EraseFlashSector( ushort* sectorStart ) { // // now setup erasing // *sectorStart = BLOCK_ERASE_SETUP; *sectorStart = BLOCK_ERASE_CONFIRM; // wait for device to signal completion // break when the device signals completion by looking for Data (0xff erasure value) on I/O 7 (a 0 on I/O 7 indicates erasure in progress) while((*sectorStart & SR_WSM_READY) != SR_WSM_READY) { } uint result = *sectorStart; // // error conditions must be cleared // *sectorStart = CLEAR_STATUS_REGISTER; *sectorStart = ENTER_READ_ARRAY_MODE; return result; } [DisableNullChecks] [DisableBoundsChecks()] [NoInline] [MemoryRequirements(MemoryAttributes.RAM)] public static unsafe uint ProgramFlashWord( ushort* address , ushort value ) { *address = PROGRAM_WORD; *address = value; // // Wait for device to signal completion // break when the device signals completion by looking for Data (0xff erasure value) on I/O 7 (a 0 on I/O 7 indicates erasure in progress) // while((*address & SR_WSM_READY) != SR_WSM_READY); uint result = *address; // // Exit Status Read Mode. // *address = CLEAR_STATUS_REGISTER; *address = ENTER_READ_ARRAY_MODE; return result; } [DisableNullChecks] [DisableBoundsChecks()] [NoInline] [MemoryRequirements(MemoryAttributes.RAM)] public static unsafe void StartBufferedProgramFlashWord( ushort* address , int count ) { *address = BUFFERED_PROGRAM_WORD; *address = (ushort)(count - 1); } [DisableNullChecks] [DisableBoundsChecks()] [NoInline] [MemoryRequirements(MemoryAttributes.RAM)] public static unsafe void AddBufferedProgramFlashWord( ushort* address , ushort value ) { *address = value; } [DisableNullChecks] [DisableBoundsChecks()] [NoInline] [MemoryRequirements(MemoryAttributes.RAM)] public static unsafe uint ConfirmProgramFlashWord( ushort* address ) { *address = BUFFERED_PROGRAM_CONFIRM; // // Wait for device to signal completion // break when the device signals completion by looking for Data (0xff erasure value) on I/O 7 (a 0 on I/O 7 indicates erasure in progress) // while((*address & SR_WSM_READY) != SR_WSM_READY); uint result = *address; // // Exit Status Read Mode. // *address = CLEAR_STATUS_REGISTER; *address = ENTER_READ_ARRAY_MODE; return result; } } } ================================================ FILE: Zelig/Zelig/RunTime/DeviceModels/ModelForPXA27x/HardwareModel/ChipSet/PXA27x/UART.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // namespace Microsoft.DeviceModels.Chipset.PXA27x { using System; using System.Runtime.CompilerServices; using Microsoft.Zelig.Runtime; [MemoryMappedPeripheral(Base=0x40100000U, Length=0x00700000U)] public class UART { public enum Id { FFUART = 0, // Full-Function UART BTUART = 1, // Bluetooth UART STUART = 6, // Standard UART } [BitFieldPeripheral(PhysicalType=typeof(byte))] public struct IER_bitfield { [BitFieldRegister(Position=7)] public bool DMAE; // DMA Requests Enable // // 0: DMA requests are disabled. // 1: DMA requests are enabled. // [BitFieldRegister(Position=6)] public bool UUE; // UART Unit Enable // // 0: The unit is disabled. // 1: The unit is enabled. // [BitFieldRegister(Position=5)] public bool NRZE; // NRZ coding Enable // // NRZ encoding/decoding is only used in UART mode, not in infrared mode. // If the slow infrared receiver or transmitteris enabled, NRZ coding is disabled. // // 0: NRZ coding disabled. // 1: NRZ coding enabled. // [BitFieldRegister(Position=4)] public bool RTOIE; // Receiver Time-Out Interrupt Enable (Source IIR[TOD]) // // 0: Receiver data time-out interrupt disabled. // 1: Receiver data time-out interrupt enabled. // [BitFieldRegister(Position=3)] public bool MIE; // Modem Interrupt Enable (Source IIR[IID]) // // 0: Modem status interrupt disabled. // 1: Modem status interrupt enabled. // [BitFieldRegister(Position=2)] public bool RLSE; // Receiver Line Status Interrupt Enable (Source IIR[IID]) // // 0: Receiver line status interrupt disabled. // 1: Receiver line status interrupt enabled. // [BitFieldRegister(Position=1)] public bool TIE; // Transmit Data reqeust Interrupt Enable (Source IIR[IID]) // // 0: Transmit FIFO data request interrupt disabled. // 1: Transmit FIFO data request interrupt enabled. // [BitFieldRegister(Position=0)] public bool RAVIE; // Receiver Data Available Interrupt Enable (Source IIR[IID]) // // 0: Receiver data available (trigger threshold reached) interrupt disabled. // 1: Receiver data available (trigger threshold reached) interrupt enabled. // } //--// [BitFieldPeripheral(PhysicalType=typeof(byte))] public struct IIR_bitfield { public enum FIFOEnableStatus : uint { NonFIFO = 0x0, // Non-FIFO mode is selected. FIFO = 0x3, // FIFO mode is selected. } public enum InterruptSource : uint { // Priority | Type | Source | RESET Control // | | | RLS = 0x3, // Highest | Receiver Line Status (RLS) | Overrun Error (OE), Parity Error (PE), Framing Error (FE), | Reading the LSR. // | | Break Interrupt (BI). | // | | | RDA = 0x2, // | Received Data Available (RDA) | Non-FIFO mode: receive buffer is full. | Reading the Receiver Buffer register. // | | FIFO mode: trigger threshold was reached. | Reading bytes until the receive FIFO drops below trigger threshold or setting. // | | | CTI = 0x6, // | Character Time-out Indication (CTI) | FIFO mode only: At least one character is left in the receive | Reading the receive FIFO or setting FCR[RESETRF]. // | | buffer indicating trailing bytes. | // | | | TFDR = 0x1, // | Transmit FIFO Data Request (TFDR) | Non-FIFO mode: Transmit Holding register empty | Reading the IIR register (if the source of the interrupt) // | | | or writing into the Transmit Holding register. // | | FIFO mode: transmit FIFO has half or less than half data. | Reading the IIR register (if the source of the interrupt) // | | | or writing to the transmit FIFO. // | | | MS = 0x0, // Lowest | Modem Status (MS) | Clear to Send, Data Set REady, Ring Indicator, Received Line | Reading the Modem Status register. // | | Signal Detect. | } [BitFieldRegister(Position=6, Size=2)] public FIFOEnableStatus FIFOES; // FIFO Mode Enable Status // [BitFieldRegister(Position=5 )] public bool EOC; // DMA End of Descriptor Chain // // 0: DMA has not signaled the end of its programmed descriptor chain. // 1: Dma has signaled the end of its programmed descriptor chain. // [BitFieldRegister(Position=4 )] public bool ABL; // Auto-Baud Lock // // 0: Auto-baud circutry has not programmed Divisor Latch registers (DLR). // 1: Divisor Latch registers (DLR) programmed by auto-baud circutry. // [BitFieldRegister(Position=3 )] public bool TOD; // Time-Out Detected // // 0: No time-out interrupt is pending. // 1: Time-out interrupt is pending. (FIFO mode only) // [BitFieldRegister(Position=1, Size=3)] public InterruptSource IID; // Interrupt Source Encoded // [BitFieldRegister(Position=0 )] public bool nIP; // Interrupt Pending // // 0: Interrupt is pending (active low). // 1: No interrupt is pending. // } //--// [BitFieldPeripheral(PhysicalType=typeof(byte))] public struct FCR_bitfield { public enum InterruptTriggerLevel : uint { TriggerAt1 = 0, // 00: trigger level = 1 TriggerAt8 = 1, // 01: trigger level = 8 TriggerAt16 = 2, // 10: trigger level = 16 TriggerAt32 = 3, // 11: trigger level = 32 } [BitFieldRegister(Position=6, Size=2)] public InterruptTriggerLevel ITL; // Interrupt Trigger-Level (Threshold) // // When the number of bytes in the receive FIFO equals the interrupt trigger threshold // programmed into this field and the received-data-available interrupt is enabled using // IER, an interrupt is generated and appropriate bits are st in the IIR. The receive // DMA request is also generated when the trigger threshold is reached. // [BitFieldRegister(Position=5 )] public bool BUS; // 32-bit Peripheral Bus // // 0: 8-bit peripheral bus // 1: 32-bit peripheral bus // [BitFieldRegister(Position=4 )] public bool TRAIL; // Trailing Bytes // // 0: Trailing bytes are removed by the processor. // 1: Trailing bytes are removed by the DMA controller. // [BitFieldRegister(Position=3 )] public bool TIL; // Transmitter Interrupt Level // // 0: Interrupt/DMA request when FIFO is half empty. // 1: Interrput/DMA request when FIFO is empty. // [BitFieldRegister(Position=2 )] public bool RESETTF; // Reset Transmit FIFO // // When RESETTF is set, all the bytes in the transmit FIFO are cleared. The TDRQ // bit in the LSR is set and the IIR shows a transmitter requests data interrupt, // if the TIE bit in the IER register is set. The transmit shift register is not // cleared, and it completes the current transmission. // // 0: Writing 0 has no effect. // 1: The transmit FIFO is cleared. // [BitFieldRegister(Position=1 )] public bool RESETRF; // Reset Receive FIFO // // When RESETRF is set, all the bytes in the receive FIFO are cleared. The // DR bit in the LSR is reset to 0. All the error bits in the FIFO and the // FIFOE bit in the LSR are cleared. Any error bits, OE, PE, FE, BI, that // had been set in the LSR are still set. The receive shift register is not // cleared. IF the IIR had been set to Received Data Available, it is cleared. // // 0: Writing 0 has no effect. // 1: The receive FIFO is cleared. // [BitFieldRegister(Position=0 )] public bool TRFIFOE; // Transmit and Receive FIFO Enable // // TRFIFOE enables/disables the transmit and receive FIFOs. When TRFIFOE is set // both FIFOs are enabled (FIFO mode). When TRFIFOE is clear, the FIFOs are both // disabled (non-FIFO mode). Writing 0b0 to this bit clears all bytes in both // FIFOs. When changing from FIFO mode to non-FIFO mode and vice versa, data // is automatically cleared from the FIFOs. This bit must be set when other bits // in this register are written or other bits are not programmed. // // 0: FIFOs are disabled. // 1: FIFOs are enabled. } //--// [BitFieldPeripheral(PhysicalType=typeof(byte))] public struct LCR_bitfield { public enum LengthSettings : uint { Use5bits = 0x0, // *00: 5 bit character length Use6bits = 0x1, // 01: 6 bit character length Use7bits = 0x2, // 10: 7 bit character length Use8bits = 0x3, // 11: 8 bit character length } [BitFieldRegister(Position=7 )] public bool DLAB; // Divisor Latch Access // // Must be set to access the Divisor Latch registers of the baud-rate generator // during a read or write operation. Must be clear to access the Receive Buffer, // the Transmit Holding Buffer, or the IER. // // 0: Access Transmit Holding register (THR), Receive Buffer register (RBR) and IER. // 1: Access Divisor Latch registers (DLL and DLH). // [BitFieldRegister(Position=6 )] public bool SB; // Set Break // // Causes a break condition to be transmitted to the receiving UART. Acts only on // the TXD pin and has no effect on the transmit logic. In FIFO mode, wait until // the transmitter is idle (LSR[TEMT] = 1) to set and clear SB. // // 0: No effect on the TXD output. // 1: Forces TXD output to 0 (space). // [BitFieldRegister(Position=5 )] public bool STKYP; // Sticky Parity // // Forces the bit value at the parity bit location to be the opposite of EPS // bit rather than the parity valkue. This stops parity generation. If PEN = 0, // STKYP is ignored. // // 0: No effect on parity bit. // 1: Forces parity bit to be opposite of EPS bit value. // [BitFieldRegister(Position=4 )] public bool EPS; // Even Parity Select // // If PEN = 0, EPS is ignored. // // 0: Sends or checks for odd parity. // 1: Sends or checks for even parity. // [BitFieldRegister(Position=3 )] public bool PEN; // Parity Enable // // Enables a parity bit to be generated on trasmission or checked on reception. // // 0: No parity // 1: Parity // [BitFieldRegister(Position=2 )] public bool STB; // Stop Bits // // Specifies the number of stop bits transmitted in each character. When // receiving, the receiver checks only the first stop bit. // // 0: 1 stop bit // 1: 2 stop bits, except for 5-bit character then 1-1/2 bits // [BitFieldRegister(Position=0, Size=2)] public LengthSettings WLS; // Word Length Select // // Specifies the number of data bits in each transmitted or received character. // } //--// [BitFieldPeripheral(PhysicalType=typeof(byte))] public struct MCR_bitfield { [BitFieldRegister(Position=5)] public bool AFE; // Auto-Flow Control Enable // // 0 = Auto-RTS and auto-CTS are disabled. // 1 = Auto-CTS is enabled. If MCR[RTS] is also set, both auto-CTS and auto-RTS are enabled. // [BitFieldRegister(Position=4)] public bool LOOP; // Loopback Mode // // Provides a local loopback feature for diagnostic testing of the UART. When LOOP is set, the following occurs: // // The transmitter serial output is set to a logic 1 state. // The receiver serial input is disconnected from the pin. // The output of the transmit shift register is “looped back” into the receive shift register input. // The four modem control inputs (nCTS, nDSR, nDCD, and nRI) are disconnected from the pins // and the modem control output pins (nRTS and nDTR) are forced to their inactive state. // // Coming out of the loopback mode may result in unpredictable activation of the delta bits (bits 3:0) in the Modem Status register. // Read MSR once to clear the MSR delta bits. // // Loopback mode must be configured before the UART is enabled. // // The lower four bits of the MCR are connected to the upper four Modem Status register bits: // // DTR = 1 forces DSR to a 1 // RTS = 1 forces CTS to a 1 // OUT1 = 1 forces RI to a 1 // OUT2 = 1 forces DCD to a 1 // // In loopback mode, data that is transmitted is immediately received. // This feature allows the processor to verify the transmit and receive data paths of the UART. // The transmit, receive, and modem-control interrupts are operational, except that the modem control interrupts are activated by MCR // bits, not by the modem-control pins. A break signal can also be transferred from the transmitter section to the receiver section in loopback mode. // // 0 = Normal UART operation // 1 = Loopback-mode UART operation // // [BitFieldRegister(Position=3)] public bool OUT2; // OUT2 Signal Control // // OUT2 connects the UART’s interrupt output to the interrupt controller unit. // // When LOOP is clear: // // 0 = UART interrupt is disabled. // 1 = UART interrupt is enabled. // // When LOOP is set, interrupts always go to the processor: // // 0 = MSR[DCD] forced to 0b0. // 1 = MSR[DCD] forced to 0b1. // [BitFieldRegister(Position=2)] public bool OUT1; // Test Bit // // Used only in loopback mode. It is ignored otherwise. // 0 = Force MSR[RI] to 0b0. // 1 = Force MSR[RI] to 0b1. // [BitFieldRegister(Position=1)] public bool RTS; // Request to Send // // 0 = Non-auto-flow mode. nRTS pin is 1. Auto-RTS is disabled. Auto-flow works only with auto-CTS. // 1 = Auto-flow mode. nRTS pin is 0. Auto-RTS is enabled. Auto-flow works with both auto-CTS and auto-RTS. // [BitFieldRegister(Position=0)] public bool DTR; // Data Terminal Ready // // 0 = nDTR pin is 1. // 1 = nDTR pin is 0. // } //--// [BitFieldPeripheral(PhysicalType=typeof(byte))] public struct LSR_bitfield { [BitFieldRegister(Position=7)] public bool FIFOE; // FIFO Error Status // // In non-FIFO mode, this bit is clear. In FIFO mode, FIFOE is set when there is // at least one parity error, framing error, or break indication for any of the // characters in the FIFO. A processor read of the LSR does not reset this bit. // FIFOE is reset when all erroneous characters have been read from the FIFO. // If DMA requests are enables (IER bit 7 set) and FIFOE is set, the error // interrupt is generated, and no receive DMA request is generated even when the // receive FIFO reaches the trigger threshold. Once the errors have been cleared // by reading the FIFO, DMA request are re-enabled automatically. If DMA requests // are not enabled (IER bit 7 clear), FIFOE set does not generate an error interrupt. // // 0: No FIFO or no error in receive FIFO. // 1: At least one character in receive FIFO has errors. // [BitFieldRegister(Position=6)] public bool TEMT; // Transmitter Empty // // Set when the Transmit Holding register and the transmit shift register are both // empty. It is cleared when either the Transmit Holding register or the transmit // shift register contains a data character. In FIFO mode, TEMT is set when the // transmit FIFO and the transmit shift register are both empty. // // 0: There is data in the transmit shift register, the Transmit Holding register or the FIFO. // 1: All the data in the transmitter has been shifted out. // [BitFieldRegister(Position=5)] public bool TDRQ; // Transmit Data Request // // Indicates that the UART is ready to accept a new character for transmission. // In addition, this bit causes the UART to issue an interrupt to the processor // when the transmit data request interrupt enable is set and generates the DMA // request to the DMA controller if DMA requests and FIFO mode are enabled. // the TDRQ bit is set when a character is transferred from the Transmit Holding // register into the transmit shift register. The bit is cleared with the loading // of the Transmit Holding register. In FIFO mode, TDRQ is set when half of the // characters in the FIFO have been loaded into the shift register or the // RESETTF bit in FCR has been set. It is cleared when the FIFO has more than // half data. If more than 64 characters are loaded into the FIFO, the excess // characters are lost. // // 0: There is data in the holding register or FIFO waiting to be shifter out. // 1: The transmit FIFO has half or less than half data. // [BitFieldRegister(Position=4)] public bool BI; // Break Interrupt // // BI is set when the received data input is held low for longer than a full-word // transmission time (the total time of start bit + data bits + parity bit + stop // bits). BI is cleared when the processor reads the LSR. In FIFO mode, only one // character equal to 0x00, is loaded into the FIFO regardless of the length of // the break condition. BI shows the break condition for the character at the // front of the FIFO, not the most recently received character. // // 0: No break signal has been received. // 1: Break signal received. // [BitFieldRegister(Position=3)] public bool FE; // Framing Error // // Indicates that the received character did not have a valid stop bit. FE is set // when the bit following the last data bit or parity bit is detected to be 0. // If the LCR had been set for two stop bits, the receiver does not check for a // valid second stop bit. FE is clared when the processor reads the LSR. The // UART re-synchronizes after a framing error. To do this, it assumes that the // framing error was due to the next start bit, so it samples this start bit // twice and then reads in the data. In FIFO mode, FE shows a framing error for // the character at the front of the FIFO, not for the most recently received // character. // // 0: No framing error. // 1: Invalid stop bit has been detected. // [BitFieldRegister(Position=2)] public bool PE; // Parity Error // // Indicates that the received data character does not have the correct even or // odd parity, as slected by the even parity select bit. PE is set upon detection // of a parity error and is cleared when the processor reads the LSR. In FIFO // mode, PE shows a parity error for the character at the front of the FIFO, // not the most recently received character. // // 0: No parity error. // 1: Parity error has occured. // [BitFieldRegister(Position=1)] public bool OE; // Overrun Error // // In non-FIFO mode, indicates that data in the REceive Buffer register was not // read by the processor before the next character was received. The new character // is lost. In FIFO mode, OE indicates that all 64 bytes of the FIFO are full and // the most recently received byte has been discarded. OE is set upon detection // of an overrun condition and clared when the processor reads the LSR. // // 0: No data has been lost. // 1: Receive data has been lost. // [BitFieldRegister(Position=0)] public bool DR; // Receiver Data Ready // // Set when a complete incoming character has been received and transferred into // the Receive Buffer register or the FIFO. In non-FIFO mode, DR is cleared when // the receive buffer is read. In FIFO mode, DR is cleared if the FIFO is empty // (last character has been read from RBR) or the FIFO is reset with FCR[RESETRF]. // // 0: No data has been received. // 1: Data is available in RBR or the FIFO. // } //--// [BitFieldPeripheral(PhysicalType=typeof(byte))] public struct ABR_bitfield { [BitFieldRegister(Position=3)] public bool ABT; // Auto-Baud Calculation // // 0: Use a formula to calculate baud rates, allowing all possible baud rates to be chosen by UART. // 1: Use a table to calculate baud rates, which limits UART to choosing commong baud rates. // [BitFieldRegister(Position=2)] public bool ABUP; // Auto-Baud Programmer // // 0: Process programs divisor latch registers. // 1: UART programs divisor latch registers. // [BitFieldRegister(Position=1)] public bool ABLIE; // Auto-Baud Lock Interrupt // // 0: Audo-baud-lock interrupt disabled (Source IIR[ABL]). // 1: Auto-baud-lock interrupt enabled (Source IIR[ABL]). // [BitFieldRegister(Position=0)] public bool ABE; // Auto-Baud Enable // // 0: Auto-baud disabled. // 1: Auto-baud enabled. // } //--// [MemoryMappedPeripheral(Base=0x0000U, Length=0x100000U)] public class Port { [Register(Offset = 0x00U)] public byte RBR; // Receive Buffer Register - R [Register(Offset = 0x00U)] public byte THR; // Transmit Holding Register - W [Register(Offset = 0x04U)] public IER_bitfield IER; // Interrupt Enable Register [Register(Offset = 0x00U)] public byte DLL; // Divisor Latch Register - Low Byte [Register(Offset = 0x04U)] public byte DLH; // Divisor Latch Register - High Byte [Register(Offset = 0x08U)] public IIR_bitfield IIR; // Interrupt ID Register - R [Register(Offset = 0x08U)] public FCR_bitfield FCR; // FIFO Control Register - W [Register(Offset = 0x0CU)] public LCR_bitfield LCR; // Line Control Register [Register(Offset = 0x10U)] public MCR_bitfield MCR; // Modem Control Register [Register(Offset = 0x14U)] public LSR_bitfield LSR; // Line Status Register - R [Register(Offset = 0x18U)] public byte MSR; // Modem Status Register - R [Register(Offset = 0x1CU)] public byte SPR; // Scrath Pad Register [Register(Offset = 0x20U)] public byte ISR; // Infared Select Register [Register(Offset = 0x24U)] public byte FOR; // Receive FIFO Occupancy Register [Register(Offset = 0x28U)] public ABR_bitfield ABR; // Auto-baud Control Register [Register(Offset = 0x2CU)] public byte ACR; // Auto-baud Count Register // // Helper Methods // [Inline] public void EnableReceiveInterrupt() { // DMAE must not be set while RAVIE bit is set. this.IER.DMAE = false; this.IER.RAVIE = true; this.IER.RTOIE = true; } [Inline] public void DisableReceiveInterrupt() { this.IER.RAVIE = false; this.IER.RTOIE = false; } [Inline] public void EnableTransmitInterrupt() { // DMAE must not be set while RAVIE bit is set. this.IER.DMAE = false; this.IER.TIE = true; } [Inline] public void DisableTransmitInterrupt() { this.IER.TIE = false; } [Inline] public bool ReadByte(out byte rx) { if (this.CanReceive) { rx = this.RBR; return true; } else { rx = 0; return false; } } [Inline] public bool WriteByte(byte tx) { if (this.CanSend) { this.THR = tx; return true; } return false; } // // Access Methods // public bool CanSend { [Inline] get { return this.LSR.TDRQ; } } public bool CanReceive { [Inline] get { return this.LSR.DR; } } public bool IsTransmitInterruptEnabled { [Inline] get { return this.IER.TIE; } } public bool IsReceiveInterruptEnabled { [Inline] get { return this.IER.RAVIE; } } // // Debug Methods // public void DEBUG_WriteLine( string text , uint value ) { DEBUG_Write( text, value ); DEBUG_Write( Environment.NewLine ); } public void DEBUG_WriteLine( string text ) { DEBUG_Write( text ); DEBUG_Write( Environment.NewLine ); } public void DEBUG_Write( string text , uint value ) { DEBUG_Write ( text ); DEBUG_WriteHex( value ); } [DisableBoundsChecks()] [DisableNullChecks] public void DEBUG_Write( string s ) { if(s != null) { for(int i = 0; i < 0; ++i ) { DEBUG_Write( s[ i ] ); } } } public void DEBUG_WriteHex( uint value ) { DEBUG_Write("0x"); for(int pos = 32 - 4; pos >= 0; pos -= 4) { uint digit = (value >> pos) & 0xF; DEBUG_Write( digit >= 10 ? (char)('A' + (digit - 10)) : (char)('0' + digit) ); } } public void DEBUG_Write( char c ) { while(this.CanSend == false) { } this.THR = (byte)c; } } //--// [Register(Offset=0x00000000U, Instances=7)] public Port[] Ports; //--// // // Helper Methods // public Port Configure( Id portNo , int baudrate ) { var cfg = new BaseSerialStream.Configuration(null) { BaudRate = baudrate, DataBits = 8, Parity = System.IO.Ports.Parity.None, StopBits = System.IO.Ports.StopBits.One, }; return Configure( portNo, ref cfg ); } public Port Configure( Id portNo , ref BaseSerialStream.Configuration cfg ) { // Enable GPIO reads by clearing PSSR[RDH] PowerManager.Instance.PSSR.RDH = true; // Get a reference to the port var port = this.Ports[(int)portNo]; //--// var gpio = GPIO.Instance; var clkMgr = ClockManager.Instance; switch(portNo) { case Id.FFUART: // FFRXD Pin 96 Alternate Function 3 (in) gpio.EnableAsInputAlternateFunction( 96, 3 ); // FFTXD Pin 99 Alternate Function 3 (out) gpio.EnableAsOutputAlternateFunction( 99, 3, true ); // enable clock to peripheral clkMgr.CKEN.EnFFUART = true; break; case Id.BTUART: // BTRXD Pin 42 Alternate Function 1 (in) gpio.EnableAsInputAlternateFunction( 42, 1 ); // BTTXD Pin 43 Alternate Fucntion 2 (out) gpio.EnableAsOutputAlternateFunction( 43, 2, true ); // enable clock to peripheral clkMgr.CKEN.EnBTUART = true; break; case Id.STUART: // STD_RXD Pin 46 Alternate Function 2 (in) gpio.EnableAsInputAlternateFunction( 46, 2 ); // STD_TXD Pin 47 Alternate Function 1 (out) gpio.EnableAsOutputAlternateFunction( 47, 1, true ); // enable clock to peripheral clkMgr.CKEN.EnSTUART = true; break; } //--// // turn on divisor latch access port.LCR.DLAB = true; switch(cfg.BaudRate) { case 300 : port.DLL = 0; port.DLH = 12; break; // 3072 Divisor case 1200 : port.DLL = 0; port.DLH = 3; break; // 768 Divisor case 2400 : port.DLL = 128; port.DLH = 1; break; // 384 Divisor case 4800 : port.DLL = 192; port.DLH = 0; break; // 192 Divisor case 9600 : port.DLL = 96; port.DLH = 0; break; // 96 Divisor case 19200 : port.DLL = 48; port.DLH = 0; break; // 48 Divisor case 38400 : port.DLL = 24; port.DLH = 0; break; // 24 Divisor case 57600 : port.DLL = 16; port.DLH = 0; break; // 16 Divisor case 115200: port.DLL = 8; port.DLH = 0; break; // 8 Divisor default: return null; } // turn off divisor latch access port.LCR.DLAB = false; //--// var lcr = new LCR_bitfield(); if(cfg.Parity != System.IO.Ports.Parity.None) { lcr.PEN = true; switch(cfg.Parity) { case System.IO.Ports.Parity.Even: lcr.EPS = true; break; case System.IO.Ports.Parity.Odd: break; default: return null; } } switch(cfg.StopBits) { case System.IO.Ports.StopBits.One: break; case System.IO.Ports.StopBits.Two: lcr.STB = true; break; default: return null; } switch(cfg.DataBits) { case 5: lcr.WLS = LCR_bitfield.LengthSettings.Use5bits; break; case 6: lcr.WLS = LCR_bitfield.LengthSettings.Use6bits; break; case 7: lcr.WLS = LCR_bitfield.LengthSettings.Use7bits; break; case 8: lcr.WLS = LCR_bitfield.LengthSettings.Use8bits; break; default: return null; } port.LCR = lcr; //--// var fcr = new FCR_bitfield() { ITL = FCR_bitfield.InterruptTriggerLevel.TriggerAt16, TIL = true, RESETTF = true, RESETRF = true, TRFIFOE = true, }; port.FCR = fcr; //--// // Sent interrupts to AITC port.MCR.OUT2 = true; // Enable uart port.IER.UUE = true; return port; } // // Access Methods // public static extern UART Instance { [SingletonFactory()] [MethodImpl(MethodImplOptions.InternalCall)] get; } } } ================================================ FILE: Zelig/Zelig/RunTime/DeviceModels/ModelForPXA27x/HardwareModel/ChipSet/PXA27x.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // namespace Microsoft.DeviceModels.Chipset.PXA27x { /* Table 28-1. Coprocessor Register Summary | CRn | CRm | Opcode2 | Register Symbol | Register Description Coprocessor 6Interrupt Controller | 0 | 0 | 0 | ICIP | Interrupt Controller IRQ Pending register | 1 | 0 | 0 | ICMR | Interrupt Controller Mask register | 2 | 0 | 0 | ICLR | Interrupt Controller Level register | 3 | 0 | 0 | ICFR | Interrupt Controller FIQ Pending register | 4 | 0 | 0 | ICPR | Interrupt Pending register | 5 | 0 | 0 | ICHP | Interrupt Highest Priority register Coprocessor 14Clock, Power Management, Debug, and Trace Registers | 0 | 0 | 0 | PMNC | Performance Monitoring Control register | 1 | 0 | 0 | CCNT | Performance Monitoring Clock Counter | 2 | 0 | 0 | PMN0 | Performance Monitoring Event Counter 0 | 3 | 0 | 0 | PMN1 | Performance Monitoring Event Counter 1 | 4 | | | | reserved | 5 | | | | reserved | 6 | 0 | 0 | CCLKCFG | Core Clock Configuration register | 7 | 0 | 0 | PWRMODE | Power Management register | 8 | 0 | 0 | TX | Access Transmit Debug register | 9 | 0 | 0 | RX | Access Receive Debug register | 10 | 0 | 0 | DBGCSR | Access Debug Control and Status register | 11 | 0 | 0 | TBREG | Access Trace Buffer register | 12 | 0 | 0 | CHKPT0 | Access Checkpoint0 register | 13 | 0 | 0 | CHKPT1 | Access Checkpoint1 register | 14 | 0 | 0 | TXRXCTRL | Access Transmit and Receive Debug Control | 15 | | | | reserved Coprocessor 15Intel XScale Core System Control ID and Cache Type Registers | 0 | 0 | 0 | ID Identification register | 0 | 0 | 1 | Cache Type Control and Auxiliary Registers | 1 | 0 | 0 | ARM* Control register | 1 | 0 | 1 | Auxiliary Control register | 2 | 0 | 0 | Translation Table Base register | 3 | 0 | 0 | Domain Access Control register | 4 | | | reserved | 5 | 0 | 0 | Fault Status register | 6 | 0 | 0 | Fault Address register Cache Operations | 7 | 7 | 0 | Invalidate I&D cache and BTB | 7 | 5 | 0 | Invalidate I cache and BTB | 7 | 5 | 1 | Invalidate I-cache Line | 7 | 6 | 0 | Invalidate D-cache | 7 | 6 | 1 | Invalidate D-cache Line | 7 | 10 | 1 | Clean D-cache Line | 7 | 10 | 4 | Drain Write (&Fill) Buffer | 7 | 5 | 6 | Invalidate Branch Target Buffer | 7 | 2 | 5 | Allocate Line in the Data Cache | 8 | 7 | 0 | Invalidate I&D TLB | 8 | 5 | 0 | Invalidate I TLB | 8 | 5 | 1 | Invalidate I TLB Entry | 8 | 6 | 0 | Invalidate D TLB | 8 | 6 | 1 | Invalidate D TLB Entry Cache Lock Down | 9 | 1 | 0 | Fetch and Lock I-Cache Line TLB Operations | 9 | 1 | 1 | Unlock I-Cache | 9 | 2 | 0 | Read Data Cache Lock register | 9 | 2 | 0 | Write Data Cache Lock register | 9 | 2 | 1 | Unlock Data Cache TLB Lock Down | 10 | 4 | 0 | Translate and Lock Instruction TLB Entry | 10 | 8 | 0 | Translate and Lock Data TLB Entry | 10 | 4 | 1 | Unlock Instruction TLB | 10 | 8 | 1 | Unlock Data TLB | 11 | | | reserved | 12 | | | reserved | 13 | 0 | 0 | PID Processor ID Breakpoint Registers | 14 | 0 | 0 | DBCR0 Data Breakpoint register 0 | 14 | 3 | 0 | DBCR1 Data Breakpoint register 1 | 14 | 4 | 0 | DBCON Data Breakpoint Control register | 14 | 8 | 0 | IBCR0 Instruction Breakpoint register 0 | 14 | 9 | 0 | IBCR1 Instruction Breakpoint register 1 | 15 | 1 | 0 | CPAR Coprocessor Access | 15 | 1 | 0 | CPAR Coprocessor Access Table 28-2. Memory Controller Register Summary | 0x4800_0000 | MDCNFG | SDRAM Configuration register | 6-43 | 0x4800_0004 | MDREFR | SDRAM Refresh Control register | 6-53 | 0x4800_0008 | MSC0 | Static Memory Control register 0 | 6-63 | 0x4800_000C | MSC1 | Static Memory Control register 1 | 6-63 | 0x4800_0010 | MSC2 | Static Memory Control register 2 | 6-63 | 0x4800_0014 | MECR | Expansion Memory (PC Card/CompactFlash) Bus Configuration register | 6-79 | 0x4800_001C | SXCNFG | Synchronous Static Memory Configuration register | 6-58 | 0x4800_0020 | FLYCNFG | Fly-by DMA DVAL<1:0> polarities | 5-39 | 0x4800_0028 | MCMEM0 | PC Card Interface Common Memory Space Socket 0 Timing Configuration register | 6-77 | 0x4800_002C | MCMEM1 | PC Card Interface Common Memory Space Socket 1 Timing Configuration register | 6-77 | 0x4800_0030 | MCATT0 | PC Card Interface Attribute Space Socket 0 Timing Configuration register | 6-77 | 0x4800_0034 | MCATT1 | PC Card Interface Attribute Space Socket 1 Timing Configuration register | 6-77 | 0x4800_0038 | MCIO0 | PC Card Interface I/o Space Socket 0 Timing Configuration register | 6-78 | 0x4800_003C | MCIO1 | PC Card Interface I/o Space Socket 1 Timing Configuration register | 6-78 | 0x4800_0040 | MDMRS | SDRAM Mode Register Set Configuration register | 6-49 | 0x4800_0044 | BOOT_DEF | Boot Time Default Configuration register | 6-75 | 0x4800_0048 | ARB_CNTL | Arbiter Control register | 29-2 | 0x4800_004C | BSCNTR0 | System Memory Buffer Strength Control register 0 | 6-81 | 0x4800_0050 | BSCNTR1 | System Memory Buffer Strength Control register 1 | 6-82 | 0x4800_0054 | LCDBSCNTR | LCD Buffer Strength Control register | 7-102 | 0x4800_0058 | MDMRSLP | Special Low Power SDRAM Mode Register Set Configuration register | 6-51 | 0x4800_005C | BSCNTR2 | System Memory Buffer Strength Control register 2 | 6-83 | 0x4800_0060 | BSCNTR3 | System Memory Buffer Strength Control register 3 | 6-84 | 0x4800_0064 | SA1110 | SA-1110 Compatibility Mode for Static Memory register | 6-70 Table 28-3. LCD Controller Register Summary | 0x4400_0000 | LCCR0 | LCD Controller Control register 0 | 7-56 | 0x4400_0004 | LCCR1 | LCD Controller Control register 1 | 7-64 | 0x4400_0008 | LCCR2 | LCD Controller Control register 2 | 7-66 | 0x4400_000C | LCCR3 | LCD Controller Control register 3 | 7-69 | 0x4400_0010 | LCCR4 | LCD Controller Control register 4 | 7-74 | 0x4400_0014 | LCCR5 | LCD Controller Control register 5 | 7-77 | 0x4400_0020 | FBR0 | DMA Channel 0 Frame Branch register | 7-101 | 0x4400_0024 | FBR1 | DMA Channel 1 Frame Branch register | 7-101 | 0x4400_0028 | FBR2 | DMA Channel 2 Frame Branch register | 7-101 | 0x4400_002C | FBR3 | DMA Channel 3 Frame Branch register | 7-101 | 0x4400_0030 | FBR4 | DMA Channel 4 Frame Branch register | 7-101 | 0x4400_0034 | LCSR1 | LCD Controller Status register 1 | 7-109 | 0x4400_0038 | LCSR0 | LCD Controller Status register 0 | 7-104 | 0x4400_003C | LIIDR | LCD Controller Interrupt ID register | 7-116 | 0x4400_0040 | TRGBR | TMED RGB Seed register | 7-97 | 0x4400_0044 | TCR | TMED Control register | 7-98 | 0x4400_0050 | OVL1 C1 | Overlay 1 Control register 1 | 7-90 | 0x4400_0060 | OVL1 C2 | Overlay 1 Control register 2 | 7-91 | 0x4400_0070 | OVL2 C1 | Overlay 2 Control register 1 | 7-92 | 0x4400_0080 | OVL2C2 | Overlay 2 Control register 2 | 7-94 | 0x4400_0090 | CCR | Cursor Control register | 7-95 | 0x4400_0100 | CMDCR | Command Control register | 7-96 | 0x4400_0104 | PRSR | Panel Read Status register | 7-103 | 0x4400_0110 | FBR5 | DMA Channel 5 Frame Branch register | 7-101 | 0x4400_0114 | FBR6 | DMA Channel 6 Frame Branch register | 7-101 | 0x4400_0200 | FDADR0 | DMA Channel 0 Frame Descriptor Address register | 7-100 | 0x4400_0204 | FSADR0 | DMA Channel 0 Frame Source Address register | 7-117 | 0x4400_0208 | FIDR0 | DMA Channel 0 Frame ID register | 7-117 | 0x4400_020C | LDCMD0 | LCD DMA Channel 0 Command register | 7-118 | 0x4400_0210 | FDADR1 | DMA Channel 1 Frame Descriptor Address register | 7-100 | 0x4400_0214 | FSADR1 | DMA Channel 1 Frame Source Address register | 7-117 | 0x4400_0218 | FIDR1 | DMA Channel 1 Frame ID register | 7-117 | 0x4400_021C | LDCMD1 | LCD DMA Channel 1 Command register | 7-118 | 0x4400_0220 | FDADR2 | DMA Channel 2 Frame Descriptor Address register | 7-100 | 0x4400_0224 | FSADR2 | DMA Channel 2 Frame Source Address register | 7-117 | 0x4400_0228 | FIDR2 | DMA Channel 2 Frame ID register | 7-117 | 0x4400_022C | LDCMD2 | LCD DMA Channel 2 Command register | 7-118 | 0x4400_0230 | FDADR3 | DMA Channel 3 Frame Descriptor Address register | 7-100 | 0x4400_0234 | FSADR3 | DMA Channel 3 Frame Source Address register | 7-117 | 0x4400_0238 | FIDR3 | DMA Channel 3 Frame ID register | 7-117 | 0x4400_023C | LDCMD3 | LCD DMA Channel 3 Command register | 7-118 | 0x4400_0240 | FDADR4 | DMA Channel 4 Frame Descriptor Address register | 7-100 | 0x4400_0244 | FSADR4 | DMA Channel 4 Frame Source Address register | 7-117 | 0x4400_0248 | FIDR4 | DMA Channel 4 Frame ID register | 7-117 | 0x4400_024C | LDCMD4 | LCD DMA Channel 4 Command register | 7-118 | 0x4400_0250 | FDADR5 | DMA Channel 5 Frame Descriptor Address register | 7-100 | 0x4400_0254 | FSADR5 | DMA Channel 5 Frame Source Address register | 7-117 | 0x4400_0258 | FIDR5 | DMA Channel 5 Frame ID register | 7-117 | 0x4400_025C | LDCMD5 | LCD DMA Channel 5 Command register | 7-118 | 0x4400_0260 | FDADR6 | DMA Channel 6 Frame Descriptor Address register | 7-100 | 0x4400_0264 | FSADR6 | DMA Channel 6 Frame Source Address register | 7-117 | 0x4400_0268 | FIDR6 | DMA Channel 6 Frame ID register | 7-117 | 0x4400_026C | LDCMD6 | LCD DMA Channel 6 Command register | 7-118 | 0x4800_0054 | LCDBSCNTR | LCD Buffer Strength Control register | 7-102 28.2.4 USB Host Controller Registers | 0x4C00 0000 | UHCREV | UHC HCI Spec Revision register | 20-10 | 0x4C00 0004 | UHCHCON | UHC Host Control register | 20-10 | 0x4C00 0008 | UHCCOMS | UHC Command Status register | 20-14 | 0x4C00 000C | UHCINTS | UHC Interrupt Status register | 20-16 | 0x4C00 0010 | UHCINTE | UHC Interrupt Enable register | 20-18 | 0x4C00 0014 | UHCINTD | UHC Interrupt Disable register | 20-20 | 0x4C00 0018 | UHCHCCA | UHC Host Controller Communication Area register | 20-21 | 0x4C00 001C | UHCPCED | UHC Period Current Endpoint Descriptor register | 20-21 | 0x4C00 0020 | UHCCHED | UHC Control Head Endpoint Descriptor register | 20-22 | 0x4C00 0024 | UHCCCED | UHC Control Current Endpoint Descriptor register | 20-22 | 0x4C00 0028 | UHCBHED | UHC Bulk Head Endpoint Descriptor register | 20-23 | 0x4C00 002C | UHCBCED | UHC Bulk Current Endpoint Descriptor register | 20-24 | 0x4C00 0030 | UHCDHEAD | UHC Done Head register | 20-25 | 0x4C00 0034 | UHCFMI | UHC Frame Interval register | 20-26 | 0x4C00 0038 | UHCFMR | UHC Frame Remaining register | 20-27 | 0x4C00 003C | UHCFMN | UHC Frame Number register | 20-28 | 0x4C00 0040 | UHCPERS | UHC Periodic Start register | 20-29 | 0x4C00 0044 | UHCLST | UHC Low-Speed Threshold register | 20-30 | 0x4C00 0048 | UHCRHDA | UHC Root Hub Descriptor A register | 20-31 | 0x4C00 004C | UHCRHDB | UHC Root Hub Descriptor B register | 20-33 | 0x4C00 0050 | UHCRHS | UHC Root Hub Status register | 20-34 | 0x4C00 0054 | UHCRHPS1 | UHC Root Hub Port 1 Status register | 20-35 | 0x4C00 0058 | UHCRHPS2 | UHC Root Hub Port 2 Status register | 20-35 | 0x4C00 005C | UHCRHPS3 | UHC Root Hub Port 3 Status register | 20-35 | 0x4C00 0060 | UHCSTAT | UHC Status register | 20-39 | 0x4C00 0064 | UHCHR | UHC Reset register | 20-41 | 0x4C00 0068 | UHCHIE | UHC Interrupt Enable register | 20-44 | 0x4C00 006C | UHCHIT | UHC Interrupt Test register | 20-45 Table 28-5. Internal Memory Register Summary 0x5C00_00000x5C00_FFFC Memory Bank 0 64-Kbyte SRAM 0x5C01_00000x5C01_FFFC Memory Bank 1 6-4Kbyte SRAM 0x5C02_00000x5C02_FFFC Memory Bank 2 64-Kbyte SRAM 0x5C03_00000x5C03_FFFC Memory Bank 3 64-Kbyte SRAM Table 28-6. Quick Capture Interface Register Summary | 0x5000_0000 | CICR0 | Quick Capture Interface Control register 0 | 27-24 | 0x5000_0004 | CICR1 | Quick Capture Interface Control register 1 | 27-28 | 0x5000_0008 | CICR2 | Quick Capture Interface Control register 2 | 27-32 | 0x5000_000C | CICR3 | Quick Capture Interface Control register 3 | 27-33 | 0x5000_0010 | CICR4 | Quick Capture Interface Control register 4 | 27-34 | 0x5000_0014 | CISR | Quick Capture Interface Status register | 27-37 | 0x5000_0018 | CIFR | Quick Capture Interface FIFO Control register | 27-40 | 0x5000_001C | CITOR | Quick Capture Interface Time-Out register | 27-37 | 0x5000_0028 | CIBR0 | Quick Capture Interface Receive Buffer register 0 (Channel 0) | 27-42 | 0x5000_0030 | CIBR1 | Quick Capture Interface Receive Buffer register 1 (Channel 1) | 27-42 | 0x5000_0038 | CIBR2 | Quick Capture Interface Receive Buffer register 2 (Channel 2) | 27-42 28.3 Peripheral Module Registers DMA Controller 0x4000_0000 UART1Full Function UART 0x4010_0000 UART2Bluetooth UART 0x4020_0000 Standard I2C Bus Interface Unit 0x4030_0000 I2S Controller 0x4040_0000 AC 97 Controller 0x4050_0000 USB Client Controller 0x4060_0000 UART 3Standard UART 0x4070_0000 Fast Infrared Communications Port 0x4080_0000 RTC 0x4090_0000 OS Timers 0x40A0_0000 PWM0 and 2 0x40B0_0000 PWM1 and 3 0x40C0_0000 Interrupt Controller 0x40D0_0000 GPIO Controller 0x40E0_0000 Power Manager 0x40F0_0000 Reset Controller 0x40F0_0000 Power Manager I2C 0x40F0_0180 Synchronous Serial Port 1 0x4100_0000 MultiMediaCard/SD/SDIO Controller 0x4110_0000 reserved 0x4120_0000 Clocks Manager 0x4130_0000 Mobile Scalable Link (MSL) 0x4140_0000 Keypad Interface 0x4150_0000 Universal Subscriber ID (USIM) Interface 0x4160_0000 Synchronous Serial Port 2 0x4170_0000 Memory Stick Host Controller 0x4180_0000 Synchronous Serial Port 3 0x4190_0000 DMA Controller | 0x4000_0000 | DCSR0 | DMA Control/Status register for Channel 0 | 5-41 | 0x4000_0004 | DCSR1 | DMA Control/Status register for Channel 1 | 5-41 | 0x4000_0008 | DCSR2 | DMA Control/Status register for Channel 2 | 5-41 | 0x4000_000C | DCSR3 | DMA Control/Status register for Channel 3 | 5-41 | 0x4000_0010 | DCSR4 | DMA Control/Status register for Channel 4 | 5-41 | 0x4000_0014 | DCSR5 | DMA Control/Status register for Channel 5 | 5-41 | 0x4000_0018 | DCSR6 | DMA Control/Status register for Channel 6 | 5-41 | 0x4000_001C | DCSR7 | DMA Control/Status register for Channel 7 | 5-41 | 0x4000_0020 | DCSR8 | DMA Control/Status register for Channel 8 | 5-41 | 0x4000_0024 | DCSR9 | DMA Control/Status register for Channel 9 | 5-41 | 0x4000_0028 | DCSR10 | DMA Control/Status register for Channel 10 | 5-41 | 0x4000_002C | DCSR11 | DMA Control/Status register for Channel 11 | 5-41 | 0x4000_0030 | DCSR12 | DMA Control/Status register for Channel 12 | 5-41 | 0x4000_0034 | DCSR13 | DMA Control/Status register for Channel 13 | 5-41 | 0x4000_0038 | DCSR14 | DMA Control/Status register for Channel 14 | 5-41 | 0x4000_003C | DCSR15 | DMA Control/Status register for Channel 15 | 5-41 | 0x4000_0040 | DCSR16 | DMA Control/Status register for Channel 16 | 5-41 | 0x4000_0044 | DCSR17 | DMA Control/Status register for Channel 17 | 5-41 | 0x4000_0048 | DCSR18 | DMA Control/Status register for Channel 18 | 5-41 | 0x4000_004C | DCSR19 | DMA Control/Status register for Channel 19 | 5-41 | 0x4000_0050 | DCSR20 | DMA Control/Status register for Channel 20 | 5-41 | 0x4000_0054 | DCSR21 | DMA Control/Status register for Channel 21 | 5-41 | 0x4000_0058 | DCSR22 | DMA Control/Status register for Channel 22 | 5-41 | 0x4000_005C | DCSR23 | DMA Control/Status register for Channel 23 | 5-41 | 0x4000_0060 | DCSR24 | DMA Control/Status register for Channel 24 | 5-41 | 0x4000_0064 | DCSR25 | DMA Control/Status register for Channel 25 | 5-41 | 0x4000_0068 | DCSR26 | DMA Control/Status register for Channel 26 | 5-41 | 0x4000_006C | DCSR27 | DMA Control/Status register for Channel 27 | 5-41 | 0x4000_0070 | DCSR28 | DMA Control/Status register for Channel 28 | 5-41 | 0x4000_0074 | DCSR29 | DMA Control/Status register for Channel 29 | 5-41 | 0x4000_0078 | DCSR30 | DMA Control/Status register for Channel 30 | 5-41 | 0x4000_007C | DCSR31 | DMA Control/Status register for Channel 31 | 5-41 | 0x4000_00A0 | DALGN | DMA Alignment register | 5-49 | 0x4000_00A4 | DPCSR | DMA Programmed I/O Control Status register | 5-51 | 0x4000_00E0 | DRQSR0 | DMA DREQ<0> Status register | 5-40 | 0x4000_00E4 | DRQSR1 | DMA DREQ<1> Status register | 5-40 | 0x4000_00E8 | DRQSR2 | DMA DREQ<2> Status register | 5-40 | 0x4000_00F0 | DINT | DMA Interrupt register | 5-48 | 0x4000_0100 | DRCMR0 | Request to Channel Map register for DREQ<0> (companion chip request 0) | 5-31 | 0x4000_0104 | DRCMR1 | Request to Channel Map register for DREQ<1> (companion chip request 1) | 5-31 | 0x4000_0108 | DRCMR2 | Request to Channel Map register for I2S receive request | 5-31 | 0x4000_010C | DRCMR3 | Request to Channel Map register for I2S transmit request | 5-31 | 0x4000_0110 | DRCMR4 | Request to Channel Map register for BTUART receive request | 5-31 | 0x4000_0114 | DRCMR5 | Request to Channel Map register for BTUART transmit request. | 5-31 | 0x4000_0118 | DRCMR6 | Request to Channel Map register for FFUART receive request | 5-31 | 0x4000_011C | DRCMR7 | Request to Channel Map register for FFUART transmit request | 5-31 | 0x4000_0120 | DRCMR8 | Request to Channel Map register for AC 97 microphone request | 5-31 | 0x4000_0124 | DRCMR9 | Request to Channel Map register for AC 97 modem receive request | 5-31 | 0x4000_0128 | DRCMR10 | Request to Channel Map register for AC 97 modem transmit request | 5-31 | 0x4000_012C | DRCMR11 | Request to Channel Map register for AC 97 audio receive request | 5-31 | 0x4000_0130 | DRCMR12 | Request to Channel Map register for AC 97 audio transmit request | 5-31 | 0x4000_0134 | DRCMR13 | Request to Channel Map register for SSP1 receive request | 5-31 | 0x4000_0138 | DRCMR14 | Request to Channel Map register for SSP1 transmit request | 5-31 | 0x4000_013C | DRCMR15 | Request to Channel Map register for SSP2 receive request | 5-31 | 0x4000_0140 | DRCMR16 | Request to Channel Map register for SSP2 transmit request | 5-31 | 0x4000_0144 | DRCMR17 | Request to Channel Map register for ICP receive request | 5-31 | 0x4000_0148 | DRCMR18 | Request to Channel Map register for ICP transmit request | 5-31 | 0x4000_014C | DRCMR19 | Request to Channel Map register for STUART receive request | 5-31 | 0x4000_0150 | DRCMR20 | Request to Channel Map register for STUART transmit request | 5-31 | 0x4000_0154 | DRCMR21 | Request to Channel Map register for MMC/SDIO receive request | 5-31 | 0x4000_0158 | DRCMR22 | Request to Channel Map register for MMC/SDIO transmit request | 5-31 | 0x4000_0160 | DRCMR24 | Request to Channel Map register for USB endpoint 0 request | 5-31 | 0x4000_0164 | DRCMR25 | Request to Channel Map register for USB endpoint A request | 5-31 | 0x4000_0168 | DRCMR26 | Request to Channel Map register for USB endpoint B request | 5-31 | 0x4000_016C | DRCMR27 | Request to Channel Map register for USB endpoint C request | 5-31 | 0x4000_0170 | DRCMR28 | Request to Channel Map register for USB endpoint D request | 5-31 | 0x4000_0174 | DRCMR29 | Request to Channel Map register for USB endpoint E request | 5-31 | 0x4000_0178 | DRCMR30 | Request to Channel Map register for USB endpoint F request | 5-31 | 0x4000_017C | DRCMR31 | Request to Channel Map register for USB endpoint G request | 5-31 | 0x4000_0180 | DRCMR32 | Request to Channel Map register for USB endpoint H request | 5-31 | 0x4000_0184 | DRCMR33 | Request to Channel Map register for USB endpoint I request | 5-31 | 0x4000_0188 | DRCMR34 | Request to Channel Map register for USB endpoint J request | 5-31 | 0x4000_018C | DRCMR35 | Request to Channel Map register for USB endpoint K request | 5-31 | 0x4000_0190 | DRCMR36 | Request to Channel Map register for USB endpoint L request | 5-31 | 0x4000_0194 | DRCMR37 | Request to Channel Map register for USB endpoint M request | 5-31 | 0x4000_0198 | DRCMR38 | Request to Channel Map register for USB endpoint N request | 5-31 | 0x4000_019C | DRCMR39 | Request to Channel Map register for USB endpoint P request | 5-31 | 0x4000_01A0 | DRCMR40 | Request to Channel Map register for USB endpoint Q request | 5-31 | 0x4000_01A4 | DRCMR41 | Request to Channel Map register for USB endpoint R request | 5-31 | 0x4000_01A8 | DRCMR42 | Request to Channel Map register for USB endpoint S request | 5-31 | 0x4000_01AC | DRCMR43 | Request to Channel Map register for USB endpoint T request | 5-31 | 0x4000_01B0 | DRCMR44 | Request to Channel Map register for USB endpoint U request | 5-31 | 0x4000_01B4 | DRCMR45 | Request to Channel Map register for USB endpoint V request | 5-31 | 0x4000_01B8 | DRCMR46 | Request to Channel Map register for USB endpoint W request | 5-31 | 0x4000_01BC | DRCMR47 | Request to Channel Map register for USB endpoint X request | 5-31 | 0x4000_01C0 | DRCMR48 | Request to Channel Map register for MSL receive request 1 | 5-31 | 0x4000_01C4 | DRCMR49 | Request to Channel Map register for MSL transmit request 1 | 5-31 | 0x4000_01C8 | DRCMR50 | Request to Channel Map register for MSL receive request 2 | 5-31 | 0x4000_01CC | DRCMR51 | Request to Channel Map register for MSL transmit request 2 | 5-31 | 0x4000_01D0 | DRCMR52 | Request to Channel Map register for MSL receive request 3 | 5-31 | 0x4000_01D4 | DRCMR53 | Request to Channel Map register for MSL transmit request 3 | 5-31 | 0x4000_01D8 | DRCMR54 | Request to Channel Map register for MSL receive request 4 | 5-31 | 0x4000_01DC | DRCMR55 | Request to Channel Map register for MSL transmit request 4 | 5-31 | 0x4000_01E0 | DRCMR56 | Request to Channel Map register for MSL receive request 5 | 5-31 | 0x4000_01E4 | DRCMR57 | Request to Channel Map register for MSL transmit request 5 | 5-31 | 0x4000_01E8 | DRCMR58 | Request to Channel Map register for MSL receive request 6 | 5-31 | 0x4000_01EC | DRCMR59 | Request to Channel Map register for MSL transmit request 6 | 5-31 | 0x4000_01F0 | DRCMR60 | Request to Channel Map register for MSL receive request 7 | 5-31 | 0x4000_01F4 | DRCMR61 | Request to Channel Map register for MSL transmit request 7 | 5-31 | 0x4000_01F8 | DRCMR62 | Request to Channel Map register for USIM receive request | 5-31 | 0x4000_01FC | DRCMR63 | Request to Channel Map register for USIM transmit request | 5-31 | 0x4000_0200 | DDADR0 | DMA Descriptor Address register for Channel 0 | 5-32 | 0x4000_0204 | DSADR0 | DMA Source Address register for Channel 0 | 5-33 | 0x4000_0208 | DTADR0 | DMA Target Address register for Channel 0 | 5-34 | 0x4000_020C | DCMD0 | DMA Command Address register for Channel 0 | 5-35 | 0x4000_0210 | DDADR1 | DMA Descriptor Address register for Channel 1 | 5-32 | 0x4000_0214 | DSADR1 | DMA Source Address register for Channel 1 | 5-33 | 0x4000_0218 | DTADR1 | DMA Target Address register for Channel 1 | 5-34 | 0x4000_021C | DCMD1 | DMA Command Address register for Channel 1 | 5-35 | 0x4000_0220 | DDADR2 | DMA Descriptor Address register for Channel 2 | 5-32 | 0x4000_0224 | DSADR2 | DMA Source Address register for Channel 2 | 5-33 | 0x4000_0228 | DTADR2 | DMA Target Address register for Channel 2 | 5-34 | 0x4000_022C | DCMD2 | DMA Command Address register for Channel 2 | 5-35 | 0x4000_0230 | DDADR3 | DMA Descriptor Address register for Channel 3 | 5-32 | 0x4000_0234 | DSADR3 | DMA Source Address register for Channel 3 | 5-33 | 0x4000_0238 | DTADR3 | DMA Target Address register for Channel 3 | 5-34 | 0x4000_023C | DCMD3 | DMA Command Address register for Channel 3 | 5-35 | 0x4000_0240 | DDADR4 | DMA Descriptor Address register for Channel 4 | 5-32 | 0x4000_0244 | DSADR4 | DMA Source Address register for Channel 4 | 5-33 | 0x4000_0248 | DTADR4 | DMA Target Address register for Channel 4 | 5-34 | 0x4000_024C | DCMD4 | DMA Command Address register for Channel 4 | 5-35 | 0x4000_0250 | DDADR5 | DMA Descriptor Address register for Channel 5 | 5-32 | 0x4000_0254 | DSADR5 | DMA Source Address register for Channel 5 | 5-33 | 0x4000_0258 | DTADR5 | DMA Target Address register for Channel 5 | 5-34 | 0x4000_025C | DCMD5 | DMA Command Address register for Channel 5 | 5-35 | 0x4000_0260 | DDADR6 | DMA Descriptor Address register for Channel 6 | 5-32 | 0x4000_0264 | DSADR6 | DMA Source Address register for Channel 6 | 5-33 | 0x4000_0268 | DTADR6 | DMA Target Address register for Channel 6 | 5-34 | 0x4000_026C | DCMD6 | DMA Command Address register for Channel 6 | 5-35 | 0x4000_0270 | DDADR7 | DMA Descriptor Address register for Channel 7 | 5-32 | 0x4000_0274 | DSADR7 | DMA Source Address register for Channel 7 | 5-33 | 0x4000_0278 | DTADR7 | DMA Target Address register for Channel 7 | 5-34 | 0x4000_027C | DCMD7 | DMA Command Address register for Channel 7 | 5-35 | 0x4000_0280 | DDADR8 | DMA Descriptor Address register for Channel 8 | 5-32 | 0x4000_0284 | DSADR8 | DMA Source Address register for Channel 8 | 5-33 | 0x4000_0288 | DTADR8 | DMA Target Address register for Channel 8 | 5-34 | 0x4000_028C | DCMD8 | DMA Command Address register for Channel 8 | 5-35 | 0x4000_0290 | DDADR9 | DMA Descriptor Address register for Channel 9 | 5-32 | 0x4000_0294 | DSADR9 | DMA Source Address register for Channel 9 | 5-33 | 0x4000_0298 | DTADR9 | DMA Target Address register for Channel 9 | 5-34 | 0x4000_029C | DCMD9 | DMA Command Address register for Channel 9 | 5-35 | 0x4000_02A0 | DDADR10 | DMA Descriptor Address register for Channel 10 | 5-32 | 0x4000_02A4 | DSADR10 | DMA Source Address register for Channel 10 | 5-33 | 0x4000_02A8 | DTADR10 | DMA Target Address register for Channel 10 | 5-34 | 0x4000_02AC | DCMD10 | DMA Command Address register for Channel 10 | 5-35 | 0x4000_02B0 | DDADR11 | DMA Descriptor Address register for Channel 11 | 5-32 | 0x4000_02B4 | DSADR11 | DMA Source Address register for Channel 11 | 5-33 | 0x4000_02B8 | DTADR11 | DMA Target Address register for Channel 11 | 5-34 | 0x4000_02BC | DCMD11 | DMA Command Address register for Channel 11 | 5-35 | 0x4000_02C0 | DDADR12 | DMA Descriptor Address register for Channel 12 | 5-32 | 0x4000_02C4 | DSADR12 | DMA Source Address register for Channel 12 | 5-33 | 0x4000_02C8 | DTADR12 | DMA Target Address register for Channel 12 | 5-34 | 0x4000_02CC | DCMD12 | DMA Command Address register for Channel 12 | 5-35 | 0x4000_02D0 | DDADR13 | DMA Descriptor Address register for Channel 13 | 5-32 | 0x4000_02D4 | DSADR13 | DMA Source Address register for Channel 13 | 5-33 | 0x4000_02D8 | DTADR13 | DMA Target Address register for Channel 13 | 5-34 | 0x4000_02DC | DCMD13 | DMA Command Address register for Channel 13 | 5-35 | 0x4000_02E0 | DDADR14 | DMA Descriptor Address register for Channel 14 | 5-32 | 0x4000_02E4 | DSADR14 | DMA Source Address register for Channel 14 | 5-33 | 0x4000_02E8 | DTADR14 | DMA Target Address register for Channel 14 | 5-34 | 0x4000_02EC | DCMD14 | DMA Command Address register for Channel 14 | 5-35 | 0x4000_02F0 | DDADR15 | DMA Descriptor Address register for Channel 15 | 5-32 | 0x4000_02F4 | DSADR15 | DMA Source Address register for Channel 15 | 5-33 | 0x4000_02F8 | DTADR15 | DMA Target Address register for Channel 15 | 5-34 | 0x4000_02FC | DCMD15 | DMA Command Address register for Channel 15 | 5-35 | 0x4000_0300 | DDADR16 | DMA Descriptor Address register for Channel 16 | 5-32 | 0x4000_0304 | DSADR16 | DMA Source Address register for Channel 16 | 5-33 | 0x4000_0308 | DTADR16 | DMA Target Address register for Channel 16 | 5-34 | 0x4000_030C | DCMD16 | DMA Command Address register for Channel 16 | 5-35 | 0x4000_0310 | DDADR17 | DMA Descriptor Address register for Channel 17 | 5-32 | 0x4000_0314 | DSADR17 | DMA Source Address register for Channel 17 | 5-33 | 0x4000_0318 | DTADR17 | DMA Target Address register for Channel 17 | 5-34 | 0x4000_031C | DCMD17 | DMA Command Address register for Channel 17 | 5-35 | 0x4000_0320 | DDADR18 | DMA Descriptor Address register for Channel 18 | 5-32 | 0x4000_0324 | DSADR18 | DMA Source Address register for Channel 18 | 5-33 | 0x4000_0328 | DTADR18 | DMA Target Address register for Channel 18 | 5-34 | 0x4000_032C | DCMD18 | DMA Command Address register for Channel 18 | 5-35 | 0x4000_0330 | DDADR19 | DMA Descriptor Address register for Channel 19 | 5-32 | 0x4000_0334 | DSADR19 | DMA Source Address register for Channel 19 | 5-33 | 0x4000_0338 | DTADR19 | DMA Target Address register for Channel 19 | 5-34 | 0x4000_033C | DCMD19 | DMA Command Address register for Channel 19 | 5-35 | 0x4000_0340 | DDADR20 | DMA Descriptor Address register for Channel 20 | 5-32 | 0x4000_0344 | DSADR20 | DMA Source Address register for Channel 20 | 5-33 | 0x4000_0348 | DTADR20 | DMA Target Address register for Channel 20 | 5-34 | 0x4000_034C | DCMD20 | DMA Command Address register for Channel 20 | 5-35 | 0x4000_0350 | DDADR21 | DMA Descriptor Address register for Channel 21 | 5-32 | 0x4000_0354 | DSADR21 | DMA Source Address register for Channel 21 | 5-33 | 0x4000_0358 | DTADR21 | DMA Target Address register for Channel 21 | 5-34 | 0x4000_035C | DCMD21 | DMA Command Address register for Channel 21 | 5-35 | 0x4000_0360 | DDADR22 | DMA Descriptor Address register for Channel 22 | 5-32 | 0x4000_0364 | DSADR22 | DMA Source Address register for Channel 22 | 5-33 | 0x4000_0368 | DTADR22 | DMA Target Address register for Channel 22 | 5-34 | 0x4000_036C | DCMD22 | DMA Command Address register for Channel 22 | 5-35 | 0x4000_0370 | DDADR23 | DMA Descriptor Address register for Channel 23 | 5-32 | 0x4000_0374 | DSADR23 | DMA Source Address register for Channel 23 | 5-33 | 0x4000_0378 | DTADR23 | DMA Target Address register for Channel 23 | 5-34 | 0x4000_037C | DCMD23 | DMA Command Address register for Channel 23 | 5-35 | 0x4000_0380 | DDADR24 | DMA Descriptor Address register for Channel 24 | 5-32 | 0x4000_0384 | DSADR24 | DMA Source Address register for Channel 24 | 5-33 | 0x4000_0388 | DTADR24 | DMA Target Address register for Channel 24 | 5-34 | 0x4000_038C | DCMD24 | DMA Command Address register for Channel 24 | 5-35 | 0x4000_0390 | DDADR25 | DMA Descriptor Address register for Channel 25 | 5-32 | 0x4000_0394 | DSADR25 | DMA Source Address register for Channel 25 | 5-33 | 0x4000_0398 | DTADR25 | DMA Target Address register for Channel 25 | 5-34 | 0x4000_039C | DCMD25 | DMA Command Address register for Channel 25 | 5-35 | 0x4000_03A0 | DDADR26 | DMA Descriptor Address register for Channel 26 | 5-32 | 0x4000_03A4 | DSADR26 | DMA Source Address register for Channel 26 | 5-33 | 0x4000_03A8 | DTADR26 | DMA Target Address register for Channel 26 | 5-34 | 0x4000_03AC | DCMD26 | DMA Command Address register for Channel 26 | 5-35 | 0x4000_03B0 | DDADR27 | DMA Descriptor Address register for Channel 27 | 5-32 | 0x4000_03B4 | DSADR27 | DMA Source Address register for Channel 27 | 5-33 | 0x4000_03B8 | DTADR27 | DMA Target Address register for Channel 27 | 5-34 | 0x4000_03BC | DCMD27 | DMA Command Address register for Channel 27 | 5-35 | 0x4000_03C0 | DDADR28 | DMA Descriptor Address register for Channel 28 | 5-32 | 0x4000_03C4 | DSADR28 | DMA Source Address register for Channel 28 | 5-33 | 0x4000_03C8 | DTADR28 | DMA Target Address register for Channel 28 | 5-34 | 0x4000_03CC | DCMD28 | DMA Command Address register for Channel 28 | 5-35 | 0x4000_03D0 | DDADR29 | DMA Descriptor Address register for Channel 29 | 5-32 | 0x4000_03D4 | DSADR29 | DMA Source Address register for Channel 29 | 5-33 | 0x4000_03D8 | DTADR29 | DMA Target Address register for Channel 29 | 5-34 | 0x4000_03DC | DCMD29 | DMA Command Address register for Channel 29 | 5-35 | 0x4000_03E0 | DDADR30 | DMA Descriptor Address register for Channel 30 | 5-32 | 0x4000_03E4 | DSADR30 | DMA Source Address register for Channel 30 | 5-33 | 0x4000_03E8 | DTADR30 | DMA Target Address register for Channel 30 | 5-34 | 0x4000_03EC | DCMD30 | DMA Command Address register for Channel 30 | 5-35 | 0x4000_03F0 | DDADR31 | DMA Descriptor Address register for Channel 31 | 5-32 | 0x4000_03F4 | DSADR31 | DMA Source Address register for Channel 31 | 5-33 | 0x4000_03F8 | DTADR31 | DMA Target Address register for Channel 31 | 5-34 | 0x4000_03FC | DCMD31 | DMA Command Address register for Channel 31 | 5-35 | 0x4000_1100 | DRCMR64 | Request to Channel Map register for Memory Stick receive request | 5-31 | 0x4000_1104 | DRCMR65 | Request to Channel Map register for Memory Stick transmit request | 5-31 | 0x4000_1108 | DRCMR66 | Request to Channel Map register for SSP3 receive request | 5-31 | 0x4000_110C | DRCMR67 | Request to Channel Map register for SSP3 transmit request | 5-31 | 0x4000_1110 | DRCMR68 | Request to Channel Map register for Quick Capture Interface Receive Request 0 | 5-31 | 0x4000_1114 | DRCMR69 | Request to Channel Map register for Quick Capture Interface Receive Request 1 | 5-31 | 0x4000_1118 | DRCMR70 | Request to Channel Map register for Quick Capture Interface Receive Request 2 | 5-31 | 0x4000_1128 | DRCMR74 | Request to Channel Map register for DREQ<2> (companion chip request 2) | 5-31 | 0x4800_0020 | FLYCNFG | Fly-by DMA DVAL<1:0> polarities | 5-39 Full-Function UART | 0x4010_0000 | FFRBR | Receive Buffer register | 10-13 | 0x4010_0000 | FFTHR | Transmit Holding register | 10-14 | 0x4010_0000 | FFDLL | Divisor Latch register, low byte | 10-14 | 0x4010_0004 | FFIER | Interrupt Enable register | 10-15 | 0x4010_0004 | FFDLH | Divisor Latch register, high byte | 10-14 | 0x4010_0008 | FFIIR | Interrupt ID register | 10-17 | 0x4010_0008 | FFFCR | FIFO Control register | 10-19 | 0x4010_000C | FFLCR | Line Control register | 10-25 | 0x4010_0010 | FFMCR | Modem Control register | 10-29 | 0x4010_0014 | FFLSR | Line Status register | 10-26 | 0x4010_0018 | FFMSR | Modem Status register | 10-31 | 0x4010_001C | FFSPR | Scratch Pad register | 10-33 | 0x4010_0020 | FFISR | Infrared Select register | 10-33 | 0x4010_0024 | FFFOR | Receive FIFO Occupancy register | 10-22 | 0x4010_0028 | FFABR | Auto-baud Control register | 10-23 | 0x4010_002C | FFACR | Auto-baud Count register | 10-24 Bluetooth UART | 0x4020_0000 | BTRBR | Receive Buffer register | 10-13 | 0x4020_0000 | BTTHR | Transmit Holding register | 10-14 | 0x4020_0000 | BTDLL | Divisor Latch register, low byte | 10-14 | 0x4020_0004 | BTIER | Interrupt Enable register | 10-15 | 0x4020_0004 | BTDLH | Divisor Latch register, high byte | 10-14 | 0x4020_0008 | BTIIR | Interrupt ID register | 10-17 | 0x4020_0008 | BTFCR | FIFO Control register | 10-19 | 0x4020_000C | BTLCR | Line Control register | 10-25 | 0x4020_0010 | BTMCR | Modem Control register | 10-29 | 0x4020_0014 | BTLSR | Line Status register | 10-26 | 0x4020_0018 | BTMSR | Modem Status register | 10-31 | 0x4020_001C | BTSPR | Scratch Pad register | 10-33 | 0x4020_0020 | BTISR | Infrared Select register | 10-33 | 0x4020_0024 | BTFOR | Receive FIFO Occupancy register | 10-22 | 0x4020_0028 | BTABR | Auto-Baud Control register | 10-23 | 0x4020_002C | BTACR | Auto-Baud Count register | 10-24 Standard I2C | 0x4030_1680 | IBMR | I2C Bus Monitor register | 9-30 | 0x4030_1688 | IDBR | I2C Data Buffer register | 9-29 | 0x4030_1690 | ICR | I2C Control register | 9-23 | 0x4030_1698 | ISR | I2C Status register | 9-26 | 0x4030_16A0 | ISAR | I2C Slave Address register | 9-28 I2S Controller | 0x4040_0000 | SACR0 | Serial Audio Global Control register | 14-10 | 0x4040_0004 | SACR1 | Serial Audio I2S/MSB-Justified Control register | 14-13 | 0x4040_000C | SASR0 | Serial Audio I2S/MSB-Justified Interface and FIFO Status register | 14-14 | 0x4040_0014 | SAIMR | Serial Audio Interrupt Mask register | 14-18 | 0x4040_0018 | SAICR | Serial Audio Interrupt Clear register | 14-17 | 0x4040_0060 | SADIV | Audio Clock Divider register | 14-16 | 0x4040_0080 | SADR | Serial Audio Data register (TX and RX FIFO access register). | 14-18 AC 97 Controller | 0x4050_0000 | POCR | PCM Out Control register | 13-27 | 0x4050_0004 | PCMICR | PCM In Control register | 13-28 | 0x4050_0008 | MCCR | Microphone In Control register | 13-33 | 0x4050_000C | GCR | Global Control register | 13-22 | 0x4050_0010 | POSR | PCM Out Status register | 13-29 | 0x4050_0014 | PCMISR | PCM In Status register | 13-30 | 0x4050_0018 | MCSR | MIC In Status register | 13-34 | 0x4050_001C | GSR | Global Status register | 13-24 | 0x4050_0020 | CAR | Codec Access register | 13-31 | 0x4050_0040 | PCDR | PCM Data register | 13-32 | 0x4050_0060 | MCDR | MIC In Data register | 13-35 | 0x4050_0100 | MOCR | Modem Out Control register | 13-36 | 0x4050_0108 | MICR | Modem In Control register | 13-37 | 0x4050_0110 | MOSR | Modem Out Status register | 13-38 | 0x4050_0118 | MISR | Modem In Status register | 13-39 | 0x4050_0140 | MODR | Modem Data register | 13-40 | 0x4050_0200 0x4050_02FC | with all in increments of 0x00004 Primary Audio Codec registers | 13-41 | 0x4050_0300 0x4050_03FC | with all in increments of 0x00004 Secondary Audio Codec registers | 13-41 | 0x4050_0400 0x4050_04FC | with all in increments of 0x0000_0004 Primary Modem Codec registers | 13-41 | 0x4050_0500 0x4050_05FC | with all in increments of 0x00004 Secondary Modem Codec registers | 13-41 USB Client Controller | 0x4060_0000 | UDCCR | UDC Control register | 12-31 | 0x4060_0004 | UDCICR0 | UDC Interrupt Control register 0 | 12-35 | 0x4060_0008 | UDCCIR1 | UDC Interrupt Control register 1 | 12-35 | 0x4060_000C | UDCISR0 | UDC Interrupt Status register 0 | 12-49 | 0x4060_0010 | UDCSIR1 | UDC Interrupt Status register 1 | 12-49 | 0x4060_0014 | UDCFNR | UDC Frame Number register | 12-52 | 0x4060_0018 | UDCOTGICR | UDC OTG Interrupt Control register | 12-35 | 0x4060_001C | UDCOTGISR | UDC OTG Interrupt Status register | 12-49 | 0x4060_0020 | UP2OCR | USB Port 2 Output Control register | 12-41 | 0x4060_0024 | UP3OCR | USB Port 3 Output Control register | 12-47 | 0x4060_0100 | UDCCSR0 | UDC Control/Status registerEndpoint 0 | 12-53 | 0x4060_0104 | UDCCSRA | UDC Control/Status registerEndpoint A | 12-56 | 0x4060_0108 | UDCCSRB | UDC Control/Status registerEndpoint B | 12-56 | 0x4060_010C | UDCCSRC | UDC Control/Status registerEndpoint C | 12-56 | 0x4060_0110 | UDCCSRD | UDC Control/Status registerEndpoint D | 12-56 | 0x4060_0114 | UDCCSRE | UDC Control/Status registerEndpoint E | 12-56 | 0x4060_0118 | UDCCSRF | UDC Control/Status registerEndpoint F | 12-56 | 0x4060_011C | UDCCSRG | UDC Control/Status registerEndpoint G | 12-56 | 0x4060_0120 | UDCCSRH | UDC Control/Status registerEndpoint H | 12-56 | 0x4060_0124 | UDCCSRI | UDC Control/Status registerEndpoint I | 12-56 | 0x4060_0128 | UDCCSRJ | UDC Control/Status registerEndpoint J | 12-56 | 0x4060_012C | UDCCSRK | UDC Control/Status registerEndpoint K | 12-56 | 0x4060_0130 | UDCCSRL | UDC Control/Status registerEndpoint L | 12-56 | 0x4060_0134 | UDCCSRM | UDC Control/Status registerEndpoint M | 12-56 | 0x4060_0138 | UDCCSRN | UDC Control/Status registerEndpoint N | 12-56 | 0x4060_013C | UDCCSRP | UDC Control/Status registerEndpoint P | 12-56 | 0x4060_0140 | UDCCSRQ | UDC Control/Status registerEndpoint Q | 12-56 | 0x4060_0144 | UDCCSRR | UDC Control/Status registerEndpoint R | 12-56 | 0x4060_0148 | UDCCSRS | UDC Control/Status registerEndpoint S | 12-56 | 0x4060_014C | UDCCSRT | UDC Control/Status registerEndpoint T | 12-56 | 0x4060_0150 | UDCCSRU | UDC Control/Status registerEndpoint U | 12-56 | 0x4060_0154 | UDCCSRV | UDC Control/Status registerEndpoint V | 12-56 | 0x4060_0158 | UDCCSRW | UDC Control/Status registerEndpoint W | 12-56 | 0x4060_015C | UDCCSRX | UDC Control/Status registerEndpoint X | 12-56 | 0x4060_0200 | UDCBCR0 | UDC Byte Count registerEndpoint 0 | 12-62 | 0x4060_0204 | UDCBCRA | UDC Byte Count registerEndpoint A | 12-62 | 0x4060_0208 | UDCBCRB | UDC Byte Count registerEndpoint B | 12-62 | 0x4060_020C | UDCBCRC | UDC Byte Count registerEndpoint C | 12-62 | 0x4060_0210 | UDCBCRD | UDC Byte Count registerEndpoint D | 12-62 | 0x4060_0214 | UDCBCRE | UDC Byte Count registerEndpoint E | 12-62 | 0x4060_0218 | UDCBCRF | UDC Byte Count registerEndpoint F | 12-62 | 0x4060_021C | UDCBCRG | UDC Byte Count registerEndpoint G | 12-62 | 0x4060_0220 | UDCBCRH | UDC Byte Count registerEndpoint H | 12-62 | 0x4060_0224 | UDCBCRI | UDC Byte Count registerEndpoint I | 12-62 | 0x4060_0228 | UDCBCRJ | UDC Byte Count registerEndpoint J | 12-62 | 0x4060_022C | UDCBCRK | UDC Byte Count registerEndpoint K | 12-62 | 0x4060_0230 | UDCBCRL | UDC Byte Count registerEndpoint L | 12-62 | 0x4060_0234 | UDCBCRM | UDC Byte Count registerEndpoint M | 12-62 | 0x4060_0238 | UDCBCRN | UDC Byte Count registerEndpoint N | 12-62 | 0x4060_023C | UDCBCRP | UDC Byte Count registerEndpoint P | 12-62 | 0x4060_0240 | UDCBCRQ | UDC Byte Count registerEndpoint Q | 12-62 | 0x4060_0244 | UDCBCRR | UDC Byte Count registerEndpoint R | 12-62 | 0x4060_0248 | UDCBCRS | UDC Byte Count registerEndpoint S | 12-62 | 0x4060_024C | UDCBCRT | UDC Byte Count registerEndpoint T | 12-62 | 0x4060_0250 | UDCBCRU | UDC Byte Count registerEndpoint U | 12-62 | 0x4060_0254 | UDCBCRV | UDC Byte Count registerEndpoint V | 12-62 | 0x4060_0258 | UDCBCRW | UDC Byte Count registerEndpoint W | 12-62 | 0x4060_025C | UDCBCRX | UDC Byte Count registerEndpoint X | 12-62 | 0x4060_0300 | UDCDR0 | UDC Data registerEndpoint 0 | 12-62 | 0x4060_0304 | UDCDRA | UDC Data registerEndpoint A | 12-62 | 0x4060_0308 | UDCDRB | UDC Data registerEndpoint B | 12-62 | 0x4060_030C | UDCDRC | UDC Data registerEndpoint C | 12-62 | 0x4060_0310 | UDCDRD | UDC Data registerEndpoint D | 12-62 | 0x4060_0314 | UDCDRE | UDC Data registerEndpoint E | 12-62 | 0x4060_0318 | UDCDRF | UDC Data registerEndpoint F | 12-62 | 0x4060_031C | UDCDRG | UDC Data registerEndpoint G | 12-62 | 0x4060_0320 | UDCDRH | UDC Data registerEndpoint H | 12-62 | 0x4060_0324 | UDCDRI | UDC Data registerEndpoint I | 12-62 | 0x4060_0328 | UDCDRJ | UDC Data registerEndpoint J | 12-62 | 0x4060_032C | UDCDRK | UDC Data registerEndpoint K | 12-62 | 0x4060_0330 | UDCDRL | UDC Data registerEndpoint L | 12-62 | 0x4060_0334 | UDCDRM | UDC Data registerEndpoint M | 12-62 | 0x4060_0338 | UDCDRN | UDC Data registerEndpoint N | 12-62 | 0x4060_033C | UDCDRP | UDC Data registerEndpoint P | 12-62 | 0x4060_0340 | UDCDRQ | UDC Data registerEndpoint Q | 12-62 | 0x4060_0344 | UDCDRR | UDC Data registerEndpoint R | 12-62 | 0x4060_0348 | UDCDRS | UDC Data registerEndpoint S | 12-62 | 0x4060_034C | UDCDRT | UDC Data registerEndpoint T | 12-62 | 0x4060_0350 | UDCDRU | UDC Data registerEndpoint U | 12-62 | 0x4060_0354 | UDCDRV | UDC Data registerEndpoint V | 12-62 | 0x4060_0358 | UDCDRW | UDC Data registerEndpoint W | 12-62 | 0x4060_035C | UDCDRX | UDC Data registerEndpoint X | 12-62 | 0x4060_0404 | UDCCRA | UDC Configuration registerEndpoint A | 12-64 | 0x4060_0408 | UDCCRB | UDC Configuration registerEndpoint B | 12-64 | 0x4060_040C | UDCCRC | UDC Configuration registerEndpoint C | 12-64 | 0x4060_0410 | UDCCRD | UDC Configuration registerEndpoint D | 12-64 | 0x4060_0414 | UDCCRE | UDC Configuration registerEndpoint E | 12-64 | 0x4060_0418 | UDCCRF | UDC Configuration registerEndpoint F | 12-64 | 0x4060_041C | UDCCRG | UDC Configuration registerEndpoint G | 12-64 | 0x4060_0420 | UDCCRH | UDC Configuration registerEndpoint H | 12-64 | 0x4060_0424 | UDCCRI | UDC Configuration registerEndpoint I | 12-64 | 0x4060_0428 | UDCCRJ | UDC Configuration registerEndpoint J | 12-64 | 0x4060_042C | UDCCRK | UDC Configuration registerEndpoint K | 12-64 | 0x4060_0430 | UDCCRL | UDC Configuration registerEndpoint L | 12-64 | 0x4060_0434 | UDCCRM | UDC Configuration registerEndpoint M | 12-64 | 0x4060_0438 | UDCCRN | UDC Configuration registerEndpoint N | 12-64 | 0x4060_043C | UDCCRP | UDC Configuration registerEndpoint P | 12-64 | 0x4060_0440 | UDCCRQ | UDC Configuration registerEndpoint Q | 12-64 | 0x4060_0444 | UDCCRR | UDC Configuration registerEndpoint R | 12-64 | 0x4060_0448 | UDCCRS | UDC Configuration registerEndpoint S | 12-64 | 0x4060_044C | UDCCRT | UDC Configuration registerEndpoint T | 12-64 | 0x4060_0450 | UDCCRU | UDC Configuration registerEndpoint U | 12-64 | 0x4060_0454 | UDCCRV | UDC Configuration registerEndpoint V | 12-64 | 0x4060_0458 | UDCCRW | UDC Configuration registerEndpoint W | 12-64 | 0x4060_045C | UDCCRX | UDC Configuration registerEndpoint X | 12-64 Standard UART | 0x4070_0000 | STRBR | Receive Buffer register | 10-13 | 0x4070_0000 | STTHR | Transmit Holding register | 10-14 | 0x4070_0000 | STDLL | Divisor Latch register, low byte | 10-14 | 0x4070_0004 | STIER | Interrupt Enable register | 10-15 | 0x4070_0004 | STDLH | Divisor Latch register, high byte | 10-14 | 0x4070_0008 | STIIR | Interrupt ID register | 10-17 | 0x4070_0008 | STFCR | FIFO Control register | 10-19 | 0x4070_000C | STLCR | Line Control register | 10-25 | 0x4070_0010 | STMCR | Modem Control register | 10-29 | 0x4070_0014 | STLSR | Line Status register | 10-26 | 0x4070_0018 | STMSR | Modem Status register | 10-31 | 0x4070_001C | STSPR | Scratch Pad register | 10-33 | 0x4070_0020 | STISR | Infrared Select register | 10-33 | 0x4070_0024 | STFOR | Receive FIFO Occupancy register | 10-22 | 0x4070_0028 | STABR | Auto-Baud Control register | 10-23 | 0x4070_002C | STACR | Auto-Baud Count register | 10-24 Infrared Communications Port | 0x4080_0000 | ICCR0 | FICP Control register 0 | 11-10 | 0x4080_0004 | ICCR1 | FICP Control register 1 | 11-13 | 0x4080_0008 | ICCR2 | FICP Control register 2 | 11-14 | 0x4080_000C | ICDR | FICP Data register | 11-15 | 0x4080_0014 | ICSR0 | FICP Status register 0 | 11-16 | 0x4080_0018 | ICSR1 | FICP Status register 1 | 11-18 | 0x4080_001C | ICFOR | FICP FIFO Occupancy Status register | 11-19 Real-Time Clock | 0x4090_0000 | RCNR | RTC Counter register | 21-24 | 0x4090_0004 | RTAR | RTC Alarm register | 21-19 | 0x4090_0008 | RTSR | RTC Status register | 21-17 | 0x4090_000C | RTTR | RTC Timer Trim register | 21-16 | 0x4090_0010 | RDCR | RTC Day Counter register | 21-24 | 0x4090_0014 | RYCR | RTC Year Counter register | 21-25 | 0x4090_0018 | RDAR1 | RTC Wristwatch Day Alarm register 1 | 21-20 | 0x4090_001C | RYAR1 | RTC Wristwatch Year Alarm register 1 | 21-21 | 0x4090_0020 | RDAR2 | RTC Wristwatch Day Alarm register 2 | 21-20 | 0x4090_0024 | RYAR2 | RTC Wristwatch Year Alarm register 2 | 21-21 | 0x4090_0028 | SWCR | RTC Stopwatch Counter register | 21-26 | 0x4090_002C | SWAR1 | RTC Stopwatch Alarm register 1 | 21-22 | 0x4090_0030 | SWAR2 | RTC Stopwatch Alarm register 2 | 21-22 | 0x4090_0034 | RTCPICR | RTC Periodic Interrupt Counter register | 21-27 | 0x4090_0038 | PIAR | RTC Periodic Interrupt Alarm register | 21-23 OS Timers | 0x40A0_0000 | OSMR0 | OS Timer Match 0 register | 22-15 | 0x40A0_0004 | OSMR1 | OS Timer Match 1 register | 22-15 | 0x40A0_0008 | OSMR2 | OS Timer Match 2 register | 22-15 | 0x40A0_000C | OSMR3 | OS Timer Match 3 register | 22-15 | 0x40A0_0010 | OSCR0 | OS Timer Counter 0 register | 22-17 | 0x40A0_0014 | OSSR | OS Timer Status register (used for all counters) | 22-18 | 0x40A0_0018 | OWER | OS Timer Watchdog Enable register | 22-16 | 0x40A0_001C | OIER | OS Timer Interrupt Enable register (used for all counters) | 22-16 | 0x40A0_0020 | OSNR | OS Timer Snapshot register | 22-19 | 0x40A0_0040 | OSCR4 | OS Timer Counter 4 register | 22-17 | 0x40A0_0044 | OSCR5 | OS Timer Counter 5 register | 22-17 | 0x40A0_0048 | OSCR6 | OS Timer Counter 6 register | 22-17 | 0x40A0_004C | OSCR7 | OS Timer Counter 7 register | 22-17 | 0x40A0_0050 | OSCR8 | OS Timer Counter 8 register | 22-17 | 0x40A0_0054 | OSCR9 | OS Timer Counter 9 register | 22-17 | 0x40A0_0058 | OSCR10 | OS Timer Counter 10 register | 22-17 | 0x40A0_005C | OSCR11 | OS Timer Counter 11 register | 22-17 | 0x40A0_0080 | OSMR4 | OS Timer Match 4 register | 22-15 | 0x40A0_0084 | OSMR5 | OS Timer Match 5 register | 22-15 | 0x40A0_0088 | OSMR6 | OS Timer Match 6 register | 22-15 | 0x40A0_008C | OSMR7 | OS Timer Match 7 register | 22-15 | 0x40A0_0090 | OSMR8 | OS Timer Match 8 register | 22-15 | 0x40A0_0094 | OSMR9 | OS Timer Match 9 register | 22-15 | 0x40A0_0098 | OSMR10 | OS Timer Match 10 register | 22-15 | 0x40A0_009C | OSMR11 | OS Timer Match 11 register | 22-15 | 0x40A0_00C0 | OMCR4 | OS Match Control 4 register | 22-9 | 0x40A0_00C4 | OMCR5 | OS Match Control 5 register | 22-9 | 0x40A0_00C8 | OMCR6 | OS Match Control 6 register | 22-9 | 0x40A0_00CC | OMCR7 | OS Match Control 7 register | 22-9 | 0x40A0_00D0 | OMCR8 | OS Match Control 8 register | 22-11 | 0x40A0_00D4 | OMCR9 | OS Match Control 9 register | 22-13 | 0x40A0_00D8 | OMCR10 | OS Match Control 10 register | 22-11 | 0x40A0_00DC | OMCR11 | OS Match Control 11 register | 22-13 Pulse-Width Modulation | 0x40B0_0000 | PWMCR0 | PWM 0 Control register | 23-7 | 0x40B0_0004 | PWMDCR0 | PWM 0 Duty Cycle register | 23-8 | 0x40B0_0008 | PWMPCR0 | PWM 0 Period register | 23-9 | 0x40B0_0010 | PWMCR2 | PWM 2 Control register | 23-7 | 0x40B0_0014 | PWMDCR2 | PWM 2 Duty Cycle register | 23-8 | 0x40B0_0018 | PWMPCR2 | PWM 2 Period register | 23-9 | 0x40C0_0000 | PWMCR1 | PWM 1 Control register | 23-7 | 0x40C0_0004 | PWMDCR1 | PWM 1 Duty Cycle register | 23-8 | 0x40C0_0008 | PWMPCR1 | PWM 1 Period register | 23-9 | 0x40C0_0010 | PWMCR3 | PWM 3 Control register | 23-7 | 0x40C0_0014 | PWMDCR3 | PWM 3 Duty Cycle register | 23-8 | 0x40C0_0018 | PWMPCR3 | PWM 3 Period register | 23-9 Interrupt Controller | 0x40D0_0000 | ICIP | Interrupt Controller IRQ Pending register | 25-11 | 0x40D0_0004 | ICMR | Interrupt Controller Mask register | 25-20 | 0x40D0_0008 | ICLR | Interrupt Controller Level register | 25-24 | 0x40D0_000C | ICFP | Interrupt Controller FIQ Pending register | 25-15 | 0x40D0_0010 | ICPR | Interrupt Controller Pending register | 25-6 | 0x40D0_0014 | ICCR | Interrupt Controller Control register | 25-27 | 0x40D0_0018 | ICHP | Interrupt Controller Highest Priority register | 25-30 | 0x40D0_001C IPR0 0x40D0_0098 | IPR31 | Interrupt Priority registers for Priorities 031 | 25-29 | 0x40D0_009C | ICIP2 | Interrupt Controller IRQ Pending register 2 | 25-10 | 0x40D0_00A0 | ICMR2 | Interrupt Controller Mask register 2 | 25-23 | 0x40D0_00A4 | ICLR2 | Interrupt Controller Level register 2 | 25-27 | 0x40D0_00A8 | ICFP2 | Interrupt Controller FIQ Pending register 2 | 25-19 | 0x40D0_00AC | ICPR2 | Interrupt Controller Pending register 2 | 25-6 | 0x40D0_00B0 IPR32 0x40D0_00CC | IPR39 |Interrupt Priority registers for Priorities 3239 | 25-29 General-Purpose I/O (GPIO) Controller | 0x40E0_0000 | GPLR0 | GPIO Pin-Level register GPIO<31:0> | 24-28 | 0x40E0_0004 | GPLR1 | GPIO Pin-Level register GPIO<63:32> | 24-28 | 0x40E0_0008 | GPLR2 | GPIO Pin-Level register GPIO<95:64> | 24-28 | 0x40E0_000C | GPDR0 | GPIO Pin Direction register GPIO<31:0> | 24-11 | 0x40E0_0010 | GPDR1 | GPIO Pin Direction register GPIO<63:32> | 24-11 | 0x40E0_0014 | GPDR2 | GPIO Pin Direction register GPIO<95:64> | 24-11 | 0x40E0_0018 | GPSR0 | GPIO Pin Output Set register GPIO<31:0> | 24-14 | 0x40E0_001C | GPSR1 | GPIO Pin Output Set register GPIO<63:32> | 24-14 | 0x40E0_0020 | GPSR2 | GPIO Pin Output Set register GPIO<95:64> | 24-14 | 0x40E0_0024 | GPCR0 | GPIO Pin Output Clear register GPIO<31:0> | 24-14 | 0x40E0_0028 | GPCR1 | GPIO Pin Output Clear register GPIO <63:32> | 24-14 | 0x40E0_002C | GPCR2 | GPIO pin Output Clear register GPIO <95:64> | 24-14 | 0x40E0_0030 | GRER0 | GPIO Rising-Edge Detect Enable register GPIO<31:0> | 24-18 | 0x40E0_0034 | GRER1 | GPIO Rising-Edge Detect Enable register GPIO<63:32> | 24-18 | 0x40E0_0038 | GRER2 | GPIO Rising-Edge Detect Enable register GPIO<95:64> | 24-18 | 0x40E0_003C | GFER0 | GPIO Falling-Edge Detect Enable register GPIO<31:0> | 24-18 | 0x40E0_0040 | GFER1 | GPIO Falling-Edge Detect Enable register GPIO<63:32> | 24-18 | 0x40E0_0044 | GFER2 | GPIO Falling-Edge Detect Enable register GPIO<95:64> | 24-18 | 0x40E0_0048 | GEDR0 | GPIO Edge Detect Status register GPIO<31:0> | 24-30 | 0x40E0_004C | GEDR1 | GPIO Edge Detect Status register GPIO<63:32> | 24-30 | 0x40E0_0050 | GEDR2 | GPIO Edge Detect Status register GPIO<95:64> | 24-30 | 0x40E0_0054 | GAFR0_L | GPIO Alternate Function register GPIO<15:0> | 24-23 | 0x40E0_0058 | GAFR0_U | GPIO Alternate Function register GPIO<31:16> | 24-23 | 0x40E0_005C | GAFR1_L | GPIO Alternate Function register GPIO<47:32> | 24-23 | 0x40E0_0060 | GAFR1_U | GPIO Alternate Function register GPIO<63:48> | 24-23 | 0x40E0_0064 | GAFR2_L | GPIO Alternate Function register GPIO<79:64> | 24-23 | 0x40E0_0068 | GAFR2_U | GPIO Alternate Function register GPIO <95:80> | 24-23 | 0x40E0_006C | GAFR3_L | GPIO Alternate Function register GPIO<111:96> | 24-23 | 0x40E0_0070 | GAFR3_U | GPIO Alternate Function register GPIO<120:112> | 24-23 | 0x40E0_0100 | GPLR3 | GPIO Pin-Level register GPIO<120:96> | 24-28 | 0x40E0_010C | GPDR3 | GPIO Pin Direction register GPIO<120:96> | 24-11 | 0x40E0_0118 | GPSR3 | GPIO Pin Output Set register GPIO<120:96> | 24-14 | 0x40E0_0124 | GPCR3 | GPIO Pin Output Clear register GPIO<120:96> | 24-14 | 0x40E0_0130 | GRER3 | GPIO Rising-Edge Detect Enable register GPIO<120:96> | 24-18 | 0x40E0_013C | GFER3 | GPIO Falling-Edge Detect Enable register GPIO<120:96> | 24-18 | 0x40E0_0148 | GEDR3 | GPIO Edge Detect Status register GPIO<120:96> | 24-18 Power Manager and Reset Control | 0x40F0_0000 | PMCR | Power Manager Control register | 3-67 | 0x40F0_0004 | PSSR | Power Manager Sleep Status register | 3-69 | 0x40F0_0008 | PSPR | Power Manager Scratch Pad register | 3-72 | 0x40F0_000C | PWER | Power Manager Wake-Up Enable register | 3-73 | 0x40F0_0010 | PRER | Power Manager Rising-Edge Detect Enable register | 3-77 | 0x40F0_0014 | PFER | Power Manager Falling-Edge Detect Enable register | 3-78 | 0x40F0_0018 | PEDR | Power Manager Edge-Detect Status register | 3-79 | 0x40F0_001C | PCFR | Power Manager General Configuration register | 3-80 | 0x40F0_0020 | PGSR0 | Power Manager GPIO Sleep State register for GPIO<31:0> | 3-83 | 0x40F0_0024 | PGSR1 | Power Manager GPIO Sleep State register for GPIO<63:32> | 3-83 | 0x40F0_0028 | PGSR2 | Power Manager GPIO Sleep State register for GPIO<95:64> | 3-83 | 0x40F0_002C | PGSR3 | Power Manager GPIO Sleep State register for GPIO<120:96> | 3-83 | 0x40F0_0030 | RCSR | Reset Controller Status register | 3-84 | 0x40F0_0034 | PSLR | Power Manager Sleep Configuration register | 3-85 | 0x40F0_0038 | PSTR | Power Manager Standby Configuration register | 3-88 | 0x40F0_0040 | PVCR | Power Manager Voltage Change Control register | 3-89 | 0x40F0_004C | PUCR | Power Manager USIM Card Control/Status register | 3-90 | 0x40F0_0050 | PKWR | Power Manager Keyboard Wake-Up Enable register | 3-92 | 0x40F0_0054 | PKSR | Power Manager Keyboard Level-Detect Status register | 3-93 | 0x40F0_0080 PCMD0 0x40F0_00FC | PCMD31 | Power Manager I2C Command register File | 3-94 Power Manager I2C | 0x40F0_0180 | PIBMR | Power Manager I2C Bus Monitor register | 9-30 | 0x40F0_0188 | PIDBR | Power Manager I2C Data Buffer register | 9-29 | 0x40F0_0190 | PICR | Power Manager I2C Control register | 9-23 | 0x40F0_0198 | PISR | Power Manager I2C Status register | 9-26 | 0x40F0_01A0 | PISAR | Power Manager I2C Slave Address register | 9-28 Synchronous Serial Port 1 | 0x4100_0000 | SSCR0_1 | SSP 1 Control register 0 | 8-25 | 0x4100_0004 | SSCR1_1 | SSP 1 Control register 1 | 8-30 | 0x4100_0008 | SSSR_1 | SSP 1 Status register | 8-43 | 0x4100_000C | SSITR_1 | SSP 1 Interrupt Test register | 8-42 | 0x4100_0010 | SSDR_1 | SSP 1 Data Write register/Data Read register | 8-48 | 0x4100_0028 | SSTO_1 | SSP 1 Time-Out register | 8-41 | 0x4100_002C | SSPSP_1 | SSP 1 Programmable Serial Protocol | 8-39 | 0x4100_0030 | SSTSA_1 | SSP1 TX Timeslot Active register | 8-48 | 0x4100_0034 | SSRSA_1 | SSP1 RX Timeslot Active register | 8-49 | 0x4100_0038 | SSTSS_1 | SSP1 Timeslot Status register | 8-50 | 0x4100_003C | SSACD_1 | SSP1 Audio Clock Divider register | 8-51 MultiMediaCard/SD/SDIO Controller | 0x4110_0000 | MMC_STRPCL| MMC Clock Start/Stop register | 15-29 | 0x4110_0004 | MMC_STAT | MMC Status register | 15-29 | 0x4110_0008 | MMC_CLKRT | MMC Clock Rate register | 15-31 | 0x4110_000C | MMC_SPI | MMC SPI Mode register | 15-31 | 0x4110_0010 | MMC_CMDAT | MMC Command/Data register | 15-32 | 0x4110_0014 | MMC_RESTO | MMC Response Time-Out register | 15-34 | 0x4110_0018 | MMC_RDTO | MMC Read Time-Out register | 15-34 | 0x4110_001C | MMC_BLKLEN| MMC Block Length register | 15-35 | 0x4110_0020 | MMC_NUMBLK| MMC Number of Blocks register | 15-35 | 0x4110_0024 | MMC_PRTBUF| MMC Buffer Partly Full register | 15-36 | 0x4110_0028 | MMC_I_MASK| MMC Interrupt Mask register | 15-36 | 0x4110_002C | MMC_I_REG | MMC Interrupt Request register | 15-38 | 0x4110_0030 | MMC_CMD | MMC Command register | 15-41 | 0x4110_0034 | MMC_ARGH | MMC Argument High register | 15-41 | 0x4110_0038 | MMC_ARGL | MMC Argument Low register | 15-42 | 0x4110_003C | MMC_RES | MMC Response FIFO | 15-42 | 0x4110_0040 | MMC_RXFIFO| MMC Receive FIFO | 15-42 | 0x4110_0044 | MMC_TXFIFO| MMC Transmit FIFO | 15-43 | 0x4110_0048 | MMC_RDWAIT| MMC RD_WAIT register | 15-43 | 0x4110_004C | MMC_BLKS_REM | MMC Blocks Remaining register | 15-44 Clocks Manager | 0x4130_0000 | CCCR | Core Clock Configuration register | 3-95 | 0x4130_0004 | CKEN | Clock Enable register | 3-98 | 0x4130_0008 | OSCC | Oscillator Configuration register | 3-99 | 0x4130_000C | CCSR | Core Clock Status register | 3-101 Mobile Scalable Link (MSL) Interface | 0x4140_0004 | BBFIFO1 | MSL Channel 1 Receive/Transmit FIFO register | 16-13 | 0x4140_0008 | BBFIFO2 | MSL Channel 2 Receive/Transmit FIFO register | 16-13 | 0x4140_000C | BBFIFO3 | MSL Channel 3 Receive/Transmit FIFO register | 16-13 | 0x4140_0010 | BBFIFO4 | MSL Channel 4 Receive/Transmit FIFO register | 16-13 | 0x4140_0014 | BBFIFO5 | MSL Channel 5 Receive/Transmit FIFO register | 16-13 | 0x4140_0018 | BBFIFO6 | MSL Channel 6 Receive/Transmit FIFO register | 16-13 | 0x4140_001C | BBFIFO7 | MSL Channel 7 Receive/Transmit FIFO register | 16-13 | 0x4140_0044 | BBCFG1 | MSL Channel 1 Configuration register | 16-15 | 0x4140_0048 | BBCFG2 | MSL Channel 2 Configuration register | 16-15 | 0x4140_004C | BBCFG3 | MSL Channel 3 Configuration register | 16-15 | 0x4140_0050 | BBCFG4 | MSL Channel 4 Configuration register | 16-15 | 0x4140_0054 | BBCFG5 | MSL Channel 5 Configuration register | 16-15 | 0x4140_0058 | BBCFG6 | MSL Channel 6 Configuration register | 16-15 | 0x4140_005C | BBCFG7 | MSL Channel 7 Configuration register | 16-15 | 0x4140_0084 | BBSTAT1 | MSL Channel 1 Status register | 16-19 | 0x4140_0088 | BBSTAT2 | MSL Channel 2 Status register | 16-19 | 0x4140_008C | BBSTAT3 | MSL Channel 3 Status register | 16-19 | 0x4140_0090 | BBSTAT4 | MSL Channel 4 Status register | 16-19 | 0x4140_0094 | BBSTAT5 | MSL Channel 5 Status register | 16-19 | 0x4140_0098 | BBSTAT6 | MSL Channel 6 Status register | 16-19 | 0x4140_009C | BBSTAT7 | MSL Channel 7 Status register | 16-19 | 0x4140_00C4 | BBEOM1 | MSL Channel 1 EOM register | 16-22 | 0x4140_00C8 | BBEOM2 | MSL Channel 2 EOM register | 16-22 | 0x4140_00CC | BBEOM3 | MSL Channel 3 EOM register | 16-22 | 0x4140_00D0 | BBEOM4 | MSL Channel 4 EOM register | 16-22 | 0x4140_00D4 | BBEOM5 | MSL Channel 5 EOM register | 16-22 | 0x4140_00D8 | BBEOM6 | MSL Channel 6 EOM register | 16-22 | 0x4140_00DC | BBEOM7 | MSL Channel 7 EOM register | 16-22 | 0x4140_0108 | BBIID | MSL Interrupt ID register | 16-23 | 0x4140_0110 | BBFREQ | MSL Transmit Frequency Select register | 10-6 | 0x4140_0114 | BBWAIT | MSL Wait Count register | 16-24 | 0x4140_0118 | BBCST | MSL Clock Stop Time register | 16-25 | 0x4140_0140 | BBWAKE | MSL Wake-Up register | 16-26 | 0x4140_0144 | BBITFC | MSL Interface Width register | 10-6 Keypad Interface | 0x4150_0000 | KPC | Keypad Interface Control register | 18-12 | 0x4150_0008 | KPDK | Keypad Interface Direct Key register | 18-16 | 0x4150_0010 | KPREC | Keypad Interface Rotary Encoder Count register | 18-17 | 0x4150_0018 | KPMK | Keypad Interface Matrix Key register | 18-18 | 0x4150_0020 | KPAS | Keypad Interface Automatic Scan register | 18-18 | 0x4150_0028 | KPASMKP0 | Keypad Interface Automatic Scan Multiple Keypress register 0 | 18-20 | 0x4150_0030 | KPASMKP1 | Keypad Interface Automatic Scan Multiple Keypress register 1 | 18-20 | 0x4150_0038 | KPASMKP2 | Keypad Interface Automatic Scan Multiple Keypress register 2 | 18-20 | 0x4150_0040 | KPASMKP3 | Keypad Interface Automatic Scan Multiple Keypress register 3 | 18-20 | 0x4150_0048 | KPKDI | Keypad Interface Key Debounce Interval register | 18-23 Universal Subscriber ID (USIM) Interface | 0x4160_0000 | RBR | USIM Receive Buffer register | 19-18 | 0x4160_0004 | THR | USIM Transmit Holding register | 19-19 | 0x4160_0008 | IER | USIM Interrupt Enable register | 19-20 | 0x4160_000C | IIR | USIM Interrupt Identification register | 19-22 | 0x4160_0010 | FCR | USIM FIFO Control register | 19-24 | 0x4160_0014 | FSR | USIM FIFO Status register | 19-26 | 0x4160_0018 | ECR | USIM Error Control register | 19-27 | 0x4160_001C | LCR | USIM Line Control register | 19-29 | 0x4160_0020 | USCCR | USIM Card Control register | 19-31 | 0x4160_0024 | LSR | USIM Line Status register | 19-32 | 0x4160_0028 | EGTR | USIM Extra Guard Time register | 19-34 | 0x4160_002C | BGTR | USIM Block Guard Time register | 19-34 | 0x4160_0030 | TOR | USIM Time-Out register | 19-35 | 0x4160_0034 | CLKR | USIM Clock register | 19-36 | 0x4160_0038 | DLR | USIM Divisor Latch register | 19-37 | 0x4160_003C | FLR | USIM Factor Latch register | 19-37 | 0x4160_0040 | CWTR | USIM Character Waiting Time register | 19-38 | 0x4160_0044 | BWTR | USIM Block Waiting Time register | 19-39 Synchronous Serial Port 2 | 0x4170_0000 | SSCR0_2 | SSP2 Control register 0 | 8-25 | 0x4170_0004 | SSCR1_2 | SSP 2 Control register 1 | 8-30 | 0x4170_0008 | SSSR_2 | SSP 2 Status register | 8-43 | 0x4170_000C | SSITR_2 | SSP 2 Interrupt Test register | 8-42 | 0x4170_0010 | SSDR_2 | SSP 2 Data Write register/Data Read register | 8-48 | 0x4170_0028 | SSTO_2 | SSP 2 Time-Out register | 8-41 | 0x4170_002C | SSPSP_2 | SSP 2 Programmable Serial Protocol | 8-39 | 0x4170_0030 | SSTSA_2 | SSP2 TX Timeslot Active register | 8-48 | 0x4170_0034 | SSRSA_2 | SSP2 RX Timeslot Active register | 8-49 | 0x4170_0038 | SSTSS_2 | SSP2 Timeslot Status register | 8-50 | 0x4170_003C | SSACD_2 | SSP2 Audio Clock Divider register | 8-51 Memory Stick Host Controller | 0x4180_0000 | MSCMR | MSHC Command register | 17-8 | 0x4180_0004 | MSCRSR | MSHC Control and Status register | 17-9 | 0x4180_0008 | MSINT | MSHC Interrupt and Status register | 17-10 | 0x4180_000C | MSINTEN | MSHC Interrupt Enable register | 17-11 | 0x4180_0010 | MSCR2 | MSHC Control register 2 | 17-12 | 0x4180_0014 | MSACD | MSHC ACD Command register | 17-13 | 0x4180_0018 | MSRXFIFO | MSHC Receive FIFO register | 17-14 | 0x4180_001C | MSTXFIFO | MSHC Transmit FIFO register | 17-15 Synchronous Serial Port 3 | 0x4190_0000 | SSCR0_3 | SSP 3 Control register 0 | 8-25 | 0x4190_0004 | SSCR1_3 | SSP 3 Control register 1 | 8-30 | 0x4190_0008 | SSSR_3 | SSP 3 Status register | 8-43 | 0x4190_000C | SSITR_3 | SSP 3 Interrupt Test register | 8-42 | 0x4190_0010 | SSDR_3 | SSP 3 Data Write register/Data Read register | 8-48 | 0x4190_0028 | SSTO_3 | SSP 3 Time-Out register | 8-41 | 0x4190_002C | SSPSP_3 | SSP 3 Programmable Serial Protocol | 8-39 | 0x4190_0030 | SSTSA_3 | SSP TX Timeslot Active register | 8-48 | 0x4190_0034 | SSRSA_3 | SSP RX Timeslot Active register | 8-49 | 0x4190_0038 | SSTSS_3 | SSP Timeslot Status register | 8-50 | 0x4190_003C | SSACD_3 | SSP Audio Clock Divider register | 8-51 */ } ================================================ FILE: Zelig/Zelig/RunTime/DeviceModels/ModelForPXA27x/HardwareModel/Drivers/GPIO.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // namespace Microsoft.DeviceModels.Chipset.PXA27x.Drivers { using System; using System.Runtime.CompilerServices; using Microsoft.Zelig.Runtime; /// /// Driver for the PXA271 GPIO subsystem. /// public abstract class GPIO { #region Constructor/Destructor /// /// protected constructor for the GPIO class. /// use the singleton to retrieve the GPIO driver instance. /// /// protected GPIO() { } /// /// Initializes the driver, connects interrupts, and enables the GPIO hardware /// in the PXA271. /// public void Initialize() { //reservation array for the ports available on the pxa271 m_reservation = new Port[120]; //#Ports on the PXA27x var intcHi = InterruptController.Instance; //wire dedicated pin 0 interrupt to our handler m_interrupt0 = InterruptController.Handler.Create( PXA27x.InterruptController.IRQ_INDEX_GPIO0, InterruptPriority.Normal, InterruptSettings.RisingEdge, this.ProcessGPIOInterruptX ); intcHi.RegisterAndEnable( m_interrupt0 ); //wire dedicated pin 1 interrupt to our handler m_interrupt1 = InterruptController.Handler.Create( PXA27x.InterruptController.IRQ_INDEX_GPIO1, InterruptPriority.Normal, InterruptSettings.RisingEdge, this.ProcessGPIOInterruptX ); intcHi.RegisterAndEnable( m_interrupt1 ); //wire pin 2-120 interrupt to our handler m_interruptX = InterruptController.Handler.Create( PXA27x.InterruptController.IRQ_INDEX_GPIOx, InterruptPriority.Normal, InterruptSettings.RisingEdge, this.ProcessGPIOInterruptX ); intcHi.RegisterAndEnable( this.m_interruptX ); //enable GPIO pins PowerManager.Instance.PSSR.RDH = true; } #endregion #region Public API #region port reservation management /// /// Reserves a port. /// /// /// If the hardware is already reserved by some other port, /// an ArgumentException will be thrown. /// /// The port to reserve. [MethodImpl(MethodImplOptions.Synchronized)] public void ReservePort( Port port ) { MustBeFree( port ); m_reservation[port.Id] = port; } /// /// Releases a port from the GPIO driver. /// /// The port to release [MethodImpl(MethodImplOptions.Synchronized)] public void ReleasePort( Port port ) { MustBeReserved( port ); m_reservation[port.Id] = null; } #endregion private void MustBeFree( Port port ) { if(port == null) { throw new ArgumentNullException( "port" ); } var port2 = m_reservation[port.Id]; if(port2 != null && port2 != port) { throw new ArgumentOutOfRangeException( "port" ); } } private void MustBeReserved( Port port ) { if(port == null) { throw new ArgumentNullException( "port" ); } if(m_reservation[port.Id] != port) { throw new ArgumentOutOfRangeException( "port" ); } } #region interrupt API /// /// Configures the interrupt associated with the port. /// /// /// The PXA271 supports edge interrupts only. /// /// The port for which to configure the interrupts /// if true, raising edges are detected as interrups and forwarded to the port. /// if true, falling edges are detected as interrups and forwarded to the port. public void ConfigureInterrupt( Port port , bool raisingEdge , bool fallingEdge ) { ReservePort( port ); var gpio = PXA27x.GPIO.Instance; gpio.ConfigureInterrupt( port.Id, raisingEdge, fallingEdge ); } #endregion #region configuration API /// /// Configures the given port to one of its #ernate functions. /// /// /// A port can either work as a standard GPIO port or run in one /// of several alternative configurations, depending on the pin. /// After configuring the port to the alternative function, standard GPIO /// operations should no longer be performed and result in unpredictable /// behavior of the GPIO pin. /// /// The port to configure. /// The alternate function to assign to this port. public void EnableAsInputAlternateFunction( Port port , int mode ) { ReservePort( port ); var gpio = PXA27x.GPIO.Instance; gpio.ConfigureInterrupt ( port.Id, false, false ); gpio.EnableAsInputAlternateFunction( port.Id, mode ); } /// /// Configures the given port to one of its primary function, i.e. as /// a GPIO input pin. /// /// The port to configure. public void EnableAsInputPin( Port port ) { ReservePort( port ); var gpio = PXA27x.GPIO.Instance; gpio.ConfigureInterrupt( port.Id, false, false ); gpio.EnableAsInputPin ( port.Id ); } /// /// Configures the given port to one of its alternate functions. /// /// /// A port can either work as a standard GPIO port or run in one /// of several alternative configurations, depending on the pin. /// After configuring the port to the alternative function, standard GPIO /// operations should no longer be performed and result in unpredictable /// behavior of the GPIO pin. /// /// The port to configure. /// The alternate function to assign to this port. public void EnableAsOutputAlternateFunction( Port port , int mode ) { ReservePort( port ); var gpio = PXA27x.GPIO.Instance; gpio.ConfigureInterrupt ( port.Id, false, false ); gpio.EnableAsOutputAlternateFunction( port.Id, mode , false ); } /// /// Configures the given port to one of its primary function, i.e. as /// a GPIO output pin. /// /// The port to configure. /// If true, the pin will signal High, If false, the pin will signal Low. public void EnableAsOutputPin( Port port , bool fSet ) { ReservePort( port ); var gpio = PXA27x.GPIO.Instance; gpio.ConfigureInterrupt( port.Id, false, false ); gpio.EnableAsOutputPin ( port.Id, fSet ); } /// /// Allows direct access to the current /// state of any port. /// /// The pin number to retrieve the current state for. /// The current state of the input pin. public bool this[int pin] { get { return PXA27x.GPIO.Instance[pin]; } set { PXA27x.GPIO.Instance[pin] = value; } } /// /// Allows direct access to the current /// state of any port. /// /// The port to retrieve the current state for. /// The current state of the input pin. public bool this[Port port] { get { return this[port.Id]; } set { this[port.Id] = value; } } #endregion #endregion #region Private API /// /// Port vector used to track active reservations /// and to wire up interrupt forwarding requests. /// private Port[] m_reservation; #region Private Interrupt dispatcher /// /// The epoch of all times reported by this module. /// The value 1.1.2004 has been chosen for compatibility reasons /// with the .Net Micro Framework. /// private static DateTime s_epoch = new DateTime( 2004, 1, 1, 0, 0, 0 ); /// /// Interrupt handler for GPIO interrupt for port 0. /// private InterruptController.Handler m_interrupt0; /// /// Interrupt handler for GPIO interrupt for port 1. /// private InterruptController.Handler m_interrupt1; /// /// Interrupt handler for GPIO interrupts /// for ports 2..120. /// private InterruptController.Handler m_interruptX; /// /// Handler for all GPIO interrupts (ports 0..120). /// /// /// Note: interrupts GPIO0, GPIO1, and GPIOx are all wired to this handler /// in . /// /// The handler that caused the interrupt. private void ProcessGPIOInterruptX( InterruptController.Handler handler ) { var gpioHandler = PXA27x.GPIO.Instance; //the timespan is for compatibility reasons //with the .Net Micro Framework TimeSpan when = TimeSpan.FromTicks((long)Drivers.RealTimeClock.Instance.CurrentTime); for (int i = 0; i < m_reservation.Length; i++) { if(Port.IsReservedPin( i ) == false) { if(gpioHandler.InterruptPending( i, true )) { Port ip = m_reservation[i]; if(ip != null) { ip.m_interrupts.EnqueueNonblocking(when); //ip.FireInterrupt( when ); } } } } } #endregion #endregion #region Singleton #if TESTMODE_DESKTOP private static GPIO s_instance; public static GPIO Instance { get { if (null != s_instance) return s_instance; s_instance = new GPIO(); s_instance.Initialize(); return s_instance; } } #else /// /// Singleton for the GPIO driver. /// extern public static GPIO Instance { [MethodImpl(MethodImplOptions.InternalCall)] [SingletonFactory] get; } #endif #endregion #region Nested classes /// /// Base class for the Port resources managed by the GPIO driver. /// public class Port : IDisposable { // // State // private readonly int m_pin; #region Constructor/Destructor /// /// Initializes a Port managed by the GPIO driver. /// /// The port identifier. /// Starts an interrupt thread for this port, if true. public Port( int pin, bool isInterrupt ) { if(IsReservedPin( pin )) { throw new ArgumentOutOfRangeException( "pin" ); } m_pin = pin; if (isInterrupt) { m_interrupts = new KernelCircularBuffer(8); m_interruptThread = new System.Threading.Thread(DispatchInterrupts); m_interruptThread.Priority = System.Threading.ThreadPriority.Highest; m_interruptThread.Start(); } } ~Port() { Dispose(false); } /// /// Releases resources associtated with this /// pin. /// public void Dispose() { Dispose(true); } /// /// Releases any custom resource associated /// with this pin. /// /// If true, called from Dispose() protected virtual void Dispose(bool disposing) { if (m_interruptThread != null && m_interruptThread.IsAlive) { try { m_interruptThread.Abort(); } catch { } } m_interruptThread = null; GC.SuppressFinalize(this); } /// /// Allows callers to modify the priority of the interrupt /// thread associated with this pin. /// protected System.Threading.ThreadPriority InterruptPriority { get { if (null == m_interruptThread) throw new NotSupportedException(); return m_interruptThread.Priority; } set { if (null == m_interruptThread) throw new NotSupportedException(); m_interruptThread.Priority = value; } } /// /// Validates if the given pin is not Reserved /// /// The pin to check. [Inline] internal static bool IsReservedPin( int pin ) { if(pin < 0 || pin >= 120) { return true; } switch(pin) { case 2: case 5: case 6: case 7: case 8: return true; } return false; } #endregion #region Public API /// /// Gets the indentifier (ID) for a port. /// /// /// The ID for the port. /// public int Id { get { return m_pin; } } #endregion #region Internal API private System.Threading.Thread m_interruptThread; internal KernelCircularBuffer m_interrupts; private void DispatchInterrupts() { while (true) { TimeSpan ts = m_interrupts.DequeueBlocking(); FireInterrupt(ts); } } /// /// Called by the hardware when an interrupt for the /// port has been detected. /// /// The time when the interrupt occured. public virtual void FireInterrupt( TimeSpan whenOccurred ) { } #endregion } #endregion } } ================================================ FILE: Zelig/Zelig/RunTime/DeviceModels/ModelForPXA27x/HardwareModel/Drivers/I2C.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // namespace Microsoft.DeviceModels.Chipset.PXA27x.Drivers { using System; using System.Threading; using System.Runtime.CompilerServices; using Microsoft.Zelig.Runtime; /// /// I2C device driver for the PXA271 I2C hardware. /// public abstract class I2C { #region Constructor/Destructor /// /// The current transaction in progress. /// private I2CBus_Transaction m_currentTransaction; /// /// The current sub transaction of the /// in progress. /// private I2CBus_TransactionUnit m_currentTransactionUnit; private const byte c_DirectionWrite = 0x00; private const byte c_DirectionRead = 0x01; /// /// The serial data line (SDA) of the I2C port. /// private GPIO.Port m_sdaPort; /// /// The serial clock line (SCL) of the I2C port. /// private GPIO.Port m_sclPort; /// /// Initialized the I2C driver. /// /// /// This function configures the slave mode address /// of the I2C device to 0x01, i.e., clients are not /// able to talk to devices configured for this address. /// public void Initialize() { //no active action m_currentTransaction = null; m_currentTransactionUnit = null; //configure SCL m_sclPort = new GPIO.Port(PXA27x.I2C.PIN_I2C_SCL, false); GPIO.Instance.EnableAsInputAlternateFunction(m_sclPort, 1); //configure SDA m_sdaPort = new GPIO.Port(PXA27x.I2C.PIN_I2C_SDA, false); GPIO.Instance.EnableAsInputAlternateFunction(m_sdaPort, 1); //configure the priority of the interrupt source in the //InterruptController Hardware //note: this is not the driver used to register // the interrupt handler with! PXA27x.InterruptController.Instance.SetPriority(PXA27x.InterruptController.IRQ_INDEX_I2C, 0); //enable and register interrupt for the I2C controller m_i2cInterruptHandler = InterruptController.Handler.Create(PXA27x.InterruptController.IRQ_INDEX_I2C, InterruptPriority.Normal, InterruptSettings.RisingEdge /*| InterruptSettings.Fast*/, new InterruptController.Callback(this.ProcessI2CInterrupt)); InterruptController.Instance.RegisterAndEnable(m_i2cInterruptHandler); //enable clock to I2C unit //note: no access to the I2C registers // before setting this bit ClockManager.Instance.CKEN.EnI2C = true; //setup our slave address - only used for slave mode PXA27x.I2C.Instance.ISAR = 0x1; //our default address } #endregion #region Public API /// /// Executes a transaction on the I2C bus. /// /// The action to execute on /// the I2C bus. public void StartTransactionAsMaster(I2CBus_Transaction transaction) { if (null == transaction) throw new ArgumentNullException("transaction"); //reset the state of this transaction transaction.ResetTransaction(); //setup current action and action unit //fail if there is a transaction going on at the moment if (null != Interlocked.CompareExchange(ref this.m_currentTransaction, transaction, null)) throw new InvalidOperationException("m_currentTransaction != null"); //get the first transaction unit m_currentTransactionUnit = transaction.Pop(); //setup default control field for new transfer PXA27x.I2C.ICR_Bitfield control = new PXA27x.I2C.ICR_Bitfield { //configure interrupts DRFIE = true, //enable Data Buffer Register (IDBR) receive interrupt ITEIE = true, //enable IDBR transit empty interrupt BEIE = true, //enable Bus error interrupt GCD = true, //disable General call //setup unit as master IUE = true, //enable I2C unit SCLE = true, //enable driving the SCL line //send first byte indication START = true, //send start condition TB = true, //Transfer Byte }; //setup I2C address uint address = (uint)(0xFE & (transaction.Address << 1)); //setup the direction bit address |= m_currentTransactionUnit.IsReadTransaction() ? I2C.c_DirectionRead : I2C.c_DirectionWrite; //the peer address is the first byte to send PXA27x.I2C.Instance.IDBR = address; //Use high bit rate if requested control.FM = (transaction.ClockRate >= 400); //Initiate the send operation PXA27x.I2C.Instance.ICR = control; } #endregion #region Private API /// /// The handler for all interrupts generated by the I2C device. /// private InterruptController.Handler m_i2cInterruptHandler; /// /// Ends any active transaction started as /// a I2C master device. /// public void StopTransactionAsMaster() { //unset all flags that depend on the transaction flow PXA27x.I2C.Instance.ICR.MA = true; //signal master abort command m_currentTransaction = null; m_currentTransactionUnit = null; } /// /// Processes interrupts generated by the I2C /// device. /// /// The handler that was registered with the /// interrupt controller for the interrupt. private void ProcessI2CInterrupt(InterruptController.Handler handler) { //read control and status PXA27x.I2C.ISR_Bitfield status = PXA27x.I2C.Instance.ISR; if (status.ITE) //If Transmit Buffer Empty interrupt { OnTransmitBufferEmpty(); } else if (status.IRF) //If Receive Buffer Full interrupt { OnReceiveBufferFull(); } else if (status.BED || status.ALD) //If there was a bus error or arbitration lost indication { //save the data in case we call "StopTransactionAsMaster" later on //which will clear the variable I2CBus_Transaction transaction = m_currentTransaction; //Shut down I2C interrupts, stop driving bus PXA27x.I2C.Instance.ICR.IUE = false; StopTransactionAsMaster(); //Problem talking to slave - we're done transaction.Signal(I2CBus_Transaction.CompletionStatus.Aborted); } } /// /// Called from the interrupt handler when the data register /// is full and data needs to be saved locally for later processing. /// private void OnReceiveBufferFull() { PXA27x.I2C i2c = PXA27x.I2C.Instance; //save the data in case we call "StopTransactionAsMaster" later on //which will clear the variables I2CBus_Transaction transaction = m_currentTransaction; I2CBus_TransactionUnit transactionUnit = m_currentTransactionUnit; //clear interrupt flag i2c.ISR.IRF = true; //Read receive buffer data if (!transactionUnit.IsTransferComplete) { byte data = (byte)i2c.IDBR; transactionUnit.Push(data); } //If last byte was just received if (transactionUnit.IsTransferComplete) { //Tidy up the control register i2c.ICR.STOP = i2c.ICR.ACKNAK = false; //Finish up the transaction if (!transaction.IsProcessingLastUnit) { //If more to transaction StartTransactionAsMaster(transaction /*, true */); } else { StopTransactionAsMaster(); //signal the succesfull complection transaction.Signal(I2CBus_Transaction.CompletionStatus.Completed); //Shut down I2C master i2c.ICR.IUE = false; } } else if (transactionUnit.IsLastByte) //If exactly 1 byte left to receive { PXA27x.I2C.ICR_Bitfield ctrl = i2c.ICR; //Initiate next byte read from slave ctrl.START = false; ctrl.STOP = ctrl.ALDIE = ctrl.ACKNAK = ctrl.TB = true; i2c.ICR = ctrl; } else //If more than one byte left to receive { PXA27x.I2C.ICR_Bitfield ctrl = i2c.ICR; //Initiate next byte read from slave ctrl.START = ctrl.STOP = ctrl.ACKNAK = false; ctrl.ALDIE = ctrl.TB = true; i2c.ICR = ctrl; } } /// /// Called from the interrupt handler when the data register /// is empty and new data needs to be send to the client device. /// private void OnTransmitBufferEmpty() { //save status and configuration PXA27x.I2C i2c = PXA27x.I2C.Instance; PXA27x.I2C.ISR_Bitfield status = i2c.ISR; PXA27x.I2C.ICR_Bitfield ctrl = i2c.ICR; //save the data in case we call "StopTransactionAsMaster" later on //which will clear the variables I2CBus_Transaction transaction = m_currentTransaction; I2CBus_TransactionUnit transactionUnit = m_currentTransactionUnit; //clear transmit empty indication flag //(writing "true" will clear the flag) i2c.ISR.ITE = true;// PXA27x.I2C.I2C.ISR__ITE; //If arbitration loss detected, clear that, too //(writing "true" will clear the flag) if (status.ALD) { i2c.ISR.ALD = true;// = PXA27x.I2C.I2C.ISR__ALD; } //If we just finished sending an address in Read mode if (status.RWM) { //If we are expecting only one byte if (transactionUnit.IsLastByte) { //Must send stop and NAK after receiving last byte ctrl.START = false; //Initiate read from slave ctrl.STOP = ctrl.ALDIE = ctrl.ACKNAK = ctrl.TB = true; } else //If we are expecting more than one byte { //Do not send a stop and ACK the next received byte ctrl.START = ctrl.STOP = ctrl.ACKNAK = false; //Initiate read from slave ctrl.ALDIE = ctrl.TB = true; } //Initiate the read operation i2c.ICR = ctrl; } else //If we have just finished sending address or data in Write mode { //if the data transfer is complete if (transactionUnit.IsTransferComplete) { //Clear the stop bit i2c.ICR.STOP = false; if (transaction.IsProcessingLastUnit) { StopTransactionAsMaster(); //signal the succesfull complection transaction.Signal(I2CBus_Transaction.CompletionStatus.Completed); //Shut down I2C port master i2c.ICR.IUE = false; } else { StartTransactionAsMaster(transaction /*, true */ ); } } else if (status.BED) //if there has been a bus error detected { //Clear the bus error i2c.ISR.BED = true; //and abort the transaction StopTransactionAsMaster(); //signal the abortion transaction.Signal(I2CBus_Transaction.CompletionStatus.Aborted); //Shut down I2C master i2c.ICR.IUE = false; } else //in the middle of the send operation { //If sending the last byte we must signal //the stop condition after the byte was sent if (transactionUnit.IsLastByte) { ctrl.START = false; ctrl.STOP = true; } else { ctrl.START = false; ctrl.STOP = false; } //Set up start/stop and arbitration loss detect //after the operation has started ctrl.ALDIE = true; i2c.ICR = ctrl; //Set up next byte to transmit //Get data ready to send and put it //into the send register i2c.IDBR = transactionUnit.Pop(); //Initiate the transmission i2c.ICR.TB = true; } } } #endregion #region Singleton API #if TESTMODE_DESKTOP private static I2C s_instance; /// /// Retrieves the I2C driver singleton. /// public static I2C Instance { get { if (null != s_instance) return s_instance; s_instance = new I2C(); s_instance.Initialize(); return s_instance; } } #else /// /// Retrieves the I2C driver singleton. /// extern public static I2C Instance { [MethodImpl(MethodImplOptions.InternalCall)] [SingletonFactory] get; } #endif #endregion } /// /// Base class for an I2C Transaction. /// public class I2CBus_TransactionUnit { #region Constructor/Destructor /// /// Initializes an I2C transaction /// /// True, if the data is read from the device. False if /// data it to be written to the device. /// The buffer to fill from (when reading) the device /// or transfer to (when writing) the device. protected I2CBus_TransactionUnit(bool isReadTransaction, byte[] buffer) { if (null == buffer) throw new ArgumentNullException("buffer"); this.Buffer = buffer; this.m_isReadTransactionUnit = isReadTransaction; //this.m_queueIndex = 0; } #endregion #region Public API /// /// The current index into the buffer /// used for Push/Pop operations. /// private int m_queueIndex; /// /// reset the internal state of this transaction /// internal void ResetTransactionUnit() { this.m_queueIndex = 0; } /// /// The buffer to fill from (when reading) the device /// or transfer to (when writing) the device. /// public readonly byte[] Buffer; #endregion #region Internal API /// /// Indicates the direction of the transaction /// private bool m_isReadTransactionUnit; /// /// Indicates the direction of the transaction /// /// /// If true, the transaction is a read transaction, i.e., /// data is read from the device and written to the buffer. /// If false, this is a write transaction, i.e., /// data is read from the buffer and written to the device. /// internal bool IsReadTransaction() { return m_isReadTransactionUnit; } /// /// Returns the next byte to send to the device /// and adjusts the internal pointer to the next byte. /// /// /// note: An exception will be raised if the transaction /// is not a write transaction. /// /// The next byte to send to the device. internal byte Pop() { if (m_isReadTransactionUnit) throw new ArgumentOutOfRangeException(); byte ret = this.Buffer[m_queueIndex]; m_queueIndex++; return ret; } /// /// Pushes the data read from the device to the internal /// buffer and adjusts the internal pointer to the next byte. /// /// /// note: An exception will be raised if the transaction /// is not a read transaction. /// /// The data read from the device to be /// pushed to the buffer. internal void Push(byte val) { if (!m_isReadTransactionUnit) throw new ArgumentOutOfRangeException("val"); this.Buffer[m_queueIndex] = val; m_queueIndex++; } /// /// Indicates if the transaction is complete, /// i.e. all data has been sent/received. /// internal bool IsTransferComplete { get { return m_queueIndex == this.Buffer.Length; } } /// /// Indicates if the last byte of the transaction /// is to be processed. /// /// /// note: the last byte is special in that the I2C /// bus requires special signalling for the /// last byte. /// internal bool IsLastByte { get { return m_queueIndex == this.Buffer.Length - 1; } } #endregion } /// /// Represents a comlex I2C transaction consisting /// of several elements. /// public class I2CBus_Transaction : IDisposable { #region Constructor/Destructor /// /// Initializes a complex transaction from a set of user transactions for /// a given peer address and clock rate. /// /// The address of the peer to talk to. /// The clock rate (either 100 or 400khz) to use as transmission speed. /// The sequence of user transaction to run against the given peer. public I2CBus_Transaction(ushort address, int clockRate, I2CBus_TransactionUnit[] units) { m_completed = new ManualResetEvent(false); m_status = CompletionStatus.Aborted; m_address = address; m_clockRate = clockRate; m_transactionUnits = units; //m_bytesTransacted = 0; //m_current = 0; } #endregion #region Public API /// /// Waits for the transaction to complete for a specified amount of time. /// /// The maximum time to wait for the transaction to complete. /// True, if the transaction is complete, false, if the transaction is still /// running. /// note: having a transaction completed does not means that it was successfull. /// Look at to see how many bytes have been successfully /// transacted. /// public bool WaitForCompletion(int milliseconds) { return m_completed.WaitOne(milliseconds, false); } /// /// The number of bytes successfully sent/received. /// public int BytesTransacted { get { return m_bytesTransacted; } internal set { m_bytesTransacted = value; } } /// /// The address of the peer. /// public ushort Address { get { return m_address; } } /// /// The clockrate at which to talk to the client. /// public int ClockRate { get { return m_clockRate; } } /// /// If true, this is the last user transaction. /// public bool IsProcessingLastUnit { get { return (null == m_transactionUnits || m_current >= m_transactionUnits.Length); } } /// /// The completion status of this transaction. /// public CompletionStatus TransactionState { get { return m_status; } } #endregion /// /// resets the state of this transaction /// internal void ResetTransaction() { m_completed.Reset(); m_status = CompletionStatus.Aborted; m_bytesTransacted = 0; m_current = 0; foreach (I2CBus_TransactionUnit unit in m_transactionUnits) { unit.ResetTransactionUnit(); } } #region Internal API private ManualResetEvent m_completed; private I2CBus_TransactionUnit[] m_transactionUnits; private int m_bytesTransacted; private ushort m_address; private int m_clockRate; private CompletionStatus m_status; private int m_current; /// /// Pops the next user transaction from the transaction queue /// and adjusts the internal pointer to the next transaction. /// /// The next user transaction to execute. internal I2CBus_TransactionUnit Pop() { if (m_current > 0) BytesTransacted += m_transactionUnits[m_current - 1].Buffer.Length; return m_transactionUnits[m_current++]; } /// /// Signal handler called by the I2C state machine to signal the end of the transactions. /// /// The result status of the user transactions. internal void Signal(CompletionStatus status) { if (status == CompletionStatus.Completed) { m_bytesTransacted = 0; for (int i = 0; i < m_transactionUnits.Length; i++) { m_bytesTransacted += m_transactionUnits[i].Buffer.Length; } } m_status = status; m_completed.Set(); } #endregion #region Nested data types /// /// The completion status of the entire /// transaction. /// public enum CompletionStatus { /// /// The transaction was aborted at /// some point. Some of the user transactions /// have possibly been completed, some possibly not. /// Aborted, /// /// All user transaction that were part of the combined /// transaction completed successfully. /// Completed }; #endregion #region IDisposable Members /// /// Disposes all resources held by the Transaction /// public void Dispose() { Dispose(true); GC.SuppressFinalize(this); } /// /// Disposes all resources held by the Transaction /// /// True, if called through Dispose(). False otherwise. protected virtual void Dispose(bool fDisposing) { if (m_completed != null) m_completed.Close(); m_completed = null; } #endregion } } ================================================ FILE: Zelig/Zelig/RunTime/DeviceModels/ModelForPXA27x/HardwareModel/Drivers/InterruptController.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // namespace Microsoft.DeviceModels.Chipset.PXA27x.Drivers { using System; using System.Runtime.CompilerServices; using RT = Microsoft.Zelig.Runtime; [Flags] public enum InterruptSettings { Normal = 0x00000000, Fast = 0x00000001, LevelSensitive = 0x00000000, EdgeSensitive = 0x00000002, ActiveLowOrFalling = 0x00000000, ActiveHighOrRising = 0x00000004, ActiveLow = LevelSensitive | ActiveLowOrFalling, ActiveHigh = LevelSensitive | ActiveHighOrRising, FallingEdge = EdgeSensitive | ActiveLowOrFalling, RisingEdge = EdgeSensitive | ActiveHighOrRising, } public enum InterruptPriority { Lowest = 0, BelowNormal = 1, Normal = 2, AboveNormal = 3, Highest = 4, } public abstract class InterruptController { public delegate void Callback( Handler handler ); public class Handler { // // State // private readonly int m_index; private readonly int m_section; internal readonly InterruptPriority m_priority; private readonly InterruptSettings m_settings; private readonly Callback m_callback; internal readonly RT.KernelNode< Handler > m_node; // // Constructor Methods // private Handler( int index , InterruptPriority priority , InterruptSettings settings , Callback callback ) { m_index = index % 32; m_section = index / 32; m_priority = priority; m_settings = settings; m_callback = callback; m_node = new RT.KernelNode< Handler >( this ); } // // Helper Methods // public static Handler Create( int index , InterruptPriority priority , InterruptSettings settings , Callback callback ) { return new Handler( index, priority, settings, callback ); } public void Enable() { PXA27x.InterruptController ctrl = PXA27x.InterruptController.Instance; uint mask = this.Mask; if(m_section == 0) { ctrl.ICMR &= ~mask; if(this.IsFastHandler) { ctrl.ICLR |= mask; } else { ctrl.ICLR &= ~mask; } ctrl.ICMR |= mask; } else { ctrl.ICMR2 &= ~mask; if(this.IsFastHandler) { ctrl.ICLR2 |= mask; } else { ctrl.ICLR2 &= ~mask; } ctrl.ICMR2 |= mask; } } public void Disable() { PXA27x.InterruptController ctrl = PXA27x.InterruptController.Instance; uint mask = this.Mask; if(m_section == 0) { ctrl.ICMR &= ~mask; } else { ctrl.ICMR2 &= ~mask; } } public void Invoke() { m_callback( this ); } // // Access Methods // public uint Mask { [RT.Inline] get { return 1U << m_index; } } public int Index { get { return m_index; } } public int Section { get { return m_section; } } public bool IsFastHandler { [RT.Inline] get { return (m_settings & InterruptSettings.Fast) != 0; } } public bool IsEdgeSensitive { [RT.Inline] get { return (m_settings & InterruptSettings.EdgeSensitive) != 0;; } } public bool IsActiveHighOrRising { [RT.Inline] get { return (m_settings & InterruptSettings.ActiveHighOrRising) != 0;; } } } // // State // private RT.KernelList< Handler > m_handlers; private RT.Peripherals.Continuation m_softCallback; // // Helper Methods // public void Initialize() { m_handlers = new RT.KernelList< Handler >(); PXA27x.InterruptController ctrl = PXA27x.InterruptController.Instance; ctrl.ICMR = 0; ctrl.ICMR2 = 0; ctrl.ICCR = new PXA27x.InterruptController.ICCR_bitfield { DIM = true }; } //--// public void RegisterAndEnable( Handler hnd ) { Register( hnd ); hnd.Enable(); } public void Register( Handler hnd ) { RT.BugCheck.AssertInterruptsOff(); var ctrl = PXA27x.InterruptController.Instance; var newPriority = hnd.m_priority; int priorityIdx = 0; // // Insert the handler in priority order and rebuild the Interrupt Priority Registers table. // for(RT.KernelNode< Handler > node = m_handlers.StartOfForwardWalk; ; node = node.Next) { if(hnd != null) { if(node.IsValidForForwardMove == false || node.Target.m_priority < newPriority) { var newNode = hnd.m_node; newNode.InsertBefore( node ); node = newNode; hnd = null; } } if(node.IsValidForForwardMove == false) { break; } ctrl.SetPriority( (uint)node.Target.Index, priorityIdx++ ); } } //--// public void DeregisterAndDisable( Handler hnd ) { RT.BugCheck.AssertInterruptsOff(); hnd.Disable(); Deregister( hnd ); } public void Deregister( Handler hnd ) { RT.BugCheck.AssertInterruptsOff(); hnd.m_node.RemoveFromList(); } //--// public void ProcessInterrupt() { ProcessInterrupt( false ); } //// [RT.MemoryRequirements( RT.MemoryAttributes.Unpaged )] public void ProcessFastInterrupt() { ProcessInterrupt( true ); } public void ProcessInterrupt( bool fFastOnly ) { PXA27x.InterruptController ctrl = PXA27x.InterruptController.Instance; while(true) { var ichp = ctrl.ICHP; uint vector; if(fFastOnly) { if(ichp.VAL_FIQ == false) { break; } vector = ichp.FIQ; } else { if(ichp.VAL_IRQ == false) { break; } vector = ichp.IRQ; } uint index = vector % 32; uint section = vector / 32; RT.KernelNode< Handler > node = m_handlers.StartOfForwardWalk; while(true) { if(node.IsValidForForwardMove == false) { // // BUGBUG: Unhandled interrupts. We should crash. For now we just disable them. // uint mask = 1U << (int)index; if(section == 0) { ctrl.ICMR &= ~mask; } else { ctrl.ICMR2 &= ~mask; } break; } Handler hnd = node.Target; if(hnd.Section == section) { if(hnd.Index == index && hnd.Section == section) { hnd.Invoke(); break; } } node = node.Next; } } } public void CauseInterrupt() { RealTimeClock.Instance.CauseInterrupt(); } public void ContinueUnderNormalInterrupt( RT.Peripherals.Continuation dlg ) { m_softCallback = dlg; CauseInterrupt(); } internal void ProcessSoftInterrupt() { RT.Peripherals.Continuation dlg = System.Threading.Interlocked.Exchange( ref m_softCallback, null ); if(dlg != null) { dlg(); } } // // Access Methods // public static extern InterruptController Instance { [RT.SingletonFactory()] [MethodImpl( MethodImplOptions.InternalCall )] get; } } } ================================================ FILE: Zelig/Zelig/RunTime/DeviceModels/ModelForPXA27x/HardwareModel/Drivers/RealTimeClock.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // namespace Microsoft.DeviceModels.Chipset.PXA27x.Drivers { using System; using System.Runtime.CompilerServices; using RT = Microsoft.Zelig.Runtime; public abstract class RealTimeClock { public delegate void Callback( Timer timer, ulong currentTime ); public class Timer { // // State // private RealTimeClock m_owner; private RT.KernelNode< Timer > m_node; private ulong m_timeout; private Callback m_callback; // // Constructor Methods // internal Timer( RealTimeClock owner , Callback callback ) { m_owner = owner; m_node = new RT.KernelNode< Timer >( this ); m_callback = callback; } // // Helper Methods // public void Cancel() { m_owner.Deregister( this ); } internal void Invoke( ulong currentTime ) { m_callback( this, currentTime ); } // // Access Methods // internal RT.KernelNode< Timer > Node { get { return m_node; } } public ulong Timeout { get { return m_timeout; } set { m_timeout = value; m_owner.Register( this ); } } public ulong RelativeTimeout { get { return m_timeout - RealTimeClock.Instance.CurrentTime; } set { m_timeout = value + RealTimeClock.Instance.CurrentTime; m_owner.Register( this ); } } } // // State // const uint c_QuarterCycle = 0x40000000u; const uint c_OverflowFlag = 0x80000000u; readonly OSTimers.OMCR_bitfield c_Timer1Ctrl = new OSTimers.OMCR_bitfield { P = true , // Keep the counter running after a match. C = false, // Channel 5 match against Channel 4 counter. CRES = OSTimers.OMCR_bitfield.Resolution.Freq1MHz, }; readonly OSTimers.OMCR_bitfield c_Timer2Ctrl = new OSTimers.OMCR_bitfield { P = true, // Keep the counter running after a match. C = true, // Channel 4 matches against its counter. CRES = OSTimers.OMCR_bitfield.Resolution.Freq1MHz, }; private uint m_lastCount; private uint m_highPart; private InterruptController.Handler m_interrupt; private InterruptController.Handler m_simulatedSoftInterrupt; private RT.KernelList< Timer > m_timers; // // Helper Methods // public void Initialize() { m_timers = new RT.KernelList< Timer >(); m_interrupt = InterruptController.Handler.Create( PXA27x.InterruptController.IRQ_INDEX_OS_TIMER , InterruptPriority.Normal, InterruptSettings.ActiveHigh, ProcessTimeout ); m_simulatedSoftInterrupt = InterruptController.Handler.Create( PXA27x.InterruptController.IRQ_INDEX_OS_TIMER0, InterruptPriority.Lowest, InterruptSettings.ActiveHigh, ProcessSoftInterrupt ); //--// var clockControl = PXA27x.ClockManager.Instance; clockControl.CKEN.EnOsTimer = true; //--// var timer = PXA27x.OSTimers.Instance; timer.OIER = 0; //--// // // We use Timer0 as a soft interrupt, so we have to wait until it has fired and NEVER reset the match value. // timer.EnableInterrupt( 0 ); timer.WriteCounter( 0, 0 ); timer.SetMatch ( 0, 100 ); while(timer.HasFired( 0 ) == false) { } //--// timer.SetControl( 5, c_Timer1Ctrl ); timer.SetControl( 4, c_Timer2Ctrl ); // // Start the timer. // timer.WriteCounter( 4, 0 ); timer.EnableInterrupt( 4 ); timer.EnableInterrupt( 5 ); //--// var intc = InterruptController.Instance; intc.RegisterAndEnable( m_interrupt ); intc.Register ( m_simulatedSoftInterrupt ); Refresh(); } public Timer CreateTimer( Callback callback ) { return new Timer( this, callback ); } //--// private void Register( Timer timer ) { RT.KernelNode< Timer > node = timer.Node; node.RemoveFromList(); ulong timeout = timer.Timeout; RT.KernelNode< Timer > node2 = m_timers.StartOfForwardWalk; while(node2.IsValidForForwardMove) { if(node2.Target.Timeout > timeout) { break; } node2 = node2.Next; } node.InsertBefore( node2 ); Refresh(); } private void Deregister( Timer timer ) { var node = timer.Node; if(node.IsLinked) { node.RemoveFromList(); Refresh(); } } //--// private void ProcessTimeout( InterruptController.Handler handler ) { ulong currentTime = this.CurrentTime; while(true) { RT.KernelNode< Timer > node = m_timers.StartOfForwardWalk; if(node.IsValidForForwardMove == false) { break; } if(node.Target.Timeout > currentTime) { break; } node.RemoveFromList(); node.Target.Invoke( currentTime ); } Refresh(); } internal void CauseInterrupt() { var timer = PXA27x.OSTimers.Instance; timer.SetMatch(0, timer.ReadCounter(0) + 8); m_simulatedSoftInterrupt.Enable(); } private void ProcessSoftInterrupt( InterruptController.Handler handler ) { m_simulatedSoftInterrupt.Disable(); InterruptController.Instance.ProcessSoftInterrupt(); } void Refresh() { Timer target = m_timers.FirstTarget(); ulong timeout; if(target != null) { timeout = target.Timeout; } else { timeout = ulong.MaxValue; } //--// ulong now = this.CurrentTime; // // Timeout in the past? Trigger the match now. // if(now > timeout) { timeout = now; } // // Timeout too far in the future? Generate match closer in time, so we handle wrap arounds. // ulong nowPlusQuarterCycle = now + c_QuarterCycle; if(nowPlusQuarterCycle < timeout) { timeout = nowPlusQuarterCycle; } uint timeoutLow = (uint)timeout; var timer = PXA27x.OSTimers.Instance; // disable second interrupt so we don't handle this timeout twice timer.DisableInterrupt( 5 ); // // Clear previous interrupts. // timer.ClearFired( 4 ); timer.ClearFired( 5 ); // // Create two matches, to protect against race conditions (at least one will fire). // timer.SetMatch( 4, timeoutLow ); timer.SetMatch( 5, timeoutLow + 10 ); timer.EnableInterrupt( 5 ); } // // Access Methods // public static extern RealTimeClock Instance { [RT.SingletonFactory()] [MethodImpl( MethodImplOptions.InternalCall )] get; } public uint CurrentTimeRaw { get { return PXA27x.OSTimers.Instance.ReadCounter( 4 ); } } public ulong CurrentTime { get { using(RT.SmartHandles.InterruptState.Disable()) { uint value = PXA27x.OSTimers.Instance.ReadCounter( 4 ); uint highPart = m_highPart; // // Wrap around? Update high part. // if(((value ^ m_lastCount) & c_OverflowFlag) != 0) { highPart++; m_lastCount = value; m_highPart = highPart; } return (ulong)highPart << 32 | value; } } } } } ================================================ FILE: Zelig/Zelig/RunTime/DeviceModels/ModelForPXA27x/HardwareModel/Drivers/SPI.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // namespace Microsoft.DeviceModels.Chipset.PXA27x.Drivers { using System; using System.Runtime.CompilerServices; using System.Threading; using Microsoft.Zelig.Runtime; #region SPI bus and device descriptors /// /// Describes a SPI bus /// public class SPI_Host { #region Constructor/Destructor /// /// One of the pre-defined SPI channels to which the device is connected. ///

/// If you're not using a pre-defined channel, be sure to /// override and /// for proper hardware initialization. ///

private uint m_spiChannelIndex; //SSP module INDEX (0 .. 2) /// /// Initializes a SPI HOST structure /// public SPI_Host() { } /// /// Initializes one of the pre-defined /// SPI HOST structures (0-2) /// /// The SPI channel to initialize. /// 0-1: standard. 2: the CC2024 SPI modul. internal SPI_Host(uint spiChannelIndex) { m_spiChannelIndex = spiChannelIndex; if (m_spiChannelIndex == 0) { RXD = new GPIO.Port(26, false); TXD = new GPIO.Port(25, false); CLK = new GPIO.Port(23, false); SSP = PXA27x.SSP.Instance.SSP1; return; } //configure SPI2 pins if (m_spiChannelIndex == 1) { RXD = new GPIO.Port(11, false); TXD = new GPIO.Port(38, false); CLK = new GPIO.Port(36, false); SSP = PXA27x.SSP.Instance.SSP2; return; }; //configure SPI3 pins (connected to the //CC2420 zigbee chip) if (m_spiChannelIndex == 2) { RXD = new GPIO.Port(41, false); TXD = new GPIO.Port(35, false); CLK = new GPIO.Port(34, false); SSP = PXA27x.SSP.Instance.SSP3; return; }; //not a known configuration throw new ArgumentOutOfRangeException("spiChannelIndex"); } #endregion #region Enable/Disable HW resources private bool m_clockEnabled; /// /// Enables/Disables the clock of the SPI device. /// public bool ClockEnabled { get { return m_clockEnabled; } set { if (value == m_clockEnabled) return; m_clockEnabled = value; OnEnableClock(m_clockEnabled); } } /// /// Called when the clock for the SPI is enabled /// or disabled. /// /// The requested state for the SPI clock. protected virtual void OnEnableClock(bool enabled) { if (enabled) { if (m_spiChannelIndex == 0) ClockManager.Instance.CKEN.EnSSP1 = true; else if (m_spiChannelIndex == 1) ClockManager.Instance.CKEN.EnSSP2 = true; else if (m_spiChannelIndex == 2) ClockManager.Instance.CKEN.EnSSP3 = true; else throw new ArgumentOutOfRangeException("enabled"); } else { if (m_spiChannelIndex == 0) ClockManager.Instance.CKEN.EnSSP1 = false; else if (m_spiChannelIndex == 1) ClockManager.Instance.CKEN.EnSSP2 = false; else if (m_spiChannelIndex == 2) ClockManager.Instance.CKEN.EnSSP3 = false; else throw new ArgumentOutOfRangeException("enabled"); } } private bool m_pinsEnabled; /// /// Enables/Disables the pins associated with the /// SPI device. /// public bool PinsEnabled { get { return m_pinsEnabled; } set { if (value == m_pinsEnabled) return; m_pinsEnabled = value; OnEnablePins(m_pinsEnabled); } } /// /// Called whenever the SPI bus pins are enabled/disabled. /// /// The requested state of the SPI bus pins. protected virtual void OnEnablePins(bool enabled) { if (enabled) { if (m_spiChannelIndex == 0) { //allow peripheral control of pins; GPIO.Instance.EnableAsOutputAlternateFunction(CLK, 2 /*GAFR__ALT_2*/); GPIO.Instance.EnableAsOutputAlternateFunction(TXD, 2 /*GAFR__ALT_2*/); GPIO.Instance.EnableAsInputAlternateFunction(RXD, 1 /*GAFR__ALT_1*/); } else if (m_spiChannelIndex == 1) { //allow peripheral control of pins; GPIO.Instance.EnableAsOutputAlternateFunction(CLK, 2 /*GAFR__ALT_2*/); GPIO.Instance.EnableAsOutputAlternateFunction(TXD, 2 /*GAFR__ALT_2*/); GPIO.Instance.EnableAsInputAlternateFunction(RXD, 2 /*GAFR__ALT_2*/); } else if (m_spiChannelIndex == 2) { //allow peripheral control of pins; GPIO.Instance.EnableAsOutputAlternateFunction(CLK, 3 /*GAFR__ALT_3*/); GPIO.Instance.EnableAsOutputAlternateFunction(TXD, 3 /*GAFR__ALT_3*/); GPIO.Instance.EnableAsInputAlternateFunction(RXD, 3 /*GAFR__ALT_3*/); } else { throw new ArgumentOutOfRangeException("enabled"); } } else { // put pins in output low state when not in use to avoid noise since clock stop and reset will cause these to become inputs if (m_spiChannelIndex == 0) { //allow peripheral control of pins; GPIO.Instance.EnableAsOutputAlternateFunction(CLK, 2 /*GAFR__ALT_2*/); GPIO.Instance.EnableAsOutputAlternateFunction(TXD, 2 /*GAFR__ALT_2*/); // avoid noise drawing excess power on a floating line by putting this in pulldown GPIO.Instance.EnableAsInputAlternateFunction(RXD, 1 /*GAFR__ALT_1*/); } else if (m_spiChannelIndex == 1) { //allow peripheral control of pins; GPIO.Instance.EnableAsOutputAlternateFunction(CLK, 2 /*GAFR__ALT_2*/); GPIO.Instance.EnableAsOutputAlternateFunction(TXD, 2 /*GAFR__ALT_2*/); // avoid noise drawing excess power on a floating line by putting this in pulldown GPIO.Instance.EnableAsInputAlternateFunction(RXD, 2 /*GAFR__ALT_2*/); } else if (m_spiChannelIndex == 2) { //allow peripheral control of pins; GPIO.Instance.EnableAsOutputAlternateFunction(CLK, 3 /*GAFR__ALT_3*/); GPIO.Instance.EnableAsOutputAlternateFunction(TXD, 3 /*GAFR__ALT_3*/); // avoid noise drawing excess power on a floating line by putting this in pulldown GPIO.Instance.EnableAsInputAlternateFunction(RXD, 3 /*GAFR__ALT_3*/); } else { throw new ArgumentOutOfRangeException("enabled"); } } } #endregion #region SPI Bus properties /// /// The clock pin for the SPI channel /// public GPIO.Port CLK { get; protected set; } /// /// The transmit data pin for the SPI channel /// public GPIO.Port TXD { get; protected set; } /// /// The receive data pin for the SPI channel /// public GPIO.Port RXD { get; protected set; } /// /// The SSP channel /// public SSP.SSP_Channel SSP { get; protected set; } #endregion } /// /// Represents a device connected to a SPI /// bus. /// public class SPI_Device { #region SPI Device configuration properties /// /// The GPIO through which the device is conntected to the SPI bus /// public GPIO.Port DeviceCS; /// /// Polarity of the chip select of the /// peer device. /// /// /// False = LOW active, /// TRUE = HIGH active /// public bool CS_Active; /// /// The polarity of the data lines when idle. /// /// /// False = LOW during idle, /// TRUE = HIGH during idle /// public bool MSK_IDLE; /// /// When to read data from the input /// line. /// /// /// False = sample falling edge, /// TRUE = samples on rising /// public bool MSK_SampleEdge; /// /// The size of an atomic transfer /// /// /// true: 16bit transfers /// false: 8bit transfers /// public bool MD_16bits; /// /// The clock rate to use when talking to the device /// public uint Clock_RateKHz; /// /// Time to wait after asserting the chip select /// before starting to send/receive data. /// public uint CS_Setup_uSecs; /// /// Time to wait after transfering the last /// element before de-asserting the chip select. /// public uint CS_Hold_uSecs; #endregion }; #endregion /// /// SPI device channel driver for the PXA271 SSP hardware. /// public class SPI_Channel { #region Constructor/Destructor private SPI_Host m_host; /// /// Initializes a SPI channel instance /// /// The configuration data for the SPI channel. public SPI_Channel(SPI_Host host) { m_host = host; } #endregion #region Public API /// /// Performs a SPI bus transaction with 16bit wide elements /// /// The peer device to talk to /// The data to send to the peer /// The number of elements to send /// The buffer for data received from the peer /// the number of elements received from the peer /// The offset to start storing read data in the read16 buffer public void WriteRead(SPI_Device configuration, UInt16[] write16, int writeCount, UInt16[] read16, int readCount, int readStartOffset) { WriteRead_Start(m_host, configuration); WriteRead_16(m_host, write16, writeCount, read16, readCount, readStartOffset); WriteRead_End(m_host, configuration); } /// /// Performs a SPI bus transaction with 8bit wide elements /// /// The peer device to talk to /// The data to send to the peer /// The number of elements to send /// The buffer for data received from the peer /// the number of elements received from the peer /// The offset to start storing read data in the Read8 buffer public void WriteRead(SPI_Device configuration, byte[] write8, int writeCount, byte[] read8, int readCount, int readStartOffset) { WriteRead_Start(m_host, configuration); WriteRead_8(m_host, write8, writeCount, read8, readCount, readStartOffset); WriteRead_End(m_host, configuration); } #endregion #region Private SPI-BUS Operations /// /// read/writes a 16bit quantum /// /// The SPI bus on which to perform the transaction /// The data to send to the peer /// The number of elements to send /// The buffer for data received from the peer /// the number of elements received from the peer /// The offset to start storing read data in the read16 buffer private static void WriteRead_16(SPI_Host host, ushort[] write16, int writeCount, ushort[] read16, int readCount, int readStartOffset) { int i, d; UInt16 Data16; int readIndex = 0; int writeIndex = 0; if (!host.PinsEnabled || !host.ClockEnabled) { Console.WriteLine("\fSPI Xaction OFF\r\n"); ASSERT(false); return; } // as master, we must always write something before reading or not ASSERT(writeCount > 0); ASSERT(write16 != null); ASSERT(readCount == 0 || read16 != null); // send the first word without qualifications host.SSP.SSDR = write16[writeIndex]; // repeat last write word for all subsequent reads, otherwise increment writeCount--; if (writeCount > 0) writeIndex++; if (readCount > 0) { i = readCount + readStartOffset - 1; // minus 1 since last read happens outside of loop d = readCount - 2; // 2 for extra reads at end of pipeline } else { i = writeCount; d = -1; } if (i-- > 0) { // wait while the transmit buffer is full while (TransmitFifoNotEmpty(host.SSP)) ; // writing sets the TBF bit again host.SSP.SSDR = write16[writeIndex]; // repeat last write word for all subsequent reads writeCount--; if (writeCount > 0) writeIndex++; while (i-- > 0) { //while(PXA271_SPI::SSP_SSSR__RNE != ((PXA271_SPI::SSP_SSSR__RNE | PXA271_SPI::SSP_SSSR__TFL) & SPI.SSP_SSSR)); while (!host.SSP.SSSR.RNE || (host.SSP.SSSR.TFL > 0)) ; // writing sets the TBF bit again host.SSP.SSDR = write16[writeIndex]; // reading clears the RBF bit and allows another transfer from the shift register Data16 = (ushort)host.SSP.SSDR; // repeat last write word for all subsequent reads writeCount--; if (writeCount > 0) writeIndex++; // only save data once we have reached readCount-1 portion of words if (i < d) { read16[readIndex] = Data16; readIndex++; } } while (ReceiveFifoEmpty(host.SSP)) ; // reading clears the RBF bit and allows another transfer from the shift register Data16 = (ushort)host.SSP.SSDR; if (readCount > 1) { read16[readIndex] = Data16; readIndex++; } } // wait for the last character written to actually get into the shifter while (TransmitFifoNotEmpty(host.SSP)) ; // no write, since we want the state machine to stop here // wait for last word to read to be ready - this also ensures the write is finished in case of no reads while (ReceiveFifoEmpty(host.SSP)) ; // read the last word, and without a transmit nothing more will happen in FULL_DUPLEX mode Data16 = (ushort)host.SSP.SSDR; // save last word read, if we are saving them if (readCount > 0) read16[readIndex] = Data16; } /// /// read/writes a 8bit quantum /// /// The SPI bus on which to perform the transaction /// The data to send to the peer /// The number of elements to send /// The buffer for data received from the peer /// the number of elements received from the peer /// The offset to start storing read data in the Read8 buffer private static void WriteRead_8(SPI_Host host, byte[] write8, int writeCount, byte[] read8, int readCount, int readStartOffset) { int i, d; byte Data8; int readIndex = 0; int writeIndex = 0; if (!host.PinsEnabled || !host.ClockEnabled) { Console.WriteLine("\fSPI Xaction OFF\r\n"); ASSERT(false); return; } // as master, we must always write something before reading or not ASSERT(writeCount > 0); ASSERT(write8 != null); ASSERT(readCount == 0 || read8 != null); // send the first word without qualifications host.SSP.SSDR = write8[writeIndex]; // repeat last write word for all subsequent reads, otherwise increment writeCount--; if (writeCount > 0) writeIndex++; if (readCount > 0) { i = readCount + readStartOffset - 1; // minus 1 since last read happens outside of loop d = readCount - 2; // 2 for extra reads at end of pipeline } else { i = writeCount; d = -1; } if (i-- > 0) { // wait while the transmit buffer is full while (TransmitFifoNotEmpty(host.SSP)) ; // writing sets the TBF bit again host.SSP.SSDR = write8[writeIndex]; // repeat last write word for all subsequent reads writeCount--; if (writeCount > 0) writeIndex++; while (i-- > 0) { //while(PXA271_SPI::SSP_SSSR__RNE != ((PXA271_SPI::SSP_SSSR__RNE | PXA271_SPI::SSP_SSSR__TFL) & SPI.SSP_SSSR)); while (!host.SSP.SSSR.RNE || (host.SSP.SSSR.TFL > 0)) ; // writing sets the TBF bit again host.SSP.SSDR = write8[writeIndex]; // reading clears the RBF bit and allows another transfer from the shift register Data8 = (byte)host.SSP.SSDR; // repeat last write word for all subsequent reads writeCount--; if (writeCount > 0) writeIndex++; // only save data once we have reached readCount-1 portion of words if (i < d) { read8[readIndex] = Data8; readIndex++; } } while (ReceiveFifoEmpty(host.SSP)) ; // reading clears the RBF bit and allows another transfer from the shift register Data8 = (byte)host.SSP.SSDR; if (readCount > 1) { read8[readIndex] = Data8; readIndex++; } } // wait for the last character written to actually get into the shifter while (TransmitFifoNotEmpty(host.SSP)) ; // no write, since we want the state machine to stop here // wait for last word to read to be ready - this also ensures the write is finished in case of no reads while (ReceiveFifoEmpty(host.SSP)) ; // read the last word, and without a transmit nothing more will happen in FULL_DUPLEX mode Data8 = (byte)host.SSP.SSDR; // save last word read, if we are saving them if (readCount > 0) read8[readIndex] = Data8; } /// /// Starts a SPI transaction /// /// /// private static void WriteRead_Start(SPI_Host host, SPI_Device configuration) { if (null == host) throw new ArgumentNullException("host"); if (null == configuration) throw new ArgumentNullException("configuration"); if (host.PinsEnabled || host.ClockEnabled) { Console.WriteLine("\fSPI Collision 3\r\n"); ASSERT(false); return; } // enable the Periperal clock for this device host.ClockEnabled = true; //TODO: enable tests // make sure we didn't start one in the middle of an existing transaction //if((0 != (uint)SPI.SSCR0.)||(0 != (uint)SPI.SSCR1)) //{ // throw new NotSupportedException(); // //return; //} host.SSP.SSCR0 = new SSP.SSCR0_Bitfield { MOD = false, //polling mode FRF = 0, //Motorol SPI DSS = ((configuration.MD_16bits) ? 15u : 7u), SCR = (ConvertClockRateToDivisor(configuration.Clock_RateKHz) - 1) }; host.SSP.SSCR1 = new SSP.SSCR1_Bitfield { SCLKDIR = false, //port is in master mode SFRMDIR = false, //port is in master mode TTE = true, //TXD tristate enable SPO = configuration.MSK_IDLE, SPH = !(configuration.MSK_IDLE ^ configuration.MSK_SampleEdge), //both are equal }; #if SPI_LOOP_BACK_PXA271 SPI.SSCR1.LBM = true; #endif host.SSP.SSCR0.SSE = true; //everything should be clean and idle ASSERT(!TransmitFifoNotEmpty(host.SSP)); ASSERT(ReceiveFifoEmpty(host.SSP)); ASSERT(ShiftBufferEmpty(host.SSP)); //allow peripheral control of pins; host.PinsEnabled = true; // first set CS active as soon as clock and data pins are in proper initial state GPIO.Instance.EnableAsOutputPin(configuration.DeviceCS, configuration.CS_Active); // then setup the receiving pin //fmegen: was configuring RXD pins if (configuration.CS_Setup_uSecs > 0) { //TODO: sleep //Time_Sleep_MicroSeconds_InterruptEnabled( Configuration.CS_Setup_uSecs ); } } /// /// ends a SPI transaction /// /// /// private static void WriteRead_End(SPI_Host host, SPI_Device configuration) { ASSERT(null != host); ASSERT(null != configuration); if (!host.PinsEnabled || !host.ClockEnabled) { Console.WriteLine("\fSPI Collision 4\r\n"); ASSERT(false); return; } // we should have cleared the last TBF on the last RBF true setting // we should never bring CS inactive with the shifter busy ASSERT(!TransmitFifoNotEmpty(host.SSP)); ASSERT(ReceiveFifoEmpty(host.SSP)); ASSERT(ShiftBufferEmpty(host.SSP)); if (configuration.CS_Hold_uSecs > 0) { //TODO: sleep //Time_Sleep_MicroSeconds_InterruptEnabled( Configuration.CS_Hold_uSecs ); } // next, bring the CS to the proper inactive state GPIO.Instance.EnableAsOutputPin(configuration.DeviceCS, !configuration.CS_Active); // put pins in output low state when not in use to avoid noise since clock stop and reset will cause these to become inputs host.PinsEnabled = false; // disable spi bus so no new operations start host.SSP.SSCR0 = new SSP.SSCR0_Bitfield(); host.SSP.SSCR1 = new SSP.SSCR1_Bitfield(); //disable the peripheral clock for this device. host.ClockEnabled = false; //at this point, everything associated with the SPI bus //should be shut down. ASSERT(!host.PinsEnabled && !host.ClockEnabled); } [Inline] private static uint ConvertClockRateToDivisor(uint Clock_RateKHz) { uint SSP_CLOCK_KHZ = 13000; if (Clock_RateKHz >= SSP_CLOCK_KHZ) return 1; else if (Clock_RateKHz <= (SSP_CLOCK_KHZ / 4096)) return 4096; else return (((SSP_CLOCK_KHZ + Clock_RateKHz - 1) / Clock_RateKHz)); } [Inline] private static bool TransmitFifoNotEmpty(SSP.SSP_Channel channel) { return (channel.SSSR.TFL != 0); } [Inline] private static bool ReceiveFifoEmpty(SSP.SSP_Channel channel) { return (channel.SSSR.RNE == false); } [Inline] private static bool ShiftBufferEmpty(SSP.SSP_Channel channel) { return (channel.SSSR.BSY == false); } private static void ASSERT(bool p) { if (!p) { Console.WriteLine("did not expect"); throw new NotSupportedException(); } } #endregion } /// /// SPI device driver for the PXA271 SSP hardware. /// public abstract class SPI { #region Singleton API #if TESTMODE_DESKTOP private static SPI s_instance; /// /// Retrieves the SPI driver singleton. /// public static SPI Instance { get { if (null != s_instance) return s_instance; s_instance = new SPI(); s_instance.Initialize(); return s_instance; } } #else /// /// Retrieves the SPI driver singleton. /// extern public static SPI Instance { [MethodImpl(MethodImplOptions.InternalCall)] [SingletonFactory] get; } #endif #endregion #region Available SPI Channels private SPI_Channel[] m_channels; /// /// SPI channel list /// public SPI_Channel[] Channels { get { if (null == m_channels) throw new InvalidOperationException("m_channels"); return m_channels; } } #endregion #region Constructor/Destructor /// /// Initialized the SPI driver. /// public void Initialize() { m_channels = new SPI_Channel[3]; //configure SPI1 pins m_channels[0] = new SPI_Channel(new SPI_Host(0)); //configure SPI2 pins m_channels[1] = new SPI_Channel(new SPI_Host(1)); //configure SPI3 pins (connected to the //CC2420 zigbee chip) m_channels[2] = new SPI_Channel(new SPI_Host(2)); } #endregion } } ================================================ FILE: Zelig/Zelig/RunTime/DeviceModels/ModelForPXA27x/HardwareModel/Drivers/SerialPort.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // namespace Microsoft.DeviceModels.Chipset.PXA27x.Drivers { using System; using System.Runtime.CompilerServices; using System.Threading; using RT = Microsoft.Zelig.Runtime; internal class SerialPort : RT.BaseSerialStream { // // State // private UART.Id m_portNo; private UART.Port m_port; private InterruptController.Handler m_interrupt; private int m_fifoTxLevel; private int m_stat_OverrunErrors; private int m_stat_FramingErrors; private int m_stat_FIFOErrors; // // Constructor Methods // internal SerialPort( ref Configuration cfg , UART.Id portNo , int irq ) : base( ref cfg ) { m_portNo = portNo; m_interrupt = InterruptController.Handler.Create( irq, InterruptPriority.Highest, InterruptSettings.ActiveHigh, ProcessInterrupt ); } // // Helper Methods // internal void Open() { m_port = UART.Instance.Configure( m_portNo, ref m_cfg ); if(m_port == null) { throw new ArgumentException(); } m_port.EnableReceiveInterrupt (); m_port.EnableTransmitInterrupt(); //--// using(RT.SmartHandles.InterruptState.Disable()) { InterruptController.Instance.RegisterAndEnable( m_interrupt ); } } public override void Close() { if(m_port != null) { using(RT.SmartHandles.InterruptState.Disable()) { InterruptController.Instance.DeregisterAndDisable( m_interrupt ); } m_port.DisableTransmitInterrupt(); m_port.DisableReceiveInterrupt (); m_port = null; } } //--// public override void Write( byte[] array , int offset , int count , int timeout ) { base.Write( array, offset, count, timeout ); using(RT.SmartHandles.InterruptState.Disable()) { WriteData(); } } public override void WriteByte( byte value , int timeout ) { base.WriteByte( value, timeout ); using(RT.SmartHandles.InterruptState.Disable()) { WriteData(); } } public override void Flush() { using(RT.SmartHandles.InterruptState.Disable()) { WriteData(); } base.Flush(); } //--// private void ProcessInterrupt( InterruptController.Handler handler ) { while(true) { var status = m_port.IIR; if(status.nIP) { return; } switch(status.IID) { case UART.IIR_bitfield.InterruptSource.RLS: CheckForOverflow( m_port.LSR ); break; case UART.IIR_bitfield.InterruptSource.CTI: case UART.IIR_bitfield.InterruptSource.RDA: CheckForOverflow( m_port.LSR ); ReadData(); break; case UART.IIR_bitfield.InterruptSource.TFDR: WriteData(); break; } } } private void CheckForOverflow( UART.LSR_bitfield val ) { if(val.OE) { m_stat_OverrunErrors++; } if(val.FE) { m_stat_FramingErrors++; } if(val.FIFOE) { m_stat_FIFOErrors++; } } private void WriteData() { while(true) { // // FIFO empty? Reset level counter. // if(m_port.CanSend) { // // Transmitter empty register means FIFO is completely empty // if(m_port.LSR.TEMT == true) { m_fifoTxLevel = 0; } // // Otherwise, FIFO is at least half empty. Reset to half if we are over. // else if(m_fifoTxLevel > 32) { m_fifoTxLevel = 32; } } // // Write up to 64 characters in the FIFO before we have to wait for it to empty. // if(m_fifoTxLevel >= 64) { break; } byte tx; if(m_transmitQueue.DequeueNonblocking( out tx ) == false) { break; } m_port.THR = tx; m_fifoTxLevel++; } } private void ReadData() { byte rx; while(m_port.ReadByte( out rx )) { if(m_receiveQueue.EnqueueNonblocking( rx ) == false) { m_stat_OverrunErrors++; } } } // // Access Methods // public int OverrunErrors { get { return m_stat_OverrunErrors; } } public override bool IsOpen { get { return m_port != null; } } } } ================================================ FILE: Zelig/Zelig/RunTime/DeviceModels/ModelForPXA27x/HardwareModel/Processor.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // namespace Microsoft.DeviceModels.Chipset.PXA27x { using System; using RT = Microsoft.Zelig.Runtime; using TS = Microsoft.Zelig.Runtime.TypeSystem; using ARMv4 = Microsoft.Zelig.Runtime.TargetPlatform.ARMv4; public abstract class Processor : RT.TargetPlatform.ARMv4.ProcessorARMv4 { public static class Configuration { public const uint SYSCLK = 13000000; public static ulong CoreClockFrequency { [RT.ConfigurationOption("System__CoreClockFrequency")] get { return 0; } } public static ulong PeripheralsClockFrequency { [RT.ConfigurationOption("System__PeripheralsClockFrequency")] get { return 0; } } public static ulong RealTimeClockFrequency { [RT.ConfigurationOption("System__RealTimeClockFrequency")] get { return 0; } } public static uint DefaultThreadPoolThreads { [RT.ConfigurationOption( "System__Runtime_DefaultThreadPoolThreads" )] get { return Int32.MaxValue; } } public static uint DefaultTimerPoolThreads { [RT.ConfigurationOption( "System__Runtime_DefaultTimerPooThreads" )] get { return 2; } } } public sealed new class Context : RT.TargetPlatform.ARMv4.ProcessorARMv4.Context { // // Constructor Methods // public Context(RT.ThreadImpl owner) : base(owner) { } // // Helper Methods // // // Access Methods // } // // Helper Methods // public override void InitializeProcessor() { Chipset.PXA27x.MemoryController.Instance.InitializeStackedFLASH(); } public override UIntPtr GetCacheableAddress( UIntPtr ptr ) { return ptr; } public override UIntPtr GetUncacheableAddress( UIntPtr ptr ) { return ptr; } //--// public static void EnableCaches() { ARMv4.Coprocessor15.InvalidateICache(); ARMv4.Coprocessor15.InvalidateDCache(); // // Enable ICache/DCache/Branch Target Buffer // ARMv4.Coprocessor15.SetControlRegisterBits( ARMv4.Coprocessor15.c_ControlRegister__ICache | ARMv4.Coprocessor15.c_ControlRegister__DCache | ARMv4.Coprocessor15.c_ControlRegister__BTB ); //// // //// // Enable ICache/DCache/Branch Target Buffer //// // //// // Relocate exception vector table. //// // //// ARMv4.Coprocessor15.SetControlRegisterBits( ARMv4.Coprocessor15.c_ControlRegister__ICache | //// ARMv4.Coprocessor15.c_ControlRegister__DCache | //// ARMv4.Coprocessor15.c_ControlRegister__BTB | //// ARMv4.Coprocessor15.c_ControlRegister__Vector ); } //--// [RT.Inline] public override RT.Processor.Context AllocateProcessorContext(RT.ThreadImpl owner) { return new Context(owner); } //--// [RT.NoInline] [RT.BottomOfCallStack] [RT.MemoryUsage( RT.MemoryUsage.Bootstrap )] [RT.DebuggerHookHandler( RT.DebuggerHook.FlushInstructionCache )] static void FlushICache() { //// RT.TargetPlatform.ARMv4.Coprocessor15.TestAndCleanDCache(); RT.TargetPlatform.ARMv4.Coprocessor15.DrainWriteBuffer (); RT.TargetPlatform.ARMv4.Coprocessor15.InvalidateICache (); Processor.Instance.Breakpoint(); } [RT.NoInline] [RT.BottomOfCallStack] [RT.SaveFullProcessorContext] [RT.MemoryUsage( RT.MemoryUsage.Bootstrap )] [RT.DebuggerHookHandler( RT.DebuggerHook.GetFullProcessorContext )] static void GetFullProcessorContext() { Processor.Instance.Breakpoint(); } } } ================================================ FILE: Zelig/Zelig/RunTime/DeviceModels/ModelForPXA27x/ModelForPXA27x.csproj ================================================  Debug AnyCPU 9.0.21022 2.0 {186F31A3-EF89-4A25-B2D5-20080519AA01} Library Properties Microsoft.DeviceModels.Chipset.ModelForPXA27x Microsoft.DeviceModels.ModelForPXA27x $(LlilumBuildRoot)\Target\obj\$(MSBuildProjectName)\ v4.5 true full false $(LlilumBuildRoot)\Target\bin\$(Configuration)\ DEBUG;TRACE prompt 4 true true true AllRules.ruleset AnyCPU false pdbonly true $(LlilumBuildRoot)\Target\bin\$(Configuration)\ TRACE prompt 4 true true true AllRules.ruleset AnyCPU false true full false $(LlilumBuildRoot)\Target\bin\$(Configuration)\ true AnyCPU DEBUG;TRACE true true false {186F31A3-EF89-4A25-B2D5-20060501AA01} mscorlib False {186F31A3-EF89-4A25-B2D5-20070702AA01} system False {186F31A3-EF89-4A25-B2D5-20061218AA01} Common False {186F31A3-EF89-4A25-B2D5-20060509AA01} Kernel False {186F31A3-EF89-4A25-B2D5-20060720AA01} TypeSystem False 3.5 ================================================ FILE: Zelig/Zelig/RunTime/DeviceModels/ModelForPXA27x/Properties/AssemblyInfo.cs ================================================ using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; // General Information about an assembly is controlled through the following // set of attributes. Change these attribute values to modify the information // associated with an assembly. [assembly: AssemblyTitle( "Microsoft.DeviceModels.ModelForLPC3180" )] [assembly: AssemblyDescription( "" )] [assembly: AssemblyConfiguration( "" )] [assembly: AssemblyCompany( "Microsoft" )] [assembly: AssemblyProduct( "Microsoft.DeviceModels.ModelForLPC3180" )] [assembly: AssemblyCopyright( "Copyright © Microsoft 2007" )] [assembly: AssemblyTrademark( "" )] [assembly: AssemblyCulture( "" )] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible( false )] //// The following GUID is for the ID of the typelib if this project is exposed to COM //[assembly: Guid( "975a7db2-22e5-41c6-9e32-d3f72152d387" )] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Revision and Build Numbers // by using the '*' as shown below: [assembly: AssemblyVersion( "1.0.0.0" )] [assembly: AssemblyFileVersion( "1.0.0.0" )] ================================================ FILE: Zelig/Zelig/RunTime/DeviceModels/ModelForPXA27x/SystemServices/SchedulerTimeImpl.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // namespace Microsoft.DeviceModels.Chipset.PXA27x.Runtime { using System; using RT = Microsoft.Zelig.Runtime; using TS = Microsoft.Zelig.Runtime.TypeSystem; // // We use the 1MHz timer for the internal time. // [RT.ExtendClass(typeof(RT.SchedulerTime), NoConstructors=true)] public struct SchedulerTimeImpl { // // Helper Methods // private static ulong ConvertFromMillisecondsToUnits( int milliSeconds ) { if(milliSeconds < 0) { return ulong.MaxValue; } else { // // The 1MHz timer. // // => 1000000 / 1000 == 1000 // ulong res = (uint)milliSeconds * 1000; return GetCurrentTime() + res; } } private static ulong ConvertFromTimeSpanTicksToUnits( long ticks ) { if(ticks < 0) { return ulong.MaxValue; } else { ulong res = ConvertFromDateTimeTicksToUnits( ticks ); return GetCurrentTime() + res; } } private static ulong ConvertFromDateTimeTicksToUnits( long ticks ) { return (ulong)((double)ticks * RatioFromDateTimeTicksToUnits); } private static long ConvertFromUnitsToDateTimeTicks( ulong units ) { return (long)((double)units * RatioFromUnitsToDateTimeTicks); } private static ulong GetCurrentTime() { return Drivers.RealTimeClock.Instance.CurrentTime; } // // Access Methods // static int HardwareClockFrequency { [RT.Inline] get { return (int)RT.Configuration.RealTimeClockFrequency; } } static double RatioFromMillisecondsToUnits { [RT.Inline] get { return (double)HardwareClockFrequency / (double)1000; } } static double RatioFromDateTimeTicksToUnits { [RT.Inline] get { return (double)HardwareClockFrequency / (double)TimeSpan.TicksPerSecond; } } static double RatioFromUnitsToMilliseconds { [RT.Inline] get { return 1.0 / RatioFromMillisecondsToUnits; } } static double RatioFromUnitsToDateTimeTicks { [RT.Inline] get { return 1.0 / RatioFromDateTimeTicksToUnits; } } } } ================================================ FILE: Zelig/Zelig/RunTime/DeviceModels/ModelForPXA27x/SystemServices/SchedulerTimeSpanImpl.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // namespace Microsoft.DeviceModels.Chipset.PXA27x.Runtime { using System; using RT = Microsoft.Zelig.Runtime; using TS = Microsoft.Zelig.Runtime.TypeSystem; // // We use the RTC time resolution for the internal time. // [RT.ExtendClass(typeof(RT.SchedulerTimeSpan), NoConstructors=true)] public struct SchedulerTimeSpanImpl { // // Helper Methods // private static long ConvertFromMillisecondsToDeltaUnits( long milliSeconds ) { return (long)((double)milliSeconds * RatioFromMillisecondsToDeltaUnits); } private static long ConvertFromTimeSpanTicksToDeltaUnits( long ticks ) { return (long)((double)ticks * RatioFromTimeSpanTicksToDeltaUnits); } private static long ConvertFromDeltaUnitsToTimeSpanTicks( long deltaUnits ) { return (long)((double)deltaUnits * RatioFromDeltaUnitsToTimeSpanTicks); } private static long ConvertFromDeltaUnitsToMilliseconds( long deltaUnits ) { return (long)((double)deltaUnits * RatioFromDeltaUnitsToMilliseconds); } // // Access Methods // static int HardwareClockFrequency { [RT.Inline] get { return (int)RT.Configuration.RealTimeClockFrequency; } } static double RatioFromMillisecondsToDeltaUnits { [RT.Inline] get { return (double)HardwareClockFrequency / (double)1000; } } static double RatioFromTimeSpanTicksToDeltaUnits { [RT.Inline] get { return (double)HardwareClockFrequency / (double)TimeSpan.TicksPerSecond; } } static double RatioFromDeltaUnitsToMilliseconds { [RT.Inline] get { return 1.0 / RatioFromMillisecondsToDeltaUnits; } } static double RatioFromDeltaUnitsToTimeSpanTicks { [RT.Inline] get { return 1.0 / RatioFromTimeSpanTicksToDeltaUnits; } } } } ================================================ FILE: Zelig/Zelig/RunTime/DeviceModels/ModelForPXA27x/SystemServices/SerialPortsManager.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // namespace Microsoft.DeviceModels.Chipset.PXA27x.Runtime { using System; using RT = Microsoft.Zelig.Runtime; using TS = Microsoft.Zelig.Runtime.TypeSystem; public abstract class SerialPortsManager : RT.SerialPortsManager { // // State // // // Helper Methods // public override void Initialize() { } public override string[] GetPortNames() { return new string[] { "FFUART", "BTUART", "STUART", }; } public override System.IO.Ports.SerialStream Open( ref RT.BaseSerialStream.Configuration cfg ) { switch (cfg.PortName) { case "FFUART": return Open(ref cfg, UART.Id.FFUART); case "BTUART": return Open(ref cfg, UART.Id.BTUART); case "STUART": return Open(ref cfg, UART.Id.STUART); } return null; } private System.IO.Ports.SerialStream Open(ref RT.BaseSerialStream.Configuration cfg, UART.Id id) { Drivers.SerialPort port; switch (id) { case UART.Id.FFUART: port = new Drivers.SerialPort(ref cfg, id, InterruptController.IRQ_INDEX_FFUART); break; case UART.Id.BTUART: port = new Drivers.SerialPort(ref cfg, id, InterruptController.IRQ_INDEX_BTUART); break; case UART.Id.STUART: port = new Drivers.SerialPort(ref cfg, id, InterruptController.IRQ_INDEX_STUART); break; default: return null; } port.Open(); return port; } } } ================================================ FILE: Zelig/Zelig/RunTime/DeviceModels/ModelForPXA27x/SystemServices/ThreadManager.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // namespace Microsoft.DeviceModels.Chipset.PXA27x.Runtime { using System; using RT = Microsoft.Zelig.Runtime; using TS = Microsoft.Zelig.Runtime.TypeSystem; public abstract class ThreadManager : RT.ARMv5ThreadManager { const ulong c_TimeQuantumMsec = 20; // // State // Drivers.RealTimeClock.Timer m_timer; Drivers.RealTimeClock.Timer m_timerForWaits; // // Helper Methods // public override void InitializeBeforeStaticConstructors() { base.InitializeBeforeStaticConstructors(); } public override void InitializeAfterStaticConstructors( uint[] systemStack ) { base.InitializeAfterStaticConstructors( systemStack ); } public override void Activate() { m_timer = Drivers.RealTimeClock.Instance.CreateTimer( TimeQuantumExpired ); m_timerForWaits = Drivers.RealTimeClock.Instance.CreateTimer( WaitExpired ); } public override void Reschedule() { base.Reschedule(); } public override void SetNextWaitTimer( RT.SchedulerTime nextTimeout ) { if(nextTimeout != RT.SchedulerTime.MaxValue) { m_timerForWaits.Timeout = nextTimeout.Units; } else { m_timerForWaits.Cancel(); } } public override void CancelQuantumTimer() { m_timer.Cancel(); } public override void SetNextQuantumTimer() { m_timer.RelativeTimeout = c_TimeQuantumMsec * 1000 * RT.Configuration.RealTimeClockFrequency / 1000000; } public override void SetNextQuantumTimer( RT.SchedulerTime nextTimeout ) { m_timer.RelativeTimeout = nextTimeout.Units; } //--// private void TimeQuantumExpired( Drivers.RealTimeClock.Timer timer , ulong currentTime ) { TimeQuantumExpired(); } private void WaitExpired( Drivers.RealTimeClock.Timer timer , ulong currentTime ) { WaitExpired( RT.SchedulerTime.FromUnits( currentTime ) ); } } } ================================================ FILE: Zelig/Zelig/RunTime/DeviceModels/ModelForWin32/HardwareModel/Device.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // namespace Microsoft.DeviceModels.Win32 { using LLOS = Zelig.LlilumOSAbstraction; using RT = Microsoft.Zelig.Runtime; public class Device : RT.Device { public override void MoveCodeToProperLocation( ) { } public override void PreInitializeProcessorAndMemory( ) { } public override void ProcessBugCheck( RT.BugCheck.StopCode code ) { m_bugCheckCode = code; LLOS.Debug.LLOS_DEBUG_Break( (uint)code ); } public override void ProcessLog(string format) { LogText( format ); } public override unsafe void ProcessLog(string format, int p1) { LogText( format, p1 ); } public override unsafe void ProcessLog(string format, int p1, int p2) { LogText( format, p1, p2 ); } public override unsafe void ProcessLog(string format, int p1, int p2, int p3) { LogText( format, p1, p2, p3 ); } public override unsafe void ProcessLog(string format, int p1, int p2, int p3, int p4) { LogText( format, p1, p2, p3, p4 ); } public override unsafe void ProcessLog(string format, int p1, int p2, int p3, int p4, int p5) { LogText( format, p1, p2, p3, p4, p5 ); } private unsafe void LogText(string format, params object[] args) { if(!string.IsNullOrEmpty( format )) { string text = args == null ? format : string.Format(format, args); fixed (char* pText = text) { LLOS.Debug.LLOS_DEBUG_LogText( pText, text.Length ); } } } } } ================================================ FILE: Zelig/Zelig/RunTime/DeviceModels/ModelForWin32/HardwareModel/HardwareProviders/HardwareProvider.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // namespace Microsoft.DeviceModels.Win32 { using System; using RT = Microsoft.Zelig.Runtime; //--// public class HardwareProvider : RT.HardwareProvider { static string []s_ports = new string[0]; public override int InvalidPin { get { throw new NotImplementedException( ); } } public override int PinCount { get { throw new NotImplementedException( ); } } public override bool GetSerialPinsFromPortName( string portName, out int txPin, out int rxPin, out int rtsPin, out int ctsPin ) { throw new NotImplementedException( ); } public override string[] GetSerialPorts( ) { return s_ports; } public override int PinToIndex( int pin ) { throw new NotImplementedException( ); } } } ================================================ FILE: Zelig/Zelig/RunTime/DeviceModels/ModelForWin32/HardwareModel/InterruptsSafeHandle.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // namespace Microsoft.Zelig.Runtime.TargetPlatform.Win32.SmartHandles { using System; using LLOS = LlilumOSAbstraction; using ISA = TargetModel.Win32.InstructionSetVersion; [ExtendClass( typeof(Runtime.SmartHandles.InterruptState), PlatformFamilyFilter = ISA.Platform_Family__Win32 )] public struct InterruptState : IDisposable { // // State // private static UIntPtr s_globalMutex = UIntPtr.Zero; private const uint c_ActionDisable = 0; private const uint c_ActionEnable = 1; private uint m_action; private uint m_state; // // Constructor Methods // [DiscardTargetImplementation()] [Inline] public InterruptState( uint basepri ) { m_action = basepri == 0 ? c_ActionDisable : c_ActionEnable; m_state = m_action; if(s_globalMutex == UIntPtr.Zero) { InterruptState.Initialize( ); } if(m_action == c_ActionDisable) { LLOS.LlilumErrors.ThrowOnError( LLOS.HAL.Mutex.LLOS_MUTEX_Acquire( s_globalMutex, -1 ), false ); } else { LLOS.LlilumErrors.ThrowOnError( LLOS.HAL.Mutex.LLOS_MUTEX_Release( s_globalMutex ), false ); } } // // Helper Methods // public static void Initialize( ) { if(s_globalMutex == UIntPtr.Zero) { LLOS.LlilumErrors.ThrowOnError(LLOS.HAL.Mutex.LLOS_MUTEX_CreateGlobalLock(ref s_globalMutex), false); } } public static bool AreInterruptsDisabled() { return ( s_globalMutex == UIntPtr.Zero ) || ( 1 == LLOS.HAL.Mutex.LLOS_MUTEX_CurrentThreadHasLock(s_globalMutex) ); } [Inline] public void Dispose() { if(m_action == m_state) { if(m_action == c_ActionDisable) { LLOS.LlilumErrors.ThrowOnError( LLOS.HAL.Mutex.LLOS_MUTEX_Release( s_globalMutex ), false ); } else { LLOS.LlilumErrors.ThrowOnError( LLOS.HAL.Mutex.LLOS_MUTEX_Acquire( s_globalMutex, -1 ), false ); } } } [Inline] public void Toggle() { BugCheck.AssertInterruptsOff( ); LLOS.LlilumErrors.ThrowOnError( LLOS.HAL.Mutex.LLOS_MUTEX_Release( s_globalMutex ), false ); LLOS.HAL.Thread.LLOS_THREAD_Yield( ); LLOS.LlilumErrors.ThrowOnError( LLOS.HAL.Mutex.LLOS_MUTEX_Acquire( s_globalMutex, -1 ), false ); } public void SwitchState() { if(m_state == c_ActionDisable) { m_state = c_ActionEnable; LLOS.LlilumErrors.ThrowOnError( LLOS.HAL.Mutex.LLOS_MUTEX_Release( s_globalMutex ), false ); } else { m_state = c_ActionDisable; LLOS.LlilumErrors.ThrowOnError( LLOS.HAL.Mutex.LLOS_MUTEX_Acquire( s_globalMutex, -1 ), false ); } } //--// [Inline] public static InterruptState Disable() { return new InterruptState( 0 ); } [Inline] public static InterruptState DisableAll( ) { return new InterruptState( 0 ); } [Inline] public static InterruptState Enable() { return new InterruptState( 1 ); } [Inline] public static InterruptState EnableAll( ) { return new InterruptState( 1 ); } public HardwareException GetCurrentExceptionMode() { return HardwareException.None; } } } ================================================ FILE: Zelig/Zelig/RunTime/DeviceModels/ModelForWin32/HardwareModel/Memory.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // namespace Microsoft.DeviceModels.Win32 { using RT = Microsoft.Zelig.Runtime; public class Memory : RT.Memory { public override void InitializeMemory( ) { } } } ================================================ FILE: Zelig/Zelig/RunTime/DeviceModels/ModelForWin32/HardwareModel/Peripherals.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // //#define ALLOW_PAUSE namespace Microsoft.DeviceModels.Win32 { using System; using RT = Microsoft.Zelig.Runtime; using LLOS = Zelig.LlilumOSAbstraction.HAL; public class Peripherals : RT.Peripherals { // // State // // // Helper Methods // public override void Initialize() { } public override void Activate() { } public override void EnableInterrupt( uint index ) { throw new NotImplementedException( ); } public override void DisableInterrupt( uint index ) { throw new NotImplementedException( ); } public override void CauseInterrupt() { } public override void ContinueUnderNormalInterrupt(Continuation dlg) { throw new NotImplementedException( ); } public override void WaitForInterrupt() { } public override void ProcessInterrupt() { throw new NotImplementedException( ); } [RT.MemoryRequirements(RT.MemoryAttributes.RAM)] public override void ProcessFastInterrupt() { throw new NotImplementedException( ); } public override ulong GetPerformanceCounterFrequency() { return LLOS.Clock.LLOS_CLOCK_GetPerformanceCounterFrequency(); } [RT.Inline] [RT.DisableNullChecks()] public override uint ReadPerformanceCounter() { return (uint)LLOS.Clock.LLOS_CLOCK_GetPerformanceCounter(); } } } ================================================ FILE: Zelig/Zelig/RunTime/DeviceModels/ModelForWin32/HardwareModel/Processor.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // namespace Microsoft.DeviceModels.Win32 { using System; using System.Threading; using LLOS = Zelig.LlilumOSAbstraction; using RT = Microsoft.Zelig.Runtime; using TS = Microsoft.Zelig.Runtime.TypeSystem; using SH = Microsoft.Zelig.Runtime.TargetPlatform.Win32.SmartHandles; [RT.ProductFilter("Microsoft.Llilum.BoardConfigurations.Win32Product")] public sealed class Processor : RT.Processor { public new class Context : RT.Processor.Context { private UIntPtr m_threadHandle; public Context(RT.ThreadImpl owner) : base(owner) { } public override UIntPtr BaseStackPointer { get { throw new NotImplementedException( ); } } public override uint ExcReturn { get { throw new NotImplementedException( ); } set { throw new NotImplementedException( ); } } public override UIntPtr ProgramCounter { get { throw new NotImplementedException( ); } set { throw new NotImplementedException( ); } } public override uint ScratchedIntegerRegisters { get { throw new NotImplementedException( ); } } public override UIntPtr StackPointer { get { throw new NotImplementedException( ); } set { throw new NotImplementedException( ); } } public override UIntPtr GetRegisterByIndex( uint idx ) { throw new NotImplementedException( ); } public override void Populate( ) { throw new NotImplementedException( ); } public override void Populate( RT.Processor.Context context ) { throw new NotImplementedException( ); } public override void PopulateFromDelegate( Delegate dlg, uint[] stack ) { LLOS.LlilumErrors.ThrowOnError(LLOS.HAL.Thread.LLOS_THREAD_CreateThread(dlg, m_owner, ref m_threadHandle), false); } public override void SetRegisterByIndex( uint idx, UIntPtr value ) { throw new NotImplementedException( ); } public override void SetupForExceptionHandling( uint mode ) { throw new NotImplementedException( ); } public override void SwitchTo( ) { LLOS.LlilumErrors.ThrowOnError(LLOS.HAL.Thread.LLOS_THREAD_SetPriority(m_threadHandle, LLOS.HAL.Thread.ThreadPriority.Highest), false); LLOS.LlilumErrors.ThrowOnError(LLOS.HAL.Thread.LLOS_THREAD_Yield(), false); // For Win32 builds we need to keep the entry-point thread alive since it is the main process thread. while(true) { LLOS.HAL.Thread.LLOS_THREAD_Sleep(Timeout.Infinite); } } public override bool Unwind( ) { throw new NotImplementedException( ); } //--// public void WaitForEvent(int timeoutMs) { LLOS.LlilumErrors.ThrowOnError(LLOS.HAL.Thread.LLOS_THREAD_Wait(m_threadHandle, timeoutMs), false); } public void SetEvent() { LLOS.LlilumErrors.ThrowOnError(LLOS.HAL.Thread.LLOS_THREAD_Signal(m_threadHandle), false); } public void Yield() { LLOS.HAL.Thread.LLOS_THREAD_Yield( ); } public void Start() { LLOS.LlilumErrors.ThrowOnError( LLOS.HAL.Thread.LLOS_THREAD_Start( m_threadHandle ), false ); } public void Retire() { LLOS.HAL.Thread.LLOS_THREAD_DeleteThread(m_threadHandle); } } [TS.WellKnownType( "Microsoft_Zelig_Win32_MethodWrapper" )] public sealed class MethodWrapper : RT.AbstractMethodWrapper { [RT.Inline] [RT.DisableNullChecks( ApplyRecursively = true )] public override void Prologue( string typeFullName, string methodFullName, TS.MethodRepresentation.BuildTimeAttributes attribs ) { } [RT.Inline] [RT.DisableNullChecks( ApplyRecursively = true )] public unsafe override void Prologue( string typeFullName, string methodFullName, TS.MethodRepresentation.BuildTimeAttributes attribs, RT.HardwareException he ) { } [RT.Inline] [RT.DisableNullChecks( ApplyRecursively = true )] public override void Epilogue( string typeFullName, string methodFullName, TS.MethodRepresentation.BuildTimeAttributes attribs ) { } [RT.Inline] [RT.DisableNullChecks( ApplyRecursively = true )] public unsafe override void Epilogue( string typeFullName, string methodFullName, TS.MethodRepresentation.BuildTimeAttributes attribs, RT.HardwareException he ) { } } // // Access methods // public override RT.Processor.Context AllocateProcessorContext( RT.ThreadImpl owner ) { return new Context( owner ); } public override bool AreAllInterruptsDisabled( ) { return AreInterruptsDisabled( ); } public override bool AreInterruptsDisabled( ) { return SH.InterruptState.AreInterruptsDisabled(); } public override bool AreInterruptsEnabled() { // Always return true because we use a global mutex instead of interrupts, so cannot guarantee that a // thread holding the mutex will not be swapped out by the Windows scheduler. The only thing that uses // this function is the AssertInterruptsOn assert which is not valid in the Win32 port. return true; } public override void Breakpoint( ) { throw new NotImplementedException( ); } public override void FlushCacheLine( UIntPtr target ) { throw new NotImplementedException( ); } public override UIntPtr GetCacheableAddress( UIntPtr ptr ) { throw new NotImplementedException( ); } public override UIntPtr GetUncacheableAddress( UIntPtr ptr ) { throw new NotImplementedException( ); } // // Helper Methods // public override void InitializeProcessor() { RT.SmartHandles.InterruptState.DisableAll( ); } [TS.GenerateUnsafeCast()] internal extern static RT.ThreadImpl CastAsThreadImpl(UIntPtr ptr); public RT.ThreadImpl CurrentThread { get { UIntPtr threadHandle = UIntPtr.Zero; if(LLOS.LlilumErrors.Succeeded( LLOS.HAL.Thread.LLOS_THREAD_GetCurrentThread( ref threadHandle ) )) { return CastAsThreadImpl(threadHandle); } return null; } } } } ================================================ FILE: Zelig/Zelig/RunTime/DeviceModels/ModelForWin32/HardwareModel/SerialPortsManager.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // namespace Microsoft.DeviceModels.Win32 { using System; using System.IO.Ports; using RT = Microsoft.Zelig.Runtime; //--// public class SerialPortsManager : RT.SerialPortsManager { public override string[] GetPortNames( ) { return null; } public override void Initialize( ) { } public override SerialStream Open( ref RT.BaseSerialStream.Configuration cfg ) { throw new NotImplementedException( ); } } } ================================================ FILE: Zelig/Zelig/RunTime/DeviceModels/ModelForWin32/ModelForWin32.csproj ================================================  Debug AnyCPU 9.0.21022 2.0 {B157F660-AED5-49A2-99DB-FE60855DC5F4} Library Properties Microsoft.DeviceModels.Win32 Microsoft.DeviceModels.ModelForWin32 $(LlilumBuildRoot)\Target\obj\$(MSBuildProjectName)\ v4.5 true full false $(LlilumBuildRoot)\Target\bin\$(Configuration)\ DEBUG;TRACE prompt 4 true true true AllRules.ruleset AnyCPU false pdbonly true $(LlilumBuildRoot)\Target\bin\$(Configuration)\ TRACE prompt 4 true true true AllRules.ruleset AnyCPU false true full false $(LlilumBuildRoot)\Target\bin\$(Configuration)\ true AnyCPU DEBUG;TRACE true true false {186F31A3-EF89-4A25-B2D5-20060501AA01} mscorlib False {186F31A3-EF89-4A25-B2D5-20070702AA01} system False {186F31A3-EF89-4A25-B2D5-20061218AA01} Common False {186F31A3-EF89-4A25-B2D5-20060509AA01} Kernel False {186F31A3-EF89-4A25-B2D5-20060720AA01} TypeSystem False {20DC2CF5-8EED-4231-9743-6BAB96BE465C} LlilumOSAbstraction {46478CA2-8163-47A0-8C65-3ACFC21CE57F} Win32Processor False 3.5 ================================================ FILE: Zelig/Zelig/RunTime/DeviceModels/ModelForWin32/Properties/AssemblyInfo.cs ================================================ using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; // General Information about an assembly is controlled through the following // set of attributes. Change these attribute values to modify the information // associated with an assembly. [assembly: AssemblyTitle( "Microsoft.DeviceModels.ModelForLPC3180" )] [assembly: AssemblyDescription( "" )] [assembly: AssemblyConfiguration( "" )] [assembly: AssemblyCompany( "Microsoft" )] [assembly: AssemblyProduct( "Microsoft.DeviceModels.ModelForLPC3180" )] [assembly: AssemblyCopyright( "Copyright © Microsoft 2007" )] [assembly: AssemblyTrademark( "" )] [assembly: AssemblyCulture( "" )] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible( false )] //// The following GUID is for the ID of the typelib if this project is exposed to COM //[assembly: Guid( "975a7db2-22e5-41c6-9e32-d3f72152d387" )] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Revision and Build Numbers // by using the '*' as shown below: [assembly: AssemblyVersion( "1.0.0.0" )] [assembly: AssemblyFileVersion( "1.0.0.0" )] ================================================ FILE: Zelig/Zelig/RunTime/DeviceModels/ModelForWin32/SystemServices/MemoryManager.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // namespace Microsoft.DeviceModels.Runtime.Win32 { using System; using RT = Microsoft.Zelig.Runtime; using LLOS = Zelig.LlilumOSAbstraction; public class MemoryManager : RT.LinearMemoryManager { private UIntPtr ManagedHeap; private UIntPtr ManagedHeapEnd; //--// public override unsafe void InitializeMemoryManager( ) { base.InitializeMemoryManager( ); uint heapSize; void *pLlilumHeap; LLOS.LlilumErrors.ThrowOnError( LLOS.API.RuntimeMemory.LLOS_MEMORY_GetMaxHeapSize( out heapSize ), false ); LLOS.LlilumErrors.ThrowOnError( LLOS.API.RuntimeMemory.LLOS_MEMORY_Allocate( heapSize, 0, out pLlilumHeap ), false ); ManagedHeap = (UIntPtr)(pLlilumHeap); ManagedHeapEnd = (UIntPtr)( (uint)pLlilumHeap + heapSize ); var attrs = RT.MemoryAttributes.InternalMemory | RT.MemoryAttributes.RandomAccessMemory | RT.MemoryAttributes.ConfiguredAtEntryPoint ; AddLinearSection( ManagedHeap, ManagedHeapEnd , attrs ); } public override bool RefersToMemory( UIntPtr address ) { return ( uint )ManagedHeap >= ( uint )address && ( uint )address < ( uint )ManagedHeapEnd; } } } ================================================ FILE: Zelig/Zelig/RunTime/DeviceModels/ModelForWin32/SystemServices/SchedulerTimeImpl.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // namespace Microsoft.CortexM3OnMBED { using System; using RT = Microsoft.Zelig.Runtime; using LLOS = Zelig.LlilumOSAbstraction; // // We use the 1MHz timer for the internal time. // [RT.ExtendClass(typeof(RT.SchedulerTime), NoConstructors=true)] public struct SchedulerTimeImpl { // // Helper Methods // private static ulong ConvertFromMillisecondsToUnits( int milliSeconds ) { if(milliSeconds < 0) { return ulong.MaxValue; } else { ulong res = (uint)milliSeconds * (uint)HardwareClockFrequency / 1000; return GetCurrentTime() + res; } } private static ulong ConvertFromTimeSpanTicksToUnits( long ticks ) { if(ticks < 0) { return ulong.MaxValue; } else { ulong res = ConvertFromDateTimeTicksToUnits( ticks ); return GetCurrentTime() + res; } } private static ulong ConvertFromDateTimeTicksToUnits( long ticks ) { return (ulong)((double)ticks * RatioFromDateTimeTicksToUnits); } private static long ConvertFromUnitsToDateTimeTicks( ulong units ) { return (long)((double)units * RatioFromUnitsToDateTimeTicks); } private static ulong GetCurrentTime() { return LLOS.HAL.Clock.LLOS_CLOCK_GetClockTicks(); } // // Access Methods // static unsafe int HardwareClockFrequency { [RT.Inline] get { return (int)LLOS.HAL.Timer.LLOS_SYSTEM_TIMER_GetTimerFrequency( null ); } } static double RatioFromMillisecondsToUnits { [RT.Inline] get { return (double)HardwareClockFrequency / 1000; } } static double RatioFromDateTimeTicksToUnits { [RT.Inline] get { return (double)HardwareClockFrequency / (double)TimeSpan.TicksPerSecond; } } static double RatioFromUnitsToMilliseconds { [RT.Inline] get { return 1.0 / RatioFromMillisecondsToUnits; } } static double RatioFromUnitsToDateTimeTicks { [RT.Inline] get { return 1.0 / RatioFromDateTimeTicksToUnits; } } } } ================================================ FILE: Zelig/Zelig/RunTime/DeviceModels/ModelForWin32/SystemServices/SchedulerTimeSpanImpl.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // namespace Microsoft.CortexM3OnMBED { using System; using RT = Microsoft.Zelig.Runtime; using LLOS = Zelig.LlilumOSAbstraction; // // We use the RTC time resolution for the internal time. // [RT.ExtendClass(typeof(RT.SchedulerTimeSpan), NoConstructors=true)] public struct SchedulerTimeSpanImpl { // // Helper Methods // private static long ConvertFromMillisecondsToDeltaUnits( long milliSeconds ) { return (long)((double)milliSeconds * RatioFromMillisecondsToDeltaUnits); } private static long ConvertFromTimeSpanTicksToDeltaUnits( long ticks ) { return (long)((double)ticks * RatioFromTimeSpanTicksToDeltaUnits); } private static long ConvertFromDeltaUnitsToTimeSpanTicks( long deltaUnits ) { return (long)((double)deltaUnits * RatioFromDeltaUnitsToTimeSpanTicks); } private static long ConvertFromDeltaUnitsToMilliseconds( long deltaUnits ) { return (long)((double)deltaUnits * RatioFromDeltaUnitsToMilliseconds); } // // Access Methods // static unsafe int HardwareClockFrequency { [RT.Inline] get { return (int)LLOS.HAL.Timer.LLOS_SYSTEM_TIMER_GetTimerFrequency( null ); } } static double RatioFromMillisecondsToDeltaUnits { [RT.Inline] get { return (double)HardwareClockFrequency / (double)1000; } } static double RatioFromTimeSpanTicksToDeltaUnits { [RT.Inline] get { return (double)HardwareClockFrequency / (double)TimeSpan.TicksPerSecond; } } static double RatioFromDeltaUnitsToMilliseconds { [RT.Inline] get { return 1.0 / RatioFromMillisecondsToDeltaUnits; } } static double RatioFromDeltaUnitsToTimeSpanTicks { [RT.Inline] get { return 1.0 / RatioFromTimeSpanTicksToDeltaUnits; } } } } ================================================ FILE: Zelig/Zelig/RunTime/DeviceModels/ModelForWin32/SystemServices/ThreadManager.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // namespace Microsoft.DeviceModels.Runtime.Win32 { using System; using System.Threading; using System.Collections.Generic; using RT = Microsoft.Zelig.Runtime; using LLOS = Zelig.LlilumOSAbstraction; using TS = Zelig.Runtime.TypeSystem; public sealed class ThreadManager : RT.ThreadManager { private static object s_deadThreadLock = new object(); private unsafe LLOS.HAL.TimerContext* m_timer; private List m_deadThreads; private AutoResetEvent m_evtThreadExit; private RT.ThreadImpl m_interruptThread; public override RT.ThreadImpl InterruptThread { get { throw new NotImplementedException(); } } public override RT.ThreadImpl FastInterruptThread { get { throw new NotImplementedException(); } } public override RT.ThreadImpl AbortThread { get { throw new NotImplementedException(); } } // // State // // // Helper Methods // public override void InitializeBeforeStaticConstructors() { base.InitializeBeforeStaticConstructors(); } public override void InitializeAfterStaticConstructors(uint[] systemStack) { base.InitializeAfterStaticConstructors(systemStack); m_deadThreads = new List(); m_evtThreadExit = new AutoResetEvent(false); m_interruptThread = new RT.ThreadImpl(null, new uint[ 128 ]); } //--// // // Extensibility // private void WaitExpired( UIntPtr context, ulong time ) { WaitExpired( RT.SchedulerTime.FromUnits( time ) ); } public override void Activate() { base.Activate(); unsafe { fixed (LLOS.HAL.TimerContext** ppTimer = &m_timer) { LLOS.LlilumErrors.ThrowOnError(LLOS.HAL.Timer.LLOS_SYSTEM_TIMER_AllocateTimer(WaitExpired, UIntPtr.Zero, ulong.MaxValue, ppTimer), false); } } } public override void CancelQuantumTimer() { } public override void SetNextQuantumTimer() { } public override void SetNextQuantumTimer(RT.SchedulerTime nextTimeout) { } public override void TimeQuantumExpired() { } public unsafe override void SetNextWaitTimer(RT.SchedulerTime nextTimeout) { if(nextTimeout != RT.SchedulerTime.MaxValue) { ulong usecFromNow = LLOS.HAL.Clock.LLOS_CLOCK_GetClockTicks(); if(usecFromNow > nextTimeout.Units) { usecFromNow = 0; } else { usecFromNow = nextTimeout.Units - usecFromNow; usecFromNow *= 1000; } LLOS.LlilumErrors.ThrowOnError(LLOS.HAL.Timer.LLOS_SYSTEM_TIMER_ScheduleTimer(m_timer, usecFromNow), false); } else { LLOS.LlilumErrors.ThrowOnError(LLOS.HAL.Timer.LLOS_SYSTEM_TIMER_ScheduleTimer(m_timer, ulong.MaxValue), false); } } protected override void IdleThread() { while(true) { m_evtThreadExit.WaitOne(); lock (s_deadThreadLock) { for(int i = 0; i // This code was generated by a tool. // Runtime Version:4.0.30319.235 // // Changes to this file may cause incorrect behavior and will be lost if // the code is regenerated. // //------------------------------------------------------------------------------ namespace Microsoft.NohauLPC3180 { using System; /// /// A strongly-typed resource class, for looking up localized strings, etc. /// // This class was auto-generated by the StronglyTypedResourceBuilder // class via a tool like ResGen or Visual Studio. // To add or remove a member, edit your .ResX file then rerun ResGen // with the /str option, or rebuild your VS project. [global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Resources.Tools.StronglyTypedResourceBuilder", "4.0.0.0")] [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] [global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()] internal class AudioSamples { private static global::System.Resources.ResourceManager resourceMan; private static global::System.Globalization.CultureInfo resourceCulture; [global::System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")] internal AudioSamples() { } /// /// Returns the cached ResourceManager instance used by this class. /// [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)] internal static global::System.Resources.ResourceManager ResourceManager { get { if (object.ReferenceEquals(resourceMan, null)) { global::System.Resources.ResourceManager temp = new global::System.Resources.ResourceManager("Microsoft.NohauLPC3180.AudioSamples", typeof(AudioSamples).Assembly); resourceMan = temp; } return resourceMan; } } /// /// Overrides the current thread's CurrentUICulture property for all /// resource lookups using this strongly typed resource class. /// [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)] internal static global::System.Globalization.CultureInfo Culture { get { return resourceCulture; } set { resourceCulture = value; } } internal static byte[] sample1 { get { object obj = ResourceManager.GetObject("sample1", resourceCulture); return ((byte[])(obj)); } } } } ================================================ FILE: Zelig/Zelig/RunTime/DeviceModels/NohauLPC3180/AudioSamples.resx ================================================  text/microsoft-resx 2.0 System.Resources.ResXResourceReader, System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 System.Resources.ResXResourceWriter, System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 Resources\sample1.pcm;System.Byte[], mscorlib, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 ================================================ FILE: Zelig/Zelig/RunTime/DeviceModels/NohauLPC3180/HardwareModel/Device.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // namespace Microsoft.NohauLPC3180 { using System; using System.Runtime.CompilerServices; using RT = Microsoft.Zelig.Runtime; using ChipsetModel = Microsoft.DeviceModels.Chipset.LPC3180; public sealed class Device : RT.Device { const uint c_PageCount = 65536; const uint c_PageSize = 512; const uint c_SpareSize = 16; const uint c_UsableSpareSize = 6; const uint c_BlockSize = 16384; const uint c_ChipSize = c_PageCount * c_PageSize; static readonly uint [] s_Page = new uint [c_PageSize / sizeof(uint )]; static readonly ushort[] s_Spare = new ushort[c_SpareSize / sizeof(ushort)]; //--// public override void PreInitializeProcessorAndMemory() { // // Enter System mode, with interrupts disabled. // Processor.SetStatusRegister( Processor.c_psr_field_c, Processor.c_psr_I | Processor.c_psr_F | Processor.c_psr_mode_SYS ); Processor.SetRegister( Processor.Context.RegistersOnStack.StackRegister, this.BootstrapStackPointer ); Processor.PreInitializeProcessor( Processor.Configuration.SYSCLK, (uint)Processor.Configuration.CoreClockFrequency, (uint)Processor.Configuration.AHBClockFrequency, (uint)Processor.Configuration.PeripheralsClockFrequency ); } public override void MoveCodeToProperLocation() { uint HCLK = (uint)Processor.Configuration.AHBClockFrequency; InitializeNANDController( HCLK ); InitializeDRAMController( HCLK ); ExecuteImageRelocation(); } private void InitializeNANDController( uint hclkMHz ) { var flashclk = new ChipsetModel.SystemControl.FLASHCLK_CTRL_bitfield(); flashclk.InterruptFromMLC = true; flashclk.MLC_ClockEnable = true; ChipsetModel.SystemControl.Instance.FLASHCLK_CTRL = flashclk; var ctrl = ChipsetModel.MultiLevelNANDController.Instance; ctrl.SetTimingRegister( hclkMHz, 45, 100, 30, 15, 30, 20, 40 ); ctrl.MLC_CMD = 0xFF; while(ctrl.MLC_ISR.NandReady == false) { } { var val = new ChipsetModel.MultiLevelNANDController.MLC_ICR_bitfield(); val.ChipWordAddress = ChipsetModel.MultiLevelNANDController.MLC_ICR_bitfield.Addressing.ThreeWords; ctrl.MLC_LOCK_PR = ChipsetModel.MultiLevelNANDController.MLC_LOCK_PR__UnlockValue; ctrl.MLC_ICR = val; } } private void InitializeDRAMController( uint hclkMHz ) { if(Processor.Configuration.Use32BitBus) { // Address mapping(AM) -> 32-bit external bus low-power SDRAM address mapping : // 128Mb (8Mx16), 4 banks, row length = 12, column length = 9 => Cfg Register values should be shifted left by 11 bits. ChipsetModel.SDRAMController.InitializeLowPowerSDR( hclkMHz, ChipsetModel.SDRAMController.MPMCDynamicConfig0_bitfield.SizeMode.Size_128Mb_8Mx16, true, 0x30u << 11, 0x2058u << 11 ); } else { // Address mapping(AM) -> 16-bit external bus low-power SDRAM address mapping : // 128Mb (8Mx16), 4 banks, row length = 12, column length = 9 => Cfg Register values should be shifted left by 10 bits. ChipsetModel.SDRAMController.InitializeLowPowerSDR( hclkMHz, ChipsetModel.SDRAMController.MPMCDynamicConfig0_bitfield.SizeMode.Size_128Mb_8Mx16, false, 0x31u << 10, 0x2058u << 10 ); } } [RT.DisableNullChecks( ApplyRecursively=true )] [RT.DisableBoundsChecks( ApplyRecursively=true )] private unsafe void ExecuteImageRelocation() { Memory.RelocationInfo[] array = Memory.Instance.RelocationData; for(int i = 0; i < array.Length; i++) { Memory.RelocationInfo ri = array[i]; uint* dst = (uint*)ri.Destination.ToPointer(); if(ri.IsEraseBlock) { uint count = ri.SizeInWords; while(count != 0) { *dst++ = 0; count--; } } else { uint start = ri.Start.ToUInt32(); uint end = ri.End .ToUInt32(); uint skipCount = 0; while(start < end) { uint address = start & ~(c_PageSize - 1); uint offset = (start - address); uint expectedLogicalAddress = address & (c_ChipSize - 1); skipCount = ReadLogicalPage( expectedLogicalAddress, skipCount ); fixed(uint* ptr = &s_Page[0]) { uint count = Math.Min( (c_PageSize - offset), (end - start) ); uint* src = ptr + offset / sizeof(uint); uint* srcEnd = src + count / sizeof(uint); while(src < srcEnd) { *dst++ = *src++; } start += count; } } } } } [RT.NoInline] [RT.MemoryUsage(RT.MemoryUsage.Bootstrap)] [RT.DisableNullChecks( ApplyRecursively=true )] [RT.DisableBoundsChecks( ApplyRecursively=true )] private static unsafe uint ReadLogicalPage( uint expectedLogicalAddress , uint skipCount ) { while(true) { uint physicalAddress = expectedLogicalAddress + skipCount * c_BlockSize; if(ReadPage( physicalAddress ) == false) { // // Bad CRC, try skipping a block. // skipCount++; continue; } // // The first 32bit word of the spare area is the logical address of the page. // uint logicalAddress = ((uint)s_Spare[0] ) | ((uint)s_Spare[1] << 16) ; if(expectedLogicalAddress != logicalAddress) { if(physicalAddress < logicalAddress) { // // We always move blocks forward, so the physical address will always be higher than the logical one. // RT.BugCheck.Raise( RT.BugCheck.StopCode.FailedBootstrap ); } // // Move forward and try again. // skipCount++; continue; } return skipCount; } } [RT.DisableNullChecks()] [RT.MemoryUsage(RT.MemoryUsage.Bootstrap)] public static unsafe bool ReadPage( uint address ) { var ctrl = ChipsetModel.MultiLevelNANDController.Instance; uint pageAddress = address / 512; ctrl.MLC_CMD = 0x00; // Select Page A ctrl.MLC_ADDR = 0; ctrl.MLC_ADDR = (pageAddress >> 0) & 0xFF; ctrl.MLC_ADDR = (pageAddress >> 8) & 0xFF; //// ctrl.MLC_ADDR = (pageAddress >> 16) & 0xFF; // Used for 4-word address chips. ctrl.MLC_ECC_AUTO_DEC_REG = 0; //--// while(true) { var val = ctrl.MLC_ISR; if(val.ControllerReady == false) { continue; } if(val.DecoderFailure) { for(int i = 0; i < s_Page.Length; i++) { s_Page[i] = ctrl.MLC_BUFF_32bits[0]; } for(int i = 0; i < s_Spare.Length; i++) { s_Spare[i] = ctrl.MLC_BUFF_16bits[0]; } return false; } break; } for(int i = 0; i < s_Page.Length; i++) { s_Page[i] = ctrl.MLC_BUFF_32bits[0]; } for(int i = 0; i < s_Spare.Length; i++) { s_Spare[i] = ctrl.MLC_BUFF_16bits[0]; } return true; } } } ================================================ FILE: Zelig/Zelig/RunTime/DeviceModels/NohauLPC3180/HardwareModel/Drivers/InterruptController.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // namespace Microsoft.NohauLPC3180.Drivers { using System; using System.Runtime.CompilerServices; using RT = Microsoft.Zelig.Runtime; using ChipsetModel = Microsoft.DeviceModels.Chipset.LPC3180; public sealed class InterruptController : ChipsetModel.Drivers.InterruptController { } } ================================================ FILE: Zelig/Zelig/RunTime/DeviceModels/NohauLPC3180/HardwareModel/Drivers/RealTimeClock.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // namespace Microsoft.NohauLPC3180.Drivers { using System; using System.Runtime.CompilerServices; using RT = Microsoft.Zelig.Runtime; using ChipsetModel = Microsoft.DeviceModels.Chipset.LPC3180; public sealed class RealTimeClock : ChipsetModel.Drivers.RealTimeClock { } } ================================================ FILE: Zelig/Zelig/RunTime/DeviceModels/NohauLPC3180/HardwareModel/Memory.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // namespace Microsoft.NohauLPC3180 { using System; using RT = Microsoft.Zelig.Runtime; using TS = Microsoft.Zelig.Runtime.TypeSystem; public sealed class Memory : RT.Memory { public override void InitializeMemory() { } } } ================================================ FILE: Zelig/Zelig/RunTime/DeviceModels/NohauLPC3180/HardwareModel/Peripherals.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // //#define ALLOW_STOP namespace Microsoft.NohauLPC3180 { using System; using System.Runtime.CompilerServices; using RT = Microsoft.Zelig.Runtime; using TS = Microsoft.Zelig.Runtime.TypeSystem; using ChipsetModel = Microsoft.DeviceModels.Chipset.LPC3180; public sealed unsafe class Peripherals : RT.Peripherals { // // State // private uint* m_performanceCounter; // // Helper Methods // public override void Initialize() { } public override void Activate() { Drivers.InterruptController.Instance.Initialize(); Drivers.RealTimeClock.Instance.Initialize(); RT.SerialPortsManager.Instance.Initialize(); } public override void EnableInterrupt( uint index ) { } public override void DisableInterrupt( uint index ) { } public override void CauseInterrupt() { Drivers.InterruptController.Instance.CauseInterrupt(); } public override void ContinueUnderNormalInterrupt( Continuation dlg ) { Drivers.InterruptController.Instance.ContinueUnderNormalInterrupt( dlg ); } [RT.MemoryRequirements( RT.MemoryAttributes.InternalMemory )] public override void WaitForInterrupt() { #if ALLOW_STOP using(RT.SmartHandles.InterruptState.DisableAll()) { var ctrl = ChipsetModel.SystemControl.Instance; if(ctrl.START_SR_INT == 0) { ctrl.SwitchToDirectRunMode(); ctrl.SwitchToStopModeWithSDRAM(); ctrl.Stabilize12vSupply(); ctrl.LockHCLKPLL(); ctrl.SwitchToRunMode(); } ctrl.START_RSR_INT = ctrl.START_SR_INT; } #else RT.TargetPlatform.ARMv4.Coprocessor15.WaitForInterrupt(); #endif } public override void ProcessInterrupt() { using(RT.SmartHandles.SwapCurrentThreadUnderInterrupt hnd = ThreadManager.InstallInterruptThread()) { Drivers.InterruptController.Instance.ProcessInterrupt(); } } [RT.MemoryRequirements( RT.MemoryAttributes.RAM )] public override void ProcessFastInterrupt() { using(RT.SmartHandles.SwapCurrentThreadUnderInterrupt hnd = ThreadManager.InstallFastInterruptThread()) { Drivers.InterruptController.Instance.ProcessFastInterrupt(); } } public override ulong GetPerformanceCounterFrequency() { return Processor.Configuration.PeripheralsClockFrequency; } public override unsafe uint ReadPerformanceCounter() { uint* ptr = m_performanceCounter; if(ptr == null) { ptr = AllocatePerformanceCounter(); } return *ptr; } //--// private unsafe uint* AllocatePerformanceCounter() { { var val = new ChipsetModel.SystemControl.TIMCLK_CTRL_bitfield(); val.HSTimer_Enable = true; ChipsetModel.SystemControl.Instance.TIMCLK_CTRL = val; } //--// ChipsetModel.HighSpeedTimer timer = ChipsetModel.HighSpeedTimer.Instance; timer.HSTIM_COUNTER = 0; { var val = new ChipsetModel.HighSpeedTimer.HSTIM_MCTRL_bitfield(); // No interrupts for now. timer.HSTIM_MCTRL = val; } { var val = new ChipsetModel.HighSpeedTimer.HSTIM_CTRL_bitfield(); val.COUNT_ENAB = true; val.PAUSE_EN = true; // Allow hardware debugging to stop the counter. timer.HSTIM_CTRL = val; } //--// fixed(uint* ptr = &timer.HSTIM_COUNTER) { m_performanceCounter = ptr; } return m_performanceCounter; } } } ================================================ FILE: Zelig/Zelig/RunTime/DeviceModels/NohauLPC3180/HardwareModel/Processor.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // namespace Microsoft.NohauLPC3180 { using System; using RT = Microsoft.Zelig.Runtime; using TS = Microsoft.Zelig.Runtime.TypeSystem; using ChipsetModel = Microsoft.DeviceModels.Chipset.LPC3180; public sealed class Processor : ChipsetModel.Processor { const uint c_IRAM__BaseAddress = 0x08000000; const uint c_IRAM__Size = 64 * 1024; const uint c_DRAM__BaseAddress = 0x80000000; const uint c_DRAM__Size = 32 * 1024 * 1024; const uint c_Peripherals1__BaseAddress = 0x20000000; const uint c_Peripherals1__EndAddress = 0x200C0000; const uint c_Peripherals2__BaseAddress = 0x30000000; const uint c_Peripherals2__EndAddress = 0x32000000; const uint c_Peripherals3__BaseAddress = 0x40000000; const uint c_Peripherals3__EndAddress = 0x40100000; [RT.AlignmentRequirements( RT.TargetPlatform.ARMv4.MMUv4.c_TLB_SecondLevelSize, sizeof(uint) )] static uint[] s_TLB_SecondLevel_IRAM = new uint[RT.TargetPlatform.ARMv4.MMUv4.c_TLB_SecondLevelSlots]; // // Helper Methods // public override void InitializeProcessor() { base.InitializeProcessor(); ConfigureMMU(); } private static void ConfigureMMU() { RT.TargetPlatform.ARMv4.MMUv4.ClearTLB(); RT.TargetPlatform.ARMv4.MMUv4.AddCoarsePages ( 0, 0 + c_IRAM__Size , s_TLB_SecondLevel_IRAM ); RT.TargetPlatform.ARMv4.MMUv4.AddCoarsePages ( c_IRAM__BaseAddress, c_IRAM__BaseAddress + c_IRAM__Size , s_TLB_SecondLevel_IRAM ); RT.TargetPlatform.ARMv4.MMUv4.AddCacheableSection ( c_DRAM__BaseAddress, c_DRAM__BaseAddress + c_DRAM__Size, c_DRAM__BaseAddress ); RT.TargetPlatform.ARMv4.MMUv4.AddUncacheableSection( c_Peripherals1__BaseAddress, c_Peripherals1__EndAddress, c_Peripherals1__BaseAddress ); RT.TargetPlatform.ARMv4.MMUv4.AddUncacheableSection( c_Peripherals2__BaseAddress, c_Peripherals2__EndAddress, c_Peripherals2__BaseAddress ); RT.TargetPlatform.ARMv4.MMUv4.AddUncacheableSection( c_Peripherals3__BaseAddress, c_Peripherals3__EndAddress, c_Peripherals3__BaseAddress ); RT.TargetPlatform.ARMv4.MMUv4.AddCacheableCoarsePages( 0, 0 + c_IRAM__Size, c_IRAM__BaseAddress, s_TLB_SecondLevel_IRAM ); RT.TargetPlatform.ARMv4.MMUv4.EnableTLB(); } //--// [RT.BottomOfCallStack()] [RT.HardwareExceptionHandler(RT.HardwareException.Interrupt)] private static void InterruptHandler( ref Context.RegistersOnStack registers ) { Context.InterruptHandlerWithContextSwitch( ref registers ); } [RT.BottomOfCallStack()] [RT.HardwareExceptionHandler(RT.HardwareException.FastInterrupt)] [RT.MemoryRequirements( RT.MemoryAttributes.RAM )] private static void FastInterruptHandler() { Context.FastInterruptHandlerWithoutContextSwitch(); } [RT.BottomOfCallStack()] [RT.HardwareExceptionHandler(RT.HardwareException.SoftwareInterrupt)] private static void SoftwareInterruptHandler( ref Context.RegistersOnStack registers ) { Context.GenericSoftwareInterruptHandler( ref registers ); } } } ================================================ FILE: Zelig/Zelig/RunTime/DeviceModels/NohauLPC3180/HardwareModel/Storage.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // namespace Microsoft.NohauLPC3180 { using System; using RT = Microsoft.Zelig.Runtime; using TS = Microsoft.Zelig.Runtime.TypeSystem; public sealed class Storage : RT.Storage { const uint DRAMSize = 1 * 8 * 1024 * 1024; const uint DRAMBase = 0x80000000 + DRAMSize; const uint DRAMEnd = DRAMBase + DRAMSize; const uint DRAMMask = ~(DRAMSize - 1); const byte ErasedValueByte = (byte)0xFFu; const ushort ErasedValue = (ushort)0xFFFFu; const uint ErasedValuePair = 0xFFFFFFFFu; // // State // // // Helper Methods // public override unsafe void InitializeStorage() { EraseSectors( new UIntPtr( DRAMBase ), new UIntPtr( DRAMEnd ) ); } //--// public override unsafe bool EraseSectors( UIntPtr addressStart , UIntPtr addressEnd ) { if(ValidateAddress ( addressStart ) && ValidateAddressPlus1( addressEnd ) ) { Memory.Fill( addressStart, addressEnd, 0xFF ); return true; } return false; } public override unsafe bool WriteByte( UIntPtr address , byte val ) { if(ValidateAddress( address )) { byte* ptr = (byte*)address.ToPointer(); *ptr = val; return true; } return false; } public override unsafe bool WriteShort( UIntPtr address , ushort val ) { if(IsOddAddress( address )) { return WriteByte( address, (byte) val ) && WriteByte( Microsoft.Zelig.AddressMath.Increment( address, 1 ), (byte)(val >> 8) ) ; } else { if(ValidateAddress( address )) { ushort* wordAddress = (ushort*)address.ToPointer(); *wordAddress = val; return true; } return false; } } public override bool WriteWord( UIntPtr address , uint val ) { if(IsOddAddress( address )) { return WriteByte ( address, (byte ) val ) && WriteShort( Microsoft.Zelig.AddressMath.Increment( address, 1 ), (ushort)(val >> 8) ) && WriteByte ( Microsoft.Zelig.AddressMath.Increment( address, 3 ), (byte )(val >> 24) ) ; } else { return WriteShort( address, (ushort) val ) && WriteShort( Microsoft.Zelig.AddressMath.Increment( address, 2 ), (ushort)(val >> 16) ) ; } } public override bool Write( UIntPtr address , byte[] buffer , uint offset , uint numBytes ) { if(numBytes > 0) { if(IsOddAddress( address )) { if(WriteByte( address, buffer[offset] ) == false) { return false; } address = Microsoft.Zelig.AddressMath.Increment( address, 1 ); offset += 1; numBytes -= 1; } while(numBytes >= 2) { uint val; val = (uint)buffer[ offset++ ]; val |= (uint)buffer[ offset++ ] << 8; if(WriteShort( address, (ushort)val ) == false) { return false; } address = Microsoft.Zelig.AddressMath.Increment( address, 2 ); numBytes -= 2; } if(numBytes != 0) { if(WriteByte( address, buffer[offset] ) == false) { return false; } } } return true; } //--// public override unsafe byte ReadByte( UIntPtr address ) { if(ValidateAddress( address )) { byte* ptr = (byte*)address.ToPointer(); return ptr[0]; } return ErasedValueByte; } public override unsafe ushort ReadShort( UIntPtr address ) { if(ValidateAddress( address )) { byte* ptr = (byte*)address.ToPointer(); return (ushort)((uint)ptr[0] | (uint)ptr[1] << 8 ); } return ErasedValue; } public override unsafe uint ReadWord( UIntPtr address ) { if(ValidateAddress( address )) { byte* ptr = (byte*)address.ToPointer(); return ((uint)ptr[0] | (uint)ptr[1] << 8 | (uint)ptr[2] << 16 | (uint)ptr[3] << 24 ); } return ErasedValuePair; } public override void Read( UIntPtr address , byte[] buffer , uint offset , uint numBytes ) { while(numBytes != 0) { buffer[offset++] = ReadByte( address ); address = Microsoft.Zelig.AddressMath.Increment( address, 1 ); numBytes--; } } public override void SubstituteFirmware( UIntPtr addressDestination , UIntPtr addressSource , uint numBytes ) { throw new NotImplementedException(); } public override void RebootDevice() { throw new System.NotImplementedException(); } //--// [RT.Inline] static bool ValidateAddress( UIntPtr address ) { if(Zelig.AddressMath.IsLessThan( address, new UIntPtr( DRAMBase ) )) { return false; } if(Zelig.AddressMath.IsGreaterThanOrEqual( address, new UIntPtr( DRAMEnd ) )) { return false; } return true; } [RT.Inline] static bool ValidateAddressPlus1( UIntPtr address ) { if(Zelig.AddressMath.IsLessThanOrEqual( address, new UIntPtr( DRAMBase ) )) { return false; } if(Zelig.AddressMath.IsGreaterThan( address, new UIntPtr( DRAMEnd ) )) { return false; } return true; } [RT.Inline] static bool IsOddAddress( UIntPtr address ) { return Zelig.AddressMath.IsAlignedTo16bits( address ) == false; } } } ================================================ FILE: Zelig/Zelig/RunTime/DeviceModels/NohauLPC3180/NohauLPC3180.csproj ================================================  Debug AnyCPU 9.0.21022 2.0 {186F31A3-EF89-4A25-B2D5-20071018AA01} Library Properties Microsoft.NohauLPC3180 Microsoft.NohauLPC3180 $(LlilumBuildRoot)\Target\obj\$(MSBuildProjectName)\ v4.5 true full false $(LlilumBuildRoot)\Target\bin\$(Configuration)\ DEBUG;TRACE prompt 4 true true true AllRules.ruleset AnyCPU false pdbonly true $(LlilumBuildRoot)\Target\bin\$(Configuration)\ TRACE prompt 4 true true true AllRules.ruleset AnyCPU false true full false $(LlilumBuildRoot)\Target\bin\$(Configuration)\ AnyCPU true DEBUG;TRACE true true false {186F31A3-EF89-4A25-B2D5-20060501AA01} mscorlib False {186F31A3-EF89-4A25-B2D5-20061218AA01} Common False {186F31A3-EF89-4A25-B2D5-20060509AA01} Kernel False {186F31A3-EF89-4A25-B2D5-20060720AA01} TypeSystem False {186F31A3-EF89-4A25-B2D5-20070911AA01} ModelForLPC3180 False 3.5 ================================================ FILE: Zelig/Zelig/RunTime/DeviceModels/NohauLPC3180/Properties/AssemblyInfo.cs ================================================ using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; // General Information about an assembly is controlled through the following // set of attributes. Change these attribute values to modify the information // associated with an assembly. [assembly: AssemblyTitle( "Microsoft.NohauLPC3180" )] [assembly: AssemblyDescription( "" )] [assembly: AssemblyConfiguration( "" )] [assembly: AssemblyCompany( "Microsoft" )] [assembly: AssemblyProduct( "Microsoft.NohauLPC3180" )] [assembly: AssemblyCopyright( "Copyright © Microsoft 2007" )] [assembly: AssemblyTrademark( "" )] [assembly: AssemblyCulture( "" )] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible( false )] //// The following GUID is for the ID of the typelib if this project is exposed to COM //[assembly: Guid( "975a7db2-22e5-41c6-9e32-d3f72152d387" )] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Revision and Build Numbers // by using the '*' as shown below: [assembly: AssemblyVersion( "1.0.0.0" )] [assembly: AssemblyFileVersion( "1.0.0.0" )] ================================================ FILE: Zelig/Zelig/RunTime/DeviceModels/NohauLPC3180/SystemServices/GarbageCollectionManager.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // namespace Microsoft.NohauLPC3180 { using System; using RT = Microsoft.Zelig.Runtime; using TS = Microsoft.Zelig.Runtime.TypeSystem; public sealed class GarbageCollectionManager : RT.PreciseMarkAndSweepCollector { } } ================================================ FILE: Zelig/Zelig/RunTime/DeviceModels/NohauLPC3180/SystemServices/MemoryManager.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // namespace Microsoft.NohauLPC3180 { using System; using RT = Microsoft.Zelig.Runtime; using TS = Microsoft.Zelig.Runtime.TypeSystem; public sealed class MemoryManager : RT.LinearMemoryManager { } } ================================================ FILE: Zelig/Zelig/RunTime/DeviceModels/NohauLPC3180/SystemServices/SerialPortsManager.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // namespace Microsoft.NohauLPC3180 { using System; using RT = Microsoft.Zelig.Runtime; using TS = Microsoft.Zelig.Runtime.TypeSystem; public sealed class SerialPortsManager : Microsoft.DeviceModels.Chipset.LPC3180.Runtime.SerialPortsManager { } } ================================================ FILE: Zelig/Zelig/RunTime/DeviceModels/NohauLPC3180/SystemServices/ThreadManager.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // namespace Microsoft.NohauLPC3180 { using System; using RT = Microsoft.Zelig.Runtime; using TS = Microsoft.Zelig.Runtime.TypeSystem; using ChipsetModel = Microsoft.DeviceModels.Chipset.LPC3180; public sealed class ThreadManager : ChipsetModel.Runtime.ThreadManager { } } ================================================ FILE: Zelig/Zelig/RunTime/DeviceModels/NohauLPC3180/SystemServices/TypeSystemManager.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // namespace Microsoft.NohauLPC3180 { using System; using RT = Microsoft.Zelig.Runtime; using TS = Microsoft.Zelig.Runtime.TypeSystem; public sealed class TypeSystemManager : RT.DefaultTypeSystemManager { } } ================================================ FILE: Zelig/Zelig/RunTime/DeviceModels/NohauLPC3180Loader/HardwareModel/Device.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // namespace Microsoft.NohauLPC3180Loader { using System; using System.Runtime.CompilerServices; using RT = Microsoft.Zelig.Runtime; using ChipsetModel = Microsoft.DeviceModels.Chipset.LPC3180; public sealed class Device : RT.Device { public override void PreInitializeProcessorAndMemory() { // // Enter System mode, with interrupts disabled. // Processor.SetStatusRegister( Processor.c_psr_field_c, Processor.c_psr_I | Processor.c_psr_F | Processor.c_psr_mode_SYS ); Processor.SetRegister( Processor.Context.RegistersOnStack.StackRegister, this.BootstrapStackPointer ); Processor.PreInitializeProcessor( Processor.Configuration.SYSCLK, (uint)Processor.Configuration.CoreClockFrequency, (uint)Processor.Configuration.AHBClockFrequency, (uint)Processor.Configuration.PeripheralsClockFrequency ); } public override void MoveCodeToProperLocation() { Memory.Instance.ExecuteImageRelocation(); } } } ================================================ FILE: Zelig/Zelig/RunTime/DeviceModels/NohauLPC3180Loader/HardwareModel/Drivers/InterruptController.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // namespace Microsoft.NohauLPC3180Loader.Drivers { using System; using System.Runtime.CompilerServices; using RT = Microsoft.Zelig.Runtime; using ChipsetModel = Microsoft.DeviceModels.Chipset.LPC3180; public sealed class InterruptController : ChipsetModel.Drivers.InterruptController { } } ================================================ FILE: Zelig/Zelig/RunTime/DeviceModels/NohauLPC3180Loader/HardwareModel/Drivers/RealTimeClock.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // namespace Microsoft.NohauLPC3180Loader.Drivers { using System; using System.Runtime.CompilerServices; using RT = Microsoft.Zelig.Runtime; using ChipsetModel = Microsoft.DeviceModels.Chipset.LPC3180; public sealed class RealTimeClock : ChipsetModel.Drivers.RealTimeClock { } } ================================================ FILE: Zelig/Zelig/RunTime/DeviceModels/NohauLPC3180Loader/HardwareModel/Memory.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // namespace Microsoft.NohauLPC3180Loader { using System; using RT = Microsoft.Zelig.Runtime; using TS = Microsoft.Zelig.Runtime.TypeSystem; public sealed class Memory : RT.Memory { public override void InitializeMemory() { } } } ================================================ FILE: Zelig/Zelig/RunTime/DeviceModels/NohauLPC3180Loader/HardwareModel/Peripherals.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // namespace Microsoft.NohauLPC3180Loader { using System; using System.Runtime.CompilerServices; using RT = Microsoft.Zelig.Runtime; using TS = Microsoft.Zelig.Runtime.TypeSystem; public sealed class Peripherals : RT.Peripherals { public override void Initialize() { } public override void Activate() { } public override void EnableInterrupt( uint index ) { } public override void DisableInterrupt( uint index ) { } public override void CauseInterrupt() { } public override void WaitForInterrupt() { } public override void ContinueUnderNormalInterrupt( Continuation dlg ) { } public override void ProcessInterrupt() { } public override void ProcessFastInterrupt() { } public override ulong GetPerformanceCounterFrequency() { return 0; } public override unsafe uint ReadPerformanceCounter() { return 0; } } } ================================================ FILE: Zelig/Zelig/RunTime/DeviceModels/NohauLPC3180Loader/HardwareModel/Processor.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // namespace Microsoft.NohauLPC3180Loader { using System; using RT = Microsoft.Zelig.Runtime; using TS = Microsoft.Zelig.Runtime.TypeSystem; using ChipsetModel = Microsoft.DeviceModels.Chipset.LPC3180; public sealed class Processor : ChipsetModel.Processor { // // Helper Methods // public override void InitializeProcessor() { } public override UIntPtr GetCacheableAddress( UIntPtr ptr ) { return ptr; } public override UIntPtr GetUncacheableAddress( UIntPtr ptr ) { return ptr; } public override unsafe void FlushCacheLine( UIntPtr target ) { } //--// [RT.Inline] public override RT.Processor.Context AllocateProcessorContext(RT.ThreadImpl owner) { return null; } } } ================================================ FILE: Zelig/Zelig/RunTime/DeviceModels/NohauLPC3180Loader/HardwareModel/Storage.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // namespace Microsoft.NohauLPC3180Loader { using System; using RT = Microsoft.Zelig.Runtime; using TS = Microsoft.Zelig.Runtime.TypeSystem; public sealed class Storage : RT.Storage { // // Helper Methods // public override void InitializeStorage() { } //--// public override bool EraseSectors( UIntPtr addressStart , UIntPtr addressEnd ) { return false; } public override bool WriteByte( UIntPtr address , byte val ) { return false; } public override bool WriteShort( UIntPtr address , ushort val ) { return false; } public override bool WriteWord( UIntPtr address , uint val ) { return false; } public override bool Write( UIntPtr address , byte[] buffer , uint offset , uint numBytes ) { return false; } //--// public override unsafe byte ReadByte( UIntPtr address ) { return 0; } public override unsafe ushort ReadShort( UIntPtr address ) { return 0; } public override unsafe uint ReadWord( UIntPtr address ) { return 0; } public override void Read( UIntPtr address , byte[] buffer , uint offset , uint numBytes ) { } public override void SubstituteFirmware( UIntPtr addressDestination , UIntPtr addressSource , uint numBytes ) { } public override void RebootDevice() { throw new System.NotImplementedException(); } } } ================================================ FILE: Zelig/Zelig/RunTime/DeviceModels/NohauLPC3180Loader/Loader.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // //#define ENABLE_TRACING //#define ENABLE_TRACING_VERBOSE //#define TEST_FP //#define TEST_VFP //#define TEST_STRUCT //#define TEST_ARRAYBOUNDCHECKS //#define DCC_TEST_HALFDUPLEX //#define DCC_TEST_FULLDUPLEX namespace Microsoft.NohauLPC3180Loader { using System; using System.Collections.Generic; using System.Runtime.CompilerServices; using RT = Microsoft.Zelig.Runtime; using TS = Microsoft.Zelig.Runtime.TypeSystem; using ChipsetModel = Microsoft.DeviceModels.Chipset.LPC3180; // // Override stock bootstrap code, to avoid including most of the code. // [RT.ExtendClass(typeof(RT.Bootstrap))] public static class BootstrapImpl { [RT.NoInline] [RT.NoReturn] private static void Initialization() { Processor.Instance.InitializeProcessor(); //--// RT.Configuration.ExecuteApplication(); } } [RT.ExtendClass(typeof(RT.TypeSystemManager),NoConstructors=true)] public class TypeSystemManagerImpl { public void DeliverException( Exception obj ) { } } class Loader { const uint cmd_Signature = 0xDEADC000; const uint cmd_Mask = 0xFFFFFF00; const byte cmd_Hello = 0x01; const byte cmd_GetConfig = 0x02; // => const byte cmd_ReadPage = 0x03; // Arg: Address => const byte cmd_ReadSpare = 0x04; // Arg: Address => const byte cmd_ChecksumMemory = 0x05; // Arg: Address => , const byte cmd_EraseBlock = 0x06; // Arg: Address => const byte cmd_ProgramPage = 0x07; // Arg: Address, # pages [bytes] => .... //--// const int c_PageCount = 65536; const int c_PageSize = 512; const int c_SpareSize = 16; const int c_UsableSpareSize = 6; const int c_BlockSize = 16384; static readonly uint [] s_Page = new uint [c_PageSize / sizeof(uint )]; static readonly ushort[] s_Spare = new ushort[c_SpareSize / sizeof(ushort)]; [RT.DisableNullChecks()] static unsafe void Initialize() { var flashclk = new ChipsetModel.SystemControl.FLASHCLK_CTRL_bitfield(); flashclk.InterruptFromMLC = true; flashclk.MLC_ClockEnable = true; ChipsetModel.SystemControl.Instance.FLASHCLK_CTRL = flashclk; //--// var ctrl = ChipsetModel.MultiLevelNANDController.Instance; ctrl.SetTimingRegister( 104, 45, 100, 30, 15, 30, 20, 40 ); ctrl.MLC_CMD = 0xFF; while(ctrl.MLC_ISR.NandReady == false) { } { var val = new ChipsetModel.MultiLevelNANDController.MLC_ICR_bitfield(); val.ChipWordAddress = ChipsetModel.MultiLevelNANDController.MLC_ICR_bitfield.Addressing.ThreeWords; ctrl.MLC_LOCK_PR = ChipsetModel.MultiLevelNANDController.MLC_LOCK_PR__UnlockValue; ctrl.MLC_ICR = val; } //--// DebugInitialize(); } //--// [System.Diagnostics.Conditional( "ENABLE_TRACING" )] static void DebugInitialize() { ChipsetModel.StandardUART.Instance.Configure( ChipsetModel.StandardUART.Id.UART5, false, 2 * 115200 ); } [System.Diagnostics.Conditional( "ENABLE_TRACING" )] static void DebugPrint( string text ) { ChipsetModel.StandardUART.Instance.Ports[(int)ChipsetModel.StandardUART.Id.UART5].DEBUG_WriteLine( text ); } [System.Diagnostics.Conditional( "ENABLE_TRACING" )] static void DebugPrint( string text , uint value ) { ChipsetModel.StandardUART.Instance.Ports[(int)ChipsetModel.StandardUART.Id.UART5].DEBUG_WriteLine( text, value ); } [System.Diagnostics.Conditional( "ENABLE_TRACING_VERBOSE" )] static void DebugPrintVerbose( string text , uint value ) { DebugPrint( text, value ); } [System.Diagnostics.Conditional( "ENABLE_TRACING" )] static void DebugChar( char c ) { ChipsetModel.StandardUART.Instance.Ports[(int)ChipsetModel.StandardUART.Id.UART5].DEBUG_Write( c ); } //--// //// [RT.DisableNullChecks()] //// static unsafe uint ReadID() //// { //// var ctrl = ChipsetModel.MultiLevelNANDController.Instance; //// uint id = 0; //// //// ctrl.MLC_CMD = 0x90; //// ctrl.MLC_ADDR = 0; //// //// id |= (uint)ctrl.MLC_DATA_8bits[0] << 24; //// id |= (uint)ctrl.MLC_DATA_8bits[0] << 16; //// id |= (uint)ctrl.MLC_DATA_8bits[0] << 8; //// id |= (uint)ctrl.MLC_DATA_8bits[0] << 0; //// //// return id; //// } [RT.NoInline] static float ComputeTest1( float a , float b ) { float res; res = a * b; res += a + b; res += a - b; res += a / b; return res; } [RT.NoInline] static double ComputeTest2( double a , double b ) { double res; res = a * b; res += a + b; res += a - b; res += a / b; return res; } [RT.NoInline] static int ComputeTest3( int a ) { float tmp = a; return (int)(tmp * 3.5); } [RT.NoInline] static long ComputeTest4( long a ) { float tmp = a; return (long)(tmp * 3.5); } [RT.NoInline] static int ComputeTest5( int a ) { double tmp = a; return (int)(tmp * 3.5); } [RT.NoInline] static long ComputeTest6( long a ) { double tmp = a; return (long)(tmp * 3.5); } [RT.NoInline] static float ComputeTest7( int a ) { int tmp; ComputeTest8( a, out tmp ); return (float)tmp; } [RT.NoInline] static void ComputeTest8( int a , out int b ) { b = a; } [RT.NoInline] [RT.SaveFullProcessorContext] private static void TestPushContext() { } [RT.DisableNullChecks()] static unsafe bool ReadPage( uint address ) { var ctrl = ChipsetModel.MultiLevelNANDController.Instance; DebugPrint( "Read Page: ", address ); uint pageAddress = address / 512; ctrl.MLC_CMD = 0x00; // Select Page A ctrl.MLC_ADDR = 0; ctrl.MLC_ADDR = (pageAddress >> 0) & 0xFF; ctrl.MLC_ADDR = (pageAddress >> 8) & 0xFF; //// ctrl.MLC_ADDR = (pageAddress >> 16) & 0xFF; // Used for 4-word address chips. ctrl.MLC_ECC_AUTO_DEC_REG = 0; //--// while(true) { var val = ctrl.MLC_ISR; if(val.ControllerReady == false) { continue; } if(val.DecoderFailure) { DebugPrint( "Failed: ", val.SymbolErrors ); for(int i = 0; i < s_Page.Length; i++) { s_Page[i] = ctrl.MLC_BUFF_32bits[0]; } for(int i = 0; i < s_Spare.Length; i++) { s_Spare[i] = ctrl.MLC_BUFF_16bits[0]; } return false; } break; } for(int i = 0; i < s_Page.Length; i++) { s_Page[i] = ctrl.MLC_BUFF_32bits[0]; //// DebugPrint( "Data: ", s_Page[i] ); } for(int i = 0; i < s_Spare.Length; i++) { s_Spare[i] = ctrl.MLC_BUFF_16bits[0]; } return true; } [RT.DisableNullChecks()] static unsafe bool ProgramPage( uint address ) { var ctrl = ChipsetModel.MultiLevelNANDController.Instance; DebugPrint( "Program Page: ", address ); uint pageAddress = address / 512; ctrl.MLC_CMD = 0x00; // Select Page A ctrl.MLC_CMD = 0x80; // Page Program Setup Code ctrl.MLC_ADDR = 0; ctrl.MLC_ADDR = (pageAddress >> 0) & 0xFF; ctrl.MLC_ADDR = (pageAddress >> 8) & 0xFF; //// ctrl.MLC_ADDR = (pageAddress >> 16) & 0xFF; // Used for 4-word address chips. ctrl.MLC_ECC_ENC_REG = 0; // Start encoding. for(int i = 0; i < s_Page.Length; i++) { ctrl.MLC_BUFF_32bits[0] = s_Page[i]; } for(int i = 0; i < c_UsableSpareSize / sizeof(ushort); i++) { ctrl.MLC_BUFF_16bits[0] = s_Spare[i]; } ctrl.MLC_ECC_AUTO_ENC_REG = 0x110; // Auto-Program //--// while(ctrl.MLC_ISR.ControllerReady == false) { } //--// ctrl.MLC_CMD = 0x70; // Read Status Register uint status = ctrl.MLC_DATA_8bits[0]; DebugPrint( "Status: ", status ); return (status & 1) == 0; } [RT.DisableNullChecks()] static unsafe bool EraseBlock( uint address ) { var ctrl = ChipsetModel.MultiLevelNANDController.Instance; DebugPrint( "Erase Block: ", address ); uint pageAddress = address / 512; ctrl.MLC_CMD = 0x60; // Block Erase Setup Code ctrl.MLC_ADDR = (pageAddress >> 0) & 0xFF; ctrl.MLC_ADDR = (pageAddress >> 8) & 0xFF; //// ctrl.MLC_ADDR = (pageAddress >> 16) & 0xFF; // Used for 4-word address chips. ctrl.MLC_CMD = 0xD0; // Confirm Code //--// while(ctrl.MLC_ISR.ControllerReady == false) { } //--// ctrl.MLC_CMD = 0x70; // Read Status Register uint status = ctrl.MLC_DATA_8bits[0]; DebugPrint( "Status: ", status ); return (status & 1) == 0; } //--// #if TEST_FP static float t1; static double t2; static int t3; static long t4; static int t5; static long t6; static float t7; #endif #if TEST_STRUCT public struct Holder : IDisposable { // // State // object m_thread; long m_timeout; ushort[] m_array; // // Constructor Methods // public Holder( object thread , long timeout , ushort[] array ) { m_thread = thread; m_timeout = timeout; m_array = array; } // // Helper Methods // public void Dispose() { if(m_array != null) { m_thread = null; } } // // Access Methods // public bool RequestFulfilled { [RT.NoInline] get { return m_array != null; } } } [RT.NoInline] private static void TestStack() { using(Holder holder = new Holder( s_Page, 0, s_Spare )) { if(holder.RequestFulfilled) { TestStack_Sub(); } } } [RT.NoInline] private static void TestStack_Sub() { } #endif #if TEST_ARRAYBOUNDCHECKS public static uint Sqrt( uint v ) { uint r = 0, s = 0; for (int i = 15; i >= 0; i--) { s = r + (uint)(1 << i * 2); r >>= 1; if (s <= v) { v -= s; r |= (uint)(1 << i * 2); } } return r; } private static void QuickSort( int[] keys, object[] values, int left, int right ) { do { int i = left; int j = right; // pre-sort the low, middle (pivot), and high values in place. // this improves performance in the face of already sorted data, or // data that is made up of multiple sorted runs appended together. int middle = i + ((j - i) >> 1); int x = keys[middle]; do { while(keys[i] < x ) i++; while(x < keys[j]) j--; if(i > j) break; if(i < j) { int key = keys[i]; keys[i] = keys[j]; keys[j] = key; if(values != null) { object value = values[i]; values[i] = values[j]; values[j] = value; } } i++; j--; } while(i <= j); if(j - left <= right - i) { if(left < j) QuickSort( keys, values, left, j ); left = i; } else { if(i < right) QuickSort( keys, values, i, right ); right = j; } } while(left < right); } static int[] TestArrayBoundChecks( int[] a , int c1 , int c2 ) { //// c1 = c1 / c2; //QuickSort( a, null, 0, a.Length - 1 ); //Array.Sort( a, delegate( int x, int y ) { return x.CompareTo( y ); } ); //// if(a.Length >= 6) //// { //// int limit = a.Length - 2; //// for(int i = 0; i < limit; i++) for(int i = 0; i < a.Length; i++) { a[i] *= 2; } for(int i = a.Length; --i >= 0;) { a[i] *= 3; } //// } return a; } #endif #if TEST_VFP static float[] s_a = new float[32]; static float[] s_b = new float[32]; static unsafe float AccumulateRowByColumn( float[] A , int Aoffset , float[] B , int Boffset , int N ) { fixed(float* Abase = &A[Aoffset]) { fixed(float* Bbase = &B[Boffset]) { const int VectorStep = 8; int Nrounded = N & ~(VectorStep-1); float res = MultiplyAndAccumulate( Abase, Bbase, Nrounded, VectorStep ); if(Nrounded < N) { float* Aptr = &Abase[Nrounded]; float* Bptr = &Bbase[Nrounded]; while(Nrounded < N) { res += *Aptr++ * *Bptr++; Nrounded++; } } return res; } } } [TS.WellKnownMethod( "Solo_DSP_MatrixMultiply__MultiplyAndAccumulate" )] [MethodImpl( MethodImplOptions.InternalCall )] private static unsafe extern float MultiplyAndAccumulate( float* Abase , float* Bbase , int N , int vectorSize ); #endif [RT.DisableNullChecks( ApplyRecursively=true )] static unsafe void Main() { #if TEST_STRUCT TestStack(); #elif TEST_FP Processor.EnableRunFastMode(); TestPushContext(); t1 = ComputeTest1( 1.0f, 2.0f ); t2 = ComputeTest2( 1.0 , 2.0 ); t3 = ComputeTest3( 100 ); t4 = ComputeTest4( 100 ); t5 = ComputeTest5( 100 ); t6 = ComputeTest6( 100 ); t7 = ComputeTest7( 100 ); #elif TEST_VFP Processor.EnableRunFastMode(); for(int i = 0; i < 16; i++) { s_a[i] = i; s_b[i] = i; } float sum = AccumulateRowByColumn( s_a, 0, s_b, 0, 16 ); #elif TEST_ARRAYBOUNDCHECKS Sqrt( 30 ); int[] a = new int[] { 1, 2, 3, 4, 5 }; a = TestArrayBoundChecks( a, 2, 3 ); #elif DCC_TEST_HALFDUPLEX while(true) { uint cmd = RT.TargetPlatform.ARMv4.Coprocessor14.ReadDCC(); uint numItems = RT.TargetPlatform.ARMv4.Coprocessor14.ReadDCC(); if(cmd == 1) { uint Sum = 0; for(uint u = 0; u < numItems; u++) { uint data = RT.TargetPlatform.ARMv4.Coprocessor14.ReadDCC(); Sum += data; } RT.TargetPlatform.ARMv4.Coprocessor14.WriteDCC( Sum ); } else { for(uint u = 0; u < numItems; u++) { RT.TargetPlatform.ARMv4.Coprocessor14.WriteDCC( u ); } } } #elif DCC_TEST_FULLDUPLEX uint counter = 0; uint words = 0; uint lastWord = 0; while(true) { if(RT.TargetPlatform.ARMv4.Coprocessor14.CanWriteDCC()) { RT.TargetPlatform.ARMv4.Coprocessor14.WriteDebugCommData( (lastWord << 16) | (words << 8) | counter ); counter++; counter &= 0xFF; } if(RT.TargetPlatform.ARMv4.Coprocessor14.CanReadDCC()) { lastWord = RT.TargetPlatform.ARMv4.Coprocessor14.ReadDebugCommData(); words++; words &= 0xFF; while(RT.TargetPlatform.ARMv4.Coprocessor14.CanWriteDCC() == false) { } } } #else Initialize(); DebugPrint( "NOHAU Loader Started" ); //// ReadPage( c_PageSize * 0 ); //// ReadPage( c_PageSize * 1 ); //// ReadPage( c_PageSize * 2 ); //// ReadPage( c_PageSize * 3 ); //// //// EraseBlock( c_PageSize * 128 ); //// ReadPage ( c_PageSize * 128 ); //// //// ReadPage ( c_PageSize * 1 ); //// ProgramPage( c_PageSize * 128 ); //// ReadPage ( c_PageSize * 128 ); while(true) { uint cmd = RT.TargetPlatform.ARMv4.Coprocessor14.ReadDCC(); if((cmd & cmd_Mask) == cmd_Signature) { DebugPrint( "Got command: ", cmd ); switch((byte)cmd) { case cmd_Hello: RT.TargetPlatform.ARMv4.Coprocessor14.WriteDCC( cmd ); break; case cmd_GetConfig: { RT.TargetPlatform.ARMv4.Coprocessor14.WriteDCC( cmd ); RT.TargetPlatform.ARMv4.Coprocessor14.WriteDCC( c_PageCount ); RT.TargetPlatform.ARMv4.Coprocessor14.WriteDCC( c_PageSize ); RT.TargetPlatform.ARMv4.Coprocessor14.WriteDCC( c_SpareSize ); RT.TargetPlatform.ARMv4.Coprocessor14.WriteDCC( c_UsableSpareSize ); RT.TargetPlatform.ARMv4.Coprocessor14.WriteDCC( c_BlockSize ); } break; case cmd_ReadPage: case cmd_ReadSpare: { uint address = RT.TargetPlatform.ARMv4.Coprocessor14.ReadDCC(); RT.TargetPlatform.ARMv4.Coprocessor14.WriteDCC( cmd ); bool fSuccess = ReadPage( address ); RT.TargetPlatform.ARMv4.Coprocessor14.WriteDCC( fSuccess ? 1u : 0u ); if((byte)cmd == cmd_ReadPage) { for(int i = 0; i < s_Page.Length; i++) { RT.TargetPlatform.ARMv4.Coprocessor14.WriteDCC( s_Page[i] ); } } for(int i = 0; i < s_Spare.Length; i += 2) { uint low = s_Spare[i]; uint high = s_Spare[i+1]; uint val = (high << 16) | low; RT.TargetPlatform.ARMv4.Coprocessor14.WriteDCC( val ); } } break; case cmd_ChecksumMemory: { uint address = RT.TargetPlatform.ARMv4.Coprocessor14.ReadDCC(); uint len = RT.TargetPlatform.ARMv4.Coprocessor14.ReadDCC(); uint sum = 0; uint and = 0xFFFFFFFF; bool fSuccess = true; RT.TargetPlatform.ARMv4.Coprocessor14.WriteDCC( cmd ); DebugPrint( "Address: ", address ); DebugPrint( "Length: ", len ); while(len > 0) { uint pageAddress = address & ~(uint)(c_PageSize - 1); fSuccess = ReadPage( pageAddress ); if(fSuccess == false) { break; } uint offset = (address % c_PageSize); while(len > 0 && offset < c_PageSize) { uint val = s_Page[offset / sizeof(uint)]; sum = ((sum & 1) << 31) | (sum >> 1); sum += val; address += sizeof(uint); offset += sizeof(uint); len -= 1; } for(int i = 0; i < s_Page.Length; i++) { and &= s_Page[i]; } for(int i = 0; i < c_UsableSpareSize; i += 2) { uint low = s_Spare[i]; uint high = s_Spare[i+1]; uint val = (high << 16) | low; and &= val; } } if(fSuccess) { RT.TargetPlatform.ARMv4.Coprocessor14.WriteDCC( 1 ); DebugPrint( "Sum: ", sum ); DebugPrint( "And: ", and ); RT.TargetPlatform.ARMv4.Coprocessor14.WriteDCC( sum ); RT.TargetPlatform.ARMv4.Coprocessor14.WriteDCC( and ); } else { RT.TargetPlatform.ARMv4.Coprocessor14.WriteDCC( 0 ); } } break; case cmd_EraseBlock: { uint address = RT.TargetPlatform.ARMv4.Coprocessor14.ReadDCC(); RT.TargetPlatform.ARMv4.Coprocessor14.WriteDCC( cmd ); bool fSuccess = EraseBlock( address ); if(fSuccess) { RT.TargetPlatform.ARMv4.Coprocessor14.WriteDCC( 1 ); } else { RT.TargetPlatform.ARMv4.Coprocessor14.WriteDCC( 0 ); } } break; case cmd_ProgramPage: { uint address = RT.TargetPlatform.ARMv4.Coprocessor14.ReadDCC(); uint pages = RT.TargetPlatform.ARMv4.Coprocessor14.ReadDCC(); RT.TargetPlatform.ARMv4.Coprocessor14.WriteDCC( cmd ); bool fSuccess = true; for(int page = 0; page < pages; page++) { for(int i = 0; i < s_Page.Length; i++) { s_Page[i] = RT.TargetPlatform.ARMv4.Coprocessor14.ReadDCC(); DebugPrintVerbose( "Program Data: ", s_Page[i] ); } for(int i = 0; i < s_Spare.Length; i += 2) { uint val = RT.TargetPlatform.ARMv4.Coprocessor14.ReadDCC(); ushort low = (ushort)(val ); ushort high = (ushort)(val >> 16); s_Spare[i ] = low; s_Spare[i+1] = high; DebugPrintVerbose( "Program Spare: ", s_Spare[i ] ); DebugPrintVerbose( "Program Spare: ", s_Spare[i+1] ); } fSuccess &= ProgramPage( address ); address += c_PageSize; } RT.TargetPlatform.ARMv4.Coprocessor14.WriteDCC( fSuccess ? 1u : 0u ); } break; } } } #endif } } } ================================================ FILE: Zelig/Zelig/RunTime/DeviceModels/NohauLPC3180Loader/NohauLPC3180Loader.csproj ================================================  Debug AnyCPU 9.0.21022 2.0 {186F31A3-EF89-4A25-B2D5-20070912AA01} Exe Properties Microsoft.NohauLPC3180Loader Microsoft.NohauLPC3180Loader $(LlilumBuildRoot)\Target\obj\$(MSBuildProjectName)\ v4.5 true full false $(LlilumBuildRoot)\Target\bin\$(Configuration)\ DEBUG;TRACE prompt 4 true true true AllRules.ruleset AnyCPU false pdbonly true $(LlilumBuildRoot)\Target\bin\$(Configuration)\ TRACE prompt 4 true true true AllRules.ruleset AnyCPU false true full false $(LlilumBuildRoot)\Target\bin\$(Configuration)\ AnyCPU TRACE;DEBUG true true true false {186F31A3-EF89-4A25-B2D5-20060501AA01} mscorlib False {186F31A3-EF89-4A25-B2D5-20070702AA01} system False {186F31A3-EF89-4A25-B2D5-20061218AA01} Common False {186F31A3-EF89-4A25-B2D5-20060509AA01} Kernel False {186F31A3-EF89-4A25-B2D5-20060720AA01} TypeSystem False {186F31A3-EF89-4A25-B2D5-20070911AA01} ModelForLPC3180 False 3.5 ================================================ FILE: Zelig/Zelig/RunTime/DeviceModels/NohauLPC3180Loader/Properties/AssemblyInfo.cs ================================================ using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; // General Information about an assembly is controlled through the following // set of attributes. Change these attribute values to modify the information // associated with an assembly. [assembly: AssemblyTitle( "Microsoft.NohauLPC3180Loader" )] [assembly: AssemblyDescription( "" )] [assembly: AssemblyConfiguration( "" )] [assembly: AssemblyCompany( "Microsoft" )] [assembly: AssemblyProduct( "Microsoft.NohauLPC3180Loader" )] [assembly: AssemblyCopyright( "Copyright © Microsoft 2007" )] [assembly: AssemblyTrademark( "" )] [assembly: AssemblyCulture( "" )] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible( false )] //// The following GUID is for the ID of the typelib if this project is exposed to COM //[assembly: Guid( "975a7db2-22e5-41c6-9e32-d3f72152d387" )] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Revision and Build Numbers // by using the '*' as shown below: [assembly: AssemblyVersion( "1.0.0.0" )] [assembly: AssemblyFileVersion( "1.0.0.0" )] ================================================ FILE: Zelig/Zelig/RunTime/DeviceModels/NohauLPC3180Tester/NohauLPC3180Tester.csproj ================================================  Debug AnyCPU 9.0.21022 2.0 {186F31A3-EF89-4A25-B2D5-20071208AA01} Exe Properties Microsoft.NohauLPC3180Tester Microsoft.NohauLPC3180Tester $(LlilumBuildRoot)\Target\obj\$(MSBuildProjectName)\ v4.5 true full false $(LlilumBuildRoot)\Target\bin\$(Configuration)\ DEBUG;TRACE prompt 4 true true true AllRules.ruleset AnyCPU false pdbonly true $(LlilumBuildRoot)\Target\bin\$(Configuration)\ TRACE prompt 4 true true true AllRules.ruleset AnyCPU false true full false $(LlilumBuildRoot)\Target\bin\$(Configuration)\ AnyCPU TRACE;DEBUG true true true false {186F31A3-EF89-4A25-B2D5-20060501AA01} mscorlib False {186F31A3-EF89-4A25-B2D5-20070702AA01} system False {186F31A3-EF89-4A25-B2D5-20061218AA01} Common False {186F31A3-EF89-4A25-B2D5-20060509AA01} Kernel False {186F31A3-EF89-4A25-B2D5-20070911AA01} ModelForLPC3180 False {186F31A3-EF89-4A25-B2D5-20071018AA01} NohauLPC3180 False 3.5 ================================================ FILE: Zelig/Zelig/RunTime/DeviceModels/NohauLPC3180Tester/Properties/AssemblyInfo.cs ================================================ using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; // General Information about an assembly is controlled through the following // set of attributes. Change these attribute values to modify the information // associated with an assembly. [assembly: AssemblyTitle( "NohauLPC3180Tester" )] [assembly: AssemblyDescription( "" )] [assembly: AssemblyConfiguration( "" )] [assembly: AssemblyCompany( "Microsoft" )] [assembly: AssemblyProduct( "NohauLPC3180Tester" )] [assembly: AssemblyCopyright( "Copyright © Microsoft 2007" )] [assembly: AssemblyTrademark( "" )] [assembly: AssemblyCulture( "" )] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. //[assembly: ComVisible( false )] // The following GUID is for the ID of the typelib if this project is exposed to COM //[assembly: Guid( "790c97c2-f14c-473e-a9eb-1b72d95bad30" )] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // [assembly: AssemblyVersion( "1.0.0.0" )] [assembly: AssemblyFileVersion( "1.0.0.0" )] ================================================ FILE: Zelig/Zelig/RunTime/DeviceModels/NohauLPC3180Tester/Tester.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // #define SEND_TEST_PATTERNS //#define DEBUG_MEMORYPERFORMANCE //#define TEST_SERIAL //#define TEST_FLOATINGPOINT //#define TEST_FLOATINGPOINT_FROM_IRAM #define TEST_VECTORHACK //#define TEST_VECTORHACK_MAC //#define TEST_VECTORHACK_OLD //#define TEST_DMA //#define TEST_QUANTIZED_MLP #if DEBUG_MEMORYPERFORMANCE #define TEST_VECTORHACK #endif namespace Microsoft.NohauLPC3180Tester { using System; using System.Collections.Generic; using System.Runtime.CompilerServices; using RT = Microsoft.Zelig.Runtime; using TS = Microsoft.Zelig.Runtime.TypeSystem; using Chipset = Microsoft.DeviceModels.Chipset.LPC3180; class Tester { [RT.NoInline] private static unsafe uint FlushCache() { uint* ptr = (uint*)0x80000000; uint* end = (uint*)0x81000000; uint sum = 0; while(ptr < end) { sum += *ptr++; } return sum; } #if TEST_FLOATINGPOINT [RT.DisableBoundsChecks] [RT.DisableNullChecks] private static unsafe double FMACD( double* left , double* right , double sum ) { for(int i = 0; i < 1024; i += 8) { sum += left[0] * right[0]; sum += left[1] * right[1]; sum += left[2] * right[2]; sum += left[3] * right[3]; sum += left[4] * right[4]; sum += left[5] * right[5]; sum += left[6] * right[6]; sum += left[7] * right[7]; left += 8; right += 8; } return sum; } [RT.DisableBoundsChecks] [RT.DisableNullChecks] private static unsafe float FMACS( float* left , float* right , float sum ) { for(int i = 0; i < 1024; i += 8) { sum += left[0] * right[0]; sum += left[1] * right[1]; sum += left[2] * right[2]; sum += left[3] * right[3]; sum += left[4] * right[4]; sum += left[5] * right[5]; sum += left[6] * right[6]; sum += left[7] * right[7]; left += 8; right += 8; } return sum; } [RT.DisableBoundsChecks] [RT.DisableNullChecks] private static unsafe float FMACS2( float* lPtr , float* rPtr , float sum ) { for(int i = 0; i < 1024; i += 8) { float lIdx0 = lPtr[0]; float rIdx0 = rPtr[0]; float lIdx1 = lPtr[1]; float rIdx1 = rPtr[1]; float lIdx2 = lPtr[2]; float rIdx2 = rPtr[2]; float lIdx3 = lPtr[3]; float rIdx3 = rPtr[3]; float lIdx4 = lPtr[4]; float rIdx4 = rPtr[4]; float lIdx5 = lPtr[5]; float rIdx5 = rPtr[5]; float lIdx6 = lPtr[6]; float rIdx6 = rPtr[6]; float lIdx7 = lPtr[7]; float rIdx7 = rPtr[7]; float mul0 = lIdx0 * rIdx0; float mul1 = lIdx1 * rIdx1; float mul2 = lIdx2 * rIdx2; float mul3 = lIdx3 * rIdx3; float mul4 = lIdx4 * rIdx4; float mul5 = lIdx5 * rIdx5; float mul6 = lIdx6 * rIdx6; float mul7 = lIdx7 * rIdx7; sum += mul0; sum += mul1; sum += mul2; sum += mul3; sum += mul4; sum += mul5; sum += mul6; sum += mul7; lPtr += 8; rPtr += 8; } return sum; } [RT.DisableBoundsChecks] [RT.DisableNullChecks] private static unsafe int IMAC( int* left , int* right , int sum ) { for(int i = 0; i < 1024; i += 8) { sum += left[0] * right[0]; sum += left[1] * right[1]; sum += left[2] * right[2]; sum += left[3] * right[3]; sum += left[4] * right[4]; sum += left[5] * right[5]; sum += left[6] * right[6]; sum += left[7] * right[7]; left += 8; right += 8; } return sum; } static long valFMACD; static long valFMACS; static long valFMACS2; static long valIMAC; private static unsafe void TestFMAC() { System.Diagnostics.Stopwatch stopwatch = new System.Diagnostics.Stopwatch(); #if TEST_FLOATINGPOINT_FROM_IRAM UIntPtr leftBase = new UIntPtr( 0x08000000 + 64 * 1024 - 1 * 1024 * 8 ); UIntPtr rightBase = new UIntPtr( 0x08000000 + 64 * 1024 - 2 * 1024 * 8 ); #else UIntPtr leftBase = new UIntPtr( 0x81000000 + 1 * 1024 * 8 ); UIntPtr rightBase = new UIntPtr( 0x81000000 + 2 * 1024 * 8 ); #endif { double* left = (double*)leftBase .ToPointer(); double* right = (double*)rightBase.ToPointer(); for(int loop = 0; loop < 1024; loop++) { left [loop] = loop + 1024; right[loop] = loop * 13; } FlushCache(); stopwatch.Start(); for(int i = 0; i < 128; i++) { double sum = FMACD( left, right, 0 ); } stopwatch.Stop(); valFMACD = stopwatch.ElapsedTicks; stopwatch.Reset(); } { float* left = (float*)leftBase .ToPointer(); float* right = (float*)rightBase.ToPointer(); for(int loop = 0; loop < 1024; loop++) { left [loop] = loop + 1024; right[loop] = loop * 13; } FlushCache(); stopwatch.Start(); for(int i = 0; i < 128; i++) { float sum = FMACS( left, right, 0 ); } stopwatch.Stop(); valFMACS = stopwatch.ElapsedTicks; stopwatch.Reset(); } { float* left = (float*)leftBase .ToPointer(); float* right = (float*)rightBase.ToPointer(); for(int loop = 0; loop < 1024; loop++) { left [loop] = loop + 1024; right[loop] = loop * 13; } FlushCache(); stopwatch.Start(); for(int i = 0; i < 128; i++) { float sum = FMACS2( left, right, 0 ); } stopwatch.Stop(); valFMACS2 = stopwatch.ElapsedTicks; stopwatch.Reset(); } { int* left = (int*)leftBase .ToPointer(); int* right = (int*)rightBase.ToPointer(); for(int loop = 0; loop < 1024; loop++) { left [loop] = loop + 1024; right[loop] = loop * 13; } FlushCache(); stopwatch.Start(); for(int i = 0; i < 128; i++) { int sum = IMAC( left, right, 0 ); } stopwatch.Stop(); valIMAC = stopwatch.ElapsedTicks; stopwatch.Reset(); } } #endif #if TEST_VECTORHACK static float valFMACS_sum1; static float valFMACS_sum2; static double valFMACS_time1; static long valFMACS_time2; static double valFMACS_timePerIter; static float[] s_A = new float[512]; static float[] s_B = new float[1024]; #if TEST_VECTORHACK_OLD [RT.DisableNullChecks()] private static unsafe float MultiplyAndAccumulate( float* Abase , float* Bbase , int N , int vectorSize ) { float c = 0.0f; float* Aptr = Abase; float* Bptr = Bbase; float* Aend = &Aptr[N & ~7]; float C1 = 0; float C2 = 0; float C3 = 0; float C4 = 0; float C5 = 0; float C6 = 0; float C7 = 0; float C8 = 0; while(Aptr < Aend) { float A1 = Aptr[0]; float A2 = Aptr[1]; float A3 = Aptr[2]; float A4 = Aptr[3]; float A5 = Aptr[4]; float A6 = Aptr[5]; float A7 = Aptr[6]; float A8 = Aptr[7]; float B1 = Bptr[0]; float B2 = Bptr[1]; float B3 = Bptr[2]; float B4 = Bptr[3]; float B5 = Bptr[4]; float B6 = Bptr[5]; float B7 = Bptr[6]; float B8 = Bptr[7]; float M1 = A1 * B1; float M2 = A2 * B2; float M3 = A3 * B3; float M4 = A4 * B4; float M5 = A5 * B5; float M6 = A6 * B6; float M7 = A7 * B7; float M8 = A8 * B8; C1 += M1; C2 += M2; C3 += M3; C4 += M4; C5 += M5; C6 += M6; C7 += M7; C8 += M8; Aptr += 8; Bptr += 8; } C1 += C5; C2 += C6; C3 += C7; C4 += C8; C1 += C3; C2 += C4; c = C1 + C2; return c; } #else [TS.WellKnownMethod( "Solo_DSP_MatrixMultiply__MultiplyAndAccumulate" )] [MethodImpl( MethodImplOptions.InternalCall )] private static unsafe extern float MultiplyAndAccumulate( float* Abase , float* Bbase , int N , int vectorSize ); #endif private static unsafe void TestVectorHack() { System.Diagnostics.Stopwatch stopwatch = new System.Diagnostics.Stopwatch(); #if TEST_FLOATINGPOINT_FROM_IRAM UIntPtr leftBase = new UIntPtr( 0x08000000 + 64 * 1024 - 1 * 1024 * 8 ); UIntPtr rightBase = new UIntPtr( 0x08000000 + 64 * 1024 - 2 * 1024 * 8 ); #else UIntPtr leftBase = new UIntPtr( 0x81000000 + 1 * 1024 * 8 ); UIntPtr rightBase = new UIntPtr( 0x81000000 + 2 * 1024 * 8 ); #endif { float* left = (float*)leftBase .ToPointer(); float* right = (float*)rightBase.ToPointer(); for(int loop = 0; loop < 1024; loop++) { left [loop] = loop + 1024; right[loop] = loop * 13; } FlushCache(); stopwatch.Start(); for(int i = 0; i < 128; i++) { valFMACS_sum1 = MultiplyAndAccumulate( left, right, 1024, 8 ); } stopwatch.Stop(); valFMACS_time1 = stopwatch.ElapsedTicks; stopwatch.Reset(); } { float* left = (float*)leftBase .ToPointer(); float* right = (float*)rightBase.ToPointer(); for(int loop = 0; loop < 1024; loop++) { left [loop] = loop + 1024; right[loop] = loop * 13; } FlushCache(); stopwatch.Start(); valFMACS_sum2 = MultiplyAndAccumulate( left, right, 1024, 8 ); stopwatch.Stop(); valFMACS_time2 = stopwatch.ElapsedTicks; stopwatch.Reset(); } } static public unsafe float AccumulateRowByColumn( float[] A , int Aoffset , float[] B , int Boffset , int N ) { fixed(float* Abase = &A[Aoffset]) { fixed(float* Bbase = &B[Boffset]) { const int VectorStep = 8; int Nrounded = N & ~(VectorStep-1); //// Chipset.GPIO gpio = Chipset.GPIO.Instance; //// //// gpio.SetGPO( 13 ); float res = MultiplyAndAccumulate( Abase, Bbase, Nrounded, VectorStep ); //// gpio.ResetGPO( 13 ); if(Nrounded < N) { float* Aptr = &Abase[Nrounded]; float* Bptr = &Bbase[Nrounded]; while(Nrounded < N) { res += *Aptr++ * *Bptr++; Nrounded++; } } return res; } } } private static unsafe void TestVectorHack2( double[] results , int runs , int K , int N ) { System.Diagnostics.Stopwatch stopwatch = new System.Diagnostics.Stopwatch(); const int M = 1; #if TEST_ROUND_SIZE const int K = 256; const int N = 512; #elif TEST_CLASSIC_MLP const int K = 226; const int N = 500; #else //// const int K = 159; //// const int N = 50; #endif int Astride = K; int Bstride = K; int Cstride = N; float[] A = new float[K ]; float[] B = new float[K*N]; float[] C = new float[ N]; //--// for(int i = 0; i < K; i++) { A[i] = 1; } for(int i = 0; i < N; i++) { for(int j = 0; j < K; j++) { B[i * K + j] = i; } } //--// for(int run = 1; run < runs; run++) { FlushCache(); stopwatch.Start(); for(int run2 = 0; run2 < run; run2++) { for (int i = 0; i < M; i++) { for (int j = 0; j < N; j++) { C[i * Cstride + j] = AccumulateRowByColumn( A, i * Astride, B, j * Bstride, K ); } } } stopwatch.Stop(); results[run] = (stopwatch.ElapsedTicks / (double)System.Diagnostics.Stopwatch.Frequency * 1E9) / (N * K) / run; stopwatch.Reset(); } } public static float Exp( float x ) { const float Exp = (float)Math.E; const float ExpHalfFactor = 1.648721f; const float ExpStep1 = 0.00138888f; const float ExpStep2 = 0.00833333f; const float ExpStep3 = 0.04166666f; const float ExpStep4 = 0.16666666f; const float ExpStep5 = 0.5f; const float ExpStep6 = 1.0f; int sign; // Reduce range to [0.0,1.0] if (x < 0) { x = -x; sign = -1; } else { sign = 1; } float result = 1.0f; while(x > 1.0f) { x -= 1.0f; result *= Exp; } // Reduce range to [0.0,0.5] if (x > 0.5f) { x -= 0.5f; result *= ExpHalfFactor; } float temp; temp = ExpStep1 * x; temp = (temp + ExpStep2) * x; temp = (temp + ExpStep3) * x; temp = (temp + ExpStep4) * x; temp = (temp + ExpStep5) * x; temp = (temp + ExpStep6) * x; result *= (temp + 1.0f); if (sign == -1) { result = 1.0f / result; } return result; } private static unsafe double[] TestVectorHack2( int runs ) { double[] results = new double[runs]; //// TestVectorHack2( results, runs, 159, 30 ); //// TestVectorHack2( results, runs, 159, 50 ); //// TestVectorHack2( results, runs, 226, 500 ); System.Diagnostics.Stopwatch stopwatch = new System.Diagnostics.Stopwatch(); stopwatch.Start(); for(int i = 0; i < 1000; i++) { Math.Exp( 0.5 ); } stopwatch.Stop(); results[0] = (stopwatch.ElapsedTicks / (double)System.Diagnostics.Stopwatch.Frequency * 1E9) / 1000; stopwatch.Reset(); stopwatch.Start(); for(int i = 0; i < 1000; i++) { Exp( 0.5f ); } stopwatch.Stop(); results[1] = (stopwatch.ElapsedTicks / (double)System.Diagnostics.Stopwatch.Frequency * 1E9) / 1000; TestVectorHack2( results, runs, 160, 30 ); TestVectorHack2( results, runs, 160, 50 ); TestVectorHack2( results, runs, 232, 500 ); TestVectorHack2( results, runs, 160, 30 ); return results; } [RT.DisableNullChecks()] private static unsafe float TestVectorHack3() { System.Diagnostics.Stopwatch stopwatch = new System.Diagnostics.Stopwatch(); float[] B = s_B;//new float[8192]; while(true) { stopwatch.Start(); //// for(int i = 0; i < 128; i++) //// { //// fixed(float* Bbase = &B[0]) //// { //// float* Bptr = Bbase; //// float* Bend = Bbase + B.Length; //// float res1 = 0; //// float res2 = 0; //// float res3 = 0; //// float res4 = 0; //// float res5 = 0; //// float res6 = 0; //// float res7 = 0; //// float res8 = 0; //// //// while(Bptr < Bend) //// { //// res1 = Bptr[0]; //// res2 = Bptr[1]; //// res3 = Bptr[2]; //// res4 = Bptr[3]; //// res5 = Bptr[4]; //// res6 = Bptr[5]; //// res7 = Bptr[6]; //// res8 = Bptr[7]; //// //// Bptr += 8; //// } //// //// valFMACS_sum1 = res1 + res2 + res3 + res4 + res5 + res6 + res7 + res8; //// } //// } int res1 = 1; //// int add = 2; int* ptr = (int*)0x80000000; for(int i = 0; i < 128*1024; i++) { res1 += *ptr; //ptr++; } stopwatch.Stop(); valFMACS_time1 = stopwatch.ElapsedTicks; stopwatch.Reset(); } } [RT.DisableNullChecks] private static unsafe void TestVectorHack4( float* Abase , float* Bbase ) { //// const int VectorStep = 8; for(int count = 0; count < 16; count++) { float* Bptr = Bbase; for(int i = 0; i < 512; i++) { //// MultiplyAndAccumulate( Abase, Bptr, 512, VectorStep ); Chipset.GPIO gpio = Chipset.GPIO.Instance; float res = 0; //// float add = 1; gpio.SetGPO( 13 ); for(int j = 0; j < 32; j++) { //// res += add; //// gpio.SetGPO( 9 ); res = *Bptr; //// gpio.ResetGPO( 9 ); Bptr += 8; } gpio.ResetGPO( 13 ); Abase[i] = res; //// Bptr += 32; } } } [RT.DisableNullChecks] private static unsafe void TestVectorHack4b( float* Abase , float* Bbase ) { const int VectorStep = 8; for(int count = 0; count < 16; count++) { const int stepReduction = 1; float* Bptr = Bbase; for(int i = 0; i < 512 * stepReduction; i++) { Chipset.GPIO gpio = Chipset.GPIO.Instance; gpio.SetGPO( 13 ); MultiplyAndAccumulate( Abase, Bptr, 512 / stepReduction, VectorStep ); gpio.ResetGPO( 13 ); Bptr += 512 / stepReduction; } } } [RT.DisableNullChecks] private static unsafe void TestVectorHack4c( float* Abase , float* Bbase ) { for(int count = 0; count < 16; count++) { uint* Bptr = (uint*)Bbase; for(int i = 0; i < 512; i++) { Chipset.GPIO gpio = Chipset.GPIO.Instance; uint res = 0; gpio.SetGPO( 13 ); for(int j = 0; j < 512/64; j++) { gpio.SetGPO( 9 ); gpio.ResetGPO( 9 ); gpio.SetGPO( 9 ); gpio.ResetGPO( 9 ); gpio.SetGPO( 9 ); res += *Bptr; Bptr += 8; res += *Bptr; Bptr += 8; res += *Bptr; Bptr += 8; res += *Bptr; Bptr += 8; res += *Bptr; Bptr += 8; res += *Bptr; Bptr += 8; res += *Bptr; Bptr += 8; res += *Bptr; Bptr += 8; gpio.ResetGPO( 9 ); } gpio.ResetGPO( 13 ); Abase[i] = (res + 1); } } } private static unsafe void TestVectorHack4() { System.Diagnostics.Stopwatch stopwatch = new System.Diagnostics.Stopwatch(); float[] A = s_A;//new float[512 ]; float[] B = new float[512*512]; float[] C = new float[ 512]; FlushCache(); //// // //// // Invalidate ICache. //// // //// Microsoft.Zelig.Runtime.TargetPlatform.ARMv4.ProcessorARMv4.MoveToCoprocessor( 15, 0, 7, 5, 0, 0 ); while(true) { stopwatch.Start(); //// TestVectorHack4( (float*)0x80000000, (float*)(0x80000000 + 512 * 4) ); fixed(float* Abase = &A[0]) { fixed(float* Bbase = &B[0]) { TestVectorHack4b( Abase, Bbase ); //// TestVectorHack4c( Abase, (float*)0x80000000 ); } } stopwatch.Stop(); valFMACS_timePerIter = stopwatch.ElapsedTicks * 16.0; valFMACS_timePerIter /= (16.0 * 512.0 * 512.0); stopwatch.Reset(); } } #endif #if TEST_DMA static double valDMA_time1; [RT.AlignmentRequirements( 32, sizeof(uint) )] static uint[] s_IRAM_src = new uint[512 + 32]; [RT.AlignmentRequirements( 32, sizeof(uint) )] static uint[] s_IRAM_dst = new uint[512 + 32]; private static unsafe void TestDMA( uint* SrcBase , uint* DstBase , bool fIncrement ) { Chipset.GPDMA dma = Chipset.GPDMA.Instance; dma.Enable(); Chipset.GPDMA.Channel chn = dma.Channels[0]; uint* SrcPtr = SrcBase; System.Diagnostics.Stopwatch stopwatch1 = new System.Diagnostics.Stopwatch(); System.Diagnostics.Stopwatch stopwatch2 = new System.Diagnostics.Stopwatch(); for(int i = 0; i < 512; i++) { //// Chipset.GPIO gpio = Chipset.GPIO.Instance; stopwatch1.Start(); stopwatch1.Stop(); stopwatch2.Start(); //// gpio.SetGPO( 13 ); chn.CopyMemory( SrcPtr, DstBase, 512, 32, true, true, false ); //// gpio.SetGPO( 9 ); //// chn.WaitForCompletion(); //// gpio.ResetGPO( 9 ); //// //// gpio.ResetGPO( 13 ); stopwatch2.Stop(); valDMA_time1 = (stopwatch2.ElapsedTicks - stopwatch1.ElapsedTicks) * 16.0; valDMA_time1 /= 208.0; stopwatch1.Reset(); stopwatch2.Reset(); if(fIncrement) { SrcPtr += 512; } } chn.WaitForCompletion(); dma.Disable(); } enum Tests { IRAM_to_IRAM , SDRAM_to_IRAM , SDRAM_to_SDRAM, IRAM_to_SDRAM , } private static unsafe void TestDMA() { System.Diagnostics.Stopwatch stopwatch = new System.Diagnostics.Stopwatch(); Tests test = Tests.IRAM_to_IRAM; uint[] Src; uint[] Dst; bool fIncrementSrc; switch(test) { default: case Tests.IRAM_to_IRAM: Src = s_IRAM_src; Dst = s_IRAM_dst; fIncrementSrc = false; break; case Tests.IRAM_to_SDRAM: Src = s_IRAM_src; Dst = new uint[512]; fIncrementSrc = false; break; case Tests.SDRAM_to_SDRAM: Src = new uint[512*512]; Dst = new uint[512]; fIncrementSrc = true; break; case Tests.SDRAM_to_IRAM: Src = new uint[512*512]; Dst = s_IRAM_dst; fIncrementSrc = true; break; } for(int i = 0; i < Src.Length; i++) { Src[i] = 0xDEADBEEF; } for(int i = 0; i < Dst.Length; i++) { Dst[i] = 0xBAD00000u + (uint)i; } FlushCache(); //// // //// // Invalidate ICache. //// // //// Microsoft.Zelig.Runtime.TargetPlatform.ARMv4.ProcessorARMv4.MoveToCoprocessor( 15, 0, 7, 5, 0, 0 ); while(true) { stopwatch.Start(); fixed(uint* SrcBase = &Src[0]) { fixed(uint* DstBbase = &Dst[0]) { TestDMA( SrcBase, DstBbase, fIncrementSrc ); } } stopwatch.Stop(); FlushCache(); //valDMA_time1 = stopwatch.ElapsedTicks; stopwatch.Reset(); } } #endif #if TEST_QUANTIZED_MLP static double valMLP_time1; const int M = 1; const int K = 256; const int N = 512; const int Astride = K; const int Bstride = K; const int Cstride = N; [RT.DisableNullChecks()] [RT.DisableBoundsChecks()] static unsafe float AccumulateRowByColumn( float[] A , int Aoffset , uint[] B , int Boffset , int N , float[] Lookup ) { fixed(float* Abase = &A[Aoffset]) { fixed(uint* Bbase = &B[Boffset]) { fixed(float* Lptr = Lookup) { float* Aptr = Abase; float* AptrEnd = &Abase[N]; uint* Bptr = Bbase; float res1 = 0; float res2 = 0; float res3 = 0; float res4 = 0; float res5 = 0; float res6 = 0; float res7 = 0; float res8 = 0; while(Aptr < AptrEnd) { uint val = Bptr[0]; float V1 = *(float*)((uint)Lptr + ((val << 2 ) & 0x3FC)); float V2 = *(float*)((uint)Lptr + ((val >> ( 8-2)) & 0x3FC)); float V3 = *(float*)((uint)Lptr + ((val >> (16-2)) & 0x3FC)); float V4 = *(float*)((uint)Lptr + ((val >> (24-2)) & 0x3FC)); val = Bptr[1]; float V5 = *(float*)((uint)Lptr + ((val << 2 ) & 0x3FC)); float V6 = *(float*)((uint)Lptr + ((val >> ( 8-2)) & 0x3FC)); float V7 = *(float*)((uint)Lptr + ((val >> (16-2)) & 0x3FC)); float V8 = *(float*)((uint)Lptr + ((val >> (24-2)) & 0x3FC)); V1 *= Aptr[0]; V2 *= Aptr[1]; V3 *= Aptr[2]; V4 *= Aptr[3]; V5 *= Aptr[4]; V6 *= Aptr[5]; V7 *= Aptr[6]; V8 *= Aptr[7]; res1 += V1; res2 += V2; res3 += V3; res4 += V4; res5 += V5; res6 += V6; res7 += V7; res8 += V8; Bptr += 2; Aptr += 8; } return res1 + res2 + res3 + res4 + res5 + res6 + res7 + res8; } } } } private static unsafe void TestQuantizedMLP() { System.Diagnostics.Stopwatch stopwatch = new System.Diagnostics.Stopwatch(); float[] Lookup = new float[256]; float[] A = new float[K]; uint[] B = new uint [K * N / sizeof(uint)]; float[] C = new float[N]; for(int i = 0; i < Lookup.Length; i++) { Lookup[i] = i; } for(int i = 0; i < K; i++) { A[i] = 1; } for(int i = 0; i < B.Length; i++) { uint weight = 0; for(int j = 0; j < 4; j++) { int val = 33477 * (i * 4 + j) % 12397; weight |= (uint)(val & 0xFF) << (j * 8); } B[i] = weight; } FlushCache(); //--// while(true) { stopwatch.Start(); for(int count = 0; count < 16; count++) { for (int i = 0; i < M; i++) { for (int j = 0; j < N; j++) { C[i * Cstride + j] = AccumulateRowByColumn( A, i * Astride, B, j * Bstride, K, Lookup ); } } } stopwatch.Stop(); valMLP_time1 = (stopwatch.ElapsedTicks * 16.0) / (16.0 * K * N); stopwatch.Reset(); } } #endif #if TEST_QUANTIZED_MLP2 static double valMLP_time1; const int M = 1; const int K = 256; const int N = 512; const int Astride = K; const int Bstride = K; const int Cstride = N; [RT.DisableNullChecks()] [RT.DisableBoundsChecks()] static unsafe float AccumulateRowByColumn( float[] A , int Aoffset , byte[] B , int Boffset , int N , float[] Lookup ) { fixed(float* Abase = &A[Aoffset]) { fixed(byte* Bbase = &B[Boffset]) { fixed(float* Lptr = Lookup) { float* Aptr = Abase; float* AptrEnd = &Abase[N]; byte* Bptr = Bbase; float res1 = 0; float res2 = 0; float res3 = 0; float res4 = 0; float res5 = 0; float res6 = 0; float res7 = 0; float res8 = 0; while(Aptr < AptrEnd) { float V1 = Lptr[Bptr[0]]; float V2 = Lptr[Bptr[1]]; float V3 = Lptr[Bptr[2]]; float V4 = Lptr[Bptr[3]]; float V5 = Lptr[Bptr[4]]; float V6 = Lptr[Bptr[5]]; float V7 = Lptr[Bptr[6]]; float V8 = Lptr[Bptr[7]]; V1 *= Aptr[0]; V2 *= Aptr[1]; V3 *= Aptr[2]; V4 *= Aptr[3]; V5 *= Aptr[4]; V6 *= Aptr[5]; V7 *= Aptr[6]; V8 *= Aptr[7]; res1 += V1; res2 += V2; res3 += V3; res4 += V4; res5 += V5; res6 += V6; res7 += V7; res8 += V8; Bptr += 8; Aptr += 8; } return res1 + res2 + res3 + res4 + res5 + res6 + res7 + res8; } } } } private static unsafe void TestQuantizedMLP() { System.Diagnostics.Stopwatch stopwatch = new System.Diagnostics.Stopwatch(); float[] Lookup = new float[256]; float[] A = new float[K]; byte[] B = new byte[K * N]; float[] C = new float[N]; for(int i = 0; i < Lookup.Length; i++) { Lookup[i] = i; } for(int i = 0; i < K; i++) { A[i] = 1; } for(int i = 0; i < B.Length; i++) { B[i] = (byte)(33477 * (i) % 12397); } FlushCache(); //--// while(true) { stopwatch.Start(); for(int count = 0; count < 16; count++) { for (int i = 0; i < M; i++) { for (int j = 0; j < N; j++) { C[i * Cstride + j] = AccumulateRowByColumn( A, i * Astride, B, j * Bstride, K, Lookup ); } } } stopwatch.Stop(); valMLP_time1 = (stopwatch.ElapsedTicks * 16) / (16 * K * N); stopwatch.Reset(); } } #endif #if TEST_SERIAL static void TestSerial() { var port = new System.IO.Ports.SerialPort( "UART5" ); port.BaudRate = 230400 * 2; port.ReadBufferSize = 256; port.WriteBufferSize = 256; port.Open(); port.Write( "Hello World!" ); byte[] writeBuf = new byte[1]; while(true) { System.Diagnostics.Stopwatch stopwatch = new System.Diagnostics.Stopwatch(); stopwatch.Start(); const int total = 32 * 1024; int ch = 0; for(int j = 0; j < total; j++) { writeBuf[0] = (byte)(48 + ch); port.Write( writeBuf, 0, 1 ); ch = (ch + 1) % 32; } stopwatch.Stop(); port.Write( "\r\n" ); port.Write( "\r\n" ); port.Write( string.Format( "Took {0} to send {1} bytes", stopwatch.ElapsedMilliseconds, total ) ); //// byte[] buf = new byte[64]; //// //// while(true) //// { //// for(int i = 0; i < 64; i++) //// { //// buf[i] = port.Read(); //// } //// //// //port.Write( (byte)'>' ); //// for(int i = 0; i < 64; i++) //// { //// port.Write( buf[i] ); //// } //// //port.Write( (byte)'<' ); //// } GC.Collect(); } } #endif static void Main() { #if TEST_SERIAL TestSerial(); #elif TEST_FLOATINGPOINT TestFMAC(); #elif TEST_VECTORHACK TestVectorHack2( 30 ); //// TestVectorHack4(); #elif TEST_DMA TestDMA(); #elif TEST_QUANTIZED_MLP TestQuantizedMLP(); #else var bc = new Microsoft.NohauLPC3180.Drivers.BelaChannel(); short[] samples = Microsoft.NohauLPC3180.Drivers.BelaChannel.AllocateSamplesArray(); #if SEND_TEST_PATTERNS //// short[] testPatterns = new short[] //// { 0,2047,4095,6143,8191,10239,12287,14335,16383,18431,20479,22527,24575,26623,28671,30719, //// 30719,28671,26623,24575,22527,20479,18431,16383,14335,12287,10239,8191,6143,4095,2047,0, //// 0,-2047,-4095,-6143,-8191,-10239,-12287,-14335,-16383,-18431,-20479,-22527,-24575,-26623,-28671,-30719, //// -30719,-28671,-26623,-24575,-22527,-20479,-18431,-16383,-14335,-12287,-10239,-8191,-6143,-4095,-2047,0, //// 16384,16384,-16384,-16384,16384,16384,-16384,-16384,16384,16384,-16384,-16384,16384,16384,-16384,-16384 }; short[] testPatterns = new short[80]; for(int i = 0; i < 80; i++) { testPatterns[i] = (short)((2*i+1) * 256 + (2*i)); } #endif bc.RequestAttention(); bc.DebugSuccess( "Hello World!" ); int frames = 0; #if SEND_TEST_PATTERNS bc.QueueAudio( testPatterns ); #endif while(true) { short[] samplesN = samples; #if SEND_TEST_PATTERNS bc.QueueAudio( testPatterns ); #endif bc.FetchSamples( samplesN ); frames++; if((frames % 100) == 0) { bc.DebugInformational( string.Format( "Got Frames: {0}", frames ) ); } bc.RequestSamples = true; } //// Bluetooth bt = new Bluetooth(); //// //// bt.Connection(); //// //// while(true); #endif } } } ================================================ FILE: Zelig/Zelig/RunTime/DeviceModels/Perf/Dhrystone/DhrystoneTest.csproj ================================================  Debug x86 8.0.30703 2.0 {30BA8CEE-868B-4C53-85C5-DFF6FA39D035} Exe Properties DhrystoneTest DhrystoneTest v4.5 512 true $(LlilumBuildRoot)\Target\bin\$(Configuration)\ DEBUG;TRACE true true true full AnyCPU prompt MinimumRecommendedRules.ruleset $(LlilumBuildRoot)\Target\bin\$(Configuration)\ TRACE true true true true pdbonly AnyCPU prompt MinimumRecommendedRules.ruleset true $(LlilumBuildRoot)\Target\bin\$(Configuration)\ DEBUG;TRACE true true true full AnyCPU MinimumRecommendedRules.ruleset {186F31A3-EF89-4A25-B2D5-20060501AA01} mscorlib False {186F31A3-EF89-4A25-B2D5-20070702AA01} system False {186F31A3-EF89-4A25-B2D5-20061218AA01} Common False {186F31A3-EF89-4A25-B2D5-20060509AA01} Kernel False {186F31A3-EF89-4A25-B2D5-20060720AA01} TypeSystem False ================================================ FILE: Zelig/Zelig/RunTime/DeviceModels/Perf/Dhrystone/Properties/AssemblyInfo.cs ================================================ using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; // General Information about an assembly is controlled through the following // set of attributes. Change these attribute values to modify the information // associated with an assembly. [assembly: AssemblyTitle( "CryptoTest" )] [assembly: AssemblyDescription( "" )] [assembly: AssemblyConfiguration( "" )] [assembly: AssemblyCompany( "Microsoft" )] [assembly: AssemblyProduct( "CryptoTest" )] [assembly: AssemblyCopyright( "Copyright © Microsoft 2012" )] [assembly: AssemblyTrademark( "" )] [assembly: AssemblyCulture( "" )] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible( false )] // The following GUID is for the ID of the typelib if this project is exposed to COM [assembly: Guid( "a1779cdc-5d49-4dd8-93aa-5093a45a444d" )] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Build and Revision Numbers // by using the '*' as shown below: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion( "1.0.0.0" )] [assembly: AssemblyFileVersion( "1.0.0.0" )] ================================================ FILE: Zelig/Zelig/RunTime/DeviceModels/Perf/Dhrystone/dhrystone.cs ================================================ /* **************************************************************************** * * "DHRYSTONE" Benchmark Program * * * Version: C, Version 2.1 * * File: dhry.h (part 1 of 3) * * Date: May 25, 1988 * * Author: Reinhold P. Weicker * Siemens AG, AUT E 51 * Postfach 3220 * 8520 Erlangen * Germany (West) * Phone: [+49]9131720330 * (817 Central European Time) * Usenet: ..!mcsun!unido!estevax!weicker * * Original Version (in Ada) published in * "Communications of the ACM" vol. 27., no. 10 (Oct. 1984), * pp. 1013 1030, together with the statistics * on which the distribution of statements etc. is based. * * In this C version, the following C library functions are used: * strcpy, strcmp (inside the measurement loop) * printf, scanf (outside the measurement loop) * In addition, Berkeley UNIX system calls "times ()" or "time ()" * are used for execution time measurement. For measurements * on other systems, these calls have to be changed. * * Collection of Results: * Reinhold Weicker (address see above) and * * Rick Richardson * PC Research. Inc. * 94 Apple Orchard Drive * Tinton Falls, NJ 07724 * Phone: (201) 3898963 (917 EST) * Usenet: ...!uunet!pcrat!rick * * Please send results to Rick Richardson and/or Reinhold Weicker. * Complete information should be given on hardware and software used. * Hardware information includes: Machine type, CPU, type and size * of caches; for microprocessors: clock frequency, memory speed * (number of wait states). * Software information includes: Compiler (and runtime library) * manufacturer and version, compilation switches, OS version. * The Operating System version may give an indication about the * compiler; Dhrystone itself performs no OS calls in the measurement loop. * * The complete output generated by the program should be mailed * such that at least some checks for correctness can be made. * *************************************************************************** * * History: This version C/2.1 has been made for two reasons: * * 1) There is an obvious need for a common C version of * Dhrystone, since C is at present the most popular system * programming language for the class of processors * (microcomputers, minicomputers) where Dhrystone is used most. * There should be, as far as possible, only one C version of * Dhrystone such that results can be compared without * restrictions. In the past, the C versions distributed * by Rick Richardson (Version 1.1) and by Reinhold Weicker * had small (though not significant) differences. * * 2) As far as it is possible without changes to the Dhrystone * statistics, optimizing compilers should be prevented from * removing significant statements. * * This C version has been developed in cooperation with * Rick Richardson (Tinton Falls, NJ), it incorporates many * ideas from the "Version 1.1" distributed previously by * him over the UNIX network Usenet. * I also thank Chaim Benedelac (National Semiconductor), * David Ditzel (SUN), Earl Killian and John Mashey (MIPS), * Alan Smith and Rafael SaavedraBarrera (UC at Berkeley) * for their help with comments on earlier versions of the * benchmark. * * Changes: In the initialization part, this version follows mostly * Rick Richardson's version distributed via Usenet, not the * version distributed earlier via floppy disk by Reinhold Weicker. * As a concession to older compilers, names have been made * unique within the first 8 characters. * Inside the measurement loop, this version follows the * version previously distributed by Reinhold Weicker. * * At several places in the benchmark, code has been added, * but within the measurement loop only in branches that * are not executed. The intention is that optimizing compilers * should be prevented from moving code out of the measurement * loop, or from removing code altogether. Since the statements * that are executed within the measurement loop have NOT been * changed, the numbers defining the "Dhrystone distribution" * (distribution of statements, operand types and locality) * still hold. Except for sophisticated optimizing compilers, * execution times for this version should be the same as * for previous versions. * * Since it has proven difficult to subtract the time for the * measurement loop overhead in a correct way, the loop check * has been made a part of the benchmark. This does have * an impact though a very minor one on the distribution * statistics which have been updated for this version. * * All changes within the measurement loop are described * and discussed in the companion paper "Rationale for * Dhrystone version 2". * * Because of the selfimposed limitation that the order and * distribution of the executed statements should not be * changed, there are still cases where optimizing compilers * may not generate code for some statements. To a certain * degree, this is unavoidable for small synthetic benchmarks. * Users of the benchmark are advised to check code listings * whether code is generated for all statements of Dhrystone. * * Version 2.1 is identical to version 2.0 distributed via * the UNIX network Usenet in March 1988 except that it corrects * some minor deficiencies that were found by users of version 2.0. * The only change within the measurement loop is that a * nonexecuted "else" part was added to the "if" statement in * Func_3, and a nonexecuted "else" part removed from Proc_3. * *************************************************************************** * * Defines: The following "Defines" are possible: * DREG=register (default: Not defined) * As an approximation to what an average C programmer * might do, the "register" storage class is applied * (if enabled by DREG=register) * for local variables, if they are used (dynamically) * five or more times * for parameters if they are used (dynamically) * six or more times * Note that an optimal "register" strategy is * compilerdependent, and that "register" declarations * do not necessarily lead to faster execution. * DNOSTRUCTASSIGN (default: Not defined) * Define if the C compiler does not support * assignment of structures. * DNOENUMS (default: Not defined) * Define if the C compiler does not support * enumeration types. * DTIMES (default) * DTIME * The "times" function of UNIX (returning process times) * or the "time" function (returning wallclock time) * is used for measurement. * For single user machines, "time ()" is adequate. For * multiuser machines where you cannot get singleuser * access, use the "times ()" function. If you have * neither, use a stopwatch in the dead of night. * "printf"s are provided marking the points "Start Timer" * and "Stop Timer". DO NOT use the UNIX "time(1)" * command, as this will measure the total time to * run this program, which will (erroneously) include * the time to allocate storage (malloc) and to perform * the initialization. * DHZ=nnn * In Berkeley UNIX, the function "times" returns process * time in 1/HZ seconds, with HZ = 60 for most systems. * CHECK YOUR SYSTEM DESCRIPTION BEFORE YOU JUST APPLY * A VALUE. * *************************************************************************** * * Compilation model and measurement (IMPORTANT): * * This C version of Dhrystone consists of three files: * dhry.h (this file, containing global definitions and comments) * dhry_1.c (containing the code corresponding to Ada package Pack_1) * dhry_2.c (containing the code corresponding to Ada package Pack_2) * * The following "ground rules" apply for measurements: * Separate compilation * No procedure merging * Otherwise, compiler optimizations are allowed but should be indicated * Default results are those without register declarations * See the companion paper "Rationale for Dhrystone Version 2" for a more * detailed discussion of these ground rules. * * For 16Bit processors (e.g. 80186, 80286), times for all compilation * models ("small", "medium", "large" etc.) should be given if possible, * together with a definition of these models for the compiler system used. * ************************************************************************** * * Dhrystone (C version) statistics: * * [Comment from the first distribution, updated for version 2. * Note that because of language differences, the numbers are slightly * different from the Ada version.] * * The following program contains statements of a high level programming * language (here: C) in a distribution considered representative: * * assignments 52 (51.0 %) * control statements 33 (32.4 %) * procedure, function calls 17 (16.7 %) * * 103 statements are dynamically executed. The program is balanced with * respect to the three aspects: * * statement type * operand type * operand locality * operand global, local, parameter, or constant. * * The combination of these three aspects is balanced only approximately. * * 1. Statement Type: * number * * V1 = V2 9 * (incl. V1 = F(..) * V = Constant 12 * Assignment, 7 * with array element * Assignment, 6 * with record component * * 34 34 * * X = Y +||"&&"|"|" Z 5 * X = Y +||"==" Constant 6 * X = X +| 1 3 * X = Y *|/ Z 2 * X = Expression, 1 * two operators * X = Expression, 1 * three operators * * 18 18 * * if .... 14 * with "else" 7 * without "else" 7 * executed 3 * not executed 4 * for ... 7 | counted every time * while ... 4 | the loop condition * do ... while 1 | is evaluated * switch ... 1 * break 1 * declaration with 1 * initialization * * 34 34 * * P (...) procedure call 11 * user procedure 10 * library procedure 1 * X = F (...) * function call 6 * user function 5 * library function 1 * * 17 17 * * 103 * * The average number of parameters in procedure or function calls * is 1.82 (not counting the function values as implicit parameters). * * * 2. Operators * * number approximate * percentage * * Arithmetic 32 50.8 * * 21 33.3 * 7 11.1 * * 3 4.8 * / (int div) 1 1.6 * * Comparison 27 42.8 * * == 9 14.3 * /= 4 6.3 * > 1 1.6 * < 3 4.8 * >= 1 1.6 * <= 9 14.3 * * Logic 4 6.3 * * && (ANDTHEN) 1 1.6 * | (OR) 1 1.6 * ! (NOT) 2 3.2 * * * 63 100.1 * * * 3. Operand Type (counted once per operand reference): * * number approximate * percentage * * Integer 175 72.3 % * Character 45 18.6 % * Pointer 12 5.0 % * String30 6 2.5 % * Array 2 0.8 % * Record 2 0.8 % * * 242 100.0 % * * When there is an access path leading to the final operand (e.g. a record * component), only the final data type on the access path is counted. * * * 4. Operand Locality: * * number approximate * percentage * * local variable 114 47.1 % * global variable 22 9.1 % * parameter 45 18.6 % * value 23 9.5 % * reference 22 9.1 % * function result 6 2.5 % * constant 55 22.7 % * * 242 100.0 % * * * The program does not compute anything meaningful, but it is syntactically * and semantically correct. All variables have a value assigned to them * before they are used as a source operand. * * There has been no explicit effort to account for the effects of a * cache, or to balance the use of long or short displacements for code or * data. * *************************************************************************** */ /* Compiler and system dependent definitions: */ //#define TIMES //typedef int int; //typedef int int; //typedef char char; //typedef int bool; //typedef char Str_30 [31]; //typedef int Arr_1_Dim [50]; //typedef int Arr_2_Dim [50] [50]; using System; using Microsoft.Zelig.Runtime; using System.Globalization; namespace Zelig.UnitTest.Peformance { [ExtendClass( typeof( System.Text.StringBuilder ), NoConstructors = true )] public class StringBuilderImpl { public System.Text.StringBuilder AppendFormat( System.IFormatProvider fmt, string str, object[] args ) { throw new NotSupportedException(); } } public class DhrystoneTest { /* Use times(2) time function unless */ /* explicitly defined otherwise */ //const double Mic_secs_Per_Second = 1000000.0; /* Berkeley UNIX C returns process times in seconds/HZ */ public enum Enumeration { Ident_1, Ident_2, Ident_3, Ident_4, Ident_5 }; /* for bool and enumeration types in Ada, Pascal */ /* General definitions: */ public class Variant { public Enumeration Enum_Comp; public int Int_Comp; public char[] Str_Comp; public Variant() { Enum_Comp = Enumeration.Ident_1; Int_Comp = 0; Str_Comp = new char[30]; } } public class Rec_Type { public Rec_Type Ptr_Comp; public Enumeration Discr; public Variant variant; public Rec_Type() { Discr = Enumeration.Ident_1; Ptr_Comp = null; variant = new Variant(); } } /* **************************************************************************** * * "DHRYSTONE" Benchmark Program * * * Version: C, Version 2.1 * * File: dhry_1.c (part 2 of 3) * * Date: May 25, 1988 * * Author: Reinhold P. Weicker * **************************************************************************** */ /* Global Variables: */ Rec_Type Ptr_Glob, Next_Ptr_Glob; int Int_Glob; bool Bool_Glob; char Ch_1_Glob, Ch_2_Glob; int[] Arr_1_Glob = new int[50]; int[/*,*/] Arr_2_Glob = new int[50 * 50]; /* variables for time measurement: */ /* see library function "times" */ readonly TimeSpan Too_Small_Time = new TimeSpan( 0, 0, 2 ); /* Measurements should last at least about 2 seconds */ DateTime Begin_Time, End_Time; TimeSpan User_Time; int DrystonesPerSecond; double Microseconds, Dhrystones_Per_Second; /* end of variables for time measurement */ public static void Main() { DhrystoneTest t = new DhrystoneTest(); t.TestMain( 500000 ); } /*****/ private readonly char[] c_SomeString; private readonly char[] c_FirstString; private readonly char[] c_SecondString; private readonly char[] c_ThirdString; public DhrystoneTest() { c_SomeString = "DHRYSTONE PROGRAM, SOME STRING".ToCharArray(); c_FirstString = "DHRYSTONE PROGRAM, 1'ST STRING".ToCharArray(); c_SecondString = "DHRYSTONE PROGRAM, 2'ND STRING".ToCharArray(); c_ThirdString = "DHRYSTONE PROGRAM, 3'RD STRING".ToCharArray(); } public void TestMain( int Number_Of_Runs ) /* main program, corresponds to procedures */ /* Main and Proc_0 in the Ada version */ { int Int_1_Loc = 0; int Int_2_Loc = 0; int Int_3_Loc = 0; char Ch_Index; Enumeration Enum_Loc = Enumeration.Ident_5; char[] Str_1_Loc = new char[30]; char[] Str_2_Loc = new char[30]; int Run_Index; //int Number_Of_Runs = numRuns; /* Initializations */ Next_Ptr_Glob = new Rec_Type(); Ptr_Glob = new Rec_Type(); Ptr_Glob.Ptr_Comp = Next_Ptr_Glob; Ptr_Glob.Discr = Enumeration.Ident_1; Ptr_Glob.variant.Enum_Comp = Enumeration.Ident_3; Ptr_Glob.variant.Int_Comp = 40; Array.Copy( c_SomeString, Ptr_Glob.variant.Str_Comp, c_SomeString.Length ); Array.Copy( c_FirstString, Str_1_Loc, c_FirstString.Length ); Arr_2_Glob[8 + 7 * 50] = 10; /* Was missing in published program. Without this statement, */ /* Arr_2_Glob [8][7] would have an undefined value. */ /* Warning: With 16Bit processors and Number_Of_Runs > 32000, */ /* overflow may occur for this array element. */ #if PRINTOUT Console.WriteLine( "" ); Console.WriteLine( "Dhrystone Benchmark, Version 2.1 (Language: C#)" ); Console.WriteLine( "" ); //Console.WriteLine("Please give the number of runs through the benchmark: "); //{ // int n; // scanf ("{0}", &n); // Number_Of_Runs = n; //} Console.WriteLine( "" ); Console.WriteLine( "Execution starts, {0} runs through Dhrystone", Number_Of_Runs ); #endif /***************/ /* Start timer */ /***************/ Begin_Time = DateTime.Now; for(Run_Index = 1; Run_Index <= Number_Of_Runs; ++Run_Index) { Proc_5(); Proc_4(); /* Ch_1_Glob == 'A', Ch_2_Glob == 'B', Bool_Glob == true */ Int_1_Loc = 2; Int_2_Loc = 3; Array.Copy( c_SecondString, Str_2_Loc, c_SecondString.Length ); Enum_Loc = Enumeration.Ident_2; Bool_Glob = !Func_2( Str_1_Loc, Str_2_Loc ); /* Bool_Glob == 1 */ while(Int_1_Loc < Int_2_Loc) /* loop body executed once */ { Int_3_Loc = 5 * Int_1_Loc - Int_2_Loc; /* Int_3_Loc == 7 */ Proc_7( Int_1_Loc, Int_2_Loc, ref Int_3_Loc ); /* Int_3_Loc == 7 */ Int_1_Loc += 1; } /* while */ /* Int_1_Loc == 3, Int_2_Loc == 3, Int_3_Loc == 7 */ Proc_8( Arr_1_Glob, Arr_2_Glob, Int_1_Loc, Int_3_Loc ); /* Int_Glob == 5 */ Proc_1( ref Ptr_Glob ); for(Ch_Index = 'A'; Ch_Index <= Ch_2_Glob; ++Ch_Index) /* loop body executed twice */ { if(Enum_Loc == Func_1( Ch_Index, 'C' )) /* then, not executed */ { Proc_6( Enumeration.Ident_1, ref Enum_Loc ); Array.Copy( c_ThirdString, Str_2_Loc, c_ThirdString.Length ); Int_2_Loc = Run_Index; Int_Glob = Run_Index; } } /* Int_1_Loc == 3, Int_2_Loc == 3, Int_3_Loc == 7 */ Int_2_Loc = Int_2_Loc * Int_1_Loc; Int_1_Loc = Int_2_Loc / Int_3_Loc; Int_2_Loc = 7 * ( Int_2_Loc - Int_3_Loc ) - Int_1_Loc; /* Int_1_Loc == 1, Int_2_Loc == 13, Int_3_Loc == 7 */ Proc_2( ref Int_1_Loc ); /* Int_1_Loc == 5 */ } /* loop "for Run_Index" */ /**************/ /* Stop timer */ /**************/ End_Time = DateTime.Now; #if PRINTOUT Console.WriteLine( "Execution ends" ); Console.WriteLine( "" ); Console.WriteLine( "Final values of the variables used in the benchmark:" ); Console.WriteLine( "" ); Console.WriteLine( "Int_Glob: {0}", Int_Glob ); Console.WriteLine( " should be: {0}", 5 ); Console.WriteLine( "Bool_Glob: {0}", Bool_Glob ); Console.WriteLine( " should be: {0}", "True" ); Console.WriteLine( "Ch_1_Glob: {0}", Ch_1_Glob ); Console.WriteLine( " should be: {0}", 'A' ); Console.WriteLine( "Ch_2_Glob: {0}", Ch_2_Glob ); Console.WriteLine( " should be: {0}", 'B' ); Console.WriteLine( "Arr_1_Glob[8]: {0}", Arr_1_Glob[8] ); Console.WriteLine( " should be: {0}", 7 ); Console.WriteLine( "Arr_2_Glob[8][7]: {0}", Arr_2_Glob[8 + 7 * 50] ); Console.WriteLine( " should be: Number_Of_Runs + 10" ); Console.WriteLine( "Ptr_Glob>" ); Console.WriteLine( " Ptr_Comp: {0}", Ptr_Glob.Ptr_Comp ); Console.WriteLine( " should be: (implementationdependent)" ); Console.WriteLine( " Discr: {0}", (int)Ptr_Glob.Discr ); Console.WriteLine( " should be: {0}", 0 ); Console.WriteLine( " Enum_Comp: {0}", (int)Ptr_Glob.variant.Enum_Comp ); Console.WriteLine( " should be: {0}", 2 ); Console.WriteLine( " Int_Comp: {0}", Ptr_Glob.variant.Int_Comp ); Console.WriteLine( " should be: {0}", 17 ); Console.WriteLine( " Str_Comp: {0}", new string( Ptr_Glob.variant.Str_Comp ) ); Console.WriteLine( " should be: DHRYSTONE PROGRAM, SOME STRING" ); Console.WriteLine( "Next_Ptr_Glob>" ); Console.WriteLine( " Ptr_Comp: {0}", Next_Ptr_Glob.Ptr_Comp ); Console.WriteLine( " should be: (implementationdependent), same as above" ); Console.WriteLine( " Discr: {0}", (int)Next_Ptr_Glob.Discr ); Console.WriteLine( " should be: {0}", 0 ); Console.WriteLine( " Enum_Comp: {0}", (int)Next_Ptr_Glob.variant.Enum_Comp ); Console.WriteLine( " should be: {0}", 1 ); Console.WriteLine( " Int_Comp: {0}", (int)Next_Ptr_Glob.variant.Int_Comp ); Console.WriteLine( " should be: {0}", 18 ); Console.WriteLine( " Str_Comp: {0}", Next_Ptr_Glob.variant.Str_Comp ); Console.WriteLine( " should be: DHRYSTONE PROGRAM, SOME STRING" ); Console.WriteLine( "Int_1_Loc: {0}", Int_1_Loc ); Console.WriteLine( " should be: {0}", 5 ); Console.WriteLine( "Int_2_Loc: {0}", Int_2_Loc ); Console.WriteLine( " should be: {0}", 13 ); Console.WriteLine( "Int_3_Loc: {0}", Int_3_Loc ); Console.WriteLine( " should be: {0}", 7 ); Console.WriteLine( "Enum_Loc: {0}", (int)Enum_Loc ); Console.WriteLine( " should be: {0}", 1 ); Console.WriteLine( "Str_1_Loc: {0}", new string( Str_1_Loc ) ); Console.WriteLine( " should be: DHRYSTONE PROGRAM, 1'ST STRING" ); Console.WriteLine( "Str_2_Loc: {0}", new string( Str_2_Loc ) ); Console.WriteLine( " should be: DHRYSTONE PROGRAM, 2'ND STRING" ); Console.WriteLine( "" ); #endif User_Time = End_Time - Begin_Time; #if PRINTOUT if(User_Time < Too_Small_Time) { Console.WriteLine( "Measured time too small to obtain meaningful results" ); Console.WriteLine( "Please increase number of runs" ); Console.WriteLine( "" ); } //else #endif { Microseconds = (double)(User_Time.Ticks / (TimeSpan.TicksPerMillisecond/1000)) / (double)Number_Of_Runs; Dhrystones_Per_Second = (double)(Number_Of_Runs * TimeSpan.TicksPerSecond) / (double)User_Time.Ticks; DrystonesPerSecond = (int)(Dhrystones_Per_Second + 0.5); #if PRINTOUT Console.WriteLine( "Microseconds for one run through Dhrystone: " ); Console.WriteLine( "{0} ", Microseconds ); Console.WriteLine( "Dhrystones per Second: " ); Console.WriteLine( "{0} ", Dhrystones_Per_Second ); Console.WriteLine( "" ); #endif } } private void structassign( Rec_Type a, Rec_Type b ) { a.Discr = b.Discr; a.Ptr_Comp = b.Ptr_Comp; a.variant.Enum_Comp = b.variant.Enum_Comp; a.variant.Int_Comp = b.variant.Int_Comp; Array.Copy( b.variant.Str_Comp, a.variant.Str_Comp, a.variant.Str_Comp.Length ); } private void Proc_1( ref Rec_Type Ptr_Val_Par ) /******************/ /* executed once */ { Rec_Type Next_Record = Ptr_Val_Par.Ptr_Comp; /* == Ptr_Glob_Next */ /* Local variable, initialized with Ptr_Val_Par.Ptr_Comp, */ /* corresponds to "rename" in Ada, "with" in Pascal */ structassign( Ptr_Val_Par.Ptr_Comp, Ptr_Glob ); Ptr_Val_Par.variant.Int_Comp = 5; Next_Record.variant.Int_Comp = Ptr_Val_Par.variant.Int_Comp; Next_Record.Ptr_Comp = Ptr_Val_Par.Ptr_Comp; Rec_Type tmp = Next_Record.Ptr_Comp; Proc_3( ref tmp ); Next_Record.Ptr_Comp = tmp; /* Ptr_Val_Par.Ptr_Comp.Ptr_Comp == Ptr_Glob.Ptr_Comp */ if(Next_Record.Discr == Enumeration.Ident_1) /* then, executed */ { Next_Record.variant.Int_Comp = 6; Enumeration tmpE = Next_Record.variant.Enum_Comp; Proc_6( Ptr_Val_Par.variant.Enum_Comp, ref tmpE ); Next_Record.variant.Enum_Comp = tmpE; Next_Record.Ptr_Comp = Ptr_Glob.Ptr_Comp; int tmpI = Next_Record.variant.Int_Comp; Proc_7( Next_Record.variant.Int_Comp, 10, ref tmpI ); Next_Record.variant.Int_Comp = tmpI; } else /* not executed */ { structassign( Ptr_Val_Par, Ptr_Val_Par.Ptr_Comp ); } } /* Proc_1 */ private void Proc_2( ref int Int_Par_Ref ) /******************/ /* executed once */ /* *Int_Par_Ref == 1, becomes 4 */ { int Int_Loc; Enumeration Enum_Loc = Enumeration.Ident_5; Int_Loc = Int_Par_Ref + 10; do /* executed once */ if(Ch_1_Glob == 'A') /* then, executed */ { Int_Loc -= 1; Int_Par_Ref = Int_Loc - Int_Glob; Enum_Loc = Enumeration.Ident_1; } /* if */ while(Enum_Loc != Enumeration.Ident_1); /* true */ } /* Proc_2 */ private void Proc_3( ref Rec_Type Ptr_Ref_Par ) /******************/ /* executed once */ /* Ptr_Ref_Par becomes Ptr_Glob */ { if(Ptr_Glob != null) /* then, executed */ Ptr_Ref_Par = Ptr_Glob.Ptr_Comp; int tmp = Ptr_Glob.variant.Int_Comp; Proc_7( 10, Int_Glob, ref tmp ); Ptr_Glob.variant.Int_Comp = tmp; } /* Proc_3 */ private void Proc_4() /* without parameters */ /*******/ /* executed once */ { bool Bool_Loc; Bool_Loc = Ch_1_Glob == 'A'; Bool_Glob = Bool_Loc | Bool_Glob; Ch_2_Glob = 'B'; } /* Proc_4 */ private void Proc_5() /* without parameters */ /*******/ /* executed once */ { Ch_1_Glob = 'A'; Bool_Glob = false; } /* Proc_5 */ /* **************************************************************************** * * "DHRYSTONE" Benchmark Program * * * Version: C, Version 2.1 * * File: dhry_2.c (part 3 of 3) * * Date: May 25, 1988 * * Author: Reinhold P. Weicker * **************************************************************************** */ private void Proc_6( Enumeration Enum_Val_Par, ref Enumeration Enum_Ref_Par ) /*********************************/ /* executed once */ /* Enum_Val_Par == Ident_3, Enum_Ref_Par becomes Ident_2 */ { Enum_Ref_Par = Enum_Val_Par; if(!Func_3( Enum_Val_Par )) /* then, not executed */ Enum_Ref_Par = Enumeration.Ident_4; switch(Enum_Val_Par) { case Enumeration.Ident_1: Enum_Ref_Par = Enumeration.Ident_1; break; case Enumeration.Ident_2: if(Int_Glob > 100) /* then */ Enum_Ref_Par = Enumeration.Ident_1; else Enum_Ref_Par = Enumeration.Ident_4; break; case Enumeration.Ident_3: /* executed */ Enum_Ref_Par = Enumeration.Ident_2; break; case Enumeration.Ident_4: break; case Enumeration.Ident_5: Enum_Ref_Par = Enumeration.Ident_3; break; } /* switch */ } /* Proc_6 */ private void Proc_7( int Int_1_Par_Val, int Int_2_Par_Val, ref int Int_Par_Ref ) /**********************************************/ /* executed three times */ /* first call: Int_1_Par_Val == 2, Int_2_Par_Val == 3, */ /* Int_Par_Ref becomes 7 */ /* second call: Int_1_Par_Val == 10, Int_2_Par_Val == 5, */ /* Int_Par_Ref becomes 17 */ /* third call: Int_1_Par_Val == 6, Int_2_Par_Val == 10, */ /* Int_Par_Ref becomes 18 */ { int Int_Loc; Int_Loc = Int_1_Par_Val + 2; Int_Par_Ref = Int_2_Par_Val + Int_Loc; } /* Proc_7 */ private void Proc_8( int[] Arr_1_Par_Ref, int[/*,*/] Arr_2_Par_Ref, int Int_1_Par_Val, int Int_2_Par_Val ) /*********************************************************************/ /* executed once */ /* Int_Par_Val_1 == 3 */ /* Int_Par_Val_2 == 7 */ { int Int_Index; int Int_Loc; Int_Loc = Int_1_Par_Val + 5; Arr_1_Par_Ref[Int_Loc] = Int_2_Par_Val; Arr_1_Par_Ref[Int_Loc + 1] = Arr_1_Par_Ref[Int_Loc]; Arr_1_Par_Ref[Int_Loc + 30] = Int_Loc; for(Int_Index = Int_Loc; Int_Index <= Int_Loc + 1; ++Int_Index) Arr_2_Par_Ref[Int_Loc + Int_Index * 50] = Int_Loc; Arr_2_Par_Ref[Int_Loc + ( Int_Loc - 1 ) * 50] += 1; Arr_2_Par_Ref[Int_Loc + 20 + ( Int_Loc * 50 )] = Arr_1_Par_Ref[Int_Loc]; Int_Glob = 5; } /* Proc_8 */ private Enumeration Func_1( char Ch_1_Par_Val, char Ch_2_Par_Val ) /*************************************************/ /* executed three times */ /* first call: Ch_1_Par_Val == 'H', Ch_2_Par_Val == 'R' */ /* second call: Ch_1_Par_Val == 'A', Ch_2_Par_Val == 'C' */ /* third call: Ch_1_Par_Val == 'B', Ch_2_Par_Val == 'C' */ { char Ch_1_Loc; char Ch_2_Loc; Ch_1_Loc = Ch_1_Par_Val; Ch_2_Loc = Ch_1_Loc; if(Ch_2_Loc != Ch_2_Par_Val) /* then, executed */ return ( Enumeration.Ident_1 ); else /* not executed */ { Ch_1_Glob = Ch_1_Loc; return ( Enumeration.Ident_2 ); } } /* Func_1 */ private int STRCMP( char[] a, char[] b ) { int lenA = a.Length; int lenB = b.Length; int min = lenA < lenB ? lenA : lenB; int i = 0; if(lenB < min) min = lenB; for(; i < min; i++) { if(a[i] != b[i]) { return a[i] < b[i] ? -1 : 1; } } return lenA == lenB ? 0 : lenA < lenB ? -1 : 1; } private bool Func_2( char[] Str_1_Par_Ref, char[] Str_2_Par_Ref ) /*************************************************/ /* executed once */ /* Str_1_Par_Ref == "DHRYSTONE PROGRAM, 1'ST STRING" */ /* Str_2_Par_Ref == "DHRYSTONE PROGRAM, 2'ND STRING" */ { int Int_Loc; char Ch_Loc = '~'; Int_Loc = 2; while(Int_Loc <= 2) /* loop body executed once */ if(Func_1( Str_1_Par_Ref[Int_Loc], Str_2_Par_Ref[Int_Loc + 1] ) == Enumeration.Ident_1) /* then, executed */ { Ch_Loc = 'A'; Int_Loc += 1; } /* if, while */ if(Ch_Loc >= 'W' && Ch_Loc < 'Z') /* then, not executed */ Int_Loc = 7; if(Ch_Loc == 'R') /* then, not executed */ return ( true ); else /* executed */ { if(STRCMP( Str_1_Par_Ref, Str_2_Par_Ref ) > 0) /* then, not executed */ { Int_Loc += 7; Int_Glob = Int_Loc; return ( true ); } else /* executed */ return ( false ); } /* if Ch_Loc */ } /* Func_2 */ private bool Func_3( Enumeration Enum_Par_Val ) /***************************/ /* executed once */ /* Enum_Par_Val == Ident_3 */ { Enumeration Enum_Loc; Enum_Loc = Enum_Par_Val; if(Enum_Loc == Enumeration.Ident_3) /* then, executed */ return ( true ); else /* not executed */ return ( false ); } /* Func_3 */ } } ================================================ FILE: Zelig/Zelig/RunTime/DeviceModels/Perf/Whetstone/Properties/AssemblyInfo.cs ================================================ using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; // General Information about an assembly is controlled through the following // set of attributes. Change these attribute values to modify the information // associated with an assembly. [assembly: AssemblyTitle( "CryptoTest" )] [assembly: AssemblyDescription( "" )] [assembly: AssemblyConfiguration( "" )] [assembly: AssemblyCompany( "Microsoft" )] [assembly: AssemblyProduct( "CryptoTest" )] [assembly: AssemblyCopyright( "Copyright © Microsoft 2012" )] [assembly: AssemblyTrademark( "" )] [assembly: AssemblyCulture( "" )] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible( false )] // The following GUID is for the ID of the typelib if this project is exposed to COM [assembly: Guid( "a1779cdc-5d49-4dd8-93aa-5093a45a444d" )] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Build and Revision Numbers // by using the '*' as shown below: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion( "1.0.0.0" )] [assembly: AssemblyFileVersion( "1.0.0.0" )] ================================================ FILE: Zelig/Zelig/RunTime/DeviceModels/Perf/Whetstone/Whetstone.cs ================================================ using System; using System.Collections.Generic; using System.Linq; using System.Text; using Microsoft.Zelig.Runtime; using System.Globalization; namespace WhetstoneTest { [ExtendClass( typeof( System.Text.StringBuilder ), NoConstructors = true )] public class StringBuilderImpl { public System.Text.StringBuilder AppendFormat( System.IFormatProvider fmt, string str, object[] args ) { throw new NotSupportedException(); } } /* * C Converted Whetstone Double Precision Benchmark * Version 1.2 22 March 1998 * * (c) Copyright 1998 Painter Engineering, Inc. * All Rights Reserved. * * Permission is granted to use, duplicate, and * publish this text and program as long as it * includes this entire comment block and limited * rights reference. * * Converted by Rich Painter, Painter Engineering, Inc. based on the * www.netlib.org benchmark/whetstoned version obtained 16 March 1998. * * A novel approach was used here to keep the look and feel of the * FORTRAN version. Altering the FORTRAN-based array indices, * starting at element 1, to start at element 0 for C, would require * numerous changes, including decrementing the variable indices by 1. * Instead, the array E1[] was declared 1 element larger in C. This * allows the FORTRAN index range to function without any literal or * variable indices changes. The array element E1[0] is simply never * used and does not alter the benchmark results. * * The major FORTRAN comment blocks were retained to minimize * differences between versions. Modules N5 and N12, like in the * FORTRAN version, have been eliminated here. * * An optional command-line argument has been provided [-c] to * offer continuous repetition of the entire benchmark. * An optional argument for setting an alternate LOOP count is also * provided. Define PRINTOUT to cause the POUT() function to print * outputs at various stages. Final timing measurements should be * made with the PRINTOUT undefined. * * Questions and comments may be directed to the author at * r.painter@ieee.org */ /* C********************************************************************** C Benchmark #2 -- Double Precision Whetstone (A001) C C o This is a REAL*8 version of C the Whetstone benchmark program. C C o DO-loop semantics are ANSI-66 compatible. C C o Final measurements are to be made with all C WRITE statements and FORMAT sttements removed. C C********************************************************************** */ /* map the FORTRAN math functions, etc. to the C versions */ //#define Math.Sin sin //#define Math.Cos cos //#define Math.Atan atan //#define DLOG log //#define DEXP exp //#define DSQRT sqrt //#define IF if ///* function prototypes */ //void POUT(long N, long J, long K, double X1, double X2, double X3, double X4); //void PA(double E[]); //void P0(void); //void P3(double X, double Y, double *Z); //#define USAGE "usage: whetdc [-c] [loops]" /* COMMON T,T1,T2,E1(4),J,K,L */ public class WhetstoneTest { double T, T1, T2; double[] E1 = new double[5]; int J, K, L, iKIPS; public static void Main() { WhetstoneTest tst = new WhetstoneTest(); tst.TestMain( 500 ); } public void TestMain( int iterations ) { /* used in the FORTRAN version */ long I; long N1, N2, N3, N4, N6, N7, N8, N9, N10, N11; double X1, X2, X3, X4, X, Y, Z; long LOOP; int II, JJ; /* added for this version */ DateTime startsec, finisec; double KIPS; //int continuous; //continuous = 0; /* C C Start benchmark timing at this point. C */ startsec = DateTime.Now; /* C C The actual benchmark starts here. C */ T = .499975; T1 = 0.50025; T2 = 2.0; /* C C With loopcount LOOP=10, one million Whetstone instructions C will be executed in EACH MAJOR LOOP..A MAJOR LOOP IS EXECUTED C 'II' TIMES TO INCREASE WALL-CLOCK TIMING ACCURACY. C LOOP = 1000; */ LOOP = 10; II = iterations; JJ = 1; IILOOP: N1 = 0; N2 = 12 * LOOP; N3 = 14 * LOOP; N4 = 345 * LOOP; N6 = 210 * LOOP; N7 = 32 * LOOP; N8 = 899 * LOOP; N9 = 616 * LOOP; N10 = 0; N11 = 93 * LOOP; /* C C Module 1: Simple identifiers C */ X1 = 1.0; X2 = -1.0; X3 = -1.0; X4 = -1.0; for(I = 1; I <= N1; I++) { X1 = ( X1 + X2 + X3 - X4 ) * T; X2 = ( X1 + X2 - X3 + X4 ) * T; X3 = ( X1 - X2 + X3 + X4 ) * T; X4 = ( -X1 + X2 + X3 + X4 ) * T; } #if PRINTOUT IF (JJ==II)POUT(N1,N1,N1,X1,X2,X3,X4); #endif /* C C Module 2: Array elements C */ E1[1] = 1.0; E1[2] = -1.0; E1[3] = -1.0; E1[4] = -1.0; for(I = 1; I <= N2; I++) { E1[1] = ( E1[1] + E1[2] + E1[3] - E1[4] ) * T; E1[2] = ( E1[1] + E1[2] - E1[3] + E1[4] ) * T; E1[3] = ( E1[1] - E1[2] + E1[3] + E1[4] ) * T; E1[4] = ( -E1[1] + E1[2] + E1[3] + E1[4] ) * T; } #if PRINTOUT IF (JJ==II)POUT(N2,N3,N2,E1[1],E1[2],E1[3],E1[4]); #endif /* C C Module 3: Array as parameter C */ for(I = 1; I <= N3; I++) PA( E1 ); #if PRINTOUT IF (JJ==II)POUT(N3,N2,N2,E1[1],E1[2],E1[3],E1[4]); #endif /* C C Module 4: Conditional jumps C */ J = 1; for(I = 1; I <= N4; I++) { if(J == 1) J = 2; else J = 3; if(J > 2) J = 0; else J = 1; if(J < 1) J = 1; else J = 0; } #if PRINTOUT IF (JJ==II)POUT(N4,J,J,X1,X2,X3,X4); #endif /* C C Module 5: Omitted C Module 6: Integer arithmetic C */ J = 1; K = 2; L = 3; for(I = 1; I <= N6; I++) { J = J * ( K - J ) * ( L - K ); K = L * K - ( L - J ) * K; L = ( L - K ) * ( K + J ); E1[L - 1] = J + K + L; E1[K - 1] = J * K * L; } #if PRINTOUT IF (JJ==II)POUT(N6,J,K,E1[1],E1[2],E1[3],E1[4]); #endif /* C C Module 7: Trigonometric functions C */ X = 0.5; Y = 0.5; for(I = 1; I <= N7; I++) { X = T * Math.Atan( T2 * Math.Sin( X ) * Math.Cos( X ) / ( Math.Cos( X + Y ) + Math.Cos( X - Y ) - 1.0 ) ); Y = T * Math.Atan( T2 * Math.Sin( Y ) * Math.Cos( Y ) / ( Math.Cos( X + Y ) + Math.Cos( X - Y ) - 1.0 ) ); } #if PRINTOUT IF (JJ==II)POUT(N7,J,K,X,X,Y,Y); #endif /* C C Module 8: Procedure calls C */ X = 1.0; Y = 1.0; Z = 1.0; for(I = 1; I <= N8; I++) P3( X, Y, ref Z ); #if PRINTOUT IF (JJ==II)POUT(N8,J,K,X,Y,Z,Z); #endif /* C C Module 9: Array references C */ J = 1; K = 2; L = 3; E1[1] = 1.0; E1[2] = 2.0; E1[3] = 3.0; for(I = 1; I <= N9; I++) P0(); #if PRINTOUT IF (JJ==II)POUT(N9,J,K,E1[1],E1[2],E1[3],E1[4]); #endif /* C C Module 10: Integer arithmetic C */ J = 2; K = 3; for(I = 1; I <= N10; I++) { J = J + K; K = J + K; J = K - J; K = K - J - J; } #if PRINTOUT IF (JJ==II)POUT(N10,J,K,X1,X2,X3,X4); #endif /* C C Module 11: Standard functions C */ X = 0.75; for(I = 1; I <= N11; I++) X = Math.Sqrt( Math.Exp( Math.Log( X ) / T1 ) ); #if PRINTOUT IF (JJ==II)POUT(N11,J,K,X,X,X,X); #endif /* C C THIS IS THE END OF THE MAJOR LOOP. C */ if(++JJ <= II) goto IILOOP; /* C C Stop benchmark timing at this point. C */ finisec = DateTime.Now; /* C---------------------------------------------------------------- C Performance in Whetstone KIP's per second is given by C C (100*LOOP*II)/TIME C C where TIME is in seconds. C-------------------------------------------------------------------- */ #if PRINTOUT Console.WriteLine( "" ); #endif if(finisec <= startsec) { #if PRINTOUT Console.WriteLine( "Insufficient duration- Increase the LOOP count" ); #endif return; } #if PRINTOUT Console.WriteLine( "Loops: {0}, Iterations: {1}, Duration: {2} sec.", LOOP, II, finisec - startsec ); #endif KIPS = ( 100.0 * LOOP * II ) / (double)( finisec - startsec ).TotalSeconds; iKIPS = (int)KIPS; #if PRINTOUT if(KIPS >= 1000.0) Console.WriteLine( "C Converted Double Precision Whetstones: {0} MIPS", KIPS / 1000.0 ); else Console.WriteLine( "C Converted Double Precision Whetstones: {0} KIPS", KIPS ); #endif //if (continuous) // goto LCONT; return; } void PA( double[] E ) { J = 0; L10: E[1] = ( E[1] + E[2] + E[3] - E[4] ) * T; E[2] = ( E[1] + E[2] - E[3] + E[4] ) * T; E[3] = ( E[1] - E[2] + E[3] + E[4] ) * T; E[4] = ( -E[1] + E[2] + E[3] + E[4] ) / T2; J += 1; if(J < 6) goto L10; } void P0() { E1[J] = E1[K]; E1[K] = E1[L]; E1[L] = E1[J]; } void P3( double X, double Y, ref double Z ) { double X1, Y1; X1 = X; Y1 = Y; X1 = T * ( X1 + Y1 ); Y1 = T * ( X1 + Y1 ); Z = ( X1 + Y1 ) / T2; } #if PRINTOUT void POUT(long N, long J, long K, double X1, double X2, double X3, double X4) { Console.WriteLine("%7ld %7ld %7ld %12.4e %12.4e %12.4e %12.4e", N, J, K, X1, X2, X3, X4); } #endif } } ================================================ FILE: Zelig/Zelig/RunTime/DeviceModels/Perf/Whetstone/WhetstoneTest.csproj ================================================  Debug x86 8.0.30703 2.0 {22248085-CA53-485F-9A71-968A7AC42B04} Exe Properties WhetstoneTest WhetstoneTest v4.5 512 true $(LlilumBuildRoot)\Target\bin\$(Configuration)\ DEBUG;TRACE true true true full AnyCPU prompt MinimumRecommendedRules.ruleset $(LlilumBuildRoot)\Target\bin\$(Configuration)\ TRACE true true true true pdbonly AnyCPU prompt MinimumRecommendedRules.ruleset true $(LlilumBuildRoot)\Target\bin\$(Configuration)\ DEBUG;TRACE true true true full AnyCPU MinimumRecommendedRules.ruleset {186F31A3-EF89-4A25-B2D5-20060501AA01} mscorlib False {186F31A3-EF89-4A25-B2D5-20070702AA01} system False {186F31A3-EF89-4A25-B2D5-20061218AA01} Common False {186F31A3-EF89-4A25-B2D5-20060509AA01} Kernel False {186F31A3-EF89-4A25-B2D5-20060720AA01} TypeSystem False ================================================ FILE: Zelig/Zelig/RunTime/DeviceModels/Perf/v8/crypto/CryptoTest/CryptoTest.csproj ================================================  Debug x86 8.0.30703 2.0 {242A3A91-4622-4463-8A89-608908C7C540} Exe Properties CryptoTest CryptoTest v4.5 512 true $(LlilumBuildRoot)\Target\bin\$(Configuration)\ DEBUG;TRACE true true full AnyCPU prompt MinimumRecommendedRules.ruleset $(LlilumBuildRoot)\Target\bin\$(Configuration)\ TRACE true true true pdbonly AnyCPU prompt MinimumRecommendedRules.ruleset true $(LlilumBuildRoot)\Target\bin\$(Configuration)\ DEBUG;TRACE true true true full AnyCPU MinimumRecommendedRules.ruleset {186F31A3-EF89-4A25-B2D5-20060501AA01} mscorlib False {186F31A3-EF89-4A25-B2D5-20070702AA01} system False {186F31A3-EF89-4A25-B2D5-20061218AA01} Common False {186F31A3-EF89-4A25-B2D5-20060509AA01} Kernel False {186F31A3-EF89-4A25-B2D5-20060720AA01} TypeSystem False ================================================ FILE: Zelig/Zelig/RunTime/DeviceModels/Perf/v8/crypto/CryptoTest/Properties/AssemblyInfo.cs ================================================ using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; // General Information about an assembly is controlled through the following // set of attributes. Change these attribute values to modify the information // associated with an assembly. [assembly: AssemblyTitle( "CryptoTest" )] [assembly: AssemblyDescription( "" )] [assembly: AssemblyConfiguration( "" )] [assembly: AssemblyCompany( "Microsoft" )] [assembly: AssemblyProduct( "CryptoTest" )] [assembly: AssemblyCopyright( "Copyright © Microsoft 2012" )] [assembly: AssemblyTrademark( "" )] [assembly: AssemblyCulture( "" )] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible( false )] // The following GUID is for the ID of the typelib if this project is exposed to COM [assembly: Guid( "a1779cdc-5d49-4dd8-93aa-5093a45a444d" )] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Build and Revision Numbers // by using the '*' as shown below: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion( "1.0.0.0" )] [assembly: AssemblyFileVersion( "1.0.0.0" )] ================================================ FILE: Zelig/Zelig/RunTime/DeviceModels/Perf/v8/crypto/CryptoTest/crypto.cs ================================================ // Comment this out to use a fixed random number seed. #define OUTLINE_LISTX_EXTEND //#define USE_RANDOM_SEED /* * Copyright (c) 2003-2005 Tom Wu * All Rights Reserved. * * Permission is hereby granted, free of charge, to any person obtaining * a copy of this software and associated documentation files (the * "Software"), to deal in the Software without restriction, including * without limitation the rights to use, copy, modify, merge, publish, * distribute, sublicense, and/or sell copies of the Software, and to * permit persons to whom the Software is furnished to do so, subject to * the following conditions: * * The above copyright notice and this permission notice shall be * included in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS-IS" AND WITHOUT WARRANTY OF ANY KIND, * EXPRESS, IMPLIED OR OTHERWISE, INCLUDING WITHOUT LIMITATION, ANY * WARRANTY OF MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE. * * IN NO EVENT SHALL TOM WU BE LIABLE FOR ANY SPECIAL, INCIDENTAL, * INDIRECT OR CONSEQUENTIAL DAMAGES OF ANY KIND, OR ANY DAMAGES WHATSOEVER * RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER OR NOT ADVISED OF * THE POSSIBILITY OF DAMAGE, AND ON ANY THEORY OF LIABILITY, ARISING OUT * OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. * * In addition, the following condition applies: * * All redistributions must retain an intact copy of this copyright notice * and disclaimer. */ // The code has been adapted for use as a benchmark by Microsoft. using System; using System.Collections.Generic; using System.Globalization; // using System.Diagnostics; // using System.Text.RegularExpressions; namespace Crypto { class Support { public static void Main() { //(String[] args) { int n = 10; //if (args.Length > 0) { // n = Int32.Parse(args[0]); //} bool verbose = true; //if (args.Length > 1) //{ // switch (args[1]) // { // case "verbose": // verbose = true; // break; // default: // Console.WriteLine("Bad arg: '{0}'.\n", args[1]); // return; // } //} Measure(n, verbose); } public static void Measure(int n, bool verbose) { DateTime start = DateTime.Now; Setup(); for (int i = 0; i < n; i++) { runEncrypt(verbose); runDecrypt(verbose); } DateTime end = DateTime.Now; TimeSpan dur = end - start; Console.WriteLine("Doing {0} iters of Crytpo takes {1} ms; {2} usec/iter.", n, dur.TotalMilliseconds, dur.TotalMilliseconds*1000 / n); } static RSAKey RSA; static String TEXT; static void Setup() { String nValue="a5261939975948bb7a58dffe5ff54e65f0498f9175f5a09288810b8975871e99af3b5dd94057b0fc07535f5f97444504fa35169d461d0d30cf0192e307727c065168c788771c561a9400fb49175e9e6aa4e23fe11af69e9412dd23b0cb6684c4c2429bce139e848ab26d0829073351f4acd36074eafd036a5eb83359d2a698d3"; String eValue="10001"; String dValue="8e9912f6d3645894e8d38cb58c0db81ff516cf4c7e5a14c7f1eddb1459d2cded4d8d293fc97aee6aefb861859c8b6a3d1dfe710463e1f9ddc72048c09751971c4a580aa51eb523357a3cc48d31cfad1d4a165066ed92d4748fb6571211da5cb14bc11b6e2df7c1a559e6d5ac1cd5c94703a22891464fba23d0d965086277a161"; String pValue="d090ce58a92c75233a6486cb0a9209bf3583b64f540c76f5294bb97d285eed33aec220bde14b2417951178ac152ceab6da7090905b478195498b352048f15e7d"; String qValue="cab575dc652bb66df15a0359609d51d1db184750c00c6698b90ef3465c99655103edbf0d54c56aec0ce3c4d22592338092a126a0cc49f65a4a30d222b411e58f"; String dmp1Value="1a24bca8e273df2f0e47c199bbf678604e7df7215480c77c8db39f49b000ce2cf7500038acfff5433b7d582a01f1826e6f4d42e1c57f5e1fef7b12aabc59fd25"; String dmq1Value="3d06982efbbe47339e1f6d36b1216b8a741d410b0c662f54f7118b27b9a4ec9d914337eb39841d8666f3034408cf94f5b62f11c402fc994fe15a05493150d9fd"; String coeffValue="3a3e731acd8960b7ff9eb81a7ff93bd1cfa74cbd56987db58b4594fb09c09084db1734c8143f98b602b981aaa9243ca28deb69b5b280ee8dcee0fd2625e53250"; BigInteger.setupEngine(new BigInteger.AMSig(BigInteger.am3), 28); RSA = new RSAKey(); RSA.setPublic(nValue, eValue); RSA.setPrivateEx(nValue, eValue, dValue, pValue, qValue, dmp1Value, dmq1Value, coeffValue); TEXT = "The quick brown fox jumped over the extremely lazy frogs!"; } public static void runEncrypt(bool verbose) { var res = RSA.encrypt(TEXT); if (verbose) Console.WriteLine("encrypt '{0}' is '{1}'", TEXT, res); TEXT = res; } public static void runDecrypt(bool verbose) { var res = RSA.decrypt(TEXT); if (verbose) Console.WriteLine("decrypt '{0}' is '{1}'", TEXT, res); TEXT = res; } } class ListX : List { public ListX() : base() {} public ListX(int cap) : base(cap) {} #if OUTLINE_LISTX_EXTEND private void ExtendTo(int index) { for(int j = Count; j < index; j++) { base.Add( default( T ) ); } } #endif public new T this[int index] { get { return base[index]; } set { if (index < Count) { base[index] = value; } else { #if OUTLINE_LISTX_EXTEND ExtendTo(index); #else for (int j = Count; j < index; j++) { base.Add(default(T)); } #endif base.Add(value); } } } } // Basic JavaScript BN library - subset useful for RSA encryption. class BigInteger { ListX array; int t; int s; // Bits per digit static int dbits; static int BI_DB; static int BI_DM; static int BI_DV; static int BI_FP; static ulong BI_FV; static int BI_F1; static int BI_F2; // JavaScript engine analysis const long canary = 0xdeadbeefcafe; const bool j_lm = ((canary&0xffffff)==0xefcafe); // (public) Constructor public BigInteger(int a, int b, SecureRandom c) { array = new ListX(); this.fromNumber(a,b,c); } public BigInteger() { array = new ListX(); } public BigInteger(String a) { array = new ListX(); this.fromString(a,256); } public BigInteger(byte[] ba) { array = new ListX(); this.fromByteArray(ba); } public BigInteger(String a, int b) { array = new ListX(); this.fromString(a,b); } // return new, unset BigInteger static BigInteger nbi() { return new BigInteger(); } public delegate int AMSig(BigInteger bi, int i, int x, BigInteger w, int j, int c, int n); static AMSig am; // am: Compute w_j += (x*this_i), propagate carries, // c is initial carry, returns final carry. // c < 3*dvalue, x < 2*dvalue, this_i < dvalue // We need to select the fastest one that works in this environment. // These appear to be unused #if false // am1: use a single mult and divide to get the high bits, // max digit bits should be 26 because // max internal value = 2*dvalue^2-2*dvalue (< 2^53) function am1(i,x,w,j,c,n) { var this_array = this.array; var w_array = w.array; while(--n >= 0) { var v = x*this_array[i++]+w_array[j]+c; c = Math.floor(v/0x4000000); w_array[j++] = v&0x3ffffff; } return c; } // am2 avoids a big mult-and-extract completely. // Max digit bits should be <= 30 because we do bitwise ops // on values up to 2*hdvalue^2-hdvalue-1 (< 2^31) function am2(i,x,w,j,c,n) { var this_array = this.array; var w_array = w.array; var xl = x&0x7fff, xh = x>>15; while(--n >= 0) { var l = this_array[i]&0x7fff; var h = this_array[i++]>>15; var m = xh*l+h*xl; l = xl*l+((m&0x7fff)<<15)+w_array[j]+(c&0x3fffffff); c = (l>>>30)+(m>>>15)+xh*h+(c>>>30); w_array[j++] = l&0x3fffffff; } return c; } #endif // Alternately, set max digit bits to 28 since some // browsers slow down when dealing with 32-bit numbers. public static int am3(BigInteger bi, int i, int x, BigInteger w, int j, int c, int n) { var this_array = bi.array; var w_array = w.array; var xl = x&0x3fff; var xh = x>>14; while(--n >= 0) { var l = this_array[i]&0x3fff; var h = this_array[i++]>>14; var m = xh*l+h*xl; l = xl*l+((m&0x3fff)<<14)+w_array[j]+c; c = (l>>28)+(m>>14)+xh*h; w_array[j++] = l&0xfffffff; } return c; } #if false // This is tailored to VMs with 2-bit tagging. It makes sure // that all the computations stay within the 29 bits available. function am4(i,x,w,j,c,n) { var this_array = this.array; var w_array = w.array; var xl = x&0x1fff, xh = x>>13; while(--n >= 0) { var l = this_array[i]&0x1fff; var h = this_array[i++]>>13; var m = xh*l+h*xl; l = xl*l+((m&0x1fff)<<13)+w_array[j]+c; c = (l>>26)+(m>>13)+xh*h; w_array[j++] = l&0x3ffffff; } return c; } #endif // Digit conversions const String BI_RM = "0123456789abcdefghijklmnopqrstuvwxyz"; static int[] BI_RC; // am3/28 is best for SM, Rhino, but am4/26 is best for v8. // Kestrel (Opera 9.5) gets its best result with am4/26. // IE7 does 9% better with am3/28 than with am4/26. // Firefox (SM) gets 10% faster with am3/28 than with am4/26. public static void setupEngine(AMSig fn, int bits) { BigInteger.am = fn; dbits = bits; BI_DB = dbits; BI_DM = ((((int)1)<<(int)dbits)-1); BI_DV = (((int)1)<<(int)dbits); BI_FP = 52; // The RHS had been Math.Pow(2,BI_FP); BI_FV = (((ulong)1)<<(int)BI_FP); BI_F1 = BI_FP-dbits; BI_F2 = 2*dbits-BI_FP; BI_RC = new int[256]; // char rr = "0".charCodeAt(0); char rr = '0'; for (int vv = 0; vv <= 9; ++vv) BI_RC[rr++] = vv; // rr = 'a".charCodeAt(0); rr = 'a'; for (int vv = 10; vv < 36; ++vv) BI_RC[rr++] = vv; // rr = "A".charCodeAt(0); rr = 'A'; for (int vv = 10; vv < 36; ++vv) BI_RC[rr++] = vv; } static char int2char(int n) { return BI_RM[(int)n]; } static int intAt(String s, int i) { // int c = (int)BI_RC[s[(int)i]]; // return (c==null)?-1:c; if (i > BI_RC.Length) return -1; else return (int)BI_RC[s[(int)i]]; } // (protected) copy this to r private void copyTo(BigInteger r) { var this_array = this.array; var r_array = r.array; for(var i = this.t-1; i >= 0; --i) r_array[i] = this_array[i]; r.t = this.t; r.s = this.s; } // (protected) set from integer value x, -DV <= x < DV private void fromInt(int x) { var this_array = this.array; this.t = 1; this.s = (x<0)?-1:0; if (this_array.Count == 0) { if (x > 0) this_array.Add(x); else if (x < -1) this_array.Add(x + BI_DV); else this.t = 0; } else { if (x > 0) this_array[0] = (int)x; else if (x < -1) this_array[0] = (int)(x + BI_DV); else this.t = 0; } } // return bigint initialized to value static BigInteger nbv(int i) { var r = nbi(); r.fromInt(i); return r; } // (protected) set from string and radix private void fromString(String s, int b) { var this_array = this.array; int k; if(b == 16) k = 4; else if(b == 8) k = 3; else if(b == 256) k = 8; // byte array else if(b == 2) k = 1; else if(b == 32) k = 5; else if(b == 4) k = 2; else { this.fromRadix(s,b); return; } this.t = 0; this.s = 0; int i = s.Length; bool mi = false; var sh = 0; while(--i >= 0) { int x = (k==8) ? (s[i] & 0xff) : intAt(s,(int)i); if(x < 0) { if(s[i] == '-') mi = true; continue; } mi = false; if(sh == 0) this_array[this.t++] = (int)x; else if(sh+k > BI_DB) { this_array[this.t-1] |= ((int)x&((((int)1)<<(BI_DB-sh))-1))<>(BI_DB-sh)); } else this_array[this.t-1] |= ((int)x)<= BI_DB) sh -= BI_DB; } if(k == 8 && (s[0]&0x80) != 0) { this.s = -1; if(sh > 0) this_array[this.t-1] |= ((((int)1)<<(BI_DB-sh))-1)<= 0) { int x = ba[i] & 0xff; mi = false; if (sh == 0) this_array[this.t++] = (int)x; else if (sh + 8 > BI_DB) { this_array[this.t - 1] |= ((int)x & ((((int)1) << (BI_DB - sh)) - 1)) << sh; this_array[this.t++] = ((int)x >> (BI_DB - sh)); } else this_array[this.t - 1] |= ((int)x) << sh; sh += 8; if (sh >= BI_DB) sh -= BI_DB; } if ((ba[0] & 0x80) != 0) { this.s = -1; if (sh > 0) this_array[this.t - 1] |= ((((int)1) << (BI_DB - sh)) - 1) << sh; } this.clamp(); if (mi) BigInteger.ZERO.subTo(this, this); } // (protected) clamp off excess high words private void clamp() { var this_array = this.array; var c = this.s&BI_DM; while(this.t > 0 && this_array[this.t-1] == c) --this.t; } // (public) return string representation in given radix public String toString(int b) { var this_array = this.array; if(this.s < 0) return "-"+this.negate().toString(b); int k; if(b == 16) k = 4; else if(b == 8) k = 3; else if(b == 2) k = 1; else if(b == 32) k = 5; else if(b == 4) k = 2; else return this.toRadix(b); int km = ((int)1< 0) { if(p < BI_DB && (d = this_array[i]>>p) > 0) { m = true; r = new String(int2char(d), 1); } while(i >= 0) { if(p < k) { d = (this_array[i]&((((int)1)<>(p+=(int)(BI_DB-k)); } else { d = (this_array[i]>>(p-=k))&km; if(p <= 0) { p += (int)BI_DB; --i; } } if(d > 0) m = true; if(m) r += int2char(d); } } return m?r:"0"; } // (public) -this public BigInteger negate() { var r = nbi(); BigInteger.ZERO.subTo(this,r); return r; } // (public) |this| public BigInteger abs() { return (this.s<0)?this.negate():this; } // (public) return + if this > a, - if this < a, 0 if equal public int compareTo(BigInteger a) { var this_array = this.array; var a_array = a.array; var r = this.s-a.s; if(r != 0) return r; int i = (int)this.t; r = i-(int)a.t; if(r != 0) return r; while(--i >= 0) if((r=(int)(this_array[i]-a_array[i])) != 0) return r; return 0; } // returns bit length of the integer x public int nbits(int x) { int r = 1; int t; if((t=x>>16) != 0) { x = t; r += 16; } if((t=x>>8) != 0) { x = t; r += 8; } if((t=x>>4) != 0) { x = t; r += 4; } if((t=x>>2) != 0) { x = t; r += 2; } if((t=x>>1) != 0) { x = t; r += 1; } return r; } // (public) return the number of bits in "this" public int bitLength() { var this_array = this.array; if(this.t <= 0) return 0; return ((int)BI_DB)*(this.t-1) + nbits(this_array[this.t-1]^(int)(this.s&BI_DM)); } // (protected) r = this << n*DB private void dLShiftTo(int n, BigInteger r) { var this_array = this.array; var r_array = r.array; for(int i = (int)this.t-1; i >= 0; --i) r_array[i+n] = this_array[i]; for(int i = (int)n-1; i >= 0; --i) r_array[i] = 0; r.t = this.t+(int)n; r.s = this.s; } // (protected) r = this >> n*DB private void dRShiftTo(int n, BigInteger r) { var this_array = this.array; var r_array = r.array; for (var i = n; i < this.t; ++i) r_array[i-n] = this_array[i]; r.t = (int)Math.Max(this.t-n,0); r.s = this.s; } // (protected) r = this << n private void lShiftTo(int n, BigInteger r) { var this_array = this.array; var r_array = r.array; int bs = (int)(n%BI_DB); int cbs = (int)(BI_DB-bs); var bm = ((int)1<= 0; --i) { r_array[i+ds+1] = (this_array[i]>>cbs)|c; c = (this_array[i]&bm)<= 0; --i) r_array[i] = 0; r_array[ds] = c; r.t = this.t+(int)ds+1; r.s = this.s; r.clamp(); } // (protected) r = this >> n private void rShiftTo(int n, BigInteger r) { var this_array = this.array; var r_array = r.array; r.s = this.s; var ds = n/BI_DB; if(ds >= this.t) { r.t = 0; return; } int bs = (int)(n%BI_DB); int cbs = (int)(BI_DB-bs); int bm = ((int)1<>bs; for(int i = ds+1; i < this.t; ++i) { r_array[i-ds-1] |= (this_array[i]&bm)<>bs; } if(bs > 0) r_array[(int)this.t-ds-1] |= ((int)this.s&bm)<>= (int)BI_DB; } if(a.t < this.t) { c -= a.s; while(i < this.t) { c += (int)this_array[i]; r_array[i++] = (int)c&BI_DM; c >>= (int)BI_DB; } c += this.s; } else { c += this.s; while(i < a.t) { c -= (int)a_array[i]; r_array[i++] = (int)c&BI_DM; c >>= (int)BI_DB; } c -= a.s; } r.s = (c<0)?-1:0; if(c < -1) r_array[i++] = (int)((int)BI_DV+c); else if(c > 0) r_array[i++] = (int)c; r.t = i; r.clamp(); } // (protected) r = this * a, r != this,a (HAC 14.12) // "this" should be the larger one if appropriate. private void multiplyTo(BigInteger a, BigInteger r) { var this_array = this.array; var r_array = r.array; var x = this.abs(); var y = a.abs(); var y_array = y.array; int i = (int)x.t; r.t = (int)i+y.t; while(--i >= 0) r_array[i] = 0; for(i = 0; i < y.t; ++i) r_array[i+(int)x.t] = am(x,0,y_array[i],r,(int)i,0,(int)x.t); r.s = 0; r.clamp(); if(this.s != a.s) BigInteger.ZERO.subTo(r,r); } // (protected) r = this^2, r != this (HAC 14.16) private void squareTo(BigInteger r) { var x = this.abs(); var x_array = x.array; var r_array = r.array; int i = (int)(2*x.t); r.t = (int)i; while(--i >= 0) r_array[i] = 0; for(i = 0; i < x.t-1; ++i) { var c = am(x,(int)i,x_array[i],r,(int)(2*i),0,1); if((r_array[(int)i+x.t]+=am(x,(int)(i+1),2*x_array[i],r,(int)(2*i+1),c,(int)x.t-i-1)) >= BI_DV) { r_array[(int)i+x.t] -= BI_DV; r_array[(int)i+x.t+1] = 1; } } if(r.t > 0) r_array[r.t-1] += am(x,(int)i,x_array[i],r,(int)(2*i),0,1); r.s = 0; r.clamp(); } // (protected) divide this by m, quotient and remainder to q, r (HAC 14.20) // r != q, this != m. q or r may be null. private void divRemTo(BigInteger m, BigInteger q, BigInteger r) { #if TRACING this.PrintArray("this"); #endif var pm = m.abs(); if(pm.t <= 0) return; var pt = this.abs(); #if TRACING pt.PrintArray("pt"); #endif if (pt.t < pm.t) { if(q != null) q.fromInt(0); if(r != null) this.copyTo(r); return; } if(r == null) r = nbi(); var y = nbi(); var ts = this.s; var ms = m.s; var pm_array = pm.array; int nsh = BI_DB-(int)nbits(pm_array[pm.t-1]); // normalize modulus if(nsh > 0) { pm.lShiftTo(nsh,y); pt.lShiftTo(nsh,r); } else { pm.copyTo(y); pt.copyTo(r); } int ys = y.t; var y_array = y.array; double y0 = (double)y_array[ys-1]; if(y0 == 0) return; double yt = (y0*(double)((int)1<1)?y_array[ys-2]>>BI_F2:0)); double d1 = ((double)BI_FV)/yt; double d2 = ((double)(1<= 0) { r_array[r.t++] = 1; r.subTo(t,r); } BigInteger.ONE.dLShiftTo((int)ys,t); t.subTo(y,y); // "negative" y so we can replace sub with am later while(y.t < ys) y_array[y.t++] = 0; while(--j >= 0) { // Estimate quotient digit int qd = (r_array[--i]==y0) ? BI_DM : (int)Math.Floor((double)r_array[i]*d1+((double)(r_array[i-1]+e))*d2); if((r_array[i]+=am(y,0,qd,r,(int)j,0,(int)ys)) < qd) { // Try it out y.dLShiftTo(j,t); r.subTo(t,r); while(r_array[i] < --qd) r.subTo(t,r); } } if(q != null) { r.dRShiftTo((int)ys,q); if(ts != ms) BigInteger.ZERO.subTo(q,q); } r.t = (int)ys; r.clamp(); if(nsh > 0) r.rShiftTo(nsh,r); // Denormalize remainder if(ts < 0) BigInteger.ZERO.subTo(r,r); } // (public) this mod a public BigInteger mod(BigInteger a) { var r = nbi(); this.abs().divRemTo(a,null,r); if(this.s < 0 && r.compareTo(BigInteger.ZERO) > 0) a.subTo(r,r); return r; } // Modular reduction using "classic" algorithm public class ClassicReducer: Reducer { BigInteger m; public ClassicReducer(BigInteger m) { this.m = m; } public void reduce(BigInteger x) { x.divRemTo(m,null,x); } public override BigInteger convert(BigInteger x) { if(x.s < 0 || x.compareTo(this.m) >= 0) return x.mod(this.m); else return x; } public override BigInteger revert(BigInteger x) { return x; } public override void mulTo(BigInteger x, BigInteger y, BigInteger r) { x.multiplyTo(y,r); this.reduce(r); } public override void sqrTo(BigInteger x, BigInteger r) { x.squareTo(r); this.reduce(r); } } // (protected) return "-1/this % 2^DB"; useful for Mont. reduction // justification: // xy == 1 (mod m) // xy = 1+km // xy(2-xy) = (1+km)(1-km) // x[y(2-xy)] = 1-k^2m^2 // x[y(2-xy)] == 1 (mod m^2) // if y is 1/x mod m, then y(2-xy) is 1/x mod m^2 // should reduce x and y(2-xy) by m^2 at each step to keep size bounded. // JS multiply "overflows" differently from C/C++, so care is needed here. private int invDigit() { var this_array = this.array; if(this.t < 1) return 0; int x = (int)this_array[0]; if((x&1) == 0) return 0; int y = x&3; // y == 1/x mod 2^2 y = (y*(2-(x&0xf)*y))&0xf; // y == 1/x mod 2^4 y = (y*(2-(x&0xff)*y))&0xff; // y == 1/x mod 2^8 y = (y*(2-(((x&0xffff)*y)&0xffff)))&0xffff; // y == 1/x mod 2^16 // last step - calculate inverse mod DV directly; // assumes 16 < DB <= 32 and assumes ability to handle 48-bit ints y = (y*(2-x*y%(int)BI_DV))%(int)BI_DV; // y == 1/x mod 2^dbits // we really want the negative inverse, and -DV < y < DV return (y>0)?(int)BI_DV-y:-y; } public abstract class Reducer { abstract public BigInteger convert(BigInteger x); abstract public BigInteger revert(BigInteger x); // DELETEME // abstract public void reduce(BigInteger x); abstract public void sqrTo(BigInteger x, BigInteger r); abstract public void mulTo(BigInteger x, BigInteger y, BigInteger r); }; class MontgomeryReducer: Reducer { BigInteger m; int mp; int mpl; int mph; int um; int mt2; public MontgomeryReducer(BigInteger m) { this.m = m; this.mp = m.invDigit(); this.mpl = this.mp&0x7fff; this.mph = this.mp>>15; this.um = (1<<(BI_DB-15))-1; this.mt2 = 2*m.t; } // xR mod m public override BigInteger convert(BigInteger x) { var r = nbi(); x.abs().dLShiftTo(this.m.t,r); r.divRemTo(this.m,null,r); if(x.s < 0 && r.compareTo(BigInteger.ZERO) > 0) this.m.subTo(r,r); return r; } public override BigInteger revert(BigInteger x) { var r = nbi(); x.copyTo(r); this.reduce(r); return r; } // x = x/R mod m (HAC 14.32) public void reduce(BigInteger x) { var x_array = x.array; while(x.t <= this.mt2) // pad x so am has enough room later x_array[x.t++] = 0; for(var i = 0; i < this.m.t; ++i) { // faster way of calculating u0 = x[i]*mp mod DV var j = x_array[i]&0x7fff; var u0 = (j*this.mpl+(((j*this.mph+(x_array[i]>>15)*this.mpl)&this.um)<<15))&BI_DM; // use am to combine the multiply-shift-add into one call j = i+this.m.t; x_array[j] += am(this.m,0,u0,x,i,0,this.m.t); // propagate carry while(x_array[j] >= BI_DV) { x_array[j] -= BI_DV; x_array[++j]++; } } x.clamp(); x.dRShiftTo(this.m.t,x); if(x.compareTo(this.m) >= 0) x.subTo(this.m,x); } // r = "x^2/R mod m"; x != r public override void sqrTo(BigInteger x, BigInteger r) { x.squareTo(r); this.reduce(r); } // r = "xy/R mod m"; x,y != r public override void mulTo(BigInteger x, BigInteger y, BigInteger r) { x.multiplyTo(y,r); this.reduce(r); } } // (protected) true iff this is even private bool isEven() { var this_array = this.array; return ((this.t>0)?(int)(this_array[0]&1):this.s) == 0; } // (protected) this^e, e < 2^32, doing sqr and mul with "z" (HAC 14.79) private BigInteger exp(uint e, Reducer z) { if(e > 0xffffffff || e < 1) return BigInteger.ONE; var r = nbi(); var r2 = nbi(); var g = z.convert(this); int i = (int)nbits((int)e)-1; g.copyTo(r); while(--i >= 0) { z.sqrTo(r,r2); if((e&(1< 0) z.mulTo(r2,g,r); else { var t = r; r = r2; r2 = t; } } return z.revert(r); } // (public) this^e % m, 0 <= e < 2^32 public BigInteger modPowInt(uint e, BigInteger m) { Reducer z; if(e < 256 || m.isEven()) z = new ClassicReducer(m); else z = new MontgomeryReducer(m); return this.exp(e,z); } // "constants" public static BigInteger ZERO = nbv(0); public static BigInteger ONE = nbv(1); // Copyright (c) 2005 Tom Wu // All Rights Reserved. // See "LICENSE" for details. // Extended JavaScript BN functions, required for RSA private ops. // (public) public BigInteger clone() { var r = nbi(); this.copyTo(r); return r; } // (public) return value as integer public int intValue() { var this_array = this.array; if(this.s < 0) { if(this.t == 1) return (int)this_array[0]-(int)BI_DV; else if(this.t == 0) return -1; } else if(this.t == 1) return (int)this_array[0]; else if(this.t == 0) return 0; // assumes 16 < DB < 32 // return ((this_array[1]&((1<<(32-BI_DB))-1))<>24); } // (public) return value as short (assumes DB>=16) public ushort shortValue() { var this_array = this.array; return (this.t==0)?(ushort)this.s:(ushort)((this_array[0]<<16)>>16); } private static double LN2 = Math.Log(2.0); // (protected) return x s.t. r^x < DV private int chunkSize(int r) { return (int)Math.Floor(LN2*(double)BI_DB/Math.Log(r)); } // (public) 0 if this == 0, 1 if this > 0 public int signum() { var this_array = this.array; if(this.s < 0) return -1; else if(this.t <= 0 || (this.t == 1 && this_array[0] <= 0)) return 0; else return 1; } private static String sdigits = "0123456789abcdefghijklmnopqrstuvwxyz"; private static String IntToString(int i, int radix) { if (radix == 10) { return i.ToString(); } else if (radix == 16) { return i.ToString("X"); } else { bool neg = false; if (i < 0) { neg = true; i = -i; } String res = ""; while (i != 0) { int digit = i % radix; res = sdigits.Substring(digit, 1) + res; i = i / radix; } if (neg) res = "-" + res; return res; } } // (protected) convert to radix string public String toRadix(int b) { // if (b == null) b = 10; if(this.signum() == 0 || b < 2 || b > 36) return "0"; var cs = this.chunkSize(b); var a = (int)Math.Pow((double)b,(double)cs); Console.WriteLine("a = {0}.", a); var d = nbv(a); var y = nbi(); var z = nbi(); var r = ""; Console.WriteLine("d.intValue = {0}.", d.intValue()); this.divRemTo(d,y,z); Console.WriteLine("y.signum = {0}", y.signum()); Console.WriteLine("z.intValue = " + z.intValue()); while(y.signum() > 0) { r = IntToString(a+z.intValue(), (int)b).Substring(1) + r; y.divRemTo(d,y,z); Console.WriteLine("y.signum = {0}", y.signum()); Console.WriteLine("z.intValue = " + z.intValue()); } return IntToString(z.intValue(), (int)b) + r; } private static int IntPow(int n, int p) { int res = 1; for (int k = 1; k < p; k++) { res *= n; } return res; } // (protected) convert from radix string private void fromRadix(String s, int b) { this.fromInt(0); var cs = this.chunkSize(b); var d = IntPow(b,cs); bool mi = false; int j = 0; int w = 0; for(int i = 0; i < s.Length; ++i) { int x = intAt(s,i); if(x < 0) { if(s[(int)i] == '-' && this.signum() == 0) mi = true; continue; } w = b*w+(int)x; if(++j >= cs) { this.dMultiply(d); this.dAddOffset(w,0); j = 0; w = 0; } } if(j > 0) { this.dMultiply(IntPow(b,j)); this.dAddOffset(w,0); } if(mi) BigInteger.ZERO.subTo(this,this); } // (protected) alternate constructor private void fromNumber(int a, int b, SecureRandom c) { if(a < 2) this.fromInt(1); else { this.fromNumber(a,c); if(!this.testBit(a-1)) // force MSB set this.bitwiseTo(BigInteger.ONE.shiftLeft((int)a-1),op_or,this); if(this.isEven()) this.dAddOffset(1,0); // force odd while(!this.isProbablePrime(b)) { this.dAddOffset(2,0); if(this.bitLength() > a) this.subTo(BigInteger.ONE.shiftLeft((int)a-1),this); } } } private void fromNumber(int a, SecureRandom b) { // new BigInteger(int,RNG) byte[] x = new byte[(a>>3)+1]; int t = (int)a&7; b.nextBytes(x); if(t > 0) x[0] &= (byte)((1<<(int)t)-1); else x[0] = 0; this.fromByteArray(x); } // (public) convert to bigendian byte array public byte[] toByteArray() { var this_array = this.array; int i = (int)this.t; var r = new ListX(); r[0] = (byte)this.s; int p = (int)BI_DB-(i*(int)BI_DB)%8; int d; int k = 0; if(i-- > 0) { if(p < BI_DB && (d = this_array[i]>>p) != (this.s&BI_DM)>>p) r[k++] = (byte)(d | ((int)this.s<<(int)(BI_DB-p))); while(i >= 0) { if(p < 8) { d = (this_array[i]&(((int)1<>(p+=BI_DB-8); } else { d = (this_array[i]>>(p-=8))&0xff; if(p <= 0) { p += BI_DB; --i; } } if((d&0x80) != 0) d = (int)((int)d | -256); if(k == 0 && (this.s&0x80) != (d&0x80)) ++k; if(k > 0 || d != this.s) r[k++] = (byte)d; } } return r.ToArray(); } public bool Equals(BigInteger a) { return(this.compareTo(a)==0); } public BigInteger min(BigInteger a) { return(this.compareTo(a)<0)?this:a; } public BigInteger max(BigInteger a) { return(this.compareTo(a)>0)?this:a; } // (protected) r = this op a (bitwise) public delegate int BinOpInt(int x1, int x2); private void bitwiseTo(BigInteger a, BinOpInt op, BigInteger r) { var this_array = this.array; var a_array = a.array; var r_array = r.array; var m = Math.Min(a.t,this.t); for(int i = 0; i < m; ++i) r_array[i] = op(this_array[i],a_array[i]); int f; if(a.t < this.t) { f = (int)a.s&BI_DM; for(int i = m; i < this.t; ++i) r_array[i] = op(this_array[i],f); r.t = this.t; } else { f = (int)this.s&BI_DM; for(int i = m; i < a.t; ++i) r_array[i] = op(f,a_array[i]); r.t = a.t; } r.s = (int)op((int)this.s,(int)a.s); r.clamp(); } // (public) this & a private static int op_and(int x, int y) { return x&y; } public BigInteger and(BigInteger a) { var r = nbi(); this.bitwiseTo(a,op_and,r); return r; } // (public) this | a private static int op_or(int x, int y) { return x|y; } public BigInteger or(BigInteger a) { var r = nbi(); this.bitwiseTo(a,op_or,r); return r; } // (public) this ^ a private static int op_xor(int x, int y) { return x^y; } public BigInteger xor(BigInteger a) { var r = nbi(); this.bitwiseTo(a,op_xor,r); return r; } // (public) this & ~a private static int op_andnot(int x, int y) { return x&~y; } public BigInteger andNot(BigInteger a) { var r = nbi(); this.bitwiseTo(a,op_andnot,r); return r; } // (public) ~this public BigInteger not() { var this_array = this.array; var r = nbi(); var r_array = r.array; for(var i = 0; i < this.t; ++i) r_array[i] = BI_DM&~this_array[i]; r.t = this.t; r.s = ~this.s; return r; } // (public) this << n public BigInteger shiftLeft(int n) { var r = nbi(); if(n < 0) this.rShiftTo(-n,r); else this.lShiftTo(n,r); return r; } // (public) this >> n public BigInteger shiftRight(int n) { var r = nbi(); if(n < 0) this.lShiftTo(-n,r); else this.rShiftTo(n,r); return r; } // return index of lowest 1-bit in x, x < 2^31 (-1 for no set bits) public static int lbit(int x) { if(x == 0) return -1; int r = 0; if((x&0xffff) == 0) { x >>= 16; r += 16; } if((x&0xff) == 0) { x >>= 8; r += 8; } if((x&0xf) == 0) { x >>= 4; r += 4; } if((x&3) == 0) { x >>= 2; r += 2; } if((x&1) == 0) ++r; return r; } // (public) returns index of lowest 1-bit (or -1 if none) public int getLowestSetBit() { var this_array = this.array; for(var i = 0; i < this.t; ++i) if(this_array[i] != 0) return i*BI_DB+lbit(this_array[i]); if(this.s < 0) return (int)this.t*BI_DB; return -1; } // return number of 1 bits in x private static int cbit(int x) { int r = 0; while(x != 0) { x &= x-1; ++r; } return r; } // (public) return number of set bits public int bitCount() { int r = 0; int x = (int)this.s&BI_DM; for(int i = 0; i < this.t; ++i) r += cbit(this.array[i]^x); return r; } // (public) true iff nth bit is set public bool testBit(int n) { var this_array = this.array; int j = n/(int)BI_DB; if(j >= this.t) return(this.s!=0); return((this_array[j]&((int)1<<(int)(n%BI_DB)))!=0); } // (protected) this op (1<>= BI_DB; } if(a.t < this.t) { c += (int)a.s; while(i < this.t) { c += this_array[i]; r_array[i++] = c&BI_DM; c >>= BI_DB; } c += (int)this.s; } else { c += (int)this.s; while(i < a.t) { c += a_array[i]; r_array[i++] = c&BI_DM; c >>= BI_DB; } c += (int)a.s; } r.s = (c<0)?-1:0; if(c > 0) r_array[i++] = c; else if(c < -1) r_array[i++] = BI_DV+c; r.t = i; r.clamp(); } // (public) this + a public BigInteger add(BigInteger a) { var r = nbi(); this.addTo(a,r); return r; } // (public) this - a public BigInteger subtract(BigInteger a) { var r = nbi(); this.subTo(a,r); return r; } // (public) this * a public BigInteger multiply(BigInteger a) { var r = nbi(); this.multiplyTo(a,r); return r; } // (public) this / a public BigInteger divide(BigInteger a) { var r = nbi(); this.divRemTo(a,r,null); return r; } // (public) this % a public BigInteger remainder(BigInteger a) { var r = nbi(); this.divRemTo(a,null,r); return r; } public struct BigIntPair { public BigInteger p1; public BigInteger p2; public BigIntPair(BigInteger p1, BigInteger p2) { this.p1 = p1; this.p2 = p2; } } // (public) [this/a,this%a] public BigIntPair divideAndRemainder(BigInteger a) { var q = nbi(); var r = nbi(); this.divRemTo(a,q,r); return new BigIntPair(q,r); } // (protected) this *= n, this >= 0, 1 < n < DV private void dMultiply(int n) { var this_array = this.array; this_array[this.t] = am(this,0,n-1,this,0,0,this.t); ++this.t; this.clamp(); } // (protected) this += n << w words, this >= 0 private void dAddOffset(int n, int w) { var this_array = this.array; while(this.t <= w) this_array[this.t++] = 0; this_array[w] += n; while(this_array[w] >= BI_DV) { this_array[w] -= BI_DV; if(++w >= this.t) this_array[this.t++] = 0; ++this_array[w]; } } class NullReducer: Reducer { public NullReducer() {} public override BigInteger convert(BigInteger x) { return x; } public override BigInteger revert(BigInteger x) { return x; } public override void mulTo(BigInteger x, BigInteger y, BigInteger r) { x.multiplyTo(y,r); } public override void sqrTo(BigInteger x, BigInteger r) { x.squareTo(r); } } // (public) this^e // public BigInteger pow(BigInteger e) { return this.exp(e,new NullReducer()); } // (protected) r = lower n words of "this * a", a.t <= n // "this" should be the larger one if appropriate. private void multiplyLowerTo(BigInteger a, int n, BigInteger r) { var r_array = r.array; var a_array = a.array; var i = Math.Min(this.t+a.t,n); r.s = 0; // assumes a,this >= 0 r.t = i; while(i > 0) r_array[--i] = 0; for(int j = r.t-this.t; i < j; ++i) r_array[i+this.t] = am(this, 0,a_array[i],r,i,0,this.t); for(int j = Math.Min(a.t,n); i < j; ++i) am(this, 0,a_array[i],r,i,0,n-i); r.clamp(); } // (protected) r = "this * a" without lower n words, n > 0 // "this" should be the larger one if appropriate. public void multiplyUpperTo(BigInteger a, int n, BigInteger r) { var r_array = r.array; var a_array = a.array; --n; int i = r.t = this.t+a.t-n; r.s = 0; // assumes a,this >= 0 while(--i >= 0) r_array[i] = 0; for(i = Math.Max(n-this.t,0); i < a.t; ++i) r_array[this.t+i-n] = am(this, n-i,a_array[i],r,0,0,this.t+i-n); r.clamp(); r.dRShiftTo(1,r); } // Barrett modular reduction public class BarrettReducer: Reducer { BigInteger r2; BigInteger q3; BigInteger mu; BigInteger m; public BarrettReducer(BigInteger m) { // setup Barrett this.r2 = nbi(); this.q3 = nbi(); BigInteger.ONE.dLShiftTo(2*m.t,this.r2); this.mu = this.r2.divide(m); this.m = m; } public override BigInteger convert(BigInteger x) { if(x.s < 0 || x.t > 2*this.m.t) return x.mod(this.m); else if(x.compareTo(this.m) < 0) return x; else { var r = nbi(); x.copyTo(r); this.reduce(r); return r; } } public override BigInteger revert(BigInteger x) { return x; } // x = x mod m (HAC 14.42) public void reduce(BigInteger x) { x.dRShiftTo(this.m.t-1,this.r2); if(x.t > this.m.t+1) { x.t = this.m.t+1; x.clamp(); } this.mu.multiplyUpperTo(this.r2,this.m.t+1,this.q3); this.m.multiplyLowerTo(this.q3,this.m.t+1,this.r2); while(x.compareTo(this.r2) < 0) x.dAddOffset(1,this.m.t+1); x.subTo(this.r2,x); while(x.compareTo(this.m) >= 0) x.subTo(this.m,x); } // r = x^2 mod m; x != r public override void sqrTo(BigInteger x, BigInteger r) { x.squareTo(r); this.reduce(r); } // r = x*y mod m; x,y != r public override void mulTo(BigInteger x, BigInteger y, BigInteger r) { x.multiplyTo(y,r); this.reduce(r); } } // (public) this^e % m (HAC 14.85) public BigInteger modPow(BigInteger e, BigInteger m) { var e_array = e.array; var i = e.bitLength(); int k; BigInteger r = nbv(1); Reducer z; if(i <= 0) return r; else if(i < 18) k = 1; else if(i < 48) k = 3; else if(i < 144) k = 4; else if(i < 768) k = 5; else k = 6; if(i < 8) z = new ClassicReducer(m); else if(m.isEven()) z = new BarrettReducer(m); else z = new MontgomeryReducer(m); // precomputation var g = new ListX(); int n = 3; int k1 = k-1; int km = (1< 1) { var g2 = nbi(); z.sqrTo(g[1],g2); while(n <= km) { g[n] = nbi(); z.mulTo(g2,g[n-2],g[n]); n += 2; } } int j = e.t-1; int w; bool is1 = true; BigInteger r2 = nbi(); BigInteger t; i = nbits(e_array[j])-1; while(j >= 0) { if(i >= k1) w = (e_array[j]>>(i-k1))&km; else { w = (e_array[j]&((1<<(i+1))-1))<<(k1-i); if(j > 0) w |= e_array[j-1]>>(BI_DB+i-k1); } n = k; while((w&1) == 0) { w >>= 1; --n; } if((i -= n) < 0) { i += BI_DB; --j; } if(is1) { // ret == 1, don't bother squaring or multiplying it g[w].copyTo(r); is1 = false; } else { while(n > 1) { z.sqrTo(r,r2); z.sqrTo(r2,r); n -= 2; } if(n > 0) z.sqrTo(r,r2); else { t = r; r = r2; r2 = t; } z.mulTo(r2,g[w],r); } while(j >= 0 && (e_array[j]&(1< 0) { x.rShiftTo(g,x); y.rShiftTo(g,y); } while(x.signum() > 0) { if((i = x.getLowestSetBit()) > 0) x.rShiftTo(i,x); if((i = y.getLowestSetBit()) > 0) y.rShiftTo(i,y); if(x.compareTo(y) >= 0) { x.subTo(y,x); x.rShiftTo(1,x); } else { y.subTo(x,y); y.rShiftTo(1,y); } } if(g > 0) y.lShiftTo(g,y); return y; } // (protected) this % n, n < 2^26 private int modInt(int n) { var this_array = this.array; if(n <= 0) return 0; var d = BI_DV%n; int r = (this.s<0)?n-1:0; if(this.t > 0) if(d == 0) r = this_array[0]%n; else for(var i = this.t-1; i >= 0; --i) r = (d*r+this_array[i])%n; return r; } // (public) 1/this % m (HAC 14.61) public BigInteger modInverse(BigInteger m) { var ac = m.isEven(); if((this.isEven() && ac) || m.signum() == 0) return BigInteger.ZERO; var u = m.clone(); var v = this.clone(); var a = nbv(1); var b = nbv(0); var c = nbv(0); var d = nbv(1); while(u.signum() != 0) { while(u.isEven()) { u.rShiftTo(1,u); if(ac) { if(!a.isEven() || !b.isEven()) { a.addTo(this,a); b.subTo(m,b); } a.rShiftTo(1,a); } else if(!b.isEven()) b.subTo(m,b); b.rShiftTo(1,b); } while(v.isEven()) { v.rShiftTo(1,v); if(ac) { if(!c.isEven() || !d.isEven()) { c.addTo(this,c); d.subTo(m,d); } c.rShiftTo(1,c); } else if(!d.isEven()) d.subTo(m,d); d.rShiftTo(1,d); } if(u.compareTo(v) >= 0) { u.subTo(v,u); if(ac) a.subTo(c,a); b.subTo(d,b); } else { v.subTo(u,v); if(ac) c.subTo(a,c); d.subTo(b,d); } } if(v.compareTo(BigInteger.ONE) != 0) return BigInteger.ZERO; if(d.compareTo(m) >= 0) return d.subtract(m); if(d.signum() < 0) d.addTo(m,d); else return d; if(d.signum() < 0) return d.add(m); else return d; } static int[] lowprimes = new int[]{2,3,5,7,11,13,17,19,23,29,31,37,41,43,47,53,59,61,67,71,73,79,83,89,97,101,103,107,109,113,127,131,137,139,149,151,157,163,167,173,179,181,191,193,197,199,211,223,227,229,233,239,241,251,257,263,269,271,277,281,283,293,307,311,313,317,331,337,347,349,353,359,367,373,379,383,389,397,401,409,419,421,431,433,439,443,449,457,461,463,467,479,487,491,499,503,509}; static int lplim = (1<<26)/lowprimes[lowprimes.Length-1]; // (public) test primality with certainty >= 1-.5^t public bool isProbablePrime(int t) { int i; var x = this.abs(); var x_array = x.array; if(x.t == 1 && x_array[0] <= lowprimes[lowprimes.Length-1]) { for(i = 0; i < lowprimes.Length; ++i) if(x_array[0] == lowprimes[i]) return true; return false; } if(x.isEven()) return false; i = 1; while(i < lowprimes.Length) { var m = lowprimes[i]; var j = i+1; while(j < lowprimes.Length && m < lplim) m *= lowprimes[j++]; m = x.modInt(m); while(i < j) if(m%lowprimes[i++] == 0) return false; } return x.millerRabin(t); } // (protected) true if probably prime (HAC 4.24, Miller-Rabin) private bool millerRabin(int t) { var n1 = this.subtract(BigInteger.ONE); var k = n1.getLowestSetBit(); if(k <= 0) return false; var r = n1.shiftRight(k); t = (t+1)>>1; if(t > lowprimes.Length) t = lowprimes.Length; var a = nbi(); for(var i = 0; i < t; ++i) { a.fromInt(lowprimes[i]); var y = a.modPow(r,this); if(y.compareTo(BigInteger.ONE) != 0 && y.compareTo(n1) != 0) { var j = 1; while(j++ < k && y.compareTo(n1) != 0) { y = y.modPowInt(2,this); if(y.compareTo(BigInteger.ONE) == 0) return false; } if(y.compareTo(n1) != 0) return false; } } return true; } public void PrintArray(String nm) { for (int kk = 0; kk < array.Count; kk++) Console.WriteLine(" {0}.array[{1}] = {2}", nm, kk, array[kk]); } // BigInteger interfaces not implemented in jsbn: // BigInteger(int signum, byte[] magnitude) // double doubleValue() // float floatValue() // int hashCode() // long longValue() // static BigInteger valueOf(long val) // prng4.js - uses Arcfour as a PRNG } abstract class RNG { abstract public void init(int[] key); abstract public int next(); } class Arcfour: RNG { int i; int j; int[] S; public Arcfour() { this.i = 0; this.j = 0; this.S = new int[256]; } // Initialize arcfour context from key, an array of ints, each from [0..255] public override void init(int[] key) { for(int i = 0; i < 256; ++i) this.S[i] = i; int j = 0; for(int i = 0; i < 256; ++i) { j = (j + this.S[i] + key[i % key.Length]) & 255; int t = this.S[i]; this.S[i] = this.S[j]; this.S[j] = t; } this.i = 0; this.j = 0; } public override int next() { this.i = (this.i + 1) & 255; this.j = (this.j + this.S[this.i]) & 255; int t = this.S[this.i]; this.S[this.i] = this.S[this.j]; this.S[this.j] = t; return this.S[(t + this.S[this.i]) & 255]; } } class SecureRandom { // Pool size must be a multiple of 4 and greater than 32. // An array of bytes the size of the pool will be passed to init() const int rng_psize = 256; // Random number generator - requires a PRNG backend, e.g. prng4.js // For best results, put code like // // in your main HTML document. RNG rng_state; int[] rng_pool; int rng_pptr; public SecureRandom() { rng_pool = new int[rng_psize]; rng_pptr = 0; #if USE_RANDOM_SEED Random rnd = new Random(); #endif while(rng_pptr < rng_psize) { // extract some randomness from Math.random() #if USE_RANDOM_SEED int t = (int)Math.Floor(65536.0 * rnd.NextDouble()); #else int t = 1000; #endif rng_pool[rng_pptr++] = (int)((uint)t >> 8); rng_pool[rng_pptr++] = t & 255; } rng_pptr = 0; rng_seed_time(); } // Mix in a 32-bit integer into the pool private void rng_seed_int(int x) { rng_pool[rng_pptr++] ^= x & 255; rng_pool[rng_pptr++] ^= (x >> 8) & 255; rng_pool[rng_pptr++] ^= (x >> 16) & 255; rng_pool[rng_pptr++] ^= (x >> 24) & 255; if(rng_pptr >= rng_psize) rng_pptr -= rng_psize; } // Mix in the current time (w/milliseconds) into the pool private void rng_seed_time() { #if USE_RANDOM_SEED rng_seed_int((int)(new DateTime().Ticks)); #endif } // Plug in your RNG constructor here private RNG prng_newstate() { return new Arcfour(); } private byte rng_get_byte() { if(rng_state == null) { rng_seed_time(); rng_state = prng_newstate(); rng_state.init(rng_pool); for(rng_pptr = 0; rng_pptr < rng_pool.Length; ++rng_pptr) rng_pool[rng_pptr] = 0; rng_pptr = 0; //rng_pool = null; } // TODO: allow reseeding after first request return (byte)rng_state.next(); } public void nextBytes(byte[] ba) { for(int i = 0; i < ba.Length; ++i) ba[i] = rng_get_byte(); } } class RSAKey { BigInteger n; int e; BigInteger d; BigInteger p; BigInteger q; BigInteger dmp1; BigInteger dmq1; BigInteger coeff; // "empty" RSA key constructor public RSAKey() { this.n = null; this.e = 0; this.d = null; this.p = null; this.q = null; this.dmp1 = null; this.dmq1 = null; this.coeff = null; } // convert a (hex) string to a bignum object private static BigInteger parseBigInt(String str, int r) { return new BigInteger(str,r); } private static String linebrk(String s, int n) { var ret = ""; var i = 0; while(i + n < s.Length) { ret += s.Substring(i,i+n) + "\n"; i += n; } return ret + s.Substring(i,s.Length); } private static String byte2Hex(byte b) { if(b < 0x10) return "0" + b.ToString("X"); else return b.ToString("X"); } // PKCS#1 (type 2, random) pad input string s to n bytes, and return a bigint private static BigInteger pkcs1pad2(String s, int n) { if(n < s.Length + 11) { throw new ArgumentException("Message too long for RSA"); } var ba = new byte[n]; var i = s.Length - 1; while(i >= 0 && n > 0) ba[--n] = (byte)s[i--]; ba[--n] = 0; var rng = new SecureRandom(); byte[] x = new byte[1]; while(n > 2) { // random non-zero pad x[0] = 0; while(x[0] == 0) rng.nextBytes(x); ba[--n] = x[0]; } ba[--n] = 2; ba[--n] = 0; // for (int k = 0; k < ba.Length; k++) Console.WriteLine("ba[{0}] = {1}", k, (int)ba[k]); return new BigInteger(ba); } // Set the public key fields N and e from hex strings public void setPublic(String N, String E) { if (N != null && E != null && N.Length > 0 && E.Length > 0) { this.n = parseBigInt(N,16); this.e = Int32.Parse(E,NumberStyles.HexNumber); } else throw new ArgumentException("Invalid RSA public key"); } // Perform raw public operation on "x": return x^e (mod n) private BigInteger doPublic(BigInteger x) { return x.modPowInt((uint)this.e, this.n); } // Return the PKCS#1 RSA encryption of "text" as an even-length hex string public String encrypt(String text) { var m = pkcs1pad2(text,(this.n.bitLength()+7)>>3); #if TRACING m.PrintArray("m"); Console.WriteLine(m.toString(10)); #endif if(m == null) return null; var c = this.doPublic(m); if(c == null) return null; var h = c.toString(16); if((h.Length & 1) == 0) return h; else return "0" + h; } // Return the PKCS#1 RSA encryption of "text" as a Base64-encoded string //function RSAEncryptB64(text) { // var h = this.encrypt(text); // if(h) return hex2b64(h); else return null; //} // Undo PKCS#1 (type 2, random) padding and, if valid, return the plaintext private String pkcs1unpad2(BigInteger d, int n) { var b = d.toByteArray(); var i = 0; while(i < b.Length && b[i] == 0) ++i; if(b.Length-i != n-1 || b[i] != 2) return null; ++i; while(b[i] != 0) if(++i >= b.Length) return null; var ret = ""; char[] oneChar = new char[1]; while(++i < b.Length) { oneChar[0] = (char)b[i]; ret += new String(oneChar); } return ret; } // Set the private key fields N, e, and d from hex strings private void setPrivate(String N, String E, String D) { if(N != null && E != null && N.Length > 0 && E.Length > 0) { this.n = parseBigInt(N,16); this.e = Int32.Parse(E,NumberStyles.HexNumber); this.d = parseBigInt(D,16); } else throw new ArgumentException("Invalid RSA private key"); } // Set the private key fields N, e, d and CRT params from hex strings public void setPrivateEx(String N, String E, String D, String P, String Q, String DP, String DQ, String C) { if(N != null && E != null && N.Length > 0 && E.Length > 0) { this.n = parseBigInt(N,16); this.e = Int32.Parse(E,NumberStyles.HexNumber); this.d = parseBigInt(D,16); this.p = parseBigInt(P,16); this.q = parseBigInt(Q,16); this.dmp1 = parseBigInt(DP,16); this.dmq1 = parseBigInt(DQ,16); this.coeff = parseBigInt(C,16); } else throw new ArgumentException("Invalid RSA private key"); } // Generate a new random private key B bits long, using public expt E private void generate(int B, String E) { var rng = new SecureRandom(); var qs = B>>1; this.e = Int32.Parse(E,NumberStyles.HexNumber); var ee = new BigInteger(E,16); for(;;) { for(;;) { this.p = new BigInteger(B-qs,1,rng); if(this.p.subtract(BigInteger.ONE).gcd(ee).compareTo(BigInteger.ONE) == 0 && this.p.isProbablePrime(10)) break; } for(;;) { this.q = new BigInteger(qs,1,rng); if(this.q.subtract(BigInteger.ONE).gcd(ee).compareTo(BigInteger.ONE) == 0 && this.q.isProbablePrime(10)) break; } if(this.p.compareTo(this.q) <= 0) { var t = this.p; this.p = this.q; this.q = t; } var p1 = this.p.subtract(BigInteger.ONE); var q1 = this.q.subtract(BigInteger.ONE); var phi = p1.multiply(q1); if(phi.gcd(ee).compareTo(BigInteger.ONE) == 0) { this.n = this.p.multiply(this.q); this.d = ee.modInverse(phi); this.dmp1 = this.d.mod(p1); this.dmq1 = this.d.mod(q1); this.coeff = this.q.modInverse(this.p); break; } } } // Perform raw private operation on "x": return x^d (mod n) private BigInteger doPrivate(BigInteger x) { if(this.p == null || this.q == null) return x.modPow(this.d, this.n); // TODO: re-calculate any missing CRT params var xp = x.mod(this.p).modPow(this.dmp1, this.p); var xq = x.mod(this.q).modPow(this.dmq1, this.q); while(xp.compareTo(xq) < 0) xp = xp.add(this.p); xp = xp.subtract(xq); xp = xp.multiply(this.coeff); xp = xp.mod(this.p); xp = xp.multiply(this.q); xp = xp.add(xq); return xp; } // Return the PKCS#1 RSA decryption of "ctext". // "ctext" is an even-length hex string and the output is a plain string. public String decrypt(String ctext) { var c = parseBigInt(ctext, 16); var m = this.doPrivate(c); if(m == null) return null; return pkcs1unpad2(m, (this.n.bitLength()+7)>>3); } } } ================================================ FILE: Zelig/Zelig/RunTime/DeviceModels/QuickTest/Program.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // namespace QuickTest { using System; using RT = Microsoft.Zelig.Runtime; using System.Runtime.InteropServices; using System.Threading; class Program { static void ThreadFunc() { for(int i=0; i<3; i++) { Console.WriteLine( "Testing..." ); Thread.Sleep( 2000 ); } } static void SetAccess( FileAccess access ) { if(access != s_access) { s_access = access; } } static void TestBools( out bool canRead, out bool canWrite ) { if(s_access == FileAccess.Write) { canRead = true; canWrite = false; } else { canRead = false; canWrite = true; } } static FileAccess s_access = FileAccess.ReadWrite; [Serializable, Flags] public enum FileAccess { // Specifies read access to the file. Data can be read from the file and // the file pointer can be moved. Combine with WRITE for read-write access. Read = 1, // Specifies write access to the file. Data can be written to the file and // the file pointer can be moved. Combine with READ for read-write access. Write = 2, // Specifies read and write access to the file. Data can be written to the // file and the file pointer can be moved. Data can also be read from the // file. ReadWrite = 3, } static void test1() { bool _canRead, _canWrite; // Get wantsRead and wantsWrite from access, note that they cannot both be false bool wantsRead = ( s_access & FileAccess.Read ) == FileAccess.Read; bool wantsWrite = ( s_access & FileAccess.Write ) == FileAccess.Write; TestBools( out _canRead, out _canWrite ); // Make sure the requests (wantsRead / wantsWrite) matches the filesystem capabilities (canRead / canWrite) // ZeligBUG - the second check fails if wantsWrite = true and _canWrite = false if(( wantsRead && !_canRead ) || ( wantsWrite && !_canWrite )) { Console.WriteLine( "PASS" ); } else { Console.WriteLine( "FAIL" ); } } static void Main() { //Thread th = new Thread( new ThreadStart( ThreadFunc ) ); //th.Start(); //GC.Collect(); //th.Join(); SetAccess( FileAccess.Write ); test1(); Console.WriteLine( "Finished" ); } } } ================================================ FILE: Zelig/Zelig/RunTime/DeviceModels/QuickTest/Properties/AssemblyInfo.cs ================================================ using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; // General Information about an assembly is controlled through the following // set of attributes. Change these attribute values to modify the information // associated with an assembly. [assembly: AssemblyTitle( "QuickTest" )] [assembly: AssemblyDescription( "" )] [assembly: AssemblyConfiguration( "" )] [assembly: AssemblyCompany( "Microsoft" )] [assembly: AssemblyProduct( "QuickTest" )] [assembly: AssemblyCopyright( "Copyright © Microsoft 2012" )] [assembly: AssemblyTrademark( "" )] [assembly: AssemblyCulture( "" )] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible( false )] // The following GUID is for the ID of the typelib if this project is exposed to COM [assembly: Guid( "387dda81-a5e0-4fc9-ab89-c7ffb8037c4f" )] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Build and Revision Numbers // by using the '*' as shown below: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion( "1.0.0.0" )] [assembly: AssemblyFileVersion( "1.0.0.0" )] ================================================ FILE: Zelig/Zelig/RunTime/DeviceModels/QuickTest/QuickTest.csproj ================================================  Debug x86 9.0.21022 2.0 {FA6F295F-6DEB-4095-86F2-DEC2D2D9A038} Exe Properties QuickTest QuickTest v4.5 512 true $(LlilumBuildRoot)\Target\bin\$(Configuration)\ DEBUG;TRACE true true full AnyCPU prompt MinimumRecommendedRules.ruleset $(LlilumBuildRoot)\Target\bin\$(Configuration)\ TRACE true true pdbonly AnyCPU prompt MinimumRecommendedRules.ruleset true $(LlilumBuildRoot)\Target\bin\$(Configuration)\ DEBUG;TRACE true true true full AnyCPU MinimumRecommendedRules.ruleset {186F31A3-EF89-4A25-B2D5-20060501AA01} mscorlib False {186F31A3-EF89-4A25-B2D5-20070702AA01} system False {186F31A3-EF89-4A25-B2D5-20061218AA01} Common False {186F31A3-EF89-4A25-B2D5-20060509AA01} Kernel False {186F31A3-EF89-4A25-B2D5-20060720AA01} TypeSystem False ================================================ FILE: Zelig/Zelig/RunTime/DeviceModels/TestMethodGen/Program.cs ================================================ using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.IO; using System.Text.RegularExpressions; namespace TestMethodGen { class Program { enum ReplaceType { test, exception, } static void Main( string[] args ) { if(args.Length < 2) { Usage(); return; } try { ReplaceType type; if(Enum.TryParse(args[0].ToLower(), out type)) { string dir = args[1]; if(File.Exists( dir )) { switch(type) { case ReplaceType.test: ParseTestFile( dir ); break; case ReplaceType.exception: ParseExceptionFile( dir ); break; } } else { ParseDirectory( type, dir ); } } else { Console.WriteLine( "Error: Invalid type"); Usage(); } } catch(Exception e) { Console.WriteLine( e.Message ); Usage(); } } static void ParseDirectory( ReplaceType type, string dir ) { foreach(string file in Directory.GetFiles( dir, "*.cs" )) { switch(type) { case ReplaceType.test: ParseTestFile( file ); break; case ReplaceType.exception: ParseExceptionFile( file ); break; } } foreach(string subdir in Directory.GetDirectories( dir )) { if(subdir != "." && subdir != "..") { ParseDirectory( type, subdir ); } } } static void ParseExceptionFile( string file ) { string fileTmp = Path.Combine( Path.GetDirectoryName( file ), Path.GetFileNameWithoutExtension( file ) ); string ext = Path.GetExtension( file ); int i = 0; Regex exp = new Regex( @"\bthrow\s+new\s+(\w*Exception)\s*\((.*)\)" ); Regex expIfDef = new Regex( "#if EXCEPTION_STRINGS" ); Regex expEndif = new Regex( "#endif" ); Regex expTabs = new Regex( @"\A(\s+)" ); Regex expComment = new Regex( @"\A\s*\/\/" ); Regex expIf = new Regex( @"\A\s*if\s*\(" ); List tests = new List(); bool exceptionFound = false; bool exceptInitFoundState = false; while(File.Exists( fileTmp + i.ToString( "X" ) + ext )) { i++; } fileTmp += i.ToString( "X" ) + ext; using(TextWriter tw = File.CreateText( fileTmp )) using(TextReader tr = File.OpenText( file )) { while(tr.Peek() != -1) { string line = tr.ReadLine(); if(exceptInitFoundState) { if(expEndif.IsMatch( line )) { exceptInitFoundState = false; } tw.WriteLine( line ); } else if(expIfDef.IsMatch( line )) { exceptInitFoundState = true; tw.WriteLine( line ); } else if(!expComment.IsMatch( line )) { Match m = exp.Match( line ); if(m.Success && m.Groups[2].Value.Trim().Length > 0) { exceptionFound = true; string exception = m.Groups[1].Value; string tab = ""; string indent = ""; string epilog = null; // find indent Match mTab = expTabs.Match( line ); if(mTab.Success) { tab = mTab.Groups[1].Value; } if(mTab.Index + mTab.Length != m.Index) { tw.WriteLine( line.Substring( 0, m.Index ) ); if(expIf.IsMatch( line )) { indent = " "; } line = tab + indent + line.Substring( m.Index ); } tw.WriteLine( "#if EXCEPTION_STRINGS" ); int idxSemi = line.IndexOf( ';' ); if(idxSemi == -1) { tw.WriteLine( line ); do { line = tr.ReadLine(); tw.WriteLine( line ); } while(line.IndexOf( ';' ) == -1); } else { epilog = line.Substring( idxSemi + 1 ).Trim(); tw.WriteLine( line.Substring(0, idxSemi + 1) ); } tw.WriteLine( "#else" ); if(exception == "ObjectDisposedException") { tw.WriteLine( tab + indent + "throw new " + exception + "( null );" ); } else { tw.WriteLine( tab + indent + "throw new " + exception + "();" ); } tw.WriteLine( "#endif" ); if(!string.IsNullOrEmpty( epilog )) { tw.WriteLine( tab + epilog ); } } else { tw.WriteLine( line ); } } else { tw.WriteLine( line ); } } } if(exceptionFound) { Console.WriteLine("Modified file: " + file); File.Copy( fileTmp, file, true ); } File.Delete( fileTmp ); } static void ParseTestFile( string file ) { string fileTmp = Path.Combine(Path.GetDirectoryName(file), Path.GetFileNameWithoutExtension(file)); string ext = Path.GetExtension(file); int i=0; Regex exp = new Regex( @"\s*public\s+MFTestResults\s+([\w+\d+_]+)\(\)" ); Regex expOpenBrace = new Regex( "{" ); Regex expCloseBrace = new Regex( "}" ); Regex expAlreadyParsed = new Regex( @"\s*public\s+MFTestMethod\[\]\s+Tests" ); Regex expTestStart = new Regex( @"\s*return\s+new\s+MFTestMethod\[\]" ); List tests = new List(); int braceCnt = 0; bool testsFound = false; int testInitFoundState = 0; int testInitBraceCount = 0; int max = 0; while(File.Exists(fileTmp + i.ToString("X") + ext)) { i++; } fileTmp += i.ToString("X") + ext; using(TextWriter tw = File.CreateText( fileTmp )) using(TextReader tr = File.OpenText( file )) { while(tr.Peek() != -1) { string line = tr.ReadLine(); if(testInitFoundState > 0) { if(testInitFoundState == 1) { if(expTestStart.IsMatch( line )) { testInitFoundState++; } else if(expOpenBrace.IsMatch( line )) { testInitBraceCount++; } continue; } else { string test = line.Trim().TrimEnd( ',' ); if(expCloseBrace.IsMatch( test )) { testInitBraceCount--; } else if(expOpenBrace.IsMatch( test )) { testInitBraceCount++; } else if(!string.IsNullOrEmpty( test )) { Regex expMFTest = new Regex( @"\s*new\s+MFTestMethod\s*\(\s*([\w+\d+_]+)," ); Match m2 = expMFTest.Match( test ); if(m2.Success) { test = m2.Groups[1].Value; } if(!tests.Contains( test )) { tests.Add( test ); } } if(testInitBraceCount <= 0) { testInitFoundState = 0; } } // make sure we don't re-write old tests continue; } else if(expAlreadyParsed.IsMatch( line )) { testInitFoundState = 1; continue; } MatchCollection ms = expOpenBrace.Matches( line ); braceCnt += ms.Count; if(max < braceCnt) max = braceCnt; ms = expCloseBrace.Matches( line ); braceCnt -= ms.Count; Match m = exp.Match( line ); if(m.Success) { string test = m.Groups[1].Value; if(m.Groups.Count > 1 && !tests.Contains(test)) { tests.Add( test ); } } if(braceCnt == 1 && max > 1 && tests.Count > 0) { tw.Write( @" public MFTestMethod[] Tests { get { return new MFTestMethod[] { " ); foreach(string tst in tests) { tw.WriteLine( " new MFTestMethod( " + tst + ", " + "\"" + tst + "\" )," ); } testsFound = true; tests.Clear(); max = 0; tw.Write( @" }; } } " ); } tw.WriteLine( line ); } } if(testsFound) { File.Copy( fileTmp, file, true ); } File.Delete( fileTmp ); } static void Usage() { Console.WriteLine( "Usage: TestMethodGen [test|exceptions] " ); } } } ================================================ FILE: Zelig/Zelig/RunTime/DeviceModels/TestMethodGen/Properties/AssemblyInfo.cs ================================================ using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; // General Information about an assembly is controlled through the following // set of attributes. Change these attribute values to modify the information // associated with an assembly. [assembly: AssemblyTitle( "TestMethodGen" )] [assembly: AssemblyDescription( "" )] [assembly: AssemblyConfiguration( "" )] [assembly: AssemblyCompany( "Microsoft" )] [assembly: AssemblyProduct( "TestMethodGen" )] [assembly: AssemblyCopyright( "Copyright © Microsoft 2011" )] [assembly: AssemblyTrademark( "" )] [assembly: AssemblyCulture( "" )] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible( false )] // The following GUID is for the ID of the typelib if this project is exposed to COM [assembly: Guid( "aeb5feef-6c4d-434b-ade5-58e1e36f63d3" )] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Build and Revision Numbers // by using the '*' as shown below: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion( "1.0.0.0" )] [assembly: AssemblyFileVersion( "1.0.0.0" )] ================================================ FILE: Zelig/Zelig/RunTime/DeviceModels/TestMethodGen/TestMethodGen.csproj ================================================  Debug x86 8.0.30703 2.0 {B7606EF5-A5EC-4A97-AB4A-35D00EFA2925} Exe Properties TestMethodGen TestMethodGen v4.5 512 true $(LlilumBuildRoot)\Target\bin\$(Configuration)\ DEBUG;TRACE full AnyCPU prompt MinimumRecommendedRules.ruleset $(LlilumBuildRoot)\Target\bin\$(Configuration)\ TRACE true pdbonly AnyCPU prompt MinimumRecommendedRules.ruleset $(LlilumBuildRoot)\Target\bin\$(Configuration)\ AnyCPU MinimumRecommendedRules.ruleset ================================================ FILE: Zelig/Zelig/RunTime/DeviceModels/VoxSoloFormFactor/HardwareModel/Device.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // namespace Microsoft.VoxSoloFormFactor { using System; using System.Runtime.CompilerServices; using RT = Microsoft.Zelig.Runtime; using ChipsetModel = Microsoft.DeviceModels.Chipset.MM9691LP; public sealed class Device : RT.Device { public override void PreInitializeProcessorAndMemory() { // // Enter System mode, with interrupts disabled. // Processor.SetStatusRegister( Processor.c_psr_field_c, Processor.c_psr_I | Processor.c_psr_F | Processor.c_psr_mode_SYS ); Processor.SetRegister( Processor.Context.RegistersOnStack.StackRegister, this.BootstrapStackPointer ); // // Disable cache and remove remap of FLASH onto RAM. // { ChipsetModel.REMAP_PAUSE remap = ChipsetModel.REMAP_PAUSE.Instance; remap.Cache_Enable = 0; remap.ClearResetMap = 0; } // // Configure external FLASH chip with proper wait states. // { ChipsetModel.EBIU.DEVICE flashChip; var ctrl = new ChipsetModel.EBIU.DEVICE.ControlBitField(); ctrl.WS = 2; ctrl.RCNT = 0; ctrl.SZ = ChipsetModel.EBIU.DEVICE.Size.SZ16; // // Low 8mega. // flashChip = ChipsetModel.EBIU.Instance.Device0; flashChip.LowAddress = 0x10000000; flashChip.HighAddress = 0x10000000 + 8 * 1024 * 1024; flashChip.Control = ctrl; // // High 8mega. // flashChip = ChipsetModel.EBIU.Instance.Device1; flashChip.LowAddress = 0x10000000 + 8 * 1024 * 1024; flashChip.HighAddress = 0x10000000 + 16 * 1024 * 1024; flashChip.Control = ctrl; } { ChipsetModel.CMU cmu = ChipsetModel.CMU.Instance; // // We should wait 80usec for the switching regulator to warm up. // Processor.Delay( 80 * 32 / 12 ); // At reset, the clock prescaler is set to 12. cmu.CLK_SEL = ChipsetModel.CMU.CLK_SEL__EXTSLOW | ChipsetModel.CMU.CLK_SEL__NOPCU; // ChipsetModel.CMU.CLK_SEL__CKOUTEN cmu.PERF_LVL = (uint)ChipsetModel.CMU.PERF_LEVEL.CLK_SEL__DIV_FAST; // // Enable GPIO clock. // cmu.EnableClock( ChipsetModel.CMU.MCLK_EN__GPIO ); } } public override void MoveCodeToProperLocation() { Memory.Instance.ExecuteImageRelocation(); } } } ================================================ FILE: Zelig/Zelig/RunTime/DeviceModels/VoxSoloFormFactor/HardwareModel/Drivers/InterruptController.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // namespace Microsoft.VoxSoloFormFactor.Drivers { using System; using System.Runtime.CompilerServices; using RT = Microsoft.Zelig.Runtime; using ChipsetModel = Microsoft.DeviceModels.Chipset.MM9691LP; public sealed class InterruptController : ChipsetModel.Drivers.InterruptController { } } ================================================ FILE: Zelig/Zelig/RunTime/DeviceModels/VoxSoloFormFactor/HardwareModel/Drivers/RealTimeClock.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // namespace Microsoft.VoxSoloFormFactor.Drivers { using System; using System.Runtime.CompilerServices; using RT = Microsoft.Zelig.Runtime; using ChipsetModel = Microsoft.DeviceModels.Chipset.MM9691LP; public sealed class RealTimeClock : ChipsetModel.Drivers.RealTimeClock { } } ================================================ FILE: Zelig/Zelig/RunTime/DeviceModels/VoxSoloFormFactor/HardwareModel/Memory.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // namespace Microsoft.VoxSoloFormFactor { using System; using RT = Microsoft.Zelig.Runtime; using TS = Microsoft.Zelig.Runtime.TypeSystem; public sealed class Memory : RT.Memory { public override void InitializeMemory() { } } } ================================================ FILE: Zelig/Zelig/RunTime/DeviceModels/VoxSoloFormFactor/HardwareModel/Peripherals.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // //#define ALLOW_PAUSE //#define DCCQUEUE_PROFILE namespace Microsoft.VoxSoloFormFactor { using System; using System.Runtime.CompilerServices; using RT = Microsoft.Zelig.Runtime; using TS = Microsoft.Zelig.Runtime.TypeSystem; using ChipsetModel = Microsoft.DeviceModels.Chipset.MM9691LP; public sealed unsafe class Peripherals : RT.Peripherals { class DccQueue { const int c_size = 8192; // // State // private readonly uint[] m_array; private int m_count; private int m_writerPos; private int m_readerPos; // // Constructor Methods // internal DccQueue() { m_array = new uint[c_size]; m_count = 0; m_writerPos = 0; m_readerPos = 0; } // // Helper Methods // internal bool Enqueue( uint val ) { if(this.IsFull) { return false; } int pos = m_writerPos; m_array[pos] = val; m_writerPos = NextPosition( pos ); m_count++; return true; } internal bool Dequeue( out uint val ) { if(this.IsEmpty) { val = 0; return false; } int pos = m_readerPos; val = m_array[pos]; m_readerPos = NextPosition( pos ); m_count--; return true; } //--// [RT.Inline] private int NextPosition( int val ) { val = val + 1; if(val == c_size) { return 0; } return val; } [RT.Inline] private int PreviousPosition( int val ) { if(val == 0) { val = c_size; } return val - 1; } // // Access Methods // internal bool IsEmpty { [RT.Inline] get { return m_count == 0; } } internal bool IsFull { [RT.Inline] get { return m_count == c_size; } } } // // State // private uint* m_performanceCounter; private DccQueue m_txQueue; private DccQueue m_rxQueue; #if DCCQUEUE_PROFILE private int m_txCount; private int m_txPump; private int m_rxCount; private int m_rxPump; #endif // // Helper Methods // public override void Initialize() { AllocatePerformanceCounter(); //// { //// // enable the arm timer clock //// ChipsetModel.CMU.Instance.EnableClock( ChipsetModel.CMU.MCLK_EN__ARMTIM ); //// //// var ctrl = new ChipsetModel.ARMTIMERx.ControlBitField(); //// //// ctrl.Prescale = ChipsetModel.ARMTIMERx.Prescale.Div1; //// ctrl.Periodic = false; //// ctrl.Enable = true; //// //// var timer = ChipsetModel.ARMTIMER0.Instance; //// //// timer.Control = ctrl; //// timer.Clear = 0; //// } } public override void Activate() { m_txQueue = new DccQueue(); m_rxQueue = new DccQueue(); Drivers.InterruptController.Instance.Initialize(); Drivers.RealTimeClock.Instance.Initialize(); } public override void EnableInterrupt( uint index ) { } public override void DisableInterrupt( uint index ) { } public override void CauseInterrupt() { Drivers.InterruptController.Instance.CauseInterrupt(); } public override void ContinueUnderNormalInterrupt( Continuation dlg ) { Drivers.InterruptController.Instance.ContinueUnderNormalInterrupt( dlg ); } public override void WaitForInterrupt() { // // Using the Pause register to save power seems to be broken at the hardware level: device locks up!!!!! // #if ALLOW_PAUSE ChipsetModel.REMAP_PAUSE.Instance.Pause_AHB = 0; #else ChipsetModel.INTC intc = ChipsetModel.INTC.Instance; while(intc.Irq.Status == 0) { PumpTxDCC(); PumpRxDCC(); } #endif } public override void ProcessInterrupt() { using(RT.SmartHandles.SwapCurrentThreadUnderInterrupt hnd = ThreadManager.InstallInterruptThread()) { Drivers.InterruptController.Instance.ProcessInterrupt(); } } [RT.MemoryRequirements( RT.MemoryAttributes.RAM )] public override void ProcessFastInterrupt() { using(RT.SmartHandles.SwapCurrentThreadUnderInterrupt hnd = ThreadManager.InstallFastInterruptThread()) { Drivers.InterruptController.Instance.ProcessFastInterrupt(); } } public override ulong GetPerformanceCounterFrequency() { return RT.Configuration.CoreClockFrequency; } [RT.Inline] [RT.DisableNullChecks()] public override unsafe uint ReadPerformanceCounter() { return *m_performanceCounter; } //--// public void PostDCC( uint value ) { #if DCCQUEUE_PROFILE m_txCount++; #endif if(m_txQueue == null) { #if DCCQUEUE_PROFILE m_txPump++; #endif RT.TargetPlatform.ARMv4.Coprocessor14.WriteDCC( value ); } else { while(true) { bool fSent; using(RT.SmartHandles.InterruptState.Disable()) { fSent = m_txQueue.Enqueue( value ); } if(fSent) { return; } lock(m_txQueue) { #if DCCQUEUE_PROFILE m_txPump++; #endif PumpTxDCC(); } } } } public uint ReceiveDCC() { #if DCCQUEUE_PROFILE m_rxCount++; #endif if(m_rxQueue == null) { #if DCCQUEUE_PROFILE m_rxPump++; #endif return RT.TargetPlatform.ARMv4.Coprocessor14.ReadDCC(); } else { while(true) { bool fGot; uint val; using(RT.SmartHandles.InterruptState.Disable()) { fGot = m_rxQueue.Dequeue( out val ); } if(fGot) { return val; } lock(m_rxQueue) { #if DCCQUEUE_PROFILE m_rxPump++; #endif PumpRxDCC(); } if(m_rxQueue.IsEmpty == false) { System.Threading.Thread.Sleep( 1 ); } } } } private void PumpTxDCC() { if(m_txQueue.IsEmpty == false && RT.TargetPlatform.ARMv4.Coprocessor14.CanWriteDCC()) { using(RT.SmartHandles.InterruptState.Disable()) { if(m_txQueue.IsEmpty == false && RT.TargetPlatform.ARMv4.Coprocessor14.CanWriteDCC()) { uint val; if(m_txQueue.Dequeue( out val )) { RT.TargetPlatform.ARMv4.Coprocessor14.WriteDebugCommData( val ); } } } } } private void PumpRxDCC() { if(RT.TargetPlatform.ARMv4.Coprocessor14.CanReadDCC() && m_rxQueue.IsFull == false) { using(RT.SmartHandles.InterruptState.Disable()) { if(RT.TargetPlatform.ARMv4.Coprocessor14.CanReadDCC() && m_rxQueue.IsFull == false) { m_rxQueue.Enqueue( RT.TargetPlatform.ARMv4.Coprocessor14.ReadDebugCommData() ); } } } } //--// private unsafe void AllocatePerformanceCounter() { const uint VTU_Channel = 0; const uint CP = (VTU_Channel / 2) >> 1; // Channel Pair, Channel pair Half, AorB portion of VTU32 (for IO Control) const uint CH = (VTU_Channel / 2) & 1; // Channel Pair, Channel pair Half, AorB portion of VTU32 (for IO Control) //--// ChipsetModel.CMU cmu = ChipsetModel.CMU.Instance; // // Enable VTU clock. // cmu.EnableClock( ChipsetModel.CMU.MCLK_EN__VTU32 ); //--// ChipsetModel.VTU32 vtu = ChipsetModel.VTU32.Instance; // get mode set before any other writes to time subsystem { uint MC = (vtu.ModeControl & 0xFFFF); MC &= ~ChipsetModel.VTU32.ModeControl__get( VTU_Channel / 2, 0x000F ); MC |= ChipsetModel.VTU32.ModeControl__set( VTU_Channel / 2, ChipsetModel.VTU32.ModeControl__TMODx_PWM32 ); vtu.ModeControl = MC; } // reset 32-bit counter to zero before starting it vtu.ChannelPair[CP].Channel[CH].Counter = 0; // turn off just our external clock select { uint extClk = vtu.ExternalClockSelectRegister; extClk &= (ChipsetModel.VTU32.ExternalClockSelectRegister__CK1 << (int)(VTU_Channel / 2)) & 0x0000000F; vtu.ExternalClockSelectRegister = extClk; } if(vtu.ChannelPair[CP].ClockPrescalar__get( CH ) != 0) { // setup current prescalar, assume in 32-bit mode, we can run full tilt with 32-bits vtu.ChannelPair[CP].ClockPrescalar__set( CH, 0 ); } // get control word, remove this PWM32's settings (both A and B) { uint IOC = (vtu.IOControl[CP].Value & 0xFFFF); IOC &= ~ChipsetModel.VTU32.IO_CONTROL.Set( CH, 0, 0x000F ); IOC |= ChipsetModel.VTU32.IO_CONTROL.Set( CH, 1, 0x000F ); vtu.IOControl[CP].Value = IOC; } // write in Period, then duty order // true period is one more than programmed value vtu.ChannelPair[CP].Channel[CH].PeriodCapture = uint.MaxValue; vtu.ChannelPair[CP].Channel[CH].DutyCycleCapture = uint.MaxValue / 2; // square wave, as if it matters here // add GO bit to start PWM counters (always TxARUN for 32-bite mode) { uint MC = (vtu.ModeControl & 0xFFFF); MC &= ~ChipsetModel.VTU32.ModeControl__get( VTU_Channel / 2, 0x000F ); MC |= ChipsetModel.VTU32.ModeControl__set( VTU_Channel / 2, ChipsetModel.VTU32.ModeControl__TMODx_PWM32 | ChipsetModel.VTU32.ModeControl__TxARUN ); vtu.ModeControl = MC; } fixed(uint* ptr = &vtu.ChannelPair[CP].Channel[CH].Counter) { m_performanceCounter = ptr; } } } } ================================================ FILE: Zelig/Zelig/RunTime/DeviceModels/VoxSoloFormFactor/HardwareModel/Processor.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // namespace Microsoft.VoxSoloFormFactor { using System; using RT = Microsoft.Zelig.Runtime; using TS = Microsoft.Zelig.Runtime.TypeSystem; using ChipsetModel = Microsoft.DeviceModels.Chipset.MM9691LP; public sealed class Processor : ChipsetModel.Processor { // // Helper Methods // [RT.BottomOfCallStack()] [RT.HardwareExceptionHandler(RT.HardwareException.Interrupt)] private static void InterruptHandler( ref Context.RegistersOnStack registers ) { Context.InterruptHandlerWithContextSwitch( ref registers ); } [RT.BottomOfCallStack()] [RT.HardwareExceptionHandler(RT.HardwareException.FastInterrupt)] [RT.MemoryRequirements( RT.MemoryAttributes.RAM )] private static void FastInterruptHandler() { Context.FastInterruptHandlerWithoutContextSwitch(); } [RT.BottomOfCallStack()] [RT.HardwareExceptionHandler(RT.HardwareException.SoftwareInterrupt)] private static void SoftwareInterruptHandler( ref Context.RegistersOnStack registers ) { Context.GenericSoftwareInterruptHandler( ref registers ); } //--// static Context.RegistersOnStack fault; [RT.NoInline] [RT.NoReturn()] [RT.HardwareExceptionHandler(RT.HardwareException.UndefinedInstruction)] [RT.MemoryUsage(RT.MemoryUsage.Bootstrap)] static void UndefinedInstruction( ref Context.RegistersOnStack registers ) { fault.Assign( ref registers ); while(true) { } } [RT.NoInline] [RT.NoReturn()] [RT.HardwareExceptionHandler(RT.HardwareException.PrefetchAbort)] [RT.MemoryUsage(RT.MemoryUsage.Bootstrap)] static void PrefetchAbort( ref Context.RegistersOnStack registers ) { fault.Assign( ref registers ); while(true) { } } [RT.NoInline] [RT.NoReturn()] [RT.HardwareExceptionHandler(RT.HardwareException.DataAbort)] [RT.MemoryUsage(RT.MemoryUsage.Bootstrap)] static void DataAbort( ref Context.RegistersOnStack registers ) { fault.Assign( ref registers ); while(true) { } } } } ================================================ FILE: Zelig/Zelig/RunTime/DeviceModels/VoxSoloFormFactor/HardwareModel/Storage.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // namespace Microsoft.VoxSoloFormFactor { using System; using RT = Microsoft.Zelig.Runtime; using TS = Microsoft.Zelig.Runtime.TypeSystem; public sealed class Storage : RT.Storage { const uint FlashBase = 0x10000000; const uint FlashSize = 16 * 1024 * 1024; const uint FlashMask = ~(FlashSize - 1); const ushort ErasedValue = (ushort)0xFFFFu; const uint ErasedValuePair = 0xFFFFFFFFu; const ushort DQ5 = (ushort)(1u << 5); class EraseSection { // // State // internal uint m_baseAddress; internal uint m_endAddress; internal uint m_numEraseBlocks; internal uint m_sizeEraseBlocks; // // Helper Methods // [RT.MemoryRequirements( RT.MemoryAttributes.RAM )] // Used during firmware update. internal unsafe bool FindBlock( UIntPtr address , out ushort* blockStart , out ushort* blockEnd ) { if(m_baseAddress <= address.ToUInt32() && address.ToUInt32() < m_endAddress) { for(uint i = 0; i < m_numEraseBlocks; i++) { uint block = m_baseAddress + m_sizeEraseBlocks * i; uint blockNext = block + m_sizeEraseBlocks; if(block <= address.ToUInt32() && address.ToUInt32() < blockNext) { blockStart = (ushort*)block; blockEnd = (ushort*)blockNext; return true; } } } blockStart = null; blockEnd = null; return false; } } // // State // EraseSection[] m_eraseSections; // // Helper Methods // public override unsafe void InitializeStorage() { ushort[] cfg = new ushort[128]; ushort* flashBaseAddress = GetChipBaseAddress(); ReadCFI( flashBaseAddress, cfg ); if(cfg[0x10] == 'Q' && cfg[0x11] == 'R' && cfg[0x12] == 'Y' ) { uint numEraseBlockRegions = cfg[0x2C]; uint baseAddress = (uint)flashBaseAddress; m_eraseSections = new EraseSection[numEraseBlockRegions]; for(uint pos = 0; pos < numEraseBlockRegions; pos++) { EraseSection section = new EraseSection(); section.m_baseAddress = baseAddress; section.m_numEraseBlocks = ((uint)cfg[0x2D + pos * 4] + ((uint)cfg[0x2E + pos * 4] << 8)) + 1u; section.m_sizeEraseBlocks = ((uint)cfg[0x2F + pos * 4] + ((uint)cfg[0x30 + pos * 4] << 8)) * 256; baseAddress += section.m_numEraseBlocks * section.m_sizeEraseBlocks; section.m_endAddress = baseAddress; m_eraseSections[pos] = section; } } } //--// public override unsafe bool EraseSectors( UIntPtr addressStart , UIntPtr addressEnd ) { ushort* flashBaseAddress = GetChipBaseAddress(); foreach(var sec in m_eraseSections) { ushort* blockStart; ushort* blockEnd; while(sec.FindBlock( addressStart, out blockStart, out blockEnd )) { if(ShouldEraseBlock( blockStart, blockEnd )) { StartBlockErase( flashBaseAddress, blockStart ); System.Threading.Thread.Sleep( 500 ); if(WaitForCompletion( blockStart ) == false) { return false; } } addressStart = new UIntPtr( blockEnd ); if(Microsoft.Zelig.AddressMath.IsLessThan( addressStart, addressEnd ) == false) { break; } } } return true; } public override unsafe bool WriteByte( UIntPtr address , byte val ) { byte* ptr = (byte*)address.ToPointer(); ushort val2; if(IsOddAddress( address )) { ptr -= 1; val2 = (ushort)((uint)val << 8 | (uint)ptr[0]); } else { val2 = (ushort)((uint)ptr[1] << 8 | (uint)val); } return WriteShort( new UIntPtr( ptr ), val2 ); } public override unsafe bool WriteShort( UIntPtr address , ushort val ) { if(IsOddAddress( address )) { return WriteByte( address, (byte) val ) && WriteByte( Microsoft.Zelig.AddressMath.Increment( address, 1 ), (byte)(val >> 8) ) ; } ushort* flashBaseAddress = GetChipBaseAddress(); ushort* wordAddress = (ushort*)address.ToPointer(); StartWordProgramming( flashBaseAddress, wordAddress, val ); WaitForCompletion( wordAddress ); return wordAddress[0] == val; } public override bool WriteWord( UIntPtr address , uint val ) { if(IsOddAddress( address )) { return WriteByte ( address, (byte ) val ) && WriteShort( Microsoft.Zelig.AddressMath.Increment( address, 1 ), (ushort)(val >> 8) ) && WriteByte ( Microsoft.Zelig.AddressMath.Increment( address, 3 ), (byte )(val >> 24) ) ; } else { return WriteShort( address, (ushort) val ) && WriteShort( Microsoft.Zelig.AddressMath.Increment( address, 2 ), (ushort)(val >> 16) ) ; } } public override bool Write( UIntPtr address , byte[] buffer , uint offset , uint numBytes ) { if(numBytes > 0) { if(IsOddAddress( address )) { if(WriteByte( address, buffer[offset] ) == false) { return false; } address = Microsoft.Zelig.AddressMath.Increment( address, 1 ); offset += 1; numBytes -= 1; } while(numBytes >= 2) { uint val; val = (uint)buffer[ offset++ ]; val |= (uint)buffer[ offset++ ] << 8; if(WriteShort( address, (ushort)val ) == false) { return false; } address = Microsoft.Zelig.AddressMath.Increment( address, 2 ); numBytes -= 2; } if(numBytes != 0) { if(WriteByte( address, buffer[offset] ) == false) { return false; } } } return true; } //--// public override unsafe byte ReadByte( UIntPtr address ) { byte* ptr = (byte*)address.ToPointer(); return ptr[0]; } public override unsafe ushort ReadShort( UIntPtr address ) { byte* ptr = (byte*)address.ToPointer(); return (ushort)((uint)ptr[0] | (uint)ptr[1] << 8 ); } public override unsafe uint ReadWord( UIntPtr address ) { byte* ptr = (byte*)address.ToPointer(); return ((uint)ptr[0] | (uint)ptr[1] << 8 | (uint)ptr[2] << 16 | (uint)ptr[3] << 24 ); } public override void Read( UIntPtr address , byte[] buffer , uint offset , uint numBytes ) { while(numBytes != 0) { buffer[offset++] = ReadByte( address ); address = Microsoft.Zelig.AddressMath.Increment( address, 1 ); numBytes--; } } [RT.NoInline] [RT.DisableNullChecks()] [RT.MemoryRequirements( RT.MemoryAttributes.RAM )] public unsafe override void SubstituteFirmware( UIntPtr addressDestination , UIntPtr addressSource , uint numBytes ) { using(RT.SmartHandles.InterruptState.DisableAll()) { ushort* flashBaseAddress = GetChipBaseAddress(); // // Erase old firmware. // { UIntPtr addressStart = addressDestination; UIntPtr addressEnd = Microsoft.Zelig.AddressMath.Increment( addressDestination, numBytes ); foreach(var sec in m_eraseSections) { ushort* blockStart; ushort* blockEnd; while(sec.FindBlock( addressStart, out blockStart, out blockEnd )) { StartBlockErase( flashBaseAddress, blockStart ); if(WaitForCompletion( blockStart ) == false) { while(true) { } } addressStart = new UIntPtr( blockEnd ); if(Microsoft.Zelig.AddressMath.IsLessThan( addressStart, addressEnd ) == false) { break; } } } } // // Copy firmware. // { var dst = (ushort*)addressDestination.ToPointer(); var src = (ushort*)addressSource .ToPointer(); for(int i = 0; i < numBytes; i += sizeof(ushort)) { StartWordProgramming( flashBaseAddress, dst, *src ); WaitForCompletion( dst ); if(*dst++ != *src++) { while(true) { } } } } // // Erase new firmware. // { UIntPtr addressStart = addressSource; UIntPtr addressEnd = Microsoft.Zelig.AddressMath.Increment( addressSource, numBytes ); foreach(var sec in m_eraseSections) { ushort* blockStart; ushort* blockEnd; while(sec.FindBlock( addressStart, out blockStart, out blockEnd )) { StartBlockErase( flashBaseAddress, blockStart ); if(WaitForCompletion( blockStart ) == false) { while(true) { } } addressStart = new UIntPtr( blockEnd ); if(Microsoft.Zelig.AddressMath.IsLessThan( addressStart, addressEnd ) == false) { break; } } } } // // Reboot. // Processor.SetRegister( Processor.Context.RegistersOnStack.ProgramCounterRegister, new UIntPtr( flashBaseAddress ) ); } } public unsafe override void RebootDevice() { // // Reboot. // Processor.SetRegister( Processor.Context.RegistersOnStack.ProgramCounterRegister, new UIntPtr( GetChipBaseAddress() ) ); } //--// [RT.Inline] static bool IsOddAddress( UIntPtr address ) { return Zelig.AddressMath.IsAlignedTo16bits( address ) == false; } [RT.DisableNullChecks()] static unsafe bool ShouldEraseBlock( ushort* blockStart , ushort* blockEnd ) { uint* ptr = (uint*)blockStart; while(ptr < blockEnd) { if(ptr[0] != ErasedValuePair) { return true; } ptr++; } return false; } [RT.NoInline] [RT.DisableNullChecks()] [RT.MemoryRequirements( RT.MemoryAttributes.RAM )] static unsafe void ReadCFI( ushort* flashBaseAddress , ushort[] buf ) { EnterCFI( flashBaseAddress ); for(int i = 0; i < buf.Length; i++) { buf[i] = flashBaseAddress[i]; } IssueResetCommand( flashBaseAddress ); } [RT.NoInline] [RT.DisableNullChecks()] [RT.MemoryRequirements( RT.MemoryAttributes.RAM )] static unsafe void StartWordProgramming( ushort* flashBaseAddress , ushort* wordAddress , ushort val ) { using(RT.SmartHandles.InterruptState.DisableAll()) { flashBaseAddress[0x555] = 0x00AA; flashBaseAddress[0x2AA] = 0x0055; flashBaseAddress[0x555] = 0x00A0; wordAddress[0] = val; } } [RT.NoInline] [RT.DisableNullChecks()] [RT.MemoryRequirements( RT.MemoryAttributes.RAM )] static unsafe void StartBlockErase( ushort* flashBaseAddress , ushort* blockStart ) { using(RT.SmartHandles.InterruptState.DisableAll()) { flashBaseAddress[0x555] = 0x00AA; flashBaseAddress[0x2AA] = 0x0055; flashBaseAddress[0x555] = 0x0080; flashBaseAddress[0x555] = 0x00AA; flashBaseAddress[0x2AA] = 0x0055; blockStart[0] = 0x0030; } } //// public static int fail; //// public static int fail_loops; //// public static int words; //// public static int loops; //// public static ushort fail_val1; //// public static ushort fail_val2; //// public static ushort fail_val3; [RT.NoInline] [RT.DisableNullChecks()] [RT.MemoryRequirements( RT.MemoryAttributes.RAM )] static unsafe bool WaitForCompletion( ushort* wordAddress ) { //// int loop = 0; while(true) { uint val1; uint val2; uint val3; using(RT.SmartHandles.InterruptState.DisableAll()) { val1 = wordAddress[0]; val2 = wordAddress[0]; val3 = wordAddress[0]; } // // Is DQ6 toggling? // if(((val1 ^ val2) & 0x40) != 0 || ((val2 ^ val3) & 0x40) != 0) { // // Continue. // //// loops++; continue; } if(val1 == val2 || val2 == val3) { //// words += 1; //// loops += loop; return true; } else { //// fail_val1 = (ushort)val1; //// fail_val2 = (ushort)val2; //// fail_val2 = (ushort)val3; //// fail += 1; //// fail_loops += loop; IssueResetCommand( wordAddress ); return false; } } } //--// [RT.Inline] [RT.DisableNullChecks()] static unsafe ushort* GetChipBaseAddress() { return (ushort*)new UIntPtr( FlashBase ).ToPointer(); } [RT.Inline] [RT.DisableNullChecks()] static unsafe ushort* GetChipBaseAddress( ushort* address ) { return (ushort*)((uint)address & FlashMask); } [RT.Inline] [RT.DisableNullChecks()] static unsafe void EnterCFI( ushort* baseAddress ) { baseAddress[0x555] = 0x98; } [RT.Inline] [RT.DisableNullChecks()] static unsafe void IssueResetCommand( ushort* baseAddress ) { baseAddress[0] = 0xF0; } } } ================================================ FILE: Zelig/Zelig/RunTime/DeviceModels/VoxSoloFormFactor/Properties/AssemblyInfo.cs ================================================ using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; // General Information about an assembly is controlled through the following // set of attributes. Change these attribute values to modify the information // associated with an assembly. [assembly: AssemblyTitle( "Microsoft.VoxSoloFormFactor" )] [assembly: AssemblyDescription( "" )] [assembly: AssemblyConfiguration( "" )] [assembly: AssemblyCompany( "Microsoft" )] [assembly: AssemblyProduct( "Microsoft.VoxSoloFormFactor" )] [assembly: AssemblyCopyright( "Copyright © Microsoft 2007" )] [assembly: AssemblyTrademark( "" )] [assembly: AssemblyCulture( "" )] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible( false )] //// The following GUID is for the ID of the typelib if this project is exposed to COM //[assembly: Guid( "975a7db2-22e5-41c6-9e32-d3f72152d387" )] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Revision and Build Numbers // by using the '*' as shown below: [assembly: AssemblyVersion( "1.0.0.0" )] [assembly: AssemblyFileVersion( "1.0.0.0" )] ================================================ FILE: Zelig/Zelig/RunTime/DeviceModels/VoxSoloFormFactor/SystemServices/GarbageCollectionManager.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // namespace Microsoft.VoxSoloFormFactor { using System; using RT = Microsoft.Zelig.Runtime; using TS = Microsoft.Zelig.Runtime.TypeSystem; public sealed class GarbageCollectionManager : RT.PreciseMarkAndSweepCollector { } } ================================================ FILE: Zelig/Zelig/RunTime/DeviceModels/VoxSoloFormFactor/SystemServices/MemoryManager.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // namespace Microsoft.VoxSoloFormFactor { using System; using RT = Microsoft.Zelig.Runtime; using TS = Microsoft.Zelig.Runtime.TypeSystem; public sealed class MemoryManager : RT.LinearMemoryManager { } } ================================================ FILE: Zelig/Zelig/RunTime/DeviceModels/VoxSoloFormFactor/SystemServices/SerialPortsManager.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // namespace Microsoft.VoxSoloFormFactor { using System; using RT = Microsoft.Zelig.Runtime; using TS = Microsoft.Zelig.Runtime.TypeSystem; public sealed class SerialPortsManager : Microsoft.DeviceModels.Chipset.MM9691LP.Runtime.SerialPortsManager { } } ================================================ FILE: Zelig/Zelig/RunTime/DeviceModels/VoxSoloFormFactor/SystemServices/ThreadManager.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // namespace Microsoft.VoxSoloFormFactor { using System; using RT = Microsoft.Zelig.Runtime; using TS = Microsoft.Zelig.Runtime.TypeSystem; using ChipsetModel = Microsoft.DeviceModels.Chipset.MM9691LP; public sealed class ThreadManager : ChipsetModel.Runtime.ThreadManager { } } ================================================ FILE: Zelig/Zelig/RunTime/DeviceModels/VoxSoloFormFactor/SystemServices/TypeSystemManager.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // namespace Microsoft.VoxSoloFormFactor { using System; using RT = Microsoft.Zelig.Runtime; using TS = Microsoft.Zelig.Runtime.TypeSystem; public sealed class TypeSystemManager : RT.DefaultTypeSystemManager { } } ================================================ FILE: Zelig/Zelig/RunTime/DeviceModels/VoxSoloFormFactor/VoxSoloFormFactor.csproj ================================================  Debug AnyCPU 9.0.21022 2.0 {186F31A3-EF89-4A25-B2D5-20070726AA01} Library Properties Microsoft.VoxSoloFormFactor Microsoft.VoxSoloFormFactor $(LlilumBuildRoot)\Target\obj\$(MSBuildProjectName)\ v4.5 true full false $(LlilumBuildRoot)\Target\bin\$(Configuration)\ DEBUG;TRACE prompt 4 true true true AllRules.ruleset AnyCPU false pdbonly true $(LlilumBuildRoot)\Target\bin\$(Configuration)\ TRACE prompt 4 true true true AllRules.ruleset AnyCPU false true full false $(LlilumBuildRoot)\Target\bin\$(Configuration)\ TRACE;DEBUG AnyCPU true true true false {186F31A3-EF89-4A25-B2D5-20060501AA01} mscorlib False {186F31A3-EF89-4A25-B2D5-20061218AA01} Common False {186F31A3-EF89-4A25-B2D5-20060509AA01} Kernel False {186F31A3-EF89-4A25-B2D5-20060720AA01} TypeSystem False {186F31A3-EF89-4A25-B2D5-20070724AA02} ModelForMM9691LP False 3.5 ================================================ FILE: Zelig/Zelig/RunTime/DeviceModels/VoxSoloFormFactorLoader/HardwareModel/Device.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // namespace Microsoft.VoxSoloFormFactorLoader { using System; using System.Runtime.CompilerServices; using RT = Microsoft.Zelig.Runtime; using ChipsetModel = Microsoft.DeviceModels.Chipset.MM9691LP; public sealed class Device : RT.Device { public override void PreInitializeProcessorAndMemory() { // // Enter System mode, with interrupts disabled. // Processor.SetStatusRegister( Processor.c_psr_field_c, Processor.c_psr_I | Processor.c_psr_F | Processor.c_psr_mode_SYS ); Processor.SetRegister( Processor.Context.RegistersOnStack.StackRegister, this.BootstrapStackPointer ); // // Disable cache and remove remap of FLASH onto RAM. // { ChipsetModel.REMAP_PAUSE remap = ChipsetModel.REMAP_PAUSE.Instance; remap.Cache_Enable = 0; remap.ClearResetMap = 0; } // // Configure external FLASH chip with proper wait states. // { ChipsetModel.EBIU.DEVICE flashChip; var ctrl = new ChipsetModel.EBIU.DEVICE.ControlBitField(); ctrl.WS = 2; ctrl.RCNT = 0; ctrl.SZ = ChipsetModel.EBIU.DEVICE.Size.SZ16; // // Low 8mega. // flashChip = ChipsetModel.EBIU.Instance.Device0; flashChip.LowAddress = 0x10000000; flashChip.HighAddress = 0x10000000 + 8 * 1024 * 1024; flashChip.Control = ctrl; // // High 8mega. // flashChip = ChipsetModel.EBIU.Instance.Device1; flashChip.LowAddress = 0x10000000 + 8 * 1024 * 1024; flashChip.HighAddress = 0x10000000 + 16 * 1024 * 1024; flashChip.Control = ctrl; } { ChipsetModel.CMU cmu = ChipsetModel.CMU.Instance; // // We should wait 80usec for the switching regulator to warm up. // Processor.Delay( 80 * 32 / 12 ); // At reset, the clock prescaler is set to 12. cmu.CLK_SEL = ChipsetModel.CMU.CLK_SEL__EXTSLOW | ChipsetModel.CMU.CLK_SEL__NOPCU; // ChipsetModel.CMU.CLK_SEL__CKOUTEN cmu.PERF_LVL = (uint)ChipsetModel.CMU.PERF_LEVEL.CLK_SEL__DIV_FAST; } } public override void MoveCodeToProperLocation() { Memory.Instance.ExecuteImageRelocation(); } } } ================================================ FILE: Zelig/Zelig/RunTime/DeviceModels/VoxSoloFormFactorLoader/HardwareModel/Drivers/InterruptController.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // namespace Microsoft.VoxSoloFormFactorLoader.Drivers { using System; using System.Runtime.CompilerServices; using RT = Microsoft.Zelig.Runtime; using ChipsetModel = Microsoft.DeviceModels.Chipset.MM9691LP; public sealed class InterruptController : ChipsetModel.Drivers.InterruptController { } } ================================================ FILE: Zelig/Zelig/RunTime/DeviceModels/VoxSoloFormFactorLoader/HardwareModel/Drivers/RealTimeClock.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // namespace Microsoft.VoxSoloFormFactorLoader.Drivers { using System; using System.Runtime.CompilerServices; using RT = Microsoft.Zelig.Runtime; using ChipsetModel = Microsoft.DeviceModels.Chipset.MM9691LP; public sealed class RealTimeClock : ChipsetModel.Drivers.RealTimeClock { } } ================================================ FILE: Zelig/Zelig/RunTime/DeviceModels/VoxSoloFormFactorLoader/HardwareModel/Memory.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // namespace Microsoft.VoxSoloFormFactorLoader { using System; using RT = Microsoft.Zelig.Runtime; using TS = Microsoft.Zelig.Runtime.TypeSystem; public sealed class Memory : RT.Memory { public override void InitializeMemory() { } } } ================================================ FILE: Zelig/Zelig/RunTime/DeviceModels/VoxSoloFormFactorLoader/HardwareModel/Peripherals.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // namespace Microsoft.VoxSoloFormFactorLoader { using System; using System.Runtime.CompilerServices; using RT = Microsoft.Zelig.Runtime; using TS = Microsoft.Zelig.Runtime.TypeSystem; public sealed class Peripherals : RT.Peripherals { public override void Initialize() { } public override void Activate() { } public override void EnableInterrupt( uint index ) { } public override void DisableInterrupt( uint index ) { } public override void CauseInterrupt() { } public override void WaitForInterrupt() { } public override void ContinueUnderNormalInterrupt( Continuation dlg ) { } public override void ProcessInterrupt() { } public override void ProcessFastInterrupt() { } public override ulong GetPerformanceCounterFrequency() { return 0; } public override unsafe uint ReadPerformanceCounter() { return 0; } } } ================================================ FILE: Zelig/Zelig/RunTime/DeviceModels/VoxSoloFormFactorLoader/HardwareModel/Processor.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // namespace Microsoft.VoxSoloFormFactorLoader { using System; using RT = Microsoft.Zelig.Runtime; using TS = Microsoft.Zelig.Runtime.TypeSystem; public sealed class Processor : RT.TargetPlatform.ARMv4.ProcessorARMv4 { // // Helper Methods // public override void InitializeProcessor() { } public override UIntPtr GetCacheableAddress( UIntPtr ptr ) { return ptr; } public override UIntPtr GetUncacheableAddress( UIntPtr ptr ) { return ptr; } public override unsafe void FlushCacheLine( UIntPtr target ) { } //--// [RT.Inline] public override RT.Processor.Context AllocateProcessorContext(RT.ThreadImpl owner) { return null; } } } ================================================ FILE: Zelig/Zelig/RunTime/DeviceModels/VoxSoloFormFactorLoader/HardwareModel/Storage.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // namespace Microsoft.VoxSoloFormFactorLoader { using System; using RT = Microsoft.Zelig.Runtime; using TS = Microsoft.Zelig.Runtime.TypeSystem; public sealed class Storage : RT.Storage { // // Helper Methods // public override void InitializeStorage() { } //--// public override bool EraseSectors( UIntPtr addressStart , UIntPtr addressEnd ) { return false; } public override bool WriteByte( UIntPtr address , byte val ) { return false; } public override bool WriteShort( UIntPtr address , ushort val ) { return false; } public override bool WriteWord( UIntPtr address , uint val ) { return false; } public override bool Write( UIntPtr address , byte[] buffer , uint offset , uint numBytes ) { return false; } //--// public override unsafe byte ReadByte( UIntPtr address ) { return 0; } public override unsafe ushort ReadShort( UIntPtr address ) { return 0; } public override unsafe uint ReadWord( UIntPtr address ) { return 0; } public override void Read( UIntPtr address , byte[] buffer , uint offset , uint numBytes ) { } public override void SubstituteFirmware( UIntPtr addressDestination , UIntPtr addressSource , uint numBytes ) { } public override void RebootDevice() { throw new System.NotImplementedException(); } } } ================================================ FILE: Zelig/Zelig/RunTime/DeviceModels/VoxSoloFormFactorLoader/Loader.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // namespace Microsoft.VoxSoloFormFactorLoader { using System; using System.Collections.Generic; using RT = Microsoft.Zelig.Runtime; // // Override stock bootstrap code, to avoid including most of the code. // [RT.ExtendClass(typeof(RT.Bootstrap))] public static class BootstrapImpl { [RT.NoInline] [RT.NoReturn] private static void Initialization() { Processor.Instance.InitializeProcessor(); RT.Configuration.ExecuteApplication(); } } [RT.ExtendClass(typeof(RT.TypeSystemManager),NoConstructors=true)] public class TypeSystemManagerImpl { public void DeliverException( Exception obj ) { } } class Loader { const uint cmd_Signature = 0xDEADC000; const uint cmd_Mask = 0xFFFFFF00; const byte cmd_Hello = 0x01; const byte cmd_EnterCFI = 0x02; // Arg: Address const byte cmd_ExitCFI = 0x03; // Arg: Address const byte cmd_ReadMemory8 = 0x04; // Arg: Address, Size => values const byte cmd_ReadMemory16 = 0x05; // Arg: Address, Size => values const byte cmd_ReadMemory32 = 0x06; // Arg: Address, Size => values const byte cmd_ChecksumMemory = 0x07; // Arg: Address, Size => CRC value, AND of all memory const byte cmd_EraseSector = 0x08; // Arg: Address => Status value const byte cmd_ProgramMemory = 0x09; // Arg: Address, Size, [32bits words] => Status value const uint FlashSize = 8 * 1024 * 1024; const uint FlashMask = ~(FlashSize - 1); //--// [RT.DisableNullChecks()] static unsafe ushort* GetChipBaseAddress( ushort* address ) { return (ushort*)((uint)address & FlashMask); } [RT.DisableNullChecks()] static unsafe void EnterCFI( ushort* baseAddress ) { baseAddress[0x555] = 0x98; } [RT.DisableNullChecks()] static unsafe void ExitCFI( ushort* baseAddress ) { baseAddress[0] = 0xF0; } [RT.DisableNullChecks()] static unsafe void EraseSector( ushort* sectorStart ) { ushort* baseAddress = GetChipBaseAddress( sectorStart ); baseAddress[0x555] = 0x00AA; baseAddress[0x2AA] = 0x0055; baseAddress[0x555] = 0x0080; baseAddress[0x555] = 0x00AA; baseAddress[0x2AA] = 0x0055; sectorStart[0] = 0x0030; while(sectorStart[0] != sectorStart[0]); } [RT.DisableNullChecks()] static unsafe void WriteWord( ushort* address , ushort value ) { ushort* baseAddress = GetChipBaseAddress( address ); baseAddress[0x555] = 0x00AA; baseAddress[0x2AA] = 0x0055; baseAddress[0x555] = 0x00A0; address[0] = value; while(address[0] != address[0]); } //--// //// static string m_lock; [RT.DisableNullChecks( ApplyRecursively=true )] static unsafe void Main() { //// while(System.Threading.Interlocked.CompareExchange( ref m_lock, "Test", null ) != null) //// { //// } while(true) { uint cmd = RT.TargetPlatform.ARMv4.Coprocessor14.ReadDCC(); if((cmd & cmd_Mask) == cmd_Signature) { switch((byte)cmd) { case cmd_Hello: RT.TargetPlatform.ARMv4.Coprocessor14.WriteDCC( cmd ); break; case cmd_EnterCFI: EnterCFI( (ushort*)RT.TargetPlatform.ARMv4.Coprocessor14.ReadDCC() ); RT.TargetPlatform.ARMv4.Coprocessor14.WriteDCC( cmd ); break; case cmd_ExitCFI: ExitCFI( (ushort*)RT.TargetPlatform.ARMv4.Coprocessor14.ReadDCC() ); RT.TargetPlatform.ARMv4.Coprocessor14.WriteDCC( cmd ); break; case cmd_ReadMemory8: { byte* ptr = (byte*)RT.TargetPlatform.ARMv4.Coprocessor14.ReadDCC(); uint len = RT.TargetPlatform.ARMv4.Coprocessor14.ReadDCC(); RT.TargetPlatform.ARMv4.Coprocessor14.WriteDCC( cmd ); while(len > 0) { RT.TargetPlatform.ARMv4.Coprocessor14.WriteDCC( *ptr++ ); len--; } } break; case cmd_ReadMemory16: { ushort* ptr = (ushort*)RT.TargetPlatform.ARMv4.Coprocessor14.ReadDCC(); uint len = RT.TargetPlatform.ARMv4.Coprocessor14.ReadDCC(); RT.TargetPlatform.ARMv4.Coprocessor14.WriteDCC( cmd ); while(len > 0) { RT.TargetPlatform.ARMv4.Coprocessor14.WriteDCC( *ptr++ ); len--; } } break; case cmd_ReadMemory32: { uint* ptr = (uint*)RT.TargetPlatform.ARMv4.Coprocessor14.ReadDCC(); uint len = RT.TargetPlatform.ARMv4.Coprocessor14.ReadDCC(); RT.TargetPlatform.ARMv4.Coprocessor14.WriteDCC( cmd ); while(len > 0) { RT.TargetPlatform.ARMv4.Coprocessor14.WriteDCC( *ptr++ ); len--; } } break; case cmd_ChecksumMemory: { uint* ptr = (uint*)RT.TargetPlatform.ARMv4.Coprocessor14.ReadDCC(); uint len = RT.TargetPlatform.ARMv4.Coprocessor14.ReadDCC(); uint sum = 0; uint and = 0xFFFFFFFF; RT.TargetPlatform.ARMv4.Coprocessor14.WriteDCC( cmd ); while(len > 0) { uint val = *ptr; sum = ((sum & 1) << 31) | (sum >> 1); sum += val; and &= val; ptr++; len--; } RT.TargetPlatform.ARMv4.Coprocessor14.WriteDCC( sum ); RT.TargetPlatform.ARMv4.Coprocessor14.WriteDCC( and ); } break; case cmd_EraseSector: EraseSector( (ushort*)RT.TargetPlatform.ARMv4.Coprocessor14.ReadDCC() ); RT.TargetPlatform.ARMv4.Coprocessor14.WriteDCC( cmd ); RT.TargetPlatform.ARMv4.Coprocessor14.WriteDCC( 0 ); break; case cmd_ProgramMemory: { ushort* ptr = (ushort*)RT.TargetPlatform.ARMv4.Coprocessor14.ReadDCC(); uint len = RT.TargetPlatform.ARMv4.Coprocessor14.ReadDCC(); RT.TargetPlatform.ARMv4.Coprocessor14.WriteDCC( cmd ); while(len > 0) { uint val = RT.TargetPlatform.ARMv4.Coprocessor14.ReadDCC(); WriteWord( ptr++, (ushort) val ); WriteWord( ptr++, (ushort)(val >> 16) ); len--; } RT.TargetPlatform.ARMv4.Coprocessor14.WriteDCC( 0 ); } break; } } } } } } ================================================ FILE: Zelig/Zelig/RunTime/DeviceModels/VoxSoloFormFactorLoader/Properties/AssemblyInfo.cs ================================================ using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; // General Information about an assembly is controlled through the following // set of attributes. Change these attribute values to modify the information // associated with an assembly. [assembly: AssemblyTitle( "Microsoft.VoxSoloFormFactorLoader" )] [assembly: AssemblyDescription( "" )] [assembly: AssemblyConfiguration( "" )] [assembly: AssemblyCompany( "Microsoft" )] [assembly: AssemblyProduct( "Microsoft.VoxSoloFormFactorLoader" )] [assembly: AssemblyCopyright( "Copyright © Microsoft 2007" )] [assembly: AssemblyTrademark( "" )] [assembly: AssemblyCulture( "" )] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible( false )] //// The following GUID is for the ID of the typelib if this project is exposed to COM //[assembly: Guid( "975a7db2-22e5-41c6-9e32-d3f72152d387" )] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Revision and Build Numbers // by using the '*' as shown below: [assembly: AssemblyVersion( "1.0.0.0" )] [assembly: AssemblyFileVersion( "1.0.0.0" )] ================================================ FILE: Zelig/Zelig/RunTime/DeviceModels/VoxSoloFormFactorLoader/VoxSoloFormFactorLoader.csproj ================================================  Debug AnyCPU 9.0.21022 2.0 {186F31A3-EF89-4A25-B2D5-20070725AA01} Exe Properties Microsoft.VoxSoloFormFactorLoader Microsoft.VoxSoloFormFactorLoader $(LlilumBuildRoot)\Target\obj\$(MSBuildProjectName)\ v4.5 true full false $(LlilumBuildRoot)\Target\bin\$(Configuration)\ DEBUG;TRACE prompt 4 true true true AllRules.ruleset AnyCPU false pdbonly true $(LlilumBuildRoot)\Target\bin\$(Configuration)\ TRACE prompt 4 true true true AllRules.ruleset AnyCPU false true full false $(LlilumBuildRoot)\Target\bin\$(Configuration)\ true AnyCPU TRACE;DEBUG true true false {186F31A3-EF89-4A25-B2D5-20060501AA01} mscorlib False {186F31A3-EF89-4A25-B2D5-20061218AA01} Common False {186F31A3-EF89-4A25-B2D5-20060509AA01} Kernel False {186F31A3-EF89-4A25-B2D5-20060720AA01} TypeSystem False {186F31A3-EF89-4A25-B2D5-20070724AA02} ModelForMM9691LP False 3.5 ================================================ FILE: Zelig/Zelig/RunTime/DeviceModels/VoxSoloFormFactorTester/Properties/AssemblyInfo.cs ================================================ using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; // General Information about an assembly is controlled through the following // set of attributes. Change these attribute values to modify the information // associated with an assembly. [assembly: AssemblyTitle( "VoxSoloFormFactorTester" )] [assembly: AssemblyDescription( "" )] [assembly: AssemblyConfiguration( "" )] [assembly: AssemblyCompany( "Microsoft" )] [assembly: AssemblyProduct( "VoxSoloFormFactorTester" )] [assembly: AssemblyCopyright( "Copyright © Microsoft 2007" )] [assembly: AssemblyTrademark( "" )] [assembly: AssemblyCulture( "" )] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. //[assembly: ComVisible( false )] // The following GUID is for the ID of the typelib if this project is exposed to COM //[assembly: Guid( "790c97c2-f14c-473e-a9eb-1b72d95bad30" )] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // [assembly: AssemblyVersion( "1.0.0.0" )] [assembly: AssemblyFileVersion( "1.0.0.0" )] ================================================ FILE: Zelig/Zelig/RunTime/DeviceModels/VoxSoloFormFactorTester/Tester.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // //#define TEST_SERIAL namespace Microsoft.VoxSoloFormFactorTester { using System; using System.Collections.Generic; class Tester { #if TEST_SERIAL static void TestSerial() { var port = new System.IO.Ports.SerialPort( "COM2" ); port.BaudRate = 115200; port.ReadBufferSize = 256; port.WriteBufferSize = 256; port.Open(); port.Write( "Hello World!" ); byte[] writeBuf = new byte[1]; while(true) { System.Diagnostics.Stopwatch stopwatch = new System.Diagnostics.Stopwatch(); stopwatch.Start(); const int total = 32 * 1024; int ch = 0; for(int j = 0; j < total; j++) { writeBuf[0] = (byte)(48 + ch); port.Write( writeBuf, 0, 1 ); ch = (ch + 1) % 32; } stopwatch.Stop(); port.Write( "\r\n" ); port.Write( "\r\n" ); port.Write( string.Format( "Took {0} to send {1} bytes", stopwatch.ElapsedMilliseconds, total ) ); //// byte[] buf = new byte[64]; //// //// while(true) //// { //// for(int i = 0; i < 64; i++) //// { //// buf[i] = port.Read(); //// } //// //// //port.Write( (byte)'>' ); //// for(int i = 0; i < 64; i++) //// { //// port.Write( buf[i] ); //// } //// //port.Write( (byte)'<' ); //// } GC.Collect(); } } #endif static void Main() { #if TEST_SERIAL TestSerial(); #endif } } } ================================================ FILE: Zelig/Zelig/RunTime/DeviceModels/VoxSoloFormFactorTester/VoxSoloFormFactorTester.csproj ================================================  Debug AnyCPU 9.0.21022 2.0 {186F31A3-EF89-4A25-B2D5-20070803AA01} Exe Properties Microsoft.VoxSoloFormFactorTester Microsoft.VoxSoloFormFactorTester $(LlilumBuildRoot)\Target\obj\$(MSBuildProjectName)\ v4.5 true full false $(LlilumBuildRoot)\Target\bin\$(Configuration)\ DEBUG;TRACE prompt 4 true true true AllRules.ruleset AnyCPU false pdbonly true $(LlilumBuildRoot)\Target\bin\$(Configuration)\ TRACE prompt 4 true true true AllRules.ruleset AnyCPU false true full false $(LlilumBuildRoot)\Target\bin\$(Configuration)\ TRACE;DEBUG AnyCPU true true true false {186F31A3-EF89-4A25-B2D5-20060501AA01} mscorlib False {186F31A3-EF89-4A25-B2D5-20070702AA01} system False {186F31A3-EF89-4A25-B2D5-20070724AA02} ModelForMM9691LP False {186F31A3-EF89-4A25-B2D5-20070726AA01} VoxSoloFormFactor False 3.5 ================================================ FILE: Zelig/Zelig/RunTime/DeviceModels/iMote2/HardwareModel/Device.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // namespace Microsoft.iMote2 { using System; using System.Runtime.CompilerServices; using RT = Microsoft.Zelig.Runtime; using ARMv4 = Microsoft.Zelig.Runtime.TargetPlatform.ARMv4; using ChipsetModel = Microsoft.DeviceModels.Chipset.PXA27x; using Microsoft.Zelig.Runtime; public sealed class Device : RT.Device { public override void PreInitializeProcessorAndMemory() { // // Enter System mode, with interrupts disabled. // Processor.SetStatusRegister( Processor.c_psr_field_c, Processor.c_psr_I | Processor.c_psr_F | Processor.c_psr_mode_SYS ); Processor.SetRegister( Processor.Context.RegistersOnStack.StackRegister, this.BootstrapStackPointer ); //--// Processor.EnableCaches(); ChipsetModel.ClockManager.Instance.InitializeClocks(); //--// ChipsetModel.MemoryController.Instance.InitializeStackedSDRAM(); } const int DefaultStackSizeMote = (16 * 1024) / sizeof( uint ); [MemoryUsage( MemoryUsage.Stack, ContentsUninitialized = true, AllocateFromHighAddress = true )] static readonly uint[] s_bootstrapStackMote = new uint[DefaultStackSizeMote]; public override uint[] BootstrapStack { get { return s_bootstrapStackMote; } } public override void MoveCodeToProperLocation() { Memory.Instance.ExecuteImageRelocation(); } } } ================================================ FILE: Zelig/Zelig/RunTime/DeviceModels/iMote2/HardwareModel/Drivers/GPIO.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // namespace Microsoft.iMote2.Drivers { using RT = Microsoft.Zelig.Runtime; using ChipsetModel = Microsoft.DeviceModels.Chipset.PXA27x; public sealed class GPIO : ChipsetModel.Drivers.GPIO { } } ================================================ FILE: Zelig/Zelig/RunTime/DeviceModels/iMote2/HardwareModel/Drivers/I2C.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // namespace Microsoft.iMote2.Drivers { using RT = Microsoft.Zelig.Runtime; using ChipsetModel = Microsoft.DeviceModels.Chipset.PXA27x; public sealed class I2C : ChipsetModel.Drivers.I2C { } } ================================================ FILE: Zelig/Zelig/RunTime/DeviceModels/iMote2/HardwareModel/Drivers/InterruptController.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // namespace Microsoft.iMote2.Drivers { using System; using System.Runtime.CompilerServices; using RT = Microsoft.Zelig.Runtime; using ChipsetModel = Microsoft.DeviceModels.Chipset.PXA27x; public sealed class InterruptController : ChipsetModel.Drivers.InterruptController { } } ================================================ FILE: Zelig/Zelig/RunTime/DeviceModels/iMote2/HardwareModel/Drivers/RealTimeClock.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // namespace Microsoft.iMote2.Drivers { using System; using System.Runtime.CompilerServices; using RT = Microsoft.Zelig.Runtime; using ChipsetModel = Microsoft.DeviceModels.Chipset.PXA27x; public sealed class RealTimeClock : ChipsetModel.Drivers.RealTimeClock { } } ================================================ FILE: Zelig/Zelig/RunTime/DeviceModels/iMote2/HardwareModel/Drivers/SPI.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // namespace Microsoft.iMote2.Drivers { using RT = Microsoft.Zelig.Runtime; using ChipsetModel = Microsoft.DeviceModels.Chipset.PXA27x; public sealed class SPI : ChipsetModel.Drivers.SPI { } } ================================================ FILE: Zelig/Zelig/RunTime/DeviceModels/iMote2/HardwareModel/Memory.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // namespace Microsoft.iMote2 { using System; using RT = Microsoft.Zelig.Runtime; using TS = Microsoft.Zelig.Runtime.TypeSystem; public sealed class Memory : RT.Memory { public override void InitializeMemory() { } } } ================================================ FILE: Zelig/Zelig/RunTime/DeviceModels/iMote2/HardwareModel/Peripherals.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // //#define ALLOW_PAUSE namespace Microsoft.iMote2 { using System; using System.Runtime.CompilerServices; using RT = Microsoft.Zelig.Runtime; using TS = Microsoft.Zelig.Runtime.TypeSystem; using ChipsetModel = Microsoft.DeviceModels.Chipset.PXA27x; public sealed unsafe class Peripherals : RT.Peripherals { // // State // // // Helper Methods // public override void Initialize() { } public override void Activate() { Drivers.InterruptController.Instance.Initialize(); Drivers.RealTimeClock.Instance.Initialize(); // These should not be initialized here, otherwise they will always be // included in the image //Drivers.GPIO.Instance.Initialize(); //Drivers.I2C.Instance.Initialize(); //Drivers.SPI.Instance.Initialize(); } public override void EnableInterrupt( uint index ) { } public override void DisableInterrupt( uint index ) { } public override void CauseInterrupt() { Drivers.InterruptController.Instance.CauseInterrupt(); } public override void ContinueUnderNormalInterrupt( Continuation dlg ) { Drivers.InterruptController.Instance.ContinueUnderNormalInterrupt( dlg ); } public override void WaitForInterrupt() { // // Using the Pause register to save power seems to be broken at the hardware level: device locks up!!!!! // #if ALLOW_PAUSE //// ChipsetModel.REMAP_PAUSE.Instance.Pause_AHB = 0; #else while(true) { var ichp = ChipsetModel.InterruptController.Instance.ICHP; if(ichp.VAL_FIQ || ichp.VAL_IRQ) { break; } } #endif } public override void ProcessInterrupt() { using(RT.SmartHandles.SwapCurrentThreadUnderInterrupt hnd = ThreadManager.InstallInterruptThread()) { Drivers.InterruptController.Instance.ProcessInterrupt(); } } [RT.MemoryRequirements( RT.MemoryAttributes.RAM )] public override void ProcessFastInterrupt() { using(RT.SmartHandles.SwapCurrentThreadUnderInterrupt hnd = ThreadManager.InstallFastInterruptThread()) { Drivers.InterruptController.Instance.ProcessFastInterrupt(); } } public override ulong GetPerformanceCounterFrequency() { return 1000000; } [RT.Inline] [RT.DisableNullChecks()] public override unsafe uint ReadPerformanceCounter() { return Drivers.RealTimeClock.Instance.CurrentTimeRaw; } } } ================================================ FILE: Zelig/Zelig/RunTime/DeviceModels/iMote2/HardwareModel/Processor.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // namespace Microsoft.iMote2 { using System; using RT = Microsoft.Zelig.Runtime; using TS = Microsoft.Zelig.Runtime.TypeSystem; using ChipsetModel = Microsoft.DeviceModels.Chipset.PXA27x; using ARMv4 = Microsoft.Zelig.Runtime.TargetPlatform.ARMv4; public sealed class Processor : ChipsetModel.Processor { const uint c_IRAM__BaseAddress = 0x5C000000; const uint c_IRAM__Size = 256 * 1024; const uint c_FLASH__BaseAddress = 0x02000000; const uint c_FLASH__Size = 32 * 1024 * 1024; const uint c_DRAM__BaseAddress = 0xA0000000; const uint c_DRAM__Size = 32 * 1024 * 1024; const uint c_Peripherals__BaseAddress = 0x40000000; const uint c_Peripherals__EndAddress = 0x54000000; [RT.AlignmentRequirements( RT.TargetPlatform.ARMv4.MMUv4.c_TLB_SecondLevelSize, sizeof(uint) )] static uint[] s_TLB_SecondLevel_Vectors = new uint[RT.TargetPlatform.ARMv4.MMUv4.c_TLB_SecondLevelSlots]; // // Helper Methods // public override void InitializeProcessor() { base.InitializeProcessor(); ConfigureMMU(); } private static void ConfigureMMU() { RT.TargetPlatform.ARMv4.MMUv4.ClearTLB(); RT.TargetPlatform.ARMv4.MMUv4.AddCacheableSection ( c_IRAM__BaseAddress , c_IRAM__BaseAddress + c_IRAM__Size , c_IRAM__BaseAddress ); RT.TargetPlatform.ARMv4.MMUv4.AddCacheableSection ( c_FLASH__BaseAddress , c_FLASH__BaseAddress + c_FLASH__Size, 0 ); RT.TargetPlatform.ARMv4.MMUv4.AddCacheableSection ( c_DRAM__BaseAddress , c_DRAM__BaseAddress + c_DRAM__Size , c_DRAM__BaseAddress ); RT.TargetPlatform.ARMv4.MMUv4.AddUncacheableSection( c_Peripherals__BaseAddress, c_Peripherals__EndAddress , c_Peripherals__BaseAddress ); RT.TargetPlatform.ARMv4.MMUv4.AddCoarsePages ( 0x00000000, 0x00100000, s_TLB_SecondLevel_Vectors ); RT.TargetPlatform.ARMv4.MMUv4.AddCacheableCoarsePages( 0x00000000, 0x00001000, 0, s_TLB_SecondLevel_Vectors ); //// RT.TargetPlatform.ARMv4.MMUv4.AddCoarsePages ( 0xFFF00000, 0xFFFFFFFF, s_TLB_SecondLevel_Vectors ); //// RT.TargetPlatform.ARMv4.MMUv4.AddCacheableCoarsePages( 0xFFFF0000, 0xFFFF1000, 0, s_TLB_SecondLevel_Vectors ); RT.TargetPlatform.ARMv4.MMUv4.EnableTLB(); } //--// [RT.BottomOfCallStack()] [RT.HardwareExceptionHandler(RT.HardwareException.Interrupt)] private static void InterruptHandler( ref Context.RegistersOnStack registers ) { s_repeatedAbort = false; Context.InterruptHandlerWithContextSwitch( ref registers ); } [RT.BottomOfCallStack()] [RT.HardwareExceptionHandler(RT.HardwareException.FastInterrupt)] [RT.MemoryRequirements( RT.MemoryAttributes.RAM )] private static void FastInterruptHandler() { s_repeatedAbort = false; Context.FastInterruptHandlerWithoutContextSwitch(); } [RT.BottomOfCallStack()] [RT.HardwareExceptionHandler(RT.HardwareException.SoftwareInterrupt)] private static void SoftwareInterruptHandler( ref Context.RegistersOnStack registers ) { s_repeatedAbort = false; Context.GenericSoftwareInterruptHandler( ref registers ); } //--// static uint fault_DFSR; static uint fault_IFSR; static uint fault_FAR; [RT.NoInline] [RT.NoReturn()] [RT.HardwareExceptionHandler(RT.HardwareException.UndefinedInstruction)] [RT.MemoryUsage(RT.MemoryUsage.Bootstrap)] static void UndefinedInstruction() { fault_DFSR = ARMv4.ProcessorARMv4.MoveFromCoprocessor( 15, 0, 5, 0, 0 ); fault_IFSR = ARMv4.ProcessorARMv4.MoveFromCoprocessor( 15, 0, 5, 0, 1 ); fault_FAR = ARMv4.ProcessorARMv4.MoveFromCoprocessor( 15, 0, 6, 0, 0 ); Processor.Instance.Breakpoint(); } [RT.NoInline] [RT.NoReturn()] [RT.HardwareExceptionHandler(RT.HardwareException.PrefetchAbort)] [RT.MemoryUsage(RT.MemoryUsage.Bootstrap)] static void PrefetchAbort() { fault_DFSR = ARMv4.ProcessorARMv4.MoveFromCoprocessor( 15, 0, 5, 0, 0 ); fault_IFSR = ARMv4.ProcessorARMv4.MoveFromCoprocessor( 15, 0, 5, 0, 1 ); fault_FAR = ARMv4.ProcessorARMv4.MoveFromCoprocessor( 15, 0, 6, 0, 0 ); Processor.Instance.Breakpoint(); } private static bool s_repeatedAbort = false; private static int s_abortCount = 0; [RT.NoInline] [RT.NoReturn()] [RT.HardwareExceptionHandler(RT.HardwareException.DataAbort)] [RT.MemoryUsage(RT.MemoryUsage.Bootstrap)] static void DataAbort() { fault_DFSR = ARMv4.ProcessorARMv4.MoveFromCoprocessor( 15, 0, 5, 0, 0 ); fault_IFSR = ARMv4.ProcessorARMv4.MoveFromCoprocessor( 15, 0, 5, 0, 1 ); fault_FAR = ARMv4.ProcessorARMv4.MoveFromCoprocessor( 15, 0, 6, 0, 0 ); bool repeatedAbort = s_repeatedAbort; s_repeatedAbort = true; s_abortCount++; if (repeatedAbort) Processor.Instance.Breakpoint(); } } } ================================================ FILE: Zelig/Zelig/RunTime/DeviceModels/iMote2/HardwareModel/Storage.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // namespace Microsoft.iMote2 { using System; using RT = Microsoft.Zelig.Runtime; using TS = Microsoft.Zelig.Runtime.TypeSystem; public sealed class Storage : RT.Storage { const uint DRAMSize = 2 * 8 * 1024 * 1024; const uint DRAMBase = 0xA0000000 + DRAMSize; const uint DRAMEnd = DRAMBase + DRAMSize; const uint DRAMMask = ~(DRAMSize - 1); const byte ErasedValueByte = (byte)0xFFu; const ushort ErasedValue = (ushort)0xFFFFu; const uint ErasedValuePair = 0xFFFFFFFFu; // // State // // // Helper Methods // public override unsafe void InitializeStorage() { } //--// public override unsafe bool EraseSectors( UIntPtr addressStart , UIntPtr addressEnd ) { if(ValidateAddress ( addressStart ) && ValidateAddressPlus1( addressEnd ) ) { RT.Memory.Fill( addressStart, addressEnd, ErasedValueByte ); return true; } return false; } public override unsafe bool WriteByte( UIntPtr address , byte val ) { if(ValidateAddress( address )) { byte* ptr = (byte*)address.ToPointer(); *ptr = val; return true; } return false; } public override unsafe bool WriteShort( UIntPtr address , ushort val ) { if(IsOddAddress( address )) { return WriteByte( address, (byte) val ) && WriteByte( Microsoft.Zelig.AddressMath.Increment( address, 1 ), (byte)(val >> 8) ) ; } else { if(ValidateAddress( address )) { ushort* wordAddress = (ushort*)address.ToPointer(); *wordAddress = val; return true; } return false; } } public override bool WriteWord( UIntPtr address , uint val ) { if(IsOddAddress( address )) { return WriteByte ( address, (byte ) val ) && WriteShort( Microsoft.Zelig.AddressMath.Increment( address, 1 ), (ushort)(val >> 8) ) && WriteByte ( Microsoft.Zelig.AddressMath.Increment( address, 3 ), (byte )(val >> 24) ) ; } else { return WriteShort( address, (ushort) val ) && WriteShort( Microsoft.Zelig.AddressMath.Increment( address, 2 ), (ushort)(val >> 16) ) ; } } public override bool Write( UIntPtr address , byte[] buffer , uint offset , uint numBytes ) { if(numBytes > 0) { if(IsOddAddress( address )) { if(WriteByte( address, buffer[offset] ) == false) { return false; } address = Microsoft.Zelig.AddressMath.Increment( address, 1 ); offset += 1; numBytes -= 1; } while(numBytes >= 2) { uint val; val = (uint)buffer[ offset++ ]; val |= (uint)buffer[ offset++ ] << 8; if(WriteShort( address, (ushort)val ) == false) { return false; } address = Microsoft.Zelig.AddressMath.Increment( address, 2 ); numBytes -= 2; } if(numBytes != 0) { if(WriteByte( address, buffer[offset] ) == false) { return false; } } } return true; } //--// public override unsafe byte ReadByte( UIntPtr address ) { if(ValidateAddress( address )) { byte* ptr = (byte*)address.ToPointer(); return ptr[0]; } return ErasedValueByte; } public override unsafe ushort ReadShort( UIntPtr address ) { if(ValidateAddress( address )) { byte* ptr = (byte*)address.ToPointer(); return (ushort)((uint)ptr[0] | (uint)ptr[1] << 8 ); } return ErasedValue; } public override unsafe uint ReadWord( UIntPtr address ) { if(ValidateAddress( address )) { byte* ptr = (byte*)address.ToPointer(); return ((uint)ptr[0] | (uint)ptr[1] << 8 | (uint)ptr[2] << 16 | (uint)ptr[3] << 24 ); } return ErasedValuePair; } public override void Read( UIntPtr address , byte[] buffer , uint offset , uint numBytes ) { while(numBytes != 0) { buffer[offset++] = ReadByte( address ); address = Microsoft.Zelig.AddressMath.Increment( address, 1 ); numBytes--; } } public override void SubstituteFirmware( UIntPtr addressDestination , UIntPtr addressSource , uint numBytes ) { throw new NotImplementedException(); } public override void RebootDevice() { throw new System.NotImplementedException(); } //--// [RT.Inline] static bool ValidateAddress( UIntPtr address ) { if(Zelig.AddressMath.IsLessThan( address, new UIntPtr( DRAMBase ) )) { return false; } if(Zelig.AddressMath.IsGreaterThanOrEqual( address, new UIntPtr( DRAMEnd ) )) { return false; } return true; } [RT.Inline] static bool ValidateAddressPlus1( UIntPtr address ) { if(Zelig.AddressMath.IsLessThanOrEqual( address, new UIntPtr( DRAMBase ) )) { return false; } if(Zelig.AddressMath.IsGreaterThan( address, new UIntPtr( DRAMEnd ) )) { return false; } return true; } [RT.Inline] static bool IsOddAddress( UIntPtr address ) { return Zelig.AddressMath.IsAlignedTo16bits( address ) == false; } } } ================================================ FILE: Zelig/Zelig/RunTime/DeviceModels/iMote2/Properties/AssemblyInfo.cs ================================================ using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; // General Information about an assembly is controlled through the following // set of attributes. Change these attribute values to modify the information // associated with an assembly. [assembly: AssemblyTitle( "Microsoft.iMote2" )] [assembly: AssemblyDescription( "" )] [assembly: AssemblyConfiguration( "" )] [assembly: AssemblyCompany( "Microsoft" )] [assembly: AssemblyProduct( "Microsoft.iMote2" )] [assembly: AssemblyCopyright( "Copyright © Microsoft 2007" )] [assembly: AssemblyTrademark( "" )] [assembly: AssemblyCulture( "" )] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible( false )] //// The following GUID is for the ID of the typelib if this project is exposed to COM //[assembly: Guid( "975a7db2-22e5-41c6-9e32-d3f72152d387" )] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Revision and Build Numbers // by using the '*' as shown below: [assembly: AssemblyVersion( "1.0.0.0" )] [assembly: AssemblyFileVersion( "1.0.0.0" )] ================================================ FILE: Zelig/Zelig/RunTime/DeviceModels/iMote2/SystemServices/GarbageCollectionManager.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // namespace Microsoft.iMote2 { using System; using RT = Microsoft.Zelig.Runtime; using TS = Microsoft.Zelig.Runtime.TypeSystem; public sealed class GarbageCollectionManager : RT.PreciseMarkAndSweepCollector { } } ================================================ FILE: Zelig/Zelig/RunTime/DeviceModels/iMote2/SystemServices/MemoryManager.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // namespace Microsoft.iMote2 { using System; using RT = Microsoft.Zelig.Runtime; using TS = Microsoft.Zelig.Runtime.TypeSystem; public sealed class MemoryManager : RT.LinearMemoryManager { } } ================================================ FILE: Zelig/Zelig/RunTime/DeviceModels/iMote2/SystemServices/SerialPortsManager.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // namespace Microsoft.iMote2 { using System; using RT = Microsoft.Zelig.Runtime; using TS = Microsoft.Zelig.Runtime.TypeSystem; public sealed class SerialPortsManager : Microsoft.DeviceModels.Chipset.PXA27x.Runtime.SerialPortsManager { } } ================================================ FILE: Zelig/Zelig/RunTime/DeviceModels/iMote2/SystemServices/ThreadManager.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // namespace Microsoft.iMote2 { using System; using RT = Microsoft.Zelig.Runtime; using TS = Microsoft.Zelig.Runtime.TypeSystem; using ChipsetModel = Microsoft.DeviceModels.Chipset.PXA27x; public sealed class ThreadManager : ChipsetModel.Runtime.ThreadManager { } } ================================================ FILE: Zelig/Zelig/RunTime/DeviceModels/iMote2/SystemServices/TypeSystemManager.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // namespace Microsoft.iMote2 { using System; using RT = Microsoft.Zelig.Runtime; using TS = Microsoft.Zelig.Runtime.TypeSystem; public sealed class TypeSystemManager : RT.DefaultTypeSystemManager { } } ================================================ FILE: Zelig/Zelig/RunTime/DeviceModels/iMote2/iMote2.csproj ================================================  Debug AnyCPU 9.0.21022 2.0 {186F31A3-EF89-4A25-B2D5-20090606AA01} Library Properties Microsoft.iMote2 Microsoft.iMote2 $(LlilumBuildRoot)\Target\obj\$(MSBuildProjectName)\ v4.5 true full false $(LlilumBuildRoot)\Target\bin\$(Configuration)\ DEBUG;TRACE prompt 4 true true true AllRules.ruleset AnyCPU false pdbonly true $(LlilumBuildRoot)\Target\bin\$(Configuration)\ TRACE prompt 4 true true true AllRules.ruleset AnyCPU false true full false $(LlilumBuildRoot)\Target\bin\$(Configuration)\ true AnyCPU TRACE;DEBUG prompt true true false {186F31A3-EF89-4A25-B2D5-20060501AA01} mscorlib False {186F31A3-EF89-4A25-B2D5-20061218AA01} Common False {186F31A3-EF89-4A25-B2D5-20060509AA01} Kernel False {186F31A3-EF89-4A25-B2D5-20060720AA01} TypeSystem False {186F31A3-EF89-4A25-B2D5-20080519AA01} ModelForPXA27x False 3.5 ================================================ FILE: Zelig/Zelig/RunTime/DeviceModels/iMote2Loader/HardwareModel/Device.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // namespace Microsoft.iMote2Loader { using System; using System.Runtime.CompilerServices; using RT = Microsoft.Zelig.Runtime; using ChipsetModel = Microsoft.DeviceModels.Chipset.PXA27x; public sealed class Device : RT.Device { public override void PreInitializeProcessorAndMemory() { Processor.SetStatusRegister( Processor.c_psr_field_c, Processor.c_psr_I | Processor.c_psr_F | Processor.c_psr_mode_ABORT ); Processor.SetRegister( Processor.Context.RegistersOnStack.StackRegister, this.BootstrapStackPointer ); Processor.SetStatusRegister( Processor.c_psr_field_c, Processor.c_psr_I | Processor.c_psr_F | Processor.c_psr_mode_UNDEF ); Processor.SetRegister( Processor.Context.RegistersOnStack.StackRegister, this.BootstrapStackPointer ); // // Enter System mode, with interrupts disabled. // Processor.SetStatusRegister( Processor.c_psr_field_c, Processor.c_psr_I | Processor.c_psr_F | Processor.c_psr_mode_SYS ); Processor.SetRegister( Processor.Context.RegistersOnStack.StackRegister, this.BootstrapStackPointer ); } public override void MoveCodeToProperLocation() { Memory.Instance.ExecuteImageRelocation(); } } } ================================================ FILE: Zelig/Zelig/RunTime/DeviceModels/iMote2Loader/HardwareModel/Drivers/GPIO.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // namespace Microsoft.iMote2Loader.Drivers { using RT = Microsoft.Zelig.Runtime; using ChipsetModel = Microsoft.DeviceModels.Chipset.PXA27x; public sealed class GPIO : ChipsetModel.Drivers.GPIO { } } ================================================ FILE: Zelig/Zelig/RunTime/DeviceModels/iMote2Loader/HardwareModel/Drivers/I2C.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // namespace Microsoft.iMote2Loader.Drivers { using RT = Microsoft.Zelig.Runtime; using ChipsetModel = Microsoft.DeviceModels.Chipset.PXA27x; public sealed class I2C : ChipsetModel.Drivers.I2C { } } ================================================ FILE: Zelig/Zelig/RunTime/DeviceModels/iMote2Loader/HardwareModel/Drivers/InterruptController.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // namespace Microsoft.iMote2Loader.Drivers { using System; using System.Runtime.CompilerServices; using RT = Microsoft.Zelig.Runtime; using ChipsetModel = Microsoft.DeviceModels.Chipset.PXA27x; public sealed class InterruptController : ChipsetModel.Drivers.InterruptController { } } ================================================ FILE: Zelig/Zelig/RunTime/DeviceModels/iMote2Loader/HardwareModel/Drivers/RealTimeClock.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // namespace Microsoft.iMote2Loader.Drivers { using System; using System.Runtime.CompilerServices; using RT = Microsoft.Zelig.Runtime; using ChipsetModel = Microsoft.DeviceModels.Chipset.PXA27x; public sealed class RealTimeClock : ChipsetModel.Drivers.RealTimeClock { } } ================================================ FILE: Zelig/Zelig/RunTime/DeviceModels/iMote2Loader/HardwareModel/Drivers/SPI.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // namespace Microsoft.iMote2Loader.Drivers { using RT = Microsoft.Zelig.Runtime; using ChipsetModel = Microsoft.DeviceModels.Chipset.PXA27x; public sealed class SPI : ChipsetModel.Drivers.SPI { } } ================================================ FILE: Zelig/Zelig/RunTime/DeviceModels/iMote2Loader/HardwareModel/Memory.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // namespace Microsoft.iMote2Loader { using System; using RT = Microsoft.Zelig.Runtime; using TS = Microsoft.Zelig.Runtime.TypeSystem; public sealed class Memory : RT.Memory { public override void InitializeMemory() { } } } ================================================ FILE: Zelig/Zelig/RunTime/DeviceModels/iMote2Loader/HardwareModel/Peripherals.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // namespace Microsoft.iMote2Loader { using System; using System.Runtime.CompilerServices; using RT = Microsoft.Zelig.Runtime; using TS = Microsoft.Zelig.Runtime.TypeSystem; public sealed class Peripherals : RT.Peripherals { public override void Initialize() { } public override void Activate() { } public override void EnableInterrupt( uint index ) { } public override void DisableInterrupt( uint index ) { } public override void CauseInterrupt() { } public override void WaitForInterrupt() { } public override void ContinueUnderNormalInterrupt( Continuation dlg ) { } public override void ProcessInterrupt() { } public override void ProcessFastInterrupt() { } public override ulong GetPerformanceCounterFrequency() { return 0; } public override unsafe uint ReadPerformanceCounter() { return 0; } } } ================================================ FILE: Zelig/Zelig/RunTime/DeviceModels/iMote2Loader/HardwareModel/Processor.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // namespace Microsoft.iMote2Loader { using System; using RT = Microsoft.Zelig.Runtime; using TS = Microsoft.Zelig.Runtime.TypeSystem; public sealed class Processor : RT.TargetPlatform.ARMv4.ProcessorARMv4 { // // Helper Methods // public override void InitializeProcessor() { } public override UIntPtr GetCacheableAddress( UIntPtr ptr ) { return ptr; } public override UIntPtr GetUncacheableAddress( UIntPtr ptr ) { return ptr; } public override unsafe void FlushCacheLine( UIntPtr target ) { } //--// [RT.Inline] public override RT.Processor.Context AllocateProcessorContext(RT.ThreadImpl owner) { return null; } } } ================================================ FILE: Zelig/Zelig/RunTime/DeviceModels/iMote2Loader/HardwareModel/Storage.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // namespace Microsoft.iMote2Loader { using System; using RT = Microsoft.Zelig.Runtime; using TS = Microsoft.Zelig.Runtime.TypeSystem; public sealed class Storage : RT.Storage { // // Helper Methods // public override void InitializeStorage() { } //--// public override bool EraseSectors( UIntPtr addressStart , UIntPtr addressEnd ) { return false; } public override bool WriteByte( UIntPtr address , byte val ) { return false; } public override bool WriteShort( UIntPtr address , ushort val ) { return false; } public override bool WriteWord( UIntPtr address , uint val ) { return false; } public override bool Write( UIntPtr address , byte[] buffer , uint offset , uint numBytes ) { return false; } //--// public override unsafe byte ReadByte( UIntPtr address ) { return 0; } public override unsafe ushort ReadShort( UIntPtr address ) { return 0; } public override unsafe uint ReadWord( UIntPtr address ) { return 0; } public override void Read( UIntPtr address , byte[] buffer , uint offset , uint numBytes ) { } public override void SubstituteFirmware( UIntPtr addressDestination , UIntPtr addressSource , uint numBytes ) { } public override void RebootDevice() { throw new System.NotImplementedException(); } } } ================================================ FILE: Zelig/Zelig/RunTime/DeviceModels/iMote2Loader/Loader.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // //#define ENABLE_TRACING //#define ENABLE_TRACING_VERBOSE //#define ENABLE_CACHE //#define ENABLE_MMU //#define ENABLE_STACKEDMEMORY //#define ENABLE_ABORTHANDLERS namespace Microsoft.iMote2Loader { using System; using System.Collections.Generic; using RT = Microsoft.Zelig.Runtime; using PXA27x = Microsoft.DeviceModels.Chipset.PXA27x; using ARMv4 = Microsoft.Zelig.Runtime.TargetPlatform.ARMv4; // // Override stock bootstrap code, to avoid including most of the code. // [RT.ExtendClass(typeof(RT.Bootstrap))] public static class BootstrapImpl { [RT.NoInline] [RT.NoReturn] private static void Initialization() { Processor.Instance.InitializeProcessor(); #if ENABLE_CACHE ARMv4.Coprocessor15.InvalidateICache(); ARMv4.Coprocessor15.InvalidateDCache(); // // Enable ICache // ARMv4.Coprocessor15.SetControlRegisterBits( ARMv4.Coprocessor15.c_ControlRegister__ICache ); #endif PXA27x.ClockManager.Instance.InitializeClocks(); #if ENABLE_STACKEDMEMORY PXA27x.MemoryController.Instance.InitializeStackedSDRAM(); PXA27x.MemoryController.Instance.InitializeStackedFLASH(); #endif #if ENABLE_MMU ConfigureMMU(); #endif RT.Configuration.ExecuteApplication(); } #if ENABLE_MMU private static void ConfigureMMU() { ARMv4.MMUv4.ClearTLB(); const uint baseFlash = 0x80000000u; const uint sizeFlash = 0x2000000; ARMv4.MMUv4.AddUncacheableSection( 0, 0 + 256 * 1024, 0x5C000000 ); ARMv4.MMUv4.AddUncacheableSection( 0x5C000000, 0x5C000000 + 256 * 1024, 0x5C000000 ); ARMv4.MMUv4.AddUncacheableSection( baseFlash, baseFlash + sizeFlash, 0 ); ARMv4.MMUv4.EnableTLB(); } #endif #if ENABLE_ABORTHANDLERS static uint fault_DFSR; static uint fault_IFSR; static uint fault_FAR; [RT.NoInline] [RT.NoReturn()] [RT.HardwareExceptionHandler(RT.HardwareException.UndefinedInstruction)] [RT.MemoryUsage(RT.MemoryUsage.Bootstrap)] static void UndefinedInstruction() { fault_DFSR = ARMv4.ProcessorARMv4.MoveFromCoprocessor( 15, 0, 5, 0, 0 ); fault_IFSR = ARMv4.ProcessorARMv4.MoveFromCoprocessor( 15, 0, 5, 0, 1 ); fault_FAR = ARMv4.ProcessorARMv4.MoveFromCoprocessor( 15, 0, 6, 0, 0 ); Processor.Instance.Breakpoint(); } [RT.NoInline] [RT.NoReturn()] [RT.HardwareExceptionHandler(RT.HardwareException.PrefetchAbort)] [RT.MemoryUsage(RT.MemoryUsage.Bootstrap)] static void PrefetchAbort() { fault_DFSR = ARMv4.ProcessorARMv4.MoveFromCoprocessor( 15, 0, 5, 0, 0 ); fault_IFSR = ARMv4.ProcessorARMv4.MoveFromCoprocessor( 15, 0, 5, 0, 1 ); fault_FAR = ARMv4.ProcessorARMv4.MoveFromCoprocessor( 15, 0, 6, 0, 0 ); Processor.Instance.Breakpoint(); } [RT.NoInline] [RT.NoReturn()] [RT.HardwareExceptionHandler(RT.HardwareException.DataAbort)] [RT.MemoryUsage(RT.MemoryUsage.Bootstrap)] static void DataAbort() { fault_DFSR = ARMv4.ProcessorARMv4.MoveFromCoprocessor( 15, 0, 5, 0, 0 ); fault_IFSR = ARMv4.ProcessorARMv4.MoveFromCoprocessor( 15, 0, 5, 0, 1 ); fault_FAR = ARMv4.ProcessorARMv4.MoveFromCoprocessor( 15, 0, 6, 0, 0 ); Processor.Instance.Breakpoint(); } #endif } [RT.ExtendClass(typeof(RT.TypeSystemManager),NoConstructors=true)] public class TypeSystemManagerImpl { public void DeliverException( Exception obj ) { } } class Loader { const uint cmd_Signature = 0xDEADC000; const uint cmd_Mask = 0xFFFFFF00; const byte cmd_Hello = 0x01; const byte cmd_EnterCFI = 0x02; // Arg: Address const byte cmd_ExitCFI = 0x03; // Arg: Address const byte cmd_ReadMemory8 = 0x04; // Arg: Address, Size => values const byte cmd_ReadMemory16 = 0x05; // Arg: Address, Size => values const byte cmd_ReadMemory32 = 0x06; // Arg: Address, Size => values const byte cmd_ChecksumMemory = 0x07; // Arg: Address, Size => CRC value, AND of all memory const byte cmd_EraseSector = 0x08; // Arg: Address => Status value const byte cmd_ProgramMemory = 0x09; // Arg: Address, Size, [32bits words] => Status value const byte cmd_EndOfStream = 0xFF; const uint FlashSize = 32 * 1024 * 1024; const uint FlashMask = ~(FlashSize - 1); const uint baseIRAM = 0x5C000000; const uint blockSize = 64 * 1024; const uint baseHostToDevice = baseIRAM + blockSize * 1; const uint baseDeviceToHost = baseIRAM + blockSize * 2; //--// static unsafe uint* s_ptrInput; static unsafe uint* s_ptrOutput; //--// [RT.DisableNullChecks()] static unsafe void EnterCFI( ushort* baseAddress ) { PXA27x.StackedFlashChip.EnterCFI( baseAddress ); } [RT.DisableNullChecks()] static unsafe void ExitCFI( ushort* baseAddress ) { PXA27x.StackedFlashChip.ExitCFI( baseAddress ); } [RT.DisableNullChecks()] static unsafe void EraseSector( ushort* sectorStart ) { PXA27x.StackedFlashChip.UnlockFlashSector( sectorStart ); PXA27x.StackedFlashChip.EraseFlashSector ( sectorStart ); } [RT.DisableNullChecks()] static unsafe void WriteWord( ushort* address , ushort value ) { PXA27x.StackedFlashChip.UnlockFlashSector( address ); PXA27x.StackedFlashChip.ProgramFlashWord ( address, value ); } //--// static unsafe void RewindAndWait( bool fSetMarker ) { s_ptrInput = (uint*)baseHostToDevice; s_ptrOutput = (uint*)baseDeviceToHost; if(fSetMarker) { *s_ptrOutput = cmd_Signature | cmd_EndOfStream; } System.Diagnostics.Debugger.Break(); } static unsafe uint ReadInput() { return *s_ptrInput++; } static unsafe void WriteOutput( uint val ) { *s_ptrOutput++ = val; } //--// [System.Diagnostics.Conditional( "ENABLE_TRACING" )] static void DebugInitialize() { PXA27x.UART.Instance.Configure( PXA27x.UART.Id.STUART, 115200 ); } [System.Diagnostics.Conditional( "ENABLE_TRACING" )] static void DebugPrint( string text ) { PXA27x.UART.Instance.Ports[(int)PXA27x.UART.Id.STUART].DEBUG_WriteLine( text ); } [System.Diagnostics.Conditional( "ENABLE_TRACING" )] static void DebugPrint( string text , uint value ) { PXA27x.UART.Instance.Ports[(int)PXA27x.UART.Id.STUART].DEBUG_WriteLine( text, value ); } [System.Diagnostics.Conditional( "ENABLE_TRACING_VERBOSE" )] static void DebugPrintVerbose( string text , uint value ) { DebugPrint( text, value ); } [System.Diagnostics.Conditional( "ENABLE_TRACING" )] static void DebugChar( char c ) { PXA27x.UART.Instance.Ports[(int)PXA27x.UART.Id.STUART].DEBUG_Write( c ); } //--// [RT.DisableNullChecks( ApplyRecursively=true )] static unsafe void Main() { //// var clockControl = PXA27x.ClockManager.Instance; //// //// clockControl.CKEN.EnOsTimer = true; //// //// //--// //// //// var timer = PXA27x.OSTimers.Instance; //// //// uint* ptr2 = (uint*)0xA0000000; //// //// uint last = timer.ReadCounter( 0 ); //// uint last2 = timer.ReadCounter( 0 ); //// //// for(uint i = 0; i < 1024; i++) //// { //// uint sum = 0; //// //// for(int j = 0; j < 1024 * 16; j++) //// { //// sum += last; //// } //// //// uint val = timer.ReadCounter( 0 ); //// ptr2[i] = val - last2; //// last2 = val; //// //// last = sum; //// } DebugInitialize(); DebugPrint( "Hello World!\r\n" ); RewindAndWait( true ); while(true) { DebugPrint( "Waiting..." ); uint cmd = ReadInput(); DebugPrint( "Got data: ", cmd ); if((cmd & cmd_Mask) == cmd_Signature) { DebugPrint( "Got command: ", cmd ); switch((byte)cmd) { case cmd_EndOfStream: WriteOutput( cmd ); RewindAndWait( false ); break; case cmd_Hello: WriteOutput( cmd ); break; case cmd_EnterCFI: EnterCFI( (ushort*)ReadInput() ); WriteOutput( cmd ); break; case cmd_ExitCFI: ExitCFI( (ushort*)ReadInput() ); WriteOutput( cmd ); break; case cmd_ReadMemory8: { byte* ptr = (byte*)ReadInput(); uint len = ReadInput(); WriteOutput( cmd ); while(len > 0) { WriteOutput( *ptr++ ); len--; } } break; case cmd_ReadMemory16: { ushort* ptr = (ushort*)ReadInput(); uint len = ReadInput(); DebugPrint( "Address: ", (uint)ptr ); DebugPrint( "Length: ", len ); WriteOutput( cmd ); while(len > 0) { DebugPrint( "Data: ", (uint)*ptr ); WriteOutput( *ptr++ ); len--; } DebugPrint( "Done." ); } break; case cmd_ReadMemory32: { uint* ptr = (uint*)ReadInput(); uint len = ReadInput(); DebugPrint( "Address: ", (uint)ptr ); DebugPrint( "Length: ", len ); WriteOutput( cmd ); while(len > 0) { DebugPrint( "Data: ", (uint)*ptr ); WriteOutput( *ptr++ ); len--; } DebugPrint( "Done." ); } break; case cmd_ChecksumMemory: { uint* ptr = (uint*)ReadInput(); uint len = ReadInput(); uint sum = 0; uint and = 0xFFFFFFFF; WriteOutput( cmd ); DebugPrint( "Address: ", (uint)ptr ); DebugPrint( "Length: ", len ); while(len > 0) { uint val = *ptr; sum = ((sum & 1) << 31) | (sum >> 1); sum += val; and &= val; ptr++; len--; } DebugPrint( "Sum: ", sum ); DebugPrint( "And: ", and ); WriteOutput( sum ); WriteOutput( and ); } break; case cmd_EraseSector: EraseSector( (ushort*)ReadInput() ); WriteOutput( cmd ); WriteOutput( 0 ); break; case cmd_ProgramMemory: { ushort* ptr = (ushort*)ReadInput(); uint len = ReadInput(); WriteOutput( cmd ); while(len > 0) { if(len >= 16) { PXA27x.StackedFlashChip.UnlockFlashSector ( ptr ); PXA27x.StackedFlashChip.StartBufferedProgramFlashWord( ptr, 32 ); for(int i = 0; i < 16; i++) { uint val = ReadInput(); PXA27x.StackedFlashChip.AddBufferedProgramFlashWord( ptr++, (ushort) val ); PXA27x.StackedFlashChip.AddBufferedProgramFlashWord( ptr++, (ushort)(val >> 16) ); DebugPrintVerbose( "Program Data: ", val ); } PXA27x.StackedFlashChip.ConfirmProgramFlashWord( ptr - 32 ); len -= 16; } else { uint val = ReadInput(); WriteWord( ptr++, (ushort) val ); WriteWord( ptr++, (ushort)(val >> 16) ); len--; } } WriteOutput( 0 ); } break; } } } } } } ================================================ FILE: Zelig/Zelig/RunTime/DeviceModels/iMote2Loader/Properties/AssemblyInfo.cs ================================================ using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; // General Information about an assembly is controlled through the following // set of attributes. Change these attribute values to modify the information // associated with an assembly. [assembly: AssemblyTitle( "Microsoft.iMote2Loader" )] [assembly: AssemblyDescription( "" )] [assembly: AssemblyConfiguration( "" )] [assembly: AssemblyCompany( "Microsoft" )] [assembly: AssemblyProduct( "Microsoft.iMote2Loader" )] [assembly: AssemblyCopyright( "Copyright © Microsoft 2007" )] [assembly: AssemblyTrademark( "" )] [assembly: AssemblyCulture( "" )] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible( false )] //// The following GUID is for the ID of the typelib if this project is exposed to COM //[assembly: Guid( "975a7db2-22e5-41c6-9e32-d3f72152d387" )] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Revision and Build Numbers // by using the '*' as shown below: [assembly: AssemblyVersion( "1.0.0.0" )] [assembly: AssemblyFileVersion( "1.0.0.0" )] ================================================ FILE: Zelig/Zelig/RunTime/DeviceModels/iMote2Loader/iMote2Loader.csproj ================================================  Debug AnyCPU 9.0.21022 2.0 {186F31A3-EF89-4A25-B2D5-20080606AA02} Exe Properties Microsoft.iMote2Loader Microsoft.iMote2Loader $(LlilumBuildRoot)\Target\obj\$(MSBuildProjectName)\ v4.5 true full false $(LlilumBuildRoot)\Target\bin\$(Configuration)\ DEBUG;TRACE prompt 4 true true true AllRules.ruleset AnyCPU false pdbonly true $(LlilumBuildRoot)\Target\bin\$(Configuration)\ TRACE prompt 4 true true true AllRules.ruleset AnyCPU false $(LlilumBuildRoot)\Target\bin\$(Configuration)\ TRACE;DEBUG AnyCPU true true true false {186F31A3-EF89-4A25-B2D5-20060501AA01} mscorlib False {186F31A3-EF89-4A25-B2D5-20070702AA01} system False {186F31A3-EF89-4A25-B2D5-20061218AA01} Common False {186F31A3-EF89-4A25-B2D5-20060509AA01} Kernel False {186F31A3-EF89-4A25-B2D5-20060720AA01} TypeSystem False {186F31A3-EF89-4A25-B2D5-20080519AA01} ModelForPXA27x False 3.5 ================================================ FILE: Zelig/Zelig/RunTime/DeviceModels/iMote2Tester/Properties/AssemblyInfo.cs ================================================ using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; // General Information about an assembly is controlled through the following // set of attributes. Change these attribute values to modify the information // associated with an assembly. [assembly: AssemblyTitle( "iMote2Tester" )] [assembly: AssemblyDescription( "" )] [assembly: AssemblyConfiguration( "" )] [assembly: AssemblyCompany( "Microsoft" )] [assembly: AssemblyProduct( "iMote2Tester" )] [assembly: AssemblyCopyright( "Copyright © Microsoft 2007" )] [assembly: AssemblyTrademark( "" )] [assembly: AssemblyCulture( "" )] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. //[assembly: ComVisible( false )] // The following GUID is for the ID of the typelib if this project is exposed to COM //[assembly: Guid( "790c97c2-f14c-473e-a9eb-1b72d95bad30" )] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // [assembly: AssemblyVersion( "1.0.0.0" )] [assembly: AssemblyFileVersion( "1.0.0.0" )] ================================================ FILE: Zelig/Zelig/RunTime/DeviceModels/iMote2Tester/Tester.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // //#define TEST_SERIAL //#define TEST_LED #define TEST_I2C namespace Microsoft.iMote2Tester { using System; using System.IO.Ports; using System.Collections.Generic; using System.Runtime.CompilerServices; using RT = Microsoft.Zelig.Runtime; using TS = Microsoft.Zelig.Runtime.TypeSystem; using Chipset = Microsoft.DeviceModels.Chipset.PXA27x; using Microsoft.iMote2Tester.UnitTests; unsafe class Tester { static void Main() { ITest unitTest; #if TEST_SERIAL unitTest = new SerialTests(); unitTest.Prepare(); unitTest.Run(); Console.WriteLine("Test " + (unitTest.Success ? "Succeeded" : "FAILED") + ", with result: " + unitTest.Result); #endif #if TEST_LED unitTest = new LEDTests(); unitTest.Prepare(); unitTest.Run(); Console.WriteLine("Test " + (unitTest.Success ? "Succeeded" : "FAILED") + ", with result: " + unitTest.Result); #endif #if TEST_I2C unitTest = new I2CBusTests(); unitTest.Prepare(); unitTest.Run(); Console.WriteLine("Test " + (unitTest.Success ? "Succeeded" : "FAILED") + ", with result: " + unitTest.Result); #endif } } } ================================================ FILE: Zelig/Zelig/RunTime/DeviceModels/iMote2Tester/UnitTests/I2C.Tests.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // namespace Microsoft.iMote2Tester.UnitTests { using System; using System.IO.Ports; using System.Collections.Generic; using System.Runtime.CompilerServices; using RT = Microsoft.Zelig.Runtime; using TS = Microsoft.Zelig.Runtime.TypeSystem; using Chipset = Microsoft.DeviceModels.Chipset.PXA27x; using Microsoft.DeviceModels.Chipset.PXA27x.Drivers; /// /// Unit Tests for the I2C subsystem /// public class I2CBusTests : ITest { #region Scan Bus test /// /// scan bus test /// public void TestCase1() { int found = 0; ushort startFrom = 0; int clockRateKHz = 400; I2CDevice.Configuration config = new I2CDevice.Configuration(startFrom, clockRateKHz); using (I2CDevice i2cDevice = new I2CDevice(config)) { bool found34, found49, found4a; found34 = found49 = found4a = false; //keep out 0 and 127) for (int i = 1; i < 126; i++) { i2cDevice.Config = new I2CDevice.Configuration((ushort)(1 + ((i + startFrom) % 126)), 400); I2CDevice.I2CTransaction unit1 = i2cDevice.CreateReadTransaction(new byte[] { 0 }); int len = i2cDevice.Execute(new I2CDevice.I2CTransaction[] { unit1 }, 200); if (len > 0) { ASSERT(len == 1, true, "not all data sent"); found34 |= (i2cDevice.Config.Address == 0x34); found49 |= (i2cDevice.Config.Address == 0x49); found4a |= (i2cDevice.Config.Address == 0x4a); found++; } else { ASSERT(len < 0, false, "illegal return value for execute"); } } ASSERT(found == 3, true, "more devices than expected"); ASSERT(found34, true, "device 0x34 not found"); ASSERT(found49, true, "device 0x49 not found"); ASSERT(found4a, true, "device 0x4a not found"); } } #endregion #region Write config data to AD converter /// /// scan bus test /// public void TestCase2() { I2CDevice.Configuration config = new I2CDevice.Configuration(0x34, 400); using (I2CDevice i2cDevice = new I2CDevice(config)) { I2CDevice.I2CTransaction unit1 = i2cDevice.CreateWriteTransaction(new byte[] { 0, 0 }); int len = i2cDevice.Execute(new I2CDevice.I2CTransaction[] { unit1 }, 200); ASSERT(len > 0, true, "not all data sent"); ASSERT(len == 2, true, "illegal return value for execute"); } } #endregion #region Read channel data from AD converter /// /// scan bus test /// public void TestCase3() { I2CDevice.Configuration config = new I2CDevice.Configuration(0x34, 400); using (I2CDevice i2cDevice = new I2CDevice(config)) { I2CDevice.I2CTransaction unit1 = i2cDevice.CreateReadTransaction(new byte[] { 0, 0, 0, 0 }); int len = i2cDevice.Execute(new I2CDevice.I2CTransaction[] { unit1 }, 200); ASSERT(len > 0, true, "not all data sent"); ASSERT(len == 4, true, "illegal return value for execute"); bool dataOk = false; for (int i = 0; i < unit1.Buffer.Length; i++) { dataOk |= (unit1.Buffer[i] != 0); } ASSERT(dataOk, true, "no data from converter"); } } #endregion #region check for illegal data /// /// scan bus test /// public void TestCase4() { I2CDevice.Configuration config = new I2CDevice.Configuration(0x34, 400); using (I2CDevice i2cDevice = new I2CDevice(config)) { try { i2cDevice.CreateReadTransaction(null); ASSERT(true, false, "illegal data"); } catch { //expected } try { i2cDevice.CreateWriteTransaction(null); ASSERT(true, false, "illegal data"); } catch { //expected } try { int len = i2cDevice.Execute(null, 200); ASSERT(true, false, "illegal data"); } catch { //expected } try { int len = i2cDevice.Execute(new I2CDevice.I2CTransaction[0], 200); ASSERT(len == 0, true, "illegal data"); } catch { ASSERT(true, false, "illegal data"); } } } #endregion #region ITest Members private bool m_success = true; private int assertionId = 0; /// /// if true, test completed with no error /// public bool Success { get { return m_success; } } /// /// checks that an object is not null /// /// /// public void ASSERT_NOT_NULL(object o, String failureMessage) { assertionId++; if (null == o) { Result += "\r\n# " + assertionId + " Object : " + failureMessage; m_success = false; } } /// /// checks that a condition is met /// /// /// /// public void ASSERT(bool current, bool expected, String failureMessage) { assertionId++; if (current != expected) { Result += "\r\n#" + assertionId + " " + current + "!=" + expected + "(expected): " + failureMessage; m_success = false; } } /// /// Prepares the output port test case /// public void Prepare() { Result = ""; } /// /// Executes the output port test case /// public void Run() { try { TestCase1(); } catch { ASSERT_NOT_NULL(null, "test case 1 - "); } try { TestCase2(); } catch { ASSERT_NOT_NULL(null, "test case 2 - "); } try { TestCase3(); } catch { ASSERT_NOT_NULL(null, "test case 3 - "); } try { TestCase4(); } catch { ASSERT_NOT_NULL(null, "test case 4 - "); } } /// /// Retrieves the results of the output port test case /// public string Result { get; private set; } #endregion } #region Test helper classes public class I2CDevice : IDisposable { #region Constructor/Destructor public I2CDevice(I2CDevice.Configuration config) { this.Config = config; } public void Dispose() { this.Dispose(true); GC.SuppressFinalize(this); } protected virtual void Dispose(bool fDisposing) { } #endregion #region Public API public Configuration Config; public int Execute(I2CDevice.I2CTransaction[] xActions, int timeout) { if (Config.Address == Microsoft.DeviceModels.Chipset.PXA27x.I2C.Instance.ISAR) return -1;// throw new ArgumentOutOfRangeException("Config.Address"); if (null == xActions) throw new ArgumentNullException("xActions"); if (0 == xActions.Length) return 0; I2CBus_Transaction action = new I2CBus_Transaction(Config.Address, Config.ClockRateKhz, xActions); I2C.Instance.StartTransactionAsMaster(action); if (!action.WaitForCompletion(timeout)) { I2C.Instance.StopTransactionAsMaster(); return 0; } return action.BytesTransacted; } public I2CDevice.I2CReadTransaction CreateReadTransaction(byte[] buffer) { return new I2CReadTransaction(buffer); } public I2CDevice.I2CWriteTransaction CreateWriteTransaction(byte[] buffer) { return new I2CWriteTransaction(buffer); } #endregion #region Nested classes public sealed class I2CReadTransaction : I2CTransaction { internal I2CReadTransaction(byte[] buffer) : base(true, buffer) { } } public sealed class I2CWriteTransaction : I2CTransaction { internal I2CWriteTransaction(byte[] buffer) : base(false, buffer) { } } public class I2CTransaction : I2CBus_TransactionUnit { internal I2CTransaction(bool isReadTransaction, byte[] buffer) : base(isReadTransaction, buffer) { } } public class Configuration { public readonly ushort Address; public readonly int ClockRateKhz; public Configuration(ushort address, int clockRateKhz) { this.Address = address; this.ClockRateKhz = clockRateKhz; } } #endregion } #endregion } ================================================ FILE: Zelig/Zelig/RunTime/DeviceModels/iMote2Tester/UnitTests/LED.Tests.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // namespace Microsoft.iMote2Tester.UnitTests { using System; using System.IO.Ports; using System.Collections.Generic; using System.Runtime.CompilerServices; using RT = Microsoft.Zelig.Runtime; using TS = Microsoft.Zelig.Runtime.TypeSystem; using Chipset = Microsoft.DeviceModels.Chipset.PXA27x; using Microsoft.DeviceModels.Chipset.PXA27x.Drivers; /// /// Unit Tests for the LEDs /// public class LEDTests : ITest { #region Generic LED tests /// /// LED test /// public void TestCase1() { Chipset.PowerManager.Instance.ReleaseReadDisableHold(); var gpio = Chipset.GPIO.Instance; gpio.EnableAsOutputPin(103, false); gpio.EnableAsOutputPin(104, false); gpio.EnableAsOutputPin(105, false); bool state = true; for (int i = 0; i < 100; i++) { System.Threading.Thread.Sleep(500); gpio[103] = state; ASSERT(gpio[103] == state, true, "wrong setting"); System.Threading.Thread.Sleep(500); gpio[104] = state; ASSERT(gpio[104] == state, true, "wrong setting"); System.Threading.Thread.Sleep(500); gpio[105] = state; ASSERT(gpio[105] == state, true, "wrong setting"); state = !state; } state = true; gpio[103] = state; gpio[104] = state; gpio[105] = state; ASSERT(gpio[103] == state, true, "wrong setting"); ASSERT(gpio[104] == state, true, "wrong setting"); ASSERT(gpio[105] == state, true, "wrong setting"); } #endregion #region ITest Members private bool m_success = true; private int assertionId = 0; /// /// if true, test completed with no error /// public bool Success { get { return m_success; } } /// /// checks that an object is not null /// /// /// public void ASSERT_NOT_NULL(object o, String failureMessage) { assertionId++; if (null == o) { Result += "\r\n# " + assertionId + " Object : " + failureMessage; m_success = false; } } /// /// checks that a condition is met /// /// /// /// public void ASSERT(bool current, bool expected, String failureMessage) { assertionId++; if (current != expected) { Result += "\r\n#" + assertionId + " " + current + "!=" + expected + "(expected): " + failureMessage; m_success = false; } } /// /// Prepares the output port test case /// public void Prepare() { Result = ""; } /// /// Executes the output port test case /// public void Run() { try { TestCase1(); } catch { ASSERT_NOT_NULL(null, "test case 1 - "); } } /// /// Retrieves the results of the output port test case /// public string Result { get; private set; } #endregion } } ================================================ FILE: Zelig/Zelig/RunTime/DeviceModels/iMote2Tester/UnitTests/Serial.Tests.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // namespace Microsoft.iMote2Tester.UnitTests { using System; using System.IO.Ports; using System.Collections.Generic; using System.Runtime.CompilerServices; using RT = Microsoft.Zelig.Runtime; using TS = Microsoft.Zelig.Runtime.TypeSystem; using Chipset = Microsoft.DeviceModels.Chipset.PXA27x; using Microsoft.DeviceModels.Chipset.PXA27x.Drivers; /// /// Unit Tests for the I2C subsystem /// public class SerialTests : ITest { #region Generic Serial tests /// /// serial port test /// public void TestCase1() { var port = new SerialPort("STUART"); port.BaudRate = 9600; port.Parity = Parity.None; port.DataBits = 8; port.StopBits = StopBits.One; port.ReadTimeout = SerialPort.InfiniteTimeout; port.WriteTimeout = SerialPort.InfiniteTimeout; port.Open(); port.Write("Hello World!"); byte[] writeBuf = new byte[1]; for (int i = 0; i < 100; i++) { var stopwatch = new System.Diagnostics.Stopwatch(); stopwatch.Start(); const int total = 32 * 1024; int ch = 0; for (int j = 0; j < total; j++) { writeBuf[0] = (byte)(48 + ch); port.Write(writeBuf, 0, 1); ch = (ch + 1) % 32; } stopwatch.Stop(); port.Write("\r\n"); port.Write("\r\n"); port.Write(string.Format("Took {0} to send {1} bytes", stopwatch.ElapsedMilliseconds, total)); //// byte[] buf = new byte[64]; //// //// while(true) //// { //// for(int i = 0; i < 64; i++) //// { //// buf[i] = port.Read(); //// } //// //// //port.Write( (byte)'>' ); //// for(int i = 0; i < 64; i++) //// { //// port.Write( buf[i] ); //// } //// //port.Write( (byte)'<' ); //// } //// //// GC.Collect(); } } #endregion #region ITest Members private bool m_success = true; private int assertionId = 0; /// /// if true, test completed with no error /// public bool Success { get { return m_success; } } /// /// checks that an object is not null /// /// /// public void ASSERT_NOT_NULL(object o, String failureMessage) { assertionId++; if (null == o) { Result += "\r\n# " + assertionId + " Object : " + failureMessage; m_success = false; } } /// /// checks that a condition is met /// /// /// /// public void ASSERT(bool current, bool expected, String failureMessage) { assertionId++; if (current != expected) { Result += "\r\n#" + assertionId + " " + current + "!=" + expected + "(expected): " + failureMessage; m_success = false; } } /// /// Prepares the output port test case /// public void Prepare() { Result = ""; } /// /// Executes the output port test case /// public void Run() { try { TestCase1(); } catch { ASSERT_NOT_NULL(null, "test case 1 - "); } } /// /// Retrieves the results of the output port test case /// public string Result { get; private set; } #endregion } } ================================================ FILE: Zelig/Zelig/RunTime/DeviceModels/iMote2Tester/UnitTests/UnitTest.Interface.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // namespace Microsoft.iMote2Tester.UnitTests { using System; using System.IO.Ports; using System.Collections.Generic; using System.Runtime.CompilerServices; using RT = Microsoft.Zelig.Runtime; using TS = Microsoft.Zelig.Runtime.TypeSystem; using Chipset = Microsoft.DeviceModels.Chipset.PXA27x; /// /// common interface for the test cases /// public interface ITest { /// /// prepares the test case /// void Prepare(); /// /// executes the test case /// void Run(); /// /// retrieves the results of the test case /// String Result { get; } /// /// if true, test completed with no error /// bool Success { get; } } } ================================================ FILE: Zelig/Zelig/RunTime/DeviceModels/iMote2Tester/iMote2Tester.csproj ================================================  Debug AnyCPU 9.0.21022 2.0 {186F31A3-EF89-4A25-B2D5-20080630AA01} Exe Properties Microsoft.iMote2Tester Microsoft.iMote2Tester $(LlilumBuildRoot)\Target\obj\$(MSBuildProjectName)\ v4.5 true full false $(LlilumBuildRoot)\Target\bin\$(Configuration)\ DEBUG;TRACE prompt 4 true true true AllRules.ruleset AnyCPU false pdbonly true $(LlilumBuildRoot)\Target\bin\$(Configuration)\ TRACE prompt 4 true true true AllRules.ruleset AnyCPU false true full false $(LlilumBuildRoot)\Target\bin\$(Configuration)\ TRACE;DEBUG AnyCPU true true true false {186F31A3-EF89-4A25-B2D5-20060501AA01} mscorlib False {186F31A3-EF89-4A25-B2D5-20070702AA01} system False {186F31A3-EF89-4A25-B2D5-20061218AA01} Common False {186F31A3-EF89-4A25-B2D5-20060509AA01} Kernel False {186F31A3-EF89-4A25-B2D5-20090606AA01} iMote2 False {186F31A3-EF89-4A25-B2D5-20080519AA01} ModelForPXA27x False 3.5 ================================================ FILE: Zelig/Zelig/RunTime/DeviceModels/lwIP/Microsoft.Llilum.Lwip.csproj ================================================  Debug AnyCPU 9.0.21022 2.0 {E77AC86E-58AB-47B6-BC6D-3C1B4545CDFD} Library Properties Microsoft.Llilum.Lwip Microsoft.Llilum.Lwip $(LlilumBuildRoot)\Target\obj\$(MSBuildProjectName)\ v4.5 true full false $(LlilumBuildRoot)\Target\bin\$(Configuration)\ DEBUG;TRACE prompt 4 true true true AllRules.ruleset AnyCPU false pdbonly true $(LlilumBuildRoot)\Target\bin\$(Configuration)\ TRACE prompt 4 true true true AllRules.ruleset AnyCPU false true full false $(LlilumBuildRoot)\Target\bin\$(Configuration)\ true AnyCPU DEBUG;TRACE true true false {186F31A3-EF89-4A25-B2D5-20060501AA01} mscorlib False {186F31A3-EF89-4A25-B2D5-20070702AA01} system False {186F31A3-EF89-4A25-B2D5-20061218AA01} Common False {186F31A3-EF89-4A25-B2D5-20060509AA01} Kernel False {186F31A3-EF89-4A25-B2D5-20060720AA01} TypeSystem False {20DC2CF5-8EED-4231-9743-6BAB96BE465C} LlilumOSAbstraction {93219A45-914C-44B7-A6CB-66849879C8B1} LlilumCMSIS-RTOS {93219a45-914c-44b7-a6cb-66849879c8b1} LlilumCMSIS-RTOS 3.5 ================================================ FILE: Zelig/Zelig/RunTime/DeviceModels/lwIP/NetworkInterface.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // namespace Microsoft.Llilum.Lwip { using System; using System.Collections; using System.Threading; using Microsoft.Zelig.Runtime; public enum NetworkInterfaceType { Unknown = 1, Ethernet = 6, Wireless80211 = 71, } public class NetworkInterface { //set update flags... private const int UPDATE_FLAGS_DNS = 0x1; private const int UPDATE_FLAGS_DHCP = 0x2; private const int UPDATE_FLAGS_DHCP_RENEW = 0x4; private const int UPDATE_FLAGS_DHCP_RELEASE = 0x8; private const int UPDATE_FLAGS_MAC = 0x10; //--// private const uint FLAGS_DHCP = 0x1; private const uint FLAGS_DYNAMIC_DNS = 0x2; //--// private static NetworkInterface s_netInterface = new NetworkInterface(0); //--// private readonly int m_interfaceIndex; private uint m_flags; private uint m_ipAddress; private uint m_gatewayAddress; private uint m_subnetMask; private NetworkInterfaceType m_networkInterfaceType; private byte[] m_macAddress; //private uint _dnsAddress1; //privae uint _dnsAddress2; //--// internal NetworkInterface( int interfaceIndex ) { this.m_interfaceIndex = interfaceIndex; m_networkInterfaceType = NetworkInterfaceType.Unknown; } public static NetworkInterface[ ] GetAllNetworkInterfaces( ) { int count = GetNetworkInterfaceCount(); NetworkInterface[] ifaces = new NetworkInterface[count]; for(uint i = 0; i < count; i++) { ifaces[ i ] = GetNetworkInterface( i ); } return ifaces; } private static NetworkInterface GetNetworkInterface( uint interfaceIndex ) { if(interfaceIndex >= GetNetworkInterfaceCount( )) { throw new ArgumentOutOfRangeException( nameof( interfaceIndex ) ); } return s_netInterface; } public static int GetNetworkInterfaceCount( ) { return NetworkInterfaceProvider.Instance.GetNetworkInterfaceCount( ); } public void InitializeNetworkInterfaceSettings( NetworkInterface netInterface ) { netInterface.IPAddress = NetworkInterfaceProvider.Instance.GetIPAddress( ); netInterface.GatewayAddress = NetworkInterfaceProvider.Instance.GetGatewayAddress( ); netInterface.SubnetMask = NetworkInterfaceProvider.Instance.GetMask( ); } public void UpdateConfiguration( NetworkInterface netInterface, int updateType ) { var ni = NetworkInterfaceProvider.Instance; // Handle only DHCP updates for now if(updateType == 0x2) { ni.Disconnect( ); if(netInterface.IsDhcpEnabled) { ni.InitializeEthernet( ); } else { ni.InitializeEthernet( netInterface.IPAddress, netInterface.SubnetMask, netInterface.GatewayAddress ); } // // After initialization is complete, we need to remap all interrupts // to the safe LLILUM wrapper // ni.RemapInterrupts( ); ni.Connect( 15000 ); } } public static uint IPv4AddressFromString( string ipAddress ) { return NetworkInterfaceProvider.Instance.IPv4AddressFromString( ipAddress ); } private string IPv4AddressToString( uint ipAddress ) { return string.Concat( ((ipAddress >> 0) & 0xFF).ToString( ), ".", ((ipAddress >> 8) & 0xFF).ToString( ), ".", ((ipAddress >> 16) & 0xFF).ToString( ), ".", ((ipAddress >> 24) & 0xFF).ToString( ) ); } public void EnableStaticIP( string ipAddress, string subnetMask, string gatewayAddress ) { try { m_ipAddress = IPv4AddressFromString( ipAddress ); m_subnetMask = IPv4AddressFromString( subnetMask ); m_gatewayAddress = IPv4AddressFromString( gatewayAddress ); m_flags &= ~FLAGS_DHCP; UpdateConfiguration( this, UPDATE_FLAGS_DHCP ); } finally { ReloadSettings( ); } } public void EnableDhcp( ) { try { m_flags |= FLAGS_DHCP; UpdateConfiguration( this, UPDATE_FLAGS_DHCP ); } finally { ReloadSettings( ); } } public void EnableStaticDns( string[ ] dnsAddresses ) { throw new NotImplementedException( ); //if (dnsAddresses == null || dnsAddresses.Length == 0 || dnsAddresses.Length > 2) //{ // throw new ArgumentException(); //} //uint[] addresses = new uint[2]; //int iAddress = 0; //for (int i = 0; i < dnsAddresses.Length; i++) //{ // uint address = IPAddressFromString(dnsAddresses[i]); // addresses[iAddress] = address; // if (address != 0) // { // iAddress++; // } //} //try //{ // _dnsAddress1 = addresses[0]; // _dnsAddress2 = addresses[1]; // _flags &= ~FLAGS_DYNAMIC_DNS; // UpdateConfiguration(this, UPDATE_FLAGS_DNS); //} //finally //{ // ReloadSettings(); //} } public void EnableDynamicDns( ) { throw new NotImplementedException( ); //try //{ // _flags |= FLAGS_DYNAMIC_DNS; // UpdateConfiguration(this, UPDATE_FLAGS_DNS); //} //finally //{ // ReloadSettings(); //} } public string IPAddress { get { return IPv4AddressToString( m_ipAddress ); } internal set { m_ipAddress = IPv4AddressFromString( value ); } } public string GatewayAddress { get { return IPv4AddressToString( m_gatewayAddress ); } internal set { m_gatewayAddress = IPv4AddressFromString( value ); } } public string SubnetMask { get { return IPv4AddressToString( m_subnetMask ); } internal set { m_subnetMask = IPv4AddressFromString( value ); } } public bool IsDhcpEnabled { get { return (m_flags & FLAGS_DHCP) != 0; } } public bool IsDynamicDnsEnabled { get { return (m_flags & FLAGS_DYNAMIC_DNS) != 0; } } public string[ ] DnsAddresses { get { ArrayList list = new ArrayList(); //if (_dnsAddress1 != 0) //{ // list.Add(IPAddressToString(_dnsAddress1)); //} //if (_dnsAddress2 != 0) //{ // list.Add(IPAddressToString(_dnsAddress2)); //} return (string[ ])list.ToArray( typeof( string ) ); } } private void ReloadSettings( ) { Thread.Sleep( 100 ); InitializeNetworkInterfaceSettings( this ); } public void ReleaseDhcpLease( ) { throw new NotImplementedException( ); //try //{ // UpdateConfiguration(this, UPDATE_FLAGS_DHCP_RELEASE); //} //finally //{ // ReloadSettings(); //} } public void RenewDhcpLease( ) { throw new NotImplementedException( ); //try //{ // UpdateConfiguration(this, UPDATE_FLAGS_DHCP_RELEASE | UPDATE_FLAGS_DHCP_RENEW); //} //finally //{ // ReloadSettings(); //} } public byte[ ] PhysicalAddress { get { return m_macAddress; } set { m_macAddress = value; throw new NotImplementedException( ); //try //{ // _macAddress = value; // UpdateConfiguration(this, UPDATE_FLAGS_MAC); //} //finally //{ // ReloadSettings(); //} } } public NetworkInterfaceType NetworkInterfaceType { get { return m_networkInterfaceType; } } } } ================================================ FILE: Zelig/Zelig/RunTime/DeviceModels/lwIP/Properties/AssemblyInfo.cs ================================================ using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; // General Information about an assembly is controlled through the following // set of attributes. Change these attribute values to modify the information // associated with an assembly. [assembly: AssemblyTitle( "Microsoft.Llilum.Lwip" )] [assembly: AssemblyDescription( "" )] [assembly: AssemblyConfiguration( "" )] [assembly: AssemblyCompany( "Microsoft" )] [assembly: AssemblyProduct( "Microsoft.Llilum.Lwip" )] [assembly: AssemblyCopyright( "Copyright © Microsoft 2007" )] [assembly: AssemblyTrademark( "" )] [assembly: AssemblyCulture( "" )] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible( false )] //// The following GUID is for the ID of the typelib if this project is exposed to COM //[assembly: Guid( "975a7db2-22e5-41c6-9e32-d3f72152d387" )] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Revision and Build Numbers // by using the '*' as shown below: [assembly: AssemblyVersion( "1.0.0.0" )] [assembly: AssemblyFileVersion( "1.0.0.0" )] ================================================ FILE: Zelig/Zelig/RunTime/DeviceModels/mbed/Properties/AssemblyInfo.cs ================================================ using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; // General Information about an assembly is controlled through the following // set of attributes. Change these attribute values to modify the information // associated with an assembly. [assembly: AssemblyTitle("mbed")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("mbed")] [assembly: AssemblyCopyright("Copyright © 2015")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible(false)] // The following GUID is for the ID of the typelib if this project is exposed to COM [assembly: Guid("39648552-80c7-4340-951a-f71865e96a70")] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Build and Revision Numbers // by using the '*' as shown below: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("1.0.0.0")] [assembly: AssemblyFileVersion("1.0.0.0")] ================================================ FILE: Zelig/Zelig/RunTime/DeviceModels/mbed/Threading.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // namespace Microsoft.Zelig.Support.mbed { using System; using System.Runtime.InteropServices; //--// public delegate void ThreadStart( UIntPtr argument ); public static class Threading { [DllImport( "C" )] public static extern UIntPtr CreateNativeContext( UIntPtr entryPoint, UIntPtr stack, int stackSize ); [DllImport( "C" )] public static extern void Yield( UIntPtr nativeContext ); [DllImport( "C" )] public static extern void Retire( UIntPtr nativeContext ); [DllImport( "C" )] public static extern void SwitchToContext( UIntPtr nativeContext ); [DllImport( "C" )] public static extern UIntPtr GetPriority( UIntPtr nativeContext ); [DllImport( "C" )] public static extern void SetPriority( UIntPtr nativeContext, UIntPtr priority ); } } ================================================ FILE: Zelig/Zelig/RunTime/DeviceModels/mbed/Timer.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // namespace Microsoft.Zelig.Support.mbed { public class Timer { private bool _running; // whether the timer is running private uint _start; // the start time of the latest slice private int _time; // any accumulated time from previous slices public static void wait_ms(int ms) { uint timestamp = UsTicker.us_ticker_read(); ms *= 1000; while ((int)(UsTicker.us_ticker_read() - timestamp) Debug AnyCPU {D7F2BC4E-1406-47AA-90E1-07BC4CE9410F} Library Properties Microsoft.Zelig.Support.mbed Microsoft.Zelig.Support.mbed v4.5 512 true full false $(LlilumBuildRoot)\Target\bin\$(Configuration)\ DEBUG;TRACE prompt 4 true pdbonly true $(LlilumBuildRoot)\Target\bin\$(Configuration)\ TRACE prompt 4 true ================================================ FILE: Zelig/Zelig/RunTime/Framework/Llilum/Devices/Adc/AdcChannel.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // namespace Microsoft.Llilum.Devices.Adc { using System; public abstract class AdcChannel : IDisposable { public abstract void Dispose(); public abstract void InitializePin(); public abstract uint ReadUnsigned(); public abstract float Read(); } } ================================================ FILE: Zelig/Zelig/RunTime/Framework/Llilum/Devices/Adc/AdcChannelInfo.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // namespace Microsoft.Llilum.Devices.Adc { using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; public interface IAdcChannelInfoUwp { int[] AdcPinNumbers { get; } int MaxValue { get; } int MinValue { get; } int ResolutionInBits { get; } } } ================================================ FILE: Zelig/Zelig/RunTime/Framework/Llilum/Devices/Adc/AdcPin.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // namespace Microsoft.Llilum.Devices.Adc { using System; using System.Runtime.CompilerServices; public class AdcPin : IDisposable { private AdcChannel m_adcPin; private int m_pinNumber; public AdcPin(int pinNumber) { m_adcPin = TryAcquireAdcPin(pinNumber); if (m_adcPin == null) { throw new InvalidOperationException(); } m_adcPin.InitializePin(); m_pinNumber = pinNumber; } ~AdcPin() { Dispose(false); } public uint ReadUnsigned() { return m_adcPin.ReadUnsigned(); } public float Read() { return m_adcPin.Read(); } protected virtual void Dispose(bool disposing) { if (m_adcPin != null) { if (disposing) { m_adcPin.Dispose(); } m_adcPin = null; } } public void Dispose() { Dispose(true); GC.SuppressFinalize(this); } [MethodImpl(MethodImplOptions.InternalCall)] private static extern AdcChannel TryAcquireAdcPin(int pinNumber); } } ================================================ FILE: Zelig/Zelig/RunTime/Framework/Llilum/Devices/Gpio/GpioPin.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // namespace Microsoft.Llilum.Devices.Gpio { using System; using System.Runtime.CompilerServices; public delegate void ValueChangedHandler( object sender, PinEdge args ); public abstract class GpioPin : IDisposable { private PinDirection m_pinDirection; private PinMode m_pinMode; private PinEdge m_activePinEdge; private ValueChangedHandler m_evt; public event ValueChangedHandler ValueChanged { add { var old = m_evt; m_evt += value; if (old == null) { EnableInterrupt(); } } remove { m_evt -= value; if (m_evt == null) { DisableInterrupt(); } } } public static int BoardPinCount { get { return GetBoardPinCount(); } } public abstract int PinNumber { get; } public PinDirection Direction { get { return m_pinDirection; } set { m_pinDirection = value; SetPinDirection(value); } } public PinMode Mode { get { return m_pinMode; } set { m_pinMode = value; SetPinMode(value); } } public PinEdge ActivePinEdge { get { return m_activePinEdge; } set { m_activePinEdge = value; SetActivePinEdge(value); } } public abstract void Dispose(); public abstract int Read(); protected abstract void SetPinMode(PinMode pinMode); protected abstract void SetPinDirection(PinDirection pinDirection); protected abstract void SetActivePinEdge(PinEdge pinEdge); public abstract void Write(int value); public static GpioPin TryCreateGpioPin(int pinNumber) { GpioPin newPin = TryAcquireGpioPin(pinNumber); if(newPin == null) { return null; } // Set default values newPin.Direction = PinDirection.Input; newPin.Mode = PinMode.Default; return newPin; } protected void SendEventInternal(PinEdge pinEdge) { m_evt?.Invoke(this, pinEdge); } protected abstract void EnableInterrupt(); protected abstract void DisableInterrupt(); [MethodImpl(MethodImplOptions.InternalCall)] private static extern GpioPin TryAcquireGpioPin(int pinNumber); [MethodImpl(MethodImplOptions.InternalCall)] private static extern int GetBoardPinCount(); } public enum PinDirection { Input = 0, Output, } public enum PinMode { Default = 0, PullNone, PullUp, PullDown, OpenDrain, Repeater, } public enum PinEdge { None = 0, RisingEdge, FallingEdge, BothEdges, LevelLow, LevelHigh, } } ================================================ FILE: Zelig/Zelig/RunTime/Framework/Llilum/Devices/I2c/I2cChannel.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // namespace Microsoft.Llilum.Devices.I2c { using System; public abstract class I2cChannel : IDisposable { public abstract II2cChannelInfo GetChannelInfo(); public abstract void Initialize(II2cChannelInfo channelInfo); public abstract void SetFrequency(int hz); public abstract int Write(byte[] buffer, int deviceAddress, int transactionStartOffset, int transactionLength, bool sendStop); public abstract int Read(byte[] buffer, int deviceAddress, int transactionStartOffset, int transactionLength, bool sendStop); public abstract void Dispose(); } } ================================================ FILE: Zelig/Zelig/RunTime/Framework/Llilum/Devices/I2c/I2cChannelInfo.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // namespace Microsoft.Llilum.Devices.I2c { using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; public interface II2cChannelInfo { int SdaPin { get; } int SclPin { get; } int PortIndex { get; } } } ================================================ FILE: Zelig/Zelig/RunTime/Framework/Llilum/Devices/I2c/I2cDevice.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // namespace Microsoft.Llilum.Devices.I2c { using System; using System.Collections.Generic; using System.Linq; using System.Runtime.CompilerServices; using System.Text; using System.Threading.Tasks; public class I2cDevice : IDisposable { private I2cChannel m_channel; private bool m_open = false; private int m_frequency; private const int defaultFrequency = 100000; public I2cDevice(int port) { I2cChannel newChannel = TryAcquireI2cChannel(port); if(newChannel == null) { throw new ArgumentException(); } Initialize(); m_channel = newChannel; } public I2cDevice(II2cChannelInfo channelInfo) { m_channel = TryAcquireI2cChannel(channelInfo); if (m_channel == null) { throw new InvalidOperationException(); } Initialize(); } ~I2cDevice() { Dispose(false); } private void Initialize() { m_frequency = defaultFrequency; } public void Open() { ThrowIfDisposed(); m_channel.Initialize(m_channel.GetChannelInfo()); m_channel.SetFrequency(Frequency); m_open = true; } public int Frequency { get { return m_frequency; } set { ThrowIfDisposed(); if (value != m_frequency) { m_frequency = value; // Cannot make calls to the channel until it is initialized if (m_open) { m_channel.SetFrequency(m_frequency); } } } } public int Write(byte[] buffer, int deviceAddress, int transactionStartOffset, int transactionLength, bool sendStop) { ThrowIfDisposed(); return m_channel.Write(buffer, deviceAddress, transactionStartOffset, transactionLength, sendStop); } public int Read(byte[] buffer, int deviceAddress, int transactionStartOffset, int transactionLength, bool sendStop) { ThrowIfDisposed(); return m_channel.Read(buffer, deviceAddress, transactionStartOffset, transactionLength, sendStop); } private void ThrowIfDisposed() { if (m_channel == null) { throw new ObjectDisposedException(null); } } protected virtual void Dispose(bool disposing) { if (m_channel != null) { if (disposing) { m_channel.Dispose(); m_channel = null; } } } public void Dispose() { Dispose(true); GC.SuppressFinalize(this); } [MethodImpl(MethodImplOptions.InternalCall)] private static extern I2cChannel TryAcquireI2cChannel(int port); [MethodImpl(MethodImplOptions.InternalCall)] private static extern I2cChannel TryAcquireI2cChannel(II2cChannelInfo channelInfo); } } ================================================ FILE: Zelig/Zelig/RunTime/Framework/Llilum/Devices/Microsoft.Llilum.Devices.csproj ================================================  Debug AnyCPU {D68EE51B-A898-4A77-97D8-C61254CAC122} Library Properties Llilum.Devices Llilum.Devices $(LlilumBuildRoot)\Target\obj\$(MSBuildProjectName)\ v4.5 true full false $(LlilumBuildRoot)\Target\bin\$(Configuration)\ DEBUG;TRACE prompt 4 true true true AllRules.ruleset AnyCPU false pdbonly true $(LlilumBuildRoot)\Target\bin\$(Configuration)\ TRACE prompt 4 true true true AllRules.ruleset AnyCPU false true full false $(LlilumBuildRoot)\Target\bin\$(Configuration)\ TRACE;DEBUG AnyCPU true true false {186F31A3-EF89-4A25-B2D5-20070702AA01} system False {186f31a3-ef89-4a25-b2d5-20060501aa01} mscorlib ================================================ FILE: Zelig/Zelig/RunTime/Framework/Llilum/Devices/Properties/AssemblyInfo.cs ================================================ using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; // General Information about an assembly is controlled through the following // set of attributes. Change these attribute values to modify the information // associated with an assembly. [assembly: AssemblyTitle("Microsoft.Llilum.Devices")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("Microsoft")] [assembly: AssemblyProduct("Windows")] [assembly: AssemblyCopyright("Copyright © Microsoft")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Build and Revision Numbers // by using the '*' as shown below: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("1.0.0.0")] [assembly: AssemblyFileVersion("1.0.0.0")] [assembly: System.CLSCompliant(false)] ================================================ FILE: Zelig/Zelig/RunTime/Framework/Llilum/Devices/Pwm/PwmChannel.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // namespace Microsoft.Llilum.Devices.Pwm { using System; public enum PwmPolarity { Normal = 0, Inverted, }; public enum PwmPrescaler { Div1 = 0, Div2, Div4, Div8, Div16, Div64, Div256, Div1024 }; public abstract class PwmChannel : IDisposable { public abstract void Dispose(); public abstract void InitializePin(); public abstract void SetDutyCycle(float ratio); public abstract void SetPulseWidth(int microSeconds); public abstract void SetPeriod(int microSeconds); public abstract void SetPolarity(PwmPolarity polarity); public abstract void SetPrescaler(PwmPrescaler prescaler); public abstract void Start( ); public abstract void Stop( ); } } ================================================ FILE: Zelig/Zelig/RunTime/Framework/Llilum/Devices/Pwm/PwmChannelInfo.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // // // Copyright (c) Microsoft Corporation. All rights reserved. // namespace Microsoft.Llilum.Devices.Pwm { public interface IPwmChannelInfoUwp { int[] PwmPinNumbers { get; } int MaxFrequency { get; } int MinFrequency { get; } } } ================================================ FILE: Zelig/Zelig/RunTime/Framework/Llilum/Devices/Pwm/PwmPin.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // namespace Microsoft.Llilum.Devices.Pwm { using System; using System.Runtime.CompilerServices; public class PwmPin : IDisposable { private PwmChannel m_pwmPin; private int m_pinNumber; public PwmPin(int pinNumber) { m_pwmPin = TryAcquirePwmPin(pinNumber); if (m_pwmPin == null) { throw new ArgumentException(); } m_pwmPin.InitializePin(); m_pinNumber = pinNumber; } ~PwmPin() { Dispose(false); } public void SetDutyCycle(float ratio) { ThrowIfDisposed(); m_pwmPin.SetDutyCycle(ratio); } public void SetPeriod(int microSeconds) { ThrowIfDisposed(); m_pwmPin.SetPeriod(microSeconds); } public void SetPulseWidth(int microSeconds) { ThrowIfDisposed(); m_pwmPin.SetPulseWidth(microSeconds); } public void Start() { ThrowIfDisposed(); m_pwmPin.Start(); } public void Stop() { ThrowIfDisposed(); m_pwmPin.Stop(); } protected virtual void Dispose(bool disposing) { if (m_pwmPin != null) { if (disposing) { m_pwmPin.Dispose(); } m_pwmPin = null; } } public void Dispose() { Dispose(true); GC.SuppressFinalize(this); } private void ThrowIfDisposed() { if(m_pwmPin == null) { throw new ObjectDisposedException(null); } } [MethodImpl(MethodImplOptions.InternalCall)] private static extern PwmChannel TryAcquirePwmPin(int pinNumber); } } ================================================ FILE: Zelig/Zelig/RunTime/Framework/Llilum/Devices/Spi/SpiChannel.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // namespace Microsoft.Llilum.Devices.Spi { using System; public abstract class SpiChannel : IDisposable { public abstract ISpiChannelInfo GetChannelInfo(); public abstract void SetupPins(ISpiChannelInfo channelInfo, bool writeOnly); public abstract void SetupPins(ISpiChannelInfo channelInfo, int alternateCsPin, bool writeOnly); public abstract void SetupChannel(int bits, SpiMode mode, bool isSlave); public abstract void SetupTiming(int frequencyInHz, int setupTime, int holdTime); public abstract void WriteRead(byte[] writeBuffer, int writeOffset, int writeLength, byte[] readBuffer, int readOffset, int readLength, int startReadOffset); public abstract void Write( byte[] writeBuffer, int writeOffset, int writeLength ); public abstract void Read( byte[] readBuffer, int readOffset, int readLength ); public abstract void Dispose(); } public enum SpiMode { Cpol0Cpha0 = 0, Cpol0Cpha1, Cpol1Cpha0, Cpol1Cpha1, } } ================================================ FILE: Zelig/Zelig/RunTime/Framework/Llilum/Devices/Spi/SpiChannelInfo.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // namespace Microsoft.Llilum.Devices.Spi { using System; /// /// This is the information we need to use a Llilum.NET SpiDevice /// public interface ISpiChannelInfo { int Mosi { get; } int Miso { get; } int Sclk { get; } int DefaultChipSelect { get; } int SetupTime { get; } int HoldTime { get; } bool ActiveLow { get; } } /// /// This is the information we need to implement UWP Spi /// public interface ISpiChannelInfoUwp { ISpiChannelInfo ChannelInfo { get; } int ChipSelectLines { get; } int MaxFreq { get; } int MinFreq { get; } bool Supports16 { get; } } } ================================================ FILE: Zelig/Zelig/RunTime/Framework/Llilum/Devices/Spi/SpiDevice.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // namespace Microsoft.Llilum.Devices.Spi { using System; using System.Runtime.CompilerServices; public class SpiDevice : IDisposable { private SpiChannel m_spiChannel; private int m_chipSelectPin; private bool m_disposed = false; private bool m_writeOnly = false; const int defaultFrequency = 100000; const SpiMode defaultMode = SpiMode.Cpol0Cpha0; const int defaultBitLength = 8; const bool defaultIsSlave = false; /// /// SpiDevice constructor /// /// Index of the port that maps to the board assembly public SpiDevice(int portIndex, bool writeOnly) { m_spiChannel = TryAcquireSpiChannel(portIndex, writeOnly); if (m_spiChannel == null) { throw new ArgumentException(); } m_writeOnly = writeOnly; // Set default values Initialize(m_spiChannel.GetChannelInfo().DefaultChipSelect); } /// /// SpiDevice constructor /// /// Channel information necessary to create a SPI channel public SpiDevice(ISpiChannelInfo channelInfo, bool writeOnly) : this(channelInfo, channelInfo.DefaultChipSelect, writeOnly) { } public SpiDevice(ISpiChannelInfo channelInfo, int chipSelectPin, bool writeOnly) { m_spiChannel = TryAcquireSpiChannel(channelInfo, chipSelectPin, writeOnly); if (m_spiChannel == null) { throw new InvalidOperationException(); } m_writeOnly = writeOnly; // Set default values Initialize(chipSelectPin); } ~SpiDevice() { Dispose(false); } /// /// Initializes the default values /// private void Initialize(int chipSelectPin) { SetChipSelect(chipSelectPin, true); DataBitLength = defaultBitLength; Mode = defaultMode; ClockFrequency = defaultFrequency; IsSlave = defaultIsSlave; } private void ThrowIfDisposed() { if (m_disposed) { throw new ObjectDisposedException(null); } } /// /// Initializes the SPI port to the values currently set in the channel /// public void Open() { ThrowIfDisposed(); ISpiChannelInfo channelInfo = m_spiChannel.GetChannelInfo(); if (ChipSelectPin != channelInfo.DefaultChipSelect) { m_spiChannel.SetupPins(channelInfo, ChipSelectPin, m_writeOnly); } else { m_spiChannel.SetupPins(channelInfo, m_writeOnly); } m_spiChannel.SetupChannel(DataBitLength, Mode, IsSlave); m_spiChannel.SetupTiming(ClockFrequency, channelInfo.SetupTime, channelInfo.HoldTime); } /// /// Is the device operating in slave mode. /// Slave mode is currently not supported /// public bool IsSlave { get; private set; } /// /// Gets or sets the chip select line for the connection to the SPI device. /// /// The chip select line. public int ChipSelectPin { get { return m_chipSelectPin; } set { SetChipSelect(value, false); } } /// /// Gets or sets the clock frequency for the connection. /// /// Value of the clock frequency in Hz. public int ClockFrequency { get; set; } /// /// Gets or sets the bit length for data on this connection. /// /// The data bit length. public int DataBitLength { get; set; } /// /// Gets or sets the SpiMode for this connection. /// /// The communication mode. public SpiMode Mode { get; set; } /// /// Performs a SPI transaction. Either writeBuffer, readBuffer, or both must be non-empty /// /// Bytes to write. If null, writes 0x0 for read /// Offset into the writeBuffer /// Length of the data in bytes to write /// Bytes to read. If null, only does write /// Offset into the readBuffer /// Length in bytes to read /// Index of the SPI response at which to start reading bytes into readBuffer at readOffset. This is used if the SPI response requires multiple writes before the response data is ready. public void WriteRead(byte[] writeBuffer, int writeOffset, int writeLength, byte[] readBuffer, int readOffset, int readLength, int startReadOffset) { ThrowIfDisposed(); m_spiChannel.WriteRead(writeBuffer, writeOffset, writeLength, readBuffer, readOffset, readLength, startReadOffset); } public void Write( byte[] writeBuffer, int writeOffset, int writeLength ) { ThrowIfDisposed(); m_spiChannel.Write( writeBuffer, writeOffset, writeLength ); } public void Read( byte[] readBuffer, int readOffset, int readLength ) { ThrowIfDisposed(); m_spiChannel.Read( readBuffer, readOffset, readLength ); } /// /// Acquires the chip select pin if a new one is entered and releases the old one. /// /// Pin number /// Is this the first time the CS pin is being set private void SetChipSelect(int newPin, bool initialSet) { ThrowIfDisposed(); if (initialSet) { m_chipSelectPin = newPin; } else { if (m_chipSelectPin != newPin) { // Release the old CS pin and reserve the new one if (TryChangeCsPin(m_chipSelectPin, newPin)) { m_chipSelectPin = newPin; } else { // This would only happen if the new CS pin is busy throw new InvalidOperationException(); } } } } protected virtual void Dispose(bool disposing) { if (!m_disposed) { ISpiChannelInfo channelInfo = m_spiChannel.GetChannelInfo(); ReleaseSpiPins(channelInfo, ChipSelectPin); if (disposing) { m_spiChannel.Dispose(); } } } public void Dispose() { Dispose(true); m_disposed = true; GC.SuppressFinalize(this); } [MethodImpl(MethodImplOptions.InternalCall)] private static extern SpiChannel TryAcquireSpiChannel(int port, bool writeOnly); [MethodImpl(MethodImplOptions.InternalCall)] private static extern SpiChannel TryAcquireSpiChannel(ISpiChannelInfo channelInfo, int alternateCsPin, bool writeOnly); [MethodImpl(MethodImplOptions.InternalCall)] private static extern bool TryChangeCsPin(int oldPin, int newPin); [MethodImpl(MethodImplOptions.InternalCall)] private static extern void ReleaseSpiPins(ISpiChannelInfo channelInfo, int csPin); } } ================================================ FILE: Zelig/Zelig/RunTime/Framework/System.Runtime.WindowsRuntime/Properties/AssemblyInfo.cs ================================================ using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; // General Information about an assembly is controlled through the following // set of attributes. Change these attribute values to modify the information // associated with an assembly. [assembly: AssemblyTitle("System.Runtime.WindowsRuntime")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("Microsoft")] [assembly: AssemblyProduct("System.Runtime.WindowsRuntime")] [assembly: AssemblyCopyright("Copyright © Microsoft")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Build and Revision Numbers // by using the '*' as shown below: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("1.0.0.0")] [assembly: AssemblyFileVersion("1.0.0.0")] [assembly: System.CLSCompliant(false)] ================================================ FILE: Zelig/Zelig/RunTime/Framework/System.Runtime.WindowsRuntime/System.Runtime.WindowsRuntime.csproj ================================================  Debug AnyCPU {016691CA-A31F-4273-A4D2-C5F6E4B3662D} Library Properties System.Runtime System.Runtime.WindowsRuntime $(LlilumBuildRoot)\Target\obj\$(MSBuildProjectName)\ v4.5 true full false $(LlilumBuildRoot)\Target\bin\$(Configuration)\ DEBUG;TRACE prompt 4 true true true AllRules.ruleset AnyCPU false pdbonly true $(LlilumBuildRoot)\Target\bin\$(Configuration)\ TRACE prompt 4 true true true AllRules.ruleset AnyCPU false true full false $(LlilumBuildRoot)\Target\bin\$(Configuration)\ TRACE;DEBUG AnyCPU true true false {186F31A3-EF89-4A25-B2D5-20070702AA01} system False {186f31a3-ef89-4a25-b2d5-20060501aa01} mscorlib {dc8c38d7-780b-4b13-8ace-9050e39cc51c} Windows ================================================ FILE: Zelig/Zelig/RunTime/Framework/System.Runtime.WindowsRuntime/WindowsRuntimeSystemExtensions.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // using System.Threading.Tasks; using Windows.Foundation; using Windows.Internal; namespace System.Runtime { /// /// Provides extension methods for converting between tasks and Windows Runtime asynchronous actions and operations. /// [CLSCompliant(false)] public static class WindowsRuntimeSystemExtensions { /// /// Returns a Windows Runtime asynchronous action that represents a started task. /// /// The started task. /// A Windows.Foundation.IAsyncAction instance that represents the started task. public static IAsyncAction AsAsyncAction(this Task source) { return Windows.Internal.WindowsRuntimeSystemExtensions.AsAsyncAction(source); } /// /// Returns a task that represents a Windows Runtime asynchronous action. /// /// The asynchronous action. /// A task that represents the asynchronous action. public static Task AsTask(this IAsyncAction source) { return Windows.Internal.WindowsRuntimeSystemExtensions.AsTask(source); } /// /// Returns a Windows Runtime asynchronous operation that represents a started task. /// /// The started task. /// A Windows.Foundation.IAsyncOperation instance that represents the started task. public static IAsyncOperation AsAsyncOperation(this Task source) { return Windows.Internal.WindowsRuntimeSystemExtensions.AsAsyncOperation(source); } /// /// Returns a task that represents a Windows Runtime asynchronous operation. /// /// The asynchronous operation. /// A task that represents the asynchronous operation. public static Task AsTask(this IAsyncOperation source) { return Windows.Internal.WindowsRuntimeSystemExtensions.AsTask(source); } /// /// Returns a Windows Runtime asynchronous operation that represents a started task. /// /// The started task. /// A Windows.Foundation.IAsyncOperation instance that represents the started task. public static IAsyncOperationWithProgress AsAsyncOperationWithProgress(this Task source) { return Windows.Internal.WindowsRuntimeSystemExtensions.AsAsyncOperationWithProgress(source); } /// /// Returns a task that represents a Windows Runtime asynchronous operation. /// /// The asynchronous operation. /// A task that represents the asynchronous operation. public static Task AsTask(this IAsyncOperationWithProgress source) { return Windows.Internal.WindowsRuntimeSystemExtensions.AsTask(source); } } } ================================================ FILE: Zelig/Zelig/RunTime/Framework/System_Core/Properties/AssemblyInfo.cs ================================================ using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; // General Information about an assembly is controlled through the following // set of attributes. Change these attribute values to modify the information // associated with an assembly. [assembly: AssemblyTitle( "System.Core" )] [assembly: AssemblyDescription( "" )] [assembly: AssemblyConfiguration( "" )] [assembly: AssemblyCompany( "Microsoft.Core" )] [assembly: AssemblyProduct( "System" )] [assembly: AssemblyCopyright( "Copyright © Microsoft" )] [assembly: AssemblyTrademark( "" )] [assembly: AssemblyCulture( "" )] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Revision and Build Numbers // by using the '*' as shown below: [assembly: AssemblyVersion( "4.5.0.0" )] [assembly: AssemblyFileVersion( "4.5.0.0" )] [assembly: System.CLSCompliant(false)] ================================================ FILE: Zelig/Zelig/RunTime/Framework/System_Core/System/FuncAndAction.cs ================================================ // ==++== // // Copyright (c) Microsoft Corporation. All rights reserved. // // ==--== namespace System { public delegate void Action(); // public delegate void Action(T obj); -- Already defined in mscorlib public delegate void Action(T1 arg1, T2 arg2); public delegate void Action(T1 arg1, T2 arg2, T3 arg3); public delegate void Action(T1 arg1, T2 arg2, T3 arg3, T4 arg4); public delegate TResult Func(); public delegate TResult Func(T arg); public delegate TResult Func(T1 arg1, T2 arg2); public delegate TResult Func(T1 arg1, T2 arg2, T3 arg3); public delegate TResult Func(T1 arg1, T2 arg2, T3 arg3, T4 arg4); } ================================================ FILE: Zelig/Zelig/RunTime/Framework/System_Core/System/Runtime/CompilerServices/Extension.cs ================================================ using System; namespace System.Runtime.CompilerServices { [AttributeUsage(AttributeTargets.Method | AttributeTargets.Class | AttributeTargets.Assembly)] public sealed class ExtensionAttribute : Attribute { } } ================================================ FILE: Zelig/Zelig/RunTime/Framework/System_Core/system_core.csproj ================================================  Debug AnyCPU 9.0.21022 2.0 {186F31A3-EF89-4A25-B2D5-20080628AA01} Library Properties System System.Core $(LlilumBuildRoot)\Target\obj\$(MSBuildProjectName)\ v4.5 true full false $(LlilumBuildRoot)\Target\bin\$(Configuration)\ DEBUG;TRACE prompt 4 true true true AllRules.ruleset AnyCPU false pdbonly true $(LlilumBuildRoot)\Target\bin\$(Configuration)\ TRACE prompt 4 true true true AllRules.ruleset AnyCPU false true full false $(LlilumBuildRoot)\Target\bin\$(Configuration)\ TRACE;DEBUG AnyCPU true true false {186F31A3-EF89-4A25-B2D5-20060501AA01} mscorlib False {186F31A3-EF89-4A25-B2D5-20070702AA01} system False ================================================ FILE: Zelig/Zelig/RunTime/Framework/Windows/Devices/Adc/AdcChannel.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // using System; namespace Windows.Devices.Adc { public sealed class AdcChannel : IDisposable { private readonly int m_channelNumber; private AdcController m_adcController; internal AdcChannel(AdcController controller, int channelNumber) { m_adcController = controller; m_channelNumber = channelNumber; } ~AdcChannel() { Dispose(false); } public AdcController Controller { get { return m_adcController; } } public int ReadValue() { ThrowIfDisposed(); return m_adcController.m_adcControllerProvider.ReadValue(m_channelNumber); } public double ReadRatio() { ThrowIfDisposed(); return (double)ReadValue() / (double)m_adcController.MaxValue; } public void Dispose() { Dispose(true); GC.SuppressFinalize(this); } private void ThrowIfDisposed() { if(m_adcController == null) { throw new ObjectDisposedException(null); } } private void Dispose(bool disposing) { if (m_adcController != null) { if(disposing) { m_adcController.m_adcControllerProvider.ReleaseChannel(m_channelNumber); m_adcController = null; } } } } } ================================================ FILE: Zelig/Zelig/RunTime/Framework/Windows/Devices/Adc/AdcChannelMode.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // namespace Windows.Devices.Adc { public enum AdcChannelMode { SingleEnded = 0, Differential, } } ================================================ FILE: Zelig/Zelig/RunTime/Framework/Windows/Devices/Adc/AdcController.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // using System; using System.Collections.Generic; using System.Runtime.CompilerServices; using Windows.Devices.Adc.Provider; using Llilum = Microsoft.Llilum.Devices.Adc; namespace Windows.Devices.Adc { public sealed class AdcController { internal IAdcControllerProvider m_adcControllerProvider; private AdcController(IAdcControllerProvider provider) { m_adcControllerProvider = provider; } public AdcChannelMode ChannelMode { get { return (AdcChannelMode)m_adcControllerProvider.ChannelMode; } set { m_adcControllerProvider.ChannelMode = (ProviderAdcChannelMode)value; } } public int ChannelCount { get { return m_adcControllerProvider.ChannelCount; } } public int MaxValue { get { return m_adcControllerProvider.MaxValue; } } public int MinValue { get { return m_adcControllerProvider.MinValue; } } public int ResolutionInBits { get { return m_adcControllerProvider.ResolutionInBits; } } public bool IsChannelModeSupported(AdcChannelMode channelMode) { return m_adcControllerProvider.IsChannelModeSupported((ProviderAdcChannelMode)channelMode); } public AdcChannel OpenChannel(int channelNumber) { // If the channel cannot be acquired, this will throw m_adcControllerProvider.AcquireChannel(channelNumber); return new AdcChannel(this, channelNumber); } public static /*IAsyncOperation*/AdcController GetDefaultAsync() { return new AdcController(new DefaultAdcProvider()); } public static /*IAsyncOperation*/List GetControllersAsync(IAdcProvider provider) { List controllers = new List(); IList providers = provider.GetControllers(); foreach (IAdcControllerProvider controllerProvider in providers) { controllers.Add(new AdcController(controllerProvider)); } controllers.Add(new AdcController(providers[0])); return controllers; } [MethodImpl(MethodImplOptions.InternalCall)] internal static extern Llilum.IAdcChannelInfoUwp GetAdcProviderInfo(); /// /// This is the default ADC provider that uses the ADC implementation in Microsoft.Llilum.Devices /// internal sealed class DefaultAdcProvider : IAdcControllerProvider { private Llilum.IAdcChannelInfoUwp m_providerInfo; private Llilum.AdcPin[] m_adcChannels; private object m_channelLock; public DefaultAdcProvider() { m_providerInfo = AdcController.GetAdcProviderInfo(); m_adcChannels = new Llilum.AdcPin[m_providerInfo.AdcPinNumbers.Length]; m_channelLock = new object(); } public int ChannelCount { get { return m_providerInfo.AdcPinNumbers.Length; } } public ProviderAdcChannelMode ChannelMode { get { return ProviderAdcChannelMode.SingleEnded; } set { if (value != ProviderAdcChannelMode.SingleEnded) { throw new InvalidOperationException(); } } } public int MaxValue { get { return m_providerInfo.MaxValue; } } public int MinValue { get { return m_providerInfo.MinValue; } } public int ResolutionInBits { get { return m_providerInfo.ResolutionInBits; } } public void AcquireChannel(int channel) { if (channel >= m_providerInfo.AdcPinNumbers.Length || channel < 0) { throw new InvalidOperationException(); } lock(m_channelLock) { if (m_adcChannels[channel] == null) { Llilum.AdcPin newChannel = new Llilum.AdcPin(m_providerInfo.AdcPinNumbers[channel]); m_adcChannels[channel] = newChannel; } } } public bool IsChannelModeSupported(ProviderAdcChannelMode channelMode) { if (channelMode == ProviderAdcChannelMode.SingleEnded) { return true; } return false; } public int ReadValue(int channel) { if (channel >= m_adcChannels.Length || channel < 0) { throw new InvalidOperationException(); } lock (m_channelLock) { if (m_adcChannels[channel] == null) { throw new InvalidOperationException(); } return (int)m_adcChannels[channel].ReadUnsigned(); } } public void ReleaseChannel(int channel) { if (channel >= m_adcChannels.Length || channel < 0) { throw new InvalidOperationException(); } lock (m_channelLock) { if (m_adcChannels[channel] == null) { throw new InvalidOperationException(); } m_adcChannels[channel] = null; } } } } } ================================================ FILE: Zelig/Zelig/RunTime/Framework/Windows/Devices/Adc/IAdcControllerProvider.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // namespace Windows.Devices.Adc.Provider { public interface IAdcControllerProvider { int ChannelCount { get; } ProviderAdcChannelMode ChannelMode { get; set; } int MaxValue { get; } int MinValue { get; } int ResolutionInBits { get; } bool IsChannelModeSupported(ProviderAdcChannelMode channelMode); void AcquireChannel(int channel); void ReleaseChannel(int channel); int ReadValue(int channelNumber); } } ================================================ FILE: Zelig/Zelig/RunTime/Framework/Windows/Devices/Adc/IAdcProvider.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // using System; using System.Collections.Generic; namespace Windows.Devices.Adc.Provider { public interface IAdcProvider { IList GetControllers(); } } ================================================ FILE: Zelig/Zelig/RunTime/Framework/Windows/Devices/Adc/ProviderAdcChannelMode.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // namespace Windows.Devices.Adc.Provider { public enum ProviderAdcChannelMode { SingleEnded = 0, Differential, } } ================================================ FILE: Zelig/Zelig/RunTime/Framework/Windows/Devices/Enumeration/DeviceInformation.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // #define INCOMPLETE using System; using System.Runtime.InteropServices; #if (!INCOMPLETE) using Windows.Foundation; using Windows.Foundation.Collections; using Windows.Foundation.Metadata; #endif namespace Windows.Devices.Enumeration { #if (!INCOMPLETE) /// Represents a device. //[ContractVersion(typeof(UniversalApiContract), 65536u), DualApiPartition(version = 100794368u), MarshalingBehavior(MarshalingType.Agile), Static(typeof(IDeviceInformationStatics2), 65536u, typeof(UniversalApiContract)), Static(typeof(IDeviceInformationStatics), 65536u, typeof(UniversalApiContract)), Threading(ThreadingModel.Both)] #endif public sealed class DeviceInformation // : IDeviceInformation, IDeviceInformation2 { private DeviceInformation(string id, string name) { Id = id; Name = name; } /// A string representing the identity of the device. /// A string representing the identity of the device. public string Id { get; } public bool IsDefault { get; } /// Indicates whether this device is enabled. /// Indicates whether this device is enabled. public bool IsEnabled { get; } /// The name of the device. /// The name of the device. This name is in the best available language for the app. public string Name { get; } #if (!INCOMPLETE) //public EnclosureLocation EnclosureLocation //{ // get; //} /// Property store containing well-known values as well as additional properties that can be specified during device enumeration. /// The property store for the device. public IMapView Properties { [return: HasVariant] get; } public DeviceInformationKind Kind { get; } public DeviceInformationPairing Pairing { get; } /// Updates the properties of an existing DeviceInformation object. /// Indicates the properties to update. public void Update([In] DeviceInformationUpdate updateInfo) { } //[RemoteAsync] public IAsyncOperation GetThumbnailAsync() { } /// Gets a glyph for the device. /// The object for managing the asynchronous operation that will return a DeviceThumbnail //[RemoteAsync] public IAsyncOperation GetGlyphThumbnailAsync() { } public static string GetAqsFilterFromDeviceClass([In] DeviceClass deviceClass) { } //[Overload("CreateFromIdAsyncWithKindAndAdditionalProperties")] public static IAsyncOperation CreateFromIdAsync([In] string deviceId, [In] IIterable additionalProperties, [In] DeviceInformationKind kind) { } //[Overload("FindAllAsyncWithKindAqsFilterAndAdditionalProperties")] public static IAsyncOperation FindAllAsync([In] string aqsFilter, [In] IIterable additionalProperties, [In] DeviceInformationKind kind) { } //[Overload("CreateWatcherWithKindAqsFilterAndAdditionalProperties")] public static DeviceWatcher CreateWatcher([In] string aqsFilter, [In] IIterable additionalProperties, [In] DeviceInformationKind kind) { } //[Overload("CreateFromIdAsync"), RemoteAsync] public static IAsyncOperation CreateFromIdAsync([In] string deviceId) { } //[Overload("CreateFromIdAsyncAdditionalProperties")] public static IAsyncOperation CreateFromIdAsync([In] string deviceId, [In] IIterable additionalProperties) { } //[Overload("FindAllAsync"), RemoteAsync] //public static IAsyncOperation FindAllAsync() public static DeviceInformationCollection FindAllAsync() { } [DefaultOverload, Overload("FindAllAsyncDeviceClass"), RemoteAsync] public static IAsyncOperation FindAllAsync([In] DeviceClass deviceClass) { } #endif /// Enumerates DeviceInformation objects matching the specified Advanced Query Syntax (AQS) string. /// The object for managing the asynchronous operation. /// An AQS string that filters the DeviceInformation objects to enumerate. Typically this string is retrieved from the GetDeviceSelector method of a class that interacts with devices. For example, GetDeviceSelector retrieves the string for the StorageDevice class. //[Overload("FindAllAsyncAqsFilter"), RemoteAsync] //public static IAsyncOperation FindAllAsync([In] string aqsFilter) public static DeviceInformationCollection FindAllAsync([In] string aqsFilter) { return new DeviceInformationCollection() { new DeviceInformation(aqsFilter, aqsFilter) }; } #if (!INCOMPLETE) //[Overload("FindAllAsyncAqsFilterAndAdditionalProperties")] public static IAsyncOperation FindAllAsync([In] string aqsFilter, [In] IIterable additionalProperties) { } /// Creates a DeviceWatcher for all devices. /// The created DeviceWatcher. //[Overload("CreateWatcher")] public static DeviceWatcher CreateWatcher() { } /// Creates a DeviceWatcher for devices matching the specified DeviceClass. /// The created DeviceWatcher. /// The class of device to enumerate using the DeviceWatcher. [DefaultOverload, Overload("CreateWatcherDeviceClass")] public static DeviceWatcher CreateWatcher([In] DeviceClass deviceClass) { } //[Overload("CreateWatcherAqsFilter")] public static DeviceWatcher CreateWatcher([In] string aqsFilter) { } //[Overload("CreateWatcherAqsFilterAndAdditionalProperties")] public static DeviceWatcher CreateWatcher([In] string aqsFilter, [In] IIterable additionalProperties) { } #endif } } ================================================ FILE: Zelig/Zelig/RunTime/Framework/Windows/Devices/Enumeration/DeviceInformationCollection.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // #define INCOMPLETE using System; using System.Collections.Generic; using System.Runtime.InteropServices; #if (!INCOMPLETE) using Windows.Foundation; using Windows.Foundation.Collections; using Windows.Foundation.Metadata; #endif namespace Windows.Devices.Enumeration { #if (!INCOMPLETE) //[ContractVersion(typeof(UniversalApiContract), 65536u), DualApiPartition(version = 100794368u), MarshalingBehavior(MarshalingType.Agile)] //public sealed class DeviceInformationCollection : IReadOnlyList, IIterable #endif public sealed class DeviceInformationCollection : List { /// The number of DeviceInformation objects in the collection. /// The number of DeviceInformation objects in the collection. public uint Size { get; } /// Gets the DeviceInformation object at the specified index. /// The DeviceInformation object at the specified index. /// The index. public DeviceInformation GetAt([In] uint index) { return base[ (int)index ]; } /// Returns the index of the specified DeviceInformation object in the collection. /// true if the method succeeded; otherwise, false. /// The DeviceInformation object in the collection. /// The index. public bool IndexOf([In] DeviceInformation value, out uint index) { index = (uint)base.IndexOf(value); return (index >= 0); } public uint GetMany([In] uint startIndex, [Out] DeviceInformation[] items) { throw new NotImplementedException( ); } #if (!INCOMPLETE) public IIterator First() { } #endif } } ================================================ FILE: Zelig/Zelig/RunTime/Framework/Windows/Devices/Gpio/DefaultPinProvider.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // using System; using Windows.Devices.Gpio.Provider; using Windows.Foundation; using Llilum = Microsoft.Llilum.Devices.Gpio; namespace Windows.Devices.Gpio { internal class DefaultPinProvider : IGpioPinProvider { private Llilum.GpioPin m_gpioPin; private TypedEventHandler m_evt; internal DefaultPinProvider(int pinNumber) { Llilum.GpioPin newPin = Llilum.GpioPin.TryCreateGpioPin(pinNumber); if (newPin == null) { throw new InvalidOperationException(); } m_gpioPin = newPin; } public TimeSpan DebounceTimeout { get { throw new NotImplementedException(); } set { throw new NotImplementedException(); } } public int PinNumber { get { return m_gpioPin.PinNumber; } } public GpioSharingMode SharingMode { get { return GpioSharingMode.Exclusive; } } public void Dispose() { m_gpioPin.Dispose(); } public event TypedEventHandler ValueChanged { add { var old = m_evt; m_evt += value; if( old == null ) { m_gpioPin.ValueChanged += HandleGpioInterrupt; } } remove { m_evt -= value; if( m_evt == null ) { m_gpioPin.ValueChanged -= HandleGpioInterrupt; } } } private void HandleGpioInterrupt(object sender, Llilum.PinEdge pinEdge) { m_evt?.Invoke(null, new GpioPinValueChangedEventArgs(pinEdge == Llilum.PinEdge.RisingEdge ? GpioPinEdge.RisingEdge : GpioPinEdge.FallingEdge)); } public GpioPinDriveMode GetDriveMode() { switch (m_gpioPin.Mode) { case Llilum.PinMode.PullNone: case Llilum.PinMode.Default: return (m_gpioPin.Direction == Llilum.PinDirection.Input) ? GpioPinDriveMode.Input : GpioPinDriveMode.Output; case Llilum.PinMode.PullDown: return GpioPinDriveMode.InputPullDown; case Llilum.PinMode.PullUp: return GpioPinDriveMode.InputPullUp; } throw new NotSupportedException(); } public bool IsDriveModeSupported(GpioPinDriveMode driveMode) { switch (driveMode) { case GpioPinDriveMode.Input: case GpioPinDriveMode.Output: case GpioPinDriveMode.InputPullUp: case GpioPinDriveMode.InputPullDown: return true; default: return false; } } public GpioPinValue Read() { return (m_gpioPin.Read() == 0) ? GpioPinValue.Low : GpioPinValue.High; } public void SetPinDriveMode(GpioDriveMode driveMode) { switch (driveMode) { case GpioDriveMode.Input: m_gpioPin.Mode = Llilum.PinMode.PullNone; m_gpioPin.Direction = Llilum.PinDirection.Input; break; case GpioDriveMode.Output: m_gpioPin.Mode = Llilum.PinMode.Default; m_gpioPin.Direction = Llilum.PinDirection.Output; break; case GpioDriveMode.InputPullUp: m_gpioPin.Mode = Llilum.PinMode.PullUp; m_gpioPin.Direction = Llilum.PinDirection.Input; break; case GpioDriveMode.InputPullDown: m_gpioPin.Mode = Llilum.PinMode.PullDown; m_gpioPin.Direction = Llilum.PinDirection.Input; break; default: throw new NotSupportedException(); } } public void Write(GpioPinValue value) { m_gpioPin.Write((int)value); } } } ================================================ FILE: Zelig/Zelig/RunTime/Framework/Windows/Devices/Gpio/GpioController.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // using System; using System.Runtime.CompilerServices; using Windows.Devices.Gpio.Provider; using Llilum = Microsoft.Llilum.Devices.Gpio; namespace Windows.Devices.Gpio { /// /// Represents the default general-purpose I/O (GPIO) controller for the system. /// public sealed class GpioController { private static readonly GpioController _instance = new GpioController(); internal GpioController() { } /// /// Gets the number of pins on the general-purpose I/O (GPIO) controller. /// /// The number of pins on the GPIO controller. Some pins may not be available in user mode. For /// information about how the pin numbers correspond to physical pins, see the documentation for your /// circuit board. public int PinCount => Llilum.GpioPin.BoardPinCount; /// /// Gets the default general-purpose I/O (GPIO) controller for the system. /// /// The default GPIO controller for the system, or null if the system has no GPIO controller. public static GpioController GetDefault() { return _instance; } /// /// Opens a connection to the specified general-purpose I/O (GPIO) pin in exclusive mode. /// /// The pin number of the GPIO pin that you want to open. Some pins may not be available /// in user mode. For information about how the pin numbers correspond to physical pins, see the /// documentation for your circuit board. /// The opened GPIO pin. public GpioPin OpenPin(int pinNumber) { return OpenPin(pinNumber, GpioSharingMode.Exclusive); } /// /// Opens the specified general-purpose I/O (GPIO) pin in the specified mode. /// /// The pin number of the GPIO pin that you want to open. Some pins may not be available /// in user mode. For information about how the pin numbers correspond to physical pins, see the /// documentation for your circuit board. /// The mode in which you want to open the GPIO pin, which determines whether other /// connections to the pin can be opened while you have the pin open. /// The opened GPIO pin. public GpioPin OpenPin(int pinNumber, GpioSharingMode sharingMode) { GpioPin pin = null; GpioOpenStatus status = GpioOpenStatus.PinUnavailable; if(!TryOpenPin(pinNumber, sharingMode, out pin, out status)) { throw new InvalidOperationException(); } return pin; } /// /// Opens the specified general-purpose I/O (GPIO) pin in the specified mode, and gets a status value that can /// be used to handle a failure to open the pin programmatically. /// /// The pin number of the GPIO pin that you want to open. Some pins may not be available /// in user mode. For information about how the pin numbers correspond to physical pins, see the /// documentation for your circuit board. /// The mode in which you want to open the GPIO pin, which determines whether other /// connections to the pin can be opened while you have the pin open. /// The opened GPIO pin if the open status is GpioOpenStatus.Success; otherwise null. /// An enumeration value that indicates either that the attempt to open the GPIO pin /// succeeded, or the reason that the attempt to open the GPIO pin failed. /// True if the pin could be opened; otherwise false. public bool TryOpenPin(int pinNumber, GpioSharingMode sharingMode, out GpioPin pin, out GpioOpenStatus status) { IGpioPinProvider provider; // Following a builder-like pattern to avoid try-catch on new operator, and having // to call ReleasePin in the catch case pin = new GpioPin(); // Call to the kernel and get the object that implements the pin functions try { provider = new DefaultPinProvider(pinNumber); } catch(InvalidOperationException) { pin = null; status = GpioOpenStatus.PinUnavailable; return false; } // We were able to get a pin provider. Set it here pin.PinProvider = provider; status = GpioOpenStatus.PinOpened; return true; } } } ================================================ FILE: Zelig/Zelig/RunTime/Framework/Windows/Devices/Gpio/GpioEnums.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // namespace Windows.Devices.Gpio { /// /// Describes the modes in which you can open a general-purpose I/O (GPIO) pin. These modes determine whether other /// connections to the GPIO pin can be opened while you have the pin open. /// public enum GpioSharingMode { /// /// Opens the GPIO pin exclusively, so that no other connection to the pin can be opened. /// Exclusive = 0, /// /// Opens the GPIO pin as shared, so that other connections in SharedReadOnly mode to the pin can be opened. /// SharedReadOnly, } /// /// Describes the possible results of opening a pin with the GpioPin.TryOpenPin method. /// public enum GpioOpenStatus { /// /// The GPIO pin was successfully opened. /// PinOpened = 0, /// /// The pin is reserved by the system and is not available to apps that run in user mode. /// PinUnavailable, /// /// The pin is currently open in an incompatible sharing mode. /// SharingViolation, } /// /// Describes whether a general-purpose I/O (GPIO) pin is configured as an input or an output, and how values are /// driven onto the pin. /// public enum GpioPinDriveMode { /// /// Configures the GPIO pin in floating mode, with high impedance. /// If you call the GpioPin.Read method for this pin, the method returns the current state of the pin as /// driven externally. /// If you call the GpioPin.Write method, the method sets the latched output value for the pin. The pin /// takes on this latched output value when the pin is changed to an output. /// Input = 0, /// /// Configures the GPIO pin in strong drive mode, with low impedance. /// If you call the GpioPin.Write method for this pin with a value of GpioPinValue.High, the method /// produces a low-impedance high value for the pin. If you call the GpioPin.Write method for this pin with /// a value of GpioPinValue.Low, the method produces a low-impedance low value for the pin. /// If you call the GpioPin.Read method for this pin, the method returns the value previously written to /// the pin. /// Output, /// /// Configures the GPIO pin in pull-up mode, with high impedance. /// If you call the GpioPin.Read method for this pin, the method returns the current state of the pin as /// driven externally. /// If you call the GpioPin.Write method, the method sets the latched output value for the pin. The pin /// takes on this latched output value when the pin is changed to an output. /// InputPullUp, /// /// Configures the GPIO pin in pull-down mode, with high impedance. /// If you call the GpioPin.Read method for this pin, the method returns the current state of the pin as /// driven externally. /// If you call the GpioPin.Write method, the method sets the latched output value for the pin. The pin /// takes on this latched output value when the pin is changed to an output. /// InputPullDown, /// /// Not supported. /// OutputOpenDrain, /// /// Not supported. /// OutputOpenDrainPullUp, /// /// Not supported. /// OutputOpenSource, /// /// Not supported. /// OutputOpenSourcePullDown, } /// /// Describes the possible values for a general-purpose I/O (GPIO) pin. /// public enum GpioPinValue { /// /// The value of the GPIO pin is low. /// Low = 0, /// /// The value of the GPIO pin is high. /// High, } /// /// Describes the possible types of change that can occur to the value of the general-purpose I/O (GPIO) pin for the /// GpioPin.ValueChanged event. /// public enum GpioPinEdge { /// /// The value of the GPIO pin changed from high to low. /// FallingEdge = 0, /// /// The value of the GPIO pin changed from low to high. /// RisingEdge, } } ================================================ FILE: Zelig/Zelig/RunTime/Framework/Windows/Devices/Gpio/GpioPin.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // using System; using Windows.Devices.Gpio.Provider; using Windows.Foundation; namespace Windows.Devices.Gpio { /// /// Represents a general-purpose I/O (GPIO) pin. /// public sealed class GpioPin : IDisposable { private IGpioPinProvider _provider; private GpioPinDriveMode _driveMode = GpioPinDriveMode.Input; private GpioPinValue _lastOutputValue = GpioPinValue.Low; private TypedEventHandler _callbacks = null; internal GpioPin() { } ~GpioPin() { Dispose(false); } /// /// Occurs when the value of the general-purpose I/O (GPIO) pin changes, either because of an external stimulus /// when the pin is configured as an input, or when a value is written to the pin when the pin is configured as /// an output. /// public event TypedEventHandler ValueChanged { add { ThrowIfDisposed(); var callbacksOld = _callbacks; _callbacks += value; if (callbacksOld == null) { _provider.ValueChanged += HandlePinChangedEvent; } } remove { ThrowIfDisposed(); _callbacks -= value; if( _callbacks == null ) { _provider.ValueChanged -= HandlePinChangedEvent; } } } /// /// Gets or sets the debounce timeout for the general-purpose I/O (GPIO) pin, which is an interval during which /// changes to the value of the pin are filtered out and do not generate ValueChanged events. /// /// The debounce timeout for the GPIO pin, which is an interval during which changes to the value of the /// pin are filtered out and do not generate ValueChanged events. If the length of this interval is /// 0, all changes to the value of the pin generate ValueChanged events. public TimeSpan DebounceTimeout { get { ThrowIfDisposed(); return _provider.DebounceTimeout; } set { ThrowIfDisposed(); _provider.DebounceTimeout = value; } } /// /// Gets the pin number of the general-purpose I/O (GPIO) pin. /// /// The pin number of the GPIO pin. public int PinNumber { get { ThrowIfDisposed(); return _provider.PinNumber; } } /// /// Gets the sharing mode in which the general-purpose I/O (GPIO) pin is open. /// /// The sharing mode in which the GPIO pin is open. public GpioSharingMode SharingMode => GpioSharingMode.Exclusive; internal IGpioPinProvider PinProvider { set { _provider = value; } } /// /// Reads the current value of the general-purpose I/O (GPIO) pin. /// /// The current value of the GPIO pin. If the pin is configured as an output, this value is the last /// value written to the pin. public GpioPinValue Read() { ThrowIfDisposed(); return (GpioPinValue)_provider.Read(); } /// /// Drives the specified value onto the general purpose I/O (GPIO) pin according to the current drive mode for /// the pin if the pin is configured as an output, or updates the latched output value for the pin if the pin is /// configured as an input. /// /// The enumeration value to write to the GPIO pin. /// If the GPIO pin is configured as an output, the method drives the specified value onto the pin /// according to the current drive mode for the pin. /// If the GPIO pin is configured as an input, the method updates the latched output value for the pin. /// The latched output value is driven onto the pin when the configuration for the pin changes to /// output. /// If the pin drive mode is not currently set to output, this will latch /// and drive the signal the when the mode is set. public void Write(GpioPinValue value) { ThrowIfDisposed(); // Remember this value in case we switch drive mode _lastOutputValue = value; if (_driveMode == GpioPinDriveMode.Output) { _provider.Write(value); } } /// /// Gets whether the general-purpose I/O (GPIO) pin supports the specified drive mode. /// /// The drive mode to check for support. /// True if the GPIO pin supports the drive mode that driveMode specifies; otherwise false. If you /// specify a drive mode for which this method returns false when you call SetDriveMode, SetDriveMode /// generates an exception. public bool IsDriveModeSupported(GpioPinDriveMode driveMode) { switch (driveMode) { case GpioPinDriveMode.Input: case GpioPinDriveMode.Output: case GpioPinDriveMode.InputPullUp: case GpioPinDriveMode.InputPullDown: return true; } return false; } /// /// Gets the current drive mode for the general-purpose I/O (GPIO) pin. The drive mode specifies whether the pin /// is configured as an input or an output, and determines how values are driven onto the pin. /// /// An enumeration value that indicates the current drive mode for the GPIO pin. The drive mode /// specifies whether the pin is configured as an input or an output, and determines how values are driven /// onto the pin. public GpioPinDriveMode GetDriveMode() { ThrowIfDisposed(); return _driveMode; } /// /// Sets the drive mode of the general-purpose I/O (GPIO) pin. The drive mode specifies whether the pin is /// configured as an input or an output, and determines how values are driven onto the pin. /// /// An enumeration value that specifies drive mode to use for the GPIO pin. The drive /// mode specifies whether the pin is configured as an input or an output, and determines how values are /// driven onto the pin. public void SetDriveMode(GpioPinDriveMode driveMode) { ThrowIfDisposed(); if (driveMode != _driveMode) { _provider.SetPinDriveMode((GpioDriveMode)driveMode); if (driveMode == GpioPinDriveMode.Output) { _provider.Write(_lastOutputValue); } _driveMode = driveMode; } } /// /// Closes the general-purpose I/O (GPIO) pin and releases the resources associated with it. /// public void Dispose() { if (_provider != null) { Dispose(true); _provider = null; GC.SuppressFinalize(this); } } private void HandlePinChangedEvent(GpioPin sender, GpioPinValueChangedEventArgs eventArgs) { if (_provider != null) { _callbacks?.Invoke(this, eventArgs); } } /// /// Releases internal resources held by the GPIO pin. /// /// True if called from Dispose, false if called from the finalizer. private void Dispose(bool disposing) { if (disposing) { if (_provider != null) { _provider.Dispose(); } } } private void ThrowIfDisposed() { if (_provider == null) { throw new ObjectDisposedException(this.GetType().FullName); } } } } ================================================ FILE: Zelig/Zelig/RunTime/Framework/Windows/Devices/Gpio/GpioPinProvider.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // using System; using Windows.Foundation; namespace Windows.Devices.Gpio.Provider { public interface IGpioPinProvider : IDisposable { event TypedEventHandler ValueChanged; TimeSpan DebounceTimeout { get; set; } int PinNumber { get; } GpioSharingMode SharingMode { get; } bool IsDriveModeSupported(GpioPinDriveMode driveMode); GpioPinDriveMode GetDriveMode(); GpioPinValue Read(); void Write(GpioPinValue value); void SetPinDriveMode(GpioDriveMode driveMode); } public enum ProviderGpioPinEdge { FallingEdge = 0, RisingEdge, } public enum GpioDriveMode { Input = 0, Output, InputPullUp, InputPullDown, OutputOpenDrain, OutputOpenDrainPullUp, OutputOpenSource, OutputOpenSourcePullDown, } } ================================================ FILE: Zelig/Zelig/RunTime/Framework/Windows/Devices/Gpio/GpioPinValueChangedEventArgs.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // namespace Windows.Devices.Gpio { /// /// Provides data about the GpioPin.ValueChanged event that occurs when the value of the general-purpose I/O (GPIO) /// pin changes, either because of an external stimulus when the pin is configured as an input, or when a value is /// written to the pin when the pin in configured as an output. /// public sealed class GpioPinValueChangedEventArgs { private readonly GpioPinEdge _edge; internal GpioPinValueChangedEventArgs(GpioPinEdge edge) { _edge = edge; } /// /// Gets the type of change that occurred to the value of the general-purpose I/O (GPIO) pin for the /// GpioPin.ValueChanged event. /// /// An enumeration value that indicates the type of change that occurred to the value of the GPIO pin for /// the GpioPin.ValueChanged event. public GpioPinEdge Edge => _edge; } } ================================================ FILE: Zelig/Zelig/RunTime/Framework/Windows/Devices/I2c/I2cConnectionSettings.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // namespace Windows.Devices.I2c { /// Represents the connection settings you want to use for an inter-integrated /// circuit (I2C) device. This API is for evaluation purposes only and is subject to change /// or removal. public sealed class I2cConnectionSettings { public I2cConnectionSettings(int slaveAddress) { SlaveAddress = slaveAddress; } /// Gets or sets the bus address of the inter-integrated circuit (I2C) device. /// The bus address of the I2C device. Only 7-bit addressing is supported, so the range of values that are valid is from 8 to 119. public int SlaveAddress { get; set; } public I2cSharingMode SharingMode { get; set; } /// Gets or sets the bus speed to use for connecting to an inter-integrated circuit (I2C) device. The bus speed is the frequency at which to clock the I2C bus when accessing the device. /// The bus speed to use for connecting to anI2C device. public I2cBusSpeed BusSpeed { get; set; } } } ================================================ FILE: Zelig/Zelig/RunTime/Framework/Windows/Devices/I2c/I2cDevice.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // using System; using System.Runtime.CompilerServices; using System.Threading; using Llilum = Microsoft.Llilum.Devices.I2c; namespace Windows.Devices.I2c { public sealed class I2cDevice : IDisposable { private struct I2cChannelContainer { public Llilum.I2cDevice Channel; public object TransactionLock; public bool Exclusive; public int RefCount; } // Initialize this array to the number of I2C channels on this board static I2cChannelContainer[] channels = new I2cChannelContainer[I2cChannelCount()]; // This lock is used for creating and removing channels internal static object channelLock = new object(); // Bus speed constants private const int HIGH_SPEED_FREQUENCY = 400000; private const int LOW_SPEED_FREQUENCY = 100000; private readonly I2cConnectionSettings m_settings; private readonly string m_deviceId; private I2cChannelContainer m_channelContainer; private bool m_disposed; private I2cDevice(I2cChannelContainer channelContainer, string deviceId, I2cConnectionSettings settings) { m_channelContainer = channelContainer; m_deviceId = deviceId; m_settings = settings; m_disposed = false; } /// Closes the connection to the inter-integrated circuit (I2C) device. public void Dispose() { if (!m_disposed) { Dispose(true); GC.SuppressFinalize(this); m_disposed = true; } } private void Dispose(bool disposing) { if (disposing) { // Ensure that channel creation and destruction do not collide lock(channelLock) { if (Interlocked.Decrement(ref m_channelContainer.RefCount) == 0) { // There are no more references to the channel. Release the pins and channel m_channelContainer.Channel.Dispose(); m_channelContainer.Channel = null; } m_disposed = true; } } } /// Gets the connection settings used for communication with the inter-integrated circuit (I2C) device. /// The connection settings used for communication with the inter-integrated circuit (I2C) device. public I2cConnectionSettings ConnectionSettings { get { return m_settings; } } /// /// Gets the plug and play device identifier of the inter-integrated circuit (I2C) bus controller for the device. /// public string DeviceId { get { return m_deviceId; } } /// /// Retrieves an I2cDevice object asynchronously for the inter-integrated circuit (I2C) bus controller that has the specified plug and play device identifier, using the specified connection settings. /// /// Device identifier /// The connection settings to use for communication with the I2C bus controller that deviceId specifies. /// public static /*IAsyncOperation*/I2cDevice FromIdAsync(string deviceId, I2cConnectionSettings settings) { Llilum.II2cChannelInfo channelInfo = GetI2cChannelInfo(deviceId); if(channelInfo == null) { throw new ArgumentException(); } int channelIndex = channelInfo.PortIndex; // Ensure that we do not double-create channels lock (channelLock) { if (channels[channelIndex].Channel != null) { if (channels[channelIndex].Exclusive) { // The user is making a mistake by trying to access an exclusive resource throw new InvalidOperationException("DeviceId is marked as exclusive"); } // The channel is open and we have access to it. Increase the ref count channels[channelIndex].RefCount++; } else { // Perform failing operation first channels[channelIndex].TransactionLock = new object(); // The channel has not been opened. We create it here // If it fails, this will throw Llilum.I2cDevice newChannel = new Llilum.I2cDevice(channelInfo); // Set the new channel frequency if (settings.BusSpeed == I2cBusSpeed.FastMode) { newChannel.Frequency = HIGH_SPEED_FREQUENCY; } else { // Default newChannel.Frequency = LOW_SPEED_FREQUENCY; } newChannel.Open(); channels[channelIndex].Channel = newChannel; channels[channelIndex].Exclusive = (settings.SharingMode == I2cSharingMode.Exclusive); channels[channelIndex].RefCount = 1; } } return new I2cDevice(channels[channelIndex], deviceId, settings); } /// Writes data to the inter-integrated circuit (I2C) bus on which the device is connected, based on the bus address specified in the I2cConnectionSettings object that you used to create the I2cDevice object. /// A buffer that contains the data that you want to write to the I2C device. This data should not include the bus address. public void Write(byte[] buffer) { ThrowIfDisposed(); int transferCount = WriteImpl(buffer, true); CheckAndThrowTransferException(transferCount, buffer.Length); } /// Writes data to the inter-integrated circuit (I2C) bus on which the device is connected, based on the bus address specified in the I2cConnectionSettings object that you used to create the I2cDevice object. /// A buffer that contains the data that you want to write to the I2C device. This data should not include the bus address. public I2cTransferResult WritePartial(byte[] buffer) { ThrowIfDisposed(); I2cTransferResult result = new I2cTransferResult(); int transferCount = WriteImpl(buffer, true); if(transferCount < 0) { // Device not found at given address result.BytesTransferred = 0; result.Status = I2cTransferStatus.SlaveAddressNotAcknowledged; } else if(transferCount < buffer.Length) { // Transfer was interrupted result.BytesTransferred = (uint)transferCount; result.Status = I2cTransferStatus.PartialTransfer; } else { result.BytesTransferred = (uint)transferCount; result.Status = I2cTransferStatus.FullTransfer; } return result; } /// Reads data from the inter-integrated circuit (I2C) bus on which the device is connected into the specified buffer. /// The buffer to which you want to read the data from the I2C bus. The length of the buffer determines how much data to request from the device. public void Read(byte[] buffer) { ThrowIfDisposed(); int transferCount = ReadImpl(buffer, true); CheckAndThrowTransferException(transferCount, buffer.Length); } /// Reads data from the inter-integrated circuit (I2C) bus on which the device is connected into the specified buffer. /// The buffer to which you want to read the data from the I2C bus. The length of the buffer determines how much data to request from the device. public I2cTransferResult ReadPartial(byte[] buffer) { ThrowIfDisposed(); I2cTransferResult result = new I2cTransferResult(); int transferCount = ReadImpl(buffer, true); if (transferCount < 0) { // Device not found at given address result.BytesTransferred = 0; result.Status = I2cTransferStatus.SlaveAddressNotAcknowledged; } else if (transferCount < buffer.Length) { // Transfer was interrupted result.BytesTransferred = (uint)transferCount; result.Status = I2cTransferStatus.PartialTransfer; } else { result.BytesTransferred = (uint)transferCount; result.Status = I2cTransferStatus.FullTransfer; } return result; } /// Performs an atomic operation to write data to and then read data from the inter-integrated circuit (I2C) bus on which the device is connected, and sends a restart condition between the write and read operations. /// A buffer that contains the data that you want to write to the I2C device. This data should not include the bus address. /// The buffer to which you want to read the data from the I2C bus. The length of the buffer determines how much data to request from the device. public void WriteRead(byte[] writeBuffer, byte[] readBuffer) { ThrowIfDisposed(); // Do not send a stop bit on WriteRead for repeated start int transferCount = WriteImpl(writeBuffer, false); CheckAndThrowTransferException(transferCount, writeBuffer.Length); transferCount = ReadImpl(readBuffer, true); CheckAndThrowTransferException(transferCount, readBuffer.Length); } /// Performs an atomic operation to write data to and then read data from the inter-integrated circuit (I2C) bus on which the device is connected, and sends a restart condition between the write and read operations. /// A buffer that contains the data that you want to write to the I2C device. This data should not include the bus address. /// The buffer to which you want to read the data from the I2C bus. The length of the buffer determines how much data to request from the device. public I2cTransferResult WriteReadPartial(byte[] writeBuffer, byte[] readBuffer) { ThrowIfDisposed(); I2cTransferResult result = new I2cTransferResult(); // Do not send a stop bit on WriteRead for repeated start int transferCountWrite = WriteImpl(writeBuffer, false); if(transferCountWrite < writeBuffer.Length) { if(transferCountWrite < 0) { // Device not found at given address result.BytesTransferred = 0; result.Status = I2cTransferStatus.SlaveAddressNotAcknowledged; } else { // Transfer was interrupted result.BytesTransferred = (uint)transferCountWrite; result.Status = I2cTransferStatus.PartialTransfer; } return result; } int transferCountRead = ReadImpl(readBuffer, true); if (transferCountRead < readBuffer.Length) { if (transferCountRead < 0) { // Device not found at given address result.BytesTransferred = 0; result.Status = I2cTransferStatus.SlaveAddressNotAcknowledged; } else { // Transfer was interrupted result.BytesTransferred = (uint)transferCountRead; result.Status = I2cTransferStatus.PartialTransfer; } return result; } result.BytesTransferred = (uint)(transferCountWrite + transferCountRead); result.Status = I2cTransferStatus.FullTransfer; return result; } /// Retrieves an Advanced Query Syntax (AQS) string for all of the inter-integrated circuit (I2C) bus controllers on the system. /// An AQS string for all of the I2C bus controllers on the system, which you can use with the DeviceInformation.FindAllAsync method to get DeviceInformation objects for those bus controllers. public static string GetDeviceSelector() { string[] channels = GetI2cChannels(); string allChannels = ""; if (channels != null) { foreach (string channel in channels) { allChannels += (channel + ";"); } } return allChannels; } /// /// Retrieves an Advanced Query Syntax (AQS) string for the inter-integrated circuit (I2C) bus that has the specified friendly name /// /// A friendly name for the particular I²C bus on a particular hardware platform for which you want to get the AQS string. /// An AQS string for the I²C bus that friendlyName specifies, which you can use with the DeviceInformation.FindAllAsync method to get a DeviceInformation object for that bus. public static string GetDeviceSelector(string friendlyName) { string[] channels = GetI2cChannels(); foreach (string channel in channels) { if (channel.Equals(friendlyName)) { return friendlyName; } } return null; } //--// /// /// Writes the buffer over the I2C channel /// /// Data to write /// Send stop bit, or repeat start /// Number of bytes written private int WriteImpl(byte[] buffer, bool sendStop) { lock(m_channelContainer.TransactionLock) { ChangeFrequencyIfneeded(); return m_channelContainer.Channel.Write(buffer, m_settings.SlaveAddress, 0, buffer.Length, sendStop); } } /// /// Reads from the I2C bus into the buffer /// /// Placeholder for read data /// Send stop bit, or repeat /// Number of bytes read private int ReadImpl(byte[] buffer, bool sendStop) { lock (m_channelContainer.TransactionLock) { ChangeFrequencyIfneeded(); return m_channelContainer.Channel.Read(buffer, m_settings.SlaveAddress, 0, buffer.Length, sendStop); } } /// /// Since channels are shared between devices, we need this helper method to check the /// current channel frequency, and change it if the device being used needs a different one /// private void ChangeFrequencyIfneeded() { int requiredFrequency = (m_settings.BusSpeed == I2cBusSpeed.FastMode) ? HIGH_SPEED_FREQUENCY : LOW_SPEED_FREQUENCY; if (m_channelContainer.Channel.Frequency != requiredFrequency) { m_channelContainer.Channel.Frequency = requiredFrequency; } } /// /// If the object is disposed, it should not be allowed to do anything /// private void ThrowIfDisposed() { if (m_disposed) { throw new ObjectDisposedException(this.GetType().FullName); } } /// /// Throw an exception after an I2C transfer, if necessary /// /// Number of bytes transferred /// Number of bytes that should have been transferred private void CheckAndThrowTransferException(int transferred, int bufferLength) { if (transferred < 0) { throw new Exception("The bus address was not acknowledged."); } else if(transferred < bufferLength) { throw new Exception("The I2C device negatively acknowledged the data transfer before the entire buffer was written."); } } //--// /// /// Gets the number of I2C channels on the current board /// /// Number of I2C channels on the current board private static int I2cChannelCount() { return GetI2cChannels().Length; } //--// [MethodImpl(MethodImplOptions.InternalCall)] private static extern string[] GetI2cChannels(); [MethodImpl(MethodImplOptions.InternalCall)] private static extern Llilum.II2cChannelInfo GetI2cChannelInfo(string busId); } } ================================================ FILE: Zelig/Zelig/RunTime/Framework/Windows/Devices/I2c/I2cEnums.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // namespace Windows.Devices.I2c { public enum I2cBusSpeed { StandardMode, /// A fast speed of 400 kHz. FastMode } /// Describes the modes in which you can connect to an inter-integrated circuit (I2C) /// bus address. These modes determine whether other connections to the I2C bus address can /// be opened while you are connected to the I2C bus address. This API is for evaluation /// purposes only and is subject to change or removal. public enum I2cSharingMode { Exclusive, /// Connects to the I2C bus address in shared mode, so that other connections /// to the I2C bus address can be made while you remain connected. You can perform /// all operations on shared connections, but use such connections with care. When /// multiple client apps change the global state of the I2C device, race conditions /// can result.An example use case for using a shared connection is a sensor that /// obtains readings without changing the state of the device. Shared } /// Describes whether the data transfers that the ReadPartial, WritePartial, or /// WriteReadPartial method performed succeeded, or provides the reason that the transfers /// did not succeed. public enum I2cTransferStatus { FullTransfer, /// The I2C device negatively acknowledged the data transfer before all of /// the data was transferred.For this status code, the value of the I2cTransferResult.BytesTransferred /// member that the method returns is the number of bytes actually transferred. For /// WriteReadPartial, the value is the sum of the number of bytes that the operation /// wrote and the number of bytes that the operation read. PartialTransfer, SlaveAddressNotAcknowledged } public struct I2cTransferResult { public I2cTransferStatus Status; /// The actual number of bytes that the operation actually transferred. /// The following table describes what this value represents for each /// method.MethodDescriptionReadPartialThe actual number of bytes that the read /// operation read into the buffer. If the value of the Status member is /// I2CTransferStatus.PartialTransfer, this value may be less than the number of /// bytes in the buffer that you specified in the buffer parameter. WritePartialThe /// actual number of bytes that the write operation transferred to the I2C device. /// If the value of the Status member is I2CTransferStatus.PartialTransfer, this /// value may be less than the number of bytes in the buffer that you specified in /// the buffer parameter. WriteReadPartial The actual number of bytes that the /// operation transferred, which is the sum of the number of bytes that the operation /// wrote and the number of bytes that the operation read. If the value of the Status /// member is I2CTransferStatus.PartialTransfer, this value may be less than the sum /// of lengths of the buffers that you specified in the writeBuffer and readBuffer /// parameters. public uint BytesTransferred; } } ================================================ FILE: Zelig/Zelig/RunTime/Framework/Windows/Devices/Pwm/DefaultPwmControllerProvider.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // using System; using Windows.Devices.Pwm.Provider; using Llilum = Microsoft.Llilum.Devices.Pwm; namespace Windows.Devices.Pwm { internal class DefaultPwmControllerProvider : IPwmControllerProvider { /// /// Used to keep track of the pin past and present state for UWP /// private class ControllerPin { public Llilum.PwmPin Pin; public bool Enabled; } private readonly Llilum.IPwmChannelInfoUwp m_providerInfo; private ControllerPin[] m_pwmPins; private object m_channelLock; private double m_frequency; public DefaultPwmControllerProvider(Llilum.IPwmChannelInfoUwp pwmInfoUwp) { m_providerInfo = pwmInfoUwp; m_pwmPins = new ControllerPin[m_providerInfo.PwmPinNumbers.Length]; m_channelLock = new object(); } public double ActualFrequency { get { return m_frequency; } } public double MaxFrequency { get { return m_providerInfo.MaxFrequency; } } public double MinFrequency { get { return m_providerInfo.MinFrequency; } } public int PinCount { get { return m_providerInfo.PwmPinNumbers.Length; } } public void AcquirePin(int pin) { int pinIndex = GetPinIndex(pin); if (pinIndex == -1) { throw new ArgumentException(null, nameof(pin)); } lock (m_channelLock) { if (m_pwmPins[pinIndex] == null) { // Try allocating first, to avoid releasing the pin if allocation fails ControllerPin controlPin = new ControllerPin(); Llilum.PwmPin newPin = new Llilum.PwmPin(m_providerInfo.PwmPinNumbers[pinIndex]); // Set frequency to current, and duty cycle to 0 (disabled) int usPeriod = (int)(1000000.0 / ActualFrequency); newPin.SetPeriod(usPeriod); // Initialize the pin to disabled by default newPin.Stop(); controlPin.Pin = newPin; m_pwmPins[pinIndex] = controlPin; } } } public void DisablePin(int pin) { int pinIndex = GetPinIndex(pin); if (pinIndex == -1) { throw new ArgumentException(null, nameof(pinIndex)); } lock (m_channelLock) { if (m_pwmPins[pinIndex] == null) { throw new InvalidOperationException(); } m_pwmPins[pinIndex].Pin.Stop(); m_pwmPins[pinIndex].Enabled = false; } } public void EnablePin(int pin) { int pinIndex = GetPinIndex(pin); if (pinIndex == -1) { throw new ArgumentException(null, nameof(pin)); } lock (m_channelLock) { if (m_pwmPins[pinIndex] == null) { throw new InvalidOperationException(); } m_pwmPins[ pinIndex ].Pin.Start(); m_pwmPins[pinIndex].Enabled = true; } } public void ReleasePin(int pin) { int pinIndex = GetPinIndex(pin); if (pinIndex == -1) { throw new ArgumentException(null, nameof(pin)); } lock (m_channelLock) { if (m_pwmPins[pinIndex] == null) { throw new InvalidOperationException(); } m_pwmPins[pinIndex].Pin.Dispose(); m_pwmPins[pinIndex] = null; } } public double SetDesiredFrequency(double frequency) { // UWP does not have a notion of having a separate frequency per pin // so we need to conform to the API and use the same frequency for all pins m_frequency = frequency; return m_frequency; } public void SetPulseParameters(int pin, double dutyCycle, bool invertPolarity) { int pinIndex = GetPinIndex(pin); if (pinIndex == -1) { throw new ArgumentException(null, nameof(pin)); } if(dutyCycle < 0 || dutyCycle > 1) { throw new ArgumentOutOfRangeException(nameof(dutyCycle)); } lock (m_channelLock) { if (m_pwmPins[pinIndex] == null) { throw new InvalidOperationException(); } // If polarity is inverted, inverted duty cycle is 100% - dutyCycle if(invertPolarity) { dutyCycle = 1.0 - dutyCycle; } m_pwmPins[pinIndex].Pin.SetDutyCycle((float)dutyCycle); } } /// /// Get the index of the pin in m_pwmPins /// /// Real pin number /// Pin index private int GetPinIndex(int pin) { for(int i = m_providerInfo.PwmPinNumbers.Length - 1; i >= 0; i--) { if(m_providerInfo.PwmPinNumbers[i] == pin) { return i; } } return -1; } } } ================================================ FILE: Zelig/Zelig/RunTime/Framework/Windows/Devices/Pwm/IPwmControllerProvider.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // namespace Windows.Devices.Pwm.Provider { public interface IPwmControllerProvider { double ActualFrequency { get; } double MaxFrequency { get; } double MinFrequency { get; } int PinCount { get; } double SetDesiredFrequency(double frequency); void AcquirePin(int pin); void ReleasePin(int pin); void EnablePin(int pin); void DisablePin(int pin); void SetPulseParameters(int pin, double dutyCycle, bool invertPolarity); } } ================================================ FILE: Zelig/Zelig/RunTime/Framework/Windows/Devices/Pwm/IPwmProvider.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // using System.Collections.Generic; namespace Windows.Devices.Pwm.Provider { public interface IPwmProvider { IList GetControllers(); } } ================================================ FILE: Zelig/Zelig/RunTime/Framework/Windows/Devices/Pwm/PwmController.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // using System; using System.Collections.Generic; using System.Runtime.CompilerServices; using Windows.Devices.Pwm.Provider; using Llilum = Microsoft.Llilum.Devices.Pwm; namespace Windows.Devices.Pwm { public sealed class PwmController { internal IPwmControllerProvider m_pwmControllerProvider; private PwmController(IPwmControllerProvider provider) { m_pwmControllerProvider = provider; } public double ActualFrequency { get { return m_pwmControllerProvider.ActualFrequency; } } public double MaxFrequency { get { return m_pwmControllerProvider.MaxFrequency; } } public double MinFrequency { get { return m_pwmControllerProvider.MinFrequency; } } public int PinCount { get { return m_pwmControllerProvider.PinCount; } } public double SetDesiredFrequency(double desiredFrequency) { return m_pwmControllerProvider.SetDesiredFrequency(desiredFrequency); } public PwmPin OpenPin(int pinNumber) { // If the channel cannot be acquired, this will throw m_pwmControllerProvider.AcquirePin(pinNumber); return new PwmPin(this, pinNumber); } // TODO: Implement as IAsyncOperation public static /*IAsyncOperation*/PwmController GetDefaultAsync() { return new PwmController(new DefaultPwmControllerProvider(GetPwmProviderInfo())); } //TODO: public static IAsyncOperation> GetControllersAsync(IPwmProvider provider) public static IList GetControllersAsync(IPwmProvider provider) { List controllers = new List(); foreach(var controller in provider.GetControllers()) { controllers.Add(new PwmController(controller)); } return controllers; } [MethodImpl(MethodImplOptions.InternalCall)] internal static extern Llilum.IPwmChannelInfoUwp GetPwmProviderInfo(); } } ================================================ FILE: Zelig/Zelig/RunTime/Framework/Windows/Devices/Pwm/PwmEnums.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // namespace Windows.Devices.Pwm { public enum PwmPulsePolarity { ActiveHigh = 0, ActiveLow, } } ================================================ FILE: Zelig/Zelig/RunTime/Framework/Windows/Devices/Pwm/PwmPin.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // using System; namespace Windows.Devices.Pwm { public sealed class PwmPin : IDisposable { private readonly int m_pinNumber; private PwmController m_pwmController; private double m_dutyCycle; internal PwmPin(PwmController controller, int pinNumber) { m_pwmController = controller; m_pinNumber = pinNumber; // Default to 50% duty cycle m_dutyCycle = 0.5; } ~PwmPin() { Dispose(false); } public PwmPulsePolarity Polarity { get; set; } public PwmController Controller { get { return m_pwmController; } } public bool IsStarted { get; private set; } public double GetActiveDutyCyclePercentage() { ThrowIfDisposed(); return m_dutyCycle; } public void SetActiveDutyCyclePercentage(double dutyCyclePercentage) { ThrowIfDisposed(); if(dutyCyclePercentage < 0 || dutyCyclePercentage > 1) { throw new ArgumentOutOfRangeException(nameof(dutyCyclePercentage)); } m_dutyCycle = dutyCyclePercentage; m_pwmController.m_pwmControllerProvider.SetPulseParameters(m_pinNumber, dutyCyclePercentage, (Polarity == PwmPulsePolarity.ActiveLow)); } public void Start() { ThrowIfDisposed(); // In case polarity changed after setting duty cycle, update the duty cycle accordingly SetActiveDutyCyclePercentage(m_dutyCycle); m_pwmController.m_pwmControllerProvider.EnablePin(m_pinNumber); IsStarted = true; } public void Stop() { ThrowIfDisposed(); m_pwmController.m_pwmControllerProvider.DisablePin(m_pinNumber); IsStarted = false; } public void Dispose() { Dispose(true); } private void ThrowIfDisposed() { if (m_pwmController == null) { throw new ObjectDisposedException(null); } } private void Dispose(bool disposing) { if (m_pwmController != null) { if (disposing) { m_pwmController.m_pwmControllerProvider.ReleasePin(m_pinNumber); } m_pwmController = null; } } } } ================================================ FILE: Zelig/Zelig/RunTime/Framework/Windows/Devices/SerialCommunication/SerialCommunicationEnums.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // namespace Windows.Devices.SerialCommunication { public enum SerialError { Frame = 0, BufferOverrun, ReceiveFull, ReceiveParity, TransmitFull, } public enum SerialHandshake { None = 0, RequestToSend, XOnXOff, RequestToSendXOnXOff, } public enum SerialParity { None = 0, Odd, Even, Mark, Space, } public enum SerialPinChange { BreakSignal = 0, CarrierDetect, ClearToSend, DataSetReady, RingIndicator, } public enum SerialStopBitCount { One = 1, Two, OnePointFive, } } ================================================ FILE: Zelig/Zelig/RunTime/Framework/Windows/Devices/SerialCommunication/SerialCommunicationEventArgs.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // namespace Windows.Devices.SerialCommunication { public sealed class PinChangedEventArgs { public PinChangedEventArgs(SerialPinChange pinChange) { PinChange = pinChange; } public SerialPinChange PinChange { get; } } public sealed class ErrorReceivedEventArgs { public ErrorReceivedEventArgs(SerialError error) { Error = error; } public SerialError Error { get; } } } ================================================ FILE: Zelig/Zelig/RunTime/Framework/Windows/Devices/SerialCommunication/SerialCommunicationInputStream.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // #define BUG_67_ACTIVE using System; using System.Runtime; using System.Runtime.InteropServices; using System.IO.Ports; using System.Threading.Tasks; namespace Windows.Devices.SerialCommunication { using Windows.Foundation; using Windows.Storage.Streams; using Windows.Internal; internal class SerialInputStream : IInputStream { private SerialPort m_serialPort; public SerialInputStream(SerialPort serialPort) { m_serialPort = serialPort; } public void Dispose() { Dispose(true); } private void Dispose(bool disposing) { if(disposing) { m_serialPort?.Dispose(); } m_serialPort = null; } public IAsyncOperationWithProgress ReadAsync(IBuffer buffer, uint count, InputStreamOptions options) { EnsurePortOpen(); ByteBuffer memBuffer = (ByteBuffer)buffer; if (memBuffer == null || count > memBuffer.Capacity) { memBuffer = new ByteBuffer(count); } try { int readBytes; #if(BUG_67_ACTIVE) readBytes = m_serialPort.Read(memBuffer.Data, 0, (int)count); if(options != InputStreamOptions.Partial) { while(readBytes < count) { readBytes += m_serialPort.Read(memBuffer.Data, readBytes, ((int)count - readBytes)); } } memBuffer.Length = (uint)readBytes; return new SynchronousOperationWithProgress(memBuffer); #else // BUG: https://github.com/NETMF/llilum/issues/67 // TODO: This task causes an exception in the Llilum compiler. Need to resolve Task readTask = new Task(() => { readBytes = m_serialPort.Read(memBuffer.Data, 0, (int)count); if (options != InputStreamOptions.Partial) { while (readBytes < count) { readBytes += m_serialPort.Read(memBuffer.Data, readBytes, ((int)count - readBytes)); } } memBuffer.Length = (uint)readBytes; return memBuffer; }); readTask.Start(); return WindowsRuntimeSystemExtensions.AsAsyncOperationWithProgress(readTask); #endif } catch (Exception ex) { return new SynchronousOperationWithProgress(ex); } } private void EnsurePortOpen() { if (!m_serialPort.IsOpen) { m_serialPort.Open(); } } } } ================================================ FILE: Zelig/Zelig/RunTime/Framework/Windows/Devices/SerialCommunication/SerialCommunicationOutputStream.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // using System; using System.Runtime.InteropServices; using System.IO.Ports; namespace Windows.Devices.SerialCommunication { using Windows.Foundation; using Windows.Storage.Streams; using Windows.Internal; internal class SerialOutputStream : IOutputStream { private SerialPort m_serialPort; public SerialOutputStream(SerialPort serialPort) { m_serialPort = serialPort; } public void Dispose() { Dispose(true); } private void Dispose(bool disposing) { if (disposing) { m_serialPort?.Dispose(); } m_serialPort = null; } public IAsyncOperation FlushAsync() { return new SynchronousOperation(true); } public IAsyncOperationWithProgress WriteAsync(IBuffer buffer) { EnsurePortOpen(); ByteBuffer bufferImpl = (ByteBuffer)buffer; uint length = bufferImpl.Length; try { m_serialPort.Write(bufferImpl.Data, 0, (int)length); return new SynchronousOperationWithProgress(length); } catch(Exception ex) { return new SynchronousOperationWithProgress(ex); } } private void EnsurePortOpen() { if (!m_serialPort.IsOpen) { m_serialPort.Open(); } } } } ================================================ FILE: Zelig/Zelig/RunTime/Framework/Windows/Devices/SerialCommunication/SerialDevice.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // using System; using System.Runtime.InteropServices; using System.IO.Ports; namespace Windows.Devices.SerialCommunication { using Windows.Internal; using Windows.Foundation; using Windows.Storage.Streams; using Ports = global::System.IO.Ports; public sealed class SerialDevice : IDisposable { private SerialPort m_serialPort; private SerialInputStream m_inputStream; private SerialOutputStream m_outputStream; internal SerialDevice(SerialPort serialPort) { m_serialPort = serialPort; m_serialPort.ErrorReceived += CatchErrorEvents; m_serialPort.PinChanged += CatchPinChangedEvents; m_inputStream = new SerialInputStream(m_serialPort); m_outputStream = new SerialOutputStream(m_serialPort); } public event TypedEventHandler ErrorReceived; public event TypedEventHandler PinChanged; public bool IsDataTerminalReadyEnabled { get { return m_serialPort.DtrEnable; } set { m_serialPort.DtrEnable = value; } } public ushort DataBits { get { return (ushort)m_serialPort.DataBits; } set { m_serialPort.DataBits = value; } } public SerialHandshake Handshake { get { return (SerialHandshake)m_serialPort.Handshake; } set { m_serialPort.Handshake = (Handshake)value; } } public bool BreakSignalState { get { return m_serialPort.BreakState; } set { m_serialPort.BreakState = value; } } public uint BaudRate { get { return (uint)m_serialPort.BaudRate; } set { m_serialPort.BaudRate = (int)value; } } public TimeSpan WriteTimeout { get { return new TimeSpan(m_serialPort.WriteTimeout); } set { m_serialPort.WriteTimeout = (int)value.TotalMilliseconds; } } public SerialStopBitCount StopBits { get { return (SerialStopBitCount)m_serialPort.StopBits; } set { m_serialPort.StopBits = (StopBits)value; } } public TimeSpan ReadTimeout { get { return new TimeSpan(m_serialPort.ReadTimeout); } set { m_serialPort.ReadTimeout = (int)value.TotalMilliseconds; } } public SerialParity Parity { get { return (SerialParity)m_serialPort.Parity; } set { m_serialPort.Parity = (Parity)value; } } public bool IsRequestToSendEnabled { get { return m_serialPort.RtsEnable; } set { m_serialPort.RtsEnable = value; } } public uint BytesReceived => (uint)m_serialPort.BytesToRead; public bool CarrierDetectState => m_serialPort.CDHolding; public bool ClearToSendState => m_serialPort.CtsHolding; public bool DataSetReadyState => m_serialPort.DsrHolding; public IInputStream InputStream => m_inputStream; public IOutputStream OutputStream => m_outputStream; public string PortName => m_serialPort.PortName; public ushort UsbProductId { get { throw new NotImplementedException(); } } public ushort UsbVendorId { get { throw new NotImplementedException(); } } public static string GetDeviceSelector() { string[] ports = SerialPort.GetPortNames(); if(ports == null || ports.Length == 0) { return null; } return ports[0]; } public static string GetDeviceSelector(string portName) { return portName; } public static string GetDeviceSelectorFromUsbVidPid(ushort vendorId, ushort productId) { throw new NotImplementedException(); } public static IAsyncOperation FromIdAsync(string deviceId) { try { SerialPort port = new SerialPort(deviceId); SerialDevice device = new SerialDevice(port); return new SynchronousOperation(device); } catch(Exception ex) { return new SynchronousOperation(ex); } } void Dispose(bool disposing) { if (m_serialPort != null) { if (disposing) { m_outputStream.Dispose(); m_inputStream.Dispose(); m_serialPort.Dispose(); } m_serialPort = null; } } public void Dispose() { Dispose(true); } private void CatchErrorEvents(object src, SerialErrorReceivedEventArgs e) { TypedEventHandler eventHandler = ErrorReceived; SerialPort serialPort = m_serialPort; if ((eventHandler != null) && (serialPort != null)) { lock (serialPort) { if (serialPort.IsOpen) { eventHandler(this, GetErrorReceivedEventArgs(e)); } } } } private void CatchPinChangedEvents(object src, SerialPinChangedEventArgs e) { TypedEventHandler eventHandler = PinChanged; SerialPort serialPort = m_serialPort; if ((eventHandler != null) && (serialPort != null)) { lock (serialPort) { if (serialPort.IsOpen) { eventHandler(this, GetPinChangedEventArgs(e)); } } } } private ErrorReceivedEventArgs GetErrorReceivedEventArgs(SerialErrorReceivedEventArgs e) { ErrorReceivedEventArgs args; switch (e.EventType) { case Ports.SerialError.TXFull: args = new ErrorReceivedEventArgs(SerialError.TransmitFull); break; case Ports.SerialError.RXOver: args = new ErrorReceivedEventArgs(SerialError.ReceiveFull); break; case Ports.SerialError.RXParity: args = new ErrorReceivedEventArgs(SerialError.ReceiveParity); break; case Ports.SerialError.Overrun: args = new ErrorReceivedEventArgs(SerialError.BufferOverrun); break; case Ports.SerialError.Frame: args = new ErrorReceivedEventArgs(SerialError.Frame); break; default: throw new NotImplementedException(); } return args; } private PinChangedEventArgs GetPinChangedEventArgs(SerialPinChangedEventArgs e) { PinChangedEventArgs args; switch (e.EventType) { case Ports.SerialPinChange.Break: args = new PinChangedEventArgs(SerialPinChange.BreakSignal); break; case Ports.SerialPinChange.CDChanged: args = new PinChangedEventArgs(SerialPinChange.CarrierDetect); break; case Ports.SerialPinChange.CtsChanged: args = new PinChangedEventArgs(SerialPinChange.ClearToSend); break; case Ports.SerialPinChange.DsrChanged: args = new PinChangedEventArgs(SerialPinChange.DataSetReady); break; case Ports.SerialPinChange.Ring: args = new PinChangedEventArgs(SerialPinChange.RingIndicator); break; default: throw new NotImplementedException(); } return args; } } } ================================================ FILE: Zelig/Zelig/RunTime/Framework/Windows/Devices/Spi/SpiBusInfo.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // using System.Collections.Generic; namespace Windows.Devices.Spi { public sealed class SpiBusInfo { // This needs to be marked as internal so the end user cannot instantiate it internal SpiBusInfo() { } /// /// Gets the number of chip select lines available on the bus. /// /// Number of chip select lines. public int ChipSelectLineCount { get; internal set; } /// /// Maximum clock cycle frequency of the bus. /// /// The clock cycle in Hz. public int MaxClockFrequency { get; internal set; } /// /// Minimum clock cycle frequency of the bus. /// /// The clock cycle in Hz. public int MinClockFrequency { get; internal set; } /// /// Gets the bit lengths that can be used on the bus for transmitting data. /// /// The supported data lengths. /// // BUGBUG: TODO TODO: implement IReadOnlyList public /*IReadOnlyList*/ List SupportedDataBitLengths { get; internal set; } } } ================================================ FILE: Zelig/Zelig/RunTime/Framework/Windows/Devices/Spi/SpiChannel.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // using System; namespace Windows.Devices.Spi.Provider { public abstract class SpiChannel : IDisposable { public abstract void SetupPins(int mosiPin, int misoPin, int sclPin, int csPin, bool useAlternateCsPin, bool activeLowCS ); public abstract void SetupChannel(int bits, int mode, bool isSlave); public abstract void SetupTiming(int frequencyInHz, int setupTime, int holdTime); public abstract void WriteRead( byte[ ] writeBuffer, byte[ ] readBuffer, int startReadOffset ); public abstract void Dispose( ); } } ================================================ FILE: Zelig/Zelig/RunTime/Framework/Windows/Devices/Spi/SpiConnectionSettings.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // namespace Windows.Devices.Spi { public sealed class SpiConnectionSettings { /// /// Initializes new instance of SpiConnectionSettings. /// /// The chip select line on which the connection will be made. public SpiConnectionSettings(int chipSelectLine) { ChipSelectLine = chipSelectLine; // These are the default values as per IoT SPI WinRT Spec ClockFrequency = 4000000; DataBitLength = 8; Mode = SpiMode.Mode0; SharingMode = SpiSharingMode.Exclusive; } /// /// Gets or sets the chip select line for the connection to the SPI device. /// /// The chip select line. public int ChipSelectLine { get; set; } /// /// Gets or sets the clock frequency for the connection. /// /// Value of the clock frequency in Hz. public int ClockFrequency { get; set; } /// /// Gets or sets the bit length for data on this connection. /// /// The data bit length. public int DataBitLength { get; set; } /// /// Gets or sets the SpiMode for this connection. /// /// The communication mode. public SpiMode Mode { get; set; } /// /// Gets or sets the sharing mode for the SPI connection. /// /// The sharing mode. public SpiSharingMode SharingMode { get; set; } } } ================================================ FILE: Zelig/Zelig/RunTime/Framework/Windows/Devices/Spi/SpiDevice.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // using System; using System.Collections.Generic; using System.Runtime.CompilerServices; using Llilum = Microsoft.Llilum.Devices.Spi; namespace Windows.Devices.Spi { public sealed class SpiDevice : IDisposable { // Connection private bool m_disposed; private readonly Llilum.SpiDevice m_channel; private readonly SpiConnectionSettings m_connectionSettings; private readonly String m_deviceId; /// /// Private SpiDevice constructor /// internal SpiDevice(string busId, SpiConnectionSettings settings, Llilum.SpiDevice channel) { m_deviceId = busId; m_connectionSettings = settings; m_channel = channel; } ~SpiDevice() { Dispose(false); } /// /// Closes resources associated with this SPI device /// public void Dispose() { if (!m_disposed) { Dispose(true); GC.SuppressFinalize(this); m_disposed = true; } } /// /// Disposes of all resources associated with this SPI device /// /// True if called from Dispose, false if called from the finalizer. private void Dispose(bool disposing) { if (disposing) { m_channel.Dispose(); } } /// /// Opens a device with the connection settings provided. /// /// The id of the bus. /// The connection settings. /// The SPI device requested. /// [RemoteAsync] public static SpiDevice FromIdAsync(string busId, SpiConnectionSettings settings) { Llilum.ISpiChannelInfoUwp channelInfoUwp = GetSpiChannelInfo(busId); if (channelInfoUwp == null) { throw new InvalidOperationException(); } Llilum.ISpiChannelInfo channelInfo = channelInfoUwp.ChannelInfo; if (channelInfo == null) { throw new InvalidOperationException(); } // This will throw if it fails Llilum.SpiDevice spiChannel = new Llilum.SpiDevice(channelInfo, settings.ChipSelectLine, false); spiChannel.ClockFrequency = settings.ClockFrequency; spiChannel.DataBitLength = settings.DataBitLength; spiChannel.Mode = (Llilum.SpiMode)settings.Mode; spiChannel.Open(); return new SpiDevice(busId, settings, spiChannel); } /// /// Gets the connection settings for the device. /// /// The connection settings. public SpiConnectionSettings ConnectionSettings { get { return m_connectionSettings; } } /// /// Gets the unique ID associated with the device. /// /// The ID. public string DeviceId { get { return m_deviceId; } } /// /// Retrieves the info about a certain bus. /// /// The id of the bus. /// The bus info requested. public static SpiBusInfo GetBusInfo(string busId) { Llilum.ISpiChannelInfoUwp channelInfo = GetSpiChannelInfo(busId); if (channelInfo == null) { return null; } var supportedDataBitLengths = new List() { 8, }; if (channelInfo.Supports16) { supportedDataBitLengths.Add(16); } return new SpiBusInfo() { ChipSelectLineCount = channelInfo.ChipSelectLines, MaxClockFrequency = channelInfo.MaxFreq, MinClockFrequency = channelInfo.MinFreq, SupportedDataBitLengths = supportedDataBitLengths, }; } /// /// Gets all the SPI buses found on the system. /// /// String containing all the buses found on the system. /// [Overload("GetDeviceSelector")] public static string GetDeviceSelector() { string[] channels = GetSpiChannels(); string allChannels = ""; if (channels != null) { foreach (string channel in channels) { allChannels += (channel + ";"); } } return allChannels; } /// /// Gets all the SPI buses found on the system that match the input parameter. /// /// Input parameter specifying an identifying name for the desired bus. This usually corresponds to a name on the schematic. /// String containing all the buses that have the input in the name. public static string GetDeviceSelector(string friendlyName) { // UWP prescribes returning the channels as one single string that looks like the following: "CH1;CH2;" string[] channels = GetSpiChannels(); foreach (string channel in channels) { if (channel.Equals(friendlyName)) { return friendlyName; } } return null; } /// /// Reads from the connected device. /// /// Array containing data read from the device public void Read(byte[] buffer) { // Read sends buffer.Length 0s, and places read values into buffer if (buffer != null && buffer.Length > 0) { m_channel.Read(buffer, 0, buffer.Length); } } /// /// Transfer data using a full duplex communication system. /// /// Array containing data to write to the device. /// Array containing data read from the device. public void TransferFullDuplex(byte[] writeBuffer, byte[] readBuffer) { if (writeBuffer != null && writeBuffer.Length > 0) { int readOffset = writeBuffer.Length; if (readBuffer != null) { // If the read buffer is smaller than the write buffer, we want to read // the last part of the transmission. Otherwise, read from the start readOffset = writeBuffer.Length - readBuffer.Length; if (readOffset < 0) { readOffset = 0; } } m_channel.WriteRead(writeBuffer, 0, writeBuffer.Length, readBuffer, 0, readBuffer.Length, readOffset); } } /// /// Transfer data sequentially to the device. /// /// Array containing data to write to the device. /// Array containing data read from the device. public void TransferSequential(byte[] writeBuffer, byte[] readBuffer) { Write(writeBuffer); Read(readBuffer); } /// /// Writes to the connected device. /// /// Array containing the data to write to the device. public void Write(byte[] buffer) { if (buffer != null && buffer.Length > 0) { m_channel.Write(buffer, 0, buffer.Length); } } //--// [MethodImpl(MethodImplOptions.InternalCall)] private static extern Llilum.ISpiChannelInfoUwp GetSpiChannelInfo(string busId); [MethodImpl(MethodImplOptions.InternalCall)] private static extern string[] GetSpiChannels(); } } ================================================ FILE: Zelig/Zelig/RunTime/Framework/Windows/Devices/Spi/SpiEnums.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // namespace Windows.Devices.Spi { /// /// Defines the SPI communication mode. This API is for evaluation purposes only and is subject to change or removal. /// public enum SpiMode { /// /// CPOL = 0, CPHA = 0. /// Mode0 = 0, /// /// CPOL = 0, CPHA = 1. /// Mode1 = 1, /// /// CPOL = 1, CPHA = 0. /// Mode2 = 2, /// /// CPOL = 1, CPHA = 1. /// Mode3 = 3 } /// /// Defines the sharing mode for the SPI bus. This API is for evaluation purposes only and is subject to change or removal. /// public enum SpiSharingMode { /// /// SPI bus segment is not shared. /// Exclusive = 0, /// /// SPI bus is shared. /// Shared = 1 } } ================================================ FILE: Zelig/Zelig/RunTime/Framework/Windows/Foundation/Delegates.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // namespace Windows.Foundation { /// /// Represents a method that handles the completed event of an asynchronous action. /// /// The asynchronous action. /// One of the enumeration values. public delegate void AsyncActionCompletedHandler(IAsyncAction asyncInfo, AsyncStatus asyncStatus); /// /// Represents a method that handles the completed event of an asynchronous operation. /// /// /// /// public delegate void AsyncOperationCompletedHandler(IAsyncOperation asyncInfo, AsyncStatus asyncStatus); /// Represents a method that handles progress update events of an asynchronous operation that provides progress updates. /// The result. /// The progress information. /// The asynchronous operation. /// The progress information. public delegate void AsyncOperationProgressHandler(IAsyncOperationWithProgress asyncInfo, TProgress progressInfo); /// /// Represents a method that handles the completed event of an asynchronous operation with a completion handler. /// /// /// /// /// public delegate void AsyncOperationWithProgressCompletedHandler(IAsyncOperationWithProgress asyncInfo, AsyncStatus asyncStatus); /// /// Represents a method that handles general events. /// /// The event source. /// The event data. If there is no event data, this parameter will be null. /// /// public delegate void TypedEventHandler(TSender sender, TResult args); } ================================================ FILE: Zelig/Zelig/RunTime/Framework/Windows/Foundation/Enums.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // namespace Windows.Foundation { /// /// Specifies the status of an asynchronous operation. /// public enum AsyncStatus { /// /// The operation has started. /// Started = 0, /// /// The operation has completed. /// Completed, /// /// The operation was canceled. /// Canceled, /// /// The operation has encountered an error. /// Error, } } ================================================ FILE: Zelig/Zelig/RunTime/Framework/Windows/Foundation/IAsyncAction.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // namespace Windows.Foundation { /// /// Represents an asynchronous action. This is the return type for many Windows Runtime asynchronous methods that /// don't have a result object, and don't report ongoing progress. /// public interface IAsyncAction : IAsyncInfo { /// /// Returns the results of the action. /// /// /// The interface definition of this method has a void return, and void is what methods that use the /// default IAsyncAction behavior will return after completing, when an awaitable syntax is used. /// If you want the method to return a result you probably should be using IAsyncOperation{TResult} /// instead. For IAsyncAction, any added logic should be in the Completed implementation, not GetResults. /// void GetResults(); /// /// Gets or sets the method that handles the action completed notification. /// /// The method that handles the notification. /// /// The Windows Runtime enforces that this property can only be set once on an action. /// Generally, a completed IAsyncAction method called using language-specific awaitable syntax does /// nothing further than to return null when it completes. /// If you're implementing IAsyncAction, then the set implementation of Completed should store the /// handler, and the surrounding logic should invoke it when Close is called. The implementation should set /// the asyncStatus parameter of invoked callbacks appropriately if there is a Cancel call, Status is not /// Completed, errors occurred, and so on. /// AsyncActionCompletedHandler Completed { get; set; } } } ================================================ FILE: Zelig/Zelig/RunTime/Framework/Windows/Foundation/IAsyncInfo.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // using System; using System.Threading; namespace Windows.Foundation { /// /// Supports asynchronous actions and operations. IAsyncInfo is a base interface for IAsyncAction, /// IAsyncActionWithProgress{TProgress}, IAsyncOperation{TResult} and IAsyncOperationWithProgress{TResult,TProgress}, /// each of which support combinations of return type and progress for an asynchronous method. /// public interface IAsyncInfo { /// /// Gets a string that describes an error condition of the asynchronous operation. /// /// /// The error string. /// Exception ErrorCode { get; } /// /// Gets the handle of the asynchronous operation. /// /// /// The handle of the asynchronous operation. /// uint Id { get; } /// /// Gets a value that indicates the status of the asynchronous operation. /// /// /// The status of the operation, as a value of the enumeration. A value of Completed indicates that the method /// has returned. The Started value represents a transition state before any of the other 3 final results /// (Completed, Error, Canceled) can be determined by the method's invocation. /// AsyncStatus Status { get; } /// /// Cancels the asynchronous operation. /// void Cancel(); /// /// Closes the asynchronous operation. /// void Close(); } internal static class AsyncInfoHelper { private static int m_actionId = 0; public static uint GetNextActionId() { return (uint)Interlocked.Increment(ref m_actionId); } } } ================================================ FILE: Zelig/Zelig/RunTime/Framework/Windows/Foundation/IAsyncOperation.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // using System; namespace Windows.Foundation { /// Represents an asynchronous operation, which returns a result upon completion. This is the return type for many Windows Runtime asynchronous methods that have results but don't report progress. /// The type of the result. public interface IAsyncOperation : IAsyncInfo { AsyncOperationCompletedHandler Completed { get; set; } /// Returns the results of the operation. /// The results of the operation. TResult GetResults(); } } ================================================ FILE: Zelig/Zelig/RunTime/Framework/Windows/Foundation/IAsyncOperationWithProgress.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // namespace Windows.Foundation { public interface IAsyncOperationWithProgress : IAsyncInfo { AsyncOperationProgressHandler Progress { get; set; } /// Gets or sets the method that handles the operation completed notification. /// The method that handles the notification. AsyncOperationWithProgressCompletedHandler Completed { get; set; } /// Returns the results of the operation. /// The results of the operation. TResult GetResults(); } } ================================================ FILE: Zelig/Zelig/RunTime/Framework/Windows/Internal/AsyncActionFromTask.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // using System; using System.Threading; using System.Threading.Tasks; using Windows.Foundation; namespace Windows.Internal { public sealed class AsyncActionFromTask : IAsyncAction { private readonly Task m_task; private AsyncActionCompletedHandler m_completedHandler; public AsyncActionFromTask(Task task) { m_task = task; } public AsyncActionCompletedHandler Completed { get { return m_completedHandler; } set { if (Interlocked.CompareExchange(ref m_completedHandler, value, null) != null) { throw new InvalidOperationException("Completed handler may only be set once."); } m_task.ContinueWith(task => m_completedHandler(this, Status)); } } public Exception ErrorCode { get { return m_task.Exception; } } public uint Id => (uint)m_task.Id; public AsyncStatus Status { get { switch (m_task.Status) { case TaskStatus.RanToCompletion: return AsyncStatus.Completed; case TaskStatus.Canceled: return AsyncStatus.Canceled; case TaskStatus.Faulted: return AsyncStatus.Error; default: return AsyncStatus.Started; } } } public void Cancel() { throw new NotImplementedException(); } public void Close() { m_task.Dispose(); } public void GetResults() { } public Task Task { get { return m_task; } } } } ================================================ FILE: Zelig/Zelig/RunTime/Framework/Windows/Internal/AsyncOperationFromTask.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // using System; using System.Threading; using System.Threading.Tasks; using Windows.Foundation; namespace Windows.Internal { public sealed class AsyncOperationFromTask : IAsyncOperation { private readonly Task m_task; private AsyncOperationCompletedHandler m_completedHandler; public AsyncOperationFromTask(Task task) { m_task = task; } public AsyncOperationCompletedHandler Completed { get { return m_completedHandler; } set { if (Interlocked.CompareExchange(ref m_completedHandler, value, null) != null) { throw new InvalidOperationException("Completed handler may only be set once."); } m_task.ContinueWith(task => m_completedHandler(this, Status)); } } public Exception ErrorCode { get { return m_task.Exception; } } public uint Id => (uint)m_task.Id; public AsyncStatus Status { get { switch (m_task.Status) { case TaskStatus.RanToCompletion: return AsyncStatus.Completed; case TaskStatus.Canceled: return AsyncStatus.Canceled; case TaskStatus.Faulted: return AsyncStatus.Error; default: return AsyncStatus.Started; } } } public void Cancel() { throw new NotImplementedException(); } public void Close() { m_task.Dispose(); } public T GetResults() { return m_task.Result; } public Task Task { get { return m_task; } } } } ================================================ FILE: Zelig/Zelig/RunTime/Framework/Windows/Internal/AsyncOperationWithProgressFromTask.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // using System; using System.Threading; using System.Threading.Tasks; using Windows.Foundation; namespace Windows.Internal { public sealed class AsyncOperationWithProgressFromTask : IAsyncOperationWithProgress { private readonly Task m_task; private AsyncOperationWithProgressCompletedHandler m_completedHandler; public AsyncOperationWithProgressFromTask(Task task) { m_task = task; } public AsyncOperationWithProgressCompletedHandler Completed { get { return m_completedHandler; } set { if (Interlocked.CompareExchange(ref m_completedHandler, value, null) != null) { throw new InvalidOperationException("Completed handler may only be set once."); } m_task.ContinueWith(task => m_completedHandler(this, Status)); } } public AsyncOperationProgressHandler Progress { get; set; } public Exception ErrorCode { get { return m_task.Exception; } } public uint Id => (uint)m_task.Id; public AsyncStatus Status { get { switch (m_task.Status) { case TaskStatus.RanToCompletion: return AsyncStatus.Completed; case TaskStatus.Canceled: return AsyncStatus.Canceled; case TaskStatus.Faulted: return AsyncStatus.Error; default: return AsyncStatus.Started; } } } public void Cancel() { throw new NotImplementedException(); } public void Close() { m_task.Dispose(); } public T GetResults() { return m_task.Result; } public Task Task { get { return m_task; } } } } ================================================ FILE: Zelig/Zelig/RunTime/Framework/Windows/Internal/ByteBuffer.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // using System; using System.Collections.Generic; using Windows.Storage.Streams; namespace Windows.Internal { internal sealed class ByteBuffer : IBuffer { private byte[] m_buffer; public ByteBuffer(uint capacity) { m_buffer = new byte[(int)capacity]; } public uint Capacity { get { return (uint)m_buffer.Length; } } public uint Length { get; set; } public byte[] Data { get { return m_buffer; } set { m_buffer = value; } } } } ================================================ FILE: Zelig/Zelig/RunTime/Framework/Windows/Internal/SynchronousOperation.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // using System; namespace Windows.Internal { using Windows.Foundation; public sealed class SynchronousOperation : IAsyncOperation { internal readonly T m_result; private AsyncOperationCompletedHandler m_completedHandler; public SynchronousOperation(T createdObject) { m_result = createdObject; Id = AsyncInfoHelper.GetNextActionId(); } public SynchronousOperation(Exception error) { ErrorCode = error; Id = AsyncInfoHelper.GetNextActionId(); } public AsyncOperationCompletedHandler Completed { get { return m_completedHandler; } set { if(m_completedHandler != null) { throw new InvalidOperationException(); } m_completedHandler = value; } } public Exception ErrorCode { get; } public uint Id { get; } public AsyncStatus Status { get { if (ErrorCode == null) { return AsyncStatus.Completed; } else { return AsyncStatus.Error; } } } public void Cancel() { // NOP } public void Close() { if (m_completedHandler != null) { m_completedHandler.Invoke(this, Status); } IDisposable currentObject = m_result as IDisposable; if(currentObject != null) { currentObject.Dispose(); } } public T GetResults() { return m_result; } } public sealed class SynchronousOperationWithProgress : IAsyncOperationWithProgress { private readonly T m_result; private AsyncOperationWithProgressCompletedHandler m_completedHandler; private AsyncOperationProgressHandler m_progressHandler; public SynchronousOperationWithProgress(T createdObject) { m_result = createdObject; Id = AsyncInfoHelper.GetNextActionId(); } public SynchronousOperationWithProgress(Exception error) { ErrorCode = error; Id = AsyncInfoHelper.GetNextActionId(); } public Exception ErrorCode { get; } public uint Id { get; } public AsyncStatus Status { get { if (ErrorCode == null) { return AsyncStatus.Completed; } else { return AsyncStatus.Error; } } } public AsyncOperationProgressHandler Progress { get { return m_progressHandler; } set { m_progressHandler = value; } } AsyncOperationWithProgressCompletedHandler IAsyncOperationWithProgress.Completed { get { return m_completedHandler; } set { if (m_completedHandler != null) { throw new InvalidOperationException(); } m_completedHandler = value; } } public void Cancel() { // NOP } public T GetResults() { return m_result; } public void Close() { if (m_completedHandler != null) { m_completedHandler.Invoke(this, Status); } IDisposable currentObject = m_result as IDisposable; if (currentObject != null) { currentObject.Dispose(); } } } } ================================================ FILE: Zelig/Zelig/RunTime/Framework/Windows/Internal/WindowsRuntimeSystemExtensions.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // using System; using System.Threading.Tasks; using Windows.Foundation; namespace Windows.Internal { /// /// Provides extension methods for converting between tasks and Windows Runtime asynchronous actions and operations. /// [CLSCompliant(false)] public static class WindowsRuntimeSystemExtensions { /// /// Returns a Windows Runtime asynchronous action that represents a started task. /// /// The started task. /// A Windows.Foundation.IAsyncAction instance that represents the started task. public static IAsyncAction AsAsyncAction(this Task source) { if (source == null) { throw new ArgumentNullException(nameof(source)); } if (source.Status == TaskStatus.Created) { throw new InvalidOperationException("Task has not been started."); } return new AsyncActionFromTask(source); } /// /// Returns a task that represents a Windows Runtime asynchronous action. /// /// The asynchronous action. /// A task that represents the asynchronous action. public static Task AsTask(this IAsyncAction source) { if (source == null) { throw new ArgumentNullException(nameof(source)); } // Short-circuit round-tripped tasks and just return the original. var asyncActionFromTask = source as AsyncActionFromTask; if (asyncActionFromTask != null) { return asyncActionFromTask.Task; } // BUGBUG: We need to implement TaskCompletionSource before we can implement this properly. throw new NotImplementedException(); } /// /// Returns a Windows Runtime asynchronous operation that represents a started task. /// /// The started task. /// A Windows.Foundation.IAsyncOperation instance that represents the started task. public static IAsyncOperation AsAsyncOperation(this Task source) { if (source == null) { throw new ArgumentNullException(nameof(source)); } if (source.Status == TaskStatus.Created) { throw new InvalidOperationException("Task has not been started."); } return new AsyncOperationFromTask(source); } /// /// Returns a task that represents a Windows Runtime asynchronous operation. /// /// The asynchronous operation. /// A task that represents the asynchronous operation. public static Task AsTask(this IAsyncOperation source) { if (source == null) { throw new ArgumentNullException(nameof(source)); } // Short-circuit round-tripped tasks and just return the original. var asyncOperationFromTask = source as AsyncOperationFromTask; if (asyncOperationFromTask != null) { return asyncOperationFromTask.Task; } // BUGBUG: We need to implement TaskCompletionSource before we can implement this properly. throw new NotImplementedException(); } /// /// Returns a Windows Runtime asynchronous operation that represents a started task. /// /// The started task. /// A Windows.Foundation.IAsyncOperation instance that represents the started task. public static IAsyncOperationWithProgress AsAsyncOperationWithProgress(this Task source) { if (source == null) { throw new ArgumentNullException(nameof(source)); } if (source.Status == TaskStatus.Created) { throw new InvalidOperationException("Task has not been started."); } return new AsyncOperationWithProgressFromTask(source); } /// /// Returns a task that represents a Windows Runtime asynchronous operation. /// /// The asynchronous operation. /// A task that represents the asynchronous operation. public static Task AsTask(this IAsyncOperationWithProgress source) { if (source == null) { throw new ArgumentNullException(nameof(source)); } // Short-circuit round-tripped tasks and just return the original. var asyncOperationFromTask = source as AsyncOperationWithProgressFromTask; if (asyncOperationFromTask != null) { return asyncOperationFromTask.Task; } // BUGBUG: We need to implement TaskCompletionSource before we can implement this properly. throw new NotImplementedException(); } } } ================================================ FILE: Zelig/Zelig/RunTime/Framework/Windows/Properties/AssemblyInfo.cs ================================================ using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; // General Information about an assembly is controlled through the following // set of attributes. Change these attribute values to modify the information // associated with an assembly. [assembly: AssemblyTitle("Windows")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("Microsoft")] [assembly: AssemblyProduct("Windows")] [assembly: AssemblyCopyright("Copyright © Microsoft")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Build and Revision Numbers // by using the '*' as shown below: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("10.0.10240.0")] [assembly: AssemblyFileVersion("10.0.10240.0")] [assembly: System.CLSCompliant(false)] ================================================ FILE: Zelig/Zelig/RunTime/Framework/Windows/Storage/Streams/ByteOrder.cs ================================================ using System; using Windows.Foundation; namespace Windows.Storage.Streams { /// Specifies the byte order of a stream. public enum ByteOrder { /// The least significant byte (lowest address) is stored first. LittleEndian, BigEndian, } } ================================================ FILE: Zelig/Zelig/RunTime/Framework/Windows/Storage/Streams/DataReader.cs ================================================ using System; using System.Collections.Generic; using System.Runtime.InteropServices; using System.Text; using System.Threading; using Windows.Foundation; using Windows.Internal; namespace Windows.Storage.Streams { public sealed class DataReader : IDisposable { private IInputStream m_inputStream; private ByteBuffer m_buffer; private ByteBuffer m_tempDataBuffer; private int m_readOffset; private const int defaultBufferSize = 512; /// Gets or sets the Unicode character encoding for the input stream. /// One of the enumeration values. public UnicodeEncoding UnicodeEncoding { get; set; } /// Gets or sets the read options for the input stream. /// One of the enumeration values. public InputStreamOptions InputStreamOptions { get; set; } public ByteOrder ByteOrder { get; set; } public uint UnconsumedBufferLength { get { return (uint)(m_buffer.Capacity - m_buffer.Length); } } /// Creates and initializes a new instance of the data reader. /// The input stream. public DataReader(IInputStream inputStream) { m_inputStream = inputStream; m_buffer = new ByteBuffer(defaultBufferSize); m_tempDataBuffer = new ByteBuffer(defaultBufferSize); // 16 to accomodate reading Guids m_tempDataBuffer.Data = new byte[16]; } private DataReader(IBuffer buffer) { m_buffer = (ByteBuffer)buffer; // 16 to accomodate reading Guids m_tempDataBuffer.Data = new byte[16]; } /// Reads a byte value from the input stream. /// The value. public byte ReadByte() { ThrowIfBytesUnavailable(1); byte value; lock (m_tempDataBuffer) { value = m_buffer.Data[m_readOffset]; m_readOffset += 1; ResetWriteReadIndexIfNeeded(); } return value; } public void ReadBytes(byte[] value) { lock(m_tempDataBuffer) { ReadBytes(value, value.Length); } } private void ReadBytes(byte[] value, int count) { ThrowIfBytesUnavailable(count); Buffer.BlockCopy(m_buffer.Data, m_readOffset, value, 0, count); m_readOffset += count; ResetWriteReadIndexIfNeeded(); } public IBuffer ReadBuffer(uint length) { ByteBuffer buffer = new ByteBuffer(length); lock(m_tempDataBuffer) { ReadBytes(buffer.Data, (int)length); } return buffer; } /// Reads a Boolean value from the input stream. /// The value. public bool ReadBoolean() { byte value; value = ReadByte(); return (value != 0x0); } /// Reads a GUID value from the input stream. /// The value. public Guid ReadGuid() { lock(m_tempDataBuffer) { ReadBytes(m_tempDataBuffer.Data, 16); return new Guid(m_tempDataBuffer.Data); } } public short ReadInt16() { lock (m_tempDataBuffer) { ReadBytes(m_tempDataBuffer.Data, 2); return BitConverter.ToInt16(m_tempDataBuffer.Data, 0); } } /// Reads a 32-bit integer value from the input stream. /// The value. public int ReadInt32() { lock (m_tempDataBuffer) { ReadBytes(m_tempDataBuffer.Data, 4); return BitConverter.ToInt32(m_tempDataBuffer.Data, 0); } } public long ReadInt64() { lock (m_tempDataBuffer) { ReadBytes(m_tempDataBuffer.Data, 8); return BitConverter.ToInt64(m_tempDataBuffer.Data, 0); } } public ushort ReadUInt16() { lock (m_tempDataBuffer) { ReadBytes(m_tempDataBuffer.Data, 2); return BitConverter.ToUInt16(m_tempDataBuffer.Data, 0); } } /// Reads a 32-bit unsigned integer from the input stream. /// The value. public uint ReadUInt32() { lock (m_tempDataBuffer) { ReadBytes(m_tempDataBuffer.Data, 4); return BitConverter.ToUInt32(m_tempDataBuffer.Data, 0); } } public ulong ReadUInt64() { lock (m_tempDataBuffer) { ReadBytes(m_tempDataBuffer.Data, 8); return BitConverter.ToUInt64(m_tempDataBuffer.Data, 0); } } /// Reads a floating-point value from the input stream. /// The value. public float ReadSingle() { lock (m_tempDataBuffer) { ReadBytes(m_tempDataBuffer.Data, 4); return BitConverter.ToSingle(m_tempDataBuffer.Data, 0); } } public double ReadDouble() { lock (m_tempDataBuffer) { ReadBytes(m_tempDataBuffer.Data, 8); return BitConverter.ToDouble(m_tempDataBuffer.Data, 0); } } public string ReadString(uint codeUnitCount) { ThrowIfBytesUnavailable((int)codeUnitCount); byte[] data = new byte[codeUnitCount]; ReadBytes(data); return Encoding.Default.GetString(data); } /// Reads a date and time value from the input stream. /// The value. public DateTime ReadDateTime() { long value = ReadInt64(); return new DateTime(value); } /// Reads a time-interval value from the input stream. /// The value. public TimeSpan ReadTimeSpan() { long value = ReadInt64(); return new TimeSpan(value); } public DataReaderLoadOperation LoadAsync(uint count) { if (m_inputStream == null) { throw new InvalidOperationException(); } ByteBuffer readBuffer = (ByteBuffer)m_inputStream.ReadAsync(m_tempDataBuffer, count, InputStreamOptions).GetResults(); int bytesRead = (int)readBuffer.Length; lock (m_tempDataBuffer) { ResetWriteReadIndexIfNeeded(); Buffer.BlockCopy(readBuffer.Data, 0, m_buffer.Data, (int)m_buffer.Length, bytesRead); m_buffer.Length += (uint)bytesRead; } return new DataReaderLoadOperation((uint)bytesRead); } /// Detaches the buffer that is associated with the data reader. /// The detached buffer. public IBuffer DetachBuffer() { return Interlocked.Exchange(ref m_buffer, null); } public IInputStream DetachStream() { return Interlocked.Exchange(ref m_inputStream, null); } public void Dispose() { m_inputStream?.Dispose(); } /// Creates a new instance of the data reader with data from the specified buffer. /// The data reader. /// The buffer. public static DataReader FromBuffer(IBuffer buffer) { return new DataReader(buffer); } /// /// Throws if user tries to read more bytes than are available /// /// Number of bytes that need to be read private void ThrowIfBytesUnavailable(int count) { if (count > (m_buffer.Length - m_readOffset)) { throw new InvalidOperationException(); } } /// /// Resets the write/read indices if all bytes have been read /// private void ResetWriteReadIndexIfNeeded() { if (m_buffer.Length == m_readOffset) { m_buffer.Length = 0; m_readOffset = 0; } } } } ================================================ FILE: Zelig/Zelig/RunTime/Framework/Windows/Storage/Streams/DataReaderLoadOperation.cs ================================================ using System; using Windows.Foundation; using Windows.Internal; namespace Windows.Storage.Streams { /// Loads data from an input stream. public sealed class DataReaderLoadOperation : IAsyncOperation { private readonly SynchronousOperation m_internalOperation; internal DataReaderLoadOperation(uint result) { m_internalOperation = new SynchronousOperation(result); } internal DataReaderLoadOperation(Exception error) { m_internalOperation = new SynchronousOperation(error); } public AsyncOperationCompletedHandler Completed { get { return m_internalOperation.Completed; } set { m_internalOperation.Completed = value; } } public Exception ErrorCode => m_internalOperation.ErrorCode; public uint Id => m_internalOperation.Id; public AsyncStatus Status => m_internalOperation.Status; public void Cancel() => m_internalOperation.Cancel(); public void Close() => m_internalOperation.Close(); public uint GetResults() => m_internalOperation.GetResults(); } } ================================================ FILE: Zelig/Zelig/RunTime/Framework/Windows/Storage/Streams/DataWriter.cs ================================================ using System; using System.Runtime.InteropServices; using System.Text; using System.Threading; using Windows.Foundation; using Windows.Internal; namespace Windows.Storage.Streams { /// Writes data to an output stream. public sealed class DataWriter : IDisposable { private IOutputStream m_outputStream; private ByteBuffer m_buffer; private const int defaultBufferSize = 512; /// Gets or sets the Unicode character encoding for the output stream. /// One of the enumeration values. public UnicodeEncoding UnicodeEncoding { get; set; } public ByteOrder ByteOrder { get; set; } public uint UnstoredBufferLength { get { return m_buffer.Capacity - m_buffer.Length; } } /// Creates and initializes a new instance of the data writer to an output stream. /// The new output stream instance. public DataWriter(IOutputStream outputStream) { m_outputStream = outputStream; m_buffer = new ByteBuffer(defaultBufferSize); } public DataWriter() { throw new NotImplementedException(); } public void WriteByte(byte value) { FlushIfFull(1); lock (m_buffer) { byte[] data = m_buffer.Data; data[m_buffer.Length] = value; m_buffer.Length++; } } private void WriteBytes(byte[] value, int start, int count) { if(count > (m_buffer.Capacity - m_buffer.Length)) { count = (int)(m_buffer.Capacity - m_buffer.Length); } Buffer.BlockCopy(value, start, m_buffer.Data, (int)m_buffer.Length, count); m_buffer.Length += (uint)count; } /// Writes an array of byte values to the output stream. /// The array of values. public void WriteBytes(byte[] value) { FlushIfFull(value.Length); lock (m_buffer) { WriteBytes(value, 0, value.Length); } } public void WriteBuffer(IBuffer buffer) { WriteBuffer(buffer, 0, buffer.Length); } /// Writes the specified bytes from a buffer to the output stream. /// The buffer. /// The starting byte. /// The number of bytes to write. public void WriteBuffer(IBuffer buffer, uint start, uint count) { byte[] data = ((ByteBuffer)buffer).Data; FlushIfFull((int)count); lock (m_buffer) { WriteBytes(data, (int)start, data.Length); } } /// Writes a Boolean value to the output stream. /// The value. public void WriteBoolean(bool value) { if(value) { WriteByte(0x1); } else { WriteByte(0x0); } } public void WriteGuid(Guid value) { WriteBytes(value.ToByteArray()); } /// Writes a 16-bit integer value to the output stream. /// The value. public void WriteInt16(short value) { WriteBytes(BitConverter.GetBytes(value)); } public void WriteInt32(int value) { WriteBytes(BitConverter.GetBytes(value)); } /// Writes a 64-bit integer value to the output stream. /// The value. public void WriteInt64(long value) { WriteBytes(BitConverter.GetBytes(value)); } /// Writes a 16-bit unsigned integer value to the output stream. /// The value. public void WriteUInt16(ushort value) { WriteBytes(BitConverter.GetBytes(value)); } public void WriteUInt32(uint value) { WriteBytes(BitConverter.GetBytes(value)); } /// Writes a 64-bit unsigned integer value to the output stream. /// The value. public void WriteUInt64(ulong value) { WriteBytes(BitConverter.GetBytes(value)); } public void WriteSingle(float value) { WriteBytes(BitConverter.GetBytes(value)); } /// Writes a floating-point value to the output stream. /// The value. public void WriteDouble(double value) { WriteBytes(BitConverter.GetBytes(value)); } public void WriteDateTime(DateTime value) { WriteBytes(BitConverter.GetBytes(value.Ticks)); } public void WriteTimeSpan(TimeSpan value) { WriteBytes(BitConverter.GetBytes(value.Ticks)); } /// Writes a string value to the output stream. /// The length of the string, in bytes. /// The value. public uint WriteString(string value) { char[] arrValue = value.ToCharArray(); int valLength = arrValue.Length; FlushIfFull(valLength); lock(m_buffer) { Buffer.BlockCopy(arrValue, 0, m_buffer.Data, (int)m_buffer.Length, valLength); m_buffer.Length += (uint)valLength; } return (uint)valLength; } /// Gets the size of a string. /// The size of the string, in bytes. /// The string. public uint MeasureString(string value) { return (uint)value.Length; } public DataWriterStoreOperation StoreAsync() { // NOP - so copy/pasted code works return null; } public IAsyncOperation FlushAsync() { if (m_outputStream == null) { throw new InvalidOperationException(); } IAsyncOperationWithProgress operation; lock (m_buffer) { operation = m_outputStream.WriteAsync(m_buffer); m_buffer.Length = 0; } if (operation.ErrorCode != null) { return new SynchronousOperation(operation.ErrorCode); } return FlushAsync(); } public IBuffer DetachBuffer() { return Interlocked.Exchange(ref m_buffer, null); } /// Detaches the stream that is associated with the data writer. /// The detached stream. public IOutputStream DetachStream() { return Interlocked.Exchange(ref m_outputStream, null); } public void Dispose() { m_outputStream?.Dispose(); } private void FlushIfFull(int count) { if((m_buffer.Length + count) >= m_buffer.Capacity) { FlushAsync().GetResults(); } } } } ================================================ FILE: Zelig/Zelig/RunTime/Framework/Windows/Storage/Streams/DataWriterStoreOperation.cs ================================================ using System; using Windows.Foundation; using Windows.Internal; namespace Windows.Storage.Streams { public sealed class DataWriterStoreOperation : IAsyncOperation { private readonly SynchronousOperation m_internalOperation; internal DataWriterStoreOperation(uint result) { m_internalOperation = new SynchronousOperation(result); } internal DataWriterStoreOperation(Exception error) { m_internalOperation = new SynchronousOperation(error); } public AsyncOperationCompletedHandler Completed { get { return m_internalOperation.Completed; } set { m_internalOperation.Completed = value; } } public Exception ErrorCode => m_internalOperation.ErrorCode; public uint Id => m_internalOperation.Id; public AsyncStatus Status => m_internalOperation.Status; public void Cancel() => m_internalOperation.Cancel(); public void Close() => m_internalOperation.Close(); public uint GetResults() => m_internalOperation.GetResults(); } } ================================================ FILE: Zelig/Zelig/RunTime/Framework/Windows/Storage/Streams/IBuffer.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // using System; using System.Collections.Generic; namespace Windows.Storage.Streams { public interface IBuffer { uint Capacity { get; } uint Length { get; set; } } } ================================================ FILE: Zelig/Zelig/RunTime/Framework/Windows/Storage/Streams/IInputStream.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // using System; using System.Runtime.InteropServices; namespace Windows.Storage.Streams { using Windows.Foundation; public enum InputStreamOptions : uint { None = 0, Partial, ReadAhead, } public interface IInputStream : IDisposable { IAsyncOperationWithProgress ReadAsync(IBuffer buffer, uint count, InputStreamOptions options); } } ================================================ FILE: Zelig/Zelig/RunTime/Framework/Windows/Storage/Streams/IOutputStream.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // using System; namespace Windows.Storage.Streams { using Windows.Foundation; public interface IOutputStream : IDisposable { IAsyncOperationWithProgress WriteAsync(IBuffer buffer); IAsyncOperation FlushAsync(); } } ================================================ FILE: Zelig/Zelig/RunTime/Framework/Windows/System/Threading/ThreadPool.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // using System; using System.Threading.Tasks; using Windows.Foundation; using ST = System.Threading; namespace Windows.System.Threading { /// /// Allows access to the thread pool. /// public static class ThreadPool { /// /// Creates a work item. /// /// The method to call when a thread becomes available to run the work item. /// An IAsyncAction interface that provides access to the work item. public static IAsyncAction RunAsync(WorkItemHandler handler) { return RunAsync(handler, WorkItemPriority.Normal, WorkItemOptions.None); } /// /// Creates a work item and specifies its priority relative to other work items in the thread pool. /// /// The method to call when a thread becomes available to run the work item. /// The priority of the work item relative to other work items in the thread pool. /// An IAsyncAction interface that provides access to the work item. public static IAsyncAction RunAsync(WorkItemHandler handler, WorkItemPriority priority) { return RunAsync(handler, priority, WorkItemOptions.None); } /// /// Creates a work item, specifies its priority relative to other work items in the thread pool, and specifies /// how long-running work items should be run. /// /// The method to call when a thread becomes available to run the work item. /// The priority of the work item relative to other work items in the thread pool. /// If this parameter is TimeSliced, the work item runs simultaneously with other time- /// sliced work items with each work item receiving a share of processor time. If this parameter is None, /// the work item runs when a worker thread becomes available. /// An IAsyncAction interface that provides access to the work item. public static IAsyncAction RunAsync(WorkItemHandler handler, WorkItemPriority priority, WorkItemOptions options) { return new AsyncActionFromWorkItem(handler); } /// /// This is a helper class specifically for RunAsync. It helps us break the circular dependency between Task, /// WorkItemHandler, and IAsyncAction. We could similarly implement this with a continuation, but that approach /// has two drawbacks: higher heap impact and creation of a dependency on the System.Runtime.WindowsRuntime /// assembly. /// private class AsyncActionFromWorkItem : IAsyncAction { private readonly Task m_task; private AsyncActionCompletedHandler m_completedHandler; public AsyncActionFromWorkItem(WorkItemHandler handler) { m_task = Task.Run(() => handler(this)); } public AsyncActionCompletedHandler Completed { get { return m_completedHandler; } set { if (ST.Interlocked.CompareExchange(ref m_completedHandler, value, null) != null) { throw new InvalidOperationException("Completed handler may only be set once."); } m_task.ContinueWith(task => m_completedHandler(this, Status)); } } public Exception ErrorCode { get { return m_task.Exception; } } public uint Id => (uint)m_task.Id; public AsyncStatus Status { get { switch (m_task.Status) { case TaskStatus.RanToCompletion: return AsyncStatus.Completed; case TaskStatus.Canceled: return AsyncStatus.Canceled; case TaskStatus.Faulted: return AsyncStatus.Error; default: return AsyncStatus.Started; } } } public void Cancel() { throw new NotImplementedException(); } public void Close() { m_task.Dispose(); } public void GetResults() { } } } } ================================================ FILE: Zelig/Zelig/RunTime/Framework/Windows/System/Threading/ThreadPoolTimer.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // using System; using ST = System.Threading; namespace Windows.System.Threading { public sealed class ThreadPoolTimer { private readonly TimerElapsedHandler m_elapsedHandler; private readonly TimerDestroyedHandler m_destroyedHandler; private readonly TimeSpan m_time; private readonly bool m_periodic; private ST.Timer m_systemTimer; private ThreadPoolTimer( TimerElapsedHandler elapsedHandler, TimerDestroyedHandler destroyedHandler, TimeSpan time, bool periodic) { m_elapsedHandler = elapsedHandler; m_destroyedHandler = destroyedHandler; m_periodic = periodic; m_time = time; if (periodic) { m_systemTimer = new ST.Timer(TimerElapsed, null, time, time); } else { m_systemTimer = new ST.Timer(TimerElapsed, null, time.Milliseconds, ST.Timeout.Infinite); } } /// /// Gets the timeout value of a single-use timer created with CreateTimer. /// /// The timeout value. When the timeout value elapses, the timer expires and its TimerElapsedHandler /// delegate is called. /// /// A timer begins counting down as soon as the timer object is created. /// public TimeSpan Delay { get { return m_periodic ? default(TimeSpan) : m_time; } } /// /// Gets the timeout value of a periodic timer created with CreatePeriodicTimer. /// /// The timeout value. When the timeout value elapses, the timer expires, its /// TimerElapsedHandler delegate is called, and the timer reactivates. This behavior continues until the /// timer is canceled. /// /// A periodic timer begins counting down as soon as the timer object is created. When the timer expires, it is /// reactivated and begins counting down again. /// public TimeSpan Period { get { return m_periodic ? m_time : default(TimeSpan); } } /// /// Creates a periodic timer. /// /// The method to call when the timer expires. /// The amount of time until the timer expires. The timer reactivates each time the period /// elapses, until the timer is canceled. /// Note: A TimeSpan value of zero (or any value less than 1 millisecond) will cause the periodic /// timer to behave as a single-shot timer. /// An instance of a periodic timer. public static ThreadPoolTimer CreatePeriodicTimer(TimerElapsedHandler handler, TimeSpan period) { return CreatePeriodicTimer(handler, period, null); } /// /// Creates a periodic timer and specifies a method to call after the periodic timer is complete. The periodic /// timer is complete when the timer has expired without being reactivated, and the final call to handler has /// finished. /// /// The method to call when the timer expires. /// The amount of time until the timer expires. The timer reactivates each time the period /// elapses, until the timer is canceled. /// Note: A TimeSpan value of zero (or any value less than 1 millisecond) will cause the periodic /// timer to behave as a single-shot timer. /// The method to call after the periodic timer is complete. /// An instance of a periodic timer. public static ThreadPoolTimer CreatePeriodicTimer( TimerElapsedHandler handler, TimeSpan period, TimerDestroyedHandler destroyed) { if (handler == null) { throw new ArgumentNullException(nameof(handler)); } return new ThreadPoolTimer(handler, destroyed, period, periodic: true); } /// /// Creates a single-use timer. /// /// The method to call when the timer expires. /// The amount of time until the timer expires. /// An instance of a single-use timer. public static ThreadPoolTimer CreateTimer( TimerElapsedHandler handler, TimeSpan delay) { return CreateTimer(handler, delay, null); } /// /// Creates a single-use timer and specifies a method to call after the timer is complete. The timer is complete /// when the timer has expired and the final call to has finished. /// /// The method to call when the timer expires. /// The amount of time until the timer expires. /// The method to call after the timer is complete. /// An instance of a single-use timer. public static ThreadPoolTimer CreateTimer( TimerElapsedHandler handler, TimeSpan delay, TimerDestroyedHandler destroyed) { if (handler == null) { throw new ArgumentNullException(nameof(handler)); } return new ThreadPoolTimer(handler, destroyed, delay, periodic: false); } /// /// Cancels a timer. /// /// /// When a timer is canceled, pending TimerElapsedHandler delegates are also canceled. TimerElapsedHandler /// delegates that are already running are allowed to finish. /// public void Cancel() { var systemTimer = ST.Interlocked.Exchange(ref m_systemTimer, null); if (systemTimer != null) { m_destroyedHandler?.Invoke(this); systemTimer.Dispose(); } } private void TimerElapsed(object state) { // Note: We don't try to enforce causality here, so this handler may be called multiple times concurrently // for very fast timers. As the timer is stateless and only supports read-only operations, this should be // acceptable for our purposes. m_elapsedHandler(this); // If this is a one-shot timer, immediately force cancellation so the completed handler gets invoked. if (!m_periodic) { Cancel(); } } } } ================================================ FILE: Zelig/Zelig/RunTime/Framework/Windows/System/Threading/ThreadingDelegates.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // // // Copyright (c) Microsoft Corporation. All rights reserved. // using Windows.Foundation; namespace Windows.System.Threading { /// /// Represents a method that is called when a timer created with CreateTimer or CreatePeriodicTimer is completed. /// /// The timer to associate with this method. public delegate void TimerDestroyedHandler(ThreadPoolTimer timer); /// /// Represents a method that is called when a timer created with CreateTimer or CreatePeriodicTimer expires. /// /// The timer to associate with this method. When this timer expires, the method is called. /// /// When a timer is canceled, pending TimerElapsedHandler delegates are also canceled. TimerElapsedHandler delegates /// that are already running are allowed to finish. /// public delegate void TimerElapsedHandler(ThreadPoolTimer timer); /// /// Represents a method that is called when a work item runs. /// /// The work item to associate with the callback method. /// /// The thread pool calls a work item's WorkItemHandler delegate when a thread becomes available to run the work /// item. If a work item is canceled, WorkItemHandler delegates that have not yet started running are not called. /// WorkItemHandler delegates that are already running are allowed to finish unless the application stops them. If a /// work item might run for a relatively long time, the application should check if cancellation has been requested /// and stop the handler in an orderly way. /// public delegate void WorkItemHandler(IAsyncAction operation); } ================================================ FILE: Zelig/Zelig/RunTime/Framework/Windows/System/Threading/ThreadingEnums.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // namespace Windows.System.Threading { /// /// Specifies how work items should be run. /// public enum WorkItemOptions { /// /// The work item should be run when the thread pool has an available worker thread. /// None = 0, /// /// The work items should be run simultaneously with other work items sharing a processor. /// TimeSliced, } /// /// Specifies the priority of a work item relative to other work items in the thread pool. /// public enum WorkItemPriority { /// /// The work item should run at normal priority. This is the default value. /// Normal = 0, /// /// The work item should run at low priority. /// Low = -1, /// /// The work item should run at high priority. /// High = 1, } } ================================================ FILE: Zelig/Zelig/RunTime/Framework/Windows/Windows.csproj ================================================  Debug AnyCPU {DC8C38D7-780B-4B13-8ACE-9050E39CC51C} Library Properties Windows Windows $(LlilumBuildRoot)\Target\obj\$(MSBuildProjectName)\ v4.5 true full false $(LlilumBuildRoot)\Target\bin\$(Configuration)\ DEBUG;TRACE prompt 4 true true true AllRules.ruleset AnyCPU false pdbonly true $(LlilumBuildRoot)\Target\bin\$(Configuration)\ TRACE prompt 4 true true true AllRules.ruleset AnyCPU false true full false $(LlilumBuildRoot)\Target\bin\$(Configuration)\ TRACE;DEBUG AnyCPU true true false {d68ee51b-a898-4a77-97d8-c61254cac122} Microsoft.Llilum.Devices {186F31A3-EF89-4A25-B2D5-20070702AA01} system False {186f31a3-ef89-4a25-b2d5-20060501aa01} mscorlib ================================================ FILE: Zelig/Zelig/RunTime/Framework/mscorlib/Properties/AssemblyInfo.cs ================================================ using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; // General Information about an assembly is controlled through the following // set of attributes. Change these attribute values to modify the information // associated with an assembly. [assembly: AssemblyTitle( "mscorlib" )] [assembly: AssemblyDescription( "" )] [assembly: AssemblyConfiguration( "" )] [assembly: AssemblyCompany( "Microsoft" )] [assembly: AssemblyProduct( "mscorlib" )] [assembly: AssemblyCopyright( "Copyright © Microsoft 2006" )] [assembly: AssemblyTrademark( "" )] [assembly: AssemblyCulture( "" )] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Revision and Build Numbers // by using the '*' as shown below: [assembly: AssemblyVersion( "4.0.0.0" )] [assembly: AssemblyFileVersion( "4.0.0.0" )] [assembly: System.CLSCompliant(false)] [assembly: InternalsVisibleTo( "System" )] [assembly: InternalsVisibleTo( "Microsoft.Zelig.Runtime" )] ================================================ FILE: Zelig/Zelig/RunTime/Framework/mscorlib/System/Action.cs ================================================ // Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. // namespace System { using System.Runtime.CompilerServices; public delegate void Action(T obj); // Action/Func delegates first shipped with .NET Framework 3.5 in System.Core.dll as part of LINQ // These were type forwarded to mscorlib.dll in .NET Framework 4.0 and in Silverlight 5.0 #if FEATURE_CORECLR [TypeForwardedFrom("System.Core, Version=2.0.5.0, Culture=Neutral, PublicKeyToken=7cec85d7bea7798e")] #else [TypeForwardedFrom("System.Core, Version=3.5.0.0, Culture=Neutral, PublicKeyToken=b77a5c561934e089")] #endif public delegate void Action(); #if FEATURE_CORECLR [TypeForwardedFrom("System.Core, Version=2.0.5.0, Culture=Neutral, PublicKeyToken=7cec85d7bea7798e")] #else [TypeForwardedFrom("System.Core, Version=3.5.0.0, Culture=Neutral, PublicKeyToken=b77a5c561934e089")] #endif public delegate void Action(T1 arg1, T2 arg2); #if FEATURE_CORECLR [TypeForwardedFrom("System.Core, Version=2.0.5.0, Culture=Neutral, PublicKeyToken=7cec85d7bea7798e")] #else [TypeForwardedFrom("System.Core, Version=3.5.0.0, Culture=Neutral, PublicKeyToken=b77a5c561934e089")] #endif public delegate void Action(T1 arg1, T2 arg2, T3 arg3); #if FEATURE_CORECLR [TypeForwardedFrom("System.Core, Version=2.0.5.0, Culture=Neutral, PublicKeyToken=7cec85d7bea7798e")] #else [TypeForwardedFrom("System.Core, Version=3.5.0.0, Culture=Neutral, PublicKeyToken=b77a5c561934e089")] #endif public delegate void Action(T1 arg1, T2 arg2, T3 arg3, T4 arg4); #if FEATURE_CORECLR [TypeForwardedFrom("System.Core, Version=2.0.5.0, Culture=Neutral, PublicKeyToken=7cec85d7bea7798e")] #else [TypeForwardedFrom("System.Core, Version=3.5.0.0, Culture=Neutral, PublicKeyToken=b77a5c561934e089")] #endif public delegate TResult Func(); #if FEATURE_CORECLR [TypeForwardedFrom("System.Core, Version=2.0.5.0, Culture=Neutral, PublicKeyToken=7cec85d7bea7798e")] #else [TypeForwardedFrom("System.Core, Version=3.5.0.0, Culture=Neutral, PublicKeyToken=b77a5c561934e089")] #endif public delegate TResult Func(T arg); #if FEATURE_CORECLR [TypeForwardedFrom("System.Core, Version=2.0.5.0, Culture=Neutral, PublicKeyToken=7cec85d7bea7798e")] #else [TypeForwardedFrom("System.Core, Version=3.5.0.0, Culture=Neutral, PublicKeyToken=b77a5c561934e089")] #endif public delegate TResult Func(T1 arg1, T2 arg2); #if FEATURE_CORECLR [TypeForwardedFrom("System.Core, Version=2.0.5.0, Culture=Neutral, PublicKeyToken=7cec85d7bea7798e")] #else [TypeForwardedFrom("System.Core, Version=3.5.0.0, Culture=Neutral, PublicKeyToken=b77a5c561934e089")] #endif public delegate TResult Func(T1 arg1, T2 arg2, T3 arg3); #if FEATURE_CORECLR [TypeForwardedFrom("System.Core, Version=2.0.5.0, Culture=Neutral, PublicKeyToken=7cec85d7bea7798e")] #else [TypeForwardedFrom("System.Core, Version=3.5.0.0, Culture=Neutral, PublicKeyToken=b77a5c561934e089")] #endif public delegate TResult Func(T1 arg1, T2 arg2, T3 arg3, T4 arg4); public delegate void Action(T1 arg1, T2 arg2, T3 arg3, T4 arg4, T5 arg5); public delegate void Action(T1 arg1, T2 arg2, T3 arg3, T4 arg4, T5 arg5, T6 arg6); public delegate void Action(T1 arg1, T2 arg2, T3 arg3, T4 arg4, T5 arg5, T6 arg6, T7 arg7); public delegate void Action(T1 arg1, T2 arg2, T3 arg3, T4 arg4, T5 arg5, T6 arg6, T7 arg7, T8 arg8); public delegate TResult Func(T1 arg1, T2 arg2, T3 arg3, T4 arg4, T5 arg5); public delegate TResult Func(T1 arg1, T2 arg2, T3 arg3, T4 arg4, T5 arg5, T6 arg6); public delegate TResult Func(T1 arg1, T2 arg2, T3 arg3, T4 arg4, T5 arg5, T6 arg6, T7 arg7); public delegate TResult Func(T1 arg1, T2 arg2, T3 arg3, T4 arg4, T5 arg5, T6 arg6, T7 arg7, T8 arg8); public delegate int Comparison(T x, T y); public delegate TOutput Converter(TInput input); public delegate bool Predicate(T obj); } ================================================ FILE: Zelig/Zelig/RunTime/Framework/mscorlib/System/Activator.cs ================================================ // ==++== // // Copyright (c) Microsoft Corporation. All rights reserved. // // ==--== //////////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////////// // // Activator is an object that contains the Activation (CreateInstance/New) // methods for late bound support. // // // // namespace System { using System; using System.Reflection; using System.Runtime.CompilerServices; ////using System.Runtime.Remoting; ////using System.Runtime.Remoting.Activation; ////using Message = System.Runtime.Remoting.Messaging.Message; ////using CultureInfo = System.Globalization.CultureInfo; ////using Evidence = System.Security.Policy.Evidence; ////using StackCrawlMark = System.Threading.StackCrawlMark; ////using System.Runtime.InteropServices; ////using System.Security.Permissions; ////using AssemblyHashAlgorithm = System.Configuration.Assemblies.AssemblyHashAlgorithm; ////using System.Runtime.Versioning; // Only statics, does not need to be marked with the serializable attribute ////[ClassInterface( ClassInterfaceType.None )] ////[ComDefaultInterface( typeof( _Activator ) )] public sealed class Activator //: _Activator { //// internal const int LookupMask = 0x000000FF; //// internal const BindingFlags ConLookup = (BindingFlags)(BindingFlags.Instance | BindingFlags.Public); //// internal const BindingFlags ConstructorDefault = BindingFlags.Instance | BindingFlags.Public | BindingFlags.CreateInstance; // This class only contains statics, so hide the worthless constructor private Activator() { } //// // CreateInstance //// // The following methods will create a new instance of an Object //// // Full Binding Support //// // For all of these methods we need to get the underlying RuntimeType and //// // call the Impl version. //// static public Object CreateInstance( Type type, //// BindingFlags bindingAttr, //// Binder binder, //// Object[] args, //// CultureInfo culture ) //// { //// return CreateInstance( type, bindingAttr, binder, args, culture, null ); //// } //// //// static public Object CreateInstance( Type type, //// BindingFlags bindingAttr, //// Binder binder, //// Object[] args, //// CultureInfo culture, //// Object[] activationAttributes ) //// { //// if(type == null) //// throw new ArgumentNullException( "type" ); //// //// if(type is System.Reflection.Emit.TypeBuilder) //// throw new NotSupportedException( Environment.GetResourceString( "NotSupported_CreateInstanceWithTypeBuilder" ) ); //// //// // If they didn't specify a lookup, then we will provide the default lookup. //// if((bindingAttr & (BindingFlags)LookupMask) == 0) //// bindingAttr |= Activator.ConstructorDefault; //// //// if(activationAttributes != null && activationAttributes.Length > 0) //// { //// // If type does not derive from MBR //// // throw notsupportedexception //// if(type.IsMarshalByRef) //// { //// // The fix below is preventative. //// // //// if(!(type.IsContextful)) //// { //// if(activationAttributes.Length > 1 || !(activationAttributes[0] is UrlAttribute)) //// throw new NotSupportedException( Environment.GetResourceString( "NotSupported_NonUrlAttrOnMBR" ) ); //// } //// } //// else //// throw new NotSupportedException( Environment.GetResourceString( "NotSupported_ActivAttrOnNonMBR" ) ); //// } //// //// RuntimeType rt = type.UnderlyingSystemType as RuntimeType; //// //// if(rt == null) //// throw new ArgumentException( Environment.GetResourceString( "Arg_MustBeType" ), "type" ); //// //// return rt.CreateInstanceImpl( bindingAttr, binder, args, culture, activationAttributes ); //// } //// //// static public Object CreateInstance( Type type, params Object[] args ) //// { //// return CreateInstance( type, //// Activator.ConstructorDefault, //// null, //// args, //// null, //// null ); //// } //// //// static public Object CreateInstance( Type type, //// Object[] args, //// Object[] activationAttributes ) //// { //// return CreateInstance( type, //// Activator.ConstructorDefault, //// null, //// args, //// null, //// activationAttributes ); //// } static public Object CreateInstance( Type type ) { throw new NotImplementedException(); //// return Activator.CreateInstance( type, false ); } //// /* //// * Create an instance using the name of type and the assembly where it exists. This allows //// * types to be created remotely without having to load the type locally. //// */ //// //// static public ObjectHandle CreateInstance( String assemblyName, //// String typeName ) //// { //// StackCrawlMark stackMark = StackCrawlMark.LookForMyCaller; //// return CreateInstance( assemblyName, //// typeName, //// false, //// Activator.ConstructorDefault, //// null, //// null, //// null, //// null, //// null, //// ref stackMark ); //// } //// //// static public ObjectHandle CreateInstance( String assemblyName, //// String typeName, //// Object[] activationAttributes ) //// { //// StackCrawlMark stackMark = StackCrawlMark.LookForMyCaller; //// return CreateInstance( assemblyName, //// typeName, //// false, //// Activator.ConstructorDefault, //// null, //// null, //// null, //// activationAttributes, //// null, //// ref stackMark ); //// } //// //// static public Object CreateInstance( Type type, bool nonPublic ) //// { //// if(type == null) //// throw new ArgumentNullException( "type" ); //// //// RuntimeType rt = type.UnderlyingSystemType as RuntimeType; //// //// if(rt == null) //// throw new ArgumentException( Environment.GetResourceString( "Arg_MustBeType" ), "type" ); //// //// return rt.CreateInstanceImpl( !nonPublic ); //// } //// //// static internal Object InternalCreateInstanceWithNoMemberAccessCheck( Type type, bool nonPublic ) //// { //// if(type == null) //// throw new ArgumentNullException( "type" ); //// //// RuntimeType rt = type.UnderlyingSystemType as RuntimeType; //// //// if(rt == null) //// throw new ArgumentException( Environment.GetResourceString( "Arg_MustBeType" ), "type" ); //// //// return rt.CreateInstanceImpl( !nonPublic, false, false ); //// } static public T CreateInstance() { return (T)CreateInstanceInner( typeof(T) ); //// bool bNeedSecurityCheck = true; //// bool bCanBeCached = false; //// RuntimeMethodHandle mh = RuntimeMethodHandle.EmptyHandle; //// return (T)RuntimeTypeHandle.CreateInstance( typeof( T ) as RuntimeType, true, true, ref bCanBeCached, ref mh, ref bNeedSecurityCheck ); } [MethodImpl( MethodImplOptions.InternalCall )] public static extern object CreateInstanceInner( Type t ); //// [ResourceExposure( ResourceScope.Machine )] //// [ResourceConsumption( ResourceScope.Machine )] //// static public ObjectHandle CreateInstanceFrom( String assemblyFile, //// String typeName ) //// { //// return CreateInstanceFrom( assemblyFile, typeName, null ); //// } //// //// [ResourceExposure( ResourceScope.Machine )] //// [ResourceConsumption( ResourceScope.Machine )] //// static public ObjectHandle CreateInstanceFrom( String assemblyFile, //// String typeName, //// Object[] activationAttributes ) //// { //// return CreateInstanceFrom( assemblyFile, //// typeName, //// false, //// Activator.ConstructorDefault, //// null, //// null, //// null, //// activationAttributes, //// null ); //// } //// //// //// static public ObjectHandle CreateInstance( String assemblyName, //// String typeName, //// bool ignoreCase, //// BindingFlags bindingAttr, //// Binder binder, //// Object[] args, //// CultureInfo culture, //// Object[] activationAttributes, //// Evidence securityInfo ) //// { //// StackCrawlMark stackMark = StackCrawlMark.LookForMyCaller; //// return CreateInstance( assemblyName, //// typeName, //// ignoreCase, //// bindingAttr, //// binder, //// args, //// culture, //// activationAttributes, //// securityInfo, //// ref stackMark ); //// } //// //// static internal ObjectHandle CreateInstance( String assemblyName, //// String typeName, //// bool ignoreCase, //// BindingFlags bindingAttr, //// Binder binder, //// Object[] args, //// CultureInfo culture, //// Object[] activationAttributes, //// Evidence securityInfo, //// ref StackCrawlMark stackMark ) //// { //// Assembly assembly; //// if(assemblyName == null) //// assembly = Assembly.GetExecutingAssembly( ref stackMark ); //// else //// assembly = Assembly.InternalLoad( assemblyName, securityInfo, ref stackMark, false ); //// //// Log( assembly != null, "CreateInstance:: ", "Loaded " + assembly.FullName, "Failed to Load: " + assemblyName ); //// if(assembly == null) return null; //// //// Type t = assembly.GetType( typeName, true, ignoreCase ); //// //// Object o = Activator.CreateInstance( t, //// bindingAttr, //// binder, //// args, //// culture, //// activationAttributes ); //// //// Log( o != null, "CreateInstance:: ", "Created Instance of class " + typeName, "Failed to create instance of class " + typeName ); //// if(o == null) //// return null; //// else //// { //// ObjectHandle Handle = new ObjectHandle( o ); //// return Handle; //// } //// } //// //// [ResourceExposure( ResourceScope.Machine )] //// [ResourceConsumption( ResourceScope.Machine )] //// static public ObjectHandle CreateInstanceFrom( String assemblyFile, //// String typeName, //// bool ignoreCase, //// BindingFlags bindingAttr, //// Binder binder, //// Object[] args, //// CultureInfo culture, //// Object[] activationAttributes, //// Evidence securityInfo ) //// { //// Assembly assembly = Assembly.LoadFrom( assemblyFile, securityInfo ); //// Type t = assembly.GetType( typeName, true, ignoreCase ); //// //// Object o = Activator.CreateInstance( t, //// bindingAttr, //// binder, //// args, //// culture, //// activationAttributes ); //// //// Log( o != null, "CreateInstanceFrom:: ", "Created Instance of class " + typeName, "Failed to create instance of class " + typeName ); //// if(o == null) //// return null; //// else //// { //// ObjectHandle Handle = new ObjectHandle( o ); //// return Handle; //// } //// } //// //// // //// // This API is designed to be used when a host needs to execute code in an AppDomain //// // with restricted security permissions. In that case, we demand in the client domain //// // and assert in the server domain because the server domain might not be trusted enough //// // to pass the security checks when activating the type. //// // //// //// [PermissionSetAttribute( SecurityAction.LinkDemand, Unrestricted = true )] //// public static ObjectHandle CreateInstance( AppDomain domain, string assemblyName, string typeName ) //// { //// if(domain == null) //// throw new ArgumentNullException( "domain" ); //// return domain.InternalCreateInstanceWithNoSecurity( assemblyName, typeName ); //// } //// //// [PermissionSetAttribute( SecurityAction.LinkDemand, Unrestricted = true )] //// public static ObjectHandle CreateInstance( AppDomain domain, //// string assemblyName, //// string typeName, //// bool ignoreCase, //// BindingFlags bindingAttr, //// Binder binder, //// Object[] args, //// CultureInfo culture, //// Object[] activationAttributes, //// Evidence securityAttributes ) //// { //// if(domain == null) //// throw new ArgumentNullException( "domain" ); //// return domain.InternalCreateInstanceWithNoSecurity( assemblyName, typeName, ignoreCase, bindingAttr, binder, args, culture, activationAttributes, securityAttributes ); //// } //// //// // //// // This API is designed to be used when a host needs to execute code in an AppDomain //// // with restricted security permissions. In that case, we demand in the client domain //// // and assert in the server domain because the server domain might not be trusted enough //// // to pass the security checks when activating the type. //// // //// //// [PermissionSetAttribute( SecurityAction.LinkDemand, Unrestricted = true )] //// [ResourceExposure( ResourceScope.Machine )] //// [ResourceConsumption( ResourceScope.Machine )] //// public static ObjectHandle CreateInstanceFrom( AppDomain domain, string assemblyFile, string typeName ) //// { //// if(domain == null) //// throw new ArgumentNullException( "domain" ); //// return domain.InternalCreateInstanceFromWithNoSecurity( assemblyFile, typeName ); //// } //// //// [PermissionSetAttribute( SecurityAction.LinkDemand, Unrestricted = true )] //// [ResourceExposure( ResourceScope.Machine )] //// [ResourceConsumption( ResourceScope.Machine )] //// public static ObjectHandle CreateInstanceFrom( AppDomain domain, //// string assemblyFile, //// string typeName, //// bool ignoreCase, //// BindingFlags bindingAttr, //// Binder binder, //// Object[] args, //// CultureInfo culture, //// Object[] activationAttributes, //// Evidence securityAttributes ) //// { //// if(domain == null) //// throw new ArgumentNullException( "domain" ); //// return domain.InternalCreateInstanceFromWithNoSecurity( assemblyFile, typeName, ignoreCase, bindingAttr, binder, args, culture, activationAttributes, securityAttributes ); //// } //// //// // This method is a helper method and delegates to the remoting //// // services to do the actual work. //// [SecurityPermissionAttribute( SecurityAction.LinkDemand, Flags = SecurityPermissionFlag.RemotingConfiguration )] //// static public Object GetObject( Type type, String url ) //// { //// return GetObject( type, url, null ); //// } //// //// // This method is a helper method and delegates to the remoting //// // services to do the actual work. //// [SecurityPermissionAttribute( SecurityAction.LinkDemand, Flags = SecurityPermissionFlag.RemotingConfiguration )] //// static public Object GetObject( Type type, String url, Object state ) //// { //// if(type == null) //// throw new ArgumentNullException( "type" ); //// return RemotingServices.Connect( type, url, state ); //// } //// //// [System.Diagnostics.Conditional( "_DEBUG" )] //// private static void Log( bool test, string title, string success, string failure ) //// { //// if(test) //// BCLDebug.Trace( "REMOTE", "{0}{1}", title, success ); //// else //// BCLDebug.Trace( "REMOTE", "{0}{1}", title, failure ); //// } } } ================================================ FILE: Zelig/Zelig/RunTime/Framework/mscorlib/System/AggregateException.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // using System.Collections.Generic; using System.Collections.ObjectModel; using System.Diagnostics; using System.Globalization; namespace System { /// Represents one or more errors that occur during application execution. /// /// is used to consolidate multiple failures into a single, throwable /// exception object. /// [Serializable] [DebuggerDisplay("Count = {InnerExceptionCount}")] public class AggregateException : Exception { private static readonly string s_defaultMessage = "One or more errors occurred."; private static readonly string s_innerExceptionNull = "An element of innerExceptions was null."; private ReadOnlyCollection m_innerExceptions; // Complete set of exceptions. /// /// Initializes a new instance of the class. /// public AggregateException() : base(s_defaultMessage) { m_innerExceptions = new ReadOnlyCollection(new Exception[0]); } /// /// Initializes a new instance of the class with /// a specified error message. /// /// The error message that explains the reason for the exception. public AggregateException(string message) : base(message) { m_innerExceptions = new ReadOnlyCollection(new Exception[0]); } /// /// Initializes a new instance of the class with a specified error /// message and a reference to the inner exception that is the cause of this exception. /// /// The error message that explains the reason for the exception. /// The exception that is the cause of the current exception. /// The argument /// is null. public AggregateException(string message, Exception innerException) : base(message, innerException) { if (innerException == null) { throw new ArgumentNullException(nameof(innerException)); } m_innerExceptions = new ReadOnlyCollection(new Exception[] { innerException }); } /// /// Initializes a new instance of the class with /// references to the inner exceptions that are the cause of this exception. /// /// The exceptions that are the cause of the current exception. /// The argument /// is null. /// An element of is /// null. public AggregateException(IEnumerable innerExceptions) : this(s_defaultMessage, innerExceptions) { } /// /// Initializes a new instance of the class with /// references to the inner exceptions that are the cause of this exception. /// /// The exceptions that are the cause of the current exception. /// The argument /// is null. /// An element of is /// null. public AggregateException(params Exception[] innerExceptions) : this(s_defaultMessage, innerExceptions) { } /// /// Initializes a new instance of the class with a specified error /// message and references to the inner exceptions that are the cause of this exception. /// /// The error message that explains the reason for the exception. /// The exceptions that are the cause of the current exception. /// The argument /// is null. /// An element of is /// null. public AggregateException(string message, IEnumerable innerExceptions) // If it's already an IList, pass that along (a defensive copy will be made in the delegated ctor). If it's null, just pass along // null typed correctly. Otherwise, create an IList from the enumerable and pass that along. : this(message, innerExceptions as IList ?? (innerExceptions == null ? (List)null : new List(innerExceptions))) { } /// /// Initializes a new instance of the class with a specified error /// message and references to the inner exceptions that are the cause of this exception. /// /// The error message that explains the reason for the exception. /// The exceptions that are the cause of the current exception. /// The argument /// is null. /// An element of is /// null. public AggregateException(string message, params Exception[] innerExceptions) : this(message, (IList)innerExceptions) { } /// /// Allocates a new aggregate exception with the specified message and list of inner exceptions. /// /// The error message that explains the reason for the exception. /// The exceptions that are the cause of the current exception. /// The argument /// is null. /// An element of is /// null. private AggregateException(string message, IList innerExceptions) : base(message, innerExceptions != null && innerExceptions.Count > 0 ? innerExceptions[0] : null) { if (innerExceptions == null) { throw new ArgumentNullException(nameof(innerExceptions)); } // Copy exceptions to our internal array and validate them. We must copy them, // because we're going to put them into a ReadOnlyCollection which simply reuses // the list passed in to it. We don't want callers subsequently mutating. Exception[] exceptionsCopy = new Exception[innerExceptions.Count]; for (int i = 0; i < exceptionsCopy.Length; i++) { exceptionsCopy[i] = innerExceptions[i]; if (exceptionsCopy[i] == null) { throw new ArgumentException(s_innerExceptionNull); } } m_innerExceptions = new ReadOnlyCollection(exceptionsCopy); } #if DISABLED_FOR_LLILUM /// /// Initializes a new instance of the class with /// references to the inner exception dispatch info objects that represent the cause of this exception. /// /// /// Information about the exceptions that are the cause of the current exception. /// /// The argument /// is null. /// An element of is /// null. internal AggregateException(IEnumerable innerExceptionInfos) : this(s_defaultMessage, innerExceptionInfos) { } /// /// Initializes a new instance of the class with a specified error /// message and references to the inner exception dispatch info objects that represent the cause of /// this exception. /// /// The error message that explains the reason for the exception. /// /// Information about the exceptions that are the cause of the current exception. /// /// The argument /// is null. /// An element of is /// null. internal AggregateException(string message, IEnumerable innerExceptionInfos) // If it's already an IList, pass that along (a defensive copy will be made in the delegated ctor). If it's null, just pass along // null typed correctly. Otherwise, create an IList from the enumerable and pass that along. : this(message, innerExceptionInfos as IList ?? (innerExceptionInfos == null ? (List)null : new List(innerExceptionInfos))) { } /// /// Allocates a new aggregate exception with the specified message and list of inner /// exception dispatch info objects. /// /// The error message that explains the reason for the exception. /// /// Information about the exceptions that are the cause of the current exception. /// /// The argument /// is null. /// An element of is /// null. private AggregateException(string message, IList innerExceptionInfos) : base(message, innerExceptionInfos != null && innerExceptionInfos.Count > 0 && innerExceptionInfos[0] != null ? innerExceptionInfos[0].SourceException : null) { if (innerExceptionInfos == null) { throw new ArgumentNullException("innerExceptionInfos"); } // Copy exceptions to our internal array and validate them. We must copy them, // because we're going to put them into a ReadOnlyCollection which simply reuses // the list passed in to it. We don't want callers subsequently mutating. Exception[] exceptionsCopy = new Exception[innerExceptionInfos.Count]; for (int i = 0; i < exceptionsCopy.Length; i++) { var edi = innerExceptionInfos[i]; if (edi != null) exceptionsCopy[i] = edi.SourceException; if (exceptionsCopy[i] == null) { throw new ArgumentException(s_innerExceptionNull); } } m_innerExceptions = new ReadOnlyCollection(exceptionsCopy); } /// /// Initializes a new instance of the class with serialized data. /// /// The that holds /// the serialized object data about the exception being thrown. /// The that /// contains contextual information about the source or destination. /// The argument is null. /// The exception could not be deserialized correctly. [SecurityCritical] protected AggregateException(SerializationInfo info, StreamingContext context) : base(info, context) { if (info == null) { throw new ArgumentNullException("info"); } Exception[] innerExceptions = info.GetValue("InnerExceptions", typeof(Exception[])) as Exception[]; if (innerExceptions == null) { throw new SerializationException("The serialization stream contains no inner exceptions."); } m_innerExceptions = new ReadOnlyCollection(innerExceptions); } /// /// Sets the with information about /// the exception. /// /// The that holds /// the serialized object data about the exception being thrown. /// The that /// contains contextual information about the source or destination. /// The argument is null. [SecurityCritical] public override void GetObjectData(SerializationInfo info, StreamingContext context) { if (info == null) { throw new ArgumentNullException("info"); } base.GetObjectData(info, context); Exception[] innerExceptions = new Exception[m_innerExceptions.Count]; m_innerExceptions.CopyTo(innerExceptions, 0); info.AddValue("InnerExceptions", innerExceptions, typeof(Exception[])); } #endif // DISABLED_FOR_LLILUM /// /// Returns the that is the root cause of this exception. /// public override Exception GetBaseException() { // Returns the first inner AggregateException that contains more or less than one inner exception // Recursively traverse the inner exceptions as long as the inner exception of type AggregateException and has only one inner exception Exception back = this; AggregateException backAsAggregate = this; while (backAsAggregate != null && backAsAggregate.InnerExceptions.Count == 1) { back = back.InnerException; backAsAggregate = back as AggregateException; } return back; } /// /// Gets a read-only collection of the instances that caused the /// current exception. /// public ReadOnlyCollection InnerExceptions { get { return m_innerExceptions; } } /// /// Invokes a handler on each contained by this . /// /// The predicate to execute for each exception. The predicate accepts as an /// argument the to be processed and returns a Boolean to indicate /// whether the exception was handled. /// /// Each invocation of the returns true or false to indicate whether the /// was handled. After all invocations, if any exceptions went /// unhandled, all unhandled exceptions will be put into a new /// which will be thrown. Otherwise, the method simply returns. If any /// invocations of the throws an exception, it will halt the processing /// of any more exceptions and immediately propagate the thrown exception as-is. /// /// An exception contained by this was not handled. /// The argument is /// null. public void Handle(Func predicate) { if (predicate == null) { throw new ArgumentNullException(nameof(predicate)); } List unhandledExceptions = null; for (int i = 0; i < m_innerExceptions.Count; i++) { // If the exception was not handled, lazily allocate a list of unhandled // exceptions (to be rethrown later) and add it. if (!predicate(m_innerExceptions[i])) { if (unhandledExceptions == null) { unhandledExceptions = new List(); } unhandledExceptions.Add(m_innerExceptions[i]); } } // If there are unhandled exceptions remaining, throw them. if (unhandledExceptions != null) { throw new AggregateException(Message, unhandledExceptions); } } /// /// Flattens an instances into a single, new instance. /// /// A new, flattened . /// /// If any inner exceptions are themselves instances of /// , this method will recursively flatten all of them. The /// inner exceptions returned in the new /// will be the union of all of the the inner exceptions from exception tree rooted at the provided /// instance. /// public AggregateException Flatten() { // Initialize a collection to contain the flattened exceptions. List flattenedExceptions = new List(); // Create a list to remember all aggregates to be flattened, this will be accessed like a FIFO queue List exceptionsToFlatten = new List(); exceptionsToFlatten.Add(this); int nDequeueIndex = 0; // Continue removing and recursively flattening exceptions, until there are no more. while (exceptionsToFlatten.Count > nDequeueIndex) { // dequeue one from exceptionsToFlatten IList currentInnerExceptions = exceptionsToFlatten[nDequeueIndex++].InnerExceptions; for (int i = 0; i < currentInnerExceptions.Count; i++) { Exception currentInnerException = currentInnerExceptions[i]; if (currentInnerException == null) { continue; } AggregateException currentInnerAsAggregate = currentInnerException as AggregateException; // If this exception is an aggregate, keep it around for later. Otherwise, // simply add it to the list of flattened exceptions to be returned. if (currentInnerAsAggregate != null) { exceptionsToFlatten.Add(currentInnerAsAggregate); } else { flattenedExceptions.Add(currentInnerException); } } } return new AggregateException(Message, flattenedExceptions); } /// /// Creates and returns a string representation of the current . /// /// A string representation of the current exception. public override string ToString() { string text = base.ToString(); for (int i = 0; i < m_innerExceptions.Count; i++) { text = string.Format( "{0}{1}---> (Inner Exception #{2}) {3}<---{5}", text, Environment.NewLine, i, m_innerExceptions[i].ToString(), Environment.NewLine); } return text; } /// /// This helper property is used by the DebuggerDisplay. /// /// Note that we don't want to remove this property and change the debugger display to {InnerExceptions.Count} /// because DebuggerDisplay should be a single property access or parameterless method call, so that the debugger /// can use a fast path without using the expression evaluator. /// /// See http://msdn.microsoft.com/en-us/library/x810d419.aspx /// private int InnerExceptionCount { get { return InnerExceptions.Count; } } } } ================================================ FILE: Zelig/Zelig/RunTime/Framework/mscorlib/System/ApplicationException.cs ================================================ // ==++== // // Copyright (c) Microsoft Corporation. All rights reserved. // // ==--== /*============================================================================= ** ** Class: ApplicationException ** ** ** Purpose: The base class for all "less serious" exceptions that must be ** declared or caught. ** ** =============================================================================*/ namespace System { using System.Runtime.Serialization; // The ApplicationException is the base class for nonfatal, // application errors that occur. These exceptions are generated // (i.e., thrown) by an application, not the Runtime. Applications that need // to create their own exceptions do so by extending this class. // ApplicationException extends but adds no new functionality to // RecoverableException. // [Serializable()] public class ApplicationException : Exception { // Creates a new ApplicationException with its message string set to // the empty string, its HRESULT set to COR_E_APPLICATION, // and its ExceptionInfo reference set to null. #if EXCEPTION_STRINGS public ApplicationException() : base( Environment.GetResourceString( "Arg_ApplicationException" ) ) #else public ApplicationException() #endif { //// SetErrorCode( __HResults.COR_E_APPLICATION ); } // Creates a new ApplicationException with its message string set to // message, its HRESULT set to COR_E_APPLICATION, // and its ExceptionInfo reference set to null. // public ApplicationException( String message ) : base( message ) { //// SetErrorCode( __HResults.COR_E_APPLICATION ); } public ApplicationException( String message, Exception innerException ) : base( message, innerException ) { //// SetErrorCode( __HResults.COR_E_APPLICATION ); } //// protected ApplicationException( SerializationInfo info , //// StreamingContext context ) : base( info, context ) //// { //// } } } ================================================ FILE: Zelig/Zelig/RunTime/Framework/mscorlib/System/ArgumentException.cs ================================================ // ==++== // // Copyright (c) Microsoft Corporation. All rights reserved. // // ==--== /*============================================================================= ** ** Class: ArgumentException ** ** ** Purpose: Exception class for invalid arguments to a method. ** ** =============================================================================*/ namespace System { using System; ////using System.Runtime.Remoting; using System.Runtime.Serialization; using System.Globalization; ////using System.Security.Permissions; // The ArgumentException is thrown when an argument does not meet // the contract of the method. Ideally it should give a meaningful error // message describing what was wrong and which parameter is incorrect. // [Serializable] public class ArgumentException : SystemException /*, ISerializable*/ { private String m_paramName; // Creates a new ArgumentException with its message // string set to the empty string. #if EXCEPTION_STRINGS public ArgumentException() : base( Environment.GetResourceString( "Arg_ArgumentException" ) ) #else public ArgumentException() #endif { } // Creates a new ArgumentException with its message // string set to message. // public ArgumentException( String message ) : base( message ) { } public ArgumentException( String message, Exception innerException ) : base( message, innerException ) { } public ArgumentException( String message, String paramName, Exception innerException ) : base( message, innerException ) { m_paramName = paramName; } public ArgumentException( String message, String paramName ) : base( message ) { m_paramName = paramName; } //// protected ArgumentException( SerializationInfo info, StreamingContext context ) : base( info, context ) //// { //// m_paramName = info.GetString( "ParamName" ); //// } public override String Message { get { return m_message + " " + m_paramName; //// String s = base.Message; //// //// if(!((m_paramName == null) || (m_paramName.Length == 0))) //// { //// return s + Environment.NewLine + String.Format( CultureInfo.CurrentCulture, Environment.GetResourceString( "Arg_ParamName_Name" ), m_paramName ); //// } //// else //// { //// return s; //// } } } public virtual String ParamName { get { return m_paramName; } } //// [SecurityPermissionAttribute( SecurityAction.LinkDemand, Flags = SecurityPermissionFlag.SerializationFormatter )] //// public override void GetObjectData( SerializationInfo info, StreamingContext context ) //// { //// base.GetObjectData( info, context ); //// //// info.AddValue( "ParamName", m_paramName, typeof( String ) ); //// } } } ================================================ FILE: Zelig/Zelig/RunTime/Framework/mscorlib/System/ArgumentNullException.cs ================================================ // ==++== // // Copyright (c) Microsoft Corporation. All rights reserved. // // ==--== /*============================================================================= ** ** Class: ArgumentNullException ** ** ** Purpose: Exception class for null arguments to a method. ** ** =============================================================================*/ namespace System { using System; using System.Runtime.Serialization; ////using System.Runtime.Remoting; ////using System.Security.Permissions; // The ArgumentException is thrown when an argument // is null when it shouldn't be. // [Serializable] public class ArgumentNullException : ArgumentException { // Creates a new ArgumentNullException with its message // string set to a default message explaining an argument was null. #if EXCEPTION_STRINGS public ArgumentNullException() : base( Environment.GetResourceString( "ArgumentNull_Generic" ) ) #else public ArgumentNullException() #endif { } #if EXCEPTION_STRINGS public ArgumentNullException( String paramName ) : base( Environment.GetResourceString( "ArgumentNull_Generic" ), paramName ) #else public ArgumentNullException( String paramName ) : base( null, paramName ) #endif { } public ArgumentNullException( String message, Exception innerException ) : base( message, innerException ) { } public ArgumentNullException( String paramName, String message ) : base( message, paramName ) { } //// [SecurityPermissionAttribute( SecurityAction.LinkDemand, Flags = SecurityPermissionFlag.SerializationFormatter )] //// protected ArgumentNullException( SerializationInfo info, StreamingContext context ) : base( info, context ) //// { //// } } } ================================================ FILE: Zelig/Zelig/RunTime/Framework/mscorlib/System/ArgumentOutOfRangeException.cs ================================================ // ==++== // // Copyright (c) Microsoft Corporation. All rights reserved. // // ==--== /*============================================================================= ** ** Class: ArgumentOutOfRangeException ** ** ** Purpose: Exception class for method arguments outside of the legal range. ** ** =============================================================================*/ namespace System { using System; ////using System.Runtime.Remoting; using System.Runtime.Serialization; using System.Globalization; ////using System.Security.Permissions; // The ArgumentOutOfRangeException is thrown when an argument // is outside the legal range for that argument. [Serializable] public class ArgumentOutOfRangeException : ArgumentException /*, ISerializable*/ { private Object m_actualValue; // Creates a new ArgumentOutOfRangeException with its message // string set to a default message explaining an argument was out of range. public ArgumentOutOfRangeException() : base( RangeMessage ) { } public ArgumentOutOfRangeException( String paramName ) : base( RangeMessage, paramName ) { } public ArgumentOutOfRangeException( String paramName, String message ) : base( message, paramName ) { } public ArgumentOutOfRangeException( String message, Exception innerException ) : base( message, innerException ) { } // We will not use this in the classlibs, but we'll provide it for // anyone that's really interested so they don't have to stick a bunch // of printf's in their code. public ArgumentOutOfRangeException( String paramName, Object actualValue, String message ) : base( message, paramName ) { m_actualValue = actualValue; } //// public override String Message //// { //// get //// { //// String s = base.Message; //// if(m_actualValue != null) //// { //// String valueMessage = String.Format( CultureInfo.CurrentCulture, Environment.GetResourceString( "ArgumentOutOfRange_ActualValue" ), m_actualValue.ToString() ); //// if(s == null) //// { //// return valueMessage; //// } //// //// return s + Environment.NewLine + valueMessage; //// } //// //// return s; //// } //// } // Gets the value of the argument that caused the exception. // Note - we don't set this anywhere in the class libraries in // version 1, but it might come in handy for other developers who // want to avoid sticking printf's in their code. public virtual Object ActualValue { get { return m_actualValue; } } private static String RangeMessage { get { #if EXCEPTION_STRINGS return Environment.GetResourceString( "Arg_ArgumentOutOfRangeException" ); #else return null; #endif } } //// [SecurityPermissionAttribute( SecurityAction.LinkDemand, Flags = SecurityPermissionFlag.SerializationFormatter )] //// public override void GetObjectData( SerializationInfo info, StreamingContext context ) //// { //// base.GetObjectData( info, context ); //// //// info.AddValue( "ActualValue", m_actualValue, typeof( Object ) ); //// } //// //// protected ArgumentOutOfRangeException( SerializationInfo info, StreamingContext context ) : base( info, context ) //// { //// m_actualValue = info.GetValue( "ActualValue", typeof( Object ) ); //// } } } ================================================ FILE: Zelig/Zelig/RunTime/Framework/mscorlib/System/ArithmeticException.cs ================================================ // ==++== // // Copyright (c) Microsoft Corporation. All rights reserved. // // ==--== /*============================================================================= ** ** Class: ArithmeticException ** ** ** Purpose: Exception class for bad arithmetic conditions! ** ** =============================================================================*/ namespace System { using System; using System.Runtime.Serialization; // The ArithmeticException is thrown when overflow or underflow // occurs. // [Serializable] public class ArithmeticException : SystemException { // Creates a new ArithmeticException with its message string set to // the empty string, its HRESULT set to COR_E_ARITHMETIC, // and its ExceptionInfo reference set to null. #if EXCEPTION_STRINGS public ArithmeticException() : base( Environment.GetResourceString( "Arg_ArithmeticException" ) ) #else public ArithmeticException() #endif { } // Creates a new ArithmeticException with its message string set to // message, its HRESULT set to COR_E_ARITHMETIC, // and its ExceptionInfo reference set to null. // public ArithmeticException( String message ) : base( message ) { } public ArithmeticException( String message, Exception innerException ) : base( message, innerException ) { } //// protected ArithmeticException( SerializationInfo info, StreamingContext context ) : base( info, context ) //// { //// } } } ================================================ FILE: Zelig/Zelig/RunTime/Framework/mscorlib/System/Array.cs ================================================ // ==++== // // Copyright (c) Microsoft Corporation. All rights reserved. // // ==--== /*============================================================ ** ** Class: Array ** ** Purpose: Base class which can be used to access any array ** ===========================================================*/ namespace System { using System; using System.Collections; using System.Collections.Generic; ////using System.Collections.ObjectModel; using System.Runtime.InteropServices; using System.Runtime.CompilerServices; using System.Runtime.ConstrainedExecution; ////using System.Runtime.Versioning; [Microsoft.Zelig.Internals.WellKnownType( "System_Array" )] [Serializable] public abstract class Array : ICloneable, IList { /// private Array() { } //// public static ReadOnlyCollection AsReadOnly( T[] array ) //// { //// if(array == null) //// { //// throw new ArgumentNullException( "array" ); //// } //// //// // T[] implements IList. //// return new ReadOnlyCollection( array ); //// } //// //// [ReliabilityContract( Consistency.WillNotCorruptState, Cer.MayFail )] //// public static void Resize( ref T[] array, int newSize ) //// { //// if(newSize < 0) //// { //// throw new ArgumentOutOfRangeException( "newSize", Environment.GetResourceString( "ArgumentOutOfRange_NeedNonNegNum" ) ); //// } //// //// T[] larray = array; //// if(larray == null) //// { //// array = new T[newSize]; //// return; //// } //// //// if(larray.Length != newSize) //// { //// T[] newArray = new T[newSize]; //// //// Array.Copy( larray, 0, newArray, 0, larray.Length > newSize ? newSize : larray.Length ); //// //// array = newArray; //// } //// } // Create instance will create an array public unsafe static Array CreateInstance( Type elementType, int length ) { if(length < 0) { #if EXCEPTION_STRINGS throw new ArgumentOutOfRangeException( "length", Environment.GetResourceString( "ArgumentOutOfRange_NeedNonNegNum" ) ); #else throw new ArgumentOutOfRangeException(); #endif } if(elementType == null) { #if EXCEPTION_STRINGS throw new ArgumentNullException( "elementType" ); #else throw new ArgumentNullException(); #endif } throw new NotImplementedException(); //// RuntimeType t = elementType.UnderlyingSystemType as RuntimeType; //// if(t == null) //// { //// throw new ArgumentException( Environment.GetResourceString( "Arg_MustBeType" ), "elementType" ); //// } //// //// return InternalCreate( (void*)t.TypeHandle.Value, 1, &length, null ); } //// public unsafe static Array CreateInstance( Type elementType, int length1, int length2 ) //// { //// if(length1 < 0 || length2 < 0) //// { //// throw new ArgumentOutOfRangeException( (length1 < 0 ? "length1" : "length2"), Environment.GetResourceString( "ArgumentOutOfRange_NeedNonNegNum" ) ); //// } //// //// if(elementType == null) //// { //// throw new ArgumentNullException( "elementType" ); //// } //// //// RuntimeType t = elementType.UnderlyingSystemType as RuntimeType; //// if(t == null) //// { //// throw new ArgumentException( Environment.GetResourceString( "Arg_MustBeType" ), "elementType" ); //// } //// //// int* pLengths = stackalloc int[2]; //// pLengths[0] = length1; //// pLengths[1] = length2; //// //// return InternalCreate( (void*)t.TypeHandle.Value, 2, pLengths, null ); //// } //// //// public unsafe static Array CreateInstance( Type elementType, int length1, int length2, int length3 ) //// { //// if(length1 < 0 || length2 < 0 || length3 < 0) //// { //// String arg = "length1"; //// if(length2 < 0) arg = "length2"; //// if(length3 < 0) arg = "length3"; //// throw new ArgumentOutOfRangeException( arg, Environment.GetResourceString( "ArgumentOutOfRange_NeedNonNegNum" ) ); //// } //// //// if(elementType == null) //// { //// throw new ArgumentNullException( "elementType" ); //// } //// //// RuntimeType t = elementType.UnderlyingSystemType as RuntimeType; //// if(t == null) //// { //// throw new ArgumentException( Environment.GetResourceString( "Arg_MustBeType" ), "elementType" ); //// } //// //// int* pLengths = stackalloc int[3]; //// pLengths[0] = length1; //// pLengths[1] = length2; //// pLengths[2] = length3; //// //// return InternalCreate( (void*)t.TypeHandle.Value, 3, pLengths, null ); //// } //// //// public unsafe static Array CreateInstance( Type elementType, params int[] lengths ) //// { //// if(lengths == null) //// { //// throw new ArgumentNullException( "lengths" ); //// } //// //// if(lengths.Length == 0) //// { //// throw new ArgumentException( Environment.GetResourceString( "Arg_NeedAtLeast1Rank" ) ); //// } //// //// // Check to make sure the lenghts are all positive. Note that we check this here to give //// // a good exception message if they are not; however we check this again inside the execution //// // engine's low level allocation function after having made a copy of the array to prevent a //// // malicious caller from mutating the array after this check. //// for(int i = 0; i < lengths.Length; i++) //// { //// if(lengths[i] < 0) //// { //// throw new ArgumentOutOfRangeException( "lengths[" + i + ']', Environment.GetResourceString( "ArgumentOutOfRange_NeedNonNegNum" ) ); //// } //// } //// //// if(elementType == null) //// { //// throw new ArgumentNullException( "elementType" ); //// } //// //// RuntimeType t = elementType.UnderlyingSystemType as RuntimeType; //// if(t == null) //// { //// throw new ArgumentException( Environment.GetResourceString( "Arg_MustBeType" ), "elementType" ); //// } //// //// fixed(int* pLengths = lengths) //// { //// return InternalCreate( (void*)t.TypeHandle.Value, lengths.Length, pLengths, null ); //// } //// } //// //// public unsafe static Array CreateInstance( Type elementType, int[] lengths, int[] lowerBounds ) //// { //// if(lengths == null) //// { //// throw new ArgumentNullException( "lengths" ); //// } //// //// if(lengths.Length == 0) //// { //// throw new ArgumentException( Environment.GetResourceString( "Arg_NeedAtLeast1Rank" ) ); //// } //// //// // Check to make sure the lenghts are all positive. Note that we check this here to give //// // a good exception message if they are not; however we check this again inside the execution //// // engine's low level allocation function after having made a copy of the array to prevent a //// // malicious caller from mutating the array after this check. //// for(int i = 0; i < lengths.Length; i++) //// { //// if(lengths[i] < 0) //// { //// throw new ArgumentOutOfRangeException( "lengths[" + i + ']', Environment.GetResourceString( "ArgumentOutOfRange_NeedNonNegNum" ) ); //// } //// } //// //// if(lowerBounds == null) //// { //// throw new ArgumentNullException( "lowerBounds" ); //// } //// //// if(lengths.Length != lowerBounds.Length) //// { //// throw new ArgumentException( Environment.GetResourceString( "Arg_RanksAndBounds" ) ); //// } //// //// //// if(elementType == null) //// { //// throw new ArgumentNullException( "elementType" ); //// } //// //// RuntimeType t = elementType.UnderlyingSystemType as RuntimeType; //// if(t == null) //// { //// throw new ArgumentException( Environment.GetResourceString( "Arg_MustBeType" ), "elementType" ); //// } //// //// fixed(int* pLengths = lengths) //// { //// fixed(int* pLowerBounds = lowerBounds) //// { //// return InternalCreate( (void*)t.TypeHandle.Value, lengths.Length, pLengths, pLowerBounds ); //// } //// } //// } //// //// [ResourceExposure( ResourceScope.None )] //// [MethodImpl( MethodImplOptions.InternalCall )] //// private unsafe static extern Array InternalCreate( void* elementType, int rank, int* pLengths, int* pLowerBounds ); // Copies length elements from sourceArray, starting at index 0, to // destinationArray, starting at index 0. // //// [ReliabilityContract( Consistency.MayCorruptInstance, Cer.MayFail )] public static void Copy( Array sourceArray, Array destinationArray, int length ) { if(sourceArray == null) { #if EXCEPTION_STRINGS throw new ArgumentNullException( "sourceArray" ); #else throw new ArgumentNullException(); #endif } if(destinationArray == null) { #if EXCEPTION_STRINGS throw new ArgumentNullException( "destinationArray" ); #else throw new ArgumentNullException(); #endif } Copy( sourceArray, sourceArray.GetLowerBound( 0 ), destinationArray, destinationArray.GetLowerBound( 0 ), length, false ); } // Copies length elements from sourceArray, starting at sourceIndex, to // destinationArray, starting at destinationIndex. // //// [ReliabilityContract( Consistency.MayCorruptInstance, Cer.MayFail )] public static void Copy( Array sourceArray, int sourceIndex, Array destinationArray, int destinationIndex, int length ) { Copy( sourceArray, sourceIndex, destinationArray, destinationIndex, length, false ); } // Reliability-wise, this method will either possibly corrupt your // instance & might fail when called from within a CER, or if the // reliable flag is true, it will either always succeed or always // throw an exception with no side effects. //// [ReliabilityContract( Consistency.MayCorruptInstance, Cer.MayFail )] //// [ResourceExposure( ResourceScope.None )] [MethodImpl( MethodImplOptions.InternalCall )] internal static extern void Copy( Array sourceArray, int sourceIndex, Array destinationArray, int destinationIndex, int length, bool reliable ); //// // Provides a strong exception guarantee - either it succeeds, or //// // it throws an exception with no side effects. The arrays must be //// // compatible array types based on the array element type - this //// // method does not support casting, boxing, or primitive widening. //// // It will up-cast, assuming the array types are correct. //// [ReliabilityContract( Consistency.WillNotCorruptState, Cer.Success )] //// public static void ConstrainedCopy( Array sourceArray, int sourceIndex, Array destinationArray, int destinationIndex, int length ) //// { //// Copy( sourceArray, sourceIndex, destinationArray, destinationIndex, length, true ); //// } // Sets length elements in array to 0 (or null for Object arrays), starting // at index. // //// [ResourceExposure( ResourceScope.None )] //// [ReliabilityContract( Consistency.WillNotCorruptState, Cer.Success )] [MethodImpl( MethodImplOptions.InternalCall )] public static extern void Clear( Array array, int index, int length ); // The various Get values... //// public unsafe Object GetValue( params int[] indices ) //// { //// if(indices == null) //// { //// throw new ArgumentNullException( "indices" ); //// } //// //// if(Rank != indices.Length) //// { //// throw new ArgumentException( Environment.GetResourceString( "Arg_RankIndices" ) ); //// } //// //// TypedReference elemref = new TypedReference(); //// //// fixed(int* pIndices = indices) //// { //// InternalGetReference( &elemref, indices.Length, pIndices ); //// } //// //// return TypedReference.InternalToObject( &elemref ); //// } public unsafe Object GetValue( int index ) { throw new NotImplementedException(); //// if(Rank != 1) //// { //// throw new ArgumentException( Environment.GetResourceString( "Arg_Need1DArray" ) ); //// } //// //// TypedReference elemref = new TypedReference(); //// //// InternalGetReference( &elemref, 1, &index ); //// //// return TypedReference.InternalToObject( &elemref ); } //// public unsafe Object GetValue( int index1, int index2 ) //// { //// if(Rank != 2) //// { //// throw new ArgumentException( Environment.GetResourceString( "Arg_Need2DArray" ) ); //// } //// //// int* pIndices = stackalloc int[2]; //// pIndices[0] = index1; //// pIndices[1] = index2; //// //// TypedReference elemref = new TypedReference(); //// //// InternalGetReference( &elemref, 2, pIndices ); //// //// return TypedReference.InternalToObject( &elemref ); //// } //// //// public unsafe Object GetValue( int index1, int index2, int index3 ) //// { //// if(Rank != 3) //// { //// throw new ArgumentException( Environment.GetResourceString( "Arg_Need3DArray" ) ); //// } //// //// int* pIndices = stackalloc int[3]; //// pIndices[0] = index1; //// pIndices[1] = index2; //// pIndices[2] = index3; //// //// TypedReference elemref = new TypedReference(); //// //// InternalGetReference( &elemref, 3, pIndices ); //// //// return TypedReference.InternalToObject( &elemref ); //// } public unsafe void SetValue( Object value, int index ) { throw new NotImplementedException(); //// if(Rank != 1) //// { //// throw new ArgumentException( Environment.GetResourceString( "Arg_Need1DArray" ) ); //// } //// //// TypedReference elemref = new TypedReference(); //// //// InternalGetReference( &elemref, 1, &index ); //// //// InternalSetValue( &elemref, value ); } //// public unsafe void SetValue( Object value, int index1, int index2 ) //// { //// if(Rank != 2) //// { //// throw new ArgumentException( Environment.GetResourceString( "Arg_Need2DArray" ) ); //// } //// //// int* pIndices = stackalloc int[2]; //// pIndices[0] = index1; //// pIndices[1] = index2; //// //// TypedReference elemref = new TypedReference(); //// //// InternalGetReference( &elemref, 2, pIndices ); //// //// InternalSetValue( &elemref, value ); //// } //// //// public unsafe void SetValue( Object value, int index1, int index2, int index3 ) //// { //// if(Rank != 3) //// { //// throw new ArgumentException( Environment.GetResourceString( "Arg_Need3DArray" ) ); //// } //// //// int* pIndices = stackalloc int[3]; //// pIndices[0] = index1; //// pIndices[1] = index2; //// pIndices[2] = index3; //// //// TypedReference elemref = new TypedReference(); //// //// InternalGetReference( &elemref, 3, pIndices ); //// //// InternalSetValue( &elemref, value ); //// } //// //// public unsafe void SetValue( Object value, params int[] indices ) //// { //// if(indices == null) //// { //// throw new ArgumentNullException( "indices" ); //// } //// if(Rank != indices.Length) //// { //// throw new ArgumentException( Environment.GetResourceString( "Arg_RankIndices" ) ); //// } //// //// TypedReference elemref = new TypedReference(); //// //// fixed(int* pIndices = indices) //// { //// InternalGetReference( &elemref, indices.Length, pIndices ); //// } //// //// InternalSetValue( &elemref, value ); //// } //// //// //// [ResourceExposure( ResourceScope.None )] //// [MethodImpl( MethodImplOptions.InternalCall )] //// // reference to TypedReference is banned, so have to pass result as pointer //// private unsafe extern void InternalGetReference( void* elemRef, int rank, int* pIndices ); //// //// // Ideally, we would like to use TypedReference.SetValue instead. Unfortunately, TypedReference.SetValue //// // always throws not-supported exception //// [ResourceExposure( ResourceScope.None )] //// [MethodImpl( MethodImplOptions.InternalCall )] //// private unsafe extern static void InternalSetValue( void* target, Object value ); public extern int Length { //// [ResourceExposure( ResourceScope.None )] //// [ReliabilityContract( Consistency.WillNotCorruptState, Cer.Success )] [MethodImpl( MethodImplOptions.InternalCall )] get; } //// [ReliabilityContract( Consistency.WillNotCorruptState, Cer.Success )] private static int GetMedian( int low, int hi ) { BCLDebug.Assert( hi - low >= 0, "Length overflow!" ); return low + ((hi - low) >> 1); } //// [ResourceExposure( ResourceScope.None )] [MethodImpl( MethodImplOptions.InternalCall )] public extern int GetLength( int dimension ); public extern int Rank { //// [ResourceExposure( ResourceScope.None )] //// [ReliabilityContract( Consistency.WillNotCorruptState, Cer.Success )] [MethodImpl( MethodImplOptions.InternalCall )] get; } //// [ResourceExposure( ResourceScope.None )] //// [ReliabilityContract( Consistency.WillNotCorruptState, Cer.Success )] [MethodImpl( MethodImplOptions.InternalCall )] public extern int GetUpperBound( int dimension ); //// [ResourceExposure( ResourceScope.None )] //// [ReliabilityContract( Consistency.WillNotCorruptState, Cer.Success )] [MethodImpl( MethodImplOptions.InternalCall )] public extern int GetLowerBound( int dimension ); //// [ResourceExposure( ResourceScope.None )] //// [ReliabilityContract( Consistency.WillNotCorruptState, Cer.Success )] //// [MethodImpl( MethodImplOptions.InternalCall )] //// internal extern int GetDataPtrOffsetInternal(); // Number of elements in the Array. int ICollection.Count { get { return Length; } } // Returns an object appropriate for synchronizing access to this // Array. public Object SyncRoot { get { return this; } } // Is this Array read-only? public bool IsReadOnly { get { return false; } } public bool IsFixedSize { get { return true; } } // Is this Array synchronized (i.e., thread-safe)? If you want a synchronized // collection, you can use SyncRoot as an object to synchronize your // collection with. You could also call GetSynchronized() // to get a synchronized wrapper around the Array. public bool IsSynchronized { get { return false; } } Object IList.this[int index] { get { return GetValue( index ); } set { SetValue( value, index ); } } int IList.Add( Object value ) { #if EXCEPTION_STRINGS throw new NotSupportedException( Environment.GetResourceString( "NotSupported_FixedSizeCollection" ) ); #else throw new NotSupportedException(); #endif } bool IList.Contains( Object value ) { return Array.IndexOf( this, value ) >= this.GetLowerBound( 0 ); } void IList.Clear() { Array.Clear( this, 0, this.Length ); } int IList.IndexOf( Object value ) { return Array.IndexOf( this, value ); } void IList.Insert( int index, Object value ) { #if EXCEPTION_STRINGS throw new NotSupportedException( Environment.GetResourceString( "NotSupported_FixedSizeCollection" ) ); #else throw new NotSupportedException(); #endif } void IList.Remove( Object value ) { #if EXCEPTION_STRINGS throw new NotSupportedException( Environment.GetResourceString( "NotSupported_FixedSizeCollection" ) ); #else throw new NotSupportedException(); #endif } void IList.RemoveAt( int index ) { #if EXCEPTION_STRINGS throw new NotSupportedException( Environment.GetResourceString( "NotSupported_FixedSizeCollection" ) ); #else throw new NotSupportedException(); #endif } // Make a new array which is a deep copy of the original array. // public Object Clone() { return MemberwiseClone(); } // Searches an array for a given element using a binary search algorithm. // Elements of the array are compared to the search value using the // IComparable interface, which must be implemented by all elements // of the array and the given search value. This method assumes that the // array is already sorted according to the IComparable interface; // if this is not the case, the result will be incorrect. // // The method returns the index of the given value in the array. If the // array does not contain the given value, the method returns a negative // integer. The bitwise complement operator (~) can be applied to a // negative result to produce the index of the first element (if any) that // is larger than the given search value. // //// [ReliabilityContract( Consistency.WillNotCorruptState, Cer.MayFail )] public static int BinarySearch( Array array, Object value ) { if(array == null) { #if EXCEPTION_STRINGS throw new ArgumentNullException( "array" ); #else throw new ArgumentNullException(); #endif } int lb = array.GetLowerBound( 0 ); return BinarySearch( array, lb, array.Length, value, null ); } // Searches a section of an array for a given element using a binary search // algorithm. Elements of the array are compared to the search value using // the IComparable interface, which must be implemented by all // elements of the array and the given search value. This method assumes // that the array is already sorted according to the IComparable // interface; if this is not the case, the result will be incorrect. // // The method returns the index of the given value in the array. If the // array does not contain the given value, the method returns a negative // integer. The bitwise complement operator (~) can be applied to a // negative result to produce the index of the first element (if any) that // is larger than the given search value. // //// [ReliabilityContract( Consistency.WillNotCorruptState, Cer.MayFail )] public static int BinarySearch( Array array, int index, int length, Object value ) { return BinarySearch( array, index, length, value, null ); } // Searches an array for a given element using a binary search algorithm. // Elements of the array are compared to the search value using the given // IComparer interface. If comparer is null, elements of the // array are compared to the search value using the IComparable // interface, which in that case must be implemented by all elements of the // array and the given search value. This method assumes that the array is // already sorted; if this is not the case, the result will be incorrect. // // The method returns the index of the given value in the array. If the // array does not contain the given value, the method returns a negative // integer. The bitwise complement operator (~) can be applied to a // negative result to produce the index of the first element (if any) that // is larger than the given search value. // //// [ReliabilityContract( Consistency.WillNotCorruptState, Cer.MayFail )] public static int BinarySearch( Array array, Object value, IComparer comparer ) { if(array == null) { #if EXCEPTION_STRINGS throw new ArgumentNullException( "array" ); #else throw new ArgumentNullException(); #endif } int lb = array.GetLowerBound( 0 ); return BinarySearch( array, lb, array.Length, value, comparer ); } // Searches a section of an array for a given element using a binary search // algorithm. Elements of the array are compared to the search value using // the given IComparer interface. If comparer is null, // elements of the array are compared to the search value using the // IComparable interface, which in that case must be implemented by // all elements of the array and the given search value. This method // assumes that the array is already sorted; if this is not the case, the // result will be incorrect. // // The method returns the index of the given value in the array. If the // array does not contain the given value, the method returns a negative // integer. The bitwise complement operator (~) can be applied to a // negative result to produce the index of the first element (if any) that // is larger than the given search value. // //// [ReliabilityContract( Consistency.WillNotCorruptState, Cer.MayFail )] public static int BinarySearch( Array array, int index, int length, Object value, IComparer comparer ) { if(array == null) { #if EXCEPTION_STRINGS throw new ArgumentNullException( "array" ); #else throw new ArgumentNullException(); #endif } int lb = array.GetLowerBound( 0 ); if(index < lb || length < 0) { #if EXCEPTION_STRINGS throw new ArgumentOutOfRangeException( (index < lb ? "index" : "length"), Environment.GetResourceString( "ArgumentOutOfRange_NeedNonNegNum" ) ); #else throw new ArgumentOutOfRangeException(); #endif } if(array.Length - (index - lb) < length) { #if EXCEPTION_STRINGS throw new ArgumentException( Environment.GetResourceString( "Argument_InvalidOffLen" ) ); #else throw new ArgumentException(); #endif } if(array.Rank != 1) { #if EXCEPTION_STRINGS throw new RankException( Environment.GetResourceString( "Rank_MultiDimNotSupported" ) ); #else throw new RankException(); #endif } if(comparer == null) comparer = Comparer.Default; //// if(comparer == Comparer.Default) //// { //// int retval; //// bool r = TrySZBinarySearch( array, index, length, value, out retval ); //// if(r) //// { //// return retval; //// } //// } int lo = index; int hi = index + length - 1; Object[] objArray = array as Object[]; if(objArray != null) { while(lo <= hi) { // i might overflow if lo and hi are both large positive numbers. int i = GetMedian( lo, hi ); int c; try { c = comparer.Compare( objArray[i], value ); } catch(Exception e) { #if EXCEPTION_STRINGS throw new InvalidOperationException( Environment.GetResourceString( "InvalidOperation_IComparerFailed" ), e ); #else throw new InvalidOperationException(null, e); #endif } if(c == 0) return i; if(c < 0) { lo = i + 1; } else { hi = i - 1; } } } else { while(lo <= hi) { int i = GetMedian( lo, hi ); int c; try { c = comparer.Compare( array.GetValue( i ), value ); } catch(Exception e) { #if EXCEPTION_STRINGS throw new InvalidOperationException( Environment.GetResourceString( "InvalidOperation_IComparerFailed" ), e ); #else throw new InvalidOperationException( null, e ); #endif } if(c == 0) return i; if(c < 0) { lo = i + 1; } else { hi = i - 1; } } } return ~lo; } //// [ResourceExposure( ResourceScope.None )] //// [ReliabilityContract( Consistency.WillNotCorruptState, Cer.MayFail )] //// [MethodImpl( MethodImplOptions.InternalCall )] //// private static extern bool TrySZBinarySearch( Array sourceArray, int sourceIndex, int count, Object value, out int retVal ); //// [ReliabilityContract(Consistency.WillNotCorruptState, Cer.MayFail)] public static int BinarySearch( T[] array, T value ) { if(array == null) { #if EXCEPTION_STRINGS throw new ArgumentNullException( "array" ); #else throw new ArgumentNullException(); #endif } return BinarySearch( array, 0, array.Length, value, null ); } //// [ReliabilityContract( Consistency.WillNotCorruptState, Cer.MayFail )] public static int BinarySearch( T[] array, T value, System.Collections.Generic.IComparer comparer ) { if(array == null) { #if EXCEPTION_STRINGS throw new ArgumentNullException( "array" ); #else throw new ArgumentNullException(); #endif } return BinarySearch( array, 0, array.Length, value, comparer ); } //// [ReliabilityContract( Consistency.WillNotCorruptState, Cer.MayFail )] public static int BinarySearch( T[] array, int index, int length, T value ) { return BinarySearch( array, index, length, value, null ); } //// [ReliabilityContract( Consistency.WillNotCorruptState, Cer.MayFail )] public static int BinarySearch( T[] array, int index, int length, T value, System.Collections.Generic.IComparer comparer ) { if(array == null) { #if EXCEPTION_STRINGS throw new ArgumentNullException( "array" ); #else throw new ArgumentNullException(); #endif } if(index < 0 || length < 0) { #if EXCEPTION_STRINGS throw new ArgumentOutOfRangeException( (index < 0 ? "index" : "length"), Environment.GetResourceString( "ArgumentOutOfRange_NeedNonNegNum" ) ); #else throw new ArgumentOutOfRangeException(); #endif } if(array.Length - index < length) { #if EXCEPTION_STRINGS throw new ArgumentException( Environment.GetResourceString( "Argument_InvalidOffLen" ) ); #else throw new ArgumentException(); #endif } return ArraySortHelper.Default.BinarySearch( array, index, length, value, comparer ); } //// public static TOutput[] ConvertAll( TInput[] array, Converter converter ) //// { //// if(array == null) //// { //// throw new ArgumentNullException( "array" ); //// } //// //// if(converter == null) //// { //// throw new ArgumentNullException( "converter" ); //// } //// //// TOutput[] newArray = new TOutput[array.Length]; //// for(int i = 0; i < array.Length; i++) //// { //// newArray[i] = converter( array[i] ); //// } //// return newArray; //// } // CopyTo copies a collection into an Array, starting at a particular // index into the array. // // This method is to support the ICollection interface, and calls // Array.Copy internally. If you aren't using ICollection explicitly, // call Array.Copy to avoid an extra indirection. // public void CopyTo( Array array, int index ) { if(array != null && array.Rank != 1) { #if EXCEPTION_STRINGS throw new ArgumentException( Environment.GetResourceString( "Arg_RankMultiDimNotSupported" ) ); #else throw new ArgumentException(); #endif } // Note: Array.Copy throws a RankException and we want a consistent ArgumentException for all the IList CopyTo methods. Array.Copy( this, GetLowerBound( 0 ), array, index, Length ); } //// public static bool Exists( T[] array, Predicate match ) //// { //// return Array.FindIndex( array, match ) != -1; //// } //// //// public static T Find( T[] array, Predicate match ) //// { //// if(array == null) //// { //// throw new ArgumentNullException( "array" ); //// } //// //// if(match == null) //// { //// throw new ArgumentNullException( "match" ); //// } //// //// for(int i = 0; i < array.Length; i++) //// { //// if(match( array[i] )) //// { //// return array[i]; //// } //// } //// //// return default( T ); //// } //// //// public static T[] FindAll( T[] array, Predicate match ) //// { //// if(array == null) //// { //// throw new ArgumentNullException( "array" ); //// } //// //// if(match == null) //// { //// throw new ArgumentNullException( "match" ); //// } //// //// List list = new List(); //// //// for(int i = 0; i < array.Length; i++) //// { //// if(match( array[i] )) //// { //// list.Add( array[i] ); //// } //// } //// //// return list.ToArray(); //// } //// //// public static int FindIndex( T[] array, Predicate match ) //// { //// if(array == null) //// { //// throw new ArgumentNullException( "array" ); //// } //// //// return FindIndex( array, 0, array.Length, match ); //// } //// //// public static int FindIndex( T[] array, int startIndex, Predicate match ) //// { //// if(array == null) //// { //// throw new ArgumentNullException( "array" ); //// } //// //// return FindIndex( array, startIndex, array.Length - startIndex, match ); //// } //// //// public static int FindIndex( T[] array, int startIndex, int count, Predicate match ) //// { //// if(array == null) //// { //// throw new ArgumentNullException( "array" ); //// } //// //// if(startIndex < 0 || startIndex > array.Length) //// { //// throw new ArgumentOutOfRangeException( "startIndex", Environment.GetResourceString( "ArgumentOutOfRange_Index" ) ); //// } //// //// if(count < 0 || startIndex > array.Length - count) //// { //// throw new ArgumentOutOfRangeException( "count", Environment.GetResourceString( "ArgumentOutOfRange_Count" ) ); //// } //// //// if(match == null) //// { //// throw new ArgumentNullException( "match" ); //// } //// //// int endIndex = startIndex + count; //// //// for(int i = startIndex; i < endIndex; i++) //// { //// if(match( array[i] )) return i; //// } //// //// return -1; //// } //// //// public static T FindLast( T[] array, Predicate match ) //// { //// if(array == null) //// { //// throw new ArgumentNullException( "array" ); //// } //// //// if(match == null) //// { //// throw new ArgumentNullException( "match" ); //// } //// //// for(int i = array.Length - 1; i >= 0; i--) //// { //// if(match( array[i] )) //// { //// return array[i]; //// } //// } //// //// return default( T ); //// } //// //// public static int FindLastIndex( T[] array, Predicate match ) //// { //// if(array == null) //// { //// throw new ArgumentNullException( "array" ); //// } //// //// return FindLastIndex( array, array.Length - 1, array.Length, match ); //// } //// //// public static int FindLastIndex( T[] array, int startIndex, Predicate match ) //// { //// if(array == null) //// { //// throw new ArgumentNullException( "array" ); //// } //// //// return FindLastIndex( array, startIndex, startIndex + 1, match ); //// } //// //// public static int FindLastIndex( T[] array, int startIndex, int count, Predicate match ) //// { //// if(array == null) //// { //// throw new ArgumentNullException( "array" ); //// } //// //// if(match == null) //// { //// throw new ArgumentNullException( "match" ); //// } //// //// if(array.Length == 0) //// { //// // Special case for 0 length List //// if(startIndex != -1) //// { //// throw new ArgumentOutOfRangeException( "startIndex", Environment.GetResourceString( "ArgumentOutOfRange_Index" ) ); //// } //// } //// else //// { //// // Make sure we're not out of range //// if(startIndex < 0 || startIndex >= array.Length) //// { //// throw new ArgumentOutOfRangeException( "startIndex", Environment.GetResourceString( "ArgumentOutOfRange_Index" ) ); //// } //// } //// //// // 2nd have of this also catches when startIndex == MAXINT, so MAXINT - 0 + 1 == -1, which is < 0. //// if(count < 0 || startIndex - count + 1 < 0) //// { //// throw new ArgumentOutOfRangeException( "count", Environment.GetResourceString( "ArgumentOutOfRange_Count" ) ); //// } //// //// int endIndex = startIndex - count; //// //// for(int i = startIndex; i > endIndex; i--) //// { //// if(match( array[i] )) //// { //// return i; //// } //// } //// //// return -1; //// } public static void ForEach( T[] array, Action action ) { if(array == null) { #if EXCEPTION_STRINGS throw new ArgumentNullException( "array" ); #else throw new ArgumentNullException(); #endif } if(action == null) { #if EXCEPTION_STRINGS throw new ArgumentNullException( "action" ); #else throw new ArgumentNullException(); #endif } for(int i = 0; i < array.Length; i++) { action( array[i] ); } } // GetEnumerator returns an IEnumerator over this Array. // // Currently, only one dimensional arrays are supported. // public IEnumerator GetEnumerator() { int lowerBound = GetLowerBound( 0 ); if(Rank == 1 && lowerBound == 0) { return new SZArrayEnumerator( this ); } else { throw new NotImplementedException(); //// return new ArrayEnumerator( this, lowerBound, Length ); } } // Returns the index of the first occurrence of a given value in an array. // The array is searched forwards, and the elements of the array are // compared to the given value using the Object.Equals method. // //// [ReliabilityContract( Consistency.WillNotCorruptState, Cer.MayFail )] public static int IndexOf( Array array, Object value ) { if(array == null) { #if EXCEPTION_STRINGS throw new ArgumentNullException( "array" ); #else throw new ArgumentNullException(); #endif } int lb = array.GetLowerBound( 0 ); return IndexOf( array, value, lb, array.Length ); } // Returns the index of the first occurrence of a given value in a range of // an array. The array is searched forwards, starting at index // startIndex and ending at the last element of the array. The // elements of the array are compared to the given value using the // Object.Equals method. // //// [ReliabilityContract( Consistency.WillNotCorruptState, Cer.MayFail )] public static int IndexOf( Array array, Object value, int startIndex ) { if(array == null) { #if EXCEPTION_STRINGS throw new ArgumentNullException( "array" ); #else throw new ArgumentNullException(); #endif } int lb = array.GetLowerBound( 0 ); return IndexOf( array, value, startIndex, array.Length - startIndex + lb ); } // Returns the index of the first occurrence of a given value in a range of // an array. The array is searched forwards, starting at index // startIndex and upto count elements. The // elements of the array are compared to the given value using the // Object.Equals method. // //// [ReliabilityContract( Consistency.WillNotCorruptState, Cer.MayFail )] public static int IndexOf( Array array, Object value, int startIndex, int count ) { if(array == null) { #if EXCEPTION_STRINGS throw new ArgumentNullException( "array" ); #else throw new ArgumentNullException(); #endif } if(array.Rank != 1) { #if EXCEPTION_STRINGS throw new RankException( Environment.GetResourceString( "Rank_MultiDimNotSupported" ) ); #else throw new RankException(); #endif } int lb = array.GetLowerBound( 0 ); if(startIndex < lb || startIndex > array.Length + lb) { #if EXCEPTION_STRINGS throw new ArgumentOutOfRangeException( "startIndex", Environment.GetResourceString( "ArgumentOutOfRange_Index" ) ); #else throw new ArgumentOutOfRangeException(); #endif } if(count < 0 || count > array.Length - startIndex + lb) { #if EXCEPTION_STRINGS throw new ArgumentOutOfRangeException( "count", Environment.GetResourceString( "ArgumentOutOfRange_Count" ) ); #else throw new ArgumentOutOfRangeException(); #endif } //// // Try calling a quick native method to handle primitive types. //// int retVal; //// bool r = TrySZIndexOf( array, startIndex, count, value, out retVal ); //// if(r) //// { //// return retVal; //// } Object[] objArray = array as Object[]; int endIndex = startIndex + count; if(objArray != null) { if(value == null) { for(int i = startIndex; i < endIndex; i++) { if(objArray[i] == null) return i; } } else { for(int i = startIndex; i < endIndex; i++) { Object obj = objArray[i]; if(obj != null && obj.Equals( value )) return i; } } } else { for(int i = startIndex; i < endIndex; i++) { Object obj = array.GetValue( i ); if(obj == null) { if(value == null) return i; } else { if(obj.Equals( value )) return i; } } } // Return one less than the lower bound of the array. This way, // for arrays with a lower bound of -1 we will not return -1 when the // item was not found. And for SZArrays (the vast majority), -1 still // works for them. return lb - 1; } public static int IndexOf( T[] array, T value ) { if(array == null) { #if EXCEPTION_STRINGS throw new ArgumentNullException( "array" ); #else throw new ArgumentNullException(); #endif } return IndexOf( array, value, 0, array.Length ); } public static int IndexOf( T[] array, T value, int startIndex ) { if(array == null) { #if EXCEPTION_STRINGS throw new ArgumentNullException( "array" ); #else throw new ArgumentNullException(); #endif } return IndexOf( array, value, startIndex, array.Length - startIndex ); } public static int IndexOf( T[] array, T value, int startIndex, int count ) { if(array == null) { #if EXCEPTION_STRINGS throw new ArgumentNullException( "array" ); #else throw new ArgumentNullException(); #endif } if(startIndex < 0 || startIndex > array.Length) { #if EXCEPTION_STRINGS throw new ArgumentOutOfRangeException( "startIndex", Environment.GetResourceString( "ArgumentOutOfRange_Index" ) ); #else throw new ArgumentOutOfRangeException(); #endif } if(count < 0 || count > array.Length - startIndex) { #if EXCEPTION_STRINGS throw new ArgumentOutOfRangeException( "count", Environment.GetResourceString( "ArgumentOutOfRange_Count" ) ); #else throw new ArgumentOutOfRangeException(); #endif } return EqualityComparer.Default.IndexOf( array, value, startIndex, count ); } //// [ResourceExposure( ResourceScope.None )] //// [ReliabilityContract( Consistency.WillNotCorruptState, Cer.MayFail )] //// [MethodImpl( MethodImplOptions.InternalCall )] //// private static extern bool TrySZIndexOf( Array sourceArray, int sourceIndex, int count, Object value, out int retVal ); // Returns the index of the last occurrence of a given value in an array. // The array is searched backwards, and the elements of the array are // compared to the given value using the Object.Equals method. // //// [ReliabilityContract( Consistency.WillNotCorruptState, Cer.MayFail )] public static int LastIndexOf( Array array, Object value ) { if(array == null) { #if EXCEPTION_STRINGS throw new ArgumentNullException( "array" ); #else throw new ArgumentNullException(); #endif } int lb = array.GetLowerBound( 0 ); return LastIndexOf( array, value, array.Length - 1 + lb, array.Length ); } // Returns the index of the last occurrence of a given value in a range of // an array. The array is searched backwards, starting at index // startIndex and ending at index 0. The elements of the array are // compared to the given value using the Object.Equals method. // //// [ReliabilityContract( Consistency.WillNotCorruptState, Cer.MayFail )] public static int LastIndexOf( Array array, Object value, int startIndex ) { if(array == null) { #if EXCEPTION_STRINGS throw new ArgumentNullException( "array" ); #else throw new ArgumentNullException(); #endif } int lb = array.GetLowerBound( 0 ); return LastIndexOf( array, value, startIndex, startIndex + 1 - lb ); } // Returns the index of the last occurrence of a given value in a range of // an array. The array is searched backwards, starting at index // startIndex and counting uptocount elements. The elements of // the array are compared to the given value using the Object.Equals // method. // //// [ReliabilityContract( Consistency.WillNotCorruptState, Cer.MayFail )] public static int LastIndexOf( Array array, Object value, int startIndex, int count ) { if(array == null) { #if EXCEPTION_STRINGS throw new ArgumentNullException( "array" ); #else throw new ArgumentNullException(); #endif } if(array.Rank != 1) { #if EXCEPTION_STRINGS throw new RankException( Environment.GetResourceString( "Rank_MultiDimNotSupported" ) ); #else throw new RankException(); #endif } int lb = array.GetLowerBound( 0 ); if(array.Length == 0) { return lb - 1; } if(startIndex < lb || startIndex >= array.Length + lb) { #if EXCEPTION_STRINGS throw new ArgumentOutOfRangeException( "startIndex", Environment.GetResourceString( "ArgumentOutOfRange_Index" ) ); #else throw new ArgumentOutOfRangeException(); #endif } if(count < 0) { #if EXCEPTION_STRINGS throw new ArgumentOutOfRangeException( "count", Environment.GetResourceString( "ArgumentOutOfRange_Count" ) ); #else throw new ArgumentOutOfRangeException(); #endif } if(count > startIndex - lb + 1) { #if EXCEPTION_STRINGS throw new ArgumentOutOfRangeException( "endIndex", Environment.GetResourceString( "ArgumentOutOfRange_EndIndexStartIndex" ) ); #else throw new ArgumentOutOfRangeException(); #endif } //// // Try calling a quick native method to handle primitive types. //// int retVal; //// bool r = TrySZLastIndexOf( array, startIndex, count, value, out retVal ); //// if(r) //// { //// return retVal; //// } Object[] objArray = array as Object[]; int endIndex = startIndex - count + 1; if(objArray != null) { if(value == null) { for(int i = startIndex; i >= endIndex; i--) { if(objArray[i] == null) return i; } } else { for(int i = startIndex; i >= endIndex; i--) { Object obj = objArray[i]; if(obj != null && obj.Equals( value )) return i; } } } else { for(int i = startIndex; i >= endIndex; i--) { Object obj = array.GetValue( i ); if(obj == null) { if(value == null) return i; } else { if(obj.Equals( value )) return i; } } } return lb - 1; // Return lb-1 for arrays with negative lower bounds. } //// public static int LastIndexOf( T[] array, T value ) //// { //// if(array == null) //// { //// throw new ArgumentNullException( "array" ); //// } //// //// return LastIndexOf( array, value, array.Length - 1, array.Length ); //// } //// //// public static int LastIndexOf( T[] array, T value, int startIndex ) //// { //// if(array == null) //// { //// throw new ArgumentNullException( "array" ); //// } //// //// // if array is empty and startIndex is 0, we need to pass 0 as count //// return LastIndexOf( array, value, startIndex, (array.Length == 0) ? 0 : (startIndex + 1) ); //// } //// //// public static int LastIndexOf( T[] array, T value, int startIndex, int count ) //// { //// if(array == null) //// { //// throw new ArgumentNullException( "array" ); //// } //// //// if(array.Length == 0) //// { //// // //// // Special case for 0 length List //// // accept -1 and 0 as valid startIndex for compablility reason. //// // //// if(startIndex != -1 && startIndex != 0) //// { //// throw new ArgumentOutOfRangeException( "startIndex", Environment.GetResourceString( "ArgumentOutOfRange_Index" ) ); //// } //// //// // only 0 is a valid value for count if array is empty //// if(count != 0) //// { //// throw new ArgumentOutOfRangeException( "count", Environment.GetResourceString( "ArgumentOutOfRange_Count" ) ); //// } //// return -1; //// } //// //// // Make sure we're not out of range //// if(startIndex < 0 || startIndex >= array.Length) //// { //// throw new ArgumentOutOfRangeException( "startIndex", Environment.GetResourceString( "ArgumentOutOfRange_Index" ) ); //// } //// //// // 2nd have of this also catches when startIndex == MAXINT, so MAXINT - 0 + 1 == -1, which is < 0. //// if(count < 0 || startIndex - count + 1 < 0) //// { //// throw new ArgumentOutOfRangeException( "count", Environment.GetResourceString( "ArgumentOutOfRange_Count" ) ); //// } //// //// return EqualityComparer.Default.LastIndexOf( array, value, startIndex, count ); //// } //// [ResourceExposure( ResourceScope.None )] //// [ReliabilityContract( Consistency.WillNotCorruptState, Cer.MayFail )] //// [MethodImpl( MethodImplOptions.InternalCall )] //// private static extern bool TrySZLastIndexOf( Array sourceArray, int sourceIndex, int count, Object value, out int retVal ); // Reverses all elements of the given array. Following a call to this // method, an element previously located at index i will now be // located at index length - i - 1, where length is the // length of the array. // //// [ReliabilityContract( Consistency.MayCorruptInstance, Cer.MayFail )] public static void Reverse( Array array ) { if(array == null) { #if EXCEPTION_STRINGS throw new ArgumentNullException( "array" ); #else throw new ArgumentNullException(); #endif } Reverse( array, array.GetLowerBound( 0 ), array.Length ); } // Reverses the elements in a range of an array. Following a call to this // method, an element in the range given by index and count // which was previously located at index i will now be located at // index index + (index + count - i - 1). // Reliability note: This may fail because it may have to box objects. // //// [ReliabilityContract( Consistency.MayCorruptInstance, Cer.MayFail )] public static void Reverse( Array array, int index, int length ) { throw new NotImplementedException(); //// if(array == null) //// { //// throw new ArgumentNullException( "array" ); //// } //// if(array.Rank != 1) //// { //// throw new RankException( Environment.GetResourceString( "Rank_MultiDimNotSupported" ) ); //// } //// //// int lb = array.GetLowerBound( 0 ); //// if(index < lb || length < 0) //// { //// throw new ArgumentOutOfRangeException( (index < 0 ? "index" : "length"), Environment.GetResourceString( "ArgumentOutOfRange_NeedNonNegNum" ) ); //// } //// if(array.Length - (index - lb) < length) //// { //// throw new ArgumentException( Environment.GetResourceString( "Argument_InvalidOffLen" ) ); //// } //// //// bool r = TrySZReverse( array, index, length ); //// if(r) //// { //// return; //// } //// //// int i = index; //// int j = index + length - 1; //// Object[] objArray = array as Object[]; //// if(objArray != null) //// { //// while(i < j) //// { //// Object temp = objArray[i]; //// objArray[i] = objArray[j]; //// objArray[j] = temp; //// i++; //// j--; //// } //// } //// else //// { //// while(i < j) //// { //// Object temp = array.GetValue( i ); //// array.SetValue( array.GetValue( j ), i ); //// array.SetValue( temp, j ); //// i++; //// j--; //// } //// } } //// [ResourceExposure( ResourceScope.None )] //// [ReliabilityContract( Consistency.MayCorruptInstance, Cer.MayFail )] //// [MethodImpl( MethodImplOptions.InternalCall )] //// private static extern bool TrySZReverse( Array array, int index, int count ); // Sorts the elements of an array. The sort compares the elements to each // other using the IComparable interface, which must be implemented // by all elements of the array. // //// [ReliabilityContract( Consistency.MayCorruptInstance, Cer.MayFail )] public static void Sort( Array array ) { if(array == null) { #if EXCEPTION_STRINGS throw new ArgumentNullException( "array" ); #else throw new ArgumentNullException(); #endif } Sort( array, null, array.GetLowerBound( 0 ), array.Length, null ); } // Sorts the elements of two arrays based on the keys in the first array. // Elements in the keys array specify the sort keys for // corresponding elements in the items array. The sort compares the // keys to each other using the IComparable interface, which must be // implemented by all elements of the keys array. // //// [ReliabilityContract( Consistency.MayCorruptInstance, Cer.MayFail )] public static void Sort( Array keys, Array items ) { if(keys == null) { #if EXCEPTION_STRINGS throw new ArgumentNullException( "keys" ); #else throw new ArgumentNullException(); #endif } Sort( keys, items, keys.GetLowerBound( 0 ), keys.Length, null ); } // Sorts the elements in a section of an array. The sort compares the // elements to each other using the IComparable interface, which // must be implemented by all elements in the given section of the array. // //// [ReliabilityContract( Consistency.MayCorruptInstance, Cer.MayFail )] public static void Sort( Array array, int index, int length ) { Sort( array, null, index, length, null ); } // Sorts the elements in a section of two arrays based on the keys in the // first array. Elements in the keys array specify the sort keys for // corresponding elements in the items array. The sort compares the // keys to each other using the IComparable interface, which must be // implemented by all elements of the keys array. // //// [ReliabilityContract( Consistency.MayCorruptInstance, Cer.MayFail )] public static void Sort( Array keys, Array items, int index, int length ) { Sort( keys, items, index, length, null ); } // Sorts the elements of an array. The sort compares the elements to each // other using the given IComparer interface. If comparer is // null, the elements are compared to each other using the // IComparable interface, which in that case must be implemented by // all elements of the array. // //// [ReliabilityContract( Consistency.MayCorruptInstance, Cer.MayFail )] public static void Sort( Array array, IComparer comparer ) { if(array == null) { #if EXCEPTION_STRINGS throw new ArgumentNullException( "array" ); #else throw new ArgumentNullException(); #endif } Sort( array, null, array.GetLowerBound( 0 ), array.Length, comparer ); } // Sorts the elements of two arrays based on the keys in the first array. // Elements in the keys array specify the sort keys for // corresponding elements in the items array. The sort compares the // keys to each other using the given IComparer interface. If // comparer is null, the elements are compared to each other using // the IComparable interface, which in that case must be implemented // by all elements of the keys array. // //// [ReliabilityContract( Consistency.MayCorruptInstance, Cer.MayFail )] public static void Sort( Array keys, Array items, IComparer comparer ) { if(keys == null) { #if EXCEPTION_STRINGS throw new ArgumentNullException( "keys" ); #else throw new ArgumentNullException(); #endif } Sort( keys, items, keys.GetLowerBound( 0 ), keys.Length, comparer ); } // Sorts the elements in a section of an array. The sort compares the // elements to each other using the given IComparer interface. If // comparer is null, the elements are compared to each other using // the IComparable interface, which in that case must be implemented // by all elements in the given section of the array. // //// [ReliabilityContract( Consistency.MayCorruptInstance, Cer.MayFail )] public static void Sort( Array array, int index, int length, IComparer comparer ) { Sort( array, null, index, length, comparer ); } // Sorts the elements in a section of two arrays based on the keys in the // first array. Elements in the keys array specify the sort keys for // corresponding elements in the items array. The sort compares the // keys to each other using the given IComparer interface. If // comparer is null, the elements are compared to each other using // the IComparable interface, which in that case must be implemented // by all elements of the given section of the keys array. // //// [ReliabilityContract( Consistency.MayCorruptInstance, Cer.MayFail )] public static void Sort( Array keys, Array items, int index, int length, IComparer comparer ) { throw new NotImplementedException(); //// if(keys == null) //// { //// throw new ArgumentNullException( "keys" ); //// } //// if(keys.Rank != 1 || (items != null && items.Rank != 1)) //// { //// throw new RankException( Environment.GetResourceString( "Rank_MultiDimNotSupported" ) ); //// } //// //// int lbK = keys .GetLowerBound( 0 ); //// int lbI = items.GetLowerBound( 0 ); //// if(items != null && lbK != lbI) //// { //// throw new ArgumentException( Environment.GetResourceString( "Arg_LowerBoundsMustMatch" ) ); //// } //// if(index < lbK || length < 0) //// { //// throw new ArgumentOutOfRangeException( (length < 0 ? "length" : "index"), Environment.GetResourceString( "ArgumentOutOfRange_NeedNonNegNum" ) ); //// } //// if(keys.Length - (index - lbK) < length || (items != null && (index - lbI) > items.Length - length)) //// { //// throw new ArgumentException( Environment.GetResourceString( "Argument_InvalidOffLen" ) ); //// } //// //// //// if(length > 1) //// { //// if(comparer == Comparer.Default || comparer == null) //// { //// bool r = TrySZSort( keys, items, index, index + length - 1 ); //// if(r) //// { //// return; //// } //// } //// //// Object[] objKeys = keys as Object[]; //// Object[] objItems = null; //// if(objKeys != null) //// { //// objItems = items as Object[]; //// } //// //// if(objKeys != null && (items == null || objItems != null)) //// { //// SorterObjectArray sorter = new SorterObjectArray( objKeys, objItems, comparer ); //// //// sorter.QuickSort( index, index + length - 1 ); //// } //// else //// { //// SorterGenericArray sorter = new SorterGenericArray( keys, items, comparer ); //// //// sorter.QuickSort( index, index + length - 1 ); //// } //// } } //// [ResourceExposure( ResourceScope.None )] //// [ReliabilityContract( Consistency.MayCorruptInstance, Cer.MayFail )] //// [MethodImpl( MethodImplOptions.InternalCall )] //// private static extern bool TrySZSort( Array keys, Array items, int left, int right ); //// //// [ReliabilityContract( Consistency.MayCorruptInstance, Cer.MayFail )] public static void Sort( T[] array ) { if(array == null) { #if EXCEPTION_STRINGS throw new ArgumentNullException( "array" ); #else throw new ArgumentNullException(); #endif } Sort( array, array.GetLowerBound( 0 ), array.Length, null ); } //// [ReliabilityContract( Consistency.MayCorruptInstance, Cer.MayFail )] public static void Sort( TKey[] keys, TValue[] items ) { if(keys == null) { #if EXCEPTION_STRINGS throw new ArgumentNullException( "keys" ); #else throw new ArgumentNullException(); #endif } Sort( keys, items, 0, keys.Length, null ); } //// [ReliabilityContract( Consistency.MayCorruptInstance, Cer.MayFail )] public static void Sort( T[] array, int index, int length ) { Sort( array, index, length, null ); } //// [ReliabilityContract( Consistency.MayCorruptInstance, Cer.MayFail )] public static void Sort( TKey[] keys, TValue[] items, int index, int length ) { Sort( keys, items, index, length, null ); } //// [ReliabilityContract( Consistency.MayCorruptInstance, Cer.MayFail )] public static void Sort( T[] array, System.Collections.Generic.IComparer comparer ) { if(array == null) { #if EXCEPTION_STRINGS throw new ArgumentNullException( "array" ); #else throw new ArgumentNullException(); #endif } Sort( array, 0, array.Length, comparer ); } //// [ReliabilityContract( Consistency.MayCorruptInstance, Cer.MayFail )] public static void Sort( TKey[] keys, TValue[] items, System.Collections.Generic.IComparer comparer ) { if(keys == null) { #if EXCEPTION_STRINGS throw new ArgumentNullException( "keys" ); #else throw new ArgumentNullException(); #endif } Sort( keys, items, 0, keys.Length, comparer ); } //// [ReliabilityContract( Consistency.MayCorruptInstance, Cer.MayFail )] public static void Sort( T[] array, int index, int length, System.Collections.Generic.IComparer comparer ) { if(array == null) { #if EXCEPTION_STRINGS throw new ArgumentNullException( "array" ); #else throw new ArgumentNullException(); #endif } if(index < 0 || length < 0) { #if EXCEPTION_STRINGS throw new ArgumentOutOfRangeException( (length < 0 ? "length" : "index"), Environment.GetResourceString( "ArgumentOutOfRange_NeedNonNegNum" ) ); #else throw new ArgumentOutOfRangeException(); #endif } if(array.Length - index < length) { #if EXCEPTION_STRINGS throw new ArgumentException( Environment.GetResourceString( "Argument_InvalidOffLen" ) ); #else throw new ArgumentException(); #endif } if(length > 1) { //// // //// // TrySZSort is still faster than the generic implementation. //// // The reason is Int32.CompareTo is still expensive than just using "<" or ">". //// // //// if(comparer == null || comparer == Comparer.Default) //// { //// if(TrySZSort( array, null, index, index + length - 1 )) //// { //// return; //// } //// } ArraySortHelper.Default.Sort( array, index, length, comparer ); } } //// [ReliabilityContract( Consistency.MayCorruptInstance, Cer.MayFail )] public static void Sort( TKey[] keys, TValue[] items, int index, int length, System.Collections.Generic.IComparer comparer ) { if(keys == null) { #if EXCEPTION_STRINGS throw new ArgumentNullException( "keys" ); #else throw new ArgumentNullException(); #endif } if(index < 0 || length < 0) { #if EXCEPTION_STRINGS throw new ArgumentOutOfRangeException( (length < 0 ? "length" : "index"), Environment.GetResourceString( "ArgumentOutOfRange_NeedNonNegNum" ) ); #else throw new ArgumentOutOfRangeException(); #endif } if(keys.Length - index < length || (items != null && index > items.Length - length)) { #if EXCEPTION_STRINGS throw new ArgumentException( Environment.GetResourceString( "Argument_InvalidOffLen" ) ); #else throw new ArgumentException(); #endif } if(length > 1) { //// if(comparer == null || comparer == Comparer.Default) //// { //// if(TrySZSort( keys, items, index, index + length - 1 )) //// { //// return; //// } //// } ArraySortHelper.Default.Sort( keys, items, index, length, comparer ); } } public static void Sort( T[] array, Comparison comparison ) { if(array == null) { #if EXCEPTION_STRINGS throw new ArgumentNullException( "array" ); #else throw new ArgumentNullException(); #endif } if(comparison == null) { #if EXCEPTION_STRINGS throw new ArgumentNullException( "comparison" ); #else throw new ArgumentNullException(); #endif } IComparer comparer = new FunctorComparer( comparison ); Array.Sort( array, comparer ); } public static bool TrueForAll( T[] array, Predicate match ) { if(array == null) { #if EXCEPTION_STRINGS throw new ArgumentNullException( "array" ); #else throw new ArgumentNullException(); #endif } if(match == null) { #if EXCEPTION_STRINGS throw new ArgumentNullException( "match" ); #else throw new ArgumentNullException(); #endif } for(int i = 0; i < array.Length; i++) { if(!match( array[i] )) { return false; } } return true; } internal sealed class FunctorComparer : IComparer { Comparison comparison; //// Comparer c = Comparer.Default; public FunctorComparer( Comparison comparison ) { this.comparison = comparison; } public int Compare( T x, T y ) { return comparison( x, y ); } } //// // Private value type used by the Sort methods. //// private struct SorterObjectArray //// { //// private Object[] keys; //// private Object[] items; //// private IComparer comparer; //// //// internal SorterObjectArray( Object[] keys, Object[] items, IComparer comparer ) //// { //// if(comparer == null) comparer = Comparer.Default; //// //// this.keys = keys; //// this.items = items; //// this.comparer = comparer; //// } //// //// internal void SwapIfGreaterWithItems( int a, int b ) //// { //// if(a != b) //// { //// try //// { //// if(comparer.Compare( keys[a], keys[b] ) > 0) //// { //// Object temp = keys[a]; //// keys[a] = keys[b]; //// keys[b] = temp; //// //// if(items != null) //// { //// Object item = items[a]; //// items[a] = items[b]; //// items[b] = item; //// } //// } //// } //// catch(IndexOutOfRangeException) //// { //// throw new ArgumentException( Environment.GetResourceString( "Arg_BogusIComparer", keys[b], keys[b].GetType().Name, comparer ) ); //// } //// catch(Exception e) //// { //// throw new InvalidOperationException( Environment.GetResourceString( "InvalidOperation_IComparerFailed" ), e ); //// } //// } //// } //// //// //// internal void QuickSort( int left, int right ) //// { //// // Can use the much faster jit helpers for array access. //// do //// { //// int i = left; //// int j = right; //// //// // pre-sort the low, middle (pivot), and high values in place. //// // this improves performance in the face of already sorted data, or //// // data that is made up of multiple sorted runs appended together. //// int middle = GetMedian( i, j ); //// //// SwapIfGreaterWithItems( i , middle ); // swap the low with the mid point //// SwapIfGreaterWithItems( i , j ); // swap the low with the high //// SwapIfGreaterWithItems( middle, j ); // swap the middle with the high //// //// Object x = keys[middle]; //// do //// { //// // Add a try block here to detect IComparers (or their //// // underlying IComparables, etc) that are bogus. //// try //// { //// while(comparer.Compare( keys[i], x ) < 0) i++; //// while(comparer.Compare( x , keys[j] ) < 0) j--; //// } //// catch(IndexOutOfRangeException) //// { //// throw new ArgumentException( Environment.GetResourceString( "Arg_BogusIComparer", x, x.GetType().Name, comparer ) ); //// } //// catch(Exception e) //// { //// throw new InvalidOperationException( Environment.GetResourceString( "InvalidOperation_IComparerFailed" ), e ); //// } //// //// BCLDebug.Assert( i >= left && j <= right, "(i>=left && j<=right) Sort failed - Is your IComparer bogus?" ); //// //// if(i > j) break; //// //// if(i < j) //// { //// Object key = keys[i]; //// keys[i] = keys[j]; //// keys[j] = key; //// //// if(items != null) //// { //// Object item = items[i]; //// items[i] = items[j]; //// items[j] = item; //// } //// } //// //// i++; //// j--; //// //// } while(i <= j); //// //// if(j - left <= right - i) //// { //// if(left < j) QuickSort( left, j ); //// left = i; //// } //// else //// { //// if(i < right) QuickSort( i, right ); //// right = j; //// } //// //// } while(left < right); //// } //// } //// //// // Private value used by the Sort methods for instances of Array. //// // This is slower than the one for Object[], since we can't use the JIT helpers //// // to access the elements. We must use GetValue & SetValue. //// private struct SorterGenericArray //// { //// private Array keys; //// private Array items; //// private IComparer comparer; //// //// internal SorterGenericArray( Array keys, Array items, IComparer comparer ) //// { //// if(comparer == null) comparer = Comparer.Default; //// //// this.keys = keys; //// this.items = items; //// this.comparer = comparer; //// } //// //// internal void SwapIfGreaterWithItems( int a, int b ) //// { //// if(a != b) //// { //// try //// { //// if(comparer.Compare( keys.GetValue( a ), keys.GetValue( b ) ) > 0) //// { //// Object key = keys.GetValue( a ); //// keys.SetValue( keys.GetValue( b ), a ); //// keys.SetValue( key , b ); //// //// if(items != null) //// { //// Object item = items.GetValue( a ); //// items.SetValue( items.GetValue( b ), a ); //// items.SetValue( item , b ); //// } //// } //// } //// catch(IndexOutOfRangeException) //// { //// throw new ArgumentException( Environment.GetResourceString( "Arg_BogusIComparer", keys.GetValue( b ), keys.GetValue( b ).GetType().Name, comparer ) ); //// } //// catch(Exception e) //// { //// throw new InvalidOperationException( Environment.GetResourceString( "InvalidOperation_IComparerFailed" ), e ); //// } //// } //// } //// //// internal void QuickSort( int left, int right ) //// { //// // Must use slow Array accessors (GetValue & SetValue) //// do //// { //// int i = left; //// int j = right; //// //// // pre-sort the low, middle (pivot), and high values in place. //// // this improves performance in the face of already sorted data, or //// // data that is made up of multiple sorted runs appended together. //// int middle = GetMedian( i, j ); //// //// SwapIfGreaterWithItems( i , middle ); // swap the low with the mid point //// SwapIfGreaterWithItems( i , j ); // swap the low with the high //// SwapIfGreaterWithItems( middle, j ); // swap the middle with the high //// //// Object x = keys.GetValue( middle ); //// do //// { //// // Add a try block here to detect IComparers (or their //// // underlying IComparables, etc) that are bogus. //// try //// { //// while(comparer.Compare( keys.GetValue( i ), x ) < 0) i++; //// while(comparer.Compare( x , keys.GetValue( j ) ) < 0) j--; //// } //// catch(IndexOutOfRangeException) //// { //// throw new ArgumentException( Environment.GetResourceString( "Arg_BogusIComparer", x, x.GetType().Name, comparer ) ); //// } //// catch(Exception e) //// { //// throw new InvalidOperationException( Environment.GetResourceString( "InvalidOperation_IComparerFailed" ), e ); //// } //// //// BCLDebug.Assert( i >= left && j <= right, "(i>=left && j<=right) Sort failed - Is your IComparer bogus?" ); //// //// if(i > j) break; //// //// if(i < j) //// { //// Object key = keys.GetValue( i ); //// keys.SetValue( keys.GetValue( j ), i ); //// keys.SetValue( key , j ); //// //// if(items != null) //// { //// Object item = items.GetValue( i ); //// items.SetValue( items.GetValue( j ), i ); //// items.SetValue( item , j ); //// } //// } //// //// if(i != Int32.MaxValue) ++i; //// if(j != Int32.MinValue) --j; //// //// } while(i <= j); //// //// if(j - left <= right - i) //// { //// if(left < j) QuickSort( left, j ); //// left = i; //// } //// else //// { //// if(i < right) QuickSort( i, right ); //// right = j; //// } //// //// } while(left < right); //// } //// } [Serializable] private sealed class SZArrayEnumerator : IEnumerator, ICloneable { private Array m_array; private int m_index; private int m_endIndex; // cache array length, since it's a little slow. internal SZArrayEnumerator( Array array ) { BCLDebug.Assert( array.Rank == 1 && array.GetLowerBound( 0 ) == 0, "SZArrayEnumerator only works on single dimension arrays w/ a lower bound of zero." ); m_array = array; m_index = -1; m_endIndex = array.Length; } public Object Clone() { return MemberwiseClone(); } public bool MoveNext() { if(m_index < m_endIndex) { m_index++; return (m_index < m_endIndex); } return false; } public Object Current { get { if(m_index < 0) { #if EXCEPTION_STRINGS throw new InvalidOperationException( Environment.GetResourceString( "InvalidOperation_EnumNotStarted" ) ); #else throw new InvalidOperationException(); #endif } if(m_index >= m_endIndex) { #if EXCEPTION_STRINGS throw new InvalidOperationException( Environment.GetResourceString( "InvalidOperation_EnumEnded" ) ); #else throw new InvalidOperationException(); #endif } return m_array.GetValue( m_index ); } } public void Reset() { m_index = -1; } } //// [Serializable] //// private sealed class ArrayEnumerator : IEnumerator, ICloneable //// { //// private Array m_array; //// private int m_index; //// private int m_endIndex; //// private int m_startIndex; // Save for Reset. //// private int[] m_indices; // The current position in a multidim array //// private bool m_complete; //// //// internal ArrayEnumerator( Array array, int index, int count ) //// { //// m_array = array; //// m_index = index - 1; //// m_startIndex = index; //// m_endIndex = index + count; //// m_indices = new int[array.Rank]; //// //// int checkForZero = 1; // Check for dimensions of size 0. //// //// for(int i = 0; i < array.Rank; i++) //// { //// m_indices[i] = array.GetLowerBound( i ); //// checkForZero *= array.GetLength( i ); //// } //// //// // To make MoveNext simpler, decrement least significant index. //// m_indices[m_indices.Length - 1]--; //// m_complete = (checkForZero == 0); //// } //// //// private void IncArray() //// { //// // This method advances us to the next valid array index, //// // handling all the multiple dimension & bounds correctly. //// // Think of it like an odometer in your car - we start with //// // the last digit, increment it, and check for rollover. If //// // it rolls over, we set all digits to the right and including //// // the current to the appropriate lower bound. Do these overflow //// // checks for each dimension, and if the most significant digit //// // has rolled over it's upper bound, we're done. //// // //// int rank = m_array.Rank; //// //// m_indices[rank - 1]++; //// //// for(int dim = rank - 1; dim >= 0; dim--) //// { //// if(m_indices[dim] > m_array.GetUpperBound( dim )) //// { //// if(dim == 0) //// { //// m_complete = true; //// break; //// } //// //// for(int j = dim; j < rank; j++) //// { //// m_indices[j] = m_array.GetLowerBound( j ); //// } //// //// m_indices[dim - 1]++; //// } //// } //// } //// //// public Object Clone() //// { //// return MemberwiseClone(); //// } //// //// public bool MoveNext() //// { //// if(m_complete) //// { //// m_index = m_endIndex; //// return false; //// } //// //// m_index++; //// //// IncArray(); //// //// return !m_complete; //// } //// //// public Object Current //// { //// get //// { //// if(m_index < m_startIndex) //// { //// throw new InvalidOperationException( Environment.GetResourceString( ResId.InvalidOperation_EnumNotStarted ) ); //// } //// //// if(m_complete) //// { //// throw new InvalidOperationException( Environment.GetResourceString( ResId.InvalidOperation_EnumEnded ) ); //// } //// //// return m_array.GetValue( m_indices ); //// } //// } //// //// public void Reset() //// { //// m_index = m_startIndex - 1; //// //// int checkForZero = 1; //// for(int i = 0; i < m_array.Rank; i++) //// { //// m_indices[i] = m_array.GetLowerBound( i ); //// checkForZero *= m_array.GetLength( i ); //// } //// //// // To make MoveNext simpler, decrement least significant index. //// m_indices[m_indices.Length - 1]--; //// m_complete = (checkForZero == 0); //// } //// } // if this is an array of value classes and that value class has a default constructor // then this calls this default constructor on every elemen in the value class array. // otherwise this is a no-op. Generally this method is called automatically by the compiler //// [ResourceExposure( ResourceScope.None )] [MethodImpl( MethodImplOptions.InternalCall )] public extern void Initialize(); } //////---------------------------------------------------------------------------------------- ////// ! READ THIS BEFORE YOU WORK ON THIS CLASS. ////// ////// The methods on this class must be written VERY carefully to avoid introducing security holes. ////// That's because they are invoked with special "this"! The "this" object ////// for all of these methods are not SZArrayHelper objects. Rather, they are of type U[] ////// where U[] is castable to T[]. No actual SZArrayHelper object is ever instantiated. Thus, you will ////// see a lot of expressions that cast "this" "T[]". ////// ////// This class is needed to allow an SZ array of type T[] to expose IList, ////// IList, etc., etc. all the way up to IList. When the following call is ////// made: ////// ////// ((IList) (new U[n])).SomeIListMethod() ////// ////// the interface stub dispatcher treats this as a special case, loads up SZArrayHelper, ////// finds the corresponding generic method (matched simply by method name), instantiates ////// it for type and executes it. ////// ////// The "T" will reflect the interface used to invoke the method. The actual runtime "this" will be ////// array that is castable to "T[]" (i.e. for primitivs and valuetypes, it will be exactly ////// "T[]" - for orefs, it may be a "U[]" where U derives from T.) //////---------------------------------------------------------------------------------------- ////sealed class SZArrayHelper ////{ //// // It is never legal to instantiate this class. //// private SZArrayHelper() //// { //// BCLDebug.Assert( false, "Hey! How'd I get here?" ); //// } //// //// //// // ----------------------------------------------------------- //// // ------- Implement IEnumerable interface methods -------- //// // ----------------------------------------------------------- //// internal IEnumerator GetEnumerator() //// { //// //! Warning: "this" is an array, not an SZArrayHelper. See comments above //// //! or you may introduce a security hole! //// return new SZGenericArrayEnumerator( this as T[] ); //// } //// //// // ----------------------------------------------------------- //// // ------- Implement ICollection interface methods -------- //// // ----------------------------------------------------------- //// void CopyTo( T[] array, int index ) //// { //// //! Warning: "this" is an array, not an SZArrayHelper. See comments above //// //! or you may introduce a security hole! //// //// if(array != null && array.Rank != 1) //// { //// throw new ArgumentException( Environment.GetResourceString( "Rank_MultiDimNotSupported" ) ); //// } //// //// T[] _this = this as T[]; //// BCLDebug.Assert( _this != null, "this should be a T[]" ); //// //// Array.Copy( _this, 0, array, index, _this.Length ); //// } //// //// internal int get_Count() //// { //// //! Warning: "this" is an array, not an SZArrayHelper. See comments above //// //! or you may introduce a security hole! //// T[] _this = this as T[]; //// BCLDebug.Assert( _this != null, "this should be a T[]" ); //// //// return _this.Length; //// } //// //// // ----------------------------------------------------------- //// // ---------- Implement IList interface methods ----------- //// // ----------------------------------------------------------- //// internal T get_Item( int index ) //// { //// //! Warning: "this" is an array, not an SZArrayHelper. See comments above //// //! or you may introduce a security hole! //// T[] _this = this as T[]; //// BCLDebug.Assert( _this != null, "this should be a T[]" ); //// if((uint)index >= (uint)_this.Length) //// { //// ThrowHelper.ThrowArgumentOutOfRangeException(); //// } //// //// return _this[index]; //// } //// //// internal void set_Item( int index, T value ) //// { //// //! Warning: "this" is an array, not an SZArrayHelper. See comments above //// //! or you may introduce a security hole! //// T[] _this = this as T[]; //// BCLDebug.Assert( _this != null, "this should be a T[]" ); //// if((uint)index >= (uint)_this.Length) //// { //// ThrowHelper.ThrowArgumentOutOfRangeException(); //// } //// //// _this[index] = value; //// } //// //// void Add( T value ) //// { //// // Not meaningful for arrays. //// throw new NotSupportedException( Environment.GetResourceString( "NotSupported_FixedSizeCollection" ) ); //// } //// //// bool Contains( T value ) //// { //// //! Warning: "this" is an array, not an SZArrayHelper. See comments above //// //! or you may introduce a security hole! //// T[] _this = this as T[]; //// BCLDebug.Assert( _this != null, "this should be a T[]" ); //// //// return Array.IndexOf( _this, value ) != -1; //// } //// //// bool get_IsReadOnly() //// { //// return true; //// } //// //// void Clear() //// { //// //! Warning: "this" is an array, not an SZArrayHelper. See comments above //// //! or you may introduce a security hole! //// throw new NotSupportedException( Environment.GetResourceString( "NotSupported_ReadOnlyCollection" ) ); //// } //// //// int IndexOf( T value ) //// { //// //! Warning: "this" is an array, not an SZArrayHelper. See comments above //// //! or you may introduce a security hole! //// T[] _this = this as T[]; //// BCLDebug.Assert( _this != null, "this should be a T[]" ); //// //// return Array.IndexOf( _this, value ); //// } //// //// void Insert( int index, T value ) //// { //// // Not meaningful for arrays //// throw new NotSupportedException( Environment.GetResourceString( "NotSupported_FixedSizeCollection" ) ); //// } //// //// bool Remove( T value ) //// { //// // Not meaningful for arrays //// throw new NotSupportedException( Environment.GetResourceString( "NotSupported_FixedSizeCollection" ) ); //// } //// //// void RemoveAt( int index ) //// { //// // Not meaningful for arrays //// throw new NotSupportedException( Environment.GetResourceString( "NotSupported_FixedSizeCollection" ) ); //// } //// //// // This is a normal generic Enumerator for SZ arrays. It doesn't have any of the "this" voodoo //// // that SZArrayHelper does. //// // //// [Serializable] //// private sealed class SZGenericArrayEnumerator : IEnumerator //// { //// private T[] m_array; //// private int m_index; //// private int m_endIndex; // cache array length, since it's a little slow. //// //// internal SZGenericArrayEnumerator( T[] array ) //// { //// BCLDebug.Assert( array.Rank == 1 && array.GetLowerBound( 0 ) == 0, "SZArrayEnumerator only works on single dimension arrays w/ a lower bound of zero." ); //// //// m_array = array; //// m_index = -1; //// m_endIndex = array.Length; //// } //// //// public bool MoveNext() //// { //// if(m_index < m_endIndex) //// { //// m_index++; //// //// return (m_index < m_endIndex); //// } //// return false; //// } //// //// public T Current //// { //// get //// { //// if(m_index < 0) //// { //// throw new InvalidOperationException( Environment.GetResourceString( ResId.InvalidOperation_EnumNotStarted ) ); //// } //// //// if(m_index >= m_endIndex) //// { //// throw new InvalidOperationException( Environment.GetResourceString( ResId.InvalidOperation_EnumEnded ) ); //// } //// //// return m_array[m_index]; //// } //// } //// //// object IEnumerator.Current //// { //// get //// { //// return Current; //// } //// } //// //// void IEnumerator.Reset() //// { //// m_index = -1; //// } //// //// public void Dispose() //// { //// } //// } ////} } ================================================ FILE: Zelig/Zelig/RunTime/Framework/mscorlib/System/ArrayTypeMismatchException.cs ================================================ // ==++== // // Copyright (c) Microsoft Corporation. All rights reserved. // // ==--== /*============================================================================= ** ** Class: ArrayTypeMismatchException ** ** ** Purpose: The arrays are of different primitive types. ** ** =============================================================================*/ namespace System { using System; using System.Runtime.Serialization; // The ArrayMismatchException is thrown when an attempt to store // an object of the wrong type within an array occurs. // [Serializable] public class ArrayTypeMismatchException : SystemException { // Creates a new ArrayMismatchException with its message string set to // the empty string, its HRESULT set to COR_E_ARRAYTYPEMISMATCH, // and its ExceptionInfo reference set to null. public ArrayTypeMismatchException() : base( Environment.GetResourceString( "Arg_ArrayTypeMismatchException" ) ) { } // Creates a new ArrayMismatchException with its message string set to // message, its HRESULT set to COR_E_ARRAYTYPEMISMATCH, // and its ExceptionInfo reference set to null. // public ArrayTypeMismatchException( String message ) : base( message ) { } public ArrayTypeMismatchException( String message, Exception innerException ) : base( message, innerException ) { } //// protected ArrayTypeMismatchException( SerializationInfo info, StreamingContext context ) : base( info, context ) //// { //// } } } ================================================ FILE: Zelig/Zelig/RunTime/Framework/mscorlib/System/AssemblyHandle.cs ================================================ // ==++== // // Copyright (c) Microsoft Corporation. All rights reserved. // // ==--== #define DEBUG_PTRS namespace System { using System; using System.Reflection; ////using System.Reflection.Emit; using System.Runtime.ConstrainedExecution; using System.Diagnostics; using System.Runtime.Serialization; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; ////using System.Runtime.Versioning; ////using System.Text; using System.Globalization; ////using System.Security; ////using Microsoft.Win32.SafeHandles; ////using StackCrawlMark = System.Threading.StackCrawlMark; internal unsafe struct AssemblyHandle { #region Public Static Members //// internal static AssemblyHandle EmptyHandle //// { //// get //// { //// return new AssemblyHandle(); //// } //// } #endregion #region Private Data Members private IntPtr m_ptr; #endregion internal IntPtr Value { get { return m_ptr; } } #region Constructor internal AssemblyHandle( IntPtr pAssembly ) { m_ptr = pAssembly; } #endregion #region Internal Members public override int GetHashCode() { return m_ptr.GetHashCode(); } public override bool Equals( object obj ) { if(!(obj is AssemblyHandle)) { return false; } return Equals( (AssemblyHandle)obj ); } public unsafe bool Equals( AssemblyHandle handle ) { return handle.m_ptr == m_ptr; } // Slow path //// [MethodImpl( MethodImplOptions.InternalCall )] //// [SuppressUnmanagedCodeSecurity] //// [ResourceExposure( ResourceScope.None )] //// private extern static void GetAssembly( AssemblyHandle handle, ObjectHandleOnStack retAssembly ); //// //// [MethodImpl( MethodImplOptions.NoInlining )] // make sure that the slow path is not inlined //// private static Assembly GetAssembly( IntPtr handle ) //// { //// Assembly assembly = null; //// //// GetAssembly( new AssemblyHandle( handle ), JitHelpers.GetObjectHandleOnStack( ref assembly ) ); //// //// return assembly; //// } //// //// // Fast path //// [MethodImpl( MethodImplOptions.InternalCall )] //// [ResourceExposure( ResourceScope.None )] //// private extern static Assembly GetAssemblyIfExists( IntPtr assembly ); //// //// internal Assembly GetAssembly() //// { //// // Cache the handle to avoid races //// IntPtr handle = m_ptr; //// if(handle.IsNull()) //// { //// return null; //// } //// // Try the fast path first //// Assembly assembly = GetAssemblyIfExists( handle ); //// if(assembly != null) //// { //// return assembly; //// } //// // Fast path did not work. Use the slow path. //// return GetAssembly( handle ); //// } //// //// [ResourceExposure( ResourceScope.None )] //// [MethodImpl( MethodImplOptions.InternalCall )] //// private extern IntPtr _GetManifestModule(); //// //// internal ModuleHandle GetManifestModule() //// { //// return new ModuleHandle( _GetManifestModule() ); //// } //// //// //// [ResourceExposure( ResourceScope.None )] //// [MethodImpl( MethodImplOptions.InternalCall )] //// private extern bool _AptcaCheck( IntPtr sourceAssembly ); //// //// internal bool AptcaCheck( AssemblyHandle sourceAssembly ) //// { //// return _AptcaCheck( (IntPtr)sourceAssembly.Value ); //// } //// //// //// [ResourceExposure( ResourceScope.None )] //// [MethodImpl( MethodImplOptions.InternalCall )] //// internal extern int GetToken(); #endregion } } ================================================ FILE: Zelig/Zelig/RunTime/Framework/mscorlib/System/AsyncCallback.cs ================================================ // ==++== // // Copyright (c) Microsoft Corporation. All rights reserved. // // ==--== /*============================================================ ** ** Interface: AsyncCallbackDelegate ** ** Purpose: Type of callback for async operations ** ===========================================================*/ namespace System { [Serializable] public delegate void AsyncCallback( IAsyncResult ar ); } ================================================ FILE: Zelig/Zelig/RunTime/Framework/mscorlib/System/Attribute.cs ================================================ // ==++== // // Copyright (c) Microsoft Corporation. All rights reserved. // // ==--== namespace System { using System; using System.Reflection; using System.Collections; using System.Runtime.InteropServices; using System.Globalization; [Microsoft.Zelig.Internals.WellKnownType( "System_Attribute" )] [Serializable] [AttributeUsage( AttributeTargets.All, Inherited = true, AllowMultiple = false )] public abstract class Attribute /*: _Attribute*/ { #region Private Statics #region PropertyInfo //// private static Attribute[] InternalGetCustomAttributes( PropertyInfo element, Type type, bool inherit ) //// { //// // walk up the hierarchy chain //// Attribute[] attributes = (Attribute[])element.GetCustomAttributes( type, inherit ); //// //// if(!inherit) //// { //// return attributes; //// } //// //// // create the hashtable that keeps track of inherited types //// Hashtable types = new Hashtable( 11 ); //// //// // create an array list to collect all the requested attibutes //// ArrayList attributeList = new ArrayList(); //// CopyToArrayList( attributeList, attributes, types ); //// //// PropertyInfo baseProp = GetParentDefinition( element ); //// while(baseProp != null) //// { //// attributes = GetCustomAttributes( baseProp, type, false ); //// //// AddAttributesToList( attributeList, attributes, types ); //// //// baseProp = GetParentDefinition( baseProp ); //// } //// //// return (Attribute[])attributeList.ToArray( type ); //// } //// //// private static bool InternalIsDefined( PropertyInfo element, Type attributeType, bool inherit ) //// { //// // walk up the hierarchy chain //// if(element.IsDefined( attributeType, inherit )) //// { //// return true; //// } //// //// if(inherit) //// { //// AttributeUsageAttribute usage = InternalGetAttributeUsage( attributeType ); //// //// if(!usage.Inherited) //// { //// return false; //// } //// //// PropertyInfo baseProp = GetParentDefinition( element ); //// //// while(baseProp != null) //// { //// if(baseProp.IsDefined( attributeType, false )) //// { //// return true; //// } //// //// baseProp = GetParentDefinition( baseProp ); //// } //// } //// //// return false; //// } //// //// private static PropertyInfo GetParentDefinition( PropertyInfo property ) //// { //// // for the current property get the base class of the getter and the setter, they might be different //// MethodInfo propAccessor = property.GetGetMethod( true ); //// //// if(propAccessor == null) //// { //// propAccessor = property.GetSetMethod( true ); //// } //// //// if(propAccessor != null) //// { //// propAccessor = propAccessor.GetParentDefinition(); //// //// if(propAccessor != null) //// { //// return propAccessor.DeclaringType.GetProperty( property.Name, property.PropertyType ); //// } //// } //// //// return null; //// } #endregion #region EventInfo //// private static Attribute[] InternalGetCustomAttributes( EventInfo element, Type type, bool inherit ) //// { //// // walk up the hierarchy chain //// Attribute[] attributes = (Attribute[])element.GetCustomAttributes( type, inherit ); //// if(inherit) //// { //// // create the hashtable that keeps track of inherited types //// Hashtable types = new Hashtable( 11 ); //// //// // create an array list to collect all the requested attibutes //// ArrayList attributeList = new ArrayList(); //// CopyToArrayList( attributeList, attributes, types ); //// //// EventInfo baseEvent = GetParentDefinition( element ); //// while(baseEvent != null) //// { //// attributes = GetCustomAttributes( baseEvent, type, false ); //// //// AddAttributesToList( attributeList, attributes, types ); //// //// baseEvent = GetParentDefinition( baseEvent ); //// } //// return (Attribute[])attributeList.ToArray( type ); //// } //// else //// { //// return attributes; //// } //// } //// //// private static EventInfo GetParentDefinition( EventInfo ev ) //// { //// MethodInfo add = ev.GetAddMethod( true ); //// if(add != null) //// { //// add = add.GetParentDefinition(); //// if(add != null) //// { //// return add.DeclaringType.GetEvent( ev.Name ); //// } //// } //// //// return null; //// } //// //// private static bool InternalIsDefined( EventInfo element, Type attributeType, bool inherit ) //// { //// // walk up the hierarchy chain //// if(element.IsDefined( attributeType, inherit )) //// { //// return true; //// } //// //// if(inherit) //// { //// AttributeUsageAttribute usage = InternalGetAttributeUsage( attributeType ); //// //// if(!usage.Inherited) //// { //// return false; //// } //// //// EventInfo baseEvent = GetParentDefinition( element ); //// //// while(baseEvent != null) //// { //// if(baseEvent.IsDefined( attributeType, false )) //// { //// return true; //// } //// //// baseEvent = GetParentDefinition( baseEvent ); //// } //// } //// //// return false; //// } //// #endregion #region ParameterInfo //// private static Attribute[] InternalParamGetCustomAttributes( MethodInfo method, ParameterInfo param, Type type, bool inherit ) //// { //// // For ParameterInfo's we need to make sure that we chain through all the MethodInfo's in the inheritance chain that //// // have this ParameterInfo defined. .We pick up all the CustomAttributes for the starting ParameterInfo. We need to pick up only attributes //// // that are marked inherited from the remainder of the MethodInfo's in the inheritance chain. //// // For MethodInfo's on an interface we do not do an inheritance walk so the default ParameterInfo attributes are returned. //// // For MethodInfo's on a class we walk up the inheritance chain but do not look at the MethodInfo's on the interfaces that the //// // class inherits from and return the respective ParameterInfo attributes //// //// ArrayList disAllowMultiple = new ArrayList(); //// Object[] objAttr; //// //// if(type == null) //// { //// type = typeof( Attribute ); //// } //// //// objAttr = param.GetCustomAttributes( type, false ); //// //// for(int i = 0; i < objAttr.Length; i++) //// { //// Type objType = objAttr[i].GetType(); //// //// AttributeUsageAttribute attribUsage = InternalGetAttributeUsage( objType ); //// //// if(attribUsage.AllowMultiple == false) //// { //// disAllowMultiple.Add( objType ); //// } //// } //// //// // Get all the attributes that have Attribute as the base class //// Attribute[] ret = null; //// if(objAttr.Length == 0) //// { //// ret = (Attribute[])Array.CreateInstance( type, 0 ); //// } //// else //// { //// ret = (Attribute[])objAttr; //// } //// //// if(method.DeclaringType == null) // This is an interface so we are done. //// { //// return ret; //// } //// //// if(!inherit) //// { //// return ret; //// } //// //// int paramPosition = param.Position; //// method = method.GetParentDefinition(); //// //// while(method != null) //// { //// // Find the ParameterInfo on this method //// ParameterInfo[] parameters = method.GetParameters(); //// param = parameters[paramPosition]; // Point to the correct ParameterInfo of the method //// //// objAttr = param.GetCustomAttributes( type, false ); //// //// int count = 0; //// for(int i = 0; i < objAttr.Length; i++) //// { //// Type objType = objAttr[i].GetType(); //// AttributeUsageAttribute attribUsage = InternalGetAttributeUsage( objType ); //// //// if((attribUsage.Inherited) && (disAllowMultiple.Contains( objType ) == false)) //// { //// if(attribUsage.AllowMultiple == false) //// disAllowMultiple.Add( objType ); //// count++; //// } //// else //// { //// objAttr[i] = null; //// } //// } //// //// // Get all the attributes that have Attribute as the base class //// Attribute[] attributes = (Attribute[])Array.CreateInstance( type, count ); //// //// count = 0; //// for(int i = 0; i < objAttr.Length; i++) //// { //// if(objAttr[i] != null) //// { //// attributes[count] = (Attribute)objAttr[i]; //// count++; //// } //// } //// //// Attribute[] temp = ret; //// ret = (Attribute[])Array.CreateInstance( type, temp.Length + count ); //// Array.Copy( temp, ret, temp.Length ); //// //// int offset = temp.Length; //// //// for(int i = 0; i < attributes.Length; i++) //// { //// ret[offset + i] = attributes[i]; //// } //// //// method = method.GetParentDefinition(); //// //// } //// //// return ret; //// //// } //// //// private static bool InternalParamIsDefined( MethodInfo method, ParameterInfo param, Type type, bool inherit ) //// { //// // For ParameterInfo's we need to make sure that we chain through all the MethodInfo's in the inheritance chain. //// // We pick up all the CustomAttributes for the starting ParameterInfo. We need to pick up only attributes //// // that are marked inherited from the remainder of the ParameterInfo's in the inheritance chain. //// // For MethodInfo's on an interface we do not do an inheritance walk. For ParameterInfo's on a //// // Class we walk up the inheritance chain but do not look at the MethodInfo's on the interfaces that the class inherits from. //// //// if(param.IsDefined( type, false )) //// { //// return true; //// } //// //// if(method.DeclaringType == null || !inherit) // This is an interface so we are done. //// { //// return false; //// } //// //// int paramPosition = param.Position; //// method = method.GetParentDefinition(); //// //// while(method != null) //// { //// ParameterInfo[] parameters = method.GetParameters(); //// param = parameters[paramPosition]; //// //// Object[] objAttr = param.GetCustomAttributes( type, false ); //// //// for(int i = 0; i < objAttr.Length; i++) //// { //// Type objType = objAttr[i].GetType(); //// AttributeUsageAttribute attribUsage = InternalGetAttributeUsage( objType ); //// //// if((objAttr[i] is Attribute) && (attribUsage.Inherited)) //// { //// return true; //// } //// } //// //// method = method.GetParentDefinition(); //// } //// //// return false; //// } //// #endregion #region Utility //// private static void CopyToArrayList( ArrayList attributeList, Attribute[] attributes, Hashtable types ) //// { //// for(int i = 0; i < attributes.Length; i++) //// { //// attributeList.Add( attributes[i] ); //// //// Type attrType = attributes[i].GetType(); //// //// if(!types.Contains( attrType )) //// { //// types[attrType] = InternalGetAttributeUsage( attrType ); //// } //// } //// } //// //// private static void AddAttributesToList( ArrayList attributeList, Attribute[] attributes, Hashtable types ) //// { //// for(int i = 0; i < attributes.Length; i++) //// { //// Type attrType = attributes[i].GetType(); //// AttributeUsageAttribute usage = (AttributeUsageAttribute)types[attrType]; //// //// if(usage == null) //// { //// // the type has never been seen before if it's inheritable add it to the list //// usage = InternalGetAttributeUsage( attrType ); //// types[attrType] = usage; //// //// if(usage.Inherited) //// { //// attributeList.Add( attributes[i] ); //// } //// } //// else if(usage.Inherited && usage.AllowMultiple) //// { //// // we saw this type already add it only if it is inheritable and it does allow multiple //// attributeList.Add( attributes[i] ); //// } //// } //// } //// //// private static AttributeUsageAttribute InternalGetAttributeUsage( Type type ) //// { //// // Check if the custom attributes is Inheritable //// Object[] obj = type.GetCustomAttributes( typeof( AttributeUsageAttribute ), false ); //// //// if(obj.Length == 1) //// { //// return (AttributeUsageAttribute)obj[0]; //// } //// //// if(obj.Length == 0) //// { //// return AttributeUsageAttribute.Default; //// } //// //// throw new FormatException( String.Format( CultureInfo.CurrentCulture, Environment.GetResourceString( "Format_AttributeUsage" ), type ) ); //// } //// //// private static void ValidateParameters( Object element, Type attributeType ) //// { //// if(element == null) //// { //// throw new ArgumentNullException( "element" ); //// } //// //// if(attributeType == null) //// { //// throw new ArgumentNullException( "attributeType" ); //// } //// //// if(!attributeType.IsSubclassOf( typeof( Attribute ) ) && attributeType != typeof( Attribute )) //// { //// throw new ArgumentException( Environment.GetResourceString( "Argument_MustHaveAttributeBaseClass" ) ); //// } //// } //// #endregion #endregion #region Public Statics #region MemberInfo //// public static Attribute[] GetCustomAttributes( MemberInfo element, Type type ) //// { //// return GetCustomAttributes( element, type, true ); //// } //// //// public static Attribute[] GetCustomAttributes( MemberInfo element, Type type, bool inherit ) //// { //// if(element == null) //// { //// throw new ArgumentNullException( "element" ); //// } //// //// if(type == null) //// { //// throw new ArgumentNullException( "type" ); //// } //// //// if(!type.IsSubclassOf( typeof( Attribute ) ) && type != typeof( Attribute )) //// { //// throw new ArgumentException( Environment.GetResourceString( "Argument_MustHaveAttributeBaseClass" ) ); //// } //// //// switch(element.MemberType) //// { //// case MemberTypes.Property: //// return InternalGetCustomAttributes( (PropertyInfo)element, type, inherit ); //// //// case MemberTypes.Event: //// return InternalGetCustomAttributes( (EventInfo)element, type, inherit ); //// //// default: //// return element.GetCustomAttributes( type, inherit ) as Attribute[]; //// } //// } //// //// public static Attribute[] GetCustomAttributes( MemberInfo element ) //// { //// return GetCustomAttributes( element, true ); //// } //// //// public static Attribute[] GetCustomAttributes( MemberInfo element, bool inherit ) //// { //// return GetCustomAttributes( element, typeof( Attribute ), inherit ); //// } //// //// //// public static bool IsDefined( MemberInfo element, Type attributeType ) //// { //// return IsDefined( element, attributeType, true ); //// } //// //// public static bool IsDefined( MemberInfo element, Type attributeType, bool inherit ) //// { //// ValidateParameters( element, attributeType ); //// //// switch(element.MemberType) //// { //// case MemberTypes.Property: //// return InternalIsDefined( (PropertyInfo)element, attributeType, inherit ); //// //// case MemberTypes.Event: //// return InternalIsDefined( (EventInfo)element, attributeType, inherit ); //// //// default: //// return element.IsDefined( attributeType, inherit ); //// } //// //// } //// //// public static Attribute GetCustomAttribute( MemberInfo element, Type attributeType ) //// { //// return GetCustomAttribute( element, attributeType, true ); //// } //// //// public static Attribute GetCustomAttribute( MemberInfo element, Type attributeType, bool inherit ) //// { //// Attribute[] attrib = GetCustomAttributes( element, attributeType, inherit ); //// //// if(attrib == null || attrib.Length == 0) //// { //// return null; //// } //// //// if(attrib.Length == 1) //// { //// return attrib[0]; //// } //// //// throw new AmbiguousMatchException( Environment.GetResourceString( "RFLCT.AmbigCust" ) ); //// } //// #endregion #region ParameterInfo //// public static Attribute[] GetCustomAttributes( ParameterInfo element ) //// { //// return GetCustomAttributes( element, true ); //// } //// //// public static Attribute[] GetCustomAttributes( ParameterInfo element, Type attributeType ) //// { //// return GetCustomAttributes( element, attributeType, true ); //// } //// //// public static Attribute[] GetCustomAttributes( ParameterInfo element, bool inherit ) //// { //// return GetCustomAttributes( element, typeof( Attribute ), inherit ); //// } //// //// public static Attribute[] GetCustomAttributes( ParameterInfo element, Type attributeType, bool inherit ) //// { //// if(element == null) //// { //// throw new ArgumentNullException( "element" ); //// } //// //// if(attributeType == null) //// { //// throw new ArgumentNullException( "attributeType" ); //// } //// //// if(attributeType != typeof( Attribute ) && !attributeType.IsSubclassOf( typeof( Attribute ) )) //// { //// throw new ArgumentException( Environment.GetResourceString( "Argument_MustHaveAttributeBaseClass" ) ); //// } //// //// MemberInfo member = element.Member; //// //// if(member.MemberType == MemberTypes.Method && inherit) //// { //// return InternalParamGetCustomAttributes( (MethodInfo)member, element, attributeType, inherit ) as Attribute[]; //// } //// //// return element.GetCustomAttributes( attributeType, inherit ) as Attribute[]; //// } //// //// //// public static bool IsDefined( ParameterInfo element, Type attributeType ) //// { //// return IsDefined( element, attributeType, true ); //// } //// //// public static bool IsDefined( ParameterInfo element, Type attributeType, bool inherit ) //// { //// // Returns true is a custom attribute subclass of attributeType class/interface with inheritance walk //// ValidateParameters( element, attributeType ); //// //// MemberInfo member = element.Member; //// //// switch(member.MemberType) //// { //// case MemberTypes.Method: // We need to climb up the member hierarchy //// return InternalParamIsDefined( (MethodInfo)member, element, attributeType, inherit ); //// //// case MemberTypes.Constructor: //// return element.IsDefined( attributeType, false ); //// //// case MemberTypes.Property: //// return element.IsDefined( attributeType, false ); //// //// default: //// BCLDebug.Assert( false, "Invalid type for ParameterInfo member in Attribute class" ); //// throw new ArgumentException( Environment.GetResourceString( "Argument_InvalidParamInfo" ) ); //// } //// } //// //// public static Attribute GetCustomAttribute( ParameterInfo element, Type attributeType ) //// { //// return GetCustomAttribute( element, attributeType, true ); //// } //// //// public static Attribute GetCustomAttribute( ParameterInfo element, Type attributeType, bool inherit ) //// { //// // Returns an Attribute of base class/inteface attributeType on the ParameterInfo or null if none exists. //// // throws an AmbiguousMatchException if there are more than one defined. //// Attribute[] attrib = GetCustomAttributes( element, attributeType, inherit ); //// //// if(attrib == null || attrib.Length == 0) //// { //// return null; //// } //// //// if(attrib.Length == 0) //// { //// return null; //// } //// //// if(attrib.Length == 1) //// { //// return attrib[0]; //// } //// //// throw new AmbiguousMatchException( Environment.GetResourceString( "RFLCT.AmbigCust" ) ); //// } //// #endregion #region Module //// public static Attribute[] GetCustomAttributes( Module element, Type attributeType ) //// { //// return GetCustomAttributes( element, attributeType, true ); //// } //// //// public static Attribute[] GetCustomAttributes( Module element ) //// { //// return GetCustomAttributes( element, true ); //// } //// //// public static Attribute[] GetCustomAttributes( Module element, bool inherit ) //// { //// return GetCustomAttributes( element, typeof( Attribute ), inherit ); //// } //// //// public static Attribute[] GetCustomAttributes( Module element, Type attributeType, bool inherit ) //// { //// ValidateParameters( element, attributeType ); //// //// return (Attribute[])element.GetCustomAttributes( attributeType, inherit ); //// } //// //// //// public static bool IsDefined( Module element, Type attributeType ) //// { //// return IsDefined( element, attributeType, false ); //// } //// //// public static bool IsDefined( Module element, Type attributeType, bool inherit ) //// { //// ValidateParameters( element, attributeType ); //// //// return element.IsDefined( attributeType, false ); //// } //// //// //// public static Attribute GetCustomAttribute( Module element, Type attributeType ) //// { //// return GetCustomAttribute( element, attributeType, true ); //// } //// //// public static Attribute GetCustomAttribute( Module element, Type attributeType, bool inherit ) //// { //// // Returns an Attribute of base class/inteface attributeType on the Module or null if none exists. //// // throws an AmbiguousMatchException if there are more than one defined. //// Attribute[] attrib = GetCustomAttributes( element, attributeType, inherit ); //// //// if(attrib == null || attrib.Length == 0) //// { //// return null; //// } //// //// if(attrib.Length == 1) //// { //// return attrib[0]; //// } //// //// throw new AmbiguousMatchException( Environment.GetResourceString( "RFLCT.AmbigCust" ) ); //// } //// #endregion #region Assembly //// public static Attribute[] GetCustomAttributes( Assembly element ) //// { //// return GetCustomAttributes( element, true ); //// } //// //// public static Attribute[] GetCustomAttributes( Assembly element, Type attributeType ) //// { //// return GetCustomAttributes( element, attributeType, true ); //// } //// //// public static Attribute[] GetCustomAttributes( Assembly element, bool inherit ) //// { //// return GetCustomAttributes( element, typeof( Attribute ), inherit ); //// } //// //// public static Attribute[] GetCustomAttributes( Assembly element, Type attributeType, bool inherit ) //// { //// ValidateParameters( element, attributeType ); //// //// return (Attribute[])element.GetCustomAttributes( attributeType, inherit ); //// } //// //// //// public static bool IsDefined( Assembly element, Type attributeType ) //// { //// return IsDefined( element, attributeType, true ); //// } //// //// public static bool IsDefined( Assembly element, Type attributeType, bool inherit ) //// { //// ValidateParameters( element, attributeType ); //// //// return element.IsDefined( attributeType, false ); //// } //// //// //// public static Attribute GetCustomAttribute( Assembly element, Type attributeType ) //// { //// return GetCustomAttribute( element, attributeType, true ); //// } //// //// public static Attribute GetCustomAttribute( Assembly element, Type attributeType, bool inherit ) //// { //// // Returns an Attribute of base class/inteface attributeType on the Assembly or null if none exists. //// // throws an AmbiguousMatchException if there are more than one defined. //// Attribute[] attrib = GetCustomAttributes( element, attributeType, inherit ); //// //// if(attrib == null || attrib.Length == 0) //// { //// return null; //// } //// //// if(attrib.Length == 1) //// { //// return attrib[0]; //// } //// //// throw new AmbiguousMatchException( Environment.GetResourceString( "RFLCT.AmbigCust" ) ); //// } #endregion #endregion #region Constructor protected Attribute() { } #endregion #region Object Overrides //// public override bool Equals( Object obj ) //// { //// if(obj == null) //// { //// return false; //// } //// //// RuntimeType thisType = (RuntimeType)this.GetType(); //// RuntimeType thatType = (RuntimeType)obj.GetType(); //// //// if(thatType != thisType) //// { //// return false; //// } //// //// Object thisObj = this; //// Object thisResult; //// Object thatResult; //// //// FieldInfo[] thisFields = thisType.GetFields( BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic ); //// //// for(int i = 0; i < thisFields.Length; i++) //// { //// thisResult = ((RuntimeFieldInfo)thisFields[i]).GetValue( thisObj ); //// thatResult = ((RuntimeFieldInfo)thisFields[i]).GetValue( obj ); //// //// if(thisResult == null) //// { //// if(thatResult != null) //// { //// return false; //// } //// } //// else if(!thisResult.Equals( thatResult )) //// { //// return false; //// } //// } //// //// return true; //// } //// //// public override int GetHashCode() //// { //// Type type = GetType(); //// //// FieldInfo[] fields = type.GetFields( BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic ); //// Object vThis = null; //// //// for(int i = 0; i < fields.Length; i++) //// { //// FieldInfo field = fields[i]; //// //// vThis = field.GetValue( this ); //// //// if(vThis != null) //// { //// break; //// } //// } //// //// if(vThis != null) //// { //// return vThis.GetHashCode(); //// } //// //// return type.GetHashCode(); //// } #endregion #region Public Virtual Members //// public virtual Object TypeId //// { //// get //// { //// return GetType(); //// } //// } //// //// public virtual bool Match( Object obj ) //// { //// return Equals( obj ); //// } #endregion #region Public Members //// public virtual bool IsDefaultAttribute() //// { //// return false; //// } #endregion } } ================================================ FILE: Zelig/Zelig/RunTime/Framework/mscorlib/System/AttributeTargets.cs ================================================ // ==++== // // Copyright (c) Microsoft Corporation. All rights reserved. // // ==--== //////////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////////// namespace System { using System; // Enum used to indicate all the elements of the // VOS it is valid to attach this element to. [Flags] [Serializable] public enum AttributeTargets { Assembly = 0x0001, Module = 0x0002, Class = 0x0004, Struct = 0x0008, Enum = 0x0010, Constructor = 0x0020, Method = 0x0040, Property = 0x0080, Field = 0x0100, Event = 0x0200, Interface = 0x0400, Parameter = 0x0800, Delegate = 0x1000, ReturnValue = 0x2000, GenericParameter = 0x4000, All = Assembly | Module | Class | Struct | Enum | Constructor | Method | Property | Field | Event | Interface | Parameter | Delegate | ReturnValue | GenericParameter, } } ================================================ FILE: Zelig/Zelig/RunTime/Framework/mscorlib/System/AttributeUsageAttribute.cs ================================================ // ==++== // // Copyright (c) Microsoft Corporation. All rights reserved. // // ==--== /*============================================================ ** ** Class: AttributeUsageAttribute ** ** ** Purpose: The class denotes how to specify the usage of an attribute ** ** ===========================================================*/ namespace System { using System.Reflection; /* By default, attributes are inherited and multiple attributes are not allowed */ [AttributeUsage( AttributeTargets.Class, Inherited = true )] [Serializable] public sealed class AttributeUsageAttribute : Attribute { internal AttributeTargets m_attributeTarget = AttributeTargets.All; // Defaults to all internal bool m_allowMultiple = false; // Defaults to false internal bool m_inherited = true; // Defaults to true //// internal static AttributeUsageAttribute Default = new AttributeUsageAttribute( AttributeTargets.All ); //Constructors public AttributeUsageAttribute( AttributeTargets validOn ) { m_attributeTarget = validOn; } internal AttributeUsageAttribute( AttributeTargets validOn, bool allowMultiple, bool inherited ) { m_attributeTarget = validOn; m_allowMultiple = allowMultiple; m_inherited = inherited; } //Properties public AttributeTargets ValidOn { get { return m_attributeTarget; } } public bool AllowMultiple { get { return m_allowMultiple; } set { m_allowMultiple = value; } } public bool Inherited { get { return m_inherited; } set { m_inherited = value; } } } } ================================================ FILE: Zelig/Zelig/RunTime/Framework/mscorlib/System/BCLDebug.cs ================================================ // ==++== // // Copyright (c) Microsoft Corporation. All rights reserved. // // ==--== /*============================================================ ** ** Class: BCLDebug ** ** ** Purpose: Debugging Macros for use in the Base Class Libraries ** ** ============================================================*/ namespace System { ////using System.IO; ////using System.Text; ////using System.Runtime.Remoting; using System.Diagnostics; ////using Microsoft.Win32; using System.Runtime.CompilerServices; ////using System.Runtime.Versioning; ////using System.Security.Permissions; ////using System.Security; [Serializable] internal enum LogLevel { Trace = 0, Status = 20, Warning = 40, Error = 50, Panic = 100, } ////internal struct SwitchStructure ////{ //// internal String name; //// internal int value; //// //// internal SwitchStructure( String n, int v ) //// { //// name = n; //// value = v; //// } ////} // Only statics, does not need to be marked with the serializable attribute internal static class BCLDebug { //// internal static bool m_registryChecked = false; //// internal static bool m_loggingNotEnabled = false; //// internal static bool m_perfWarnings; //// internal static bool m_correctnessWarnings; //// internal static bool m_safeHandleStackTraces; #if _DEBUG //// internal static bool m_domainUnloadAdded; #endif //// internal static PermissionSet m_MakeConsoleErrorLoggingWork; //// //// static readonly SwitchStructure[] switches = //// { //// new SwitchStructure( "NLS" , 0x00000001 ), //// new SwitchStructure( "SER" , 0x00000002 ), //// new SwitchStructure( "DYNIL" , 0x00000004 ), //// new SwitchStructure( "REMOTE" , 0x00000008 ), //// new SwitchStructure( "BINARY" , 0x00000010 ), //Binary Formatter //// new SwitchStructure( "SOAP" , 0x00000020 ), // Soap Formatter //// new SwitchStructure( "REMOTINGCHANNELS", 0x00000040 ), //// new SwitchStructure( "CACHE" , 0x00000080 ), //// new SwitchStructure( "RESMGRFILEFORMAT", 0x00000100 ), // .resources files //// new SwitchStructure( "PERF" , 0x00000200 ), //// new SwitchStructure( "CORRECTNESS" , 0x00000400 ), //// new SwitchStructure( "MEMORYFAILPOINT" , 0x00000800 ), //// }; //// //// static readonly LogLevel[] levelConversions = //// { //// LogLevel.Panic , //// LogLevel.Error , //// LogLevel.Error , //// LogLevel.Warning, //// LogLevel.Warning, //// LogLevel.Status , //// LogLevel.Status , //// LogLevel.Trace , //// LogLevel.Trace , //// LogLevel.Trace , //// LogLevel.Trace , //// }; #if _DEBUG internal static void WaitForFinalizers( Object sender, EventArgs e ) { if(!m_registryChecked) { CheckRegistry(); } if(m_correctnessWarnings) { GC.GetTotalMemory( true ); GC.WaitForPendingFinalizers(); } } #endif [Conditional( "_DEBUG" )] //// [ResourceExposure( ResourceScope.None )] static public void Assert( bool condition, String message ) { #if _DEBUG //// // Speed up debug builds marginally by avoiding the garbage from //// // concatinating "BCL Assert: " and the message. //// if(!condition) //// { //// System.Diagnostics.Assert.Check( condition, "BCL Assert", message ); //// } #endif } [Conditional( "_LOGGING" )] //// [ResourceExposure( ResourceScope.None )] static public void Log( String message ) { //// if(AppDomain.CurrentDomain.IsUnloadingForcedFinalize()) //// { //// return; //// } //// //// if(!m_registryChecked) //// { //// CheckRegistry(); //// } //// //// System.Diagnostics.Log.Trace( message ); //// System.Diagnostics.Log.Trace( Environment.NewLine ); } [Conditional( "_LOGGING" )] //// [ResourceExposure( ResourceScope.None )] static public void Log( String switchName, String message ) { //// if(AppDomain.CurrentDomain.IsUnloadingForcedFinalize()) //// { //// return; //// } //// //// if(!m_registryChecked) //// { //// CheckRegistry(); //// } //// try //// { //// LogSwitch ls = LogSwitch.GetSwitch( switchName ); //// if(ls != null) //// { //// System.Diagnostics.Log.Trace( ls, message ); //// System.Diagnostics.Log.Trace( ls, Environment.NewLine ); //// } //// } //// catch //// { //// System.Diagnostics.Log.Trace( "Exception thrown in logging." + Environment.NewLine ); //// System.Diagnostics.Log.Trace( "Switch was: " + ((switchName == null) ? "" : switchName) + Environment.NewLine ); //// System.Diagnostics.Log.Trace( "Message was: " + ((message == null) ? "" : message) + Environment.NewLine ); //// } } //// // //// // This code gets called during security startup, so we can't go through Marshal to get the values. This is //// // just a small helper in native code instead of that. //// // //// [ResourceExposure( ResourceScope.None )] //// [MethodImpl( MethodImplOptions.InternalCall )] //// private extern static int GetRegistryLoggingValues( out bool loggingEnabled, out bool logToConsole, out int logLevel, out bool perfWarnings, out bool correctnessWarnings, out bool safeHandleStackTraces ); //// //// private static void CheckRegistry() //// { //// if(AppDomain.CurrentDomain.IsUnloadingForcedFinalize()) //// { //// return; //// } //// //// if(m_registryChecked) //// { //// return; //// } //// //// m_registryChecked = true; //// //// bool loggingEnabled; //// bool logToConsole; //// int logLevel; //// int facilityValue; //// //// facilityValue = GetRegistryLoggingValues( out loggingEnabled, out logToConsole, out logLevel, out m_perfWarnings, out m_correctnessWarnings, out m_safeHandleStackTraces ); //// //// // Note we can get into some recursive situations where we call //// // ourseves recursively through the .cctor. That's why we have the //// // check for levelConversions == null. //// if(!loggingEnabled) //// { //// m_loggingNotEnabled = true; //// } //// //// if(loggingEnabled && levelConversions != null) //// { //// try //// { //// //The values returned for the logging levels in the registry don't map nicely onto the //// //values which we support internally (which are an approximation of the ones that //// //the System.Diagnostics namespace uses) so we have a quick map. //// Assert( logLevel >= 0 && logLevel <= 10, "logLevel>=0 && logLevel<=10" ); //// //// logLevel = (int)levelConversions[logLevel]; //// //// if(facilityValue > 0) //// { //// for(int i = 0; i < switches.Length; i++) //// { //// if((switches[i].value & facilityValue) != 0) //// { //// LogSwitch L = new LogSwitch( switches[i].name, switches[i].name, System.Diagnostics.Log.GlobalSwitch ); //// L.MinimumLevel = (LoggingLevels)logLevel; //// } //// } //// //// System.Diagnostics.Log.GlobalSwitch.MinimumLevel = (LoggingLevels)logLevel; //// System.Diagnostics.Log.IsConsoleEnabled = logToConsole; //// } //// //// } //// catch //// { //// //Silently eat any exceptions. //// } //// } //// } //// //// internal static bool CheckEnabled( String switchName ) //// { //// if(AppDomain.CurrentDomain.IsUnloadingForcedFinalize()) //// { //// return false; //// } //// //// if(!m_registryChecked) //// { //// CheckRegistry(); //// } //// //// LogSwitch logSwitch = LogSwitch.GetSwitch( switchName ); //// if(logSwitch == null) //// { //// return false; //// } //// //// return ((int)logSwitch.MinimumLevel <= (int)LogLevel.Trace); //// } //// //// private static bool CheckEnabled( String switchName, LogLevel level, out LogSwitch logSwitch ) //// { //// if(AppDomain.CurrentDomain.IsUnloadingForcedFinalize()) //// { //// logSwitch = null; //// return false; //// } //// //// logSwitch = LogSwitch.GetSwitch( switchName ); //// if(logSwitch == null) //// { //// return false; //// } //// //// return ((int)logSwitch.MinimumLevel <= (int)level); //// } [Conditional( "_LOGGING" )] //// [ResourceExposure( ResourceScope.None )] public static void Log( String switchName, LogLevel level, params Object[] messages ) { //// if(AppDomain.CurrentDomain.IsUnloadingForcedFinalize()) //// { //// return; //// } //// //// //Add code to check if logging is enabled in the registry. //// LogSwitch logSwitch; //// //// if(!m_registryChecked) //// { //// CheckRegistry(); //// } //// //// if(!CheckEnabled( switchName, level, out logSwitch )) //// { //// return; //// } //// //// StringBuilder sb = new StringBuilder(); //// //// for(int i = 0; i < messages.Length; i++) //// { //// String s; //// //// try //// { //// if(messages[i] == null) //// { //// s = ""; //// } //// else //// { //// s = messages[i].ToString(); //// } //// } //// catch //// { //// s = ""; //// } //// //// sb.Append( s ); //// } //// //// System.Diagnostics.Log.LogMessage( (LoggingLevels)((int)level), logSwitch, sb.ToString() ); } // Note this overload doesn't take a format string. You probably don't // want this one. [Conditional( "_LOGGING" )] //// [ResourceExposure( ResourceScope.None )] public static void Trace( String switchName, params Object[] messages ) { //// if(m_loggingNotEnabled) //// { //// return; //// } //// //// LogSwitch logSwitch; //// if(!CheckEnabled( switchName, LogLevel.Trace, out logSwitch )) //// { //// return; //// } //// //// StringBuilder sb = new StringBuilder(); //// //// for(int i = 0; i < messages.Length; i++) //// { //// String s; //// //// try //// { //// if(messages[i] == null) //// { //// s = ""; //// } //// else //// { //// s = messages[i].ToString(); //// } //// } //// catch //// { //// s = ""; //// } //// //// sb.Append( s ); //// } //// //// sb.Append( Environment.NewLine ); //// System.Diagnostics.Log.LogMessage( LoggingLevels.TraceLevel0, logSwitch, sb.ToString() ); } [Conditional( "_LOGGING" )] //// [ResourceExposure( ResourceScope.None )] public static void Trace( String switchName, String format, params Object[] messages ) { //// if(m_loggingNotEnabled) //// { //// return; //// } //// //// LogSwitch logSwitch; //// if(!CheckEnabled( switchName, LogLevel.Trace, out logSwitch )) //// { //// return; //// } //// //// StringBuilder sb = new StringBuilder(); //// //// sb.AppendFormat( format, messages ); //// sb.Append( Environment.NewLine ); //// //// System.Diagnostics.Log.LogMessage( LoggingLevels.TraceLevel0, logSwitch, sb.ToString() ); } [Conditional( "_LOGGING" )] //// [ResourceExposure( ResourceScope.None )] public static void DumpStack( String switchName ) { //// LogSwitch logSwitch; //// //// if(!m_registryChecked) //// { //// CheckRegistry(); //// } //// //// if(!CheckEnabled( switchName, LogLevel.Trace, out logSwitch )) //// { //// return; //// } //// //// StackTrace trace = new StackTrace(); //// //// System.Diagnostics.Log.LogMessage( LoggingLevels.TraceLevel0, logSwitch, trace.ToString() ); } // For logging errors related to the console - we often can't expect to // write to stdout if it doesn't exist. [Conditional( "_DEBUG" )] //// [ResourceExposure( ResourceScope.None )] // Debug-only extra logging code //// [ResourceConsumption( ResourceScope.Machine, ResourceScope.Machine )] internal static void ConsoleError( String msg ) { //// if(AppDomain.CurrentDomain.IsUnloadingForcedFinalize()) //// { //// return; //// } //// //// if(m_MakeConsoleErrorLoggingWork == null) //// { //// PermissionSet perms = new PermissionSet(); //// //// perms.AddPermission( new EnvironmentPermission( PermissionState .Unrestricted ) ); //// perms.AddPermission( new FileIOPermission ( FileIOPermissionAccess.AllAccess, Path.GetFullPath( "." ) ) ); //// //// m_MakeConsoleErrorLoggingWork = perms; //// } //// //// m_MakeConsoleErrorLoggingWork.Assert(); //// //// using(TextWriter err = File.AppendText( "ConsoleErrors.log" )) //// { //// err.WriteLine( msg ); //// } } // For perf-related asserts. On a debug build, set the registry key // BCLPerfWarnings to non-zero. [Conditional( "_DEBUG" )] //// [ResourceExposure( ResourceScope.None )] internal static void Perf( bool expr, String msg ) { //// if(AppDomain.CurrentDomain.IsUnloadingForcedFinalize()) //// { //// return; //// } //// //// if(!m_registryChecked) //// { //// CheckRegistry(); //// } //// //// if(!m_perfWarnings) //// { //// return; //// } //// //// if(!expr) //// { //// Log( "PERF", "BCL Perf Warning: " + msg ); //// } //// //// System.Diagnostics.Assert.Check( expr, "BCL Perf Warning: Your perf may be less than perfect because...", msg ); } // For correctness-related asserts. On a debug build, set the registry key // BCLCorrectnessWarnings to non-zero. [Conditional( "_DEBUG" )] //// [ResourceExposure( ResourceScope.None )] internal static void Correctness( bool expr, String msg ) { #if _DEBUG //// if(AppDomain.CurrentDomain.IsUnloadingForcedFinalize()) //// { //// return; //// } //// //// if(!m_registryChecked) //// { //// CheckRegistry(); //// } //// //// if(!m_correctnessWarnings) //// { //// return; //// } //// //// if(!m_domainUnloadAdded) //// { //// m_domainUnloadAdded = true; //// //// AppDomain.CurrentDomain.DomainUnload += new EventHandler( WaitForFinalizers ); //// } //// //// if(!expr) //// { //// Log( "CORRECTNESS", "BCL Correctness Warning: " + msg ); //// } //// //// System.Diagnostics.Assert.Check( expr, "BCL Correctness Warning: Your program may not work because...", msg ); #endif } internal static bool CorrectnessEnabled() { #if WIN32 //// if(AppDomain.CurrentDomain.IsUnloadingForcedFinalize()) //// { //// return false; //// } //// //// if(!m_registryChecked) //// { //// CheckRegistry(); //// } //// //// return m_correctnessWarnings; return false; #else return false; #endif // WIN32 } // Whether SafeHandles include a stack trace showing where they // were allocated. Only useful in checked & debug builds. internal static bool SafeHandleStackTracesEnabled { get { #if _DEBUG //// if(!m_registryChecked) //// { //// CheckRegistry(); //// } //// //// return m_safeHandleStackTraces; return false; #else return false; #endif } } } //--// internal sealed class ASSERT : Exception { #region FRIEND //// private static bool AssertIsFriend( Type[] friends, StackTrace st ) //// { //// Type typeOfCallee = st.GetFrame( 1 ).GetMethod().DeclaringType; //// Type typeOfCaller = st.GetFrame( 2 ).GetMethod().DeclaringType; //// //// bool noFriends = true; //// foreach(Type friend in friends) //// { //// if(typeOfCaller != friend && typeOfCaller != typeOfCallee) //// { //// noFriends = false; //// } //// } //// //// if(noFriends) //// { //// Assert( false, Environment.GetResourceString( "RtType.InvalidCaller" ), st.ToString() ); //// } //// //// return true; //// } //// [Conditional( "_DEBUG" )] //// internal static void FRIEND( Type[] friends ) //// { //// StackTrace st = new StackTrace(); //// AssertIsFriend( friends, st ); //// } //// [Conditional( "_DEBUG" )] //// internal static void FRIEND( Type friend ) //// { //// StackTrace st = new StackTrace(); //// AssertIsFriend( new Type[] { friend }, st ); //// } //// [Conditional( "_DEBUG" )] //// internal static void FRIEND( string ns ) //// { //// StackTrace st = new StackTrace(); //// //// string nsOfCallee = st.GetFrame( 1 ).GetMethod().DeclaringType.Namespace; //// string nsOfCaller = st.GetFrame( 2 ).GetMethod().DeclaringType.Namespace; //// //// Assert( nsOfCaller.Equals( nsOfCaller ) || nsOfCaller.Equals( ns ), Environment.GetResourceString( "RtType.InvalidCaller" ), st.ToString() ); //// } #endregion #region PRECONDITION [Conditional( "_DEBUG" )] internal static void PRECONDITION( bool condition ) { Assert( condition ); } [Conditional( "_DEBUG" )] internal static void PRECONDITION( bool condition, string message ) { Assert( condition, message ); } [Conditional( "_DEBUG" )] internal static void PRECONDITION( bool condition, string message, string detailedMessage ) { Assert( condition, message, detailedMessage ); } #endregion #region POSTCONDITION [Conditional( "_DEBUG" )] internal static void POSTCONDITION( bool condition ) { Assert( condition ); } [Conditional( "_DEBUG" )] internal static void POSTCONDITION( bool condition, string message ) { Assert( condition, message ); } [Conditional( "_DEBUG" )] internal static void POSTCONDITION( bool condition, string message, string detailedMessage ) { Assert( condition, message, detailedMessage ); } #endregion #region CONSISTENCY_CHECK [Conditional( "_DEBUG" )] internal static void CONSISTENCY_CHECK( bool condition ) { Assert( condition ); } [Conditional( "_DEBUG" )] internal static void CONSISTENCY_CHECK( bool condition, string message ) { Assert( condition, message ); } [Conditional( "_DEBUG" )] internal static void CONSISTENCY_CHECK( bool condition, string message, string detailedMessage ) { Assert( condition, message, detailedMessage ); } #endregion #region SIMPLIFYING_ASSUMPTION [Conditional( "_DEBUG" )] internal static void SIMPLIFYING_ASSUMPTION( bool condition ) { Assert( condition ); } [Conditional( "_DEBUG" )] internal static void SIMPLIFYING_ASSUMPTION( bool condition, string message ) { Assert( condition, message ); } [Conditional( "_DEBUG" )] internal static void SIMPLIFYING_ASSUMPTION( bool condition, string message, string detailedMessage ) { Assert( condition, message, detailedMessage ); } #endregion #region UNREACHABLE [Conditional( "_DEBUG" )] internal static void UNREACHABLE() { Assert(); } [Conditional( "_DEBUG" )] internal static void UNREACHABLE( string message ) { Assert( message ); } [Conditional( "_DEBUG" )] internal static void UNREACHABLE( string message, string detailedMessage ) { Assert( message, detailedMessage ); } #endregion #region NOT_IMPLEMENTED [Conditional( "_DEBUG" )] internal static void NOT_IMPLEMENTED() { Assert(); } [Conditional( "_DEBUG" )] internal static void NOT_IMPLEMENTED( string message ) { Assert( message ); } [Conditional( "_DEBUG" )] internal static void NOT_IMPLEMENTED( string message, string detailedMessage ) { Assert( message, detailedMessage ); } #endregion #region Private Asserts - Throw before assert so debugger can inspect private static void Assert() { Assert( false, null, null ); } private static void Assert( string message ) { Assert( false, message, null ); } private static void Assert( bool condition ) { Assert( condition, null, null ); } private static void Assert( bool condition, string message ) { Assert( condition, message, null ); } private static void Assert( string message, string detailedMessage ) { Assert( false, message, detailedMessage ); } private static void Assert( bool condition, string message, string detailedMessage ) { if(!condition) { // Console.WriteLine("ASSERT MESSAGE: " + message + ", " + detailedMessage); // System.Diagnostics.Debug.Assert(condition, message, detailedMessage); // throw new ASSERT(); } } #endregion } internal static class LOGIC { internal static bool IMPLIES( bool p, bool q ) { return !p || q; } internal static bool BIJECTION( bool p, bool q ) { return IMPLIES( p, q ) && IMPLIES( q, p ); } } } ================================================ FILE: Zelig/Zelig/RunTime/Framework/mscorlib/System/BitConverter.cs ================================================ // ==++== // // Copyright (c) Microsoft Corporation. All rights reserved. // // ==--== /*============================================================ ** ** Class: BitConverter ** ** ** Purpose: Allows developers to view the base data types as ** an arbitrary array of bits. ** ** ===========================================================*/ namespace System { using System; using System.Runtime.CompilerServices; // The BitConverter class contains methods for // converting an array of bytes to one of the base data // types, as well as for converting a base data type to an // array of bytes. // // Only statics, does not need to be marked with the serializable attribute public static class BitConverter { // This field indicates the "endianess" of the architecture. // The value is set to true if the architecture is // little endian; false if it is big endian. #if BIGENDIAN public static readonly bool IsLittleEndian /* = false */; #else public static readonly bool IsLittleEndian = true; #endif // Converts a byte into an array of bytes with length one. public static byte[] GetBytes( bool value ) { byte[] r = new byte[1]; r[0] = (value ? (byte)Boolean.True : (byte)Boolean.False); return r; } // Converts a char into an array of bytes with length two. public static byte[] GetBytes( char value ) { return GetBytes( (short)value ); } // Converts a short into an array of bytes with length // two. public unsafe static byte[] GetBytes( short value ) { byte[] bytes = new byte[2]; fixed(byte* b = bytes) { *((short*)b) = value; } return bytes; } // Converts an int into an array of bytes with length // four. public unsafe static byte[] GetBytes( int value ) { byte[] bytes = new byte[4]; fixed(byte* b = bytes) { *((int*)b) = value; } return bytes; } // Converts a long into an array of bytes with length // eight. public unsafe static byte[] GetBytes( long value ) { byte[] bytes = new byte[8]; fixed(byte* b = bytes) { *((long*)b) = value; } return bytes; } // Converts an ushort into an array of bytes with // length two. [CLSCompliant( false )] public static byte[] GetBytes( ushort value ) { return GetBytes( (short)value ); } // Converts an uint into an array of bytes with // length four. [CLSCompliant( false )] public static byte[] GetBytes( uint value ) { return GetBytes( (int)value ); } // Converts an unsigned long into an array of bytes with // length eight. [CLSCompliant( false )] public static byte[] GetBytes( ulong value ) { return GetBytes( (long)value ); } // Converts a float into an array of bytes with length // four. public unsafe static byte[] GetBytes( float value ) { return GetBytes( *(int*)&value ); } // Converts a double into an array of bytes with length // eight. public unsafe static byte[] GetBytes( double value ) { return GetBytes( *(long*)&value ); } // Converts an array of bytes into a char. public static char ToChar( byte[] value, int startIndex ) { return (char)ToInt16( value, startIndex ); } // Converts an array of bytes into a short. public static unsafe short ToInt16( byte[] value, int startIndex ) { if(value == null) { ThrowHelper.ThrowArgumentNullException( ExceptionArgument.value ); } if((uint)startIndex >= value.Length) { ThrowHelper.ThrowArgumentOutOfRangeException( ExceptionArgument.startIndex, ExceptionResource.ArgumentOutOfRange_Index ); } if(startIndex > value.Length - 2) { ThrowHelper.ThrowArgumentException( ExceptionResource.Arg_ArrayPlusOffTooSmall ); } fixed(byte* pbyte = &value[startIndex]) { if(startIndex % 2 == 0) { // data is aligned return *((short*)pbyte); } else { if(IsLittleEndian) { return (short)((*pbyte) | (*(pbyte + 1) << 8)); } else { return (short)((*pbyte << 8) | (*(pbyte + 1))); } } } } // Converts an array of bytes into an int. public static unsafe int ToInt32( byte[] value, int startIndex ) { if(value == null) { ThrowHelper.ThrowArgumentNullException( ExceptionArgument.value ); } if((uint)startIndex >= value.Length) { ThrowHelper.ThrowArgumentOutOfRangeException( ExceptionArgument.startIndex, ExceptionResource.ArgumentOutOfRange_Index ); } if(startIndex > value.Length - 4) { ThrowHelper.ThrowArgumentException( ExceptionResource.Arg_ArrayPlusOffTooSmall ); } fixed(byte* pbyte = &value[startIndex]) { if(startIndex % 4 == 0) { // data is aligned return *((int*)pbyte); } else { if(IsLittleEndian) { return (*pbyte) | (*(pbyte + 1) << 8) | (*(pbyte + 2) << 16) | (*(pbyte + 3) << 24); } else { return (*pbyte << 24) | (*(pbyte + 1) << 16) | (*(pbyte + 2) << 8) | (*(pbyte + 3)); } } } } // Converts an array of bytes into a long. public static unsafe long ToInt64( byte[] value, int startIndex ) { if(value == null) { ThrowHelper.ThrowArgumentNullException( ExceptionArgument.value ); } if((uint)startIndex >= value.Length) { ThrowHelper.ThrowArgumentOutOfRangeException( ExceptionArgument.startIndex, ExceptionResource.ArgumentOutOfRange_Index ); } if(startIndex > value.Length - 8) { ThrowHelper.ThrowArgumentException( ExceptionResource.Arg_ArrayPlusOffTooSmall ); } fixed(byte* pbyte = &value[startIndex]) { if(startIndex % 8 == 0) { // data is aligned return *((long*)pbyte); } else { if(IsLittleEndian) { int i1 = (*(pbyte )) | (*(pbyte + 1) << 8) | (*(pbyte + 2) << 16) | (*(pbyte + 3) << 24); int i2 = (*(pbyte + 4)) | (*(pbyte + 5) << 8) | (*(pbyte + 6) << 16) | (*(pbyte + 7) << 24); return (uint)i1 | ((long)i2 << 32); } else { int i1 = (*(pbyte ) << 24) | (*(pbyte + 1) << 16) | (*(pbyte + 2) << 8) | (*(pbyte + 3)); int i2 = (*(pbyte + 4) << 24) | (*(pbyte + 5) << 16) | (*(pbyte + 6) << 8) | (*(pbyte + 7)); return (uint)i2 | ((long)i1 << 32); } } } } // Converts an array of bytes into an ushort. // [CLSCompliant( false )] public static ushort ToUInt16( byte[] value, int startIndex ) { return (ushort)ToInt16( value, startIndex ); } // Converts an array of bytes into an uint. // [CLSCompliant( false )] public static uint ToUInt32( byte[] value, int startIndex ) { return (uint)ToInt32( value, startIndex ); } // Converts an array of bytes into an unsigned long. // [CLSCompliant( false )] public static ulong ToUInt64( byte[] value, int startIndex ) { return (ulong)ToInt64( value, startIndex ); } // Converts an array of bytes into a float. unsafe public static float ToSingle( byte[] value, int startIndex ) { int val = ToInt32( value, startIndex ); return *(float*)&val; } // Converts an array of bytes into a double. unsafe public static double ToDouble( byte[] value, int startIndex ) { long val = ToInt64( value, startIndex ); return *(double*)&val; } private static char GetHexValue( int i ) { BCLDebug.Assert( i >= 0 && i < 16, "i is out of range." ); if(i < 10) { return (char)(i + '0'); } return (char)(i - 10 + 'A'); } // Converts an array of bytes into a String. public static String ToString( byte[] value, int startIndex, int length ) { if(value == null) { #if EXCEPTION_STRINGS throw new ArgumentNullException( "byteArray" ); #else throw new ArgumentNullException(); #endif } int arrayLen = value.Length; if(startIndex < 0 || (startIndex >= arrayLen && startIndex > 0)) { #if EXCEPTION_STRINGS throw new ArgumentOutOfRangeException( "startIndex", Environment.GetResourceString( "ArgumentOutOfRange_StartIndex" ) ); #else throw new ArgumentOutOfRangeException(); #endif } int realLength = length; if(realLength < 0) { #if EXCEPTION_STRINGS throw new ArgumentOutOfRangeException( "length", Environment.GetResourceString( "ArgumentOutOfRange_GenericPositive" ) ); #else throw new ArgumentOutOfRangeException(); #endif } if(startIndex > arrayLen - realLength) { #if EXCEPTION_STRINGS throw new ArgumentException( Environment.GetResourceString( "Arg_ArrayPlusOffTooSmall" ) ); #else throw new ArgumentException(); #endif } if(realLength == 0) { return string.Empty; } char[] chArray = new char[realLength * 3]; int i = 0; int index = startIndex; for(i = 0; i < realLength * 3; i += 3) { byte b = value[index++]; chArray[i] = GetHexValue( b / 16 ); chArray[i + 1] = GetHexValue( b % 16 ); chArray[i + 2] = '-'; } // We don't need the last '-' character return new String( chArray, 0, chArray.Length - 1 ); } // Converts an array of bytes into a String. public static String ToString( byte[] value ) { if(value == null) { #if EXCEPTION_STRINGS throw new ArgumentNullException( "value" ); #else throw new ArgumentNullException(); #endif } return ToString( value, 0, value.Length ); } // Converts an array of bytes into a String. public static String ToString( byte[] value, int startIndex ) { if(value == null) { #if EXCEPTION_STRINGS throw new ArgumentNullException( "value" ); #else throw new ArgumentNullException(); #endif } return ToString( value, startIndex, value.Length - startIndex ); } /*==================================ToBoolean=================================== **Action: Convert an array of bytes to a boolean value. We treat this array ** as if the first 4 bytes were an Int4 an operate on this value. **Returns: True if the Int4 value of the first 4 bytes is non-zero. **Arguments: value -- The byte array ** startIndex -- The position within the array. **Exceptions: See ToInt4. ==============================================================================*/ // Converts an array of bytes into a boolean. public static bool ToBoolean( byte[] value, int startIndex ) { if(value == null) { #if EXCEPTION_STRINGS throw new ArgumentNullException( "value" ); #else throw new ArgumentNullException(); #endif } if(startIndex < 0) { #if EXCEPTION_STRINGS throw new ArgumentOutOfRangeException( "startIndex", Environment.GetResourceString( "ArgumentOutOfRange_NeedNonNegNum" ) ); #else throw new ArgumentOutOfRangeException(); #endif } if(startIndex > value.Length - 1) { #if EXCEPTION_STRINGS throw new ArgumentOutOfRangeException( "startIndex", Environment.GetResourceString( "ArgumentOutOfRange_Index" ) ); #else throw new ArgumentOutOfRangeException(); #endif } return (value[startIndex] == 0) ? false : true; } public static unsafe long DoubleToInt64Bits( double value ) { return *((long*)&value); } public static unsafe double Int64BitsToDouble( long value ) { return *((double*)&value); } } } ================================================ FILE: Zelig/Zelig/RunTime/Framework/mscorlib/System/Boolean.cs ================================================ // ==++== // // Copyright (c) Microsoft Corporation. All rights reserved. // // ==--== /*============================================================ ** ** Class: Boolean ** ** ** Purpose: The boolean class serves as a wrapper for the primitive ** type boolean. ** ** ===========================================================*/ namespace System { using System; using System.Globalization; // The Boolean class provides the // object representation of the boolean primitive type. [Microsoft.Zelig.Internals.WellKnownType( "System_Boolean" )] [Serializable] public struct Boolean : IComparable, IConvertible, IComparable, IEquatable { internal const int True = 1; // The true value. internal const int False = 0; // The false value. internal const String TrueLiteral = "True"; // The internal string representation of true. internal const String FalseLiteral = "False"; // The internal string representation of false. private static char[] s_trimmableChars; // // Member Variables // private bool m_value; // // Public Constants // public static readonly String TrueString = TrueLiteral; // The public string representation of true. public static readonly String FalseString = FalseLiteral; // The public string representation of false. // // Overriden Instance Methods // /*=================================GetHashCode================================== **Args: None **Returns: 1 or 0 depending on whether this instance represents true or false. **Exceptions: None **Overriden From: Value ==============================================================================*/ // Provides a hash code for this instance. public override int GetHashCode() { return (m_value) ? True : False; } /*===================================ToString=================================== **Args: None **Returns: "True" or "False" depending on the state of the boolean. **Exceptions: None. ==============================================================================*/ // Converts the boolean value of this instance to a String. public override String ToString() { if(false == m_value) { return FalseLiteral; } return TrueLiteral; } public String ToString( IFormatProvider provider ) { if(false == m_value) { return FalseLiteral; } return TrueLiteral; } // Determines whether two Boolean objects are equal. public override bool Equals( Object obj ) { //If it's not a boolean, we're definitely not equal if(!(obj is Boolean)) { return false; } return Equals( (Boolean)obj ); } public bool Equals( Boolean obj ) { return m_value == obj; } // Compares this object to another object, returning an integer that // indicates the relationship. For booleans, false sorts before true. // null is considered to be less than any instance. // If object is not of type boolean, this method throws an ArgumentException. // // Returns a value less than zero if this object // public int CompareTo( Object obj ) { if(obj == null) { return 1; } if(!(obj is Boolean)) { #if EXCEPTION_STRINGS throw new ArgumentException( Environment.GetResourceString( "Arg_MustBeBoolean" ) ); #else throw new ArgumentException(); #endif } return CompareTo( (Boolean)obj ); } public int CompareTo( Boolean value ) { if(m_value == value) { return 0; } else if(m_value == false) { return -1; } return 1; } // // Static Methods // // Determines whether a String represents true or false. // public static Boolean Parse( String value ) { if(value == null) { #if EXCEPTION_STRINGS throw new ArgumentNullException( "value" ); #else throw new ArgumentNullException(); #endif } Boolean result = false; if(!TryParse( value, out result )) { #if EXCEPTION_STRINGS throw new FormatException( Environment.GetResourceString( "Format_BadBoolean" ) ); #else throw new FormatException(); #endif } else { return result; } } // Determines whether a String represents true or false. // public static Boolean TryParse( String value, out Boolean result ) { result = false; if(value == null) { return false; } // For perf reasons, let's first see if they're equal, then do the // trim to get rid of white space, and check again. if(TrueLiteral.Equals( value, StringComparison.OrdinalIgnoreCase )) { result = true; return true; } if(FalseLiteral.Equals( value, StringComparison.OrdinalIgnoreCase )) { result = false; return true; } // Special case: Trim whitespace as well as null characters. // Solution: Lazily initialize a new character array including 0x0000 if(s_trimmableChars == null) { char[] m_trimmableCharsTemp = new char[String.WhitespaceChars.Length + 1]; Array.Copy( String.WhitespaceChars, m_trimmableCharsTemp, String.WhitespaceChars.Length ); m_trimmableCharsTemp[m_trimmableCharsTemp.Length - 1] = (char)0x0000; s_trimmableChars = m_trimmableCharsTemp; } value = value.Trim( s_trimmableChars ); // Remove leading & trailing white space. if(TrueLiteral.Equals( value, StringComparison.OrdinalIgnoreCase )) { result = true; return true; } if(FalseLiteral.Equals( value, StringComparison.OrdinalIgnoreCase )) { result = false; return true; } return false; } #region IConvertible public TypeCode GetTypeCode() { return TypeCode.Boolean; } /// bool IConvertible.ToBoolean( IFormatProvider provider ) { return m_value; } /// char IConvertible.ToChar( IFormatProvider provider ) { #if EXCEPTION_STRINGS throw new InvalidCastException( String.Format( CultureInfo.CurrentCulture, Environment.GetResourceString( "InvalidCast_FromTo" ), "Boolean", "Char" ) ); #else throw new InvalidCastException(); #endif } /// sbyte IConvertible.ToSByte( IFormatProvider provider ) { return Convert.ToSByte( m_value ); } /// byte IConvertible.ToByte( IFormatProvider provider ) { return Convert.ToByte( m_value ); } /// short IConvertible.ToInt16( IFormatProvider provider ) { return Convert.ToInt16( m_value ); } /// ushort IConvertible.ToUInt16( IFormatProvider provider ) { return Convert.ToUInt16( m_value ); } /// int IConvertible.ToInt32( IFormatProvider provider ) { return Convert.ToInt32( m_value ); } /// uint IConvertible.ToUInt32( IFormatProvider provider ) { return Convert.ToUInt32( m_value ); } /// long IConvertible.ToInt64( IFormatProvider provider ) { return Convert.ToInt64( m_value ); } /// ulong IConvertible.ToUInt64( IFormatProvider provider ) { return Convert.ToUInt64( m_value ); } /// float IConvertible.ToSingle( IFormatProvider provider ) { return Convert.ToSingle( m_value ); } /// double IConvertible.ToDouble( IFormatProvider provider ) { return Convert.ToDouble( m_value ); } /// Decimal IConvertible.ToDecimal( IFormatProvider provider ) { return Convert.ToDecimal( m_value ); } /// DateTime IConvertible.ToDateTime( IFormatProvider provider ) { #if EXCEPTION_STRINGS throw new InvalidCastException( String.Format( CultureInfo.CurrentCulture, Environment.GetResourceString( "InvalidCast_FromTo" ), "Boolean", "DateTime" ) ); #else throw new InvalidCastException(); #endif } /// Object IConvertible.ToType( Type type, IFormatProvider provider ) { return Convert.DefaultToType( (IConvertible)this, type, provider ); } #endregion } } ================================================ FILE: Zelig/Zelig/RunTime/Framework/mscorlib/System/Buffer.cs ================================================ // ==++== // // Copyright (c) Microsoft Corporation. All rights reserved. // // ==--== namespace System { //Only contains static methods. Does not require serialization using System; using System.Runtime.CompilerServices; ////using System.Runtime.Versioning; public static class Buffer { // Copies from one primitive array to another primitive array without // respecting types. This calls memmove internally. //// [ResourceExposure( ResourceScope.None )] [MethodImpl( MethodImplOptions.InternalCall )] public static extern void BlockCopy( Array src , int srcOffset , Array dst , int dstOffset , int count ); //// // A very simple and efficient array copy that assumes all of the //// // parameter validation has already been done. All counts here are //// // in bytes. //// [ResourceExposure( ResourceScope.None )] [MethodImpl( MethodImplOptions.InternalCall )] internal static extern void InternalBlockCopy( Array src , int srcOffset , Array dst , int dstOffset , int count ); //// // This is ported from the optimized CRT assembly in memchr.asm. The JIT generates //// // pretty good code here and this ends up being within a couple % of the CRT asm. //// // It is however cross platform as the CRT hasn't ported their fast version to 64-bit //// // platforms. //// // //// internal unsafe static int IndexOfByte( byte* src, byte value, int index, int count ) //// { //// BCLDebug.Assert( src != null, "src should not be null" ); //// //// byte* pByte = src + index; //// //// // Align up the pointer to sizeof(int). //// while(((int)pByte & 3) != 0) //// { //// if(count == 0) //// { //// return -1; //// } //// else if(*pByte == value) //// { //// return (int)(pByte - src); //// } //// //// count--; //// pByte++; //// } //// //// // Fill comparer with value byte for comparisons //// // //// // comparer = 0/0/value/value //// uint comparer = (((uint)value << 8) + (uint)value); //// // comparer = value/value/value/value //// comparer = (comparer << 16) + comparer; //// //// // Run through buffer until we hit a 4-byte section which contains //// // the byte we're looking for or until we exhaust the buffer. //// while(count > 3) //// { //// // Test the buffer for presence of value. comparer contains the byte //// // replicated 4 times. //// uint t1 = *(uint*)pByte; //// t1 = t1 ^ comparer; //// uint t2 = 0x7efefeff + t1; //// t1 = t1 ^ 0xffffffff; //// t1 = t1 ^ t2; //// t1 = t1 & 0x81010100; //// //// // if t1 is zero then these 4-bytes don't contain a match //// if(t1 != 0) //// { //// // We've found a match for value, figure out which position it's in. //// int foundIndex = (int)(pByte - src); //// if(pByte[0] == value) //// { //// return foundIndex; //// } //// else if(pByte[1] == value) //// { //// return foundIndex + 1; //// } //// else if(pByte[2] == value) //// { //// return foundIndex + 2; //// } //// else if(pByte[3] == value) //// { //// return foundIndex + 3; //// } //// } //// //// count -= 4; //// pByte += 4; //// //// } //// //// // Catch any bytes that might be left at the tail of the buffer //// while(count > 0) //// { //// if(*pByte == value) //// { //// return (int)(pByte - src); //// } //// //// count--; //// pByte++; //// } //// //// // If we don't have a match return -1; //// return -1; //// } //// //// // Gets a particular byte out of the array. The array must be an //// // array of primitives. //// // //// // This essentially does the following: //// // return ((byte*)array) + index. //// // //// [ResourceExposure( ResourceScope.None )] //// [MethodImpl( MethodImplOptions.InternalCall )] //// public static extern byte GetByte( Array array, int index ); //// //// // Sets a particular byte in an the array. The array must be an //// // array of primitives. //// // //// // This essentially does the following: //// // *(((byte*)array) + index) = value. //// // //// [ResourceExposure( ResourceScope.None )] //// [MethodImpl( MethodImplOptions.InternalCall )] //// public static extern void SetByte( Array array, int index, byte value ); //// //// // Gets a particular byte out of the array. The array must be an //// // array of primitives. //// // //// // This essentially does the following: //// // return array.length * sizeof(array.UnderlyingElementType). //// // //// [ResourceExposure( ResourceScope.None )] //// [MethodImpl( MethodImplOptions.InternalCall )] //// public static extern int ByteLength( Array array ); //// //// internal unsafe static void ZeroMemory( byte* src, long len ) //// { //// while(len-- > 0) //// { //// *(src + len) = 0; //// } //// } //// //// internal unsafe static void memcpy( byte* src, int srcIndex, byte[] dest, int destIndex, int len ) //// { //// BCLDebug.Assert( (srcIndex >= 0) && (destIndex >= 0) && (len >= 0), "Index and length must be non-negative!" ); //// BCLDebug.Assert( dest.Length - destIndex >= len, "not enough bytes in dest" ); //// //// // If dest has 0 elements, the fixed statement will throw an //// // IndexOutOfRangeException. Special-case 0-byte copies. //// if(len == 0) //// { //// return; //// } //// //// fixed(byte* pDest = dest) //// { //// memcpyimpl( src + srcIndex, pDest + destIndex, len ); //// } //// } //// //// internal unsafe static void memcpy( byte[] src, int srcIndex, byte* pDest, int destIndex, int len ) //// { //// BCLDebug.Assert( (srcIndex >= 0) && (destIndex >= 0) && (len >= 0), "Index and length must be non-negative!" ); //// BCLDebug.Assert( src.Length - srcIndex >= len, "not enough bytes in src" ); //// //// // If dest has 0 elements, the fixed statement will throw an //// // IndexOutOfRangeException. Special-case 0-byte copies. //// if(len == 0) //// { //// return; //// } //// //// fixed(byte* pSrc = src) //// { //// memcpyimpl( pSrc + srcIndex, pDest + destIndex, len ); //// } //// } //// //// internal unsafe static void memcpy( char* pSrc, int srcIndex, char* pDest, int destIndex, int len ) //// { //// BCLDebug.Assert( (srcIndex >= 0) && (destIndex >= 0) && (len >= 0), "Index and length must be non-negative!" ); //// //// // No boundary check for buffer overruns - dangerous //// if(len == 0) //// { //// return; //// } //// //// memcpyimpl( (byte*)(char*)(pSrc + srcIndex), (byte*)(char*)(pDest + destIndex), len * 2 ); //// } //--// [MethodImpl( MethodImplOptions.InternalCall )] internal unsafe extern static void InternalMemoryCopy( byte* src , byte* dst , int count ); [MethodImpl( MethodImplOptions.InternalCall )] internal unsafe extern static void InternalMemoryCopy( sbyte* src , sbyte* dst , int count ); [MethodImpl( MethodImplOptions.InternalCall )] internal unsafe extern static void InternalMemoryCopy( ushort* src , ushort* dst , int count ); [MethodImpl( MethodImplOptions.InternalCall )] internal unsafe extern static void InternalMemoryCopy( short* src , short* dst , int count ); [MethodImpl( MethodImplOptions.InternalCall )] internal unsafe extern static void InternalMemoryCopy( char* src , char* dst , int count ); [MethodImpl( MethodImplOptions.InternalCall )] internal unsafe extern static void InternalMemoryCopy( uint* src , uint* dst , int count ); [MethodImpl( MethodImplOptions.InternalCall )] internal unsafe extern static void InternalMemoryCopy( int* src , int* dst , int count ); //--// [MethodImpl( MethodImplOptions.InternalCall )] internal unsafe extern static void InternalBackwardMemoryCopy( byte* src , byte* dst , int count ); [MethodImpl( MethodImplOptions.InternalCall )] internal unsafe extern static void InternalBackwardMemoryCopy( sbyte* src , sbyte* dst , int count ); [MethodImpl( MethodImplOptions.InternalCall )] internal unsafe extern static void InternalBackwardMemoryCopy( ushort* src , ushort* dst , int count ); [MethodImpl( MethodImplOptions.InternalCall )] internal unsafe extern static void InternalBackwardMemoryCopy( short* src , short* dst , int count ); [MethodImpl( MethodImplOptions.InternalCall )] internal unsafe extern static void InternalBackwardMemoryCopy( char* src , char* dst , int count ); [MethodImpl( MethodImplOptions.InternalCall )] internal unsafe extern static void InternalBackwardMemoryCopy( uint* src , uint* dst , int count ); [MethodImpl( MethodImplOptions.InternalCall )] internal unsafe extern static void InternalBackwardMemoryCopy( int* src , int* dst , int count ); //--// [MethodImpl( MethodImplOptions.InternalCall )] internal unsafe extern static void InternalMemoryMove( byte* src , byte* dst , int count ); [MethodImpl( MethodImplOptions.InternalCall )] internal unsafe extern static void InternalMemoryMove( sbyte* src , sbyte* dst , int count ); [MethodImpl( MethodImplOptions.InternalCall )] internal unsafe extern static void InternalMemoryMove( ushort* src , ushort* dst , int count ); [MethodImpl( MethodImplOptions.InternalCall )] internal unsafe extern static void InternalMemoryMove( short* src , short* dst , int count ); [MethodImpl( MethodImplOptions.InternalCall )] internal unsafe extern static void InternalMemoryMove( char* src , char* dst , int count ); [MethodImpl( MethodImplOptions.InternalCall )] internal unsafe extern static void InternalMemoryMove( uint* src , uint* dst , int count ); [MethodImpl( MethodImplOptions.InternalCall )] internal unsafe extern static void InternalMemoryMove( int* src , int* dst , int count ); } } ================================================ FILE: Zelig/Zelig/RunTime/Framework/mscorlib/System/Byte.cs ================================================ // ==++== // // Copyright (c) Microsoft Corporation. All rights reserved. // // ==--== /*============================================================ ** ** Class: Byte ** ** ** Purpose: This class will encapsulate a byte and provide an ** Object representation of it. ** ** ===========================================================*/ namespace System { using System; using System.Globalization; using System.Runtime.InteropServices; using System.Runtime.CompilerServices; // The Byte class extends the Value class and // provides object representation of the byte primitive type. // [Microsoft.Zelig.Internals.WellKnownType( "System_Byte" )] [Serializable] [StructLayout( LayoutKind.Sequential )] public struct Byte : IComparable, IFormattable, IConvertible, IComparable, IEquatable { public const byte MaxValue = (byte)0xFF; // The maximum value that a Byte may represent: 255. public const byte MinValue = 0x00; // The minimum value that a Byte may represent: 0. private byte m_value; // Compares this object to another object, returning an integer that // indicates the relationship. // Returns a value less than zero if this object // null is considered to be less than any instance. // If object is not of type byte, this method throws an ArgumentException. // public int CompareTo( Object value ) { if(value == null) { return 1; } if(!(value is Byte)) { #if EXCEPTION_STRINGS throw new ArgumentException( Environment.GetResourceString( "Arg_MustBeByte" ) ); #else throw new ArgumentException(); #endif } return m_value - (((Byte)value).m_value); } public int CompareTo( Byte value ) { return m_value - value; } // Determines whether two Byte objects are equal. public override bool Equals( Object obj ) { if(!(obj is Byte)) { return false; } return m_value == ((Byte)obj).m_value; } public bool Equals( Byte obj ) { return m_value == obj; } // Gets a hash code for this instance. public override int GetHashCode() { return m_value; } public static byte Parse( String s ) { return Parse( s, NumberStyles.Integer, NumberFormatInfo.CurrentInfo ); } public static byte Parse( String s , NumberStyles style ) { NumberFormatInfo.ValidateParseStyleInteger( style ); return Parse( s, style, NumberFormatInfo.CurrentInfo ); } public static byte Parse( String s , IFormatProvider provider ) { return Parse( s, NumberStyles.Integer, NumberFormatInfo.GetInstance( provider ) ); } // Parses an unsigned byte from a String in the given style. If // a NumberFormatInfo isn't specified, the current culture's // NumberFormatInfo is assumed. public static byte Parse( String s , NumberStyles style , IFormatProvider provider ) { NumberFormatInfo.ValidateParseStyleInteger( style ); return Parse( s, style, NumberFormatInfo.GetInstance( provider ) ); } private static byte Parse( String s , NumberStyles style , NumberFormatInfo info ) { int i = 0; try { i = Number.ParseInt32( s, style, info ); } catch(OverflowException e) { #if EXCEPTION_STRINGS throw new OverflowException( Environment.GetResourceString( "Overflow_Byte" ), e ); #else throw new OverflowException( null, e); #endif } if(i < MinValue || i > MaxValue) { #if EXCEPTION_STRINGS throw new OverflowException( Environment.GetResourceString( "Overflow_Byte" ) ); #else throw new OverflowException(); #endif } return (byte)i; } public static bool TryParse( String s , out Byte result ) { return TryParse( s, NumberStyles.Integer, NumberFormatInfo.CurrentInfo, out result ); } public static bool TryParse( String s , NumberStyles style , IFormatProvider provider , out Byte result ) { NumberFormatInfo.ValidateParseStyleInteger( style ); return TryParse( s, style, NumberFormatInfo.GetInstance( provider ), out result ); } private static bool TryParse( String s , NumberStyles style , NumberFormatInfo info , out Byte result ) { result = 0; int i; if(!Number.TryParseInt32( s, style, info, out i )) { return false; } if(i < MinValue || i > MaxValue) { return false; } result = (byte)i; return true; } public override String ToString() { return Number.FormatInt32( m_value, /*null,*/ NumberFormatInfo.CurrentInfo ); } public String ToString( String format ) { return Number.FormatInt32( m_value, format, NumberFormatInfo.CurrentInfo ); } public String ToString( IFormatProvider provider ) { return Number.FormatInt32( m_value, /*null,*/ NumberFormatInfo.GetInstance( provider ) ); } public String ToString( String format, IFormatProvider provider ) { return Number.FormatInt32( m_value, format, NumberFormatInfo.GetInstance( provider ) ); } #region IConvertible public TypeCode GetTypeCode() { return TypeCode.Byte; } /// bool IConvertible.ToBoolean( IFormatProvider provider ) { return Convert.ToBoolean( m_value ); } /// char IConvertible.ToChar( IFormatProvider provider ) { return Convert.ToChar( m_value ); } /// sbyte IConvertible.ToSByte( IFormatProvider provider ) { return Convert.ToSByte( m_value ); } /// byte IConvertible.ToByte( IFormatProvider provider ) { return m_value; } /// short IConvertible.ToInt16( IFormatProvider provider ) { return Convert.ToInt16( m_value ); } /// ushort IConvertible.ToUInt16( IFormatProvider provider ) { return Convert.ToUInt16( m_value ); } /// int IConvertible.ToInt32( IFormatProvider provider ) { return Convert.ToInt32( m_value ); } /// uint IConvertible.ToUInt32( IFormatProvider provider ) { return Convert.ToUInt32( m_value ); } /// long IConvertible.ToInt64( IFormatProvider provider ) { return Convert.ToInt64( m_value ); } /// ulong IConvertible.ToUInt64( IFormatProvider provider ) { return Convert.ToUInt64( m_value ); } /// float IConvertible.ToSingle( IFormatProvider provider ) { return Convert.ToSingle( m_value ); } /// double IConvertible.ToDouble( IFormatProvider provider ) { return Convert.ToDouble( m_value ); } /// Decimal IConvertible.ToDecimal( IFormatProvider provider ) { return Convert.ToDecimal( m_value ); } /// DateTime IConvertible.ToDateTime( IFormatProvider provider ) { #if EXCEPTION_STRINGS throw new InvalidCastException( String.Format( CultureInfo.CurrentCulture, Environment.GetResourceString( "InvalidCast_FromTo" ), "Byte", "DateTime" ) ); #else throw new InvalidCastException(); #endif } /// Object IConvertible.ToType( Type type, IFormatProvider provider ) { return Convert.DefaultToType( (IConvertible)this, type, provider ); } #endregion } } ================================================ FILE: Zelig/Zelig/RunTime/Framework/mscorlib/System/CLSCompliantAttribute.cs ================================================ // ==++== // // Copyright (c) Microsoft Corporation. All rights reserved. // // ==--== /*============================================================================= ** ** Class: CLSCompliantAttribute ** ** ** Purpose: Container for assemblies. ** ** =============================================================================*/ namespace System { [Serializable] [AttributeUsage( AttributeTargets.All, Inherited = true, AllowMultiple = false )] public sealed class CLSCompliantAttribute : Attribute { private bool m_compliant; public CLSCompliantAttribute( bool isCompliant ) { m_compliant = isCompliant; } public bool IsCompliant { get { return m_compliant; } } } } ================================================ FILE: Zelig/Zelig/RunTime/Framework/mscorlib/System/Char.cs ================================================ // ==++== // // Copyright (c) Microsoft Corporation. All rights reserved. // // ==--== /*============================================================ ** ** Class: Char ** ** ** Purpose: This is the value class representing a Unicode character ** Char methods until we create this functionality. ** ** ===========================================================*/ namespace System { using System; using System.Globalization; using System.Runtime.InteropServices; using System.Runtime.CompilerServices; [Microsoft.Zelig.Internals.WellKnownType( "System_Char" )] [Serializable] [StructLayout( LayoutKind.Sequential )] public struct Char : IComparable, IConvertible, IComparable, IEquatable { public const char MaxValue = (char)0xFFFF; public const char MinValue = (char)0x0000; // // Member Variables // internal char m_value; //// // Unicode category values from Unicode U+0000 ~ U+00FF. Store them in byte[] array to save space. //// private const byte CTRL = (byte)UnicodeCategory.Control; //// private const byte SPACE = (byte)UnicodeCategory.SpaceSeparator; //// private const byte DIGIT = (byte)UnicodeCategory.DecimalDigitNumber; //// private const byte DIGIT_OTHER = (byte)UnicodeCategory.OtherNumber; //// private const byte LETTER_UC = (byte)UnicodeCategory.UppercaseLetter; //// private const byte LETTER_LC = (byte)UnicodeCategory.LowercaseLetter; //// private const byte PUNCT_OPEN = (byte)UnicodeCategory.OpenPunctuation; //// private const byte PUNCT_CLOSE = (byte)UnicodeCategory.ClosePunctuation; //// private const byte PUNCT_DASH = (byte)UnicodeCategory.DashPunctuation; //// private const byte PUNCT_CONN = (byte)UnicodeCategory.ConnectorPunctuation; //// private const byte PUNCT_IQ = (byte)UnicodeCategory.InitialQuotePunctuation; //// private const byte PUNCT_FQ = (byte)UnicodeCategory.FinalQuotePunctuation; //// private const byte PUNCT_OTHER = (byte)UnicodeCategory.OtherPunctuation; //// private const byte CURRENCY = (byte)UnicodeCategory.CurrencySymbol; //// private const byte MATH = (byte)UnicodeCategory.MathSymbol; //// private const byte MODIFIER = (byte)UnicodeCategory.ModifierSymbol; //// private const byte OTHER = (byte)UnicodeCategory.OtherSymbol; //// //// private readonly static byte[] categoryForLatin1 = //// { //// CTRL , CTRL , CTRL , CTRL , CTRL , CTRL , CTRL , CTRL , // 0000 - 0007 //// CTRL , CTRL , CTRL , CTRL , CTRL , CTRL , CTRL , CTRL , // 0008 - 000F //// CTRL , CTRL , CTRL , CTRL , CTRL , CTRL , CTRL , CTRL , // 0010 - 0017 //// CTRL , CTRL , CTRL , CTRL , CTRL , CTRL , CTRL , CTRL , // 0018 - 001F //// SPACE , PUNCT_OTHER, PUNCT_OTHER, PUNCT_OTHER, CURRENCY , PUNCT_OTHER, PUNCT_OTHER, PUNCT_OTHER, // 0020 - 0027 //// PUNCT_OPEN , PUNCT_CLOSE, PUNCT_OTHER, MATH , PUNCT_OTHER, PUNCT_DASH , PUNCT_OTHER, PUNCT_OTHER, // 0028 - 002F //// DIGIT , DIGIT , DIGIT , DIGIT , DIGIT , DIGIT , DIGIT , DIGIT , // 0030 - 0037 //// DIGIT , DIGIT , PUNCT_OTHER, PUNCT_OTHER, MATH , MATH , MATH , PUNCT_OTHER, // 0038 - 003F //// PUNCT_OTHER, LETTER_UC , LETTER_UC , LETTER_UC , LETTER_UC , LETTER_UC , LETTER_UC , LETTER_UC , // 0040 - 0047 //// LETTER_UC , LETTER_UC , LETTER_UC , LETTER_UC , LETTER_UC , LETTER_UC , LETTER_UC , LETTER_UC , // 0048 - 004F //// LETTER_UC , LETTER_UC , LETTER_UC , LETTER_UC , LETTER_UC , LETTER_UC , LETTER_UC , LETTER_UC , // 0050 - 0057 //// LETTER_UC , LETTER_UC , LETTER_UC , PUNCT_OPEN , PUNCT_OTHER, PUNCT_CLOSE, MODIFIER , PUNCT_CONN , // 0058 - 005F //// MODIFIER , LETTER_LC , LETTER_LC , LETTER_LC , LETTER_LC , LETTER_LC , LETTER_LC , LETTER_LC , // 0060 - 0067 //// LETTER_LC , LETTER_LC , LETTER_LC , LETTER_LC , LETTER_LC , LETTER_LC , LETTER_LC , LETTER_LC , // 0068 - 006F //// LETTER_LC , LETTER_LC , LETTER_LC , LETTER_LC , LETTER_LC , LETTER_LC , LETTER_LC , LETTER_LC , // 0070 - 0077 //// LETTER_LC , LETTER_LC , LETTER_LC , PUNCT_OPEN , MATH , PUNCT_CLOSE, MATH , CTRL , // 0078 - 007F //// CTRL , CTRL , CTRL , CTRL , CTRL , CTRL , CTRL , CTRL , // 0080 - 0087 //// CTRL , CTRL , CTRL , CTRL , CTRL , CTRL , CTRL , CTRL , // 0088 - 008F //// CTRL , CTRL , CTRL , CTRL , CTRL , CTRL , CTRL , CTRL , // 0090 - 0097 //// CTRL , CTRL , CTRL , CTRL , CTRL , CTRL , CTRL , CTRL , // 0098 - 009F //// SPACE , PUNCT_OTHER, CURRENCY , CURRENCY , CURRENCY , CURRENCY , OTHER , OTHER , // 00A0 - 00A7 //// MODIFIER , OTHER , LETTER_LC , PUNCT_IQ , MATH , PUNCT_DASH , OTHER , MODIFIER , // 00A8 - 00AF //// OTHER , MATH , DIGIT_OTHER, DIGIT_OTHER, MODIFIER , LETTER_LC , OTHER , PUNCT_OTHER, // 00B0 - 00B7 //// MODIFIER , DIGIT_OTHER, LETTER_LC , PUNCT_FQ , DIGIT_OTHER, DIGIT_OTHER, DIGIT_OTHER, PUNCT_OTHER, // 00B8 - 00BF //// LETTER_UC , LETTER_UC , LETTER_UC , LETTER_UC , LETTER_UC , LETTER_UC , LETTER_UC , LETTER_UC , // 00C0 - 00C7 //// LETTER_UC , LETTER_UC , LETTER_UC , LETTER_UC , LETTER_UC , LETTER_UC , LETTER_UC , LETTER_UC , // 00C8 - 00CF //// LETTER_UC , LETTER_UC , LETTER_UC , LETTER_UC , LETTER_UC , LETTER_UC , LETTER_UC , MATH , // 00D0 - 00D7 //// LETTER_UC , LETTER_UC , LETTER_UC , LETTER_UC , LETTER_UC , LETTER_UC , LETTER_UC , LETTER_LC , // 00D8 - 00DF //// LETTER_LC , LETTER_LC , LETTER_LC , LETTER_LC , LETTER_LC , LETTER_LC , LETTER_LC , LETTER_LC , // 00E0 - 00E7 //// LETTER_LC , LETTER_LC , LETTER_LC , LETTER_LC , LETTER_LC , LETTER_LC , LETTER_LC , LETTER_LC , // 00E8 - 00EF //// LETTER_LC , LETTER_LC , LETTER_LC , LETTER_LC , LETTER_LC , LETTER_LC , LETTER_LC , MATH , // 00F0 - 00F7 //// LETTER_LC , LETTER_LC , LETTER_LC , LETTER_LC , LETTER_LC , LETTER_LC , LETTER_LC , LETTER_LC , // 00F8 - 00FF //// }; // Return true for all characters below or equal U+00ff, which is ASCII + Latin-1 Supplement. private static bool IsLatin1( char ch ) { return (ch <= '\x00ff'); } //// // Return true for all characters below or equal U+007f, which is ASCII. //// private static bool IsAscii( char ch ) //// { //// return (ch <= '\x007f'); //// } //// //// // Return the Unicode category for Unicode character <= 0x00ff. //// private static UnicodeCategory GetLatin1UnicodeCategory( char ch ) //// { //// //// BCLDebug.Assert( IsLatin1( ch ), "Char.GetLatin1UnicodeCategory(): ch should be <= 007f" ); //// return (UnicodeCategory)(categoryForLatin1[(int)ch]); //// } // // Overriden Instance Methods // // Calculate a hashcode for a 2 byte Unicode character. public override int GetHashCode() { return (int)m_value | ((int)m_value << 16); } // Used for comparing two boxed Char objects. // public override bool Equals( Object obj ) { if(!(obj is Char)) { return false; } return (m_value == ((Char)obj).m_value); } public bool Equals( Char obj ) { return m_value == obj; } // Compares this object to another object, returning an integer that // indicates the relationship. // Returns a value less than zero if this object // null is considered to be less than any instance. // If object is not of type Char, this method throws an ArgumentException. // public int CompareTo( Object value ) { if(value == null) { return 1; } if(!(value is Char)) { #if EXCEPTION_STRINGS throw new ArgumentException( Environment.GetResourceString( "Arg_MustBeChar" ) ); #else throw new ArgumentException(); #endif } return (m_value - ((Char)value).m_value); } public int CompareTo( Char value ) { return (m_value - value); } // Overrides System.Object.ToString. public override String ToString() { return Char.ToString( m_value ); } public String ToString( IFormatProvider provider ) { return Char.ToString( m_value ); } // // Formatting Methods // /*===================================ToString=================================== **This static methods takes a character and returns the String representation of it. ==============================================================================*/ // Provides a string representation of a character. public static String ToString( char c ) { return new String( c, 1 ); } public static char Parse( String s ) { if(s == null) { #if EXCEPTION_STRINGS throw new ArgumentNullException( "s" ); #else throw new ArgumentNullException(); #endif } if(s.Length != 1) { #if EXCEPTION_STRINGS throw new FormatException( Environment.GetResourceString( "Format_NeedSingleChar" ) ); #else throw new FormatException(); #endif } return s[0]; } public static bool TryParse( String s, out Char result ) { result = '\0'; if(s == null) { return false; } if(s.Length != 1) { return false; } result = s[0]; return true; } //// // //// // Static Methods //// // //// /*=================================ISDIGIT====================================== //// **A wrapper for Char. Returns a boolean indicating whether ** //// **character c is considered to be a digit. ** //// ==============================================================================*/ //// // Determines whether a character is a digit. //// public static bool IsDigit( char c ) //// { //// if(IsLatin1( c )) //// { //// return (c >= '0' && c <= '9'); //// } //// return (CharUnicodeInfo.GetUnicodeCategory( c ) == UnicodeCategory.DecimalDigitNumber); //// } //// //// //// /*=================================CheckLetter===================================== //// ** Check if the specified UnicodeCategory belongs to the letter categories. //// ==============================================================================*/ //// internal static bool CheckLetter( UnicodeCategory uc ) //// { //// switch(uc) //// { //// case UnicodeCategory.UppercaseLetter: //// case UnicodeCategory.LowercaseLetter: //// case UnicodeCategory.TitlecaseLetter: //// case UnicodeCategory.ModifierLetter : //// case UnicodeCategory.OtherLetter : //// return true; //// } //// return false; //// } //// //// /*=================================ISLETTER===================================== //// **A wrapper for Char. Returns a boolean indicating whether ** //// **character c is considered to be a letter. ** //// ==============================================================================*/ //// // Determines whether a character is a letter. //// public static bool IsLetter( char c ) //// { //// if(IsLatin1( c )) //// { //// if(IsAscii( c )) //// { //// c |= (char)0x20; //// //// return ((c >= 'a' && c <= 'z')); //// } //// //// return (CheckLetter( GetLatin1UnicodeCategory( c ) )); //// } //// //// return (CheckLetter( CharUnicodeInfo.GetUnicodeCategory( c ) )); //// } private static bool IsWhiteSpaceLatin1( char c ) { // There are characters which belong to UnicodeCategory.Control but are considered as white spaces. // We use code point comparisons for these characters here as a temporary fix. // U+0009 = HORIZONTAL TAB // U+000a = LINE FEED // U+000b = VERTICAL TAB // U+000c = FORM FEED // U+000d = CARRIAGE RETURN // U+0085 = NEXT LINE // U+00a0 = NO-BREAK SPACE if((c == ' ') || (c >= '\x0009' && c <= '\x000d') || c == '\x00a0' || c == '\x0085') { return (true); } return (false); } /*===============================ISWHITESPACE=================================== **A wrapper for Char. Returns a boolean indicating whether ** **character c is considered to be a whitespace character. ** ==============================================================================*/ // Determines whether a character is whitespace. public static bool IsWhiteSpace( char c ) { if(IsLatin1( c )) { return (IsWhiteSpaceLatin1( c )); } //// return CharUnicodeInfo.IsWhiteSpace( c ); return false; } //// /*===================================IsUpper==================================== //// **Arguments: c -- the characater to be checked. //// **Returns: True if c is an uppercase character. //// ==============================================================================*/ //// // Determines whether a character is upper-case. //// public static bool IsUpper( char c ) //// { //// if(IsLatin1( c )) //// { //// if(IsAscii( c )) //// { //// return (c >= 'A' && c <= 'Z'); //// } //// return (GetLatin1UnicodeCategory( c ) == UnicodeCategory.UppercaseLetter); //// } //// //// return (CharUnicodeInfo.GetUnicodeCategory( c ) == UnicodeCategory.UppercaseLetter); //// } //// //// /*===================================IsLower==================================== //// **Arguments: c -- the characater to be checked. //// **Returns: True if c is an lowercase character. //// ==============================================================================*/ //// // Determines whether a character is lower-case. //// public static bool IsLower( char c ) //// { //// if(IsLatin1( c )) //// { //// if(IsAscii( c )) //// { //// return (c >= 'a' && c <= 'z'); //// } //// return (GetLatin1UnicodeCategory( c ) == UnicodeCategory.LowercaseLetter); //// } //// //// return (CharUnicodeInfo.GetUnicodeCategory( c ) == UnicodeCategory.LowercaseLetter); //// } //// //// internal static bool CheckPunctuation( UnicodeCategory uc ) //// { //// switch(uc) //// { //// case UnicodeCategory.ConnectorPunctuation : //// case UnicodeCategory.DashPunctuation : //// case UnicodeCategory.OpenPunctuation : //// case UnicodeCategory.ClosePunctuation : //// case UnicodeCategory.InitialQuotePunctuation: //// case UnicodeCategory.FinalQuotePunctuation : //// case UnicodeCategory.OtherPunctuation : //// return true; //// } //// //// return false; //// } //// //// //// /*================================IsPunctuation================================= //// **Arguments: c -- the characater to be checked. //// **Returns: True if c is an punctuation mark //// ==============================================================================*/ //// // Determines whether a character is a punctuation mark. //// public static bool IsPunctuation( char c ) //// { //// if(IsLatin1( c )) //// { //// return (CheckPunctuation( GetLatin1UnicodeCategory( c ) )); //// } //// //// return (CheckPunctuation( CharUnicodeInfo.GetUnicodeCategory( c ) )); //// } //// //// /*=================================CheckLetterOrDigit===================================== //// ** Check if the specified UnicodeCategory belongs to the letter or digit categories. //// ==============================================================================*/ //// internal static bool CheckLetterOrDigit( UnicodeCategory uc ) //// { //// switch(uc) //// { //// case UnicodeCategory.UppercaseLetter : //// case UnicodeCategory.LowercaseLetter : //// case UnicodeCategory.TitlecaseLetter : //// case UnicodeCategory.ModifierLetter : //// case UnicodeCategory.OtherLetter : //// case UnicodeCategory.DecimalDigitNumber: //// return true; //// } //// return false; //// } //// //// // Determines whether a character is a letter or a digit. //// public static bool IsLetterOrDigit( char c ) //// { //// if(IsLatin1( c )) //// { //// return (CheckLetterOrDigit( GetLatin1UnicodeCategory( c ) )); //// } //// //// return (CheckLetterOrDigit( CharUnicodeInfo.GetUnicodeCategory( c ) )); //// } //// //// /*===================================ToUpper==================================== //// ** //// ==============================================================================*/ //// // Converts a character to upper-case for the specified culture. //// // <;<;Not fully implemented>;>; //// public static char ToUpper( char c, CultureInfo culture ) //// { //// if(culture == null) //// { //// throw new ArgumentNullException( "culture" ); //// } //// //// return culture.TextInfo.ToUpper( c ); //// } //// //// /*=================================TOUPPER====================================== //// **A wrapper for Char.toUpperCase. Converts character c to its ** //// **uppercase equivalent. If c is already an uppercase character or is not an ** //// **alphabetic, nothing happens. ** //// ==============================================================================*/ //// // Converts a character to upper-case for the default culture. //// // //// public static char ToUpper( char c ) //// { //// return ToUpper( c, CultureInfo.CurrentCulture ); //// } //// //// // Converts a character to upper-case for invariant culture. //// public static char ToUpperInvariant( char c ) //// { //// return ToUpper( c, CultureInfo.InvariantCulture ); //// } //// //// /*===================================ToLower==================================== //// ** //// ==============================================================================*/ //// // Converts a character to lower-case for the specified culture. //// // <;<;Not fully implemented>;>; //// public static char ToLower( char c, CultureInfo culture ) //// { //// if(culture == null) //// { //// throw new ArgumentNullException( "culture" ); //// } //// //// return culture.TextInfo.ToLower( c ); //// } //// //// /*=================================TOLOWER====================================== //// **A wrapper for Char.toLowerCase. Converts character c to its ** //// **lowercase equivalent. If c is already a lowercase character or is not an ** //// **alphabetic, nothing happens. ** //// ==============================================================================*/ //// // Converts a character to lower-case for the default culture. //// public static char ToLower( char c ) //// { //// return ToLower( c, CultureInfo.CurrentCulture ); //// } //// //// // Converts a character to lower-case for invariant culture. //// public static char ToLowerInvariant( char c ) //// { //// return ToLower( c, CultureInfo.InvariantCulture ); //// } #region IConvertible public TypeCode GetTypeCode() { return TypeCode.Char; } /// bool IConvertible.ToBoolean( IFormatProvider provider ) { #if EXCEPTION_STRINGS throw new InvalidCastException( String.Format( CultureInfo.CurrentCulture, Environment.GetResourceString( "InvalidCast_FromTo" ), "Char", "Boolean" ) ); #else throw new InvalidCastException(); #endif } /// char IConvertible.ToChar( IFormatProvider provider ) { return m_value; } /// sbyte IConvertible.ToSByte( IFormatProvider provider ) { return Convert.ToSByte( m_value ); } /// byte IConvertible.ToByte( IFormatProvider provider ) { return Convert.ToByte( m_value ); } /// short IConvertible.ToInt16( IFormatProvider provider ) { return Convert.ToInt16( m_value ); } /// ushort IConvertible.ToUInt16( IFormatProvider provider ) { return Convert.ToUInt16( m_value ); } /// int IConvertible.ToInt32( IFormatProvider provider ) { return Convert.ToInt32( m_value ); } /// uint IConvertible.ToUInt32( IFormatProvider provider ) { return Convert.ToUInt32( m_value ); } /// long IConvertible.ToInt64( IFormatProvider provider ) { return Convert.ToInt64( m_value ); } /// ulong IConvertible.ToUInt64( IFormatProvider provider ) { return Convert.ToUInt64( m_value ); } /// float IConvertible.ToSingle( IFormatProvider provider ) { #if EXCEPTION_STRINGS throw new InvalidCastException( String.Format( CultureInfo.CurrentCulture, Environment.GetResourceString( "InvalidCast_FromTo" ), "Char", "Single" ) ); #else throw new InvalidCastException(); #endif } /// double IConvertible.ToDouble( IFormatProvider provider ) { #if EXCEPTION_STRINGS throw new InvalidCastException( String.Format( CultureInfo.CurrentCulture, Environment.GetResourceString( "InvalidCast_FromTo" ), "Char", "Double" ) ); #else throw new InvalidCastException(); #endif } /// Decimal IConvertible.ToDecimal( IFormatProvider provider ) { #if EXCEPTION_STRINGS throw new InvalidCastException( String.Format( CultureInfo.CurrentCulture, Environment.GetResourceString( "InvalidCast_FromTo" ), "Char", "Decimal" ) ); #else throw new InvalidCastException(); #endif } /// DateTime IConvertible.ToDateTime( IFormatProvider provider ) { #if EXCEPTION_STRINGS throw new InvalidCastException( String.Format( CultureInfo.CurrentCulture, Environment.GetResourceString( "InvalidCast_FromTo" ), "Char", "DateTime" ) ); #else throw new InvalidCastException(); #endif } /// Object IConvertible.ToType( Type type, IFormatProvider provider ) { return Convert.DefaultToType( (IConvertible)this, type, provider ); } #endregion //// public static bool IsControl( char c ) //// { //// if(IsLatin1( c )) //// { //// return (GetLatin1UnicodeCategory( c ) == UnicodeCategory.Control); //// } //// //// return (CharUnicodeInfo.GetUnicodeCategory( c ) == UnicodeCategory.Control); //// } //// //// public static bool IsControl( String s, int index ) //// { //// if(s == null) //// { //// throw new ArgumentNullException( "s" ); //// } //// //// if(((uint)index) >= ((uint)s.Length)) //// { //// throw new ArgumentOutOfRangeException( "index" ); //// } //// //// char c = s[index]; //// if(IsLatin1( c )) //// { //// return (GetLatin1UnicodeCategory( c ) == UnicodeCategory.Control); //// } //// //// return (CharUnicodeInfo.GetUnicodeCategory( s, index ) == UnicodeCategory.Control); //// } //// //// //// public static bool IsDigit( String s, int index ) //// { //// if(s == null) //// { //// throw new ArgumentNullException( "s" ); //// } //// //// if(((uint)index) >= ((uint)s.Length)) //// { //// throw new ArgumentOutOfRangeException( "index" ); //// } //// //// char c = s[index]; //// if(IsLatin1( c )) //// { //// return (c >= '0' && c <= '9'); //// } //// //// return (CharUnicodeInfo.GetUnicodeCategory( s, index ) == UnicodeCategory.DecimalDigitNumber); //// } //// //// public static bool IsLetter( String s, int index ) //// { //// if(s == null) //// { //// throw new ArgumentNullException( "s" ); //// } //// if(((uint)index) >= ((uint)s.Length)) //// { //// throw new ArgumentOutOfRangeException( "index" ); //// } //// //// char c = s[index]; //// if(IsLatin1( c )) //// { //// if(IsAscii( c )) //// { //// c |= (char)0x20; //// return ((c >= 'a' && c <= 'z')); //// } //// //// return (CheckLetter( GetLatin1UnicodeCategory( c ) )); //// } //// //// return (CheckLetter( CharUnicodeInfo.GetUnicodeCategory( s, index ) )); //// } //// //// public static bool IsLetterOrDigit( String s, int index ) //// { //// if(s == null) //// { //// throw new ArgumentNullException( "s" ); //// } //// //// if(((uint)index) >= ((uint)s.Length)) //// { //// throw new ArgumentOutOfRangeException( "index" ); //// } //// //// char c = s[index]; //// if(IsLatin1( c )) //// { //// return CheckLetterOrDigit( GetLatin1UnicodeCategory( c ) ); //// } //// //// return CheckLetterOrDigit( CharUnicodeInfo.GetUnicodeCategory( s, index ) ); //// } //// //// public static bool IsLower( String s, int index ) //// { //// if(s == null) //// { //// throw new ArgumentNullException( "s" ); //// } //// //// if(((uint)index) >= ((uint)s.Length)) //// { //// throw new ArgumentOutOfRangeException( "index" ); //// } //// //// char c = s[index]; //// if(IsLatin1( c )) //// { //// if(IsAscii( c )) //// { //// return (c >= 'a' && c <= 'z'); //// } //// //// return (GetLatin1UnicodeCategory( c ) == UnicodeCategory.LowercaseLetter); //// } //// //// return (CharUnicodeInfo.GetUnicodeCategory( s, index ) == UnicodeCategory.LowercaseLetter); //// } //// //// /*=================================CheckNumber===================================== //// ** Check if the specified UnicodeCategory belongs to the number categories. //// ==============================================================================*/ //// //// internal static bool CheckNumber( UnicodeCategory uc ) //// { //// switch(uc) //// { //// case UnicodeCategory.DecimalDigitNumber: //// case UnicodeCategory.LetterNumber : //// case UnicodeCategory.OtherNumber : //// return true; //// } //// return false; //// } //// //// public static bool IsNumber( char c ) //// { //// if(IsLatin1( c )) //// { //// if(IsAscii( c )) //// { //// return (c >= '0' && c <= '9'); //// } //// //// return (CheckNumber( GetLatin1UnicodeCategory( c ) )); //// } //// //// return (CheckNumber( CharUnicodeInfo.GetUnicodeCategory( c ) )); //// } //// //// public static bool IsNumber( String s, int index ) //// { //// if(s == null) //// { //// throw new ArgumentNullException( "s" ); //// } //// //// if(((uint)index) >= ((uint)s.Length)) //// { //// throw new ArgumentOutOfRangeException( "index" ); //// } //// //// char c = s[index]; //// if(IsLatin1( c )) //// { //// if(IsAscii( c )) //// { //// return (c >= '0' && c <= '9'); //// } //// //// return (CheckNumber( GetLatin1UnicodeCategory( c ) )); //// } //// //// return (CheckNumber( CharUnicodeInfo.GetUnicodeCategory( s, index ) )); //// } //// //// //////////////////////////////////////////////////////////////////////// //// // //// // IsPunctuation //// // //// // Determines if the given character is a punctuation character. //// // //// //////////////////////////////////////////////////////////////////////// //// //// public static bool IsPunctuation( String s, int index ) //// { //// if(s == null) //// { //// throw new ArgumentNullException( "s" ); //// } //// //// if(((uint)index) >= ((uint)s.Length)) //// { //// throw new ArgumentOutOfRangeException( "index" ); //// } //// //// char c = s[index]; //// if(IsLatin1( c )) //// { //// return (CheckPunctuation( GetLatin1UnicodeCategory( c ) )); //// } //// //// return (CheckPunctuation( CharUnicodeInfo.GetUnicodeCategory( s, index ) )); //// } //// //// //// /*================================= CheckSeparator ============================ //// ** Check if the specified UnicodeCategory belongs to the seprator categories. //// ==============================================================================*/ //// //// internal static bool CheckSeparator( UnicodeCategory uc ) //// { //// switch(uc) //// { //// case UnicodeCategory.SpaceSeparator : //// case UnicodeCategory.LineSeparator : //// case UnicodeCategory.ParagraphSeparator: //// return true; //// } //// return false; //// } //// //// private static bool IsSeparatorLatin1( char c ) //// { //// // U+00a0 = NO-BREAK SPACE //// // There is no LineSeparator or ParagraphSeparator in Latin 1 range. //// return (c == '\x0020' || c == '\x00a0'); //// } //// //// public static bool IsSeparator( char c ) //// { //// if(IsLatin1( c )) //// { //// return (IsSeparatorLatin1( c )); //// } //// //// return (CheckSeparator( CharUnicodeInfo.GetUnicodeCategory( c ) )); //// } //// //// public static bool IsSeparator( String s, int index ) //// { //// if(s == null) //// { //// throw new ArgumentNullException( "s" ); //// } //// //// if(((uint)index) >= ((uint)s.Length)) //// { //// throw new ArgumentOutOfRangeException( "index" ); //// } //// //// char c = s[index]; //// if(IsLatin1( c )) //// { //// return (IsSeparatorLatin1( c )); //// } //// //// return (CheckSeparator( CharUnicodeInfo.GetUnicodeCategory( s, index ) )); //// } public static bool IsSurrogate( char c ) { return (c >= HIGH_SURROGATE_START && c <= LOW_SURROGATE_END); } public static bool IsSurrogate( String s, int index ) { if(s == null) { #if EXCEPTION_STRINGS throw new ArgumentNullException( "s" ); #else throw new ArgumentNullException(); #endif } if(((uint)index) >= ((uint)s.Length)) { #if EXCEPTION_STRINGS throw new ArgumentOutOfRangeException( "index" ); #else throw new ArgumentOutOfRangeException(); #endif } return (IsSurrogate( s[index] )); } //// /*================================= CheckSymbol ============================ //// ** Check if the specified UnicodeCategory belongs to the symbol categories. //// ==============================================================================*/ //// //// internal static bool CheckSymbol( UnicodeCategory uc ) //// { //// switch(uc) //// { //// case UnicodeCategory.MathSymbol : //// case UnicodeCategory.CurrencySymbol: //// case UnicodeCategory.ModifierSymbol: //// case UnicodeCategory.OtherSymbol : //// return true; //// } //// return false; //// } //// //// public static bool IsSymbol( char c ) //// { //// if(IsLatin1( c )) //// { //// return (CheckSymbol( GetLatin1UnicodeCategory( c ) )); //// } //// //// return (CheckSymbol( CharUnicodeInfo.GetUnicodeCategory( c ) )); //// } //// //// public static bool IsSymbol( String s, int index ) //// { //// if(s == null) //// { //// throw new ArgumentNullException( "s" ); //// } //// //// if(((uint)index) >= ((uint)s.Length)) //// { //// throw new ArgumentOutOfRangeException( "index" ); //// } //// //// if(IsLatin1( s[index] )) //// { //// return (CheckSymbol( GetLatin1UnicodeCategory( s[index] ) )); //// } //// //// return (CheckSymbol( CharUnicodeInfo.GetUnicodeCategory( s, index ) )); //// } //// //// //// public static bool IsUpper( String s, int index ) //// { //// if(s == null) //// { //// throw new ArgumentNullException( "s" ); //// } //// //// if(((uint)index) >= ((uint)s.Length)) //// { //// throw new ArgumentOutOfRangeException( "index" ); //// } //// //// char c = s[index]; //// if(IsLatin1( c )) //// { //// if(IsAscii( c )) //// { //// return (c >= 'A' && c <= 'Z'); //// } //// //// return (GetLatin1UnicodeCategory( c ) == UnicodeCategory.UppercaseLetter); //// } //// //// return (CharUnicodeInfo.GetUnicodeCategory( s, index ) == UnicodeCategory.UppercaseLetter); //// } //// //// public static bool IsWhiteSpace( String s, int index ) //// { //// if(s == null) //// { //// throw new ArgumentNullException( "s" ); //// } //// //// if(((uint)index) >= ((uint)s.Length)) //// { //// throw new ArgumentOutOfRangeException( "index" ); //// } //// //// if(IsLatin1( s[index] )) //// { //// return IsWhiteSpaceLatin1( s[index] ); //// } //// //// return CharUnicodeInfo.IsWhiteSpace( s, index ); //// } //// //// public static UnicodeCategory GetUnicodeCategory( char c ) //// { //// if(IsLatin1( c )) //// { //// return (GetLatin1UnicodeCategory( c )); //// } //// //// return CharUnicodeInfo.InternalGetUnicodeCategory( c ); //// } //// //// public static UnicodeCategory GetUnicodeCategory( String s, int index ) //// { //// if(s == null) //// { //// throw new ArgumentNullException( "s" ); //// } //// //// if(((uint)index) >= ((uint)s.Length)) //// { //// throw new ArgumentOutOfRangeException( "index" ); //// } //// //// if(IsLatin1( s[index] )) //// { //// return (GetLatin1UnicodeCategory( s[index] )); //// } //// //// return CharUnicodeInfo.InternalGetUnicodeCategory( s, index ); //// } //// //// public static double GetNumericValue( char c ) //// { //// return CharUnicodeInfo.GetNumericValue( c ); //// } //// //// public static double GetNumericValue( String s, int index ) //// { //// if(s == null) //// { //// throw new ArgumentNullException( "s" ); //// } //// //// if(((uint)index) >= ((uint)s.Length)) //// { //// throw new ArgumentOutOfRangeException( "index" ); //// } //// //// return CharUnicodeInfo.GetNumericValue( s, index ); //// } /*================================= IsHighSurrogate ============================ ** Check if a char is a high surrogate. ==============================================================================*/ public static bool IsHighSurrogate( char c ) { return ((c >= CharUnicodeInfo.HIGH_SURROGATE_START) && (c <= CharUnicodeInfo.HIGH_SURROGATE_END)); } public static bool IsHighSurrogate( String s, int index ) { if(s == null) { #if EXCEPTION_STRINGS throw new ArgumentNullException( "s" ); #else throw new ArgumentNullException(); #endif } if(index < 0 || index >= s.Length) { #if EXCEPTION_STRINGS throw new ArgumentOutOfRangeException( "index" ); #else throw new ArgumentOutOfRangeException(); #endif } return (IsHighSurrogate( s[index] )); } /*================================= IsLowSurrogate ============================ ** Check if a char is a low surrogate. ==============================================================================*/ public static bool IsLowSurrogate( char c ) { return ((c >= CharUnicodeInfo.LOW_SURROGATE_START) && (c <= CharUnicodeInfo.LOW_SURROGATE_END)); } public static bool IsLowSurrogate( String s, int index ) { if(s == null) { #if EXCEPTION_STRINGS throw new ArgumentNullException( "s" ); #else throw new ArgumentNullException(); #endif } if(index < 0 || index >= s.Length) { #if EXCEPTION_STRINGS throw new ArgumentOutOfRangeException( "index" ); #else throw new ArgumentOutOfRangeException(); #endif } return (IsLowSurrogate( s[index] )); } /*================================= IsSurrogatePair ============================ ** Check if the string specified by the index starts with a surrogate pair. ==============================================================================*/ public static bool IsSurrogatePair( String s, int index ) { if(s == null) { #if EXCEPTION_STRINGS throw new ArgumentNullException( "s" ); #else throw new ArgumentNullException(); #endif } if(index < 0 || index >= s.Length) { #if EXCEPTION_STRINGS throw new ArgumentOutOfRangeException( "index" ); #else throw new ArgumentOutOfRangeException(); #endif } if(index + 1 < s.Length) { return (IsSurrogatePair( s[index], s[index + 1] )); } return false; } public static bool IsSurrogatePair( char highSurrogate, char lowSurrogate ) { return ((highSurrogate >= CharUnicodeInfo.HIGH_SURROGATE_START && highSurrogate <= CharUnicodeInfo.HIGH_SURROGATE_END) && (lowSurrogate >= CharUnicodeInfo.LOW_SURROGATE_START && lowSurrogate <= CharUnicodeInfo.LOW_SURROGATE_END ) ); } internal const int UNICODE_PLANE00_END = 0x00FFFF; internal const int UNICODE_PLANE01_START = 0x010000; // The starting codepoint for Unicode plane 1. Plane 1 contains 0x010000 ~ 0x01ffff. internal const int UNICODE_PLANE16_END = 0x10FFFF; // The end codepoint for Unicode plane 16. Plane 16 contains 0x100000 ~ 0x10ffff. This is the maximum code point value allowed for Unicode. internal const int HIGH_SURROGATE_START = 0x00D800; internal const int LOW_SURROGATE_END = 0x00DFFF; //// /*================================= ConvertFromUtf32 ============================ //// ** Convert an UTF32 value into a surrogate pair. //// ==============================================================================*/ //// //// public static String ConvertFromUtf32( int utf32 ) //// { //// // For UTF32 values from U+00D800 ~ U+00DFFF, we should throw. They //// // are considered as irregular code unit sequence, but they are not illegal. //// if((utf32 < 0 || utf32 > UNICODE_PLANE16_END) || (utf32 >= HIGH_SURROGATE_START && utf32 <= LOW_SURROGATE_END)) //// { //// throw new ArgumentOutOfRangeException( "utf32", Environment.GetResourceString( "ArgumentOutOfRange_InvalidUTF32" ) ); //// } //// //// if(utf32 < UNICODE_PLANE01_START) //// { //// // This is a BMP character. //// return (Char.ToString( (char)utf32 )); //// } //// //// // This is a sumplementary character. Convert it to a surrogate pair in UTF-16. //// utf32 -= UNICODE_PLANE01_START; //// char[] surrogate = new char[2]; //// surrogate[0] = (char)((utf32 / 0x400) + (int)CharUnicodeInfo.HIGH_SURROGATE_START); //// surrogate[1] = (char)((utf32 % 0x400) + (int)CharUnicodeInfo.LOW_SURROGATE_START ); //// return (new String( surrogate )); //// } /*=============================ConvertToUtf32=================================== ** Convert a surrogate pair to UTF32 value ==============================================================================*/ public static int ConvertToUtf32( char highSurrogate, char lowSurrogate ) { if(!IsHighSurrogate( highSurrogate )) { #if EXCEPTION_STRINGS throw new ArgumentOutOfRangeException( "highSurrogate", Environment.GetResourceString( "ArgumentOutOfRange_InvalidHighSurrogate" ) ); #else throw new ArgumentOutOfRangeException(); #endif } if(!IsLowSurrogate( lowSurrogate )) { #if EXCEPTION_STRINGS throw new ArgumentOutOfRangeException( "lowSurrogate", Environment.GetResourceString( "ArgumentOutOfRange_InvalidLowSurrogate" ) ); #else throw new ArgumentOutOfRangeException(); #endif } return (((highSurrogate - CharUnicodeInfo.HIGH_SURROGATE_START) * 0x400) + (lowSurrogate - CharUnicodeInfo.LOW_SURROGATE_START) + UNICODE_PLANE01_START); } /*=============================ConvertToUtf32=================================== ** Convert a character or a surrogate pair starting at index of the specified string ** to UTF32 value. ** The char pointed by index should be a surrogate pair or a BMP character. ** This method throws if a high-surrogate is not followed by a low surrogate. ** This method throws if a low surrogate is seen without preceding a high-surrogate. ==============================================================================*/ public static int ConvertToUtf32( String s, int index ) { if(s == null) { #if EXCEPTION_STRINGS throw new ArgumentNullException( "s" ); #else throw new ArgumentNullException(); #endif } if(index < 0 || index >= s.Length) { #if EXCEPTION_STRINGS throw new ArgumentOutOfRangeException( "index", Environment.GetResourceString( "ArgumentOutOfRange_Index" ) ); #else throw new ArgumentOutOfRangeException(); #endif } // Check if the character at index is a high surrogate. int temp1 = (int)s[index] - CharUnicodeInfo.HIGH_SURROGATE_START; if(temp1 >= 0 && temp1 <= 0x7ff) { // Found a surrogate char. if(temp1 <= 0x3ff) { // Found a high surrogate. if(index < s.Length - 1) { int temp2 = (int)s[index + 1] - CharUnicodeInfo.LOW_SURROGATE_START; if(temp2 >= 0 && temp2 <= 0x3ff) { // Found a low surrogate. return ((temp1 * 0x400) + temp2 + UNICODE_PLANE01_START); } else { #if EXCEPTION_STRINGS throw new ArgumentException( Environment.GetResourceString( "Argument_InvalidHighSurrogate", index ), "s" ); #else throw new ArgumentException(); #endif } } else { // Found a high surrogate at the end of the string. #if EXCEPTION_STRINGS throw new ArgumentException( Environment.GetResourceString( "Argument_InvalidHighSurrogate", index ), "s" ); #else throw new ArgumentException(); #endif } } else { // Find a low surrogate at the character pointed by index. #if EXCEPTION_STRINGS throw new ArgumentException( Environment.GetResourceString( "Argument_InvalidLowSurrogate", index ), "s" ); #else throw new ArgumentException(); #endif } } // Not a high-surrogate or low-surrogate. Genereate the UTF32 value for the BMP characters. return ((int)s[index]); } } } ================================================ FILE: Zelig/Zelig/RunTime/Framework/mscorlib/System/CharEnumerator.cs ================================================ // ==++== // // Copyright (c) Microsoft Corporation. All rights reserved. // // ==--== /*============================================================ ** ** Class: CharEnumerator ** ** ** Purpose: Enumerates the characters on a string. skips range ** checks. ** ** ============================================================*/ namespace System { using System.Collections; using System.Collections.Generic; [Serializable] public sealed class CharEnumerator : IEnumerator, ICloneable, IEnumerator { private String m_str; private int m_index; private char m_currentElement; internal CharEnumerator( String str ) { m_str = str; m_index = -1; } public Object Clone() { return MemberwiseClone(); } public bool MoveNext() { if(m_index < (m_str.Length - 1)) { m_index++; m_currentElement = m_str[m_index]; return true; } else { m_index = m_str.Length; } return false; } void IDisposable.Dispose() { } /// Object IEnumerator.Current { get { if(m_index == -1) { #if EXCEPTION_STRINGS throw new InvalidOperationException( Environment.GetResourceString( "InvalidOperation_EnumNotStarted" ) ); #else throw new InvalidOperationException(); #endif } if(m_index >= m_str.Length) { #if EXCEPTION_STRINGS throw new InvalidOperationException( Environment.GetResourceString( "InvalidOperation_EnumEnded" ) ); #else throw new InvalidOperationException(); #endif } return m_currentElement; } } public char Current { get { if(m_index == -1) { #if EXCEPTION_STRINGS throw new InvalidOperationException( Environment.GetResourceString( "InvalidOperation_EnumNotStarted" ) ); #else throw new InvalidOperationException(); #endif } if(m_index >= m_str.Length) { #if EXCEPTION_STRINGS throw new InvalidOperationException( Environment.GetResourceString( "InvalidOperation_EnumEnded" ) ); #else throw new InvalidOperationException(); #endif } return m_currentElement; } } public void Reset() { m_currentElement = (char)0; m_index = -1; } } } ================================================ FILE: Zelig/Zelig/RunTime/Framework/mscorlib/System/Collections/ArrayList.cs ================================================ // ==++== // // Copyright (c) Microsoft Corporation. All rights reserved. // // ==--== /*============================================================ ** ** Class: ArrayList ** ** ** Purpose: Implements a dynamically sized List as an array, ** and provides many convenience methods for treating ** an array as an IList. ** ** ===========================================================*/ namespace System.Collections { using System; ////using System.Security.Permissions; using System.Diagnostics; using System.Runtime.Serialization; // Implements a variable-size List that uses an array of objects to store the // elements. A ArrayList has a capacity, which is the allocated length // of the internal array. As elements are added to a ArrayList, the capacity // of the ArrayList is automatically increased as required by reallocating the // internal array. // ////[DebuggerTypeProxy( typeof( System.Collections.ArrayList.ArrayListDebugView ) )] ////[DebuggerDisplay( "Count = {Count}" )] [Serializable] public class ArrayList : IList, ICloneable { private const int cDefaultCapacity = 4; private static readonly Object[] emptyArray = new Object[0]; private Object[] m_items; private int m_size; private int m_version; [NonSerialized] private Object m_syncRoot; // Note: this constructor is a bogus constructor that does nothing // and is for use only with SyncArrayList. internal ArrayList( bool trash ) { } // Constructs a ArrayList. The list is initially empty and has a capacity // of zero. Upon adding the first element to the list the capacity is // increased to cDefaultCapacity, and then increased in multiples of two as required. public ArrayList() { m_items = emptyArray; } // Constructs a ArrayList with a given initial capacity. The list is // initially empty, but will have room for the given number of elements // before any reallocations are required. // public ArrayList( int capacity ) { if(capacity < 0) { #if EXCEPTION_STRINGS throw new ArgumentOutOfRangeException( "capacity", Environment.GetResourceString( "ArgumentOutOfRange_MustBeNonNegNum", "capacity" ) ); #else throw new ArgumentOutOfRangeException(); #endif } m_items = new Object[capacity]; } // Constructs a ArrayList, copying the contents of the given collection. The // size and capacity of the new list will both be equal to the size of the // given collection. // public ArrayList( ICollection c ) { if(c == null) { #if EXCEPTION_STRINGS throw new ArgumentNullException( "c", Environment.GetResourceString( "ArgumentNull_Collection" ) ); #else throw new ArgumentNullException(); #endif } m_items = new Object[c.Count]; AddRange( c ); } // Gets and sets the capacity of this list. The capacity is the size of // the internal array used to hold items. When set, the internal // array of the list is reallocated to the given capacity. // public virtual int Capacity { get { return m_items.Length; } set { // We don't want to update the version number when we change the capacity. // Some existing applications have dependency on this. if(value != m_items.Length) { if(value < m_size) { #if EXCEPTION_STRINGS throw new ArgumentOutOfRangeException( "value", Environment.GetResourceString( "ArgumentOutOfRange_SmallCapacity" ) ); #else throw new ArgumentOutOfRangeException(); #endif } if(value > 0) { Object[] newItems = new Object[value]; if(m_size > 0) { Array.Copy( m_items, 0, newItems, 0, m_size ); } m_items = newItems; } else { m_items = new Object[cDefaultCapacity]; } } } } // Read-only property describing how many elements are in the List. public virtual int Count { get { return m_size; } } public virtual bool IsFixedSize { get { return false; } } // Is this ArrayList read-only? public virtual bool IsReadOnly { get { return false; } } // Is this ArrayList synchronized (thread-safe)? public virtual bool IsSynchronized { get { return false; } } // Synchronization root for this object. public virtual Object SyncRoot { get { if(m_syncRoot == null) { System.Threading.Interlocked.CompareExchange( ref m_syncRoot, new Object(), null ); } return m_syncRoot; } } // Sets or Gets the element at the given index. // public virtual Object this[int index] { get { if(index < 0 || index >= m_size) { #if EXCEPTION_STRINGS throw new ArgumentOutOfRangeException( "index", Environment.GetResourceString( "ArgumentOutOfRange_Index" ) ); #else throw new ArgumentOutOfRangeException(); #endif } return m_items[index]; } set { if(index < 0 || index >= m_size) { #if EXCEPTION_STRINGS throw new ArgumentOutOfRangeException( "index", Environment.GetResourceString( "ArgumentOutOfRange_Index" ) ); #else throw new ArgumentOutOfRangeException(); #endif } m_items[index] = value; m_version++; } } //// // Creates a ArrayList wrapper for a particular IList. This does not //// // copy the contents of the IList, but only wraps the ILIst. So any //// // changes to the underlying list will affect the ArrayList. This would //// // be useful if you want to Reverse a subrange of an IList, or want to //// // use a generic BinarySearch or Sort method without implementing one yourself. //// // However, since these methods are generic, the performance may not be //// // nearly as good for some operations as they would be on the IList itself. //// // //// public static ArrayList Adapter( IList list ) //// { //// if(list == null) //// { //// throw new ArgumentNullException( "list" ); //// } //// //// return new IListWrapper( list ); //// } // Adds the given object to the end of this list. The size of the list is // increased by one. If required, the capacity of the list is doubled // before adding the new element. // public virtual int Add( Object value ) { if(m_size == m_items.Length) { EnsureCapacity( m_size + 1 ); } m_items[m_size] = value; m_version++; return m_size++; } // Adds the elements of the given collection to the end of this list. If // required, the capacity of the list is increased to twice the previous // capacity or the new size, whichever is larger. // public virtual void AddRange( ICollection c ) { InsertRange( m_size, c ); } // Searches a section of the list for a given element using a binary search // algorithm. Elements of the list are compared to the search value using // the given IComparer interface. If comparer is null, elements of // the list are compared to the search value using the IComparable // interface, which in that case must be implemented by all elements of the // list and the given search value. This method assumes that the given // section of the list is already sorted; if this is not the case, the // result will be incorrect. // // The method returns the index of the given value in the list. If the // list does not contain the given value, the method returns a negative // integer. The bitwise complement operator (~) can be applied to a // negative result to produce the index of the first element (if any) that // is larger than the given search value. This is also the index at which // the search value should be inserted into the list in order for the list // to remain sorted. // // The method uses the Array.BinarySearch method to perform the // search. // public virtual int BinarySearch( int index, int count, Object value, IComparer comparer ) { if(index < 0 || count < 0) { #if EXCEPTION_STRINGS throw new ArgumentOutOfRangeException( (index < 0 ? "index" : "count"), Environment.GetResourceString( "ArgumentOutOfRange_NeedNonNegNum" ) ); #else throw new ArgumentOutOfRangeException(); #endif } if(m_size - index < count) { #if EXCEPTION_STRINGS throw new ArgumentException( Environment.GetResourceString( "Argument_InvalidOffLen" ) ); #else throw new ArgumentException(); #endif } return Array.BinarySearch( (Array)m_items, index, count, value, comparer ); } public virtual int BinarySearch( Object value ) { return BinarySearch( 0, Count, value, null ); } public virtual int BinarySearch( Object value, IComparer comparer ) { return BinarySearch( 0, Count, value, comparer ); } // Clears the contents of ArrayList. public virtual void Clear() { if(m_size > 0) { Array.Clear( m_items, 0, m_size ); // Don't need to doc this but we clear the elements so that the gc can reclaim the references. m_size = 0; } m_version++; } // Clones this ArrayList, doing a shallow copy. (A copy is made of all // Object references in the ArrayList, but the Objects pointed to // are not cloned). public virtual Object Clone() { ArrayList la = new ArrayList( m_size ); la.m_size = m_size; la.m_version = m_version; Array.Copy( m_items, 0, la.m_items, 0, m_size ); return la; } // Contains returns true if the specified element is in the ArrayList. // It does a linear, O(n) search. Equality is determined by calling // item.Equals(). // public virtual bool Contains( Object item ) { if(item == null) { for(int i = 0; i < m_size; i++) { if(m_items[i] == null) { return true; } } return false; } else { for(int i = 0; i < m_size; i++) { if((m_items[i] != null) && (m_items[i].Equals( item ))) { return true; } } return false; } } // Copies this ArrayList into array, which must be of a // compatible array type. // public virtual void CopyTo( Array array ) { CopyTo( array, 0 ); } // Copies this ArrayList into array, which must be of a // compatible array type. // public virtual void CopyTo( Array array, int arrayIndex ) { if((array != null) && (array.Rank != 1)) { #if EXCEPTION_STRINGS throw new ArgumentException( Environment.GetResourceString( "Arg_RankMultiDimNotSupported" ) ); #else throw new ArgumentException(); #endif } // Delegate rest of error checking to Array.Copy. Array.Copy( m_items, 0, array, arrayIndex, m_size ); } // Copies a section of this list to the given array at the given index. // // The method uses the Array.Copy method to copy the elements. // public virtual void CopyTo( int index, Array array, int arrayIndex, int count ) { if(m_size - index < count) { #if EXCEPTION_STRINGS throw new ArgumentException( Environment.GetResourceString( "Argument_InvalidOffLen" ) ); #else throw new ArgumentException(); #endif } if((array != null) && (array.Rank != 1)) { #if EXCEPTION_STRINGS throw new ArgumentException( Environment.GetResourceString( "Arg_RankMultiDimNotSupported" ) ); #else throw new ArgumentException(); #endif } // Delegate rest of error checking to Array.Copy. Array.Copy( m_items, index, array, arrayIndex, count ); } // Ensures that the capacity of this list is at least the given minimum // value. If the currect capacity of the list is less than min, the // capacity is increased to twice the current capacity or to min, // whichever is larger. private void EnsureCapacity( int min ) { if(m_items.Length < min) { int newCapacity = m_items.Length == 0 ? cDefaultCapacity : m_items.Length * 2; if(newCapacity < min) newCapacity = min; Capacity = newCapacity; } } //// // Returns a list wrapper that is fixed at the current size. Operations //// // that add or remove items will fail, however, replacing items is allowed. //// // //// public static IList FixedSize( IList list ) //// { //// if(list == null) //// { //// throw new ArgumentNullException( "list" ); //// } //// //// return new FixedSizeList( list ); //// } //// // Returns a list wrapper that is fixed at the current size. Operations //// // that add or remove items will fail, however, replacing items is allowed. //// // //// public static ArrayList FixedSize( ArrayList list ) //// { //// if(list == null) //// { //// throw new ArgumentNullException( "list" ); //// } //// //// return new FixedSizeArrayList( list ); //// } // Returns an enumerator for this list with the given // permission for removal of elements. If modifications made to the list // while an enumeration is in progress, the MoveNext and // GetObject methods of the enumerator will throw an exception. // public virtual IEnumerator GetEnumerator() { return new ArrayListEnumeratorSimple( this ); } // Returns an enumerator for a section of this list with the given // permission for removal of elements. If modifications made to the list // while an enumeration is in progress, the MoveNext and // GetObject methods of the enumerator will throw an exception. // public virtual IEnumerator GetEnumerator( int index, int count ) { if(index < 0 || count < 0) { #if EXCEPTION_STRINGS throw new ArgumentOutOfRangeException( (index < 0 ? "index" : "count"), Environment.GetResourceString( "ArgumentOutOfRange_NeedNonNegNum" ) ); #else throw new ArgumentOutOfRangeException(); #endif } if(m_size - index < count) { #if EXCEPTION_STRINGS throw new ArgumentException( Environment.GetResourceString( "Argument_InvalidOffLen" ) ); #else throw new ArgumentException(); #endif } return new ArrayListEnumerator( this, index, count ); } // Returns the index of the first occurrence of a given value in a range of // this list. The list is searched forwards from beginning to end. // The elements of the list are compared to the given value using the // Object.Equals method. // // This method uses the Array.IndexOf method to perform the // search. // public virtual int IndexOf( Object value ) { return Array.IndexOf( (Array)m_items, value, 0, m_size ); } // Returns the index of the first occurrence of a given value in a range of // this list. The list is searched forwards, starting at index // startIndex and ending at count number of elements. The // elements of the list are compared to the given value using the // Object.Equals method. // // This method uses the Array.IndexOf method to perform the // search. // public virtual int IndexOf( Object value, int startIndex ) { if(startIndex > m_size) { #if EXCEPTION_STRINGS throw new ArgumentOutOfRangeException( "startIndex", Environment.GetResourceString( "ArgumentOutOfRange_Index" ) ); #else throw new ArgumentOutOfRangeException(); #endif } return Array.IndexOf( (Array)m_items, value, startIndex, m_size - startIndex ); } // Returns the index of the first occurrence of a given value in a range of // this list. The list is searched forwards, starting at index // startIndex and upto count number of elements. The // elements of the list are compared to the given value using the // Object.Equals method. // // This method uses the Array.IndexOf method to perform the // search. // public virtual int IndexOf( Object value, int startIndex, int count ) { if(startIndex > m_size) { #if EXCEPTION_STRINGS throw new ArgumentOutOfRangeException( "startIndex", Environment.GetResourceString( "ArgumentOutOfRange_Index" ) ); #else throw new ArgumentOutOfRangeException(); #endif } if(count < 0 || startIndex > m_size - count) { #if EXCEPTION_STRINGS throw new ArgumentOutOfRangeException( "count", Environment.GetResourceString( "ArgumentOutOfRange_Count" ) ); #else throw new ArgumentOutOfRangeException(); #endif } return Array.IndexOf( (Array)m_items, value, startIndex, count ); } // Inserts an element into this list at a given index. The size of the list // is increased by one. If required, the capacity of the list is doubled // before inserting the new element. // public virtual void Insert( int index, Object value ) { // Note that insertions at the end are legal. if(index < 0 || index > m_size) { #if EXCEPTION_STRINGS throw new ArgumentOutOfRangeException( "index", Environment.GetResourceString( "ArgumentOutOfRange_ArrayListInsert" ) ); #else throw new ArgumentOutOfRangeException(); #endif } if(m_size == m_items.Length) EnsureCapacity( m_size + 1 ); if(index < m_size) { Array.Copy( m_items, index, m_items, index + 1, m_size - index ); } m_items[index] = value; m_size++; m_version++; } // Inserts the elements of the given collection at a given index. If // required, the capacity of the list is increased to twice the previous // capacity or the new size, whichever is larger. Ranges may be added // to the end of the list by setting index to the ArrayList's size. // public virtual void InsertRange( int index, ICollection c ) { if(c == null) { #if EXCEPTION_STRINGS throw new ArgumentNullException( "c", Environment.GetResourceString( "ArgumentNull_Collection" ) ); #else throw new ArgumentNullException(); #endif } if(index < 0 || index > m_size) { #if EXCEPTION_STRINGS throw new ArgumentOutOfRangeException( "index", Environment.GetResourceString( "ArgumentOutOfRange_Index" ) ); #else throw new ArgumentOutOfRangeException(); #endif } int count = c.Count; if(count > 0) { EnsureCapacity( m_size + count ); // shift existing items if(index < m_size) { Array.Copy( m_items, index, m_items, index + count, m_size - index ); } Object[] itemsToInsert = new Object[count]; c.CopyTo( itemsToInsert, 0 ); itemsToInsert.CopyTo( m_items, index ); m_size += count; m_version++; } } // Returns the index of the last occurrence of a given value in a range of // this list. The list is searched backwards, starting at the end // and ending at the first element in the list. The elements of the list // are compared to the given value using the Object.Equals method. // // This method uses the Array.LastIndexOf method to perform the // search. // public virtual int LastIndexOf( Object value ) { return LastIndexOf( value, m_size - 1, m_size ); } // Returns the index of the last occurrence of a given value in a range of // this list. The list is searched backwards, starting at index // startIndex and ending at the first element in the list. The // elements of the list are compared to the given value using the // Object.Equals method. // // This method uses the Array.LastIndexOf method to perform the // search. // public virtual int LastIndexOf( Object value, int startIndex ) { if(startIndex >= m_size) { #if EXCEPTION_STRINGS throw new ArgumentOutOfRangeException( "startIndex", Environment.GetResourceString( "ArgumentOutOfRange_Index" ) ); #else throw new ArgumentOutOfRangeException(); #endif } return LastIndexOf( value, startIndex, startIndex + 1 ); } // Returns the index of the last occurrence of a given value in a range of // this list. The list is searched backwards, starting at index // startIndex and upto count elements. The elements of // the list are compared to the given value using the Object.Equals // method. // // This method uses the Array.LastIndexOf method to perform the // search. // public virtual int LastIndexOf( Object value, int startIndex, int count ) { if(m_size == 0) { return -1; } if(startIndex < 0 || count < 0) { #if EXCEPTION_STRINGS throw new ArgumentOutOfRangeException( (startIndex < 0 ? "startIndex" : "count"), Environment.GetResourceString( "ArgumentOutOfRange_NeedNonNegNum" ) ); #else throw new ArgumentOutOfRangeException(); #endif } if(startIndex >= m_size || count > startIndex + 1) { #if EXCEPTION_STRINGS throw new ArgumentOutOfRangeException( (startIndex >= m_size ? "startIndex" : "count"), Environment.GetResourceString( "ArgumentOutOfRange_BiggerThanCollection" ) ); #else throw new ArgumentOutOfRangeException(); #endif } return Array.LastIndexOf( (Array)m_items, value, startIndex, count ); } //// // Returns a read-only IList wrapper for the given IList. //// // //// public static IList ReadOnly( IList list ) //// { //// if(list == null) //// { //// throw new ArgumentNullException( "list" ); //// } //// //// return new ReadOnlyList( list ); //// } //// // Returns a read-only ArrayList wrapper for the given ArrayList. //// // //// public static ArrayList ReadOnly( ArrayList list ) //// { //// if(list == null) //// { //// throw new ArgumentNullException( "list" ); //// } //// //// return new ReadOnlyArrayList( list ); //// } // Removes the element at the given index. The size of the list is // decreased by one. // public virtual void Remove( Object obj ) { int index = IndexOf( obj ); BCLDebug.Correctness( index >= 0 || !(obj is Int32), "You passed an Int32 to Remove that wasn't in the ArrayList.\r\nDid you mean RemoveAt? int: " + obj + " Count: " + Count ); if(index >= 0) { RemoveAt( index ); } } // Removes the element at the given index. The size of the list is // decreased by one. // public virtual void RemoveAt( int index ) { if(index < 0 || index >= m_size) { #if EXCEPTION_STRINGS throw new ArgumentOutOfRangeException( "index", Environment.GetResourceString( "ArgumentOutOfRange_Index" ) ); #else throw new ArgumentOutOfRangeException(); #endif } m_size--; if(index < m_size) { Array.Copy( m_items, index + 1, m_items, index, m_size - index ); } m_items[m_size] = null; m_version++; } // Removes a range of elements from this list. // public virtual void RemoveRange( int index, int count ) { if(index < 0 || count < 0) { #if EXCEPTION_STRINGS throw new ArgumentOutOfRangeException( (index < 0 ? "index" : "count"), Environment.GetResourceString( "ArgumentOutOfRange_NeedNonNegNum" ) ); #else throw new ArgumentOutOfRangeException(); #endif } if(m_size - index < count) { #if EXCEPTION_STRINGS throw new ArgumentException( Environment.GetResourceString( "Argument_InvalidOffLen" ) ); #else throw new ArgumentException(); #endif } if(count > 0) { int i = m_size; m_size -= count; if(index < m_size) { Array.Copy( m_items, index + count, m_items, index, m_size - index ); } while(i > m_size) { m_items[--i] = null; } m_version++; } } // Returns an IList that contains count copies of value. // public static ArrayList Repeat( Object value, int count ) { if(count < 0) { #if EXCEPTION_STRINGS throw new ArgumentOutOfRangeException( "count", Environment.GetResourceString( "ArgumentOutOfRange_NeedNonNegNum" ) ); #else throw new ArgumentOutOfRangeException(); #endif } ArrayList list = new ArrayList( (count > cDefaultCapacity) ? count : cDefaultCapacity ); for(int i = 0; i < count; i++) { list.Add( value ); } return list; } // Reverses the elements in this list. public virtual void Reverse() { Reverse( 0, Count ); } // Reverses the elements in a range of this list. Following a call to this // method, an element in the range given by index and count // which was previously located at index i will now be located at // index index + (index + count - i - 1). // // This method uses the Array.Reverse method to reverse the // elements. // public virtual void Reverse( int index, int count ) { if(index < 0 || count < 0) { #if EXCEPTION_STRINGS throw new ArgumentOutOfRangeException( (index < 0 ? "index" : "count"), Environment.GetResourceString( "ArgumentOutOfRange_NeedNonNegNum" ) ); #else throw new ArgumentOutOfRangeException(); #endif } if(m_size - index < count) { #if EXCEPTION_STRINGS throw new ArgumentException( Environment.GetResourceString( "Argument_InvalidOffLen" ) ); #else throw new ArgumentException(); #endif } Array.Reverse( m_items, index, count ); m_version++; } // Sets the elements starting at the given index to the elements of the // given collection. // public virtual void SetRange( int index, ICollection c ) { if(c == null) { #if EXCEPTION_STRINGS throw new ArgumentNullException( "c", Environment.GetResourceString( "ArgumentNull_Collection" ) ); #else throw new ArgumentNullException(); #endif } int count = c.Count; if(index < 0 || index > m_size - count) { #if EXCEPTION_STRINGS throw new ArgumentOutOfRangeException( "index", Environment.GetResourceString( "ArgumentOutOfRange_Index" ) ); #else throw new ArgumentOutOfRangeException(); #endif } if(count > 0) { c.CopyTo( m_items, index ); m_version++; } } //// public virtual ArrayList GetRange( int index, int count ) //// { //// if(index < 0 || count < 0) //// { //// throw new ArgumentOutOfRangeException( (index < 0 ? "index" : "count"), Environment.GetResourceString( "ArgumentOutOfRange_NeedNonNegNum" ) ); //// } //// //// if(m_size - index < count) //// { //// throw new ArgumentException( Environment.GetResourceString( "Argument_InvalidOffLen" ) ); //// } //// //// return new Range( this, index, count ); //// } // Sorts the elements in this list. Uses the default comparer and // Array.Sort. public virtual void Sort() { Sort( 0, Count, Comparer.Default ); } // Sorts the elements in this list. Uses Array.Sort with the // provided comparer. public virtual void Sort( IComparer comparer ) { Sort( 0, Count, comparer ); } // Sorts the elements in a section of this list. The sort compares the // elements to each other using the given IComparer interface. If // comparer is null, the elements are compared to each other using // the IComparable interface, which in that case must be implemented by all // elements of the list. // // This method uses the Array.Sort method to sort the elements. // public virtual void Sort( int index, int count, IComparer comparer ) { if(index < 0 || count < 0) { #if EXCEPTION_STRINGS throw new ArgumentOutOfRangeException( (index < 0 ? "index" : "count"), Environment.GetResourceString( "ArgumentOutOfRange_NeedNonNegNum" ) ); #else throw new ArgumentOutOfRangeException(); #endif } if(m_size - index < count) { #if EXCEPTION_STRINGS throw new ArgumentException( Environment.GetResourceString( "Argument_InvalidOffLen" ) ); #else throw new ArgumentException(); #endif } Array.Sort( m_items, index, count, comparer ); m_version++; } //// // Returns a thread-safe wrapper around an IList. //// // //// [HostProtection( Synchronization = true )] //// public static IList Synchronized( IList list ) //// { //// if(list == null) //// { //// throw new ArgumentNullException( "list" ); //// } //// //// return new SyncIList( list ); //// } //// // Returns a thread-safe wrapper around a ArrayList. //// // //// [HostProtection( Synchronization = true )] //// public static ArrayList Synchronized( ArrayList list ) //// { //// if(list == null) //// { //// throw new ArgumentNullException( "list" ); //// } //// //// return new SyncArrayList( list ); //// } // ToArray returns a new Object array containing the contents of the ArrayList. // This requires copying the ArrayList, which is an O(n) operation. public virtual Object[] ToArray() { Object[] array = new Object[m_size]; Array.Copy( m_items, 0, array, 0, m_size ); return array; } // ToArray returns a new array of a particular type containing the contents // of the ArrayList. This requires copying the ArrayList and potentially // downcasting all elements. This copy may fail and is an O(n) operation. // Internally, this implementation calls Array.Copy. // public virtual Array ToArray( Type type ) { if(type == null) { #if EXCEPTION_STRINGS throw new ArgumentNullException( "type" ); #else throw new ArgumentNullException(); #endif } Array array = Array.CreateInstance( type, m_size ); Array.Copy( m_items, 0, array, 0, m_size ); return array; } // Sets the capacity of this list to the size of the list. This method can // be used to minimize a list's memory overhead once it is known that no // new elements will be added to the list. To completely clear a list and // release all memory referenced by the list, execute the following // statements: // // list.Clear(); // list.TrimToSize(); // public virtual void TrimToSize() { Capacity = m_size; } #region Commented IListWrapper //// // This class wraps an IList, exposing it as a ArrayList //// // Note this requires reimplementing half of ArrayList... //// [Serializable] //// private class IListWrapper : ArrayList //// { //// private IList m_list; //// //// internal IListWrapper( IList list ) //// { //// m_list = list; //// m_version = 0; // list doesn't not contain a version number //// } //// //// public override int Capacity //// { //// get //// { //// return m_list.Count; //// //// } //// //// set //// { //// if(value < m_list.Count) //// { //// throw new ArgumentOutOfRangeException( "value", Environment.GetResourceString( "ArgumentOutOfRange_SmallCapacity" ) ); //// } //// } //// } //// //// public override int Count //// { //// get //// { //// return m_list.Count; //// } //// } //// //// public override bool IsReadOnly //// { //// get //// { //// return m_list.IsReadOnly; //// } //// } //// //// public override bool IsFixedSize //// { //// get //// { //// return m_list.IsFixedSize; //// } //// } //// //// //// public override bool IsSynchronized //// { //// get //// { //// return m_list.IsSynchronized; //// } //// } //// //// public override Object this[int index] //// { //// get //// { //// return m_list[index]; //// } //// //// set //// { //// m_list[index] = value; //// m_version++; //// } //// } //// //// public override Object SyncRoot //// { //// get //// { //// return m_list.SyncRoot; //// } //// } //// //// public override int Add( Object obj ) //// { //// int i = m_list.Add( obj ); //// //// m_version++; //// //// return i; //// } //// //// public override void AddRange( ICollection c ) //// { //// InsertRange( Count, c ); //// } //// //// // Other overloads with automatically work //// public override int BinarySearch( int index, int count, Object value, IComparer comparer ) //// { //// if(index < 0 || count < 0) //// { //// throw new ArgumentOutOfRangeException( (index < 0 ? "index" : "count"), Environment.GetResourceString( "ArgumentOutOfRange_NeedNonNegNum" ) ); //// } //// //// if(m_list.Count - index < count) //// { //// throw new ArgumentException( Environment.GetResourceString( "Argument_InvalidOffLen" ) ); //// } //// //// if(comparer == null) //// { //// comparer = Comparer.Default; //// } //// //// int lo = index; //// int hi = index + count - 1; //// int mid; //// while(lo <= hi) //// { //// mid = (lo + hi) / 2; //// int r = comparer.Compare( value, m_list[mid] ); //// if(r == 0) //// { //// return mid; //// } //// //// if(r < 0) //// { //// hi = mid - 1; //// } //// else //// { //// lo = mid + 1; //// } //// } //// //// // return bitwise complement of the first element greater than value. //// // Since hi is less than lo now, ~lo is the correct item. //// return ~lo; //// } //// //// public override void Clear() //// { //// // If _list is an array, it will support Clear method. //// // We shouldn't allow clear operation on a FixedSized ArrayList //// if(m_list.IsFixedSize) //// { //// throw new NotSupportedException( Environment.GetResourceString( "NotSupported_FixedSizeCollection" ) ); //// } //// //// m_list.Clear(); //// m_version++; //// } //// //// public override Object Clone() //// { //// // This does not do a shallow copy of _list into a ArrayList! //// // This clones the IListWrapper, creating another wrapper class! //// return new IListWrapper( m_list ); //// } //// //// public override bool Contains( Object obj ) //// { //// return m_list.Contains( obj ); //// } //// //// public override void CopyTo( Array array, int index ) //// { //// m_list.CopyTo( array, index ); //// } //// //// public override void CopyTo( int index, Array array, int arrayIndex, int count ) //// { //// if(array == null) //// { //// throw new ArgumentNullException( "array" ); //// } //// //// if(index < 0 || arrayIndex < 0) //// { //// throw new ArgumentOutOfRangeException( (index < 0) ? "index" : "arrayIndex", Environment.GetResourceString( "ArgumentOutOfRange_NeedNonNegNum" ) ); //// } //// //// if(count < 0) //// { //// throw new ArgumentOutOfRangeException( "count", Environment.GetResourceString( "ArgumentOutOfRange_NeedNonNegNum" ) ); //// } //// //// if(array.Length - arrayIndex < count) //// { //// throw new ArgumentException( Environment.GetResourceString( "Argument_InvalidOffLen" ) ); //// } //// //// if(m_list.Count - index < count) //// { //// throw new ArgumentException( Environment.GetResourceString( "Argument_InvalidOffLen" ) ); //// } //// //// if(array.Rank != 1) //// { //// throw new ArgumentException( Environment.GetResourceString( "Arg_RankMultiDimNotSupported" ) ); //// } //// //// for(int i = index; i < index + count; i++) //// { //// array.SetValue( m_list[i], arrayIndex++ ); //// } //// } //// //// public override IEnumerator GetEnumerator() //// { //// return m_list.GetEnumerator(); //// } //// //// public override IEnumerator GetEnumerator( int index, int count ) //// { //// if(index < 0 || count < 0) //// { //// throw new ArgumentOutOfRangeException( (index < 0 ? "index" : "count"), Environment.GetResourceString( "ArgumentOutOfRange_NeedNonNegNum" ) ); //// } //// //// if(m_list.Count - index < count) //// { //// throw new ArgumentException( Environment.GetResourceString( "Argument_InvalidOffLen" ) ); //// } //// //// return new IListWrapperEnumWrapper( this, index, count ); //// } //// //// public override int IndexOf( Object value ) //// { //// return m_list.IndexOf( value ); //// } //// //// public override int IndexOf( Object value, int startIndex ) //// { //// return IndexOf( value, startIndex, m_list.Count - startIndex ); //// } //// //// public override int IndexOf( Object value, int startIndex, int count ) //// { //// if(startIndex < 0 || startIndex > m_list.Count) //// { //// throw new ArgumentOutOfRangeException( "startIndex", Environment.GetResourceString( "ArgumentOutOfRange_Index" ) ); //// } //// //// if(count < 0 || startIndex > m_list.Count - count) //// { //// throw new ArgumentOutOfRangeException( "count", Environment.GetResourceString( "ArgumentOutOfRange_Count" ) ); //// } //// //// int endIndex = startIndex + count; //// if(value == null) //// { //// for(int i = startIndex; i < endIndex; i++) //// { //// if(m_list[i] == null) //// { //// return i; //// } //// } //// //// return -1; //// } //// else //// { //// for(int i = startIndex; i < endIndex; i++) //// { //// if(m_list[i] != null && m_list[i].Equals( value )) //// { //// return i; //// } //// } //// //// return -1; //// } //// } //// //// public override void Insert( int index, Object obj ) //// { //// m_list.Insert( index, obj ); //// m_version++; //// } //// //// public override void InsertRange( int index, ICollection c ) //// { //// if(c == null) //// { //// throw new ArgumentNullException( "c", Environment.GetResourceString( "ArgumentNull_Collection" ) ); //// } //// //// if(index < 0 || index > m_list.Count) //// { //// throw new ArgumentOutOfRangeException( "index", Environment.GetResourceString( "ArgumentOutOfRange_Index" ) ); //// } //// //// if(c.Count > 0) //// { //// ArrayList al = m_list as ArrayList; //// if(al != null) //// { //// // We need to special case ArrayList. //// // When c is a range of _list, we need to handle this in a special way. //// // See ArrayList.InsertRange for details. //// al.InsertRange( index, c ); //// } //// else //// { //// IEnumerator en = c.GetEnumerator(); //// while(en.MoveNext()) //// { //// m_list.Insert( index++, en.Current ); //// } //// } //// //// m_version++; //// } //// } //// //// public override int LastIndexOf( Object value ) //// { //// return LastIndexOf( value, m_list.Count - 1, m_list.Count ); //// } //// //// public override int LastIndexOf( Object value, int startIndex ) //// { //// return LastIndexOf( value, startIndex, startIndex + 1 ); //// } //// //// public override int LastIndexOf( Object value, int startIndex, int count ) //// { //// if(m_list.Count == 0) //// { //// return -1; //// } //// //// if(startIndex < 0 || startIndex >= m_list.Count) //// { //// throw new ArgumentOutOfRangeException( "startIndex", Environment.GetResourceString( "ArgumentOutOfRange_Index" ) ); //// } //// //// if(count < 0 || count > startIndex + 1) //// { //// throw new ArgumentOutOfRangeException( "count", Environment.GetResourceString( "ArgumentOutOfRange_Count" ) ); //// } //// //// int endIndex = startIndex - count + 1; //// if(value == null) //// { //// for(int i = startIndex; i >= endIndex; i--) //// { //// if(m_list[i] == null) //// { //// return i; //// } //// } //// //// return -1; //// } //// else //// { //// for(int i = startIndex; i >= endIndex; i--) //// { //// if(m_list[i] != null && m_list[i].Equals( value )) //// { //// return i; //// } //// } //// //// return -1; //// } //// } //// //// public override void Remove( Object value ) //// { //// int index = IndexOf( value ); //// if(index >= 0) //// { //// RemoveAt( index ); //// } //// } //// //// public override void RemoveAt( int index ) //// { //// m_list.RemoveAt( index ); //// m_version++; //// } //// //// public override void RemoveRange( int index, int count ) //// { //// if(index < 0 || count < 0) //// { //// throw new ArgumentOutOfRangeException( (index < 0 ? "index" : "count"), Environment.GetResourceString( "ArgumentOutOfRange_NeedNonNegNum" ) ); //// } //// //// if(m_list.Count - index < count) //// { //// throw new ArgumentException( Environment.GetResourceString( "Argument_InvalidOffLen" ) ); //// } //// //// if(count > 0) // be consistent with ArrayList //// { //// m_version++; //// } //// //// while(count > 0) //// { //// m_list.RemoveAt( index ); //// count--; //// } //// } //// //// public override void Reverse( int index, int count ) //// { //// if(index < 0 || count < 0) //// { //// throw new ArgumentOutOfRangeException( (index < 0 ? "index" : "count"), Environment.GetResourceString( "ArgumentOutOfRange_NeedNonNegNum" ) ); //// } //// //// if(m_list.Count - index < count) //// { //// throw new ArgumentException( Environment.GetResourceString( "Argument_InvalidOffLen" ) ); //// } //// //// int i = index; //// int j = index + count - 1; //// while(i < j) //// { //// Object tmp = m_list[i]; //// m_list[i++] = m_list[j]; //// m_list[j--] = tmp; //// } //// //// m_version++; //// } //// //// public override void SetRange( int index, ICollection c ) //// { //// if(c == null) //// { //// throw new ArgumentNullException( "c", Environment.GetResourceString( "ArgumentNull_Collection" ) ); //// } //// //// if(index < 0 || index > m_list.Count - c.Count) //// { //// throw new ArgumentOutOfRangeException( "index", Environment.GetResourceString( "ArgumentOutOfRange_Index" ) ); //// } //// //// if(c.Count > 0) //// { //// IEnumerator en = c.GetEnumerator(); //// while(en.MoveNext()) //// { //// m_list[index++] = en.Current; //// } //// //// m_version++; //// } //// } //// //// public override ArrayList GetRange( int index, int count ) //// { //// if(index < 0 || count < 0) //// { //// throw new ArgumentOutOfRangeException( (index < 0 ? "index" : "count"), Environment.GetResourceString( "ArgumentOutOfRange_NeedNonNegNum" ) ); //// } //// //// if(m_list.Count - index < count) //// { //// throw new ArgumentException( Environment.GetResourceString( "Argument_InvalidOffLen" ) ); //// } //// //// return new Range( this, index, count ); //// } //// //// public override void Sort( int index, int count, IComparer comparer ) //// { //// if(index < 0 || count < 0) //// { //// throw new ArgumentOutOfRangeException( (index < 0 ? "index" : "count"), Environment.GetResourceString( "ArgumentOutOfRange_NeedNonNegNum" ) ); //// } //// //// if(m_list.Count - index < count) //// { //// throw new ArgumentException( Environment.GetResourceString( "Argument_InvalidOffLen" ) ); //// } //// //// Object[] array = new Object[count]; //// CopyTo( index, array, 0, count ); //// //// Array.Sort( array, 0, count, comparer ); //// //// for(int i = 0; i < count; i++) //// { //// m_list[i + index] = array[i]; //// } //// //// m_version++; //// } //// //// //// public override Object[] ToArray() //// { //// Object[] array = new Object[Count]; //// //// m_list.CopyTo( array, 0 ); //// //// return array; //// } //// //// public override Array ToArray( Type type ) //// { //// if(type == null) //// { //// throw new ArgumentNullException( "type" ); //// } //// //// Array array = Array.CreateInstance( type, m_list.Count ); //// //// m_list.CopyTo( array, 0 ); //// //// return array; //// } //// //// public override void TrimToSize() //// { //// // Can't really do much here... //// } //// //// // This is the enumerator for an IList that's been wrapped in another //// // class that implements all of ArrayList's methods. //// [Serializable] //// private sealed class IListWrapperEnumWrapper : IEnumerator, ICloneable //// { //// private IEnumerator m_en; //// private int m_remaining; //// private int m_initialStartIndex; // for reset //// private int m_initialCount; // for reset //// private bool m_firstCall; // firstCall to MoveNext //// //// private IListWrapperEnumWrapper() //// { //// } //// //// internal IListWrapperEnumWrapper( IListWrapper listWrapper, int startIndex, int count ) //// { //// m_en = listWrapper.GetEnumerator(); //// m_initialStartIndex = startIndex; //// m_initialCount = count; //// //// while(startIndex-- > 0 && m_en.MoveNext()); //// //// m_remaining = count; //// m_firstCall = true; //// } //// //// public Object Clone() //// { //// // We must clone the underlying enumerator, I think. //// IListWrapperEnumWrapper clone = new IListWrapperEnumWrapper(); //// //// clone.m_en = (IEnumerator)((ICloneable)m_en).Clone(); //// clone.m_initialStartIndex = m_initialStartIndex; //// clone.m_initialCount = m_initialCount; //// clone.m_remaining = m_remaining; //// clone.m_firstCall = m_firstCall; //// //// return clone; //// } //// //// public bool MoveNext() //// { //// if(m_firstCall) //// { //// m_firstCall = false; //// return m_remaining-- > 0 && m_en.MoveNext(); //// } //// //// if(m_remaining < 0) //// { //// return false; //// } //// //// bool r = m_en.MoveNext(); //// //// return r && m_remaining-- > 0; //// } //// //// public Object Current //// { //// get //// { //// if(m_firstCall) //// { //// throw new InvalidOperationException( Environment.GetResourceString( "InvalidOperation_EnumNotStarted" ) ); //// } //// //// if(m_remaining < 0) //// { //// throw new InvalidOperationException( Environment.GetResourceString( "InvalidOperation_EnumEnded" ) ); //// } //// //// return m_en.Current; //// } //// } //// //// public void Reset() //// { //// m_en.Reset(); //// //// int startIndex = m_initialStartIndex; //// while(startIndex-- > 0 && m_en.MoveNext()); //// //// m_remaining = m_initialCount; //// m_firstCall = true; //// } //// } //// } #endregion #region Commented SyncArrayList //// [Serializable] //// private class SyncArrayList : ArrayList //// { //// private ArrayList m_list; //// private Object m_root; //// //// internal SyncArrayList( ArrayList list ) : base( false ) //// { //// m_list = list; //// m_root = list.SyncRoot; //// } //// //// public override int Capacity //// { //// get //// { //// lock(m_root) //// { //// return m_list.Capacity; //// } //// } //// set //// { //// lock(m_root) //// { //// m_list.Capacity = value; //// } //// } //// } //// //// public override int Count //// { //// get //// { //// lock(m_root) //// { //// return m_list.Count; //// } //// } //// } //// //// public override bool IsReadOnly //// { //// get //// { //// return m_list.IsReadOnly; //// } //// } //// //// public override bool IsFixedSize //// { //// get //// { //// return m_list.IsFixedSize; //// } //// } //// //// //// public override bool IsSynchronized //// { //// get //// { //// return true; //// } //// } //// //// public override Object this[int index] //// { //// get //// { //// lock(m_root) //// { //// return m_list[index]; //// } //// } //// set //// { //// lock(m_root) //// { //// m_list[index] = value; //// } //// } //// } //// //// public override Object SyncRoot //// { //// get //// { //// return m_root; //// } //// } //// //// public override int Add( Object value ) //// { //// lock(m_root) //// { //// return m_list.Add( value ); //// } //// } //// //// public override void AddRange( ICollection c ) //// { //// lock(m_root) //// { //// m_list.AddRange( c ); //// } //// } //// //// public override int BinarySearch( Object value ) //// { //// lock(m_root) //// { //// return m_list.BinarySearch( value ); //// } //// } //// //// public override int BinarySearch( Object value, IComparer comparer ) //// { //// lock(m_root) //// { //// return m_list.BinarySearch( value, comparer ); //// } //// } //// //// public override int BinarySearch( int index, int count, Object value, IComparer comparer ) //// { //// lock(m_root) //// { //// return m_list.BinarySearch( index, count, value, comparer ); //// } //// } //// //// public override void Clear() //// { //// lock(m_root) //// { //// m_list.Clear(); //// } //// } //// //// public override Object Clone() //// { //// lock(m_root) //// { //// return new SyncArrayList( (ArrayList)m_list.Clone() ); //// } //// } //// //// public override bool Contains( Object item ) //// { //// lock(m_root) //// { //// return m_list.Contains( item ); //// } //// } //// //// public override void CopyTo( Array array ) //// { //// lock(m_root) //// { //// m_list.CopyTo( array ); //// } //// } //// //// public override void CopyTo( Array array, int index ) //// { //// lock(m_root) //// { //// m_list.CopyTo( array, index ); //// } //// } //// //// public override void CopyTo( int index, Array array, int arrayIndex, int count ) //// { //// lock(m_root) //// { //// m_list.CopyTo( index, array, arrayIndex, count ); //// } //// } //// //// public override IEnumerator GetEnumerator() //// { //// lock(m_root) //// { //// return m_list.GetEnumerator(); //// } //// } //// //// public override IEnumerator GetEnumerator( int index, int count ) //// { //// lock(m_root) //// { //// return m_list.GetEnumerator( index, count ); //// } //// } //// //// public override int IndexOf( Object value ) //// { //// lock(m_root) //// { //// return m_list.IndexOf( value ); //// } //// } //// //// public override int IndexOf( Object value, int startIndex ) //// { //// lock(m_root) //// { //// return m_list.IndexOf( value, startIndex ); //// } //// } //// //// public override int IndexOf( Object value, int startIndex, int count ) //// { //// lock(m_root) //// { //// return m_list.IndexOf( value, startIndex, count ); //// } //// } //// //// public override void Insert( int index, Object value ) //// { //// lock(m_root) //// { //// m_list.Insert( index, value ); //// } //// } //// //// public override void InsertRange( int index, ICollection c ) //// { //// lock(m_root) //// { //// m_list.InsertRange( index, c ); //// } //// } //// //// public override int LastIndexOf( Object value ) //// { //// lock(m_root) //// { //// return m_list.LastIndexOf( value ); //// } //// } //// //// public override int LastIndexOf( Object value, int startIndex ) //// { //// lock(m_root) //// { //// return m_list.LastIndexOf( value, startIndex ); //// } //// } //// //// public override int LastIndexOf( Object value, int startIndex, int count ) //// { //// lock(m_root) //// { //// return m_list.LastIndexOf( value, startIndex, count ); //// } //// } //// //// public override void Remove( Object value ) //// { //// lock(m_root) //// { //// m_list.Remove( value ); //// } //// } //// //// public override void RemoveAt( int index ) //// { //// lock(m_root) //// { //// m_list.RemoveAt( index ); //// } //// } //// //// public override void RemoveRange( int index, int count ) //// { //// lock(m_root) //// { //// m_list.RemoveRange( index, count ); //// } //// } //// //// public override void Reverse( int index, int count ) //// { //// lock(m_root) //// { //// m_list.Reverse( index, count ); //// } //// } //// //// public override void SetRange( int index, ICollection c ) //// { //// lock(m_root) //// { //// m_list.SetRange( index, c ); //// } //// } //// //// public override ArrayList GetRange( int index, int count ) //// { //// lock(m_root) //// { //// return m_list.GetRange( index, count ); //// } //// } //// //// public override void Sort() //// { //// lock(m_root) //// { //// m_list.Sort(); //// } //// } //// //// public override void Sort( IComparer comparer ) //// { //// lock(m_root) //// { //// m_list.Sort( comparer ); //// } //// } //// //// public override void Sort( int index, int count, IComparer comparer ) //// { //// lock(m_root) //// { //// m_list.Sort( index, count, comparer ); //// } //// } //// //// public override Object[] ToArray() //// { //// lock(m_root) //// { //// return m_list.ToArray(); //// } //// } //// //// public override Array ToArray( Type type ) //// { //// lock(m_root) //// { //// return m_list.ToArray( type ); //// } //// } //// //// public override void TrimToSize() //// { //// lock(m_root) //// { //// m_list.TrimToSize(); //// } //// } //// } #endregion #region Commented SyncIList //// [Serializable] //// private class SyncIList : IList //// { //// private IList m_list; //// private Object m_root; //// //// internal SyncIList( IList list ) //// { //// m_list = list; //// m_root = list.SyncRoot; //// } //// //// public virtual int Count //// { //// get //// { //// lock(m_root) //// { //// return m_list.Count; //// } //// } //// } //// //// public virtual bool IsReadOnly //// { //// get //// { //// return m_list.IsReadOnly; //// } //// } //// //// public virtual bool IsFixedSize //// { //// get //// { //// return m_list.IsFixedSize; //// } //// } //// //// public virtual bool IsSynchronized //// { //// get //// { //// return true; //// } //// } //// //// public virtual Object this[int index] //// { //// get //// { //// lock(m_root) //// { //// return m_list[index]; //// } //// } //// //// set //// { //// lock(m_root) //// { //// m_list[index] = value; //// } //// } //// } //// //// public virtual Object SyncRoot //// { //// get //// { //// return m_root; //// } //// } //// //// public virtual int Add( Object value ) //// { //// lock(m_root) //// { //// return m_list.Add( value ); //// } //// } //// //// //// public virtual void Clear() //// { //// lock(m_root) //// { //// m_list.Clear(); //// } //// } //// //// public virtual bool Contains( Object item ) //// { //// lock(m_root) //// { //// return m_list.Contains( item ); //// } //// } //// //// public virtual void CopyTo( Array array, int index ) //// { //// lock(m_root) //// { //// m_list.CopyTo( array, index ); //// } //// } //// //// public virtual IEnumerator GetEnumerator() //// { //// lock(m_root) //// { //// return m_list.GetEnumerator(); //// } //// } //// //// public virtual int IndexOf( Object value ) //// { //// lock(m_root) //// { //// return m_list.IndexOf( value ); //// } //// } //// //// public virtual void Insert( int index, Object value ) //// { //// lock(m_root) //// { //// m_list.Insert( index, value ); //// } //// } //// //// public virtual void Remove( Object value ) //// { //// lock(m_root) //// { //// m_list.Remove( value ); //// } //// } //// //// public virtual void RemoveAt( int index ) //// { //// lock(m_root) //// { //// m_list.RemoveAt( index ); //// } //// } //// } #endregion #region Commented FixedSizeList //// [Serializable] //// private class FixedSizeList : IList //// { //// private IList m_list; //// //// internal FixedSizeList( IList l ) //// { //// m_list = l; //// } //// //// public virtual int Count //// { //// get //// { //// return m_list.Count; //// } //// } //// //// public virtual bool IsReadOnly //// { //// get //// { //// return m_list.IsReadOnly; //// } //// } //// //// public virtual bool IsFixedSize //// { //// get //// { //// return true; //// } //// } //// //// public virtual bool IsSynchronized //// { //// get //// { //// return m_list.IsSynchronized; //// } //// } //// //// public virtual Object this[int index] //// { //// get //// { //// return m_list[index]; //// } //// //// set //// { //// m_list[index] = value; //// } //// } //// //// public virtual Object SyncRoot //// { //// get //// { //// return m_list.SyncRoot; //// } //// } //// //// public virtual int Add( Object obj ) //// { //// throw new NotSupportedException( Environment.GetResourceString( "NotSupported_FixedSizeCollection" ) ); //// } //// //// public virtual void Clear() //// { //// throw new NotSupportedException( Environment.GetResourceString( "NotSupported_FixedSizeCollection" ) ); //// } //// //// public virtual bool Contains( Object obj ) //// { //// return m_list.Contains( obj ); //// } //// //// public virtual void CopyTo( Array array, int index ) //// { //// m_list.CopyTo( array, index ); //// } //// //// public virtual IEnumerator GetEnumerator() //// { //// return m_list.GetEnumerator(); //// } //// //// public virtual int IndexOf( Object value ) //// { //// return m_list.IndexOf( value ); //// } //// //// public virtual void Insert( int index, Object obj ) //// { //// throw new NotSupportedException( Environment.GetResourceString( "NotSupported_FixedSizeCollection" ) ); //// } //// //// public virtual void Remove( Object value ) //// { //// throw new NotSupportedException( Environment.GetResourceString( "NotSupported_FixedSizeCollection" ) ); //// } //// //// public virtual void RemoveAt( int index ) //// { //// throw new NotSupportedException( Environment.GetResourceString( "NotSupported_FixedSizeCollection" ) ); //// } //// } #endregion #region Commented FixedSizeArrayList //// [Serializable] //// private class FixedSizeArrayList : ArrayList //// { //// private ArrayList m_list; //// //// internal FixedSizeArrayList( ArrayList l ) //// { //// m_list = l; //// m_version = m_list.m_version; //// } //// //// public override int Count //// { //// get //// { //// return m_list.Count; //// } //// } //// //// public override bool IsReadOnly //// { //// get //// { //// return m_list.IsReadOnly; //// } //// } //// //// public override bool IsFixedSize //// { //// get //// { //// return true; //// } //// } //// //// public override bool IsSynchronized //// { //// get //// { //// return m_list.IsSynchronized; //// } //// } //// //// public override Object this[int index] //// { //// get //// { //// return m_list[index]; //// } //// //// set //// { //// m_list[index] = value; //// //// m_version = m_list.m_version; //// } //// } //// //// public override Object SyncRoot //// { //// get //// { //// return m_list.SyncRoot; //// } //// } //// //// public override int Add( Object obj ) //// { //// throw new NotSupportedException( Environment.GetResourceString( "NotSupported_FixedSizeCollection" ) ); //// } //// //// public override void AddRange( ICollection c ) //// { //// throw new NotSupportedException( Environment.GetResourceString( "NotSupported_FixedSizeCollection" ) ); //// } //// //// public override int BinarySearch( int index, int count, Object value, IComparer comparer ) //// { //// return m_list.BinarySearch( index, count, value, comparer ); //// } //// //// public override int Capacity //// { //// get //// { //// return m_list.Capacity; //// } //// //// set //// { //// throw new NotSupportedException( Environment.GetResourceString( "NotSupported_FixedSizeCollection" ) ); //// } //// } //// //// public override void Clear() //// { //// throw new NotSupportedException( Environment.GetResourceString( "NotSupported_FixedSizeCollection" ) ); //// } //// //// public override Object Clone() //// { //// FixedSizeArrayList arrayList = new FixedSizeArrayList( m_list ); //// //// arrayList.m_list = (ArrayList)m_list.Clone(); //// //// return arrayList; //// } //// //// public override bool Contains( Object obj ) //// { //// return m_list.Contains( obj ); //// } //// //// public override void CopyTo( Array array, int index ) //// { //// m_list.CopyTo( array, index ); //// } //// //// public override void CopyTo( int index, Array array, int arrayIndex, int count ) //// { //// m_list.CopyTo( index, array, arrayIndex, count ); //// } //// //// public override IEnumerator GetEnumerator() //// { //// return m_list.GetEnumerator(); //// } //// //// public override IEnumerator GetEnumerator( int index, int count ) //// { //// return m_list.GetEnumerator( index, count ); //// } //// //// public override int IndexOf( Object value ) //// { //// return m_list.IndexOf( value ); //// } //// //// public override int IndexOf( Object value, int startIndex ) //// { //// return m_list.IndexOf( value, startIndex ); //// } //// //// public override int IndexOf( Object value, int startIndex, int count ) //// { //// return m_list.IndexOf( value, startIndex, count ); //// } //// //// public override void Insert( int index, Object obj ) //// { //// throw new NotSupportedException( Environment.GetResourceString( "NotSupported_FixedSizeCollection" ) ); //// } //// //// public override void InsertRange( int index, ICollection c ) //// { //// throw new NotSupportedException( Environment.GetResourceString( "NotSupported_FixedSizeCollection" ) ); //// } //// //// public override int LastIndexOf( Object value ) //// { //// return m_list.LastIndexOf( value ); //// } //// //// public override int LastIndexOf( Object value, int startIndex ) //// { //// return m_list.LastIndexOf( value, startIndex ); //// } //// //// public override int LastIndexOf( Object value, int startIndex, int count ) //// { //// return m_list.LastIndexOf( value, startIndex, count ); //// } //// //// public override void Remove( Object value ) //// { //// throw new NotSupportedException( Environment.GetResourceString( "NotSupported_FixedSizeCollection" ) ); //// } //// //// public override void RemoveAt( int index ) //// { //// throw new NotSupportedException( Environment.GetResourceString( "NotSupported_FixedSizeCollection" ) ); //// } //// //// public override void RemoveRange( int index, int count ) //// { //// throw new NotSupportedException( Environment.GetResourceString( "NotSupported_FixedSizeCollection" ) ); //// } //// //// public override void SetRange( int index, ICollection c ) //// { //// m_list.SetRange( index, c ); //// //// m_version = m_list.m_version; //// } //// //// public override ArrayList GetRange( int index, int count ) //// { //// if(index < 0 || count < 0) //// { //// throw new ArgumentOutOfRangeException( (index < 0 ? "index" : "count"), Environment.GetResourceString( "ArgumentOutOfRange_NeedNonNegNum" ) ); //// } //// //// if(Count - index < count) //// { //// throw new ArgumentException( Environment.GetResourceString( "Argument_InvalidOffLen" ) ); //// } //// //// return new Range( this, index, count ); //// } //// //// public override void Reverse( int index, int count ) //// { //// m_list.Reverse( index, count ); //// //// m_version = m_list.m_version; //// } //// //// public override void Sort( int index, int count, IComparer comparer ) //// { //// m_list.Sort( index, count, comparer ); //// //// m_version = m_list.m_version; //// } //// //// public override Object[] ToArray() //// { //// return m_list.ToArray(); //// } //// //// public override Array ToArray( Type type ) //// { //// return m_list.ToArray( type ); //// } //// //// public override void TrimToSize() //// { //// throw new NotSupportedException( Environment.GetResourceString( "NotSupported_FixedSizeCollection" ) ); //// } //// } #endregion #region Commented ReadOnlyList //// [Serializable] //// private class ReadOnlyList : IList //// { //// private IList m_list; //// //// internal ReadOnlyList( IList l ) //// { //// m_list = l; //// } //// //// public virtual int Count //// { //// get //// { //// return m_list.Count; //// } //// } //// //// public virtual bool IsReadOnly //// { //// get //// { //// return true; //// } //// } //// //// public virtual bool IsFixedSize //// { //// get //// { //// return true; //// } //// } //// //// public virtual bool IsSynchronized //// { //// get //// { //// return m_list.IsSynchronized; //// } //// } //// //// public virtual Object this[int index] //// { //// get //// { //// return m_list[index]; //// } //// //// set //// { //// throw new NotSupportedException( Environment.GetResourceString( "NotSupported_ReadOnlyCollection" ) ); //// } //// } //// //// public virtual Object SyncRoot //// { //// get //// { //// return m_list.SyncRoot; //// } //// } //// //// public virtual int Add( Object obj ) //// { //// throw new NotSupportedException( Environment.GetResourceString( "NotSupported_ReadOnlyCollection" ) ); //// } //// //// public virtual void Clear() //// { //// throw new NotSupportedException( Environment.GetResourceString( "NotSupported_ReadOnlyCollection" ) ); //// } //// //// public virtual bool Contains( Object obj ) //// { //// return m_list.Contains( obj ); //// } //// //// public virtual void CopyTo( Array array, int index ) //// { //// m_list.CopyTo( array, index ); //// } //// //// public virtual IEnumerator GetEnumerator() //// { //// return m_list.GetEnumerator(); //// } //// //// public virtual int IndexOf( Object value ) //// { //// return m_list.IndexOf( value ); //// } //// //// public virtual void Insert( int index, Object obj ) //// { //// throw new NotSupportedException( Environment.GetResourceString( "NotSupported_ReadOnlyCollection" ) ); //// } //// //// public virtual void Remove( Object value ) //// { //// throw new NotSupportedException( Environment.GetResourceString( "NotSupported_ReadOnlyCollection" ) ); //// } //// //// public virtual void RemoveAt( int index ) //// { //// throw new NotSupportedException( Environment.GetResourceString( "NotSupported_ReadOnlyCollection" ) ); //// } //// } #endregion #region Commented ReadOnlyArrayList //// [Serializable] //// private class ReadOnlyArrayList : ArrayList //// { //// private ArrayList m_list; //// //// internal ReadOnlyArrayList( ArrayList l ) //// { //// m_list = l; //// } //// //// public override int Count //// { //// get //// { //// return m_list.Count; //// } //// } //// //// public override bool IsReadOnly //// { //// get //// { //// return true; //// } //// } //// //// public override bool IsFixedSize //// { //// get //// { //// return true; //// } //// } //// //// public override bool IsSynchronized //// { //// get //// { //// return m_list.IsSynchronized; //// } //// } //// //// public override Object this[int index] //// { //// get //// { //// return m_list[index]; //// } //// //// set //// { //// throw new NotSupportedException( Environment.GetResourceString( "NotSupported_ReadOnlyCollection" ) ); //// } //// } //// //// public override Object SyncRoot //// { //// get //// { //// return m_list.SyncRoot; //// } //// } //// //// public override int Add( Object obj ) //// { //// throw new NotSupportedException( Environment.GetResourceString( "NotSupported_ReadOnlyCollection" ) ); //// } //// //// public override void AddRange( ICollection c ) //// { //// throw new NotSupportedException( Environment.GetResourceString( "NotSupported_ReadOnlyCollection" ) ); //// } //// //// public override int BinarySearch( int index, int count, Object value, IComparer comparer ) //// { //// return m_list.BinarySearch( index, count, value, comparer ); //// } //// //// //// public override int Capacity //// { //// get //// { //// return m_list.Capacity; //// } //// //// set //// { //// throw new NotSupportedException( Environment.GetResourceString( "NotSupported_ReadOnlyCollection" ) ); //// } //// } //// //// public override void Clear() //// { //// throw new NotSupportedException( Environment.GetResourceString( "NotSupported_ReadOnlyCollection" ) ); //// } //// //// public override Object Clone() //// { //// ReadOnlyArrayList arrayList = new ReadOnlyArrayList( m_list ); //// //// arrayList.m_list = (ArrayList)m_list.Clone(); //// //// return arrayList; //// } //// //// public override bool Contains( Object obj ) //// { //// return m_list.Contains( obj ); //// } //// //// public override void CopyTo( Array array, int index ) //// { //// m_list.CopyTo( array, index ); //// } //// //// public override void CopyTo( int index, Array array, int arrayIndex, int count ) //// { //// m_list.CopyTo( index, array, arrayIndex, count ); //// } //// //// public override IEnumerator GetEnumerator() //// { //// return m_list.GetEnumerator(); //// } //// //// public override IEnumerator GetEnumerator( int index, int count ) //// { //// return m_list.GetEnumerator( index, count ); //// } //// //// public override int IndexOf( Object value ) //// { //// return m_list.IndexOf( value ); //// } //// //// public override int IndexOf( Object value, int startIndex ) //// { //// return m_list.IndexOf( value, startIndex ); //// } //// //// public override int IndexOf( Object value, int startIndex, int count ) //// { //// return m_list.IndexOf( value, startIndex, count ); //// } //// //// public override void Insert( int index, Object obj ) //// { //// throw new NotSupportedException( Environment.GetResourceString( "NotSupported_ReadOnlyCollection" ) ); //// } //// //// public override void InsertRange( int index, ICollection c ) //// { //// throw new NotSupportedException( Environment.GetResourceString( "NotSupported_ReadOnlyCollection" ) ); //// } //// //// public override int LastIndexOf( Object value ) //// { //// return m_list.LastIndexOf( value ); //// } //// //// public override int LastIndexOf( Object value, int startIndex ) //// { //// return m_list.LastIndexOf( value, startIndex ); //// } //// //// public override int LastIndexOf( Object value, int startIndex, int count ) //// { //// return m_list.LastIndexOf( value, startIndex, count ); //// } //// //// public override void Remove( Object value ) //// { //// throw new NotSupportedException( Environment.GetResourceString( "NotSupported_ReadOnlyCollection" ) ); //// } //// //// public override void RemoveAt( int index ) //// { //// throw new NotSupportedException( Environment.GetResourceString( "NotSupported_ReadOnlyCollection" ) ); //// } //// //// public override void RemoveRange( int index, int count ) //// { //// throw new NotSupportedException( Environment.GetResourceString( "NotSupported_ReadOnlyCollection" ) ); //// } //// //// public override void SetRange( int index, ICollection c ) //// { //// throw new NotSupportedException( Environment.GetResourceString( "NotSupported_ReadOnlyCollection" ) ); //// } //// //// public override ArrayList GetRange( int index, int count ) //// { //// if(index < 0 || count < 0) //// { //// throw new ArgumentOutOfRangeException( (index < 0 ? "index" : "count"), Environment.GetResourceString( "ArgumentOutOfRange_NeedNonNegNum" ) ); //// } //// //// if(Count - index < count) //// { //// throw new ArgumentException( Environment.GetResourceString( "Argument_InvalidOffLen" ) ); //// } //// //// return new Range( this, index, count ); //// } //// //// public override void Reverse( int index, int count ) //// { //// throw new NotSupportedException( Environment.GetResourceString( "NotSupported_ReadOnlyCollection" ) ); //// } //// //// public override void Sort( int index, int count, IComparer comparer ) //// { //// throw new NotSupportedException( Environment.GetResourceString( "NotSupported_ReadOnlyCollection" ) ); //// } //// //// public override Object[] ToArray() //// { //// return m_list.ToArray(); //// } //// //// public override Array ToArray( Type type ) //// { //// return m_list.ToArray( type ); //// } //// //// public override void TrimToSize() //// { //// throw new NotSupportedException( Environment.GetResourceString( "NotSupported_ReadOnlyCollection" ) ); //// } //// } #endregion #region Commented ArrayListEnumerator // Implements an enumerator for a ArrayList. The enumerator uses the // internal version number of the list to ensure that no modifications are // made to the list while an enumeration is in progress. [Serializable] private sealed class ArrayListEnumerator : IEnumerator, ICloneable { private ArrayList m_list; private int m_index; private int m_endIndex; // Where to stop. private int m_version; private Object m_currentElement; private int m_startIndex; // Save this for Reset. internal ArrayListEnumerator( ArrayList list, int index, int count ) { m_list = list; m_startIndex = index; m_index = index - 1; m_endIndex = m_index + count; // last valid index m_version = list.m_version; m_currentElement = null; } public Object Clone() { return MemberwiseClone(); } public bool MoveNext() { if(m_version != m_list.m_version) { #if EXCEPTION_STRINGS throw new InvalidOperationException( Environment.GetResourceString( "InvalidOperation_EnumFailedVersion" ) ); #else throw new InvalidOperationException(); #endif } if(m_index < m_endIndex) { m_currentElement = m_list[++m_index]; return true; } else { m_index = m_endIndex + 1; return false; } } public Object Current { get { if(m_index < m_startIndex) { #if EXCEPTION_STRINGS throw new InvalidOperationException( Environment.GetResourceString( "InvalidOperation_EnumNotStarted" ) ); #else throw new InvalidOperationException(); #endif } else if(m_index > m_endIndex) { #if EXCEPTION_STRINGS throw new InvalidOperationException( Environment.GetResourceString( "InvalidOperation_EnumEnded" ) ); #else throw new InvalidOperationException(); #endif } return m_currentElement; } } public void Reset() { if(m_version != m_list.m_version) { #if EXCEPTION_STRINGS throw new InvalidOperationException( Environment.GetResourceString( "InvalidOperation_EnumFailedVersion" ) ); #else throw new InvalidOperationException(); #endif } m_index = m_startIndex - 1; } } #endregion #region Commented Range //// // Implementation of a generic list subrange. An instance of this class //// // is returned by the default implementation of List.GetRange. //// [Serializable] //// private class Range : ArrayList //// { //// private ArrayList m_baseList; //// private int m_baseIndex; //// private int m_baseSize; //// private int m_baseVersion; //// //// internal Range( ArrayList list, int index, int count ) : base( false ) //// { //// m_baseList = list; //// m_baseIndex = index; //// m_baseSize = count; //// m_baseVersion = list.m_version; //// //// // we also need to update _version field to make Range of Range work //// m_version = list.m_version; //// } //// //// private void InternalUpdateRange() //// { //// if(m_baseVersion != m_baseList.m_version) //// { //// throw new InvalidOperationException( Environment.GetResourceString( "InvalidOperation_UnderlyingArrayListChanged" ) ); //// } //// } //// //// private void InternalUpdateVersion() //// { //// m_baseVersion++; //// m_version++; //// } //// //// public override int Add( Object value ) //// { //// InternalUpdateRange(); //// //// m_baseList.Insert( m_baseIndex + m_baseSize, value ); //// //// InternalUpdateVersion(); //// return m_baseSize++; //// } //// //// public override void AddRange( ICollection c ) //// { //// InternalUpdateRange(); //// if(c == null) //// { //// throw new ArgumentNullException( "c" ); //// } //// //// int count = c.Count; //// if(count > 0) //// { //// m_baseList.InsertRange( m_baseIndex + m_baseSize, c ); //// InternalUpdateVersion(); //// m_baseSize += count; //// } //// } //// //// // Other overloads with automatically work //// public override int BinarySearch( int index, int count, Object value, IComparer comparer ) //// { //// InternalUpdateRange(); //// //// if(index < 0 || count < 0) //// { //// throw new ArgumentOutOfRangeException( (index < 0 ? "index" : "count"), Environment.GetResourceString( "ArgumentOutOfRange_NeedNonNegNum" ) ); //// } //// //// if(m_baseSize - index < count) //// { //// throw new ArgumentException( Environment.GetResourceString( "Argument_InvalidOffLen" ) ); //// } //// //// int i = m_baseList.BinarySearch( m_baseIndex + index, count, value, comparer ); //// if(i >= 0) return i - m_baseIndex; //// return i + m_baseIndex; //// } //// //// public override int Capacity //// { //// get //// { //// return m_baseList.Capacity; //// } //// //// set //// { //// if(value < Count) //// { //// throw new ArgumentOutOfRangeException( "value", Environment.GetResourceString( "ArgumentOutOfRange_SmallCapacity" ) ); //// } //// } //// } //// //// //// public override void Clear() //// { //// InternalUpdateRange(); //// //// if(m_baseSize != 0) //// { //// m_baseList.RemoveRange( m_baseIndex, m_baseSize ); //// //// InternalUpdateVersion(); //// m_baseSize = 0; //// } //// } //// //// public override Object Clone() //// { //// InternalUpdateRange(); //// //// Range arrayList = new Range( m_baseList, m_baseIndex, m_baseSize ); //// //// arrayList.m_baseList = (ArrayList)m_baseList.Clone(); //// //// return arrayList; //// } //// //// public override bool Contains( Object item ) //// { //// InternalUpdateRange(); //// //// if(item == null) //// { //// for(int i = 0; i < m_baseSize; i++) //// { //// if(m_baseList[m_baseIndex + i] == null) //// { //// return true; //// } //// } //// //// return false; //// } //// else //// { //// for(int i = 0; i < m_baseSize; i++) //// { //// if(m_baseList[m_baseIndex + i] != null && m_baseList[m_baseIndex + i].Equals( item )) //// { //// return true; //// } //// } //// //// return false; //// } //// } //// //// public override void CopyTo( Array array, int index ) //// { //// InternalUpdateRange(); //// //// if(array == null) //// { //// throw new ArgumentNullException( "array" ); //// } //// //// if(array.Rank != 1) //// { //// throw new ArgumentException( Environment.GetResourceString( "Arg_RankMultiDimNotSupported" ) ); //// } //// //// if(index < 0) //// { //// throw new ArgumentOutOfRangeException( "index", Environment.GetResourceString( "ArgumentOutOfRange_NeedNonNegNum" ) ); //// } //// //// if(array.Length - index < m_baseSize) //// { //// throw new ArgumentException( Environment.GetResourceString( "Argument_InvalidOffLen" ) ); //// } //// //// m_baseList.CopyTo( m_baseIndex, array, index, m_baseSize ); //// } //// //// public override void CopyTo( int index, Array array, int arrayIndex, int count ) //// { //// InternalUpdateRange(); //// //// if(array == null) //// { //// throw new ArgumentNullException( "array" ); //// } //// //// if(array.Rank != 1) //// { //// throw new ArgumentException( Environment.GetResourceString( "Arg_RankMultiDimNotSupported" ) ); //// } //// //// if(index < 0 || count < 0) //// { //// throw new ArgumentOutOfRangeException( (index < 0 ? "index" : "count"), Environment.GetResourceString( "ArgumentOutOfRange_NeedNonNegNum" ) ); //// } //// //// if(array.Length - arrayIndex < count) //// { //// throw new ArgumentException( Environment.GetResourceString( "Argument_InvalidOffLen" ) ); //// } //// //// if(m_baseSize - index < count) //// { //// throw new ArgumentException( Environment.GetResourceString( "Argument_InvalidOffLen" ) ); //// } //// //// m_baseList.CopyTo( m_baseIndex + index, array, arrayIndex, count ); //// } //// //// public override int Count //// { //// get //// { //// InternalUpdateRange(); //// //// return m_baseSize; //// } //// } //// //// public override bool IsReadOnly //// { //// get //// { //// return m_baseList.IsReadOnly; //// } //// } //// //// public override bool IsFixedSize //// { //// get //// { //// return m_baseList.IsFixedSize; //// } //// } //// //// public override bool IsSynchronized //// { //// get //// { //// return m_baseList.IsSynchronized; //// } //// } //// //// public override IEnumerator GetEnumerator() //// { //// return GetEnumerator( 0, m_baseSize ); //// } //// //// public override IEnumerator GetEnumerator( int index, int count ) //// { //// InternalUpdateRange(); //// //// if(index < 0 || count < 0) //// { //// throw new ArgumentOutOfRangeException( (index < 0 ? "index" : "count"), Environment.GetResourceString( "ArgumentOutOfRange_NeedNonNegNum" ) ); //// } //// //// if(m_baseSize - index < count) //// { //// throw new ArgumentException( Environment.GetResourceString( "Argument_InvalidOffLen" ) ); //// } //// //// return m_baseList.GetEnumerator( m_baseIndex + index, count ); //// } //// //// public override ArrayList GetRange( int index, int count ) //// { //// InternalUpdateRange(); //// //// if(index < 0 || count < 0) //// { //// throw new ArgumentOutOfRangeException( (index < 0 ? "index" : "count"), Environment.GetResourceString( "ArgumentOutOfRange_NeedNonNegNum" ) ); //// } //// //// if(m_baseSize - index < count) //// { //// throw new ArgumentException( Environment.GetResourceString( "Argument_InvalidOffLen" ) ); //// } //// //// return new Range( this, index, count ); //// } //// //// public override Object SyncRoot //// { //// get //// { //// return m_baseList.SyncRoot; //// } //// } //// //// //// public override int IndexOf( Object value ) //// { //// InternalUpdateRange(); //// //// int i = m_baseList.IndexOf( value, m_baseIndex, m_baseSize ); //// //// if(i >= 0) return i - m_baseIndex; //// //// return -1; //// } //// //// public override int IndexOf( Object value, int startIndex ) //// { //// InternalUpdateRange(); //// //// if(startIndex < 0) //// { //// throw new ArgumentOutOfRangeException( "startIndex", Environment.GetResourceString( "ArgumentOutOfRange_NeedNonNegNum" ) ); //// } //// //// if(startIndex > m_baseSize) //// { //// throw new ArgumentOutOfRangeException( "startIndex", Environment.GetResourceString( "ArgumentOutOfRange_Index" ) ); //// } //// //// int i = m_baseList.IndexOf( value, m_baseIndex + startIndex, m_baseSize - startIndex ); //// //// if(i >= 0) return i - m_baseIndex; //// //// return -1; //// } //// //// public override int IndexOf( Object value, int startIndex, int count ) //// { //// InternalUpdateRange(); //// //// if(startIndex < 0 || startIndex > m_baseSize) //// { //// throw new ArgumentOutOfRangeException( "startIndex", Environment.GetResourceString( "ArgumentOutOfRange_Index" ) ); //// } //// //// if(count < 0 || (startIndex > m_baseSize - count)) //// { //// throw new ArgumentOutOfRangeException( "count", Environment.GetResourceString( "ArgumentOutOfRange_Count" ) ); //// } //// //// int i = m_baseList.IndexOf( value, m_baseIndex + startIndex, count ); //// //// if(i >= 0) return i - m_baseIndex; //// //// return -1; //// } //// //// public override void Insert( int index, Object value ) //// { //// InternalUpdateRange(); //// //// if(index < 0 || index > m_baseSize) //// { //// throw new ArgumentOutOfRangeException( "index", Environment.GetResourceString( "ArgumentOutOfRange_Index" ) ); //// } //// //// m_baseList.Insert( m_baseIndex + index, value ); //// //// InternalUpdateVersion(); //// //// m_baseSize++; //// } //// //// public override void InsertRange( int index, ICollection c ) //// { //// InternalUpdateRange(); //// //// if(index < 0 || index > m_baseSize) //// { //// throw new ArgumentOutOfRangeException( "index", Environment.GetResourceString( "ArgumentOutOfRange_Index" ) ); //// } //// //// if(c == null) //// { //// throw new ArgumentNullException( "c" ); //// } //// //// int count = c.Count; //// if(count > 0) //// { //// m_baseList.InsertRange( m_baseIndex + index, c ); //// m_baseSize += count; //// //// InternalUpdateVersion(); //// } //// } //// //// public override int LastIndexOf( Object value ) //// { //// InternalUpdateRange(); //// //// int i = m_baseList.LastIndexOf( value, m_baseIndex + m_baseSize - 1, m_baseSize ); //// //// if(i >= 0) return i - m_baseIndex; //// //// return -1; //// } //// //// public override int LastIndexOf( Object value, int startIndex ) //// { //// return LastIndexOf( value, startIndex, startIndex + 1 ); //// } //// //// public override int LastIndexOf( Object value, int startIndex, int count ) //// { //// InternalUpdateRange(); //// //// if(m_baseSize == 0) //// { //// return -1; //// } //// //// if(startIndex >= m_baseSize) //// { //// throw new ArgumentOutOfRangeException( "startIndex", Environment.GetResourceString( "ArgumentOutOfRange_Index" ) ); //// } //// //// if(startIndex < 0) //// { //// throw new ArgumentOutOfRangeException( "startIndex", Environment.GetResourceString( "ArgumentOutOfRange_NeedNonNegNum" ) ); //// } //// //// int i = m_baseList.LastIndexOf( value, m_baseIndex + startIndex, count ); //// //// if(i >= 0) return i - m_baseIndex; //// //// return -1; //// } //// //// // Don't need to override Remove //// //// public override void RemoveAt( int index ) //// { //// InternalUpdateRange(); //// //// if(index < 0 || index >= m_baseSize) //// { //// throw new ArgumentOutOfRangeException( "index", Environment.GetResourceString( "ArgumentOutOfRange_Index" ) ); //// } //// //// m_baseList.RemoveAt( m_baseIndex + index ); //// //// InternalUpdateVersion(); //// m_baseSize--; //// } //// //// public override void RemoveRange( int index, int count ) //// { //// InternalUpdateRange(); //// //// if(index < 0 || count < 0) //// { //// throw new ArgumentOutOfRangeException( (index < 0 ? "index" : "count"), Environment.GetResourceString( "ArgumentOutOfRange_NeedNonNegNum" ) ); //// } //// //// if(m_baseSize - index < count) //// { //// throw new ArgumentException( Environment.GetResourceString( "Argument_InvalidOffLen" ) ); //// } //// //// // No need to call _bastList.RemoveRange if count is 0. //// // In addition, _baseList won't change the vresion number if count is 0. //// if(count > 0) //// { //// m_baseList.RemoveRange( m_baseIndex + index, count ); //// //// InternalUpdateVersion(); //// //// m_baseSize -= count; //// } //// } //// //// public override void Reverse( int index, int count ) //// { //// InternalUpdateRange(); //// //// if(index < 0 || count < 0) //// { //// throw new ArgumentOutOfRangeException( (index < 0 ? "index" : "count"), Environment.GetResourceString( "ArgumentOutOfRange_NeedNonNegNum" ) ); //// } //// //// if(m_baseSize - index < count) //// { //// throw new ArgumentException( Environment.GetResourceString( "Argument_InvalidOffLen" ) ); //// } //// //// m_baseList.Reverse( m_baseIndex + index, count ); //// InternalUpdateVersion(); //// } //// //// //// public override void SetRange( int index, ICollection c ) //// { //// InternalUpdateRange(); //// //// if(index < 0 || index >= m_baseSize) //// { //// throw new ArgumentOutOfRangeException( "index", Environment.GetResourceString( "ArgumentOutOfRange_Index" ) ); //// } //// //// m_baseList.SetRange( m_baseIndex + index, c ); //// if(c.Count > 0) //// { //// InternalUpdateVersion(); //// } //// } //// //// public override void Sort( int index, int count, IComparer comparer ) //// { //// InternalUpdateRange(); //// //// if(index < 0 || count < 0) //// { //// throw new ArgumentOutOfRangeException( (index < 0 ? "index" : "count"), Environment.GetResourceString( "ArgumentOutOfRange_NeedNonNegNum" ) ); //// } //// //// if(m_baseSize - index < count) //// { //// throw new ArgumentException( Environment.GetResourceString( "Argument_InvalidOffLen" ) ); //// } //// //// m_baseList.Sort( m_baseIndex + index, count, comparer ); //// InternalUpdateVersion(); //// } //// //// public override Object this[int index] //// { //// get //// { //// InternalUpdateRange(); //// //// if(index < 0 || index >= m_baseSize) //// { //// throw new ArgumentOutOfRangeException( "index", Environment.GetResourceString( "ArgumentOutOfRange_Index" ) ); //// } //// //// return m_baseList[m_baseIndex + index]; //// } //// set //// { //// InternalUpdateRange(); //// //// if(index < 0 || index >= m_baseSize) //// { //// throw new ArgumentOutOfRangeException( "index", Environment.GetResourceString( "ArgumentOutOfRange_Index" ) ); //// } //// //// m_baseList[m_baseIndex + index] = value; //// //// InternalUpdateVersion(); //// } //// } //// //// public override Object[] ToArray() //// { //// InternalUpdateRange(); //// //// Object[] array = new Object[m_baseSize]; //// //// Array.Copy( m_baseList.m_items, m_baseIndex, array, 0, m_baseSize ); //// //// return array; //// } //// //// public override Array ToArray( Type type ) //// { //// InternalUpdateRange(); //// //// if(type == null) //// { //// throw new ArgumentNullException( "type" ); //// } //// //// Array array = Array.CreateInstance( type, m_baseSize ); //// //// m_baseList.CopyTo( m_baseIndex, array, 0, m_baseSize ); //// //// return array; //// } //// //// public override void TrimToSize() //// { //// throw new NotSupportedException( Environment.GetResourceString( "NotSupported_RangeCollection" ) ); //// } //// } #endregion #region Commented ArrayListEnumeratorSimple [Serializable] private sealed class ArrayListEnumeratorSimple : IEnumerator, ICloneable { // this object is used to indicate enumeration has not started or has terminated static Object dummyObject = new Object(); private ArrayList m_list; private int m_index; private int m_version; private Object m_currentElement; [NonSerialized] private bool m_isArrayList; internal ArrayListEnumeratorSimple( ArrayList list ) { m_list = list; m_index = -1; m_version = list.m_version; m_isArrayList = (list.GetType() == typeof( ArrayList )); m_currentElement = dummyObject; } public Object Clone() { return MemberwiseClone(); } public bool MoveNext() { if(m_version != m_list.m_version) { #if EXCEPTION_STRINGS throw new InvalidOperationException( Environment.GetResourceString( "InvalidOperation_EnumFailedVersion" ) ); #else throw new InvalidOperationException(); #endif } if(m_isArrayList) { // avoid calling virtual methods if we are operating on ArrayList to improve performance if(m_index < m_list.m_size - 1) { m_currentElement = m_list.m_items[++m_index]; return true; } else { m_currentElement = dummyObject; m_index = m_list.m_size; return false; } } else { if(m_index < m_list.Count - 1) { m_currentElement = m_list[++m_index]; return true; } else { m_index = m_list.Count; m_currentElement = dummyObject; return false; } } } public Object Current { get { object temp = m_currentElement; if(dummyObject == temp) { // check if enumeration has not started or has terminated if(m_index == -1) { #if EXCEPTION_STRINGS throw new InvalidOperationException( Environment.GetResourceString( "InvalidOperation_EnumNotStarted" ) ); #else throw new InvalidOperationException(); #endif } else { #if EXCEPTION_STRINGS throw new InvalidOperationException( Environment.GetResourceString( "InvalidOperation_EnumEnded" ) ); #else throw new InvalidOperationException(); #endif } } return temp; } } public void Reset() { if(m_version != m_list.m_version) { #if EXCEPTION_STRINGS throw new InvalidOperationException( Environment.GetResourceString( "InvalidOperation_EnumFailedVersion" ) ); #else throw new InvalidOperationException(); #endif } m_currentElement = dummyObject; m_index = -1; } } #endregion #region Commented ArrayListDebugView //// //// internal class ArrayListDebugView //// { //// private ArrayList arrayList; //// //// public ArrayListDebugView( ArrayList arrayList ) //// { //// if(arrayList == null) //// { //// throw new ArgumentNullException( "arrayList" ); //// } //// //// this.arrayList = arrayList; //// } //// //// [DebuggerBrowsable( DebuggerBrowsableState.RootHidden )] //// public Object[] Items //// { //// get //// { //// return arrayList.ToArray(); //// } //// } //// } #endregion } } ================================================ FILE: Zelig/Zelig/RunTime/Framework/mscorlib/System/Collections/BitArray.cs ================================================ // ==++== // // Copyright (c) Microsoft Corporation. All rights reserved. // // ==--== /*============================================================================= ** ** Class: BitArray ** ** ** Purpose: The BitArray class manages a compact array of bit values. ** ** =============================================================================*/ namespace System.Collections { using System; ////using System.Security.Permissions; // A vector of bits. Use this to store bits efficiently, without having to do bit // shifting yourself. [Serializable] public sealed class BitArray : ICollection, ICloneable { private const int cShrinkThreshold = 256; private int[] m_array; private int m_length; private int m_version; [NonSerialized] private Object m_syncRoot; private BitArray() { } /*========================================================================= ** Allocates space to hold length bit values. All of the values in the bit ** array are set to false. ** ** Exceptions: ArgumentException if length < 0. =========================================================================*/ public BitArray( int length ) : this( length, false ) { } /*========================================================================= ** Allocates space to hold length bit values. All of the values in the bit ** array are set to defaultValue. ** ** Exceptions: ArgumentOutOfRangeException if length < 0. =========================================================================*/ public BitArray( int length, bool defaultValue ) { if(length < 0) { #if EXCEPTION_STRINGS throw new ArgumentOutOfRangeException( "length", Environment.GetResourceString( "ArgumentOutOfRange_NeedNonNegNum" ) ); #else throw new ArgumentOutOfRangeException(); #endif } m_array = new int[(length + 31) / 32]; m_length = length; int fillValue = defaultValue ? unchecked( ((int)0xffffffff) ) : 0; for(int i = 0; i < m_array.Length; i++) { m_array[i] = fillValue; } m_version = 0; } /*========================================================================= ** Allocates space to hold the bit values in bytes. bytes[0] represents ** bits 0 - 7, bytes[1] represents bits 8 - 15, etc. The LSB of each byte ** represents the lowest index value; bytes[0] & 1 represents bit 0, ** bytes[0] & 2 represents bit 1, bytes[0] & 4 represents bit 2, etc. ** ** Exceptions: ArgumentException if bytes == null. =========================================================================*/ public BitArray( byte[] bytes ) { if(bytes == null) { #if EXCEPTION_STRINGS throw new ArgumentNullException( "bytes" ); #else throw new ArgumentNullException(); #endif } m_array = new int[(bytes.Length + 3) / 4]; m_length = bytes.Length * 8; int i = 0; int j = 0; while(bytes.Length - j >= 4) { m_array[i++] = (bytes[j ] & 0xff) | ((bytes[j + 1] & 0xff) << 8) | ((bytes[j + 2] & 0xff) << 16) | ((bytes[j + 3] & 0xff) << 24); j += 4; } BCLDebug.Assert( bytes.Length - j >= 0, "BitArray byteLength problem" ); BCLDebug.Assert( bytes.Length - j < 4 , "BitArray byteLength problem #2" ); switch(bytes.Length - j) { case 3: m_array[i] = ((bytes[j + 2] & 0xff) << 16); goto case 2; // fall through case 2: m_array[i] |= ((bytes[j + 1] & 0xff) << 8); goto case 1; // fall through case 1: m_array[i] |= (bytes[j] & 0xff); break; } m_version = 0; } public BitArray( bool[] values ) { if(values == null) { #if EXCEPTION_STRINGS throw new ArgumentNullException( "values" ); #else throw new ArgumentNullException(); #endif } m_array = new int[(values.Length + 31) / 32]; m_length = values.Length; for(int i = 0; i < values.Length; i++) { if(values[i]) { m_array[i / 32] |= (1 << (i % 32)); } } m_version = 0; } /*========================================================================= ** Allocates space to hold the bit values in values. values[0] represents ** bits 0 - 31, values[1] represents bits 32 - 63, etc. The LSB of each ** integer represents the lowest index value; values[0] & 1 represents bit ** 0, values[0] & 2 represents bit 1, values[0] & 4 represents bit 2, etc. ** ** Exceptions: ArgumentException if values == null. =========================================================================*/ public BitArray( int[] values ) { if(values == null) { #if EXCEPTION_STRINGS throw new ArgumentNullException( "values" ); #else throw new ArgumentNullException(); #endif } m_array = new int[values.Length]; m_length = values.Length * 32; Array.Copy( values, m_array, values.Length ); m_version = 0; } /*========================================================================= ** Allocates a new BitArray with the same length and bit values as bits. ** ** Exceptions: ArgumentException if bits == null. =========================================================================*/ public BitArray( BitArray bits ) { if(bits == null) { #if EXCEPTION_STRINGS throw new ArgumentNullException( "bits" ); #else throw new ArgumentNullException(); #endif } m_array = new int[(bits.m_length + 31) / 32]; m_length = bits.m_length; Array.Copy( bits.m_array, m_array, (bits.m_length + 31) / 32 ); m_version = bits.m_version; } public bool this[int index] { get { return Get( index ); } set { Set( index, value ); } } /*========================================================================= ** Returns the bit value at position index. ** ** Exceptions: ArgumentOutOfRangeException if index < 0 or ** index >= GetLength(). =========================================================================*/ public bool Get( int index ) { if(index < 0 || index >= m_length) { #if EXCEPTION_STRINGS throw new ArgumentOutOfRangeException( "index", Environment.GetResourceString( "ArgumentOutOfRange_Index" ) ); #else throw new ArgumentOutOfRangeException(); #endif } return (m_array[index / 32] & (1 << (index % 32))) != 0; } /*========================================================================= ** Sets the bit value at position index to value. ** ** Exceptions: ArgumentOutOfRangeException if index < 0 or ** index >= GetLength(). =========================================================================*/ public void Set( int index, bool value ) { if(index < 0 || index >= m_length) { #if EXCEPTION_STRINGS throw new ArgumentOutOfRangeException( "index", Environment.GetResourceString( "ArgumentOutOfRange_Index" ) ); #else throw new ArgumentOutOfRangeException(); #endif } if(value) { m_array[index / 32] |= (1 << (index % 32)); } else { m_array[index / 32] &= ~(1 << (index % 32)); } m_version++; } /*========================================================================= ** Sets all the bit values to value. =========================================================================*/ public void SetAll( bool value ) { int fillValue = value ? unchecked( ((int)0xffffffff) ) : 0; int ints = (m_length + 31) / 32; for(int i = 0; i < ints; i++) { m_array[i] = fillValue; } m_version++; } /*========================================================================= ** Returns a reference to the current instance ANDed with value. ** ** Exceptions: ArgumentException if value == null or ** value.Length != this.Length. =========================================================================*/ public BitArray And( BitArray value ) { if(value == null) { #if EXCEPTION_STRINGS throw new ArgumentNullException( "value" ); #else throw new ArgumentNullException(); #endif } if(m_length != value.m_length) { #if EXCEPTION_STRINGS throw new ArgumentException( Environment.GetResourceString( "Arg_ArrayLengthsDiffer" ) ); #else throw new ArgumentException(); #endif } int ints = (m_length + 31) / 32; for(int i = 0; i < ints; i++) { m_array[i] &= value.m_array[i]; } m_version++; return this; } /*========================================================================= ** Returns a reference to the current instance ORed with value. ** ** Exceptions: ArgumentException if value == null or ** value.Length != this.Length. =========================================================================*/ public BitArray Or( BitArray value ) { if(value == null) { #if EXCEPTION_STRINGS throw new ArgumentNullException( "value" ); #else throw new ArgumentNullException(); #endif } if(m_length != value.m_length) { #if EXCEPTION_STRINGS throw new ArgumentException( Environment.GetResourceString( "Arg_ArrayLengthsDiffer" ) ); #else throw new ArgumentException(); #endif } int ints = (m_length + 31) / 32; for(int i = 0; i < ints; i++) { m_array[i] |= value.m_array[i]; } m_version++; return this; } /*========================================================================= ** Returns a reference to the current instance XORed with value. ** ** Exceptions: ArgumentException if value == null or ** value.Length != this.Length. =========================================================================*/ public BitArray Xor( BitArray value ) { if(value == null) { #if EXCEPTION_STRINGS throw new ArgumentNullException( "value" ); #else throw new ArgumentNullException(); #endif } if(m_length != value.m_length) { #if EXCEPTION_STRINGS throw new ArgumentException( Environment.GetResourceString( "Arg_ArrayLengthsDiffer" ) ); #else throw new ArgumentException(); #endif } int ints = (m_length + 31) / 32; for(int i = 0; i < ints; i++) { m_array[i] ^= value.m_array[i]; } m_version++; return this; } /*========================================================================= ** Inverts all the bit values. On/true bit values are converted to ** off/false. Off/false bit values are turned on/true. The current instance ** is updated and returned. =========================================================================*/ public BitArray Not() { int ints = (m_length + 31) / 32; for(int i = 0; i < ints; i++) { m_array[i] = ~m_array[i]; } m_version++; return this; } public int Length { get { return m_length; } set { if(value < 0) { #if EXCEPTION_STRINGS throw new ArgumentOutOfRangeException( "value", Environment.GetResourceString( "ArgumentOutOfRange_NeedNonNegNum" ) ); #else throw new ArgumentOutOfRangeException(); #endif } int newints = (value + 31) / 32; if(newints > m_array.Length || newints + cShrinkThreshold < m_array.Length) { // grow or shrink (if wasting more than _ShrinkThreshold ints) int[] newarray = new int[newints]; Array.Copy( m_array, newarray, newints > m_array.Length ? m_array.Length : newints ); m_array = newarray; } if(value > m_length) { // clear high bit values in the last int int last = ((m_length + 31) / 32) - 1; int bits = m_length % 32; if(bits > 0) { m_array[last] &= (1 << bits) - 1; } // clear remaining int values Array.Clear( m_array, last + 1, newints - last - 1 ); } m_length = value; m_version++; } } // ICollection implementation public void CopyTo( Array array, int index ) { if(array == null) { #if EXCEPTION_STRINGS throw new ArgumentNullException( "array" ); #else throw new ArgumentNullException(); #endif } if(index < 0) { #if EXCEPTION_STRINGS throw new ArgumentOutOfRangeException( "index", Environment.GetResourceString( "ArgumentOutOfRange_NeedNonNegNum" ) ); #else throw new ArgumentOutOfRangeException(); #endif } if(array.Rank != 1) { #if EXCEPTION_STRINGS throw new ArgumentException( Environment.GetResourceString( "Arg_RankMultiDimNotSupported" ) ); #else throw new ArgumentException(); #endif } if(array is int[]) { Array.Copy( m_array, 0, array, index, (m_length + 31) / 32 ); } else if(array is byte[]) { if((array.Length - index) < (m_length + 7) / 8) { #if EXCEPTION_STRINGS throw new ArgumentException( Environment.GetResourceString( "Argument_InvalidOffLen" ) ); #else throw new ArgumentException(); #endif } byte[] b = (byte[])array; for(int i = 0; i < (m_length + 7) / 8; i++) { b[index + i] = (byte)((m_array[i / 4] >> ((i % 4) * 8)) & 0x000000FF); // Shift to bring the required byte to LSB, then mask } } else if(array is bool[]) { if(array.Length - index < m_length) { #if EXCEPTION_STRINGS throw new ArgumentException( Environment.GetResourceString( "Argument_InvalidOffLen" ) ); #else throw new ArgumentException(); #endif } bool[] b = (bool[])array; for(int i = 0; i < m_length; i++) { b[index + i] = ((m_array[i / 32] >> (i % 32)) & 0x00000001) != 0; } } else { #if EXCEPTION_STRINGS throw new ArgumentException( Environment.GetResourceString( "Arg_BitArrayTypeUnsupported" ) ); #else throw new ArgumentException(); #endif } } public int Count { get { return m_length; } } public Object Clone() { BitArray bitArray = new BitArray( m_array ); bitArray.m_version = m_version; bitArray.m_length = m_length; return bitArray; } public Object SyncRoot { get { if(m_syncRoot == null) { System.Threading.Interlocked.CompareExchange( ref m_syncRoot, new Object(), null ); } return m_syncRoot; } } public bool IsReadOnly { get { return false; } } public bool IsSynchronized { get { return false; } } public IEnumerator GetEnumerator() { return new BitArrayEnumeratorSimple( this ); } [Serializable] private class BitArrayEnumeratorSimple : IEnumerator, ICloneable { private BitArray m_bitarray; private int m_index; private int m_version; private bool m_currentElement; internal BitArrayEnumeratorSimple( BitArray bitarray ) { m_bitarray = bitarray; m_index = -1; m_version = bitarray.m_version; } public Object Clone() { return MemberwiseClone(); } public virtual bool MoveNext() { if(m_version != m_bitarray.m_version) { #if EXCEPTION_STRINGS throw new InvalidOperationException( Environment.GetResourceString( "InvalidOperation_EnumFailedVersion" ) ); #else throw new InvalidOperationException(); #endif } if(m_index < (m_bitarray.Count - 1)) { m_index++; m_currentElement = m_bitarray.Get( m_index ); return true; } else { m_index = m_bitarray.Count; } return false; } public virtual Object Current { get { if(m_index == -1) { #if EXCEPTION_STRINGS throw new InvalidOperationException( Environment.GetResourceString( "InvalidOperation_EnumNotStarted" ) ); #else throw new InvalidOperationException(); #endif } if(m_index >= m_bitarray.Count) { #if EXCEPTION_STRINGS throw new InvalidOperationException( Environment.GetResourceString( "InvalidOperation_EnumEnded" ) ); #else throw new InvalidOperationException(); #endif } return m_currentElement; } } public void Reset() { if(m_version != m_bitarray.m_version) { #if EXCEPTION_STRINGS throw new InvalidOperationException( Environment.GetResourceString( "InvalidOperation_EnumFailedVersion" ) ); #else throw new InvalidOperationException(); #endif } m_index = -1; } } } } ================================================ FILE: Zelig/Zelig/RunTime/Framework/mscorlib/System/Collections/Comparer.cs ================================================ // ==++== // // Copyright (c) Microsoft Corporation. All rights reserved. // // ==--== /*============================================================ ** ** Class: Comparer ** ** ** Purpose: Default IComparer implementation. ** ** ===========================================================*/ namespace System.Collections { using System; using System.Globalization; using System.Runtime.Serialization; ////using System.Security.Permissions; [Serializable] public sealed class Comparer : IComparer /*, ISerializable*/ { public static readonly Comparer Default = new Comparer( CultureInfo.CurrentCulture ); //// public static readonly Comparer DefaultInvariant = new Comparer( CultureInfo.InvariantCulture ); //// private const String CompareInfoName = "CompareInfo"; private CompareInfo m_compareInfo; private Comparer() { m_compareInfo = null; } public Comparer( CultureInfo culture ) { m_compareInfo = null; // TODO: Implement feature... //// if(culture == null) //// { //// throw new ArgumentNullException( "culture" ); //// } //// //// m_compareInfo = culture.CompareInfo; } //// private Comparer( SerializationInfo info, StreamingContext context ) //// { //// m_compareInfo = null; //// //// SerializationInfoEnumerator enumerator = info.GetEnumerator(); //// while(enumerator.MoveNext()) //// { //// switch(enumerator.Name) //// { //// case CompareInfoName: //// m_compareInfo = (CompareInfo)info.GetValue( CompareInfoName, typeof( CompareInfo ) ); //// break; //// } //// } //// } // Compares two Objects by calling CompareTo. If a == // b,0 is returned. If a implements // IComparable, a.CompareTo(b) is returned. If a // doesn't implement IComparable and b does, // -(b.CompareTo(a)) is returned, otherwise an // exception is thrown. // public int Compare( Object a, Object b ) { if(a == b ) return 0; if(a == null) return -1; if(b == null) return 1; if(m_compareInfo != null) { String sa = a as String; String sb = b as String; if(sa != null && sb != null) { return m_compareInfo.Compare( sa, sb ); } } IComparable ia = a as IComparable; if(ia != null) { return ia.CompareTo( b ); } #if EXCEPTION_STRINGS throw new ArgumentException( Environment.GetResourceString( "Argument_ImplementIComparable" ) ); #else throw new ArgumentException(); #endif } //// [SecurityPermissionAttribute( SecurityAction.LinkDemand, Flags = SecurityPermissionFlag.SerializationFormatter )] //// public void GetObjectData( SerializationInfo info, StreamingContext context ) //// { //// if(info == null) //// { //// throw new ArgumentNullException( "info" ); //// } //// //// if(m_compareInfo != null) //// { //// info.AddValue( CompareInfoName, m_compareInfo ); //// } //// } } } ================================================ FILE: Zelig/Zelig/RunTime/Framework/mscorlib/System/Collections/DictionaryEntry.cs ================================================ // ==++== // // Copyright (c) Microsoft Corporation. All rights reserved. // // ==--== /*============================================================ ** ** Interface: DictionaryEntry ** ** ** Purpose: Return Value for IDictionaryEnumerator::GetEntry ** ** ===========================================================*/ namespace System.Collections { using System; // A DictionaryEntry holds a key and a value from a dictionary. // It is returned by IDictionaryEnumerator::GetEntry(). [Serializable] public struct DictionaryEntry { private Object m_key; private Object m_value; // Constructs a new DictionaryEnumerator by setting the Key // and Value fields appropriately. public DictionaryEntry( Object key, Object value ) { m_key = key; m_value = value; } public Object Key { get { return m_key; } set { m_key = value; } } public Object Value { get { return m_value; } set { m_value = value; } } } } ================================================ FILE: Zelig/Zelig/RunTime/Framework/mscorlib/System/Collections/Generic/ArraySortHelper.cs ================================================ // ==++== // // Copyright (c) Microsoft Corporation. All rights reserved. // // ==--== /*============================================================ ** ** Class: ArraySortHelper ** ** ** Purpose: class to sort arrays ** ** ===========================================================*/ namespace System.Collections.Generic { using System; using System.Globalization; using System.Runtime.CompilerServices; ////[TypeDependencyAttribute( "System.Collections.Generic.GenericArraySortHelper`1" )] [Microsoft.Zelig.Internals.TypeDependency( typeof(System.Collections.Generic.GenericArraySortHelper<>) )] internal class ArraySortHelper { static ArraySortHelper defaultArraySortHelper; public static ArraySortHelper Default { get { ArraySortHelper sorter = defaultArraySortHelper; if(sorter != null) { return sorter; } return CreateArraySortHelper(); } } private static ArraySortHelper CreateArraySortHelper() { //// if(typeof( IComparable ).IsAssignableFrom( typeof( T ) )) //// { //// defaultArraySortHelper = (ArraySortHelper)(typeof( GenericArraySortHelper ).TypeHandle.CreateInstanceForAnotherGenericParameter( typeof( T ) )); //// } //// else { defaultArraySortHelper = new ArraySortHelper(); } return defaultArraySortHelper; } public void Sort( T[] items, int index, int length, IComparer comparer ) { QuickSort( items, (object[])null, index, index + (length - 1), comparer ); //// Sort( items, (object[])null, index, length, comparer ); } // // ZELIG HACK: virtual generic methods are not supported yet. // public void Sort( T[] keys, TValue[] values, int index, int length, IComparer comparer ) //// public virtual void Sort( T[] keys, TValue[] values, int index, int length, IComparer comparer ) { //// BCLDebug.Assert( keys != null, "Check the arguments in the caller!" ); //// BCLDebug.Assert( index >= 0 && length >= 0 && (keys.Length - index >= length), "Check the arguments in the caller!" ); //// //// if(comparer == null || comparer == Comparer.Default) //// { //// comparer = Comparer.Default; //// } QuickSort( keys, values, index, index + (length - 1), comparer ); } private void SwapIfGreaterWithItems( T[] keys, TValue[] values, IComparer comparer, int a, int b ) { if(a != b) { try { if(comparer.Compare( keys[a], keys[b] ) > 0) { T key = keys[a]; keys[a] = keys[b]; keys[b] = key; if(values != null) { TValue value = values[a]; values[a] = values[b]; values[b] = value; } } } catch(IndexOutOfRangeException) { #if EXCEPTION_STRINGS throw new ArgumentException( Environment.GetResourceString( "Arg_BogusIComparer", keys[b], keys[b].GetType().Name, comparer ) ); #else throw new ArgumentException(); #endif } catch(Exception e) { #if EXCEPTION_STRINGS throw new InvalidOperationException( Environment.GetResourceString( "InvalidOperation_IComparerFailed" ), e ); #else throw new InvalidOperationException( null, e ); #endif } } } private void QuickSort( T[] keys, TValue[] values, int left, int right, IComparer comparer ) { do { int i = left; int j = right; // pre-sort the low, middle (pivot), and high values in place. // this improves performance in the face of already sorted data, or // data that is made up of multiple sorted runs appended together. int middle = i + ((j - i) >> 1); SwapIfGreaterWithItems( keys, values, comparer, i, middle ); // swap the low with the mid point SwapIfGreaterWithItems( keys, values, comparer, i, j ); // swap the low with the high SwapIfGreaterWithItems( keys, values, comparer, middle, j ); // swap the middle with the high T x = keys[middle]; do { // Add a try block here to detect IComparers (or their // underlying IComparables, etc) that are bogus. try { while(comparer.Compare( keys[i], x ) < 0) i++; while(comparer.Compare( x, keys[j] ) < 0) j--; } catch(IndexOutOfRangeException) { #if EXCEPTION_STRINGS throw new ArgumentException( Environment.GetResourceString( "Arg_BogusIComparer", x, x.GetType().Name, comparer ) ); #else throw new ArgumentException(); #endif } catch(Exception e) { #if EXCEPTION_STRINGS throw new InvalidOperationException( Environment.GetResourceString( "InvalidOperation_IComparerFailed" ), e ); #else throw new InvalidOperationException( null, e ); #endif } BCLDebug.Assert( i >= left && j <= right, "(i>=left && j<=right) Sort failed - Is your IComparer bogus?" ); if(i > j) break; if(i < j) { T key = keys[i]; keys[i] = keys[j]; keys[j] = key; if(values != null) { TValue value = values[i]; values[i] = values[j]; values[j] = value; } } i++; j--; } while(i <= j); if(j - left <= right - i) { if(left < j) QuickSort( keys, values, left, j, comparer ); left = i; } else { if(i < right) QuickSort( keys, values, i, right, comparer ); right = j; } } while(left < right); } public virtual int BinarySearch( T[] array, int index, int length, T value, IComparer comparer ) { BCLDebug.Assert( array != null, "Check the arguments in the caller!" ); BCLDebug.Assert( index >= 0 && length >= 0 && (array.Length - index >= length), "Check the arguments in the caller!" ); if(comparer == null) { comparer = System.Collections.Generic.Comparer.Default; } int lo = index; int hi = index + length - 1; while(lo <= hi) { int i = lo + ((hi - lo) >> 1); int order; try { order = comparer.Compare( array[i], value ); } catch(Exception e) { #if EXCEPTION_STRINGS throw new InvalidOperationException( Environment.GetResourceString( "InvalidOperation_IComparerFailed" ), e ); #else throw new InvalidOperationException( null, e ); #endif } if(order == 0) return i; if(order < 0) { lo = i + 1; } else { hi = i - 1; } } return ~lo; } } [Serializable()] internal class GenericArraySortHelper : ArraySortHelper where T : IComparable { public override int BinarySearch( T[] array, int index, int length, T value, IComparer comparer ) { BCLDebug.Assert( array != null, "Check the arguments in the caller!" ); BCLDebug.Assert( index >= 0 && length >= 0 && (array.Length - index >= length), "Check the arguments in the caller!" ); if(comparer == null || comparer == Comparer.Default) { return BinarySearch( array, index, length, value ); } else { return base.BinarySearch( array, index, length, value, comparer ); } } //// public override void Sort( T[] keys, TValue[] values, int index, int length, IComparer comparer ) //// { //// BCLDebug.Assert( keys != null, "Check the arguments in the caller!" ); //// BCLDebug.Assert( index >= 0 && length >= 0 && (keys.Length - index >= length), "Check the arguments in the caller!" ); //// //// if(comparer == null || comparer == Comparer.Default) //// { //// // call the fatser version of QuickSort if the user doesn't provide a comparer //// QuickSort( keys, values, index, index + length - 1 ); //// } //// else //// { //// base.Sort( keys, values, index, length, comparer ); //// } //// } // This function is called when the user doesn't specify any comparer. // Since T is constrained here, we can call IComparable.CompareTo here. // We can avoid boxing for value type and casting for reference types. private int BinarySearch( T[] array, int index, int length, T value ) { int lo = index; int hi = index + length - 1; while(lo <= hi) { int i = lo + ((hi - lo) >> 1); int order; try { if(array[i] == null) { order = (value == null) ? 0 : -1; } else { order = array[i].CompareTo( value ); } } catch(Exception e) { #if EXCEPTION_STRINGS throw new InvalidOperationException( Environment.GetResourceString( "InvalidOperation_IComparerFailed" ), e ); #else throw new InvalidOperationException( null, e ); #endif } if(order == 0) return i; if(order < 0) { lo = i + 1; } else { hi = i - 1; } } return ~lo; } private void SwapIfGreaterWithItems( T[] keys, TValue[] values, int a, int b ) { if(a != b) { try { if(keys[a] == null || keys[a].CompareTo( keys[b] ) > 0) { T key = keys[a]; keys[a] = keys[b]; keys[b] = key; if(values != null) { TValue value = values[a]; values[a] = values[b]; values[b] = value; } } } catch(IndexOutOfRangeException) { #if EXCEPTION_STRINGS throw new ArgumentException( Environment.GetResourceString( "Arg_BogusIComparer", keys[b], keys[b].GetType().Name, null ) ); #else throw new ArgumentException(); #endif } catch(Exception e) { #if EXCEPTION_STRINGS throw new InvalidOperationException( Environment.GetResourceString( "InvalidOperation_IComparerFailed" ), e ); #else throw new InvalidOperationException( null, e ); #endif } } } private void QuickSort( T[] keys, TValue[] values, int left, int right ) { // The code in this function looks very similar to QuickSort in ArraySortHelper class. // The difference is that T is constrainted to IComparable here. // So the IL code will be different. This function is faster than the one in ArraySortHelper. do { int i = left; int j = right; // pre-sort the low, middle (pivot), and high values in place. // this improves performance in the face of already sorted data, or // data that is made up of multiple sorted runs appended together. int middle = i + ((j - i) >> 1); SwapIfGreaterWithItems( keys, values, i, middle ); // swap the low with the mid point SwapIfGreaterWithItems( keys, values, i, j ); // swap the low with the high SwapIfGreaterWithItems( keys, values, middle, j ); // swap the middle with the high T x = keys[middle]; do { // Add a try block here to detect IComparers (or their // underlying IComparables, etc) that are bogus. try { if(x == null) { // if x null, the loop to find two elements to be switched can be reduced. while(keys[j] != null) j--; } else { while(x.CompareTo( keys[i] ) > 0) i++; while(x.CompareTo( keys[j] ) < 0) j--; } } catch(IndexOutOfRangeException) { #if EXCEPTION_STRINGS throw new ArgumentException( Environment.GetResourceString( "Arg_BogusIComparer", x, x.GetType().Name, null ) ); #else throw new ArgumentException(); #endif } catch(Exception e) { #if EXCEPTION_STRINGS throw new InvalidOperationException( Environment.GetResourceString( "InvalidOperation_IComparerFailed" ), e ); #else throw new InvalidOperationException( null, e ); #endif } BCLDebug.Assert( i >= left && j <= right, "(i>=left && j<=right) Sort failed - Is your IComparer bogus?" ); if(i > j) break; if(i < j) { T key = keys[i]; keys[i] = keys[j]; keys[j] = key; if(values != null) { TValue value = values[i]; values[i] = values[j]; values[j] = value; } } i++; j--; } while(i <= j); if(j - left <= right - i) { if(left < j) QuickSort( keys, values, left, j ); left = i; } else { if(i < right) QuickSort( keys, values, i, right ); right = j; } } while(left < right); } } } ================================================ FILE: Zelig/Zelig/RunTime/Framework/mscorlib/System/Collections/Generic/Comparer.cs ================================================ // ==++== // // Copyright (c) Microsoft Corporation. All rights reserved. // // ==--== namespace System.Collections.Generic { using System; using System.Collections; using System.Collections.Generic; using System.Globalization; using System.Runtime.CompilerServices; [Serializable] ////[TypeDependencyAttribute( "System.Collections.Generic.GenericComparer`1" )] [Microsoft.Zelig.Internals.WellKnownType( "System_Collections_Generic_Comparer_of_T" )] [Microsoft.Zelig.Internals.TypeDependency( typeof(System.Collections.Generic.GenericComparer<>) )] public abstract class Comparer : IComparer, IComparer { static Comparer defaultComparer; public static Comparer Default { get { Comparer comparer = defaultComparer; if(comparer == null) { comparer = CreateComparer(); defaultComparer = comparer; } return comparer; } } [MethodImpl( MethodImplOptions.InternalCall )] private static extern Comparer CreateComparer(); //// { //// Type t = typeof( T ); //// //// // If T implements IComparable return a GenericComparer //// if(typeof( IComparable ).IsAssignableFrom( t )) //// { //// //return (Comparer)Activator.CreateInstance(typeof(GenericComparer<>).MakeGenericType(t)); //// return (Comparer)(typeof( GenericComparer ).TypeHandle.CreateInstanceForAnotherGenericParameter( t )); //// } //// //// // If T is a Nullable where U implements IComparable return a NullableComparer //// if(t.IsGenericType && t.GetGenericTypeDefinition() == typeof( Nullable<> )) //// { //// Type u = t.GetGenericArguments()[0]; //// if(typeof( IComparable<> ).MakeGenericType( u ).IsAssignableFrom( u )) //// { //// //return (Comparer)Activator.CreateInstance(typeof(NullableComparer<>).MakeGenericType(u)); //// return (Comparer)(typeof( NullableComparer ).TypeHandle.CreateInstanceForAnotherGenericParameter( u )); //// } //// } //// //// // Otherwise return an ObjectComparer //// return new ObjectComparer(); //// } public abstract int Compare( T x, T y ); int IComparer.Compare( object x, object y ) { if(x == null) return y == null ? 0 : -1; if(y == null) return 1; if(x is T && y is T) return Compare( (T)x, (T)y ); ThrowHelper.ThrowArgumentException( ExceptionResource.Argument_InvalidArgumentForComparison ); return 0; } } [Serializable] [Microsoft.Zelig.Internals.WellKnownType( "System_Collections_Generic_GenericComparer_of_T" )] internal class GenericComparer : Comparer where T : IComparable { public override int Compare( T x, T y ) { if(x != null) { if(y != null) return x.CompareTo( y ); return 1; } if(y != null) return -1; return 0; } // Equals method for the comparer itself. public override bool Equals( Object obj ) { GenericComparer comparer = obj as GenericComparer; return comparer != null; } public override int GetHashCode() { return this.GetType().Name.GetHashCode(); } } [Serializable] [Microsoft.Zelig.Internals.WellKnownType( "System_Collections_Generic_NullableComparer_of_T" )] internal class NullableComparer : Comparer< Nullable > where T : struct, IComparable { public override int Compare( Nullable x, Nullable y ) { if(x.HasValue) { if(y.HasValue) return x.value.CompareTo( y.value ); return 1; } if(y.HasValue) return -1; return 0; } // Equals method for the comparer itself. public override bool Equals( Object obj ) { NullableComparer comparer = obj as NullableComparer; return comparer != null; } public override int GetHashCode() { return this.GetType().Name.GetHashCode(); } } [Serializable] [Microsoft.Zelig.Internals.WellKnownType( "System_Collections_Generic_ObjectComparer_of_T" )] internal class ObjectComparer : Comparer { public override int Compare( T x, T y ) { return System.Collections.Comparer.Default.Compare( x, y ); } // Equals method for the comparer itself. public override bool Equals( Object obj ) { ObjectComparer comparer = obj as ObjectComparer; return comparer != null; } public override int GetHashCode() { return this.GetType().Name.GetHashCode(); } } } ================================================ FILE: Zelig/Zelig/RunTime/Framework/mscorlib/System/Collections/Generic/Dictionary.cs ================================================ // ==++== // // Copyright (c) Microsoft Corporation. All rights reserved. // // ==--== /*============================================================ ** ** Class: Dictionary ** ** Purpose: Generic hash table implementation ** ** ===========================================================*/ namespace System.Collections.Generic { using System; using System.Collections; using System.Diagnostics; using System.Runtime.Serialization; ////using System.Security.Permissions; ////[DebuggerTypeProxy(typeof(Mscorlib_DictionaryDebugView<,>))] ////[DebuggerDisplay("Count = {Count}")] [Serializable] public class Dictionary : IDictionary, IDictionary /*, ISerializable, IDeserializationCallback*/ { private struct Entry { public int hashCode; // Lower 31 bits of hash code, -1 if unused public int next; // Index of next entry, -1 if last public TKey key; // Key of entry public TValue value; // Value of entry } // constants for serialization private const String VersionName = "Version"; private const String HashSizeName = "HashSize"; // Must save buckets.Length private const String KeyValuePairsName = "KeyValuePairs"; private const String ComparerName = "Comparer"; private int[] m_buckets; private Entry[] m_entries; private int m_count; private int m_version; private int m_freeList; private int m_freeCount; private IEqualityComparer m_comparer; private KeyCollection m_keys; private ValueCollection m_values; private Object m_syncRoot; //// private SerializationInfo m_siInfo; //A temporary variable which we need during deserialization. public Dictionary() : this( 0, null ) { } public Dictionary( int capacity ) : this( capacity, null ) { } public Dictionary( IEqualityComparer comparer ) : this( 0, comparer ) { } public Dictionary( int capacity, IEqualityComparer comparer ) { if(capacity < 0) { ThrowHelper.ThrowArgumentOutOfRangeException( ExceptionArgument.capacity ); } if(capacity > 0) { Initialize( capacity ); } if(comparer == null) { comparer = EqualityComparer.Default; } m_comparer = comparer; } public Dictionary( IDictionary dictionary ) : this( dictionary, null ) { } public Dictionary( IDictionary dictionary, IEqualityComparer comparer ) : this( dictionary != null ? dictionary.Count : 0, comparer ) { if(dictionary == null) { ThrowHelper.ThrowArgumentNullException( ExceptionArgument.dictionary ); } foreach(KeyValuePair pair in dictionary) { Add( pair.Key, pair.Value ); } } //// protected Dictionary( SerializationInfo info, StreamingContext context ) //// { //// //We can't do anything with the keys and values until the entire graph has been deserialized //// //and we have a resonable estimate that GetHashCode is not going to fail. For the time being, //// //we'll just cache this. The graph is not valid until OnDeserialization has been called. //// m_siInfo = info; //// } public IEqualityComparer Comparer { get { return m_comparer; } } public int Count { get { return m_count - m_freeCount; } } public KeyCollection Keys { get { if(m_keys == null) { m_keys = new KeyCollection( this ); } return m_keys; } } ICollection IDictionary.Keys { get { if(m_keys == null) { m_keys = new KeyCollection( this ); } return m_keys; } } public ValueCollection Values { get { if(m_values == null) { m_values = new ValueCollection( this ); } return m_values; } } ICollection IDictionary.Values { get { if(m_values == null) { m_values = new ValueCollection( this ); } return m_values; } } public TValue this[TKey key] { get { int i = FindEntry( key ); if(i >= 0) { return m_entries[i].value; } ThrowHelper.ThrowKeyNotFoundException(); return default( TValue ); } set { Insert( key, value, false ); } } public void Add( TKey key, TValue value ) { Insert( key, value, true ); } void ICollection>.Add( KeyValuePair keyValuePair ) { Add( keyValuePair.Key, keyValuePair.Value ); } bool ICollection>.Contains( KeyValuePair keyValuePair ) { int i = FindEntry( keyValuePair.Key ); if(i >= 0 && EqualityComparer.Default.Equals( m_entries[i].value, keyValuePair.Value )) { return true; } return false; } bool ICollection>.Remove( KeyValuePair keyValuePair ) { int i = FindEntry( keyValuePair.Key ); if(i >= 0 && EqualityComparer.Default.Equals( m_entries[i].value, keyValuePair.Value )) { Remove( keyValuePair.Key ); return true; } return false; } public void Clear() { if(m_count > 0) { for(int i = 0; i < m_buckets.Length; i++) { m_buckets[i] = -1; } Array.Clear( m_entries, 0, m_count ); m_freeList = -1; m_count = 0; m_freeCount = 0; m_version++; } } public bool ContainsKey( TKey key ) { return FindEntry( key ) >= 0; } public bool ContainsValue( TValue value ) { if(value == null) { for(int i = 0; i < m_count; i++) { if(m_entries[i].hashCode >= 0 && m_entries[i].value == null) { return true; } } } else { EqualityComparer c = EqualityComparer.Default; for(int i = 0; i < m_count; i++) { if(m_entries[i].hashCode >= 0 && c.Equals( m_entries[i].value, value )) { return true; } } } return false; } private void CopyTo( KeyValuePair[] array, int index ) { if(array == null) { ThrowHelper.ThrowArgumentNullException( ExceptionArgument.array ); } if(index < 0 || index > array.Length) { ThrowHelper.ThrowArgumentOutOfRangeException( ExceptionArgument.index, ExceptionResource.ArgumentOutOfRange_NeedNonNegNum ); } if(array.Length - index < Count) { ThrowHelper.ThrowArgumentException( ExceptionResource.Arg_ArrayPlusOffTooSmall ); } int count = m_count; Entry[] entries = m_entries; for(int i = 0; i < count; i++) { if(entries[i].hashCode >= 0) { array[index++] = new KeyValuePair( entries[i].key, entries[i].value ); } } } public Enumerator GetEnumerator() { return new Enumerator( this, Enumerator.KeyValuePair ); } IEnumerator> IEnumerable>.GetEnumerator() { return new Enumerator( this, Enumerator.KeyValuePair ); } //// [SecurityPermissionAttribute( SecurityAction.LinkDemand, Flags = SecurityPermissionFlag.SerializationFormatter )] //// public virtual void GetObjectData( SerializationInfo info, StreamingContext context ) //// { //// if(info == null) //// { //// ThrowHelper.ThrowArgumentNullException( ExceptionArgument.info ); //// } //// //// info.AddValue( VersionName , m_version ); //// info.AddValue( ComparerName, m_comparer , typeof( IEqualityComparer ) ); //// info.AddValue( HashSizeName, m_buckets == null ? 0 : m_buckets.Length ); //This is the length of the bucket array. //// //// if(m_buckets != null) //// { //// KeyValuePair[] array = new KeyValuePair[Count]; //// //// CopyTo( array, 0 ); //// //// info.AddValue( KeyValuePairsName, array, typeof( KeyValuePair[] ) ); //// } //// } private int FindEntry( TKey key ) { if(key == null) { ThrowHelper.ThrowArgumentNullException( ExceptionArgument.key ); } if(m_buckets != null) { int hashCode = m_comparer.GetHashCode( key ) & 0x7FFFFFFF; for(int i = m_buckets[hashCode % m_buckets.Length]; i >= 0; i = m_entries[i].next) { if(m_entries[i].hashCode == hashCode && m_comparer.Equals( m_entries[i].key, key )) { return i; } } } return -1; } private void Initialize( int capacity ) { int size = HashHelpers.GetPrime( capacity ); m_buckets = new int[size]; for(int i = 0; i < m_buckets.Length; i++) { m_buckets[i] = -1; } m_entries = new Entry[size]; m_freeList = -1; } private void Insert( TKey key, TValue value, bool add ) { if(key == null) { ThrowHelper.ThrowArgumentNullException( ExceptionArgument.key ); } if(m_buckets == null) { Initialize( 0 ); } int hashCode = m_comparer.GetHashCode( key ) & 0x7FFFFFFF; int targetBucket = hashCode % m_buckets.Length; for(int i = m_buckets[targetBucket]; i >= 0; i = m_entries[i].next) { if(m_entries[i].hashCode == hashCode && m_comparer.Equals( m_entries[i].key, key )) { if(add) { ThrowHelper.ThrowArgumentException( ExceptionResource.Argument_AddingDuplicate ); } m_entries[i].value = value; m_version++; return; } } int index; if(m_freeCount > 0) { index = m_freeList; m_freeList = m_entries[index].next; m_freeCount--; } else { if(m_count == m_entries.Length) { Resize(); targetBucket = hashCode % m_buckets.Length; } index = m_count; m_count++; } m_entries[index].hashCode = hashCode; m_entries[index].next = m_buckets[targetBucket]; m_entries[index].key = key; m_entries[index].value = value; m_buckets[targetBucket] = index; m_version++; } //// public virtual void OnDeserialization( Object sender ) //// { //// if(m_siInfo == null) //// { //// // It might be necessary to call OnDeserialization from a container if the container object also implements //// // OnDeserialization. However, remoting will call OnDeserialization again. //// // We can return immediately if this function is called twice. //// // Note we set m_siInfo to null at the end of this method. //// return; //// } //// //// int realVersion = m_siInfo.GetInt32( VersionName ); //// int hashsize = m_siInfo.GetInt32( HashSizeName ); //// //// m_comparer = (IEqualityComparer)m_siInfo.GetValue( ComparerName, typeof( IEqualityComparer ) ); //// //// if(hashsize != 0) //// { //// m_buckets = new int[hashsize]; //// for(int i = 0; i < m_buckets.Length; i++) //// { //// m_buckets[i] = -1; //// } //// //// m_entries = new Entry[hashsize]; //// m_freeList = -1; //// //// KeyValuePair[] array = (KeyValuePair[])m_siInfo.GetValue( KeyValuePairsName, typeof( KeyValuePair[] ) ); //// //// if(array == null) //// { //// ThrowHelper.ThrowSerializationException( ExceptionResource.Serialization_MissingKeys ); //// } //// //// for(int i = 0; i < array.Length; i++) //// { //// if(array[i].Key == null) //// { //// ThrowHelper.ThrowSerializationException( ExceptionResource.Serialization_NullKey ); //// } //// //// Insert( array[i].Key, array[i].Value, true ); //// } //// } //// else //// { //// m_buckets = null; //// } //// //// m_version = realVersion; //// m_siInfo = null; //// } private void Resize() { int newSize = HashHelpers.GetPrime( m_count * 2 ); int[] newBuckets = new int[newSize]; for(int i = 0; i < newBuckets.Length; i++) { newBuckets[i] = -1; } Entry[] newEntries = new Entry[newSize]; Array.Copy( m_entries, 0, newEntries, 0, m_count ); for(int i = 0; i < m_count; i++) { int bucket = newEntries[i].hashCode % newSize; newEntries[i].next = newBuckets[bucket]; newBuckets[bucket] = i; } m_buckets = newBuckets; m_entries = newEntries; } public bool Remove( TKey key ) { if(key == null) { ThrowHelper.ThrowArgumentNullException( ExceptionArgument.key ); } if(m_buckets != null) { int hashCode = m_comparer.GetHashCode( key ) & 0x7FFFFFFF; int bucket = hashCode % m_buckets.Length; int last = -1; for(int i = m_buckets[bucket]; i >= 0; last = i, i = m_entries[i].next) { if(m_entries[i].hashCode == hashCode && m_comparer.Equals( m_entries[i].key, key )) { if(last < 0) { m_buckets[bucket] = m_entries[i].next; } else { m_entries[last].next = m_entries[i].next; } m_entries[i].hashCode = -1; m_entries[i].next = m_freeList; m_entries[i].key = default( TKey ); m_entries[i].value = default( TValue ); m_freeList = i; m_freeCount++; m_version++; return true; } } } return false; } public bool TryGetValue( TKey key, out TValue value ) { int i = FindEntry( key ); if(i >= 0) { value = m_entries[i].value; return true; } value = default( TValue ); return false; } bool ICollection>.IsReadOnly { get { return false; } } void ICollection>.CopyTo( KeyValuePair[] array, int index ) { CopyTo( array, index ); } void ICollection.CopyTo( Array array, int index ) { if(array == null) { ThrowHelper.ThrowArgumentNullException( ExceptionArgument.array ); } if(array.Rank != 1) { ThrowHelper.ThrowArgumentException( ExceptionResource.Arg_RankMultiDimNotSupported ); } if(array.GetLowerBound( 0 ) != 0) { ThrowHelper.ThrowArgumentException( ExceptionResource.Arg_NonZeroLowerBound ); } if(index < 0 || index > array.Length) { ThrowHelper.ThrowArgumentOutOfRangeException( ExceptionArgument.index, ExceptionResource.ArgumentOutOfRange_NeedNonNegNum ); } if(array.Length - index < Count) { ThrowHelper.ThrowArgumentException( ExceptionResource.Arg_ArrayPlusOffTooSmall ); } KeyValuePair[] pairs = array as KeyValuePair[]; if(pairs != null) { CopyTo( pairs, index ); } else if(array is DictionaryEntry[]) { DictionaryEntry[] dictEntryArray = array as DictionaryEntry[]; Entry[] entries = m_entries; for(int i = 0; i < m_count; i++) { if(entries[i].hashCode >= 0) { dictEntryArray[index++] = new DictionaryEntry( entries[i].key, entries[i].value ); } } } else { object[] objects = array as object[]; if(objects == null) { ThrowHelper.ThrowArgumentException( ExceptionResource.Argument_InvalidArrayType ); } try { int count = m_count; Entry[] entries = m_entries; for(int i = 0; i < count; i++) { if(entries[i].hashCode >= 0) { objects[index++] = new KeyValuePair( entries[i].key, entries[i].value ); } } } catch(ArrayTypeMismatchException) { ThrowHelper.ThrowArgumentException( ExceptionResource.Argument_InvalidArrayType ); } } } IEnumerator IEnumerable.GetEnumerator() { return new Enumerator( this, Enumerator.KeyValuePair ); } bool ICollection.IsSynchronized { get { return false; } } object ICollection.SyncRoot { get { if(m_syncRoot == null) { System.Threading.Interlocked.CompareExchange( ref m_syncRoot, new Object(), null ); } return m_syncRoot; } } bool IDictionary.IsFixedSize { get { return false; } } bool IDictionary.IsReadOnly { get { return false; } } ICollection IDictionary.Keys { get { return (ICollection)Keys; } } ICollection IDictionary.Values { get { return (ICollection)Values; } } object IDictionary.this[object key] { get { if(IsCompatibleKey( key )) { int i = FindEntry( (TKey)key ); if(i >= 0) { return m_entries[i].value; } } return null; } set { if(key == null) { ThrowHelper.ThrowArgumentNullException( ExceptionArgument.key ); } ThrowHelper.IfNullAndNullsAreIllegalThenThrow( value, ExceptionArgument.value ); try { TKey tempKey = (TKey)key; try { this[tempKey] = (TValue)value; } catch(InvalidCastException) { ThrowHelper.ThrowWrongValueTypeArgumentException( value, typeof( TValue ) ); } } catch(InvalidCastException) { ThrowHelper.ThrowWrongKeyTypeArgumentException( key, typeof( TKey ) ); } } } private static bool IsCompatibleKey( object key ) { if(key == null) { ThrowHelper.ThrowArgumentNullException( ExceptionArgument.key ); } return (key is TKey); } void IDictionary.Add( object key, object value ) { if(key == null) { ThrowHelper.ThrowArgumentNullException( ExceptionArgument.key ); } ThrowHelper.IfNullAndNullsAreIllegalThenThrow( value, ExceptionArgument.value ); try { TKey tempKey = (TKey)key; try { Add( tempKey, (TValue)value ); } catch(InvalidCastException) { ThrowHelper.ThrowWrongValueTypeArgumentException( value, typeof( TValue ) ); } } catch(InvalidCastException) { ThrowHelper.ThrowWrongKeyTypeArgumentException( key, typeof( TKey ) ); } } bool IDictionary.Contains( object key ) { if(IsCompatibleKey( key )) { return ContainsKey( (TKey)key ); } return false; } IDictionaryEnumerator IDictionary.GetEnumerator() { return new Enumerator( this, Enumerator.DictEntry ); } void IDictionary.Remove( object key ) { if(IsCompatibleKey( key )) { Remove( (TKey)key ); } } [Serializable] public struct Enumerator : IEnumerator< KeyValuePair >, IDictionaryEnumerator { internal const int DictEntry = 1; internal const int KeyValuePair = 2; private Dictionary m_dictionary; private int m_version; private int m_index; private KeyValuePair m_current; private int m_getEnumeratorRetType; // What should Enumerator.Current return? internal Enumerator( Dictionary dictionary, int getEnumeratorRetType ) { m_dictionary = dictionary; m_version = dictionary.m_version; m_index = 0; m_getEnumeratorRetType = getEnumeratorRetType; m_current = new KeyValuePair(); } public bool MoveNext() { if(m_version != m_dictionary.m_version) { ThrowHelper.ThrowInvalidOperationException( ExceptionResource.InvalidOperation_EnumFailedVersion ); } // Use unsigned comparison since we set index to dictionary.count+1 when the enumeration ends. // dictionary.count+1 could be negative if dictionary.count is Int32.MaxValue while((uint)m_index < (uint)m_dictionary.m_count) { if(m_dictionary.m_entries[m_index].hashCode >= 0) { m_current = new KeyValuePair( m_dictionary.m_entries[m_index].key, m_dictionary.m_entries[m_index].value ); m_index++; return true; } m_index++; } m_index = m_dictionary.m_count + 1; m_current = new KeyValuePair(); return false; } public KeyValuePair Current { get { return m_current; } } public void Dispose() { } object IEnumerator.Current { get { if(m_index == 0 || (m_index == m_dictionary.m_count + 1)) { ThrowHelper.ThrowInvalidOperationException( ExceptionResource.InvalidOperation_EnumOpCantHappen ); } if(m_getEnumeratorRetType == DictEntry) { return new System.Collections.DictionaryEntry( m_current.Key, m_current.Value ); } else { return new KeyValuePair( m_current.Key, m_current.Value ); } } } void IEnumerator.Reset() { if(m_version != m_dictionary.m_version) { ThrowHelper.ThrowInvalidOperationException( ExceptionResource.InvalidOperation_EnumFailedVersion ); } m_index = 0; m_current = new KeyValuePair(); } DictionaryEntry IDictionaryEnumerator.Entry { get { if(m_index == 0 || (m_index == m_dictionary.m_count + 1)) { ThrowHelper.ThrowInvalidOperationException( ExceptionResource.InvalidOperation_EnumOpCantHappen ); } return new DictionaryEntry( m_current.Key, m_current.Value ); } } object IDictionaryEnumerator.Key { get { if(m_index == 0 || (m_index == m_dictionary.m_count + 1)) { ThrowHelper.ThrowInvalidOperationException( ExceptionResource.InvalidOperation_EnumOpCantHappen ); } return m_current.Key; } } object IDictionaryEnumerator.Value { get { if(m_index == 0 || (m_index == m_dictionary.m_count + 1)) { ThrowHelper.ThrowInvalidOperationException( ExceptionResource.InvalidOperation_EnumOpCantHappen ); } return m_current.Value; } } } //// [DebuggerTypeProxy( typeof( Mscorlib_DictionaryKeyCollectionDebugView<,> ) )] //// [DebuggerDisplay( "Count = {Count}" )] [Serializable] public sealed class KeyCollection : ICollection, ICollection { private Dictionary m_dictionary; public KeyCollection( Dictionary dictionary ) { if(dictionary == null) { ThrowHelper.ThrowArgumentNullException( ExceptionArgument.dictionary ); } m_dictionary = dictionary; } public Enumerator GetEnumerator() { return new Enumerator( m_dictionary ); } public void CopyTo( TKey[] array, int index ) { if(array == null) { ThrowHelper.ThrowArgumentNullException( ExceptionArgument.array ); } if(index < 0 || index > array.Length) { ThrowHelper.ThrowArgumentOutOfRangeException( ExceptionArgument.index, ExceptionResource.ArgumentOutOfRange_NeedNonNegNum ); } if(array.Length - index < m_dictionary.Count) { ThrowHelper.ThrowArgumentException( ExceptionResource.Arg_ArrayPlusOffTooSmall ); } int count = m_dictionary.m_count; Entry[] entries = m_dictionary.m_entries; for(int i = 0; i < count; i++) { if(entries[i].hashCode >= 0) array[index++] = entries[i].key; } } public int Count { get { return m_dictionary.Count; } } bool ICollection.IsReadOnly { get { return true; } } void ICollection.Add( TKey item ) { ThrowHelper.ThrowNotSupportedException( ExceptionResource.NotSupported_KeyCollectionSet ); } void ICollection.Clear() { ThrowHelper.ThrowNotSupportedException( ExceptionResource.NotSupported_KeyCollectionSet ); } bool ICollection.Contains( TKey item ) { return m_dictionary.ContainsKey( item ); } bool ICollection.Remove( TKey item ) { ThrowHelper.ThrowNotSupportedException( ExceptionResource.NotSupported_KeyCollectionSet ); return false; } IEnumerator IEnumerable.GetEnumerator() { return new Enumerator( m_dictionary ); } IEnumerator IEnumerable.GetEnumerator() { return new Enumerator( m_dictionary ); } void ICollection.CopyTo( Array array, int index ) { if(array == null) { ThrowHelper.ThrowArgumentNullException( ExceptionArgument.array ); } if(array.Rank != 1) { ThrowHelper.ThrowArgumentException( ExceptionResource.Arg_RankMultiDimNotSupported ); } if(array.GetLowerBound( 0 ) != 0) { ThrowHelper.ThrowArgumentException( ExceptionResource.Arg_NonZeroLowerBound ); } if(index < 0 || index > array.Length) { ThrowHelper.ThrowArgumentOutOfRangeException( ExceptionArgument.index, ExceptionResource.ArgumentOutOfRange_NeedNonNegNum ); } if(array.Length - index < m_dictionary.Count) { ThrowHelper.ThrowArgumentException( ExceptionResource.Arg_ArrayPlusOffTooSmall ); } TKey[] keys = array as TKey[]; if(keys != null) { CopyTo( keys, index ); } else { object[] objects = array as object[]; if(objects == null) { ThrowHelper.ThrowArgumentException( ExceptionResource.Argument_InvalidArrayType ); } int count = m_dictionary.m_count; Entry[] entries = m_dictionary.m_entries; try { for(int i = 0; i < count; i++) { if(entries[i].hashCode >= 0) objects[index++] = entries[i].key; } } catch(ArrayTypeMismatchException) { ThrowHelper.ThrowArgumentException( ExceptionResource.Argument_InvalidArrayType ); } } } bool ICollection.IsSynchronized { get { return false; } } Object ICollection.SyncRoot { get { return ((ICollection)m_dictionary).SyncRoot; } } [Serializable] public struct Enumerator : IEnumerator, IEnumerator { private Dictionary m_dictionary; private int m_index; private int m_version; private TKey m_currentKey; internal Enumerator( Dictionary dictionary ) { m_dictionary = dictionary; m_version = dictionary.m_version; m_index = 0; m_currentKey = default( TKey ); } public void Dispose() { } public bool MoveNext() { if(m_version != m_dictionary.m_version) { ThrowHelper.ThrowInvalidOperationException( ExceptionResource.InvalidOperation_EnumFailedVersion ); } while((uint)m_index < (uint)m_dictionary.m_count) { if(m_dictionary.m_entries[m_index].hashCode >= 0) { m_currentKey = m_dictionary.m_entries[m_index].key; m_index++; return true; } m_index++; } m_index = m_dictionary.m_count + 1; m_currentKey = default( TKey ); return false; } public TKey Current { get { return m_currentKey; } } Object System.Collections.IEnumerator.Current { get { if(m_index == 0 || (m_index == m_dictionary.m_count + 1)) { ThrowHelper.ThrowInvalidOperationException( ExceptionResource.InvalidOperation_EnumOpCantHappen ); } return m_currentKey; } } void System.Collections.IEnumerator.Reset() { if(m_version != m_dictionary.m_version) { ThrowHelper.ThrowInvalidOperationException( ExceptionResource.InvalidOperation_EnumFailedVersion ); } m_index = 0; m_currentKey = default( TKey ); } } } //// [DebuggerTypeProxy( typeof( Mscorlib_DictionaryValueCollectionDebugView<,> ) )] //// [DebuggerDisplay( "Count = {Count}" )] [Serializable] public sealed class ValueCollection : ICollection, ICollection { private Dictionary m_dictionary; public ValueCollection( Dictionary dictionary ) { if(dictionary == null) { ThrowHelper.ThrowArgumentNullException( ExceptionArgument.dictionary ); } m_dictionary = dictionary; } public Enumerator GetEnumerator() { return new Enumerator( m_dictionary ); } public void CopyTo( TValue[] array, int index ) { if(array == null) { ThrowHelper.ThrowArgumentNullException( ExceptionArgument.array ); } if(index < 0 || index > array.Length) { ThrowHelper.ThrowArgumentOutOfRangeException( ExceptionArgument.index, ExceptionResource.ArgumentOutOfRange_NeedNonNegNum ); } if(array.Length - index < m_dictionary.Count) { ThrowHelper.ThrowArgumentException( ExceptionResource.Arg_ArrayPlusOffTooSmall ); } int count = m_dictionary.m_count; Entry[] entries = m_dictionary.m_entries; for(int i = 0; i < count; i++) { if(entries[i].hashCode >= 0) array[index++] = entries[i].value; } } public int Count { get { return m_dictionary.Count; } } bool ICollection.IsReadOnly { get { return true; } } void ICollection.Add( TValue item ) { ThrowHelper.ThrowNotSupportedException( ExceptionResource.NotSupported_ValueCollectionSet ); } bool ICollection.Remove( TValue item ) { ThrowHelper.ThrowNotSupportedException( ExceptionResource.NotSupported_ValueCollectionSet ); return false; } void ICollection.Clear() { ThrowHelper.ThrowNotSupportedException( ExceptionResource.NotSupported_ValueCollectionSet ); } bool ICollection.Contains( TValue item ) { return m_dictionary.ContainsValue( item ); } IEnumerator IEnumerable.GetEnumerator() { return new Enumerator( m_dictionary ); } IEnumerator IEnumerable.GetEnumerator() { return new Enumerator( m_dictionary ); } void ICollection.CopyTo( Array array, int index ) { if(array == null) { ThrowHelper.ThrowArgumentNullException( ExceptionArgument.array ); } if(array.Rank != 1) { ThrowHelper.ThrowArgumentException( ExceptionResource.Arg_RankMultiDimNotSupported ); } if(array.GetLowerBound( 0 ) != 0) { ThrowHelper.ThrowArgumentException( ExceptionResource.Arg_NonZeroLowerBound ); } if(index < 0 || index > array.Length) { ThrowHelper.ThrowArgumentOutOfRangeException( ExceptionArgument.index, ExceptionResource.ArgumentOutOfRange_NeedNonNegNum ); } if(array.Length - index < m_dictionary.Count) { ThrowHelper.ThrowArgumentException( ExceptionResource.Arg_ArrayPlusOffTooSmall ); } TValue[] values = array as TValue[]; if(values != null) { CopyTo( values, index ); } else { object[] objects = array as object[]; if(objects == null) { ThrowHelper.ThrowArgumentException( ExceptionResource.Argument_InvalidArrayType ); } int count = m_dictionary.m_count; Entry[] entries = m_dictionary.m_entries; try { for(int i = 0; i < count; i++) { if(entries[i].hashCode >= 0) objects[index++] = entries[i].value; } } catch(ArrayTypeMismatchException) { ThrowHelper.ThrowArgumentException( ExceptionResource.Argument_InvalidArrayType ); } } } bool ICollection.IsSynchronized { get { return false; } } Object ICollection.SyncRoot { get { return ((ICollection)m_dictionary).SyncRoot; } } [Serializable] public struct Enumerator : IEnumerator, IEnumerator { private Dictionary m_dictionary; private int m_index; private int m_version; private TValue m_currentValue; internal Enumerator( Dictionary dictionary ) { m_dictionary = dictionary; m_version = dictionary.m_version; m_index = 0; m_currentValue = default( TValue ); } public void Dispose() { } public bool MoveNext() { if(m_version != m_dictionary.m_version) { ThrowHelper.ThrowInvalidOperationException( ExceptionResource.InvalidOperation_EnumFailedVersion ); } while((uint)m_index < (uint)m_dictionary.m_count) { if(m_dictionary.m_entries[m_index].hashCode >= 0) { m_currentValue = m_dictionary.m_entries[m_index].value; m_index++; return true; } m_index++; } m_index = m_dictionary.m_count + 1; m_currentValue = default( TValue ); return false; } public TValue Current { get { return m_currentValue; } } Object System.Collections.IEnumerator.Current { get { if(m_index == 0 || (m_index == m_dictionary.m_count + 1)) { ThrowHelper.ThrowInvalidOperationException( ExceptionResource.InvalidOperation_EnumOpCantHappen ); } return m_currentValue; } } void System.Collections.IEnumerator.Reset() { if(m_version != m_dictionary.m_version) { ThrowHelper.ThrowInvalidOperationException( ExceptionResource.InvalidOperation_EnumFailedVersion ); } m_index = 0; m_currentValue = default( TValue ); } } } } } ================================================ FILE: Zelig/Zelig/RunTime/Framework/mscorlib/System/Collections/Generic/EqualityComparer.cs ================================================ // ==++== // // Copyright (c) Microsoft Corporation. All rights reserved. // // ==--== namespace System.Collections.Generic { using System; using System.Collections; using System.Collections.Generic; using System.Globalization; using System.Runtime.CompilerServices; [Serializable] ////[TypeDependencyAttribute( "System.Collections.Generic.GenericEqualityComparer`1" )] [Microsoft.Zelig.Internals.WellKnownType( "System_Collections_Generic_EqualityComparer_of_T" )] [Microsoft.Zelig.Internals.TypeDependency( typeof(System.Collections.Generic.GenericEqualityComparer<>) )] public abstract class EqualityComparer : IEqualityComparer, IEqualityComparer { static EqualityComparer defaultComparer; public static EqualityComparer Default { get { EqualityComparer comparer = defaultComparer; if(comparer == null) { comparer = CreateComparer(); defaultComparer = comparer; } return comparer; } } [MethodImpl( MethodImplOptions.InternalCall )] private static extern EqualityComparer CreateComparer(); //// { //// Type t = typeof( T ); //// //// // Specialize type byte for performance reasons //// if(t == typeof( byte )) //// { //// return (EqualityComparer)(object)(new ByteEqualityComparer()); //// } //// //// // If T implements IEquatable return a GenericEqualityComparer //// if(typeof( IEquatable ).IsAssignableFrom( t )) //// { //// //return (EqualityComparer)Activator.CreateInstance(typeof(GenericEqualityComparer<>).MakeGenericType(t)); //// return (EqualityComparer)(typeof( GenericEqualityComparer ).TypeHandle.CreateInstanceForAnotherGenericParameter( t )); //// } //// //// // If T is a Nullable where U implements IEquatable return a NullableEqualityComparer //// if(t.IsGenericType && t.GetGenericTypeDefinition() == typeof( Nullable<> )) //// { //// Type u = t.GetGenericArguments()[0]; //// if(typeof( IEquatable<> ).MakeGenericType( u ).IsAssignableFrom( u )) //// { //// //return (EqualityComparer)Activator.CreateInstance(typeof(NullableEqualityComparer<>).MakeGenericType(u)); //// return (EqualityComparer)(typeof( NullableEqualityComparer ).TypeHandle.CreateInstanceForAnotherGenericParameter( u )); //// } //// } //// //// // Otherwise return an ObjectEqualityComparer //// return new ObjectEqualityComparer(); //// } public abstract bool Equals( T x, T y ); public abstract int GetHashCode( T obj ); internal virtual int IndexOf( T[] array, T value, int startIndex, int count ) { int endIndex = startIndex + count; for(int i = startIndex; i < endIndex; i++) { if(Equals( array[i], value )) return i; } return -1; } internal virtual int LastIndexOf( T[] array, T value, int startIndex, int count ) { int endIndex = startIndex - count + 1; for(int i = startIndex; i >= endIndex; i--) { if(Equals( array[i], value )) return i; } return -1; } int IEqualityComparer.GetHashCode( object obj ) { if(obj == null) return 0; if(obj is T) return GetHashCode( (T)obj ); ThrowHelper.ThrowArgumentException( ExceptionResource.Argument_InvalidArgumentForComparison ); return 0; } bool IEqualityComparer.Equals( object x, object y ) { if(x == y) return true; if(x == null || y == null) return false; if((x is T) && (y is T)) return Equals( (T)x, (T)y ); ThrowHelper.ThrowArgumentException( ExceptionResource.Argument_InvalidArgumentForComparison ); return false; } } // The methods in this class look identical to the inherited methods, but the calls // to Equal bind to IEquatable.Equals(T) instead of Object.Equals(Object) [Serializable] [Microsoft.Zelig.Internals.WellKnownType( "System_Collections_Generic_GenericEqualityComparer_of_T" )] internal class GenericEqualityComparer : EqualityComparer where T : IEquatable { public override bool Equals( T x, T y ) { if(x != null) { if(y != null) return x.Equals( y ); return false; } if(y != null) return false; return true; } public override int GetHashCode( T obj ) { if(obj == null) return 0; return obj.GetHashCode(); } internal override int IndexOf( T[] array, T value, int startIndex, int count ) { int endIndex = startIndex + count; if(value == null) { for(int i = startIndex; i < endIndex; i++) { if(array[i] == null) return i; } } else { for(int i = startIndex; i < endIndex; i++) { if(array[i] != null && array[i].Equals( value )) return i; } } return -1; } internal override int LastIndexOf( T[] array, T value, int startIndex, int count ) { int endIndex = startIndex - count + 1; if(value == null) { for(int i = startIndex; i >= endIndex; i--) { if(array[i] == null) return i; } } else { for(int i = startIndex; i >= endIndex; i--) { if(array[i] != null && array[i].Equals( value )) return i; } } return -1; } // Equals method for the comparer itself. public override bool Equals( Object obj ) { GenericEqualityComparer comparer = obj as GenericEqualityComparer; return comparer != null; } public override int GetHashCode() { return this.GetType().Name.GetHashCode(); } } [Serializable] [Microsoft.Zelig.Internals.WellKnownType( "System_Collections_Generic_NullableEqualityComparer_of_T" )] internal class NullableEqualityComparer : EqualityComparer< Nullable > where T : struct, IEquatable { public override bool Equals( Nullable x, Nullable y ) { if(x.HasValue) { if(y.HasValue) return x.value.Equals( y.value ); return false; } if(y.HasValue) return false; return true; } public override int GetHashCode( Nullable obj ) { return obj.GetHashCode(); } internal override int IndexOf( Nullable[] array, Nullable value, int startIndex, int count ) { int endIndex = startIndex + count; if(!value.HasValue) { for(int i = startIndex; i < endIndex; i++) { if(!array[i].HasValue) return i; } } else { for(int i = startIndex; i < endIndex; i++) { if(array[i].HasValue && array[i].value.Equals( value.value )) return i; } } return -1; } internal override int LastIndexOf( Nullable[] array, Nullable value, int startIndex, int count ) { int endIndex = startIndex - count + 1; if(!value.HasValue) { for(int i = startIndex; i >= endIndex; i--) { if(!array[i].HasValue) return i; } } else { for(int i = startIndex; i >= endIndex; i--) { if(array[i].HasValue && array[i].value.Equals( value.value )) return i; } } return -1; } // Equals method for the comparer itself. public override bool Equals( Object obj ) { NullableEqualityComparer comparer = obj as NullableEqualityComparer; return comparer != null; } public override int GetHashCode() { return this.GetType().Name.GetHashCode(); } } [Serializable] [Microsoft.Zelig.Internals.WellKnownType( "System_Collections_Generic_ObjectEqualityComparer_of_T" )] internal class ObjectEqualityComparer : EqualityComparer { public override bool Equals( T x, T y ) { if(x != null) { if(y != null) return x.Equals( y ); return false; } if(y != null) return false; return true; } public override int GetHashCode( T obj ) { if(obj == null) return 0; return obj.GetHashCode(); } internal override int IndexOf( T[] array, T value, int startIndex, int count ) { int endIndex = startIndex + count; if(value == null) { for(int i = startIndex; i < endIndex; i++) { if(array[i] == null) return i; } } else { for(int i = startIndex; i < endIndex; i++) { if(array[i] != null && array[i].Equals( value )) return i; } } return -1; } internal override int LastIndexOf( T[] array, T value, int startIndex, int count ) { int endIndex = startIndex - count + 1; if(value == null) { for(int i = startIndex; i >= endIndex; i--) { if(array[i] == null) return i; } } else { for(int i = startIndex; i >= endIndex; i--) { if(array[i] != null && array[i].Equals( value )) return i; } } return -1; } // Equals method for the comparer itself. public override bool Equals( Object obj ) { ObjectEqualityComparer comparer = obj as ObjectEqualityComparer; return comparer != null; } public override int GetHashCode() { return this.GetType().Name.GetHashCode(); } } // Performance of IndexOf on byte array is very important for some scenarios. // We will call the C runtime function memchr, which is optimized. [Serializable] internal class ByteEqualityComparer : EqualityComparer { public override bool Equals( byte x, byte y ) { return x == y; } public override int GetHashCode( byte b ) { return b.GetHashCode( ); } } //// internal unsafe override int IndexOf( byte[] array, byte value, int startIndex, int count ) //// { //// if(array == null) //// { //// throw new ArgumentNullException( "array" ); //// } //// //// if(startIndex < 0) //// { //// throw new ArgumentOutOfRangeException( "startIndex", Environment.GetResourceString( "ArgumentOutOfRange_Index" ) ); //// } //// //// if(count < 0) //// { //// throw new ArgumentOutOfRangeException( "count", Environment.GetResourceString( "ArgumentOutOfRange_Count" ) ); //// } //// //// if(count > array.Length - startIndex) //// { //// throw new ArgumentException( Environment.GetResourceString( "Argument_InvalidOffLen" ) ); //// } //// //// if(count == 0) return -1; //// //// fixed(byte* pbytes = array) //// { //// return Buffer.IndexOfByte( pbytes, value, startIndex, count ); //// } //// } //// //// internal override int LastIndexOf( byte[] array, byte value, int startIndex, int count ) //// { //// int endIndex = startIndex - count + 1; //// for(int i = startIndex; i >= endIndex; i--) //// { //// if(array[i] == value) return i; //// } //// return -1; //// } //// //// // Equals method for the comparer itself. //// public override bool Equals( Object obj ) //// { //// ByteEqualityComparer comparer = obj as ByteEqualityComparer; //// return comparer != null; //// } //// //// public override int GetHashCode() //// { //// return this.GetType().Name.GetHashCode(); //// } [Serializable] [Microsoft.Zelig.Internals.WellKnownType( "System_Collections_Generic_EqualityComparer_of_Enum" )] internal class EnumEqualityComparer : EqualityComparer where T : struct { public override bool Equals(T x, T y) { int x_final = System.Runtime.CompilerServices.JitHelpers.UnsafeEnumCast(x); int y_final = System.Runtime.CompilerServices.JitHelpers.UnsafeEnumCast(y); return x_final == y_final; } public override int GetHashCode(T obj) { int x_final = System.Runtime.CompilerServices.JitHelpers.UnsafeEnumCast(obj); return x_final.GetHashCode(); } } [Serializable] [Microsoft.Zelig.Internals.WellKnownType( "System_Collections_Generic_EqualityComparer_of_Enum_sbyte" )] internal class SByteEnumEqualityComparer : EnumEqualityComparer where T : struct { public override int GetHashCode( T obj ) { int x_final = System.Runtime.CompilerServices.JitHelpers.UnsafeEnumCast(obj); return ((sbyte)x_final).GetHashCode( ); } } [Serializable] [Microsoft.Zelig.Internals.WellKnownType( "System_Collections_Generic_EqualityComparer_of_Enum_short" )] internal class ShortEnumEqualityComparer : EnumEqualityComparer where T : struct { public override int GetHashCode( T obj ) { int x_final = System.Runtime.CompilerServices.JitHelpers.UnsafeEnumCast(obj); return ((short)x_final).GetHashCode( ); } } [Serializable] [Microsoft.Zelig.Internals.WellKnownType( "System_Collections_Generic_EqualityComparer_of_Enum_long" )] internal class LongEnumEqualityComparer : EqualityComparer where T : struct { public override bool Equals(T x, T y) { long x_final = System.Runtime.CompilerServices.JitHelpers.UnsafeEnumCastLong(x); long y_final = System.Runtime.CompilerServices.JitHelpers.UnsafeEnumCastLong(y); return x_final == y_final; } public override int GetHashCode(T obj) { long x_final = System.Runtime.CompilerServices.JitHelpers.UnsafeEnumCastLong(obj); return x_final.GetHashCode(); } } } ================================================ FILE: Zelig/Zelig/RunTime/Framework/mscorlib/System/Collections/Generic/ICollection.cs ================================================ // ==++== // // Copyright (c) Microsoft Corporation. All rights reserved. // // ==--== /*============================================================ ** ** Interface: ICollection ** ** ** Purpose: Base interface for all generic collections. ** ** ===========================================================*/ namespace System.Collections.Generic { using System; using System.Runtime.CompilerServices; // Base interface for all collections, defining enumerators, size, and // synchronization methods. // Note that T[] : IList, and we want to ensure that if you use // IList, we ensure a YourValueType[] can be used // without jitting. Hence the TypeDependencyAttribute on SZArrayHelper. // This is a special hack internally though - see VM\compile.cpp. // The same attribute is on IEnumerable and ICollection. [Microsoft.Zelig.Internals.WellKnownType( "System_Collections_Generic_ICollection_of_T" )] ////[TypeDependencyAttribute( "System.SZArrayHelper" )] public interface ICollection : IEnumerable { // Interfaces are not serialable // Number of items in the collections. int Count { get; } bool IsReadOnly { get; } void Add( T item ); void Clear(); bool Contains( T item ); // CopyTo copies a collection into an Array, starting at a particular // index into the array. // void CopyTo( T[] array, int arrayIndex ); //void CopyTo(int sourceIndex, T[] destinationArray, int destinationIndex, int count); bool Remove( T item ); } } ================================================ FILE: Zelig/Zelig/RunTime/Framework/mscorlib/System/Collections/Generic/IComparer.cs ================================================ // ==++== // // Copyright (c) Microsoft Corporation. All rights reserved. // // ==--== /*============================================================ ** ** Interface: IComparer ** ** ** Purpose: Interface for comparing two generic Objects. ** ** ===========================================================*/ namespace System.Collections.Generic { using System; // The generic IComparer interface implements a method that compares // two objects. It is used in conjunction with the Sort and // BinarySearch methods on the Array, List, and SortedList classes. public interface IComparer { // Compares two objects. An implementation of this method must return a // value less than zero if x is less than y, zero if x is equal to y, or a // value greater than zero if x is greater than y. // int Compare( T x, T y ); } } ================================================ FILE: Zelig/Zelig/RunTime/Framework/mscorlib/System/Collections/Generic/IDictionary.cs ================================================ // ==++== // // Copyright (c) Microsoft Corporation. All rights reserved. // // ==--== /*============================================================ ** ** Interface: IDictionary ** ** ** Purpose: Base interface for all generic dictionaries. ** ** ===========================================================*/ namespace System.Collections.Generic { using System; // An IDictionary is a possibly unordered set of key-value pairs. // Keys can be any non-null object. Values can be any object. // You can look up a value in an IDictionary via the default indexed // property, Items. public interface IDictionary : ICollection< KeyValuePair > { // Interfaces are not serializable // The Item property provides methods to read and edit entries // in the Dictionary. TValue this[TKey key] { get; set; } // Returns a collections of the keys in this dictionary. ICollection Keys { get; } // Returns a collections of the values in this dictionary. ICollection Values { get; } // Returns whether this dictionary contains a particular key. // bool ContainsKey( TKey key ); // Adds a key-value pair to the dictionary. // void Add( TKey key, TValue value ); // Removes a particular key from the dictionary. // bool Remove( TKey key ); bool TryGetValue( TKey key, out TValue value ); } } ================================================ FILE: Zelig/Zelig/RunTime/Framework/mscorlib/System/Collections/Generic/IEnumerable.cs ================================================ // ==++== // // Copyright (c) Microsoft Corporation. All rights reserved. // // ==--== /*============================================================ ** ** Interface: IEnumerable ** ** ** Purpose: Interface for providing generic IEnumerators ** ** ===========================================================*/ namespace System.Collections.Generic { using System; using System.Collections; using System.Runtime.InteropServices; using System.Runtime.CompilerServices; // Implement this interface if you need to support foreach semantics. // Note that T[] : IList, and we want to ensure that if you use // IList, we ensure a YourValueType[] can be used // without jitting. Hence the TypeDependencyAttribute on SZArrayHelper. // This is a special hack internally though - see VM\compile.cpp. // The same attribute is on IList and ICollection. [Microsoft.Zelig.Internals.WellKnownType( "System_Collections_Generic_IEnumerable_of_T" )] ////[TypeDependencyAttribute( "System.SZArrayHelper" )] public interface IEnumerable : IEnumerable { // Interfaces are not serializable // Returns an IEnumerator for this enumerable Object. The enumerator provides // a simple way to access all the contents of a collection. /// new IEnumerator GetEnumerator(); } } ================================================ FILE: Zelig/Zelig/RunTime/Framework/mscorlib/System/Collections/Generic/IEnumerator.cs ================================================ // ==++== // // Copyright (c) Microsoft Corporation. All rights reserved. // // ==--== /*============================================================ ** ** Interface: IEnumerator ** ** ** Purpose: Base interface for all generic enumerators. ** ** ===========================================================*/ namespace System.Collections.Generic { using System; using System.Runtime.InteropServices; // Base interface for all generic enumerators, providing a simple approach // to iterating over a collection. public interface IEnumerator : IDisposable, IEnumerator { // Returns the current element of the enumeration. The returned value is // undefined before the first call to MoveNext and following a // call to MoveNext that returned false. Multiple calls to // GetCurrent with no intervening calls to MoveNext // will return the same object. // /// new T Current { get; } } } ================================================ FILE: Zelig/Zelig/RunTime/Framework/mscorlib/System/Collections/Generic/IEqualityComparer.cs ================================================ // ==++== // // Copyright (c) Microsoft Corporation. All rights reserved. // // ==--== namespace System.Collections.Generic { using System; // The generic IEqualityComparer interface implements methods to if check two objects are equal // and generate Hashcode for an object. // It is use in Dictionary class. public interface IEqualityComparer { bool Equals( T x, T y ); int GetHashCode( T obj ); } } ================================================ FILE: Zelig/Zelig/RunTime/Framework/mscorlib/System/Collections/Generic/IList.cs ================================================ // ==++== // // Copyright (c) Microsoft Corporation. All rights reserved. // // ==--== /*============================================================ ** ** Interface: IList ** ** ** Purpose: Base interface for all generic lists. ** ** ===========================================================*/ namespace System.Collections.Generic { using System; using System.Runtime.CompilerServices; // An IList is an ordered collection of objects. The exact ordering // is up to the implementation of the list, ranging from a sorted // order to insertion order. // Note that T[] : IList, and we want to ensure that if you use // IList, we ensure a YourValueType[] can be used // without jitting. Hence the TypeDependencyAttribute on SZArrayHelper. // This is a special hack internally though - see VM\compile.cpp. // The same attribute is on IEnumerable and ICollection. [Microsoft.Zelig.Internals.WellKnownType( "System_Collections_Generic_IList_of_T" )] ////[TypeDependencyAttribute("System.SZArrayHelper")] public interface IList : ICollection { // The Item property provides methods to read and edit entries in the List. T this[int index] { get; set; } // Returns the index of a particular item, if it is in the list. // Returns -1 if the item isn't in the list. int IndexOf(T item); // Inserts value into the list at position index. // index must be non-negative and less than or equal to the // number of elements in the list. If index equals the number // of items in the list, then value is appended to the end. void Insert(int index, T item); // Removes the item at position index. void RemoveAt(int index); } } ================================================ FILE: Zelig/Zelig/RunTime/Framework/mscorlib/System/Collections/Generic/KeyNotFoundException.cs ================================================ // ==++== // // Copyright (c) Microsoft Corporation. All rights reserved. // // ==--== /*============================================================================= ** ** Class: KeyNotFoundException ** ** ** Purpose: Exception class for Hashtable and Dictionary. ** ** =============================================================================*/ namespace System.Collections.Generic { using System; ////using System.Runtime.Remoting; using System.Runtime.Serialization; [Serializable] public class KeyNotFoundException : SystemException /*, ISerializable*/ { #if EXCEPTION_STRINGS public KeyNotFoundException() : base( Environment.GetResourceString( "Arg_KeyNotFound" ) ) #else public KeyNotFoundException() #endif { } public KeyNotFoundException( String message ) : base( message ) { } public KeyNotFoundException( String message, Exception innerException ) : base( message, innerException ) { } //// protected KeyNotFoundException( SerializationInfo info, StreamingContext context ) : base( info, context ) //// { //// } } } ================================================ FILE: Zelig/Zelig/RunTime/Framework/mscorlib/System/Collections/Generic/KeyValuePair.cs ================================================ // ==++== // // Copyright (c) Microsoft Corporation. All rights reserved. // // ==--== /*============================================================ ** ** Interface: KeyValuePair ** ** ** Purpose: Generic key-value pair for dictionary enumerators. ** ** ===========================================================*/ namespace System.Collections.Generic { using System; ////using System.Text; // A KeyValuePair holds a key and a value from a dictionary. // It is returned by IDictionaryEnumerator::GetEntry(). [Serializable] public struct KeyValuePair< TKey, TValue > { private TKey m_key; private TValue m_value; public KeyValuePair( TKey key, TValue value ) { m_key = key; m_value = value; } public TKey Key { get { return m_key; } } public TValue Value { get { return m_value; } } //// public override string ToString() //// { //// StringBuilder s = new StringBuilder(); //// //// s.Append( '[' ); //// //// if(Key != null) //// { //// s.Append( Key.ToString() ); //// } //// //// s.Append( ", " ); //// //// if(Value != null) //// { //// s.Append( Value.ToString() ); //// } //// //// s.Append( ']' ); //// //// return s.ToString(); //// } } } ================================================ FILE: Zelig/Zelig/RunTime/Framework/mscorlib/System/Collections/Generic/List.cs ================================================ // ==++== // // Copyright (c) Microsoft Corporation. All rights reserved. // // ==--== /*============================================================ ** ** Class: List ** ** Purpose: Implements a generic, dynamically sized list as an ** array. ** ** ===========================================================*/ namespace System.Collections.Generic { using System; using System.Diagnostics; using System.Collections.ObjectModel; ////using System.Security.Permissions; // Implements a variable-size List that uses an array of objects to store the // elements. A List has a capacity, which is the allocated length // of the internal array. As elements are added to a List, the capacity // of the List is automatically increased as required by reallocating the // internal array. // ////[DebuggerTypeProxy( typeof( Mscorlib_CollectionDebugView<> ) )] ////[DebuggerDisplay( "Count = {Count}" )] [Serializable] public class List : IList, System.Collections.IList { private const int cDefaultCapacity = 4; static readonly T[] sEmptyArray = new T[0]; private T[] m_items; private int m_size; private int m_version; [NonSerialized] private Object m_syncRoot; // Constructs a List. The list is initially empty and has a capacity // of zero. Upon adding the first element to the list the capacity is // increased to 16, and then increased in multiples of two as required. public List() { m_items = sEmptyArray; } // Constructs a List with a given initial capacity. The list is // initially empty, but will have room for the given number of elements // before any reallocations are required. // public List( int capacity ) { if(capacity < 0) { ThrowHelper.ThrowArgumentOutOfRangeException( ExceptionArgument.capacity, ExceptionResource.ArgumentOutOfRange_NeedNonNegNum ); } m_items = new T[capacity]; } // Constructs a List, copying the contents of the given collection. The // size and capacity of the new list will both be equal to the size of the // given collection. // public List( IEnumerable collection ) { if(collection == null) { ThrowHelper.ThrowArgumentNullException( ExceptionArgument.collection ); } ICollection c = collection as ICollection; if(c != null) { int count = c.Count; m_items = new T[count]; c.CopyTo( m_items, 0 ); m_size = count; } else { m_size = 0; m_items = new T[cDefaultCapacity]; using(IEnumerator en = collection.GetEnumerator()) { while(en.MoveNext()) { Add( en.Current ); } } } } // Gets and sets the capacity of this list. The capacity is the size of // the internal array used to hold items. When set, the internal // array of the list is reallocated to the given capacity. // public int Capacity { get { return m_items.Length; } set { if(value != m_items.Length) { if(value < m_size) { ThrowHelper.ThrowArgumentOutOfRangeException( ExceptionArgument.value, ExceptionResource.ArgumentOutOfRange_SmallCapacity ); } if(value > 0) { T[] newItems = new T[value]; if(m_size > 0) { Array.Copy( m_items, 0, newItems, 0, m_size ); } m_items = newItems; } else { m_items = sEmptyArray; } } } } // Read-only property describing how many elements are in the List. public int Count { get { return m_size; } } bool System.Collections.IList.IsFixedSize { get { return false; } } // Is this List read-only? bool ICollection.IsReadOnly { get { return false; } } bool System.Collections.IList.IsReadOnly { get { return false; } } // Is this List synchronized (thread-safe)? bool System.Collections.ICollection.IsSynchronized { get { return false; } } // Synchronization root for this object. Object System.Collections.ICollection.SyncRoot { get { if(m_syncRoot == null) { System.Threading.Interlocked.CompareExchange( ref m_syncRoot, new Object(), null ); } return m_syncRoot; } } // Sets or Gets the element at the given index. // public T this[int index] { get { // Fllowing trick can reduce the range check by one if((uint)index >= (uint)m_size) { ThrowHelper.ThrowArgumentOutOfRangeException(); } return m_items[index]; } set { if((uint)index >= (uint)m_size) { ThrowHelper.ThrowArgumentOutOfRangeException(); } m_items[index] = value; m_version++; } } private static bool IsCompatibleObject( object value ) { // Non-null values are fine. Only accept nulls if T is a class or Nullable. // Note that default(T) is not equal to null for value types except when T is Nullable. return ((value is T) || (value == null && default( T ) == null)); } Object System.Collections.IList.this[int index] { get { return this[index]; } set { ThrowHelper.IfNullAndNullsAreIllegalThenThrow( value, ExceptionArgument.value ); try { this[index] = (T)value; } catch(InvalidCastException) { ThrowHelper.ThrowWrongValueTypeArgumentException( value, typeof( T ) ); } } } // Adds the given object to the end of this list. The size of the list is // increased by one. If required, the capacity of the list is doubled // before adding the new element. // public void Add( T item ) { if(m_size == m_items.Length) { EnsureCapacity( m_size + 1 ); } m_items[m_size++] = item; m_version++; } int System.Collections.IList.Add( Object item ) { ThrowHelper.IfNullAndNullsAreIllegalThenThrow( item, ExceptionArgument.item ); try { Add( (T)item ); } catch(InvalidCastException) { ThrowHelper.ThrowWrongValueTypeArgumentException( item, typeof( T ) ); } return Count - 1; } // Adds the elements of the given collection to the end of this list. If // required, the capacity of the list is increased to twice the previous // capacity or the new size, whichever is larger. // public void AddRange( IEnumerable collection ) { InsertRange( m_size, collection ); } public ReadOnlyCollection AsReadOnly() { return new ReadOnlyCollection( this ); } // Searches a section of the list for a given element using a binary search // algorithm. Elements of the list are compared to the search value using // the given IComparer interface. If comparer is null, elements of // the list are compared to the search value using the IComparable // interface, which in that case must be implemented by all elements of the // list and the given search value. This method assumes that the given // section of the list is already sorted; if this is not the case, the // result will be incorrect. // // The method returns the index of the given value in the list. If the // list does not contain the given value, the method returns a negative // integer. The bitwise complement operator (~) can be applied to a // negative result to produce the index of the first element (if any) that // is larger than the given search value. This is also the index at which // the search value should be inserted into the list in order for the list // to remain sorted. // // The method uses the Array.BinarySearch method to perform the // search. // public int BinarySearch( int index, int count, T item, IComparer comparer ) { if(index < 0 || count < 0) { ThrowHelper.ThrowArgumentOutOfRangeException( (index < 0 ? ExceptionArgument.index : ExceptionArgument.count), ExceptionResource.ArgumentOutOfRange_NeedNonNegNum ); } if(m_size - index < count) { ThrowHelper.ThrowArgumentException( ExceptionResource.Argument_InvalidOffLen ); } return Array.BinarySearch( m_items, index, count, item, comparer ); } public int BinarySearch( T item ) { return BinarySearch( 0, Count, item, null ); } public int BinarySearch( T item, IComparer comparer ) { return BinarySearch( 0, Count, item, comparer ); } // Clears the contents of List. public void Clear() { if(m_size > 0) { Array.Clear( m_items, 0, m_size ); // Don't need to doc this but we clear the elements so that the gc can reclaim the references. m_size = 0; } m_version++; } // Contains returns true if the specified element is in the List. // It does a linear, O(n) search. Equality is determined by calling // item.Equals(). // public bool Contains( T item ) { if((Object)item == null) { for(int i = 0; i < m_size; i++) { if((Object)m_items[i] == null) { return true; } } return false; } else { EqualityComparer c = EqualityComparer.Default; for(int i = 0; i < m_size; i++) { if(c.Equals( m_items[i], item )) return true; } return false; } } bool System.Collections.IList.Contains( Object item ) { if(IsCompatibleObject( item )) { return Contains( (T)item ); } return false; } public List ConvertAll( Converter converter ) { if(converter == null) { ThrowHelper.ThrowArgumentNullException( ExceptionArgument.converter ); } List list = new List( m_size ); for(int i = 0; i < m_size; i++) { list.m_items[i] = converter( m_items[i] ); } list.m_size = m_size; return list; } // Copies this List into array, which must be of a // compatible array type. // public void CopyTo( T[] array ) { CopyTo( array, 0 ); } // Copies this List into array, which must be of a // compatible array type. // void System.Collections.ICollection.CopyTo( Array array, int arrayIndex ) { if((array != null) && (array.Rank != 1)) { ThrowHelper.ThrowArgumentException( ExceptionResource.Arg_RankMultiDimNotSupported ); } try { // Array.Copy will check for NULL. Array.Copy( m_items, 0, array, arrayIndex, m_size ); } catch(ArrayTypeMismatchException) { ThrowHelper.ThrowArgumentException( ExceptionResource.Argument_InvalidArrayType ); } } // Copies a section of this list to the given array at the given index. // // The method uses the Array.Copy method to copy the elements. // public void CopyTo( int index, T[] array, int arrayIndex, int count ) { if(m_size - index < count) { ThrowHelper.ThrowArgumentException( ExceptionResource.Argument_InvalidOffLen ); } // Delegate rest of error checking to Array.Copy. Array.Copy( m_items, index, array, arrayIndex, count ); } public void CopyTo( T[] array, int arrayIndex ) { // Delegate rest of error checking to Array.Copy. Array.Copy( m_items, 0, array, arrayIndex, m_size ); } // Ensures that the capacity of this list is at least the given minimum // value. If the currect capacity of the list is less than min, the // capacity is increased to twice the current capacity or to min, // whichever is larger. private void EnsureCapacity( int min ) { if(m_items.Length < min) { int newCapacity = m_items.Length == 0 ? cDefaultCapacity : m_items.Length * 2; if(newCapacity < min) newCapacity = min; Capacity = newCapacity; } } public bool Exists( Predicate match ) { return FindIndex( match ) != -1; } public T Find( Predicate match ) { if(match == null) { ThrowHelper.ThrowArgumentNullException( ExceptionArgument.match ); } for(int i = 0; i < m_size; i++) { if(match( m_items[i] )) { return m_items[i]; } } return default( T ); } public List FindAll( Predicate match ) { if(match == null) { ThrowHelper.ThrowArgumentNullException( ExceptionArgument.match ); } List list = new List(); for(int i = 0; i < m_size; i++) { if(match( m_items[i] )) { list.Add( m_items[i] ); } } return list; } public int FindIndex( Predicate match ) { return FindIndex( 0, m_size, match ); } public int FindIndex( int startIndex, Predicate match ) { return FindIndex( startIndex, m_size - startIndex, match ); } public int FindIndex( int startIndex, int count, Predicate match ) { if((uint)startIndex > (uint)m_size) { ThrowHelper.ThrowArgumentOutOfRangeException( ExceptionArgument.startIndex, ExceptionResource.ArgumentOutOfRange_Index ); } if(count < 0 || startIndex > m_size - count) { ThrowHelper.ThrowArgumentOutOfRangeException( ExceptionArgument.count, ExceptionResource.ArgumentOutOfRange_Count ); } if(match == null) { ThrowHelper.ThrowArgumentNullException( ExceptionArgument.match ); } int endIndex = startIndex + count; for(int i = startIndex; i < endIndex; i++) { if(match( m_items[i] )) return i; } return -1; } public T FindLast( Predicate match ) { if(match == null) { ThrowHelper.ThrowArgumentNullException( ExceptionArgument.match ); } for(int i = m_size - 1; i >= 0; i--) { if(match( m_items[i] )) { return m_items[i]; } } return default( T ); } public int FindLastIndex( Predicate match ) { return FindLastIndex( m_size - 1, m_size, match ); } public int FindLastIndex( int startIndex, Predicate match ) { return FindLastIndex( startIndex, startIndex + 1, match ); } public int FindLastIndex( int startIndex, int count, Predicate match ) { if(match == null) { ThrowHelper.ThrowArgumentNullException( ExceptionArgument.match ); } if(m_size == 0) { // Special case for 0 length List if(startIndex != -1) { ThrowHelper.ThrowArgumentOutOfRangeException( ExceptionArgument.startIndex, ExceptionResource.ArgumentOutOfRange_Index ); } } else { // Make sure we're not out of range if((uint)startIndex >= (uint)m_size) { ThrowHelper.ThrowArgumentOutOfRangeException( ExceptionArgument.startIndex, ExceptionResource.ArgumentOutOfRange_Index ); } } // 2nd have of this also catches when startIndex == MAXINT, so MAXINT - 0 + 1 == -1, which is < 0. if(count < 0 || startIndex - count + 1 < 0) { ThrowHelper.ThrowArgumentOutOfRangeException( ExceptionArgument.count, ExceptionResource.ArgumentOutOfRange_Count ); } int endIndex = startIndex - count; for(int i = startIndex; i > endIndex; i--) { if(match( m_items[i] )) { return i; } } return -1; } public void ForEach( Action action ) { if(action == null) { ThrowHelper.ThrowArgumentNullException( ExceptionArgument.match ); } for(int i = 0; i < m_size; i++) { action( m_items[i] ); } } // Returns an enumerator for this list with the given // permission for removal of elements. If modifications made to the list // while an enumeration is in progress, the MoveNext and // GetObject methods of the enumerator will throw an exception. // public Enumerator GetEnumerator() { return new Enumerator( this ); } /// IEnumerator IEnumerable.GetEnumerator() { return new Enumerator( this ); } System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator() { return new Enumerator( this ); } public List GetRange( int index, int count ) { if(index < 0 || count < 0) { ThrowHelper.ThrowArgumentOutOfRangeException( (index < 0 ? ExceptionArgument.index : ExceptionArgument.count), ExceptionResource.ArgumentOutOfRange_NeedNonNegNum ); } if(m_size - index < count) { ThrowHelper.ThrowArgumentException( ExceptionResource.Argument_InvalidOffLen ); } List list = new List( count ); Array.Copy( m_items, index, list.m_items, 0, count ); list.m_size = count; return list; } // Returns the index of the first occurrence of a given value in a range of // this list. The list is searched forwards from beginning to end. // The elements of the list are compared to the given value using the // Object.Equals method. // // This method uses the Array.IndexOf method to perform the // search. // public int IndexOf( T item ) { return Array.IndexOf( m_items, item, 0, m_size ); } int System.Collections.IList.IndexOf( Object item ) { if(IsCompatibleObject( item )) { return IndexOf( (T)item ); } return -1; } // Returns the index of the first occurrence of a given value in a range of // this list. The list is searched forwards, starting at index // index and ending at count number of elements. The // elements of the list are compared to the given value using the // Object.Equals method. // // This method uses the Array.IndexOf method to perform the // search. // public int IndexOf( T item, int index ) { if(index > m_size) { ThrowHelper.ThrowArgumentOutOfRangeException( ExceptionArgument.index, ExceptionResource.ArgumentOutOfRange_Index ); } return Array.IndexOf( m_items, item, index, m_size - index ); } // Returns the index of the first occurrence of a given value in a range of // this list. The list is searched forwards, starting at index // index and upto count number of elements. The // elements of the list are compared to the given value using the // Object.Equals method. // // This method uses the Array.IndexOf method to perform the // search. // public int IndexOf( T item, int index, int count ) { if(index > m_size) { ThrowHelper.ThrowArgumentOutOfRangeException( ExceptionArgument.index, ExceptionResource.ArgumentOutOfRange_Index ); } if(count < 0 || index > m_size - count) { ThrowHelper.ThrowArgumentOutOfRangeException( ExceptionArgument.count, ExceptionResource.ArgumentOutOfRange_Count ); } return Array.IndexOf( m_items, item, index, count ); } // Inserts an element into this list at a given index. The size of the list // is increased by one. If required, the capacity of the list is doubled // before inserting the new element. // public void Insert( int index, T item ) { // Note that insertions at the end are legal. if((uint)index > (uint)m_size) { ThrowHelper.ThrowArgumentOutOfRangeException( ExceptionArgument.index, ExceptionResource.ArgumentOutOfRange_ListInsert ); } if(m_size == m_items.Length) { EnsureCapacity( m_size + 1 ); } if(index < m_size) { Array.Copy( m_items, index, m_items, index + 1, m_size - index ); } m_items[index] = item; m_size++; m_version++; } void System.Collections.IList.Insert( int index, Object item ) { ThrowHelper.IfNullAndNullsAreIllegalThenThrow( item, ExceptionArgument.item ); try { Insert( index, (T)item ); } catch(InvalidCastException) { ThrowHelper.ThrowWrongValueTypeArgumentException( item, typeof( T ) ); } } // Inserts the elements of the given collection at a given index. If // required, the capacity of the list is increased to twice the previous // capacity or the new size, whichever is larger. Ranges may be added // to the end of the list by setting index to the List's size. // public void InsertRange( int index, IEnumerable collection ) { if(collection == null) { ThrowHelper.ThrowArgumentNullException( ExceptionArgument.collection ); } if((uint)index > (uint)m_size) { ThrowHelper.ThrowArgumentOutOfRangeException( ExceptionArgument.index, ExceptionResource.ArgumentOutOfRange_Index ); } ICollection c = collection as ICollection; if(c != null) { // if collection is ICollection int count = c.Count; if(count > 0) { EnsureCapacity( m_size + count ); if(index < m_size) { Array.Copy( m_items, index, m_items, index + count, m_size - index ); } // If we're inserting a List into itself, we want to be able to deal with that. if(this == c) { // Copy first part of _items to insert location Array.Copy( m_items, 0 , m_items, index , index ); // Copy last part of _items back to inserted location Array.Copy( m_items, index + count, m_items, index * 2, m_size - index ); } else { T[] itemsToInsert = new T[count]; c.CopyTo( itemsToInsert, 0 ); itemsToInsert.CopyTo( m_items, index ); } m_size += count; } } else { using(IEnumerator en = collection.GetEnumerator()) { while(en.MoveNext()) { Insert( index++, en.Current ); } } } m_version++; } // Returns the index of the last occurrence of a given value in a range of // this list. The list is searched backwards, starting at the end // and ending at the first element in the list. The elements of the list // are compared to the given value using the Object.Equals method. // // This method uses the Array.LastIndexOf method to perform the // search. // public int LastIndexOf( T item ) { return LastIndexOf( item, m_size - 1, m_size ); } // Returns the index of the last occurrence of a given value in a range of // this list. The list is searched backwards, starting at index // index and ending at the first element in the list. The // elements of the list are compared to the given value using the // Object.Equals method. // // This method uses the Array.LastIndexOf method to perform the // search. // public int LastIndexOf( T item, int index ) { if(index >= m_size) { ThrowHelper.ThrowArgumentOutOfRangeException( ExceptionArgument.index, ExceptionResource.ArgumentOutOfRange_Index ); } return LastIndexOf( item, index, index + 1 ); } // Returns the index of the last occurrence of a given value in a range of // this list. The list is searched backwards, starting at index // index and upto count elements. The elements of // the list are compared to the given value using the Object.Equals // method. // // This method uses the Array.LastIndexOf method to perform the // search. // public int LastIndexOf( T item, int index, int count ) { if(m_size == 0) { return -1; } if(index < 0 || count < 0) { ThrowHelper.ThrowArgumentOutOfRangeException( (index < 0 ? ExceptionArgument.index : ExceptionArgument.count), ExceptionResource.ArgumentOutOfRange_NeedNonNegNum ); } if(index >= m_size || count > index + 1) { ThrowHelper.ThrowArgumentOutOfRangeException( (index >= m_size ? ExceptionArgument.index : ExceptionArgument.count), ExceptionResource.ArgumentOutOfRange_BiggerThanCollection ); } return Array.LastIndexOf( m_items, item, index, count ); } // Removes the element at the given index. The size of the list is // decreased by one. // public bool Remove( T item ) { int index = IndexOf( item ); if(index >= 0) { RemoveAt( index ); return true; } return false; } void System.Collections.IList.Remove( Object item ) { if(IsCompatibleObject( item )) { Remove( (T)item ); } } // This method removes all items which matches the predicate. // The complexity is O(n). public int RemoveAll( Predicate match ) { if(match == null) { ThrowHelper.ThrowArgumentNullException( ExceptionArgument.match ); } int freeIndex = 0; // the first free slot in items array // Find the first item which needs to be removed. while(freeIndex < m_size && !match( m_items[freeIndex] )) { freeIndex++; } if(freeIndex >= m_size) { return 0; } int current = freeIndex + 1; while(current < m_size) { // Find the first item which needs to be kept. while(current < m_size && match( m_items[current] )) { current++; } if(current < m_size) { // copy item to the free slot. m_items[freeIndex++] = m_items[current++]; } } Array.Clear( m_items, freeIndex, m_size - freeIndex ); int result = m_size - freeIndex; m_size = freeIndex; m_version++; return result; } // Removes the element at the given index. The size of the list is // decreased by one. // public void RemoveAt( int index ) { if((uint)index >= (uint)m_size) { ThrowHelper.ThrowArgumentOutOfRangeException(); } m_size--; if(index < m_size) { Array.Copy( m_items, index + 1, m_items, index, m_size - index ); } m_items[m_size] = default( T ); m_version++; } // Removes a range of elements from this list. // public void RemoveRange( int index, int count ) { if(index < 0 || count < 0) { ThrowHelper.ThrowArgumentOutOfRangeException( (index < 0 ? ExceptionArgument.index : ExceptionArgument.count), ExceptionResource.ArgumentOutOfRange_NeedNonNegNum ); } if(m_size - index < count) { ThrowHelper.ThrowArgumentException( ExceptionResource.Argument_InvalidOffLen ); } if(count > 0) { int i = m_size; m_size -= count; if(index < m_size) { Array.Copy( m_items, index + count, m_items, index, m_size - index ); } Array.Clear( m_items, m_size, count ); m_version++; } } // Reverses the elements in this list. public void Reverse() { Reverse( 0, Count ); } // Reverses the elements in a range of this list. Following a call to this // method, an element in the range given by index and count // which was previously located at index i will now be located at // index index + (index + count - i - 1). // // This method uses the Array.Reverse method to reverse the // elements. // public void Reverse( int index, int count ) { if(index < 0 || count < 0) { ThrowHelper.ThrowArgumentOutOfRangeException( (index < 0 ? ExceptionArgument.index : ExceptionArgument.count), ExceptionResource.ArgumentOutOfRange_NeedNonNegNum ); } if(m_size - index < count) { ThrowHelper.ThrowArgumentException( ExceptionResource.Argument_InvalidOffLen ); } Array.Reverse( m_items, index, count ); m_version++; } // Sorts the elements in this list. Uses the default comparer and // Array.Sort. public void Sort() { Sort( 0, Count, null ); } // Sorts the elements in this list. Uses Array.Sort with the // provided comparer. public void Sort( IComparer comparer ) { Sort( 0, Count, comparer ); } // Sorts the elements in a section of this list. The sort compares the // elements to each other using the given IComparer interface. If // comparer is null, the elements are compared to each other using // the IComparable interface, which in that case must be implemented by all // elements of the list. // // This method uses the Array.Sort method to sort the elements. // public void Sort( int index, int count, IComparer comparer ) { if(index < 0 || count < 0) { ThrowHelper.ThrowArgumentOutOfRangeException( (index < 0 ? ExceptionArgument.index : ExceptionArgument.count), ExceptionResource.ArgumentOutOfRange_NeedNonNegNum ); } if(m_size - index < count) { ThrowHelper.ThrowArgumentException( ExceptionResource.Argument_InvalidOffLen ); } Array.Sort( m_items, index, count, comparer ); m_version++; } public void Sort( Comparison comparison ) { if(comparison == null) { ThrowHelper.ThrowArgumentNullException( ExceptionArgument.match ); } if(m_size > 0) { IComparer comparer = new Array.FunctorComparer( comparison ); Array.Sort( m_items, 0, m_size, comparer ); } } // ToArray returns a new Object array containing the contents of the List. // This requires copying the List, which is an O(n) operation. public T[] ToArray() { T[] array = new T[m_size]; Array.Copy( m_items, 0, array, 0, m_size ); return array; } // Sets the capacity of this list to the size of the list. This method can // be used to minimize a list's memory overhead once it is known that no // new elements will be added to the list. To completely clear a list and // release all memory referenced by the list, execute the following // statements: // // list.Clear(); // list.TrimExcess(); // public void TrimExcess() { int threshold = (int)(((double)m_items.Length) * 0.9); if(m_size < threshold) { Capacity = m_size; } } public bool TrueForAll( Predicate match ) { if(match == null) { ThrowHelper.ThrowArgumentNullException( ExceptionArgument.match ); } for(int i = 0; i < m_size; i++) { if(!match( m_items[i] )) { return false; } } return true; } [Serializable] public struct Enumerator : IEnumerator, System.Collections.IEnumerator { private List m_list; private int m_index; private int m_version; private T m_current; internal Enumerator( List list ) { m_list = list; m_index = 0; m_version = list.m_version; m_current = default( T ); } public void Dispose() { } public bool MoveNext() { if(m_version != m_list.m_version) { ThrowHelper.ThrowInvalidOperationException( ExceptionResource.InvalidOperation_EnumFailedVersion ); } if((uint)m_index < (uint)m_list.m_size) { m_current = m_list.m_items[m_index]; m_index++; return true; } m_index = m_list.m_size + 1; m_current = default( T ); return false; } public T Current { get { return m_current; } } Object System.Collections.IEnumerator.Current { get { if(m_index == 0 || m_index == m_list.m_size + 1) { ThrowHelper.ThrowInvalidOperationException( ExceptionResource.InvalidOperation_EnumOpCantHappen ); } return Current; } } void System.Collections.IEnumerator.Reset() { if(m_version != m_list.m_version) { ThrowHelper.ThrowInvalidOperationException( ExceptionResource.InvalidOperation_EnumFailedVersion ); } m_index = 0; m_current = default( T ); } } } } ================================================ FILE: Zelig/Zelig/RunTime/Framework/mscorlib/System/Collections/Hashtable.cs ================================================ // ==++== // // Copyright (c) Microsoft Corporation. All rights reserved. // // ==--== /*============================================================ ** ** Class: Hashtable ** ** ** Purpose: Hash table implementation ** ** ===========================================================*/ namespace System.Collections { using System; using System.Runtime.Serialization; ////using System.Security.Permissions; using System.Diagnostics; using System.Threading; using System.Runtime.CompilerServices; using System.Runtime.ConstrainedExecution; // The Hashtable class represents a dictionary of associated keys and values // with constant lookup time. // // Objects used as keys in a hashtable must implement the GetHashCode // and Equals methods (or they can rely on the default implementations // inherited from Object if key equality is simply reference // equality). Furthermore, the GetHashCode and Equals methods of // a key object must produce the same results given the same parameters for the // entire time the key is present in the hashtable. In practical terms, this // means that key objects should be immutable, at least for the time they are // used as keys in a hashtable. // // When entries are added to a hashtable, they are placed into // buckets based on the hashcode of their keys. Subsequent lookups of // keys will use the hashcode of the keys to only search a particular bucket, // thus substantially reducing the number of key comparisons required to find // an entry. A hashtable's maximum load factor, which can be specified // when the hashtable is instantiated, determines the maximum ratio of // hashtable entries to hashtable buckets. Smaller load factors cause faster // average lookup times at the cost of increased memory consumption. The // default maximum load factor of 1.0 generally provides the best balance // between speed and size. As entries are added to a hashtable, the hashtable's // actual load factor increases, and when the actual load factor reaches the // maximum load factor value, the number of buckets in the hashtable is // automatically increased by approximately a factor of two (to be precise, the // number of hashtable buckets is increased to the smallest prime number that // is larger than twice the current number of hashtable buckets). // // Each object provides their own hash function, accessed by calling // GetHashCode(). However, one can write their own object // implementing IEqualityComparer and pass it to a constructor on // the Hashtable. That hash function (and the equals method on the // IEqualityComparer) would be used for all objects in the table. // // Changes since V1 during Whidbey: // *) Deprecated IHashCodeProvider, use IEqualityComparer instead. This will // allow better performance for objects where equality checking can be // done much faster than establishing an ordering between two objects, // such as an ordinal string equality check. // ////[DebuggerTypeProxy( typeof( System.Collections.Hashtable.HashtableDebugView ) )] ////[DebuggerDisplay( "Count = {Count}" )] [Serializable] public class Hashtable : IDictionary /*, ISerializable, IDeserializationCallback*/, ICloneable { /* Implementation Notes: The generic Dictionary was copied from Hashtable's source - any bug fixes here probably need to be made to the generic Dictionary as well. This Hashtable uses double hashing. There are hashsize buckets in the table, and each bucket can contain 0 or 1 element. We a bit to mark whether there's been a collision when we inserted multiple elements (ie, an inserted item was hashed at least a second time and we probed this bucket, but it was already in use). Using the collision bit, we can terminate lookups & removes for elements that aren't in the hash table more quickly. We steal the most significant bit from the hash code to store the collision bit. Our hash function is of the following form: h(key, n) = h1(key) + n*h2(key) where n is the number of times we've hit a collided bucket and rehashed (on this particular lookup). Here are our hash functions: h1(key) = GetHash(key); // default implementation calls key.GetHashCode(); h2(key) = 1 + (((h1(key) >> 5) + 1) % (hashsize - 1)); The h1 can return any number. h2 must return a number between 1 and hashsize - 1 that is relatively prime to hashsize (not a problem if hashsize is prime). (Knuth's Art of Computer Programming, Vol. 3, p. 528-9) If this is true, then we are guaranteed to visit every bucket in exactly hashsize probes, since the least common multiple of hashsize and h2(key) will be hashsize * h2(key). (This is the first number where adding h2 to h1 mod hashsize will be 0 and we will search the same bucket twice). We previously used a different h2(key, n) that was not constant. That is a horrifically bad idea, unless you can prove that series will never produce any identical numbers that overlap when you mod them by hashsize, for all subranges from i to i+hashsize, for all i. It's not worth investigating, since there was no clear benefit from using that hash function, and it was broken. For efficiency reasons, we've implemented this by storing h1 and h2 in a temporary, and setting a variable called seed equal to h1. We do a probe, and if we collided, we simply add h2 to seed each time through the loop. A good test for h2() is to subclass Hashtable, provide your own implementation of GetHash() that returns a constant, then add many items to the hash table. Make sure Count equals the number of items you inserted. Note that when we remove an item from the hash table, we set the key equal to buckets, if there was a collision in this bucket. Otherwise we'd either wipe out the collision bit, or we'd still have an item in the hash table. -- */ private const String LoadFactorName = "LoadFactor"; private const String VersionName = "Version"; private const String ComparerName = "Comparer"; private const String HashCodeProviderName = "HashCodeProvider"; private const String HashSizeName = "HashSize"; // Must save buckets.Length private const String KeysName = "Keys"; private const String ValuesName = "Values"; private const String KeyComparerName = "KeyComparer"; // Deleted entries have their key set to buckets // The hash table data. // This cannot be serialised private struct bucket { public Object key; public Object val; public int hash_coll; // Store hash code; sign bit means there was a collision. } private bucket[] m_buckets; // The total number of entries in the hash table. private int m_count; // The total number of collision bits set in the hashtable private int m_occupancy; private int m_loadsize; private float m_loadFactor; private volatile int m_version; private volatile bool m_isWriterInProgress; private ICollection m_keys; private ICollection m_values; private IEqualityComparer m_keycomparer; private Object m_syncRoot; //// private SerializationInfo m_siInfo; //A temporary variable which we need during deserialization. //// [Obsolete( "Please use EqualityComparer property." )] //// protected IHashCodeProvider hcp //// { //// get //// { //// if(m_keycomparer is CompatibleComparer) //// { //// return ((CompatibleComparer)m_keycomparer).HashCodeProvider; //// } //// else if(m_keycomparer == null) //// { //// return null; //// } //// else //// { //// throw new ArgumentException( Environment.GetResourceString( "Arg_CannotMixComparisonInfrastructure" ) ); //// } //// } //// //// set //// { //// if(m_keycomparer is CompatibleComparer) //// { //// CompatibleComparer keyComparer = (CompatibleComparer)m_keycomparer; //// //// m_keycomparer = new CompatibleComparer( keyComparer.Comparer, value ); //// } //// else if(m_keycomparer == null) //// { //// m_keycomparer = new CompatibleComparer( (IComparer)null, value ); //// } //// else //// { //// throw new ArgumentException( Environment.GetResourceString( "Arg_CannotMixComparisonInfrastructure" ) ); //// } //// } //// } //// //// //// [Obsolete( "Please use KeyComparer properties." )] //// protected IComparer comparer //// { //// get //// { //// if(m_keycomparer is CompatibleComparer) //// { //// return ((CompatibleComparer)m_keycomparer).Comparer; //// } //// else if(m_keycomparer == null) //// { //// return null; //// } //// else //// { //// throw new ArgumentException( Environment.GetResourceString( "Arg_CannotMixComparisonInfrastructure" ) ); //// } //// } //// //// set //// { //// if(m_keycomparer is CompatibleComparer) //// { //// CompatibleComparer keyComparer = (CompatibleComparer)m_keycomparer; //// //// m_keycomparer = new CompatibleComparer( value, keyComparer.HashCodeProvider ); //// } //// else if(m_keycomparer == null) //// { //// m_keycomparer = new CompatibleComparer( value, (IHashCodeProvider)null ); //// } //// else //// { //// throw new ArgumentException( Environment.GetResourceString( "Arg_CannotMixComparisonInfrastructure" ) ); //// } //// } //// } protected IEqualityComparer EqualityComparer { get { return m_keycomparer; } } //// // Note: this constructor is a bogus constructor that does nothing //// // and is for use only with SyncHashtable. //// internal Hashtable( bool trash ) //// { //// } // Constructs a new hashtable. The hashtable is created with an initial // capacity of zero and a load factor of 1.0. public Hashtable() : this( 0, 1.0f ) { } // Constructs a new hashtable with the given initial capacity and a load // factor of 1.0. The capacity argument serves as an indication of // the number of entries the hashtable will contain. When this number (or // an approximation) is known, specifying it in the constructor can // eliminate a number of resizing operations that would otherwise be // performed when elements are added to the hashtable. // public Hashtable( int capacity ) : this( capacity, 1.0f ) { } // Constructs a new hashtable with the given initial capacity and load // factor. The capacity argument serves as an indication of the // number of entries the hashtable will contain. When this number (or an // approximation) is known, specifying it in the constructor can eliminate // a number of resizing operations that would otherwise be performed when // elements are added to the hashtable. The loadFactor argument // indicates the maximum ratio of hashtable entries to hashtable buckets. // Smaller load factors cause faster average lookup times at the cost of // increased memory consumption. A load factor of 1.0 generally provides // the best balance between speed and size. // public Hashtable( int capacity, float loadFactor ) { if(capacity < 0) { #if EXCEPTION_STRINGS throw new ArgumentOutOfRangeException( "capacity", Environment.GetResourceString( "ArgumentOutOfRange_NeedNonNegNum" ) ); #else throw new ArgumentOutOfRangeException(); #endif } if(!(loadFactor >= 0.1f && loadFactor <= 1.0f)) { #if EXCEPTION_STRINGS throw new ArgumentOutOfRangeException( "loadFactor", Environment.GetResourceString( "ArgumentOutOfRange_HashtableLoadFactor", .1, 1.0 ) ); #else throw new ArgumentOutOfRangeException(); #endif } // Based on perf work, .72 is the optimal load factor for this table. m_loadFactor = 0.72f * loadFactor; double rawsize = capacity / m_loadFactor; if(rawsize > Int32.MaxValue) { #if EXCEPTION_STRINGS throw new ArgumentException( Environment.GetResourceString( "Arg_HTCapacityOverflow" ) ); #else throw new ArgumentException(); #endif } // Avoid awfully small sizes int hashsize = (rawsize > 11) ? HashHelpers.GetPrime( (int)rawsize ) : 11; m_buckets = new bucket[hashsize]; m_loadsize = (int)(m_loadFactor * hashsize); m_isWriterInProgress = false; // Based on the current algorithm, loadsize must be less than hashsize. BCLDebug.Assert( m_loadsize < hashsize, "Invalid hashtable loadsize!" ); } //// // Constructs a new hashtable with the given initial capacity and load //// // factor. The capacity argument serves as an indication of the //// // number of entries the hashtable will contain. When this number (or an //// // approximation) is known, specifying it in the constructor can eliminate //// // a number of resizing operations that would otherwise be performed when //// // elements are added to the hashtable. The loadFactor argument //// // indicates the maximum ratio of hashtable entries to hashtable buckets. //// // Smaller load factors cause faster average lookup times at the cost of //// // increased memory consumption. A load factor of 1.0 generally provides //// // the best balance between speed and size. The hcp argument //// // is used to specify an Object that will provide hash codes for all //// // the Objects in the table. Using this, you can in effect override //// // GetHashCode() on each Object using your own hash function. The //// // comparer argument will let you specify a custom function for //// // comparing keys. By specifying user-defined objects for hcp //// // and comparer, users could make a hash table using strings //// // as keys do case-insensitive lookups. //// // //// [Obsolete( "Please use Hashtable(int, float, IEqualityComparer) instead." )] //// public Hashtable( int capacity, float loadFactor, IHashCodeProvider hcp, IComparer comparer ) : this( capacity, loadFactor ) //// { //// if(hcp == null && comparer == null) //// { //// this.m_keycomparer = null; //// } //// else //// { //// this.m_keycomparer = new CompatibleComparer( comparer, hcp ); //// } //// } public Hashtable( int capacity, float loadFactor, IEqualityComparer equalityComparer ) : this( capacity, loadFactor ) { m_keycomparer = equalityComparer; } //// // Constructs a new hashtable using a custom hash function //// // and a custom comparison function for keys. This will enable scenarios //// // such as doing lookups with case-insensitive strings. //// // //// [Obsolete( "Please use Hashtable(IEqualityComparer) instead." )] //// public Hashtable( IHashCodeProvider hcp, IComparer comparer ) : this( 0, 1.0f, hcp, comparer ) //// { //// } public Hashtable( IEqualityComparer equalityComparer ) : this( 0, 1.0f, equalityComparer ) { } //// // Constructs a new hashtable using a custom hash function //// // and a custom comparison function for keys. This will enable scenarios //// // such as doing lookups with case-insensitive strings. //// // //// [Obsolete( "Please use Hashtable(int, IEqualityComparer) instead." )] //// public Hashtable( int capacity, IHashCodeProvider hcp, IComparer comparer ) : this( capacity, 1.0f, hcp, comparer ) //// { //// } public Hashtable( int capacity, IEqualityComparer equalityComparer ) : this( capacity, 1.0f, equalityComparer ) { } // Constructs a new hashtable containing a copy of the entries in the given // dictionary. The hashtable is created with a load factor of 1.0. // public Hashtable( IDictionary d ) : this( d, 1.0f ) { } // Constructs a new hashtable containing a copy of the entries in the given // dictionary. The hashtable is created with the given load factor. // public Hashtable( IDictionary d, float loadFactor ) : this( d, loadFactor, (IEqualityComparer)null ) { } //// [Obsolete( "Please use Hashtable(IDictionary, IEqualityComparer) instead." )] //// public Hashtable( IDictionary d, IHashCodeProvider hcp, IComparer comparer ) : this( d, 1.0f, hcp, comparer ) //// { //// } public Hashtable( IDictionary d, IEqualityComparer equalityComparer ) : this( d, 1.0f, equalityComparer ) { } //// [Obsolete( "Please use Hashtable(IDictionary, float, IEqualityComparer) instead." )] //// public Hashtable( IDictionary d, float loadFactor, IHashCodeProvider hcp, IComparer comparer ) : this( (d != null ? d.Count : 0), loadFactor, hcp, comparer ) //// { //// if(d == null) //// { //// throw new ArgumentNullException( "d", Environment.GetResourceString( "ArgumentNull_Dictionary" ) ); //// } //// //// IDictionaryEnumerator e = d.GetEnumerator(); //// //// while(e.MoveNext()) Add( e.Key, e.Value ); //// } public Hashtable( IDictionary d, float loadFactor, IEqualityComparer equalityComparer ) : this( (d != null ? d.Count : 0), loadFactor, equalityComparer ) { if(d == null) { #if EXCEPTION_STRINGS throw new ArgumentNullException( "d", Environment.GetResourceString( "ArgumentNull_Dictionary" ) ); #else throw new ArgumentNullException(); #endif } IDictionaryEnumerator e = d.GetEnumerator(); while(e.MoveNext()) Add( e.Key, e.Value ); } //// protected Hashtable( SerializationInfo info, StreamingContext context ) //// { //// //We can't do anything with the keys and values until the entire graph has been deserialized //// //and we have a resonable estimate that GetHashCode is not going to fail. For the time being, //// //we'll just cache this. The graph is not valid until OnDeserialization has been called. //// m_siInfo = info; //// } // Computes the hash function: H(key, i) = h1(key) + i*h2(key, hashSize). // The out parameter seed is h1(key), while the out parameter // incr is h2(key, hashSize). Callers of this function should // add incr each time through a loop. private uint InitHash( Object key, int hashsize, out uint seed, out uint incr ) { // Hashcode must be positive. Also, we must not use the sign bit, since // that is used for the collision bit. uint hashcode = (uint)GetHash( key ) & 0x7FFFFFFF; seed = (uint)hashcode; // Restriction: incr MUST be between 1 and hashsize - 1, inclusive for // the modular arithmetic to work correctly. This guarantees you'll // visit every bucket in the table exactly once within hashsize // iterations. Violate this and it'll cause obscure bugs forever. // If you change this calculation for h2(key), update putEntry too! incr = (uint)(1 + (((seed >> 5) + 1) % ((uint)hashsize - 1))); return hashcode; } // Adds an entry with the given key and value to this hashtable. An // ArgumentException is thrown if the key is null or if the key is already // present in the hashtable. // public virtual void Add( Object key, Object value ) { Insert( key, value, true ); } // Removes all entries from this hashtable. //// [ReliabilityContract( Consistency.WillNotCorruptState, Cer.Success )] public virtual void Clear() { if(m_count == 0) { return; } Thread.BeginCriticalRegion(); m_isWriterInProgress = true; for(int i = 0; i < m_buckets.Length; i++) { m_buckets[i].hash_coll = 0; m_buckets[i].key = null; m_buckets[i].val = null; } m_count = 0; m_occupancy = 0; UpdateVersion(); m_isWriterInProgress = false; Thread.EndCriticalRegion(); } // Clone returns a virtually identical copy of this hash table. This does // a shallow copy - the Objects in the table aren't cloned, only the references // to those Objects. public virtual Object Clone() { bucket[] lbuckets = m_buckets; Hashtable ht = new Hashtable( m_count, m_keycomparer ); ht.m_version = m_version; ht.m_loadFactor = m_loadFactor; ht.m_count = 0; int bucket = lbuckets.Length; while(bucket > 0) { bucket--; Object keyv = lbuckets[bucket].key; if((keyv != null) && (keyv != lbuckets)) { ht[keyv] = lbuckets[bucket].val; } } return ht; } // Checks if this hashtable contains the given key. public virtual bool Contains( Object key ) { return ContainsKey( key ); } // Checks if this hashtable contains an entry with the given key. This is // an O(1) operation. // public virtual bool ContainsKey( Object key ) { if(key == null) { #if EXCEPTION_STRINGS throw new ArgumentNullException( "key", Environment.GetResourceString( "ArgumentNull_Key" ) ); #else throw new ArgumentNullException(); #endif } uint seed; uint incr; // Take a snapshot of buckets, in case another thread resizes table bucket[] lbuckets = m_buckets; uint hashcode = InitHash( key, lbuckets.Length, out seed, out incr ); int ntry = 0; int bucketNumber = (int)(seed % (uint)lbuckets.Length); bucket b; do { b = lbuckets[bucketNumber]; if(b.key == null) { return false; } if(((b.hash_coll & 0x7FFFFFFF) == hashcode) && KeyEquals( b.key, key )) { return true; } bucketNumber = (int)(((long)bucketNumber + incr) % (uint)lbuckets.Length); } while(b.hash_coll < 0 && ++ntry < lbuckets.Length); return false; } // Checks if this hashtable contains an entry with the given value. The // values of the entries of the hashtable are compared to the given value // using the Object.Equals method. This method performs a linear // search and is thus be substantially slower than the ContainsKey // method. // public virtual bool ContainsValue( Object value ) { if(value == null) { for(int i = m_buckets.Length; --i >= 0; ) { if(m_buckets[i].key != null && m_buckets[i].key != m_buckets && m_buckets[i].val == null) { return true; } } } else { for(int i = m_buckets.Length; --i >= 0; ) { Object val = m_buckets[i].val; if(val != null && val.Equals( value )) { return true; } } } return false; } // Copies the keys of this hashtable to a given array starting at a given // index. This method is used by the implementation of the CopyTo method in // the Collection class. private void CopyKeys( Array array, int arrayIndex ) { bucket[] lbuckets = m_buckets; for(int i = lbuckets.Length; --i >= 0; ) { Object keyv = lbuckets[i].key; if((keyv != null) && (keyv != m_buckets)) { array.SetValue( keyv, arrayIndex++ ); } } } // Copies the keys of this hashtable to a given array starting at a given // index. This method is used by the implementation of the CopyTo method in // the Collection class. private void CopyEntries( Array array, int arrayIndex ) { bucket[] lbuckets = m_buckets; for(int i = lbuckets.Length; --i >= 0; ) { Object keyv = lbuckets[i].key; if((keyv != null) && (keyv != m_buckets)) { DictionaryEntry entry = new DictionaryEntry( keyv, lbuckets[i].val ); array.SetValue( entry, arrayIndex++ ); } } } // Copies the values in this hash table to an array at // a given index. Note that this only copies values, and not keys. public virtual void CopyTo( Array array, int arrayIndex ) { if(array == null) { #if EXCEPTION_STRINGS throw new ArgumentNullException( "array", Environment.GetResourceString( "ArgumentNull_Array" ) ); #else throw new ArgumentNullException(); #endif } if(array.Rank != 1) { #if EXCEPTION_STRINGS throw new ArgumentException( Environment.GetResourceString( "Arg_RankMultiDimNotSupported" ) ); #else throw new ArgumentException(); #endif } if(arrayIndex < 0) { #if EXCEPTION_STRINGS throw new ArgumentOutOfRangeException( "arrayIndex", Environment.GetResourceString( "ArgumentOutOfRange_NeedNonNegNum" ) ); #else throw new ArgumentOutOfRangeException(); #endif } if(array.Length - arrayIndex < m_count) { #if EXCEPTION_STRINGS throw new ArgumentException( Environment.GetResourceString( "Arg_ArrayPlusOffTooSmall" ) ); #else throw new ArgumentException(); #endif } CopyEntries( array, arrayIndex ); } // Copies the values in this Hashtable to an KeyValuePairs array. // KeyValuePairs is different from Dictionary Entry in that it has special // debugger attributes on its fields. internal virtual KeyValuePairs[] ToKeyValuePairsArray() { KeyValuePairs[] array = new KeyValuePairs[m_count]; int index = 0; bucket[] lbuckets = m_buckets; for(int i = lbuckets.Length; --i >= 0; ) { Object keyv = lbuckets[i].key; if((keyv != null) && (keyv != m_buckets)) { array[index++] = new KeyValuePairs( keyv, lbuckets[i].val ); } } return array; } // Copies the values of this hashtable to a given array starting at a given // index. This method is used by the implementation of the CopyTo method in // the Collection class. private void CopyValues( Array array, int arrayIndex ) { bucket[] lbuckets = m_buckets; for(int i = lbuckets.Length; --i >= 0; ) { Object keyv = lbuckets[i].key; if((keyv != null) && (keyv != m_buckets)) { array.SetValue( lbuckets[i].val, arrayIndex++ ); } } } // Returns the value associated with the given key. If an entry with the // given key is not found, the returned value is null. // public virtual Object this[Object key] { get { if(key == null) { #if EXCEPTION_STRINGS throw new ArgumentNullException( "key", Environment.GetResourceString( "ArgumentNull_Key" ) ); #else throw new ArgumentNullException(); #endif } uint seed; uint incr; // Take a snapshot of buckets, in case another thread does a resize bucket[] lbuckets = m_buckets; bucket b; uint hashcode = InitHash( key, lbuckets.Length, out seed, out incr ); int ntry = 0; int bucketNumber = (int)(seed % (uint)lbuckets.Length); do { int currentversion; // A read operation on hashtable has three steps: // (1) calculate the hash and find the slot number. // (2) compare the hashcode, if equal, go to step 3. Otherwise end. // (3) compare the key, if equal, go to step 4. Otherwise end. // (4) return the value contained in the bucket. // After step 3 and before step 4. A writer can kick in a remove the old item and add a new one // in the same bukcet. So in the reader we need to check if the hash table is modified during above steps. // // Writers (Insert, Remove, Clear) will set 'isWriterInProgress' flag before it starts modifying // the hashtable and will ckear the flag when it is done. When the flag is cleared, the 'version' // will be increased. We will repeat the reading if a writer is in progress or done with the modification // during the read. // // Our memory model guarantee if we pick up the change in bucket from another processor, // we will see the 'isWriterProgress' flag to be true or 'version' is changed in the reader. // int spinCount = 0; do { // this is violate read, following memory accesses can not be moved ahead of it. currentversion = m_version; b = lbuckets[bucketNumber]; // The contention between reader and writer shouldn't happen frequently. // But just in case this will burn CPU, yield the control of CPU if we spinned a few times. // 8 is just a random number I pick. if((++spinCount) % 8 == 0) { Thread.Sleep( 1 ); // 1 means we are yeilding control to all threads, including low-priority ones. } } while(m_isWriterInProgress || (currentversion != m_version)); if(b.key == null) { return null; } if(((b.hash_coll & 0x7FFFFFFF) == hashcode) && KeyEquals( b.key, key )) { return b.val; } bucketNumber = (int)(((long)bucketNumber + incr) % (uint)lbuckets.Length); } while(b.hash_coll < 0 && ++ntry < lbuckets.Length); return null; } set { Insert( key, value, false ); } } // Increases the bucket count of this hashtable. This method is called from // the Insert method when the actual load factor of the hashtable reaches // the upper limit specified when the hashtable was constructed. The number // of buckets in the hashtable is increased to the smallest prime number // that is larger than twice the current number of buckets, and the entries // in the hashtable are redistributed into the new buckets using the cached // hashcodes. private void expand() { int rawsize = HashHelpers.GetPrime( m_buckets.Length * 2 ); // buckets.Length*2 will not overflow rehash( rawsize ); } // We occationally need to rehash the table to clean up the collision bits. private void rehash() { rehash( m_buckets.Length ); } private void UpdateVersion() { // Version might become negative when version is Int32.MaxValue, but the oddity will be still be correct. // So we don't need to special case this. m_version++; } //// [ReliabilityContract( Consistency.WillNotCorruptState, Cer.MayFail )] private void rehash( int newsize ) { // reset occupancy m_occupancy = 0; // Don't replace any internal state until we've finished adding to the // new bucket[]. This serves two purposes: // 1) Allow concurrent readers to see valid hashtable contents // at all times // 2) Protect against an OutOfMemoryException while allocating this // new bucket[]. bucket[] newBuckets = new bucket[newsize]; // rehash table into new buckets for(int nb = 0; nb < m_buckets.Length; nb++) { bucket oldb = m_buckets[nb]; if((oldb.key != null) && (oldb.key != m_buckets)) { putEntry( newBuckets, oldb.key, oldb.val, oldb.hash_coll & 0x7FFFFFFF ); } } // New bucket[] is good to go - replace buckets and other internal state. Thread.BeginCriticalRegion(); m_isWriterInProgress = true; m_buckets = newBuckets; m_loadsize = (int)(m_loadFactor * newsize); UpdateVersion(); m_isWriterInProgress = false; Thread.EndCriticalRegion(); // minimun size of hashtable is 11 now and maximum loadFactor is 0.72 now. BCLDebug.Assert( m_loadsize < newsize, "Our current implementaion means this is not possible." ); return; } // Returns an enumerator for this hashtable. // If modifications made to the hashtable while an enumeration is // in progress, the MoveNext and Current methods of the // enumerator will throw an exception. // IEnumerator IEnumerable.GetEnumerator() { return new HashtableEnumerator( this, HashtableEnumerator.DictEntry ); } // Returns a dictionary enumerator for this hashtable. // If modifications made to the hashtable while an enumeration is // in progress, the MoveNext and Current methods of the // enumerator will throw an exception. // public virtual IDictionaryEnumerator GetEnumerator() { return new HashtableEnumerator( this, HashtableEnumerator.DictEntry ); } // Internal method to get the hash code for an Object. This will call // GetHashCode() on each object if you haven't provided an IHashCodeProvider // instance. Otherwise, it calls hcp.GetHashCode(obj). protected virtual int GetHash( Object key ) { if(m_keycomparer != null) { return m_keycomparer.GetHashCode( key ); } return key.GetHashCode(); } // Is this Hashtable read-only? public virtual bool IsReadOnly { get { return false; } } public virtual bool IsFixedSize { get { return false; } } // Is this Hashtable synchronized? See SyncRoot property public virtual bool IsSynchronized { get { return false; } } // Internal method to compare two keys. If you have provided an IComparer // instance in the constructor, this method will call comparer.Compare(item, key). // Otherwise, it will call item.Equals(key). // protected virtual bool KeyEquals( Object item, Object key ) { BCLDebug.Assert( key != null, "key can't be null here!" ); if(Object.ReferenceEquals( m_buckets, item )) { return false; } if(m_keycomparer != null) { return m_keycomparer.Equals( item, key ); } return item == null ? false : item.Equals( key ); } // Returns a collection representing the keys of this hashtable. The order // in which the returned collection represents the keys is unspecified, but // it is guaranteed to be buckets = newBuckets; the same order in which a collection returned by // GetValues represents the values of the hashtable. // // The returned collection is live in the sense that any changes // to the hash table are reflected in this collection. It is not // a static copy of all the keys in the hash table. // public virtual ICollection Keys { get { if(m_keys == null) { m_keys = new Collection( this, true ); } return m_keys; } } // Returns a collection representing the values of this hashtable. The // order in which the returned collection represents the values is // unspecified, but it is guaranteed to be the same order in which a // collection returned by GetKeys represents the keys of the // hashtable. // // The returned collection is live in the sense that any changes // to the hash table are reflected in this collection. It is not // a static copy of all the keys in the hash table. // public virtual ICollection Values { get { if(m_values == null) { m_values = new Collection( this, false ); } return m_values; } } // Inserts an entry into this hashtable. This method is called from the Set // and Add methods. If the add parameter is true and the given key already // exists in the hashtable, an exception is thrown. //// [ReliabilityContract( Consistency.WillNotCorruptState, Cer.MayFail )] private void Insert( Object key, Object nvalue, bool add ) { if(key == null) { #if EXCEPTION_STRINGS throw new ArgumentNullException( "key", Environment.GetResourceString( "ArgumentNull_Key" ) ); #else throw new ArgumentNullException(); #endif } if(m_count >= m_loadsize) { expand(); } else if(m_occupancy > m_loadsize && m_count > 100) { rehash(); } uint seed; uint incr; // Assume we only have one thread writing concurrently. Modify // buckets to contain new data, as long as we insert in the right order. bucket[] lbuckets = m_buckets; uint hashcode = InitHash( key, lbuckets.Length, out seed, out incr ); int ntry = 0; int emptySlotNumber = -1; // We use the empty slot number to cache the first empty slot. We chose to reuse slots // create by remove that have the collision bit set over using up new slots. int bucketNumber = (int)(seed % (uint)lbuckets.Length); do { bucket b = lbuckets[bucketNumber]; // Set emptySlot number to current bucket if it is the first available bucket that we have seen // that once contained an entry and also has had a collision. // We need to search this entire collision chain because we have to ensure that there are no // duplicate entries in the table. if(emptySlotNumber == -1 && b.key == lbuckets && b.hash_coll < 0) { emptySlotNumber = bucketNumber; } // Insert the key/value pair into this bucket if this bucket is empty and has never contained an entry // OR // This bucket once contained an entry but there has never been a collision if((b.key == null) || (b.key == lbuckets && b.hash_coll >= 0)) { // If we have found an available bucket that has never had a collision, but we've seen an available // bucket in the past that has the collision bit set, use the previous bucket instead if(emptySlotNumber != -1) // Reuse slot { bucketNumber = emptySlotNumber; b = lbuckets[bucketNumber]; } // We pretty much have to insert in this order. Don't set hash // code until the value & key are set appropriately. Thread.BeginCriticalRegion(); m_isWriterInProgress = true; b.val = nvalue; b.key = key; b.hash_coll |= (int)hashcode; m_count++; UpdateVersion(); m_isWriterInProgress = false; Thread.EndCriticalRegion(); return; } // The current bucket is in use // OR // it is available, but has had the collision bit set and we have already found an available bucket if(((b.hash_coll & 0x7FFFFFFF) == hashcode) && KeyEquals( b.key, key )) { if(add) { #if EXCEPTION_STRINGS throw new ArgumentException( Environment.GetResourceString( "Argument_AddingDuplicate__", b.key, key ) ); #else throw new ArgumentException(); #endif } Thread.BeginCriticalRegion(); m_isWriterInProgress = true; b.val = nvalue; UpdateVersion(); m_isWriterInProgress = false; Thread.EndCriticalRegion(); return; } // The current bucket is full, and we have therefore collided. We need to set the collision bit // UNLESS // we have remembered an available slot previously. if(emptySlotNumber == -1) { // We don't need to set the collision bit here since we already have an empty slot if(lbuckets[bucketNumber].hash_coll >= 0) { lbuckets[bucketNumber].hash_coll |= unchecked( (int)0x80000000 ); m_occupancy++; } } bucketNumber = (int)(((long)bucketNumber + incr) % (uint)lbuckets.Length); } while(++ntry < m_buckets.Length); // This code is here if and only if there were no buckets without a collision bit set in the entire table if(emptySlotNumber != -1) { // We pretty much have to insert in this order. Don't set hash // code until the value & key are set appropriately. Thread.BeginCriticalRegion(); m_isWriterInProgress = true; bucket b = m_buckets[emptySlotNumber]; b.val = nvalue; b.key = key; b.hash_coll |= (int)hashcode; m_count++; UpdateVersion(); m_isWriterInProgress = false; Thread.EndCriticalRegion(); return; } // If you see this assert, make sure load factor & count are reasonable. // Then verify that our double hash function (h2, described at top of file) // meets the requirements described above. You should never see this assert. BCLDebug.Assert( false, "hash table insert failed! Load factor too high, or our double hashing function is incorrect." ); #if EXCEPTION_STRINGS throw new InvalidOperationException( Environment.GetResourceString( "InvalidOperation_HashInsertFailed" ) ); #else throw new InvalidOperationException(); #endif } private void putEntry( bucket[] newBuckets, Object key, Object nvalue, int hashcode ) { BCLDebug.Assert( hashcode >= 0, "hashcode >= 0" ); // make sure collision bit (sign bit) wasn't set. uint seed = (uint)hashcode; uint incr = (uint)(1 + (((seed >> 5) + 1) % ((uint)newBuckets.Length - 1))); int bucketNumber = (int)(seed % (uint)newBuckets.Length); do { bucket b = newBuckets[bucketNumber]; if((b.key == null) || (b.key == m_buckets)) { b.val = nvalue; b.key = key; b.hash_coll |= hashcode; return; } if(b.hash_coll >= 0) { b.hash_coll |= unchecked( (int)0x80000000 ); m_occupancy++; } bucketNumber = (int)(((long)bucketNumber + incr) % (uint)newBuckets.Length); } while(true); } // Removes an entry from this hashtable. If an entry with the specified // key exists in the hashtable, it is removed. An ArgumentException is // thrown if the key is null. // //// [ReliabilityContract( Consistency.WillNotCorruptState, Cer.MayFail )] public virtual void Remove( Object key ) { if(key == null) { #if EXCEPTION_STRINGS throw new ArgumentNullException( "key", Environment.GetResourceString( "ArgumentNull_Key" ) ); #else throw new ArgumentNullException(); #endif } uint seed; uint incr; // Assuming only one concurrent writer, write directly into buckets. uint hashcode = InitHash( key, m_buckets.Length, out seed, out incr ); int ntry = 0; int bucketNumber = (int)(seed % (uint)m_buckets.Length); // bucketNumber bucket b; do { b = m_buckets[bucketNumber]; if(((b.hash_coll & 0x7FFFFFFF) == hashcode) && KeyEquals( b.key, key )) { Thread.BeginCriticalRegion(); m_isWriterInProgress = true; // Clear hash_coll field, then key, then value b.hash_coll &= unchecked( (int)0x80000000 ); if(b.hash_coll != 0) { b.key = m_buckets; } else { b.key = null; } b.val = null; // Free object references sooner & simplify ContainsValue. m_count--; UpdateVersion(); m_isWriterInProgress = false; Thread.EndCriticalRegion(); return; } bucketNumber = (int)(((long)bucketNumber + incr) % (uint)m_buckets.Length); } while(b.hash_coll < 0 && ++ntry < m_buckets.Length); //throw new ArgumentException(Environment.GetResourceString("Arg_RemoveArgNotFound")); } // Returns the object to synchronize on for this hash table. public virtual Object SyncRoot { get { if(m_syncRoot == null) { System.Threading.Interlocked.CompareExchange( ref m_syncRoot, new Object(), null ); } return m_syncRoot; } } // Returns the number of associations in this hashtable. // public virtual int Count { get { return m_count; } } //// // Returns a thread-safe wrapper for a Hashtable. //// // //// [HostProtection( Synchronization = true )] //// public static Hashtable Synchronized( Hashtable table ) //// { //// if(table == null) //// { //// throw new ArgumentNullException( "table" ); //// } //// //// return new SyncHashtable( table ); //// } //// // //// // The ISerializable Implementation //// // //// //// public virtual void GetObjectData( SerializationInfo info, StreamingContext context ) //// { //// if(info == null) //// { //// throw new ArgumentNullException( "info" ); //// } //// //// info.AddValue( LoadFactorName, m_loadFactor ); //// info.AddValue( VersionName , m_version ); //// //// // //// // We need to maintain serialization compatibility with Everett and RTM. //// // If the comparer is null or a compatible comparer, serialize Hashtable //// // in a format that can be deserialized on Everett and RTM. //// // ////#pragma warning disable 618 //////// if(m_keycomparer == null) //////// { //////// info.AddValue( ComparerName , null, typeof( IComparer ) ); //////// info.AddValue( HashCodeProviderName, null, typeof( IHashCodeProvider ) ); //////// } //////// else if(m_keycomparer is CompatibleComparer) //////// { //////// CompatibleComparer c = m_keycomparer as CompatibleComparer; //////// //////// info.AddValue( ComparerName , c.Comparer , typeof( IComparer ) ); //////// info.AddValue( HashCodeProviderName, c.HashCodeProvider, typeof( IHashCodeProvider ) ); //////// } //////// else //////// { //// info.AddValue( KeyComparerName, m_keycomparer, typeof( IEqualityComparer ) ); //////// } ////#pragma warning restore 618 //// //// info.AddValue( HashSizeName, m_buckets.Length ); //This is the length of the bucket array. //// //// Object[] serKeys = new Object[m_count]; //// Object[] serValues = new Object[m_count]; //// //// CopyKeys ( serKeys , 0 ); //// CopyValues( serValues, 0 ); //// //// info.AddValue( KeysName , serKeys , typeof( Object[] ) ); //// info.AddValue( ValuesName, serValues, typeof( Object[] ) ); //// } //// //// // //// // DeserializationEvent Listener //// // //// public virtual void OnDeserialization( Object sender ) //// { //// if(m_buckets != null) //// { //// return; //Somebody had a dependency on this hashtable and fixed us up before the ObjectManager got to it. //// } //// //// if(m_siInfo == null) //// { //// throw new SerializationException( Environment.GetResourceString( "Serialization_InvalidOnDeser" ) ); //// } //// //// int hashsize = 0; //// IComparer c = null; //// ////////#pragma warning disable 618 //////// IHashCodeProvider hcp = null; ////////#pragma warning restore 618 //// //// Object[] serKeys = null; //// Object[] serValues = null; //// //// SerializationInfoEnumerator enumerator = m_siInfo.GetEnumerator(); //// //// while(enumerator.MoveNext()) //// { //// switch(enumerator.Name) //// { //// case LoadFactorName: //// m_loadFactor = m_siInfo.GetSingle( LoadFactorName ); //// break; //// //// case HashSizeName: //// hashsize = m_siInfo.GetInt32( HashSizeName ); //// break; //// //// case KeyComparerName: //// m_keycomparer = (IEqualityComparer)m_siInfo.GetValue( KeyComparerName, typeof( IEqualityComparer ) ); //// break; //// //// case ComparerName: //// c = (IComparer)m_siInfo.GetValue( ComparerName, typeof( IComparer ) ); //// break; //// //////// case HashCodeProviderName: ////////#pragma warning disable 618 //////// hcp = (IHashCodeProvider)m_siInfo.GetValue( HashCodeProviderName, typeof( IHashCodeProvider ) ); ////////#pragma warning restore 618 //////// break; //// //// case KeysName: //// serKeys = (Object[])m_siInfo.GetValue( KeysName, typeof( Object[] ) ); //// break; //// //// case ValuesName: //// serValues = (Object[])m_siInfo.GetValue( ValuesName, typeof( Object[] ) ); //// break; //// } //// } //// //// m_loadsize = (int)(m_loadFactor * hashsize); //// //////// // V1 object doesn't has _keycomparer field. //////// if((m_keycomparer == null) && ((c != null) || (hcp != null))) //////// { //////// m_keycomparer = new CompatibleComparer( c, hcp ); //////// } //// //// m_buckets = new bucket[hashsize]; //// //// if(serKeys == null) //// { //// throw new SerializationException( Environment.GetResourceString( "Serialization_MissingKeys" ) ); //// } //// //// if(serValues == null) //// { //// throw new SerializationException( Environment.GetResourceString( "Serialization_MissingValues" ) ); //// } //// //// if(serKeys.Length != serValues.Length) //// { //// throw new SerializationException( Environment.GetResourceString( "Serialization_KeyValueDifferentSizes" ) ); //// } //// //// for(int i = 0; i < serKeys.Length; i++) //// { //// if(serKeys[i] == null) //// { //// throw new SerializationException( Environment.GetResourceString( "Serialization_NullKey" ) ); //// } //// //// Insert( serKeys[i], serValues[i], true ); //// } //// //// m_version = m_siInfo.GetInt32( VersionName ); //// //// m_siInfo = null; //// } // Implements a Collection for the keys or values of a hashtable. An instance of this // class is created by the GetKeys/GetValues method of a hashtable. [Serializable] private class Collection : ICollection { private Hashtable m_hashtable; private bool m_keys; internal Collection( Hashtable hashtable, bool keys ) { m_hashtable = hashtable; m_keys = keys; } public virtual void CopyTo( Array array, int arrayIndex ) { if(array == null) { #if EXCEPTION_STRINGS throw new ArgumentNullException( "array" ); #else throw new ArgumentNullException(); #endif } if(array.Rank != 1) { #if EXCEPTION_STRINGS throw new ArgumentException( Environment.GetResourceString( "Arg_RankMultiDimNotSupported" ) ); #else throw new ArgumentException(); #endif } if(arrayIndex < 0) { #if EXCEPTION_STRINGS throw new ArgumentOutOfRangeException( "arrayIndex", Environment.GetResourceString( "ArgumentOutOfRange_NeedNonNegNum" ) ); #else throw new ArgumentOutOfRangeException(); #endif } if(array.Length - arrayIndex < m_hashtable.m_count) { #if EXCEPTION_STRINGS throw new ArgumentException( Environment.GetResourceString( "Arg_ArrayPlusOffTooSmall" ) ); #else throw new ArgumentException(); #endif } if(m_keys) { m_hashtable.CopyKeys( array, arrayIndex ); } else { m_hashtable.CopyValues( array, arrayIndex ); } } public virtual IEnumerator GetEnumerator() { return new HashtableEnumerator( m_hashtable, m_keys ? HashtableEnumerator.Keys : HashtableEnumerator.Values ); } public virtual bool IsSynchronized { get { return m_hashtable.IsSynchronized; } } public virtual Object SyncRoot { get { return m_hashtable.SyncRoot; } } public virtual int Count { get { return m_hashtable.m_count; } } } //// // Synchronized wrapper for hashtable //// [Serializable] //// private class SyncHashtable : Hashtable, IEnumerable //// { //// protected Hashtable m_table; //// //// internal SyncHashtable( Hashtable table ) : base( false ) //// { //// m_table = table; //// } //// //// internal SyncHashtable( SerializationInfo info, StreamingContext context ) : base( info, context ) //// { //// m_table = (Hashtable)info.GetValue( "ParentTable", typeof( Hashtable ) ); //// if(m_table == null) //// { //// throw new SerializationException( Environment.GetResourceString( "Serialization_InsufficientState" ) ); //// } //// } //// //// //// /*================================GetObjectData================================= //// **Action: Return a serialization info containing a reference to _table. We need //// ** to implement this because our parent HT does and we don't want to actually //// ** serialize all of it's values (just a reference to the table, which will then //// ** be serialized separately.) //// **Returns: void //// **Arguments: info -- the SerializationInfo into which to store the data. //// ** context -- the StreamingContext for the current serialization (ignored) //// **Exceptions: ArgumentNullException if info is null. //// ==============================================================================*/ //// public override void GetObjectData( SerializationInfo info, StreamingContext context ) //// { //// if(info == null) //// { //// throw new ArgumentNullException( "info" ); //// } //// //// info.AddValue( "ParentTable", m_table, typeof( Hashtable ) ); //// } //// //// public override int Count //// { //// get //// { //// return m_table.Count; //// } //// } //// //// public override bool IsReadOnly //// { //// get //// { //// return m_table.IsReadOnly; //// } //// } //// //// public override bool IsFixedSize //// { //// get //// { //// return m_table.IsFixedSize; //// } //// } //// //// public override bool IsSynchronized //// { //// get //// { //// return true; //// } //// } //// //// public override Object this[Object key] //// { //// get //// { //// return m_table[key]; //// } //// //// set //// { //// lock(m_table.SyncRoot) //// { //// m_table[key] = value; //// } //// } //// } //// //// public override Object SyncRoot //// { //// get //// { //// return m_table.SyncRoot; //// } //// } //// //// public override void Add( Object key, Object value ) //// { //// lock(m_table.SyncRoot) //// { //// m_table.Add( key, value ); //// } //// } //// //// public override void Clear() //// { //// lock(m_table.SyncRoot) //// { //// m_table.Clear(); //// } //// } //// //// public override bool Contains( Object key ) //// { //// return m_table.Contains( key ); //// } //// //// public override bool ContainsKey( Object key ) //// { //// return m_table.ContainsKey( key ); //// } //// //// public override bool ContainsValue( Object key ) //// { //// lock(m_table.SyncRoot) //// { //// return m_table.ContainsValue( key ); //// } //// } //// //// public override void CopyTo( Array array, int arrayIndex ) //// { //// lock(m_table.SyncRoot) //// { //// m_table.CopyTo( array, arrayIndex ); //// } //// } //// //// public override Object Clone() //// { //// lock(m_table.SyncRoot) //// { //// return Hashtable.Synchronized( (Hashtable)m_table.Clone() ); //// } //// } //// //// IEnumerator IEnumerable.GetEnumerator() //// { //// return m_table.GetEnumerator(); //// } //// //// public override IDictionaryEnumerator GetEnumerator() //// { //// return m_table.GetEnumerator(); //// } //// //// public override ICollection Keys //// { //// get //// { //// lock(m_table.SyncRoot) //// { //// return m_table.Keys; //// } //// } //// } //// //// public override ICollection Values //// { //// get //// { //// lock(m_table.SyncRoot) //// { //// return m_table.Values; //// } //// } //// } //// //// public override void Remove( Object key ) //// { //// lock(m_table.SyncRoot) //// { //// m_table.Remove( key ); //// } //// } //// //// /*==============================OnDeserialization=============================== //// **Action: Does nothing. We have to implement this because our parent HT implements it, //// ** but it doesn't do anything meaningful. The real work will be done when we //// ** call OnDeserialization on our parent table. //// **Returns: void //// **Arguments: None //// **Exceptions: None //// ==============================================================================*/ //// public override void OnDeserialization( Object sender ) //// { //// return; //// } //// //// internal override KeyValuePairs[] ToKeyValuePairsArray() //// { //// return m_table.ToKeyValuePairsArray(); //// } //// } // Implements an enumerator for a hashtable. The enumerator uses the // internal version number of the hashtabke to ensure that no modifications // are made to the hashtable while an enumeration is in progress. [Serializable] private class HashtableEnumerator : IDictionaryEnumerator, ICloneable { internal const int Keys = 1; internal const int Values = 2; internal const int DictEntry = 3; private Hashtable m_hashtable; private int m_bucket; private int m_version; private bool m_current; private int m_getObjectRetType; // What should GetObject return? private Object m_currentKey; private Object m_currentValue; internal HashtableEnumerator( Hashtable hashtable, int getObjRetType ) { m_hashtable = hashtable; m_bucket = hashtable.m_buckets.Length; m_version = hashtable.m_version; m_current = false; m_getObjectRetType = getObjRetType; } public Object Clone() { return MemberwiseClone(); } public virtual Object Key { get { if(m_current == false) { #if EXCEPTION_STRINGS throw new InvalidOperationException( Environment.GetResourceString( "InvalidOperation_EnumNotStarted" ) ); #else throw new InvalidOperationException(); #endif } return m_currentKey; } } public virtual bool MoveNext() { if(m_version != m_hashtable.m_version) { #if EXCEPTION_STRINGS throw new InvalidOperationException( Environment.GetResourceString( "InvalidOperation_EnumFailedVersion" ) ); #else throw new InvalidOperationException(); #endif } while(m_bucket > 0) { m_bucket--; bucket[] lbuckets = m_hashtable.m_buckets; Object keyv = lbuckets[m_bucket].key; if((keyv != null) && (keyv != lbuckets)) { m_currentKey = keyv; m_currentValue = lbuckets[m_bucket].val; m_current = true; return true; } } m_current = false; return false; } public virtual DictionaryEntry Entry { get { if(m_current == false) { #if EXCEPTION_STRINGS throw new InvalidOperationException( Environment.GetResourceString( "InvalidOperation_EnumOpCantHappen" ) ); #else throw new InvalidOperationException(); #endif } return new DictionaryEntry( m_currentKey, m_currentValue ); } } public virtual Object Current { get { if(m_current == false) { #if EXCEPTION_STRINGS throw new InvalidOperationException( Environment.GetResourceString( "InvalidOperation_EnumOpCantHappen" ) ); #else throw new InvalidOperationException(); #endif } if(m_getObjectRetType == Keys) { return m_currentKey; } else if(m_getObjectRetType == Values) { return m_currentValue; } else { return new DictionaryEntry( m_currentKey, m_currentValue ); } } } public virtual Object Value { get { if(m_current == false) { #if EXCEPTION_STRINGS throw new InvalidOperationException( Environment.GetResourceString( "InvalidOperation_EnumOpCantHappen" ) ); #else throw new InvalidOperationException(); #endif } return m_currentValue; } } public virtual void Reset() { if(m_version != m_hashtable.m_version) { #if EXCEPTION_STRINGS throw new InvalidOperationException( Environment.GetResourceString( "InvalidOperation_EnumFailedVersion" ) ); #else throw new InvalidOperationException(); #endif } m_current = false; m_bucket = m_hashtable.m_buckets.Length; m_currentKey = null; m_currentValue = null; } } //// // internal debug view class for hashtable //// internal class HashtableDebugView //// { //// private Hashtable hashtable; //// //// public HashtableDebugView( Hashtable hashtable ) //// { //// if(hashtable == null) //// { //// throw new ArgumentNullException( "hashtable" ); //// } //// //// this.hashtable = hashtable; //// } //// //// //// [DebuggerBrowsable( DebuggerBrowsableState.RootHidden )] //// public KeyValuePairs[] Items //// { //// get //// { //// return hashtable.ToKeyValuePairsArray(); //// } //// } //// } } internal static class HashHelpers { // Table of prime numbers to use as hash table sizes. // The entry used for capacity is the smallest prime number in this aaray // that is larger than twice the previous capacity. internal static readonly int[] primes = { 3, 7, 11, 17, 23, 29, 37, 47, 59, 71, 89, 107, 131, 163, 197, 239, 293, 353, 431, 521, 631, 761, 919, 1103, 1327, 1597, 1931, 2333, 2801, 3371, 4049, 4861, 5839, 7013, 8419, 10103, 12143, 14591, 17519, 21023, 25229, 30293, 36353, 43627, 52361, 62851, 75431, 90523, 108631, 130363, 156437, 187751, 225307, 270371, 324449, 389357, 467237, 560689, 672827, 807403, 968897, 1162687, 1395263, 1674319, 2009191, 2411033, 2893249, 3471899, 4166287, 4999559, 5999471, 7199369 }; //// [ReliabilityContract( Consistency.WillNotCorruptState, Cer.Success )] internal static bool IsPrime( int candidate ) { if((candidate & 1) != 0) { for(int divisor = 3; divisor * divisor <= candidate; divisor += 2) { if((candidate % divisor) == 0) { return false; } } return true; } return (candidate == 2); } //// [ReliabilityContract( Consistency.WillNotCorruptState, Cer.Success )] internal static int GetPrime( int min ) { if(min < 0) { #if EXCEPTION_STRINGS throw new ArgumentException( Environment.GetResourceString( "Arg_HTCapacityOverflow" ) ); #else throw new ArgumentException(); #endif } for(int i = 0; i < primes.Length; i++) { int prime = primes[i]; if(prime >= min) return prime; } //outside of our predefined table. //compute the hard way. for(int i = (min | 1); i < Int32.MaxValue; i += 2) { if(IsPrime( i )) { return i; } } return min; } } } ================================================ FILE: Zelig/Zelig/RunTime/Framework/mscorlib/System/Collections/ICollection.cs ================================================ // ==++== // // Copyright (c) Microsoft Corporation. All rights reserved. // // ==--== /*============================================================ ** ** Interface: ICollection ** ** ** Purpose: Base interface for all collections. ** ** ===========================================================*/ namespace System.Collections { using System; // Base interface for all collections, defining enumerators, size, and // synchronization methods. public interface ICollection : IEnumerable { // Interfaces are not serialable // CopyTo copies a collection into an Array, starting at a particular // index into the array. // void CopyTo( Array array, int index ); // Number of items in the collections. int Count { get; } // SyncRoot will return an Object to use for synchronization // (thread safety). You can use this object in your code to take a // lock on the collection, even if this collection is a wrapper around // another collection. The intent is to tunnel through to a real // implementation of a collection, and use one of the internal objects // found in that code. // // In the absense of a static Synchronized method on a collection, // the expected usage for SyncRoot would look like this: // // ICollection col = ... // lock (col.SyncRoot) { // // Some operation on the collection, which is now thread safe. // // This may include multiple operations. // } // // // The system-provided collections have a static method called // Synchronized which will create a thread-safe wrapper around the // collection. All access to the collection that you want to be // thread-safe should go through that wrapper collection. However, if // you need to do multiple calls on that collection (such as retrieving // two items, or checking the count then doing something), you should // NOT use our thread-safe wrapper since it only takes a lock for the // duration of a single method call. Instead, use Monitor.Enter/Exit // or your language's equivalent to the C# lock keyword as mentioned // above. // // For collections with no publically available underlying store, the // expected implementation is to simply return the this pointer. Note // that the this pointer may not be sufficient for collections that // wrap other collections; those should return the underlying // collection's SyncRoot property. Object SyncRoot { get; } // Is this collection synchronized (i.e., thread-safe)? If you want a // thread-safe collection, you can use SyncRoot as an object to // synchronize your collection with. If you're using one of the // collections in System.Collections, you could call the static // Synchronized method to get a thread-safe wrapper around the // underlying collection. bool IsSynchronized { get; } } } ================================================ FILE: Zelig/Zelig/RunTime/Framework/mscorlib/System/Collections/IComparer.cs ================================================ // ==++== // // Copyright (c) Microsoft Corporation. All rights reserved. // // ==--== /*============================================================ ** ** Interface: IComparer ** ** ** Purpose: Interface for comparing two Objects. ** ** ===========================================================*/ namespace System.Collections { using System; // The IComparer interface implements a method that compares two objects. It is // used in conjunction with the Sort and BinarySearch methods on // the Array and List classes. // // Interfaces are not serializable public interface IComparer { // Compares two objects. An implementation of this method must return a // value less than zero if x is less than y, zero if x is equal to y, or a // value greater than zero if x is greater than y. // int Compare( Object x, Object y ); } } ================================================ FILE: Zelig/Zelig/RunTime/Framework/mscorlib/System/Collections/IDictionary.cs ================================================ // ==++== // // Copyright (c) Microsoft Corporation. All rights reserved. // // ==--== /*============================================================ ** ** Interface: IDictionary ** ** ** Purpose: Base interface for all dictionaries. ** ** ===========================================================*/ namespace System.Collections { using System; // An IDictionary is a possibly unordered set of key-value pairs. // Keys can be any non-null object. Values can be any object. // You can look up a value in an IDictionary via the default indexed // property, Items. public interface IDictionary : ICollection { // Interfaces are not serializable // The Item property provides methods to read and edit entries // in the Dictionary. Object this[Object key] { get; set; } // Returns a collections of the keys in this dictionary. ICollection Keys { get; } // Returns a collections of the values in this dictionary. ICollection Values { get; } // Returns whether this dictionary contains a particular key. // bool Contains( Object key ); // Adds a key-value pair to the dictionary. // void Add( Object key, Object value ); // Removes all pairs from the dictionary. void Clear(); bool IsReadOnly { get; } bool IsFixedSize { get; } // Returns an IDictionaryEnumerator for this dictionary. new IDictionaryEnumerator GetEnumerator(); // Removes a particular key from the dictionary. // void Remove( Object key ); } } ================================================ FILE: Zelig/Zelig/RunTime/Framework/mscorlib/System/Collections/IDictionaryEnumerator.cs ================================================ // ==++== // // Copyright (c) Microsoft Corporation. All rights reserved. // // ==--== /*============================================================ ** ** Interface: IDictionaryEnumerator ** ** ** Purpose: Base interface for dictionary enumerators. ** ** ===========================================================*/ namespace System.Collections { // Interfaces are not serializable using System; // This interface represents an enumerator that allows sequential access to the // elements of a dictionary. Upon creation, an enumerator is conceptually // positioned before the first element of the enumeration. The first call to the // MoveNext method brings the first element of the enumeration into view, // and each successive call to MoveNext brings the next element into // view until MoveNext returns false, indicating that there are no more // elements to enumerate. Following each call to MoveNext, the // Key and Value methods are used to obtain the key and // value of the element currently in view. The values returned by calls to // Key and Value are undefined before the first call to // MoveNext and following a call to MoveNext that returned false. // Enumerators are typically used in while loops of the form // // IDictionaryEnumerator e = ...; // while (e.MoveNext()) { // Object key = e.Key; // Object value = e.Value; // ... // } // // The IDictionaryEnumerator interface extends the IEnumerator // inerface and can thus be used as a regular enumerator. The Current // method of an IDictionaryEnumerator returns a DictionaryEntry containing // the current key and value pair. However, the GetEntry method will // return the same DictionaryEntry and avoids boxing the DictionaryEntry (boxing // is somewhat expensive). // public interface IDictionaryEnumerator : IEnumerator { // Returns the key of the current element of the enumeration. The returned // value is undefined before the first call to GetNext and following // a call to GetNext that returned false. Multiple calls to // GetKey with no intervening calls to GetNext will return // the same object. // Object Key { get; } // Returns the value of the current element of the enumeration. The // returned value is undefined before the first call to GetNext and // following a call to GetNext that returned false. Multiple calls // to GetValue with no intervening calls to GetNext will // return the same object. // Object Value { get; } // GetBlock will copy dictionary values into the given Array. It will either // fill up the array, or if there aren't enough elements, it will // copy as much as possible into the Array. The number of elements // copied is returned. // DictionaryEntry Entry { get; } } } ================================================ FILE: Zelig/Zelig/RunTime/Framework/mscorlib/System/Collections/IEnumerable.cs ================================================ // ==++== // // Copyright (c) Microsoft Corporation. All rights reserved. // // ==--== /*============================================================ ** ** Interface: IEnumerable ** ** ** Purpose: Interface for classes providing IEnumerators ** ** ===========================================================*/ namespace System.Collections { using System; using System.Runtime.InteropServices; // Implement this interface if you need to support VB's foreach semantics. // Also, COM classes that support an enumerator will also implement this interface. public interface IEnumerable { // Interfaces are not serializable // Returns an IEnumerator for this enumerable Object. The enumerator provides // a simple way to access all the contents of a collection. IEnumerator GetEnumerator(); } } ================================================ FILE: Zelig/Zelig/RunTime/Framework/mscorlib/System/Collections/IEnumerator.cs ================================================ // ==++== // // Copyright (c) Microsoft Corporation. All rights reserved. // // ==--== /*============================================================ ** ** Interface: IEnumerator ** ** ** Purpose: Base interface for all enumerators. ** ** ===========================================================*/ namespace System.Collections { using System; using System.Runtime.InteropServices; // Base interface for all enumerators, providing a simple approach // to iterating over a collection. public interface IEnumerator { // Interfaces are not serializable // Advances the enumerator to the next element of the enumeration and // returns a boolean indicating whether an element is available. Upon // creation, an enumerator is conceptually positioned before the first // element of the enumeration, and the first call to MoveNext // brings the first element of the enumeration into view. // bool MoveNext(); // Returns the current element of the enumeration. The returned value is // undefined before the first call to MoveNext and following a // call to MoveNext that returned false. Multiple calls to // GetCurrent with no intervening calls to MoveNext // will return the same object. // Object Current { get; } // Resets the enumerator to the beginning of the enumeration, starting over. // The preferred behavior for Reset is to return the exact same enumeration. // This means if you modify the underlying collection then call Reset, your // IEnumerator will be invalid, just as it would have been if you had called // MoveNext or Current. // void Reset(); } } ================================================ FILE: Zelig/Zelig/RunTime/Framework/mscorlib/System/Collections/IEqualityComparer.cs ================================================ // ==++== // // Copyright (c) Microsoft Corporation. All rights reserved. // // ==--== /*============================================================ ** ** Interface: IKeyComparer ** ** ** Purpose: A mechanism to expose a simplified infrastructure for ** Comparing objects in collections. ** ** ===========================================================*/ namespace System.Collections { using System; // An IEqualityComparer is a mechanism to consume custom performant comparison infrastructure // that can be consumed by some of the common collections. public interface IEqualityComparer { bool Equals( Object x, Object y ); int GetHashCode( Object obj ); } } ================================================ FILE: Zelig/Zelig/RunTime/Framework/mscorlib/System/Collections/IList.cs ================================================ // ==++== // // Copyright (c) Microsoft Corporation. All rights reserved. // // ==--== /*============================================================ ** ** Interface: IList ** ** ** Purpose: Base interface for all Lists. ** ** ===========================================================*/ namespace System.Collections { using System; // An IList is an ordered collection of objects. The exact ordering // is up to the implementation of the list, ranging from a sorted // order to insertion order. public interface IList : ICollection { // Interfaces are not serializable // The Item property provides methods to read and edit entries in the List. Object this[int index] { get; set; } // Adds an item to the list. The exact position in the list is // implementation-dependent, so while ArrayList may always insert // in the last available location, a SortedList most likely would not. // The return value is the position the new element was inserted in. int Add( Object value ); // Returns whether the list contains a particular item. bool Contains( Object value ); // Removes all items from the list. void Clear(); bool IsReadOnly { get; } bool IsFixedSize { get; } // Returns the index of a particular item, if it is in the list. // Returns -1 if the item isn't in the list. int IndexOf( Object value ); // Inserts value into the list at position index. // index must be non-negative and less than or equal to the // number of elements in the list. If index equals the number // of items in the list, then value is appended to the end. void Insert( int index, Object value ); // Removes an item from the list. void Remove( Object value ); // Removes the item at position index. void RemoveAt( int index ); } } ================================================ FILE: Zelig/Zelig/RunTime/Framework/mscorlib/System/Collections/KeyValuePairs.cs ================================================ // ==++== // // Copyright (c) Microsoft Corporation. All rights reserved. // // ==--== /*============================================================ ** ** Class: KeyValuePairs ** ** ** Purpose: KeyValuePairs to display items in collection class under debugger ** ** ===========================================================*/ namespace System.Collections { using System.Diagnostics; ////[DebuggerDisplay( "{value}", Name = "[{key}]", Type = "" )] internal class KeyValuePairs { [DebuggerBrowsable( DebuggerBrowsableState.Never )] private object key; [DebuggerBrowsable( DebuggerBrowsableState.Never )] private object value; public KeyValuePairs( object key, object value ) { this.value = value; this.key = key; } public object Key { get { return key; } } public object Value { get { return value; } } } } ================================================ FILE: Zelig/Zelig/RunTime/Framework/mscorlib/System/Collections/ObjectModel/Collection.cs ================================================ // ==++== // // Copyright (c) Microsoft Corporation. All rights reserved. // // ==--== namespace System.Collections.ObjectModel { using System; using System.Collections; using System.Collections.Generic; using System.Diagnostics; [Serializable] ////[DebuggerTypeProxy( typeof( Mscorlib_CollectionDebugView<> ) )] ////[DebuggerDisplay( "Count = {Count}" )] public class Collection : IList, IList { IList m_items; [NonSerialized] private Object m_syncRoot; public Collection() { m_items = new List(); } public Collection( IList list ) { if(list == null) { ThrowHelper.ThrowArgumentNullException( ExceptionArgument.list ); } m_items = list; } public int Count { get { return m_items.Count; } } protected IList Items { get { return m_items; } } public T this[int index] { get { return m_items[index]; } set { if(m_items.IsReadOnly) { ThrowHelper.ThrowNotSupportedException( ExceptionResource.NotSupported_ReadOnlyCollection ); } if(index < 0 || index >= m_items.Count) { ThrowHelper.ThrowArgumentOutOfRangeException(); } SetItem( index, value ); } } public void Add( T item ) { if(m_items.IsReadOnly) { ThrowHelper.ThrowNotSupportedException( ExceptionResource.NotSupported_ReadOnlyCollection ); } int index = m_items.Count; InsertItem( index, item ); } public void Clear() { if(m_items.IsReadOnly) { ThrowHelper.ThrowNotSupportedException( ExceptionResource.NotSupported_ReadOnlyCollection ); } ClearItems(); } public void CopyTo( T[] array, int index ) { m_items.CopyTo( array, index ); } public bool Contains( T item ) { return m_items.Contains( item ); } public IEnumerator GetEnumerator() { return m_items.GetEnumerator(); } public int IndexOf( T item ) { return m_items.IndexOf( item ); } public void Insert( int index, T item ) { if(m_items.IsReadOnly) { ThrowHelper.ThrowNotSupportedException( ExceptionResource.NotSupported_ReadOnlyCollection ); } if(index < 0 || index > m_items.Count) { ThrowHelper.ThrowArgumentOutOfRangeException( ExceptionArgument.index, ExceptionResource.ArgumentOutOfRange_ListInsert ); } InsertItem( index, item ); } public bool Remove( T item ) { if(m_items.IsReadOnly) { ThrowHelper.ThrowNotSupportedException( ExceptionResource.NotSupported_ReadOnlyCollection ); } int index = m_items.IndexOf( item ); if(index < 0) { return false; } RemoveItem( index ); return true; } public void RemoveAt( int index ) { if(m_items.IsReadOnly) { ThrowHelper.ThrowNotSupportedException( ExceptionResource.NotSupported_ReadOnlyCollection ); } if(index < 0 || index >= m_items.Count) { ThrowHelper.ThrowArgumentOutOfRangeException(); } RemoveItem( index ); } protected virtual void ClearItems() { m_items.Clear(); } protected virtual void InsertItem( int index, T item ) { m_items.Insert( index, item ); } protected virtual void RemoveItem( int index ) { m_items.RemoveAt( index ); } protected virtual void SetItem( int index, T item ) { m_items[index] = item; } bool ICollection.IsReadOnly { get { return m_items.IsReadOnly; } } IEnumerator IEnumerable.GetEnumerator() { return ((IEnumerable)m_items).GetEnumerator(); } bool ICollection.IsSynchronized { get { return false; } } object ICollection.SyncRoot { get { if(m_syncRoot == null) { ICollection c = m_items as ICollection; if(c != null) { m_syncRoot = c.SyncRoot; } else { System.Threading.Interlocked.CompareExchange( ref m_syncRoot, new Object(), null ); } } return m_syncRoot; } } void ICollection.CopyTo( Array array, int index ) { if(array == null) { ThrowHelper.ThrowArgumentNullException( ExceptionArgument.array ); } if(array.Rank != 1) { ThrowHelper.ThrowArgumentException( ExceptionResource.Arg_RankMultiDimNotSupported ); } if(array.GetLowerBound( 0 ) != 0) { ThrowHelper.ThrowArgumentException( ExceptionResource.Arg_NonZeroLowerBound ); } if(index < 0) { ThrowHelper.ThrowArgumentOutOfRangeException( ExceptionArgument.index, ExceptionResource.ArgumentOutOfRange_NeedNonNegNum ); } if(array.Length - index < Count) { ThrowHelper.ThrowArgumentException( ExceptionResource.Arg_ArrayPlusOffTooSmall ); } T[] tArray = array as T[]; if(tArray != null) { m_items.CopyTo( tArray, index ); } else { // // Catch the obvious case assignment will fail. // We can found all possible problems by doing the check though. // For example, if the element type of the Array is derived from T, // we can't figure out if we can successfully copy the element beforehand. // Type targetType = array.GetType().GetElementType(); Type sourceType = typeof( T ); if(!(targetType.IsAssignableFrom( sourceType ) || sourceType.IsAssignableFrom( targetType ))) { ThrowHelper.ThrowArgumentException( ExceptionResource.Argument_InvalidArrayType ); } // // We can't cast array of value type to object[], so we don't support // widening of primitive types here. // object[] objects = array as object[]; if(objects == null) { ThrowHelper.ThrowArgumentException( ExceptionResource.Argument_InvalidArrayType ); } int count = m_items.Count; try { for(int i = 0; i < count; i++) { objects[index++] = m_items[i]; } } catch(ArrayTypeMismatchException) { ThrowHelper.ThrowArgumentException( ExceptionResource.Argument_InvalidArrayType ); } } } object IList.this[int index] { get { return m_items[index]; } set { ThrowHelper.IfNullAndNullsAreIllegalThenThrow( value, ExceptionArgument.value ); try { this[index] = (T)value; } catch(InvalidCastException) { ThrowHelper.ThrowWrongValueTypeArgumentException( value, typeof( T ) ); } } } bool IList.IsReadOnly { get { return m_items.IsReadOnly; } } bool IList.IsFixedSize { get { // There is no IList.IsFixedSize, so we must assume that only // readonly collections are fixed size, if our internal item // collection does not implement IList. Note that Array implements // IList, and therefore T[] and U[] will be fixed-size. IList list = m_items as IList; if(list != null) { return list.IsFixedSize; } return m_items.IsReadOnly; } } int IList.Add( object value ) { if(m_items.IsReadOnly) { ThrowHelper.ThrowNotSupportedException( ExceptionResource.NotSupported_ReadOnlyCollection ); } ThrowHelper.IfNullAndNullsAreIllegalThenThrow( value, ExceptionArgument.value ); try { Add( (T)value ); } catch(InvalidCastException) { ThrowHelper.ThrowWrongValueTypeArgumentException( value, typeof( T ) ); } return this.Count - 1; } bool IList.Contains( object value ) { if(IsCompatibleObject( value )) { return Contains( (T)value ); } return false; } int IList.IndexOf( object value ) { if(IsCompatibleObject( value )) { return IndexOf( (T)value ); } return -1; } void IList.Insert( int index, object value ) { if(m_items.IsReadOnly) { ThrowHelper.ThrowNotSupportedException( ExceptionResource.NotSupported_ReadOnlyCollection ); } ThrowHelper.IfNullAndNullsAreIllegalThenThrow( value, ExceptionArgument.value ); try { Insert( index, (T)value ); } catch(InvalidCastException) { ThrowHelper.ThrowWrongValueTypeArgumentException( value, typeof( T ) ); } } void IList.Remove( object value ) { if(m_items.IsReadOnly) { ThrowHelper.ThrowNotSupportedException( ExceptionResource.NotSupported_ReadOnlyCollection ); } if(IsCompatibleObject( value )) { Remove( (T)value ); } } private static bool IsCompatibleObject( object value ) { // Non-null values are fine. Only accept nulls if T is a class or Nullable. // Note that default(T) is not equal to null for value types except when T is Nullable. return ((value is T) || (value == null && default( T ) == null)); } } } ================================================ FILE: Zelig/Zelig/RunTime/Framework/mscorlib/System/Collections/ObjectModel/KeyedCollection.cs ================================================ // ==++== // // Copyright (c) Microsoft Corporation. All rights reserved. // // ==--== namespace System.Collections.ObjectModel { using System; using System.Collections.Generic; using System.Diagnostics; [Serializable] ////[DebuggerTypeProxy( typeof( Mscorlib_KeyedCollectionDebugView<,> ) )] ////[DebuggerDisplay( "Count = {Count}" )] public abstract class KeyedCollection : Collection { const int defaultThreshold = 0; IEqualityComparer m_comparer; Dictionary m_dict; int m_keyCount; int m_threshold; protected KeyedCollection() : this( null, defaultThreshold ) { } protected KeyedCollection( IEqualityComparer comparer ) : this( comparer, defaultThreshold ) { } protected KeyedCollection( IEqualityComparer comparer, int dictionaryCreationThreshold ) { if(comparer == null) { comparer = EqualityComparer.Default; } if(dictionaryCreationThreshold == -1) { dictionaryCreationThreshold = int.MaxValue; } if(dictionaryCreationThreshold < -1) { ThrowHelper.ThrowArgumentOutOfRangeException( ExceptionArgument.dictionaryCreationThreshold, ExceptionResource.ArgumentOutOfRange_InvalidThreshold ); } m_comparer = comparer; m_threshold = dictionaryCreationThreshold; } public IEqualityComparer Comparer { get { return m_comparer; } } public TItem this[TKey key] { get { if(key == null) { ThrowHelper.ThrowArgumentNullException( ExceptionArgument.key ); } if(m_dict != null) { return m_dict[key]; } foreach(TItem item in Items) { if(m_comparer.Equals( GetKeyForItem( item ), key )) { return item; } } ThrowHelper.ThrowKeyNotFoundException(); return default( TItem ); } } public bool Contains( TKey key ) { if(key == null) { ThrowHelper.ThrowArgumentNullException( ExceptionArgument.key ); } if(m_dict != null) { return m_dict.ContainsKey( key ); } if(key != null) { foreach(TItem item in Items) { if(m_comparer.Equals( GetKeyForItem( item ), key )) { return true; } } } return false; } private bool ContainsItem( TItem item ) { TKey key; if((m_dict == null) || ((key = GetKeyForItem( item )) == null)) { return Items.Contains( item ); } TItem itemInDict; bool exist = m_dict.TryGetValue( key, out itemInDict ); if(exist) { return EqualityComparer.Default.Equals( itemInDict, item ); } return false; } public bool Remove( TKey key ) { if(key == null) { ThrowHelper.ThrowArgumentNullException( ExceptionArgument.key ); } if(m_dict != null) { if(m_dict.ContainsKey( key )) { return Remove( m_dict[key] ); } return false; } if(key != null) { for(int i = 0; i < Items.Count; i++) { if(m_comparer.Equals( GetKeyForItem( Items[i] ), key )) { RemoveItem( i ); return true; } } } return false; } protected IDictionary Dictionary { get { return m_dict; } } protected void ChangeItemKey( TItem item, TKey newKey ) { // check if the item exists in the collection if(!ContainsItem( item )) { ThrowHelper.ThrowArgumentException( ExceptionResource.Argument_ItemNotExist ); } TKey oldKey = GetKeyForItem( item ); if(!m_comparer.Equals( oldKey, newKey )) { if(newKey != null) { AddKey( newKey, item ); } if(oldKey != null) { RemoveKey( oldKey ); } } } protected override void ClearItems() { base.ClearItems(); if(m_dict != null) { m_dict.Clear(); } m_keyCount = 0; } protected abstract TKey GetKeyForItem( TItem item ); protected override void InsertItem( int index, TItem item ) { TKey key = GetKeyForItem( item ); if(key != null) { AddKey( key, item ); } base.InsertItem( index, item ); } protected override void RemoveItem( int index ) { TKey key = GetKeyForItem( Items[index] ); if(key != null) { RemoveKey( key ); } base.RemoveItem( index ); } protected override void SetItem( int index, TItem item ) { TKey newKey = GetKeyForItem( item ); TKey oldKey = GetKeyForItem( Items[index] ); if(m_comparer.Equals( oldKey, newKey )) { if(newKey != null && m_dict != null) { m_dict[newKey] = item; } } else { if(newKey != null) { AddKey( newKey, item ); } if(oldKey != null) { RemoveKey( oldKey ); } } base.SetItem( index, item ); } private void AddKey( TKey key, TItem item ) { if(m_dict != null) { m_dict.Add( key, item ); } else if(m_keyCount == m_threshold) { CreateDictionary(); m_dict.Add( key, item ); } else { if(Contains( key )) { ThrowHelper.ThrowArgumentException( ExceptionResource.Argument_AddingDuplicate ); } m_keyCount++; } } private void CreateDictionary() { m_dict = new Dictionary( m_comparer ); foreach(TItem item in Items) { TKey key = GetKeyForItem( item ); if(key != null) { m_dict.Add( key, item ); } } } private void RemoveKey( TKey key ) { BCLDebug.Assert( key != null, "key shouldn't be null!" ); if(m_dict != null) { m_dict.Remove( key ); } else { m_keyCount--; } } } } ================================================ FILE: Zelig/Zelig/RunTime/Framework/mscorlib/System/Collections/ObjectModel/ReadOnlyCollection.cs ================================================ // ==++== // // Copyright (c) Microsoft Corporation. All rights reserved. // // ==--== namespace System.Collections.ObjectModel { using System; using System.Collections; using System.Collections.Generic; using System.Diagnostics; [Serializable] ////[DebuggerTypeProxy( typeof( Mscorlib_CollectionDebugView<> ) )] ////[DebuggerDisplay( "Count = {Count}" )] public class ReadOnlyCollection : IList, IList { IList list; [NonSerialized] private Object _syncRoot; public ReadOnlyCollection( IList list ) { if(list == null) { ThrowHelper.ThrowArgumentNullException( ExceptionArgument.list ); } this.list = list; } public int Count { get { return list.Count; } } public T this[int index] { get { return list[index]; } } public bool Contains( T value ) { return list.Contains( value ); } public void CopyTo( T[] array, int index ) { list.CopyTo( array, index ); } public IEnumerator GetEnumerator() { return list.GetEnumerator(); } public int IndexOf( T value ) { return list.IndexOf( value ); } protected IList Items { get { return list; } } bool ICollection.IsReadOnly { get { return true; } } T IList.this[int index] { get { return list[index]; } set { ThrowHelper.ThrowNotSupportedException( ExceptionResource.NotSupported_ReadOnlyCollection ); } } void ICollection.Add( T value ) { ThrowHelper.ThrowNotSupportedException( ExceptionResource.NotSupported_ReadOnlyCollection ); } void ICollection.Clear() { ThrowHelper.ThrowNotSupportedException( ExceptionResource.NotSupported_ReadOnlyCollection ); } void IList.Insert( int index, T value ) { ThrowHelper.ThrowNotSupportedException( ExceptionResource.NotSupported_ReadOnlyCollection ); } bool ICollection.Remove( T value ) { ThrowHelper.ThrowNotSupportedException( ExceptionResource.NotSupported_ReadOnlyCollection ); return false; } void IList.RemoveAt( int index ) { ThrowHelper.ThrowNotSupportedException( ExceptionResource.NotSupported_ReadOnlyCollection ); } IEnumerator IEnumerable.GetEnumerator() { return ((IEnumerable)list).GetEnumerator(); } bool ICollection.IsSynchronized { get { return false; } } object ICollection.SyncRoot { get { if(_syncRoot == null) { ICollection c = list as ICollection; if(c != null) { _syncRoot = c.SyncRoot; } else { System.Threading.Interlocked.CompareExchange( ref _syncRoot, new Object(), null ); } } return _syncRoot; } } void ICollection.CopyTo( Array array, int index ) { if(array == null) { ThrowHelper.ThrowArgumentNullException( ExceptionArgument.array ); } if(array.Rank != 1) { ThrowHelper.ThrowArgumentException( ExceptionResource.Arg_RankMultiDimNotSupported ); } if(array.GetLowerBound( 0 ) != 0) { ThrowHelper.ThrowArgumentException( ExceptionResource.Arg_NonZeroLowerBound ); } if(index < 0) { ThrowHelper.ThrowArgumentOutOfRangeException( ExceptionArgument.arrayIndex, ExceptionResource.ArgumentOutOfRange_NeedNonNegNum ); } if(array.Length - index < Count) { ThrowHelper.ThrowArgumentException( ExceptionResource.Arg_ArrayPlusOffTooSmall ); } T[] items = array as T[]; if(items != null) { list.CopyTo( items, index ); } else { // // Catch the obvious case assignment will fail. // We can found all possible problems by doing the check though. // For example, if the element type of the Array is derived from T, // we can't figure out if we can successfully copy the element beforehand. // Type targetType = array.GetType().GetElementType(); Type sourceType = typeof( T ); if(!(targetType.IsAssignableFrom( sourceType ) || sourceType.IsAssignableFrom( targetType ))) { ThrowHelper.ThrowArgumentException( ExceptionResource.Argument_InvalidArrayType ); } // // We can't cast array of value type to object[], so we don't support // widening of primitive types here. // object[] objects = array as object[]; if(objects == null) { ThrowHelper.ThrowArgumentException( ExceptionResource.Argument_InvalidArrayType ); } int count = list.Count; try { for(int i = 0; i < count; i++) { objects[index++] = list[i]; } } catch(ArrayTypeMismatchException) { ThrowHelper.ThrowArgumentException( ExceptionResource.Argument_InvalidArrayType ); } } } bool IList.IsFixedSize { get { return true; } } bool IList.IsReadOnly { get { return true; } } object IList.this[int index] { get { return list[index]; } set { ThrowHelper.ThrowNotSupportedException( ExceptionResource.NotSupported_ReadOnlyCollection ); } } int IList.Add( object value ) { ThrowHelper.ThrowNotSupportedException( ExceptionResource.NotSupported_ReadOnlyCollection ); return -1; } void IList.Clear() { ThrowHelper.ThrowNotSupportedException( ExceptionResource.NotSupported_ReadOnlyCollection ); } private static bool IsCompatibleObject( object value ) { // Non-null values are fine. Only accept nulls if T is a class or Nullable. // Note that default(T) is not equal to null for value types except when T is Nullable. return ((value is T) || (value == null && default( T ) == null)); } bool IList.Contains( object value ) { if(IsCompatibleObject( value )) { return Contains( (T)value ); } return false; } int IList.IndexOf( object value ) { if(IsCompatibleObject( value )) { return IndexOf( (T)value ); } return -1; } void IList.Insert( int index, object value ) { ThrowHelper.ThrowNotSupportedException( ExceptionResource.NotSupported_ReadOnlyCollection ); } void IList.Remove( object value ) { ThrowHelper.ThrowNotSupportedException( ExceptionResource.NotSupported_ReadOnlyCollection ); } void IList.RemoveAt( int index ) { ThrowHelper.ThrowNotSupportedException( ExceptionResource.NotSupported_ReadOnlyCollection ); } } } ================================================ FILE: Zelig/Zelig/RunTime/Framework/mscorlib/System/Collections/Queue.cs ================================================ // ==++== // // Copyright (c) Microsoft Corporation. All rights reserved. // // ==--== /*============================================================================= ** ** Class: Queue ** ** Purpose: A circular-array implementation of a queue. ** ** =============================================================================*/ namespace System.Collections { using System; ////using System.Security.Permissions; using System.Diagnostics; // A simple Queue of objects. Internally it is implemented as a circular // buffer, so Enqueue can be O(n). Dequeue is O(1). ////[DebuggerTypeProxy( typeof( System.Collections.Queue.QueueDebugView ) )] ////[DebuggerDisplay( "Count = {Count}" )] [Serializable] public class Queue : ICollection, ICloneable { private const int cMinimumGrow = 4; private const int cShrinkThreshold = 32; private Object[] m_array; private int m_head; // First valid element in the queue private int m_tail; // Last valid element in the queue private int m_size; // Number of elements. private int m_growFactor; // 100 == 1.0, 130 == 1.3, 200 == 2.0 private int m_version; [NonSerialized] private Object m_syncRoot; // Creates a queue with room for capacity objects. The default initial // capacity and grow factor are used. public Queue() : this( 32, (float)2.0 ) { } // Creates a queue with room for capacity objects. The default grow factor // is used. // public Queue( int capacity ) : this( capacity, (float)2.0 ) { } // Creates a queue with room for capacity objects. When full, the new // capacity is set to the old capacity * growFactor. // public Queue( int capacity, float growFactor ) { if(capacity < 0) { #if EXCEPTION_STRINGS throw new ArgumentOutOfRangeException( "capacity", Environment.GetResourceString( "ArgumentOutOfRange_NeedNonNegNum" ) ); #else throw new ArgumentOutOfRangeException(); #endif } if(!(growFactor >= 1.0 && growFactor <= 10.0)) { #if EXCEPTION_STRINGS throw new ArgumentOutOfRangeException( "growFactor", Environment.GetResourceString( "ArgumentOutOfRange_QueueGrowFactor", 1, 10 ) ); #else throw new ArgumentOutOfRangeException(); #endif } m_array = new Object[capacity]; m_head = 0; m_tail = 0; m_size = 0; m_growFactor = (int)(growFactor * 100); } // Fills a Queue with the elements of an ICollection. Uses the enumerator // to get each of the elements. // public Queue( ICollection col ) : this( (col == null ? 32 : col.Count) ) { if(col == null) { #if EXCEPTION_STRINGS throw new ArgumentNullException( "col" ); #else throw new ArgumentNullException(); #endif } IEnumerator en = col.GetEnumerator(); while(en.MoveNext()) { Enqueue( en.Current ); } } public virtual int Count { get { return m_size; } } public virtual Object Clone() { Queue q = new Queue( m_size ); q.m_size = m_size; int numToCopy = m_size; int firstPart = Math.Min( m_array.Length - m_head, numToCopy ); Array.Copy( m_array, m_head, q.m_array, 0, firstPart ); numToCopy -= firstPart; if(numToCopy > 0) { Array.Copy( m_array, 0, q.m_array, m_array.Length - m_head, numToCopy ); } q.m_version = m_version; return q; } public virtual bool IsSynchronized { get { return false; } } public virtual Object SyncRoot { get { if(m_syncRoot == null) { System.Threading.Interlocked.CompareExchange( ref m_syncRoot, new Object(), null ); } return m_syncRoot; } } // Removes all Objects from the queue. public virtual void Clear() { if(m_head < m_tail) { Array.Clear( m_array, m_head, m_size ); } else { Array.Clear( m_array, m_head, m_array.Length - m_head ); Array.Clear( m_array, 0 , m_tail ); } m_head = 0; m_tail = 0; m_size = 0; m_version++; } // CopyTo copies a collection into an Array, starting at a particular // index into the array. // public virtual void CopyTo( Array array, int index ) { if(array == null) { #if EXCEPTION_STRINGS throw new ArgumentNullException( "array" ); #else throw new ArgumentNullException(); #endif } if(array.Rank != 1) { #if EXCEPTION_STRINGS throw new ArgumentException( Environment.GetResourceString( "Arg_RankMultiDimNotSupported" ) ); #else throw new ArgumentException(); #endif } if(index < 0) { #if EXCEPTION_STRINGS throw new ArgumentOutOfRangeException( "index", Environment.GetResourceString( "ArgumentOutOfRange_Index" ) ); #else throw new ArgumentOutOfRangeException(); #endif } int arrayLen = array.Length; if(arrayLen - index < m_size) { #if EXCEPTION_STRINGS throw new ArgumentException( Environment.GetResourceString( "Argument_InvalidOffLen" ) ); #else throw new ArgumentException(); #endif } int numToCopy = m_size; if(numToCopy == 0) { return; } int firstPart = Math.Min( m_array.Length - m_head, numToCopy ); Array.Copy( m_array, m_head, array, index, firstPart ); numToCopy -= firstPart; if(numToCopy > 0) { Array.Copy( m_array, 0, array, index + m_array.Length - m_head, numToCopy ); } } // Adds obj to the tail of the queue. // public virtual void Enqueue( Object obj ) { if(m_size == m_array.Length) { int newcapacity = (int)((long)m_array.Length * (long)m_growFactor / 100); if(newcapacity < m_array.Length + cMinimumGrow) { newcapacity = m_array.Length + cMinimumGrow; } SetCapacity( newcapacity ); } m_array[m_tail] = obj; //// m_tail = (m_tail + 1) % m_array.Length; int tailNext = m_tail + 1; m_tail = (tailNext == m_array.Length) ? 0 : tailNext; m_size++; m_version++; } // GetEnumerator returns an IEnumerator over this Queue. This // Enumerator will support removing. // public virtual IEnumerator GetEnumerator() { return new QueueEnumerator( this ); } // Removes the object at the head of the queue and returns it. If the queue // is empty, this method simply returns null. public virtual Object Dequeue() { if(m_size == 0) { #if EXCEPTION_STRINGS throw new InvalidOperationException( Environment.GetResourceString( "InvalidOperation_EmptyQueue" ) ); #else throw new InvalidOperationException(); #endif } Object removed = m_array[m_head]; m_array[m_head] = null; //// m_head = (m_head + 1) % m_array.Length; int headNext = m_head + 1; m_head = (headNext == m_array.Length) ? 0 : headNext; m_size--; m_version++; return removed; } // Returns the object at the head of the queue. The object remains in the // queue. If the queue is empty, this method throws an // InvalidOperationException. public virtual Object Peek() { if(m_size == 0) { #if EXCEPTION_STRINGS throw new InvalidOperationException( Environment.GetResourceString( "InvalidOperation_EmptyQueue" ) ); #else throw new InvalidOperationException(); #endif } return m_array[m_head]; } //// // Returns a synchronized Queue. Returns a synchronized wrapper //// // class around the queue - the caller must not use references to the //// // original queue. //// // //// [HostProtection( Synchronization = true )] //// public static Queue Synchronized( Queue queue ) //// { //// if(queue == null) //// { //// throw new ArgumentNullException( "queue" ); //// } //// //// return new SynchronizedQueue( queue ); //// } // Returns true if the queue contains at least one object equal to obj. // Equality is determined using obj.Equals(). // // Exceptions: ArgumentNullException if obj == null. public virtual bool Contains( Object obj ) { int index = m_head; int count = m_size; while(count-- > 0) { if(obj == null) { if(m_array[index] == null) { return true; } } else if(m_array[index] != null && m_array[index].Equals( obj )) { return true; } //// index = (index + 1) % m_array.Length; index = (index + 1); if(index == m_array.Length) { index = 0; } } return false; } internal Object GetElement( int i ) { return m_array[(m_head + i) % m_array.Length]; } // Iterates over the objects in the queue, returning an array of the // objects in the Queue, or an empty array if the queue is empty. // The order of elements in the array is first in to last in, the same // order produced by successive calls to Dequeue. public virtual Object[] ToArray() { Object[] arr = new Object[m_size]; if(m_size == 0) { return arr; } if(m_head < m_tail) { Array.Copy( m_array, m_head, arr, 0, m_size ); } else { Array.Copy( m_array, m_head, arr, 0 , m_array.Length - m_head ); Array.Copy( m_array, 0 , arr, m_array.Length - m_head, m_tail ); } return arr; } // PRIVATE Grows or shrinks the buffer to hold capacity objects. Capacity // must be >= _size. private void SetCapacity( int capacity ) { Object[] newarray = new Object[capacity]; if(m_size > 0) { if(m_head < m_tail) { Array.Copy( m_array, m_head, newarray, 0, m_size ); } else { Array.Copy( m_array, m_head, newarray, 0 , m_array.Length - m_head ); Array.Copy( m_array, 0 , newarray, m_array.Length - m_head, m_tail ); } } m_array = newarray; m_head = 0; m_tail = (m_size == capacity) ? 0 : m_size; m_version++; } public virtual void TrimToSize() { SetCapacity( m_size ); } //// // Implements a synchronization wrapper around a queue. //// [Serializable] //// private class SynchronizedQueue : Queue //// { //// private Queue m_q; //// private Object m_root; //// //// internal SynchronizedQueue( Queue q ) //// { //// m_q = q; //// m_root = q.SyncRoot; //// } //// //// public override bool IsSynchronized //// { //// get //// { //// return true; //// } //// } //// //// public override Object SyncRoot //// { //// get //// { //// return m_root; //// } //// } //// //// public override int Count //// { //// get //// { //// lock(m_root) //// { //// return m_q.Count; //// } //// } //// } //// //// public override void Clear() //// { //// lock(m_root) //// { //// m_q.Clear(); //// } //// } //// //// public override Object Clone() //// { //// lock(m_root) //// { //// return new SynchronizedQueue( (Queue)m_q.Clone() ); //// } //// } //// //// public override bool Contains( Object obj ) //// { //// lock(m_root) //// { //// return m_q.Contains( obj ); //// } //// } //// //// public override void CopyTo( Array array, int arrayIndex ) //// { //// lock(m_root) //// { //// m_q.CopyTo( array, arrayIndex ); //// } //// } //// //// public override void Enqueue( Object value ) //// { //// lock(m_root) //// { //// m_q.Enqueue( value ); //// } //// } //// //// public override Object Dequeue() //// { //// lock(m_root) //// { //// return m_q.Dequeue(); //// } //// } //// //// public override IEnumerator GetEnumerator() //// { //// lock(m_root) //// { //// return m_q.GetEnumerator(); //// } //// } //// //// public override Object Peek() //// { //// lock(m_root) //// { //// return m_q.Peek(); //// } //// } //// //// public override Object[] ToArray() //// { //// lock(m_root) //// { //// return m_q.ToArray(); //// } //// } //// //// public override void TrimToSize() //// { //// lock(m_root) //// { //// m_q.TrimToSize(); //// } //// } //// } // Implements an enumerator for a Queue. The enumerator uses the // internal version number of the list to ensure that no modifications are // made to the list while an enumeration is in progress. [Serializable] private class QueueEnumerator : IEnumerator, ICloneable { private Queue m_q; private int m_index; private int m_version; private Object m_currentElement; internal QueueEnumerator( Queue q ) { m_q = q; m_version = q.m_version; m_index = 0; m_currentElement = q.m_array; if(q.m_size == 0) { m_index = -1; } } public Object Clone() { return MemberwiseClone(); } public virtual bool MoveNext() { if(m_version != m_q.m_version) { #if EXCEPTION_STRINGS throw new InvalidOperationException( Environment.GetResourceString( "InvalidOperation_EnumFailedVersion" ) ); #else throw new InvalidOperationException(); #endif } if(m_index < 0) { m_currentElement = m_q.m_array; return false; } m_currentElement = m_q.GetElement( m_index ); m_index++; if(m_index == m_q.m_size) { m_index = -1; } return true; } public virtual Object Current { get { if(m_currentElement == m_q.m_array) { if(m_index == 0) { #if EXCEPTION_STRINGS throw new InvalidOperationException( Environment.GetResourceString( "InvalidOperation_EnumNotStarted" ) ); #else throw new InvalidOperationException(); #endif } else { #if EXCEPTION_STRINGS throw new InvalidOperationException( Environment.GetResourceString( "InvalidOperation_EnumEnded" ) ); #else throw new InvalidOperationException(); #endif } } return m_currentElement; } } public virtual void Reset() { if(m_version != m_q.m_version) { #if EXCEPTION_STRINGS throw new InvalidOperationException( Environment.GetResourceString( "InvalidOperation_EnumFailedVersion" ) ); #else throw new InvalidOperationException(); #endif } if(m_q.m_size == 0) { m_index = -1; } else { m_index = 0; } m_currentElement = m_q.m_array; } } //// internal class QueueDebugView //// { //// private Queue queue; //// //// public QueueDebugView( Queue queue ) //// { //// if(queue == null) //// { //// throw new ArgumentNullException( "queue" ); //// } //// //// this.queue = queue; //// } //// //// [DebuggerBrowsable( DebuggerBrowsableState.RootHidden )] //// public Object[] Items //// { //// get //// { //// return queue.ToArray(); //// } //// } //// } } } ================================================ FILE: Zelig/Zelig/RunTime/Framework/mscorlib/System/Collections/ReadOnlyCollectionBase.cs ================================================ // ==++== // // Copyright (c) Microsoft Corporation. All rights reserved. // // ==--== //------------------------------------------------------------------------------ //------------------------------------------------------------------------------ namespace System.Collections { using System; // Useful base class for typed readonly collections where items derive from object [Serializable] ////[System.Runtime.InteropServices.ComVisible( true )] public abstract class ReadOnlyCollectionBase : ICollection { ArrayList list; protected ArrayList InnerList { get { if(list == null) { list = new ArrayList(); } return list; } } public virtual int Count { get { return InnerList.Count; } } bool ICollection.IsSynchronized { get { return InnerList.IsSynchronized; } } object ICollection.SyncRoot { get { return InnerList.SyncRoot; } } void ICollection.CopyTo( Array array, int index ) { InnerList.CopyTo( array, index ); } public virtual IEnumerator GetEnumerator() { return InnerList.GetEnumerator(); } } } ================================================ FILE: Zelig/Zelig/RunTime/Framework/mscorlib/System/Collections/SortedList.cs ================================================ // ==++== // // Copyright (c) Microsoft Corporation. All rights reserved. // // ==--== /*============================================================ ** ** Class: SortedList ** ** Purpose: A sorted dictionary. ** ** ===========================================================*/ namespace System.Collections { using System; ////using System.Security.Permissions; using System.Diagnostics; using System.Globalization; // The SortedList class implements a sorted list of keys and values. Entries in // a sorted list are sorted by their keys and are accessible both by key and by // index. The keys of a sorted list can be ordered either according to a // specific IComparer implementation given when the sorted list is // instantiated, or according to the IComparable implementation provided // by the keys themselves. In either case, a sorted list does not allow entries // with duplicate keys. // // A sorted list internally maintains two arrays that store the keys and // values of the entries. The capacity of a sorted list is the allocated // length of these internal arrays. As elements are added to a sorted list, the // capacity of the sorted list is automatically increased as required by // reallocating the internal arrays. The capacity is never automatically // decreased, but users can call either TrimToSize or // Capacity explicitly. // // The GetKeyList and GetValueList methods of a sorted list // provides access to the keys and values of the sorted list in the form of // List implementations. The List objects returned by these // methods are aliases for the underlying sorted list, so modifications // made to those lists are directly reflected in the sorted list, and vice // versa. // // The SortedList class provides a convenient way to create a sorted // copy of another dictionary, such as a Hashtable. For example: // // Hashtable h = new Hashtable(); // h.Add(...); // h.Add(...); // ... // SortedList s = new SortedList(h); // // The last line above creates a sorted list that contains a copy of the keys // and values stored in the hashtable. In this particular example, the keys // will be ordered according to the IComparable interface, which they // all must implement. To impose a different ordering, SortedList also // has a constructor that allows a specific IComparer implementation to // be specified. // ////[DebuggerTypeProxy( typeof( System.Collections.SortedList.SortedListDebugView ) )] ////[DebuggerDisplay( "Count = {Count}" )] [Serializable] public class SortedList : IDictionary, ICloneable { private const int cDefaultCapacity = 16; private static Object[] emptyArray = new Object[0]; private Object[] m_keys; private Object[] m_values; private int m_size; private int m_version; private IComparer m_comparer; private KeyList m_keyList; private ValueList m_valueList; [NonSerialized] private Object m_syncRoot; // Constructs a new sorted list. The sorted list is initially empty and has // a capacity of zero. Upon adding the first element to the sorted list the // capacity is increased to 16, and then increased in multiples of two as // required. The elements of the sorted list are ordered according to the // IComparable interface, which must be implemented by the keys of // all entries added to the sorted list. public SortedList() { m_keys = emptyArray; m_values = emptyArray; m_size = 0; m_comparer = new Comparer( CultureInfo.CurrentCulture ); } // Constructs a new sorted list. The sorted list is initially empty and has // a capacity of zero. Upon adding the first element to the sorted list the // capacity is increased to 16, and then increased in multiples of two as // required. The elements of the sorted list are ordered according to the // IComparable interface, which must be implemented by the keys of // all entries added to the sorted list. // public SortedList( int initialCapacity ) { if(initialCapacity < 0) { #if EXCEPTION_STRINGS throw new ArgumentOutOfRangeException( "initialCapacity", Environment.GetResourceString( "ArgumentOutOfRange_NeedNonNegNum" ) ); #else throw new ArgumentOutOfRangeException(); #endif } m_keys = new Object[initialCapacity]; m_values = new Object[initialCapacity]; m_comparer = new Comparer( CultureInfo.CurrentCulture ); } // Constructs a new sorted list with a given IComparer // implementation. The sorted list is initially empty and has a capacity of // zero. Upon adding the first element to the sorted list the capacity is // increased to 16, and then increased in multiples of two as required. The // elements of the sorted list are ordered according to the given // IComparer implementation. If comparer is null, the // elements are compared to each other using the IComparable // interface, which in that case must be implemented by the keys of all // entries added to the sorted list. // public SortedList( IComparer comparer ) : this() { if(comparer != null) { m_comparer = comparer; } } // Constructs a new sorted list with a given IComparer // implementation and a given initial capacity. The sorted list is // initially empty, but will have room for the given number of elements // before any reallocations are required. The elements of the sorted list // are ordered according to the given IComparer implementation. If // comparer is null, the elements are compared to each other using // the IComparable interface, which in that case must be implemented // by the keys of all entries added to the sorted list. // public SortedList( IComparer comparer, int capacity ) : this( comparer ) { this.Capacity = capacity; } // Constructs a new sorted list containing a copy of the entries in the // given dictionary. The elements of the sorted list are ordered according // to the IComparable interface, which must be implemented by the // keys of all entries in the the given dictionary as well as keys // subsequently added to the sorted list. // public SortedList( IDictionary d ) : this( d, null ) { } // Constructs a new sorted list containing a copy of the entries in the // given dictionary. The elements of the sorted list are ordered according // to the given IComparer implementation. If comparer is // null, the elements are compared to each other using the // IComparable interface, which in that case must be implemented // by the keys of all entries in the the given dictionary as well as keys // subsequently added to the sorted list. // public SortedList( IDictionary d, IComparer comparer ) : this( comparer, (d != null ? d.Count : 0) ) { if(d == null) { #if EXCEPTION_STRINGS throw new ArgumentNullException( "d", Environment.GetResourceString( "ArgumentNull_Dictionary" ) ); #else throw new ArgumentNullException(); #endif } d.Keys .CopyTo( m_keys , 0 ); d.Values.CopyTo( m_values, 0 ); Array.Sort( m_keys, m_values, comparer ); m_size = d.Count; } // Adds an entry with the given key and value to this sorted list. An // ArgumentException is thrown if the key is already present in the sorted list. // public virtual void Add( Object key, Object value ) { if(key == null) { #if EXCEPTION_STRINGS throw new ArgumentNullException( "key", Environment.GetResourceString( "ArgumentNull_Key" ) ); #else throw new ArgumentNullException(); #endif } int i = Array.BinarySearch( m_keys, 0, m_size, key, m_comparer ); if(i >= 0) { #if EXCEPTION_STRINGS throw new ArgumentException( Environment.GetResourceString( "Argument_AddingDuplicate__", GetKey( i ), key ) ); #else throw new ArgumentException(); #endif } Insert( ~i, key, value ); } // Returns the capacity of this sorted list. The capacity of a sorted list // represents the allocated length of the internal arrays used to store the // keys and values of the list, and thus also indicates the maximum number // of entries the list can contain before a reallocation of the internal // arrays is required. // public virtual int Capacity { get { return m_keys.Length; } set { if(value != m_keys.Length) { if(value < m_size) { #if EXCEPTION_STRINGS throw new ArgumentOutOfRangeException( "value", Environment.GetResourceString( "ArgumentOutOfRange_SmallCapacity" ) ); #else throw new ArgumentOutOfRangeException(); #endif } if(value > 0) { Object[] newKeys = new Object[value]; Object[] newValues = new Object[value]; if(m_size > 0) { Array.Copy( m_keys , 0, newKeys , 0, m_size ); Array.Copy( m_values, 0, newValues, 0, m_size ); } m_keys = newKeys; m_values = newValues; } else { // size can only be zero here. BCLDebug.Assert( m_size == 0, "Size is not zero" ); m_keys = emptyArray; m_values = emptyArray; } } } } // Returns the number of entries in this sorted list. // public virtual int Count { get { return m_size; } } // Returns a collection representing the keys of this sorted list. This // method returns the same object as GetKeyList, but typed as an // ICollection instead of an IList. // public virtual ICollection Keys { get { return GetKeyList(); } } // Returns a collection representing the values of this sorted list. This // method returns the same object as GetValueList, but typed as an // ICollection instead of an IList. // public virtual ICollection Values { get { return GetValueList(); } } // Is this SortedList read-only? public virtual bool IsReadOnly { get { return false; } } public virtual bool IsFixedSize { get { return false; } } // Is this SortedList synchronized (thread-safe)? public virtual bool IsSynchronized { get { return false; } } // Synchronization root for this object. public virtual Object SyncRoot { get { if(m_syncRoot == null) { System.Threading.Interlocked.CompareExchange( ref m_syncRoot, new Object(), null ); } return m_syncRoot; } } // Removes all entries from this sorted list. public virtual void Clear() { // clear does not change the capacity m_version++; Array.Clear( m_keys , 0, m_size ); // Don't need to doc this but we clear the elements so that the gc can reclaim the references. Array.Clear( m_values, 0, m_size ); // Don't need to doc this but we clear the elements so that the gc can reclaim the references. m_size = 0; } // Makes a virtually identical copy of this SortedList. This is a shallow // copy. IE, the Objects in the SortedList are not cloned - we copy the // references to those objects. public virtual Object Clone() { SortedList sl = new SortedList( m_size ); Array.Copy( m_keys , 0, sl.m_keys , 0, m_size ); Array.Copy( m_values, 0, sl.m_values, 0, m_size ); sl.m_size = m_size; sl.m_version = m_version; sl.m_comparer = m_comparer; // Don't copy keyList nor valueList. return sl; } // Checks if this sorted list contains an entry with the given key. // public virtual bool Contains( Object key ) { return IndexOfKey( key ) >= 0; } // Checks if this sorted list contains an entry with the given key. // public virtual bool ContainsKey( Object key ) { // Yes, this is a SPEC'ed duplicate of Contains(). return IndexOfKey( key ) >= 0; } // Checks if this sorted list contains an entry with the given value. The // values of the entries of the sorted list are compared to the given value // using the Object.Equals method. This method performs a linear // search and is substantially slower than the Contains // method. // public virtual bool ContainsValue( Object value ) { return IndexOfValue( value ) >= 0; } // Copies the values in this SortedList to an array. public virtual void CopyTo( Array array, int arrayIndex ) { if(array == null) { #if EXCEPTION_STRINGS throw new ArgumentNullException( "array", Environment.GetResourceString( "ArgumentNull_Array" ) ); #else throw new ArgumentNullException(); #endif } if(array.Rank != 1) { #if EXCEPTION_STRINGS throw new ArgumentException( Environment.GetResourceString( "Arg_RankMultiDimNotSupported" ) ); #else throw new ArgumentException(); #endif } if(arrayIndex < 0) { #if EXCEPTION_STRINGS throw new ArgumentOutOfRangeException( "arrayIndex", Environment.GetResourceString( "ArgumentOutOfRange_NeedNonNegNum" ) ); #else throw new ArgumentOutOfRangeException(); #endif } if(array.Length - arrayIndex < Count) { #if EXCEPTION_STRINGS throw new ArgumentException( Environment.GetResourceString( "Arg_ArrayPlusOffTooSmall" ) ); #else throw new ArgumentException(); #endif } for(int i = 0; i < Count; i++) { DictionaryEntry entry = new DictionaryEntry( m_keys[i], m_values[i] ); array.SetValue( entry, i + arrayIndex ); } } // Copies the values in this SortedList to an KeyValuePairs array. // KeyValuePairs is different from Dictionary Entry in that it has special // debugger attributes on its fields. internal virtual KeyValuePairs[] ToKeyValuePairsArray() { KeyValuePairs[] array = new KeyValuePairs[Count]; for(int i = 0; i < Count; i++) { array[i] = new KeyValuePairs( m_keys[i], m_values[i] ); } return array; } // Ensures that the capacity of this sorted list is at least the given // minimum value. If the currect capacity of the list is less than // min, the capacity is increased to twice the current capacity or // to min, whichever is larger. private void EnsureCapacity( int min ) { int newCapacity = m_keys.Length == 0 ? cDefaultCapacity : m_keys.Length * 2; if(newCapacity < min) { newCapacity = min; } this.Capacity = newCapacity; } // Returns the value of the entry at the given index. // public virtual Object GetByIndex( int index ) { if(index < 0 || index >= m_size) { #if EXCEPTION_STRINGS throw new ArgumentOutOfRangeException( "index", Environment.GetResourceString( "ArgumentOutOfRange_Index" ) ); #else throw new ArgumentOutOfRangeException(); #endif } return m_values[index]; } // Returns an IEnumerator for this sorted list. If modifications // made to the sorted list while an enumeration is in progress, // the MoveNext and Remove methods // of the enumerator will throw an exception. // IEnumerator IEnumerable.GetEnumerator() { return new SortedListEnumerator( this, 0, m_size, SortedListEnumerator.DictEntry ); } // Returns an IDictionaryEnumerator for this sorted list. If modifications // made to the sorted list while an enumeration is in progress, // the MoveNext and Remove methods // of the enumerator will throw an exception. // public virtual IDictionaryEnumerator GetEnumerator() { return new SortedListEnumerator( this, 0, m_size, SortedListEnumerator.DictEntry ); } // Returns the key of the entry at the given index. // public virtual Object GetKey( int index ) { if(index < 0 || index >= m_size) { #if EXCEPTION_STRINGS throw new ArgumentOutOfRangeException( "index", Environment.GetResourceString( "ArgumentOutOfRange_Index" ) ); #else throw new ArgumentOutOfRangeException(); #endif } return m_keys[index]; } // Returns an IList representing the keys of this sorted list. The // returned list is an alias for the keys of this sorted list, so // modifications made to the returned list are directly reflected in the // underlying sorted list, and vice versa. The elements of the returned // list are ordered in the same way as the elements of the sorted list. The // returned list does not support adding, inserting, or modifying elements // (the Add, AddRange, Insert, InsertRange, // Reverse, Set, SetRange, and Sort methods // throw exceptions), but it does allow removal of elements (through the // Remove and RemoveRange methods or through an enumerator). // Null is an invalid key value. // public virtual IList GetKeyList() { if(m_keyList == null) { m_keyList = new KeyList( this ); } return m_keyList; } // Returns an IList representing the values of this sorted list. The // returned list is an alias for the values of this sorted list, so // modifications made to the returned list are directly reflected in the // underlying sorted list, and vice versa. The elements of the returned // list are ordered in the same way as the elements of the sorted list. The // returned list does not support adding or inserting elements (the // Add, AddRange, Insert and InsertRange // methods throw exceptions), but it does allow modification and removal of // elements (through the Remove, RemoveRange, Set and // SetRange methods or through an enumerator). // public virtual IList GetValueList() { if(m_valueList == null) { m_valueList = new ValueList( this ); } return m_valueList; } // Returns the value associated with the given key. If an entry with the // given key is not found, the returned value is null. // public virtual Object this[Object key] { get { int i = IndexOfKey( key ); if(i >= 0) { return m_values[i]; } return null; } set { if(key == null) { #if EXCEPTION_STRINGS throw new ArgumentNullException( "key", Environment.GetResourceString( "ArgumentNull_Key" ) ); #else throw new ArgumentNullException(); #endif } int i = Array.BinarySearch( m_keys, 0, m_size, key, m_comparer ); if(i >= 0) { m_values[i] = value; m_version++; return; } Insert( ~i, key, value ); } } // Returns the index of the entry with a given key in this sorted list. The // key is located through a binary search, and thus the average execution // time of this method is proportional to Log2(size), where // size is the size of this sorted list. The returned value is -1 if // the given key does not occur in this sorted list. Null is an invalid // key value. // public virtual int IndexOfKey( Object key ) { if(key == null) { #if EXCEPTION_STRINGS throw new ArgumentNullException( "key", Environment.GetResourceString( "ArgumentNull_Key" ) ); #else throw new ArgumentNullException(); #endif } int ret = Array.BinarySearch( m_keys, 0, m_size, key, m_comparer ); return ret >= 0 ? ret : -1; } // Returns the index of the first occurrence of an entry with a given value // in this sorted list. The entry is located through a linear search, and // thus the average execution time of this method is proportional to the // size of this sorted list. The elements of the list are compared to the // given value using the Object.Equals method. // public virtual int IndexOfValue( Object value ) { return Array.IndexOf( m_values, value, 0, m_size ); } // Inserts an entry with a given key and value at a given index. private void Insert( int index, Object key, Object value ) { if(m_size == m_keys.Length) { EnsureCapacity( m_size + 1 ); } if(index < m_size) { Array.Copy( m_keys , index, m_keys , index + 1, m_size - index ); Array.Copy( m_values, index, m_values, index + 1, m_size - index ); } m_keys [index] = key; m_values[index] = value; m_size++; m_version++; } // Removes the entry at the given index. The size of the sorted list is // decreased by one. // public virtual void RemoveAt( int index ) { if(index < 0 || index >= m_size) { #if EXCEPTION_STRINGS throw new ArgumentOutOfRangeException( "index", Environment.GetResourceString( "ArgumentOutOfRange_Index" ) ); #else throw new ArgumentOutOfRangeException(); #endif } m_size--; if(index < m_size) { Array.Copy( m_keys , index + 1, m_keys , index, m_size - index ); Array.Copy( m_values, index + 1, m_values, index, m_size - index ); } m_keys [m_size] = null; m_values[m_size] = null; m_version++; } // Removes an entry from this sorted list. If an entry with the specified // key exists in the sorted list, it is removed. An ArgumentException is // thrown if the key is null. // public virtual void Remove( Object key ) { int i = IndexOfKey( key ); if(i >= 0) { RemoveAt( i ); } } // Sets the value at an index to a given value. The previous value of // the given entry is overwritten. // public virtual void SetByIndex( int index, Object value ) { if(index < 0 || index >= m_size) { #if EXCEPTION_STRINGS throw new ArgumentOutOfRangeException( "index", Environment.GetResourceString( "ArgumentOutOfRange_Index" ) ); #else throw new ArgumentOutOfRangeException(); #endif } m_values[index] = value; m_version++; } //// // Returns a thread-safe SortedList. //// // //// [HostProtection( Synchronization = true )] //// public static SortedList Synchronized( SortedList list ) //// { //// if(list == null) //// { //// throw new ArgumentNullException( "list" ); //// } //// //// return new SyncSortedList( list ); //// } // Sets the capacity of this sorted list to the size of the sorted list. // This method can be used to minimize a sorted list's memory overhead once // it is known that no new elements will be added to the sorted list. To // completely clear a sorted list and release all memory referenced by the // sorted list, execute the following statements: // // sortedList.Clear(); // sortedList.TrimToSize(); // public virtual void TrimToSize() { Capacity = m_size; } //// [Serializable] //// private class SyncSortedList : SortedList //// { //// private SortedList m_list; //// private Object m_root; //// //// internal SyncSortedList( SortedList list ) //// { //// m_list = list; //// m_root = list.SyncRoot; //// } //// //// public override int Count //// { //// get //// { //// lock(m_root) //// { //// return m_list.Count; //// } //// } //// } //// //// public override Object SyncRoot //// { //// get //// { //// return m_root; //// } //// } //// //// public override bool IsReadOnly //// { //// get //// { //// return m_list.IsReadOnly; //// } //// } //// //// public override bool IsFixedSize //// { //// get //// { //// return m_list.IsFixedSize; //// } //// } //// //// //// public override bool IsSynchronized //// { //// get //// { //// return true; //// } //// } //// //// public override Object this[Object key] //// { //// get //// { //// lock(m_root) //// { //// return m_list[key]; //// } //// } //// //// set //// { //// lock(m_root) //// { //// m_list[key] = value; //// } //// } //// } //// //// public override void Add( Object key, Object value ) //// { //// lock(m_root) //// { //// m_list.Add( key, value ); //// } //// } //// //// public override int Capacity //// { //// get //// { //// lock(m_root) //// { //// return m_list.Capacity; //// } //// } //// } //// //// public override void Clear() //// { //// lock(m_root) //// { //// m_list.Clear(); //// } //// } //// //// public override Object Clone() //// { //// lock(m_root) //// { //// return m_list.Clone(); //// } //// } //// //// public override bool Contains( Object key ) //// { //// lock(m_root) //// { //// return m_list.Contains( key ); //// } //// } //// //// public override bool ContainsKey( Object key ) //// { //// lock(m_root) //// { //// return m_list.ContainsKey( key ); //// } //// } //// //// public override bool ContainsValue( Object key ) //// { //// lock(m_root) //// { //// return m_list.ContainsValue( key ); //// } //// } //// //// public override void CopyTo( Array array, int index ) //// { //// lock(m_root) //// { //// m_list.CopyTo( array, index ); //// } //// } //// //// public override Object GetByIndex( int index ) //// { //// lock(m_root) //// { //// return m_list.GetByIndex( index ); //// } //// } //// //// public override IDictionaryEnumerator GetEnumerator() //// { //// lock(m_root) //// { //// return m_list.GetEnumerator(); //// } //// } //// //// public override Object GetKey( int index ) //// { //// lock(m_root) //// { //// return m_list.GetKey( index ); //// } //// } //// //// public override IList GetKeyList() //// { //// lock(m_root) //// { //// return m_list.GetKeyList(); //// } //// } //// //// public override IList GetValueList() //// { //// lock(m_root) //// { //// return m_list.GetValueList(); //// } //// } //// //// public override int IndexOfKey( Object key ) //// { //// lock(m_root) //// { //// return m_list.IndexOfKey( key ); //// } //// } //// //// public override int IndexOfValue( Object value ) //// { //// lock(m_root) //// { //// return m_list.IndexOfValue( value ); //// } //// } //// //// public override void RemoveAt( int index ) //// { //// lock(m_root) //// { //// m_list.RemoveAt( index ); //// } //// } //// //// public override void Remove( Object key ) //// { //// lock(m_root) //// { //// m_list.Remove( key ); //// } //// } //// //// public override void SetByIndex( int index, Object value ) //// { //// lock(m_root) //// { //// m_list.SetByIndex( index, value ); //// } //// } //// //// internal override KeyValuePairs[] ToKeyValuePairsArray() //// { //// return m_list.ToKeyValuePairsArray(); //// } //// //// public override void TrimToSize() //// { //// lock(m_root) //// { //// m_list.TrimToSize(); //// } //// } //// } [Serializable] private class SortedListEnumerator : IDictionaryEnumerator, ICloneable { internal const int Keys = 1; internal const int Values = 2; internal const int DictEntry = 3; private SortedList m_sortedList; private Object m_key; private Object m_value; private int m_index; private int m_startIndex; // Store for Reset. private int m_endIndex; private int m_version; private bool m_current; // Is the current element valid? private int m_getObjectRetType; // What should GetObject return? internal SortedListEnumerator( SortedList sortedList, int index, int count, int getObjRetType ) { m_sortedList = sortedList; m_index = index; m_startIndex = index; m_endIndex = index + count; m_version = sortedList.m_version; m_current = false; m_getObjectRetType = getObjRetType; } public Object Clone() { return MemberwiseClone(); } public virtual Object Key { get { if(m_version != m_sortedList.m_version) { #if EXCEPTION_STRINGS throw new InvalidOperationException( Environment.GetResourceString( "InvalidOperation_EnumFailedVersion" ) ); #else throw new InvalidOperationException(); #endif } if(m_current == false) { #if EXCEPTION_STRINGS throw new InvalidOperationException( Environment.GetResourceString( "InvalidOperation_EnumOpCantHappen" ) ); #else throw new InvalidOperationException(); #endif } return m_key; } } public virtual bool MoveNext() { if(m_version != m_sortedList.m_version) { #if EXCEPTION_STRINGS throw new InvalidOperationException( Environment.GetResourceString( "InvalidOperation_EnumFailedVersion" ) ); #else throw new InvalidOperationException(); #endif } if(m_index < m_endIndex) { m_key = m_sortedList.m_keys [m_index]; m_value = m_sortedList.m_values[m_index]; m_index++; m_current = true; return true; } m_key = null; m_value = null; m_current = false; return false; } public virtual DictionaryEntry Entry { get { if(m_version != m_sortedList.m_version) { #if EXCEPTION_STRINGS throw new InvalidOperationException( Environment.GetResourceString( "InvalidOperation_EnumFailedVersion" ) ); #else throw new InvalidOperationException(); #endif } if(m_current == false) { #if EXCEPTION_STRINGS throw new InvalidOperationException( Environment.GetResourceString( "InvalidOperation_EnumOpCantHappen" ) ); #else throw new InvalidOperationException(); #endif } return new DictionaryEntry( m_key, m_value ); } } public virtual Object Current { get { if(m_current == false) { #if EXCEPTION_STRINGS throw new InvalidOperationException( Environment.GetResourceString( "InvalidOperation_EnumOpCantHappen" ) ); #else throw new InvalidOperationException(); #endif } if(m_getObjectRetType == Keys) { return m_key; } else if(m_getObjectRetType == Values) { return m_value; } else { return new DictionaryEntry( m_key, m_value ); } } } public virtual Object Value { get { if(m_version != m_sortedList.m_version) { #if EXCEPTION_STRINGS throw new InvalidOperationException( Environment.GetResourceString( "InvalidOperation_EnumFailedVersion" ) ); #else throw new InvalidOperationException(); #endif } if(m_current == false) { #if EXCEPTION_STRINGS throw new InvalidOperationException( Environment.GetResourceString( "InvalidOperation_EnumOpCantHappen" ) ); #else throw new InvalidOperationException(); #endif } return m_value; } } public virtual void Reset() { if(m_version != m_sortedList.m_version) { #if EXCEPTION_STRINGS throw new InvalidOperationException( Environment.GetResourceString( "InvalidOperation_EnumFailedVersion" ) ); #else throw new InvalidOperationException(); #endif } m_index = m_startIndex; m_current = false; m_key = null; m_value = null; } } [Serializable] private class KeyList : IList { private SortedList m_sortedList; internal KeyList( SortedList sortedList ) { this.m_sortedList = sortedList; } public virtual int Count { get { return m_sortedList.m_size; } } public virtual bool IsReadOnly { get { return true; } } public virtual bool IsFixedSize { get { return true; } } public virtual bool IsSynchronized { get { return m_sortedList.IsSynchronized; } } public virtual Object SyncRoot { get { return m_sortedList.SyncRoot; } } public virtual int Add( Object key ) { #if EXCEPTION_STRINGS throw new NotSupportedException( Environment.GetResourceString( "NotSupported_SortedListNestedWrite" ) ); #else throw new NotSupportedException(); #endif } public virtual void Clear() { #if EXCEPTION_STRINGS throw new NotSupportedException( Environment.GetResourceString( "NotSupported_SortedListNestedWrite" ) ); #else throw new NotSupportedException(); #endif } public virtual bool Contains( Object key ) { return m_sortedList.Contains( key ); } public virtual void CopyTo( Array array, int arrayIndex ) { if(array != null && array.Rank != 1) { #if EXCEPTION_STRINGS throw new ArgumentException( Environment.GetResourceString( "Arg_RankMultiDimNotSupported" ) ); #else throw new ArgumentException(); #endif } // defer error checking to Array.Copy Array.Copy( m_sortedList.m_keys, 0, array, arrayIndex, m_sortedList.Count ); } public virtual void Insert( int index, Object value ) { #if EXCEPTION_STRINGS throw new NotSupportedException( Environment.GetResourceString( "NotSupported_SortedListNestedWrite" ) ); #else throw new NotSupportedException(); #endif } public virtual Object this[int index] { get { return m_sortedList.GetKey( index ); } set { #if EXCEPTION_STRINGS throw new NotSupportedException( Environment.GetResourceString( "NotSupported_KeyCollectionSet" ) ); #else throw new NotSupportedException(); #endif } } public virtual IEnumerator GetEnumerator() { return new SortedListEnumerator( m_sortedList, 0, m_sortedList.Count, SortedListEnumerator.Keys ); } public virtual int IndexOf( Object key ) { if(key == null) { #if EXCEPTION_STRINGS throw new ArgumentNullException( "key", Environment.GetResourceString( "ArgumentNull_Key" ) ); #else throw new ArgumentNullException(); #endif } int i = Array.BinarySearch( m_sortedList.m_keys, 0, m_sortedList.Count, key, m_sortedList.m_comparer ); if(i >= 0) return i; return -1; } public virtual void Remove( Object key ) { #if EXCEPTION_STRINGS throw new NotSupportedException( Environment.GetResourceString( "NotSupported_SortedListNestedWrite" ) ); #else throw new NotSupportedException(); #endif } public virtual void RemoveAt( int index ) { #if EXCEPTION_STRINGS throw new NotSupportedException( Environment.GetResourceString( "NotSupported_SortedListNestedWrite" ) ); #else throw new NotSupportedException(); #endif } } [Serializable] private class ValueList : IList { private SortedList m_sortedList; internal ValueList( SortedList sortedList ) { m_sortedList = sortedList; } public virtual int Count { get { return m_sortedList.m_size; } } public virtual bool IsReadOnly { get { return true; } } public virtual bool IsFixedSize { get { return true; } } public virtual bool IsSynchronized { get { return m_sortedList.IsSynchronized; } } public virtual Object SyncRoot { get { return m_sortedList.SyncRoot; } } public virtual int Add( Object key ) { #if EXCEPTION_STRINGS throw new NotSupportedException( Environment.GetResourceString( "NotSupported_SortedListNestedWrite" ) ); #else throw new NotSupportedException(); #endif } public virtual void Clear() { #if EXCEPTION_STRINGS throw new NotSupportedException( Environment.GetResourceString( "NotSupported_SortedListNestedWrite" ) ); #else throw new NotSupportedException(); #endif } public virtual bool Contains( Object value ) { return m_sortedList.ContainsValue( value ); } public virtual void CopyTo( Array array, int arrayIndex ) { if(array != null && array.Rank != 1) { #if EXCEPTION_STRINGS throw new ArgumentException( Environment.GetResourceString( "Arg_RankMultiDimNotSupported" ) ); #else throw new ArgumentException(); #endif } // defer error checking to Array.Copy Array.Copy( m_sortedList.m_values, 0, array, arrayIndex, m_sortedList.Count ); } public virtual void Insert( int index, Object value ) { #if EXCEPTION_STRINGS throw new NotSupportedException( Environment.GetResourceString( "NotSupported_SortedListNestedWrite" ) ); #else throw new NotSupportedException(); #endif } public virtual Object this[int index] { get { return m_sortedList.GetByIndex( index ); } set { #if EXCEPTION_STRINGS throw new NotSupportedException( Environment.GetResourceString( "NotSupported_SortedListNestedWrite" ) ); #else throw new NotSupportedException(); #endif } } public virtual IEnumerator GetEnumerator() { return new SortedListEnumerator( m_sortedList, 0, m_sortedList.Count, SortedListEnumerator.Values ); } public virtual int IndexOf( Object value ) { return Array.IndexOf( m_sortedList.m_values, value, 0, m_sortedList.Count ); } public virtual void Remove( Object value ) { #if EXCEPTION_STRINGS throw new NotSupportedException( Environment.GetResourceString( "NotSupported_SortedListNestedWrite" ) ); #else throw new NotSupportedException(); #endif } public virtual void RemoveAt( int index ) { #if EXCEPTION_STRINGS throw new NotSupportedException( Environment.GetResourceString( "NotSupported_SortedListNestedWrite" ) ); #else throw new NotSupportedException(); #endif } } //// // internal debug view class for sorted list //// internal class SortedListDebugView //// { //// private SortedList sortedList; //// //// public SortedListDebugView( SortedList sortedList ) //// { //// if(sortedList == null) //// { //// throw new ArgumentNullException( "sortedList" ); //// } //// //// this.sortedList = sortedList; //// } //// //// [DebuggerBrowsable( DebuggerBrowsableState.RootHidden )] //// public KeyValuePairs[] Items //// { //// get //// { //// return sortedList.ToKeyValuePairsArray(); //// } //// } //// } } } ================================================ FILE: Zelig/Zelig/RunTime/Framework/mscorlib/System/Collections/Stack.cs ================================================ // ==++== // // Copyright (c) Microsoft Corporation. All rights reserved. // // ==--== /*============================================================================= ** ** Class: Stack ** ** Purpose: An array implementation of a stack. ** ** =============================================================================*/ namespace System.Collections { using System; ////using System.Security.Permissions; using System.Diagnostics; // A simple stack of objects. Internally it is implemented as an array, // so Push can be O(n). Pop is O(1). ////[DebuggerTypeProxy( typeof( System.Collections.Stack.StackDebugView ) )] ////[DebuggerDisplay( "Count = {Count}" )] [Serializable] public class Stack : ICollection, ICloneable { private const int cDefaultCapacity = 10; private Object[] m_array; // Storage for stack elements private int m_size; // Number of items in the stack. private int m_version; // Used to keep enumerator in sync w/ collection. [NonSerialized] private Object m_syncRoot; public Stack() { m_array = new Object[cDefaultCapacity]; m_size = 0; m_version = 0; } // Create a stack with a specific initial capacity. The initial capacity // must be a non-negative number. public Stack( int initialCapacity ) { if(initialCapacity < 0) { #if EXCEPTION_STRINGS throw new ArgumentOutOfRangeException( "initialCapacity", Environment.GetResourceString( "ArgumentOutOfRange_NeedNonNegNum" ) ); #else throw new ArgumentOutOfRangeException(); #endif } if(initialCapacity < cDefaultCapacity) { initialCapacity = cDefaultCapacity; // Simplify doubling logic in Push. } m_array = new Object[initialCapacity]; m_size = 0; m_version = 0; } // Fills a Stack with the contents of a particular collection. The items are // pushed onto the stack in the same order they are read by the enumerator. // public Stack( ICollection col ) : this( (col == null ? 32 : col.Count) ) { if(col == null) { #if EXCEPTION_STRINGS throw new ArgumentNullException( "col" ); #else throw new ArgumentNullException(); #endif } IEnumerator en = col.GetEnumerator(); while(en.MoveNext()) { Push( en.Current ); } } public virtual int Count { get { return m_size; } } public virtual bool IsSynchronized { get { return false; } } public virtual Object SyncRoot { get { if(m_syncRoot == null) { System.Threading.Interlocked.CompareExchange( ref m_syncRoot, new Object(), null ); } return m_syncRoot; } } // Removes all Objects from the Stack. public virtual void Clear() { Array.Clear( m_array, 0, m_size ); // Don't need to doc this but we clear the elements so that the gc can reclaim the references. m_size = 0; m_version++; } public virtual Object Clone() { Stack s = new Stack( m_size ); s.m_size = m_size; Array.Copy( m_array, 0, s.m_array, 0, m_size ); s.m_version = m_version; return s; } public virtual bool Contains( Object obj ) { int count = m_size; while(count-- > 0) { object obj2 = m_array[count]; if(obj == null) { if(obj2 == null) { return true; } } else if(obj2 != null && obj2.Equals( obj )) { return true; } } return false; } // Copies the stack into an array. public virtual void CopyTo( Array array, int index ) { if(array == null) { #if EXCEPTION_STRINGS throw new ArgumentNullException( "array" ); #else throw new ArgumentNullException(); #endif } if(array.Rank != 1) { #if EXCEPTION_STRINGS throw new ArgumentException( Environment.GetResourceString( "Arg_RankMultiDimNotSupported" ) ); #else throw new ArgumentException(); #endif } if(index < 0) { #if EXCEPTION_STRINGS throw new ArgumentOutOfRangeException( "index", Environment.GetResourceString( "ArgumentOutOfRange_NeedNonNegNum" ) ); #else throw new ArgumentOutOfRangeException(); #endif } if(array.Length - index < m_size) { #if EXCEPTION_STRINGS throw new ArgumentException( Environment.GetResourceString( "Argument_InvalidOffLen" ) ); #else throw new ArgumentException(); #endif } int i = 0; if(array is Object[]) { Object[] objArray = (Object[])array; while(i < m_size) { objArray[i + index] = m_array[m_size - i - 1]; i++; } } else { while(i < m_size) { array.SetValue( m_array[m_size - i - 1], i + index ); i++; } } } // Returns an IEnumerator for this Stack. public virtual IEnumerator GetEnumerator() { return new StackEnumerator( this ); } // Returns the top object on the stack without removing it. If the stack // is empty, Peek throws an InvalidOperationException. public virtual Object Peek() { if(m_size == 0) { #if EXCEPTION_STRINGS throw new InvalidOperationException( Environment.GetResourceString( "InvalidOperation_EmptyStack" ) ); #else throw new InvalidOperationException(); #endif } return m_array[m_size - 1]; } // Pops an item from the top of the stack. If the stack is empty, Pop // throws an InvalidOperationException. public virtual Object Pop() { if(m_size == 0) { #if EXCEPTION_STRINGS throw new InvalidOperationException( Environment.GetResourceString( "InvalidOperation_EmptyStack" ) ); #else throw new InvalidOperationException(); #endif } m_version++; Object obj = m_array[--m_size]; m_array[m_size] = null; // Free memory quicker. return obj; } // Pushes an item to the top of the stack. // public virtual void Push( Object obj ) { if(m_size == m_array.Length) { Object[] newArray = new Object[2 * m_array.Length]; Array.Copy( m_array, 0, newArray, 0, m_size ); m_array = newArray; } m_array[m_size++] = obj; m_version++; } //// // Returns a synchronized Stack. //// // //// [HostProtection( Synchronization = true )] //// public static Stack Synchronized( Stack stack ) //// { //// if(stack == null) //// { //// throw new ArgumentNullException( "stack" ); //// } //// //// return new SyncStack( stack ); //// } // Copies the Stack to an array, in the same order Pop would return the items. public virtual Object[] ToArray() { Object[] objArray = new Object[m_size]; int i = 0; while(i < m_size) { objArray[i] = m_array[m_size - i - 1]; i++; } return objArray; } //// [Serializable] //// private class SyncStack : Stack //// { //// private Stack m_s; //// private Object m_root; //// //// internal SyncStack( Stack stack ) //// { //// m_s = stack; //// m_root = stack.SyncRoot; //// } //// //// public override bool IsSynchronized //// { //// get //// { //// return true; //// } //// } //// //// public override Object SyncRoot //// { //// get //// { //// return m_root; //// } //// } //// //// public override int Count //// { //// get //// { //// lock(m_root) //// { //// return m_s.Count; //// } //// } //// } //// //// public override bool Contains( Object obj ) //// { //// lock(m_root) //// { //// return m_s.Contains( obj ); //// } //// } //// //// public override Object Clone() //// { //// lock(m_root) //// { //// return new SyncStack( (Stack)m_s.Clone() ); //// } //// } //// //// public override void Clear() //// { //// lock(m_root) //// { //// m_s.Clear(); //// } //// } //// //// public override void CopyTo( Array array, int arrayIndex ) //// { //// lock(m_root) //// { //// m_s.CopyTo( array, arrayIndex ); //// } //// } //// //// public override void Push( Object value ) //// { //// lock(m_root) //// { //// m_s.Push( value ); //// } //// } //// //// public override Object Pop() //// { //// lock(m_root) //// { //// return m_s.Pop(); //// } //// } //// //// public override IEnumerator GetEnumerator() //// { //// lock(m_root) //// { //// return m_s.GetEnumerator(); //// } //// } //// //// public override Object Peek() //// { //// lock(m_root) //// { //// return m_s.Peek(); //// } //// } //// //// public override Object[] ToArray() //// { //// lock(m_root) //// { //// return m_s.ToArray(); //// } //// } //// } [Serializable] private class StackEnumerator : IEnumerator, ICloneable { private Stack m_stack; private int m_index; private int m_version; private Object m_currentElement; internal StackEnumerator( Stack stack ) { m_stack = stack; m_version = stack.m_version; m_index = -2; m_currentElement = null; } public Object Clone() { return MemberwiseClone(); } public virtual bool MoveNext() { bool retval; if(m_version != m_stack.m_version) { #if EXCEPTION_STRINGS throw new InvalidOperationException( Environment.GetResourceString( "InvalidOperation_EnumFailedVersion" ) ); #else throw new InvalidOperationException(); #endif } if(m_index == -2) { // First call to enumerator. m_index = m_stack.m_size - 1; retval = (m_index >= 0); if(retval) { m_currentElement = m_stack.m_array[m_index]; } return retval; } if(m_index == -1) { // End of enumeration. return false; } retval = (--m_index >= 0); if(retval) { m_currentElement = m_stack.m_array[m_index]; } else { m_currentElement = null; } return retval; } public virtual Object Current { get { if(m_index == -2) { #if EXCEPTION_STRINGS throw new InvalidOperationException( Environment.GetResourceString( "InvalidOperation_EnumNotStarted" ) ); #else throw new InvalidOperationException(); #endif } if(m_index == -1) { #if EXCEPTION_STRINGS throw new InvalidOperationException( Environment.GetResourceString( "InvalidOperation_EnumEnded" ) ); #else throw new InvalidOperationException(); #endif } return m_currentElement; } } public virtual void Reset() { if(m_version != m_stack.m_version) { #if EXCEPTION_STRINGS throw new InvalidOperationException( Environment.GetResourceString( "InvalidOperation_EnumFailedVersion" ) ); #else throw new InvalidOperationException(); #endif } m_index = -2; m_currentElement = null; } } //// internal class StackDebugView //// { //// private Stack stack; //// //// public StackDebugView( Stack stack ) //// { //// if(stack == null) //// { //// throw new ArgumentNullException( "stack" ); //// } //// //// this.stack = stack; //// } //// //// [DebuggerBrowsable( DebuggerBrowsableState.RootHidden )] //// public Object[] Items //// { //// get //// { //// return stack.ToArray(); //// } //// } //// } } } ================================================ FILE: Zelig/Zelig/RunTime/Framework/mscorlib/System/Configuration/Assemblies/AssemblyHashAlgorithm.cs ================================================ // ==++== // // Copyright (c) Microsoft Corporation. All rights reserved. // // ==--== /*============================================================ ** ** File: AssemblyHashAlgorithm ** ** ** Purpose: ** ** ===========================================================*/ namespace System.Configuration.Assemblies { using System; [Serializable] public enum AssemblyHashAlgorithm { None = 0x0000, MD5 = 0x8003, SHA1 = 0x8004, } } ================================================ FILE: Zelig/Zelig/RunTime/Framework/mscorlib/System/Configuration/Assemblies/AssemblyVersionCompatibility.cs ================================================ // ==++== // // Copyright (c) Microsoft Corporation. All rights reserved. // // ==--== /*============================================================ ** ** File: AssemblyVersionCompatibility ** ** Author: Suzanne Cook ** ** Purpose: defining the different flavor's assembly version compatibility ** ** Date: June 4, 1999 ** ===========================================================*/ namespace System.Configuration.Assemblies { using System; [Serializable] public enum AssemblyVersionCompatibility { SameMachine = 1, SameProcess = 2, SameDomain = 3, } } ================================================ FILE: Zelig/Zelig/RunTime/Framework/mscorlib/System/Console.cs ================================================ // ==++== // // Copyright (c) Microsoft Corporation. All rights reserved. // // ==--== /*============================================================================= ** ** Class: Console ** ** ** Purpose: This class provides access to the standard input, standard output ** and standard error streams. ** ** =============================================================================*/ namespace System { using System.Security.Permissions; ////using Microsoft.Win32; using System.Runtime.CompilerServices; ////using Microsoft.Win32.SafeHandles; ////using System.Runtime.Versioning; // Provides static fields for console input & output. Use // Console.In for input from the standard input stream (stdin), // Console.Out for output to stdout, and Console.Error // for output to stderr. If any of those console streams are // redirected from the command line, these streams will be redirected. // A program can also redirect its own output or input with the // SetIn, SetOut, and SetError methods. // // The distinction between Console.Out & Console.Error is useful // for programs that redirect output to a file or a pipe. Note that // stdout & stderr can be output to different files at the same // time from the DOS command line: // // someProgram 1> out 2> err // //Contains only static data. Serializable attribute not required. public static class Console { //// private const int _DefaultConsoleBufferSize = 256; //// private const short AltVKCode = 0x12; //// //// private static TextReader _in; //// private static TextWriter _out; //// private static TextWriter _error; //// //// private static ConsoleCancelEventHandler _cancelCallbacks; //// private static ControlCHooker _hooker; //// //// private static bool _wasOutRedirected; //// private static bool _wasErrorRedirected; //// //// // Private object for locking instead of locking on a public type for SQL reliability work. //// private static Object s_InternalSyncObject; //// private static Object InternalSyncObject //// { //// get //// { //// if(s_InternalSyncObject == null) //// { //// Object o = new Object(); //// Interlocked.CompareExchange( ref s_InternalSyncObject, o, null ); //// } //// return s_InternalSyncObject; //// } //// } //// //// // About reliability: I'm not using SafeHandle here. We don't //// // need to close these handles, and we don't allow the user to close //// // them so we don't have many of the security problems inherent in //// // something like file handles. Additionally, in a host like SQL //// // Server, we won't have a console. //// private static IntPtr _consoleInputHandle; //// private static IntPtr _consoleOutputHandle; //// //// private static IntPtr ConsoleInputHandle //// { //// [ResourceExposure( ResourceScope.Process )] //// [ResourceConsumption( ResourceScope.Process )] //// get //// { //// if(_consoleInputHandle == IntPtr.Zero) //// { //// _consoleInputHandle = Win32Native.GetStdHandle( Win32Native.STD_INPUT_HANDLE ); //// } //// return _consoleInputHandle; //// } //// } //// //// private static IntPtr ConsoleOutputHandle //// { //// [ResourceExposure( ResourceScope.Process )] //// [ResourceConsumption( ResourceScope.Process )] //// get //// { //// if(_consoleOutputHandle == IntPtr.Zero) //// { //// _consoleOutputHandle = Win32Native.GetStdHandle( Win32Native.STD_OUTPUT_HANDLE ); //// } //// return _consoleOutputHandle; //// } //// } //// //// public static TextWriter Error //// { //// [HostProtection( UI = true )] //// get //// { //// // Hopefully this is inlineable. //// if(_error == null) //// InitializeStdOutError( false ); //// return _error; //// } //// } //// //// public static TextReader In //// { //// [HostProtection( UI = true )] //// [ResourceExposure( ResourceScope.None )] //// [ResourceConsumption( ResourceScope.Process, ResourceScope.Process )] //// get //// { //// // Because most applications don't use stdin, we can delay //// // initialize it slightly better startup performance. //// if(_in == null) //// { //// lock(InternalSyncObject) //// { //// if(_in == null) //// { //// // Set up Console.In //// Stream s = OpenStandardInput( _DefaultConsoleBufferSize ); //// TextReader tr; //// if(s == Stream.Null) //// tr = StreamReader.Null; //// else //// { //// // Hopefully Encoding.GetEncoding doesn't load as many classes now. //// Encoding enc = Encoding.GetEncoding( (int)Win32Native.GetConsoleCP() ); //// tr = TextReader.Synchronized( new StreamReader( s, enc, false, _DefaultConsoleBufferSize, false ) ); //// } //// System.Threading.Thread.MemoryBarrier(); //// _in = tr; //// } //// } //// } //// return _in; //// } //// } //// //// public static TextWriter Out //// { //// [HostProtection( UI = true )] //// [ResourceExposure( ResourceScope.None )] //// [ResourceConsumption( ResourceScope.Process, ResourceScope.Process )] //// get //// { //// // Hopefully this is inlineable. //// if(_out == null) //// InitializeStdOutError( true ); //// return _out; //// } //// } //// //// // For console apps, the console handles are set to values like 3, 7, //// // and 11 OR if you've been created via CreateProcess, possibly -1 //// // or 0. -1 is definitely invalid, while 0 is probably invalid. //// // Also note each handle can independently be invalid or good. //// // For Windows apps, the console handles are set to values like 3, 7, //// // and 11 but are invalid handles - you may not write to them. However, //// // you can still spawn a Windows app via CreateProcess and read stdout //// // and stderr. //// // So, we always need to check each handle independently for validity //// // by trying to write or read to it, unless it is -1. //// //// // We do not do a security check here, under the assumption that this //// // cannot create a security hole, but only waste a user's time or //// // cause a possible denial of service attack. //// [ResourceExposure( ResourceScope.None )] //// [ResourceConsumption( ResourceScope.Process, ResourceScope.Process )] //// private static void InitializeStdOutError( bool stdout ) //// { //// // Set up Console.Out or Console.Error. //// lock(InternalSyncObject) //// { //// if(stdout && _out != null) //// return; //// else if(!stdout && _error != null) //// return; //// //// TextWriter writer = null; //// Stream s; //// if(stdout) //// s = OpenStandardOutput( _DefaultConsoleBufferSize ); //// else //// s = OpenStandardError( _DefaultConsoleBufferSize ); //// //// if(s == Stream.Null) //// { //// writer = TextWriter.Synchronized( StreamWriter.Null ); //// } //// else //// { //// int codePage = (int)Win32Native.GetConsoleOutputCP(); //// Encoding encoding = Encoding.GetEncoding( codePage ); //// StreamWriter stdxxx = new StreamWriter( s, encoding, _DefaultConsoleBufferSize, false ); //// stdxxx.HaveWrittenPreamble = true; //// stdxxx.AutoFlush = true; //// writer = TextWriter.Synchronized( stdxxx ); //// } //// if(stdout) //// _out = writer; //// else //// _error = writer; //// BCLDebug.Assert( (stdout && _out != null) || (!stdout && _error != null), "Didn't set Console::_out or _error appropriately!" ); //// } //// } //// //// // This method is only exposed via methods to get at the console. //// // We won't use any security checks here. //// [ResourceExposure( ResourceScope.Process )] //// [ResourceConsumption( ResourceScope.Process )] //// private static Stream GetStandardFile( int stdHandleName, FileAccess access, int bufferSize ) //// { //// // We shouldn't close the handle for stdout, etc, or we'll break //// // unmanaged code in the process that will print to console. //// // We should have a better way of marking this on SafeHandle. //// IntPtr handle = Win32Native.GetStdHandle( stdHandleName ); //// SafeFileHandle sh = new SafeFileHandle( handle, false ); //// //// // If someone launches a managed process via CreateProcess, stdout //// // stderr, & stdin could independently be set to INVALID_HANDLE_VALUE. //// // Additionally they might use 0 as an invalid handle. //// if(sh.IsInvalid) //// { //// // Minor perf optimization - get it out of the finalizer queue. //// sh.SetHandleAsInvalid(); //// return Stream.Null; //// } //// //// // Check whether we can read or write to this handle. //// if(stdHandleName != Win32Native.STD_INPUT_HANDLE && !ConsoleHandleIsValid( sh )) //// { //// //BCLDebug.ConsoleError("Console::ConsoleHandleIsValid for std handle "+stdHandleName+" failed, setting it to a null stream"); //// return Stream.Null; //// } //// //// //BCLDebug.ConsoleError("Console::GetStandardFile for std handle "+stdHandleName+" succeeded, returning handle number "+handle.ToString()); //// Stream console = new __ConsoleStream( sh, access ); //// // Do not buffer console streams, or we can get into situations where //// // we end up blocking waiting for you to hit enter twice. It was //// // redundant. //// return console; //// } //// //// public static Encoding InputEncoding //// { //// get //// { //// uint cp = Win32Native.GetConsoleCP(); //// return Encoding.GetEncoding( (int)cp ); //// } //// [ResourceExposure( ResourceScope.Process )] //// [ResourceConsumption( ResourceScope.Process )] //// set //// { //// if(value == null) //// throw new ArgumentNullException( "value" ); //// //// new UIPermission( UIPermissionWindow.SafeTopLevelWindows ).Demand(); //// //// uint cp = (uint)value.CodePage; //// //// lock(InternalSyncObject) //// { //// bool r = Win32Native.SetConsoleCP( cp ); //// if(!r) //// __Error.WinIOError(); //// //// // We need to reinitialize Console.In in the next call to _in //// // This will discard the current StreamReader, potentially //// // losing buffered data //// _in = null; //// } //// } //// } //// //// public static Encoding OutputEncoding //// { //// get //// { //// uint cp = Win32Native.GetConsoleOutputCP(); //// return Encoding.GetEncoding( (int)cp ); //// } //// [ResourceExposure( ResourceScope.Process )] //// [ResourceConsumption( ResourceScope.Process )] //// set //// { //// if(value == null) //// throw new ArgumentNullException( "value" ); //// //// new UIPermission( UIPermissionWindow.SafeTopLevelWindows ).Demand(); //// //// lock(InternalSyncObject) //// { //// // Before changing the code page we need to flush the data //// // if Out hasn't been redirected. Also, have the next call to //// // _out reinitialize the console code page. //// //// if(_out != null && !_wasOutRedirected) //// { //// _out.Flush(); //// _out = null; //// } //// if(_error != null && !_wasErrorRedirected) //// { //// _error.Flush(); //// _error = null; //// } //// //// uint cp = (uint)value.CodePage; //// bool r = Win32Native.SetConsoleOutputCP( cp ); //// if(!r) //// __Error.WinIOError(); //// } //// } //// } //// //// [HostProtection( UI = true )] //// public static void Beep() //// { //// Beep( 800, 200 ); //// } //// //// [HostProtection( UI = true )] //// public static void Beep( int frequency, int duration ) //// { //// if(frequency < MinBeepFrequency || frequency > MaxBeepFrequency) //// throw new ArgumentOutOfRangeException( "frequency", frequency, Environment.GetResourceString( "ArgumentOutOfRange_BeepFrequency", MinBeepFrequency, MaxBeepFrequency ) ); //// if(duration <= 0) //// throw new ArgumentOutOfRangeException( "duration", duration, Environment.GetResourceString( "ArgumentOutOfRange_NeedPosNum" ) ); //// //// // Note that Beep over Remote Desktop connections does not currently //// // work. Ignore any failures here. //// Win32Native.Beep( frequency, duration ); //// } //// //// [ResourceExposure( ResourceScope.Process )] //// [ResourceConsumption( ResourceScope.Process )] //// public static void Clear() //// { //// Win32Native.COORD coordScreen = new Win32Native.COORD(); //// Win32Native.CONSOLE_SCREEN_BUFFER_INFO csbi; //// bool success; //// int conSize; //// //// IntPtr hConsole = ConsoleOutputHandle; //// if(hConsole == Win32Native.INVALID_HANDLE_VALUE) //// throw new IOException( Environment.GetResourceString( "IO.IO_NoConsole" ) ); //// //// // get the number of character cells in the current buffer //// // Go through my helper method for fetching a screen buffer info //// // to correctly handle default console colors. //// csbi = GetBufferInfo(); //// conSize = csbi.dwSize.X * csbi.dwSize.Y; //// //// // fill the entire screen with blanks //// //// int numCellsWritten = 0; //// success = Win32Native.FillConsoleOutputCharacter( hConsole, ' ', //// conSize, coordScreen, out numCellsWritten ); //// if(!success) //// __Error.WinIOError(); //// //// // now set the buffer's attributes accordingly //// //// numCellsWritten = 0; //// success = Win32Native.FillConsoleOutputAttribute( hConsole, csbi.wAttributes, //// conSize, coordScreen, out numCellsWritten ); //// if(!success) //// __Error.WinIOError(); //// //// // put the cursor at (0, 0) //// //// success = Win32Native.SetConsoleCursorPosition( hConsole, coordScreen ); //// if(!success) //// __Error.WinIOError(); //// } public static extern ConsoleColor BackgroundColor { //// [ResourceExposure( ResourceScope.None )] //// [ResourceConsumption( ResourceScope.Process, ResourceScope.Process )] [MethodImpl( MethodImplOptions.InternalCall )] get; //// [ResourceExposure( ResourceScope.Process )] //// [ResourceConsumption( ResourceScope.Process )] [MethodImpl( MethodImplOptions.InternalCall )] set; } public static extern ConsoleColor ForegroundColor { //// [ResourceExposure( ResourceScope.None )] //// [ResourceConsumption( ResourceScope.Process, ResourceScope.Process )] [MethodImpl( MethodImplOptions.InternalCall )] get; //// [ResourceExposure( ResourceScope.Process )] //// [ResourceConsumption( ResourceScope.Process )] [MethodImpl( MethodImplOptions.InternalCall )] set; } //// [ResourceExposure( ResourceScope.Process )] //// [ResourceConsumption( ResourceScope.Process )] //// public static void ResetColor() //// { //// new UIPermission( UIPermissionWindow.SafeTopLevelWindows ).Demand(); //// //// bool succeeded; //// Win32Native.CONSOLE_SCREEN_BUFFER_INFO csbi = GetBufferInfo( false, out succeeded ); //// // For code that may be used from Windows app w/ no console //// if(!succeeded) //// return; //// //// BCLDebug.Assert( _haveReadDefaultColors, "Setting the foreground color before we've read the default foreground color!" ); //// //// short defaultAttrs = (short)(ushort)_defaultColors; //// // Ignore errors here - there are some scenarios for running code that wants //// // to print in colors to the console in a Windows application. //// Win32Native.SetConsoleTextAttribute( ConsoleOutputHandle, defaultAttrs ); //// } //// //// [ResourceExposure( ResourceScope.Process )] //// [ResourceConsumption( ResourceScope.Process )] //// public static void MoveBufferArea( int sourceLeft, int sourceTop, //// int sourceWidth, int sourceHeight, int targetLeft, int targetTop ) //// { //// MoveBufferArea( sourceLeft, sourceTop, sourceWidth, sourceHeight, targetLeft, targetTop, ' ', ConsoleColor.Black, BackgroundColor ); //// } //// //// [ResourceExposure( ResourceScope.Process )] //// [ResourceConsumption( ResourceScope.Process )] //// public unsafe static void MoveBufferArea( int sourceLeft, int sourceTop, //// int sourceWidth, int sourceHeight, int targetLeft, int targetTop, //// char sourceChar, ConsoleColor sourceForeColor, //// ConsoleColor sourceBackColor ) //// { //// if(sourceForeColor < ConsoleColor.Black || sourceForeColor > ConsoleColor.White) //// throw new ArgumentException( Environment.GetResourceString( "Arg_InvalidConsoleColor" ), "sourceForeColor" ); //// if(sourceBackColor < ConsoleColor.Black || sourceBackColor > ConsoleColor.White) //// throw new ArgumentException( Environment.GetResourceString( "Arg_InvalidConsoleColor" ), "sourceBackColor" ); //// //// Win32Native.CONSOLE_SCREEN_BUFFER_INFO csbi = GetBufferInfo(); //// Win32Native.COORD bufferSize = csbi.dwSize; //// if(sourceLeft < 0 || sourceLeft > bufferSize.X) //// throw new ArgumentOutOfRangeException( "sourceLeft", sourceLeft, Environment.GetResourceString( "ArgumentOutOfRange_ConsoleBufferBoundaries" ) ); //// if(sourceTop < 0 || sourceTop > bufferSize.Y) //// throw new ArgumentOutOfRangeException( "sourceTop", sourceTop, Environment.GetResourceString( "ArgumentOutOfRange_ConsoleBufferBoundaries" ) ); //// if(sourceWidth < 0 || sourceWidth > bufferSize.X - sourceLeft) //// throw new ArgumentOutOfRangeException( "sourceWidth", sourceWidth, Environment.GetResourceString( "ArgumentOutOfRange_ConsoleBufferBoundaries" ) ); //// if(sourceHeight < 0 || sourceTop > bufferSize.Y - sourceHeight) //// throw new ArgumentOutOfRangeException( "sourceHeight", sourceHeight, Environment.GetResourceString( "ArgumentOutOfRange_ConsoleBufferBoundaries" ) ); //// //// // Note: if the target range is partially in and partially out //// // of the buffer, then we let the OS clip it for us. //// if(targetLeft < 0 || targetLeft > bufferSize.X) //// throw new ArgumentOutOfRangeException( "targetLeft", targetLeft, Environment.GetResourceString( "ArgumentOutOfRange_ConsoleBufferBoundaries" ) ); //// if(targetTop < 0 || targetTop > bufferSize.Y) //// throw new ArgumentOutOfRangeException( "targetTop", targetTop, Environment.GetResourceString( "ArgumentOutOfRange_ConsoleBufferBoundaries" ) ); //// //// // If we're not doing any work, bail out now (Windows will return //// // an error otherwise) //// if(sourceWidth == 0 || sourceHeight == 0) //// return; //// //// new UIPermission( UIPermissionWindow.SafeTopLevelWindows ).Demand(); //// //// // Read data from the original location, blank it out, then write //// // it to the new location. This will handle overlapping source and //// // destination regions correctly. //// //// // See the "Reading and Writing Blocks of Characters and Attributes" //// // sample for help //// //// // Read the old data //// Win32Native.CHAR_INFO[] data = new Win32Native.CHAR_INFO[sourceWidth * sourceHeight]; //// bufferSize.X = (short)sourceWidth; //// bufferSize.Y = (short)sourceHeight; //// Win32Native.COORD bufferCoord = new Win32Native.COORD(); //// Win32Native.SMALL_RECT readRegion = new Win32Native.SMALL_RECT(); //// readRegion.Left = (short)sourceLeft; //// readRegion.Right = (short)(sourceLeft + sourceWidth - 1); //// readRegion.Top = (short)sourceTop; //// readRegion.Bottom = (short)(sourceTop + sourceHeight - 1); //// //// bool r; //// fixed(Win32Native.CHAR_INFO* pCharInfo = data) //// r = Win32Native.ReadConsoleOutput( ConsoleOutputHandle, pCharInfo, bufferSize, bufferCoord, ref readRegion ); //// if(!r) //// __Error.WinIOError(); //// //// // Overwrite old section //// // I don't have a good function to blank out a rectangle. //// Win32Native.COORD writeCoord = new Win32Native.COORD(); //// writeCoord.X = (short)sourceLeft; //// Win32Native.Color c = ConsoleColorToColorAttribute( sourceBackColor, true ); //// c |= ConsoleColorToColorAttribute( sourceForeColor, false ); //// short attr = (short)c; //// int numWritten; //// for(int i = sourceTop; i < sourceTop + sourceHeight; i++) //// { //// writeCoord.Y = (short)i; //// r = Win32Native.FillConsoleOutputCharacter( ConsoleOutputHandle, sourceChar, sourceWidth, writeCoord, out numWritten ); //// BCLDebug.Assert( numWritten == sourceWidth, "FillConsoleOutputCharacter wrote the wrong number of chars!" ); //// if(!r) //// __Error.WinIOError(); //// //// r = Win32Native.FillConsoleOutputAttribute( ConsoleOutputHandle, attr, sourceWidth, writeCoord, out numWritten ); //// if(!r) //// __Error.WinIOError(); //// } //// //// // Write text to new location //// Win32Native.SMALL_RECT writeRegion = new Win32Native.SMALL_RECT(); //// writeRegion.Left = (short)targetLeft; //// writeRegion.Right = (short)(targetLeft + sourceWidth); //// writeRegion.Top = (short)targetTop; //// writeRegion.Bottom = (short)(targetTop + sourceHeight); //// //// fixed(Win32Native.CHAR_INFO* pCharInfo = data) //// r = Win32Native.WriteConsoleOutput( ConsoleOutputHandle, pCharInfo, bufferSize, bufferCoord, ref writeRegion ); //// } //// //// public static int BufferHeight //// { //// [ResourceExposure( ResourceScope.Process )] //// [ResourceConsumption( ResourceScope.Process )] //// get //// { //// Win32Native.CONSOLE_SCREEN_BUFFER_INFO csbi = GetBufferInfo(); //// return csbi.dwSize.Y; //// } //// [ResourceExposure( ResourceScope.Process )] //// [ResourceConsumption( ResourceScope.Process )] //// set //// { //// SetBufferSize( BufferWidth, value ); //// } //// } //// //// public static int BufferWidth //// { //// [ResourceExposure( ResourceScope.Process )] //// [ResourceConsumption( ResourceScope.Process )] //// get //// { //// Win32Native.CONSOLE_SCREEN_BUFFER_INFO csbi = GetBufferInfo(); //// return csbi.dwSize.X; //// } //// [ResourceExposure( ResourceScope.Process )] //// [ResourceConsumption( ResourceScope.Process )] //// set //// { //// SetBufferSize( value, BufferHeight ); //// } //// } //// //// [ResourceExposure( ResourceScope.Process )] //// [ResourceConsumption( ResourceScope.Process )] //// public static void SetBufferSize( int width, int height ) //// { //// new UIPermission( UIPermissionWindow.SafeTopLevelWindows ).Demand(); //// //// // Ensure the new size is not smaller than the console window //// Win32Native.CONSOLE_SCREEN_BUFFER_INFO csbi = GetBufferInfo(); //// Win32Native.SMALL_RECT srWindow = csbi.srWindow; //// if(width < srWindow.Right + 1 || width >= Int16.MaxValue) //// throw new ArgumentOutOfRangeException( "width", width, Environment.GetResourceString( "ArgumentOutOfRange_ConsoleBufferLessThanWindowSize" ) ); //// if(height < srWindow.Bottom + 1 || height >= Int16.MaxValue) //// throw new ArgumentOutOfRangeException( "height", height, Environment.GetResourceString( "ArgumentOutOfRange_ConsoleBufferLessThanWindowSize" ) ); //// //// Win32Native.COORD size = new Win32Native.COORD(); //// size.X = (short)width; //// size.Y = (short)height; //// bool r = Win32Native.SetConsoleScreenBufferSize( ConsoleOutputHandle, size ); //// if(!r) //// __Error.WinIOError(); //// } //// //// //// public static int WindowHeight //// { //// [ResourceExposure( ResourceScope.None )] //// [ResourceConsumption( ResourceScope.Process, ResourceScope.Process )] //// get //// { //// Win32Native.CONSOLE_SCREEN_BUFFER_INFO csbi = GetBufferInfo(); //// return csbi.srWindow.Bottom - csbi.srWindow.Top + 1; //// } //// [ResourceExposure( ResourceScope.Process )] //// [ResourceConsumption( ResourceScope.Process )] //// set //// { //// SetWindowSize( WindowWidth, value ); //// } //// } //// //// public static int WindowWidth //// { //// [ResourceExposure( ResourceScope.None )] //// [ResourceConsumption( ResourceScope.Process, ResourceScope.Process )] //// get //// { //// Win32Native.CONSOLE_SCREEN_BUFFER_INFO csbi = GetBufferInfo(); //// return csbi.srWindow.Right - csbi.srWindow.Left + 1; //// } //// [ResourceExposure( ResourceScope.Process )] //// [ResourceConsumption( ResourceScope.Process )] //// set //// { //// SetWindowSize( value, WindowHeight ); //// } //// } //// //// [ResourceExposure( ResourceScope.Process )] //// [ResourceConsumption( ResourceScope.Process )] //// public static unsafe void SetWindowSize( int width, int height ) //// { //// new UIPermission( UIPermissionWindow.SafeTopLevelWindows ).Demand(); //// //// // Get the position of the current console window //// Win32Native.CONSOLE_SCREEN_BUFFER_INFO csbi = GetBufferInfo(); //// //// if(width <= 0) //// throw new ArgumentOutOfRangeException( "width", width, Environment.GetResourceString( "ArgumentOutOfRange_NeedPosNum" ) ); //// if(height <= 0) //// throw new ArgumentOutOfRangeException( "height", height, Environment.GetResourceString( "ArgumentOutOfRange_NeedPosNum" ) ); //// //// bool r; //// //// // If the buffer is smaller than this new window size, resize the //// // buffer to be large enough. Include window position. //// bool resizeBuffer = false; //// Win32Native.COORD size = new Win32Native.COORD(); //// size.X = csbi.dwSize.X; //// size.Y = csbi.dwSize.Y; //// if(csbi.dwSize.X < csbi.srWindow.Left + width) //// { //// if(csbi.srWindow.Left >= Int16.MaxValue - width) //// throw new ArgumentOutOfRangeException( "width", Environment.GetResourceString( "ArgumentOutOfRange_ConsoleWindowBufferSize" ) ); //// size.X = (short)(csbi.srWindow.Left + width); //// resizeBuffer = true; //// } //// if(csbi.dwSize.Y < csbi.srWindow.Top + height) //// { //// if(csbi.srWindow.Top >= Int16.MaxValue - height) //// throw new ArgumentOutOfRangeException( "height", Environment.GetResourceString( "ArgumentOutOfRange_ConsoleWindowBufferSize" ) ); //// size.Y = (short)(csbi.srWindow.Top + height); //// resizeBuffer = true; //// } //// if(resizeBuffer) //// { //// r = Win32Native.SetConsoleScreenBufferSize( ConsoleOutputHandle, size ); //// if(!r) //// __Error.WinIOError(); //// } //// //// Win32Native.SMALL_RECT srWindow = csbi.srWindow; //// // Preserve the position, but change the size. //// srWindow.Bottom = (short)(srWindow.Top + height - 1); //// srWindow.Right = (short)(srWindow.Left + width - 1); //// //// r = Win32Native.SetConsoleWindowInfo( ConsoleOutputHandle, true, &srWindow ); //// if(!r) //// { //// int errorCode = Marshal.GetLastWin32Error(); //// //// // If we resized the buffer, un-resize it. //// if(resizeBuffer) //// { //// Win32Native.SetConsoleScreenBufferSize( ConsoleOutputHandle, csbi.dwSize ); //// } //// //// // Try to give a better error message here //// Win32Native.COORD bounds = Win32Native.GetLargestConsoleWindowSize( ConsoleOutputHandle ); //// if(width > bounds.X) //// throw new ArgumentOutOfRangeException( "width", width, Environment.GetResourceString( "ArgumentOutOfRange_ConsoleWindowSize_Size", bounds.X ) ); //// if(height > bounds.Y) //// throw new ArgumentOutOfRangeException( "height", height, Environment.GetResourceString( "ArgumentOutOfRange_ConsoleWindowSize_Size", bounds.Y ) ); //// //// __Error.WinIOError( errorCode, String.Empty ); //// } //// } //// //// public static int LargestWindowWidth //// { //// [ResourceExposure( ResourceScope.None )] //// [ResourceConsumption( ResourceScope.Process, ResourceScope.Process )] //// get //// { //// // Note this varies based on current screen resolution and //// // current console font. Do not cache this value. //// Win32Native.COORD bounds = Win32Native.GetLargestConsoleWindowSize( ConsoleOutputHandle ); //// return bounds.X; //// } //// } //// //// public static int LargestWindowHeight //// { //// [ResourceExposure( ResourceScope.None )] //// [ResourceConsumption( ResourceScope.Process, ResourceScope.Process )] //// get //// { //// // Note this varies based on current screen resolution and //// // current console font. Do not cache this value. //// Win32Native.COORD bounds = Win32Native.GetLargestConsoleWindowSize( ConsoleOutputHandle ); //// return bounds.Y; //// } //// } //// //// public static int WindowLeft //// { //// [ResourceExposure( ResourceScope.None )] //// [ResourceConsumption( ResourceScope.Process, ResourceScope.Process )] //// get //// { //// Win32Native.CONSOLE_SCREEN_BUFFER_INFO csbi = GetBufferInfo(); //// return csbi.srWindow.Left; //// } //// [ResourceExposure( ResourceScope.Process )] //// [ResourceConsumption( ResourceScope.Process )] //// set //// { //// SetWindowPosition( value, WindowTop ); //// } //// } //// //// public static int WindowTop //// { //// [ResourceExposure( ResourceScope.None )] //// [ResourceConsumption( ResourceScope.Process, ResourceScope.Process )] //// get //// { //// Win32Native.CONSOLE_SCREEN_BUFFER_INFO csbi = GetBufferInfo(); //// return csbi.srWindow.Top; //// } //// [ResourceExposure( ResourceScope.Process )] //// [ResourceConsumption( ResourceScope.Process )] //// set //// { //// SetWindowPosition( WindowLeft, value ); //// } //// } //// //// [ResourceExposure( ResourceScope.Process )] //// [ResourceConsumption( ResourceScope.Process )] //// public static unsafe void SetWindowPosition( int left, int top ) //// { //// new UIPermission( UIPermissionWindow.SafeTopLevelWindows ).Demand(); //// //// // Get the size of the current console window //// Win32Native.CONSOLE_SCREEN_BUFFER_INFO csbi = GetBufferInfo(); //// //// Win32Native.SMALL_RECT srWindow = csbi.srWindow; //// //// // Check for arithmetic underflows & overflows. //// int newRight = left + srWindow.Right - srWindow.Left + 1; //// if(left < 0 || newRight > csbi.dwSize.X || newRight < 0) //// throw new ArgumentOutOfRangeException( "left", left, Environment.GetResourceString( "ArgumentOutOfRange_ConsoleWindowPos" ) ); //// int newBottom = top + srWindow.Bottom - srWindow.Top + 1; //// if(top < 0 || newBottom > csbi.dwSize.Y || newBottom < 0) //// throw new ArgumentOutOfRangeException( "top", top, Environment.GetResourceString( "ArgumentOutOfRange_ConsoleWindowPos" ) ); //// //// // Preserve the size, but move the position. //// srWindow.Bottom -= (short)(srWindow.Top - top); //// srWindow.Right -= (short)(srWindow.Left - left); //// srWindow.Left = (short)left; //// srWindow.Top = (short)top; //// //// bool r = Win32Native.SetConsoleWindowInfo( ConsoleOutputHandle, true, &srWindow ); //// if(!r) //// __Error.WinIOError(); //// } //// //// public static int CursorLeft //// { //// [ResourceExposure( ResourceScope.None )] //// [ResourceConsumption( ResourceScope.Process, ResourceScope.Process )] //// get //// { //// Win32Native.CONSOLE_SCREEN_BUFFER_INFO csbi = GetBufferInfo(); //// return csbi.dwCursorPosition.X; //// } //// [ResourceExposure( ResourceScope.Process )] //// [ResourceConsumption( ResourceScope.Process )] //// set //// { //// SetCursorPosition( value, CursorTop ); //// } //// } //// //// public static int CursorTop //// { //// [ResourceExposure( ResourceScope.None )] //// [ResourceConsumption( ResourceScope.Process, ResourceScope.Process )] //// get //// { //// Win32Native.CONSOLE_SCREEN_BUFFER_INFO csbi = GetBufferInfo(); //// return csbi.dwCursorPosition.Y; //// } //// [ResourceExposure( ResourceScope.Process )] //// [ResourceConsumption( ResourceScope.Process )] //// set //// { //// SetCursorPosition( CursorLeft, value ); //// } //// } //// //// [ResourceExposure( ResourceScope.Process )] //// [ResourceConsumption( ResourceScope.Process )] //// public static void SetCursorPosition( int left, int top ) //// { //// // Note on argument checking - the upper bounds are NOT correct //// // here! But it looks slightly expensive to compute them. Let //// // Windows calculate them, then we'll give a nice error message. //// if(left < 0 || left >= Int16.MaxValue) //// throw new ArgumentOutOfRangeException( "left", left, Environment.GetResourceString( "ArgumentOutOfRange_ConsoleBufferBoundaries" ) ); //// if(top < 0 || top >= Int16.MaxValue) //// throw new ArgumentOutOfRangeException( "top", top, Environment.GetResourceString( "ArgumentOutOfRange_ConsoleBufferBoundaries" ) ); //// //// new UIPermission( UIPermissionWindow.SafeTopLevelWindows ).Demand(); //// //// IntPtr hConsole = ConsoleOutputHandle; //// Win32Native.COORD coords = new Win32Native.COORD(); //// coords.X = (short)left; //// coords.Y = (short)top; //// bool r = Win32Native.SetConsoleCursorPosition( hConsole, coords ); //// if(!r) //// { //// // Give a nice error message for out of range sizes //// int errorCode = Marshal.GetLastWin32Error(); //// Win32Native.CONSOLE_SCREEN_BUFFER_INFO csbi = GetBufferInfo(); //// if(left < 0 || left >= csbi.dwSize.X) //// throw new ArgumentOutOfRangeException( "left", left, Environment.GetResourceString( "ArgumentOutOfRange_ConsoleBufferBoundaries" ) ); //// if(top < 0 || top >= csbi.dwSize.Y) //// throw new ArgumentOutOfRangeException( "top", top, Environment.GetResourceString( "ArgumentOutOfRange_ConsoleBufferBoundaries" ) ); //// //// __Error.WinIOError( errorCode, String.Empty ); //// } //// } //// //// public static int CursorSize //// { //// [ResourceExposure( ResourceScope.None )] //// [ResourceConsumption( ResourceScope.Process, ResourceScope.Process )] //// get //// { //// Win32Native.CONSOLE_CURSOR_INFO cci; //// IntPtr hConsole = ConsoleOutputHandle; //// bool r = Win32Native.GetConsoleCursorInfo( hConsole, out cci ); //// if(!r) //// __Error.WinIOError(); //// //// return cci.dwSize; //// } //// [ResourceExposure( ResourceScope.Process )] //// [ResourceConsumption( ResourceScope.Process )] //// set //// { //// // Value should be a percentage from [1, 100]. //// if(value < 1 || value > 100) //// throw new ArgumentOutOfRangeException( "value", value, Environment.GetResourceString( "ArgumentOutOfRange_CursorSize" ) ); //// //// new UIPermission( UIPermissionWindow.SafeTopLevelWindows ).Demand(); //// //// Win32Native.CONSOLE_CURSOR_INFO cci; //// IntPtr hConsole = ConsoleOutputHandle; //// bool r = Win32Native.GetConsoleCursorInfo( hConsole, out cci ); //// if(!r) //// __Error.WinIOError(); //// //// cci.dwSize = value; //// r = Win32Native.SetConsoleCursorInfo( hConsole, ref cci ); //// if(!r) //// __Error.WinIOError(); //// } //// } //// //// public static bool CursorVisible //// { //// [ResourceExposure( ResourceScope.None )] //// [ResourceConsumption( ResourceScope.Process, ResourceScope.Process )] //// get //// { //// Win32Native.CONSOLE_CURSOR_INFO cci; //// IntPtr hConsole = ConsoleOutputHandle; //// bool r = Win32Native.GetConsoleCursorInfo( hConsole, out cci ); //// if(!r) //// __Error.WinIOError(); //// //// return cci.bVisible; //// } //// [ResourceExposure( ResourceScope.Process )] //// [ResourceConsumption( ResourceScope.Process )] //// set //// { //// new UIPermission( UIPermissionWindow.SafeTopLevelWindows ).Demand(); //// //// Win32Native.CONSOLE_CURSOR_INFO cci; //// IntPtr hConsole = ConsoleOutputHandle; //// bool r = Win32Native.GetConsoleCursorInfo( hConsole, out cci ); //// if(!r) //// __Error.WinIOError(); //// //// cci.bVisible = value; //// r = Win32Native.SetConsoleCursorInfo( hConsole, ref cci ); //// if(!r) //// __Error.WinIOError(); //// } //// } //// //// public static String Title //// { //// [ResourceExposure( ResourceScope.None )] //// [ResourceConsumption( ResourceScope.Process, ResourceScope.Process )] //// get //// { //// StringBuilder sb = new StringBuilder( MaxConsoleTitleLength + 1 ); //// // As of Windows Server 2003 (and probably all prior //// // releases), GetConsoleTitle doesn't do anything useful on //// // empty strings, such as calling SetLastError so callers can //// // determine whether that 0 was an error or was a success. //// Win32Native.SetLastError( 0 ); //// int r = Win32Native.GetConsoleTitle( sb, sb.Capacity ); //// if(r == 0) //// { //// // Allow a 0-length title //// int errorCode = Marshal.GetLastWin32Error(); //// if(errorCode == 0) //// sb.Length = 0; //// else //// __Error.WinIOError( errorCode, String.Empty ); //// } //// else if(r > MaxConsoleTitleLength) //// throw new InvalidOperationException( Environment.GetResourceString( "ArgumentOutOfRange_ConsoleTitleTooLong" ) ); //// return sb.ToString(); //// } //// [ResourceExposure( ResourceScope.None )] //// [ResourceConsumption( ResourceScope.Process, ResourceScope.Process )] //// set //// { //// new UIPermission( UIPermissionWindow.SafeTopLevelWindows ).Demand(); //// //// if(value == null) //// throw new ArgumentNullException( "value" ); //// if(value.Length > MaxConsoleTitleLength) //// throw new ArgumentOutOfRangeException( "value", Environment.GetResourceString( "ArgumentOutOfRange_ConsoleTitleTooLong" ) ); //// //// if(!Win32Native.SetConsoleTitle( value )) //// __Error.WinIOError(); //// } //// } //// //// [Flags] //// internal enum ControlKeyState //// { //// RightAltPressed = 0x0001, //// LeftAltPressed = 0x0002, //// RightCtrlPressed = 0x0004, //// LeftCtrlPressed = 0x0008, //// ShiftPressed = 0x0010, //// NumLockOn = 0x0020, //// ScrollLockOn = 0x0040, //// CapsLockOn = 0x0080, //// EnhancedKey = 0x0100 //// } //// //// [HostProtection( UI = true )] //// [ResourceExposure( ResourceScope.Process )] //// [ResourceConsumption( ResourceScope.Process )] //// public static ConsoleKeyInfo ReadKey() //// { //// return ReadKey( false ); //// } //// //// // For tracking Alt+NumPad unicode key sequence. When you presss Alt key down //// // and press a numpad unicode decimal sequence and then release Alt key, the //// // desired effect is to translate the sequence into one Unicode KeyPress. //// // We need to keep track of the Alt+NumPad sequence and surface the final //// // unicode char alone when the Alt key is released. //// private static bool IsAltKeyDown( Win32Native.InputRecord ir ) //// { //// return (((ControlKeyState)ir.keyEvent.controlKeyState) //// & (ControlKeyState.LeftAltPressed | ControlKeyState.RightAltPressed)) != 0; //// } //// //// // Skip non key events. Generally we want to surface only KeyDown event //// // and suppress KeyUp event from the same Key press but there are cases //// // where the assumption of KeyDown-KeyUp pairing for a given key press //// // is invalid. For example in IME Unicode keyboard input, we often see //// // only KeyUp until the key is released. //// private static bool IsKeyDownEvent( Win32Native.InputRecord ir ) //// { //// return (ir.eventType == Win32Native.KEY_EVENT && ir.keyEvent.keyDown); //// } //// //// private static bool IsModKey( Win32Native.InputRecord ir ) //// { //// // We should also skip over Shift, Control, and Alt, as well as caps lock. //// // Apparently we don't need to check for 0xA0 through 0xA5, which are keys like //// // Left Control & Right Control. See the ConsoleKey enum for these values. //// short keyCode = ir.keyEvent.virtualKeyCode; //// return ((keyCode >= 0x10 && keyCode <= 0x12) //// || keyCode == 0x14 || keyCode == 0x90 || keyCode == 0x91); //// } //// //// [HostProtection( UI = true )] //// [ResourceExposure( ResourceScope.Process )] //// [ResourceConsumption( ResourceScope.Process )] //// public static ConsoleKeyInfo ReadKey( bool intercept ) //// { //// Win32Native.InputRecord ir; //// int numEventsRead = -1; //// bool r; //// //// if(_cachedInputRecord.eventType == Win32Native.KEY_EVENT) //// { //// // We had a previous keystroke with repeated characters. //// ir = _cachedInputRecord; //// if(_cachedInputRecord.keyEvent.repeatCount == 0) //// _cachedInputRecord.eventType = -1; //// else //// { //// _cachedInputRecord.keyEvent.repeatCount--; //// } //// // We will return one key from this method, so we decrement the //// // repeatCount here, leaving the cachedInputRecord in the "queue". //// } //// else //// { //// while(true) //// { //// r = Win32Native.ReadConsoleInput( ConsoleInputHandle, out ir, 1, out numEventsRead ); //// if(!r || numEventsRead == 0) //// { //// // This will fail when stdin is redirected from a file or pipe. //// // We could theoretically call Console.Read here, but I //// // think we might do some things incorrectly then. //// throw new InvalidOperationException( Environment.GetResourceString( "InvalidOperation_ConsoleReadKeyOnFile" ) ); //// } //// //// short keyCode = ir.keyEvent.virtualKeyCode; //// //// // First check for non-keyboard events & discard them. Generally we tap into only KeyDown events and ignore the KeyUp events //// // but it is possible that we are dealing with a Alt+NumPad unicode key sequence, the final unicode char is revealed only when //// // the Alt key is released (i.e when the sequence is complete). To avoid noise, when the Alt key is down, we should eat up //// // any intermediate key strokes (from NumPad) that collectively forms the Unicode character. //// //// if(!IsKeyDownEvent( ir )) //// { //// // REVIEW: Unicode IME input comes through as KeyUp event with no accompanying KeyDown. //// if(keyCode != AltVKCode) //// continue; //// } //// //// char ch = (char)ir.keyEvent.uChar; //// //// // In a Alt+NumPad unicode sequence, when the alt key is released uChar will represent the final unicode character, we need to //// // surface this. VirtualKeyCode for this event will be Alt from the Alt-Up key event. This is probably not the right code, //// // especially when we don't expose ConsoleKey.Alt, so this will end up being the hex value (0x12). VK_PACKET comes very //// // close to being useful and something that we could look into using for this purpose... //// //// if(ch == 0) //// { //// // Skip mod keys. //// if(IsModKey( ir )) //// continue; //// } //// //// // When Alt is down, it is possible that we are in the middle of a Alt+NumPad unicode sequence. //// // Escape any intermediate NumPad keys whether NumLock is on or not (notepad behavior) //// ConsoleKey key = (ConsoleKey)keyCode; //// if(IsAltKeyDown( ir ) && ((key >= ConsoleKey.NumPad0 && key <= ConsoleKey.NumPad9) //// || (key == ConsoleKey.Clear) || (key == ConsoleKey.Insert) //// || (key >= ConsoleKey.PageUp && key <= ConsoleKey.DownArrow))) //// { //// continue; //// } //// //// if(ir.keyEvent.repeatCount > 1) //// { //// ir.keyEvent.repeatCount--; //// _cachedInputRecord = ir; //// } //// break; //// } //// } //// //// ControlKeyState state = (ControlKeyState)ir.keyEvent.controlKeyState; //// bool shift = (state & ControlKeyState.ShiftPressed) != 0; //// bool alt = (state & (ControlKeyState.LeftAltPressed | ControlKeyState.RightAltPressed)) != 0; //// bool control = (state & (ControlKeyState.LeftCtrlPressed | ControlKeyState.RightCtrlPressed)) != 0; //// //// ConsoleKeyInfo info = new ConsoleKeyInfo( (char)ir.keyEvent.uChar, (ConsoleKey)ir.keyEvent.virtualKeyCode, shift, alt, control ); //// //// if(!intercept) //// Console.Write( ir.keyEvent.uChar ); //// return info; //// } //// //// public static bool KeyAvailable //// { //// [ResourceExposure( ResourceScope.Process )] //// [ResourceConsumption( ResourceScope.Process )] //// [HostProtection( UI = true )] //// get //// { //// if(_cachedInputRecord.eventType == Win32Native.KEY_EVENT) //// return true; //// //// Win32Native.InputRecord ir = new Win32Native.InputRecord(); //// int numEventsRead = 0; //// while(true) //// { //// bool r = Win32Native.PeekConsoleInput( ConsoleInputHandle, out ir, 1, out numEventsRead ); //// if(!r) //// { //// int errorCode = Marshal.GetLastWin32Error(); //// if(errorCode == Win32Native.ERROR_INVALID_HANDLE) //// throw new InvalidOperationException( Environment.GetResourceString( "InvalidOperation_ConsoleKeyAvailableOnFile" ) ); //// __Error.WinIOError( errorCode, "stdin" ); //// } //// //// if(numEventsRead == 0) //// return false; //// //// // Skip non key-down && mod key events. //// if(!IsKeyDownEvent( ir ) || IsModKey( ir )) //// { //// // REVIEW: Unicode IME input comes through as KeyUp event with no accompanying KeyDown //// //// // Exempt Alt keyUp for possible Alt+NumPad unicode sequence. //// //short keyCode = ir.keyEvent.virtualKeyCode; //// //if (!IsKeyDownEvent(ir) && (keyCode == AltVKCode)) //// // return true; //// //// r = Win32Native.ReadConsoleInput( ConsoleInputHandle, out ir, 1, out numEventsRead ); //// //// if(!r) //// __Error.WinIOError(); //// } //// else //// { //// return true; //// } //// } //// } //// } //// //// public static bool NumberLock //// { //// [ResourceExposure( ResourceScope.Process )] //// [ResourceConsumption( ResourceScope.Process )] //// get //// { //// short s = Win32Native.GetKeyState( NumberLockVKCode ); //// return (s & 1) == 1; //// } //// } //// //// public static bool CapsLock //// { //// [ResourceExposure( ResourceScope.Process )] //// [ResourceConsumption( ResourceScope.Process )] //// get //// { //// short s = Win32Native.GetKeyState( CapsLockVKCode ); //// return (s & 1) == 1; //// } //// } //// //// public static bool TreatControlCAsInput //// { //// [ResourceExposure( ResourceScope.None )] //// [ResourceConsumption( ResourceScope.Process, ResourceScope.Process )] //// get //// { //// IntPtr handle = ConsoleInputHandle; //// if(handle == Win32Native.INVALID_HANDLE_VALUE) //// throw new IOException( Environment.GetResourceString( "IO.IO_NoConsole" ) ); //// int mode = 0; //// bool r = Win32Native.GetConsoleMode( handle, out mode ); //// if(!r) //// __Error.WinIOError(); //// return (mode & Win32Native.ENABLE_PROCESSED_INPUT) == 0; //// } //// [ResourceExposure( ResourceScope.Process )] //// [ResourceConsumption( ResourceScope.Process )] //// set //// { //// new UIPermission( UIPermissionWindow.SafeTopLevelWindows ).Demand(); //// //// IntPtr handle = ConsoleInputHandle; //// if(handle == Win32Native.INVALID_HANDLE_VALUE) //// throw new IOException( Environment.GetResourceString( "IO.IO_NoConsole" ) ); //// //// int mode = 0; //// bool r = Win32Native.GetConsoleMode( handle, out mode ); //// if(value) //// mode &= ~Win32Native.ENABLE_PROCESSED_INPUT; //// else //// mode |= Win32Native.ENABLE_PROCESSED_INPUT; //// r = Win32Native.SetConsoleMode( handle, mode ); //// //// if(!r) //// __Error.WinIOError(); //// } //// } //// //// // During an appdomain unload, we must call into the OS and remove //// // our delegate from the OS's list of console control handlers. If //// // we don't do this, the OS will call back on a delegate that no //// // longer exists. So, subclass CriticalFinalizableObject. //// // This problem would theoretically exist during process exit for a //// // single appdomain too, so using a critical finalizer is probably //// // better than the appdomain unload event (I'm not sure we call that //// // in the default appdomain during process exit). //// internal sealed class ControlCHooker : CriticalFinalizerObject //// { //// private bool _hooked; //// private Win32Native.ConsoleCtrlHandlerRoutine _handler; //// //// internal ControlCHooker() //// { //// _handler = new Win32Native.ConsoleCtrlHandlerRoutine( BreakEvent ); //// } //// //// [ResourceExposure( ResourceScope.None )] //// [ResourceConsumption( ResourceScope.Machine, ResourceScope.Machine )] //// ~ControlCHooker() //// { //// Unhook(); //// } //// //// [ResourceExposure( ResourceScope.Process )] //// [ResourceConsumption( ResourceScope.Process )] //// internal void Hook() //// { //// if(!_hooked) //// { //// bool r = Win32Native.SetConsoleCtrlHandler( _handler, true ); //// if(!r) //// __Error.WinIOError(); //// _hooked = true; //// } //// } //// //// [ReliabilityContract( Consistency.WillNotCorruptState, Cer.Success )] //// [ResourceExposure( ResourceScope.Process )] //// [ResourceConsumption( ResourceScope.Process )] //// internal void Unhook() //// { //// if(_hooked) //// { //// bool r = Win32Native.SetConsoleCtrlHandler( _handler, false ); //// if(!r) //// __Error.WinIOError(); //// _hooked = false; //// } //// } //// } //// //// // A class with data so ControlC handlers can be called on a Threadpool thread. //// private sealed class ControlCDelegateData //// { //// internal ConsoleSpecialKey ControlKey; //// internal bool Cancel; //// internal bool DelegateStarted; //// internal ManualResetEvent CompletionEvent; //// internal ConsoleCancelEventHandler CancelCallbacks; //// internal ControlCDelegateData( ConsoleSpecialKey controlKey, ConsoleCancelEventHandler cancelCallbacks ) //// { //// this.ControlKey = controlKey; //// this.CancelCallbacks = cancelCallbacks; //// this.CompletionEvent = new ManualResetEvent( false ); //// // this.Cancel defaults to false //// // this.DelegateStarted defaults to false //// } //// } //// //// // Returns true if we've "handled" the break request, false if //// // we want to terminate the process (or at least let the next //// // control handler function have a chance). //// private static bool BreakEvent( int controlType ) //// { //// //// // The thread that this gets called back on has a very small stack on 64 bit systems. There is //// // not enough space to handle a managed exception being caught and thrown. So, queue up a work //// // item on another thread for the actual event callback. //// //// if(controlType == Win32Native.CTRL_C_EVENT || //// controlType == Win32Native.CTRL_BREAK_EVENT) //// { //// //// // To avoid race between remove handler and raising the event //// ConsoleCancelEventHandler cancelCallbacks = Console._cancelCallbacks; //// if(cancelCallbacks == null) //// { //// return false; //// } //// //// // Create the delegate //// ConsoleSpecialKey controlKey = (controlType == 0) ? ConsoleSpecialKey.ControlC : ConsoleSpecialKey.ControlBreak; //// ControlCDelegateData delegateData = new ControlCDelegateData( controlKey, cancelCallbacks ); //// WaitCallback controlCCallback = new WaitCallback( ControlCDelegate ); //// //// // Queue the delegate //// if(!ThreadPool.QueueUserWorkItem( controlCCallback, delegateData )) //// { //// BCLDebug.Assert( false, "ThreadPool.QueueUserWorkItem returned false without throwing. Unable to execute ControlC handler" ); //// return false; //// } //// // Block until the delegate is done. We need to be robust in the face of the work item not executing //// // but we also want to get control back immediately after it is done and we don't want to give the //// // handler a fixed time limit in case it needs to display UI. Wait on the event twice, once with a //// // timout and a second time without if we are sure that the handler actually started. //// TimeSpan controlCWaitTime = new TimeSpan( 0, 0, 30 ); // 30 seconds //// delegateData.CompletionEvent.WaitOne( controlCWaitTime, false ); //// if(!delegateData.DelegateStarted) //// { //// BCLDebug.Assert( false, "ThreadPool.QueueUserWorkItem did not execute the handler within 30 seconds." ); //// return false; //// } //// delegateData.CompletionEvent.WaitOne(); //// delegateData.CompletionEvent.Close(); //// return delegateData.Cancel; //// //// } //// return false; //// } //// //// // This is the worker delegate that is called on the Threadpool thread to fire the actual events. It must guarentee that it //// // signals the caller on the ControlC thread so that it does not block indefinitely. //// private static void ControlCDelegate( object data ) //// { //// ControlCDelegateData controlCData = (ControlCDelegateData)data; //// try //// { //// controlCData.DelegateStarted = true; //// ConsoleCancelEventArgs args = new ConsoleCancelEventArgs( controlCData.ControlKey ); //// controlCData.CancelCallbacks( null, args ); //// controlCData.Cancel = args.Cancel; //// } //// finally //// { //// controlCData.CompletionEvent.Set(); //// } //// } //// //// // Note: hooking this event allows you to prevent Control-C from //// // killing a console app, which is somewhat surprising for users. //// // Some permission seems appropriate. We chose UI permission for lack //// // of a better one. However, we also applied host protection //// // permission here as well, for self-affecting process management. //// // This allows hosts to prevent people from adding a handler for //// // this event. //// public static event ConsoleCancelEventHandler CancelKeyPress //// { //// [ResourceExposure( ResourceScope.Process )] //// [ResourceConsumption( ResourceScope.Process )] //// add //// { //// new UIPermission( UIPermissionWindow.SafeTopLevelWindows ).Demand(); //// //// lock(InternalSyncObject) //// { //// // Add this delegate to the pile. //// _cancelCallbacks += value; //// //// // If we haven't registered our control-C handler, do it. //// if(_hooker == null) //// { //// _hooker = new ControlCHooker(); //// _hooker.Hook(); //// } //// } //// } //// [ResourceExposure( ResourceScope.Process )] //// [ResourceConsumption( ResourceScope.Process )] //// remove //// { //// new UIPermission( UIPermissionWindow.SafeTopLevelWindows ).Demand(); //// //// lock(InternalSyncObject) //// { //// // If count was 0, call SetConsoleCtrlEvent to remove cb. //// _cancelCallbacks -= value; //// BCLDebug.Assert( _cancelCallbacks == null || _cancelCallbacks.GetInvocationList().Length > 0, "Teach Console::CancelKeyPress to handle a non-null but empty list of callbacks" ); //// if(_hooker != null && _cancelCallbacks == null) //// _hooker.Unhook(); //// } //// } //// } //// //// [HostProtection( UI = true )] //// [ResourceExposure( ResourceScope.Process )] //// [ResourceConsumption( ResourceScope.Process )] //// public static Stream OpenStandardError() //// { //// return OpenStandardError( _DefaultConsoleBufferSize ); //// } //// //// [HostProtection( UI = true )] //// [ResourceExposure( ResourceScope.Process )] //// [ResourceConsumption( ResourceScope.Process )] //// public static Stream OpenStandardError( int bufferSize ) //// { //// if(bufferSize < 0) //// throw new ArgumentOutOfRangeException( "bufferSize", Environment.GetResourceString( "ArgumentOutOfRange_NeedNonNegNum" ) ); //// return GetStandardFile( Win32Native.STD_ERROR_HANDLE, //// FileAccess.Write, bufferSize ); //// } //// //// [HostProtection( UI = true )] //// [ResourceExposure( ResourceScope.Process )] //// [ResourceConsumption( ResourceScope.Process )] //// public static Stream OpenStandardInput() //// { //// return OpenStandardInput( _DefaultConsoleBufferSize ); //// } //// //// [HostProtection( UI = true )] //// [ResourceExposure( ResourceScope.Process )] //// [ResourceConsumption( ResourceScope.Process )] //// public static Stream OpenStandardInput( int bufferSize ) //// { //// if(bufferSize < 0) //// throw new ArgumentOutOfRangeException( "bufferSize", Environment.GetResourceString( "ArgumentOutOfRange_NeedNonNegNum" ) ); //// return GetStandardFile( Win32Native.STD_INPUT_HANDLE, //// FileAccess.Read, bufferSize ); //// } //// //// [HostProtection( UI = true )] //// [ResourceExposure( ResourceScope.Process )] //// [ResourceConsumption( ResourceScope.Process )] //// public static Stream OpenStandardOutput() //// { //// return OpenStandardOutput( _DefaultConsoleBufferSize ); //// } //// //// [HostProtection( UI = true )] //// [ResourceExposure( ResourceScope.Process )] //// [ResourceConsumption( ResourceScope.Process )] //// public static Stream OpenStandardOutput( int bufferSize ) //// { //// if(bufferSize < 0) //// throw new ArgumentOutOfRangeException( "bufferSize", Environment.GetResourceString( "ArgumentOutOfRange_NeedNonNegNum" ) ); //// return GetStandardFile( Win32Native.STD_OUTPUT_HANDLE, //// FileAccess.Write, bufferSize ); //// } //// //// [HostProtection( UI = true )] //// [ResourceExposure( ResourceScope.AppDomain )] //// public static void SetIn( TextReader newIn ) //// { //// if(newIn == null) //// throw new ArgumentNullException( "newIn" ); //// new SecurityPermission( SecurityPermissionFlag.UnmanagedCode ).Demand(); //// //// newIn = TextReader.Synchronized( newIn ); //// lock(InternalSyncObject) //// { //// _in = newIn; //// } //// } //// //// [HostProtection( UI = true )] //// [ResourceExposure( ResourceScope.AppDomain )] //// public static void SetOut( TextWriter newOut ) //// { //// if(newOut == null) //// throw new ArgumentNullException( "newOut" ); //// new SecurityPermission( SecurityPermissionFlag.UnmanagedCode ).Demand(); //// //// _wasOutRedirected = true; //// newOut = TextWriter.Synchronized( newOut ); //// lock(InternalSyncObject) //// { //// _out = newOut; //// } //// } //// //// [HostProtection( UI = true )] //// [ResourceExposure( ResourceScope.AppDomain )] //// public static void SetError( TextWriter newError ) //// { //// if(newError == null) //// throw new ArgumentNullException( "newError" ); //// new SecurityPermission( SecurityPermissionFlag.UnmanagedCode ).Demand(); //// //// _wasErrorRedirected = true; //// newError = TextWriter.Synchronized( newError ); //// lock(InternalSyncObject) //// { //// _error = newError; //// } //// } //// //// [HostProtection( UI = true )] //// public static int Read() //// { //// return In.Read(); //// } //// //// [HostProtection( UI = true )] //// public static String ReadLine() //// { //// return In.ReadLine(); //// } [HostProtection( UI = true )] [MethodImpl( MethodImplOptions.InternalCall )] public static extern void WriteLine(); //// { //// Out.WriteLine(); //// } //// [HostProtection( UI = true )] //// public static void WriteLine( bool value ) //// { //// Out.WriteLine( value ); //// } //// //// [HostProtection( UI = true )] //// public static void WriteLine( char value ) //// { //// Out.WriteLine( value ); //// } //// //// [HostProtection( UI = true )] //// public static void WriteLine( char[] buffer ) //// { //// Out.WriteLine( buffer ); //// } //// //// [HostProtection( UI = true )] //// public static void WriteLine( char[] buffer, int index, int count ) //// { //// Out.WriteLine( buffer, index, count ); //// } //// //// [HostProtection( UI = true )] //// public static void WriteLine( decimal value ) //// { //// Out.WriteLine( value ); //// } [HostProtection( UI = true )] [MethodImpl( MethodImplOptions.InternalCall )] public extern static void WriteLine( double value ); //// { //// Out.WriteLine( value ); //// } //// //// [HostProtection( UI = true )] //// public static void WriteLine( float value ) //// { //// Out.WriteLine( value ); //// } [HostProtection( UI = true )] [MethodImpl( MethodImplOptions.InternalCall )] public extern static void WriteLine( int value ); //// { //// Out.WriteLine( value ); //// } //// //// [HostProtection( UI = true )] //// [CLSCompliant( false )] //// public static void WriteLine( uint value ) //// { //// Out.WriteLine( value ); //// } //// //// [HostProtection( UI = true )] //// public static void WriteLine( long value ) //// { //// Out.WriteLine( value ); //// } //// //// [HostProtection( UI = true )] //// [CLSCompliant( false )] //// public static void WriteLine( ulong value ) //// { //// Out.WriteLine( value ); //// } [HostProtection( UI = true )] [MethodImpl( MethodImplOptions.InternalCall )] public extern static void WriteLine( Object value ); //// { //// Out.WriteLine( value ); //// } [HostProtection( UI = true )] [MethodImpl( MethodImplOptions.InternalCall )] public static extern void WriteLine( String value ); //// { //// Out.WriteLine( value ); //// } [HostProtection( UI = true )] [MethodImpl( MethodImplOptions.InternalCall )] public static extern void WriteLine( String format, Object arg0 ); //// { //// Out.WriteLine( format, arg0 ); //// } [HostProtection( UI = true )] [MethodImpl( MethodImplOptions.InternalCall )] public static extern void WriteLine( String format, Object arg0, Object arg1 ); //// { //// Out.WriteLine( format, arg0, arg1 ); //// } [HostProtection( UI = true )] [MethodImpl( MethodImplOptions.InternalCall )] public static extern void WriteLine( String format, Object arg0, Object arg1, Object arg2 ); //// { //// Out.WriteLine( format, arg0, arg1, arg2 ); //// } //// [HostProtection( UI = true )] //// [CLSCompliant( false )] //// public static void WriteLine( String format, Object arg0, Object arg1, Object arg2, Object arg3, __arglist ) //// { //// Object[] objArgs; //// int argCount; //// //// ArgIterator args = new ArgIterator( __arglist ); //// //// //+4 to account for the 4 hard-coded arguments at the beginning of the list. //// argCount = args.GetRemainingCount() + 4; //// //// objArgs = new Object[argCount]; //// //// //Handle the hard-coded arguments //// objArgs[0] = arg0; //// objArgs[1] = arg1; //// objArgs[2] = arg2; //// objArgs[3] = arg3; //// //// //Walk all of the args in the variable part of the argument list. //// for(int i = 4; i < argCount; i++) //// { //// objArgs[i] = TypedReference.ToObject( args.GetNextArg() ); //// } //// //// Out.WriteLine( format, objArgs ); //// } [HostProtection( UI = true )] [MethodImpl( MethodImplOptions.InternalCall )] public static extern void WriteLine( String format, params Object[] arg ); //// { //// Out.WriteLine( format, arg ); //// } //// [HostProtection( UI = true )] //// public static void Write( String format, Object arg0 ) //// { //// Out.Write( format, arg0 ); //// } //// //// [HostProtection( UI = true )] //// public static void Write( String format, Object arg0, Object arg1 ) //// { //// Out.Write( format, arg0, arg1 ); //// } //// //// [HostProtection( UI = true )] //// public static void Write( String format, Object arg0, Object arg1, Object arg2 ) //// { //// Out.Write( format, arg0, arg1, arg2 ); //// } //// //// [HostProtection( UI = true )] //// [CLSCompliant( false )] //// public static void Write( String format, Object arg0, Object arg1, Object arg2, Object arg3, __arglist ) //// { //// Object[] objArgs; //// int argCount; //// //// ArgIterator args = new ArgIterator( __arglist ); //// //// //+4 to account for the 4 hard-coded arguments at the beginning of the list. //// argCount = args.GetRemainingCount() + 4; //// //// objArgs = new Object[argCount]; //// //// //Handle the hard-coded arguments //// objArgs[0] = arg0; //// objArgs[1] = arg1; //// objArgs[2] = arg2; //// objArgs[3] = arg3; //// //// //Walk all of the args in the variable part of the argument list. //// for(int i = 4; i < argCount; i++) //// { //// objArgs[i] = TypedReference.ToObject( args.GetNextArg() ); //// } //// //// Out.Write( format, objArgs ); //// } //// //// //// [HostProtection( UI = true )] //// public static void Write( String format, params Object[] arg ) //// { //// Out.Write( format, arg ); //// } //// //// [HostProtection( UI = true )] //// public static void Write( bool value ) //// { //// Out.Write( value ); //// } //// //// [HostProtection( UI = true )] //// public static void Write( char value ) //// { //// Out.Write( value ); //// } //// //// [HostProtection( UI = true )] //// public static void Write( char[] buffer ) //// { //// Out.Write( buffer ); //// } //// //// [HostProtection( UI = true )] //// public static void Write( char[] buffer, int index, int count ) //// { //// Out.Write( buffer, index, count ); //// } //// //// [HostProtection( UI = true )] //// public static void Write( double value ) //// { //// Out.Write( value ); //// } //// //// [HostProtection( UI = true )] //// public static void Write( decimal value ) //// { //// Out.Write( value ); //// } //// //// [HostProtection( UI = true )] //// public static void Write( float value ) //// { //// Out.Write( value ); //// } //// //// [HostProtection( UI = true )] //// public static void Write( int value ) //// { //// Out.Write( value ); //// } //// //// [HostProtection( UI = true )] //// [CLSCompliant( false )] //// public static void Write( uint value ) //// { //// Out.Write( value ); //// } //// //// [HostProtection( UI = true )] //// public static void Write( long value ) //// { //// Out.Write( value ); //// } //// //// [HostProtection( UI = true )] //// [CLSCompliant( false )] //// public static void Write( ulong value ) //// { //// Out.Write( value ); //// } //// //// [HostProtection( UI = true )] //// public static void Write( Object value ) //// { //// Out.Write( value ); //// } //// //// [HostProtection( UI = true )] //// public static void Write( String value ) //// { //// Out.Write( value ); //// } //// //// // Checks whether stdout or stderr are writable. Do NOT pass //// // stdin here. //// [ResourceExposure( ResourceScope.Process )] //// [ResourceConsumption( ResourceScope.Process )] //// private static unsafe bool ConsoleHandleIsValid( SafeFileHandle handle ) //// { //// // Do NOT call this method on stdin! //// //// // Windows apps may have non-null valid looking handle values for //// // stdin, stdout and stderr, but they may not be readable or //// // writable. Verify this by calling ReadFile & WriteFile in the //// // appropriate modes. //// // This must handle console-less Windows apps. //// if(handle.IsInvalid) //// return false; // WinCE would return here, if we ran on CE. //// //// int bytesWritten; //// byte junkByte = 0x41; //// int r; //// r = __ConsoleStream.WriteFile( handle, &junkByte, 0, out bytesWritten, IntPtr.Zero ); //// // In Win32 apps w/ no console, bResult should be 0 for failure. //// return r != 0; //// } } } ================================================ FILE: Zelig/Zelig/RunTime/Framework/mscorlib/System/ConsoleColor.cs ================================================ // ==++== // // Copyright (c) Microsoft Corporation. All rights reserved. // // ==--== /*============================================================================= ** ** Class: ConsoleColor ** ** ** Purpose: This enumeration represents the colors that can be used for ** console text foreground and background colors. ** ** =============================================================================*/ namespace System { [Serializable] public enum ConsoleColor { Black = 0, DarkBlue = 1, DarkGreen = 2, DarkCyan = 3, DarkRed = 4, DarkMagenta = 5, DarkYellow = 6, Gray = 7, DarkGray = 8, Blue = 9, Green = 10, Cyan = 11, Red = 12, Magenta = 13, Yellow = 14, White = 15, } } ================================================ FILE: Zelig/Zelig/RunTime/Framework/mscorlib/System/Convert.cs ================================================ // ==++== // // Copyright (c) Microsoft Corporation. All rights reserved. // // ==--== /*============================================================ ** ** Class: Convert ** ** ** Purpose: Home for static conversion methods. ** ** ===========================================================*/ namespace System { using System; using System.Globalization; using System.Threading; using System.Reflection; using System.Runtime.CompilerServices; ////using System.Runtime.Versioning; // Returns the type code of this object. An implementation of this method // must not return TypeCode.Empty (which represents a null reference) or // TypeCode.Object (which represents an object that doesn't implement the // IConvertible interface). An implementation of this method should return // TypeCode.DBNull if the value of this object is a database null. For // example, a nullable integer type should return TypeCode.DBNull if the // value of the object is the database null. Otherwise, an implementation // of this method should return the TypeCode that best describes the // internal representation of the object. // The Value class provides conversion and querying methods for values. The // Value class contains static members only, and it is not possible to create // instances of the class. // // The statically typed conversion methods provided by the Value class are all // of the form: // // public static XXX ToXXX(YYY value) // // where XXX is the target type and YYY is the source type. The matrix below // shows the set of supported conversions. The set of conversions is symmetric // such that for every ToXXX(YYY) there is also a ToYYY(XXX). // // From: To: Bol Chr SBy Byt I16 U16 I32 U32 I64 U64 Sgl Dbl Dec Dat Str // ---------------------------------------------------------------------- // Boolean x x x x x x x x x x x x x // Char x x x x x x x x x x // SByte x x x x x x x x x x x x x x // Byte x x x x x x x x x x x x x x // Int16 x x x x x x x x x x x x x x // UInt16 x x x x x x x x x x x x x x // Int32 x x x x x x x x x x x x x x // UInt32 x x x x x x x x x x x x x x // Int64 x x x x x x x x x x x x x x // UInt64 x x x x x x x x x x x x x x // Single x x x x x x x x x x x x x // Double x x x x x x x x x x x x x // Decimal x x x x x x x x x x x x x // DateTime x x // String x x x x x x x x x x x x x x x // ---------------------------------------------------------------------- // // For dynamic conversions, the Value class provides a set of methods of the // form: // // public static XXX ToXXX(object value) // // where XXX is the target type (Boolean, Char, SByte, Byte, Int16, UInt16, // Int32, UInt32, Int64, UInt64, Single, Double, Decimal, DateTime, // or String). The implementations of these methods all take the form: // // public static XXX toXXX(object value) { // return value == null? XXX.Default: ((IConvertible)value).ToXXX(); // } // // The code first checks if the given value is a null reference (which is the // same as Value.Empty), in which case it returns the default value for type // XXX. Otherwise, a cast to IConvertible is performed, and the appropriate ToXXX() // method is invoked on the object. An InvalidCastException is thrown if the // cast to IConvertible fails, and that exception is simply allowed to propagate out // of the conversion method. // Constant representing the database null value. This value is used in // database applications to indicate the absense of a known value. Note // that Value.DBNull is NOT the same as a null object reference, which is // represented by Value.Empty. // // The Equals() method of DBNull always returns false, even when the // argument is itself DBNull. // // When passed Value.DBNull, the Value.GetTypeCode() method returns // TypeCode.DBNull. // // When passed Value.DBNull, the Value.ToXXX() methods all throw an // InvalidCastException. public static class Convert { //A typeof operation is fairly expensive (does a system call), so we'll cache these here //statically. These are exactly lined up with the TypeCode, eg. ConvertType[TypeCode.Int16] //will give you the type of an Int16. internal static readonly Type[] ConvertTypes = { typeof(System.Empty), typeof(Object), typeof(System.DBNull), typeof(Boolean), typeof(Char), typeof(SByte), typeof(Byte), typeof(Int16), typeof(UInt16), typeof(Int32), typeof(UInt32), typeof(Int64), typeof(UInt64), typeof(Single), typeof(Double), typeof(Decimal), typeof(DateTime), typeof(Object), //TypeCode is discontinuous so we need a placeholder. typeof(String) }; internal static readonly char[] base64Table = {'A','B','C','D','E','F','G','H','I','J','K','L','M','N','O', 'P','Q','R','S','T','U','V','W','X','Y','Z','a','b','c','d', 'e','f','g','h','i','j','k','l','m','n','o','p','q','r','s', 't','u','v','w','x','y','z','0','1','2','3','4','5','6','7', '8','9','+','/','=' }; #if _DEBUG static Convert() { BCLDebug.Assert(ConvertTypes!=null, "[Convert.cctor]ConvertTypes!=null"); BCLDebug.Assert(ConvertTypes.Length == ((int)TypeCode.String + 1), "[Convert.cctor]ConvertTypes.Length == ((int)TypeCode.String + 1)"); BCLDebug.Assert(ConvertTypes[(int)TypeCode.Empty]==typeof(System.Empty), "[Convert.cctor]ConvertTypes[(int)TypeCode.Empty]==typeof(System.Empty)"); BCLDebug.Assert(ConvertTypes[(int)TypeCode.String]==typeof(String), "[Convert.cctor]ConvertTypes[(int)TypeCode.String]==typeof(System.String)"); BCLDebug.Assert(ConvertTypes[(int)TypeCode.Int32]==typeof(int), "[Convert.cctor]ConvertTypes[(int)TypeCode.Int32]==typeof(int)"); } #endif public static readonly Object DBNull = System.DBNull.Value; // Returns the type code for the given object. If the argument is null, // the result is TypeCode.Empty. If the argument is not a value (i.e. if // the object does not implement IConvertible), the result is TypeCode.Object. // Otherwise, the result is the type code of the object, as determined by // the object's implementation of IConvertible. public static TypeCode GetTypeCode( object value ) { if(value == null) return TypeCode.Empty; IConvertible temp = value as IConvertible; if(temp != null) { return temp.GetTypeCode(); } return TypeCode.Object; } // Returns true if the given object is a database null. This operation // corresponds to "value.GetTypeCode() == TypeCode.DBNull". public static bool IsDBNull( object value ) { if(value == System.DBNull.Value) return true; IConvertible convertible = value as IConvertible; return convertible != null ? convertible.GetTypeCode() == TypeCode.DBNull : false; } // Converts the given object to the given type. In general, this method is // equivalent to calling the Value.ToXXX(value) method for the given // typeCode and boxing the result. // // The method first checks if the given object implements IConvertible. If not, // the only permitted conversion is from a null to TypeCode.Empty, the // result of which is null. // // If the object does implement IConvertible, a check is made to see if the // object already has the given type code, in which case the object is // simply returned. Otherwise, the appropriate ToXXX() is invoked on the // object's implementation of IConvertible. public static Object ChangeType( Object value, TypeCode typeCode ) { return ChangeType( value, typeCode, Thread.CurrentThread.CurrentCulture ); } public static Object ChangeType( Object value, TypeCode typeCode, IFormatProvider provider ) { if(value == null && (typeCode == TypeCode.Empty || typeCode == TypeCode.String || typeCode == TypeCode.Object)) { return null; } IConvertible v = value as IConvertible; if(v == null) { #if EXCEPTION_STRINGS throw new InvalidCastException( Environment.GetResourceString( "InvalidCast_IConvertible" ) ); #else throw new InvalidCastException(); #endif } // This line is invalid for things like Enums that return a TypeCode // of Int32, but the object can't actually be cast to an Int32. // if (v.GetTypeCode() == typeCode) return value; switch(typeCode) { case TypeCode.Boolean: return v.ToBoolean( provider ); case TypeCode.Char: return v.ToChar( provider ); case TypeCode.SByte: return v.ToSByte( provider ); case TypeCode.Byte: return v.ToByte( provider ); case TypeCode.Int16: return v.ToInt16( provider ); case TypeCode.UInt16: return v.ToUInt16( provider ); case TypeCode.Int32: return v.ToInt32( provider ); case TypeCode.UInt32: return v.ToUInt32( provider ); case TypeCode.Int64: return v.ToInt64( provider ); case TypeCode.UInt64: return v.ToUInt64( provider ); case TypeCode.Single: return v.ToSingle( provider ); case TypeCode.Double: return v.ToDouble( provider ); case TypeCode.Decimal: return v.ToDecimal( provider ); case TypeCode.DateTime: return v.ToDateTime( provider ); case TypeCode.String: return v.ToString( provider ); case TypeCode.Object: return value; case TypeCode.DBNull: #if EXCEPTION_STRINGS throw new InvalidCastException( Environment.GetResourceString( "InvalidCast_DBNull" ) ); #else throw new InvalidCastException(); #endif case TypeCode.Empty: #if EXCEPTION_STRINGS throw new InvalidCastException( Environment.GetResourceString( "InvalidCast_Empty" ) ); #else throw new InvalidCastException(); #endif default: #if EXCEPTION_STRINGS throw new ArgumentException( Environment.GetResourceString( "Arg_UnknownTypeCode" ) ); #else throw new ArgumentException(); #endif } } internal static Object DefaultToType( IConvertible value, Type targetType, IFormatProvider provider ) { BCLDebug.Assert( value != null, "[Convert.DefaultToType]value!=null" ); if(targetType == null) { #if EXCEPTION_STRINGS throw new ArgumentNullException( "targetType" ); #else throw new ArgumentNullException(); #endif } if(value.GetType() == targetType) { return value; } if(targetType == ConvertTypes[(int)TypeCode.Boolean]) return value.ToBoolean( provider ); if(targetType == ConvertTypes[(int)TypeCode.Char]) return value.ToChar( provider ); if(targetType == ConvertTypes[(int)TypeCode.SByte]) return value.ToSByte( provider ); if(targetType == ConvertTypes[(int)TypeCode.Byte]) return value.ToByte( provider ); if(targetType == ConvertTypes[(int)TypeCode.Int16]) return value.ToInt16( provider ); if(targetType == ConvertTypes[(int)TypeCode.UInt16]) return value.ToUInt16( provider ); if(targetType == ConvertTypes[(int)TypeCode.Int32]) return value.ToInt32( provider ); if(targetType == ConvertTypes[(int)TypeCode.UInt32]) return value.ToUInt32( provider ); if(targetType == ConvertTypes[(int)TypeCode.Int64]) return value.ToInt64( provider ); if(targetType == ConvertTypes[(int)TypeCode.UInt64]) return value.ToUInt64( provider ); if(targetType == ConvertTypes[(int)TypeCode.Single]) return value.ToSingle( provider ); if(targetType == ConvertTypes[(int)TypeCode.Double]) return value.ToDouble( provider ); if(targetType == ConvertTypes[(int)TypeCode.Decimal]) return value.ToDecimal( provider ); if(targetType == ConvertTypes[(int)TypeCode.DateTime]) return value.ToDateTime( provider ); if(targetType == ConvertTypes[(int)TypeCode.String]) { return value.ToString( provider ); } if(targetType == ConvertTypes[(int)TypeCode.Object]) return (Object)value; if(targetType == ConvertTypes[(int)TypeCode.DBNull]) { #if EXCEPTION_STRINGS throw new InvalidCastException( Environment.GetResourceString( "InvalidCast_DBNull" ) ); #else throw new InvalidCastException(); #endif } if(targetType == ConvertTypes[(int)TypeCode.Empty]) { #if EXCEPTION_STRINGS throw new InvalidCastException( Environment.GetResourceString( "InvalidCast_Empty" ) ); #else throw new InvalidCastException(); #endif } #if EXCEPTION_STRINGS throw new InvalidCastException( String.Format( CultureInfo.CurrentCulture, Environment.GetResourceString( "InvalidCast_FromTo" ), value.GetType().FullName, targetType.FullName ) ); #else throw new InvalidCastException(); #endif } public static Object ChangeType( Object value, Type conversionType ) { return ChangeType( value, conversionType, Thread.CurrentThread.CurrentCulture ); } public static Object ChangeType( Object value, Type conversionType, IFormatProvider provider ) { if(conversionType == null) { #if EXCEPTION_STRINGS throw new ArgumentNullException( "conversionType" ); #else throw new ArgumentNullException(); #endif } if(value == null) { if(conversionType.IsValueType) { #if EXCEPTION_STRINGS throw new InvalidCastException( Environment.GetResourceString( "InvalidCast_CannotCastNullToValueType" ) ); #else throw new InvalidCastException(); #endif } return null; } IConvertible ic = value as IConvertible; if(ic == null) { if(value.GetType() == conversionType) { return value; } #if EXCEPTION_STRINGS throw new InvalidCastException( Environment.GetResourceString( "InvalidCast_IConvertible" ) ); #else throw new InvalidCastException(); #endif } if(conversionType == ConvertTypes[(int)TypeCode.Boolean]) return ic.ToBoolean( provider ); if(conversionType == ConvertTypes[(int)TypeCode.Char]) return ic.ToChar( provider ); if(conversionType == ConvertTypes[(int)TypeCode.SByte]) return ic.ToSByte( provider ); if(conversionType == ConvertTypes[(int)TypeCode.Byte]) return ic.ToByte( provider ); if(conversionType == ConvertTypes[(int)TypeCode.Int16]) return ic.ToInt16( provider ); if(conversionType == ConvertTypes[(int)TypeCode.UInt16]) return ic.ToUInt16( provider ); if(conversionType == ConvertTypes[(int)TypeCode.Int32]) return ic.ToInt32( provider ); if(conversionType == ConvertTypes[(int)TypeCode.UInt32]) return ic.ToUInt32( provider ); if(conversionType == ConvertTypes[(int)TypeCode.Int64]) return ic.ToInt64( provider ); if(conversionType == ConvertTypes[(int)TypeCode.UInt64]) return ic.ToUInt64( provider ); if(conversionType == ConvertTypes[(int)TypeCode.Single]) return ic.ToSingle( provider ); if(conversionType == ConvertTypes[(int)TypeCode.Double]) return ic.ToDouble( provider ); if(conversionType == ConvertTypes[(int)TypeCode.Decimal]) return ic.ToDecimal( provider ); if(conversionType == ConvertTypes[(int)TypeCode.DateTime]) return ic.ToDateTime( provider ); if(conversionType == ConvertTypes[(int)TypeCode.String]) { return ic.ToString( provider ); } if(conversionType == ConvertTypes[(int)TypeCode.Object]) return (Object)value; return ic.ToType( conversionType, provider ); } // Conversions to Boolean public static bool ToBoolean( Object value ) { return value == null ? false : ((IConvertible)value).ToBoolean( null ); } public static bool ToBoolean( Object value, IFormatProvider provider ) { return value == null ? false : ((IConvertible)value).ToBoolean( provider ); } public static bool ToBoolean( bool value ) { return value; } [CLSCompliant( false )] public static bool ToBoolean( sbyte value ) { return value != 0; } // To be consistent with IConvertible in the base data types else we get different semantics // with widening operations. Without this operator this widen succeeds,with this API the widening throws. public static bool ToBoolean( char value ) { return ((IConvertible)value).ToBoolean( null ); } public static bool ToBoolean( byte value ) { return value != 0; } public static bool ToBoolean( short value ) { return value != 0; } [CLSCompliant( false )] public static bool ToBoolean( ushort value ) { return value != 0; } public static bool ToBoolean( int value ) { return value != 0; } [CLSCompliant( false )] public static bool ToBoolean( uint value ) { return value != 0; } public static bool ToBoolean( long value ) { return value != 0; } [CLSCompliant( false )] public static bool ToBoolean( ulong value ) { return value != 0; } public static bool ToBoolean( String value ) { if(value == null) return false; return Boolean.Parse( value ); } public static bool ToBoolean( String value, IFormatProvider provider ) { if(value == null) return false; return Boolean.Parse( value ); } public static bool ToBoolean( float value ) { return value != 0; } public static bool ToBoolean( double value ) { return value != 0; } public static bool ToBoolean( decimal value ) { return value != 0; } public static bool ToBoolean( DateTime value ) { return ((IConvertible)value).ToBoolean( null ); } // Disallowed conversions to Boolean // public static bool ToBoolean(TimeSpan value) // Conversions to Char public static char ToChar( object value ) { return value == null ? (char)0 : ((IConvertible)value).ToChar( null ); } public static char ToChar( object value, IFormatProvider provider ) { return value == null ? (char)0 : ((IConvertible)value).ToChar( provider ); } public static char ToChar( bool value ) { return ((IConvertible)value).ToChar( null ); } public static char ToChar( char value ) { return value; } [CLSCompliant( false )] public static char ToChar( sbyte value ) { if(value < 0) { #if EXCEPTION_STRINGS throw new OverflowException( Environment.GetResourceString( "Overflow_Char" ) ); #else throw new OverflowException(); #endif } return (char)value; } public static char ToChar( byte value ) { return (char)value; } public static char ToChar( short value ) { if(value < 0) { #if EXCEPTION_STRINGS throw new OverflowException( Environment.GetResourceString( "Overflow_Char" ) ); #else throw new OverflowException(); #endif } return (char)value; } [CLSCompliant( false )] public static char ToChar( ushort value ) { return (char)value; } public static char ToChar( int value ) { if(value < 0 || value > Char.MaxValue) { #if EXCEPTION_STRINGS throw new OverflowException( Environment.GetResourceString( "Overflow_Char" ) ); #else throw new OverflowException(); #endif } return (char)value; } [CLSCompliant( false )] public static char ToChar( uint value ) { if(value > Char.MaxValue) { #if EXCEPTION_STRINGS throw new OverflowException( Environment.GetResourceString( "Overflow_Char" ) ); #else throw new OverflowException(); #endif } return (char)value; } public static char ToChar( long value ) { if(value < 0 || value > Char.MaxValue) { #if EXCEPTION_STRINGS throw new OverflowException( Environment.GetResourceString( "Overflow_Char" ) ); #else throw new OverflowException(); #endif } return (char)value; } [CLSCompliant( false )] public static char ToChar( ulong value ) { if(value > Char.MaxValue) { #if EXCEPTION_STRINGS throw new OverflowException( Environment.GetResourceString( "Overflow_Char" ) ); #else throw new OverflowException(); #endif } return (char)value; } // // @VariantSwitch // Remove FormatExceptions; // public static char ToChar( String value ) { return ToChar( value, null ); } public static char ToChar( String value, IFormatProvider provider ) { if(value == null) #if EXCEPTION_STRINGS throw new ArgumentNullException( "value" ); #else throw new ArgumentNullException(); #endif if(value.Length != 1) #if EXCEPTION_STRINGS throw new FormatException( Environment.GetResourceString( "Format_NeedSingleChar" ) ); #else throw new FormatException(); #endif return value[0]; } // To be consistent with IConvertible in the base data types else we get different semantics // with widening operations. Without this operator this widen succeeds,with this API the widening throws. public static char ToChar( float value ) { return ((IConvertible)value).ToChar( null ); } // To be consistent with IConvertible in the base data types else we get different semantics // with widening operations. Without this operator this widen succeeds,with this API the widening throws. public static char ToChar( double value ) { return ((IConvertible)value).ToChar( null ); } // To be consistent with IConvertible in the base data types else we get different semantics // with widening operations. Without this operator this widen succeeds,with this API the widening throws. public static char ToChar( decimal value ) { return ((IConvertible)value).ToChar( null ); } public static char ToChar( DateTime value ) { return ((IConvertible)value).ToChar( null ); } // Disallowed conversions to Char // public static char ToChar(TimeSpan value) // Conversions to SByte [CLSCompliant( false )] public static sbyte ToSByte( object value ) { return value == null ? (sbyte)0 : ((IConvertible)value).ToSByte( null ); } [CLSCompliant( false )] public static sbyte ToSByte( object value, IFormatProvider provider ) { return value == null ? (sbyte)0 : ((IConvertible)value).ToSByte( provider ); } [CLSCompliant( false )] public static sbyte ToSByte( bool value ) { return value ? (sbyte)Boolean.True : (sbyte)Boolean.False; } [CLSCompliant( false )] public static sbyte ToSByte( sbyte value ) { return value; } [CLSCompliant( false )] public static sbyte ToSByte( char value ) { if(value > SByte.MaxValue) { #if EXCEPTION_STRINGS throw new OverflowException( Environment.GetResourceString( "Overflow_SByte" ) ); #else throw new OverflowException(); #endif } return (sbyte)value; } [CLSCompliant( false )] public static sbyte ToSByte( byte value ) { if(value > SByte.MaxValue) { #if EXCEPTION_STRINGS throw new OverflowException( Environment.GetResourceString( "Overflow_SByte" ) ); #else throw new OverflowException(); #endif } return (sbyte)value; } [CLSCompliant( false )] public static sbyte ToSByte( short value ) { if(value < SByte.MinValue || value > SByte.MaxValue) { #if EXCEPTION_STRINGS throw new OverflowException( Environment.GetResourceString( "Overflow_SByte" ) ); #else throw new OverflowException(); #endif } return (sbyte)value; } [CLSCompliant( false )] public static sbyte ToSByte( ushort value ) { if(value > SByte.MaxValue) { #if EXCEPTION_STRINGS throw new OverflowException( Environment.GetResourceString( "Overflow_SByte" ) ); #else throw new OverflowException(); #endif } return (sbyte)value; } [CLSCompliant( false )] public static sbyte ToSByte( int value ) { if(value < SByte.MinValue || value > SByte.MaxValue) { #if EXCEPTION_STRINGS throw new OverflowException( Environment.GetResourceString( "Overflow_SByte" ) ); #else throw new OverflowException(); #endif } return (sbyte)value; } [CLSCompliant( false )] public static sbyte ToSByte( uint value ) { if(value > SByte.MaxValue) { #if EXCEPTION_STRINGS throw new OverflowException( Environment.GetResourceString( "Overflow_SByte" ) ); #else throw new OverflowException(); #endif } return (sbyte)value; } [CLSCompliant( false )] public static sbyte ToSByte( long value ) { if(value < SByte.MinValue || value > SByte.MaxValue) { #if EXCEPTION_STRINGS throw new OverflowException( Environment.GetResourceString( "Overflow_SByte" ) ); #else throw new OverflowException(); #endif } return (sbyte)value; } [CLSCompliant( false )] public static sbyte ToSByte( ulong value ) { if(value > (ulong)SByte.MaxValue) { #if EXCEPTION_STRINGS throw new OverflowException( Environment.GetResourceString( "Overflow_SByte" ) ); #else throw new OverflowException(); #endif } return (sbyte)value; } [CLSCompliant( false )] public static sbyte ToSByte( float value ) { return ToSByte( (double)value ); } [CLSCompliant( false )] public static sbyte ToSByte( double value ) { return ToSByte( ToInt32( value ) ); } [CLSCompliant( false )] public static sbyte ToSByte( decimal value ) { return Decimal.ToSByte( Decimal.Round( value, 0 ) ); } [CLSCompliant( false )] public static sbyte ToSByte( String value ) { if(value == null) return 0; return SByte.Parse( value, CultureInfo.CurrentCulture ); } [CLSCompliant( false )] public static sbyte ToSByte( String value, IFormatProvider provider ) { return SByte.Parse( value, NumberStyles.Integer, provider ); } [CLSCompliant( false )] public static sbyte ToSByte( DateTime value ) { return ((IConvertible)value).ToSByte( null ); } // Disallowed conversions to SByte // public static sbyte ToSByte(TimeSpan value) // Conversions to Byte public static byte ToByte( object value ) { return value == null ? (byte)0 : ((IConvertible)value).ToByte( null ); } public static byte ToByte( object value, IFormatProvider provider ) { return value == null ? (byte)0 : ((IConvertible)value).ToByte( provider ); } public static byte ToByte( bool value ) { return value ? (byte)Boolean.True : (byte)Boolean.False; } public static byte ToByte( byte value ) { return value; } public static byte ToByte( char value ) { if(value > Byte.MaxValue) { #if EXCEPTION_STRINGS throw new OverflowException( Environment.GetResourceString( "Overflow_Byte" ) ); #else throw new OverflowException(); #endif } return (byte)value; } [CLSCompliant( false )] public static byte ToByte( sbyte value ) { if(value < Byte.MinValue) { #if EXCEPTION_STRINGS throw new OverflowException( Environment.GetResourceString( "Overflow_Byte" ) ); #else throw new OverflowException(); #endif } return (byte)value; } public static byte ToByte( short value ) { if(value < Byte.MinValue || value > Byte.MaxValue) { #if EXCEPTION_STRINGS throw new OverflowException( Environment.GetResourceString( "Overflow_Byte" ) ); #else throw new OverflowException(); #endif } return (byte)value; } [CLSCompliant( false )] public static byte ToByte( ushort value ) { if(value > Byte.MaxValue) { #if EXCEPTION_STRINGS throw new OverflowException( Environment.GetResourceString( "Overflow_Byte" ) ); #else throw new OverflowException(); #endif } return (byte)value; } public static byte ToByte( int value ) { if(value < Byte.MinValue || value > Byte.MaxValue) { #if EXCEPTION_STRINGS throw new OverflowException( Environment.GetResourceString( "Overflow_Byte" ) ); #else throw new OverflowException(); #endif } return (byte)value; } [CLSCompliant( false )] public static byte ToByte( uint value ) { if(value > Byte.MaxValue) { #if EXCEPTION_STRINGS throw new OverflowException( Environment.GetResourceString( "Overflow_Byte" ) ); #else throw new OverflowException(); #endif } return (byte)value; } public static byte ToByte( long value ) { if(value < Byte.MinValue || value > Byte.MaxValue) { #if EXCEPTION_STRINGS throw new OverflowException( Environment.GetResourceString( "Overflow_Byte" ) ); #else throw new OverflowException(); #endif } return (byte)value; } [CLSCompliant( false )] public static byte ToByte( ulong value ) { if(value > Byte.MaxValue) { #if EXCEPTION_STRINGS throw new OverflowException( Environment.GetResourceString( "Overflow_Byte" ) ); #else throw new OverflowException(); #endif } return (byte)value; } public static byte ToByte( float value ) { return ToByte( (double)value ); } public static byte ToByte( double value ) { return ToByte( ToInt32( value ) ); } public static byte ToByte( decimal value ) { return Decimal.ToByte( Decimal.Round( value, 0 ) ); } public static byte ToByte( String value ) { if(value == null) return 0; return Byte.Parse( value, CultureInfo.CurrentCulture ); } public static byte ToByte( String value, IFormatProvider provider ) { if(value == null) return 0; return Byte.Parse( value, NumberStyles.Integer, provider ); } public static byte ToByte( DateTime value ) { return ((IConvertible)value).ToByte( null ); } // Disallowed conversions to Byte // public static byte ToByte(TimeSpan value) // Conversions to Int16 public static short ToInt16( object value ) { return value == null ? (short)0 : ((IConvertible)value).ToInt16( null ); } public static short ToInt16( object value, IFormatProvider provider ) { return value == null ? (short)0 : ((IConvertible)value).ToInt16( provider ); } public static short ToInt16( bool value ) { return value ? (short)Boolean.True : (short)Boolean.False; } public static short ToInt16( char value ) { if(value > Int16.MaxValue) { #if EXCEPTION_STRINGS throw new OverflowException( Environment.GetResourceString( "Overflow_Int16" ) ); #else throw new OverflowException(); #endif } return (short)value; } [CLSCompliant( false )] public static short ToInt16( sbyte value ) { return value; } public static short ToInt16( byte value ) { return value; } [CLSCompliant( false )] public static short ToInt16( ushort value ) { if(value > Int16.MaxValue) { #if EXCEPTION_STRINGS throw new OverflowException( Environment.GetResourceString( "Overflow_Int16" ) ); #else throw new OverflowException(); #endif } return (short)value; } public static short ToInt16( int value ) { if(value < Int16.MinValue || value > Int16.MaxValue) { #if EXCEPTION_STRINGS throw new OverflowException( Environment.GetResourceString( "Overflow_Int16" ) ); #else throw new OverflowException(); #endif } return (short)value; } [CLSCompliant( false )] public static short ToInt16( uint value ) { if(value > Int16.MaxValue) { #if EXCEPTION_STRINGS throw new OverflowException( Environment.GetResourceString( "Overflow_Int16" ) ); #else throw new OverflowException(); #endif } return (short)value; } public static short ToInt16( short value ) { return value; } public static short ToInt16( long value ) { if(value < Int16.MinValue || value > Int16.MaxValue) { #if EXCEPTION_STRINGS throw new OverflowException( Environment.GetResourceString( "Overflow_Int16" ) ); #else throw new OverflowException(); #endif } return (short)value; } [CLSCompliant( false )] public static short ToInt16( ulong value ) { if(value > (ulong)Int16.MaxValue) { #if EXCEPTION_STRINGS throw new OverflowException( Environment.GetResourceString( "Overflow_Int16" ) ); #else throw new OverflowException(); #endif } return (short)value; } public static short ToInt16( float value ) { return ToInt16( (double)value ); } public static short ToInt16( double value ) { return ToInt16( ToInt32( value ) ); } public static short ToInt16( decimal value ) { return Decimal.ToInt16( Decimal.Round( value, 0 ) ); } public static short ToInt16( String value ) { if(value == null) return 0; return Int16.Parse( value, CultureInfo.CurrentCulture ); } public static short ToInt16( String value, IFormatProvider provider ) { if(value == null) return 0; return Int16.Parse( value, NumberStyles.Integer, provider ); } public static short ToInt16( DateTime value ) { return ((IConvertible)value).ToInt16( null ); } // Disallowed conversions to Int16 // public static short ToInt16(TimeSpan value) // Conversions to UInt16 [CLSCompliant( false )] public static ushort ToUInt16( object value ) { return value == null ? (ushort)0 : ((IConvertible)value).ToUInt16( null ); } [CLSCompliant( false )] public static ushort ToUInt16( object value, IFormatProvider provider ) { return value == null ? (ushort)0 : ((IConvertible)value).ToUInt16( provider ); } [CLSCompliant( false )] public static ushort ToUInt16( bool value ) { return value ? (ushort)Boolean.True : (ushort)Boolean.False; } [CLSCompliant( false )] public static ushort ToUInt16( char value ) { return value; } [CLSCompliant( false )] public static ushort ToUInt16( sbyte value ) { if(value < 0) { #if EXCEPTION_STRINGS throw new OverflowException( Environment.GetResourceString( "Overflow_UInt16" ) ); #else throw new OverflowException(); #endif } return (ushort)value; } [CLSCompliant( false )] public static ushort ToUInt16( byte value ) { return value; } [CLSCompliant( false )] public static ushort ToUInt16( short value ) { if(value < 0) { #if EXCEPTION_STRINGS throw new OverflowException( Environment.GetResourceString( "Overflow_UInt16" ) ); #else throw new OverflowException(); #endif } return (ushort)value; } [CLSCompliant( false )] public static ushort ToUInt16( int value ) { if(value < 0 || value > UInt16.MaxValue) { #if EXCEPTION_STRINGS throw new OverflowException( Environment.GetResourceString( "Overflow_UInt16" ) ); #else throw new OverflowException(); #endif } return (ushort)value; } [CLSCompliant( false )] public static ushort ToUInt16( ushort value ) { return value; } [CLSCompliant( false )] public static ushort ToUInt16( uint value ) { if(value > UInt16.MaxValue) { #if EXCEPTION_STRINGS throw new OverflowException( Environment.GetResourceString( "Overflow_UInt16" ) ); #else throw new OverflowException(); #endif } return (ushort)value; } [CLSCompliant( false )] public static ushort ToUInt16( long value ) { if(value < 0 || value > UInt16.MaxValue) { #if EXCEPTION_STRINGS throw new OverflowException( Environment.GetResourceString( "Overflow_UInt16" ) ); #else throw new OverflowException(); #endif } return (ushort)value; } [CLSCompliant( false )] public static ushort ToUInt16( ulong value ) { if(value > UInt16.MaxValue) { #if EXCEPTION_STRINGS throw new OverflowException( Environment.GetResourceString( "Overflow_UInt16" ) ); #else throw new OverflowException(); #endif } return (ushort)value; } [CLSCompliant( false )] public static ushort ToUInt16( float value ) { return ToUInt16( (double)value ); } [CLSCompliant( false )] public static ushort ToUInt16( double value ) { return ToUInt16( ToInt32( value ) ); } [CLSCompliant( false )] public static ushort ToUInt16( decimal value ) { return Decimal.ToUInt16( Decimal.Round( value, 0 ) ); } [CLSCompliant( false )] public static ushort ToUInt16( String value ) { if(value == null) return 0; return UInt16.Parse( value, CultureInfo.CurrentCulture ); } [CLSCompliant( false )] public static ushort ToUInt16( String value, IFormatProvider provider ) { if(value == null) return 0; return UInt16.Parse( value, NumberStyles.Integer, provider ); } [CLSCompliant( false )] public static ushort ToUInt16( DateTime value ) { return ((IConvertible)value).ToUInt16( null ); } // Disallowed conversions to UInt16 // public static ushort ToUInt16(TimeSpan value) // Conversions to Int32 public static int ToInt32( object value ) { return value == null ? 0 : ((IConvertible)value).ToInt32( null ); } public static int ToInt32( object value, IFormatProvider provider ) { return value == null ? 0 : ((IConvertible)value).ToInt32( provider ); } public static int ToInt32( bool value ) { return value ? Boolean.True : Boolean.False; } public static int ToInt32( char value ) { return value; } [CLSCompliant( false )] public static int ToInt32( sbyte value ) { return value; } public static int ToInt32( byte value ) { return value; } public static int ToInt32( short value ) { return value; } [CLSCompliant( false )] public static int ToInt32( ushort value ) { return value; } [CLSCompliant( false )] public static int ToInt32( uint value ) { if(value > Int32.MaxValue) { #if EXCEPTION_STRINGS throw new OverflowException( Environment.GetResourceString( "Overflow_Int32" ) ); #else throw new OverflowException(); #endif } return (int)value; } public static int ToInt32( int value ) { return value; } public static int ToInt32( long value ) { if(value < Int32.MinValue || value > Int32.MaxValue) { #if EXCEPTION_STRINGS throw new OverflowException( Environment.GetResourceString( "Overflow_Int32" ) ); #else throw new OverflowException(); #endif } return (int)value; } [CLSCompliant( false )] public static int ToInt32( ulong value ) { if(value > Int32.MaxValue) { #if EXCEPTION_STRINGS throw new OverflowException( Environment.GetResourceString( "Overflow_Int32" ) ); #else throw new OverflowException(); #endif } return (int)value; } public static int ToInt32( float value ) { return ToInt32( (double)value ); } public static int ToInt32( double value ) { if(value >= 0) { if(value < 2147483647.5) { int result = (int)value; double dif = value - result; if(dif > 0.5 || dif == 0.5 && (result & 1) != 0) result++; return result; } } else { if(value >= -2147483648.5) { int result = (int)value; double dif = value - result; if(dif < -0.5 || dif == -0.5 && (result & 1) != 0) result--; return result; } } #if EXCEPTION_STRINGS throw new OverflowException( Environment.GetResourceString( "Overflow_Int32" ) ); #else throw new OverflowException(); #endif } public static int ToInt32( decimal value ) { return Decimal.FCallToInt32( value ); } public static int ToInt32( String value ) { if(value == null) return 0; return Int32.Parse( value, CultureInfo.CurrentCulture ); } public static int ToInt32( String value, IFormatProvider provider ) { if(value == null) return 0; return Int32.Parse( value, NumberStyles.Integer, provider ); } public static int ToInt32( DateTime value ) { return ((IConvertible)value).ToInt32( null ); } // Disallowed conversions to Int32 // public static int ToInt32(TimeSpan value) // Conversions to UInt32 [CLSCompliant( false )] public static uint ToUInt32( object value ) { return value == null ? 0 : ((IConvertible)value).ToUInt32( null ); } [CLSCompliant( false )] public static uint ToUInt32( object value, IFormatProvider provider ) { return value == null ? 0 : ((IConvertible)value).ToUInt32( provider ); } [CLSCompliant( false )] public static uint ToUInt32( bool value ) { return value ? (uint)Boolean.True : (uint)Boolean.False; } [CLSCompliant( false )] public static uint ToUInt32( char value ) { return value; } [CLSCompliant( false )] public static uint ToUInt32( sbyte value ) { if(value < 0) { #if EXCEPTION_STRINGS throw new OverflowException( Environment.GetResourceString( "Overflow_UInt32" ) ); #else throw new OverflowException(); #endif } return (uint)value; } [CLSCompliant( false )] public static uint ToUInt32( byte value ) { return value; } [CLSCompliant( false )] public static uint ToUInt32( short value ) { if(value < 0) { #if EXCEPTION_STRINGS throw new OverflowException( Environment.GetResourceString( "Overflow_UInt32" ) ); #else throw new OverflowException(); #endif } return (uint)value; } [CLSCompliant( false )] public static uint ToUInt32( ushort value ) { return value; } [CLSCompliant( false )] public static uint ToUInt32( int value ) { if(value < 0) { #if EXCEPTION_STRINGS throw new OverflowException( Environment.GetResourceString( "Overflow_UInt32" ) ); #else throw new OverflowException(); #endif } return (uint)value; } [CLSCompliant( false )] public static uint ToUInt32( uint value ) { return value; } [CLSCompliant( false )] public static uint ToUInt32( long value ) { if(value < 0 || value > UInt32.MaxValue) { #if EXCEPTION_STRINGS throw new OverflowException( Environment.GetResourceString( "Overflow_UInt32" ) ); #else throw new OverflowException(); #endif } return (uint)value; } [CLSCompliant( false )] public static uint ToUInt32( ulong value ) { if(value > UInt32.MaxValue) { #if EXCEPTION_STRINGS throw new OverflowException( Environment.GetResourceString( "Overflow_UInt32" ) ); #else throw new OverflowException(); #endif } return (uint)value; } [CLSCompliant( false )] public static uint ToUInt32( float value ) { return ToUInt32( (double)value ); } [CLSCompliant( false )] public static uint ToUInt32( double value ) { if(value >= -0.5 && value < 4294967295.5) { uint result = (uint)value; double dif = value - result; if(dif > 0.5 || dif == 0.5 && (result & 1) != 0) result++; return result; } #if EXCEPTION_STRINGS throw new OverflowException( Environment.GetResourceString( "Overflow_UInt32" ) ); #else throw new OverflowException(); #endif } [CLSCompliant( false )] public static uint ToUInt32( decimal value ) { return Decimal.ToUInt32( Decimal.Round( value, 0 ) ); } [CLSCompliant( false )] public static uint ToUInt32( String value ) { if(value == null) return 0; return UInt32.Parse( value, CultureInfo.CurrentCulture ); } [CLSCompliant( false )] public static uint ToUInt32( String value, IFormatProvider provider ) { if(value == null) return 0; return UInt32.Parse( value, NumberStyles.Integer, provider ); } [CLSCompliant( false )] public static uint ToUInt32( DateTime value ) { return ((IConvertible)value).ToUInt32( null ); } // Disallowed conversions to UInt32 // public static uint ToUInt32(TimeSpan value) // Conversions to Int64 public static long ToInt64( object value ) { return value == null ? 0 : ((IConvertible)value).ToInt64( null ); } public static long ToInt64( object value, IFormatProvider provider ) { return value == null ? 0 : ((IConvertible)value).ToInt64( provider ); } public static long ToInt64( bool value ) { return value ? Boolean.True : Boolean.False; } public static long ToInt64( char value ) { return value; } [CLSCompliant( false )] public static long ToInt64( sbyte value ) { return value; } public static long ToInt64( byte value ) { return value; } public static long ToInt64( short value ) { return value; } [CLSCompliant( false )] public static long ToInt64( ushort value ) { return value; } public static long ToInt64( int value ) { return value; } [CLSCompliant( false )] public static long ToInt64( uint value ) { return value; } [CLSCompliant( false )] public static long ToInt64( ulong value ) { if(value > Int64.MaxValue) { #if EXCEPTION_STRINGS throw new OverflowException( Environment.GetResourceString( "Overflow_Int64" ) ); #else throw new OverflowException(); #endif } return (long)value; } public static long ToInt64( long value ) { return value; } public static long ToInt64( float value ) { return ToInt64( (double)value ); } public static long ToInt64( double value ) { return checked( (long)Math.Round( value ) ); } public static long ToInt64( decimal value ) { return Decimal.ToInt64( Decimal.Round( value, 0 ) ); } public static long ToInt64( string value ) { if(value == null) return 0; return Int64.Parse( value, CultureInfo.CurrentCulture ); } public static long ToInt64( String value, IFormatProvider provider ) { if(value == null) return 0; return Int64.Parse( value, NumberStyles.Integer, provider ); } public static long ToInt64( DateTime value ) { return ((IConvertible)value).ToInt64( null ); } // Disallowed conversions to Int64 // public static long ToInt64(TimeSpan value) // Conversions to UInt64 [CLSCompliant( false )] public static ulong ToUInt64( object value ) { return value == null ? 0 : ((IConvertible)value).ToUInt64( null ); } [CLSCompliant( false )] public static ulong ToUInt64( object value, IFormatProvider provider ) { return value == null ? 0 : ((IConvertible)value).ToUInt64( provider ); } [CLSCompliant( false )] public static ulong ToUInt64( bool value ) { return value ? (ulong)Boolean.True : (ulong)Boolean.False; } [CLSCompliant( false )] public static ulong ToUInt64( char value ) { return value; } [CLSCompliant( false )] public static ulong ToUInt64( sbyte value ) { if(value < 0) { #if EXCEPTION_STRINGS throw new OverflowException( Environment.GetResourceString( "Overflow_UInt64" ) ); #else throw new OverflowException(); #endif } return (ulong)value; } [CLSCompliant( false )] public static ulong ToUInt64( byte value ) { return value; } [CLSCompliant( false )] public static ulong ToUInt64( short value ) { if(value < 0) { #if EXCEPTION_STRINGS throw new OverflowException( Environment.GetResourceString( "Overflow_UInt64" ) ); #else throw new OverflowException(); #endif } return (ulong)value; } [CLSCompliant( false )] public static ulong ToUInt64( ushort value ) { return value; } [CLSCompliant( false )] public static ulong ToUInt64( int value ) { if(value < 0) { #if EXCEPTION_STRINGS throw new OverflowException( Environment.GetResourceString( "Overflow_UInt64" ) ); #else throw new OverflowException(); #endif } return (ulong)value; } [CLSCompliant( false )] public static ulong ToUInt64( uint value ) { return value; } [CLSCompliant( false )] public static ulong ToUInt64( long value ) { if(value < 0) { #if EXCEPTION_STRINGS throw new OverflowException( Environment.GetResourceString( "Overflow_UInt64" ) ); #else throw new OverflowException(); #endif } return (ulong)value; } [CLSCompliant( false )] public static ulong ToUInt64( UInt64 value ) { return value; } [CLSCompliant( false )] public static ulong ToUInt64( float value ) { return ToUInt64( (double)value ); } [CLSCompliant( false )] public static ulong ToUInt64( double value ) { return checked( (ulong)Math.Round( value ) ); } [CLSCompliant( false )] public static ulong ToUInt64( decimal value ) { return Decimal.ToUInt64( Decimal.Round( value, 0 ) ); } [CLSCompliant( false )] public static ulong ToUInt64( String value ) { if(value == null) return 0; return UInt64.Parse( value, CultureInfo.CurrentCulture ); } [CLSCompliant( false )] public static ulong ToUInt64( String value, IFormatProvider provider ) { if(value == null) return 0; return UInt64.Parse( value, NumberStyles.Integer, provider ); } [CLSCompliant( false )] public static ulong ToUInt64( DateTime value ) { return ((IConvertible)value).ToUInt64( null ); } // Disallowed conversions to UInt64 // public static ulong ToUInt64(TimeSpan value) // Conversions to Single public static float ToSingle( object value ) { return value == null ? 0 : ((IConvertible)value).ToSingle( null ); } public static float ToSingle( object value, IFormatProvider provider ) { return value == null ? 0 : ((IConvertible)value).ToSingle( provider ); } [CLSCompliant( false )] public static float ToSingle( sbyte value ) { return value; } public static float ToSingle( byte value ) { return value; } public static float ToSingle( char value ) { return ((IConvertible)value).ToSingle( null ); } public static float ToSingle( short value ) { return value; } [CLSCompliant( false )] public static float ToSingle( ushort value ) { return value; } public static float ToSingle( int value ) { return value; } [CLSCompliant( false )] public static float ToSingle( uint value ) { return value; } public static float ToSingle( long value ) { return value; } [CLSCompliant( false )] public static float ToSingle( ulong value ) { return value; } public static float ToSingle( float value ) { return value; } public static float ToSingle( double value ) { return (float)value; } public static float ToSingle( decimal value ) { return (float)value; } public static float ToSingle( String value ) { if(value == null) return 0; return Single.Parse( value, CultureInfo.CurrentCulture ); } public static float ToSingle( String value, IFormatProvider provider ) { if(value == null) return 0; return Single.Parse( value, NumberStyles.Float | NumberStyles.AllowThousands, provider ); } public static float ToSingle( bool value ) { return value ? Boolean.True : Boolean.False; } public static float ToSingle( DateTime value ) { return ((IConvertible)value).ToSingle( null ); } // Disallowed conversions to Single // public static float ToSingle(TimeSpan value) // Conversions to Double public static double ToDouble( object value ) { return value == null ? 0 : ((IConvertible)value).ToDouble( null ); } public static double ToDouble( object value, IFormatProvider provider ) { return value == null ? 0 : ((IConvertible)value).ToDouble( provider ); } [CLSCompliant( false )] public static double ToDouble( sbyte value ) { return value; } public static double ToDouble( byte value ) { return value; } public static double ToDouble( short value ) { return value; } public static double ToDouble( char value ) { return ((IConvertible)value).ToDouble( null ); } [CLSCompliant( false )] public static double ToDouble( ushort value ) { return value; } public static double ToDouble( int value ) { return value; } [CLSCompliant( false )] public static double ToDouble( uint value ) { return value; } public static double ToDouble( long value ) { return value; } [CLSCompliant( false )] public static double ToDouble( ulong value ) { return value; } public static double ToDouble( float value ) { return value; } public static double ToDouble( double value ) { return value; } public static double ToDouble( decimal value ) { return (double)value; } public static double ToDouble( String value ) { if(value == null) return 0; return Double.Parse( value, CultureInfo.CurrentCulture ); } public static double ToDouble( String value, IFormatProvider provider ) { if(value == null) return 0; return Double.Parse( value, NumberStyles.Float | NumberStyles.AllowThousands, provider ); } public static double ToDouble( bool value ) { return value ? Boolean.True : Boolean.False; } public static double ToDouble( DateTime value ) { return ((IConvertible)value).ToDouble( null ); } // Disallowed conversions to Double // public static double ToDouble(TimeSpan value) // Conversions to Decimal public static decimal ToDecimal( object value ) { return value == null ? 0 : ((IConvertible)value).ToDecimal( null ); } public static decimal ToDecimal( object value, IFormatProvider provider ) { return value == null ? 0 : ((IConvertible)value).ToDecimal( provider ); } [CLSCompliant( false )] public static decimal ToDecimal( sbyte value ) { return value; } public static decimal ToDecimal( byte value ) { return value; } public static decimal ToDecimal( char value ) { return ((IConvertible)value).ToDecimal( null ); } public static decimal ToDecimal( short value ) { return value; } [CLSCompliant( false )] public static decimal ToDecimal( ushort value ) { return value; } public static decimal ToDecimal( int value ) { return value; } [CLSCompliant( false )] public static decimal ToDecimal( uint value ) { return value; } public static decimal ToDecimal( long value ) { return value; } [CLSCompliant( false )] public static decimal ToDecimal( ulong value ) { return value; } public static decimal ToDecimal( float value ) { return (decimal)value; } public static decimal ToDecimal( double value ) { return (decimal)value; } public static decimal ToDecimal( String value ) { if(value == null) return 0m; return Decimal.Parse( value, CultureInfo.CurrentCulture ); } public static Decimal ToDecimal( String value, IFormatProvider provider ) { if(value == null) return 0m; return Decimal.Parse( value, NumberStyles.Number, provider ); } public static decimal ToDecimal( decimal value ) { return value; } public static decimal ToDecimal( bool value ) { return value ? Boolean.True : Boolean.False; } public static decimal ToDecimal( DateTime value ) { return ((IConvertible)value).ToDecimal( null ); } // Disallowed conversions to Decimal // public static decimal ToDecimal(TimeSpan value) // Conversions to DateTime public static DateTime ToDateTime( DateTime value ) { return value; } public static DateTime ToDateTime( object value ) { return value == null ? DateTime.MinValue : ((IConvertible)value).ToDateTime( null ); } public static DateTime ToDateTime( object value, IFormatProvider provider ) { return value == null ? DateTime.MinValue : ((IConvertible)value).ToDateTime( provider ); } public static DateTime ToDateTime( String value ) { if(value == null) return new DateTime( 0 ); return DateTime.Parse( value, CultureInfo.CurrentCulture ); } public static DateTime ToDateTime( String value, IFormatProvider provider ) { if(value == null) return new DateTime( 0 ); return DateTime.Parse( value, provider ); } [CLSCompliant( false )] public static DateTime ToDateTime( sbyte value ) { return ((IConvertible)value).ToDateTime( null ); } public static DateTime ToDateTime( byte value ) { return ((IConvertible)value).ToDateTime( null ); } public static DateTime ToDateTime( short value ) { return ((IConvertible)value).ToDateTime( null ); } [CLSCompliant( false )] public static DateTime ToDateTime( ushort value ) { return ((IConvertible)value).ToDateTime( null ); } public static DateTime ToDateTime( int value ) { return ((IConvertible)value).ToDateTime( null ); } [CLSCompliant( false )] public static DateTime ToDateTime( uint value ) { return ((IConvertible)value).ToDateTime( null ); } public static DateTime ToDateTime( long value ) { return ((IConvertible)value).ToDateTime( null ); } [CLSCompliant( false )] public static DateTime ToDateTime( ulong value ) { return ((IConvertible)value).ToDateTime( null ); } public static DateTime ToDateTime( bool value ) { return ((IConvertible)value).ToDateTime( null ); } public static DateTime ToDateTime( char value ) { return ((IConvertible)value).ToDateTime( null ); } public static DateTime ToDateTime( float value ) { return ((IConvertible)value).ToDateTime( null ); } public static DateTime ToDateTime( double value ) { return ((IConvertible)value).ToDateTime( null ); } public static DateTime ToDateTime( decimal value ) { return ((IConvertible)value).ToDateTime( null ); } // Disallowed conversions to DateTime // public static DateTime ToDateTime(TimeSpan value) // Conversions to String public static string ToString( Object value ) { return ToString( value, null ); } public static string ToString( Object value, IFormatProvider provider ) { IConvertible ic = value as IConvertible; if(ic != null) return ic.ToString( provider ); IFormattable formattable = value as IFormattable; if(formattable != null) return formattable.ToString( null, provider ); return value == null ? String.Empty : value.ToString(); } public static string ToString( bool value ) { return value.ToString(); } public static string ToString( bool value, IFormatProvider provider ) { return value.ToString( provider ); } public static string ToString( char value ) { return Char.ToString( value ); } public static string ToString( char value, IFormatProvider provider ) { return value.ToString( provider ); } [CLSCompliant( false )] public static string ToString( sbyte value ) { return value.ToString( CultureInfo.CurrentCulture ); } [CLSCompliant( false )] public static string ToString( sbyte value, IFormatProvider provider ) { return value.ToString( provider ); } public static string ToString( byte value ) { return value.ToString( CultureInfo.CurrentCulture ); } public static string ToString( byte value, IFormatProvider provider ) { return value.ToString( provider ); } public static string ToString( short value ) { return value.ToString( CultureInfo.CurrentCulture ); } public static string ToString( short value, IFormatProvider provider ) { return value.ToString( provider ); } [CLSCompliant( false )] public static string ToString( ushort value ) { return value.ToString( CultureInfo.CurrentCulture ); } [CLSCompliant( false )] public static string ToString( ushort value, IFormatProvider provider ) { return value.ToString( provider ); } public static string ToString( int value ) { return value.ToString( CultureInfo.CurrentCulture ); } public static string ToString( int value, IFormatProvider provider ) { return value.ToString( provider ); } [CLSCompliant( false )] public static string ToString( uint value ) { return value.ToString( CultureInfo.CurrentCulture ); } [CLSCompliant( false )] public static string ToString( uint value, IFormatProvider provider ) { return value.ToString( provider ); } public static string ToString( long value ) { return value.ToString( CultureInfo.CurrentCulture ); } public static string ToString( long value, IFormatProvider provider ) { return value.ToString( provider ); } [CLSCompliant( false )] public static string ToString( ulong value ) { return value.ToString( CultureInfo.CurrentCulture ); } [CLSCompliant( false )] public static string ToString( ulong value, IFormatProvider provider ) { return value.ToString( provider ); } public static string ToString( float value ) { return value.ToString( CultureInfo.CurrentCulture ); } public static string ToString( float value, IFormatProvider provider ) { return value.ToString( provider ); } public static string ToString( double value ) { return value.ToString( CultureInfo.CurrentCulture ); } public static string ToString( double value, IFormatProvider provider ) { return value.ToString( provider ); } public static string ToString( decimal value ) { return value.ToString( CultureInfo.CurrentCulture ); } public static string ToString( Decimal value, IFormatProvider provider ) { return value.ToString( provider ); } public static string ToString( DateTime value ) { return value.ToString(); } public static string ToString( DateTime value, IFormatProvider provider ) { return value.ToString( provider ); } public static String ToString( String value ) { return value; } public static String ToString( String value, IFormatProvider provider ) { return value; // avoid the null check } // // Conversions which understand Base XXX numbers. // // Parses value in base base. base can only // be 2, 8, 10, or 16. If base is 16, the number may be preceded // by 0x; any other leading or trailing characters cause an error. // public static byte ToByte( String value, int fromBase ) { if(fromBase != 2 && fromBase != 8 && fromBase != 10 && fromBase != 16) { #if EXCEPTION_STRINGS throw new ArgumentException( Environment.GetResourceString( "Arg_InvalidBase" ) ); #else throw new ArgumentException(); #endif } int r = ParseNumbers.StringToInt( value, fromBase, ParseNumbers.IsTight | ParseNumbers.TreatAsUnsigned ); if(r < Byte.MinValue || r > Byte.MaxValue) #if EXCEPTION_STRINGS throw new OverflowException( Environment.GetResourceString( "Overflow_Byte" ) ); #else throw new OverflowException(); #endif return (byte)r; } // Parses value in base fromBase. fromBase can only // be 2, 8, 10, or 16. If fromBase is 16, the number may be preceded // by 0x; any other leading or trailing characters cause an error. // [CLSCompliant( false )] public static sbyte ToSByte( String value, int fromBase ) { if(fromBase != 2 && fromBase != 8 && fromBase != 10 && fromBase != 16) { #if EXCEPTION_STRINGS throw new ArgumentException( Environment.GetResourceString( "Arg_InvalidBase" ) ); #else throw new ArgumentException(); #endif } int r = ParseNumbers.StringToInt( value, fromBase, ParseNumbers.IsTight | ParseNumbers.TreatAsI1 ); if(fromBase != 10 && r <= Byte.MaxValue) return (sbyte)r; if(r < SByte.MinValue || r > SByte.MaxValue) #if EXCEPTION_STRINGS throw new OverflowException( Environment.GetResourceString( "Overflow_SByte" ) ); #else throw new OverflowException(); #endif return (sbyte)r; } // Parses value in base fromBase. fromBase can only // be 2, 8, 10, or 16. If fromBase is 16, the number may be preceded // by 0x; any other leading or trailing characters cause an error. // public static short ToInt16( String value, int fromBase ) { if(fromBase != 2 && fromBase != 8 && fromBase != 10 && fromBase != 16) { #if EXCEPTION_STRINGS throw new ArgumentException( Environment.GetResourceString( "Arg_InvalidBase" ) ); #else throw new ArgumentException(); #endif } int r = ParseNumbers.StringToInt( value, fromBase, ParseNumbers.IsTight | ParseNumbers.TreatAsI2 ); if(fromBase != 10 && r <= UInt16.MaxValue) return (short)r; if(r < Int16.MinValue || r > Int16.MaxValue) #if EXCEPTION_STRINGS throw new OverflowException( Environment.GetResourceString( "Overflow_Int16" ) ); #else throw new OverflowException(); #endif return (short)r; } // Parses value in base fromBase. fromBase can only // be 2, 8, 10, or 16. If fromBase is 16, the number may be preceded // by 0x; any other leading or trailing characters cause an error. // [CLSCompliant( false )] public static ushort ToUInt16( String value, int fromBase ) { if(fromBase != 2 && fromBase != 8 && fromBase != 10 && fromBase != 16) { #if EXCEPTION_STRINGS throw new ArgumentException( Environment.GetResourceString( "Arg_InvalidBase" ) ); #else throw new ArgumentException(); #endif } int r = ParseNumbers.StringToInt( value, fromBase, ParseNumbers.IsTight | ParseNumbers.TreatAsUnsigned ); if(r < UInt16.MinValue || r > UInt16.MaxValue) #if EXCEPTION_STRINGS throw new OverflowException( Environment.GetResourceString( "Overflow_UInt16" ) ); #else throw new OverflowException(); #endif return (ushort)r; } // Parses value in base fromBase. fromBase can only // be 2, 8, 10, or 16. If fromBase is 16, the number may be preceded // by 0x; any other leading or trailing characters cause an error. // public static int ToInt32( String value, int fromBase ) { if(fromBase != 2 && fromBase != 8 && fromBase != 10 && fromBase != 16) { #if EXCEPTION_STRINGS throw new ArgumentException( Environment.GetResourceString( "Arg_InvalidBase" ) ); #else throw new ArgumentException(); #endif } return ParseNumbers.StringToInt( value, fromBase, ParseNumbers.IsTight ); } // Parses value in base fromBase. fromBase can only // be 2, 8, 10, or 16. If fromBase is 16, the number may be preceded // by 0x; any other leading or trailing characters cause an error. // [CLSCompliant( false )] public static uint ToUInt32( String value, int fromBase ) { if(fromBase != 2 && fromBase != 8 && fromBase != 10 && fromBase != 16) { #if EXCEPTION_STRINGS throw new ArgumentException( Environment.GetResourceString( "Arg_InvalidBase" ) ); #else throw new ArgumentException(); #endif } return (uint)ParseNumbers.StringToInt( value, fromBase, ParseNumbers.TreatAsUnsigned | ParseNumbers.IsTight ); } // Parses value in base fromBase. fromBase can only // be 2, 8, 10, or 16. If fromBase is 16, the number may be preceded // by 0x; any other leading or trailing characters cause an error. // public static long ToInt64( String value, int fromBase ) { if(fromBase != 2 && fromBase != 8 && fromBase != 10 && fromBase != 16) { #if EXCEPTION_STRINGS throw new ArgumentException( Environment.GetResourceString( "Arg_InvalidBase" ) ); #else throw new ArgumentException(); #endif } return ParseNumbers.StringToLong( value, fromBase, ParseNumbers.IsTight ); } // Parses value in base fromBase. fromBase can only // be 2, 8, 10, or 16. If fromBase is 16, the number may be preceded // by 0x; any other leading or trailing characters cause an error. // [CLSCompliant( false )] public static ulong ToUInt64( String value, int fromBase ) { if(fromBase != 2 && fromBase != 8 && fromBase != 10 && fromBase != 16) { #if EXCEPTION_STRINGS throw new ArgumentException( Environment.GetResourceString( "Arg_InvalidBase" ) ); #else throw new ArgumentException(); #endif } return (ulong)ParseNumbers.StringToLong( value, fromBase, ParseNumbers.TreatAsUnsigned | ParseNumbers.IsTight ); } // Convert the byte value to a string in base fromBase public static String ToString( byte value, int toBase ) { if(toBase != 2 && toBase != 8 && toBase != 10 && toBase != 16) { #if EXCEPTION_STRINGS throw new ArgumentException( Environment.GetResourceString( "Arg_InvalidBase" ) ); #else throw new ArgumentException(); #endif } return ParseNumbers.IntToString( (int)value, toBase, -1, ' ', ParseNumbers.PrintAsI1 ); } // Convert the Int16 value to a string in base fromBase public static String ToString( short value, int toBase ) { if(toBase != 2 && toBase != 8 && toBase != 10 && toBase != 16) { #if EXCEPTION_STRINGS throw new ArgumentException( Environment.GetResourceString( "Arg_InvalidBase" ) ); #else throw new ArgumentException(); #endif } return ParseNumbers.IntToString( (int)value, toBase, -1, ' ', ParseNumbers.PrintAsI2 ); } // Convert the Int32 value to a string in base toBase public static String ToString( int value, int toBase ) { if(toBase != 2 && toBase != 8 && toBase != 10 && toBase != 16) { #if EXCEPTION_STRINGS throw new ArgumentException( Environment.GetResourceString( "Arg_InvalidBase" ) ); #else throw new ArgumentException(); #endif } return ParseNumbers.IntToString( value, toBase, -1, ' ', 0 ); } // Convert the Int64 value to a string in base toBase public static String ToString( long value, int toBase ) { if(toBase != 2 && toBase != 8 && toBase != 10 && toBase != 16) { #if EXCEPTION_STRINGS throw new ArgumentException( Environment.GetResourceString( "Arg_InvalidBase" ) ); #else throw new ArgumentException(); #endif } return ParseNumbers.LongToString( value, toBase, -1, ' ', 0 ); } public static String ToBase64String( byte[] inArray ) { if(inArray == null) { #if EXCEPTION_STRINGS throw new ArgumentNullException( "inArray" ); #else throw new ArgumentNullException(); #endif } return ToBase64String( inArray, 0, inArray.Length, Base64FormattingOptions.None ); } public static String ToBase64String( byte[] inArray, Base64FormattingOptions options ) { if(inArray == null) { #if EXCEPTION_STRINGS throw new ArgumentNullException( "inArray" ); #else throw new ArgumentNullException(); #endif } return ToBase64String( inArray, 0, inArray.Length, options ); } public static String ToBase64String( byte[] inArray, int offset, int length ) { return ToBase64String( inArray, offset, length, Base64FormattingOptions.None ); } public static unsafe String ToBase64String( byte[] inArray, int offset, int length, Base64FormattingOptions options ) { int inArrayLength; int stringLength; //Do data verfication if(inArray == null) #if EXCEPTION_STRINGS throw new ArgumentNullException( "inArray" ); #else throw new ArgumentNullException(); #endif if(length < 0) #if EXCEPTION_STRINGS throw new ArgumentOutOfRangeException( "length", Environment.GetResourceString( "ArgumentOutOfRange_Index" ) ); #else throw new ArgumentOutOfRangeException(); #endif if(offset < 0) #if EXCEPTION_STRINGS throw new ArgumentOutOfRangeException( "offset", Environment.GetResourceString( "ArgumentOutOfRange_GenericPositive" ) ); #else throw new ArgumentOutOfRangeException(); #endif inArrayLength = inArray.Length; if(offset > (inArrayLength - length)) #if EXCEPTION_STRINGS throw new ArgumentOutOfRangeException( "offset", Environment.GetResourceString( "ArgumentOutOfRange_OffsetLength" ) ); #else throw new ArgumentOutOfRangeException(); #endif if(options < Base64FormattingOptions.None || options > Base64FormattingOptions.InsertLineBreaks) { #if EXCEPTION_STRINGS throw new ArgumentException( Environment.GetResourceString( "Arg_EnumIllegalVal", (int)options ) ); #else throw new ArgumentException(); #endif } if(inArrayLength == 0) return String.Empty; bool insertLineBreaks = (options == Base64FormattingOptions.InsertLineBreaks); //Create the new string. This is the maximally required length. stringLength = CalculateOutputLength( length, insertLineBreaks ); string returnString = String.GetStringForStringBuilder( String.Empty, stringLength ); fixed(char* outChars = returnString) { fixed(byte* inData = inArray) { int j = ConvertToBase64Array( outChars, inData, offset, length, insertLineBreaks ); returnString.SetLength( j ); return returnString; } } } public static int ToBase64CharArray( byte[] inArray, int offsetIn, int length, char[] outArray, int offsetOut ) { return ToBase64CharArray( inArray, offsetIn, length, outArray, offsetOut, Base64FormattingOptions.None ); } public static unsafe int ToBase64CharArray( byte[] inArray, int offsetIn, int length, char[] outArray, int offsetOut, Base64FormattingOptions options ) { int retVal; int inArrayLength; int outArrayLength; int numElementsToCopy; //Do data verfication if(inArray == null) #if EXCEPTION_STRINGS throw new ArgumentNullException( "inArray" ); #else throw new ArgumentNullException(); #endif if(outArray == null) #if EXCEPTION_STRINGS throw new ArgumentNullException( "outArray" ); #else throw new ArgumentNullException(); #endif if(length < 0) #if EXCEPTION_STRINGS throw new ArgumentOutOfRangeException( "length", Environment.GetResourceString( "ArgumentOutOfRange_Index" ) ); #else throw new ArgumentOutOfRangeException(); #endif if(offsetIn < 0) #if EXCEPTION_STRINGS throw new ArgumentOutOfRangeException( "offsetIn", Environment.GetResourceString( "ArgumentOutOfRange_GenericPositive" ) ); #else throw new ArgumentOutOfRangeException(); #endif if(offsetOut < 0) #if EXCEPTION_STRINGS throw new ArgumentOutOfRangeException( "offsetOut", Environment.GetResourceString( "ArgumentOutOfRange_GenericPositive" ) ); #else throw new ArgumentOutOfRangeException(); #endif if(options < Base64FormattingOptions.None || options > Base64FormattingOptions.InsertLineBreaks) { #if EXCEPTION_STRINGS throw new ArgumentException( Environment.GetResourceString( "Arg_EnumIllegalVal", (int)options ) ); #else throw new ArgumentException(); #endif } inArrayLength = inArray.Length; if(offsetIn > (int)(inArrayLength - length)) #if EXCEPTION_STRINGS throw new ArgumentOutOfRangeException( "offsetIn", Environment.GetResourceString( "ArgumentOutOfRange_OffsetLength" ) ); #else throw new ArgumentOutOfRangeException(); #endif if(inArrayLength == 0) return 0; bool insertLineBreaks = (options == Base64FormattingOptions.InsertLineBreaks); //This is the maximally required length that must be available in the char array outArrayLength = outArray.Length; // Length of the char buffer required numElementsToCopy = CalculateOutputLength( length, insertLineBreaks ); if(offsetOut > (int)(outArrayLength - numElementsToCopy)) #if EXCEPTION_STRINGS throw new ArgumentOutOfRangeException( "offsetOut", Environment.GetResourceString( "ArgumentOutOfRange_OffsetOut" ) ); #else throw new ArgumentOutOfRangeException(); #endif fixed(char* outChars = &outArray[offsetOut]) { fixed(byte* inData = inArray) { retVal = ConvertToBase64Array( outChars, inData, offsetIn, length, insertLineBreaks ); } } return retVal; } private static unsafe int ConvertToBase64Array( char* outChars, byte* inData, int offset, int length, bool insertLineBreaks ) { int lengthmod3 = length % 3; int calcLength = offset + (length - lengthmod3); int j = 0; int charcount = 0; //Convert three bytes at a time to base64 notation. This will consume 4 chars. int i; // get a pointer to the base64Table to avoid unnecessary range checking fixed(char* base64 = base64Table) { for(i = offset; i < calcLength; i += 3) { if(insertLineBreaks) { if(charcount == 76) { outChars[j++] = '\r'; outChars[j++] = '\n'; charcount = 0; } charcount += 4; } outChars[j] = base64[(inData[i] & 0xfc) >> 2]; outChars[j + 1] = base64[((inData[i] & 0x03) << 4) | ((inData[i + 1] & 0xf0) >> 4)]; outChars[j + 2] = base64[((inData[i + 1] & 0x0f) << 2) | ((inData[i + 2] & 0xc0) >> 6)]; outChars[j + 3] = base64[(inData[i + 2] & 0x3f)]; j += 4; } //Where we left off before i = calcLength; if(insertLineBreaks && (lengthmod3 != 0) && (charcount == 76)) { outChars[j++] = '\r'; outChars[j++] = '\n'; } switch(lengthmod3) { case 2: //One character padding needed outChars[j] = base64[(inData[i] & 0xfc) >> 2]; outChars[j + 1] = base64[((inData[i] & 0x03) << 4) | ((inData[i + 1] & 0xf0) >> 4)]; outChars[j + 2] = base64[(inData[i + 1] & 0x0f) << 2]; outChars[j + 3] = base64[64]; //Pad j += 4; break; case 1: // Two character padding needed outChars[j] = base64[(inData[i] & 0xfc) >> 2]; outChars[j + 1] = base64[(inData[i] & 0x03) << 4]; outChars[j + 2] = base64[64]; //Pad outChars[j + 3] = base64[64]; //Pad j += 4; break; } } return j; } private static int CalculateOutputLength( int inputLength, bool insertLineBreaks ) { int outlen = (int)(inputLength / 3 * 4); // the base length - we want integer division here. outlen += ((inputLength % 3) != 0) ? 4 : 0; // at most 4 more chars for the remainder if(outlen == 0) return outlen; if(insertLineBreaks) { int newLines = outlen / 76; if((outlen % 76) == 0) { --newLines; } outlen += newLines * 2; // the number of line break chars we'll add, "\r\n" } return outlen; } //// [ResourceExposure( ResourceScope.None )] [MethodImplAttribute( MethodImplOptions.InternalCall )] public static extern byte[] FromBase64String( String s ); //// [ResourceExposure( ResourceScope.None )] [MethodImplAttribute( MethodImplOptions.InternalCall )] public static extern byte[] FromBase64CharArray( char[] inArray, int offset, int length ); } [Flags] public enum Base64FormattingOptions { None = 0, InsertLineBreaks = 1 } } ================================================ FILE: Zelig/Zelig/RunTime/Framework/mscorlib/System/CurrentTimeZone.cs ================================================ // ==++== // // Copyright (c) Microsoft Corporation. All rights reserved. // // ==--== /*============================================================ ** ** Class: CurrentTimeZone ** ** ** Purpose: ** This class represents the current system timezone. It is ** the only meaningful implementation of the TimeZone class ** available in this version. ** ** The only TimeZone that we support in version 1 is the ** CurrentTimeZone as determined by the system timezone. ** ** ============================================================*/ namespace System { using System; using System.Text; using System.Threading; using System.Collections; using System.Collections.Generic; using System.Globalization; using System.Runtime.CompilerServices; ////using System.Runtime.Versioning; // // Currently, this is the only supported timezone. // The values of the timezone is from the current system timezone setting in the // control panel. // [Microsoft.Zelig.Internals.WellKnownType( "System_CurrentSystemTimeZone" )] [Serializable()] internal class CurrentSystemTimeZone : TimeZone { // BUGBUG : // One problem is when user changes the current timezone. We // are not able to update currentStandardName/currentDaylightName/ // currentDaylightChanges. // We need WM_TIMECHANGE to do this or use // RegNotifyChangeKeyValue() to monitor // private const long TicksPerMillisecond = 10000; private const long TicksPerSecond = TicksPerMillisecond * 1000; private const long TicksPerMinute = TicksPerSecond * 60; //// // The per-year information is cached in in this instance value. As a result it can //// // be cleaned up by CultureInfo.ClearCachedData, which will clear the instance of this object //// private Dictionary m_CachedDaylightChanges = new Dictionary(); private DaylightTime m_CachedDaylightChanges; private int m_CachedDaylightChangesYear; // Standard offset in ticks to the Universal time if // no daylight saving is in used. // E.g. the offset for PST (Pacific Standard time) should be -8 * 60 * 60 * 1000 * 10000. // (1 millisecond = 10000 ticks) private long m_ticksOffset; private String m_standardName; private String m_daylightName; internal CurrentSystemTimeZone() { m_ticksOffset = nativeGetTimeZoneMinuteOffset() * TicksPerMinute; m_standardName = null; m_daylightName = null; } public override String StandardName { get { if(m_standardName == null) { m_standardName = nativeGetStandardName(); } return (m_standardName); } } public override String DaylightName { get { if(m_daylightName == null) { m_daylightName = nativeGetDaylightName(); if(m_daylightName == null) { m_daylightName = this.StandardName; } } return (m_daylightName); } } internal long GetUtcOffsetFromUniversalTime( DateTime time, ref Boolean isAmbiguousLocalDst ) { // Get the daylight changes for the year of the specified time. TimeSpan offset = new TimeSpan( m_ticksOffset ); DaylightTime daylightTime = GetDaylightChanges( time.Year ); isAmbiguousLocalDst = false; if(daylightTime == null || daylightTime.Delta.Ticks == 0) { return offset.Ticks; } // The start and end times represent the range of universal times that are in DST for that year. // Within that there is an ambiguous hour, usually right at the end, but at the beginning in // the unusual case of a negative daylight savings delta. DateTime startTime = daylightTime.Start - offset; DateTime endTime = daylightTime.End - offset - daylightTime.Delta; DateTime ambiguousStart; DateTime ambiguousEnd; if(daylightTime.Delta.Ticks > 0) { ambiguousStart = endTime - daylightTime.Delta; ambiguousEnd = endTime; } else { ambiguousStart = startTime; ambiguousEnd = startTime - daylightTime.Delta; } Boolean isDst = false; if(startTime > endTime) { // In southern hemisphere, the daylight saving time starts later in the year, and ends in the beginning of next year. // Note, the summer in the southern hemisphere begins late in the year. isDst = (time < endTime || time >= startTime); } else { // In northern hemisphere, the daylight saving time starts in the middle of the year. isDst = (time >= startTime && time < endTime); } if(isDst) { offset += daylightTime.Delta; // See if the resulting local time becomes ambiguous. This must be captured here or the // DateTime will not be able to round-trip back to UTC accurately. if(time >= ambiguousStart && time < ambiguousEnd) { isAmbiguousLocalDst = true; } } return offset.Ticks; } public override DateTime ToLocalTime( DateTime time ) { if(time.Kind == DateTimeKind.Local) { return time; } Boolean isAmbiguousLocalDst = false; Int64 offset = GetUtcOffsetFromUniversalTime( time, ref isAmbiguousLocalDst ); long tick = time.Ticks + offset; if(tick > DateTime.MaxTicks) { return new DateTime( DateTime.MaxTicks, DateTimeKind.Local ); } if(tick < DateTime.MinTicks) { return new DateTime( DateTime.MinTicks, DateTimeKind.Local ); } return new DateTime( tick, DateTimeKind.Local, isAmbiguousLocalDst ); } // Private object for locking instead of locking on a public type for SQL reliability work. private static Object s_InternalSyncObject; private static Object InternalSyncObject { get { if(s_InternalSyncObject == null) { Object o = new Object(); Interlocked.CompareExchange( ref s_InternalSyncObject, o, null ); } return s_InternalSyncObject; } } public override DaylightTime GetDaylightChanges( int year ) { if(year < 1 || year > 9999) { #if EXCEPTION_STRINGS throw new ArgumentOutOfRangeException( "year", String.Format( CultureInfo.CurrentCulture, Environment.GetResourceString( "ArgumentOutOfRange_Range" ), 1, 9999 ) ); #else throw new ArgumentOutOfRangeException(); #endif } lock(InternalSyncObject) { //// Object cachedObject; //// if(m_CachedDaylightChanges.TryGetValue( year, out cachedObject )) //// { //// return (DaylightTime)cachedObject; //// } //// else if(m_CachedDaylightChangesYear == year && m_CachedDaylightChanges != null) { return m_CachedDaylightChanges; } else { // // rawData is an array of 17 short (16 bit) numbers. // The first 8 numbers contains the // year/month/day/dayOfWeek/hour/minute/second/millisecond for the starting time of daylight saving time. // The next 8 numbers contains the // year/month/day/dayOfWeek/hour/minute/second/millisecond for the ending time of daylight saving time. // The last short number is the delta to the standard offset in minutes. // short[] rawData = nativeGetDaylightChanges(); DaylightTime currentDaylightChanges; if(rawData == null) { // // If rawData is null, it means that daylight saving time is not used // in this timezone. So keep currentDaylightChanges as the empty array. // currentDaylightChanges = new DaylightTime( DateTime.MinValue, DateTime.MinValue, TimeSpan.Zero ); } else { DateTime start; DateTime end; TimeSpan delta; // // Store the start of daylight saving time. // start = GetDayOfWeek( year, rawData[1], rawData[2], rawData[3], rawData[4], rawData[5], rawData[6], rawData[7] ); // // Store the end of daylight saving time. // end = GetDayOfWeek( year, rawData[9], rawData[10], rawData[11], rawData[12], rawData[13], rawData[14], rawData[15] ); delta = new TimeSpan( rawData[16] * TicksPerMinute ); currentDaylightChanges = new DaylightTime( start, end, delta ); } //// m_CachedDaylightChanges.Add( year, currentDaylightChanges ); m_CachedDaylightChangesYear = year; m_CachedDaylightChanges = currentDaylightChanges; return currentDaylightChanges; } } } public override TimeSpan GetUtcOffset( DateTime time ) { if(time.Kind == DateTimeKind.Utc) { return TimeSpan.Zero; } else { return new TimeSpan( TimeZone.CalculateUtcOffset( time, GetDaylightChanges( time.Year ) ).Ticks + m_ticksOffset ); } } // // Return the (numberOfSunday)th day of week in a particular year/month. // private static DateTime GetDayOfWeek( int year, int month, int targetDayOfWeek, int numberOfSunday, int hour, int minute, int second, int millisecond ) { DateTime time; if(numberOfSunday <= 4) { // // Get the (numberOfSunday)th Sunday. // time = new DateTime( year, month, 1, hour, minute, second, millisecond, DateTimeKind.Local ); int dayOfWeek = (int)time.DayOfWeek; int delta = targetDayOfWeek - dayOfWeek; if(delta < 0) { delta += 7; } delta += 7 * (numberOfSunday - 1); if(delta > 0) { time = time.AddDays( delta ); } } else { // // If numberOfSunday is greater than 4, we will get the last sunday. // Calendar cal = GregorianCalendar.GetDefaultInstance(); time = new DateTime( year, month, cal.GetDaysInMonth( year, month ), hour, minute, second, millisecond, DateTimeKind.Local ); // This is the day of week for the last day of the month. int dayOfWeek = (int)time.DayOfWeek; int delta = dayOfWeek - targetDayOfWeek; if(delta < 0) { delta += 7; } if(delta > 0) { time = time.AddDays( -delta ); } } return (time); } //// [ResourceExposure( ResourceScope.None )] [MethodImplAttribute( MethodImplOptions.InternalCall )] internal extern static int nativeGetTimeZoneMinuteOffset(); //// [ResourceExposure( ResourceScope.None )] [MethodImplAttribute( MethodImplOptions.InternalCall )] internal extern static String nativeGetDaylightName(); //// [ResourceExposure( ResourceScope.None )] [MethodImplAttribute( MethodImplOptions.InternalCall )] internal extern static String nativeGetStandardName(); //// [ResourceExposure( ResourceScope.None )] [MethodImplAttribute( MethodImplOptions.InternalCall )] internal extern static short[] nativeGetDaylightChanges(); } // class CurrentSystemTimeZone } ================================================ FILE: Zelig/Zelig/RunTime/Framework/mscorlib/System/DBNull.cs ================================================ // ==++== // // Copyright (c) Microsoft Corporation. All rights reserved. // // ==--== //////////////////////////////////////////////////////////////////////////////// // Void // This class represents a Missing Variant //////////////////////////////////////////////////////////////////////////////// namespace System { using System; ////using System.Runtime.Remoting; using System.Runtime.Serialization; [Serializable] public sealed class DBNull /*: ISerializable, IConvertible*/ { public static readonly DBNull Value = new DBNull(); //Package private constructor private DBNull() { } //// private DBNull( SerializationInfo info, StreamingContext context ) //// { //// throw new NotSupportedException( Environment.GetResourceString( "NotSupported_DBNullSerial" ) ); //// } //// //// public void GetObjectData( SerializationInfo info, StreamingContext context ) //// { //// UnitySerializationHolder.GetUnitySerializationInfo( info, UnitySerializationHolder.NullUnity, null, null ); //// } //// //// public override String ToString() //// { //// return String.Empty; //// } #region IConvertible //// //// public TypeCode GetTypeCode() //// { //// return TypeCode.DBNull; //// } //// //// /// //// bool IConvertible.ToBoolean( IFormatProvider provider ) //// { //// throw new InvalidCastException( Environment.GetResourceString( "InvalidCast_FromDBNull" ) ); //// } //// //// /// //// char IConvertible.ToChar( IFormatProvider provider ) //// { //// throw new InvalidCastException( Environment.GetResourceString( "InvalidCast_FromDBNull" ) ); //// } //// //// /// //// sbyte IConvertible.ToSByte( IFormatProvider provider ) //// { //// throw new InvalidCastException( Environment.GetResourceString( "InvalidCast_FromDBNull" ) ); //// } //// //// /// //// byte IConvertible.ToByte( IFormatProvider provider ) //// { //// throw new InvalidCastException( Environment.GetResourceString( "InvalidCast_FromDBNull" ) ); //// } //// //// /// //// short IConvertible.ToInt16( IFormatProvider provider ) //// { //// throw new InvalidCastException( Environment.GetResourceString( "InvalidCast_FromDBNull" ) ); //// } //// //// /// //// ushort IConvertible.ToUInt16( IFormatProvider provider ) //// { //// throw new InvalidCastException( Environment.GetResourceString( "InvalidCast_FromDBNull" ) ); //// } //// //// /// //// int IConvertible.ToInt32( IFormatProvider provider ) //// { //// throw new InvalidCastException( Environment.GetResourceString( "InvalidCast_FromDBNull" ) ); //// } //// //// /// //// uint IConvertible.ToUInt32( IFormatProvider provider ) //// { //// throw new InvalidCastException( Environment.GetResourceString( "InvalidCast_FromDBNull" ) ); //// } //// //// /// //// long IConvertible.ToInt64( IFormatProvider provider ) //// { //// throw new InvalidCastException( Environment.GetResourceString( "InvalidCast_FromDBNull" ) ); //// } //// //// /// //// ulong IConvertible.ToUInt64( IFormatProvider provider ) //// { //// throw new InvalidCastException( Environment.GetResourceString( "InvalidCast_FromDBNull" ) ); //// } //// //// /// //// float IConvertible.ToSingle( IFormatProvider provider ) //// { //// throw new InvalidCastException( Environment.GetResourceString( "InvalidCast_FromDBNull" ) ); //// } //// //// /// //// double IConvertible.ToDouble( IFormatProvider provider ) //// { //// throw new InvalidCastException( Environment.GetResourceString( "InvalidCast_FromDBNull" ) ); //// } //// //// /// //// decimal IConvertible.ToDecimal( IFormatProvider provider ) //// { //// throw new InvalidCastException( Environment.GetResourceString( "InvalidCast_FromDBNull" ) ); //// } //// //// /// //// DateTime IConvertible.ToDateTime( IFormatProvider provider ) //// { //// throw new InvalidCastException( Environment.GetResourceString( "InvalidCast_FromDBNull" ) ); //// } //// //// public String ToString( IFormatProvider provider ) //// { //// return String.Empty; //// } //// //// /// //// Object IConvertible.ToType( Type type, IFormatProvider provider ) //// { //// return Convert.DefaultToType( (IConvertible)this, type, provider ); //// } #endregion } } ================================================ FILE: Zelig/Zelig/RunTime/Framework/mscorlib/System/DateTime.cs ================================================ // ==++== // // Copyright (c) Microsoft Corporation. All rights reserved. // // ==--== namespace System { using System; using System.Threading; using System.Globalization; using System.Runtime.InteropServices; using System.Runtime.CompilerServices; using System.Runtime.Serialization; ////using System.Security.Permissions; ////using CultureInfo = System.Globalization.CultureInfo; ////using Calendar = System.Globalization.Calendar; // This value type represents a date and time. Every DateTime // object has a private field (Ticks) of type Int64 that stores the // date and time as the number of 100 nanosecond intervals since // 12:00 AM January 1, year 1 A.D. in the proleptic Gregorian Calendar. // // Starting from V2.0, DateTime also stored some context about its time // zone in the form of a 3-state value representing Unspecified, Utc or // Local. This is stored in the two top bits of the 64-bit numeric value // with the remainder of the bits storing the tick count. This information // is only used during time zone conversions and is not part of the // identity of the DateTime. Thus, operations like Compare and Equals // ignore this state. This is to stay compatible with earlier behavior // and performance characteristics and to avoid forcing people into dealing // with the effects of daylight savings. Note, that this has little effect // on how the DateTime works except in a context where its specific time // zone is needed, such as during conversions and some parsing and formatting // cases. // // There is also 4th state stored that is a special type of Local value that // is used to avoid data loss when round-tripping between local and UTC time. // See below for more information on this 4th state, although it is // effectively hidden from most users, who just see the 3-state DateTimeKind // enumeration. // // For compatability, DateTime does not serialize the Kind data when used in // binary serialization. // // For a description of various calendar issues, look at // // Calendar Studies web site, at // http://serendipity.nofadz.com/hermetic/cal_stud.htm. // // [Serializable] [StructLayout( LayoutKind.Auto )] public struct DateTime : IComparable, /*IFormattable,*/ IConvertible, /*ISerializable,*/ IComparable, IEquatable { private const long TicksPerMillisecond = 10000; // Number of 100ns ticks per time unit private const long TicksPerSecond = TicksPerMillisecond * 1000; private const long TicksPerMinute = TicksPerSecond * 60; private const long TicksPerHour = TicksPerMinute * 60; private const long TicksPerDay = TicksPerHour * 24; private const int MillisPerSecond = 1000; // Number of milliseconds per time unit private const int MillisPerMinute = MillisPerSecond * 60; private const int MillisPerHour = MillisPerMinute * 60; private const int MillisPerDay = MillisPerHour * 24; private const int DaysPerYear = 365; // Number of days in a non-leap year private const int DaysPer4Years = DaysPerYear * 4 + 1; // Number of days in 4 years private const int DaysPer100Years = DaysPer4Years * 25 - 1; // Number of days in 100 years private const int DaysPer400Years = DaysPer100Years * 4 + 1; // Number of days in 400 years private const int DaysTo1601 = DaysPer400Years * 4; // Number of days from 1/1/0001 to 12/31/1600 private const int DaysTo1899 = DaysPer400Years * 4 + DaysPer100Years * 3 - 367; // Number of days from 1/1/0001 to 12/30/1899 private const int DaysTo10000 = DaysPer400Years * 25 - 366; // Number of days from 1/1/0001 to 12/31/9999 internal const long MinTicks = 0; internal const long MaxTicks = DaysTo10000 * TicksPerDay - 1; private const long MaxMillis = (long)DaysTo10000 * MillisPerDay; private const long FileTimeOffset = DaysTo1601 * TicksPerDay; private const long DoubleDateOffset = DaysTo1899 * TicksPerDay; private const long OADateMinAsTicks = (DaysPer100Years - DaysPerYear) * TicksPerDay; private const double OADateMinAsDouble = -657435.0; // All OA dates must be greater than (not >=) OADateMinAsDouble (minimum date is 0100/01/01: Note it's year 100) private const double OADateMaxAsDouble = 2958466.0; // All OA dates must be less than (not <=) OADateMaxAsDouble (maximum date is 9999/12/31) private const int DatePartYear = 0; private const int DatePartDayOfYear = 1; private const int DatePartMonth = 2; private const int DatePartDay = 3; private static readonly int[] DaysToMonth365 = { 0, 31, 59, 90, 120, 151, 181, 212, 243, 273, 304, 334, 365 }; private static readonly int[] DaysToMonth366 = { 0, 31, 60, 91, 121, 152, 182, 213, 244, 274, 305, 335, 366 }; public static readonly DateTime MinValue = new DateTime( MinTicks, DateTimeKind.Unspecified ); public static readonly DateTime MaxValue = new DateTime( MaxTicks, DateTimeKind.Unspecified ); private const UInt64 TicksMask = 0x3FFFFFFFFFFFFFFF; private const UInt64 FlagsMask = 0xC000000000000000; private const UInt64 LocalMask = 0x8000000000000000; private const Int64 TicksCeiling = 0x4000000000000000; private const UInt64 KindUnspecified = 0x0000000000000000; private const UInt64 KindUtc = 0x4000000000000000; private const UInt64 KindLocal = 0x8000000000000000; private const UInt64 KindLocalAmbiguousDst = 0xC000000000000000; private const Int32 KindShift = 62; //// private const String TicksField = "ticks"; //// private const String DateDataField = "dateData"; // The data is stored as an unsigned 64-bit integeter // Bits 01-62: The value of 100-nanosecond ticks where 0 represents 1/1/0001 12:00am, up until the value // 12/31/9999 23:59:59.9999999 // Bits 63-64: A four-state value that describes the DateTimeKind value of the date time, with a 2nd // value for the rare case where the date time is local, but is in an overlapped daylight // savings time hour and it is in daylight savings time. This allows distinction of these // otherwise ambiguous local times and prevents data loss when round tripping from Local to // UTC time. private UInt64 dateData; // Constructs a DateTime from a tick count. The ticks // argument specifies the date as the number of 100-nanosecond intervals // that have elapsed since 1/1/0001 12:00am. // public DateTime( long ticks ) { if(ticks < MinTicks || ticks > MaxTicks) { #if EXCEPTION_STRINGS throw new ArgumentOutOfRangeException( "ticks", Environment.GetResourceString( "ArgumentOutOfRange_DateTimeBadTicks" ) ); #else throw new ArgumentOutOfRangeException(); #endif } dateData = (UInt64)ticks; } private DateTime( UInt64 dateData ) { this.dateData = dateData; } public DateTime( long ticks, DateTimeKind kind ) { if(ticks < MinTicks || ticks > MaxTicks) { #if EXCEPTION_STRINGS throw new ArgumentOutOfRangeException( "ticks", Environment.GetResourceString( "ArgumentOutOfRange_DateTimeBadTicks" ) ); #else throw new ArgumentOutOfRangeException(); #endif } if(kind < DateTimeKind.Unspecified || kind > DateTimeKind.Local) { #if EXCEPTION_STRINGS throw new ArgumentException( Environment.GetResourceString( "Argument_InvalidDateTimeKind" ), "kind" ); #else throw new ArgumentException(); #endif } this.dateData = ((UInt64)ticks | ((UInt64)kind << KindShift)); } internal DateTime( long ticks, DateTimeKind kind, Boolean isAmbiguousDst ) { if(ticks < MinTicks || ticks > MaxTicks) { #if EXCEPTION_STRINGS throw new ArgumentOutOfRangeException( "ticks", Environment.GetResourceString( "ArgumentOutOfRange_DateTimeBadTicks" ) ); #else throw new ArgumentOutOfRangeException(); #endif } BCLDebug.Assert( kind == DateTimeKind.Local, "Internal Constructor is for local times only" ); dateData = ((UInt64)ticks | (isAmbiguousDst ? KindLocalAmbiguousDst : KindLocal)); } // Constructs a DateTime from a given year, month, and day. The // time-of-day of the resulting DateTime is always midnight. // public DateTime( int year, int month, int day ) { this.dateData = (UInt64)DateToTicks( year, month, day ); } //// // Constructs a DateTime from a given year, month, and day for //// // the specified calendar. The //// // time-of-day of the resulting DateTime is always midnight. //// // //// public DateTime( int year, int month, int day, Calendar calendar ) : this( year, month, day, 0, 0, 0, calendar ) //// { //// } // Constructs a DateTime from a given year, month, day, hour, // minute, and second. // public DateTime( int year, int month, int day, int hour, int minute, int second ) { this.dateData = (UInt64)(DateToTicks( year, month, day ) + TimeToTicks( hour, minute, second )); } public DateTime( int year, int month, int day, int hour, int minute, int second, DateTimeKind kind ) { Int64 ticks = DateToTicks( year, month, day ) + TimeToTicks( hour, minute, second ); if(kind < DateTimeKind.Unspecified || kind > DateTimeKind.Local) { #if EXCEPTION_STRINGS throw new ArgumentException( Environment.GetResourceString( "Argument_InvalidDateTimeKind" ), "kind" ); #else throw new ArgumentException(); #endif } this.dateData = ((UInt64)ticks | ((UInt64)kind << KindShift)); } //// // Constructs a DateTime from a given year, month, day, hour, //// // minute, and second for the specified calendar. //// // //// public DateTime( int year, int month, int day, int hour, int minute, int second, Calendar calendar ) //// { //// if(calendar == null) //// { //// throw new ArgumentNullException( "calendar" ); //// } //// //// this.dateData = (UInt64)calendar.ToDateTime( year, month, day, hour, minute, second, 0 ).Ticks; //// } // Constructs a DateTime from a given year, month, day, hour, // minute, and second. // public DateTime( int year, int month, int day, int hour, int minute, int second, int millisecond ) { Int64 ticks = DateToTicks( year, month, day ) + TimeToTicks( hour, minute, second ); if(millisecond < 0 || millisecond >= MillisPerSecond) { #if EXCEPTION_STRINGS throw new ArgumentOutOfRangeException( "millisecond", String.Format( CultureInfo.CurrentCulture, Environment.GetResourceString( "ArgumentOutOfRange_Range" ), 0, MillisPerSecond - 1 ) ); #else throw new ArgumentOutOfRangeException(); #endif } ticks += millisecond * TicksPerMillisecond; if(ticks < MinTicks || ticks > MaxTicks) { #if EXCEPTION_STRINGS throw new ArgumentException( Environment.GetResourceString( "Arg_DateTimeRange" ) ); #else throw new ArgumentException(); #endif } this.dateData = (UInt64)ticks; } public DateTime( int year, int month, int day, int hour, int minute, int second, int millisecond, DateTimeKind kind ) { Int64 ticks = DateToTicks( year, month, day ) + TimeToTicks( hour, minute, second ); if(millisecond < 0 || millisecond >= MillisPerSecond) { #if EXCEPTION_STRINGS throw new ArgumentOutOfRangeException( "millisecond", String.Format( CultureInfo.CurrentCulture, Environment.GetResourceString( "ArgumentOutOfRange_Range" ), 0, MillisPerSecond - 1 ) ); #else throw new ArgumentOutOfRangeException(); #endif } ticks += millisecond * TicksPerMillisecond; if(ticks < MinTicks || ticks > MaxTicks) { #if EXCEPTION_STRINGS throw new ArgumentException( Environment.GetResourceString( "Arg_DateTimeRange" ) ); #else throw new ArgumentException(); #endif } if(kind < DateTimeKind.Unspecified || kind > DateTimeKind.Local) { #if EXCEPTION_STRINGS throw new ArgumentException( Environment.GetResourceString( "Argument_InvalidDateTimeKind" ), "kind" ); #else throw new ArgumentException(); #endif } this.dateData = ((UInt64)ticks | ((UInt64)kind << KindShift)); } //// // Constructs a DateTime from a given year, month, day, hour, //// // minute, and second for the specified calendar. //// // //// public DateTime( int year, int month, int day, int hour, int minute, int second, int millisecond, Calendar calendar ) //// { //// if(calendar == null) //// { //// throw new ArgumentNullException( "calendar" ); //// } //// //// Int64 ticks = calendar.ToDateTime( year, month, day, hour, minute, second, 0 ).Ticks; //// if(millisecond < 0 || millisecond >= MillisPerSecond) //// { //// throw new ArgumentOutOfRangeException( "millisecond", String.Format( CultureInfo.CurrentCulture, Environment.GetResourceString( "ArgumentOutOfRange_Range" ), 0, MillisPerSecond - 1 ) ); //// } //// //// ticks += millisecond * TicksPerMillisecond; //// if(ticks < MinTicks || ticks > MaxTicks) //// { //// throw new ArgumentException( Environment.GetResourceString( "Arg_DateTimeRange" ) ); //// } //// //// this.dateData = (UInt64)ticks; //// } //// //// public DateTime( int year, int month, int day, int hour, int minute, int second, int millisecond, Calendar calendar, DateTimeKind kind ) //// { //// if(calendar == null) //// { //// throw new ArgumentNullException( "calendar" ); //// } //// //// Int64 ticks = calendar.ToDateTime( year, month, day, hour, minute, second, 0 ).Ticks; //// if(millisecond < 0 || millisecond >= MillisPerSecond) //// { //// throw new ArgumentOutOfRangeException( "millisecond", String.Format( CultureInfo.CurrentCulture, Environment.GetResourceString( "ArgumentOutOfRange_Range" ), 0, MillisPerSecond - 1 ) ); //// } //// //// ticks += millisecond * TicksPerMillisecond; //// if(ticks < MinTicks || ticks > MaxTicks) //// { //// throw new ArgumentException( Environment.GetResourceString( "Arg_DateTimeRange" ) ); //// } //// //// if(kind < DateTimeKind.Unspecified || kind > DateTimeKind.Local) //// { //// throw new ArgumentException( Environment.GetResourceString( "Argument_InvalidDateTimeKind" ), "kind" ); //// } //// //// this.dateData = ((UInt64)ticks | ((UInt64)kind << KindShift)); //// } //// //// private DateTime( SerializationInfo info, StreamingContext context ) //// { //// if(info == null) //// { //// throw new ArgumentNullException( "info" ); //// } //// //// Boolean foundTicks = false; //// Boolean foundDateData = false; //// Int64 serializedTicks = 0; //// UInt64 serializedDateData = 0; //// //// //// // Get the data //// SerializationInfoEnumerator enumerator = info.GetEnumerator(); //// while(enumerator.MoveNext()) //// { //// switch(enumerator.Name) //// { //// case TicksField: //// serializedTicks = Convert.ToInt64( enumerator.Value, CultureInfo.InvariantCulture ); //// foundTicks = true; //// break; //// //// case DateDataField: //// serializedDateData = Convert.ToUInt64( enumerator.Value, CultureInfo.InvariantCulture ); //// foundDateData = true; //// break; //// //// default: //// // Ignore other fields for forward compatability. //// break; //// } //// } //// //// if(foundDateData) //// { //// this.dateData = serializedDateData; //// } //// else if(foundTicks) //// { //// this.dateData = (UInt64)serializedTicks; //// } //// else //// { //// throw new SerializationException( Environment.GetResourceString( "Serialization_MissingDateTimeData" ) ); //// } //// //// Int64 ticks = InternalTicks; //// if(ticks < MinTicks || ticks > MaxTicks) //// { //// throw new SerializationException( Environment.GetResourceString( "Serialization_DateTimeTicksOutOfRange" ) ); //// } //// } private Int64 InternalTicks { get { return (Int64)(dateData & TicksMask); } } private UInt64 InternalKind { get { return (dateData & FlagsMask); } } // Returns the DateTime resulting from adding the given // TimeSpan to this DateTime. // public DateTime Add( TimeSpan value ) { return AddTicks( value.Ticks ); } // Returns the DateTime resulting from adding a fractional number of // time units to this DateTime. private DateTime Add( double value, int scale ) { long millis = (long)(value * scale + (value >= 0 ? 0.5 : -0.5)); if(millis <= -MaxMillis || millis >= MaxMillis) { #if EXCEPTION_STRINGS throw new ArgumentOutOfRangeException( "value", Environment.GetResourceString( "ArgumentOutOfRange_AddValue" ) ); #else throw new ArgumentOutOfRangeException(); #endif } return AddTicks( millis * TicksPerMillisecond ); } // Returns the DateTime resulting from adding a fractional number of // days to this DateTime. The result is computed by rounding the // fractional number of days given by value to the nearest // millisecond, and adding that interval to this DateTime. The // value argument is permitted to be negative. // public DateTime AddDays( double value ) { return Add( value, MillisPerDay ); } // Returns the DateTime resulting from adding a fractional number of // hours to this DateTime. The result is computed by rounding the // fractional number of hours given by value to the nearest // millisecond, and adding that interval to this DateTime. The // value argument is permitted to be negative. // public DateTime AddHours( double value ) { return Add( value, MillisPerHour ); } // Returns the DateTime resulting from the given number of // milliseconds to this DateTime. The result is computed by rounding // the number of milliseconds given by value to the nearest integer, // and adding that interval to this DateTime. The value // argument is permitted to be negative. // public DateTime AddMilliseconds( double value ) { return Add( value, 1 ); } // Returns the DateTime resulting from adding a fractional number of // minutes to this DateTime. The result is computed by rounding the // fractional number of minutes given by value to the nearest // millisecond, and adding that interval to this DateTime. The // value argument is permitted to be negative. // public DateTime AddMinutes( double value ) { return Add( value, MillisPerMinute ); } // Returns the DateTime resulting from adding the given number of // months to this DateTime. The result is computed by incrementing // (or decrementing) the year and month parts of this DateTime by // months months, and, if required, adjusting the day part of the // resulting date downwards to the last day of the resulting month in the // resulting year. The time-of-day part of the result is the same as the // time-of-day part of this DateTime. // // In more precise terms, considering this DateTime to be of the // form y / m / d + t, where y is the // year, m is the month, d is the day, and t is the // time-of-day, the result is y1 / m1 / d1 + t, // where y1 and m1 are computed by adding months months // to y and m, and d1 is the largest value less than // or equal to d that denotes a valid day in month m1 of year // y1. // public DateTime AddMonths( int months ) { if(months < -120000 || months > 120000) { #if EXCEPTION_STRINGS throw new ArgumentOutOfRangeException( "months", Environment.GetResourceString( "ArgumentOutOfRange_DateTimeBadMonths" ) ); #else throw new ArgumentOutOfRangeException(); #endif } int y = GetDatePart( DatePartYear ); int m = GetDatePart( DatePartMonth ); int d = GetDatePart( DatePartDay ); int i = m - 1 + months; if(i >= 0) { m = i % 12 + 1; y = y + i / 12; } else { m = 12 + (i + 1) % 12; y = y + (i - 11) / 12; } if(y < 1 || y > 9999) { #if EXCEPTION_STRINGS throw new ArgumentOutOfRangeException( "months", Environment.GetResourceString( "ArgumentOutOfRange_DateArithmetic" ) ); #else throw new ArgumentOutOfRangeException(); #endif } int days = DaysInMonth( y, m ); if(d > days) d = days; return new DateTime( (UInt64)(DateToTicks( y, m, d ) + InternalTicks % TicksPerDay) | InternalKind ); } // Returns the DateTime resulting from adding a fractional number of // seconds to this DateTime. The result is computed by rounding the // fractional number of seconds given by value to the nearest // millisecond, and adding that interval to this DateTime. The // value argument is permitted to be negative. // public DateTime AddSeconds( double value ) { return Add( value, MillisPerSecond ); } // Returns the DateTime resulting from adding the given number of // 100-nanosecond ticks to this DateTime. The value argument // is permitted to be negative. // public DateTime AddTicks( long value ) { long ticks = InternalTicks; if(value > MaxTicks - ticks || value < MinTicks - ticks) { #if EXCEPTION_STRINGS throw new ArgumentOutOfRangeException( "value", Environment.GetResourceString( "ArgumentOutOfRange_DateArithmetic" ) ); #else throw new ArgumentOutOfRangeException(); #endif } return new DateTime( (UInt64)(ticks + value) | InternalKind ); } // Returns the DateTime resulting from adding the given number of // years to this DateTime. The result is computed by incrementing // (or decrementing) the year part of this DateTime by value // years. If the month and day of this DateTime is 2/29, and if the // resulting year is not a leap year, the month and day of the resulting // DateTime becomes 2/28. Otherwise, the month, day, and time-of-day // parts of the result are the same as those of this DateTime. // public DateTime AddYears( int value ) { if(value < -10000 || value > 10000) { #if EXCEPTION_STRINGS throw new ArgumentOutOfRangeException( "years", Environment.GetResourceString( "ArgumentOutOfRange_DateTimeBadYears" ) ); #else throw new ArgumentOutOfRangeException(); #endif } return AddMonths( value * 12 ); } // Compares two DateTime values, returning an integer that indicates // their relationship. // public static int Compare( DateTime t1, DateTime t2 ) { Int64 ticks1 = t1.InternalTicks; Int64 ticks2 = t2.InternalTicks; if(ticks1 > ticks2) return 1; if(ticks1 < ticks2) return -1; return 0; } // Compares this DateTime to a given object. This method provides an // implementation of the IComparable interface. The object // argument must be another DateTime, or otherwise an exception // occurs. Null is considered less than any instance. // // Returns a value less than zero if this object public int CompareTo( Object value ) { if(value == null) return 1; if(!(value is DateTime)) { #if EXCEPTION_STRINGS throw new ArgumentException( Environment.GetResourceString( "Arg_MustBeDateTime" ) ); #else throw new ArgumentException(); #endif } return CompareTo( (DateTime)value ); } public int CompareTo( DateTime value ) { long valueTicks = value.InternalTicks; long ticks = InternalTicks; if(ticks > valueTicks) return 1; if(ticks < valueTicks) return -1; return 0; } // Returns the tick count corresponding to the given year, month, and day. // Will check the if the parameters are valid. private static long DateToTicks( int year, int month, int day ) { if(year >= 1 && year <= 9999 && month >= 1 && month <= 12) { int[] days = IsLeapYear( year ) ? DaysToMonth366 : DaysToMonth365; if(day >= 1 && day <= days[month] - days[month - 1]) { int y = year - 1; int n = y * 365 + y / 4 - y / 100 + y / 400 + days[month - 1] + day - 1; return n * TicksPerDay; } } #if EXCEPTION_STRINGS throw new ArgumentOutOfRangeException( null, Environment.GetResourceString( "ArgumentOutOfRange_BadYearMonthDay" ) ); #else throw new ArgumentOutOfRangeException(); #endif } // Return the tick count corresponding to the given hour, minute, second. // Will check the if the parameters are valid. private static long TimeToTicks( int hour, int minute, int second ) { //TimeSpan.TimeToTicks is a family access function which does no error checking, so //we need to put some error checking out here. if(hour >= 0 && hour < 24 && minute >= 0 && minute < 60 && second >= 0 && second < 60) { return (TimeSpan.TimeToTicks( hour, minute, second )); } #if EXCEPTION_STRINGS throw new ArgumentOutOfRangeException( null, Environment.GetResourceString( "ArgumentOutOfRange_BadHourMinuteSecond" ) ); #else throw new ArgumentOutOfRangeException(); #endif } // Returns the number of days in the month given by the year and // month arguments. // public static int DaysInMonth( int year, int month ) { if(month < 1 || month > 12) { #if EXCEPTION_STRINGS throw new ArgumentOutOfRangeException( "month", Environment.GetResourceString( "ArgumentOutOfRange_Month" ) ); #else throw new ArgumentOutOfRangeException(); #endif } // IsLeapYear checks the year argument int[] days = IsLeapYear( year ) ? DaysToMonth366 : DaysToMonth365; return days[month] - days[month - 1]; } //// // Converts an OLE Date to a tick count. //// // This function is duplicated in COMDateTime.cpp //// internal static long DoubleDateToTicks( double value ) //// { //// if(value >= OADateMaxAsDouble || value <= OADateMinAsDouble) //// { //// throw new ArgumentException( Environment.GetResourceString( "Arg_OleAutDateInvalid" ) ); //// } //// //// long millis = (long)(value * MillisPerDay + (value >= 0 ? 0.5 : -0.5)); //// // The interesting thing here is when you have a value like 12.5 it all positive 12 days and 12 hours from 01/01/1899 //// // However if you a value of -12.25 it is minus 12 days but still positive 6 hours, almost as though you meant -11.75 all negative //// // This line below fixes up the millis in the negative case //// if(millis < 0) //// { //// millis -= (millis % MillisPerDay) * 2; //// } //// //// millis += DoubleDateOffset / TicksPerMillisecond; //// //// if(millis < 0 || millis >= MaxMillis) //// { //// throw new ArgumentException( Environment.GetResourceString( "Arg_OleAutDateScale" ) ); //// } //// //// return millis * TicksPerMillisecond; //// } // Checks if this DateTime is equal to a given object. Returns // true if the given object is a boxed DateTime and its value // is equal to the value of this DateTime. Returns false // otherwise. // public override bool Equals( Object value ) { if(value is DateTime) { return InternalTicks == ((DateTime)value).InternalTicks; } return false; } public bool Equals( DateTime value ) { return InternalTicks == value.InternalTicks; } // Compares two DateTime values for equality. Returns true if // the two DateTime values are equal, or false if they are // not equal. // public static bool Equals( DateTime t1, DateTime t2 ) { return t1.InternalTicks == t2.InternalTicks; } //// public static DateTime FromBinary( Int64 dateData ) //// { //// if((dateData & (unchecked( (Int64)LocalMask ))) != 0) //// { //// // Local times need to be adjusted as you move from one time zone to another, //// // just as they are when serializing in text. As such the format for local times //// // changes to store the ticks of the UTC time, but with flags that look like a //// // local date. //// Int64 ticks = dateData & (unchecked( (Int64)TicksMask )); //// // Negative ticks are stored in the top part of the range and should be converted back into a negative number //// if(ticks > TicksCeiling - TicksPerDay) //// { //// ticks = ticks - TicksCeiling; //// } //// // Convert the ticks back to local. If the UTC ticks are out of range, we need to default to //// // the UTC offset from MinValue and MaxValue to be consistent with Parse. //// Boolean isAmbiguousLocalDst = false; //// Int64 offsetTicks; //// if(ticks < MinTicks) //// { //// offsetTicks = TimeZone.CurrentTimeZone.GetUtcOffset( DateTime.MinValue ).Ticks; //// } //// else if(ticks > MaxTicks) //// { //// offsetTicks = TimeZone.CurrentTimeZone.GetUtcOffset( DateTime.MaxValue ).Ticks; //// } //// else //// { //// // Because the ticks conversion between UTC and local is lossy, we need to capture whether the //// // time is in a repeated hour so that it can be passed to the DateTime constructor. //// CurrentSystemTimeZone tz = (CurrentSystemTimeZone)TimeZone.CurrentTimeZone; //// //// offsetTicks = tz.GetUtcOffsetFromUniversalTime( new DateTime( ticks ), ref isAmbiguousLocalDst ); //// } //// //// ticks += offsetTicks; //// // Another behaviour of parsing is to cause small times to wrap around, so that they can be used //// // to compare times of day //// if(ticks < 0) //// { //// ticks += TicksPerDay; //// } //// if(ticks < MinTicks || ticks > MaxTicks) //// { //// throw new ArgumentException( Environment.GetResourceString( "Argument_DateTimeBadBinaryData" ), "dateData" ); //// } //// //// return new DateTime( ticks, DateTimeKind.Local, isAmbiguousLocalDst ); //// } //// else //// { //// return DateTime.FromBinaryRaw( dateData ); //// } //// } //// //// // A version of ToBinary that uses the real representation and does not adjust local times. This is needed for //// // scenarios where the serialized data must maintain compatability //// internal static DateTime FromBinaryRaw( Int64 dateData ) //// { //// Int64 ticks = dateData & (Int64)TicksMask; //// if(ticks < MinTicks || ticks > MaxTicks) //// { //// throw new ArgumentException( Environment.GetResourceString( "Argument_DateTimeBadBinaryData" ), "dateData" ); //// } //// //// return new DateTime( (UInt64)dateData ); //// } //// //// // Creates a DateTime from a Windows filetime. A Windows filetime is //// // a long representing the date and time as the number of //// // 100-nanosecond intervals that have elapsed since 1/1/1601 12:00am. //// // //// public static DateTime FromFileTime( long fileTime ) //// { //// return FromFileTimeUtc( fileTime ).ToLocalTime(); //// } //// //// public static DateTime FromFileTimeUtc( long fileTime ) //// { //// if(fileTime < 0 || fileTime > MaxTicks - FileTimeOffset) //// { //// throw new ArgumentOutOfRangeException( "fileTime", Environment.GetResourceString( "ArgumentOutOfRange_FileTimeInvalid" ) ); //// } //// //// // This is the ticks in Universal time for this fileTime. //// long universalTicks = fileTime + FileTimeOffset; //// //// return new DateTime( universalTicks, DateTimeKind.Utc ); //// } //// //// // Creates a DateTime from an OLE Automation Date. //// // //// public static DateTime FromOADate( double d ) //// { //// return new DateTime( DoubleDateToTicks( d ), DateTimeKind.Unspecified ); //// } //// //// [SecurityPermissionAttribute( SecurityAction.LinkDemand, Flags = SecurityPermissionFlag.SerializationFormatter )] //// void ISerializable.GetObjectData( SerializationInfo info, StreamingContext context ) //// { //// if(info == null) //// { //// throw new ArgumentNullException( "info" ); //// } //// //// // Serialize both the old and the new format //// info.AddValue( TicksField , InternalTicks ); //// info.AddValue( DateDataField, dateData ); //// } public Boolean IsDaylightSavingTime() { return TimeZone.CurrentTimeZone.IsDaylightSavingTime( this ); } public static DateTime SpecifyKind( DateTime value, DateTimeKind kind ) { return new DateTime( value.InternalTicks, kind ); } //// public Int64 ToBinary() //// { //// if(Kind == DateTimeKind.Local) //// { //// // Local times need to be adjusted as you move from one time zone to another, //// // just as they are when serializing in text. As such the format for local times //// // changes to store the ticks of the UTC time, but with flags that look like a //// // local date. //// //// // To match serialization in text we need to be able to handle cases where //// // the UTC value would be out of range. Unused parts of the ticks range are //// // used for this, so that values just past max value are stored just past the //// // end of the maximum range, and values just below minimum value are stored //// // at the end of the ticks area, just below 2^62. //// TimeSpan offset = TimeZone.CurrentTimeZone.GetUtcOffset( this ); //// Int64 ticks = Ticks; //// Int64 storedTicks = ticks - offset.Ticks; //// //// if(storedTicks < 0) //// { //// storedTicks = TicksCeiling + storedTicks; //// } //// //// return storedTicks | (unchecked( (Int64)LocalMask )); //// } //// else //// { //// return (Int64)dateData; //// } //// } //// //// // Return the underlying data, without adjust local times to the right time zone. Needed if performance //// // or compatability are important. //// internal Int64 ToBinaryRaw() //// { //// return (Int64)dateData; //// } // Returns the date part of this DateTime. The resulting value // corresponds to this DateTime with the time-of-day part set to // zero (midnight). // public DateTime Date { get { Int64 ticks = InternalTicks; return new DateTime( (UInt64)(ticks - ticks % TicksPerDay) | InternalKind ); } } // Returns a given date part of this DateTime. This method is used // to compute the year, day-of-year, month, or day part. private int GetDatePart( int part ) { Int64 ticks = InternalTicks; // n = number of days since 1/1/0001 int n = (int)(ticks / TicksPerDay); // y400 = number of whole 400-year periods since 1/1/0001 int y400 = n / DaysPer400Years; // n = day number within 400-year period n -= y400 * DaysPer400Years; // y100 = number of whole 100-year periods within 400-year period int y100 = n / DaysPer100Years; // Last 100-year period has an extra day, so decrement result if 4 if(y100 == 4) y100 = 3; // n = day number within 100-year period n -= y100 * DaysPer100Years; // y4 = number of whole 4-year periods within 100-year period int y4 = n / DaysPer4Years; // n = day number within 4-year period n -= y4 * DaysPer4Years; // y1 = number of whole years within 4-year period int y1 = n / DaysPerYear; // Last year has an extra day, so decrement result if 4 if(y1 == 4) y1 = 3; // If year was requested, compute and return it if(part == DatePartYear) { return y400 * 400 + y100 * 100 + y4 * 4 + y1 + 1; } // n = day number within year n -= y1 * DaysPerYear; // If day-of-year was requested, return it if(part == DatePartDayOfYear) return n + 1; // Leap year calculation looks different from IsLeapYear since y1, y4, // and y100 are relative to year 1, not year 0 bool leapYear = y1 == 3 && (y4 != 24 || y100 == 3); int[] days = leapYear ? DaysToMonth366 : DaysToMonth365; // All months have less than 32 days, so n >> 5 is a good conservative // estimate for the month int m = n >> 5 + 1; // m = 1-based month number while(n >= days[m]) m++; // If month was requested, return it if(part == DatePartMonth) return m; // Return 1-based day-of-month return n - days[m - 1] + 1; } // Returns the day-of-month part of this DateTime. The returned // value is an integer between 1 and 31. // public int Day { get { return GetDatePart( DatePartDay ); } } // Returns the day-of-week part of this DateTime. The returned value // is an integer between 0 and 6, where 0 indicates Sunday, 1 indicates // Monday, 2 indicates Tuesday, 3 indicates Wednesday, 4 indicates // Thursday, 5 indicates Friday, and 6 indicates Saturday. // public DayOfWeek DayOfWeek { get { return (DayOfWeek)((InternalTicks / TicksPerDay + 1) % 7); } } // Returns the day-of-year part of this DateTime. The returned value // is an integer between 1 and 366. // public int DayOfYear { get { return GetDatePart( DatePartDayOfYear ); } } // Returns the hash code for this DateTime. // public override int GetHashCode() { Int64 ticks = InternalTicks; return unchecked( (int)ticks ) ^ (int)(ticks >> 32); } // Returns the hour part of this DateTime. The returned value is an // integer between 0 and 23. // public int Hour { get { return (int)((InternalTicks / TicksPerHour) % 24); } } internal Boolean IsAmbiguousDaylightSavingTime() { return (InternalKind == KindLocalAmbiguousDst); } public DateTimeKind Kind { get { switch(InternalKind) { case KindUnspecified: return DateTimeKind.Unspecified; case KindUtc: return DateTimeKind.Utc; default: return DateTimeKind.Local; } } } // Returns the millisecond part of this DateTime. The returned value // is an integer between 0 and 999. // public int Millisecond { get { return (int)((InternalTicks / TicksPerMillisecond) % 1000); } } // Returns the minute part of this DateTime. The returned value is // an integer between 0 and 59. // public int Minute { get { return (int)((InternalTicks / TicksPerMinute) % 60); } } // Returns the month part of this DateTime. The returned value is an // integer between 1 and 12. // public int Month { get { return GetDatePart( DatePartMonth ); } } // Returns a DateTime representing the current date and time. The // resolution of the returned value depends on the system timer. For // Windows NT 3.5 and later the timer resolution is approximately 10ms, // for Windows NT 3.1 it is approximately 16ms, and for Windows 95 and 98 // it is approximately 55ms. // public static DateTime Now { get { return UtcNow.ToLocalTime(); } } public static DateTime UtcNow { get { return new DateTime( GetSystemTimeAsDateTimeTicks() | KindUtc ); //// // following code is tuned for speed. Don't change it without running benchmark. //// long ticks = GetSystemTimeAsFileTime(); //// //// return new DateTime( ((UInt64)(ticks + FileTimeOffset)) | KindUtc ); } } [MethodImpl( MethodImplOptions.InternalCall )] internal static extern ulong GetSystemTimeAsDateTimeTicks(); //// [MethodImpl( MethodImplOptions.InternalCall )] //// internal static extern long GetSystemTimeAsFileTime(); //// //// // Returns the second part of this DateTime. The returned value is // an integer between 0 and 59. // public int Second { get { return (int)((InternalTicks / TicksPerSecond) % 60); } } // Returns the tick count for this DateTime. The returned value is // the number of 100-nanosecond intervals that have elapsed since 1/1/0001 // 12:00am. // public long Ticks { get { return InternalTicks; } } // Returns the time-of-day part of this DateTime. The returned value // is a TimeSpan that indicates the time elapsed since midnight. // public TimeSpan TimeOfDay { get { return new TimeSpan( InternalTicks % TicksPerDay ); } } // Returns a DateTime representing the current date. The date part // of the returned value is the current date, and the time-of-day part of // the returned value is zero (midnight). // public static DateTime Today { get { return DateTime.Now.Date; } } // Returns the year part of this DateTime. The returned value is an // integer between 1 and 9999. // public int Year { get { return GetDatePart( DatePartYear ); } } // Checks whether a given year is a leap year. This method returns true if // year is a leap year, or false if not. // public static bool IsLeapYear( int year ) { if(year < 1 || year > 9999) { #if EXCEPTION_STRINGS throw new ArgumentOutOfRangeException( "year", Environment.GetResourceString( "ArgumentOutOfRange_Year" ) ); #else throw new ArgumentOutOfRangeException(); #endif } return year % 4 == 0 && (year % 100 != 0 || year % 400 == 0); } // Constructs a DateTime from a string. The string must specify a // date and optionally a time in a culture-specific or universal format. // Leading and trailing whitespace characters are allowed. // public static DateTime Parse( String s ) { return (DateTimeParse.Parse( s, DateTimeFormatInfo.CurrentInfo, DateTimeStyles.None )); } // Constructs a DateTime from a string. The string must specify a // date and optionally a time in a culture-specific or universal format. // Leading and trailing whitespace characters are allowed. // public static DateTime Parse( String s , IFormatProvider provider ) { return (DateTimeParse.Parse( s, DateTimeFormatInfo.GetInstance( provider ), DateTimeStyles.None )); } public static DateTime Parse( String s , IFormatProvider provider , DateTimeStyles styles ) { DateTimeFormatInfo.ValidateStyles( styles, "styles" ); return (DateTimeParse.Parse( s, DateTimeFormatInfo.GetInstance( provider ), styles )); } // Constructs a DateTime from a string. The string must specify a // date and optionally a time in a culture-specific or universal format. // Leading and trailing whitespace characters are allowed. // public static DateTime ParseExact( String s , String format , IFormatProvider provider ) { return (DateTimeParse.ParseExact( s, format, DateTimeFormatInfo.GetInstance( provider ), DateTimeStyles.None )); } // Constructs a DateTime from a string. The string must specify a // date and optionally a time in a culture-specific or universal format. // Leading and trailing whitespace characters are allowed. // public static DateTime ParseExact( String s , String format , IFormatProvider provider , DateTimeStyles style ) { DateTimeFormatInfo.ValidateStyles( style, "style" ); return (DateTimeParse.ParseExact( s, format, DateTimeFormatInfo.GetInstance( provider ), style )); } public static DateTime ParseExact( String s , String[] formats , IFormatProvider provider , DateTimeStyles style ) { DateTimeFormatInfo.ValidateStyles( style, "style" ); return DateTimeParse.ParseExactMultiple( s, formats, DateTimeFormatInfo.GetInstance( provider ), style ); } public TimeSpan Subtract( DateTime value ) { return new TimeSpan( InternalTicks - value.InternalTicks ); } public DateTime Subtract( TimeSpan value ) { long ticks = InternalTicks; long valueTicks = value.Ticks; if(ticks - MinTicks < valueTicks || ticks - MaxTicks > valueTicks) { #if EXCEPTION_STRINGS throw new ArgumentOutOfRangeException( "value", Environment.GetResourceString( "ArgumentOutOfRange_DateArithmetic" ) ); #else throw new ArgumentOutOfRangeException(); #endif } return new DateTime( (UInt64)(ticks - valueTicks) | InternalKind ); } //// // This function is duplicated in COMDateTime.cpp //// private static double TicksToOADate( long value ) //// { //// if(value == 0) //// { //// return 0.0; // Returns OleAut's zero'ed date value. //// } //// //// if(value < TicksPerDay) // This is a fix for VB. They want the default day to be 1/1/0001 rathar then 12/30/1899. //// { //// value += DoubleDateOffset; // We could have moved this fix down but we would like to keep the bounds check. //// } //// //// if(value < OADateMinAsTicks) //// { //// throw new OverflowException( Environment.GetResourceString( "Arg_OleAutDateInvalid" ) ); //// } //// //// // Currently, our max date == OA's max date (12/31/9999), so we don't //// // need an overflow check in that direction. //// long millis = (value - DoubleDateOffset) / TicksPerMillisecond; //// if(millis < 0) //// { //// long frac = millis % MillisPerDay; //// //// if(frac != 0) millis -= (MillisPerDay + frac) * 2; //// } //// //// return (double)millis / MillisPerDay; //// } //// //// // Converts the DateTime instance into an OLE Automation compatible //// // double date. //// public double ToOADate() //// { //// return TicksToOADate( InternalTicks ); //// } //// //// public long ToFileTime() //// { //// // Treats the input as local if it is not specified //// return ToUniversalTime().ToFileTimeUtc(); //// } //// //// public long ToFileTimeUtc() //// { //// // Treats the input as universal if it is not specified //// long ticks = ((InternalKind & LocalMask) != 0) ? ToUniversalTime().InternalTicks : this.InternalTicks; //// ticks -= FileTimeOffset; //// if(ticks < 0) //// { //// throw new ArgumentOutOfRangeException( null, Environment.GetResourceString( "ArgumentOutOfRange_FileTimeInvalid" ) ); //// } //// //// return ticks; //// } //// public DateTime ToLocalTime() { return TimeZone.CurrentTimeZone.ToLocalTime( this ); } //// public String ToLongDateString() //// { //// return DateTimeFormat.Format( this, "D", DateTimeFormatInfo.CurrentInfo ); //// } //// //// public String ToLongTimeString() //// { //// return DateTimeFormat.Format( this, "T", DateTimeFormatInfo.CurrentInfo ); //// } //// //// public String ToShortDateString() //// { //// return DateTimeFormat.Format( this, "d", DateTimeFormatInfo.CurrentInfo ); //// } //// //// public String ToShortTimeString() //// { //// return DateTimeFormat.Format( this, "t", DateTimeFormatInfo.CurrentInfo ); //// } public override String ToString() { return DateTimeFormat.Format( this, /*null,*/ DateTimeFormatInfo.CurrentInfo ); } public String ToString( String format ) { return DateTimeFormat.Format( this, format, DateTimeFormatInfo.CurrentInfo ); } public String ToString( IFormatProvider provider ) { return DateTimeFormat.Format( this, /*null,*/ DateTimeFormatInfo.GetInstance( provider ) ); } //// public String ToString( String format, IFormatProvider provider ) //// { //// return DateTimeFormat.Format( this, format, DateTimeFormatInfo.GetInstance( provider ) ); //// } //// //// public DateTime ToUniversalTime() //// { //// return TimeZone.CurrentTimeZone.ToUniversalTime( this ); //// } //// //// public static Boolean TryParse( String s, out DateTime result ) //// { //// return DateTimeParse.TryParse( s, DateTimeFormatInfo.CurrentInfo, DateTimeStyles.None, out result ); //// } //// //// public static Boolean TryParse( String s, IFormatProvider provider, DateTimeStyles styles, out DateTime result ) //// { //// DateTimeFormatInfo.ValidateStyles( styles, "styles" ); //// //// return DateTimeParse.TryParse( s, DateTimeFormatInfo.GetInstance( provider ), styles, out result ); //// } //// //// public static Boolean TryParseExact( String s, String format, IFormatProvider provider, DateTimeStyles style, out DateTime result ) //// { //// DateTimeFormatInfo.ValidateStyles( style, "style" ); //// //// return DateTimeParse.TryParseExact( s, format, DateTimeFormatInfo.GetInstance( provider ), style, out result ); //// } //// //// public static Boolean TryParseExact( String s, String[] formats, IFormatProvider provider, DateTimeStyles style, out DateTime result ) //// { //// DateTimeFormatInfo.ValidateStyles( style, "style" ); //// //// return DateTimeParse.TryParseExactMultiple( s, formats, DateTimeFormatInfo.GetInstance( provider ), style, out result ); //// } public static DateTime operator +( DateTime d, TimeSpan t ) { long ticks = d.InternalTicks; long valueTicks = t.Ticks; if(valueTicks > MaxTicks - ticks || valueTicks < MinTicks - ticks) { #if EXCEPTION_STRINGS throw new ArgumentOutOfRangeException( "t", Environment.GetResourceString( "ArgumentOutOfRange_DateArithmetic" ) ); #else throw new ArgumentOutOfRangeException(); #endif } return new DateTime( (UInt64)(ticks + valueTicks) | d.InternalKind ); } public static DateTime operator -( DateTime d, TimeSpan t ) { long ticks = d.InternalTicks; long valueTicks = t.Ticks; if(ticks - MinTicks < valueTicks || ticks - MaxTicks > valueTicks) { #if EXCEPTION_STRINGS throw new ArgumentOutOfRangeException( "t", Environment.GetResourceString( "ArgumentOutOfRange_DateArithmetic" ) ); #else throw new ArgumentOutOfRangeException(); #endif } return new DateTime( (UInt64)(ticks - valueTicks) | d.InternalKind ); } public static TimeSpan operator -( DateTime d1, DateTime d2 ) { return new TimeSpan( d1.InternalTicks - d2.InternalTicks ); } public static bool operator ==( DateTime d1, DateTime d2 ) { return d1.InternalTicks == d2.InternalTicks; } public static bool operator !=( DateTime d1, DateTime d2 ) { return d1.InternalTicks != d2.InternalTicks; } public static bool operator <( DateTime t1, DateTime t2 ) { return t1.InternalTicks < t2.InternalTicks; } public static bool operator <=( DateTime t1, DateTime t2 ) { return t1.InternalTicks <= t2.InternalTicks; } public static bool operator >( DateTime t1, DateTime t2 ) { return t1.InternalTicks > t2.InternalTicks; } public static bool operator >=( DateTime t1, DateTime t2 ) { return t1.InternalTicks >= t2.InternalTicks; } //// // Returns a string array containing all of the known date and time options for the //// // current culture. The strings returned are properly formatted date and //// // time strings for the current instance of DateTime. //// public String[] GetDateTimeFormats() //// { //// return (GetDateTimeFormats( CultureInfo.CurrentCulture )); //// } //// //// // Returns a string array containing all of the known date and time options for the //// // using the information provided by IFormatProvider. The strings returned are properly formatted date and //// // time strings for the current instance of DateTime. //// public String[] GetDateTimeFormats( IFormatProvider provider ) //// { //// return (DateTimeFormat.GetAllDateTimes( this, DateTimeFormatInfo.GetInstance( provider ) )); //// } //// //// //// // Returns a string array containing all of the date and time options for the //// // given format format and current culture. The strings returned are properly formatted date and //// // time strings for the current instance of DateTime. //// public String[] GetDateTimeFormats( char format ) //// { //// return (GetDateTimeFormats( format, CultureInfo.CurrentCulture )); //// } //// //// // Returns a string array containing all of the date and time options for the //// // given format format and given culture. The strings returned are properly formatted date and //// // time strings for the current instance of DateTime. //// public String[] GetDateTimeFormats( char format, IFormatProvider provider ) //// { //// return (DateTimeFormat.GetAllDateTimes( this, format, DateTimeFormatInfo.GetInstance( provider ) )); //// } #region IConvertible public TypeCode GetTypeCode() { return TypeCode.DateTime; } /// bool IConvertible.ToBoolean( IFormatProvider provider ) { #if EXCEPTION_STRINGS throw new InvalidCastException( String.Format( CultureInfo.CurrentCulture, Environment.GetResourceString( "InvalidCast_FromTo" ), "DateTime", "Boolean" ) ); #else throw new InvalidCastException(); #endif } /// char IConvertible.ToChar( IFormatProvider provider ) { #if EXCEPTION_STRINGS throw new InvalidCastException( String.Format( CultureInfo.CurrentCulture, Environment.GetResourceString( "InvalidCast_FromTo" ), "DateTime", "Char" ) ); #else throw new InvalidCastException(); #endif } /// sbyte IConvertible.ToSByte( IFormatProvider provider ) { #if EXCEPTION_STRINGS throw new InvalidCastException( String.Format( CultureInfo.CurrentCulture, Environment.GetResourceString( "InvalidCast_FromTo" ), "DateTime", "SByte" ) ); #else throw new InvalidCastException(); #endif } /// byte IConvertible.ToByte( IFormatProvider provider ) { #if EXCEPTION_STRINGS throw new InvalidCastException( String.Format( CultureInfo.CurrentCulture, Environment.GetResourceString( "InvalidCast_FromTo" ), "DateTime", "Byte" ) ); #else throw new InvalidCastException(); #endif } /// short IConvertible.ToInt16( IFormatProvider provider ) { #if EXCEPTION_STRINGS throw new InvalidCastException( String.Format( CultureInfo.CurrentCulture, Environment.GetResourceString( "InvalidCast_FromTo" ), "DateTime", "Int16" ) ); #else throw new InvalidCastException(); #endif } /// ushort IConvertible.ToUInt16( IFormatProvider provider ) { #if EXCEPTION_STRINGS throw new InvalidCastException( String.Format( CultureInfo.CurrentCulture, Environment.GetResourceString( "InvalidCast_FromTo" ), "DateTime", "UInt16" ) ); #else throw new InvalidCastException(); #endif } /// int IConvertible.ToInt32( IFormatProvider provider ) { #if EXCEPTION_STRINGS throw new InvalidCastException( String.Format( CultureInfo.CurrentCulture, Environment.GetResourceString( "InvalidCast_FromTo" ), "DateTime", "Int32" ) ); #else throw new InvalidCastException(); #endif } /// uint IConvertible.ToUInt32( IFormatProvider provider ) { #if EXCEPTION_STRINGS throw new InvalidCastException( String.Format( CultureInfo.CurrentCulture, Environment.GetResourceString( "InvalidCast_FromTo" ), "DateTime", "UInt32" ) ); #else throw new InvalidCastException(); #endif } /// long IConvertible.ToInt64( IFormatProvider provider ) { #if EXCEPTION_STRINGS throw new InvalidCastException( String.Format( CultureInfo.CurrentCulture, Environment.GetResourceString( "InvalidCast_FromTo" ), "DateTime", "Int64" ) ); #else throw new InvalidCastException(); #endif } /// ulong IConvertible.ToUInt64( IFormatProvider provider ) { #if EXCEPTION_STRINGS throw new InvalidCastException( String.Format( CultureInfo.CurrentCulture, Environment.GetResourceString( "InvalidCast_FromTo" ), "DateTime", "UInt64" ) ); #else throw new InvalidCastException(); #endif } /// float IConvertible.ToSingle( IFormatProvider provider ) { #if EXCEPTION_STRINGS throw new InvalidCastException( String.Format( CultureInfo.CurrentCulture, Environment.GetResourceString( "InvalidCast_FromTo" ), "DateTime", "Single" ) ); #else throw new InvalidCastException(); #endif } /// double IConvertible.ToDouble( IFormatProvider provider ) { #if EXCEPTION_STRINGS throw new InvalidCastException( String.Format( CultureInfo.CurrentCulture, Environment.GetResourceString( "InvalidCast_FromTo" ), "DateTime", "Double" ) ); #else throw new InvalidCastException(); #endif } /// Decimal IConvertible.ToDecimal( IFormatProvider provider ) { #if EXCEPTION_STRINGS throw new InvalidCastException( String.Format( CultureInfo.CurrentCulture, Environment.GetResourceString( "InvalidCast_FromTo" ), "DateTime", "Decimal" ) ); #else throw new InvalidCastException(); #endif } /// DateTime IConvertible.ToDateTime( IFormatProvider provider ) { return this; } /// Object IConvertible.ToType( Type type, IFormatProvider provider ) { return Convert.DefaultToType( (IConvertible)this, type, provider ); } #endregion // Tries to construct a DateTime from a given year, month, day, hour, // minute, second and millisecond. // internal static Boolean TryCreate( int year, int month, int day, int hour, int minute, int second, int millisecond, out DateTime result ) { result = DateTime.MinValue; if(year < 1 || year > 9999 || month < 1 || month > 12) { return false; } int[] days = IsLeapYear( year ) ? DaysToMonth366 : DaysToMonth365; if(day < 1 || day > days[month] - days[month - 1]) { return false; } if(hour < 0 || hour >= 24 || minute < 0 || minute >= 60 || second < 0 || second >= 60) { return false; } if(millisecond < 0 || millisecond >= MillisPerSecond) { return false; } long ticks = DateToTicks( year, month, day ) + TimeToTicks( hour, minute, second ); ticks += millisecond * TicksPerMillisecond; if(ticks < MinTicks || ticks > MaxTicks) { return false; } result = new DateTime( ticks, DateTimeKind.Unspecified ); return true; } } } ================================================ FILE: Zelig/Zelig/RunTime/Framework/mscorlib/System/DateTimeKind.cs ================================================ // ==++== // // Copyright (c) Microsoft Corporation. All rights reserved. // // ==--== namespace System { // This enum is used to indentify DateTime instances in cases when they are known to be in local time, // UTC time or if this information has not been specified or is not applicable. [Serializable] public enum DateTimeKind { Unspecified = 0, Utc = 1, Local = 2, } } ================================================ FILE: Zelig/Zelig/RunTime/Framework/mscorlib/System/DayOfWeek.cs ================================================ // ==++== // // Copyright (c) Microsoft Corporation. All rights reserved. // // ==--== /*============================================================ ** ** Class: DayOfWeek ** ** ** Purpose: Enum for the day of the week. ** ** ============================================================*/ namespace System { [Serializable] public enum DayOfWeek { Sunday = 0, Monday = 1, Tuesday = 2, Wednesday = 3, Thursday = 4, Friday = 5, Saturday = 6, } } ================================================ FILE: Zelig/Zelig/RunTime/Framework/mscorlib/System/Decimal.cs ================================================ // ==++== // // Copyright (c) Microsoft Corporation. All rights reserved. // // ==--== namespace System { using System; using System.Globalization; using System.Runtime.InteropServices; using System.Runtime.CompilerServices; using System.Runtime.ConstrainedExecution; ////using System.Runtime.Versioning; using System.Runtime.Serialization; // Implements the Decimal data type. The Decimal data type can // represent values ranging from -79,228,162,514,264,337,593,543,950,335 to // 79,228,162,514,264,337,593,543,950,335 with 28 significant digits. The // Decimal data type is ideally suited to financial calculations that // require a large number of significant digits and no round-off errors. // // The finite set of values of type Decimal are of the form m // / 10e, where m is an integer such that // -296 <; m <; 296, and e is an integer // between 0 and 28 inclusive. // // Contrary to the float and double data types, decimal // fractional numbers such as 0.1 can be represented exactly in the // Decimal representation. In the float and double // representations, such numbers are often infinite fractions, making those // representations more prone to round-off errors. // // The Decimal class implements widening conversions from the // ubyte, char, short, int, and long types // to Decimal. These widening conversions never loose any information // and never throw exceptions. The Decimal class also implements // narrowing conversions from Decimal to ubyte, char, // short, int, and long. These narrowing conversions round // the Decimal value towards zero to the nearest integer, and then // converts that integer to the destination type. An OverflowException // is thrown if the result is not within the range of the destination type. // // The Decimal class provides a widening conversion from // Currency to Decimal. This widening conversion never loses any // information and never throws exceptions. The Currency class provides // a narrowing conversion from Decimal to Currency. This // narrowing conversion rounds the Decimal to four decimals and then // converts that number to a Currency. An OverflowException // is thrown if the result is not within the range of the Currency type. // // The Decimal class provides narrowing conversions to and from the // float and double types. A conversion from Decimal to // float or double may loose precision, but will not loose // information about the overall magnitude of the numeric value, and will never // throw an exception. A conversion from float or double to // Decimal throws an OverflowException if the value is not within // the range of the Decimal type. [Serializable] [StructLayout( LayoutKind.Sequential )] public struct Decimal : IFormattable, IComparable, IConvertible /*, IDeserializationCallback, IComparable, IEquatable*/ { // Sign mask for the flags field. A value of zero in this bit indicates a // positive Decimal value, and a value of one in this bit indicates a // negative Decimal value. // // Look at OleAut's DECIMAL_NEG constant to check for negative values // in native code. private const int SignMask = unchecked( (int)0x80000000 ); // Scale mask for the flags field. This byte in the flags field contains // the power of 10 to divide the Decimal value by. The scale byte must // contain a value between 0 and 28 inclusive. private const int ScaleMask = 0x00FF0000; // Number of bits scale is shifted by. private const int ScaleShift = 16; // The maximum power of 10 that a 32 bit integer can store private const Int32 MaxInt32Scale = 9; // Fast access for 10^n where n is 0-9 private static UInt32[] Powers10 = new UInt32[] { 1, 10, 100, 1000, 10000, 100000, 1000000, 10000000, 100000000, 1000000000 }; // Constant representing the Decimal value 0. public const Decimal Zero = 0m; // Constant representing the Decimal value 1. public const Decimal One = 1m; // Constant representing the Decimal value -1. public const Decimal MinusOne = -1m; // Constant representing the largest possible Decimal value. The value of // this constant is 79,228,162,514,264,337,593,543,950,335. public const Decimal MaxValue = 79228162514264337593543950335m; // Constant representing the smallest possible Decimal value. The value of // this constant is -79,228,162,514,264,337,593,543,950,335. public const Decimal MinValue = -79228162514264337593543950335m; // The lo, mid, hi, and flags fields contain the representation of the // Decimal value. The lo, mid, and hi fields contain the 96-bit integer // part of the Decimal. Bits 0-15 (the lower word) of the flags field are // unused and must be zero; bits 16-23 contain must contain a value between // 0 and 28, indicating the power of 10 to divide the 96-bit integer part // by to produce the Decimal value; bits 24-30 are unused and must be zero; // and finally bit 31 indicates the sign of the Decimal value, 0 meaning // positive and 1 meaning negative. // // NOTE: Do not change the order in which these fields are declared. The // native methods in this class rely on this particular order. private int flags; private int hi; private int lo; private int mid; // Constructs a zero Decimal. //public Decimal() { // lo = 0; // mid = 0; // hi = 0; // flags = 0; //} // Constructs a Decimal from an integer value. // public Decimal( int value ) { if(value >= 0) { flags = 0; } else { flags = SignMask; value = -value; } lo = value; mid = 0; hi = 0; } // Constructs a Decimal from an unsigned integer value. // [CLSCompliant( false )] public Decimal( uint value ) { flags = 0; lo = (int)value; mid = 0; hi = 0; } //// // Constructs a Decimal from a long value. // public Decimal( long value ) { if(value >= 0) { flags = 0; } else { flags = SignMask; value = -value; } lo = (int)value; mid = (int)(value >> 32); hi = 0; } // Constructs a Decimal from an unsigned long value. // [CLSCompliant( false )] public Decimal( ulong value ) { flags = 0; lo = (int)value; mid = (int)(value >> 32); hi = 0; } // Constructs a Decimal from a float value. // //// [ResourceExposure( ResourceScope.None )] [MethodImpl( MethodImplOptions.InternalCall )] public extern Decimal( float value ); // Constructs a Decimal from a double value. // //// [ResourceExposure( ResourceScope.None )] [MethodImpl( MethodImplOptions.InternalCall )] public extern Decimal( double value ); //// // Constructs a Decimal from a Currency value. //// // //// internal Decimal( Currency value ) //// { //// Decimal temp = Currency.ToDecimal( value ); //// //// this.lo = temp.lo; //// this.mid = temp.mid; //// this.hi = temp.hi; //// this.flags = temp.flags; //// } //// //// // Don't remove these 2 methods below. They are required by the fx when the are dealing with Currency in their //// // databases //// public static long ToOACurrency( Decimal value ) //// { //// return new Currency( value ).ToOACurrency(); //// } //// //// public static Decimal FromOACurrency( long cy ) //// { //// return Currency.ToDecimal( Currency.FromOACurrency( cy ) ); //// } // Constructs a Decimal from an integer array containing a binary // representation. The bits argument must be a non-null integer // array with four elements. bits[0], bits[1], and // bits[2] contain the low, middle, and high 32 bits of the 96-bit // integer part of the Decimal. bits[3] contains the scale factor // and sign of the Decimal: bits 0-15 (the lower word) are unused and must // be zero; bits 16-23 must contain a value between 0 and 28, indicating // the power of 10 to divide the 96-bit integer part by to produce the // Decimal value; bits 24-30 are unused and must be zero; and finally bit // 31 indicates the sign of the Decimal value, 0 meaning positive and 1 // meaning negative. // // Note that there are several possible binary representations for the // same numeric value. For example, the value 1 can be represented as {1, // 0, 0, 0} (integer value 1 with a scale factor of 0) and equally well as // {1000, 0, 0, 0x30000} (integer value 1000 with a scale factor of 3). // The possible binary representations of a particular value are all // equally valid, and all are numerically equivalent. // public Decimal( int[] bits ) { this.lo = 0; this.mid = 0; this.hi = 0; this.flags = 0; SetBits( bits ); } private void SetBits( int[] bits ) { if(bits == null) { #if EXCEPTION_STRINGS throw new ArgumentNullException( "bits" ); #else throw new ArgumentNullException(); #endif } if(bits.Length == 4) { int f = bits[3]; if((f & ~(SignMask | ScaleMask)) == 0 && (f & ScaleMask) <= (28 << 16)) { lo = bits[0]; mid = bits[1]; hi = bits[2]; flags = f; return; } } #if EXCEPTION_STRINGS throw new ArgumentException( Environment.GetResourceString( "Arg_DecBitCtor" ) ); #else throw new ArgumentException(); #endif } // Constructs a Decimal from its constituent parts. // public Decimal( int lo, int mid, int hi, bool isNegative, byte scale ) { if(scale > 28) { #if EXCEPTION_STRINGS throw new ArgumentOutOfRangeException( "scale", Environment.GetResourceString( "ArgumentOutOfRange_DecimalScale" ) ); #else throw new ArgumentOutOfRangeException(); #endif } this.lo = lo; this.mid = mid; this.hi = hi; this.flags = ((int)scale) << 16; if(isNegative) { this.flags |= SignMask; } } //// void IDeserializationCallback.OnDeserialization( Object sender ) //// { //// // OnDeserialization is called after each instance of this class is deserialized. //// // This callback method performs decimal validation after being deserialized. //// try //// { //// SetBits( GetBits( this ) ); //// } //// catch(ArgumentException e) //// { //// throw new SerializationException( Environment.GetResourceString( "Overflow_Decimal" ), e ); //// } //// } // Constructs a Decimal from its constituent parts. private Decimal( int lo, int mid, int hi, int flags ) { this.lo = lo; this.mid = mid; this.hi = hi; this.flags = flags; } // Returns the absolute value of the given Decimal. If d is // positive, the result is d. If d is negative, the result // is -d. // internal static Decimal Abs( Decimal d ) { return new Decimal( d.lo, d.mid, d.hi, d.flags & ~SignMask ); } // Adds two Decimal values. // public static Decimal Add( Decimal d1, Decimal d2 ) { Decimal result = new Decimal(); FCallAdd( ref result, d1, d2 ); return result; } //// [ResourceExposure( ResourceScope.None )] [MethodImpl( MethodImplOptions.InternalCall )] private static extern void FCallAdd( ref Decimal result, Decimal d1, Decimal d2 ); // Rounds a Decimal to an integer value. The Decimal argument is rounded // towards positive infinity. public static Decimal Ceiling( Decimal d ) { return (-(Decimal.Floor( -d ))); } // Compares two Decimal values, returning an integer that indicates their // relationship. // //// [ResourceExposure( ResourceScope.None )] [MethodImpl( MethodImplOptions.InternalCall )] //// [ReliabilityContract( Consistency.WillNotCorruptState, Cer.Success )] public static extern int Compare( Decimal d1, Decimal d2 ); // Compares this object to another object, returning an integer that // indicates the relationship. // Returns a value less than zero if this object // null is considered to be less than any instance. // If object is not of type Decimal, this method throws an ArgumentException. // public int CompareTo( Object value ) { if(value == null) { return 1; } if(!(value is Decimal)) { #if EXCEPTION_STRINGS throw new ArgumentException( Environment.GetResourceString( "Arg_MustBeDecimal" ) ); #else throw new ArgumentException(); #endif } return Decimal.Compare( this, (Decimal)value ); } public int CompareTo( Decimal value ) { return Decimal.Compare( this, value ); } // Divides two Decimal values. // public static Decimal Divide( Decimal d1, Decimal d2 ) { Decimal result = new Decimal(); FCallDivide( ref result, d1, d2 ); return result; } //// [ResourceExposure( ResourceScope.None )] [MethodImpl( MethodImplOptions.InternalCall )] private static extern void FCallDivide( ref Decimal result, Decimal d1, Decimal d2 ); // Checks if this Decimal is equal to a given object. Returns true // if the given object is a boxed Decimal and its value is equal to the // value of this Decimal. Returns false otherwise. // public override bool Equals( Object value ) { if(value is Decimal) { return Compare( this, (Decimal)value ) == 0; } return false; } public bool Equals( Decimal value ) { return Compare( this, value ) == 0; } // Returns the hash code for this Decimal. // //// [ResourceExposure( ResourceScope.None )] [MethodImpl( MethodImplOptions.InternalCall )] public extern override int GetHashCode(); // Compares two Decimal values for equality. Returns true if the two // Decimal values are equal, or false if they are not equal. // public static bool Equals( Decimal d1, Decimal d2 ) { return Compare( d1, d2 ) == 0; } // Rounds a Decimal to an integer value. The Decimal argument is rounded // towards negative infinity. // public static Decimal Floor( Decimal d ) { Decimal result = new Decimal(); FCallFloor( ref result, d ); return result; } //// [ResourceExposure( ResourceScope.None )] [MethodImpl( MethodImplOptions.InternalCall )] private static extern void FCallFloor( ref Decimal result, Decimal d ); // Converts this Decimal to a string. The resulting string consists of an // optional minus sign ("-") followed to a sequence of digits ("0" - "9"), // optionally followed by a decimal point (".") and another sequence of // digits. // public override String ToString() { return Number.FormatDecimal( this, null, NumberFormatInfo.CurrentInfo ); } public String ToString( String format ) { return Number.FormatDecimal( this, format, NumberFormatInfo.CurrentInfo ); } public String ToString( IFormatProvider provider ) { return Number.FormatDecimal( this, null, NumberFormatInfo.GetInstance( provider ) ); } public String ToString( String format, IFormatProvider provider ) { return Number.FormatDecimal( this, format, NumberFormatInfo.GetInstance( provider ) ); } // Converts a string to a Decimal. The string must consist of an optional // minus sign ("-") followed by a sequence of digits ("0" - "9"). The // sequence of digits may optionally contain a single decimal point (".") // character. Leading and trailing whitespace characters are allowed. // Parse also allows a currency symbol, a trailing negative sign, and // parentheses in the number. // public static Decimal Parse( String s ) { return Number.ParseDecimal( s, NumberStyles.Number, NumberFormatInfo.CurrentInfo ); } public static Decimal Parse( String s, NumberStyles style ) { NumberFormatInfo.ValidateParseStyleFloatingPoint( style ); return Number.ParseDecimal( s, style, NumberFormatInfo.CurrentInfo ); } public static Decimal Parse( String s, IFormatProvider provider ) { return Number.ParseDecimal( s, NumberStyles.Number, NumberFormatInfo.GetInstance( provider ) ); } public static Decimal Parse( String s, NumberStyles style, IFormatProvider provider ) { NumberFormatInfo.ValidateParseStyleFloatingPoint( style ); return Number.ParseDecimal( s, style, NumberFormatInfo.GetInstance( provider ) ); } public static Boolean TryParse( String s, out Decimal result ) { return Number.TryParseDecimal( s, NumberStyles.Number, NumberFormatInfo.CurrentInfo, out result ); } public static Boolean TryParse( String s, NumberStyles style, IFormatProvider provider, out Decimal result ) { NumberFormatInfo.ValidateParseStyleFloatingPoint( style ); return Number.TryParseDecimal( s, style, NumberFormatInfo.GetInstance( provider ), out result ); } // Returns a binary representation of a Decimal. The return value is an // integer array with four elements. Elements 0, 1, and 2 contain the low, // middle, and high 32 bits of the 96-bit integer part of the Decimal. // Element 3 contains the scale factor and sign of the Decimal: bits 0-15 // (the lower word) are unused; bits 16-23 contain a value between 0 and // 28, indicating the power of 10 to divide the 96-bit integer part by to // produce the Decimal value; bits 24-30 are unused; and finally bit 31 // indicates the sign of the Decimal value, 0 meaning positive and 1 // meaning negative. // public static int[] GetBits( Decimal d ) { return new int[] { d.lo, d.mid, d.hi, d.flags }; } internal static void GetBytes( Decimal d, byte[] buffer ) { BCLDebug.Assert( (buffer != null && buffer.Length >= 16), "[GetBytes]buffer != null && buffer.Length >= 16" ); buffer[ 0] = (byte) d.lo; buffer[ 1] = (byte)(d.lo >> 8); buffer[ 2] = (byte)(d.lo >> 16); buffer[ 3] = (byte)(d.lo >> 24); buffer[ 4] = (byte) d.mid; buffer[ 5] = (byte)(d.mid >> 8); buffer[ 6] = (byte)(d.mid >> 16); buffer[ 7] = (byte)(d.mid >> 24); buffer[ 8] = (byte) d.hi; buffer[ 9] = (byte)(d.hi >> 8); buffer[10] = (byte)(d.hi >> 16); buffer[11] = (byte)(d.hi >> 24); buffer[12] = (byte) d.flags; buffer[13] = (byte)(d.flags >> 8); buffer[14] = (byte)(d.flags >> 16); buffer[15] = (byte)(d.flags >> 24); } internal static decimal ToDecimal( byte[] buffer ) { int lo = ((int)buffer[ 0]) | ((int)buffer[ 1] << 8) | ((int)buffer[ 2] << 16) | ((int)buffer[ 3] << 24); int mid = ((int)buffer[ 4]) | ((int)buffer[ 5] << 8) | ((int)buffer[ 6] << 16) | ((int)buffer[ 7] << 24); int hi = ((int)buffer[ 8]) | ((int)buffer[ 9] << 8) | ((int)buffer[10] << 16) | ((int)buffer[11] << 24); int flags = ((int)buffer[12]) | ((int)buffer[13] << 8) | ((int)buffer[14] << 16) | ((int)buffer[15] << 24); return new Decimal( lo, mid, hi, flags ); } // This method does a 'raw' and 'unchecked' addition of a UInt32 to a Decimal in place. // 'raw' means that it operates on the internal 96-bit unsigned integer value and // ingores the sign and scale. This means that it is not equivalent to just adding // that number, as the sign and scale are effectively applied to the UInt32 value also. // 'unchecked' means that it does not fail if you overflow the 96 bit value. private static void InternalAddUInt32RawUnchecked( ref Decimal value, UInt32 i ) { UInt32 v; UInt32 sum; v = (UInt32)value.lo; sum = v + i; value.lo = (Int32)sum; if(sum < v || sum < i) { v = (UInt32)value.mid; sum = v + 1; value.mid = (Int32)sum; if(sum < v || sum < 1) { value.hi = (Int32)((UInt32)value.hi + 1); } } } // This method does an in-place division of a decimal by a UInt32, returning the remainder. // Although it does not operate on the sign or scale, this does not result in any // caveat for the result. It is equivalent to dividing by that number. private static UInt32 InternalDivRemUInt32( ref Decimal value, UInt32 divisor ) { UInt32 remainder = 0; UInt64 n; if(value.hi != 0) { n = ((UInt32)value.hi); value.hi = (Int32)((UInt32)(n / divisor)); remainder = (UInt32)(n % divisor); } if(value.mid != 0 || remainder != 0) { n = ((UInt64)remainder << 32) | (UInt32)value.mid; value.mid = (Int32)((UInt32)(n / divisor)); remainder = (UInt32)(n % divisor); } if(value.lo != 0 || remainder != 0) { n = ((UInt64)remainder << 32) | (UInt32)value.lo; value.lo = (Int32)((UInt32)(n / divisor)); remainder = (UInt32)(n % divisor); } return remainder; } // Does an in-place round the specified number of digits, rounding mid-point values // away from zero private static void InternalRoundFromZero( ref Decimal d, int decimalCount ) { Int32 scale = (d.flags & ScaleMask) >> ScaleShift; Int32 scaleDifference = scale - decimalCount; if(scaleDifference <= 0) { return; } // Divide the value by 10^scaleDifference UInt32 lastRemainder; UInt32 lastDivisor; do { Int32 diffChunk = (scaleDifference > MaxInt32Scale) ? MaxInt32Scale : scaleDifference; lastDivisor = Powers10[diffChunk]; lastRemainder = InternalDivRemUInt32( ref d, lastDivisor ); scaleDifference -= diffChunk; } while(scaleDifference > 0); // Round away from zero at the mid point if(lastRemainder >= (lastDivisor >> 1)) { InternalAddUInt32RawUnchecked( ref d, 1 ); } // the scale becomes the desired decimal count d.flags = ((decimalCount << ScaleShift) & ScaleMask) | (d.flags & SignMask); } // Returns the larger of two Decimal values. // //// [ReliabilityContract( Consistency.WillNotCorruptState, Cer.Success )] internal static Decimal Max( Decimal d1, Decimal d2 ) { return Compare( d1, d2 ) >= 0 ? d1 : d2; } // Returns the smaller of two Decimal values. // //// [ReliabilityContract( Consistency.WillNotCorruptState, Cer.Success )] internal static Decimal Min( Decimal d1, Decimal d2 ) { return Compare( d1, d2 ) < 0 ? d1 : d2; } public static Decimal Remainder( Decimal d1, Decimal d2 ) { // OleAut doesn't provide a VarDecMod. // In the operation x % y the sign of y does not matter. Result will have the sign of x. d2.flags = (d2.flags & ~SignMask) | (d1.flags & SignMask); // This piece of code is to work around the fact that Dividing a decimal with 28 digits number by decimal which causes // causes the result to be 28 digits, can cause to be incorrectly rounded up. // eg. Decimal.MaxValue / 2 * Decimal.MaxValue will overflow since the division by 2 was rounded instead of being truncked. if(Abs( d1 ) < Abs( d2 )) { return d1; } d1 -= d2; if(d1 == 0) { // The sign of D1 will be wrong here. Fall through so that we still get a DivideByZeroException d1.flags = (d1.flags & ~SignMask) | (d2.flags & SignMask); } // Formula: d1 - (RoundTowardsZero(d1 / d2) * d2) Decimal dividedResult = Truncate( d1 / d2 ); Decimal multipliedResult = dividedResult * d2; Decimal result = d1 - multipliedResult; // See if the result has crossed 0 if((d1.flags & SignMask) != (result.flags & SignMask)) { if(result == 0) { // A zero result just needs its sign corrected result.flags = (result.flags & ~SignMask) | (d1.flags & SignMask); } else { // If the division rounds up because it runs out of digits, the multiplied result can end up with a larger // absolute value and the result of the formula crosses 0. To correct it can add the divisor back. result += d2; } } return result; } // Multiplies two Decimal values. // public static Decimal Multiply( Decimal d1, Decimal d2 ) { Decimal result = new Decimal(); FCallMultiply( ref result, d1, d2 ); return result; } //// [ResourceExposure( ResourceScope.None )] [MethodImpl( MethodImplOptions.InternalCall )] private static extern void FCallMultiply( ref Decimal result, Decimal d1, Decimal d2 ); // Returns the negated value of the given Decimal. If d is non-zero, // the result is -d. If d is zero, the result is zero. // public static Decimal Negate( Decimal d ) { return new Decimal( d.lo, d.mid, d.hi, d.flags ^ SignMask ); } // Rounds a Decimal value to a given number of decimal places. The value // given by d is rounded to the number of decimal places given by // decimals. The decimals argument must be an integer between // 0 and 28 inclusive. // // By default a mid-point value is rounded to the nearest even number. If the mode is // passed in, it can also round away from zero. public static Decimal Round( Decimal d ) { return Round( d, 0 ); } public static Decimal Round( Decimal d, int decimals ) { Decimal result = new Decimal(); FCallRound( ref result, d, decimals ); return result; } public static Decimal Round( Decimal d, MidpointRounding mode ) { return Round( d, 0, mode ); } public static Decimal Round( Decimal d, int decimals, MidpointRounding mode ) { if((decimals < 0) || (decimals > 28)) { #if EXCEPTION_STRINGS throw new ArgumentOutOfRangeException( "decimals", Environment.GetResourceString( "ArgumentOutOfRange_DecimalRound" ) ); #else throw new ArgumentOutOfRangeException(); #endif } if(mode < MidpointRounding.ToEven || mode > MidpointRounding.AwayFromZero) { #if EXCEPTION_STRINGS throw new ArgumentException( Environment.GetResourceString( "Argument_InvalidEnumValue", mode, "MidpointRounding" ), "mode" ); #else throw new ArgumentException(); #endif } Decimal returnValue = d; if(mode == MidpointRounding.ToEven) { FCallRound( ref returnValue, d, decimals ); } else { InternalRoundFromZero( ref returnValue, decimals ); } return returnValue; } //// [ResourceExposure( ResourceScope.None )] [MethodImpl( MethodImplOptions.InternalCall )] private static extern void FCallRound( ref Decimal result, Decimal d, int decimals ); // Subtracts two Decimal values. // public static Decimal Subtract( Decimal d1, Decimal d2 ) { Decimal result = new Decimal(); FCallSubtract( ref result, d1, d2 ); return result; } //// [ResourceExposure( ResourceScope.None )] [MethodImpl( MethodImplOptions.InternalCall )] private static extern void FCallSubtract( ref Decimal result, Decimal d1, Decimal d2 ); // Converts a Decimal to an unsigned byte. The Decimal value is rounded // towards zero to the nearest integer value, and the result of this // operation is returned as a byte. // public static byte ToByte( Decimal value ) { uint temp = ToUInt32( value ); if(temp < Byte.MinValue || temp > Byte.MaxValue) { #if EXCEPTION_STRINGS throw new OverflowException( Environment.GetResourceString( "Overflow_Byte" ) ); #else throw new OverflowException(); #endif } return (byte)temp; } // Converts a Decimal to a signed byte. The Decimal value is rounded // towards zero to the nearest integer value, and the result of this // operation is returned as a byte. // [CLSCompliant( false )] public static sbyte ToSByte( Decimal value ) { int temp = ToInt32( value ); if(temp < SByte.MinValue || temp > SByte.MaxValue) { #if EXCEPTION_STRINGS throw new OverflowException( Environment.GetResourceString( "Overflow_SByte" ) ); #else throw new OverflowException(); #endif } return (sbyte)temp; } // Converts a Decimal to a short. The Decimal value is // rounded towards zero to the nearest integer value, and the result of // this operation is returned as a short. // public static short ToInt16( Decimal value ) { int temp = ToInt32( value ); if(temp < Int16.MinValue || temp > Int16.MaxValue) { #if EXCEPTION_STRINGS throw new OverflowException( Environment.GetResourceString( "Overflow_Int16" ) ); #else throw new OverflowException(); #endif } return (short)temp; } //// // Converts a Decimal to a Currency. Since a Currency //// // has fewer significant digits than a Decimal, this operation may //// // produce round-off errors. //// // //// internal static Currency ToCurrency( Decimal d ) //// { //// Currency result = new Currency(); //// //// FCallToCurrency( ref result, d ); //// //// return result; //// } //// //// [ResourceExposure( ResourceScope.None )] //// [MethodImpl( MethodImplOptions.InternalCall )] //// private static extern void FCallToCurrency( ref Currency result, Decimal d ); // Converts a Decimal to a double. Since a double has fewer significant // digits than a Decimal, this operation may produce round-off errors. // //// [ResourceExposure( ResourceScope.None )] [MethodImpl( MethodImplOptions.InternalCall )] public static extern double ToDouble( Decimal d ); //// [ResourceExposure( ResourceScope.None )] [MethodImpl( MethodImplOptions.InternalCall )] internal static extern int FCallToInt32( Decimal d ); // Converts a Decimal to an integer. The Decimal value is rounded towards // zero to the nearest integer value, and the result of this operation is // returned as an integer. // public static int ToInt32( Decimal d ) { if((d.flags & ScaleMask) != 0) d = Truncate( d ); if(d.hi == 0 && d.mid == 0) { int i = d.lo; if(d.flags >= 0) { if(i >= 0) return i; } else { i = -i; if(i <= 0) return i; } } #if EXCEPTION_STRINGS throw new OverflowException( Environment.GetResourceString( "Overflow_Int32" ) ); #else throw new OverflowException(); #endif } // Converts a Decimal to a long. The Decimal value is rounded towards zero // to the nearest integer value, and the result of this operation is // returned as a long. // public static long ToInt64( Decimal d ) { if((d.flags & ScaleMask) != 0) d = Truncate( d ); if(d.hi == 0) { long l = d.lo & 0xFFFFFFFFL | (long)d.mid << 32; if(d.flags >= 0) { if(l >= 0) return l; } else { l = -l; if(l <= 0) return l; } } #if EXCEPTION_STRINGS throw new OverflowException( Environment.GetResourceString( "Overflow_Int64" ) ); #else throw new OverflowException(); #endif } // Converts a Decimal to an ushort. The Decimal // value is rounded towards zero to the nearest integer value, and the // result of this operation is returned as an ushort. // [CLSCompliant( false )] public static ushort ToUInt16( Decimal value ) { uint temp = ToUInt32( value ); if(temp < UInt16.MinValue || temp > UInt16.MaxValue) { #if EXCEPTION_STRINGS throw new OverflowException( Environment.GetResourceString( "Overflow_UInt16" ) ); #else throw new OverflowException(); #endif } return (ushort)temp; } // Converts a Decimal to an unsigned integer. The Decimal // value is rounded towards zero to the nearest integer value, and the // result of this operation is returned as an unsigned integer. // [CLSCompliant( false )] public static uint ToUInt32( Decimal d ) { if((d.flags & ScaleMask) != 0) d = Truncate( d ); if(d.hi == 0 && d.mid == 0) { uint i = (uint)d.lo; if(d.flags >= 0 || i == 0) { return i; } } #if EXCEPTION_STRINGS throw new OverflowException( Environment.GetResourceString( "Overflow_UInt32" ) ); #else throw new OverflowException(); #endif } // Converts a Decimal to an unsigned long. The Decimal // value is rounded towards zero to the nearest integer value, and the // result of this operation is returned as a long. // [CLSCompliant( false )] public static ulong ToUInt64( Decimal d ) { if((d.flags & ScaleMask) != 0) d = Truncate( d ); if(d.hi == 0) { ulong l = ((ulong)(uint)d.lo) | ((ulong)(uint)d.mid << 32); if(d.flags >= 0 || l == 0) { return l; } } #if EXCEPTION_STRINGS throw new OverflowException( Environment.GetResourceString( "Overflow_UInt64" ) ); #else throw new OverflowException(); #endif } // Converts a Decimal to a float. Since a float has fewer significant // digits than a Decimal, this operation may produce round-off errors. // //// [ResourceExposure( ResourceScope.None )] [MethodImpl( MethodImplOptions.InternalCall )] public static extern float ToSingle( Decimal d ); // Truncates a Decimal to an integer value. The Decimal argument is rounded // towards zero to the nearest integer value, corresponding to removing all // digits after the decimal point. // public static Decimal Truncate( Decimal d ) { Decimal result = new Decimal(); FCallTruncate( ref result, d ); return result; } //// [ResourceExposure( ResourceScope.None )] [MethodImpl( MethodImplOptions.InternalCall )] private static extern void FCallTruncate( ref Decimal result, Decimal d ); public static implicit operator Decimal( byte value ) { return new Decimal( value ); } [CLSCompliant( false )] public static implicit operator Decimal( sbyte value ) { return new Decimal( value ); } public static implicit operator Decimal( short value ) { return new Decimal( value ); } [CLSCompliant( false )] public static implicit operator Decimal( ushort value ) { return new Decimal( value ); } public static implicit operator Decimal( char value ) { return new Decimal( value ); } public static implicit operator Decimal( int value ) { return new Decimal( value ); } [CLSCompliant( false )] public static implicit operator Decimal( uint value ) { return new Decimal( value ); } public static implicit operator Decimal( long value ) { return new Decimal( value ); } [CLSCompliant( false )] public static implicit operator Decimal( ulong value ) { return new Decimal( value ); } public static explicit operator Decimal( float value ) { return new Decimal( value ); } public static explicit operator Decimal( double value ) { return new Decimal( value ); } public static explicit operator byte( Decimal value ) { return ToByte( value ); } [CLSCompliant( false )] public static explicit operator sbyte( Decimal value ) { return ToSByte( value ); } public static explicit operator char( Decimal value ) { return (char)ToUInt16( value ); } public static explicit operator short( Decimal value ) { return ToInt16( value ); } [CLSCompliant( false )] public static explicit operator ushort( Decimal value ) { return ToUInt16( value ); } public static explicit operator int( Decimal value ) { return ToInt32( value ); } [CLSCompliant( false )] public static explicit operator uint( Decimal value ) { return ToUInt32( value ); } public static explicit operator long( Decimal value ) { return ToInt64( value ); } [CLSCompliant( false )] public static explicit operator ulong( Decimal value ) { return ToUInt64( value ); } public static explicit operator float( Decimal value ) { return ToSingle( value ); } public static explicit operator double( Decimal value ) { return ToDouble( value ); } public static Decimal operator +( Decimal d ) { return d; } public static Decimal operator -( Decimal d ) { return Negate( d ); } public static Decimal operator ++( Decimal d ) { return Add( d, One ); } public static Decimal operator --( Decimal d ) { return Subtract( d, One ); } public static Decimal operator +( Decimal d1, Decimal d2 ) { return Add( d1, d2 ); } public static Decimal operator -( Decimal d1, Decimal d2 ) { return Subtract( d1, d2 ); } public static Decimal operator *( Decimal d1, Decimal d2 ) { return Multiply( d1, d2 ); } public static Decimal operator /( Decimal d1, Decimal d2 ) { return Divide( d1, d2 ); } public static Decimal operator %( Decimal d1, Decimal d2 ) { return Remainder( d1, d2 ); } /*private static bool operator equals(Decimal d1, Decimal d2) { return Compare(d1, d2) == 0; } private static int operator compare(Decimal d1, Decimal d2) { int c = Compare(d1, d2); if (c < 0) return -1; if (c > 0) return 1; return 0; }*/ public static bool operator ==( Decimal d1, Decimal d2 ) { return Compare( d1, d2 ) == 0; } public static bool operator !=( Decimal d1, Decimal d2 ) { return Compare( d1, d2 ) != 0; } public static bool operator <( Decimal d1, Decimal d2 ) { return Compare( d1, d2 ) < 0; } public static bool operator <=( Decimal d1, Decimal d2 ) { return Compare( d1, d2 ) <= 0; } public static bool operator >( Decimal d1, Decimal d2 ) { return Compare( d1, d2 ) > 0; } public static bool operator >=( Decimal d1, Decimal d2 ) { return Compare( d1, d2 ) >= 0; } #region IConvertible public TypeCode GetTypeCode() { return TypeCode.Decimal; } /// bool IConvertible.ToBoolean( IFormatProvider provider ) { return Convert.ToBoolean( this ); } /// char IConvertible.ToChar( IFormatProvider provider ) { #if EXCEPTION_STRINGS throw new InvalidCastException( String.Format( CultureInfo.CurrentCulture, Environment.GetResourceString( "InvalidCast_FromTo" ), "Decimal", "Char" ) ); #else throw new InvalidCastException(); #endif } /// sbyte IConvertible.ToSByte( IFormatProvider provider ) { return Convert.ToSByte( this ); } /// byte IConvertible.ToByte( IFormatProvider provider ) { return Convert.ToByte( this ); } /// short IConvertible.ToInt16( IFormatProvider provider ) { return Convert.ToInt16( this ); } /// ushort IConvertible.ToUInt16( IFormatProvider provider ) { return Convert.ToUInt16( this ); } /// int IConvertible.ToInt32( IFormatProvider provider ) { return Convert.ToInt32( this ); } /// uint IConvertible.ToUInt32( IFormatProvider provider ) { return Convert.ToUInt32( this ); } /// long IConvertible.ToInt64( IFormatProvider provider ) { return Convert.ToInt64( this ); } /// ulong IConvertible.ToUInt64( IFormatProvider provider ) { return Convert.ToUInt64( this ); } /// float IConvertible.ToSingle( IFormatProvider provider ) { return Convert.ToSingle( this ); } /// double IConvertible.ToDouble( IFormatProvider provider ) { return Convert.ToDouble( this ); } /// Decimal IConvertible.ToDecimal( IFormatProvider provider ) { return this; } /// DateTime IConvertible.ToDateTime( IFormatProvider provider ) { #if EXCEPTION_STRINGS throw new InvalidCastException( String.Format( CultureInfo.CurrentCulture, Environment.GetResourceString( "InvalidCast_FromTo" ), "Decimal", "DateTime" ) ); #else throw new InvalidCastException(); #endif } /// Object IConvertible.ToType( Type type, IFormatProvider provider ) { return Convert.DefaultToType( (IConvertible)this, type, provider ); } #endregion } } ================================================ FILE: Zelig/Zelig/RunTime/Framework/mscorlib/System/Delegate.cs ================================================ // ==++== // // Copyright (c) Microsoft Corporation. All rights reserved. // // ==--== namespace System { using System; using System.Reflection; using System.Threading; using System.Runtime.Serialization; using System.Runtime.InteropServices; using System.Runtime.CompilerServices; ////using System.Runtime.Versioning; [Microsoft.Zelig.Internals.WellKnownType( "System_Delegate" )] [Serializable] public abstract class Delegate : ICloneable /*, ISerializable*/ { //// // m_target is the object we will invoke on //// internal Object m_target; //// //// // MethodBase, either cached after first request or assigned from a DynamicMethod #pragma warning disable 649 // Field 'field' is never assigned to, and will always have its default value 'value' //// internal MethodInfo m_methodBase; #pragma warning restore 649 //// //// // m_methodPtr is a pointer to the method we will invoke //// // It could be a small thunk if this is a static or UM call //// internal IntPtr m_methodPtr; //// //// // In the case of a static method passed to a delegate, this field stores //// // whatever m_methodPtr would have stored: and m_methodPtr points to a //// // small thunk which removes the "this" pointer before going on //// // to m_methodPtrAux. //// internal IntPtr m_methodPtrAux; //// //// // This constructor is called from the class generated by the compiler generated code //// protected Delegate( Object target, String method ) //// { //// if(target == null) //// { //// throw new ArgumentNullException( "target" ); //// } //// //// if(method == null) //// { //// throw new ArgumentNullException( "method" ); //// } //// //// // This API existed in v1/v1.1 and only expected to create closed //// // instance delegates. Constrain the call to BindToMethodName to //// // such and don't allow relaxed signature matching (which could make //// // the choice of target method ambiguous) for backwards //// // compatibility. The name matching was case sensitive and we //// // preserve that as well. //// if(!BindToMethodName( target, Type.GetTypeHandle( target ), method, //// DelegateBindingFlags.InstanceMethodOnly | //// DelegateBindingFlags.ClosedDelegateOnly )) //// { //// throw new ArgumentException( Environment.GetResourceString( "Arg_DlgtTargMeth" ) ); //// } //// } //// //// // This constructor is called from a class to generate a //// // delegate based upon a static method name and the Type object //// // for the class defining the method. //// protected unsafe Delegate( Type target, String method ) //// { //// if(target == null) //// { //// throw new ArgumentNullException( "target" ); //// } //// //// if(!(target is RuntimeType)) //// { //// throw new ArgumentException( Environment.GetResourceString( "Argument_MustBeRuntimeType" ), "target" ); //// } //// //// if(target.IsGenericType && target.ContainsGenericParameters) //// { //// throw new ArgumentException( Environment.GetResourceString( "Arg_UnboundGenParam" ), "target" ); //// } //// //// if(method == null) //// { //// throw new ArgumentNullException( "method" ); //// } //// //// // This API existed in v1/v1.1 and only expected to create open //// // static delegates. Constrain the call to BindToMethodName to such //// // and don't allow relaxed signature matching (which could make the //// // choice of target method ambiguous) for backwards compatibility. //// // The name matching was case insensitive (no idea why this is //// // different from the constructor above) and we preserve that as //// // well. //// BindToMethodName( null, target.TypeHandle, method, //// DelegateBindingFlags.StaticMethodOnly | //// DelegateBindingFlags.OpenDelegateOnly | //// DelegateBindingFlags.CaselessMatching ); //// } //// //// // Protect the default constructor so you can't build a delegate //// private Delegate() //// { //// } //// //// public Object DynamicInvoke( params Object[] args ) //// { //// return DynamicInvokeImpl( args ); //// } //// //// protected virtual object DynamicInvokeImpl( object[] args ) //// { //// RuntimeMethodHandle method = new RuntimeMethodHandle( GetInvokeMethod() ); //// //// RuntimeTypeHandle delegateType = Type.GetTypeHandle( this ); //// //// RuntimeMethodInfo invoke = (RuntimeMethodInfo)RuntimeType.GetMethodBase( delegateType, method ); //// //// return invoke.Invoke( this, BindingFlags.Default, null, args, null, true ); //// } [MethodImpl( MethodImplOptions.InternalCall )] public extern override bool Equals( Object obj ); //// { //// if(obj == null || !InternalEqualTypes( this, obj )) //// { //// return false; //// } //// //// Delegate d = (Delegate)obj; //// //// return (m_target == d.m_target && m_methodBase == d.m_methodBase); //// //// // do an optimistic check first. This is hopefully cheap enough to be worth //// if(m_target == d.m_target && m_methodPtr == d.m_methodPtr && m_methodPtrAux == d.m_methodPtrAux) //// { //// return true; //// } //// //// // even though the fields were not all equals the delegates may still match //// // When target carries the delegate itself the 2 targets (delegates) may be different instances //// // but the delegates are logically the same //// // It may also happen that the method pointer was not jitted when creating one delegate and jitted in the other //// // if that's the case the delegates may still be equals but we need to make a more complicated check //// //// if(m_methodPtrAux.IsNull()) //// { //// if(!d.m_methodPtrAux.IsNull()) //// { //// return false; // different delegate kind //// } //// //// // they are both closed over the first arg //// if(m_target != d.m_target) //// { //// return false; //// } //// // fall through method handle check //// } //// else //// { //// if(d.m_methodPtrAux.IsNull()) //// { //// return false; // different delegate kind //// } //// //// // Ignore the target as it will be the delegate instance, though it may be a different one //// /* //// if (_methodPtr != d._methodPtr) //// return false; //// */ //// //// if(m_methodPtrAux == d.m_methodPtrAux) //// { //// return true; //// } //// // fall through method handle check //// } //// //// // method ptrs don't match, go down long path //// // //// if(m_methodBase == null || d.m_methodBase == null) //// { //// return FindMethodHandle().Equals( d.FindMethodHandle() ); //// } //// else //// { //// return m_methodBase.Equals( d.m_methodBase ); //// } //// } [MethodImpl( MethodImplOptions.InternalCall )] public extern override int GetHashCode(); //// { //// // //// // this is not right in the face of a method being jitted in one delegate and not in another //// // in that case the delegate is the same and Equals will return true but GetHashCode returns a //// // different hashcode which is not true. //// /* //// if (_methodPtrAux.IsNull()) //// return unchecked((int)((long)this._methodPtr)); //// else //// return unchecked((int)((long)this._methodPtrAux)); //// */ //// return GetType().GetHashCode(); //// } [MethodImpl( MethodImplOptions.InternalCall )] public extern static Delegate Combine( Delegate a, Delegate b ); //// { //// // boundry conditions -- if either (or both) delegates is null //// // return the other. //// if((Object)a == null) // cast to object for a more efficient test //// { //// return b; //// } //// if((Object)b == null) // cast to object for a more efficient test //// { //// return a; //// } //// //// if(!InternalEqualTypes( a, b )) //// { //// throw new ArgumentException( Environment.GetResourceString( "Arg_DlgtTypeMis" ) ); //// } //// //// return a.CombineImpl( b ); //// } public static Delegate Combine( params Delegate[] delegates ) { if(delegates == null || delegates.Length == 0) { return null; } Delegate d = delegates[0]; for(int i = 1; i < delegates.Length; i++) { d = Combine( d, delegates[i] ); } return d; } public virtual Delegate[] GetInvocationList() { Delegate[] d = new Delegate[1]; d[0] = this; return d; } // This routine will return the method public MethodInfo Method { get { return GetMethodImpl(); } } [MethodImpl( MethodImplOptions.InternalCall )] protected virtual extern MethodInfo GetMethodImpl(); //// { //// if(m_methodBase == null) //// { //// RuntimeMethodHandle method = FindMethodHandle(); //// RuntimeTypeHandle declaringType = method.GetDeclaringType(); //// //// // need a proper declaring type instance method on a generic type //// if(declaringType.IsGenericTypeDefinition() || declaringType.HasInstantiation()) //// { //// bool isStatic = (method.GetAttributes() & MethodAttributes.Static) != (MethodAttributes)0; //// if(!isStatic) //// { //// if(m_methodPtrAux == (IntPtr)0) //// { //// // The target may be of a derived type that doesn't have visibility onto the //// // target method. We don't want to call RuntimeType.GetMethodBase below with that //// // or reflection can end up generating a MethodInfo where the ReflectedType cannot //// // see the MethodInfo itself and that breaks an important invariant. But the //// // target type could include important generic type information we need in order //// // to work out what the exact instantiation of the method's declaring type is. So //// // we'll walk up the inheritance chain (which will yield exactly instantiated //// // types at each step) until we find the declaring type. Since the declaring type //// // we get from the method is probably shared and those in the hierarchy we're //// // walking won't be we compare using the generic type definition forms instead. //// Type currentType = m_target.GetType(); //// Type targetType = declaringType.GetRuntimeType().GetGenericTypeDefinition(); //// while(true) //// { //// if(currentType.IsGenericType && currentType.GetGenericTypeDefinition() == targetType) //// { //// break; //// } //// //// currentType = currentType.BaseType; //// } //// declaringType = currentType.TypeHandle; //// } //// else //// { //// // it's an open one, need to fetch the first arg of the instantiation //// MethodInfo invoke = this.GetType().GetMethod( "Invoke" ); //// //// declaringType = invoke.GetParameters()[0].ParameterType.TypeHandle; //// } //// } //// } //// //// m_methodBase = (MethodInfo)RuntimeType.GetMethodBase( declaringType, method ); //// } //// //// return m_methodBase; //// } public Object Target { get { return GetTarget(); } } [MethodImpl( MethodImplOptions.InternalCall )] public extern static Delegate Remove( Delegate source, Delegate value ); //// { //// if(source == null) //// { //// return null; //// } //// //// if(value == null) //// { //// return source; //// } //// //// if(!InternalEqualTypes( source, value )) //// { //// throw new ArgumentException( Environment.GetResourceString( "Arg_DlgtTypeMis" ) ); //// } //// //// return source.RemoveImpl( value ); //// } public static Delegate RemoveAll( Delegate source, Delegate value ) { Delegate newDelegate = null; do { newDelegate = source; source = Remove( source, value ); } while(newDelegate != source); return newDelegate; } public virtual Object Clone() { return MemberwiseClone(); } //// // V1 API. //// public static Delegate CreateDelegate( Type type, Object target, String method ) //// { //// return CreateDelegate( type, target, method, false, true ); //// } //// //// // V1 API. //// public static Delegate CreateDelegate( Type type, Object target, String method, bool ignoreCase ) //// { //// return CreateDelegate( type, target, method, ignoreCase, true ); //// } //// //// private static void ValidateType( Type type ) //// { //// if(type == null) //// { //// throw new ArgumentNullException( "type" ); //// } //// //// if(!(type is RuntimeType)) //// { //// throw new ArgumentException( Environment.GetResourceString( "Argument_MustBeRuntimeType" ), "type" ); //// } //// //// Type c = type.BaseType; //// if(c == null || c != typeof( MulticastDelegate )) //// { //// throw new ArgumentException( Environment.GetResourceString( "Arg_MustBeDelegate" ), "type" ); //// } //// } //// //// private static void ValidateTarget( Object target ) //// { //// if(target == null) //// { //// throw new ArgumentNullException( "target" ); //// } //// } //// //// private static void ValidateTarget( Type target ) //// { //// if(target == null) //// { //// throw new ArgumentNullException( "target" ); //// } //// //// if(!(target is RuntimeType)) //// { //// throw new ArgumentException( Environment.GetResourceString( "Argument_MustBeRuntimeType" ), "target" ); //// } //// //// if(target.IsGenericType && target.ContainsGenericParameters) //// { //// throw new ArgumentException( Environment.GetResourceString( "Arg_UnboundGenParam" ), "target" ); //// } //// } //// //// private static void ValidateMethod( Object method ) //// { //// if(method == null) //// { //// throw new ArgumentNullException( "method" ); //// } //// } //// //// private static void ValidateMethod( MethodInfo method ) //// { //// if(method == null) //// { //// throw new ArgumentNullException( "method" ); //// } //// //// if(!(method is RuntimeMethodInfo)) //// { //// throw new ArgumentException( Environment.GetResourceString( "Argument_MustBeRuntimeMethodInfo" ), "method" ); //// } //// } //// //// //// // V1 API. //// public static Delegate CreateDelegate( Type type, Object target, String method, bool ignoreCase, bool throwOnBindFailure ) //// { //// ValidateType( type ); //// ValidateTarget( target ); //// ValidateMethod( method ); //// //// Delegate d = InternalAlloc( type.TypeHandle ); //// // This API existed in v1/v1.1 and only expected to create closed //// // instance delegates. Constrain the call to BindToMethodName to such //// // and don't allow relaxed signature matching (which could make the //// // choice of target method ambiguous) for backwards compatibility. //// // We never generate a closed over null delegate and this is //// // actually enforced via the check on target above, but we pass //// // NeverCloseOverNull anyway just for clarity. //// if(!d.BindToMethodName( target, Type.GetTypeHandle( target ), method, //// DelegateBindingFlags.InstanceMethodOnly | //// DelegateBindingFlags.ClosedDelegateOnly | //// DelegateBindingFlags.NeverCloseOverNull | //// (ignoreCase ? DelegateBindingFlags.CaselessMatching : 0) )) //// { //// if(throwOnBindFailure) //// { //// throw new ArgumentException( Environment.GetResourceString( "Arg_DlgtTargMeth" ) ); //// } //// d = null; //// } //// //// return d; //// } //// //// // V1 API. //// public static Delegate CreateDelegate( Type type, Type target, String method ) //// { //// return CreateDelegate( type, target, method, false, true ); //// } //// //// // V1 API. //// public static Delegate CreateDelegate( Type type, Type target, String method, bool ignoreCase ) //// { //// return CreateDelegate( type, target, method, ignoreCase, true ); //// } //// //// // V1 API. //// public static Delegate CreateDelegate( Type type, Type target, String method, bool ignoreCase, bool throwOnBindFailure ) //// { //// ValidateType( type ); //// ValidateTarget( target ); //// ValidateMethod( method ); //// //// Delegate d = InternalAlloc( type.TypeHandle ); //// // This API existed in v1/v1.1 and only expected to create open //// // static delegates. Constrain the call to BindToMethodName to such //// // and don't allow relaxed signature matching (which could make the //// // choice of target method ambiguous) for backwards compatibility. //// if(!d.BindToMethodName( null, target.TypeHandle, method, //// DelegateBindingFlags.StaticMethodOnly | //// DelegateBindingFlags.OpenDelegateOnly | //// (ignoreCase ? DelegateBindingFlags.CaselessMatching : 0) )) //// { //// if(throwOnBindFailure) //// { //// throw new ArgumentException( Environment.GetResourceString( "Arg_DlgtTargMeth" ) ); //// } //// //// d = null; //// } //// //// return d; //// } //// //// // V1 API. //// public static Delegate CreateDelegate( Type type, MethodInfo method ) //// { //// return CreateDelegate( type, method, true ); //// } //// //// // V1 API. //// public static Delegate CreateDelegate( Type type, MethodInfo method, bool throwOnBindFailure ) //// { //// ValidateType( type ); //// ValidateMethod( method ); //// //// // Initialize the delegate... //// Delegate d = InternalAlloc( type.TypeHandle ); //// // This API existed in v1/v1.1 and only expected to create closed //// // instance delegates. Constrain the call to BindToMethodInfo to //// // open delegates only for backwards compatibility. But we'll allow //// // relaxed signature checking and open static delegates because //// // there's no ambiguity there (the caller would have to explicitly //// // pass us a static method or a method with a non-exact signature //// // and the only change in behavior from v1.1 there is that we won't //// // fail the call). //// if(!d.BindToMethodInfo( null, method.MethodHandle, method.DeclaringType.TypeHandle, //// DelegateBindingFlags.OpenDelegateOnly | //// DelegateBindingFlags.RelaxedSignature )) //// { //// if(throwOnBindFailure) //// { //// throw new ArgumentException( Environment.GetResourceString( "Arg_DlgtTargMeth" ) ); //// } //// d = null; //// } //// //// return d; //// } //// //// // V2 API. //// public static Delegate CreateDelegate( Type type, Object firstArgument, MethodInfo method ) //// { //// return CreateDelegate( type, firstArgument, method, true ); //// } //// //// // V2 API. //// public static Delegate CreateDelegate( Type type, Object firstArgument, MethodInfo method, bool throwOnBindFailure ) //// { //// ValidateType( type ); //// ValidateMethod( method ); //// //// // Initialize the method... //// Delegate d = InternalAlloc( type.TypeHandle ); //// // This API is new in Whidbey and allows the full range of delegate //// // flexability (open or closed delegates binding to static or //// // instance methods with relaxed signature checking. The delegate //// // can also be closed over null. There's no ambiguity with all these //// // options since the caller is providing us a specific MethodInfo. //// if(!d.BindToMethodInfo( firstArgument, method.MethodHandle, method.DeclaringType.TypeHandle, //// DelegateBindingFlags.RelaxedSignature )) //// { //// if(throwOnBindFailure) //// { //// throw new ArgumentException( Environment.GetResourceString( "Arg_DlgtTargMeth" ) ); //// } //// d = null; //// } //// return d; //// } //// public static bool operator ==( Delegate d1, Delegate d2 ) { if((Object)d1 == null) { return (Object)d2 == null; } return d1.Equals( d2 ); } public static bool operator !=( Delegate d1, Delegate d2 ) { if((Object)d1 == null) { return (Object)d2 != null; } return !d1.Equals( d2 ); } //// // //// // Implementation of ISerializable //// // //// //// public virtual void GetObjectData( SerializationInfo info, StreamingContext context ) //// { //// throw new NotSupportedException(); //// } //// //// // //// // internal implementation details (FCALLS and utilities) //// // //// //// // V2 internal API. //// internal unsafe static Delegate CreateDelegate( Type type, Object target, RuntimeMethodHandle method ) //// { //// ValidateType( type ); //// //// if(method.IsNullHandle()) //// { //// throw new ArgumentNullException( "method" ); //// } //// //// // Initialize the method... //// Delegate d = InternalAlloc( type.TypeHandle ); //// // This is a new internal API added in Whidbey. Currently it's only //// // used by the dynamic method code to generate a wrapper delegate. //// // Allow flexible binding options since the target method is //// // unambiguously provided to us. //// // Might consider passing SkipSecurityChecks here; I haven't //// // looked at the security implications yet. //// if(!d.BindToMethodInfo( target, method, method.GetDeclaringType(), DelegateBindingFlags.RelaxedSignature )) //// { //// throw new ArgumentException( Environment.GetResourceString( "Arg_DlgtTargMeth" ) ); //// } //// return d; //// } //// //// // Caution: this method is intended for deserialization only, no security checks are performed. //// internal static Delegate InternalCreateDelegate( Type type, Object firstArgument, MethodInfo method ) //// { //// ValidateType( type ); //// ValidateMethod( method ); //// //// // Initialize the method... //// Delegate d = InternalAlloc( type.TypeHandle ); //// // This API is used by the formatters when deserializing a delegate. //// // They pass us the specific target method (that was already the //// // target in a valid delegate) so we should bind with the most //// // relaxed rules available (the result will never be ambiguous, it //// // just increases the chance of success with minor (compatible) //// // signature changes). We explicitly skip security checks here -- //// // we're not really constructing a delegate, we're cloning an //// // existing instance which already passed its checks. //// if(!d.BindToMethodInfo( firstArgument, method.MethodHandle, method.DeclaringType.TypeHandle, //// DelegateBindingFlags.SkipSecurityChecks | //// DelegateBindingFlags.RelaxedSignature )) //// { //// throw new ArgumentException( Environment.GetResourceString( "Arg_DlgtTargMeth" ) ); //// } //// //// return d; //// } //// //// [ResourceExposure( ResourceScope.None )] //// [MethodImpl( MethodImplOptions.InternalCall )] //// private extern bool BindToMethodName( Object target, RuntimeTypeHandle methodType, String method, DelegateBindingFlags flags ); //// //// [ResourceExposure( ResourceScope.None )] //// [MethodImpl( MethodImplOptions.InternalCall )] //// private extern bool BindToMethodInfo( Object target, RuntimeMethodHandle method, RuntimeTypeHandle methodType, DelegateBindingFlags flags ); //// //// [ResourceExposure( ResourceScope.None )] //// [MethodImpl( MethodImplOptions.InternalCall )] //// internal extern static MulticastDelegate InternalAlloc( RuntimeTypeHandle type ); //// //// [ResourceExposure( ResourceScope.None )] //// [MethodImpl( MethodImplOptions.InternalCall )] //// internal extern static MulticastDelegate InternalAllocLike( Delegate d ); //// //// [ResourceExposure( ResourceScope.None )] //// [MethodImpl( MethodImplOptions.InternalCall )] //// internal extern static bool InternalEqualTypes( object a, object b ); //// //// // Used by the ctor. Do not call directly. //// // The name of this function will appear in managed stacktraces as delegate constructor. //// [ResourceExposure( ResourceScope.None )] //// [MethodImpl( MethodImplOptions.InternalCall )] //// private extern void DelegateConstruct( Object target, IntPtr slot ); //// //// [ResourceExposure( ResourceScope.None )] //// [MethodImpl( MethodImplOptions.InternalCall )] //// internal extern IntPtr GetMulticastInvoke(); //// //// [ResourceExposure( ResourceScope.None )] //// [MethodImpl( MethodImplOptions.InternalCall )] //// internal extern IntPtr GetInvokeMethod(); //// //// [ResourceExposure( ResourceScope.None )] //// [MethodImpl( MethodImplOptions.InternalCall )] //// internal extern RuntimeMethodHandle FindMethodHandle(); //// //// [ResourceExposure( ResourceScope.None )] //// [MethodImpl( MethodImplOptions.InternalCall )] //// internal extern IntPtr GetUnmanagedCallSite(); //// //// [ResourceExposure( ResourceScope.None )] //// [MethodImpl( MethodImplOptions.InternalCall )] //// internal extern IntPtr AdjustTarget( Object target, IntPtr methodPtr ); //// //// [ResourceExposure( ResourceScope.None )] //// [MethodImpl( MethodImplOptions.InternalCall )] //// internal extern IntPtr GetCallStub( IntPtr methodPtr ); [MethodImpl( MethodImplOptions.InternalCall )] internal extern virtual Object GetTarget(); } ////// These flags effect the way BindToMethodInfo and BindToMethodName are allowed to bind a delegate to a target method. Their ////// values must be kept in sync with the definition in vm\comdelegate.h. ////internal enum DelegateBindingFlags ////{ //// StaticMethodOnly = 0x00000001, // Can only bind to static target methods //// InstanceMethodOnly = 0x00000002, // Can only bind to instance (including virtual) methods //// OpenDelegateOnly = 0x00000004, // Only allow the creation of delegates open over the 1st argument //// ClosedDelegateOnly = 0x00000008, // Only allow the creation of delegates closed over the 1st argument //// NeverCloseOverNull = 0x00000010, // A null target will never been considered as a possible null 1st argument //// CaselessMatching = 0x00000020, // Use case insensitive lookup for methods matched by name //// SkipSecurityChecks = 0x00000040, // Skip security checks (visibility, link demand etc.) //// RelaxedSignature = 0x00000080, // Allow relaxed signature matching (co/contra variance) ////} } ================================================ FILE: Zelig/Zelig/RunTime/Framework/mscorlib/System/Diagnostics/CodeAnalysis/SuppressMessageAttribute.cs ================================================ // ==++== // // Copyright (c) Microsoft Corporation. All rights reserved. // // ==--== /*============================================================ ** ** Class: SuppressMessageAttribute ** ** ** An attribute to suppress violation messages/warnings ** by static code analysis tools. ** ** ===========================================================*/ using System; namespace System.Diagnostics.CodeAnalysis { [AttributeUsage(AttributeTargets.All, Inherited = false, AllowMultiple = true)] [Conditional( "CODE_ANALYSIS" )] public sealed class SuppressMessageAttribute : Attribute { private string category; private string justification; private string checkId; private string scope; private string target; private string messageId; public SuppressMessageAttribute( string category, string checkId ) { this.category = category; this.checkId = checkId; } public string Category { get { return category; } } public string CheckId { get { return checkId; } } public string Scope { get { return scope; } set { scope = value; } } public string Target { get { return target; } set { target = value; } } public string MessageId { get { return messageId; } set { messageId = value; } } public string Justification { get { return justification; } set { justification = value; } } } } ================================================ FILE: Zelig/Zelig/RunTime/Framework/mscorlib/System/Diagnostics/ConditionalAttribute.cs ================================================ // ==++== // // Copyright (c) Microsoft Corporation. All rights reserved. // // ==--== using System; namespace System.Diagnostics { [Serializable] [AttributeUsage( AttributeTargets.Method | AttributeTargets.Class, AllowMultiple = true )] public sealed class ConditionalAttribute : Attribute { private String m_conditionString; public ConditionalAttribute( String conditionString ) { m_conditionString = conditionString; } public String ConditionString { get { return m_conditionString; } } } } ================================================ FILE: Zelig/Zelig/RunTime/Framework/mscorlib/System/Diagnostics/Contracts/Contracts.cs ================================================ // Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. /*============================================================ ** ** ** ** Purpose: The contract class allows for expressing preconditions, ** postconditions, and object invariants about methods in source ** code for runtime checking & static analysis. ** ** Two classes (Contract and ContractHelper) are split into partial classes ** in order to share the public front for multiple platforms (this file) ** while providing separate implementation details for each platform. ** ===========================================================*/ #define DEBUG // The behavior of this contract library should be consistent regardless of build type. #if SILVERLIGHT #define FEATURE_UNTRUSTED_CALLERS #elif REDHAWK_RUNTIME #elif BARTOK_RUNTIME #else // CLR #define FEATURE_UNTRUSTED_CALLERS ////#define FEATURE_RELIABILITY_CONTRACTS #define FEATURE_SERIALIZATION #endif using System; using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; using System.Diagnostics.Contracts; #if FEATURE_RELIABILITY_CONTRACTS using System.Runtime.ConstrainedExecution; #endif #if FEATURE_UNTRUSTED_CALLERS using System.Security; using System.Security.Permissions; #endif namespace System.Diagnostics.Contracts { #region Attributes /// /// Methods and classes marked with this attribute can be used within calls to Contract methods. Such methods not make any visible state changes. /// [Conditional("CONTRACTS_FULL")] [AttributeUsage(AttributeTargets.Constructor | AttributeTargets.Method | AttributeTargets.Property | AttributeTargets.Event | AttributeTargets.Delegate | AttributeTargets.Class | AttributeTargets.Parameter, AllowMultiple = false, Inherited = true)] public sealed class PureAttribute : Attribute { } /// /// Types marked with this attribute specify that a separate type contains the contracts for this type. /// [Conditional("CONTRACTS_FULL")] [Conditional("DEBUG")] [AttributeUsage(AttributeTargets.Class | AttributeTargets.Interface | AttributeTargets.Delegate, AllowMultiple = false, Inherited = false)] public sealed class ContractClassAttribute : Attribute { private Type _typeWithContracts; public ContractClassAttribute(Type typeContainingContracts) { _typeWithContracts = typeContainingContracts; } public Type TypeContainingContracts { get { return _typeWithContracts; } } } /// /// Types marked with this attribute specify that they are a contract for the type that is the argument of the constructor. /// [Conditional("CONTRACTS_FULL")] [AttributeUsage(AttributeTargets.Class, AllowMultiple = false, Inherited = false)] public sealed class ContractClassForAttribute : Attribute { private Type _typeIAmAContractFor; public ContractClassForAttribute(Type typeContractsAreFor) { _typeIAmAContractFor = typeContractsAreFor; } public Type TypeContractsAreFor { get { return _typeIAmAContractFor; } } } /// /// This attribute is used to mark a method as being the invariant /// method for a class. The method can have any name, but it must /// return "void" and take no parameters. The body of the method /// must consist solely of one or more calls to the method /// Contract.Invariant. A suggested name for the method is /// "ObjectInvariant". /// [Conditional("CONTRACTS_FULL")] [AttributeUsage(AttributeTargets.Method, AllowMultiple = false, Inherited = false)] public sealed class ContractInvariantMethodAttribute : Attribute { } /// /// Attribute that specifies that an assembly is a reference assembly with contracts. /// [AttributeUsage(AttributeTargets.Assembly)] public sealed class ContractReferenceAssemblyAttribute : Attribute { } /// /// Methods (and properties) marked with this attribute can be used within calls to Contract methods, but have no runtime behavior associated with them. /// [Conditional("CONTRACTS_FULL")] [AttributeUsage(AttributeTargets.Method | AttributeTargets.Property, AllowMultiple = false, Inherited = true)] public sealed class ContractRuntimeIgnoredAttribute : Attribute { } /* #if FEATURE_SERIALIZATION [Serializable] #endif internal enum Mutability { Immutable, // read-only after construction, except for lazy initialization & caches // Do we need a "deeply immutable" value? Mutable, HasInitializationPhase, // read-only after some point. // Do we need a value for mutable types with read-only wrapper subclasses? } // Note: This hasn't been thought through in any depth yet. Consider it experimental. // We should replace this with Joe's concepts. [Conditional("CONTRACTS_FULL")] [AttributeUsage(AttributeTargets.Class | AttributeTargets.Struct, AllowMultiple = false, Inherited = false)] [SuppressMessage("Microsoft.Design", "CA1019:DefineAccessorsForAttributeArguments", Justification = "Thank you very much, but we like the names we've defined for the accessors")] internal sealed class MutabilityAttribute : Attribute { private Mutability _mutabilityMarker; public MutabilityAttribute(Mutability mutabilityMarker) { _mutabilityMarker = mutabilityMarker; } public Mutability Mutability { get { return _mutabilityMarker; } } } */ /// /// Instructs downstream tools whether to assume the correctness of this assembly, type or member without performing any verification or not. /// Can use [ContractVerification(false)] to explicitly mark assembly, type or member as one to *not* have verification performed on it. /// Most specific element found (member, type, then assembly) takes precedence. /// (That is useful if downstream tools allow a user to decide which polarity is the default, unmarked case.) /// /// /// Apply this attribute to a type to apply to all members of the type, including nested types. /// Apply this attribute to an assembly to apply to all types and members of the assembly. /// Apply this attribute to a property to apply to both the getter and setter. /// [Conditional("CONTRACTS_FULL")] [AttributeUsage(AttributeTargets.Assembly | AttributeTargets.Class | AttributeTargets.Struct | AttributeTargets.Method | AttributeTargets.Constructor | AttributeTargets.Property)] public sealed class ContractVerificationAttribute : Attribute { private bool _value; public ContractVerificationAttribute(bool value) { _value = value; } public bool Value { get { return _value; } } } /// /// Allows a field f to be used in the method contracts for a method m when f has less visibility than m. /// For instance, if the method is public, but the field is private. /// [Conditional("CONTRACTS_FULL")] [AttributeUsage(AttributeTargets.Field)] [SuppressMessage("Microsoft.Design", "CA1019:DefineAccessorsForAttributeArguments", Justification = "Thank you very much, but we like the names we've defined for the accessors")] public sealed class ContractPublicPropertyNameAttribute : Attribute { private String _publicName; public ContractPublicPropertyNameAttribute(String name) { _publicName = name; } public String Name { get { return _publicName; } } } /// /// Enables factoring legacy if-then-throw into separate methods for reuse and full control over /// thrown exception and arguments /// [AttributeUsage(AttributeTargets.Method, AllowMultiple = false)] [Conditional("CONTRACTS_FULL")] public sealed class ContractArgumentValidatorAttribute : Attribute { } /// /// Enables writing abbreviations for contracts that get copied to other methods /// [AttributeUsage(AttributeTargets.Method, AllowMultiple = false)] [Conditional("CONTRACTS_FULL")] public sealed class ContractAbbreviatorAttribute : Attribute { } /// /// Allows setting contract and tool options at assembly, type, or method granularity. /// [AttributeUsage(AttributeTargets.All, AllowMultiple = true, Inherited = false)] [Conditional("CONTRACTS_FULL")] public sealed class ContractOptionAttribute : Attribute { private String _category; private String _setting; private bool _enabled; private String _value; public ContractOptionAttribute(String category, String setting, bool enabled) { _category = category; _setting = setting; _enabled = enabled; } public ContractOptionAttribute(String category, String setting, String value) { _category = category; _setting = setting; _value = value; } public String Category { get { return _category; } } public String Setting { get { return _setting; } } public bool Enabled { get { return _enabled; } } public String Value { get { return _value; } } } #endregion Attributes #if ENABLE_CONTRACTS /// /// Contains static methods for representing program contracts such as preconditions, postconditions, and invariants. /// /// /// WARNING: A binary rewriter must be used to insert runtime enforcement of these contracts. /// Otherwise some contracts like Ensures can only be checked statically and will not throw exceptions during runtime when contracts are violated. /// Please note this class uses conditional compilation to help avoid easy mistakes. Defining the preprocessor /// symbol CONTRACTS_PRECONDITIONS will include all preconditions expressed using Contract.Requires in your /// build. The symbol CONTRACTS_FULL will include postconditions and object invariants, and requires the binary rewriter. /// public static partial class Contract { #region User Methods #region Assume /// /// Instructs code analysis tools to assume the expression is true even if it can not be statically proven to always be true. /// /// Expression to assume will always be true. /// /// At runtime this is equivalent to an . /// [Pure] [Conditional("DEBUG")] [Conditional("CONTRACTS_FULL")] #if FEATURE_RELIABILITY_CONTRACTS [ReliabilityContract(Consistency.WillNotCorruptState, Cer.MayFail)] #endif public static void Assume(bool condition) { if (!condition) { ReportFailure(ContractFailureKind.Assume, null, null, null); } } /// /// Instructs code analysis tools to assume the expression is true even if it can not be statically proven to always be true. /// /// Expression to assume will always be true. /// If it is not a constant string literal, then the contract may not be understood by tools. /// /// At runtime this is equivalent to an . /// [Pure] [Conditional("DEBUG")] [Conditional("CONTRACTS_FULL")] #if FEATURE_RELIABILITY_CONTRACTS [ReliabilityContract(Consistency.WillNotCorruptState, Cer.MayFail)] #endif public static void Assume(bool condition, String userMessage) { if (!condition) { ReportFailure(ContractFailureKind.Assume, userMessage, null, null); } } #endregion Assume #region Assert /// /// In debug builds, perform a runtime check that is true. /// /// Expression to check to always be true. [Pure] [Conditional("DEBUG")] [Conditional("CONTRACTS_FULL")] #if FEATURE_RELIABILITY_CONTRACTS [ReliabilityContract(Consistency.WillNotCorruptState, Cer.MayFail)] #endif public static void Assert(bool condition) { if (!condition) ReportFailure(ContractFailureKind.Assert, null, null, null); } /// /// In debug builds, perform a runtime check that is true. /// /// Expression to check to always be true. /// If it is not a constant string literal, then the contract may not be understood by tools. [Pure] [Conditional("DEBUG")] [Conditional("CONTRACTS_FULL")] #if FEATURE_RELIABILITY_CONTRACTS [ReliabilityContract(Consistency.WillNotCorruptState, Cer.MayFail)] #endif public static void Assert(bool condition, String userMessage) { if (!condition) ReportFailure(ContractFailureKind.Assert, userMessage, null, null); } #endregion Assert #region Requires /// /// Specifies a contract such that the expression must be true before the enclosing method or property is invoked. /// /// Boolean expression representing the contract. /// /// This call must happen at the beginning of a method or property before any other code. /// This contract is exposed to clients so must only reference members at least as visible as the enclosing method. /// Use this form when backward compatibility does not force you to throw a particular exception. /// [Pure] [Conditional("CONTRACTS_FULL")] #if FEATURE_RELIABILITY_CONTRACTS [ReliabilityContract(Consistency.WillNotCorruptState, Cer.MayFail)] #endif public static void Requires(bool condition) { AssertMustUseRewriter(ContractFailureKind.Precondition, "Requires"); } /// /// Specifies a contract such that the expression must be true before the enclosing method or property is invoked. /// /// Boolean expression representing the contract. /// If it is not a constant string literal, then the contract may not be understood by tools. /// /// This call must happen at the beginning of a method or property before any other code. /// This contract is exposed to clients so must only reference members at least as visible as the enclosing method. /// Use this form when backward compatibility does not force you to throw a particular exception. /// [Pure] [Conditional("CONTRACTS_FULL")] #if FEATURE_RELIABILITY_CONTRACTS [ReliabilityContract(Consistency.WillNotCorruptState, Cer.MayFail)] #endif public static void Requires(bool condition, String userMessage) { AssertMustUseRewriter(ContractFailureKind.Precondition, "Requires"); } /// /// Specifies a contract such that the expression must be true before the enclosing method or property is invoked. /// /// Boolean expression representing the contract. /// /// This call must happen at the beginning of a method or property before any other code. /// This contract is exposed to clients so must only reference members at least as visible as the enclosing method. /// Use this form when you want to throw a particular exception. /// [SuppressMessage("Microsoft.Usage", "CA1801:ReviewUnusedParameters", MessageId = "condition")] [SuppressMessage("Microsoft.Design", "CA1004:GenericMethodsShouldProvideTypeParameter")] [Pure] #if FEATURE_RELIABILITY_CONTRACTS [ReliabilityContract(Consistency.WillNotCorruptState, Cer.MayFail)] #endif public static void Requires(bool condition) where TException : Exception { AssertMustUseRewriter(ContractFailureKind.Precondition, "Requires"); } /// /// Specifies a contract such that the expression must be true before the enclosing method or property is invoked. /// /// Boolean expression representing the contract. /// If it is not a constant string literal, then the contract may not be understood by tools. /// /// This call must happen at the beginning of a method or property before any other code. /// This contract is exposed to clients so must only reference members at least as visible as the enclosing method. /// Use this form when you want to throw a particular exception. /// [SuppressMessage("Microsoft.Usage", "CA1801:ReviewUnusedParameters", MessageId = "userMessage")] [SuppressMessage("Microsoft.Usage", "CA1801:ReviewUnusedParameters", MessageId = "condition")] [SuppressMessage("Microsoft.Design", "CA1004:GenericMethodsShouldProvideTypeParameter")] [Pure] #if FEATURE_RELIABILITY_CONTRACTS [ReliabilityContract(Consistency.WillNotCorruptState, Cer.MayFail)] #endif public static void Requires(bool condition, String userMessage) where TException : Exception { AssertMustUseRewriter(ContractFailureKind.Precondition, "Requires"); } #endregion Requires #region Ensures /// /// Specifies a public contract such that the expression will be true when the enclosing method or property returns normally. /// /// Boolean expression representing the contract. May include and . /// /// This call must happen at the beginning of a method or property before any other code. /// This contract is exposed to clients so must only reference members at least as visible as the enclosing method. /// The contract rewriter must be used for runtime enforcement of this postcondition. /// [Pure] [Conditional("CONTRACTS_FULL")] #if FEATURE_RELIABILITY_CONTRACTS [ReliabilityContract(Consistency.WillNotCorruptState, Cer.MayFail)] #endif public static void Ensures(bool condition) { AssertMustUseRewriter(ContractFailureKind.Postcondition, "Ensures"); } /// /// Specifies a public contract such that the expression will be true when the enclosing method or property returns normally. /// /// Boolean expression representing the contract. May include and . /// If it is not a constant string literal, then the contract may not be understood by tools. /// /// This call must happen at the beginning of a method or property before any other code. /// This contract is exposed to clients so must only reference members at least as visible as the enclosing method. /// The contract rewriter must be used for runtime enforcement of this postcondition. /// [Pure] [Conditional("CONTRACTS_FULL")] #if FEATURE_RELIABILITY_CONTRACTS [ReliabilityContract(Consistency.WillNotCorruptState, Cer.MayFail)] #endif public static void Ensures(bool condition, String userMessage) { AssertMustUseRewriter(ContractFailureKind.Postcondition, "Ensures"); } /// /// Specifies a contract such that if an exception of type is thrown then the expression will be true when the enclosing method or property terminates abnormally. /// /// Type of exception related to this postcondition. /// Boolean expression representing the contract. May include and . /// /// This call must happen at the beginning of a method or property before any other code. /// This contract is exposed to clients so must only reference types and members at least as visible as the enclosing method. /// The contract rewriter must be used for runtime enforcement of this postcondition. /// [Pure] [Conditional("CONTRACTS_FULL")] [SuppressMessage("Microsoft.Design", "CA1004:GenericMethodsShouldProvideTypeParameter", Justification = "Exception type used in tools.")] #if FEATURE_RELIABILITY_CONTRACTS [ReliabilityContract(Consistency.WillNotCorruptState, Cer.MayFail)] #endif public static void EnsuresOnThrow(bool condition) where TException : Exception { AssertMustUseRewriter(ContractFailureKind.PostconditionOnException, "EnsuresOnThrow"); } /// /// Specifies a contract such that if an exception of type is thrown then the expression will be true when the enclosing method or property terminates abnormally. /// /// Type of exception related to this postcondition. /// Boolean expression representing the contract. May include and . /// If it is not a constant string literal, then the contract may not be understood by tools. /// /// This call must happen at the beginning of a method or property before any other code. /// This contract is exposed to clients so must only reference types and members at least as visible as the enclosing method. /// The contract rewriter must be used for runtime enforcement of this postcondition. /// [Pure] [Conditional("CONTRACTS_FULL")] [SuppressMessage("Microsoft.Design", "CA1004:GenericMethodsShouldProvideTypeParameter", Justification = "Exception type used in tools.")] #if FEATURE_RELIABILITY_CONTRACTS [ReliabilityContract(Consistency.WillNotCorruptState, Cer.MayFail)] #endif public static void EnsuresOnThrow(bool condition, String userMessage) where TException : Exception { AssertMustUseRewriter(ContractFailureKind.PostconditionOnException, "EnsuresOnThrow"); } #region Old, Result, and Out Parameters /// /// Represents the result (a.k.a. return value) of a method or property. /// /// Type of return value of the enclosing method or property. /// Return value of the enclosing method or property. /// /// This method can only be used within the argument to the contract. /// [SuppressMessage("Microsoft.Design", "CA1004:GenericMethodsShouldProvideTypeParameter", Justification = "Not intended to be called at runtime.")] [Pure] #if FEATURE_RELIABILITY_CONTRACTS [ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)] #endif public static T Result() { return default(T); } /// /// Represents the final (output) value of an out parameter when returning from a method. /// /// Type of the out parameter. /// The out parameter. /// The output value of the out parameter. /// /// This method can only be used within the argument to the contract. /// [SuppressMessage("Microsoft.Design", "CA1021:AvoidOutParameters", MessageId = "0#", Justification = "Not intended to be called at runtime.")] [Pure] #if FEATURE_RELIABILITY_CONTRACTS [ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)] #endif public static T ValueAtReturn(out T value) { value = default(T); return value; } /// /// Represents the value of as it was at the start of the method or property. /// /// Type of . This can be inferred. /// Value to represent. This must be a field or parameter. /// Value of at the start of the method or property. /// /// This method can only be used within the argument to the contract. /// [SuppressMessage("Microsoft.Usage", "CA1801:ReviewUnusedParameters", MessageId = "value")] [Pure] #if FEATURE_RELIABILITY_CONTRACTS [ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)] #endif public static T OldValue(T value) { return default(T); } #endregion Old, Result, and Out Parameters #endregion Ensures #region Invariant /// /// Specifies a contract such that the expression will be true after every method or property on the enclosing class. /// /// Boolean expression representing the contract. /// /// This contact can only be specified in a dedicated invariant method declared on a class. /// This contract is not exposed to clients so may reference members less visible as the enclosing method. /// The contract rewriter must be used for runtime enforcement of this invariant. /// [Pure] [Conditional("CONTRACTS_FULL")] #if FEATURE_RELIABILITY_CONTRACTS [ReliabilityContract(Consistency.WillNotCorruptState, Cer.MayFail)] #endif public static void Invariant(bool condition) { AssertMustUseRewriter(ContractFailureKind.Invariant, "Invariant"); } /// /// Specifies a contract such that the expression will be true after every method or property on the enclosing class. /// /// Boolean expression representing the contract. /// If it is not a constant string literal, then the contract may not be understood by tools. /// /// This contact can only be specified in a dedicated invariant method declared on a class. /// This contract is not exposed to clients so may reference members less visible as the enclosing method. /// The contract rewriter must be used for runtime enforcement of this invariant. /// [Pure] [Conditional("CONTRACTS_FULL")] #if FEATURE_RELIABILITY_CONTRACTS [ReliabilityContract(Consistency.WillNotCorruptState, Cer.MayFail)] #endif public static void Invariant(bool condition, String userMessage) { AssertMustUseRewriter(ContractFailureKind.Invariant, "Invariant"); } #endregion Invariant #region Quantifiers #region ForAll /// /// Returns whether the returns true /// for all integers starting from to - 1. /// /// First integer to pass to . /// One greater than the last integer to pass to . /// Function that is evaluated from to - 1. /// true if returns true for all integers /// starting from to - 1. /// [Pure] #if FEATURE_RELIABILITY_CONTRACTS [ReliabilityContract(Consistency.WillNotCorruptState, Cer.MayFail)] // Assumes predicate obeys CER rules. #endif public static bool ForAll(int fromInclusive, int toExclusive, Predicate predicate) { if (fromInclusive > toExclusive) #if INSIDE_CLR throw new ArgumentException(Environment.GetResourceString("Argument_ToExclusiveLessThanFromExclusive")); #else throw new ArgumentException("fromInclusive must be less than or equal to toExclusive."); #endif if (predicate == null) throw new ArgumentNullException("predicate"); Contract.EndContractBlock(); for (int i = fromInclusive; i < toExclusive; i++) if (!predicate(i)) return false; return true; } /// /// Returns whether the returns true /// for all elements in the . /// /// The collection from which elements will be drawn from to pass to . /// Function that is evaluated on elements from . /// true if and only if returns true for all elements in /// . /// [Pure] #if FEATURE_RELIABILITY_CONTRACTS [ReliabilityContract(Consistency.WillNotCorruptState, Cer.MayFail)] // Assumes predicate & collection enumerator obey CER rules. #endif public static bool ForAll(IEnumerable collection, Predicate predicate) { if (collection == null) throw new ArgumentNullException("collection"); if (predicate == null) throw new ArgumentNullException("predicate"); Contract.EndContractBlock(); foreach (T t in collection) if (!predicate(t)) return false; return true; } #endregion ForAll #region Exists /// /// Returns whether the returns true /// for any integer starting from to - 1. /// /// First integer to pass to . /// One greater than the last integer to pass to . /// Function that is evaluated from to - 1. /// true if returns true for any integer /// starting from to - 1. /// [Pure] #if FEATURE_RELIABILITY_CONTRACTS [ReliabilityContract(Consistency.WillNotCorruptState, Cer.MayFail)] // Assumes predicate obeys CER rules. #endif public static bool Exists(int fromInclusive, int toExclusive, Predicate predicate) { if (fromInclusive > toExclusive) #if INSIDE_CLR throw new ArgumentException(Environment.GetResourceString("Argument_ToExclusiveLessThanFromExclusive")); #else throw new ArgumentException("fromInclusive must be less than or equal to toExclusive."); #endif if (predicate == null) throw new ArgumentNullException("predicate"); Contract.EndContractBlock(); for (int i = fromInclusive; i < toExclusive; i++) if (predicate(i)) return true; return false; } /// /// Returns whether the returns true /// for any element in the . /// /// The collection from which elements will be drawn from to pass to . /// Function that is evaluated on elements from . /// true if and only if returns true for an element in /// . /// [Pure] #if FEATURE_RELIABILITY_CONTRACTS [ReliabilityContract(Consistency.WillNotCorruptState, Cer.MayFail)] // Assumes predicate & collection enumerator obey CER rules. #endif public static bool Exists(IEnumerable collection, Predicate predicate) { if (collection == null) throw new ArgumentNullException("collection"); if (predicate == null) throw new ArgumentNullException("predicate"); Contract.EndContractBlock(); foreach (T t in collection) if (predicate(t)) return true; return false; } #endregion Exists #endregion Quantifiers #region Pointers #if FEATURE_UNSAFE_CONTRACTS /// /// Runtime checking for pointer bounds is not currently feasible. Thus, at runtime, we just return /// a very long extent for each pointer that is writable. As long as assertions are of the form /// WritableBytes(ptr) >= ..., the runtime assertions will not fail. /// The runtime value is 2^64 - 1 or 2^32 - 1. /// [SuppressMessage("Microsoft.Performance", "CA1802", Justification = "FxCop is confused")] static readonly ulong MaxWritableExtent = (UIntPtr.Size == 4) ? UInt32.MaxValue : UInt64.MaxValue; /// /// Allows specifying a writable extent for a UIntPtr, similar to SAL's writable extent. /// NOTE: this is for static checking only. No useful runtime code can be generated for this /// at the moment. /// /// Start of memory region /// The result is the number of bytes writable starting at [CLSCompliant(false)] [Pure] [ContractRuntimeIgnored] #if FEATURE_RELIABILITY_CONTRACTS [ReliabilityContract(Consistency.WillNotCorruptState, Cer.MayFail)] #endif public static ulong WritableBytes(UIntPtr startAddress) { return MaxWritableExtent - startAddress.ToUInt64(); } /// /// Allows specifying a writable extent for a UIntPtr, similar to SAL's writable extent. /// NOTE: this is for static checking only. No useful runtime code can be generated for this /// at the moment. /// /// Start of memory region /// The result is the number of bytes writable starting at [CLSCompliant(false)] [Pure] [ContractRuntimeIgnored] #if FEATURE_RELIABILITY_CONTRACTS [ReliabilityContract(Consistency.WillNotCorruptState, Cer.MayFail)] #endif public static ulong WritableBytes(IntPtr startAddress) { return MaxWritableExtent - (ulong)startAddress; } /// /// Allows specifying a writable extent for a UIntPtr, similar to SAL's writable extent. /// NOTE: this is for static checking only. No useful runtime code can be generated for this /// at the moment. /// /// Start of memory region /// The result is the number of bytes writable starting at [CLSCompliant(false)] [Pure] [ContractRuntimeIgnored] [SecurityCritical] #if FEATURE_RELIABILITY_CONTRACTS [ReliabilityContract(Consistency.WillNotCorruptState, Cer.MayFail)] #endif unsafe public static ulong WritableBytes(void* startAddress) { return MaxWritableExtent - (ulong)startAddress; } /// /// Allows specifying a readable extent for a UIntPtr, similar to SAL's readable extent. /// NOTE: this is for static checking only. No useful runtime code can be generated for this /// at the moment. /// /// Start of memory region /// The result is the number of bytes readable starting at [CLSCompliant(false)] [Pure] [ContractRuntimeIgnored] #if FEATURE_RELIABILITY_CONTRACTS [ReliabilityContract(Consistency.WillNotCorruptState, Cer.MayFail)] #endif public static ulong ReadableBytes(UIntPtr startAddress) { return MaxWritableExtent - startAddress.ToUInt64(); } /// /// Allows specifying a readable extent for a UIntPtr, similar to SAL's readable extent. /// NOTE: this is for static checking only. No useful runtime code can be generated for this /// at the moment. /// /// Start of memory region /// The result is the number of bytes readable starting at [CLSCompliant(false)] [Pure] [ContractRuntimeIgnored] #if FEATURE_RELIABILITY_CONTRACTS [ReliabilityContract(Consistency.WillNotCorruptState, Cer.MayFail)] #endif public static ulong ReadableBytes(IntPtr startAddress) { return MaxWritableExtent - (ulong)startAddress; } /// /// Allows specifying a readable extent for a UIntPtr, similar to SAL's readable extent. /// NOTE: this is for static checking only. No useful runtime code can be generated for this /// at the moment. /// /// Start of memory region /// The result is the number of bytes readable starting at [CLSCompliant(false)] [Pure] [ContractRuntimeIgnored] [SecurityCritical] #if FEATURE_RELIABILITY_CONTRACTS [ReliabilityContract(Consistency.WillNotCorruptState, Cer.MayFail)] #endif unsafe public static ulong ReadableBytes(void* startAddress) { return MaxWritableExtent - (ulong)startAddress; } #endif // FEATURE_UNSAFE_CONTRACTS #endregion #region Misc. /// /// Marker to indicate the end of the contract section of a method. /// [Conditional("CONTRACTS_FULL")] #if FEATURE_RELIABILITY_CONTRACTS [ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)] #endif public static void EndContractBlock() { } #endregion #endregion User Methods #region Failure Behavior /// /// Without contract rewriting, failing Assert/Assumes end up calling this method. /// Code going through the contract rewriter never calls this method. Instead, the rewriter produced failures call /// System.Runtime.CompilerServices.ContractHelper.RaiseContractFailedEvent, followed by /// System.Runtime.CompilerServices.ContractHelper.TriggerFailure. /// static partial void ReportFailure(ContractFailureKind failureKind, String userMessage, String conditionText, Exception innerException); /// /// This method is used internally to trigger a failure indicating to the "programmer" that he is using the interface incorrectly. /// It is NEVER used to indicate failure of actual contracts at runtime. /// static partial void AssertMustUseRewriter(ContractFailureKind kind, String contractKind); #endregion } #endif // ENABLE_CONTRACTS public enum ContractFailureKind { Precondition, [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "Postcondition")] Postcondition, [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "Postcondition")] PostconditionOnException, Invariant, Assert, Assume, } } // Note: In .NET FX 4.5, we duplicated the ContractHelper class in the System.Runtime.CompilerServices // namespace to remove an ugly wart of a namespace from the Windows 8 profile. But we still need the // old locations left around, so we can support rewritten .NET FX 4.0 libraries. Consider removing // these from our reference assembly in a future version. namespace System.Diagnostics.Contracts.Internal { [Obsolete("Use the ContractHelper class in the System.Runtime.CompilerServices namespace instead.")] public static class ContractHelper { #region Rewriter Failure Hooks /// /// Rewriter will call this method on a contract failure to allow listeners to be notified. /// The method should not perform any failure (assert/throw) itself. /// /// null if the event was handled and should not trigger a failure. /// Otherwise, returns the localized failure message [SuppressMessage("Microsoft.Design", "CA1030:UseEventsWhereAppropriate")] [System.Diagnostics.DebuggerNonUserCode] #if FEATURE_RELIABILITY_CONTRACTS [ReliabilityContract(Consistency.WillNotCorruptState, Cer.MayFail)] #endif public static string RaiseContractFailedEvent(ContractFailureKind failureKind, String userMessage, String conditionText, Exception innerException) { return System.Runtime.CompilerServices.ContractHelper.RaiseContractFailedEvent(failureKind, userMessage, conditionText, innerException); } /// /// Rewriter calls this method to get the default failure behavior. /// [System.Diagnostics.DebuggerNonUserCode] #if FEATURE_RELIABILITY_CONTRACTS [ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)] #endif public static void TriggerFailure(ContractFailureKind kind, String displayMessage, String userMessage, String conditionText, Exception innerException) { System.Runtime.CompilerServices.ContractHelper.TriggerFailure(kind, displayMessage, userMessage, conditionText, innerException); } #endregion Rewriter Failure Hooks } } // namespace System.Diagnostics.Contracts.Internal namespace System.Runtime.CompilerServices { public static partial class ContractHelper { #region Rewriter Failure Hooks /// /// Rewriter will call this method on a contract failure to allow listeners to be notified. /// The method should not perform any failure (assert/throw) itself. /// /// null if the event was handled and should not trigger a failure. /// Otherwise, returns the localized failure message [SuppressMessage("Microsoft.Design", "CA1030:UseEventsWhereAppropriate")] [System.Diagnostics.DebuggerNonUserCode] #if FEATURE_RELIABILITY_CONTRACTS [ReliabilityContract(Consistency.WillNotCorruptState, Cer.MayFail)] #endif public static string RaiseContractFailedEvent(ContractFailureKind failureKind, String userMessage, String conditionText, Exception innerException) { var resultFailureMessage = "Contract failed"; // default in case implementation does not assign anything. RaiseContractFailedEventImplementation(failureKind, userMessage, conditionText, innerException, ref resultFailureMessage); return resultFailureMessage; } /// /// Rewriter calls this method to get the default failure behavior. /// [System.Diagnostics.DebuggerNonUserCode] #if FEATURE_RELIABILITY_CONTRACTS [ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)] #endif public static void TriggerFailure(ContractFailureKind kind, String displayMessage, String userMessage, String conditionText, Exception innerException) { TriggerFailureImplementation(kind, displayMessage, userMessage, conditionText, innerException); } #endregion Rewriter Failure Hooks #region Implementation Stubs /// /// Rewriter will call this method on a contract failure to allow listeners to be notified. /// The method should not perform any failure (assert/throw) itself. /// This method has 3 functions: /// 1. Call any contract hooks (such as listeners to Contract failed events) /// 2. Determine if the listeneres deem the failure as handled (then resultFailureMessage should be set to null) /// 3. Produce a localized resultFailureMessage used in advertising the failure subsequently. /// /// Should really be out (or the return value), but partial methods are not flexible enough. /// On exit: null if the event was handled and should not trigger a failure. /// Otherwise, returns the localized failure message static partial void RaiseContractFailedEventImplementation(ContractFailureKind failureKind, String userMessage, String conditionText, Exception innerException, ref string resultFailureMessage); /// /// Implements the default failure behavior of the platform. Under the BCL, it triggers an Assert box. /// static partial void TriggerFailureImplementation(ContractFailureKind kind, String displayMessage, String userMessage, String conditionText, Exception innerException); #endregion Implementation Stubs } } // namespace System.Runtime.CompilerServices ================================================ FILE: Zelig/Zelig/RunTime/Framework/mscorlib/System/Diagnostics/Debugger.cs ================================================ // ==++== // // Copyright (c) Microsoft Corporation. All rights reserved. // // ==--== // The Debugger class is a part of the System.Diagnostics package // and is used for communicating with a debugger. namespace System.Diagnostics { using System; ////using System.IO; using System.Collections; using System.Reflection; using System.Runtime.CompilerServices; ////using System.Security; ////using System.Security.Permissions; ////using System.Runtime.Versioning; // No data, does not need to be marked with the serializable attribute public sealed class Debugger { // Break causes a breakpoint to be signalled to an attached debugger. If no debugger // is attached, the user is asked if he wants to attach a debugger. If yes, then the // debugger is launched. //// [ResourceExposure( ResourceScope.Process )] //// [ResourceConsumption( ResourceScope.Process )] [MethodImpl( MethodImplOptions.InternalCall )] public extern static void Break(); //// { //// if(!IsDebuggerAttached()) //// { //// // Try and demand UnmanagedCodePermission. This is done in a try block because if this //// // fails we want to be able to silently eat the exception and just return so //// // that the call to Break does not possibly cause an unhandled exception. //// // The idea here is that partially trusted code shouldn't be able to launch a debugger //// // without the user going through Watson. //// try //// { //// new SecurityPermission( SecurityPermissionFlag.UnmanagedCode ).Demand(); //// } //// //// // If we enter this block, we do not have permission to break into the debugger //// // and so we just return. //// catch(SecurityException) //// { //// return; //// } //// } //// //// // Causing a break is now allowed. //// BreakInternal(); //// } //// [ResourceExposure( ResourceScope.Process )] //// [ResourceConsumption( ResourceScope.Process )] //// static void BreakCanThrow() //// { //// if(!IsDebuggerAttached()) //// { //// new SecurityPermission( SecurityPermissionFlag.UnmanagedCode ).Demand(); //// } //// //// // Causing a break is now allowed. //// BreakInternal(); //// } //// //// [ResourceExposure( ResourceScope.Process )] //// [MethodImplAttribute( MethodImplOptions.InternalCall )] //// private static extern void BreakInternal(); //// // Launch launches & attaches a debugger to the process. If a debugger is already attached, //// // nothing happens. //// // //// [ResourceExposure( ResourceScope.Machine )] //// [ResourceConsumption( ResourceScope.Machine )] //// public static bool Launch() //// { //// if(IsDebuggerAttached()) //// return (true); //// //// // Try and demand UnmanagedCodePermission. This is done in a try block because if this //// // fails we want to be able to silently eat the exception and just return so //// // that the call to Break does not possibly cause an unhandled exception. //// // The idea here is that partially trusted code shouldn't be able to launch a debugger //// // without the user going through Watson. //// try //// { //// new SecurityPermission( SecurityPermissionFlag.UnmanagedCode ).Demand(); //// } //// //// // If we enter this block, we do not have permission to break into the debugger //// // and so we just return. //// catch(SecurityException) //// { //// return (false); //// } //// //// // Causing the debugger to launch is now allowed. //// return (LaunchInternal()); //// } //// //// [ResourceExposure( ResourceScope.Machine )] //// [MethodImplAttribute( MethodImplOptions.InternalCall )] //// private static extern bool LaunchInternal(); // Returns whether or not a debugger is attached to the process. // public static bool IsAttached { //// [ResourceExposure( ResourceScope.Process )] //// [ResourceConsumption( ResourceScope.Process )] get { return IsDebuggerAttached(); } } //// [ResourceExposure( ResourceScope.Process )] [MethodImplAttribute( MethodImplOptions.InternalCall )] private static extern bool IsDebuggerAttached(); // Constants representing the importance level of messages to be logged. // // An attached debugger can enable or disable which messages will // actually be reported to the user through the COM+ debugger // services API. This info is communicated to the runtime so only // desired events are actually reported to the debugger. // // Constant representing the default category public static readonly String DefaultCategory = null; // Posts a message for the attached debugger. If there is no // debugger attached, has no effect. The debugger may or may not // report the message depending on its settings. //// [ResourceExposure( ResourceScope.None )] [MethodImplAttribute( MethodImplOptions.InternalCall )] public static extern void Log( int level, String category, String message ); } } ================================================ FILE: Zelig/Zelig/RunTime/Framework/mscorlib/System/Diagnostics/DebuggerAttributes.cs ================================================ // ==++== // // Copyright (c) Microsoft Corporation. All rights reserved. // // ==--== /*============================================================ ** ** Class: DebuggerAttributes ** ** ** Purpose: Attributes for debugger ** ** ===========================================================*/ namespace System.Diagnostics { using System; using System.Runtime.InteropServices; [Serializable] [AttributeUsage( AttributeTargets.Class | AttributeTargets.Struct | AttributeTargets.Method | AttributeTargets.Constructor, Inherited = false )] public sealed class DebuggerStepThroughAttribute : Attribute { public DebuggerStepThroughAttribute() { } } [Serializable] [AttributeUsage( AttributeTargets.Method | AttributeTargets.Constructor, Inherited = false )] public sealed class DebuggerStepperBoundaryAttribute : Attribute { public DebuggerStepperBoundaryAttribute() { } } [Serializable] [AttributeUsage( AttributeTargets.Method | AttributeTargets.Property | AttributeTargets.Constructor, Inherited = false )] public sealed class DebuggerHiddenAttribute : Attribute { public DebuggerHiddenAttribute() { } } [Serializable] [AttributeUsage( AttributeTargets.Class | AttributeTargets.Method | AttributeTargets.Property | AttributeTargets.Constructor | AttributeTargets.Struct, Inherited = false )] public sealed class DebuggerNonUserCodeAttribute : Attribute { public DebuggerNonUserCodeAttribute() { } } // Attribute class used by the compiler to mark modules. // If present, then debugging information for everything in the // assembly was generated by the compiler, and will be preserved // by the Runtime so that the debugger can provide full functionality // in the case of JIT attach. If not present, then the compiler may // or may not have included debugging information, and the Runtime // won't preserve the debugging info, which will make debugging after // a JIT attach difficult. [AttributeUsage( AttributeTargets.Assembly | AttributeTargets.Module, AllowMultiple = false )] public sealed class DebuggableAttribute : Attribute { [Flags] public enum DebuggingModes { None = 0x000, Default = 0x001, IgnoreSymbolStoreSequencePoints = 0x002, EnableEditAndContinue = 0x004, DisableOptimizations = 0x100, } private DebuggingModes m_debuggingModes; public DebuggableAttribute( bool isJITTrackingEnabled, bool isJITOptimizerDisabled ) { m_debuggingModes = 0; if(isJITTrackingEnabled) { m_debuggingModes |= DebuggingModes.Default; } if(isJITOptimizerDisabled) { m_debuggingModes |= DebuggingModes.DisableOptimizations; } } public DebuggableAttribute( DebuggingModes modes ) { m_debuggingModes = modes; } public bool IsJITTrackingEnabled { get { return ((m_debuggingModes & DebuggingModes.Default) != 0); } } public bool IsJITOptimizerDisabled { get { return ((m_debuggingModes & DebuggingModes.DisableOptimizations) != 0); } } public DebuggingModes DebuggingFlags { get { return m_debuggingModes; } } } // DebuggerBrowsableState states are defined as follows: // Never never show this element // Expanded expansion of the class is done, so that all visible internal members are shown // Collapsed expansion of the class is not performed. Internal visible members are hidden // RootHidden The target element itself should not be shown, but should instead be // automatically expanded to have its members displayed. // Default value is collapsed // Please also change the code which validates DebuggerBrowsableState variable (in this file) // if you change this enum. public enum DebuggerBrowsableState { Never = 0, //Expanded is not supported in this release //Expanded = 1, Collapsed = 2, RootHidden = 3, } // the one currently supported with the csee.dat // (mcee.dat, autoexp.dat) file. [AttributeUsage( AttributeTargets.Field | AttributeTargets.Property, AllowMultiple = false )] public sealed class DebuggerBrowsableAttribute : Attribute { private DebuggerBrowsableState m_state; public DebuggerBrowsableAttribute( DebuggerBrowsableState state ) { if(state < DebuggerBrowsableState.Never || state > DebuggerBrowsableState.RootHidden) { #if EXCEPTION_STRINGS throw new ArgumentOutOfRangeException( "state" ); #else throw new ArgumentOutOfRangeException(); #endif } m_state = state; } public DebuggerBrowsableState State { get { return m_state; } } } // DebuggerTypeProxyAttribute [AttributeUsage( AttributeTargets.Struct | AttributeTargets.Class | AttributeTargets.Assembly, AllowMultiple = true )] public sealed class DebuggerTypeProxyAttribute : Attribute { private string m_typeName; private string m_targetName; private Type m_target; public DebuggerTypeProxyAttribute( Type type ) { if(type == null) { #if EXCEPTION_STRINGS throw new ArgumentNullException( "type" ); #else throw new ArgumentNullException(); #endif } m_typeName = type.AssemblyQualifiedName; } public DebuggerTypeProxyAttribute( string typeName ) { m_typeName = typeName; } public string ProxyTypeName { get { return m_typeName; } } public Type Target { set { if(value == null) { #if EXCEPTION_STRINGS throw new ArgumentNullException( "value" ); #else throw new ArgumentNullException(); #endif } m_targetName = value.AssemblyQualifiedName; m_target = value; } get { return m_target; } } public string TargetTypeName { get { return m_targetName; } set { m_targetName = value; } } } // This attribute is used to control what is displayed for the given class or field // in the data windows in the debugger. The single argument to this attribute is // the string that will be displayed in the value column for instances of the type. // This string can include text between { and } which can be either a field, // property or method (as will be documented in mscorlib). In the C# case, // a general expression will be allowed which only has implicit access to the this pointer // for the current instance of the target type. The expression will be limited, // however: there is no access to aliases, locals, or pointers. // In addition, attributes on properties referenced in the expression are not processed. [AttributeUsage( AttributeTargets.Class | AttributeTargets.Struct | AttributeTargets.Delegate | AttributeTargets.Enum | AttributeTargets.Field | AttributeTargets.Property | AttributeTargets.Assembly, AllowMultiple = true )] public sealed class DebuggerDisplayAttribute : Attribute { private string m_name; private string m_value; private string m_type; private string m_targetName; private Type m_target; public DebuggerDisplayAttribute( string value ) { if(value == null) { m_value = ""; } else { m_value = value; } m_name = ""; m_type = ""; } public string Value { get { return m_value; } } public string Name { get { return m_name; } set { m_name = value; } } public string Type { get { return m_type; } set { m_type = value; } } public Type Target { set { if(value == null) { #if EXCEPTION_STRINGS throw new ArgumentNullException( "value" ); #else throw new ArgumentNullException(); #endif } m_targetName = value.AssemblyQualifiedName; m_target = value; } get { return m_target; } } public string TargetTypeName { get { return m_targetName; } set { m_targetName = value; } } } /// /// Signifies that the attributed type has a visualizer which is pointed /// to by the parameter type name strings. /// [AttributeUsage( AttributeTargets.Struct | AttributeTargets.Class | AttributeTargets.Assembly, AllowMultiple = true )] public sealed class DebuggerVisualizerAttribute : Attribute { private string m_visualizerObjectSourceName; private string m_visualizerName; private string m_description; private string m_targetName; private Type m_target; public DebuggerVisualizerAttribute( string visualizerTypeName ) { m_visualizerName = visualizerTypeName; } public DebuggerVisualizerAttribute( string visualizerTypeName, string visualizerObjectSourceTypeName ) { m_visualizerName = visualizerTypeName; m_visualizerObjectSourceName = visualizerObjectSourceTypeName; } public DebuggerVisualizerAttribute( string visualizerTypeName, Type visualizerObjectSource ) { if(visualizerObjectSource == null) { #if EXCEPTION_STRINGS throw new ArgumentNullException( "visualizerObjectSource" ); #else throw new ArgumentNullException(); #endif } m_visualizerName = visualizerTypeName; m_visualizerObjectSourceName = visualizerObjectSource.AssemblyQualifiedName; } public DebuggerVisualizerAttribute( Type visualizer ) { if(visualizer == null) { #if EXCEPTION_STRINGS throw new ArgumentNullException( "visualizer" ); #else throw new ArgumentNullException(); #endif } m_visualizerName = visualizer.AssemblyQualifiedName; } public DebuggerVisualizerAttribute( Type visualizer, Type visualizerObjectSource ) { if(visualizer == null) { #if EXCEPTION_STRINGS throw new ArgumentNullException( "visualizer" ); #else throw new ArgumentNullException(); #endif } if(visualizerObjectSource == null) { #if EXCEPTION_STRINGS throw new ArgumentNullException( "visualizerObjectSource" ); #else throw new ArgumentNullException(); #endif } m_visualizerName = visualizer .AssemblyQualifiedName; m_visualizerObjectSourceName = visualizerObjectSource.AssemblyQualifiedName; } public DebuggerVisualizerAttribute( Type visualizer, string visualizerObjectSourceTypeName ) { if(visualizer == null) { #if EXCEPTION_STRINGS throw new ArgumentNullException( "visualizer" ); #else throw new ArgumentNullException(); #endif } m_visualizerName = visualizer.AssemblyQualifiedName; m_visualizerObjectSourceName = visualizerObjectSourceTypeName; } public string VisualizerObjectSourceTypeName { get { return m_visualizerObjectSourceName; } } public string VisualizerTypeName { get { return m_visualizerName; } } public string Description { get { return m_description; } set { m_description = value; } } public Type Target { set { if(value == null) { #if EXCEPTION_STRINGS throw new ArgumentNullException( "value" ); #else throw new ArgumentNullException(); #endif } m_targetName = value.AssemblyQualifiedName; m_target = value; } get { return m_target; } } public string TargetTypeName { set { m_targetName = value; } get { return m_targetName; } } } } ================================================ FILE: Zelig/Zelig/RunTime/Framework/mscorlib/System/Diagnostics/StackFrame.cs ================================================ // ==++== // // Copyright (c) Microsoft Corporation. All rights reserved. // // ==--== namespace System.Diagnostics { using System.Text; using System; ////using System.IO; using System.Reflection; ////using System.Security.Permissions; // There is no good reason for the methods of this class to be virtual. // In order to ensure trusted code can trust the data it gets from a // StackTrace, we use an InheritanceDemand to prevent partially-trusted // subclasses. ////[SecurityPermission( SecurityAction.InheritanceDemand, UnmanagedCode = true )] [Serializable] public class StackFrame { private MethodBase method; private int offset; private int ILOffset; private String strFileName; private int iLineNumber; private int iColumnNumber; internal void InitMembers( ) { method = null; offset = OFFSET_UNKNOWN; ILOffset = OFFSET_UNKNOWN; strFileName = null; iLineNumber = 0; iColumnNumber = 0; } // Constructs a StackFrame corresponding to the active stack frame. public StackFrame( ) { InitMembers( ); BuildStackFrame( 0 + StackTrace.METHODS_TO_SKIP, false );// iSkipFrames=0 } // Constructs a StackFrame corresponding to the active stack frame. public StackFrame( bool fNeedFileInfo ) { InitMembers( ); BuildStackFrame( 0 + StackTrace.METHODS_TO_SKIP, fNeedFileInfo );// iSkipFrames=0 } // Constructs a StackFrame corresponding to a calling stack frame. // public StackFrame( int skipFrames ) { InitMembers( ); BuildStackFrame( skipFrames + StackTrace.METHODS_TO_SKIP, false ); } // Constructs a StackFrame corresponding to a calling stack frame. // public StackFrame( int skipFrames, bool fNeedFileInfo ) { InitMembers( ); BuildStackFrame( skipFrames + StackTrace.METHODS_TO_SKIP, fNeedFileInfo ); } // Called from the class "StackTrace" // internal StackFrame( bool DummyFlag1, bool DummyFlag2 ) { InitMembers( ); } // Constructs a "fake" stack frame, just containing the given file // name and line number. Use when you don't want to use the // debugger's line mapping logic. // public StackFrame( String fileName, int lineNumber ) { InitMembers( ); BuildStackFrame( StackTrace.METHODS_TO_SKIP, false ); strFileName = fileName; iLineNumber = lineNumber; iColumnNumber = 0; } // Constructs a "fake" stack frame, just containing the given file // name, line number and column number. Use when you don't want to // use the debugger's line mapping logic. // public StackFrame( String fileName, int lineNumber, int colNumber ) { InitMembers( ); BuildStackFrame( StackTrace.METHODS_TO_SKIP, false ); strFileName = fileName; iLineNumber = lineNumber; iColumnNumber = colNumber; } // Constant returned when the native or IL offset is unknown public const int OFFSET_UNKNOWN = -1; internal virtual void SetMethodBase( MethodBase mb ) { method = mb; } internal virtual void SetOffset( int iOffset ) { offset = iOffset; } internal virtual void SetILOffset( int iOffset ) { ILOffset = iOffset; } internal virtual void SetFileName( String strFName ) { strFileName = strFName; } internal virtual void SetLineNumber( int iLine ) { iLineNumber = iLine; } internal virtual void SetColumnNumber( int iCol ) { iColumnNumber = iCol; } // Returns the method the frame is executing // public virtual MethodBase GetMethod() { return method; } // Returns the offset from the start of the native (jitted) code for the // method being executed // public virtual int GetNativeOffset( ) { return offset; } // Returns the offset from the start of the IL code for the // method being executed. This offset may be approximate depending // on whether the jitter is generating debuggable code or not. // public virtual int GetILOffset( ) { return ILOffset; } // Returns the file name containing the code being executed. This // information is normally extracted from the debugging symbols // for the executable. // public virtual String GetFileName( ) { //////if(strFileName != null) //////{ ////// // This isn't really correct, but we don't have ////// // a permission that protects discovery of potentially ////// // local urls so we'll use this. ////// FileIOPermission perm = new FileIOPermission( PermissionState.None ); ////// perm.AllFiles = FileIOPermissionAccess.PathDiscovery; ////// perm.Demand( ); //////} return strFileName; } // Returns the line number in the file containing the code being executed. // This information is normally extracted from the debugging symbols // for the executable. // public virtual int GetFileLineNumber() { return iLineNumber; } // Returns the column number in the line containing the code being executed. // This information is normally extracted from the debugging symbols // for the executable. // public virtual int GetFileColumnNumber( ) { return iColumnNumber; } // Builds a readable representation of the stack frame // public override String ToString( ) { StringBuilder sb = new StringBuilder( 255 ); if(method != null) { sb.Append( method.Name ); // deal with the generic portion of the method if(method is MethodInfo && ( (MethodInfo)method ).IsGenericMethod) { Type[] typars = ((MethodInfo)method).GetGenericArguments(); sb.Append( "<" ); int k = 0; bool fFirstTyParam = true; while(k < typars.Length) { if(fFirstTyParam == false) { sb.Append( "," ); } else { fFirstTyParam = false; } sb.Append( typars[ k ].Name ); k++; } sb.Append( ">" ); } sb.Append( " at offset " ); if(offset == OFFSET_UNKNOWN) { sb.Append( "" ); } else { sb.Append( offset ); } sb.Append( " in file:line:column " ); bool useFileName = (strFileName != null); if(useFileName) { try { //////// This isn't really correct, but we don't have //////// a permission that protects discovery of potentially //////// local urls so we'll use this. //////FileIOPermission perm = new FileIOPermission( PermissionState.None ); //////perm.AllFiles = FileIOPermissionAccess.PathDiscovery; //////perm.Demand( ); } catch/*(System.Security.SecurityException)*/ { useFileName = false; } } if(!useFileName) { sb.Append( "" ); } else { sb.Append( strFileName ); } sb.Append( ":" ); sb.Append( iLineNumber ); sb.Append( ":" ); sb.Append( iColumnNumber ); } else { sb.Append( "" ); } sb.Append( Environment.NewLine ); return sb.ToString( ); } private void BuildStackFrame( int skipFrames, bool fNeedFileInfo ) { StackFrameHelper StackF = new StackFrameHelper( fNeedFileInfo, null ); StackTrace.GetStackFramesInternal( StackF, 0, null ); int iNumOfFrames = StackF.GetNumberOfFrames(); skipFrames += StackTrace.CalculateFramesToSkip( StackF, iNumOfFrames ); if(( iNumOfFrames - skipFrames ) > 0) { method = StackF.GetMethodBase( skipFrames ); offset = StackF.GetOffset( skipFrames ); ILOffset = StackF.GetILOffset( skipFrames ); if(fNeedFileInfo) { strFileName = StackF.GetFilename( skipFrames ); iLineNumber = StackF.GetLineNumber( skipFrames ); iColumnNumber = StackF.GetColumnNumber( skipFrames ); } } } } } ================================================ FILE: Zelig/Zelig/RunTime/Framework/mscorlib/System/Diagnostics/StackTrace.cs ================================================ // ==++== // // Copyright (c) Microsoft Corporation. All rights reserved. // // ==--== namespace System.Diagnostics { using System.Text; using System.Threading; using System; ////using System.Security; ////using System.Security.Permissions; ////using System.IO; using System.Reflection; using System.Runtime.InteropServices; using System.Runtime.CompilerServices; ////using System.Globalization; ////using System.Runtime.Serialization; ////using System.Runtime.Versioning; // READ ME: // Modifying the order or fields of this object may require other changes // to the unmanaged definition of the StackFrameHelper class, in // VM\DebugDebugger.h. The binder will catch some of these layout problems. [Serializable] internal class StackFrameHelper { [NonSerialized] private Thread targetThread; private int[] rgiOffset; private int[] rgiILOffset; // this field is here only for backwards compatibility of serialization format //////private MethodBase[] rgMethodBase; //// ////#pragma warning disable 414 // Field is not used from managed. //// // dynamicMethods is an array of System.Resolver objects, used to keep //// // DynamicMethodDescs alive for the lifetime of StackFrameHelper. //// private Object dynamicMethods; ////#pragma warning restore 414 //// //// [NonSerialized] private RuntimeMethodHandle[] rgMethodHandle; private String[] rgFilename; private int[] rgiLineNumber; private int[] rgiColumnNumber; private int iFrameCount; private bool fNeedFileInfo; public StackFrameHelper( bool fNeedFileLineColInfo, Thread target ) { targetThread = target; //////rgMethodBase = null; rgMethodHandle = null; rgiOffset = null; rgiILOffset = null; rgFilename = null; rgiLineNumber = null; rgiColumnNumber = null; //////dynamicMethods = null; // 0 means capture all frames. For StackTraces from an Exception, the EE always // captures all frames. For other uses of StackTraces, we can abort stack walking after // some limit if we want to by setting this to a non-zero value. In Whidbey this was // hard-coded to 512, but some customers complained. There shouldn't be any need to limit // this as memory/CPU is no longer allocated up front. If there is some reason to provide a // limit in the future, then we should expose it in the managed API so applications can // override it. iFrameCount = 0; fNeedFileInfo = fNeedFileLineColInfo; } public virtual MethodBase GetMethodBase( int i ) { // There may be a better way to do this. // we got RuntimeMethodHandles here and we need to go to MethodBase // but we don't know whether the reflection info has been initialized // or not. So we call GetMethods and GetConstructors on the type // and then we fetch the proper MethodBase!! RuntimeMethodHandle mh = rgMethodHandle[i]; if(mh.IsNullHandle( )) return null; //////mh = mh.GetTypicalMethodDefinition( ); //////return RuntimeType.GetMethodBase( mh ); return null; ; } public virtual int GetOffset( int i ) { return rgiOffset[ i ]; } public virtual int GetILOffset( int i ) { return rgiILOffset[ i ]; } public virtual String GetFilename( int i ) { return rgFilename[ i ]; } public virtual int GetLineNumber( int i ) { return rgiLineNumber[ i ]; } public virtual int GetColumnNumber( int i ) { return rgiColumnNumber[ i ]; } public virtual int GetNumberOfFrames( ) { return iFrameCount; } public virtual void SetNumberOfFrames( int i ) { iFrameCount = i; } //// // //// // serialization implementation //// // //// [OnSerializing] //// void OnSerializing( StreamingContext context ) //// { //// // this is called in the process of serializing this object. //// // For compatibility with Everett we need to assign the rgMethodBase field as that is the field //// // that will be serialized //// rgMethodBase = (rgMethodHandle == null) ? null : new MethodBase[rgMethodHandle.Length]; //// if(rgMethodHandle != null) //// { //// for(int i = 0; i < rgMethodHandle.Length; i++) //// { //// if(!rgMethodHandle[i].IsNullHandle()) //// rgMethodBase[i] = RuntimeType.GetMethodBase( rgMethodHandle[i] ); //// } //// } //// } //// //// [OnSerialized] //// void OnSerialized( StreamingContext context ) //// { //// // after we are done serializing null the rgMethodBase field //// rgMethodBase = null; //// } //// //// [OnDeserialized] //// void OnDeserialized( StreamingContext context ) //// { //// // after we are done deserializing we need to transform the rgMethodBase in rgMethodHandle //// rgMethodHandle = (rgMethodBase == null) ? null : new RuntimeMethodHandle[rgMethodBase.Length]; //// if(rgMethodBase != null) //// { //// for(int i = 0; i < rgMethodBase.Length; i++) //// { //// if(rgMethodBase[i] != null) //// rgMethodHandle[i] = rgMethodBase[i].MethodHandle; //// } //// } //// rgMethodBase = null; //// } } // Class which represents a description of a stack trace // There is no good reason for the methods of this class to be virtual. // In order to ensure trusted code can trust the data it gets from a // StackTrace, we use an InheritanceDemand to prevent partially-trusted // subclasses. ////[SecurityPermission( SecurityAction.InheritanceDemand, UnmanagedCode = true )] [Serializable] public class StackTrace { public const int METHODS_TO_SKIP = 0; private StackFrame[] frames; private int m_iNumOfFrames; private int m_iMethodsToSkip; // Constructs a stack trace from the current location. public StackTrace( ) { m_iNumOfFrames = 0; m_iMethodsToSkip = 0; CaptureStackTrace( METHODS_TO_SKIP, false, null, null ); } // Constructs a stack trace from the current location. // public StackTrace( bool fNeedFileInfo ) { m_iNumOfFrames = 0; m_iMethodsToSkip = 0; CaptureStackTrace( METHODS_TO_SKIP, fNeedFileInfo, null, null ); } // Constructs a stack trace from the current location, in a caller's // frame // public StackTrace( int skipFrames ) { if(skipFrames < 0) { throw new ArgumentOutOfRangeException( "skipFrames", Environment.GetResourceString( "ArgumentOutOfRange_NeedNonNegNum" ) ); } m_iNumOfFrames = 0; m_iMethodsToSkip = 0; CaptureStackTrace( skipFrames + METHODS_TO_SKIP, false, null, null ); } // Constructs a stack trace from the current location, in a caller's // frame // public StackTrace( int skipFrames, bool fNeedFileInfo ) { if(skipFrames < 0) { throw new ArgumentOutOfRangeException( "skipFrames", Environment.GetResourceString( "ArgumentOutOfRange_NeedNonNegNum" ) ); } m_iNumOfFrames = 0; m_iMethodsToSkip = 0; CaptureStackTrace( skipFrames + METHODS_TO_SKIP, fNeedFileInfo, null, null ); } // Constructs a stack trace from the current location. public StackTrace( Exception e ) { if(e == null) { throw new ArgumentNullException( "e" ); } m_iNumOfFrames = 0; m_iMethodsToSkip = 0; CaptureStackTrace( METHODS_TO_SKIP, false, null, e ); } // Constructs a stack trace from the current location. // public StackTrace( Exception e, bool fNeedFileInfo ) { if(e == null) { throw new ArgumentNullException( "e" ); } m_iNumOfFrames = 0; m_iMethodsToSkip = 0; CaptureStackTrace( METHODS_TO_SKIP, fNeedFileInfo, null, e ); } // Constructs a stack trace from the current location, in a caller's // frame // public StackTrace( Exception e, int skipFrames ) { if(e == null) { throw new ArgumentNullException( "e" ); } if(skipFrames < 0) { throw new ArgumentOutOfRangeException( "skipFrames", Environment.GetResourceString( "ArgumentOutOfRange_NeedNonNegNum" ) ); } m_iNumOfFrames = 0; m_iMethodsToSkip = 0; CaptureStackTrace( skipFrames + METHODS_TO_SKIP, false, null, e ); } // Constructs a stack trace from the current location, in a caller's // frame // public StackTrace( Exception e, int skipFrames, bool fNeedFileInfo ) { if(e == null) { throw new ArgumentNullException( "e" ); } if(skipFrames < 0) { throw new ArgumentOutOfRangeException( "skipFrames", Environment.GetResourceString( "ArgumentOutOfRange_NeedNonNegNum" ) ); } m_iNumOfFrames = 0; m_iMethodsToSkip = 0; CaptureStackTrace( skipFrames + METHODS_TO_SKIP, fNeedFileInfo, null, e ); } // Constructs a "fake" stack trace, just containing a single frame. // Does not have the overhead of a full stack trace. // public StackTrace( StackFrame frame ) { frames = new StackFrame[ 1 ]; frames[ 0 ] = frame; m_iMethodsToSkip = 0; m_iNumOfFrames = 1; } // Constructs a stack trace for the given thread // public StackTrace( Thread targetThread, bool needFileInfo ) { m_iNumOfFrames = 0; m_iMethodsToSkip = 0; CaptureStackTrace( METHODS_TO_SKIP, needFileInfo, targetThread, null ); } //////[ResourceExposure( ResourceScope.None )] [MethodImplAttribute( MethodImplOptions.InternalCall )] internal static extern void GetStackFramesInternal( StackFrameHelper sfh, int iSkip, Exception e ); internal static int CalculateFramesToSkip( StackFrameHelper StackF, int iNumFrames ) { int iRetVal = 0; String PackageName = "System.Diagnostics"; // Check if this method is part of the System.Diagnostics // package. If so, increment counter keeping track of // System.Diagnostics functions for(int i = 0; i < iNumFrames; i++) { MethodBase mb = StackF.GetMethodBase( i ); if(mb != null) { Type t = mb.DeclaringType; if(t == null) break; String ns = t.Namespace; if(ns == null) break; if(String.Compare( ns, PackageName, StringComparison.Ordinal ) != 0) break; } iRetVal++; } return iRetVal; } // Retrieves an object with stack trace information encoded. // It leaves out the first "iSkip" lines of the stacktrace. // private void CaptureStackTrace( int iSkip, bool fNeedFileInfo, Thread targetThread, Exception e ) { m_iMethodsToSkip += iSkip; StackFrameHelper StackF = new StackFrameHelper( fNeedFileInfo, targetThread ); GetStackFramesInternal( StackF, 0, e ); m_iNumOfFrames = StackF.GetNumberOfFrames( ); if(m_iMethodsToSkip > m_iNumOfFrames) m_iMethodsToSkip = m_iNumOfFrames; if(m_iNumOfFrames != 0) { frames = new StackFrame[ m_iNumOfFrames ]; for(int i = 0; i < m_iNumOfFrames; i++) { bool fDummy1 = true; bool fDummy2 = true; StackFrame sfTemp = new StackFrame( fDummy1, fDummy2 ); sfTemp.SetMethodBase( StackF.GetMethodBase( i ) ); sfTemp.SetOffset( StackF.GetOffset( i ) ); sfTemp.SetILOffset( StackF.GetILOffset( i ) ); if(fNeedFileInfo) { sfTemp.SetFileName( StackF.GetFilename( i ) ); sfTemp.SetLineNumber( StackF.GetLineNumber( i ) ); sfTemp.SetColumnNumber( StackF.GetColumnNumber( i ) ); } frames[ i ] = sfTemp; } // CalculateFramesToSkip skips all frames in the System.Diagnostics namespace, // but this is not desired if building a stack trace from an exception. if(e == null) m_iMethodsToSkip += CalculateFramesToSkip( StackF, m_iNumOfFrames ); m_iNumOfFrames -= m_iMethodsToSkip; if(m_iNumOfFrames < 0) { m_iNumOfFrames = 0; } } // In case this is the same object being re-used, set frames to null else frames = null; } // Property to get the number of frames in the stack trace // public virtual int FrameCount { get { return m_iNumOfFrames; } } // Returns a given stack frame. Stack frames are numbered starting at // zero, which is the last stack frame pushed. // public virtual StackFrame GetFrame( int index ) { throw new NotImplementedException(); //// if((frames != null) && (index < m_iNumOfFrames) && (index >= 0)) //// { //// return frames[index + m_iMethodsToSkip]; //// } //// //// return null; } // Returns an array of all stack frames for this stacktrace. // The array is ordered and sized such that GetFrames()[i] == GetFrame(i) // The nth element of this array is the same as GetFrame(n). // The length of the array is the same as FrameCount. // public virtual StackFrame[ ] GetFrames( ) { if(frames == null || m_iNumOfFrames <= 0) { return null; } // We have to return a subset of the array. Unfortunately this // means we have to allocate a new array and copy over. StackFrame[] array = new StackFrame[m_iNumOfFrames]; Array.Copy( frames, m_iMethodsToSkip, array, 0, m_iNumOfFrames ); return array; } // Builds a readable representation of the stack trace // public override String ToString( ) { // Include a trailing newline for backwards compatibility return ToString( TraceFormat.TrailingNewLine ); } // TraceFormat is Used to specify options for how the // string-representation of a StackTrace should be generated. internal enum TraceFormat { Normal, TrailingNewLine, // include a trailing new line character NoResourceLookup // to prevent infinite resource recusion } // Builds a readable representation of the stack trace, specifying // the format for backwards compatibility. internal String ToString( TraceFormat traceFormat ) { String word_At = "at"; String inFileLineNum = "in {0}:line {1}"; if(traceFormat != TraceFormat.NoResourceLookup) { word_At = Environment.GetResourceString( "Word_At" ); inFileLineNum = Environment.GetResourceString( "StackTrace_InFileLineNumber" ); } bool fFirstFrame = true; StringBuilder sb = new StringBuilder( 255 ); for(int iFrameIndex = 0; iFrameIndex < m_iNumOfFrames; iFrameIndex++) { StackFrame sf = GetFrame( iFrameIndex ); MethodBase mb = sf.GetMethod(); if(mb != null) { // We want a newline at the end of every line except for the last if(fFirstFrame) fFirstFrame = false; else sb.Append( Environment.NewLine ); sb.AppendFormat( /*CultureInfo.InvariantCulture,*/ " {0} ", word_At ); Type t = mb.DeclaringType; // if there is a type (non global method) print it if(t != null) { sb.Append( t.FullName.Replace( '+', '.' ) ); sb.Append( "." ); } sb.Append( mb.Name ); // deal with the generic portion of the method if(mb is MethodInfo && ( (MethodInfo)mb ).IsGenericMethod) { Type[] typars = ((MethodInfo)mb).GetGenericArguments(); sb.Append( "[" ); int k = 0; bool fFirstTyParam = true; while(k < typars.Length) { if(fFirstTyParam == false) sb.Append( "," ); else fFirstTyParam = false; sb.Append( typars[ k ].Name ); k++; } sb.Append( "]" ); } // arguments printing sb.Append( "(" ); ParameterInfo[] pi = mb.GetParameters(); bool fFirstParam = true; for(int j = 0; j < pi.Length; j++) { if(fFirstParam == false) sb.Append( ", " ); else fFirstParam = false; String typeName = ""; if(pi[ j ].ParameterType != null) typeName = pi[ j ].ParameterType.Name; sb.Append( typeName + " " + pi[ j ].Name ); } sb.Append( ")" ); // source location printing if(sf.GetILOffset( ) != -1) { // It's possible we have a debug version of an executable but no PDB. In // this case, the file name will be null. String fileName = null; try { fileName = sf.GetFileName( ); } catch/*(SecurityException)*/ { } if(fileName != null) { // tack on " in c:\tmp\MyFile.cs:line 5" sb.Append( ' ' ); sb.AppendFormat( /*CultureInfo.InvariantCulture,*/ inFileLineNum, fileName, sf.GetFileLineNumber( ) ); } } } } if(traceFormat == TraceFormat.TrailingNewLine) { sb.Append( Environment.NewLine ); } return sb.ToString( ); } // This helper is called from within the EE to construct a string representation // of the current stack trace. private static String GetManagedStackTraceStringHelper( bool fNeedFileInfo ) { // Note all the frames in System.Diagnostics will be skipped when capturing // a normal stack trace (not from an exception) so we don't need to explicitly // skip the GetManagedStackTraceStringHelper frame. StackTrace st = new StackTrace( 0, fNeedFileInfo ); return st.ToString( ); } } } ================================================ FILE: Zelig/Zelig/RunTime/Framework/mscorlib/System/DivideByZeroException.cs ================================================ // ==++== // // Copyright (c) Microsoft Corporation. All rights reserved. // // ==--== /*============================================================================= ** ** Class: DivideByZeroException ** ** ** Purpose: Exception class for bad arithmetic conditions! ** ** =============================================================================*/ namespace System { using System; using System.Runtime.Serialization; [Serializable] public class DivideByZeroException : ArithmeticException { #if EXCEPTION_STRINGS public DivideByZeroException() : base( Environment.GetResourceString( "Arg_DivideByZero" ) ) #else public DivideByZeroException() #endif { } public DivideByZeroException( String message ) : base( message ) { } public DivideByZeroException( String message, Exception innerException ) : base( message, innerException ) { } //// protected DivideByZeroException( SerializationInfo info, StreamingContext context ) : base( info, context ) //// { //// } } } ================================================ FILE: Zelig/Zelig/RunTime/Framework/mscorlib/System/Double.cs ================================================ // ==++== // // Copyright (c) Microsoft Corporation. All rights reserved. // // ==--== /*============================================================ ** ** Class: Double ** ** ** Purpose: A representation of an IEEE double precision ** floating point number. ** ** ===========================================================*/ namespace System { using System; using System.Globalization; using System.Runtime.InteropServices; using System.Runtime.CompilerServices; using System.Runtime.ConstrainedExecution; [Microsoft.Zelig.Internals.WellKnownType( "System_Double" )] [Serializable] [StructLayout( LayoutKind.Sequential )] public struct Double : IComparable, IFormattable, IConvertible, IComparable, IEquatable { // // Public Constants // public const double MinValue = -1.7976931348623157E+308; public const double Epsilon = 4.9406564584124654E-324;// Note Epsilon should be a double whose hex representation is 0x1 on little endian machines. public const double MaxValue = 1.7976931348623157E+308; public const double NegativeInfinity = (double)-1.0 / (double)0.0; public const double PositiveInfinity = (double) 1.0 / (double)0.0; public const double NaN = (double) 0.0 / (double)0.0; //// internal static double NegativeZero = BitConverter.Int64BitsToDouble( unchecked( (long)0x8000000000000000 ) ); internal double m_value; public unsafe static bool IsInfinity( double d ) { return (*(long*)(&d) & 0x7FFFFFFFFFFFFFFF) == 0x7FF0000000000000; } public static bool IsPositiveInfinity( double d ) { //Jit will generate inlineable code with this if(d == double.PositiveInfinity) { return true; } else { return false; } } public static bool IsNegativeInfinity( double d ) { //Jit will generate inlineable code with this if(d == double.NegativeInfinity) { return true; } else { return false; } } internal unsafe static bool IsNegative( double d ) { return (*(UInt64*)(&d) & 0x8000000000000000) == 0x8000000000000000; } //// [ReliabilityContract( Consistency.WillNotCorruptState, Cer.Success )] public static bool IsNaN( double d ) { //Jit will generate inlineable code with this // warning CS1718: comparison to same variable #pragma warning disable 1718 if(d != d) { return true; } else { return false; } #pragma warning restore 1718 } // Compares this object to another object, returning an instance of System.Relation. // Null is considered less than any instance. // // If object is not of type Double, this method throws an ArgumentException. // // Returns a value less than zero if this object // public int CompareTo( Object value ) { if(value == null) { return 1; } if(value is Double) { return CompareTo( (Double)value ); } #if EXCEPTION_STRINGS throw new ArgumentException( Environment.GetResourceString( "Arg_MustBeDouble" ) ); #else throw new ArgumentException(); #endif } public int CompareTo( Double value ) { if(m_value < value) return -1; if(m_value > value) return 1; if(m_value == value) return 0; // At least one of the values is NaN. if(IsNaN( m_value )) { return (IsNaN( value ) ? 0 : -1); } else { return 1; } } // True if obj is another Double with the same value as the current instance. This is // a method of object equality, that only returns true if obj is also a double. public override bool Equals( Object obj ) { if(!(obj is Double)) { return false; } return Equals( (Double)obj ); } public bool Equals( Double obj ) { if(obj == m_value) { return true; } return IsNaN( obj ) && IsNaN( m_value ); } //The hashcode for a double is the absolute value of the integer representation //of that double. // public unsafe override int GetHashCode() { double d = m_value; if(d == 0) { // Ensure that 0 and -0 have the same hash code return 0; } long value = *(long*)(&d); return unchecked( (int)value ) ^ ((int)(value >> 32)); } public override String ToString() { return Number.FormatDouble( m_value, /*null,*/ NumberFormatInfo.CurrentInfo ); } public String ToString( String format ) { return Number.FormatDouble( m_value, format, NumberFormatInfo.CurrentInfo ); } public String ToString( IFormatProvider provider ) { return Number.FormatDouble( m_value, /*null,*/ NumberFormatInfo.GetInstance( provider ) ); } public String ToString( String format, IFormatProvider provider ) { return Number.FormatDouble( m_value, format, NumberFormatInfo.GetInstance( provider ) ); } public static double Parse( String s ) { return Parse( s, NumberStyles.Float | NumberStyles.AllowThousands, NumberFormatInfo.CurrentInfo ); } public static double Parse( String s, NumberStyles style ) { NumberFormatInfo.ValidateParseStyleFloatingPoint( style ); return Parse( s, style, NumberFormatInfo.CurrentInfo ); } public static double Parse( String s, IFormatProvider provider ) { return Parse( s, NumberStyles.Float | NumberStyles.AllowThousands, NumberFormatInfo.GetInstance( provider ) ); } public static double Parse( String s, NumberStyles style, IFormatProvider provider ) { NumberFormatInfo.ValidateParseStyleFloatingPoint( style ); return Parse( s, style, NumberFormatInfo.GetInstance( provider ) ); } // Parses a double from a String in the given style. If // a NumberFormatInfo isn't specified, the current culture's // NumberFormatInfo is assumed. // // This method will not throw an OverflowException, but will return // PositiveInfinity or NegativeInfinity for a number that is too // large or too small. // private static double Parse( String s, NumberStyles style, NumberFormatInfo info ) { try { return Number.ParseDouble( s, style, info ); } catch(FormatException) { //If we caught a FormatException, it may be from one of our special strings. //Check the three with which we're concerned and rethrow if it's not one of //those strings. String sTrim = s.Trim(); if(sTrim.Equals( info.PositiveInfinitySymbol )) { return PositiveInfinity; } if(sTrim.Equals( info.NegativeInfinitySymbol )) { return NegativeInfinity; } if(sTrim.Equals( info.NaNSymbol )) { return NaN; } //Rethrow the previous exception; throw; } } public static bool TryParse( String s, out double result ) { return TryParse( s, NumberStyles.Float | NumberStyles.AllowThousands, NumberFormatInfo.CurrentInfo, out result ); } public static bool TryParse( String s, NumberStyles style, IFormatProvider provider, out double result ) { NumberFormatInfo.ValidateParseStyleFloatingPoint( style ); return TryParse( s, style, NumberFormatInfo.GetInstance( provider ), out result ); } private static bool TryParse( String s, NumberStyles style, NumberFormatInfo info, out double result ) { if(s == null) { result = 0; return false; } bool success = Number.TryParseDouble( s, style, info, out result ); if(!success) { String sTrim = s.Trim(); if(sTrim.Equals( info.PositiveInfinitySymbol )) { result = PositiveInfinity; } else if(sTrim.Equals( info.NegativeInfinitySymbol )) { result = NegativeInfinity; } else if(sTrim.Equals( info.NaNSymbol )) { result = NaN; } else { return false; // We really failed } } return true; } #region IConvertible public TypeCode GetTypeCode() { return TypeCode.Double; } /// bool IConvertible.ToBoolean( IFormatProvider provider ) { return Convert.ToBoolean( m_value ); } /// char IConvertible.ToChar( IFormatProvider provider ) { #if EXCEPTION_STRINGS throw new InvalidCastException( String.Format( CultureInfo.CurrentCulture, Environment.GetResourceString( "InvalidCast_FromTo" ), "Double", "Char" ) ); #else throw new InvalidCastException(); #endif } /// sbyte IConvertible.ToSByte( IFormatProvider provider ) { return Convert.ToSByte( m_value ); } /// byte IConvertible.ToByte( IFormatProvider provider ) { return Convert.ToByte( m_value ); } /// short IConvertible.ToInt16( IFormatProvider provider ) { return Convert.ToInt16( m_value ); } /// ushort IConvertible.ToUInt16( IFormatProvider provider ) { return Convert.ToUInt16( m_value ); } /// int IConvertible.ToInt32( IFormatProvider provider ) { return Convert.ToInt32( m_value ); } /// uint IConvertible.ToUInt32( IFormatProvider provider ) { return Convert.ToUInt32( m_value ); } /// long IConvertible.ToInt64( IFormatProvider provider ) { return Convert.ToInt64( m_value ); } /// ulong IConvertible.ToUInt64( IFormatProvider provider ) { return Convert.ToUInt64( m_value ); } /// float IConvertible.ToSingle( IFormatProvider provider ) { return Convert.ToSingle( m_value ); } /// double IConvertible.ToDouble( IFormatProvider provider ) { return m_value; } /// Decimal IConvertible.ToDecimal( IFormatProvider provider ) { return Convert.ToDecimal( m_value ); } /// DateTime IConvertible.ToDateTime( IFormatProvider provider ) { #if EXCEPTION_STRINGS throw new InvalidCastException( String.Format( CultureInfo.CurrentCulture, Environment.GetResourceString( "InvalidCast_FromTo" ), "Double", "DateTime" ) ); #else throw new InvalidCastException(); #endif } /// Object IConvertible.ToType( Type type, IFormatProvider provider ) { return Convert.DefaultToType( (IConvertible)this, type, provider ); } #endregion } } ================================================ FILE: Zelig/Zelig/RunTime/Framework/mscorlib/System/Empty.cs ================================================ // ==++== // // Copyright (c) Microsoft Corporation. All rights reserved. // // ==--== //////////////////////////////////////////////////////////////////////////////// // Empty // This class represents an empty variant //////////////////////////////////////////////////////////////////////////////// namespace System { using System; ////using System.Runtime.Remoting; using System.Runtime.Serialization; [Serializable] internal sealed class Empty /*: ISerializable*/ { public static readonly Empty Value = new Empty(); private Empty() { } //// public override String ToString() //// { //// return String.Empty; //// } //// //// public void GetObjectData( SerializationInfo info, StreamingContext context ) //// { //// if(info == null) //// { //// throw new ArgumentNullException( "info" ); //// } //// UnitySerializationHolder.GetUnitySerializationInfo( info, UnitySerializationHolder.EmptyUnity, null, null ); //// } } } ================================================ FILE: Zelig/Zelig/RunTime/Framework/mscorlib/System/Enum.cs ================================================ // ==++== // // Copyright (c) Microsoft Corporation. All rights reserved. // // ==--== namespace System { using System; using System.Reflection; ////using System.Reflection.Emit; ////using System.Text; using System.Collections; using System.Globalization; using System.Runtime.CompilerServices; ////using System.Runtime.Versioning; [Microsoft.Zelig.Internals.WellKnownType( "System_Enum" )] [Serializable] public abstract class Enum : ValueType, IComparable, IFormattable, IConvertible { #region Private Static Data Members //// private const int maxHashElements = 100; // to trim the working set //// private const String enumSeperator = ", "; //// private static char[] enumSeperatorCharArray = new char[] { ',' }; //// private static Type intType = typeof( int ); //// private static Type stringType = typeof( String ); //// private static Hashtable fieldInfoHash = Hashtable.Synchronized( new Hashtable() ); #endregion #region Private Static Methods //// private static void ValidateEnumType( Type enumType) //// { //// if(enumType == null) //// { //// throw new ArgumentNullException( "enumType" ); //// } //// //// if(!(enumType is RuntimeType)) //// { //// throw new ArgumentException( Environment.GetResourceString( "Arg_MustBeType" ), "enumType" ); //// } //// //// if(!enumType.IsEnum) //// { //// throw new ArgumentException( Environment.GetResourceString( "Arg_MustBeEnum" ), "enumType" ); //// } //// } //// private static FieldInfo GetValueField( Type type ) //// { //// FieldInfo[] flds; //// //// flds = type.GetFields( BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic ); //// //// if((flds == null) || (flds.Length != 1)) //// { //// throw new ArgumentException( Environment.GetResourceString( "Arg_EnumMustHaveUnderlyingValueField" ) ); //// } //// //// return flds[0]; //// } //// //// private static HashEntry GetHashEntry( Type enumType ) //// { //// HashEntry hashEntry = (HashEntry)fieldInfoHash[enumType]; //// //// if(hashEntry == null) //// { //// // To reduce the workingset we clear the hashtable when a threshold number of elements are inserted. //// if(fieldInfoHash.Count > maxHashElements) //// { //// fieldInfoHash.Clear(); //// } //// //// ulong[] values = null; //// String[] names = null; //// //// BCLDebug.Assert( enumType.BaseType == typeof( Enum ), "Base type must of type Enum" ); //// if(enumType.BaseType == typeof( Enum )) //// { //// InternalGetEnumValues( enumType, ref values, ref names ); //// } //// // If we switch over to EnumBuilder, this code path will be required. //// else //// { //// // fall back on reflection for odd cases //// FieldInfo[] flds = enumType.GetFields( BindingFlags.Static | BindingFlags.Public ); //// //// values = new ulong[flds.Length]; //// names = new String[flds.Length]; //// for(int i = 0; i < flds.Length; i++) //// { //// names[i] = flds[i].Name; //// values[i] = ToUInt64( flds[i].GetValue( null ) ); //// } //// //// // Insertion Sort these values in ascending order. //// // We use this O(n^2) algorithm, but it turns out that most of the time the elements are already in sorted order and //// // the common case performance will be faster than quick sorting this. //// for(int i = 1; i < values.Length; i++) //// { //// int j = i; //// String tempStr = names[i]; //// ulong val = values[i]; //// bool exchanged = false; //// //// // Since the elements are sorted we only need to do one comparision, we keep the check for j inside the loop. //// while(values[j - 1] > val) //// { //// names [j] = names [j - 1]; //// values[j] = values[j - 1]; //// //// j--; //// //// exchanged = true; //// if(j == 0) //// { //// break; //// } //// } //// //// if(exchanged) //// { //// names [j] = tempStr; //// values[j] = val; //// } //// } //// } //// //// hashEntry = new HashEntry( names, values ); //// //// fieldInfoHash[enumType] = hashEntry; //// } //// //// return hashEntry; //// } //// //// private static String InternalGetValueAsString( Type enumType, Object value ) //// { //// //Don't ask for the private fields. Only .value is private and we don't need that. //// HashEntry hashEntry = GetHashEntry ( enumType ); //// Type eT = GetUnderlyingType( enumType ); //// //// // Lets break this up based upon the size. We'll do part as an 64bit value //// // and part as the 32bit values. //// if(eT == intType || eT == typeof( short ) || eT == typeof( long ) || eT == typeof( ushort ) || eT == typeof( byte ) || eT == typeof( sbyte ) || eT == typeof( uint ) || eT == typeof( ulong )) //// { //// ulong val = ToUInt64( value ); //// int index = BinarySearch( hashEntry.values, val ); //// //// if(index >= 0) //// { //// return hashEntry.names[index]; //// } //// } //// //// return null; //// } //// //// private static String InternalFormattedHexString( Object value ) //// { //// TypeCode typeCode = Convert.GetTypeCode( value ); //// //// switch(typeCode) //// { //// case TypeCode.SByte: //// { //// Byte result = (byte)(sbyte)value; //// //// return result.ToString( "X2", null ); //// } //// //// case TypeCode.Byte: //// { //// Byte result = (byte)value; //// //// return result.ToString( "X2", null ); //// } //// //// case TypeCode.Int16: //// { //// UInt16 result = (UInt16)(Int16)value; //// //// return result.ToString( "X4", null ); //// } //// //// case TypeCode.UInt16: //// { //// UInt16 result = (UInt16)value; //// //// return result.ToString( "X4", null ); //// } //// //// case TypeCode.UInt32: //// { //// UInt32 result = (UInt32)value; //// //// return result.ToString( "X8", null ); //// } //// //// case TypeCode.Int32: //// { //// UInt32 result = (UInt32)(int)value; //// //// return result.ToString( "X8", null ); //// } //// //// case TypeCode.UInt64: //// { //// UInt64 result = (UInt64)value; //// //// return result.ToString( "X16", null ); //// } //// //// case TypeCode.Int64: //// { //// UInt64 result = (UInt64)(Int64)value; //// //// return result.ToString( "X16", null ); //// } //// //// // All unsigned types will be directly cast //// default: //// BCLDebug.Assert( false, "Invalid Object type in Format" ); //// throw new InvalidOperationException( Environment.GetResourceString( "InvalidOperation_UnknownEnumType" ) ); //// } //// } //// //// private static String InternalFormat( Type eT, Object value ) //// { //// if(!eT.IsDefined( typeof( System.FlagsAttribute ), false )) // Not marked with Flags attribute //// { //// // Try to see if its one of the enum values, then we return a String back else the value //// String retval = InternalGetValueAsString( eT, value ); //// if(retval == null) //// { //// return value.ToString(); //// } //// else //// { //// return retval; //// } //// } //// else // These are flags OR'ed together (We treat everything as unsigned types) //// { //// return InternalFlagsFormat( eT, value ); //// } //// } //// //// private static String InternalFlagsFormat( Type eT, Object value ) //// { //// ulong result = ToUInt64( value ); //// HashEntry hashEntry = GetHashEntry( eT ); //// //// // These values are sorted by value. Don't change this //// String[] names = hashEntry.names; //// ulong[] values = hashEntry.values; //// //// int index = values.Length - 1; //// StringBuilder retval = new StringBuilder(); //// bool firstTime = true; //// ulong saveResult = result; //// //// // We will not optimize this code further to keep it maintainable. There are some boundary checks that can be applied //// // to minimize the comparsions required. This code works the same for the best/worst case. In general the number of //// // items in an enum are sufficiently small and not worth the optimization. //// while(index >= 0) //// { //// if((index == 0) && (values[index] == 0)) //// { //// break; //// } //// //// if((result & values[index]) == values[index]) //// { //// result -= values[index]; //// //// if(!firstTime) //// { //// retval.Insert( 0, enumSeperator ); //// } //// //// retval.Insert( 0, names[index] ); //// firstTime = false; //// } //// //// index--; //// } //// //// // We were unable to represent this number as a bitwise or of valid flags //// if(result != 0) //// { //// return value.ToString(); //// } //// //// // For the case when we have zero //// if(saveResult == 0) //// { //// if(values[0] == 0) //// { //// return names[0]; // Zero was one of the enum values. //// } //// else //// { //// return "0"; //// } //// } //// else //// { //// return retval.ToString(); // Return the string representation //// } //// } //// //// private static ulong ToUInt64( Object value ) //// { //// // Helper function to silently convert the value to UInt64 from the other base types for enum without throwing an exception. //// // This is need since the Convert functions do overflow checks. //// TypeCode typeCode = Convert.GetTypeCode( value ); //// ulong result; //// //// switch(typeCode) //// { //// case TypeCode.SByte: //// case TypeCode.Int16: //// case TypeCode.Int32: //// case TypeCode.Int64: //// result = (UInt64)Convert.ToInt64( value, CultureInfo.InvariantCulture ); //// break; //// //// case TypeCode.Byte: //// case TypeCode.UInt16: //// case TypeCode.UInt32: //// case TypeCode.UInt64: //// result = Convert.ToUInt64( value, CultureInfo.InvariantCulture ); //// break; //// //// default: //// // All unsigned types will be directly cast //// BCLDebug.Assert( false, "Invalid Object type in ToUInt64" ); //// throw new InvalidOperationException( Environment.GetResourceString( "InvalidOperation_UnknownEnumType" ) ); //// } //// return result; //// } //// //// private static int BinarySearch( ulong[] array, ulong value ) //// { //// int lo = 0; //// int hi = array.Length - 1; //// //// while(lo <= hi) //// { //// int i = (lo + hi) >> 1; //// ulong temp = array[i]; //// //// if(value == temp) return i; //// //// if(temp < value) //// { //// lo = i + 1; //// } //// else //// { //// hi = i - 1; //// } //// } //// //// return ~lo; //// } //// [ResourceExposure( ResourceScope.None )] [MethodImpl( MethodImplOptions.InternalCall )] private static extern int InternalCompareTo( Object o1, Object o2 ); //// [ResourceExposure( ResourceScope.None )] //// [MethodImpl( MethodImplOptions.InternalCall )] //// private static extern Type InternalGetUnderlyingType( Type enumType ); //// //// [ResourceExposure( ResourceScope.None )] //// [MethodImpl( MethodImplOptions.InternalCall )] //// private static extern void InternalGetEnumValues( Type enumType, ref ulong[] values, ref String[] names ); #endregion #region Public Static Methods public static Object Parse( Type enumType, String value ) { return Parse( enumType, value, false ); } [MethodImpl( MethodImplOptions.InternalCall )] public static extern Object Parse( Type enumType, String value, bool ignoreCase ); //// { //// ValidateEnumType( enumType ); //// //// if(value == null) //// { //// throw new ArgumentNullException( "value" ); //// } //// //// value = value.Trim(); //// if(value.Length == 0) //// { //// throw new ArgumentException( Environment.GetResourceString( "Arg_MustContainEnumInfo" ) ); //// } //// //// // We have 2 code paths here. One if they are values else if they are Strings. //// // values will have the first character as as number or a sign. //// ulong result = 0; //// //// if(Char.IsDigit( value[0] ) || value[0] == '-' || value[0] == '+') //// { //// Type underlyingType = GetUnderlyingType( enumType ); //// Object temp; //// //// try //// { //// temp = Convert.ChangeType( value, underlyingType, CultureInfo.InvariantCulture ); //// //// return ToObject( enumType, temp ); //// } //// catch(FormatException) //// { // We need to Parse this a String instead. There are cases //// // when you tlbimp enums that can have values of the form "3D". //// // Don't fix this code. //// } //// } //// //// String[] values = value.Split( enumSeperatorCharArray ); //// //// // Find the field.Lets assume that these are always static classes because the class is //// // an enum. //// HashEntry hashEntry = GetHashEntry( enumType ); //// String[] names = hashEntry.names; //// //// for(int i = 0; i < values.Length; i++) //// { //// values[i] = values[i].Trim(); // We need to remove whitespace characters //// //// bool success = false; //// //// for(int j = 0; j < names.Length; j++) //// { //// if(ignoreCase) //// { //// if(String.Compare( names[j], values[i], StringComparison.OrdinalIgnoreCase ) != 0) //// { //// continue; //// } //// } //// else //// { //// if(!names[j].Equals( values[i] )) //// { //// continue; //// } //// } //// //// ulong item = hashEntry.values[j]; //// //// result |= item; //// success = true; //// break; //// } //// //// if(!success) //// { //// // Not found, throw an argument exception. //// throw new ArgumentException( String.Format( CultureInfo.CurrentCulture, Environment.GetResourceString( "Arg_EnumValueNotFound" ), value ) ); //// } //// } //// //// return ToObject( enumType, result ); //// } public static Type GetUnderlyingType( Type enumType ) { throw new NotImplementedException(); //// ////// Make this function working for EnumBuilder. JScript uses it. //// ////if(enumType is EnumBuilder) //// ////{ //// //// return ((EnumBuilder)enumType).UnderlyingSystemType; //// ////} //// //// ValidateEnumType( enumType ); //// //// return InternalGetUnderlyingType( enumType ); } public static Array GetValues( Type enumType ) { throw new NotImplementedException(); //// ValidateEnumType( enumType ); //// //// // Get all of the values //// ulong[] values = GetHashEntry( enumType ).values; //// //// // Create a generic Array //// Array ret = Array.CreateInstance( enumType, values.Length ); //// //// for(int i = 0; i < values.Length; i++) //// { //// Object val = ToObject( enumType, values[i] ); //// //// ret.SetValue( val, i ); //// } //// //// return ret; } //// public static String GetName( Type enumType, Object value ) //// { //// ValidateEnumType( enumType ); //// //// if(value == null) //// { //// throw new ArgumentNullException( "value" ); //// } //// //// Type valueType = value.GetType(); //// //// if(valueType.IsEnum || valueType == intType || valueType == typeof( short ) || valueType == typeof( ushort ) || valueType == typeof( byte ) || valueType == typeof( sbyte ) || valueType == typeof( uint ) || valueType == typeof( long ) || valueType == typeof( ulong )) //// { //// return InternalGetValueAsString( enumType, value ); //// } //// //// throw new ArgumentException( Environment.GetResourceString( "Arg_MustBeEnumBaseTypeOrEnum" ), "value" ); //// } //// //// public static String[] GetNames( Type enumType ) //// { //// ValidateEnumType( enumType ); //// //// // Get all of the Field names //// String[] ret = GetHashEntry( enumType ).names; //// //// // Make a copy since we can't hand out the same array since users can modify them //// String[] retVal = new String[ret.Length]; //// //// Array.Copy( ret, retVal, ret.Length ); //// //// return retVal; //// } //// //// public static Object ToObject( Type enumType, Object value ) //// { //// if(value == null) //// { //// throw new ArgumentNullException( "value" ); //// } //// //// // Delegate rest of error checking to the other functions //// TypeCode typeCode = Convert.GetTypeCode( value ); //// //// switch(typeCode) //// { //// case TypeCode.Int32: //// return ToObject( enumType, (int)value ); //// //// case TypeCode.SByte: //// return ToObject( enumType, (sbyte)value ); //// //// case TypeCode.Int16: //// return ToObject( enumType, (short)value ); //// //// case TypeCode.Int64: //// return ToObject( enumType, (long)value ); //// //// case TypeCode.UInt32: //// return ToObject( enumType, (uint)value ); //// //// case TypeCode.Byte: //// return ToObject( enumType, (byte)value ); //// //// case TypeCode.UInt16: //// return ToObject( enumType, (ushort)value ); //// //// case TypeCode.UInt64: //// return ToObject( enumType, (ulong)value ); //// //// default: //// // All unsigned types will be directly cast //// throw new ArgumentException( Environment.GetResourceString( "Arg_MustBeEnumBaseTypeOrEnum" ), "value" ); //// } //// } //// //// public static bool IsDefined( Type enumType, Object value ) //// { //// ValidateEnumType( enumType ); //// //// if(value == null) //// { //// throw new ArgumentNullException( "value" ); //// } //// //// // Check if both of them are of the same type //// Type valueType = value.GetType(); //// //// if(!(valueType is RuntimeType)) //// { //// throw new ArgumentException( Environment.GetResourceString( "Arg_MustBeType" ), "valueType" ); //// } //// //// Type underlyingType = GetUnderlyingType( enumType ); //// //// // If the value is an Enum then we need to extract the underlying value from it //// if(valueType.IsEnum) //// { //// Type valueUnderlyingType = GetUnderlyingType( valueType ); //// //// if(valueType != enumType) //// { //// throw new ArgumentException( String.Format( CultureInfo.CurrentCulture, Environment.GetResourceString( "Arg_EnumAndObjectMustBeSameType" ), valueType.ToString(), enumType.ToString() ) ); //// } //// //// valueType = valueUnderlyingType; //// } //// else //// { //// // The value must be of the same type as the Underlying type of the Enum //// if((valueType != underlyingType) && (valueType != stringType)) //// { //// throw new ArgumentException( String.Format( CultureInfo.CurrentCulture, Environment.GetResourceString( "Arg_EnumUnderlyingTypeAndObjectMustBeSameType" ), valueType.ToString(), underlyingType.ToString() ) ); //// } //// } //// //// // If String is passed in //// if(valueType == stringType) //// { //// // Get all of the Fields //// String[] names = GetHashEntry( enumType ).names; //// //// for(int i = 0; i < names.Length; i++) //// { //// if(names[i].Equals( (string)value )) //// { //// return true; //// } //// } //// //// return false; //// } //// //// ulong[] values = GetHashEntry( enumType ).values; //// //// // Look at the 8 possible enum base classes //// if(valueType == intType || valueType == typeof( short ) || valueType == typeof( ushort ) || valueType == typeof( byte ) || valueType == typeof( sbyte ) || valueType == typeof( uint ) || valueType == typeof( long ) || valueType == typeof( ulong )) //// { //// ulong val = ToUInt64( value ); //// //// return (BinarySearch( values, val ) >= 0); //// } //// //// BCLDebug.Assert( false, "Unknown enum type" ); //// throw new InvalidOperationException( Environment.GetResourceString( "InvalidOperation_UnknownEnumType" ) ); //// } //// //// public static String Format( Type enumType, Object value, String format ) //// { //// ValidateEnumType( enumType ); //// //// if(value == null) //// { //// throw new ArgumentNullException( "value" ); //// } //// //// if(format == null) //// { //// throw new ArgumentNullException( "format" ); //// } //// //// // Check if both of them are of the same type //// Type valueType = value.GetType(); //// //// if(!(valueType is RuntimeType)) //// { //// throw new ArgumentException( Environment.GetResourceString( "Arg_MustBeType" ), "valueType" ); //// } //// //// Type underlyingType = GetUnderlyingType( enumType ); //// //// // If the value is an Enum then we need to extract the underlying value from it //// if(valueType.IsEnum) //// { //// Type valueUnderlyingType = GetUnderlyingType( valueType ); //// //// if(valueType != enumType) //// { //// throw new ArgumentException( String.Format( CultureInfo.CurrentCulture, Environment.GetResourceString( "Arg_EnumAndObjectMustBeSameType" ), valueType.ToString(), enumType.ToString() ) ); //// } //// //// valueType = valueUnderlyingType; //// value = ((Enum)value).GetValue(); //// } //// // The value must be of the same type as the Underlying type of the Enum //// else if(valueType != underlyingType) //// { //// throw new ArgumentException( String.Format( CultureInfo.CurrentCulture, Environment.GetResourceString( "Arg_EnumFormatUnderlyingTypeAndObjectMustBeSameType" ), valueType.ToString(), underlyingType.ToString() ) ); //// } //// //// if(format.Length != 1) //// { //// // all acceptable format string are of length 1 //// throw new FormatException( Environment.GetResourceString( "Format_InvalidEnumFormatSpecification" ) ); //// } //// //// char formatCh = format[0]; //// //// if(formatCh == 'D' || formatCh == 'd') //// { //// return value.ToString(); //// } //// //// if(formatCh == 'X' || formatCh == 'x') //// { //// // Retrieve the value from the field. //// return InternalFormattedHexString( value ); //// } //// //// if(formatCh == 'G' || formatCh == 'g') //// { //// return InternalFormat( enumType, value ); //// } //// //// if(formatCh == 'F' || formatCh == 'f') //// { //// return InternalFlagsFormat( enumType, value ); //// } //// //// throw new FormatException( Environment.GetResourceString( "Format_InvalidEnumFormatSpecification" ) ); //// } //// #endregion #region Definitions //// private class HashEntry //// { //// // Each entry contains a list of sorted pair of enum field names and values, sorted by values //// public HashEntry( String[] names, ulong[] values ) //// { //// this.names = names; //// this.values = values; //// } //// //// public String[] names; //// public ulong[] values; //// } #endregion #region Private Methods private Object GetValue() { throw new NotImplementedException(); //// return InternalGetValue(); } //// private String ToHexString() //// { //// Type eT = this.GetType(); //// FieldInfo thisField = GetValueField( eT ); //// //// // Retrieve the value from the field. //// return InternalFormattedHexString( ((RtFieldInfo)thisField).InternalGetValue( this, false ) ); //// //return InternalFormattedHexString(((RuntimeFieldInfo)thisField).GetValue(this)); //// } //// //// [ResourceExposure( ResourceScope.None )] //// [MethodImpl( MethodImplOptions.InternalCall )] //// private extern Object InternalGetValue(); //// #endregion #region Object Overrides //// [ResourceExposure( ResourceScope.None )] //// [MethodImpl( MethodImplOptions.InternalCall )] //// public extern override bool Equals( Object obj ); //// ////FCIMPL2(FC_BOOL_RET, ReflectionEnum::InternalEquals, Object *pRefThis, Object* pRefTarget) //// ////{ //// //// FCALL_CONTRACT; //// //// //// //// VALIDATEOBJECT(pRefThis); //// //// BOOL ret = false; //// //// if (pRefTarget == NULL) { //// //// FC_RETURN_BOOL(ret); //// //// } //// //// //// //// if( pRefThis == pRefTarget) //// //// FC_RETURN_BOOL(true); //// //// //// //// //Make sure we are comparing same type. //// //// MethodTable* pMTThis = pRefThis->GetMethodTable(); //// //// _ASSERTE(!pMTThis->IsArray()); // bunch of assumptions about arrays wrong. //// //// if ( pMTThis != pRefTarget->GetMethodTable()) { //// //// FC_RETURN_BOOL(ret); //// //// } //// //// //// //// void * pThis = pRefThis->UnBox(); //// //// void * pTarget = pRefTarget->UnBox(); //// //// switch (pMTThis->GetNumInstanceFieldBytes()) { //// //// case 1: //// //// ret = (*(UINT8*)pThis == *(UINT8*)pTarget); //// //// break; //// //// case 2: //// //// ret = (*(UINT16*)pThis == *(UINT16*)pTarget); //// //// break; //// //// case 4: //// //// ret = (*(UINT32*)pThis == *(UINT32*)pTarget); //// //// break; //// //// case 8: //// //// ret = (*(UINT64*)pThis == *(UINT64*)pTarget); //// //// break; //// //// default: //// //// // should not reach here. //// //// UNREACHABLE_MSG("Incorrect Enum Type size!"); //// //// break; //// //// } //// //// //// //// FC_RETURN_BOOL(ret); //// ////} //// ////FCIMPLEND //// //// public override int GetHashCode() //// { //// return GetValue().GetHashCode(); //// } //// //// public override String ToString() //// { //// // Returns the value in a human readable format. For PASCAL style enums who's value maps directly the name of the field is returned. //// // For PASCAL style enums who's values do not map directly the decimal value of the field is returned. //// // For BitFlags (indicated by the Flags custom attribute): If for each bit that is set in the value there is a corresponding constant //// //(a pure power of 2), then the OR string (ie "Red | Yellow") is returned. Otherwise, if the value is zero or if you can't create a string that consists of //// // pure powers of 2 OR-ed together, you return a hex value //// Type eT = this.GetType(); //// FieldInfo thisField = GetValueField( eT ); //// //// // Retrieve the value from the field. //// Object value = ((RtFieldInfo)thisField).InternalGetValue( this, false ); //// //// //Object value = ((RuntimeFieldInfo)thisField).GetValueInternal(this); //// return InternalFormat( eT, value ); //// } #endregion #region IFormattable [Obsolete( "The provider argument is not used. Please use ToString(String)." )] public String ToString( String format, IFormatProvider provider ) { return ToString( format ); } #endregion #region IComparable public int CompareTo( Object target ) { const int retIncompatibleMethodTables = 2; // indicates that the method tables did not match const int retInvalidEnumType = 3; // indicates that the enum was of an unknown/unsupported unerlying type if(this == null) { throw new NullReferenceException(); } int ret = InternalCompareTo( this, target ); if(ret < retIncompatibleMethodTables) { // -1, 0 and 1 are the normal return codes return ret; } else if(ret == retIncompatibleMethodTables) { Type thisType = this.GetType(); Type targetType = target.GetType(); #if EXCEPTION_STRINGS throw new ArgumentException( String.Format( CultureInfo.CurrentCulture, Environment.GetResourceString( "Arg_EnumAndObjectMustBeSameType" ), targetType.ToString(), thisType.ToString() ) ); #else throw new ArgumentException(); #endif } else { // assert valid return code (3) BCLDebug.Assert( ret == retInvalidEnumType, "Enum.InternalCompareTo return code was invalid" ); #if EXCEPTION_STRINGS throw new InvalidOperationException( Environment.GetResourceString( "InvalidOperation_UnknownEnumType" ) ); #else throw new InvalidOperationException(); #endif } } #endregion #region Public Methods public String ToString( String format ) { return ToString(); //// if(format == null || format.Length == 0) //// { //// format = "G"; //// } //// //// if(String.Compare( format, "G", StringComparison.OrdinalIgnoreCase ) == 0) //// { //// return ToString(); //// // return InternalFormat(this.GetType(), this.GetValue()); //// } //// //// if(String.Compare( format, "D", StringComparison.OrdinalIgnoreCase ) == 0) //// { //// return this.GetValue().ToString(); //// } //// //// if(String.Compare( format, "X", StringComparison.OrdinalIgnoreCase ) == 0) //// { //// return this.ToHexString(); //// } //// //// if(String.Compare( format, "F", StringComparison.OrdinalIgnoreCase ) == 0) //// { //// return InternalFlagsFormat( this.GetType(), this.GetValue() ); //// } //// //// throw new FormatException( Environment.GetResourceString( "Format_InvalidEnumFormatSpecification" ) ); } [Obsolete( "The provider argument is not used. Please use ToString()." )] public String ToString( IFormatProvider provider ) { return ToString(); } #endregion #region IConvertible public TypeCode GetTypeCode() { Type enumType = this.GetType(); Type underlyingType = GetUnderlyingType( enumType ); if(underlyingType == typeof( Int32 )) { return TypeCode.Int32; } if(underlyingType == typeof( sbyte )) { return TypeCode.SByte; } if(underlyingType == typeof( Int16 )) { return TypeCode.Int16; } if(underlyingType == typeof( Int64 )) { return TypeCode.Int64; } if(underlyingType == typeof( UInt32 )) { return TypeCode.UInt32; } if(underlyingType == typeof( byte )) { return TypeCode.Byte; } if(underlyingType == typeof( UInt16 )) { return TypeCode.UInt16; } if(underlyingType == typeof( UInt64 )) { return TypeCode.UInt64; } BCLDebug.Assert( false, "Unknown underlying type." ); #if EXCEPTION_STRINGS throw new InvalidOperationException( Environment.GetResourceString( "InvalidOperation_UnknownEnumType" ) ); #else throw new InvalidOperationException(); #endif } /// bool IConvertible.ToBoolean( IFormatProvider provider ) { return Convert.ToBoolean( GetValue(), CultureInfo.CurrentCulture ); } /// char IConvertible.ToChar( IFormatProvider provider ) { return Convert.ToChar( GetValue(), CultureInfo.CurrentCulture ); } /// sbyte IConvertible.ToSByte( IFormatProvider provider ) { return Convert.ToSByte( GetValue(), CultureInfo.CurrentCulture ); } /// byte IConvertible.ToByte( IFormatProvider provider ) { return Convert.ToByte( GetValue(), CultureInfo.CurrentCulture ); } /// short IConvertible.ToInt16( IFormatProvider provider ) { return Convert.ToInt16( GetValue(), CultureInfo.CurrentCulture ); } /// ushort IConvertible.ToUInt16( IFormatProvider provider ) { return Convert.ToUInt16( GetValue(), CultureInfo.CurrentCulture ); } /// int IConvertible.ToInt32( IFormatProvider provider ) { return Convert.ToInt32( GetValue(), CultureInfo.CurrentCulture ); } /// uint IConvertible.ToUInt32( IFormatProvider provider ) { return Convert.ToUInt32( GetValue(), CultureInfo.CurrentCulture ); } /// long IConvertible.ToInt64( IFormatProvider provider ) { return Convert.ToInt64( GetValue(), CultureInfo.CurrentCulture ); } /// ulong IConvertible.ToUInt64( IFormatProvider provider ) { return Convert.ToUInt64( GetValue(), CultureInfo.CurrentCulture ); } /// float IConvertible.ToSingle( IFormatProvider provider ) { return Convert.ToSingle( GetValue(), CultureInfo.CurrentCulture ); } /// double IConvertible.ToDouble( IFormatProvider provider ) { return Convert.ToDouble( GetValue(), CultureInfo.CurrentCulture ); } /// Decimal IConvertible.ToDecimal( IFormatProvider provider ) { return Convert.ToDecimal( GetValue(), CultureInfo.CurrentCulture ); } /// DateTime IConvertible.ToDateTime( IFormatProvider provider ) { #if EXCEPTION_STRINGS throw new InvalidCastException( String.Format( CultureInfo.CurrentCulture, Environment.GetResourceString( "InvalidCast_FromTo" ), "Enum", "DateTime" ) ); #else throw new InvalidCastException(); #endif } /// Object IConvertible.ToType( Type type, IFormatProvider provider ) { return Convert.DefaultToType( (IConvertible)this, type, provider ); } #endregion #region ToObject //// [ResourceExposure( ResourceScope.None )] //// [MethodImpl( MethodImplOptions.InternalCall )] //// private static extern Object InternalBoxEnum( Type enumType, long value ); //// ////FCIMPL2_IV(Object*, ReflectionEnum::InternalBoxEnum, ReflectClassBaseObject* target, INT64 value) { //// //// FCALL_CONTRACT; //// //// //// //// VALIDATEOBJECT(target); //// //// OBJECTREF ret = NULL; //// //// //// //// MethodTable* pMT = target->GetType().AsMethodTable(); //// //// HELPER_METHOD_FRAME_BEGIN_RET_0(); //// //// //// //// ret = pMT->Box(ArgSlotEndianessFixup((ARG_SLOT*)&value, pMT->GetNumInstanceFieldBytes()), FALSE); //// //// //// //// HELPER_METHOD_FRAME_END(); //// //// return OBJECTREFToObject(ret); //// ////} //// ////FCIMPLEND //// //// //// //// [CLSCompliant( false )] //// public static Object ToObject( Type enumType, sbyte value ) //// { //// ValidateEnumType( enumType ); //// //// return InternalBoxEnum( enumType, value ); //// } //// //// public static Object ToObject( Type enumType, short value ) //// { //// ValidateEnumType( enumType ); //// //// return InternalBoxEnum( enumType, value ); //// } //// //// public static Object ToObject( Type enumType, int value ) //// { //// ValidateEnumType( enumType ); //// //// return InternalBoxEnum( enumType, value ); //// } //// //// public static Object ToObject( Type enumType, byte value ) //// { //// ValidateEnumType( enumType ); //// //// return InternalBoxEnum( enumType, value ); //// } //// //// [CLSCompliant( false )] //// public static Object ToObject( Type enumType, ushort value ) //// { //// ValidateEnumType( enumType ); //// //// return InternalBoxEnum( enumType, value ); //// } //// //// [CLSCompliant( false )] //// public static Object ToObject( Type enumType, uint value ) //// { //// ValidateEnumType( enumType ); //// //// return InternalBoxEnum( enumType, value ); //// } //// //// public static Object ToObject( Type enumType, long value ) //// { //// ValidateEnumType( enumType ); //// //// return InternalBoxEnum( enumType, value ); //// } //// //// [CLSCompliant( false )] //// public static Object ToObject( Type enumType, ulong value ) //// { //// ValidateEnumType( enumType ); //// //// return InternalBoxEnum( enumType, unchecked( (long)value ) ); //// } #endregion } } ================================================ FILE: Zelig/Zelig/RunTime/Framework/mscorlib/System/Environment.cs ================================================ // ==++== // // Copyright (c) Microsoft Corporation. All rights reserved. // // ==--== /*============================================================ ** ** Class: Environment ** ** ** Purpose: Provides some basic access to some environment ** functionality. ** ** ============================================================*/ namespace System { ////using System.IO; ////using System.Security; ////using System.Resources; using System.Globalization; using System.Collections; ////using System.Security.Permissions; ////using System.Text; using System.Configuration.Assemblies; using System.Runtime.InteropServices; using System.Runtime.CompilerServices; using System.Runtime.ConstrainedExecution; using System.Reflection; using System.Diagnostics; using System.Threading; ////using System.Runtime.Versioning; ////using Microsoft.Win32; ////public enum EnvironmentVariableTarget ////{ //// Process = 0, //// User = 1, //// Machine = 2, ////} public static class Environment { //// // Assume the following constants include the terminating '\0' - use <, not <= //// const int MaxEnvVariableValueLength = 32767; // maximum length for environment variable name and value //// //// // System environment variables are stored in the registry, and have //// // a size restriction that is separate from both normal environment //// // variables and registry value name lengths, according to MSDN. //// // MSDN doesn't detail whether the name is limited to 1024, or whether //// // that includes the contents of the environment variable. //// const int MaxSystemEnvVariableLength = 1024; //// //// internal sealed class ResourceHelper //// { //// private ResourceManager SystemResMgr; //// //// // To avoid infinite loops when calling GetResourceString. See comments //// // in GetResourceString for this field. //// private Stack currentlyLoading; //// //// // process-wide state (since this is only used in one domain), //// // used to avoid the TypeInitialization infinite recusion //// // in GetResourceStringCode //// internal bool resourceManagerInited = false; //// //// internal class GetResourceStringUserData //// { //// public ResourceHelper m_resourceHelper; //// public String m_key; //// public String m_retVal; //// public bool m_lockWasTaken; //// //// public GetResourceStringUserData( ResourceHelper resourceHelper, String key ) //// { //// m_resourceHelper = resourceHelper; //// m_key = key; //// } //// } //// //// [ReliabilityContract( Consistency.WillNotCorruptState, Cer.MayFail )] //// internal String GetResourceString( String key ) //// { //// if(key == null || key.Length == 0) //// { //// BCLDebug.Assert( false, "Environment::GetResourceString with null or empty key. Bug in caller, or weird recursive loading problem?" ); //// return "[Resource lookup failed - null or empty resource name]"; //// } //// //// // We have a somewhat common potential for infinite //// // loops with mscorlib's ResourceManager. If "potentially dangerous" //// // code throws an exception, we will get into an infinite loop //// // inside the ResourceManager and this "potentially dangerous" code. //// // Potentially dangerous code includes the IO package, CultureInfo, //// // parts of the loader, some parts of Reflection, Security (including //// // custom user-written permissions that may parse an XML file at //// // class load time), assembly load event handlers, etc. Essentially, //// // this is not a bounded set of code, and we need to fix the problem. //// // Fortunately, this is limited to mscorlib's error lookups and is NOT //// // a general problem for all user code using the ResourceManager. //// //// // The solution is to make sure only one thread at a time can call //// // GetResourceString. Also, since resource lookups can be //// // reentrant, if the same thread comes into GetResourceString //// // twice looking for the exact same resource name before //// // returning, we're going into an infinite loop and we should //// // return a bogus string. //// //// GetResourceStringUserData userData = new GetResourceStringUserData( this, key ); //// //// RuntimeHelpers.TryCode tryCode = new RuntimeHelpers.TryCode ( GetResourceStringCode ); //// RuntimeHelpers.CleanupCode cleanupCode = new RuntimeHelpers.CleanupCode( GetResourceStringBackoutCode ); //// //// RuntimeHelpers.ExecuteCodeWithGuaranteedCleanup( tryCode, cleanupCode, userData ); //// //// return userData.m_retVal; //// } //// //// private void GetResourceStringCode( Object userDataIn ) //// { //// GetResourceStringUserData userData = (GetResourceStringUserData)userDataIn; //// ResourceHelper rh = userData.m_resourceHelper; //// String key = userData.m_key; //// //// Monitor.ReliableEnter( rh, ref userData.m_lockWasTaken ); //// //// // Are we recursively looking up the same resource? //// if(rh.currentlyLoading != null && rh.currentlyLoading.Count > 0 && rh.currentlyLoading.Contains( key )) //// { //// // This is often a bug in the BCL, security, NLS+ code, //// // or the loader somewhere. However, this could also //// // be a setup problem - check whether mscorlib & //// // mscorwks are both of the same build flavor. //// String stackTrace = "[Couldn't get a stack trace]"; //// //// try //// { //// StackTrace st = new StackTrace( true ); //// //// // Don't attempt to localize strings in this stack trace, otherwise it could cause //// // infinite recursion. This stack trace is used for an Assert message only, and //// // so the lack of localization should not be an issue. //// stackTrace = st.ToString( System.Diagnostics.StackTrace.TraceFormat.NoResourceLookup ); //// } //// catch(StackOverflowException) //// { //// } //// catch(NullReferenceException) //// { //// } //// catch(OutOfMemoryException) //// { //// } //// //// BCLDebug.Assert( false, "Infinite recursion during resource lookup. Resource name: " + key + "\r\n" + stackTrace ); //// //// // Note: can't append the key name, since that may require //// // an extra allocation... //// userData.m_retVal = "[Resource lookup failed - infinite recursion or critical failure detected.]"; //// return; //// } //// //// if(rh.currentlyLoading == null) //// { //// rh.currentlyLoading = new Stack( 4 ); //// } //// //// // Call class constructors preemptively, so that we cannot get into an infinite //// // loop constructing a TypeInitializationException. If this were omitted, //// // we could get the Infinite recursion assert above by failing type initialization //// // between the Push and Pop calls below. //// //// if(!rh.resourceManagerInited) //// { //// // process-critical code here. No ThreadAbortExceptions //// // can be thrown here. Other exceptions percolate as normal. //// RuntimeHelpers.PrepareConstrainedRegions(); //// try //// { //// } //// finally //// { //// RuntimeHelpers.RunClassConstructor( typeof( ResourceManager ).TypeHandle ); //// RuntimeHelpers.RunClassConstructor( typeof( ResourceReader ).TypeHandle ); //// RuntimeHelpers.RunClassConstructor( typeof( RuntimeResourceSet ).TypeHandle ); //// RuntimeHelpers.RunClassConstructor( typeof( BinaryReader ).TypeHandle ); //// //// rh.resourceManagerInited = true; //// } //// //// } //// //// rh.currentlyLoading.Push( key ); //// //// if(rh.SystemResMgr == null) //// { //// rh.SystemResMgr = new ResourceManager( "mscorlib", typeof( Object ).Assembly ); //// } //// //// String s = rh.SystemResMgr.GetString( key, null ); //// //// rh.currentlyLoading.Pop(); //// //// BCLDebug.Assert( s != null, "Managed resource string lookup failed. Was your resource name misspelled? Did you rebuild mscorlib after adding a resource to resources.txt? Debug this w/ cordbg and bug whoever owns the code that called rhironment.GetResourceString. Resource name was: \"" + key + "\"" ); //// //// userData.m_retVal = s; //// } //// //// [PrePrepareMethod] //// private void GetResourceStringBackoutCode( Object userDataIn, bool exceptionThrown ) //// { //// GetResourceStringUserData userData = (GetResourceStringUserData)userDataIn; //// ResourceHelper rh = userData.m_resourceHelper; //// //// if(exceptionThrown) //// { //// if(userData.m_lockWasTaken) //// { //// // Backout code - throw away potentially corrupt state //// rh.SystemResMgr = null; //// rh.currentlyLoading = null; //// } //// } //// //// // Release the lock, if we took it. //// if(userData.m_lockWasTaken) //// { //// Monitor.Exit( rh ); //// } //// } //// } //// //// //// private static ResourceHelper m_resHelper; // Doesn't need to be initialized as they're zero-init. //// //// private const int MaxMachineNameLength = 256; //// //// // Private object for locking instead of locking on a public type for SQL reliability work. //// private static Object s_InternalSyncObject; //// private static Object InternalSyncObject //// { //// [ReliabilityContract( Consistency.WillNotCorruptState, Cer.MayFail )] //// get //// { //// if(s_InternalSyncObject == null) //// { //// Object o = new Object(); //// //// Interlocked.CompareExchange( ref s_InternalSyncObject, o, null ); //// } //// //// return s_InternalSyncObject; //// } //// } //// //// //// private static OperatingSystem m_os; // Cached OperatingSystem value //// private static OSName m_osname; /*==================================TickCount=================================== **Action: Gets the number of ticks since the system was started. **Returns: The number of ticks since the system was started. **Arguments: None **Exceptions: None ==============================================================================*/ public extern static int TickCount { [MethodImpl( MethodImplOptions.InternalCall )] get; //// { //// return nativeGetTickCount(); //// } } //// [ResourceExposure( ResourceScope.None )] //// [MethodImpl( MethodImplOptions.InternalCall )] //// private static extern int nativeGetTickCount(); //// //// // Terminates this process with the given exit code. //// [ResourceExposure( ResourceScope.Process )] //// [MethodImpl( MethodImplOptions.InternalCall )] //// private static extern void ExitNative( int exitCode ); //// //// [ResourceExposure( ResourceScope.Process )] //// [ResourceConsumption( ResourceScope.Process )] //// [SecurityPermissionAttribute( SecurityAction.Demand, Flags = SecurityPermissionFlag.UnmanagedCode )] //// public static void Exit( int exitCode ) //// { //// ExitNative( exitCode ); //// } //// //// //// public static int ExitCode //// { //// get //// { //// return nativeGetExitCode(); //// } //// //// set //// { //// nativeSetExitCode( value ); //// } //// } //// //// [ResourceExposure( ResourceScope.None )] //// [MethodImpl( MethodImplOptions.InternalCall )] //// private static extern void nativeSetExitCode( int exitCode ); //// //// // Gets the exit code of the process. //// [ResourceExposure( ResourceScope.None )] //// [MethodImpl( MethodImplOptions.InternalCall )] //// private static extern int nativeGetExitCode(); //// //// //// [SecurityPermissionAttribute( SecurityAction.LinkDemand, Flags = SecurityPermissionFlag.UnmanagedCode )] //// [ResourceExposure( ResourceScope.Process )] //// [MethodImpl( MethodImplOptions.InternalCall )] //// public static extern void FailFast( String message ); //// //// //// public static String CommandLine //// { //// get //// { //// new EnvironmentPermission( EnvironmentPermissionAccess.Read, "Path" ).Demand(); //// //// return GetCommandLineNative(); //// } //// } //// //// [ResourceExposure( ResourceScope.None )] //// [MethodImpl( MethodImplOptions.InternalCall )] //// private static extern String GetCommandLineNative(); //// //// /*===============================CurrentDirectory=============================== //// **Action: Provides a getter and setter for the current directory. The original //// ** current directory is the one from which the process was started. //// **Returns: The current directory (from the getter). Void from the setter. //// **Arguments: The current directory to which to switch to the setter. //// **Exceptions: //// ==============================================================================*/ //// public static String CurrentDirectory //// { //// [ResourceExposure( ResourceScope.Machine )] //// [ResourceConsumption( ResourceScope.Machine )] //// get //// { //// return Directory.GetCurrentDirectory(); //// } //// //// [ResourceExposure( ResourceScope.Machine )] //// [ResourceConsumption( ResourceScope.Machine )] //// set //// { //// Directory.SetCurrentDirectory( value ); //// } //// } //// //// // Returns the system directory (ie, C:\WinNT\System32). //// public static String SystemDirectory //// { //// [ResourceExposure( ResourceScope.Machine )] //// [ResourceConsumption( ResourceScope.Machine )] //// get //// { //// StringBuilder sb = new StringBuilder( Path.MAX_PATH ); //// int r = Win32Native.GetSystemDirectory( sb, Path.MAX_PATH ); //// BCLDebug.Assert( r < Path.MAX_PATH, "r < Path.MAX_PATH" ); //// if(r == 0) //// { //// __Error.WinIOError(); //// } //// //// String path = sb.ToString(); //// //// // Do security check //// new FileIOPermission( FileIOPermissionAccess.PathDiscovery, path ).Demand(); //// //// return path; //// } //// } //// //// // Returns the windows directory (ie, C:\WinNT). //// // Used by NLS+ custom culures only at the moment. //// internal static String InternalWindowsDirectory //// { //// [ResourceExposure( ResourceScope.Machine )] //// [ResourceConsumption( ResourceScope.Machine )] //// get //// { //// StringBuilder sb = new StringBuilder( Path.MAX_PATH ); //// //// int r = Win32Native.GetWindowsDirectory( sb, Path.MAX_PATH ); //// BCLDebug.Assert( r < Path.MAX_PATH, "r < Path.MAX_PATH" ); //// //// if(r == 0) //// { //// __Error.WinIOError(); //// } //// //// String path = sb.ToString(); //// //// return path; //// } //// } //// //// public static String ExpandEnvironmentVariables( String name ) //// { //// if(name == null) //// { //// throw new ArgumentNullException( "name" ); //// } //// //// if(name.Length == 0) //// { //// return name; //// } //// //// // Do a security check to guarantee we can read each of the //// // individual environment variables requested here. //// String[] varArray = name.Split( new char[] { '%' } ); //// StringBuilder vars = new StringBuilder(); //// //// int currentSize = 100; //// StringBuilder blob = new StringBuilder( currentSize ); // A somewhat reasonable default size //// int size; //// bool fJustExpanded = false; // to accommodate expansion alg. //// //// for(int i = 1; i < varArray.Length - 1; i++) //// { // Skip first and last tokens //// // ExpandEnvironmentStrings' greedy algorithm expands every //// // non-boundary %-delimited substring, provided the previous //// // has not been expanded. //// // if "foo" is not expandable, and "PATH" is, then both //// // %foo%PATH% and %foo%foo%PATH% will expand PATH, but //// // %PATH%PATH% will expand only once. //// // Therefore, if we've just expanded, skip this substring. //// if(varArray[i].Length == 0 || fJustExpanded == true) //// { //// fJustExpanded = false; //// continue; // Nothing to expand //// } //// //// // Guess a somewhat reasonable initial size, call the method, then if //// // it fails (ie, the return value is larger than our buffer size), //// // make a new buffer & try again. //// blob.Length = 0; //// //// String envVar = "%" + varArray[i] + "%"; //// size = Win32Native.ExpandEnvironmentStrings( envVar, blob, currentSize ); //// if(size == 0) //// { //// Marshal.ThrowExceptionForHR( Marshal.GetHRForLastWin32Error() ); //// } //// //// // some environment variable might be changed while this function is called //// while(size > currentSize) //// { //// currentSize = size; //// blob.Capacity = currentSize; //// blob.Length = 0; //// size = Win32Native.ExpandEnvironmentStrings( envVar, blob, currentSize ); //// if(size == 0) //// { //// Marshal.ThrowExceptionForHR( Marshal.GetHRForLastWin32Error() ); //// } //// } //// //// String temp = blob.ToString(); //// fJustExpanded = (temp != envVar); //// if(fJustExpanded) //// { // We expanded successfully, we need to do String comparision here //// // since %FOO% can become %FOOD //// vars.Append( varArray[i] ); //// vars.Append( ';' ); //// } //// } //// //// new EnvironmentPermission( EnvironmentPermissionAccess.Read, vars.ToString() ).Demand(); //// //// blob.Length = 0; //// size = Win32Native.ExpandEnvironmentStrings( name, blob, currentSize ); //// if(size == 0) //// { //// Marshal.ThrowExceptionForHR( Marshal.GetHRForLastWin32Error() ); //// } //// //// while(size > currentSize) //// { //// currentSize = size; //// //// blob.Capacity = currentSize; //// blob.Length = 0; //// //// size = Win32Native.ExpandEnvironmentStrings( name, blob, currentSize ); //// if(size == 0) //// { //// Marshal.ThrowExceptionForHR( Marshal.GetHRForLastWin32Error() ); //// } //// } //// //// return blob.ToString(); //// } //// //// public static String MachineName //// { //// get //// { //// // In future release of operating systems, you might be able to rename a machine without //// // rebooting. Therefore, don't cache this machine name. //// new EnvironmentPermission( EnvironmentPermissionAccess.Read, "COMPUTERNAME" ).Demand(); //// //// StringBuilder buf = new StringBuilder( MaxMachineNameLength ); //// int len = MaxMachineNameLength; //// if(Win32Native.GetComputerName( buf, ref len ) == 0) //// { //// throw new InvalidOperationException( Environment.GetResourceString( "InvalidOperation_ComputerName" ) ); //// } //// //// return buf.ToString(); //// } //// } //// //// public static int ProcessorCount //// { //// get //// { //// new EnvironmentPermission( EnvironmentPermissionAccess.Read, "NUMBER_OF_PROCESSORS" ).Demand(); //// //// Win32Native.SYSTEM_INFO info = new Win32Native.SYSTEM_INFO(); //// //// Win32Native.GetSystemInfo( ref info ); //// //// return info.dwNumberOfProcessors; //// } //// } //// //// /*==============================GetCommandLineArgs============================== //// **Action: Gets the command line and splits it appropriately to deal with whitespace, //// ** quotes, and escape characters. //// **Returns: A string array containing your command line arguments. //// **Arguments: None //// **Exceptions: None. //// ==============================================================================*/ //// public static String[] GetCommandLineArgs() //// { //// new EnvironmentPermission( EnvironmentPermissionAccess.Read, "Path" ).Demand(); //// //// return GetCommandLineArgsNative(); //// } //// //// [ResourceExposure( ResourceScope.None )] //// [MethodImpl( MethodImplOptions.InternalCall )] //// private static extern String[] GetCommandLineArgsNative(); //// //// // We need to keep this Fcall since it is used in AppDomain.cs. //// // If we call GetEnvironmentVariable from AppDomain.cs, we will use StringBuilder class. //// // That has side effect to change the ApartmentState of the calling Thread to MTA. //// // So runtime can't change the ApartmentState of calling thread any more. //// [ResourceExposure( ResourceScope.Process )] //// [MethodImpl( MethodImplOptions.InternalCall )] //// internal static extern String nativeGetEnvironmentVariable( String variable ); //// //// /*============================GetEnvironmentVariable============================ //// **Action: //// **Returns: //// **Arguments: //// **Exceptions: //// ==============================================================================*/ //// [ResourceExposure( ResourceScope.Machine )] //// [ResourceConsumption( ResourceScope.Machine )] //// public static String GetEnvironmentVariable( String variable ) //// { //// if(variable == null) //// { //// throw new ArgumentNullException( "variable" ); //// } //// //// (new EnvironmentPermission( EnvironmentPermissionAccess.Read, variable )).Demand(); //// //// StringBuilder blob = new StringBuilder( 128 ); // A somewhat reasonable default size //// int requiredSize = Win32Native.GetEnvironmentVariable( variable, blob, blob.Capacity ); //// if(requiredSize == 0) //// { // GetEnvironmentVariable failed //// if(Marshal.GetLastWin32Error() == Win32Native.ERROR_ENVVAR_NOT_FOUND) //// { //// return null; //// } //// } //// //// while(requiredSize > blob.Capacity) //// { // need to retry since the environment variable might be changed //// blob.Capacity = requiredSize; //// blob.Length = 0; //// //// requiredSize = Win32Native.GetEnvironmentVariable( variable, blob, blob.Capacity ); //// } //// //// return blob.ToString(); //// } //// //// [ResourceExposure( ResourceScope.Machine )] //// [ResourceConsumption( ResourceScope.Machine )] //// public static string GetEnvironmentVariable( string variable, EnvironmentVariableTarget target ) //// { //// if(target == EnvironmentVariableTarget.Process) //// { //// return GetEnvironmentVariable( variable ); //// } //// //// if(variable == null) //// { //// throw new ArgumentNullException( "variable" ); //// } //// //// (new EnvironmentPermission( PermissionState.Unrestricted )).Demand(); //// //// if(target == EnvironmentVariableTarget.Machine) //// { //// using(RegistryKey environmentKey = Registry.LocalMachine.OpenSubKey( @"System\CurrentControlSet\Control\Session Manager\Environment", false )) //// { //// string value = environmentKey.GetValue( variable ) as string; //// return value; //// } //// } //// else if(target == EnvironmentVariableTarget.User) //// { //// using(RegistryKey environmentKey = Registry.CurrentUser.OpenSubKey( "Environment", false )) //// { //// string value = environmentKey.GetValue( variable ) as string; //// return value; //// } //// } //// else //// { //// throw new ArgumentException( String.Format( CultureInfo.CurrentCulture, Environment.GetResourceString( "Arg_EnumIllegalVal" ), (int)target ) ); //// } //// } //// //// /*===========================GetEnvironmentVariables============================ //// **Action: Returns an IDictionary containing all enviroment variables and their values. //// **Returns: An IDictionary containing all environment variables and their values. //// **Arguments: None. //// **Exceptions: None. //// ==============================================================================*/ //// [MethodImpl( MethodImplOptions.InternalCall )] //// [ResourceExposure( ResourceScope.Machine )] //// private static extern char[] nativeGetEnvironmentCharArray(); //// //// [ResourceExposure( ResourceScope.Machine )] //// [ResourceConsumption( ResourceScope.Machine )] //// public static IDictionary GetEnvironmentVariables() //// { //// // Using an FCall is better than using PInvoke here since //// // Interop Marshaler can't handle string which contains '\0', we need //// // to allocate an unmanaged buffer, do the conversion and free the buffer //// // if we do use PInvoke. //// char[] block = nativeGetEnvironmentCharArray(); //// if(block == null) //// { //// throw new OutOfMemoryException(); //// } //// //// Hashtable table = new Hashtable( 20 ); //// StringBuilder vars = new StringBuilder(); //// // Copy strings out, parsing into pairs and inserting into the table. //// // The first few environment variable entries start with an '='! //// // The current working directory of every drive (except for those drives //// // you haven't cd'ed into in your DOS window) are stored in the //// // environment block (as =C:=pwd) and the program's exit code is //// // as well (=ExitCode=00000000) Skip all that start with =. //// // Read docs about Environment Blocks on MSDN's CreateProcess page. //// //// // Format for GetEnvironmentStrings is: //// // (=HiddenVar=value\0 | Variable=value\0)* \0 //// // See the description of Environment Blocks in MSDN's //// // CreateProcess page (null-terminated array of null-terminated strings). //// // Note the =HiddenVar's aren't always at the beginning. //// //// // GetEnvironmentCharArray will not return the trailing 0 to terminate //// // the array - we have the array length instead. //// bool first = true; //// for(int i = 0; i < block.Length; i++) //// { //// int startKey = i; //// // Skip to key //// // On some old OS, the environment block can be corrupted. //// // Someline will not have '=', so we need to check for '\0'. //// while(block[i] != '=' && block[i] != '\0') //// { //// i++; //// } //// //// if(block[i] == '\0') //// { //// continue; //// } //// //// // Skip over environment variables starting with '=' //// if(i - startKey == 0) //// { //// while(block[i] != 0) //// { //// i++; //// } //// continue; //// } //// //// String key = new String( block, startKey, i - startKey ); //// i++; // skip over '=' //// int startValue = i; //// while(block[i] != 0) //// { //// // Read to end of this entry //// i++; //// } //// //// String value = new String( block, startValue, i - startValue ); //// // skip over 0 handled by for loop's i++ //// table[key] = value; //// //// if(first) //// { //// first = false; //// } //// else //// { //// vars.Append( ';' ); //// } //// //// vars.Append( key ); //// } //// //// new EnvironmentPermission( EnvironmentPermissionAccess.Read, vars.ToString() ).Demand(); //// return table; //// } //// //// //// internal static IDictionary GetRegistryKeyNameValuePairs( RegistryKey registryKey ) //// { //// Hashtable table = new Hashtable( 20 ); //// string[] names = registryKey.GetValueNames(); //// foreach(string name in names) //// { //// string value = registryKey.GetValue( name, "" ).ToString(); //// //// table.Add( name, value ); //// } //// //// return table; //// } //// //// [ResourceExposure( ResourceScope.Machine )] //// [ResourceConsumption( ResourceScope.Machine )] //// public static IDictionary GetEnvironmentVariables( EnvironmentVariableTarget target ) //// { //// if(target == EnvironmentVariableTarget.Process) //// { //// return GetEnvironmentVariables(); //// } //// //// (new EnvironmentPermission( PermissionState.Unrestricted )).Demand(); //// //// if(target == EnvironmentVariableTarget.Machine) //// { //// using(RegistryKey environmentKey = Registry.LocalMachine.OpenSubKey( @"System\CurrentControlSet\Control\Session Manager\Environment", false )) //// { //// //// return GetRegistryKeyNameValuePairs( environmentKey ); //// } //// } //// else if(target == EnvironmentVariableTarget.User) //// { //// using(RegistryKey environmentKey = Registry.CurrentUser.OpenSubKey( "Environment", false )) //// { //// return GetRegistryKeyNameValuePairs( environmentKey ); //// } //// } //// else //// { //// throw new ArgumentException( String.Format( CultureInfo.CurrentCulture, Environment.GetResourceString( "Arg_EnumIllegalVal" ), (int)target ) ); //// } //// } //// //// [ResourceExposure( ResourceScope.Machine )] //// [ResourceConsumption( ResourceScope.Machine )] //// public static void SetEnvironmentVariable( string variable, string value ) //// { //// CheckEnvironmentVariableName( variable ); //// //// new EnvironmentPermission( PermissionState.Unrestricted ).Demand(); //// //// // explicitly null out value if is the empty string. //// if(String.IsNullOrEmpty( value ) || value[0] == '\0') //// { //// value = null; //// } //// else //// { //// if(value.Length >= MaxEnvVariableValueLength) //// { //// throw new ArgumentException( Environment.GetResourceString( "Argument_LongEnvVarValue" ) ); //// } //// } //// //// if(!Win32Native.SetEnvironmentVariable( variable, value )) //// { //// int errorCode = Marshal.GetLastWin32Error(); //// //// // Allow user to try to clear a environment variable //// if(errorCode == Win32Native.ERROR_ENVVAR_NOT_FOUND) //// { //// return; //// } //// //// // The error message from Win32 is "The filename or extension is too long", //// // which is not accurate. //// if(errorCode == Win32Native.ERROR_FILENAME_EXCED_RANGE) //// { //// throw new ArgumentException( Environment.GetResourceString( "Argument_LongEnvVarValue" ) ); //// } //// //// throw new ArgumentException( Win32Native.GetMessage( errorCode ) ); //// } //// } //// //// private static void CheckEnvironmentVariableName( string variable ) //// { //// if(variable == null) //// { //// throw new ArgumentNullException( "variable" ); //// } //// //// if(variable.Length == 0) //// { //// throw new ArgumentException( Environment.GetResourceString( "Argument_StringZeroLength" ), "variable" ); //// } //// //// if(variable[0] == '\0') //// { //// throw new ArgumentException( Environment.GetResourceString( "Argument_StringFirstCharIsZero" ), "variable" ); //// } //// //// // Make sure the environment variable name isn't longer than the //// // max limit on environment variable values. (MSDN is ambiguous //// // on whether this check is necessary.) //// if(variable.Length >= MaxEnvVariableValueLength) //// { //// throw new ArgumentException( Environment.GetResourceString( "Argument_LongEnvVarValue" ) ); //// } //// //// if(variable.IndexOf( '=' ) != -1) //// { //// throw new ArgumentException( Environment.GetResourceString( "Argument_IllegalEnvVarName" ) ); //// } //// } //// //// [ResourceExposure( ResourceScope.Machine )] //// [ResourceConsumption( ResourceScope.Machine )] //// public static void SetEnvironmentVariable( string variable, string value, EnvironmentVariableTarget target ) //// { //// if(target == EnvironmentVariableTarget.Process) //// { //// SetEnvironmentVariable( variable, value ); //// return; //// } //// //// CheckEnvironmentVariableName( variable ); //// //// // System-wide environment variables stored in the registry are //// // limited to 1024 chars for the environment variable name. //// if(variable.Length >= MaxSystemEnvVariableLength) //// { //// throw new ArgumentException( Environment.GetResourceString( "Argument_LongEnvVarName" ) ); //// } //// //// new EnvironmentPermission( PermissionState.Unrestricted ).Demand(); //// //// // explicitly null out value if is the empty string. //// if(String.IsNullOrEmpty( value ) || value[0] == '\0') //// { //// value = null; //// } //// //// if(target == EnvironmentVariableTarget.Machine) //// { //// using(RegistryKey environmentKey = Registry.LocalMachine.OpenSubKey( @"System\CurrentControlSet\Control\Session Manager\Environment", true )) //// { //// if(value == null) //// { //// environmentKey.DeleteValue( variable, false ); //// } //// else //// { //// environmentKey.SetValue( variable, value ); //// } //// } //// } //// else if(target == EnvironmentVariableTarget.User) //// { //// using(RegistryKey environmentKey = Registry.CurrentUser.OpenSubKey( "Environment", true )) //// { //// if(value == null) //// { //// environmentKey.DeleteValue( variable, false ); //// } //// else //// { //// environmentKey.SetValue( variable, value ); //// } //// } //// } //// else //// { //// throw new ArgumentException( String.Format( CultureInfo.CurrentCulture, Environment.GetResourceString( "Arg_EnumIllegalVal" ), (int)target ) ); //// } //// //// // send a WM_SETTINGCHANGE message to all windows //// IntPtr r = Win32Native.SendMessageTimeout( new IntPtr( Win32Native.HWND_BROADCAST ), Win32Native.WM_SETTINGCHANGE, IntPtr.Zero, "Environment", 0, 1000, IntPtr.Zero ); //// //// if(r == IntPtr.Zero) //// { //// BCLDebug.Assert( false, "SetEnvironmentVariable failed: " + Marshal.GetLastWin32Error() ); //// } //// } //// //// //// /*===============================GetLogicalDrives=============================== //// **Action: Retrieves the names of the logical drives on this machine in the form "C:\". //// **Arguments: None. //// **Exceptions: IOException. //// **Permissions: SystemInfo Permission. //// ==============================================================================*/ //// public static String[] GetLogicalDrives() //// { //// new EnvironmentPermission( PermissionState.Unrestricted ).Demand(); //// //// int drives = Win32Native.GetLogicalDrives(); //// if(drives == 0) //// { //// __Error.WinIOError(); //// } //// //// uint d = (uint)drives; //// int count = 0; //// while(d != 0) //// { //// if(((int)d & 1) != 0) count++; //// d >>= 1; //// } //// //// String[] result = new String[count]; //// char[] root = new char[] { 'A', ':', '\\' }; //// //// d = (uint)drives; //// count = 0; //// while(d != 0) //// { //// if(((int)d & 1) != 0) //// { //// result[count++] = new String( root ); //// } //// d >>= 1; //// root[0]++; //// } //// //// return result; //// } /*===================================NewLine==================================== **Action: A property which returns the appropriate newline string for the given ** platform. **Returns: \r\n on Win32. **Arguments: None. **Exceptions: None. ==============================================================================*/ public static String NewLine { get { #if !PLATFORM_UNIX return "\r\n"; #else return "\n"; #endif // !PLATFORM_UNIX } } //// //// //// /*===================================Version==================================== //// **Action: Returns the COM+ version struct, describing the build number. //// **Returns: //// **Arguments: //// **Exceptions: //// ==============================================================================*/ //// public static Version Version //// { //// get //// { //// return new Version( ThisAssembly.InformationalVersion ); //// } //// } //// //// //// /*==================================WorkingSet================================== //// **Action: //// **Returns: //// **Arguments: //// **Exceptions: //// ==============================================================================*/ //// [ResourceExposure( ResourceScope.None )] //// [MethodImpl( MethodImplOptions.InternalCall )] //// internal static extern long nativeGetWorkingSet(); //// //// public static long WorkingSet //// { //// get //// { //// new EnvironmentPermission( PermissionState.Unrestricted ).Demand(); //// //// return (long)nativeGetWorkingSet(); //// } //// } //// //// /*==================================OSVersion=================================== //// **Action: //// **Returns: //// **Arguments: //// **Exceptions: //// ==============================================================================*/ //// public static OperatingSystem OSVersion //// { //// get //// { //// if(m_os == null) //// { //// // We avoid the lock since we don't care if two threads will set this at the same time. //// Microsoft.Win32.Win32Native.OSVERSIONINFO osvi = new Microsoft.Win32.Win32Native.OSVERSIONINFO(); //// if(!Win32Native.GetVersionEx( osvi )) //// { //// throw new InvalidOperationException( Environment.GetResourceString( "InvalidOperation_GetVersion" ) ); //// } //// //// // Get Service pack information //// Microsoft.Win32.Win32Native.OSVERSIONINFOEX osviEx = new Microsoft.Win32.Win32Native.OSVERSIONINFOEX(); //// if(!Win32Native.GetVersionEx( osviEx )) //// { //// throw new InvalidOperationException( Environment.GetResourceString( "InvalidOperation_GetVersion" ) ); //// } //// //// PlatformID id; //// switch(osvi.PlatformId) //// { //// case Win32Native.VER_PLATFORM_WIN32_NT: //// id = PlatformID.Win32NT; //// break; //// //// default: //// BCLDebug.Assert( false, "Unsupported platform!" ); //// throw new InvalidOperationException( Environment.GetResourceString( "InvalidOperation_InvalidPlatformID" ) ); //// } //// //// Version v = new Version( osvi.MajorVersion, osvi.MinorVersion, osvi.BuildNumber, (osviEx.ServicePackMajor << 16) | osviEx.ServicePackMinor ); //// //// m_os = new OperatingSystem( id, v, osvi.CSDVersion ); //// } //// //// BCLDebug.Assert( m_os != null, "m_os != null" ); //// return m_os; //// } //// } //// //// [Serializable] //// internal enum OSName //// { //// Invalid = 0, //// Unknown = 1, //// WinNT = 0x80, //// Win2k = 2 | WinNT //// } //// //// internal static OSName OSInfo //// { //// get //// { //// if(m_osname == OSName.Invalid) //// { //// lock(InternalSyncObject) //// { //// if(m_osname == OSName.Invalid) //// { //// Microsoft.Win32.Win32Native.OSVERSIONINFO osvi = new Microsoft.Win32.Win32Native.OSVERSIONINFO(); //// //// bool r = Win32Native.GetVersionEx( osvi ); //// if(!r) //// { //// BCLDebug.Assert( r, "OSVersion native call failed." ); //// throw new InvalidOperationException( Environment.GetResourceString( "InvalidOperation_GetVersion" ) ); //// } //// //// switch(osvi.PlatformId) //// { //// case Win32Native.VER_PLATFORM_WIN32_NT: //// switch(osvi.MajorVersion) //// { //// case 5: //// m_osname = OSName.Win2k; //// break; //// //// case 4: //// BCLDebug.Assert( false, "NT4 is no longer a supported platform!" ); //// m_osname = OSName.Unknown; // Unknown OS //// break; //// //// default: //// m_osname = OSName.WinNT; //// break; //// } //// break; //// //// case Win32Native.VER_PLATFORM_WIN32_WINDOWS: //// BCLDebug.Assert( false, "Win9x is no longer a supported platform!" ); //// m_osname = OSName.Unknown; // Unknown OS //// break; //// //// default: //// m_osname = OSName.Unknown; // Unknown OS //// break; //// //// } //// } //// } //// } //// return m_osname; //// } //// } /*==================================StackTrace================================== **Action: **Returns: **Arguments: **Exceptions: ==============================================================================*/ //////public static String StackTrace //////{ ////// get ////// { ////// //////new EnvironmentPermission( PermissionState.Unrestricted ).Demand( ); ////// return GetStackTrace( null, true ); ////// } //////} //////internal static String GetStackTrace( Exception e, bool needFileInfo ) //////{ ////// // Note: Setting needFileInfo to true will start up COM and set our ////// // apartment state. Try to not call this when passing "true" ////// // before the EE's ExecuteMainMethod has had a chance to set up the ////// // apartment state. -- ////// StackTrace st; ////// if(e == null) ////// { ////// st = new StackTrace( needFileInfo ); ////// } ////// else ////// { ////// st = new StackTrace( e, needFileInfo ); ////// } ////// // Do no include a trailing newline for backwards compatibility ////// return st.ToString( System.Diagnostics.StackTrace.TraceFormat.Normal ); //////} //// private static void InitResourceHelper() //// { //// // Only the default AppDomain should have a ResourceHelper. All calls to //// // GetResourceString from any AppDomain delegate to GetResourceStringLocal //// // in the default AppDomain via the fcall GetResourceFromDefault. //// //// // Use Thread.BeginCriticalRegion to tell the CLR all managed //// // allocations within this block are appdomain-critical. //// // Use a CER to ensure we always exit this region. //// bool enteredRegion = false; //// bool tookLock = false; //// //// RuntimeHelpers.PrepareConstrainedRegions(); //// try //// { //// RuntimeHelpers.PrepareConstrainedRegions(); //// try //// { //// } //// finally //// { //// Thread.BeginCriticalRegion(); //// enteredRegion = true; //// //// Monitor.Enter( Environment.InternalSyncObject ); //// tookLock = true; //// } //// //// if(m_resHelper == null) //// { //// ResourceHelper rh = new ResourceHelper(); //// //// System.Threading.Thread.MemoryBarrier(); //// m_resHelper = rh; //// } //// } //// finally //// { //// if(tookLock) //// { //// Monitor.Exit( Environment.InternalSyncObject ); //// } //// //// if(enteredRegion) //// { //// Thread.EndCriticalRegion(); //// } //// } //// } //// [ResourceExposure( ResourceScope.None )] //// [MethodImpl( MethodImplOptions.InternalCall )] internal static String GetResourceFromDefault( String key ) { return key; } //// // Looks up the resource string value for key. //// // //// // if you change this method's signature then you must change the code that calls it //// // in excep.cpp and probably you will have to visit mscorlib.h to add the new signature //// // as well as metasig.h to create the new signature type //// internal static String GetResourceStringLocal( String key ) //// { //// if(m_resHelper == null) //// { //// InitResourceHelper(); //// } //// //// return m_resHelper.GetResourceString( key ); //// } //// [ResourceExposure( ResourceScope.None )] internal static String GetResourceString( String key ) { return GetResourceFromDefault( key ); } //// [ResourceExposure( ResourceScope.None )] internal static String GetResourceString( String key, params Object[] values ) { String s = GetResourceFromDefault( key ); return String.Format( CultureInfo.CurrentCulture, s, values ); } //// public static bool HasShutdownStarted //// { //// get //// { //// return nativeHasShutdownStarted(); //// } //// } //// //// [ResourceExposure( ResourceScope.None )] //// [MethodImpl( MethodImplOptions.InternalCall )] //// private static extern bool nativeHasShutdownStarted(); //// //// // This is the temporary Whidbey stub for compatibility flags //// [ResourceExposure( ResourceScope.None )] //// [MethodImpl( MethodImplOptions.InternalCall )] //// internal static extern bool GetCompatibilityFlag( CompatibilityFlag flag ); //// //// public static string UserName //// { //// get //// { //// new EnvironmentPermission( EnvironmentPermissionAccess.Read, "UserName" ).Demand(); //// //// StringBuilder sb = new StringBuilder( 256 ); //// int size = sb.Capacity; //// //// Win32Native.GetUserName( sb, ref size ); //// //// return sb.ToString(); //// } //// } //// //// // Note that this is a handle to a process window station, but it does //// // not need to be closed. CloseWindowStation would ignore this handle. //// // We also do handle equality checking as well. This isn't a great fit //// // for SafeHandle. We don't gain anything by using SafeHandle here. //// private static IntPtr processWinStation; // Doesn't need to be initialized as they're zero-init. //// private static bool isUserNonInteractive; //// //// public static bool UserInteractive //// { //// [ResourceExposure( ResourceScope.None )] //// [ResourceConsumption( ResourceScope.Machine, ResourceScope.Machine )] //// get //// { //// if((OSInfo & OSName.WinNT) == OSName.WinNT) //// { // On WinNT //// IntPtr hwinsta = Win32Native.GetProcessWindowStation(); //// if(hwinsta != IntPtr.Zero && processWinStation != hwinsta) //// { //// int lengthNeeded = 0; //// Win32Native.USEROBJECTFLAGS flags = new Win32Native.USEROBJECTFLAGS(); //// //// if(Win32Native.GetUserObjectInformation( hwinsta, Win32Native.UOI_FLAGS, flags, Marshal.SizeOf( flags ), ref lengthNeeded )) //// { //// if((flags.dwFlags & Win32Native.WSF_VISIBLE) == 0) //// { //// isUserNonInteractive = true; //// } //// } //// processWinStation = hwinsta; //// } //// } //// // The logic is reversed to avoid static initialization to true //// return !isUserNonInteractive; //// } //// } //// //// [ResourceExposure( ResourceScope.Machine )] //// [ResourceConsumption( ResourceScope.Machine )] //// public static string GetFolderPath( SpecialFolder folder ) //// { //// if(!Enum.IsDefined( typeof( SpecialFolder ), folder )) //// { //// throw new ArgumentException( String.Format( CultureInfo.CurrentCulture, Environment.GetResourceString( "Arg_EnumIllegalVal" ), (int)folder ) ); //// } //// //// StringBuilder sb = new StringBuilder( Path.MAX_PATH ); //// //// Win32Native.SHGetFolderPath( IntPtr.Zero, (int)folder, IntPtr.Zero, Win32Native.SHGFP_TYPE_CURRENT, sb ); //// //// String s = sb.ToString(); //// //// new FileIOPermission( FileIOPermissionAccess.PathDiscovery, s ).Demand(); //// //// return s; //// } //// //// public static string UserDomainName //// { //// get //// { //// new EnvironmentPermission( EnvironmentPermissionAccess.Read, "UserDomain" ).Demand(); //// //// byte[] sid = new byte[1024]; //// int sidLen = sid.Length; //// //// StringBuilder domainName = new StringBuilder( 1024 ); //// int domainNameLen = domainName.Capacity; //// int peUse; //// //// byte ret = Win32Native.GetUserNameEx( Win32Native.NameSamCompatible, domainName, ref domainNameLen ); //// if(ret == 1) //// { //// string samName = domainName.ToString(); //// int index = samName.IndexOf( '\\' ); //// if(index != -1) //// { //// return samName.Substring( 0, index ); //// } //// } //// //// domainNameLen = domainName.Capacity; //// //// bool success = Win32Native.LookupAccountName( null, UserName, sid, ref sidLen, domainName, ref domainNameLen, out peUse ); //// if(!success) //// { //// int errorCode = Marshal.GetLastWin32Error(); //// throw new InvalidOperationException( Win32Native.GetMessage( errorCode ) ); //// } //// //// return domainName.ToString(); //// } //// } //// //// public enum SpecialFolder //// { //// // //// // Represents the file system directory that serves as a common repository for //// // application-specific data for the current, roaming user. //// // A roaming user works on more than one computer on a network. A roaming user's //// // profile is kept on a server on the network and is loaded onto a system when the //// // user logs on. //// // //// ApplicationData = Win32Native.CSIDL_APPDATA, //// // //// // Represents the file system directory that serves as a common repository for application-specific data that //// // is used by all users. //// // //// CommonApplicationData = Win32Native.CSIDL_COMMON_APPDATA, //// // //// // Represents the file system directory that serves as a common repository for application specific data that //// // is used by the current, non-roaming user. //// // //// LocalApplicationData = Win32Native.CSIDL_LOCAL_APPDATA, //// // //// // Represents the file system directory that serves as a common repository for Internet //// // cookies. //// // //// Cookies = Win32Native.CSIDL_COOKIES, //// Desktop = Win32Native.CSIDL_DESKTOP, //// // //// // Represents the file system directory that serves as a common repository for the user's //// // favorite items. //// // //// Favorites = Win32Native.CSIDL_FAVORITES, //// // //// // Represents the file system directory that serves as a common repository for Internet //// // history items. //// // //// History = Win32Native.CSIDL_HISTORY, //// // //// // Represents the file system directory that serves as a common repository for temporary //// // Internet files. //// // //// InternetCache = Win32Native.CSIDL_INTERNET_CACHE, //// // //// // Represents the file system directory that contains //// // the user's program groups. //// // //// Programs = Win32Native.CSIDL_PROGRAMS, //// MyComputer = Win32Native.CSIDL_DRIVES, //// MyMusic = Win32Native.CSIDL_MYMUSIC, //// MyPictures = Win32Native.CSIDL_MYPICTURES, //// // //// // Represents the file system directory that contains the user's most recently used //// // documents. //// // //// Recent = Win32Native.CSIDL_RECENT, //// // //// // Represents the file system directory that contains Send To menu items. //// // //// SendTo = Win32Native.CSIDL_SENDTO, //// // //// // Represents the file system directory that contains the Start menu items. //// // //// StartMenu = Win32Native.CSIDL_STARTMENU, //// // //// // Represents the file system directory that corresponds to the user's Startup program group. The system //// // starts these programs whenever any user logs on to Windows NT, or //// // starts Windows 95 or Windows 98. //// // //// Startup = Win32Native.CSIDL_STARTUP, //// // //// // System directory. //// // //// System = Win32Native.CSIDL_SYSTEM, //// // //// // Represents the file system directory that serves as a common repository for document //// // templates. //// // //// Templates = Win32Native.CSIDL_TEMPLATES, //// // //// // Represents the file system directory used to physically store file objects on the desktop. //// // This should not be confused with the desktop folder itself, which is //// // a virtual folder. //// // //// DesktopDirectory = Win32Native.CSIDL_DESKTOPDIRECTORY, //// // //// // Represents the file system directory that serves as a common repository for documents. //// // //// Personal = Win32Native.CSIDL_PERSONAL, //// //// // "MyDocuments" is a better name than "Personal" //// MyDocuments = Win32Native.CSIDL_PERSONAL, //// // //// // Represents the program files folder. //// // //// ProgramFiles = Win32Native.CSIDL_PROGRAM_FILES, //// // //// // Represents the folder for components that are shared across applications. //// // //// CommonProgramFiles = Win32Native.CSIDL_PROGRAM_FILES_COMMON, //// } } } ================================================ FILE: Zelig/Zelig/RunTime/Framework/mscorlib/System/EventArgs.cs ================================================ // ==++== // // Copyright (c) Microsoft Corporation. All rights reserved. // // ==--== namespace System { using System; // The base class for all event classes. [Serializable] public class EventArgs { public static readonly EventArgs Empty = new EventArgs(); public EventArgs() { } } } ================================================ FILE: Zelig/Zelig/RunTime/Framework/mscorlib/System/EventHandler.cs ================================================ // ==++== // // Copyright (c) Microsoft Corporation. All rights reserved. // // ==--== namespace System { using System; [Serializable] public delegate void EventHandler( Object sender, EventArgs e ); [Serializable] public delegate void EventHandler( Object sender, TEventArgs e ) where TEventArgs : EventArgs; } ================================================ FILE: Zelig/Zelig/RunTime/Framework/mscorlib/System/Exception.cs ================================================ // ==++== // // Copyright (c) Microsoft Corporation. All rights reserved. // // ==--== /*============================================================================= ** ** Class: Exception ** ** ** Purpose: The base class for all exceptional conditions. ** ** =============================================================================*/ namespace System { using System; using System.Runtime.InteropServices; using System.Runtime.CompilerServices; using System.Runtime.Serialization; ////using System.Runtime.Versioning; ////using System.Diagnostics; ////using System.Security.Permissions; ////using System.Security; ////using System.IO; ////using System.Text; using System.Reflection; using System.Collections; using System.Globalization; ////using MethodInfo = System.Reflection.MethodInfo; ////using MethodBase = System.Reflection.MethodBase; [Serializable] public class Exception /*: ISerializable*/ { internal String m_message; private Exception m_innerException; //// private Object m_stackTrace; //// private IDictionary m_data; //// private String m_helpURL; //// private String m_className; // Needed for serialization. //// private MethodBase m_exceptionMethod; // Needed for serialization. //// private String m_exceptionMethodString; // Needed for serialization. //// private String m_stackTraceString; // Needed for serialization. //// private String m_remoteStackTraceString; //// private int m_remoteStackIndex; //// private String m_source; // Mainly used by VB. //// ////////#pragma warning disable 414 // Field is not used from managed. //////// // m_dynamicMethods is an array of System.Resolver objects, used to keep //////// // DynamicMethodDescs alive for the lifetime of the exception. We do this because //////// // the m_stackTrace field holds MethodDescs, and a DynamicMethodDesc can be destroyed //////// // unless a System.Resolver object roots it. //////// private Object m_dynamicMethods; ////////#pragma warning restore 414 public Exception() { m_message = null; //// m_stackTrace = null; //// m_dynamicMethods = null; } public Exception( String message ) { m_message = message; //// m_stackTrace = null; //// m_dynamicMethods = null; } // Creates a new Exception. All derived classes should // provide this constructor. // Note: the stack trace is not started until the exception // is thrown // public Exception( String message, Exception innerException ) { m_message = message; m_innerException = innerException; //// m_stackTrace = null; //// m_dynamicMethods = null; } //// protected Exception( SerializationInfo info, StreamingContext context ) //// { //// if(info == null) //// { //// throw new ArgumentNullException( "info" ); //// } //// //// m_message = info.GetString ( "Message" ); //// m_innerException = (Exception )(info.GetValue ( "InnerException", typeof( Exception ) )); //// m_data = (IDictionary)(info.GetValueNoThrow( "Data" , typeof( IDictionary ) )); //// m_helpURL = info.GetString ( "HelpURL" ); //// m_className = info.GetString ( "ClassName" ); //// m_exceptionMethodString = info.GetString ( "ExceptionMethod" ); //// m_stackTraceString = info.GetString ( "StackTraceString" ); //// m_remoteStackTraceString = info.GetString ( "RemoteStackTraceString" ); //// m_remoteStackIndex = info.GetInt32 ( "RemoteStackIndex" ); //// m_source = info.GetString ( "Source" ); //// //// if(m_className == null) //// { //// throw new SerializationException( Environment.GetResourceString( "Serialization_InsufficientState" ) ); //// } //// //// // If we are constructing a new exception after a cross-appdomain call... //// if(context.State == StreamingContextStates.CrossAppDomain) //// { //// // ...this new exception may get thrown. It is logically a re-throw, but //// // physically a brand-new exception. Since the stack trace is cleared //// // on a new exception, the "_remoteStackTraceString" is provided to //// // effectively import a stack trace from a "remote" exception. So, //// // move the _stackTraceString into the _remoteStackTraceString. Note //// // that if there is an existing _remoteStackTraceString, it will be //// // preserved at the head of the new string, so everything works as //// // expected. //// // Even if this exception is NOT thrown, things will still work as expected //// // because the StackTrace property returns the concatenation of the //// // _remoteStackTraceString and the _stackTraceString. //// m_remoteStackTraceString = m_remoteStackTraceString + m_stackTraceString; //// m_stackTraceString = null; //// } //// } public virtual String Message { get { //// if(m_message == null) //// { //// if(m_className == null) //// { //// m_className = GetClassName(); //// } //// //// return String.Format( CultureInfo.CurrentCulture, Environment.GetResourceString( "Exception_WasThrown" ), m_className ); //// } //// else //// { return m_message; //// } } } //// public virtual IDictionary Data //// { //// get //// { //// return GetDataInternal(); //// } //// } //// //// // This method is internal so that callers can't override which function they call. //// internal IDictionary GetDataInternal() //// { //// if(m_data == null) //// { //// if(IsImmutableAgileException( this )) //// { //// m_data = new EmptyReadOnlyDictionaryInternal(); //// } //// else //// { //// m_data = new ListDictionaryInternal(); //// } //// } //// //// return m_data; //// } //// //// [ResourceExposure( ResourceScope.None )] //// [MethodImpl( MethodImplOptions.InternalCall )] //// private static extern bool IsImmutableAgileException( Exception e ); //// //// //// [ResourceExposure( ResourceScope.None )] //// [MethodImpl( MethodImplOptions.InternalCall )] //// private extern String GetClassName(); // Retrieves the lowest exception (inner most) for the given Exception. // This will traverse exceptions using the innerException property. // public virtual Exception GetBaseException() { Exception inner = InnerException; Exception back = this; while(inner != null) { back = inner; inner = inner.InnerException; } return back; } // Returns the inner exception contained in this exception // public Exception InnerException { get { return m_innerException; } } //// [ResourceExposure( ResourceScope.None )] //// [MethodImpl( MethodImplOptions.InternalCall )] //// static extern unsafe private void* _InternalGetMethod( Object stackTrace ); //// //// static unsafe private RuntimeMethodHandle InternalGetMethod( Object stackTrace ) //// { //// return new RuntimeMethodHandle( _InternalGetMethod( stackTrace ) ); //// } //// //// //// public MethodBase TargetSite //// { //// get //// { //// return GetTargetSiteInternal(); //// } //// } //// //// //// // this function is provided as a private helper to avoid the security demand //// private MethodBase GetTargetSiteInternal() //// { //// if(m_exceptionMethod != null) //// { //// return m_exceptionMethod; //// } //// //// if(m_stackTrace == null) //// { //// return null; //// } //// //// if(m_exceptionMethodString != null) //// { //// m_exceptionMethod = GetExceptionMethodFromString(); //// } //// else //// { //// RuntimeMethodHandle method = InternalGetMethod( m_stackTrace ).GetTypicalMethodDefinition(); //// //// m_exceptionMethod = RuntimeType.GetMethodBase( method ); //// } //// //// return m_exceptionMethod; //// } //// //// // Returns the stack trace as a string. If no stack trace is //// // available, null is returned. //// public virtual String StackTrace //// { //// get //// { //// // if no stack trace, try to get one //// if(m_stackTraceString != null) //// { //// return m_remoteStackTraceString + m_stackTraceString; //// } //// //// if(m_stackTrace == null) //// { //// return m_remoteStackTraceString; //// } //// //// // Obtain the stack trace string. Note that since Environment.GetStackTrace //// // will add the path to the source file if the PDB is present and a demand //// // for PathDiscoveryPermission succeeds, we need to make sure we don't store //// // the stack trace string in the _stackTraceString member variable. //// String tempStackTraceString = Environment.GetStackTrace( this, true ); //// //// return m_remoteStackTraceString + tempStackTraceString; //// } //// } //// //// // Sets the help link for this exception. //// // This should be in a URL/URN form, such as: //// // "file:///C:/Applications/Bazzal/help.html#ErrorNum42" //// // Changed to be a read-write String and not return an exception //// public virtual String HelpLink //// { //// get //// { //// return m_helpURL; //// } //// //// set //// { //// m_helpURL = value; //// } //// } //// //// public virtual String Source //// { //// get //// { //// if(m_source == null) //// { //// StackTrace st = new StackTrace( this, true ); //// //// if(st.FrameCount > 0) //// { //// StackFrame sf = st.GetFrame( 0 ); //// MethodBase method = sf.GetMethod(); //// //// m_source = method.Module.Assembly.GetSimpleName(); //// } //// } //// //// return m_source; //// } //// //// set //// { //// m_source = value; //// } //// } public override String ToString() { return Message; //// String message = Message; //// String s; //// //// if(m_className == null) //// { //// m_className = GetClassName(); //// } //// //// if(message == null || message.Length <= 0) //// { //// s = m_className; //// } //// else //// { //// s = m_className + ": " + message; //// } //// //// if(m_innerException != null) //// { //// s = s + " ---> " + m_innerException.ToString() + Environment.NewLine + " " + Environment.GetResourceString( "Exception_EndOfInnerExceptionStack" ); //// } //// //// //// if(StackTrace != null) //// { //// s += Environment.NewLine + StackTrace; //// } //// //// return s; } //// private String GetExceptionMethodString() //// { //// MethodBase methBase = GetTargetSiteInternal(); //// if(methBase == null) //// { //// return null; //// } //// //// // Note that the newline separator is only a separator, chosen such that //// // it won't (generally) occur in a method name. This string is used //// // only for serialization of the Exception Method. //// char separator = '\n'; //// //// StringBuilder result = new StringBuilder(); //// //// if(methBase is ConstructorInfo) //// { //// RuntimeConstructorInfo rci = (RuntimeConstructorInfo)methBase; //// Type t = rci.ReflectedType; //// //// result.Append( (int)MemberTypes.Constructor ); //// result.Append( separator ); //// result.Append( rci.Name ); //// //// if(t != null) //// { //// result.Append( separator ); //// result.Append( t.Assembly.FullName ); //// result.Append( separator ); //// result.Append( t.FullName ); //// } //// //// result.Append( separator ); //// result.Append( rci.ToString() ); //// } //// else //// { //// BCLDebug.Assert( methBase is MethodInfo, "[Exception.GetExceptionMethodString]methBase is MethodInfo" ); //// //// RuntimeMethodInfo rmi = (RuntimeMethodInfo)methBase; //// Type t = rmi.DeclaringType; //// //// result.Append( (int)MemberTypes.Method ); //// result.Append( separator ); //// result.Append( rmi.Name ); //// result.Append( separator ); //// result.Append( rmi.Module.Assembly.FullName ); //// result.Append( separator ); //// if(t != null) //// { //// result.Append( t.FullName ); //// result.Append( separator ); //// } //// result.Append( rmi.ToString() ); //// } //// //// return result.ToString(); //// } //// //// private MethodBase GetExceptionMethodFromString() //// { //// BCLDebug.Assert( m_exceptionMethodString != null, "Method string cannot be NULL!" ); //// //// String[] args = m_exceptionMethodString.Split( new char[] { '\0', '\n' } ); //// if(args.Length != 5) //// { //// throw new SerializationException(); //// } //// //// SerializationInfo si = new SerializationInfo( typeof( MemberInfoSerializationHolder ), new FormatterConverter() ); //// //// si.AddValue( "MemberType" , (int)Int32.Parse( args[0], CultureInfo.InvariantCulture ), typeof( Int32 ) ); //// si.AddValue( "Name" , args[1], typeof( String ) ); //// si.AddValue( "AssemblyName", args[2], typeof( String ) ); //// si.AddValue( "ClassName" , args[3] ); //// si.AddValue( "Signature" , args[4] ); //// //// MethodBase result; //// //// StreamingContext sc = new StreamingContext( StreamingContextStates.All ); //// try //// { //// result = (MethodBase)new MemberInfoSerializationHolder( si, sc ).GetRealObject( sc ); //// } //// catch(SerializationException) //// { //// result = null; //// } //// return result; //// } //// //// [SecurityPermissionAttribute( SecurityAction.LinkDemand, Flags = SecurityPermissionFlag.SerializationFormatter )] //// public virtual void GetObjectData( SerializationInfo info, StreamingContext context ) //// { //// String tempStackTraceString = m_stackTraceString; //// //// if(info == null) //// { //// throw new ArgumentNullException( "info" ); //// } //// //// if(m_className == null) //// { //// m_className = GetClassName(); //// } //// //// if(m_stackTrace != null) //// { //// if(tempStackTraceString == null) //// { //// tempStackTraceString = Environment.GetStackTrace( this, true ); //// } //// //// if(m_exceptionMethod == null) //// { //// RuntimeMethodHandle method = InternalGetMethod( m_stackTrace ).GetTypicalMethodDefinition(); //// //// m_exceptionMethod = RuntimeType.GetMethodBase( method ); //// } //// } //// //// if(m_source == null) //// { //// m_source = Source; // Set the Source information correctly before serialization //// } //// //// info.AddValue( "ClassName" , m_className , typeof( String ) ); //// info.AddValue( "Message" , m_message , typeof( String ) ); //// info.AddValue( "Data" , m_data , typeof( IDictionary ) ); //// info.AddValue( "InnerException" , m_innerException , typeof( Exception ) ); //// info.AddValue( "HelpURL" , m_helpURL , typeof( String ) ); //// info.AddValue( "StackTraceString" , tempStackTraceString , typeof( String ) ); //// info.AddValue( "RemoteStackTraceString", m_remoteStackTraceString , typeof( String ) ); //// info.AddValue( "RemoteStackIndex" , m_remoteStackIndex , typeof( Int32 ) ); //// info.AddValue( "ExceptionMethod" , GetExceptionMethodString(), typeof( String ) ); //// info.AddValue( "Source" , m_source , typeof( String ) ); //// } //// //// // This is used by remoting to preserve the server side stack trace //// // by appending it to the message ... before the exception is rethrown //// // at the client call site. //// internal Exception PrepForRemoting() //// { //// String tmp = null; //// //// if(m_remoteStackIndex == 0) //// { //// tmp = Environment.NewLine + "Server stack trace: " + Environment.NewLine //// + StackTrace //// + Environment.NewLine + Environment.NewLine //// + "Exception rethrown at [" + m_remoteStackIndex + "]: " + Environment.NewLine; //// } //// else //// { //// tmp = StackTrace //// + Environment.NewLine + Environment.NewLine //// + "Exception rethrown at [" + m_remoteStackIndex + "]: " + Environment.NewLine; //// } //// //// m_remoteStackTraceString = tmp; //// m_remoteStackIndex++; //// return this; //// } //// //// // This is used by the runtime when re-throwing a managed exception. It will //// // copy the stack trace to _remoteStackTraceString. //// internal void InternalPreserveStackTrace() //// { //// string tmpStackTraceString = StackTrace; //// //// if(tmpStackTraceString != null && tmpStackTraceString.Length > 0) //// { //// m_remoteStackTraceString = tmpStackTraceString + Environment.NewLine; //// } //// //// m_stackTrace = null; //// m_stackTraceString = null; //// } //// //// internal virtual String InternalToString() //// { //// try //// { //// SecurityPermission sp = new SecurityPermission( SecurityPermissionFlag.ControlEvidence | SecurityPermissionFlag.ControlPolicy ); //// sp.Assert(); //// } //// catch //// { //// //under normal conditions there should be no exceptions //// //however if something wrong happens we still can call the usual ToString //// } //// return ToString(); //// } // this method is required so Object.GetType is not made virtual by the compiler public new Type GetType() { return base.GetType(); } //// internal bool IsTransient //// { //// get //// { //// return nIsTransient( m_HResult ); //// } //// } //// //// [ResourceExposure( ResourceScope.None )] //// [MethodImpl( MethodImplOptions.InternalCall )] //// private extern static bool nIsTransient( int hr ); // This piece of infrastructure exists to help avoid deadlocks // between parts of mscorlib that might throw an exception while // holding a lock that are also used by mscorlib's ResourceManager // instance. As a special case of code that may throw while holding // a lock, we also need to fix our asynchronous exceptions to use // Win32 resources as well (assuming we ever call a managed // constructor on instances of them). We should grow this set of // exception messages as we discover problems, then move the resources // involved to native code. internal enum ExceptionMessageKind { ThreadAbort = 1, ThreadInterrupted = 2, OutOfMemory = 3, } // See comment on ExceptionMessageKind //// [ResourceExposure( ResourceScope.None )] //// [MethodImpl( MethodImplOptions.InternalCall )] //// internal static extern String GetMessageFromNativeResources( ExceptionMessageKind kind ); internal static String GetMessageFromNativeResources( ExceptionMessageKind kind ) { // // BUGBUG: This needs to be implemented as an internal call. // return kind.ToString(); } } } ================================================ FILE: Zelig/Zelig/RunTime/Framework/mscorlib/System/FlagsAttribute.cs ================================================ // ==++== // // Copyright (c) Microsoft Corporation. All rights reserved. // // ==--== //////////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////////// namespace System { using System; // Custom attribute to indicate that the enum // should be treated as a bitfield (or set of flags). // An IDE may use this information to provide a richer // development experience. [Microsoft.Zelig.Internals.WellKnownType( "System_FlagsAttribute" )] [AttributeUsage( AttributeTargets.Enum, Inherited = false ), Serializable] public class FlagsAttribute : Attribute { public FlagsAttribute() { } } } ================================================ FILE: Zelig/Zelig/RunTime/Framework/mscorlib/System/FormatException.cs ================================================ // ==++== // // Copyright (c) Microsoft Corporation. All rights reserved. // // ==--== /*============================================================ ** ** Class: FormatException ** ** ** Purpose: Exception to designate an illegal argument to FormatMessage. ** ** ===========================================================*/ namespace System { using System; using System.Runtime.Serialization; [Serializable] public class FormatException : SystemException { #if EXCEPTION_STRINGS public FormatException() : base( Environment.GetResourceString( "Arg_FormatException" ) ) #else public FormatException() #endif { } public FormatException( String message ) : base( message ) { } public FormatException( String message, Exception innerException ) : base( message, innerException ) { } //// protected FormatException( SerializationInfo info, StreamingContext context ) : base( info, context ) //// { //// } } } ================================================ FILE: Zelig/Zelig/RunTime/Framework/mscorlib/System/GC.cs ================================================ // ==++== // // Copyright (c) Microsoft Corporation. All rights reserved. // // ==--== /*============================================================ ** ** Class: GC ** ** ** Purpose: Exposes features of the Garbage Collector through ** the class libraries. This is a class which cannot be ** instantiated. ** ** ===========================================================*/ namespace System { //This class only static members and doesn't require the serializable keyword. using System; ////using System.Security.Permissions; using System.Reflection; ////using System.Security; using System.Threading; using System.Runtime.CompilerServices; using System.Runtime.ConstrainedExecution; ////using System.Reflection.Cache; ////using System.Runtime.Versioning; public static class GC { //// [ResourceExposure( ResourceScope.None )] //// [MethodImpl( MethodImplOptions.InternalCall )] //// private static extern int GetGenerationWR( IntPtr handle ); //// //// [ResourceExposure( ResourceScope.None )] //// [MethodImpl( MethodImplOptions.InternalCall )] //// private static extern long nativeGetTotalMemory(); //// //// [ResourceExposure( ResourceScope.None )] //// [MethodImpl( MethodImplOptions.InternalCall )] //// private static extern void nativeCollectGeneration( int generation ); //// //// [ResourceExposure( ResourceScope.None )] //// [MethodImpl( MethodImplOptions.InternalCall )] //// private static extern int nativeGetMaxGeneration(); //// //// [ResourceExposure( ResourceScope.None )] //// [MethodImpl( MethodImplOptions.InternalCall )] //// [ReliabilityContract( Consistency.WillNotCorruptState, Cer.Success )] //// private static extern int nativeCollectionCount( int generation ); //// //// [ResourceExposure( ResourceScope.None )] //// [MethodImpl( MethodImplOptions.InternalCall )] //// internal static extern bool nativeIsServerGC(); //// //// [ResourceExposure( ResourceScope.None )] //// [MethodImpl( MethodImplOptions.InternalCall )] //// internal static extern void nativeAddMemoryPressure( UInt64 bytesAllocated ); //// //// [ResourceExposure( ResourceScope.None )] //// [MethodImpl( MethodImplOptions.InternalCall )] //// internal static extern void nativeRemoveMemoryPressure( UInt64 bytesAllocated ); //// //// [SecurityPermission( SecurityAction.LinkDemand, UnmanagedCode = true )] //// public static void AddMemoryPressure( long bytesAllocated ) //// { //// if(bytesAllocated <= 0) //// { //// throw new ArgumentOutOfRangeException( "bytesAllocated", Environment.GetResourceString( "ArgumentOutOfRange_NeedPosNum" ) ); //// } //// //// if((IntPtr.Size == 4) && (bytesAllocated > Int32.MaxValue)) //// { //// throw new ArgumentOutOfRangeException( "pressure", Environment.GetResourceString( "ArgumentOutOfRange_MustBeNonNegInt32" ) ); //// } //// //// nativeAddMemoryPressure( (ulong)bytesAllocated ); //// } //// //// [SecurityPermission( SecurityAction.LinkDemand, UnmanagedCode = true )] //// public static void RemoveMemoryPressure( long bytesAllocated ) //// { //// if(bytesAllocated <= 0) //// { //// throw new ArgumentOutOfRangeException( "bytesAllocated", Environment.GetResourceString( "ArgumentOutOfRange_NeedPosNum" ) ); //// } //// //// if((IntPtr.Size == 4) && (bytesAllocated > Int32.MaxValue)) //// { //// throw new ArgumentOutOfRangeException( "bytesAllocated", Environment.GetResourceString( "ArgumentOutOfRange_MustBeNonNegInt32" ) ); //// } //// //// nativeRemoveMemoryPressure( (ulong)bytesAllocated ); //// } //// //// //// // Returns the generation that obj is currently in. //// // //// [ResourceExposure( ResourceScope.None )] //// [MethodImpl( MethodImplOptions.InternalCall )] //// public static extern int GetGeneration( Object obj ); //// //// //// // Forces a collection of all generations from 0 through Generation. //// // //// public static void Collect( int generation ) //// { //// if(generation < 0) //// { //// throw new ArgumentOutOfRangeException( "generation", Environment.GetResourceString( "ArgumentOutOfRange_GenericPositive" ) ); //// } //// //// nativeCollectGeneration( generation ); //// } // Garbage Collect all generations. // [MethodImpl( MethodImplOptions.InternalCall )] public static extern void Collect(); //// { //// //-1 says to GC all generations. //// nativeCollectGeneration( -1 ); //// } //// [ReliabilityContract( Consistency.WillNotCorruptState, Cer.Success )] [MethodImpl( MethodImplOptions.InternalCall )] public static extern int CollectionCount( int generation ); //// { //// if(generation < 0) //// { //// throw new ArgumentOutOfRangeException( "generation", Environment.GetResourceString( "ArgumentOutOfRange_GenericPositive" ) ); //// } //// //// return nativeCollectionCount( generation ); //// //// } // This method DOES NOT DO ANYTHING in and of itself. It's used to // prevent a finalizable object from losing any outstanding references // a touch too early. The JIT is very aggressive about keeping an // object's lifetime to as small a window as possible, to the point // where a 'this' pointer isn't considered live in an instance method // unless you read a value from the instance. So for finalizable // objects that store a handle or pointer and provide a finalizer that // cleans them up, this can cause subtle races with the finalizer // thread. This isn't just about handles - it can happen with just // about any finalizable resource. // // Users should insert a call to this method near the end of a // method where they must keep an object alive for the duration of that // method, up until this method is called. Here is an example: // // "...all you really need is one object with a Finalize method, and a // second object with a Close/Dispose/Done method. Such as the following // contrived example: // // class Foo { // Stream stream = ...; // protected void Finalize() { stream.Close(); } // void Problem() { stream.MethodThatSpansGCs(); } // static void Main() { new Foo().Problem(); } // } // // // In this code, Foo will be finalized in the middle of // stream.MethodThatSpansGCs, thus closing a stream still in use." // // If we insert a call to GC.KeepAlive(this) at the end of Problem(), then // Foo doesn't get finalized and the stream says open. //// [ResourceExposure( ResourceScope.None )] [MethodImpl( MethodImplOptions.InternalCall )] //// [ReliabilityContract( Consistency.WillNotCorruptState, Cer.Success )] public static extern void KeepAlive( Object obj ); //// // Returns the generation in which wo currently resides. //// // //// public static int GetGeneration( WeakReference wo ) //// { //// int result = GetGenerationWR( wo.m_handle ); //// //// KeepAlive( wo ); //// //// return result; //// } //// //// // Returns the maximum GC generation. Currently assumes only 1 heap. //// // //// public static int MaxGeneration //// { //// get //// { //// return nativeGetMaxGeneration(); //// } //// } //// [ResourceExposure( ResourceScope.None )] [MethodImpl( MethodImplOptions.InternalCall )] public static extern void WaitForPendingFinalizers(); //// // Indicates that the system should not call the Finalize() method on //// // an object that would normally require this call. //// // Has the DynamicSecurityMethodAttribute custom attribute to prevent //// // inlining of the caller. //// [ResourceExposure( ResourceScope.None )] //// [MethodImpl( MethodImplOptions.InternalCall )] //// [ReliabilityContract( Consistency.WillNotCorruptState, Cer.Success )] //// internal static extern void nativeSuppressFinalize( Object o ); //// [ReliabilityContract( Consistency.WillNotCorruptState, Cer.Success )] [MethodImpl( MethodImplOptions.InternalCall )] public static extern void SuppressFinalize( Object obj ); //// { //// if(obj == null) //// { //// throw new ArgumentNullException( "obj" ); //// } //// //// nativeSuppressFinalize( obj ); //// } //// // Indicates that the system should call the Finalize() method on an object //// // for which SuppressFinalize has already been called. The other situation //// // where calling ReRegisterForFinalize is useful is inside a finalizer that //// // needs to resurrect itself or an object that it references. //// // Has the DynamicSecurityMethodAttribute custom attribute to prevent //// // inlining of the caller. //// [ResourceExposure( ResourceScope.None )] //// [MethodImpl( MethodImplOptions.InternalCall )] //// private static extern void nativeReRegisterForFinalize( Object o ); [MethodImpl( MethodImplOptions.InternalCall )] public static extern void ReRegisterForFinalize( Object obj ); //// { //// if(obj == null) //// { //// throw new ArgumentNullException( "obj" ); //// } //// //// nativeReRegisterForFinalize( obj ); //// } // Returns the total number of bytes currently in use by live objects in // the GC heap. This does not return the total size of the GC heap, but // only the live objects in the GC heap. // [MethodImpl( MethodImplOptions.InternalCall )] public static extern long GetTotalMemory( bool forceFullCollection ); //// { //// long size = nativeGetTotalMemory(); //// //// if(!forceFullCollection) //// { //// return size; //// } //// //// // If we force a full collection, we will run the finalizers on all //// // existing objects and do a collection until the value stabilizes. //// // The value is "stable" when either the value is within 5% of the //// // previous call to nativeGetTotalMemory, or if we have been sitting //// // here for more than x times (we don't want to loop forever here). //// int reps = 20; // Number of iterations //// long newSize = size; //// float diff; //// do //// { //// GC.WaitForPendingFinalizers(); //// GC.Collect(); //// //// size = newSize; //// newSize = nativeGetTotalMemory(); //// diff = ((float)(newSize - size)) / size; //// } while(reps-- > 0 && !(-.05 < diff && diff < .05)); //// //// return newSize; //// } //// //// [ResourceExposure( ResourceScope.None )] //// [MethodImpl( MethodImplOptions.InternalCall )] //// private static extern void SetCleanupCache(); //// //// private static ClearCacheHandler m_cacheHandler; //// //// private static readonly Object locker = new Object(); //// //// internal static event ClearCacheHandler ClearCache //// { //// add //// { //// lock(locker) //// { //// m_cacheHandler += value; //// //// SetCleanupCache(); //// } //// } //// remove //// { //// lock(locker) //// { //// m_cacheHandler -= value; //// } //// } //// } //// //// //This method is called from native code. If you update the signature, please also update //// //mscorlib.h and COMUtilNative.cpp //// internal static void FireCacheEvent() //// { //// BCLDebug.Trace( "CACHE", "Called FileCacheEvent" ); //// ClearCacheHandler handler = Interlocked.Exchange( ref m_cacheHandler, null ); //// if(handler != null) //// { //// handler( null, null ); //// } //// } } } ================================================ FILE: Zelig/Zelig/RunTime/Framework/mscorlib/System/Globalization/BaseInfoTable.cs ================================================ // ==++== // // Copyright (c) Microsoft Corporation. All rights reserved. // // ==--== namespace System.Globalization { using System; using System.Collections; using System.IO; ////using System.Runtime.Remoting; using System.Runtime.InteropServices; using System.Runtime.CompilerServices; using System.Threading; using System.Security.Permissions; ////using System.Runtime.Versioning; //////////////////////////////////////////////////////////////////////// // // Base class used to read NLS+ data tables for culture/region/calendar data // // // Data types supported in this version: // 0: WORD A WORD value. It is returend as signed int. The interpretation of sign is left to caller. // 1: String A string value. The first WORD is the size of the string. // 2: WORD[] A WORD array. The first DWORD is the size of the array, and it is followed by the DWORD values. // 3: String[] A string array. The first WORD is the size of the string array. And it is folowed by offsets to counted string values. // //////////////////////////////////////////////////////////////////////// internal abstract class BaseInfoTable { //// // The base pointer of the data table (beginning of the data file) //// unsafe internal byte* m_pDataFileStart; //// //// protected MemoryMapFile memoryMapFile = null; //// //// // The pointer to the main header //// unsafe protected CultureTableHeader* m_pCultureHeader; //// //// // The pointer to where the item data begins. //// unsafe internal byte* m_pItemData; //// //// // The total number of data items. //// internal uint m_numItem; //// //// // The size of each data item. This is the total size (in bytes) of each calendar or culture record. //// internal uint m_itemSize; //// //// internal unsafe ushort* m_pDataPool; //// //// // Where we came from //// internal bool fromAssembly; //// internal String fileName; //// //// protected bool m_valid = true; //// //// //private static String m_InternationalRegKey = "Control Panel\\International"; //// //// //////////////////////////////////////////////////////////////////////// //// // //// // Read the table and set up pointers pointing to different parts of //// // the table. //// // Parameters: //// // fromAssembly When true, we will load data table from mscorlib assemlby. //// // //// //////////////////////////////////////////////////////////////////////// //// //// [ResourceExposure( ResourceScope.Machine )] //// [ResourceConsumption( ResourceScope.Machine )] //// internal unsafe BaseInfoTable( String fileName, bool fromAssembly ) //// { //// this.fileName = fileName; //// this.fromAssembly = fromAssembly; //// InitializeBaseInfoTablePointers( fileName, fromAssembly ); //// } //// //// [ResourceExposure( ResourceScope.Machine )] //// [ResourceConsumption( ResourceScope.Machine )] //// internal unsafe void InitializeBaseInfoTablePointers( String fileName, bool fromAssembly ) //// { //// if(fromAssembly) //// { //// m_pDataFileStart = GlobalizationAssembly.GetGlobalizationResourceBytePtr( typeof( BaseInfoTable ).Assembly, fileName ); //// } //// else //// { //// this.memoryMapFile = new MemoryMapFile( fileName ); //// //// if(this.memoryMapFile.FileSize == 0) //// { //// m_valid = false; //// return; //// } //// //// this.m_pDataFileStart = this.memoryMapFile.GetBytePtr(); //// } //// EndianessHeader* pEndianHeader = (EndianessHeader*)m_pDataFileStart; //// //// // Set up pointer to the CultureTableHeader //// ////#if BIGENDIAN //// BCLDebug.Assert(pEndianHeader->beOffset != 0, "Big-Endian data is expected."); //// m_pCultureHeader = (CultureTableHeader*)(m_pDataFileStart + pEndianHeader->beOffset); ////#else //// BCLDebug.Assert( pEndianHeader->leOffset != 0, "Little-Endian data is expected." ); //// m_pCultureHeader = (CultureTableHeader*)(m_pDataFileStart + pEndianHeader->leOffset); ////#endif //// //// // Set up misc pointers and variables. //// // Different data items for calendar and culture, so they each have their own setting thingy. //// SetDataItemPointers(); //// } //// //// // //// // IsValid //// // tell if the current object is valid to use or not. note the only cases this object br invalid is //// // when we have corrupted custom culture file. //// // //// //// internal bool IsValid //// { //// get { return m_valid; } //// } //// //// public override unsafe bool Equals( Object value ) //// { //// BaseInfoTable that = value as BaseInfoTable; //// return (that != null) && //// (this.fromAssembly == that.fromAssembly && //// CultureInfo.InvariantCulture.CompareInfo.Compare( //// this.fileName, that.fileName, CompareOptions.IgnoreCase ) == 0); //// } //// //// public override int GetHashCode() //// { //// return (this.fileName.GetHashCode()); //// } //// //// //////////////////////////////////////////////////////////////////////// //// // //// // Set Data Item Pointers that are unique to calendar or culture table //// // //// //////////////////////////////////////////////////////////////////////// //// internal abstract unsafe void SetDataItemPointers(); //// //// //////////////////////////////////////////////////////////////////////// //// // //// // Read a string from the string pool using the given string offset //// // //// //////////////////////////////////////////////////////////////////////// //// internal unsafe String GetStringPoolString( uint offset ) //// { //// char* pCharValues = unchecked( (char*)(m_pDataPool + offset) ); //// // In the case of empty string, pCharValues[0] will have a size of 1, so we should check pCharValues[1] for empty string. //// if(pCharValues[1] == 0) return (String.Empty); //// return (new String( pCharValues + 1, 0, (int)pCharValues[0] )); //// } //// //// //////////////////////////////////////////////////////////////////////// //// // //// // Read a string array from the pool using the given offset //// // //// //////////////////////////////////////////////////////////////////////// //// internal unsafe String[] GetStringArray( uint iOffset ) //// { //// // If its empty return null //// if(iOffset == 0) //// return new String[0]; //// //// // The offset value is in char, and is related to the begining of string pool. //// ushort* pCount = m_pDataPool + iOffset; //// int count = (int)pCount[0]; // The number of strings in the array //// String[] values = new String[count]; //// //// // Get past count and cast to uint //// uint* pStringArray = (uint*)(pCount + 1); //// //// // Get our strings //// for(int i = 0; i < count; i++) //// values[i] = GetStringPoolString( pStringArray[i] ); //// //// return (values); //// } //// //// //////////////////////////////////////////////////////////////////////// //// // //// // Return multiple WORD field arrays values for the specified data item in the data table. //// // The result is retured as an array of int since that's what most CI/NFI/DTFI properties return. //// // //// //////////////////////////////////////////////////////////////////////// //// internal unsafe int[][] GetWordArrayArray( uint iOffset ) //// { //// // if its empty return null //// if(iOffset == 0) //// return new int[0][]; //// //// // The offset value is in char, and is related to the begining of string pool. //// // Need short* to get proper negative numbers for negative eras. //// short* pCount = (short*)(m_pDataPool + iOffset); //// int countArrays = (int)pCount[0]; // The number of word arrays in the array //// int[][] values = new int[countArrays][]; //// //// // Get past count and cast to uint to get the pointers to the word arrays //// uint* pWordArrays = (uint*)(pCount + 1); //// //// // Get our word arrays //// for(int i = 0; i < countArrays; i++) //// { //// pCount = (short*)(m_pDataPool + pWordArrays[i]); //// int count = pCount[0]; //// pCount++; // Advance past count and reuse for word pointer //// values[i] = new int[count]; //// for(int j = 0; j < count; j++) //// { //// values[i][j] = pCount[j]; //// } //// } //// //// return (values); //// } //// //// //////////////////////////////////////////////////////////////////////// //// // //// // Compare a managed string to a string pool using the given string offset. //// // Does binary comparisons. This is a bit better for perf. and reources than //// // creating a string object and making an f-call. //// // //// // Parameters //// // name: The name to be compared. //// // offset: an offset into the string table. //// // //// // Note //// // name should be in lowercase when this is called. //// // //// //////////////////////////////////////////////////////////////////////// //// internal unsafe int CompareStringToStringPoolStringBinary( String name, int offset ) //// { //// int test = 0; //// char* pCharValues = unchecked( (char*)(m_pDataPool + offset) ); //// // In the case of empty string, pCharValues[0] will have a size of 1, so we should check pCharValues[1] for empty string. //// if(pCharValues[1] == 0) //// { //// if(name.Length == 0) //// { //// return (0); //// } //// return (1); //// } //// //// for(int i = 0; (i < (int)pCharValues[0]) && (i < name.Length); i++) //// { //// BCLDebug.Assert( !(name[i] >= 'A' && name[i] <= 'Z'), "name should be in lowercase" ); //// // A little case insensitivity, for ASCII only. //// test = name[i] - ((pCharValues[i + 1] <= 'Z' && pCharValues[i + 1] >= 'A') ? //// (pCharValues[i + 1] + 'a' - 'A') : //// (pCharValues[i + 1])); //// //// if(test != 0) //// { //// break; //// } //// } //// //// return (test == 0 ? name.Length - (int)pCharValues[0] : test); //// } } } ================================================ FILE: Zelig/Zelig/RunTime/Framework/mscorlib/System/Globalization/Calendar.cs ================================================ // ==++== // // Copyright (c) Microsoft Corporation. All rights reserved. // // ==--== namespace System.Globalization { using System; using System.Runtime.CompilerServices; using System.Globalization; ////using System.Runtime.Versioning; // This abstract class represents a calendar. A calendar reckons time in // divisions such as weeks, months and years. The number, length and start of // the divisions vary in each calendar. // // Any instant in time can be represented as an n-tuple of numeric values using // a particular calendar. For example, the next vernal equinox occurs at (0.0, 0 // , 46, 8, 20, 3, 1999) in the Gregorian calendar. An implementation of // Calendar can map any DateTime value to such an n-tuple and vice versa. The // DateTimeFormat class can map between such n-tuples and a textual // representation such as "8:46 AM March 20th 1999 AD". // // Most calendars identify a year which begins the current era. There may be any // number of previous eras. The Calendar class identifies the eras as enumerated // integers where the current era (CurrentEra) has the value zero. // // For consistency, the first unit in each interval, e.g. the first month, is // assigned the value one. // The calculation of hour/minute/second is moved to Calendar from GregorianCalendar, // since most of the calendars (or all?) have the same way of calcuating hour/minute/second. [Serializable] public abstract class Calendar : ICloneable { // Number of 100ns (10E-7 second) ticks per time unit internal const long TicksPerMillisecond = 10000; internal const long TicksPerSecond = TicksPerMillisecond * 1000; internal const long TicksPerMinute = TicksPerSecond * 60; internal const long TicksPerHour = TicksPerMinute * 60; internal const long TicksPerDay = TicksPerHour * 24; // Number of milliseconds per time unit internal const int MillisPerSecond = 1000; internal const int MillisPerMinute = MillisPerSecond * 60; internal const int MillisPerHour = MillisPerMinute * 60; internal const int MillisPerDay = MillisPerHour * 24; // Number of days in a non-leap year internal const int DaysPerYear = 365; // Number of days in 4 years internal const int DaysPer4Years = DaysPerYear * 4 + 1; // Number of days in 100 years internal const int DaysPer100Years = DaysPer4Years * 25 - 1; // Number of days in 400 years internal const int DaysPer400Years = DaysPer100Years * 4 + 1; // Number of days from 1/1/0001 to 1/1/10000 internal const int DaysTo10000 = DaysPer400Years * 25 - 366; internal const long MaxMillis = (long)DaysTo10000 * MillisPerDay; // // Calendar ID Values. This is used to get data from calendar.nlp. // The order of calendar ID means the order of data items in the table. // internal const int CAL_GREGORIAN = 1; // Gregorian (localized) calendar internal const int CAL_GREGORIAN_US = 2; // Gregorian (U.S.) calendar internal const int CAL_JAPAN = 3; // Japanese Emperor Era calendar internal const int CAL_TAIWAN = 4; // Taiwan Era calendar internal const int CAL_KOREA = 5; // Korean Tangun Era calendar internal const int CAL_HIJRI = 6; // Hijri (Arabic Lunar) calendar internal const int CAL_THAI = 7; // Thai calendar internal const int CAL_HEBREW = 8; // Hebrew (Lunar) calendar internal const int CAL_GREGORIAN_ME_FRENCH = 9; // Gregorian Middle East French calendar internal const int CAL_GREGORIAN_ARABIC = 10; // Gregorian Arabic calendar internal const int CAL_GREGORIAN_XLIT_ENGLISH = 11; // Gregorian Transliterated English calendar internal const int CAL_GREGORIAN_XLIT_FRENCH = 12; internal const int CAL_JULIAN = 13; internal const int CAL_JAPANESELUNISOLAR = 14; internal const int CAL_CHINESELUNISOLAR = 15; internal const int CAL_SAKA = 16; // reserved to match Office but not implemented in our code internal const int CAL_LUNAR_ETO_CHN = 17; // reserved to match Office but not implemented in our code internal const int CAL_LUNAR_ETO_KOR = 18; // reserved to match Office but not implemented in our code internal const int CAL_LUNAR_ETO_ROKUYOU = 19; // reserved to match Office but not implemented in our code internal const int CAL_KOREANLUNISOLAR = 20; internal const int CAL_TAIWANLUNISOLAR = 21; internal const int CAL_PERSIAN = 22; internal const int CAL_UMALQURA = 23; internal int m_currentEraValue = -1; [System.Runtime.Serialization.OptionalField( VersionAdded = 2 )] private bool m_isReadOnly = false; // The minimum supported DateTime range for the calendar. public virtual DateTime MinSupportedDateTime { get { return (DateTime.MinValue); } } // The maximum supported DateTime range for the calendar. public virtual DateTime MaxSupportedDateTime { get { return (DateTime.MaxValue); } } protected Calendar() { //Do-nothing constructor. } /// // This can not be abstract, otherwise no one can create a subclass of Calendar. // internal virtual int ID { get { return (-1); } } /// // Return the Base calendar ID for calendars that didn't have defined data in culture.nlp // internal virtual int BaseCalendarID { get { return ID; } } // Returns the type of the calendar. // public virtual CalendarAlgorithmType AlgorithmType { get { return CalendarAlgorithmType.Unknown; } } //////////////////////////////////////////////////////////////////////// // // IsReadOnly // // Detect if the object is readonly. // //////////////////////////////////////////////////////////////////////// public bool IsReadOnly { get { return (m_isReadOnly); } } //////////////////////////////////////////////////////////////////////// // // Clone // // Is the implementation of IColnable. // //////////////////////////////////////////////////////////////////////// public virtual Object Clone() { object o = MemberwiseClone(); ((Calendar)o).SetReadOnlyState( false ); return (o); } //////////////////////////////////////////////////////////////////////// // // ReadOnly // // Create a cloned readonly instance or return the input one if it is // readonly. // //////////////////////////////////////////////////////////////////////// public static Calendar ReadOnly( Calendar calendar ) { if(calendar == null) { #if EXCEPTION_STRINGS throw new ArgumentNullException( "calendar" ); #else throw new ArgumentNullException(); #endif } if(calendar.IsReadOnly) { return (calendar); } Calendar clonedCalendar = (Calendar)(calendar.MemberwiseClone()); clonedCalendar.SetReadOnlyState( true ); return (clonedCalendar); } internal void VerifyWritable() { if(m_isReadOnly) { #if EXCEPTION_STRINGS throw new InvalidOperationException( Environment.GetResourceString( "InvalidOperation_ReadOnly" ) ); #else throw new InvalidOperationException(); #endif } } internal void SetReadOnlyState( bool readOnly ) { m_isReadOnly = readOnly; } //// /*=================================CurrentEraValue========================== //// **Action: This is used to convert CurretEra(0) to an appropriate era value. //// **Returns: //// **Arguments: //// **Exceptions: //// **Notes: //// ** The value is from calendar.nlp. //// ============================================================================*/ //// //// internal virtual int CurrentEraValue //// { //// get //// { //// // The following code assumes that the current era value can not be -1. //// if(m_currentEraValue == -1) //// { //// BCLDebug.Assert( BaseCalendarID > 0, "[Calendar.CurrentEraValue] Expected ID > 0" ); //// m_currentEraValue = CalendarTable.Default.ICURRENTERA( BaseCalendarID ); //// } //// return (m_currentEraValue); //// } //// } // The current era for a calendar. public const int CurrentEra = 0; internal int twoDigitYearMax = -1; internal static void CheckAddResult( long ticks, DateTime minValue, DateTime maxValue ) { if(ticks < minValue.Ticks || ticks > maxValue.Ticks) { #if EXCEPTION_STRINGS throw new ArgumentException( String.Format( CultureInfo.InvariantCulture, Environment.GetResourceString( "Argument_ResultCalendarRange" ), minValue, maxValue ) ); #else throw new ArgumentException(); #endif } } internal DateTime Add( DateTime time, double value, int scale ) { long millis = (long)(value * scale + (value >= 0 ? 0.5 : -0.5)); if(millis <= -MaxMillis || millis >= MaxMillis) { #if EXCEPTION_STRINGS throw new ArgumentOutOfRangeException( "value", Environment.GetResourceString( "ArgumentOutOfRange_AddValue" ) ); #else throw new ArgumentOutOfRangeException(); #endif } long ticks = time.Ticks + millis * TicksPerMillisecond; CheckAddResult( ticks, MinSupportedDateTime, MaxSupportedDateTime ); return (new DateTime( ticks )); } // Returns the DateTime resulting from adding the given number of // milliseconds to the specified DateTime. The result is computed by rounding // the number of milliseconds given by value to the nearest integer, // and adding that interval to the specified DateTime. The value // argument is permitted to be negative. // public virtual DateTime AddMilliseconds( DateTime time, double milliseconds ) { return (Add( time, milliseconds, 1 )); } // Returns the DateTime resulting from adding a fractional number of // days to the specified DateTime. The result is computed by rounding the // fractional number of days given by value to the nearest // millisecond, and adding that interval to the specified DateTime. The // value argument is permitted to be negative. // public virtual DateTime AddDays( DateTime time, int days ) { return (Add( time, days, MillisPerDay )); } // Returns the DateTime resulting from adding a fractional number of // hours to the specified DateTime. The result is computed by rounding the // fractional number of hours given by value to the nearest // millisecond, and adding that interval to the specified DateTime. The // value argument is permitted to be negative. // public virtual DateTime AddHours( DateTime time, int hours ) { return (Add( time, hours, MillisPerHour )); } // Returns the DateTime resulting from adding a fractional number of // minutes to the specified DateTime. The result is computed by rounding the // fractional number of minutes given by value to the nearest // millisecond, and adding that interval to the specified DateTime. The // value argument is permitted to be negative. // public virtual DateTime AddMinutes( DateTime time, int minutes ) { return (Add( time, minutes, MillisPerMinute )); } // Returns the DateTime resulting from adding the given number of // months to the specified DateTime. The result is computed by incrementing // (or decrementing) the year and month parts of the specified DateTime by // value months, and, if required, adjusting the day part of the // resulting date downwards to the last day of the resulting month in the // resulting year. The time-of-day part of the result is the same as the // time-of-day part of the specified DateTime. // // In more precise terms, considering the specified DateTime to be of the // form y / m / d + t, where y is the // year, m is the month, d is the day, and t is the // time-of-day, the result is y1 / m1 / d1 + t, // where y1 and m1 are computed by adding value months // to y and m, and d1 is the largest value less than // or equal to d that denotes a valid day in month m1 of year // y1. // public abstract DateTime AddMonths( DateTime time, int months ); // Returns the DateTime resulting from adding a number of // seconds to the specified DateTime. The result is computed by rounding the // fractional number of seconds given by value to the nearest // millisecond, and adding that interval to the specified DateTime. The // value argument is permitted to be negative. // public virtual DateTime AddSeconds( DateTime time, int seconds ) { return Add( time, seconds, MillisPerSecond ); } // Returns the DateTime resulting from adding a number of // weeks to the specified DateTime. The // value argument is permitted to be negative. // public virtual DateTime AddWeeks( DateTime time, int weeks ) { return (AddDays( time, weeks * 7 )); } // Returns the DateTime resulting from adding the given number of // years to the specified DateTime. The result is computed by incrementing // (or decrementing) the year part of the specified DateTime by value // years. If the month and day of the specified DateTime is 2/29, and if the // resulting year is not a leap year, the month and day of the resulting // DateTime becomes 2/28. Otherwise, the month, day, and time-of-day // parts of the result are the same as those of the specified DateTime. // public abstract DateTime AddYears( DateTime time, int years ); // Returns the day-of-month part of the specified DateTime. The returned // value is an integer between 1 and 31. // public abstract int GetDayOfMonth( DateTime time ); // Returns the day-of-week part of the specified DateTime. The returned value // is an integer between 0 and 6, where 0 indicates Sunday, 1 indicates // Monday, 2 indicates Tuesday, 3 indicates Wednesday, 4 indicates // Thursday, 5 indicates Friday, and 6 indicates Saturday. // public abstract DayOfWeek GetDayOfWeek( DateTime time ); // Returns the day-of-year part of the specified DateTime. The returned value // is an integer between 1 and 366. // public abstract int GetDayOfYear( DateTime time ); // Returns the number of days in the month given by the year and // month arguments. // public virtual int GetDaysInMonth( int year, int month ) { return (GetDaysInMonth( year, month, CurrentEra )); } // Returns the number of days in the month given by the year and // month arguments for the specified era. // public abstract int GetDaysInMonth( int year, int month, int era ); // Returns the number of days in the year given by the year argument for the current era. // public virtual int GetDaysInYear( int year ) { return (GetDaysInYear( year, CurrentEra )); } // Returns the number of days in the year given by the year argument for the current era. // public abstract int GetDaysInYear( int year, int era ); // Returns the era for the specified DateTime value. public abstract int GetEra( DateTime time ); /*=================================Eras========================== **Action: Get the list of era values. **Returns: The int array of the era names supported in this calendar. ** null if era is not used. **Arguments: None. **Exceptions: None. ============================================================================*/ public abstract int[] Eras { get; } // Returns the hour part of the specified DateTime. The returned value is an // integer between 0 and 23. // public virtual int GetHour( DateTime time ) { return ((int)((time.Ticks / TicksPerHour) % 24)); } // Returns the millisecond part of the specified DateTime. The returned value // is an integer between 0 and 999. // public virtual double GetMilliseconds( DateTime time ) { return (double)((time.Ticks / TicksPerMillisecond) % 1000); } // Returns the minute part of the specified DateTime. The returned value is // an integer between 0 and 59. // public virtual int GetMinute( DateTime time ) { return ((int)((time.Ticks / TicksPerMinute) % 60)); } // Returns the month part of the specified DateTime. The returned value is an // integer between 1 and 12. // public abstract int GetMonth( DateTime time ); // Returns the number of months in the specified year in the current era. public virtual int GetMonthsInYear( int year ) { return (GetMonthsInYear( year, CurrentEra )); } // Returns the number of months in the specified year and era. public abstract int GetMonthsInYear( int year, int era ); // Returns the second part of the specified DateTime. The returned value is // an integer between 0 and 59. // public virtual int GetSecond( DateTime time ) { return ((int)((time.Ticks / TicksPerSecond) % 60)); } /*=================================GetFirstDayWeekOfYear========================== **Action: Get the week of year using the FirstDay rule. **Returns: the week of year. **Arguments: ** time ** firstDayOfWeek the first day of week (0=Sunday, 1=Monday, ... 6=Saturday) **Notes: ** The CalendarWeekRule.FirstDay rule: Week 1 begins on the first day of the year. ** Assume f is the specifed firstDayOfWeek, ** and n is the day of week for January 1 of the specified year. ** Assign offset = n - f; ** Case 1: offset = 0 ** E.g. ** f=1 ** weekday 0 1 2 3 4 5 6 0 1 ** date 1/1 ** week# 1 2 ** then week of year = (GetDayOfYear(time) - 1) / 7 + 1 ** ** Case 2: offset < 0 ** e.g. ** n=1 f=3 ** weekday 0 1 2 3 4 5 6 0 ** date 1/1 ** week# 1 2 ** This means that the first week actually starts 5 days before 1/1. ** So week of year = (GetDayOfYear(time) + (7 + offset) - 1) / 7 + 1 ** Case 3: offset > 0 ** e.g. ** f=0 n=2 ** weekday 0 1 2 3 4 5 6 0 1 2 ** date 1/1 ** week# 1 2 ** This means that the first week actually starts 2 days before 1/1. ** So Week of year = (GetDayOfYear(time) + offset - 1) / 7 + 1 ============================================================================*/ internal int GetFirstDayWeekOfYear( DateTime time, int firstDayOfWeek ) { int dayOfYear = GetDayOfYear( time ) - 1; // Make the day of year to be 0-based, so that 1/1 is day 0. // Calculate the day of week for the first day of the year. // dayOfWeek - (dayOfYear % 7) is the day of week for the first day of this year. Note that // this value can be less than 0. It's fine since we are making it positive again in calculating offset. int dayForJan1 = (int)GetDayOfWeek( time ) - (dayOfYear % 7); int offset = (dayForJan1 - firstDayOfWeek + 14) % 7; BCLDebug.Assert( offset >= 0, "Calendar.GetFirstDayWeekOfYear(): offset >= 0" ); return ((dayOfYear + offset) / 7 + 1); } internal int GetWeekOfYearFullDays( DateTime time, CalendarWeekRule rule, int firstDayOfWeek, int fullDays ) { int dayForJan1; int offset; int day; int dayOfYear = GetDayOfYear( time ) - 1; // Make the day of year to be 0-based, so that 1/1 is day 0. // // Calculate the number of days between the first day of year (1/1) and the first day of the week. // This value will be a positive value from 0 ~ 6. We call this value as "offset". // // If offset is 0, it means that the 1/1 is the start of the first week. // Assume the first day of the week is Monday, it will look like this: // Sun Mon Tue Wed Thu Fri Sat // 12/31 1/1 1/2 1/3 1/4 1/5 1/6 // +--> First week starts here. // // If offset is 1, it means that the first day of the week is 1 day ahead of 1/1. // Assume the first day of the week is Monday, it will look like this: // Sun Mon Tue Wed Thu Fri Sat // 1/1 1/2 1/3 1/4 1/5 1/6 1/7 // +--> First week starts here. // // If offset is 2, it means that the first day of the week is 2 days ahead of 1/1. // Assume the first day of the week is Monday, it will look like this: // Sat Sun Mon Tue Wed Thu Fri Sat // 1/1 1/2 1/3 1/4 1/5 1/6 1/7 1/8 // +--> First week starts here. // Day of week is 0-based. // Get the day of week for 1/1. This can be derived from the day of week of the target day. // Note that we can get a negative value. It's ok since we are going to make it a positive value when calculating the offset. dayForJan1 = (int)GetDayOfWeek( time ) - (dayOfYear % 7); // Now, calucalte the offset. Substract the first day of week from the dayForJan1. And make it a positive value. offset = (firstDayOfWeek - dayForJan1 + 14) % 7; if(offset != 0 && offset >= fullDays) { // // If the offset is greater than the value of fullDays, it means that // the first week of the year starts on the week where Jan/1 falls on. // offset -= 7; } // // Calculate the day of year for specified time by taking offset into account. // day = dayOfYear - offset; if(day >= 0) { // // If the day of year value is greater than zero, get the week of year. // return (day / 7 + 1); } // // Otherwise, the specified time falls on the week of previous year. // Call this method again by passing the last day of previous year. // return (GetWeekOfYearFullDays( time.AddDays( -(dayOfYear + 1) ), rule, firstDayOfWeek, fullDays )); } // Returns the week of year for the specified DateTime. The returned value is an // integer between 1 and 53. // public virtual int GetWeekOfYear( DateTime time, CalendarWeekRule rule, DayOfWeek firstDayOfWeek ) { if((int)firstDayOfWeek < 0 || (int)firstDayOfWeek > 6) { #if EXCEPTION_STRINGS throw new ArgumentOutOfRangeException( "firstDayOfWeek", String.Format( CultureInfo.CurrentCulture, Environment.GetResourceString( "ArgumentOutOfRange_Range" ), DayOfWeek.Sunday, DayOfWeek.Saturday ) ); #else throw new ArgumentOutOfRangeException(); #endif } switch(rule) { case CalendarWeekRule.FirstDay: return (GetFirstDayWeekOfYear( time, (int)firstDayOfWeek )); case CalendarWeekRule.FirstFullWeek: return (GetWeekOfYearFullDays( time, rule, (int)firstDayOfWeek, 7 )); case CalendarWeekRule.FirstFourDayWeek: return (GetWeekOfYearFullDays( time, rule, (int)firstDayOfWeek, 4 )); } #if EXCEPTION_STRINGS throw new ArgumentOutOfRangeException( "rule", String.Format( CultureInfo.CurrentCulture, Environment.GetResourceString( "ArgumentOutOfRange_Range" ), CalendarWeekRule.FirstDay, CalendarWeekRule.FirstFourDayWeek ) ); #else throw new ArgumentOutOfRangeException(); #endif } // Returns the year part of the specified DateTime. The returned value is an // integer between 1 and 9999. // public abstract int GetYear( DateTime time ); // Checks whether a given day in the current era is a leap day. This method returns true if // the date is a leap day, or false if not. // public virtual bool IsLeapDay( int year, int month, int day ) { return (IsLeapDay( year, month, day, CurrentEra )); } // Checks whether a given day in the specified era is a leap day. This method returns true if // the date is a leap day, or false if not. // public abstract bool IsLeapDay( int year, int month, int day, int era ); // Checks whether a given month in the current era is a leap month. This method returns true if // month is a leap month, or false if not. // public virtual bool IsLeapMonth( int year, int month ) { return (IsLeapMonth( year, month, CurrentEra )); } // Checks whether a given month in the specified era is a leap month. This method returns true if // month is a leap month, or false if not. // public abstract bool IsLeapMonth( int year, int month, int era ); // Returns the leap month in a calendar year of the current era. This method returns 0 // if this calendar does not have leap month, or this year is not a leap year. // public virtual int GetLeapMonth( int year ) { return (GetLeapMonth( year, CurrentEra )); } // Returns the leap month in a calendar year of the specified era. This method returns 0 // if this calendar does not have leap month, or this year is not a leap year. // public virtual int GetLeapMonth( int year, int era ) { if(!IsLeapYear( year, era )) return 0; int monthsCount = GetMonthsInYear( year, era ); for(int month = 1; month <= monthsCount; month++) { if(IsLeapMonth( year, month, era )) return month; } return 0; } // Checks whether a given year in the current era is a leap year. This method returns true if // year is a leap year, or false if not. // public virtual bool IsLeapYear( int year ) { return (IsLeapYear( year, CurrentEra )); } // Checks whether a given year in the specified era is a leap year. This method returns true if // year is a leap year, or false if not. // public abstract bool IsLeapYear( int year, int era ); // Returns the date and time converted to a DateTime value. Throws an exception if the n-tuple is invalid. // public virtual DateTime ToDateTime( int year, int month, int day, int hour, int minute, int second, int millisecond ) { return (ToDateTime( year, month, day, hour, minute, second, millisecond, CurrentEra )); } // Returns the date and time converted to a DateTime value. Throws an exception if the n-tuple is invalid. // public abstract DateTime ToDateTime( int year, int month, int day, int hour, int minute, int second, int millisecond, int era ); internal virtual Boolean TryToDateTime( int year, int month, int day, int hour, int minute, int second, int millisecond, int era, out DateTime result ) { result = DateTime.MinValue; try { result = ToDateTime( year, month, day, hour, minute, second, millisecond, era ); return true; } catch(ArgumentException) { return false; } } internal virtual bool IsValidYear( int year, int era ) { return (year >= GetYear( MinSupportedDateTime ) && year <= GetYear( MaxSupportedDateTime )); } internal virtual bool IsValidMonth( int year, int month, int era ) { return (IsValidYear( year, era ) && month >= 1 && month <= GetMonthsInYear( year, era )); } internal virtual bool IsValidDay( int year, int month, int day, int era ) { return (IsValidMonth( year, month, era ) && day >= 1 && day <= GetDaysInMonth( year, month, era )); } //// [ResourceExposure( ResourceScope.None )] [MethodImplAttribute( MethodImplOptions.InternalCall )] internal static extern int nativeGetTwoDigitYearMax( int calID ); // Returns and assigns the maximum value to represent a two digit year. This // value is the upper boundary of a 100 year range that allows a two digit year // to be properly translated to a four digit year. For example, if 2029 is the // upper boundary, then a two digit value of 30 should be interpreted as 1930 // while a two digit value of 29 should be interpreted as 2029. In this example // , the 100 year range would be from 1930-2029. See ToFourDigitYear(). public virtual int TwoDigitYearMax { get { return (twoDigitYearMax); } set { VerifyWritable(); twoDigitYearMax = value; } } // Converts the year value to the appropriate century by using the // TwoDigitYearMax property. For example, if the TwoDigitYearMax value is 2029, // then a two digit value of 30 will get converted to 1930 while a two digit // value of 29 will get converted to 2029. public virtual int ToFourDigitYear( int year ) { if(year < 0) { throw new ArgumentOutOfRangeException( "year", Environment.GetResourceString( "ArgumentOutOfRange_NeedNonNegNum" ) ); } if(year < 100) { return ((TwoDigitYearMax / 100 - (year > TwoDigitYearMax % 100 ? 1 : 0)) * 100 + year); } // If the year value is above 100, just return the year value. Don't have to do // the TwoDigitYearMax comparison. return (year); } // Return the tick count corresponding to the given hour, minute, second. // Will check the if the parameters are valid. internal static long TimeToTicks( int hour, int minute, int second, int millisecond ) { if(hour >= 0 && hour < 24 && minute >= 0 && minute < 60 && second >= 0 && second < 60) { if(millisecond < 0 || millisecond >= MillisPerSecond) { #if EXCEPTION_STRINGS throw new ArgumentOutOfRangeException( "millisecond", String.Format( CultureInfo.InvariantCulture, Environment.GetResourceString( "ArgumentOutOfRange_Range" ), 0, MillisPerSecond - 1 ) ); #else throw new ArgumentOutOfRangeException(); #endif } return TimeSpan.TimeToTicks( hour, minute, second ) + millisecond * TicksPerMillisecond; } #if EXCEPTION_STRINGS throw new ArgumentOutOfRangeException( null, Environment.GetResourceString( "ArgumentOutOfRange_BadHourMinuteSecond" ) ); #else throw new ArgumentOutOfRangeException(); #endif } //// [ResourceExposure( ResourceScope.None )] //// [ResourceConsumption( ResourceScope.Machine, ResourceScope.Machine )] internal static int GetSystemTwoDigitYearSetting( int CalID, int defaultYearValue ) { // // Call Win32 ::GetCalendarInfo() to retrieve CAL_ITWODIGITYEARMAX value. // This function only exists after Windows 98 and Windows 2000. // int twoDigitYearMax = nativeGetTwoDigitYearMax( CalID ); if(twoDigitYearMax < 0) { twoDigitYearMax = defaultYearValue; } return (twoDigitYearMax); } } } ================================================ FILE: Zelig/Zelig/RunTime/Framework/mscorlib/System/Globalization/CalendarAlgorithmType.cs ================================================ // ==++== // // Copyright (c) Microsoft Corporation. All rights reserved. // // ==--== namespace System.Globalization { using System; public enum CalendarAlgorithmType { Unknown = 0, // This is the default value to return in the Calendar base class. SolarCalendar = 1, // Solar-base calendar, such as GregorianCalendar, jaoaneseCalendar, JulianCalendar, etc. // Solar calendars are based on the solar year and seasons. LunarCalendar = 2, // Lunar-based calendar, such as Hijri and UmAlQuraCalendar. // Lunar calendars are based on the path of the moon. The seasons are not accurately represented. LunisolarCalendar = 3 // Lunisolar-based calendar which use leap month rule, such as HebrewCalendar and Asian Lunisolar calendars. // Lunisolar calendars are based on the cycle of the moon, but consider the seasons as a secondary consideration, // so they align with the seasons as well as lunar events. } } ================================================ FILE: Zelig/Zelig/RunTime/Framework/mscorlib/System/Globalization/CalendarTable.cs ================================================ // ==++== // // Copyright (c) Microsoft Corporation. All rights reserved. // // ==--== namespace System.Globalization { ////using System.Runtime.Remoting; using System; using System.Runtime.CompilerServices; using System.Threading; ////using System.Runtime.Versioning; using System.Runtime.InteropServices; /*============================================================================= * * Calendar Data table for DateTimeFormatInfo classes. Used by System.Globalization.DateTimeFormatInfo. * ==============================================================================*/ internal class CalendarTable : BaseInfoTable { //// //// // The default instance of calendar table. We should only create one instance per app-domain. //// private static CalendarTable m_defaultInstance; //// unsafe CalendarTableData* m_calendars; //// //// [ResourceExposure( ResourceScope.Machine )] //// [ResourceConsumption( ResourceScope.Machine )] //// static CalendarTable() //// { //// m_defaultInstance = new CalendarTable( "culture.nlp", true ); //// } //// //// [ResourceExposure( ResourceScope.Machine )] //// [ResourceConsumption( ResourceScope.Machine )] //// internal CalendarTable( String fileName, bool fromAssembly ) //// : base( fileName, fromAssembly ) //// { //// // Do nothing here. //// } //// //// //////////////////////////////////////////////////////////////////////// //// // //// // Set Data Item Pointers that are unique to calendar table //// // //// //////////////////////////////////////////////////////////////////////// //// internal override unsafe void SetDataItemPointers() //// { //// m_itemSize = m_pCultureHeader->sizeCalendarItem; //// m_numItem = m_pCultureHeader->numCalendarItems; //// m_pDataPool = (ushort*)(m_pDataFileStart + m_pCultureHeader->offsetToDataPool); //// // We subtract item size because calender indices start at 1 but our table doesn't have an entry for 0 //// m_pItemData = m_pDataFileStart + m_pCultureHeader->offsetToCalendarItemData - m_itemSize; //// // Get calendar list. We subtract 1 because calender indices start at 1 but our table doesn't have an entry for 0 //// m_calendars = (CalendarTableData*)(m_pDataFileStart + m_pCultureHeader->offsetToCalendarItemData) - 1; //// } //// //// internal static CalendarTable Default //// { //// get //// { //// BCLDebug.Assert( m_defaultInstance != null, "CalendarTable.Default: default instance is not created." ); //// return (m_defaultInstance); //// } //// } //// //// internal unsafe int ICURRENTERA( int id ) //// { //// BCLDebug.Assert( id > 0 && id <= m_numItem, //// "[CalendarTable.ICURRENTERA]id out of calendar range" ); //// //// return m_calendars[id].iCurrentEra; //// } //// //// internal unsafe int IFORMATFLAGS( int id ) //// { //// BCLDebug.Assert( id > 0 && id <= m_numItem, //// "[CalendarTable.IFORMATFLAGS]id out of calendar range" ); //// //// return m_calendars[id].iFormatFlags; //// } //// //// internal unsafe String[] SDAYNAMES( int id ) //// { //// BCLDebug.Assert( id > 0 && id <= m_numItem, //// "[CalendarTable.SDAYNAMES]id out of calendar range" ); //// //// return GetStringArray( m_calendars[id].saDayNames ); //// } //// //// internal unsafe String[] SABBREVDAYNAMES( int id ) //// { //// BCLDebug.Assert( id > 0 && id <= m_numItem, //// "[CalendarTable.SABBREVDAYNAMES]id out of calendar range" ); //// //// return GetStringArray( m_calendars[id].saAbbrevDayNames ); //// } //// //// internal unsafe String[] SSUPERSHORTDAYNAMES( int id ) //// { //// BCLDebug.Assert( id > 0 && id <= m_numItem, //// "[CalendarTable.SSUPERSHORTDAYNAMES]id out of calendar range" ); //// //// return GetStringArray( m_calendars[id].saSuperShortDayNames ); //// } //// //// internal unsafe String[] SMONTHNAMES( int id ) //// { //// BCLDebug.Assert( id > 0 && id <= m_numItem, //// "[CalendarTable.SMONTHNAMES]id out of calendar range" ); //// //// return GetStringArray( m_calendars[id].saMonthNames ); //// } //// //// internal unsafe String[] SABBREVMONTHNAMES( int id ) //// { //// BCLDebug.Assert( id > 0 && id <= m_numItem, //// "[CalendarTable.SABBREVMONTHNAMES]id out of calendar range" ); //// //// return GetStringArray( m_calendars[id].saAbbrevMonthNames ); //// } //// //// internal unsafe String[] SLEAPYEARMONTHNAMES( int id ) //// { //// BCLDebug.Assert( id > 0 && id <= m_numItem, //// "[CalendarTable.SLEAPYEARMONTHNAMES]id out of calendar range" ); //// //// return GetStringArray( m_calendars[id].saLeapYearMonthNames ); //// } //// //// internal unsafe String[] SSHORTDATE( int id ) //// { //// BCLDebug.Assert( id > 0 && id <= m_numItem, //// "[CalendarTable.SSHORTDATE]id out of calendar range" ); //// //// return GetStringArray( m_calendars[id].saShortDate ); //// } //// //// internal unsafe String[] SLONGDATE( int id ) //// { //// BCLDebug.Assert( id > 0 && id <= m_numItem, //// "[CalendarTable.SLONGDATE]id out of calendar range" ); //// //// return GetStringArray( m_calendars[id].saLongDate ); //// } //// //// internal unsafe String[] SYEARMONTH( int id ) //// { //// BCLDebug.Assert( id > 0 && id <= m_numItem, //// "[CalendarTable.SYEARMONTH]id out of calendar range" ); //// //// return GetStringArray( m_calendars[id].saYearMonth ); //// } //// //// internal unsafe String SMONTHDAY( int id ) //// { //// BCLDebug.Assert( id > 0 && id <= m_numItem, //// "[CalendarTable.SMONTHDAY]id out of calendar range" ); //// //// return GetStringPoolString( m_calendars[id].sMonthDay ); //// } //// //// internal unsafe int[][] SERARANGES( int id ) //// { //// BCLDebug.Assert( id > 0 && id <= m_numItem, //// "[CalendarTable.SERARANGES]id out of calendar range" ); //// //// return GetWordArrayArray( m_calendars[id].waaEraRanges ); //// } //// //// internal unsafe String[] SERANAMES( int id ) //// { //// BCLDebug.Assert( id > 0 && id <= m_numItem, //// "[CalendarTable.SERANAMES]id out of calendar range" ); //// //// return GetStringArray( m_calendars[id].saEraNames ); //// } //// //// internal unsafe String[] SABBREVERANAMES( int id ) //// { //// BCLDebug.Assert( id > 0 && id <= m_numItem, //// "[CalendarTable.SABBREVERANAMES]id out of calendar range" ); //// //// return GetStringArray( m_calendars[id].saAbbrevEraNames ); //// } //// //// internal unsafe String[] SABBREVENGERANAMES( int id ) //// { //// BCLDebug.Assert( id > 0 && id <= m_numItem, //// "[CalendarTable.SABBREVENGERANAMES]id out of calendar range" ); //// //// return GetStringArray( m_calendars[id].saAbbrevEnglishEraNames ); //// } //// //// [ResourceExposure( ResourceScope.None )] //// [MethodImplAttribute( MethodImplOptions.InternalCall )] //// internal static extern String nativeGetEraName( int culture, int calID ); } } ================================================ FILE: Zelig/Zelig/RunTime/Framework/mscorlib/System/Globalization/CalendarWeekRule.cs ================================================ // ==++== // // Copyright (c) Microsoft Corporation. All rights reserved. // // ==--== namespace System.Globalization { using System; [Serializable] public enum CalendarWeekRule { FirstDay = 0, // Week 1 begins on the first day of the year FirstFullWeek = 1, // Week 1 begins on first FirstDayOfWeek not before the first day of the year FirstFourDayWeek = 2 // Week 1 begins on first FirstDayOfWeek such that FirstDayOfWeek+3 is not before the first day of the year }; } ================================================ FILE: Zelig/Zelig/RunTime/Framework/mscorlib/System/Globalization/CharUnicodeInfo.cs ================================================ // ==++== // // Copyright (c) Microsoft Corporation. All rights reserved. // // ==--== //////////////////////////////////////////////////////////////////////////// // // Class: CharacterInfo // // Purpose: This class implements a set of methods for retrieving // character type information. Character type information is // independent of culture and region. // // Date: August 12, 1998 // //////////////////////////////////////////////////////////////////////////// namespace System.Globalization { //This class has only static members and therefore doesn't need to be serialized. using System; using System.Threading; using System.Runtime.InteropServices; using System.Runtime.CompilerServices; using System.Reflection; ////using System.Runtime.Versioning; // Only statics, does not need to be marked with the serializable attribute public sealed class CharUnicodeInfo : System.Object { //--------------------------------------------------------------------// // Internal Information // //--------------------------------------------------------------------// // // Native methods to access the Unicode category data tables in charinfo.nlp. // internal const char HIGH_SURROGATE_START = '\ud800'; internal const char HIGH_SURROGATE_END = '\udbff'; internal const char LOW_SURROGATE_START = '\udc00'; internal const char LOW_SURROGATE_END = '\udfff'; internal const int UNICODE_CATEGORY_OFFSET = 0; internal const int BIDI_CATEGORY_OFFSET = 1; //// // The base pointer of the data table //// unsafe static byte* m_pDataTable; //// //// // The native pointer to the 12:4:4 index table of the Unicode cateogry data. //// unsafe static ushort* m_pCategoryLevel1Index; //// unsafe static byte* m_pCategoriesValue; //// //// // The native pointer to the 12:4:4 index table of the Unicode numeric data. //// // The value of this index table is an index into the real value table stored in m_pNumericValues. //// unsafe static ushort* m_pNumericLevel1Index; //// //// // The numeric value table, which is indexed by m_pNumericLevel1Index. //// // Every item contains the value for numeric value. //// // unsafe static double* m_pNumericValues; //// // To get around the IA64 alignment issue. Our double data is aligned in 8-byte boundary, but loader loads the embeded table starting //// // at 4-byte boundary. This cause a alignment issue since double is 8-byte. //// unsafe static byte* m_pNumericValues; //// //// // The digit value table, which is indexed by m_pNumericLevel1Index. It shares the same indice as m_pNumericValues. //// // Every item contains the value for decimal digit/digit value. //// unsafe static DigitValues* m_pDigitValues; //// //// internal const String UNICODE_INFO_FILE_NAME = "charinfo.nlp"; //// // The starting codepoint for Unicode plane 1. Plane 1 contains 0x010000 ~ 0x01ffff. //// internal const int UNICODE_PLANE01_START = 0x10000; //// //// //// // //// // This is the header for the native data table that we load from UNICODE_INFO_FILE_NAME. //// // //// // Excplicit layout is used here since a syntax like char[16] can not be used in sequential layout. //// [StructLayout( LayoutKind.Explicit )] //// internal unsafe struct UnicodeDataHeader //// { //// [FieldOffset( 0 )] //// internal char TableName; // WCHAR[16] //// [FieldOffset( 0x20 )] //// internal ushort version; // WORD[4] //// [FieldOffset( 0x28 )] //// internal uint OffsetToCategoriesIndex; // DWORD //// [FieldOffset( 0x2c )] //// internal uint OffsetToCategoriesValue; // DWORD //// [FieldOffset( 0x30 )] //// internal uint OffsetToNumbericIndex; // DWORD //// [FieldOffset( 0x34 )] //// internal uint OffsetToDigitValue; // DWORD //// [FieldOffset( 0x38 )] //// internal uint OffsetToNumbericValue; // DWORD //// //// } //// //// // NOTE: It's important to specify pack size here, since the size of the structure is 2 bytes. Otherwise, //// // the default pack size will be 4. //// //// [StructLayout( LayoutKind.Sequential, Pack = 2 )] //// internal struct DigitValues //// { //// internal sbyte decimalDigit; //// internal sbyte digit; //// } //// //// //// //We need to allocate the underlying table that provides us with the information that we //// //use. We allocate this once in the class initializer and then we don't need to worry //// //about it again. //// // //// [ResourceExposure( ResourceScope.None )] //// [ResourceConsumption( ResourceScope.Process, ResourceScope.Process )] //// unsafe static CharUnicodeInfo() //// { //// m_pDataTable = GlobalizationAssembly.GetGlobalizationResourceBytePtr( typeof( CharUnicodeInfo ).Assembly, UNICODE_INFO_FILE_NAME ); //// UnicodeDataHeader* mainHeader = (UnicodeDataHeader*)m_pDataTable; //// //// // Set up the native pointer to different part of the tables. //// m_pCategoryLevel1Index = (ushort*)(m_pDataTable + mainHeader->OffsetToCategoriesIndex); //// m_pCategoriesValue = (byte*)(m_pDataTable + mainHeader->OffsetToCategoriesValue); //// m_pNumericLevel1Index = (ushort*)(m_pDataTable + mainHeader->OffsetToNumbericIndex); //// m_pNumericValues = (byte*)(m_pDataTable + mainHeader->OffsetToNumbericValue); //// m_pDigitValues = (DigitValues*)(m_pDataTable + mainHeader->OffsetToDigitValue); //// //// // Go to native side to make sure the native CharacterInfoTable pointer in the native side is initialized. //// nativeInitTable( m_pDataTable ); //// } //// //// //// //////////////////////////////////////////////////////////////////////// //// // //// // Define a private ctor so that compiler won't generate a default public ctor for us. //// // //// //////////////////////////////////////////////////////////////////////// //// private CharUnicodeInfo() //// { //// } //// //// //// //////////////////////////////////////////////////////////////////////// //// // //// // Actions: //// // Convert the BMP character or surrogate pointed by index to a UTF32 value. //// // This is similar to Char.ConvertToUTF32, but the difference is that //// // it does not throw exceptions when invalid surrogate characters are passed in. //// // //// // WARNING: since it doesn't throw an exception it CAN return a value //// // in the surrogate range D800-DFFF, which are not legal unicode values. //// // //// //////////////////////////////////////////////////////////////////////// //// //// internal static int InternalConvertToUtf32( String s, int index ) //// { //// BCLDebug.Assert( s != null, "s != null" ); //// BCLDebug.Assert( index >= 0 && index < s.Length, "index < s.Length" ); //// if(index < s.Length - 1) //// { //// int temp1 = (int)s[index] - HIGH_SURROGATE_START; //// if(temp1 >= 0 && temp1 <= 0x3ff) //// { //// int temp2 = (int)s[index + 1] - LOW_SURROGATE_START; //// if(temp2 >= 0 && temp2 <= 0x3ff) //// { //// // Convert the surrogate to UTF32 and get the result. //// return ((temp1 * 0x400) + temp2 + UNICODE_PLANE01_START); //// } //// } //// } //// return ((int)s[index]); //// } //// //// //////////////////////////////////////////////////////////////////////// //// // //// // Convert a character or a surrogate pair starting at index of string s //// // to UTF32 value. //// // //// // Parameters: //// // s The string //// // index The starting index. It can point to a BMP character or //// // a surrogate pair. //// // len The length of the string. //// // charLength [out] If the index points to a BMP char, charLength //// // will be 1. If the index points to a surrogate pair, //// // charLength will be 2. //// // //// // WARNING: since it doesn't throw an exception it CAN return a value //// // in the surrogate range D800-DFFF, which are not legal unicode values. //// // //// // Returns: //// // The UTF32 value //// // //// //////////////////////////////////////////////////////////////////////// //// //// internal static int InternalConvertToUtf32( String s, int index, out int charLength ) //// { //// BCLDebug.Assert( s != null, "s != null" ); //// BCLDebug.Assert( s.Length > 0, "s.Length > 0" ); //// BCLDebug.Assert( index >= 0 && index < s.Length, "index >= 0 && index < s.Length" ); //// charLength = 1; //// if(index < s.Length - 1) //// { //// int temp1 = (int)s[index] - HIGH_SURROGATE_START; //// if(temp1 >= 0 && temp1 <= 0x3ff) //// { //// int temp2 = (int)s[index + 1] - LOW_SURROGATE_START; //// if(temp2 >= 0 && temp2 <= 0x3ff) //// { //// // Convert the surrogate to UTF32 and get the result. //// charLength++; //// return ((temp1 * 0x400) + temp2 + UNICODE_PLANE01_START); //// } //// } //// } //// return ((int)s[index]); //// } //// //// //////////////////////////////////////////////////////////////////////// //// // //// // IsWhiteSpace //// // //// // Determines if the given character is a white space character. //// // //// //////////////////////////////////////////////////////////////////////// //// //// internal static bool IsWhiteSpace( String s, int index ) //// { //// BCLDebug.Assert( s != null, "s!=null" ); //// BCLDebug.Assert( index >= 0 && index < s.Length, "index >= 0 && index < s.Length" ); //// //// UnicodeCategory uc = GetUnicodeCategory( s, index ); //// // In Unicode 3.0, U+2028 is the only character which is under the category "LineSeparator". //// // And U+2029 is th eonly character which is under the category "ParagraphSeparator". //// switch(uc) //// { //// case (UnicodeCategory.SpaceSeparator): //// case (UnicodeCategory.LineSeparator): //// case (UnicodeCategory.ParagraphSeparator): //// return (true); //// } //// return (false); //// } //// //// //// internal static bool IsWhiteSpace( char c ) //// { //// UnicodeCategory uc = GetUnicodeCategory( c ); //// // In Unicode 3.0, U+2028 is the only character which is under the category "LineSeparator". //// // And U+2029 is th eonly character which is under the category "ParagraphSeparator". //// switch(uc) //// { //// case (UnicodeCategory.SpaceSeparator): //// case (UnicodeCategory.LineSeparator): //// case (UnicodeCategory.ParagraphSeparator): //// return (true); //// } //// //// return (false); //// } //// //// // //// // This is called by the public char and string, index versions //// // //// // Note that for ch in the range D800-DFFF we just treat it as any other non-numeric character //// // //// internal unsafe static double InternalGetNumericValue( int ch ) //// { //// BCLDebug.Assert( ch >= 0 && ch <= 0x10ffff, "ch is not in valid Unicode range." ); //// // Get the level 2 item from the highest 12 bit (8 - 19) of ch. //// ushort index = m_pNumericLevel1Index[ch >> 8]; //// // Get the level 2 WORD offset from the 4 - 7 bit of ch. This provides the base offset of the level 3 table. //// // The offset is referred to an float item in m_pNumericFloatData. //// // Note that & has the lower precedence than addition, so don't forget the parathesis. //// index = m_pNumericLevel1Index[index + ((ch >> 4) & 0x000f)]; //// byte* pBytePtr = (byte*)&(m_pNumericLevel1Index[index]); //// // Get the result from the 0 -3 bit of ch. //// return (((double*)m_pNumericValues)[pBytePtr[(ch & 0x000f)]]); //// } //// //// // //// // This is called by the public char and string, index versions //// // //// // Note that for ch in the range D800-DFFF we just treat it as any other non-numeric character //// // //// internal unsafe static DigitValues* InternalGetDigitValues( int ch ) //// { //// BCLDebug.Assert( ch >= 0 && ch <= 0x10ffff, "ch is not in valid Unicode range." ); //// // Get the level 2 item from the highest 12 bit (8 - 19) of ch. //// ushort index = m_pNumericLevel1Index[ch >> 8]; //// // Get the level 2 WORD offset from the 4 - 7 bit of ch. This provides the base offset of the level 3 table. //// // The offset is referred to an float item in m_pNumericFloatData. //// // Note that & has the lower precedence than addition, so don't forget the parathesis. //// index = m_pNumericLevel1Index[index + ((ch >> 4) & 0x000f)]; //// byte* pBytePtr = (byte*)&(m_pNumericLevel1Index[index]); //// // Get the result from the 0 -3 bit of ch. //// return &(m_pDigitValues[pBytePtr[(ch & 0x000f)]]); //// } //// //// //// internal unsafe static sbyte InternalGetDecimalDigitValue( int ch ) //// { //// return (InternalGetDigitValues( ch )->decimalDigit); //// } //// //// internal unsafe static sbyte InternalGetDigitValue( int ch ) //// { //// return (InternalGetDigitValues( ch )->digit); //// } //// //// //// //////////////////////////////////////////////////////////////////////// //// // //// //Returns the numeric value associated with the character c. If the character is a fraction, //// // the return value will not be an integer. If the character does not have a numeric value, the return value is -1. //// // //// //Returns: //// // the numeric value for the specified Unicode character. If the character does not have a numeric value, the return value is -1. //// //Arguments: //// // ch a Unicode character //// //Exceptions: //// // ArgumentNullException //// // ArgumentOutOfRangeException //// // //// //////////////////////////////////////////////////////////////////////// //// //// //// public static double GetNumericValue( char ch ) //// { //// return (InternalGetNumericValue( ch )); //// } //// //// //// public static double GetNumericValue( String s, int index ) //// { //// if(s == null) //// { //// throw new ArgumentNullException( "s" ); //// } //// if(index < 0 || index >= s.Length) //// { //// throw new ArgumentOutOfRangeException( "index", Environment.GetResourceString( "ArgumentOutOfRange_Index" ) ); //// } //// return (InternalGetNumericValue( InternalConvertToUtf32( s, index ) )); //// //// } //// //// //////////////////////////////////////////////////////////////////////// //// // //// //Returns the decimal digit value associated with the character c. //// // //// // The value should be from 0 ~ 9. //// // If the character does not have a numeric value, the return value is -1. //// // From Unicode.org: Decimal Digits. Digits that can be used to form decimal-radix numbers. //// //Returns: //// // the decimal digit value for the specified Unicode character. If the character does not have a decimal digit value, the return value is -1. //// //Arguments: //// // ch a Unicode character //// //Exceptions: //// // ArgumentNullException //// // ArgumentOutOfRangeException //// // //// //////////////////////////////////////////////////////////////////////// //// //// //// public static int GetDecimalDigitValue( char ch ) //// { //// return (InternalGetDecimalDigitValue( ch )); //// } //// //// //// public static int GetDecimalDigitValue( String s, int index ) //// { //// if(s == null) //// { //// throw new ArgumentNullException( "s" ); //// } //// if(index < 0 || index >= s.Length) //// { //// throw new ArgumentOutOfRangeException( "index", Environment.GetResourceString( "ArgumentOutOfRange_Index" ) ); //// } //// //// return (InternalGetDecimalDigitValue( InternalConvertToUtf32( s, index ) )); //// } //// //// //////////////////////////////////////////////////////////////////////// //// // //// //Action: Returns the digit value associated with the character c. //// // If the character does not have a numeric value, the return value is -1. //// // From Unicode.org: If the character represents a digit, not necessarily a decimal digit, //// // the value is here. This covers digits which do not form decimal radix forms, such as the compatibility superscript digits. //// // //// // An example is: U+2460 IRCLED DIGIT ONE. This character has digit value 1, but does not have associcated decimal digit value. //// // //// //Returns: //// // the digit value for the specified Unicode character. If the character does not have a digit value, the return value is -1. //// //Arguments: //// // ch a Unicode character //// //Exceptions: //// // ArgumentNullException //// // ArgumentOutOfRangeException //// // //// //////////////////////////////////////////////////////////////////////// //// //// //// public static int GetDigitValue( char ch ) //// { //// return (InternalGetDigitValue( ch )); //// } //// //// //// public static int GetDigitValue( String s, int index ) //// { //// if(s == null) //// { //// throw new ArgumentNullException( "s" ); //// } //// if(index < 0 || index >= s.Length) //// { //// throw new ArgumentOutOfRangeException( "index", Environment.GetResourceString( "ArgumentOutOfRange_Index" ) ); //// } //// return (InternalGetDigitValue( InternalConvertToUtf32( s, index ) )); //// } //// //// public static UnicodeCategory GetUnicodeCategory( char ch ) //// { //// return (InternalGetUnicodeCategory( ch )); //// } //// //// public static UnicodeCategory GetUnicodeCategory( String s, int index ) //// { //// if(s == null) //// throw new ArgumentNullException( "s" ); //// if(((uint)index) >= ((uint)s.Length)) //// { //// throw new ArgumentOutOfRangeException( "index" ); //// } //// return InternalGetUnicodeCategory( s, index ); //// } //// //// internal unsafe static UnicodeCategory InternalGetUnicodeCategory( int ch ) //// { //// return ((UnicodeCategory)InternalGetCategoryValue( ch, UNICODE_CATEGORY_OFFSET )); //// } //// //// //////////////////////////////////////////////////////////////////////// //// // //// //Action: Returns the Unicode Category property for the character c. //// //Returns: //// // an value in UnicodeCategory enum //// //Arguments: //// // ch a Unicode character //// //Exceptions: //// // None //// // //// //Note that this API will return values for D800-DF00 surrogate halves. //// // //// //////////////////////////////////////////////////////////////////////// //// //// internal unsafe static byte InternalGetCategoryValue( int ch, int offset ) //// { //// BCLDebug.Assert( ch >= 0 && ch <= 0x10ffff, "ch is not in valid Unicode range." ); //// // Get the level 2 item from the highest 12 bit (8 - 19) of ch. //// ushort index = m_pCategoryLevel1Index[ch >> 8]; //// // Get the level 2 WORD offset from the 4 - 7 bit of ch. This provides the base offset of the level 3 table. //// // Note that & has the lower precedence than addition, so don't forget the parathesis. //// index = m_pCategoryLevel1Index[index + ((ch >> 4) & 0x000f)]; //// byte* pBytePtr = (byte*)&(m_pCategoryLevel1Index[index]); //// // Get the result from the 0 -3 bit of ch. //// byte valueIndex = pBytePtr[(ch & 0x000f)]; //// byte uc = m_pCategoriesValue[valueIndex * 2 + offset]; //// // //// // Make sure that OtherNotAssigned is the last category in UnicodeCategory. //// // If that changes, change the following assertion as well. //// // //// //BCLDebug.Assert(uc >= 0 && uc <= UnicodeCategory.OtherNotAssigned, "Table returns incorrect Unicode category"); //// return (uc); //// } //// //// // internal static BidiCategory GetBidiCategory(char ch) { //// // return ((BidiCategory)InternalGetCategoryValue(c, BIDI_CATEGORY_OFFSET)); //// // } //// //// internal static BidiCategory GetBidiCategory( String s, int index ) //// { //// if(s == null) //// throw new ArgumentNullException( "s" ); //// if(((uint)index) >= ((uint)s.Length)) //// { //// throw new ArgumentOutOfRangeException( "index" ); //// } //// return ((BidiCategory)InternalGetCategoryValue( InternalConvertToUtf32( s, index ), BIDI_CATEGORY_OFFSET )); //// } //// //// //////////////////////////////////////////////////////////////////////// //// // //// //Action: Returns the Unicode Category property for the character c. //// //Returns: //// // an value in UnicodeCategory enum //// //Arguments: //// // value a Unicode String //// // index Index for the specified string. //// //Exceptions: //// // None //// // //// //////////////////////////////////////////////////////////////////////// //// //// internal static UnicodeCategory InternalGetUnicodeCategory( String value, int index ) //// { //// BCLDebug.Assert( value != null, "value can not be null" ); //// BCLDebug.Assert( index < value.Length, "index < value.Length" ); //// //// return (InternalGetUnicodeCategory( InternalConvertToUtf32( value, index ) )); //// } //// //// //////////////////////////////////////////////////////////////////////// //// // //// // Get the Unicode category of the character starting at index. If the character is in BMP, charLength will return 1. //// // If the character is a valid surrogate pair, charLength will return 2. //// // //// //////////////////////////////////////////////////////////////////////// //// //// internal static UnicodeCategory InternalGetUnicodeCategory( String str, int index, out int charLength ) //// { //// BCLDebug.Assert( str != null, "str can not be null" ); //// BCLDebug.Assert( str.Length > 0, "str.Length > 0" ); ; //// BCLDebug.Assert( index >= 0 && index < str.Length, "index >= 0 && index < str.Length" ); //// //// return (InternalGetUnicodeCategory( InternalConvertToUtf32( str, index, out charLength ) )); //// } //// //// internal static bool IsCombiningCategory( UnicodeCategory uc ) //// { //// BCLDebug.Assert( uc >= 0, "uc >= 0" ); //// return ( //// uc == UnicodeCategory.NonSpacingMark || //// uc == UnicodeCategory.SpacingCombiningMark || //// uc == UnicodeCategory.EnclosingMark //// ); //// } //// //// [ResourceExposure( ResourceScope.Process )] //// [MethodImplAttribute( MethodImplOptions.InternalCall )] //// private unsafe static extern void nativeInitTable( byte* bytePtr ); } } ================================================ FILE: Zelig/Zelig/RunTime/Framework/mscorlib/System/Globalization/CompareInfo.cs ================================================ // ==++== // // Copyright (c) Microsoft Corporation. All rights reserved. // // ==--== //////////////////////////////////////////////////////////////////////////// // // Class: CompareInfo // // // Purpose: This class implements a set of methods for comparing // strings. // // Date: August 12, 1998 // //////////////////////////////////////////////////////////////////////////// namespace System.Globalization { // // We're dependent on the m_pSortingTable getting created when an instance of the // class is initialized (through a call to InitializeCompareInfo). When in // native, we assume that the table has already been allocated. we may decide // to delay-allocate any of the tables (as we may do for US English)// // System.Globalization.SortKey also uses the m_pSortingTables. Currently the only // way to get a SortKey is to call through CompareInfo, which means that the table // has already been initialized. If this invariant changes, SortKey's constructor // needs to call InitializedSortingTable (which can safely be called multiple times // for the same locale.) // using System; using System.Collections; using System.Reflection; using System.Runtime.Serialization; using System.Runtime.CompilerServices; using System.Runtime.ConstrainedExecution; ////using System.Threading; ////using System.Security.Permissions; using System.Runtime.InteropServices; ////using System.Runtime.Versioning; ////using Microsoft.Win32; // // Options can be used during string comparison. // // Native implementation (COMNlsInfo.cpp & SortingTable.cpp) relies on the values of these, // If you change the values below, be sure to change the values in native part as well. // [Flags] [Serializable] public enum CompareOptions { None = 0x00000000, IgnoreCase = 0x00000001, IgnoreNonSpace = 0x00000002, IgnoreSymbols = 0x00000004, IgnoreKanaType = 0x00000008, // ignore kanatype IgnoreWidth = 0x00000010, // ignore width OrdinalIgnoreCase = 0x10000000, // This flag can not be used with other flags. StringSort = 0x20000000, // use string sort method Ordinal = 0x40000000, // This flag can not be used with other flags. // StopOnNull = 0x10000000, // StopOnNull is defined in SortingTable.h, but we didn't enable this option here. // Do not use this value for other flags accidentally. } [Serializable] public class CompareInfo /*: IDeserializationCallback*/ { // Mask used to check if IndexOf()/LastIndexOf()/IsPrefix()/IsPostfix() has the right flags. private const CompareOptions ValidIndexMaskOffFlags = ~(CompareOptions.IgnoreCase | CompareOptions.IgnoreSymbols | CompareOptions.IgnoreNonSpace | CompareOptions.IgnoreWidth | CompareOptions.IgnoreKanaType); // Mask used to check if Compare() has the right flags. private const CompareOptions ValidCompareMaskOffFlags = ~(CompareOptions.IgnoreCase | CompareOptions.IgnoreSymbols | CompareOptions.IgnoreNonSpace | CompareOptions.IgnoreWidth | CompareOptions.IgnoreKanaType | CompareOptions.StringSort); // Mask used to check if GetHashCodeOfString() has the right flags. private const CompareOptions ValidHashCodeOfStringMaskOffFlags = ~(CompareOptions.IgnoreCase | CompareOptions.IgnoreSymbols | CompareOptions.IgnoreNonSpace | CompareOptions.IgnoreWidth | CompareOptions.IgnoreKanaType); //// [ResourceExposure( ResourceScope.Process )] //// [MethodImpl( MethodImplOptions.InternalCall )] //// unsafe internal static extern byte[] nativeCreateSortKey( void* pSortingFile, String pString, int dwFlags, int win32LCID ); //// //// [ResourceExposure( ResourceScope.None )] //// [MethodImpl( MethodImplOptions.InternalCall )] //// unsafe internal static extern int nativeGetGlobalizedHashCode( void* pSortingFile, String pString, int dwFlags, int win32LCID ); //// //// [ResourceExposure( ResourceScope.None )] //// [MethodImpl( MethodImplOptions.InternalCall )] //// unsafe internal static extern bool nativeIsSortable( void* pSortingFile, String pString ); //// //// // //// [ResourceExposure( ResourceScope.None )] //// [MethodImpl( MethodImplOptions.InternalCall )] //// internal static extern int nativeCompareString( int lcid, string string1, int offset1, int length1, //// string string2, int offset2, int length2, int flags ); //// //// // Private object for locking instead of locking on a public type for SQL reliability work. //// private static Object s_InternalSyncObject; //// //// private static Object InternalSyncObject //// { //// get //// { //// if(s_InternalSyncObject == null) //// { //// Object o = new Object(); //// //// Interlocked.CompareExchange( ref s_InternalSyncObject, o, null ); //// } //// //// return s_InternalSyncObject; //// } //// } //// //// /*=================================GetCompareInfo========================== //// **Action: Get the CompareInfo constructed from the data table in the specified assembly for the specified culture. //// ** The purpose of this method is to provide versioning for CompareInfo tables. //// ** If you pass Assembly which contains different sorting table, you will sort your strings using the data //// ** in the assembly. //// **Returns: The CompareInfo for the specified culture. //// **Arguments: //// ** culture the ID of the culture //// ** assembly the assembly which contains the sorting table. //// **Exceptions: //// ** ArugmentNullException when the assembly is null //// ** ArgumentException if culture is invalid. //// ============================================================================*/ //// //// /* The design goal here is that we can still provide version even when the underlying algorithm for CompareInfo //// is totally changed in the future. //// In the case that the algorithm for CompareInfo is changed, we can use this method to //// provide the old algorithm for the old tables. The idea is to change the implementation for GetCompareInfo() //// to something like: //// 1. Check the ID of the assembly. //// 2. If the assembly needs old code, create an instance of the old CompareInfo class. The name of CompareInfo //// will be like CompareInfoVersion1 and extends from CompareInfo. //// 3. Otherwise, create an instance of the current CompareInfo. //// The CompareInfo ctor always provides the implementation for the current data table. //// */ //// //// //// public static CompareInfo GetCompareInfo( int culture, Assembly assembly ) //// { //// // Parameter checking. //// if(assembly == null) //// { //// throw new ArgumentNullException( "assembly" ); //// } //// //// if(CultureTableRecord.IsCustomCultureId( culture )) //// { //// // Customized culture cannot be created by the LCID. //// throw new ArgumentException( Environment.GetResourceString( "Argument_CustomCultureCannotBePassedByNumber", "culture" ) ); //// } //// //// if(assembly != typeof( Object ).Module.Assembly) //// { //// throw new ArgumentException( Environment.GetResourceString( "Argument_OnlyMscorlib" ) ); //// } //// //// // culture is verified to see if it is valid when CompareInfo is constructed. //// //// GlobalizationAssembly ga = GlobalizationAssembly.GetGlobalizationAssembly( assembly ); //// //// Object compInfo = ga.compareInfoCache[culture]; //// if(compInfo == null) //// { //// lock(InternalSyncObject) //// { //// // //// // Re-check again to make sure that no one has created the CompareInfo for the culture yet before the current //// // thread enters this sync block. //// // //// if((compInfo = ga.compareInfoCache[culture]) == null) //// { //// compInfo = new CompareInfo( ga, culture ); //// //// System.Threading.Thread.MemoryBarrier(); //// ga.compareInfoCache[culture] = compInfo; //// } //// } //// } //// //// return (CompareInfo)compInfo; //// } //// //// //// // //// // GetCompareInfoByName get CompareInfo object using the name. it is the shared code //// // between GetCompareInfo(name) and GetCompareInfo(name, assembly) //// // //// //// private const int TraditionalChineseCultureId = 0x7C04; //// private const int HongKongCultureId = 0x0C04; //// //// private static CompareInfo GetCompareInfoByName( string name, Assembly assembly ) //// { //// CultureInfo cultureInfo = CultureInfo.GetCultureInfo( name ); //// if(cultureInfo.IsNeutralCulture && !CultureTableRecord.IsCustomCultureId( cultureInfo.cultureID )) //// { //// // When requesting CompareInfo with name we always retun a specific (non neutral) one even //// // the input name is neutral. this to keep compatibility with Everett. //// // "passing "en" we'll get "en-US" with 0x409 LCID //// if(cultureInfo.cultureID == TraditionalChineseCultureId) //// { //// cultureInfo = CultureInfo.GetCultureInfo( HongKongCultureId ); //// } //// else //// { //// cultureInfo = CultureInfo.GetCultureInfo( cultureInfo.CompareInfoId ); //// } //// } //// //// CompareInfo compareInfo; //// //// if(assembly != null) //// { //// compareInfo = GetCompareInfo( cultureInfo.CompareInfoId, assembly ); //// } //// else //// { //// compareInfo = GetCompareInfo( cultureInfo.CompareInfoId ); //// } //// //// // Compare info name is known by the cultureInfo //// compareInfo.m_name = cultureInfo.SortName; //// //// return compareInfo; //// } //// //// //// /*=================================GetCompareInfo========================== //// **Action: Get the CompareInfo constructed from the data table in the specified assembly for the specified culture. //// ** The purpose of this method is to provide version for CompareInfo tables. //// **Returns: The CompareInfo for the specified culture. //// **Arguments: //// ** name the name of the culture //// ** assembly the assembly which contains the sorting table. //// **Exceptions: //// ** ArugmentNullException when the assembly is null //// ** ArgumentException if name is invalid. //// ============================================================================*/ //// //// public static CompareInfo GetCompareInfo( String name, Assembly assembly ) //// { //// if(name == null || assembly == null) //// { //// throw new ArgumentNullException( name == null ? "name" : "assembly" ); //// } //// //// if(assembly != typeof( Object ).Module.Assembly) //// { //// throw new ArgumentException( Environment.GetResourceString( "Argument_OnlyMscorlib" ) ); //// } //// //// return GetCompareInfoByName( name, assembly ); //// } //// //// /*=================================GetCompareInfo========================== //// **Action: Get the CompareInfo for the specified culture. //// ** This method is provided for ease of integration with NLS-based software. //// **Returns: The CompareInfo for the specified culture. //// **Arguments: //// ** culture the ID of the culture. //// **Exceptions: //// ** ArgumentException if culture is invalid. //// **Notes: //// ** We optimize in the default case. We don't go thru the GlobalizationAssembly hashtable. //// ** Instead, we access the m_defaultInstance directly. //// ============================================================================*/ //// //// public static CompareInfo GetCompareInfo( int culture ) //// { //// if(CultureTableRecord.IsCustomCultureId( culture )) //// { //// // Customized culture cannot be created by the LCID. //// throw new ArgumentException( Environment.GetResourceString( "Argument_CustomCultureCannotBePassedByNumber", "culture" ) ); //// } //// //// // culture is verified to see if it is valid when CompareInfo is constructed. //// Object compInfo = GlobalizationAssembly.DefaultInstance.compareInfoCache[culture]; //// if(compInfo == null) //// { //// lock(InternalSyncObject) //// { //// // //// // Re-check again to make sure that no one has created the CompareInfo for the culture yet before the current //// // thread enters this sync block. //// // //// if((compInfo = GlobalizationAssembly.DefaultInstance.compareInfoCache[culture]) == null) //// { //// compInfo = new CompareInfo( GlobalizationAssembly.DefaultInstance, culture ); //// //// System.Threading.Thread.MemoryBarrier(); //// GlobalizationAssembly.DefaultInstance.compareInfoCache[culture] = compInfo; //// } //// } //// } //// return (CompareInfo)compInfo; //// } //// //// /*=================================GetCompareInfo========================== //// **Action: Get the CompareInfo for the specified culture. //// **Returns: The CompareInfo for the specified culture. //// **Arguments: //// ** name the name of the culture. //// **Exceptions: //// ** ArgumentException if name is invalid. //// ============================================================================*/ //// //// public static CompareInfo GetCompareInfo( String name ) //// { //// if(name == null) //// { //// throw new ArgumentNullException( "name" ); //// } //// //// return GetCompareInfoByName( name, null ); //// } //// //// public static bool IsSortable( char ch ) //// { //// return (IsSortable( ch.ToString() )); //// } //// //// public static bool IsSortable( String text ) //// { //// if(text == null) //// { //// // A null param is invalid here. //// throw new ArgumentNullException( "text" ); //// } //// //// if(text.Length == 0) //// { //// // A zero length string is not invalid, but it is also not sortable. //// return false; //// } //// //// unsafe //// { //// return nativeIsSortable( CultureInfo.InvariantCulture.CompareInfo.m_pSortingTable, text ); //// } //// } #region Serialization //// // the following fields are defined to keep the compatibility with Everett. //// // don't change/remove the names/types of these fields. //// private int win32LCID; // mapped sort culture id of this instance //// private int culture; // the culture ID used to create this instance. //// //// [OnDeserializing] //// private void OnDeserializing( StreamingContext ctx ) //// { //// this.culture = -1; //// this.m_sortingLCID = -1; //// } //// //// [ResourceExposure( ResourceScope.None )] //// [ResourceConsumption( ResourceScope.Process, ResourceScope.Process )] //// private unsafe void OnDeserialized() //// { //// BCLDebug.Assert( this.culture >= 0, "[CompareInfo.OnDeserialized] - culture >= 0" ); //// //// // Get the Win32 LCID used to create NativeCompareInfo, which only takes Win32 LCID. //// if(m_sortingLCID <= 0) //// { //// m_sortingLCID = GetSortingLCID( this.culture ); //// } //// //// if(m_pSortingTable == null && !IsSynthetic) //// { //// m_pSortingTable = InitializeCompareInfo( GlobalizationAssembly.DefaultInstance.pNativeGlobalizationAssembly, this.m_sortingLCID ); //// } //// //// BCLDebug.Assert( IsSynthetic || m_pSortingTable != null, "m_pSortingTable != null" ); //// // m_name is intialized later if it not exist in the serialization stream //// } //// //// //// [OnDeserialized] //// private void OnDeserialized( StreamingContext ctx ) //// { //// OnDeserialized(); //// } //// //// [OnSerializing] //// private void OnSerializing( StreamingContext ctx ) //// { //// win32LCID = m_sortingLCID; //// } #endregion Serialization //// ///////////////////////////----- Name -----///////////////////////////////// //// // //// // Returns the name of the culture (well actually, of the sort). //// // Very important for providing a non-LCID way of identifying //// // what the sort is. //// // //// //////////////////////////////////////////////////////////////////////// //// //// public virtual String Name //// { //// get //// { //// if(m_name == null) //// { //// m_name = CultureInfo.GetCultureInfo( culture ).SortName; //// } //// //// return (m_name); //// } //// } //// //// internal void SetName( string name ) //// { //// m_name = name; //// } //// //// internal static void ClearDefaultAssemblyCache() //// { //// lock(InternalSyncObject) //// { //// GlobalizationAssembly.DefaultInstance.compareInfoCache = new Hashtable( 4 ); //// } //// } //// //// //// internal CultureTableRecord CultureTableRecord //// { //// get //// { //// if(m_cultureTableRecord == null) //// { //// m_cultureTableRecord = CultureInfo.GetCultureInfo( this.m_sortingLCID ).m_cultureTableRecord; //// } //// //// return m_cultureTableRecord; //// } //// } //// //// // //// private bool IsSynthetic //// { //// get //// { //// return CultureTableRecord.IsSynthetic; //// } //// } //// //// // //// // pSortingTable is a 32-bit pointer value pointing to a native C++ SortingTable object. //// // //// [NonSerialized] //// unsafe internal void* m_pSortingTable; //// [NonSerialized] //// private int m_sortingLCID; // mapped sort culture id of this instance //// [NonSerialized] //// private CultureTableRecord m_cultureTableRecord; //// //// private String m_name = null; // The name of the culture of this instance //// //// //// //// //////////////////////////////////////////////////////////////////////// //// // //// // CompareInfo Constructor //// // //// // //// //////////////////////////////////////////////////////////////////////// //// //// //// // Constructs an instance that most closely corresponds to the NLS locale //// // identifier. //// [ResourceExposure( ResourceScope.None )] //// [ResourceConsumption( ResourceScope.Process, ResourceScope.Process )] //// internal unsafe CompareInfo( GlobalizationAssembly ga, int culture ) //// { //// if(culture < 0) //// { //// throw new ArgumentOutOfRangeException( "culture", Environment.GetResourceString( "ArgumentOutOfRange_NeedPosNum" ) ); //// } //// //// // Get the Win32 LCID used to create NativeCompareInfo, which only takes Win32 LCID. //// this.m_sortingLCID = GetSortingLCID( culture ); //// //// // If version support is enabled, InitializeCompareInfo should use ga instead of getting the default //// // instance. //// //// // Call to the native side to create/get the corresponding native C++ SortingTable for this culture. //// // The returned value is a 32-bit pointer to the native C++ SortingTable instance. //// // We cache this pointer so that we can call methods of the SortingTable directly. //// if(!IsSynthetic) //// { //// m_pSortingTable = InitializeCompareInfo( GlobalizationAssembly.DefaultInstance.pNativeGlobalizationAssembly, this.m_sortingLCID ); //// } //// //// // Since this.m_sortingLCID can be different from the passed-in culture in the case of neutral cultures, store the culture ID in a different place. //// this.culture = culture; //// } //// //// //// internal int GetSortingLCID( int culture ) //// { //// int sortingLCID = 0; //// // //// // Verify that this is a valid culture. //// // //// CultureInfo cultureObj = CultureInfo.GetCultureInfo( culture ); //// //// // We do the following because the native C++ SortingTable is based on the //// // WIN32 LCID. It doesn't work for neutral cultures liek 0x0009. So we convert culture //// // to a Win32 LCID here. //// //// // Get Sort ID from culture. This will affect the result of string comparison. //// sortingLCID = cultureObj.CompareInfoId; //// //// int sortID = CultureInfo.GetSortID( culture ); //// if(sortID != 0) //// { //// // Need to verify if the Sort ID is valid. //// if(!cultureObj.m_cultureTableRecord.IsValidSortID( sortID )) //// { //// throw new ArgumentException( String.Format( CultureInfo.CurrentCulture, Environment.GetResourceString( "Argument_CultureNotSupported" ), culture ), "culture" ); //// } //// //// // This is an alterinative sort LCID. Hey man, don't forget to take your SORTID with you. //// sortingLCID |= sortID << 16; //// } //// //// return sortingLCID; //// //// } //// //// // //// // These flags is used in the native Win32. so we need to map the managed options to those flags //// //// private const int NORM_IGNORECASE = 0x00000001; // Ignores case. //// private const int NORM_IGNOREKANATYPE = 0x00010000; // Does not differentiate between Hiragana and Katakana characters. Corresponding Hiragana and Katakana will compare as equal. //// private const int NORM_IGNORENONSPACE = 0x00000002; // Ignores nonspacing. This flag also removes Japanese accent characters. //// private const int NORM_IGNORESYMBOLS = 0x00000004; // Ignores symbols. //// private const int NORM_IGNOREWIDTH = 0x00020000; // Does not differentiate between a single-byte character and the same character as a double-byte character. //// private const int SORT_STRINGSORT = 0x00001000; // Treats punctuation the same as symbols. //// //// internal static int GetNativeCompareFlags( CompareOptions options ) //// { //// int nativeCompareFlags = 0; //// //// if((options & CompareOptions.IgnoreCase ) != 0) { nativeCompareFlags |= NORM_IGNORECASE ; } //// if((options & CompareOptions.IgnoreKanaType) != 0) { nativeCompareFlags |= NORM_IGNOREKANATYPE; } //// if((options & CompareOptions.IgnoreNonSpace) != 0) { nativeCompareFlags |= NORM_IGNORENONSPACE; } //// if((options & CompareOptions.IgnoreSymbols ) != 0) { nativeCompareFlags |= NORM_IGNORESYMBOLS ; } //// if((options & CompareOptions.IgnoreWidth ) != 0) { nativeCompareFlags |= NORM_IGNOREWIDTH ; } //// if((options & CompareOptions.StringSort ) != 0) { nativeCompareFlags |= SORT_STRINGSORT ; } //// //// return nativeCompareFlags; //// } //////////////////////////////////////////////////////////////////////// // // Compare // // Compares the two strings with the given options. Returns 0 if the // two strings are equal, a number less than 0 if string1 is less // than string2, and a number greater than 0 if string1 is greater // than string2. // //////////////////////////////////////////////////////////////////////// public virtual int Compare( String string1, String string2 ) { return Compare( string1, string2, CompareOptions.None ); } public unsafe virtual int Compare( String string1, String string2, CompareOptions options ) { if(options == CompareOptions.OrdinalIgnoreCase) { return String.Compare( string1, string2, StringComparison.OrdinalIgnoreCase ); } // Verify the options before we do any real comparison. if((options & CompareOptions.Ordinal) != 0) { if(options == CompareOptions.Ordinal) { //Our paradigm is that null sorts less than any other string and //that two nulls sort as equal. if(string1 == null) { if(string2 == null) { return (0); // Equal } return (-1); // null < non-null } if(string2 == null) { return (1); // non-null > null } return String.nativeCompareOrdinal( string1, string2, false ); } else { #if EXCEPTION_STRINGS throw new ArgumentException( Environment.GetResourceString( "Argument_CompareOptionOrdinal" ), "options" ); #else throw new ArgumentException(); #endif } } throw new NotImplementedException(); //// if((options & ValidCompareMaskOffFlags) != 0) //// { //// throw new ArgumentException( Environment.GetResourceString( "Argument_InvalidFlag" ), "options" ); //// } //// //// //Our paradigm is that null sorts less than any other string and //// //that two nulls sort as equal. //// if(string1 == null) //// { //// if(string2 == null) //// { //// return (0); // Equal //// } //// //// return (-1); // null < non-null //// } //// //// if(string2 == null) //// { //// return (1); // non-null > null //// } //// //// // //// if(IsSynthetic) //// { //// if(options == CompareOptions.Ordinal) //// { //// return Compare( CultureInfo.InvariantCulture.CompareInfo.m_pSortingTable, this.m_sortingLCID, string1, string2, options ); //// } //// //// return nativeCompareString( m_sortingLCID, string1, 0, string1.Length, string2, 0, string2.Length, GetNativeCompareFlags( options ) ); //// } //// //// return (Compare( m_pSortingTable, this.m_sortingLCID, string1, string2, options )); } //// // This native method will check the parameters and validate them accordingly. //// // COMNlsInfo::Compare //// [ResourceExposure( ResourceScope.None )] //// [MethodImpl( MethodImplOptions.InternalCall )] //// unsafe private static extern int Compare( void* pSortingTable, int sortingLCID, String string1, String string2, CompareOptions options ); //// //// //// //////////////////////////////////////////////////////////////////////// //// // //// // Compare //// // //// // Compares the specified regions of the two strings with the given //// // options. //// // Returns 0 if the two strings are equal, a number less than 0 if //// // string1 is less than string2, and a number greater than 0 if //// // string1 is greater than string2. //// // //// //////////////////////////////////////////////////////////////////////// //// //// //// public unsafe virtual int Compare( String string1, int offset1, int length1, String string2, int offset2, int length2 ) //// { //// return Compare( string1, offset1, length1, //// string2, offset2, length2, 0 ); //// } //// //// //// public unsafe virtual int Compare( String string1, int offset1, //// String string2, int offset2, CompareOptions options ) //// { //// return Compare( string1, offset1, string1 == null ? 0 : string1.Length - offset1, //// string2, offset2, string2 == null ? 0 : string2.Length - offset2, options ); //// } //// //// //// public unsafe virtual int Compare( String string1, int offset1, //// String string2, int offset2 ) //// { //// return Compare( string1, offset1, string2, offset2, 0 ); //// } //// //// //// public unsafe virtual int Compare( String string1, int offset1, int length1, //// String string2, int offset2, int length2, CompareOptions options ) //// { //// if(options == CompareOptions.OrdinalIgnoreCase) //// { //// int result = String.Compare( string1, offset1, //// string2, offset2, length1 < length2 ? length1 : length2, StringComparison.OrdinalIgnoreCase ); //// //// if((length1 != length2) && result == 0) //// { //// return (length1 > length2 ? 1 : -1); //// } //// //// return (result); //// } //// //// // Verify inputs //// if(length1 < 0 || length2 < 0) //// { //// throw new ArgumentOutOfRangeException( (length1 < 0) ? "length1" : "length2", Environment.GetResourceString( "ArgumentOutOfRange_NeedPosNum" ) ); //// } //// //// if(offset1 < 0 || offset2 < 0) //// { //// throw new ArgumentOutOfRangeException( (offset1 < 0) ? "offset1" : "offset2", Environment.GetResourceString( "ArgumentOutOfRange_NeedPosNum" ) ); //// } //// //// if(offset1 > (string1 == null ? 0 : string1.Length) - length1) //// { //// throw new ArgumentOutOfRangeException( "string1", Environment.GetResourceString( "ArgumentOutOfRange_OffsetLength" ) ); //// } //// //// if(offset2 > (string2 == null ? 0 : string2.Length) - length2) //// { //// throw new ArgumentOutOfRangeException( "string2", Environment.GetResourceString( "ArgumentOutOfRange_OffsetLength" ) ); //// } //// //// if((options & CompareOptions.Ordinal) != 0) //// { //// if(options == CompareOptions.Ordinal) //// { //// // //// // Check for the null case. //// // //// if(string1 == null) //// { //// if(string2 == null) //// { //// return (0); //// } //// return (-1); //// } //// if(string2 == null) //// { //// return (1); //// } //// //// int result = String.nativeCompareOrdinalEx( string1, offset1, string2, offset2, (length1 < length2 ? length1 : length2) ); //// if((length1 != length2) && result == 0) //// { //// return (length1 > length2 ? 1 : -1); //// } //// return (result); //// } //// else //// { //// throw new ArgumentException( Environment.GetResourceString( "Argument_CompareOptionOrdinal" ), "options" ); //// } //// } //// //// if((options & ValidCompareMaskOffFlags) != 0) //// { //// throw new ArgumentException( Environment.GetResourceString( "Argument_InvalidFlag" ), "options" ); //// } //// //// // //// // Check for the null case. //// // //// if(string1 == null) //// { //// if(string2 == null) //// { //// return (0); //// } //// return (-1); //// } //// //// if(string2 == null) //// { //// return (1); //// } //// //// // //// if(IsSynthetic) //// { //// if(options == CompareOptions.Ordinal) //// { //// return CompareRegion( //// CultureInfo.InvariantCulture.CompareInfo.m_pSortingTable, //// this.m_sortingLCID, //// string1, //// offset1, //// length1, //// string2, //// offset2, //// length2, //// options ); //// } //// //// return nativeCompareString( m_sortingLCID, string1, offset1, length1, string2, offset2, length2, GetNativeCompareFlags( options ) ); //// } //// //// // Call native code to do comparison //// return (CompareRegion( m_pSortingTable, this.m_sortingLCID, string1, offset1, length1, string2, offset2, length2, options )); //// } //// //// // This native method will check the parameters and validate them accordingly. //// // Native method: COMNlsInfo::CompareRegion //// [ResourceExposure( ResourceScope.None )] //// [MethodImpl( MethodImplOptions.InternalCall )] //// unsafe private static extern int CompareRegion( void* pSortingTable, int sortingLCID, String string1, int offset1, int length1, String string2, int offset2, int length2, CompareOptions options ); //// //// [NonSerialized] //// static int fFindNLSStringSupported; // Defaults to 0 -- means valid, or not yet checked //// //// private static unsafe int FindNLSStringWrap( int lcid, int flags, string src, int start, int cchSrc, string value, int cchValue ) //// { //// int retval = -1; //// //// fixed(char* lpStringSource = src) //// { //// fixed(char* lpStringValue = value) //// { //// if(1 == fFindNLSStringSupported) //// { //// // Already verified the API is present, so just use it. //// retval = Win32Native.FindNLSString( lcid, flags, &lpStringSource[start], cchSrc, lpStringValue, cchValue, IntPtr.Zero ); //// } //// else //// { //// try //// { //// // Call the API once with a handler (in case it is not there) //// retval = Win32Native.FindNLSString( lcid, flags, &lpStringSource[start], cchSrc, lpStringValue, cchValue, IntPtr.Zero ); //// fFindNLSStringSupported = 1; //// } //// catch(System.EntryPointNotFoundException) //// { //// // Unable to find the method, so we will fall back to the old behavior. Return -2 //// // so the caller knows this happeneed. //// retval = fFindNLSStringSupported = -2; //// } //// } //// } //// } //// //// return (retval); //// } //// //// private bool SyntheticIsPrefix( string source, int start, int length, string prefix, int nativeCompareFlags ) //// { //// BCLDebug.Assert( start + length <= source.Length, "[CompareInfo.SyntheticIsPrefix] invalid parameters." ); //// //// if(fFindNLSStringSupported >= 0) //// { //// int retval = FindNLSStringWrap( m_sortingLCID, nativeCompareFlags | Win32Native.FIND_STARTSWITH, source, start, length, prefix, prefix.Length ); //// if(retval >= -1) //// { //// return (retval != -1); //// } //// } //// //// for(int i = 1; i <= length; i++) //// { //// if(nativeCompareString( m_sortingLCID, prefix, 0, prefix.Length, source, start, i, nativeCompareFlags ) == 0) { return true; } //// } //// //// return false; //// } //// //// // Returns the index of the substring if found one. otherwise it returns -1 //// private int SyntheticIsSuffix( string source, int end, int length, string suffix, int nativeCompareFlags ) //// { //// BCLDebug.Assert( end < source.Length && (end + 1 >= length), "[CompareInfo.SyntheticIsSuffix] invalid parameters." ); //// //// if(fFindNLSStringSupported >= 0) //// { //// int retval = FindNLSStringWrap( m_sortingLCID, nativeCompareFlags | Win32Native.FIND_ENDSWITH, source, 0, length, suffix, suffix.Length ); //// if(retval >= -1) //// { //// return (retval); //// } //// } //// //// for(int i = 0; i < length; i++) //// { //// if(nativeCompareString( m_sortingLCID, suffix, 0, suffix.Length, source, end - i, i + 1, nativeCompareFlags ) == 0) { return end - i; } //// } //// //// return -1; //// } //// //// private int SyntheticIndexOf( string source, string value, int start, int length, int nativeCompareFlags ) //// { //// BCLDebug.Assert( start + length <= source.Length, "[CompareInfo.SyntheticIndexOf] invalid parameters." ); //// //// if(fFindNLSStringSupported >= 0) //// { //// int retval = FindNLSStringWrap( m_sortingLCID, nativeCompareFlags | Win32Native.FIND_FROMSTART, source, start, length, value, value.Length ); //// if(retval >= -1) //// { //// return (retval); //// } //// } //// //// for(int i = 0; i < length; i++) //// { //// if(SyntheticIsPrefix( source, start + i, length - i, value, nativeCompareFlags )) { return start + i; } //// } //// //// return -1; //// } //// //// private int SyntheticLastIndexOf( string source, string value, int end, int length, int nativeCompareFlags ) //// { //// BCLDebug.Assert( end + 1 >= length, "[CompareInfo.SyntheticLastIndexOf] invalid parameters." ); //// //// if(fFindNLSStringSupported >= 0) //// { //// int retval = FindNLSStringWrap( m_sortingLCID, nativeCompareFlags | Win32Native.FIND_FROMEND, source, end - length + 1, length, value, value.Length ); //// if(retval >= -1) //// { //// return (retval); //// } //// } //// //// for(int i = 0; i < length; i++) //// { //// int index = SyntheticIsSuffix( source, end - i, length - i, value, nativeCompareFlags ); //// if(index >= 0) { return index; } //// } //// //// return -1; //// } //////////////////////////////////////////////////////////////////////// // // IsPrefix // // Determines whether prefix is a prefix of string. If prefix equals // String.Empty, true is returned. // //////////////////////////////////////////////////////////////////////// public unsafe virtual bool IsPrefix( String source, String prefix, CompareOptions options ) { if(source == null || prefix == null) { #if EXCEPTION_STRINGS throw new ArgumentNullException( (source == null ? "source" : "prefix"), Environment.GetResourceString( "ArgumentNull_String" ) ); #else throw new ArgumentNullException(); #endif } int prefixLen = prefix.Length; if(prefixLen == 0) { return (true); } if(options == CompareOptions.OrdinalIgnoreCase) { return source.StartsWith( prefix, StringComparison.OrdinalIgnoreCase ); } if((options & ValidIndexMaskOffFlags) != 0 && (options != CompareOptions.Ordinal)) { #if EXCEPTION_STRINGS throw new ArgumentException( Environment.GetResourceString( "Argument_InvalidFlag" ), "options" ); #else throw new ArgumentException(); #endif } //// // //// if(IsSynthetic) //// { //// if(options == CompareOptions.Ordinal) //// { //// return nativeIsPrefix( CultureInfo.InvariantCulture.CompareInfo.m_pSortingTable, this.m_sortingLCID, source, prefix, options ); //// } //// //// return SyntheticIsPrefix( source, 0, source.Length, prefix, GetNativeCompareFlags( options ) ); //// } //// //// return (nativeIsPrefix( m_pSortingTable, this.m_sortingLCID, source, prefix, options )); throw new NotSupportedException(); } //// [ResourceExposure( ResourceScope.None )] [MethodImpl( MethodImplOptions.InternalCall )] unsafe private static extern bool nativeIsPrefix( void* pSortingTable, int sortingLCID, String source, String prefix, CompareOptions options ); public virtual bool IsPrefix( String source, String prefix ) { return (IsPrefix( source, prefix, 0 )); } //////////////////////////////////////////////////////////////////////// // // IsSuffix // // Determines whether suffix is a suffix of string. If suffix equals // String.Empty, true is returned. // //////////////////////////////////////////////////////////////////////// public unsafe virtual bool IsSuffix( String source, String suffix, CompareOptions options ) { if(source == null || suffix == null) { #if EXCEPTION_STRINGS throw new ArgumentNullException( (source == null ? "source" : "suffix"), Environment.GetResourceString( "ArgumentNull_String" ) ); #else throw new ArgumentNullException(); #endif } int suffixLen = suffix.Length; if(suffixLen == 0) { return (true); } if(options == CompareOptions.OrdinalIgnoreCase) { return source.EndsWith( suffix, StringComparison.OrdinalIgnoreCase ); } if((options & ValidIndexMaskOffFlags) != 0 && (options != CompareOptions.Ordinal)) { #if EXCEPTION_STRINGS throw new ArgumentException( Environment.GetResourceString( "Argument_InvalidFlag" ), "options" ); #else throw new ArgumentException(); #endif } //// // //// if(IsSynthetic) //// { //// if(options == CompareOptions.Ordinal) //// { //// return nativeIsSuffix( CultureInfo.InvariantCulture.CompareInfo.m_pSortingTable, this.m_sortingLCID, source, suffix, options ); //// } //// return SyntheticIsSuffix( source, source.Length - 1, source.Length, suffix, GetNativeCompareFlags( options ) ) >= 0; //// } //// //// return (nativeIsSuffix( m_pSortingTable, this.m_sortingLCID, source, suffix, options )); throw new NotSupportedException(); } public virtual bool IsSuffix( String source, String suffix ) { return (IsSuffix( source, suffix, 0 )); } //// [ResourceExposure( ResourceScope.None )] //// [MethodImpl( MethodImplOptions.InternalCall )] //// private static unsafe extern bool nativeIsSuffix( void* pSortingTable, int sortingLCID, String source, String prefix, CompareOptions options ); //////////////////////////////////////////////////////////////////////// // // IndexOf // // Returns the first index where value is found in string. The // search starts from startIndex and ends at endIndex. Returns -1 if // the specified value is not found. If value equals String.Empty, // startIndex is returned. Throws IndexOutOfRange if startIndex or // endIndex is less than zero or greater than the length of string. // Throws ArgumentException if value is null. // //////////////////////////////////////////////////////////////////////// public unsafe virtual int IndexOf( String source, char value ) { if(source == null) { #if EXCEPTION_STRINGS throw new ArgumentNullException( "source" ); #else throw new ArgumentNullException(); #endif } return IndexOf( source, value, 0, source.Length, CompareOptions.None ); } public unsafe virtual int IndexOf( String source, String value ) { if(source == null) { #if EXCEPTION_STRINGS throw new ArgumentNullException( "source" ); #else throw new ArgumentNullException(); #endif } return IndexOf( source, value, 0, source.Length, CompareOptions.None ); } public unsafe virtual int IndexOf( String source, char value, CompareOptions options ) { if(source == null) { #if EXCEPTION_STRINGS throw new ArgumentNullException( "source" ); #else throw new ArgumentNullException(); #endif } return IndexOf( source, value, 0, source.Length, options ); } public unsafe virtual int IndexOf( String source, String value, CompareOptions options ) { if(source == null) { #if EXCEPTION_STRINGS throw new ArgumentNullException( "source" ); #else throw new ArgumentNullException(); #endif } return IndexOf( source, value, 0, source.Length, options ); } public unsafe virtual int IndexOf( String source, char value, int startIndex ) { if(source == null) { #if EXCEPTION_STRINGS throw new ArgumentNullException( "source" ); #else throw new ArgumentNullException(); #endif } return IndexOf( source, value, startIndex, source.Length - startIndex, CompareOptions.None ); } public unsafe virtual int IndexOf( String source, String value, int startIndex ) { if(source == null) { #if EXCEPTION_STRINGS throw new ArgumentNullException( "source" ); #else throw new ArgumentNullException(); #endif } return IndexOf( source, value, startIndex, source.Length - startIndex, CompareOptions.None ); } public unsafe virtual int IndexOf( String source, char value, int startIndex, CompareOptions options ) { if(source == null) { #if EXCEPTION_STRINGS throw new ArgumentNullException( "source" ); #else throw new ArgumentNullException(); #endif } return IndexOf( source, value, startIndex, source.Length - startIndex, options ); } public unsafe virtual int IndexOf( String source, String value, int startIndex, CompareOptions options ) { if(source == null) { #if EXCEPTION_STRINGS throw new ArgumentNullException( "source" ); #else throw new ArgumentNullException(); #endif } return IndexOf( source, value, startIndex, source.Length - startIndex, options ); } public unsafe virtual int IndexOf( String source, char value, int startIndex, int count ) { return IndexOf( source, value, startIndex, count, CompareOptions.None ); } public unsafe virtual int IndexOf( String source, String value, int startIndex, int count ) { return IndexOf( source, value, startIndex, count, CompareOptions.None ); } //// [ResourceExposure( ResourceScope.None )] //// [ResourceConsumption( ResourceScope.Process, ResourceScope.Process )] public unsafe virtual int IndexOf( String source, char value, int startIndex, int count, CompareOptions options ) { // Validate inputs if(source == null) { #if EXCEPTION_STRINGS throw new ArgumentNullException( "source" ); #else throw new ArgumentNullException(); #endif } if(startIndex < 0 || startIndex > source.Length) { #if EXCEPTION_STRINGS throw new ArgumentOutOfRangeException( "startIndex", Environment.GetResourceString( "ArgumentOutOfRange_Index" ) ); #else throw new ArgumentOutOfRangeException(); #endif } if(count < 0 || startIndex > source.Length - count) { #if EXCEPTION_STRINGS throw new ArgumentOutOfRangeException( "count", Environment.GetResourceString( "ArgumentOutOfRange_Count" ) ); #else throw new ArgumentOutOfRangeException(); #endif } //// if(options == CompareOptions.OrdinalIgnoreCase) //// { //// return TextInfo.nativeIndexOfCharOrdinalIgnoreCase( //// TextInfo.InvariantNativeTextInfo, //// source, //// value, //// startIndex, //// count ); //// } //// //// // Validate CompareOptions //// // Ordinal can't be selected with other flags //// if((options & ValidIndexMaskOffFlags) != 0 && (options != CompareOptions.Ordinal)) //// { //// throw new ArgumentException( Environment.GetResourceString( "Argument_InvalidFlag" ), "options" ); //// } //// //// // //// if(IsSynthetic) //// { //// if(options == CompareOptions.Ordinal) //// { //// return IndexOfChar( //// CultureInfo.InvariantCulture.CompareInfo.m_pSortingTable, //// this.m_sortingLCID, //// source, //// value, //// startIndex, //// count, //// (int)options ); //// } //// return SyntheticIndexOf( source, new String( value, 1 ), startIndex, count, GetNativeCompareFlags( options ) ); //// } //// //// return IndexOfChar( m_pSortingTable, this.m_sortingLCID, source, value, startIndex, count, (int)options ); throw new NotSupportedException(); } public unsafe virtual int IndexOf( String source, String value, int startIndex, int count, CompareOptions options ) { // Validate inputs if(source == null) { #if EXCEPTION_STRINGS throw new ArgumentNullException( "source" ); #else throw new ArgumentNullException(); #endif } if(value == null) { #if EXCEPTION_STRINGS throw new ArgumentNullException( "value" ); #else throw new ArgumentNullException(); #endif } if(startIndex > source.Length) { #if EXCEPTION_STRINGS throw new ArgumentOutOfRangeException( "startIndex", Environment.GetResourceString( "ArgumentOutOfRange_Index" ) ); #else throw new ArgumentOutOfRangeException(); #endif } // In Everett we used to return -1 for empty string even if startIndex is negative number so we keeping same behavior here. // We return 0 if both source and value are empty strings for Everett compatibility too. if(source.Length == 0) { if(value.Length == 0) { return 0; } return -1; } if(startIndex < 0) { #if EXCEPTION_STRINGS throw new ArgumentOutOfRangeException( "startIndex", Environment.GetResourceString( "ArgumentOutOfRange_Index" ) ); #else throw new ArgumentOutOfRangeException(); #endif } if(count < 0 || startIndex > source.Length - count) { #if EXCEPTION_STRINGS throw new ArgumentOutOfRangeException( "count", Environment.GetResourceString( "ArgumentOutOfRange_Count" ) ); #else throw new ArgumentOutOfRangeException(); #endif } //// if(options == CompareOptions.OrdinalIgnoreCase) //// { //// return TextInfo.IndexOfStringOrdinalIgnoreCase( source, value, startIndex, count ); //// } //// //// // Validate CompareOptions //// // Ordinal can't be selected with other flags //// if((options & ValidIndexMaskOffFlags) != 0 && (options != CompareOptions.Ordinal)) //// { //// throw new ArgumentException( Environment.GetResourceString( "Argument_InvalidFlag" ), "options" ); //// } //// //// // //// if(IsSynthetic) //// { //// if(options == CompareOptions.Ordinal) //// { //// return IndexOfString( //// CultureInfo.InvariantCulture.CompareInfo.m_pSortingTable, //// this.m_sortingLCID, //// source, //// value, //// startIndex, //// count, //// (int)options ); //// } //// //// return SyntheticIndexOf( source, value, startIndex, count, GetNativeCompareFlags( options ) ); //// } //// //// return IndexOfString( m_pSortingTable, this.m_sortingLCID, source, value, startIndex, count, (int)options ); // // Removing NotSupportedException in favor of naive implementation: see https://github.com/NETMF/llilum/issues/99 // //throw new NotSupportedException(); return IndexOfString( source, value, startIndex, count, (int)options ); } // This native method will check the parameters and validate them accordingly. // Native method: COMNlsInfo::IndexOfChar //// [ResourceExposure( ResourceScope.None )] [MethodImpl( MethodImplOptions.InternalCall )] unsafe private static extern int IndexOfChar( void* pSortingTable, int sortingLCID, String source, char value, int startIndex, int count, int options ); //// // This native method will check the parameters and validate them accordingly. //// // Native method: COMNlsInfo::IndexOfString //// [ResourceExposure( ResourceScope.None )] [MethodImpl( MethodImplOptions.InternalCall )] //// unsafe private static extern int IndexOfString( void* pSortingTable, int sortingLCID, String source, String value, int startIndex, int count, int options ); unsafe private static extern int IndexOfString( String source, String value, int startIndex, int count, int options ); //// //// //// //////////////////////////////////////////////////////////////////////// //// // //// // LastIndexOf //// // //// // Returns the last index where value is found in string. The //// // search starts from startIndex and ends at endIndex. Returns -1 if //// // the specified value is not found. If value equals String.Empty, //// // endIndex is returned. Throws IndexOutOfRange if startIndex or //// // endIndex is less than zero or greater than the length of string. //// // Throws ArgumentException if value is null. //// // //// //////////////////////////////////////////////////////////////////////// //// //// //// public unsafe virtual int LastIndexOf( String source, char value ) //// { //// if(source == null) //// { //// throw new ArgumentNullException( "source" ); //// } //// //// // Can't start at negative index, so make sure we check for the length == 0 case. //// return LastIndexOf( source, value, source.Length - 1, source.Length, CompareOptions.None ); //// } //// //// //// public unsafe virtual int LastIndexOf( String source, String value ) //// { //// if(source == null) //// { //// throw new ArgumentNullException( "source" ); //// } //// //// // Can't start at negative index, so make sure we check for the length == 0 case. //// return LastIndexOf( source, value, source.Length - 1, source.Length, CompareOptions.None ); //// } //// //// //// public unsafe virtual int LastIndexOf( String source, char value, CompareOptions options ) //// { //// if(source == null) //// { //// throw new ArgumentNullException( "source" ); //// } //// //// // Can't start at negative index, so make sure we check for the length == 0 case. //// return LastIndexOf( source, value, source.Length - 1, source.Length, options ); //// } //// //// public unsafe virtual int LastIndexOf( String source, String value, CompareOptions options ) //// { //// if(source == null) //// { //// throw new ArgumentNullException( "source" ); //// } //// //// // Can't start at negative index, so make sure we check for the length == 0 case. //// return LastIndexOf( source, value, source.Length - 1, source.Length, options ); //// } //// //// //// public unsafe virtual int LastIndexOf( String source, char value, int startIndex ) //// { //// return LastIndexOf( source, value, startIndex, startIndex + 1, CompareOptions.None ); //// } //// //// //// public unsafe virtual int LastIndexOf( String source, String value, int startIndex ) //// { //// return LastIndexOf( source, value, startIndex, startIndex + 1, CompareOptions.None ); //// } //// //// //// public unsafe virtual int LastIndexOf( String source, char value, int startIndex, CompareOptions options ) //// { //// return LastIndexOf( source, value, startIndex, startIndex + 1, options ); //// } //// //// //// public unsafe virtual int LastIndexOf( String source, String value, int startIndex, CompareOptions options ) //// { //// return LastIndexOf( source, value, startIndex, startIndex + 1, options ); //// } //// //// //// public unsafe virtual int LastIndexOf( String source, char value, int startIndex, int count ) //// { //// return LastIndexOf( source, value, startIndex, count, CompareOptions.None ); //// } //// //// //// public unsafe virtual int LastIndexOf( String source, String value, int startIndex, int count ) //// { //// return LastIndexOf( source, value, startIndex, count, CompareOptions.None ); //// } //// //// //// [ResourceExposure( ResourceScope.None )] //// [ResourceConsumption( ResourceScope.Process, ResourceScope.Process )] //// public unsafe virtual int LastIndexOf( String source, char value, int startIndex, int count, CompareOptions options ) //// { //// // Verify Arguments //// if(source == null) //// { //// throw new ArgumentNullException( "source" ); //// } //// //// // Validate CompareOptions //// // Ordinal can't be selected with other flags //// if((options & ValidIndexMaskOffFlags) != 0 && //// (options != CompareOptions.Ordinal) && //// (options != CompareOptions.OrdinalIgnoreCase)) //// { //// throw new ArgumentException( Environment.GetResourceString( "Argument_InvalidFlag" ), "options" ); //// } //// //// // Special case for 0 length input strings //// if(source.Length == 0 && (startIndex == -1 || startIndex == 0)) //// { //// return -1; //// } //// //// // Make sure we're not out of range //// if(startIndex < 0 || startIndex > source.Length) //// { //// throw new ArgumentOutOfRangeException( "startIndex", Environment.GetResourceString( "ArgumentOutOfRange_Index" ) ); //// } //// //// // Make sure that we allow startIndex == source.Length //// if(startIndex == source.Length) //// { //// startIndex--; //// if(count > 0) //// { //// count--; //// } //// } //// //// // 2nd have of this also catches when startIndex == MAXINT, so MAXINT - 0 + 1 == -1, which is < 0. //// if(count < 0 || startIndex - count + 1 < 0) //// { //// throw new ArgumentOutOfRangeException( "count", Environment.GetResourceString( "ArgumentOutOfRange_Count" ) ); //// } //// //// if(options == CompareOptions.OrdinalIgnoreCase) //// { //// return TextInfo.nativeLastIndexOfCharOrdinalIgnoreCase( //// TextInfo.InvariantNativeTextInfo, //// source, //// value, //// startIndex, //// count ); //// } //// //// // //// if(IsSynthetic) //// { //// if(options == CompareOptions.Ordinal) //// { //// return LastIndexOfChar( //// CultureInfo.InvariantCulture.CompareInfo.m_pSortingTable, //// this.m_sortingLCID, //// source, //// value, //// startIndex, //// count, //// (int)options ); //// } //// //// return SyntheticLastIndexOf( source, new String( value, 1 ), startIndex, count, GetNativeCompareFlags( options ) ); //// } //// //// return (LastIndexOfChar( m_pSortingTable, this.m_sortingLCID, source, value, startIndex, count, (int)options )); //// } //// //// //// public unsafe virtual int LastIndexOf( String source, String value, int startIndex, int count, CompareOptions options ) //// { //// // Verify Arguments //// if(source == null) //// { //// throw new ArgumentNullException( "source" ); //// } //// //// if(value == null) //// { //// throw new ArgumentNullException( "value" ); //// } //// //// // Validate CompareOptions //// // Ordinal can't be selected with other flags //// if((options & ValidIndexMaskOffFlags) != 0 && //// (options != CompareOptions.Ordinal) && //// (options != CompareOptions.OrdinalIgnoreCase)) //// { //// throw new ArgumentException( Environment.GetResourceString( "Argument_InvalidFlag" ), "options" ); //// } //// //// // Special case for 0 length input strings //// if(source.Length == 0 && (startIndex == -1 || startIndex == 0)) //// { //// return (value.Length == 0) ? 0 : -1; //// } //// //// // Make sure we're not out of range //// if(startIndex < 0 || startIndex > source.Length) //// { //// throw new ArgumentOutOfRangeException( "startIndex", Environment.GetResourceString( "ArgumentOutOfRange_Index" ) ); //// } //// //// // Make sure that we allow startIndex == source.Length //// if(startIndex == source.Length) //// { //// startIndex--; //// if(count > 0) //// { //// count--; //// } //// //// // If we are looking for nothing, just return 0 //// if(value.Length == 0 && count >= 0 && startIndex - count + 1 >= 0) //// { //// return startIndex; //// } //// } //// //// // 2nd have of this also catches when startIndex == MAXINT, so MAXINT - 0 + 1 == -1, which is < 0. //// if(count < 0 || startIndex - count + 1 < 0) //// { //// throw new ArgumentOutOfRangeException( "count", Environment.GetResourceString( "ArgumentOutOfRange_Count" ) ); //// } //// //// if(options == CompareOptions.OrdinalIgnoreCase) //// { //// return TextInfo.LastIndexOfStringOrdinalIgnoreCase( source, value, startIndex, count ); //// } //// //// // //// if(IsSynthetic) //// { //// if(options == CompareOptions.Ordinal) //// { //// return LastIndexOfString( //// CultureInfo.InvariantCulture.CompareInfo.m_pSortingTable, //// this.m_sortingLCID, //// source, //// value, //// startIndex, //// count, //// (int)options ); //// } //// //// return SyntheticLastIndexOf( source, value, startIndex, count, GetNativeCompareFlags( options ) ); //// } //// //// return (LastIndexOfString( m_pSortingTable, this.m_sortingLCID, source, value, startIndex, count, (int)options )); //// } //// //// // This native method will check the parameters and validate them accordingly. //// // Native method: COMNlsInfo::LastIndexOfChar //// [ResourceExposure( ResourceScope.None )] //// [MethodImpl( MethodImplOptions.InternalCall )] //// unsafe internal static extern int LastIndexOfChar( void* pSortingTable, int sortingLCID, String source, char value, int startIndex, int count, int options ); //// //// // This native method will check the parameters and validate them accordingly. //// // Native method: COMNlsInfo::LastIndexOfString //// [ResourceExposure( ResourceScope.None )] //// [MethodImpl( MethodImplOptions.InternalCall )] //// unsafe internal static extern int LastIndexOfString( void* pSortingTable, int sortingLCID, String source, String value, int startIndex, int count, int options ); //// //// //// //////////////////////////////////////////////////////////////////////// //// // //// // GetSortKey //// // //// // Gets the SortKey for the given string with the given options. //// // //// //////////////////////////////////////////////////////////////////////// //// //// //// public unsafe virtual SortKey GetSortKey( String source, CompareOptions options ) //// { //// // //// if(IsSynthetic) //// { //// return new SortKey( this.m_sortingLCID, source, options ); //// } //// //// // SortKey() will check the parameters and validate them accordingly. //// //// return new SortKey( m_pSortingTable, this.m_sortingLCID, source, options ); //// } //// //// //// public unsafe virtual SortKey GetSortKey( String source ) //// { //// // //// if(IsSynthetic) //// { //// return new SortKey( this.m_sortingLCID, source, CompareOptions.None ); //// } //// //// return new SortKey( m_pSortingTable, this.m_sortingLCID, source, CompareOptions.None ); //// } //// //// //////////////////////////////////////////////////////////////////////// //// // //// // Equals //// // //// // Implements Object.Equals(). Returns a boolean indicating whether //// // or not object refers to the same CompareInfo as the current //// // instance. //// // //// //////////////////////////////////////////////////////////////////////// //// //// public override bool Equals( Object value ) //// { //// CompareInfo that = value as CompareInfo; //// if(that != null) //// { //// return this.m_sortingLCID == that.m_sortingLCID && this.Name.Equals( that.Name ); //// } //// //// return false; //// } //// //// //// //////////////////////////////////////////////////////////////////////// //// // //// // GetHashCode //// // //// // Implements Object.GetHashCode(). Returns the hash code for the //// // CompareInfo. The hash code is guaranteed to be the same for //// // CompareInfo A and B where A.Equals(B) is true. //// // //// //////////////////////////////////////////////////////////////////////// //// //// //// public override int GetHashCode() //// { //// return this.Name.GetHashCode(); //// } //// //// //////////////////////////////////////////////////////////////////////// //// // //// // GetHashCodeOfString //// // //// // This internal method allows a method that allows the equivalent of creating a Sortkey for a //// // string from CompareInfo, and generate a hashcode value from it. It is not very convenient //// // to use this method as is and it creates an unnecessary Sortkey object that will be GC'ed. //// // //// // The hash code is guaranteed to be the same for string A and B where A.Equals(B) is true and both //// // the CompareInfo and the CompareOptions are the same. If two different CompareInfo objects //// // treat the string the same way, this implementation will treat them differently (the same way that //// // Sortkey does at the moment). //// // //// // This method will never be made public itself, but public consumers of it could be created, e.g.: //// // //// // string.GetHashCode(CultureInfo) //// // string.GetHashCode(CompareInfo) //// // string.GetHashCode(CultureInfo, CompareOptions) //// // string.GetHashCode(CompareInfo, CompareOptions) //// // etc. //// // //// // (the methods above that take a CultureInfo would use CultureInfo.CompareInfo) //// // //// //////////////////////////////////////////////////////////////////////// //// unsafe internal int GetHashCodeOfString( string source, CompareOptions options ) //// { //// // //// // Parameter validation //// // //// if(source == null) //// { //// throw new ArgumentNullException( "source" ); //// } //// //// if((options & ValidHashCodeOfStringMaskOffFlags) != 0) //// { //// throw new ArgumentException( Environment.GetResourceString( "Argument_InvalidFlag" ), "options" ); //// } //// //// if(source.Length == 0) //// { //// return (0); //// } //// //// // //// //////////////////////////////////////////////////////////////////////// //// //// // //// // CONSIDER: An update to nativeGetGlobalizedHashCode that called the NLS LCMapString and then //// // subsequently used the same hashcode logic would be a much better globalized hashcode. //// // //// //// // //// if(IsSynthetic) //// { //// return CultureInfo.InvariantCulture.CompareInfo.GetHashCodeOfString( source, options ); //// } //// //// return nativeGetGlobalizedHashCode( m_pSortingTable, source, (int)options, this.m_sortingLCID ); //// } //// //// //////////////////////////////////////////////////////////////////////// //// // //// // ToString //// // //// // Implements Object.ToString(). Returns a string describing the //// // CompareInfo. //// // //// //////////////////////////////////////////////////////////////////////// //// //// public override String ToString() //// { //// return "CompareInfo - " + this.culture; //// } //// //// //// public int LCID //// { //// get //// { //// return this.culture; //// } //// } //// //// // This is a thin wrapper for InitializeNativeCompareInfo() to provide the necessary //// // synchronization. //// //// /*=================================InitializeCompareInfo========================== //// **Action: Makes a native C++ SortingTable pointer using the specified assembly and Win32 LCID. //// **Returns: a 32-bit pointer value to native C++ SrotingTable instance. //// ** //// ** This method shouldn't be called when having synthetic culture (ELK) //// ** Couldn't assert her because this is a static method and cannot detect the synthetic cultures case. //// ** //// **Arguments: //// ** pNativeGlobalizationAssembly the 32-bit pointer value to a native C++ NLSAssembly instance. //// ** sortingLCID the Win32 LCID. //// **Exceptions: //// ** None. //// ============================================================================*/ //// [ResourceExposure( ResourceScope.Process )] //// [ResourceConsumption( ResourceScope.Process )] //// unsafe private static void* InitializeCompareInfo( void* pNativeGlobalizationAssembly, int sortingLCID ) //// { //// void* pTemp = null; //// bool tookLock = false; //// //// RuntimeHelpers.PrepareConstrainedRegions(); //// try //// { //// // This is intentionally taking a process-global lock, using a CER //// // to guarantee we release the lock. //// // Note that we should lock on a internal mscorlib type, so that //// // no public caller can block us by locking on the same type. //// Monitor.ReliableEnter( typeof( CultureTableRecord ), ref tookLock ); //// //// // we should lock on the call of InitializeNativeCompareInfo because it uses native static //// // variables that are not safe to be accessed in same time from different threads. //// // Since we're just calling an FCALL method here that will //// // probe for stack space, we don't need to use //// // ExecuteCodeWithGuaranteedCleanup here. //// pTemp = InitializeNativeCompareInfo( pNativeGlobalizationAssembly, sortingLCID ); //// } //// finally //// { //// if(tookLock) //// { //// Monitor.Exit( typeof( CultureTableRecord ) ); //// } //// } //// //// BCLDebug.Assert( pTemp != null, "pTemp != null" ); //// return pTemp; //// } //// //// unsafe void IDeserializationCallback.OnDeserialization( Object sender ) //// { //// OnDeserialized(); //// } //// //// // This method requires synchonization because class global data member is used //// // in the native side. //// // Native method: COMNlsInfo::InitializeNativeCompareInfo //// [ResourceExposure( ResourceScope.Process )] //// [MethodImpl( MethodImplOptions.InternalCall )] //// unsafe private static extern void* InitializeNativeCompareInfo( void* pNativeGlobalizationAssembly, int sortingLCID ); } } ================================================ FILE: Zelig/Zelig/RunTime/Framework/mscorlib/System/Globalization/CultureInfo.cs ================================================ // ==++== // // Copyright (c) Microsoft Corporation. All rights reserved. // // ==--== //////////////////////////////////////////////////////////////////////////// // // Class: CultureInfo // // // Purpose: This class represents the software preferences of a particular // culture or community. It includes information such as the // language, writing system, and a calendar used by the culture // as well as methods for common operations such as printing // dates and sorting strings. // // Date: March 31, 1999 // // // !!!! NOTE WHEN CHANGING THIS CLASS !!!! // // If adding or removing members to this class, please update CultureInfoBaseObject // in ndp/clr/src/vm/object.h. Note, the "actual" layout of the class may be // different than the order in which members are declared. For instance, all // reference types will come first in the class before value types (like ints, bools, etc) // regardless of the order in which they are declared. The best way to see the // actual order of the class is to do a !dumpobj on an instance of the managed // object inside of the debugger. // //////////////////////////////////////////////////////////////////////////// namespace System.Globalization { using System; using System.Threading; using System.Collections; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using System.Runtime.Serialization; ////using System.Security.Permissions; using System.Reflection; ////using Microsoft.Win32; ////using System.Runtime.Versioning; [Serializable] public class CultureInfo : /*ICloneable,*/ IFormatProvider { //// // //// // Special culture IDs //// // //// internal const int zh_CHT_CultureID = 0x7c04; //// // Serbian Neutral culture ID. //// internal const int sr_CultureID = 0x7c1a; //// internal const int sr_SP_Latn_CultureID = 0x081a; //// //// // Ietf name registry location //// internal const string ietfRegistryKey = "SYSTEM\\CurrentControlSet\\Control\\Nls\\IetfLanguage"; //// //// //--------------------------------------------------------------------// //// // Internal Information // //// //--------------------------------------------------------------------// //// //// //--------------------------------------------------------------------// //// // //// // Static data members //// // //// //--------------------------------------------------------------------// //// //// //Get the current user default culture. This one is almost always used, so we create it by default. //// private static CultureInfo m_userDefaultCulture = null; // // All of the following will be created on demand. // //The Invariant culture; private static CultureInfo m_InvariantCultureInfo = null; //// //The culture used in the user interface. This is mostly used to load correct localized resources. //// private static CultureInfo m_userDefaultUICulture = null; //// //// //This is the UI culture used to install the OS. //// private static CultureInfo m_InstalledUICultureInfo = null; //// //// //This is a cache of all previously created cultures. Valid keys are LCIDs or the name. We use two hashtables to track them, //// // depending on how they are called. //// private static Hashtable m_LcidCachedCultures = null; //// private static Hashtable m_NameCachedCultures = null; //// private static Hashtable m_IetfCachedCultures = null; //// //// // May need a registry key if looking up ietf names by name //// private static RegistryKey m_ietfNameLookupKey = null; //// //// //// //--------------------------------------------------------------------// //// // Data members to be serialized: //// //--------------------------------------------------------------------// //// //// // This is the string used to construct CultureInfo. //// // It is in the format of ISO639 (2 letter language name) plus dash plus //// // ISO 3166 (2 letter region name). The language name is in lowercase and region name //// // are in uppercase. (now part of cultureTableRecord) //// //// // //// // This is the culture ID used in the NLS+ world. The concept of cultureID is similar //// // to the concept of LCID in Win32. However, NLS+ support "neutral" culture //// // which Win32 doesn't support. //// // //// // The format of culture ID (32 bits) is: //// // //// // 31 - 20 19 18 17 16 15 14 13 12 11 10 9 8 7 6 5 4 3 2 1 0 //// // +-----+ +---------+ +---------------+ +-----------------+ //// // | | | Primary language ID (10 bits) //// // | | +----------- Sublanguage ID (6 its) //// // | +----------------------- Sort ID (4 bits) //// // +--------------------------------- Reserved (12 bits) //// // //// // Primary language ID and sublanguage ID can be zero to specify 'neutral' language. //// // For example, cultureID 0x(0000)0009 is the English neutral culture. //// // cultureID 0x(0000)0000 means the invariant culture (or called neutral culture). //// // //// // We'd just use cultureTableInfo.cultureID for ID, however cultureTableInfo doesn't //// // remember the sort info. //// //// // WARNING //// // WARNING: All member fields declared here must also be in ndp/clr/src/vm/object.h //// // WARNING: They aren't really private because object.h can access them, but other C# stuff cannot //// // WARNING //// internal int cultureID; internal bool m_isReadOnly = false; //// //// internal CompareInfo compareInfo = null; internal TextInfo textInfo = null; internal NumberFormatInfo numInfo = null; internal DateTimeFormatInfo dateTimeInfo = null; //// internal Calendar calendar = null; // // The CultureTable instance that we are going to read data from. // For supported culture, this will be the CultureTable instance that read data from mscorlib assembly. // For customized culture, this will be the CultureTable instance that read data from user customized culture binary file. // [NonSerialized] internal CultureTableRecord m_cultureTableRecord; [NonSerialized] internal bool m_isInherited; //// [NonSerialized] //// private bool m_isSafeCrossDomain = false; //// [NonSerialized] //// private int m_createdDomainID = 0; //// [NonSerialized] //// private CultureInfo m_consoleFallbackCulture = null; //// //// // Names are confusing. Here are 3 names we have: //// // //// // new CultureInfo() m_name m_nonSortName m_sortName //// // en-US en-US en-US en-US //// // de-de_phoneb de-DE_phoneb de-DE de-DE_phoneb //// // fj-fj (custom) fj-FJ fj-FJ en-US (if specified sort is en-US) //// //// // Note that the name used to be serialized for Everett; it is now serialized //// // because alernate sorts can have alternate names. //// // This has a de-DE, de-DE_phoneb or fj-FJ style name //// internal string m_name = null; //// //// // This will hold the non sorting name to be returned from CultureInfo.Name property. //// // This has a de-DE style name even for de-DE_phoneb type cultures //// [NonSerialized] //// private string m_nonSortName = null; //// //// // This will hold the sorting name to be returned from CultureInfo.SortName property. //// // This might be completely unrelated to the culture name if a custom culture. Ie en-US for fj-FJ. //// // Otherwise its the sort name, ie: de-DE or de-DE_phoneb //// [NonSerialized] //// private string m_sortName = null; //// //// // Ietf name //// [NonSerialized] //// private string m_ietfName = null; //// //// //The parent culture. //// [NonSerialized] //// private CultureInfo m_parent; //// //// //// // //// // Helper Methods. //// // //// [ResourceExposure( ResourceScope.None )] //// [MethodImpl( MethodImplOptions.InternalCall )] //// internal static extern bool IsValidLCID( int LCID, int flag ); //// //// [ResourceExposure( ResourceScope.None )] //// [MethodImpl( MethodImplOptions.InternalCall )] //// internal static extern unsafe String nativeGetUserDefaultLCID( int* LCID, int lcidType ); //// //// [ResourceExposure( ResourceScope.None )] //// [MethodImpl( MethodImplOptions.InternalCall )] //// internal static extern unsafe String nativeGetUserDefaultUILanguage( int* LCID ); //// //// [ResourceExposure( ResourceScope.None )] //// [MethodImpl( MethodImplOptions.InternalCall )] //// internal static extern unsafe String nativeGetSystemDefaultUILanguage( int* LCID ); //// //// [ResourceExposure( ResourceScope.None )] //// [MethodImpl( MethodImplOptions.InternalCall )] //// internal static extern bool nativeSetThreadLocale( int LCID ); //// //// [ResourceExposure( ResourceScope.None )] //// [MethodImpl( MethodImplOptions.InternalCall )] //// internal static extern String nativeGetLocaleInfo( int LCID, int field ); //// //// [ResourceExposure( ResourceScope.None )] //// [MethodImpl( MethodImplOptions.InternalCall )] //// internal static extern int nativeGetCurrentCalendar(); //// //// [ResourceExposure( ResourceScope.None )] //// [MethodImpl( MethodImplOptions.InternalCall )] //// internal static extern unsafe bool nativeGetDTFIUserValues( int lcid, ref DTFIUserOverrideValues values ); //// //// [ResourceExposure( ResourceScope.None )] //// [MethodImpl( MethodImplOptions.InternalCall )] //// internal static extern unsafe bool nativeGetNFIUserValues( int lcid, NumberFormatInfo nfi ); //// //// // //// [ResourceExposure( ResourceScope.None )] //// [MethodImpl( MethodImplOptions.InternalCall )] //// internal static extern unsafe bool nativeGetCultureData( int lcid, ref CultureData cultureData ); //// //// // //// [ResourceExposure( ResourceScope.None )] //// [MethodImpl( MethodImplOptions.InternalCall )] //// internal static extern bool nativeEnumSystemLocales( out int[] localesArray ); //// //// // //// [ResourceExposure( ResourceScope.None )] //// [MethodImpl( MethodImplOptions.InternalCall )] //// internal static extern string nativeGetCultureName( int lcid, bool useSNameLCType, bool getMonthName ); //// //// // //// // Return the path to the Windows directory (such as c:\Windows). The returned string does NOT include the backslash. //// // //// [ResourceExposure( ResourceScope.Machine )] //// [MethodImpl( MethodImplOptions.InternalCall )] //// internal static extern string nativeGetWindowsDirectory(); //// //// // //// // Check if the specified fileName exists in the file system or not. //// // //// [ResourceExposure( ResourceScope.Machine )] //// [MethodImpl( MethodImplOptions.InternalCall )] //// internal static extern bool nativeFileExists( String fileName ); //// //// // //// // Get the static int array data used by globalization classes. //// // //// [ResourceExposure( ResourceScope.None )] //// [MethodImpl( MethodImplOptions.InternalCall )] //// internal static extern unsafe int* nativeGetStaticInt32DataTable( int type, out int tableSize ); //// //// // //// // we didn't make LCMapStringW fast call because in the debug mscorwks we should call LCMapStringW through a wrapper //// // which can switch to ansi version randomally (to simulate the running in the ansi platforms). //// // //// // we just need to call the Unicode version all the time as we check running on the Unicode platforms before we proceed //// // while getting the culture data (in nativeGetCultureData) //// // //// // //// internal static unsafe int GetNativeSortKey( int lcid, int flags, string source, int cchSrc, out byte[] sortKey ) //// { //// sortKey = null; //// //// int length; //// //// fixed(char* src = source) //// { //// length = Win32Native.LCMapStringW( lcid, flags | Win32Native.LCMAP_SORTKEY, src, cchSrc, null, 0 ); //// if(length == 0) //// { //// return 0; //// } //// //// sortKey = new byte[length]; //// //// fixed(byte* key = sortKey) //// { //// length = Win32Native.LCMapStringW( lcid, flags | Win32Native.LCMAP_SORTKEY, src, cchSrc, (char*)key, length ); //// } //// } //// //// return length; //// } //// //// private const int LOCALE_NEUTRAL = 0x0000; internal const int LOCALE_INVARIANT = 0x007f; //// internal const int LOCALE_USER_DEFAULT = 0x0400; //// internal const int LOCALE_SYSTEM_DEFAULT = 0x0800; //// internal const int LOCALE_CUSTOM_DEFAULT = 0x0c00; //// internal const int LOCALE_CUSTOM_UNSPECIFIED = 0x1000; //// internal const int LOCALE_TRADITIONAL_SPANISH = 0x040a; //// internal const int LCID_INSTALLED = 0x0001; //// internal const int LCID_SUPPORTED = 0x0002; // // The CultureTable instance that read data from culture.nlp in the mscorlib assembly. // static unsafe CultureInfo() { if(m_InvariantCultureInfo == null) { CultureInfo temp = new CultureInfo( LOCALE_INVARIANT, false ); //// temp.m_isReadOnly = true; m_InvariantCultureInfo = temp; } //// // First we set it to Invariant in case someone needs it before we're done finding it. //// // For example, if we throw an exception in InitUserDefaultCulture, we will still need an valid //// // m_userDefaultCulture to be used in Thread.CurrentCulture. //// m_userDefaultCulture = m_userDefaultUICulture = m_InvariantCultureInfo; //// //// m_userDefaultCulture = InitUserDefaultCulture(); //// m_userDefaultUICulture = InitUserDefaultUICulture(); } //// static unsafe CultureInfo InitUserDefaultCulture() //// { //// int LCID; //// String strDefault = nativeGetUserDefaultLCID( &LCID, LOCALE_USER_DEFAULT ); //// CultureInfo temp = GetCultureByLCIDOrName ( LCID, strDefault ); //// if(temp == null) //// { //// strDefault = nativeGetUserDefaultLCID( &LCID, LOCALE_SYSTEM_DEFAULT ); //// temp = GetCultureByLCIDOrName ( LCID, strDefault ); //// //// if(temp == null) //// { //// // If system default doesn't work, keep using the invariant //// return (CultureInfo.InvariantCulture); //// } //// } //// //// temp.m_isReadOnly = true; //// //// return (temp); //// } //// //// static unsafe CultureInfo InitUserDefaultUICulture() //// { //// int LCID; //// String strDefault = nativeGetUserDefaultUILanguage( &LCID ); //// //// // In most of cases, UserDefaultCulture == UserDefaultUICulture, so we should use the same instance if possible. //// if(LCID == UserDefaultCulture.LCID || strDefault == UserDefaultCulture.Name) //// { //// return (UserDefaultCulture); //// } //// //// CultureInfo temp = GetCultureByLCIDOrName( LCID, strDefault ); //// //// if(temp == null) //// { //// strDefault = nativeGetSystemDefaultUILanguage( &LCID ); //// temp = GetCultureByLCIDOrName ( LCID, strDefault ); //// } //// //// if(temp == null) //// { //// return (CultureInfo.InvariantCulture); //// } //// //// temp.m_isReadOnly = true; //// //// return (temp); //// } //////////////////////////////////////////////////////////////////////// // // CultureInfo Constructors // //////////////////////////////////////////////////////////////////////// public CultureInfo( String name ) : this( name, true ) { } public CultureInfo( String name, bool useUserOverride ) { //// if(name == null) //// { //// throw new ArgumentNullException( "name", Environment.GetResourceString( "ArgumentNull_String" ) ); //// } //// //// this.m_cultureTableRecord = CultureTableRecord.GetCultureTableRecord( name, useUserOverride ); //// this.cultureID = this.m_cultureTableRecord.ActualCultureID; //// this.m_name = this.m_cultureTableRecord.ActualName; //// this.m_isInherited = (this.GetType() != typeof( System.Globalization.CultureInfo )); } public CultureInfo( int culture ) : this( culture, true ) { } public unsafe CultureInfo( int culture, bool useUserOverride ) { //// // We don't check for other invalid LCIDS here... //// if(culture < 0) //// { //// throw new ArgumentOutOfRangeException( "culture", Environment.GetResourceString( "ArgumentOutOfRange_NeedPosNum" ) ); //// } //// //// switch(culture) //// { //// case LOCALE_CUSTOM_DEFAULT: //// // CONSDIER: Support this LCID value any time the OS is using a custom culture as the user default. //// // Note that if this is to be supported that the code below is not correct since it assumes //// // the LCID value is describing the NLS+ culture, not the NLS locale. //// /* //// this.m_cultureTableRecord = CultureInfo.CurrentCulture.m_cultureTableRecord; //// this.cultureID = CultureInfo.CurrentCulture.cultureID; //// break; //// */ //// case LOCALE_SYSTEM_DEFAULT: //// /* //// String strSystemDefault = nativeGetUserDefaultLCID(&culture, LOCALE_SYSTEM_DEFAULT); //// CultureInfo systemDefault; //// //// // See if we can get our LOCALE_SYSTEM_DEFAULT //// systemDefault = GetCultureByLCIDOrName(culture, strSystemDefault); //// //// if (systemDefault == null) //// // That didn't work, try invariant //// systemDefault = InvariantCulture; //// //// this.cultureID = systemDefault.cultureID; //// this.m_cultureTableRecord = systemDefault.m_cultureTableRecord; //// break; //// */ //// case LOCALE_NEUTRAL: //// case LOCALE_USER_DEFAULT: //// case LOCALE_CUSTOM_UNSPECIFIED: //// // Can't support unknown custom cultures and we do not support neutral or //// // non-custom user locales. //// throw new ArgumentException( Environment.GetResourceString( "Argument_CultureNotSupported", culture ), "culture" ); //// //// default: //// this.cultureID = culture; //// // Now see if this LCID is supported in the system default culture.nlp table. //// this.m_cultureTableRecord = CultureTableRecord.GetCultureTableRecord( this.cultureID, useUserOverride ); //// this.m_name = this.m_cultureTableRecord.ActualName; //// break; //// } //// //// m_isInherited = (this.GetType() != typeof( System.Globalization.CultureInfo )); } //// //// //// // //// // CheckDomainSafetyObject throw if the object is customized object which cannot be attached to //// // other object (like CultureInfo or DateTimeFormatInfo). //// // //// //// internal static void CheckDomainSafetyObject( Object obj, Object container ) //// { //// if(obj.GetType().Assembly != typeof( System.Globalization.CultureInfo ).Assembly) //// { //// throw new InvalidOperationException( String.Format( CultureInfo.CurrentCulture, //// Environment.GetResourceString( "InvalidOperation_SubclassedObject" ), //// obj.GetType(), //// container.GetType() ) ); //// } //// } #region Serialization //// // the following fields are defined to keep the compatibility with .NET V1.0/V1.1. //// // don't change/remove the names/types of these fields. //// private int m_dataItem; //// private bool m_useUserOverride; //// //// [OnDeserialized] //// private void OnDeserialized( StreamingContext ctx ) //// { //// // In .NET ver 1.0 we can get m_name = null if the Name property never requested //// // before serializing the culture info object. //// //// BCLDebug.Assert( m_name != null || cultureID > 0, "[CultureInfo.OnDeserialized] m_name != null || cultureID>0" ); //// //// if(m_name != null && cultureID != LOCALE_TRADITIONAL_SPANISH) //// { //// m_cultureTableRecord = CultureTableRecord.GetCultureTableRecord( m_name, m_useUserOverride ); //// } //// else //// { //// m_cultureTableRecord = CultureTableRecord.GetCultureTableRecord( cultureID, m_useUserOverride ); //// } //// //// m_isInherited = (this.GetType() != typeof( System.Globalization.CultureInfo )); //// //// if(m_name == null) //// { //// m_name = m_cultureTableRecord.ActualName; //// } //// //// // in case we have non customized CultureInfo object we shouldn't allow any customized object //// // to be attached to it for cross app domain safety. //// if(this.GetType().Assembly == typeof( System.Globalization.CultureInfo ).Assembly) //// { //// if(textInfo != null) //// { //// CheckDomainSafetyObject( textInfo, this ); //// } //// //// if(compareInfo != null) //// { //// CheckDomainSafetyObject( compareInfo, this ); //// } //// } //// } //// //// [OnSerializing] //// private void OnSerializing( StreamingContext ctx ) //// { //// m_name = m_cultureTableRecord.CultureName; //// m_useUserOverride = m_cultureTableRecord.UseUserOverride; //// m_dataItem = m_cultureTableRecord.EverettDataItem(); //// } #endregion Serialization //// internal bool IsSafeCrossDomain //// { //// get //// { //// BCLDebug.Assert( m_createdDomainID != 0, "[CultureInfo.IsSafeCrossDomain] m_createdDomainID != 0" ); //// return m_isSafeCrossDomain; //// } //// } //// //// internal int CreatedDomainID //// { //// get //// { //// BCLDebug.Assert( m_createdDomainID != 0, "[CultureInfo.CreatedDomain] m_createdDomainID != 0" ); //// return m_createdDomainID; //// } //// } //// //// internal void StartCrossDomainTracking() //// { //// // If we have decided about cross domain safety of this instance, we are done //// if(m_createdDomainID != 0) //// { //// return; //// } //// //// if(this.GetType() == typeof( System.Globalization.CultureInfo )) //// { //// m_isSafeCrossDomain = true; //// } //// //// // m_createdDomainID has to be assigned last. We use it to signal that we have //// // completed the check. //// System.Threading.Thread.MemoryBarrier(); //// //// m_createdDomainID = Thread.GetDomainID(); //// } //// //// // Constructor called by SQL Server's special munged culture - creates a culture with //// // a TextInfo and CompareInfo that come from a supplied alternate source. This object //// // is ALWAYS read-only. //// // Note that we really cannot use an LCID version of this override as the cached //// // name we create for it has to include both names, and the logic for this is in //// // the GetCultureInfo override *only*. //// internal CultureInfo( String cultureName, String textAndCompareCultureName ) //// { //// if(cultureName == null) //// { //// throw new ArgumentNullException( "cultureName", Environment.GetResourceString( "ArgumentNull_String" ) ); //// } //// //// this.m_cultureTableRecord = CultureTableRecord.GetCultureTableRecord( cultureName, false ); //// this.cultureID = this.m_cultureTableRecord.ActualCultureID; //// this.m_name = this.m_cultureTableRecord.ActualName; //// //// CultureInfo altCulture = GetCultureInfo( textAndCompareCultureName ); //// //// this.compareInfo = altCulture.CompareInfo; //// this.textInfo = altCulture.TextInfo; //// } //// //// //// // Get a culture when trying to create it from LCID or name //// // This happens when asking windows for the locale information. //// // In this case we want to use LCID if provided, otherwise use //// // the name. Using LCID gives us system default values, using //// // names would allow users to override system cultures when we //// // don't expect them to. //// // //// // Note that this should pick up a CC of the same name for //// // OS ELKS/LIPS/whatever, but will throw if no CC is installed. //// private static CultureInfo GetCultureByLCIDOrName( int preferLCID, String fallbackToString ) //// { //// // If we don't have a string or we don't have //// CultureInfo culture = null; //// //// // We prefer LCID because that gives us the system values, but we can't use //// // it if there's no lang part //// if((preferLCID & 0x3ff) != 0) //// { //// // Try to get it //// try //// { //// culture = new CultureInfo( preferLCID ); //// } //// catch(ArgumentException) //// { //// } //// } //// //// // If it didn't work by # we need to try string (if possible) //// if(culture == null && fallbackToString != null && fallbackToString.Length > 0) //// { //// // Try to get it //// try //// { //// culture = new CultureInfo( fallbackToString ); //// } //// catch(ArgumentException) //// { //// } //// } //// //// return culture; //// } //// //// //// //// public static CultureInfo CreateSpecificCulture( String name ) //// { //// CultureInfo culture; //// //// try //// { //// culture = new CultureInfo( name ); //// } //// catch(ArgumentException exp) //// { //// // When CultureInfo throws this exception, it may be because someone passed the form //// // like "az-az" because it came out of an http accept lang. We should try a little //// // parsing to perhaps fall back to "az" here and use *it* to create the neutral. //// //// int idx; //// //// culture = null; //// for(idx = 0; idx < name.Length; idx++) //// { //// if('-' == name[idx]) //// { //// try //// { //// culture = new CultureInfo( name.Substring( 0, idx ) ); //// break; //// } //// catch(ArgumentException) //// { //// // throw the original exception so the name in the string will be right //// throw (exp); //// } //// } //// } //// //// if(culture == null) //// { //// // nothing to save here; throw the original exception //// throw (exp); //// } //// } //// //// //In the most common case, they've given us a specific culture, so we'll just return that. //// if(!(culture.IsNeutralCulture)) //// { //// return culture; //// } //// //// int lcid = culture.LCID; //// //If we have the Chinese locale, we have no way of producing a //// //specific culture without encountering significant geopolitical //// //issues. Based on that, we have no choice but to return. //// if((lcid & 0x3FF) == 0x04) //// { //// throw new ArgumentException( Environment.GetResourceString( "Argument_NoSpecificCulture" ) ); //// } //// //// return (new CultureInfo( culture.m_cultureTableRecord.SSPECIFICCULTURE )); //// } //// //// internal static bool VerifyCultureName( CultureInfo culture, bool throwException ) //// { //// BCLDebug.Assert( culture != null, "[CultureInfo.VerifyCultureName]culture!=null" ); //// //// //If we have an instance of one of our CultureInfos, the user can't have changed the //// //name and we know that all names are valid in files. //// if(!culture.m_isInherited) //// { //// return true; //// } //// //// // This function is used by ResourceManager.GetResourceFileName(). //// // ResourceManager searches for resource using CultureInfo.Name, //// // so we should check against CultureInfo.Name. //// String name = culture.Name; //// //// for(int i = 0; i < name.Length; i++) //// { //// char c = name[i]; //// if(Char.IsLetterOrDigit( c ) || c == '-' || c == '_') //// { //// continue; //// } //// //// if(throwException) //// { //// throw new ArgumentException( Environment.GetResourceString( "Argument_InvalidResourceCultureName", name ) ); //// } //// //// return false; //// } //// //// return true; //// } //// //// //--------------------------------------------------------------------// //// // Misc static functions // //// //--------------------------------------------------------------------// //// //// internal static int GetSubLangID( int culture ) //// { //// return ((culture >> 10) & 0x3f); //// } //// //// internal static int GetLangID( int culture ) //// { //// return (culture & 0xffff); //// } //// //// internal static int GetSortID( int lcid ) //// { //// return ((lcid >> 16) & 0xf); //// } //// //// //////////////////////////////////////////////////////////////////////// //// // //// // CurrentCulture //// // //// // This instance provides methods based on the current user settings. //// // These settings are volatile and may change over the lifetime of the //// // thread. //// // //// //////////////////////////////////////////////////////////////////////// public static CultureInfo CurrentCulture { get { return Thread.CurrentThread.CurrentCulture; } } // // This is the equivalence of the Win32 GetUserDefaultLCID() // internal static CultureInfo UserDefaultCulture { get { //// CultureInfo temp = m_userDefaultCulture; //// if(temp == null) //// { //// // //// // setting the m_userDefaultCulture with invariant culture before intializing it is a protection //// // against recursion problem just in case if somebody called CurrentCulture from the CultureInfo //// // creation path. the recursion can happen if the current user culture is a replaced custom culture. //// // //// //// m_userDefaultCulture = CultureInfo.InvariantCulture; //// //// temp = InitUserDefaultCulture(); //// //// m_userDefaultCulture = temp; //// } //// return (temp); return CultureInfo.InvariantCulture; } } //// // //// // This is the equivalence of the Win32 GetUserDefaultUILanguage() //// // //// internal static unsafe CultureInfo UserDefaultUICulture //// { //// get //// { //// CultureInfo temp = m_userDefaultUICulture; //// if(temp == null) //// { //// // //// // setting the m_userDefaultCulture with invariant culture before intializing it is a protection //// // against recursion problem just in case if somebody called CurrentUICulture from the CultureInfo //// // creation path. the recursion can happen if the current user culture is a replaced custom culture. //// // //// //// m_userDefaultUICulture = CultureInfo.InvariantCulture; //// //// temp = InitUserDefaultUICulture(); //// //// m_userDefaultUICulture = temp; //// } //// return (temp); //// } //// } //// //// //// public static CultureInfo CurrentUICulture //// { //// get //// { //// return Thread.CurrentThread.CurrentUICulture; //// } //// } //// //// //// // //// // This is the equivalence of the Win32 GetSystemDefaultUILanguage() //// // //// public static unsafe CultureInfo InstalledUICulture //// { //// get //// { //// CultureInfo temp = m_InstalledUICultureInfo; //// if(temp == null) //// { //// int LCID; //// String strDefault = nativeGetSystemDefaultUILanguage( &LCID ); //// temp = GetCultureByLCIDOrName ( LCID, strDefault ); //// //// if(temp == null) //// { //// temp = new CultureInfo( LOCALE_INVARIANT, true ); //// } //// //// temp.m_isReadOnly = true; //// //// m_InstalledUICultureInfo = temp; //// } //// return temp; //// } //// } //////////////////////////////////////////////////////////////////////// // // InvariantCulture // // This instance provides methods, for example for casing and sorting, // that are independent of the system and current user settings. It // should be used only by processes such as some system services that // require such invariant results (eg. file systems). In general, // the results are not linguistically correct and do not match any // culture info. // //////////////////////////////////////////////////////////////////////// public static CultureInfo InvariantCulture { get { return m_InvariantCultureInfo; } } //// //////////////////////////////////////////////////////////////////////// //// // //// // Parent //// // //// // Return the parent CultureInfo for the current instance. //// // //// //////////////////////////////////////////////////////////////////////// //// //// public virtual CultureInfo Parent //// { //// get //// { //// if(m_parent == null) //// { //// try //// { //// int parentCulture = this.m_cultureTableRecord.IPARENT; //// if(parentCulture == LOCALE_INVARIANT) //// { //// m_parent = InvariantCulture; //// } //// else if(CultureTableRecord.IsCustomCultureId( parentCulture )) //// { //// // Customized culture -- use the string for the parent. //// m_parent = new CultureInfo( this.m_cultureTableRecord.SPARENT ); //// } //// else //// { //// m_parent = new CultureInfo( parentCulture, this.m_cultureTableRecord.UseUserOverride ); //// } //// } //// catch(ArgumentException) //// { //// // For whatever reason our IPARENT or SPARENT wasn't correct, so use invariant //// // We can't allow ourselves to fail. In case of custom cultures the parent of the //// // current custom culture isn't installed. //// m_parent = InvariantCulture; //// } //// } //// //// return m_parent; //// } //// } //// //// //////////////////////////////////////////////////////////////////////// //// // //// // LCID //// // //// // Returns a properly formed culture identifier for the current //// // culture info. //// // //// //////////////////////////////////////////////////////////////////////// //// //// //// public virtual int LCID //// { //// get //// { //// return this.cultureID; //// } //// } //// //// //////////////////////////////////////////////////////////////////////// //// // //// // BaseInputLanguage //// // //// // Essentially an LCID, though one that may be different than LCID in the case //// // of a customized culture (LCID == -1). //// // //// //////////////////////////////////////////////////////////////////////// //// //// public virtual int KeyboardLayoutId //// { //// get //// { //// int keyId = this.m_cultureTableRecord.IINPUTLANGUAGEHANDLE; //// //// // Not a customized culture, return the default Keyboard layout ID, which is the same as the language ID. //// return keyId; //// } //// } //// //// //// public static CultureInfo[] GetCultures( CultureTypes types ) //// { //// return CultureTable.Default.GetCultures( types ); //// } //// //// //////////////////////////////////////////////////////////////////////// // // Name // // Returns the full name of the CultureInfo. The name is in format like // "en-US" This version does NOT include sort information in the name. // //////////////////////////////////////////////////////////////////////// public virtual String Name { get { //////// We return non sorting name here. //////if(this.m_nonSortName == null) //////{ ////// this.m_nonSortName = this.m_cultureTableRecord.CultureName; //////} //////return this.m_nonSortName; return "en"; } } //// //// //// internal String SortName //// { //// get //// { //// if(this.m_sortName == null) //// { //// if(CultureTableRecord.IsCustomCultureId( cultureID )) //// { //// CultureInfo sortCI = CultureInfo.GetCultureInfo( CompareInfoId ); //// //// BCLDebug.Assert( !CultureTableRecord.IsCustomCultureId( sortCI.cultureID ), //// "[CultureInfo.SortName]Expected non-custom sort id" ); //// //// if(CultureTableRecord.IsCustomCultureId( sortCI.cultureID )) //// { //// // m_name create could call SortName (not supposed to for CI), //// // but just to be safe, use SNAME not m_name //// this.m_sortName = m_cultureTableRecord.SNAME; //// } //// else //// { //// this.m_sortName = sortCI.SortName; // Name of culture doing our sort //// } //// } //// else //// { //// // If its not custom, our sort is our full name //// BCLDebug.Assert( m_name != null, "[CultureInfo.SortName]Always expect m_name to be set" ); //// this.m_sortName = this.m_name; // full name, including sort //// } //// } //// //// return this.m_sortName; //// } //// } //// //// public String IetfLanguageTag //// { //// get //// { //// if(this.m_ietfName == null) //// { //// this.m_ietfName = this.m_cultureTableRecord.SIETFTAG; //// } //// //// // IETF RFC 3066 name goes here //// return this.m_ietfName; //// } //// } //// //// //////////////////////////////////////////////////////////////////////// //// // //// // DisplayName //// // //// // Returns the full name of the CultureInfo in the localized language. //// // For example, if the localized language of the runtime is Spanish and the CultureInfo is //// // US English, "Ingles (Estados Unidos)" will be returned. //// // //// //////////////////////////////////////////////////////////////////////// //// //// //// public virtual String DisplayName //// { //// get //// { //// BCLDebug.Assert( m_name != null, "[CultureInfo.DisplayName]Always expect m_name to be set" ); //// //// if(m_cultureTableRecord.IsCustomCulture) //// { //// if(m_cultureTableRecord.IsReplacementCulture) //// { //// // //// if(m_cultureTableRecord.IsSynthetic) //// { //// return m_cultureTableRecord.CultureNativeDisplayName; //// } //// else //// { //// return (Environment.GetResourceString( "Globalization.ci_" + this.m_name )); //// } //// } //// else //// { //// return m_cultureTableRecord.SNATIVEDISPLAYNAME; //// } //// } //// else //// { //// // //// if(m_cultureTableRecord.IsSynthetic) //// { //// return m_cultureTableRecord.CultureNativeDisplayName; //// } //// else //// { //// return (Environment.GetResourceString( "Globalization.ci_" + this.m_name )); //// } //// } //// } //// } //// //// //////////////////////////////////////////////////////////////////////// //// // //// // GetNativeName //// // //// // Returns the full name of the CultureInfo in the native language. //// // For example, if the CultureInfo is US English, "English //// // (United States)" will be returned. //// // //// //////////////////////////////////////////////////////////////////////// //// //// //// public virtual String NativeName //// { //// get //// { //// return (this.m_cultureTableRecord.SNATIVEDISPLAYNAME); //// } //// } //// //// //////////////////////////////////////////////////////////////////////// //// // //// // GetEnglishName //// // //// // Returns the full name of the CultureInfo in English. //// // For example, if the CultureInfo is US English, "English //// // (United States)" will be returned. //// // //// //////////////////////////////////////////////////////////////////////// //// //// //// public virtual String EnglishName //// { //// get //// { //// return this.m_cultureTableRecord.SENGDISPLAYNAME; //// } //// } //// //// //// public virtual String TwoLetterISOLanguageName //// { //// get //// { //// return this.m_cultureTableRecord.SISO639LANGNAME; //// } //// } //// //// //// public virtual String ThreeLetterISOLanguageName //// { //// get //// { //// return this.m_cultureTableRecord.SISO639LANGNAME2; //// } //// } //// //// //////////////////////////////////////////////////////////////////////// //// // //// // GetAbbreviatedName //// // //// // Returns the abbreviated name for the current instance. The //// // abbreviated form is usually based on the ISO 639 standard, for //// // example the two letter abbreviation for English is "en". //// // //// //////////////////////////////////////////////////////////////////////// //// //// //// public virtual String ThreeLetterWindowsLanguageName //// { //// get //// { //// return this.m_cultureTableRecord.SABBREVLANGNAME; //// } //// } //////////////////////////////////////////////////////////////////////// // // CompareInfo Read-Only Property // // Gets the CompareInfo for this culture. // //////////////////////////////////////////////////////////////////////// public extern virtual CompareInfo CompareInfo { [MethodImpl( MethodImplOptions.InternalCall )] get; //// { //// if(compareInfo == null) //// { //// //// CompareInfo temp; //// //// // In case of non custom neutral cultures we always return compare info with neutral culture id //// // and neutral culture name. this to be compatible with Everett. //// //// if(IsNeutralCulture && !CultureTableRecord.IsCustomCultureId( cultureID )) //// { //// temp = CompareInfo.GetCompareInfo( cultureID ); //// } //// else //// { //// temp = CompareInfo.GetCompareInfo( CompareInfoId ); //// } //// //// // The name is not preset when CompareInfo is set by LCID, so lets set it now. //// temp.SetName( this.SortName ); //// compareInfo = temp; //// //// } //// return compareInfo; //// } } //// internal int CompareInfoId //// { //// get //// { //// int compareId; //// //// if(this.cultureID == LOCALE_TRADITIONAL_SPANISH) //// { //// // Special case Trad. Spanish since there is no //// // ICOMPAREINFO entry for them. //// compareId = LOCALE_TRADITIONAL_SPANISH; //// } //// else if(GetSortID( this.cultureID ) != 0) //// { //// // Special case alternate sorts since there is no //// // ICOMPAREINFO entry for them. //// compareId = this.cultureID; //// } //// else //// { //// compareId = unchecked( (int)this.m_cultureTableRecord.ICOMPAREINFO ); //// } //// //// return compareId; //// } //// } //////////////////////////////////////////////////////////////////////// // // TextInfo // // Gets the TextInfo for this culture. // //////////////////////////////////////////////////////////////////////// public virtual TextInfo TextInfo { get { if(textInfo == null) { //// // Make a new textInfo //// TextInfo tempTextInfo = new TextInfo( this.m_cultureTableRecord ); //// //// tempTextInfo.SetReadOnlyState( m_isReadOnly ); //// //// textInfo = tempTextInfo; textInfo = new TextInfo(); } return textInfo; } } //// //////////////////////////////////////////////////////////////////////// //// // //// // Equals //// // //// // Implements Object.Equals(). Returns a boolean indicating whether //// // or not object refers to the same CultureInfo as the current instance. //// // //// //////////////////////////////////////////////////////////////////////// //// //// //// public override bool Equals( Object value ) //// { //// if(Object.ReferenceEquals( this, value )) //// { //// return true; //// } //// //// CultureInfo that = value as CultureInfo; //// if(that != null) //// { //// // using CompareInfo to verify the data passed through the constructor //// // CultureInfo(String cultureName, String textAndCompareCultureName) //// //// return (this.Name.Equals( that.Name ) && this.CompareInfo.Equals( that.CompareInfo )); //// } //// //// return (false); //// } //// //// //// //////////////////////////////////////////////////////////////////////// //// // //// // GetHashCode //// // //// // Implements Object.GetHashCode(). Returns the hash code for the //// // CultureInfo. The hash code is guaranteed to be the same for CultureInfo A //// // and B where A.Equals(B) is true. //// // //// //////////////////////////////////////////////////////////////////////// //// //// //// public override int GetHashCode() //// { //// return this.Name.GetHashCode() + this.CompareInfo.GetHashCode(); //// } //// //// //// //////////////////////////////////////////////////////////////////////// //// // //// // ToString //// // //// // Implements Object.ToString(). Returns the name of the CultureInfo, //// // eg. "English (United States)". //// // //// //////////////////////////////////////////////////////////////////////// //// //// //// public override String ToString() //// { //// BCLDebug.Assert( m_name != null, "[CultureInfo.ToString]Always expect m_name to be set" ); //// return m_name; //// } public virtual Object GetFormat( Type formatType ) { if(formatType == typeof( NumberFormatInfo )) { return NumberFormat; } //// if(formatType == typeof( DateTimeFormatInfo )) //// { //// return DateTimeFormat; //// } return null; } //// internal static void CheckNeutral( CultureInfo culture ) //// { //// if(culture.IsNeutralCulture) //// { //// BCLDebug.Assert( culture.m_name != null, "[CultureInfo.CheckNeutral]Always expect m_name to be set" ); //// throw new NotSupportedException( Environment.GetResourceString( "Argument_CultureInvalidFormat", culture.m_name ) ); //// } //// } //// //// public virtual bool IsNeutralCulture //// { //// get //// { //// return this.m_cultureTableRecord.IsNeutralCulture; //// } //// } //// //// public CultureTypes CultureTypes //// { //// get //// { //// CultureTypes types = 0; //// //// if(m_cultureTableRecord.IsNeutralCulture) //// { //// types |= CultureTypes.NeutralCultures; //// } //// else //// { //// types |= CultureTypes.SpecificCultures; //// } //// //// if(m_cultureTableRecord.IsSynthetic) //// { //// types |= CultureTypes.WindowsOnlyCultures | CultureTypes.InstalledWin32Cultures; // Synthetic is installed culture too. //// } //// else //// { //// // Not Synthetic //// if(CultureTable.IsInstalledLCID( cultureID )) //// { //// types |= CultureTypes.InstalledWin32Cultures; //// } //// //// if(!m_cultureTableRecord.IsCustomCulture || m_cultureTableRecord.IsReplacementCulture) //// { //// types |= CultureTypes.FrameworkCultures; //// } //// } //// //// if(m_cultureTableRecord.IsCustomCulture) //// { //// types |= CultureTypes.UserCustomCulture; //// //// if(m_cultureTableRecord.IsReplacementCulture) //// { //// types |= CultureTypes.ReplacementCultures; //// } //// } //// //// return types; //// } //// } public virtual NumberFormatInfo NumberFormat { get { //// CultureInfo.CheckNeutral( this ); if(numInfo == null) { NumberFormatInfo temp = new NumberFormatInfo( this.m_cultureTableRecord ); temp.isReadOnly = m_isReadOnly; numInfo = temp; } return (numInfo); } set { //// VerifyWritable(); if(value == null) { #if EXCEPTION_STRINGS throw new ArgumentNullException( "value", Environment.GetResourceString( "ArgumentNull_Obj" ) ); #else throw new ArgumentNullException(); #endif } numInfo = value; } } //////////////////////////////////////////////////////////////////////// // // GetDateTimeFormatInfo // // Create a DateTimeFormatInfo, and fill in the properties according to // the CultureID. // //////////////////////////////////////////////////////////////////////// public virtual DateTimeFormatInfo DateTimeFormat { get { if(dateTimeInfo == null) { //// CultureInfo.CheckNeutral( this ); //// // Change the calendar of DTFI to the specified calendar of this CultureInfo. //// DateTimeFormatInfo temp = new DateTimeFormatInfo( this.m_cultureTableRecord, GetLangID( cultureID ), this.Calendar ); //// //// temp.m_isReadOnly = m_isReadOnly; //// //// System.Threading.Thread.MemoryBarrier(); //// //// dateTimeInfo = temp; dateTimeInfo = new DateTimeFormatInfo(); } return dateTimeInfo; } //// set //// { //// VerifyWritable(); //// if(value == null) //// { //// throw new ArgumentNullException( "value", Environment.GetResourceString( "ArgumentNull_Obj" ) ); //// } //// dateTimeInfo = value; //// } } //// public unsafe void ClearCachedData() //// { //// m_userDefaultUICulture = null; //// m_userDefaultCulture = null; //// //// RegionInfo.m_currentRegionInfo = null; //// //// TimeZone.ResetTimeZone(); //// //// // Delete the cached cultures. //// m_LcidCachedCultures = null; //// m_NameCachedCultures = null; //// m_IetfCachedCultures = null; //// //// CultureTableRecord.ResetCustomCulturesCache(); //// CompareInfo.ClearDefaultAssemblyCache(); //// } //// //// /*=================================GetCalendarInstance========================== //// **Action: Map a Win32 CALID to an instance of supported calendar. //// **Returns: An instance of calendar. //// **Arguments: calType The Win32 CALID //// **Exceptions: //// ** Shouldn't throw exception since the calType value is from our data table or from Win32 registry. //// ** If we are in trouble (like getting a weird value from Win32 registry), just return the GregorianCalendar. //// ============================================================================*/ //// internal static Calendar GetCalendarInstance( int calType ) //// { //// if(calType == Calendar.CAL_GREGORIAN) //// { //// return new GregorianCalendar(); //// } //// //// return GetCalendarInstanceRare( calType ); //// } //// //// //This function exists as a shortcut to prevent us from loading all of the non-gregorian //// //calendars unless they're required. //// internal static Calendar GetCalendarInstanceRare( int calType ) //// { //// BCLDebug.Assert( calType != Calendar.CAL_GREGORIAN, "calType!=Calendar.CAL_GREGORIAN" ); //// //// switch(calType) //// { //// case Calendar.CAL_GREGORIAN_US: // Gregorian (U.S.) calendar //// case Calendar.CAL_GREGORIAN_ME_FRENCH: // Gregorian Middle East French calendar //// case Calendar.CAL_GREGORIAN_ARABIC: // Gregorian Arabic calendar //// case Calendar.CAL_GREGORIAN_XLIT_ENGLISH: // Gregorian Transliterated English calendar //// case Calendar.CAL_GREGORIAN_XLIT_FRENCH: // Gregorian Transliterated French calendar //// return new GregorianCalendar( (GregorianCalendarTypes)calType ); //// //// case Calendar.CAL_TAIWAN: // Taiwan Era calendar //// return new TaiwanCalendar(); //// //// case Calendar.CAL_JAPAN: // Japanese Emperor Era calendar //// return new JapaneseCalendar(); //// //// case Calendar.CAL_KOREA: // Korean Tangun Era calendar //// return new KoreanCalendar(); //// //// case Calendar.CAL_HIJRI: // Hijri (Arabic Lunar) calendar //// return new HijriCalendar(); //// //// case Calendar.CAL_THAI: // Thai calendar //// return new ThaiBuddhistCalendar(); //// //// case Calendar.CAL_HEBREW: // Hebrew (Lunar) calendar //// return new HebrewCalendar(); //// //// case Calendar.CAL_PERSIAN: //// return new PersianCalendar(); //// //// case Calendar.CAL_UMALQURA: //// return new UmAlQuraCalendar(); //// //// case Calendar.CAL_CHINESELUNISOLAR: //// return new ChineseLunisolarCalendar(); //// //// case Calendar.CAL_JAPANESELUNISOLAR: //// return new JapaneseLunisolarCalendar(); //// //// case Calendar.CAL_KOREANLUNISOLAR: //// return new KoreanLunisolarCalendar(); //// //// case Calendar.CAL_TAIWANLUNISOLAR: //// return new TaiwanLunisolarCalendar(); //// } //// //// return new GregorianCalendar(); //// } //// //// //// /*=================================Calendar========================== //// **Action: Return/set the default calendar used by this culture. //// ** This value can be overridden by regional option if this is a current culture. //// **Returns: //// **Arguments: //// **Exceptions: //// ** ArgumentNull_Obj if the set value is null. //// ============================================================================*/ //// //// //// public virtual Calendar Calendar //// { //// get //// { //// if(calendar == null) //// { //// BCLDebug.Assert( this.m_cultureTableRecord.IOPTIONALCALENDARS.Length > 0, "this.m_cultureTableRecord.IOPTIONALCALENDARS.Length > 0" ); //// // Get the default calendar for this culture. Note that the value can be //// // from registry if this is a user default culture. //// int calType = this.m_cultureTableRecord.ICALENDARTYPE; //// //// Calendar newObj = GetCalendarInstance( calType ); //// //// System.Threading.Thread.MemoryBarrier(); //// //// newObj.SetReadOnlyState( m_isReadOnly ); //// //// calendar = newObj; //// } //// return calendar; //// } //// } //// //// /*=================================OptionCalendars========================== //// **Action: Return an array of the optional calendar for this culture. //// **Returns: an array of Calendar. //// **Arguments: //// **Exceptions: //// ============================================================================*/ //// //// //// public virtual Calendar[] OptionalCalendars //// { //// get //// { //// // //// // This property always returns a new copy of the calendar array. //// // //// int[] calID = this.m_cultureTableRecord.IOPTIONALCALENDARS; //// Calendar[] cals = new Calendar[calID.Length]; //// for(int i = 0; i < cals.Length; i++) //// { //// cals[i] = GetCalendarInstance( calID[i] ); //// } //// return cals; //// } //// } //// //// //// public bool UseUserOverride //// { //// get //// { //// return this.m_cultureTableRecord.UseUserOverride; //// } //// } //// //// public CultureInfo GetConsoleFallbackUICulture() //// { //// CultureInfo temp = m_consoleFallbackCulture; //// if(temp == null) //// { //// temp = GetCultureInfo( this.m_cultureTableRecord.SCONSOLEFALLBACKNAME ); //// //// temp.m_isReadOnly = true; //// //// m_consoleFallbackCulture = temp; //// } //// return temp; //// } //// //// //// public virtual Object Clone() //// { //// CultureInfo ci = (CultureInfo)MemberwiseClone(); //// //// ci.m_isReadOnly = false; //// //// if(!ci.IsNeutralCulture) //// { //// //If this is exactly our type, we can make certain optimizations so that we don't allocate NumberFormatInfo or DTFI unless //// //they've already been allocated. If this is a derived type, we'll take a more generic codepath. //// if(!m_isInherited) //// { //// if(dateTimeInfo != null) //// { //// ci.dateTimeInfo = (DateTimeFormatInfo)dateTimeInfo.Clone(); //// } //// if(numInfo != null) //// { //// ci.numInfo = (NumberFormatInfo)numInfo.Clone(); //// } //// //// } //// else //// { //// ci.DateTimeFormat = (DateTimeFormatInfo)this.DateTimeFormat.Clone(); //// ci.NumberFormat = (NumberFormatInfo )this.NumberFormat .Clone(); //// } //// } //// //// if(textInfo != null) //// { //// ci.textInfo = (TextInfo)textInfo.Clone(); //// } //// //// if(calendar != null) //// { //// ci.calendar = (Calendar)calendar.Clone(); //// } //// //// return ci; //// } //// //// //// public static CultureInfo ReadOnly( CultureInfo ci ) //// { //// if(ci == null) //// { //// throw new ArgumentNullException( "ci" ); //// } //// //// if(ci.IsReadOnly) //// { //// return ci; //// } //// //// CultureInfo info = (CultureInfo)ci.MemberwiseClone(); //// //// if(!ci.IsNeutralCulture) //// { //// //If this is exactly our type, we can make certain optimizations so that we don't allocate NumberFormatInfo or DTFI unless //// //they've already been allocated. If this is a derived type, we'll take a more generic codepath. //// if(!ci.m_isInherited) //// { //// if(ci.dateTimeInfo != null) //// { //// info.dateTimeInfo = DateTimeFormatInfo.ReadOnly( ci.dateTimeInfo ); //// } //// //// if(ci.numInfo != null) //// { //// info.numInfo = NumberFormatInfo.ReadOnly( ci.numInfo ); //// } //// //// } //// else //// { //// info.DateTimeFormat = DateTimeFormatInfo.ReadOnly( ci.DateTimeFormat ); //// info.NumberFormat = NumberFormatInfo .ReadOnly( ci.NumberFormat ); //// } //// } //// //// if(ci.textInfo != null) //// { //// info.textInfo = TextInfo.ReadOnly( ci.textInfo ); //// } //// //// if(ci.calendar != null) //// { //// info.calendar = Calendar.ReadOnly( ci.calendar ); //// } //// //// // Don't set the read-only flag too early. //// // We should set the read-only flag here. Otherwise, info.DateTimeFormat will not be able to set. //// info.m_isReadOnly = true; //// //// return info; //// } //// //// //// public bool IsReadOnly //// { //// get //// { //// return m_isReadOnly; //// } //// } //// //// private void VerifyWritable() //// { //// if(m_isReadOnly) //// { //// throw new InvalidOperationException( Environment.GetResourceString( "InvalidOperation_ReadOnly" ) ); //// } //// } //// //// // Helper function both both overloads of GetCachedReadOnlyCulture. If lcid is 0, we use the name. //// // If lcid is -1, use the altName and create one of those special SQL cultures. //// // If lcid is -2 we're looking for Ietf name //// internal static CultureInfo GetCultureInfoHelper( int lcid, string name, string altName ) //// { //// // retval is our return value. //// CultureInfo retval; //// //// // Temporary hashtable for the names. //// Hashtable tempNameHT = m_NameCachedCultures; //// //// if(name != null) //// { //// name = CultureTableRecord.AnsiToLower( name ); //// } //// //// if(altName != null) //// { //// altName = CultureTableRecord.AnsiToLower( altName ); //// } //// //// // We expect the same result for all 3 hashtables, but will test individually for added safety. //// if(tempNameHT == null) //// { //// tempNameHT = Hashtable.Synchronized( new Hashtable() ); //// } //// else //// { //// // If we are called by name, check if the object exists in the hashtable. If so, return it. //// if(lcid == -1) //// { //// retval = (CultureInfo)tempNameHT[name + '\xfffd' + altName]; //// if(retval != null) //// { //// return retval; //// } //// } //// else if(lcid == 0) //// { //// retval = (CultureInfo)tempNameHT[name]; //// if(retval != null) //// { //// return retval; //// } //// } //// } //// //// // Next, the Lcid table. //// Hashtable tempLcidHT = m_LcidCachedCultures; //// //// if(tempLcidHT == null) //// { //// // Case insensitive is not an issue here, save the constructor call. //// tempLcidHT = Hashtable.Synchronized( new Hashtable() ); //// } //// else //// { //// // If we were called by Lcid, check if the object exists in the table. If so, return it. //// if(lcid > 0) //// { //// retval = (CultureInfo)tempLcidHT[lcid]; //// if(retval != null) //// { //// return retval; //// } //// } //// } //// //// // Last the Ietf name table //// Hashtable tempIetfHT = m_IetfCachedCultures; //// //// if(tempIetfHT == null) //// { //// tempIetfHT = Hashtable.Synchronized( new Hashtable() ); //// } //// else //// { //// // If we wanted ietf name, then lcid is -2 //// if(lcid == -2) //// { //// retval = (CultureInfo)tempIetfHT[name]; //// if(retval != null) //// { //// return retval; //// } //// } //// } //// //// // We now have two temporary hashtables and the desired object was not found. //// // We'll construct it. We catch any exceptions from the constructor call and return null. //// try //// { //// switch(lcid) //// { //// case -2: //// { //// // -2 is Ietf name, map Ietf name to Culture name and get it by name //// String cultureName = CultureTableRecord.GetCultureNameFromIetfName( name ); //// if(cultureName == null) //// { //// return null; //// } //// //// retval = new CultureInfo( cultureName, false ); //// break; //// } //// //// case -1: //// // call the private constructor //// retval = new CultureInfo( name, altName ); //// break; //// //// case 0: //// retval = new CultureInfo( name, false ); //// break; //// //// default: //// //// // //// // checking the current culture first is a protection against recursion so the creation //// // code of CompareInfo is calling GetCultureInfo. //// // The recursion can happen if we have current user culture is replaced custom culture //// // and we are trying to create object for that culture and current user culture is not //// // stored in our cache. //// // //// //// if(m_userDefaultCulture != null && m_userDefaultCulture.LCID == lcid) //// { //// retval = (CultureInfo)m_userDefaultCulture.Clone(); //// retval.m_cultureTableRecord = retval.m_cultureTableRecord.CloneWithUserOverride( false ); //// } //// else //// { //// retval = new CultureInfo( lcid, false ); //// } //// break; //// } //// } //// catch(ArgumentException) //// { //// return null; //// } //// //// // Set it to read-only //// retval.m_isReadOnly = true; //// //// if(lcid == -1) //// { //// // This new culture will be added only to the name hash table. //// tempNameHT[name + '\xfffd' + altName] = retval; //// //// // when lcid == -1 then TextInfo object is already get created and we need to set it as read only. //// retval.TextInfo.SetReadOnlyState( true ); //// } //// else //// { //// // We add this new culture info object to all 3 hash tables. //// tempLcidHT[retval.LCID] = retval; //// //// // Remember our name (as constructed). Do NOT use alternate sort name versions because //// // we have internal state representing the sort. (So someone would get the wrong cached version) //// string newName = CultureTableRecord.AnsiToLower( retval.m_name ); //// //// tempNameHT[newName] = retval; //// //// newName = retval.IetfLanguageTag; //// if(newName != null) //// { //// newName = CultureTableRecord.AnsiToLower( newName ); //// tempIetfHT[newName] = retval; //// } //// //// if(lcid == -2 && !name.Equals( newName )) //// { //// tempIetfHT[name] = retval; //// } //// //// } //// //// // Copy the two hashtables to the corresponding member variables. This will potentially overwrite //// // new tables simultaneously created by a new thread, but maximizes thread safety. //// // If it was funky name we don't need to cache Ietf or LCID names. //// if(-1 != lcid) //// { //// // Only when we modify the lcid hash table, is there a need to overwrite. //// m_LcidCachedCultures = tempLcidHT; //// m_IetfCachedCultures = tempIetfHT; //// } //// //// m_NameCachedCultures = tempNameHT; //// //// // Finally, return our new CultureInfo object. //// return retval; //// } //// //// // Gets a cached copy of the specified culture from an internal hashtable (or creates it //// // if not found). //// public static CultureInfo GetCultureInfo( int culture ) //// { //// // Must check for -1 now since the helper function uses the value to signal //// // the altCulture code path for SQL Server. //// // Also check for zero as this would fail trying to add as a key to the hash. //// if(culture <= 0) //// { //// throw new ArgumentOutOfRangeException( "culture", Environment.GetResourceString( "ArgumentOutOfRange_NeedPosNum" ) ); //// } //// //// CultureInfo retval = GetCultureInfoHelper( culture, null, null ); //// if(retval == null) //// { //// throw new ArgumentException( Environment.GetResourceString( "Argument_CultureNotSupported", culture ), "culture" ); //// } //// //// return retval; //// } //// //// // Gets a cached copy of the specified culture from an internal hashtable (or creates it //// // if not found). //// public static CultureInfo GetCultureInfo( string name ) //// { //// // Make sure we have a valid, non-zero length string as name //// if(name == null) //// { //// throw new ArgumentNullException( "name" ); //// } //// //// CultureInfo retval = GetCultureInfoHelper( 0, name, null ); //// if(retval == null) //// { //// throw new ArgumentException( String.Format( CultureInfo.CurrentCulture, Environment.GetResourceString( "Argument_InvalidCultureName" ), name ), "name" ); //// } //// //// return retval; //// } //// //// // Gets a cached copy of the specified culture from an internal hashtable (or creates it //// // if not found). //// public static CultureInfo GetCultureInfo( string name, string altName ) //// { //// // Make sure we have a valid, non-zero length string as name //// if(name == null) //// { //// throw new ArgumentNullException( "name" ); //// } //// //// if(altName == null) //// { //// throw new ArgumentNullException( "altName" ); //// } //// //// CultureInfo retval = GetCultureInfoHelper( -1, name, altName ); //// if(retval == null) //// { //// throw new ArgumentException( //// String.Format( //// CultureInfo.CurrentCulture, //// Environment.GetResourceString( "Argument_OneOfCulturesNotSupported" ), //// name, //// altName ), //// "name" ); //// } //// //// return retval; //// } //// //// // Get a cached copy of the specified culture from ietf language tag. //// public static CultureInfo GetCultureInfoByIetfLanguageTag( string name ) //// { //// // Make sure we have a valid, non-zero length string as name //// if(name == null) //// { //// throw new ArgumentNullException( "name" ); //// } //// //// CultureInfo retval = GetCultureInfoHelper( -2, name, null ); //// if(retval == null) //// { //// throw new ArgumentException( //// String.Format( CultureInfo.CurrentCulture, Environment.GetResourceString( //// "Argument_CultureIetfNotSupported" ), name ), //// "name" ); //// } //// //// return retval; //// } //// //// // Looks for Ietf names in the registry. //// [ResourceExposure( ResourceScope.None )] //// [ResourceConsumption( ResourceScope.Machine, ResourceScope.Machine )] //// internal static string LookupIetfNameFromRegistry( string name ) //// { //// // Make sure our key is open //// if(m_ietfNameLookupKey == null) //// { //// m_ietfNameLookupKey = Registry.LocalMachine.OpenSubKey( ietfRegistryKey ); //// //// // If not present that's OK, we just won't find one. //// if(m_ietfNameLookupKey == null) //// { //// return null; //// } //// } //// //// // Look up our particular name to see if it works //// String realNames = m_ietfNameLookupKey.GetValue( name ) as string; //// //// if(String.IsNullOrEmpty( realNames )) //// { //// return null; //// } //// //// int iEndOfFirstName = realNames.IndexOf( ';' ); //// //// // If only one name then return it //// if(iEndOfFirstName < 0) //// { //// return realNames; //// } //// //// // If no first name, return null //// if(iEndOfFirstName == 0) //// { //// return null; //// } //// //// // Return just the first name //// return realNames.Substring( 0, iEndOfFirstName ); //// } } } ================================================ FILE: Zelig/Zelig/RunTime/Framework/mscorlib/System/Globalization/CultureTableRecord.cs ================================================ // ==++== // // Copyright (c) Microsoft Corporation. All rights reserved. // // ==--== namespace System.Globalization { using System; using System.IO; using System.Runtime.InteropServices; using System.Text; using System.Threading; using System.Runtime.CompilerServices; using System.Runtime.ConstrainedExecution; using System.Collections; ////using Microsoft.Win32.SafeHandles; using System.Collections.Generic; using System.Runtime.Serialization; ////using System.Runtime.Versioning; // Enum for the IFLAGS field [Flags] internal enum CultureFlags { IsSpecificCulture = 0x0001, } /*============================================================================= * * Data record for CultureInfo classes. Used by System.Globalization.CultureInfo. * * NOTE: ALL of the data table/user override/OS version, etc. hacks related to * the data should be in here. DTFI, CI, etc. should have NO knowledge * of eccentricities of the data store. * * ==============================================================================*/ // Only statics, does not need to be marked with the serializable attribute internal class CultureTableRecord { //// // For spanish sorting //// internal const int SPANISH_TRADITIONAL_SORT = 0x040a; //// private const int SPANISH_INTERNATIONAL_SORT = 0x0c0a; //// //// // Sizes defined by the RFC3066 spec //// private const int MAXSIZE_LANGUAGE = 8; //// private const int MAXSIZE_REGION = MAXSIZE_LANGUAGE; //// private const int MAXSIZE_SUFFIX = 8 * MAXSIZE_LANGUAGE; //// private const int MAXSIZE_FULLTAGNAME = MAXSIZE_LANGUAGE + MAXSIZE_REGION + MAXSIZE_SUFFIX + 4; // The 2 is for the tags and the prefix //// //// private static Object s_InternalSyncObject; //// private static Object InternalSyncObject //// { //// get //// { //// if(s_InternalSyncObject == null) //// { //// Object o = new Object(); //// Interlocked.CompareExchange( ref s_InternalSyncObject, o, null ); //// } //// return s_InternalSyncObject; //// } //// } //// //// // //// // CultureTableRecordCache caches all CultureTableRecord created objects except the objects created by //// // RegionInfo constructor which takes region name and instead will be cached in CultureTableRecordRegionCache //// // //// //// private static Hashtable CultureTableRecordCache; //// private static Hashtable CultureTableRecordRegionCache; //// //// // CultureTable this data refers to. //// private CultureTable m_CultureTable; //// private unsafe CultureTableData* m_pData; //// private unsafe ushort* m_pPool; //// private bool m_bUseUserOverride; //// private int m_CultureID; //// private String m_CultureName; //// //// private int m_ActualCultureID = 0; //// private string m_ActualName = null; //// //// // //// // m_synthetic will be true only if we have synthetic culture or synthetic replacement culture. //// private bool m_synthetic = false; //// //// private SafeNativeMemoryHandle nativeMemoryHandle; // //// private string m_windowsPath = null; //// //// private const int LOCALE_SLANGUAGE = 0x00000002; // localized name of language //// private const int LOCALE_SCOUNTRY = 0x00000006; // localized name of country //// private const int LOCALE_SNATIVELANGNAME = 0x00000004; // native name of language //// private const int LOCALE_SNATIVECTRYNAME = 0x00000008; // native name of country //// private const int LOCALE_ICALENDARTYPE = 0x00001009; // iCalendarType type of calendar //// //// //// //////////////////////////////////////////////////////////////////////// //// // //// // Create a CultureTable from the given custom/replacement culture name. //// // //// // SECURITY SECURITY SECURITY //// // Before call this function, call ValidateCulturePieceToLower() to verify //// // that the name does not contain illegal characters (such as "." or backslash. //// // //// //////////////////////////////////////////////////////////////////////// //// //// [ResourceExposure( ResourceScope.None )] //// [ResourceConsumption( ResourceScope.Machine, ResourceScope.Machine )] //// private unsafe CultureTable GetCustomCultureTable( string name ) //// { //// CultureTable cultureTable = null; //// //// string customCultureFile = GetCustomCultureFile( name ); //// if(customCultureFile == null) //// { //// return null; //// } //// //// try //// { //// cultureTable = new CultureTable( customCultureFile, false ); //// if(!cultureTable.IsValid) //// { //// // If we have invalid culture table then we have custom culture. in that case we'll try //// // to see if the culture name is one of the framework or synthetic cultures and then //// // try to create it otherwise we'll throw. //// //// String defaultTableActualName; //// int defaultTableCultureID; //// int defaultTableDataItem = CultureTable.Default.GetDataItemFromCultureName( //// name, out defaultTableCultureID, out defaultTableActualName ); //// //// if(defaultTableDataItem < 0) // not built in framework culture //// { //// } //// //// return null; // returning null means fallback to framework or synthetic culture. //// } //// } //// catch(FileNotFoundException) //// { //// // //// // getting here means custom culture file get unregistered/renamed from different AppDomain/Process. //// // just update the cache to point to the empty string as subsequent calls will not bother trying again. //// // //// cultureTable = null; //// } //// //// return cultureTable; //// } //// //// //////////////////////////////////////////////////////////////////////// //// // //// // Using the specified replacementCultureName, check if there is a replacment //// // culture file. If yes, return the CultureTable created from the custom culture file. //// // //// // Parameters //// // replacementCultureName: The culture name to check. Note that alternative sort like de-DE_phoneb should pass de-DE here. //// // [OUT] dataItem: The dataItem for the culture name in the custom culture file. //// // Returns //// // A valid CultureTable from the custom culture file. null, if the custom file can not be found or the dataItem can not be found. //// // //// //////////////////////////////////////////////////////////////////////// //// //// internal unsafe CultureTable TryCreateReplacementCulture( String replacementCultureName, out int dataItem ) //// { //// string name = ValidateCulturePieceToLower( replacementCultureName, "cultureName", MAXSIZE_FULLTAGNAME ); //// //// // Before call this function, call ValidateCulturePieceToLower() to verify //// // that the name does not contain illegal characters (such as "." or backslash. //// CultureTable cultureTable = GetCustomCultureTable( name ); //// //// if(cultureTable == null) //// { //// dataItem = -1; //// return (null); //// } //// // We have a replacement culture. Use it. //// int tempID; //// String tempName; //// dataItem = cultureTable.GetDataItemFromCultureName( name, out tempID, out tempName ); //// return (dataItem >= 0 ? cultureTable : null); //// } //// //// //// // //// // GetCultureTableRecord create CultureTableRecord object for specific culture name. //// // This method uses CultureTableRecordCache to make sure we don't have to create this //// // object if it is already created before. //// // //// //// internal static CultureTableRecord GetCultureTableRecord( string name, bool useUserOverride ) //// { //// BCLDebug.Assert( name != null, "[CultureTableRecord::GetCultureTableRecord] name should be valid." ); //// //// // Make sure the cache is valid. //// if(CultureTableRecordCache == null) //// { //// if(name.Length == 0) // Invariant culture //// { //// // First time Invariant culture get created we ignore creating the cache //// return new CultureTableRecord( name, useUserOverride ); //// } //// //// lock(InternalSyncObject) //// { //// if(CultureTableRecordCache == null) //// CultureTableRecordCache = new Hashtable(); //// } //// } //// //// name = ValidateCulturePieceToLower( name, "name", MAXSIZE_FULLTAGNAME ); //// //// CultureTableRecord[] cultureRecordArray = (CultureTableRecord[])CultureTableRecordCache[name]; //// if(cultureRecordArray != null) //// { //// int index = useUserOverride ? 0 : 1; //// //// if(cultureRecordArray[index] == null) //// { //// int filled = index == 0 ? 1 : 0; //// cultureRecordArray[index] = (CultureTableRecord)cultureRecordArray[filled].CloneWithUserOverride( useUserOverride ); //// } //// //// return cultureRecordArray[index]; //// } //// //// CultureTableRecord cultureRecord = new CultureTableRecord( name, useUserOverride ); //// lock(InternalSyncObject) //// { //// if(CultureTableRecordCache[name] == null) //// { //// cultureRecordArray = new CultureTableRecord[2]; //// cultureRecordArray[useUserOverride ? 0 : 1] = cultureRecord; //// CultureTableRecordCache[name] = cultureRecordArray; //// } //// } //// //// return cultureRecord; //// } //// //// // //// // GetCultureTableRecord create CultureTableRecord object for specific culture Id. //// // This method convert the culture Id to culture name and then uses GetCultureTableRecord //// // to get the CultureTableRecord object. //// // //// //// internal static CultureTableRecord GetCultureTableRecord( int cultureId, bool useUserOverride ) //// { //// if(cultureId == CultureInfo.LOCALE_INVARIANT) //// return GetCultureTableRecord( "", false ); //// //// String name = null; //// if(CultureTable.Default.GetDataItemFromCultureID( cultureId, out name ) < 0) //// { //// } //// //// if(name != null && name.Length > 0) // GetDataItemFromCultureID can set the name to empty string. //// { //// return GetCultureTableRecord( name, useUserOverride ); //// } //// //// throw new ArgumentException( //// String.Format( //// CultureInfo.CurrentCulture, //// Environment.GetResourceString( "Argument_CultureNotSupported" ), cultureId ), "culture" ); //// } //// //// // //// // GetCultureTableRecordForRegion create CultureTableRecord object for specific region name. //// // this method do the following //// // o try to get the object from the cache. if found then return otherwise try to create it. //// // o it try to get the record from the framework culture table. if found it then create //// // the CultureTableRecord object and store it in the cache then return. //// // o call GetCultureTableRecord to get the object. if found it then store it in the cache //// // and return. notice that GetCultureTableRecord will try the custom culture then synthetic //// // culture. //// // o otherwise we'll throw ArgumentException. //// // //// //// internal static CultureTableRecord GetCultureTableRecordForRegion( string regionName, bool useUserOverride ) //// { //// BCLDebug.Assert( regionName != null, "[CultureTableRecord::GetCultureTableRecordForRegion] regionName should be valid." ); //// //// // Make sure the cache is valid. //// if(CultureTableRecordRegionCache == null) //// { //// lock(InternalSyncObject) //// { //// if(CultureTableRecordRegionCache == null) //// CultureTableRecordRegionCache = new Hashtable(); //// } //// } //// //// regionName = ValidateCulturePieceToLower( regionName, "regionName", MAXSIZE_FULLTAGNAME ); //// //// CultureTableRecord[] cultureRecordArray = (CultureTableRecord[])CultureTableRecordRegionCache[regionName]; //// if(cultureRecordArray != null) //// { //// int index = useUserOverride ? 0 : 1; //// if(cultureRecordArray[index] == null) //// { //// cultureRecordArray[index] = cultureRecordArray[index == 0 ? 1 : 0].CloneWithUserOverride( useUserOverride ); //// } //// return cultureRecordArray[index]; //// } //// //// int dataItem = CultureTable.Default.GetDataItemFromRegionName( regionName ); //// //// CultureTableRecord cultureRecord = null; //// //// if(dataItem > 0) //// { //// cultureRecord = new CultureTableRecord( regionName, dataItem, useUserOverride ); //// } //// else //// { //// try //// { //// cultureRecord = GetCultureTableRecord( regionName, useUserOverride ); //// } //// catch(ArgumentException) //// { //// throw new ArgumentException( //// String.Format( //// CultureInfo.CurrentCulture, //// Environment.GetResourceString( "Argument_InvalidRegionName" ), regionName ), "name" ); //// } //// } //// //// BCLDebug.Assert( cultureRecord != null, "[CultureTableRecord::GetCultureTableRecordForRegion] cultureRecord should be valid." ); //// lock(InternalSyncObject) //// { //// if(CultureTableRecordRegionCache[regionName] == null) //// { //// cultureRecordArray = new CultureTableRecord[2]; //// cultureRecordArray[useUserOverride ? 0 : 1] = cultureRecord.CloneWithUserOverride( useUserOverride ); //// CultureTableRecordRegionCache[regionName] = cultureRecordArray; //// } //// } //// //// return cultureRecord; //// } //// //// // //// // This constructor used only to create a Framework culture. it doesn't create custom //// // culture nor synthetic culture. //// // This is used when requesting the native calendar name for a custom culture with //// // empty string native calendar name. //// // //// internal unsafe CultureTableRecord( int cultureId, bool useUserOverride ) //// { //// this.m_bUseUserOverride = useUserOverride; //// //// int defaultTableDataItem = CultureTable.Default.GetDataItemFromCultureID( cultureId, out m_ActualName ); //// if(defaultTableDataItem < 0) //// { //// throw new ArgumentException( //// String.Format( //// CultureInfo.CurrentCulture, //// Environment.GetResourceString( "Argument_CultureNotSupported" ), cultureId ), "culture" ); //// } //// //// m_ActualCultureID = cultureId; //// m_CultureTable = CultureTable.Default; //// //// m_pData = (CultureTableData*)(m_CultureTable.m_pItemData + m_CultureTable.m_itemSize * defaultTableDataItem); //// m_pPool = m_CultureTable.m_pDataPool; //// //// m_CultureName = SNAME; //// m_CultureID = (cultureId == SPANISH_TRADITIONAL_SORT) ? cultureId : ILANGUAGE; //// //// BCLDebug.Assert( !IsCustomCulture, "[CultureTableRecord::ctor] we shouldn't have custom culture." ); //// BCLDebug.Assert( !IsSynthetic, "[CultureTableRecord::ctor] we shouldn't have synthetic culture." ); //// } //// //// // //// // m_bUseUserOverride indicates that if we need to check for user-override values for this CultureInfo instance. //// // For the user default culture of the system, user can choose to override some of the values //// // associated with that culture. For example, the default short-date format for en-US is //// // "M/d/yyyy", however, one may change it to "dd/MM/yyyy" from the Regional Option in //// // the control panel. //// // So when a CultureInfo is created, one can specify if the create CultureInfo should check //// // for user-override values, or should always get the default values. //// // //// // //// // AVOID USING P/INVOKE IN THIS CODEPATH. //// // AVOID USING P/INVOKE IN THIS CODEPATH. //// // AVOID USING P/INVOKE IN THIS CODEPATH. //// // //// // P/Invoke will cause COM to be initialized and sets the thread apartment model. Since CultureInfo is used early in the CLR process, //// // this will prevent Loader from having a chance to look at the executable and setting the apartment model to the one the application wants. //// //// //// //// // //// // Search order for creating a culture. //// // //// //// /* //// First, search by name //// if this is a known culture name from culture.nlp, and it is an alternative sort name (such as de-DE_phoneb) //// { //// Get the name from the LANGID by removing the sort ID (so the name becomes de-DE). //// This is the name used for search replacment culture. //// } //// //// Check if this specified name has a custom/replacement culture file. //// if there is a custom/replacement culture file //// { //// // This is a custom culture, or a replacement culture. //// return; [CUSTOM/REPLACEMENT CULTURE (.NET CULTURE/SYNTHETIC CULTURE) FOUND BY NAME] //// } //// From culture.nlp, check if tihs is a vlid culture name //// if this is a valid culture name //// { //// // This is a .NET culture. //// return; [NON-REPLACEMENT .NET CULTURE FOUND BY NAME] //// } //// Check if this is a valid name from synthetic culture //// if this is a valid synthetic culture name //// { //// // This is a synthetic culture. Set the cultureID, so we will //// // create it when we search by LCID later. //// // [SYNTHETIC CULTURE FOUND BY NAME] //// } else //// { //// throw exception; [INVALID NAME] //// } //// Then Search by LCID //// we'll come here only if the lcid is filled with synthetic culture Id. //// // This is synthetic culture. //// Get the name for this LANGID of this synthetic LCID. //// if there is a replacement culture for this LCID by checking name. //// { //// Use it and return the replacement culture for synthetic culture. //// return; [REPLACEMENT SYNTHETIC CULTURE] //// } //// Init and return the synthetic culture. //// return; [NON-REPLACEMENT SYNTHETIC CULTURE] //// //// } //// otherwise throw exception //// //// */ //// // //// // * IMPORTANT * cultureName should be in lower case. //// // //// private unsafe CultureTableRecord( String cultureName, bool useUserOverride ) //// { //// BCLDebug.Assert( cultureName != null, "[CultureTableRecord::ctor] cultureName should be valid." ); //// //// int cultureID = 0; //// //// // Special case for invariant name //// if(cultureName.Length == 0) //// { //// useUserOverride = false; //// cultureID = CultureInfo.LOCALE_INVARIANT; //// } //// //// this.m_bUseUserOverride = useUserOverride; //// //// // We prefer to look up by name (if available) //// int iDataItem = -1; //// if(cultureName.Length > 0) //// { //// // Check if this is an alternative sort name. //// String defaultTableActualName; //// int defaultTableCultureID; //// string name = cultureName; //// int defaultTableDataItem = CultureTable.Default.GetDataItemFromCultureName( name, out defaultTableCultureID, out defaultTableActualName ); //// if(defaultTableDataItem >= 0 && //// (CultureInfo.GetSortID( defaultTableCultureID ) > 0 || defaultTableCultureID == SPANISH_TRADITIONAL_SORT)) //// { //// String replacmentCultureName; //// //// int nonSortId; //// if(defaultTableCultureID == SPANISH_TRADITIONAL_SORT) //// nonSortId = SPANISH_INTERNATIONAL_SORT; //// else //// nonSortId = CultureInfo.GetLangID( defaultTableCultureID ); //// //// // This is an alternative sort culture. //// if(CultureTable.Default.GetDataItemFromCultureID( nonSortId, out replacmentCultureName ) >= 0) //// { //// // This is the replacement culture name for an alternative sort. //// name = ValidateCulturePieceToLower( replacmentCultureName, "cultureName", MAXSIZE_FULLTAGNAME ); //// } //// } //// //// // If the compatibility flag is defined and culture is replacemet culture then we don't //// // open the custom culture file. instead we'll try to get framework/OS culture. //// if(!Environment.GetCompatibilityFlag( CompatibilityFlag.DisableReplacementCustomCulture ) || //// IsCustomCultureId( defaultTableCultureID )) //// { //// //// // we always try the replacement custom cultures first. //// // Before call this function, call ValidateCulturePieceToLower() to verify //// // that the name does not contain illegal characters (such as "." or backslash. //// m_CultureTable = GetCustomCultureTable( name ); //// } //// //// if(m_CultureTable != null) //// { //// // //// // [CUSTOM/REPLACEMENT CULTURE (.NET CULTURE/SYNTHETIC CULTURE) FOUND BY NAME] //// // //// iDataItem = this.m_CultureTable.GetDataItemFromCultureName( name, out this.m_ActualCultureID, out this.m_ActualName ); //// if(defaultTableDataItem >= 0) //// { //// // This is a replacment culture (since defaultTableDataItem >= 0), use the default ID/Name from the table. //// // For de-DE_phoneb, this will set the the actualCultureID to be 0x10407, instead of the LCID for replacment cutlure 0x0407. //// this.m_ActualCultureID = defaultTableCultureID; //// this.m_ActualName = defaultTableActualName; //// } //// } //// //// if(iDataItem < 0 && defaultTableDataItem >= 0) //// { //// // //// // [NON-REPLACEMENT .NET CULTURE FOUND BY NAME] //// // //// this.m_CultureTable = CultureTable.Default; //// this.m_ActualCultureID = defaultTableCultureID; //// this.m_ActualName = defaultTableActualName; //// iDataItem = defaultTableDataItem; //// } //// } //// //// // If we couldn't get it by name, try culture ID. //// if(iDataItem < 0 && cultureID > 0) //// { //// if(cultureID == CultureInfo.LOCALE_INVARIANT) //// { //// // Special case for the Invariant culture. //// iDataItem = CultureTable.Default.GetDataItemFromCultureID( cultureID, out this.m_ActualName ); //// if(iDataItem > 0) //// { //// m_ActualCultureID = cultureID; //// m_CultureTable = CultureTable.Default; //// } //// } //// } //// //// // If we found one, use it and return //// if(iDataItem >= 0) //// { //// // Found it, use it //// this.m_pData = (CultureTableData*)(this.m_CultureTable.m_pItemData + //// this.m_CultureTable.m_itemSize * iDataItem); //// this.m_pPool = this.m_CultureTable.m_pDataPool; //// // Use name & ID from the file ('cept spanish traditional, which has to stay the same) //// this.m_CultureName = this.SNAME; //// this.m_CultureID = (m_ActualCultureID == SPANISH_TRADITIONAL_SORT) ? m_ActualCultureID : this.ILANGUAGE; //// //// return; //// } //// //// // Error, if we have a name throw that name //// if(cultureName != null) //// throw new ArgumentException( //// String.Format( //// CultureInfo.CurrentCulture, //// Environment.GetResourceString( "Argument_InvalidCultureName" ), cultureName ), "name" ); //// //// // No name, throw the LCID //// throw new ArgumentException( //// String.Format( //// CultureInfo.CurrentCulture, //// Environment.GetResourceString( "Argument_CultureNotSupported" ), cultureID ), "culture" ); //// } //// //// // //// // this constructor will create the CultureTableRecord object and point to the //// // culture table at the slot dataItem. //// // //// //// private unsafe CultureTableRecord( string regionName, int dataItem, bool useUserOverride ) //// { //// BCLDebug.Assert( regionName != null && regionName.Length > 0, //// "[CultureTableRecord.CultureTableRecord(regionName,bool)]Expected non-null/empty name" ); //// //// BCLDebug.Assert( dataItem > 0, "[CultureTableRecord.CultureTableRecord(regionName, dataItem, bool)] dataItem > 0 should be true." ); //// //// // Assuming it works we'll want these //// this.m_bUseUserOverride = useUserOverride; //// this.m_CultureName = regionName; //// this.m_CultureTable = CultureTable.Default; //// //// // Found it, use it //// this.m_pData = (CultureTableData*)(this.m_CultureTable.m_pItemData + //// this.m_CultureTable.m_itemSize * dataItem); //// this.m_pPool = this.m_CultureTable.m_pDataPool; //// //// // Use ID from the file //// this.m_CultureID = this.ILANGUAGE; //// } //// //// //// internal static void ResetCustomCulturesCache() //// { //// } //// //// //// private String WindowsPath //// { //// [ResourceExposure( ResourceScope.Machine )] //// [ResourceConsumption( ResourceScope.Machine )] //// get //// { //// if(m_windowsPath == null) //// { //// m_windowsPath = CultureInfo.nativeGetWindowsDirectory(); //// } //// return (m_windowsPath); //// } //// } //// //// /*--------------------------------------------------------- //// * //// * Gets a filename of a custom culture covered by the given string. //// * //// * Builds a cache of items found (adding String.Empty for files that are not present) //// * to avoid hitting the disk repeatedly. //// * //// *--------------------------------------------------------*/ //// [ResourceExposure( ResourceScope.None )] //// [ResourceConsumption( ResourceScope.Machine, ResourceScope.Machine )] //// private string GetCustomCultureFile( string name ) //// { //// return (null); //// } //// //// /*--------------------------------------------------------- //// * //// * Validate a culture name -- throws if it is not valid. If it is valid, return //// * the lowercase version of it, suitable for later caching. //// * //// *--------------------------------------------------------*/ //// private static string ValidateCulturePieceToLower( string testString, string paramName, int maxLength ) //// { //// if(testString.Length > maxLength) //// { //// throw new ArgumentException( //// String.Format( CultureInfo.CurrentCulture, Environment.GetResourceString( "Argument_NameTooLong" ), testString, maxLength ), paramName ); //// } //// //// StringBuilder sb = new StringBuilder( testString.Length ); //// //// for(int ich = 0; ich < testString.Length; ich++) //// { //// char ch = testString[ich]; //// //// if(ch <= 'Z' && ch >= 'A') //// { //// sb.Append( (char)(ch - 'A' + 'a') ); //// } //// else if(((ch <= 'z' && ch >= 'a') || //// (ch <= '9' && ch >= '0') || //// (ch == '_') || //// (ch == '-'))) //// { //// sb.Append( ch ); //// } //// else //// { //// throw new ArgumentException( //// String.Format( CultureInfo.CurrentCulture, Environment.GetResourceString( "Argument_NameContainsInvalidCharacters" ), testString ), paramName ); //// } //// } //// //// return (sb.ToString()); //// //// } //// //// internal static string AnsiToLower( string testString ) //// { //// StringBuilder sb = new StringBuilder( testString.Length ); //// //// for(int ich = 0; ich < testString.Length; ich++) //// { //// char ch = testString[ich]; //// sb.Append( ch <= 'Z' && ch >= 'A' ? (char)(ch - 'A' + 'a') : ch ); //// } //// //// return (sb.ToString()); //// } //// //// //========================GetCultureNameFromIetfName============================ //// //Action: Given an ietf name, get the corresponding culture name. //// //Returns: The culture name or null if not valid. //// //Arguments: //// // name culture name //// //Note: The passed name should be in lower case. //// //Exceptions: //// //============================================================================== //// unsafe internal static String GetCultureNameFromIetfName( String name ) //// { //// BCLDebug.Assert( name != null, "CultureTable.GetCultureNameFromIetfName(): name!=null" ); //// string actualName = null; //// //// // First check our default table to see if it exists there //// actualName = CultureTable.Default.LookupIetfName( name ); //// //// return actualName; //// } //// //// internal static string LookupIetfNameFromSynthetic( string name ) //// { //// string cultureName = null; //// return cultureName; //// } //// //// // //// internal bool IsSynthetic { get { return m_synthetic; } } //// //// internal bool IsCustomCulture //// { //// get //// { //// // If we came from the assembly we aren't custom //// return !(this.m_CultureTable.fromAssembly); //// } //// } //// //// internal bool IsReplacementCulture //// { //// get //// { //// return (this.IsCustomCulture && !IsCustomCultureId( m_CultureID )); //// } //// } //// //// internal int CultureID //// { //// get //// { //// BCLDebug.Assert( this.m_CultureID > 0, "[CultureTableRecord.CultureID]unexpected m_CultureId" ); //// return this.m_CultureID; //// } //// } //// //// internal String CultureName //// { //// get //// { //// BCLDebug.Assert( this.m_CultureName != null, "[CultureTableRecord.CultureName]unexpected m_CultureName" ); //// return this.m_CultureName; //// } //// //// set //// { //// BCLDebug.Assert( value != null, "[CultureTableRecord.CultureName]Expected non-null value for culture name" ); //// this.m_CultureName = value; //// } //// } //// //// internal bool UseUserOverride //// { //// get //// { //// return this.m_bUseUserOverride; //// } //// } //// //// // A property to indicate if we should retrieve information by calling the Win32 GetLocaleInfo(). //// //// internal unsafe bool UseGetLocaleInfo //// { //// get //// { //// if(!this.m_bUseUserOverride) //// { //// return (false); //// } //// int lcid; //// CultureInfo.nativeGetUserDefaultLCID( &lcid, CultureInfo.LOCALE_USER_DEFAULT ); //// //// if(ActualCultureID == CultureInfo.LOCALE_CUSTOM_UNSPECIFIED && //// lcid == CultureInfo.LOCALE_CUSTOM_DEFAULT) //// { //// if(SNAME.Equals( CultureInfo.nativeGetCultureName( lcid, true, false ) )) //// { //// return true; //// } //// return false; //// } //// //// return (this.ActualCultureID == lcid); //// } //// } //// //// // A method to check if we can use the Win32 GetLocaleInfo() for the specified locale and the specified calenar in this CultureTableRecord. //// // It will be true when all of the following are true: //// // * UseUserOverride is true //// // * UseGetLocaleInfo is true (which means the specified locale is the current user default locale. //// // * The specified calendar is the current calendar in the user default locale. //// // Parameters: //// // calID: The calendar ID to be checked. //// internal unsafe bool UseCurrentCalendar( int calID ) //// { //// return (UseGetLocaleInfo && CultureInfo.nativeGetCurrentCalendar() == calID); //// } //// //// //// internal bool IsValidSortID( int sortID ) //// { //// BCLDebug.Assert( sortID >= 0 && sortID <= 0xffff, "sortID is invalid" ); // SortID is 16-bit positive integer. //// if(sortID == 0 || //// (this.SALTSORTID != null && //// this.SALTSORTID.Length >= sortID && //// this.SALTSORTID[sortID - 1].Length != 0)) //// { //// return true; //// } //// else //// { //// return false; //// } //// } //// //// internal CultureTableRecord CloneWithUserOverride( bool userOverride ) //// { //// if(m_bUseUserOverride == userOverride) //// return this; //// //// CultureTableRecord cultureTableRecord = (CultureTableRecord)this.MemberwiseClone(); //// cultureTableRecord.m_bUseUserOverride = userOverride; //// //// return cultureTableRecord; //// } //// //// // //// // CultureNativeDisplayName called when we need to get the native display name for the culture //// // from Win32 side. we need to do that in cases like synthetic cultures. //// // //// //// internal unsafe string CultureNativeDisplayName //// { //// get //// { //// int lcid; //// CultureInfo.nativeGetUserDefaultUILanguage( &lcid ); //// //// if(CultureInfo.GetLangID( lcid ) == CultureInfo.GetLangID( CultureInfo.CurrentUICulture.LCID )) //// { //// string localizedLanguageName = CultureInfo.nativeGetLocaleInfo( m_ActualCultureID, LOCALE_SLANGUAGE ); //// if(localizedLanguageName != null) //// { //// // check for null terminated character. //// if(localizedLanguageName[localizedLanguageName.Length - 1] == '\u0000') //// return localizedLanguageName.Substring( 0, localizedLanguageName.Length - 1 ); //// else //// return localizedLanguageName; //// } //// } //// //// return this.SNATIVEDISPLAYNAME; //// } //// } //// //// // //// // RegionNativeDisplayName called when we need to get the native display name for the region //// // from Win32 side. we need to do that in cases like synthetic cultures. //// // //// //// internal unsafe string RegionNativeDisplayName //// { //// get //// { //// int lcid; //// CultureInfo.nativeGetUserDefaultUILanguage( &lcid ); //// //// if(CultureInfo.GetLangID( lcid ) == CultureInfo.GetLangID( CultureInfo.CurrentUICulture.LCID )) //// { //// string localizedCountryName = CultureInfo.nativeGetLocaleInfo( m_ActualCultureID, LOCALE_SCOUNTRY ); //// if(localizedCountryName != null) //// { //// if(localizedCountryName[localizedCountryName.Length - 1] == '\u0000') //// return localizedCountryName.Substring( 0, localizedCountryName.Length - 1 ); //// else //// return localizedCountryName; //// } //// } //// //// return this.SNATIVECOUNTRY; //// } //// } //// //// //////////////////////////////////////////////////////////////////////// //// // //// // Equals //// // //// // Implements Object.Equals(). Returns a boolean indicating whether //// // or not object refers to the same CultureTableRecord as the current instance. //// // //// //////////////////////////////////////////////////////////////////////// //// public override unsafe bool Equals( Object value ) //// { //// CultureTableRecord that = value as CultureTableRecord; //// return (that != null) && //// (this.m_pData == that.m_pData && //// this.m_bUseUserOverride == that.m_bUseUserOverride && //// this.m_CultureID == that.m_CultureID && //// CultureInfo.InvariantCulture.CompareInfo.Compare( //// this.m_CultureName, that.m_CultureName, CompareOptions.IgnoreCase ) == 0 && //// this.m_CultureTable.Equals( that.m_CultureTable ) //// ); //// } //// //// //////////////////////////////////////////////////////////////////////// //// // //// // GetHashCode //// // //// // Implements Object.GetHashCode(). Returns the hash code for the //// // CultureInfo. The hash code is guaranteed to be the same for RegionInfo //// // A and B where A.Equals(B) is true. //// // //// //////////////////////////////////////////////////////////////////////// //// public override int GetHashCode() //// { //// //This doesn't tell apart user override from non-user override //// if(!IsCustomCultureId( m_CultureID )) //// return (this.m_CultureID); //// //// return (this.m_CultureName.GetHashCode()); //// } //// //// // Get a String //// private unsafe String GetString( uint iOffset ) //// { //// char* pCharValues = unchecked( (char*)(this.m_pPool + iOffset) ); //// // For null strings, iOffset, pPool[0] and pPool[1] are all three 0. //// // The previous implimentation used [1] to test and I was afraid to change it. //// if(pCharValues[1] == 0) //// { //// BCLDebug.Assert( iOffset == 0, //// "[CultureTableRecord.GetString]Expected empty strings to have 0 offset" ); //// return String.Empty; //// } //// return new String( pCharValues + 1, 0, (int)pCharValues[0] ); //// } //// //// private int InteropLCID //// { //// get //// { //// return ActualCultureID == CultureInfo.LOCALE_CUSTOM_UNSPECIFIED ? //// CultureInfo.LOCALE_CUSTOM_DEFAULT : ActualCultureID; //// } //// } //// //// private String GetOverrideString( uint iOffset, int iWindowsFlag ) //// { //// return GetString( iOffset ); //// } //// //// private unsafe String[] GetStringArray( uint iOffset ) //// { //// if(iOffset == 0) return new String[0]; //// //// // The offset value is in char, and is related to the begining of string pool. //// ushort* pCount = m_pPool + iOffset; //// int count = (int)pCount[0]; // The number of strings in the array //// BCLDebug.Assert( count != 0, //// "[CultureTableRecord.GetStringArray]Expected non-zero length array" ); //// String[] values = new String[count]; //// //// // Get past count and cast to uint //// uint* pStringArray = (uint*)(pCount + 1); //// //// // Get our strings //// for(int i = 0; i < count; i++) //// values[i] = GetString( pStringArray[i] ); //// //// return (values); //// } //// //// // Get first string in this array of strings //// private unsafe String GetStringArrayDefault( uint iOffset ) //// { //// if(iOffset == 0) //// return String.Empty; //// //// // The offset value is in char, and is related to the begining of string pool. //// ushort* pCount = m_pPool + iOffset; //// BCLDebug.Assert( pCount[0] != 0, //// "[CultureTableRecord.GetStringArrayDefault]Expected non-zero length array" ); //// //// // Get past count and cast to uint //// uint* pStringArray = (uint*)(pCount + 1); //// //// // We had strings, return the first one //// return GetString( pStringArray[0] ); //// } //// //// // Get the user override or the first array of this string array //// private String GetOverrideStringArrayDefault( uint iOffset, int iWindowsFlag ) //// { //// // If override wasn't available, return the table version //// return GetStringArrayDefault( iOffset ); //// } //// //// private ushort GetOverrideUSHORT( ushort iData, int iWindowsFlag ) //// { //// return iData; //// } //// //// private unsafe int[] GetWordArray( uint iData ) //// { //// if(iData == 0) //// return new int[0]; //// //// ushort* pWord = this.m_pPool + iData; //// int count = (int)pWord[0]; // The number of words in the array //// BCLDebug.Assert( count != 0, //// "[CultureTableRecord.GetWordArray]Expected non-zero length array" ); //// //// int[] values = new int[count]; //// pWord++; // Get past count //// for(int i = 0; i < count; i++) //// { //// values[i] = pWord[i]; //// } //// return (values); //// } //// //// private int[] GetOverrideGrouping( uint iData, int iWindowsFlag ) //// { //// // No Override, use it from the tables. //// return GetWordArray( iData ); //// } //// //// // The actual LCID, used when a name lookup leads to a custom sort (thus //// // 'de-DE-deudi' will be 0x10407 rather than the plain old 0x0407 of 'de-DE'). //// internal int ActualCultureID //// { //// get //// { //// if(0 == this.m_ActualCultureID) //// { //// this.m_ActualCultureID = this.ILANGUAGE; //// } //// //// return (this.m_ActualCultureID); //// } //// } //// //// // The actual name, used when an LCID lookup leads to a custom sort (thus will be //// // 0x10407 will be 'de-DE-deudi' rather than the plain old 'de-DE' of 0x0407). //// internal string ActualName //// { //// get //// { //// if(null == this.m_ActualName) //// { //// this.m_ActualName = this.SNAME; //// } //// //// return (this.m_ActualName); //// } //// } //// //// internal bool IsNeutralCulture //// { //// get //// { //// return ((IFLAGS & (ushort)CultureFlags.IsSpecificCulture) == 0); //// } //// } //// //// //////////////////////////////////////////////////////////////////////// //// // //// // All the accessors //// // //// // Accessors for our data object items //// // //// //////////////////////////////////////////////////////////////////////// //// //// // These ones allow user override //// // Integers //// internal unsafe ushort IDIGITS { get { return (this.m_pData->iDigits); } } // (user can override) number of fractional digits //// internal unsafe ushort INEGNUMBER { get { return (this.m_pData->iNegativeNumber); } } // (user can override) negative number format //// internal unsafe ushort ICURRDIGITS { get { return (this.m_pData->iCurrencyDigits); } } // (user can override) # local monetary fractional digits //// internal unsafe ushort ICURRENCY { get { return (this.m_pData->iCurrency); } } // (user can override) positive currency format //// internal unsafe ushort INEGCURR { get { return (this.m_pData->iNegativeCurrency); } } // (user can override) negative currency format //// // internal unsafe ushort ILEADINGZEROS { get { return GetOverrideUSHORT(this.m_pData->iLEADINGZEROS, CultureTableData.LOCALE_ILEADINGZEROS); } } // (user can override) leading zeros 0 leading zeros, 1 ading zeros //// internal unsafe ushort ICALENDARTYPE //// { //// get //// { //// return ((ushort)IOPTIONALCALENDARS[0]); //// } //// } //// internal unsafe ushort IFIRSTWEEKOFYEAR { get { return GetOverrideUSHORT( this.m_pData->iFirstWeekOfYear, CultureTableData.LOCALE_IFIRSTWEEKOFYEAR ); } } // (user can override) first week of year //// // internal unsafe ushort ICOUNTRY { get { return GetOverrideUSHORT(this.m_pData->iCOUNTRY, CultureTableData.LOCALE_ICOUNTRY); } } // (user can override) country code (RegionInfo) //// internal unsafe ushort IMEASURE { get { return GetOverrideUSHORT( this.m_pData->iMeasure, CultureTableData.LOCALE_IMEASURE ); } } // (user can override) system of measurement 0ric, 1(RegionInfo) //// internal unsafe ushort IDIGITSUBSTITUTION { get { return GetOverrideUSHORT( this.m_pData->iDigitSubstitution, CultureTableData.LOCALE_IDIGITSUBSTITUTION ); } } // (user can override) Digit substitution 0text, 1e/arabic, 2ive/national (2 seems to be unused) //// //// // Grouping //// internal unsafe int[] SGROUPING { get { return GetOverrideGrouping( this.m_pData->waGrouping, CultureTableData.LOCALE_SGROUPING ); } } // (user can override) grouping of digits //// internal unsafe int[] SMONGROUPING { get { return GetOverrideGrouping( this.m_pData->waMonetaryGrouping, CultureTableData.LOCALE_SMONGROUPING ); } } // (user can override) monetary grouping of digits //// //// // Strings //// internal unsafe String SLIST { get { return GetOverrideString( this.m_pData->sListSeparator, CultureTableData.LOCALE_SLIST ); } } // (user can override) list Separator //// internal unsafe String SDECIMAL { get { return GetString( this.m_pData->sDecimalSeparator ); } } // (user can override) decimal Separator //// internal unsafe String STHOUSAND { get { return GetString( this.m_pData->sThousandSeparator ); } } // (user can override) thousands Separator //// internal unsafe String SCURRENCY { get { return GetString( this.m_pData->sCurrency ); } } // (user can override) local monetary symbol //// internal unsafe String SMONDECIMALSEP { get { return GetString( this.m_pData->sMonetaryDecimal ); } } // (user can override) monetary decimal Separator //// internal unsafe String SMONTHOUSANDSEP { get { return GetString( this.m_pData->sMonetaryThousand ); } } // (user can override) monetary thousands separator //// internal unsafe String SNEGATIVESIGN { get { return GetString( this.m_pData->sNegativeSign ); } } // (user can override) negative sign //// internal unsafe String S1159 { get { return GetString( this.m_pData->sAM1159 ); } } // (user can override) AM designator //// internal unsafe String S2359 { get { return GetString( this.m_pData->sPM2359 ); } } // (user can override) PM designator //// //// // String array DEFAULTS //// // Note: GetDTFIOverrideValues does the user overrides for these, so we don't have to. //// internal unsafe String STIMEFORMAT { get { return ReescapeWin32String( GetStringArrayDefault( this.m_pData->saTimeFormat ) ); } } // (user can override) time format //// internal unsafe String SSHORTTIME { get { return ReescapeWin32String( GetStringArrayDefault( this.m_pData->saShortTime ) ); } } // short time format //// internal unsafe String SSHORTDATE { get { return ReescapeWin32String( GetStringArrayDefault( this.m_pData->saShortDate ) ); } } // (user can override) short date format //// internal unsafe String SLONGDATE { get { return ReescapeWin32String( GetStringArrayDefault( this.m_pData->saLongDate ) ); } } // (user can override) long date format //// internal unsafe String SYEARMONTH { get { return ReescapeWin32String( GetStringArrayDefault( this.m_pData->saYearMonth ) ); } } // (user can override) year/month format //// internal unsafe String SMONTHDAY { get { return ReescapeWin32String( GetString( this.m_pData->sMonthDay ) ); } } // month/day format (single string, no override) //// //// // String arrays //// internal unsafe String[] STIMEFORMATS { get { return ReescapeWin32Strings( GetStringArray( this.m_pData->saTimeFormat ) ); } } // (user can override) time format //// internal unsafe String[] SSHORTTIMES { get { return ReescapeWin32Strings( GetStringArray( this.m_pData->saShortTime ) ); } } // short time format //// internal unsafe String[] SSHORTDATES { get { return ReescapeWin32Strings( GetStringArray( this.m_pData->saShortDate ) ); } } // (user can override default only) short date format //// internal unsafe String[] SLONGDATES { get { return ReescapeWin32Strings( GetStringArray( this.m_pData->saLongDate ) ); } } // (user can override default only) long date format //// internal unsafe String[] SYEARMONTHS { get { return ReescapeWin32Strings( GetStringArray( this.m_pData->saYearMonth ) ); } } // (user can override) date year/month format. (9x doesn't support override) //// //// internal unsafe String[] SNATIVEDIGITS //// { // (user can override) native characters for digits 0-9 //// get //// { //// return GetStringArray( this.m_pData->saNativeDigits ); //// } //// } //// //// // Integer ones are all pretty trivial //// internal unsafe ushort ILANGUAGE { get { return this.m_pData->iLanguage; } } // //// // internal unsafe ushort IDEFAULTLANGUAGE { get { return this.m_pData->iDEFAULTLANGUAGE; } } // Default language if this is a rare lcid (Windows Only) //// internal unsafe ushort IDEFAULTANSICODEPAGE { get { return this.m_pData->iDefaultAnsiCodePage; } } // default ansi code page ID (ACP) //// internal unsafe ushort IDEFAULTOEMCODEPAGE { get { return this.m_pData->iDefaultOemCodePage; } } // default oem code page ID (OCP or OEM) //// internal unsafe ushort IDEFAULTMACCODEPAGE { get { return this.m_pData->iDefaultMacCodePage; } } // default macintosh code page //// internal unsafe ushort IDEFAULTEBCDICCODEPAGE { get { return this.m_pData->iDefaultEbcdicCodePage; } } // default EBCDIC code page //// internal unsafe ushort IGEOID { get { return this.m_pData->iGeoId; } } // GeoId (RegionInfo) //// // internal unsafe ushort IPAPERSIZE { get { return this.m_pData->iPAPERSIZE; } } // default paper size (RegionInfo) //// // internal unsafe ushort IINTLCURRENCYDIGITS { get { return this.m_pData->iINTLCURRENCYDIGITS; } } // # of digits after decimal in intl currency format (Windows Only) //// internal unsafe ushort INEGATIVEPERCENT { get { return this.m_pData->iNegativePercent; } } // //// internal unsafe ushort IPOSITIVEPERCENT { get { return this.m_pData->iPositivePercent; } } // //// internal unsafe ushort IPARENT { get { return this.m_pData->iParent; } } // //// internal unsafe ushort ILINEORIENTATIONS { get { return this.m_pData->iLineOrientations; } } // //// internal unsafe uint ICOMPAREINFO { get { return this.m_pData->iCompareInfo; } } // //// internal unsafe uint IFLAGS { get { return this.m_pData->iFlags; } } // Flags for culture //// //// // OptionalCalendars //// internal unsafe int[] IOPTIONALCALENDARS { get { return GetWordArray( this.m_pData->waCalendars ); } } // additional calendar type(s), semicolon seperated, ie: '1;6' //// //// // Strings //// internal unsafe String SNAME { get { return GetString( this.m_pData->sName ); } } // //// internal unsafe String SABBREVLANGNAME { get { return GetString( this.m_pData->sAbbrevLang ); } } // abbreviated language name //// internal unsafe String SISO639LANGNAME { get { return GetString( this.m_pData->sISO639Language ); } } // //// // internal unsafe String SENGLISHLANGUAGE { get { return GetString(this.m_pData->sENGLISHLANGUAGE); } } // English name for this language (Windows Only) //// // internal unsafe String SNATIVELANGUAGE { get { return GetString(this.m_pData->sNATIVELANGUAGE); } } // Native name of this language (Windows Only) //// internal unsafe String SENGCOUNTRY { get { return GetString( this.m_pData->sEnglishCountry ); } } // english country name (RegionInfo) //// internal unsafe String SNATIVECOUNTRY { get { return GetString( this.m_pData->sNativeCountry ); } } // native country name (RegionInfo) //// internal unsafe String SABBREVCTRYNAME { get { return GetString( this.m_pData->sAbbrevCountry ); } } // abbreviated country name (RegionInfo) //// internal unsafe String SISO3166CTRYNAME { get { return GetString( this.m_pData->sISO3166CountryName ); } } // (RegionInfo) //// internal unsafe String SINTLSYMBOL { get { return GetString( this.m_pData->sIntlMonetarySymbol ); } } // international monetary symbol (RegionInfo) //// internal unsafe String SENGLISHCURRENCY { get { return GetString( this.m_pData->sEnglishCurrency ); } } // English name for this currency (RegionInfo) //// internal unsafe String SNATIVECURRENCY { get { return GetString( this.m_pData->sNativeCurrency ); } } // Native name for this currency (RegionInfo) //// internal unsafe String SENGDISPLAYNAME { get { return GetString( this.m_pData->sEnglishDisplayName ); } } // //// internal unsafe String SISO639LANGNAME2 { get { return GetString( this.m_pData->sISO639Language2 ); } } // //// internal unsafe String SNATIVEDISPLAYNAME //// { //// get //// { //// // Special case for Taiwan. //// if(CultureInfo.GetLangID( ActualCultureID ) == 0x0404 && //// CultureInfo.GetLangID( CultureInfo.InstalledUICulture.LCID ) == 0x0404 && //// !IsCustomCulture) //// { //// return (CultureInfo.nativeGetLocaleInfo( 0x0404, LOCALE_SNATIVELANGNAME ) + " (" + CultureInfo.nativeGetLocaleInfo( 0x0404, LOCALE_SNATIVECTRYNAME ) + ")"); //// } //// return GetString( this.m_pData->sNativeDisplayName ); //// } //// } // //// //// internal unsafe String SPERCENT { get { return GetString( this.m_pData->sPercent ); } } // //// internal unsafe String SNAN { get { return GetString( this.m_pData->sNaN ); } } // //// internal unsafe String SPOSINFINITY { get { return GetString( this.m_pData->sPositiveInfinity ); } } // //// internal unsafe String SNEGINFINITY { get { return GetString( this.m_pData->sNegativeInfinity ); } } // //// internal unsafe String SADERA { get { return GetString( this.m_pData->sAdEra ); } } // localized names for the A.D. Era //// internal unsafe String SABBREVADERA { get { return GetString( this.m_pData->sAbbrevAdEra ); } } // abbreviated localized names for the A.D. Era //// internal unsafe String SISO3166CTRYNAME2 { get { return GetString( this.m_pData->sISO3166CountryName2 ); } } // (RegionInfo) //// internal unsafe String SREGIONNAME { get { return GetString( this.m_pData->sRegionName ); } } // (RegionInfo) //// internal unsafe String SPARENT { get { return GetString( this.m_pData->sParent ); } } // //// internal unsafe String SCONSOLEFALLBACKNAME { get { return GetString( this.m_pData->sConsoleFallbackName ); } } //// internal unsafe String SSPECIFICCULTURE { get { return GetString( this.m_pData->sSpecificCulture ); } } //// internal unsafe String SIETFTAG { get { return GetString( this.m_pData->sIetfLanguage ); } } // RFC 3066 name //// //// // String Arrays //// internal unsafe String[] SDAYNAMES { get { return GetStringArray( this.m_pData->saDayNames ); } } // day names //// internal unsafe String[] SABBREVDAYNAMES { get { return GetStringArray( this.m_pData->saAbbrevDayNames ); } } // abbreviated day names //// internal unsafe String[] SSUPERSHORTDAYNAMES { get { return GetStringArray( this.m_pData->saSuperShortDayNames ); } } // one letter day names //// internal unsafe String[] SMONTHNAMES { get { return GetStringArray( this.m_pData->saMonthNames ); } } // month names //// internal unsafe String[] SABBREVMONTHNAMES { get { return GetStringArray( this.m_pData->saAbbrevMonthNames ); } } // abbreviated month names //// internal unsafe String[] SMONTHGENITIVENAMES { get { return GetStringArray( this.m_pData->saMonthGenitiveNames ); } } // //// internal unsafe String[] SABBREVMONTHGENITIVENAMES { get { return GetStringArray( this.m_pData->saAbbrevMonthGenitiveNames ); } }// //// internal unsafe String[] SNATIVECALNAMES { get { return GetStringArray( this.m_pData->saNativeCalendarNames ); } } // Native calendar names. index of optional calendar - 1, empty if no optional calendar at that number //// internal unsafe String[] SDATEWORDS { get { return GetStringArray( this.m_pData->saDateWords ); } } // //// internal unsafe String[] SALTSORTID { get { return GetStringArray( this.m_pData->saAltSortID ); } } // The array of alternate sort names //// //// // Fontsignature //// // internal unsafe ushort FONTSIGNATURE { get { return this.m_pData->waFONTSIGNATURE; } } // Font signature (16 WORDS) (Windows Only) //// //// // DateTimeFormatFlags //// internal unsafe DateTimeFormatFlags IFORMATFLAGS { get { return (DateTimeFormatFlags)this.m_pData->iFormatFlags; } } // //// //// // Special handling required for these fields //// // (user can override) positive sign. We use "+" if empty (windows data is usually empty) //// internal unsafe String SPOSITIVESIGN //// { //// get //// { //// String strTemp = GetString( this.m_pData->sPositiveSign ); //// if(strTemp == null || strTemp.Length == 0) strTemp = "+"; //// return strTemp; //// } //// } //// //// internal static bool IsCustomCultureId( int cultureId ) //// { //// if(cultureId == CultureInfo.LOCALE_CUSTOM_DEFAULT || cultureId == CultureInfo.LOCALE_CUSTOM_UNSPECIFIED) //// return true; //// //// return false; //// } //// //// private unsafe ushort ConvertFirstDayOfWeekMonToSun( int iTemp ) //// { //// // Convert Mon-Sun to Sun-Sat format //// if(iTemp < 0 || iTemp > 6) //// { //// // If invalid data exist in registry, assume //// // the first day of week is Monday. //// iTemp = 1; //// } //// else //// { //// if(iTemp == 6) //// { //// iTemp = 0; //// } //// else //// { //// iTemp++; //// } //// } //// return unchecked( (ushort)iTemp ); //// } //// //// // (user can override) first day of week (0 is Sunday) //// internal unsafe ushort IFIRSTDAYOFWEEK //// { //// get //// { //// return this.m_pData->iFirstDayOfWeek; //// } //// } //// //// internal unsafe ushort IINPUTLANGUAGEHANDLE //// { //// get //// { //// // Remember this returns SPANISH_INTERNATIONAL_SORT even //// // in the deprecated case. //// return (this.m_pData->iInputLanguageHandle); //// } //// } //// //// internal unsafe ushort ITEXTINFO //// { //// get //// { //// ushort textInfo = this.m_pData->iTextInfo; //// //// // Need to return SPANISH_TRADITIONAL_SORT even if we're faking it //// // (Hack because SPANISH_TRADITIONAL_SORT isn't in the table) //// if(this.CultureID == (ushort)SPANISH_TRADITIONAL_SORT) //// textInfo = (ushort)SPANISH_TRADITIONAL_SORT; //// //// // Make sure custom culture and unknown get something //// if(textInfo == CultureInfo.LOCALE_CUSTOM_DEFAULT || textInfo == 0) //// textInfo = CultureInfo.LOCALE_INVARIANT; //// return textInfo; //// } //// } //// //// //// //////////////////////////////////////////////////////////////////////////// //// // //// // Unescape a Win32 style quote string //// // //// // This is also the escaping style used by custom culture data files //// // //// // This removes the 'fred' and 'fred''s' windows quoted formatting from a string. //// // The output string will NOT have ANY escaping. Currently its used for //// // separators, where the output string has no characters with special meaning //// // //// // We don't build the stringbuilder unless we find a '. If we find a ', we //// // always build a stringbuilder because we need to remove the '. //// // //// //////////////////////////////////////////////////////////////////////////// //// static private String UnescapeWin32String( String str, int start, int end ) //// { //// StringBuilder result = null; //// //// bool inQuote = false; //// for(int i = start; i < str.Length && i <= end; i++) //// { //// // Look for quote //// if(str[i] == '\'') //// { //// // Already in quote? //// if(inQuote) //// { //// BCLDebug.Assert( result != null, "[CultureTable.UnescapeWin32String]Expect result to be non-null" ); //// // See another single quote. Is this '' of 'fred''s' or ending quote? //// if(i + 1 < str.Length) //// { //// if(str[i + 1] == '\'') //// { //// // Append a ' and keep going (so we don't turn off quote mode) //// result.Append( '\'' ); //// i++; //// continue; //// } //// } //// //// inQuote = false; //// } //// else //// { //// // Found beginning quote, remove it. //// inQuote = true; //// if(result == null) //// result = new StringBuilder( str, start, i - start, str.Length ); //// } //// } //// else //// { //// // If we have a builder we need to add our non-quote char //// if(result != null) //// result.Append( str[i] ); //// } //// } //// //// // No ', just return input string substring //// if(result == null) //// return (str.Substring( start, end - start + 1 )); //// //// // Had ', need to use the builder //// return (result.ToString()); //// } //// //// //// //////////////////////////////////////////////////////////////////////////// //// // //// // Reescape a Win32 style quote string as a NLS+ style quoted string //// // //// // This is also the escaping style used by custom culture data files //// // //// // NLS+ uses \ to escape the next character, whether in a quoted string or //// // not, so we always have to change \ to \\. //// // //// // NLS+ uses \' to escape a quote inside a quoted string so we have to change //// // '' to \' (if inside a quoted string) //// // //// // We don't build the stringbuilder unless we find something to change //// //////////////////////////////////////////////////////////////////////////// //// static private String ReescapeWin32String( String str ) //// { //// // If we don't have data, then don't try anything //// if(str == null) //// return null; //// //// StringBuilder result = null; //// //// bool inQuote = false; //// for(int i = 0; i < str.Length; i++) //// { //// // Look for quote //// if(str[i] == '\'') //// { //// // Already in quote? //// if(inQuote) //// { //// // See another single quote. Is this '' of 'fred''s' or '''', or is it an ending quote? //// if(i + 1 < str.Length && str[i + 1] == '\'') //// { //// // Found another ', so we have ''. Need to add \' instead. //// // 1st make sure we have our stringbuilder //// if(result == null) //// result = new StringBuilder( str, 0, i, str.Length * 2 ); //// //// // Append a \' and keep going (so we don't turn off quote mode) //// result.Append( "\\'" ); //// i++; //// continue; //// } //// //// // Turning off quote mode, fall through to add it //// inQuote = false; //// } //// else //// { //// // Found beginning quote, fall through to add it //// inQuote = true; //// } //// } //// // Is there a single \ character? //// else if(str[i] == '\\') //// { //// // Found a \, need to change it to \\ //// // 1st make sure we have our stringbuilder //// if(result == null) //// result = new StringBuilder( str, 0, i, str.Length * 2 ); //// //// // Append our \\ to the string & continue //// result.Append( "\\\\" ); //// continue; //// } //// //// // If we have a builder we need to add our character //// if(result != null) //// result.Append( str[i] ); //// } //// //// // Unchanged string? , just return input string //// if(result == null) //// return str; //// //// // String changed, need to use the builder //// return result.ToString(); //// } //// //// static private String[] ReescapeWin32Strings( String[] array ) //// { //// if(array != null) //// { //// for(int i = 0; i < array.Length; i++) //// { //// array[i] = ReescapeWin32String( array[i] ); //// } //// } //// //// return array; //// } //// //// internal unsafe String STIME //// { //// get //// { //// // Compute SDATE from STIMEFORMAT //// String timeFormat = GetOverrideStringArrayDefault( this.m_pData->saTimeFormat, CultureTableData.LOCALE_STIMEFORMAT ); //// return GetTimeSeparator( timeFormat ); //// } //// } //// //// internal unsafe String SDATE //// { //// get //// { //// // Compute SDATE from SSHORTDATE //// String shortDate = GetOverrideStringArrayDefault( this.m_pData->saShortDate, CultureTableData.LOCALE_SSHORTDATE ); //// return GetDateSeparator( shortDate ); //// } //// } //// //// static private String GetTimeSeparator( String format ) //// { //// // Time format separator (ie: : in 12:39:00) //// // //// // We calculate this from the provided time format //// // //// //// // //// // Find the time separator so that we can pretend we know STIME. //// // //// String strUse = String.Empty; //// int count = 0; //// int separatorStart = -1; //// //// // Look through the whole string //// for(count = 0; count < format.Length; count++) //// { //// // See if we have Hhms //// if(format[count] == 'H' || format[count] == 'h' || format[count] == 'm' || format[count] == 's') //// { //// // Found a time part, find out when it changes //// char cFound = format[count]; //// //// for(count++; count < format.Length && format[count] == cFound; count++) //// { //// // Done //// } //// //// // Did we find anything? //// if(count < format.Length) //// { //// // We found start of separator //// separatorStart = count; //// break; //// } //// } //// //// // If it was quotes, ignore quoted stuff //// if(format[count] == '\'') //// { //// // //// // Ignore quotes. //// // //// //// for(count++; count < format.Length && (format[count] != '\''); count++) //// { //// // Done //// } //// //// // Don't go past end of string //// } //// //// // Advance to next char (skipping unknown char or last quote) //// } //// //// // Now we need to find the end of the separator //// if(separatorStart != -1) //// { //// for(count = separatorStart; count < format.Length; count++) //// { //// // See if we have Hhms //// if(format[count] == 'H' || format[count] == 'h' || format[count] == 'm' || format[count] == 's') //// { //// // Found a time part, stop, we can look for our separator //// // From [separatorStart, count) is our string, except we don't want ''s //// strUse = UnescapeWin32String( format, separatorStart, count - 1 ); //// break; //// } //// //// // If it was quotes, ignore quoted stuff //// if(format[count] == '\'') //// { //// // //// // Ignore quotes. //// // //// for(count++; count < format.Length && (format[count] != '\''); count++) //// { //// // Done //// } //// //// // Don't go past end of string //// } //// //// // Advance to next char (skipping unknown char or last quote) //// } //// } //// //// // Return the one we're using //// return strUse; //// } //// //// static private String GetDateSeparator( String format ) //// { //// // Date format separator (ie: / in 9/1/03) //// // //// // We calculate this from the provided short date //// // //// //// // //// // Find the date separator so that we can pretend we know SDATE. //// // //// String strUse = String.Empty; //// int count = 0; //// int separatorStart = -1; //// //// // Look through the whole string //// for(count = 0; count < format.Length; count++) //// { //// // See if we have dyM //// if(format[count] == 'd' || format[count] == 'y' || format[count] == 'M') //// { //// // Found a time part, find out when it changes //// char cFound = format[count]; //// //// for(count++; count < format.Length && format[count] == cFound; count++) //// { //// // Done //// } //// //// // Did we find anything? //// if(count < format.Length) //// { //// // We found start of separator //// separatorStart = count; //// break; //// } //// } //// //// // If it was quotes, ignore quoted stuff //// if(format[count] == '\'') //// { //// // //// // Ignore quotes. //// // //// //// for(count++; count < format.Length && (format[count] != '\''); count++) //// { //// // Done //// } //// //// // Don't go past end of string //// } //// //// // Advance to next char (skipping unknown char or last quote) //// } //// //// // Now we need to find the end of the separator //// if(separatorStart != -1) //// { //// for(count = separatorStart; count < format.Length; count++) //// { //// // See if we have yMd //// if(format[count] == 'y' || format[count] == 'M' || format[count] == 'd') //// { //// // Found a time part, stop, we can look for our separator //// // From [separatorStart, count) is our string, except we don't want ''s //// strUse = UnescapeWin32String( format, separatorStart, count - 1 ); //// break; //// } //// //// // If it was quotes, ignore quoted stuff //// if(format[count] == '\'') //// { //// // //// // Ignore quotes. //// // //// for(count++; count < format.Length && (format[count] != '\''); count++) //// { //// // Done //// } //// //// // Don't go past end of string //// } //// //// // Advance to next char (skipping unknown char or last quote) //// } //// } //// //// // Return the one we're using //// return strUse; //// } //// //// //////////////////////////////////////////////////////////////////////////// //// // //// // Parameters: //// // calendarValueOnly Retrieve the values which are affected by the calendar change of DTFI. //// // This will cause values like longTimePattern not be retrieved since it is //// // not affected by the Calendar property in DTFI. //// // //// //////////////////////////////////////////////////////////////////////////// //// internal unsafe void GetDTFIOverrideValues( ref DTFIUserOverrideValues values ) //// { //// BCLDebug.Assert( UseUserOverride, "CultureTableRecord.GetDTFIOverrideValues(): Call this only when UseUserOverride is true." ); //// bool result = false; //// if(UseGetLocaleInfo) //// result = CultureInfo.nativeGetDTFIUserValues( InteropLCID, ref values ); //// //// if(result) //// { //// //// // if we got values.yearMonthPattern = null this means the data is not located in the registry and //// // we couldn't call GetLocaleInfo. we leave yearMonthPattern as null here so the caller (DTFI) //// // will initialize it properly. //// //// values.firstDayOfWeek = ConvertFirstDayOfWeekMonToSun( (int)values.firstDayOfWeek ); //// //// // Need to do escaping of win32/file type patterns to NLS type patterns //// values.shortDatePattern = ReescapeWin32String( values.shortDatePattern ); //// values.longDatePattern = ReescapeWin32String( values.longDatePattern ); //// values.longTimePattern = ReescapeWin32String( values.longTimePattern ); //// values.yearMonthPattern = ReescapeWin32String( values.yearMonthPattern ); //// } //// else //// { //// // //// // We do not use user-override values or something failed during the call to GetLocaleInfo(). Use the information in culture.nlp. //// // //// values.firstDayOfWeek = IFIRSTDAYOFWEEK; //// values.calendarWeekRule = IFIRSTWEEKOFYEAR; //// values.shortDatePattern = SSHORTDATE; //// values.longDatePattern = SLONGDATE; //// values.yearMonthPattern = SYEARMONTH; //// values.amDesignator = S1159; //// values.pmDesignator = S2359; //// values.longTimePattern = STIMEFORMAT; //// } //// } //// //// internal unsafe void GetNFIOverrideValues( NumberFormatInfo nfi ) //// { //// bool result = false; //// if(UseGetLocaleInfo) //// { //// result = CultureInfo.nativeGetNFIUserValues( InteropLCID, nfi ); //// } //// //// if(!result) //// { //// // Something failed during the call to GetLocaleInfo(). Use the information in culture.nlp. //// nfi.numberDecimalDigits = IDIGITS; //// nfi.numberNegativePattern = INEGNUMBER; //// nfi.currencyDecimalDigits = ICURRDIGITS; //// nfi.currencyPositivePattern = ICURRENCY; //// nfi.currencyNegativePattern = INEGCURR; //// nfi.negativeSign = SNEGATIVESIGN; //// nfi.numberDecimalSeparator = SDECIMAL; //// nfi.numberGroupSeparator = STHOUSAND; //// nfi.positiveSign = SPOSITIVESIGN; //// nfi.currencyDecimalSeparator = SMONDECIMALSEP; //// nfi.currencySymbol = SCURRENCY; //// nfi.currencyGroupSeparator = SMONTHOUSANDSEP; //// nfi.nativeDigits = SNATIVEDIGITS; //// nfi.digitSubstitution = IDIGITSUBSTITUTION; //// } //// //// nfi.numberGroupSizes = SGROUPING; //// nfi.currencyGroupSizes = SMONGROUPING; //// //// nfi.percentDecimalDigits = nfi.numberDecimalDigits; //// nfi.percentDecimalSeparator = nfi.numberDecimalSeparator; //// nfi.percentGroupSizes = nfi.numberGroupSizes; //// nfi.percentGroupSeparator = nfi.numberGroupSeparator; //// nfi.percentNegativePattern = INEGATIVEPERCENT; //// nfi.percentPositivePattern = IPOSITIVEPERCENT; //// nfi.percentSymbol = SPERCENT; //// //// if(nfi.positiveSign == null || nfi.positiveSign.Length == 0) nfi.positiveSign = "+"; //// //// //Special case for Italian. The currency decimal separator in the control panel is the empty string. When the user //// //specifies C4 as the currency format, this results in the number apparently getting multiplied by 10000 because the //// //decimal point doesn't show up. We'll just hack this here because our default currency format will never use nfi. //// if(nfi.currencyDecimalSeparator.Length == 0) //// { //// nfi.currencyDecimalSeparator = SMONDECIMALSEP; //// } //// //// //// } //// //// //// //// // EverettDataItem //// // //// // Everett can't deserialize using names/ids, so it has to use the data item. //// internal unsafe int EverettDataItem() //// { //// // See if its a custom culture //// if(this.IsCustomCulture) //// { //// // They're hosed, this is a custom culture, return 0 (Invariant) //// // It'd be better if Everett threw an error, but the accessors don't have to do //// // range checking on this, so we'd just read off the end of the data and get //// // junk, which wouldn't be guaranteed to throw an error. Invariant is a better choice. //// return 0; //// } //// //// InitEverettCultureDataItemMapping(); //// // Normal culture, look up its data item from our LCID //// // Do a binary search //// int left = 0; //// int right = (m_EverettCultureDataItemMappingsSize / 2) - 1; //// //// while(left <= right) //// { //// int mid = (left + right) / 2; //// int result = this.m_CultureID - m_EverettCultureDataItemMappings[mid * 2]; //// if(result == 0) //// { //// // Found it, return the index //// return m_EverettCultureDataItemMappings[mid * 2 + 1]; //// } //// if(result < 0) //// right = mid - 1; //// else //// left = mid + 1; //// } //// //// // They're hosed, couldn't find an Everett data item for this culture. //// // It'd be better if Everett threw an error, but the accessors don't have to do //// // range checking on this, so we'd just read off the end of the data and get //// // junk, which wouldn't be guaranteed to throw an error. Invariant is a better choice. //// return 0; //// } //// //// internal unsafe int EverettRegionDataItem() //// { //// // See if its a custom culture //// if(this.IsCustomCulture) //// { //// // They're hosed, this is a custom culture, return 0 (Invariant) //// // It'd be better if Everett threw an error, but the accessors don't have to do //// // range checking on this, so we'd just read off the end of the data and get //// // junk, which wouldn't be guaranteed to throw an error. Invariant is a better choice. //// return 0; //// } //// //// InitEverettRegionDataItemMapping(); //// // Normal culture, look up its data item from our LCID //// // Do a binary search //// int left = 0; //// int right = (m_EverettRegionDataItemMappingsSize / 2) - 1; //// //// while(left <= right) //// { //// int mid = (left + right) / 2; //// int result = this.m_CultureID - m_EverettRegionDataItemMappings[mid * 2]; //// if(result == 0) //// { //// // Found it, return the index //// return m_EverettRegionDataItemMappings[mid * 2 + 1]; //// } //// if(result < 0) //// right = mid - 1; //// else //// left = mid + 1; //// } //// //// // They're hosed, couldn't find an Everett data item for this culture. //// // It'd be better if Everett threw an error, but the accessors don't have to do //// // range checking on this, so we'd just read off the end of the data and get //// // junk, which wouldn't be guaranteed to throw an error. Invariant is a better choice. //// return 0; //// } //// //// internal static unsafe int IdFromEverettDataItem( int iDataItem ) //// { //// InitEverettDataItemToLCIDMappings(); //// //// // Assert that it exists //// BCLDebug.Assert( iDataItem >= 0 && iDataItem < m_EverettDataItemToLCIDMappingsSize, //// String.Format( //// CultureInfo.CurrentCulture, //// "[CultureTableRecord.IdFromEverettDataItem]Expected Everett data item in range of data table {0}", iDataItem ) ); //// if(iDataItem < 0 || iDataItem >= m_EverettDataItemToLCIDMappingsSize) //// { //// // If the dataItem is not valid, throw. //// throw new SerializationException( Environment.GetResourceString( "Serialization_InvalidFieldState" ) ); //// } //// return m_EverettDataItemToLCIDMappings[iDataItem]; //// } //// //// internal static unsafe int IdFromEverettRegionInfoDataItem( int iDataItem ) //// { //// InitEverettRegionDataItemToLCIDMappings(); //// //// // Assert that it exists //// BCLDebug.Assert( iDataItem >= 0 && iDataItem < m_EverettRegionInfoDataItemToLCIDMappingsSize, //// String.Format( //// CultureInfo.CurrentCulture, //// "[CultureTableRecord.IdFromEverettRegionInfoDataItem]Expected Everett data item in range of data table {0}", iDataItem ) ); //// if(iDataItem < 0 || iDataItem >= m_EverettRegionInfoDataItemToLCIDMappingsSize) //// { //// // If the dataItem is not valid, throw. //// throw new SerializationException( Environment.GetResourceString( "Serialization_InvalidFieldState" ) ); //// } //// return m_EverettRegionInfoDataItemToLCIDMappings[iDataItem]; //// } //// //// // The const here should be in sync with the one defined in the native side. //// const int INT32TABLE_EVERETT_REGION_DATA_ITEM_MAPPINGS = 0; //// const int INT32TABLE_EVERETT_CULTURE_DATA_ITEM_MAPPINGS = 1; //// const int INT32TABLE_EVERETT_DATA_ITEM_TO_LCID_MAPPINGS = 2; //// const int INT32TABLE_EVERETT_REGION_DATA_ITEM_TO_LCID_MAPPINGS = 3; //// //// // Call InitEverettRegionDataItemMapping() before using these two. //// static unsafe int* m_EverettRegionDataItemMappings = null; //// static unsafe int m_EverettRegionDataItemMappingsSize = 0; //// //// //////////////////////////////////////////////////////////////////////// //// // //// // Initialize the data used for mapping RegionInfo ID to dataItem. //// // Everett uses dataItem in persisting RegionInfo. //// // //// //////////////////////////////////////////////////////////////////////// //// //// private static unsafe void InitEverettRegionDataItemMapping() //// { //// if(m_EverettRegionDataItemMappings == null) //// { //// int* temp = CultureInfo.nativeGetStaticInt32DataTable( INT32TABLE_EVERETT_REGION_DATA_ITEM_MAPPINGS, out m_EverettRegionDataItemMappingsSize ); //// m_EverettRegionDataItemMappings = temp; //// BCLDebug.Assert( m_EverettRegionDataItemMappings != null, "CultureTableRecord.m_EverettRegionDataItemMappings can not be null" ); //// BCLDebug.Assert( m_EverettRegionDataItemMappingsSize > 0, "CultureTableRecord.m_EverettRegionDataItemMappingsSize > 0" ); //// } //// } //// //// // Call InitEverettCultureDataItemMapping before using these two. //// unsafe static int* m_EverettCultureDataItemMappings = null; //// static int m_EverettCultureDataItemMappingsSize = 0; //// //// //////////////////////////////////////////////////////////////////////// //// // //// // Initialize the data used for mapping CultureInfo ID to dataItem. //// // Everett uses dataItem in persisting CultureInfo. //// // //// //////////////////////////////////////////////////////////////////////// //// //// private static unsafe void InitEverettCultureDataItemMapping() //// { //// if(m_EverettCultureDataItemMappings == null) //// { //// int* temp = CultureInfo.nativeGetStaticInt32DataTable( INT32TABLE_EVERETT_CULTURE_DATA_ITEM_MAPPINGS, out m_EverettCultureDataItemMappingsSize ); //// m_EverettCultureDataItemMappings = temp; //// BCLDebug.Assert( m_EverettCultureDataItemMappings != null, "CultureTableRecord.m_EverettCultureDataItemMappings can not be null" ); //// BCLDebug.Assert( m_EverettCultureDataItemMappingsSize > 0, "CultureTableRecord.m_EverettCultureDataItemMappingsSize > 0" ); //// } //// } //// //// //// // Call InitEverettDataItemToLCIDMappings() before using these two. //// private static unsafe int* m_EverettDataItemToLCIDMappings = null; //// private static int m_EverettDataItemToLCIDMappingsSize = 0; //// //// //////////////////////////////////////////////////////////////////////// //// // //// // Initialize the CultureInfo data used for mapping an Everett dataItem to a LCID. //// // Everett uses dataItem in persisting CultureInfo. //// // //// //////////////////////////////////////////////////////////////////////// //// //// private static unsafe void InitEverettDataItemToLCIDMappings() //// { //// if(m_EverettDataItemToLCIDMappings == null) //// { //// int* temp = CultureInfo.nativeGetStaticInt32DataTable( INT32TABLE_EVERETT_DATA_ITEM_TO_LCID_MAPPINGS, out m_EverettDataItemToLCIDMappingsSize ); //// m_EverettDataItemToLCIDMappings = temp; //// BCLDebug.Assert( m_EverettDataItemToLCIDMappings != null, "CultureTableRecord.m_EverettDataItemToLCIDMappings can not be null" ); //// BCLDebug.Assert( m_EverettDataItemToLCIDMappingsSize > 0, "CultureTableRecord.m_EverettDataItemToLCIDMappingsSize > 0" ); //// } //// } //// //// // Call InitEverettRegionDataItemToLCIDMappings() before using these two. //// private static unsafe int* m_EverettRegionInfoDataItemToLCIDMappings = null; //// private static int m_EverettRegionInfoDataItemToLCIDMappingsSize = 0; //// //// //////////////////////////////////////////////////////////////////////// //// // //// // Initialize the RegionInfo data used for mapping an Everett dataItem to a LCID. //// // Everett uses dataItem in persisting RegionInfo. //// // //// //////////////////////////////////////////////////////////////////////// //// //// private static unsafe void InitEverettRegionDataItemToLCIDMappings() //// { //// if(m_EverettRegionInfoDataItemToLCIDMappings == null) //// { //// int* temp = CultureInfo.nativeGetStaticInt32DataTable( //// INT32TABLE_EVERETT_REGION_DATA_ITEM_TO_LCID_MAPPINGS, //// out m_EverettRegionInfoDataItemToLCIDMappingsSize ); //// //// m_EverettRegionInfoDataItemToLCIDMappings = temp; //// BCLDebug.Assert( m_EverettRegionInfoDataItemToLCIDMappings != null, //// "CultureTableRecord.m_EverettRegionInfoDataItemToLCIDMappings can not be null" ); //// BCLDebug.Assert( m_EverettRegionInfoDataItemToLCIDMappingsSize > 0, //// "CultureTableRecord.m_EverettRegionInfoDataItemToLCIDMappingsSize > 0" ); //// } //// } ////} //// //////////////////////////////////////////////////////////////////////////////// ////// ////// This structure contains DateTimeFormatInfo properties that can be overridden by users. ////// We define this structure so that we can fill these values in one FCALL, instead of calling GetLocaleInfo() multiple times in ////// separate FCalls. ////// ////// NOTE: When adding int fields, be sure to pad an extra int so that they are ////// aligned in DWORD. By doing so, it will make sure that String fields are ////// aligned in DWORD. ////// //////////////////////////////////////////////////////////////////////////////// //// ////[StructLayout( LayoutKind.Sequential, Pack = 2 )] ////internal struct DTFIUserOverrideValues ////{ //// // DTFI values that are affected by calendar setttings. //// internal String shortDatePattern; //// internal String longDatePattern; //// internal String yearMonthPattern; //// //// // DTFI values that will not be affected by calendar settings. //// internal String amDesignator; //// internal String pmDesignator; //// internal String longTimePattern; //// internal int firstDayOfWeek; //// internal int padding1; // Add padding to make sure that we are aligned in DWORD. This is important for 64-bit platforms //// internal int calendarWeekRule; //// internal int padding2; // Add padding to make sure that we are aligned in DWORD. This is important for 64-bit platforms ////} //// ////// CultureData has a cloned strucure in the native side. we send this struct to the native side to be filled ////// by the native APIs (mostly GetLocaleInfo) to load the synthetic cultures data. ////// ////// IMPORTANT IMPORTANT IMPORTANT IMPORTANT IMPORTANT ////// any change in this structure require a change in the cloned one in the native side. (ComNlsInfo.h/.cpp) ////// ////// Also we use the default alignment which is 8-bytes in the managed and native sides so don't use the "Pack" property here ////// ////// ////[StructLayout( LayoutKind.Sequential )] ////internal struct CultureData ////{ //// internal string sIso639Language; // LOCALE_SISO639LANGNAME (TwoLetterISOLanguageName) //// internal string sIso3166CountryName; // LOCALE_SISO3166CTRYNAME (TwoLetterISORegionName) //// internal string sListSeparator; // LOCALE_SLIST (ListSeparator) //// internal string sDecimalSeparator; // LOCALE_SDECIMAL (NumberDecimalSeparator) //// internal string sThousandSeparator; // LOCALE_STHOUSAND (NumberGroupSeparator) //// internal string sCurrency; // LOCALE_SCURRENCY (CurrencySymbol) //// internal string sMonetaryDecimal; // LOCALE_SMONDECIMALSEP (CurrencyDecimalSeparator) //// internal string sMonetaryThousand; // LOCALE_SMONTHOUSANDSEP (CurrencyGroupSeparator) //// internal string sNegativeSign; // LOCALE_SNEGATIVESIGN (NegativeSign) //// internal string sAM1159; // LOCALE_S1159 (AMDesignator) //// internal string sPM2359; // LOCALE_S2359 (PMDesignator) //// internal string sAbbrevLang; // LOCALE_SABBREVLANGNAME (ThreeLetterWindowsLanguageName) //// internal string sEnglishLanguage; // LOCALE_SENGLANGUAGE (Part of EnglishName) //// internal string sEnglishCountry; // LOCALE_SENGCOUNTRY (Part of EnglishName) //// internal string sNativeLanguage; // LOCALE_SNATIVELANGNAME (Part of NativeName) //// internal string sNativeCountry; // LOCALE_SNATIVECTRYNAME (Part of NativeName) //// internal string sAbbrevCountry; // LOCALE_SABBREVCTRYNAME (ThreeLetterWindowsRegionName) //// internal string sIntlMonetarySymbol; // LOCALE_SINTLSYMBOL (ISOCurrencySymbol) //// internal string sEnglishCurrency; // LOCALE_SENGCURRNAME (CurrencyEnglishName) //// internal string sNativeCurrency; // LOCALE_SNATIVECURRNAME (CurrencyNativeName) //// internal string saAltSortID; // LOCALE_SSORTNAME (SortName) //// //// //// // sPositiveSign in NLS always return empty string //// internal string sPositiveSign; // LOCALE_SPOSITIVESIGN (PositiveSign) //// //// // saNativeDigits should be converted to array of string instead of array of characters later. //// internal string saNativeDigits; // LOCALE_SNATIVEDIGITS (NativeDigits) //// //// internal string waGrouping; // LOCALE_SGROUPING (NumberGroupSizes) //// internal string waMonetaryGrouping; // LOCALE_SMONGROUPING (CurrencyGroupSizes) //// internal string waFontSignature; // LOCALE_FONTSIGNATURE (No API for it) //// //// // Some fields defined only post XP //// internal string sNaN; // LOCALE_SNAN (NaNSymbol) //// internal string sPositiveInfinity; // LOCALE_SPOSINFINITY (PositiveInfinitySymbol) //// internal string sNegativeInfinity; // LOCALE_SNEGINFINITY (NegativeInfinitySymbol) //// internal string sISO3166CountryName2; // LOCALE_SISO3166CTRYNAME2 (ThreeLetterISORegionName) //// internal string sISO639Language2; // LOCALE_SISO639LANGNAME2 (ThreeLetterISOLanguageName) //// internal string sIetfLanguage; // LOCALE_SIETFLANGUAGE (IetfLanguageTag) //// //// internal string[] saSuperShortDayNames; // LOCALE_SSHORTESTDAYNAME1..LOCALE_SSHORTESTDAYNAME7 (ShortestDayNames) //// // End of the fields defined only post XP //// //// internal string[] saTimeFormat; // EnumTimeFormats (GetAllDateTimePatterns('T')) //// //// internal string[] saShortDate; // EnumDateFormatsEx (GetAllDateTimePatterns('d')) //// internal string[] saLongDate; // EnumDateFormatsEx (GetAllDateTimePatterns('D')) //// internal string[] saYearMonth; // EnumDateFormatsEx (GetAllDateTimePatterns("Y")) //// //// internal string[] saMonthNames; // LOCALE_SMONTHNAME(1~13) (MonthNames) //// //// // LOCALE_SDAYNAME1 means Monday in NLS (need conversion in NLS+ //// internal string[] saDayNames; // LOCALE_SDAYNAME(1~7) (GetDayOfWeekNames) //// // LOCALE_SABBREVDAYNAME means Monday in NLS (need conversion in NLS+ //// internal string[] saAbbrevDayNames; // LOCALE_SABBREVDAYNAME(1~7) (GetAbbreviatedDayOfWeekNames/SuperShortDayNames) //// internal string[] saAbbrevMonthNames; // LOCALE_SABBREVMONTHNAME(1~13)(AbbreviatedMonthNames) //// internal string[] saNativeCalendarNames; // GetCalendarInfo/CAL_SCALNAME (NativeCalendarName) //// //// internal string[] saGenitiveMonthNames; // GetDateFormat with "dd MMMM" (MonthGenitiveNames) //// internal string[] saAbbrevGenitiveMonthNames; // GetDateFormat with "d MMM" (AbbreviatedMonthGenitiveNames) //// //// // use also EnumCalendarInfo/CAL_ICALINTVALUE //// internal ushort[] waCalendars; // LOCALE_IOPTIONALCALENDAR (OptionalCalendars) //// //// // iFirstDayOfWeek (0 is Monday for NLS and is Sunday in NLS+) //// internal int iFirstDayOfWeek; // LOCALE_IFIRSTDAYOFWEEK (FirstDayOfWeek) //// internal int iDigits; // LOCALE_IDIGITS (NumberDecimalDigits) //// internal int iNegativeNumber; // LOCALE_INEGNUMBER (NumberNegativePattern) //// internal int iCurrencyDigits; // LOCALE_ICURRDIGITS (CurrencyDecimalDigits) //// internal int iCurrency; // LOCALE_ICURRENCY (CurrencyPositivePattern) //// internal int iNegativeCurrency; // LOCALE_INEGCURR (CurrencyNegativePattern) //// internal int iFirstWeekOfYear; // LOCALE_IFIRSTWEEKOFYEAR (CalendarWeekRule) //// internal int iMeasure; // LOCALE_IMEASURE (IsMetric) //// internal int iDigitSubstitution; // LOCALE_IDIGITSUBSTITUTION (DigitSubstitution) //// internal int iDefaultAnsiCodePage; // LOCALE_IDEFAULTANSICODEPAGE (ANSICodePage) //// internal int iDefaultOemCodePage; // LOCALE_IDEFAULTCODEPAGE (OEMCodePage) //// internal int iDefaultMacCodePage; // LOCALE_IDEFAULTMACCODEPAGE (MacCodePage) //// internal int iDefaultEbcdicCodePage; // LOCALE_IDEFAULTEBCDICCODEPAGE(EBCDICCodePage) //// internal int iCountry; // LOCALE_ICOUNTRY (No API for this field) //// internal int iPaperSize; // LOCALE_IPAPERSIZE (No API for this field) //// internal int iLeadingZeros; // LOCALE_IDAYLZERO (No API for this field) //// internal int iIntlCurrencyDigits; // LOCALE_IINTLCURRDIGITS (No API for this field) //// internal int iGeoId; // EnumSystemGeoID/GetGeoInfo (RegionInfo.GeoId) //// internal int iDefaultCalender; // LOCALE_ICALENDARTYPE (No API for this field) } } ================================================ FILE: Zelig/Zelig/RunTime/Framework/mscorlib/System/Globalization/DateTimeFormat.cs ================================================ // ==++== // // Copyright (c) Microsoft Corporation. All rights reserved. // // ==--== namespace System { using System.Text; using System.Threading; using System.Globalization; using ArrayList = System.Collections.ArrayList; /* Customized format patterns: P.S. Format in the table below is the internal number format used to display the pattern. Patterns Format Description Example ========= ========== ===================================== ======== "h" "0" hour (12-hour clock)w/o leading zero 3 "hh" "00" hour (12-hour clock)with leading zero 03 "hh*" "00" hour (12-hour clock)with leading zero 03 "H" "0" hour (24-hour clock)w/o leading zero 8 "HH" "00" hour (24-hour clock)with leading zero 08 "HH*" "00" hour (24-hour clock) 08 "m" "0" minute w/o leading zero "mm" "00" minute with leading zero "mm*" "00" minute with leading zero "s" "0" second w/o leading zero "ss" "00" second with leading zero "ss*" "00" second with leading zero "f" "0" second fraction (1 digit) "ff" "00" second fraction (2 digit) "fff" "000" second fraction (3 digit) "ffff" "0000" second fraction (4 digit) "fffff" "00000" second fraction (5 digit) "ffffff" "000000" second fraction (6 digit) "fffffff" "0000000" second fraction (7 digit) "F" "0" second fraction (up to 1 digit) "FF" "00" second fraction (up to 2 digit) "FFF" "000" second fraction (up to 3 digit) "FFFF" "0000" second fraction (up to 4 digit) "FFFFF" "00000" second fraction (up to 5 digit) "FFFFFF" "000000" second fraction (up to 6 digit) "FFFFFFF" "0000000" second fraction (up to 7 digit) "t" first character of AM/PM designator A "tt" AM/PM designator AM "tt*" AM/PM designator PM "d" "0" day w/o leading zero 1 "dd" "00" day with leading zero 01 "ddd" short weekday name (abbreviation) Mon "dddd" full weekday name Monday "dddd*" full weekday name Monday "M" "0" month w/o leading zero 2 "MM" "00" month with leading zero 02 "MMM" short month name (abbreviation) Feb "MMMM" full month name Febuary "MMMM*" full month name Febuary "y" "0" two digit year (year % 100) w/o leading zero 0 "yy" "00" two digit year (year % 100) with leading zero 00 "yyy" "D3" year 2000 "yyyy" "D4" year 2000 "yyyyy" "D5" year 2000 ... "z" "+0;-0" timezone offset w/o leading zero -8 "zz" "+00;-00" timezone offset with leading zero -08 "zzz" "+00;-00" for hour offset, "00" for minute offset full timezone offset -08:00 "zzz*" "+00;-00" for hour offset, "00" for minute offset full timezone offset -08:00 "K" -Local "zzz", e.g. -08:00 -Utc "'Z'", representing UTC -Unspecified "" "g*" the current era name A.D. ":" time separator : "/" date separator / "'" quoted string 'ABC' will insert ABC into the formatted string. '"' quoted string "ABC" will insert ABC into the formatted string. "%" used to quote a single pattern characters E.g.The format character "%y" is to print two digit year. "\" escaped character E.g. '\d' insert the character 'd' into the format string. other characters insert the character into the format string. Pre-defined format characters: (U) to indicate Universal time is used. (G) to indicate Gregorian calendar is used. Format Description Real format Example ========= ================================= ====================== ======================= "d" short date culture-specific 10/31/1999 "D" long data culture-specific Sunday, October 31, 1999 "f" full date (long date + short time) culture-specific Sunday, October 31, 1999 2:00 AM "F" full date (long date + long time) culture-specific Sunday, October 31, 1999 2:00:00 AM "g" general date (short date + short time) culture-specific 10/31/1999 2:00 AM "G" general date (short date + long time) culture-specific 10/31/1999 2:00:00 AM "m"/"M" Month/Day date culture-specific October 31 (G) "o"/"O" Round Trip XML "yyyy-MM-ddTHH:mm:ss.fffffffK" 1999-10-31 02:00:00.0000000Z (G) "r"/"R" RFC 1123 date, "ddd, dd MMM yyyy HH':'mm':'ss 'GMT'" Sun, 31 Oct 1999 10:00:00 GMT (G) "s" Sortable format, based on ISO 8601. "yyyy-MM-dd'T'HH:mm:ss" 1999-10-31T02:00:00 ('T' for local time) "t" short time culture-specific 2:00 AM "T" long time culture-specific 2:00:00 AM (G) "u" Universal time with sortable format, "yyyy'-'MM'-'dd HH':'mm':'ss'Z'" 1999-10-31 10:00:00Z based on ISO 8601. (U) "U" Universal time with full culture-specific Sunday, October 31, 1999 10:00:00 AM (long date + long time) format "y"/"Y" Year/Month day culture-specific October, 1999 */ //This class contains only static members and does not require the serializable attribute. internal static class DateTimeFormat { internal const int MaxSecondsFractionDigits = 7; //// internal static char[] allStandardFormats = //// { //// 'd', 'D', 'f', 'F', 'g', 'G', //// 'm', 'M', 'o', 'O', 'r', 'R', //// 's', 't', 'T', 'u', 'U', 'y', 'Y', //// }; internal const String RoundtripFormat = "yyyy'-'MM'-'dd'T'HH':'mm':'ss.fffffffK"; //// private const int DEFAULT_ALL_DATETIMES_SIZE = 132; private static String[] fixedNumberFormats = new String[] { "0", "00", "000", "0000", "00000", "000000", "0000000", }; //////////////////////////////////////////////////////////////////////////// // // Format the positive integer value to a string and perfix with assigned // length of leading zero. // // Parameters: // value: The value to format // len: The maximum length for leading zero. // If the digits of the value is greater than len, no leading zero is added. // // Notes: // The function can format to Int32.MaxValue. // //////////////////////////////////////////////////////////////////////////// private static void FormatDigits( StringBuilder outputBuffer, int value, int len ) { BCLDebug.Assert( value >= 0, "DateTimeFormat.FormatDigits(): value >= 0" ); // Limit the use of this function to be two-digits, so that we have the same behavior // as RTM bits. if(len > 2) { len = 2; } char[] buffer = new char[16]; int offset = buffer.Length; int n = value; do { buffer[--offset] = (char)(n % 10 + '0'); n /= 10; } while((n != 0) && (offset > 0)); int digits = (int)(16 - offset); //If the repeat count is greater than 0, we're trying //to emulate the "00" format, so we have to prepend //a zero if the string only has one character. while((digits < len) && (offset > 0)) { buffer[--offset] = '0'; digits++; } outputBuffer.Append( buffer, offset, digits ); } //// private static void HebrewFormatDigits( StringBuilder outputBuffer, int digits ) //// { //// outputBuffer.Append( HebrewNumber.ToString( digits ) ); //// } static int ParseRepeatPattern( String format, int pos, char patternChar ) { int len = format.Length; int index = pos + 1; while((index < len) && (format[index] == patternChar)) { index++; } return (index - pos); } private static String FormatDayOfWeek( int dayOfWeek, int repeat, DateTimeFormatInfo dtfi ) { BCLDebug.Assert( dayOfWeek >= 0 && dayOfWeek <= 6, "dayOfWeek >= 0 && dayOfWeek <= 6" ); if(repeat == 3) { return (dtfi.GetAbbreviatedDayName( (DayOfWeek)dayOfWeek )); } // Call dtfi.GetDayName() here, instead of accessing DayNames property, because we don't // want a clone of DayNames, which will hurt perf. return (dtfi.GetDayName( (DayOfWeek)dayOfWeek )); } private static String FormatMonth( int month, int repeatCount, DateTimeFormatInfo dtfi ) { BCLDebug.Assert( month >= 1 && month <= 12, "month >=1 && month <= 12" ); if(repeatCount == 3) { return (dtfi.GetAbbreviatedMonthName( month )); } // Call GetMonthName() here, instead of accessing MonthNames property, because we don't // want a clone of MonthNames, which will hurt perf. return (dtfi.GetMonthName( month )); } //// // //// // FormatHebrewMonthName //// // //// // Action: Return the Hebrew month name for the specified DateTime. //// // Returns: The month name string for the specified DateTime. //// // Arguments: //// // time the time to format //// // month The month is the value of HebrewCalendar.GetMonth(time). //// // repeat Return abbreviated month name if repeat=3, or full month name if repeat=4 //// // dtfi The DateTimeFormatInfo which uses the Hebrew calendars as its calendar. //// // Exceptions: None. //// // //// //// /* Note: //// If DTFI is using Hebrew calendar, GetMonthName()/GetAbbreviatedMonthName() will return month names like this: //// 1 Hebrew 1st Month //// 2 Hebrew 2nd Month //// .. ... //// 6 Hebrew 6th Month //// 7 Hebrew 6th Month II (used only in a leap year) //// 8 Hebrew 7th Month //// 9 Hebrew 8th Month //// 10 Hebrew 9th Month //// 11 Hebrew 10th Month //// 12 Hebrew 11th Month //// 13 Hebrew 12th Month //// //// Therefore, if we are in a regular year, we have to increment the month name if moth is greater or eqaul to 7. //// */ //// private static String FormatHebrewMonthName( DateTime time, int month, int repeatCount, DateTimeFormatInfo dtfi ) //// { //// BCLDebug.Assert( repeatCount != 3 || repeatCount != 4, "repeateCount should be 3 or 4" ); //// if(dtfi.Calendar.IsLeapYear( dtfi.Calendar.GetYear( time ) )) //// { //// // This month is in a leap year //// return (dtfi.internalGetMonthName( month, MonthNameStyles.LeapYear, (repeatCount == 3) )); //// } //// // This is in a regular year. //// if(month >= 7) //// { //// month++; //// } //// if(repeatCount == 3) //// { //// return (dtfi.GetAbbreviatedMonthName( month )); //// } //// return (dtfi.GetMonthName( month )); //// } // // The pos should point to a quote character. This method will // get the string encloed by the quote character. // internal static int ParseQuoteString( String format, int pos, StringBuilder result ) { // // NOTE : pos will be the index of the quote character in the 'format' string. // int formatLen = format.Length; int beginPos = pos; char quoteChar = format[pos++]; // Get the character used to quote the following string. bool foundQuote = false; while(pos < formatLen) { char ch = format[pos++]; if(ch == quoteChar) { foundQuote = true; break; } else if(ch == '\\') { // The following are used to support escaped character. // Escaped character is also supported in the quoted string. // Therefore, someone can use a format like "'minute:' mm\"" to display: // minute: 45" // because the second double quote is escaped. if(pos < formatLen) { result.Append( format[pos++] ); } else { // // This means that '\' is at the end of the formatting string. // #if EXCEPTION_STRINGS throw new FormatException( Environment.GetResourceString( "Format_InvalidString" ) ); #else throw new FormatException(); #endif } } else { result.Append( ch ); } } if(!foundQuote) { // Here we can't find the matching quote. #if EXCEPTION_STRINGS throw new FormatException( String.Format( CultureInfo.CurrentCulture, Environment.GetResourceString( "Format_BadQuote" ), quoteChar ) ); #else throw new FormatException(); #endif } // // Return the character count including the begin/end quote characters and enclosed string. // return (pos - beginPos); } // // Get the next character at the index of 'pos' in the 'format' string. // Return value of -1 means 'pos' is already at the end of the 'format' string. // Otherwise, return value is the int value of the next character. // private static int ParseNextChar( String format, int pos ) { if(pos >= format.Length - 1) { return (-1); } return ((int)format[pos + 1]); } //// // //// // IsUseGenitiveForm //// // //// // Actions: Check the format to see if we should use genitive month in the formatting. //// // Starting at the position (index) in the (format) string, look back and look ahead to //// // see if there is "d" or "dd". In the case like "d MMMM" or "MMMM dd", we can use //// // genitive form. Genitive form is not used if there is more than two "d". //// // Arguments: //// // format The format string to be scanned. //// // index Where we should start the scanning. This is generally where "M" starts. //// // tokenLen The len of the current pattern character. This indicates how many "M" that we have. //// // patternToMatch The pattern that we want to search. This generally uses "d" //// // //// private static bool IsUseGenitiveForm( String format, int index, int tokenLen, char patternToMatch ) //// { //// int i; //// int repeat = 0; //// // //// // Look back to see if we can find "d" or "ddd" //// // //// //// // Find first "d". //// for(i = index - 1; i >= 0 && format[i] != patternToMatch; i--) { /*Do nothing here */ }; //// //// if(i >= 0) //// { //// // Find a "d", so look back to see how many "d" that we can find. //// while(--i >= 0 && format[i] == patternToMatch) //// { //// repeat++; //// } //// // //// // repeat == 0 means that we have one (patternToMatch) //// // repeat == 1 means that we have two (patternToMatch) //// // //// if(repeat <= 1) //// { //// return (true); //// } //// // Note that we can't just stop here. We may find "ddd" while looking back, and we have to look //// // ahead to see if there is "d" or "dd". //// } //// //// // //// // If we can't find "d" or "dd" by looking back, try look ahead. //// // //// //// // Find first "d" //// for(i = index + tokenLen; i < format.Length && format[i] != patternToMatch; i++) { /* Do nothing here */ }; //// //// if(i < format.Length) //// { //// repeat = 0; //// // Find a "d", so contine the walk to see how may "d" that we can find. //// while(++i < format.Length && format[i] == patternToMatch) //// { //// repeat++; //// } //// // //// // repeat == 0 means that we have one (patternToMatch) //// // repeat == 1 means that we have two (patternToMatch) //// // //// if(repeat <= 1) //// { //// return (true); //// } //// } //// return (false); //// } // // FormatCustomized // // Actions: Format the DateTime instance using the specified format. // private static String FormatCustomized( DateTime dateTime, String format, DateTimeFormatInfo dtfi ) { Calendar cal = dtfi.Calendar; StringBuilder result = new StringBuilder(); // This is a flag to indicate if we are format the dates using Hebrew calendar. //// bool isHebrewCalendar = (cal.ID == Calendar.CAL_HEBREW); // This is a flag to indicate if we are formating hour/minute/second only. bool bTimeOnly = true; int i = 0; int tokenLen, hour12; while(i < format.Length) { char ch = format[i]; int nextChar; switch(ch) { case 'g': tokenLen = ParseRepeatPattern( format, i, ch ); //// result.Append( dtfi.GetEraName( cal.GetEra( dateTime ) ) ); break; case 'h': tokenLen = ParseRepeatPattern( format, i, ch ); hour12 = dateTime.Hour % 12; if(hour12 == 0) { hour12 = 12; } FormatDigits( result, hour12, tokenLen ); break; case 'H': tokenLen = ParseRepeatPattern( format, i, ch ); FormatDigits( result, dateTime.Hour, tokenLen ); break; case 'm': tokenLen = ParseRepeatPattern( format, i, ch ); FormatDigits( result, dateTime.Minute, tokenLen ); break; case 's': tokenLen = ParseRepeatPattern( format, i, ch ); FormatDigits( result, dateTime.Second, tokenLen ); break; case 'f': case 'F': tokenLen = ParseRepeatPattern( format, i, ch ); if(tokenLen <= MaxSecondsFractionDigits) { long fraction = (dateTime.Ticks % Calendar.TicksPerSecond); fraction = fraction / (long)Math.Pow( 10, 7 - tokenLen ); if(ch == 'f') { result.Append( ((int)fraction).ToString( fixedNumberFormats[tokenLen - 1], CultureInfo.InvariantCulture ) ); } else { int effectiveDigits = tokenLen; while(effectiveDigits > 0) { if(fraction % 10 == 0) { fraction = fraction / 10; effectiveDigits--; } else { break; } } if(effectiveDigits > 0) { result.Append( ((int)fraction).ToString( fixedNumberFormats[effectiveDigits - 1], CultureInfo.InvariantCulture ) ); } else { // No fraction to emit, so see if we should remove decimal also. if(result.Length > 0 && result[result.Length - 1] == '.') { result.Remove( result.Length - 1, 1 ); } } } } else { #if EXCEPTION_STRINGS throw new FormatException( Environment.GetResourceString( "Format_InvalidString" ) ); #else throw new FormatException(); #endif } break; case 't': tokenLen = ParseRepeatPattern( format, i, ch ); if(tokenLen == 1) { if(dateTime.Hour < 12) { if(dtfi.AMDesignator.Length >= 1) { result.Append( dtfi.AMDesignator[0] ); } } else { if(dtfi.PMDesignator.Length >= 1) { result.Append( dtfi.PMDesignator[0] ); } } } else { result.Append( (dateTime.Hour < 12 ? dtfi.AMDesignator : dtfi.PMDesignator) ); } break; case 'd': // // tokenLen == 1 : Day of month as digits with no leading zero. // tokenLen == 2 : Day of month as digits with leading zero for single-digit months. // tokenLen == 3 : Day of week as a three-leter abbreviation. // tokenLen >= 4 : Day of week as its full name. // tokenLen = ParseRepeatPattern( format, i, ch ); if(tokenLen <= 2) { int day = cal.GetDayOfMonth( dateTime ); //// if(isHebrewCalendar) //// { //// // For Hebrew calendar, we need to convert numbers to Hebrew text for yyyy, MM, and dd values. //// HebrewFormatDigits( result, day ); //// } //// else { FormatDigits( result, day, tokenLen ); } } else { int dayOfWeek = (int)cal.GetDayOfWeek( dateTime ); result.Append( FormatDayOfWeek( dayOfWeek, tokenLen, dtfi ) ); } bTimeOnly = false; break; case 'M': // // tokenLen == 1 : Month as digits with no leading zero. // tokenLen == 2 : Month as digits with leading zero for single-digit months. // tokenLen == 3 : Month as a three-letter abbreviation. // tokenLen >= 4 : Month as its full name. // tokenLen = ParseRepeatPattern( format, i, ch ); int month = cal.GetMonth( dateTime ); if(tokenLen <= 2) { //// if(isHebrewCalendar) //// { //// // For Hebrew calendar, we need to convert numbers to Hebrew text for yyyy, MM, and dd values. //// HebrewFormatDigits( result, month ); //// } //// else { FormatDigits( result, month, tokenLen ); } } else { //// if(isHebrewCalendar) //// { //// result.Append( FormatHebrewMonthName( dateTime, month, tokenLen, dtfi ) ); //// } //// else { //// if((dtfi.FormatFlags & DateTimeFormatFlags.UseGenitiveMonth) != 0 && tokenLen >= 4) //// { //// result.Append( //// dtfi.internalGetMonthName( //// month, //// IsUseGenitiveForm( format, i, tokenLen, 'd' ) ? MonthNameStyles.Genitive : MonthNameStyles.Regular, //// false ) ); //// } //// else { result.Append( FormatMonth( month, tokenLen, dtfi ) ); } } } bTimeOnly = false; break; case 'y': // Notes about OS behavior: // y: Always print (year % 100). No leading zero. // yy: Always print (year % 100) with leading zero. // yyy/yyyy/yyyyy/... : Print year value. No leading zero. int year = cal.GetYear( dateTime ); tokenLen = ParseRepeatPattern( format, i, ch ); //// if(dtfi.HasForceTwoDigitYears) //// { //// FormatDigits( result, year, tokenLen <= 2 ? tokenLen : 2 ); //// } //// else if(cal.ID == Calendar.CAL_HEBREW) //// { //// HebrewFormatDigits( result, year ); //// } //// else { if(tokenLen <= 2) { FormatDigits( result, year % 100, tokenLen ); } else { String fmtPattern = "D" + tokenLen; result.Append( year.ToString( fmtPattern, CultureInfo.InvariantCulture ) ); } } bTimeOnly = false; break; case 'z': // // Output the offset of the timezone according to the system timezone setting. // tokenLen = ParseRepeatPattern( format, i, ch ); TimeSpan offset; if(bTimeOnly && dateTime.Ticks < Calendar.TicksPerDay) { offset = TimeZone.CurrentTimeZone.GetUtcOffset( DateTime.Now ); } else { if(dateTime.Kind == DateTimeKind.Utc) { // This code path points to a bug in user code. It would make sense to return a 0 offset in this case. // However, because it was only possible to detect this in Whidbey, there is user code that takes a // dependency on being serialize a UTC DateTime using the 'z' format, and it will work almost all the // time if it is offset by an incorrect conversion to local time when parsed. Therefore, we need to // explicitly emit the local time offset. InvalidFormatForUtc( format, dateTime ); offset = TimeZone.CurrentTimeZone.GetUtcOffset( DateTime.SpecifyKind( dateTime, DateTimeKind.Local ) ); } else { offset = TimeZone.CurrentTimeZone.GetUtcOffset( dateTime ); } } switch(tokenLen) { case 1: result.Append( (offset.Hours).ToString( "+0;-0", CultureInfo.InvariantCulture ) ); break; case 2: result.Append( (offset.Hours).ToString( "+00;-00", CultureInfo.InvariantCulture ) ); break; default: if(offset.Ticks >= 0) { result.Append( String.Format( CultureInfo.InvariantCulture, "+{0:00}:{1:00}", offset.Hours, offset.Minutes ) ); } else { // When the offset is negative, note that the offset.Minute is also negative. // So use should use -offset.Minute to get the postive value. result.Append( String.Format( CultureInfo.InvariantCulture, "-{0:00}:{1:00}", -offset.Hours, -offset.Minutes ) ); } break; } break; case 'K': tokenLen = 1; // The objective of this format is to round trip the Kind value and preserve the time zone switch(dateTime.Kind) { case DateTimeKind.Local: // This should output the local offset, e.g. "-07:00" TimeSpan localOffset = TimeZone.CurrentTimeZone.GetUtcOffset( dateTime ); if(localOffset.Ticks >= 0) { result.Append( String.Format( CultureInfo.InvariantCulture, "+{0:00}:{1:00}", localOffset.Hours, localOffset.Minutes ) ); } else { // When the offset is negative, note that the localOffset.Minute is also negative. // So use should use -localOffset.Minute to get the postive value. result.Append( String.Format( CultureInfo.InvariantCulture, "-{0:00}:{1:00}", -localOffset.Hours, -localOffset.Minutes ) ); } break; case DateTimeKind.Utc: // The 'Z' constant is a marker for a UTC date result.Append( "Z" ); break; default: // If the kind is unspecified, we output nothing here break; } break; case ':': result.Append( dtfi.TimeSeparator ); tokenLen = 1; break; case '/': result.Append( dtfi.DateSeparator ); tokenLen = 1; break; case '\'': case '\"': StringBuilder enquotedString = new StringBuilder(); tokenLen = ParseQuoteString( format, i, enquotedString ); result.Append( enquotedString ); break; case '%': // Optional format character. // For example, format string "%d" will print day of month // without leading zero. Most of the cases, "%" can be ignored. nextChar = ParseNextChar( format, i ); // nextChar will be -1 if we already reach the end of the format string. // Besides, we will not allow "%%" appear in the pattern. if(nextChar >= 0 && nextChar != (int)'%') { result.Append( FormatCustomized( dateTime, ((char)nextChar).ToString(), dtfi ) ); tokenLen = 2; } else { // // This means that '%' is at the end of the format string or // "%%" appears in the format string. // #if EXCEPTION_STRINGS throw new FormatException( Environment.GetResourceString( "Format_InvalidString" ) ); #else throw new FormatException(); #endif } break; case '\\': // Escaped character. Can be used to insert character into the format string. // For exmple, "\d" will insert the character 'd' into the string. // // NOTENOTE : we can remove this format character if we enforce the enforced quote // character rule. // That is, we ask everyone to use single quote or double quote to insert characters, // then we can remove this character. // nextChar = ParseNextChar( format, i ); if(nextChar >= 0) { result.Append( ((char)nextChar) ); tokenLen = 2; } else { // // This means that '\' is at the end of the formatting string. // #if EXCEPTION_STRINGS throw new FormatException( Environment.GetResourceString( "Format_InvalidString" ) ); #else throw new FormatException(); #endif } break; default: // NOTENOTE : we can remove this rule if we enforce the enforced quote // character rule. // That is, if we ask everyone to use single quote or double quote to insert characters, // then we can remove this default block. result.Append( ch ); tokenLen = 1; break; } i += tokenLen; } return (result.ToString()); } internal static String GetRealFormat( String format, DateTimeFormatInfo dtfi ) { String realFormat = null; switch(format[0]) { case 'd': // Short Date realFormat = dtfi.ShortDatePattern; break; case 'D': // Long Date realFormat = dtfi.LongDatePattern; break; case 'f': // Full (long date + short time) realFormat = dtfi.LongDatePattern + " " + dtfi.ShortTimePattern; break; case 'F': // Full (long date + long time) realFormat = dtfi.FullDateTimePattern; break; case 'g': // General (short date + short time) realFormat = dtfi.GeneralShortTimePattern; break; case 'G': // General (short date + long time) realFormat = dtfi.GeneralLongTimePattern; break; case 'm': case 'M': // Month/Day Date realFormat = dtfi.MonthDayPattern; break; case 'o': case 'O': realFormat = RoundtripFormat; break; case 'r': case 'R': // RFC 1123 Standard realFormat = dtfi.RFC1123Pattern; break; case 's': // Sortable without Time Zone Info realFormat = dtfi.SortableDateTimePattern; break; case 't': // Short Time realFormat = dtfi.ShortTimePattern; break; case 'T': // Long Time realFormat = dtfi.LongTimePattern; break; case 'u': // Universal with Sortable format realFormat = dtfi.UniversalSortableDateTimePattern; break; case 'U': // Universal with Full (long date + long time) format realFormat = dtfi.FullDateTimePattern; break; case 'y': case 'Y': // Year/Month Date realFormat = dtfi.YearMonthPattern; break; default: #if EXCEPTION_STRINGS throw new FormatException( Environment.GetResourceString( "Format_InvalidString" ) ); #else throw new FormatException(); #endif } return (realFormat); } // Expand a pre-defined format string (like "D" for long date) to the real format that // we are going to use in the date time parsing. // This method also convert the dateTime if necessary (e.g. when the format is in Universal time), // and change dtfi if necessary (e.g. when the format should use invariant culture). // private static String ExpandPredefinedFormat( String format, ref DateTime dateTime, ref DateTimeFormatInfo dtfi ) { switch(format[0]) { case 'o': case 'O': // Round trip format dtfi = DateTimeFormatInfo.InvariantInfo; break; case 'r': case 'R': // RFC 1123 Standard if(dateTime.Kind == DateTimeKind.Local) { InvalidFormatForLocal( format, dateTime ); } dtfi = DateTimeFormatInfo.InvariantInfo; break; case 's': // Sortable without Time Zone Info dtfi = DateTimeFormatInfo.InvariantInfo; break; case 'u': // Universal time in sortable format. if(dateTime.Kind == DateTimeKind.Local) { InvalidFormatForLocal( format, dateTime ); } dtfi = DateTimeFormatInfo.InvariantInfo; break; case 'U': // Universal time in culture dependent format. // Universal time is always in Greogrian calendar. // // Change the Calendar to be Gregorian Calendar. // //// dtfi = (DateTimeFormatInfo)dtfi.Clone(); //// if(dtfi.Calendar.GetType() != typeof( GregorianCalendar )) //// { //// dtfi.Calendar = GregorianCalendar.GetDefaultInstance(); //// } //// dateTime = dateTime.ToUniversalTime(); dtfi = DateTimeFormatInfo.InvariantInfo; break; } format = GetRealFormat( format, dtfi ); return (format); } internal static String Format( DateTime dateTime, DateTimeFormatInfo dtfi ) { string format = dtfi.GeneralLongTimePattern; Calendar cal = dtfi.Calendar; StringBuilder result = new StringBuilder(); int i = 0; int tokenLen; while(i < format.Length) { char ch = format[i]; switch(ch) { case 'M': // // tokenLen == 1 : Month as digits with no leading zero. // tokenLen == 2 : Month as digits with leading zero for single-digit months. // tokenLen == 3 : Month as a three-letter abbreviation. // tokenLen >= 4 : Month as its full name. // tokenLen = ParseRepeatPattern( format, i, ch ); int month = cal.GetMonth( dateTime ); if(tokenLen <= 2) { //// if(isHebrewCalendar) //// { //// // For Hebrew calendar, we need to convert numbers to Hebrew text for yyyy, MM, and dd values. //// HebrewFormatDigits( result, month ); //// } //// else { FormatDigits( result, month, tokenLen ); } } else { //// if(isHebrewCalendar) //// { //// result.Append( FormatHebrewMonthName( dateTime, month, tokenLen, dtfi ) ); //// } //// else { //// if((dtfi.FormatFlags & DateTimeFormatFlags.UseGenitiveMonth) != 0 && tokenLen >= 4) //// { //// result.Append( //// dtfi.internalGetMonthName( //// month, //// IsUseGenitiveForm( format, i, tokenLen, 'd' ) ? MonthNameStyles.Genitive : MonthNameStyles.Regular, //// false ) ); //// } //// else { result.Append( FormatMonth( month, tokenLen, dtfi ) ); } } } break; case 'd': // // tokenLen == 1 : Day of month as digits with no leading zero. // tokenLen == 2 : Day of month as digits with leading zero for single-digit months. // tokenLen == 3 : Day of week as a three-leter abbreviation. // tokenLen >= 4 : Day of week as its full name. // tokenLen = ParseRepeatPattern( format, i, ch ); if(tokenLen <= 2) { int day = cal.GetDayOfMonth( dateTime ); //// if(isHebrewCalendar) //// { //// // For Hebrew calendar, we need to convert numbers to Hebrew text for yyyy, MM, and dd values. //// HebrewFormatDigits( result, day ); //// } //// else { FormatDigits( result, day, tokenLen ); } } else { int dayOfWeek = (int)cal.GetDayOfWeek( dateTime ); result.Append( FormatDayOfWeek( dayOfWeek, tokenLen, dtfi ) ); } break; case 'y': // Notes about OS behavior: // y: Always print (year % 100). No leading zero. // yy: Always print (year % 100) with leading zero. // yyy/yyyy/yyyyy/... : Print year value. No leading zero. int year = cal.GetYear( dateTime ); tokenLen = ParseRepeatPattern( format, i, ch ); //// if(dtfi.HasForceTwoDigitYears) //// { //// FormatDigits( result, year, tokenLen <= 2 ? tokenLen : 2 ); //// } //// else if(cal.ID == Calendar.CAL_HEBREW) //// { //// HebrewFormatDigits( result, year ); //// } //// else { if(tokenLen <= 2) { FormatDigits( result, year % 100, tokenLen ); } else { FormatDigits( result, year, tokenLen ); //String fmtPattern = "D" + tokenLen; //result.Append( year.ToString( fmtPattern, CultureInfo.InvariantCulture ) ); } } break; case 'H': tokenLen = ParseRepeatPattern( format, i, ch ); FormatDigits( result, dateTime.Hour, tokenLen ); break; case 'm': tokenLen = ParseRepeatPattern( format, i, ch ); FormatDigits( result, dateTime.Minute, tokenLen ); break; case 's': tokenLen = ParseRepeatPattern( format, i, ch ); FormatDigits( result, dateTime.Second, tokenLen ); break; default: // NOTENOTE : we can remove this rule if we enforce the enforced quote // character rule. // That is, if we ask everyone to use single quote or double quote to insert characters, // then we can remove this default block. //result.Append( ch ); tokenLen = 1; break; } i += tokenLen; } return result.ToString(); } internal static String Format( DateTime dateTime, String format, DateTimeFormatInfo dtfi ) { if(format == null || format.Length == 0) { format = "G"; //// if(dateTime.Ticks < Calendar.TicksPerDay) //// { //// // If the time is less than 1 day, consider it as time of day. //// // Just print out the short time format. //// // //// // This is a workaround for VB, since they use ticks less then one day to be //// // time of day. In cultures which use calendar other than Gregorian calendar, these //// // alternative calendar may not support ticks less than a day. //// // For example, Japanese calendar only supports date after 1868/9/8. //// // This will pose a problem when people in VB get the time of day, and use it //// // to call ToString(), which will use the general format (short date + long time). //// // Since Japanese calendar does not support Gregorian year 0001, an exception will be //// // thrown when we try to get the Japanese year for Gregorian year 0001. //// // Therefore, the workaround allows them to call ToString() for time of day from a DateTime by //// // formatting as ISO 8601 format. //// switch(dtfi.Calendar.ID) //// { //// case Calendar.CAL_JAPAN: //// case Calendar.CAL_TAIWAN: //// case Calendar.CAL_HIJRI: //// case Calendar.CAL_HEBREW: //// case Calendar.CAL_JULIAN: //// format = "s"; //// break; //// } //// } } if(format.Length == 1) { format = ExpandPredefinedFormat( format, ref dateTime, ref dtfi ); } return (FormatCustomized( dateTime, format, dtfi )); } //// internal static String[] GetAllDateTimes( DateTime dateTime, char format, DateTimeFormatInfo dtfi ) //// { //// String[] allFormats = null; //// String[] results = null; //// //// switch(format) //// { //// case 'd': //// case 'D': //// case 'f': //// case 'F': //// case 'g': //// case 'G': //// case 'm': //// case 'M': //// case 't': //// case 'T': //// case 'y': //// case 'Y': //// allFormats = dtfi.GetAllDateTimePatterns( format ); //// results = new String[allFormats.Length]; //// for(int i = 0; i < allFormats.Length; i++) //// { //// results[i] = Format( dateTime, allFormats[i], dtfi ); //// } //// break; //// case 'U': //// DateTime universalTime = dateTime.ToUniversalTime(); //// allFormats = dtfi.GetAllDateTimePatterns( format ); //// results = new String[allFormats.Length]; //// for(int i = 0; i < allFormats.Length; i++) //// { //// results[i] = Format( universalTime, allFormats[i], dtfi ); //// } //// break; //// // //// // The following ones are special cases because these patterns are read-only in //// // DateTimeFormatInfo. //// // //// case 'r': //// case 'R': //// case 'o': //// case 'O': //// case 's': //// case 'u': //// results = new String[] { Format( dateTime, new String( new char[] { format } ), dtfi ) }; //// break; //// default: //// throw new FormatException( Environment.GetResourceString( "Format_InvalidString" ) ); //// //// } //// return (results); //// } //// //// internal static String[] GetAllDateTimes( DateTime dateTime, DateTimeFormatInfo dtfi ) //// { //// ArrayList results = new ArrayList( DEFAULT_ALL_DATETIMES_SIZE ); //// //// for(int i = 0; i < allStandardFormats.Length; i++) //// { //// String[] strings = GetAllDateTimes( dateTime, allStandardFormats[i], dtfi ); //// for(int j = 0; j < strings.Length; j++) //// { //// results.Add( strings[j] ); //// } //// } //// String[] value = new String[results.Count]; //// results.CopyTo( 0, value, 0, results.Count ); //// return (value); //// } // This is a placeholder for an MDA to detect when the user is using a // local DateTime with a format that will be interpreted as UTC. internal static void InvalidFormatForLocal( String format, DateTime dateTime ) { } // This is an MDA for cases when the user is using a local format with // a Utc DateTime. internal static void InvalidFormatForUtc( String format, DateTime dateTime ) { #if MDA_SUPPORTED //// Mda.DateTimeInvalidLocalFormat(); #endif } } } ================================================ FILE: Zelig/Zelig/RunTime/Framework/mscorlib/System/Globalization/DateTimeFormatInfo.cs ================================================ // ==++== // // Copyright (c) Microsoft Corporation. All rights reserved. // // ==--== namespace System.Globalization { using System; using System.Security; using System.Threading; using System.Collections; using System.Runtime.Serialization; using System.Security.Permissions; using System.Runtime.InteropServices; using System.Runtime.CompilerServices; using System.Text; // // Flags used to indicate different styles of month names. // This is an internal flag used by internalGetMonthName(). // Use flag here in case that we need to provide a combination of these styles // (such as month name of a leap year in genitive form. Not likely for now, // but would like to keep the option open). // [Flags] internal enum MonthNameStyles { Regular = 0x00000000, Genitive = 0x00000001, LeapYear = 0x00000002, } // // Flags used to indicate special rule used in parsing/formatting // for a specific DateTimeFormatInfo instance. // This is an internal flag. // // This flag is different from MonthNameStyles because this flag // can be expanded to accomodate parsing behaviors like CJK month names // or alternative month names, etc. [Flags] internal enum DateTimeFormatFlags { None = 0x00000000, UseGenitiveMonth = 0x00000001, UseLeapYearMonth = 0x00000002, UseSpacesInMonthNames = 0x00000004, // Has spaces or non-breaking space in the month names. UseHebrewRule = 0x00000008, // Format/Parse using the Hebrew calendar rule. UseSpacesInDayNames = 0x00000010, // Has spaces or non-breaking space in the day names. UseDigitPrefixInTokens = 0x00000020, // Has token starting with numbers. NotInitialized = -1, } [Serializable] public sealed class DateTimeFormatInfo /*: ICloneable, IFormatProvider*/ { // cache for the invarinat culture. // invariantInfo is constant irrespective of your current culture. private static DateTimeFormatInfo invariantInfo; //// // an index which points to a record in Culture Data Table. //// [NonSerialized] //// internal CultureTableRecord m_cultureTableRecord; //// //// // The culture name used to create this DTFI. //// [OptionalField( VersionAdded = 2 )] //// internal String m_name = null; //// //// // The language name of the culture used to create this DTFI. //// [NonSerialized] //// internal String m_langName = null; //// //// // CompareInfo usually used by the parser. //// [NonSerialized] //// internal CompareInfo m_compareInfo = null; // Flag to indicate if the specified calendar for this DTFI is the // default calendar stored in the culture.nlp. internal bool m_isDefaultCalendar; //// internal int CultureId { get { return this.m_cultureTableRecord.CultureID; } } //// //// // Flags to indicate if we want to retreive the information from calendar data table (calendar.nlp) or from culture data table (culture.nlp). //// // If the flag is true, we will retrieve the data from calendar data table (calendar.nlp). //// // If the flag is false, we will retrieve the data from culture data table (culture.nlp) or from the control panel settings. //// // The follwoing set of information both exist in culture.nlp and calendar.nlp. //// // //// // LongDatePattern //// // ShortDatePattern //// // YearMonthPattern //// // //// // This flag is needed so that we can support the following scenario: //// // CultureInfo ci = new CultureInfo("ja-jp"); // Japanese. The default calendar for it is GregorianCalendar. //// // ci.Calendar = new JapaneseCalendar(); // Assign the calendar to be Japanese now. //// // String str = DateTimeFormatInfo.GetInstance(ci).LongDatePattern; //// // //// // The new behavior will return "gg y'\x5e74'M'\x6708'd'\x65e5'".. This is the right pattern for Japanese calendar. //// // Previous, it returned "yyyy'\x5e74'M'\x6708'd'\x65e5'". This is wrong because it is the format for Gregorain. //// // //// // The default value is false, so we will get information from culture for the invariant culture. //// // //// // The value is decided when DateTimeFormatInfo is created in CultureInfo.GetDateTimeFormatInfo() //// // The logic is like this: //// // If the specified culture is the user default culture in the system, we have to look at the calendar setting in the control panel. //// // If the calendar is the same as the calendar setting in the control panel, we have to take the date patterns/month names/day names //// // from the control panel. By doing this, we can get the user overridden values in the control panel. //// // Otherwise, we should get the date patterns/month names/day names from the calendar.nlp if the calendar is not Gregorian localized. //// // If the specified culture is NOT the user default culture in the system, //// // Check if the calendar is Gregorian localized? //// // If yes, we use the date patterns/month names/day names from culture.nlp. //// // Otherwise, use the date patterns/month names/day names from calendar.nlp. //// internal bool bUseCalendarInfo = false; //// //// // //// // Caches for various properties. //// // //// internal String amDesignator = null; //// internal String pmDesignator = null; //// internal String dateSeparator = null; //// internal String longTimePattern = null; //// internal String shortTimePattern = null; //// internal String generalShortTimePattern = null; //// internal String generalLongTimePattern = null; //// internal String timeSeparator = null; //// internal String monthDayPattern = null; //// //// // In case default time/date pattern included in the all patterns array then we always set it as first item. //// // that is to be easy to know if we need to add the default pattern to the array when the array is requested. //// // look at SetDefaultPatternAsFirstItem to see how we do that. //// internal String[] allShortTimePatterns = null; //// internal String[] allLongTimePatterns = null; // // The following are constant values. // internal const String rfc1123Pattern = "ddd, dd MMM yyyy HH':'mm':'ss 'GMT'"; // The sortable pattern is based on ISO 8601. internal const String sortableDateTimePattern = "yyyy'-'MM'-'dd'T'HH':'mm':'ss"; internal const String universalSortableDateTimePattern = "yyyy'-'MM'-'dd HH':'mm':'ss'Z'"; // // The following are affected by calendar settings. // internal Calendar calendar = null; //// internal int firstDayOfWeek = -1; //// internal int calendarWeekRule = -1; //// //// internal String fullDateTimePattern = null; //// //// internal String longDatePattern = null; //// //// internal String shortDatePattern = null; //// //// internal String yearMonthPattern = null; //// //// internal String[] abbreviatedDayNames = null; //// //// [OptionalField( VersionAdded = 2 )] //// internal String[] m_superShortDayNames = null; internal String[] dayNames = null; internal String[] abbreviatedMonthNames = null; internal String[] monthNames = null; //// // Cache the genitive month names that we retrieve from the data table. //// [OptionalField( VersionAdded = 2 )] //// internal String[] genitiveMonthNames = null; //// //// // Cache the abbreviated genitive month names that we retrieve from the data table. //// [OptionalField( VersionAdded = 2 )] //// internal String[] m_genitiveAbbreviatedMonthNames = null; //// //// // Cache the month names of a leap year that we retrieve from the data table. //// [OptionalField( VersionAdded = 2 )] //// internal String[] leapYearMonthNames = null; //// //// // In case default time/date pattern included in the all patterns array then we always set it as first item. //// // that is to be easy to know if we need to add the default pattern to the array when the array is requested. //// // look at SetDefaultPatternAsFirstItem to see how we do that. //// //// [NonSerialized] // this is lazy intialized so no need to serialize it. //// internal String[] allYearMonthPatterns = null; //// internal String[] allShortDatePatterns = null; //// internal String[] allLongDatePatterns = null; //// //// //// //// // Cache the era names for this DateTimeFormatInfo instance. //// internal String[] m_eraNames = null; //// internal String[] m_abbrevEraNames = null; //// internal String[] m_abbrevEnglishEraNames = null; //// //// internal String[] m_dateWords = null; //// //// internal int[] optionalCalendars = null; //// //// private const int DEFAULT_ALL_DATETIMES_SIZE = 132; //// //// internal bool m_isReadOnly = false; //// // This flag gives hints about if formatting/parsing should perform special code path for things like //// // genitive form or leap year month names. //// [OptionalField( VersionAdded = 2 )] //// internal DateTimeFormatFlags formatFlags = DateTimeFormatFlags.NotInitialized; //// //// private static Hashtable m_calendarNativeNames; // Maps from calendar Id to calendar native name. //// private static Object s_InternalSyncObject; //// //// private static Object InternalSyncObject //// { //// get //// { //// if(s_InternalSyncObject == null) //// { //// Object o = new Object(); //// Interlocked.CompareExchange( ref s_InternalSyncObject, o, null ); //// } //// return s_InternalSyncObject; //// } //// } //// //// internal String CultureName //// { //// get //// { //// if(m_name == null) //// { //// m_name = this.m_cultureTableRecord.SNAME; //// } //// return (m_name); //// } //// } //// //// internal String LanguageName //// { //// get //// { //// if(m_langName == null) //// { //// m_langName = this.m_cultureTableRecord.SISO639LANGNAME; //// } //// return (m_langName); //// } //// } //// //// //////////////////////////////////////////////////////////////////////////// //// // //// // Create an array of string which contains the abbreviated day names. //// // //// //////////////////////////////////////////////////////////////////////////// //// //// private String[] GetAbbreviatedDayOfWeekNames() //// { //// if(abbreviatedDayNames == null) //// { //// if(abbreviatedDayNames == null) //// { //// String[] temp = null; //// if(!m_isDefaultCalendar) //// { //// BCLDebug.Assert( Calendar.ID > 0, "[DateTimeFormatInfo.GetAbbreviatedDayOfWeekNames] Expected Calendar.ID > 0" ); //// temp = CalendarTable.Default.SABBREVDAYNAMES( Calendar.ID ); //// } //// if(temp == null || temp.Length == 0 || //// temp[0].Length == 0) //// temp = this.m_cultureTableRecord.SABBREVDAYNAMES; //// System.Threading.Thread.MemoryBarrier(); //// abbreviatedDayNames = temp; //// BCLDebug.Assert( abbreviatedDayNames.Length == 7, "[DateTimeFormatInfo.GetAbbreviatedDayOfWeekNames] Expected 7 day names in a week" ); //// } //// } //// return (abbreviatedDayNames); //// } //// //// //////////////////////////////////////////////////////////////////////// //// // //// // Action: Returns the string array of the one-letter day of week names. //// // Returns: //// // an array of one-letter day of week names //// // Arguments: //// // None //// // Exceptions: //// // None //// // //// //////////////////////////////////////////////////////////////////////// //// //// private String[] internalGetSuperShortDayNames() //// { //// if(this.m_superShortDayNames == null) //// { //// if(this.m_superShortDayNames == null) //// { //// String[] temp = null; //// if(!m_isDefaultCalendar) //// { //// BCLDebug.Assert( Calendar.ID > 0, "[DateTimeFormatInfo.internalGetSuperShortDayNames] Expected Calendar.ID > 0" ); //// temp = CalendarTable.Default.SSUPERSHORTDAYNAMES( Calendar.ID ); //// } //// if(temp == null || temp.Length == 0 || //// temp[0].Length == 0) //// temp = this.m_cultureTableRecord.SSUPERSHORTDAYNAMES; //// System.Threading.Thread.MemoryBarrier(); //// this.m_superShortDayNames = temp; //// BCLDebug.Assert( this.m_superShortDayNames.Length == 7, "[DateTimeFormatInfo.internalGetSuperShortDayNames] Expected 7 day names in a week" ); //// } //// } //// return (this.m_superShortDayNames); //// } //// //// //////////////////////////////////////////////////////////////////////////// //// // //// // Create an array of string which contains the day names. //// // //// //////////////////////////////////////////////////////////////////////////// //// //// private String[] GetDayOfWeekNames() //// { //// if(dayNames == null) //// { //// if(dayNames == null) //// { //// String[] temp = null; //// if(!m_isDefaultCalendar) //// { //// BCLDebug.Assert( Calendar.ID > 0, "[DateTimeFormatInfo.GetDayOfWeekNames] Expected Calendar.ID > 0" ); //// temp = CalendarTable.Default.SDAYNAMES( Calendar.ID ); //// } //// if(temp == null || temp.Length == 0 || //// temp[0].Length == 0) //// temp = this.m_cultureTableRecord.SDAYNAMES; //// System.Threading.Thread.MemoryBarrier(); //// dayNames = temp; //// BCLDebug.Assert( dayNames.Length == 7, "[DateTimeFormatInfo.GetDayOfWeekNames] Expected 7 day names in a week" ); //// } //// } //// return (dayNames); //// } //////////////////////////////////////////////////////////////////////////// // // Create an array of string which contains the abbreviated month names. // //////////////////////////////////////////////////////////////////////////// private String[] GetAbbreviatedMonthNames() { if(abbreviatedMonthNames == null) { //// String[] temp = null; //// if(!m_isDefaultCalendar) //// { //// BCLDebug.Assert( Calendar.ID > 0, "[DateTimeFormatInfo.GetAbbreviatedMonthNames] Expected Calendar.ID > 0" ); //// temp = CalendarTable.Default.SABBREVMONTHNAMES( Calendar.ID ); //// } //// if(temp == null || temp.Length == 0 || //// temp[0].Length == 0) //// temp = this.m_cultureTableRecord.SABBREVMONTHNAMES; //// System.Threading.Thread.MemoryBarrier(); abbreviatedMonthNames = new [] { "Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec", "" }; //// BCLDebug.Assert( abbreviatedMonthNames.Length == 12 || abbreviatedMonthNames.Length == 13, //// "[DateTimeFormatInfo.GetAbbreviatedMonthNames] Expected 12 or 13 month names in a year" ); } return (abbreviatedMonthNames); } //////////////////////////////////////////////////////////////////////////// // // Create an array of string which contains the month names. // //////////////////////////////////////////////////////////////////////////// private String[] GetMonthNames() { if(monthNames == null) { //// String[] temp = null; //// if(!m_isDefaultCalendar) //// { //// BCLDebug.Assert( Calendar.ID > 0, "[DateTimeFormatInfo.GetMonthNames] Expected Calendar.ID > 0" ); //// temp = CalendarTable.Default.SMONTHNAMES( Calendar.ID ); //// } //// if(temp == null || temp.Length == 0 || //// temp[0].Length == 0) //// temp = this.m_cultureTableRecord.SMONTHNAMES; //// System.Threading.Thread.MemoryBarrier(); monthNames = new [] { "January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December", "" }; //// BCLDebug.Assert( MonthNames.Length == 12 || MonthNames.Length == 13, //// "[DateTimeFormatInfo.GetMonthNames] Expected 12 or 13 month names in a year" ); } return (monthNames); } public DateTimeFormatInfo() { //// // //// // Invariant DateTimeFormatInfo doesn't have user-overriden values, so we pass false in useUserOverride. //// // //// this.m_cultureTableRecord = CultureInfo.InvariantCulture.m_cultureTableRecord; // In Invariant culture, the default calendar store in culture.nlp is Gregorian localized. // And the date/time pattern for invariant culture stored in this.m_isDefaultCalendar = true; this.calendar = GregorianCalendar.GetDefaultInstance(); //// //// // We don't have to call the setter of Calendar property here because the Calendar getter //// // will return Gregorian localized calendar by default. //// InitializeOverridableProperties(); } //// internal DateTimeFormatInfo( CultureTableRecord cultureTable, int cultureID, Calendar cal ) //// { //// this.m_cultureTableRecord = cultureTable; //// // m_isDefaultCalendar is set in the setter of Calendar below. //// this.Calendar = cal; //// } //// //// #region Serialization //// // The following fields are defined to keep the serialization compatibility with .NET V1.0/V1.1. //// private int CultureID; //// private bool m_useUserOverride; //// private int nDataItem; //// //// [OnDeserialized] //// private void OnDeserialized( StreamingContext ctx ) //// { //// BCLDebug.Assert( CultureID >= 0, "[DateTimeFormatInfo.OnDeserialized] clulture ID < 0" ); //// //// if(CultureTableRecord.IsCustomCultureId( CultureID )) //// m_cultureTableRecord = CultureTableRecord.GetCultureTableRecord( m_name, m_useUserOverride ); //// else //// m_cultureTableRecord = CultureTableRecord.GetCultureTableRecord( CultureID, m_useUserOverride ); //// //// if(calendar == null) //// { //// calendar = (Calendar)GregorianCalendar.GetDefaultInstance().Clone(); //// calendar.SetReadOnlyState( m_isReadOnly ); //// } //// else //// { //// CultureInfo.CheckDomainSafetyObject( calendar, this ); //// } //// //// InitializeOverridableProperties(); //// } //// //// [OnSerializing] //// private void OnSerializing( StreamingContext ctx ) //// { //// CultureID = m_cultureTableRecord.CultureID; //// m_useUserOverride = m_cultureTableRecord.UseUserOverride; //// nDataItem = m_cultureTableRecord.EverettDataItem(); //// //// // //// // If we have custom culture then we serialize a valid name so it can be used //// // during the deserialization as we cannot use the CultureID at that time. //// // //// //// if(CultureTableRecord.IsCustomCultureId( CultureID )) //// { //// // make sure the m_name is initialized. //// m_name = this.CultureName; //// } //// } //// #endregion Serialization // Returns a default DateTimeFormatInfo that will be universally // supported and constant irrespective of the current culture. // Used by FromString methods. // public static DateTimeFormatInfo InvariantInfo { get { if(invariantInfo == null) { DateTimeFormatInfo info = new DateTimeFormatInfo(); //// info.Calendar.SetReadOnlyState( true ); //// info.m_isReadOnly = true; invariantInfo = info; } return (invariantInfo); } } // Returns the current culture's DateTimeFormatInfo. Used by Parse methods. // public static DateTimeFormatInfo CurrentInfo { get { System.Globalization.CultureInfo culture = System.Threading.Thread.CurrentThread.CurrentCulture; //// if(!culture.m_isInherited) //// { DateTimeFormatInfo info = culture.DateTimeFormat; //// if(info != null) //// { return info; //// } //// } //// return (DateTimeFormatInfo)culture.GetFormat( typeof( DateTimeFormatInfo ) ); } } [MethodImplAttribute( MethodImplOptions.InternalCall )] public static extern DateTimeFormatInfo GetInstance( IFormatProvider provider ); //// { //// // Fast case for a regular CultureInfo //// DateTimeFormatInfo info; //// CultureInfo cultureProvider = provider as CultureInfo; //// if(cultureProvider != null && !cultureProvider.m_isInherited) //// { //// info = cultureProvider.dateTimeInfo; //// if(info != null) //// { //// return info; //// } //// else //// { //// return cultureProvider.DateTimeFormat; //// } //// } //// // Fast case for a DTFI; //// info = provider as DateTimeFormatInfo; //// if(info != null) //// { //// return info; //// } //// if(provider != null) //// { //// info = provider.GetFormat( typeof( DateTimeFormatInfo ) ) as DateTimeFormatInfo; //// if(info != null) //// { //// return info; //// } //// } //// return CurrentInfo; //// } //// //// //// public Object GetFormat( Type formatType ) //// { //// return (formatType == typeof( DateTimeFormatInfo ) ? this : null); //// } //// //// //// public Object Clone() //// { //// DateTimeFormatInfo n = (DateTimeFormatInfo)MemberwiseClone(); //// // We can use the data member calendar in the setter, instead of the property Calendar, //// // since the cloned copy should have the same state as the original copy. //// n.calendar = (Calendar)this.Calendar.Clone(); //// n.m_isReadOnly = false; //// return n; //// } public String AMDesignator { get { return "AM"; //// BCLDebug.Assert( amDesignator != null, "DateTimeFormatInfo.AMDesignator, amDesignator != null" ); //// return (amDesignator); } //// set //// { //// VerifyWritable(); //// if(value == null) //// { //// throw new ArgumentNullException( "value", //// Environment.GetResourceString( "ArgumentNull_String" ) ); //// } //// ClearTokenHashTable( true ); //// amDesignator = value; //// } } //// private void InitializeOverridableProperties() //// { //// // These properties are not affected by calendar settings. And they should be always initialized. //// //// if(amDesignator == null) { amDesignator = m_cultureTableRecord.S1159; } //// if(pmDesignator == null) { pmDesignator = m_cultureTableRecord.S2359; } //// if(longTimePattern == null) { longTimePattern = m_cultureTableRecord.STIMEFORMAT; } //// if(firstDayOfWeek == -1) { firstDayOfWeek = m_cultureTableRecord.IFIRSTDAYOFWEEK; } //// if(calendarWeekRule == -1) { calendarWeekRule = m_cultureTableRecord.IFIRSTWEEKOFYEAR; } //// //// // These 3 properties are affected by calendar settings. //// if(yearMonthPattern == null) { yearMonthPattern = GetYearMonthPattern( calendar.ID ); } //// if(shortDatePattern == null) { shortDatePattern = GetShortDatePattern( calendar.ID ); } //// if(longDatePattern == null) { longDatePattern = GetLongDatePattern( calendar.ID ); } //// } public Calendar Calendar { get { //// BCLDebug.Assert( calendar != null, "DateTimeFormatInfo.Calendar: calendar != null" ); return (calendar); } //// set //// { //// VerifyWritable(); //// if(value == null) //// { //// throw new ArgumentNullException( "value", //// Environment.GetResourceString( "ArgumentNull_Obj" ) ); //// } //// if(value == calendar) //// { //// return; //// } //// //// // //// // Because the culture is agile object which can be attached to a thread and then thread can travel //// // to another app domain then we prevent attaching any customized object to culture that we cannot contol. //// // //// CultureInfo.CheckDomainSafetyObject( value, this ); //// //// for(int i = 0; i < OptionalCalendars.Length; i++) //// { //// if(OptionalCalendars[i] == value.ID) //// { //// ClearTokenHashTable( false ); //// // //// // Get the current Win32 user culture. //// // //// m_isDefaultCalendar = (value.ID == Calendar.CAL_GREGORIAN); //// /* //// When UseUserOverride is TRUE, we should follow the following table //// to retrieve date/time patterns. //// //// CurrentCulture: Is the culture which creates the DTFI the current user default culture //// specified in the control panel? //// CurrentCalendar: Is the specified calendar the current calendar specified in the control panel? //// n/r: not relavent, don't care. //// //// Case CurrentCulture? CurrentCalendar? GregorianLocalized? Get Data from //// ---- --------------- ---------------- ------------------- -------------------------- //// 1 Y Y n/r registry & culture.nlp (for user-overridable data) //// 2 n/r n/r Y culture.nlp //// 3 n/r n/r N CALENDAR.nlp* //// */ //// //// if(calendar != null) //// { //// // clean related properties which are affected by the calendar setting, //// // so that they will be refreshed when they are accessed next time. //// // //// //// // These properites are in the order as appearing in calendar.xml. //// m_eraNames = null; //// m_abbrevEraNames = null; //// m_abbrevEnglishEraNames = null; //// //// shortDatePattern = null; //// yearMonthPattern = null; //// monthDayPattern = null; //// longDatePattern = null; //// //// dayNames = null; //// abbreviatedDayNames = null; //// m_superShortDayNames = null; //// monthNames = null; //// abbreviatedMonthNames = null; //// genitiveMonthNames = null; //// m_genitiveAbbreviatedMonthNames = null; //// leapYearMonthNames = null; //// formatFlags = DateTimeFormatFlags.NotInitialized; //// //// // These properies are not in calendar.xml, but they are dependent on the values like shortDatePattern. //// fullDateTimePattern = null; //// generalShortTimePattern = null; //// generalLongTimePattern = null; //// allShortDatePatterns = null; //// allLongDatePatterns = null; //// allYearMonthPatterns = null; //// //// //// } //// //// calendar = value; //// //// // Retrieve the settings that can be overridden by users. //// // TODO: This doesn't guarantee current cultureness for custom culture. //// if(this.m_cultureTableRecord.UseCurrentCalendar( value.ID )) //// { //// // //// // [Case 1] //// // //// // If user overriden values are allowed, and the culture is the user default culture //// // and the specified calendar matches the calendar setting in the control panel, //// // use data from registry by setting bUseCalendarInfo to be false. //// // //// DTFIUserOverrideValues temp = new DTFIUserOverrideValues(); //// //// // If this is the first time calendar is set, just assign //// // the value to calendar. We don't have to clean up //// // related fields. //// // We need to retrieve all user-override values and cache them to avoid to get different //// // values between calls to CultureInfo.ClearCachedData() //// m_cultureTableRecord.GetDTFIOverrideValues( ref temp ); //// //// //// amDesignator = temp.amDesignator; //// pmDesignator = temp.pmDesignator; //// longTimePattern = temp.longTimePattern; //// firstDayOfWeek = (int)temp.firstDayOfWeek; //// calendarWeekRule = (int)temp.calendarWeekRule; //// shortDatePattern = temp.shortDatePattern; //// longDatePattern = temp.longDatePattern; //// yearMonthPattern = temp.yearMonthPattern; //// //// // There is also a NLS bug that GetLocaleInfo returns incorrect YearMonth pattern when the reg key of for YearMonth does not //// // exists. GetDTFIOverrideValues() will leave yearMonthPattern to be null in that case. //// //// // In these cases, fall back to the table value. //// //// if(yearMonthPattern == null) //// { //// yearMonthPattern = GetYearMonthPattern( value.ID ); //// } //// //// } //// else //// { //// // Case 2 & Case 3 //// //// InitializeOverridableProperties(); //// } //// return; //// } //// } //// // The assigned calendar is not a valid calendar for this culture. //// throw new ArgumentOutOfRangeException( "value", Environment.GetResourceString( "Argument_InvalidCalendar" ) ); //// } } //// internal int[] OptionalCalendars //// { //// get //// { //// if(optionalCalendars == null) //// { //// optionalCalendars = this.m_cultureTableRecord.IOPTIONALCALENDARS; //// } //// return (optionalCalendars); //// } //// } //// //// /*=================================GetEra========================== //// **Action: Get the era value by parsing the name of the era. //// **Returns: The era value for the specified era name. //// ** -1 if the name of the era is not valid or not supported. //// **Arguments: eraName the name of the era. //// **Exceptions: None. //// ============================================================================*/ //// //// //// public int GetEra( String eraName ) //// { //// if(eraName == null) //// { //// throw new ArgumentNullException( "eraName", //// Environment.GetResourceString( "ArgumentNull_String" ) ); //// } //// //// // The following is based on the assumption that the era value is starting from 1, and has a //// // serial values. //// // If that ever changes, the code has to be changed. //// //// // The calls to String.Compare should use the current culture for the string comparisons, but the //// // invariant culture when comparing against the english names. //// for(int i = 0; i < EraNames.Length; i++) //// { //// // Compare the era name in a case-insensitive way. //// if(m_eraNames[i].Length > 0) //// { //// if(String.Compare( eraName, m_eraNames[i], true, CultureInfo.CurrentCulture ) == 0) //// { //// return (i + 1); //// } //// } //// } //// for(int i = 0; i < AbbreviatedEraNames.Length; i++) //// { //// if(String.Compare( eraName, m_abbrevEraNames[i], true, CultureInfo.CurrentCulture ) == 0) //// { //// return (i + 1); //// } //// } //// for(int i = 0; i < AbbreviatedEnglishEraNames.Length; i++) //// { //// // this comparison should use the InvariantCulture. The English name could have linguistically //// // interesting characters. //// if(String.Compare( eraName, m_abbrevEnglishEraNames[i], true, CultureInfo.InvariantCulture ) == 0) //// { //// return (i + 1); //// } //// } //// return (-1); //// } //// //// internal String[] EraNames //// { //// get //// { //// if(m_eraNames == null) //// { //// if(Calendar.ID == Calendar.CAL_GREGORIAN) //// { //// // If the calendar is Gregorian localized calendar, //// // grab the localized name from culture.nlp. //// m_eraNames = new String[1] { //// this.m_cultureTableRecord.SADERA //// }; //// } //// else if(Calendar.ID != Calendar.CAL_TAIWAN) //// { //// // Use Calendar property so that we initialized the calendar when necessary. //// BCLDebug.Assert( Calendar.ID > 0, "[DateTimeFormatInfo.EraNames] Expected Calendar.ID > 0" ); //// m_eraNames = CalendarTable.Default.SERANAMES( Calendar.ID ); //// } //// else //// { //// // Special case for Taiwan calendar. //// // 0x0404 is the locale ID for Taiwan. //// m_eraNames = new String[] { CalendarTable.nativeGetEraName( 0x0404, Calendar.ID ) }; //// } //// } //// return (m_eraNames); //// } //// } //// //// /*=================================GetEraName========================== //// **Action: Get the name of the era for the specified era value. //// **Returns: The name of the specified era. //// **Arguments: //// ** era the era value. //// **Exceptions: //// ** ArguementException if the era valie is invalid. //// ============================================================================*/ //// //// //// public String GetEraName( int era ) //// { //// if(era == Calendar.CurrentEra) //// { //// era = Calendar.CurrentEraValue; //// } //// //// // The following is based on the assumption that the era value is starting from 1, and has a //// // serial values. //// // If that ever changes, the code has to be changed. //// if((--era) < EraNames.Length && (era >= 0)) //// { //// return (m_eraNames[era]); //// } //// throw new ArgumentOutOfRangeException( "era", Environment.GetResourceString( "ArgumentOutOfRange_InvalidEraValue" ) ); //// } //// //// internal String[] AbbreviatedEraNames //// { //// get //// { //// if(m_abbrevEraNames == null) //// { //// if(Calendar.ID == Calendar.CAL_TAIWAN) //// { //// String twnEra = GetEraName( 1 ); //// if(twnEra.Length > 0) //// { //// if(twnEra.Length == 4) //// { //// // Windows 2000 & above use 4-character era name. //// // Special case for Taiwan because of geo-political issue. //// m_abbrevEraNames = new String[] { twnEra.Substring( 2, 2 ) }; //// } //// else //// { //// // Windows 98/Windows ME use 2-character era name. //// m_abbrevEraNames = new String[] { twnEra }; //// } //// } //// else //// { //// // Return an etmpy string. //// m_abbrevEraNames = new String[0]; //// } //// } //// else //// { //// if(Calendar.ID == Calendar.CAL_GREGORIAN) //// { //// // If the calendar is Gregorian localized calendar, //// // grab the localized name from culture.nlp. //// m_abbrevEraNames = new String[1] { //// this.m_cultureTableRecord.SABBREVADERA //// }; //// } //// else //// { //// BCLDebug.Assert( Calendar.ID > 0, "[DateTimeFormatInfo.AbbreviatedEraNames] Expected Calendar.ID > 0" ); //// m_abbrevEraNames = CalendarTable.Default.SABBREVERANAMES( Calendar.ID ); //// } //// } //// } //// return (m_abbrevEraNames); //// } //// } //// //// //// public String GetAbbreviatedEraName( int era ) //// { //// if(AbbreviatedEraNames.Length == 0) //// { //// // If abbreviation era name is not used in this culture, //// // return the full era name. //// return (GetEraName( era )); //// } //// if(era == Calendar.CurrentEra) //// { //// era = Calendar.CurrentEraValue; //// } //// if((--era) < m_abbrevEraNames.Length && (era >= 0)) //// { //// return (m_abbrevEraNames[era]); //// } //// throw new ArgumentOutOfRangeException( "era", Environment.GetResourceString( "ArgumentOutOfRange_InvalidEraValue" ) ); //// } //// //// internal String[] AbbreviatedEnglishEraNames //// { //// get //// { //// if(m_abbrevEnglishEraNames == null) //// { //// BCLDebug.Assert( Calendar.ID > 0, "[DateTimeFormatInfo.AbbreviatedEnglishEraNames] Expected Calendar.ID > 0" ); //// m_abbrevEnglishEraNames = CalendarTable.Default.SABBREVENGERANAMES( Calendar.ID ); //// } //// return (m_abbrevEnglishEraNames); //// } //// } public String DateSeparator { get { return "/"; //// if(dateSeparator == null) //// { //// dateSeparator = this.m_cultureTableRecord.SDATE; //// } //// return (dateSeparator); } //// set //// { //// VerifyWritable(); //// if(value == null) //// { //// throw new ArgumentNullException( "value", //// Environment.GetResourceString( "ArgumentNull_String" ) ); //// } //// ClearTokenHashTable( true ); //// dateSeparator = value; //// } } //// public DayOfWeek FirstDayOfWeek //// { //// get //// { //// // FirstDayOfWeek is always set in the Calendar setter. //// return ((DayOfWeek)firstDayOfWeek); //// } //// //// set //// { //// VerifyWritable(); //// if(value >= DayOfWeek.Sunday && value <= DayOfWeek.Saturday) //// { //// firstDayOfWeek = (int)value; //// } //// else //// { //// throw new ArgumentOutOfRangeException( //// "value", String.Format( CultureInfo.CurrentCulture, Environment.GetResourceString( "ArgumentOutOfRange_Range" ), //// DayOfWeek.Sunday, DayOfWeek.Saturday ) ); //// } //// } //// } //// //// //// public CalendarWeekRule CalendarWeekRule //// { //// get //// { //// // CalendarWeekRule is always set in the Calendar setter. //// return ((CalendarWeekRule)this.calendarWeekRule); //// } //// //// set //// { //// VerifyWritable(); //// if(value >= CalendarWeekRule.FirstDay && value <= CalendarWeekRule.FirstFourDayWeek) //// { //// calendarWeekRule = (int)value; //// } //// else //// { //// throw new ArgumentOutOfRangeException( //// "value", String.Format( CultureInfo.CurrentCulture, Environment.GetResourceString( "ArgumentOutOfRange_Range" ), //// CalendarWeekRule.FirstDay, CalendarWeekRule.FirstFourDayWeek ) ); //// } //// } //// } public String FullDateTimePattern { get { //// if(fullDateTimePattern == null) //// { //// fullDateTimePattern = LongDatePattern + " " + LongTimePattern; //// } //// return (fullDateTimePattern); return LongDatePattern + " " + LongTimePattern; } //// set //// { //// VerifyWritable(); //// if(value == null) //// { //// throw new ArgumentNullException( "value", //// Environment.GetResourceString( "ArgumentNull_String" ) ); //// } //// fullDateTimePattern = value; //// } } //// private String GetLongDatePattern( int calID ) //// { //// String strTemp = String.Empty; //// if(!m_isDefaultCalendar) //// { //// // Has to be > 0 or the data'll be null //// BCLDebug.Assert( calID > 1, "[DateTimeFormatInfo.LongDatePattern] Expected calID > 1" ); //// strTemp = CalendarTable.Default.SLONGDATE( calID )[0]; //// //// BCLDebug.Assert( strTemp.Length != 0, "Calendar.nlp should have SLONGDATE value" ); //// } //// else //// { //// strTemp = this.m_cultureTableRecord.SLONGDATE; //// } //// return (strTemp); //// } public String LongDatePattern { get { return "dddd, dd MMMM yyyy"; //// BCLDebug.Assert( longDatePattern != null, "DateTimeFormatInfo.LongDatePattern, longDatePattern != null" ); //// return (longDatePattern); } //// set //// { //// VerifyWritable(); //// if(value == null) //// { //// throw new ArgumentNullException( "value", //// Environment.GetResourceString( "ArgumentNull_String" ) ); //// } //// ClearTokenHashTable( true ); //// //// SetDefaultPatternAsFirstItem( allLongDatePatterns, value ); //// longDatePattern = value; //// // Clean up cached values that will be affected by this property. //// fullDateTimePattern = null; //// } } public String LongTimePattern { get { return "HH:mm:ss"; //// // LongTimeProperty is always set in the Calendar setter. //// BCLDebug.Assert( longTimePattern != null, "DateTimeFormatInfo.LongTimePattern, longTimePattern != null" ); //// return (longTimePattern); } //// set //// { //// VerifyWritable(); //// if(value == null) //// { //// throw new ArgumentNullException( "value", //// Environment.GetResourceString( "ArgumentNull_String" ) ); //// } //// //// longTimePattern = value; //// // Clean up cached values that will be affected by this property. //// fullDateTimePattern = null; // Full date = long date + long Time //// generalLongTimePattern = null; // General long date = short date + long Time //// } } public String MonthDayPattern { get { return "MMMM dd"; //// if(monthDayPattern == null) //// { //// // strTemp avoids Empty (but not null) string problems in the else. //// // presumably Empty could be set. //// String strTemp; //// if(m_isDefaultCalendar) //// { //// strTemp = this.m_cultureTableRecord.SMONTHDAY; //// } //// else //// { //// BCLDebug.Assert( Calendar.ID > 0, "[DateTimeFormatInfo.GetStringFromTable] Expected Calendar.ID > 0" ); //// strTemp = CalendarTable.Default.SMONTHDAY( Calendar.ID ); //// // Note that for a tiny bit of time we're not null here, but we're also not necessarily non-empty //// if(strTemp.Length == 0) //// strTemp = this.m_cultureTableRecord.SMONTHDAY; //// } //// monthDayPattern = strTemp; //// } //// return (monthDayPattern); } //// set //// { //// VerifyWritable(); //// if(value == null) //// { //// throw new ArgumentNullException( "value", //// Environment.GetResourceString( "ArgumentNull_String" ) ); //// } //// monthDayPattern = value; //// } } public String PMDesignator { get { return "PM"; //// BCLDebug.Assert( pmDesignator != null, "DateTimeFormatInfo.PMDesignator, pmDesignator != null" ); //// return (pmDesignator); } //// set //// { //// VerifyWritable(); //// if(value == null) //// { //// throw new ArgumentNullException( "value", //// Environment.GetResourceString( "ArgumentNull_String" ) ); //// } //// ClearTokenHashTable( true ); //// pmDesignator = value; //// } } public String RFC1123Pattern { get { return (rfc1123Pattern); } } //// internal String GetShortDatePattern( int calID ) //// { //// String strTemp = String.Empty; //// if(!m_isDefaultCalendar) //// { //// // Has to be > 0 or the data'll be null //// BCLDebug.Assert( calID > 1, "[DateTimeFormatInfo.ShortDatePattern] Expected calID > 1" ); //// strTemp = CalendarTable.Default.SSHORTDATE( calID )[0]; //// //// BCLDebug.Assert( strTemp.Length != 0, "Calendar.nlp should have SHORTDATE value" ); //// } //// else //// { //// strTemp = this.m_cultureTableRecord.SSHORTDATE; //// } //// return (strTemp); //// } public String ShortDatePattern { get { return "MM/dd/yyyy"; //// BCLDebug.Assert( shortDatePattern != null, "DateTimeFormatInfo.ShortDatePattern, shortDatePattern != null" ); //// return (shortDatePattern); } //// set //// { //// VerifyWritable(); //// if(value == null) //// { //// throw new ArgumentNullException( "value", //// Environment.GetResourceString( "ArgumentNull_String" ) ); //// } //// //// SetDefaultPatternAsFirstItem( allShortDatePatterns, value ); //// shortDatePattern = value; //// // Clean up cached values that will be affected by this property. //// generalLongTimePattern = null; //// generalShortTimePattern = null; //// } } public String ShortTimePattern { get { return "HH:mm"; //// if(shortTimePattern == null) //// { //// shortTimePattern = this.m_cultureTableRecord.SSHORTTIME; //// } //// return (shortTimePattern); } //// set //// { //// VerifyWritable(); //// if(value == null) //// { //// throw new ArgumentNullException( "value", //// Environment.GetResourceString( "ArgumentNull_String" ) ); //// } //// shortTimePattern = value; //// // Clean up cached values that will be affected by this property. //// generalShortTimePattern = null; // General short date = short date + short time. //// } } public String SortableDateTimePattern { get { return (sortableDateTimePattern); } } /*=================================GeneralShortTimePattern===================== **Property: Return the pattern for 'g' general format: shortDate + short time **Note: This is used by DateTimeFormat.cs to get the pattern for 'g' ** We put this internal property here so that we can avoid doing the ** concatation every time somebody asks for the general format. ==============================================================================*/ internal String GeneralShortTimePattern { get { //// if(generalShortTimePattern == null) //// { //// generalShortTimePattern = ShortDatePattern + " " + ShortTimePattern; //// } //// return (generalShortTimePattern); return ShortDatePattern + " " + ShortTimePattern; } } /*=================================GeneralLongTimePattern===================== **Property: Return the pattern for 'g' general format: shortDate + Long time **Note: This is used by DateTimeFormat.cs to get the pattern for 'g' ** We put this internal property here so that we can avoid doing the ** concatation every time somebody asks for the general format. ==============================================================================*/ internal String GeneralLongTimePattern { get { //// if(generalLongTimePattern == null) //// { //// generalLongTimePattern = ShortDatePattern + " " + LongTimePattern; //// } //// return (generalLongTimePattern); return ShortDatePattern + " " + LongTimePattern; } } public String TimeSeparator { get { return ":"; //// if(timeSeparator == null) //// { //// timeSeparator = this.m_cultureTableRecord.STIME; //// } //// return (timeSeparator); } //// set //// { //// VerifyWritable(); //// if(value == null) //// { //// throw new ArgumentNullException( "value", //// Environment.GetResourceString( "ArgumentNull_String" ) ); //// } //// ClearTokenHashTable( true ); //// timeSeparator = value; //// } } public String UniversalSortableDateTimePattern { get { return (universalSortableDateTimePattern); } } //// private String GetYearMonthPattern( int calID ) //// { //// String result = null; //// if(!m_isDefaultCalendar) //// { //// // The calendar is the calendar not specified in culture.nlp. Use the calendar table. //// // Has to be > 0 or the data'll be null //// BCLDebug.Assert( calID > 1, "[DateTimeFormatInfo.YearMonthPattern] Expected calID > 1" ); //// result = CalendarTable.Default.SYEARMONTH( calID )[0]; //// //// BCLDebug.Assert( result.Length != 0, "Calendar.nlp should have SYEARMONTH value" ); //// } //// else //// { //// // The calendar is the calendar specified in culture.nlp. Use it. //// result = this.m_cultureTableRecord.SYEARMONTHS[0]; //// } //// return (result); //// //// } public String YearMonthPattern { get { //// BCLDebug.Assert( yearMonthPattern != null, "DateTimeFormatInfo.YearMonthPattern: yearMonthPattern != null" ); //// return (yearMonthPattern); return "yyyy MMMM"; } //// set //// { //// VerifyWritable(); //// if(value == null) //// { //// throw new ArgumentNullException( "value", //// Environment.GetResourceString( "ArgumentNull_String" ) ); //// } //// yearMonthPattern = value; //// SetDefaultPatternAsFirstItem( allYearMonthPatterns, yearMonthPattern ); //// } } //// // //// // Check if a string array contains a null value, and throw ArgumentNullException with parameter name "value" //// // //// private void CheckNullValue( String[] values, int length ) //// { //// BCLDebug.Assert( values != null, "value != null" ); //// for(int i = 0; i < length; i++) //// { //// if(values[i] == null) //// { //// throw new ArgumentNullException( "value", //// Environment.GetResourceString( "ArgumentNull_ArrayValue" ) ); //// } //// } //// } //// //// //// public String[] AbbreviatedDayNames //// { //// get //// { //// return ((String[])GetAbbreviatedDayOfWeekNames().Clone()); //// } //// //// set //// { //// VerifyWritable(); //// if(value == null) //// { //// throw new ArgumentNullException( "value", //// Environment.GetResourceString( "ArgumentNull_Array" ) ); //// } //// if(value.Length != 7) //// { //// throw new ArgumentException( String.Format( CultureInfo.CurrentCulture, Environment.GetResourceString( "Argument_InvalidArrayLength" ), 7 ), "value" ); //// } //// CheckNullValue( value, value.Length ); //// ClearTokenHashTable( true ); //// abbreviatedDayNames = value; //// } //// } //// //// //// // Returns the string array of the one-letter day of week names. //// public String[] ShortestDayNames //// { //// get //// { //// return ((String[])internalGetSuperShortDayNames().Clone()); //// } //// //// set //// { //// VerifyWritable(); //// if(value == null) //// { //// throw new ArgumentNullException( "value", //// Environment.GetResourceString( "ArgumentNull_Array" ) ); //// } //// if(value.Length != 7) //// { //// throw new ArgumentException( String.Format( CultureInfo.CurrentCulture, Environment.GetResourceString( "Argument_InvalidArrayLength" ), 7 ), "value" ); //// } //// CheckNullValue( value, value.Length ); //// this.m_superShortDayNames = value; //// } //// } //// //// //// public String[] DayNames //// { //// get //// { //// return ((String[])GetDayOfWeekNames().Clone()); //// } //// //// set //// { //// VerifyWritable(); //// if(value == null) //// { //// throw new ArgumentNullException( "value", //// Environment.GetResourceString( "ArgumentNull_Array" ) ); //// } //// if(value.Length != 7) //// { //// throw new ArgumentException( String.Format( CultureInfo.CurrentCulture, Environment.GetResourceString( "Argument_InvalidArrayLength" ), 7 ), "value" ); //// } //// CheckNullValue( value, value.Length ); //// ClearTokenHashTable( true ); //// dayNames = value; //// } //// } //// //// //// public String[] AbbreviatedMonthNames //// { //// get //// { //// return ((String[])GetAbbreviatedMonthNames().Clone()); //// } //// //// set //// { //// VerifyWritable(); //// if(value == null) //// { //// throw new ArgumentNullException( "value", //// Environment.GetResourceString( "ArgumentNull_Array" ) ); //// } //// if(value.Length != 13) //// { //// throw new ArgumentException( String.Format( CultureInfo.CurrentCulture, Environment.GetResourceString( "Argument_InvalidArrayLength" ), 13 ), "value" ); //// } //// CheckNullValue( value, value.Length - 1 ); //// ClearTokenHashTable( true ); //// abbreviatedMonthNames = value; //// } //// } public String[] MonthNames { get { return ((String[])GetMonthNames().Clone()); } //// set //// { //// VerifyWritable(); //// if(value == null) //// { //// throw new ArgumentNullException( "value", //// Environment.GetResourceString( "ArgumentNull_Array" ) ); //// } //// if(value.Length != 13) //// { //// throw new ArgumentException( String.Format( CultureInfo.CurrentCulture, Environment.GetResourceString( "Argument_InvalidArrayLength" ), 13 ), "value" ); //// } //// CheckNullValue( value, value.Length - 1 ); //// monthNames = value; //// ClearTokenHashTable( true ); //// } } //// // Whitespaces that we allow in the month names. //// // U+00a0 is non-breaking space. //// static char[] MonthSpaces = { ' ', '\u00a0' }; //// //// internal bool HasSpacesInMonthNames //// { //// get //// { //// return (FormatFlags & DateTimeFormatFlags.UseSpacesInMonthNames) != 0; //// } //// } //// //// internal bool HasSpacesInDayNames //// { //// get //// { //// return (FormatFlags & DateTimeFormatFlags.UseSpacesInDayNames) != 0; //// } //// } //// //// //// // //// // internalGetMonthName //// // //// // Actions: Return the month name using the specified MonthNameStyles in either abbreviated form //// // or full form. //// // Arguments: //// // month //// // style To indicate a form like regular/genitive/month name in a leap year. //// // abbreviated When true, return abbreviated form. Otherwise, return a full form. //// // Exceptions: //// // ArgumentOutOfRangeException When month name is invalid. //// // //// internal String internalGetMonthName( int month, MonthNameStyles style, bool abbreviated ) //// { //// // //// // Right now, style is mutual exclusive, but I make the style to be flag so that //// // maybe we can combine flag if there is such a need. //// // //// String[] monthNamesArray = null; //// switch(style) //// { //// case MonthNameStyles.Genitive: //// monthNamesArray = internalGetGenitiveMonthNames( abbreviated ); //// break; //// case MonthNameStyles.LeapYear: //// monthNamesArray = internalGetLeapYearMonthNames(/*abbreviated*/); //// break; //// default: //// monthNamesArray = (abbreviated ? GetAbbreviatedMonthNames() : GetMonthNames()); //// break; //// } //// // The month range is from 1 ~ this.m_monthNames.Length //// // (actually is 13 right now for all cases) //// if((month < 1) || (month > monthNamesArray.Length)) //// { //// throw new ArgumentOutOfRangeException( //// "month", String.Format( CultureInfo.CurrentCulture, Environment.GetResourceString( "ArgumentOutOfRange_Range" ), //// 1, monthNamesArray.Length ) ); //// } //// return (monthNamesArray[month - 1]); //// } //// //// // //// // internalGetGenitiveMonthNames //// // //// // Action: Retrieve the array which contains the month names in genitive form. //// // If this culture does not use the gentive form, the normal month name is returned. //// // Arguments: //// // abbreviated When true, return abbreviated form. Otherwise, return a full form. //// // //// private String[] internalGetGenitiveMonthNames( bool abbreviated ) //// { //// if(abbreviated) //// { //// if(this.m_genitiveAbbreviatedMonthNames == null) //// { //// if(m_isDefaultCalendar) //// { //// // Only Gregorian localized calendar can have genitive form. //// String[] temp = this.m_cultureTableRecord.SABBREVMONTHGENITIVENAMES; //// if(temp.Length > 0) //// { //// // Genitive form exists. //// this.m_genitiveAbbreviatedMonthNames = temp; //// } //// else //// { //// // Genitive form does not exist. Use the regular month names. //// this.m_genitiveAbbreviatedMonthNames = GetAbbreviatedMonthNames(); //// } //// } //// else //// { //// this.m_genitiveAbbreviatedMonthNames = GetAbbreviatedMonthNames(); //// } //// BCLDebug.Assert( this.m_genitiveAbbreviatedMonthNames.Length == 13, //// "[DateTimeFormatInfo.GetGenitiveMonthNames] Expected 13 abbreviated genitive month names in a year" ); //// } //// return (this.m_genitiveAbbreviatedMonthNames); //// } //// //// if(genitiveMonthNames == null) //// { //// if(m_isDefaultCalendar) //// { //// // Only Gregorian localized calendar can have genitive form. //// String[] temp = this.m_cultureTableRecord.SMONTHGENITIVENAMES; //// if(temp.Length > 0) //// { //// // Genitive form exists. //// genitiveMonthNames = temp; //// } //// else //// { //// // Genitive form does not exist. Use the regular month names. //// genitiveMonthNames = GetMonthNames(); //// } //// } //// else //// { //// genitiveMonthNames = GetMonthNames(); //// } //// BCLDebug.Assert( genitiveMonthNames.Length == 13, //// "[DateTimeFormatInfo.GetGenitiveMonthNames] Expected 13 genitive month names in a year" ); //// } //// return (genitiveMonthNames); //// } //// //// // //// // internalGetLeapYearMonthNames //// // //// // Actions: Retrieve the month names used in a leap year. //// // If this culture does not have different month names in a leap year, the normal month name is returned. //// // Agruments: None. (can use abbreviated later if needed) //// // //// internal String[] internalGetLeapYearMonthNames(/*bool abbreviated*/) //// { //// if(leapYearMonthNames == null) //// { //// if(m_isDefaultCalendar) //// { //// // //// // If this is a Gregorian localized calendar, there is no differences between the month names in a regular year //// // and those in a leap year. Just return the regular month names. //// // //// leapYearMonthNames = GetMonthNames(); //// } //// else //// { //// BCLDebug.Assert( Calendar.ID > 0, "[DateTimeFormatInfo.internalGetLeapYearMonthNames] Expected Calendar.ID > 0" ); //// String[] temp = CalendarTable.Default.SLEAPYEARMONTHNAMES( Calendar.ID ); //// if(temp.Length > 0) //// { //// leapYearMonthNames = temp; //// } //// else //// { //// leapYearMonthNames = GetMonthNames(); //// } //// } //// } //// return (leapYearMonthNames); //// } //// //// public String GetAbbreviatedDayName( DayOfWeek dayofweek ) { switch(dayofweek) { case DayOfWeek.Sunday : return "Sun"; case DayOfWeek.Monday : return "Mon"; case DayOfWeek.Tuesday : return "Tue"; case DayOfWeek.Wednesday: return "Wed"; case DayOfWeek.Thursday : return "Thu"; case DayOfWeek.Friday : return "Fri"; case DayOfWeek.Saturday : return "Sat"; } return String.Empty; } //// public String GetAbbreviatedDayName( DayOfWeek dayofweek ) //// { //// //// if((int)dayofweek < 0 || (int)dayofweek > 6) //// { //// throw new ArgumentOutOfRangeException( //// "dayofweek", String.Format( CultureInfo.CurrentCulture, Environment.GetResourceString( "ArgumentOutOfRange_Range" ), //// DayOfWeek.Sunday, DayOfWeek.Saturday ) ); //// } //// // //// // Don't call the public property AbbreviatedDayNames here since a clone is needed in that //// // property, so it will be slower. Instead, use GetAbbreviatedDayOfWeekNames() directly. //// // //// return (GetAbbreviatedDayOfWeekNames()[(int)dayofweek]); //// } //// //// // Returns the super short day of week names for the specified day of week. //// //// public String GetShortestDayName( DayOfWeek dayOfWeek ) //// { //// //// if((int)dayOfWeek < 0 || (int)dayOfWeek > 6) //// { //// throw new ArgumentOutOfRangeException( //// "dayOfWeek", String.Format( CultureInfo.CurrentCulture, Environment.GetResourceString( "ArgumentOutOfRange_Range" ), //// DayOfWeek.Sunday, DayOfWeek.Saturday ) ); //// } //// // //// // Don't call the public property SuperShortDayNames here since a clone is needed in that //// // property, so it will be slower. Instead, use internalGetSuperShortDayNames() directly. //// // //// return (internalGetSuperShortDayNames()[(int)dayOfWeek]); //// } //// //// //// internal String[] GetCombinedPatterns( String[] patterns1, String[] patterns2, String connectString ) //// { //// String[] result = new String[patterns1.Length * patterns2.Length]; //// for(int i = 0; i < patterns1.Length; i++) //// { //// for(int j = 0; j < patterns2.Length; j++) //// { //// result[i * patterns2.Length + j] = patterns1[i] + connectString + patterns2[j]; //// } //// } //// return (result); //// } //// //// //// public String[] GetAllDateTimePatterns() //// { //// ArrayList results = new ArrayList( DEFAULT_ALL_DATETIMES_SIZE ); //// //// for(int i = 0; i < DateTimeFormat.allStandardFormats.Length; i++) //// { //// String[] strings = GetAllDateTimePatterns( DateTimeFormat.allStandardFormats[i] ); //// for(int j = 0; j < strings.Length; j++) //// { //// results.Add( strings[j] ); //// } //// } //// String[] value = new String[results.Count]; //// results.CopyTo( 0, value, 0, results.Count ); //// return (value); //// } //// //// //// public String[] GetAllDateTimePatterns( char format ) //// { //// String[] result = null; //// //// switch(format) //// { //// case 'd': //// result = ClonedAllShortDatePatterns; //// break; //// case 'D': //// result = ClonedAllLongDatePatterns; //// break; //// case 'f': //// result = GetCombinedPatterns( ClonedAllLongDatePatterns, ClonedAllShortTimePatterns, " " ); //// break; //// case 'F': //// result = GetCombinedPatterns( ClonedAllLongDatePatterns, ClonedAllLongTimePatterns, " " ); //// break; //// case 'g': //// result = GetCombinedPatterns( ClonedAllShortDatePatterns, ClonedAllShortTimePatterns, " " ); //// break; //// case 'G': //// result = GetCombinedPatterns( ClonedAllShortDatePatterns, ClonedAllLongTimePatterns, " " ); //// break; //// case 'm': //// case 'M': //// result = new String[] { MonthDayPattern }; //// break; //// case 'o': //// case 'O': //// result = new String[] { DateTimeFormat.RoundtripFormat }; //// break; //// case 'r': //// case 'R': //// result = new String[] { rfc1123Pattern }; //// break; //// case 's': //// result = new String[] { sortableDateTimePattern }; //// break; //// case 't': //// result = ClonedAllShortTimePatterns; //// break; //// case 'T': //// result = ClonedAllLongTimePatterns; //// break; //// case 'u': //// result = new String[] { UniversalSortableDateTimePattern }; //// break; //// case 'U': //// result = GetCombinedPatterns( ClonedAllLongDatePatterns, ClonedAllLongTimePatterns, " " ); //// break; //// case 'y': //// case 'Y': //// result = ClonedAllYearMonthPatterns; //// break; //// default: //// throw new ArgumentException( Environment.GetResourceString( "Argument_BadFormatSpecifier" ), "format" ); //// } //// return (result); //// } public String GetDayName( DayOfWeek dayofweek ) { switch(dayofweek) { case DayOfWeek.Sunday : return "Sunday"; case DayOfWeek.Monday : return "Monday"; case DayOfWeek.Tuesday : return "Tuesday"; case DayOfWeek.Wednesday: return "Wednesday"; case DayOfWeek.Thursday : return "Thursday"; case DayOfWeek.Friday : return "Friday"; case DayOfWeek.Saturday : return "Saturday"; } return String.Empty; } //// public String GetDayName( DayOfWeek dayofweek ) //// { //// if((int)dayofweek < 0 || (int)dayofweek > 6) //// { //// throw new ArgumentOutOfRangeException( //// "dayofweek", String.Format( CultureInfo.CurrentCulture, Environment.GetResourceString( "ArgumentOutOfRange_Range" ), //// DayOfWeek.Sunday, DayOfWeek.Saturday ) ); //// } //// //// return (GetDayOfWeekNames()[(int)dayofweek]); //// } public String GetAbbreviatedMonthName( int month ) { if(month < 1 || month > 13) { #if EXCEPTION_STRINGS throw new ArgumentOutOfRangeException( "month", String.Format( CultureInfo.CurrentCulture, Environment.GetResourceString( "ArgumentOutOfRange_Range" ), 1, 13 ) ); #else throw new ArgumentOutOfRangeException(); #endif } return (GetAbbreviatedMonthNames()[month - 1]); } public String GetMonthName( int month ) { if(month < 1 || month > 13) { #if EXCEPTION_STRINGS throw new ArgumentOutOfRangeException( "month", String.Format( CultureInfo.CurrentCulture, Environment.GetResourceString( "ArgumentOutOfRange_Range" ), 1, 13 ) ); #else throw new ArgumentOutOfRangeException(); #endif } return (GetMonthNames()[month - 1]); } //// internal String[] ClonedAllYearMonthPatterns //// { //// get //// { //// if(allYearMonthPatterns == null) //// { //// String[] temp = null; //// //// if(!m_isDefaultCalendar) //// { //// BCLDebug.Assert( Calendar.ID > 0, "[DateTimeFormatInfo.AllYearMonthPatternsNeedClone] Expected Calendar.ID > 0" ); //// //// temp = CalendarTable.Default.SYEARMONTH( Calendar.ID ); //// //// // In the data table, some calendars store null for long date pattern. //// // This means that we have to use the default format of the user culture for that calendar. //// // So, get the pattern from culture. //// if(temp == null) //// { //// temp = this.m_cultureTableRecord.SYEARMONTHS; //// } //// } //// else //// { //// temp = this.m_cultureTableRecord.SYEARMONTHS; //// } //// //// System.Threading.Thread.MemoryBarrier(); //// SetDefaultPatternAsFirstItem( temp, YearMonthPattern ); //// allYearMonthPatterns = temp; //// } //// //// if(allYearMonthPatterns[0].Equals( YearMonthPattern )) //// { //// return (String[])allYearMonthPatterns.Clone(); //// } //// //// return AddDefaultFormat( allYearMonthPatterns, YearMonthPattern ); //// } //// } //// //// //// // NOTE: Clone this string array if you want to return it to user. Otherwise, you are returnning a writable cache copy. //// internal String[] ClonedAllShortDatePatterns //// { //// get //// { //// if(allShortDatePatterns == null) //// { //// String[] temp = null; //// if(!m_isDefaultCalendar) //// { //// BCLDebug.Assert( Calendar.ID > 0, "[DateTimeFormatInfo.AllShortDatePatternsNeedClone] Expected Calendar.ID > 0" ); //// temp = CalendarTable.Default.SSHORTDATE( Calendar.ID ); //// // In the data table, some calendars store null for long date pattern. //// // This means that we have to use the default format of the user culture for that calendar. //// // So, get the pattern from culture. //// if(temp == null) //// { //// temp = this.m_cultureTableRecord.SSHORTDATES; //// } //// } //// else //// { //// temp = this.m_cultureTableRecord.SSHORTDATES; //// } //// System.Threading.Thread.MemoryBarrier(); //// SetDefaultPatternAsFirstItem( temp, ShortDatePattern ); //// allShortDatePatterns = temp; //// } //// //// if(allShortDatePatterns[0].Equals( ShortDatePattern )) //// { //// return (String[])allShortDatePatterns.Clone(); //// } //// //// return (AddDefaultFormat( allShortDatePatterns, ShortDatePattern )); //// } //// } //// //// // NOTE: Clone this string array if you want to return it to user. Otherwise, you are returnning a writable cache copy. //// internal String[] ClonedAllLongDatePatterns //// { //// get //// { //// if(allLongDatePatterns == null) //// { //// String[] temp = null; //// if(!m_isDefaultCalendar) //// { //// BCLDebug.Assert( Calendar.ID > 0, "[DateTimeFormatInfo.AllLongDatePatternsNeedClone] Expected Calendar.ID > 0" ); //// temp = CalendarTable.Default.SLONGDATE( Calendar.ID ); //// // In the data table, some calendars store null for long date pattern. //// // This means that we have to use the default format of the user culture for that calendar. //// // So, get the pattern from culture. //// if(temp == null) //// { //// temp = this.m_cultureTableRecord.SLONGDATES; //// } //// } //// else //// { //// temp = this.m_cultureTableRecord.SLONGDATES; //// } //// System.Threading.Thread.MemoryBarrier(); //// SetDefaultPatternAsFirstItem( temp, LongDatePattern ); //// allLongDatePatterns = temp; //// } //// //// if(allLongDatePatterns[0].Equals( LongDatePattern )) //// { //// return (String[])allLongDatePatterns.Clone(); //// } //// //// return (AddDefaultFormat( allLongDatePatterns, LongDatePattern )); //// } //// } //// //// internal void SetDefaultPatternAsFirstItem( string[] patterns, string defaultPattern ) //// { //// if(patterns == null) { return; } //// //// for(int i = 0; i < patterns.Length; i++) //// { //// if(patterns[i].Equals( defaultPattern )) //// { //// if(i != 0) //// { //// // default date is already exist in the list. set it as first item in the list. //// string temp = patterns[i]; //// //// for(int j = i; j > 0; j--) //// { //// patterns[j] = patterns[j - 1]; //// } //// //// patterns[0] = temp; //// } //// //// return; //// } //// } //// } //// //// //////////////////////////////////////////////////////////////////////// //// // //// // The default LongDatePattern is not in the standard list. Add it as the first item. //// // //// //////////////////////////////////////////////////////////////////////// //// //// internal string[] AddDefaultFormat( string[] datePatterns, string defaultDateFormat ) //// { //// string[] updatedPatterns = new string[datePatterns.Length + 1]; //// updatedPatterns[0] = defaultDateFormat; //// Array.Copy( datePatterns, 0, updatedPatterns, 1, datePatterns.Length ); //// // We need to scan the non-standard longDatePattern. //// m_scanDateWords = true; //// return updatedPatterns; //// } //// //// // NOTE: Clone this string array if you want to return it to user. Otherwise, you are returnning a writable cache copy. //// internal String[] ClonedAllShortTimePatterns //// { //// get //// { //// if(allShortTimePatterns == null) //// { //// allShortTimePatterns = this.m_cultureTableRecord.SSHORTTIMES; //// SetDefaultPatternAsFirstItem( allShortTimePatterns, ShortTimePattern ); //// } //// //// if(allShortTimePatterns[0].Equals( ShortTimePattern )) //// { //// return (String[])allShortTimePatterns.Clone(); //// } //// //// return (AddDefaultFormat( allShortTimePatterns, ShortTimePattern )); //// } //// } //// //// internal String[] ClonedAllLongTimePatterns //// { //// get //// { //// if(allLongTimePatterns == null) //// { //// allLongTimePatterns = this.m_cultureTableRecord.STIMEFORMATS; //// SetDefaultPatternAsFirstItem( allLongTimePatterns, LongTimePattern ); //// } //// if(allLongTimePatterns[0].Equals( LongTimePattern )) //// { //// return (String[])allLongTimePatterns.Clone(); //// } //// //// return (AddDefaultFormat( allLongTimePatterns, LongTimePattern )); //// } //// } //// //// // //// // The known word used in date pattern for this culture. E.g. Spanish cultures often //// // have 'de' in their long date pattern. //// // This is used by DateTime.Parse() to decide if a word should be ignored or not. //// // //// internal String[] DateWords //// { //// get //// { //// if(m_dateWords == null) //// { //// m_dateWords = this.m_cultureTableRecord.SDATEWORDS; //// } //// //// return (m_dateWords); //// } //// } //// //// //// public static DateTimeFormatInfo ReadOnly( DateTimeFormatInfo dtfi ) //// { //// if(dtfi == null) //// { //// throw new ArgumentNullException( "dtfi", //// Environment.GetResourceString( "ArgumentNull_Obj" ) ); //// } //// if(dtfi.IsReadOnly) //// { //// return (dtfi); //// } //// DateTimeFormatInfo info = (DateTimeFormatInfo)(dtfi.MemberwiseClone()); //// info.Calendar = Calendar.ReadOnly( info.Calendar ); //// info.m_isReadOnly = true; //// return (info); //// } //// //// //// public bool IsReadOnly //// { //// get //// { //// return (m_isReadOnly); //// } //// } //// //// private static int CalendarIdToCultureId( int calendarId ) //// { //// switch(calendarId) //// { //// case Calendar.CAL_GREGORIAN_US: //// return 0x0429; // "fa-IR" Iran //// //// case Calendar.CAL_JAPAN: //// return 0x0411; // "ja-JP" Japan //// //// case Calendar.CAL_TAIWAN: //// return 0x0404; // zh-TW Taiwan //// //// case Calendar.CAL_KOREA: //// return 0x0412; // "ko-KR" Korea //// //// case Calendar.CAL_HIJRI: //// case Calendar.CAL_GREGORIAN_ARABIC: //// case Calendar.CAL_UMALQURA: //// return 0x0401; // "ar-SA" Saudi Arabia //// //// case Calendar.CAL_THAI: //// return 0x041e; // "th-TH" Thailand //// //// case Calendar.CAL_HEBREW: //// return 0x040d; // "he-IL" Israel //// //// case Calendar.CAL_GREGORIAN_ME_FRENCH: //// return 0x1401; // "ar-DZ" Algeria //// //// case Calendar.CAL_GREGORIAN_XLIT_ENGLISH: //// case Calendar.CAL_GREGORIAN_XLIT_FRENCH: //// return 0x0801; // "ar-IQ"; Iraq //// //// default: //// BCLDebug.Assert( false, //// "[DateTimeFormatInfo.CalendarIdToCultureId] we shouldn't come here." ); //// break; //// } //// //// return 0; //// } //// //// // //// // GetCalendarNativeNameFallback is used when we got empty string native calendar name from the culture data //// // in the case of the custom cultures. //// // GetCalendarNativeNameFallback is getting the name from the framework data from some specific cultures //// // for example to get the native name for Hijri calendar we use ar-SA culture to get that name. //// // //// private string GetCalendarNativeNameFallback( int calendarId ) //// { //// BCLDebug.Assert( calendarId != Calendar.CAL_GREGORIAN, //// "[DateTimeFormatInfo.GetCalendarNativeNameFallback] Unexpected Gregorian localized calendar." ); //// //// if(m_calendarNativeNames == null) //// { //// lock(InternalSyncObject) //// { //// if(m_calendarNativeNames == null) //// m_calendarNativeNames = new Hashtable(); //// } //// } //// //// BCLDebug.Assert( m_calendarNativeNames != null, //// "[DateTimeFormatInfo.GetCalendarNativeNameFallback] m_calendarNativeNames should be valid" ); //// //// string temp = (string)m_calendarNativeNames[calendarId]; //// if(temp != null) //// return temp; //// //// string name = String.Empty; //// //// int cultureId = CalendarIdToCultureId( calendarId ); //// //// if(cultureId != 0) //// { //// String[] values = new CultureTableRecord( cultureId, false ).SNATIVECALNAMES; //// //// BCLDebug.Assert( calendar.ID >= 1, "[DateTimeFormatInfo.GetCalendarNativeNameFallback] calendar.ID >= 1" ); //// //// int id = calendar.ID - 1; //// //// // The element 0 stored the name for calendar ID 1 (since there is no calendar ID 0) //// if(id < values.Length) //// { //// // If U+FEFF is stored, it means that no information for that calendar is available. //// if(values[id].Length > 0 && values[id][0] != '\xfeff') //// name = values[id]; //// } //// } //// //// lock(InternalSyncObject) //// { //// if(m_calendarNativeNames[calendarId] == null) //// m_calendarNativeNames[calendarId] = name; //// } //// //// return name; //// } //// //// // Return the native name for the calendar in DTFI.Calendar. The native name is referred to //// // the culture used to create the DTFI. E.g. in the following example, the native language is Japanese. //// // DateTimeFormatInfo dtfi = new CutlureInfo("ja-JP", false).DateTimeFormat.Calendar = new JapaneseCalendar(); //// // String nativeName = dtfi.NativeCalendarName; // Get the Japanese name for the Japanese calendar. //// // DateTimeFormatInfo dtfi = new CutlureInfo("ja-JP", false).DateTimeFormat.Calendar = new GregorianCalendar(GregorianCalendarTypes.Localized); //// // String nativeName = dtfi.NativeCalendarName; // Get the Japanese name for the Gregorian calendar. //// //// //// public String NativeCalendarName //// { //// get //// { //// //// if(Calendar.ID == Calendar.CAL_TAIWAN) //// { //// // //// // Specail case for Taiwan calenadr. //// // //// //// // In non-Taiwan machine, the following call will return null. //// // 0x0404 is the locale ID for Taiwan. //// String result = GetCalendarInfo( 0x0404, Calendar.CAL_TAIWAN, CAL_SCALNAME ); //// if(result == null) //// { //// // 0x0404 is the locale ID for Taiwan. //// // In Win9x, the Win32 GetCalendarInfo() does not support CAL_SCALNAME. In that case, //// // fallback to use the era name. //// result = CalendarTable.nativeGetEraName( 0x0404, Calendar.CAL_TAIWAN ); //// if(result == null) //// { //// // In non-CHT platform, the previous two Win32 calls will fail. Just return an empty string. //// result = String.Empty; //// } //// } //// return (result); //// } //// else //// { //// String[] values = this.m_cultureTableRecord.SNATIVECALNAMES; //// BCLDebug.Assert( calendar.ID >= 1, "calendar.ID >= 1" ); //// int id = calendar.ID - 1; //// // The element 0 stored the name for calendar ID 1 (since there is no calendar ID 0) //// if(id < values.Length) //// { //// if(values[id].Length > 0) //// { //// // If U+FEFF is stored, it means that no information for that calendar is available. //// if(values[id][0] != '\xfeff') //// return (values[id]); //// } //// else //// { //// // //// // Empty string means we have custom culture. Then try the fallback. //// // //// BCLDebug.Assert( this.m_cultureTableRecord.IsCustomCulture, "[DateTimeFormatInfo.NativeCalendarName] Expected custom culture" ); //// return GetCalendarNativeNameFallback( calendar.ID ); //// } //// } //// } //// // If data is not available, just return an empty string. //// return (String.Empty); //// } //// } //// //// // //// // Used by custom cultures and others to set the list of available formats. Note that none of them are //// // explicitly used unless someone calls GetAllDateTimePatterns and subsequently uses one of the items //// // from the list. //// // //// // Most of the format characters that can be used in GetAllDateTimePatterns are //// // not really needed since they are one of the following: //// // //// // r/R/s/u locale-independent constants -- cannot be changed! //// // m/M/y/Y fields with a single string in them -- that can be set through props directly //// // f/F/g/G/U derived fields based on combinations of various of the below formats //// // //// // NOTE: No special validation is done here beyond what is done when the actual respective fields //// // are used (what would be the point of disallowing here what we allow in the appropriate property?) //// // //// // WARNING: If more validation is ever done in one place, it should be done in the other. //// // //// //// public void SetAllDateTimePatterns( String[] patterns, char format ) //// { //// VerifyWritable(); //// if(patterns == null) //// { //// throw new ArgumentNullException( "patterns", //// Environment.GetResourceString( "ArgumentNull_Array" ) ); //// } //// //// if(patterns.Length == 0) //// { //// throw new ArgumentException( Environment.GetResourceString( "Arg_ArrayZeroError" ), "patterns" ); //// } //// //// for(int i = 0; i < patterns.Length; i++) //// { //// if(patterns[i] == null) //// { //// throw new ArgumentNullException( Environment.GetResourceString( "ArgumentNull_ArrayValue" ) ); //// } //// } //// //// switch(format) //// { //// case 'd': //// ShortDatePattern = patterns[0]; //// this.allShortDatePatterns = patterns; //// break; //// //// case 'D': //// LongDatePattern = patterns[0]; //// this.allLongDatePatterns = patterns; //// break; //// //// case 't': //// ShortTimePattern = patterns[0]; //// this.allShortTimePatterns = patterns; //// break; //// //// case 'T': //// LongTimePattern = patterns[0]; //// this.allLongTimePatterns = patterns; //// break; //// //// case 'y': //// case 'Y': //// yearMonthPattern = patterns[0]; //// this.allYearMonthPatterns = patterns; //// break; //// //// default: //// throw new ArgumentException( Environment.GetResourceString( "Argument_BadFormatSpecifier" ), "format" ); //// } //// return; //// } //// //// public String[] AbbreviatedMonthGenitiveNames //// { //// get //// { //// return ((String[])internalGetGenitiveMonthNames( true ).Clone()); //// } //// //// set //// { //// VerifyWritable(); //// if(value == null) //// { //// throw new ArgumentNullException( "value", //// Environment.GetResourceString( "ArgumentNull_Array" ) ); //// } //// if(value.Length != 13) //// { //// throw new ArgumentException( String.Format( CultureInfo.CurrentCulture, Environment.GetResourceString( "Argument_InvalidArrayLength" ), 13 ), "value" ); //// } //// CheckNullValue( value, value.Length - 1 ); //// ClearTokenHashTable( true ); //// this.m_genitiveAbbreviatedMonthNames = value; //// } //// } //// //// public String[] MonthGenitiveNames //// { //// get //// { //// return ((String[])internalGetGenitiveMonthNames( false ).Clone()); //// } //// //// set //// { //// VerifyWritable(); //// if(value == null) //// { //// throw new ArgumentNullException( "value", //// Environment.GetResourceString( "ArgumentNull_Array" ) ); //// } //// if(value.Length != 13) //// { //// throw new ArgumentException( String.Format( CultureInfo.CurrentCulture, Environment.GetResourceString( "Argument_InvalidArrayLength" ), 13 ), "value" ); //// } //// CheckNullValue( value, value.Length - 1 ); //// genitiveMonthNames = value; //// ClearTokenHashTable( true ); //// } //// } //// //// //// // //// // Get suitable CompareInfo from current DTFI object. //// // //// //// internal CompareInfo CompareInfo //// { //// get //// { //// if(m_compareInfo == null) //// { //// // We use the regular GetCompareInfo here to make sure the created CompareInfo object is stored in the //// // CompareInfo cache. otherwise we would just create CompareInfo using m_cultureTableRecord. //// if(CultureTableRecord.IsCustomCultureId( CultureId )) //// m_compareInfo = CompareInfo.GetCompareInfo( (int)m_cultureTableRecord.ICOMPAREINFO ); //// else //// m_compareInfo = CompareInfo.GetCompareInfo( CultureId ); //// } //// //// return m_compareInfo; //// } //// } //// //// //// private void VerifyWritable() //// { //// if(m_isReadOnly) //// { //// throw new InvalidOperationException( Environment.GetResourceString( "InvalidOperation_ReadOnly" ) ); //// } //// } //// //// //private const DateTimeStyles InvalidDateTimeStyles = unchecked((DateTimeStyles)0xFFFFFF00); //// private const DateTimeStyles InvalidDateTimeStyles = ~(DateTimeStyles.AllowLeadingWhite | DateTimeStyles.AllowTrailingWhite //// | DateTimeStyles.AllowInnerWhite | DateTimeStyles.NoCurrentDateDefault //// | DateTimeStyles.AdjustToUniversal | DateTimeStyles.AssumeLocal //// | DateTimeStyles.AssumeUniversal | DateTimeStyles.RoundtripKind); [MethodImplAttribute( MethodImplOptions.InternalCall )] internal static extern void ValidateStyles( DateTimeStyles style , String parameterName ); //// { //// if((style & InvalidDateTimeStyles) != 0) //// { //// throw new ArgumentException( Environment.GetResourceString( "Argument_InvalidDateTimeStyles" ), parameterName ); //// } //// if(((style & (DateTimeStyles.AssumeLocal)) != 0) && ((style & (DateTimeStyles.AssumeUniversal)) != 0)) //// { //// throw new ArgumentException( Environment.GetResourceString( "Argument_ConflictingDateTimeStyles" ), parameterName ); //// } //// if(((style & DateTimeStyles.RoundtripKind) != 0) //// && ((style & (DateTimeStyles.AssumeLocal | DateTimeStyles.AssumeUniversal | DateTimeStyles.AdjustToUniversal)) != 0)) //// { //// throw new ArgumentException( Environment.GetResourceString( "Argument_ConflictingDateTimeRoundtripStyles" ), parameterName ); //// } //// } //// //// // //// // Actions: Return the internal flag used in formatting and parsing. //// // The flag can be used to indicate things like if genitive forms is used in this DTFi, or if leap year gets different month names. //// // //// internal DateTimeFormatFlags FormatFlags //// { //// get //// { //// if(formatFlags == DateTimeFormatFlags.NotInitialized) //// { //// if(m_scanDateWords || m_cultureTableRecord.IsSynthetic) //// { //// formatFlags = DateTimeFormatFlags.None; //// formatFlags |= (DateTimeFormatFlags)DateTimeFormatInfoScanner.GetFormatFlagGenitiveMonth( MonthNames, internalGetGenitiveMonthNames( false ), AbbreviatedMonthNames, internalGetGenitiveMonthNames( true ) ); //// formatFlags |= (DateTimeFormatFlags)DateTimeFormatInfoScanner.GetFormatFlagUseSpaceInMonthNames( MonthNames, internalGetGenitiveMonthNames( false ), AbbreviatedMonthNames, internalGetGenitiveMonthNames( true ) ); //// formatFlags |= (DateTimeFormatFlags)DateTimeFormatInfoScanner.GetFormatFlagUseSpaceInDayNames( DayNames, AbbreviatedDayNames ); //// formatFlags |= (DateTimeFormatFlags)DateTimeFormatInfoScanner.GetFormatFlagUseHebrewCalendar( (int)Calendar.ID ); //// } //// else //// { //// // No customized format, we can use the pre-calculated formatflags. //// if(m_isDefaultCalendar) //// { //// formatFlags = this.m_cultureTableRecord.IFORMATFLAGS; //// } //// else //// { //// BCLDebug.Assert( Calendar.ID > 0, "[DateTimeFormatInfo.FormatFlags] Expected Calendar.ID > 0" ); //// formatFlags = (DateTimeFormatFlags)CalendarTable.Default.IFORMATFLAGS( Calendar.ID ); //// } //// } //// } //// return (formatFlags); //// } //// } //// //// internal Boolean HasForceTwoDigitYears //// { //// get //// { //// switch(calendar.ID) //// { //// // Add a special case for Japanese and Taiwan. //// // If is y/yy, do not get (year % 100). "y" will print //// // year without leading zero. "yy" will print year with two-digit in leading zero. //// // If pattern is yyy/yyyy/..., print year value with two-digit in leading zero. //// // So year 5 is "05", and year 125 is "125". //// // The reason for not doing (year % 100) is for Taiwan calendar. //// // If year 125, then output 125 and not 25. //// // Note: OS uses "yyyy" for Taiwan calendar by default. //// case (Calendar.CAL_JAPAN): //// case (Calendar.CAL_TAIWAN): //// return true; //// } //// return false; //// } //// } //// //// // Returns whether the YearMonthAdjustment function has any fix-up work to do for this culture/calendar. //// internal Boolean HasYearMonthAdjustment //// { //// get //// { //// return ((FormatFlags & DateTimeFormatFlags.UseHebrewRule) != 0); //// } //// } //// //// // This is a callback that the parser can make back into the DTFI to let it fiddle with special //// // cases associated with that culture or calendar. Currently this only has special cases for //// // the Hebrew calendar, but this could be extended to other cultures. //// // //// // The return value is whether the year and month are actually valid for this calendar. //// internal Boolean YearMonthAdjustment( ref int year, ref int month, Boolean parsedMonthName ) //// { //// if((FormatFlags & DateTimeFormatFlags.UseHebrewRule) != 0) //// { //// //// // Special rules to fix up the Hebrew year/month //// //// // When formatting, we only format up to the hundred digit of the Hebrew year, although Hebrew year is now over 5000. //// // E.g. if the year is 5763, we only format as 763. //// if(year < 1000) //// { //// year += 5000; //// } //// //// // Because we need to calculate leap year, we should fall out now for an invalid year. //// if(year < Calendar.GetYear( Calendar.MinSupportedDateTime ) || year > Calendar.GetYear( Calendar.MaxSupportedDateTime )) //// { //// return false; //// } //// //// // To handle leap months, the set of month names in the symbol table does not always correspond to the numbers. //// // For non-leap years, month 7 (Adar Bet) is not present, so we need to make using this month invalid and //// // shuffle the other months down. //// if(parsedMonthName) //// { //// if(!Calendar.IsLeapYear( year )) //// { //// if(month >= 8) //// { //// month--; //// } //// else if(month == 7) //// { //// return false; //// } //// } //// } //// } //// return true; //// } //// //// // //// // DateTimeFormatInfo tokenizer. This is used by DateTime.Parse() to break input string into tokens. //// // //// [NonSerialized] //// TokenHashValue[] m_dtfiTokenHash; //// // The flag to indicate if we need to re-generate date words & formatflags. //// [NonSerialized] //// bool m_scanDateWords = false; //// //// //// private const int TOKEN_HASH_SIZE = 199; //// private const int SECOND_PRIME = 197; //// private const String alternativeDateSeparator = "-"; //// private const String invariantDateSeparator = "/"; //// private const String invariantTimeSeparator = ":"; //// //// // //// // Year/Month/Day suffixes //// // //// internal const String CJKYearSuff = "\u5e74"; //// internal const String CJKMonthSuff = "\u6708"; //// internal const String CJKDaySuff = "\u65e5"; //// //// internal const String KoreanYearSuff = "\ub144"; //// internal const String KoreanMonthSuff = "\uc6d4"; //// internal const String KoreanDaySuff = "\uc77c"; //// //// internal const String KoreanHourSuff = "\uc2dc"; //// internal const String KoreanMinuteSuff = "\ubd84"; //// internal const String KoreanSecondSuff = "\ucd08"; //// //// internal const String CJKHourSuff = "\u6642"; //// internal const String ChineseHourSuff = "\u65f6"; //// //// internal const String CJKMinuteSuff = "\u5206"; //// internal const String CJKSecondSuff = "\u79d2"; //// //// internal const String LocalTimeMark = "T"; //// //// internal const String KoreanLangName = "ko"; //// internal const String JapaneseLangName = "ja"; //// internal const String EnglishLangName = "en"; //// //// private static DateTimeFormatInfo m_jajpDTFI = null; //// private static DateTimeFormatInfo m_zhtwDTFI = null; //// //// // //// // Create a Japanese DTFI which uses JapaneseCalendar. This is used to parse //// // date string with Japanese era name correctly even when the supplied DTFI //// // does not use Japanese calendar. //// // The created instance is stored in global m_jajpDTFI. //// // //// internal static DateTimeFormatInfo GetJapaneseCalendarDTFI() //// { //// DateTimeFormatInfo temp = m_jajpDTFI; //// if(temp == null) //// { //// temp = new CultureInfo( "ja-JP", false ).DateTimeFormat; //// temp.Calendar = JapaneseCalendar.GetDefaultInstance(); //// m_jajpDTFI = temp; //// } //// return (temp); //// } //// //// //// // //// // Create a Taiwan DTFI which uses TaiwanCalendar. This is used to parse //// // date string with era name correctly even when the supplied DTFI //// // does not use Taiwan calendar. //// // The created instance is stored in global m_zhtwDTFI. //// // //// internal static DateTimeFormatInfo GetTaiwanCalendarDTFI() //// { //// DateTimeFormatInfo temp = m_zhtwDTFI; //// if(temp == null) //// { //// temp = new CultureInfo( "zh-TW", false ).DateTimeFormat; //// temp.Calendar = TaiwanCalendar.GetDefaultInstance(); //// m_zhtwDTFI = temp; //// } //// return (temp); //// } //// //// //// // DTFI properties should call this when the setter are called. //// private void ClearTokenHashTable( bool scanDateWords ) //// { //// m_dtfiTokenHash = null; //// m_dateWords = null; //// // The properties in this class have been changed, and we need to re-generate //// // date words & format flags, instead of using the table values. //// m_scanDateWords = scanDateWords; //// formatFlags = DateTimeFormatFlags.NotInitialized; //// } //// //// internal TokenHashValue[] CreateTokenHashTable() //// { //// TokenHashValue[] temp = m_dtfiTokenHash; //// if(temp == null) //// { //// temp = new TokenHashValue[TOKEN_HASH_SIZE]; //// //// InsertHash( temp, ",", TokenType.IgnorableSymbol, 0 ); //// InsertHash( temp, ".", TokenType.IgnorableSymbol, 0 ); //// //// InsertHash( temp, this.TimeSeparator, TokenType.SEP_Time, 0 ); //// InsertHash( temp, this.AMDesignator, TokenType.SEP_Am | TokenType.Am, 0 ); //// InsertHash( temp, this.PMDesignator, TokenType.SEP_Pm | TokenType.Pm, 1 ); //// //// if(CultureName.Equals( "sq-AL" )) //// { //// // Algerian allows time formats like "12:00.PD" //// InsertHash( temp, "." + this.AMDesignator, TokenType.SEP_Am | TokenType.Am, 0 ); //// InsertHash( temp, "." + this.PMDesignator, TokenType.SEP_Pm | TokenType.Pm, 1 ); //// } //// //// // CJK suffix //// InsertHash( temp, CJKYearSuff, TokenType.SEP_YearSuff, 0 ); //// InsertHash( temp, KoreanYearSuff, TokenType.SEP_YearSuff, 0 ); //// InsertHash( temp, CJKMonthSuff, TokenType.SEP_MonthSuff, 0 ); //// InsertHash( temp, KoreanMonthSuff, TokenType.SEP_MonthSuff, 0 ); //// InsertHash( temp, CJKDaySuff, TokenType.SEP_DaySuff, 0 ); //// InsertHash( temp, KoreanDaySuff, TokenType.SEP_DaySuff, 0 ); //// //// InsertHash( temp, CJKHourSuff, TokenType.SEP_HourSuff, 0 ); //// InsertHash( temp, ChineseHourSuff, TokenType.SEP_HourSuff, 0 ); //// InsertHash( temp, CJKMinuteSuff, TokenType.SEP_MinuteSuff, 0 ); //// InsertHash( temp, CJKSecondSuff, TokenType.SEP_SecondSuff, 0 ); //// //// if(LanguageName.Equals( KoreanLangName )) //// { //// // Korean suffix //// InsertHash( temp, KoreanHourSuff, TokenType.SEP_HourSuff, 0 ); //// InsertHash( temp, KoreanMinuteSuff, TokenType.SEP_MinuteSuff, 0 ); //// InsertHash( temp, KoreanSecondSuff, TokenType.SEP_SecondSuff, 0 ); //// } //// //// String[] dateWords = null; //// DateTimeFormatInfoScanner scanner = null; //// //// // Get the all of the long date pattern. The getter will check if the default LongDatePattern //// // is in the standard list or not. If not, m_scanDateWords will be true, and we will //// // need to scan the date words. //// // Note that dateWords is used as a temp buffer here. It will be reset as the real date words later. //// if(!m_scanDateWords) //// { //// dateWords = ClonedAllLongDatePatterns; //// } //// if(m_scanDateWords || m_cultureTableRecord.IsSynthetic) //// { //// scanner = new DateTimeFormatInfoScanner(); //// // Enumarate all LongDatePatterns, and get the DateWords and scan for month postfix. //// m_dateWords = dateWords = scanner.GetDateWordsOfDTFI( this ); //// // Ensure the formatflags is initialized. //// DateTimeFormatFlags flag = FormatFlags; //// m_scanDateWords = false; //// } //// else //// { //// // Use the table value. //// dateWords = this.DateWords; ; //// } //// //// // For some cultures, the date separator works more like a comma, being allowed before or after any date part. //// // In this cultures, we do not use normal date separator since we disallow date separator after a date terminal state. //// // This is determinted in DateTimeFormatInfoScanner. Use this flag to determine if we should treat date separator as ignorable symbol. //// bool useDateSepAsIgnorableSymbol = false; //// //// String monthPostfix = null; //// if(dateWords != null) //// { //// // There are DateWords. It could be a real date word (such as "de"), or a monthPostfix. //// // The monthPostfix starts with '\xfffe' (MonthPostfixChar), followed by the real monthPostfix. //// for(int i = 0; i < dateWords.Length; i++) //// { //// switch(dateWords[i][0]) //// { //// // This is a month postfix //// case DateTimeFormatInfoScanner.MonthPostfixChar: //// // Get the real month postfix. //// monthPostfix = dateWords[i].Substring( 1 ); //// // Add the month name + postfix into the token. //// AddMonthNames( temp, monthPostfix ); //// break; //// case DateTimeFormatInfoScanner.IgnorableSymbolChar: //// String symbol = dateWords[i].Substring( 1 ); //// InsertHash( temp, symbol, TokenType.IgnorableSymbol, 0 ); //// if(this.DateSeparator.Trim( null ).Equals( symbol )) //// { //// // The date separator is the same as the ingorable symbol. //// useDateSepAsIgnorableSymbol = true; //// } //// break; //// default: //// InsertHash( temp, dateWords[i], TokenType.DateWordToken, 0 ); //// if(CultureName.Equals( "eu-ES" )) //// { //// // Basque has date words with leading dots //// InsertHash( temp, "." + dateWords[i], TokenType.DateWordToken, 0 ); //// } //// break; //// } //// } //// } //// //// if(!useDateSepAsIgnorableSymbol) //// { //// // Use the normal date separator. //// InsertHash( temp, this.DateSeparator, TokenType.SEP_Date, 0 ); //// } //// // Add the regular month names. //// AddMonthNames( temp, null ); //// //// // Add the abbreviated month names. //// for(int i = 1; i <= 13; i++) //// { //// InsertHash( temp, GetAbbreviatedMonthName( i ), TokenType.MonthToken, i ); //// } //// //// //// if(CultureName.Equals( "gl-ES" )) //// { //// // //// // Special case for gl-ES. It has a potential incorrect format in year/month: MMMM'de 'yyyy. //// // It probably has to be MMMM' de 'yyyy. //// // //// //// // We keep this so that we can still parse dates formatted in the older version. //// for(int i = 1; i <= 13; i++) //// { //// String str; //// //str = internalGetMonthName(i, MonthNameStyles.Regular, false); //// // We have to call public methods here to work with inherited DTFI. //// // Insert the month name first, so that they are at the front of abbrevaited //// // month names. //// str = GetMonthName( i ); //// if(str.Length > 0) //// { //// // Insert the month name with the postfix first, so it can be matched first. //// InsertHash( temp, str + "de", TokenType.MonthToken, i ); //// } //// } //// } //// //// if((FormatFlags & DateTimeFormatFlags.UseGenitiveMonth) != 0) //// { //// for(int i = 1; i <= 13; i++) //// { //// String str; //// str = internalGetMonthName( i, MonthNameStyles.Genitive, false ); //// InsertHash( temp, str, TokenType.MonthToken, i ); //// } //// } //// //// if((FormatFlags & DateTimeFormatFlags.UseLeapYearMonth) != 0) //// { //// for(int i = 1; i <= 13; i++) //// { //// String str; //// str = internalGetMonthName( i, MonthNameStyles.LeapYear, false ); //// InsertHash( temp, str, TokenType.MonthToken, i ); //// } //// } //// //// for(int i = 0; i < 7; i++) //// { //// //String str = GetDayOfWeekNames()[i]; //// // We have to call public methods here to work with inherited DTFI. //// String str = GetDayName( (DayOfWeek)i ); //// InsertHash( temp, str, TokenType.DayOfWeekToken, i ); //// //// str = GetAbbreviatedDayName( (DayOfWeek)i ); //// InsertHash( temp, str, TokenType.DayOfWeekToken, i ); //// //// } //// //// int[] eras = calendar.Eras; //// for(int i = 1; i <= eras.Length; i++) //// { //// InsertHash( temp, GetEraName( i ), TokenType.EraToken, i ); //// InsertHash( temp, GetAbbreviatedEraName( i ), TokenType.EraToken, i ); //// } //// //// if(LanguageName.Equals( JapaneseLangName )) //// { //// // Japanese allows day of week forms like: "(Tue)" //// for(int i = 0; i < 7; i++) //// { //// String specialDayOfWeek = "(" + GetAbbreviatedDayName( (DayOfWeek)i ) + ")"; //// InsertHash( temp, specialDayOfWeek, TokenType.DayOfWeekToken, i ); //// } //// if(this.Calendar.GetType() != typeof( JapaneseCalendar )) //// { //// // Special case for Japanese. If this is a Japanese DTFI, and the calendar is not Japanese calendar, //// // we will check Japanese Era name as well when the calendar is Gregorian. //// DateTimeFormatInfo jaDtfi = GetJapaneseCalendarDTFI(); //// for(int i = 1; i <= jaDtfi.Calendar.Eras.Length; i++) //// { //// InsertHash( temp, jaDtfi.GetEraName( i ), TokenType.JapaneseEraToken, i ); //// InsertHash( temp, jaDtfi.GetAbbreviatedEraName( i ), TokenType.JapaneseEraToken, i ); //// // m_abbrevEnglishEraNames[0] contains the name for era 1, so the token value is i+1. //// InsertHash( temp, jaDtfi.AbbreviatedEnglishEraNames[i - 1], TokenType.JapaneseEraToken, i ); //// } //// } //// } //// else if(CultureName.Equals( "zh-TW" )) //// { //// DateTimeFormatInfo twDtfi = GetTaiwanCalendarDTFI(); //// for(int i = 1; i <= twDtfi.Calendar.Eras.Length; i++) //// { //// if(twDtfi.GetEraName( i ).Length > 0) //// { //// InsertHash( temp, twDtfi.GetEraName( i ), TokenType.TEraToken, i ); //// } //// } //// } //// //// InsertHash( temp, InvariantInfo.AMDesignator, TokenType.SEP_Am | TokenType.Am, 0 ); //// InsertHash( temp, InvariantInfo.PMDesignator, TokenType.SEP_Pm | TokenType.Pm, 1 ); //// //// // Add invariant month names and day names. //// for(int i = 1; i <= 12; i++) //// { //// String str; //// // We have to call public methods here to work with inherited DTFI. //// // Insert the month name first, so that they are at the front of abbrevaited //// // month names. //// str = InvariantInfo.GetMonthName( i ); //// InsertHash( temp, str, TokenType.MonthToken, i ); //// str = InvariantInfo.GetAbbreviatedMonthName( i ); //// InsertHash( temp, str, TokenType.MonthToken, i ); //// } //// //// for(int i = 0; i < 7; i++) //// { //// // We have to call public methods here to work with inherited DTFI. //// String str = InvariantInfo.GetDayName( (DayOfWeek)i ); //// InsertHash( temp, str, TokenType.DayOfWeekToken, i ); //// //// str = InvariantInfo.GetAbbreviatedDayName( (DayOfWeek)i ); //// InsertHash( temp, str, TokenType.DayOfWeekToken, i ); //// //// } //// //// for(int i = 0; i < AbbreviatedEnglishEraNames.Length; i++) //// { //// // m_abbrevEnglishEraNames[0] contains the name for era 1, so the token value is i+1. //// InsertHash( temp, AbbreviatedEnglishEraNames[i], TokenType.EraToken, i + 1 ); //// } //// //// InsertHash( temp, LocalTimeMark, TokenType.SEP_LocalTimeMark, 0 ); //// InsertHash( temp, DateTimeParse.GMTName, TokenType.TimeZoneToken, 0 ); //// InsertHash( temp, DateTimeParse.ZuluName, TokenType.TimeZoneToken, 0 ); //// //// InsertHash( temp, invariantDateSeparator, TokenType.SEP_Date, 0 ); //// InsertHash( temp, invariantTimeSeparator, TokenType.SEP_Time, 0 ); //// //// if(CultureName.Equals( "ky-KG" )) //// { //// // For some cultures, the date separator works more like a comma, being allowed before or after any date part //// InsertHash( temp, alternativeDateSeparator, TokenType.IgnorableSymbol, 0 ); //// } //// else //// { //// InsertHash( temp, alternativeDateSeparator, TokenType.SEP_Date, 0 ); //// } //// //// m_dtfiTokenHash = temp; //// } //// return (temp); //// } //// //// private void AddMonthNames( TokenHashValue[] temp, String monthPostfix ) //// { //// for(int i = 1; i <= 13; i++) //// { //// String str; //// //str = internalGetMonthName(i, MonthNameStyles.Regular, false); //// // We have to call public methods here to work with inherited DTFI. //// // Insert the month name first, so that they are at the front of abbrevaited //// // month names. //// str = GetMonthName( i ); //// if(str.Length > 0) //// { //// if(monthPostfix != null) //// { //// // Insert the month name with the postfix first, so it can be matched first. //// InsertHash( temp, str + monthPostfix, TokenType.MonthToken, i ); //// } //// else //// { //// InsertHash( temp, str, TokenType.MonthToken, i ); //// } //// } //// str = GetAbbreviatedMonthName( i ); //// InsertHash( temp, str, TokenType.MonthToken, i ); //// } //// //// } //// //// //////////////////////////////////////////////////////////////////////// //// // //// // Actions: //// // Try to parse the current word to see if it is a Hebrew number. //// // Tokens will be updated accordingly. //// // This is called by the Lexer of DateTime.Parse(). //// // //// // Unlike most of the functions in this class, the return value indicates //// // whether or not it started to parse. The badFormat parameter indicates //// // if parsing began, but the format was bad. //// // //// //////////////////////////////////////////////////////////////////////// //// //// private static bool TryParseHebrewNumber( //// ref __DTString str, //// out Boolean badFormat, //// out int number ) //// { //// //// number = -1; //// badFormat = false; //// //// int i = str.Index; //// if(!HebrewNumber.IsDigit( str.Value[i] )) //// { //// // If the current character is not a Hebrew digit, just return false. //// // There is no chance that we can parse a valid Hebrew number from here. //// return (false); //// } //// // The current character is a Hebrew digit. Try to parse this word as a Hebrew number. //// HebrewNumberParsingContext context = new HebrewNumberParsingContext( 0 ); //// HebrewNumberParsingState state; //// //// do //// { //// state = HebrewNumber.ParseByChar( str.Value[i++], ref context ); //// switch(state) //// { //// case HebrewNumberParsingState.InvalidHebrewNumber: // Not a valid Hebrew number. //// case HebrewNumberParsingState.NotHebrewDigit: // The current character is not a Hebrew digit character. //// // Break out so that we don't continue to try parse this as a Hebrew number. //// return (false); //// } //// } while(i < str.Value.Length && (state != HebrewNumberParsingState.FoundEndOfHebrewNumber)); //// //// // When we are here, we are either at the end of the string, or we find a valid Hebrew number. //// BCLDebug.Assert( state == HebrewNumberParsingState.ContinueParsing || state == HebrewNumberParsingState.FoundEndOfHebrewNumber, //// "Invalid returned state from HebrewNumber.ParseByChar()" ); //// //// if(state != HebrewNumberParsingState.FoundEndOfHebrewNumber) //// { //// // We reach end of the string but we can't find a terminal state in parsing Hebrew number. //// return (false); //// } //// //// // We have found a valid Hebrew number. Update the index. //// str.Advance( i - str.Index ); //// //// // Get the final Hebrew number value from the HebrewNumberParsingContext. //// number = context.result; //// //// return (true); //// } //// //// private static bool IsHebrewChar( char ch ) //// { //// return (ch >= '\x0590' && ch <= '\x05ff'); //// } //// //// internal bool Tokenize( TokenType TokenMask, out TokenType tokenType, out int tokenValue, ref __DTString str ) //// { //// tokenType = TokenType.UnknownToken; //// tokenValue = 0; //// //// TokenHashValue value; //// BCLDebug.Assert( str.Index < str.Value.Length, "DateTimeFormatInfo.Tokenize(): start < value.Length" ); //// //// char ch = str.m_current; //// bool isLetter = Char.IsLetter( ch ); //// if(isLetter) //// { //// ch = Char.ToLower( ch, CultureInfo.CurrentCulture ); //// if(IsHebrewChar( ch ) && TokenMask == TokenType.RegularTokenMask) //// { //// bool badFormat; //// if(TryParseHebrewNumber( ref str, out badFormat, out tokenValue )) //// { //// if(badFormat) //// { //// tokenType = TokenType.UnknownToken; //// return (false); //// } //// // This is a Hebrew number. //// // Do nothing here. TryParseHebrewNumber() will update token accordingly. //// tokenType = TokenType.HebrewNumber; //// return (true); //// } //// } //// } //// //// //// int hashcode = ch % TOKEN_HASH_SIZE; //// int hashProbe = 1 + ch % SECOND_PRIME; //// int remaining = str.len - str.Index; //// int i = 0; //// //// TokenHashValue[] hashTable = m_dtfiTokenHash; //// if(hashTable == null) //// { //// hashTable = CreateTokenHashTable(); //// } //// do //// { //// value = hashTable[hashcode]; //// if(value == null) //// { //// // Not found. //// break; //// } //// // Check this value has the right category (regular token or separator token) that we are looking for. //// if(((int)value.tokenType & (int)TokenMask) > 0 && value.tokenString.Length <= remaining) //// { //// if(String.Compare( str.Value, str.Index, value.tokenString, 0, value.tokenString.Length, true, CultureInfo.CurrentCulture ) == 0) //// { //// if(isLetter) //// { //// // If this token starts with a letter, make sure that we won't allow partial match. So you can't tokenize "MarchWed" separately. //// int nextCharIndex; //// if((nextCharIndex = str.Index + value.tokenString.Length) < str.len) //// { //// // Check word boundary. The next character should NOT be a letter. //// char nextCh = str.Value[nextCharIndex]; //// if(Char.IsLetter( nextCh )) //// { //// return (false); //// } //// } //// } //// tokenType = value.tokenType & TokenMask; //// tokenValue = value.tokenValue; //// str.Advance( value.tokenString.Length ); //// return (true); //// } //// else if(value.tokenType == TokenType.MonthToken && HasSpacesInMonthNames) //// { //// // For month token, we will match the month names which have spaces. //// int matchStrLen = 0; //// if(str.MatchSpecifiedWords( value.tokenString, true, ref matchStrLen )) //// { //// tokenType = value.tokenType & TokenMask; //// tokenValue = value.tokenValue; //// str.Advance( matchStrLen ); //// return (true); //// } //// } //// else if(value.tokenType == TokenType.DayOfWeekToken && HasSpacesInDayNames) //// { //// // For month token, we will match the month names which have spaces. //// int matchStrLen = 0; //// if(str.MatchSpecifiedWords( value.tokenString, true, ref matchStrLen )) //// { //// tokenType = value.tokenType & TokenMask; //// tokenValue = value.tokenValue; //// str.Advance( matchStrLen ); //// return (true); //// } //// } //// } //// i++; //// hashcode += hashProbe; //// if(hashcode >= TOKEN_HASH_SIZE) hashcode -= TOKEN_HASH_SIZE; //// } while(i < TOKEN_HASH_SIZE); //// //// return (false); //// } //// //// void InsertAtCurrentHashNode( TokenHashValue[] hashTable, String str, char ch, TokenType tokenType, int tokenValue, int pos, int hashcode, int hashProbe ) //// { //// // Remember the current slot. //// TokenHashValue previousNode = hashTable[hashcode]; //// //// //// Console.WriteLine(" Insert Key: {0} in {1}", str, slotToInsert); //// // Insert the new node into the current slot. //// hashTable[hashcode] = new TokenHashValue( str, tokenType, tokenValue ); ; //// //// while(++pos < TOKEN_HASH_SIZE) //// { //// hashcode += hashProbe; //// if(hashcode >= TOKEN_HASH_SIZE) hashcode -= TOKEN_HASH_SIZE; //// // Remember this slot //// TokenHashValue temp = hashTable[hashcode]; //// //// if(temp != null && Char.ToLower( temp.tokenString[0], CultureInfo.CurrentCulture ) != ch) //// { //// continue; //// } //// // Put the previous slot into this slot. //// hashTable[hashcode] = previousNode; //// //// Console.WriteLine(" Move {0} to slot {1}", previousNode.tokenString, hashcode); //// if(temp == null) //// { //// // Done //// return; //// } //// previousNode = temp; //// }; //// BCLDebug.Assert( true, "The hashtable is full. This should not happen." ); //// } //// //// void InsertHash( TokenHashValue[] hashTable, String str, TokenType tokenType, int tokenValue ) //// { //// // The month of the 13th month is allowed to be null, so make sure that we ignore null value here. //// if(str == null || str.Length == 0) //// { //// return; //// } //// TokenHashValue value; //// int i = 0; //// // If there is whitespace characters in the beginning and end of the string, trim them since whitespaces are skipped by //// // DateTime.Parse(). //// if(Char.IsWhiteSpace( str[0] ) || Char.IsWhiteSpace( str[str.Length - 1] )) //// { //// str = str.Trim( null ); // Trim white space characters. //// // Could have space for separators //// if(str.Length == 0) //// return; //// } //// char ch = Char.ToLower( str[0], CultureInfo.CurrentCulture ); //// int hashcode = ch % TOKEN_HASH_SIZE; //// int hashProbe = 1 + ch % SECOND_PRIME; //// do //// { //// value = hashTable[hashcode]; //// if(value == null) //// { //// //// Console.WriteLine(" Put Key: {0} in {1}", str, hashcode); //// hashTable[hashcode] = new TokenHashValue( str, tokenType, tokenValue ); //// return; //// } //// else //// { //// // Collision happens. Find another slot. //// if(str.Length >= value.tokenString.Length) //// { //// // If there are two tokens with the same prefix, we have to make sure that the longer token should be at the front of //// // the shorter ones. //// if(String.Compare( str, 0, value.tokenString, 0, value.tokenString.Length, true, CultureInfo.CurrentCulture ) == 0) //// { //// if(str.Length > value.tokenString.Length) //// { //// // The str to be inserted has the same prefix as the current token, and str is longer. //// // Insert str into this node, and shift every node behind it. //// InsertAtCurrentHashNode( hashTable, str, ch, tokenType, tokenValue, i, hashcode, hashProbe ); //// return; //// } //// else //// { //// // Same token. If they have different types (regular token vs separator token. Add them. //// if(((int)tokenType & 0xff00) != ((int)value.tokenType & 0xff00)) //// { //// value.tokenType |= tokenType; //// if(tokenValue != 0) //// { //// value.tokenValue = tokenValue; //// } //// } //// // The token to be inserted is already in the table. Skip it. //// } //// } //// } //// } //// //// Console.WriteLine(" COLLISION. Old Key: {0}, New Key: {1}", hashTable[hashcode].tokenString, str); //// i++; //// hashcode += hashProbe; //// if(hashcode >= TOKEN_HASH_SIZE) hashcode -= TOKEN_HASH_SIZE; //// } while(i < TOKEN_HASH_SIZE); //// BCLDebug.Assert( true, "The hashtable is full. This should not happen." ); //// } //// //// internal static string GetCalendarInfo( int culture, int calendar, int calType ) //// { //// int size = Microsoft.Win32.Win32Native.GetCalendarInfo( culture, calendar, calType, null, 0, IntPtr.Zero ); //// if(size > 0) //// { //// StringBuilder buffer = new StringBuilder( size ); //// size = Microsoft.Win32.Win32Native.GetCalendarInfo( culture, calendar, calType, buffer, size, IntPtr.Zero ); //// if(size > 0) //// return buffer.ToString( 0, size - 1 ); // Exclude the null termination. //// } //// return null; //// } //// //// // Win32 Constants for calling GetCalendarInfo(). //// internal const int CAL_SCALNAME = 0x00000002; // native name of calendar } // class DateTimeFormatInfo ////internal class TokenHashValue ////{ //// internal String tokenString; //// internal TokenType tokenType; //// internal int tokenValue; //// //// internal TokenHashValue( String tokenString, TokenType tokenType, int tokenValue ) //// { //// this.tokenString = tokenString; //// this.tokenType = tokenType; //// this.tokenValue = tokenValue; //// } ////} } ================================================ FILE: Zelig/Zelig/RunTime/Framework/mscorlib/System/Globalization/DateTimeParse.cs ================================================ // ==++== // // Copyright (c) Microsoft Corporation. All rights reserved. // // ==--== //////////////////////////////////////////////////////////////////////////// // // Class: DateTimeParse // // Purpose: This class is called by DateTime to parse a date/time string. // //////////////////////////////////////////////////////////////////////////// namespace System { using System; using System.Text; using System.Globalization; using System.Threading; using System.Collections; using System.Runtime.CompilerServices; //////////////////////////////////////////////////////////////////////// /* There are some nasty cases in the parsing of date/time: 0x438 fo (country:Faroe Islands, language:Faroese) LOCALE_STIME=[.] LOCALE_STIMEFOR=[HH.mm.ss] LOCALE_SDATE=[-] LOCALE_SSHORTDATE=[dd-MM-yyyy] LOCALE_SLONGDATE=[d. MMMM yyyy] The time separator is ".", However, it also has a "." in the long date format. 0x437: (country:Georgia, language:Georgian) Short date: dd.MM.yy Long date: yyyy ???? dd MM, dddd The order in long date is YDM, which is different from the common ones: YMD/MDY/DMY. 0x0404: (country:Taiwan, language:Chinese) LOCALE_STIMEFORMAT=[tt hh:mm:ss] When general date is used, the pattern is "yyyy/M/d tt hh:mm:ss". Note that the "tt" is after "yyyy/M/d". And this is different from most cultures. 0x0437: (country:Georgia, language:Georgian) Short date: dd.MM.yy Long date: yyyy ???? dd MM, dddd 0x0456: */ //This class contains only static members internal static class DateTimeParse { //// //// internal const Int32 MaxDateTimeNumberDigits = 8; //// //// internal delegate bool MatchNumberDelegate( ref __DTString str, int digitLen, out int result ); //// //// internal static MatchNumberDelegate m_hebrewNumberParser = new MatchNumberDelegate( DateTimeParse.MatchHebrewDigits ); [MethodImplAttribute( MethodImplOptions.InternalCall )] internal static extern DateTime ParseExact( String s , String format , DateTimeFormatInfo dtfi , DateTimeStyles style ); //// { //// DateTimeResult result = new DateTimeResult(); // The buffer to store the parsing result. //// result.Init(); //// if(TryParseExact( s, format, dtfi, style, ref result )) //// { //// return result.parsedDate; //// } //// else //// { //// throw GetDateTimeParseException( ref result ); //// } //// } //// //// internal static bool TryParseExact( String s, String format, DateTimeFormatInfo dtfi, DateTimeStyles style, out DateTime result ) //// { //// result = DateTime.MinValue; //// DateTimeResult resultData = new DateTimeResult(); // The buffer to store the parsing result. //// resultData.Init(); //// if(TryParseExact( s, format, dtfi, style, ref resultData )) //// { //// result = resultData.parsedDate; //// return true; //// } //// return false; //// } //// //// internal static bool TryParseExact( String s, String format, DateTimeFormatInfo dtfi, DateTimeStyles style, ref DateTimeResult result ) //// { //// if(s == null) //// { //// result.SetFailure( ParseFailureKind.ArgumentNull, "ArgumentNull_String", null, "s" ); //// return false; //// } //// if(format == null) //// { //// result.SetFailure( ParseFailureKind.ArgumentNull, "ArgumentNull_String", null, "format" ); //// return false; //// } //// if(s.Length == 0) //// { //// result.SetFailure( ParseFailureKind.Format, "Format_BadDateTime", null ); //// return false; //// } //// //// if(format.Length == 0) //// { //// result.SetFailure( ParseFailureKind.Format, "Argument_BadFormatSpecifier", null ); //// return false; //// } //// //// BCLDebug.Assert( dtfi != null, "dtfi == null" ); //// //// return DoStrictParse( s, format, style, dtfi, ref result ); //// } [MethodImplAttribute( MethodImplOptions.InternalCall )] internal static extern DateTime ParseExactMultiple( String s , String[] formats , DateTimeFormatInfo dtfi , DateTimeStyles style ); //// { //// DateTimeResult result = new DateTimeResult(); // The buffer to store the parsing result. //// result.Init(); //// if(TryParseExactMultiple( s, formats, dtfi, style, ref result )) //// { //// return result.parsedDate; //// } //// else //// { //// throw GetDateTimeParseException( ref result ); //// } //// } //// //// internal static bool TryParseExactMultiple( String s, String[] formats, //// DateTimeFormatInfo dtfi, DateTimeStyles style, out DateTime result ) //// { //// result = DateTime.MinValue; //// DateTimeResult resultData = new DateTimeResult(); // The buffer to store the parsing result. //// resultData.Init(); //// if(TryParseExactMultiple( s, formats, dtfi, style, ref resultData )) //// { //// result = resultData.parsedDate; //// return true; //// } //// return false; //// } //// //// internal static bool TryParseExactMultiple( String s, String[] formats, //// DateTimeFormatInfo dtfi, DateTimeStyles style, ref DateTimeResult result ) //// { //// if(s == null) //// { //// result.SetFailure( ParseFailureKind.ArgumentNull, "ArgumentNull_String", null, "s" ); //// return false; //// } //// if(formats == null) //// { //// result.SetFailure( ParseFailureKind.ArgumentNull, "ArgumentNull_String", null, "formats" ); //// return false; //// } //// //// if(s.Length == 0) //// { //// result.SetFailure( ParseFailureKind.Format, "Format_BadDateTime", null ); //// return false; //// } //// //// if(formats.Length == 0) //// { //// result.SetFailure( ParseFailureKind.Format, "Argument_BadFormatSpecifier", null ); //// return false; //// } //// //// BCLDebug.Assert( dtfi != null, "dtfi == null" ); //// //// // //// // Do a loop through the provided formats and see if we can parse succesfully in //// // one of the formats. //// // //// for(int i = 0; i < formats.Length; i++) //// { //// if(formats[i] == null || formats[i].Length == 0) //// { //// result.SetFailure( ParseFailureKind.Format, "Argument_BadFormatSpecifier", null ); //// return false; //// } //// if(TryParseExact( s, formats[i], dtfi, style, out result.parsedDate )) //// { //// return (true); //// } //// } //// result.SetFailure( ParseFailureKind.Format, "Format_BadDateTime", null ); //// return (false); //// } //// //// //////////////////////////////////////////////////////////////////////////// //// // Date Token Types //// // //// // Following is the set of tokens that can be generated from a date //// // string. Notice that the legal set of trailing separators have been //// // folded in with the date number, and month name tokens. This set //// // of tokens is chosen to reduce the number of date parse states. //// // //// //////////////////////////////////////////////////////////////////////////// //// //// internal enum DTT : int //// { //// //// End = 0, // '\0' //// NumEnd = 1, // Num[ ]*[\0] //// NumAmpm = 2, // Num[ ]+AmPm //// NumSpace = 3, // Num[ ]+^[Dsep|Tsep|'0\'] //// NumDatesep = 4, // Num[ ]*Dsep //// NumTimesep = 5, // Num[ ]*Tsep //// MonthEnd = 6, // Month[ ]*'\0' //// MonthSpace = 7, // Month[ ]+^[Dsep|Tsep|'\0'] //// MonthDatesep = 8, // Month[ ]*Dsep //// NumDatesuff = 9, // Month[ ]*DSuff //// NumTimesuff = 10, // Month[ ]*TSuff //// DayOfWeek = 11, // Day of week name //// YearSpace = 12, // Year+^[Dsep|Tsep|'0\'] //// YearDateSep = 13, // Year+Dsep //// YearEnd = 14, // Year+['\0'] //// TimeZone = 15, // timezone name //// Era = 16, // era name //// NumUTCTimeMark = 17, // Num + 'Z' //// // When you add a new token which will be in the //// // state table, add it after NumLocalTimeMark. //// Unk = 18, // unknown //// NumLocalTimeMark = 19, // Num + 'T' //// Max = 20, // marker //// } //// //// internal enum TM //// { //// NotSet = -1, //// AM = 0, //// PM = 1, //// } //// //// //// //////////////////////////////////////////////////////////////////////////// //// // //// // DateTime parsing state enumeration (DS.*) //// // //// //////////////////////////////////////////////////////////////////////////// //// //// internal enum DS //// { //// BEGIN = 0, //// N = 1, // have one number //// NN = 2, // have two numbers //// //// // The following are known to be part of a date //// //// D_Nd = 3, // date string: have number followed by date separator //// D_NN = 4, // date string: have two numbers //// D_NNd = 5, // date string: have two numbers followed by date separator //// //// D_M = 6, // date string: have a month //// D_MN = 7, // date string: have a month and a number //// D_NM = 8, // date string: have a number and a month //// D_MNd = 9, // date string: have a month and number followed by date separator //// D_NDS = 10, // date string: have one number followed a date suffix. //// //// D_Y = 11, // date string: have a year. //// D_YN = 12, // date string: have a year and a number //// D_YNd = 13, // date string: have a year and a number and a date separator //// D_YM = 14, // date string: have a year and a month //// D_YMd = 15, // date string: have a year and a month and a date separator //// D_S = 16, // have numbers followed by a date suffix. //// T_S = 17, // have numbers followed by a time suffix. //// //// // The following are known to be part of a time //// //// T_Nt = 18, // have num followed by time separator //// T_NNt = 19, // have two numbers followed by time separator //// //// //// ERROR = 20, //// //// // The following are terminal states. These all have an action //// // associated with them; and transition back to BEGIN. //// //// DX_NN = 21, // day from two numbers //// DX_NNN = 22, // day from three numbers //// DX_MN = 23, // day from month and one number //// DX_NM = 24, // day from month and one number //// DX_MNN = 25, // day from month and two numbers //// DX_DS = 26, // a set of date suffixed numbers. //// DX_DSN = 27, // day from date suffixes and one number. //// DX_NDS = 28, // day from one number and date suffixes . //// DX_NNDS = 29, // day from one number and date suffixes . //// //// DX_YNN = 30, // date string: have a year and two number //// DX_YMN = 31, // date string: have a year, a month, and a number. //// DX_YN = 32, // date string: have a year and one number //// DX_YM = 33, // date string: have a year, a month. //// TX_N = 34, // time from one number (must have ampm) //// TX_NN = 35, // time from two numbers //// TX_NNN = 36, // time from three numbers //// TX_TS = 37, // a set of time suffixed numbers. //// DX_NNY = 38, //// } //// //// //////////////////////////////////////////////////////////////////////////// //// // //// // NOTE: The following state machine table is dependent on the order of the //// // DS and DTT enumerations. //// // //// // For each non terminal state, the following table defines the next state //// // for each given date token type. //// // //// //////////////////////////////////////////////////////////////////////////// //// //// // End NumEnd NumAmPm NumSpace NumDaySep NumTimesep MonthEnd MonthSpace MonthDSep NumDateSuff NumTimeSuff DayOfWeek YearSpace YearDateSep YearEnd TimeZone Era UTCTimeMark //// private static DS[][] dateParsingStates = { //// // DS.BEGIN // DS.BEGIN //// new DS[] { DS.BEGIN, DS.ERROR, DS.TX_N, DS.N, DS.D_Nd, DS.T_Nt, DS.ERROR, DS.D_M, DS.D_M, DS.D_S, DS.T_S, DS.BEGIN, DS.D_Y, DS.D_Y, DS.ERROR, DS.BEGIN, DS.BEGIN, DS.ERROR}, //// //// // DS.N // DS.N //// new DS[] { DS.ERROR, DS.DX_NN, DS.ERROR, DS.NN, DS.D_NNd, DS.ERROR, DS.DX_NM, DS.D_NM, DS.D_MNd, DS.D_NDS, DS.ERROR, DS.N, DS.D_YN, DS.D_YNd, DS.DX_YN, DS.N, DS.N, DS.ERROR}, //// //// // DS.NN // DS.NN //// new DS[] { DS.DX_NN, DS.DX_NNN, DS.TX_N, DS.DX_NNN, DS.ERROR, DS.T_Nt, DS.DX_MNN, DS.DX_MNN, DS.ERROR, DS.ERROR, DS.T_S, DS.NN, DS.DX_NNY, DS.ERROR, DS.DX_NNY, DS.NN, DS.NN, DS.ERROR}, //// //// // DS.D_Nd // DS.D_Nd //// new DS[] { DS.ERROR, DS.DX_NN, DS.ERROR, DS.D_NN, DS.D_NNd, DS.ERROR, DS.DX_NM, DS.D_MN, DS.D_MNd, DS.ERROR, DS.ERROR, DS.D_Nd, DS.D_YN, DS.D_YNd, DS.DX_YN, DS.ERROR, DS.D_Nd, DS.ERROR}, //// //// // DS.D_NN // DS.D_NN //// new DS[] { DS.DX_NN, DS.DX_NNN, DS.TX_N, DS.DX_NNN, DS.ERROR, DS.T_Nt, DS.DX_MNN, DS.DX_MNN, DS.ERROR, DS.DX_DS, DS.T_S, DS.D_NN, DS.DX_NNY, DS.ERROR, DS.DX_NNY, DS.ERROR, DS.D_NN, DS.ERROR}, //// //// // DS.D_NNd // DS.D_NNd //// new DS[] { DS.ERROR, DS.DX_NNN, DS.DX_NNN, DS.DX_NNN, DS.ERROR, DS.ERROR, DS.DX_MNN, DS.DX_MNN, DS.ERROR, DS.DX_DS, DS.ERROR, DS.D_NNd, DS.DX_NNY, DS.ERROR, DS.DX_NNY, DS.ERROR, DS.D_NNd, DS.ERROR}, //// //// // DS.D_M // DS.D_M //// new DS[] { DS.ERROR, DS.DX_MN, DS.ERROR, DS.D_MN, DS.D_MNd, DS.ERROR, DS.ERROR, DS.ERROR, DS.ERROR, DS.ERROR, DS.ERROR, DS.D_M, DS.D_YM, DS.D_YMd, DS.DX_YM, DS.ERROR, DS.D_M, DS.ERROR}, //// //// // DS.D_MN // DS.D_MN //// new DS[] { DS.DX_MN, DS.DX_MNN, DS.DX_MNN, DS.DX_MNN, DS.ERROR, DS.T_Nt, DS.ERROR, DS.ERROR, DS.ERROR, DS.DX_DS, DS.T_S, DS.D_MN, DS.DX_YMN, DS.ERROR, DS.DX_YMN, DS.ERROR, DS.D_MN, DS.ERROR}, //// //// // DS.D_NM // DS.D_NM //// new DS[] { DS.DX_NM, DS.DX_MNN, DS.DX_MNN, DS.DX_MNN, DS.ERROR, DS.T_Nt, DS.ERROR, DS.ERROR, DS.ERROR, DS.DX_DS, DS.T_S, DS.D_NM, DS.DX_YMN, DS.ERROR, DS.DX_YMN, DS.ERROR, DS.D_NM, DS.ERROR}, //// //// // DS.D_MNd // DS.D_MNd //// new DS[] { DS.ERROR, DS.DX_MNN, DS.ERROR, DS.DX_MNN, DS.ERROR, DS.ERROR, DS.ERROR, DS.ERROR, DS.ERROR, DS.ERROR, DS.ERROR, DS.D_MNd, DS.DX_YMN, DS.ERROR, DS.DX_YMN, DS.ERROR, DS.D_MNd, DS.ERROR}, //// //// // DS.D_NDS, // DS.D_NDS, //// new DS[] { DS.DX_NDS,DS.DX_NNDS, DS.DX_NNDS, DS.DX_NNDS, DS.ERROR, DS.T_Nt, DS.ERROR, DS.ERROR, DS.ERROR, DS.D_NDS, DS.T_S, DS.D_NDS, DS.ERROR, DS.ERROR, DS.ERROR, DS.ERROR, DS.D_NDS, DS.ERROR}, //// //// // DS.D_Y // DS.D_Y //// new DS[] { DS.ERROR, DS.DX_YN, DS.ERROR, DS.D_YN, DS.D_YNd, DS.ERROR, DS.DX_YM, DS.D_YM, DS.D_YMd, DS.D_YM, DS.ERROR, DS.D_Y, DS.ERROR, DS.ERROR, DS.ERROR, DS.ERROR, DS.D_Y, DS.ERROR}, //// //// // DS.D_YN // DS.D_YN //// new DS[] { DS.DX_YN, DS.DX_YNN, DS.DX_YNN, DS.DX_YNN, DS.ERROR, DS.ERROR, DS.DX_YMN, DS.DX_YMN, DS.ERROR, DS.ERROR, DS.ERROR, DS.D_YN, DS.ERROR, DS.ERROR, DS.ERROR, DS.ERROR, DS.D_YN, DS.ERROR}, //// //// // DS.D_YNd // DS.D_YNd //// new DS[] { DS.ERROR, DS.DX_YNN, DS.DX_YNN, DS.DX_YNN, DS.ERROR, DS.ERROR, DS.DX_YMN, DS.DX_YMN, DS.ERROR, DS.ERROR, DS.ERROR, DS.D_YN, DS.ERROR, DS.ERROR, DS.ERROR, DS.ERROR, DS.D_YN, DS.ERROR}, //// //// // DS.D_YM // DS.D_YM //// new DS[] { DS.DX_YM, DS.DX_YMN, DS.DX_YMN, DS.DX_YMN, DS.ERROR, DS.ERROR, DS.ERROR, DS.ERROR, DS.ERROR, DS.ERROR, DS.ERROR, DS.D_YM, DS.ERROR, DS.ERROR, DS.ERROR, DS.ERROR, DS.D_YM, DS.ERROR}, //// //// // DS.D_YMd // DS.D_YMd //// new DS[] { DS.ERROR, DS.DX_YMN, DS.DX_YMN, DS.DX_YMN, DS.ERROR, DS.ERROR, DS.ERROR, DS.ERROR, DS.ERROR, DS.ERROR, DS.ERROR, DS.D_YM, DS.ERROR, DS.ERROR, DS.ERROR, DS.ERROR, DS.D_YM, DS.ERROR}, //// //// // DS.D_S // DS.D_S //// new DS[] { DS.DX_DS, DS.DX_DSN, DS.TX_N, DS.T_Nt, DS.ERROR, DS.T_Nt, DS.ERROR, DS.ERROR, DS.ERROR, DS.D_S, DS.T_S, DS.D_S, DS.ERROR, DS.ERROR, DS.ERROR, DS.ERROR, DS.D_S, DS.ERROR}, //// //// // DS.T_S // DS.T_S //// new DS[] { DS.TX_TS, DS.TX_TS, DS.TX_TS, DS.T_Nt, DS.D_Nd, DS.ERROR, DS.ERROR, DS.ERROR, DS.ERROR, DS.D_S, DS.T_S, DS.T_S, DS.ERROR, DS.ERROR, DS.ERROR, DS.T_S, DS.T_S, DS.ERROR}, //// //// // DS.T_Nt // DS.T_Nt //// new DS[] { DS.ERROR, DS.TX_NN, DS.TX_NN, DS.TX_NN, DS.ERROR, DS.T_NNt, DS.DX_NM, DS.D_NM, DS.ERROR, DS.ERROR, DS.T_S, DS.ERROR, DS.ERROR, DS.ERROR, DS.ERROR, DS.T_Nt, DS.T_Nt, DS.TX_NN}, //// //// // DS.T_NNt // DS.T_NNt //// new DS[] { DS.ERROR, DS.TX_NNN, DS.TX_NNN, DS.TX_NNN, DS.ERROR, DS.ERROR, DS.ERROR, DS.ERROR, DS.ERROR, DS.ERROR, DS.T_S, DS.T_NNt, DS.ERROR, DS.ERROR, DS.ERROR, DS.T_NNt, DS.T_NNt, DS.TX_NNN}, //// //// }; //// // End NumEnd NumAmPm NumSpace NumDaySep NumTimesep MonthEnd MonthSpace MonthDSep NumDateSuff NumTimeSuff DayOfWeek YearSpace YearDateSep YearEnd TimeZone Era UTCMark //// //// internal const String GMTName = "GMT"; //// internal const String ZuluName = "Z"; //// //// // //// // Search from the index of str at str.Index to see if the target string exists in the str. //// // //// private static bool MatchWord( ref __DTString str, String target ) //// { //// int length = target.Length; //// if(length > (str.Value.Length - str.Index)) //// { //// return false; //// } //// //// if(str.CompareInfo.Compare( str.Value, str.Index, length, //// target, 0, length, CompareOptions.IgnoreCase ) != 0) //// { //// return (false); //// } //// //// int nextCharIndex = str.Index + target.Length; //// //// if(nextCharIndex < str.Value.Length) //// { //// char nextCh = str.Value[nextCharIndex]; //// if(Char.IsLetter( nextCh )) //// { //// return (false); //// } //// } //// str.Index = nextCharIndex; //// if(str.Index < str.len) //// { //// str.m_current = str.Value[str.Index]; //// } //// //// return (true); //// } //// //// //// // //// // Check the word at the current index to see if it matches GMT name or Zulu name. //// // //// private static bool GetTimeZoneName( ref __DTString str ) //// { //// // //// // When we support more timezone, change this to return an instance of TimeZone. //// // //// if(MatchWord( ref str, GMTName )) //// { //// return (true); //// } //// //// if(MatchWord( ref str, ZuluName )) //// { //// return (true); //// } //// //// return (false); //// } //// //// internal static bool IsDigit( char ch ) //// { //// return (ch >= '0' && ch <= '9'); //// } //// //// //// /*=================================ParseFraction========================== //// **Action: Starting at the str.Index, which should be a decimal symbol. //// ** if the current character is a digit, parse the remaining //// ** numbers as fraction. For example, if the sub-string starting at str.Index is "123", then //// ** the method will return 0.123 //// **Returns: The fraction number. //// **Arguments: //// ** str the parsing string //// **Exceptions: //// ============================================================================*/ //// //// private static bool ParseFraction( ref __DTString str, out double result ) //// { //// result = 0; //// double decimalBase = 0.1; //// int digits = 0; //// char ch; //// while(str.GetNext() //// && IsDigit( ch = str.m_current )) //// { //// result += (ch - '0') * decimalBase; //// decimalBase *= 0.1; //// digits++; //// } //// return (digits > 0); //// } //// //// /*=================================ParseTimeZone========================== //// **Action: Parse the timezone offset in the following format: //// ** "+8", "+08", "+0800", "+0800" //// ** This method is used by DateTime.Parse(). //// **Returns: The TimeZone offset. //// **Arguments: //// ** str the parsing string //// **Exceptions: //// ** FormatException if invalid timezone format is found. //// ============================================================================*/ //// //// private static bool ParseTimeZone( ref __DTString str, ref TimeSpan result ) //// { //// // The hour/minute offset for timezone. //// int hourOffset = 0; //// int minuteOffset = 0; //// DTSubString sub; //// //// // Consume the +/- character that has already been read //// sub = str.GetSubString(); //// if(sub.length != 1) //// { //// return false; //// } //// char offsetChar = sub[0]; //// if(offsetChar != '+' && offsetChar != '-') //// { //// return false; //// } //// str.ConsumeSubString( sub ); //// //// sub = str.GetSubString(); //// if(sub.type != DTSubStringType.Number) //// { //// return false; //// } //// int value = sub.value; //// int length = sub.length; //// if(length == 1 || length == 2) //// { //// // Parsing "+8" or "+08" //// hourOffset = value; //// str.ConsumeSubString( sub ); //// sub = str.GetSubString(); //// if(sub.length == 1 && sub[0] == ':') //// { //// // Parsing "+8:00" or "+08:00" //// str.ConsumeSubString( sub ); //// sub = str.GetSubString(); //// if(sub.type != DTSubStringType.Number || sub.length < 1 || sub.length > 2) //// { //// return false; //// } //// minuteOffset = sub.value; //// str.ConsumeSubString( sub ); //// } //// } //// else if(length == 3 || length == 4) //// { //// // Parsing "+800" or "+0800" //// hourOffset = value / 100; //// minuteOffset = value % 100; //// str.ConsumeSubString( sub ); //// } //// else //// { //// // Wrong number of digits //// return false; //// } //// BCLDebug.Assert( hourOffset >= 0 && hourOffset <= 99, "hourOffset >= 0 && hourOffset <= 99" ); //// BCLDebug.Assert( minuteOffset >= 0 && minuteOffset <= 99, "minuteOffset >= 0 && minuteOffset <= 99" ); //// if(minuteOffset < 0 || minuteOffset >= 60) //// { //// return false; //// } //// result = new TimeSpan( hourOffset, minuteOffset, 0 ); //// if(offsetChar == '-') //// { //// result = result.Negate(); //// } //// return true; //// } //// //// // //// // This is the lexer. Check the character at the current index, and put the found token in dtok and //// // some raw date/time information in raw. //// // //// private static Boolean Lex( //// DS dps, ref __DTString str, ref DateTimeToken dtok, ref DateTimeRawInfo raw, ref DateTimeResult result, ref DateTimeFormatInfo dtfi ) //// { //// //// TokenType tokenType; //// int tokenValue; //// //// TokenType sep; //// dtok.dtt = DTT.Unk; // Assume the token is unkown. //// //// str.GetRegularToken( out tokenType, out tokenValue, dtfi ); //// //// // Look at the regular token. //// switch(tokenType) //// { //// case TokenType.NumberToken: //// case TokenType.YearNumberToken: //// if(raw.numCount == 3 || tokenValue == -1) //// { //// result.SetFailure( ParseFailureKind.Format, "Format_BadDateTime", null ); //// return false; //// } //// // //// // This is a digit. //// // //// // If the previous parsing state is DS.T_NNt (like 12:01), and we got another number, //// // so we will have a terminal state DS.TX_NNN (like 12:01:02). //// // If the previous parsing state is DS.T_Nt (like 12:), and we got another number, //// // so we will have a terminal state DS.TX_NN (like 12:01). //// // //// // Look ahead to see if the following character is a decimal point or timezone offset. //// // This enables us to parse time in the forms of: //// // "11:22:33.1234" or "11:22:33-08". //// if(dps == DS.T_NNt) //// { //// if((str.Index < str.len - 1)) //// { //// char nextCh = str.Value[str.Index]; //// if(nextCh == '.') //// { //// // While ParseFraction can fail, it just means that there were no digits after //// // the dot. In this case ParseFraction just swallows the dot. This is actually //// // valid for cultures like Albanian, that join the time marker to the time with //// // with a dot: e.g. "9:03.MD" //// ParseFraction( ref str, out raw.fraction ); //// } //// } //// } //// if(dps == DS.T_NNt || dps == DS.T_Nt) //// { //// if((str.Index < str.len - 1)) //// { //// char nextCh = str.Value[str.Index]; //// // Skip whitespace, but don't update the index unless we find a time zone marker //// int whitespaceCount = 0; //// while(Char.IsWhiteSpace( nextCh ) && str.Index + whitespaceCount < str.len - 1) //// { //// whitespaceCount++; //// nextCh = str.Value[str.Index + whitespaceCount]; //// } //// if(nextCh == '+' || nextCh == '-') //// { //// str.Index += whitespaceCount; //// if((result.flags & ParseFlags.TimeZoneUsed) != 0) //// { //// // Should not have two timezone offsets. //// result.SetFailure( ParseFailureKind.Format, "Format_BadDateTime", null ); //// return false; //// } //// result.flags |= ParseFlags.TimeZoneUsed; //// if(!ParseTimeZone( ref str, ref result.timeZoneOffset )) //// { //// result.SetFailure( ParseFailureKind.Format, "Format_BadDateTime", null ); //// return false; //// } //// } //// } //// } //// //// dtok.num = tokenValue; //// if(tokenType == TokenType.YearNumberToken) //// { //// if(raw.year == -1) //// { //// raw.year = tokenValue; //// // //// // If we have number which has 3 or more digits (like "001" or "0001"), //// // we assume this number is a year. Save the currnet raw.numCount in //// // raw.year. //// // //// switch(sep = str.GetSeparatorToken( dtfi )) //// { //// case TokenType.SEP_End: //// dtok.dtt = DTT.YearEnd; //// break; //// case TokenType.SEP_Am: //// case TokenType.SEP_Pm: //// if(raw.timeMark == TM.NotSet) //// { //// raw.timeMark = (sep == TokenType.SEP_Am ? TM.AM : TM.PM); //// dtok.dtt = DTT.YearSpace; //// } //// else //// { //// result.SetFailure( ParseFailureKind.Format, "Format_BadDateTime", null ); //// } //// break; //// case TokenType.SEP_Space: //// dtok.dtt = DTT.YearSpace; //// break; //// case TokenType.SEP_Date: //// dtok.dtt = DTT.YearDateSep; //// break; //// case TokenType.SEP_YearSuff: //// case TokenType.SEP_MonthSuff: //// case TokenType.SEP_DaySuff: //// dtok.dtt = DTT.NumDatesuff; //// dtok.suffix = sep; //// break; //// case TokenType.SEP_HourSuff: //// case TokenType.SEP_MinuteSuff: //// case TokenType.SEP_SecondSuff: //// dtok.dtt = DTT.NumTimesuff; //// dtok.suffix = sep; //// break; //// default: //// // Invalid separator after number number. //// result.SetFailure( ParseFailureKind.Format, "Format_BadDateTime", null ); //// return false; //// } //// // //// // Found the token already. Return now. //// // //// return true; //// } //// result.SetFailure( ParseFailureKind.Format, "Format_BadDateTime", null ); //// return false; //// } //// switch(sep = str.GetSeparatorToken( dtfi )) //// { //// // //// // Note here we check if the numCount is less than three. //// // When we have more than three numbers, it will be caught as error in the state machine. //// // //// case TokenType.SEP_End: //// dtok.dtt = DTT.NumEnd; //// raw.AddNumber( dtok.num ); //// break; //// case TokenType.SEP_Am: //// case TokenType.SEP_Pm: //// if(raw.timeMark == TM.NotSet) //// { //// raw.timeMark = (sep == TokenType.SEP_Am ? TM.AM : TM.PM); //// dtok.dtt = DTT.NumAmpm; //// raw.AddNumber( dtok.num ); //// } //// else //// { //// result.SetFailure( ParseFailureKind.Format, "Format_BadDateTime", null ); //// } //// break; //// case TokenType.SEP_Space: //// dtok.dtt = DTT.NumSpace; //// raw.AddNumber( dtok.num ); //// break; //// case TokenType.SEP_Date: //// dtok.dtt = DTT.NumDatesep; //// raw.AddNumber( dtok.num ); //// break; //// case TokenType.SEP_Time: //// if((result.flags & ParseFlags.TimeZoneUsed) == 0) //// { //// dtok.dtt = DTT.NumTimesep; //// raw.AddNumber( dtok.num ); //// } //// else //// { //// // If we already got timezone, there should be no //// // time separator again. //// result.SetFailure( ParseFailureKind.Format, "Format_BadDateTime", null ); //// return false; //// } //// break; //// case TokenType.SEP_YearSuff: //// dtok.num = dtfi.Calendar.ToFourDigitYear( tokenValue ); //// dtok.dtt = DTT.NumDatesuff; //// dtok.suffix = sep; //// break; //// case TokenType.SEP_MonthSuff: //// case TokenType.SEP_DaySuff: //// dtok.dtt = DTT.NumDatesuff; //// dtok.suffix = sep; //// break; //// case TokenType.SEP_HourSuff: //// case TokenType.SEP_MinuteSuff: //// case TokenType.SEP_SecondSuff: //// dtok.dtt = DTT.NumTimesuff; //// dtok.suffix = sep; //// break; //// case TokenType.SEP_LocalTimeMark: //// dtok.dtt = DTT.NumLocalTimeMark; //// raw.AddNumber( dtok.num ); //// break; //// default: //// // Invalid separator after number number. //// result.SetFailure( ParseFailureKind.Format, "Format_BadDateTime", null ); //// return false; //// } //// break; //// case TokenType.HebrewNumber: //// if(tokenValue >= 100) //// { //// // This is a year number //// if(raw.year == -1) //// { //// raw.year = tokenValue; //// // //// // If we have number which has 3 or more digits (like "001" or "0001"), //// // we assume this number is a year. Save the currnet raw.numCount in //// // raw.year. //// // //// switch(sep = str.GetSeparatorToken( dtfi )) //// { //// case TokenType.SEP_End: //// dtok.dtt = DTT.YearEnd; //// break; //// case TokenType.SEP_Space: //// dtok.dtt = DTT.YearSpace; //// break; //// default: //// // Invalid separator after number number. //// result.SetFailure( ParseFailureKind.Format, "Format_BadDateTime", null ); //// return false; //// } //// } //// else //// { //// // Invalid separator after number number. //// result.SetFailure( ParseFailureKind.Format, "Format_BadDateTime", null ); //// return false; //// } //// } //// else //// { //// // This is a day number //// dtok.num = tokenValue; //// raw.AddNumber( dtok.num ); //// //// switch(sep = str.GetSeparatorToken( dtfi )) //// { //// // //// // Note here we check if the numCount is less than three. //// // When we have more than three numbers, it will be caught as error in the state machine. //// // //// case TokenType.SEP_End: //// dtok.dtt = DTT.NumEnd; //// break; //// case TokenType.SEP_Space: //// case TokenType.SEP_Date: //// dtok.dtt = DTT.NumDatesep; //// break; //// default: //// // Invalid separator after number number. //// result.SetFailure( ParseFailureKind.Format, "Format_BadDateTime", null ); //// return false; //// } //// } //// break; //// case TokenType.DayOfWeekToken: //// if(raw.dayOfWeek == -1) //// { //// // //// // This is a day of week name. //// // //// raw.dayOfWeek = tokenValue; //// dtok.dtt = DTT.DayOfWeek; //// } //// else //// { //// result.SetFailure( ParseFailureKind.Format, "Format_BadDateTime", null ); //// return false; //// } //// break; //// case TokenType.MonthToken: //// if(raw.month == -1) //// { //// // //// // This is a month name //// // //// switch(sep = str.GetSeparatorToken( dtfi )) //// { //// case TokenType.SEP_End: //// dtok.dtt = DTT.MonthEnd; //// break; //// case TokenType.SEP_Space: //// dtok.dtt = DTT.MonthSpace; //// break; //// case TokenType.SEP_Date: //// dtok.dtt = DTT.MonthDatesep; //// break; //// default: //// //Invalid separator after month name //// result.SetFailure( ParseFailureKind.Format, "Format_BadDateTime", null ); //// return false; //// } //// raw.month = tokenValue; //// } //// else //// { //// result.SetFailure( ParseFailureKind.Format, "Format_BadDateTime", null ); //// return false; //// } //// break; //// case TokenType.EraToken: //// if(result.era != -1) //// { //// result.era = tokenValue; //// dtok.dtt = DTT.Era; //// } //// else //// { //// result.SetFailure( ParseFailureKind.Format, "Format_BadDateTime", null ); //// return false; //// } //// break; //// case TokenType.JapaneseEraToken: //// // Special case for Japanese. We allow Japanese era name to be used even if the calendar is not Japanese Calendar. //// result.calendar = JapaneseCalendar.GetDefaultInstance(); //// dtfi = DateTimeFormatInfo.GetJapaneseCalendarDTFI(); //// if(result.era != -1) //// { //// result.era = tokenValue; //// dtok.dtt = DTT.Era; //// } //// else //// { //// result.SetFailure( ParseFailureKind.Format, "Format_BadDateTime", null ); //// return false; //// } //// break; //// case TokenType.TEraToken: //// // Special case for Taiwan. //// result.calendar = TaiwanCalendar.GetDefaultInstance(); //// dtfi = DateTimeFormatInfo.GetTaiwanCalendarDTFI(); //// if(result.era != -1) //// { //// result.era = tokenValue; //// dtok.dtt = DTT.Era; //// } //// else //// { //// result.SetFailure( ParseFailureKind.Format, "Format_BadDateTime", null ); //// return false; //// } //// break; //// case TokenType.TimeZoneToken: //// // //// // This is a timezone designator //// // //// // NOTENOTE : for now, we only support "GMT" and "Z" (for Zulu time). //// // //// dtok.dtt = DTT.TimeZone; //// result.flags |= ParseFlags.TimeZoneUsed; //// result.timeZoneOffset = new TimeSpan( 0 ); //// result.flags |= ParseFlags.TimeZoneUtc; //// break; //// case TokenType.EndOfString: //// dtok.dtt = DTT.End; //// break; //// case TokenType.DateWordToken: //// case TokenType.IgnorableSymbol: //// // Date words and ignorable symbols can just be skipped over //// break; //// case TokenType.Am: //// case TokenType.Pm: //// if(raw.timeMark == TM.NotSet) //// { //// raw.timeMark = (TM)tokenValue; //// } //// else //// { //// result.SetFailure( ParseFailureKind.Format, "Format_BadDateTime", null ); //// return false; //// } //// break; //// case TokenType.UnknownToken: //// if(Char.IsLetter( str.m_current )) //// { //// result.SetFailure( ParseFailureKind.FormatWithParameter, "Format_UnknowDateTimeWord", str.Index ); //// return (false); //// } //// else //// { //// // If DateTimeParseIgnorePunctuation is defined, we want to have the V1.1 behavior of just //// // ignoring any unrecognized punctuation and moving on to the next character //// if(Environment.GetCompatibilityFlag( CompatibilityFlag.DateTimeParseIgnorePunctuation )) //// { //// str.GetNext(); //// return true; //// } //// else //// { //// if(VerifyValidPunctuation( ref str )) //// { //// return true; //// } //// } //// result.SetFailure( ParseFailureKind.Format, "Format_BadDateTime", null ); //// return false; //// } //// } //// //// return true; //// } //// //// private static Boolean VerifyValidPunctuation( ref __DTString str ) //// { //// // Compatability Behavior. Allow trailing nulls and surrounding hashes //// Char ch = str.Value[str.Index]; //// if(ch == '#') //// { //// bool foundStart = false; //// bool foundEnd = false; //// for(int i = 0; i < str.len; i++) //// { //// ch = str.Value[i]; //// if(ch == '#') //// { //// if(foundStart) //// { //// if(foundEnd) //// { //// // Having more than two hashes is invalid //// return false; //// } //// else //// { //// foundEnd = true; //// } //// } //// else //// { //// foundStart = true; //// } //// } //// else if(ch == '\0') //// { //// // Allow nulls only at the end //// if(!foundEnd) //// { //// return false; //// } //// } //// else if((!Char.IsWhiteSpace( ch ))) //// { //// // Anthyhing other than whitespace outside hashes is invalid //// if(!foundStart || foundEnd) //// { //// return false; //// } //// } //// } //// if(!foundEnd) //// { //// // The has was un-paired //// return false; //// } //// // Valid Hash usage: eat the hash and continue. //// str.GetNext(); //// return true; //// } //// else if(ch == '\0') //// { //// for(int i = str.Index; i < str.len; i++) //// { //// if(str.Value[i] != '\0') //// { //// // Nulls are only valid if they are the only trailing character //// return false; //// } //// } //// // Move to the end of the string //// str.Index = str.len; //// return true; //// } //// return false; //// } //// //// private const int ORDER_YMD = 0; // The order of date is Year/Month/Day. //// private const int ORDER_MDY = 1; // The order of date is Month/Day/Year. //// private const int ORDER_DMY = 2; // The order of date is Day/Month/Year. //// private const int ORDER_YDM = 3; // The order of date is Year/Day/Month //// private const int ORDER_YM = 4; // Year/Month order. //// private const int ORDER_MY = 5; // Month/Year order. //// private const int ORDER_MD = 6; // Month/Day order. //// private const int ORDER_DM = 7; // Day/Month order. //// //// // //// // Decide the year/month/day order from the datePattern. //// // //// // Return 0 for YMD, 1 for MDY, 2 for DMY, otherwise -1. //// // //// private static Boolean GetYearMonthDayOrder( String datePattern, DateTimeFormatInfo dtfi, out int order ) //// { //// int yearOrder = -1; //// int monthOrder = -1; //// int dayOrder = -1; //// int orderCount = 0; //// //// bool inQuote = false; //// //// for(int i = 0; i < datePattern.Length && orderCount < 3; i++) //// { //// char ch = datePattern[i]; //// if(ch == '\'' || ch == '"') //// { //// inQuote = !inQuote; //// } //// //// if(!inQuote) //// { //// if(ch == 'y') //// { //// yearOrder = orderCount++; //// //// // //// // Skip all year pattern charaters. //// // //// for(; i + 1 < datePattern.Length && datePattern[i + 1] == 'y'; i++) //// { //// // Do nothing here. //// } //// } //// else if(ch == 'M') //// { //// monthOrder = orderCount++; //// // //// // Skip all month pattern characters. //// // //// for(; i + 1 < datePattern.Length && datePattern[i + 1] == 'M'; i++) //// { //// // Do nothing here. //// } //// } //// else if(ch == 'd') //// { //// //// int patternCount = 1; //// // //// // Skip all day pattern characters. //// // //// for(; i + 1 < datePattern.Length && datePattern[i + 1] == 'd'; i++) //// { //// patternCount++; //// } //// // //// // Make sure this is not "ddd" or "dddd", which means day of week. //// // //// if(patternCount <= 2) //// { //// dayOrder = orderCount++; //// } //// } //// } //// } //// //// if(yearOrder == 0 && monthOrder == 1 && dayOrder == 2) //// { //// order = ORDER_YMD; //// return true; //// } //// if(monthOrder == 0 && dayOrder == 1 && yearOrder == 2) //// { //// order = ORDER_MDY; //// return true; //// } //// if(dayOrder == 0 && monthOrder == 1 && yearOrder == 2) //// { //// order = ORDER_DMY; //// return true; //// } //// if(yearOrder == 0 && dayOrder == 1 && monthOrder == 2) //// { //// order = ORDER_YDM; //// return true; //// } //// order = -1; //// return false; //// } //// //// // //// // Decide the year/month order from the pattern. //// // //// // Return 0 for YM, 1 for MY, otherwise -1. //// // //// private static Boolean GetYearMonthOrder( String pattern, DateTimeFormatInfo dtfi, out int order ) //// { //// int yearOrder = -1; //// int monthOrder = -1; //// int orderCount = 0; //// //// bool inQuote = false; //// for(int i = 0; i < pattern.Length && orderCount < 2; i++) //// { //// char ch = pattern[i]; //// if(ch == '\'' || ch == '"') //// { //// inQuote = !inQuote; //// } //// //// if(!inQuote) //// { //// if(ch == 'y') //// { //// yearOrder = orderCount++; //// //// // //// // Skip all year pattern charaters. //// // //// for(; i + 1 < pattern.Length && pattern[i + 1] == 'y'; i++) //// { //// } //// } //// else if(ch == 'M') //// { //// monthOrder = orderCount++; //// // //// // Skip all month pattern characters. //// // //// for(; i + 1 < pattern.Length && pattern[i + 1] == 'M'; i++) //// { //// } //// } //// } //// } //// //// if(yearOrder == 0 && monthOrder == 1) //// { //// order = ORDER_YM; //// return true; //// } //// if(monthOrder == 0 && yearOrder == 1) //// { //// order = ORDER_MY; //// return true; //// } //// order = -1; //// return false; //// } //// //// // //// // Decide the month/day order from the pattern. //// // //// // Return 0 for MD, 1 for DM, otherwise -1. //// // //// private static Boolean GetMonthDayOrder( String pattern, DateTimeFormatInfo dtfi, out int order ) //// { //// int monthOrder = -1; //// int dayOrder = -1; //// int orderCount = 0; //// //// bool inQuote = false; //// for(int i = 0; i < pattern.Length && orderCount < 2; i++) //// { //// char ch = pattern[i]; //// if(ch == '\'' || ch == '"') //// { //// inQuote = !inQuote; //// } //// //// if(!inQuote) //// { //// if(ch == 'd') //// { //// int patternCount = 1; //// // //// // Skip all day pattern charaters. //// // //// for(; i + 1 < pattern.Length && pattern[i + 1] == 'd'; i++) //// { //// patternCount++; //// } //// //// // //// // Make sure this is not "ddd" or "dddd", which means day of week. //// // //// if(patternCount <= 2) //// { //// dayOrder = orderCount++; //// } //// //// } //// else if(ch == 'M') //// { //// monthOrder = orderCount++; //// // //// // Skip all month pattern characters. //// // //// for(; i + 1 < pattern.Length && pattern[i + 1] == 'M'; i++) //// { //// } //// } //// } //// } //// //// if(monthOrder == 0 && dayOrder == 1) //// { //// order = ORDER_MD; //// return true; //// } //// if(dayOrder == 0 && monthOrder == 1) //// { //// order = ORDER_DM; //// return true; //// } //// order = -1; //// return false; //// } //// //// // //// // Adjust the two-digit year if necessary. //// // //// private static int AdjustYear( ref DateTimeResult result, int year ) //// { //// if(year < 100) //// { //// year = result.calendar.ToFourDigitYear( year ); //// } //// return (year); //// } //// //// private static bool SetDateYMD( ref DateTimeResult result, int year, int month, int day ) //// { //// // Note, longer term these checks should be done at the end of the parse. This current //// // way of checking creates order dependence with parsing the era name. //// if(result.calendar.IsValidDay( year, month, day, result.era )) //// { //// result.SetDate( year, month, day ); // YMD //// return (true); //// } //// return (false); //// } //// //// private static bool SetDateMDY( ref DateTimeResult result, int month, int day, int year ) //// { //// return (SetDateYMD( ref result, year, month, day )); //// } //// //// private static bool SetDateDMY( ref DateTimeResult result, int day, int month, int year ) //// { //// return (SetDateYMD( ref result, year, month, day )); //// } //// //// private static bool SetDateYDM( ref DateTimeResult result, int year, int day, int month ) //// { //// return (SetDateYMD( ref result, year, month, day )); //// } //// //// // Processing teriminal case: DS.DX_NN //// private static Boolean GetDayOfNN( ref DateTimeResult result, ref DateTimeRawInfo raw, DateTimeFormatInfo dtfi ) //// { //// //// if((result.flags & ParseFlags.HaveDate) != 0) //// { //// // Multiple dates in the input string //// result.SetFailure( ParseFailureKind.Format, "Format_BadDateTime", null ); //// return false; //// } //// //// int n1 = raw.GetNumber( 0 ); //// int n2 = raw.GetNumber( 1 ); //// //// int year = result.calendar.GetYear( DateTime.Now ); //// //// int order; //// if(!GetMonthDayOrder( dtfi.MonthDayPattern, dtfi, out order )) //// { //// result.SetFailure( ParseFailureKind.FormatWithParameter, "Format_BadDatePattern", dtfi.MonthDayPattern ); //// return false; //// } //// //// if(order == ORDER_MD) //// { //// if(SetDateYMD( ref result, year, n1, n2 )) // MD //// { //// result.flags |= ParseFlags.HaveDate; //// return true; //// } //// } //// else //// { //// // ORDER_DM //// if(SetDateYMD( ref result, year, n2, n1 )) // DM //// { //// result.flags |= ParseFlags.HaveDate; //// return true; //// } //// } //// result.SetFailure( ParseFailureKind.Format, "Format_BadDateTime", null ); //// return false; //// } //// //// // Processing teriminal case: DS.DX_NNN //// private static Boolean GetDayOfNNN( ref DateTimeResult result, ref DateTimeRawInfo raw, DateTimeFormatInfo dtfi ) //// { //// if((result.flags & ParseFlags.HaveDate) != 0) //// { //// // Multiple dates in the input string //// result.SetFailure( ParseFailureKind.Format, "Format_BadDateTime", null ); //// return false; //// } //// //// int n1 = raw.GetNumber( 0 ); //// int n2 = raw.GetNumber( 1 ); ; //// int n3 = raw.GetNumber( 2 ); //// //// int order; //// if(!GetYearMonthDayOrder( dtfi.ShortDatePattern, dtfi, out order )) //// { //// result.SetFailure( ParseFailureKind.FormatWithParameter, "Format_BadDatePattern", dtfi.ShortDatePattern ); //// return false; //// } //// //// if(order == ORDER_YMD) //// { //// if(SetDateYMD( ref result, AdjustYear( ref result, n1 ), n2, n3 )) // YMD //// { //// result.flags |= ParseFlags.HaveDate; //// return true; //// } //// } //// else if(order == ORDER_MDY) //// { //// if(SetDateMDY( ref result, n1, n2, AdjustYear( ref result, n3 ) )) // MDY //// { //// result.flags |= ParseFlags.HaveDate; //// return true; //// } //// } //// else if(order == ORDER_DMY) //// { //// if(SetDateDMY( ref result, n1, n2, AdjustYear( ref result, n3 ) )) // DMY //// { //// result.flags |= ParseFlags.HaveDate; //// return true; //// } //// } //// else if(order == ORDER_YDM) //// { //// if(SetDateYDM( ref result, AdjustYear( ref result, n1 ), n2, n3 )) // YDM //// { //// result.flags |= ParseFlags.HaveDate; //// return true; //// } //// } //// result.SetFailure( ParseFailureKind.Format, "Format_BadDateTime", null ); //// return false; //// } //// //// private static Boolean GetDayOfMN( ref DateTimeResult result, ref DateTimeRawInfo raw, DateTimeFormatInfo dtfi ) //// { //// //// if((result.flags & ParseFlags.HaveDate) != 0) //// { //// // Multiple dates in the input string //// result.SetFailure( ParseFailureKind.Format, "Format_BadDateTime", null ); //// return false; //// } //// //// // The interpretation is based on the MonthDayPattern and YearMonthPattern //// // //// // MonthDayPattern YearMonthPattern Interpretation //// // --------------- ---------------- --------------- //// // MMMM dd MMMM yyyy Day //// // MMMM dd yyyy MMMM Day //// // dd MMMM MMMM yyyy Year //// // dd MMMM yyyy MMMM Day //// // //// // In the first and last cases, it could be either or neither, but a day is a better default interpretation //// // than a 2 digit year. //// //// int monthDayOrder; //// if(!GetMonthDayOrder( dtfi.MonthDayPattern, dtfi, out monthDayOrder )) //// { //// result.SetFailure( ParseFailureKind.FormatWithParameter, "Format_BadDatePattern", dtfi.MonthDayPattern ); //// return false; //// } //// if(monthDayOrder == ORDER_DM) //// { //// int yearMonthOrder; //// if(!GetYearMonthOrder( dtfi.YearMonthPattern, dtfi, out yearMonthOrder )) //// { //// result.SetFailure( ParseFailureKind.FormatWithParameter, "Format_BadDatePattern", dtfi.YearMonthPattern ); //// return false; //// } //// if(yearMonthOrder == ORDER_MY) //// { //// if(!SetDateYMD( ref result, AdjustYear( ref result, raw.GetNumber( 0 ) ), raw.month, 1 )) //// { //// result.SetFailure( ParseFailureKind.Format, "Format_BadDateTime", null ); //// return false; //// } //// return true; //// } //// } //// //// int currentYear = result.calendar.GetYear( DateTime.Now ); //// if(!SetDateYMD( ref result, currentYear, raw.month, raw.GetNumber( 0 ) )) //// { //// result.SetFailure( ParseFailureKind.Format, "Format_BadDateTime", null ); //// return false; //// } //// return true; //// //// } //// //// //////////////////////////////////////////////////////////////////////// //// // Actions: //// // Deal with the terminal state for Hebrew Month/Day pattern //// // //// //////////////////////////////////////////////////////////////////////// //// //// private static Boolean GetHebrewDayOfNM( ref DateTimeResult result, ref DateTimeRawInfo raw, DateTimeFormatInfo dtfi ) //// { //// int monthDayOrder; //// if(!GetMonthDayOrder( dtfi.MonthDayPattern, dtfi, out monthDayOrder )) //// { //// result.SetFailure( ParseFailureKind.FormatWithParameter, "Format_BadDatePattern", dtfi.MonthDayPattern ); //// return false; //// } //// result.Month = raw.month; //// if(monthDayOrder == ORDER_DM) //// { //// if(result.calendar.IsValidDay( result.Year, result.Month, raw.GetNumber( 0 ), result.era )) //// { //// result.Day = raw.GetNumber( 0 ); //// return true; //// } //// } //// result.SetFailure( ParseFailureKind.Format, "Format_BadDateTime", null ); //// return false; //// } //// //// private static Boolean GetDayOfNM( ref DateTimeResult result, ref DateTimeRawInfo raw, DateTimeFormatInfo dtfi ) //// { //// if((result.flags & ParseFlags.HaveDate) != 0) //// { //// // Multiple dates in the input string //// result.SetFailure( ParseFailureKind.Format, "Format_BadDateTime", null ); //// return false; //// } //// //// // The interpretation is based on the MonthDayPattern and YearMonthPattern //// // //// // MonthDayPattern YearMonthPattern Interpretation //// // --------------- ---------------- --------------- //// // MMMM dd MMMM yyyy Day //// // MMMM dd yyyy MMMM Year //// // dd MMMM MMMM yyyy Day //// // dd MMMM yyyy MMMM Day //// // //// // In the first and last cases, it could be either or neither, but a day is a better default interpretation //// // than a 2 digit year. //// //// int monthDayOrder; //// if(!GetMonthDayOrder( dtfi.MonthDayPattern, dtfi, out monthDayOrder )) //// { //// result.SetFailure( ParseFailureKind.FormatWithParameter, "Format_BadDatePattern", dtfi.MonthDayPattern ); //// return false; //// } //// if(monthDayOrder == ORDER_MD) //// { //// int yearMonthOrder; //// if(!GetYearMonthOrder( dtfi.YearMonthPattern, dtfi, out yearMonthOrder )) //// { //// result.SetFailure( ParseFailureKind.FormatWithParameter, "Format_BadDatePattern", dtfi.YearMonthPattern ); //// return false; //// } //// if(yearMonthOrder == ORDER_YM) //// { //// if(!SetDateYMD( ref result, AdjustYear( ref result, raw.GetNumber( 0 ) ), raw.month, 1 )) //// { //// result.SetFailure( ParseFailureKind.Format, "Format_BadDateTime", null ); //// return false; //// } //// return true; //// } //// } //// //// int currentYear = result.calendar.GetYear( DateTime.Now ); //// if(!SetDateYMD( ref result, currentYear, raw.month, raw.GetNumber( 0 ) )) //// { //// result.SetFailure( ParseFailureKind.Format, "Format_BadDateTime", null ); //// return false; //// } //// return true; //// } //// //// private static Boolean GetDayOfMNN( ref DateTimeResult result, ref DateTimeRawInfo raw, DateTimeFormatInfo dtfi ) //// { //// if((result.flags & ParseFlags.HaveDate) != 0) //// { //// // Multiple dates in the input string //// result.SetFailure( ParseFailureKind.Format, "Format_BadDateTime", null ); //// return false; //// } //// //// int n1 = raw.GetNumber( 0 ); //// int n2 = raw.GetNumber( 1 ); //// //// int order; //// if(!GetYearMonthDayOrder( dtfi.ShortDatePattern, dtfi, out order )) //// { //// result.SetFailure( ParseFailureKind.FormatWithParameter, "Format_BadDatePattern", dtfi.ShortDatePattern ); //// return false; //// } //// int year; //// //// if(order == ORDER_MDY) //// { //// if(result.calendar.IsValidDay( year = AdjustYear( ref result, n2 ), raw.month, n1, result.era )) //// { //// result.SetDate( year, raw.month, n1 ); // MDY //// result.flags |= ParseFlags.HaveDate; //// return true; //// } //// else if(result.calendar.IsValidDay( year = AdjustYear( ref result, n1 ), raw.month, n2, result.era )) //// { //// result.SetDate( year, raw.month, n2 ); // YMD //// result.flags |= ParseFlags.HaveDate; //// return true; //// } //// } //// else if(order == ORDER_YMD) //// { //// if(result.calendar.IsValidDay( year = AdjustYear( ref result, n1 ), raw.month, n2, result.era )) //// { //// result.SetDate( year, raw.month, n2 ); // YMD //// result.flags |= ParseFlags.HaveDate; //// return true; //// } //// else if(result.calendar.IsValidDay( year = AdjustYear( ref result, n2 ), raw.month, n1, result.era )) //// { //// result.SetDate( year, raw.month, n1 ); // DMY //// result.flags |= ParseFlags.HaveDate; //// return true; //// } //// } //// else if(order == ORDER_DMY) //// { //// if(result.calendar.IsValidDay( year = AdjustYear( ref result, n2 ), raw.month, n1, result.era )) //// { //// result.SetDate( year, raw.month, n1 ); // DMY //// result.flags |= ParseFlags.HaveDate; //// return true; //// } //// else if(result.calendar.IsValidDay( year = AdjustYear( ref result, n1 ), raw.month, n2, result.era )) //// { //// result.SetDate( year, raw.month, n2 ); // YMD //// result.flags |= ParseFlags.HaveDate; //// return true; //// } //// } //// //// result.SetFailure( ParseFailureKind.Format, "Format_BadDateTime", null ); //// return false; //// } //// //// private static Boolean GetDayOfYNN( ref DateTimeResult result, ref DateTimeRawInfo raw, DateTimeFormatInfo dtfi ) //// { //// //// if((result.flags & ParseFlags.HaveDate) != 0) //// { //// // Multiple dates in the input string //// result.SetFailure( ParseFailureKind.Format, "Format_BadDateTime", null ); //// return false; //// } //// //// int n1 = raw.GetNumber( 0 ); //// int n2 = raw.GetNumber( 1 ); //// String pattern = dtfi.ShortDatePattern; //// //// // by the way, I think I've seen the opposite behavior in the tables. //// if(dtfi.CultureId == 0x0437) //// { //// // 0x0437 = Georgian - Georgia (ka-GE) //// // Very special case for ka-GE: //// // Its short date patten is "dd.MM.yyyy" (ORDER_DMY). //// // However, its long date pattern is "yyyy '\x10ec\x10da\x10d8\x10e1' dd MM, dddd" (ORDER_YDM) //// pattern = dtfi.LongDatePattern; //// } //// //// // For compatability, don't throw if we can't determine the order, but default to YMD instead //// int order; //// if(GetYearMonthDayOrder( pattern, dtfi, out order ) && order == ORDER_YDM) //// { //// if(SetDateYMD( ref result, raw.year, n2, n1 )) //// { //// result.flags |= ParseFlags.HaveDate; //// return true; // Year + DM //// } //// } //// else //// { //// if(SetDateYMD( ref result, raw.year, n1, n2 )) //// { //// result.flags |= ParseFlags.HaveDate; //// return true; // Year + MD //// } //// } //// result.SetFailure( ParseFailureKind.Format, "Format_BadDateTime", null ); //// return false; //// } //// //// private static Boolean GetDayOfNNY( ref DateTimeResult result, ref DateTimeRawInfo raw, DateTimeFormatInfo dtfi ) //// { //// //// if((result.flags & ParseFlags.HaveDate) != 0) //// { //// // Multiple dates in the input string //// result.SetFailure( ParseFailureKind.Format, "Format_BadDateTime", null ); //// return false; //// } //// //// int n1 = raw.GetNumber( 0 ); //// int n2 = raw.GetNumber( 1 ); //// //// int order; //// if(!GetYearMonthDayOrder( dtfi.ShortDatePattern, dtfi, out order )) //// { //// result.SetFailure( ParseFailureKind.FormatWithParameter, "Format_BadDatePattern", dtfi.ShortDatePattern ); //// return false; //// } //// //// if(order == ORDER_MDY || order == ORDER_YMD) //// { //// if(SetDateYMD( ref result, raw.year, n1, n2 )) //// { //// result.flags |= ParseFlags.HaveDate; //// return true; // MD + Year //// } //// } //// else //// { //// if(SetDateYMD( ref result, raw.year, n2, n1 )) //// { //// result.flags |= ParseFlags.HaveDate; //// return true; // DM + Year //// } //// } //// result.SetFailure( ParseFailureKind.Format, "Format_BadDateTime", null ); //// return false; //// } //// //// //// private static Boolean GetDayOfYMN( ref DateTimeResult result, ref DateTimeRawInfo raw, DateTimeFormatInfo dtfi ) //// { //// //// if((result.flags & ParseFlags.HaveDate) != 0) //// { //// // Multiple dates in the input string //// result.SetFailure( ParseFailureKind.Format, "Format_BadDateTime", null ); //// return false; //// } //// //// if(SetDateYMD( ref result, raw.year, raw.month, raw.GetNumber( 0 ) )) //// { //// result.flags |= ParseFlags.HaveDate; //// return true; //// } //// result.SetFailure( ParseFailureKind.Format, "Format_BadDateTime", null ); //// return false; //// } //// //// private static Boolean GetDayOfYN( ref DateTimeResult result, ref DateTimeRawInfo raw, DateTimeFormatInfo dtfi ) //// { //// if((result.flags & ParseFlags.HaveDate) != 0) //// { //// // Multiple dates in the input string //// result.SetFailure( ParseFailureKind.Format, "Format_BadDateTime", null ); //// return false; //// } //// //// if(SetDateYMD( ref result, raw.year, raw.GetNumber( 0 ), 1 )) //// { //// result.flags |= ParseFlags.HaveDate; //// return true; //// } //// result.SetFailure( ParseFailureKind.Format, "Format_BadDateTime", null ); //// return false; //// } //// //// private static Boolean GetDayOfYM( ref DateTimeResult result, ref DateTimeRawInfo raw, DateTimeFormatInfo dtfi ) //// { //// if((result.flags & ParseFlags.HaveDate) != 0) //// { //// // Multiple dates in the input string //// result.SetFailure( ParseFailureKind.Format, "Format_BadDateTime", null ); //// return false; //// } //// //// if(SetDateYMD( ref result, raw.year, raw.month, 1 )) //// { //// result.flags |= ParseFlags.HaveDate; //// return true; //// } //// result.SetFailure( ParseFailureKind.Format, "Format_BadDateTime", null ); //// return false; //// } //// //// private static void AdjustTimeMark( DateTimeFormatInfo dtfi, ref DateTimeRawInfo raw ) //// { //// // Specail case for culture which uses AM as empty string. //// // E.g. af-ZA (0x0436) //// // S1159 \x0000 //// // S2359 nm //// // In this case, if we are parsing a string like "2005/09/14 12:23", we will assume this is in AM. //// //// if(raw.timeMark == TM.NotSet) //// { //// if(dtfi.AMDesignator != null && dtfi.PMDesignator != null) //// { //// if(dtfi.AMDesignator.Length == 0 && dtfi.PMDesignator.Length != 0) //// { //// raw.timeMark = TM.AM; //// } //// if(dtfi.PMDesignator.Length == 0 && dtfi.AMDesignator.Length != 0) //// { //// raw.timeMark = TM.PM; //// } //// } //// } //// } //// //// // //// // Adjust hour according to the time mark. //// // //// private static Boolean AdjustHour( ref int hour, TM timeMark ) //// { //// if(timeMark != TM.NotSet) //// { //// //// if(timeMark == TM.AM) //// { //// if(hour < 0 || hour > 12) //// { //// return false; //// } //// hour = (hour == 12) ? 0 : hour; //// } //// else //// { //// if(hour < 0 || hour > 23) //// { //// return false; //// } //// if(hour < 12) //// { //// hour += 12; //// } //// } //// } //// return true; //// } //// //// private static Boolean GetTimeOfN( DateTimeFormatInfo dtfi, ref DateTimeResult result, ref DateTimeRawInfo raw ) //// { //// if((result.flags & ParseFlags.HaveTime) != 0) //// { //// // Multiple times in the input string //// result.SetFailure( ParseFailureKind.Format, "Format_BadDateTime", null ); //// return false; //// } //// // //// // In this case, we need a time mark. Check if so. //// // //// if(raw.timeMark == TM.NotSet) //// { //// result.SetFailure( ParseFailureKind.Format, "Format_BadDateTime", null ); //// return false; //// } //// result.Hour = raw.GetNumber( 0 ); //// result.flags |= ParseFlags.HaveTime; //// return true; //// } //// //// private static Boolean GetTimeOfNN( DateTimeFormatInfo dtfi, ref DateTimeResult result, ref DateTimeRawInfo raw ) //// { //// BCLDebug.Assert( raw.numCount >= 2, "raw.numCount >= 2" ); //// if((result.flags & ParseFlags.HaveTime) != 0) //// { //// // Multiple times in the input string //// result.SetFailure( ParseFailureKind.Format, "Format_BadDateTime", null ); //// return false; //// } //// //// result.Hour = raw.GetNumber( 0 ); //// result.Minute = raw.GetNumber( 1 ); //// result.flags |= ParseFlags.HaveTime; //// return true; //// } //// //// private static Boolean GetTimeOfNNN( DateTimeFormatInfo dtfi, ref DateTimeResult result, ref DateTimeRawInfo raw ) //// { //// if((result.flags & ParseFlags.HaveTime) != 0) //// { //// // Multiple times in the input string //// result.SetFailure( ParseFailureKind.Format, "Format_BadDateTime", null ); //// return false; //// } //// BCLDebug.Assert( raw.numCount >= 3, "raw.numCount >= 3" ); //// result.Hour = raw.GetNumber( 0 ); //// result.Minute = raw.GetNumber( 1 ); //// result.Second = raw.GetNumber( 2 ); //// result.flags |= ParseFlags.HaveTime; //// return true; //// } //// //// // //// // Processing terminal state: A Date suffix followed by one number. //// // //// private static Boolean GetDateOfDSN( ref DateTimeResult result, ref DateTimeRawInfo raw ) //// { //// if(raw.numCount != 1 || result.Day != -1) //// { //// result.SetFailure( ParseFailureKind.Format, "Format_BadDateTime", null ); //// return false; //// } //// result.Day = raw.GetNumber( 0 ); //// return true; //// } //// //// private static Boolean GetDateOfNDS( ref DateTimeResult result, ref DateTimeRawInfo raw ) //// { //// if(result.Month == -1) //// { //// //Should have a month suffix //// result.SetFailure( ParseFailureKind.Format, "Format_BadDateTime", null ); //// return false; //// } //// if(result.Year != -1) //// { //// // Aleady has a year suffix //// result.SetFailure( ParseFailureKind.Format, "Format_BadDateTime", null ); //// return false; //// } //// result.Year = AdjustYear( ref result, raw.GetNumber( 0 ) ); //// result.Day = 1; //// return true; //// } //// //// private static Boolean GetDateOfNNDS( ref DateTimeResult result, ref DateTimeRawInfo raw, DateTimeFormatInfo dtfi ) //// { //// //// // For partial CJK Dates, the only valid formats are with a specified year, followed by two numbers, which //// // will be the Month and Day, and with a specified Month, when the numbers are either the year and day or //// // day and year, depending on the short date pattern. //// //// if((result.flags & ParseFlags.HaveYear) != 0) //// { //// if(((result.flags & ParseFlags.HaveMonth) == 0) && ((result.flags & ParseFlags.HaveDay) == 0)) //// { //// if(SetDateYMD( ref result, result.Year = AdjustYear( ref result, raw.year ), raw.GetNumber( 0 ), raw.GetNumber( 1 ) )) //// { //// return true; //// } //// } //// } //// else if((result.flags & ParseFlags.HaveMonth) != 0) //// { //// if(((result.flags & ParseFlags.HaveYear) == 0) && ((result.flags & ParseFlags.HaveDay) == 0)) //// { //// int order; //// if(!GetYearMonthDayOrder( dtfi.ShortDatePattern, dtfi, out order )) //// { //// result.SetFailure( ParseFailureKind.FormatWithParameter, "Format_BadDatePattern", dtfi.ShortDatePattern ); //// return false; //// } //// int year; //// if(order == ORDER_YMD) //// { //// if(SetDateYMD( ref result, year = AdjustYear( ref result, raw.GetNumber( 0 ) ), result.Month, raw.GetNumber( 1 ) )) //// { //// return true; //// } //// } //// else //// { //// if(SetDateYMD( ref result, year = AdjustYear( ref result, raw.GetNumber( 1 ) ), result.Month, raw.GetNumber( 0 ) )) //// { //// return true; //// } //// } //// } //// } //// result.SetFailure( ParseFailureKind.Format, "Format_BadDateTime", null ); //// return false; //// } //// //// // //// // A date suffix is found, use this method to put the number into the result. //// // //// private static bool ProcessDateTimeSuffix( ref DateTimeResult result, ref DateTimeRawInfo raw, ref DateTimeToken dtok ) //// { //// switch(dtok.suffix) //// { //// case TokenType.SEP_YearSuff: //// if((result.flags & ParseFlags.HaveYear) != 0) //// { //// return false; //// } //// result.flags |= ParseFlags.HaveYear; //// result.Year = raw.year = dtok.num; //// break; //// case TokenType.SEP_MonthSuff: //// if((result.flags & ParseFlags.HaveMonth) != 0) //// { //// return false; //// } //// result.flags |= ParseFlags.HaveMonth; //// result.Month = raw.month = dtok.num; //// break; //// case TokenType.SEP_DaySuff: //// if((result.flags & ParseFlags.HaveDay) != 0) //// { //// return false; //// } //// result.flags |= ParseFlags.HaveDay; //// result.Day = dtok.num; //// break; //// case TokenType.SEP_HourSuff: //// if((result.flags & ParseFlags.HaveHour) != 0) //// { //// return false; //// } //// result.flags |= ParseFlags.HaveHour; //// result.Hour = dtok.num; //// break; //// case TokenType.SEP_MinuteSuff: //// if((result.flags & ParseFlags.HaveMinute) != 0) //// { //// return false; //// } //// result.flags |= ParseFlags.HaveMinute; //// result.Minute = dtok.num; //// break; //// case TokenType.SEP_SecondSuff: //// if((result.flags & ParseFlags.HaveSecond) != 0) //// { //// return false; //// } //// result.flags |= ParseFlags.HaveSecond; //// result.Second = dtok.num; //// break; //// } //// return true; //// //// } //// //// //////////////////////////////////////////////////////////////////////// //// // //// // Actions: //// // This is used by DateTime.Parse(). //// // Process the terminal state for the Hebrew calendar parsing. //// // //// //////////////////////////////////////////////////////////////////////// //// //// internal static Boolean ProcessHebrewTerminalState( DS dps, ref DateTimeResult result, ref DateTimeRawInfo raw, DateTimeFormatInfo dtfi ) //// { //// // The following are accepted terminal state for Hebrew date. //// switch(dps) //// { //// case DS.DX_MNN: //// // Deal with the default long/short date format when the year number is ambigous (i.e. year < 100). //// raw.year = raw.GetNumber( 1 ); //// if(!dtfi.YearMonthAdjustment( ref raw.year, ref raw.month, true )) //// { //// result.SetFailure( ParseFailureKind.FormatBadDateTimeCalendar, "Format_BadDateTimeCalendar", null ); //// return false; //// } //// if(!GetDayOfMNN( ref result, ref raw, dtfi )) //// { //// return false; //// } //// break; //// case DS.DX_YMN: //// // Deal with the default long/short date format when the year number is NOT ambigous (i.e. year >= 100). //// if(!dtfi.YearMonthAdjustment( ref raw.year, ref raw.month, true )) //// { //// result.SetFailure( ParseFailureKind.FormatBadDateTimeCalendar, "Format_BadDateTimeCalendar", null ); //// return false; //// } //// if(!GetDayOfYMN( ref result, ref raw, dtfi )) //// { //// return false; //// } //// break; //// case DS.DX_NM: //// // Deal with Month/Day pattern. //// result.Year = dtfi.Calendar.GetYear( DateTime.Now ); //// if(!dtfi.YearMonthAdjustment( ref result.Year, ref raw.month, true )) //// { //// result.SetFailure( ParseFailureKind.FormatBadDateTimeCalendar, "Format_BadDateTimeCalendar", null ); //// return false; //// } //// if(!GetHebrewDayOfNM( ref result, ref raw, dtfi )) //// { //// return false; //// } //// break; //// case DS.DX_YM: //// // Deal with Year/Month pattern. //// if(!dtfi.YearMonthAdjustment( ref raw.year, ref raw.month, true )) //// { //// result.SetFailure( ParseFailureKind.FormatBadDateTimeCalendar, "Format_BadDateTimeCalendar", null ); //// return false; //// } //// if(!GetDayOfYM( ref result, ref raw, dtfi )) //// { //// return false; //// } //// break; //// case DS.TX_N: //// // Deal hour + AM/PM //// if(!GetTimeOfN( dtfi, ref result, ref raw )) //// { //// return false; //// } //// break; //// case DS.TX_NN: //// if(!GetTimeOfNN( dtfi, ref result, ref raw )) //// { //// return false; //// } //// break; //// case DS.TX_NNN: //// if(!GetTimeOfNNN( dtfi, ref result, ref raw )) //// { //// return false; //// } //// break; //// default: //// result.SetFailure( ParseFailureKind.Format, "Format_BadDateTime", null ); //// return false; //// //// } //// if(dps > DS.ERROR) //// { //// // //// // We have reached a terminal state. Reset the raw num count. //// // //// raw.numCount = 0; //// } //// return true; //// } //// //// // //// // A terminal state has been reached, call the appropriate function to fill in the parsing result. //// // Return true if the state is a terminal state. //// // //// internal static Boolean ProcessTerminaltState( DS dps, ref DateTimeResult result, ref DateTimeRawInfo raw, DateTimeFormatInfo dtfi ) //// { //// //// switch(dps) //// { //// case DS.DX_NN: //// if(!GetDayOfNN( ref result, ref raw, dtfi )) //// { //// return false; //// } //// break; //// case DS.DX_NNN: //// if(!GetDayOfNNN( ref result, ref raw, dtfi )) //// { //// return false; //// } //// break; //// case DS.DX_MN: //// if(!GetDayOfMN( ref result, ref raw, dtfi )) //// { //// return false; //// } //// break; //// case DS.DX_NM: //// if(!GetDayOfNM( ref result, ref raw, dtfi )) //// { //// return false; //// } //// break; //// case DS.DX_MNN: //// if(!GetDayOfMNN( ref result, ref raw, dtfi )) //// { //// return false; //// } //// break; //// case DS.DX_DS: //// // The result has got the correct value. No need to process. //// break; //// case DS.DX_YNN: //// if(!GetDayOfYNN( ref result, ref raw, dtfi )) //// { //// return false; //// } //// break; //// case DS.DX_NNY: //// if(!GetDayOfNNY( ref result, ref raw, dtfi )) //// { //// return false; //// } //// break; //// case DS.DX_YMN: //// if(!GetDayOfYMN( ref result, ref raw, dtfi )) //// { //// return false; //// } //// break; //// case DS.DX_YN: //// if(!GetDayOfYN( ref result, ref raw, dtfi )) //// { //// return false; //// } //// break; //// case DS.DX_YM: //// if(!GetDayOfYM( ref result, ref raw, dtfi )) //// { //// return false; //// } //// break; //// case DS.TX_N: //// if(!GetTimeOfN( dtfi, ref result, ref raw )) //// { //// return false; //// } //// break; //// case DS.TX_NN: //// if(!GetTimeOfNN( dtfi, ref result, ref raw )) //// { //// return false; //// } //// break; //// case DS.TX_NNN: //// if(!GetTimeOfNNN( dtfi, ref result, ref raw )) //// { //// return false; //// } //// break; //// case DS.TX_TS: //// // The result has got the correct value. Nothing to do. //// break; //// case DS.DX_DSN: //// if(!GetDateOfDSN( ref result, ref raw )) //// { //// return false; //// } //// break; //// case DS.DX_NDS: //// if(!GetDateOfNDS( ref result, ref raw )) //// { //// return false; //// } //// break; //// case DS.DX_NNDS: //// if(!GetDateOfNNDS( ref result, ref raw, dtfi )) //// { //// return false; //// } //// break; //// } //// //// if(dps > DS.ERROR) //// { //// // //// // We have reached a terminal state. Reset the raw num count. //// // //// raw.numCount = 0; //// } //// return true; //// } [MethodImplAttribute( MethodImplOptions.InternalCall )] internal static extern DateTime Parse( String s , DateTimeFormatInfo dtfi , DateTimeStyles styles ); //// { //// DateTimeResult result = new DateTimeResult(); // The buffer to store the parsing result. //// result.Init(); //// if(TryParse( s, dtfi, styles, ref result )) //// { //// return result.parsedDate; //// } //// else //// { //// throw GetDateTimeParseException( ref result ); //// } //// } //// //// internal static bool TryParse( String s, DateTimeFormatInfo dtfi, DateTimeStyles styles, out DateTime result ) //// { //// result = DateTime.MinValue; //// DateTimeResult resultData = new DateTimeResult(); // The buffer to store the parsing result. //// resultData.Init(); //// if(TryParse( s, dtfi, styles, ref resultData )) //// { //// result = resultData.parsedDate; //// return true; //// } //// return false; //// } //// //// // //// // This is the real method to do the parsing work. //// // //// internal static bool TryParse( String s, DateTimeFormatInfo dtfi, DateTimeStyles styles, ref DateTimeResult result ) //// { //// if(s == null) //// { //// result.SetFailure( ParseFailureKind.ArgumentNull, "ArgumentNull_String", null, "s" ); //// return false; //// } //// if(s.Length == 0) //// { //// result.SetFailure( ParseFailureKind.Format, "Format_BadDateTime", null ); //// return false; //// } //// //// BCLDebug.Assert( dtfi != null, "dtfi == null" ); //// //// DateTime time; //// // //// // First try the predefined format. //// // //// //@ToDo: We need a more efficient way of doing this. //// // if (ParseExactMultiple( //// // s, predefinedFormats, DateTimeFormatInfo.InvariantInfo, DateTimeStyles.AllowWhiteSpaces, out time)) { //// // return (time); //// // } //// //// DS dps = DS.BEGIN; // Date Parsing State. //// bool reachTerminalState = false; //// //// DateTimeToken dtok = new DateTimeToken(); // The buffer to store the parsing token. //// dtok.suffix = TokenType.SEP_Unk; //// DateTimeRawInfo raw = new DateTimeRawInfo(); // The buffer to store temporary parsing information. //// unsafe //// { //// Int32* numberPointer = stackalloc Int32[3]; //// raw.Init( numberPointer ); //// } //// result.calendar = dtfi.Calendar; //// result.era = Calendar.CurrentEra; //// //// // //// // The string to be parsed. Use a __DTString wrapper so that we can trace the index which //// // indicates the begining of next token. //// // //// __DTString str = new __DTString( s, dtfi ); //// //// str.GetNext(); //// //// // //// // The following loop will break out when we reach the end of the str. //// // //// do //// { //// // //// // Call the lexer to get the next token. //// // //// // If we find a era in Lex(), the era value will be in raw.era. //// if(!Lex( dps, ref str, ref dtok, ref raw, ref result, ref dtfi )) //// { //// return false; //// } //// //// // //// // If the token is not unknown, process it. //// // Otherwise, just discard it. //// // //// if(dtok.dtt != DTT.Unk) //// { //// // //// // Check if we got any CJK Date/Time suffix. //// // Since the Date/Time suffix tells us the number belongs to year/month/day/hour/minute/second, //// // store the number in the appropriate field in the result. //// // //// if(dtok.suffix != TokenType.SEP_Unk) //// { //// if(!ProcessDateTimeSuffix( ref result, ref raw, ref dtok )) //// { //// result.SetFailure( ParseFailureKind.Format, "Format_BadDateTime", null ); //// return false; //// } //// //// dtok.suffix = TokenType.SEP_Unk; // Reset suffix to SEP_Unk; //// } //// //// if(dtok.dtt == DTT.NumLocalTimeMark) //// { //// if(dps == DS.D_YNd || dps == DS.D_YN) //// { //// // Consider this as ISO 8601 format: //// // "yyyy-MM-dd'T'HH:mm:ss" 1999-10-31T02:00:00 //// return (ParseISO8601( ref raw, ref str, styles, ref result )); //// } //// else //// { //// result.SetFailure( ParseFailureKind.Format, "Format_BadDateTime", null ); //// return false; //// } //// } //// //// // //// // Advance to the next state, and continue //// // //// dps = dateParsingStates[(int)dps][(int)dtok.dtt]; //// //// if(dps == DS.ERROR) //// { //// result.SetFailure( ParseFailureKind.Format, "Format_BadDateTime", null ); //// return false; //// } //// else if(dps > DS.ERROR) //// { //// if((dtfi.FormatFlags & DateTimeFormatFlags.UseHebrewRule) != 0) //// { //// if(!ProcessHebrewTerminalState( dps, ref result, ref raw, dtfi )) //// { //// return false; //// } //// } //// else //// { //// if(!ProcessTerminaltState( dps, ref result, ref raw, dtfi )) //// { //// return false; //// } //// } //// reachTerminalState = true; //// //// // //// // If we have reached a terminal state, start over from DS.BEGIN again. //// // For example, when we parsed "1999-12-23 13:30", we will reach a terminal state at "1999-12-23", //// // and we start over so we can continue to parse "12:30". //// // //// dps = DS.BEGIN; //// } //// } //// } while(dtok.dtt != DTT.End && dtok.dtt != DTT.NumEnd && dtok.dtt != DTT.MonthEnd); //// //// if(!reachTerminalState) //// { //// result.SetFailure( ParseFailureKind.Format, "Format_BadDateTime", null ); //// return false; //// } //// //// AdjustTimeMark( dtfi, ref raw ); //// if(!AdjustHour( ref result.Hour, raw.timeMark )) //// { //// result.SetFailure( ParseFailureKind.Format, "Format_BadDateTime", null ); //// return false; //// } //// //// // Check if the parased string only contains hour/minute/second values. //// bool bTimeOnly = (result.Year == -1 && result.Month == -1 && result.Day == -1); //// //// // //// // Check if any year/month/day is missing in the parsing string. //// // If yes, get the default value from today's date. //// // //// CheckDefaultDateTime( ref result, ref result.calendar, styles ); //// //// if(!result.calendar.TryToDateTime( result.Year, result.Month, result.Day, //// result.Hour, result.Minute, result.Second, 0, result.era, out time )) //// { //// result.SetFailure( ParseFailureKind.FormatBadDateTimeCalendar, "Format_BadDateTimeCalendar", null ); //// return false; //// } //// if(raw.fraction > 0) //// { //// time = time.AddTicks( (long)Math.Round( raw.fraction * Calendar.TicksPerSecond ) ); //// } //// //// // //// // We have to check day of week before we adjust to the time zone. //// // Otherwise, the value of day of week may change after adjustting to the time zone. //// // //// if(raw.dayOfWeek != -1) //// { //// // //// // Check if day of week is correct. //// // //// if(raw.dayOfWeek != (int)result.calendar.GetDayOfWeek( time )) //// { //// result.SetFailure( ParseFailureKind.Format, "Format_BadDayOfWeek", null ); //// return false; //// } //// } //// //// result.parsedDate = time; //// //// if(!DetermineTimeZoneAdjustments( ref result, styles, bTimeOnly )) //// { //// return false; //// } //// //// return true; //// } //// //// // Handles time zone adjustments and sets DateTimeKind values as required by the styles //// private static Boolean DetermineTimeZoneAdjustments( ref DateTimeResult result, DateTimeStyles styles, Boolean bTimeOnly ) //// { //// //// // The flags AssumeUniveral and AssumeLocal only apply when the input does not have a time zone //// if((result.flags & ParseFlags.TimeZoneUsed) == 0) //// { //// //// // If AssumeLocal or AssumeLocal is used, there will always be a kind specified. As in the //// // case when a time zone is present, it will default to being local unless AdjustToUniversal //// // is present. These comparisons determine whether setting the kind is sufficient, or if a //// // time zone adjustment is required. For consistentcy with the rest of parsing, it is desirable //// // to fall through to the Adjust methods below, so that there is consist handling of boundary //// // cases like wrapping around on time-only dates and temporarily allowing an adjusted date //// // to exceed DateTime.MaxValue //// if((styles & DateTimeStyles.AssumeLocal) != 0) //// { //// if((styles & DateTimeStyles.AdjustToUniversal) != 0) //// { //// result.flags |= ParseFlags.TimeZoneUsed; //// result.timeZoneOffset = TimeZone.CurrentTimeZone.GetUtcOffset( result.parsedDate ); //// } //// else //// { //// result.parsedDate = DateTime.SpecifyKind( result.parsedDate, DateTimeKind.Local ); //// return true; //// } //// } //// else if((styles & DateTimeStyles.AssumeUniversal) != 0) //// { //// if((styles & DateTimeStyles.AdjustToUniversal) != 0) //// { //// result.parsedDate = DateTime.SpecifyKind( result.parsedDate, DateTimeKind.Utc ); //// return true; //// } //// else //// { //// result.flags |= ParseFlags.TimeZoneUsed; //// result.timeZoneOffset = TimeSpan.Zero; //// } //// } //// else //// { //// // No time zone and no Assume flags, so DateTimeKind.Unspecified is fine //// BCLDebug.Assert( result.parsedDate.Kind == DateTimeKind.Unspecified, "result.parsedDate.Kind == DateTimeKind.Unspecified" ); //// return true; //// } //// } //// //// if(((styles & DateTimeStyles.RoundtripKind) != 0) && ((result.flags & ParseFlags.TimeZoneUtc) != 0)) //// { //// result.parsedDate = DateTime.SpecifyKind( result.parsedDate, DateTimeKind.Utc ); //// return true; //// } //// //// if((styles & DateTimeStyles.AdjustToUniversal) != 0) //// { //// return (AdjustTimeZoneToUniversal( ref result )); //// } //// return (AdjustTimeZoneToLocal( ref result, bTimeOnly )); //// } //// //// // //// // Adjust the specified time to universal time based on the supplied timezone. //// // E.g. when parsing "2001/06/08 14:00-07:00", //// // the time is 2001/06/08 14:00, and timeZoneOffset = -07:00. //// // The result will be "2001/06/08 21:00" //// // //// private static Boolean AdjustTimeZoneToUniversal( ref DateTimeResult result ) //// { //// long resultTicks = result.parsedDate.Ticks; //// resultTicks -= result.timeZoneOffset.Ticks; //// if(resultTicks < 0) //// { //// resultTicks += Calendar.TicksPerDay; //// } //// //// if(resultTicks < DateTime.MinTicks || resultTicks > DateTime.MaxTicks) //// { //// result.SetFailure( ParseFailureKind.Format, "Format_DateOutOfRange", null ); //// return false; //// } //// result.parsedDate = new DateTime( resultTicks, DateTimeKind.Utc ); //// return true; //// } //// //// // //// // Adjust the specified time to universal time based on the supplied timezone, //// // and then convert to local time. //// // E.g. when parsing "2001/06/08 14:00-04:00", and local timezone is GMT-7. //// // the time is 2001/06/08 14:00, and timeZoneOffset = -05:00. //// // The result will be "2001/06/08 11:00" //// // //// private static Boolean AdjustTimeZoneToLocal( ref DateTimeResult result, bool bTimeOnly ) //// { //// long resultTicks = result.parsedDate.Ticks; //// // Convert to local ticks //// CurrentSystemTimeZone tz = (CurrentSystemTimeZone)TimeZone.CurrentTimeZone; //// Boolean isAmbiguousLocalDst = false; //// if(resultTicks < Calendar.TicksPerDay) //// { //// // //// // This is time of day. //// // //// //// // Adjust timezone. //// resultTicks -= result.timeZoneOffset.Ticks; //// // If the time is time of day, use the current timezone offset. //// resultTicks += tz.GetUtcOffset( bTimeOnly ? DateTime.Now : result.parsedDate ).Ticks; //// //// if(resultTicks < 0) //// { //// resultTicks += Calendar.TicksPerDay; //// } //// } //// else //// { //// // Adjust timezone to GMT. //// resultTicks -= result.timeZoneOffset.Ticks; //// if(resultTicks < DateTime.MinTicks || resultTicks > DateTime.MaxTicks) //// { //// // If the result ticks is greater than DateTime.MaxValue, we can not create a DateTime from this ticks. //// // In this case, keep using the old code. //// resultTicks += tz.GetUtcOffset( result.parsedDate ).Ticks; //// } //// else //// { //// // Convert the GMT time to local time. //// resultTicks += tz.GetUtcOffsetFromUniversalTime( new DateTime( resultTicks ), ref isAmbiguousLocalDst ); //// } //// } //// if(resultTicks < DateTime.MinTicks || resultTicks > DateTime.MaxTicks) //// { //// result.parsedDate = DateTime.MinValue; //// result.SetFailure( ParseFailureKind.Format, "Format_DateOutOfRange", null ); //// return false; //// } //// result.parsedDate = new DateTime( resultTicks, DateTimeKind.Local, isAmbiguousLocalDst ); //// return true; //// } //// //// // //// // Parse the ISO8601 format string found during Parse(); //// // //// // //// private static bool ParseISO8601( ref DateTimeRawInfo raw, ref __DTString str, DateTimeStyles styles, ref DateTimeResult result ) //// { //// if(raw.year < 0 || raw.GetNumber( 0 ) < 0 || raw.GetNumber( 1 ) < 0) //// { //// } //// str.Index--; //// int hour, minute; //// int second = 0; //// double partSecond = 0; //// //// str.SkipWhiteSpaces(); //// if(!ParseDigits( ref str, 2, out hour )) //// { //// result.SetFailure( ParseFailureKind.Format, "Format_BadDateTime", null ); //// return false; //// } //// str.SkipWhiteSpaces(); //// if(!str.Match( ':' )) //// { //// result.SetFailure( ParseFailureKind.Format, "Format_BadDateTime", null ); //// return false; //// } //// str.SkipWhiteSpaces(); //// if(!ParseDigits( ref str, 2, out minute )) //// { //// result.SetFailure( ParseFailureKind.Format, "Format_BadDateTime", null ); //// return false; //// } //// str.SkipWhiteSpaces(); //// if(str.Match( ':' )) //// { //// str.SkipWhiteSpaces(); //// if(!ParseDigits( ref str, 2, out second )) //// { //// result.SetFailure( ParseFailureKind.Format, "Format_BadDateTime", null ); //// return false; //// } //// if(str.Match( '.' )) //// { //// if(!ParseFraction( ref str, out partSecond )) //// { //// result.SetFailure( ParseFailureKind.Format, "Format_BadDateTime", null ); //// return false; //// } //// str.Index--; //// } //// str.SkipWhiteSpaces(); //// } //// if(str.GetNext()) //// { //// char ch = str.GetChar(); //// if(ch == '+' || ch == '-') //// { //// result.flags |= ParseFlags.TimeZoneUsed; //// if(!ParseTimeZone( ref str, ref result.timeZoneOffset )) //// { //// result.SetFailure( ParseFailureKind.Format, "Format_BadDateTime", null ); //// return false; //// } //// } //// else if(ch == 'Z' || ch == 'z') //// { //// result.flags |= ParseFlags.TimeZoneUsed; //// result.timeZoneOffset = TimeSpan.Zero; //// result.flags |= ParseFlags.TimeZoneUtc; //// } //// else //// { //// str.Index--; //// } //// str.SkipWhiteSpaces(); //// if(str.Match( '#' )) //// { //// if(!VerifyValidPunctuation( ref str )) //// { //// result.SetFailure( ParseFailureKind.Format, "Format_BadDateTime", null ); //// return false; //// } //// str.SkipWhiteSpaces(); //// } //// if(str.Match( '\0' )) //// { //// if(!VerifyValidPunctuation( ref str )) //// { //// result.SetFailure( ParseFailureKind.Format, "Format_BadDateTime", null ); //// return false; //// } //// } //// if(str.GetNext()) //// { //// // If this is true, there were non-white space characters remaining in the DateTime //// result.SetFailure( ParseFailureKind.Format, "Format_BadDateTime", null ); //// return false; //// } //// } //// //// DateTime time; //// Calendar calendar = GregorianCalendar.GetDefaultInstance(); //// if(!calendar.TryToDateTime( raw.year, raw.GetNumber( 0 ), raw.GetNumber( 1 ), //// hour, minute, second, 0, result.era, out time )) //// { //// result.SetFailure( ParseFailureKind.FormatBadDateTimeCalendar, "Format_BadDateTimeCalendar", null ); //// return false; //// } //// //// time = time.AddTicks( (long)Math.Round( partSecond * Calendar.TicksPerSecond ) ); //// result.parsedDate = time; //// if(!DetermineTimeZoneAdjustments( ref result, styles, false )) //// { //// return false; //// } //// return true; //// } //// //// //// //////////////////////////////////////////////////////////////////////// //// // //// // Actions: //// // Parse the current word as a Hebrew number. //// // This is used by DateTime.ParseExact(). //// // //// //////////////////////////////////////////////////////////////////////// //// //// internal static bool MatchHebrewDigits( ref __DTString str, int digitLen, out int number ) //// { //// number = 0; //// //// // Create a context object so that we can parse the Hebrew number text character by character. //// HebrewNumberParsingContext context = new HebrewNumberParsingContext( 0 ); //// //// // Set this to ContinueParsing so that we will run the following while loop in the first time. //// HebrewNumberParsingState state = HebrewNumberParsingState.ContinueParsing; //// //// while(state == HebrewNumberParsingState.ContinueParsing && str.GetNext()) //// { //// state = HebrewNumber.ParseByChar( str.GetChar(), ref context ); //// } //// //// if(state == HebrewNumberParsingState.FoundEndOfHebrewNumber) //// { //// // If we have reached a terminal state, update the result and returns. //// number = context.result; //// return (true); //// } //// //// // If we run out of the character before reaching FoundEndOfHebrewNumber, or //// // the state is InvalidHebrewNumber or ContinueParsing, we fail to match a Hebrew number. //// // Return an error. //// return false; //// } //// //// /*=================================ParseDigits================================== //// **Action: Parse the number string in __DTString that are formatted using //// ** the following patterns: //// ** "0", "00", and "000..0" //// **Returns: the integer value //// **Arguments: str: a __DTString. The parsing will start from the //// ** next character after str.Index. //// **Exceptions: FormatException if error in parsing number. //// ==============================================================================*/ //// //// internal static bool ParseDigits( ref __DTString str, int digitLen, out int result ) //// { //// if(digitLen == 1) //// { //// // 1 really means 1 or 2 for this call //// return ParseDigits( ref str, 1, 2, out result ); //// } //// else //// { //// return ParseDigits( ref str, digitLen, digitLen, out result ); //// } //// } //// //// internal static bool ParseDigits( ref __DTString str, int minDigitLen, int maxDigitLen, out int result ) //// { //// BCLDebug.Assert( minDigitLen > 0, "minDigitLen > 0" ); //// BCLDebug.Assert( maxDigitLen < 9, "maxDigitLen < 9" ); //// BCLDebug.Assert( minDigitLen <= maxDigitLen, "minDigitLen <= maxDigitLen" ); //// result = 0; //// int startingIndex = str.Index; //// int tokenLength = 0; //// while(tokenLength < maxDigitLen) //// { //// if(!str.GetNextDigit()) //// { //// str.Index--; //// break; //// } //// result = result * 10 + str.GetDigit(); //// tokenLength++; //// } //// if(tokenLength < minDigitLen) //// { //// str.Index = startingIndex; //// return false; //// } //// return true; //// } //// //// /*=================================ParseFractionExact================================== //// **Action: Parse the number string in __DTString that are formatted using //// ** the following patterns: //// ** "0", "00", and "000..0" //// **Returns: the fraction value //// **Arguments: str: a __DTString. The parsing will start from the //// ** next character after str.Index. //// **Exceptions: FormatException if error in parsing number. //// ==============================================================================*/ //// //// private static bool ParseFractionExact( ref __DTString str, int maxDigitLen, ref double result ) //// { //// if(!str.GetNextDigit()) //// { //// str.Index--; //// return false; //// } //// result = str.GetDigit(); //// //// int digitLen = 1; //// for(; digitLen < maxDigitLen; digitLen++) //// { //// if(!str.GetNextDigit()) //// { //// str.Index--; //// break; //// } //// result = result * 10 + str.GetDigit(); //// } //// //// result = ((double)result / Math.Pow( 10, digitLen )); //// return (digitLen == maxDigitLen); //// } //// //// /*=================================ParseSign================================== //// **Action: Parse a positive or a negative sign. //// **Returns: true if postive sign. flase if negative sign. //// **Arguments: str: a __DTString. The parsing will start from the //// ** next character after str.Index. //// **Exceptions: FormatException if end of string is encountered or a sign //// ** symbol is not found. //// ==============================================================================*/ //// //// private static bool ParseSign( ref __DTString str, ref bool result ) //// { //// if(!str.GetNext()) //// { //// // A sign symbol ('+' or '-') is expected. However, end of string is encountered. //// return false; //// } //// char ch = str.GetChar(); //// if(ch == '+') //// { //// result = true; //// return (true); //// } //// else if(ch == '-') //// { //// result = false; //// return (true); //// } //// // A sign symbol ('+' or '-') is expected. //// return false; //// } //// //// /*=================================ParseTimeZoneOffset================================== //// **Action: Parse the string formatted using "z", "zz", "zzz" in DateTime.Format(). //// **Returns: the TimeSpan for the parsed timezone offset. //// **Arguments: str: a __DTString. The parsing will start from the //// ** next character after str.Index. //// ** len: the repeated number of the "z" //// **Exceptions: FormatException if errors in parsing. //// ==============================================================================*/ //// //// private static bool ParseTimeZoneOffset( ref __DTString str, int len, ref TimeSpan result ) //// { //// bool isPositive = true; //// int hourOffset; //// int minuteOffset = 0; //// //// switch(len) //// { //// case 1: //// case 2: //// if(!ParseSign( ref str, ref isPositive )) //// { //// return (false); //// } //// if(!ParseDigits( ref str, len, out hourOffset )) //// { //// return (false); //// } //// break; //// default: //// if(!ParseSign( ref str, ref isPositive )) //// { //// return (false); //// } //// //// // Parsing 1 digit will actually parse 1 or 2. //// if(!ParseDigits( ref str, 1, out hourOffset )) //// { //// return (false); //// } //// // ':' is optional. //// if(str.Match( ":" )) //// { //// // Found ':' //// if(!ParseDigits( ref str, 2, out minuteOffset )) //// { //// return (false); //// } //// } //// else //// { //// // Since we can not match ':', put the char back. //// str.Index--; //// if(!ParseDigits( ref str, 2, out minuteOffset )) //// { //// return (false); //// } //// } //// break; //// } //// if(minuteOffset < 0 || minuteOffset >= 60) //// { //// return false; //// } //// result = (new TimeSpan( hourOffset, minuteOffset, 0 )); //// if(!isPositive) //// { //// result = result.Negate(); //// } //// return (true); //// } //// //// /*=================================MatchAbbreviatedMonthName================================== //// **Action: Parse the abbreviated month name from string starting at str.Index. //// **Returns: A value from 1 to 12 for the first month to the twelveth month. //// **Arguments: str: a __DTString. The parsing will start from the //// ** next character after str.Index. //// **Exceptions: FormatException if an abbreviated month name can not be found. //// ==============================================================================*/ //// //// private static bool MatchAbbreviatedMonthName( ref __DTString str, DateTimeFormatInfo dtfi, ref int result ) //// { //// int maxMatchStrLen = 0; //// result = -1; //// if(str.GetNext()) //// { //// // //// // Scan the month names (note that some calendars has 13 months) and find //// // the matching month name which has the max string length. //// // We need to do this because some cultures (e.g. "cs-CZ") which have //// // abbreviated month names with the same prefix. //// // //// int monthsInYear = (dtfi.GetMonthName( 13 ).Length == 0 ? 12 : 13); //// for(int i = 1; i <= monthsInYear; i++) //// { //// String searchStr = dtfi.GetAbbreviatedMonthName( i ); //// int matchStrLen = searchStr.Length; //// if(dtfi.HasSpacesInMonthNames //// ? str.MatchSpecifiedWords( searchStr, false, ref matchStrLen ) //// : str.MatchSpecifiedWord( searchStr )) //// { //// if(matchStrLen > maxMatchStrLen) //// { //// maxMatchStrLen = matchStrLen; //// result = i; //// } //// } //// } //// //// // Search leap year form. //// if((dtfi.FormatFlags & DateTimeFormatFlags.UseLeapYearMonth) != 0) //// { //// int tempResult = str.MatchLongestWords( dtfi.internalGetLeapYearMonthNames(), ref maxMatchStrLen ); //// // We found a longer match in the leap year month name. Use this as the result. //// // The result from MatchLongestWords is 0 ~ length of word array. //// // So we increment the result by one to become the month value. //// if(tempResult >= 0) //// { //// result = tempResult + 1; //// } //// } //// //// //// } //// if(result > 0) //// { //// str.Index += (maxMatchStrLen - 1); //// return (true); //// } //// return false; //// } //// //// /*=================================MatchMonthName================================== //// **Action: Parse the month name from string starting at str.Index. //// **Returns: A value from 1 to 12 indicating the first month to the twelveth month. //// **Arguments: str: a __DTString. The parsing will start from the //// ** next character after str.Index. //// **Exceptions: FormatException if a month name can not be found. //// ==============================================================================*/ //// //// private static bool MatchMonthName( ref __DTString str, DateTimeFormatInfo dtfi, ref int result ) //// { //// int maxMatchStrLen = 0; //// result = -1; //// if(str.GetNext()) //// { //// // //// // Scan the month names (note that some calendars has 13 months) and find //// // the matching month name which has the max string length. //// // We need to do this because some cultures (e.g. "vi-VN") which have //// // month names with the same prefix. //// // //// int monthsInYear = (dtfi.GetMonthName( 13 ).Length == 0 ? 12 : 13); //// for(int i = 1; i <= monthsInYear; i++) //// { //// String searchStr = dtfi.GetMonthName( i ); //// int matchStrLen = searchStr.Length; //// if(dtfi.HasSpacesInMonthNames //// ? str.MatchSpecifiedWords( searchStr, false, ref matchStrLen ) //// : str.MatchSpecifiedWord( searchStr )) //// { //// if(matchStrLen > maxMatchStrLen) //// { //// maxMatchStrLen = matchStrLen; //// result = i; //// } //// } //// } //// //// // Search genitive form. //// if((dtfi.FormatFlags & DateTimeFormatFlags.UseGenitiveMonth) != 0) //// { //// int tempResult = str.MatchLongestWords( dtfi.MonthGenitiveNames, ref maxMatchStrLen ); //// // We found a longer match in the genitive month name. Use this as the result. //// // The result from MatchLongestWords is 0 ~ length of word array. //// // So we increment the result by one to become the month value. //// if(tempResult >= 0) //// { //// result = tempResult + 1; //// } //// } //// //// // Search leap year form. //// if((dtfi.FormatFlags & DateTimeFormatFlags.UseLeapYearMonth) != 0) //// { //// int tempResult = str.MatchLongestWords( dtfi.internalGetLeapYearMonthNames(), ref maxMatchStrLen ); //// // We found a longer match in the leap year month name. Use this as the result. //// // The result from MatchLongestWords is 0 ~ length of word array. //// // So we increment the result by one to become the month value. //// if(tempResult >= 0) //// { //// result = tempResult + 1; //// } //// } //// //// //// } //// //// if(result > 0) //// { //// str.Index += (maxMatchStrLen - 1); //// return (true); //// } //// return false; //// } //// //// /*=================================MatchAbbreviatedDayName================================== //// **Action: Parse the abbreviated day of week name from string starting at str.Index. //// **Returns: A value from 0 to 6 indicating Sunday to Saturday. //// **Arguments: str: a __DTString. The parsing will start from the //// ** next character after str.Index. //// **Exceptions: FormatException if a abbreviated day of week name can not be found. //// ==============================================================================*/ //// //// private static bool MatchAbbreviatedDayName( ref __DTString str, DateTimeFormatInfo dtfi, ref int result ) //// { //// int maxMatchStrLen = 0; //// result = -1; //// if(str.GetNext()) //// { //// for(DayOfWeek i = DayOfWeek.Sunday; i <= DayOfWeek.Saturday; i++) //// { //// String searchStr = dtfi.GetAbbreviatedDayName( i ); //// int matchStrLen = searchStr.Length; //// if(dtfi.HasSpacesInDayNames //// ? str.MatchSpecifiedWords( searchStr, false, ref matchStrLen ) //// : str.MatchSpecifiedWord( searchStr )) //// { //// if(matchStrLen > maxMatchStrLen) //// { //// maxMatchStrLen = matchStrLen; //// result = (int)i; //// } //// } //// } //// } //// if(result >= 0) //// { //// str.Index += maxMatchStrLen - 1; //// return (true); //// } //// return false; //// } //// //// /*=================================MatchDayName================================== //// **Action: Parse the day of week name from string starting at str.Index. //// **Returns: A value from 0 to 6 indicating Sunday to Saturday. //// **Arguments: str: a __DTString. The parsing will start from the //// ** next character after str.Index. //// **Exceptions: FormatException if a day of week name can not be found. //// ==============================================================================*/ //// //// private static bool MatchDayName( ref __DTString str, DateTimeFormatInfo dtfi, ref int result ) //// { //// // Turkish (tr-TR) got day names with the same prefix. //// int maxMatchStrLen = 0; //// result = -1; //// if(str.GetNext()) //// { //// for(DayOfWeek i = DayOfWeek.Sunday; i <= DayOfWeek.Saturday; i++) //// { //// String searchStr = dtfi.GetDayName( i ); //// int matchStrLen = searchStr.Length; //// if(dtfi.HasSpacesInDayNames //// ? str.MatchSpecifiedWords( searchStr, false, ref matchStrLen ) //// : str.MatchSpecifiedWord( searchStr )) //// { //// if(matchStrLen > maxMatchStrLen) //// { //// maxMatchStrLen = matchStrLen; //// result = (int)i; //// } //// } //// } //// } //// if(result >= 0) //// { //// str.Index += maxMatchStrLen - 1; //// return (true); //// } //// return false; //// } //// //// /*=================================MatchEraName================================== //// **Action: Parse era name from string starting at str.Index. //// **Returns: An era value. //// **Arguments: str: a __DTString. The parsing will start from the //// ** next character after str.Index. //// **Exceptions: FormatException if an era name can not be found. //// ==============================================================================*/ //// //// private static bool MatchEraName( ref __DTString str, DateTimeFormatInfo dtfi, ref int result ) //// { //// if(str.GetNext()) //// { //// int[] eras = dtfi.Calendar.Eras; //// //// if(eras != null) //// { //// for(int i = 0; i < eras.Length; i++) //// { //// String searchStr = dtfi.GetEraName( eras[i] ); //// if(str.MatchSpecifiedWord( searchStr )) //// { //// str.Index += (searchStr.Length - 1); //// result = eras[i]; //// return (true); //// } //// searchStr = dtfi.GetAbbreviatedEraName( eras[i] ); //// if(str.MatchSpecifiedWord( searchStr )) //// { //// str.Index += (searchStr.Length - 1); //// result = eras[i]; //// return (true); //// } //// } //// } //// } //// return false; //// } //// //// /*=================================MatchTimeMark================================== //// **Action: Parse the time mark (AM/PM) from string starting at str.Index. //// **Returns: TM_AM or TM_PM. //// **Arguments: str: a __DTString. The parsing will start from the //// ** next character after str.Index. //// **Exceptions: FormatException if a time mark can not be found. //// ==============================================================================*/ //// //// private static bool MatchTimeMark( ref __DTString str, DateTimeFormatInfo dtfi, ref TM result ) //// { //// result = TM.NotSet; //// // In some cultures have empty strings in AM/PM mark. E.g. af-ZA (0x0436), the AM mark is "", and PM mark is "nm". //// if(dtfi.AMDesignator.Length == 0) //// { //// result = TM.AM; //// } //// if(dtfi.PMDesignator.Length == 0) //// { //// result = TM.PM; //// } //// //// if(str.GetNext()) //// { //// String searchStr = dtfi.AMDesignator; //// if(searchStr.Length > 0) //// { //// if(str.MatchSpecifiedWord( searchStr )) //// { //// // Found an AM timemark with length > 0. //// str.Index += (searchStr.Length - 1); //// result = TM.AM; //// return (true); //// } //// } //// searchStr = dtfi.PMDesignator; //// if(searchStr.Length > 0) //// { //// if(str.MatchSpecifiedWord( searchStr )) //// { //// // Found a PM timemark with length > 0. //// str.Index += (searchStr.Length - 1); //// result = TM.PM; //// return (true); //// } //// } //// str.Index--; // Undo the GetNext call. //// } //// if(result != TM.NotSet) //// { //// // If one of the AM/PM marks is empty string, return the result. //// return (true); //// } //// return false; //// } //// //// /*=================================MatchAbbreviatedTimeMark================================== //// **Action: Parse the abbreviated time mark (AM/PM) from string starting at str.Index. //// **Returns: TM_AM or TM_PM. //// **Arguments: str: a __DTString. The parsing will start from the //// ** next character after str.Index. //// **Exceptions: FormatException if a abbreviated time mark can not be found. //// ==============================================================================*/ //// //// private static bool MatchAbbreviatedTimeMark( ref __DTString str, DateTimeFormatInfo dtfi, ref TM result ) //// { //// // NOTENOTE : the assumption here is that abbreviated time mark is the first //// // character of the AM/PM designator. If this invariant changes, we have to //// // change the code below. //// if(str.GetNext()) //// { //// if(str.GetChar() == dtfi.AMDesignator[0]) //// { //// result = TM.AM; //// return (true); //// } //// if(str.GetChar() == dtfi.PMDesignator[0]) //// { //// result = TM.PM; //// return (true); //// } //// } //// return false; //// } //// //// /*=================================CheckNewValue================================== //// **Action: Check if currentValue is initialized. If not, return the newValue. //// ** If yes, check if the current value is equal to newValue. Return false //// ** if they are not equal. This is used to check the case like "d" and "dd" are both //// ** used to format a string. //// **Returns: the correct value for currentValue. //// **Arguments: //// **Exceptions: //// ==============================================================================*/ //// //// private static bool CheckNewValue( ref int currentValue, int newValue, char patternChar, ref DateTimeResult result ) //// { //// if(currentValue == -1) //// { //// currentValue = newValue; //// return (true); //// } //// else //// { //// if(newValue != currentValue) //// { //// result.SetFailure( ParseFailureKind.FormatWithParameter, "Format_RepeatDateTimePattern", patternChar ); //// return (false); //// } //// } //// return (true); //// } //// //// private static void CheckDefaultDateTime( ref DateTimeResult result, ref Calendar cal, DateTimeStyles styles ) //// { //// //// if((result.Year == -1) || (result.Month == -1) || (result.Day == -1)) //// { //// /* //// The following table describes the behaviors of getting the default value //// when a certain year/month/day values are missing. //// //// An "X" means that the value exists. And "--" means that value is missing. //// //// Year Month Day => ResultYear ResultMonth ResultDay Note //// //// X X X Parsed year Parsed month Parsed day //// X X -- Parsed Year Parsed month First day If we have year and month, assume the first day of that month. //// X -- X Parsed year First month Parsed day If the month is missing, assume first month of that year. //// X -- -- Parsed year First month First day If we have only the year, assume the first day of that year. //// //// -- X X CurrentYear Parsed month Parsed day If the year is missing, assume the current year. //// -- X -- CurrentYear Parsed month First day If we have only a month value, assume the current year and current day. //// -- -- X CurrentYear First month Parsed day If we have only a day value, assume current year and first month. //// -- -- -- CurrentYear Current month Current day So this means that if the date string only contains time, you will get current date. //// //// */ //// //// DateTime now = DateTime.Now; //// if(result.Month == -1 && result.Day == -1) //// { //// if(result.Year == -1) //// { //// if((styles & DateTimeStyles.NoCurrentDateDefault) != 0) //// { //// // If there is no year/month/day values, and NoCurrentDateDefault flag is used, //// // set the year/month/day value to the beginning year/month/day of DateTime(). //// // Note we should be using Gregorian for the year/month/day. //// cal = GregorianCalendar.GetDefaultInstance(); //// result.Year = result.Month = result.Day = 1; //// } //// else //// { //// // Year/Month/Day are all missing. //// result.Year = cal.GetYear( now ); //// result.Month = cal.GetMonth( now ); //// result.Day = cal.GetDayOfMonth( now ); //// } //// } //// else //// { //// // Month/Day are both missing. //// result.Month = 1; //// result.Day = 1; //// } //// } //// else //// { //// if(result.Year == -1) //// { //// result.Year = cal.GetYear( now ); //// } //// if(result.Month == -1) //// { //// result.Month = 1; //// } //// if(result.Day == -1) //// { //// result.Day = 1; //// } //// } //// } //// // Set Hour/Minute/Second to zero if these value are not in str. //// if(result.Hour == -1) result.Hour = 0; //// if(result.Minute == -1) result.Minute = 0; //// if(result.Second == -1) result.Second = 0; //// if(result.era == -1) result.era = Calendar.CurrentEra; //// } //// //// // Expand a pre-defined format string (like "D" for long date) to the real format that //// // we are going to use in the date time parsing. //// // This method also set the dtfi according/parseInfo to some special pre-defined //// // formats. //// // //// private static String ExpandPredefinedFormat( String format, ref DateTimeFormatInfo dtfi, ref ParsingInfo parseInfo, ref DateTimeResult result ) //// { //// // //// // Check the format to see if we need to override the dtfi to be InvariantInfo, //// // and see if we need to set up the userUniversalTime flag. //// // //// switch(format[0]) //// { //// case 'o': //// case 'O': // Round Trip Format //// parseInfo.calendar = GregorianCalendar.GetDefaultInstance(); //// dtfi = DateTimeFormatInfo.InvariantInfo; //// break; //// case 'r': //// case 'R': // RFC 1123 Standard. (in Universal time) //// parseInfo.calendar = GregorianCalendar.GetDefaultInstance(); //// dtfi = DateTimeFormatInfo.InvariantInfo; //// break; //// case 's': // Sortable format (in local time) //// dtfi = DateTimeFormatInfo.InvariantInfo; //// parseInfo.calendar = GregorianCalendar.GetDefaultInstance(); //// break; //// case 'u': // Universal time format in sortable format. //// parseInfo.calendar = GregorianCalendar.GetDefaultInstance(); //// dtfi = DateTimeFormatInfo.InvariantInfo; //// break; //// case 'U': // Universal time format with culture-dependent format. //// parseInfo.calendar = GregorianCalendar.GetDefaultInstance(); //// result.flags |= ParseFlags.TimeZoneUsed; //// result.timeZoneOffset = new TimeSpan( 0 ); //// result.flags |= ParseFlags.TimeZoneUtc; //// if(dtfi.Calendar.GetType() != typeof( GregorianCalendar )) //// { //// dtfi = (DateTimeFormatInfo)dtfi.Clone(); //// dtfi.Calendar = GregorianCalendar.GetDefaultInstance(); //// } //// break; //// } //// //// // //// // Expand the pre-defined format character to the real format from DateTimeFormatInfo. //// // //// return (DateTimeFormat.GetRealFormat( format, dtfi )); //// } //// //// // Given a specified format character, parse and update the parsing result. //// // //// private static bool ParseByFormat( //// ref __DTString str, //// ref __DTString format, //// ref ParsingInfo parseInfo, //// DateTimeFormatInfo dtfi, //// ref DateTimeResult result ) //// { //// //// int tokenLen = 0; //// int tempYear = 0, tempMonth = 0, tempDay = 0, tempDayOfWeek = 0, tempHour = 0, tempMinute = 0, tempSecond = 0; //// double tempFraction = 0; //// TM tempTimeMark = 0; //// //// char ch = format.GetChar(); //// //// switch(ch) //// { //// case 'y': //// tokenLen = format.GetRepeatCount(); //// bool parseResult; //// if(dtfi.HasForceTwoDigitYears) //// { //// parseResult = ParseDigits( ref str, 1, 4, out tempYear ); //// } //// else //// { //// if(tokenLen <= 2) //// { //// parseInfo.fUseTwoDigitYear = true; //// } //// parseResult = ParseDigits( ref str, tokenLen, out tempYear ); //// } //// if(!parseResult && parseInfo.fCustomNumberParser) //// { //// parseResult = parseInfo.parseNumberDelegate( ref str, tokenLen, out tempYear ); //// } //// if(!parseResult) //// { //// result.SetFailure( ParseFailureKind.Format, "Format_BadDateTime", null ); //// return (false); //// } //// if(!CheckNewValue( ref result.Year, tempYear, ch, ref result )) //// { //// return (false); //// } //// break; //// case 'M': //// tokenLen = format.GetRepeatCount(); //// if(tokenLen <= 2) //// { //// if(!ParseDigits( ref str, tokenLen, out tempMonth )) //// { //// if(!parseInfo.fCustomNumberParser || //// !parseInfo.parseNumberDelegate( ref str, tokenLen, out tempMonth )) //// { //// result.SetFailure( ParseFailureKind.Format, "Format_BadDateTime", null ); //// return (false); //// } //// } //// } //// else //// { //// if(tokenLen == 3) //// { //// if(!MatchAbbreviatedMonthName( ref str, dtfi, ref tempMonth )) //// { //// result.SetFailure( ParseFailureKind.Format, "Format_BadDateTime", null ); //// return (false); //// } //// } //// else //// { //// if(!MatchMonthName( ref str, dtfi, ref tempMonth )) //// { //// result.SetFailure( ParseFailureKind.Format, "Format_BadDateTime", null ); //// return (false); //// } //// } //// result.flags |= ParseFlags.ParsedMonthName; //// } //// if(!CheckNewValue( ref result.Month, tempMonth, ch, ref result )) //// { //// return (false); //// } //// break; //// case 'd': //// // Day & Day of week //// tokenLen = format.GetRepeatCount(); //// if(tokenLen <= 2) //// { //// // "d" & "dd" //// //// if(!ParseDigits( ref str, tokenLen, out tempDay )) //// { //// if(!parseInfo.fCustomNumberParser || //// !parseInfo.parseNumberDelegate( ref str, tokenLen, out tempDay )) //// { //// result.SetFailure( ParseFailureKind.Format, "Format_BadDateTime", null ); //// return (false); //// } //// } //// if(!CheckNewValue( ref result.Day, tempDay, ch, ref result )) //// { //// return (false); //// } //// } //// else //// { //// if(tokenLen == 3) //// { //// // "ddd" //// if(!MatchAbbreviatedDayName( ref str, dtfi, ref tempDayOfWeek )) //// { //// result.SetFailure( ParseFailureKind.Format, "Format_BadDateTime", null ); //// return (false); //// } //// } //// else //// { //// // "dddd*" //// if(!MatchDayName( ref str, dtfi, ref tempDayOfWeek )) //// { //// result.SetFailure( ParseFailureKind.Format, "Format_BadDateTime", null ); //// return (false); //// } //// } //// if(!CheckNewValue( ref parseInfo.dayOfWeek, tempDayOfWeek, ch, ref result )) //// { //// return (false); //// } //// } //// break; //// case 'g': //// tokenLen = format.GetRepeatCount(); //// // Put the era value in result.era. //// if(!MatchEraName( ref str, dtfi, ref result.era )) //// { //// result.SetFailure( ParseFailureKind.Format, "Format_BadDateTime", null ); //// return (false); //// } //// break; //// case 'h': //// parseInfo.fUseHour12 = true; //// tokenLen = format.GetRepeatCount(); //// if(!ParseDigits( ref str, (tokenLen < 2 ? 1 : 2), out tempHour )) //// { //// result.SetFailure( ParseFailureKind.Format, "Format_BadDateTime", null ); //// return (false); //// } //// if(!CheckNewValue( ref result.Hour, tempHour, ch, ref result )) //// { //// return (false); //// } //// break; //// case 'H': //// tokenLen = format.GetRepeatCount(); //// if(!ParseDigits( ref str, (tokenLen < 2 ? 1 : 2), out tempHour )) //// { //// result.SetFailure( ParseFailureKind.Format, "Format_BadDateTime", null ); //// return (false); //// } //// if(!CheckNewValue( ref result.Hour, tempHour, ch, ref result )) //// { //// return (false); //// } //// break; //// case 'm': //// tokenLen = format.GetRepeatCount(); //// if(!ParseDigits( ref str, (tokenLen < 2 ? 1 : 2), out tempMinute )) //// { //// result.SetFailure( ParseFailureKind.Format, "Format_BadDateTime", null ); //// return (false); //// } //// if(!CheckNewValue( ref result.Minute, tempMinute, ch, ref result )) //// { //// return (false); //// } //// break; //// case 's': //// tokenLen = format.GetRepeatCount(); //// if(!ParseDigits( ref str, (tokenLen < 2 ? 1 : 2), out tempSecond )) //// { //// result.SetFailure( ParseFailureKind.Format, "Format_BadDateTime", null ); //// return (false); //// } //// if(!CheckNewValue( ref result.Second, tempSecond, ch, ref result )) //// { //// return (false); //// } //// break; //// case 'f': //// case 'F': //// tokenLen = format.GetRepeatCount(); //// if(tokenLen <= DateTimeFormat.MaxSecondsFractionDigits) //// { //// if(!ParseFractionExact( ref str, tokenLen, ref tempFraction )) //// { //// if(ch == 'f') //// { //// result.SetFailure( ParseFailureKind.Format, "Format_BadDateTime", null ); //// return (false); //// } //// } //// if(result.fraction < 0) //// { //// result.fraction = tempFraction; //// } //// else //// { //// if(tempFraction != result.fraction) //// { //// result.SetFailure( ParseFailureKind.FormatWithParameter, "Format_RepeatDateTimePattern", ch ); //// return (false); //// } //// } //// } //// else //// { //// result.SetFailure( ParseFailureKind.Format, "Format_BadDateTime", null ); //// return (false); //// } //// break; //// case 't': //// // AM/PM designator //// tokenLen = format.GetRepeatCount(); //// if(tokenLen == 1) //// { //// if(!MatchAbbreviatedTimeMark( ref str, dtfi, ref tempTimeMark )) //// { //// result.SetFailure( ParseFailureKind.Format, "Format_BadDateTime", null ); //// return (false); //// } //// } //// else //// { //// if(!MatchTimeMark( ref str, dtfi, ref tempTimeMark )) //// { //// result.SetFailure( ParseFailureKind.Format, "Format_BadDateTime", null ); //// return (false); //// } //// } //// //// if(parseInfo.timeMark == TM.NotSet) //// { //// parseInfo.timeMark = tempTimeMark; //// } //// else //// { //// if(parseInfo.timeMark != tempTimeMark) //// { //// result.SetFailure( ParseFailureKind.FormatWithParameter, "Format_RepeatDateTimePattern", ch ); //// return (false); //// } //// } //// break; //// case 'z': //// // timezone offset //// tokenLen = format.GetRepeatCount(); //// { //// TimeSpan tempTimeZoneOffset = new TimeSpan( 0 ); //// if(!ParseTimeZoneOffset( ref str, tokenLen, ref tempTimeZoneOffset )) //// { //// result.SetFailure( ParseFailureKind.Format, "Format_BadDateTime", null ); //// return (false); //// } //// if((result.flags & ParseFlags.TimeZoneUsed) != 0 && tempTimeZoneOffset != result.timeZoneOffset) //// { //// result.SetFailure( ParseFailureKind.FormatWithParameter, "Format_RepeatDateTimePattern", 'z' ); //// return (false); //// } //// result.timeZoneOffset = tempTimeZoneOffset; //// result.flags |= ParseFlags.TimeZoneUsed; //// } //// break; //// case 'Z': //// if((result.flags & ParseFlags.TimeZoneUsed) != 0 && result.timeZoneOffset != TimeSpan.Zero) //// { //// result.SetFailure( ParseFailureKind.FormatWithParameter, "Format_RepeatDateTimePattern", 'Z' ); //// return (false); //// } //// result.flags |= ParseFlags.TimeZoneUsed; //// result.timeZoneOffset = new TimeSpan( 0 ); //// result.flags |= ParseFlags.TimeZoneUtc; //// //// // The updating of the indexes is to reflect that ParseExact MatchXXX methods assume that //// // they need to increment the index and Parse GetXXX do not. Since we are calling a Parse //// // method from inside ParseExact we need to adjust this. Long term, we should try to //// // eliminate this discrepancy. //// str.Index++; //// if(!GetTimeZoneName( ref str )) //// { //// result.SetFailure( ParseFailureKind.Format, "Format_BadDateTime", null ); //// return false; //// } //// str.Index--; //// break; //// case 'K': //// // This should parse either as a blank, the 'Z' character or a local offset like "-07:00" //// if(str.Match( 'Z' )) //// { //// if((result.flags & ParseFlags.TimeZoneUsed) != 0 && result.timeZoneOffset != TimeSpan.Zero) //// { //// result.SetFailure( ParseFailureKind.FormatWithParameter, "Format_RepeatDateTimePattern", 'K' ); //// return (false); //// } //// result.flags |= ParseFlags.TimeZoneUsed; //// result.timeZoneOffset = new TimeSpan( 0 ); //// result.flags |= ParseFlags.TimeZoneUtc; //// } //// else if(str.Match( '+' ) || str.Match( '-' )) //// { //// str.Index--; // Put the character back for the parser //// TimeSpan tempTimeZoneOffset = new TimeSpan( 0 ); //// if(!ParseTimeZoneOffset( ref str, 3, ref tempTimeZoneOffset )) //// { //// result.SetFailure( ParseFailureKind.Format, "Format_BadDateTime", null ); //// return (false); //// } //// if((result.flags & ParseFlags.TimeZoneUsed) != 0 && tempTimeZoneOffset != result.timeZoneOffset) //// { //// result.SetFailure( ParseFailureKind.FormatWithParameter, "Format_RepeatDateTimePattern", 'K' ); //// return (false); //// } //// result.timeZoneOffset = tempTimeZoneOffset; //// result.flags |= ParseFlags.TimeZoneUsed; //// } //// // Otherwise it is unspecified and we consume no characters //// break; //// case ':': //// if(!str.Match( dtfi.TimeSeparator )) //// { //// // A time separator is expected. //// result.SetFailure( ParseFailureKind.Format, "Format_BadDateTime", null ); //// return false; //// } //// break; //// case '/': //// if(!str.Match( dtfi.DateSeparator )) //// { //// // A date separator is expected. //// result.SetFailure( ParseFailureKind.Format, "Format_BadDateTime", null ); //// return false; //// } //// break; //// case '\"': //// case '\'': //// StringBuilder enquotedString = new StringBuilder(); //// // Use ParseQuoteString so that we can handle escape characters within the quoted string. //// if(!TryParseQuoteString( format.Value, format.Index, enquotedString, out tokenLen )) //// { //// result.SetFailure( ParseFailureKind.FormatWithParameter, "Format_BadQuote", ch ); //// return (false); //// } //// format.Index += tokenLen - 1; //// //// // Some cultures uses space in the quoted string. E.g. Spanish has long date format as: //// // "dddd, dd' de 'MMMM' de 'yyyy". When inner spaces flag is set, we should skip whitespaces if there is space //// // in the quoted string. //// String quotedStr = enquotedString.ToString(); //// for(int i = 0; i < quotedStr.Length; i++) //// { //// if(quotedStr[i] == ' ' && parseInfo.fAllowInnerWhite) //// { //// str.SkipWhiteSpaces(); //// } //// else if(!str.Match( quotedStr[i] )) //// { //// // Can not find the matching quoted string. //// result.SetFailure( ParseFailureKind.Format, "Format_BadDateTime", null ); //// return false; //// } //// } //// break; //// case '%': //// // Skip this so we can get to the next pattern character. //// // Used in case like "%d", "%y" //// //// // Make sure the next character is not a '%' again. //// if(format.Index >= format.Value.Length - 1 || format.Value[format.Index + 1] == '%') //// { //// result.SetFailure( ParseFailureKind.Format, "Argument_BadFormatSpecifier", null ); //// return false; //// } //// break; //// case '\\': //// // Escape character. For example, "\d". //// // Get the next character in format, and see if we can //// // find a match in str. //// if(format.GetNext()) //// { //// if(!str.Match( format.GetChar() )) //// { //// // Can not find a match for the escaped character. //// result.SetFailure( ParseFailureKind.Format, "Format_BadDateTime", null ); //// return false; //// } //// } //// else //// { //// result.SetFailure( ParseFailureKind.Format, "Argument_BadFormatSpecifier", null ); //// return false; //// } //// break; //// case '.': //// if(!str.Match( ch )) //// { //// if(format.GetNext()) //// { //// // If we encounter the pattern ".F", and the dot is not present, it is an optional //// // second fraction and we can skip this format. //// if(format.Match( 'F' )) //// { //// format.GetRepeatCount(); //// break; //// } //// } //// result.SetFailure( ParseFailureKind.Format, "Format_BadDateTime", null ); //// return false; //// } //// break; //// default: //// if(ch == ' ') //// { //// if(parseInfo.fAllowInnerWhite) //// { //// // Skip whitespaces if AllowInnerWhite. //// // Do nothing here. //// } //// else //// { //// if(!str.Match( ch )) //// { //// // If the space does not match, and trailing space is allowed, we do //// // one more step to see if the next format character can lead to //// // successful parsing. //// // This is used to deal with special case that a empty string can match //// // a specific pattern. //// // The example here is af-ZA, which has a time format like "hh:mm:ss tt". However, //// // its AM symbol is "" (empty string). If fAllowTrailingWhite is used, and time is in //// // the AM, we will trim the whitespaces at the end, which will lead to a failure //// // when we are trying to match the space before "tt". //// if(parseInfo.fAllowTrailingWhite) //// { //// if(format.GetNext()) //// { //// if(ParseByFormat( ref str, ref format, ref parseInfo, dtfi, ref result )) //// { //// return (true); //// } //// } //// } //// result.SetFailure( ParseFailureKind.Format, "Format_BadDateTime", null ); //// return false; //// } //// // Found a macth. //// } //// } //// else //// { //// if(format.MatchSpecifiedWord( GMTName )) //// { //// format.Index += (GMTName.Length - 1); //// // Found GMT string in format. This means the DateTime string //// // is in GMT timezone. //// result.flags |= ParseFlags.TimeZoneUsed; //// result.timeZoneOffset = TimeSpan.Zero; //// if(!str.Match( GMTName )) //// { //// result.SetFailure( ParseFailureKind.Format, "Format_BadDateTime", null ); //// return false; //// } //// } //// else if(!str.Match( ch )) //// { //// // ch is expected. //// result.SetFailure( ParseFailureKind.Format, "Format_BadDateTime", null ); //// return false; //// } //// } //// break; //// } // switch //// return (true); //// } //// //// // //// // The pos should point to a quote character. This method will //// // get the string encloed by the quote character. //// // //// internal static bool TryParseQuoteString( String format, int pos, StringBuilder result, out int returnValue ) //// { //// // //// // NOTE : pos will be the index of the quote character in the 'format' string. //// // //// returnValue = 0; //// int formatLen = format.Length; //// int beginPos = pos; //// char quoteChar = format[pos++]; // Get the character used to quote the following string. //// //// bool foundQuote = false; //// while(pos < formatLen) //// { //// char ch = format[pos++]; //// if(ch == quoteChar) //// { //// foundQuote = true; //// break; //// } //// else if(ch == '\\') //// { //// // The following are used to support escaped character. //// // Escaped character is also supported in the quoted string. //// // Therefore, someone can use a format like "'minute:' mm\"" to display: //// // minute: 45" //// // because the second double quote is escaped. //// if(pos < formatLen) //// { //// result.Append( format[pos++] ); //// } //// else //// { //// // //// // This means that '\' is at the end of the formatting string. //// // //// return false; //// } //// } //// else //// { //// result.Append( ch ); //// } //// } //// //// if(!foundQuote) //// { //// // Here we can't find the matching quote. //// return false; //// } //// //// // //// // Return the character count including the begin/end quote characters and enclosed string. //// // //// returnValue = (pos - beginPos); //// return true; //// } //// //// //// /*=================================DoStrictParse================================== //// **Action: Do DateTime parsing using the format in formatParam. //// **Returns: The parsed DateTime. //// **Arguments: //// **Exceptions: //// ** //// **Notes: //// ** When the following general formats are used, InvariantInfo is used in dtfi: //// ** 'r', 'R', 's'. //// ** When the following general formats are used, the time is assumed to be in Universal time. //// ** //// **Limitations: //// ** Only GregarianCalendar is supported for now. //// ** Only support GMT timezone. //// ==============================================================================*/ //// //// private static bool DoStrictParse( //// String s, //// String formatParam, //// DateTimeStyles styles, //// DateTimeFormatInfo dtfi, //// ref DateTimeResult result ) //// { //// //// bool bTimeOnly = false; //// ParsingInfo parseInfo = new ParsingInfo(); //// parseInfo.Init(); //// //// parseInfo.calendar = dtfi.Calendar; //// parseInfo.fAllowInnerWhite = ((styles & DateTimeStyles.AllowInnerWhite) != 0); //// parseInfo.fAllowTrailingWhite = ((styles & DateTimeStyles.AllowTrailingWhite) != 0); //// //// if(formatParam.Length == 1) //// { //// formatParam = ExpandPredefinedFormat( formatParam, ref dtfi, ref parseInfo, ref result ); //// } //// result.calendar = parseInfo.calendar; //// //// if(parseInfo.calendar.ID == Calendar.CAL_HEBREW) //// { //// parseInfo.parseNumberDelegate = m_hebrewNumberParser; //// parseInfo.fCustomNumberParser = true; //// } //// //// // Reset these values to negative one so that we could throw exception //// // if we have parsed every item twice. //// result.Hour = result.Minute = result.Second = -1; //// //// __DTString format = new __DTString( formatParam, dtfi, false ); //// __DTString str = new __DTString( s, dtfi, false ); //// //// if(parseInfo.fAllowTrailingWhite) //// { //// // Trim trailing spaces if AllowTrailingWhite. //// format.TrimTail(); //// format.RemoveTrailingInQuoteSpaces(); //// str.TrimTail(); //// } //// //// if((styles & DateTimeStyles.AllowLeadingWhite) != 0) //// { //// format.SkipWhiteSpaces(); //// format.RemoveLeadingInQuoteSpaces(); //// str.SkipWhiteSpaces(); //// } //// //// // //// // Scan every character in format and match the pattern in str. //// // //// while(format.GetNext()) //// { //// // We trim inner spaces here, so that we will not eat trailing spaces when //// // AllowTrailingWhite is not used. //// if(parseInfo.fAllowInnerWhite) //// { //// str.SkipWhiteSpaces(); //// } //// if(!ParseByFormat( ref str, ref format, ref parseInfo, dtfi, ref result )) //// { //// return (false); //// } //// } //// if(str.Index < str.Value.Length - 1) //// { //// // There are still remaining character in str. //// result.SetFailure( ParseFailureKind.Format, "Format_BadDateTime", null ); //// return false; //// } //// //// if(parseInfo.fUseTwoDigitYear && ((dtfi.FormatFlags & DateTimeFormatFlags.UseHebrewRule) == 0)) //// { //// // A two digit year value is expected. Check if the parsed year value is valid. //// if(result.Year >= 100) //// { //// result.SetFailure( ParseFailureKind.Format, "Format_BadDateTime", null ); //// return false; //// } //// result.Year = parseInfo.calendar.ToFourDigitYear( result.Year ); //// } //// //// if(parseInfo.fUseHour12) //// { //// if(parseInfo.timeMark == TM.NotSet) //// { //// // hh is used, but no AM/PM designator is specified. //// // Assume the time is AM. //// // Don't throw exceptions in here becasue it is very confusing for the caller. //// // I always got confused myself when I use "hh:mm:ss" to parse a time string, //// // and ParseExact() throws on me (because I didn't use the 24-hour clock 'HH'). //// parseInfo.timeMark = TM.AM; //// } //// if(result.Hour > 12) //// { //// // AM/PM is used, but the value for HH is too big. //// result.SetFailure( ParseFailureKind.Format, "Format_BadDateTime", null ); //// return false; //// } //// if(parseInfo.timeMark == TM.AM) //// { //// if(result.Hour == 12) //// { //// result.Hour = 0; //// } //// } //// else //// { //// result.Hour = (result.Hour == 12) ? 12 : result.Hour + 12; //// } //// } //// //// // Check if the parased string only contains hour/minute/second values. //// bTimeOnly = (result.Year == -1 && result.Month == -1 && result.Day == -1); //// CheckDefaultDateTime( ref result, ref parseInfo.calendar, styles ); //// //// if(!bTimeOnly && dtfi.HasYearMonthAdjustment) //// { //// if(!dtfi.YearMonthAdjustment( ref result.Year, ref result.Month, ((result.flags & ParseFlags.ParsedMonthName) != 0) )) //// { //// result.SetFailure( ParseFailureKind.FormatBadDateTimeCalendar, "Format_BadDateTimeCalendar", null ); //// return false; //// } //// } //// if(!parseInfo.calendar.TryToDateTime( result.Year, result.Month, result.Day, //// result.Hour, result.Minute, result.Second, 0, result.era, out result.parsedDate )) //// { //// result.SetFailure( ParseFailureKind.FormatBadDateTimeCalendar, "Format_BadDateTimeCalendar", null ); //// return false; //// } //// if(result.fraction > 0) //// { //// result.parsedDate = result.parsedDate.AddTicks( (long)Math.Round( result.fraction * Calendar.TicksPerSecond ) ); //// } //// //// // //// // We have to check day of week before we adjust to the time zone. //// // It is because the value of day of week may change after adjusting //// // to the time zone. //// // //// if(parseInfo.dayOfWeek != -1) //// { //// // //// // Check if day of week is correct. //// // //// if(parseInfo.dayOfWeek != (int)parseInfo.calendar.GetDayOfWeek( result.parsedDate )) //// { //// result.SetFailure( ParseFailureKind.Format, "Format_BadDayOfWeek", null ); //// return false; //// } //// } //// //// //// if(!DetermineTimeZoneAdjustments( ref result, styles, bTimeOnly )) //// { //// return false; //// } //// return true; //// } //// //// private static Exception GetDateTimeParseException( ref DateTimeResult result ) //// { //// switch(result.failure) //// { //// case ParseFailureKind.ArgumentNull: //// return new ArgumentNullException( result.failureArgumentName, Environment.GetResourceString( result.failureMessageID ) ); //// case ParseFailureKind.Format: //// return new FormatException( Environment.GetResourceString( result.failureMessageID ) ); //// case ParseFailureKind.FormatWithParameter: //// return new FormatException( Environment.GetResourceString( result.failureMessageID, result.failureMessageFormatArgument ) ); //// case ParseFailureKind.FormatBadDateTimeCalendar: //// return new FormatException( Environment.GetResourceString( result.failureMessageID, result.calendar ) ); //// default: //// BCLDebug.Assert( false, "Unkown DateTimeParseFailure: " + result ); //// return null; //// //// } //// } } ////// ////// This is a string parsing helper which wraps a String object. ////// It has a Index property which tracks ////// the current parsing pointer of the string. ////// ////internal struct __DTString ////{ //// //// // //// // Value propery: stores the real string to be parsed. //// // //// internal String Value; //// //// // //// // Index property: points to the character that we are currently parsing. //// // //// internal int Index; //// //// // The length of Value string. //// internal int len; //// //// // The current chracter to be looked at. //// internal char m_current; //// //// private CompareInfo m_info; //// // Flag to indicate if we encouter an digit, we should check for token or not. //// // In some cultures, such as mn-MN, it uses "\x0031\x00a0\x0434\x04af\x0433\x044d\x044d\x0440\x00a0\x0441\x0430\x0440" in month names. //// private bool m_checkDigitToken; //// //// internal __DTString( String str, DateTimeFormatInfo dtfi, bool checkDigitToken ) //// : this( str, dtfi ) //// { //// m_checkDigitToken = checkDigitToken; //// } //// //// internal __DTString( String str, DateTimeFormatInfo dtfi ) //// { //// Index = -1; //// Value = str; //// len = Value.Length; //// //// m_current = '\0'; //// if(dtfi != null) //// { //// m_info = dtfi.CompareInfo; //// m_checkDigitToken = ((dtfi.FormatFlags & DateTimeFormatFlags.UseDigitPrefixInTokens) != 0); //// } //// else //// { //// m_info = Thread.CurrentThread.CurrentCulture.CompareInfo; //// m_checkDigitToken = false; //// } //// } //// //// internal CompareInfo CompareInfo //// { //// get { return m_info; } //// } //// //// // //// // Advance the Index. //// // Return true if Index is NOT at the end of the string. //// // //// // Typical usage: //// // while (str.GetNext()) //// // { //// // char ch = str.GetChar() //// // } //// internal bool GetNext() //// { //// Index++; //// if(Index < len) //// { //// m_current = Value[Index]; //// return (true); //// } //// return (false); //// } //// //// internal bool Advance( int count ) //// { //// BCLDebug.Assert( Index + count <= len, "__DTString::Advance: Index + count <= len" ); //// Index += count; //// if(Index < len) //// { //// m_current = Value[Index]; //// return (true); //// } //// return (false); //// } //// //// //// // Used by DateTime.Parse() to get the next token. //// internal void GetRegularToken( out TokenType tokenType, out int tokenValue, DateTimeFormatInfo dtfi ) //// { //// tokenValue = 0; //// if(Index >= len) //// { //// tokenType = TokenType.EndOfString; //// return; //// } //// //// tokenType = TokenType.UnknownToken; //// //// Start: //// if(DateTimeParse.IsDigit( m_current )) //// { //// // This is a digit. //// tokenValue = m_current - '0'; //// int value; //// int start = Index; //// //// // //// // Collect other digits. //// // //// while(++Index < len) //// { //// m_current = Value[Index]; //// value = m_current - '0'; //// if(value >= 0 && value <= 9) //// { //// tokenValue = tokenValue * 10 + value; //// } //// else //// { //// break; //// } //// } //// if(Index - start > DateTimeParse.MaxDateTimeNumberDigits) //// { //// tokenType = TokenType.NumberToken; //// tokenValue = -1; //// } //// else if(Index - start < 3) //// { //// tokenType = TokenType.NumberToken; //// } //// else //// { //// // If there are more than 3 digits, assume that it's a year value. //// tokenType = TokenType.YearNumberToken; //// } //// if(m_checkDigitToken) //// { //// int save = Index; //// char saveCh = m_current; //// // Re-scan using the staring Index to see if this is a token. //// Index = start; // To include the first digit. //// m_current = Value[Index]; //// TokenType tempType; //// int tempValue; //// // This DTFI has tokens starting with digits. //// // E.g. mn-MN has month name like "\x0031\x00a0\x0434\x04af\x0433\x044d\x044d\x0440\x00a0\x0441\x0430\x0440" //// if(dtfi.Tokenize( TokenType.RegularTokenMask, out tempType, out tempValue, ref this )) //// { //// tokenType = tempType; //// tokenValue = tempValue; //// // This is a token, so the Index has been advanced propertly in DTFI.Tokenizer(). //// } //// else //// { //// // Use the number token value. //// // Restore the index. //// Index = save; //// m_current = saveCh; //// } //// //// } //// //// } //// else if(Char.IsWhiteSpace( m_current )) //// { //// // Just skip to the next character. //// while(++Index < len) //// { //// m_current = Value[Index]; //// if(!(Char.IsWhiteSpace( m_current ))) //// { //// goto Start; //// } //// } //// // We have reached the end of string. //// tokenType = TokenType.EndOfString; //// } //// else //// { //// dtfi.Tokenize( TokenType.RegularTokenMask, out tokenType, out tokenValue, ref this ); //// } //// } //// //// internal TokenType GetSeparatorToken( DateTimeFormatInfo dtfi ) //// { //// TokenType tokenType; //// if(!SkipWhiteSpaceCurrent()) //// { //// // Reach the end of the string. //// return (TokenType.SEP_End); //// } //// if(!DateTimeParse.IsDigit( m_current )) //// { //// // Not a digit. Tokenize it. //// int tokenValue; //// bool found = dtfi.Tokenize( TokenType.SeparatorTokenMask, out tokenType, out tokenValue, ref this ); //// if(!found) //// { //// tokenType = TokenType.SEP_Space; //// } //// } //// else //// { //// // Do nothing here. If we see a number, it will not be a separator. There is no need wasting time trying to find the //// // separator token. //// tokenType = TokenType.SEP_Space; //// } //// return (tokenType); //// } //// //// internal bool MatchSpecifiedWord( String target ) //// { //// return MatchSpecifiedWord( target, target.Length + Index ); //// } //// //// internal bool MatchSpecifiedWord( String target, int endIndex ) //// { //// int count = endIndex - Index; //// //// if(count != target.Length) //// { //// return false; //// } //// //// if(Index + count > len) //// { //// return false; //// } //// //// return (m_info.Compare( Value, Index, count, target, 0, count, CompareOptions.IgnoreCase ) == 0); //// } //// //// private static Char[] WhiteSpaceChecks = new Char[] { ' ', '\u00A0' }; //// //// internal bool MatchSpecifiedWords( String target, bool checkWordBoundary, ref int matchLength ) //// { //// int valueRemaining = Value.Length - Index; //// matchLength = target.Length; //// //// if(matchLength > valueRemaining || m_info.Compare( Value, Index, matchLength, target, 0, matchLength, CompareOptions.IgnoreCase ) != 0) //// { //// // Check word by word //// int targetPosition = 0; // Where we are in the target string //// int thisPosition = Index; // Where we are in this string //// int wsIndex = target.IndexOfAny( WhiteSpaceChecks, targetPosition ); //// if(wsIndex == -1) //// { //// return false; //// } //// do //// { //// int segmentLength = wsIndex - targetPosition; //// if(thisPosition >= Value.Length - segmentLength) //// { // Subtraction to prevent overflow. //// return false; //// } //// if(segmentLength == 0) //// { //// // If segmentLength == 0, it means that we have leading space in the target string. //// // In that case, skip the leading spaces in the target and this string. //// matchLength--; //// } //// else //// { //// // Make sure we also have whitespace in the input string //// if(!Char.IsWhiteSpace( Value[thisPosition + segmentLength] )) //// { //// return false; //// } //// if(m_info.Compare( Value, thisPosition, segmentLength, target, targetPosition, segmentLength, CompareOptions.IgnoreCase ) != 0) //// { //// return false; //// } //// // Advance the input string //// thisPosition = thisPosition + segmentLength + 1; //// } //// // Advance our target string //// targetPosition = wsIndex + 1; //// //// //// // Skip past multiple whitespace //// while(thisPosition < Value.Length && Char.IsWhiteSpace( Value[thisPosition] )) //// { //// thisPosition++; //// matchLength++; //// } //// } while((wsIndex = target.IndexOfAny( WhiteSpaceChecks, targetPosition )) >= 0); //// // now check the last segment; //// if(targetPosition < target.Length) //// { //// int segmentLength = target.Length - targetPosition; //// if(thisPosition > Value.Length - segmentLength) //// { //// return false; //// } //// if(m_info.Compare( Value, thisPosition, segmentLength, target, targetPosition, segmentLength, CompareOptions.IgnoreCase ) != 0) //// { //// return false; //// } //// } //// } //// //// if(checkWordBoundary) //// { //// int nextCharIndex = Index + matchLength; //// if(nextCharIndex < Value.Length) //// { //// if(Char.IsLetter( Value[nextCharIndex] )) //// { //// return (false); //// } //// } //// } //// return (true); //// } //// //// // //// // Check to see if the string starting from Index is a prefix of //// // str. //// // If a match is found, true value is returned and Index is updated to the next character to be parsed. //// // Otherwise, Index is unchanged. //// // //// internal bool Match( String str ) //// { //// if(++Index >= len) //// { //// return (false); //// } //// //// if(str.Length > (Value.Length - Index)) //// { //// return false; //// } //// //// if(m_info.Compare( Value, Index, str.Length, str, 0, str.Length, CompareOptions.Ordinal ) == 0) //// { //// // Update the Index to the end of the matching string. //// // So the following GetNext()/Match() opeartion will get //// // the next character to be parsed. //// Index += (str.Length - 1); //// return (true); //// } //// return (false); //// } //// //// internal bool Match( char ch ) //// { //// if(++Index >= len) //// { //// return (false); //// } //// if(Value[Index] == ch) //// { //// m_current = ch; //// return (true); //// } //// Index--; //// return (false); //// } //// //// // //// // Actions: From the current position, try matching the longest word in the specified string array. //// // E.g. words[] = {"AB", "ABC", "ABCD"}, if the current position points to a substring like "ABC DEF", //// // MatchLongestWords(words, ref MaxMatchStrLen) will return 1 (the index), and maxMatchLen will be 3. //// // Returns: //// // The index that contains the longest word to match //// // Arguments: //// // words The string array that contains words to search. //// // maxMatchStrLen [in/out] the initailized maximum length. This parameter can be used to //// // find the longest match in two string arrays. //// // //// internal int MatchLongestWords( String[] words, ref int maxMatchStrLen ) //// { //// int result = -1; //// for(int i = 0; i < words.Length; i++) //// { //// String word = words[i]; //// int matchLength = word.Length; //// if(MatchSpecifiedWords( word, false, ref matchLength )) //// { //// if(matchLength > maxMatchStrLen) //// { //// maxMatchStrLen = matchLength; //// result = i; //// } //// } //// } //// //// return (result); //// } //// //// // //// // Get the number of repeat character after the current character. //// // For a string "hh:mm:ss" at Index of 3. GetRepeatCount() = 2, and Index //// // will point to the second ':'. //// // //// internal int GetRepeatCount() //// { //// char repeatChar = Value[Index]; //// int pos = Index + 1; //// while((pos < len) && (Value[pos] == repeatChar)) //// { //// pos++; //// } //// int repeatCount = (pos - Index); //// // Update the Index to the end of the repeated characters. //// // So the following GetNext() opeartion will get //// // the next character to be parsed. //// Index = pos - 1; //// return (repeatCount); //// } //// //// // Return false when end of string is encountered or a non-digit character is found. //// internal bool GetNextDigit() //// { //// if(++Index >= len) //// { //// return (false); //// } //// return (DateTimeParse.IsDigit( Value[Index] )); //// } //// //// // //// // Get the current character. //// // //// internal char GetChar() //// { //// BCLDebug.Assert( Index >= 0 && Index < len, "Index >= 0 && Index < len" ); //// return (Value[Index]); //// } //// //// // //// // Convert the current character to a digit, and return it. //// // //// internal int GetDigit() //// { //// BCLDebug.Assert( Index >= 0 && Index < len, "Index >= 0 && Index < len" ); //// BCLDebug.Assert( DateTimeParse.IsDigit( Value[Index] ), "IsDigit(Value[Index])" ); //// return (Value[Index] - '0'); //// } //// //// // //// // Eat White Space ahead of the current position //// // //// // Return false if end of string is encountered. //// // //// internal void SkipWhiteSpaces() //// { //// // Look ahead to see if the next character //// // is a whitespace. //// while(Index + 1 < len) //// { //// char ch = Value[Index + 1]; //// if(!Char.IsWhiteSpace( ch )) //// { //// return; //// } //// Index++; //// } //// return; //// } //// //// // //// // Skip white spaces from the current position //// // //// // Return false if end of string is encountered. //// // //// internal bool SkipWhiteSpaceCurrent() //// { //// if(Index >= len) //// { //// return (false); //// } //// //// if(!Char.IsWhiteSpace( m_current )) //// { //// return (true); //// } //// //// while(++Index < len) //// { //// m_current = Value[Index]; //// if(!Char.IsWhiteSpace( m_current )) //// { //// return (true); //// } //// // Nothing here. //// } //// return (false); //// } //// //// internal void TrimTail() //// { //// int i = len - 1; //// while(i >= 0 && Char.IsWhiteSpace( Value[i] )) //// { //// i--; //// } //// Value = Value.Substring( 0, i + 1 ); //// len = Value.Length; //// } //// //// // Trim the trailing spaces within a quoted string. //// // Call this after TrimTail() is done. //// internal void RemoveTrailingInQuoteSpaces() //// { //// int i = len - 1; //// if(i <= 1) //// { //// return; //// } //// char ch = Value[i]; //// // Check if the last character is a quote. //// if(ch == '\'' || ch == '\"') //// { //// if(Char.IsWhiteSpace( Value[i - 1] )) //// { //// i--; //// while(i >= 1 && Char.IsWhiteSpace( Value[i - 1] )) //// { //// i--; //// } //// Value = Value.Remove( i, Value.Length - 1 - i ); //// len = Value.Length; //// } //// } //// } //// //// // Trim the leading spaces within a quoted string. //// // Call this after the leading spaces before quoted string are trimmed. //// internal void RemoveLeadingInQuoteSpaces() //// { //// if(len <= 2) //// { //// return; //// } //// int i = 0; //// char ch = Value[i]; //// // Check if the last character is a quote. //// if(ch == '\'' || ch == '\"') //// { //// while((i + 1) < len && Char.IsWhiteSpace( Value[i + 1] )) //// { //// i++; //// } //// if(i != 0) //// { //// Value = Value.Remove( 1, i ); //// len = Value.Length; //// } //// } //// } //// //// internal DTSubString GetSubString() //// { //// DTSubString sub = new DTSubString(); //// sub.index = Index; //// sub.s = Value; //// while(Index + sub.length < len) //// { //// DTSubStringType currentType; //// Char ch = Value[Index + sub.length]; //// if(ch >= '0' && ch <= '9') //// { //// currentType = DTSubStringType.Number; //// } //// else //// { //// currentType = DTSubStringType.Other; //// } //// //// if(sub.length == 0) //// { //// sub.type = currentType; //// } //// else //// { //// if(sub.type != currentType) //// { //// break; //// } //// } //// sub.length++; //// if(currentType == DTSubStringType.Number) //// { //// // Incorporate the number into the value //// // Limit the digits to prevent overflow //// if(sub.length > DateTimeParse.MaxDateTimeNumberDigits) //// { //// sub.type = DTSubStringType.Invalid; //// return sub; //// } //// int number = ch - '0'; //// BCLDebug.Assert( number >= 0 && number <= 9, "number >= 0 && number <= 9" ); //// sub.value = sub.value * 10 + number; //// } //// else //// { //// // For non numbers, just return this length 1 token. This should be expanded //// // to more types of thing if this parsing approach is used for things other //// // than numbers and single characters //// break; //// } //// } //// if(sub.length == 0) //// { //// sub.type = DTSubStringType.End; //// return sub; //// } //// //// return sub; //// } //// //// internal void ConsumeSubString( DTSubString sub ) //// { //// BCLDebug.Assert( sub.index == Index, "sub.index == Index" ); //// BCLDebug.Assert( sub.index + sub.length <= len, "sub.index + sub.length <= len" ); //// Index = sub.index + sub.length; //// if(Index < len) //// { //// m_current = Value[Index]; //// } //// } //// //// ////} //// ////internal enum DTSubStringType ////{ //// Unknown = 0, //// Invalid = 1, //// Number = 2, //// End = 3, //// Other = 4, ////} //// ////internal struct DTSubString ////{ //// internal String s; //// internal Int32 index; //// internal Int32 length; //// internal DTSubStringType type; //// internal Int32 value; //// //// internal Char this[Int32 relativeIndex] //// { //// get //// { //// return s[index + relativeIndex]; //// } //// } ////} //// ////// ////// The buffer to store the parsing token. ////// ////internal struct DateTimeToken ////{ //// internal DateTimeParse.DTT dtt; // Store the token //// internal TokenType suffix; // Store the CJK Year/Month/Day suffix (if any) //// internal int num; // Store the number that we are parsing (if any) ////} //// ////// ////// The buffer to store temporary parsing information. ////// ////internal unsafe struct DateTimeRawInfo ////{ //// private int* num; //// internal int numCount; //// internal int month; //// internal int year; //// internal int dayOfWeek; //// internal int era; //// internal DateTimeParse.TM timeMark; //// internal double fraction; //// // //// // when we support more timezone names, change this to be //// // type of TimeZone. //// // //// internal bool timeZone; //// //// internal void Init( int* numberBuffer ) //// { //// month = -1; //// year = -1; //// dayOfWeek = -1; //// era = -1; //// timeMark = DateTimeParse.TM.NotSet; //// fraction = -1; //// num = numberBuffer; //// } //// internal unsafe void AddNumber( int value ) //// { //// num[numCount++] = value; //// } //// internal unsafe int GetNumber( int index ) //// { //// return num[index]; //// } ////} //// ////internal enum ParseFailureKind ////{ //// None = 0, //// ArgumentNull = 1, //// Format = 2, //// FormatWithParameter = 3, //// FormatBadDateTimeCalendar = 4, // FormatException when ArgumentOutOfRange is thrown by a Calendar.TryToDateTime(). ////}; //// ////[Flags] ////internal enum ParseFlags ////{ //// HaveYear = 0x00000001, //// HaveMonth = 0x00000002, //// HaveDay = 0x00000004, //// HaveHour = 0x00000008, //// HaveMinute = 0x00000010, //// HaveSecond = 0x00000020, //// HaveTime = 0x00000040, //// HaveDate = 0x00000080, //// TimeZoneUsed = 0x00000100, //// TimeZoneUtc = 0x00000200, //// ParsedMonthName = 0x00000400, ////} //// ////// ////// This will store the result of the parsing. And it will be eventually ////// used to construct a DateTime instance. ////// ////internal struct DateTimeResult ////{ //// internal int Year; //// internal int Month; //// internal int Day; //// // //// // Set time defualt to 00:00:00. //// // //// internal int Hour; //// internal int Minute; //// internal int Second; //// internal double fraction; //// //// internal int era; //// //// internal ParseFlags flags; //// //// internal TimeSpan timeZoneOffset; //// //// internal Calendar calendar; //// //// internal DateTime parsedDate; //// //// internal ParseFailureKind failure; //// internal string failureMessageID; //// internal object failureMessageFormatArgument; //// internal string failureArgumentName; //// //// internal void Init() //// { //// Year = -1; //// Month = -1; //// Day = -1; //// fraction = -1; //// era = -1; //// } //// //// internal void SetDate( int year, int month, int day ) //// { //// Year = year; //// Month = month; //// Day = day; //// } //// internal void SetFailure( ParseFailureKind failure, string failureMessageID, object failureMessageFormatArgument ) //// { //// this.failure = failure; //// this.failureMessageID = failureMessageID; //// this.failureMessageFormatArgument = failureMessageFormatArgument; //// } //// //// internal void SetFailure( ParseFailureKind failure, string failureMessageID, object failureMessageFormatArgument, string failureArgumentName ) //// { //// this.failure = failure; //// this.failureMessageID = failureMessageID; //// this.failureMessageFormatArgument = failureMessageFormatArgument; //// this.failureArgumentName = failureArgumentName; //// } //// //// //// //// ////} //// ////// This is the helper data structure used in ParseExact(). ////internal struct ParsingInfo ////{ //// //// internal Calendar calendar; //// internal int dayOfWeek; //// internal DateTimeParse.TM timeMark; //// //// internal bool fUseHour12; //// internal bool fUseTwoDigitYear; //// internal bool fAllowInnerWhite; //// internal bool fAllowTrailingWhite; //// internal bool fCustomNumberParser; //// internal DateTimeParse.MatchNumberDelegate parseNumberDelegate; //// //// internal void Init() //// { //// dayOfWeek = -1; //// timeMark = DateTimeParse.TM.NotSet; //// } //// ////} //// ////// ////// The type of token that will be returned by DateTimeFormatInfo.Tokenize(). ////// ////internal enum TokenType ////{ //// // The valid token should start from 1. //// //// // Regular tokens. The range is from 0x00 ~ 0xff. //// NumberToken = 1, // The number. E.g. "12" //// YearNumberToken = 2, // The number which is considered as year number, which has 3 or more digits. E.g. "2003" //// Am = 3, // AM timemark. E.g. "AM" //// Pm = 4, // PM timemark. E.g. "PM" //// MonthToken = 5, // A word (or words) that represents a month name. E.g. "March" //// EndOfString = 6, // End of string //// DayOfWeekToken = 7, // A word (or words) that represents a day of week name. E.g. "Monday" or "Mon" //// TimeZoneToken = 8, // A word that represents a timezone name. E.g. "GMT" //// EraToken = 9, // A word that represents a era name. E.g. "A.D." //// DateWordToken = 10, // A word that can appear in a DateTime string, but serves no parsing semantics. E.g. "de" in Spanish culture. //// UnknownToken = 11, // An unknown word, which signals an error in parsing. //// HebrewNumber = 12, // A number that is composed of Hebrew text. Hebrew calendar uses Hebrew digits for year values, month values, and day values. //// JapaneseEraToken = 13, // Era name for JapaneseCalendar //// TEraToken = 14, // Era name for TaiwanCalenadr //// IgnorableSymbol = 15, // A separator like "," that is equivalent to whitespace //// //// //// // Separator tokens. //// SEP_Unk = 0x100, // Unknown separator. //// SEP_End = 0x200, // The end of the parsing string. //// SEP_Space = 0x300, // Whitespace (including comma). //// SEP_Am = 0x400, // AM timemark. E.g. "AM" //// SEP_Pm = 0x500, // PM timemark. E.g. "PM" //// SEP_Date = 0x600, // date separator. E.g. "/" //// SEP_Time = 0x700, // time separator. E.g. ":" //// SEP_YearSuff = 0x800, // Chinese/Japanese/Korean year suffix. //// SEP_MonthSuff = 0x900, // Chinese/Japanese/Korean month suffix. //// SEP_DaySuff = 0xa00, // Chinese/Japanese/Korean day suffix. //// SEP_HourSuff = 0xb00, // Chinese/Japanese/Korean hour suffix. //// SEP_MinuteSuff = 0xc00, // Chinese/Japanese/Korean minute suffix. //// SEP_SecondSuff = 0xd00, // Chinese/Japanese/Korean second suffix. //// SEP_LocalTimeMark = 0xe00, // 'T', used in ISO 8601 format. //// //// RegularTokenMask = 0x00ff, //// SeparatorTokenMask = 0xff00, ////} } ================================================ FILE: Zelig/Zelig/RunTime/Framework/mscorlib/System/Globalization/DateTimeStyles.cs ================================================ // ==++== // // Copyright (c) Microsoft Corporation. All rights reserved. // // ==--== /*============================================================ ** ** Enum: DateTimeStyles.cs ** ** ** Purpose: Contains valid formats for DateTime recognized by ** the DateTime class' parsing code. ** ** ===========================================================*/ namespace System.Globalization { [Flags, Serializable] public enum DateTimeStyles { // Bit flag indicating that leading whitespace is allowed. Character values // 0x0009, 0x000A, 0x000B, 0x000C, 0x000D, and 0x0020 are considered to be // whitespace. None = 0x00000000, AllowLeadingWhite = 0x00000001, AllowTrailingWhite = 0x00000002, //Bitflag indicating trailing whitespace is allowed. AllowInnerWhite = 0x00000004, AllowWhiteSpaces = AllowLeadingWhite | AllowInnerWhite | AllowTrailingWhite, // When parsing a date/time string, if all year/month/day are missing, set the default date // to 0001/1/1, instead of the current year/month/day. NoCurrentDateDefault = 0x00000008, // When parsing a date/time string, if a timezone specifier ("GMT","Z","+xxxx", "-xxxx" exists), we will // ajdust the parsed time based to GMT. AdjustToUniversal = 0x00000010, AssumeLocal = 0x00000020, AssumeUniversal = 0x00000040, // Attempt to preserve whether the input is unspecified, local or UTC RoundtripKind = 0x00000080, } } ================================================ FILE: Zelig/Zelig/RunTime/Framework/mscorlib/System/Globalization/DaylightTime.cs ================================================ // ==++== // // Copyright (c) Microsoft Corporation. All rights reserved. // // ==--== namespace System.Globalization { using System; // This class represents a starting/ending time for a period of daylight saving time. [Serializable] public class DaylightTime { internal DateTime m_start; internal DateTime m_end; internal TimeSpan m_delta; private DaylightTime() { } public DaylightTime( DateTime start, DateTime end, TimeSpan delta ) { m_start = start; m_end = end; m_delta = delta; } // The start date of a daylight saving period. public DateTime Start { get { return m_start; } } // The end date of a daylight saving period. public DateTime End { get { return m_end; } } // Delta to stardard offset in ticks. public TimeSpan Delta { get { return m_delta; } } } } ================================================ FILE: Zelig/Zelig/RunTime/Framework/mscorlib/System/Globalization/DigitShapes.cs ================================================ // ==++== // // Copyright (c) Microsoft Corporation. All rights reserved. // // ==--== // // The enumeration constants used in NumberFormatInfo.DigitSubstitution. // namespace System.Globalization { [Serializable] public enum DigitShapes : int { Context = 0x0000, // The shape depends on the previous text in the same output. None = 0x0001, // Gives full Unicode compatibility. NativeNational = 0x0002, // National shapes determined by LOCALE_SNATIVEDIGITS } } ================================================ FILE: Zelig/Zelig/RunTime/Framework/mscorlib/System/Globalization/GregorianCalendar.cs ================================================ // ==++== // // Copyright (c) Microsoft Corporation. All rights reserved. // // ==--== namespace System.Globalization { // // N.B.: // A lot of this code is directly from DateTime.cs. If you update that class, // update this one as well. // However, we still need these duplicated code because we will add era support // in this class. // // using System.Threading; using System; using System.Globalization; using System.Runtime.Serialization; // // This class implements the Gregorian calendar. In 1582, Pope Gregory XIII made // minor changes to the solar Julian or "Old Style" calendar to make it more // accurate. Thus the calendar became known as the Gregorian or "New Style" // calendar, and adopted in Catholic countries such as Spain and France. Later // the Gregorian calendar became popular throughout Western Europe because it // was accurate and convenient for international trade. Scandinavian countries // adopted it in 1700, Great Britain in 1752, the American colonies in 1752 and // India in 1757. China adopted the same calendar in 1911, Russia in 1918, and // some Eastern European countries as late as 1940. // // This calendar recognizes two era values: // 0 CurrentEra (AD) // 1 BeforeCurrentEra (BC) [Serializable()] public class GregorianCalendar : Calendar { /* A.D. = anno Domini (after the birth of Jesus Christ) */ public const int ADEra = 1; internal const int DatePartYear = 0; internal const int DatePartDayOfYear = 1; internal const int DatePartMonth = 2; internal const int DatePartDay = 3; // // This is the max Gregorian year can be represented by DateTime class. The limitation // is derived from DateTime class. // internal const int MaxYear = 9999; internal GregorianCalendarTypes m_type; internal static readonly int[] DaysToMonth365 = { 0, 31, 59, 90, 120, 151, 181, 212, 243, 273, 304, 334, 365 }; internal static readonly int[] DaysToMonth366 = { 0, 31, 60, 91, 121, 152, 182, 213, 244, 274, 305, 335, 366 }; internal static Calendar m_defaultInstance = null; //// #region Serialization //// [OnDeserialized] //// private void OnDeserialized( StreamingContext ctx ) //// { //// if(m_type < GregorianCalendarTypes.Localized || //// m_type > GregorianCalendarTypes.TransliteratedFrench) //// { //// throw new SerializationException( //// String.Format( //// CultureInfo.CurrentCulture, //// Environment.GetResourceString( //// "Serialization_MemberOutOfRange" ), //// "type", //// "GregorianCalendar" ) ); //// } //// } //// #endregion Serialization public override DateTime MinSupportedDateTime { get { return (DateTime.MinValue); } } public override DateTime MaxSupportedDateTime { get { return (DateTime.MaxValue); } } // Return the type of the Gregorian calendar. // public override CalendarAlgorithmType AlgorithmType { get { return CalendarAlgorithmType.SolarCalendar; } } /*=================================GetDefaultInstance========================== **Action: Internal method to provide a default intance of GregorianCalendar. Used by NLS+ implementation ** and other calendars. **Returns: **Arguments: **Exceptions: ============================================================================*/ internal static Calendar GetDefaultInstance() { if(m_defaultInstance == null) { m_defaultInstance = new GregorianCalendar(); } return (m_defaultInstance); } // Construct an instance of gregorian calendar. public GregorianCalendar() : this( GregorianCalendarTypes.Localized ) { } public GregorianCalendar( GregorianCalendarTypes type ) { if((int)type < (int)GregorianCalendarTypes.Localized || (int)type > (int)GregorianCalendarTypes.TransliteratedFrench) { #if EXCEPTION_STRINGS throw new ArgumentOutOfRangeException( "type", String.Format( CultureInfo.CurrentCulture, Environment.GetResourceString( "ArgumentOutOfRange_Range" ), GregorianCalendarTypes.Localized, GregorianCalendarTypes.TransliteratedFrench ) ); #else throw new ArgumentOutOfRangeException(); #endif } this.m_type = type; } public virtual GregorianCalendarTypes CalendarType { get { return (m_type); } set { VerifyWritable(); switch(value) { case GregorianCalendarTypes.Localized: case GregorianCalendarTypes.USEnglish: case GregorianCalendarTypes.MiddleEastFrench: case GregorianCalendarTypes.Arabic: case GregorianCalendarTypes.TransliteratedEnglish: case GregorianCalendarTypes.TransliteratedFrench: m_type = value; break; default: #if EXCEPTION_STRINGS throw new ArgumentOutOfRangeException( "m_type", Environment.GetResourceString( "ArgumentOutOfRange_Enum" ) ); #else throw new ArgumentOutOfRangeException(); #endif } } } internal override int ID { get { // By returning different ID for different variations of GregorianCalendar, // we can support the Transliterated Gregorian calendar. // DateTimeFormatInfo will use this ID to get formatting information about // the calendar. return ((int)m_type); } } // Returns a given date part of this DateTime. This method is used // to compute the year, day-of-year, month, or day part. internal virtual int GetDatePart( long ticks, int part ) { // n = number of days since 1/1/0001 int n = (int)(ticks / TicksPerDay); // y400 = number of whole 400-year periods since 1/1/0001 int y400 = n / DaysPer400Years; // n = day number within 400-year period n -= y400 * DaysPer400Years; // y100 = number of whole 100-year periods within 400-year period int y100 = n / DaysPer100Years; // Last 100-year period has an extra day, so decrement result if 4 if(y100 == 4) y100 = 3; // n = day number within 100-year period n -= y100 * DaysPer100Years; // y4 = number of whole 4-year periods within 100-year period int y4 = n / DaysPer4Years; // n = day number within 4-year period n -= y4 * DaysPer4Years; // y1 = number of whole years within 4-year period int y1 = n / DaysPerYear; // Last year has an extra day, so decrement result if 4 if(y1 == 4) y1 = 3; // If year was requested, compute and return it if(part == DatePartYear) { return (y400 * 400 + y100 * 100 + y4 * 4 + y1 + 1); } // n = day number within year n -= y1 * DaysPerYear; // If day-of-year was requested, return it if(part == DatePartDayOfYear) { return (n + 1); } // Leap year calculation looks different from IsLeapYear since y1, y4, // and y100 are relative to year 1, not year 0 bool leapYear = (y1 == 3 && (y4 != 24 || y100 == 3)); int[] days = leapYear ? DaysToMonth366 : DaysToMonth365; // All months have less than 32 days, so n >> 5 is a good conservative // estimate for the month int m = n >> 5 + 1; // m = 1-based month number while(n >= days[m]) m++; // If month was requested, return it if(part == DatePartMonth) return (m); // Return 1-based day-of-month return (n - days[m - 1] + 1); } /*=================================GetAbsoluteDate========================== **Action: Gets the absolute date for the given Gregorian date. The absolute date means ** the number of days from January 1st, 1 A.D. **Returns: the absolute date **Arguments: ** year the Gregorian year ** month the Gregorian month ** day the day **Exceptions: ** ArgumentOutOfRangException if year, month, day value is valid. **Note: ** This is an internal method used by DateToTicks() and the calculations of Hijri and Hebrew calendars. ** Number of Days in Prior Years (both common and leap years) + ** Number of Days in Prior Months of Current Year + ** Number of Days in Current Month ** ============================================================================*/ internal static long GetAbsoluteDate( int year, int month, int day ) { if(year >= 1 && year <= MaxYear && month >= 1 && month <= 12) { int[] days = ((year % 4 == 0 && (year % 100 != 0 || year % 400 == 0))) ? DaysToMonth366 : DaysToMonth365; if(day >= 1 && (day <= days[month] - days[month - 1])) { int y = year - 1; int absoluteDate = y * 365 + y / 4 - y / 100 + y / 400 + days[month - 1] + day - 1; return (absoluteDate); } } #if EXCEPTION_STRINGS throw new ArgumentOutOfRangeException( null, Environment.GetResourceString( "ArgumentOutOfRange_BadYearMonthDay" ) ); #else throw new ArgumentOutOfRangeException(); #endif } // Returns the tick count corresponding to the given year, month, and day. // Will check the if the parameters are valid. internal virtual long DateToTicks( int year, int month, int day ) { return (GetAbsoluteDate( year, month, day ) * TicksPerDay); } // Returns the DateTime resulting from adding the given number of // months to the specified DateTime. The result is computed by incrementing // (or decrementing) the year and month parts of the specified DateTime by // value months, and, if required, adjusting the day part of the // resulting date downwards to the last day of the resulting month in the // resulting year. The time-of-day part of the result is the same as the // time-of-day part of the specified DateTime. // // In more precise terms, considering the specified DateTime to be of the // form y / m / d + t, where y is the // year, m is the month, d is the day, and t is the // time-of-day, the result is y1 / m1 / d1 + t, // where y1 and m1 are computed by adding value months // to y and m, and d1 is the largest value less than // or equal to d that denotes a valid day in month m1 of year // y1. // public override DateTime AddMonths( DateTime time, int months ) { if(months < -120000 || months > 120000) { #if EXCEPTION_STRINGS throw new ArgumentOutOfRangeException( "months", String.Format( CultureInfo.CurrentCulture, Environment.GetResourceString( "ArgumentOutOfRange_Range" ), -120000, 120000 ) ); #else throw new ArgumentOutOfRangeException(); #endif } int y = GetDatePart( time.Ticks, DatePartYear ); int m = GetDatePart( time.Ticks, DatePartMonth ); int d = GetDatePart( time.Ticks, DatePartDay ); int i = m - 1 + months; if(i >= 0) { m = i % 12 + 1; y = y + i / 12; } else { m = 12 + (i + 1) % 12; y = y + (i - 11) / 12; } int[] daysArray = (y % 4 == 0 && (y % 100 != 0 || y % 400 == 0)) ? DaysToMonth366 : DaysToMonth365; int days = (daysArray[m] - daysArray[m - 1]); if(d > days) { d = days; } long ticks = DateToTicks( y, m, d ) + time.Ticks % TicksPerDay; Calendar.CheckAddResult( ticks, MinSupportedDateTime, MaxSupportedDateTime ); return (new DateTime( ticks )); } // Returns the DateTime resulting from adding the given number of // years to the specified DateTime. The result is computed by incrementing // (or decrementing) the year part of the specified DateTime by value // years. If the month and day of the specified DateTime is 2/29, and if the // resulting year is not a leap year, the month and day of the resulting // DateTime becomes 2/28. Otherwise, the month, day, and time-of-day // parts of the result are the same as those of the specified DateTime. // public override DateTime AddYears( DateTime time, int years ) { return (AddMonths( time, years * 12 )); } // Returns the day-of-month part of the specified DateTime. The returned // value is an integer between 1 and 31. // public override int GetDayOfMonth( DateTime time ) { return (GetDatePart( time.Ticks, DatePartDay )); } // Returns the day-of-week part of the specified DateTime. The returned value // is an integer between 0 and 6, where 0 indicates Sunday, 1 indicates // Monday, 2 indicates Tuesday, 3 indicates Wednesday, 4 indicates // Thursday, 5 indicates Friday, and 6 indicates Saturday. // public override DayOfWeek GetDayOfWeek( DateTime time ) { return ((DayOfWeek)((int)(time.Ticks / TicksPerDay + 1) % 7)); } // This is copied from the generic implementation of Calendar.cs. The generic implementation is not good enough // in the case of FristFullWeek and FirstFourDayWeek since it needs the data for B.C. year 1 near 0001/1/1. // We override the generic implementation to handle this special case. public override int GetWeekOfYear( DateTime time, CalendarWeekRule rule, DayOfWeek firstDayOfWeek ) { if((int)firstDayOfWeek < 0 || (int)firstDayOfWeek > 6) { #if EXCEPTION_STRINGS throw new ArgumentOutOfRangeException( "firstDayOfWeek", String.Format( CultureInfo.CurrentCulture, Environment.GetResourceString( "ArgumentOutOfRange_Range" ), DayOfWeek.Sunday, DayOfWeek.Saturday ) ); #else throw new ArgumentOutOfRangeException(); #endif } switch(rule) { case CalendarWeekRule.FirstDay: return (GetFirstDayWeekOfYear( time, (int)firstDayOfWeek )); case CalendarWeekRule.FirstFullWeek: return (InternalGetWeekOfYearFullDays( this, time, (int)firstDayOfWeek, 7, 365 )); case CalendarWeekRule.FirstFourDayWeek: return (InternalGetWeekOfYearFullDays( this, time, (int)firstDayOfWeek, 4, 365 )); } #if EXCEPTION_STRINGS throw new ArgumentOutOfRangeException( "rule", String.Format( CultureInfo.CurrentCulture, Environment.GetResourceString( "ArgumentOutOfRange_Range" ), CalendarWeekRule.FirstDay, CalendarWeekRule.FirstFourDayWeek ) ); #else throw new ArgumentOutOfRangeException(); #endif } // This is copied from the generic implementation of GetWeekOfYearFullDays() in Calendar.cs. The generic implementation is not good enough // in the case of FristFullWeek and FirstFourDayWeek since it needs the data for B.C. year 1 near 0001/1/1. // We override the generic implementation to handle this special case. // Parameters // internal static int InternalGetWeekOfYearFullDays( Calendar cal, DateTime time, int firstDayOfWeek, int fullDays, int daysOfMinYearMinusOne ) { int dayForJan1; int offset; int day; int dayOfYear = cal.GetDayOfYear( time ) - 1; // Make the day of year to be 0-based, so that 1/1 is day 0. // // Calculate the number of days between the first day of year (1/1) and the first day of the week. // This value will be a positive value from 0 ~ 6. We call this value as "offset". // // If offset is 0, it means that the 1/1 is the start of the first week. // Assume the first day of the week is Monday, it will look like this: // Sun Mon Tue Wed Thu Fri Sat // 12/31 1/1 1/2 1/3 1/4 1/5 1/6 // +--> First week starts here. // // If offset is 1, it means that the first day of the week is 1 day ahead of 1/1. // Assume the first day of the week is Monday, it will look like this: // Sun Mon Tue Wed Thu Fri Sat // 1/1 1/2 1/3 1/4 1/5 1/6 1/7 // +--> First week starts here. // // If offset is 2, it means that the first day of the week is 2 days ahead of 1/1. // Assume the first day of the week is Monday, it will look like this: // Sat Sun Mon Tue Wed Thu Fri Sat // 1/1 1/2 1/3 1/4 1/5 1/6 1/7 1/8 // +--> First week starts here. // Day of week is 0-based. // Get the day of week for 1/1. This can be derived from the day of week of the target day. // Note that we can get a negative value. It's ok since we are going to make it a positive value when calculating the offset. dayForJan1 = (int)cal.GetDayOfWeek( time ) - (dayOfYear % 7); // Now, calucalte the offset. Substract the first day of week from the dayForJan1. And make it a positive value. offset = (firstDayOfWeek - dayForJan1 + 14) % 7; if(offset != 0 && offset >= fullDays) { // // If the offset is greater than the value of fullDays, it means that // the first week of the year starts on the week where Jan/1 falls on. // offset -= 7; } // // Calculate the day of year for specified time by taking offset into account. // day = dayOfYear - offset; if(day >= 0) { // // If the day of year value is greater than zero, get the week of year. // return (day / 7 + 1); } // // Otherwise, the specified time falls on the week of previous year. // Note that it is not always week 52 or 53, because it depends on the calendar. Different calendars have different number of days in a year. // // Repeat the previous calculation logic using the previous year and calculate the week of year for the last day of previous year. int year = cal.GetYear( time ); if(year <= cal.GetYear( cal.MinSupportedDateTime )) { // This specified time is in 0001/1/1 ~ 0001/1/7. dayOfYear = daysOfMinYearMinusOne; } else { dayOfYear = cal.GetDaysInYear( year - 1 ); } dayForJan1 = dayForJan1 - (dayOfYear % 7); // Now, calucalte the offset. Substract the first day of week from the dayForJan1. And make it a positive value. offset = (firstDayOfWeek - dayForJan1 + 14) % 7; if(offset != 0 && offset >= fullDays) { // // If the offset is greater than the value of fullDays, it means that // the first week of the year starts on the week where Jan/1 falls on. // offset -= 7; } // // Calculate the day of year for specified time by taking offset into account. // day = dayOfYear - offset; return (day / 7 + 1); } // Returns the day-of-year part of the specified DateTime. The returned value // is an integer between 1 and 366. // public override int GetDayOfYear( DateTime time ) { return (GetDatePart( time.Ticks, DatePartDayOfYear )); } // Returns the number of days in the month given by the year and // month arguments. // public override int GetDaysInMonth( int year, int month, int era ) { if(era == CurrentEra || era == ADEra) { if(year < 1 || year > MaxYear) { #if EXCEPTION_STRINGS throw new ArgumentOutOfRangeException( "year", String.Format( CultureInfo.CurrentCulture, Environment.GetResourceString( "ArgumentOutOfRange_Range" ), 1, MaxYear ) ); #else throw new ArgumentOutOfRangeException(); #endif } if(month < 1 || month > 12) { #if EXCEPTION_STRINGS throw new ArgumentOutOfRangeException( "month", Environment.GetResourceString( "ArgumentOutOfRange_Month" ) ); #else throw new ArgumentOutOfRangeException(); #endif } int[] days = ((year % 4 == 0 && (year % 100 != 0 || year % 400 == 0)) ? DaysToMonth366 : DaysToMonth365); return (days[month] - days[month - 1]); } #if EXCEPTION_STRINGS throw new ArgumentOutOfRangeException( "era", Environment.GetResourceString( "ArgumentOutOfRange_InvalidEraValue" ) ); #else throw new ArgumentOutOfRangeException(); #endif } // Returns the number of days in the year given by the year argument for the current era. // public override int GetDaysInYear( int year, int era ) { if(era == CurrentEra || era == ADEra) { if(year >= 1 && year <= MaxYear) { return ((year % 4 == 0 && (year % 100 != 0 || year % 400 == 0)) ? 366 : 365); } #if EXCEPTION_STRINGS throw new ArgumentOutOfRangeException( "year", String.Format( CultureInfo.CurrentCulture, Environment.GetResourceString( "ArgumentOutOfRange_Range" ), 1, MaxYear ) ); #else throw new ArgumentOutOfRangeException(); #endif } #if EXCEPTION_STRINGS throw new ArgumentOutOfRangeException( "era", Environment.GetResourceString( "ArgumentOutOfRange_InvalidEraValue" ) ); #else throw new ArgumentOutOfRangeException(); #endif } // Returns the era for the specified DateTime value. public override int GetEra( DateTime time ) { return (ADEra); } public override int[] Eras { get { return (new int[] { ADEra }); } } // Returns the month part of the specified DateTime. The returned value is an // integer between 1 and 12. // public override int GetMonth( DateTime time ) { return (GetDatePart( time.Ticks, DatePartMonth )); } // Returns the number of months in the specified year and era. public override int GetMonthsInYear( int year, int era ) { if(era == CurrentEra || era == ADEra) { if(year >= 1 && year <= MaxYear) { return (12); } #if EXCEPTION_STRINGS throw new ArgumentOutOfRangeException( "year", String.Format( CultureInfo.CurrentCulture, Environment.GetResourceString( "ArgumentOutOfRange_Range" ), 1, MaxYear ) ); #endif } #if EXCEPTION_STRINGS throw new ArgumentOutOfRangeException( "era", Environment.GetResourceString( "ArgumentOutOfRange_InvalidEraValue" ) ); #else throw new ArgumentOutOfRangeException(); #endif } // Returns the year part of the specified DateTime. The returned value is an // integer between 1 and 9999. // public override int GetYear( DateTime time ) { return (GetDatePart( time.Ticks, DatePartYear )); } // Checks whether a given day in the specified era is a leap day. This method returns true if // the date is a leap day, or false if not. // public override bool IsLeapDay( int year, int month, int day, int era ) { if(era != CurrentEra && era != ADEra) { #if EXCEPTION_STRINGS throw new ArgumentOutOfRangeException( "era", Environment.GetResourceString( "ArgumentOutOfRange_InvalidEraValue" ) ); #else throw new ArgumentOutOfRangeException(); #endif } if(year < 1 || year > MaxYear) { #if EXCEPTION_STRINGS throw new ArgumentOutOfRangeException( "year", String.Format( CultureInfo.CurrentCulture, Environment.GetResourceString( "ArgumentOutOfRange_Range" ), 1, MaxYear ) ); #else throw new ArgumentOutOfRangeException(); #endif } if(month < 1 || month > 12) { #if EXCEPTION_STRINGS throw new ArgumentOutOfRangeException( "month", String.Format( CultureInfo.CurrentCulture, Environment.GetResourceString( "ArgumentOutOfRange_Range" ), 1, 12 ) ); #else throw new ArgumentOutOfRangeException(); #endif } if(day < 1 || day > GetDaysInMonth( year, month )) { #if EXCEPTION_STRINGS throw new ArgumentOutOfRangeException( "day", String.Format( CultureInfo.CurrentCulture, Environment.GetResourceString( "ArgumentOutOfRange_Range" ), 1, GetDaysInMonth( year, month ) ) ); #else throw new ArgumentOutOfRangeException(); #endif } if(!IsLeapYear( year )) { return (false); } if(month == 2 && day == 29) { return (true); } return (false); } // Returns the leap month in a calendar year of the specified era. This method returns 0 // if this calendar does not have leap month, or this year is not a leap year. // public override int GetLeapMonth( int year, int era ) { if(era != CurrentEra && era != ADEra) { #if EXCEPTION_STRINGS throw new ArgumentOutOfRangeException( "era", Environment.GetResourceString( "ArgumentOutOfRange_InvalidEraValue" ) ); #else throw new ArgumentOutOfRangeException(); #endif } if(year < 1 || year > MaxYear) { #if EXCEPTION_STRINGS throw new ArgumentOutOfRangeException( "year", String.Format( CultureInfo.CurrentCulture, Environment.GetResourceString( "ArgumentOutOfRange_Range" ), 1, MaxYear ) ); #else throw new ArgumentOutOfRangeException(); #endif } return (0); } // Checks whether a given month in the specified era is a leap month. This method returns true if // month is a leap month, or false if not. // public override bool IsLeapMonth( int year, int month, int era ) { if(era != CurrentEra && era != ADEra) { #if EXCEPTION_STRINGS throw new ArgumentOutOfRangeException( "era", Environment.GetResourceString( "ArgumentOutOfRange_InvalidEraValue" ) ); #else throw new ArgumentOutOfRangeException(); #endif } if(year < 1 || year > MaxYear) { #if EXCEPTION_STRINGS throw new ArgumentOutOfRangeException( "year", String.Format( CultureInfo.CurrentCulture, Environment.GetResourceString( "ArgumentOutOfRange_Range" ), 1, MaxYear ) ); #else throw new ArgumentOutOfRangeException(); #endif } if(month < 1 || month > 12) { #if EXCEPTION_STRINGS throw new ArgumentOutOfRangeException( "month", String.Format( CultureInfo.CurrentCulture, Environment.GetResourceString( "ArgumentOutOfRange_Range" ), 1, 12 ) ); #else throw new ArgumentOutOfRangeException(); #endif } return (false); } // Checks whether a given year in the specified era is a leap year. This method returns true if // year is a leap year, or false if not. // public override bool IsLeapYear( int year, int era ) { if(era == CurrentEra || era == ADEra) { if(year >= 1 && year <= MaxYear) { return (year % 4 == 0 && (year % 100 != 0 || year % 400 == 0)); } #if EXCEPTION_STRINGS throw new ArgumentOutOfRangeException( "year", String.Format( CultureInfo.CurrentCulture, Environment.GetResourceString( "ArgumentOutOfRange_Range" ), 1, MaxYear ) ); #endif } #if EXCEPTION_STRINGS throw new ArgumentOutOfRangeException( "era", Environment.GetResourceString( "ArgumentOutOfRange_InvalidEraValue" ) ); #else throw new ArgumentOutOfRangeException(); #endif } // Returns the date and time converted to a DateTime value. Throws an exception if the n-tuple is invalid. // public override DateTime ToDateTime( int year, int month, int day, int hour, int minute, int second, int millisecond, int era ) { if(era == CurrentEra || era == ADEra) { return new DateTime( year, month, day, hour, minute, second, millisecond ); } #if EXCEPTION_STRINGS throw new ArgumentOutOfRangeException( "era", Environment.GetResourceString( "ArgumentOutOfRange_InvalidEraValue" ) ); #else throw new ArgumentOutOfRangeException(); #endif } internal override Boolean TryToDateTime( int year, int month, int day, int hour, int minute, int second, int millisecond, int era, out DateTime result ) { if(era == CurrentEra || era == ADEra) { return DateTime.TryCreate( year, month, day, hour, minute, second, millisecond, out result ); } result = DateTime.MinValue; return false; } private const int DEFAULT_TWO_DIGIT_YEAR_MAX = 2029; public override int TwoDigitYearMax { get { if(twoDigitYearMax == -1) { twoDigitYearMax = GetSystemTwoDigitYearSetting( ID, DEFAULT_TWO_DIGIT_YEAR_MAX ); } return (twoDigitYearMax); } set { VerifyWritable(); if(value < 99 || value > MaxYear) { #if EXCEPTION_STRINGS throw new ArgumentOutOfRangeException( "year", String.Format( CultureInfo.CurrentCulture, Environment.GetResourceString( "ArgumentOutOfRange_Range" ), 99, MaxYear ) ); #else throw new ArgumentOutOfRangeException(); #endif } twoDigitYearMax = value; } } public override int ToFourDigitYear( int year ) { if(year > MaxYear) { #if EXCEPTION_STRINGS throw new ArgumentOutOfRangeException( "year", String.Format( CultureInfo.CurrentCulture, Environment.GetResourceString( "ArgumentOutOfRange_Range" ), 1, MaxYear ) ); #else throw new ArgumentOutOfRangeException(); #endif } return (base.ToFourDigitYear( year )); } } } ================================================ FILE: Zelig/Zelig/RunTime/Framework/mscorlib/System/Globalization/GregorianCalendarTypes.cs ================================================ // ==++== // // Copyright (c) Microsoft Corporation. All rights reserved. // // ==--== namespace System.Globalization { using System; [Serializable] public enum GregorianCalendarTypes { Localized = Calendar.CAL_GREGORIAN, USEnglish = Calendar.CAL_GREGORIAN_US, MiddleEastFrench = Calendar.CAL_GREGORIAN_ME_FRENCH, Arabic = Calendar.CAL_GREGORIAN_ARABIC, TransliteratedEnglish = Calendar.CAL_GREGORIAN_XLIT_ENGLISH, TransliteratedFrench = Calendar.CAL_GREGORIAN_XLIT_FRENCH, } } ================================================ FILE: Zelig/Zelig/RunTime/Framework/mscorlib/System/Globalization/NumberFormatInfo.cs ================================================ // ==++== // // Copyright (c) Microsoft Corporation. All rights reserved. // // ==--== namespace System.Globalization { using System.Security.Permissions; using System.Runtime.Serialization; using System.Text; using System; // // Property Default Description // PositiveSign '+' Character used to indicate positive values. // NegativeSign '-' Character used to indicate negative values. // NumberDecimalSeparator '.' The character used as the decimal separator. // NumberGroupSeparator ',' The character used to separate groups of // digits to the left of the decimal point. // NumberDecimalDigits 2 The default number of decimal places. // NumberGroupSizes 3 The number of digits in each group to the // left of the decimal point. // NaNSymbol "NaN" The string used to represent NaN values. // PositiveInfinitySymbol"Infinity" The string used to represent positive // infinities. // NegativeInfinitySymbol"-Infinity" The string used to represent negative // infinities. // // // // Property Default Description // CurrencyDecimalSeparator '.' The character used as the decimal // separator. // CurrencyGroupSeparator ',' The character used to separate groups // of digits to the left of the decimal // point. // CurrencyDecimalDigits 2 The default number of decimal places. // CurrencyGroupSizes 3 The number of digits in each group to // the left of the decimal point. // CurrencyPositivePattern 0 The format of positive values. // CurrencyNegativePattern 0 The format of negative values. // CurrencySymbol "$" String used as local monetary symbol. // ////[Serializable] sealed public class NumberFormatInfo : ICloneable, IFormatProvider { // invariantInfo is constant irrespective of your current culture. private static NumberFormatInfo invariantInfo; // READTHIS READTHIS READTHIS // This class has an exact mapping onto a native structure defined in COMNumber.cpp // DO NOT UPDATE THIS WITHOUT UPDATING THAT STRUCTURE. IF YOU ADD BOOL, ADD THEM AT THE END. // ALSO MAKE SURE TO UPDATE mscorlib.h in the VM directory to check field offsets. // READTHIS READTHIS READTHIS internal int[] numberGroupSizes = new int[] { 3 }; internal int[] currencyGroupSizes = new int[] { 3 }; internal int[] percentGroupSizes = new int[] { 3 }; internal String positiveSign = "+"; internal String negativeSign = "-"; internal String numberDecimalSeparator = "."; internal String numberGroupSeparator = ","; internal String currencyGroupSeparator = ","; internal String currencyDecimalSeparator = "."; internal String currencySymbol = "\x00a4"; // U+00a4 is the symbol for International Monetary Fund. // The alternative currency symbol used in Win9x ANSI codepage, that can not roundtrip between ANSI and Unicode. // Currently, only ja-JP and ko-KR has non-null values (which is U+005c, backslash) internal String ansiCurrencySymbol = null; internal String nanSymbol = "NaN"; internal String positiveInfinitySymbol = "Infinity"; internal String negativeInfinitySymbol = "-Infinity"; internal String percentDecimalSeparator = "."; internal String percentGroupSeparator = ","; internal String percentSymbol = "%"; internal String perMilleSymbol = "\u2030"; [OptionalField( VersionAdded = 2 )] internal String[] nativeDigits = { "0", "1", "2", "3", "4", "5", "6", "7", "8", "9" }; // an index which points to a record in Culture Data Table. // We shouldn't be persisting dataItem (since its useless & we weren't using it), // but since COMNumber.cpp uses it and since serialization isn't implimented, its stuck for now. internal int m_dataItem = 0; // NEVER USED, DO NOT USE THIS! (Serialized in Everett) internal int numberDecimalDigits = 2; internal int currencyDecimalDigits = 2; internal int currencyPositivePattern = 0; internal int currencyNegativePattern = 0; internal int numberNegativePattern = 1; internal int percentPositivePattern = 0; internal int percentNegativePattern = 0; internal int percentDecimalDigits = 2; [OptionalField( VersionAdded = 2 )] internal int digitSubstitution = 1; // DigitShapes.None internal bool isReadOnly = false; // We shouldn't be persisting m_useUserOverride (since its useless & we weren't using it), // but since COMNumber.cpp uses it and since serialization isn't implimented, its stuck for now. internal bool m_useUserOverride = false; // NEVER USED, DO NOT USE THIS! (Serialized in Everett) public NumberFormatInfo() : this( null ) { } //// #region Serialization //// // The following fields are exist to keep the serialization compatibility with Everett and shouldn't //// // be used for any other purpose //// internal bool validForParseAsNumber = true; //// internal bool validForParseAsCurrency = true; //// //// [OnSerializing] //// private void OnSerializing( StreamingContext ctx ) //// { //// if(numberDecimalSeparator != numberGroupSeparator) //// { //// validForParseAsNumber = true; //// } //// else //// { //// validForParseAsNumber = false; //// } //// //// if((numberDecimalSeparator != numberGroupSeparator) && //// (numberDecimalSeparator != currencyGroupSeparator) && //// (currencyDecimalSeparator != numberGroupSeparator) && //// (currencyDecimalSeparator != currencyGroupSeparator)) //// { //// validForParseAsCurrency = true; //// } //// else //// { //// validForParseAsCurrency = false; //// } //// } //// //// //// [OnDeserializing] //// private void OnDeserializing( StreamingContext ctx ) //// { //// nativeDigits = null; //// digitSubstitution = -1; //// } //// //// [OnDeserialized] //// private void OnDeserialized( StreamingContext ctx ) //// { //// if(nativeDigits == null) //// { //// nativeDigits = new String[] { "0", "1", "2", "3", "4", "5", "6", "7", "8", "9" }; //// } //// //// if(digitSubstitution < 0) //// { //// digitSubstitution = 1; //// } //// } //// //// #endregion Serialization //// private void VerifyDecimalSeparator( String decSep, String propertyName ) //// { //// if(decSep == null) //// { //// throw new ArgumentNullException( propertyName, //// Environment.GetResourceString( "ArgumentNull_String" ) ); //// } //// //// if(decSep.Length == 0) //// { //// throw new ArgumentException( Environment.GetResourceString( "Argument_EmptyDecString" ) ); //// } //// //// } //// //// private void VerifyGroupSeparator( String groupSep, String propertyName ) //// { //// if(groupSep == null) //// { //// throw new ArgumentNullException( propertyName, //// Environment.GetResourceString( "ArgumentNull_String" ) ); //// } //// } //// //// private void VerifyNativeDigits( String[] nativeDig, String propertyName ) //// { //// if(nativeDig == null) //// { //// throw new ArgumentNullException( propertyName, //// Environment.GetResourceString( "ArgumentNull_Array" ) ); //// } //// //// if(nativeDig.Length != 10) //// { //// throw new ArgumentException( propertyName, Environment.GetResourceString( "Argument_InvalidNativeDigitCount" ) ); //// } //// //// for(int i = 0; i < nativeDig.Length; i++) //// { //// if(nativeDig[i] == null) //// { //// throw new ArgumentNullException( propertyName, //// Environment.GetResourceString( "ArgumentNull_ArrayValue" ) ); //// } //// //// //// if(nativeDig[i].Length != 1) //// { //// if(nativeDig[i].Length != 2) //// { //// // Not 1 or 2 UTF-16 code points //// throw new ArgumentException( propertyName, Environment.GetResourceString( "Argument_InvalidNativeDigitValue" ) ); //// } //// else if(!char.IsSurrogatePair( nativeDig[i][0], nativeDig[i][1] )) //// { //// // 2 UTF-6 code points, but not a surrogate pair //// throw new ArgumentException( propertyName, Environment.GetResourceString( "Argument_InvalidNativeDigitValue" ) ); //// } //// } //// //// if(CharUnicodeInfo.GetDecimalDigitValue( nativeDig[i], 0 ) != i) //// { //// // Not the appropriate digit according to the Unicode data properties //// // (Digit 0 must be a 0, etc.). //// throw new ArgumentException( propertyName, Environment.GetResourceString( "Argument_InvalidNativeDigitValue" ) ); //// } //// } //// } //// //// private void VerifyDigitSubstitution( DigitShapes digitSub, String propertyName ) //// { //// switch(digitSub) //// { //// case DigitShapes.Context: //// case DigitShapes.None: //// case DigitShapes.NativeNational: //// // Success. //// break; //// //// default: //// throw new ArgumentException( propertyName, Environment.GetResourceString( "Argument_InvalidDigitSubstitution" ) ); //// } //// } // We aren't persisting dataItem any more (since its useless & we weren't using it), // Ditto with m_useUserOverride. Don't use them, we use a local copy of everything. internal NumberFormatInfo( CultureTableRecord cultureTableRecord ) { if(cultureTableRecord != null) { //// /* //// We don't have information for the following four. All cultures use //// the same value set in the ctor of NumberFormatInfo. //// PercentGroupSize //// PercentDecimalDigits //// PercentGroupSeparator //// PerMilleSymbol //// */ //// //// // We directly use fields here since these data is coming from data table or Win32, so we //// // don't need to verify their values (except for invalid parsing situations). //// //// cultureTableRecord.GetNFIOverrideValues( this ); //// //// // The Japanese and Korean fonts map a backslash (U+005c) to the correct currency symbol. //// // And yes, we use the ANSI currency symbol in parsing, even for Unicode strings. //// if((932 == cultureTableRecord.IDEFAULTANSICODEPAGE) || //// (949 == cultureTableRecord.IDEFAULTANSICODEPAGE)) //// { //// // Legacy behavior for cultures that use Japanese/Korean default ANSI code pages //// this.ansiCurrencySymbol = "\\"; //// } //// this.negativeInfinitySymbol = cultureTableRecord.SNEGINFINITY; //// this.positiveInfinitySymbol = cultureTableRecord.SPOSINFINITY; //// this.nanSymbol = cultureTableRecord.SNAN; } } private void VerifyWritable() { if(isReadOnly) { #if EXCEPTION_STRINGS throw new InvalidOperationException( Environment.GetResourceString( "InvalidOperation_ReadOnly" ) ); #else throw new InvalidOperationException(); #endif } } // Returns a default NumberFormatInfo that will be universally // supported and constant irrespective of the current culture. // Used by FromString methods. // public static NumberFormatInfo InvariantInfo { get { if(invariantInfo == null) { // Lazy create the invariant info. This cannot be done in a .cctor because exceptions can // be thrown out of a .cctor stack that will need this. invariantInfo = ReadOnly( new NumberFormatInfo() ); } return invariantInfo; } } public static NumberFormatInfo GetInstance( IFormatProvider formatProvider ) { //// // Fast case for a regular CultureInfo //// NumberFormatInfo info; //// CultureInfo cultureProvider = formatProvider as CultureInfo; //// if(cultureProvider != null && !cultureProvider.m_isInherited) //// { //// info = cultureProvider.numInfo; //// if(info != null) //// { //// return info; //// } //// else //// { //// return cultureProvider.NumberFormat; //// } //// } //// // Fast case for an NFI; //// info = formatProvider as NumberFormatInfo; //// if(info != null) //// { //// return info; //// } //// if(formatProvider != null) //// { //// info = formatProvider.GetFormat( typeof( NumberFormatInfo ) ) as NumberFormatInfo; //// if(info != null) //// { //// return info; //// } //// } return CurrentInfo; } public Object Clone() { NumberFormatInfo n = (NumberFormatInfo)MemberwiseClone(); n.isReadOnly = false; return n; } //// public int CurrencyDecimalDigits //// { //// get { return currencyDecimalDigits; } //// set //// { //// VerifyWritable(); //// if(value < 0 || value > 99) //// { //// throw new ArgumentOutOfRangeException( //// "CurrencyDecimalDigits", //// String.Format( //// CultureInfo.CurrentCulture, //// Environment.GetResourceString( "ArgumentOutOfRange_Range" ), //// 0, //// 99 ) ); //// } //// currencyDecimalDigits = value; //// } //// } //// //// //// public String CurrencyDecimalSeparator //// { //// get { return currencyDecimalSeparator; } //// set //// { //// VerifyWritable(); //// VerifyDecimalSeparator( value, "CurrencyDecimalSeparator" ); //// currencyDecimalSeparator = value; //// } //// } public bool IsReadOnly { get { return isReadOnly; } } //// // //// // Check the values of the groupSize array. //// // //// // Every element in the groupSize array should be between 1 and 9 //// // excpet the last element could be zero. //// // //// internal void CheckGroupSize( String propName, int[] groupSize ) //// { //// for(int i = 0; i < groupSize.Length; i++) //// { //// if(groupSize[i] < 1) //// { //// if(i == groupSize.Length - 1 && groupSize[i] == 0) //// return; //// throw new ArgumentException( propName, Environment.GetResourceString( "Argument_InvalidGroupSize" ) ); //// } //// else if(groupSize[i] > 9) //// { //// throw new ArgumentException( propName, Environment.GetResourceString( "Argument_InvalidGroupSize" ) ); //// } //// } //// } //// //// //// public int[] CurrencyGroupSizes //// { //// get //// { //// return ((int[])currencyGroupSizes.Clone()); //// } //// set //// { //// VerifyWritable(); //// if(value == null) //// { //// throw new ArgumentNullException( "CurrencyGroupSizes", //// Environment.GetResourceString( "ArgumentNull_Obj" ) ); //// } //// //// Int32[] inputSizes = (Int32[])value.Clone(); //// CheckGroupSize( "CurrencyGroupSizes", inputSizes ); //// currencyGroupSizes = inputSizes; //// } //// //// } //// //// //// //// public int[] NumberGroupSizes //// { //// get //// { //// return ((int[])numberGroupSizes.Clone()); //// } //// set //// { //// VerifyWritable(); //// if(value == null) //// { //// throw new ArgumentNullException( "NumberGroupSizes", //// Environment.GetResourceString( "ArgumentNull_Obj" ) ); //// } //// //// Int32[] inputSizes = (Int32[])value.Clone(); //// CheckGroupSize( "NumberGroupSizes", inputSizes ); //// numberGroupSizes = inputSizes; //// } //// } //// //// //// public int[] PercentGroupSizes //// { //// get //// { //// return ((int[])percentGroupSizes.Clone()); //// } //// set //// { //// VerifyWritable(); //// if(value == null) //// { //// throw new ArgumentNullException( "PercentGroupSizes", //// Environment.GetResourceString( "ArgumentNull_Obj" ) ); //// } //// Int32[] inputSizes = (Int32[])value.Clone(); //// CheckGroupSize( "PercentGroupSizes", inputSizes ); //// percentGroupSizes = inputSizes; //// } //// //// } //// //// //// public String CurrencyGroupSeparator //// { //// get { return currencyGroupSeparator; } //// set //// { //// VerifyWritable(); //// VerifyGroupSeparator( value, "CurrencyGroupSeparator" ); //// currencyGroupSeparator = value; //// } //// } //// //// //// public String CurrencySymbol //// { //// get { return currencySymbol; } //// set //// { //// VerifyWritable(); //// if(value == null) //// { //// throw new ArgumentNullException( "CurrencySymbol", //// Environment.GetResourceString( "ArgumentNull_String" ) ); //// } //// currencySymbol = value; //// } //// } // Returns the current culture's NumberFormatInfo. Used by Parse methods. // public static NumberFormatInfo CurrentInfo { get { System.Globalization.CultureInfo culture = System.Threading.Thread.CurrentThread.CurrentCulture; if(!culture.m_isInherited) { NumberFormatInfo info = culture.numInfo; if(info != null) { return info; } } return ((NumberFormatInfo)culture.GetFormat( typeof( NumberFormatInfo ) )); } } public String NaNSymbol { get { return nanSymbol; } set { VerifyWritable(); if(value == null) { #if EXCEPTION_STRINGS throw new ArgumentNullException( "NaNSymbol", Environment.GetResourceString( "ArgumentNull_String" ) ); #else throw new ArgumentNullException(); #endif } nanSymbol = value; } } //// public int CurrencyNegativePattern //// { //// get { return currencyNegativePattern; } //// set //// { //// VerifyWritable(); //// if(value < 0 || value > 15) //// { //// throw new ArgumentOutOfRangeException( //// "CurrencyNegativePattern", //// String.Format( //// CultureInfo.CurrentCulture, //// Environment.GetResourceString( "ArgumentOutOfRange_Range" ), //// 0, //// 15 ) ); //// } //// currencyNegativePattern = value; //// } //// } //// //// //// public int NumberNegativePattern //// { //// get { return numberNegativePattern; } //// set //// { //// // //// // NOTENOTE: the range of value should correspond to negNumberFormats[] in vm\COMNumber.cpp. //// // //// VerifyWritable(); //// if(value < 0 || value > 4) //// { //// throw new ArgumentOutOfRangeException( //// "NumberNegativePattern", //// String.Format( //// CultureInfo.CurrentCulture, //// Environment.GetResourceString( "ArgumentOutOfRange_Range" ), //// 0, //// 4 ) ); //// } //// numberNegativePattern = value; //// } //// } //// //// //// public int PercentPositivePattern //// { //// get { return percentPositivePattern; } //// set //// { //// // //// // NOTENOTE: the range of value should correspond to posPercentFormats[] in vm\COMNumber.cpp. //// // //// VerifyWritable(); //// if(value < 0 || value > 3) //// { //// throw new ArgumentOutOfRangeException( //// "PercentPositivePattern", //// String.Format( //// CultureInfo.CurrentCulture, //// Environment.GetResourceString( "ArgumentOutOfRange_Range" ), //// 0, //// 3 ) ); //// } //// percentPositivePattern = value; //// } //// } //// //// //// public int PercentNegativePattern //// { //// get { return percentNegativePattern; } //// set //// { //// // //// // NOTENOTE: the range of value should correspond to posPercentFormats[] in vm\COMNumber.cpp. //// // //// VerifyWritable(); //// if(value < 0 || value > 11) //// { //// throw new ArgumentOutOfRangeException( //// "PercentNegativePattern", //// String.Format( //// CultureInfo.CurrentCulture, //// Environment.GetResourceString( "ArgumentOutOfRange_Range" ), //// 0, //// 11 ) ); //// } //// percentNegativePattern = value; //// } //// } public String NegativeInfinitySymbol { get { return negativeInfinitySymbol; } set { VerifyWritable(); if(value == null) { #if EXCEPTION_STRINGS throw new ArgumentNullException( "NegativeInfinitySymbol", Environment.GetResourceString( "ArgumentNull_String" ) ); #else throw new ArgumentNullException(); #endif } negativeInfinitySymbol = value; } } //// public String NegativeSign //// { //// get { return negativeSign; } //// set //// { //// VerifyWritable(); //// if(value == null) //// { //// throw new ArgumentNullException( "NegativeSign", //// Environment.GetResourceString( "ArgumentNull_String" ) ); //// } //// negativeSign = value; //// } //// } //// //// //// public int NumberDecimalDigits //// { //// get { return numberDecimalDigits; } //// set //// { //// VerifyWritable(); //// if(value < 0 || value > 99) //// { //// throw new ArgumentOutOfRangeException( //// "NumberDecimalDigits", //// String.Format( //// CultureInfo.CurrentCulture, //// Environment.GetResourceString( "ArgumentOutOfRange_Range" ), //// 0, //// 99 ) ); //// } //// numberDecimalDigits = value; //// } //// } //// //// //// public String NumberDecimalSeparator //// { //// get { return numberDecimalSeparator; } //// set //// { //// VerifyWritable(); //// VerifyDecimalSeparator( value, "NumberDecimalSeparator" ); //// numberDecimalSeparator = value; //// } //// } //// //// //// public String NumberGroupSeparator //// { //// get { return numberGroupSeparator; } //// set //// { //// VerifyWritable(); //// VerifyGroupSeparator( value, "NumberGroupSeparator" ); //// numberGroupSeparator = value; //// } //// } //// //// //// public int CurrencyPositivePattern //// { //// get { return currencyPositivePattern; } //// set //// { //// VerifyWritable(); //// if(value < 0 || value > 3) //// { //// throw new ArgumentOutOfRangeException( //// "CurrencyPositivePattern", //// String.Format( //// CultureInfo.CurrentCulture, //// Environment.GetResourceString( "ArgumentOutOfRange_Range" ), //// 0, //// 3 ) ); //// } //// currencyPositivePattern = value; //// } //// } public String PositiveInfinitySymbol { get { return positiveInfinitySymbol; } set { VerifyWritable(); if(value == null) { throw new ArgumentNullException( "PositiveInfinitySymbol", Environment.GetResourceString( "ArgumentNull_String" ) ); } positiveInfinitySymbol = value; } } //// public String PositiveSign //// { //// get { return positiveSign; } //// set //// { //// VerifyWritable(); //// if(value == null) //// { //// throw new ArgumentNullException( "PositiveSign", //// Environment.GetResourceString( "ArgumentNull_String" ) ); //// } //// positiveSign = value; //// } //// } //// //// //// public int PercentDecimalDigits //// { //// get { return percentDecimalDigits; } //// set //// { //// VerifyWritable(); //// if(value < 0 || value > 99) //// { //// throw new ArgumentOutOfRangeException( //// "PercentDecimalDigits", //// String.Format( //// CultureInfo.CurrentCulture, //// Environment.GetResourceString( "ArgumentOutOfRange_Range" ), //// 0, //// 99 ) ); //// } //// percentDecimalDigits = value; //// } //// } //// //// //// public String PercentDecimalSeparator //// { //// get { return percentDecimalSeparator; } //// set //// { //// VerifyWritable(); //// VerifyDecimalSeparator( value, "PercentDecimalSeparator" ); //// percentDecimalSeparator = value; //// } //// } //// //// //// public String PercentGroupSeparator //// { //// get { return percentGroupSeparator; } //// set //// { //// VerifyWritable(); //// VerifyGroupSeparator( value, "PercentGroupSeparator" ); //// percentGroupSeparator = value; //// } //// } //// //// //// public String PercentSymbol //// { //// get //// { //// return percentSymbol; //// } //// set //// { //// VerifyWritable(); //// if(value == null) //// { //// throw new ArgumentNullException( "PercentSymbol", //// Environment.GetResourceString( "ArgumentNull_String" ) ); //// } //// percentSymbol = value; //// } //// } //// //// //// public String PerMilleSymbol //// { //// get { return perMilleSymbol; } //// set //// { //// VerifyWritable(); //// if(value == null) //// { //// throw new ArgumentNullException( "PerMilleSymbol", //// Environment.GetResourceString( "ArgumentNull_String" ) ); //// } //// perMilleSymbol = value; //// } //// } //// //// //// public String[] NativeDigits //// { //// get { return nativeDigits; } //// set //// { //// VerifyWritable(); //// VerifyNativeDigits( value, "NativeDigits" ); //// nativeDigits = value; //// } //// } //// //// //// public DigitShapes DigitSubstitution //// { //// get { return (DigitShapes)digitSubstitution; } //// set //// { //// VerifyWritable(); //// VerifyDigitSubstitution( value, "DigitSubstitution" ); //// digitSubstitution = (int)value; //// } //// } public Object GetFormat( Type formatType ) { return formatType == typeof( NumberFormatInfo ) ? this : null; } public static NumberFormatInfo ReadOnly( NumberFormatInfo nfi ) { if(nfi == null) { #if EXCEPTION_STRINGS throw new ArgumentNullException( "nfi" ); #else throw new ArgumentNullException(); #endif } if(nfi.IsReadOnly) { return (nfi); } NumberFormatInfo info = (NumberFormatInfo)(nfi.MemberwiseClone()); info.isReadOnly = true; return info; } // private const NumberStyles InvalidNumberStyles = unchecked((NumberStyles) 0xFFFFFC00); private const NumberStyles InvalidNumberStyles = ~(NumberStyles.AllowLeadingWhite | NumberStyles.AllowTrailingWhite | NumberStyles.AllowLeadingSign | NumberStyles.AllowTrailingSign | NumberStyles.AllowParentheses | NumberStyles.AllowDecimalPoint | NumberStyles.AllowThousands | NumberStyles.AllowExponent | NumberStyles.AllowCurrencySymbol | NumberStyles.AllowHexSpecifier); internal static void ValidateParseStyleInteger( NumberStyles style ) { // Check for undefined flags if((style & InvalidNumberStyles) != 0) { #if EXCEPTION_STRINGS throw new ArgumentException( Environment.GetResourceString( "Argument_InvalidNumberStyles" ), "style" ); #else throw new ArgumentException(); #endif } if((style & NumberStyles.AllowHexSpecifier) != 0) { // Check for hex number if((style & ~NumberStyles.HexNumber) != 0) { #if EXCEPTION_STRINGS throw new ArgumentException( Environment.GetResourceString( "Arg_InvalidHexStyle" ) ); #else throw new ArgumentException(); #endif } } } internal static void ValidateParseStyleFloatingPoint( NumberStyles style ) { // Check for undefined flags if((style & InvalidNumberStyles) != 0) { #if EXCEPTION_STRINGS throw new ArgumentException( Environment.GetResourceString( "Argument_InvalidNumberStyles" ), "style" ); #else throw new ArgumentException(); #endif } if((style & NumberStyles.AllowHexSpecifier) != 0) { // Check for hex number #if EXCEPTION_STRINGS throw new ArgumentException( Environment.GetResourceString( "Arg_HexStyleNotSupported" ) ); #else throw new ArgumentException(); #endif } } } // NumberFormatInfo } ================================================ FILE: Zelig/Zelig/RunTime/Framework/mscorlib/System/Globalization/NumberStyles.cs ================================================ // ==++== // // Copyright (c) Microsoft Corporation. All rights reserved. // // ==--== /*============================================================ ** ** Enum: NumberStyles.cs ** ** ** Purpose: Contains valid formats for Numbers recognized by ** the Number class' parsing code. ** ** ===========================================================*/ namespace System.Globalization { using System; [Serializable] [Flags] public enum NumberStyles { // Bit flag indicating that leading whitespace is allowed. Character values // 0x0009, 0x000A, 0x000B, 0x000C, 0x000D, and 0x0020 are considered to be // whitespace. None = 0x00000000, AllowLeadingWhite = 0x00000001, AllowTrailingWhite = 0x00000002, //Bitflag indicating trailing whitespace is allowed. AllowLeadingSign = 0x00000004, //Can the number start with a sign char. //Specified by NumberFormatInfo.PositiveSign and NumberFormatInfo.NegativeSign AllowTrailingSign = 0x00000008, //Allow the number to end with a sign char AllowParentheses = 0x00000010, //Allow the number to be enclosed in parens AllowDecimalPoint = 0x00000020, //Allow a decimal point AllowThousands = 0x00000040, //Allow thousands separators (more properly, allow group separators) AllowExponent = 0x00000080, //Allow an exponent AllowCurrencySymbol = 0x00000100, //Allow a currency symbol. AllowHexSpecifier = 0x00000200, //Allow specifiying hexadecimal. //Common uses. These represent some of the most common combinations of these flags. Integer = AllowLeadingWhite | AllowTrailingWhite | AllowLeadingSign, HexNumber = AllowLeadingWhite | AllowTrailingWhite | AllowHexSpecifier, Number = AllowLeadingWhite | AllowTrailingWhite | AllowLeadingSign | AllowTrailingSign | AllowDecimalPoint | AllowThousands, Float = AllowLeadingWhite | AllowTrailingWhite | AllowLeadingSign | AllowDecimalPoint | AllowExponent, Currency = AllowLeadingWhite | AllowTrailingWhite | AllowLeadingSign | AllowTrailingSign | AllowParentheses | AllowDecimalPoint | AllowThousands | AllowCurrencySymbol, Any = AllowLeadingWhite | AllowTrailingWhite | AllowLeadingSign | AllowTrailingSign | AllowParentheses | AllowDecimalPoint | AllowThousands | AllowCurrencySymbol | AllowExponent, } } ================================================ FILE: Zelig/Zelig/RunTime/Framework/mscorlib/System/Globalization/TextInfo.cs ================================================ // ==++== // // Copyright (c) Microsoft Corporation. All rights reserved. // // ==--== //////////////////////////////////////////////////////////////////////////// // // Class: TextInfo // // Purpose: This Class defines behaviors specific to a writing system. // A writing system is the collection of scripts and // orthographic rules required to represent a language as text. // // Date: March 31, 1999 // //////////////////////////////////////////////////////////////////////////// namespace System.Globalization { using System; using System.Text; using System.Threading; using System.Runtime.InteropServices; using System.Runtime.CompilerServices; using System.Runtime.Serialization; ////using System.Security.Permissions; ////using System.Runtime.Versioning; [Serializable] public class TextInfo /*: ICloneable, IDeserializationCallback*/ { //// //--------------------------------------------------------------------// //// // Internal Information // //// //--------------------------------------------------------------------// //// //// //// // //// // Variables. //// // //// //// [OptionalField( VersionAdded = 2 )] //// private String m_listSeparator; //// //// [OptionalField( VersionAdded = 2 )] //// private bool m_isReadOnly = false; //// //// // //// // Basically, this is the language ID (LANGID) used to call Win32 NLS APIs except that //// // the value can be zero for the invariant culture. //// // The reason for this data member to exist is that Win32 APIs //// // doesn't take all of the culture IDs supported in NLS+. //// // For example, NLS+ support culture IDs like 0x0000, 0x0009. //// // However, these are not valid locale IDs in Win32. Therefore, //// // we use a table to map a culutre ID like //// // 0x0009 to 0x0409. //// // //// //// // m_textInfoID should be either 0 or a supported language ID. See TextInfo(m_textInfoID) //// // for comments. //// [NonSerialized] //// private int m_textInfoID; //// [NonSerialized] //// private string m_name = null; //// [NonSerialized] //// private CultureTableRecord m_cultureTableRecord; //// [NonSerialized] //// private TextInfo m_casingTextInfo; //// //// // //// // m_pNativeTextInfo is a 32-bit pointer value pointing to a native C++ NativeTextInfo object. //// // The C++ NativeTextInfo is providing the implemenation of uppercasing/lowercasing. //// // //// // Note: m_pNativeTextInfo is intialized with invariant in case of synthetic cultuers //// [NonSerialized] //// private unsafe void* m_pNativeTextInfo; //// private static unsafe void* m_pInvariantNativeTextInfo; //// private static unsafe void* m_pDefaultCasingTable; //// //// // This file contains the default casing data (uppercasing/lowercasing/titlecasing), and the table to //// // map cultures with exceptions to an exception sub-table in CASING_EXCEPTIONS_FILE_NAME. //// private const String CASING_FILE_NAME = "l_intl.nlp"; //// // This file contains the casing data for cultures with exceptions. //// private const String CASING_EXCEPTIONS_FILE_NAME = "l_except.nlp"; //// //// // //// // This is the header for the native data table that we load from charinfo.nlp. //// // //// [StructLayout( LayoutKind.Explicit )] //// internal unsafe struct TextInfoDataHeader //// { //// [FieldOffset( 0 )] //// internal char TableName; // WCHAR[16] //// [FieldOffset( 0x20 )] //// internal ushort version; // WORD[4] //// [FieldOffset( 0x28 )] //// internal uint OffsetToUpperCasingTable; // DWORD //// [FieldOffset( 0x2c )] //// internal uint OffsetToLowerCasingTable; // DWORD //// [FieldOffset( 0x30 )] //// internal uint OffsetToTitleCaseTable; // DWORD //// [FieldOffset( 0x34 )] //// internal uint PlaneOffset; //// // Each plane has DWORD offset for uppercase and DWORD offset for lowercase. //// // 0xb4 = 0x34 + 8*16 //// [FieldOffset( 0xb4 )] //// internal ushort exceptionCount; //// [FieldOffset( 0xb6 )] //// internal ushort exceptionLangId; //// } //// //// [StructLayout( LayoutKind.Sequential, Pack = 2 )] //// internal struct ExceptionTableItem //// { //// internal ushort langID; // The lcid that contains the exceptions. //// internal ushort exceptIndex; // The name of the exception tables. //// } //// //// //// // The base pointer of the defult casing table //// static unsafe byte* m_pDataTable; //// // The total count of cultures with exceptions. //// static int m_exceptionCount; //// // The pointer to the exception index table. This table maps a culture with exceptions //// // to a sub-table in the exception data table. //// static unsafe ExceptionTableItem* m_exceptionTable; //// //// // The base pointer for exception data file. //// static unsafe byte* m_pExceptionFile; //// // This array caches the native pointer of the NativeTextInfo get by calling InternalAllocateCasingTable. //// //// // NOTE: use long to hold native pointers. //// //static unsafe void*[] m_exceptionNativeTextInfo; //// static unsafe long[] m_exceptionNativeTextInfo; //// //// //////////////////////////////////////////////////////////////////////// //// // //// // Actions: //// // This is the static ctor for TextInfo. It does the following items: //// // * Get the total count of cultures with exceptions. //// // * Set up an exception index table so that we can check if a culture has exception. If yes, which sub-table //// // in the exception table file we should use for this culture. //// // * Set up a cache for NativeTextInfo that we create for cultures with exceptions. //// // //// //////////////////////////////////////////////////////////////////////// //// //// [ResourceExposure( ResourceScope.None )] //// [ResourceConsumption( ResourceScope.Machine, ResourceScope.Machine )] //// static unsafe TextInfo() //// { //// //with AppDomains active, the static initializer is no longer good enough to ensure that only one //// //thread is ever in AllocateDefaultCasingTable at a given time. //// //We use InterlockedExchangePointer in the native side to ensure that only one instance of native CasingTable instance //// //is created per process. //// //// //We check if the table is already allocated in native, so we only need to synchronize //// //access in managed. //// byte* temp = GlobalizationAssembly.GetGlobalizationResourceBytePtr( typeof( TextInfo ).Assembly, CASING_FILE_NAME ); //// System.Threading.Thread.MemoryBarrier(); //// m_pDataTable = temp; //// //// TextInfoDataHeader* pHeader = (TextInfoDataHeader*)m_pDataTable; //// m_exceptionCount = pHeader->exceptionCount; //// // Setup exception tables //// m_exceptionTable = (ExceptionTableItem*)&(pHeader->exceptionLangId); //// m_exceptionNativeTextInfo = new long[m_exceptionCount]; //// //// // Create the native NativeTextInfo for the default linguistic casing table. //// m_pDefaultCasingTable = AllocateDefaultCasingTable( m_pDataTable ); //// //// BCLDebug.Assert( m_pDataTable != null, "Error in reading the table." ); //// BCLDebug.Assert( m_pDefaultCasingTable != null, "m_pDefaultCasingTable != null" ); //// } //// //// // Private object for locking instead of locking on a public type for SQL reliability work. //// private static Object s_InternalSyncObject; //// private static Object InternalSyncObject //// { //// get //// { //// if(s_InternalSyncObject == null) //// { //// Object o = new Object(); //// Interlocked.CompareExchange( ref s_InternalSyncObject, o, null ); //// } //// return s_InternalSyncObject; //// } //// } //// //// //////////////////////////////////////////////////////////////////////// //// // //// // TextInfo Constructors //// // //// // Implements CultureInfo.TextInfo. //// // //// //////////////////////////////////////////////////////////////////////// //// [ResourceExposure( ResourceScope.None )] //// [ResourceConsumption( ResourceScope.Process, ResourceScope.Process )] //// internal unsafe TextInfo( CultureTableRecord table ) //// { //// this.m_cultureTableRecord = table; //// this.m_textInfoID = this.m_cultureTableRecord.ITEXTINFO; //// //// if(table.IsSynthetic) //// { //// // //// // //// // we just initialize m_pNativeTextInfo with variant to make the synthetic TextInfo works when //// // GetCaseInsensitiveHashCode and ChangeCaseSurrogate get called. otherwise m_pNativeTextInfo //// // is not used at all in TextInfo with synthetic cultures. //// // //// m_pNativeTextInfo = InvariantNativeTextInfo; //// } //// else //// { //// this.m_pNativeTextInfo = GetNativeTextInfo( this.m_textInfoID ); //// } //// } //// //// //// //////////////////////////////////////////////////////////////////////// //// // //// // Return the native TextInfo instance for the invariant culture. //// // //// //////////////////////////////////////////////////////////////////////// //// //// internal unsafe static void* InvariantNativeTextInfo //// { //// [ResourceExposure( ResourceScope.Process )] //// [ResourceConsumption( ResourceScope.Process )] //// get //// { //// if(m_pInvariantNativeTextInfo == null) //// { //// lock(InternalSyncObject) //// { //// if(m_pInvariantNativeTextInfo == null) //// { //// m_pInvariantNativeTextInfo = GetNativeTextInfo( CultureInfo.LOCALE_INVARIANT ); //// } //// } //// } //// BCLDebug.Assert( m_pInvariantNativeTextInfo != null, "TextInfo.InvariantNativeTextInfo: m_pInvariantNativeTextInfo != null" ); //// return (m_pInvariantNativeTextInfo); //// } //// } //// //// #region Serialization //// // The following field is used only for the supplemental custom culture serialization to remember //// // the name of the custom culture so we can reconstruct the text info properly during the deserialization. //// //// [OptionalField( VersionAdded = 2 )] //// private string customCultureName; //// //// // the following fields is defined to keep the compatibility with Everett. //// // don't change/remove the names/types of these fields. //// //// internal int m_nDataItem; //// internal bool m_useUserOverride; //// internal int m_win32LangID; //// //// //// [OnDeserializing] //// private void OnDeserializing( StreamingContext ctx ) //// { //// m_cultureTableRecord = null; //// m_win32LangID = 0; //// } //// //// [ResourceExposure( ResourceScope.None )] //// [ResourceConsumption( ResourceScope.Process, ResourceScope.Process )] //// private unsafe void OnDeserialized() //// { //// // this method will be called twice because of the support of IDeserializationCallback //// if(m_cultureTableRecord == null) //// { //// // Due to our versioning, getting the CORRECT culture ID for an Everett structure is challenging. //// if(m_win32LangID == 0) //// { //// m_win32LangID = CultureTableRecord.IdFromEverettDataItem( m_nDataItem ); //// } //// //// if(customCultureName != null) //// { //// m_cultureTableRecord = CultureTableRecord.GetCultureTableRecord( customCultureName, m_useUserOverride ); //// } //// else //// { //// m_cultureTableRecord = CultureTableRecord.GetCultureTableRecord( m_win32LangID, m_useUserOverride ); //// } //// //// m_textInfoID = m_cultureTableRecord.ITEXTINFO; //// //// if(m_cultureTableRecord.IsSynthetic) //// { //// // //// m_pNativeTextInfo = InvariantNativeTextInfo; //// } //// else //// { //// m_pNativeTextInfo = GetNativeTextInfo( m_textInfoID ); //// } //// } //// } //// //// //// [OnDeserialized] //// private void OnDeserialized( StreamingContext ctx ) //// { //// OnDeserialized(); //// } //// //// [OnSerializing] //// private void OnSerializing( StreamingContext ctx ) //// { //// m_nDataItem = m_cultureTableRecord.EverettDataItem(); //// m_useUserOverride = m_cultureTableRecord.UseUserOverride; //// //// if(CultureTableRecord.IsCustomCultureId( m_cultureTableRecord.CultureID )) //// { //// customCultureName = m_cultureTableRecord.SNAME; //// m_win32LangID = m_textInfoID; //// } //// else //// { //// customCultureName = null; //// m_win32LangID = m_cultureTableRecord.CultureID; //// } //// //// } //// //// #endregion Serialization //// //// //// [ResourceExposure( ResourceScope.Process )] //// [ResourceConsumption( ResourceScope.Process )] //// internal static unsafe void* GetNativeTextInfo( int cultureID ) //// { //// // First, assume this culture does not has exceptions. I.e. we should use the default casingg table. //// // So we assign the native NativeTextInfo for the default casing table to it. //// void* pNativeTextInfo = m_pDefaultCasingTable; //// //// // Now, go thru the exception table to see if it has exception or not. //// for(int i = 0; i < m_exceptionCount; i++) //// { //// if(m_exceptionTable[i].langID == cultureID) //// { //// // This culture has exceptions. //// if(m_exceptionNativeTextInfo[i] == 0) //// { //// lock(InternalSyncObject) //// { //// // Read the exception casing file. //// if(m_pExceptionFile == null) //// { //// m_pExceptionFile = GlobalizationAssembly.GetGlobalizationResourceBytePtr( typeof( TextInfo ).Assembly, CASING_EXCEPTIONS_FILE_NAME ); //// } //// long tempPtr = (long)(InternalAllocateCasingTable( m_pExceptionFile, m_exceptionTable[i].exceptIndex )); //// System.Threading.Thread.MemoryBarrier(); //// m_exceptionNativeTextInfo[i] = tempPtr; //// } //// } //// pNativeTextInfo = (void*)m_exceptionNativeTextInfo[i]; //// break; //// } //// } //// return (pNativeTextInfo); //// //// } //// //// [ResourceExposure( ResourceScope.None )] //// [ResourceConsumption( ResourceScope.Process, ResourceScope.Process )] [MethodImplAttribute( MethodImplOptions.InternalCall )] internal static extern unsafe int CompareOrdinalIgnoreCase( String str1, String str2 ); //// { //// return (nativeCompareOrdinalIgnoreCase( InvariantNativeTextInfo, str1, str2 )); //// } //// //// // This function doesn't check arguments. Please do check in the caller. //// // The underlying unmanaged code will assert the sanity of arguments. //// [ResourceExposure( ResourceScope.None )] //// [ResourceConsumption( ResourceScope.Process, ResourceScope.Process )] //// internal static unsafe int CompareOrdinalIgnoreCaseEx( String strA, int indexA, String strB, int indexB, int length ) //// { //// return (nativeCompareOrdinalIgnoreCaseEx( InvariantNativeTextInfo, strA, indexA, strB, indexB, length )); //// } //// //// // This function doesn't check arguments. Please do check in the caller. //// // The underlying unmanaged code will assert the sanity of arguments. //// [ResourceExposure( ResourceScope.None )] //// [ResourceConsumption( ResourceScope.Process, ResourceScope.Process )] //// internal static unsafe int GetHashCodeOrdinalIgnoreCase( String s ) //// { //// return (nativeGetHashCodeOrdinalIgnoreCase( InvariantNativeTextInfo, s )); //// } //// //// [ResourceExposure( ResourceScope.None )] //// [ResourceConsumption( ResourceScope.Process, ResourceScope.Process )] //// internal static unsafe int IndexOfStringOrdinalIgnoreCase( String source, String value, int startIndex, int count ) //// { //// if(source == null) //// throw new ArgumentNullException( "source" ); //// //// return nativeIndexOfStringOrdinalIgnoreCase( InvariantNativeTextInfo, source, value, startIndex, count ); //// } //// //// [ResourceExposure( ResourceScope.None )] //// [ResourceConsumption( ResourceScope.Process, ResourceScope.Process )] //// internal static unsafe int LastIndexOfStringOrdinalIgnoreCase( String source, String value, int startIndex, int count ) //// { //// //// if(source == null) //// throw new ArgumentNullException( "source" ); //// //// return nativeLastIndexOfStringOrdinalIgnoreCase( InvariantNativeTextInfo, source, value, startIndex, count ); //// } //// //// //////////////////////////////////////////////////////////////////////// //// // //// // CodePage //// // //// // Returns the number of the code page used by this writing system. //// // The type parameter can be any of the following values: //// // ANSICodePage //// // OEMCodePage //// // MACCodePage //// // //// //////////////////////////////////////////////////////////////////////// //// //// //// public virtual int ANSICodePage //// { //// get //// { //// return (this.m_cultureTableRecord.IDEFAULTANSICODEPAGE); //// } //// } //// //// //// //// public virtual int OEMCodePage //// { //// get //// { //// return (this.m_cultureTableRecord.IDEFAULTOEMCODEPAGE); //// } //// } //// //// //// public virtual int MacCodePage //// { //// get //// { //// return (this.m_cultureTableRecord.IDEFAULTMACCODEPAGE); //// } //// } //// //// //// public virtual int EBCDICCodePage //// { //// get //// { //// return (this.m_cultureTableRecord.IDEFAULTEBCDICCODEPAGE); //// } //// } //// //// //// //////////////////////////////////////////////////////////////////////// //// // //// // LCID //// // //// // We need a way to get an LCID from outside of the BCL. This prop is the way. //// // //// // neutral cultures will cause GPS incorrect LCIDS from this //// //////////////////////////////////////////////////////////////////////// //// //// //// public int LCID //// { //// get //// { //// return (this.m_textInfoID); //// } //// } //// //// //////////////////////////////////////////////////////////////////////// //// // //// // CultureName //// // //// // The name of the culture from which the TextInfo was created. Even better than //// // the LCID since the LCID is not always unique (like in custom cultures). //// // //// //////////////////////////////////////////////////////////////////////// //// //// //// public string CultureName //// { //// get //// { //// if(null == this.m_name) //// { //// this.m_name = CultureInfo.GetCultureInfo( this.m_textInfoID ).Name; //// } //// //// return (this.m_name); //// } //// } //// //// //////////////////////////////////////////////////////////////////////// //// // //// // IsReadOnly //// // //// // Detect if the object is readonly. //// // //// //////////////////////////////////////////////////////////////////////// //// public bool IsReadOnly //// { //// get { return (m_isReadOnly); } //// } //// //// //////////////////////////////////////////////////////////////////////// //// // //// // Clone //// // //// // Is the implementation of IColnable. //// // //// //////////////////////////////////////////////////////////////////////// //// public virtual Object Clone() //// { //// object o = MemberwiseClone(); //// ((TextInfo)o).SetReadOnlyState( false ); //// return (o); //// } //// //// //////////////////////////////////////////////////////////////////////// //// // //// // ReadOnly //// // //// // Create a cloned readonly instance or return the input one if it is //// // readonly. //// // //// //////////////////////////////////////////////////////////////////////// //// public static TextInfo ReadOnly( TextInfo textInfo ) //// { //// if(textInfo == null) { throw new ArgumentNullException( "textInfo" ); } //// if(textInfo.IsReadOnly) { return (textInfo); } //// //// TextInfo clonedTextInfo = (TextInfo)(textInfo.MemberwiseClone()); //// clonedTextInfo.SetReadOnlyState( true ); //// //// return (clonedTextInfo); //// } //// //// private void VerifyWritable() //// { //// if(m_isReadOnly) //// { //// throw new InvalidOperationException( Environment.GetResourceString( "InvalidOperation_ReadOnly" ) ); //// } //// } //// //// internal void SetReadOnlyState( bool readOnly ) //// { //// m_isReadOnly = readOnly; //// } //// //// //// //////////////////////////////////////////////////////////////////////// //// // //// // ListSeparator //// // //// // Returns the string used to separate items in a list. //// // //// //////////////////////////////////////////////////////////////////////// //// //// //// public virtual String ListSeparator //// { //// get //// { //// if(m_listSeparator == null) //// { //// m_listSeparator = this.m_cultureTableRecord.SLIST; //// } //// return (m_listSeparator); //// } //// //// set //// { //// VerifyWritable(); //// if(value == null) //// { //// throw new ArgumentNullException( "value", Environment.GetResourceString( "ArgumentNull_String" ) ); //// } //// m_listSeparator = value; //// } //// } //// //// internal TextInfo CasingTextInfo //// { //// get //// { //// if(m_casingTextInfo == null) //// { //// if(ANSICodePage == TurkishAnsiCodepage) //// { //// // Turkish cultures have different uppercase and lowercase for 'i' and 'I' characters. so we need //// // to treat it as special case. //// m_casingTextInfo = CultureInfo.GetCultureInfo( "tr-TR" ).TextInfo; //// } //// else //// { //// m_casingTextInfo = CultureInfo.GetCultureInfo( "en-US" ).TextInfo; //// } //// } //// //// return m_casingTextInfo; //// } //// } //////////////////////////////////////////////////////////////////////// // // ToLower // // Converts the character or string to lower case. Certain locales // have different casing semantics from the file systems in Win32. // //////////////////////////////////////////////////////////////////////// [MethodImplAttribute( MethodImplOptions.InternalCall )] public unsafe extern virtual char ToLower( char c ); //// { //// return (nativeChangeCaseChar( m_textInfoID, m_pNativeTextInfo, c, false )); //// } [MethodImplAttribute( MethodImplOptions.InternalCall )] public unsafe extern virtual String ToLower( String str ); //// { //// if(str == null) { throw new ArgumentNullException( "str" ); } //// //// return (nativeChangeCaseString( m_textInfoID, m_pNativeTextInfo, str, false )); //// } //////////////////////////////////////////////////////////////////////// // // ToUpper // // Converts the character or string to upper case. Certain locales // have different casing semantics from the file systems in Win32. // //////////////////////////////////////////////////////////////////////// [MethodImplAttribute( MethodImplOptions.InternalCall )] public unsafe extern virtual char ToUpper( char c ); //// { //// return (nativeChangeCaseChar( m_textInfoID, m_pNativeTextInfo, c, true )); //// } [MethodImplAttribute( MethodImplOptions.InternalCall )] public unsafe extern virtual String ToUpper( String str ); //// { //// if(str == null) { throw new ArgumentNullException( "str" ); } //// //// return (nativeChangeCaseString( m_textInfoID, m_pNativeTextInfo, str, true )); //// } //// //////////////////////////////////////////////////////////////////////// //// // //// // Equals //// // //// // Implements Object.Equals(). Returns a boolean indicating whether //// // or not object refers to the same CultureInfo as the current instance. //// // //// //////////////////////////////////////////////////////////////////////// //// //// //// public override bool Equals( Object obj ) //// { //// TextInfo that = obj as TextInfo; //// //// if(that != null) //// { //// return this.CultureName.Equals( that.CultureName ); //// } //// //// return (false); //// } //// //// //// //////////////////////////////////////////////////////////////////////// //// // //// // GetHashCode //// // //// // Implements Object.GetHashCode(). Returns the hash code for the //// // CultureInfo. The hash code is guaranteed to be the same for CultureInfo A //// // and B where A.Equals(B) is true. //// // //// //////////////////////////////////////////////////////////////////////// //// //// //// public override int GetHashCode() //// { //// return (this.CultureName.GetHashCode()); //// } //// //// //// //////////////////////////////////////////////////////////////////////// //// // //// // ToString //// // //// // Implements Object.ToString(). Returns a string describing the //// // TextInfo. //// // //// //////////////////////////////////////////////////////////////////////// //// //// //// public override String ToString() //// { //// return ("TextInfo - " + this.m_textInfoID); //// } //// //// // //// // Used in ToTitleCase(): //// // When we find a starting letter, the following array decides if a category should be //// // considered as word seprator or not. //// // //// private const int wordSeparatorMask = //// /* false */ (0 << 0) | // UppercaseLetter = 0, //// /* false */ (0 << 1) | // LowercaseLetter = 1, //// /* false */ (0 << 2) | // TitlecaseLetter = 2, //// /* false */ (0 << 3) | // ModifierLetter = 3, //// /* false */ (0 << 4) | // OtherLetter = 4, //// /* false */ (0 << 5) | // NonSpacingMark = 5, //// /* false */ (0 << 6) | // SpacingCombiningMark = 6, //// /* false */ (0 << 7) | // EnclosingMark = 7, //// /* false */ (0 << 8) | // DecimalDigitNumber = 8, //// /* false */ (0 << 9) | // LetterNumber = 9, //// /* false */ (0 << 10) | // OtherNumber = 10, //// /* true */ (1 << 11) | // SpaceSeparator = 11, //// /* true */ (1 << 12) | // LineSeparator = 12, //// /* true */ (1 << 13) | // ParagraphSeparator = 13, //// /* true */ (1 << 14) | // Control = 14, //// /* true */ (1 << 15) | // Format = 15, //// /* false */ (0 << 16) | // Surrogate = 16, //// /* false */ (0 << 17) | // PrivateUse = 17, //// /* true */ (1 << 18) | // ConnectorPunctuation = 18, //// /* true */ (1 << 19) | // DashPunctuation = 19, //// /* true */ (1 << 20) | // OpenPunctuation = 20, //// /* true */ (1 << 21) | // ClosePunctuation = 21, //// /* true */ (1 << 22) | // InitialQuotePunctuation = 22, //// /* true */ (1 << 23) | // FinalQuotePunctuation = 23, //// /* true */ (1 << 24) | // OtherPunctuation = 24, //// /* true */ (1 << 25) | // MathSymbol = 25, //// /* true */ (1 << 26) | // CurrencySymbol = 26, //// /* true */ (1 << 27) | // ModifierSymbol = 27, //// /* true */ (1 << 28) | // OtherSymbol = 28, //// /* false */ (0 << 29); // OtherNotAssigned = 29; //// //// private bool IsWordSeparator( UnicodeCategory category ) //// { //// return (wordSeparatorMask & (1 << (int)category)) != 0; //// } //// //// // Returns the mapping of the specified string to title case. Note that the //// // returned string may differ in length from the input string. //// // Generally, the first character of every word in str is uppercased. //// // For titlecase characters, they are uppercased in a specail way. //// //// internal const int TurkishAnsiCodepage = 1254; //// //// public unsafe String ToTitleCase( String str ) //// { //// if(str == null) //// { //// throw new ArgumentNullException( "str" ); //// } //// //// int len = str.Length; //// if(len == 0) //// { //// return (str); //// } //// //// int i; //// StringBuilder result = new StringBuilder(); //// String lowercaseData = null; //// //// for(i = 0; i < len; i++) //// { //// UnicodeCategory charType; //// int charLen; //// //// charType = CharUnicodeInfo.InternalGetUnicodeCategory( str, i, out charLen ); //// if(Char.CheckLetter( charType )) //// { //// // Do the uppercasing for the first character of the word. //// // There are titlecase characters that need to be special treated. //// //// if(charLen == 1) //// { //// result.Append( nativeGetTitleCaseChar( m_pNativeTextInfo, str[i] ) ); //// } //// else //// { //// // //// // ASSUMPTION: There is no titlecase char in the surrogate. //// // //// char resultHighSurrogate; //// char resultLowSurrogate; //// //// ChangeCaseSurrogate( str[i], str[i + 1], out resultHighSurrogate, out resultLowSurrogate, true ); //// result.Append( resultHighSurrogate ); //// result.Append( resultLowSurrogate ); //// } //// i += charLen; //// //// // //// // Convert the characters until the end of the this word //// // to lowercase. //// // //// int lowercaseStart = i; //// //// // //// // Use hasLowerCase flag to prevent from lowercasing acronyms (like "URT", "USA", etc) //// // This is in line with Word 2000 behavior of titilecasing. //// // //// bool hasLowerCase = (charType == UnicodeCategory.LowercaseLetter); //// // Use a loop to find all of the other letters following this letter. //// while(i < len) //// { //// charType = CharUnicodeInfo.InternalGetUnicodeCategory( str, i, out charLen ); //// if(IsLetterCategory( charType )) //// { //// if(charType == UnicodeCategory.LowercaseLetter) //// { //// hasLowerCase = true; //// } //// i += charLen; //// } //// else if(str[i] == '\'') //// { //// // Special case for APOSTROPHE. It should be considered part of the word. E.g. "can't". //// i++; //// if(hasLowerCase) //// { //// if(lowercaseData == null) //// { //// lowercaseData = this.ToLower( str ); //// } //// result.Append( lowercaseData, lowercaseStart, i - lowercaseStart ); //// } //// else //// { //// result.Append( str, lowercaseStart, i - lowercaseStart ); //// } //// lowercaseStart = i; //// hasLowerCase = true; //// } //// else if(!IsWordSeparator( charType )) //// { //// // This category is considered to be part of the word. //// // This is any category that is marked as false in wordSeprator array. //// i += charLen; //// } //// else //// { //// // A word separator. Break out of the loop. //// break; //// } //// } //// //// int count = i - lowercaseStart; //// //// if(count > 0) //// { //// if(hasLowerCase) //// { //// if(lowercaseData == null) //// { //// lowercaseData = this.ToLower( str ); //// } //// result.Append( lowercaseData, lowercaseStart, count ); //// } //// else //// { //// result.Append( str, lowercaseStart, count ); //// } //// } //// //// if(i < len) //// { //// // Add the non-letter character. //// if(charLen == 1) //// { //// result.Append( str[i] ); //// } //// else //// { //// // Surrogate. //// result.Append( str[i++] ); //// result.Append( str[i] ); //// } //// } //// } //// else //// { //// // //// // Not a letter, just append them. //// // //// if(charLen == 1) //// { //// result.Append( str[i] ); //// } //// else //// { //// // Surrogate. //// result.Append( str[i++] ); //// result.Append( str[i] ); //// } //// } //// } //// return (result.ToString()); //// } //// //// // The dominant direction of text and UI such as the relative position of buttons and scroll bars. //// //// //// public bool IsRightToLeft //// { //// get //// { //// // The highest bit indicates writing order for left-to-right (0) or right-to-left (1) //// return ((this.m_cultureTableRecord.ILINEORIENTATIONS & 0x8000) != 0); //// } //// } //// //// private bool IsLetterCategory( UnicodeCategory uc ) //// { //// return (uc == UnicodeCategory.UppercaseLetter //// || uc == UnicodeCategory.LowercaseLetter //// || uc == UnicodeCategory.TitlecaseLetter //// || uc == UnicodeCategory.ModifierLetter //// || uc == UnicodeCategory.OtherLetter); //// } //// //// /// //// void IDeserializationCallback.OnDeserialization( Object sender ) //// { //// OnDeserialized(); //// } //// //// // //// // Get case-insensitive hash code for the specified string. //// // //// // NOTENOTE: this is an internal function. The caller should verify the string //// // is not null before calling this. Currenlty, CaseInsensitiveHashCodeProvider //// // does that. //// // //// internal unsafe int GetCaseInsensitiveHashCode( String str ) //// { //// // This must be called to guarantee m_pNativeTextInfo is initialized. //// // The reason is that the order of calling OnDeserializtion on dependent //// // objects are not guaranteed, so a class using //// // TextInfo class (Hashtable is an example) will have problems in //// // its deserializtion process if methods of TextInfo class is called in the //// // deserialization process. //// // //// //// if(str == null) //// { //// throw new ArgumentNullException( "str" ); //// } //// //// if(m_pNativeTextInfo == null) //// { //// OnDeserialized(); //// } //// //// // This is the fix to avoid introduce //// // a dependency on mscorlib.dll and mscorwks.dll, which the real fix needs. //// // By doing this, we will do uppercase twice for Turkish/Azeri, so it is slower //// // in these two cultures. The benefit is that we only have to do the fix in the managed side. //// switch(m_textInfoID) //// { //// case 0x041f: // Turkish //// case 0x042c: // Azeri //// // Uppercase the specified characters. //// str = nativeChangeCaseString( m_textInfoID, m_pNativeTextInfo, str, true ); //// break; //// } //// return (nativeGetCaseInsHash( str, m_pNativeTextInfo )); //// // A better fix is to exam the m_wing32LangID and the high-char state in the native side to decide if we can do "fast hashing". //// //return nativeGetCaseInsHash(m_textInfoID, str, m_pNativeTextInfo); //// //// } //// //// // A thin wrapper to avoid us to mark ToTitleCase() as unsafe. //// internal unsafe void ChangeCaseSurrogate( char highSurrogate, char lowSurrogate, out char resultHighSurrogate, out char resultLowSurrogate, bool isToUpper ) //// { //// fixed(char* pResultChar1 = &resultHighSurrogate, pResultChar2 = &resultLowSurrogate) //// { //// nativeChangeCaseSurrogate( m_pNativeTextInfo, highSurrogate, lowSurrogate, pResultChar1, pResultChar2, isToUpper ); //// } //// } //// //// //This method requires synchronization and should only be called from the Class Initializer. //// [ResourceExposure( ResourceScope.Process )] //// [MethodImplAttribute( MethodImplOptions.InternalCall )] //// private static unsafe extern void* AllocateDefaultCasingTable( byte* ptr ); //// //// //This method requires synchronization and should only be called from the Class Initializer. //// [ResourceExposure( ResourceScope.None )] //// [MethodImplAttribute( MethodImplOptions.InternalCall )] //// private static unsafe extern void* nativeGetInvariantTextInfo(); //// //// [ResourceExposure( ResourceScope.Process )] //// [MethodImplAttribute( MethodImplOptions.InternalCall )] //// private static unsafe extern void* InternalAllocateCasingTable( byte* ptr, int exceptionIndex ); //// //// [ResourceExposure( ResourceScope.None )] //// [MethodImplAttribute( MethodImplOptions.InternalCall )] //// private static unsafe extern int nativeGetCaseInsHash( String str, void* pNativeTextInfo ); //// // private static extern int nativeGetCaseInsHash(int win32LangID, String str, void* pNativeTextInfo); //// //// [ResourceExposure( ResourceScope.None )] //// [MethodImplAttribute( MethodImplOptions.InternalCall )] //// private static unsafe extern char nativeGetTitleCaseChar( void* pNativeTextInfo, char ch ); //// //// [ResourceExposure( ResourceScope.None )] //// [MethodImplAttribute( MethodImplOptions.InternalCall )] //// internal static unsafe extern char nativeChangeCaseChar( int win32LangID, void* pNativeTextInfo, char ch, bool isToUpper ); //// [ResourceExposure( ResourceScope.None )] //// [MethodImplAttribute( MethodImplOptions.InternalCall )] //// internal static unsafe extern String nativeChangeCaseString( int win32LangID, void* pNativeTextInfo, String str, bool isToUpper ); //// //// [ResourceExposure( ResourceScope.None )] //// [MethodImplAttribute( MethodImplOptions.InternalCall )] //// internal static unsafe extern void nativeChangeCaseSurrogate( void* pNativeTextInfo, char highSurrogate, char lowSurrogate, char* resultHighSurrogate, char* resultLowSurrogate, bool isToUpper ); //// //// [ResourceExposure( ResourceScope.None )] //// [MethodImplAttribute( MethodImplOptions.InternalCall )] //// private static unsafe extern int nativeCompareOrdinalIgnoreCase( void* pNativeTextInfo, String str1, String str2 ); //// //// [ResourceExposure( ResourceScope.None )] //// [MethodImplAttribute( MethodImplOptions.InternalCall )] //// private static unsafe extern int nativeCompareOrdinalIgnoreCaseEx( void* pNativeTextInfo, String strA, int indexA, String strB, int indexB, int length ); //// //// [ResourceExposure( ResourceScope.None )] //// [MethodImplAttribute( MethodImplOptions.InternalCall )] //// private static unsafe extern int nativeGetHashCodeOrdinalIgnoreCase( void* pNativeTextInfo, String s ); //// //// //// [ResourceExposure( ResourceScope.None )] //// [MethodImplAttribute( MethodImplOptions.InternalCall )] //// private static unsafe extern int nativeIndexOfStringOrdinalIgnoreCase( void* pNativeTextInfo, String str, String value, int startIndex, int count ); //// //// [ResourceExposure( ResourceScope.None )] //// [MethodImplAttribute( MethodImplOptions.InternalCall )] //// private static unsafe extern int nativeLastIndexOfStringOrdinalIgnoreCase( void* pNativeTextInfo, String str, String value, int startIndex, int count ); //// //// [ResourceExposure( ResourceScope.None )] //// [MethodImplAttribute( MethodImplOptions.InternalCall )] //// internal static unsafe extern int nativeIndexOfCharOrdinalIgnoreCase( void* pNativeTextInfo, String str, Char value, int startIndex, int count ); //// //// [ResourceExposure( ResourceScope.None )] //// [MethodImplAttribute( MethodImplOptions.InternalCall )] //// internal static unsafe extern int nativeLastIndexOfCharOrdinalIgnoreCase( void* pNativeTextInfo, String str, Char value, int startIndex, int count ); } } ================================================ FILE: Zelig/Zelig/RunTime/Framework/mscorlib/System/Guid.cs ================================================ // ==++== // // Copyright (c) Microsoft Corporation. All rights reserved. // // ==--== namespace System { using System; using System.Globalization; using System.Text; ////using Microsoft.Win32; using System.Runtime.InteropServices; using System.Runtime.CompilerServices; // Represents a Globally Unique Identifier. [Serializable] [StructLayout( LayoutKind.Sequential )] public struct Guid : /*IFormattable,*/ IComparable, IComparable< Guid >, IEquatable< Guid > { public static readonly Guid Empty = new Guid(); //////////////////////////////////////////////////////////////////////////////// // Member variables //////////////////////////////////////////////////////////////////////////////// private int _a; private short _b; private short _c; private byte _d; private byte _e; private byte _f; private byte _g; private byte _h; private byte _i; private byte _j; private byte _k; //////////////////////////////////////////////////////////////////////////////// // Constructors //////////////////////////////////////////////////////////////////////////////// // Creates a new guid from an array of bytes. // public Guid( byte[] b ) { if(b == null) { #if EXCEPTION_STRINGS throw new ArgumentNullException( "b" ); #else throw new ArgumentNullException(); #endif } if(b.Length != 16) { #if EXCEPTION_STRINGS throw new ArgumentException( String.Format( CultureInfo.CurrentCulture, Environment.GetResourceString( "Arg_GuidArrayCtor" ), "16" ) ); #else throw new ArgumentException(); #endif } _a = ((int)b[3] << 24) | ((int)b[2] << 16) | ((int)b[1] << 8) | b[0]; _b = (short)(((int)b[5] << 8) | b[4]); _c = (short)(((int)b[7] << 8) | b[6]); _d = b[8]; _e = b[9]; _f = b[10]; _g = b[11]; _h = b[12]; _i = b[13]; _j = b[14]; _k = b[15]; } [CLSCompliant( false )] public Guid( uint a , ushort b , ushort c , byte d , byte e , byte f , byte g , byte h , byte i , byte j , byte k ) { _a = (int)a; _b = (short)b; _c = (short)c; _d = d; _e = e; _f = f; _g = g; _h = h; _i = i; _j = j; _k = k; } //// // Creates a new guid based on the value in the string. The value is made up //// // of hex digits speared by the dash ("-"). The string may begin and end with //// // brackets ("{", "}"). //// // //// // The string must be of the form dddddddd-dddd-dddd-dddd-dddddddddddd. where //// // d is a hex digit. (That is 8 hex digits, followed by 4, then 4, then 4, //// // then 12) such as: "CA761232-ED42-11CE-BACD-00AA0057B223" //// // //// public Guid( String g ) //// { //// if(g == null) //// { //// throw new ArgumentNullException( "g" ); //// } //// //// int startPos = 0; //// int temp; //// long templ; //// int currentPos = 0; //// //// try //// { //// // Check if it's of the form dddddddd-dddd-dddd-dddd-dddddddddddd //// if(g.IndexOf( '-', 0 ) >= 0) //// { //// //// String guidString = g.Trim(); //Remove Whitespace //// //// // check to see that it's the proper length //// if(guidString[0] == '{') //// { //// if(guidString.Length != 38 || guidString[37] != '}') //// { //// throw new FormatException( Environment.GetResourceString( "Format_GuidInvLen" ) ); //// } //// startPos = 1; //// } //// else if(guidString[0] == '(') //// { //// if(guidString.Length != 38 || guidString[37] != ')') //// { //// throw new FormatException( Environment.GetResourceString( "Format_GuidInvLen" ) ); //// } //// startPos = 1; //// } //// else if(guidString.Length != 36) //// { //// throw new FormatException( Environment.GetResourceString( "Format_GuidInvLen" ) ); //// } //// if(guidString[8 + startPos] != '-' || //// guidString[13 + startPos] != '-' || //// guidString[18 + startPos] != '-' || //// guidString[23 + startPos] != '-') //// { //// throw new FormatException( Environment.GetResourceString( "Format_GuidDashes" ) ); //// } //// //// currentPos = startPos; //// _a = TryParse( guidString, ref currentPos, 8 ); //// ++currentPos; //Increment past the '-'; //// _b = (short)TryParse( guidString, ref currentPos, 4 ); //// ++currentPos; //Increment past the '-'; //// _c = (short)TryParse( guidString, ref currentPos, 4 ); //// ++currentPos; //Increment past the '-'; //// temp = TryParse( guidString, ref currentPos, 4 ); //// ++currentPos; //Increment past the '-'; //// startPos = currentPos; //// templ = ParseNumbers.StringToLong( guidString, 16, ParseNumbers.NoSpace, ref currentPos ); //// if(currentPos - startPos != 12) //// { //// throw new FormatException( String.Format( CultureInfo.CurrentCulture, Environment.GetResourceString( "Format_GuidInvLen" ) ) ); //// } //// _d = (byte)(temp >> 8); //// _e = (byte)(temp); //// temp = (int)(templ >> 32); //// _f = (byte)(temp >> 8); //// _g = (byte)(temp); //// temp = (int)(templ); //// _h = (byte)(temp >> 24); //// _i = (byte)(temp >> 16); //// _j = (byte)(temp >> 8); //// _k = (byte)(temp); //// } //// // Else check if it is of the form //// // {0xdddddddd,0xdddd,0xdddd,{0xdd,0xdd,0xdd,0xdd,0xdd,0xdd,0xdd,0xdd}} //// else if(g.IndexOf( '{', 0 ) >= 0) //// { //// int numStart = 0; //// int numLen = 0; //// //// // Convert to lower case //// //g = g.ToLower(); //// //// // Eat all of the whitespace //// g = EatAllWhitespace( g ); //// //// // Check for leading '{' //// if(g[0] != '{') //// throw new FormatException( Environment.GetResourceString( "Format_GuidBrace" ) ); //// //// // Check for '0x' //// if(!IsHexPrefix( g, 1 )) //// throw new FormatException( String.Format( CultureInfo.CurrentCulture, Environment.GetResourceString( "Format_GuidHexPrefix" ), "{0xdddddddd, etc}" ) ); //// //// // Find the end of this hex number (since it is not fixed length) //// numStart = 3; //// numLen = g.IndexOf( ',', numStart ) - numStart; //// if(numLen <= 0) //// throw new FormatException( Environment.GetResourceString( "Format_GuidComma" ) ); //// //// // Read in the number //// _a = (int)ParseNumbers.StringToInt( g.Substring( numStart, numLen ), // first DWORD //// 16, // hex //// ParseNumbers.IsTight ); // tight parsing //// //// // Check for '0x' //// if(!IsHexPrefix( g, numStart + numLen + 1 )) //// throw new FormatException( String.Format( CultureInfo.CurrentCulture, Environment.GetResourceString( "Format_GuidHexPrefix" ), "{0xdddddddd, 0xdddd, etc}" ) ); //// //// // +3 to get by ',0x' //// numStart = numStart + numLen + 3; //// numLen = g.IndexOf( ',', numStart ) - numStart; //// if(numLen <= 0) //// throw new FormatException( Environment.GetResourceString( "Format_GuidComma" ) ); //// //// // Read in the number //// _b = (short)ParseNumbers.StringToInt( //// g.Substring( numStart, numLen ), // first DWORD //// 16, // hex //// ParseNumbers.IsTight ); // tight parsing //// //// // Check for '0x' //// if(!IsHexPrefix( g, numStart + numLen + 1 )) //// throw new FormatException( String.Format( CultureInfo.CurrentCulture, Environment.GetResourceString( "Format_GuidHexPrefix" ), "{0xdddddddd, 0xdddd, 0xdddd, etc}" ) ); //// //// // +3 to get by ',0x' //// numStart = numStart + numLen + 3; //// numLen = g.IndexOf( ',', numStart ) - numStart; //// if(numLen <= 0) //// throw new FormatException( Environment.GetResourceString( "Format_GuidComma" ) ); //// //// // Read in the number //// _c = (short)ParseNumbers.StringToInt( //// g.Substring( numStart, numLen ), // first DWORD //// 16, // hex //// ParseNumbers.IsTight ); // tight parsing //// //// // Check for '{' //// if(g.Length <= numStart + numLen + 1 || g[numStart + numLen + 1] != '{') //// throw new FormatException( Environment.GetResourceString( "Format_GuidBrace" ) ); //// //// // Prepare for loop //// numLen++; //// byte[] bytes = new byte[8]; //// //// for(int i = 0; i < 8; i++) //// { //// // Check for '0x' //// if(!IsHexPrefix( g, numStart + numLen + 1 )) //// throw new FormatException( String.Format( CultureInfo.CurrentCulture, Environment.GetResourceString( "Format_GuidHexPrefix" ), "{... { ... 0xdd, ...}}" ) ); //// //// // +3 to get by ',0x' or '{0x' for first case //// numStart = numStart + numLen + 3; //// //// // Calculate number length //// if(i < 7) // first 7 cases //// { //// numLen = g.IndexOf( ',', numStart ) - numStart; //// if(numLen <= 0) //// { //// throw new FormatException( Environment.GetResourceString( "Format_GuidComma" ) ); //// } //// } //// else // last case ends with '}', not ',' //// { //// numLen = g.IndexOf( '}', numStart ) - numStart; //// if(numLen <= 0) //// { //// throw new FormatException( Environment.GetResourceString( "Format_GuidBraceAfterLastNumber" ) ); //// } //// } //// //// // Read in the number //// uint number = (uint)Convert.ToInt32( g.Substring( numStart, numLen ), 16 ); //// // check for overflow //// if(number > 255) //// { //// throw new FormatException( Environment.GetResourceString( "Overflow_Byte" ) ); //// } //// bytes[i] = (byte)number; //// } //// //// _d = bytes[0]; //// _e = bytes[1]; //// _f = bytes[2]; //// _g = bytes[3]; //// _h = bytes[4]; //// _i = bytes[5]; //// _j = bytes[6]; //// _k = bytes[7]; //// //// // Check for last '}' //// if(numStart + numLen + 1 >= g.Length || g[numStart + numLen + 1] != '}') //// { //// throw new FormatException( Environment.GetResourceString( "Format_GuidEndBrace" ) ); //// } //// //// // Check if we have extra characters at the end //// if(numStart + numLen + 1 != g.Length - 1) //// { //// throw new FormatException( Environment.GetResourceString( "Format_ExtraJunkAtEnd" ) ); //// } //// //// return; //// } //// else //// // Check if it's of the form dddddddddddddddddddddddddddddddd //// { //// String guidString = g.Trim(); //Remove Whitespace //// //// if(guidString.Length != 32) //// { //// throw new FormatException( Environment.GetResourceString( "Format_GuidInvLen" ) ); //// } //// //// for(int i = 0; i < guidString.Length; i++) //// { //// char ch = guidString[i]; //// if(ch >= '0' && ch <= '9') //// { //// continue; //// } //// else //// { //// char upperCaseCh = Char.ToUpper( ch, CultureInfo.InvariantCulture ); //// if(upperCaseCh >= 'A' && upperCaseCh <= 'F') //// { //// continue; //// } //// } //// //// throw new FormatException( Environment.GetResourceString( "Format_GuidInvalidChar" ) ); //// } //// //// _a = (int)ParseNumbers.StringToInt( guidString.Substring( startPos, 8 ), // first DWORD //// 16, // hex //// ParseNumbers.IsTight ); // tight parsing //// startPos += 8; //// _b = (short)ParseNumbers.StringToInt( guidString.Substring( startPos, 4 ), //// 16, //// ParseNumbers.IsTight ); //// startPos += 4; //// _c = (short)ParseNumbers.StringToInt( guidString.Substring( startPos, 4 ), //// 16, //// ParseNumbers.IsTight ); //// //// startPos += 4; //// temp = (short)ParseNumbers.StringToInt( guidString.Substring( startPos, 4 ), //// 16, //// ParseNumbers.IsTight ); //// startPos += 4; //// currentPos = startPos; //// templ = ParseNumbers.StringToLong( guidString, 16, startPos, ref currentPos ); //// if(currentPos - startPos != 12) //// { //// throw new FormatException( String.Format( CultureInfo.CurrentCulture, Environment.GetResourceString( "Format_GuidInvLen" ) ) ); //// } //// _d = (byte)(temp >> 8); //// _e = (byte)(temp); //// temp = (int)(templ >> 32); //// _f = (byte)(temp >> 8); //// _g = (byte)(temp); //// temp = (int)(templ); //// _h = (byte)(temp >> 24); //// _i = (byte)(temp >> 16); //// _j = (byte)(temp >> 8); //// _k = (byte)(temp); //// } //// } //// catch(IndexOutOfRangeException) //// { //// throw new FormatException( Environment.GetResourceString( "Format_GuidUnrecognized" ) ); //// } //// } //// //// // Creates a new GUID initialized to the value represented by the arguments. //// // //// public Guid( int a, short b, short c, byte[] d ) //// { //// if(d == null) //// throw new ArgumentNullException( "d" ); //// // Check that array is not too big //// if(d.Length != 8) //// throw new ArgumentException( String.Format( CultureInfo.CurrentCulture, Environment.GetResourceString( "Arg_GuidArrayCtor" ), "8" ) ); //// //// _a = a; //// _b = b; //// _c = c; //// _d = d[0]; //// _e = d[1]; //// _f = d[2]; //// _g = d[3]; //// _h = d[4]; //// _i = d[5]; //// _j = d[6]; //// _k = d[7]; //// } // Creates a new GUID initialized to the value represented by the // arguments. The bytes are specified like this to avoid endianness issues. // public Guid( int a , short b , short c , byte d , byte e , byte f , byte g , byte h , byte i , byte j , byte k ) { _a = a; _b = b; _c = c; _d = d; _e = e; _f = f; _g = g; _h = h; _i = i; _j = j; _k = k; } //// private static int TryParse( String str, ref int parsePos, int requiredLength ) //// { //// int currStart = parsePos; //// // the exception message from ParseNumbers is better //// int retVal = ParseNumbers.StringToInt( str, 16, ParseNumbers.NoSpace, ref parsePos ); //// //// //If we didn't parse enough characters, there's clearly an error. //// if(parsePos - currStart != requiredLength) //// { //// throw new FormatException( Environment.GetResourceString( "Format_GuidInvalidChar" ) ); //// } //// return retVal; //// } //// //// private static String EatAllWhitespace( String str ) //// { //// int newLength = 0; //// char[] chArr = new char[str.Length]; //// char curChar; //// //// // Now get each char from str and if it is not whitespace add it to chArr //// for(int i = 0; i < str.Length; i++) //// { //// curChar = str[i]; //// if(!Char.IsWhiteSpace( curChar )) //// { //// chArr[newLength++] = curChar; //// } //// } //// //// // Return a new string based on chArr //// return new String( chArr, 0, newLength ); //// } //// //// private static bool IsHexPrefix( String str, int i ) //// { //// if(str[i] == '0' && (Char.ToLower( str[i + 1], CultureInfo.InvariantCulture ) == 'x')) //// return true; //// else //// return false; //// } // Returns an unsigned byte array containing the GUID. public byte[] ToByteArray() { byte[] g = new byte[16]; g[0] = (byte)(_a); g[1] = (byte)(_a >> 8); g[2] = (byte)(_a >> 16); g[3] = (byte)(_a >> 24); g[4] = (byte)(_b); g[5] = (byte)(_b >> 8); g[6] = (byte)(_c); g[7] = (byte)(_c >> 8); g[8] = _d; g[9] = _e; g[10] = _f; g[11] = _g; g[12] = _h; g[13] = _i; g[14] = _j; g[15] = _k; return g; } //// // Returns the guid in "registry" format. //// public override String ToString() //// { //// return ToString( "D", null ); //// } public override int GetHashCode() { return _a ^ (((int)_b << 16) | (int)(ushort)_c) ^ (((int)_f << 24) | _k); } // Returns true if and only if the guid represented // by o is the same as this instance. public override bool Equals( Object o ) { // Check that o is a Guid first if(o == null || !(o is Guid)) { return false; } return Equals( (Guid)o ); } public bool Equals( Guid g ) { // Now compare each of the elements if(g._a != _a) return false; if(g._b != _b) return false; if(g._c != _c) return false; if(g._d != _d) return false; if(g._e != _e) return false; if(g._f != _f) return false; if(g._g != _g) return false; if(g._h != _h) return false; if(g._i != _i) return false; if(g._j != _j) return false; if(g._k != _k) return false; return true; } private int GetResult( uint me, uint them ) { if(me < them) { return -1; } return 1; } public int CompareTo( Object value ) { if(value == null) { return 1; } if(!(value is Guid)) { #if EXCEPTION_STRINGS throw new ArgumentException( Environment.GetResourceString( "Arg_MustBeGuid" ) ); #else throw new ArgumentException(); #endif } return CompareTo( (Guid)value ); } public int CompareTo(Guid value) { if (value._a!=this._a) { return GetResult((uint)this._a, (uint)value._a); } if (value._b!=this._b) { return GetResult((uint)this._b, (uint)value._b); } if (value._c!=this._c) { return GetResult((uint)this._c, (uint)value._c); } if (value._d!=this._d) { return GetResult((uint)this._d, (uint)value._d); } if (value._e!=this._e) { return GetResult((uint)this._e, (uint)value._e); } if (value._f!=this._f) { return GetResult((uint)this._f, (uint)value._f); } if (value._g!=this._g) { return GetResult((uint)this._g, (uint)value._g); } if (value._h!=this._h) { return GetResult((uint)this._h, (uint)value._h); } if (value._i!=this._i) { return GetResult((uint)this._i, (uint)value._i); } if (value._j!=this._j) { return GetResult((uint)this._j, (uint)value._j); } if (value._k!=this._k) { return GetResult((uint)this._k, (uint)value._k); } return 0; } public static bool operator ==( Guid a, Guid b ) { // Now compare each of the elements if(a._a != b._a) return false; if(a._b != b._b) return false; if(a._c != b._c) return false; if(a._d != b._d) return false; if(a._e != b._e) return false; if(a._f != b._f) return false; if(a._g != b._g) return false; if(a._h != b._h) return false; if(a._i != b._i) return false; if(a._j != b._j) return false; if(a._k != b._k) return false; return true; } public static bool operator !=( Guid a, Guid b ) { return !(a == b); } // This will create a new guid. Since we've now decided that constructors should 0-init, // we need a method that allows users to create a guid. public static Guid NewGuid() { //// Guid guid; //// Marshal.ThrowExceptionForHR( Win32Native.CoCreateGuid( out guid ), new IntPtr( -1 ) ); //// return guid; byte[] buf = new byte[16]; Random rnd = new Random(); rnd.NextBytes( buf ); return new Guid( buf ); } //// public String ToString( String format ) //// { //// return ToString( format, null ); //// } //// //// private static char HexToChar( int a ) //// { //// a = a & 0xf; //// return (char)((a > 9) ? a - 10 + 0x61 : a + 0x30); //// } //// //// private static int HexsToChars( char[] guidChars, int offset, int a, int b ) //// { //// guidChars[offset++] = HexToChar( a >> 4 ); //// guidChars[offset++] = HexToChar( a ); //// guidChars[offset++] = HexToChar( b >> 4 ); //// guidChars[offset++] = HexToChar( b ); //// return offset; //// } //// //// // IFormattable interface //// // We currently ignore provider //// public String ToString( String format, IFormatProvider provider ) //// { //// if(format == null || format.Length == 0) //// format = "D"; //// //// char[] guidChars; //// int offset = 0; //// int strLength = 38; //// bool dash = true; //// //// if(format.Length != 1) //// { //// // all acceptable format string are of length 1 //// throw new FormatException( Environment.GetResourceString( "Format_InvalidGuidFormatSpecification" ) ); //// } //// //// char formatCh = format[0]; //// if(formatCh == 'D' || formatCh == 'd') //// { //// guidChars = new char[36]; //// strLength = 36; //// } //// else if(formatCh == 'N' || formatCh == 'n') //// { //// guidChars = new char[32]; //// strLength = 32; //// dash = false; //// } //// else if(formatCh == 'B' || formatCh == 'b') //// { //// guidChars = new char[38]; //// guidChars[offset++] = '{'; //// guidChars[37] = '}'; //// } //// else if(formatCh == 'P' || formatCh == 'p') //// { //// guidChars = new char[38]; //// guidChars[offset++] = '('; //// guidChars[37] = ')'; //// } //// else //// { //// throw new FormatException( Environment.GetResourceString( "Format_InvalidGuidFormatSpecification" ) ); //// } //// //// offset = HexsToChars( guidChars, offset, _a >> 24, _a >> 16 ); //// offset = HexsToChars( guidChars, offset, _a >> 8, _a ); //// //// if(dash) guidChars[offset++] = '-'; //// //// offset = HexsToChars( guidChars, offset, _b >> 8, _b ); //// //// if(dash) guidChars[offset++] = '-'; //// //// offset = HexsToChars( guidChars, offset, _c >> 8, _c ); //// //// if(dash) guidChars[offset++] = '-'; //// //// offset = HexsToChars( guidChars, offset, _d, _e ); //// //// if(dash) guidChars[offset++] = '-'; //// //// offset = HexsToChars( guidChars, offset, _f, _g ); //// offset = HexsToChars( guidChars, offset, _h, _i ); //// offset = HexsToChars( guidChars, offset, _j, _k ); //// //// return new String( guidChars, 0, strLength ); //// } } } ================================================ FILE: Zelig/Zelig/RunTime/Framework/mscorlib/System/IAsyncResult.cs ================================================ // ==++== // // Copyright (c) Microsoft Corporation. All rights reserved. // // ==--== /*============================================================ ** ** Interface: IAsyncResult ** ** Purpose: Interface to encapsulate the results of an async ** operation ** ===========================================================*/ namespace System { using System; using System.Threading; public interface IAsyncResult { bool IsCompleted { get; } WaitHandle AsyncWaitHandle { get; } Object AsyncState { get; } bool CompletedSynchronously { get; } } } ================================================ FILE: Zelig/Zelig/RunTime/Framework/mscorlib/System/ICloneable.cs ================================================ // ==++== // // Copyright (c) Microsoft Corporation. All rights reserved. // // ==--== /*============================================================ ** ** Class: ICloneable ** ** This interface is implemented by classes that support cloning. ** ===========================================================*/ namespace System { using System; // Defines an interface indicating that an object may be cloned. Only objects // that implement ICloneable may be cloned. The interface defines a single // method which is called to create a clone of the object. Object defines a method // MemberwiseClone to support default clone operations. // public interface ICloneable { // Interface does not need to be marked with the serializable attribute // Make a new object which is a copy of the object instanced. This object may be either // deep copy or a shallow copy depending on the implementation of clone. The default // Object support for clone does a shallow copy. // Object Clone(); } } ================================================ FILE: Zelig/Zelig/RunTime/Framework/mscorlib/System/IComparable.cs ================================================ // ==++== // // Copyright (c) Microsoft Corporation. All rights reserved. // // ==--== namespace System { using System; // The IComparable interface is implemented by classes that support an // ordering of instances of the class. The ordering represented by // IComparable can be used to sort arrays and collections of objects // that implement the interface. // public interface IComparable { // Interface does not need to be marked with the serializable attribute // Compares this object to another object, returning an integer that // indicates the relationship. An implementation of this method must return // a value less than zero if this is less than object, zero // if this is equal to object, or a value greater than zero // if this is greater than object. // int CompareTo( Object obj ); } // Generic version of IComparable. [Microsoft.Zelig.Internals.WellKnownType( "System_IComparable_of_T" )] public interface IComparable { // Interface does not need to be marked with the serializable attribute // Compares this object to another object, returning an integer that // indicates the relationship. An implementation of this method must return // a value less than zero if this is less than object, zero // if this is equal to object, or a value greater than zero // if this is greater than object. // int CompareTo( T other ); } } ================================================ FILE: Zelig/Zelig/RunTime/Framework/mscorlib/System/IConvertible.cs ================================================ // ==++== // // Copyright (c) Microsoft Corporation. All rights reserved. // // ==--== namespace System { using System.Threading; // The IValue interface represents an object that contains a value. This // interface is implemented by the following types in the System namespace: // Boolean, Char, SByte, Byte, Int16, UInt16, Int32, UInt32, Int64, UInt64, // Single, Double, Decimal, DateTime, TimeSpan, and String. The interface may // be implemented by other types that are to be considered values. For example, // a library of nullable database types could implement IValue. // // The implementations of IValue provided by the System.XXX value classes // simply forward to the appropriate Value.ToXXX(YYY) methods (a description of // the Value class follows below). In cases where a Value.ToXXX(YYY) method // does not exist (because the particular conversion is not supported), the // IValue implementation should simply throw an InvalidCastException. [CLSCompliant( false )] public interface IConvertible { // Returns the type code of this object. An implementation of this method // must not return TypeCode.Empty (which represents a null reference) or // TypeCode.Object (which represents an object that doesn't implement the // IValue interface). An implementation of this method should return // TypeCode.DBNull if the value of this object is a database null. For // example, a nullable integer type should return TypeCode.DBNull if the // value of the object is the database null. Otherwise, an implementation // of this method should return the TypeCode that best describes the // internal representation of the object. TypeCode GetTypeCode(); // The ToXXX methods convert the value of the underlying object to the // given type. If a particular conversion is not supported, the // implementation must throw an InvalidCastException. If the value of the // underlying object is not within the range of the target type, the // implementation must throw an OverflowException. The // IFormatProvider will be used to get a NumberFormatInfo or similar // appropriate service object, and may safely be null. bool ToBoolean ( IFormatProvider provider ); char ToChar ( IFormatProvider provider ); sbyte ToSByte ( IFormatProvider provider ); byte ToByte ( IFormatProvider provider ); short ToInt16 ( IFormatProvider provider ); ushort ToUInt16 ( IFormatProvider provider ); int ToInt32 ( IFormatProvider provider ); uint ToUInt32 ( IFormatProvider provider ); long ToInt64 ( IFormatProvider provider ); ulong ToUInt64 ( IFormatProvider provider ); float ToSingle ( IFormatProvider provider ); double ToDouble ( IFormatProvider provider ); Decimal ToDecimal ( IFormatProvider provider ); DateTime ToDateTime( IFormatProvider provider ); String ToString ( IFormatProvider provider ); Object ToType( Type conversionType, IFormatProvider provider ); } } ================================================ FILE: Zelig/Zelig/RunTime/Framework/mscorlib/System/ICustomFormatter.cs ================================================ // ==++== // // Copyright (c) Microsoft Corporation. All rights reserved. // // ==--== /*============================================================ ** ** Interface: ICustomFormatter ** ** ** Purpose: Marks a class as providing special formatting ** ** ===========================================================*/ namespace System { using System; using System.Runtime.Serialization; public interface ICustomFormatter { // Interface does not need to be marked with the serializable attribute String Format( String format, Object arg, IFormatProvider formatProvider ); } } ================================================ FILE: Zelig/Zelig/RunTime/Framework/mscorlib/System/IDisposable.cs ================================================ // ==++== // // Copyright (c) Microsoft Corporation. All rights reserved. // // ==--== /*============================================================ ** ** Interface: IDisposable ** ** ** Purpose: Interface for assisting with deterministic finalization. ** ** ===========================================================*/ namespace System { // IDisposable is an attempt at helping to solve problems with deterministic // finalization. The GC of course doesn't leave any way to deterministically // know when a finalizer will run. This forces classes that hold onto OS // resources or some sort of important state (such as a FileStream or a // network connection) to provide a Close or Dispose method so users can // run clean up code deterministically. We have formalized this into an // interface with one method. Classes may privately implement IDisposable and // provide a Close method instead, if that name is by far the expected name // for objects in that domain (ie, you don't Dispose of a FileStream, you Close // it). // // This interface could be theoretically used as a marker by a compiler to // ensure a disposable object has been cleaned up along all code paths if it's // been allocated in that method, though in practice any compiler that // draconian may tick off any number of people. Perhaps an external tool (like // like Purify or BoundsChecker) could do this. Instead, C# has added a using // clause, which will generate a try/finally statement where the resource // passed into the using clause will always have it's Dispose method called. // Syntax is using(FileStream fs = ...) { .. }; // // Dispose should meet the following conditions: // 1) Be safely callable multiple times // 2) Release any resources associated with the instance // 3) Call the base class's Dispose method, if necessary // 4) Suppress finalization of this class to help the GC by reducing the // number of objects on the finalization queue. // 5) Dispose shouldn't generally throw exceptions, except for very serious // errors that are particularly unexpected. (ie, OutOfMemoryException) // Ideally, nothing should go wrong with your object by calling Dispose. // // If possible, a class should define a finalizer that calls Dispose. // However, in many situations, this is impractical. For instance, take the // classic example of a Stream and a StreamWriter (which has an internal // buffer of data to write to the Stream). If both objects are collected // before Close or Dispose has been called on either, then the GC may run the // finalizer for the Stream first, before the StreamWriter. At that point, any // data buffered by the StreamWriter cannot be written to the Stream. In this // case, it doesn't make much sense to provide a finalizer on the StreamWriter // since you cannot solve this problem correctly. public interface IDisposable { void Dispose(); } } ================================================ FILE: Zelig/Zelig/RunTime/Framework/mscorlib/System/IEquatable.cs ================================================ // ==++== // // Copyright (c) Microsoft Corporation. All rights reserved. // // ==--== namespace System { using System; [Microsoft.Zelig.Internals.WellKnownType( "System_IEquatable_of_T" )] public interface IEquatable { bool Equals( T other ); } } ================================================ FILE: Zelig/Zelig/RunTime/Framework/mscorlib/System/IFormatProvider.cs ================================================ // ==++== // // Copyright (c) Microsoft Corporation. All rights reserved. // // ==--== /*============================================================ ** ** Class: IFormatProvider ** ** ** Purpose: Notes a class which knows how to return formatting information ** ** ============================================================*/ namespace System { using System; public interface IFormatProvider { // Interface does not need to be marked with the serializable attribute Object GetFormat( Type formatType ); } } ================================================ FILE: Zelig/Zelig/RunTime/Framework/mscorlib/System/IFormattable.cs ================================================ // ==++== // // Copyright (c) Microsoft Corporation. All rights reserved. // // ==--== namespace System { using System; public interface IFormattable { String ToString( String format, IFormatProvider formatProvider ); } } ================================================ FILE: Zelig/Zelig/RunTime/Framework/mscorlib/System/IO/BinaryReader.cs ================================================ // ==++== // // Copyright (c) Microsoft Corporation. All rights reserved. // // ==--== /*============================================================ ** ** Class: BinaryReader ** ** ** Purpose: Wraps a stream and provides convenient read functionality ** for strings and primitive types. ** ** ============================================================*/ namespace System.IO { using System; using System.Text; using System.Globalization; ////[System.Runtime.InteropServices.ComVisible( true )] public class BinaryReader : IDisposable { private const int MaxCharBytesSize = 128; private Stream m_stream; private byte[] m_buffer; private Decoder m_decoder; private byte[] m_charBytes; private char[] m_singleChar; private char[] m_charBuffer; private int m_maxCharsSize; // From MaxCharBytesSize & Encoding // Performance optimization for Read() w/ Unicode. Speeds us up by ~40% private bool m_2BytesPerChar; private bool m_isMemoryStream; // "do we sit on MemoryStream?" for Read/ReadInt32 perf public BinaryReader( Stream input ) : this( input, new UTF8Encoding() ) { } public BinaryReader( Stream input, Encoding encoding ) { if(input == null) { #if EXCEPTION_STRINGS throw new ArgumentNullException( "input" ); #else throw new ArgumentNullException(); #endif } if(encoding == null) { #if EXCEPTION_STRINGS throw new ArgumentNullException( "encoding" ); #else throw new ArgumentNullException(); #endif } if(!input.CanRead) #if EXCEPTION_STRINGS throw new ArgumentException( Environment.GetResourceString( "Argument_StreamNotReadable" ) ); #else throw new ArgumentException(); #endif m_stream = input; m_decoder = encoding.GetDecoder(); m_maxCharsSize = encoding.GetMaxCharCount( MaxCharBytesSize ); int minBufferSize = encoding.GetMaxByteCount( 1 ); // max bytes per one char if(minBufferSize < 16) minBufferSize = 16; m_buffer = new byte[minBufferSize]; m_charBuffer = null; m_charBytes = null; // For Encodings that always use 2 bytes per char (or more), // special case them here to make Read() & Peek() faster. m_2BytesPerChar = encoding is UnicodeEncoding; // check if BinaryReader is based on MemoryStream, and keep this for it's life // we cannot use "as" operator, since derived classes are not allowed m_isMemoryStream = (m_stream.GetType() == typeof( MemoryStream )); BCLDebug.Assert( m_decoder != null, "[BinaryReader.ctor]m_decoder!=null" ); } public virtual Stream BaseStream { get { return m_stream; } } public virtual void Close() { Dispose( true ); } protected virtual void Dispose( bool disposing ) { if(disposing) { Stream copyOfStream = m_stream; m_stream = null; if(copyOfStream != null) copyOfStream.Close(); } m_stream = null; m_buffer = null; m_decoder = null; m_charBytes = null; m_singleChar = null; m_charBuffer = null; } /// void IDisposable.Dispose() { Dispose( true ); } public virtual int PeekChar() { if(m_stream == null) __Error.FileNotOpen(); if(!m_stream.CanSeek) return -1; long origPos = m_stream.Position; int ch = Read(); m_stream.Position = origPos; return ch; } public virtual int Read() { if(m_stream == null) { __Error.FileNotOpen(); } return InternalReadOneChar(); } public virtual bool ReadBoolean() { FillBuffer( 1 ); return (m_buffer[0] != 0); } public virtual byte ReadByte() { // Inlined to avoid some method call overhead with FillBuffer. if(m_stream == null) __Error.FileNotOpen(); int b = m_stream.ReadByte(); if(b == -1) __Error.EndOfFile(); return (byte)b; } [CLSCompliant( false )] public virtual sbyte ReadSByte() { FillBuffer( 1 ); return (sbyte)(m_buffer[0]); } public virtual char ReadChar() { int value = Read(); if(value == -1) { __Error.EndOfFile(); } return (char)value; } public virtual short ReadInt16() { FillBuffer( 2 ); return (short)(m_buffer[0] | m_buffer[1] << 8); } [CLSCompliant( false )] public virtual ushort ReadUInt16() { FillBuffer( 2 ); return (ushort)(m_buffer[0] | m_buffer[1] << 8); } public virtual int ReadInt32() { if(m_isMemoryStream) { // read directly from MemoryStream buffer MemoryStream mStream = m_stream as MemoryStream; BCLDebug.Assert( mStream != null, "m_stream as MemoryStream != null" ); return mStream.InternalReadInt32(); } else { FillBuffer( 4 ); return (int)(m_buffer[0] | m_buffer[1] << 8 | m_buffer[2] << 16 | m_buffer[3] << 24); } } [CLSCompliant( false )] public virtual uint ReadUInt32() { FillBuffer( 4 ); return (uint)(m_buffer[0] | m_buffer[1] << 8 | m_buffer[2] << 16 | m_buffer[3] << 24); } public virtual long ReadInt64() { FillBuffer( 8 ); uint lo = (uint)(m_buffer[0] | m_buffer[1] << 8 | m_buffer[2] << 16 | m_buffer[3] << 24); uint hi = (uint)(m_buffer[4] | m_buffer[5] << 8 | m_buffer[6] << 16 | m_buffer[7] << 24); return (long)((ulong)hi) << 32 | lo; } [CLSCompliant( false )] public virtual ulong ReadUInt64() { FillBuffer( 8 ); uint lo = (uint)(m_buffer[0] | m_buffer[1] << 8 | m_buffer[2] << 16 | m_buffer[3] << 24); uint hi = (uint)(m_buffer[4] | m_buffer[5] << 8 | m_buffer[6] << 16 | m_buffer[7] << 24); return ((ulong)hi) << 32 | lo; } public virtual unsafe float ReadSingle() { FillBuffer( 4 ); uint tmpBuffer = (uint)(m_buffer[0] | m_buffer[1] << 8 | m_buffer[2] << 16 | m_buffer[3] << 24); return *((float*)&tmpBuffer); } public virtual unsafe double ReadDouble() { FillBuffer( 8 ); uint lo = (uint)(m_buffer[0] | m_buffer[1] << 8 | m_buffer[2] << 16 | m_buffer[3] << 24); uint hi = (uint)(m_buffer[4] | m_buffer[5] << 8 | m_buffer[6] << 16 | m_buffer[7] << 24); ulong tmpBuffer = ((ulong)hi) << 32 | lo; return *((double*)&tmpBuffer); } public virtual decimal ReadDecimal() { FillBuffer( 16 ); return Decimal.ToDecimal( m_buffer ); } public virtual String ReadString() { int currPos = 0; int n; int stringLength; int readLength; int charsRead; if(m_stream == null) __Error.FileNotOpen(); // Length of the string in bytes, not chars stringLength = Read7BitEncodedInt(); if(stringLength < 0) { #if EXCEPTION_STRINGS throw new IOException( String.Format( CultureInfo.CurrentCulture, Environment.GetResourceString( "IO.IO_InvalidStringLen_Len" ), stringLength ) ); #else throw new IOException(); #endif } if(stringLength == 0) { return String.Empty; } if(m_charBytes == null) { m_charBytes = new byte[MaxCharBytesSize]; } if(m_charBuffer == null) { m_charBuffer = new char[m_maxCharsSize]; } StringBuilder sb = null; do { readLength = ((stringLength - currPos) > MaxCharBytesSize) ? MaxCharBytesSize : (stringLength - currPos); n = m_stream.Read( m_charBytes, 0, readLength ); if(n == 0) { __Error.EndOfFile(); } charsRead = m_decoder.GetChars( m_charBytes, 0, n, m_charBuffer, 0 ); if(currPos == 0 && n == stringLength) return new String( m_charBuffer, 0, charsRead ); if(sb == null) sb = new StringBuilder( stringLength ); // Actual string length in chars may be smaller. sb.Append( m_charBuffer, 0, charsRead ); currPos += n; } while(currPos < stringLength); return sb.ToString(); } public virtual int Read( char[] buffer, int index, int count ) { if(buffer == null) { #if EXCEPTION_STRINGS throw new ArgumentNullException( "buffer", Environment.GetResourceString( "ArgumentNull_Buffer" ) ); #else throw new ArgumentNullException(); #endif } if(index < 0) { #if EXCEPTION_STRINGS throw new ArgumentOutOfRangeException( "index", Environment.GetResourceString( "ArgumentOutOfRange_NeedNonNegNum" ) ); #else throw new ArgumentOutOfRangeException(); #endif } if(count < 0) { #if EXCEPTION_STRINGS throw new ArgumentOutOfRangeException( "count", Environment.GetResourceString( "ArgumentOutOfRange_NeedNonNegNum" ) ); #else throw new ArgumentOutOfRangeException(); #endif } if(buffer.Length - index < count) { #if EXCEPTION_STRINGS throw new ArgumentException( Environment.GetResourceString( "Argument_InvalidOffLen" ) ); #else throw new ArgumentException(); #endif } if(m_stream == null) __Error.FileNotOpen(); return InternalReadChars( buffer, index, count ); } private int InternalReadChars( char[] buffer, int index, int count ) { int charsRead = 0; int numBytes = 0; int charsRemaining = count; if(m_charBytes == null) { m_charBytes = new byte[MaxCharBytesSize]; } while(charsRemaining > 0) { // We really want to know what the minimum number of bytes per char // is for our encoding. Otherwise for UnicodeEncoding we'd have to // do ~1+log(n) reads to read n characters. numBytes = charsRemaining; if(m_2BytesPerChar) numBytes <<= 1; if(numBytes > MaxCharBytesSize) numBytes = MaxCharBytesSize; if(m_isMemoryStream) { MemoryStream mStream = m_stream as MemoryStream; BCLDebug.Assert( mStream != null, "m_stream as MemoryStream != null" ); int position = mStream.InternalGetPosition(); numBytes = mStream.InternalEmulateRead( numBytes ); if(numBytes == 0) { return (count - charsRemaining); } charsRead = m_decoder.GetChars( mStream.InternalGetBuffer(), position, numBytes, buffer, index ); } else { numBytes = m_stream.Read( m_charBytes, 0, numBytes ); if(numBytes == 0) { // Console.WriteLine("Found no bytes. We're outta here."); return (count - charsRemaining); } charsRead = m_decoder.GetChars( m_charBytes, 0, numBytes, buffer, index ); } charsRemaining -= charsRead; index += charsRead; // Console.WriteLine("That became: " + charsRead + " characters."); } BCLDebug.Assert( charsRemaining == 0, "We didn't read all the chars we thought we would." ); return count; } private int InternalReadOneChar() { // I know having a separate InternalReadOneChar method seems a little // redundant, but this makes a scenario like the security parser code // 20% faster, in addition to the optimizations for UnicodeEncoding I // put in InternalReadChars. int charsRead = 0; int numBytes = 0; long posSav = posSav = 0; if(m_stream.CanSeek) posSav = m_stream.Position; if(m_charBytes == null) { m_charBytes = new byte[MaxCharBytesSize]; //REVIEW: We need atmost 2 bytes/char here? } if(m_singleChar == null) { m_singleChar = new char[1]; } while(charsRead == 0) { // We really want to know what the minimum number of bytes per char // is for our encoding. Otherwise for UnicodeEncoding we'd have to // do ~1+log(n) reads to read n characters. // Assume 1 byte can be 1 char unless m_2BytesPerChar is true. numBytes = m_2BytesPerChar ? 2 : 1; int r = m_stream.ReadByte(); m_charBytes[0] = (byte)r; if(r == -1) numBytes = 0; if(numBytes == 2) { r = m_stream.ReadByte(); m_charBytes[1] = (byte)r; if(r == -1) numBytes = 1; } if(numBytes == 0) { // Console.WriteLine("Found no bytes. We're outta here."); return -1; } BCLDebug.Assert( numBytes == 1 || numBytes == 2, "BinaryReader::InternalReadOneChar assumes it's reading one or 2 bytes only." ); try { charsRead = m_decoder.GetChars( m_charBytes, 0, numBytes, m_singleChar, 0 ); } catch { // Handle surrogate char if(m_stream.CanSeek) m_stream.Seek( (posSav - m_stream.Position), SeekOrigin.Current ); // else - we can't do much here throw; } BCLDebug.Assert( charsRead < 2, "InternalReadOneChar - assuming we only got 0 or 1 char, not 2!" ); // Console.WriteLine("That became: " + charsRead + " characters."); } if(charsRead == 0) return -1; return m_singleChar[0]; } public virtual char[] ReadChars( int count ) { if(m_stream == null) { __Error.FileNotOpen(); } if(count < 0) { #if EXCEPTION_STRINGS throw new ArgumentOutOfRangeException( "count", Environment.GetResourceString( "ArgumentOutOfRange_NeedNonNegNum" ) ); #else throw new ArgumentOutOfRangeException(); #endif } char[] chars = new char[count]; int n = InternalReadChars( chars, 0, count ); if(n != count) { char[] copy = new char[n]; Buffer.InternalBlockCopy( chars, 0, copy, 0, 2 * n ); // sizeof(char) chars = copy; } return chars; } public virtual int Read( byte[] buffer, int index, int count ) { if(buffer == null) #if EXCEPTION_STRINGS throw new ArgumentNullException( "buffer", Environment.GetResourceString( "ArgumentNull_Buffer" ) ); #else throw new ArgumentNullException(); #endif if(index < 0) #if EXCEPTION_STRINGS throw new ArgumentOutOfRangeException( "index", Environment.GetResourceString( "ArgumentOutOfRange_NeedNonNegNum" ) ); #else throw new ArgumentOutOfRangeException(); #endif if(count < 0) #if EXCEPTION_STRINGS throw new ArgumentOutOfRangeException( "count", Environment.GetResourceString( "ArgumentOutOfRange_NeedNonNegNum" ) ); #else throw new ArgumentOutOfRangeException(); #endif if(buffer.Length - index < count) #if EXCEPTION_STRINGS throw new ArgumentException( Environment.GetResourceString( "Argument_InvalidOffLen" ) ); #else throw new ArgumentException(); #endif if(m_stream == null) __Error.FileNotOpen(); return m_stream.Read( buffer, index, count ); } public virtual byte[] ReadBytes( int count ) { if(count < 0) #if EXCEPTION_STRINGS throw new ArgumentOutOfRangeException( "count", Environment.GetResourceString( "ArgumentOutOfRange_NeedNonNegNum" ) ); #else throw new ArgumentOutOfRangeException(); #endif if(m_stream == null) __Error.FileNotOpen(); byte[] result = new byte[count]; int numRead = 0; do { int n = m_stream.Read( result, numRead, count ); if(n == 0) break; numRead += n; count -= n; } while(count > 0); if(numRead != result.Length) { // Trim array. This should happen on EOF & possibly net streams. byte[] copy = new byte[numRead]; Buffer.InternalBlockCopy( result, 0, copy, 0, numRead ); result = copy; } return result; } protected virtual void FillBuffer( int numBytes ) { BCLDebug.Assert( m_buffer == null || (numBytes > 0 && numBytes <= m_buffer.Length), "[FillBuffer]numBytes>0 && numBytes<=m_buffer.Length" ); int bytesRead = 0; int n = 0; if(m_stream == null) __Error.FileNotOpen(); // Need to find a good threshold for calling ReadByte() repeatedly // vs. calling Read(byte[], int, int) for both buffered & unbuffered // streams. if(numBytes == 1) { n = m_stream.ReadByte(); if(n == -1) __Error.EndOfFile(); m_buffer[0] = (byte)n; return; } do { n = m_stream.Read( m_buffer, bytesRead, numBytes - bytesRead ); if(n == 0) { __Error.EndOfFile(); } bytesRead += n; } while(bytesRead < numBytes); } internal protected int Read7BitEncodedInt() { // Read out an Int32 7 bits at a time. The high bit // of the byte when on means to continue reading more bytes. int count = 0; int shift = 0; byte b; do { // Check for a corrupted stream. Read a max of 5 bytes. // In a future version, add a DataFormatException. if(shift == 5 * 7) // 5 bytes max per Int32, shift += 7 #if EXCEPTION_STRINGS throw new FormatException( Environment.GetResourceString( "Format_Bad7BitInt32" ) ); #else throw new FormatException(); #endif // ReadByte handles end of stream cases for us. b = ReadByte(); count |= (b & 0x7F) << shift; shift += 7; } while((b & 0x80) != 0); return count; } } } ================================================ FILE: Zelig/Zelig/RunTime/Framework/mscorlib/System/IO/BinaryWriter.cs ================================================ // ==++== // // Copyright (c) Microsoft Corporation. All rights reserved. // // ==--== /*============================================================ ** ** Class: BinaryWriter ** ** Purpose: Provides a way to write primitives types in ** binary from a Stream, while also supporting writing Strings ** in a particular encoding. ** ** ===========================================================*/ using System; using System.Text; namespace System.IO { // This abstract base class represents a writer that can write // primitives to an arbitrary stream. A subclass can override methods to // give unique encodings. // [Serializable] ////[System.Runtime.InteropServices.ComVisible( true )] public class BinaryWriter : IDisposable { public static readonly BinaryWriter Null = new BinaryWriter(); protected Stream OutStream; private byte[] _buffer; // temp space for writing primitives to. private Encoding _encoding; private Encoder _encoder; private char[] _tmpOneCharBuffer = new char[1]; // Perf optimization stuff private byte[] _largeByteBuffer; // temp space for writing chars. private int _maxChars; // max # of chars we can put in _largeByteBuffer // Size should be around the max number of chars/string * Encoding's max bytes/char private const int LargeByteBufferSize = 256; // Protected default constructor that sets the output stream // to a null stream (a bit bucket). protected BinaryWriter() { OutStream = Stream.Null; _buffer = new byte[16]; _encoding = new UTF8Encoding( false, true ); _encoder = _encoding.GetEncoder(); } public BinaryWriter( Stream output ) : this( output, new UTF8Encoding( false, true ) ) { } public BinaryWriter( Stream output, Encoding encoding ) { if(output == null) #if EXCEPTION_STRINGS throw new ArgumentNullException( "output" ); #else throw new ArgumentNullException(); #endif if(encoding == null) #if EXCEPTION_STRINGS throw new ArgumentNullException( "encoding" ); #else throw new ArgumentNullException(); #endif if(!output.CanWrite) #if EXCEPTION_STRINGS throw new ArgumentException( Environment.GetResourceString( "Argument_StreamNotWritable" ) ); #else throw new ArgumentException(); #endif OutStream = output; _buffer = new byte[16]; _encoding = encoding; _encoder = _encoding.GetEncoder(); } // Closes this writer and releases any system resources associated with the // writer. Following a call to Close, any operations on the writer // may raise exceptions. public virtual void Close() { Dispose( true ); } protected virtual void Dispose( bool disposing ) { if(disposing) OutStream.Close(); } /// void IDisposable.Dispose() { Dispose( true ); } /* * Returns the stream associate with the writer. It flushes all pending * writes before returning. All subclasses should override Flush to * ensure that all buffered data is sent to the stream. */ public virtual Stream BaseStream { get { Flush(); return OutStream; } } // Clears all buffers for this writer and causes any buffered data to be // written to the underlying device. public virtual void Flush() { OutStream.Flush(); } public virtual long Seek( int offset, SeekOrigin origin ) { return OutStream.Seek( offset, origin ); } // Writes a boolean to this stream. A single byte is written to the stream // with the value 0 representing false or the value 1 representing true. // public virtual void Write( bool value ) { _buffer[0] = (byte)(value ? 1 : 0); OutStream.Write( _buffer, 0, 1 ); } // Writes a byte to this stream. The current position of the stream is // advanced by one. // public virtual void Write( byte value ) { OutStream.WriteByte( value ); } // Writes a signed byte to this stream. The current position of the stream // is advanced by one. // [CLSCompliant( false )] public virtual void Write( sbyte value ) { OutStream.WriteByte( (byte)value ); } // Writes a byte array to this stream. // // This default implementation calls the Write(Object, int, int) // method to write the byte array. // public virtual void Write( byte[] buffer ) { if(buffer == null) #if EXCEPTION_STRINGS throw new ArgumentNullException( "buffer" ); #else throw new ArgumentNullException(); #endif OutStream.Write( buffer, 0, buffer.Length ); } // Writes a section of a byte array to this stream. // // This default implementation calls the Write(Object, int, int) // method to write the byte array. // public virtual void Write( byte[] buffer, int index, int count ) { OutStream.Write( buffer, index, count ); } // Writes a character to this stream. The current position of the stream is // advanced by two. // Note this method cannot handle surrogates properly in UTF-8. // public unsafe virtual void Write( char ch ) { if(Char.IsSurrogate( ch )) #if EXCEPTION_STRINGS throw new ArgumentException( Environment.GetResourceString( "Arg_SurrogatesNotAllowedAsSingleChar" ) ); #else throw new ArgumentException(); #endif BCLDebug.Assert( _encoding.GetMaxByteCount( 1 ) <= 16, "_encoding.GetMaxByteCount(1) <= 16)" ); int numBytes = 0; fixed(byte* pBytes = _buffer) { numBytes = _encoder.GetBytes( &ch, 1, pBytes, 16, true ); } OutStream.Write( _buffer, 0, numBytes ); } // Writes a character array to this stream. // // This default implementation calls the Write(Object, int, int) // method to write the character array. // public virtual void Write( char[] chars ) { if(chars == null) #if EXCEPTION_STRINGS throw new ArgumentNullException( "chars" ); #else throw new ArgumentNullException(); #endif byte[] bytes = _encoding.GetBytes( chars, 0, chars.Length ); OutStream.Write( bytes, 0, bytes.Length ); } // Writes a section of a character array to this stream. // // This default implementation calls the Write(Object, int, int) // method to write the character array. // public virtual void Write( char[] chars, int index, int count ) { byte[] bytes = _encoding.GetBytes( chars, index, count ); OutStream.Write( bytes, 0, bytes.Length ); } // Writes a double to this stream. The current position of the stream is // advanced by eight. // public unsafe virtual void Write( double value ) { ulong TmpValue = *(ulong*)&value; _buffer[0] = (byte)TmpValue; _buffer[1] = (byte)(TmpValue >> 8); _buffer[2] = (byte)(TmpValue >> 16); _buffer[3] = (byte)(TmpValue >> 24); _buffer[4] = (byte)(TmpValue >> 32); _buffer[5] = (byte)(TmpValue >> 40); _buffer[6] = (byte)(TmpValue >> 48); _buffer[7] = (byte)(TmpValue >> 56); OutStream.Write( _buffer, 0, 8 ); } public virtual void Write( decimal value ) { Decimal.GetBytes( value, _buffer ); OutStream.Write( _buffer, 0, 16 ); } // Writes a two-byte signed integer to this stream. The current position of // the stream is advanced by two. // public virtual void Write( short value ) { _buffer[0] = (byte)value; _buffer[1] = (byte)(value >> 8); OutStream.Write( _buffer, 0, 2 ); } // Writes a two-byte unsigned integer to this stream. The current position // of the stream is advanced by two. // [CLSCompliant( false )] public virtual void Write( ushort value ) { _buffer[0] = (byte)value; _buffer[1] = (byte)(value >> 8); OutStream.Write( _buffer, 0, 2 ); } // Writes a four-byte signed integer to this stream. The current position // of the stream is advanced by four. // public virtual void Write( int value ) { _buffer[0] = (byte)value; _buffer[1] = (byte)(value >> 8); _buffer[2] = (byte)(value >> 16); _buffer[3] = (byte)(value >> 24); OutStream.Write( _buffer, 0, 4 ); } // Writes a four-byte unsigned integer to this stream. The current position // of the stream is advanced by four. // [CLSCompliant( false )] public virtual void Write( uint value ) { _buffer[0] = (byte)value; _buffer[1] = (byte)(value >> 8); _buffer[2] = (byte)(value >> 16); _buffer[3] = (byte)(value >> 24); OutStream.Write( _buffer, 0, 4 ); } // Writes an eight-byte signed integer to this stream. The current position // of the stream is advanced by eight. // public virtual void Write( long value ) { _buffer[0] = (byte)value; _buffer[1] = (byte)(value >> 8); _buffer[2] = (byte)(value >> 16); _buffer[3] = (byte)(value >> 24); _buffer[4] = (byte)(value >> 32); _buffer[5] = (byte)(value >> 40); _buffer[6] = (byte)(value >> 48); _buffer[7] = (byte)(value >> 56); OutStream.Write( _buffer, 0, 8 ); } // Writes an eight-byte unsigned integer to this stream. The current // position of the stream is advanced by eight. // [CLSCompliant( false )] public virtual void Write( ulong value ) { _buffer[0] = (byte)value; _buffer[1] = (byte)(value >> 8); _buffer[2] = (byte)(value >> 16); _buffer[3] = (byte)(value >> 24); _buffer[4] = (byte)(value >> 32); _buffer[5] = (byte)(value >> 40); _buffer[6] = (byte)(value >> 48); _buffer[7] = (byte)(value >> 56); OutStream.Write( _buffer, 0, 8 ); } // Writes a float to this stream. The current position of the stream is // advanced by four. // public unsafe virtual void Write( float value ) { uint TmpValue = *(uint*)&value; _buffer[0] = (byte)TmpValue; _buffer[1] = (byte)(TmpValue >> 8); _buffer[2] = (byte)(TmpValue >> 16); _buffer[3] = (byte)(TmpValue >> 24); OutStream.Write( _buffer, 0, 4 ); } // Writes a length-prefixed string to this stream in the BinaryWriter's // current Encoding. This method first writes the length of the string as // a four-byte unsigned integer, and then writes that many characters // to the stream. // public unsafe virtual void Write( String value ) { if(value == null) #if EXCEPTION_STRINGS throw new ArgumentNullException( "value" ); #else throw new ArgumentNullException(); #endif int len = _encoding.GetByteCount( value ); Write7BitEncodedInt( len ); if(_largeByteBuffer == null) { _largeByteBuffer = new byte[LargeByteBufferSize]; _maxChars = LargeByteBufferSize / _encoding.GetMaxByteCount( 1 ); } if(len <= LargeByteBufferSize) { //BCLDebug.Assert(len == _encoding.GetBytes(chars, 0, chars.Length, _largeByteBuffer, 0), "encoding's GetByteCount & GetBytes gave different answers! encoding type: "+_encoding.GetType().Name); _encoding.GetBytes( value, 0, value.Length, _largeByteBuffer, 0 ); OutStream.Write( _largeByteBuffer, 0, len ); } else { // Aggressively try to not allocate memory in this loop for // runtime performance reasons. Use an Encoder to write out // the string correctly (handling surrogates crossing buffer // boundaries properly). int charStart = 0; int numLeft = value.Length; #if _DEBUG int totalBytes = 0; #endif while(numLeft > 0) { // Figure out how many chars to process this round. int charCount = (numLeft > _maxChars) ? _maxChars : numLeft; int byteLen; fixed(char* pChars = value) { fixed(byte* pBytes = _largeByteBuffer) { byteLen = _encoder.GetBytes( pChars + charStart, charCount, pBytes, LargeByteBufferSize, charCount == numLeft ); } } #if _DEBUG totalBytes += byteLen; BCLDebug.Assert (totalBytes <= len && byteLen <= LargeByteBufferSize, "BinaryWriter::Write(String) - More bytes encoded than expected!"); #endif OutStream.Write( _largeByteBuffer, 0, byteLen ); charStart += charCount; numLeft -= charCount; } #if _DEBUG BCLDebug.Assert(totalBytes == len, "BinaryWriter::Write(String) - Didn't write out all the bytes!"); #endif } } protected void Write7BitEncodedInt( int value ) { // Write out an int 7 bits at a time. The high bit of the byte, // when on, tells reader to continue reading more bytes. uint v = (uint)value; // support negative numbers while(v >= 0x80) { Write( (byte)(v | 0x80) ); v >>= 7; } Write( (byte)v ); } } } ================================================ FILE: Zelig/Zelig/RunTime/Framework/mscorlib/System/IO/Directory.cs ================================================ //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // Copyright (c) Microsoft Corporation. All rights reserved. //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// using System; using System.Collections; using System.Collections.Generic; namespace System.IO { public sealed class Directory { private Directory() { } //--// public static DirectoryInfo CreateDirectory(string path) { // path validation in Path.GetFullPath() path = Path.GetFullPath(path); /// According to MSDN, Directory.CreateDirectory on an existing /// directory is no-op. NativeIO.CreateDirectory(path); return new DirectoryInfo(path); } public static bool Exists(string path) { // path validation in Path.GetFullPath() path = Path.GetFullPath(path); /// Is this the absolute root? this always exists. if (path == NativeIO.FSRoot) { return true; } else { try { uint attributes = NativeIO.GetAttributes(path); /// This is essentially file not found. if (attributes == 0xFFFFFFFF) return false; /// Need to make sure these are not FAT16 or FAT32 specific. if ((((FileAttributes)attributes) & FileAttributes.Directory) == FileAttributes.Directory) { /// It is a directory. return true; } } catch (Exception) { return false; } } return false; } public static IEnumerable EnumerateFiles(string path) { if (!Directory.Exists(path)) #if EXCEPTION_STRINGS throw new IOException("", (int)IOExceptionErrorCode.DirectoryNotFound); #else throw new IOException(); #endif return new FileEnumerator(path, FileEnumFlags.Files); } public static IEnumerable EnumerateDirectories(string path) { if (!Directory.Exists(path)) #if EXCEPTION_STRINGS throw new IOException("", (int)IOExceptionErrorCode.DirectoryNotFound); #else throw new IOException(); #endif return new FileEnumerator(path, FileEnumFlags.Directories); } public static IEnumerable EnumerateFileSystemEntries(string path) { if (!Directory.Exists(path)) #if EXCEPTION_STRINGS throw new IOException("", (int)IOExceptionErrorCode.DirectoryNotFound); #else throw new IOException(); #endif return new FileEnumerator(path, FileEnumFlags.FilesAndDirectories); } public static string[] GetFiles(string path) { return GetChildren(path, "*", false); } public static string[] GetDirectories(string path) { return GetChildren(path, "*", true); } public static string GetCurrentDirectory() { return FileSystemManager.CurrentDirectory; } public static void SetCurrentDirectory(string path) { // path validation in Path.GetFullPath() path = Path.GetFullPath(path); // We lock the directory for read-access first, to ensure path won't get deleted Object record = FileSystemManager.AddToOpenListForRead(path); try { if (!Directory.Exists(path)) { #if EXCEPTION_STRINGS throw new IOException("", (int)IOExceptionErrorCode.DirectoryNotFound); #else throw new IOException(); #endif } // This will put the actual lock on path. (also read-access) FileSystemManager.SetCurrentDirectory(path); } finally { // We take our lock off. FileSystemManager.RemoveFromOpenList(record); } } public static void Move(string sourceDirName, string destDirName) { // sourceDirName and destDirName validation in Path.GetFullPath() sourceDirName = Path.GetFullPath(sourceDirName); destDirName = Path.GetFullPath(destDirName); bool tryCopyAndDelete = false; Object srcRecord = FileSystemManager.AddToOpenList(sourceDirName); try { // Make sure sourceDir is actually a directory if (!Exists(sourceDirName)) { #if EXCEPTION_STRINGS throw new IOException("", (int)IOExceptionErrorCode.DirectoryNotFound); #else throw new IOException(); #endif } if (Exists( destDirName )) { #if EXCEPTION_STRINGS throw new IOException( "", (int)IOExceptionErrorCode.PathAlreadyExists ); #else throw new IOException(); #endif } // If Move() returns false, we'll try doing copy and delete to accomplish the move // ZeligBUG - the following fails to set tryCopyAndDelete //tryCopyAndDelete = !NativeIO.Move(sourceDirName, destDirName); if(false == NativeIO.Move( sourceDirName, destDirName )) { tryCopyAndDelete = true; } } finally { FileSystemManager.RemoveFromOpenList(srcRecord); } if (tryCopyAndDelete) { RecursiveCopyAndDelete(sourceDirName, destDirName); } } private static void RecursiveCopyAndDelete(String sourceDirName, String destDirName) { String[] files; int filesCount, i; int relativePathIndex = sourceDirName.Length + 1; // relative path starts after the sourceDirName and a path seperator // We have to make sure no one else can modify it (for example, delete the directory and // create a file of the same name) while we're moving Object recordSrc = FileSystemManager.AddToOpenList(sourceDirName); try { // Make sure sourceDir is actually a directory if (!Exists(sourceDirName)) { #if EXCEPTION_STRINGS throw new IOException("", (int)IOExceptionErrorCode.DirectoryNotFound); #else throw new IOException(); #endif } // Make sure destDir does not yet exist if (Exists(destDirName)) { #if EXCEPTION_STRINGS throw new IOException("", (int)IOExceptionErrorCode.PathAlreadyExists); #else throw new IOException(); #endif } NativeIO.CreateDirectory(destDirName); files = Directory.GetFiles(sourceDirName); filesCount = files.Length; for (i = 0; i < filesCount; i++) { File.Copy(files[i], Path.Combine(destDirName, files[i].Substring(relativePathIndex)), false, true); } files = Directory.GetDirectories(sourceDirName); filesCount = files.Length; for (i = 0; i < filesCount; i++) { RecursiveCopyAndDelete(files[i], Path.Combine(destDirName, files[i].Substring(relativePathIndex))); } NativeIO.Delete(sourceDirName); } finally { FileSystemManager.RemoveFromOpenList(recordSrc); } } public static void Delete(string path) { Delete(path, false); } public static void Delete(string path, bool recursive) { path = Path.GetFullPath(path); Object record = FileSystemManager.LockDirectory(path); try { uint attributes = NativeIO.GetAttributes(path); if (attributes == 0xFFFFFFFF) { #if EXCEPTION_STRINGS throw new IOException("", (int)IOExceptionErrorCode.DirectoryNotFound); #else throw new IOException(); #endif } if (((attributes & (uint)(FileAttributes.Directory)) == 0) || ((attributes & (uint)(FileAttributes.ReadOnly)) != 0)) { /// it's readonly or not a directory #if EXCEPTION_STRINGS throw new IOException("", (int)IOExceptionErrorCode.UnauthorizedAccess); #else throw new IOException(); #endif } if (!Exists(path)) // make sure it is indeed a directory (and not a file) { #if EXCEPTION_STRINGS throw new IOException("", (int)IOExceptionErrorCode.DirectoryNotFound); #else throw new IOException(); #endif } if (!recursive) { NativeFindFile ff = new NativeFindFile(path, "*"); try { if (ff.GetNext() != null) { #if EXCEPTION_STRINGS throw new IOException("", (int)IOExceptionErrorCode.DirectoryNotEmpty); #else throw new IOException(); #endif } } finally { ff.Close(); } } NativeIO.Delete(path); } finally { // regardless of what happened, we need to release the directory when we're done FileSystemManager.UnlockDirectory(record); } } private static string[] GetChildren(string path, string searchPattern, bool isDirectory) { // path and searchPattern validation in Path.GetFullPath() and Path.NormalizePath() path = Path.GetFullPath(path); if (!Directory.Exists(path)) #if EXCEPTION_STRINGS throw new IOException("", (int)IOExceptionErrorCode.DirectoryNotFound); #else throw new IOException(); #endif Path.NormalizePath(searchPattern, true); List fileNames = new List(); string root = Path.GetPathRoot(path); if (String.Equals(root, path)) { /// This is special case. Return all the volumes. /// Note this will not work, once we start having \\server\share like paths. if (isDirectory) { VolumeInfo[] volumes = VolumeInfo.GetVolumes(); int count = volumes.Length; for (int i = 0; i < count; i++) { fileNames.Add(volumes[i].RootDirectory); } } } else { Object record = FileSystemManager.AddToOpenListForRead(path); NativeFindFile ff = new NativeFindFile( path, searchPattern ); try { uint targetAttribute = (isDirectory ? (uint)FileAttributes.Directory : 0); NativeFileInfo fileinfo = ff.GetNext(); while (fileinfo != null) { if ((fileinfo.Attributes & (uint)FileAttributes.Directory) == targetAttribute) { fileNames.Add( Path.Combine(path, fileinfo.FileName) ); } fileinfo = ff.GetNext(); } } finally { if (ff != null) ff.Close(); FileSystemManager.RemoveFromOpenList(record); } } return fileNames.ToArray(); } } } ================================================ FILE: Zelig/Zelig/RunTime/Framework/mscorlib/System/IO/DirectoryInfo.cs ================================================ //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // Copyright (c) Microsoft Corporation. All rights reserved. //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// using System; namespace System.IO { public sealed class DirectoryInfo : FileSystemInfo { private DirectoryInfo() { } public DirectoryInfo(string path) { // path validation in Path.GetFullPath() m_fullPath = Path.GetFullPath(path); } public override string Name { get { return Path.GetFileName(m_fullPath); } } public DirectoryInfo Parent { get { string parentDirPath = Path.GetDirectoryName(m_fullPath); if (parentDirPath == null) return null; return new DirectoryInfo(parentDirPath); } } public DirectoryInfo CreateSubdirectory(string path) { // path validatation in Path.Combine() string subDirPath = Path.Combine(m_fullPath, path); /// This will also ensure "path" is valid. subDirPath = Path.GetFullPath(subDirPath); return Directory.CreateDirectory(subDirPath); } public void Create() { Directory.CreateDirectory(m_fullPath); } public override bool Exists { get { return Directory.Exists(m_fullPath); } } public FileInfo[] GetFiles() { string[] fileNames = Directory.GetFiles(m_fullPath); FileInfo[] files = new FileInfo[fileNames.Length]; for (int i = 0; i < fileNames.Length; i++) { files[i] = new FileInfo(fileNames[i]); } return files; } public DirectoryInfo[] GetDirectories() { // searchPattern validation in Directory.GetDirectories() string[] dirNames = Directory.GetDirectories(m_fullPath); DirectoryInfo[] dirs = new DirectoryInfo[dirNames.Length]; for (int i = 0; i < dirNames.Length; i++) { dirs[i] = new DirectoryInfo(dirNames[i]); } return dirs; } public DirectoryInfo Root { get { return new DirectoryInfo(Path.GetPathRoot(m_fullPath)); } } public void MoveTo(string destDirName) { // destDirName validation in Directory.Move() Directory.Move(m_fullPath, destDirName); } public override void Delete() { Directory.Delete(m_fullPath); } public void Delete(bool recursive) { Directory.Delete(m_fullPath, recursive); } public override string ToString() { return m_fullPath; } } } ================================================ FILE: Zelig/Zelig/RunTime/Framework/mscorlib/System/IO/EndOfStreamException.cs ================================================ // ==++== // // Copyright (c) Microsoft Corporation. All rights reserved. // // ==--== /*============================================================ ** ** Class: EndOfStreamException ** ** ** Purpose: Exception to be thrown when reading past end-of-file. ** ** ===========================================================*/ using System; using System.Runtime.Serialization; namespace System.IO { [Serializable] public class EndOfStreamException : IOException { #if EXCEPTION_STRINGS public EndOfStreamException() : base( Environment.GetResourceString( "Arg_EndOfStreamException" ) ) #else public EndOfStreamException() #endif { //// SetErrorCode( __HResults.COR_E_ENDOFSTREAM ); } public EndOfStreamException( String message ) : base( message ) { //// SetErrorCode( __HResults.COR_E_ENDOFSTREAM ); } public EndOfStreamException( String message, Exception innerException ) : base( message, innerException ) { //// SetErrorCode( __HResults.COR_E_ENDOFSTREAM ); } //// protected EndOfStreamException( SerializationInfo info, StreamingContext context ) : base( info, context ) //// { //// } } } ================================================ FILE: Zelig/Zelig/RunTime/Framework/mscorlib/System/IO/File.cs ================================================ //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // Copyright (c) Microsoft Corporation. All rights reserved. //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// using System; using System.Runtime.InteropServices; using System.Text; using System.Collections; namespace System.IO { // Class for creating FileStream objects, and some basic file management // routines such as Delete, etc. public static class File { // Copies an existing file to a new file. An exception is raised if the // destination file already exists. Use the // Copy(String, String, boolean) method to allow // overwriting an existing file. // // The caller must have certain FileIOPermissions. The caller must have // Read permission to sourceFileName and Create // and Write permissions to destFileName. // public static void Copy(String sourceFileName, String destFileName) { Copy(sourceFileName, destFileName, false, false); } // Copies an existing file to a new file. If overwrite is // false, then an IOException is thrown if the destination file // already exists. If overwrite is true, the file is // overwritten. // // The caller must have certain FileIOPermissions. The caller must have // Read permission to sourceFileName // and Write permissions to destFileName. // public static void Copy(String sourceFileName, String destFileName, bool overwrite) { Copy(sourceFileName, destFileName, overwrite, false); } private const int _defaultCopyBufferSize = 2048; /// Experiment on desktop shows 2k-4k is ideal size perfwise. internal static void Copy(String sourceFileName, String destFileName, bool overwrite, bool deleteOriginal) { // sourceFileName and destFileName validation in Path.GetFullPath() sourceFileName = Path.GetFullPath(sourceFileName); destFileName = Path.GetFullPath(destFileName); FileMode writerMode = (overwrite) ? FileMode.Create : FileMode.CreateNew; FileStream reader = new FileStream(sourceFileName, FileMode.Open, FileAccess.Read, FileShare.Read, NativeFileStream.BufferSizeDefault); try { using (FileStream writer = new FileStream(destFileName, writerMode, FileAccess.Write, FileShare.None, NativeFileStream.BufferSizeDefault)) { long fileLength = reader.Length; writer.SetLength(fileLength); byte[] buffer = new byte[_defaultCopyBufferSize]; for (; ; ) { int readSize = reader.Read(buffer, 0, _defaultCopyBufferSize); if (readSize <= 0) break; writer.Write(buffer, 0, readSize); } // Copy the attributes too NativeIO.SetAttributes(destFileName, NativeIO.GetAttributes(sourceFileName)); } } finally { if (deleteOriginal) { reader.DisposeAndDelete(); } else { reader.Dispose(); } } } // Creates a file in a particular path. If the file exists, it is replaced. // The file is opened with ReadWrite accessand cannot be opened by another // application until it has been closed. An IOException is thrown if the // directory specified doesn't exist. // // Your application must have Create, Read, and Write permissions to // the file. // public static FileStream Create(String path) { return new FileStream(path, FileMode.Create, FileAccess.ReadWrite, FileShare.None, NativeFileStream.BufferSizeDefault); } // Creates a file in a particular path. If the file exists, it is replaced. // The file is opened with ReadWrite access and cannot be opened by another // application until it has been closed. An IOException is thrown if the // directory specified doesn't exist. // // Your application must have Create, Read, and Write permissions to // the file. // public static FileStream Create(String path, int bufferSize) { return new FileStream(path, FileMode.Create, FileAccess.ReadWrite, FileShare.None, bufferSize); } // Deletes a file. The file specified by the designated path is deleted. // If the file does not exist, Delete succeeds without throwing // an exception. // // On NT, Delete will fail for a file that is open for normal I/O // or a file that is memory mapped. On Win95, the file will be // deleted irregardless of whether the file is being used. // // Your application must have Delete permission to the target file. // public static void Delete(String path) { // path validation in Path.GetFullPath() path = Path.GetFullPath(path); string folderPath = Path.GetDirectoryName(path); // We have to make sure no one else has the file opened, and no one else can modify it when we're deleting Object record = FileSystemManager.AddToOpenList(path); try { uint attributes = NativeIO.GetAttributes(folderPath); /// If the folder does not exist or invalid we throw DirNotFound Exception (same as desktop). if (attributes == 0xFFFFFFFF) { #if EXCEPTION_STRINGS throw new IOException("", (int)IOExceptionErrorCode.DirectoryNotFound); #else throw new IOException(); #endif } /// Folder exists, lets verify whether the file itself exists. attributes = NativeIO.GetAttributes(path); if (attributes == 0xFFFFFFFF) { // No-op on file not found return; } if ((attributes & (uint)(FileAttributes.Directory | FileAttributes.ReadOnly)) != 0) { /// it's a readonly file or an directory #if EXCEPTION_STRINGS throw new IOException("", (int)IOExceptionErrorCode.UnauthorizedAccess); #else throw new IOException(); #endif } NativeIO.Delete(path); } finally { // regardless of what happened, we need to release the file when we're done FileSystemManager.RemoveFromOpenList(record); } } // Tests if a file exists. The result is true if the file // given by the specified path exists; otherwise, the result is // false. Note that if path describes a directory, // Exists will return true. // // Your application must have Read permission for the target directory. // public static bool Exists(String path) { try { // path validation in Path.GetFullPath() path = Path.GetFullPath(path); /// Is this the absolute root? this is not a file. string root = Path.GetPathRoot(path); if (String.Equals(root, path)) { return false; } else { uint attributes = NativeIO.GetAttributes(path); /// This is essentially file not found. if (attributes == 0xFFFFFFFF) return false; if ((attributes & (uint)FileAttributes.Directory) == 0) { /// Not a directory, it must be a file. return true; } } } catch (Exception) { /// Like desktop, exists here does not throw exception in /// a number of cases, instead returns false. For more /// details see MSDN. } return false; } public static FileStream Open(String path, FileMode mode) { return new FileStream(path, mode, (mode == FileMode.Append ? FileAccess.Write : FileAccess.ReadWrite), FileShare.None, NativeFileStream.BufferSizeDefault); } public static FileStream Open(String path, FileMode mode, FileAccess access) { return new FileStream(path, mode, access, FileShare.None, NativeFileStream.BufferSizeDefault); } public static FileStream Open(String path, FileMode mode, FileAccess access, FileShare share) { return new FileStream(path, mode, access, share, NativeFileStream.BufferSizeDefault); } public static FileAttributes GetAttributes(String path) { // path validation in Path.GetFullPath() String fullPath = Path.GetFullPath(path); uint attributes = NativeIO.GetAttributes(fullPath); if (attributes == 0xFFFFFFFF) #if EXCEPTION_STRINGS throw new IOException("", (int)IOExceptionErrorCode.FileNotFound); #else throw new IOException(); #endif else if (attributes == 0x0) return FileAttributes.Normal; else return (FileAttributes)attributes; } public static void SetAttributes(String path, FileAttributes fileAttributes) { // path validation in Path.GetFullPath() String fullPath = Path.GetFullPath(path); NativeIO.SetAttributes(fullPath, (uint)fileAttributes); } public static FileStream OpenRead(String path) { return new FileStream(path, FileMode.Open, FileAccess.Read, FileShare.Read, NativeFileStream.BufferSizeDefault); } public static FileStream OpenWrite(String path) { return new FileStream(path, FileMode.OpenOrCreate, FileAccess.Write, FileShare.None, NativeFileStream.BufferSizeDefault); } public static byte[] ReadAllBytes(String path) { byte[] bytes; using (FileStream fs = new FileStream(path, FileMode.Open, FileAccess.Read, FileShare.Read, NativeFileStream.BufferSizeDefault)) { // Do a blocking read int index = 0; long fileLength = fs.Length; if (fileLength > Int32.MaxValue) throw new IOException(); int count = (int)fileLength; bytes = new byte[count]; while (count > 0) { int n = fs.Read(bytes, index, count); index += n; count -= n; } } return bytes; } public static void WriteAllBytes(String path, byte[] bytes) { if (bytes == null) #if EXCEPTION_STRINGS throw new ArgumentNullException("bytes"); #else throw new ArgumentNullException(); #endif using (FileStream fs = new FileStream(path, FileMode.Create, FileAccess.Write, FileShare.Read, NativeFileStream.BufferSizeDefault)) fs.Write(bytes, 0, bytes.Length); } // Moves a specified file to a new location and potentially a new file name. // This method does work across volumes. // // The caller must have certain FileIOPermissions. The caller must // have Read and Write permission to // sourceFileName and Write // permissions to destFileName. // public static void Move(String sourceFileName, String destFileName) { // sourceFileName and destFileName validation in Path.GetFullPath() sourceFileName = Path.GetFullPath(sourceFileName); destFileName = Path.GetFullPath(destFileName); bool tryCopyAndDelete = false; // We only need to lock the source, not the dest because if dest is taken // Move() will failed at the driver's level anyway. (there will be no conflict even if // another thread is creating dest, as only one of the operations will succeed -- // the native calls are atomic) Object srcRecord = FileSystemManager.AddToOpenList(sourceFileName); try { if (!Exists(sourceFileName)) { #if EXCEPTION_STRINGS throw new IOException("", (int)IOExceptionErrorCode.FileNotFound); #else throw new IOException(); #endif } if (Exists( destFileName )) { #if EXCEPTION_STRINGS throw new IOException( "", (int)IOExceptionErrorCode.PathAlreadyExists ); #else throw new IOException(); #endif } //We'll try copy and deleting if Move returns false // ZeligBUG - the following fails to set tryCopyAndDelete //tryCopyAndDelete = !NativeIO.Move( sourceFileName, destFileName ); if(false == NativeIO.Move( sourceFileName, destFileName )) { tryCopyAndDelete = true; } } finally { FileSystemManager.RemoveFromOpenList(srcRecord); } if (tryCopyAndDelete) { Copy(sourceFileName, destFileName, false, true); } } } } ================================================ FILE: Zelig/Zelig/RunTime/Framework/mscorlib/System/IO/FileAccess.cs ================================================ //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // Copyright (c) Microsoft Corporation. All rights reserved. //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// using System; namespace System.IO { // Contains constants for specifying the access you want for a file. // You can have Read, Write or ReadWrite access. // [Serializable, Flags] public enum FileAccess { // Specifies read access to the file. Data can be read from the file and // the file pointer can be moved. Combine with WRITE for read-write access. Read = 1, // Specifies write access to the file. Data can be written to the file and // the file pointer can be moved. Combine with READ for read-write access. Write = 2, // Specifies read and write access to the file. Data can be written to the // file and the file pointer can be moved. Data can also be read from the // file. ReadWrite = 3, } } ================================================ FILE: Zelig/Zelig/RunTime/Framework/mscorlib/System/IO/FileAttributes.cs ================================================ //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // Copyright (c) Microsoft Corporation. All rights reserved. //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// using System; namespace System.IO { [Flags] public enum FileAttributes { ReadOnly = 0x1, Hidden = 0x2, System = 0x4, Directory = 0x10, Archive = 0x20, Normal = 0x80, } } ================================================ FILE: Zelig/Zelig/RunTime/Framework/mscorlib/System/IO/FileEnum.cs ================================================ //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // Copyright (c) Microsoft Corporation. All rights reserved. //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// using System; using System.Collections; namespace System.IO { public enum FileEnumFlags { Files = 0x0001, Directories = 0x0002, FilesAndDirectories = Files | Directories, } public class FileEnum : IEnumerator, IDisposable { private NativeFindFile m_findFile; private NativeFileInfo m_currentFile; private FileEnumFlags m_flags; private string m_path; private bool m_disposed; private object m_openForReadHandle; public FileEnum(string path, FileEnumFlags flags) { m_flags = flags; m_path = path; m_openForReadHandle = FileSystemManager.AddToOpenListForRead(m_path); m_findFile = new NativeFindFile(m_path, "*"); } #region IEnumerator Members public object Current { get { if (m_disposed) #if EXCEPTION_STRINGS throw new ObjectDisposedException(""); #else throw new ObjectDisposedException(null); #endif return Path.Combine(m_path, m_currentFile.FileName); } } public bool MoveNext() { if (m_disposed) #if EXCEPTION_STRINGS throw new ObjectDisposedException(""); #else throw new ObjectDisposedException(null); #endif NativeFileInfo fileinfo = m_findFile.GetNext(); while (fileinfo != null) { if (m_flags != FileEnumFlags.FilesAndDirectories) { uint targetAttribute = (0 != (m_flags & FileEnumFlags.Directories) ? (uint)FileAttributes.Directory : 0); if ((fileinfo.Attributes & (uint)FileAttributes.Directory) == targetAttribute) { m_currentFile = fileinfo; break; } } else { m_currentFile = fileinfo; break; } fileinfo = m_findFile.GetNext(); } if (fileinfo == null) { m_findFile.Close(); m_findFile = null; FileSystemManager.RemoveFromOpenList(m_openForReadHandle); m_openForReadHandle = null; } return fileinfo != null; } public void Reset() { if (m_disposed) #if EXCEPTION_STRINGS throw new ObjectDisposedException(""); #else throw new ObjectDisposedException(null); #endif if (m_findFile != null) { m_findFile.Close(); } if(m_openForReadHandle == null) { m_openForReadHandle = FileSystemManager.AddToOpenListForRead(m_path); } m_findFile = new NativeFindFile(m_path, "*"); } #endregion protected virtual void Dispose(bool disposing) { if (m_findFile != null) { m_findFile.Close(); m_findFile = null; } if (m_openForReadHandle != null) { FileSystemManager.RemoveFromOpenList(m_openForReadHandle); m_openForReadHandle = null; } m_disposed = true; } ~FileEnum() { Dispose(false); } #region IDisposable Members public void Dispose() { Dispose(true); GC.SuppressFinalize(this); } #endregion } public class FileEnumerator : IEnumerable { private string m_path; private FileEnumFlags m_flags; public FileEnumerator(string path, FileEnumFlags flags) { m_path = Path.GetFullPath(path); m_flags = flags; if (!Directory.Exists(m_path)) #if EXCEPTION_STRINGS throw new IOException("", (int)IOExceptionErrorCode.DirectoryNotFound); #else throw new IOException(); #endif } #region IEnumerable Members public IEnumerator GetEnumerator() { return new FileEnum(m_path, m_flags); } #endregion } } ================================================ FILE: Zelig/Zelig/RunTime/Framework/mscorlib/System/IO/FileInfo.cs ================================================ //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // Copyright (c) Microsoft Corporation. All rights reserved. //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// using System; namespace System.IO { [Serializable] public sealed class FileInfo : FileSystemInfo { public FileInfo(String fileName) { // path validation in Path.GetFullPath() m_fullPath = Path.GetFullPath(fileName); } public override String Name { get { return Path.GetFileName(m_fullPath); } } public long Length { get { RefreshIfNull(); return (long)_nativeFileInfo.Size; } } public String DirectoryName { get { return Path.GetDirectoryName(m_fullPath); } } public DirectoryInfo Directory { get { String dirName = DirectoryName; if (dirName == null) { return null; } return new DirectoryInfo(dirName); } } public FileStream Create() { return File.Create(m_fullPath); } public override void Delete() { File.Delete(m_fullPath); } public override bool Exists { get { return File.Exists(m_fullPath); } } public FileStream Open(FileMode mode) { return Open(mode, FileAccess.ReadWrite, FileShare.None); } public FileStream Open(FileMode mode, FileAccess access) { return Open(mode, access, FileShare.None); } public FileStream Open(FileMode mode, FileAccess access, FileShare share) { return new FileStream(FullName, mode, access, share); } public override String ToString() { return m_fullPath; } } } ================================================ FILE: Zelig/Zelig/RunTime/Framework/mscorlib/System/IO/FileMode.cs ================================================ //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // Copyright (c) Microsoft Corporation. All rights reserved. //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// using System; namespace System.IO { // Contains constants for specifying how the OS should open a file. // These will control whether you overwrite a file, open an existing // file, or some combination thereof. // // To append to a file, use Append (which maps to OpenOrCreate then we seek // to the end of the file). To truncate a file or create it if it doesn't // exist, use Create. // [Serializable] public enum FileMode { // Creates a new file. An exception is raised if the file already exists. CreateNew = 1, // Creates a new file. If the file already exists, it is overwritten. Create = 2, // Opens an existing file. An exception is raised if the file does not exist. Open = 3, // Opens the file if it exists. Otherwise, creates a new file. OpenOrCreate = 4, // Opens an existing file. Once opened, the file is truncated so that its // size is zero bytes. The calling process must open the file with at least // WRITE access. An exception is raised if the file does not exist. Truncate = 5, // Opens the file if it exists and seeks to the end. Otherwise, // creates a new file. Append = 6, } } ================================================ FILE: Zelig/Zelig/RunTime/Framework/mscorlib/System/IO/FileShare.cs ================================================ //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // Copyright (c) Microsoft Corporation. All rights reserved. //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// using System; namespace System.IO { // Contains constants for controlling file sharing options while // opening files. You can specify what access other processes trying // to open the same file concurrently can have. [Serializable, Flags] public enum FileShare { // No sharing. Any request to open the file (by this process or another // process) will fail until the file is closed. None = 0, // Allows subsequent opening of the file for reading. If this flag is not // specified, any request to open the file for reading (by this process or // another process) will fail until the file is closed. Read = 1, // Allows subsequent opening of the file for writing. If this flag is not // specified, any request to open the file for writing (by this process or // another process) will fail until the file is closed. Write = 2, // Allows subsequent opening of the file for writing or reading. If this flag // is not specified, any request to open the file for writing or reading (by // this process or another process) will fail until the file is closed. ReadWrite = 3, } } ================================================ FILE: Zelig/Zelig/RunTime/Framework/mscorlib/System/IO/FileStream.cs ================================================ //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // Copyright (c) Microsoft Corporation. All rights reserved. //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// using System.Threading; namespace System.IO { public class FileStream : Stream { // Driver data private NativeFileStream _nativeFileStream; private FileSystemManager.FileRecord _fileRecord; private String _fileName; private bool _canRead; private bool _canWrite; private bool _canSeek; private long _seekLimit; private bool _disposed; //--// public FileStream( String path, FileMode mode ) : this( path, mode, ( mode == FileMode.Append ? FileAccess.Write : FileAccess.ReadWrite ), FileShare.Read, NativeFileStream.BufferSizeDefault ) { } public FileStream( String path, FileMode mode, FileAccess access ) : this( path, mode, access, FileShare.Read, NativeFileStream.BufferSizeDefault ) { } public FileStream( String path, FileMode mode, FileAccess access, FileShare share ) : this( path, mode, access, share, NativeFileStream.BufferSizeDefault ) { } public FileStream( String path, FileMode mode, FileAccess access, FileShare share, int bufferSize ) { // This will perform validation on path _fileName = Path.GetFullPath( path ); // make sure mode, access, and share are within range if(mode < FileMode.CreateNew || mode > FileMode.Append || access < FileAccess.Read || access > FileAccess.ReadWrite || share < FileShare.None || share > FileShare.ReadWrite) { throw new ArgumentOutOfRangeException(); } // Get wantsRead and wantsWrite from access, note that they cannot both be false bool wantsRead = ( access & FileAccess.Read ) == FileAccess.Read; bool wantsWrite = ( access & FileAccess.Write ) == FileAccess.Write; // You can't open for readonly access (wantsWrite == false) when // mode is CreateNew, Create, Truncate or Append (when it's not Open or OpenOrCreate) if(mode != FileMode.Open && mode != FileMode.OpenOrCreate) // && !wantsWrite) // TODO: BUGBUG: this line produces a compiler bug { // this line added because of bug above if(( access & FileAccess.Write ) != FileAccess.Write) { throw new ArgumentException(); } } // We need to register the share information prior to the actual file open call (the NativeFileStream ctor) // so subsequent file operation on the same file will behave correctly _fileRecord = FileSystemManager.AddToOpenList( _fileName, (int)access, (int)share ); try { uint attributes = NativeIO.GetAttributes( _fileName ); bool exists = ( attributes != 0xFFFFFFFF ); bool isReadOnly = ( exists ) ? ( ( (FileAttributes)attributes ) & FileAttributes.ReadOnly ) == FileAttributes.ReadOnly : false; // If the path specified is an existing directory, fail if(exists && ( ( ( (FileAttributes)attributes ) & FileAttributes.Directory ) == FileAttributes.Directory )) { #if EXCEPTION_STRINGS throw new IOException( "", (int)IOExceptionErrorCode.UnauthorizedAccess ); #else throw new IOException(); #endif } // The seek limit is 0 (the beginning of the file) for all modes except Append _seekLimit = 0; switch(mode) { case FileMode.CreateNew: // if the file exists, IOException is thrown if(exists) #if EXCEPTION_STRINGS throw new IOException( "", (int)IOExceptionErrorCode.PathAlreadyExists ); #else throw new IOException(); #endif _nativeFileStream = new NativeFileStream( _fileName, bufferSize ); break; case FileMode.Create: // if the file exists, it should be overwritten _nativeFileStream = new NativeFileStream( _fileName, bufferSize ); if(exists) _nativeFileStream.SetLength( 0 ); break; case FileMode.Open: // if the file does not exist, IOException/FileNotFound is thrown if(!exists) #if EXCEPTION_STRINGS throw new IOException( "", (int)IOExceptionErrorCode.FileNotFound ); #else throw new IOException(); #endif _nativeFileStream = new NativeFileStream( _fileName, bufferSize ); break; case FileMode.OpenOrCreate: // if the file does not exist, it is created _nativeFileStream = new NativeFileStream( _fileName, bufferSize ); break; case FileMode.Truncate: // the file would be overwritten. if the file does not exist, IOException/FileNotFound is thrown if(!exists) #if EXCEPTION_STRINGS throw new IOException( "", (int)IOExceptionErrorCode.FileNotFound ); #else throw new IOException(); #endif _nativeFileStream = new NativeFileStream( _fileName, bufferSize ); _nativeFileStream.SetLength( 0 ); break; case FileMode.Append: // Opens the file if it exists and seeks to the end of the file. Append can only be used in conjunction with FileAccess.Write // Attempting to seek to a position before the end of the file will throw an IOException and any attempt to read fails and throws an NotSupportedException if(access != FileAccess.Write) throw new ArgumentException(); _nativeFileStream = new NativeFileStream( _fileName, bufferSize ); _seekLimit = _nativeFileStream.Seek( 0, (uint)SeekOrigin.End ); break; // We've already checked the mode value previously, so no need for default //default: // throw new ArgumentOutOfRangeException(); } // Now that we have a valid NativeFileStream, we add it to the FileRecord, so it could gets clean up // in case an eject or force format _fileRecord.NativeFileStream = _nativeFileStream; // Retrive the filesystem capabilities _nativeFileStream.GetStreamProperties( out _canRead, out _canWrite, out _canSeek ); // If the file is readonly, regardless of the filesystem capability, we'll turn off write if(isReadOnly) { _canWrite = false; } // Make sure the requests (wantsRead / wantsWrite) matches the filesystem capabilities (canRead / canWrite) // ZeligBUG - the second check fails if wantsWrite = true and _canWrite = false //if(( wantsRead && !_canRead ) || ( wantsWrite && !_canWrite )) if( wantsRead && !_canRead ) { #if EXCEPTION_STRINGS throw new IOException( "", (int)IOExceptionErrorCode.UnauthorizedAccess ); #else throw new IOException(); #endif } // ZeligBUG - this fixes bug above... (also, for some reason, wantsWrite is not being compiled correctly) if(( access & FileAccess.Write ) == FileAccess.Write && isReadOnly) { #if EXCEPTION_STRINGS throw new IOException( "", (int)IOExceptionErrorCode.UnauthorizedAccess ); #else throw new IOException(); #endif } // finally, adjust the _canRead / _canWrite to match the requests if(!wantsWrite) { _canWrite = false; } else if(!wantsRead) { _canRead = false; } } catch { // something went wrong, clean up and re-throw the exception if(_nativeFileStream != null) { _nativeFileStream.Close(); } FileSystemManager.RemoveFromOpenList( _fileRecord ); throw; } } protected override void Dispose( bool disposing ) { if(!_disposed) { try { if(disposing) { _canRead = false; _canWrite = false; _canSeek = false; } if(_nativeFileStream != null) { _nativeFileStream.Close(); } } finally { if(_fileRecord != null) { FileSystemManager.RemoveFromOpenList( _fileRecord ); _fileRecord = null; } _nativeFileStream = null; _disposed = true; } } } ~FileStream() { Dispose( false ); } // This is for internal use to support proper atomic CopyAndDelete internal void DisposeAndDelete() { _nativeFileStream.Close(); _nativeFileStream = null; // so Dispose(true) won't close the stream again NativeIO.Delete( _fileName ); Dispose( true ); } public override void Flush() { if(_disposed) #if EXCEPTION_STRINGS throw new ObjectDisposedException( "" ); #else throw new ObjectDisposedException( null ); #endif _nativeFileStream.Flush(); } public override void SetLength( long value ) { if(_disposed) #if EXCEPTION_STRINGS throw new ObjectDisposedException( "" ); #else throw new ObjectDisposedException( null ); #endif if(!_canWrite || !_canSeek) throw new NotSupportedException(); // argument validation in interop layer _nativeFileStream.SetLength( value ); } public override int Read( byte[] buffer, int offset, int count ) { if(_disposed) #if EXCEPTION_STRINGS throw new ObjectDisposedException( typeof( FileStream ).ToString() ); #else throw new ObjectDisposedException( null ); #endif if(!_canRead) throw new NotSupportedException(); lock(_nativeFileStream) { // argument validation in interop layer return _nativeFileStream.Read( buffer, offset, count, NativeFileStream.TimeoutDefault ); } } public override long Seek( long offset, SeekOrigin origin ) { if(_disposed) #if EXCEPTION_STRINGS throw new ObjectDisposedException( typeof( FileStream ).ToString() ); #else throw new ObjectDisposedException( null ); #endif if(!_canSeek) throw new NotSupportedException(); long oldPosition = this.Position; long newPosition = _nativeFileStream.Seek( offset, (uint)origin ); if(newPosition < _seekLimit) { this.Position = oldPosition; throw new IOException(); } return newPosition; } public override void Write( byte[] buffer, int offset, int count ) { if(_disposed) #if EXCEPTION_STRINGS throw new ObjectDisposedException( typeof( FileStream ).ToString() ); #else throw new ObjectDisposedException( null ); #endif if(!_canWrite) throw new NotSupportedException(); // argument validation in interop layer int bytesWritten; lock(_nativeFileStream) { // we check for count being != 0 because we want to handle negative cases // as well in the interop layer while(count != 0) { bytesWritten = _nativeFileStream.Write( buffer, offset, count, NativeFileStream.TimeoutDefault ); if(bytesWritten == 0) throw new IOException(); offset += bytesWritten; count -= bytesWritten; } } } public override bool CanRead { get { return _canRead; } } public override bool CanWrite { get { return _canWrite; } } public override bool CanSeek { get { return _canSeek; } } public virtual bool IsAsync { get { return false; } } public override long Length { get { if(_disposed) #if EXCEPTION_STRINGS throw new ObjectDisposedException(""); #else throw new ObjectDisposedException( null ); #endif if(!_canSeek) throw new NotSupportedException(); return _nativeFileStream.GetLength(); } } public String Name { get { return _fileName; } } public override long Position { get { if(_disposed) #if EXCEPTION_STRINGS throw new ObjectDisposedException(""); #else throw new ObjectDisposedException( null ); #endif if(!_canSeek) throw new NotSupportedException(); // argument validation in interop layer return _nativeFileStream.Seek( 0, (uint)SeekOrigin.Current ); } set { if(_disposed) #if EXCEPTION_STRINGS throw new ObjectDisposedException(""); #else throw new ObjectDisposedException( null ); #endif if(!_canSeek) throw new NotSupportedException(); if(value < _seekLimit) throw new IOException(); // argument validation in interop layer _nativeFileStream.Seek( value, (uint)SeekOrigin.Begin ); } } } } ================================================ FILE: Zelig/Zelig/RunTime/Framework/mscorlib/System/IO/FileSystemInfo.cs ================================================ //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // Copyright (c) Microsoft Corporation. All rights reserved. //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// using System; namespace System.IO { public abstract class FileSystemInfo : MarshalByRefObject { protected String m_fullPath; // fully qualified path of the directory //--// public virtual String FullName { get { return m_fullPath; } } public String Extension { get { return Path.GetExtension(FullName); } } public abstract String Name { get; } public abstract bool Exists { get; } public abstract void Delete(); public FileAttributes Attributes { get { RefreshIfNull(); return (FileAttributes)_nativeFileInfo.Attributes; } } public DateTime CreationTime { get { return CreationTimeUtc.ToLocalTime(); } } public DateTime CreationTimeUtc { get { RefreshIfNull(); return new DateTime(_nativeFileInfo.CreationTime); } } public DateTime LastAccessTime { get { return LastAccessTimeUtc.ToLocalTime(); } } public DateTime LastAccessTimeUtc { get { RefreshIfNull(); return new DateTime(_nativeFileInfo.LastAccessTime); } } public DateTime LastWriteTime { get { return LastWriteTimeUtc.ToLocalTime(); } } public DateTime LastWriteTimeUtc { get { RefreshIfNull(); return new DateTime(_nativeFileInfo.LastWriteTime); } } public void Refresh() { Object record = FileSystemManager.AddToOpenListForRead(m_fullPath); try { _nativeFileInfo = NativeFindFile.GetFileInfo(m_fullPath); if (_nativeFileInfo == null) { IOExceptionErrorCode errorCode = (this is FileInfo) ? IOExceptionErrorCode.FileNotFound : IOExceptionErrorCode.DirectoryNotFound; #if EXCEPTION_STRINGS throw new IOException("", (int)errorCode); #else throw new IOException(); #endif } } finally { FileSystemManager.RemoveFromOpenList(record); } } protected void RefreshIfNull() { if (_nativeFileInfo == null) { Refresh(); } } internal NativeFileInfo _nativeFileInfo; } } ================================================ FILE: Zelig/Zelig/RunTime/Framework/mscorlib/System/IO/FileSystemManager.cs ================================================ using System; using System.Collections; using System.Runtime.CompilerServices; namespace System.IO { internal class FileSystemManager { // KEEP IN-SYNC WITH FileAccess.cs and FileShare.cs private const int FileAccessRead = 1; private const int FileAccessWrite = 2; private const int FileAccessReadWrite = 3; private const int FileShareNone = 0; private const int FileShareRead = 1; private const int FileShareWrite = 2; private const int FileShareReadWrite = 3; //--// internal class FileRecord { public String FullName; public NativeFileStream NativeFileStream; public int Share; public FileRecord(String fullName, int share) { FullName = fullName; Share = share; } } // private static ArrayList m_openFiles = new ArrayList(); private static ArrayList m_lockedDirs = new ArrayList(); //--// public static Object AddToOpenList(String fullName) { return AddToOpenList(fullName, FileAccessReadWrite, FileShareNone); } public static Object AddToOpenListForRead(String fullName) { return AddToOpenList(fullName, FileAccessRead, FileShareReadWrite); } public static FileRecord AddToOpenList(String fullName, int access, int share) { fullName = fullName.ToUpper(); FileRecord record = new FileRecord(fullName, share); lock (m_openFiles) { int count = m_lockedDirs.Count; for (int i = 0; i < count; i++) { if (IsInDirectory(fullName, (String)m_lockedDirs[i])) { #if EXCEPTION_STRINGS throw new IOException("", (int)IOExceptionErrorCode.UnauthorizedAccess); #else throw new IOException(); #endif } } FileRecord current; count = m_openFiles.Count; for (int i = 0; i < count; ++i) { current = (FileRecord)m_openFiles[i]; if (current.FullName == fullName) { // Given the previous fileshare info and the requested fileaccess and fileshare // the following is the ONLY combinations that we should allow -- All others // should failed with IOException // (Behavior verified on desktop .NET) // // Previous FileShare Requested FileAccess Requested FileShare // Read Read ReadWrite // Write Write ReadWrite // ReadWrite Read ReadWrite // ReadWrite Write ReadWrite // ReadWrite ReadWrite ReadWrite // // The following check take advantage of the fact that the value for // Read, Write, and ReadWrite in FileAccess enum and FileShare enum are // identical. if ((share != FileShareReadWrite) || ((current.Share & access) != access)) { #if EXCEPTION_STRINGS throw new IOException("", (int)IOExceptionErrorCode.UnauthorizedAccess); #else throw new IOException(); #endif } } } m_openFiles.Add(record); } return record; } public static void RemoveFromOpenList(Object record) { lock (m_openFiles) { m_openFiles.Remove(record); } } public static Object LockDirectory(String directory) { directory = directory.ToUpper(); lock (m_openFiles) { int count = m_openFiles.Count; for (int i = 0; i < count; i++) { if (IsInDirectory(((FileRecord)m_openFiles[i]).FullName, directory)) { #if EXCEPTION_STRINGS throw new IOException("", (int)IOExceptionErrorCode.UnauthorizedAccess); #else throw new IOException(); #endif } } count = m_lockedDirs.Count; for (int i = 0; i < count; i++) { if (((String)m_lockedDirs[i]) == directory) { #if EXCEPTION_STRINGS throw new IOException("", (int)IOExceptionErrorCode.UnauthorizedAccess); #else throw new IOException(); #endif } } m_lockedDirs.Add(directory); } return (Object)directory; } public static void UnlockDirectory(Object record) { lock (m_openFiles) { m_lockedDirs.Remove(record); } } public static void UnlockDirectory(String directory) { directory = directory.ToUpper(); lock (m_openFiles) { int count = m_lockedDirs.Count; for (int i = 0; i < count; i++) { if (((String)m_lockedDirs[i]) == directory) { m_lockedDirs.RemoveAt(i); break; } } } } public static void ForceRemoveNameSpace(String nameSpace) { String root = "\\" + nameSpace.ToUpper(); FileRecord record; lock (m_openFiles) { int count = m_openFiles.Count; for (int i = 0; i < count; i++) { record = (FileRecord)m_openFiles[i]; if (IsInDirectory(record.FullName, root)) { if (record.NativeFileStream != null) { record.NativeFileStream.Close(); } m_openFiles.RemoveAt(i); } } } } public static bool IsInDirectory(String path, String directory) { string[] paths = path.ToLower().Split( '\\' ); string[] dirs = directory.ToLower().Split( '\\' ); if(dirs.Length > paths.Length) return false; for(int i = 0; i < dirs.Length; i++) { if(dirs[i] != paths[i]) { return false; } } return true; //if (path.IndexOf(directory) == 0) //{ // int directoryLength = directory.Length; // if (path.Length > directoryLength) // { // return path[directoryLength] == '\\'; // } // else // { // return true; // } //} //return false; } //--// public static String CurrentDirectory = NativeIO.FSRoot; private static Object m_currentDirectoryRecord = null; //--// internal static void SetCurrentDirectory(String path) { if (m_currentDirectoryRecord != null) // implies that CurrentDirectory != NativeIO.FSRoot { RemoveFromOpenList(m_currentDirectoryRecord); } if (path != NativeIO.FSRoot) { m_currentDirectoryRecord = AddToOpenListForRead(path); } else { m_currentDirectoryRecord = null; } CurrentDirectory = path; } } } ================================================ FILE: Zelig/Zelig/RunTime/Framework/mscorlib/System/IO/IO.cs ================================================ //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // Copyright (c) Microsoft Corporation. All rights reserved. //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// using System; using System.IO; using System.Runtime.CompilerServices; [assembly: System.Runtime.CompilerServices.InternalsVisibleTo("System.IO")] namespace System.IO { public enum IOExceptionErrorCode { Others = -536870912, InvalidDriver = -520093696, FileNotFound = -503316480, DirectoryNotFound = -486539264, VolumeNotFound = -469762048, PathTooLong = -452984832, DirectoryNotEmpty = -436207616, UnauthorizedAccess = -419430400, PathAlreadyExists = -402653184, TooManyOpenHandles = -385875968, } internal class NativeFileStream { public const int TimeoutDefault = 0; public const int BufferSizeDefault = 0; [MethodImplAttribute(MethodImplOptions.InternalCall)] public extern NativeFileStream( string path, int bufferSize ); [MethodImplAttribute(MethodImplOptions.InternalCall)] public extern int Read(byte[] buf, int offset, int count, int timeout); [MethodImplAttribute(MethodImplOptions.InternalCall)] public extern int Write(byte[] buf, int offset, int count, int timeout); [MethodImplAttribute(MethodImplOptions.InternalCall)] public extern long Seek(long offset, uint origin); [MethodImplAttribute(MethodImplOptions.InternalCall)] public extern void Flush(); [MethodImplAttribute(MethodImplOptions.InternalCall)] public extern long GetLength(); [MethodImplAttribute(MethodImplOptions.InternalCall)] public extern void SetLength(long length); [MethodImplAttribute(MethodImplOptions.InternalCall)] public extern void GetStreamProperties(out bool canRead, out bool canWrite, out bool canSeek); [MethodImplAttribute(MethodImplOptions.InternalCall)] public extern void Close(); } internal class NativeFileInfo { public uint Attributes; public long CreationTime; public long LastAccessTime; public long LastWriteTime; public long Size; public String FileName; } internal class NativeFindFile { //object m_ff; [MethodImplAttribute(MethodImplOptions.InternalCall)] internal extern NativeFindFile(string path, string searchPattern); [MethodImplAttribute(MethodImplOptions.InternalCall)] public extern NativeFileInfo GetNext(); [MethodImplAttribute(MethodImplOptions.InternalCall)] public extern void Close(); [MethodImplAttribute(MethodImplOptions.InternalCall)] public static extern NativeFileInfo GetFileInfo(String path); } internal static class NativeIO { internal const string FSRoot = @"\"; internal const int FSMaxPathLength = 260 - 2; // From FS_decl.h internal const int FSMaxFilenameLength = 256; // From FS_decl.h internal const int FSNameMaxLength = 7 + 1; // From FS_decl.h [MethodImplAttribute(MethodImplOptions.InternalCall)] internal static extern void Format(String nameSpace, String fileSystem, String volumeLabel, uint parameter); [MethodImplAttribute(MethodImplOptions.InternalCall)] internal static extern void Delete(string path); [MethodImplAttribute(MethodImplOptions.InternalCall)] internal static extern bool Move(string sourceFileName, string destFileName); [MethodImplAttribute(MethodImplOptions.InternalCall)] internal static extern void CreateDirectory(string path); [MethodImplAttribute(MethodImplOptions.InternalCall)] internal static extern uint GetAttributes(string path); [MethodImplAttribute(MethodImplOptions.InternalCall)] internal static extern void SetAttributes(string path, uint attributes); } } ================================================ FILE: Zelig/Zelig/RunTime/Framework/mscorlib/System/IO/IOException.cs ================================================ // ==++== // // Copyright (c) Microsoft Corporation. All rights reserved. // // ==--== /*============================================================ ** ** Class: IOException ** ** ** Purpose: Exception for a generic IO error. ** ** ===========================================================*/ using System; using System.Runtime.Serialization; namespace System.IO { [Serializable] public class IOException : SystemException { // For debugging purposes, store the complete path in the IOException // if possible. Don't give it back to users due to security concerns. // Let the code that throws the exception worry about that. But we can // at least assist people attached to the process with a managed // debugger. Don't serialize it to avoid any security problems. // This information isn't guaranteed to be correct, but is our second // best effort at a file or directory involved, after the exception // message. [NonSerialized] private String _maybeFullPath; // For debuggers on partial trust code private int _hresult; #if EXCEPTION_STRINGS public IOException() : base( Environment.GetResourceString( "Arg_IOException" ) ) #else public IOException() #endif { //// SetErrorCode( __HResults.COR_E_IO ); } public IOException( String message ) : base( message ) { //// SetErrorCode( __HResults.COR_E_IO ); } public IOException( String message, int hresult ) : base( message ) { SetErrorCode( hresult ); } // Adding this for debuggers when looking at exceptions in partial // trust code that may not have interesting path information in // the exception message. internal IOException( String message, int hresult, String maybeFullPath ) : base( message ) { SetErrorCode( hresult ); _maybeFullPath = maybeFullPath; } public IOException( String message, Exception innerException ) : base( message, innerException ) { //// SetErrorCode( __HResults.COR_E_IO ); } internal void SetErrorCode( int hresult ) { _hresult = hresult; base.m_message += "\n\tHRESULT = 0x" + hresult.ToString('X'); } public int ErrorCode { get { return _hresult; } } //// protected IOException( SerializationInfo info, StreamingContext context ) : base( info, context ) //// { //// } } } ================================================ FILE: Zelig/Zelig/RunTime/Framework/mscorlib/System/IO/MediaManager.cs ================================================ //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // Copyright (c) Microsoft Corporation. All rights reserved. //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// using System; using System.IO; using System.Collections; using System.Threading; using System.Runtime.CompilerServices; namespace System.IO { internal enum StorageEventType : byte { Invalid = 0, Insert = 1, Eject = 2, } public class BaseEvent { public byte EventMessage; public ushort Source; } public interface IEventProcessor { BaseEvent ProcessEvent( uint data1, uint data2, DateTime time ); } public interface IEventListener { void InitializeForEventSource(); bool OnEvent( BaseEvent ev ); } internal class StorageEvent : BaseEvent { public StorageEventType EventType; public uint Handle; public DateTime Time; } internal class StorageEventProcessor : IEventProcessor { public BaseEvent ProcessEvent( uint data1, uint data2, DateTime time ) { StorageEvent ev = new StorageEvent(); ev.EventType = (StorageEventType)( data1 & 0xFF ); ev.Handle = data2; ev.Time = time; return ev; } } internal class StorageEventListener : IEventListener { public void InitializeForEventSource() { } public bool OnEvent( BaseEvent ev ) { if(ev is StorageEvent) { RemovableMedia.PostEvent( (StorageEvent)ev ); } return true; } } public sealed class VolumeInfo { internal uint VolumePtr; public extern String Name { [MethodImplAttribute( MethodImplOptions.InternalCall )] get; } public extern String VolumeLabel { [MethodImplAttribute( MethodImplOptions.InternalCall )] get; } public uint VolumeID { get { return VolumePtr; } } public extern String FileSystem { [MethodImplAttribute( MethodImplOptions.InternalCall )] get; } //public extern uint FileSystemFlags //{ // [MethodImplAttribute( MethodImplOptions.InternalCall )] // get; //} //public extern uint DeviceFlags //{ // [MethodImplAttribute( MethodImplOptions.InternalCall )] // get; //} //public extern uint SerialNumber //{ // [MethodImplAttribute( MethodImplOptions.InternalCall )] // get; //} public extern long TotalFreeSpace { [MethodImplAttribute( MethodImplOptions.InternalCall )] get; } public extern long TotalSize { [MethodImplAttribute( MethodImplOptions.InternalCall )] get; } [MethodImplAttribute(MethodImplOptions.InternalCall)] public extern VolumeInfo(String volumeName); [MethodImplAttribute(MethodImplOptions.InternalCall)] internal extern VolumeInfo(uint volumePtr); // This is used internally to create a VolumeInfo for removable volumes that have been ejected internal VolumeInfo(VolumeInfo ejectedVolumeInfo) { //Name = ejectedVolumeInfo.Name; } [MethodImplAttribute(MethodImplOptions.InternalCall)] public extern void Refresh(); public String RootDirectory { get { return "\\" + Name; } } public bool IsFormatted { get { return FileSystem != null && TotalSize > 0; } } public void Format(uint parameter) { Format(FileSystem, parameter, VolumeLabel, false); } public void Format(uint parameter, bool force) { Format(FileSystem, parameter, VolumeLabel, force); } public void Format(String fileSystem, uint parameter) { Format(fileSystem, parameter, VolumeLabel, false); } public void Format(String fileSystem, uint parameter, bool force) { Format( fileSystem, parameter, VolumeLabel, force ); } public void Format(String fileSystem, uint parameter, String volumeLabel, bool force ) { String rootedNameSpace = "\\" + Name; bool restoreCD = FileSystemManager.CurrentDirectory == rootedNameSpace; if (FileSystemManager.IsInDirectory(FileSystemManager.CurrentDirectory, rootedNameSpace)) { FileSystemManager.SetCurrentDirectory(NativeIO.FSRoot); } if (force) { FileSystemManager.ForceRemoveNameSpace(Name); } Object record = FileSystemManager.LockDirectory(rootedNameSpace); try { NativeIO.Format(Name, fileSystem, volumeLabel, parameter); Refresh(); } finally { FileSystemManager.UnlockDirectory(record); } if (restoreCD) { FileSystemManager.SetCurrentDirectory(rootedNameSpace); } } [MethodImplAttribute(MethodImplOptions.InternalCall)] public extern static VolumeInfo[] GetVolumes(); //[MethodImplAttribute(MethodImplOptions.InternalCall)] //public extern static String[] GetFileSystems(); //[MethodImplAttribute(MethodImplOptions.InternalCall)] //public extern void FlushAll(); } public static class RemovableMedia { public static event InsertEventHandler Insert; public static event EjectEventHandler Eject; private static ArrayList _volumes; private static Queue _events; //--// static RemovableMedia() { try { //Microsoft.SPOT.EventSink.AddEventProcessor(EventCategory.Storage, new StorageEventProcessor()); //Microsoft.SPOT.EventSink.AddEventListener(EventCategory.Storage, new StorageEventListener()); _volumes = new ArrayList(); _events = new Queue(); MountRemovableVolumes(); } catch { } } [MethodImplAttribute(MethodImplOptions.InternalCall)] private extern static void MountRemovableVolumes(); internal static void PostEvent( StorageEvent ev ) { /// We are using timer to process events instead of a separate message loop /// thread, to keep it light weight. try { // create a time and push it in a queue to make sure GC does not eat it up before it fires // the timer will pop itself in the callback and GC will take it from there // be trasaction-safe and create and queue the timer before setting it up to fire Timer messagePseudoThread = new Timer( MessageHandler, ev, Timeout.Infinite, Timeout.Infinite ); _events.Enqueue( messagePseudoThread ); // now that all operation that can fail have been done, enable the timer to fire messagePseudoThread.Change( 10, Timeout.Infinite ); } catch // eat up all exceptions, nothing we can do { } } private static void MessageHandler(object args) { try { StorageEvent ev = args as StorageEvent; if (ev == null) return; lock(_volumes) { if (ev.EventType == StorageEventType.Insert) { VolumeInfo volume = new VolumeInfo(ev.Handle); _volumes.Add(volume); if (Insert != null) { MediaEventArgs mediaEventArgs = new MediaEventArgs(volume, ev.Time); Insert(null, mediaEventArgs); } } else if (ev.EventType == StorageEventType.Eject) { VolumeInfo volumeInfo = RemoveVolume(ev.Handle); if(volumeInfo != null) { FileSystemManager.ForceRemoveNameSpace(volumeInfo.Name); if (Eject != null) { MediaEventArgs mediaEventArgs = new MediaEventArgs(new VolumeInfo(volumeInfo), ev.Time); Eject(null, mediaEventArgs); } } } } } finally { // get rid of this timer _events.Dequeue(); } } private static VolumeInfo RemoveVolume(uint handle) { VolumeInfo volumeInfo; int count = _volumes.Count; for (int i = 0; i < count; i++) { volumeInfo = ((VolumeInfo)_volumes[i]); if (volumeInfo.VolumePtr == handle) { _volumes.RemoveAt(i); return volumeInfo; } } return null; } } //--// public class MediaEventArgs { public readonly DateTime Time; public readonly VolumeInfo Volume; public MediaEventArgs(VolumeInfo volume, DateTime time) { Time = time; Volume = volume; } } public delegate void InsertEventHandler(object sender, MediaEventArgs e); public delegate void EjectEventHandler(object sender, MediaEventArgs e); } ================================================ FILE: Zelig/Zelig/RunTime/Framework/mscorlib/System/IO/MemoryStream.cs ================================================ // ==++== // // Copyright (c) Microsoft Corporation. All rights reserved. // // ==--== /*============================================================ ** ** Class: MemoryStream ** ** ** Purpose: A Stream whose backing store is memory. Great ** for temporary storage without creating a temp file. Also ** lets users expose a byte[] as a stream. ** ** ===========================================================*/ using System; using System.Runtime.InteropServices; namespace System.IO { // A MemoryStream represents a Stream in memory (ie, it has no backing store). // This stream may reduce the need for temporary buffers and files in // an application. // // There are two ways to create a MemoryStream. You can initialize one // from an unsigned byte array, or you can create an empty one. Empty // memory streams are resizable, while ones created with a byte array provide // a stream "view" of the data. [Serializable] public class MemoryStream : Stream { private byte[] _buffer; // Either allocated internally or externally. private int _origin; // For user-provided arrays, start at this origin private int _position; // read/write head. private int _length; // Number of bytes within the memory stream private int _capacity; // length of usable portion of buffer for stream // Note that _capacity == _buffer.Length for non-user-provided byte[]'s private bool _expandable; // User-provided buffers aren't expandable. private bool _writable; // Can user write to this stream? private bool _exposable; // Whether the array can be returned to the user. private bool _isOpen; // Is this stream open or closed? // In V2, if we get support for arrays of more than 2 GB worth of elements, // consider removing this constraing, or setting it to Int64.MaxValue. private const int MemStreamMaxLength = Int32.MaxValue; public MemoryStream() : this( 0 ) { } public MemoryStream( int capacity ) { if(capacity < 0) { #if EXCEPTION_STRINGS throw new ArgumentOutOfRangeException( "capacity", Environment.GetResourceString( "ArgumentOutOfRange_NegativeCapacity" ) ); #else throw new ArgumentOutOfRangeException(); #endif } _buffer = new byte[capacity]; _capacity = capacity; _expandable = true; _writable = true; _exposable = true; _origin = 0; // Must be 0 for byte[]'s created by MemoryStream _isOpen = true; } public MemoryStream( byte[] buffer ) : this( buffer, true ) { } public MemoryStream( byte[] buffer, bool writable ) { if(buffer == null) #if EXCEPTION_STRINGS throw new ArgumentNullException( "buffer", Environment.GetResourceString( "ArgumentNull_Buffer" ) ); #else throw new ArgumentNullException(); #endif _buffer = buffer; _length = _capacity = buffer.Length; _writable = writable; _exposable = false; _origin = 0; _isOpen = true; } public MemoryStream( byte[] buffer, int index, int count ) : this( buffer, index, count, true, false ) { } public MemoryStream( byte[] buffer, int index, int count, bool writable ) : this( buffer, index, count, writable, false ) { } public MemoryStream( byte[] buffer, int index, int count, bool writable, bool publiclyVisible ) { if(buffer == null) { #if EXCEPTION_STRINGS throw new ArgumentNullException( "buffer", Environment.GetResourceString( "ArgumentNull_Buffer" ) ); #else throw new ArgumentNullException(); #endif } if(index < 0) { #if EXCEPTION_STRINGS throw new ArgumentOutOfRangeException( "index", Environment.GetResourceString( "ArgumentOutOfRange_NeedNonNegNum" ) ); #else throw new ArgumentOutOfRangeException(); #endif } if(count < 0) { #if EXCEPTION_STRINGS throw new ArgumentOutOfRangeException( "count", Environment.GetResourceString( "ArgumentOutOfRange_NeedNonNegNum" ) ); #else throw new ArgumentOutOfRangeException(); #endif } if(buffer.Length - index < count) { #if EXCEPTION_STRINGS throw new ArgumentException( Environment.GetResourceString( "Argument_InvalidOffLen" ) ); #else throw new ArgumentException(); #endif } _buffer = buffer; _origin = _position = index; _length = _capacity = index + count; _writable = writable; _exposable = publiclyVisible; // Can GetBuffer return the array? _expandable = false; _isOpen = true; } public override bool CanRead { get { return _isOpen; } } public override bool CanSeek { get { return _isOpen; } } public override bool CanWrite { get { return _writable; } } protected override void Dispose( bool disposing ) { try { if(disposing) { _isOpen = false; _writable = false; _expandable = false; // Don't set buffer to null - allow GetBuffer & ToArray to work. } } finally { // Call base.Close() to cleanup async IO resources base.Dispose( disposing ); } } // returns a bool saying whether we allocated a new array. private bool EnsureCapacity( int value ) { // Check for overflow if(value < 0) { #if EXCEPTION_STRINGS throw new IOException( Environment.GetResourceString( "IO.IO_StreamTooLong" ) ); #else throw new IOException(); #endif } if(value > _capacity) { int newCapacity = value; if(newCapacity < 256) newCapacity = 256; if(newCapacity < _capacity * 2) newCapacity = _capacity * 2; Capacity = newCapacity; return true; } return false; } public override void Flush() { } public virtual byte[] GetBuffer() { if(!_exposable) { #if EXCEPTION_STRINGS throw new UnauthorizedAccessException( Environment.GetResourceString( "UnauthorizedAccess_MemStreamBuffer" ) ); #else throw new UnauthorizedAccessException(); #endif } return _buffer; } // -------------- PERF: Internal functions for fast direct access of MemoryStream buffer (cf. BinaryReader for usage) --------------- // PERF: Internal sibling of GetBuffer, always returns a buffer (cf. GetBuffer()) internal byte[] InternalGetBuffer() { return _buffer; } // PERF: Get origin and length - used in ResourceWriter. internal void InternalGetOriginAndLength( out int origin, out int length ) { if(!_isOpen) { __Error.StreamIsClosed(); } origin = _origin; length = _length; } // PERF: True cursor position, we don't need _origin for direct access internal int InternalGetPosition() { if(!_isOpen) { __Error.StreamIsClosed(); } return _position; } // PERF: Takes out Int32 as fast as possible internal int InternalReadInt32() { if(!_isOpen) { __Error.StreamIsClosed(); } int pos = (_position += 4); // use temp to avoid race if(pos > _length) { _position = _length; __Error.EndOfFile(); } return (int)(_buffer[pos - 4] | _buffer[pos - 3] << 8 | _buffer[pos - 2] << 16 | _buffer[pos - 1] << 24); } // PERF: Get actual length of bytes available for read; do sanity checks; shift position - i.e. everything except actual copying bytes internal int InternalEmulateRead( int count ) { if(!_isOpen) { __Error.StreamIsClosed(); } int n = _length - _position; if(n > count) n = count; if(n < 0) n = 0; BCLDebug.Assert( _position + n >= 0, "_position + n >= 0" ); // len is less than 2^31 -1. _position += n; return n; } // Gets &; sets the capacity (number of bytes allocated) for this stream. // The capacity cannot be set to a value less than the current length // of the stream. // public virtual int Capacity { get { if(!_isOpen) { __Error.StreamIsClosed(); } return _capacity - _origin; } set { if(!_isOpen) { __Error.StreamIsClosed(); } if(value != _capacity) { if(!_expandable) { __Error.MemoryStreamNotExpandable(); } if(value < _length) { #if EXCEPTION_STRINGS throw new ArgumentOutOfRangeException( "value", Environment.GetResourceString( "ArgumentOutOfRange_SmallCapacity" ) ); #else throw new ArgumentOutOfRangeException(); #endif } if(value > 0) { byte[] newBuffer = new byte[value]; if(_length > 0) Buffer.InternalBlockCopy( _buffer, 0, newBuffer, 0, _length ); _buffer = newBuffer; } else { _buffer = null; } _capacity = value; } } } public override long Length { get { if(!_isOpen) { __Error.StreamIsClosed(); } return _length - _origin; } } public override long Position { get { if(!_isOpen) { __Error.StreamIsClosed(); } return _position - _origin; } set { if(!_isOpen) { __Error.StreamIsClosed(); } if(value < 0) { #if EXCEPTION_STRINGS throw new ArgumentOutOfRangeException( "value", Environment.GetResourceString( "ArgumentOutOfRange_NeedNonNegNum" ) ); #else throw new ArgumentOutOfRangeException(); #endif } if(value > MemStreamMaxLength) { #if EXCEPTION_STRINGS throw new ArgumentOutOfRangeException( "value", Environment.GetResourceString( "ArgumentOutOfRange_MemStreamLength" ) ); #else throw new ArgumentOutOfRangeException(); #endif } _position = _origin + (int)value; } } public override int Read( [In, Out] byte[] buffer, int offset, int count ) { if(!_isOpen) { __Error.StreamIsClosed(); } if(buffer == null) { #if EXCEPTION_STRINGS throw new ArgumentNullException( "buffer", Environment.GetResourceString( "ArgumentNull_Buffer" ) ); #else throw new ArgumentNullException(); #endif } if(offset < 0) { #if EXCEPTION_STRINGS throw new ArgumentOutOfRangeException( "offset", Environment.GetResourceString( "ArgumentOutOfRange_NeedNonNegNum" ) ); #else throw new ArgumentOutOfRangeException(); #endif } if(count < 0) { #if EXCEPTION_STRINGS throw new ArgumentOutOfRangeException( "count", Environment.GetResourceString( "ArgumentOutOfRange_NeedNonNegNum" ) ); #else throw new ArgumentOutOfRangeException(); #endif } if(buffer.Length - offset < count) { #if EXCEPTION_STRINGS throw new ArgumentException( Environment.GetResourceString( "Argument_InvalidOffLen" ) ); #else throw new ArgumentException(); #endif } int n = _length - _position; if(n > count) n = count; if(n <= 0) { return 0; } BCLDebug.Assert( _position + n >= 0, "_position + n >= 0" ); // len is less than 2^31 -1. if(n <= 8) { int byteCount = n; while(--byteCount >= 0) { buffer[offset + byteCount] = _buffer[_position + byteCount]; } } else { Buffer.InternalBlockCopy( _buffer, _position, buffer, offset, n ); } _position += n; return n; } public override int ReadByte() { if(!_isOpen) { __Error.StreamIsClosed(); } if(_position >= _length) return -1; return _buffer[_position++]; } public override long Seek( long offset, SeekOrigin loc ) { if(!_isOpen) { __Error.StreamIsClosed(); } if(offset > MemStreamMaxLength) { #if EXCEPTION_STRINGS throw new ArgumentOutOfRangeException( "offset", Environment.GetResourceString( "ArgumentOutOfRange_MemStreamLength" ) ); #else throw new ArgumentOutOfRangeException(); #endif } switch(loc) { case SeekOrigin.Begin: if(offset < 0) { #if EXCEPTION_STRINGS throw new IOException( Environment.GetResourceString( "IO.IO_SeekBeforeBegin" ) ); #else throw new IOException(); #endif } _position = _origin + (int)offset; break; case SeekOrigin.Current: if(offset + _position < _origin) { #if EXCEPTION_STRINGS throw new IOException( Environment.GetResourceString( "IO.IO_SeekBeforeBegin" ) ); #else throw new IOException(); #endif } _position += (int)offset; break; case SeekOrigin.End: if(_length + offset < _origin) { #if EXCEPTION_STRINGS throw new IOException( Environment.GetResourceString( "IO.IO_SeekBeforeBegin" ) ); #else throw new IOException(); #endif } _position = _length + (int)offset; break; default: #if EXCEPTION_STRINGS throw new ArgumentException( Environment.GetResourceString( "Argument_InvalidSeekOrigin" ) ); #else throw new ArgumentException(); #endif } BCLDebug.Assert( _position >= 0, "_position >= 0" ); return _position; } // Sets the length of the stream to a given value. The new // value must be nonnegative and less than the space remaining in // the array, Int32.MaxValue - origin // Origin is 0 in all cases other than a MemoryStream created on // top of an existing array and a specific starting offset was passed // into the MemoryStream constructor. The upper bounds prevents any // situations where a stream may be created on top of an array then // the stream is made longer than the maximum possible length of the // array (Int32.MaxValue). // public override void SetLength( long value ) { if(!_writable) { __Error.WriteNotSupported(); } if(value > MemStreamMaxLength) { #if EXCEPTION_STRINGS throw new ArgumentOutOfRangeException( "value", Environment.GetResourceString( "ArgumentOutOfRange_MemStreamLength" ) ); #else throw new ArgumentOutOfRangeException(); #endif } if(value < 0 || value > (Int32.MaxValue - _origin)) { #if EXCEPTION_STRINGS throw new ArgumentOutOfRangeException( "value", Environment.GetResourceString( "ArgumentOutOfRange_MemStreamLength" ) ); #else throw new ArgumentOutOfRangeException(); #endif } int newLength = _origin + (int)value; bool allocatedNewArray = EnsureCapacity( newLength ); if(!allocatedNewArray && newLength > _length) { Array.Clear( _buffer, _length, newLength - _length ); } _length = newLength; if(_position > newLength) _position = newLength; } public virtual byte[] ToArray() { BCLDebug.Perf( _exposable, "MemoryStream::GetBuffer will let you avoid a copy." ); byte[] copy = new byte[_length - _origin]; Buffer.InternalBlockCopy( _buffer, _origin, copy, 0, _length - _origin ); return copy; } public override void Write( byte[] buffer, int offset, int count ) { if(!_isOpen) { __Error.StreamIsClosed(); } if(!_writable) { __Error.WriteNotSupported(); } if(buffer == null) { #if EXCEPTION_STRINGS throw new ArgumentNullException( "buffer", Environment.GetResourceString( "ArgumentNull_Buffer" ) ); #else throw new ArgumentNullException(); #endif } if(offset < 0) { #if EXCEPTION_STRINGS throw new ArgumentOutOfRangeException( "offset", Environment.GetResourceString( "ArgumentOutOfRange_NeedNonNegNum" ) ); #else throw new ArgumentOutOfRangeException(); #endif } if(count < 0) { #if EXCEPTION_STRINGS throw new ArgumentOutOfRangeException( "count", Environment.GetResourceString( "ArgumentOutOfRange_NeedNonNegNum" ) ); #else throw new ArgumentOutOfRangeException(); #endif } if(buffer.Length - offset < count) { #if EXCEPTION_STRINGS throw new ArgumentException( Environment.GetResourceString( "Argument_InvalidOffLen" ) ); #else throw new ArgumentException(); #endif } int i = _position + count; // Check for overflow if(i < 0) { #if EXCEPTION_STRINGS throw new IOException( Environment.GetResourceString( "IO.IO_StreamTooLong" ) ); #else throw new IOException(); #endif } if(i > _length) { bool mustZero = _position > _length; if(i > _capacity) { bool allocatedNewArray = EnsureCapacity( i ); if(allocatedNewArray) { mustZero = false; } } if(mustZero) { Array.Clear( _buffer, _length, i - _length ); } _length = i; } if((count <= 8) && (buffer != _buffer)) { int byteCount = count; while(--byteCount >= 0) { _buffer[_position + byteCount] = buffer[offset + byteCount]; } } else { Buffer.InternalBlockCopy( buffer, offset, _buffer, _position, count ); } _position = i; return; } public override void WriteByte( byte value ) { if(!_isOpen) { __Error.StreamIsClosed(); } if(!_writable) { __Error.WriteNotSupported(); } if(_position >= _length) { int newLength = _position + 1; bool mustZero = _position > _length; if(newLength >= _capacity) { bool allocatedNewArray = EnsureCapacity( newLength ); if(allocatedNewArray) { mustZero = false; } } if(mustZero) { Array.Clear( _buffer, _length, _position - _length ); } _length = newLength; } _buffer[_position++] = value; } // Writes this MemoryStream to another stream. public virtual void WriteTo( Stream stream ) { if(!_isOpen) { __Error.StreamIsClosed(); } if(stream == null) { #if EXCEPTION_STRINGS throw new ArgumentNullException( "stream", Environment.GetResourceString( "ArgumentNull_Stream" ) ); #else throw new ArgumentNullException(); #endif } stream.Write( _buffer, _origin, _length - _origin ); } } } ================================================ FILE: Zelig/Zelig/RunTime/Framework/mscorlib/System/IO/Path.cs ================================================ //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // Copyright (c) Microsoft Corporation. All rights reserved. //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// using System; using System.Collections; using System.Text; namespace System.IO { /* * Provides methods for processing directory strings in an ideally * cross-platform manner. Most of the methods don't do a complete * full parsing (such as examining a UNC hostname), but they will * handle most string operations. * *

File names cannot contain backslash (\), slash (/), colon (:), * asterick (*), question mark (?), quote ("), less than (<), * greater than (>), or pipe (|). The first three are used as directory * separators on various platforms. Asterick and question mark are treated * as wild cards. Less than, Greater than, and pipe all redirect input * or output from a program to a file or some combination thereof. Quotes * are special. * *

We are guaranteeing that Path.SeparatorChar is the correct * directory separator on all platforms, and we will support * Path.AltSeparatorChar as well. To write cross platform * code with minimal pain, you can use slash (/) as a directory separator in * your strings. */ // Class contains only static data, no need to serialize public sealed class Path { private Path() { } /* * Platform specific directory separator character. This is backslash * ('\') on Windows, slash ('/') on Unix, and colon (':') on Mac. * * Make this platform specific when we port. */ public static readonly char DirectorySeparatorChar = '\\'; /* * Platform specific invalid list of characters in a path. * * Make this platform specific when we port. */ public static readonly char[] InvalidPathChars = { '/', '\"', '<', '>', '|', ':', '\0', (Char)1, (Char)2, (Char)3, (Char)4, (Char)5, (Char)6, (Char)7, (Char)8, (Char)9, (Char)10, (Char)11, (Char)12, (Char)13, (Char)14, (Char)15, (Char)16, (Char)17, (Char)18, (Char)19, (Char)20, (Char)21, (Char)22, (Char)23, (Char)24, (Char)25, (Char)26, (Char)27, (Char)28, (Char)29, (Char)30, (Char)31 }; /* * Changes the extension of a file path. The path parameter * specifies a file path, and the extension parameter * specifies a file extension (with a leading period, such as * ".exe" or ".cool").

* * The function returns a file path with the same root, directory, and base * name parts as path, but with the file extension changed to * the specified extension. If path is null, the function * returns null. If path does not contain a file extension, * the new file extension is appended to the path. If extension * is null, any exsiting extension is removed from path. * * @param path The path for which to change file extension. * @param extension The new file extension (with a leading period), or * null to remove the extension. * @return Path with the new file extension. * @exception ArgumentException if path contains invalid characters. * @see #getExtension * @see #hasExtension */ public static String ChangeExtension(String path, String extension) { if (path != null) { CheckInvalidPathChars(path); String s = path; for (int i = path.Length; --i >= 0; ) { char ch = path[i]; if (ch == '.') { s = path.Substring(0, i); break; } if (ch == DirectorySeparatorChar) break; } if (extension != null && path.Length != 0) { if (extension.Length == 0 || extension[0] != '.') { s = s + "."; } s = s + extension; } return s; } return null; } /* * Returns the directory path of a file path. This method effectively * removes the last element of the given file path, i.e. it returns a * string consisting of all characters up to but not including the last * backslash ("\") in the file path. The returned value is null if the file * path is null or if the file path denotes a root (such as "\", "C:", or * "\\server\share"). * * @param path The path of a file or directory. * @return The directory path of the given path, or null if the given path * denotes a root. * @exception ArgumentException if path contains invalid characters. * @see #GetExtension * @see #GetFileNameFromPath * @see #GetRoot * @see #IsRooted */ public static String GetDirectoryName(String path) { if (path != null) { NormalizePath(path, false); int root = GetRootLength(path); int i = path.Length; if (i > root) { i = path.Length; if (i == root) return null; while (i > root && path[--i] != DirectorySeparatorChar) ; return path.Substring(0, i); } } return null; } /* * Gets the length of the root DirectoryInfo or whatever DirectoryInfo markers * are specified for the first part of the DirectoryInfo name. * * @internalonly */ internal static int GetRootLength(String path) { CheckInvalidPathChars(path); int i = 0; int length = path.Length; if (length >= 1 && (IsDirectorySeparator(path[0]))) { // handles UNC names and directories off current drive's root. i = 1; if (length >= 2 && (IsDirectorySeparator(path[1]))) { i = 2; int n = 2; while (i < length && ((path[i] != DirectorySeparatorChar || --n > 0))) i++; } } return i; } internal static bool IsDirectorySeparator(char c) { return c == DirectorySeparatorChar; } public static char[] GetInvalidPathChars() { int len = InvalidPathChars.Length; char[] retVal = new char[len]; Array.Copy( InvalidPathChars, retVal, len ); return retVal; } public static String GetFullPath(String path) { ValidateNullOrEmpty(path); if (!Path.IsPathRooted(path)) { string currDir = Directory.GetCurrentDirectory(); path = Path.Combine(currDir, path); } return NormalizePath(path, false); } /* * Returns the extension of the given path. The returned value includes the * period (".") character of the extension except when you have a terminal period when you get String.Empty, such as ".exe" or * ".cpp". The returned value is null if the given path is * null or if the given path does not include an extension. * * @param path The path of a file or directory. * @return The extension of the given path, or null if the given path does * not include an extension. * @exception ArgumentException if path contains invalid * characters. * @see #GetDirectoryNameFromPath * @see #GetFileNameFromPath * @see #GetRoot * @see #HasExtension */ public static String GetExtension(String path) { if (path == null) return null; CheckInvalidPathChars(path); int length = path.Length; for (int i = length; --i >= 0; ) { char ch = path[i]; if (ch == '.') { if (i != length - 1) return path.Substring(i, length - i); else return String.Empty; } if (ch == DirectorySeparatorChar) break; } return String.Empty; } /* * Returns the name and extension parts of the given path. The resulting * string contains the characters of path that follow the last * backslash ("\"), slash ("/"), or colon (":") character in * path. The resulting string is the entire path if path * contains no backslash after removing trailing slashes, slash, or colon characters. The resulting * string is null if path is null. * * @param path The path of a file or directory. * @return The name and extension parts of the given path. * @exception ArgumentException if path contains invalid characters. * @see #GetDirectoryNameFromPath * @see #GetExtension * @see #GetRoot */ public static String GetFileName(String path) { if (path != null) { CheckInvalidPathChars(path); int length = path.Length; for (int i = length; --i >= 0; ) { char ch = path[i]; if (ch == DirectorySeparatorChar) return path.Substring(i + 1, length - i - 1); } } return path; } public static String GetFileNameWithoutExtension(String path) { path = GetFileName(path); if (path != null) { int i; if ((i = path.LastIndexOf('.')) == -1) return path; // No path extension found else return path.Substring(0, i); } return null; } /* * Returns the root portion of the given path. The resulting string * consists of those rightmost characters of the path that constitute the * root of the path. Possible patterns for the resulting string are: An * empty string (a relative path on the current drive), "\" (an absolute * path on the current drive), "X:" (a relative path on a given drive, * where X is the drive letter), "X:\" (an absolute path on a given drive), * and "\\server\share" (a UNC path for a given server and share name). * The resulting string is null if path is null. * * @param path The path of a file or directory. * @return The root portion of the given path. * @exception ArgumentException if path contains invalid characters. * @see #GetDirectory * @see #GetExtension * @see #GetName * @see #IsRooted */ public static String GetPathRoot(String path) { if (path == null) return null; return path.Substring(0, GetRootLength(path)); } /* * Tests if a path includes a file extension. The result is * true if the characters that follow the last directory * separator ('\\' or '/') or volume separator (':') in the path include * a period (".") other than a terminal period. The result is false otherwise. * * @param path The path to test. * @return Boolean indicating whether the path includes a file extension. * @exception ArgumentException if path contains invalid characters. * @see #ChangeExtension * @see #GetExtension */ public static bool HasExtension(String path) { if (path != null) { CheckInvalidPathChars(path); for (int i = path.Length; --i >= 0; ) { char ch = path[i]; if (ch == '.') { if (i != path.Length - 1) return true; else return false; } if (ch == DirectorySeparatorChar) break; } } return false; } /* * Tests if the given path contains a root. A path is considered rooted * if it starts with a backslash ("\") or a drive letter and a colon (":"). * * @param path The path to test. * @return Boolean indicating whether the path is rooted. * @exception ArgumentException if path contains invalid characters. * @see #GetRoot */ public static bool IsPathRooted(String path) { if (path != null) { CheckInvalidPathChars(path); int length = path.Length; if (length >= 1 && (path[0] == DirectorySeparatorChar)) return true; } return false; } public static String Combine(String path1, String path2) { if (path1 == null || path2 == null) #if EXCEPTION_STRINGS throw new ArgumentNullException(/*(path1==null) ? "path1" : "path2"*/); #else throw new ArgumentNullException(); #endif CheckInvalidPathChars(path1); CheckInvalidPathChars(path2); if (path2.Length == 0) return path1; if (path1.Length == 0) return path2; if (IsPathRooted(path2)) return path2; char ch = path1[path1.Length - 1]; if (ch != DirectorySeparatorChar) return path1 + DirectorySeparatorChar + path2; return path1 + path2; } //--// internal static void CheckInvalidPathChars(String path) { if (-1 != path.IndexOfAny(InvalidPathChars)) #if EXCEPTION_STRINGS throw new ArgumentException(/*Environment.GetResourceString("Argument_InvalidPathChars")*/); #else throw new ArgumentException(); #endif } // Windows API definitions internal const int MAX_PATH = 260; // From WinDef.h internal static char[] m_illegalCharacters = { '?', '*' }; internal static void ValidateNullOrEmpty(string str) { if (str == null) throw new ArgumentNullException(); if (str.Length == 0) throw new ArgumentException(); } internal static string NormalizePath(string path, bool pattern) { ValidateNullOrEmpty(path); int pathLength = path.Length; int i = 0; for (i = 0; i < pathLength; i++) { if (path[i] != '\\') break; } bool rootedPath = false; bool serverPath = false; /// Handle some of the special cases. /// 1. Root (\) /// 2. Server (\\server). /// 3. InvalidPath (\\\, \\\\, etc). if (i == 1) { rootedPath = true; } else if ((i == 2) && (pathLength > 2)) { serverPath = true; } else if (i > 2) { throw new ArgumentException(); } if (rootedPath) { int limit = i + NativeIO.FSNameMaxLength; for (; i < limit && i < pathLength; i++) { if (path[i] == '\\') { break; } } if (i == limit) // if the namespace is too long { #if EXCEPTION_STRINGS throw new IOException("", (int)IOExceptionErrorCode.VolumeNotFound); #else throw new IOException(); #endif } else if (pathLength - i >= NativeIO.FSMaxPathLength) // if the "relative" path exceeds the limit { #if EXCEPTION_STRINGS throw new IOException("", (int)IOExceptionErrorCode.PathTooLong); #else throw new IOException(); #endif } } else // For non-rooted paths (i.e. server paths or relative paths), we follow the MAX_PATH (260) limit from desktop { if (pathLength >= MAX_PATH) { #if EXCEPTION_STRINGS throw new IOException("", (int)IOExceptionErrorCode.PathTooLong); #else throw new IOException(); #endif } } string[] pathParts = path.Split(DirectorySeparatorChar); if (pattern && (pathParts.Length > 1)) throw new ArgumentException(); ArrayList finalPathSegments = new ArrayList(); int pathPartLen; for (int e = 0; e < pathParts.Length; e++) { pathPartLen = pathParts[e].Length; if (pathPartLen == 0) { /// Do nothing. Apparently paths like c:\\folder\\\file.txt works fine in Windows. continue; } else if (pathPartLen >= NativeIO.FSMaxFilenameLength) { #if EXCEPTION_STRINGS throw new IOException("", (int)IOExceptionErrorCode.PathTooLong); #else throw new IOException(); #endif } if (pathParts[e].IndexOfAny(InvalidPathChars) != -1) throw new ArgumentException(); if (!pattern) { if (pathParts[e].IndexOfAny(m_illegalCharacters) != -1) throw new ArgumentException(); } /// verify whether pathParts[e] is all '.'s. If it is /// we have some special cases. Also path with both dots /// and spaces only are invalid. int length = pathParts[e].Length; bool spaceFound = false; for (i = 0; i < length; i++) { if (pathParts[e][i] == '.') continue; if (pathParts[e][i] == ' ') { spaceFound = true; continue; } break; } if (i >= length) { if (!spaceFound) { /// Dots only. if (i == 1) { /// Stay in same directory. } else if (i == 2) { if (finalPathSegments.Count == 0) throw new ArgumentException(); finalPathSegments.RemoveAt(finalPathSegments.Count - 1); } else { throw new ArgumentException(); } } else { /// Just dots and spaces doesn't make the cut. throw new ArgumentException(); } } else { int trim = length - 1; while (pathParts[e][trim] == ' ' || pathParts[e][trim] == '.') { trim--; } finalPathSegments.Add(pathParts[e].Substring(0, trim + 1)); } } string normalizedPath = ""; if (rootedPath) { normalizedPath += @"\"; } else if (serverPath) { normalizedPath += @"\\"; /// btw, server path must specify server name. if (finalPathSegments.Count == 0) throw new ArgumentException(); } bool firstSegment = true; for (int e = 0; e < finalPathSegments.Count; e++) { if (!firstSegment) { normalizedPath += "\\"; } else { firstSegment = false; } normalizedPath += (string)finalPathSegments[e]; } return normalizedPath; } } } ================================================ FILE: Zelig/Zelig/RunTime/Framework/mscorlib/System/IO/SeekOrigin.cs ================================================ // ==++== // // Copyright (c) Microsoft Corporation. All rights reserved. // // ==--== /*============================================================ ** ** Enum: SeekOrigin ** ** ** Purpose: Enum describing locations in a stream you could ** seek relative to. ** ** ===========================================================*/ using System; namespace System.IO { // Provides seek reference points. To seek to the end of a stream, // call stream.Seek(0, SeekOrigin.End). [Serializable()] public enum SeekOrigin { // These constants match Win32's FILE_BEGIN, FILE_CURRENT, and FILE_END Begin = 0, Current = 1, End = 2, } } ================================================ FILE: Zelig/Zelig/RunTime/Framework/mscorlib/System/IO/Stream.cs ================================================ // ==++== // // Copyright (c) Microsoft Corporation. All rights reserved. // // ==--== /*============================================================ ** ** Class: Stream ** ** ** Purpose: Abstract base class for all Streams. Provides ** default implementations of asynchronous reads & writes, in ** terms of the synchronous reads & writes (and vice versa). ** ** ===========================================================*/ using System; using System.Threading; using System.Runtime.InteropServices; //using System.Runtime.Remoting.Messaging; using System.Security; using System.Security.Permissions; namespace System.IO { [Serializable()] public abstract class Stream : MarshalByRefObject, IDisposable { public static readonly Stream Null = new NullStream(); public abstract bool CanRead { get; } // If CanSeek is false, Position, Seek, Length, and SetLength should throw. public abstract bool CanSeek { get; } public virtual bool CanTimeout { get { return false; } } public abstract bool CanWrite { get; } public abstract long Length { get; } public abstract long Position { get; set; } public virtual int ReadTimeout { get { #if EXCEPTION_STRINGS throw new InvalidOperationException( Environment.GetResourceString( "InvalidOperation_TimeoutsNotSupported" ) ); #else throw new InvalidOperationException(); #endif } set { #if EXCEPTION_STRINGS throw new InvalidOperationException( Environment.GetResourceString( "InvalidOperation_TimeoutsNotSupported" ) ); #else throw new InvalidOperationException(); #endif } } public virtual int WriteTimeout { get { #if EXCEPTION_STRINGS throw new InvalidOperationException( Environment.GetResourceString( "InvalidOperation_TimeoutsNotSupported" ) ); #else throw new InvalidOperationException(); #endif } set { #if EXCEPTION_STRINGS throw new InvalidOperationException( Environment.GetResourceString( "InvalidOperation_TimeoutsNotSupported" ) ); #else throw new InvalidOperationException(); #endif } } // Stream used to require that all cleanup logic went into Close(), // which was thought up before we invented IDisposable. However, we // need to follow the IDisposable pattern so that users can write // sensible subclasses without needing to inspect all their base // classes, and without worrying about version brittleness, from a // base class switching to the Dispose pattern. We're moving // Stream to the Dispose(bool) pattern - that's where all subclasses // should put their cleanup starting in V2. public virtual void Close() { Dispose( true ); GC.SuppressFinalize( this ); } public void Dispose() { Close(); } protected virtual void Dispose( bool disposing ) { //// // Note: Never change this to call other virtual methods on Stream //// // like Write, since the state on subclasses has already been //// // torn down. This is the last code to run on cleanup for a stream. //// if((disposing) && (_asyncActiveEvent != null)) //// _CloseAsyncActiveEvent( Interlocked.Decrement( ref _asyncActiveCount ) ); } //// private void _CloseAsyncActiveEvent( int asyncActiveCount ) //// { //// BCLDebug.Assert( _asyncActiveCount >= 0, "ref counting mismatch, possible race in the code" ); //// //// // If no pending async IO, close the event //// if((_asyncActiveEvent != null) && (asyncActiveCount == 0)) //// { //// _asyncActiveEvent.Close(); //// _asyncActiveEvent = null; //// } //// } public abstract void Flush(); [Obsolete( "CreateWaitHandle will be removed eventually. Please use \"new ManualResetEvent(false)\" instead." )] protected virtual WaitHandle CreateWaitHandle() { return new ManualResetEvent( false ); } [HostProtection( ExternalThreading = true )] public virtual IAsyncResult BeginRead( byte[] buffer, int offset, int count, AsyncCallback callback, Object state ) { if(!CanRead) __Error.ReadNotSupported(); // To avoid a race with a stream's position pointer & generating race // conditions with internal buffer indexes in our own streams that // don't natively support async IO operations when there are multiple // async requests outstanding, we will block the application's main // thread and do the IO synchronously. // This can't perform well - use a different approach. SynchronousAsyncResult asyncResult = new SynchronousAsyncResult( state, false ); try { int numRead = Read( buffer, offset, count ); asyncResult._numRead = numRead; if(callback != null) callback( asyncResult ); } catch(IOException e) { asyncResult._exception = e; } finally { asyncResult._isCompleted = true; asyncResult._waitHandle.Set(); } return asyncResult; } public virtual int EndRead( IAsyncResult asyncResult ) { if(asyncResult == null) #if EXCEPTION_STRINGS throw new ArgumentNullException( "asyncResult" ); #else throw new ArgumentNullException(); #endif SynchronousAsyncResult ar = asyncResult as SynchronousAsyncResult; if(ar == null || ar.IsWrite) __Error.WrongAsyncResult(); if(ar._EndXxxCalled) __Error.EndReadCalledTwice(); ar._EndXxxCalled = true; if(ar._exception != null) throw ar._exception; return ar._numRead; } [HostProtection( ExternalThreading = true )] public virtual IAsyncResult BeginWrite( byte[] buffer, int offset, int count, AsyncCallback callback, Object state ) { if(!CanWrite) __Error.WriteNotSupported(); // To avoid a race with a stream's position pointer & generating race // conditions with internal buffer indexes in our own streams that // don't natively support async IO operations when there are multiple // async requests outstanding, we will block the application's main // thread and do the IO synchronously. // This can't perform well - use a different approach. SynchronousAsyncResult asyncResult = new SynchronousAsyncResult( state, true ); try { Write( buffer, offset, count ); if(callback != null) callback( asyncResult ); } catch(IOException e) { asyncResult._exception = e; } finally { asyncResult._isCompleted = true; asyncResult._waitHandle.Set(); } return asyncResult; } public virtual void EndWrite( IAsyncResult asyncResult ) { if(asyncResult == null) #if EXCEPTION_STRINGS throw new ArgumentNullException( "asyncResult" ); #else throw new ArgumentNullException(); #endif SynchronousAsyncResult ar = asyncResult as SynchronousAsyncResult; if(ar == null || !ar.IsWrite) __Error.WrongAsyncResult(); if(ar._EndXxxCalled) __Error.EndWriteCalledTwice(); ar._EndXxxCalled = true; if(ar._exception != null) throw ar._exception; } public abstract long Seek( long offset, SeekOrigin origin ); public abstract void SetLength( long value ); public abstract int Read( [In, Out] byte[] buffer, int offset, int count ); // Reads one byte from the stream by calling Read(byte[], int, int). // Will return an unsigned byte cast to an int or -1 on end of stream. // This implementation does not perform well because it allocates a new // byte[] each time you call it, and should be overridden by any // subclass that maintains an internal buffer. Then, it can help perf // significantly for people who are reading one byte at a time. public virtual int ReadByte() { byte[] oneByteArray = new byte[1]; int r = Read( oneByteArray, 0, 1 ); if(r == 0) return -1; return oneByteArray[0]; } public abstract void Write( byte[] buffer, int offset, int count ); // Writes one byte from the stream by calling Write(byte[], int, int). // This implementation does not perform well because it allocates a new // byte[] each time you call it, and should be overridden by any // subclass that maintains an internal buffer. Then, it can help perf // significantly for people who are writing one byte at a time. public virtual void WriteByte( byte value ) { byte[] oneByteArray = new byte[1]; oneByteArray[0] = value; Write( oneByteArray, 0, 1 ); } [HostProtection( Synchronization = true )] public static Stream Synchronized( Stream stream ) { if(stream == null) #if EXCEPTION_STRINGS throw new ArgumentNullException( "stream" ); #else throw new ArgumentNullException(); #endif if(stream is SyncStream) return stream; return new SyncStream( stream ); } [Serializable] private sealed class NullStream : Stream { internal NullStream() { } public override bool CanRead { get { return true; } } public override bool CanWrite { get { return true; } } public override bool CanSeek { get { return true; } } public override long Length { get { return 0; } } public override long Position { get { return 0; } set { } } // No need to override Close public override void Flush() { } public override int Read( [In, Out] byte[] buffer, int offset, int count ) { return 0; } public override int ReadByte() { return -1; } public override void Write( byte[] buffer, int offset, int count ) { } public override void WriteByte( byte value ) { } public override long Seek( long offset, SeekOrigin origin ) { return 0; } public override void SetLength( long length ) { } } // Used as the IAsyncResult object when using asynchronous IO methods // on the base Stream class. Note I'm not using async delegates, so // this is necessary. private sealed class SynchronousAsyncResult : IAsyncResult { internal ManualResetEvent _waitHandle; internal Object _stateObject; internal int _numRead; internal bool _isCompleted; internal bool _isWrite; internal bool _EndXxxCalled; internal Exception _exception; internal SynchronousAsyncResult( Object asyncStateObject, bool isWrite ) { _stateObject = asyncStateObject; _isWrite = isWrite; _waitHandle = new ManualResetEvent( false ); } public bool IsCompleted { get { return _isCompleted; } } public WaitHandle AsyncWaitHandle { get { return _waitHandle; } } public Object AsyncState { get { return _stateObject; } } public bool CompletedSynchronously { get { return true; } } internal bool IsWrite { get { return _isWrite; } } } // SyncStream is a wrapper around a stream that takes // a lock for every operation making it thread safe. [Serializable()] internal sealed class SyncStream : Stream, IDisposable { private Stream _stream; internal SyncStream( Stream stream ) { if(stream == null) #if EXCEPTION_STRINGS throw new ArgumentNullException( "stream" ); #else throw new ArgumentNullException(); #endif _stream = stream; } public override bool CanRead { get { return _stream.CanRead; } } public override bool CanWrite { get { return _stream.CanWrite; } } public override bool CanSeek { get { return _stream.CanSeek; } } public override bool CanTimeout { get { return _stream.CanTimeout; } } public override long Length { get { lock(_stream) { return _stream.Length; } } } public override long Position { get { lock(_stream) { return _stream.Position; } } set { lock(_stream) { _stream.Position = value; } } } public override int ReadTimeout { get { return _stream.ReadTimeout; } set { _stream.ReadTimeout = value; } } public override int WriteTimeout { get { return _stream.WriteTimeout; } set { _stream.WriteTimeout = value; } } // In the off chance that some wrapped stream has different // semantics for Close vs. Dispose, let's preserve that. public override void Close() { lock(_stream) { try { _stream.Close(); } finally { base.Dispose( true ); } } } protected override void Dispose( bool disposing ) { lock(_stream) { try { // Explicitly pick up a potentially methodimpl'ed Dispose if(disposing) { ((IDisposable)_stream).Dispose(); } } finally { base.Dispose( disposing ); } } } public override void Flush() { lock(_stream) { _stream.Flush(); } } public override int Read( [In, Out]byte[] bytes, int offset, int count ) { lock(_stream) { return _stream.Read( bytes, offset, count ); } } public override int ReadByte() { lock(_stream) { return _stream.ReadByte(); } } [HostProtection( ExternalThreading = true )] public override IAsyncResult BeginRead( byte[] buffer, int offset, int count, AsyncCallback callback, Object state ) { lock(_stream) { return _stream.BeginRead( buffer, offset, count, callback, state ); } } public override int EndRead( IAsyncResult asyncResult ) { lock(_stream) { return _stream.EndRead( asyncResult ); } } public override long Seek( long offset, SeekOrigin origin ) { lock(_stream) { return _stream.Seek( offset, origin ); } } public override void SetLength( long length ) { lock(_stream) { _stream.SetLength( length ); } } public override void Write( byte[] bytes, int offset, int count ) { lock(_stream) { _stream.Write( bytes, offset, count ); } } public override void WriteByte( byte b ) { lock(_stream) { _stream.WriteByte( b ); } } [HostProtection( ExternalThreading = true )] public override IAsyncResult BeginWrite( byte[] buffer, int offset, int count, AsyncCallback callback, Object state ) { lock(_stream) { return _stream.BeginWrite( buffer, offset, count, callback, state ); } } public override void EndWrite( IAsyncResult asyncResult ) { lock(_stream) { _stream.EndWrite( asyncResult ); } } } } } ================================================ FILE: Zelig/Zelig/RunTime/Framework/mscorlib/System/IO/StreamReader.cs ================================================ // ==++== // // Copyright (c) Microsoft Corporation. All rights reserved. // // ==--== /*============================================================ ** ** Class: StreamReader ** ** ** Purpose: For reading text from streams in a particular ** encoding. ** ** ===========================================================*/ using System; using System.Text; using System.Runtime.InteropServices; using System.Runtime.CompilerServices; //using System.Runtime.Versioning; namespace System.IO { // This class implements a TextReader for reading characters to a Stream. // This is designed for character input in a particular Encoding, // whereas the Stream class is designed for byte input and output. // [Serializable()] public class StreamReader : TextReader { //// // StreamReader.Null is threadsafe. //// public new static readonly StreamReader Null = new NullStreamReader(); // Using a 1K byte buffer and a 4K FileStream buffer works out pretty well // perf-wise. On even a 40 MB text file, any perf loss by using a 4K // buffer is negated by the win of allocating a smaller byte[], which // saves construction time. This does break adaptive buffering, // but this is slightly faster. internal const int DefaultBufferSize = 1024; // Byte buffer size private const int DefaultFileStreamBufferSize = 4096; private const int MinBufferSize = 128; private bool _closable; // For Console.In. We should consider exposing a Closable bit perhaps on stream at some point. private Stream stream; private Encoding encoding; private Decoder decoder; private byte[] byteBuffer; private char[] charBuffer; private byte[] _preamble; // Encoding's preamble, which identifies this encoding. private int charPos; private int charLen; // Record the number of valid bytes in the byteBuffer, for a few checks. private int byteLen; // This is used only for preamble detection private int bytePos; // This is the maximum number of chars we can get from one call to // ReadBuffer. Used so ReadBuffer can tell when to copy data into // a user's char[] directly, instead of our internal char[]. private int _maxCharsPerBuffer; // We will support looking for byte order marks in the stream and trying // to decide what the encoding might be from the byte order marks, IF they // exist. But that's all we'll do. private bool _detectEncoding; // Whether we must still check for the encoding's given preamble at the // beginning of this file. private bool _checkPreamble; // Whether the stream is most likely not going to give us back as much // data as we want the next time we call it. We must do the computation // before we do any byte order mark handling and save the result. Note // that we need this to allow users to handle streams used for an // interactive protocol, where they block waiting for the remote end // to send a response, like logging in on a Unix machine. private bool _isBlocked; // StreamReader by default will ignore illegal UTF8 characters. We don't want to // throw here because we want to be able to read ill-formed data without choking. // The high level goal is to be tolerant of encoding errors when we read and very strict // when we write. Hence, default StreamWriter encoding will throw on error. internal StreamReader() { } public StreamReader( Stream stream ) : this( stream, true ) { } public StreamReader( Stream stream , bool detectEncodingFromByteOrderMarks ) : this( stream, Encoding.UTF8, detectEncodingFromByteOrderMarks, DefaultBufferSize ) { } public StreamReader( Stream stream , Encoding encoding ) : this( stream, encoding, true, DefaultBufferSize ) { } public StreamReader( Stream stream , Encoding encoding , bool detectEncodingFromByteOrderMarks ) : this( stream, encoding, detectEncodingFromByteOrderMarks, DefaultBufferSize ) { } // Creates a new StreamReader for the given stream. The // character encoding is set by encoding and the buffer size, // in number of 16-bit characters, is set by bufferSize. // // Note that detectEncodingFromByteOrderMarks is a very // loose attempt at detecting the encoding by looking at the first // 3 bytes of the stream. It will recognize UTF-8, little endian // unicode, and big endian unicode text, but that's it. If neither // of those three match, it will use the Encoding you provided. // public StreamReader( Stream stream , Encoding encoding , bool detectEncodingFromByteOrderMarks , int bufferSize ) { if(stream == null || encoding == null) { #if EXCEPTION_STRINGS throw new ArgumentNullException( (stream == null ? "stream" : "encoding") ); #else throw new ArgumentNullException(); #endif } if(!stream.CanRead) { #if EXCEPTION_STRINGS throw new ArgumentException( Environment.GetResourceString( "Argument_StreamNotReadable" ) ); #else throw new ArgumentException(); #endif } if(bufferSize <= 0) { #if EXCEPTION_STRINGS throw new ArgumentOutOfRangeException( "bufferSize", Environment.GetResourceString( "ArgumentOutOfRange_NeedPosNum" ) ); #else throw new ArgumentOutOfRangeException(); #endif } Init( stream, encoding, detectEncodingFromByteOrderMarks, bufferSize ); } // For non closable streams such as Console.In internal StreamReader( Stream stream , Encoding encoding , bool detectEncodingFromByteOrderMarks , int bufferSize , bool closable ) : this( stream, encoding, detectEncodingFromByteOrderMarks, bufferSize ) { _closable = closable; } //// [ResourceExposure( ResourceScope.Machine )] //// [ResourceConsumption( ResourceScope.Machine )] public StreamReader( String path ) : this( path, true ) { } //// [ResourceExposure( ResourceScope.Machine )] //// [ResourceConsumption( ResourceScope.Machine )] public StreamReader( String path , bool detectEncodingFromByteOrderMarks ) : this( path, Encoding.UTF8, detectEncodingFromByteOrderMarks, DefaultBufferSize ) { } //// [ResourceExposure( ResourceScope.Machine )] //// [ResourceConsumption( ResourceScope.Machine )] public StreamReader( String path , Encoding encoding ) : this( path, encoding, true, DefaultBufferSize ) { } //// [ResourceExposure( ResourceScope.Machine )] //// [ResourceConsumption( ResourceScope.Machine )] public StreamReader( String path , Encoding encoding , bool detectEncodingFromByteOrderMarks ) : this( path, encoding, detectEncodingFromByteOrderMarks, DefaultBufferSize ) { } //// [ResourceExposure( ResourceScope.Machine )] //// [ResourceConsumption( ResourceScope.Machine )] public StreamReader( String path , Encoding encoding , bool detectEncodingFromByteOrderMarks , int bufferSize ) { // Don't open a Stream before checking for invalid arguments, // or we'll create a FileStream on disk and we won't close it until // the finalizer runs, causing problems for applications. if(path == null || encoding == null) { #if EXCEPTION_STRINGS throw new ArgumentNullException( (path == null ? "path" : "encoding") ); #else throw new ArgumentNullException(); #endif } if(path.Length == 0) { #if EXCEPTION_STRINGS throw new ArgumentException( Environment.GetResourceString( "Argument_EmptyPath" ) ); #else throw new ArgumentException(); #endif } if(bufferSize <= 0) { #if EXCEPTION_STRINGS throw new ArgumentOutOfRangeException( "bufferSize", Environment.GetResourceString( "ArgumentOutOfRange_NeedPosNum" ) ); #else throw new ArgumentOutOfRangeException(); #endif } Stream stream = CreateFile( path ); Init( stream, encoding, detectEncodingFromByteOrderMarks, bufferSize ); } private void Init( Stream stream , Encoding encoding , bool detectEncodingFromByteOrderMarks , int bufferSize ) { this.stream = stream; this.encoding = encoding; decoder = encoding.GetDecoder(); if(bufferSize < MinBufferSize) bufferSize = MinBufferSize; byteBuffer = new byte[bufferSize]; _maxCharsPerBuffer = encoding.GetMaxCharCount( bufferSize ); charBuffer = new char[_maxCharsPerBuffer]; byteLen = 0; bytePos = 0; _detectEncoding = detectEncodingFromByteOrderMarks; _preamble = encoding.GetPreamble(); _checkPreamble = (_preamble.Length > 0); _isBlocked = false; _closable = true; // ByDefault all streams are closable unless explicitly told otherwise } //// [ResourceExposure( ResourceScope.Machine )] //// [ResourceConsumption( ResourceScope.Machine )] //// [MethodImpl( MethodImplOptions.InternalCall )] private static Stream CreateFile( String path ) { FileStream f = new FileStream( path, FileMode.Open, FileAccess.Read, FileShare.Read, DefaultFileStreamBufferSize ); //, FileOptions.SequentialScan ); return f; } public override void Close() { Dispose( true ); } protected override void Dispose( bool disposing ) { // Dispose of our resources if this StreamReader is closable. // Note that Console.In should not be closable. try { // Note that Stream.Close() can potentially throw here. So we need to // ensure cleaning up internal resources, inside the finally block. if(Closable && disposing && (stream != null)) { stream.Close(); } } finally { if(Closable && (stream != null)) { stream = null; encoding = null; decoder = null; byteBuffer = null; charBuffer = null; charPos = 0; charLen = 0; base.Dispose( disposing ); } } } public virtual Encoding CurrentEncoding { get { return encoding; } } public virtual Stream BaseStream { get { return stream; } } internal bool Closable { get { return _closable; } //set { _closable = value; } } // DiscardBufferedData tells StreamReader to throw away its internal // buffer contents. This is useful if the user needs to seek on the // underlying stream to a known location then wants the StreamReader // to start reading from this new point. This method should be called // very sparingly, if ever, since it can lead to very poor performance. // However, it may be the only way of handling some scenarios where // users need to re-read the contents of a StreamReader a second time. public void DiscardBufferedData() { byteLen = 0; charLen = 0; charPos = 0; decoder = encoding.GetDecoder(); _isBlocked = false; } public bool EndOfStream { get { if(stream == null) { __Error.ReaderClosed(); } if(charPos < charLen) { return false; } // This may block on pipes! int numRead = ReadBuffer(); return numRead == 0; } } public override int Peek() { if(stream == null) { __Error.ReaderClosed(); } if(charPos == charLen) { if(_isBlocked || ReadBuffer() == 0) return -1; } return charBuffer[charPos]; } public override int Read() { if(stream == null) { __Error.ReaderClosed(); } if(charPos == charLen) { if(ReadBuffer() == 0) return -1; } int result = charBuffer[charPos]; charPos++; return result; } public override int Read( [In, Out] char[] buffer, int index, int count ) { if(stream == null) { __Error.ReaderClosed(); } if(buffer == null) { #if EXCEPTION_STRINGS throw new ArgumentNullException( "buffer", Environment.GetResourceString( "ArgumentNull_Buffer" ) ); #else throw new ArgumentNullException(); #endif } if(index < 0 || count < 0) { #if EXCEPTION_STRINGS throw new ArgumentOutOfRangeException( (index < 0 ? "index" : "count"), Environment.GetResourceString( "ArgumentOutOfRange_NeedNonNegNum" ) ); #else throw new ArgumentOutOfRangeException(); #endif } if(buffer.Length - index < count) { #if EXCEPTION_STRINGS throw new ArgumentException( Environment.GetResourceString( "Argument_InvalidOffLen" ) ); #else throw new ArgumentException(); #endif } int charsRead = 0; // As a perf optimization, if we had exactly one buffer's worth of // data read in, let's try writing directly to the user's buffer. bool readToUserBuffer = false; while(count > 0) { int n = charLen - charPos; if(n == 0) n = ReadBuffer( buffer, index + charsRead, count, out readToUserBuffer ); if(n == 0) break; // We're at EOF if(n > count) n = count; if(!readToUserBuffer) { Buffer.InternalBlockCopy( charBuffer, charPos * 2, buffer, (index + charsRead) * 2, n * 2 ); charPos += n; } charsRead += n; count -= n; // This function shouldn't block for an indefinite amount of time, // or reading from a network stream won't work right. If we got // fewer bytes than we requested, then we want to break right here. if(_isBlocked) { break; } } return charsRead; } public override String ReadToEnd() { if(stream == null) { __Error.ReaderClosed(); } // Call ReadBuffer, then pull data out of charBuffer. StringBuilder sb = new StringBuilder( charLen - charPos ); do { sb.Append( charBuffer, charPos, charLen - charPos ); charPos = charLen; // Note we consumed these characters ReadBuffer(); } while(charLen > 0); return sb.ToString(); } // Trims n bytes from the front of the buffer. private void CompressBuffer( int n ) { BCLDebug.Assert( byteLen >= n, "CompressBuffer was called with a number of bytes greater than the current buffer length. Are two threads using this StreamReader at the same time?" ); Buffer.InternalBlockCopy( byteBuffer, n, byteBuffer, 0, byteLen - n ); byteLen -= n; } private void DetectEncoding() { if(byteLen < 2) { return; } //// _detectEncoding = false; //// bool changedEncoding = false; //// if(byteBuffer[0] == 0xFE && byteBuffer[1] == 0xFF) //// { //// // Big Endian Unicode //// //// encoding = new UnicodeEncoding( true, true ); //// CompressBuffer( 2 ); //// changedEncoding = true; //// } //// else if(byteBuffer[0] == 0xFF && byteBuffer[1] == 0xFE) //// { //// // Little Endian Unicode, or possibly little endian UTF32 //// if(byteLen >= 4 && byteBuffer[2] == 0 && byteBuffer[3] == 0) //// { //// encoding = new UTF32Encoding( false, true ); //// CompressBuffer( 4 ); //// } //// else //// { //// encoding = new UnicodeEncoding( false, true ); //// CompressBuffer( 2 ); //// } //// changedEncoding = true; //// } //// else if(byteLen >= 3 && byteBuffer[0] == 0xEF && byteBuffer[1] == 0xBB && byteBuffer[2] == 0xBF) //// { //// // UTF-8 //// encoding = Encoding.UTF8; //// CompressBuffer( 3 ); //// changedEncoding = true; //// } //// else if(byteLen >= 4 && byteBuffer[0] == 0 && byteBuffer[1] == 0 && //// byteBuffer[2] == 0xFE && byteBuffer[3] == 0xFF) //// { //// // Big Endian UTF32 //// encoding = new UTF32Encoding( true, true ); //// changedEncoding = true; //// } //// else if(byteLen == 2) //// { //// _detectEncoding = true; //// } //// //// // Note: in the future, if we change this algorithm significantly, //// // we can support checking for the preamble of the given encoding. //// //// if(changedEncoding) //// { //// decoder = encoding.GetDecoder(); //// _maxCharsPerBuffer = encoding.GetMaxCharCount( byteBuffer.Length ); //// charBuffer = new char[_maxCharsPerBuffer]; //// } } // Trims the preamble bytes from the byteBuffer. This routine can be called multiple times // and we will buffer the bytes read until the preamble is matched or we determine that // there is no match. If there is no match, every byte read previously will be available // for further consumption. If there is a match, we will compress the buffer for the // leading preamble bytes private bool IsPreamble() { if(!_checkPreamble) { return _checkPreamble; } BCLDebug.Assert( bytePos <= _preamble.Length, "_compressPreamble was called with the current bytePos greater than the preamble buffer length. Are two threads using this StreamReader at the same time?" ); int len = (byteLen >= (_preamble.Length)) ? (_preamble.Length - bytePos) : (byteLen - bytePos); for(int i = 0; i < len; i++, bytePos++) { if(byteBuffer[bytePos] != _preamble[bytePos]) { bytePos = 0; _checkPreamble = false; break; } } BCLDebug.Assert( bytePos <= _preamble.Length, "possible bug in _compressPreamble. Are two threads using this StreamReader at the same time?" ); if(_checkPreamble) { if(bytePos == _preamble.Length) { // We have a match CompressBuffer( _preamble.Length ); bytePos = 0; _checkPreamble = false; _detectEncoding = false; } } return _checkPreamble; } private int ReadBuffer() { charLen = 0; charPos = 0; if(!_checkPreamble) { byteLen = 0; } do { if(_checkPreamble) { BCLDebug.Assert( bytePos <= _preamble.Length, "possible bug in _compressPreamble. Are two threads using this StreamReader at the same time?" ); int len = stream.Read( byteBuffer, bytePos, byteBuffer.Length - bytePos ); BCLDebug.Assert( len >= 0, "Stream.Read returned a negative number! This is a bug in your stream class." ); if(len == 0) { // EOF but we might have buffered bytes from previous // attempts to detecting preamble that needs to decoded now if(byteLen > 0) charLen += decoder.GetChars( byteBuffer, 0, byteLen, charBuffer, charLen ); return charLen; } byteLen += len; } else { BCLDebug.Assert( bytePos == 0, "bytePos can be non zero only when we are trying to _checkPreamble. Are two threads using this StreamReader at the same time?" ); byteLen = stream.Read( byteBuffer, 0, byteBuffer.Length ); BCLDebug.Assert( byteLen >= 0, "Stream.Read returned a negative number! This is a bug in your stream class." ); if(byteLen == 0) // We're at EOF return charLen; } // _isBlocked == whether we read fewer bytes than we asked for. // Note we must check it here because CompressBuffer or // DetectEncoding will screw with byteLen. _isBlocked = (byteLen < byteBuffer.Length); // Check for preamble before detect encoding. This is not to override the // user suppplied Encoding for the one we implicitly detect. The user could // customize the encoding which we will loose, such as ThrowOnError on UTF8 if(IsPreamble()) continue; // If we're supposed to detect the encoding and haven't done so yet, // do it. Note this may need to be called more than once. if(_detectEncoding && byteLen >= 2) DetectEncoding(); charLen += decoder.GetChars( byteBuffer, 0, byteLen, charBuffer, charLen ); } while(charLen == 0); //Console.WriteLine("ReadBuffer called. chars: "+charLen); return charLen; } // This version has a perf optimization to decode data DIRECTLY into the // user's buffer, bypassing StreamWriter's own buffer. // This gives a > 20% perf improvement for our encodings across the board, // but only when asking for at least the number of characters that one // buffer's worth of bytes could produce. // This optimization, if run, will break SwitchEncoding, so we must not do // this on the first call to ReadBuffer. private int ReadBuffer( char[] userBuffer, int userOffset, int desiredChars, out bool readToUserBuffer ) { charLen = 0; charPos = 0; if(!_checkPreamble) byteLen = 0; int charsRead = 0; // As a perf optimization, we can decode characters DIRECTLY into a // user's char[]. We absolutely must not write more characters // into the user's buffer than they asked for. Calculating // encoding.GetMaxCharCount(byteLen) each time is potentially very // expensive - instead, cache the number of chars a full buffer's // worth of data may produce. Yes, this makes the perf optimization // less aggressive, in that all reads that asked for fewer than AND // returned fewer than _maxCharsPerBuffer chars won't get the user // buffer optimization. This affects reads where the end of the // Stream comes in the middle somewhere, and when you ask for // fewer chars than than your buffer could produce. readToUserBuffer = desiredChars >= _maxCharsPerBuffer; do { if(_checkPreamble) { BCLDebug.Assert( bytePos <= _preamble.Length, "possible bug in _compressPreamble. Are two threads using this StreamReader at the same time?" ); int len = stream.Read( byteBuffer, bytePos, byteBuffer.Length - bytePos ); BCLDebug.Assert( len >= 0, "Stream.Read returned a negative number! This is a bug in your stream class." ); if(len == 0) { // EOF but we might have buffered bytes from previous // attempts to detecting preamble that needs to decoded now if(byteLen > 0) { if(readToUserBuffer) { charsRead += decoder.GetChars( byteBuffer, 0, byteLen, userBuffer, userOffset + charsRead ); charLen = 0; // StreamReader's buffer is empty. } else { charsRead = decoder.GetChars( byteBuffer, 0, byteLen, charBuffer, charsRead ); charLen += charsRead; // Number of chars in StreamReader's buffer. } } return charsRead; } byteLen += len; } else { BCLDebug.Assert( bytePos == 0, "bytePos can be non zero only when we are trying to _checkPreamble. Are two threads using this StreamReader at the same time?" ); byteLen = stream.Read( byteBuffer, 0, byteBuffer.Length ); BCLDebug.Assert( byteLen >= 0, "Stream.Read returned a negative number! This is a bug in your stream class." ); if(byteLen == 0) // EOF { return charsRead; } } // _isBlocked == whether we read fewer bytes than we asked for. // Note we must check it here because CompressBuffer or // DetectEncoding will screw with byteLen. _isBlocked = (byteLen < byteBuffer.Length); // Check for preamble before detect encoding. This is not to override the // user suppplied Encoding for the one we implicitly detect. The user could // customize the encoding which we will loose, such as ThrowOnError on UTF8 // Note: we don't need to recompute readToUserBuffer optimization as IsPreamble // doesn't change the encoding or affect _maxCharsPerBuffer if(IsPreamble()) { continue; } // On the first call to ReadBuffer, if we're supposed to detect the encoding, do it. if(_detectEncoding && byteLen >= 2) { DetectEncoding(); // DetectEncoding changes some buffer state. Recompute this. readToUserBuffer = desiredChars >= _maxCharsPerBuffer; } charPos = 0; if(readToUserBuffer) { charsRead += decoder.GetChars( byteBuffer, 0, byteLen, userBuffer, userOffset + charsRead ); charLen = 0; // StreamReader's buffer is empty. } else { charsRead = decoder.GetChars( byteBuffer, 0, byteLen, charBuffer, charsRead ); charLen += charsRead; // Number of chars in StreamReader's buffer. } } while(charsRead == 0); _isBlocked &= charsRead < desiredChars; //Console.WriteLine("ReadBuffer: charsRead: "+charsRead+" readToUserBuffer: "+readToUserBuffer); return charsRead; } // Reads a line. A line is defined as a sequence of characters followed by // a carriage return ('\r'), a line feed ('\n'), or a carriage return // immediately followed by a line feed. The resulting string does not // contain the terminating carriage return and/or line feed. The returned // value is null if the end of the input stream has been reached. // public override String ReadLine() { if(stream == null) { __Error.ReaderClosed(); } if(charPos == charLen) { if(ReadBuffer() == 0) return null; } StringBuilder sb = null; do { int i = charPos; do { char ch = charBuffer[i]; // Note the following common line feed chars: // \n - UNIX \r\n - DOS \r - Mac if(ch == '\r' || ch == '\n') { String s; if(sb != null) { sb.Append( charBuffer, charPos, i - charPos ); s = sb.ToString(); } else { s = new String( charBuffer, charPos, i - charPos ); } charPos = i + 1; if(ch == '\r' && (charPos < charLen || ReadBuffer() > 0)) { if(charBuffer[charPos] == '\n') charPos++; } return s; } i++; } while(i < charLen); i = charLen - charPos; if(sb == null) sb = new StringBuilder( i + 80 ); sb.Append( charBuffer, charPos, i ); } while(ReadBuffer() > 0); return sb.ToString(); } // No data, class doesn't need to be serializable. // Note this class is threadsafe. private class NullStreamReader : StreamReader { internal NullStreamReader() : base( Stream.Null, Encoding.Unicode, false, 1 ) { } public override Stream BaseStream { get { return Stream.Null; } } public override Encoding CurrentEncoding { get { return Encoding.Unicode; } } protected override void Dispose( bool disposing ) { // Do nothing - this is essentially unclosable. } public override int Peek() { return -1; } public override int Read() { return -1; } public override int Read( char[] buffer, int index, int count ) { return 0; } public override String ReadLine() { return null; } public override String ReadToEnd() { return String.Empty; } } } } ================================================ FILE: Zelig/Zelig/RunTime/Framework/mscorlib/System/IO/StreamWriter.cs ================================================ // ==++== // // Copyright (c) Microsoft Corporation. All rights reserved. // // ==--== /*============================================================ ** ** Class: StreamWriter ** ** ** Purpose: For writing text to streams in a particular ** encoding. ** ** ===========================================================*/ using System; using System.Text; using System.Threading; using System.Globalization; using System.Runtime.CompilerServices; //using System.Runtime.Versioning; //using System.Runtime.Serialization; namespace System.IO { // This class implements a TextWriter for writing characters to a Stream. // This is designed for character output in a particular Encoding, // whereas the Stream class is designed for byte input and output. // [Serializable] public class StreamWriter : TextWriter { // For UTF-8, the values of 1K for the default buffer size and 4K for the // file stream buffer size are reasonable & give very reasonable // performance for in terms of construction time for the StreamWriter and // write perf. Note that for UTF-8, we end up allocating a 4K byte buffer, // which means we take advantage of adaptive buffering code. // The performance using UnicodeEncoding is acceptable. private const int DefaultBufferSize = 1024; // char[] private const int DefaultFileStreamBufferSize = 4096; private const int MinBufferSize = 128; //// // Bit bucket - Null has no backing store. Non closable. //// public new static readonly StreamWriter Null = new StreamWriter( Stream.Null, new UTF8Encoding( false, true ), MinBufferSize, false ); internal Stream stream; private Encoding encoding; private Encoder encoder; internal byte[] byteBuffer; internal char[] charBuffer; internal int charPos; internal int charLen; internal bool autoFlush; private bool haveWrittenPreamble; private bool closable; // For Console.Out - should Finalize call Dispose? //// // The high level goal is to be tolerant of encoding errors when we read and very strict //// // when we write. Hence, default StreamWriter encoding will throw on encoding error. //// // Note: when StreamWriter throws on invalid encoding chars (for ex, high surrogate character //// // D800-DBFF without a following low surrogate character DC00-DFFF), it will cause the //// // internal StreamWriter's state to be irrecoverable as it would have buffered the //// // illegal chars and any subsequent call to Flush() would hit the encoding error again. //// // Even Close() will hit the exception as it would try to flush the unwritten data. //// // May be we can add a DiscardBufferedData() method to get out of such situation (like //// // StreamRerader though for different reason). Eitherway, the buffered data will be lost! private static Encoding _UTF8NoBOM; internal static Encoding UTF8NoBOM { get { if(_UTF8NoBOM == null) { // No need for double lock - we just want to avoid extra // allocations in the common case. UTF8Encoding noBOM = new UTF8Encoding( false, true ); //Thread.MemoryBarrier(); _UTF8NoBOM = noBOM; } return _UTF8NoBOM; } } internal StreamWriter() : base( null ) { // Ask for CurrentCulture all the time } public StreamWriter( Stream stream ) : this( stream, UTF8NoBOM, DefaultBufferSize ) { } public StreamWriter( Stream stream, Encoding encoding ) : this( stream, encoding, DefaultBufferSize ) { } // Creates a new StreamWriter for the given stream. The // character encoding is set by encoding and the buffer size, // in number of 16-bit characters, is set by bufferSize. // public StreamWriter( Stream stream, Encoding encoding, int bufferSize ) : base( null ) { // Ask for CurrentCulture all the time if(stream == null || encoding == null) { #if EXCEPTION_STRINGS throw new ArgumentNullException( (stream == null ? "stream" : "encoding") ); #else throw new ArgumentNullException(); #endif } if(!stream.CanWrite) { #if EXCEPTION_STRINGS throw new ArgumentException( Environment.GetResourceString( "Argument_StreamNotWritable" ) ); #else throw new ArgumentException(); #endif } if(bufferSize <= 0) { #if EXCEPTION_STRINGS throw new ArgumentOutOfRangeException( "bufferSize", Environment.GetResourceString( "ArgumentOutOfRange_NeedPosNum" ) ); #else throw new ArgumentOutOfRangeException(); #endif } Init( stream, encoding, bufferSize ); } // For non closable streams such as Console.Out internal StreamWriter( Stream stream, Encoding encoding, int bufferSize, bool closeable ) : this( stream, encoding, bufferSize ) { closable = closeable; } //// [ResourceExposure( ResourceScope.Machine )] //// [ResourceConsumption( ResourceScope.Machine )] public StreamWriter( String path ) : this( path, false, UTF8NoBOM, DefaultBufferSize ) { } //// [ResourceExposure( ResourceScope.Machine )] //// [ResourceConsumption( ResourceScope.Machine )] public StreamWriter( String path, bool append ) : this( path, append, UTF8NoBOM, DefaultBufferSize ) { } //// [ResourceExposure( ResourceScope.Machine )] //// [ResourceConsumption( ResourceScope.Machine )] public StreamWriter( String path, bool append, Encoding encoding ) : this( path, append, encoding, DefaultBufferSize ) { } //// [ResourceExposure( ResourceScope.Machine )] //// [ResourceConsumption( ResourceScope.Machine )] public StreamWriter( String path, bool append, Encoding encoding, int bufferSize ) : base( null ) { // Ask for CurrentCulture all the time if(path == null || encoding == null) { #if EXCEPTION_STRINGS throw new ArgumentNullException( (path == null ? "path" : "encoding") ); #else throw new ArgumentNullException(); #endif } if(bufferSize <= 0) { #if EXCEPTION_STRINGS throw new ArgumentOutOfRangeException( "bufferSize", Environment.GetResourceString( "ArgumentOutOfRange_NeedPosNum" ) ); #else throw new ArgumentOutOfRangeException(); #endif } Stream stream = CreateFile( path, append ); Init( stream, encoding, bufferSize ); } private void Init( Stream stream, Encoding encoding, int bufferSize ) { this.stream = stream; this.encoding = encoding; this.encoder = encoding.GetEncoder(); if(bufferSize < MinBufferSize) bufferSize = MinBufferSize; charBuffer = new char[bufferSize]; byteBuffer = new byte[encoding.GetMaxByteCount( bufferSize )]; charLen = bufferSize; // If we're appending to a Stream that already has data, don't write // the preamble. if(stream.CanSeek && stream.Position > 0) { haveWrittenPreamble = true; } closable = true; } //// [ResourceExposure( ResourceScope.Machine )] //// [ResourceConsumption( ResourceScope.Machine )] //// [MethodImpl( MethodImplOptions.InternalCall )] private static Stream CreateFile( String path, bool append ) { FileMode mode = append ? FileMode.Append : FileMode.Create; FileStream f = new FileStream( path, mode, FileAccess.Write, FileShare.Read, DefaultFileStreamBufferSize ); //, FileOptions.SequentialScan ); return f; } public override void Close() { Dispose( true ); GC.SuppressFinalize( this ); } protected override void Dispose( bool disposing ) { try { // We need to flush any buffered data if we are being closed/disposed. // Also, we never close the handles for stdout & friends. So we can safely // write any buffered data to those streams even during finalization, which // is generally the right thing to do. if(stream != null) { // Note: flush on the underlying stream can throw (ex., low disk space) //if(disposing || (!Closable && stream is __ConsoleStream)) if(disposing) { Flush( true, true ); } } } finally { // Dispose of our resources if this StreamWriter is closable. // Note: Console.Out and other such non closable streamwriters should be left alone if(Closable && stream != null) { try { // Attempt to close the stream even if there was an IO error from Flushing. // Note that Stream.Close() can potentially throw here (may or may not be // due to the same Flush error). In this case, we still need to ensure // cleaning up internal resources, hence the finally block. if(disposing) { stream.Close(); } } finally { stream = null; byteBuffer = null; charBuffer = null; encoding = null; encoder = null; charLen = 0; base.Dispose( disposing ); } } } } public override void Flush() { Flush( true, true ); } private void Flush( bool flushStream, bool flushEncoder ) { // flushEncoder should be true at the end of the file and if // the user explicitly calls Flush (though not if AutoFlush is true). // This is required to flush any dangling characters from our UTF-7 // and UTF-8 encoders. if(stream == null) { __Error.WriterClosed(); } // Perf boost for Flush on non-dirty writers. if(charPos == 0 && !flushStream && !flushEncoder) { return; } if(!haveWrittenPreamble) { haveWrittenPreamble = true; byte[] preamble = encoding.GetPreamble(); if(preamble.Length > 0) { stream.Write( preamble, 0, preamble.Length ); } } int count = encoder.GetBytes( charBuffer, 0, charPos, byteBuffer, 0, flushEncoder ); charPos = 0; if(count > 0) { stream.Write( byteBuffer, 0, count ); } // By definition, calling Flush should flush the stream, but this is // only necessary if we passed in true for flushStream. The Web // Services guys have some perf tests where flushing needlessly hurts. if(flushStream) { stream.Flush(); } } public virtual bool AutoFlush { get { return autoFlush; } set { autoFlush = value; if(value) Flush( true, false ); } } public virtual Stream BaseStream { get { return stream; } } internal bool Closable { get { return closable; } //set { closable = value; } } internal bool HaveWrittenPreamble { set { haveWrittenPreamble = value; } } public override Encoding Encoding { get { return encoding; } } public override void Write( char value ) { if(charPos == charLen) Flush( false, false ); charBuffer[charPos] = value; charPos++; if(autoFlush) Flush( true, false ); } public override void Write( char[] buffer ) { // This may be faster than the one with the index & count since it // has to do less argument checking. if(buffer == null) { return; } int index = 0; int count = buffer.Length; while(count > 0) { if(charPos == charLen) Flush( false, false ); int n = charLen - charPos; if(n > count) n = count; BCLDebug.Assert( n > 0, "StreamWriter::Write(char[]) isn't making progress! This is most likely a race in user code." ); Buffer.InternalBlockCopy( buffer, index * 2, charBuffer, charPos * 2, n * 2 ); charPos += n; index += n; count -= n; } if(autoFlush) Flush( true, false ); } public override void Write( char[] buffer, int index, int count ) { if(buffer == null) { #if EXCEPTION_STRINGS throw new ArgumentNullException( "buffer", Environment.GetResourceString( "ArgumentNull_Buffer" ) ); #else throw new ArgumentNullException(); #endif } if(index < 0) { #if EXCEPTION_STRINGS throw new ArgumentOutOfRangeException( "index", Environment.GetResourceString( "ArgumentOutOfRange_NeedNonNegNum" ) ); #else throw new ArgumentOutOfRangeException(); #endif } if(count < 0) { #if EXCEPTION_STRINGS throw new ArgumentOutOfRangeException( "count", Environment.GetResourceString( "ArgumentOutOfRange_NeedNonNegNum" ) ); #else throw new ArgumentOutOfRangeException(); #endif } if(buffer.Length - index < count) { #if EXCEPTION_STRINGS throw new ArgumentException( Environment.GetResourceString( "Argument_InvalidOffLen" ) ); #else throw new ArgumentException(); #endif } while(count > 0) { if(charPos == charLen) Flush( false, false ); int n = charLen - charPos; if(n > count) n = count; BCLDebug.Assert( n > 0, "StreamWriter::Write(char[], int, int) isn't making progress! This is most likely a race condition in user code." ); Buffer.InternalBlockCopy( buffer, index * 2, charBuffer, charPos * 2, n * 2 ); charPos += n; index += n; count -= n; } if(autoFlush) Flush( true, false ); } public override void Write( String value ) { if(value != null) { int count = value.Length; int index = 0; while(count > 0) { if(charPos == charLen) Flush( false, false ); int n = charLen - charPos; if(n > count) n = count; BCLDebug.Assert( n > 0, "StreamWriter::Write(String) isn't making progress! This is most likely a race condition in user code." ); value.CopyTo( index, charBuffer, charPos, n ); charPos += n; index += n; count -= n; } if(autoFlush) Flush( true, false ); } } } } ================================================ FILE: Zelig/Zelig/RunTime/Framework/mscorlib/System/IO/TextReader.cs ================================================ // ==++== // // Copyright (c) Microsoft Corporation. All rights reserved. // // ==--== /*============================================================ ** ** Class: TextReader ** ** ** Purpose: Abstract base class for all Text-only Readers. ** Subclasses will include StreamReader & StringReader. ** ** ===========================================================*/ using System; using System.Text; using System.Runtime.InteropServices; using System.Runtime.CompilerServices; using System.Reflection; using System.Security.Permissions; namespace System.IO { // This abstract base class represents a reader that can read a sequential // stream of characters. This is not intended for reading bytes - // there are methods on the Stream class to read bytes. // A subclass must minimally implement the Peek() and Read() methods. // // This class is intended for character input, not bytes. // There are methods on the Stream class for reading bytes. [Serializable()] public abstract class TextReader : MarshalByRefObject, IDisposable { public static readonly TextReader Null = new NullTextReader(); protected TextReader() { } // Closes this TextReader and releases any system resources associated with the // TextReader. Following a call to Close, any operations on the TextReader // may raise exceptions. // // This default method is empty, but descendant classes can override the // method to provide the appropriate functionality. public virtual void Close() { Dispose( true ); GC.SuppressFinalize( this ); } public void Dispose() { Dispose( true ); GC.SuppressFinalize( this ); } protected virtual void Dispose( bool disposing ) { } // Returns the next available character without actually reading it from // the input stream. The current position of the TextReader is not changed by // this operation. The returned value is -1 if no further characters are // available. // // This default method simply returns -1. // public virtual int Peek() { return -1; } // Reads the next character from the input stream. The returned value is // -1 if no further characters are available. // // This default method simply returns -1. // public virtual int Read() { return -1; } // Reads a block of characters. This method will read up to // count characters from this TextReader into the // buffer character array starting at position // index. Returns the actual number of characters read. // public virtual int Read( [In, Out] char[] buffer, int index, int count ) { if(buffer == null) { #if EXCEPTION_STRINGS throw new ArgumentNullException( "buffer", Environment.GetResourceString( "ArgumentNull_Buffer" ) ); #else throw new ArgumentNullException(); #endif } if(index < 0) { #if EXCEPTION_STRINGS throw new ArgumentOutOfRangeException( "index", Environment.GetResourceString( "ArgumentOutOfRange_NeedNonNegNum" ) ); #else throw new ArgumentOutOfRangeException(); #endif } if(count < 0) { #if EXCEPTION_STRINGS throw new ArgumentOutOfRangeException( "count", Environment.GetResourceString( "ArgumentOutOfRange_NeedNonNegNum" ) ); #else throw new ArgumentOutOfRangeException(); #endif } if(buffer.Length - index < count) { #if EXCEPTION_STRINGS throw new ArgumentException( Environment.GetResourceString( "Argument_InvalidOffLen" ) ); #else throw new ArgumentException(); #endif } int n = 0; do { int ch = Read(); if(ch == -1) break; buffer[index + n++] = (char)ch; } while(n < count); return n; } // Reads all characters from the current position to the end of the // TextReader, and returns them as one string. public virtual String ReadToEnd() { char[] chars = new char[4096]; int len; StringBuilder sb = new StringBuilder( 4096 ); while((len = Read( chars, 0, chars.Length )) != 0) { sb.Append( chars, 0, len ); } return sb.ToString(); } // Blocking version of read. Returns only when count // characters have been read or the end of the file was reached. // public virtual int ReadBlock( [In, Out] char[] buffer, int index, int count ) { int i, n = 0; do { n += (i = Read( buffer, index + n, count - n )); } while(i > 0 && n < count); return n; } // Reads a line. A line is defined as a sequence of characters followed by // a carriage return ('\r'), a line feed ('\n'), or a carriage return // immediately followed by a line feed. The resulting string does not // contain the terminating carriage return and/or line feed. The returned // value is null if the end of the input stream has been reached. // public virtual String ReadLine() { StringBuilder sb = new StringBuilder(); while(true) { int ch = Read(); if(ch == -1) break; if(ch == '\r' || ch == '\n') { if(ch == '\r' && Peek() == '\n') Read(); return sb.ToString(); } sb.Append( (char)ch ); } if(sb.Length > 0) return sb.ToString(); return null; } [HostProtection( Synchronization = true )] public static TextReader Synchronized( TextReader reader ) { if(reader == null) { #if EXCEPTION_STRINGS throw new ArgumentNullException( "reader" ); #else throw new ArgumentNullException(); #endif } if(reader is SyncTextReader) { return reader; } return new SyncTextReader( reader ); } [Serializable()] private sealed class NullTextReader : TextReader { public override int Read( char[] buffer, int index, int count ) { return 0; } public override String ReadLine() { return null; } } [Serializable()] internal sealed class SyncTextReader : TextReader { internal TextReader _in; internal SyncTextReader( TextReader t ) { _in = t; } [MethodImplAttribute( MethodImplOptions.Synchronized )] public override void Close() { // So that any overriden Close() gets run _in.Close(); } [MethodImplAttribute( MethodImplOptions.Synchronized )] protected override void Dispose( bool disposing ) { // Explicitly pick up a potentially methodimpl'ed Dispose if(disposing) { ((IDisposable)_in).Dispose(); } } [MethodImplAttribute( MethodImplOptions.Synchronized )] public override int Peek() { return _in.Peek(); } [MethodImplAttribute( MethodImplOptions.Synchronized )] public override int Read() { return _in.Read(); } [MethodImplAttribute( MethodImplOptions.Synchronized )] public override int Read( [In, Out] char[] buffer, int index, int count ) { return _in.Read( buffer, index, count ); } [MethodImplAttribute( MethodImplOptions.Synchronized )] public override int ReadBlock( [In, Out] char[] buffer, int index, int count ) { return _in.ReadBlock( buffer, index, count ); } [MethodImplAttribute( MethodImplOptions.Synchronized )] public override String ReadLine() { return _in.ReadLine(); } [MethodImplAttribute( MethodImplOptions.Synchronized )] public override String ReadToEnd() { return _in.ReadToEnd(); } } } } ================================================ FILE: Zelig/Zelig/RunTime/Framework/mscorlib/System/IO/TextWriter.cs ================================================ // ==++== // // Copyright (c) Microsoft Corporation. All rights reserved. // // ==--== /*============================================================ ** ** Class: TextWriter ** ** ** Purpose: Abstract base class for Text-only Writers. ** Subclasses will include StreamWriter & StringWriter. ** ** ===========================================================*/ using System; using System.Text; using System.Threading; using System.Runtime.CompilerServices; using System.Reflection; using System.Security.Permissions; using System.Globalization; namespace System.IO { // This abstract base class represents a writer that can write a sequential // stream of characters. A subclass must minimally implement the // Write(char) method. // // This class is intended for character output, not bytes. // There are methods on the Stream class for writing bytes. [Serializable] public abstract class TextWriter : MarshalByRefObject, IDisposable { public static readonly TextWriter Null = new NullTextWriter(); // This should be initialized to Environment.NewLine, but // to avoid loading Environment unnecessarily so I've duplicated // the value here. #if !PLATFORM_UNIX private const String InitialNewLine = "\r\n"; protected char[] CoreNewLine = new char[] { '\r', '\n' }; #else private const String InitialNewLine = "\n"; protected char[] CoreNewLine = new char[] {'\n'}; #endif // !PLATFORM_UNIX // Can be null - if so, ask for the Thread's CurrentCulture every time. private IFormatProvider InternalFormatProvider; protected TextWriter() { InternalFormatProvider = null; // Ask for CurrentCulture all the time. } protected TextWriter( IFormatProvider formatProvider ) { InternalFormatProvider = formatProvider; } public virtual IFormatProvider FormatProvider { get { if(InternalFormatProvider == null) { return Thread.CurrentThread.CurrentCulture; } else { return InternalFormatProvider; } } } // Closes this TextWriter and releases any system resources associated with the // TextWriter. Following a call to Close, any operations on the TextWriter // may raise exceptions. This default method is empty, but descendant // classes can override the method to provide the appropriate // functionality. public virtual void Close() { Dispose( true ); GC.SuppressFinalize( this ); } protected virtual void Dispose( bool disposing ) { } public void Dispose() { Dispose( true ); GC.SuppressFinalize( this ); } // Clears all buffers for this TextWriter and causes any buffered data to be // written to the underlying device. This default method is empty, but // descendant classes can override the method to provide the appropriate // functionality. public virtual void Flush() { } public abstract Encoding Encoding { get; } // Returns the line terminator string used by this TextWriter. The default line // terminator string is a carriage return followed by a line feed ("\r\n"). // // Sets the line terminator string for this TextWriter. The line terminator // string is written to the text stream whenever one of the // WriteLine methods are called. In order for text written by // the TextWriter to be readable by a TextReader, only one of the following line // terminator strings should be used: "\r", "\n", or "\r\n". // public virtual String NewLine { get { return new String( CoreNewLine ); } set { if(value == null) { value = InitialNewLine; } CoreNewLine = value.ToCharArray(); } } [HostProtection( Synchronization = true )] public static TextWriter Synchronized( TextWriter writer ) { if(writer == null) { #if EXCEPTION_STRINGS throw new ArgumentNullException( "writer" ); #else throw new ArgumentNullException(); #endif } if(writer is SyncTextWriter) { return writer; } return new SyncTextWriter( writer ); } // Writes a character to the text stream. This default method is empty, // but descendant classes can override the method to provide the // appropriate functionality. // public virtual void Write( char value ) { } // Writes a character array to the text stream. This default method calls // Write(char) for each of the characters in the character array. // If the character array is null, nothing is written. // public virtual void Write( char[] buffer ) { if(buffer != null) { Write( buffer, 0, buffer.Length ); } } // Writes a range of a character array to the text stream. This method will // write count characters of data into this TextWriter from the // buffer character array starting at position index. // public virtual void Write( char[] buffer, int index, int count ) { if(buffer == null) { #if EXCEPTION_STRINGS throw new ArgumentNullException( "buffer", Environment.GetResourceString( "ArgumentNull_Buffer" ) ); #else throw new ArgumentNullException(); #endif } if(index < 0) { #if EXCEPTION_STRINGS throw new ArgumentOutOfRangeException( "index", Environment.GetResourceString( "ArgumentOutOfRange_NeedNonNegNum" ) ); #else throw new ArgumentOutOfRangeException(); #endif } if(count < 0) { #if EXCEPTION_STRINGS throw new ArgumentOutOfRangeException( "count", Environment.GetResourceString( "ArgumentOutOfRange_NeedNonNegNum" ) ); #else throw new ArgumentOutOfRangeException(); #endif } if(buffer.Length - index < count) { #if EXCEPTION_STRINGS throw new ArgumentException( Environment.GetResourceString( "Argument_InvalidOffLen" ) ); #else throw new ArgumentException(); #endif } for(int i = 0; i < count; i++) { Write( buffer[index + i] ); } } // Writes the text representation of a boolean to the text stream. This // method outputs either Boolean.TrueString or Boolean.FalseString. // public virtual void Write( bool value ) { Write( value ? Boolean.TrueLiteral : Boolean.FalseLiteral ); } // Writes the text representation of an integer to the text stream. The // text representation of the given value is produced by calling the // Int32.ToString() method. // public virtual void Write( int value ) { Write( value.ToString( FormatProvider ) ); } // Writes the text representation of an integer to the text stream. The // text representation of the given value is produced by calling the // UInt32.ToString() method. // [CLSCompliant( false )] public virtual void Write( uint value ) { Write( value.ToString( FormatProvider ) ); } // Writes the text representation of a long to the text stream. The // text representation of the given value is produced by calling the // Int64.ToString() method. // public virtual void Write( long value ) { Write( value.ToString( FormatProvider ) ); } // Writes the text representation of an unsigned long to the text // stream. The text representation of the given value is produced // by calling the UInt64.ToString() method. // [CLSCompliant( false )] public virtual void Write( ulong value ) { Write( value.ToString( FormatProvider ) ); } // Writes the text representation of a float to the text stream. The // text representation of the given value is produced by calling the // Float.toString(float) method. // public virtual void Write( float value ) { Write( value.ToString( FormatProvider ) ); } // Writes the text representation of a double to the text stream. The // text representation of the given value is produced by calling the // Double.toString(double) method. // public virtual void Write( double value ) { Write( value.ToString( FormatProvider ) ); } public virtual void Write( Decimal value ) { Write( value.ToString( FormatProvider ) ); } // Writes a string to the text stream. If the given string is null, nothing // is written to the text stream. // public virtual void Write( String value ) { if(value != null) { Write( value.ToCharArray() ); } } // Writes the text representation of an object to the text stream. If the // given object is null, nothing is written to the text stream. // Otherwise, the object's ToString method is called to produce the // string representation, and the resulting string is then written to the // output stream. // public virtual void Write( Object value ) { if(value != null) { IFormattable f = value as IFormattable; if(f != null) { Write( f.ToString( null, FormatProvider ) ); } else { Write( value.ToString() ); } } } // Writes out a formatted string. Uses the same semantics as // String.Format. // public virtual void Write( String format, Object arg0 ) { Write( String.Format( FormatProvider, format, arg0 ) ); } // Writes out a formatted string. Uses the same semantics as // String.Format. // public virtual void Write( String format, Object arg0, Object arg1 ) { Write( String.Format( FormatProvider, format, arg0, arg1 ) ); } // Writes out a formatted string. Uses the same semantics as // String.Format. // public virtual void Write( String format, Object arg0, Object arg1, Object arg2 ) { Write( String.Format( FormatProvider, format, arg0, arg1, arg2 ) ); } // Writes out a formatted string. Uses the same semantics as // String.Format. // public virtual void Write( String format, params Object[] arg ) { Write( String.Format( FormatProvider, format, arg ) ); } // Writes a line terminator to the text stream. The default line terminator // is a carriage return followed by a line feed ("\r\n"), but this value // can be changed by setting the NewLine property. // public virtual void WriteLine() { Write( CoreNewLine ); } // Writes a character followed by a line terminator to the text stream. // public virtual void WriteLine( char value ) { Write( value ); WriteLine(); } // Writes an array of characters followed by a line terminator to the text // stream. // public virtual void WriteLine( char[] buffer ) { Write( buffer ); WriteLine(); } // Writes a range of a character array followed by a line terminator to the // text stream. // public virtual void WriteLine( char[] buffer, int index, int count ) { Write( buffer, index, count ); WriteLine(); } // Writes the text representation of a boolean followed by a line // terminator to the text stream. // public virtual void WriteLine( bool value ) { Write( value ); WriteLine(); } // Writes the text representation of an integer followed by a line // terminator to the text stream. // public virtual void WriteLine( int value ) { Write( value ); WriteLine(); } // Writes the text representation of an unsigned integer followed by // a line terminator to the text stream. // [CLSCompliant( false )] public virtual void WriteLine( uint value ) { Write( value ); WriteLine(); } // Writes the text representation of a long followed by a line terminator // to the text stream. // public virtual void WriteLine( long value ) { Write( value ); WriteLine(); } // Writes the text representation of an unsigned long followed by // a line terminator to the text stream. // [CLSCompliant( false )] public virtual void WriteLine( ulong value ) { Write( value ); WriteLine(); } // Writes the text representation of a float followed by a line terminator // to the text stream. // public virtual void WriteLine( float value ) { Write( value ); WriteLine(); } // Writes the text representation of a double followed by a line terminator // to the text stream. // public virtual void WriteLine( double value ) { Write( value ); WriteLine(); } public virtual void WriteLine( decimal value ) { Write( value ); WriteLine(); } // Writes a string followed by a line terminator to the text stream. // public virtual void WriteLine( String value ) { if(value == null) { WriteLine(); } else { // We'd ideally like WriteLine to be atomic, in that one call // to WriteLine equals one call to the OS (ie, so writing to // console while simultaneously calling printf will guarantee we // write out a string and new line chars, without any interference). // Additionally, we need to call ToCharArray on Strings anyways, // so allocating a char[] here isn't any worse than what we were // doing anyways. We do reduce the number of calls to the // backing store this way, potentially. int vLen = value.Length; int nlLen = CoreNewLine.Length; char[] chars = new char[vLen + nlLen]; value.CopyTo( 0, chars, 0, vLen ); // CoreNewLine will almost always be 2 chars, and possibly 1. if(nlLen == 2) { chars[vLen] = CoreNewLine[0]; chars[vLen + 1] = CoreNewLine[1]; } else if(nlLen == 1) { chars[vLen] = CoreNewLine[0]; } else { Buffer.BlockCopy( CoreNewLine, 0, chars, vLen * 2, nlLen * 2 ); } Write( chars, 0, vLen + nlLen ); } /* Write(value); // We could call Write(String) on StreamWriter... WriteLine(); */ } // Writes the text representation of an object followed by a line // terminator to the text stream. // public virtual void WriteLine( Object value ) { if(value == null) { WriteLine(); } else { // Call WriteLine(value.ToString), not Write(Object), WriteLine(). // This makes calls to WriteLine(Object) atomic. IFormattable f = value as IFormattable; if(f != null) { WriteLine( f.ToString( null, FormatProvider ) ); } else { WriteLine( value.ToString() ); } } } // Writes out a formatted string and a new line. Uses the same // semantics as String.Format. // public virtual void WriteLine( String format, Object arg0 ) { WriteLine( String.Format( FormatProvider, format, arg0 ) ); } // Writes out a formatted string and a new line. Uses the same // semantics as String.Format. // public virtual void WriteLine( String format, Object arg0, Object arg1 ) { WriteLine( String.Format( FormatProvider, format, arg0, arg1 ) ); } // Writes out a formatted string and a new line. Uses the same // semantics as String.Format. // public virtual void WriteLine( String format, Object arg0, Object arg1, Object arg2 ) { WriteLine( String.Format( FormatProvider, format, arg0, arg1, arg2 ) ); } // Writes out a formatted string and a new line. Uses the same // semantics as String.Format. // public virtual void WriteLine( String format, params Object[] arg ) { WriteLine( String.Format( FormatProvider, format, arg ) ); } [Serializable()] private sealed class NullTextWriter : TextWriter { internal NullTextWriter() : base( CultureInfo.InvariantCulture ) { } public override Encoding Encoding { get { return Encoding.Default; } } public override void Write( char[] buffer, int index, int count ) { } public override void Write( String value ) { } // Not strictly necessary, but for perf reasons public override void WriteLine() { } // Not strictly necessary, but for perf reasons public override void WriteLine( String value ) { } public override void WriteLine( Object value ) { } } [Serializable()] internal sealed class SyncTextWriter : TextWriter, IDisposable { private TextWriter _out; internal SyncTextWriter( TextWriter t ) : base( t.FormatProvider ) { _out = t; } public override Encoding Encoding { get { return _out.Encoding; } } public override IFormatProvider FormatProvider { get { return _out.FormatProvider; } } public override String NewLine { [MethodImplAttribute( MethodImplOptions.Synchronized )] get { return _out.NewLine; } [MethodImplAttribute( MethodImplOptions.Synchronized )] set { _out.NewLine = value; } } [MethodImplAttribute( MethodImplOptions.Synchronized )] public override void Close() { // So that any overriden Close() gets run _out.Close(); } [MethodImplAttribute( MethodImplOptions.Synchronized )] protected override void Dispose( bool disposing ) { // Explicitly pick up a potentially methodimpl'ed Dispose if(disposing) { ((IDisposable)_out).Dispose(); } } [MethodImplAttribute( MethodImplOptions.Synchronized )] public override void Flush() { _out.Flush(); } [MethodImplAttribute( MethodImplOptions.Synchronized )] public override void Write( char value ) { _out.Write( value ); } [MethodImplAttribute( MethodImplOptions.Synchronized )] public override void Write( char[] buffer ) { _out.Write( buffer ); } [MethodImplAttribute( MethodImplOptions.Synchronized )] public override void Write( char[] buffer, int index, int count ) { _out.Write( buffer, index, count ); } [MethodImplAttribute( MethodImplOptions.Synchronized )] public override void Write( bool value ) { _out.Write( value ); } [MethodImplAttribute( MethodImplOptions.Synchronized )] public override void Write( int value ) { _out.Write( value ); } [MethodImplAttribute( MethodImplOptions.Synchronized )] public override void Write( uint value ) { _out.Write( value ); } [MethodImplAttribute( MethodImplOptions.Synchronized )] public override void Write( long value ) { _out.Write( value ); } [MethodImplAttribute( MethodImplOptions.Synchronized )] public override void Write( ulong value ) { _out.Write( value ); } [MethodImplAttribute( MethodImplOptions.Synchronized )] public override void Write( float value ) { _out.Write( value ); } [MethodImplAttribute( MethodImplOptions.Synchronized )] public override void Write( double value ) { _out.Write( value ); } [MethodImplAttribute( MethodImplOptions.Synchronized )] public override void Write( Decimal value ) { _out.Write( value ); } [MethodImplAttribute( MethodImplOptions.Synchronized )] public override void Write( String value ) { _out.Write( value ); } [MethodImplAttribute( MethodImplOptions.Synchronized )] public override void Write( Object value ) { _out.Write( value ); } [MethodImplAttribute( MethodImplOptions.Synchronized )] public override void Write( String format, Object arg0 ) { _out.Write( format, arg0 ); } [MethodImplAttribute( MethodImplOptions.Synchronized )] public override void Write( String format, Object arg0, Object arg1 ) { _out.Write( format, arg0, arg1 ); } [MethodImplAttribute( MethodImplOptions.Synchronized )] public override void Write( String format, Object arg0, Object arg1, Object arg2 ) { _out.Write( format, arg0, arg1, arg2 ); } [MethodImplAttribute( MethodImplOptions.Synchronized )] public override void Write( String format, Object[] arg ) { _out.Write( format, arg ); } [MethodImplAttribute( MethodImplOptions.Synchronized )] public override void WriteLine() { _out.WriteLine(); } [MethodImplAttribute( MethodImplOptions.Synchronized )] public override void WriteLine( char value ) { _out.WriteLine( value ); } [MethodImplAttribute( MethodImplOptions.Synchronized )] public override void WriteLine( decimal value ) { _out.WriteLine( value ); } [MethodImplAttribute( MethodImplOptions.Synchronized )] public override void WriteLine( char[] buffer ) { _out.WriteLine( buffer ); } [MethodImplAttribute( MethodImplOptions.Synchronized )] public override void WriteLine( char[] buffer, int index, int count ) { _out.WriteLine( buffer, index, count ); } [MethodImplAttribute( MethodImplOptions.Synchronized )] public override void WriteLine( bool value ) { _out.WriteLine( value ); } [MethodImplAttribute( MethodImplOptions.Synchronized )] public override void WriteLine( int value ) { _out.WriteLine( value ); } [MethodImplAttribute( MethodImplOptions.Synchronized )] public override void WriteLine( uint value ) { _out.WriteLine( value ); } [MethodImplAttribute( MethodImplOptions.Synchronized )] public override void WriteLine( long value ) { _out.WriteLine( value ); } [MethodImplAttribute( MethodImplOptions.Synchronized )] public override void WriteLine( ulong value ) { _out.WriteLine( value ); } [MethodImplAttribute( MethodImplOptions.Synchronized )] public override void WriteLine( float value ) { _out.WriteLine( value ); } [MethodImplAttribute( MethodImplOptions.Synchronized )] public override void WriteLine( double value ) { _out.WriteLine( value ); } [MethodImplAttribute( MethodImplOptions.Synchronized )] public override void WriteLine( String value ) { _out.WriteLine( value ); } [MethodImplAttribute( MethodImplOptions.Synchronized )] public override void WriteLine( Object value ) { _out.WriteLine( value ); } [MethodImplAttribute( MethodImplOptions.Synchronized )] public override void WriteLine( String format, Object arg0 ) { _out.WriteLine( format, arg0 ); } [MethodImplAttribute( MethodImplOptions.Synchronized )] public override void WriteLine( String format, Object arg0, Object arg1 ) { _out.WriteLine( format, arg0, arg1 ); } [MethodImplAttribute( MethodImplOptions.Synchronized )] public override void WriteLine( String format, Object arg0, Object arg1, Object arg2 ) { _out.WriteLine( format, arg0, arg1, arg2 ); } [MethodImplAttribute( MethodImplOptions.Synchronized )] public override void WriteLine( String format, Object[] arg ) { _out.WriteLine( format, arg ); } } } } ================================================ FILE: Zelig/Zelig/RunTime/Framework/mscorlib/System/IO/__Error.cs ================================================ // ==++== // // Copyright (c) Microsoft Corporation. All rights reserved. // // ==--== /*============================================================ ** ** Class: __Error ** ** ** Purpose: Centralized error methods for the IO package. ** Mostly useful for translating Win32 HRESULTs into meaningful ** error strings & exceptions. ** ** ===========================================================*/ using System; using System.Runtime.InteropServices; //using Win32Native = Microsoft.Win32.Win32Native; using System.Text; //using System.Globalization; //using System.Security; //using System.Security.Permissions; namespace System.IO { // Only static data no need to serialize internal static class __Error { internal static void EndOfFile() { #if EXCEPTION_STRINGS throw new EndOfStreamException( Environment.GetResourceString( "IO.EOF_ReadBeyondEOF" ) ); #else throw new EndOfStreamException(); #endif } internal static void FileNotOpen() { #if EXCEPTION_STRINGS throw new ObjectDisposedException( null, Environment.GetResourceString( "ObjectDisposed_FileClosed" ) ); #else throw new ObjectDisposedException( null ); #endif } internal static void StreamIsClosed() { #if EXCEPTION_STRINGS throw new ObjectDisposedException( null, Environment.GetResourceString( "ObjectDisposed_StreamClosed" ) ); #else throw new ObjectDisposedException( null ); #endif } internal static void MemoryStreamNotExpandable() { #if EXCEPTION_STRINGS throw new NotSupportedException( Environment.GetResourceString( "NotSupported_MemStreamNotExpandable" ) ); #else throw new NotSupportedException(); #endif } internal static void ReaderClosed() { #if EXCEPTION_STRINGS throw new ObjectDisposedException( null, Environment.GetResourceString( "ObjectDisposed_ReaderClosed" ) ); #else throw new ObjectDisposedException( null ); #endif } internal static void ReadNotSupported() { #if EXCEPTION_STRINGS throw new NotSupportedException( Environment.GetResourceString( "NotSupported_UnreadableStream" ) ); #else throw new NotSupportedException(); #endif } internal static void SeekNotSupported() { #if EXCEPTION_STRINGS throw new NotSupportedException( Environment.GetResourceString( "NotSupported_UnseekableStream" ) ); #else throw new NotSupportedException(); #endif } internal static void WrongAsyncResult() { #if EXCEPTION_STRINGS throw new ArgumentException( Environment.GetResourceString( "Arg_WrongAsyncResult" ) ); #else throw new ArgumentException(); #endif } internal static void EndReadCalledTwice() { // Should ideally be InvalidOperationExc but we can't maitain parity with Stream and FileStream without some work #if EXCEPTION_STRINGS throw new ArgumentException( Environment.GetResourceString( "InvalidOperation_EndReadCalledMultiple" ) ); #else throw new ArgumentException(); #endif } internal static void EndWriteCalledTwice() { // Should ideally be InvalidOperationExc but we can't maintain parity with Stream and FileStream without some work #if EXCEPTION_STRINGS throw new ArgumentException( Environment.GetResourceString( "InvalidOperation_EndWriteCalledMultiple" ) ); #else throw new ArgumentException(); #endif } //// // Given a possible fully qualified path, ensure that we have path //// // discovery permission to that path. If we do not, return just the //// // file name. If we know it is a directory, then don't return the //// // directory name. //// internal static String GetDisplayablePath( String path, bool isInvalidPath ) //// { //// if(String.IsNullOrEmpty( path )) //// return path; //// //// // Is it a fully qualified path? //// bool isFullyQualified = false; //// if(path.Length < 2) //// return path; //// if(Path.IsDirectorySeparator( path[0] ) && Path.IsDirectorySeparator( path[1] )) //// isFullyQualified = true; //// else if(path[1] == Path.VolumeSeparatorChar) //// { //// isFullyQualified = true; //// } //// //// if(!isFullyQualified && !isInvalidPath) //// return path; //// //// bool safeToReturn = false; //// try //// { //// if(!isInvalidPath) //// { //// new FileIOPermission( FileIOPermissionAccess.PathDiscovery, new String[] { path }, false, false ).Demand(); //// safeToReturn = true; //// } //// } //// catch(SecurityException) //// { //// } //// catch(ArgumentException) //// { //// // ? and * characters cause ArgumentException to be thrown from HasIllegalCharacters //// // inside FileIOPermission.AddPathList //// } //// catch(NotSupportedException) //// { //// // paths like "!Bogus\\dir:with/junk_.in it" can cause NotSupportedException to be thrown //// // from Security.Util.StringExpressionSet.CanonicalizePath when ':' is found in the path //// // beyond string index position 1. //// } //// //// if(!safeToReturn) //// { //// if(Path.IsDirectorySeparator( path[path.Length - 1] )) //// path = Environment.GetResourceString( "IO.IO_NoPermissionToDirectoryName" ); //// else //// path = Path.GetFileName( path ); //// } //// //// return path; //// } //// //// internal static void WinIOError() //// { //// int errorCode = Marshal.GetLastWin32Error(); //// WinIOError( errorCode, String.Empty ); //// } //// //// // After calling GetLastWin32Error(), it clears the last error field, //// // so you must save the HResult and pass it to this method. This method //// // will determine the appropriate exception to throw dependent on your //// // error, and depending on the error, insert a string into the message //// // gotten from the ResourceManager. //// internal static void WinIOError( int errorCode, String maybeFullPath ) //// { //// // This doesn't have to be perfect, but is a perf optimization. //// bool isInvalidPath = errorCode == Win32Native.ERROR_INVALID_NAME || errorCode == Win32Native.ERROR_BAD_PATHNAME; //// String str = GetDisplayablePath( maybeFullPath, isInvalidPath ); //// //// switch(errorCode) //// { //// case Win32Native.ERROR_FILE_NOT_FOUND: //// if(str.Length == 0) //// throw new FileNotFoundException( Environment.GetResourceString( "IO.FileNotFound" ) ); //// else //// throw new FileNotFoundException( String.Format( CultureInfo.CurrentCulture, Environment.GetResourceString( "IO.FileNotFound_FileName" ), str ), str ); //// //// case Win32Native.ERROR_PATH_NOT_FOUND: //// if(str.Length == 0) //// throw new DirectoryNotFoundException( Environment.GetResourceString( "IO.PathNotFound_NoPathName" ) ); //// else //// throw new DirectoryNotFoundException( String.Format( CultureInfo.CurrentCulture, Environment.GetResourceString( "IO.PathNotFound_Path" ), str ) ); //// //// case Win32Native.ERROR_ACCESS_DENIED: //// if(str.Length == 0) //// throw new UnauthorizedAccessException( Environment.GetResourceString( "UnauthorizedAccess_IODenied_NoPathName" ) ); //// else //// throw new UnauthorizedAccessException( String.Format( CultureInfo.CurrentCulture, Environment.GetResourceString( "UnauthorizedAccess_IODenied_Path" ), str ) ); //// //// case Win32Native.ERROR_ALREADY_EXISTS: //// if(str.Length == 0) //// goto default; //// throw new IOException( Environment.GetResourceString( "IO.IO_AlreadyExists_Name", str ), Win32Native.MakeHRFromErrorCode( errorCode ), maybeFullPath ); //// //// case Win32Native.ERROR_FILENAME_EXCED_RANGE: //// throw new PathTooLongException( Environment.GetResourceString( "IO.PathTooLong" ) ); //// //// case Win32Native.ERROR_INVALID_DRIVE: //// throw new DriveNotFoundException( String.Format( CultureInfo.CurrentCulture, Environment.GetResourceString( "IO.DriveNotFound_Drive" ), str ) ); //// //// case Win32Native.ERROR_INVALID_PARAMETER: //// throw new IOException( Win32Native.GetMessage( errorCode ), Win32Native.MakeHRFromErrorCode( errorCode ), maybeFullPath ); //// //// case Win32Native.ERROR_SHARING_VIOLATION: //// if(str.Length == 0) //// throw new IOException( Environment.GetResourceString( "IO.IO_SharingViolation_NoFileName" ), Win32Native.MakeHRFromErrorCode( errorCode ), maybeFullPath ); //// else //// throw new IOException( Environment.GetResourceString( "IO.IO_SharingViolation_File", str ), Win32Native.MakeHRFromErrorCode( errorCode ), maybeFullPath ); //// //// case Win32Native.ERROR_FILE_EXISTS: //// if(str.Length == 0) //// goto default; //// throw new IOException( String.Format( CultureInfo.CurrentCulture, Environment.GetResourceString( "IO.IO_FileExists_Name" ), str ), Win32Native.MakeHRFromErrorCode( errorCode ), maybeFullPath ); //// //// case Win32Native.ERROR_OPERATION_ABORTED: //// throw new OperationCanceledException(); //// //// default: //// throw new IOException( Win32Native.GetMessage( errorCode ), Win32Native.MakeHRFromErrorCode( errorCode ), maybeFullPath ); //// } //// } //// //// // An alternative to WinIOError with friendlier messages for drives //// internal static void WinIODriveError( String driveName ) //// { //// int errorCode = Marshal.GetLastWin32Error(); //// WinIODriveError( driveName, errorCode ); //// } //// //// internal static void WinIODriveError( String driveName, int errorCode ) //// { //// switch(errorCode) //// { //// case Win32Native.ERROR_PATH_NOT_FOUND: //// case Win32Native.ERROR_INVALID_DRIVE: //// throw new DriveNotFoundException( String.Format( CultureInfo.CurrentCulture, Environment.GetResourceString( "IO.DriveNotFound_Drive" ), driveName ) ); //// //// default: //// WinIOError( errorCode, driveName ); //// break; //// } //// } internal static void WriteNotSupported() { #if EXCEPTION_STRINGS throw new NotSupportedException( Environment.GetResourceString( "NotSupported_UnwritableStream" ) ); #else throw new NotSupportedException(); #endif } internal static void WriterClosed() { #if EXCEPTION_STRINGS throw new ObjectDisposedException( null, Environment.GetResourceString( "ObjectDisposed_WriterClosed" ) ); #else throw new ObjectDisposedException( null ); #endif } //// // From WinError.h //// internal const int ERROR_FILE_NOT_FOUND = Win32Native.ERROR_FILE_NOT_FOUND; //// internal const int ERROR_PATH_NOT_FOUND = Win32Native.ERROR_PATH_NOT_FOUND; //// internal const int ERROR_ACCESS_DENIED = Win32Native.ERROR_ACCESS_DENIED; //// internal const int ERROR_INVALID_PARAMETER = Win32Native.ERROR_INVALID_PARAMETER; } } ================================================ FILE: Zelig/Zelig/RunTime/Framework/mscorlib/System/IServiceObjectProvider.cs ================================================ // ==++== // // Copyright (c) Microsoft Corporation. All rights reserved. // // ==--== namespace System { using System; using System.Runtime.InteropServices; public interface IServiceProvider { // Interface does not need to be marked with the serializable attribute Object GetService( Type serviceType ); } } ================================================ FILE: Zelig/Zelig/RunTime/Framework/mscorlib/System/IndexOutOfRangeException.cs ================================================ // ==++== // // Copyright (c) Microsoft Corporation. All rights reserved. // // ==--== /*============================================================================= ** ** Class: IndexOutOfRangeException ** ** ** Purpose: Exception class for invalid array indices. ** ** =============================================================================*/ namespace System { using System; using System.Runtime.Serialization; [Serializable] public sealed class IndexOutOfRangeException : SystemException { #if EXCEPTION_STRINGS public IndexOutOfRangeException() : base( Environment.GetResourceString( "Arg_IndexOutOfRangeException" ) ) #else public IndexOutOfRangeException() #endif { } public IndexOutOfRangeException( String message ) : base( message ) { } public IndexOutOfRangeException( String message, Exception innerException ) : base( message, innerException ) { } //// internal IndexOutOfRangeException( SerializationInfo info, StreamingContext context ) : base( info, context ) //// { //// } } } ================================================ FILE: Zelig/Zelig/RunTime/Framework/mscorlib/System/Int16.cs ================================================ // ==++== // // Copyright (c) Microsoft Corporation. All rights reserved. // // ==--== /*============================================================ ** ** Class: Int16.cs ** ** ** Purpose: This class will encapsulate a short and provide an ** Object representation of it. ** ** ===========================================================*/ namespace System { using System; using System.Globalization; using System.Runtime.InteropServices; using System.Runtime.CompilerServices; [Microsoft.Zelig.Internals.WellKnownType( "System_Int16" )] [Serializable] [StructLayout( LayoutKind.Sequential )] public struct Int16 : IComparable, IFormattable, IConvertible, IComparable, IEquatable { public const short MaxValue = (short)0x7FFF; public const short MinValue = unchecked( (short)0x8000 ); internal short m_value; // Compares this object to another object, returning an integer that // indicates the relationship. // Returns a value less than zero if this object // null is considered to be less than any instance. // If object is not of type Int16, this method throws an ArgumentException. // public int CompareTo( Object value ) { if(value == null) { return 1; } if(value is Int16) { return CompareTo( (Int16)value ); } #if EXCEPTION_STRINGS throw new ArgumentException( Environment.GetResourceString( "Arg_MustBeInt16" ) ); #else throw new ArgumentException(); #endif } public int CompareTo( Int16 value ) { return m_value - value; } public override bool Equals( Object obj ) { if(!(obj is Int16)) { return false; } return Equals( (Int16)obj ); } public bool Equals( Int16 obj ) { return m_value == obj; } // Returns a HashCode for the Int16 public override int GetHashCode() { return ((int)((ushort)m_value) | (((int)m_value) << 16)); } public override String ToString() { return Number.FormatInt32( m_value, /*null,*/ NumberFormatInfo.CurrentInfo ); } public String ToString( IFormatProvider provider ) { return Number.FormatInt32( m_value, /*null,*/ NumberFormatInfo.GetInstance( provider ) ); } public String ToString( String format ) { return ToString( format, NumberFormatInfo.CurrentInfo ); } public String ToString( String format, IFormatProvider provider ) { return ToString( format, NumberFormatInfo.GetInstance( provider ) ); } private String ToString( String format, NumberFormatInfo info ) { if(m_value < 0 && format != null && format.Length > 0 && (format[0] == 'X' || format[0] == 'x')) { uint temp = (uint)(m_value & 0x0000FFFF); return Number.FormatUInt32( temp, format, info ); } return Number.FormatInt32( m_value, format, info ); } public static short Parse( String s ) { return Parse( s, NumberStyles.Integer, NumberFormatInfo.CurrentInfo ); } public static short Parse( String s , NumberStyles style ) { NumberFormatInfo.ValidateParseStyleInteger( style ); return Parse( s, style, NumberFormatInfo.CurrentInfo ); } public static short Parse( String s , IFormatProvider provider ) { return Parse( s, NumberStyles.Integer, NumberFormatInfo.GetInstance( provider ) ); } public static short Parse( String s , NumberStyles style , IFormatProvider provider ) { NumberFormatInfo.ValidateParseStyleInteger( style ); return Parse( s, style, NumberFormatInfo.GetInstance( provider ) ); } private static short Parse( String s , NumberStyles style , NumberFormatInfo info ) { int i = 0; try { i = Number.ParseInt32( s, style, info ); } catch(OverflowException e) { #if EXCEPTION_STRINGS throw new OverflowException( Environment.GetResourceString( "Overflow_Int16" ), e ); #else throw new OverflowException( null, e); #endif } // We need this check here since we don't allow signs to specified in hex numbers. So we fixup the result // for negative numbers if((style & NumberStyles.AllowHexSpecifier) != 0) { // We are parsing a hexadecimal number if((i < 0) || (i > UInt16.MaxValue)) { #if EXCEPTION_STRINGS throw new OverflowException( Environment.GetResourceString( "Overflow_Int16" ) ); #else throw new OverflowException(); #endif } return (short)i; } if(i < MinValue || i > MaxValue) { #if EXCEPTION_STRINGS throw new OverflowException( Environment.GetResourceString( "Overflow_Int16" ) ); #else throw new OverflowException(); #endif } return (short)i; } public static bool TryParse( String s , out Int16 result ) { return TryParse( s, NumberStyles.Integer, NumberFormatInfo.CurrentInfo, out result ); } public static bool TryParse( String s , NumberStyles style , IFormatProvider provider , out Int16 result ) { NumberFormatInfo.ValidateParseStyleInteger( style ); return TryParse( s, style, NumberFormatInfo.GetInstance( provider ), out result ); } private static bool TryParse( String s , NumberStyles style , NumberFormatInfo info , out Int16 result ) { result = 0; int i; if(!Number.TryParseInt32( s, style, info, out i )) { return false; } // We need this check here since we don't allow signs to specified in hex numbers. So we fixup the result // for negative numbers if((style & NumberStyles.AllowHexSpecifier) != 0) { // We are parsing a hexadecimal number if((i < 0) || i > UInt16.MaxValue) { return false; } result = (Int16)i; return true; } if(i < MinValue || i > MaxValue) { return false; } result = (Int16)i; return true; } #region IConvertible public TypeCode GetTypeCode() { return TypeCode.Int16; } /// bool IConvertible.ToBoolean( IFormatProvider provider ) { return Convert.ToBoolean( m_value ); } /// char IConvertible.ToChar( IFormatProvider provider ) { return Convert.ToChar( m_value ); } /// sbyte IConvertible.ToSByte( IFormatProvider provider ) { return Convert.ToSByte( m_value ); } /// byte IConvertible.ToByte( IFormatProvider provider ) { return Convert.ToByte( m_value ); } /// short IConvertible.ToInt16( IFormatProvider provider ) { return m_value; } /// ushort IConvertible.ToUInt16( IFormatProvider provider ) { return Convert.ToUInt16( m_value ); } /// int IConvertible.ToInt32( IFormatProvider provider ) { return Convert.ToInt32( m_value ); } /// uint IConvertible.ToUInt32( IFormatProvider provider ) { return Convert.ToUInt32( m_value ); } /// long IConvertible.ToInt64( IFormatProvider provider ) { return Convert.ToInt64( m_value ); } /// ulong IConvertible.ToUInt64( IFormatProvider provider ) { return Convert.ToUInt64( m_value ); } /// float IConvertible.ToSingle( IFormatProvider provider ) { return Convert.ToSingle( m_value ); } /// double IConvertible.ToDouble( IFormatProvider provider ) { return Convert.ToDouble( m_value ); } /// Decimal IConvertible.ToDecimal( IFormatProvider provider ) { return Convert.ToDecimal( m_value ); } /// DateTime IConvertible.ToDateTime( IFormatProvider provider ) { #if EXCEPTION_STRINGS throw new InvalidCastException( String.Format( CultureInfo.CurrentCulture, Environment.GetResourceString( "InvalidCast_FromTo" ), "Int16", "DateTime" ) ); #else throw new InvalidCastException(); #endif } /// Object IConvertible.ToType( Type type, IFormatProvider provider ) { return Convert.DefaultToType( (IConvertible)this, type, provider ); } #endregion } } ================================================ FILE: Zelig/Zelig/RunTime/Framework/mscorlib/System/Int32.cs ================================================ // ==++== // // Copyright (c) Microsoft Corporation. All rights reserved. // // ==--== /*============================================================ ** ** Class: Int32 ** ** ** Purpose: A representation of a 32 bit 2's complement ** integer. ** ** ===========================================================*/ namespace System { using System; using System.Globalization; using System.Runtime.InteropServices; using System.Runtime.CompilerServices; [Microsoft.Zelig.Internals.WellKnownType( "System_Int32" )] [Serializable] [StructLayout( LayoutKind.Sequential )] public struct Int32 : IComparable, IFormattable, IConvertible, IComparable, IEquatable { public const int MaxValue = 0x7FFFFFFF; public const int MinValue = unchecked( (int)0x80000000 ); internal int m_value; // Compares this object to another object, returning an integer that // indicates the relationship. // Returns a value less than zero if this object // null is considered to be less than any instance. // If object is not of type Int32, this method throws an ArgumentException. // public int CompareTo( Object value ) { if(value == null) { return 1; } if(value is Int32) { return CompareTo( (Int32)value ); } #if EXCEPTION_STRINGS throw new ArgumentException( Environment.GetResourceString( "Arg_MustBeInt32" ) ); #else throw new ArgumentException(); #endif } public int CompareTo( int value ) { // Need to use compare because subtraction will wrap // to positive for very large neg numbers, etc. if(m_value < value) return -1; if(m_value > value) return 1; return 0; } public override bool Equals( Object obj ) { if(!(obj is Int32)) { return false; } return Equals( (Int32)obj ); } public bool Equals( Int32 obj ) { return m_value == obj; } // The absolute value of the int contained. public override int GetHashCode() { return m_value; } public override String ToString() { return Number.FormatInt32( m_value, /*null,*/ NumberFormatInfo.CurrentInfo ); } public String ToString( char formatChar ) { return Number.FormatInt32( m_value, formatChar, NumberFormatInfo.CurrentInfo ); } public String ToString( String format ) { return Number.FormatInt32( m_value, format, NumberFormatInfo.CurrentInfo ); } public String ToString( IFormatProvider provider ) { return Number.FormatInt32( m_value, /*null,*/ NumberFormatInfo.GetInstance( provider ) ); } public String ToString( String format , IFormatProvider provider ) { return Number.FormatInt32( m_value, format, NumberFormatInfo.GetInstance( provider ) ); } public static int Parse( String s ) { return Number.ParseInt32( s, NumberStyles.Integer, NumberFormatInfo.CurrentInfo ); } public static int Parse( String s , NumberStyles style ) { NumberFormatInfo.ValidateParseStyleInteger( style ); return Number.ParseInt32( s, style, NumberFormatInfo.CurrentInfo ); } // Parses an integer from a String in the given style. If // a NumberFormatInfo isn't specified, the current culture's // NumberFormatInfo is assumed. // public static int Parse( String s , IFormatProvider provider ) { return Number.ParseInt32( s, NumberStyles.Integer, NumberFormatInfo.GetInstance( provider ) ); } // Parses an integer from a String in the given style. If // a NumberFormatInfo isn't specified, the current culture's // NumberFormatInfo is assumed. // public static int Parse( String s , NumberStyles style , IFormatProvider provider ) { NumberFormatInfo.ValidateParseStyleInteger( style ); return Number.ParseInt32( s, style, NumberFormatInfo.GetInstance( provider ) ); } // Parses an integer from a String. Returns false rather // than throwing exceptin if input is invalid // public static bool TryParse( String s , out Int32 result ) { return Number.TryParseInt32( s, NumberStyles.Integer, NumberFormatInfo.CurrentInfo, out result ); } // Parses an integer from a String in the given style. Returns false rather // than throwing exceptin if input is invalid // public static bool TryParse( String s , NumberStyles style , IFormatProvider provider , out Int32 result ) { NumberFormatInfo.ValidateParseStyleInteger( style ); return Number.TryParseInt32( s, style, NumberFormatInfo.GetInstance( provider ), out result ); } #region IConvertible public TypeCode GetTypeCode() { return TypeCode.Int32; } /// bool IConvertible.ToBoolean( IFormatProvider provider ) { return Convert.ToBoolean( m_value ); } /// char IConvertible.ToChar( IFormatProvider provider ) { return Convert.ToChar( m_value ); } /// sbyte IConvertible.ToSByte( IFormatProvider provider ) { return Convert.ToSByte( m_value ); } /// byte IConvertible.ToByte( IFormatProvider provider ) { return Convert.ToByte( m_value ); } /// short IConvertible.ToInt16( IFormatProvider provider ) { return Convert.ToInt16( m_value ); } /// ushort IConvertible.ToUInt16( IFormatProvider provider ) { return Convert.ToUInt16( m_value ); } /// int IConvertible.ToInt32( IFormatProvider provider ) { return m_value; } /// uint IConvertible.ToUInt32( IFormatProvider provider ) { return Convert.ToUInt32( m_value ); } /// long IConvertible.ToInt64( IFormatProvider provider ) { return Convert.ToInt64( m_value ); } /// ulong IConvertible.ToUInt64( IFormatProvider provider ) { return Convert.ToUInt64( m_value ); } /// float IConvertible.ToSingle( IFormatProvider provider ) { return Convert.ToSingle( m_value ); } /// double IConvertible.ToDouble( IFormatProvider provider ) { return Convert.ToDouble( m_value ); } /// Decimal IConvertible.ToDecimal( IFormatProvider provider ) { return Convert.ToDecimal( m_value ); } /// DateTime IConvertible.ToDateTime( IFormatProvider provider ) { #if EXCEPTION_STRINGS throw new InvalidCastException( String.Format( CultureInfo.CurrentCulture, Environment.GetResourceString( "InvalidCast_FromTo" ), "Int32", "DateTime" ) ); #else throw new InvalidCastException(); #endif } /// Object IConvertible.ToType( Type type, IFormatProvider provider ) { return Convert.DefaultToType( (IConvertible)this, type, provider ); } #endregion } } ================================================ FILE: Zelig/Zelig/RunTime/Framework/mscorlib/System/Int64.cs ================================================ // ==++== // // Copyright (c) Microsoft Corporation. All rights reserved. // // ==--== /*============================================================ ** ** Class: Int64.cs ** ** ** Purpose: This class will encapsulate a long and provide an ** Object representation of it. ** ** ===========================================================*/ namespace System { using System; using System.Globalization; using System.Runtime.InteropServices; using System.Runtime.CompilerServices; [Microsoft.Zelig.Internals.WellKnownType( "System_Int64" )] [Serializable] [StructLayout( LayoutKind.Sequential )] public struct Int64 : IComparable, IFormattable, IConvertible, IComparable, IEquatable { public const long MaxValue = 0x7FFFFFFFFFFFFFFFL; public const long MinValue = unchecked( (long)0x8000000000000000L ); internal long m_value; // Compares this object to another object, returning an integer that // indicates the relationship. // Returns a value less than zero if this object // null is considered to be less than any instance. // If object is not of type Int64, this method throws an ArgumentException. // public int CompareTo( Object value ) { if(value == null) { return 1; } if(value is Int64) { return CompareTo( (Int64)value ); } #if EXCEPTION_STRINGS throw new ArgumentException( Environment.GetResourceString( "Arg_MustBeInt64" ) ); #else throw new ArgumentException(); #endif } public int CompareTo( Int64 value ) { // Need to use compare because subtraction will wrap // to positive for very large neg numbers, etc. if(m_value < value) return -1; if(m_value > value) return 1; return 0; } public override bool Equals( Object obj ) { if(!(obj is Int64)) { return false; } return Equals( (Int64)obj ); } public bool Equals( Int64 obj ) { return m_value == obj; } // The value of the lower 32 bits XORed with the uppper 32 bits. public override int GetHashCode() { return (unchecked( (int)((long)m_value) ) ^ (int)(m_value >> 32)); } public override String ToString() { return Number.FormatInt64( m_value, /*null,*/ NumberFormatInfo.CurrentInfo ); } public String ToString( IFormatProvider provider ) { return Number.FormatInt64( m_value, /*null,*/ NumberFormatInfo.GetInstance( provider ) ); } public String ToString( String format ) { return Number.FormatInt64( m_value, format, NumberFormatInfo.CurrentInfo ); } public String ToString( String format , IFormatProvider provider ) { return Number.FormatInt64( m_value, format, NumberFormatInfo.GetInstance( provider ) ); } public static long Parse( String s ) { return Number.ParseInt64( s, NumberStyles.Integer, NumberFormatInfo.CurrentInfo ); } public static long Parse( String s , NumberStyles style ) { NumberFormatInfo.ValidateParseStyleInteger( style ); return Number.ParseInt64( s, style, NumberFormatInfo.CurrentInfo ); } public static long Parse( String s , IFormatProvider provider ) { return Number.ParseInt64( s, NumberStyles.Integer, NumberFormatInfo.GetInstance( provider ) ); } // Parses a long from a String in the given style. If // a NumberFormatInfo isn't specified, the current culture's // NumberFormatInfo is assumed. // public static long Parse( String s , NumberStyles style , IFormatProvider provider ) { NumberFormatInfo.ValidateParseStyleInteger( style ); return Number.ParseInt64( s, style, NumberFormatInfo.GetInstance( provider ) ); } public static Boolean TryParse( String s , out Int64 result ) { return Number.TryParseInt64( s, NumberStyles.Integer, NumberFormatInfo.CurrentInfo, out result ); } public static Boolean TryParse( String s , NumberStyles style , IFormatProvider provider , out Int64 result ) { NumberFormatInfo.ValidateParseStyleInteger( style ); return Number.TryParseInt64( s, style, NumberFormatInfo.GetInstance( provider ), out result ); } #region IConvertible public TypeCode GetTypeCode() { return TypeCode.Int64; } /// bool IConvertible.ToBoolean( IFormatProvider provider ) { return Convert.ToBoolean( m_value ); } /// char IConvertible.ToChar( IFormatProvider provider ) { return Convert.ToChar( m_value ); } /// sbyte IConvertible.ToSByte( IFormatProvider provider ) { return Convert.ToSByte( m_value ); } /// byte IConvertible.ToByte( IFormatProvider provider ) { return Convert.ToByte( m_value ); } /// short IConvertible.ToInt16( IFormatProvider provider ) { return Convert.ToInt16( m_value ); } /// ushort IConvertible.ToUInt16( IFormatProvider provider ) { return Convert.ToUInt16( m_value ); } /// int IConvertible.ToInt32( IFormatProvider provider ) { return Convert.ToInt32( m_value ); } /// uint IConvertible.ToUInt32( IFormatProvider provider ) { return Convert.ToUInt32( m_value ); } /// long IConvertible.ToInt64( IFormatProvider provider ) { return m_value; } /// ulong IConvertible.ToUInt64( IFormatProvider provider ) { return Convert.ToUInt64( m_value ); } /// float IConvertible.ToSingle( IFormatProvider provider ) { return Convert.ToSingle( m_value ); } /// double IConvertible.ToDouble( IFormatProvider provider ) { return Convert.ToDouble( m_value ); } /// Decimal IConvertible.ToDecimal( IFormatProvider provider ) { return Convert.ToDecimal( m_value ); } /// DateTime IConvertible.ToDateTime( IFormatProvider provider ) { #if EXCEPTION_STRINGS throw new InvalidCastException( String.Format( CultureInfo.CurrentCulture, Environment.GetResourceString( "InvalidCast_FromTo" ), "Int64", "DateTime" ) ); #else throw new InvalidCastException(); #endif } /// Object IConvertible.ToType( Type type, IFormatProvider provider ) { return Convert.DefaultToType( (IConvertible)this, type, provider ); } #endregion } } ================================================ FILE: Zelig/Zelig/RunTime/Framework/mscorlib/System/IntPtr.cs ================================================ // ==++== // // Copyright (c) Microsoft Corporation. All rights reserved. // // ==--== /*============================================================ ** ** Class: IntPtr ** ** ** Purpose: Platform independent integer ** ** ===========================================================*/ namespace System { using System; using System.Globalization; using System.Runtime.Serialization; using System.Runtime.CompilerServices; using System.Runtime.ConstrainedExecution; [Microsoft.Zelig.Internals.WellKnownType( "System_IntPtr" )] [Serializable] public struct IntPtr /*: ISerializable*/ { public static readonly IntPtr Zero; unsafe private void* m_value; // The compiler treats void* closest to uint hence explicit casts are required to preserve int behavior // fast way to compare IntPtr to (IntPtr)0 while IntPtr.Zero doesn't work due to slow statics access //// [ReliabilityContract( Consistency.WillNotCorruptState, Cer.Success )] internal unsafe bool IsNull() { return (this.m_value == null); } //// [ReliabilityContract( Consistency.MayCorruptInstance, Cer.MayFail )] public unsafe IntPtr( int value ) { m_value = (void *)value; } public unsafe IntPtr( long value ) { m_value = (void *)checked((int)value); } [CLSCompliant( false )] //// [ReliabilityContract( Consistency.MayCorruptInstance, Cer.MayFail )] public unsafe IntPtr( void* value ) { m_value = value; } //// private unsafe IntPtr( SerializationInfo info, StreamingContext context ) //// { //// long l = info.GetInt64( "value" ); //// //// if((l > Int32.MaxValue || l < Int32.MinValue)) //// { //// throw new ArgumentException( Environment.GetResourceString( "Serialization_InvalidPtrValue" ) ); //// } //// //// m_value = (void*)l; //// } //// //// unsafe void ISerializable.GetObjectData( SerializationInfo info, StreamingContext context ) //// { //// if(info == null) //// { //// throw new ArgumentNullException( "info" ); //// } //// //// info.AddValue( "value", (long)((int)m_value) ); //// } public unsafe override bool Equals( Object obj ) { if(obj is IntPtr) { return (m_value == ((IntPtr)obj).m_value); } return false; } public unsafe override int GetHashCode() { return unchecked( (int)((long)m_value) ); } //// [ReliabilityContract( Consistency.WillNotCorruptState, Cer.Success )] public unsafe int ToInt32() { return (int)m_value; } public unsafe long ToInt64() { return (long)(int)m_value; } //// public unsafe override String ToString() //// { //// return ((int)m_value).ToString( CultureInfo.InvariantCulture ); //// } //// //// public unsafe String ToString( String format ) //// { //// return ((int)m_value).ToString( format, CultureInfo.InvariantCulture ); //// } //// [ReliabilityContract( Consistency.MayCorruptInstance, Cer.MayFail )] public static explicit operator IntPtr( int value ) { return new IntPtr( value ); } public static explicit operator IntPtr( long value ) { return new IntPtr( value ); } [CLSCompliant( false )] //// [ReliabilityContract( Consistency.MayCorruptInstance, Cer.MayFail )] public static unsafe explicit operator IntPtr( void* value ) { return new IntPtr( value ); } [CLSCompliant( false )] public static unsafe explicit operator void*( IntPtr value ) { return value.ToPointer(); } public unsafe static explicit operator int( IntPtr value ) { return (int)value.m_value; } public unsafe static explicit operator long( IntPtr value ) { return (long)(int)value.m_value; } //// [ReliabilityContract( Consistency.WillNotCorruptState, Cer.Success )] public unsafe static bool operator ==( IntPtr value1, IntPtr value2 ) { return value1.m_value == value2.m_value; } //// [ReliabilityContract( Consistency.WillNotCorruptState, Cer.Success )] public unsafe static bool operator !=( IntPtr value1, IntPtr value2 ) { return value1.m_value != value2.m_value; } public static int Size { //// [ReliabilityContract( Consistency.WillNotCorruptState, Cer.Success )] get { return 4; } } [CLSCompliant( false )] //// [ReliabilityContract( Consistency.WillNotCorruptState, Cer.Success )] public unsafe void* ToPointer() { return m_value; } } } ================================================ FILE: Zelig/Zelig/RunTime/Framework/mscorlib/System/InvalidCastException.cs ================================================ // ==++== // // Copyright (c) Microsoft Corporation. All rights reserved. // // ==--== /*============================================================================= ** ** Class: InvalidCastException ** ** ** Purpose: Exception class for bad cast conditions! ** ** =============================================================================*/ namespace System { using System; using System.Runtime.Serialization; [Serializable] public class InvalidCastException : SystemException { #if EXCEPTION_STRINGS public InvalidCastException() : base( Environment.GetResourceString( "Arg_InvalidCastException" ) ) #else public InvalidCastException() #endif { } public InvalidCastException( String message ) : base( message ) { } public InvalidCastException( String message, Exception innerException ) : base( message, innerException ) { } //// protected InvalidCastException( SerializationInfo info, StreamingContext context ) : base( info, context ) //// { //// } //// public InvalidCastException( String message, int errorCode ) : base( message ) { } } } ================================================ FILE: Zelig/Zelig/RunTime/Framework/mscorlib/System/InvalidOperationException.cs ================================================ // ==++== // // Copyright (c) Microsoft Corporation. All rights reserved. // // ==--== /*============================================================================= ** ** Class: InvalidOperationException ** ** ** Purpose: Exception class for denoting an object was in a state that ** made calling a method illegal. ** ** =============================================================================*/ namespace System { using System; using System.Runtime.Serialization; [Serializable] public class InvalidOperationException : SystemException { #if EXCEPTION_STRINGS public InvalidOperationException() : base( Environment.GetResourceString( "Arg_InvalidOperationException" ) ) #else public InvalidOperationException() #endif { } public InvalidOperationException( String message ) : base( message ) { } public InvalidOperationException( String message, Exception innerException ) : base( message, innerException ) { } //// //// protected InvalidOperationException( SerializationInfo info, StreamingContext context ) : base( info, context ) //// { //// } } } ================================================ FILE: Zelig/Zelig/RunTime/Framework/mscorlib/System/InvalidProgramException.cs ================================================ // ==++== // // Copyright (c) Microsoft Corporation. All rights reserved. // // ==--== /*============================================================================= ** ** Class: InvalidProgramException ** ** ** Purpose: The exception class for programs with invalid IL or bad metadata. ** ** =============================================================================*/ namespace System { using System; using System.Runtime.Serialization; [Serializable] public sealed class InvalidProgramException : SystemException { public InvalidProgramException() : base( Environment.GetResourceString( "InvalidProgram_Default" ) ) { //// SetErrorCode( __HResults.COR_E_INVALIDPROGRAM ); } public InvalidProgramException( String message ) : base( message ) { //// SetErrorCode( __HResults.COR_E_INVALIDPROGRAM ); } public InvalidProgramException( String message, Exception inner ) : base( message, inner ) { //// SetErrorCode( __HResults.COR_E_INVALIDPROGRAM ); } //// internal InvalidProgramException( SerializationInfo info , //// StreamingContext context ) : base( info, context ) //// { //// } } } ================================================ FILE: Zelig/Zelig/RunTime/Framework/mscorlib/System/MarshalByRefObject.cs ================================================ // ==++== // // Copyright (c) Microsoft Corporation. All rights reserved. // // ==--== /*============================================================ ** ** File: MarshalByRefObject.cs ** ** ** ** Purpose: Defines the root type for all marshal by reference aka ** AppDomain bound types ** ** ** ===========================================================*/ namespace System { using System; ////using System.Security; ////using System.Security.Permissions; using System.Threading; ////using System.Runtime.Remoting; ////using System.Runtime.Remoting.Lifetime; ////using System.Runtime.Remoting.Services; using System.Runtime.InteropServices; using System.Reflection; using System.Runtime.CompilerServices; ////using System.Runtime.Versioning; using CultureInfo = System.Globalization.CultureInfo; [Serializable] public abstract class MarshalByRefObject { //// private Object m_identity; //// //// private Object Identity //// { //// get //// { //// return m_identity; //// } //// //// set //// { //// m_identity = value; //// } //// } //// //// // (1) for remote COM objects IsInstance of can't be executed on //// // the proxies, so we need this method to be executed on the //// // actual object. //// // (2) for remote objects that do not have the complete type information //// // we intercept calls to check the type and execute it on the actual //// // object //// internal bool IsInstanceOfType( Type T ) //// { //// return T.IsInstanceOfType( this ); //// } //// //// // Returns a new cloned MBR instance that is a memberwise copy of this //// // with the identity nulled out, so there are no identity conflicts //// // when the cloned object is marshalled //// protected MarshalByRefObject MemberwiseClone( bool cloneIdentity ) //// { //// MarshalByRefObject mbr = (MarshalByRefObject)base.MemberwiseClone(); //// // set the identity on the cloned object to null //// if(!cloneIdentity) //// { //// mbr.Identity = null; //// } //// //// return mbr; //// } //// //// // A helper routine to extract the identity either from the marshalbyrefobject base //// // class if it is not a proxy, otherwise from the real proxy. //// // A flag is set to indicate whether the object passed in is a server or a proxy //// internal static Identity GetIdentity( MarshalByRefObject obj, out bool fServer ) //// { //// fServer = true; //// //// Identity id = null; //// //// if(obj != null) //// { //// if(!RemotingServices.IsTransparentProxy( obj )) //// { //// id = (Identity)obj.Identity; //// } //// else //// { //// // Toggle flag to indicate that we have a proxy //// fServer = false; //// //// id = RemotingServices.GetRealProxy( obj ).IdentityObject; //// } //// } //// //// return id; //// } //// //// // Another helper that delegates to the helper above //// internal static Identity GetIdentity( MarshalByRefObject obj ) //// { //// BCLDebug.Assert( !RemotingServices.IsTransparentProxy( obj ), "Use this method for server objects only" ); //// //// bool fServer; //// //// return GetIdentity( obj, out fServer ); //// } //// //// internal ServerIdentity __RaceSetServerIdentity( ServerIdentity id ) //// { //// if(m_identity == null) //// { //// // For strictly MBR types, the TP field in the identity //// // holds the real server //// if(!id.IsContextBound) //// { //// id.RaceSetTransparentProxy( this ); //// } //// //// Interlocked.CompareExchange( ref m_identity, id, null ); //// } //// //// return (ServerIdentity)m_identity; //// } //// //// //// internal void __ResetServerIdentity() //// { //// m_identity = null; //// } //// //// // This method is used return a lifetime service object which //// // is used to control the lifetime policy to the object. //// // For the default Lifetime service this will be an object of typoe ILease. //// // //// [SecurityPermissionAttribute( SecurityAction.LinkDemand, Flags = SecurityPermissionFlag.Infrastructure )] //// public Object GetLifetimeService() //// { //// return LifetimeServices.GetLease( this ); //// } //// //// // This method is used return lifetime service object. This method //// // can be overridden to return a LifetimeService object with properties unique to //// // this object. //// // For the default Lifetime service this will be an object of type ILease. //// // //// [SecurityPermissionAttribute( SecurityAction.LinkDemand, Flags = SecurityPermissionFlag.Infrastructure )] //// public virtual Object InitializeLifetimeService() //// { //// return LifetimeServices.GetLeaseInitial( this ); //// } //// //// [SecurityPermissionAttribute( SecurityAction.LinkDemand, Flags = SecurityPermissionFlag.Infrastructure )] //// public virtual ObjRef CreateObjRef( Type requestedType ) //// { //// if(m_identity == null) //// { //// throw new RemotingException( Environment.GetResourceString( "Remoting_NoIdentityEntry" ) ); //// } //// //// return new ObjRef( this, requestedType ); //// } //// //// //// // This is for casting interop ObjRefLite's. //// // ObjRefLite's have been deprecated. These methods are not exposed //// // through any user APIs and would be removed in the future //// internal bool CanCastToXmlType( String xmlTypeName, String xmlTypeNamespace ) //// { //// Type castType = SoapServices.GetInteropTypeFromXmlType( xmlTypeName, xmlTypeNamespace ); //// //// if(castType == null) //// { //// String typeNamespace; //// String assemblyName; //// //// if(!SoapServices.DecodeXmlNamespaceForClrTypeNamespace( xmlTypeNamespace, out typeNamespace, out assemblyName )) //// { //// return false; //// } //// //// String typeName; //// //// if((typeNamespace != null) && (typeNamespace.Length > 0)) //// { //// typeName = typeNamespace + "." + xmlTypeName; //// } //// else //// { //// typeName = xmlTypeName; //// } //// //// try //// { //// Assembly asm = Assembly.Load( assemblyName ); //// //// castType = asm.GetType( typeName, false, false ); //// } //// catch //// { //// return false; //// } //// } //// //// if(castType != null) //// { //// return castType.IsAssignableFrom( this.GetType() ); //// } //// //// return false; //// } // CanCastToXmlType //// //// // helper method for calling CanCastToXmlType //// // ObjRefLite's have been deprecated. These methods are not exposed //// // through any user APIs and would be removed in the future //// internal static bool CanCastToXmlTypeHelper( Type castType, MarshalByRefObject o ) //// { //// if(castType == null) //// { //// throw new ArgumentNullException( "castType" ); //// } //// //// // MarshalByRefObject's can only be casted to MarshalByRefObject's or interfaces. //// if(!castType.IsInterface && !castType.IsMarshalByRef) //// { //// return false; //// } //// //// // figure out xml type name //// String xmlTypeName = null; //// String xmlTypeNamespace = null; //// //// if(!SoapServices.GetXmlTypeForInteropType( castType, out xmlTypeName, out xmlTypeNamespace )) //// { //// // There's no registered interop type name, so just use the default. //// xmlTypeName = castType.Name; //// xmlTypeNamespace = SoapServices.CodeXmlNamespaceForClrTypeNamespace( castType.Namespace, castType.Module.Assembly.GetSimpleName() ); //// } //// //// return o.CanCastToXmlType( xmlTypeName, xmlTypeNamespace ); //// } // CanCastToXmlType } } // namespace ================================================ FILE: Zelig/Zelig/RunTime/Framework/mscorlib/System/Math.cs ================================================ // ==++== // // Copyright (c) Microsoft Corporation. All rights reserved. // // ==--== /*============================================================ ** ** Class: Math ** ** ** Purpose: Some floating-point math operations ** ** ===========================================================*/ namespace System { //This class contains only static members and doesn't require serialization. using System; using System.Runtime.CompilerServices; using System.Runtime.ConstrainedExecution; ////using System.Runtime.Versioning; public static class Math { //// private static double doubleRoundLimit = 1E16d; //// //// private const int maxRoundingDigits = 15; //// //// // This table is required for the Round function which can specify the number of digits to round to //// private static double[] roundPower10Double = new double[] //// { //// 1E0, 1E1, 1E2, 1E3, 1E4, 1E5, 1E6, 1E7, 1E8, //// 1E9, 1E10, 1E11, 1E12, 1E13, 1E14, 1E15 //// }; public const double PI = 3.14159265358979323846; public const double E = 2.7182818284590452354; //// [ResourceExposure( ResourceScope.None )] //// [MethodImpl( MethodImplOptions.InternalCall )] //// public static extern double Acos( double d ); //// //// [ResourceExposure( ResourceScope.None )] //// [MethodImpl( MethodImplOptions.InternalCall )] //// public static extern double Asin( double d ); //// //// [ResourceExposure( ResourceScope.None )] [MethodImpl( MethodImplOptions.InternalCall )] public static extern double Atan( double d ); //// //// [ResourceExposure( ResourceScope.None )] //// [MethodImpl( MethodImplOptions.InternalCall )] //// public static extern double Atan2( double y, double x ); //// //// public static Decimal Ceiling( Decimal d ) //// { //// return Decimal.Ceiling( d ); //// } //// [ResourceExposure( ResourceScope.None )] [MethodImpl( MethodImplOptions.InternalCall )] public static extern double Ceiling( double a ); //// [ResourceExposure( ResourceScope.None )] [MethodImpl( MethodImplOptions.InternalCall )] public extern static double Cos( double d ); //// [ResourceExposure( ResourceScope.None )] //// [MethodImpl( MethodImplOptions.InternalCall )] //// public static extern double Cosh( double value ); //// //// public static Decimal Floor( Decimal d ) //// { //// return Decimal.Floor( d ); //// } //// [ResourceExposure( ResourceScope.None )] [MethodImpl( MethodImplOptions.InternalCall )] public static extern double Floor( double d ); //// private static unsafe double InternalRound( double value, int digits, MidpointRounding mode ) //// { //// if(Abs( value ) < doubleRoundLimit) //// { //// Double power10 = roundPower10Double[digits]; //// //// value *= power10; //// //// if(mode == MidpointRounding.AwayFromZero) //// { //// double fraction = SplitFractionDouble( &value ); //// if(Abs( fraction ) >= 0.5d) //// { //// value += Sign( fraction ); //// } //// } //// else //// { //// // On X86 this can be inlined to just a few instructions //// value = Round( value ); //// } //// //// value /= power10; //// } //// //// return value; //// } //// //// private unsafe static double InternalTruncate( double d ) //// { //// SplitFractionDouble( &d ); //// //// return d; //// } //// //// [ResourceExposure( ResourceScope.None )] [MethodImpl( MethodImplOptions.InternalCall )] public static extern double Sin( double a ); //// [ResourceExposure( ResourceScope.None )] //// [MethodImpl( MethodImplOptions.InternalCall )] //// public static extern double Tan( double a ); //// //// [ResourceExposure( ResourceScope.None )] //// [MethodImpl( MethodImplOptions.InternalCall )] //// public static extern double Sinh( double value ); //// //// [ResourceExposure( ResourceScope.None )] //// [MethodImpl( MethodImplOptions.InternalCall )] //// public static extern double Tanh( double value ); //// [ResourceExposure( ResourceScope.None )] [MethodImpl( MethodImplOptions.InternalCall )] public static extern double Round( double a ); //// public static double Round( double value, int digits ) //// { //// if((digits < 0) || (digits > maxRoundingDigits)) //// { //// throw new ArgumentOutOfRangeException( "digits", Environment.GetResourceString( "ArgumentOutOfRange_RoundingDigits" ) ); //// } //// //// return InternalRound( value, digits, MidpointRounding.ToEven ); //// } //// //// public static double Round( double value, MidpointRounding mode ) //// { //// return Round( value, 0, mode ); //// } //// //// public static double Round( double value, int digits, MidpointRounding mode ) //// { //// if((digits < 0) || (digits > maxRoundingDigits)) //// { //// throw new ArgumentOutOfRangeException( "digits", Environment.GetResourceString( "ArgumentOutOfRange_RoundingDigits" ) ); //// } //// //// if(mode < MidpointRounding.ToEven || mode > MidpointRounding.AwayFromZero) //// { //// throw new ArgumentException( Environment.GetResourceString( "Argument_InvalidEnumValue", mode, "MidpointRounding" ), "mode" ); //// } //// //// return InternalRound( value, digits, mode ); //// } //// //// public static Decimal Round( Decimal d ) //// { //// return Decimal.Round( d, 0 ); //// } //// //// public static Decimal Round( Decimal d, int decimals ) //// { //// return Decimal.Round( d, decimals ); //// } //// //// public static Decimal Round( Decimal d, MidpointRounding mode ) //// { //// return Decimal.Round( d, 0, mode ); //// } //// //// public static Decimal Round( Decimal d, int decimals, MidpointRounding mode ) //// { //// return Decimal.Round( d, decimals, mode ); //// } //// //// [ResourceExposure( ResourceScope.None )] //// [MethodImpl( MethodImplOptions.InternalCall )] //// private static unsafe extern double SplitFractionDouble( double* value ); //// //// public static Decimal Truncate( Decimal d ) //// { //// return Decimal.Truncate( d ); //// } //// //// public static double Truncate( double d ) //// { //// return InternalTruncate( d ); //// } //// //// [ResourceExposure( ResourceScope.None )] //// [ReliabilityContract( Consistency.WillNotCorruptState, Cer.Success )] [MethodImpl( MethodImplOptions.InternalCall )] public static extern double Sqrt( double d ); //// [ResourceExposure( ResourceScope.None )] [MethodImpl( MethodImplOptions.InternalCall )] public static extern double Log( double d ); //// [ResourceExposure( ResourceScope.None )] [MethodImpl( MethodImplOptions.InternalCall )] public static extern double Log10( double d ); //// [ResourceExposure( ResourceScope.None )] [MethodImpl( MethodImplOptions.InternalCall )] public static extern double Exp( double d ); //// [ResourceExposure( ResourceScope.None )] [MethodImpl( MethodImplOptions.InternalCall )] public static extern double Pow( double x, double y ); //// public static double IEEERemainder( double x, double y ) //// { //// double regularMod = x % y; //// if(Double.IsNaN( regularMod )) //// { //// return Double.NaN; //// } //// //// if(regularMod == 0) //// { //// if(Double.IsNegative( x )) //// { //// return Double.NegativeZero; //// } //// } //// //// double alternativeResult = regularMod - (Math.Abs( y ) * Math.Sign( x )); //// if(Math.Abs( alternativeResult ) == Math.Abs( regularMod )) //// { //// double divisionResult = x / y; //// double roundedResult = Math.Round( divisionResult ); //// if(Math.Abs( roundedResult ) > Math.Abs( divisionResult )) //// { //// return alternativeResult; //// } //// else //// { //// return regularMod; //// } //// } //// //// if(Math.Abs( alternativeResult ) < Math.Abs( regularMod )) //// { //// return alternativeResult; //// } //// else //// { //// return regularMod; //// } //// } /*================================Abs========================================= **Returns the absolute value of it's argument. ============================================================================*/ [CLSCompliant( false )] public static sbyte Abs( sbyte value ) { if(value >= 0) { return value; } else { return AbsHelper( value ); } } private static sbyte AbsHelper( sbyte value ) { //// BCLDebug.Assert( value < 0, "AbsHelper should only be called for negative values! (hack for JIT inlining)" ); //// if(value == SByte.MinValue) //// { //// throw new OverflowException( Environment.GetResourceString( "Overflow_NegateTwosCompNum" ) ); //// } return ((sbyte)(-value)); } public static short Abs( short value ) { if(value >= 0) { return value; } else { return AbsHelper( value ); } } private static short AbsHelper( short value ) { //// BCLDebug.Assert( value < 0, "AbsHelper should only be called for negative values! (hack for JIT inlining)" ); //// if(value == Int16.MinValue) //// { //// throw new OverflowException( Environment.GetResourceString( "Overflow_NegateTwosCompNum" ) ); //// } return (short)-value; } public static int Abs( int value ) { if(value >= 0) { return value; } else { return AbsHelper( value ); } } private static int AbsHelper( int value ) { //// BCLDebug.Assert( value < 0, "AbsHelper should only be called for negative values! (hack for JIT inlining)" ); //// //// if(value == Int32.MinValue) //// { //// throw new OverflowException( Environment.GetResourceString( "Overflow_NegateTwosCompNum" ) ); //// } return -value; } public static long Abs( long value ) { if(value >= 0) { return value; } else { return AbsHelper( value ); } } private static long AbsHelper( long value ) { //// BCLDebug.Assert( value < 0, "AbsHelper should only be called for negative values! (hack for JIT inlining)" ); //// if(value == Int64.MinValue) //// { //// throw new OverflowException( Environment.GetResourceString( "Overflow_NegateTwosCompNum" ) ); //// } return -value; } //// [ResourceExposure( ResourceScope.None )] [MethodImpl( MethodImplOptions.InternalCall )] extern public static float Abs( float value ); // This is special code to handle NaN (We need to make sure NaN's aren't // negated). In CSharp, the else clause here should always be taken if // value is NaN, since the normal case is taken if and only if value < 0. // To illustrate this completely, a compiler has translated this into: // "load value; load 0; bge; ret -value ; ret value". // The bge command branches for comparisons with the unordered NaN. So // it runs the else case, which returns +value instead of negating it. // return (value < 0) ? -value : value; //// [ResourceExposure( ResourceScope.None )] [MethodImpl( MethodImplOptions.InternalCall )] extern public static double Abs( double value ); // This is special code to handle NaN (We need to make sure NaN's aren't // negated). In CSharp, the else clause here should always be taken if // value is NaN, since the normal case is taken if and only if value < 0. // To illustrate this completely, a compiler has translated this into: // "load value; load 0; bge; ret -value ; ret value". // The bge command branches for comparisons with the unordered NaN. So // it runs the else case, which returns +value instead of negating it. // return (value < 0) ? -value : value; //// public static Decimal Abs( Decimal value ) //// { //// return Decimal.Abs( value ); //// } /*================================MAX========================================= **Returns the larger of val1 and val2 ============================================================================*/ [CLSCompliant( false )] //// [ReliabilityContract( Consistency.WillNotCorruptState, Cer.Success )] public static sbyte Max( sbyte val1, sbyte val2 ) { return (val1 >= val2) ? val1 : val2; } //// [ReliabilityContract( Consistency.WillNotCorruptState, Cer.Success )] public static byte Max( byte val1, byte val2 ) { return (val1 >= val2) ? val1 : val2; } //// [ReliabilityContract( Consistency.WillNotCorruptState, Cer.Success )] public static short Max( short val1, short val2 ) { return (val1 >= val2) ? val1 : val2; } [CLSCompliant( false )] //// [ReliabilityContract( Consistency.WillNotCorruptState, Cer.Success )] public static ushort Max( ushort val1, ushort val2 ) { return (val1 >= val2) ? val1 : val2; } //// [ReliabilityContract( Consistency.WillNotCorruptState, Cer.Success )] public static int Max( int val1, int val2 ) { return (val1 >= val2) ? val1 : val2; } [CLSCompliant( false )] //// [ReliabilityContract( Consistency.WillNotCorruptState, Cer.Success )] public static uint Max( uint val1, uint val2 ) { return (val1 >= val2) ? val1 : val2; } //// [ReliabilityContract( Consistency.WillNotCorruptState, Cer.Success )] public static long Max( long val1, long val2 ) { return (val1 >= val2) ? val1 : val2; } [CLSCompliant( false )] //// [ReliabilityContract( Consistency.WillNotCorruptState, Cer.Success )] public static ulong Max( ulong val1, ulong val2 ) { return (val1 >= val2) ? val1 : val2; } //// [ReliabilityContract( Consistency.WillNotCorruptState, Cer.Success )] public static float Max( float val1, float val2 ) { if(val1 > val2) { return val1; } //// if(Single.IsNaN( val1 )) //// { //// return val1; //// } return val2; } //// [ReliabilityContract( Consistency.WillNotCorruptState, Cer.Success )] public static double Max( double val1, double val2 ) { if(val1 > val2) { return val1; } //// if(Double.IsNaN( val1 )) //// { //// return val1; //// } return val2; } //// [ReliabilityContract( Consistency.WillNotCorruptState, Cer.Success )] //// public static Decimal Max( Decimal val1, Decimal val2 ) //// { //// return Decimal.Max( val1, val2 ); //// } /*================================MIN========================================= **Returns the smaller of val1 and val2. ============================================================================*/ [CLSCompliant( false )] //// [ReliabilityContract( Consistency.WillNotCorruptState, Cer.Success )] public static sbyte Min( sbyte val1, sbyte val2 ) { return (val1 <= val2) ? val1 : val2; } //// [ReliabilityContract( Consistency.WillNotCorruptState, Cer.Success )] public static byte Min( byte val1, byte val2 ) { return (val1 <= val2) ? val1 : val2; } //// [ReliabilityContract( Consistency.WillNotCorruptState, Cer.Success )] public static short Min( short val1, short val2 ) { return (val1 <= val2) ? val1 : val2; } [CLSCompliant( false )] //// [ReliabilityContract( Consistency.WillNotCorruptState, Cer.Success )] public static ushort Min( ushort val1, ushort val2 ) { return (val1 <= val2) ? val1 : val2; } //// [ReliabilityContract( Consistency.WillNotCorruptState, Cer.Success )] public static int Min( int val1, int val2 ) { return (val1 <= val2) ? val1 : val2; } [CLSCompliant( false )] //// [ReliabilityContract( Consistency.WillNotCorruptState, Cer.Success )] public static uint Min( uint val1, uint val2 ) { return (val1 <= val2) ? val1 : val2; } //// [ReliabilityContract( Consistency.WillNotCorruptState, Cer.Success )] public static long Min( long val1, long val2 ) { return (val1 <= val2) ? val1 : val2; } [CLSCompliant( false )] //// [ReliabilityContract( Consistency.WillNotCorruptState, Cer.Success )] public static ulong Min( ulong val1, ulong val2 ) { return (val1 <= val2) ? val1 : val2; } //// [ReliabilityContract( Consistency.WillNotCorruptState, Cer.Success )] public static float Min( float val1, float val2 ) { if(val1 < val2) { return val1; } //// if(Single.IsNaN( val1 )) //// { //// return val1; //// } return val2; } //// [ReliabilityContract( Consistency.WillNotCorruptState, Cer.Success )] public static double Min( double val1, double val2 ) { if(val1 < val2) { return val1; } //// if(Double.IsNaN( val1 )) //// { //// return val1; //// } return val2; } //// [ReliabilityContract( Consistency.WillNotCorruptState, Cer.Success )] //// public static Decimal Min( Decimal val1, Decimal val2 ) //// { //// return Decimal.Min( val1, val2 ); //// } /*=====================================Log====================================== ** ==============================================================================*/ public static double Log( double a, double newBase ) { if(newBase == 1) { return Double.NaN; } if(a != 1 && (newBase == 0 || Double.IsPositiveInfinity( newBase ))) { return Double.NaN; } return (Log( a ) / Log( newBase )); } // Sign function for VB. Returns -1, 0, or 1 if the sign of the number // is negative, 0, or positive. Throws for floating point NaN's. [CLSCompliant( false )] public static int Sign( sbyte value ) { if(value < 0) { return -1; } else if(value > 0) { return 1; } else { return 0; } } // Sign function for VB. Returns -1, 0, or 1 if the sign of the number // is negative, 0, or positive. Throws for floating point NaN's. public static int Sign( short value ) { if(value < 0) { return -1; } else if(value > 0) { return 1; } else { return 0; } } // Sign function for VB. Returns -1, 0, or 1 if the sign of the number // is negative, 0, or positive. Throws for floating point NaN's. public static int Sign( int value ) { if(value < 0) { return -1; } else if(value > 0) { return 1; } else { return 0; } } public static int Sign( long value ) { if(value < 0) { return -1; } else if(value > 0) { return 1; } else { return 0; } } //// public static int Sign( float value ) //// { //// if(value < 0) //// { //// return -1; //// } //// else if(value > 0) //// { //// return 1; //// } //// else if(value == 0) //// { //// return 0; //// } //// //// throw new ArithmeticException( Environment.GetResourceString( "Arithmetic_NaN" ) ); //// } //// //// public static int Sign( double value ) //// { //// if(value < 0) //// { //// return -1; //// } //// else if(value > 0) //// { //// return 1; //// } //// else if(value == 0) //// { //// return 0; //// } //// //// throw new ArithmeticException( Environment.GetResourceString( "Arithmetic_NaN" ) ); //// } //// //// public static int Sign( Decimal value ) //// { //// if(value < 0) //// { //// return -1; //// } //// else if(value > 0) //// { //// return 1; //// } //// else //// { //// return 0; //// } //// } //// //// public static long BigMul( int a, int b ) //// { //// return ((long)a) * b; //// } //// //// public static int DivRem( int a, int b, out int result ) //// { //// result = a % b; //// return a / b; //// } //// //// public static long DivRem( long a, long b, out long result ) //// { //// result = a % b; //// return a / b; //// } } } ================================================ FILE: Zelig/Zelig/RunTime/Framework/mscorlib/System/MidpointRounding.cs ================================================ // ==++== // // Copyright (c) Microsoft Corporation. All rights reserved. // // ==--== namespace System { public enum MidpointRounding { ToEven = 0, AwayFromZero = 1, } } ================================================ FILE: Zelig/Zelig/RunTime/Framework/mscorlib/System/MulticastDelegate.cs ================================================ // ==++== // // Copyright (c) Microsoft Corporation. All rights reserved. // // ==--== namespace System { using System; using System.Reflection; using System.Runtime.Serialization; using System.Runtime.CompilerServices; [Microsoft.Zelig.Internals.WellKnownType( "System_MulticastDelegate" )] [Serializable] public abstract class MulticastDelegate : Delegate { //// private Object m_invocationList; //// private IntPtr m_invocationCount; //// //// // This constructor is called from the class generated by the //// // compiler generated code (This must match the constructor //// // in Delegate //// protected MulticastDelegate( Object target, String method ) : base( target, method ) //// { //// } //// //// // This constructor is called from a class to generate a //// // delegate based upon a static method name and the Type object //// // for the class defining the method. //// protected MulticastDelegate( Type target, String method ) : base( target, method ) //// { //// } //// //// internal bool IsUnmanagedFunctionPtr() //// { //// return (m_invocationCount == (IntPtr)(-1)); //// } //// //// public override void GetObjectData( SerializationInfo info, StreamingContext context ) //// { //// int targetIndex = 0; //// Object[] invocationList = m_invocationList as Object[]; //// //// if(invocationList == null) //// { //// MethodInfo method = Method; //// //// // if it is a delegate over a DynamicMethod or an unmanaged function pointer, throw //// if(method is System.Reflection.Emit.DynamicMethod || method is System.Reflection.Emit.DynamicMethod.RTDynamicMethod || IsUnmanagedFunctionPtr()) //// { //// throw new SerializationException( Environment.GetResourceString( "Serialization_InvalidDelegateType" ) ); //// } //// //// // We can't deal with secure delegates either. //// if(m_invocationList != null && !m_invocationCount.IsNull()) //// { //// throw new SerializationException( Environment.GetResourceString( "Serialization_InvalidDelegateType" ) ); //// } //// //// DelegateSerializationHolder.GetDelegateSerializationInfo( info, this.GetType(), Target, method, targetIndex ); //// } //// else //// { //// DelegateSerializationHolder.DelegateEntry nextDe = null; //// //// int invocationCount = (int)m_invocationCount; //// for(int i = invocationCount; --i >= 0; ) //// { //// MulticastDelegate d = (MulticastDelegate)invocationList[i]; //// //// MethodInfo method = d.Method; //// if(method is System.Reflection.Emit.DynamicMethod || method is System.Reflection.Emit.DynamicMethod.RTDynamicMethod || IsUnmanagedFunctionPtr()) //// { //// continue; //// } //// //// // We can't deal with secure delegates either. //// if(d.m_invocationList != null && !d.m_invocationCount.IsNull()) //// { //// continue; //// } //// //// DelegateSerializationHolder.DelegateEntry de = DelegateSerializationHolder.GetDelegateSerializationInfo( info, d.GetType(), d.Target, method, targetIndex++ ); //// if(nextDe != null) //// { //// nextDe.Entry = de; //// } //// //// nextDe = de; //// } //// //// // if nothing was serialized it is a delegate over a DynamicMethod, so just throw //// if(nextDe == null) //// { //// throw new SerializationException( Environment.GetResourceString( "Serialization_InvalidDelegateType" ) ); //// } //// } //// } // equals returns true IIF the delegate is not null and has the // same target, method and invocation list as this object [MethodImpl( MethodImplOptions.InternalCall )] public override extern bool Equals( Object obj ); //// { //// if(obj == null || !InternalEqualTypes( this, obj )) //// { //// return false; //// } //// //// MulticastDelegate d = obj as MulticastDelegate; //// if(d == null) //// { //// return false; //// } //// //// if(m_invocationCount != (IntPtr)0) //// { //// // there are 4 kind of delegate kinds that fall into this bucket //// // 1- Multicast (_invocationList is Object[]) //// // 2- Secure (_invocationList is Delegate) //// // 3- Unmanaged FntPtr (_invocationList == null) //// // 4- Open virtual (_invocationCount == MethodDesc of target) //// //// if(m_invocationList == null) //// { //// if(IsUnmanagedFunctionPtr()) //// { //// if(!d.IsUnmanagedFunctionPtr()) //// return false; //// //// if(m_methodPtr != d.m_methodPtr) //// { //// return false; //// } //// //// if(GetUnmanagedCallSite() != d.GetUnmanagedCallSite()) //// { //// return false; //// } //// //// return true; //// } //// //// return base.Equals( obj ); //// } //// else //// { //// if((m_invocationList as Delegate) != null) //// { //// // this is a secure delegate so we need to unwrap and check the inner one //// return m_invocationList.Equals( obj ); //// } //// else //// { //// BCLDebug.Assert( (_invocationList as Object[]) != null, "empty invocation list on multicast delegate" ); //// //// return InvocationListEquals( d ); //// } //// } //// } //// else //// { //// // among the several kind of delegates falling into this bucket one has got a non //// // empty _invocationList (open static with special sig) //// // to be equals we need to check that _invocationList matches (both null is fine) //// // and call the base.Equals() //// if(m_invocationList != null) //// { //// if(!m_invocationList.Equals( d.m_invocationList )) //// { //// return false; //// } //// //// return base.Equals( d ); //// } //// //// // now we know 'this' is not a special one, so we can work out what the other is //// if(d.m_invocationList != null || d.m_invocationCount != (IntPtr)0) //// { //// if((d.m_invocationList as Delegate) != null) //// { //// // this is a secure delegate so we need to unwrap and check the inner one //// return (d.m_invocationList as Delegate).Equals( this ); //// } //// //// return false; //// } //// //// // now we can call on the base //// return base.Equals( d ); //// } //// } [MethodImpl( MethodImplOptions.InternalCall )] public override extern int GetHashCode(); //// { //// if(IsUnmanagedFunctionPtr()) //// { //// return unchecked( (int)((long)this.m_methodPtr) ); //// } //// //// Object[] invocationList = m_invocationList as Object[]; //// if(invocationList == null) //// { //// return base.GetHashCode(); //// } //// else //// { //// int hash = 0; //// for(int i = 0; i < (int)m_invocationCount; i++) //// { //// hash = hash * 33 + invocationList[i].GetHashCode(); //// } //// //// return hash; //// } //// } //// //// //// // Recursive function which will check for equality of the invocation list. //// private bool InvocationListEquals( MulticastDelegate d ) //// { //// BCLDebug.Assert( d != null && (m_invocationList as Object[]) != null, "bogus delegate in multicast list comparison" ); //// //// if(d.m_invocationCount != m_invocationCount) //// { //// return false; //// } //// //// Object[] invocationList = m_invocationList as Object[]; //// int invocationCount = (int)m_invocationCount; //// for(int i = 0; i < invocationCount; i++) //// { //// Delegate dd = (Delegate)invocationList[i]; //// //// Object[] dInvocationList = d.m_invocationList as Object[]; //// if(!dd.Equals( dInvocationList[i] )) //// { //// return false; //// } //// } //// //// return true; //// } //// //// private bool TrySetSlot( Object[] a, int index, Object o ) //// { //// if(a[index] == null && System.Threading.Interlocked.CompareExchange( ref a[index], o, null ) == null) //// { //// return true; //// } //// //// // The slot may be already set because we have added and removed the same method before. //// // Optimize this case, because it's cheaper than copying the array. //// if(a[index] != null) //// { //// MulticastDelegate d = (MulticastDelegate)o; //// MulticastDelegate dd = (MulticastDelegate)a[index]; //// //// if(dd.m_methodPtr == d.m_methodPtr && //// dd.m_target == d.m_target && //// dd.m_methodPtrAux == d.m_methodPtrAux ) //// { //// return true; //// } //// } //// //// return false; //// } //// //// internal MulticastDelegate NewMulticastDelegate( Object[] invocationList, int invocationCount, bool thisIsMultiCastAlready ) //// { //// // First, allocate a new multicast delegate just like this one, i.e. same type as the this object //// MulticastDelegate result = (MulticastDelegate)InternalAllocLike( this ); //// //// // Performance optimization - if this already points to a true multicast delegate, //// // copy _methodPtr and _methodPtrAux fields rather than calling into the EE to get them //// if(thisIsMultiCastAlready) //// { //// result.m_methodPtr = this.m_methodPtr; //// result.m_methodPtrAux = this.m_methodPtrAux; //// } //// else //// { //// result.m_methodPtr = GetMulticastInvoke(); //// result.m_methodPtrAux = GetInvokeMethod(); //// } //// //// result.m_target = result; //// result.m_invocationList = invocationList; //// result.m_invocationCount = (IntPtr)invocationCount; //// //// return result; //// } //// //// internal MulticastDelegate NewMulticastDelegate( Object[] invocationList, int invocationCount ) //// { //// return NewMulticastDelegate( invocationList, invocationCount, false ); //// } //// //// internal void StoreDynamicMethod( MethodInfo dynamicMethod ) //// { //// if(m_invocationCount != (IntPtr)0) //// { //// BCLDebug.Assert( !IsUnmanagedFunctionPtr(), "dynamic method and unmanaged fntptr delegate combined" ); //// // must be a secure one, unwrap and save //// MulticastDelegate d = (MulticastDelegate)m_invocationList; //// d.m_methodBase = dynamicMethod; //// //// } //// else //// { //// m_methodBase = dynamicMethod; //// } //// } //// //// // This method will combine this delegate with the passed delegate to form a new delegate. //// protected override sealed Delegate CombineImpl( Delegate follow ) //// { //// // Verify that the types are the same... //// // Actually, we don't need to do this, because Delegate.Combine already checks this. //// // if (!InternalEqualTypes(this, follow) //// // throw new ArgumentException(Environment.GetResourceString("Arg_DlgtTypeMis")); //// //// MulticastDelegate dFollow = (MulticastDelegate)follow; //// //// Object[] resultList; //// int followCount = 1; //// Object[] followList = dFollow.m_invocationList as Object[]; //// if(followList != null) //// { //// followCount = (int)dFollow.m_invocationCount; //// } //// //// int resultCount; //// Object[] invocationList = m_invocationList as Object[]; //// if(invocationList == null) //// { //// resultCount = 1 + followCount; //// resultList = new Object[resultCount]; //// //// resultList[0] = this; //// if(followList == null) //// { //// resultList[1] = dFollow; //// } //// else //// { //// for(int i = 0; i < followCount; i++) //// { //// resultList[1 + i] = followList[i]; //// } //// } //// //// return NewMulticastDelegate( resultList, resultCount ); //// } //// else //// { //// int invocationCount = (int)m_invocationCount; //// //// resultCount = invocationCount + followCount; //// resultList = null; //// //// if(resultCount <= invocationList.Length) //// { //// resultList = invocationList; //// if(followList == null) //// { //// if(!TrySetSlot( resultList, invocationCount, dFollow )) //// { //// resultList = null; //// } //// } //// else //// { //// for(int i = 0; i < followCount; i++) //// { //// if(!TrySetSlot( resultList, invocationCount + i, followList[i] )) //// { //// resultList = null; //// break; //// } //// } //// } //// } //// //// if(resultList == null) //// { //// int allocCount = invocationList.Length; //// while(allocCount < resultCount) //// { //// allocCount *= 2; //// } //// //// resultList = new Object[allocCount]; //// //// for(int i = 0; i < invocationCount; i++) //// { //// resultList[i] = invocationList[i]; //// } //// //// if(followList == null) //// { //// resultList[invocationCount] = dFollow; //// } //// else //// { //// for(int i = 0; i < followCount; i++) //// { //// resultList[invocationCount + i] = followList[i]; //// } //// } //// } //// return NewMulticastDelegate( resultList, resultCount, true ); //// } //// } //// //// private Object[] DeleteFromInvocationList( Object[] invocationList, int invocationCount, int deleteIndex, int deleteCount ) //// { //// Object[] thisInvocationList = m_invocationList as Object[]; //// //// int allocCount = thisInvocationList.Length; //// while(allocCount / 2 >= invocationCount - deleteCount) //// { //// allocCount /= 2; //// } //// //// Object[] newInvocationList = new Object[allocCount]; //// //// for(int i = 0; i < deleteIndex; i++) //// { //// newInvocationList[i] = invocationList[i]; //// } //// //// for(int i = deleteIndex + deleteCount; i < invocationCount; i++) //// { //// newInvocationList[i - deleteCount] = invocationList[i]; //// } //// //// return newInvocationList; //// } //// //// private bool EqualInvocationLists( Object[] a, Object[] b, int start, int count ) //// { //// for(int i = 0; i < count; i++) //// { //// if(!(a[start + i].Equals( b[i] ))) //// { //// return false; //// } //// } //// //// return true; //// } //// //// // This method currently looks backward on the invocation list //// // for an element that has Delegate based equality with value. (Doesn't //// // look at the invocation list.) If this is found we remove it from //// // this list and return a new delegate. If its not found a copy of the //// // current list is returned. //// protected override sealed Delegate RemoveImpl( Delegate value ) //// { //// // There is a special case were we are removing using a delegate as //// // the value we need to check for this case //// // //// MulticastDelegate v = value as MulticastDelegate; //// //// if(v == null) //// { //// return this; //// } //// //// if(v.m_invocationList as Object[] == null) //// { //// Object[] invocationList = m_invocationList as Object[]; //// if(invocationList == null) //// { //// // they are both not real Multicast //// if(this.Equals( value )) //// return null; //// } //// else //// { //// int invocationCount = (int)m_invocationCount; //// for(int i = invocationCount; --i >= 0; ) //// { //// if(value.Equals( invocationList[i] )) //// { //// if(invocationCount == 2) //// { //// // Special case - only one value left, either at the beginning or the end //// return (Delegate)invocationList[1 - i]; //// } //// else //// { //// Object[] list = DeleteFromInvocationList( invocationList, invocationCount, i, 1 ); //// //// return NewMulticastDelegate( list, invocationCount - 1, true ); //// } //// } //// } //// } //// } //// else //// { //// Object[] invocationList = m_invocationList as Object[]; //// //// if(invocationList != null) //// { //// int invocationCount = (int) m_invocationCount; //// int vInvocationCount = (int)v.m_invocationCount; //// for(int i = invocationCount - vInvocationCount; i >= 0; i--) //// { //// if(EqualInvocationLists( invocationList, v.m_invocationList as Object[], i, vInvocationCount )) //// { //// if(invocationCount - vInvocationCount == 0) //// { //// // Special case - no values left //// return null; //// } //// else if(invocationCount - vInvocationCount == 1) //// { //// // Special case - only one value left, either at the beginning or the end //// return (Delegate)invocationList[i != 0 ? 0 : invocationCount - 1]; //// } //// else //// { //// Object[] list = DeleteFromInvocationList( invocationList, invocationCount, i, vInvocationCount ); //// //// return NewMulticastDelegate( list, invocationCount - vInvocationCount, true ); //// } //// } //// } //// } //// } //// //// return this; //// } //// //// // This method returns the Invocation list of this multicast delegate. //// public override sealed Delegate[] GetInvocationList() //// { //// Delegate[] del; //// Object[] invocationList = m_invocationList as Object[]; //// if(invocationList == null) //// { //// del = new Delegate[1]; //// del[0] = this; //// } //// else //// { //// // Create an array of delegate copies and each //// // element into the array //// int invocationCount = (int)m_invocationCount; //// //// del = new Delegate[invocationCount]; //// //// for(int i = 0; i < invocationCount; i++) //// { //// del[i] = (Delegate)invocationList[i]; //// } //// } //// //// return del; //// } public static bool operator ==( MulticastDelegate d1, MulticastDelegate d2 ) { if((Object)d1 == null) { return (Object)d2 == null; } return d1.Equals( d2 ); } public static bool operator !=( MulticastDelegate d1, MulticastDelegate d2 ) { if((Object)d1 == null) { return (Object)d2 != null; } return !d1.Equals( d2 ); } //// internal override Object GetTarget() //// { //// if(m_invocationCount != (IntPtr)0) //// { //// // _invocationCount != 0 we are in one of these cases: //// // - Multicast -> return the target of the last delegate in the list //// // - Secure delegate -> return the target of the inner delegate //// // - unmanaged function pointer - return null //// // - virtual open delegate - return base.GetTarget() //// if(m_invocationList == null) //// { //// // both open virtual and ftn pointer return null for the target //// return null; //// } //// else //// { //// Object[] invocationList = m_invocationList as Object[]; //// if(invocationList != null) //// { //// int invocationCount = (int)m_invocationCount; //// return ((Delegate)invocationList[invocationCount - 1]).GetTarget(); //// } //// else //// { //// Delegate receiver = m_invocationList as Delegate; //// if(receiver != null) //// return receiver.GetTarget(); //// } //// } //// } //// return base.GetTarget(); //// } //// //// protected override MethodInfo GetMethodImpl() //// { //// if(m_invocationCount != (IntPtr)0 && m_invocationList != null) //// { //// // multicast case //// Object[] invocationList = m_invocationList as Object[]; //// if(invocationList != null) //// { //// int index = (int)m_invocationCount - 1; //// return ((Delegate)invocationList[index]).Method; //// } //// else //// { //// // must be a secure delegate //// return ((MulticastDelegate)m_invocationList).GetMethodImpl(); //// } //// } //// //// return base.GetMethodImpl(); //// } //// //// // this should help inlining //// [System.Diagnostics.DebuggerNonUserCode] //// private void ThrowNullThisInDelegateToInstance() //// { //// throw new ArgumentException( Environment.GetResourceString( "Arg_DlgtNullInst" ) ); //// } //// //// [System.Diagnostics.DebuggerNonUserCode] //// private void CtorClosed( Object target, IntPtr methodPtr ) //// { //// if(target == null) //// { //// ThrowNullThisInDelegateToInstance(); //// } //// //// this.m_target = target; //// this.m_methodPtr = methodPtr; //// } //// //// [System.Diagnostics.DebuggerNonUserCode] //// private void CtorClosedStatic( Object target, IntPtr methodPtr ) //// { //// this.m_target = target; //// this.m_methodPtr = methodPtr; //// } //// //// [System.Diagnostics.DebuggerNonUserCode] //// private void CtorRTClosed( Object target, IntPtr methodPtr ) //// { //// this.m_target = target; //// this.m_methodPtr = AdjustTarget( target, methodPtr ); //// } //// //// [System.Diagnostics.DebuggerNonUserCode] //// private void CtorOpened( Object target, IntPtr methodPtr, IntPtr shuffleThunk ) //// { //// this.m_target = this; //// this.m_methodPtr = shuffleThunk; //// this.m_methodPtrAux = methodPtr; //// } //// //// [System.Diagnostics.DebuggerNonUserCode] //// private void CtorSecureClosed( Object target, IntPtr methodPtr, IntPtr callThunk, IntPtr assembly ) //// { //// MulticastDelegate realDelegate = (MulticastDelegate)Delegate.InternalAlloc( Type.GetTypeHandle( this ) ); //// //// realDelegate.CtorClosed( target, methodPtr ); //// //// this.m_invocationList = realDelegate; //// this.m_target = this; //// this.m_methodPtr = callThunk; //// this.m_methodPtrAux = assembly; //// this.m_invocationCount = GetInvokeMethod(); //// } //// //// [System.Diagnostics.DebuggerNonUserCode] //// private void CtorSecureClosedStatic( Object target, IntPtr methodPtr, IntPtr callThunk, IntPtr assembly ) //// { //// MulticastDelegate realDelegate = (MulticastDelegate)Delegate.InternalAlloc( Type.GetTypeHandle( this ) ); //// //// realDelegate.CtorClosedStatic( target, methodPtr ); //// //// this.m_invocationList = realDelegate; //// this.m_target = this; //// this.m_methodPtr = callThunk; //// this.m_methodPtrAux = assembly; //// this.m_invocationCount = GetInvokeMethod(); //// } //// //// [System.Diagnostics.DebuggerNonUserCode] //// private void CtorSecureRTClosed( Object target, IntPtr methodPtr, IntPtr callThunk, IntPtr assembly ) //// { //// MulticastDelegate realDelegate = Delegate.InternalAlloc( Type.GetTypeHandle( this ) ); //// //// realDelegate.CtorRTClosed( target, methodPtr ); //// //// this.m_invocationList = realDelegate; //// this.m_target = this; //// this.m_methodPtr = callThunk; //// this.m_methodPtrAux = assembly; //// this.m_invocationCount = GetInvokeMethod(); //// } //// //// [System.Diagnostics.DebuggerNonUserCode] //// private void CtorSecureOpened( Object target, IntPtr methodPtr, IntPtr shuffleThunk, IntPtr callThunk, IntPtr assembly ) //// { //// MulticastDelegate realDelegate = Delegate.InternalAlloc( Type.GetTypeHandle( this ) ); //// //// realDelegate.CtorOpened( target, methodPtr, shuffleThunk ); //// //// this.m_invocationList = realDelegate; //// this.m_target = this; //// this.m_methodPtr = callThunk; //// this.m_methodPtrAux = assembly; //// this.m_invocationCount = GetInvokeMethod(); //// } //// //// [System.Diagnostics.DebuggerNonUserCode] //// private void CtorVirtualDispatch( Object target, IntPtr methodPtr, IntPtr shuffleThunk ) //// { //// this.m_target = this; //// this.m_methodPtr = shuffleThunk; //// this.m_methodPtrAux = GetCallStub( methodPtr ); //// } //// //// [System.Diagnostics.DebuggerNonUserCode] //// private void CtorSecureVirtualDispatch( Object target, IntPtr methodPtr, IntPtr shuffleThunk, IntPtr callThunk, IntPtr assembly ) //// { //// MulticastDelegate realDelegate = Delegate.InternalAlloc( Type.GetTypeHandle( this ) ); //// //// realDelegate.CtorVirtualDispatch( target, methodPtr, shuffleThunk ); //// //// this.m_invocationList = realDelegate; //// this.m_target = this; //// this.m_methodPtr = callThunk; //// this.m_methodPtrAux = assembly; //// this.m_invocationCount = GetInvokeMethod(); //// } } } ================================================ FILE: Zelig/Zelig/RunTime/Framework/mscorlib/System/MulticastNotSupportedException.cs ================================================ // ==++== // // Copyright (c) Microsoft Corporation. All rights reserved. // // ==--== //////////////////////////////////////////////////////////////////////////////// // MulticastNotSupportedException // This is thrown when you add multiple callbacks to a non-multicast delegate. //////////////////////////////////////////////////////////////////////////////// namespace System { using System; ////using System.Runtime.Serialization; [Serializable] public sealed class MulticastNotSupportedException : SystemException { public MulticastNotSupportedException() : base( Environment.GetResourceString( "Arg_MulticastNotSupportedException" ) ) { } public MulticastNotSupportedException( String message ) : base( message ) { } public MulticastNotSupportedException( String message, Exception inner ) : base( message, inner ) { } //// internal MulticastNotSupportedException( SerializationInfo info, StreamingContext context ) : base( info, context ) //// { //// } } } ================================================ FILE: Zelig/Zelig/RunTime/Framework/mscorlib/System/NonSerializedAttribute.cs ================================================ // ==++== // // Copyright (c) Microsoft Corporation. All rights reserved. // // ==--== /*============================================================ ** ** Class: NonSerializedAttribute ** ** ** Purpose: Used to mark a member as being not-serialized ** ** ============================================================*/ namespace System { using System.Reflection; [AttributeUsage( AttributeTargets.Field, Inherited = false )] public sealed class NonSerializedAttribute : Attribute { //// internal static Attribute GetCustomAttribute( RuntimeFieldInfo field ) //// { //// if((field.Attributes & FieldAttributes.NotSerialized) == 0) //// { //// return null; //// } //// //// return new NonSerializedAttribute(); //// } //// //// internal static bool IsDefined( RuntimeFieldInfo field ) //// { //// return (field.Attributes & FieldAttributes.NotSerialized) != 0; //// } public NonSerializedAttribute() { } } } ================================================ FILE: Zelig/Zelig/RunTime/Framework/mscorlib/System/NotFiniteNumberException.cs ================================================ // ==++== // // Copyright (c) Microsoft Corporation. All rights reserved. // // ==--== namespace System { using System; using System.Runtime.Serialization; using System.Security.Permissions; [Serializable] public class NotFiniteNumberException : ArithmeticException { private double _offendingNumber; public NotFiniteNumberException() : base( Environment.GetResourceString( "Arg_NotFiniteNumberException" ) ) { _offendingNumber = 0; } public NotFiniteNumberException( double offendingNumber ) : base() { _offendingNumber = offendingNumber; } public NotFiniteNumberException( String message ) : base( message ) { _offendingNumber = 0; } public NotFiniteNumberException( String message, double offendingNumber ) : base( message ) { _offendingNumber = offendingNumber; } public NotFiniteNumberException( String message, Exception innerException ) : base( message, innerException ) { } public NotFiniteNumberException( String message, double offendingNumber, Exception innerException ) : base( message, innerException ) { _offendingNumber = offendingNumber; } //// protected NotFiniteNumberException( SerializationInfo info, StreamingContext context ) : base( info, context ) //// { //// _offendingNumber = info.GetInt32( "OffendingNumber" ); //// } public double OffendingNumber { get { return _offendingNumber; } } //// [SecurityPermissionAttribute( SecurityAction.LinkDemand, Flags = SecurityPermissionFlag.SerializationFormatter )] //// public override void GetObjectData( SerializationInfo info, StreamingContext context ) //// { //// if(info == null) //// { //// throw new ArgumentNullException( "info" ); //// } //// base.GetObjectData( info, context ); //// info.AddValue( "OffendingNumber", _offendingNumber, typeof( Int32 ) ); //// } } } ================================================ FILE: Zelig/Zelig/RunTime/Framework/mscorlib/System/NotImplementedException.cs ================================================ // ==++== // // Copyright (c) Microsoft Corporation. All rights reserved. // // ==--== /*============================================================================= ** ** Class: NotImplementedException ** ** ** Purpose: Exception thrown when a requested method or operation is not ** implemented. ** ** =============================================================================*/ namespace System { using System; using System.Runtime.Serialization; [Serializable] public class NotImplementedException : SystemException { #if EXCEPTION_STRINGS public NotImplementedException() : base( Environment.GetResourceString( "Arg_NotImplementedException" ) ) #else public NotImplementedException() #endif { } public NotImplementedException( String message ) : base( message ) { } public NotImplementedException( String message, Exception inner ) : base( message, inner ) { } //// //// protected NotImplementedException( SerializationInfo info, StreamingContext context ) : base( info, context ) //// { //// } } } ================================================ FILE: Zelig/Zelig/RunTime/Framework/mscorlib/System/NotSupportedException.cs ================================================ // ==++== // // Copyright (c) Microsoft Corporation. All rights reserved. // // ==--== /*============================================================================= ** ** Class: NotSupportedException ** ** ** Purpose: For methods that should be implemented on subclasses. ** ** =============================================================================*/ namespace System { using System; using System.Runtime.Serialization; [Serializable] public class NotSupportedException : SystemException { public NotSupportedException() : base( Environment.GetResourceString( "Arg_NotSupportedException" ) ) { } public NotSupportedException( String message ) : base( message ) { } public NotSupportedException( String message, Exception innerException ) : base( message, innerException ) { } //// protected NotSupportedException( SerializationInfo info, StreamingContext context ) : base( info, context ) //// { //// } } } ================================================ FILE: Zelig/Zelig/RunTime/Framework/mscorlib/System/NullReferenceException.cs ================================================ // ==++== // // Copyright (c) Microsoft Corporation. All rights reserved. // // ==--== /*============================================================================= ** ** Class: NullReferenceException ** ** ** Purpose: Exception class for dereferencing a null reference. ** ** =============================================================================*/ namespace System { using System; using System.Runtime.Serialization; [Serializable] public class NullReferenceException : SystemException { #if EXCEPTION_STRINGS public NullReferenceException() : base( Environment.GetResourceString( "Arg_NullReferenceException" ) ) #else public NullReferenceException() #endif { } public NullReferenceException( String message ) : base( message ) { } public NullReferenceException( String message, Exception innerException ) : base( message, innerException ) { } //// protected NullReferenceException( SerializationInfo info, StreamingContext context ) : base( info, context ) //// { //// } } } ================================================ FILE: Zelig/Zelig/RunTime/Framework/mscorlib/System/Nullable.cs ================================================ // ==++== // // Copyright (c) Microsoft Corporation. All rights reserved. // // ==--== namespace System { using System; using System.Globalization; using System.Reflection; using System.Collections.Generic; using System.Runtime.CompilerServices; ////using System.Security; // Warning, don't put System.Runtime.Serialization.On*Serializ*Attribute // on this class without first fixing ObjectClone::InvokeVtsCallbacks // Also, because we have special type system support that says a a boxed Nullable // can be used where a boxed is use, Nullable can not implement any intefaces // at all (since T may not). Do NOT add any interfaces to Nullable! // ////[TypeDependencyAttribute( "System.Collections.Generic.NullableComparer`1" )] ////[TypeDependencyAttribute( "System.Collections.Generic.NullableEqualityComparer`1" )] [Microsoft.Zelig.Internals.WellKnownType( "System_Nullable_of_T" )] [Microsoft.Zelig.Internals.TypeDependency( typeof(System.Collections.Generic.NullableComparer<>) )] [Microsoft.Zelig.Internals.TypeDependency( typeof(System.Collections.Generic.NullableEqualityComparer<>) )] [Serializable] public struct Nullable where T : struct { private bool hasValue; internal T value; public Nullable( T value ) { this.value = value; this.hasValue = true; } public bool HasValue { get { return hasValue; } } public T Value { get { if(!HasValue) { ThrowHelper.ThrowInvalidOperationException( ExceptionResource.InvalidOperation_NoValue ); } return value; } } public T GetValueOrDefault() { return value; } public T GetValueOrDefault( T defaultValue ) { return HasValue ? value : defaultValue; } public override bool Equals( object other ) { if(!HasValue) return other == null; if(other == null) return false; return value.Equals( other ); } public override int GetHashCode() { return HasValue ? value.GetHashCode() : 0; } public override string ToString() { return HasValue ? value.ToString() : ""; } public static implicit operator Nullable( T value ) { return new Nullable( value ); } public static explicit operator T( Nullable value ) { return value.Value; } //--// // // ZELIG HACK: Once we have support for generic open classes, we can move this helper method to the Zelig code base. // public object Box() { return HasValue ? (object)value : null; } } public static class Nullable { public static int Compare( Nullable n1, Nullable n2 ) where T : struct { if(n1.HasValue) { if(n2.HasValue) return Comparer.Default.Compare( n1.value, n2.value ); return 1; } if(n2.HasValue) return -1; return 0; } public static bool Equals( Nullable n1, Nullable n2 ) where T : struct { if(n1.HasValue) { if(n2.HasValue) return EqualityComparer.Default.Equals( n1.value, n2.value ); return false; } if(n2.HasValue) return false; return true; } //// // If the type provided is not a Nullable Type, return null. //// // Otherwise, returns the underlying type of the Nullable type //// public static Type GetUnderlyingType( Type nullableType ) //// { //// if(nullableType == null) //// { //// throw new ArgumentNullException( "nullableType" ); //// } //// //// Type result = null; //// //// if(nullableType.IsGenericType && !nullableType.IsGenericTypeDefinition) //// { //// // instantiated generic type only //// Type genericType = nullableType.GetGenericTypeDefinition(); //// //// if(genericType == typeof( Nullable<> )) //// { //// result = nullableType.GetGenericArguments()[0]; //// } //// } //// //// return result; //// } } } ================================================ FILE: Zelig/Zelig/RunTime/Framework/mscorlib/System/Number.cs ================================================ // ==++== // // Copyright (c) Microsoft Corporation. All rights reserved. // // ==--== namespace System { using System; using System.Globalization; using System.Runtime.CompilerServices; ////using System.Runtime.Versioning; // The Number class implements methods for formatting and parsing // numeric values. To format and parse numeric values, applications should // use the Format and Parse methods provided by the numeric // classes (Byte, Int16, Int32, Int64, // Single, Double, Currency, and Decimal). Those // Format and Parse methods share a common implementation // provided by this class, and are thus documented in detail here. // // Formatting // // The Format methods provided by the numeric classes are all of the // form // // public static String Format(XXX value, String format); // public static String Format(XXX value, String format, NumberFormatInfo info); // // where XXX is the name of the particular numeric class. The methods convert // the numeric value to a string using the format string given by the // format parameter. If the format parameter is null or // an empty string, the number is formatted as if the string "G" (general // format) was specified. The info parameter specifies the // NumberFormatInfo instance to use when formatting the number. If the // info parameter is null or omitted, the numeric formatting information // is obtained from the current culture. The NumberFormatInfo supplies // such information as the characters to use for decimal and thousand // separators, and the spelling and placement of currency symbols in monetary // values. // // Format strings fall into two categories: Standard format strings and // user-defined format strings. A format string consisting of a single // alphabetic character (A-Z or a-z), optionally followed by a sequence of // digits (0-9), is a standard format string. All other format strings are // used-defined format strings. // // A standard format string takes the form Axx, where A is an // alphabetic character called the format specifier and xx is a // sequence of digits called the precision specifier. The format // specifier controls the type of formatting applied to the number and the // precision specifier controls the number of significant digits or decimal // places of the formatting operation. The following table describes the // supported standard formats. // // C c - Currency format. The number is // converted to a string that represents a currency amount. The conversion is // controlled by the currency format information of the NumberFormatInfo // used to format the number. The precision specifier indicates the desired // number of decimal places. If the precision specifier is omitted, the default // currency precision given by the NumberFormatInfo is used. // // D d - Decimal format. This format is // supported for integral types only. The number is converted to a string of // decimal digits, prefixed by a minus sign if the number is negative. The // precision specifier indicates the minimum number of digits desired in the // resulting string. If required, the number will be left-padded with zeros to // produce the number of digits given by the precision specifier. // // E e Engineering (scientific) format. // The number is converted to a string of the form // "-d.ddd...E+ddd" or "-d.ddd...e+ddd", where each // 'd' indicates a digit (0-9). The string starts with a minus sign if the // number is negative, and one digit always precedes the decimal point. The // precision specifier indicates the desired number of digits after the decimal // point. If the precision specifier is omitted, a default of 6 digits after // the decimal point is used. The format specifier indicates whether to prefix // the exponent with an 'E' or an 'e'. The exponent is always consists of a // plus or minus sign and three digits. // // F f Fixed point format. The number is // converted to a string of the form "-ddd.ddd....", where each // 'd' indicates a digit (0-9). The string starts with a minus sign if the // number is negative. The precision specifier indicates the desired number of // decimal places. If the precision specifier is omitted, the default numeric // precision given by the NumberFormatInfo is used. // // G g - General format. The number is // converted to the shortest possible decimal representation using fixed point // or scientific format. The precision specifier determines the number of // significant digits in the resulting string. If the precision specifier is // omitted, the number of significant digits is determined by the type of the // number being converted (10 for int, 19 for long, 7 for // float, 15 for double, 19 for Currency, and 29 for // Decimal). Trailing zeros after the decimal point are removed, and the // resulting string contains a decimal point only if required. The resulting // string uses fixed point format if the exponent of the number is less than // the number of significant digits and greater than or equal to -4. Otherwise, // the resulting string uses scientific format, and the case of the format // specifier controls whether the exponent is prefixed with an 'E' or an // 'e'. // // N n Number format. The number is // converted to a string of the form "-d,ddd,ddd.ddd....", where // each 'd' indicates a digit (0-9). The string starts with a minus sign if the // number is negative. Thousand separators are inserted between each group of // three digits to the left of the decimal point. The precision specifier // indicates the desired number of decimal places. If the precision specifier // is omitted, the default numeric precision given by the // NumberFormatInfo is used. // // X x - Hexadecimal format. This format is // supported for integral types only. The number is converted to a string of // hexadecimal digits. The format specifier indicates whether to use upper or // lower case characters for the hexadecimal digits above 9 ('X' for 'ABCDEF', // and 'x' for 'abcdef'). The precision specifier indicates the minimum number // of digits desired in the resulting string. If required, the number will be // left-padded with zeros to produce the number of digits given by the // precision specifier. // // Some examples of standard format strings and their results are shown in the // table below. (The examples all assume a default NumberFormatInfo.) // // Value Format Result // 12345.6789 C $12,345.68 // -12345.6789 C ($12,345.68) // 12345 D 12345 // 12345 D8 00012345 // 12345.6789 E 1.234568E+004 // 12345.6789 E10 1.2345678900E+004 // 12345.6789 e4 1.2346e+004 // 12345.6789 F 12345.68 // 12345.6789 F0 12346 // 12345.6789 F6 12345.678900 // 12345.6789 G 12345.6789 // 12345.6789 G7 12345.68 // 123456789 G7 1.234568E8 // 12345.6789 N 12,345.68 // 123456789 N4 123,456,789.0000 // 0x2c45e x 2c45e // 0x2c45e X 2C45E // 0x2c45e X8 0002C45E // // Format strings that do not start with an alphabetic character, or that start // with an alphabetic character followed by a non-digit, are called // user-defined format strings. The following table describes the formatting // characters that are supported in user defined format strings. // // // 0 - Digit placeholder. If the value being // formatted has a digit in the position where the '0' appears in the format // string, then that digit is copied to the output string. Otherwise, a '0' is // stored in that position in the output string. The position of the leftmost // '0' before the decimal point and the rightmost '0' after the decimal point // determines the range of digits that are always present in the output // string. // // # - Digit placeholder. If the value being // formatted has a digit in the position where the '#' appears in the format // string, then that digit is copied to the output string. Otherwise, nothing // is stored in that position in the output string. // // . - Decimal point. The first '.' character // in the format string determines the location of the decimal separator in the // formatted value; any additional '.' characters are ignored. The actual // character used as a the decimal separator in the output string is given by // the NumberFormatInfo used to format the number. // // , - Thousand separator and number scaling. // The ',' character serves two purposes. First, if the format string contains // a ',' character between two digit placeholders (0 or #) and to the left of // the decimal point if one is present, then the output will have thousand // separators inserted between each group of three digits to the left of the // decimal separator. The actual character used as a the decimal separator in // the output string is given by the NumberFormatInfo used to format the // number. Second, if the format string contains one or more ',' characters // immediately to the left of the decimal point, or after the last digit // placeholder if there is no decimal point, then the number will be divided by // 1000 times the number of ',' characters before it is formatted. For example, // the format string '0,,' will represent 100 million as just 100. Use of the // ',' character to indicate scaling does not also cause the formatted number // to have thousand separators. Thus, to scale a number by 1 million and insert // thousand separators you would use the format string '#,##0,,'. // // % - Percentage placeholder. The presence of // a '%' character in the format string causes the number to be multiplied by // 100 before it is formatted. The '%' character itself is inserted in the // output string where it appears in the format string. // // E+ E- e+ e- - Scientific notation. // If any of the strings 'E+', 'E-', 'e+', or 'e-' are present in the format // string and are immediately followed by at least one '0' character, then the // number is formatted using scientific notation with an 'E' or 'e' inserted // between the number and the exponent. The number of '0' characters following // the scientific notation indicator determines the minimum number of digits to // output for the exponent. The 'E+' and 'e+' formats indicate that a sign // character (plus or minus) should always precede the exponent. The 'E-' and // 'e-' formats indicate that a sign character should only precede negative // exponents. // // \ - Literal character. A backslash character // causes the next character in the format string to be copied to the output // string as-is. The backslash itself isn't copied, so to place a backslash // character in the output string, use two backslashes (\\) in the format // string. // // 'ABC' "ABC" - Literal string. Characters // enclosed in single or double quotation marks are copied to the output string // as-is and do not affect formatting. // // ; - Section separator. The ';' character is // used to separate sections for positive, negative, and zero numbers in the // format string. // // Other - All other characters are copied to // the output string in the position they appear. // // For fixed point formats (formats not containing an 'E+', 'E-', 'e+', or // 'e-'), the number is rounded to as many decimal places as there are digit // placeholders to the right of the decimal point. If the format string does // not contain a decimal point, the number is rounded to the nearest // integer. If the number has more digits than there are digit placeholders to // the left of the decimal point, the extra digits are copied to the output // string immediately before the first digit placeholder. // // For scientific formats, the number is rounded to as many significant digits // as there are digit placeholders in the format string. // // To allow for different formatting of positive, negative, and zero values, a // user-defined format string may contain up to three sections separated by // semicolons. The results of having one, two, or three sections in the format // string are described in the table below. // // Sections: // // One - The format string applies to all values. // // Two - The first section applies to positive values // and zeros, and the second section applies to negative values. If the number // to be formatted is negative, but becomes zero after rounding according to // the format in the second section, then the resulting zero is formatted // according to the first section. // // Three - The first section applies to positive // values, the second section applies to negative values, and the third section // applies to zeros. The second section may be left empty (by having no // characters between the semicolons), in which case the first section applies // to all non-zero values. If the number to be formatted is non-zero, but // becomes zero after rounding according to the format in the first or second // section, then the resulting zero is formatted according to the third // section. // // For both standard and user-defined formatting operations on values of type // float and double, if the value being formatted is a NaN (Not // a Number) or a positive or negative infinity, then regardless of the format // string, the resulting string is given by the NaNSymbol, // PositiveInfinitySymbol, or NegativeInfinitySymbol property of // the NumberFormatInfo used to format the number. // // Parsing // // The Parse methods provided by the numeric classes are all of the form // // public static XXX Parse(String s); // public static XXX Parse(String s, int style); // public static XXX Parse(String s, int style, NumberFormatInfo info); // // where XXX is the name of the particular numeric class. The methods convert a // string to a numeric value. The optional style parameter specifies the // permitted style of the numeric string. It must be a combination of bit flags // from the NumberStyles enumeration. The optional info parameter // specifies the NumberFormatInfo instance to use when parsing the // string. If the info parameter is null or omitted, the numeric // formatting information is obtained from the current culture. // // Numeric strings produced by the Format methods using the Currency, // Decimal, Engineering, Fixed point, General, or Number standard formats // (the C, D, E, F, G, and N format specifiers) are guaranteed to be parseable // by the Parse methods if the NumberStyles.Any style is // specified. Note, however, that the Parse methods do not accept // NaNs or Infinities. // //This class contains only static members and does not need to be serializable internal class Number { private int precision; private int scale; private bool negative; private char[] digits = new char[NumberMaxDigits + 1]; //--// // Constants used by number parsing private const Int32 NumberMaxDigits = 50; private const Int32 Int32Precision = 10; private const Int32 UInt32Precision = Int32Precision; private const Int32 Int64Precision = 19; private const Int32 UInt64Precision = 20; private const Int32 FloatPrecision = 7; private const Int32 DoublePrecision = 15; //// // NumberBuffer is a partial wrapper around a stack pointer that maps on to //// // the native NUMBER struct so that it can be passed to native directly. It //// // must be initialized with a stack Byte * of size NumberBufferBytes. //// // For performance, this structure should attempt to be completely inlined. //// // //// // It should always be initialized like so: //// // //// // Byte * numberBufferBytes = stackalloc Byte[NumberBuffer.NumberBufferBytes]; //// // NumberBuffer number = new NumberBuffer(numberBufferBytes); //// // //// // For performance, when working on the buffer in managed we use the values in this //// // structure, except for the digits, and pack those values into the byte buffer //// // if called out to managed. //// unsafe struct NumberBuffer //// { //// //// // Enough space for NumberMaxDigit characters plus null and 3 32 bit integers //// public const Int32 NumberBufferBytes = 12 + ((NumberMaxDigits + 1) * 2); //// private Byte* baseAddress; //// public Char* digits; //// public Int32 precision; //// public Int32 scale; //// public Boolean sign; //// //// public NumberBuffer( Byte* stackBuffer ) //// { //// this.baseAddress = stackBuffer; //// this.digits = (((Char*)stackBuffer) + 6); //// this.precision = 0; //// this.scale = 0; //// this.sign = false; //// } //// //// public Byte* PackForNative() //// { //// Int32* baseInteger = (Int32*)baseAddress; //// baseInteger[0] = precision; //// baseInteger[1] = scale; //// baseInteger[2] = sign ? 1 : 0; //// return baseAddress; //// } //// } //// //// private static Boolean HexNumberToInt32( ref NumberBuffer number, ref Int32 value ) //// { //// UInt32 passedValue = 0; //// Boolean returnValue = HexNumberToUInt32( ref number, ref passedValue ); //// value = (Int32)passedValue; //// return returnValue; //// } //// //// private static Boolean HexNumberToInt64( ref NumberBuffer number, ref Int64 value ) //// { //// UInt64 passedValue = 0; //// Boolean returnValue = HexNumberToUInt64( ref number, ref passedValue ); //// value = (Int64)passedValue; //// return returnValue; //// } //// //// private unsafe static Boolean HexNumberToUInt32( ref NumberBuffer number, ref UInt32 value ) //// { //// //// Int32 i = number.scale; //// if(i > UInt32Precision || i < number.precision) //// { //// return false; //// } //// Char* p = number.digits; //// BCLDebug.Assert( p != null, "" ); //// //// UInt32 n = 0; //// while(--i >= 0) //// { //// if(n > ((UInt32)0xFFFFFFFF / 16)) //// { //// return false; //// } //// n *= 16; //// if(*p != '\0') //// { //// UInt32 newN = n; //// if(*p != '\0') //// { //// if(*p >= '0' && *p <= '9') //// { //// newN += (UInt32)(*p - '0'); //// } //// else //// { //// if(*p >= 'A' && *p <= 'F') //// { //// newN += (UInt32)((*p - 'A') + 10); //// } //// else //// { //// BCLDebug.Assert( *p >= 'a' && *p <= 'f', "" ); //// newN += (UInt32)((*p - 'a') + 10); //// } //// } //// p++; //// } //// //// // Detect an overflow here... //// if(newN < n) //// { //// return false; //// } //// n = newN; //// } //// } //// value = n; //// return true; //// } //// //// private unsafe static Boolean HexNumberToUInt64( ref NumberBuffer number, ref UInt64 value ) //// { //// //// Int32 i = number.scale; //// if(i > UInt64Precision || i < number.precision) //// { //// return false; //// } //// Char* p = number.digits; //// BCLDebug.Assert( p != null, "" ); //// //// UInt64 n = 0; //// while(--i >= 0) //// { //// if(n > (0xFFFFFFFFFFFFFFFF / 16)) //// { //// return false; //// } //// n *= 16; //// if(*p != '\0') //// { //// UInt64 newN = n; //// if(*p != '\0') //// { //// if(*p >= '0' && *p <= '9') //// { //// newN += (UInt64)(*p - '0'); //// } //// else //// { //// if(*p >= 'A' && *p <= 'F') //// { //// newN += (UInt64)((*p - 'A') + 10); //// } //// else //// { //// BCLDebug.Assert( *p >= 'a' && *p <= 'f', "" ); //// newN += (UInt64)((*p - 'a') + 10); //// } //// } //// p++; //// } //// //// // Detect an overflow here... //// if(newN < n) //// { //// return false; //// } //// n = newN; //// } //// } //// value = n; //// return true; //// } private static Boolean IsWhite( char ch ) { return (((ch) == 0x20) || ((ch) >= 0x09 && (ch) <= 0x0D)); } //// private unsafe static Boolean NumberToInt32( ref NumberBuffer number, ref Int32 value ) //// { //// //// Int32 i = number.scale; //// if(i > Int32Precision || i < number.precision) //// { //// return false; //// } //// char* p = number.digits; //// BCLDebug.Assert( p != null, "" ); //// Int32 n = 0; //// while(--i >= 0) //// { //// if((UInt32)n > (0x7FFFFFFF / 10)) //// { //// return false; //// } //// n *= 10; //// if(*p != '\0') //// { //// n += (Int32)(*p++ - '0'); //// } //// } //// if(number.sign) //// { //// n = -n; //// if(n > 0) //// { //// return false; //// } //// } //// else //// { //// if(n < 0) //// { //// return false; //// } //// } //// value = n; //// return true; //// } //// //// private unsafe static Boolean NumberToInt64( ref NumberBuffer number, ref Int64 value ) //// { //// //// Int32 i = number.scale; //// if(i > Int64Precision || i < number.precision) //// { //// return false; //// } //// char* p = number.digits; //// BCLDebug.Assert( p != null, "" ); //// Int64 n = 0; //// while(--i >= 0) //// { //// if((UInt64)n > (0x7FFFFFFFFFFFFFFF / 10)) //// { //// return false; //// } //// n *= 10; //// if(*p != '\0') //// { //// n += (Int32)(*p++ - '0'); //// } //// } //// if(number.sign) //// { //// n = -n; //// if(n > 0) //// { //// return false; //// } //// } //// else //// { //// if(n < 0) //// { //// return false; //// } //// } //// value = n; //// return true; //// } //// //// private unsafe static Boolean NumberToUInt32( ref NumberBuffer number, ref UInt32 value ) //// { //// //// Int32 i = number.scale; //// if(i > UInt32Precision || i < number.precision || number.sign) //// { //// return false; //// } //// char* p = number.digits; //// BCLDebug.Assert( p != null, "" ); //// UInt32 n = 0; //// while(--i >= 0) //// { //// if(n > (0xFFFFFFFF / 10)) //// { //// return false; //// } //// n *= 10; //// if(*p != '\0') //// { //// UInt32 newN = n + (UInt32)(*p++ - '0'); //// // Detect an overflow here... //// if(newN < n) //// { //// return false; //// } //// n = newN; //// } //// } //// value = n; //// return true; //// } //// //// private unsafe static Boolean NumberToUInt64( ref NumberBuffer number, ref UInt64 value ) //// { //// //// Int32 i = number.scale; //// if(i > UInt64Precision || i < number.precision || number.sign) //// { //// return false; //// } //// char* p = number.digits; //// BCLDebug.Assert( p != null, "" ); //// UInt64 n = 0; //// while(--i >= 0) //// { //// if(n > (0xFFFFFFFFFFFFFFFF / 10)) //// { //// return false; //// } //// n *= 10; //// if(*p != '\0') //// { //// UInt64 newN = n + (UInt64)(*p++ - '0'); //// // Detect an overflow here... //// if(newN < n) //// { //// return false; //// } //// n = newN; //// } //// } //// value = n; //// return true; //// } //// //// private unsafe static char* MatchChars( char* p, string str ) //// { //// fixed(char* stringPointer = str) //// { //// return MatchChars( p, stringPointer ); //// } //// } //// private unsafe static char* MatchChars( char* p, char* str ) //// { //// BCLDebug.Assert( p != null && str != null, "" ); //// //// if(*str == '\0') //// { //// return null; //// } //// for(; (*str != '\0'); p++, str++) //// { //// if(*p != *str) //// { //We only hurt the failure case //// if((*str == '\u00A0') && (*p == '\u0020')) //// {// This fix is for French or Kazakh cultures. Since a user cannot type 0xA0 as a //// // space character we use 0x20 space character instead to mean the same. //// continue; //// } //// return null; //// } //// } //// return p; //// } [MethodImpl( MethodImplOptions.InternalCall )] internal unsafe static extern Decimal ParseDecimal( String value , NumberStyles options , NumberFormatInfo numfmt ); //// { //// //// Byte* numberBufferBytes = stackalloc Byte[NumberBuffer.NumberBufferBytes]; //// NumberBuffer number = new NumberBuffer( numberBufferBytes ); //// Decimal result = 0; //// //// StringToNumber( value, options, ref number, numfmt, true ); //// //// if(!NumberBufferToDecimal( number.PackForNative(), ref result )) //// { //// throw new OverflowException( Environment.GetResourceString( "Overflow_Decimal" ) ); //// } //// return result; //// } [MethodImpl( MethodImplOptions.InternalCall )] internal unsafe static extern Double ParseDouble( String value , NumberStyles options , NumberFormatInfo numfmt ); //// { //// Byte* numberBufferBytes = stackalloc Byte[NumberBuffer.NumberBufferBytes]; //// NumberBuffer number = new NumberBuffer( numberBufferBytes ); //// Double d = 0; //// //// StringToNumber( value, options, ref number, numfmt, false ); //// //// if(!NumberBufferToDouble( number.PackForNative(), ref d )) //// { //// throw new OverflowException( Environment.GetResourceString( "Overflow_Double" ) ); //// } //// //// return d; //// } [MethodImpl( MethodImplOptions.InternalCall )] internal unsafe static extern Int32 ParseInt32( String s , NumberStyles style , NumberFormatInfo info ); //// { //// //// Byte* numberBufferBytes = stackalloc Byte[NumberBuffer.NumberBufferBytes]; //// NumberBuffer number = new NumberBuffer( numberBufferBytes ); //// Int32 i = 0; //// //// StringToNumber( s, style, ref number, info, false ); //// //// if((style & NumberStyles.AllowHexSpecifier) != 0) //// { //// if(!HexNumberToInt32( ref number, ref i )) //// { //// throw new OverflowException( Environment.GetResourceString( "Overflow_Int32" ) ); //// } //// } //// else //// { //// if(!NumberToInt32( ref number, ref i )) //// { //// throw new OverflowException( Environment.GetResourceString( "Overflow_Int32" ) ); //// } //// } //// return i; //// } [MethodImpl( MethodImplOptions.InternalCall )] internal unsafe static extern Int64 ParseInt64( String value , NumberStyles options , NumberFormatInfo numfmt ); //// { //// Byte* numberBufferBytes = stackalloc Byte[NumberBuffer.NumberBufferBytes]; //// NumberBuffer number = new NumberBuffer( numberBufferBytes ); //// Int64 i = 0; //// //// StringToNumber( value, options, ref number, numfmt, false ); //// //// if((options & NumberStyles.AllowHexSpecifier) != 0) //// { //// if(!HexNumberToInt64( ref number, ref i )) //// { //// throw new OverflowException( Environment.GetResourceString( "Overflow_Int64" ) ); //// } //// } //// else //// { //// if(!NumberToInt64( ref number, ref i )) //// { //// throw new OverflowException( Environment.GetResourceString( "Overflow_Int64" ) ); //// } //// } //// return i; //// } //// //// private unsafe static Boolean ParseNumber( ref char* str, NumberStyles options, ref NumberBuffer number, NumberFormatInfo numfmt, Boolean parseDecimal ) //// { //// //// const Int32 StateSign = 0x0001; //// const Int32 StateParens = 0x0002; //// const Int32 StateDigits = 0x0004; //// const Int32 StateNonZero = 0x0008; //// const Int32 StateDecimal = 0x0010; //// const Int32 StateCurrency = 0x0020; //// //// number.scale = 0; //// number.sign = false; //// string decSep; // decimal separator from NumberFormatInfo. //// string groupSep; // group separator from NumberFormatInfo. //// string currSymbol = null; // currency symbol from NumberFormatInfo. //// //// // The alternative currency symbol used in ANSI codepage, that can not roundtrip between ANSI and Unicode. //// // Currently, only ja-JP and ko-KR has non-null values (which is U+005c, backslash) //// string ansicurrSymbol = null; // currency symbol from NumberFormatInfo. //// string altdecSep = null; // decimal separator from NumberFormatInfo as a decimal //// string altgroupSep = null; // group separator from NumberFormatInfo as a decimal //// //// Boolean parsingCurrency = false; //// if((options & NumberStyles.AllowCurrencySymbol) != 0) //// { //// currSymbol = numfmt.CurrencySymbol; //// if(numfmt.ansiCurrencySymbol != null) //// { //// ansicurrSymbol = numfmt.ansiCurrencySymbol; //// } //// // The idea here is to match the currency separators and on failure match the number separators to keep the perf of VB's IsNumeric fast. //// // The values of decSep are setup to use the correct relevant separator (currency in the if part and decimal in the else part). //// altdecSep = numfmt.NumberDecimalSeparator; //// altgroupSep = numfmt.NumberGroupSeparator; //// decSep = numfmt.CurrencyDecimalSeparator; //// groupSep = numfmt.CurrencyGroupSeparator; //// parsingCurrency = true; //// } //// else //// { //// decSep = numfmt.NumberDecimalSeparator; //// groupSep = numfmt.NumberGroupSeparator; //// } //// //// Int32 state = 0; //// Boolean signflag = false; // Cache the results of "options & PARSE_LEADINGSIGN && !(state & STATE_SIGN)" to avoid doing this twice //// //// char* p = str; //// char ch = *p; //// char* next; //// //// while(true) //// { //// // Eat whitespace unless we've found a sign which isn't followed by a currency symbol. //// // "-Kr 1231.47" is legal but "- 1231.47" is not. //// if(IsWhite( ch ) && ((options & NumberStyles.AllowLeadingWhite) != 0) && (((state & StateSign) == 0) || (((state & StateSign) != 0) && (((state & StateCurrency) != 0) || numfmt.numberNegativePattern == 2)))) //// { //// // Do nothing here. We will increase p at the end of the loop. //// } //// else if((signflag = (((options & NumberStyles.AllowLeadingSign) != 0) && ((state & StateSign) == 0))) && ((next = MatchChars( p, numfmt.positiveSign )) != null)) //// { //// state |= StateSign; //// p = next - 1; //// } //// else if(signflag && (next = MatchChars( p, numfmt.negativeSign )) != null) //// { //// state |= StateSign; //// number.sign = true; //// p = next - 1; //// } //// else if(ch == '(' && ((options & NumberStyles.AllowParentheses) != 0) && ((state & StateSign) == 0)) //// { //// state |= StateSign | StateParens; //// number.sign = true; //// } //// else if((currSymbol != null && (next = MatchChars( p, currSymbol )) != null) || (ansicurrSymbol != null && (next = MatchChars( p, ansicurrSymbol )) != null)) //// { //// state |= StateCurrency; //// currSymbol = null; //// ansicurrSymbol = null; //// // We already found the currency symbol. There should not be more currency symbols. Set //// // currSymbol to NULL so that we won't search it again in the later code path. //// p = next - 1; //// } //// else //// { //// break; //// } //// ch = *++p; //// } //// Int32 digCount = 0; //// Int32 digEnd = 0; //// while(true) //// { //// if((ch >= '0' && ch <= '9') || (((options & NumberStyles.AllowHexSpecifier) != 0) && ((ch >= 'a' && ch <= 'f') || (ch >= 'A' && ch <= 'F')))) //// { //// state |= StateDigits; //// if(ch != '0' || (state & StateNonZero) != 0) //// { //// if(digCount < NumberMaxDigits) //// { //// number.digits[digCount++] = ch; //// if(ch != '0' || parseDecimal) //// { //// digEnd = digCount; //// } //// } //// if((state & StateDecimal) == 0) //// { //// number.scale++; //// } //// state |= StateNonZero; //// } //// else if((state & StateDecimal) != 0) //// { //// number.scale--; //// } //// } //// else if(((options & NumberStyles.AllowDecimalPoint) != 0) && ((state & StateDecimal) == 0) && ((next = MatchChars( p, decSep )) != null || ((parsingCurrency) && (state & StateCurrency) == 0) && (next = MatchChars( p, altdecSep )) != null)) //// { //// state |= StateDecimal; //// p = next - 1; //// } //// else if(((options & NumberStyles.AllowThousands) != 0) && ((state & StateDigits) != 0) && ((state & StateDecimal) == 0) && ((next = MatchChars( p, groupSep )) != null || ((parsingCurrency) && (state & StateCurrency) == 0) && (next = MatchChars( p, altgroupSep )) != null)) //// { //// p = next - 1; //// } //// else //// { //// break; //// } //// ch = *++p; //// } //// //// Boolean negExp = false; //// number.precision = digEnd; //// number.digits[digEnd] = '\0'; //// if((state & StateDigits) != 0) //// { //// if((ch == 'E' || ch == 'e') && ((options & NumberStyles.AllowExponent) != 0)) //// { //// char* temp = p; //// ch = *++p; //// if((next = MatchChars( p, numfmt.positiveSign )) != null) //// { //// ch = *(p = next); //// } //// else if((next = MatchChars( p, numfmt.negativeSign )) != null) //// { //// ch = *(p = next); //// negExp = true; //// } //// if(ch >= '0' && ch <= '9') //// { //// Int32 exp = 0; //// do //// { //// exp = exp * 10 + (ch - '0'); //// ch = *++p; //// if(exp > 1000) //// { //// exp = 9999; //// while(ch >= '0' && ch <= '9') //// { //// ch = *++p; //// } //// } //// } while(ch >= '0' && ch <= '9'); //// if(negExp) //// { //// exp = -exp; //// } //// number.scale += exp; //// } //// else //// { //// p = temp; //// ch = *p; //// } //// } //// while(true) //// { //// if(IsWhite( ch ) && ((options & NumberStyles.AllowTrailingWhite) != 0)) //// { //// } //// else if((signflag = (((options & NumberStyles.AllowTrailingSign) != 0) && ((state & StateSign) == 0))) && (next = MatchChars( p, numfmt.positiveSign )) != null) //// { //// state |= StateSign; //// p = next - 1; //// } //// else if(signflag && (next = MatchChars( p, numfmt.negativeSign )) != null) //// { //// state |= StateSign; //// number.sign = true; //// p = next - 1; //// } //// else if(ch == ')' && ((state & StateParens) != 0)) //// { //// state &= ~StateParens; //// } //// else if((currSymbol != null && (next = MatchChars( p, currSymbol )) != null) || (ansicurrSymbol != null && (next = MatchChars( p, ansicurrSymbol )) != null)) //// { //// currSymbol = null; //// ansicurrSymbol = null; //// p = next - 1; //// } //// else //// { //// break; //// } //// ch = *++p; //// } //// if((state & StateParens) == 0) //// { //// if((state & StateNonZero) == 0) //// { //// if(!parseDecimal) //// { //// number.scale = 0; //// } //// if((state & StateDecimal) == 0) //// { //// number.sign = false; //// } //// } //// str = p; //// return true; //// } //// } //// str = p; //// return false; //// } [MethodImpl( MethodImplOptions.InternalCall )] internal unsafe static extern Single ParseSingle( String value , NumberStyles options , NumberFormatInfo numfmt ); //// { //// //// Byte* numberBufferBytes = stackalloc Byte[NumberBuffer.NumberBufferBytes]; //// NumberBuffer number = new NumberBuffer( numberBufferBytes ); //// Double d = 0; //// //// StringToNumber( value, options, ref number, numfmt, false ); //// //// if(!NumberBufferToDouble( number.PackForNative(), ref d )) //// { //// throw new OverflowException( Environment.GetResourceString( "Overflow_Single" ) ); //// } //// Single castSingle = (Single)d; //// if(Single.IsInfinity( castSingle )) //// { //// throw new OverflowException( Environment.GetResourceString( "Overflow_Single" ) ); //// } //// return castSingle; //// } [MethodImpl( MethodImplOptions.InternalCall )] internal unsafe static extern UInt32 ParseUInt32( String value , NumberStyles options , NumberFormatInfo numfmt ); //// { //// //// Byte* numberBufferBytes = stackalloc Byte[NumberBuffer.NumberBufferBytes]; //// NumberBuffer number = new NumberBuffer( numberBufferBytes ); //// UInt32 i = 0; //// //// StringToNumber( value, options, ref number, numfmt, false ); //// //// if((options & NumberStyles.AllowHexSpecifier) != 0) //// { //// if(!HexNumberToUInt32( ref number, ref i )) //// { //// throw new OverflowException( Environment.GetResourceString( "Overflow_UInt32" ) ); //// } //// } //// else //// { //// if(!NumberToUInt32( ref number, ref i )) //// { //// throw new OverflowException( Environment.GetResourceString( "Overflow_UInt32" ) ); //// } //// } //// //// return i; //// } [MethodImpl( MethodImplOptions.InternalCall )] internal unsafe static extern UInt64 ParseUInt64( String value , NumberStyles options , NumberFormatInfo numfmt ); //// { //// Byte* numberBufferBytes = stackalloc Byte[NumberBuffer.NumberBufferBytes]; //// NumberBuffer number = new NumberBuffer( numberBufferBytes ); //// UInt64 i = 0; //// //// StringToNumber( value, options, ref number, numfmt, false ); //// if((options & NumberStyles.AllowHexSpecifier) != 0) //// { //// if(!HexNumberToUInt64( ref number, ref i )) //// { //// throw new OverflowException( Environment.GetResourceString( "Overflow_UInt64" ) ); //// } //// } //// else //// { //// if(!NumberToUInt64( ref number, ref i )) //// { //// throw new OverflowException( Environment.GetResourceString( "Overflow_UInt64" ) ); //// } //// } //// return i; //// } //// //// private unsafe static void StringToNumber( String str, NumberStyles options, ref NumberBuffer number, NumberFormatInfo info, Boolean parseDecimal ) //// { //// //// if(str == null) //// { //// throw new ArgumentNullException( "String" ); //// } //// BCLDebug.Assert( info != null, "" ); //// fixed(char* stringPointer = str) //// { //// char* p = stringPointer; //// if(!ParseNumber( ref p, options, ref number, info, parseDecimal ) //// || (p - stringPointer < str.Length && !TrailingZeros( str, (int)(p - stringPointer) ))) //// { //// throw new FormatException( Environment.GetResourceString( "Format_InvalidString" ) ); //// } //// } //// } //// //// private static Boolean TrailingZeros( String s, Int32 index ) //// { //// // For compatability, we need to allow trailing zeros at the end of a number string //// for(int i = index; i < s.Length; i++) //// { //// if(s[i] != '\0') //// { //// return false; //// } //// } //// return true; //// } [MethodImpl( MethodImplOptions.InternalCall )] internal unsafe static extern Boolean TryParseDecimal( String value , NumberStyles options , NumberFormatInfo numfmt , out Decimal result ); //// { //// //// Byte* numberBufferBytes = stackalloc Byte[NumberBuffer.NumberBufferBytes]; //// NumberBuffer number = new NumberBuffer( numberBufferBytes ); //// result = 0; //// //// if(!TryStringToNumber( value, options, ref number, numfmt, true )) //// { //// return false; //// } //// //// if(!NumberBufferToDecimal( number.PackForNative(), ref result )) //// { //// return false; //// } //// return true; //// } [MethodImpl( MethodImplOptions.InternalCall )] internal unsafe static extern Boolean TryParseDouble( String value , NumberStyles options , NumberFormatInfo numfmt , out Double result ); //// { //// Byte* numberBufferBytes = stackalloc Byte[NumberBuffer.NumberBufferBytes]; //// NumberBuffer number = new NumberBuffer( numberBufferBytes ); //// result = 0; //// //// //// if(!TryStringToNumber( value, options, ref number, numfmt, false )) //// { //// return false; //// } //// if(!NumberBufferToDouble( number.PackForNative(), ref result )) //// { //// return false; //// } //// return true; //// } [MethodImpl( MethodImplOptions.InternalCall )] internal unsafe static extern Boolean TryParseInt32( String s , NumberStyles style , NumberFormatInfo info , out Int32 result ); //// { //// //// Byte* numberBufferBytes = stackalloc Byte[NumberBuffer.NumberBufferBytes]; //// NumberBuffer number = new NumberBuffer( numberBufferBytes ); //// result = 0; //// //// if(!TryStringToNumber( s, style, ref number, info, false )) //// { //// return false; //// } //// //// if((style & NumberStyles.AllowHexSpecifier) != 0) //// { //// if(!HexNumberToInt32( ref number, ref result )) //// { //// return false; //// } //// } //// else //// { //// if(!NumberToInt32( ref number, ref result )) //// { //// return false; //// } //// } //// return true; //// } [MethodImpl( MethodImplOptions.InternalCall )] internal unsafe static extern Boolean TryParseInt64( String s , NumberStyles style , NumberFormatInfo info , out Int64 result ); //// { //// //// Byte* numberBufferBytes = stackalloc Byte[NumberBuffer.NumberBufferBytes]; //// NumberBuffer number = new NumberBuffer( numberBufferBytes ); //// result = 0; //// //// if(!TryStringToNumber( s, style, ref number, info, false )) //// { //// return false; //// } //// //// if((style & NumberStyles.AllowHexSpecifier) != 0) //// { //// if(!HexNumberToInt64( ref number, ref result )) //// { //// return false; //// } //// } //// else //// { //// if(!NumberToInt64( ref number, ref result )) //// { //// return false; //// } //// } //// return true; //// } [MethodImpl( MethodImplOptions.InternalCall )] internal unsafe static extern Boolean TryParseSingle( String value , NumberStyles options , NumberFormatInfo numfmt , out Single result ); //// { //// Byte* numberBufferBytes = stackalloc Byte[NumberBuffer.NumberBufferBytes]; //// NumberBuffer number = new NumberBuffer( numberBufferBytes ); //// result = 0; //// Double d = 0; //// //// if(!TryStringToNumber( value, options, ref number, numfmt, false )) //// { //// return false; //// } //// if(!NumberBufferToDouble( number.PackForNative(), ref d )) //// { //// return false; //// } //// Single castSingle = (Single)d; //// if(Single.IsInfinity( castSingle )) //// { //// return false; //// } //// //// result = castSingle; //// return true; //// } [MethodImpl( MethodImplOptions.InternalCall )] internal unsafe static extern Boolean TryParseUInt32( String s , NumberStyles style , NumberFormatInfo info , out UInt32 result ); //// { //// //// Byte* numberBufferBytes = stackalloc Byte[NumberBuffer.NumberBufferBytes]; //// NumberBuffer number = new NumberBuffer( numberBufferBytes ); //// result = 0; //// //// if(!TryStringToNumber( s, style, ref number, info, false )) //// { //// return false; //// } //// //// if((style & NumberStyles.AllowHexSpecifier) != 0) //// { //// if(!HexNumberToUInt32( ref number, ref result )) //// { //// return false; //// } //// } //// else //// { //// if(!NumberToUInt32( ref number, ref result )) //// { //// return false; //// } //// } //// return true; //// } [MethodImpl( MethodImplOptions.InternalCall )] internal unsafe static extern Boolean TryParseUInt64( String s , NumberStyles style , NumberFormatInfo info , out UInt64 result ); //// { //// //// Byte* numberBufferBytes = stackalloc Byte[NumberBuffer.NumberBufferBytes]; //// NumberBuffer number = new NumberBuffer( numberBufferBytes ); //// result = 0; //// //// if(!TryStringToNumber( s, style, ref number, info, false )) //// { //// return false; //// } //// //// if((style & NumberStyles.AllowHexSpecifier) != 0) //// { //// if(!HexNumberToUInt64( ref number, ref result )) //// { //// return false; //// } //// } //// else //// { //// if(!NumberToUInt64( ref number, ref result )) //// { //// return false; //// } //// } //// return true; //// } //// //// private unsafe static Boolean TryStringToNumber( String str, NumberStyles options, ref NumberBuffer number, NumberFormatInfo numfmt, Boolean parseDecimal ) //// { //// //// if(str == null) //// { //// return false; //// } //// BCLDebug.Assert( numfmt != null, "" ); //// //// fixed(char* stringPointer = str) //// { //// char* p = stringPointer; //// if(!ParseNumber( ref p, options, ref number, numfmt, parseDecimal ) //// || (p - stringPointer < str.Length && !TrailingZeros( str, (int)(p - stringPointer) ))) //// { //// return false; //// } //// } //// //// return true; //// } //// private Number( ref Decimal value ) //// { //// this.precision = DecimalPrecision; //// this.negative = value.negative; //// int index = NumberMaxDigits; //// while(value.mid32 != 0 || value.hi32 != 0) //// { //// Int32ToDecChars( this.digits, ref index, DecDivMod1E9( ref value ), 9 ); //// } //// Int32ToDecChars( this.digits, ref index, value.lo32, 0 ); //// int digitCount = NumberMaxDigits - index; //// this.scale = digitCount - value.scale; //// int destIndex = 0; //// while(digitCount > 0) //// { //// this.digits[destIndex] = this.digits[index]; //// destIndex++; //// index++; //// digitCount--; //// } //// this.digits[destIndex] = '\0'; //// } private Number( int value ) { this.precision = Int32Precision; if(value >= 0) { this.negative = false; } else { this.negative = true; value = -value; } int index = Int32ToDecChars( this.digits, Int32Precision, unchecked( (uint)value ), 0 ); int digitCount = Int32Precision - index; int destIndex = 0; this.scale = digitCount; while(digitCount > 0) { this.digits[destIndex] = this.digits[index]; destIndex++; index++; digitCount--; } this.digits[destIndex] = '\0'; } private Number( uint value ) { this.precision = Int32Precision; this.negative = false; int index = Int32ToDecChars( this.digits, Int32Precision, value, 0 ); int digitCount = Int32Precision - index; int destIndex = 0; this.scale = digitCount; while(digitCount > 0) { this.digits[destIndex] = this.digits[index]; destIndex++; index++; digitCount--; } this.digits[destIndex] = '\0'; } private Number( long value ) { this.precision = Int64Precision; if(value >= 0) { this.negative = false; } else { this.negative = true; value = -value; } int index = Int64ToDecChars( this.digits, Int64Precision, unchecked( (ulong)value ), 0 ); int digitCount = Int64Precision - index; int destIndex = 0; this.scale = digitCount; while(digitCount > 0) { this.digits[destIndex] = this.digits[index]; destIndex++; index++; digitCount--; } this.digits[destIndex] = '\0'; } private Number( ulong value ) { this.precision = Int64Precision; this.negative = false; int index = Int64ToDecChars( this.digits, Int64Precision, value, 0 ); int digitCount = Int64Precision - index; int destIndex = 0; this.scale = digitCount; while(digitCount > 0) { this.digits[destIndex] = this.digits[index]; destIndex++; index++; digitCount--; } this.digits[destIndex] = '\0'; } // inline this!!! private static bool EndString( String s, int p ) { return p == s.Length || s[p] == '\0'; } // markples: see also Lightning\Src\VM\COMNumber.cpp:: // wchar* MatchChars(wchar* p, wchar* str) // will now return -1 instead of NULL on failure private static int MatchChars( String str1, int p, String str ) { int str_i = 0; if(EndString( str, str_i )) return -1; for(; !EndString( str, str_i ); p++, str_i++) { if(str1[p] != str[str_i]) //We only hurt the failure case { if((str[str_i] == 0xA0) && (str1[p] == 0x20)) // This fix is for French or Kazakh cultures. // Since a user cannot type 0xA0 as a space // character we use 0x20 space character // instead to mean the same. continue; return -1; } } return p; } private const int STATE_SIGN = 0x0001; private const int STATE_PARENS = 0x0002; private const int STATE_DIGITS = 0x0004; private const int STATE_NONZERO = 0x0008; private const int STATE_DECIMAL = 0x0010; private const int STATE_HEXLEAD = 0x0020; // #defines in Lightning\Src\VM\COMNumber.cpp private const int FLOAT_PRECISION = 7; private const int DOUBLE_PRECISION = 15; private const int MIN_BUFFER_SIZE = 105; private const int SCALE_NAN = unchecked( (int)0x80000000 ); private const int SCALE_INF = 0x7FFFFFFF; private static String[] posPercentFormats = { "# %", "#%", "%#" }; // BUGBUG yslin: have to verify on the negative Percent // format for real format. private static String[] negPercentFormats = { "-# %", "-#%", "-%#" }; private static String[] negNumberFormats = { "(#)", "-#", "- #", "#-", "# -" }; private static String posNumberFormat = "#"; // code below depends on seeing the null terminator... private static char Get( String str, int i ) { return i < str.Length ? str[i] : '\0'; } private Number( double value , int precision ) { this.precision = precision; if(value >= 0) { this.negative = false; } else { this.negative = true; value = -value; } double log = Math.Floor( Math.Log10( value ) ); int digitPos = (int)log; // // Limit to something slightly less than the maximum exponent or we might overflow/underflow. // if(digitPos >= 308) digitPos = 307; if(digitPos <= -308) digitPos = -307; double value2 = value * PowerOfTen( -digitPos ); // // Log10 returns a value that is almost the correct one, but due to the integer truncation, we might be off by an order of magnitude. // Make sure the number to convert is within the range [0.1,1) // if(value2 < 0.01) { value2 *= 1E2; digitPos -= 2; } else if(value2 < 0.1) { value2 *= 10; digitPos -= 1; } else if(value2 >= 10) { value2 *= 1E-2; digitPos += 2; } else if(value2 >= 1) { value2 *= 1E-1; digitPos += 1; } this.scale = digitPos; value2 *= PowerOfTen( precision ); ulong valInt = unchecked( (ulong)(long)value2 ); int index = Int64ToDecChars( this.digits, UInt64Precision, valInt, 0 ); int digitCount = UInt64Precision - index; int destIndex = 0; while(digitCount > 0) { this.digits[destIndex] = this.digits[index]; destIndex++; index++; digitCount--; } } static double PowerOfTen( int scale ) { double res = 1; if(scale > 0) { switch(scale % 32) { case 0 : res *= 1E0 ; break; case 1 : res *= 1E1 ; break; case 2 : res *= 1E2 ; break; case 3 : res *= 1E3 ; break; case 4 : res *= 1E4 ; break; case 5 : res *= 1E5 ; break; case 6 : res *= 1E6 ; break; case 7 : res *= 1E7 ; break; case 8 : res *= 1E8 ; break; case 9 : res *= 1E9 ; break; case 10: res *= 1E10; break; case 11: res *= 1E11; break; case 12: res *= 1E12; break; case 13: res *= 1E13; break; case 14: res *= 1E14; break; case 15: res *= 1E15; break; case 16: res *= 1E16; break; case 17: res *= 1E17; break; case 18: res *= 1E18; break; case 19: res *= 1E19; break; case 20: res *= 1E20; break; case 21: res *= 1E21; break; case 22: res *= 1E22; break; case 23: res *= 1E23; break; case 24: res *= 1E24; break; case 25: res *= 1E25; break; case 26: res *= 1E26; break; case 27: res *= 1E27; break; case 28: res *= 1E28; break; case 29: res *= 1E29; break; case 30: res *= 1E30; break; case 31: res *= 1E31; break; } while(scale >= 32) { res *= 1E32; scale -= 32; } } else if(scale < 0) { scale = -scale; switch(scale % 32) { case 0 : res *= 1E-0 ; break; case 1 : res *= 1E-1 ; break; case 2 : res *= 1E-2 ; break; case 3 : res *= 1E-3 ; break; case 4 : res *= 1E-4 ; break; case 5 : res *= 1E-5 ; break; case 6 : res *= 1E-6 ; break; case 7 : res *= 1E-7 ; break; case 8 : res *= 1E-8 ; break; case 9 : res *= 1E-9 ; break; case 10: res *= 1E-10; break; case 11: res *= 1E-11; break; case 12: res *= 1E-12; break; case 13: res *= 1E-13; break; case 14: res *= 1E-14; break; case 15: res *= 1E-15; break; case 16: res *= 1E-16; break; case 17: res *= 1E-17; break; case 18: res *= 1E-18; break; case 19: res *= 1E-19; break; case 20: res *= 1E-20; break; case 21: res *= 1E-21; break; case 22: res *= 1E-22; break; case 23: res *= 1E-23; break; case 24: res *= 1E-24; break; case 25: res *= 1E-25; break; case 26: res *= 1E-26; break; case 27: res *= 1E-27; break; case 28: res *= 1E-28; break; case 29: res *= 1E-29; break; case 30: res *= 1E-30; break; case 31: res *= 1E-31; break; } while(scale >= 32) { res *= 1E-32; scale -= 32; } } return res; } //// // markples: see also Lightning\Src\VM\COMNumber.cpp:: //// // int ParseNumber(wchar** str, int options, //// // NUMBER* number, NUMFMTREF numfmt) //// // clr behavior: return nonzero on failure and update *str //// // new behavior: return false iff broken (error or *str != \0 at end) //// private bool ParseNumber( String str, NumberStyles style ) //// { //// this.scale = 0; //// this.negative = false; //// String decSep = info.numberDecimalSeparator; //// String groupSep = info.numberGroupSeparator; //// //// int state = 0; //// bool signflag = false; // Cache the results of //// // "style & NumberStyles.AllowLeadingSign && //// // !(state & STATE_SIGN)" //// // to avoid doing this twice //// int p = 0; //// int next; //// //// if((style & NumberStyles.AllowHexSpecifier) != 0 && //// str.Length >= 2) //// { //// if(str[0] == '0' && (str[1] == 'x' || str[1] == 'X')) //// { //// p = 2; //// } //// } //// //// char ch = Get( str, p ); //// //// while(true) //// { //// //Eat whitespace unless we've found a sign. //// if(IsWhite( ch ) //// && ((style & NumberStyles.AllowLeadingWhite) != 0) //// && (!((state & STATE_SIGN) != 0) || //// (((state & STATE_SIGN) != 0) && //// (info.numberNegativePattern == 2)))) //// { //// // Do nothing here. We will increase p at the end of the loop //// } //// else if((signflag = //// (((style & NumberStyles.AllowLeadingSign) != 0) && //// !((state & STATE_SIGN) != 0))) && //// (next = MatchChars( str, p, info.positiveSign )) != -1) //// { //// state |= STATE_SIGN; //// p = next - 1; //// } //// else if(signflag && //// (next = MatchChars( str, p, info.negativeSign )) != -1) //// { //// state |= STATE_SIGN; //// this.negative = true; //// p = next - 1; //// } //// else if(ch == '(' && //// ((style & NumberStyles.AllowParentheses) != 0) && //// !((state & STATE_SIGN) != 0)) //// { //// state |= STATE_SIGN | STATE_PARENS; //// this.negative = true; //// } //// else //// { //// break; //// } //// ch = Get( str, ++p ); //// } //// int digCount = 0; //// int digEnd = 0; //// while(true) //// { //// if((ch >= '0' && ch <= '9') || //// (((style & NumberStyles.AllowHexSpecifier) != 0) && //// ((ch >= 'a' && ch <= 'f') || (ch >= 'A' && ch <= 'F')))) //// { //// state |= STATE_DIGITS; //// if(ch != '0' || ((state & STATE_NONZERO) != 0)) //// { //// if(digCount < NUMBER_MAXDIGITS) //// { //// this.digits[digCount++] = ch; //// if(ch != '0') digEnd = digCount; //// } //// if(!((state & STATE_DECIMAL) != 0)) this.scale++; //// state |= STATE_NONZERO; //// } //// else if((state & STATE_DECIMAL) != 0) this.scale--; //// } //// else if(((style & NumberStyles.AllowDecimalPoint) != 0) && //// !((state & STATE_DECIMAL) != 0) && //// ((next = MatchChars( str, p, decSep )) != -1)) //// { //// state |= STATE_DECIMAL; //// p = next - 1; //// } //// else if(((style & NumberStyles.AllowThousands) != 0) && //// ((state & STATE_DIGITS) != 0) && //// !((state & STATE_DECIMAL) != 0) && //// ((next = MatchChars( str, p, groupSep )) != -1)) //// { //// p = next - 1; //// } //// else //// { //// break; //// } //// ch = Get( str, ++p ); //// } //// //// bool negExp = false; //// this.precision = digEnd; //// this.digits[digEnd] = '\0'; //// if((state & STATE_DIGITS) != 0) //// { //// if((ch == 'E' || ch == 'e') && //// ((style & NumberStyles.AllowExponent) != 0)) //// { //// int temp = p; //// ch = Get( str, ++p ); //// if((next = MatchChars( str, p, info.positiveSign )) != -1) //// { //// ch = Get( str, p = next ); //// } //// else if((next = MatchChars( str, p, info.negativeSign )) != -1) //// { //// ch = Get( str, p = next ); //// negExp = true; //// } //// if(ch >= '0' && ch <= '9') //// { //// int exp = 0; //// do //// { //// exp = exp * 10 + (ch - '0'); //// ch = Get( str, ++p ); //// if(exp > 1000) //// { //// exp = 9999; //// while(ch >= '0' && ch <= '9') //// { //// ch = Get( str, ++p ); //// } //// } //// } while(ch >= '0' && ch <= '9'); //// if(negExp) exp = -exp; //// this.scale += exp; //// } //// else //// { //// p = temp; //// ch = Get( str, p ); //// } //// } //// while(true) //// { //// if(IsWhite( ch ) && //// ((style & NumberStyles.AllowTrailingWhite) != 0)) //// { //// // do nothing //// } //// else if((signflag = //// (((style & NumberStyles.AllowTrailingSign) != 0) //// && //// !((state & STATE_SIGN) != 0))) && //// (next = //// MatchChars( str, p, info.positiveSign )) != -1) //// { //// state |= STATE_SIGN; //// p = next - 1; //// } //// else if(signflag && //// (next = MatchChars( str, p, //// info.negativeSign )) != -1) //// { //// state |= STATE_SIGN; //// this.negative = true; //// p = next - 1; //// } //// else if(ch == ')' && ((state & STATE_PARENS) != 0)) //// { //// state &= ~STATE_PARENS; //// } //// else //// { //// break; //// } //// ch = Get( str, ++p ); //// } //// if(!((state & STATE_PARENS) != 0)) //// { //// if(!((state & STATE_NONZERO) != 0)) //// { //// this.scale = 0; //// if(!((state & STATE_DECIMAL) != 0)) //// { //// this.negative = false; //// } //// } //// // *str = p; //// // return 1; //// return EndString( str, p ); //// } //// } //// // *str = p; //// // return 0; //// return false; //// } //// //// //// // markples: see also Lightning\Src\VM\COMNumber.cpp:: //// //void StringToNumber(STRINGREF str, int options, //// // NUMBER* number, NUMFMTREF numfmt) //// private Number( String str, NumberStyles style ) //// { //// { //// //THROWSCOMPLUSEXCEPTION(); //// //// if(str == null) //// { //// throw new NullReferenceException(); //// } //// //// if(!info.validForParseAsNumber) //// { //// throw new ArgumentException( "Argument_AmbiguousNumberInfo" ); //// } //// //wchar* p = str->GetBuffer(); //// if(!ParseNumber( str, style )) //// { //// throw new FormatException( "Format_InvalidString" ); //// } //// } //// } [MethodImpl( MethodImplOptions.InternalCall )] public static extern String FormatDecimal( Decimal value , String format , NumberFormatInfo info ); //// { //// // rusa: see also Lightning\Src\VM\COMNumber.cpp::FormatDecimal //// if(format == null) //// { //// throw new ArgumentNullException( "format" ); //// } //// Number number = new Number( ref value ); //// return FPNumberToString( number, format, info ); //// } public static String FormatDouble( double value , NumberFormatInfo info ) { Number number = new Number( value, DOUBLE_PRECISION ); if(number.scale == SCALE_NAN) { return info.nanSymbol; } if(number.scale == SCALE_INF) { return number.negative ? info.negativeInfinitySymbol : info.positiveInfinitySymbol; } return number.ToString( 'G', -1, info ); } public static String FormatDouble( double value , String format , NumberFormatInfo info ) { // rusa: see also Lightning\Src\VM\COMNumber.cpp::FormatDouble Number number; int digits; char fmt = ParseFormatSpecifier( format, out digits ); char val = (char)(fmt & 0xFFDF); int precision = DOUBLE_PRECISION; switch(val) { case 'R': //In order to give numbers that are both //friendly to display and round-trippable, we //parse the number using 15 digits and then //determine if it round trips to the same value. //If it does, we convert that NUMBER to a //string, otherwise we reparse using 17 digits //and display that. number = new Number( value, DOUBLE_PRECISION ); if(number.scale == SCALE_NAN) { return info.nanSymbol; } if(number.scale == SCALE_INF) { return number.negative ? info.negativeInfinitySymbol : info.positiveInfinitySymbol; } //// double dTest; //// NumberToDouble( number, out dTest ); //// //// if(dTest == value) //// { //// return number.ToString( 'G', DOUBLE_PRECISION ); //// } number = new Number( value, 17 ); return number.ToString( 'G', 17, info ); case 'E': // Here we round values less than E14 to 15 digits if(digits > 14) { precision = 17; } break; case 'G': // Here we round values less than G15 to 15 // digits, G16 and G17 will not be touched if(digits > 15) { precision = 17; } break; } number = new Number( value, precision ); return FPNumberToString( number, format, info ); } internal static String FormatInt32( int value, NumberFormatInfo info ) { return FormatInt32( value, 'G', info ); } internal static String FormatInt32( int value , char formatChar, NumberFormatInfo info ) { Number number = new Number( value ); return number.ToString( formatChar, -1, info ); } public static String FormatInt32( int value , String format , NumberFormatInfo info ) { // rusa: see also Lightning\Src\VM\COMNumber.cpp::FormatInt32 int digits; char fmt = ParseFormatSpecifier( format, out digits ); switch(fmt) { case 'g': case 'G': { if(digits > 0) break; goto case 'D'; } case 'd': case 'D': { return Int32ToDecString( value, digits, info.negativeSign ); } case 'x': case 'X': { return Int32ToHexString( unchecked( (uint)value ), (char)(fmt - ('X' - 'A' + 10)), digits ); } default: { break; } } Number number = new Number( value ); if(fmt == 0) { return number.ToStringFormat( format, info ); } else { return number.ToString( fmt, digits, info ); } } internal static String FormatUInt32( uint value, NumberFormatInfo info ) { Number number = new Number( value ); return number.ToString( 'G', -1, info ); } public static String FormatUInt32( uint value , String format , NumberFormatInfo info ) { // rusa: see also Lightning\Src\VM\COMNumber.cpp::FormatUInt32 int digits; char fmt = ParseFormatSpecifier( format, out digits ); switch(fmt) { case 'g': case 'G': { if(digits > 0) break; goto case 'D'; } case 'd': case 'D': { return UInt32ToDecString( value, digits ); } case 'x': case 'X': { return Int32ToHexString( value, (char)(fmt - ('X' - 'A' + 10)), digits ); } default: { break; } } Number number = new Number( value ); if(fmt == 0) { return number.ToStringFormat( format, info ); } else { return number.ToString( fmt, digits, info ); } } internal static String FormatInt64( Int64 value, NumberFormatInfo info ) { Number number = new Number( value ); return number.ToString( 'G', -1, info ); } public static String FormatInt64( long value , String format , NumberFormatInfo info ) { // rusa: see also Lightning\Src\VM\COMNumber.cpp::FormatInt64 int digits; char fmt = ParseFormatSpecifier( format, out digits ); switch(fmt) { case 'g': case 'G': { if(digits > 0) break; goto case 'D'; } case 'd': case 'D': { return Int64ToDecString( value, digits, info.negativeSign ); } case 'x': case 'X': { return Int64ToHexString( unchecked( (ulong)value ), (char)(fmt - ('X' - 'A' + 10)), digits ); } default: { break; } } Number number = new Number( value ); if(fmt == 0) { return number.ToStringFormat( format, info ); } else { return number.ToString( fmt, digits, info ); } } internal static String FormatUInt64( UInt64 value, NumberFormatInfo info ) { Number number = new Number( value ); return number.ToString( 'G', -1, info ); } public static String FormatUInt64( ulong value , String format , NumberFormatInfo info ) { // rusa: see also Lightning\Src\VM\COMNumber.cpp::FormatUInt64 int digits; char fmt = ParseFormatSpecifier( format, out digits ); switch(fmt) { case 'g': case 'G': { if(digits > 0) break; goto case 'D'; } case 'd': case 'D': { return UInt64ToDecString( value, digits ); } case 'x': case 'X': { return Int64ToHexString( value, (char)(fmt - ('X' - 'A' + 10)), digits ); } default: { break; } } Number number = new Number( value ); if(fmt == 0) { return number.ToStringFormat( format, info ); } else { return number.ToString( fmt, digits, info ); } } public static String FormatSingle( float value, NumberFormatInfo info ) { Number number = new Number( value, FLOAT_PRECISION ); if(number.scale == SCALE_NAN) { return info.nanSymbol; } if(number.scale == SCALE_INF) { return number.negative ? info.negativeInfinitySymbol : info.positiveInfinitySymbol; } return number.ToString( 'G', -1, info ); } public static String FormatSingle( float value , String format , NumberFormatInfo info ) { // rusa: see also Lightning\Src\VM\COMNumber.cpp::FormatSingle Number number; int digits; double argsValue = value; char fmt = ParseFormatSpecifier( format, out digits ); char val = (char)(fmt & 0xFFDF); int precision = FLOAT_PRECISION; switch(val) { case 'R': //In order to give numbers that are both //friendly to display and round-trippable, we //parse the number using 7 digits and then //determine if it round trips to the same value. //If it does, we convert that NUMBER to a //string, otherwise we reparse using 9 digits //and display that. number = new Number( argsValue, FLOAT_PRECISION ); if(number.scale == SCALE_NAN) { return info.nanSymbol; } if(number.scale == SCALE_INF) { return number.negative ? info.negativeInfinitySymbol : info.positiveInfinitySymbol; } //// double dTest; //// NumberToDouble( number, out dTest ); //// //// // HACK: force restriction to float //// float[] hack = new float[1]; //// hack[0] = (float)dTest; //// float fTest = hack[0]; //// //// if(fTest == value) //// { //// return number.ToString( 'G', FLOAT_PRECISION ); //// } number = new Number( argsValue, 9 ); return number.ToString( 'G', 9, info ); case 'E': // Here we round values less than E14 to 15 digits if(digits > 6) { precision = 9; } break; case 'G': // Here we round values less than G15 to 15 // digits, G16 and G17 will not be touched if(digits > 7) { precision = 9; } break; } number = new Number( value, precision ); return FPNumberToString( number, format, info ); } //// public static Decimal ParseDecimal( String s, NumberStyles style ) //// { //// // rusa: see also Lightning\Src\VM\COMNumber.cpp::ParseDecimal //// Number number = new Number( s, style ); //// Decimal result; //// if(!NumberToDecimal( number, out result )) //// { //// throw new OverflowException( "Overflow_Decimal" ); //// } //// return result; //// } //// //// public static double ParseDouble( String s, NumberStyles style ) //// { //// Number number = new Number( s, style ); //// double result; //// NumberToDouble( number, out result ); //// return result; //// } //// //// public static int ParseInt32( String s, NumberStyles style ) //// { //// // rusa: see also Lightning\Src\VM\COMNumber.cpp::ParseInt32 //// Number number = new Number( s, style ); //// int result; //// if((style & NumberStyles.AllowHexSpecifier) != 0) //// { //// uint temp; //// if(!HexNumberToUInt32( number, out temp )) //// { //// throw new OverflowException( "Overflow_Int32" ); //// } //// result = unchecked( (int)temp ); //// } //// else //// { //// if(!NumberToInt32( number, out result )) //// { //// throw new OverflowException( "Overflow_Int32" ); //// } //// } //// return result; //// } //// //// public static uint ParseUInt32( String s, NumberStyles style ) //// { //// // rusa: see also Lightning\Src\VM\COMNumber.cpp::ParseUInt32 //// Number number = new Number( s, style ); //// uint result; //// if((style & NumberStyles.AllowHexSpecifier) != 0) //// { //// if(!HexNumberToUInt32( number, out result )) //// { //// throw new OverflowException( "Overflow_UInt32" ); //// } //// } //// else //// { //// if(!NumberToUInt32( number, out result )) //// { //// throw new OverflowException( "Overflow_UInt32" ); //// } //// } //// return result; //// } //// //// public static long ParseInt64( String s, NumberStyles style ) //// { //// // rusa: see also Lightning\Src\VM\COMNumber.cpp::ParseInt64 //// Number number = new Number( s, style ); //// long result; //// if((style & NumberStyles.AllowHexSpecifier) != 0) //// { //// ulong temp; //// if(!HexNumberToUInt64( number, out temp )) //// { //// throw new OverflowException( "Overflow_UInt32" ); //// } //// result = unchecked( (long)temp ); //// } //// else //// { //// if(!NumberToInt64( number, out result )) //// { //// throw new OverflowException( "Overflow_UInt32" ); //// } //// } //// return result; //// } //// //// public static ulong ParseUInt64( String s, NumberStyles style ) //// { //// // rusa: see also Lightning\Src\VM\COMNumber.cpp::ParseUInt64 //// Number number = new Number( s, style ); //// ulong result; //// if((style & NumberStyles.AllowHexSpecifier) != 0) //// { //// if(!HexNumberToUInt64( number, out result )) //// { //// throw new OverflowException( "Overflow_UInt32" ); //// } //// } //// else //// { //// if(!NumberToUInt64( number, out result )) //// { //// throw new OverflowException( "Overflow_UInt32" ); //// } //// } //// return result; //// } //// //// public static float ParseSingle( String s, NumberStyles style ) //// { //// return (float)ParseDouble( s, style ); //// } private static String FPNumberToString( Number number, String format, NumberFormatInfo info ) { if(number.scale == SCALE_NAN) { return info.nanSymbol; } if(number.scale == SCALE_INF) { return number.negative ? info.negativeInfinitySymbol : info.positiveInfinitySymbol; } int digits; char fmt = ParseFormatSpecifier( format, out digits ); if(fmt != 0) { return number.ToString( fmt, digits, info ); } return number.ToStringFormat( format, info ); } private String ToString( char format , int digits , NumberFormatInfo info ) { long newBufferLen = MIN_BUFFER_SIZE; System.Text.StringBuilder sb = null; int digCount = 0; char ftype = (char)(format & 0xFFDF); switch(ftype) { case 'F': if(digits < 0) digits = info.numberDecimalDigits; if(this.scale < 0) digCount = 0; else digCount = this.scale + digits; newBufferLen += digCount; // For number and exponent newBufferLen += info.negativeSign.Length; newBufferLen += info.numberDecimalSeparator.Length; sb = new System.Text.StringBuilder( (int)newBufferLen ); RoundNumber( this.scale + digits ); if(this.negative) { sb.Append( info.negativeSign ); } FormatFixed( sb, digits, null, info.numberDecimalSeparator, null, info ); break; case 'N': // Since we are using digits in our calculation if(digits < 0) digits = info.numberDecimalDigits; if(this.scale < 0) digCount = 0; else digCount = this.scale + digits; newBufferLen += digCount; // For number and exponent newBufferLen += info.negativeSign.Length; // For all the grouping sizes newBufferLen += info.numberGroupSeparator.Length * digCount; newBufferLen += info.numberDecimalSeparator.Length; sb = new System.Text.StringBuilder( (int)newBufferLen ); RoundNumber( this.scale + digits ); FormatNumber( sb, digits, info ); break; case 'E': if(digits < 0) digits = 6; digits++; newBufferLen += digits; // For number and exponent newBufferLen += (info.negativeSign.Length + info.positiveSign.Length) * 2; newBufferLen += info.numberDecimalSeparator.Length; sb = new System.Text.StringBuilder( (int)newBufferLen ); RoundNumber( digits ); if(this.negative) { sb.Append( info.negativeSign ); } FormatScientific( sb, digits, format, info ); break; case 'G': if(digits < 1) digits = this.precision; newBufferLen += digits; // For number and exponent newBufferLen += (info.negativeSign.Length + info.positiveSign.Length) * 2; newBufferLen += info.numberDecimalSeparator.Length; sb = new System.Text.StringBuilder( (int)newBufferLen ); RoundNumber( digits ); if(this.negative) { sb.Append( info.negativeSign ); } FormatGeneral( sb, digits, (char)(format - ('G' - 'E')), info ); break; case 'P': if(digits < 0) digits = info.percentDecimalDigits; this.scale += 2; if(this.scale < 0) digCount = 0; else digCount = this.scale + digits; newBufferLen += digCount; // For number and exponent newBufferLen += info.negativeSign.Length; // For all the grouping sizes newBufferLen += info.percentGroupSeparator.Length * digCount; newBufferLen += info.percentDecimalSeparator.Length; newBufferLen += info.percentSymbol.Length; sb = new System.Text.StringBuilder( (int)newBufferLen ); RoundNumber( this.scale + digits ); FormatPercent( sb, digits, info ); break; default: #if EXCEPTION_STRINGS throw new FormatException( "Format_BadFormatSpecifier" ); #else throw new FormatException(); #endif // COMPlusThrow(kFormatException,L"Format_BadFormatSpecifier"); } return sb.ToString(); } //// private static bool NumberToDecimal( Number number, out Decimal value ) //// { //// throw new Exception( "System.Number.NumberToDecimal not implemented in Bartok!" ); //// } //// //// private static void NumberToDouble( Number number, out double value ) //// { //// if(number.digits[0] != 0) //// { //// byte[] buffer = new byte[64]; //// int index = 0; //// char[] src = number.digits; //// if(number.negative) buffer[index++] = (byte)'-'; //// for(int j = 0; j < src.Length; j++) //// { //// if(src[j] == '\0') //// { //// break; //// } //// else //// { //// buffer[index++] = (byte)src[j]; //// } //// } //// int i = number.scale - number.precision; //// if(i != 0) //// { //// buffer[index++] = (byte)'e'; //// if(i < 0) //// { //// buffer[index++] = (byte)'-'; //// i = -i; //// } //// if(i >= 100) //// { //// if(i > 999) i = 999; //// buffer[index++] = (byte)(i / 100 + (int)'0'); //// i %= 100; //// } //// buffer[index++] = (byte)(i / 10 + (int)'0'); //// buffer[index++] = (byte)(i % 10 + (int)'0'); //// } //// buffer[index] = (byte)'\0'; //// value = atof( buffer ); //// } //// else //// { //// value = 0; //// } //// //// } //// //// // int NumberToInt32(NUMBER* number, int* value) //// // Returns 1 (true) on success, 0 (false) for fail. //// private static bool NumberToInt32( Number number, out int value ) //// { //// // markples: see also Lightning\Src\VM\COMNumber.cpp::NumberToInt32 //// int i = number.scale; //// if(i > Int32Precision || i < number.precision) goto broken; //// char[] c = number.digits; //// int p = 0; //// int n = 0; //// while(--i >= 0) //// { //// if((uint)n > (0x7FFFFFFF / 10)) goto broken; //// n *= 10; //// if(c[p] != '\0') n += c[p++] - '0'; //// } //// if(number.negative) //// { //// n = -n; //// if(n > 0) goto broken; //// } //// else //// { //// if(n < 0) goto broken; //// } //// value = n; //// return true; //// //// broken: //// value = 0; //// return false; //// } //// //// private static bool NumberToUInt32( Number number, out uint value ) //// { //// // markples: see also Lightning\Src\VM\COMNumber.cpp::NumberToInt32 //// int i = number.scale; //// if(i > UInt32Precision || i < number.precision) goto broken; //// if(number.negative) goto broken; //// char[] c = number.digits; //// int p = 0; //// uint n = 0; //// while(--i >= 0) //// { //// if((uint)n > (0xFFFFFFFF / 10)) goto broken; //// n *= 10; //// if(c[p] != '\0') n += (uint)(c[p++] - '0'); //// } //// value = n; //// return true; //// //// broken: //// value = 0; //// return false; //// } //// //// private static bool NumberToInt64( Number number, out long value ) //// { //// // markples: see also Lightning\Src\VM\COMNumber.cpp::NumberToInt32 //// int i = number.scale; //// if(i > UInt64Precision || i < number.precision) goto broken; //// char[] c = number.digits; //// int p = 0; //// long n = 0; //// while(--i >= 0) //// { //// if((ulong)n > (0x7FFFFFFFFFFFFFFF / 10)) goto broken; //// n *= 10; //// if(c[p] != '\0') n += c[p++] - '0'; //// } //// if(number.negative) //// { //// n = -n; //// if(n > 0) goto broken; //// } //// else //// { //// if(n < 0) goto broken; //// } //// value = n; //// return true; //// //// broken: //// value = 0; //// return false; //// } //// //// private static bool NumberToUInt64( Number number, out ulong value ) //// { //// // markples: see also Lightning\Src\VM\COMNumber.cpp::NumberToInt32 //// int i = number.scale; //// if(i > Int64Precision || i < number.precision) goto broken; //// if(number.negative) goto broken; //// char[] c = number.digits; //// int p = 0; //// ulong n = 0; //// while(--i >= 0) //// { //// if((ulong)n > (0xFFFFFFFFFFFFFFFF / 10)) goto broken; //// n *= 10; //// if(c[p] != '\0') n += (ulong)(c[p++] - '0'); //// } //// value = n; //// return true; //// //// broken: //// value = 0; //// return false; //// } //// //// private static bool HexNumberToUInt32( Number number, out uint value ) //// { //// // markples: see also Lightning\Src\VM\COMNumber.cpp::HexNumberToInt32 //// int i = number.scale; //// if(i > UInt32Precision || i < number.precision) //// { //// goto broken; //// } //// if(number.negative) //// { //// goto broken; //// } //// char[] c = number.digits; //// int p = 0; //// uint n = 0; //// while(--i >= 0) //// { //// if((uint)n > (0xFFFFFFFF / 16)) //// { //// goto broken; //// } //// n *= 16; //// if(c[p] >= '0' && c[p] <= '9') //// { //// n += (uint)(c[p++] - '0'); //// } //// else if(c[p] >= 'a' && c[p] <= 'f') //// { //// n += 10 + (uint)(c[p++] - 'a'); //// } //// else if(c[p] >= 'A' && c[p] <= 'F') //// { //// n += 10 + (uint)(c[p++] - 'A'); //// } //// } //// value = n; //// return true; //// //// broken: //// value = 0; //// return false; //// } //// //// private static bool HexNumberToUInt64( Number number, out ulong value ) //// { //// // markples: see also Lightning\Src\VM\COMNumber.cpp::HexNumberToInt32 //// int i = number.scale; //// if(i > Int64Precision || i < number.precision) //// { //// goto broken; //// } //// if(number.negative) //// { //// goto broken; //// } //// char[] c = number.digits; //// int p = 0; //// ulong n = 0; //// while(--i >= 0) //// { //// if((ulong)n > (0xFFFFFFFFFFFFFFFF / 16)) //// { //// goto broken; //// } //// n *= 16; //// if(c[p] >= '0' && c[p] <= '9') //// { //// n += (uint)(c[p++] - '0'); //// } //// else if(c[p] >= 'a' && c[p] <= 'f') //// { //// n += 10 + (uint)(c[p++] - 'a'); //// } //// else if(c[p] >= 'A' && c[p] <= 'F') //// { //// n += 10 + (uint)(c[p++] - 'A'); //// } //// } //// value = n; //// return true; //// //// broken: //// value = 0; //// return false; //// } private static char ParseFormatSpecifier( string format, out int digits ) { if(format != null) { int index = 0; char c = Get( format, index ); if(c != 0) { if(c >= 'A' && c <= 'Z' || c >= 'a' && c <= 'z') { index++; int n = -1; c = Get( format, index ); if(c >= '0' && c <= '9') { n = (c - '0'); index++; c = Get( format, index ); while(c >= '0' && c <= '9') { n = n * 10 + (c - '0'); index++; c = Get( format, index ); if(n >= 10) break; } } if(c == 0) { digits = n; return Get( format, 0 ); } } digits = -1; return '\0'; } } digits = -1; return 'G'; } struct ToStringFormatState { internal int section; internal int sectionOffset; internal int firstDigit; internal int lastDigit; internal int digitCount; internal int scaleAdjust; internal bool scientific; internal int decimalPos; internal int percent; internal int permille; internal int thousandSeps; internal int thousandCount; internal int thousandPos; internal String format; internal int src; //--/ internal void Reset() { decimalPos = -1; firstDigit = 0x7FFFFFFF; lastDigit = 0; scientific = false; percent = 0; permille = 0; thousandSeps = 0; src = sectionOffset; } internal char DecodeFormat( char ch ) { digitCount = 0; thousandPos = -1; scaleAdjust = 0; while(ch != '\0' && ch != ';') { switch(ch) { case '#': digitCount++; break; case '0': if(firstDigit == 0x7FFFFFFF) { firstDigit = digitCount; } digitCount++; lastDigit = digitCount; break; case '.': if(decimalPos < 0) { decimalPos = digitCount; } break; case ',': if(digitCount > 0 && decimalPos < 0) { if(thousandPos >= 0) { if(thousandPos == digitCount) { thousandCount++; break; } thousandSeps = 1; } thousandPos = digitCount; thousandCount = 1; } break; case '%': percent++; scaleAdjust += 2; break; case '\u2030': permille++; scaleAdjust += 3; break; case '\'': case '"': while(true) { char ch2 = PeekAt( 0 ); if(ch2 == 0 || ch2 == ch ) { break; } src++; } break; case '\\': if(PeekAt( 0 ) != 0) { src++; } break; case 'E': { char ch2 = PeekAt( 0 ); char ch3 = PeekAt( 1 ); if( ch2 == '0' || ((ch2 == '+' || ch2 == '-' ) && ch3 == '0') ) { MoveToEnd(); scientific = true; } } break; } ch = Get(); } if(decimalPos < 0) { decimalPos = digitCount; } if(thousandPos >= 0) { if(thousandPos == decimalPos) { scaleAdjust -= thousandCount * 3; } else { thousandSeps = 1; } } return ch; } internal char Get() { if(src < format.Length) { return format[src++]; } return '\0'; } internal char PeekAt( int offset ) { if(src + offset < format.Length) { return format[src+offset]; } return '\0'; } internal void Advance() { src++; } private void MoveToEnd() { src = format.Length; } } // rusa: see also Lightning\Src\VM\COMNumber.cpp::NumberToStringFormat private String ToStringFormat( String format , NumberFormatInfo info ) { ToStringFormatState state = new ToStringFormatState(); state.format = format; state.section = (this.digits[0] == 0 ? 2 : (this.negative ? 1 : 0)); state.sectionOffset = FindSection( state.format, state.section ); while(true) { state.Reset(); char ch = state.DecodeFormat( state.Get() ); if(this.digits[0] != 0) { this.scale += state.scaleAdjust; int pos = (state.scientific ? state.digitCount : (this.scale + state.digitCount - state.decimalPos)); this.RoundNumber( pos ); if(this.digits[0] == 0) { state.src = FindSection( state.format, 2 ); if(state.src != state.sectionOffset) { state.sectionOffset = state.src; continue; } } } else { this.negative = false; } break; } state.firstDigit = (state.firstDigit < state.decimalPos) ? state.decimalPos - state.firstDigit : 0; state.lastDigit = (state.lastDigit > state.decimalPos) ? state.decimalPos - state. lastDigit : 0; int digPos; int adjust; if(state.scientific) { digPos = state.decimalPos; adjust = 0; } else { digPos = (this.scale > state.decimalPos) ? this.scale : state.decimalPos; adjust = this.scale - state.decimalPos; } state.src = state.sectionOffset; ulong adjustLength = (adjust > 0) ? (uint)adjust : 0U; int bufferLength = 125; int[] thousandSepPos = null; int thousandSepCtr = -1; if(state.thousandSeps != 0) { int groupSizeLen = info.numberGroupSizes.Length; if(groupSizeLen == 0) { state.thousandSeps = 0; } else { thousandSepPos = new int[bufferLength]; long groupTotalSizeCount = info.numberGroupSizes[0]; int groupSizeIndex = 0; int groupSize = (int)groupTotalSizeCount; int totalDigits = digPos + ((adjust < 0) ? adjust : 0); int numDigits = (state.firstDigit > totalDigits) ? state.firstDigit : totalDigits; while(numDigits > groupTotalSizeCount) { if(groupSize == 0) { break; } thousandSepCtr++; thousandSepPos[thousandSepCtr] = (int)groupTotalSizeCount; if(groupSizeIndex < groupSizeLen - 1) { groupSizeIndex++; groupSize = info.numberGroupSizes[groupSizeIndex]; } groupTotalSizeCount += groupSize; if(bufferLength - thousandSepCtr < 10) { bufferLength *= 2; int[] oldThousandSepPos = thousandSepPos; thousandSepPos = new int[bufferLength]; for(int i = 0; i < thousandSepCtr; i++) { thousandSepPos[i] = oldThousandSepPos[i]; } } } adjustLength += (ulong)((thousandSepCtr + 1) * info.numberGroupSeparator.Length); } } System.Text.StringBuilder sb = new System.Text.StringBuilder( 128 ); if(this.negative && state.sectionOffset == 0) { sb.Append( info.negativeSign ); } { char ch = state.Get(); int digitOffset = 0; while(ch != 0 && ch != ';') { switch(ch) { case '#': case '0': { while(adjust > 0) { sb.Append( this.digits[digitOffset] != 0 ? this.digits[digitOffset++] : '0' ); if(state.thousandSeps != 0 && digPos > 1 && thousandSepCtr >= 0 ) { if(digPos == thousandSepPos[thousandSepCtr] + 1) { sb.Append( info.numberGroupSeparator ); thousandSepCtr--; } } digPos--; adjust--; } if(adjust < 0) { adjust++; ch = (digPos <= state.firstDigit) ? '0' : '\0'; } else { ch = ((this.digits[digitOffset] != 0) ? this.digits[digitOffset++] : ((digPos > state.lastDigit) ? '0' : '\0')); } if(ch != 0) { if(digPos == 0) { sb.Append( info.numberDecimalSeparator ); } sb.Append( ch ); if(state.thousandSeps != 0 && digPos > 1 && thousandSepCtr >= 0 ) { if(digPos == thousandSepPos[thousandSepCtr] + 1) { sb.Append( info.numberGroupSeparator ); thousandSepCtr--; } } } digPos--; break; } case '.': break; case '\u2030': sb.Append( info.perMilleSymbol ); break; case '%': sb.Append( info.percentSymbol ); break; case ',': break; case '\'': case '"': while(true) { char ch2 = state.Get(); if(ch2 == 0 || ch2 == ch) { break; } sb.Append( ch2 ); } break; case '\\': { char ch2 = state.Get(); if(ch2 != 0) { sb.Append( ch2 ); } } break; case 'E': case 'e': { String sign = null; int i = 0; if(state.scientific) { char ch2 = state.PeekAt( 0 ); char ch3 = state.PeekAt( 1 ); if(ch2 == '0') { i++; } else if(ch2 == '+' && ch3 == '0') { sign = info.positiveSign; } else if(ch2 == '-' && ch3 == '0') { // Do nothing } else { sb.Append( ch ); break; } state.Advance(); while(state.PeekAt( 0 ) == '0') { state.Advance(); i++; } if(i > 10) { i = 10; } int exp = ((this.digits[0] == 0) ? 0 : (this.scale - state.decimalPos)); FormatExponent( sb, exp, ch, sign, info.negativeSign, i ); state.scientific = false; } else { sb.Append( ch ); while(state.PeekAt( 0 ) != 0) { sb.Append( state.Get() ); } } break; } default: sb.Append( ch ); break; } ch = state.Get(); } } return sb.ToString(); } private static int FindSection( String format, int section ) { if(section == 0) { return 0; } int src = 0; while(true) { char ch = Get( format, src ); src++; switch(ch) { case '\'': case '"': while(Get( format, src ) != '\0' && Get( format, src ) != ch) { src++; } break; case '\\': if(Get( format, src ) != 0) { src++; } break; case ';': section--; if(section != 0) { break; } if(Get( format, src ) != 0 && Get( format, src ) != ';') { return src; } return 0; case '\0': return 0; } } } // markples: see also Lightning\Src\VM\COMNumber.cpp:: // STRINGREF Int32ToDecStr(int value, int digits, STRINGREF sNegative) private static String Int32ToDecString( int value, int digits, String sign ) { //THROWSCOMPLUSEXCEPTION(); //CQuickBytes buf; int bufferLength = 100; // was UINT int negLength = 0; // wchar* src = NULL; if(digits < 1) digits = 1; if(value < 0) { //src = sNegative->GetBuffer(); negLength = sign.Length; if(negLength > 85) { bufferLength = negLength + 15; //was implicit C++ cast } } char[] buffer = new char[bufferLength]; //if (!buffer) // COMPlusThrowOM(); int p = Int32ToDecChars( buffer, bufferLength, (uint)(value >= 0 ? value : -value), digits ); if(value < 0) { for(int i = negLength - 1; i >= 0; i--) { buffer[--p] = sign[i]; // *(--p) = *(src+i); } } // _ASSERTE( buffer + bufferLength - p >=0 && buffer <= p); return new string( buffer, p, bufferLength - p ); // return COMString::NewString(p, buffer + bufferLength - p); } private static String Int32ToHexString( uint value, char hexBase, int digits ) { char[] buffer = new char[100]; if(digits < 1) { digits = 1; } int start = Int32ToHexChars( buffer, 100, value, hexBase, digits ); return new string( buffer, start, 100 - start ); } private static int Int32ToHexChars( char[] buffer, int offset, uint value, char hexBase, int digits ) { while(digits > 0 || value != 0) { digits--; uint digit = value & 0xf; offset--; buffer[offset] = (char)(digit + (digit < 10 ? '0' : hexBase)); value >>= 4; } return offset; } private static String UInt32ToDecString( uint value, int digits ) { int bufferLength = 100; if(digits < 1) digits = 1; char[] buffer = new char[bufferLength]; int p = Int32ToDecChars( buffer, bufferLength, value, digits ); return new string( buffer, p, bufferLength - p ); } // used to be macros private static uint LO32( ulong x ) { return (uint)(x); } private static uint HI32( ulong x ) { return (uint)((((ulong)x) & 0xFFFFFFFF00000000L) >> 32); } // markples: see also Lightning\Src\VM\COMNumber.cpp:: //STRINGREF Int64ToDecStr(__int64 value, int digits, STRINGREF sNegative) private static String Int64ToDecString( long value, int digits, String sign ) { //THROWSCOMPLUSEXCEPTION(); //CQuickBytes buf; if(digits < 1) digits = 1; int signNum = (int)HI32( unchecked( (ulong)value ) ); int bufferLength = 100; // was UINT if(signNum < 0) { value = -value; int negLength = sign.Length; if(negLength > 75) {// Since max is 20 digits bufferLength = negLength + 25; } } char[] buffer = new char[bufferLength]; //if (!buffer) // COMPlusThrowOM(); int p = bufferLength; while(HI32( unchecked( (ulong)value ) ) != 0) { uint rem; value = (long)Int64DivMod1E9( (ulong)value, out rem ); p = Int32ToDecChars( buffer, p, rem, 9 ); digits -= 9; } p = Int32ToDecChars( buffer, p, LO32( unchecked( (ulong)value ) ), digits ); if(signNum < 0) { for(int i = sign.Length - 1; i >= 0; i--) { buffer[--p] = sign[i]; } } return new string( buffer, p, bufferLength - p ); } private static int Int64ToHexChars( char[] buffer, int offset, ulong value, char hexBase, int digits ) { while(digits > 0 || value != 0) { digits--; uint digit = ((uint)value) & 0xf; offset--; buffer[offset] = (char)(digit + (digit < 10 ? '0' : hexBase)); value >>= 4; } return offset; } private static String Int64ToHexString( ulong value, char hexBase, int digits ) { char[] buffer = new char[100]; if(digits < 1) { digits = 1; } int start = Int64ToHexChars( buffer, 100, value, hexBase, digits ); return new string( buffer, start, 100 - start ); } private static String UInt64ToDecString( ulong value, int digits ) { int bufferLength = 100; char[] buffer = new char[bufferLength]; if(digits < 1) digits = 1; int p = bufferLength; while(HI32( value ) != 0) { uint rem; value = Int64DivMod1E9( value, out rem ); p = Int32ToDecChars( buffer, p, rem, 9 ); digits -= 9; } p = Int32ToDecChars( buffer, p, LO32( value ), digits ); return new string( buffer, p, bufferLength - p ); } // markples: see also Lightning\Src\VM\COMNumber.cpp:: // wchar* Int32ToDecChars(wchar* p, unsigned int value, int digits) // There's a x86 asm version there too. private static int Int32ToDecChars( char[] buffer , int bufferIndex , uint value , int digits ) { while(--digits >= 0 || value != 0) { buffer[--bufferIndex] = (char)(value % 10 + '0'); value /= 10; } return bufferIndex; } private static int Int64ToDecChars( char[] buffer , int bufferIndex , ulong value , int digits ) { while(--digits >= 0 || value != 0) { buffer[--bufferIndex] = (char)(value % 10 + '0'); value /= 10; } return bufferIndex; } // markples: see also Lightning\Src\VM\COMNumber.cpp:: // void RoundNumber(NUMBER* number, int pos) private void RoundNumber( int pos ) { int i = 0; while(i < pos && this.digits[i] != 0) i++; if(i == pos && this.digits[i] >= '5') { while(i > 0 && this.digits[i - 1] == '9') i--; if(i > 0) { this.digits[i - 1]++; } else { this.scale++; this.digits[0] = '1'; i = 1; } } else { while(i > 0 && this.digits[i - 1] == '0') i--; } if(i == 0) { this.scale = 0; this.negative = false; } this.digits[i] = '\0'; } private void FormatExponent( System.Text.StringBuilder sb , int value , char expChar , String posSignStr , String negSignStr , int minDigits ) { char[] digits = new char[11]; sb.Append( expChar ); if(value < 0) { sb.Append( negSignStr ); value = -value; } else { if(posSignStr != null) { sb.Append( posSignStr ); } } // REVIEW: (int) was implicit in C++ code int p = Int32ToDecChars( digits, 10, checked( (uint)value ), minDigits ); int i = 10 - p; while(--i >= 0) { sb.Append( digits[p++] ); } } private void FormatGeneral( System.Text.StringBuilder sb , int digits , char expChar , NumberFormatInfo info ) { int digPos = this.scale; bool scientific = false; if(digPos > digits || digPos < -3) { digPos = 1; scientific = true; } int dig = 0; // number->digits; if(digPos > 0) { do { sb.Append( this.digits[dig] != 0 ? this.digits[dig++] : '0' ); } while(--digPos > 0); } else { sb.Append( '0' ); } if(this.digits[dig] != 0) { sb.Append( info.numberDecimalSeparator ); while(digPos < 0) { sb.Append( '0' ); digPos++; } do { sb.Append( this.digits[dig++] ); } while(this.digits[dig] != 0); } if(scientific) { FormatExponent( sb, this.scale - 1, expChar, info.positiveSign, info.negativeSign, 2 ); } } private void FormatScientific( System.Text.StringBuilder sb , int digits , char expChar , NumberFormatInfo info ) { int dig = 0; // number->digits; sb.Append( this.digits[dig] != 0 ? this.digits[dig++] : '0' ); if(digits != 1) { // For E0 we would like to suppress the decimal point sb.Append( info.numberDecimalSeparator ); } while(--digits > 0) { sb.Append( this.digits[dig] != 0 ? this.digits[dig++] : '0' ); } int e = this.digits[0] == 0 ? 0 : this.scale - 1; FormatExponent( sb, e, expChar, info.positiveSign, info.negativeSign, 3 ); } // REVIEW: call the real wcslen? private static int wcslen( char[] c, int i ) { int j; for(j = i; j < c.Length; ++j) { if(c[j] == '\0') break; } return j - i; } private void FormatFixed( System.Text.StringBuilder sb , int digits , int[] groupDigits , String sDecimal , String sGroup , NumberFormatInfo info ) { // int bufferSize = 0; // the length of the result buffer string. int digPos = this.scale; int dig = 0; // = number->digits; if(digPos > 0) { if(groupDigits != null) { // index into the groupDigits array. int groupSizeIndex = 0; // the current total of group size. int groupSizeCount = groupDigits[groupSizeIndex]; // the length of groupDigits array. int groupSizeLen = groupDigits.Length; // the length of the result buffer string. int bufferSize = digPos; // the length of the group separator string. int groupSeparatorLen = sGroup.Length; // the current group size. int groupSize = 0; // // Find out the size of the string buffer for the result. // if(groupSizeLen != 0) // You can pass in 0 length arrays { while(digPos > groupSizeCount) { groupSize = groupDigits[groupSizeIndex]; if(groupSize == 0) { break; } bufferSize += groupSeparatorLen; if(groupSizeIndex < groupSizeLen - 1) { groupSizeIndex++; } groupSizeCount += groupDigits[groupSizeIndex]; if(groupSizeCount < 0 || bufferSize < 0) { throw new ArgumentOutOfRangeException(); // if we overflow //COMPlusThrow(kArgumentOutOfRangeException); } } // If you passed in an array with one // entry as 0, groupSizeCount == 0 if(groupSizeCount == 0) groupSize = 0; else groupSize = groupDigits[0]; } groupSizeIndex = 0; int digitCount = 0; int digLength = (int)wcslen( this.digits, dig ); int digStart = (digPos < digLength) ? digPos : digLength; char[] buffer = new char[bufferSize]; int p = bufferSize - 1; for(int i = digPos - 1; i >= 0; i--) { buffer[p--] = (i < digStart) ? this.digits[dig + i] : '0'; if(groupSize > 0) { digitCount++; if(digitCount == groupSize && i != 0) { for(int j = groupSeparatorLen - 1; j >= 0; j--) { buffer[p--] = sGroup[j]; } if(groupSizeIndex < groupSizeLen - 1) { groupSizeIndex++; groupSize = groupDigits[groupSizeIndex]; } digitCount = 0; } } } sb.Append( buffer ); dig += digStart; } else { do { sb.Append( this.digits[dig] != 0 ? this.digits[dig++] : '0' ); } while(--digPos > 0); } } else { sb.Append( '0' ); } if(digits > 0) { sb.Append( sDecimal ); while(digPos < 0 && digits > 0) { sb.Append( '0' ); digPos++; digits--; } while(digits > 0) { char ch = this.digits[dig]; if(ch == 0) { ch = '0'; } else { dig++; } sb.Append( ch ); digits--; } } } private void FormatNumber( System.Text.StringBuilder sb , int digits , NumberFormatInfo info ) { String fmt = this.negative ? negNumberFormats[info.numberNegativePattern] : posNumberFormat; int fmtIndex = 0; for(; fmtIndex < fmt.Length; fmtIndex++) { char ch = fmt[fmtIndex]; switch(ch) { case '#': FormatFixed( sb, digits, info.numberGroupSizes, info.numberDecimalSeparator, info.numberGroupSeparator, info ); break; case '-': sb.Append( info.negativeSign ); break; default: sb.Append( ch ); break; } } } private void FormatPercent( System.Text.StringBuilder sb , int digits , NumberFormatInfo info ) { String fmt = this.negative ? negPercentFormats[info.percentNegativePattern] : posPercentFormats[info.percentPositivePattern]; int fmtIndex = 0; char ch; while((ch = fmt[fmtIndex++]) != 0) { switch(ch) { case '#': FormatFixed( sb, digits, info.percentGroupSizes, info.percentDecimalSeparator, info.percentGroupSeparator, info ); break; case '-': sb.Append( info.negativeSign ); break; case '%': sb.Append( info.percentSymbol ); break; default: sb.Append( ch ); break; } } } private uint D32DivMod1E9( uint hi32, uint lo32, out uint newlo32 ) { ulong n = (((ulong)hi32) << 32) | lo32; newlo32 = (uint)(n / 1000000000); return (uint)(n % 1000000000); } //// private uint DecDivMod1E9( ref Decimal value ) //// { //// uint newhi, newmid, newlo; //// uint result = D32DivMod1E9( D32DivMod1E9( D32DivMod1E9( 0, //// value.hi32, //// out newhi ), //// value.mid32, //// out newmid ), //// value.lo32, //// out newlo ); //// value.hi32 = newhi; //// value.mid32 = newmid; //// value.lo32 = newlo; //// return result; //// } // markples: see also Lightning\Src\VM\COMNumber.cpp:: // unsigned int Int64DivMod1E9(unsigned __int64* value) // There's a x86 asm version there too. // The interface is different because Bartok does not support // taking the address of 64 bit values. private static ulong Int64DivMod1E9( ulong value, out uint rem ) { rem = (uint)(value % 1000000000); value /= 1000000000; return value; } public static bool TryParseDouble( String s, NumberStyles style, out double result ) { #if EXCEPTION_STRINGS throw new Exception( "System.Number.TryParseDouble not implemented in Bartok!" ); #else throw new Exception(); #endif } private const int DecimalPrecision = 29; } } ================================================ FILE: Zelig/Zelig/RunTime/Framework/mscorlib/System/Object.cs ================================================ // ==++== // // Copyright (c) Microsoft Corporation. All rights reserved. // // ==--== /*============================================================ ** ** Class: Object ** ** ** Object is the root class for all CLR objects. This class ** defines only the basics. ** ** ===========================================================*/ namespace System { using System; using System.Runtime.InteropServices; using System.Runtime.CompilerServices; using System.Runtime.ConstrainedExecution; ////using System.Runtime.Versioning; ////using CultureInfo = System.Globalization.CultureInfo; ////using FieldInfo = System.Reflection.FieldInfo; ////using BindingFlags = System.Reflection.BindingFlags; ////using RemotingException = System.Runtime.Remoting.RemotingException; // The Object is the root class for all object in the CLR System. Object // is the super class for all other CLR objects and provide a set of methods and low level // services to subclasses. These services include object synchronization and support for clone // operations. // //This class contains no data and does not need to be serializable ////[Serializable] [Microsoft.Zelig.Internals.WellKnownType( "System_Object" )] public class Object { // Creates a new instance of an Object. //// [ReliabilityContract( Consistency.WillNotCorruptState, Cer.MayFail )] public Object() { } // Returns a String which represents the object instance. The default // for an object is to return the fully qualified name of the class. // public virtual String ToString() { return GetType().ToString(); } // Returns a boolean indicating if the passed in object obj is // Equal to this. Equality is defined as object equality for reference // types and bitwise equality for value types. // Zelig generates proper Equals methods for all value types, so no reflection is involved. // [Microsoft.Zelig.Internals.WellKnownMethod( "Object_Equals" )] public virtual bool Equals( Object obj ) { return ReferenceEquals( this, obj ); } //// [ResourceExposure( ResourceScope.None )] //// [MethodImpl( MethodImplOptions.InternalCall )] //// internal static extern bool InternalEquals( Object objA, Object objB ); public static bool Equals( Object objA, Object objB ) { if(objA == objB) { return true; } if(objA == null || objB == null) { return false; } return objA.Equals( objB ); } //// [ReliabilityContract( Consistency.WillNotCorruptState, Cer.Success )] public static bool ReferenceEquals( Object objA, Object objB ) { return objA == objB; } // GetHashCode is intended to serve as a hash function for this object. // Based on the contents of the object, the hash function will return a suitable // value with a relatively random distribution over the various inputs. // // The default implementation returns the sync block index for this instance. // Calling it on the same object multiple times will return the same value, so // it will technically meet the needs of a hash function, but it's less than ideal. // Objects (& especially value classes) should override this method. // [Microsoft.Zelig.Internals.WellKnownMethod( "Object_GetHashCode" )] [MethodImpl( MethodImplOptions.InternalCall )] public extern virtual int GetHashCode(); //// { //// return InternalGetHashCode( this ); //// } //// //// // See INT32 ObjectNative::GetHashCodeEx(Object *objRef) for details. //// [ResourceExposure( ResourceScope.None )] //// [MethodImpl( MethodImplOptions.InternalCall )] //// internal static extern int InternalGetHashCode( Object obj ); // Returns a Type object which represent this object instance. // //// [ResourceExposure( ResourceScope.None )] [MethodImpl( MethodImplOptions.InternalCall )] public extern Type GetType(); // Allow an object to free resources before the object is reclaimed by the GC. // //// [ReliabilityContract( Consistency.WillNotCorruptState, Cer.Success )] ~Object() { } // Returns a new object instance that is a memberwise copy of this // object. This is always a shallow copy of the instance. The method is protected // so that other object may only call this method on themselves. It is entended to // support the ICloneable interface. // //// [ResourceExposure( ResourceScope.None )] [MethodImpl( MethodImplOptions.InternalCall )] protected extern Object MemberwiseClone(); //// // Sets the value specified in the variant on the field //// // //// private void FieldSetter( String typeName, String fieldName, Object val ) //// { //// // Extract the field info object //// FieldInfo fldInfo = GetFieldInfo( typeName, fieldName ); //// //// if(fldInfo.IsInitOnly) //// throw new FieldAccessException( Environment.GetResourceString( "FieldAccess_InitOnly" ) ); //// //// // Make sure that the value is compatible with the type //// // of field //// System.Runtime.Remoting.Messaging.Message.CoerceArg( val, fldInfo.FieldType ); //// //// // Set the value //// fldInfo.SetValue( this, val ); //// } //// //// // Gets the value specified in the variant on the field //// // //// private void FieldGetter( String typeName, String fieldName, ref Object val ) //// { //// // Extract the field info object //// FieldInfo fldInfo = GetFieldInfo( typeName, fieldName ); //// //// // Get the value //// val = fldInfo.GetValue( this ); //// } //// //// // Gets the field info object given the type name and field name. //// // //// private FieldInfo GetFieldInfo( String typeName, String fieldName ) //// { //// Type t = GetType(); //// while(null != t) //// { //// if(t.FullName.Equals( typeName )) //// { //// break; //// } //// //// t = t.BaseType; //// } //// //// if(t == null) //// { //// throw new RemotingException( String.Format( //// CultureInfo.CurrentCulture, Environment.GetResourceString( "Remoting_BadType" ), //// typeName ) ); //// } //// //// FieldInfo fldInfo = t.GetField( fieldName, BindingFlags.Public | //// BindingFlags.Instance | //// BindingFlags.IgnoreCase ); //// if(fldInfo == null) //// { //// throw new RemotingException( String.Format( //// CultureInfo.CurrentCulture, Environment.GetResourceString( "Remoting_BadField" ), //// fieldName, typeName ) ); //// } //// //// return fldInfo; //// } } //// //// ////// Internal methodtable used to instantiate the "canonical" methodtable for generic instantiations. ////// The name "__Canon" will never been seen by users but it will appear a lot in debugger stack traces ////// involving generics so it is kept deliberately short as to avoid being a nuisance. //// ////[Serializable] ////internal class __Canon ////{ ////} } ================================================ FILE: Zelig/Zelig/RunTime/Framework/mscorlib/System/ObjectDisposedException.cs ================================================ // ==++== // // Copyright (c) Microsoft Corporation. All rights reserved. // // ==--== namespace System { using System; using System.Runtime.Serialization; using System.Globalization; ////using System.Security.Permissions; /// /// The exception that is thrown when accessing an object that was /// disposed. /// [Serializable()] public class ObjectDisposedException : InvalidOperationException { private String objectName; // This constructor should only be called by the EE (COMPlusThrow) private ObjectDisposedException() : this( null, Environment.GetResourceString( "ObjectDisposed_Generic" ) ) { } public ObjectDisposedException( String objectName ) : this( objectName, Environment.GetResourceString( "ObjectDisposed_Generic" ) ) { } public ObjectDisposedException( String objectName, String message ) : base( message ) { //// SetErrorCode( __HResults.COR_E_OBJECTDISPOSED ); this.objectName = objectName; } public ObjectDisposedException( String message, Exception innerException ) : base( message, innerException ) { //// SetErrorCode( __HResults.COR_E_OBJECTDISPOSED ); } /// /// Gets the text for the message for this exception. /// public override String Message { get { String name = ObjectName; if(name == null || name.Length == 0) { return base.Message; } #if EXCEPTION_STRINGS return base.Message + Environment.NewLine + String.Format( CultureInfo.CurrentCulture, Environment.GetResourceString( "ObjectDisposed_ObjectName_Name" ), name ); #else return base.Message + Environment.NewLine + name; #endif } } public String ObjectName { get { if(objectName == null) { return String.Empty; } return objectName; } } //// protected ObjectDisposedException( SerializationInfo info, StreamingContext context ) : base( info, context ) //// { //// objectName = info.GetString( "ObjectName" ); //// } //// //// [SecurityPermissionAttribute( SecurityAction.LinkDemand, Flags = SecurityPermissionFlag.SerializationFormatter )] //// public override void GetObjectData( SerializationInfo info, StreamingContext context ) //// { //// base.GetObjectData( info, context ); //// info.AddValue( "ObjectName", ObjectName, typeof( String ) ); //// } } } ================================================ FILE: Zelig/Zelig/RunTime/Framework/mscorlib/System/ObsoleteAttribute.cs ================================================ // ==++== // // Copyright (c) Microsoft Corporation. All rights reserved. // // ==--== /*============================================================ ** ** Class: ObsoleteAttribute ** ** ** Purpose: Attribute for functions, etc that will be removed. ** ** ===========================================================*/ namespace System { using System; ////using System.Runtime.Remoting; // This attribute is attached to members that are not to be used any longer. // Message is some human readable explanation of what to use // Error indicates if the compiler should treat usage of such a method as an // error. (this would be used if the actual implementation of the obsolete // method's implementation had changed). // [Serializable] [AttributeUsage( AttributeTargets.Class | AttributeTargets.Struct | AttributeTargets.Enum | AttributeTargets.Interface | AttributeTargets.Constructor | AttributeTargets.Method | AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Event | AttributeTargets.Delegate , Inherited = false )] public sealed class ObsoleteAttribute : Attribute { private String m_message; private bool m_error; public ObsoleteAttribute() { m_message = null; m_error = false; } public ObsoleteAttribute( String message ) { m_message = message; m_error = false; } public ObsoleteAttribute( String message, bool error ) { m_message = message; m_error = error; } public String Message { get { return m_message; } } public bool IsError { get { return m_error; } } } } ================================================ FILE: Zelig/Zelig/RunTime/Framework/mscorlib/System/OperationCanceledException.cs ================================================ // Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. /*============================================================ ** ** ** ** Purpose: Exception for cancelled IO requests. ** ** ===========================================================*/ using System; using System.Runtime.Serialization; using System.Threading; namespace System { [Serializable] [System.Runtime.InteropServices.ComVisible(true)] public class OperationCanceledException : SystemException { [NonSerialized] private CancellationToken _cancellationToken; public CancellationToken CancellationToken { get { return _cancellationToken; } private set { _cancellationToken = value; } } #if EXCEPTION_STRINGS public OperationCanceledException() : base(Environment.GetResourceString("OperationCanceled")) #else // EXCEPTION_STRINGS public OperationCanceledException() #endif // EXCEPTION_STRINGS { } public OperationCanceledException(string message) : base(message) { } public OperationCanceledException(string message, Exception innerException) : base(message, innerException) { } public OperationCanceledException(CancellationToken token) : this() { CancellationToken = token; } public OperationCanceledException(string message, CancellationToken token) : this(message) { CancellationToken = token; } public OperationCanceledException(string message, Exception innerException, CancellationToken token) : this(message, innerException) { CancellationToken = token; } #if DISABLED_FOR_LLILUM protected OperationCanceledException(SerializationInfo info, StreamingContext context) : base (info, context) { } #endif // DISABLED_FOR_LLILUM } } ================================================ FILE: Zelig/Zelig/RunTime/Framework/mscorlib/System/OutOfMemoryException.cs ================================================ // ==++== // // Copyright (c) Microsoft Corporation. All rights reserved. // // ==--== /*============================================================================= ** ** Class: OutOfMemoryException ** ** ** Purpose: The exception class for OOM. ** ** =============================================================================*/ namespace System { using System; using System.Runtime.Serialization; [Serializable] public class OutOfMemoryException : SystemException { public OutOfMemoryException() : base( GetMessageFromNativeResources( ExceptionMessageKind.OutOfMemory ) ) { } public OutOfMemoryException( String message ) : base( message ) { } public OutOfMemoryException( String message, Exception innerException ) : base( message, innerException ) { } //// protected OutOfMemoryException( SerializationInfo info, StreamingContext context ) : base( info, context ) //// { //// } } } ================================================ FILE: Zelig/Zelig/RunTime/Framework/mscorlib/System/OverflowException.cs ================================================ // ==++== // // Copyright (c) Microsoft Corporation. All rights reserved. // // ==--== /*============================================================================= ** ** Class: OverflowException ** ** ** Purpose: Exception class for Arthimatic Overflows. ** ** =============================================================================*/ namespace System { using System; using System.Runtime.Serialization; [Serializable] public class OverflowException : ArithmeticException { #if EXCEPTION_STRINGS public OverflowException() : base( Environment.GetResourceString( "Arg_OverflowException" ) ) #else public OverflowException() #endif { } public OverflowException( String message ) : base( message ) { } public OverflowException( String message, Exception innerException ) : base( message, innerException ) { } //// protected OverflowException( SerializationInfo info, StreamingContext context ) : base( info, context ) //// { //// } } } ================================================ FILE: Zelig/Zelig/RunTime/Framework/mscorlib/System/ParamArrayAttribute.cs ================================================ // ==++== // // Copyright (c) Microsoft Corporation. All rights reserved. // // ==--== /*============================================================================= ** ** Class: ParamArrayAttribute ** ** ** Purpose: Container for assemblies. ** ** =============================================================================*/ namespace System { //This class contains only static members and does not need to be serializable [AttributeUsage( AttributeTargets.Parameter, Inherited = true, AllowMultiple = false )] public sealed class ParamArrayAttribute : Attribute { public ParamArrayAttribute() { } } } ================================================ FILE: Zelig/Zelig/RunTime/Framework/mscorlib/System/ParseNumbers.cs ================================================ // ==++== // // Copyright (c) Microsoft Corporation. All rights reserved. // // ==--== /*============================================================ ** ** Class: ParseNumbers ** ** ** Purpose: Methods for Parsing numbers and Strings. ** All methods are implemented in native. ** ** ===========================================================*/ namespace System { //This class contains only static members and does not need to be serializable. using System; using System.Runtime.CompilerServices; ////using System.Runtime.Versioning; internal static class ParseNumbers { internal const int PrintAsI1 = 0x40; internal const int PrintAsI2 = 0x80; internal const int PrintAsI4 = 0x100; internal const int TreatAsUnsigned = 0x200; internal const int TreatAsI1 = 0x400; internal const int TreatAsI2 = 0x800; internal const int IsTight = 0x1000; internal const int NoSpace = 0x2000; // // // NATIVE METHODS // For comments on these methods please see $\src\vm\COMUtilNative.cpp // public unsafe static long StringToLong( System.String s, int radix, int flags ) { return StringToLong( s, radix, flags, null ); } //// [ResourceExposure( ResourceScope.None )] [MethodImplAttribute( MethodImplOptions.InternalCall )] public unsafe extern static long StringToLong( System.String s, int radix, int flags, int* currPos ); public unsafe static long StringToLong( System.String s, int radix, int flags, ref int currPos ) { fixed(int* ppos = &currPos) { return StringToLong( s, radix, flags, ppos ); } } public unsafe static int StringToInt( System.String s, int radix, int flags ) { return StringToInt( s, radix, flags, null ); } //// [ResourceExposure( ResourceScope.None )] [MethodImplAttribute( MethodImplOptions.InternalCall )] public unsafe extern static int StringToInt( System.String s, int radix, int flags, int* currPos ); public unsafe static int StringToInt( System.String s, int radix, int flags, ref int currPos ) { fixed(int* ppos = &currPos) { return StringToInt( s, radix, flags, ppos ); } } //// [ResourceExposure( ResourceScope.None )] [MethodImplAttribute( MethodImplOptions.InternalCall )] public extern static String IntToString( int l, int radix, int width, char paddingChar, int flags ); //// [ResourceExposure( ResourceScope.None )] [MethodImplAttribute( MethodImplOptions.InternalCall )] public extern static String LongToString( long l, int radix, int width, char paddingChar, int flags ); } } ================================================ FILE: Zelig/Zelig/RunTime/Framework/mscorlib/System/Random.cs ================================================ // ==++== // // Copyright (c) Microsoft Corporation. All rights reserved. // // ==--== /*============================================================ ** ** Class: Random ** ** ** Purpose: A random number generator. ** ** ===========================================================*/ namespace System { using System; using System.Runtime.CompilerServices; using System.Globalization; [Serializable()] public class Random { // // Private Constants // private const int MBIG = Int32.MaxValue; private const int MSEED = 161803398; private const int MZ = 0; // // Member Variables // private int inext, inextp; private int[] SeedArray = new int[56]; // // Public Constants // // // Native Declarations // // // Constructors // public Random() : this( Environment.TickCount ) { } public Random( int Seed ) { int ii; int mj, mk; //Initialize our Seed array. //This algorithm comes from Numerical Recipes in C (2nd Ed.) mj = MSEED - Math.Abs( Seed ); SeedArray[55] = mj; mk = 1; for(int i = 1; i < 55; i++) { //Apparently the range [1..55] is special (Knuth) and so we're wasting the 0'th position. ii = (21 * i) % 55; SeedArray[ii] = mk; mk = mj - mk; if(mk < 0) mk += MBIG; mj = SeedArray[ii]; } for(int k = 1; k < 5; k++) { for(int i = 1; i < 56; i++) { SeedArray[i] -= SeedArray[1 + (i + 30) % 55]; if(SeedArray[i] < 0) SeedArray[i] += MBIG; } } inext = 0; inextp = 21; Seed = 1; } // // Package Private Methods // /*====================================Sample==================================== **Action: Return a new random number [0..1) and reSeed the Seed array. **Returns: A double [0..1) **Arguments: None **Exceptions: None ==============================================================================*/ protected virtual double Sample() { //Including this division at the end gives us significantly improved //random number distribution. return (InternalSample() * (1.0 / MBIG)); } private int InternalSample() { int retVal; int locINext = inext; int locINextp = inextp; if(++locINext >= 56) locINext = 1; if(++locINextp >= 56) locINextp = 1; retVal = SeedArray[locINext] - SeedArray[locINextp]; if(retVal < 0) retVal += MBIG; SeedArray[locINext] = retVal; inext = locINext; inextp = locINextp; return retVal; } // // Public Instance Methods // /*=====================================Next===================================== **Returns: An int [0..Int32.MaxValue) **Arguments: None **Exceptions: None. ==============================================================================*/ public virtual int Next() { return InternalSample(); } private double GetSampleForLargeRange() { // The distribution of double value returned by Sample // is not distributed well enough for a large range. // If we use Sample for a range [Int32.MinValue..Int32.MaxValue) // We will end up getting even numbers only. int result = InternalSample(); // Note we can't use addition here. The distribution will be bad if we do that. bool negative = (InternalSample() % 2 == 0) ? true : false; // decide the sign based on second sample if(negative) { result = -result; } double d = result; d += (Int32.MaxValue - 1); // get a number in range [0 .. 2 * Int32MaxValue - 1) d /= 2 * (uint)Int32.MaxValue - 1; return d; } /*=====================================Next===================================== **Returns: An int [minvalue..maxvalue) **Arguments: minValue -- the least legal value for the Random number. ** maxValue -- One greater than the greatest legal return value. **Exceptions: None. ==============================================================================*/ public virtual int Next( int minValue, int maxValue ) { if(minValue > maxValue) { #if EXCEPTION_STRINGS throw new ArgumentOutOfRangeException( "minValue", String.Format( CultureInfo.CurrentCulture, Environment.GetResourceString( "Argument_MinMaxValue" ), "minValue", "maxValue" ) ); #else throw new ArgumentOutOfRangeException(); #endif } long range = (long)maxValue - minValue; if(range <= (long)Int32.MaxValue) { return ((int)(Sample() * range) + minValue); } else { return (int)((long)(GetSampleForLargeRange() * range) + minValue); } } /*=====================================Next===================================== **Returns: An int [0..maxValue) **Arguments: maxValue -- One more than the greatest legal return value. **Exceptions: None. ==============================================================================*/ public virtual int Next( int maxValue ) { if(maxValue < 0) { #if EXCEPTION_STRINGS throw new ArgumentOutOfRangeException( "maxValue", String.Format( CultureInfo.CurrentCulture, Environment.GetResourceString( "ArgumentOutOfRange_MustBePositive" ), "maxValue" ) ); #else throw new ArgumentOutOfRangeException(); #endif } return (int)(Sample() * maxValue); } /*=====================================Next===================================== **Returns: A double [0..1) **Arguments: None **Exceptions: None ==============================================================================*/ public virtual double NextDouble() { return Sample(); } /*==================================NextBytes=================================== **Action: Fills the byte array with random bytes [0..0x7f]. The entire array is filled. **Returns:Void **Arugments: buffer -- the array to be filled. **Exceptions: None ==============================================================================*/ public virtual void NextBytes( byte[] buffer ) { if(buffer == null) #if EXCEPTION_STRINGS throw new ArgumentNullException( "buffer" ); #else throw new ArgumentNullException(); #endif for(int i = 0; i < buffer.Length; i++) { buffer[i] = (byte)(InternalSample() % (Byte.MaxValue + 1)); } } } } ================================================ FILE: Zelig/Zelig/RunTime/Framework/mscorlib/System/RankException.cs ================================================ // ==++== // // Copyright (c) Microsoft Corporation. All rights reserved. // // ==--== /*============================================================================= ** ** Class: RankException ** ** ** Purpose: For methods that are passed arrays with the wrong number of ** dimensions. ** ** =============================================================================*/ namespace System { using System; using System.Runtime.Serialization; [Serializable] public class RankException : SystemException { public RankException() : base( Environment.GetResourceString( "Arg_RankException" ) ) { } public RankException( String message ) : base( message ) { } public RankException( String message, Exception innerException ) : base( message, innerException ) { } //// protected RankException( SerializationInfo info, StreamingContext context ) : base( info, context ) //// { //// } } } ================================================ FILE: Zelig/Zelig/RunTime/Framework/mscorlib/System/Reflection/Assembly.cs ================================================ // ==++== // // Copyright (c) Microsoft Corporation. All rights reserved. // // ==--== /*============================================================================= ** ** Class: Assembly ** ** ** Purpose: For Assembly-related stuff. ** ** =============================================================================*/ namespace System.Reflection { using System; using System.Collections; ////using System.Security; ////using System.Security.Policy; ////using System.Security.Permissions; ////using System.IO; ////using System.Reflection.Emit; ////using System.Reflection.Cache; using System.Configuration.Assemblies; using System.Runtime.InteropServices; using System.Runtime.CompilerServices; using System.Runtime.Serialization; using System.Threading; ////using System.Runtime.Versioning; ////using Microsoft.Win32; ////using BinaryFormatter = System.Runtime.Serialization.Formatters.Binary.BinaryFormatter; ////using IEvidenceFactory = System.Security.IEvidenceFactory; ////using CultureInfo = System.Globalization.CultureInfo; ////using SecurityZone = System.Security.SecurityZone; ////using StringBuilder = System.Text.StringBuilder; ////using StackCrawlMark = System.Threading.StackCrawlMark; ////using __HResults = System.__HResults; ////[Serializable] ////public delegate Module ModuleResolveEventHandler( Object sender, ResolveEventArgs e ); [Serializable] public class Assembly /*: IEvidenceFactory, ICustomAttributeProvider, ISerializable*/ { //// private const String s_localFilePrefix = "file:"; //// //// // READ ME //// // If you modify any of these fields, you must also update the //// // AssemblyBaseObject structure in object.h //// internal AssemblyBuilderData m_assemblyData; //// //// [method: SecurityPermissionAttribute( SecurityAction.LinkDemand, ControlAppDomain = true )] //// public event ModuleResolveEventHandler ModuleResolve; //// //// private InternalCache m_cachedData; #pragma warning disable 649 // Field 'field' is never assigned to, and will always have its default value 'value' private IntPtr m_assembly; // slack for ptr datum on unmanaged side #pragma warning restore 649 //// [ResourceExposure( ResourceScope.Machine )] //// [MethodImpl( MethodImplOptions.InternalCall )] //// private static extern void GetCodeBase( AssemblyHandle assembly, bool copiedName, StringHandleOnStack retString ); //// //// internal String GetCodeBase( bool copiedName ) //// { //// String codeBase = null; //// //// GetCodeBase( GetNativeHandle(), copiedName, JitHelpers.GetStringHandleOnStack( ref codeBase ) ); //// //// return codeBase; //// } //// //// public virtual String CodeBase //// { //// [ResourceExposure( ResourceScope.Machine )] //// [ResourceConsumption( ResourceScope.Machine )] //// get //// { //// String codeBase = GetCodeBase( false ); //// //// VerifyCodeBaseDiscovery( codeBase ); //// //// return codeBase; //// } //// } //// //// //// public virtual String EscapedCodeBase //// { //// [ResourceExposure( ResourceScope.Machine )] //// [ResourceConsumption( ResourceScope.Machine )] //// get //// { //// return AssemblyName.EscapeCodeBase( CodeBase ); //// } //// } //// //// public virtual AssemblyName GetName() //// { //// return GetName( false ); //// } internal AssemblyHandle AssemblyHandle { get { return new AssemblyHandle( m_assembly ); } } //// // Returns handle for interop with EE. The handle is guaranteed to be non-null. //// internal unsafe AssemblyHandle GetNativeHandle() //// { //// IntPtr assembly = m_assembly; //// //// // This should never happen under normal circumstances. m_assembly is always assigned before it is handed out to the user. //// // There are ways how to create an unitialized objects through remoting, etc. Avoid AVing in the EE by throwing a nice //// // exception here. //// if(assembly.IsNull()) //// { //// throw new ArgumentException( Environment.GetResourceString( "Argument_InvalidHandle" ) ); //// } //// //// return new AssemblyHandle( assembly ); //// } //// // If the assembly is copied before it is loaded, the codebase will be set to the //// // actual file loaded if copiedName is true. If it is false, then the original code base //// // is returned. //// [ResourceExposure( ResourceScope.None )] //// [ResourceConsumption( ResourceScope.Machine, ResourceScope.Machine )] //// public virtual AssemblyName GetName( bool copiedName ) //// { //// AssemblyName an = new AssemblyName(); //// //// String codeBase = GetCodeBase( copiedName ); //// VerifyCodeBaseDiscovery( codeBase ); //// //// an.Init( GetSimpleName(), //// GetPublicKey(), //// null, // public key token //// GetVersion(), //// GetLocale(), //// GetHashAlgorithm(), //// AssemblyVersionCompatibility.SameMachine, //// codeBase, //// GetFlags() | AssemblyNameFlags.PublicKey, //// null ); // strong name key pair //// //// an.ProcessorArchitecture = ComputeProcArchIndex(); //// return an; //// } //// //// [MethodImpl( MethodImplOptions.InternalCall )] //// [SuppressUnmanagedCodeSecurity] //// [ResourceExposure( ResourceScope.None )] //// private extern static void GetFullName( AssemblyHandle assembly, StringHandleOnStack retString ); //// //// public virtual String FullName //// { //// get //// { //// // If called by Object.ToString(), return val may be NULL. //// String s; //// if((s = (String)Cache[CacheObjType.AssemblyName]) != null) //// { //// return s; //// } //// //// GetFullName( GetNativeHandle(), JitHelpers.GetStringHandleOnStack( ref s ) ); //// if(s != null) //// { //// Cache[CacheObjType.AssemblyName] = s; //// } //// //// return s; //// } //// } public static String CreateQualifiedName( String assemblyName, String typeName ) { return typeName + ", " + assemblyName; } //// [ResourceExposure( ResourceScope.None )] //// [MethodImpl( MethodImplOptions.InternalCall )] //// [SuppressUnmanagedCodeSecurity] //// private static extern RuntimeMethodHandle GetEntryPoint( AssemblyHandle assembly ); //// //// public virtual MethodInfo EntryPoint //// { //// get //// { //// RuntimeMethodHandle methodHandle = GetEntryPoint( GetNativeHandle() ); //// //// if(methodHandle.IsNullHandle()) //// { //// return null; //// } //// //// return (MethodInfo)RuntimeType.GetMethodBase( methodHandle ); //// } //// } //// //// public static Assembly GetAssembly( Type type ) //// { //// if(type == null) //// { //// throw new ArgumentNullException( "type" ); //// } //// //// Module m = type.Module; //// if(m == null) //// { //// return null; //// } //// else //// { //// return m.Assembly; //// } //// } //// //// public virtual Type GetType( String name ) //// { //// return GetType( name, false, false ); //// } //// //// public virtual Type GetType( String name, bool throwOnError ) //// { //// return GetType( name, throwOnError, false ); //// } //// //// [ResourceExposure( ResourceScope.None )] //// [MethodImpl( MethodImplOptions.InternalCall )] //// [SuppressUnmanagedCodeSecurity] //// private static extern RuntimeTypeHandle GetType( AssemblyHandle assembly, String name, bool throwOnError, bool ignoreCase ); //// //// public Type GetType( String name, bool throwOnError, bool ignoreCase ) //// { //// return GetType( GetNativeHandle(), name, throwOnError, ignoreCase ).GetRuntimeType(); //// } //// //// [ResourceExposure( ResourceScope.None )] //// [MethodImpl( MethodImplOptions.InternalCall )] //// [SuppressUnmanagedCodeSecurity] //// private extern static void GetExportedTypes( AssemblyHandle assembly, ObjectHandleOnStack retTypes ); //// //// public virtual Type[] GetExportedTypes() //// { //// Type[] types = null; //// //// GetExportedTypes( GetNativeHandle(), JitHelpers.GetObjectHandleOnStack( ref types ) ); //// //// return types; //// } //// //// [ResourceExposure( ResourceScope.None )] //// [ResourceConsumption( ResourceScope.Machine | ResourceScope.Assembly, ResourceScope.Machine | ResourceScope.Assembly )] //// public virtual Type[] GetTypes() //// { //// Module[] m = GetModules( true, false ); //// int iNumModules = m.Length; //// int iFinalLength = 0; //// StackCrawlMark stackMark = StackCrawlMark.LookForMyCaller; //// Type[][] ModuleTypes = new Type[iNumModules][]; //// //// for(int i = 0; i < iNumModules; i++) //// { //// ModuleTypes[i] = m[i].GetTypes( ref stackMark ); //// //// iFinalLength += ModuleTypes[i].Length; //// } //// //// int iCurrent = 0; //// Type[] ret = new Type[iFinalLength]; //// for(int i = 0; i < iNumModules; i++) //// { //// int iLength = ModuleTypes[i].Length; //// //// Array.Copy( ModuleTypes[i], 0, ret, iCurrent, iLength ); //// //// iCurrent += iLength; //// } //// //// return ret; //// } //// //// // Load a resource based on the NameSpace of the type. //// public virtual Stream GetManifestResourceStream( Type type, String name ) //// { //// StackCrawlMark stackMark = StackCrawlMark.LookForMyCaller; //// //// return GetManifestResourceStream( type, name, false, ref stackMark ); //// } //// //// public virtual Stream GetManifestResourceStream( String name ) //// { //// StackCrawlMark stackMark = StackCrawlMark.LookForMyCaller; //// //// return GetManifestResourceStream( name, ref stackMark, false ); //// } //// //// public Assembly GetSatelliteAssembly( CultureInfo culture ) //// { //// return InternalGetSatelliteAssembly( culture, null, true ); //// } //// //// // Useful for binding to a very specific version of a satellite assembly //// public Assembly GetSatelliteAssembly( CultureInfo culture, Version version ) //// { //// return InternalGetSatelliteAssembly( culture, version, true ); //// } //// //// public virtual Evidence Evidence //// { //// [SecurityPermissionAttribute( SecurityAction.Demand, ControlEvidence = true )] //// get //// { //// return nGetEvidence().Copy(); //// } //// } //// //// //// // ISerializable implementation //// [SecurityPermissionAttribute( SecurityAction.LinkDemand, Flags = SecurityPermissionFlag.SerializationFormatter )] //// public virtual void GetObjectData( SerializationInfo info, StreamingContext context ) //// { //// if(info == null) //// { //// throw new ArgumentNullException( "info" ); //// } //// //// //// UnitySerializationHolder.GetUnitySerializationInfo( info, UnitySerializationHolder.AssemblyUnity, this.FullName, this ); //// } //// //// internal bool AptcaCheck( Assembly sourceAssembly ) //// { //// return AssemblyHandle.AptcaCheck( sourceAssembly.AssemblyHandle ); //// } //// //// public Module ManifestModule //// { //// [ResourceExposure( ResourceScope.None )] //// [ResourceConsumption( ResourceScope.Machine | ResourceScope.Assembly, ResourceScope.Machine | ResourceScope.Assembly )] //// get //// { //// return AssemblyHandle.GetManifestModule().GetModule(); //// } //// } //// //// public virtual Object[] GetCustomAttributes( bool inherit ) //// { //// return CustomAttribute.GetCustomAttributes( this, typeof( object ) as RuntimeType ); //// } //// //// public virtual Object[] GetCustomAttributes( Type attributeType, bool inherit ) //// { //// if(attributeType == null) //// { //// throw new ArgumentNullException( "attributeType" ); //// } //// //// RuntimeType attributeRuntimeType = attributeType.UnderlyingSystemType as RuntimeType; //// //// if(attributeRuntimeType == null) //// { //// throw new ArgumentException( Environment.GetResourceString( "Arg_MustBeType" ), "attributeType" ); //// } //// //// return CustomAttribute.GetCustomAttributes( this, attributeRuntimeType ); //// } //// //// public virtual bool IsDefined( Type attributeType, bool inherit ) //// { //// if(attributeType == null) //// { //// throw new ArgumentNullException( "attributeType" ); //// } //// //// RuntimeType attributeRuntimeType = attributeType.UnderlyingSystemType as RuntimeType; //// //// if(attributeRuntimeType == null) //// { //// throw new ArgumentException( Environment.GetResourceString( "Arg_MustBeType" ), "caType" ); //// } //// //// return CustomAttribute.IsDefined( this, attributeRuntimeType ); //// } //// //// //// // Locate an assembly by the name of the file containing the manifest. //// [ResourceExposure( ResourceScope.Machine )] //// [ResourceConsumption( ResourceScope.Machine )] //// public static Assembly LoadFrom( String assemblyFile ) //// { //// // The stack mark is used for MDA filtering //// StackCrawlMark stackMark = StackCrawlMark.LookForMyCaller; //// //// return InternalLoadFrom( assemblyFile, //// null, // securityEvidence //// null, // hashValue //// AssemblyHashAlgorithm.None, //// false, // forIntrospection //// ref stackMark ); //// } //// //// // Locate an assembly for reflection by the name of the file containing the manifest. //// [ResourceExposure( ResourceScope.Machine )] //// [ResourceConsumption( ResourceScope.Machine )] //// public static Assembly ReflectionOnlyLoadFrom( String assemblyFile ) //// { //// // The stack mark is ingored for ReflectionOnlyLoadFrom //// StackCrawlMark stackMark = StackCrawlMark.LookForMyCaller; //// //// return InternalLoadFrom( assemblyFile, //// null, //securityEvidence //// null, //hashValue //// AssemblyHashAlgorithm.None, //// true, //forIntrospection //// ref stackMark ); //// } //// //// // Evidence is protected in Assembly.Load() //// [ResourceExposure( ResourceScope.Machine )] //// [ResourceConsumption( ResourceScope.Machine )] //// public static Assembly LoadFrom( String assemblyFile, Evidence securityEvidence ) //// { //// // The stack mark is used for MDA filtering //// StackCrawlMark stackMark = StackCrawlMark.LookForMyCaller; //// //// return InternalLoadFrom( assemblyFile, //// securityEvidence, //// null, // hashValue //// AssemblyHashAlgorithm.None, //// false, // forIntrospection //// ref stackMark ); //// } //// //// // Evidence is protected in Assembly.Load() //// [ResourceExposure( ResourceScope.Machine )] //// [ResourceConsumption( ResourceScope.Machine )] //// public static Assembly LoadFrom( String assemblyFile, Evidence securityEvidence, byte[] hashValue, AssemblyHashAlgorithm hashAlgorithm ) //// { //// // The stack mark is used for MDA filtering //// StackCrawlMark stackMark = StackCrawlMark.LookForMyCaller; //// //// return InternalLoadFrom( assemblyFile, securityEvidence, hashValue, hashAlgorithm, false, ref stackMark ); //// } //// //// //// [ResourceExposure( ResourceScope.Machine )] //// [ResourceConsumption( ResourceScope.Machine )] //// private static Assembly InternalLoadFrom( String assemblyFile , //// Evidence securityEvidence , //// byte[] hashValue , //// AssemblyHashAlgorithm hashAlgorithm , //// bool forIntrospection , //// ref StackCrawlMark stackMark ) //// { //// if(assemblyFile == null) //// { //// throw new ArgumentNullException( "assemblyFile" ); //// } //// //// AssemblyName an = new AssemblyName(); //// //// an.CodeBase = assemblyFile; //// an.SetHashControl( hashValue, hashAlgorithm ); //// //// return InternalLoad( an, securityEvidence, ref stackMark, forIntrospection ); //// } //// //// //// // Locate an assembly by the long form of the assembly name. //// // eg. "Toolbox.dll, version=1.1.10.1220, locale=en, publickey=1234567890123456789012345678901234567890" //// public static Assembly Load( String assemblyString ) //// { //// StackCrawlMark stackMark = StackCrawlMark.LookForMyCaller; //// //// return InternalLoad( assemblyString, null, ref stackMark, false ); //// } //// //// // Locate an assembly for reflection by the long form of the assembly name. //// // eg. "Toolbox.dll, version=1.1.10.1220, locale=en, publickey=1234567890123456789012345678901234567890" //// // //// public static Assembly ReflectionOnlyLoad( String assemblyString ) //// { //// StackCrawlMark stackMark = StackCrawlMark.LookForMyCaller; //// //// return InternalLoad( assemblyString, null, ref stackMark, true /*forIntrospection*/); //// } //// //// public static Assembly Load( String assemblyString, Evidence assemblySecurity ) //// { //// StackCrawlMark stackMark = StackCrawlMark.LookForMyCaller; //// //// return InternalLoad( assemblyString, assemblySecurity, ref stackMark, false ); //// } //// //// // Locate an assembly by its name. The name can be strong or //// // weak. The assembly is loaded into the domain of the caller. //// static public Assembly Load( AssemblyName assemblyRef ) //// { //// StackCrawlMark stackMark = StackCrawlMark.LookForMyCaller; //// //// return InternalLoad( assemblyRef, null, ref stackMark, false ); //// } //// //// //// static public Assembly Load( AssemblyName assemblyRef, Evidence assemblySecurity ) //// { //// StackCrawlMark stackMark = StackCrawlMark.LookForMyCaller; //// //// return InternalLoad( assemblyRef, assemblySecurity, ref stackMark, false ); //// } //// //// // used by vm //// static unsafe private IntPtr LoadWithPartialNameHack( String partialName, bool cropPublicKey ) //// { //// StackCrawlMark stackMark = StackCrawlMark.LookForMyCaller; //// //// Assembly result = null; //// AssemblyName an = new AssemblyName( partialName ); //// //// if(!IsSimplyNamed( an )) //// { //// if(cropPublicKey) //// { //// an.SetPublicKey( null ); //// an.SetPublicKeyToken( null ); //// } //// //// AssemblyName GACAssembly = EnumerateCache( an ); //// if(GACAssembly != null) //// { //// result = InternalLoad( GACAssembly, null, ref stackMark, false ); //// } //// } //// //// if(result == null) //// { //// return (IntPtr)0; //// } //// //// return (IntPtr)result.AssemblyHandle.Value; //// } //// //// [Obsolete( "This method has been deprecated. Please use Assembly.Load() instead. http://go.microsoft.com/fwlink/?linkid=14202" )] //// static public Assembly LoadWithPartialName( String partialName ) //// { //// StackCrawlMark stackMark = StackCrawlMark.LookForMyCaller; //// //// return LoadWithPartialNameInternal( partialName, null, ref stackMark ); //// } //// //// [Obsolete( "This method has been deprecated. Please use Assembly.Load() instead. http://go.microsoft.com/fwlink/?linkid=14202" )] //// static public Assembly LoadWithPartialName( String partialName, Evidence securityEvidence ) //// { //// StackCrawlMark stackMark = StackCrawlMark.LookForMyCaller; //// //// return LoadWithPartialNameInternal( partialName, securityEvidence, ref stackMark ); //// } //// //// static internal Assembly LoadWithPartialNameInternal( String partialName, Evidence securityEvidence, ref StackCrawlMark stackMark ) //// { //// if(securityEvidence != null) //// { //// new SecurityPermission( SecurityPermissionFlag.ControlEvidence ).Demand(); //// } //// //// Assembly result = null; //// AssemblyName an = new AssemblyName( partialName ); //// try //// { //// result = nLoad( an, null, securityEvidence, null, ref stackMark, true, false ); //// } //// catch(Exception e) //// { //// if(e.IsTransient) //// { //// throw e; //// } //// //// if(IsSimplyNamed( an )) //// { //// return null; //// } //// //// AssemblyName GACAssembly = EnumerateCache( an ); //// if(GACAssembly != null) //// { //// return InternalLoad( GACAssembly, securityEvidence, ref stackMark, false ); //// } //// } //// //// return result; //// } //// //// //// [ResourceExposure( ResourceScope.None )] //// [MethodImpl( MethodImplOptions.InternalCall )] //// private static extern bool IsReflectionOnly( IntPtr assembly ); //// //// public virtual bool ReflectionOnly //// { //// get //// { //// return IsReflectionOnly( GetNativeHandle().Value ); //// } //// } //// //// //// static private AssemblyName EnumerateCache( AssemblyName partialName ) //// { //// new SecurityPermission( SecurityPermissionFlag.UnmanagedCode ).Assert(); //// //// partialName.Version = null; //// //// ArrayList a = new ArrayList(); //// Fusion.ReadCache( a, partialName.FullName, ASM_CACHE.GAC ); //// //// IEnumerator myEnum = a.GetEnumerator(); //// AssemblyName ainfoBest = null; //// CultureInfo refCI = partialName.CultureInfo; //// //// while(myEnum.MoveNext()) //// { //// AssemblyName ainfo = new AssemblyName( (String)myEnum.Current ); //// //// if(CulturesEqual( refCI, ainfo.CultureInfo )) //// { //// if(ainfoBest == null) //// { //// ainfoBest = ainfo; //// } //// else //// { //// // Choose highest version //// if(ainfo.Version > ainfoBest.Version) //// { //// ainfoBest = ainfo; //// } //// } //// } //// } //// //// return ainfoBest; //// } //// //// static private bool CulturesEqual( CultureInfo refCI, CultureInfo defCI ) //// { //// bool defNoCulture = defCI.Equals( CultureInfo.InvariantCulture ); //// //// // cultured asms aren't allowed to be bound to if //// // the ref doesn't ask for them specifically //// if((refCI == null) || refCI.Equals( CultureInfo.InvariantCulture )) //// { //// return defNoCulture; //// } //// //// if(defNoCulture || (!defCI.Equals( refCI ))) //// { //// return false; //// } //// //// return true; //// } //// //// static private bool IsSimplyNamed( AssemblyName partialName ) //// { //// byte[] pk = partialName.GetPublicKeyToken(); //// if((pk != null) && (pk.Length == 0)) //// { //// return true; //// } //// //// pk = partialName.GetPublicKey(); //// if((pk != null) && (pk.Length == 0)) //// { //// return true; //// } //// //// return false; //// } //// //// // Loads the assembly with a COFF based IMAGE containing //// // an emitted assembly. The assembly is loaded into the domain //// // of the caller. //// static public Assembly Load( byte[] rawAssembly ) //// { //// StackCrawlMark stackMark = StackCrawlMark.LookForMyCaller; //// //// return nLoadImage( rawAssembly, //// null, // symbol store //// null, // evidence //// ref stackMark, //// false // fIntrospection //// ); //// } //// //// // Loads the assembly for reflection with a COFF based IMAGE containing //// // an emitted assembly. The assembly is loaded into the domain //// // of the caller. //// static public Assembly ReflectionOnlyLoad( byte[] rawAssembly ) //// { //// StackCrawlMark stackMark = StackCrawlMark.LookForMyCaller; //// //// return nLoadImage( rawAssembly, //// null, // symbol store //// null, // evidence //// ref stackMark, //// true // fIntrospection //// ); //// } //// //// // Loads the assembly with a COFF based IMAGE containing //// // an emitted assembly. The assembly is loaded into the domain //// // of the caller. The second parameter is the raw bytes //// // representing the symbol store that matches the assembly. //// static public Assembly Load( byte[] rawAssembly, byte[] rawSymbolStore ) //// { //// StackCrawlMark stackMark = StackCrawlMark.LookForMyCaller; //// //// return nLoadImage( rawAssembly, //// rawSymbolStore, //// null, // evidence //// ref stackMark, //// false // fIntrospection //// ); //// } //// //// [SecurityPermissionAttribute( SecurityAction.Demand, Flags = SecurityPermissionFlag.ControlEvidence )] //// static public Assembly Load( byte[] rawAssembly, byte[] rawSymbolStore, Evidence securityEvidence ) //// { //// StackCrawlMark stackMark = StackCrawlMark.LookForMyCaller; //// return nLoadImage( rawAssembly, //// rawSymbolStore, //// securityEvidence, //// ref stackMark, //// false // fIntrospection //// ); //// } //// //// [ResourceExposure( ResourceScope.Machine )] //// [ResourceConsumption( ResourceScope.Machine )] //// static public Assembly LoadFile( String path ) //// { //// new FileIOPermission( FileIOPermissionAccess.PathDiscovery | FileIOPermissionAccess.Read, path ).Demand(); //// //// return nLoadFile( path, null ); //// } //// //// [ResourceExposure( ResourceScope.Machine )] //// [ResourceConsumption( ResourceScope.Machine )] //// [SecurityPermissionAttribute( SecurityAction.Demand, Flags = SecurityPermissionFlag.ControlEvidence )] //// static public Assembly LoadFile( String path, Evidence securityEvidence ) //// { //// new FileIOPermission( FileIOPermissionAccess.PathDiscovery | FileIOPermissionAccess.Read, path ).Demand(); //// //// return nLoadFile( path, securityEvidence ); //// } //// //// [ResourceExposure( ResourceScope.Machine )] //// [ResourceConsumption( ResourceScope.Machine )] //// public Module LoadModule( String moduleName, byte[] rawModule ) //// { //// return LoadModule( moduleName, rawModule, null ); //// } //// //// [ResourceExposure( ResourceScope.Machine | ResourceScope.Assembly )] //// [MethodImpl( MethodImplOptions.InternalCall )] //// [SuppressUnmanagedCodeSecurity] //// private extern static ModuleHandle LoadModule( AssemblyHandle assembly , //// String moduleName , //// byte[] rawModule , //// int cbModule , //// byte[] rawSymbolStore, //// int cbSymbolStore ); //// //// [ResourceExposure( ResourceScope.Machine )] //// [ResourceConsumption( ResourceScope.Machine )] //// [SecurityPermissionAttribute( SecurityAction.Demand, ControlEvidence = true )] //// public Module LoadModule( String moduleName, byte[] rawModule, byte[] rawSymbolStore ) //// { //// return LoadModule( GetNativeHandle(), moduleName, rawModule, (rawModule != null) ? rawModule.Length : 0, rawSymbolStore, (rawSymbolStore != null) ? rawSymbolStore.Length : 0 ).GetModule(); //// } //// //// // //// // Locates a type from this assembly and creates an instance of it using //// // the system activator. //// // //// public Object CreateInstance( String typeName ) //// { //// return CreateInstance( typeName, //// false, // ignore case //// BindingFlags.Public | BindingFlags.Instance, //// null, // binder //// null, // args //// null, // culture //// null ); // activation attributes //// } //// //// public Object CreateInstance( String typeName, bool ignoreCase ) //// { //// return CreateInstance( typeName, //// ignoreCase, //// BindingFlags.Public | BindingFlags.Instance, //// null, // binder //// null, // args //// null, // culture //// null ); // activation attributes //// } //// //// public Object CreateInstance( String typeName , //// bool ignoreCase , //// BindingFlags bindingAttr , //// Binder binder , //// Object[] args , //// CultureInfo culture , //// Object[] activationAttributes ) //// { //// Type t = GetType( typeName, false, ignoreCase ); //// if(t == null) //// { //// return null; //// } //// //// return Activator.CreateInstance( t , //// bindingAttr , //// binder , //// args , //// culture , //// activationAttributes ); //// } //// //// [ResourceExposure( ResourceScope.Machine | ResourceScope.Assembly )] //// [ResourceConsumption( ResourceScope.Machine | ResourceScope.Assembly )] //// public Module[] GetLoadedModules() //// { //// return GetModules( false, false ); //// } //// //// [ResourceExposure( ResourceScope.Machine | ResourceScope.Assembly )] //// [ResourceConsumption( ResourceScope.Machine | ResourceScope.Assembly )] //// public Module[] GetLoadedModules( bool getResourceModules ) //// { //// return GetModules( false, getResourceModules ); //// } //// //// [ResourceExposure( ResourceScope.Machine | ResourceScope.Assembly )] //// [ResourceConsumption( ResourceScope.Machine | ResourceScope.Assembly )] //// public Module[] GetModules() //// { //// return GetModules( true, false ); //// } //// //// [ResourceExposure( ResourceScope.Machine | ResourceScope.Assembly )] //// [ResourceConsumption( ResourceScope.Machine | ResourceScope.Assembly )] //// public Module[] GetModules( bool getResourceModules ) //// { //// return GetModules( true, getResourceModules ); //// } //// //// // Returns the module in this assembly with name 'name' //// //// [MethodImpl( MethodImplOptions.InternalCall )] //// [SuppressUnmanagedCodeSecurity] //// private static extern ModuleHandle GetModule( AssemblyHandle assembly, String name ); //// //// [ResourceExposure( ResourceScope.Machine | ResourceScope.Assembly )] //// public Module GetModule( String name ) //// { //// return GetModule( GetNativeHandle(), name ).GetModule(); //// } //// //// // Returns the file in the File table of the manifest that matches the //// // given name. (Name should not include path.) //// [ResourceExposure( ResourceScope.Machine | ResourceScope.Assembly )] //// [ResourceConsumption( ResourceScope.Machine | ResourceScope.Assembly )] //// public virtual FileStream GetFile( String name ) //// { //// Module m = GetModule( name ); //// if(m == null) //// { //// return null; //// } //// //// return new FileStream( m.GetFullyQualifiedName(), FileMode.Open, FileAccess.Read, FileShare.Read ); //// } //// //// [ResourceExposure( ResourceScope.Machine | ResourceScope.Assembly )] //// [ResourceConsumption( ResourceScope.Machine | ResourceScope.Assembly )] //// public virtual FileStream[] GetFiles() //// { //// return GetFiles( false ); //// } //// //// [ResourceExposure( ResourceScope.Machine | ResourceScope.Assembly )] //// [ResourceConsumption( ResourceScope.Machine | ResourceScope.Assembly )] //// public virtual FileStream[] GetFiles( bool getResourceModules ) //// { //// Module[] m = GetModules( true, getResourceModules ); //// int iLength = m.Length; //// FileStream[] fs = new FileStream[iLength]; //// //// for(int i = 0; i < iLength; i++) //// { //// fs[i] = new FileStream( m[i].GetFullyQualifiedName(), FileMode.Open, FileAccess.Read, FileShare.Read ); //// } //// //// return fs; //// } //// //// //// // Returns the names of all the resources //// [ResourceExposure( ResourceScope.None )] //// [MethodImpl( MethodImplOptions.InternalCall )] //// private static extern String[] GetManifestResourceNames( IntPtr assembly ); //// //// // Returns the names of all the resources //// public virtual String[] GetManifestResourceNames() //// { //// return GetManifestResourceNames( GetNativeHandle().Value ); //// } //// //// //// [ResourceExposure( ResourceScope.None )] //// [MethodImpl( MethodImplOptions.InternalCall )] //// [SuppressUnmanagedCodeSecurity] //// private extern static AssemblyHandle GetExecutingAssembly( StackCrawlMarkHandle stackMark ); //// //// internal static Assembly GetExecutingAssembly( ref StackCrawlMark stackMark ) //// { //// return GetExecutingAssembly( JitHelpers.GetStackCrawlMarkHandle( ref stackMark ) ).GetAssembly(); //// } //// //// /* //// * Get the assembly that the current code is running from. //// */ //// public static Assembly GetExecutingAssembly() //// { //// // passing address of local will also prevent inlining //// StackCrawlMark stackMark = StackCrawlMark.LookForMyCaller; //// //// return GetExecutingAssembly( ref stackMark ); //// } //// //// public static Assembly GetCallingAssembly() //// { //// StackCrawlMark stackMark = StackCrawlMark.LookForMyCallersCaller; //// //// return GetExecutingAssembly( ref stackMark ); //// } //// //// //// public static Assembly GetEntryAssembly() //// { //// AppDomainManager domainManager = AppDomain.CurrentDomain.DomainManager; //// if(domainManager == null) //// { //// domainManager = new AppDomainManager(); //// } //// //// return domainManager.EntryAssembly; //// } //// //// //// // Returns the names of all the resources //// [MethodImpl( MethodImplOptions.InternalCall )] //// [ResourceExposure( ResourceScope.None )] //// private static extern AssemblyName[] GetReferencedAssemblies( IntPtr assembly ); //// //// public AssemblyName[] GetReferencedAssemblies() //// { //// return GetReferencedAssemblies( GetNativeHandle().Value ); //// } //// //// //// [ResourceExposure( ResourceScope.Machine )] //// [MethodImpl( MethodImplOptions.InternalCall )] //// [SuppressUnmanagedCodeSecurity] //// private static extern int GetManifestResourceInfo( AssemblyHandle assembly , //// String resourceName, //// out AssemblyHandle assemblyRef , //// StringHandleOnStack retFileName , //// StackCrawlMarkHandle stackMark ); //// //// [ResourceExposure( ResourceScope.Machine )] //// [ResourceConsumption( ResourceScope.Machine )] //// public virtual ManifestResourceInfo GetManifestResourceInfo( String resourceName ) //// { //// AssemblyHandle refAssembly; //// String fileName = null; //// StackCrawlMark stackMark = StackCrawlMark.LookForMyCaller; //// //// int location = GetManifestResourceInfo( GetNativeHandle(), resourceName, out refAssembly, //// JitHelpers.GetStringHandleOnStack( ref fileName ), //// JitHelpers.GetStackCrawlMarkHandle( ref stackMark ) ); //// //// if(location == -1) //// { //// return null; //// } //// //// return new ManifestResourceInfo( refAssembly.GetAssembly(), fileName, (ResourceLocation)location ); //// } //// //// //// public override String ToString() //// { //// String displayName = FullName; //// if(displayName == null) //// { //// return base.ToString(); //// } //// else //// { //// return displayName; //// } //// } //// //// //// [ResourceExposure( ResourceScope.Machine )] //// [MethodImpl( MethodImplOptions.InternalCall )] //// [SuppressUnmanagedCodeSecurity] //// private static extern void GetLocation( AssemblyHandle assembly, StringHandleOnStack retString ); //// //// public virtual String Location //// { //// [ResourceExposure( ResourceScope.Machine )] //// [ResourceConsumption( ResourceScope.Machine )] //// get //// { //// String location = null; //// //// GetLocation( GetNativeHandle(), JitHelpers.GetStringHandleOnStack( ref location ) ); //// //// if(location != null) //// { //// new FileIOPermission( FileIOPermissionAccess.PathDiscovery, location ).Demand(); //// } //// //// return location; //// } //// } //// //// //// [ResourceExposure( ResourceScope.None )] //// [MethodImpl( MethodImplOptions.InternalCall )] //// [SuppressUnmanagedCodeSecurity] //// private extern static void GetImageRuntimeVersion( AssemblyHandle assembly, StringHandleOnStack retString ); //// //// public virtual String ImageRuntimeVersion //// { //// get //// { //// String s = null; //// //// GetImageRuntimeVersion( GetNativeHandle(), JitHelpers.GetStringHandleOnStack( ref s ) ); //// //// return s; //// } //// } //// //// //// [ResourceExposure( ResourceScope.None )] //// [MethodImpl( MethodImplOptions.InternalCall )] //// private extern static bool IsGlobalAssemblyCache( IntPtr assembly ); //// //// /* //// Returns true if the assembly was loaded from the global assembly cache. //// */ //// //// public bool GlobalAssemblyCache //// { //// get //// { //// return IsGlobalAssemblyCache( GetNativeHandle().Value ); //// } //// } //// //// //// [ResourceExposure( ResourceScope.None )] //// [MethodImpl( MethodImplOptions.InternalCall )] //// [SuppressUnmanagedCodeSecurity] //// private extern static Int64 GetHostContext( AssemblyHandle assembly ); //// //// public Int64 HostContext //// { //// get //// { //// return GetHostContext( GetNativeHandle() ); //// } //// } //// //// //// [ResourceExposure( ResourceScope.Machine )] //// [ResourceConsumption( ResourceScope.Machine )] //// internal static String VerifyCodeBase( String codebase ) //// { //// if(codebase == null) //// { //// return null; //// } //// //// int len = codebase.Length; //// if(len == 0) //// { //// return null; //// } //// //// //// int j = codebase.IndexOf( ':' ); //// // Check to see if the url has a prefix //// if((j != -1) && (j + 2 < len) && //// ((codebase[j + 1] == '/') || (codebase[j + 1] == '\\')) && //// ((codebase[j + 2] == '/') || (codebase[j + 2] == '\\'))) //// { //// return codebase; //// } //// else if((len > 2) && (codebase[0] == '\\') && (codebase[1] == '\\')) //// { //// return "file://" + codebase; //// } //// else //// { //// return "file:///" + Path.GetFullPathInternal( codebase ); //// } //// } //// //// internal virtual Stream GetManifestResourceStream( Type type, String name, bool skipSecurityCheck, ref StackCrawlMark stackMark ) //// { //// StringBuilder sb = new StringBuilder(); //// if(type == null) //// { //// if(name == null) //// { //// throw new ArgumentNullException( "type" ); //// } //// } //// else //// { //// String nameSpace = type.Namespace; //// if(nameSpace != null) //// { //// sb.Append( nameSpace ); //// if(name != null) //// { //// sb.Append( Type.Delimiter ); //// } //// } //// } //// //// if(name != null) //// { //// sb.Append( name ); //// } //// //// return GetManifestResourceStream( sb.ToString(), ref stackMark, skipSecurityCheck ); //// } //// //// internal Assembly() //// { //// } //// //// [ResourceExposure( ResourceScope.Machine )] //// [MethodImpl( MethodImplOptions.InternalCall )] //// private extern static IntPtr GetOnDiskAssemblyModule( IntPtr assembly ); //// //// internal Module GetOnDiskAssemblyModule() //// { //// return new ModuleHandle( GetOnDiskAssemblyModule( GetNativeHandle().Value ) ).GetModule(); //// } //// //// [ResourceExposure( ResourceScope.None )] //// [MethodImpl( MethodImplOptions.InternalCall )] //// private extern static IntPtr GetInMemoryAssemblyModule( IntPtr assembly ); //// //// internal Module GetInMemoryAssemblyModule() //// { //// return new ModuleHandle( GetInMemoryAssemblyModule( GetNativeHandle().Value ) ).GetModule(); //// } //// //// private static void DecodeSerializedEvidence( Evidence evidence, byte[] serializedEvidence ) //// { //// BinaryFormatter formatter = new BinaryFormatter(); //// //// Evidence asmEvidence = null; //// //// PermissionSet permSet = new PermissionSet( false ); //// permSet.SetPermission( new SecurityPermission( SecurityPermissionFlag.SerializationFormatter ) ); //// permSet.PermitOnly(); //// permSet.Assert(); //// //// try //// { //// using(MemoryStream ms = new MemoryStream( serializedEvidence )) //// { //// asmEvidence = (Evidence)formatter.Deserialize( ms ); //// } //// } //// catch //// { //// } //// //// if(asmEvidence != null) //// { //// IEnumerator enumerator = asmEvidence.GetAssemblyEnumerator(); //// //// while(enumerator.MoveNext()) //// { //// Object obj = enumerator.Current; //// //// evidence.AddAssembly( obj ); //// } //// } //// } //// //// private static void AddX509Certificate( Evidence evidence, byte[] cert ) //// { //// evidence.AddHost( new Publisher( new System.Security.Cryptography.X509Certificates.X509Certificate( cert ) ) ); //// } //// //// private static void AddStrongName( Evidence evidence, byte[] blob, String strSimpleName, int major, int minor, int build, int revision ) //// { //// evidence.AddHost( new StrongName( new StrongNamePublicKeyBlob( blob ), strSimpleName, new Version( major, minor, build, revision ) ) ); //// } //// //// private static Evidence CreateSecurityIdentity( Assembly asm , //// String strUrl , //// int zone , //// byte[] cert , //// byte[] publicKeyBlob , //// String strSimpleName , //// int major , //// int minor , //// int build , //// int revision , //// byte[] serializedEvidence , //// Evidence additionalEvidence ) //// { //// Evidence evidence = new Evidence(); //// //// if(zone != -1) //// { //// evidence.AddHost( new Zone( (SecurityZone)zone ) ); //// } //// //// if(strUrl != null) //// { //// evidence.AddHost( new Url( strUrl, true ) ); //// //// // Only create a site piece of evidence if we are not loading from a file. //// if(String.Compare( strUrl, 0, s_localFilePrefix, 0, 5, StringComparison.OrdinalIgnoreCase ) != 0) //// { //// evidence.AddHost( Site.CreateFromUrl( strUrl ) ); //// } //// } //// //// if(cert != null) //// { //// AddX509Certificate( evidence, cert ); //// } //// //// // Determine if it's in the GAC and add some evidence about it //// if(asm != null && System.Runtime.InteropServices.RuntimeEnvironment.FromGlobalAccessCache( asm )) //// { //// evidence.AddHost( new GacInstalled() ); //// } //// //// // This code was moved to a different function because: //// // 1) it is rarely called so we should only JIT it if we need it. //// // 2) it references lots of classes that otherwise aren't loaded. //// if(serializedEvidence != null) //// { //// DecodeSerializedEvidence( evidence, serializedEvidence ); //// } //// //// if((publicKeyBlob != null) && (publicKeyBlob.Length != 0)) //// { //// AddStrongName( evidence, publicKeyBlob, strSimpleName, major, minor, build, revision ); //// } //// //// if(asm != null && !asm.IsDynamic()) //// { //// evidence.AddHost( new Hash( asm ) ); //// } //// //// // If the host (caller of Assembly.Load) provided evidence, merge it //// // with the evidence we've just created. The host evidence takes //// // priority. //// if(additionalEvidence != null) //// { //// evidence.MergeWithNoDuplicates( additionalEvidence ); //// } //// //// if(asm != null) //// { //// // The host might want to modify the evidence of the assembly through //// // the HostSecurityManager provided in AppDomainManager, so take that into account. //// HostSecurityManager securityManager = AppDomain.CurrentDomain.HostSecurityManager; //// //// if((securityManager.Flags & HostSecurityManagerOptions.HostAssemblyEvidence) == HostSecurityManagerOptions.HostAssemblyEvidence) //// { //// return securityManager.ProvideAssemblyEvidence( asm, evidence ); //// } //// } //// //// return evidence; //// } //// //// // GetResource will return a pointer to the resources in memory. //// [ResourceExposure( ResourceScope.None )] //// [MethodImpl( MethodImplOptions.InternalCall )] //// [SuppressUnmanagedCodeSecurity] //// private static unsafe extern byte* GetResource( AssemblyHandle assembly , //// String resourceName , //// out ulong length , //// StackCrawlMarkHandle stackMark , //// bool skipSecurityCheck ); //// //// internal unsafe virtual Stream GetManifestResourceStream( String name, ref StackCrawlMark stackMark, bool skipSecurityCheck ) //// { //// ulong length = 0; //// byte* pbInMemoryResource = GetResource( GetNativeHandle(), name, out length, JitHelpers.GetStackCrawlMarkHandle( ref stackMark ), skipSecurityCheck ); //// //// if(pbInMemoryResource != null) //// { //// //Console.WriteLine("Creating an unmanaged memory stream of length "+length); //// if(length > Int64.MaxValue) //// { //// throw new NotImplementedException( Environment.GetResourceString( "NotImplemented_ResourcesLongerThan2^63" ) ); //// } //// //// // For cases where we're loading an embedded resource from an assembly, //// // in V1 we do not have any serious lifetime issues with the //// // UnmanagedMemoryStream. If the Stream is only used //// // in the AppDomain that contains the assembly, then if that AppDomain //// // is unloaded, we will collect all of the objects in the AppDomain first //// // before unloading assemblies. If the Stream is shared across AppDomains, //// // then the original AppDomain was unloaded, accesses to this Stream will //// // throw an exception saying the appdomain was unloaded. This is //// // guaranteed be EE AppDomain goo. And for shared assemblies like //// // mscorlib, their lifetime is the lifetime of the process, so the //// // assembly will NOT be unloaded, so the resource will always be in memory. //// return new UnmanagedMemoryStream( pbInMemoryResource, (long)length, (long)length, FileAccess.Read, true ); //// } //// //// //Console.WriteLine("GetManifestResourceStream: Blob "+name+" not found..."); //// return null; //// } //// //// [ResourceExposure( ResourceScope.None )] //// [MethodImpl( MethodImplOptions.InternalCall )] //// [SuppressUnmanagedCodeSecurity] //// private static extern void GetVersion( AssemblyHandle assembly, //// out int majVer , //// out int minVer , //// out int buildNum, //// out int revNum ); //// //// internal Version GetVersion() //// { //// int majorVer; //// int minorVer; //// int build; //// int revision; //// //// GetVersion( GetNativeHandle(), out majorVer, out minorVer, out build, out revision ); //// //// return new Version( majorVer, minorVer, build, revision ); //// } //// //// [MethodImpl( MethodImplOptions.InternalCall )] //// [SuppressUnmanagedCodeSecurity] //// private static extern void GetLocale( AssemblyHandle assembly, StringHandleOnStack retString ); //// //// internal CultureInfo GetLocale() //// { //// String locale = null; //// //// GetLocale( GetNativeHandle(), JitHelpers.GetStringHandleOnStack( ref locale ) ); //// //// if(locale == null) //// { //// return CultureInfo.InvariantCulture; //// } //// //// return new CultureInfo( locale ); //// } //// //// [ResourceExposure( ResourceScope.None )] //// [MethodImpl( MethodImplOptions.InternalCall )] //// private static extern bool IsDynamic( IntPtr assembly ); //// //// internal bool IsDynamic() //// { //// return IsDynamic( GetNativeHandle().Value ); //// } //// //// private void VerifyCodeBaseDiscovery( String codeBase ) //// { //// if((codeBase != null) && (String.Compare( codeBase, 0, s_localFilePrefix, 0, 5, StringComparison.OrdinalIgnoreCase ) == 0)) //// { //// System.Security.Util.URLString urlString = new System.Security.Util.URLString( codeBase, true ); //// //// new FileIOPermission( FileIOPermissionAccess.PathDiscovery, urlString.GetFileName() ).Demand(); //// } //// } //// //// [ResourceExposure( ResourceScope.None )] //// [MethodImpl( MethodImplOptions.InternalCall )] //// [SuppressUnmanagedCodeSecurity] //// private static extern void GetSimpleName( AssemblyHandle assembly, StringHandleOnStack retSimpleName ); //// //// internal String GetSimpleName() //// { //// string name = null; //// //// GetSimpleName( GetNativeHandle(), JitHelpers.GetStringHandleOnStack( ref name ) ); //// //// return name; //// } //// //// [ResourceExposure( ResourceScope.None )] //// [MethodImpl( MethodImplOptions.InternalCall )] //// [SuppressUnmanagedCodeSecurity] //// private extern static AssemblyHashAlgorithm GetHashAlgorithm( AssemblyHandle assembly ); //// //// AssemblyHashAlgorithm GetHashAlgorithm() //// { //// return GetHashAlgorithm( GetNativeHandle() ); //// } //// //// [ResourceExposure( ResourceScope.None )] //// [MethodImpl( MethodImplOptions.InternalCall )] //// [SuppressUnmanagedCodeSecurity] //// private extern static AssemblyNameFlags GetFlags( AssemblyHandle assembly ); //// //// AssemblyNameFlags GetFlags() //// { //// return GetFlags( GetNativeHandle() ); //// } //// //// [ResourceExposure( ResourceScope.None )] //// [MethodImpl( MethodImplOptions.InternalCall )] //// [SuppressUnmanagedCodeSecurity] //// private static extern void GetPublicKey( AssemblyHandle assembly, ObjectHandleOnStack retPublicKey ); //// //// internal byte[] GetPublicKey() //// { //// byte[] publicKey = null; //// //// GetPublicKey( GetNativeHandle(), JitHelpers.GetObjectHandleOnStack( ref publicKey ) ); //// //// return publicKey; //// } //// //// [ResourceExposure( ResourceScope.None )] //// [MethodImpl( MethodImplOptions.InternalCall )] //// internal extern Evidence nGetEvidence(); //// //// [MethodImpl( MethodImplOptions.InternalCall )] //// [SuppressUnmanagedCodeSecurity] //// [ResourceExposure( ResourceScope.None )] //// private extern static void GetGrantSet( AssemblyHandle assembly, ObjectHandleOnStack granted, ObjectHandleOnStack denied ); //// //// internal void GetGrantSet( out PermissionSet newGrant, out PermissionSet newDenied ) //// { //// PermissionSet granted = null, denied = null; //// //// GetGrantSet( GetNativeHandle(), JitHelpers.GetObjectHandleOnStack( ref granted ), JitHelpers.GetObjectHandleOnStack( ref denied ) ); //// //// newGrant = granted; newDenied = denied; //// } //// //// internal static Assembly InternalLoad( String assemblyString , //// Evidence assemblySecurity , //// ref StackCrawlMark stackMark , //// bool forIntrospection ) //// { //// if(assemblyString == null) //// { //// throw new ArgumentNullException( "assemblyString" ); //// } //// if((assemblyString.Length == 0) || (assemblyString[0] == '\0')) //// { //// throw new ArgumentException( Environment.GetResourceString( "Format_StringZeroLength" ) ); //// } //// //// AssemblyName an = new AssemblyName(); //// Assembly assembly = null; //// //// an.Name = assemblyString; //// int hr = an.nInit( out assembly, forIntrospection, true ); //// //// if(hr == System.__HResults.FUSION_E_INVALID_NAME) //// { //// return assembly; //// } //// //// return InternalLoad( an, assemblySecurity, ref stackMark, forIntrospection ); //// } //// //// [ResourceExposure( ResourceScope.None )] //// [ResourceConsumption( ResourceScope.Machine, ResourceScope.Machine )] //// internal static Assembly InternalLoad( AssemblyName assemblyRef , //// Evidence assemblySecurity , //// ref StackCrawlMark stackMark , //// bool forIntrospection ) //// { //// if(assemblyRef == null) //// { //// throw new ArgumentNullException( "assemblyRef" ); //// } //// //// assemblyRef = (AssemblyName)assemblyRef.Clone(); //// if(assemblySecurity != null) //// { //// new SecurityPermission( SecurityPermissionFlag.ControlEvidence ).Demand(); //// } //// //// String codeBase = VerifyCodeBase( assemblyRef.CodeBase ); //// if(codeBase != null) //// { //// //// if(String.Compare( codeBase, 0, s_localFilePrefix, 0, 5, StringComparison.OrdinalIgnoreCase ) != 0) //// { //// IPermission perm = CreateWebPermission( assemblyRef.EscapedCodeBase ); //// perm.Demand(); //// } //// else //// { //// System.Security.Util.URLString urlString = new System.Security.Util.URLString( codeBase, true ); //// //// new FileIOPermission( FileIOPermissionAccess.PathDiscovery | FileIOPermissionAccess.Read, urlString.GetFileName() ).Demand(); //// } //// } //// //// return nLoad( assemblyRef, codeBase, assemblySecurity, null, ref stackMark, true, forIntrospection ); //// } //// //// // demandFlag: //// // 0 demand PathDiscovery permission only //// // 1 demand Read permission only //// // 2 demand both Read and PathDiscovery //// // 3 demand Web permission only //// [ResourceExposure( ResourceScope.None )] //// [ResourceConsumption( ResourceScope.Machine, ResourceScope.Machine )] //// private static void DemandPermission( String codeBase, bool havePath, int demandFlag ) //// { //// FileIOPermissionAccess access = FileIOPermissionAccess.PathDiscovery; //// switch(demandFlag) //// { //// //// case 0: // default //// break; //// //// case 1: //// access = FileIOPermissionAccess.Read; //// break; //// //// case 2: //// access = FileIOPermissionAccess.PathDiscovery | FileIOPermissionAccess.Read; //// break; //// //// case 3: //// IPermission perm = CreateWebPermission( AssemblyName.EscapeCodeBase( codeBase ) ); //// perm.Demand(); //// return; //// } //// //// if(!havePath) //// { //// System.Security.Util.URLString urlString = new System.Security.Util.URLString( codeBase, true ); //// //// codeBase = urlString.GetFileName(); //// } //// //// codeBase = Path.GetFullPathInternal( codeBase ); // canonicalize //// //// new FileIOPermission( access, codeBase ).Demand(); //// } //// //// [ResourceExposure( ResourceScope.None )] //// [MethodImpl( MethodImplOptions.InternalCall )] //// private static extern Assembly nLoad( AssemblyName fileName , //// String codeBase , //// Evidence assemblySecurity , //// Assembly locationHint , //// ref StackCrawlMark stackMark , //// bool throwOnFileNotFound, //// bool forIntrospection ); //// //// private static IPermission CreateWebPermission( String codeBase ) //// { //// BCLDebug.Assert( codeBase != null, "Must pass in a valid CodeBase" ); //// Assembly sys = Assembly.Load( "System, Version=" + ThisAssembly.Version + ", Culture=neutral, PublicKeyToken=" + AssemblyRef.EcmaPublicKeyToken ); //// //// Type type = sys.GetType( "System.Net.NetworkAccess", true ); //// //// IPermission retval = null; //// if(!type.IsEnum || !type.IsVisible) //// { //// goto Exit; //// } //// //// Object[] webArgs = new Object[2]; //// webArgs[0] = (Enum)Enum.Parse( type, "Connect", true ); //// if(webArgs[0] == null) //// { //// goto Exit; //// } //// //// webArgs[1] = codeBase; //// //// type = sys.GetType( "System.Net.WebPermission", true ); //// //// if(!type.IsVisible) //// { //// goto Exit; //// } //// //// retval = (IPermission)Activator.CreateInstance( type, webArgs ); //// //// Exit: //// if(retval == null) //// { //// BCLDebug.Assert( false, "Unable to create WebPermission" ); //// throw new ExecutionEngineException(); //// } //// //// return retval; //// } //// //// //// private Module OnModuleResolveEvent( String moduleName ) //// { //// ModuleResolveEventHandler moduleResolve = ModuleResolve; //// if(moduleResolve == null) //// { //// return null; //// } //// //// Delegate[] ds = moduleResolve.GetInvocationList(); //// int len = ds.Length; //// for(int i = 0; i < len; i++) //// { //// Module ret = ((ModuleResolveEventHandler)ds[i])( this, new ResolveEventArgs( moduleName ) ); //// if(ret != null) //// { //// return ret; //// } //// } //// //// return null; //// } //// //// //// internal Assembly InternalGetSatelliteAssembly( CultureInfo culture, Version version, bool throwOnFileNotFound ) //// { //// if(culture == null) //// { //// throw new ArgumentNullException( "culture" ); //// } //// //// AssemblyName an = new AssemblyName(); //// //// an.SetPublicKey( GetPublicKey() ); //// an.Flags = GetFlags() | AssemblyNameFlags.PublicKey; //// //// if(version == null) //// { //// an.Version = GetVersion(); //// } //// else //// { //// an.Version = version; //// } //// //// an.CultureInfo = culture; //// an.Name = GetSimpleName() + ".resources"; //// //// StackCrawlMark stackMark = StackCrawlMark.LookForMyCaller; //// //// Assembly a = nLoad( an, null, null, this, ref stackMark, throwOnFileNotFound, false ); //// if(a == this) //// { //// throw new FileNotFoundException( String.Format( culture, Environment.GetResourceString( "IO.FileNotFound_FileName" ), an.Name ) ); //// } //// //// return a; //// } //// //// internal InternalCache Cache //// { //// get //// { //// // This grabs an internal copy of m_cachedData and uses //// // that instead of looking at m_cachedData directly because //// // the cache may get cleared asynchronously. This prevents //// // us from having to take a lock. //// InternalCache cache = m_cachedData; //// if(cache == null) //// { //// cache = new InternalCache( "Assembly" ); //// //// m_cachedData = cache; //// //// GC.ClearCache += new ClearCacheHandler( OnCacheClear ); //// } //// //// return cache; //// } //// } //// //// internal void OnCacheClear( Object sender, ClearCacheEventArgs cacheEventArgs ) //// { //// m_cachedData = null; //// } //// //// [ResourceExposure( ResourceScope.Machine )] //// [MethodImpl( MethodImplOptions.InternalCall )] //// static internal extern Assembly nLoadFile( String path, Evidence evidence ); //// //// [ResourceExposure( ResourceScope.None )] //// [MethodImpl( MethodImplOptions.InternalCall )] //// static internal extern Assembly nLoadImage( byte[] rawAssembly , //// byte[] rawSymbolStore , //// Evidence evidence , //// ref StackCrawlMark stackMark , //// bool fIntrospection ); //// //// //// [MethodImpl( MethodImplOptions.InternalCall )] //// [SuppressUnmanagedCodeSecurity] //// private extern static void GetModules( AssemblyHandle assembly , //// bool loadIfNotFound , //// bool getResourceModules, //// ObjectHandleOnStack retModuleHandles ); //// //// [ResourceExposure( ResourceScope.Machine | ResourceScope.Assembly )] //// internal Module[] GetModules( bool loadIfNotFound, bool getResourceModules ) //// { //// Module[] modules = null; //// //// GetModules( GetNativeHandle(), loadIfNotFound, getResourceModules, JitHelpers.GetObjectHandleOnStack( ref modules ) ); //// //// return modules; //// } //// //// //// internal ProcessorArchitecture ComputeProcArchIndex() //// { //// PortableExecutableKinds pek; //// ImageFileMachine ifm; //// //// Module manifestModule = ManifestModule; //// if(manifestModule != null) //// { //// if(manifestModule.MDStreamVersion > 0x10000) //// { //// ManifestModule.GetPEKind( out pek, out ifm ); //// if((pek & System.Reflection.PortableExecutableKinds.PE32Plus) == System.Reflection.PortableExecutableKinds.PE32Plus) //// { //// switch(ifm) //// { //// case System.Reflection.ImageFileMachine.IA64: //// return ProcessorArchitecture.IA64; //// //// case System.Reflection.ImageFileMachine.AMD64: //// return ProcessorArchitecture.Amd64; //// //// case System.Reflection.ImageFileMachine.I386: //// if((pek & System.Reflection.PortableExecutableKinds.ILOnly) == System.Reflection.PortableExecutableKinds.ILOnly) //// { //// return ProcessorArchitecture.MSIL; //// } //// break; //// } //// } //// //// else //// { //// if(ifm == System.Reflection.ImageFileMachine.I386) //// { //// if((pek & System.Reflection.PortableExecutableKinds.Required32Bit) == System.Reflection.PortableExecutableKinds.Required32Bit) //// { //// return ProcessorArchitecture.X86; //// } //// //// if((pek & System.Reflection.PortableExecutableKinds.ILOnly) == System.Reflection.PortableExecutableKinds.ILOnly) //// { //// return ProcessorArchitecture.MSIL; //// } //// //// return ProcessorArchitecture.X86; //// } //// } //// } //// } //// //// return ProcessorArchitecture.None; //// } } } ================================================ FILE: Zelig/Zelig/RunTime/Framework/mscorlib/System/Reflection/AssemblyAttributes.cs ================================================ // ==++== // // Copyright (c) Microsoft Corporation. All rights reserved. // // ==--== /*============================================================================= ** ** File: AssemblyAttributes ** ** ** Purpose: For Assembly-related custom attributes. ** ** =============================================================================*/ namespace System.Reflection { using System; using System.Configuration.Assemblies; [AttributeUsage( AttributeTargets.Assembly, Inherited = false )] public sealed class AssemblyCopyrightAttribute : Attribute { private String m_copyright; public AssemblyCopyrightAttribute( String copyright ) { m_copyright = copyright; } public String Copyright { get { return m_copyright; } } } [AttributeUsage( AttributeTargets.Assembly, Inherited = false )] public sealed class AssemblyTrademarkAttribute : Attribute { private String m_trademark; public AssemblyTrademarkAttribute( String trademark ) { m_trademark = trademark; } public String Trademark { get { return m_trademark; } } } [AttributeUsage( AttributeTargets.Assembly, Inherited = false )] public sealed class AssemblyProductAttribute : Attribute { private String m_product; public AssemblyProductAttribute( String product ) { m_product = product; } public String Product { get { return m_product; } } } [AttributeUsage( AttributeTargets.Assembly, Inherited = false )] public sealed class AssemblyCompanyAttribute : Attribute { private String m_company; public AssemblyCompanyAttribute( String company ) { m_company = company; } public String Company { get { return m_company; } } } [AttributeUsage( AttributeTargets.Assembly, Inherited = false )] public sealed class AssemblyDescriptionAttribute : Attribute { private String m_description; public AssemblyDescriptionAttribute( String description ) { m_description = description; } public String Description { get { return m_description; } } } [AttributeUsage( AttributeTargets.Assembly, Inherited = false )] public sealed class AssemblyTitleAttribute : Attribute { private String m_title; public AssemblyTitleAttribute( String title ) { m_title = title; } public String Title { get { return m_title; } } } [AttributeUsage( AttributeTargets.Assembly, Inherited = false )] public sealed class AssemblyConfigurationAttribute : Attribute { private String m_configuration; public AssemblyConfigurationAttribute( String configuration ) { m_configuration = configuration; } public String Configuration { get { return m_configuration; } } } [AttributeUsage( AttributeTargets.Assembly, Inherited = false )] public sealed class AssemblyDefaultAliasAttribute : Attribute { private String m_defaultAlias; public AssemblyDefaultAliasAttribute( String defaultAlias ) { m_defaultAlias = defaultAlias; } public String DefaultAlias { get { return m_defaultAlias; } } } [AttributeUsage( AttributeTargets.Assembly, Inherited = false )] public sealed class AssemblyInformationalVersionAttribute : Attribute { private String m_informationalVersion; public AssemblyInformationalVersionAttribute( String informationalVersion ) { m_informationalVersion = informationalVersion; } public String InformationalVersion { get { return m_informationalVersion; } } } [AttributeUsage( AttributeTargets.Assembly, Inherited = false )] public sealed class AssemblyFileVersionAttribute : Attribute { private String m_version; public AssemblyFileVersionAttribute( String version ) { if(version == null) { #if EXCEPTION_STRINGS throw new ArgumentNullException( "version" ); #else throw new ArgumentNullException(); #endif } m_version = version; } public String Version { get { return m_version; } } } [AttributeUsage( AttributeTargets.Assembly, Inherited = false )] public unsafe sealed class AssemblyCultureAttribute : Attribute { private String m_culture; public AssemblyCultureAttribute( String culture ) { m_culture = culture; } public String Culture { get { return m_culture; } } } [AttributeUsage( AttributeTargets.Assembly, Inherited = false )] public unsafe sealed class AssemblyVersionAttribute : Attribute { private String m_version; public AssemblyVersionAttribute( String version ) { m_version = version; } public String Version { get { return m_version; } } } [AttributeUsage( AttributeTargets.Assembly, Inherited = false )] public sealed class AssemblyKeyFileAttribute : Attribute { private String m_keyFile; public AssemblyKeyFileAttribute( String keyFile ) { m_keyFile = keyFile; } public String KeyFile { get { return m_keyFile; } } } [AttributeUsage( AttributeTargets.Assembly, Inherited = false )] public sealed class AssemblyDelaySignAttribute : Attribute { private bool m_delaySign; public AssemblyDelaySignAttribute( bool delaySign ) { m_delaySign = delaySign; } public bool DelaySign { get { return m_delaySign; } } } [AttributeUsage( AttributeTargets.Assembly, Inherited = false )] public unsafe sealed class AssemblyAlgorithmIdAttribute : Attribute { private uint m_algId; public AssemblyAlgorithmIdAttribute( AssemblyHashAlgorithm algorithmId ) { m_algId = (uint)algorithmId; } [CLSCompliant( false )] public AssemblyAlgorithmIdAttribute( uint algorithmId ) { m_algId = algorithmId; } [CLSCompliant( false )] public uint AlgorithmId { get { return m_algId; } } } ////[AttributeUsage( AttributeTargets.Assembly, Inherited = false )] ////public unsafe sealed class AssemblyFlagsAttribute : Attribute ////{ //// private AssemblyNameFlags m_flags; //// //// [Obsolete( "This constructor has been deprecated. Please use AssemblyFlagsAttribute(AssemblyNameFlags) instead. http://go.microsoft.com/fwlink/?linkid=14202" )] //// [CLSCompliant( false )] //// public AssemblyFlagsAttribute( uint flags ) //// { //// m_flags = (AssemblyNameFlags)flags; //// } //// //// [Obsolete( "This property has been deprecated. Please use AssemblyFlags instead. http://go.microsoft.com/fwlink/?linkid=14202" )] //// [CLSCompliant( false )] //// public uint Flags //// { //// get //// { //// return (uint)m_flags; //// } //// } //// //// // This, of course, should be typed as AssemblyNameFlags. The compat police don't allow such changes. //// public int AssemblyFlags //// { //// get //// { //// return (int)m_flags; //// } //// } //// //// [Obsolete( "This constructor has been deprecated. Please use AssemblyFlagsAttribute(AssemblyNameFlags) instead. http://go.microsoft.com/fwlink/?linkid=14202" )] //// public AssemblyFlagsAttribute( int assemblyFlags ) //// { //// m_flags = (AssemblyNameFlags)assemblyFlags; //// } //// //// //// public AssemblyFlagsAttribute( AssemblyNameFlags assemblyFlags ) //// { //// m_flags = assemblyFlags; //// } ////} [AttributeUsage( AttributeTargets.Assembly, Inherited = false )] public sealed class AssemblyKeyNameAttribute : Attribute { private String m_keyName; public AssemblyKeyNameAttribute( String keyName ) { m_keyName = keyName; } public String KeyName { get { return m_keyName; } } } } ================================================ FILE: Zelig/Zelig/RunTime/Framework/mscorlib/System/Reflection/Binder.cs ================================================ // ==++== // // Copyright (c) Microsoft Corporation. All rights reserved. // // ==--== //////////////////////////////////////////////////////////////////////////////// // // This interface defines a set of methods which interact with reflection // during the binding process. This control allows systems to apply language // specific semantics to the binding and invocation process. // // Author: darylo // Date: June 98 // namespace System.Reflection { using System; using System.Runtime.InteropServices; using CultureInfo = System.Globalization.CultureInfo; [Serializable] public abstract class Binder { // Given a set of methods that match the basic criteria, select a method to // invoke. When this method is finished, we should have public abstract MethodBase BindToMethod( BindingFlags bindingAttr, MethodBase[] match , ref Object[] args , ParameterModifier[] modifiers , CultureInfo culture , String[] names , out Object state ); // Given a set of methods that match the basic criteria, select a method to // invoke. When this method is finished, we should have public abstract FieldInfo BindToField( BindingFlags bindingAttr, FieldInfo[] match , Object value , CultureInfo culture ); // Given a set of methods that match the base criteria, select a method based // upon an array of types. This method should return null if no method matchs // the criteria. public abstract MethodBase SelectMethod( BindingFlags bindingAttr, MethodBase[] match , Type[] types , ParameterModifier[] modifiers ); // Given a set of propreties that match the base criteria, select one. public abstract PropertyInfo SelectProperty( BindingFlags bindingAttr, PropertyInfo[] match , Type returnType , Type[] indexes , ParameterModifier[] modifiers ); // ChangeType // This method will convert the value into the property type. // It throws a cast exception if this fails. public abstract Object ChangeType( Object value, Type type, CultureInfo culture ); public abstract void ReorderArgumentArray( ref Object[] args, Object state ); // CanChangeType // This method checks whether the value can be converted into the property type. public virtual bool CanChangeType( Object value, Type type, CultureInfo culture ) { return false; } } } ================================================ FILE: Zelig/Zelig/RunTime/Framework/mscorlib/System/Reflection/BindingFlags.cs ================================================ // ==++== // // Copyright (c) Microsoft Corporation. All rights reserved. // // ==--== //////////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////////// // // BindingFlags are a set of flags that control the binding and invocation process // in Reflection. There are two processes. The first is selection of a Member which // is the binding phase. The second, is invocation. These flags control how this // process works. // // Author: darylo // Date: June 99 // namespace System.Reflection { using System; [Flags] [Serializable] public enum BindingFlags { // NOTES: We have lookup masks defined in RuntimeType and Activator. If we // change the lookup values then these masks may need to change also. // a place holder for no flag specifed Default = 0x00000000, // These flags indicate what to search for when binding IgnoreCase = 0x00000001, // Ignore the case of Names while searching DeclaredOnly = 0x00000002, // Only look at the members declared on the Type Instance = 0x00000004, // Include Instance members in search Static = 0x00000008, // Include Static members in search Public = 0x00000010, // Include Public members in search NonPublic = 0x00000020, // Include Non-Public members in search FlattenHierarchy = 0x00000040, // Rollup the statics into the class. // These flags are used by InvokeMember to determine // what type of member we are trying to Invoke. InvokeMethod = 0x00000100, CreateInstance = 0x00000200, GetField = 0x00000400, SetField = 0x00000800, GetProperty = 0x00001000, SetProperty = 0x00002000, // These flags are also used by InvokeMember but they should only // be used when calling InvokeMember on a COM object. PutDispProperty = 0x00004000, PutRefDispProperty = 0x00008000, ExactBinding = 0x00010000, // Bind with Exact Type matching, No Change type SuppressChangeType = 0x00020000, // DefaultValueBinding will return the set of methods having ArgCount or // more parameters. This is used for default values, etc. OptionalParamBinding = 0x00040000, // These are a couple of misc attributes used IgnoreReturn = 0x01000000, // This is used in COM Interop } } ================================================ FILE: Zelig/Zelig/RunTime/Framework/mscorlib/System/Reflection/CallingConventions.cs ================================================ // ==++== // // Copyright (c) Microsoft Corporation. All rights reserved. // // ==--== //////////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////////// // // CallingConventions is a set of Bits representing the calling conventions // in the system. // // Author: meichint // Date: Aug 99 // namespace System.Reflection { using System; using System.Runtime.InteropServices; [Flags] [Serializable] public enum CallingConventions { //NOTE: If you change this please update COMMember.cpp. These // are defined there. Standard = 0x0001, VarArgs = 0x0002, Any = Standard | VarArgs, HasThis = 0x0020, ExplicitThis = 0x0040, } } ================================================ FILE: Zelig/Zelig/RunTime/Framework/mscorlib/System/Reflection/ConstructorInfo.cs ================================================ // ==++== // // Copyright (c) Microsoft Corporation. All rights reserved. // // ==--== namespace System.Reflection { using System; using System.Reflection; ////using System.Reflection.Cache; ////using System.Reflection.Emit; using System.Globalization; using System.Threading; using System.Diagnostics; ////using System.Security.Permissions; ////using System.Collections; ////using System.Security; ////using System.Text; using System.Runtime.ConstrainedExecution; ////using System.Runtime.CompilerServices; ////using System.Runtime.InteropServices; ////using System.Runtime.Serialization; ////using System.Runtime.Versioning; ////using RuntimeTypeCache = System.RuntimeType.RuntimeTypeCache; ////using CorElementType = System.Reflection.CorElementType; ////using MdToken = System.Reflection.MetadataToken; [Serializable] ////[PermissionSetAttribute( SecurityAction.InheritanceDemand, Name = "FullTrust" )] public abstract class ConstructorInfo : MethodBase { #region Static Members //// public readonly static String ConstructorName = ".ctor"; //// //// public readonly static String TypeConstructorName = ".cctor"; #endregion #region Constructor protected ConstructorInfo() { } #endregion #region MemberInfo Overrides public override MemberTypes MemberType { get { return System.Reflection.MemberTypes.Constructor; } } #endregion #region Public Abstract\Virtual Members //// public abstract Object Invoke( BindingFlags invokeAttr, Binder binder, Object[] parameters, CultureInfo culture ); #endregion #region Public Members //// internal override Type GetReturnType() //// { //// return DeclaringType; //// } //// //// [DebuggerStepThroughAttribute] //// [Diagnostics.DebuggerHidden] //// public Object Invoke( Object[] parameters ) //// { //// return Invoke( BindingFlags.Default, null, parameters, null ); //// } #endregion } } ================================================ FILE: Zelig/Zelig/RunTime/Framework/mscorlib/System/Reflection/DefaultMemberAttribute.cs ================================================ // ==++== // // Copyright (c) Microsoft Corporation. All rights reserved. // // ==--== //////////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////////// // // DefaultMemberAttribute is defines the Member of a Type that is the "default" // member used by Type.InvokeMember. The default member is simply a name given // to a type. // // // // namespace System.Reflection { using System; [AttributeUsage( AttributeTargets.Class | AttributeTargets.Struct | AttributeTargets.Interface ), Serializable] public sealed class DefaultMemberAttribute : Attribute { // The name of the member private String m_memberName; // You must provide the name of the member, this is required public DefaultMemberAttribute( String memberName ) { m_memberName = memberName; } // A get accessor to return the name from the attribute. // NOTE: There is no setter because the name must be provided // to the constructor. The name is not optional. public String MemberName { get { return m_memberName; } } } } ================================================ FILE: Zelig/Zelig/RunTime/Framework/mscorlib/System/Reflection/EventInfo.cs ================================================ // ==++== // // Copyright (c) Microsoft Corporation. All rights reserved. // // ==--== namespace System.Reflection { using System; using System.Reflection; ////using System.Reflection.Cache; ////using System.Reflection.Emit; using System.Globalization; using System.Threading; using System.Diagnostics; ////using System.Security.Permissions; ////using System.Collections; ////using System.Security; ////using System.Text; using System.Runtime.ConstrainedExecution; ////using System.Runtime.CompilerServices; ////using System.Runtime.InteropServices; ////using System.Runtime.Serialization; ////using System.Runtime.Versioning; ////using RuntimeTypeCache = System.RuntimeType.RuntimeTypeCache; ////using CorElementType = System.Reflection.CorElementType; ////using MdToken = System.Reflection.MetadataToken; [Serializable] ////[PermissionSetAttribute( SecurityAction.InheritanceDemand, Name = "FullTrust" )] public abstract class EventInfo : MemberInfo { #region Constructor protected EventInfo() { } #endregion #region MemberInfo Overrides public override MemberTypes MemberType { get { return MemberTypes.Event; } } #endregion #region Public Abstract\Virtual Members //// public virtual MethodInfo[] GetOtherMethods( bool nonPublic ) //// { //// throw new NotImplementedException(); //// } //// //// public abstract MethodInfo GetAddMethod( bool nonPublic ); //// //// public abstract MethodInfo GetRemoveMethod( bool nonPublic ); //// //// public abstract MethodInfo GetRaiseMethod( bool nonPublic ); //// //// public abstract EventAttributes Attributes //// { //// get; //// } #endregion #region Public Members //// public MethodInfo[] GetOtherMethods() //// { //// return GetOtherMethods( false ); //// } //// //// public MethodInfo GetAddMethod() //// { //// return GetAddMethod( false ); //// } //// //// public MethodInfo GetRemoveMethod() //// { //// return GetRemoveMethod( false ); //// } //// //// public MethodInfo GetRaiseMethod() //// { //// return GetRaiseMethod( false ); //// } //// //// [DebuggerStepThroughAttribute] //// [Diagnostics.DebuggerHidden] //// public void AddEventHandler( Object target, Delegate handler ) //// { //// MethodInfo addMethod = GetAddMethod(); //// //// if(addMethod == null) //// { //// throw new InvalidOperationException( Environment.GetResourceString( "InvalidOperation_NoPublicAddMethod" ) ); //// } //// //// addMethod.Invoke( target, new object[] { handler } ); //// } //// //// [DebuggerStepThroughAttribute] //// [Diagnostics.DebuggerHidden] //// public void RemoveEventHandler( Object target, Delegate handler ) //// { //// MethodInfo removeMethod = GetRemoveMethod(); //// //// if(removeMethod == null) //// { //// throw new InvalidOperationException( Environment.GetResourceString( "InvalidOperation_NoPublicRemoveMethod" ) ); //// } //// //// removeMethod.Invoke( target, new object[] { handler } ); //// } //// //// public Type EventHandlerType //// { //// get //// { //// MethodInfo m = GetAddMethod( true ); //// //// ParameterInfo[] p = m.GetParametersNoCopy(); //// //// Type del = typeof( Delegate ); //// //// for(int i = 0; i < p.Length; i++) //// { //// Type c = p[i].ParameterType; //// //// if(c.IsSubclassOf( del )) //// { //// return c; //// } //// } //// return null; //// } //// } //// //// public bool IsSpecialName //// { //// get //// { //// return (Attributes & EventAttributes.SpecialName) != 0; //// } //// } //// //// public bool IsMulticast //// { //// get //// { //// Type cl = EventHandlerType; //// Type mc = typeof( MulticastDelegate ); //// //// return mc.IsAssignableFrom( cl ); //// } //// } #endregion } } ================================================ FILE: Zelig/Zelig/RunTime/Framework/mscorlib/System/Reflection/FieldInfo.cs ================================================ // ==++== // // Copyright (c) Microsoft Corporation. All rights reserved. // // ==--== namespace System.Reflection { using System; using System.Reflection; ////using System.Reflection.Cache; ////using System.Reflection.Emit; using System.Globalization; using System.Threading; ////using System.Diagnostics; ////using System.Security.Permissions; ////using System.Collections; ////using System.Security; ////using System.Text; using System.Runtime.ConstrainedExecution; ////using System.Runtime.CompilerServices; ////using System.Runtime.InteropServices; ////using System.Runtime.Serialization; ////using System.Runtime.Versioning; ////using RuntimeTypeCache = System.RuntimeType.RuntimeTypeCache; ////using CorElementType = System.Reflection.CorElementType; ////using MdToken = System.Reflection.MetadataToken; [Serializable] ////[PermissionSetAttribute( SecurityAction.InheritanceDemand, Name = "FullTrust" )] public abstract class FieldInfo : MemberInfo { #region Static Members //// public static FieldInfo GetFieldFromHandle( RuntimeFieldHandle handle ) //// { //// if(handle.IsNullHandle()) //// { //// throw new ArgumentException( Environment.GetResourceString( "Argument_InvalidHandle" ) ); //// } //// //// FieldInfo f = RuntimeType.GetFieldInfo( handle ); //// //// if(f.DeclaringType != null && f.DeclaringType.IsGenericType) //// { //// throw new ArgumentException( String.Format( CultureInfo.CurrentCulture, Environment.GetResourceString( "Argument_FieldDeclaringTypeGeneric" ), f.Name, f.DeclaringType.GetGenericTypeDefinition() ) ); //// } //// //// return f; //// } //// //// public static FieldInfo GetFieldFromHandle( RuntimeFieldHandle handle, RuntimeTypeHandle declaringType ) //// { //// if(handle.IsNullHandle()) //// { //// throw new ArgumentException( Environment.GetResourceString( "Argument_InvalidHandle" ) ); //// } //// //// return RuntimeType.GetFieldInfo( declaringType, handle ); //// } public static bool operator ==( FieldInfo left, FieldInfo right ) { if ((object)left == null) { return (object)right == null; } if ((object)right == null) { return false; } return left.Equals(right); } public static bool operator !=( FieldInfo left, FieldInfo right ) { return !(left == right); } #endregion #region Constructor protected FieldInfo() { } #endregion #region MemberInfo Overrides public override MemberTypes MemberType { get { return System.Reflection.MemberTypes.Field; } } public override bool Equals( object obj ) { if(obj == null) { return false; } if ((obj is FieldInfo) == false) { return false; } return (this.FieldType == ((FieldInfo)obj).FieldType) && (this.GetValue( this ) == ((FieldInfo)obj).GetValue( obj )); } public override int GetHashCode() { return GetValue( this ).GetHashCode(); } #endregion #region Public Abstract\Virtual Members //// public virtual Type[] GetRequiredCustomModifiers() //// { //// throw new NotImplementedException(); //// } //// //// public virtual Type[] GetOptionalCustomModifiers() //// { //// throw new NotImplementedException(); //// } //// //// [CLSCompliant( false )] //// public virtual void SetValueDirect( TypedReference obj, Object value ) //// { //// throw new NotSupportedException( Environment.GetResourceString( "NotSupported_AbstractNonCLS" ) ); //// } //// //// [CLSCompliant( false )] //// public virtual Object GetValueDirect( TypedReference obj ) //// { //// throw new NotSupportedException( Environment.GetResourceString( "NotSupported_AbstractNonCLS" ) ); //// } //// //// public abstract RuntimeFieldHandle FieldHandle //// { //// get; //// } public abstract Type FieldType { get; } public abstract Object GetValue( Object obj ); //// public virtual Object GetRawConstantValue() //// { //// throw new NotSupportedException( Environment.GetResourceString( "NotSupported_AbstractNonCLS" ) ); //// } //// //// public abstract void SetValue( Object obj, Object value, BindingFlags invokeAttr, Binder binder, CultureInfo culture ); //// //// public abstract FieldAttributes Attributes //// { //// get; //// } #endregion #region Public Members //// [DebuggerStepThroughAttribute] //// [Diagnostics.DebuggerHidden] public void SetValue( Object obj, Object value ) { throw new NotImplementedException(); //// SetValue( obj, value, BindingFlags.Default, Type.DefaultBinder, null ); } //// public bool IsPublic //// { //// get //// { //// return (Attributes & FieldAttributes.FieldAccessMask) == FieldAttributes.Public; //// } //// } //// //// public bool IsPrivate //// { //// get //// { //// return (Attributes & FieldAttributes.FieldAccessMask) == FieldAttributes.Private; //// } //// } //// //// public bool IsFamily //// { //// get //// { //// return (Attributes & FieldAttributes.FieldAccessMask) == FieldAttributes.Family; //// } //// } //// //// public bool IsAssembly //// { //// get //// { //// return (Attributes & FieldAttributes.FieldAccessMask) == FieldAttributes.Assembly; //// } //// } //// //// public bool IsFamilyAndAssembly //// { //// get //// { //// return (Attributes & FieldAttributes.FieldAccessMask) == FieldAttributes.FamANDAssem; //// } //// } //// //// public bool IsFamilyOrAssembly //// { //// get //// { //// return (Attributes & FieldAttributes.FieldAccessMask) == FieldAttributes.FamORAssem; //// } //// } //// //// public bool IsStatic //// { //// get //// { //// return (Attributes & FieldAttributes.Static) != 0; //// } //// } //// //// public bool IsInitOnly //// { //// get //// { //// return (Attributes & FieldAttributes.InitOnly) != 0; //// } //// } //// //// public bool IsLiteral //// { //// get //// { //// return (Attributes & FieldAttributes.Literal) != 0; //// } //// } //// //// public bool IsNotSerialized //// { //// get //// { //// return (Attributes & FieldAttributes.NotSerialized) != 0; //// } //// } //// //// public bool IsSpecialName //// { //// get //// { //// return (Attributes & FieldAttributes.SpecialName) != 0; //// } //// } //// //// public bool IsPinvokeImpl //// { //// get //// { //// return (Attributes & FieldAttributes.PinvokeImpl) != 0; //// } //// } #endregion } } ================================================ FILE: Zelig/Zelig/RunTime/Framework/mscorlib/System/Reflection/ICustomAttributeProvider.cs ================================================ // ==++== // // Copyright (c) Microsoft Corporation. All rights reserved. // // ==--== //////////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////////// // // ICustomAttributeProvider is an interface that is implemented by reflection // objects which support custom attributes. // // Author: darylo & Rajesh Chandrashekaran (rajeshc) // Date: July 99 // namespace System.Reflection { using System; // Interface does not need to be marked with the serializable attribute public interface ICustomAttributeProvider { // Return an array of custom attributes identified by Type Object[] GetCustomAttributes( Type attributeType, bool inherit ); // Return an array of all of the custom attributes (named attributes are not included) Object[] GetCustomAttributes( bool inherit ); // Returns true if one or more instance of attributeType is defined on this member. bool IsDefined( Type attributeType, bool inherit ); } } ================================================ FILE: Zelig/Zelig/RunTime/Framework/mscorlib/System/Reflection/IReflect.cs ================================================ // ==++== // // Copyright (c) Microsoft Corporation. All rights reserved. // // ==--== //////////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////////// // // IReflect is an interface that defines a subset of the Type reflection methods. // This interface is used to access and invoke members of a Type. It can be either // type based (like Type) or instance based (like Expando). This interface is used in // combination with IExpando to model the IDispatchEx expando capibilities in // the interop layer. // // Author: darylo // Date: Sep 98 // namespace System.Reflection { using System; using System.Runtime.InteropServices; using CultureInfo = System.Globalization.CultureInfo; // Interface does not need to be marked with the serializable attribute public interface IReflect { // Return the requested method if it is implemented by the Reflection object. The // match is based upon the name and DescriptorInfo which describes the signature // of the method. MethodInfo GetMethod( String name, BindingFlags bindingAttr, Binder binder, Type[] types, ParameterModifier[] modifiers ); // Return the requested method if it is implemented by the Reflection object. The // match is based upon the name of the method. If the object implementes multiple methods // with the same name an AmbiguousMatchException is thrown. MethodInfo GetMethod( String name, BindingFlags bindingAttr ); MethodInfo[] GetMethods( BindingFlags bindingAttr ); // Return the requestion field if it is implemented by the Reflection object. The // match is based upon a name. There cannot be more than a single field with // a name. FieldInfo GetField( String name, BindingFlags bindingAttr ); FieldInfo[] GetFields( BindingFlags bindingAttr ); // Return the property based upon name. If more than one property has the given // name an AmbiguousMatchException will be thrown. Returns null if no property // is found. PropertyInfo GetProperty( String name, BindingFlags bindingAttr ); // Return the property based upon the name and Descriptor info describing the property // indexing. Return null if no property is found. PropertyInfo GetProperty( String name, BindingFlags bindingAttr, Binder binder, Type returnType, Type[] types, ParameterModifier[] modifiers ); // Returns an array of PropertyInfos for all the properties defined on // the Reflection object. PropertyInfo[] GetProperties( BindingFlags bindingAttr ); // Return an array of members which match the passed in name. MemberInfo[] GetMember( String name, BindingFlags bindingAttr ); // Return an array of all of the members defined for this object. MemberInfo[] GetMembers( BindingFlags bindingAttr ); // Description of the Binding Process. // We must invoke a method that is accessable and for which the provided // parameters have the most specific match. A method may be called if // 1. The number of parameters in the method declaration equals the number of // arguments provided to the invocation // 2. The type of each argument can be converted by the binder to the // type of the type of the parameter. // // The binder will find all of the matching methods. These method are found based // upon the type of binding requested (MethodInvoke, Get/Set Properties). The set // of methods is filtered by the name, number of arguments and a set of search modifiers // defined in the Binder. // // After the method is selected, it will be invoked. Accessability is checked // at that point. The search may be control which set of methods are searched based // upon the accessibility attribute associated with the method. // // The BindToMethod method is responsible for selecting the method to be invoked. // For the default binder, the most specific method will be selected. // // This will invoke a specific member... Object InvokeMember( String name , BindingFlags invokeAttr , Binder binder , Object target , Object[] args , ParameterModifier[] modifiers , CultureInfo culture , String[] namedParameters ); // Return the underlying Type that represents the IReflect Object. For expando object, // this is the (Object) IReflectInstance.GetType(). For Type object it is this. Type UnderlyingSystemType { get; } } } ================================================ FILE: Zelig/Zelig/RunTime/Framework/mscorlib/System/Reflection/InterfaceMapping.cs ================================================ // ==++== // // Copyright (c) Microsoft Corporation. All rights reserved. // // ==--== //////////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////////// // // Interface Map. This struct returns the mapping of an interface into the actual methods on a class // that implement that interface. // // Author: darylo // Date: March 2000 // namespace System.Reflection { using System; public struct InterfaceMapping { public Type TargetType; // The type implementing the interface public Type InterfaceType; // The type representing the interface public MethodInfo[] TargetMethods; // The methods implementing the interface public MethodInfo[] InterfaceMethods; // The methods defined on the interface } } ================================================ FILE: Zelig/Zelig/RunTime/Framework/mscorlib/System/Reflection/MemberInfo.cs ================================================ // ==++== // // Copyright (c) Microsoft Corporation. All rights reserved. // // ==--== namespace System.Reflection { using System; using System.Reflection; ////using System.Reflection.Cache; ////using System.Reflection.Emit; using System.Globalization; using System.Threading; ////using System.Diagnostics; ////using System.Security.Permissions; ////using System.Collections; ////using System.Security; ////using System.Text; using System.Runtime.ConstrainedExecution; ////using System.Runtime.CompilerServices; ////using System.Runtime.InteropServices; ////using System.Runtime.Serialization; ////using System.Runtime.Versioning; ////using RuntimeTypeCache = System.RuntimeType.RuntimeTypeCache; ////using CorElementType = System.Reflection.CorElementType; ////using MdToken = System.Reflection.MetadataToken; internal enum MemberListType { All , CaseSensitive , CaseInsensitive, HandleToInfo , } [Serializable] ////[PermissionSetAttribute( SecurityAction.InheritanceDemand, Name = "FullTrust" )] public abstract class MemberInfo : ICustomAttributeProvider { #region Static Members public static bool operator ==( MemberInfo left, MemberInfo right ) { if ((object)left == null) { return (object)right == null; } if ((object)right == null) { return false; } return left.Equals( right ); } public static bool operator !=( MemberInfo left, MemberInfo right ) { return !(left == right); } #endregion #region Consts // // Invocation cached flags. Those are used in unmanaged code as well // so be careful if you change them // internal const uint INVOCATION_FLAGS_UNKNOWN = 0x00000000; internal const uint INVOCATION_FLAGS_INITIALIZED = 0x00000001; // it's used for both method and field to signify that no access is allowed internal const uint INVOCATION_FLAGS_NO_INVOKE = 0x00000002; internal const uint INVOCATION_FLAGS_NEED_SECURITY = 0x00000004; internal const uint INVOCATION_FLAGS_NO_CTOR_INVOKE = 0x00000008; // because field and method are different we can reuse the same bits method internal const uint INVOCATION_FLAGS_IS_CTOR = 0x00000010; internal const uint INVOCATION_FLAGS_RISKY_METHOD = 0x00000020; internal const uint INVOCATION_FLAGS_SECURITY_IMPOSED = 0x00000040; internal const uint INVOCATION_FLAGS_IS_DELEGATE_CTOR = 0x00000080; internal const uint INVOCATION_FLAGS_CONTAINS_STACK_POINTERS = 0x00000100; // field internal const uint INVOCATION_FLAGS_SPECIAL_FIELD = 0x00000010; internal const uint INVOCATION_FLAGS_FIELD_SPECIAL_CAST = 0x00000020; // temporary flag used for flagging invocation of method vs ctor // this flag never appears on the instance m_invocationFlag and is simply // passed down from within ConstructorInfo.Invoke() internal const uint INVOCATION_FLAGS_CONSTRUCTOR_INVOKE = 0x10000000; #endregion #region Constructor protected MemberInfo() { } #endregion #region MemberInfo Overrides public override bool Equals( object obj ) { if (obj == null) { return false; } if ((obj is MemberInfo) == false) { return false; } return this.GetHashCode() == obj.GetHashCode(); } public override int GetHashCode() { return MetadataTokenInternal; } #endregion #region Internal Methods //// internal virtual bool CacheEquals( object o ) //// { //// throw new NotImplementedException(); //// } #endregion #region Legacy Remoting Cache //// // The size of CachedData is accounted for by BaseObjectWithCachedData in object.h. //// // This member is currently being used by Remoting for caching remoting data. If you //// // need to cache data here, talk to the Remoting team to work out a mechanism, so that //// // both caching systems can happily work together. //// private InternalCache m_cachedData; //// //// internal InternalCache Cache //// { //// get //// { //// // This grabs an internal copy of m_cachedData and uses //// // that instead of looking at m_cachedData directly because //// // the cache may get cleared asynchronously. This prevents //// // us from having to take a lock. //// InternalCache cache = m_cachedData; //// if(cache == null) //// { //// cache = new InternalCache( "MemberInfo" ); //// //// InternalCache ret = Interlocked.CompareExchange( ref m_cachedData, cache, null ); //// if(ret != null) //// { //// cache = ret; //// } //// //// GC.ClearCache += new ClearCacheHandler( OnCacheClear ); //// } //// //// return cache; //// } //// } //// //// //// internal void OnCacheClear( Object sender, ClearCacheEventArgs cacheEventArgs ) //// { //// m_cachedData = null; //// } #endregion #region Public Abstract\Virtual Members public abstract MemberTypes MemberType { get; } public abstract String Name { get; } public abstract Type DeclaringType { get; } //// public abstract Type ReflectedType //// { //// get; //// } #region ICustomAttributeProvider public abstract Object[] GetCustomAttributes( bool inherit ); public abstract Object[] GetCustomAttributes( Type attributeType, bool inherit ); public abstract bool IsDefined( Type attributeType, bool inherit ); #endregion public virtual int MetadataToken { get { throw new InvalidOperationException(); } } internal virtual int MetadataTokenInternal { get { return MetadataToken; } } public virtual Module Module { get { if(this is Type) { return ((Type)this).Module; } throw new NotImplementedException(); } } #endregion } } ================================================ FILE: Zelig/Zelig/RunTime/Framework/mscorlib/System/Reflection/MemberTypes.cs ================================================ // ==++== // // Copyright (c) Microsoft Corporation. All rights reserved. // // ==--== //////////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////////// // // MemberTypes is an bit mask marking each type of Member that is defined as // a subclass of MemberInfo. These are returned by MemberInfo.MemberType and // are useful in switch statements. // // Author: darylo // Date: July 99 // namespace System.Reflection { using System; // This Enum matchs the CorTypeAttr defined in CorHdr.h [Flags] [Serializable] public enum MemberTypes { // The following are the known classes which extend MemberInfo Constructor = 0x01, Event = 0x02, Field = 0x04, Method = 0x08, Property = 0x10, TypeInfo = 0x20, Custom = 0x40, NestedType = 0x80, All = Constructor | Event | Field | Method | Property | TypeInfo | NestedType, } } ================================================ FILE: Zelig/Zelig/RunTime/Framework/mscorlib/System/Reflection/MethodAttributes.cs ================================================ // ==++== // // Copyright (c) Microsoft Corporation. All rights reserved. // // ==--== //////////////////////////////////////////////////////////////////////////////// namespace System.Reflection { using System; [Flags] ////[Serializable] public enum MethodAttributes { // NOTE: This Enum matchs the CorMethodAttr defined in CorHdr.h // member access mask - Use this mask to retrieve accessibility information. MemberAccessMask = 0x0007, PrivateScope = 0x0000, // Member not referenceable. Private = 0x0001, // Accessible only by the parent type. FamANDAssem = 0x0002, // Accessible by sub-types only in this Assembly. Assembly = 0x0003, // Accessibly by anyone in the Assembly. Family = 0x0004, // Accessible only by type and sub-types. FamORAssem = 0x0005, // Accessibly by sub-types anywhere, plus anyone in assembly. Public = 0x0006, // Accessibly by anyone who has visibility to this scope. // end member access mask // method contract attributes. Static = 0x0010, // Defined on type, else per instance. Final = 0x0020, // Method may not be overridden. Virtual = 0x0040, // Method virtual. HideBySig = 0x0080, // Method hides by name+sig, else just by name. CheckAccessOnOverride = 0x0200, // vtable layout mask - Use this mask to retrieve vtable attributes. VtableLayoutMask = 0x0100, ReuseSlot = 0x0000, // The default. NewSlot = 0x0100, // Method always gets a new slot in the vtable. // end vtable layout mask // method implementation attributes. Abstract = 0x0400, // Method does not provide an implementation. SpecialName = 0x0800, // Method is special. Name describes how. // interop attributes PinvokeImpl = 0x2000, // Implementation is forwarded through pinvoke. UnmanagedExport = 0x0008, // Managed method exported via thunk to unmanaged code. RTSpecialName = 0x1000, // Runtime should check name encoding. // Reserved flags for runtime use only. ReservedMask = 0xd000, HasSecurity = 0x4000, // Method has security associate with it. RequireSecObject = 0x8000, // Method calls another method containing security code. } } ================================================ FILE: Zelig/Zelig/RunTime/Framework/mscorlib/System/Reflection/MethodBase.cs ================================================ // ==++== // // Copyright (c) Microsoft Corporation. All rights reserved. // // ==--== namespace System.Reflection { using System; using System.Reflection; ////using System.Reflection.Cache; ////using System.Reflection.Emit; using System.Globalization; using System.Threading; ////using System.Diagnostics; ////using System.Security.Permissions; ////using System.Collections; ////using System.Security; ////using System.Text; using System.Runtime.ConstrainedExecution; using System.Runtime.CompilerServices; ////using System.Runtime.InteropServices; ////using System.Runtime.Serialization; ////using System.Runtime.Versioning; ////using RuntimeTypeCache = System.RuntimeType.RuntimeTypeCache; ////using CorElementType = System.Reflection.CorElementType; ////using MdToken = System.Reflection.MetadataToken; [Serializable] ////[PermissionSetAttribute( SecurityAction.InheritanceDemand, Name = "FullTrust" )] public abstract class MethodBase : MemberInfo { #region Static Members //// public static MethodBase GetMethodFromHandle( RuntimeMethodHandle handle ) //// { //// if(handle.IsNullHandle()) //// { //// throw new ArgumentException( Environment.GetResourceString( "Argument_InvalidHandle" ) ); //// } //// //// MethodBase m = RuntimeType.GetMethodBase( handle ); //// //// if(m.DeclaringType != null && m.DeclaringType.IsGenericType) //// { //// throw new ArgumentException( String.Format( CultureInfo.CurrentCulture, Environment.GetResourceString( "Argument_MethodDeclaringTypeGeneric" ), m, m.DeclaringType.GetGenericTypeDefinition() ) ); //// } //// //// return m; //// } //// //// public static MethodBase GetMethodFromHandle( RuntimeMethodHandle handle, RuntimeTypeHandle declaringType ) //// { //// if(handle.IsNullHandle()) //// { //// throw new ArgumentException( Environment.GetResourceString( "Argument_InvalidHandle" ) ); //// } //// //// return RuntimeType.GetMethodBase( declaringType, handle ); //// } //// //// [DynamicSecurityMethod] // Specify DynamicSecurityMethod attribute to prevent inlining of the caller. //// public static MethodBase GetCurrentMethod() //// { //// StackCrawlMark stackMark = StackCrawlMark.LookForMyCaller; //// //// return RuntimeMethodInfo.InternalGetCurrentMethod( ref stackMark ); //// } #endregion #region Constructor //// protected MethodBase() //// { //// } #endregion #region Internal Members //// internal virtual bool IsOverloaded //// { //// get //// { //// throw new NotSupportedException( Environment.GetResourceString( "InvalidOperation_Method" ) ); //// } //// } //// //// internal virtual RuntimeMethodHandle GetMethodHandle() //// { //// return MethodHandle; //// } #endregion #region Public Abstract\Virtual Members //// internal virtual Type GetReturnType() //// { //// throw new NotImplementedException(); //// } //// //// internal virtual ParameterInfo[] GetParametersNoCopy() //// { //// return GetParameters(); //// } public abstract ParameterInfo[] GetParameters(); //// public abstract MethodImplAttributes GetMethodImplementationFlags(); //// //// public abstract RuntimeMethodHandle MethodHandle //// { //// get; //// } //// //// public abstract MethodAttributes Attributes //// { //// get; //// } public abstract Object Invoke( Object obj, BindingFlags invokeAttr, Binder binder, Object[] parameters, CultureInfo culture ); //// public virtual CallingConventions CallingConvention //// { //// get //// { //// return CallingConventions.Standard; //// } //// } public virtual Type[ ] GetGenericArguments( ) { throw new NotSupportedException( Environment.GetResourceString( "NotSupported_SubclassOverride" ) ); } //// public virtual bool IsGenericMethodDefinition //// { //// get //// { //// return false; //// } //// } //// //// public virtual bool ContainsGenericParameters //// { //// get //// { //// return false; //// } //// } public virtual bool IsGenericMethod { get { return false; } } #endregion #region Public Members //// [DebuggerStepThroughAttribute] [Diagnostics.DebuggerHidden] public Object Invoke( Object obj, Object[] parameters ) { return Invoke( obj, BindingFlags.Default, null, parameters, null ); } //// public bool IsPublic //// { //// get //// { //// return (Attributes & MethodAttributes.MemberAccessMask) == MethodAttributes.Public; //// } //// } //// //// public bool IsPrivate //// { //// get //// { //// return (Attributes & MethodAttributes.MemberAccessMask) == MethodAttributes.Private; //// } //// } //// //// public bool IsFamily //// { //// get //// { //// return (Attributes & MethodAttributes.MemberAccessMask) == MethodAttributes.Family; //// } //// } //// //// public bool IsAssembly //// { //// get //// { //// return (Attributes & MethodAttributes.MemberAccessMask) == MethodAttributes.Assembly; //// } //// } //// //// public bool IsFamilyAndAssembly //// { //// get //// { //// return (Attributes & MethodAttributes.MemberAccessMask) == MethodAttributes.FamANDAssem; //// } //// } //// //// public bool IsFamilyOrAssembly //// { //// get //// { //// return (Attributes & MethodAttributes.MemberAccessMask) == MethodAttributes.FamORAssem; //// } //// } //// //// public bool IsStatic //// { //// get //// { //// return (Attributes & MethodAttributes.Static) != 0; //// } //// } //// //// public bool IsFinal //// { //// get //// { //// return (Attributes & MethodAttributes.Final) != 0; //// } //// } //// //// public bool IsVirtual //// { //// get //// { //// return (Attributes & MethodAttributes.Virtual) != 0; //// } //// } //// //// public bool IsHideBySig //// { //// get //// { //// return (Attributes & MethodAttributes.HideBySig) != 0; //// } //// } public extern bool IsAbstract { [MethodImpl( MethodImplOptions.InternalCall )] get; //// { //// return (Attributes & MethodAttributes.Abstract) != 0; //// } } //// public bool IsSpecialName //// { //// get //// { //// return (Attributes & MethodAttributes.SpecialName) != 0; //// } //// } //// //// public bool IsConstructor //// { //// get //// { //// return ((Attributes & MethodAttributes.RTSpecialName) != 0) && Name.Equals( ConstructorInfo.ConstructorName ); //// } //// } //// //// [ReflectionPermissionAttribute( SecurityAction.Demand, Flags = ReflectionPermissionFlag.MemberAccess )] //// public virtual MethodBody GetMethodBody() //// { //// throw new InvalidOperationException(); //// } #endregion #region Private Invocation Helpers //// [ResourceExposure( ResourceScope.None )] //// [MethodImpl( MethodImplOptions.InternalCall )] //// static extern internal uint GetSpecialSecurityFlags( RuntimeMethodHandle method ); //// //// [ResourceExposure( ResourceScope.None )] //// [MethodImpl( MethodImplOptions.InternalCall )] //// static extern internal void PerformSecurityCheck( Object obj, RuntimeMethodHandle method, IntPtr parent, uint invocationFlags ); #endregion #region Internal Methods //// internal virtual Type[] GetParameterTypes() //// { //// ParameterInfo[] paramInfo = GetParametersNoCopy(); //// Type[] parameterTypes = null; //// //// parameterTypes = new Type[paramInfo.Length]; //// for(int i = 0; i < paramInfo.Length; i++) //// { //// parameterTypes[i] = paramInfo[i].ParameterType; //// } //// //// return parameterTypes; //// } //// //// virtual internal uint GetOneTimeFlags() //// { //// RuntimeMethodHandle handle = MethodHandle; //// //// uint invocationFlags = 0; //// Type declaringType = DeclaringType; //// //// // //// // first take care of all the NO_INVOKE cases //// if( //// (ContainsGenericParameters) || //// (declaringType != null && declaringType.ContainsGenericParameters) || //// ((CallingConvention & CallingConventions.VarArgs) == CallingConventions.VarArgs) || //// ((Attributes & MethodAttributes.RequireSecObject) == MethodAttributes.RequireSecObject) || //// (Module.Assembly.GetType() == typeof( AssemblyBuilder ) && ((AssemblyBuilder)Module.Assembly).m_assemblyData.m_access == AssemblyBuilderAccess.Save) //// ) //// { //// invocationFlags |= INVOCATION_FLAGS_NO_INVOKE; //// } //// else //// { //// // //// // this should be an invocable method, determine the other flags that participate in invocation //// invocationFlags |= MethodBase.GetSpecialSecurityFlags( handle ); //// //// if((invocationFlags & INVOCATION_FLAGS_NEED_SECURITY) == 0) //// { //// // determine whether the method needs security //// if( //// ((Attributes & MethodAttributes.MemberAccessMask) != MethodAttributes.Public) || //// (declaringType != null && !declaringType.IsVisible) //// ) //// { //// invocationFlags |= INVOCATION_FLAGS_NEED_SECURITY; //// } //// else if(IsGenericMethod) //// { //// Type[] genericArguments = GetGenericArguments(); //// //// for(int i = 0; i < genericArguments.Length; i++) //// { //// if(!genericArguments[i].IsVisible) //// { //// invocationFlags |= INVOCATION_FLAGS_NEED_SECURITY; //// break; //// } //// } //// } //// } //// //// } //// //// invocationFlags |= GetOneTimeSpecificFlags(); //// //// invocationFlags |= INVOCATION_FLAGS_INITIALIZED; //// return invocationFlags; //// } //// //// // only ctors have special flags for now //// internal virtual uint GetOneTimeSpecificFlags() //// { //// return 0; //// } //// //// internal Object[] CheckArguments( Object[] parameters, Binder binder, BindingFlags invokeAttr, CultureInfo culture, Signature sig ) //// { //// int actualCount = (parameters != null) ? parameters.Length : 0; //// // copy the arguments in a different array so we detach from any user changes //// Object[] copyOfParameters = new Object[actualCount]; //// //// ParameterInfo[] p = null; //// for(int i = 0; i < actualCount; i++) //// { //// Object arg = parameters[i]; //// RuntimeTypeHandle argRTH = sig.Arguments[i]; //// //// if(arg == Type.Missing) //// { //// if(p == null) //// { //// p = GetParametersNoCopy(); //// } //// //// if(p[i].DefaultValue == System.DBNull.Value) //// { //// throw new ArgumentException( Environment.GetResourceString( "Arg_VarMissNull" ), "parameters" ); //// } //// //// arg = p[i].DefaultValue; //// } //// //// if(argRTH.IsInstanceOfType( arg )) //// { //// copyOfParameters[i] = arg; //// } //// else //// { //// copyOfParameters[i] = argRTH.GetRuntimeType().CheckValue( arg, binder, culture, invokeAttr ); //// } //// } //// //// return copyOfParameters; //// } #endregion } } ================================================ FILE: Zelig/Zelig/RunTime/Framework/mscorlib/System/Reflection/MethodImplAttributes.cs ================================================ // ==++== // // Copyright (c) Microsoft Corporation. All rights reserved. // // ==--== namespace System.Reflection { using System; // This Enum matchs the CorMethodImpl defined in CorHdr.h [Serializable] public enum MethodImplAttributes { // code impl mask CodeTypeMask = 0x0003, // Flags about code type. IL = 0x0000, // Method impl is IL. Native = 0x0001, // Method impl is native. /// OPTIL = 0x0002, // Method impl is OPTIL Runtime = 0x0003, // Method impl is provided by the runtime. // end code impl mask // managed mask ManagedMask = 0x0004, // Flags specifying whether the code is managed or unmanaged. Unmanaged = 0x0004, // Method impl is unmanaged, otherwise managed. Managed = 0x0000, // Method impl is managed. // end managed mask // implementation info and interop ForwardRef = 0x0010, // Indicates method is not defined; used primarily in merge scenarios. PreserveSig = 0x0080, // Indicates method sig is exported exactly as declared. InternalCall = 0x1000, // Internal Call... Synchronized = 0x0020, // Method is single threaded through the body. NoInlining = 0x0008, // Method may not be inlined. MaxMethodImplVal = 0xFFFF, // Range check value } } ================================================ FILE: Zelig/Zelig/RunTime/Framework/mscorlib/System/Reflection/MethodInfo.cs ================================================ // ==++== // // Copyright (c) Microsoft Corporation. All rights reserved. // // ==--== namespace System.Reflection { using System; using System.Reflection; ////using System.Reflection.Cache; ////using System.Reflection.Emit; using System.Globalization; using System.Threading; ////using System.Diagnostics; ////using System.Security.Permissions; ////using System.Collections; ////using System.Security; ////using System.Text; using System.Runtime.ConstrainedExecution; ////using System.Runtime.CompilerServices; ////using System.Runtime.InteropServices; ////using System.Runtime.Serialization; ////using System.Runtime.Versioning; ////using RuntimeTypeCache = System.RuntimeType.RuntimeTypeCache; ////using CorElementType = System.Reflection.CorElementType; ////using MdToken = System.Reflection.MetadataToken; [Serializable] ////[PermissionSetAttribute( SecurityAction.InheritanceDemand, Name = "FullTrust" )] public abstract class MethodInfo : MethodBase { #region Constructor protected MethodInfo() { } #endregion #region MemberInfo Overrides public override MemberTypes MemberType { get { return System.Reflection.MemberTypes.Method; } } #endregion #region Internal Members //// internal virtual MethodInfo GetParentDefinition() //// { //// return null; //// } #endregion #region Public Abstract\Virtual Members //// public virtual Type ReturnType //// { //// get //// { //// return GetReturnType(); //// } //// } //// //// internal override Type GetReturnType() //// { //// return ReturnType; //// } //// //// public virtual ParameterInfo ReturnParameter //// { //// get //// { //// throw new NotImplementedException(); //// } //// } //// //// public abstract ICustomAttributeProvider ReturnTypeCustomAttributes //// { //// get; //// } //// //// public abstract MethodInfo GetBaseDefinition(); public override Type[ ] GetGenericArguments( ) { throw new NotSupportedException( Environment.GetResourceString( "NotSupported_SubclassOverride" ) ); } //// public virtual MethodInfo GetGenericMethodDefinition() //// { //// throw new NotSupportedException( Environment.GetResourceString( "NotSupported_SubclassOverride" ) ); //// } //// //// public override bool IsGenericMethodDefinition //// { //// get //// { //// return false; //// } //// } //// //// public override bool ContainsGenericParameters //// { //// get //// { //// return false; //// } //// } //// //// public virtual MethodInfo MakeGenericMethod( params Type[] typeArguments ) //// { //// throw new NotSupportedException( Environment.GetResourceString( "NotSupported_SubclassOverride" ) ); //// } //// public override bool IsGenericMethod { get { return false; } } #endregion } } ================================================ FILE: Zelig/Zelig/RunTime/Framework/mscorlib/System/Reflection/Module.cs ================================================ // ==++== // // Copyright (c) Microsoft Corporation. All rights reserved. // // ==--== //////////////////////////////////////////////////////////////////////////////// namespace System.Reflection { using System; ////using System.Diagnostics.SymbolStore; ////using System.Runtime.Remoting; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using System.Runtime.Serialization; ////using System.Reflection.Emit; using System.Collections; using System.Threading; ////using System.Security; ////using System.Security.Permissions; ////using System.IO; using System.Globalization; ////using System.Runtime.Versioning; [Flags] [Serializable] public enum PortableExecutableKinds { NotAPortableExecutableImage = 0x0, ILOnly = 0x1, Required32Bit = 0x2, PE32Plus = 0x4, Unmanaged32Bit = 0x8, } [Serializable] public enum ImageFileMachine { I386 = 0x014c, IA64 = 0x0200, AMD64 = 0x8664, } [Serializable] public class Module /*: ISerializable, ICustomAttributeProvider*/ { #region FCalls //// [ResourceExposure( ResourceScope.None )] //// [MethodImpl( MethodImplOptions.InternalCall )] //// [SuppressUnmanagedCodeSecurity] //// private extern static RuntimeTypeHandle GetType( ModuleHandle module, String className, bool ignoreCase, bool throwOnError ); //// //// [ResourceExposure( ResourceScope.None )] //// [MethodImpl( MethodImplOptions.InternalCall )] //// [SuppressUnmanagedCodeSecurity] //// private extern static void GetScopeName( ModuleHandle module, StringHandleOnStack retString ); //// //// [ResourceExposure( ResourceScope.Machine )] //// [MethodImpl( MethodImplOptions.InternalCall )] //// [SuppressUnmanagedCodeSecurity] //// private extern static void GetFullyQualifiedName( ModuleHandle module, StringHandleOnStack retString ); //// //// [ResourceExposure( ResourceScope.None )] //// [MethodImpl( MethodImplOptions.InternalCall )] //// private extern static Type[] GetTypes( IntPtr module, ref StackCrawlMark stackMark ); //// //// internal Type[] GetTypes( ref StackCrawlMark stackMark ) //// { //// return GetTypes( GetNativeHandle().Value, ref stackMark ); //// } //// //// [ResourceExposure( ResourceScope.None )] //// [MethodImpl( MethodImplOptions.InternalCall )] //// private extern static bool IsResource( IntPtr module ); //// //// [ResourceExposure( ResourceScope.None )] //// [MethodImpl( MethodImplOptions.InternalCall )] //// [SuppressUnmanagedCodeSecurity] //// static private extern void GetSignerCertificate( ModuleHandle module, ObjectHandleOnStack retData ); #endregion #region Static Constructor //// static Module() //// { //// __Filters _fltObj; //// _fltObj = new __Filters(); //// FilterTypeName = new TypeFilter( _fltObj.FilterTypeName ); //// FilterTypeNameIgnoreCase = new TypeFilter( _fltObj.FilterTypeNameIgnoreCase ); //// } #endregion #region Public Statics //// public static readonly TypeFilter FilterTypeName; //// //// public static readonly TypeFilter FilterTypeNameIgnoreCase; //// //// public MethodBase ResolveMethod( int metadataToken ) //// { //// return ResolveMethod( metadataToken, null, null ); //// } //// //// private static RuntimeTypeHandle[] ConvertToTypeHandleArray( Type[] genericArguments ) //// { //// if(genericArguments == null) //// { //// return null; //// } //// //// int size = genericArguments.Length; //// RuntimeTypeHandle[] typeHandleArgs = new RuntimeTypeHandle[size]; //// for(int i = 0; i < size; i++) //// { //// Type typeArg = genericArguments[i]; //// if(typeArg == null) //// { //// throw new ArgumentException( Environment.GetResourceString( "Argument_InvalidGenericInstArray" ) ); //// } //// //// typeArg = typeArg.UnderlyingSystemType; //// if(typeArg == null) //// { //// throw new ArgumentException( Environment.GetResourceString( "Argument_InvalidGenericInstArray" ) ); //// } //// if(!(typeArg is RuntimeType)) //// { //// throw new ArgumentException( Environment.GetResourceString( "Argument_InvalidGenericInstArray" ) ); //// } //// //// typeHandleArgs[i] = typeArg.GetTypeHandleInternal(); //// } //// return typeHandleArgs; //// } //// //// public byte[] ResolveSignature( int metadataToken ) //// { //// MetadataToken tk = new MetadataToken( metadataToken ); //// //// if(!MetadataImport.IsValidToken( tk )) //// { //// throw new ArgumentOutOfRangeException( "metadataToken", String.Format( CultureInfo.CurrentCulture, Environment.GetResourceString( "Argument_InvalidToken", tk, this ) ) ); //// } //// //// if(!tk.IsMemberRef && !tk.IsMethodDef && !tk.IsTypeSpec && !tk.IsSignature && !tk.IsFieldDef) //// { //// throw new ArgumentException( String.Format( CultureInfo.CurrentCulture, Environment.GetResourceString( "Argument_InvalidToken", tk, this ) ), "metadataToken" ); //// } //// //// ConstArray signature; //// if(tk.IsMemberRef) //// { //// signature = MetadataImport.GetMemberRefProps( metadataToken ); //// } //// else //// { //// signature = MetadataImport.GetSignatureFromToken( metadataToken ); //// } //// //// byte[] sig = new byte[signature.Length]; //// //// for(int i = 0; i < signature.Length; i++) //// { //// sig[i] = signature[i]; //// } //// //// return sig; //// } //// //// public MethodBase ResolveMethod( int metadataToken, Type[] genericTypeArguments, Type[] genericMethodArguments ) //// { //// MetadataToken tk = new MetadataToken( metadataToken ); //// //// if(!MetadataImport.IsValidToken( tk )) //// { //// throw new ArgumentOutOfRangeException( "metadataToken", String.Format( CultureInfo.CurrentCulture, Environment.GetResourceString( "Argument_InvalidToken", tk, this ) ) ); //// } //// //// RuntimeTypeHandle[] typeArgs = ConvertToTypeHandleArray( genericTypeArguments ); //// RuntimeTypeHandle[] methodArgs = ConvertToTypeHandleArray( genericMethodArguments ); //// //// try //// { //// if(!tk.IsMethodDef && !tk.IsMethodSpec) //// { //// if(!tk.IsMemberRef) //// { //// throw new ArgumentException( "metadataToken", String.Format( CultureInfo.CurrentCulture, Environment.GetResourceString( "Argument_ResolveMethod", tk, this ) ) ); //// } //// //// unsafe //// { //// ConstArray sig = MetadataImport.GetMemberRefProps( tk ); //// //// if(*(MdSigCallingConvention*)sig.Signature.ToPointer() == MdSigCallingConvention.Field) //// { //// throw new ArgumentException( "metadataToken", String.Format( CultureInfo.CurrentCulture, Environment.GetResourceString( "Argument_ResolveMethod" ), tk, this ) ); //// } //// } //// } //// //// RuntimeMethodHandle methodHandle = GetModuleHandle().ResolveMethodHandle( tk, typeArgs, methodArgs ); //// Type declaringType = methodHandle.GetDeclaringType().GetRuntimeType(); //// //// if(declaringType.IsGenericType || declaringType.IsArray) //// { //// MetadataToken tkDeclaringType = new MetadataToken( MetadataImport.GetParentToken( tk ) ); //// //// if(tk.IsMethodSpec) //// { //// tkDeclaringType = new MetadataToken( MetadataImport.GetParentToken( tkDeclaringType ) ); //// } //// //// declaringType = ResolveType( tkDeclaringType, genericTypeArguments, genericMethodArguments ); //// } //// //// return System.RuntimeType.GetMethodBase( declaringType.GetTypeHandleInternal(), methodHandle ); //// } //// catch(BadImageFormatException e) //// { //// throw new ArgumentException( Environment.GetResourceString( "Argument_BadImageFormatExceptionResolve" ), e ); //// } //// } //// //// internal FieldInfo ResolveLiteralField( int metadataToken, Type[] genericTypeArguments, Type[] genericMethodArguments ) //// { //// MetadataToken tk = new MetadataToken( metadataToken ); //// //// if(!MetadataImport.IsValidToken( tk )) //// { //// throw new ArgumentOutOfRangeException( "metadataToken", String.Format( CultureInfo.CurrentUICulture, Environment.GetResourceString( "Argument_InvalidToken", tk, this ) ) ); //// } //// //// string fieldName = MetadataImport.GetName( tk ).ToString(); //// int tkDeclaringType = MetadataImport.GetParentToken( tk ); //// //// Type declaringType = ResolveType( tkDeclaringType, genericTypeArguments, genericMethodArguments ); //// //// declaringType.GetFields(); //// //// try //// { //// return declaringType.GetField( fieldName, //// BindingFlags.Static | BindingFlags.Instance | //// BindingFlags.Public | BindingFlags.NonPublic | //// BindingFlags.DeclaredOnly ); //// } //// catch //// { //// throw new ArgumentException( String.Format( CultureInfo.CurrentCulture, Environment.GetResourceString( "Argument_ResolveField" ), tk, this ), "metadataToken" ); //// } //// } //// //// public FieldInfo ResolveField( int metadataToken ) //// { //// return ResolveField( metadataToken, null, null ); //// } //// //// public FieldInfo ResolveField( int metadataToken, Type[] genericTypeArguments, Type[] genericMethodArguments ) //// { //// MetadataToken tk = new MetadataToken( metadataToken ); //// //// if(!MetadataImport.IsValidToken( tk )) //// { //// throw new ArgumentOutOfRangeException( "metadataToken", String.Format( CultureInfo.CurrentCulture, Environment.GetResourceString( "Argument_InvalidToken", tk, this ) ) ); //// } //// //// RuntimeTypeHandle[] typeArgs = ConvertToTypeHandleArray( genericTypeArguments ); //// RuntimeTypeHandle[] methodArgs = ConvertToTypeHandleArray( genericMethodArguments ); //// //// try //// { //// RuntimeFieldHandle fieldHandle = new RuntimeFieldHandle(); //// //// if(!tk.IsFieldDef) //// { //// if(!tk.IsMemberRef) //// { //// throw new ArgumentException( "metadataToken", String.Format( CultureInfo.CurrentCulture, Environment.GetResourceString( "Argument_ResolveField" ), tk, this ) ); //// } //// //// unsafe //// { //// ConstArray sig = MetadataImport.GetMemberRefProps( tk ); //// //// if(*(MdSigCallingConvention*)sig.Signature.ToPointer() != MdSigCallingConvention.Field) //// { //// throw new ArgumentException( "metadataToken", String.Format( CultureInfo.CurrentCulture, Environment.GetResourceString( "Argument_ResolveField" ), tk, this ) ); //// } //// } //// //// fieldHandle = GetModuleHandle().ResolveFieldHandle( tk, typeArgs, methodArgs ); //// } //// //// fieldHandle = GetModuleHandle().ResolveFieldHandle( metadataToken, typeArgs, methodArgs ); //// Type declaringType = fieldHandle.GetApproxDeclaringType().GetRuntimeType(); //// //// if(declaringType.IsGenericType || declaringType.IsArray) //// { //// int tkDeclaringType = GetModuleHandle().GetMetadataImport().GetParentToken( metadataToken ); //// //// declaringType = ResolveType( tkDeclaringType, genericTypeArguments, genericMethodArguments ); //// } //// //// return System.RuntimeType.GetFieldInfo( declaringType.GetTypeHandleInternal(), fieldHandle ); //// } //// catch(MissingFieldException) //// { //// return ResolveLiteralField( tk, genericTypeArguments, genericMethodArguments ); //// } //// catch(BadImageFormatException e) //// { //// throw new ArgumentException( Environment.GetResourceString( "Argument_BadImageFormatExceptionResolve" ), e ); //// } //// } //// //// public Type ResolveType( int metadataToken ) //// { //// return ResolveType( metadataToken, null, null ); //// } //// //// public Type ResolveType( int metadataToken, Type[] genericTypeArguments, Type[] genericMethodArguments ) //// { //// MetadataToken tk = new MetadataToken( metadataToken ); //// //// if(tk.IsGlobalTypeDefToken) //// { //// throw new ArgumentException( String.Format( CultureInfo.CurrentCulture, Environment.GetResourceString( "Argument_ResolveModuleType" ), tk ), "metadataToken" ); //// } //// //// if(!MetadataImport.IsValidToken( tk )) //// { //// throw new ArgumentOutOfRangeException( "metadataToken", String.Format( CultureInfo.CurrentCulture, Environment.GetResourceString( "Argument_InvalidToken", tk, this ) ) ); //// } //// //// if(!tk.IsTypeDef && !tk.IsTypeSpec && !tk.IsTypeRef) //// { //// throw new ArgumentException( String.Format( CultureInfo.CurrentCulture, Environment.GetResourceString( "Argument_ResolveType" ), tk, this ), "metadataToken" ); //// } //// //// RuntimeTypeHandle[] typeArgs = ConvertToTypeHandleArray( genericTypeArguments ); //// RuntimeTypeHandle[] methodArgs = ConvertToTypeHandleArray( genericMethodArguments ); //// //// try //// { //// Type t = GetModuleHandle().ResolveTypeHandle( metadataToken, typeArgs, methodArgs ).GetRuntimeType(); //// //// if(t == null) //// { //// throw new ArgumentException( String.Format( CultureInfo.CurrentCulture, Environment.GetResourceString( "Argument_ResolveType" ), tk, this ), "metadataToken" ); //// } //// //// return t; //// } //// catch(BadImageFormatException e) //// { //// throw new ArgumentException( Environment.GetResourceString( "Argument_BadImageFormatExceptionResolve" ), e ); //// } //// } //// //// public MemberInfo ResolveMember( int metadataToken ) //// { //// return ResolveMember( metadataToken, null, null ); //// } //// //// public MemberInfo ResolveMember( int metadataToken, Type[] genericTypeArguments, Type[] genericMethodArguments ) //// { //// MetadataToken tk = new MetadataToken( metadataToken ); //// //// if(tk.IsProperty) //// { //// throw new ArgumentException( Environment.GetResourceString( "InvalidOperation_PropertyInfoNotAvailable" ) ); //// } //// //// if(tk.IsEvent) //// { //// throw new ArgumentException( Environment.GetResourceString( "InvalidOperation_EventInfoNotAvailable" ) ); //// } //// //// if(tk.IsMethodSpec || tk.IsMethodDef) //// { //// return ResolveMethod( metadataToken, genericTypeArguments, genericMethodArguments ); //// } //// //// if(tk.IsFieldDef) //// { //// return ResolveField( metadataToken, genericTypeArguments, genericMethodArguments ); //// } //// //// if(tk.IsTypeRef || tk.IsTypeDef || tk.IsTypeSpec) //// { //// return ResolveType( metadataToken, genericTypeArguments, genericMethodArguments ); //// } //// //// if(tk.IsMemberRef) //// { //// if(!MetadataImport.IsValidToken( tk )) //// { //// throw new ArgumentOutOfRangeException( "metadataToken", String.Format( CultureInfo.CurrentCulture, Environment.GetResourceString( "Argument_InvalidToken", tk, this ) ) ); //// } //// //// ConstArray sig = MetadataImport.GetMemberRefProps( tk ); //// //// unsafe //// { //// if(*(MdSigCallingConvention*)sig.Signature.ToPointer() == MdSigCallingConvention.Field) //// { //// return ResolveField( tk, genericTypeArguments, genericMethodArguments ); //// } //// else //// { //// return ResolveMethod( tk, genericTypeArguments, genericMethodArguments ); //// } //// } //// } //// //// throw new ArgumentException( "metadataToken", String.Format( CultureInfo.CurrentCulture, Environment.GetResourceString( "Argument_ResolveMember", tk, this ) ) ); //// } //// //// public string ResolveString( int metadataToken ) //// { //// MetadataToken tk = new MetadataToken( metadataToken ); //// //// if(!tk.IsString) //// { //// throw new ArgumentException( String.Format( CultureInfo.CurrentUICulture, Environment.GetResourceString( "Argument_ResolveString" ), metadataToken, ToString() ) ); //// } //// //// if(!MetadataImport.IsValidToken( tk )) //// { //// throw new ArgumentOutOfRangeException( "metadataToken", String.Format( CultureInfo.CurrentUICulture, Environment.GetResourceString( "Argument_InvalidToken", tk, this ) ) ); //// } //// //// string str = MetadataImport.GetUserString( metadataToken ); //// //// if(str == null) //// { //// throw new ArgumentException( String.Format( CultureInfo.CurrentUICulture, Environment.GetResourceString( "Argument_ResolveString" ), metadataToken, ToString() ) ); //// } //// //// return str; //// } //// //// public void GetPEKind( out PortableExecutableKinds peKind, out ImageFileMachine machine ) //// { //// GetModuleHandle().GetPEKind( out peKind, out machine ); //// } //// //// public int MDStreamVersion //// { //// get //// { //// return GetModuleHandle().MDStreamVersion; //// } //// } //// #endregion #region Literals //// private const BindingFlags DefaultLookup = BindingFlags.Instance | BindingFlags.Static | BindingFlags.Public; #endregion #region Data Members #pragma warning disable 169 //// // If you add any data members, you need to update the native declaration ReflectModuleBaseObject. //// internal ArrayList m_TypeBuilderList; //// internal ISymbolWriter m_iSymWriter; //// internal ModuleBuilderData m_moduleData; //// private RuntimeType m_runtimeType; //// private IntPtr m_pRefClass; //// internal IntPtr m_pData; //// internal IntPtr m_pInternalSymWriter; //// private IntPtr m_pGlobals; //// private IntPtr m_pFields; //// internal MethodToken m_EntryPoint; #pragma warning restore 169 #endregion #region Constructor //// internal Module() //// { //// // Construct a new module. This returns the default dynamic module. //// // 0 is defined as being a module without an entry point (ie a DLL); //// // This must throw because this dies in ToString() when constructed here... //// throw new NotSupportedException( Environment.GetResourceString( ResId.NotSupported_Constructor ) ); //// //m_EntryPoint=new MethodToken(0); //// } #endregion #region Private Members //// private FieldInfo InternalGetField( String name, BindingFlags bindingAttr ) //// { //// if(RuntimeType == null) //// { //// return null; //// } //// //// return RuntimeType.GetField( name, bindingAttr ); //// } #endregion #region Internal Members //// internal virtual bool IsDynamic() //// { //// if(this is ModuleBuilder) //// { //// return true; //// } //// //// return false; //// } //// //// internal RuntimeType RuntimeType //// { //// get //// { //// unsafe //// { //// if(m_runtimeType == null) //// { //// m_runtimeType = GetModuleHandle().GetModuleTypeHandle().GetRuntimeType() as RuntimeType; //// } //// //// return m_runtimeType; //// } //// } //// } #endregion #region Protected Virtuals //// protected virtual MethodInfo GetMethodImpl( String name , //// BindingFlags bindingAttr , //// Binder binder , //// CallingConventions callConvention, //// Type[] types , //// ParameterModifier[] modifiers ) //// { //// if(RuntimeType == null) //// { //// return null; //// } //// //// if(types == null) //// { //// return RuntimeType.GetMethod( name, bindingAttr ); //// } //// else //// { //// return RuntimeType.GetMethod( name, bindingAttr, binder, callConvention, types, modifiers ); //// } //// } //// //// internal MetadataImport MetadataImport //// { //// get //// { //// unsafe //// { //// return ModuleHandle.GetMetadataImport(); //// } //// } //// } #endregion #region ICustomAttributeProvider Members //// public virtual Object[] GetCustomAttributes( bool inherit ) //// { //// return CustomAttribute.GetCustomAttributes( this, typeof( object ) as RuntimeType ); //// } //// //// public virtual Object[] GetCustomAttributes( Type attributeType, bool inherit ) //// { //// if(attributeType == null) //// { //// throw new ArgumentNullException( "attributeType" ); //// } //// //// RuntimeType attributeRuntimeType = attributeType.UnderlyingSystemType as RuntimeType; //// //// if(attributeRuntimeType == null) //// { //// throw new ArgumentException( Environment.GetResourceString( "Arg_MustBeType" ), "attributeType" ); //// } //// //// return CustomAttribute.GetCustomAttributes( this, attributeRuntimeType ); //// } //// //// public virtual bool IsDefined( Type attributeType, bool inherit ) //// { //// if(attributeType == null) //// { //// throw new ArgumentNullException( "attributeType" ); //// } //// //// RuntimeType attributeRuntimeType = attributeType.UnderlyingSystemType as RuntimeType; //// //// if(attributeRuntimeType == null) //// { //// throw new ArgumentException( Environment.GetResourceString( "Arg_MustBeType" ), "caType" ); //// } //// //// return CustomAttribute.IsDefined( this, attributeRuntimeType ); //// } //// #endregion #region Public Virtuals //// [SecurityPermissionAttribute( SecurityAction.LinkDemand, Flags = SecurityPermissionFlag.SerializationFormatter )] //// public virtual void GetObjectData( SerializationInfo info, StreamingContext context ) //// { //// if(info == null) //// { //// throw new ArgumentNullException( "info" ); //// } //// //// UnitySerializationHolder.GetUnitySerializationInfo( info, UnitySerializationHolder.ModuleUnity, this.ScopeName, this.Assembly ); //// } //// //// public virtual Type GetType( String className, bool ignoreCase ) //// { //// return GetType( className, false, ignoreCase ); //// } //// //// public virtual Type GetType( String className ) //// { //// return GetType( className, false, false ); //// } //// //// public virtual Type GetType( String className, bool throwOnError, bool ignoreCase ) //// { //// return GetType( GetNativeHandle(), className, throwOnError, ignoreCase ).GetRuntimeType(); //// } //// //// internal string GetFullyQualifiedName() //// { //// String fullyQualifiedName = null; //// //// GetFullyQualifiedName( GetNativeHandle(), JitHelpers.GetStringHandleOnStack( ref fullyQualifiedName ) ); //// //// return fullyQualifiedName; //// } //// //// public virtual String FullyQualifiedName //// { //// [ResourceExposure( ResourceScope.Machine )] //// [ResourceConsumption( ResourceScope.Machine )] //// get //// { //// String fullyQualifiedName = GetFullyQualifiedName(); //// //// if(fullyQualifiedName != null) //// { //// bool checkPermission = true; //// try //// { //// Path.GetFullPathInternal( fullyQualifiedName ); //// } //// catch(ArgumentException) //// { //// checkPermission = false; //// } //// if(checkPermission) //// { //// new FileIOPermission( FileIOPermissionAccess.PathDiscovery, fullyQualifiedName ).Demand(); //// } //// } //// //// return fullyQualifiedName; //// } //// } //// //// public virtual Type[] FindTypes( TypeFilter filter, Object filterCriteria ) //// { //// StackCrawlMark stackMark = StackCrawlMark.LookForMyCaller; //// //// Type[] c = GetTypes( ref stackMark ); //// int cnt = 0; //// for(int i = 0; i < c.Length; i++) //// { //// if(filter != null && !filter( c[i], filterCriteria )) //// { //// c[i] = null; //// } //// else //// { //// cnt++; //// } //// } //// if(cnt == c.Length) //// { //// return c; //// } //// //// Type[] ret = new Type[cnt]; //// //// cnt = 0; //// for(int i = 0; i < c.Length; i++) //// { //// if(c[i] != null) //// { //// ret[cnt++] = c[i]; //// } //// } //// return ret; //// } //// //// public virtual Type[] GetTypes() //// { //// StackCrawlMark stackMark = StackCrawlMark.LookForMyCaller; //// //// return GetTypes( ref stackMark ); //// } //// #endregion #region Public Members //// public Guid ModuleVersionId //// { //// get //// { //// unsafe //// { //// Guid mvid; //// //// MetadataImport.GetScopeProps( out mvid ); //// //// return mvid; //// } //// } //// } //// //// public int MetadataToken //// { //// get //// { //// return GetModuleHandle().GetToken(); //// } //// } //// //// public bool IsResource() //// { //// return IsResource( GetNativeHandle().Value ); //// } //// //// public FieldInfo[] GetFields() //// { //// if(RuntimeType == null) //// { //// return new FieldInfo[0]; //// } //// //// return RuntimeType.GetFields(); //// } //// //// public FieldInfo[] GetFields( BindingFlags bindingFlags ) //// { //// if(RuntimeType == null) //// { //// return new FieldInfo[0]; //// } //// //// return RuntimeType.GetFields( bindingFlags ); //// } //// //// public FieldInfo GetField( String name ) //// { //// if(name == null) //// { //// throw new ArgumentNullException( "name" ); //// } //// //// return GetField( name, Module.DefaultLookup ); //// } //// //// public FieldInfo GetField( String name, BindingFlags bindingAttr ) //// { //// if(name == null) //// { //// throw new ArgumentNullException( "name" ); //// } //// //// return InternalGetField( name, bindingAttr ); //// } //// //// public MethodInfo[] GetMethods() //// { //// if(RuntimeType == null) //// { //// return new MethodInfo[0]; //// } //// //// return RuntimeType.GetMethods(); //// } //// //// public MethodInfo[] GetMethods( BindingFlags bindingFlags ) //// { //// if(RuntimeType == null) //// { //// return new MethodInfo[0]; //// } //// //// return RuntimeType.GetMethods( bindingFlags ); //// } //// //// public MethodInfo GetMethod( String name , //// BindingFlags bindingAttr , //// Binder binder , //// CallingConventions callConvention, //// Type[] types , //// ParameterModifier[] modifiers ) //// { //// if(name == null) //// { //// throw new ArgumentNullException( "name" ); //// } //// //// if(types == null) //// { //// throw new ArgumentNullException( "types" ); //// } //// //// for(int i = 0; i < types.Length; i++) //// { //// if(types[i] == null) //// { //// throw new ArgumentNullException( "types" ); //// } //// } //// //// return GetMethodImpl( name, bindingAttr, binder, callConvention, types, modifiers ); //// //// } //// //// public MethodInfo GetMethod( String name, Type[] types ) //// { //// if(name == null) //// { //// throw new ArgumentNullException( "name" ); //// } //// //// if(types == null) //// { //// throw new ArgumentNullException( "types" ); //// } //// //// for(int i = 0; i < types.Length; i++) //// { //// if(types[i] == null) //// { //// throw new ArgumentNullException( "types" ); //// } //// } //// //// return GetMethodImpl( name, Module.DefaultLookup, null, CallingConventions.Any, types, null ); //// } //// //// public MethodInfo GetMethod( String name ) //// { //// if(name == null) //// { //// throw new ArgumentNullException( "name" ); //// } //// //// return GetMethodImpl( name, Module.DefaultLookup, null, CallingConventions.Any, null, null ); //// } //// //// public String ScopeName //// { //// get //// { //// string scopeName = null; //// //// GetScopeName( GetNativeHandle(), JitHelpers.GetStringHandleOnStack( ref scopeName ) ); //// //// return scopeName; //// } //// } //// //// public String Name //// { //// [ResourceExposure( ResourceScope.None )] //// [ResourceConsumption( ResourceScope.Machine, ResourceScope.Machine )] //// get //// { //// String s = GetFullyQualifiedName(); //// //// int i = s.LastIndexOf( System.IO.Path.DirectorySeparatorChar ); //// if(i == -1) //// { //// return s; //// } //// //// return new String( s.ToCharArray(), i + 1, s.Length - i - 1 ); //// } //// } //// //// public override String ToString() //// { //// return ScopeName; //// } //// public Assembly Assembly { get { throw new NotImplementedException(); //// return ModuleHandle.GetAssemblyHandle().GetAssembly(); } } //// public ModuleHandle ModuleHandle //// { //// get //// { //// //TODO: Add this back when the GetPEKind is removed from ModuleHandle //// //if (Assembly.ReflectionOnly) //// // throw new InvalidOperationException(Environment.GetResourceString("InvalidOperation_NotAllowedInReflectionOnly")); //// return new ModuleHandle( m_pData ); //// } //// } //// //// internal ModuleHandle GetModuleHandle() //// { //// return new ModuleHandle( m_pData ); //// } //// //// // Returns handle for interop with EE. The handle is guaranteed to be non-null. //// internal ModuleHandle GetNativeHandle() //// { //// IntPtr data = m_pData; //// //// // This should never happen under normal circumstances. m_pData is always assigned before it is handed out to the user. //// // There are ways how to create an unitialized objects through remoting, etc. Avoid AVing in the EE by throwing a nice //// // exception here. //// if(data.IsNull()) //// { //// throw new ArgumentException( Environment.GetResourceString( "Argument_InvalidHandle" ) ); //// } //// //// return new ModuleHandle( data ); //// } //// //// public System.Security.Cryptography.X509Certificates.X509Certificate GetSignerCertificate() //// { //// byte[] data = null; //// //// GetSignerCertificate( GetNativeHandle(), JitHelpers.GetObjectHandleOnStack( ref data ) ); //// //// return (data != null) ? new System.Security.Cryptography.X509Certificates.X509Certificate( data ) : null; //// } #endregion } } ================================================ FILE: Zelig/Zelig/RunTime/Framework/mscorlib/System/Reflection/ParameterAttributes.cs ================================================ // ==++== // // Copyright (c) Microsoft Corporation. All rights reserved. // // ==--== //////////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////////// // // ParameterAttributes is an enum defining the attributes that may be // associated with a Parameter. These are defined in CorHdr.h. // // Author: darylo // Date: Aug 99 // namespace System.Reflection { using System; // This Enum matchs the CorParamAttr defined in CorHdr.h [Flags] [Serializable] public enum ParameterAttributes { None = 0x0000, // no flag is specified In = 0x0001, // Param is [In] Out = 0x0002, // Param is [Out] Lcid = 0x0004, // Param is [lcid] Retval = 0x0008, // Param is [Retval] Optional = 0x0010, // Param is optional // Reserved flags for Runtime use only. ReservedMask = 0xf000, HasDefault = 0x1000, // Param has default value. HasFieldMarshal = 0x2000, // Param has FieldMarshal. Reserved3 = 0x4000, // reserved bit Reserved4 = 0x8000, // reserved bit } } ================================================ FILE: Zelig/Zelig/RunTime/Framework/mscorlib/System/Reflection/ParameterInfo.cs ================================================ // ==++== // // Copyright (c) Microsoft Corporation. All rights reserved. // // ==--== namespace System.Reflection { using System; using System.Reflection; ////using System.Reflection.Cache; ////using System.Reflection.Emit; using System.Globalization; using System.Threading; using System.Diagnostics; ////using System.Security.Permissions; ////using System.Collections; ////using System.Security; ////using System.Text; using System.Runtime.ConstrainedExecution; using System.Runtime.CompilerServices; ////using System.Runtime.InteropServices; ////using System.Runtime.Serialization; ////using System.Runtime.Versioning; ////using RuntimeTypeCache = System.RuntimeType.RuntimeTypeCache; ////using CorElementType = System.Reflection.CorElementType; ////using MdToken = System.Reflection.MetadataToken; [Serializable] public unsafe class ParameterInfo /*: ICustomAttributeProvider*/ { #region Static Members //// internal unsafe static ParameterInfo[] GetParameters( MethodBase method, MemberInfo member, Signature sig ) //// { //// ParameterInfo dummy; //// //// return GetParameters( method, member, sig, out dummy, false ); //// } //// //// internal unsafe static ParameterInfo GetReturnParameter( MethodBase method, MemberInfo member, Signature sig ) //// { //// ParameterInfo returnParameter; //// //// GetParameters( method, member, sig, out returnParameter, true ); //// //// return returnParameter; //// } //// //// internal unsafe static ParameterInfo[] GetParameters( MethodBase method , //// MemberInfo member , //// Signature sig , //// out ParameterInfo returnParameter , //// bool fetchReturnParameter ) //// { //// returnParameter = null; //// //// RuntimeMethodHandle methodHandle = method.GetMethodHandle(); //// int sigArgCount = sig.Arguments.Length; //// ParameterInfo[] args = fetchReturnParameter ? null : new ParameterInfo[sigArgCount]; //// //// int tkMethodDef = methodHandle.GetMethodDef(); //// int cParamDefs = 0; //// //// // Not all methods have tokens. Arrays, pointers and byRef types do not have tokens as they //// // are generated on the fly by the runtime. //// if(!MdToken.IsNullToken( tkMethodDef )) //// { //// MetadataImport scope = methodHandle.GetDeclaringType().GetModuleHandle().GetMetadataImport(); //// //// cParamDefs = scope.EnumParamsCount( tkMethodDef ); //// //// int* tkParamDefs = stackalloc int[cParamDefs]; //// //// scope.EnumParams( tkMethodDef, tkParamDefs, cParamDefs ); //// //// // Not all parameters have tokens. Parameters may have no token //// // if they have no name and no attributes. //// ASSERT.CONSISTENCY_CHECK( cParamDefs <= sigArgCount + 1 /* return type */); //// //// //// for(uint i = 0; i < cParamDefs; i++) //// { //// #region Populate ParameterInfos //// ParameterAttributes attr; //// int position; //// int tkParamDef = tkParamDefs[i]; //// //// scope.GetParamDefProps( tkParamDef, out position, out attr ); //// //// position--; //// //// if(fetchReturnParameter == true && position == -1) //// { //// ASSERT.CONSISTENCY_CHECK( returnParameter == null ); //// returnParameter = new ParameterInfo( sig, scope, tkParamDef, position, attr, member ); //// } //// else if(fetchReturnParameter == false && position >= 0) //// { //// ASSERT.CONSISTENCY_CHECK( position < sigArgCount ); //// args[position] = new ParameterInfo( sig, scope, tkParamDef, position, attr, member ); //// } //// #endregion //// } //// } //// //// // Fill in empty ParameterInfos for those without tokens //// if(fetchReturnParameter) //// { //// if(returnParameter == null) //// { //// returnParameter = new ParameterInfo( sig, MetadataImport.EmptyImport, 0, -1, (ParameterAttributes)0, member ); //// } //// } //// else //// { //// if(cParamDefs < args.Length + 1) //// { //// for(int i = 0; i < args.Length; i++) //// { //// if(args[i] != null) //// { //// continue; //// } //// //// args[i] = new ParameterInfo( sig, MetadataImport.EmptyImport, 0, i, (ParameterAttributes)0, member ); //// } //// } //// } //// //// return args; //// } #endregion #region Private Statics //// private static readonly Type s_DecimalConstantAttributeType = typeof( DecimalConstantAttribute ); //// private static readonly Type s_CustomConstantAttributeType = typeof( CustomConstantAttribute ); //// private static Type ParameterInfoType = typeof( System.Reflection.ParameterInfo ); #endregion #region Definitions //// [Flags] //// private enum WhatIsCached //// { //// Nothing = 0x0, //// Name = 0x1, //// ParameterType = 0x2, //// DefaultValue = 0x4, //// All = Name | ParameterType | DefaultValue //// } #endregion #region Legacy Protected Members //// protected String NameImpl; //// protected Type ClassImpl; //// protected int PositionImpl; //// protected ParameterAttributes AttrsImpl; //// protected Object DefaultValueImpl; // cannot cache this as it may be non agile user defined enum //// protected MemberInfo MemberImpl; #endregion #region Legacy Private Members // These are here only for backwards compatibility -- they are not set // until this instance is serialized, so don't rely on their values from // arbitrary code. #pragma warning disable 414 //// private IntPtr _importer; //// private int _token; //// private bool bExtraConstChecked; #pragma warning restore 414 #endregion #region Private Data Members //// // These are new in Whidbey, so we cannot serialize them directly or we break backwards compatibility. //// [NonSerialized] //// private int m_tkParamDef; //// [NonSerialized] //// private MetadataImport m_scope; //// [NonSerialized] //// private Signature m_signature; //// [NonSerialized] //// private volatile bool m_nameIsCached = false; //// [NonSerialized] //// private readonly bool m_noDefaultValue = false; #endregion #region VTS magic to serialize/deserialized to/from pre-Whidbey endpoints. //// [OnSerializing] //// private void OnSerializing( StreamingContext context ) //// { //// // We could be serializing for consumption by a pre-Whidbey //// // endpoint. Therefore we set up all the serialized fields to look //// // just like a v1.0/v1.1 instance. //// //// // First force all the protected fields (*Impl) which are computed //// // to be set if they aren't already. //// Object dummy; //// dummy = ParameterType; //// dummy = Name; //// DefaultValueImpl = DefaultValue; //// //// // Now set the legacy fields that the current implementation doesn't //// // use any more. Note that _importer is a raw pointer that should //// // never have been serialized in V1. We set it to zero here; if the //// // deserializer uses it (by calling GetCustomAttributes() on this //// // instance) they'll AV, but at least it will be a well defined //// // exception and not a random AV. //// _importer = IntPtr.Zero; //// _token = m_tkParamDef; //// bExtraConstChecked = false; //// } //// //// [OnDeserialized] //// private void OnDeserialized( StreamingContext context ) //// { //// // Once all the serializable fields have come in we can setup this //// // instance based on just two of them (MemberImpl and PositionImpl). //// // Use these members to lookup a template ParameterInfo then clone //// // that instance into this one. //// //// ParameterInfo targetInfo = null; //// //// if(MemberImpl == null) //// { //// throw new SerializationException( Environment.GetResourceString( ResId.Serialization_InsufficientState ) ); //// } //// //// ParameterInfo[] args = null; //// //// switch(MemberImpl.MemberType) //// { //// case MemberTypes.Constructor: //// case MemberTypes.Method: //// if(PositionImpl == -1) //// { //// if(MemberImpl.MemberType == MemberTypes.Method) //// { //// targetInfo = ((MethodInfo)MemberImpl).ReturnParameter; //// } //// else //// { //// throw new SerializationException( Environment.GetResourceString( ResId.Serialization_BadParameterInfo ) ); //// } //// } //// else //// { //// args = ((MethodBase)MemberImpl).GetParametersNoCopy(); //// //// if(args != null && PositionImpl < args.Length) //// { //// targetInfo = args[PositionImpl]; //// } //// else //// { //// throw new SerializationException( Environment.GetResourceString( ResId.Serialization_BadParameterInfo ) ); //// } //// } //// break; //// //// case MemberTypes.Property: //// args = ((PropertyInfo)MemberImpl).GetIndexParameters(); //// //// if(args != null && PositionImpl > -1 && PositionImpl < args.Length) //// { //// targetInfo = args[PositionImpl]; //// } //// else //// { //// throw new SerializationException( Environment.GetResourceString( ResId.Serialization_BadParameterInfo ) ); //// } //// break; //// //// default: //// throw new SerializationException( Environment.GetResourceString( ResId.Serialization_NoParameterInfo ) ); //// } //// //// // We've got a ParameterInfo that matches the incoming information, //// // clone it into ourselves. We really only need to copy the private //// // members we didn't receive via serialization. //// ASSERT.PRECONDITION( targetInfo != null ); //// //// m_tkParamDef = targetInfo.m_tkParamDef; //// m_scope = targetInfo.m_scope; //// m_signature = targetInfo.m_signature; //// m_nameIsCached = true; //// } #endregion #region Constructor //// protected ParameterInfo() //// { //// m_nameIsCached = true; //// m_noDefaultValue = true; //// } //// //// internal ParameterInfo( ParameterInfo accessor, RuntimePropertyInfo property ) : this( accessor, (MemberInfo)property ) //// { //// m_signature = property.Signature; //// } //// //// internal ParameterInfo( ParameterInfo accessor, MethodBuilderInstantiation method ) : this( accessor, (MemberInfo)method ) //// { //// m_signature = accessor.m_signature; //// //// if(ClassImpl.IsGenericParameter) //// { //// ClassImpl = method.GetGenericArguments()[ClassImpl.GenericParameterPosition]; //// } //// } //// //// private ParameterInfo( ParameterInfo accessor, MemberInfo member ) //// { //// // Change ownership //// MemberImpl = member; //// //// // Populate all the caches -- we inherit this behavior from RTM //// NameImpl = accessor.Name; //// m_nameIsCached = true; //// ClassImpl = accessor.ParameterType; //// PositionImpl = accessor.Position; //// AttrsImpl = accessor.Attributes; //// //// // Strictly speeking, property's don't contain paramter tokens //// // However we need this to make ca's work... oh well... //// m_tkParamDef = MdToken.IsNullToken( accessor.MetadataToken ) ? (int)MetadataTokenType.ParamDef : accessor.MetadataToken; //// m_scope = accessor.m_scope; //// } //// //// private ParameterInfo( Signature signature , //// MetadataImport scope , //// int tkParamDef, //// int position , //// ParameterAttributes attributes, //// MemberInfo member ) //// { //// ASSERT.PRECONDITION( member != null ); //// ASSERT.PRECONDITION( LOGIC.BIJECTION( MdToken.IsNullToken( tkParamDef ), scope.Equals( null ) ) ); //// ASSERT.PRECONDITION( LOGIC.IMPLIES( !MdToken.IsNullToken( tkParamDef ), MdToken.IsTokenOfType( tkParamDef, MetadataTokenType.ParamDef ) ) ); //// //// PositionImpl = position; //// MemberImpl = member; //// m_signature = signature; //// m_tkParamDef = MdToken.IsNullToken( tkParamDef ) ? (int)MetadataTokenType.ParamDef : tkParamDef; //// m_scope = scope; //// AttrsImpl = attributes; //// //// ClassImpl = null; //// NameImpl = null; //// } //// //// // ctor for no metadata MethodInfo //// internal ParameterInfo( MethodInfo owner, String name, RuntimeType parameterType, int position ) //// { //// MemberImpl = owner; //// NameImpl = name; //// m_nameIsCached = true; //// m_noDefaultValue = true; //// ClassImpl = parameterType; //// PositionImpl = position; //// AttrsImpl = ParameterAttributes.None; //// m_tkParamDef = (int)MetadataTokenType.ParamDef; //// m_scope = MetadataImport.EmptyImport; //// } #endregion #region Private Members //// private bool IsLegacyParameterInfo //// { //// get //// { //// return GetType() != typeof( ParameterInfo ); //// } //// } #endregion #region Internal Members //// // this is an internal api for DynamicMethod. A better solution is to change the relationship //// // between ParameterInfo and ParameterBuilder so that a ParameterBuilder can be seen as a writer //// // api over a ParameterInfo. However that is a possible breaking change so it needs to go through some process first //// internal void SetName( String name ) //// { //// NameImpl = name; //// } //// //// internal void SetAttributes( ParameterAttributes attributes ) //// { //// AttrsImpl = attributes; //// } #endregion #region Public Methods public extern virtual Type ParameterType { [MethodImpl( MethodImplOptions.InternalCall )] get; //// { //// // only instance of ParameterInfo has ClassImpl, all its subclasses don't //// if(ClassImpl == null && this.GetType() == typeof( ParameterInfo )) //// { //// RuntimeTypeHandle parameterTypeHandle; //// if(PositionImpl == -1) //// { //// parameterTypeHandle = m_signature.ReturnTypeHandle; //// } //// else //// { //// parameterTypeHandle = m_signature.Arguments[PositionImpl]; //// } //// //// ASSERT.CONSISTENCY_CHECK( !parameterTypeHandle.IsNullHandle() ); //// // different thread could only write ClassImpl to the same value, so race is not a problem here //// ClassImpl = parameterTypeHandle.GetRuntimeType(); //// } //// //// BCLDebug.Assert( ClassImpl != null || this.GetType() != typeof( ParameterInfo ), "ClassImple should already be initialized for ParameterInfo class" ); //// //// return ClassImpl; //// } } public virtual String Name { get { //////if(!m_nameIsCached) //////{ ////// if(!MdToken.IsNullToken( m_tkParamDef )) ////// { ////// string name = m_scope.GetName( m_tkParamDef ).ToString(); ////// NameImpl = name; ////// } ////// // other threads could only write it to true, so race is OK ////// // this field is volatile, so the write ordering is guaranteed ////// m_nameIsCached = true; //////} //////// name may be null //////return NameImpl; return String.Empty; } } //// public virtual Object DefaultValue //// { //// get //// { //// return GetDefaultValue( false ); //// } //// } //// //// public virtual Object RawDefaultValue //// { //// get //// { //// return GetDefaultValue( true ); //// } //// } //// //// internal Object GetDefaultValue( bool raw ) //// { //// // Cannot cache because default value could be non-agile user defined enumeration. //// object defaultValue = null; //// //// // for dynamic method we pretend to have cached the value so we do not go to metadata //// if(!m_noDefaultValue) //// { //// if(ParameterType == typeof( DateTime )) //// { //// if(raw) //// { //// CustomAttributeTypedArgument value = CustomAttributeData.Filter( CustomAttributeData.GetCustomAttributes( this ), typeof( DateTimeConstantAttribute ), 0 ); //// //// if(value.ArgumentType != null) //// { //// return new DateTime( (long)value.Value ); //// } //// } //// else //// { //// object[] dt = GetCustomAttributes( typeof( DateTimeConstantAttribute ), false ); //// //// if(dt != null && dt.Length != 0) //// { //// return ((DateTimeConstantAttribute)dt[0]).Value; //// } //// } //// } //// //// #region Look for a default value in metadata //// if(!MdToken.IsNullToken( m_tkParamDef )) //// { //// defaultValue = MdConstant.GetValue( m_scope, m_tkParamDef, ParameterType.GetTypeHandleInternal(), raw ); //// } //// #endregion //// //// if(defaultValue == DBNull.Value) //// { //// #region Look for a default value in the custom attributes //// if(raw) //// { //// System.Collections.Generic.IList attrs = CustomAttributeData.GetCustomAttributes( this ); //// CustomAttributeTypedArgument value = CustomAttributeData.Filter( attrs, s_CustomConstantAttributeType, "Value" ); //// //// if(value.ArgumentType == null) //// { //// value = CustomAttributeData.Filter( attrs, s_DecimalConstantAttributeType, "Value" ); //// //// //// if(value.ArgumentType == null) //// { //// for(int i = 0; i < attrs.Count; i++) //// { //// if(attrs[i].Constructor.DeclaringType == s_DecimalConstantAttributeType) //// { //// ParameterInfo[] parameters = attrs[i].Constructor.GetParameters(); //// //// if(parameters.Length != 0) //// { //// if(parameters[2].ParameterType == typeof( uint )) //// { //// System.Collections.Generic.IList args = attrs[i].ConstructorArguments; //// //// int low = (int)(UInt32)args[4].Value; //// int mid = (int)(UInt32)args[3].Value; //// int hi = (int)(UInt32)args[2].Value; //// byte sign = (byte)args[1].Value; //// byte scale = (byte)args[0].Value; //// //// value = new CustomAttributeTypedArgument( new System.Decimal( low, mid, hi, (sign != 0), scale ) ); //// } //// else //// { //// System.Collections.Generic.IList args = attrs[i].ConstructorArguments; //// //// int low = (int)args[4].Value; //// int mid = (int)args[3].Value; //// int hi = (int)args[2].Value; //// byte sign = (byte)args[1].Value; //// byte scale = (byte)args[0].Value; //// //// value = new CustomAttributeTypedArgument( new System.Decimal( low, mid, hi, (sign != 0), scale ) ); //// } //// } //// } //// } //// } //// } //// //// if(value.ArgumentType != null) //// { //// defaultValue = value.Value; //// } //// } //// else //// { //// Object[] CustomAttrs = GetCustomAttributes( s_CustomConstantAttributeType, false ); //// if(CustomAttrs.Length != 0) //// { //// defaultValue = ((CustomConstantAttribute)CustomAttrs[0]).Value; //// } //// else //// { //// CustomAttrs = GetCustomAttributes( s_DecimalConstantAttributeType, false ); //// if(CustomAttrs.Length != 0) //// { //// defaultValue = ((DecimalConstantAttribute)CustomAttrs[0]).Value; //// } //// } //// } //// #endregion //// } //// //// if(defaultValue == DBNull.Value) //// { //// #region Handle case if no default value was found //// if(IsOptional) //// { //// // If the argument is marked as optional then the default value is Missing.Value. //// defaultValue = Type.Missing; //// } //// #endregion //// } //// } //// //// return defaultValue; //// } //// //// public virtual int Position //// { //// get //// { //// return PositionImpl; //// } //// } //// //// public virtual ParameterAttributes Attributes //// { //// get //// { //// return AttrsImpl; //// } //// } //// //// public virtual MemberInfo Member //// { //// get //// { //// return MemberImpl; //// } //// } //// //// public bool IsIn //// { //// get //// { //// return ((Attributes & ParameterAttributes.In) != 0); //// } //// } //// //// public bool IsOut //// { //// get //// { //// return ((Attributes & ParameterAttributes.Out) != 0); //// } //// } //// //// public bool IsLcid //// { //// get //// { //// return ((Attributes & ParameterAttributes.Lcid) != 0); //// } //// } //// //// public bool IsRetval //// { //// get //// { //// return ((Attributes & ParameterAttributes.Retval) != 0); //// } //// } //// //// public bool IsOptional //// { //// get //// { //// return ((Attributes & ParameterAttributes.Optional) != 0); //// } //// } //// //// public int MetadataToken //// { //// get //// { //// return m_tkParamDef; //// } //// } //// //// public virtual Type[] GetRequiredCustomModifiers() //// { //// if(IsLegacyParameterInfo) //// { //// return new Type[0]; //// } //// //// return m_signature.GetCustomModifiers( PositionImpl + 1, true ); //// } //// //// public virtual Type[] GetOptionalCustomModifiers() //// { //// if(IsLegacyParameterInfo) //// { //// return new Type[0]; //// } //// //// return m_signature.GetCustomModifiers( PositionImpl + 1, false ); //// } //// #endregion #region Object Overrides //// public override String ToString() //// { //// return ParameterType.SigToString() + " " + Name; //// } #endregion #region ICustomAttributeProvider //// public virtual Object[] GetCustomAttributes( bool inherit ) //// { //// if(IsLegacyParameterInfo) //// { //// return null; //// } //// //// if(MdToken.IsNullToken( m_tkParamDef )) //// { //// return new object[0]; //// } //// //// return CustomAttribute.GetCustomAttributes( this, typeof( object ) as RuntimeType ); //// } //// //// public virtual Object[] GetCustomAttributes( Type attributeType, bool inherit ) //// { //// if(IsLegacyParameterInfo) //// { //// return null; //// } //// //// if(attributeType == null) //// { //// throw new ArgumentNullException( "attributeType" ); //// } //// //// if(MdToken.IsNullToken( m_tkParamDef )) //// { //// return new object[0]; //// } //// //// RuntimeType attributeRuntimeType = attributeType.UnderlyingSystemType as RuntimeType; //// //// if(attributeRuntimeType == null) //// { //// throw new ArgumentException( Environment.GetResourceString( "Arg_MustBeType" ), "attributeType" ); //// } //// //// return CustomAttribute.GetCustomAttributes( this, attributeRuntimeType ); //// } //// //// public virtual bool IsDefined( Type attributeType, bool inherit ) //// { //// if(IsLegacyParameterInfo) //// { //// return false; //// } //// //// if(attributeType == null) //// { //// throw new ArgumentNullException( "attributeType" ); //// } //// //// if(MdToken.IsNullToken( m_tkParamDef )) //// { //// return false; //// } //// //// RuntimeType attributeRuntimeType = attributeType.UnderlyingSystemType as RuntimeType; //// //// if(attributeRuntimeType == null) //// { //// throw new ArgumentException( Environment.GetResourceString( "Arg_MustBeType" ), "attributeType" ); //// } //// //// return CustomAttribute.IsDefined( this, attributeRuntimeType ); //// } #endregion #region Remoting Cache //// private InternalCache m_cachedData; //// //// internal InternalCache Cache //// { //// get //// { //// // This grabs an internal copy of m_cachedData and uses //// // that instead of looking at m_cachedData directly because //// // the cache may get cleared asynchronously. This prevents //// // us from having to take a lock. //// InternalCache cache = m_cachedData; //// if(cache == null) //// { //// cache = new InternalCache( "ParameterInfo" ); //// InternalCache ret = Interlocked.CompareExchange( ref m_cachedData, cache, null ); //// if(ret != null) //// { //// cache = ret; //// } //// //// GC.ClearCache += new ClearCacheHandler( OnCacheClear ); //// } //// //// return cache; //// } //// } //// //// internal void OnCacheClear( Object sender, ClearCacheEventArgs cacheEventArgs ) //// { //// m_cachedData = null; //// } #endregion } } ================================================ FILE: Zelig/Zelig/RunTime/Framework/mscorlib/System/Reflection/ParameterModifier.cs ================================================ // ==++== // // Copyright (c) Microsoft Corporation. All rights reserved. // // ==--== namespace System.Reflection { using System; [Serializable] public struct ParameterModifier { #region Private Data Members private bool[] m_byRef; #endregion #region Constructor public ParameterModifier( int parameterCount ) { if(parameterCount <= 0) { #if EXCEPTION_STRINGS throw new ArgumentException( Environment.GetResourceString( "Arg_ParmArraySize" ) ); #else throw new ArgumentException(); #endif } m_byRef = new bool[parameterCount]; } #endregion #region Internal Members internal bool[] IsByRefArray { get { return m_byRef; } } #endregion #region Public Members public bool this[int index] { get { return m_byRef[index]; } set { m_byRef[index] = value; } } #endregion } } ================================================ FILE: Zelig/Zelig/RunTime/Framework/mscorlib/System/Reflection/PropertyInfo.cs ================================================ // ==++== // // Copyright (c) Microsoft Corporation. All rights reserved. // // ==--== namespace System.Reflection { using System; using System.Reflection; ////using System.Reflection.Cache; ////using System.Reflection.Emit; using System.Globalization; using System.Threading; ////using System.Diagnostics; ////using System.Security.Permissions; ////using System.Collections; ////using System.Security; ////using System.Text; using System.Runtime.ConstrainedExecution; ////using System.Runtime.CompilerServices; ////using System.Runtime.InteropServices; ////using System.Runtime.Serialization; ////using System.Runtime.Versioning; ////using RuntimeTypeCache = System.RuntimeType.RuntimeTypeCache; ////using CorElementType = System.Reflection.CorElementType; ////using MdToken = System.Reflection.MetadataToken; [Serializable] ////[PermissionSetAttribute( SecurityAction.InheritanceDemand, Name = "FullTrust" )] public abstract class PropertyInfo : MemberInfo { #region Constructor //// protected PropertyInfo() //// { //// } #endregion #region MemberInfo Overrides public override MemberTypes MemberType { get { return System.Reflection.MemberTypes.Property; } } #endregion #region Public Abstract\Virtual Members //// public virtual object GetConstantValue() //// { //// throw new NotImplementedException(); //// } //// //// public virtual object GetRawConstantValue() //// { //// throw new NotImplementedException(); //// } //// //// public abstract Type PropertyType //// { //// get; //// } //// //// public abstract void SetValue( Object obj, Object value, BindingFlags invokeAttr, Binder binder, Object[] index, CultureInfo culture ); //// //// public abstract MethodInfo[] GetAccessors( bool nonPublic ); //// //// public abstract MethodInfo GetGetMethod( bool nonPublic ); //// //// public abstract MethodInfo GetSetMethod( bool nonPublic ); //// //// public abstract ParameterInfo[] GetIndexParameters(); //// //// public abstract PropertyAttributes Attributes //// { //// get; //// } //// //// public abstract bool CanRead //// { //// get; //// } //// //// public abstract bool CanWrite //// { //// get; //// } //// //// [DebuggerStepThroughAttribute] //// [Diagnostics.DebuggerHidden] //// public virtual Object GetValue( Object obj, Object[] index ) //// { //// return GetValue( obj, BindingFlags.Default, null, index, null ); //// } //// //// public abstract Object GetValue( Object obj, BindingFlags invokeAttr, Binder binder, Object[] index, CultureInfo culture ); //// //// [DebuggerStepThroughAttribute] //// [Diagnostics.DebuggerHidden] //// public virtual void SetValue( Object obj, Object value, Object[] index ) //// { //// SetValue( obj, value, BindingFlags.Default, null, index, null ); //// } #endregion #region Public Members //// public virtual Type[] GetRequiredCustomModifiers() //// { //// return new Type[0]; //// } //// //// public virtual Type[] GetOptionalCustomModifiers() //// { //// return new Type[0]; //// } //// //// public MethodInfo[] GetAccessors() //// { //// return GetAccessors( false ); //// } //// //// public MethodInfo GetGetMethod() //// { //// return GetGetMethod( false ); //// } //// //// public MethodInfo GetSetMethod() //// { //// return GetSetMethod( false ); //// } //// //// public bool IsSpecialName //// { //// get //// { //// return (Attributes & PropertyAttributes.SpecialName) != 0; //// } //// } #endregion } } ================================================ FILE: Zelig/Zelig/RunTime/Framework/mscorlib/System/Reflection/RuntimeConstructorInfo.cs ================================================ // ==++== // // Copyright (c) Microsoft Corporation. All rights reserved. // // ==--== namespace System.Reflection { using System; using System.Reflection; ////using System.Reflection.Cache; ////using System.Reflection.Emit; using System.Globalization; ////using System.Threading; ////using System.Diagnostics; ////using System.Security.Permissions; ////using System.Collections; ////using System.Security; ////using System.Text; using System.Runtime.ConstrainedExecution; using System.Runtime.CompilerServices; ////using System.Runtime.InteropServices; ////using System.Runtime.Serialization; ////using System.Runtime.Versioning; ////using RuntimeTypeCache = System.RuntimeType.RuntimeTypeCache; ////using CorElementType = System.Reflection.CorElementType; ////using MdToken = System.Reflection.MetadataToken; [Serializable] internal sealed class RuntimeConstructorInfo : ConstructorInfo /*, ISerializable*/ { #region Private Data Members #pragma warning disable 169 // The private field 'class member' is never used private RuntimeMethodHandle m_handle; #pragma warning restore 169 //// private RuntimeTypeCache m_reflectedTypeCache; //// private RuntimeType m_declaringType; //// private string m_toString; //// private MethodAttributes m_methodAttributes; //// private BindingFlags m_bindingFlags; //// private ParameterInfo[] m_parameters = null; // Created lazily when GetParameters() is called. //// private uint m_invocationFlags; //// private Signature m_signature; #endregion #region Constructor //// internal RuntimeConstructorInfo() //// { //// // Used for dummy head node during population //// } //// //// internal RuntimeConstructorInfo( RuntimeMethodHandle handle , //// RuntimeTypeHandle declaringTypeHandle , //// RuntimeTypeCache reflectedTypeCache , //// MethodAttributes methodAttributes , //// BindingFlags bindingFlags ) //// { //// ASSERT.POSTCONDITION( methodAttributes == handle.GetAttributes() ); //// //// m_bindingFlags = bindingFlags; //// m_handle = handle; //// m_reflectedTypeCache = reflectedTypeCache; //// m_declaringType = declaringTypeHandle.GetRuntimeType(); //// m_parameters = null; // Created lazily when GetParameters() is called. //// m_toString = null; //// m_methodAttributes = methodAttributes; //// } #endregion #region NonPublic Methods //// [ReliabilityContract( Consistency.WillNotCorruptState, Cer.Success )] //// internal override bool CacheEquals( object o ) //// { //// RuntimeConstructorInfo m = o as RuntimeConstructorInfo; //// //// if(m == null) //// { //// return false; //// } //// //// return m.m_handle.Equals( m_handle ); //// } //// //// private Signature Signature //// { //// get //// { //// if(m_signature == null) //// { //// m_signature = new Signature( m_handle, m_declaringType.GetTypeHandleInternal() ); //// } //// //// return m_signature; //// } //// } //// //// private RuntimeTypeHandle ReflectedTypeHandle //// { //// get //// { //// return m_reflectedTypeCache.RuntimeTypeHandle; //// } //// } //// //// private void CheckConsistency( Object target ) //// { //// if(target == null && IsStatic) //// { //// return; //// } //// //// if(!m_declaringType.IsInstanceOfType( target )) //// { //// if(target == null) //// { //// throw new TargetException( Environment.GetResourceString( "RFLCT.Targ_StatMethReqTarg" ) ); //// } //// //// throw new TargetException( Environment.GetResourceString( "RFLCT.Targ_ITargMismatch" ) ); //// } //// } //// //// internal BindingFlags BindingFlags //// { //// get //// { //// return m_bindingFlags; //// } //// } //// //// internal override RuntimeMethodHandle GetMethodHandle() //// { //// return m_handle; //// } //// //// internal override bool IsOverloaded //// { //// get //// { //// return m_reflectedTypeCache.GetConstructorList( MemberListType.CaseSensitive, Name ).Count > 1; //// } //// } //// //// internal override uint GetOneTimeSpecificFlags() //// { //// uint invocationFlags = INVOCATION_FLAGS_IS_CTOR; // this is a given //// //// if( //// (DeclaringType != null && DeclaringType.IsAbstract) || //// (IsStatic) //// ) //// { //// invocationFlags |= INVOCATION_FLAGS_NO_CTOR_INVOKE; //// } //// else if(DeclaringType == typeof( void )) //// { //// invocationFlags |= INVOCATION_FLAGS_NO_INVOKE; //// } //// // Check for attempt to create a delegate class, we demand unmanaged //// // code permission for this since it's hard to validate the target address. //// else if(typeof( Delegate ).IsAssignableFrom( DeclaringType )) //// { //// invocationFlags |= INVOCATION_FLAGS_IS_DELEGATE_CTOR; //// } //// //// return invocationFlags; //// } #endregion #region Object Overrides //// public override String ToString() //// { //// if(m_toString == null) //// { //// m_toString = "Void " + RuntimeMethodInfo.ConstructName( this ); //// } //// //// return m_toString; //// } #endregion #region ICustomAttributeProvider public override Object[] GetCustomAttributes( bool inherit ) { throw new NotImplementedException(); //// return CustomAttribute.GetCustomAttributes( this, typeof( object ) as RuntimeType ); } public override Object[] GetCustomAttributes( Type attributeType, bool inherit ) { throw new NotImplementedException(); //// if(attributeType == null) //// { //// throw new ArgumentNullException( "attributeType" ); //// } //// //// RuntimeType attributeRuntimeType = attributeType.UnderlyingSystemType as RuntimeType; //// //// if(attributeRuntimeType == null) //// { //// throw new ArgumentException( Environment.GetResourceString( "Arg_MustBeType" ), "attributeType" ); //// } //// //// return CustomAttribute.GetCustomAttributes( this, attributeRuntimeType ); } public override bool IsDefined( Type attributeType, bool inherit ) { throw new NotImplementedException(); //// if(attributeType == null) //// { //// throw new ArgumentNullException( "attributeType" ); //// } //// //// RuntimeType attributeRuntimeType = attributeType.UnderlyingSystemType as RuntimeType; //// //// if(attributeRuntimeType == null) //// { //// throw new ArgumentException( Environment.GetResourceString( "Arg_MustBeType" ), "attributeType" ); //// } //// //// return CustomAttribute.IsDefined( this, attributeRuntimeType ); } #endregion #region MemberInfo Overrides public override String Name { //// [MethodImpl( MethodImplOptions.InternalCall )] get { throw new NotImplementedException(); //// return m_handle.GetName(); } } //// public override MemberTypes MemberType //// { //// get //// { //// return MemberTypes.Constructor; //// } //// } public override Type DeclaringType { get { throw new NotImplementedException(); //// return m_reflectedTypeCache.IsGlobal ? null : m_declaringType; } } //// public override Type ReflectedType //// { //// get //// { //// return m_reflectedTypeCache.IsGlobal ? null : m_reflectedTypeCache.RuntimeType; //// } //// } //// //// public override int MetadataToken //// { //// get //// { //// return m_handle.GetMethodDef(); //// } //// } //// //// public override Module Module //// { //// get //// { //// return m_declaringType.GetTypeHandleInternal().GetModuleHandle().GetModule(); //// } //// } #endregion #region MethodBase Overrides //// internal override Type GetReturnType() //// { //// return Signature.ReturnTypeHandle.GetRuntimeType(); //// } //// //// internal override ParameterInfo[] GetParametersNoCopy() //// { //// if(m_parameters == null) //// { //// m_parameters = ParameterInfo.GetParameters( this, this, Signature ); //// } //// //// return m_parameters; //// } [MethodImpl( MethodImplOptions.InternalCall )] public extern override ParameterInfo[] GetParameters(); //// { //// ParameterInfo[] parameters = GetParametersNoCopy(); //// //// if(parameters.Length == 0) //// { //// return parameters; //// } //// //// ParameterInfo[] ret = new ParameterInfo[parameters.Length]; //// //// Array.Copy( parameters, ret, parameters.Length ); //// //// return ret; //// } //// //// public override MethodImplAttributes GetMethodImplementationFlags() //// { //// return m_handle.GetImplAttributes(); //// } //// //// public override RuntimeMethodHandle MethodHandle //// { //// get //// { //// Type declaringType = DeclaringType; //// if((declaringType == null && Module.Assembly.ReflectionOnly) || declaringType is ReflectionOnlyType) //// { //// throw new InvalidOperationException( Environment.GetResourceString( "InvalidOperation_NotAllowedInReflectionOnly" ) ); //// } //// //// return m_handle; //// } //// } //// //// public override MethodAttributes Attributes //// { //// get //// { //// return m_methodAttributes; //// } //// } //// //// public override CallingConventions CallingConvention //// { //// get //// { //// return Signature.CallingConvention; //// } //// } //// //// internal static void CheckCanCreateInstance( Type declaringType, bool isVarArg ) //// { //// if(declaringType == null) //// { //// throw new ArgumentNullException( "declaringType" ); //// } //// //// // ctor is ReflectOnly //// if(declaringType is ReflectionOnlyType) //// { //// throw new InvalidOperationException( Environment.GetResourceString( "Arg_ReflectionOnlyInvoke" ) ); //// } //// // ctor is declared on interface class //// else if(declaringType.IsInterface) //// { //// throw new MemberAccessException( String.Format( CultureInfo.CurrentUICulture, Environment.GetResourceString( "Acc_CreateInterfaceEx" ), declaringType ) ); //// } //// // ctor is on an abstract class //// else if(declaringType.IsAbstract) //// { //// throw new MemberAccessException( String.Format( CultureInfo.CurrentUICulture, Environment.GetResourceString( "Acc_CreateAbstEx" ), declaringType ) ); //// } //// // ctor is on a class that contains stack pointers //// else if(declaringType.GetRootElementType() == typeof( ArgIterator )) //// { //// throw new NotSupportedException(); //// } //// // ctor is vararg //// else if(isVarArg) //// { //// throw new NotSupportedException(); //// } //// // ctor is generic or on a generic class //// else if(declaringType.ContainsGenericParameters) //// { //// throw new MemberAccessException( String.Format( CultureInfo.CurrentUICulture, Environment.GetResourceString( "Acc_CreateGenericEx" ), declaringType ) ); //// } //// // ctor is declared on System.Void //// else if(declaringType == typeof( void )) //// { //// throw new MemberAccessException( Environment.GetResourceString( "Access_Void" ) ); //// } //// } //// //// internal void ThrowNoInvokeException() //// { //// CheckCanCreateInstance( DeclaringType, (CallingConvention & CallingConventions.VarArgs) == CallingConventions.VarArgs ); //// //// // ctor is .cctor //// if((Attributes & MethodAttributes.Static) == MethodAttributes.Static) //// { //// throw new MemberAccessException( Environment.GetResourceString( "Acc_NotClassInit" ) ); //// } //// //// throw new TargetException(); //// } //// //// [DebuggerStepThroughAttribute] [Diagnostics.DebuggerHidden] [MethodImpl( MethodImplOptions.InternalCall )] public extern override Object Invoke( Object obj, BindingFlags invokeAttr, Binder binder, Object[] parameters, CultureInfo culture ); //// { //// // set one time info for invocation //// if(m_invocationFlags == INVOCATION_FLAGS_UNKNOWN) //// { //// m_invocationFlags = GetOneTimeFlags(); //// } //// //// if((m_invocationFlags & INVOCATION_FLAGS_NO_INVOKE) != 0) //// { //// ThrowNoInvokeException(); //// } //// //// // check basic method consistency. This call will throw if there are problems in the target/method relationship //// CheckConsistency( obj ); //// //// if(obj != null) //// { //// new SecurityPermission( SecurityPermissionFlag.SkipVerification ).Demand(); //// } //// //// if((m_invocationFlags & (INVOCATION_FLAGS_RISKY_METHOD | INVOCATION_FLAGS_NEED_SECURITY)) != 0) //// { //// if((m_invocationFlags & INVOCATION_FLAGS_RISKY_METHOD) != 0) //// { //// CodeAccessPermission.DemandInternal( PermissionType.ReflectionMemberAccess ); //// } //// if((m_invocationFlags & INVOCATION_FLAGS_NEED_SECURITY) != 0) //// { //// PerformSecurityCheck( obj, m_handle, m_declaringType.TypeHandle.Value, m_invocationFlags ); //// } //// } //// //// // get the signature //// int formalCount = Signature.Arguments.Length; //// int actualCount = (parameters != null) ? parameters.Length : 0; //// if(formalCount != actualCount) //// { //// throw new TargetParameterCountException( Environment.GetResourceString( "Arg_ParmCnt" ) ); //// } //// //// // if we are here we passed all the previous checks. Time to look at the arguments //// if(actualCount > 0) //// { //// Object[] arguments = CheckArguments( parameters, binder, invokeAttr, culture, Signature ); //// Object retValue = m_handle.InvokeMethodFast( obj, arguments, Signature, m_methodAttributes, (ReflectedType != null) ? ReflectedType.TypeHandle : RuntimeTypeHandle.EmptyHandle ); //// //// // copy out. This should be made only if ByRef are present. //// for(int index = 0; index < actualCount; index++) //// { //// parameters[index] = arguments[index]; //// } //// //// return retValue; //// } //// //// return m_handle.InvokeMethodFast( obj, null, Signature, m_methodAttributes, (DeclaringType != null) ? DeclaringType.TypeHandle : RuntimeTypeHandle.EmptyHandle ); //// } //// //// //// [ReflectionPermissionAttribute( SecurityAction.Demand, Flags = ReflectionPermissionFlag.MemberAccess )] //// public override MethodBody GetMethodBody() //// { //// MethodBody mb = m_handle.GetMethodBody( ReflectedTypeHandle ); //// if(mb != null) //// { //// mb.m_methodBase = this; //// } //// return mb; //// } #endregion #region ConstructorInfo Overrides //// [DebuggerStepThroughAttribute] //// [Diagnostics.DebuggerHidden] //// public override Object Invoke( BindingFlags invokeAttr, Binder binder, Object[] parameters, CultureInfo culture ) //// { //// // get the declaring TypeHandle early for consistent exceptions in IntrospectionOnly context //// RuntimeTypeHandle declaringTypeHandle = m_declaringType.TypeHandle; //// //// // set one time info for invocation //// if(m_invocationFlags == INVOCATION_FLAGS_UNKNOWN) //// { //// m_invocationFlags = GetOneTimeFlags(); //// } //// //// if((m_invocationFlags & (INVOCATION_FLAGS_NO_INVOKE | INVOCATION_FLAGS_CONTAINS_STACK_POINTERS | INVOCATION_FLAGS_NO_CTOR_INVOKE)) != 0) //// { //// ThrowNoInvokeException(); //// } //// //// if((m_invocationFlags & (INVOCATION_FLAGS_RISKY_METHOD | INVOCATION_FLAGS_NEED_SECURITY | INVOCATION_FLAGS_IS_DELEGATE_CTOR)) != 0) //// { //// if((m_invocationFlags & INVOCATION_FLAGS_RISKY_METHOD) != 0) //// { //// CodeAccessPermission.DemandInternal( PermissionType.ReflectionMemberAccess ); //// } //// if((m_invocationFlags & INVOCATION_FLAGS_NEED_SECURITY) != 0) //// { //// PerformSecurityCheck( null, m_handle, m_declaringType.TypeHandle.Value, m_invocationFlags & INVOCATION_FLAGS_CONSTRUCTOR_INVOKE ); //// } //// if((m_invocationFlags & INVOCATION_FLAGS_IS_DELEGATE_CTOR) != 0) //// { //// new SecurityPermission( SecurityPermissionFlag.UnmanagedCode ).Demand(); //// } //// } //// //// // get the signature //// int formalCount = Signature.Arguments.Length; //// int actualCount = (parameters != null) ? parameters.Length : 0; //// if(formalCount != actualCount) //// { //// throw new TargetParameterCountException( Environment.GetResourceString( "Arg_ParmCnt" ) ); //// } //// //// // make sure the class ctor has been run //// RuntimeHelpers.RunClassConstructor( declaringTypeHandle ); //// //// // if we are here we passed all the previous checks. Time to look at the arguments //// if(actualCount > 0) //// { //// Object[] arguments = CheckArguments( parameters, binder, invokeAttr, culture, Signature ); //// Object retValue = m_handle.InvokeConstructor( arguments, Signature, declaringTypeHandle ); //// //// // copy out. This should be made only if ByRef are present. //// for(int index = 0; index < actualCount; index++) //// { //// parameters[index] = arguments[index]; //// } //// //// return retValue; //// } //// //// return m_handle.InvokeConstructor( null, Signature, declaringTypeHandle ); //// } #endregion #region ISerializable Implementation //// public void GetObjectData( SerializationInfo info, StreamingContext context ) //// { //// if(info == null) //// { //// throw new ArgumentNullException( "info" ); //// } //// //// MemberInfoSerializationHolder.GetSerializationInfo( info, Name, ReflectedTypeHandle.GetRuntimeType(), ToString(), MemberTypes.Constructor ); //// } //// //// internal void SerializationInvoke( Object target, SerializationInfo info, StreamingContext context ) //// { //// MethodHandle.SerializationInvoke( target, Signature, info, context ); //// } #endregion } } ================================================ FILE: Zelig/Zelig/RunTime/Framework/mscorlib/System/Reflection/RuntimeEventInfo.cs ================================================ // ==++== // // Copyright (c) Microsoft Corporation. All rights reserved. // // ==--== namespace System.Reflection { using System; using System.Reflection; ////using System.Reflection.Cache; ////using System.Reflection.Emit; ////using System.Globalization; ////using System.Threading; ////using System.Diagnostics; ////using System.Security.Permissions; ////using System.Collections; ////using System.Security; ////using System.Text; using System.Runtime.ConstrainedExecution; ////using System.Runtime.CompilerServices; ////using System.Runtime.InteropServices; ////using System.Runtime.Serialization; ////using System.Runtime.Versioning; ////using RuntimeTypeCache = System.RuntimeType.RuntimeTypeCache; ////using CorElementType = System.Reflection.CorElementType; ////using MdToken = System.Reflection.MetadataToken; [Serializable] internal unsafe sealed class RuntimeEventInfo : EventInfo /*, ISerializable*/ { #region Private Data Members //// private int m_token; //// private EventAttributes m_flags; //// private string m_name; //// private void* m_utf8name; //// private RuntimeTypeCache m_reflectedTypeCache; //// private RuntimeMethodInfo m_addMethod; //// private RuntimeMethodInfo m_removeMethod; //// private RuntimeMethodInfo m_raiseMethod; //// private MethodInfo[] m_otherMethod; //// private RuntimeType m_declaringType; //// private BindingFlags m_bindingFlags; #endregion #region Constructor //// internal RuntimeEventInfo() //// { //// // Used for dummy head node during population //// } //// //// internal RuntimeEventInfo( int tkEvent, RuntimeType declaredType, RuntimeTypeCache reflectedTypeCache, out bool isPrivate ) //// { //// ASSERT.PRECONDITION( declaredType != null ); //// ASSERT.PRECONDITION( reflectedTypeCache != null ); //// ASSERT.PRECONDITION( !reflectedTypeCache.IsGlobal ); //// //// MetadataImport scope = declaredType.Module.MetadataImport; //// //// m_token = tkEvent; //// m_reflectedTypeCache = reflectedTypeCache; //// m_declaringType = declaredType; //// //// RuntimeTypeHandle declaredTypeHandle = declaredType.GetTypeHandleInternal(); //// RuntimeTypeHandle reflectedTypeHandle = reflectedTypeCache.RuntimeTypeHandle; //// RuntimeMethodInfo dummy; //// //// scope.GetEventProps( tkEvent, out m_utf8name, out m_flags ); //// //// int cAssociateRecord = scope.GetAssociatesCount( tkEvent ); //// //// AssociateRecord* associateRecord = stackalloc AssociateRecord[cAssociateRecord]; //// //// scope.GetAssociates( tkEvent, associateRecord, cAssociateRecord ); //// //// Associates.AssignAssociates( associateRecord, cAssociateRecord, declaredTypeHandle, reflectedTypeHandle, //// out m_addMethod, out m_removeMethod, out m_raiseMethod, //// out dummy, out dummy, out m_otherMethod, out isPrivate, out m_bindingFlags ); //// } #endregion #region Internal Members //// [ReliabilityContract( Consistency.WillNotCorruptState, Cer.Success )] //// internal override bool CacheEquals( object o ) //// { //// RuntimeEventInfo m = o as RuntimeEventInfo; //// //// if(m == null) //// { //// return false; //// } //// //// return m.m_token == m_token && m_declaringType.GetTypeHandleInternal().GetModuleHandle().Equals( m.m_declaringType.GetTypeHandleInternal().GetModuleHandle() ); //// } //// //// internal BindingFlags BindingFlags //// { //// get //// { //// return m_bindingFlags; //// } //// } #endregion #region Object Overrides //// public override String ToString() //// { //// if(m_addMethod == null || m_addMethod.GetParametersNoCopy().Length == 0) //// { //// throw new InvalidOperationException( Environment.GetResourceString( "InvalidOperation_NoPublicAddMethod" ) ); //// } //// //// return m_addMethod.GetParametersNoCopy()[0].ParameterType.SigToString() + " " + Name; //// } #endregion #region ICustomAttributeProvider public override Object[] GetCustomAttributes( bool inherit ) { throw new NotImplementedException(); //// return CustomAttribute.GetCustomAttributes( this, typeof( object ) as RuntimeType ); } public override Object[] GetCustomAttributes( Type attributeType, bool inherit ) { throw new NotImplementedException(); //// if(attributeType == null) //// { //// throw new ArgumentNullException( "attributeType" ); //// } //// //// RuntimeType attributeRuntimeType = attributeType.UnderlyingSystemType as RuntimeType; //// //// if(attributeRuntimeType == null) //// { //// throw new ArgumentException( Environment.GetResourceString( "Arg_MustBeType" ), "attributeType" ); //// } //// //// return CustomAttribute.GetCustomAttributes( this, attributeRuntimeType ); } public override bool IsDefined( Type attributeType, bool inherit ) { throw new NotImplementedException(); //// if(attributeType == null) //// { //// throw new ArgumentNullException( "attributeType" ); //// } //// //// RuntimeType attributeRuntimeType = attributeType.UnderlyingSystemType as RuntimeType; //// //// if(attributeRuntimeType == null) //// { //// throw new ArgumentException( Environment.GetResourceString( "Arg_MustBeType" ), "attributeType" ); //// } //// //// return CustomAttribute.IsDefined( this, attributeRuntimeType ); } #endregion #region MemberInfo Overrides //// public override MemberTypes MemberType //// { //// get //// { //// return MemberTypes.Event; //// } //// } public override String Name { get { throw new NotImplementedException(); //// if(m_name == null) //// { //// m_name = new Utf8String( m_utf8name ).ToString(); //// } //// //// return m_name; } } public override Type DeclaringType { get { throw new NotImplementedException(); //// return m_declaringType; } } //// public override Type ReflectedType //// { //// get //// { //// return m_reflectedTypeCache.RuntimeType; //// } //// } //// //// public override int MetadataToken //// { //// get //// { //// return m_token; //// } //// } //// //// public override Module Module //// { //// get //// { //// return m_declaringType.Module; //// } //// } #endregion #region ISerializable //// [SecurityPermissionAttribute( SecurityAction.LinkDemand, Flags = SecurityPermissionFlag.SerializationFormatter )] //// public void GetObjectData( SerializationInfo info, StreamingContext context ) //// { //// if(info == null) //// { //// throw new ArgumentNullException( "info" ); //// } //// //// MemberInfoSerializationHolder.GetSerializationInfo( info, Name, ReflectedType, null, MemberTypes.Event ); //// } #endregion #region EventInfo Overrides //// public override MethodInfo[] GetOtherMethods( bool nonPublic ) //// { //// ArrayList ret = new ArrayList(); //// //// if(m_otherMethod == null) //// { //// return new MethodInfo[0]; //// } //// //// for(int i = 0; i < m_otherMethod.Length; i++) //// { //// if(Associates.IncludeAccessor( (MethodInfo)m_otherMethod[i], nonPublic )) //// { //// ret.Add( m_otherMethod[i] ); //// } //// } //// //// return ret.ToArray( typeof( MethodInfo ) ) as MethodInfo[]; //// } //// //// public override MethodInfo GetAddMethod( bool nonPublic ) //// { //// if(!Associates.IncludeAccessor( m_addMethod, nonPublic )) //// { //// return null; //// } //// //// return m_addMethod; //// } //// //// public override MethodInfo GetRemoveMethod( bool nonPublic ) //// { //// if(!Associates.IncludeAccessor( m_removeMethod, nonPublic )) //// { //// return null; //// } //// //// return m_removeMethod; //// } //// //// public override MethodInfo GetRaiseMethod( bool nonPublic ) //// { //// if(!Associates.IncludeAccessor( m_raiseMethod, nonPublic )) //// { //// return null; //// } //// //// return m_raiseMethod; //// } //// //// public override EventAttributes Attributes //// { //// get //// { //// return m_flags; //// } //// } #endregion } } ================================================ FILE: Zelig/Zelig/RunTime/Framework/mscorlib/System/Reflection/RuntimeFieldInfo.cs ================================================ // ==++== // // Copyright (c) Microsoft Corporation. All rights reserved. // // ==--== namespace System.Reflection { using System; using System.Reflection; ////using System.Reflection.Cache; ////using System.Reflection.Emit; ////using System.Globalization; ////using System.Threading; ////using System.Diagnostics; ////using System.Security.Permissions; ////using System.Collections; ////using System.Security; ////using System.Text; using System.Runtime.ConstrainedExecution; ////using System.Runtime.CompilerServices; ////using System.Runtime.InteropServices; ////using System.Runtime.Serialization; ////using System.Runtime.Versioning; ////using RuntimeTypeCache = System.RuntimeType.RuntimeTypeCache; ////using CorElementType = System.Reflection.CorElementType; ////using MdToken = System.Reflection.MetadataToken; [Serializable] internal abstract class RuntimeFieldInfo : FieldInfo { #region Private Data Members //// private BindingFlags m_bindingFlags; //// protected RuntimeTypeCache m_reflectedTypeCache; //// protected RuntimeType m_declaringType; #endregion #region Constructor //// protected RuntimeFieldInfo() //// { //// // Used for dummy head node during population //// } //// //// protected RuntimeFieldInfo( RuntimeTypeCache reflectedTypeCache, RuntimeType declaringType, BindingFlags bindingFlags ) //// { //// m_bindingFlags = bindingFlags; //// m_declaringType = declaringType; //// m_reflectedTypeCache = reflectedTypeCache; //// } #endregion #region NonPublic Members //// internal BindingFlags BindingFlags //// { //// get //// { //// return m_bindingFlags; //// } //// } //// //// private RuntimeTypeHandle ReflectedTypeHandle //// { //// get //// { //// return m_reflectedTypeCache.RuntimeTypeHandle; //// } //// } //// //// internal RuntimeTypeHandle DeclaringTypeHandle //// { //// get //// { //// Type declaringType = DeclaringType; //// //// if(declaringType == null) //// { //// return Module.ModuleHandle.GetModuleTypeHandle(); //// } //// //// return declaringType.GetTypeHandleInternal(); //// } //// } //// //// internal virtual RuntimeFieldHandle GetFieldHandle() //// { //// return FieldHandle; //// } #endregion #region MemberInfo Overrides //// public override MemberTypes MemberType //// { //// get //// { //// return MemberTypes.Field; //// } //// } //// //// public override Type ReflectedType //// { //// get //// { //// return m_reflectedTypeCache.IsGlobal ? null : m_reflectedTypeCache.RuntimeType; //// } //// } //// //// public override Type DeclaringType //// { //// get //// { //// return m_reflectedTypeCache.IsGlobal ? null : m_declaringType; //// } //// } #endregion #region Object Overrides //// public unsafe override String ToString() //// { //// return FieldType.SigToString() + " " + Name; //// } #endregion #region ICustomAttributeProvider //// public override Object[] GetCustomAttributes( bool inherit ) //// { //// return CustomAttribute.GetCustomAttributes( this, typeof( object ) as RuntimeType ); //// } //// //// public override Object[] GetCustomAttributes( Type attributeType, bool inherit ) //// { //// if(attributeType == null) //// { //// throw new ArgumentNullException( "attributeType" ); //// } //// //// RuntimeType attributeRuntimeType = attributeType.UnderlyingSystemType as RuntimeType; //// //// if(attributeRuntimeType == null) //// { //// throw new ArgumentException( Environment.GetResourceString( "Arg_MustBeType" ), "attributeType" ); //// } //// //// return CustomAttribute.GetCustomAttributes( this, attributeRuntimeType ); //// } //// //// public override bool IsDefined( Type attributeType, bool inherit ) //// { //// if(attributeType == null) //// { //// throw new ArgumentNullException( "attributeType" ); //// } //// //// RuntimeType attributeRuntimeType = attributeType.UnderlyingSystemType as RuntimeType; //// //// if(attributeRuntimeType == null) //// { //// throw new ArgumentException( Environment.GetResourceString( "Arg_MustBeType" ), "attributeType" ); //// } //// //// return CustomAttribute.IsDefined( this, attributeRuntimeType ); //// } #endregion #region FieldInfo Overrides // All implemented on derived classes #endregion #region ISerializable Implementation //// public void GetObjectData( SerializationInfo info, StreamingContext context ) //// { //// if(info == null) //// { //// throw new ArgumentNullException( "info" ); //// } //// //// MemberInfoSerializationHolder.GetSerializationInfo( info, this.Name, this.ReflectedType, this.ToString(), MemberTypes.Field ); //// } #endregion } } ================================================ FILE: Zelig/Zelig/RunTime/Framework/mscorlib/System/Reflection/RuntimeMethodInfo.cs ================================================ // ==++== // // Copyright (c) Microsoft Corporation. All rights reserved. // // ==--== namespace System.Reflection { using System; using System.Reflection; ////using System.Reflection.Cache; ////using System.Reflection.Emit; using System.Globalization; using System.Threading; ////using System.Diagnostics; ////using System.Security.Permissions; ////using System.Collections; ////using System.Security; ////using System.Text; using System.Runtime.ConstrainedExecution; using System.Runtime.CompilerServices; ////using System.Runtime.InteropServices; ////using System.Runtime.Serialization; ////using System.Runtime.Versioning; ////using RuntimeTypeCache = System.RuntimeType.RuntimeTypeCache; ////using CorElementType = System.Reflection.CorElementType; ////using MdToken = System.Reflection.MetadataToken; [Serializable] internal sealed class RuntimeMethodInfo : MethodInfo /*, ISerializable*/ { #region Static Members //// internal static string ConstructParameters( ParameterInfo[] parameters, CallingConventions callingConvention ) //// { //// Type[] parameterTypes = new Type[parameters.Length]; //// //// for(int i = 0; i < parameters.Length; i++) //// { //// parameterTypes[i] = parameters[i].ParameterType; //// } //// //// return ConstructParameters( parameterTypes, callingConvention ); //// } //// //// internal static string ConstructParameters( Type[] parameters, CallingConventions callingConvention ) //// { //// string toString = ""; //// string comma = ""; //// //// for(int i = 0; i < parameters.Length; i++) //// { //// Type t = parameters[i]; //// //// toString += comma; //// toString += t.SigToString(); //// if(t.IsByRef) //// { //// toString = toString.TrimEnd( new char[] { '&' } ); //// toString += " ByRef"; //// } //// //// comma = ", "; //// } //// //// if((callingConvention & CallingConventions.VarArgs) == CallingConventions.VarArgs) //// { //// toString += comma; //// toString += "..."; //// } //// //// return toString; //// } //// //// internal static string ConstructName( MethodBase mi ) //// { //// // Serialization uses ToString to resolve MethodInfo overloads. //// string toString = null; //// //// toString += mi.Name; //// //// RuntimeMethodInfo rmi = mi as RuntimeMethodInfo; //// //// if(rmi != null && rmi.IsGenericMethod) //// { //// toString += rmi.m_handle.ConstructInstantiation(); //// } //// //// toString += "(" + ConstructParameters( mi.GetParametersNoCopy(), mi.CallingConvention ) + ")"; //// //// return toString; //// } #endregion #region Private Data Members #pragma warning disable 169 // The private field 'class member' is never used private RuntimeMethodHandle m_handle; #pragma warning restore 169 //// private RuntimeTypeCache m_reflectedTypeCache; //// private string m_name; //// private string m_toString; //// private ParameterInfo[] m_parameters; //// private ParameterInfo m_returnParameter; //// private BindingFlags m_bindingFlags; //// private MethodAttributes m_methodAttributes; //// private Signature m_signature; //// private RuntimeType m_declaringType; //// private uint m_invocationFlags; #endregion #region Constructor internal RuntimeMethodInfo() { // Used for dummy head node during population } //// internal RuntimeMethodInfo( RuntimeMethodHandle handle , //// RuntimeTypeHandle declaringTypeHandle, //// RuntimeTypeCache reflectedTypeCache , //// MethodAttributes methodAttributes , //// BindingFlags bindingFlags ) //// { //// ASSERT.PRECONDITION( !handle.IsNullHandle() ); //// ASSERT.PRECONDITION( methodAttributes == handle.GetAttributes() ); //// //// m_toString = null; //// m_bindingFlags = bindingFlags; //// m_handle = handle; //// m_reflectedTypeCache = reflectedTypeCache; //// m_parameters = null; // Created lazily when GetParameters() is called. //// m_methodAttributes = methodAttributes; //// m_declaringType = declaringTypeHandle.GetRuntimeType(); //// //// ASSERT.POSTCONDITION( !m_handle.IsNullHandle() ); //// } #endregion #region Private Methods //// private RuntimeTypeHandle ReflectedTypeHandle //// { //// get //// { //// return m_reflectedTypeCache.RuntimeTypeHandle; //// } //// } //// //// internal ParameterInfo[] FetchNonReturnParameters() //// { //// if(m_parameters == null) //// { //// m_parameters = ParameterInfo.GetParameters( this, this, Signature ); //// } //// //// return m_parameters; //// } //// //// internal ParameterInfo FetchReturnParameter() //// { //// if(m_returnParameter == null) //// { //// m_returnParameter = ParameterInfo.GetReturnParameter( this, this, Signature ); //// } //// //// return m_returnParameter; //// } //// #endregion #region Internal Members //// [ReliabilityContract( Consistency.WillNotCorruptState, Cer.Success )] //// internal override bool CacheEquals( object o ) //// { //// RuntimeMethodInfo m = o as RuntimeMethodInfo; //// //// if(m == null) //// { //// return false; //// } //// //// return m.m_handle.Equals( m_handle ); //// } //// //// internal Signature Signature //// { //// get //// { //// if(m_signature == null) //// { //// m_signature = new Signature( m_handle, m_declaringType.GetTypeHandleInternal() ); //// } //// //// return m_signature; //// } //// } //// //// internal BindingFlags BindingFlags //// { //// get //// { //// return m_bindingFlags; //// } //// } //// //// internal override RuntimeMethodHandle GetMethodHandle() //// { //// return m_handle; //// } //// //// internal override MethodInfo GetParentDefinition() //// { //// if(!IsVirtual || m_declaringType.IsInterface) //// { //// return null; //// } //// //// Type parent = m_declaringType.BaseType; //// //// if(parent == null) //// { //// return null; //// } //// //// int slot = m_handle.GetSlot(); //// //// if(parent.GetTypeHandleInternal().GetNumVtableSlots() <= slot) //// { //// return null; //// } //// //// return (MethodInfo)RuntimeType.GetMethodBase( parent.GetTypeHandleInternal(), parent.GetTypeHandleInternal().GetMethodAt( slot ) ); //// } //// //// internal override uint GetOneTimeFlags() //// { //// uint invocationFlags = 0; //// //// if(ReturnType.IsByRef) //// { //// invocationFlags = INVOCATION_FLAGS_NO_INVOKE; //// } //// //// invocationFlags |= base.GetOneTimeFlags(); //// //// return invocationFlags; //// } #endregion #region Object Overrides //// public override String ToString() //// { //// if(m_toString == null) //// { //// m_toString = ReturnType.SigToString() + " " + ConstructName( this ); //// } //// //// return m_toString; //// } //// //// public override int GetHashCode() //// { //// return m_handle.GetHashCode(); //// } //// //// public override bool Equals( object obj ) //// { //// if(!IsGenericMethod) //// { //// return obj == this; //// } //// //// RuntimeMethodInfo mi = obj as RuntimeMethodInfo; //// //// RuntimeMethodHandle handle1 = GetMethodHandle().StripMethodInstantiation(); //// RuntimeMethodHandle handle2 = mi.GetMethodHandle().StripMethodInstantiation(); //// if(handle1 != handle2) //// { //// return false; //// } //// //// if(mi == null || !mi.IsGenericMethod) //// { //// return false; //// } //// //// Type[] lhs = GetGenericArguments(); //// Type[] rhs = mi.GetGenericArguments(); //// //// if(lhs.Length != rhs.Length) //// { //// return false; //// } //// //// for(int i = 0; i < lhs.Length; i++) //// { //// if(lhs[i] != rhs[i]) //// { //// return false; //// } //// } //// //// return true; //// } #endregion #region ICustomAttributeProvider [MethodImpl( MethodImplOptions.InternalCall )] public extern override Object[] GetCustomAttributes( bool inherit ); //// { //// return CustomAttribute.GetCustomAttributes( this, typeof( object ) as RuntimeType as RuntimeType, inherit ); //// } [MethodImpl( MethodImplOptions.InternalCall )] public extern override Object[] GetCustomAttributes( Type attributeType, bool inherit ); //// { //// if(attributeType == null) //// { //// throw new ArgumentNullException( "attributeType" ); //// } //// //// RuntimeType attributeRuntimeType = attributeType.UnderlyingSystemType as RuntimeType; //// //// if(attributeRuntimeType == null) //// { //// throw new ArgumentException( Environment.GetResourceString( "Arg_MustBeType" ), "attributeType" ); //// } //// //// return CustomAttribute.GetCustomAttributes( this, attributeRuntimeType, inherit ); //// } [MethodImpl( MethodImplOptions.InternalCall )] public extern override bool IsDefined( Type attributeType, bool inherit ); //// { //// if(attributeType == null) //// { //// throw new ArgumentNullException( "attributeType" ); //// } //// //// RuntimeType attributeRuntimeType = attributeType.UnderlyingSystemType as RuntimeType; //// //// if(attributeRuntimeType == null) //// { //// throw new ArgumentException( Environment.GetResourceString( "Arg_MustBeType" ), "attributeType" ); //// } //// //// return CustomAttribute.IsDefined( this, attributeRuntimeType, inherit ); //// } #endregion #region MemberInfo Overrides public override String Name { //// [MethodImpl( MethodImplOptions.InternalCall )] get { throw new NotImplementedException(); //// if(m_name == null) //// { //// m_name = m_handle.GetName(); //// } //// //// return m_name; } } public override Type DeclaringType { get { throw new NotImplementedException(); //// if(m_reflectedTypeCache.IsGlobal) //// { //// return null; //// } //// //// return m_declaringType; } } //// public override Type ReflectedType //// { //// get //// { //// if(m_reflectedTypeCache.IsGlobal) //// { //// return null; //// } //// //// return m_reflectedTypeCache.RuntimeType; //// } //// } public override MemberTypes MemberType { get { return MemberTypes.Method; } } //// public override int MetadataToken //// { //// get //// { //// return m_handle.GetMethodDef(); //// } //// } //// //// public override Module Module //// { //// get //// { //// return m_declaringType.Module; //// } //// } #endregion #region MethodBase Overrides //// internal override ParameterInfo[] GetParametersNoCopy() //// { //// FetchNonReturnParameters(); //// //// return m_parameters; //// } [MethodImpl( MethodImplOptions.InternalCall )] public extern override ParameterInfo[] GetParameters(); //// { //// FetchNonReturnParameters(); //// //// if(m_parameters.Length == 0) //// { //// return m_parameters; //// } //// //// ParameterInfo[] ret = new ParameterInfo[m_parameters.Length]; //// //// Array.Copy( m_parameters, ret, m_parameters.Length ); //// //// return ret; //// } //// //// public override MethodImplAttributes GetMethodImplementationFlags() //// { //// return m_handle.GetImplAttributes(); //// } //// //// internal override bool IsOverloaded //// { //// get //// { //// return m_reflectedTypeCache.GetMethodList( MemberListType.CaseSensitive, Name ).Count > 1; //// } //// } //// //// public override RuntimeMethodHandle MethodHandle //// { //// get //// { //// Type declaringType = DeclaringType; //// if((declaringType == null && Module.Assembly.ReflectionOnly) || declaringType is ReflectionOnlyType) //// { //// throw new InvalidOperationException( Environment.GetResourceString( "InvalidOperation_NotAllowedInReflectionOnly" ) ); //// } //// //// return m_handle; //// } //// } //// //// public override MethodAttributes Attributes //// { //// get //// { //// return m_methodAttributes; //// } //// } //// //// public override CallingConventions CallingConvention //// { //// get //// { //// return Signature.CallingConvention; //// } //// } //// //// [ReflectionPermissionAttribute( SecurityAction.Demand, Flags = ReflectionPermissionFlag.MemberAccess )] //// public override MethodBody GetMethodBody() //// { //// MethodBody mb = m_handle.GetMethodBody( ReflectedTypeHandle ); //// if(mb != null) //// { //// mb.m_methodBase = this; //// } //// //// return mb; //// } #endregion #region Invocation Logic(On MemberBase) //// private void CheckConsistency( Object target ) //// { //// // only test instance methods //// if((m_methodAttributes & MethodAttributes.Static) != MethodAttributes.Static) //// { //// if(!m_declaringType.IsInstanceOfType( target )) //// { //// if(target == null) //// { //// throw new TargetException( Environment.GetResourceString( "RFLCT.Targ_StatMethReqTarg" ) ); //// } //// else //// { //// throw new TargetException( Environment.GetResourceString( "RFLCT.Targ_ITargMismatch" ) ); //// } //// } //// } //// } //// //// private void ThrowNoInvokeException() //// { //// // method is ReflectionOnly //// Type declaringType = DeclaringType; //// if((declaringType == null && Module.Assembly.ReflectionOnly) || declaringType is ReflectionOnlyType) //// { //// throw new InvalidOperationException( Environment.GetResourceString( "Arg_ReflectionOnlyInvoke" ) ); //// } //// //// // method is on a class that contains stack pointers //// if(DeclaringType.GetRootElementType() == typeof( ArgIterator )) //// { //// throw new NotSupportedException(); //// } //// // method is vararg //// else if((CallingConvention & CallingConventions.VarArgs) == CallingConventions.VarArgs) //// { //// throw new NotSupportedException(); //// } //// // method is generic or on a generic class //// else if(DeclaringType.ContainsGenericParameters || ContainsGenericParameters) //// { //// throw new InvalidOperationException( Environment.GetResourceString( "Arg_UnboundGenParam" ) ); //// } //// // method is abstract class //// else if(IsAbstract) //// { //// throw new MemberAccessException(); //// } //// // ByRef return are not allowed in reflection //// else if(ReturnType.IsByRef) //// { //// throw new NotSupportedException( Environment.GetResourceString( "NotSupported_ByRefReturn" ) ); //// } //// //// throw new TargetException(); //// } //// //// [DebuggerStepThroughAttribute] [Diagnostics.DebuggerHidden] [MethodImpl( MethodImplOptions.InternalCall )] public extern override Object Invoke( Object obj, BindingFlags invokeAttr, Binder binder, Object[] parameters, CultureInfo culture ); //// { //// return Invoke( obj, invokeAttr, binder, parameters, culture, false ); //// } //// //// [DebuggerStepThroughAttribute] //// [Diagnostics.DebuggerHidden] //// internal object Invoke( Object obj, BindingFlags invokeAttr, Binder binder, Object[] parameters, CultureInfo culture, bool skipVisibilityChecks ) //// { //// // get the signature //// int formalCount = Signature.Arguments.Length; //// int actualCount = (parameters != null) ? parameters.Length : 0; //// //// // set one time info for invocation //// if((m_invocationFlags & INVOCATION_FLAGS_INITIALIZED) == 0) //// { //// m_invocationFlags = GetOneTimeFlags(); //// } //// //// if((m_invocationFlags & INVOCATION_FLAGS_NO_INVOKE) != 0) //// { //// ThrowNoInvokeException(); //// } //// //// // check basic method consistency. This call will throw if there are problems in the target/method relationship //// CheckConsistency( obj ); //// //// if(formalCount != actualCount) //// { //// throw new TargetParameterCountException( Environment.GetResourceString( "Arg_ParmCnt" ) ); //// } //// //// // Don't allow more than 65535 parameters. //// if(actualCount > UInt16.MaxValue) //// { //// throw new TargetParameterCountException( Environment.GetResourceString( "NotSupported_TooManyArgs" ) ); //// } //// //// if(!skipVisibilityChecks && (m_invocationFlags & (INVOCATION_FLAGS_RISKY_METHOD | INVOCATION_FLAGS_NEED_SECURITY)) != 0) //// { //// if((m_invocationFlags & INVOCATION_FLAGS_RISKY_METHOD) != 0) //// { //// CodeAccessPermission.DemandInternal( PermissionType.ReflectionMemberAccess ); //// } //// //// if((m_invocationFlags & INVOCATION_FLAGS_NEED_SECURITY) != 0) //// { //// PerformSecurityCheck( obj, m_handle, m_declaringType.TypeHandle.Value, m_invocationFlags ); //// } //// } //// //// // if we are here we passed all the previous checks. Time to look at the arguments //// RuntimeTypeHandle declaringTypeHandle = RuntimeTypeHandle.EmptyHandle; //// if(!m_reflectedTypeCache.IsGlobal) //// { //// declaringTypeHandle = m_declaringType.TypeHandle; //// } //// //// if(actualCount == 0) //// { //// return m_handle.InvokeMethodFast( obj, null, Signature, m_methodAttributes, declaringTypeHandle ); //// } //// //// Object[] arguments = CheckArguments( parameters, binder, invokeAttr, culture, Signature ); //// //// Object retValue = m_handle.InvokeMethodFast( obj, arguments, Signature, m_methodAttributes, declaringTypeHandle ); //// //// // copy out. This should be made only if ByRef are present. //// for(int index = 0; index < actualCount; index++) //// { //// parameters[index] = arguments[index]; //// } //// //// return retValue; //// } #endregion #region MethodInfo Overrides //// public override Type ReturnType //// { //// get //// { //// return Signature.ReturnTypeHandle.GetRuntimeType(); //// } //// } //// //// public override ICustomAttributeProvider ReturnTypeCustomAttributes //// { //// get //// { //// return ReturnParameter; //// } //// } //// //// public override ParameterInfo ReturnParameter //// { //// get //// { //// FetchReturnParameter(); //// ASSERT.POSTCONDITION( m_returnParameter != null ); //// return m_returnParameter as ParameterInfo; //// } //// } //// //// public override MethodInfo GetBaseDefinition() //// { //// if(!IsVirtual || m_declaringType.IsInterface) //// { //// return this; //// } //// //// int slot = m_handle.GetSlot(); //// RuntimeTypeHandle parent = m_handle.GetDeclaringType(); //// RuntimeMethodHandle baseMethodHandle = RuntimeMethodHandle.EmptyHandle; //// //// do //// { //// int cVtblSlots = parent.GetNumVtableSlots(); //// //// if(cVtblSlots <= slot) //// { //// break; //// } //// //// baseMethodHandle = parent.GetMethodAt( slot ); //// parent = baseMethodHandle.GetDeclaringType().GetBaseTypeHandle(); //// } while(!parent.IsNullHandle()); //// //// ASSERT.CONSISTENCY_CHECK( (baseMethodHandle.GetAttributes() & MethodAttributes.Virtual) != 0 ); //// //// return (MethodInfo)RuntimeType.GetMethodBase( baseMethodHandle ); //// } #endregion #region Generics //// public override MethodInfo MakeGenericMethod( params Type[] methodInstantiation ) //// { //// if(methodInstantiation == null) //// { //// throw new ArgumentNullException( "methodInstantiation" ); //// } //// //// Type[] methodInstantiationCopy = new Type[methodInstantiation.Length]; //// for(int i = 0; i < methodInstantiation.Length; i++) //// { //// methodInstantiationCopy[i] = methodInstantiation[i]; //// } //// methodInstantiation = methodInstantiationCopy; //// //// if(!IsGenericMethodDefinition) //// { //// throw new InvalidOperationException( String.Format( CultureInfo.CurrentCulture, Environment.GetResourceString( "Arg_NotGenericMethodDefinition" ), this ) ); //// } //// //// for(int i = 0; i < methodInstantiation.Length; i++) //// { //// if(methodInstantiation[i] == null) //// { //// throw new ArgumentNullException(); //// } //// //// if(!(methodInstantiation[i] is RuntimeType)) //// { //// return MethodBuilderInstantiation.MakeGenericMethod( this, methodInstantiation ); //// } //// } //// //// Type[] genericParameters = GetGenericArguments(); //// //// RuntimeType.SanityCheckGenericArguments( methodInstantiation, genericParameters ); //// //// RuntimeTypeHandle[] typeHandles = new RuntimeTypeHandle[methodInstantiation.Length]; //// //// for(int i = 0; i < methodInstantiation.Length; i++) //// { //// typeHandles[i] = methodInstantiation[i].GetTypeHandleInternal(); //// } //// //// MethodInfo ret = null; //// //// try //// { //// ret = RuntimeType.GetMethodBase( m_reflectedTypeCache.RuntimeTypeHandle, m_handle.GetInstantiatingStub( m_declaringType.GetTypeHandleInternal(), typeHandles ) ) as MethodInfo; //// } //// catch(VerificationException e) //// { //// RuntimeType.ValidateGenericArguments( this, methodInstantiation, e ); //// throw e; //// } //// //// return ret; //// } //// //// public override Type[] GetGenericArguments() //// { //// RuntimeType[] rtypes = null; //// RuntimeTypeHandle[] types = m_handle.GetMethodInstantiation(); //// //// if(types != null) //// { //// rtypes = new RuntimeType[types.Length]; //// //// for(int i = 0; i < types.Length; i++) //// { //// rtypes[i] = types[i].GetRuntimeType(); //// } //// } //// else //// { //// rtypes = new RuntimeType[0]; //// } //// //// return rtypes; //// } //// //// public override MethodInfo GetGenericMethodDefinition() //// { //// if(!IsGenericMethod) //// { //// throw new InvalidOperationException(); //// } //// //// return RuntimeType.GetMethodBase( m_declaringType.GetTypeHandleInternal(), m_handle.StripMethodInstantiation() ) as MethodInfo; //// } //// //// public override bool IsGenericMethod //// { //// get //// { //// return m_handle.HasMethodInstantiation(); //// } //// } //// //// public override bool IsGenericMethodDefinition //// { //// get //// { //// return m_handle.IsGenericMethodDefinition(); //// } //// } //// //// public override bool ContainsGenericParameters //// { //// get //// { //// if(DeclaringType != null && DeclaringType.ContainsGenericParameters) //// { //// return true; //// } //// //// if(!IsGenericMethod) //// { //// return false; //// } //// //// Type[] pis = GetGenericArguments(); //// for(int i = 0; i < pis.Length; i++) //// { //// if(pis[i].ContainsGenericParameters) //// { //// return true; //// } //// } //// //// return false; //// } //// } #endregion #region ISerializable Implementation //// public void GetObjectData( SerializationInfo info, StreamingContext context ) //// { //// if(info == null) //// { //// throw new ArgumentNullException( "info" ); //// } //// //// if(m_reflectedTypeCache.IsGlobal) //// { //// throw new NotSupportedException( Environment.GetResourceString( "NotSupported_GlobalMethodSerialization" ) ); //// } //// //// MemberInfoSerializationHolder.GetSerializationInfo( //// info, Name, ReflectedTypeHandle.GetRuntimeType(), ToString(), MemberTypes.Method, //// IsGenericMethod & !IsGenericMethodDefinition ? GetGenericArguments() : null ); //// } #endregion #region Legacy Internal //// internal static MethodBase InternalGetCurrentMethod( ref StackCrawlMark stackMark ) //// { //// RuntimeMethodHandle method = RuntimeMethodHandle.GetCurrentMethod( ref stackMark ); //// //// if(method.IsNullHandle()) //// { //// return null; //// } //// //// // If C.m was called, GetCurrentMethod returns C.m. We cannot //// // get know that the instantiation used Foo or Bar at that point. So the next best thing //// // is to return C.m

and that's what GetTypicalMethodDefinition will do for us. //// method = method.GetTypicalMethodDefinition(); //// //// return RuntimeType.GetMethodBase( method ); //// } #endregion } } ================================================ FILE: Zelig/Zelig/RunTime/Framework/mscorlib/System/Reflection/RuntimePropertyInfo.cs ================================================ // ==++== // // Copyright (c) Microsoft Corporation. All rights reserved. // // ==--== namespace System.Reflection { using System; using System.Reflection; ////using System.Reflection.Cache; ////using System.Reflection.Emit; ////using System.Globalization; ////using System.Threading; ////using System.Diagnostics; ////using System.Security.Permissions; ////using System.Collections; ////using System.Security; ////using System.Text; using System.Runtime.ConstrainedExecution; ////using System.Runtime.CompilerServices; ////using System.Runtime.InteropServices; ////using System.Runtime.Serialization; ////using System.Runtime.Versioning; ////using RuntimeTypeCache = System.RuntimeType.RuntimeTypeCache; ////using CorElementType = System.Reflection.CorElementType; ////using MdToken = System.Reflection.MetadataToken; [Serializable] internal unsafe sealed class RuntimePropertyInfo : PropertyInfo /*, ISerializable*/ { #region Private Data Members //// private int m_token; //// private string m_name; //// private void* m_utf8name; //// private PropertyAttributes m_flags; //// private RuntimeTypeCache m_reflectedTypeCache; //// private RuntimeMethodInfo m_getterMethod; //// private RuntimeMethodInfo m_setterMethod; //// private MethodInfo[] m_otherMethod; //// private RuntimeType m_declaringType; //// private BindingFlags m_bindingFlags; //// private Signature m_signature; #endregion #region Constructor //// internal RuntimePropertyInfo( int tkProperty, RuntimeType declaredType, RuntimeTypeCache reflectedTypeCache, out bool isPrivate ) //// { //// ASSERT.PRECONDITION( declaredType != null ); //// ASSERT.PRECONDITION( reflectedTypeCache != null ); //// ASSERT.PRECONDITION( !reflectedTypeCache.IsGlobal ); //// //// MetadataImport scope = declaredType.Module.MetadataImport; //// //// m_token = tkProperty; //// m_reflectedTypeCache = reflectedTypeCache; //// m_declaringType = declaredType; //// //// RuntimeTypeHandle declaredTypeHandle = declaredType.GetTypeHandleInternal(); //// RuntimeTypeHandle reflectedTypeHandle = reflectedTypeCache.RuntimeTypeHandle; //// RuntimeMethodInfo dummy; //// //// scope.GetPropertyProps( tkProperty, out m_utf8name, out m_flags, out MetadataArgs.Skip.ConstArray ); //// //// int cAssociateRecord = scope.GetAssociatesCount( tkProperty ); //// //// AssociateRecord* associateRecord = stackalloc AssociateRecord[cAssociateRecord]; //// //// scope.GetAssociates( tkProperty, associateRecord, cAssociateRecord ); //// //// Associates.AssignAssociates( associateRecord, cAssociateRecord, declaredTypeHandle, reflectedTypeHandle, //// out dummy, out dummy, out dummy, //// out m_getterMethod, out m_setterMethod, out m_otherMethod, //// out isPrivate, out m_bindingFlags ); //// } #endregion #region Internal Members //// [ReliabilityContract( Consistency.WillNotCorruptState, Cer.Success )] //// internal override bool CacheEquals( object o ) //// { //// RuntimePropertyInfo m = o as RuntimePropertyInfo; //// //// if(m == null) //// { //// return false; //// } //// //// return m.m_token == m_token && m_declaringType.GetTypeHandleInternal().GetModuleHandle().Equals( m.m_declaringType.GetTypeHandleInternal().GetModuleHandle() ); //// } //// //// internal Signature Signature //// { //// get //// { //// if(m_signature == null) //// { //// ConstArray sig; //// //// void* name; //// //// Module.MetadataImport.GetPropertyProps( m_token, out name, out MetadataArgs.Skip.PropertyAttributes, out sig ); //// //// m_signature = new Signature( sig.Signature.ToPointer(), (int)sig.Length, m_declaringType.GetTypeHandleInternal() ); //// } //// //// return m_signature; //// } //// } //// //// internal BindingFlags BindingFlags //// { //// get //// { //// return m_bindingFlags; //// } //// } //// //// internal bool EqualsSig( RuntimePropertyInfo target ) //// { //// //@Asymmetry - Legacy policy is to remove duplicate properties, including hidden properties. //// // The comparison is done by name and by sig. The EqualsSig comparison is expensive //// // but forutnetly it is only called when an inherited property is hidden by name or //// // when an interfaces declare properies with the same signature. //// //// ASSERT.PRECONDITION( Name.Equals( target.Name ) ); //// ASSERT.PRECONDITION( this != target ); //// ASSERT.PRECONDITION( this.ReflectedType == target.ReflectedType ); //// //// return Signature.DiffSigs( target.Signature ); //// } #endregion #region Object Overrides //// public override String ToString() //// { //// string toString = PropertyType.SigToString() + " " + Name; //// //// RuntimeTypeHandle[] argumentHandles = Signature.Arguments; //// if(argumentHandles.Length > 0) //// { //// Type[] paramters = new Type[argumentHandles.Length]; //// for(int i = 0; i < paramters.Length; i++) //// { //// paramters[i] = argumentHandles[i].GetRuntimeType(); //// } //// //// toString += " [" + RuntimeMethodInfo.ConstructParameters( paramters, Signature.CallingConvention ) + "]"; //// } //// //// return toString; //// } #endregion #region ICustomAttributeProvider public override Object[] GetCustomAttributes( bool inherit ) { throw new NotImplementedException(); //// return CustomAttribute.GetCustomAttributes( this, typeof( object ) as RuntimeType ); } public override Object[] GetCustomAttributes( Type attributeType, bool inherit ) { throw new NotImplementedException(); //// if(attributeType == null) //// { //// throw new ArgumentNullException( "attributeType" ); //// } //// //// RuntimeType attributeRuntimeType = attributeType.UnderlyingSystemType as RuntimeType; //// //// if(attributeRuntimeType == null) //// { //// throw new ArgumentException( Environment.GetResourceString( "Arg_MustBeType" ), "attributeType" ); //// } //// //// return CustomAttribute.GetCustomAttributes( this, attributeRuntimeType ); } public override bool IsDefined( Type attributeType, bool inherit ) { throw new NotImplementedException(); //// if(attributeType == null) //// { //// throw new ArgumentNullException( "attributeType" ); //// } //// //// RuntimeType attributeRuntimeType = attributeType.UnderlyingSystemType as RuntimeType; //// //// if(attributeRuntimeType == null) //// { //// throw new ArgumentException( Environment.GetResourceString( "Arg_MustBeType" ), "attributeType" ); //// } //// //// return CustomAttribute.IsDefined( this, attributeRuntimeType ); } #endregion #region MemberInfo Overrides //// public override MemberTypes MemberType //// { //// get //// { //// return MemberTypes.Property; //// } //// } public override String Name { get { throw new NotImplementedException(); //// if(m_name == null) //// { //// m_name = new Utf8String( m_utf8name ).ToString(); //// } //// //// return m_name; } } public override Type DeclaringType { get { throw new NotImplementedException(); //// return m_declaringType; } } //// public override Type ReflectedType //// { //// get //// { //// return m_reflectedTypeCache.RuntimeType; //// } //// } //// //// public override int MetadataToken //// { //// get //// { //// return m_token; //// } //// } //// //// public override Module Module //// { //// get //// { //// return m_declaringType.Module; //// } //// } #endregion #region PropertyInfo Overrides #region Non Dynamic //// public override Type[] GetRequiredCustomModifiers() //// { //// return Signature.GetCustomModifiers( 0, true ); //// } //// //// public override Type[] GetOptionalCustomModifiers() //// { //// return Signature.GetCustomModifiers( 0, false ); //// } //// //// internal object GetConstantValue( bool raw ) //// { //// Object defaultValue = MdConstant.GetValue( Module.MetadataImport, m_token, PropertyType.GetTypeHandleInternal(), raw ); //// //// if(defaultValue == DBNull.Value) //// { //// // Arg_EnumLitValueNotFound -> "Literal value was not found." //// throw new InvalidOperationException( Environment.GetResourceString( "Arg_EnumLitValueNotFound" ) ); //// } //// //// return defaultValue; //// } //// //// public override object GetConstantValue() //// { //// return GetConstantValue( false ); //// } //// //// public override object GetRawConstantValue() //// { //// return GetConstantValue( true ); //// } //// //// public override MethodInfo[] GetAccessors( bool nonPublic ) //// { //// ArrayList accessorList = new ArrayList(); //// //// if(Associates.IncludeAccessor( m_getterMethod, nonPublic )) //// { //// accessorList.Add( m_getterMethod ); //// } //// //// if(Associates.IncludeAccessor( m_setterMethod, nonPublic )) //// { //// accessorList.Add( m_setterMethod ); //// } //// //// if(m_otherMethod != null) //// { //// for(int i = 0; i < m_otherMethod.Length; i++) //// { //// if(Associates.IncludeAccessor( m_otherMethod[i] as MethodInfo, nonPublic )) //// { //// accessorList.Add( m_otherMethod[i] ); //// } //// } //// } //// //// return accessorList.ToArray( typeof( MethodInfo ) ) as MethodInfo[]; //// } //// //// public override Type PropertyType //// { //// get //// { //// return Signature.ReturnTypeHandle.GetRuntimeType(); //// } //// } //// //// public override MethodInfo GetGetMethod( bool nonPublic ) //// { //// if(!Associates.IncludeAccessor( m_getterMethod, nonPublic )) //// { //// return null; //// } //// //// return m_getterMethod; //// } //// //// public override MethodInfo GetSetMethod( bool nonPublic ) //// { //// if(!Associates.IncludeAccessor( m_setterMethod, nonPublic )) //// { //// return null; //// } //// //// return m_setterMethod; //// } //// //// public override ParameterInfo[] GetIndexParameters() //// { //// // @History - Logic ported from RTM //// //// int numParams = 0; //// ParameterInfo[] methParams = null; //// //// // First try to get the Get method. //// MethodInfo m = GetGetMethod( true ); //// if(m != null) //// { //// // There is a Get method so use it. //// methParams = m.GetParametersNoCopy(); //// numParams = methParams.Length; //// } //// else //// { //// // If there is no Get method then use the Set method. //// m = GetSetMethod( true ); //// //// if(m != null) //// { //// methParams = m.GetParametersNoCopy(); //// numParams = methParams.Length - 1; //// } //// } //// //// // Now copy over the parameter info's and change their //// // owning member info to the current property info. //// //// if(methParams != null && methParams.Length == 0) //// { //// return methParams; //// } //// //// ParameterInfo[] propParams = new ParameterInfo[numParams]; //// //// for(int i = 0; i < numParams; i++) //// { //// propParams[i] = new ParameterInfo( methParams[i], this ); //// } //// //// return propParams; //// } //// //// public override PropertyAttributes Attributes //// { //// get //// { //// return m_flags; //// } //// } //// //// public override bool CanRead //// { //// get //// { //// return m_getterMethod != null; //// } //// } //// //// public override bool CanWrite //// { //// get //// { //// return m_setterMethod != null; //// } //// } #endregion #region Dynamic //// [DebuggerStepThroughAttribute] //// [Diagnostics.DebuggerHidden] //// public override Object GetValue( Object obj, Object[] index ) //// { //// return GetValue( obj, BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.Static, null, index, null ); //// } //// //// [DebuggerStepThroughAttribute] //// [Diagnostics.DebuggerHidden] //// public override Object GetValue( Object obj, BindingFlags invokeAttr, Binder binder, Object[] index, CultureInfo culture ) //// { //// MethodInfo m = GetGetMethod( true ); //// if(m == null) //// { //// throw new ArgumentException( System.Environment.GetResourceString( "Arg_GetMethNotFnd" ) ); //// } //// //// return m.Invoke( obj, invokeAttr, binder, index, null ); //// } //// //// [DebuggerStepThroughAttribute] //// [Diagnostics.DebuggerHidden] //// public override void SetValue( Object obj, Object value, Object[] index ) //// { //// SetValue( obj, //// value, //// BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.Static, //// null, //// index, //// null ); //// } //// //// [DebuggerStepThroughAttribute] //// [Diagnostics.DebuggerHidden] //// public override void SetValue( Object obj, Object value, BindingFlags invokeAttr, Binder binder, Object[] index, CultureInfo culture ) //// { //// MethodInfo m = GetSetMethod( true ); //// if(m == null) //// { //// throw new ArgumentException( System.Environment.GetResourceString( "Arg_SetMethNotFnd" ) ); //// } //// //// Object[] args = null; //// //// if(index != null) //// { //// args = new Object[index.Length + 1]; //// //// for(int i = 0; i < index.Length; i++) //// { //// args[i] = index[i]; //// } //// //// args[index.Length] = value; //// } //// else //// { //// args = new Object[1]; //// args[0] = value; //// } //// //// m.Invoke( obj, invokeAttr, binder, args, culture ); //// } #endregion #endregion #region ISerializable Implementation //// public void GetObjectData( SerializationInfo info, StreamingContext context ) //// { //// if(info == null) //// { //// throw new ArgumentNullException( "info" ); //// } //// //// MemberInfoSerializationHolder.GetSerializationInfo( info, Name, ReflectedType, ToString(), MemberTypes.Property ); //// } #endregion } } ================================================ FILE: Zelig/Zelig/RunTime/Framework/mscorlib/System/Reflection/TypeAttributes.cs ================================================ // ==++== // // Copyright (c) Microsoft Corporation. All rights reserved. // // ==--== namespace System.Reflection { using System; using System.Runtime.InteropServices; // This Enum matchs the CorTypeAttr defined in CorHdr.h [Flags] [Serializable] public enum TypeAttributes { VisibilityMask = 0x00000007, NotPublic = 0x00000000, // Class is not public scope. Public = 0x00000001, // Class is public scope. NestedPublic = 0x00000002, // Class is nested with public visibility. NestedPrivate = 0x00000003, // Class is nested with private visibility. NestedFamily = 0x00000004, // Class is nested with family visibility. NestedAssembly = 0x00000005, // Class is nested with assembly visibility. NestedFamANDAssem = 0x00000006, // Class is nested with family and assembly visibility. NestedFamORAssem = 0x00000007, // Class is nested with family or assembly visibility. // Use this mask to retrieve class layout informaiton // 0 is AutoLayout, 0x2 is SequentialLayout, 4 is ExplicitLayout LayoutMask = 0x00000018, AutoLayout = 0x00000000, // Class fields are auto-laid out SequentialLayout = 0x00000008, // Class fields are laid out sequentially ExplicitLayout = 0x00000010, // Layout is supplied explicitly // end layout mask // Use this mask to distinguish a type declaration as a Class, ValueType or Interface ClassSemanticsMask = 0x00000020, Class = 0x00000000, // Type is a class. Interface = 0x00000020, // Type is an interface. // Special semantics in addition to class semantics. Abstract = 0x00000080, // Class is abstract Sealed = 0x00000100, // Class is concrete and may not be extended SpecialName = 0x00000400, // Class name is special. Name describes how. // Implementation attributes. Import = 0x00001000, // Class / interface is imported Serializable = 0x00002000, // The class is Serializable. // Use tdStringFormatMask to retrieve string information for native interop StringFormatMask = 0x00030000, AnsiClass = 0x00000000, // LPTSTR is interpreted as ANSI in this class UnicodeClass = 0x00010000, // LPTSTR is interpreted as UNICODE AutoClass = 0x00020000, // LPTSTR is interpreted automatically CustomFormatClass = 0x00030000, // A non-standard encoding specified by CustomFormatMask CustomFormatMask = 0x00C00000, // Use this mask to retrieve non-standard encoding information for native interop. The meaning of the values of these 2 bits is unspecified. // end string format mask BeforeFieldInit = 0x00100000, // Initialize the class any time before first static field access. // Flags reserved for runtime use. ReservedMask = 0x00040800, RTSpecialName = 0x00000800, // Runtime should check name encoding. HasSecurity = 0x00040000, // Class has security associate with it. } } ================================================ FILE: Zelig/Zelig/RunTime/Framework/mscorlib/System/Reflection/TypeFilter.cs ================================================ // ==++== // // Copyright (c) Microsoft Corporation. All rights reserved. // // ==--== //////////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////////// // // TypeFilter defines a delegate that is as a callback function for filtering // a list of Types. // // Author: darylo // Date: March 98 // namespace System.Reflection { // Define the delegate [Serializable] public delegate bool TypeFilter( Type m, Object filterCriteria ); } ================================================ FILE: Zelig/Zelig/RunTime/Framework/mscorlib/System/Resources/ResourceManager.cs ================================================ // ==++== // // Copyright (c) Microsoft Corporation. All rights reserved. // // ==--== /*============================================================ ** ** Class: ResourceManager ** ** ** Purpose: Default way to access String resources from ** an assembly. ** ** ===========================================================*/ namespace System.Resources { using System; using System.IO; using System.Globalization; using System.Collections; using System.Text; using System.Reflection; using System.Runtime.CompilerServices; ////using System.Runtime.Remoting.Activation; ////using System.Runtime.Serialization; ////using System.Security.Permissions; using System.Threading; using System.Runtime.InteropServices; ////using Microsoft.Win32; using System.Collections.Generic; ////using System.Runtime.Versioning; // Resource Manager exposes an assembly's resources to an application for // the correct CultureInfo. An example would be localizing text for a // user-visible message. Create a set of resource files listing a name // for a message and its value, compile them using ResGen, put them in // an appropriate place (your assembly manifest(?)), then create a Resource // Manager and query for the name of the message you want. The Resource // Manager will use CultureInfo.GetCurrentUICulture() to look // up a resource for your user's locale settings. // // Users should ideally create a resource file for every culture, or // at least a meaningful subset. The filenames will follow the naming // scheme: // // basename.culture name.resources // // The base name can be the name of your application, or depending on // the granularity desired, possibly the name of each class. The culture // name is determined from CultureInfo's Name property. // An example file name may be MyApp.en-US.resources for // MyApp's US English resources. // [Microsoft.Zelig.Internals.WellKnownType( "System_Resources_ResourceManager" )] [Serializable] public class ResourceManager { protected String BaseNameField; //// // Sets is a many-to-one table of CultureInfos mapped to ResourceSets. //// // Don't synchronize ResourceSets - too fine-grained a lock to be effective //// protected Hashtable ResourceSets; //// private String moduleDir; // For assembly-ignorant directory location protected Assembly MainAssembly; // Need the assembly manifest sometimes. //// private Type _locationInfo; // For Assembly or type-based directory layout //// private Type _userResourceSet; // Which ResourceSet instance to create //// private CultureInfo _neutralResourcesCulture; // For perf optimizations. //// //// private bool _ignoreCase; // Whether case matters in GetString & GetObject //// // When we create a separate FileBasedResourceManager subclass, //// // UseManifest can be replaced with "false". //// private bool UseManifest; // Use Assembly manifest, or grovel disk. //// //// // When we create a separate FileBasedResourceManager subclass, //// // UseSatelliteAssem can be replaced with "true". //// private bool UseSatelliteAssem; // Are all the .resources files in the //// // main assembly, or in satellite assemblies for each culture? //// //// // Whether to fall back to the main assembly or a particular //// // satellite for the neutral resources. //// [OptionalField] //// private UltimateResourceFallbackLocation _fallbackLoc; //// // Version number of satellite assemblies to look for. May be null. //// [OptionalField] //// private Version _satelliteContractVersion; //// [OptionalField] //// private bool _lookedForSatelliteContractVersion; //// //// private Assembly _callingAssembly; // Assembly who created the ResMgr. //// //// public static readonly int MagicNumber = unchecked( (int)0xBEEFCACE ); // If only hex had a K... //// //// // Version number so ResMgr can get the ideal set of classes for you. //// // ResMgr header is: //// // 1) MagicNumber (little endian Int32) //// // 2) HeaderVersionNumber (little endian Int32) //// // 3) Num Bytes to skip past ResMgr header (little endian Int32) //// // 4) IResourceReader type name for this file (bytelength-prefixed UTF-8 String) //// // 5) ResourceSet type name for this file (bytelength-prefixed UTF8 String) //// public static readonly int HeaderVersionNumber = 1; //// //// // //// //It would be better if we could use _neutralCulture instead of calling //// //CultureInfo.InvariantCulture everywhere, but we run into problems with the .cctor. CultureInfo //// //initializes assembly, which initializes ResourceManager, which tries to get a CultureInfo which isn't //// //there yet because CultureInfo's class initializer hasn't finished. If we move SystemResMgr off of //// //Assembly (or at least make it an internal property) we should be able to circumvent this problem. //// // //// // private static CultureInfo _neutralCulture = null; //// //// // This is our min required ResourceSet type. //// private static readonly Type _minResourceSet = typeof( ResourceSet ); //// // These Strings are used to avoid using Reflection in CreateResourceSet. //// // The first set are used by ResourceWriter. The second are used by //// // InternalResGen. //// internal static readonly String ResReaderTypeName = typeof( ResourceReader ).FullName; //// internal static readonly String ResSetTypeName = typeof( RuntimeResourceSet ).FullName; //// internal static readonly String MscorlibName = typeof( ResourceReader ).Assembly.FullName; //// internal const String ResFileExtension = ".resources"; //// internal const int ResFileExtensionLength = 10; //// //// // My private debugging aid. Set to 5 or 6 for verbose output. Set to 3 //// // for summary level information. //// internal static readonly int DEBUG = 0; //Making this const causes C# to consider all of the code that it guards unreachable. protected ResourceManager() { //// StackCrawlMark stackMark = StackCrawlMark.LookForMyCaller; //// _callingAssembly = Assembly.GetExecutingAssembly( ref stackMark ); } //// // Constructs a Resource Manager for files beginning with //// // baseName in the directory specified by resourceDir //// // or in the current directory. This Assembly-ignorant constructor is //// // mostly useful for testing your own ResourceSet implementation. //// // //// // A good example of a baseName might be "Strings". BaseName //// // should not end in ".resources". //// // //// // Note: System.Windows.Forms uses this method at design time. //// // //// [ResourceExposure( ResourceScope.Machine )] //// [ResourceConsumption( ResourceScope.Machine )] //// private ResourceManager( String baseName, String resourceDir, Type usingResourceSet ) //// { //// //// // //// // __FileBasedResourceManager: We should move all the file-based functionality into a //// // (potentially internal) subclass of ResourceManager. This will simplify //// // InternalGetResourceSet a lot. We can also make several fields like UseManifest //// // private. //// // //// //// //// if(null == baseName) //// throw new ArgumentNullException( "baseName" ); //// if(null == resourceDir) //// throw new ArgumentNullException( "resourceDir" ); //// //// BaseNameField = baseName; //// //// moduleDir = resourceDir; //// _userResourceSet = usingResourceSet; //// ResourceSets = new Hashtable(); //// UseManifest = false; //// } public ResourceManager( String baseName, Assembly assembly ) { //// if(null == baseName) //// throw new ArgumentNullException( "baseName" ); //// if(null == assembly) //// throw new ArgumentNullException( "assembly" ); MainAssembly = assembly; //// _locationInfo = null; BaseNameField = baseName; //// CommonSatelliteAssemblyInit(); //// StackCrawlMark stackMark = StackCrawlMark.LookForMyCaller; //// _callingAssembly = Assembly.GetExecutingAssembly( ref stackMark ); //// // Special case for mscorlib - protect mscorlib's private resources. //// // This isn't for security reasons, but to ensure we can make //// // breaking changes to mscorlib's internal resources without //// // assuming users may have taken a dependency on them. //// if(assembly == typeof( Object ).Assembly && _callingAssembly != assembly) //// _callingAssembly = null; } //// public ResourceManager( String baseName, Assembly assembly, Type usingResourceSet ) //// { //// if(null == baseName) //// throw new ArgumentNullException( "baseName" ); //// if(null == assembly) //// throw new ArgumentNullException( "assembly" ); //// //// MainAssembly = assembly; //// _locationInfo = null; //// BaseNameField = baseName; //// //// if(usingResourceSet != null && (usingResourceSet != _minResourceSet) && !(usingResourceSet.IsSubclassOf( _minResourceSet ))) //// throw new ArgumentException( Environment.GetResourceString( "Arg_ResMgrNotResSet" ), "usingResourceSet" ); //// _userResourceSet = usingResourceSet; //// //// CommonSatelliteAssemblyInit(); //// StackCrawlMark stackMark = StackCrawlMark.LookForMyCaller; //// _callingAssembly = Assembly.GetExecutingAssembly( ref stackMark ); //// // Special case for mscorlib - protect mscorlib's private resources. //// // This isn't for security reasons, but to ensure we can make //// // breaking changes to mscorlib's internal resources without //// // assuming users may have taken a dependency on them. //// if(assembly == typeof( Object ).Assembly && _callingAssembly != assembly) //// _callingAssembly = null; //// } //// //// public ResourceManager( Type resourceSource ) //// { //// if(null == resourceSource) //// throw new ArgumentNullException( "resourceSource" ); //// //// _locationInfo = resourceSource; //// MainAssembly = _locationInfo.Assembly; //// BaseNameField = resourceSource.Name; //// //// CommonSatelliteAssemblyInit(); //// StackCrawlMark stackMark = StackCrawlMark.LookForMyCaller; //// _callingAssembly = Assembly.GetExecutingAssembly( ref stackMark ); //// // Special case for mscorlib - protect mscorlib's private resources. //// if(MainAssembly == typeof( Object ).Assembly && _callingAssembly != MainAssembly) //// _callingAssembly = null; //// } //// //// // Trying to unify code as much as possible, even though having to do a //// // security check in each constructor prevents it. //// private void CommonSatelliteAssemblyInit() //// { //// UseManifest = true; //// UseSatelliteAssem = true; //// //// ResourceSets = new Hashtable(); //// //// _fallbackLoc = UltimateResourceFallbackLocation.MainAssembly; //// } //// //// // Gets the base name for the ResourceManager. //// public virtual String BaseName //// { //// get { return BaseNameField; } //// } //// //// // Whether we should ignore the capitalization of resources when calling //// // GetString or GetObject. //// public virtual bool IgnoreCase //// { //// get { return _ignoreCase; } //// set { _ignoreCase = value; } //// } //// //// // Returns the Type of the ResourceSet the ResourceManager uses //// // to construct ResourceSets. //// public virtual Type ResourceSetType //// { //// get { return (_userResourceSet == null) ? typeof( RuntimeResourceSet ) : _userResourceSet; } //// } //// //// protected UltimateResourceFallbackLocation FallbackLocation //// { //// get { return _fallbackLoc; } //// set { _fallbackLoc = value; } //// } //// //// // Tells the ResourceManager to call Close on all ResourceSets and //// // release all resources. This will shrink your working set by //// // potentially a substantial amount in a running application. Any //// // future resource lookups on this ResourceManager will be as //// // expensive as the very first lookup, since it will need to search //// // for files and load resources again. //// // //// // This may be useful in some complex threading scenarios, where //// // creating a new ResourceManager isn't quite the correct behavior. //// public virtual void ReleaseAllResources() //// { //// IDictionaryEnumerator setEnum = ResourceSets.GetEnumerator(); //// // If any calls to Close throw, at least leave ourselves in a //// // consistent state. //// ResourceSets = new Hashtable(); //// while(setEnum.MoveNext()) //// { //// ((ResourceSet)setEnum.Value).Close(); //// } //// } //// //// [ResourceExposure( ResourceScope.Machine )] //// [ResourceConsumption( ResourceScope.Machine )] //// public static ResourceManager CreateFileBasedResourceManager( String baseName, String resourceDir, Type usingResourceSet ) //// { //// return new ResourceManager( baseName, resourceDir, usingResourceSet ); //// } //// //// // Given a CultureInfo, it generates the path &; file name for //// // the .resources file for that CultureInfo. This method will grovel //// // the disk looking for the correct file name & path. Uses CultureInfo's //// // Name property. If the module directory was set in the ResourceManager //// // constructor, we'll look there first. If it couldn't be found in the module //// // diretory or the module dir wasn't provided, look in the current //// // directory. //// [ResourceExposure( ResourceScope.Machine )] //// [ResourceConsumption( ResourceScope.Machine )] //// private String FindResourceFile( CultureInfo culture ) //// { //// //// // __FileBasedResourceManager: When we create a __FileBasedResourceManager, move this method //// // to that class. This is part of the assembly-ignorant implementation //// // that really doesn't belong on ResourceManager. //// //// String fileName = GetResourceFileName( culture ); //// //// // If we have a moduleDir, check there first. Get module fully //// // qualified name, append path to that. //// if(moduleDir != null) //// { //// String path = Path.Combine( moduleDir, fileName ); //// if(File.Exists( path )) //// { //// return path; //// } //// } //// //// // look in . //// if(File.Exists( fileName )) //// return fileName; //// //// return null; // give up. //// } //// //// // Given a CultureInfo, GetResourceFileName generates the name for //// // the binary file for the given CultureInfo. This method uses //// // CultureInfo's Name property as part of the file name for all cultures //// // other than the invariant culture. This method does not touch the disk, //// // and is used only to construct what a resource file name (suitable for //// // passing to the ResourceReader constructor) or a manifest resource blob //// // name should look like. //// // //// // This method can be overriden to look for a different extension, //// // such as ".ResX", or a completely different format for naming files. //// protected virtual String GetResourceFileName( CultureInfo culture ) //// { //// StringBuilder sb = new StringBuilder( 255 ); //// sb.Append( BaseNameField ); //// // If this is the neutral culture, don't append culture name. //// if(!culture.Equals( CultureInfo.InvariantCulture )) //// { //// CultureInfo.VerifyCultureName( culture, true ); //// sb.Append( '.' ); //// sb.Append( culture.Name ); //// } //// sb.Append( ResFileExtension ); //// return sb.ToString(); //// } //// //// // Looks up a set of resources for a particular CultureInfo. This is //// // not useful for most users of the ResourceManager - call //// // GetString() or GetObject() instead. //// // //// // The parameters let you control whether the ResourceSet is created //// // if it hasn't yet been loaded and if parent CultureInfos should be //// // loaded as well for resource inheritance. //// // //// public virtual ResourceSet GetResourceSet( CultureInfo culture, bool createIfNotExists, bool tryParents ) //// { //// if(null == culture) //// throw new ArgumentNullException( "culture" ); //// //// //// Hashtable localResourceSets = ResourceSets; //// ResourceSet rs; //// if(localResourceSets != null) //// { //// rs = (ResourceSet)localResourceSets[culture]; //// if(null != rs) //// return rs; //// } //// //// if(UseManifest && culture.Equals( CultureInfo.InvariantCulture )) //// { //// StackCrawlMark stackMark = StackCrawlMark.LookForMyCaller; //// string fileName = GetResourceFileName( culture ); //// Stream stream = MainAssembly.GetManifestResourceStream( _locationInfo, fileName, _callingAssembly == MainAssembly, ref stackMark ); //// if(createIfNotExists && stream != null) //// { //// rs = CreateResourceSet( stream, MainAssembly ); //// lock(localResourceSets) //// { //// localResourceSets.Add( culture, rs ); //// } //// return rs; //// } //// } //// //// return InternalGetResourceSet( culture, createIfNotExists, tryParents ); //// } //// //// // InternalGetResourceSet is a non-threadsafe method where all the logic //// // for getting a resource set lives. Access to it is controlled by //// // threadsafe methods such as GetResourceSet, GetString, & GetObject. //// // This will take a minimal number of locks. //// [ResourceExposure( ResourceScope.None )] //// [ResourceConsumption( ResourceScope.Machine, ResourceScope.Machine )] //// protected virtual ResourceSet InternalGetResourceSet( CultureInfo culture, bool createIfNotExists, bool tryParents ) //// { //// BCLDebug.Assert( culture != null, "culture != null" ); //// //// Hashtable localResourceSets = ResourceSets; //// ResourceSet rs = (ResourceSet)localResourceSets[culture]; //// if(null != rs) //// return rs; //// //// // InternalGetResourceSet will never be threadsafe. However, it must //// // be protected against reentrancy from the SAME THREAD. (ie, calling //// // GetSatelliteAssembly may send some window messages or trigger the //// // Assembly load event, which could fail then call back into the //// // ResourceManager). It's happened. //// //// Stream stream = null; //// String fileName = null; //// Assembly satellite = null; // Which assembly we loaded from //// if(UseManifest) //// { //// fileName = GetResourceFileName( culture ); //// // Ask assembly for resource stream named fileName. //// StackCrawlMark stackMark = StackCrawlMark.LookForMyCaller; //// if(UseSatelliteAssem) //// { //// CultureInfo lookForCulture = culture; //// if(_neutralResourcesCulture == null) //// _neutralResourcesCulture = GetNeutralResourcesLanguage( MainAssembly, ref _fallbackLoc ); //// // If our neutral resources were written in this culture //// // AND we know the main assembly does NOT contain neutral //// // resources, don't probe for this satellite. //// if(culture.Equals( _neutralResourcesCulture ) && //// FallbackLocation == UltimateResourceFallbackLocation.MainAssembly) //// { //// // Update internal state. //// lookForCulture = CultureInfo.InvariantCulture; //// fileName = GetResourceFileName( lookForCulture ); //// } //// //// // For neutral locale, look in the main assembly //// // if and only if our fallback location is MainAssembly. //// if(lookForCulture.Equals( CultureInfo.InvariantCulture )) //// { //// if(FallbackLocation == UltimateResourceFallbackLocation.Satellite) //// { //// satellite = GetSatelliteAssembly( _neutralResourcesCulture ); //// // If your ultimate fallback satellite couldn't be //// // loaded, it's a fatal error. We'll give //// // you a nice error message. //// if(satellite == null) //// { //// String satAssemName = MainAssembly.GetSimpleName() + ".resources.dll"; //// if(_satelliteContractVersion != null) //// satAssemName += ", Version=" + _satelliteContractVersion.ToString(); //// //// AssemblyName an = new AssemblyName(); //// an.SetPublicKey( MainAssembly.GetPublicKey() ); //// byte[] token = an.GetPublicKeyToken(); //// //// int iLen = token.Length; //// StringBuilder publicKeyTok = new StringBuilder( iLen * 2 ); //// for(int i = 0; i < iLen; i++) //// publicKeyTok.Append( token[i].ToString( "x", CultureInfo.InvariantCulture ) ); //// satAssemName += ", PublicKeyToken=" + publicKeyTok; //// String cultureName = _neutralResourcesCulture.Name; //// if(cultureName.Length == 0) //// cultureName = ""; //// throw new MissingSatelliteAssemblyException( String.Format( CultureInfo.CurrentCulture, Environment.GetResourceString( "MissingSatelliteAssembly_Culture_Name" ), _neutralResourcesCulture, satAssemName ), cultureName ); //// } //// // Correct fileName for this satellite. //// fileName = GetResourceFileName( _neutralResourcesCulture ); //// } //// else //// satellite = MainAssembly; //// } //// else //// satellite = GetSatelliteAssembly( lookForCulture ); //// //// //// // Look for a possibly-NameSpace-qualified resource file, ie, //// // Microsoft.Name.myApp.en-US.resources. //// // (A null _locationInfo is legal) //// if(satellite != null) //// { //// // Handle case in here where someone added a callback //// // for assembly load events. While no other threads //// // have called into GetResourceSet, our own thread can! //// // At that point, we could already have an RS in our //// // hash table, and we don't want to add it twice. //// rs = (ResourceSet)localResourceSets[lookForCulture]; //// if(null != rs) //// { //// return rs; //// } //// //// // If we're looking in the main assembly AND if the main //// // assembly was the person who created the ResourceManager, //// // skip a security check for private manifest resources. //// bool canSkipSecurityCheck = MainAssembly == satellite && _callingAssembly == MainAssembly; //// stream = satellite.GetManifestResourceStream( _locationInfo, fileName, canSkipSecurityCheck, ref stackMark ); //// if(stream == null) //// stream = CaseInsensitiveManifestResourceStreamLookup( satellite, fileName ); //// } //// } //// else //// { // if !UseSatelliteAssembly //// satellite = MainAssembly; //// stream = MainAssembly.GetManifestResourceStream( _locationInfo, fileName, _callingAssembly == MainAssembly, ref stackMark ); //// } //// //// if(stream == null && tryParents) //// { //// // If we've hit top of the Culture tree, return. //// if(culture.Equals( CultureInfo.InvariantCulture )) //// { //// // Keep people from bothering me about resources problems //// if(MainAssembly == typeof( Object ).Assembly && BaseName.Equals( "mscorlib" )) //// { //// // This would break CultureInfo & all our exceptions. //// BCLDebug.Assert( false, "Couldn't get mscorlib" + ResFileExtension + " from mscorlib's assembly" + Environment.NewLine + Environment.NewLine + "Are you building the runtime on your machine? Chances are the BCL directory didn't build correctly. Type 'build -c' in the BCL directory. If you get build errors, look at buildd.log. If you then can't figure out what's wrong (and you aren't changing the assembly-related metadata code), ask a BCL dev.\n\nIf you did NOT build the runtime, you shouldn't be seeing this and you've found a bug." ); //// throw new ExecutionEngineException( "mscorlib" + ResFileExtension + " couldn't be found! Large parts of the BCL won't work!" ); //// } //// // We really don't think this should happen - we always //// // expect the neutral locale's resources to be present. //// String resName = String.Empty; //// if(_locationInfo != null && _locationInfo.Namespace != null) //// resName = _locationInfo.Namespace + Type.Delimiter; //// resName += fileName; //// throw new MissingManifestResourceException( Environment.GetResourceString( "MissingManifestResource_NoNeutralAsm", resName, MainAssembly.GetSimpleName() ) ); //// } //// //// CultureInfo parent = culture.Parent; //// //// // Recurse now. //// rs = InternalGetResourceSet( parent, createIfNotExists, tryParents ); //// if(rs != null) //// { //// AddResourceSet( localResourceSets, culture, ref rs ); //// } //// return rs; //// } //// } //UseManifest //// else //// { //// // Don't use Assembly manifest, but grovel on disk for a file. //// new System.Security.Permissions.FileIOPermission( System.Security.Permissions.PermissionState.Unrestricted ).Assert(); //// //// // Create new ResourceSet, if a file exists on disk for it. //// fileName = FindResourceFile( culture ); //// if(fileName == null) //// { //// if(tryParents) //// { //// // If we've hit top of the Culture tree, return. //// if(culture.Equals( CultureInfo.InvariantCulture )) //// { //// // We really don't think this should happen - we always //// // expect the neutral locale's resources to be present. //// //// throw new MissingManifestResourceException( Environment.GetResourceString( "MissingManifestResource_NoNeutralDisk" ) + Environment.NewLine + "baseName: " + BaseNameField + " locationInfo: " + (_locationInfo == null ? "" : _locationInfo.FullName) + " fileName: " + GetResourceFileName( culture ) ); //// } //// //// CultureInfo parent = culture.Parent; //// //// // Recurse now. //// rs = InternalGetResourceSet( parent, createIfNotExists, tryParents ); //// if(rs != null) //// { //// AddResourceSet( localResourceSets, culture, ref rs ); //// } //// return rs; //// } //// } //// else //// { //// rs = CreateResourceSet( fileName ); //// //// // To speed up ResourceSet lookups in the future, store this //// // culture with its parent culture's ResourceSet. //// if(rs != null) //// { //// AddResourceSet( localResourceSets, culture, ref rs ); //// } //// return rs; //// } //// } //// //// if(createIfNotExists && stream != null && rs == null) //// { //// rs = CreateResourceSet( stream, satellite ); //// AddResourceSet( localResourceSets, culture, ref rs ); //// } //// //// return rs; //// } //// //// // Simple helper to ease maintenance and improve readability. //// private static void AddResourceSet( Hashtable localResourceSets, CultureInfo culture, ref ResourceSet rs ) //// { //// // InternalGetResourceSet is both recursive and reentrant - //// // assembly load callbacks in particular are a way we can call //// // back into the ResourceManager in unexpectedly on the same thread. //// lock(localResourceSets) //// { //// // If another thread added this culture, return that. //// ResourceSet lostRace = (ResourceSet)localResourceSets[culture]; //// if(lostRace != null) //// { //// if(!Object.ReferenceEquals( lostRace, rs )) //// { //// rs.Dispose(); //// rs = lostRace; //// } //// } //// else //// { //// localResourceSets.Add( culture, rs ); //// } //// } //// } //// //// // Looks up a .resources file in the assembly manifest using //// // case-insensitive lookup rules. Yes, this is slow. The metadata //// // dev lead refuses to make all manifest blob lookups case-insensitive, //// // even optionally case-insensitive. //// private Stream CaseInsensitiveManifestResourceStreamLookup( Assembly satellite, String name ) //// { //// StringBuilder sb = new StringBuilder(); //// if(_locationInfo != null) //// { //// String nameSpace = _locationInfo.Namespace; //// if(nameSpace != null) //// { //// sb.Append( nameSpace ); //// if(name != null) //// sb.Append( Type.Delimiter ); //// } //// } //// sb.Append( name ); //// //// String givenName = sb.ToString(); //// CompareInfo comparer = CultureInfo.InvariantCulture.CompareInfo; //// String canonicalName = null; //// foreach(String existingName in satellite.GetManifestResourceNames()) //// { //// if(comparer.Compare( existingName, givenName, CompareOptions.IgnoreCase ) == 0) //// { //// if(canonicalName == null) //// canonicalName = existingName; //// else //// throw new MissingManifestResourceException( String.Format( CultureInfo.CurrentCulture, Environment.GetResourceString( "MissingManifestResource_MultipleBlobs" ), givenName, satellite.ToString() ) ); //// } //// } //// //// if(canonicalName == null) //// return null; //// // If we're looking in the main assembly AND if the main //// // assembly was the person who created the ResourceManager, //// // skip a security check for private manifest resources. //// bool canSkipSecurityCheck = MainAssembly == satellite && _callingAssembly == MainAssembly; //// StackCrawlMark stackMark = StackCrawlMark.LookForMyCaller; //// Stream s = satellite.GetManifestResourceStream( canonicalName, ref stackMark, canSkipSecurityCheck ); //// // GetManifestResourceStream will return null if we don't have //// // permission to read this stream from the assembly. For example, //// // if the stream is private and we're trying to access it from another //// // assembly (ie, ResMgr in mscorlib accessing anything else), we //// // require Reflection TypeInformation permission to be able to read //// // this. This meaning of private in satellite assemblies is a really //// // odd concept, and is orthogonal to the ResourceManager. //// // We should not assume we can skip this security check, //// // which means satellites must always use public manifest resources //// // if you want to support semi-trusted code. //// BCLDebug.Correctness( s != null, "Could not access the manifest resource from your satellite. Make " + canonicalName + " in assembly " + satellite.GetSimpleName() + " public." ); //// return s; //// } //// //// protected static Version GetSatelliteContractVersion( Assembly a ) //// { //// BCLDebug.Assert( a != null, "assembly != null" ); //// Object[] attrs = a.GetCustomAttributes( typeof( SatelliteContractVersionAttribute ), false ); //// if(attrs.Length == 0) //// return null; //// BCLDebug.Assert( attrs.Length == 1, "Cannot have multiple instances of SatelliteContractVersionAttribute on an assembly!" ); //// String v = ((SatelliteContractVersionAttribute)attrs[0]).Version; //// Version ver; //// try //// { //// ver = new Version( v ); //// } //// catch(Exception e) //// { //// // Note we are prone to hitting infinite loops if mscorlib's //// // SatelliteContractVersionAttribute contains bogus values. //// // If this assert fires, please fix the build process for the //// // BCL directory. //// if(a == typeof( Object ).Assembly) //// { //// BCLDebug.Assert( false, "mscorlib's SatelliteContractVersionAttribute is a malformed version string!" ); //// return null; //// } //// //// throw new ArgumentException( String.Format( CultureInfo.CurrentCulture, Environment.GetResourceString( "Arg_InvalidSatelliteContract_Asm_Ver" ), a.ToString(), v ), e ); //// } //// return ver; //// } //// //// protected static CultureInfo GetNeutralResourcesLanguage( Assembly a ) //// { //// // This method should be obsolete - replace it with the one below. //// // Unfortunately, we made it protected. //// UltimateResourceFallbackLocation ignoringUsefulData = UltimateResourceFallbackLocation.MainAssembly; //// CultureInfo culture = GetNeutralResourcesLanguage( a, ref ignoringUsefulData ); //// return culture; //// } //// //// private static CultureInfo GetNeutralResourcesLanguage( Assembly a, ref UltimateResourceFallbackLocation fallbackLocation ) //// { //// BCLDebug.Assert( a != null, "assembly != null" ); //// //// IList attrs = CustomAttributeData.GetCustomAttributes( a ); //// CustomAttributeData attr = null; //// for(int i = 0; i < attrs.Count; i++) //// { //// if(attrs[i].Constructor.DeclaringType == typeof( NeutralResourcesLanguageAttribute )) //// { //// attr = attrs[i]; //// break; //// } //// } //// //// if(attr == null) //// { //// BCLDebug.Perf( false, "Consider adding NeutralResourcesLanguageAttribute to assembly " + a.FullName ); //// fallbackLocation = UltimateResourceFallbackLocation.MainAssembly; //// return CultureInfo.InvariantCulture; //// } //// //// string cultureName = null; //// if(attr.Constructor.GetParameters().Length == 2) //// { //// fallbackLocation = (UltimateResourceFallbackLocation)attr.ConstructorArguments[1].Value; //// if(fallbackLocation < UltimateResourceFallbackLocation.MainAssembly || fallbackLocation > UltimateResourceFallbackLocation.Satellite) //// throw new ArgumentException( Environment.GetResourceString( "Arg_InvalidNeutralResourcesLanguage_FallbackLoc", fallbackLocation ) ); //// } //// else //// fallbackLocation = UltimateResourceFallbackLocation.MainAssembly; //// //// cultureName = attr.ConstructorArguments[0].Value as string; //// //// try //// { //// CultureInfo c = CultureInfo.GetCultureInfo( cultureName ); //// return c; //// } //// catch(ArgumentException e) //// { // we should catch ArgumentException only. //// // Note we could go into infinite loops if mscorlib's //// // NeutralResourcesLanguageAttribute is mangled. If this assert //// // fires, please fix the build process for the BCL directory. //// if(a == typeof( Object ).Assembly) //// { //// BCLDebug.Assert( false, "mscorlib's NeutralResourcesLanguageAttribute is a malformed culture name! name: \"" + cultureName + "\" Exception: " + e ); //// return CultureInfo.InvariantCulture; //// } //// //// throw new ArgumentException( String.Format( CultureInfo.CurrentCulture, Environment.GetResourceString( "Arg_InvalidNeutralResourcesLanguage_Asm_Culture" ), a.ToString(), cultureName ), e ); //// } //// } //// //// private Assembly GetSatelliteAssembly( CultureInfo lookForCulture ) //// { //// if(!_lookedForSatelliteContractVersion) //// { //// _satelliteContractVersion = GetSatelliteContractVersion( MainAssembly ); //// _lookedForSatelliteContractVersion = true; //// } //// //// Assembly satellite = null; //// //// // Look up the satellite assembly, but don't let problems //// // like a partially signed satellite assembly stop us from //// // doing fallback and displaying something to the user. //// // Yet also somehow log this error for a developer. //// try //// { //// satellite = MainAssembly.InternalGetSatelliteAssembly( lookForCulture, _satelliteContractVersion, false ); //// } //// //// // Don't throw for FUSION_E_REFDEFMISMATCH, for compat with MOM, which may cause assembly w/ incorrect culture to be found //// // @todo: seems that we would want to rethrow for all other cases... //// catch(FileLoadException fle) //// { //// // Ignore cases where the loader gets an access //// // denied back from the OS. This showed up for //// // href-run exe's at one point. //// int hr = Marshal.GetHRForException( fle ); //// if(hr != Win32Native.MakeHRFromErrorCode( Win32Native.ERROR_ACCESS_DENIED )) //// { //// BCLDebug.Assert( false, "[This is an ignorable assert to catch satellite assembly build problems - talk to your build lab & loc engineer]" + Environment.NewLine + "GetSatelliteAssembly failed for culture " + lookForCulture.Name + " and version " + (_satelliteContractVersion == null ? MainAssembly.GetVersion().ToString() : _satelliteContractVersion.ToString()) + " of assembly " + MainAssembly.GetSimpleName() + " with error code 0x" + hr.ToString( "X", CultureInfo.InvariantCulture ) + "\r\nException: " + fle ); //// } //// } //// //// // Don't throw for zero-length satellite assemblies, for compat with v1 //// catch(BadImageFormatException bife) //// { //// BCLDebug.Assert( false, "[This is an ignorable assert to catch satellite assembly build problems - talk to your build lab & loc engineer]" + Environment.NewLine + "GetSatelliteAssembly failed for culture " + lookForCulture.Name + " and version " + (_satelliteContractVersion == null ? MainAssembly.GetVersion().ToString() : _satelliteContractVersion.ToString()) + " of assembly " + MainAssembly.GetSimpleName() + "\r\nException: " + bife ); //// } //// //// return satellite; //// } //// //// // Constructs a new ResourceSet for a given file name. The logic in //// // here avoids a ReflectionPermission check for our RuntimeResourceSet //// // for perf and working set reasons. //// [ResourceExposure( ResourceScope.Machine )] //// [ResourceConsumption( ResourceScope.Machine )] //// private ResourceSet CreateResourceSet( String file ) //// { //// if(_userResourceSet == null) //// { //// // Explicitly avoid CreateInstance if possible, because it //// // requires ReflectionPermission to call private & protected //// // constructors. //// return new RuntimeResourceSet( file ); //// } //// else //// { //// Object[] args = new Object[1]; //// args[0] = file; //// try //// { //// return (ResourceSet)Activator.CreateInstance( _userResourceSet, args ); //// } //// catch(MissingMethodException e) //// { //// throw new InvalidOperationException( String.Format( CultureInfo.CurrentCulture, Environment.GetResourceString( "InvalidOperation_ResMgrBadResSet_Type" ), _userResourceSet.AssemblyQualifiedName ), e ); //// } //// } //// } //// //// // Constructs a new ResourceSet for a given file name. The logic in //// // here avoids a ReflectionPermission check for our RuntimeResourceSet //// // for perf and working set reasons. //// // Use the assembly to resolve assembly manifest resource references. //// // Note that is can be null, but probably shouldn't be. //// private ResourceSet CreateResourceSet( Stream store, Assembly assembly ) //// { //// BCLDebug.Assert( store != null, "I need a Stream!" ); //// // Check to see if this is a Stream the ResourceManager understands, //// // and check for the correct resource reader type. //// if(store.CanSeek && store.Length > 4) //// { //// long startPos = store.Position; //// BinaryReader br = new BinaryReader( store ); //// // Look for our magic number as a little endian Int32. //// int bytes = br.ReadInt32(); //// if(bytes == MagicNumber) //// { //// int resMgrHeaderVersion = br.ReadInt32(); //// String readerTypeName = null, resSetTypeName = null; //// if(resMgrHeaderVersion == HeaderVersionNumber) //// { //// br.ReadInt32(); // We don't want the number of bytes to skip. //// readerTypeName = br.ReadString(); //// resSetTypeName = br.ReadString(); //// } //// else if(resMgrHeaderVersion > HeaderVersionNumber) //// { //// // Assume that the future ResourceManager headers will //// // have two strings for us - the reader type name and //// // resource set type name. Read those, then use the num //// // bytes to skip field to correct our position. //// int numBytesToSkip = br.ReadInt32(); //// long endPosition = br.BaseStream.Position + numBytesToSkip; //// //// readerTypeName = br.ReadString(); //// resSetTypeName = br.ReadString(); //// //// br.BaseStream.Seek( endPosition, SeekOrigin.Begin ); //// } //// else //// { //// // resMgrHeaderVersion is older than this ResMgr version. //// // We should add in backwards compatibility support here. //// //// throw new NotSupportedException( Environment.GetResourceString( "NotSupported_ObsoleteResourcesFile", MainAssembly.GetSimpleName() ) ); //// } //// //// store.Position = startPos; //// // Perf optimization - Don't use Reflection for our defaults. //// // Note there are two different sets of strings here - the //// // assembly qualified strings emitted by ResourceWriter, and //// // the abbreviated ones emitted by InternalResGen. //// if(CanUseDefaultResourceClasses( readerTypeName, resSetTypeName )) //// { //// RuntimeResourceSet rs; //// rs = new RuntimeResourceSet( store ); //// return rs; //// } //// else //// { //// // we do not want to use partial binding here. //// Type readerType = Type.GetType( readerTypeName, true ); //// Object[] args = new Object[1]; //// args[0] = store; //// IResourceReader reader = (IResourceReader)Activator.CreateInstance( readerType, args ); //// //// Object[] resourceSetArgs = new Object[1]; //// resourceSetArgs[0] = reader; //// Type resSetType; //// if(_userResourceSet == null) //// { //// BCLDebug.Assert( resSetTypeName != null, "We should have a ResourceSet type name from the custom resource file here." ); //// resSetType = Type.GetType( resSetTypeName, true, false ); //// } //// else //// resSetType = _userResourceSet; //// ResourceSet rs = (ResourceSet)Activator.CreateInstance( resSetType, //// BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.CreateInstance, //// null, //// resourceSetArgs, //// null, //// null ); //// return rs; //// } //// } //// else //// store.Position = startPos; //// } //// //// if(_userResourceSet == null) //// { //// // Explicitly avoid CreateInstance if possible, because it //// // requires ReflectionPermission to call private & protected //// // constructors. //// return new RuntimeResourceSet( store ); //// } //// else //// { //// Object[] args = new Object[2]; //// args[0] = store; //// args[1] = assembly; //// try //// { //// ResourceSet rs = null; //// // Add in a check for a constructor taking in an assembly first. //// try //// { //// rs = (ResourceSet)Activator.CreateInstance( _userResourceSet, args ); //// return rs; //// } //// catch(MissingMethodException) { } //// //// args = new Object[1]; //// args[0] = store; //// rs = (ResourceSet)Activator.CreateInstance( _userResourceSet, args ); //// return rs; //// } //// catch(MissingMethodException e) //// { //// throw new InvalidOperationException( String.Format( CultureInfo.CurrentCulture, Environment.GetResourceString( "InvalidOperation_ResMgrBadResSet_Type" ), _userResourceSet.AssemblyQualifiedName ), e ); //// } //// } //// } //// //// // Perf optimization - Don't use Reflection for most cases with //// // our .resources files. This makes our code run faster and we can //// // creating a ResourceReader via Reflection. This would incur //// // a security check (since the link-time check on the constructor that //// // takes a String is turned into a full demand with a stack walk) //// // and causes partially trusted localized apps to fail. //// private bool CanUseDefaultResourceClasses( String readerTypeName, String resSetTypeName ) //// { //// if(_userResourceSet != null) //// return false; //// //// // Ignore the actual version of the ResourceReader and //// // RuntimeResourceSet classes. Let those classes deal with //// // versioning themselves. //// AssemblyName mscorlib = new AssemblyName( MscorlibName ); //// //// if(readerTypeName != null) //// { //// if(!CompareNames( readerTypeName, ResReaderTypeName, mscorlib )) //// return false; //// } //// //// if(resSetTypeName != null) //// { //// if(!CompareNames( resSetTypeName, ResSetTypeName, mscorlib )) //// return false; //// } //// //// return true; //// } //// //// //// // IGNORES VERSION //// internal static bool CompareNames( String asmTypeName1, //// String typeName2, //// AssemblyName asmName2 ) //// { //// BCLDebug.Assert( asmTypeName1 != null, "asmTypeName1 was unexpectedly null" ); //// //// // First, compare type names //// int comma = asmTypeName1.IndexOf( ',' ); //// if(((comma == -1) ? asmTypeName1.Length : comma) != typeName2.Length) //// return false; //// //// // case sensitive //// if(String.Compare( asmTypeName1, 0, typeName2, 0, typeName2.Length, StringComparison.Ordinal ) != 0) //// return false; //// if(comma == -1) //// return true; //// //// // Now, compare assembly display names (IGNORES VERSION AND PROCESSORARCHITECTURE) //// while(Char.IsWhiteSpace( asmTypeName1[++comma] )) ; //// //// // case insensitive //// AssemblyName an1 = new AssemblyName( asmTypeName1.Substring( comma ) ); //// if(String.Compare( an1.Name, asmName2.Name, StringComparison.OrdinalIgnoreCase ) != 0) //// return false; //// //// if((an1.CultureInfo != null) && (asmName2.CultureInfo != null) && //// (an1.CultureInfo.LCID != asmName2.CultureInfo.LCID)) //// return false; //// //// byte[] pkt1 = an1.GetPublicKeyToken(); //// byte[] pkt2 = asmName2.GetPublicKeyToken(); //// if((pkt1 != null) && (pkt2 != null)) //// { //// if(pkt1.Length != pkt2.Length) //// return false; //// //// for(int i = 0; i < pkt1.Length; i++) //// { //// if(pkt1[i] != pkt2[i]) //// return false; //// } //// } //// //// return true; //// } // Looks up a resource value for a particular name. Looks in the // current thread's CultureInfo, and if not found, all parent CultureInfos. // Returns null if the resource wasn't found. // public virtual String GetString( String name ) { return GetString( name, (CultureInfo)null ); } // Looks up a resource value for a particular name. Looks in the // specified CultureInfo, and if not found, all parent CultureInfos. // Returns null if the resource wasn't found. // [MethodImpl( MethodImplOptions.InternalCall )] public virtual extern String GetString( String name, CultureInfo culture ); //// { //// if(null == name) //// throw new ArgumentNullException( "name" ); //// if(null == culture) //// { //// culture = CultureInfo.CurrentUICulture; //// } //// //// ResourceSet rs = InternalGetResourceSet( culture, true, true ); //// //// if(rs != null) //// { //// String value = rs.GetString( name, _ignoreCase ); //// if(value != null) //// return value; //// } //// //// // This is the CultureInfo hierarchy traversal code for resource //// // lookups, similar but necessarily orthogonal to the ResourceSet //// // lookup logic. //// ResourceSet last = null; //// while(!culture.Equals( CultureInfo.InvariantCulture ) && !culture.Equals( _neutralResourcesCulture )) //// { //// culture = culture.Parent; //// //// rs = InternalGetResourceSet( culture, true, true ); //// if(rs == null) //// break; //// if(rs != last) //// { //// String value = rs.GetString( name, _ignoreCase ); //// if(value != null) //// return value; //// last = rs; //// } //// } //// return null; //// } // Looks up a resource value for a particular name. Looks in the // current thread's CultureInfo, and if not found, all parent CultureInfos. // Returns null if the resource wasn't found. // public virtual Object GetObject( String name ) { return GetObject( name, (CultureInfo)null, true ); } // Looks up a resource value for a particular name. Looks in the // specified CultureInfo, and if not found, all parent CultureInfos. // Returns null if the resource wasn't found. // public virtual Object GetObject( String name, CultureInfo culture ) { return GetObject( name, culture, true ); } [MethodImpl( MethodImplOptions.InternalCall )] private extern Object GetObject( String name, CultureInfo culture, bool wrapUnmanagedMemStream ); //// { //// if(null == name) //// throw new ArgumentNullException( "name" ); //// if(null == culture) //// { //// culture = CultureInfo.CurrentUICulture; //// } //// //// ResourceSet rs = InternalGetResourceSet( culture, true, true ); //// //// if(rs != null) //// { //// Object value = rs.GetObject( name, _ignoreCase ); //// if(value != null) //// { //// UnmanagedMemoryStream stream = value as UnmanagedMemoryStream; //// if(stream != null && wrapUnmanagedMemStream) //// return new UnmanagedMemoryStreamWrapper( stream ); //// else //// return value; //// } //// } //// //// // This is the CultureInfo hierarchy traversal code for resource //// // lookups, similar but necessarily orthogonal to the ResourceSet //// // lookup logic. //// ResourceSet last = null; //// while(!culture.Equals( CultureInfo.InvariantCulture ) && !culture.Equals( _neutralResourcesCulture )) //// { //// culture = culture.Parent; //// rs = InternalGetResourceSet( culture, true, true ); //// if(rs == null) //// break; //// if(rs != last) //// { //// Object value = rs.GetObject( name, _ignoreCase ); //// if(value != null) //// { //// UnmanagedMemoryStream stream = value as UnmanagedMemoryStream; //// if(stream != null && wrapUnmanagedMemStream) //// return new UnmanagedMemoryStreamWrapper( stream ); //// else //// return value; //// } //// last = rs; //// } //// } //// return null; //// } //// //// [CLSCompliant( false )] //// public UnmanagedMemoryStream GetStream( String name ) //// { //// return GetStream( name, (CultureInfo)null ); //// } //// //// [CLSCompliant( false )] //// public UnmanagedMemoryStream GetStream( String name, CultureInfo culture ) //// { //// Object obj = GetObject( name, culture, false ); //// UnmanagedMemoryStream ums = obj as UnmanagedMemoryStream; //// if(ums == null && obj != null) //// throw new InvalidOperationException( Environment.GetResourceString( "InvalidOperation_ResourceNotStream_Name", name ) ); //// return ums; //// } } } ================================================ FILE: Zelig/Zelig/RunTime/Framework/mscorlib/System/Runtime/CompilerServices/AsyncStateMachineAttribute.cs ================================================ namespace System.Runtime.CompilerServices { [Serializable] [AttributeUsage(AttributeTargets.Method, Inherited = false, AllowMultiple = false)] public sealed class AsyncStateMachineAttribute : StateMachineAttribute { public AsyncStateMachineAttribute(Type stateMachineType) : base(stateMachineType) { } } } ================================================ FILE: Zelig/Zelig/RunTime/Framework/mscorlib/System/Runtime/CompilerServices/AsyncTaskMethodBuilder.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // // =+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+ // Compiler-targeted types that build tasks for use as the return types of asynchronous methods. // =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=- // In the desktop and phone CLR, the system caches lightweight tasks for common default values to reduce allocation // overhead. In the future, we may want to enable limited caching if performance/memory analysis indicates that it would // be beneficial. For now, we're generating these results on demand to limit static memory overhead. //#define ENABLE_CACHED_TASKS using System; using System.Diagnostics; using System.Diagnostics.Contracts; using System.Security; using System.Threading; using System.Threading.Tasks; namespace System.Runtime.CompilerServices { ///

/// Provides a builder for asynchronous methods that return void. /// This type is intended for compiler use only. /// ////[HostProtection(Synchronization = true, ExternalThreading = true)] public struct AsyncVoidMethodBuilder { /// State related to the IAsyncStateMachine. private AsyncMethodBuilderCore m_coreState; // mutable struct: must not be readonly /// Task used for debugging and logging purposes only. Lazily initialized. private Task m_task; /// Initializes a new . /// The initialized . public static AsyncVoidMethodBuilder Create() { return new AsyncVoidMethodBuilder(); } /// Initiates the builder's execution with the associated state machine. /// Specifies the type of the state machine. /// The state machine instance, passed by reference. /// The argument was null (Nothing in Visual Basic). [SecuritySafeCritical] [DebuggerStepThrough] public void Start(ref TStateMachine stateMachine) where TStateMachine : IAsyncStateMachine { AsyncMethodBuilderCore.Start(stateMachine); } /// Associates the builder with the state machine it represents. /// The heap-allocated state machine object. /// The argument was null (Nothing in Visual Basic). /// The builder is incorrectly initialized. public void SetStateMachine(IAsyncStateMachine stateMachine) { m_coreState.SetStateMachine(stateMachine); // argument validation handled by AsyncMethodBuilderCore } /// /// Schedules the specified state machine to be pushed forward when the specified awaiter completes. /// /// Specifies the type of the awaiter. /// Specifies the type of the state machine. /// The awaiter. /// The state machine. public void AwaitOnCompleted(ref TAwaiter awaiter, ref TStateMachine stateMachine) where TAwaiter : INotifyCompletion where TStateMachine : IAsyncStateMachine { try { awaiter.OnCompleted(m_coreState.GetCompletionAction(stateMachine)); } catch (Exception exc) { // Prevent exceptions from leaking to the call site, which could then allow multiple flows of execution // through the same async method if the awaiter had already scheduled the continuation by the time the // exception was thrown. We propagate the exception on the ThreadPool because we can trust it to not // throw, unlike if we were to go to a user-supplied SynchronizationContext, whose Post method could // easily throw. AsyncMethodBuilderCore.ThrowAsync(exc); } } /// /// Schedules the specified state machine to be pushed forward when the specified awaiter completes. /// /// Specifies the type of the awaiter. /// Specifies the type of the state machine. /// The awaiter. /// The state machine. [SecuritySafeCritical] public void AwaitUnsafeOnCompleted(ref TAwaiter awaiter, ref TStateMachine stateMachine) where TAwaiter : ICriticalNotifyCompletion where TStateMachine : IAsyncStateMachine { try { awaiter.UnsafeOnCompleted(m_coreState.GetCompletionAction(stateMachine)); } catch (Exception e) { AsyncMethodBuilderCore.ThrowAsync(e); } } /// Completes the method builder successfully. public void SetResult() { } /// Faults the method builder with an exception. /// The exception that is the cause of this fault. /// The argument is null (Nothing in Visual Basic). /// The builder is not initialized. public void SetException(Exception exception) { if (exception == null) { throw new ArgumentNullException(nameof(exception)); } #if ENABLE_CONTRACTS Contract.EndContractBlock(); #endif // ENABLE_CONTRACTS // Otherwise, queue the exception to be thrown on the ThreadPool. AsyncMethodBuilderCore.ThrowAsync(exception); } // This property lazily instantiates the Task in a non-thread-safe manner. private Task Task { get { if (m_task == null) { m_task = new Task(); } return m_task; } } } /// /// Provides a builder for asynchronous methods that return . /// This type is intended for compiler use only. /// /// /// AsyncTaskMethodBuilder is a value type, and thus it is copied by value. /// Prior to being copied, one of its Task, SetResult, or SetException members must be accessed, /// or else the copies may end up building distinct Task instances. /// ////[HostProtection(Synchronization = true, ExternalThreading = true)] public struct AsyncTaskMethodBuilder { #if ENABLE_CACHED_TASKS // We cache VoidTaskResult regardless of our overall cache policy, since it's extremely common. /// A cached VoidTaskResult task used for builders that complete synchronously. private readonly static Task s_cachedCompleted = AsyncTaskMethodBuilder.s_defaultResultTask; #else // ENABLE_CACHED_TASKS /// A cached VoidTaskResult task used for builders that complete synchronously. private readonly static Task s_cachedCompleted = new Task(default(VoidTaskResult)); #endif // ENABLE_CACHED_TASKS /// The generic builder object to which this non-generic instance delegates. private AsyncTaskMethodBuilder m_builder; // mutable struct: must not be readonly /// Initializes a new . /// The initialized . public static AsyncTaskMethodBuilder Create() { return default(AsyncTaskMethodBuilder); // Note: If ATMB.Create is modified to do any initialization, this // method needs to be updated to do m_builder = ATMB.Create(). } /// Initiates the builder's execution with the associated state machine. /// Specifies the type of the state machine. /// The state machine instance, passed by reference. [SecuritySafeCritical] [DebuggerStepThrough] public void Start(ref TStateMachine stateMachine) where TStateMachine : IAsyncStateMachine { AsyncMethodBuilderCore.Start(stateMachine); } /// Associates the builder with the state machine it represents. /// The heap-allocated state machine object. /// The argument was null (Nothing in Visual Basic). /// The builder is incorrectly initialized. public void SetStateMachine(IAsyncStateMachine stateMachine) { m_builder.SetStateMachine(stateMachine); // argument validation handled by AsyncMethodBuilderCore } /// /// Schedules the specified state machine to be pushed forward when the specified awaiter completes. /// /// Specifies the type of the awaiter. /// Specifies the type of the state machine. /// The awaiter. /// The state machine. public void AwaitOnCompleted( ref TAwaiter awaiter, ref TStateMachine stateMachine) where TAwaiter : INotifyCompletion where TStateMachine : IAsyncStateMachine { m_builder.AwaitOnCompleted(ref awaiter, ref stateMachine); } /// /// Schedules the specified state machine to be pushed forward when the specified awaiter completes. /// /// Specifies the type of the awaiter. /// Specifies the type of the state machine. /// The awaiter. /// The state machine. public void AwaitUnsafeOnCompleted( ref TAwaiter awaiter, ref TStateMachine stateMachine) where TAwaiter : ICriticalNotifyCompletion where TStateMachine : IAsyncStateMachine { m_builder.AwaitUnsafeOnCompleted(ref awaiter, ref stateMachine); } /// Gets the for this builder. /// The representing the builder's asynchronous operation. /// The builder is not initialized. public Task Task => m_builder.Task; /// /// Completes the in the /// RanToCompletion state. /// /// The builder is not initialized. /// The task has already completed. public void SetResult() { // Accessing AsyncTaskMethodBuilder.s_cachedCompleted is faster than // accessing AsyncTaskMethodBuilder.s_defaultResultTask. m_builder.SetResult(s_cachedCompleted); } /// /// Completes the in the /// Faulted state with the specified exception. /// /// The to use to fault the task. /// The argument is null (Nothing in Visual Basic). /// The builder is not initialized. /// The task has already completed. public void SetException(Exception exception) { #if DISABLED_FOR_LLILUM m_builder.SetException(exception); #else // DISABLED_FOR_LLILUM // We don't yet enable catching of exceptions, so this path should never run. throw new NotImplementedException(); #endif // DISABLED_FOR_LLILUM } } /// /// Provides a builder for asynchronous methods that return . /// This type is intended for compiler use only. /// /// /// AsyncTaskMethodBuilder{TResult} is a value type, and thus it is copied by value. /// Prior to being copied, one of its Task, SetResult, or SetException members must be accessed, /// or else the copies may end up building distinct Task instances. /// ////[HostProtection(Synchronization = true, ExternalThreading = true)] public struct AsyncTaskMethodBuilder { #if ENABLE_CACHED_TASKS /// A cached task for default(TResult). internal readonly static Task s_defaultResultTask = AsyncTaskCache.CreateCacheableTask(default(TResult)); #endif // ENABLE_CACHED_TASKS private static readonly string s_transitionToFinalAlreadyCompleted = "An attempt was made to transition a task to a final state when it had already completed."; // WARNING: For performance reasons, the m_task field is lazily initialized. // For correct results, the struct AsyncTaskMethodBuilder must // always be used from the same location/copy, at least until m_task is // initialized. If that guarantee is broken, the field could end up being // initialized on the wrong copy. /// State related to the IAsyncStateMachine. private AsyncMethodBuilderCore m_coreState; // mutable struct: must not be readonly /// The lazily-initialized built task. private Task m_task; // lazily-initialized: must not be readonly /// Initializes a new . /// The initialized . public static AsyncTaskMethodBuilder Create() { return default(AsyncTaskMethodBuilder); // NOTE: If this method is ever updated to perform more initialization, // ATMB.Create must also be updated to call this Create method. } /// Initiates the builder's execution with the associated state machine. /// Specifies the type of the state machine. /// The state machine instance, passed by reference. [SecuritySafeCritical] [DebuggerStepThrough] public void Start(ref TStateMachine stateMachine) where TStateMachine : IAsyncStateMachine { AsyncMethodBuilderCore.Start(stateMachine); } /// Associates the builder with the state machine it represents. /// The heap-allocated state machine object. /// The argument was null (Nothing in Visual Basic). /// The builder is incorrectly initialized. public void SetStateMachine(IAsyncStateMachine stateMachine) { m_coreState.SetStateMachine(stateMachine); // argument validation handled by AsyncMethodBuilderCore } /// /// Schedules the specified state machine to be pushed forward when the specified awaiter completes. /// /// Specifies the type of the awaiter. /// Specifies the type of the state machine. /// The awaiter. /// The state machine. public void AwaitOnCompleted(ref TAwaiter awaiter, ref TStateMachine stateMachine) where TAwaiter : INotifyCompletion where TStateMachine : IAsyncStateMachine { try { awaiter.OnCompleted(m_coreState.GetCompletionAction(stateMachine)); } catch (Exception e) { AsyncMethodBuilderCore.ThrowAsync(e); } } /// /// Schedules the specified state machine to be pushed forward when the specified awaiter completes. /// /// Specifies the type of the awaiter. /// Specifies the type of the state machine. /// The awaiter. /// The state machine. [SecuritySafeCritical] public void AwaitUnsafeOnCompleted(ref TAwaiter awaiter, ref TStateMachine stateMachine) where TAwaiter : ICriticalNotifyCompletion where TStateMachine : IAsyncStateMachine { try { awaiter.UnsafeOnCompleted(m_coreState.GetCompletionAction(stateMachine)); } catch (Exception e) { AsyncMethodBuilderCore.ThrowAsync(e); } } /// Gets the for this builder. /// The representing the builder's asynchronous operation. public Task Task { get { // Get and return the task. If there isn't one, first create one and store it. if (m_task == null) { m_task = new Task(); } return m_task; } } /// /// Completes the in the /// RanToCompletion state with the specified result. /// /// The result to use to complete the task. /// The task has already completed. public void SetResult(TResult result) { // Get the currently stored task, which will be non-null if get_Task has already been accessed. // If there isn't one, get a task and store it. var task = m_task; if (task == null) { m_task = GetTaskForResult(result); #if ENABLE_CONTRACTS Contract.Assert(m_task != null, "GetTaskForResult should never return null"); #endif // ENABLE_CONTRACTS } // Slow path: complete the existing task. else if (!task.TrySetResult(result)) { throw new InvalidOperationException(s_transitionToFinalAlreadyCompleted); } } /// /// Completes the builder by using either the supplied completed task, or by completing /// the builder's previously accessed task using default(TResult). /// /// A task already completed with the value default(TResult). /// The task has already completed. internal void SetResult(Task completedTask) { #if ENABLE_CONTRACTS Contract.Requires(completedTask != null, "Expected non-null task"); Contract.Requires(completedTask.Status == TaskStatus.RanToCompletion, "Expected a successfully completed task"); #endif // ENABLE_CONTRACTS // Get the currently stored task, which will be non-null if get_Task has already been accessed. // If there isn't one, store the supplied completed task. var task = m_task; if (task == null) { m_task = completedTask; } else { // Otherwise, complete the task that's there. SetResult(default(TResult)); } } /// /// Completes the in the /// Faulted state with the specified exception. /// /// The to use to fault the task. /// The argument is null (Nothing in Visual Basic). /// The task has already completed. public void SetException(Exception exception) { if (exception == null) { throw new ArgumentNullException(nameof(exception)); } #if ENABLE_CONTRACTS Contract.EndContractBlock(); #endif // ENABLE_CONTRACTS #if DISABLED_FOR_LLILUM var task = m_task; if (task == null) { // Get the task, forcing initialization if it hasn't already been initialized. task = this.Task; } // If the exception represents cancellation, cancel the task. Otherwise, fault the task. var oce = exception as OperationCanceledException; bool successfullySet = oce != null ? task.TrySetCanceled(oce.CancellationToken, oce) : task.TrySetException(exception); // Unlike with TaskCompletionSource, we do not need to spin here until m_task is completed, // since AsyncTaskMethodBuilder.SetException should not be immediately followed by any code // that depends on the task having completely completed. Moreover, with correct usage, // SetResult or SetException should only be called once, so the Try* methods should always // return true, so no spinning would be necessary anyway (the spinning in TCS is only relevant // if another thread completes the task first). if (!successfullySet) { throw new InvalidOperationException(s_transitionToFinalAlreadyCompleted); } #else // DISABLED_FOR_LLILUM throw new NotImplementedException(); #endif // DISABLED_FOR_LLILUM } /// /// Gets a task for the specified result. This will either /// be a cached or new task, never null. /// /// The result for which we need a task. /// The completed task containing the result. [SecuritySafeCritical] // for JitHelpers.UnsafeCast private Task GetTaskForResult(TResult result) { #if ENABLE_CONTRACTS Contract.Ensures( EqualityComparer.Default.Equals(result, Contract.Result>().Result), "The returned task's Result must return the same value as the specified result value."); #endif // ENABLE_CONTRACTS #if ENABLE_CACHED_TASKS // The goal of this function is to give back a cached task if possible, or to otherwise give back a new task. // To give back a cached task, we need to be able to evaluate the incoming result value, and we need to // avoid as much overhead as possible when doing so, as this function is invoked as part of the return path // from every async method. Most tasks won't be cached, and thus we need the checks for those that are to be // as close to free as possible. This requires some trickiness given the lack of generic specialization. // Note: For ahead-of-time compilation, this is far less sensitive than the CoreCLR version. We have // therefore simplified it to remove special JIT-related optimizations. // Avoid value-type branches for ref types. if (null != default(TResult)) { Task defaultTask; AsyncTaskCache.GetCachedTask(result, out defaultTask); if (defaultTask != null) { return defaultTask; } } else if (result == null) // optimized away for value types { return s_defaultResultTask; } #endif // ENABLE_CACHED_TASKS // No cached task is available. Manufacture a new one for this result. return new Task(result); } } #if ENABLE_CACHED_TASKS /// Provides a cache of closed generic tasks for async methods. internal static class AsyncTaskCache { // All static members are initialized inline to ensure type is beforefieldinit /// A cached Task{Boolean}.Result == true. internal readonly static Task TrueTask = CreateCacheableTask(true); /// A cached Task{Boolean}.Result == false. internal readonly static Task FalseTask = CreateCacheableTask(false); // Tasks for defaults of various known value types. internal readonly static Task ByteTask = CreateCacheableTask(default(Byte)); internal readonly static Task SByteTask = CreateCacheableTask(default(SByte)); internal readonly static Task CharTask = CreateCacheableTask(default(Char)); internal readonly static Task Int16Task = CreateCacheableTask(default(Int16)); internal readonly static Task UInt16Task = CreateCacheableTask(default(UInt16)); internal readonly static Task Int32Task = CreateCacheableTask(default(Int32)); internal readonly static Task UInt32Task = CreateCacheableTask(default(UInt32)); internal readonly static Task Int64Task = CreateCacheableTask(default(Int64)); internal readonly static Task UInt64Task = CreateCacheableTask(default(UInt64)); internal readonly static Task IntPtrTask = CreateCacheableTask(default(IntPtr)); internal readonly static Task UIntPtrTask = CreateCacheableTask(default(UIntPtr)); // Generic default task accessors for the known value types. internal static void GetCachedTask(bool value, out Task task) { task = value ? TrueTask : FalseTask; } internal static void GetCachedTask(Byte value, out Task task) { task = (value == default(Byte)) ? AsyncTaskMethodBuilder.s_defaultResultTask : null; } internal static void GetCachedTask(SByte value, out Task task) { task = (value == default(SByte)) ? AsyncTaskMethodBuilder.s_defaultResultTask : null; } internal static void GetCachedTask(Char value, out Task task) { task = (value == default(Char)) ? AsyncTaskMethodBuilder.s_defaultResultTask : null; } internal static void GetCachedTask(Int16 value, out Task task) { task = (value == default(Int16)) ? AsyncTaskMethodBuilder.s_defaultResultTask : null; } internal static void GetCachedTask(UInt16 value, out Task task) { task = (value == default(UInt16)) ? AsyncTaskMethodBuilder.s_defaultResultTask : null; } internal static void GetCachedTask(Int32 value, out Task task) { task = (value == default(Int32)) ? AsyncTaskMethodBuilder.s_defaultResultTask : null; } internal static void GetCachedTask(UInt32 value, out Task task) { task = (value == default(UInt32)) ? AsyncTaskMethodBuilder.s_defaultResultTask : null; } internal static void GetCachedTask(Int64 value, out Task task) { task = (value == default(Int64)) ? AsyncTaskMethodBuilder.s_defaultResultTask : null; } internal static void GetCachedTask(UInt64 value, out Task task) { task = (value == default(UInt64)) ? AsyncTaskMethodBuilder.s_defaultResultTask : null; } internal static void GetCachedTask(IntPtr value, out Task task) { task = (value == default(IntPtr)) ? AsyncTaskMethodBuilder.s_defaultResultTask : null; } internal static void GetCachedTask(UIntPtr value, out Task task) { task = (value == default(UIntPtr)) ? AsyncTaskMethodBuilder.s_defaultResultTask : null; } internal static void GetCachedTask(TResult value, out Task task) { task = null; } /// Creates a non-disposable task. /// Specifies the result type. /// The result for the task. /// The cacheable task. internal static Task CreateCacheableTask(TResult result) { return new Task(result); } } #endif // ENABLE_CACHED_TASKS /// Holds state related to the builder's IAsyncStateMachine. /// This is a mutable struct. Be very delicate with it. internal struct AsyncMethodBuilderCore { /// A reference to the heap-allocated state machine object associated with this builder. internal IAsyncStateMachine m_stateMachine; /// A cached Action delegate used when dealing with a default ExecutionContext. internal Action m_defaultContextAction; /// Initiates the builder's execution with the associated state machine. /// Specifies the type of the state machine. /// The state machine instance, passed by reference. /// The argument is null (Nothing in Visual Basic). [SecuritySafeCritical] [DebuggerStepThrough] internal static void Start(IAsyncStateMachine stateMachine) { if (stateMachine == null) { throw new ArgumentNullException(nameof(stateMachine)); } #if ENABLE_CONTRACTS Contract.EndContractBlock(); #endif // ENABLE_CONTRACTS RuntimeHelpers.PrepareConstrainedRegions(); stateMachine.MoveNext(); } /// Associates the builder with the state machine it represents. /// The heap-allocated state machine object. /// The argument was null (Nothing in Visual Basic). /// The builder is incorrectly initialized. public void SetStateMachine(IAsyncStateMachine stateMachine) { if (stateMachine == null) { throw new ArgumentNullException(nameof(stateMachine)); } #if ENABLE_CONTRACTS Contract.EndContractBlock(); #endif // ENABLE_CONTRACTS if (m_stateMachine != null) { throw new InvalidOperationException(); } m_stateMachine = stateMachine; } /// /// Gets the Action to use with an awaiter's OnCompleted or UnsafeOnCompleted method. /// On first invocation, the supplied state machine will be boxed. /// /// Specifies the type of the method builder used. /// Specifies the type of the state machine used. /// The builder. /// The state machine. /// An Action to provide to the awaiter. [SecuritySafeCritical] internal Action GetCompletionAction(IAsyncStateMachine stateMachine) { #if ENABLE_CONTRACTS Contract.Assert(m_defaultContextAction == null || m_stateMachine != null, "Expected non-null m_stateMachine on non-null m_defaultContextAction"); #endif // ENABLE_CONTRACTS // If this is our first await, such that we've not yet boxed the state machine, do so now. if (m_stateMachine == null) { // Box the state machine, then tell the boxed instance to call back into its own builder, // so we can cache the boxed reference. NOTE: The language compiler may choose to use // a class instead of a struct for the state machine for debugging purposes; in such cases, // the stateMachine will already be an object. m_stateMachine = stateMachine; m_stateMachine.SetStateMachine(m_stateMachine); } // BUGBUG: Initializing delegates with interface methods doesn't work yet. Restore this line to the // following once they're fixed: return new Action(m_stateMachine.MoveNext); } /// Throws the exception on the ThreadPool. /// The exception to propagate. /// The target context on which to propagate the exception. Null to use the ThreadPool. internal static void ThrowAsync(Exception exception) { // Propagate the exception(s) on the ThreadPool. ThreadPool.QueueUserWorkItem(e => { throw (Exception)e; }, exception); } } } ================================================ FILE: Zelig/Zelig/RunTime/Framework/mscorlib/System/Runtime/CompilerServices/CompilationRelaxations.cs ================================================ // ==++== // // Copyright (c) Microsoft Corporation. All rights reserved. // // ==--== //////////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////////// namespace System.Runtime.CompilerServices { using System; /// IMPORTANT: Keep this in sync with corhdr.h [Serializable] [Flags] public enum CompilationRelaxations : int { NoStringInterning = 0x0008, // Start in 0x0008, we had other non public flags in this enum before, // so we'll start here just in case somebody used them. This flag is only // valid when set for Assemblies. } [Serializable] [AttributeUsage( AttributeTargets.Assembly | AttributeTargets.Module | AttributeTargets.Class | AttributeTargets.Method )] public class CompilationRelaxationsAttribute : Attribute { private int m_relaxations; // The relaxations. public CompilationRelaxationsAttribute( int relaxations ) { m_relaxations = relaxations; } public CompilationRelaxationsAttribute( CompilationRelaxations relaxations ) { m_relaxations = (int)relaxations; } //// public int CompilationRelaxations //// { //// get //// { //// return m_relaxations; //// } //// } } } ================================================ FILE: Zelig/Zelig/RunTime/Framework/mscorlib/System/Runtime/CompilerServices/CompilerGeneratedAttribute.cs ================================================ // ==++== // // Copyright (c) Microsoft Corporation. All rights reserved. // // ==--== //////////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////////// namespace System.Runtime.CompilerServices { [Serializable] [AttributeUsage( AttributeTargets.All, Inherited = true )] public sealed class CompilerGeneratedAttribute : Attribute { public CompilerGeneratedAttribute() { } } } ================================================ FILE: Zelig/Zelig/RunTime/Framework/mscorlib/System/Runtime/CompilerServices/DecimalConstantAttribute.cs ================================================ // ==++== // // Copyright (c) Microsoft Corporation. All rights reserved. // // ==--== // Note: If you add a new ctor overloads you need to update ParameterInfo.RawDefaultValue namespace System.Runtime.CompilerServices { [Serializable, AttributeUsage( AttributeTargets.Field | AttributeTargets.Parameter, Inherited = false )] public sealed class DecimalConstantAttribute : Attribute { [CLSCompliant( false )] public DecimalConstantAttribute( byte scale , byte sign , uint hi , uint mid , uint low ) { dec = new System.Decimal( (int)low, (int)mid, (int)hi, (sign != 0), scale ); } public DecimalConstantAttribute( byte scale , byte sign , int hi , int mid , int low ) { dec = new System.Decimal( low, mid, hi, (sign != 0), scale ); } public System.Decimal Value { get { return dec; } } private System.Decimal dec; } } ================================================ FILE: Zelig/Zelig/RunTime/Framework/mscorlib/System/Runtime/CompilerServices/ExtensionAttribute.cs ================================================ // Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using System; namespace System.Runtime.CompilerServices { /// /// Indicates that a method is an extension method, or that a class or assembly contains extension methods. /// [AttributeUsage(AttributeTargets.Method | AttributeTargets.Class | AttributeTargets.Assembly)] public sealed class ExtensionAttribute : Attribute { } } ================================================ FILE: Zelig/Zelig/RunTime/Framework/mscorlib/System/Runtime/CompilerServices/IAsyncStateMachine.cs ================================================ // Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. // =+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+ // // // // Represents state machines generated for asynchronous methods. // // =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=- namespace System.Runtime.CompilerServices { /// /// Represents state machines generated for asynchronous methods. /// This type is intended for compiler use only. /// public interface IAsyncStateMachine { /// Moves the state machine to its next state. void MoveNext(); /// Configures the state machine with a heap-allocated replica. /// The heap-allocated replica. void SetStateMachine(IAsyncStateMachine stateMachine); } } ================================================ FILE: Zelig/Zelig/RunTime/Framework/mscorlib/System/Runtime/CompilerServices/INotifyCompletion.cs ================================================ // Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. // =+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+= // // // // Interfaces used to represent instances that notify listeners of their completion via continuations. // =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= using System; using System.Security; namespace System.Runtime.CompilerServices { /// /// Represents an operation that will schedule continuations when the operation completes. /// public interface INotifyCompletion { /// Schedules the continuation action to be invoked when the instance completes. /// The action to invoke when the operation completes. /// The argument is null (Nothing in Visual Basic). void OnCompleted(Action continuation); } /// /// Represents an awaiter used to schedule continuations when an await operation completes. /// public interface ICriticalNotifyCompletion : INotifyCompletion { /// Schedules the continuation action to be invoked when the instance completes. /// The action to invoke when the operation completes. /// The argument is null (Nothing in Visual Basic). /// Unlike OnCompleted, UnsafeOnCompleted need not propagate ExecutionContext information. [SecurityCritical] void UnsafeOnCompleted(Action continuation); } } ================================================ FILE: Zelig/Zelig/RunTime/Framework/mscorlib/System/Runtime/CompilerServices/IndexerNameAttribute.cs ================================================ // ==++== // // Copyright (c) Microsoft Corporation. All rights reserved. // // ==--== namespace System.Runtime.CompilerServices { using System; [Serializable] [AttributeUsage( AttributeTargets.Property, Inherited = true )] public sealed class IndexerNameAttribute : Attribute { public IndexerNameAttribute( String indexerName ) { } } } ================================================ FILE: Zelig/Zelig/RunTime/Framework/mscorlib/System/Runtime/CompilerServices/InternalsVisibleToAttribute.cs ================================================ // ==++== // // Copyright (c) Microsoft Corporation. All rights reserved. // // ==--== //------------------------------------------------------------------------------ //------------------------------------------------------------------------------ namespace System.Runtime.CompilerServices { using System; [AttributeUsage( AttributeTargets.Assembly, AllowMultiple = true, Inherited = false )] public sealed class InternalsVisibleToAttribute : Attribute { private string _assemblyName; private bool _allInternalsVisible = true; public InternalsVisibleToAttribute( string assemblyName ) { this._assemblyName = assemblyName; } public string AssemblyName { get { return _assemblyName; } } public bool AllInternalsVisible { get { return _allInternalsVisible; } set { _allInternalsVisible = value; } } } /// /// If AllInternalsVisible is not true for a friend assembly, the FriendAccessAllowed attribute /// indicates which internals are shared with that friend assembly. /// [AttributeUsage(AttributeTargets.Class | AttributeTargets.Constructor | AttributeTargets.Enum | AttributeTargets.Event | AttributeTargets.Field | AttributeTargets.Interface | AttributeTargets.Method | AttributeTargets.Property | AttributeTargets.Struct, AllowMultiple = false, Inherited = false)] [FriendAccessAllowed] internal sealed class FriendAccessAllowedAttribute : Attribute { } } ================================================ FILE: Zelig/Zelig/RunTime/Framework/mscorlib/System/Runtime/CompilerServices/IsVolatile.cs ================================================ // ==++== // // Copyright (c) Microsoft Corporation. All rights reserved. // // ==--== namespace System.Runtime.CompilerServices { [Microsoft.Zelig.Internals.WellKnownType( "System_Runtime_CompilerServices_IsVolatile" )] public static class IsVolatile { // no instantiation, please! } } ================================================ FILE: Zelig/Zelig/RunTime/Framework/mscorlib/System/Runtime/CompilerServices/JitHelpers.cs ================================================ // ==++== // // Copyright (c) Microsoft Corporation. All rights reserved. // // ==--== //////////////////////////////////////////////////////////////////////////////// // JitHelpers // Low-level Jit Helpers //////////////////////////////////////////////////////////////////////////////// //////using System; //////using System.Threading; //////using System.Runtime; //////using System.Runtime.Versioning; //////using System.Diagnostics.Contracts; //////using System.Runtime.InteropServices; //////using System.Security; namespace System.Runtime.CompilerServices { //////// Wrapper for address of a string variable on stack //////internal struct StringHandleOnStack //////{ ////// private IntPtr m_ptr; ////// internal StringHandleOnStack(IntPtr pString) ////// { ////// m_ptr = pString; ////// } //////} //////// Wrapper for address of a object variable on stack //////internal struct ObjectHandleOnStack //////{ ////// private IntPtr m_ptr; ////// internal ObjectHandleOnStack(IntPtr pObject) ////// { ////// m_ptr = pObject; ////// } //////} //////// Wrapper for StackCrawlMark //////internal struct StackCrawlMarkHandle //////{ ////// private IntPtr m_ptr; ////// internal StackCrawlMarkHandle(IntPtr stackMark) ////// { ////// m_ptr = stackMark; ////// } //////} //////// Helper class to assist with unsafe pinning of arbitrary objects. The typical usage pattern is: //////// fixed (byte * pData = &JitHelpers.GetPinningHelper(value).m_data) //////// { //////// ... pData is what Object::GetData() returns in VM ... //////// } //////internal class PinningHelper //////{ ////// public byte m_data; //////} //////[FriendAccessAllowed] internal static class JitHelpers { //////// The special dll name to be used for DllImport of QCalls //////internal const string QCall = "QCall"; //////// Wraps object variable into a handle. Used to return managed strings from QCalls. //////// s has to be a local variable on the stack. //////[SecurityCritical] ////// static internal StringHandleOnStack GetStringHandleOnStack(ref string s) ////// { ////// return new StringHandleOnStack(UnsafeCastToStackPointer(ref s)); ////// } ////// // Wraps object variable into a handle. Used to pass managed object references in and out of QCalls. ////// // o has to be a local variable on the stack. ////// [SecurityCritical] ////// static internal ObjectHandleOnStack GetObjectHandleOnStack(ref T o) where T : class ////// { ////// return new ObjectHandleOnStack(UnsafeCastToStackPointer(ref o)); ////// } ////// // Wraps StackCrawlMark into a handle. Used to pass StackCrawlMark to QCalls. ////// // stackMark has to be a local variable on the stack. ////// [SecurityCritical] ////// static internal StackCrawlMarkHandle GetStackCrawlMarkHandle(ref StackCrawlMark stackMark) ////// { ////// return new StackCrawlMarkHandle(UnsafeCastToStackPointer(ref stackMark)); ////// } //////#if _DEBUG ////// [SecurityCritical] ////// [FriendAccessAllowed] ////// static internal T UnsafeCast(Object o) where T : class ////// { ////// T ret = UnsafeCastInternal(o); ////// Contract.Assert(ret == (o as T), "Invalid use of JitHelpers.UnsafeCast!"); ////// return ret; ////// } ////// // The IL body of this method is not critical, but its body will be replaced with unsafe code, so ////// // this method is effectively critical ////// [SecurityCritical] ////// static private T UnsafeCastInternal(Object o) where T : class ////// { ////// // The body of this function will be replaced by the EE with unsafe code that just returns o!!! ////// // See getILIntrinsicImplementation for how this happens. ////// throw new InvalidOperationException(); ////// } ////// static internal int UnsafeEnumCast(T val) where T : struct // Actually T must be 4 byte (or less) enum ////// { ////// Contract.Assert(typeof(T).IsEnum ////// && (Enum.GetUnderlyingType(typeof(T)) == typeof(int) ////// || Enum.GetUnderlyingType(typeof(T)) == typeof(uint) ////// || Enum.GetUnderlyingType(typeof(T)) == typeof(short) ////// || Enum.GetUnderlyingType(typeof(T)) == typeof(ushort) ////// || Enum.GetUnderlyingType(typeof(T)) == typeof(byte) ////// || Enum.GetUnderlyingType(typeof(T)) == typeof(sbyte)), ////// "Error, T must be an 4 byte (or less) enum JitHelpers.UnsafeEnumCast!"); ////// return UnsafeEnumCastInternal(val); ////// } ////// static private int UnsafeEnumCastInternal(T val) where T : struct // Actually T must be 4 (or less) byte enum ////// { ////// // should be return (int) val; but C# does not allow, runtime does this magically ////// // See getILIntrinsicImplementation for how this happens. ////// throw new InvalidOperationException(); ////// } ////// static internal long UnsafeEnumCastLong(T val) where T : struct // Actually T must be 8 byte enum ////// { ////// Contract.Assert(typeof(T).IsEnum ////// && (Enum.GetUnderlyingType(typeof(T)) == typeof(long) ////// || Enum.GetUnderlyingType(typeof(T)) == typeof(ulong)), ////// "Error, T must be an 8 byte enum JitHelpers.UnsafeEnumCastLong!"); ////// return UnsafeEnumCastLongInternal(val); ////// } ////// static private long UnsafeEnumCastLongInternal(T val) where T : struct // Actually T must be 8 byte enum ////// { ////// // should be return (int) val; but C# does not allow, runtime does this magically ////// // See getILIntrinsicImplementation for how this happens. ////// throw new InvalidOperationException(); ////// } ////// // Internal method for getting a raw pointer for handles in JitHelpers. ////// // The reference has to point into a local stack variable in order so it can not be moved by the GC. ////// [SecurityCritical] ////// static internal IntPtr UnsafeCastToStackPointer(ref T val) ////// { ////// IntPtr p = UnsafeCastToStackPointerInternal(ref val); ////// Contract.Assert(IsAddressInStack(p), "Pointer not in the stack!"); ////// return p; ////// } ////// [SecurityCritical] ////// static private IntPtr UnsafeCastToStackPointerInternal(ref T val) ////// { ////// // The body of this function will be replaced by the EE with unsafe code that just returns val!!! ////// // See getILIntrinsicImplementation for how this happens. ////// throw new InvalidOperationException(); ////// } //////#else // _DEBUG ////// // The IL body of this method is not critical, but its body will be replaced with unsafe code, so ////// // this method is effectively critical ////// [SecurityCritical] ////// [FriendAccessAllowed] //////static public extern T UnsafeCast( Object o ) where T : class //////{ ////// // The body of this function will be replaced by the EE with unsafe code that just returns o!!! ////// // See getILIntrinsicImplementation for how this happens. ////// throw new InvalidOperationException( ); //////} [MethodImpl( MethodImplOptions.InternalCall )] static internal extern int UnsafeEnumCast( T val ) where T : struct; // Actually T must be 4 byte (or less) enum //////{ ////// // should be return (int) val; but C# does not allow, runtime does this magically ////// // See getILIntrinsicImplementation for how this happens. ////// throw new InvalidOperationException( ); //////} [MethodImpl( MethodImplOptions.InternalCall )] static internal extern long UnsafeEnumCastLong( T val ) where T : struct; // Actually T must be 8 byte enum //////{ ////// // should be return (long) val; but C# does not allow, runtime does this magically ////// // See getILIntrinsicImplementation for how this happens. ////// throw new InvalidOperationException( ); //////} ////// [SecurityCritical] ////// static internal IntPtr UnsafeCastToStackPointer(ref T val) ////// { ////// // The body of this function will be replaced by the EE with unsafe code that just returns o!!! ////// // See getILIntrinsicImplementation for how this happens. ////// throw new InvalidOperationException(); ////// } //////#endif // _DEBUG ////// // Set the given element in the array without any type or range checks ////// [SecurityCritical] ////// [ResourceExposure(ResourceScope.None)] ////// [MethodImplAttribute(MethodImplOptions.InternalCall)] ////// extern static internal void UnsafeSetArrayElement(Object[] target, int index, Object element); ////// // Used for unsafe pinning of arbitrary objects. ////// [System.Security.SecurityCritical] // auto-generated ////// static internal PinningHelper GetPinningHelper(Object o) ////// { ////// // This cast is really unsafe - call the private version that does not assert in debug //////#if _DEBUG ////// return UnsafeCastInternal(o); //////#else ////// return UnsafeCast(o); //////#endif ////// } //////#if _DEBUG ////// [SecurityCritical] ////// [ResourceExposure(ResourceScope.None)] ////// [MethodImplAttribute(MethodImplOptions.InternalCall)] ////// extern static bool IsAddressInStack(IntPtr ptr); //////#endif } } ================================================ FILE: Zelig/Zelig/RunTime/Framework/mscorlib/System/Runtime/CompilerServices/MethodImplAttribute.cs ================================================ // ==++== // // Copyright (c) Microsoft Corporation. All rights reserved. // // ==--== namespace System.Runtime.CompilerServices { using System; using System.Reflection; // This Enum matchs the miImpl flags defined in corhdr.h. It is used to specify // certain method properties. [Flags] [Serializable] public enum MethodImplOptions { Unmanaged = MethodImplAttributes.Unmanaged , ForwardRef = MethodImplAttributes.ForwardRef , PreserveSig = MethodImplAttributes.PreserveSig , InternalCall = MethodImplAttributes.InternalCall, Synchronized = MethodImplAttributes.Synchronized, NoInlining = MethodImplAttributes.NoInlining , } [Serializable] public enum MethodCodeType { IL = System.Reflection.MethodImplAttributes.IL , Native = System.Reflection.MethodImplAttributes.Native , /// OPTIL = System.Reflection.MethodImplAttributes.OPTIL , Runtime = System.Reflection.MethodImplAttributes.Runtime, } // Custom attribute to specify additional method properties. [Serializable] [AttributeUsage( AttributeTargets.Method | AttributeTargets.Constructor, Inherited = false )] sealed public class MethodImplAttribute : Attribute { internal MethodImplOptions m_val; public MethodCodeType MethodCodeType; internal MethodImplAttribute( MethodImplAttributes methodImplAttributes ) { MethodImplOptions all = MethodImplOptions.Unmanaged | MethodImplOptions.ForwardRef | MethodImplOptions.PreserveSig | MethodImplOptions.InternalCall | MethodImplOptions.Synchronized | MethodImplOptions.NoInlining; m_val = ((MethodImplOptions)methodImplAttributes) & all; } public MethodImplAttribute( MethodImplOptions methodImplOptions ) { m_val = methodImplOptions; } //// public MethodImplAttribute( short value ) //// { //// m_val = (MethodImplOptions)value; //// } public MethodImplAttribute() { } public MethodImplOptions Value { get { return m_val; } } } } ================================================ FILE: Zelig/Zelig/RunTime/Framework/mscorlib/System/Runtime/CompilerServices/RuntimeCompatibilityAttribute.cs ================================================ // ==++== // // Copyright (c) Microsoft Corporation. All rights reserved. // // ==--== //////////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////////// /*============================================================================= ** ** Class: RuntimeCompatibilityAttribute ** ** ** Purpose: Mark up the program to indicate various legacy or new opt-in behaviors. ** ** =============================================================================*/ namespace System.Runtime.CompilerServices { using System; [Serializable] [AttributeUsage( AttributeTargets.Assembly, Inherited = false, AllowMultiple = false )] public sealed class RuntimeCompatibilityAttribute : Attribute { // fields private bool m_wrapNonExceptionThrows; // constructors public RuntimeCompatibilityAttribute() { // legacy behavior is the default, and m_wrapNonExceptionThrows is implicitly // false thanks to the CLR's guarantee of zeroed memory. } // properties // If a non-CLSCompliant exception (i.e. one that doesn't derive from System.Exception) is // thrown, should it be wrapped up in a System.Runtime.CompilerServices.RuntimeWrappedException // instance when presented to catch handlers? public bool WrapNonExceptionThrows { get { return m_wrapNonExceptionThrows; } set { m_wrapNonExceptionThrows = value; } } } } ================================================ FILE: Zelig/Zelig/RunTime/Framework/mscorlib/System/Runtime/CompilerServices/RuntimeHelpers.cs ================================================ // ==++== // // Copyright (c) Microsoft Corporation. All rights reserved. // // ==--== //////////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////////// // // RuntimeHelpers // This class defines a set of static methods that provide support for compilers. // // Date: April 2000 // namespace System.Runtime.CompilerServices { using System; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using System.Runtime.ConstrainedExecution; ////using System.Security.Permissions; using System.Threading; ////using System.Runtime.Versioning; public static class RuntimeHelpers { //// [ResourceExposure( ResourceScope.None )] [MethodImpl( MethodImplOptions.InternalCall )] public static extern void InitializeArray( Array array, RuntimeFieldHandle fldHandle ); // GetObjectValue is intended to allow value classes to be manipulated as 'Object' // but have aliasing behavior of a value class. The intent is that you would use // this function just before an assignment to a variable of type 'Object'. If the // value being assigned is a mutable value class, then a shallow copy is returned // (because value classes have copy semantics), but otherwise the object itself // is returned. // // Note: VB calls this method when they're about to assign to an Object // or pass it as a parameter. The goal is to make sure that boxed // value types work identical to unboxed value types - ie, they get // cloned when you pass them around, and are always passed by value. // Of course, reference types are not cloned. // //// [ResourceExposure( ResourceScope.None )] [MethodImpl( MethodImplOptions.InternalCall )] public static extern Object GetObjectValue( Object obj ); // RunClassConstructor causes the class constructor for the given type to be triggered // in the current domain. After this call returns, the class constructor is guaranteed to // have at least been started by some thread. In the absence of class constructor // deadlock conditions, the call is further guaranteed to have completed. // // This call will generate an exception if the specified class constructor threw an // exception when it ran. //// [ResourceExposure( ResourceScope.None )] //// [MethodImpl( MethodImplOptions.InternalCall )] //// private static extern void _RunClassConstructor( IntPtr type ); //// //// public static void RunClassConstructor( RuntimeTypeHandle type ) //// { //// _RunClassConstructor( type.Value ); //// } // RunModuleConstructor causes the module constructor for the given type to be triggered // in the current domain. After this call returns, the module constructor is guaranteed to // have at least been started by some thread. In the absence of module constructor // deadlock conditions, the call is further guaranteed to have completed. // // This call will generate an exception if the specified module constructor threw an // exception when it ran. //// [ResourceExposure( ResourceScope.None )] //// [MethodImpl( MethodImplOptions.InternalCall )] //// private static extern void _RunModuleConstructor( IntPtr module ); //// //// public static void RunModuleConstructor( ModuleHandle module ) //// { //// _RunModuleConstructor( module.Value ); //// } //// [ResourceExposure( ResourceScope.None )] //// [MethodImpl( MethodImplOptions.InternalCall )] //// private static extern void _PrepareMethod( IntPtr method, RuntimeTypeHandle[] instantiation ); //// //// // Simple (instantiation not required) method. //// [SecurityPermission( SecurityAction.LinkDemand, UnmanagedCode = true )] //// public static void PrepareMethod( RuntimeMethodHandle method ) //// { //// _PrepareMethod( method.Value, null ); //// } //// //// // Generic method or method with generic class with specific instantiation. //// [SecurityPermission( SecurityAction.LinkDemand, UnmanagedCode = true )] //// public static void PrepareMethod( RuntimeMethodHandle method, RuntimeTypeHandle[] instantiation ) //// { //// _PrepareMethod( method.Value, instantiation ); //// } //// // This method triggers a given delegate to be prepared. This involves preparing the //// // delegate's Invoke method and preparing the target of that Invoke. In the case of //// // a multi-cast delegate, we rely on the fact that each individual component was prepared //// // prior to the Combine. In other words, this service does not navigate through the //// // entire multicasting list. //// // If our own reliable event sinks perform the Combine (for example AppDomain.DomainUnload), //// // then the result is fully prepared. But if a client calls Combine himself and then //// // then adds that combination to e.g. AppDomain.DomainUnload, then the client is responsible //// // for his own preparation. //// [ResourceExposure( ResourceScope.None )] //// [MethodImpl( MethodImplOptions.InternalCall )] //// [SecurityPermission( SecurityAction.LinkDemand, UnmanagedCode = true )] //// public static extern void PrepareDelegate( Delegate d ); //// public static int GetHashCode( Object o ) //// { //// return Object.InternalGetHashCode( o ); //// } //// //// public new static bool Equals( Object o1, Object o2 ) //// { //// return Object.InternalEquals( o1, o2 ); //// } public extern static int OffsetToStringData { [MethodImpl( MethodImplOptions.InternalCall )] get; //// { //// // Number of bytes from the address pointed to by a reference to //// // a String to the first 16-bit character in the String. Skip //// // over the MethodTable pointer, String capacity, & String //// // length. Of course, the String reference points to the memory //// // after the sync block, so don't count that. //// // This property allows C#'s fixed statement to work on Strings. //// // On 64 bit platforms, this should be 16. #if !WIN64 //// return 12; #else //// return 16; #endif //// } } //// [ResourceExposure( ResourceScope.None )] //// [SecurityPermission( SecurityAction.LinkDemand, UnmanagedCode = true )] //// [ReliabilityContract( Consistency.WillNotCorruptState, Cer.MayFail )] [MethodImpl( MethodImplOptions.InternalCall )] public static extern void ProbeForSufficientStack(); // This method is a marker placed immediately before a try clause to mark the corresponding catch and finally blocks as // constrained. There's no code here other than the probe because most of the work is done at JIT time when we spot a call to this routine. //// [SecurityPermission( SecurityAction.LinkDemand, UnmanagedCode = true )] //// [ReliabilityContract( Consistency.WillNotCorruptState, Cer.MayFail )] public static void PrepareConstrainedRegions() { ProbeForSufficientStack(); } // When we detect a CER with no calls, we can point the JIT to this non-probing version instead // as we don't need to probe. //// [SecurityPermission( SecurityAction.LinkDemand, UnmanagedCode = true )] //// [ReliabilityContract( Consistency.WillNotCorruptState, Cer.MayFail )] public static void PrepareConstrainedRegionsNoOP() { } public delegate void TryCode( Object userData ); public delegate void CleanupCode( Object userData, bool exceptionThrown ); //// [ResourceExposure( ResourceScope.None )] [MethodImpl( MethodImplOptions.InternalCall )] //// [SecurityPermission( SecurityAction.LinkDemand, UnmanagedCode = true )] public static extern void ExecuteCodeWithGuaranteedCleanup( TryCode code, CleanupCode backoutCode, Object userData ); //// [PrePrepareMethod] //// internal static void ExecuteBackoutCodeHelper( Object backoutCode, Object userData, bool exceptionThrown ) //// { //// ((CleanupCode)backoutCode)( userData, exceptionThrown ); //// } //// // Roughly equivalent to a CER try/finally that will take a lock, run //// // the try code, and in the finally block, release the lock. Calls //// // ExecuteCodeWithGuaranteedCleanup to ensure this will work w.r.t. //// // stack overflows. //// // We should consider making this public. //// [SecurityPermission( SecurityAction.LinkDemand, UnmanagedCode = true )] //// [HostProtection( Synchronization = true )] //// internal static void ExecuteCodeWithLock( Object lockObject, TryCode code, object userState ) //// { //// ExecuteWithLockHelper execHelper = new ExecuteWithLockHelper( lockObject, code, userState ); //// ExecuteCodeWithGuaranteedCleanup( s_EnterMonitor, s_ExitMonitor, execHelper ); //// } //// //// private static TryCode s_EnterMonitor = new TryCode( EnterMonitorAndTryCode ); //// private static CleanupCode s_ExitMonitor = new CleanupCode( ExitMonitorOnBackout ); //// //// private static void EnterMonitorAndTryCode( Object helper ) //// { //// ExecuteWithLockHelper execHelper = (ExecuteWithLockHelper)helper; //// BCLDebug.Assert( execHelper != null, "ExecuteWithLockHelper is null" ); //// BCLDebug.Assert( execHelper.m_lockObject != null, "LockObject is null" ); //// BCLDebug.Assert( execHelper.m_userCode != null, "UserCode is null" ); //// //// Monitor.ReliableEnter( execHelper.m_lockObject, ref execHelper.m_tookLock ); //// execHelper.m_userCode( execHelper.m_userState ); //// } //// //// [PrePrepareMethod] //// private static void ExitMonitorOnBackout( Object helper, bool exceptionThrown ) //// { //// ExecuteWithLockHelper execHelper = (ExecuteWithLockHelper)helper; //// BCLDebug.Assert( execHelper != null, "ExecuteWithLockHelper is null" ); //// BCLDebug.Assert( execHelper.m_lockObject != null, "LockObject is null" ); //// //// if(execHelper.m_tookLock) //// { //// Monitor.Exit( execHelper.m_lockObject ); //// } //// } //// //// class ExecuteWithLockHelper //// { //// internal Object m_lockObject; //// internal bool m_tookLock; //// internal TryCode m_userCode; //// internal object m_userState; //// //// internal ExecuteWithLockHelper( Object lockObject, TryCode userCode, object userState ) //// { //// m_lockObject = lockObject; //// m_userCode = userCode; //// m_userState = userState; //// } //// } } } ================================================ FILE: Zelig/Zelig/RunTime/Framework/mscorlib/System/Runtime/CompilerServices/SpecialNameAttribute.cs ================================================ // ==++== // // Copyright (c) Microsoft Corporation. All rights reserved. // // ==--== using System; using System.Reflection; using System.Runtime.InteropServices; namespace System.Runtime.CompilerServices { [AttributeUsage( AttributeTargets.Class | AttributeTargets.Method | AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Event | AttributeTargets.Struct )] public sealed class SpecialNameAttribute : Attribute { public SpecialNameAttribute() { } } } ================================================ FILE: Zelig/Zelig/RunTime/Framework/mscorlib/System/Runtime/CompilerServices/StateMachineAttribute.cs ================================================ // Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. namespace System.Runtime.CompilerServices { [Serializable, AttributeUsage(AttributeTargets.Method, Inherited = false, AllowMultiple = false)] public class StateMachineAttribute : Attribute { public Type StateMachineType { get; private set; } public StateMachineAttribute(Type stateMachineType) { StateMachineType = stateMachineType; } } } ================================================ FILE: Zelig/Zelig/RunTime/Framework/mscorlib/System/Runtime/CompilerServices/TaskAwaiter.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // // =+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+ // // // // Types for awaiting Task and Task. These types are emitted from Task{}.GetAwaiter // and Task{}.ConfigureAwait. They are meant to be used only by the compiler, e.g. // // await nonGenericTask; // ===================== // var $awaiter = nonGenericTask.GetAwaiter(); // if (!$awaiter.IsCompleted) // { // SPILL: // $builder.AwaitUnsafeOnCompleted(ref $awaiter, ref this); // return; // Label: // UNSPILL; // } // $awaiter.GetResult(); // // result += await genericTask.ConfigureAwait(false); // =================================================================================== // var $awaiter = genericTask.ConfigureAwait(false).GetAwaiter(); // if (!$awaiter.IsCompleted) // { // SPILL; // $builder.AwaitUnsafeOnCompleted(ref $awaiter, ref this); // return; // Label: // UNSPILL; // } // result += $awaiter.GetResult(); // // =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=- using System; using System.Diagnostics.Contracts; using System.Security; using System.Security.Permissions; using System.Threading; using System.Threading.Tasks; // NOTE: For performance reasons, initialization is not verified. If a developer // incorrectly initializes a task awaiter, which should only be done by the compiler, // NullReferenceExceptions may be generated (the alternative would be for us to detect // this case and then throw a different exception instead). This is the same tradeoff // that's made with other compiler-focused value types like List.Enumerator. namespace System.Runtime.CompilerServices { /// Provides an awaiter for awaiting a . /// This type is intended for compiler use only. ////[HostProtection(Synchronization = true, ExternalThreading = true)] public struct TaskAwaiter : ICriticalNotifyCompletion { /// The task being awaited. private readonly Task m_task; /// Initializes the . /// The to be awaited. internal TaskAwaiter(Task task) { #if ENABLE_CONTRACTS Contract.Requires(task != null, "Constructing an awaiter requires a task to await."); #endif // ENABLE_CONTRACTS m_task = task; } /// Gets whether the task being awaited is completed. /// This property is intended for compiler user rather than use directly in code. /// The awaiter was not properly initialized. public bool IsCompleted => m_task.IsCompleted; /// Schedules the continuation onto the associated with this . /// The action to invoke when the await operation completes. /// The argument is null (Nothing in Visual Basic). /// The awaiter was not properly initialized. /// This method is intended for compiler user rather than use directly in code. [SecuritySafeCritical] public void OnCompleted(Action continuation) { OnCompletedInternal(m_task, continuation, continueOnCapturedContext: true, flowExecutionContext: true); } /// Schedules the continuation onto the associated with this . /// The action to invoke when the await operation completes. /// The argument is null (Nothing in Visual Basic). /// The awaiter was not properly initialized. /// This method is intended for compiler user rather than use directly in code. [SecurityCritical] public void UnsafeOnCompleted(Action continuation) { OnCompletedInternal(m_task, continuation, continueOnCapturedContext: true, flowExecutionContext: false); } /// Ends the await on the completed . /// The awaiter was not properly initialized. /// The task was canceled. /// The task completed in a Faulted state. public void GetResult() { ValidateEnd(m_task); } /// /// Fast checks for the end of an await operation to determine whether more needs to be done /// prior to completing the await. /// /// The awaited task. internal static void ValidateEnd(Task task) { // Synchronously wait for the task to complete. When used by the compiler, the task will already be complete. // This code exists only for direct GetResult use, for cases where the same exception propagation semantics // used by "await" are desired, but where for one reason or another synchronous rather than asynchronous // waiting is needed. if (!task.IsCompleted) { bool taskCompleted = task.InternalWait(Timeout.Infinite, default(CancellationToken)); #if ENABLE_CONTRACTS Contract.Assert(taskCompleted, "With an infinite timeout, the task should have always completed."); #endif // ENABLE_CONTRACTS } // And throw an exception if the task is faulted or canceled. switch (task.Status) { case TaskStatus.RanToCompletion: break; // If the task completed in a canceled state, throw an OperationCanceledException. // This will either be the OCE that actually caused the task to cancel, or it will be a new // TaskCanceledException. TCE derives from OCE, and by throwing it we automatically pick up the // completed task's CancellationToken if it has one, including that CT in the OCE. case TaskStatus.Canceled: throw new TaskCanceledException(task); // If the task faulted, throw its first exception, // even if it contained more than one. case TaskStatus.Faulted: throw task.Exception; } } /// Schedules the continuation onto the associated with this . /// The task being awaited. /// The action to invoke when the await operation completes. /// Whether to capture and marshal back to the current context. /// Whether to flow ExecutionContext across the await. /// The argument is null (Nothing in Visual Basic). /// The awaiter was not properly initialized. /// This method is intended for compiler user rather than use directly in code. [SecurityCritical] internal static void OnCompletedInternal(Task task, Action continuation, bool continueOnCapturedContext, bool flowExecutionContext) { if (continuation == null) { throw new ArgumentNullException(nameof(continuation)); } // Set the continuation onto the awaited task. // BUGBUG: We don't currently support capturing context, so this will always run on the thread pool. task.SetContinuationForAwait(continuation); } } /// Provides an awaiter for awaiting a . /// This type is intended for compiler use only. ////[HostProtection(Synchronization = true, ExternalThreading = true)] public struct TaskAwaiter : ICriticalNotifyCompletion { /// The task being awaited. private readonly Task m_task; /// Initializes the . /// The to be awaited. internal TaskAwaiter(Task task) { #if ENABLE_CONTRACTS Contract.Requires(task != null, "Constructing an awaiter requires a task to await."); #endif // ENABLE_CONTRACTS m_task = task; } /// Gets whether the task being awaited is completed. /// This property is intended for compiler user rather than use directly in code. /// The awaiter was not properly initialized. public bool IsCompleted => m_task.IsCompleted; /// Schedules the continuation onto the associated with this . /// The action to invoke when the await operation completes. /// The argument is null (Nothing in Visual Basic). /// The awaiter was not properly initialized. /// This method is intended for compiler user rather than use directly in code. [SecuritySafeCritical] public void OnCompleted(Action continuation) { TaskAwaiter.OnCompletedInternal(m_task, continuation, continueOnCapturedContext: true, flowExecutionContext: true); } /// Schedules the continuation onto the associated with this . /// The action to invoke when the await operation completes. /// The argument is null (Nothing in Visual Basic). /// The awaiter was not properly initialized. /// This method is intended for compiler user rather than use directly in code. [SecurityCritical] public void UnsafeOnCompleted(Action continuation) { TaskAwaiter.OnCompletedInternal(m_task, continuation, continueOnCapturedContext: true, flowExecutionContext: false); } /// Ends the await on the completed . /// The result of the completed . /// The awaiter was not properly initialized. /// The task was canceled. /// The task completed in a Faulted state. public TResult GetResult() { TaskAwaiter.ValidateEnd(m_task); return m_task.Result; } } /// Provides an awaitable object that allows for configured awaits on . /// This type is intended for compiler use only. public struct ConfiguredTaskAwaitable { /// The task being awaited. private readonly ConfiguredTaskAwaitable.ConfiguredTaskAwaiter m_configuredTaskAwaiter; /// Initializes the . /// The awaitable . /// /// true to attempt to marshal the continuation back to the original context captured; otherwise, false. /// internal ConfiguredTaskAwaitable(Task task, bool continueOnCapturedContext) { #if ENABLE_CONTRACTS Contract.Requires(task != null, "Constructing an awaitable requires a task to await."); #endif // ENABLE_CONTRACTS m_configuredTaskAwaiter = new ConfiguredTaskAwaitable.ConfiguredTaskAwaiter(task, continueOnCapturedContext); } /// Gets an awaiter for this awaitable. /// The awaiter. public ConfiguredTaskAwaitable.ConfiguredTaskAwaiter GetAwaiter() { return m_configuredTaskAwaiter; } /// Provides an awaiter for a . /// This type is intended for compiler use only. ////[HostProtection(Synchronization = true, ExternalThreading = true)] public struct ConfiguredTaskAwaiter : ICriticalNotifyCompletion { /// The task being awaited. private readonly Task m_task; /// Whether to attempt marshaling back to the original context. private readonly bool m_continueOnCapturedContext; /// Initializes the . /// The to await. /// /// true to attempt to marshal the continuation back to the original context captured /// when BeginAwait is called; otherwise, false. /// internal ConfiguredTaskAwaiter(Task task, bool continueOnCapturedContext) { #if ENABLE_CONTRACTS Contract.Requires(task != null, "Constructing an awaiter requires a task to await."); #endif // ENABLE_CONTRACTS m_task = task; m_continueOnCapturedContext = continueOnCapturedContext; } /// Gets whether the task being awaited is completed. /// This property is intended for compiler user rather than use directly in code. /// The awaiter was not properly initialized. public bool IsCompleted => m_task.IsCompleted; /// Schedules the continuation onto the associated with this . /// The action to invoke when the await operation completes. /// The argument is null (Nothing in Visual Basic). /// The awaiter was not properly initialized. /// This method is intended for compiler user rather than use directly in code. [SecuritySafeCritical] public void OnCompleted(Action continuation) { TaskAwaiter.OnCompletedInternal(m_task, continuation, m_continueOnCapturedContext, flowExecutionContext: true); } /// Schedules the continuation onto the associated with this . /// The action to invoke when the await operation completes. /// The argument is null (Nothing in Visual Basic). /// The awaiter was not properly initialized. /// This method is intended for compiler user rather than use directly in code. [SecurityCritical] public void UnsafeOnCompleted(Action continuation) { TaskAwaiter.OnCompletedInternal(m_task, continuation, m_continueOnCapturedContext, flowExecutionContext: false); } /// Ends the await on the completed . /// The result of the completed . /// The awaiter was not properly initialized. /// The task was canceled. /// The task completed in a Faulted state. public void GetResult() { TaskAwaiter.ValidateEnd(m_task); } } } /// Provides an awaitable object that allows for configured awaits on . /// This type is intended for compiler use only. public struct ConfiguredTaskAwaitable { /// The underlying awaitable on whose logic this awaitable relies. private readonly ConfiguredTaskAwaitable.ConfiguredTaskAwaiter m_configuredTaskAwaiter; /// Initializes the . /// The awaitable . /// /// true to attempt to marshal the continuation back to the original context captured; otherwise, false. /// internal ConfiguredTaskAwaitable(Task task, bool continueOnCapturedContext) { m_configuredTaskAwaiter = new ConfiguredTaskAwaitable.ConfiguredTaskAwaiter(task, continueOnCapturedContext); } /// Gets an awaiter for this awaitable. /// The awaiter. public ConfiguredTaskAwaitable.ConfiguredTaskAwaiter GetAwaiter() { return m_configuredTaskAwaiter; } /// Provides an awaiter for a . /// This type is intended for compiler use only. [HostProtection(Synchronization = true, ExternalThreading = true)] public struct ConfiguredTaskAwaiter : ICriticalNotifyCompletion { /// The task being awaited. private readonly Task m_task; /// Whether to attempt marshaling back to the original context. private readonly bool m_continueOnCapturedContext; /// Initializes the . /// The awaitable . /// /// true to attempt to marshal the continuation back to the original context captured; otherwise, false. /// internal ConfiguredTaskAwaiter(Task task, bool continueOnCapturedContext) { #if ENABLE_CONTRACTS Contract.Requires(task != null, "Constructing an awaiter requires a task to await."); #endif // ENABLE_CONTRACTS m_task = task; m_continueOnCapturedContext = continueOnCapturedContext; } /// Gets whether the task being awaited is completed. /// This property is intended for compiler user rather than use directly in code. /// The awaiter was not properly initialized. public bool IsCompleted => m_task.IsCompleted; /// Schedules the continuation onto the associated with this . /// The action to invoke when the await operation completes. /// The argument is null (Nothing in Visual Basic). /// The awaiter was not properly initialized. /// This method is intended for compiler user rather than use directly in code. [SecuritySafeCritical] public void OnCompleted(Action continuation) { TaskAwaiter.OnCompletedInternal(m_task, continuation, m_continueOnCapturedContext, flowExecutionContext: true); } /// Schedules the continuation onto the associated with this . /// The action to invoke when the await operation completes. /// The argument is null (Nothing in Visual Basic). /// The awaiter was not properly initialized. /// This method is intended for compiler user rather than use directly in code. [SecurityCritical] public void UnsafeOnCompleted(Action continuation) { TaskAwaiter.OnCompletedInternal(m_task, continuation, m_continueOnCapturedContext, flowExecutionContext: false); } /// Ends the await on the completed . /// The result of the completed . /// The awaiter was not properly initialized. /// The task was canceled. /// The task completed in a Faulted state. public TResult GetResult() { TaskAwaiter.ValidateEnd(m_task); return m_task.Result; } } } } ================================================ FILE: Zelig/Zelig/RunTime/Framework/mscorlib/System/Runtime/CompilerServices/TypeForwardedFromAttribute.cs ================================================ // Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. namespace System.Runtime.CompilerServices { [AttributeUsage(AttributeTargets.Class | AttributeTargets.Struct | AttributeTargets.Enum | AttributeTargets.Interface | AttributeTargets.Delegate, Inherited = false, AllowMultiple = false)] public sealed class TypeForwardedFromAttribute : Attribute { string assemblyFullName; private TypeForwardedFromAttribute() { // Disallow default constructor } public TypeForwardedFromAttribute(string assemblyFullName) { if (String.IsNullOrEmpty(assemblyFullName)) { throw new ArgumentNullException("assemblyFullName"); } this.assemblyFullName = assemblyFullName; } public string AssemblyFullName { get { return assemblyFullName; } } } } ================================================ FILE: Zelig/Zelig/RunTime/Framework/mscorlib/System/Runtime/CompilerServices/UnsafeValueTypeAttribute.cs ================================================ // ==++== // // Copyright (c) Microsoft Corporation. All rights reserved. // // ==--== namespace System.Runtime.CompilerServices { using System; [Serializable, AttributeUsage(AttributeTargets.Struct)] sealed public class UnsafeValueTypeAttribute : Attribute { } } ================================================ FILE: Zelig/Zelig/RunTime/Framework/mscorlib/System/Runtime/InteropServices/Attributes.cs ================================================ // ==++== // // Copyright (c) Microsoft Corporation. All rights reserved. // // ==--== //////////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////////// namespace System.Runtime.InteropServices { using System; using System.Reflection; ////[AttributeUsage( AttributeTargets.Delegate, AllowMultiple = false, Inherited = false )] ////public sealed class UnmanagedFunctionPointerAttribute : Attribute ////{ //// CallingConvention m_callingConvention; //// //// public UnmanagedFunctionPointerAttribute( CallingConvention callingConvention ) { m_callingConvention = callingConvention; } //// //// public CallingConvention CallingConvention //// { //// get //// { //// return m_callingConvention; //// } //// } //// //// public CharSet CharSet; //// public bool BestFitMapping; //// public bool ThrowOnUnmappableChar; //// public bool SetLastError; //// //public bool PreserveSig; ////} [AttributeUsage(AttributeTargets.Assembly | AttributeTargets.Interface | AttributeTargets.Class | AttributeTargets.Struct | AttributeTargets.Delegate | AttributeTargets.Enum | AttributeTargets.Field | AttributeTargets.Method | AttributeTargets.Property, Inherited = false)] public sealed class ComVisibleAttribute : Attribute { internal bool _val; public ComVisibleAttribute( bool visibility ) { _val = visibility; } //// public bool Value //// { //// get //// { //// return _val; //// } //// } } [Serializable] public enum VarEnum { VT_EMPTY = 0, VT_NULL = 1, VT_I2 = 2, VT_I4 = 3, VT_R4 = 4, VT_R8 = 5, VT_CY = 6, VT_DATE = 7, VT_BSTR = 8, ////#if FEATURE_COMINTEROP //// VT_DISPATCH = 9, ////#endif // FEATURE_COMINTEROP VT_ERROR = 10, VT_BOOL = 11, VT_VARIANT = 12, VT_UNKNOWN = 13, VT_DECIMAL = 14, VT_I1 = 16, VT_UI1 = 17, VT_UI2 = 18, VT_UI4 = 19, VT_I8 = 20, VT_UI8 = 21, VT_INT = 22, VT_UINT = 23, VT_VOID = 24, VT_HRESULT = 25, VT_PTR = 26, VT_SAFEARRAY = 27, VT_CARRAY = 28, VT_USERDEFINED = 29, VT_LPSTR = 30, VT_LPWSTR = 31, VT_RECORD = 36, VT_FILETIME = 64, VT_BLOB = 65, VT_STREAM = 66, VT_STORAGE = 67, VT_STREAMED_OBJECT = 68, VT_STORED_OBJECT = 69, VT_BLOB_OBJECT = 70, VT_CF = 71, VT_CLSID = 72, VT_VECTOR = 0x1000, VT_ARRAY = 0x2000, VT_BYREF = 0x4000 } [Serializable] public enum UnmanagedType { Bool = 0x02, // 4 byte boolean value (true != 0, false == 0) I1 = 0x03, // 1 byte signed value U1 = 0x04, // 1 byte unsigned value I2 = 0x05, // 2 byte signed value U2 = 0x06, // 2 byte unsigned value I4 = 0x07, // 4 byte signed value U4 = 0x08, // 4 byte unsigned value I8 = 0x09, // 8 byte signed value U8 = 0x0A, // 8 byte unsigned value R4 = 0x0B, // 4 byte floating point R8 = 0x0C, // 8 byte floating point Currency = 0x0F, // A currency ////#if FEATURE_COMINTEROP //// BStr = 0x13, // OLE Unicode BSTR ////#endif //FEATURE_COMINTEROP LPStr = 0x14, // Ptr to SBCS string LPWStr = 0x15, // Ptr to Unicode string LPTStr = 0x16, // Ptr to OS preferred (SBCS/Unicode) string ByValTStr = 0x17, // OS preferred (SBCS/Unicode) inline string (only valid in structs) IUnknown = 0x19, // COM IUnknown pointer. ////#if FEATURE_COMINTEROP //// IDispatch = 0x1A, // COM IDispatch pointer ////#endif //FEATURE_COMINTEROP Struct = 0x1B, // Structure ////#if FEATURE_COMINTEROP //// Interface = 0x1C, // COM interface //// //// SafeArray = 0x1D, // OLE SafeArray ////#endif //FEATURE_COMINTEROP ByValArray = 0x1E, // Array of fixed size (only valid in structs) SysInt = 0x1F, // Hardware natural sized signed integer SysUInt = 0x20, ////#if FEATURE_COMINTEROP //// VBByRefStr = 0x22, //// //// AnsiBStr = 0x23, // OLE BSTR containing SBCS characters //// //// TBStr = 0x24, // Ptr to OS preferred (SBCS/Unicode) BSTR //// //// VariantBool = 0x25, // OLE defined BOOLEAN (2 bytes, true == -1, false == 0) ////#endif //FEATURE_COMINTEROP FunctionPtr = 0x26, // Function pointer AsAny = 0x28, // Paired with Object type and does runtime marshalling determination LPArray = 0x2A, // C style array LPStruct = 0x2B, // Pointer to a structure CustomMarshaler = 0x2C, Error = 0x2D, } [AttributeUsage( AttributeTargets.Parameter | AttributeTargets.Field | AttributeTargets.ReturnValue, Inherited = false )] public unsafe sealed class MarshalAsAttribute : Attribute { //// internal static Attribute GetCustomAttribute( ParameterInfo parameter ) //// { //// return GetCustomAttribute( parameter.MetadataToken, parameter.Member.Module ); //// } //// //// internal static bool IsDefined( ParameterInfo parameter ) //// { //// return GetCustomAttribute( parameter ) != null; //// } //// //// internal static Attribute GetCustomAttribute( RuntimeFieldInfo field ) //// { //// return GetCustomAttribute( field.MetadataToken, field.Module ); ; //// } //// //// internal static bool IsDefined( RuntimeFieldInfo field ) //// { //// return GetCustomAttribute( field ) != null; //// } //// //// internal static Attribute GetCustomAttribute( int token, Module scope ) //// { //// UnmanagedType unmanagedType, arraySubType; //// VarEnum safeArraySubType; //// int sizeParamIndex = 0, sizeConst = 0; //// string marshalTypeName = null, marshalCookie = null, safeArrayUserDefinedTypeName = null; //// int iidParamIndex = 0; //// //// ConstArray nativeType = scope.ModuleHandle.GetMetadataImport().GetFieldMarshal( token ); //// //// if(nativeType.Length == 0) //// return null; //// //// MetadataImport.GetMarshalAs( nativeType, //// out unmanagedType, out safeArraySubType, out safeArrayUserDefinedTypeName, out arraySubType, out sizeParamIndex, //// out sizeConst, out marshalTypeName, out marshalCookie, out iidParamIndex ); //// //// Type safeArrayUserDefinedType = safeArrayUserDefinedTypeName == null || safeArrayUserDefinedTypeName.Length == 0 ? null : //// RuntimeTypeHandle.GetTypeByNameUsingCARules( safeArrayUserDefinedTypeName, scope ); //// Type marshalTypeRef = null; //// //// try //// { //// marshalTypeRef = marshalTypeName == null ? null : RuntimeTypeHandle.GetTypeByNameUsingCARules( marshalTypeName, scope ); //// } //// catch(System.TypeLoadException) //// { //// // The user may have supplied a bad type name string causing this TypeLoadException //// // Regardless, we return the bad type name //// ASSERT.CONSISTENCY_CHECK( marshalTypeName != null ); //// } //// //// return new MarshalAsAttribute( //// unmanagedType, safeArraySubType, safeArrayUserDefinedType, arraySubType, //// (short)sizeParamIndex, sizeConst, marshalTypeName, marshalTypeRef, marshalCookie, iidParamIndex ); //// } //// //// internal MarshalAsAttribute( UnmanagedType val, VarEnum safeArraySubType, Type safeArrayUserDefinedSubType, UnmanagedType arraySubType, //// short sizeParamIndex, int sizeConst, string marshalType, Type marshalTypeRef, string marshalCookie, int iidParamIndex ) //// { //// m_val = val; ////#if FEATURE_COMINTEROP //// SafeArraySubType = safeArraySubType; //// SafeArrayUserDefinedSubType = safeArrayUserDefinedSubType; //// IidParameterIndex = iidParamIndex; ////#endif // FEATURE_COMINTEROP //// ArraySubType = arraySubType; //// SizeParamIndex = sizeParamIndex; //// SizeConst = sizeConst; //// MarshalType = marshalType; //// MarshalTypeRef = marshalTypeRef; //// MarshalCookie = marshalCookie; //// } internal UnmanagedType m_val; public MarshalAsAttribute( UnmanagedType unmanagedType ) { m_val = unmanagedType; } //// public MarshalAsAttribute( short unmanagedType ) //// { //// m_val = (UnmanagedType)unmanagedType; //// } public UnmanagedType Value { get { return m_val; } } ////#if FEATURE_COMINTEROP //// // Fields used with SubType = SafeArray. //// public VarEnum SafeArraySubType; //// public Type SafeArrayUserDefinedSubType; //// //// // Field used with iid_is attribute (interface pointers). //// public int IidParameterIndex; ////#endif // FEATURE_COMINTEROP //// //// // Fields used with SubType = ByValArray and LPArray. //// // Array size = parameter(PI) * PM + C //// public UnmanagedType ArraySubType; //// public short SizeParamIndex; // param index PI //// public int SizeConst; // constant C //// //// // Fields used with SubType = CustomMarshaler //// public String MarshalType; // Name of marshaler class //// public Type MarshalTypeRef; // Type of marshaler class //// public String MarshalCookie; // cookie to pass to marshaler } ////[AttributeUsage( AttributeTargets.Class | AttributeTargets.Interface, Inherited = false )] ////public sealed class ComImportAttribute : Attribute ////{ //// internal static Attribute GetCustomAttribute( RuntimeType type ) //// { //// if((type.Attributes & TypeAttributes.Import) == 0) //// { //// return null; //// } //// //// return new ComImportAttribute(); //// } //// //// internal static bool IsDefined( RuntimeType type ) //// { //// return (type.Attributes & TypeAttributes.Import) != 0; //// } //// //// public ComImportAttribute() //// { //// } ////} [AttributeUsage( AttributeTargets.Assembly | AttributeTargets.Interface | AttributeTargets.Class | AttributeTargets.Enum | AttributeTargets.Struct | AttributeTargets.Delegate, Inherited = false )] public sealed class GuidAttribute : Attribute { internal String m_val; public GuidAttribute( String guid ) { m_val = guid; } public String Value { get { return m_val; } } } ////[AttributeUsage( AttributeTargets.Method, Inherited = false )] ////public sealed class PreserveSigAttribute : Attribute ////{ //// internal static Attribute GetCustomAttribute( RuntimeMethodInfo method ) //// { //// if((method.GetMethodImplementationFlags() & MethodImplAttributes.PreserveSig) == 0) //// { //// return null; //// } //// //// return new PreserveSigAttribute(); //// } //// //// internal static bool IsDefined( RuntimeMethodInfo method ) //// { //// return (method.GetMethodImplementationFlags() & MethodImplAttributes.PreserveSig) != 0; //// } //// //// public PreserveSigAttribute() //// { //// } ////} [AttributeUsage( AttributeTargets.Parameter, Inherited = false )] public sealed class InAttribute : Attribute { //// internal static Attribute GetCustomAttribute( ParameterInfo parameter ) //// { //// return parameter.IsIn ? new InAttribute() : null; //// } //// //// internal static bool IsDefined( ParameterInfo parameter ) //// { //// return parameter.IsIn; //// } public InAttribute() { } } [AttributeUsage( AttributeTargets.Parameter, Inherited = false )] public sealed class OutAttribute : Attribute { //// internal static Attribute GetCustomAttribute( ParameterInfo parameter ) //// { //// return parameter.IsOut ? new OutAttribute() : null; //// } //// //// internal static bool IsDefined( ParameterInfo parameter ) //// { //// return parameter.IsOut; //// } public OutAttribute() { } } ////[AttributeUsage( AttributeTargets.Parameter, Inherited = false )] ////public sealed class OptionalAttribute : Attribute ////{ //// internal static Attribute GetCustomAttribute( ParameterInfo parameter ) //// { //// return parameter.IsOptional ? new OptionalAttribute() : null; //// } //// //// internal static bool IsDefined( ParameterInfo parameter ) //// { //// return parameter.IsOptional; //// } //// //// public OptionalAttribute() //// { //// } ////} [AttributeUsage( AttributeTargets.Method, Inherited = false )] public unsafe sealed class DllImportAttribute : Attribute { //// internal static Attribute GetCustomAttribute( RuntimeMethodInfo method ) //// { //// if((method.Attributes & MethodAttributes.PinvokeImpl) == 0) //// { //// return null; //// } //// //// MetadataImport scope = method.Module.ModuleHandle.GetMetadataImport(); //// string entryPoint; //// string dllName = null; //// int token = method.MetadataToken; //// PInvokeAttributes flags = 0; //// //// scope.GetPInvokeMap( token, out flags, out entryPoint, out dllName ); //// //// CharSet charSet = CharSet.None; //// //// switch(flags & PInvokeAttributes.CharSetMask) //// { //// case PInvokeAttributes.CharSetNotSpec: charSet = CharSet.None ; break; //// case PInvokeAttributes.CharSetAnsi : charSet = CharSet.Ansi ; break; //// case PInvokeAttributes.CharSetUnicode: charSet = CharSet.Unicode; break; //// case PInvokeAttributes.CharSetAuto : charSet = CharSet.Auto ; break; //// default: ASSERT.UNREACHABLE(); break; //// } //// //// CallingConvention callingConvention = CallingConvention.Cdecl; //// //// switch(flags & PInvokeAttributes.CallConvMask) //// { //// case PInvokeAttributes.CallConvWinapi : callingConvention = CallingConvention.Winapi ; break; //// case PInvokeAttributes.CallConvCdecl : callingConvention = CallingConvention.Cdecl ; break; //// case PInvokeAttributes.CallConvStdcall : callingConvention = CallingConvention.StdCall ; break; //// case PInvokeAttributes.CallConvThiscall: callingConvention = CallingConvention.ThisCall; break; //// case PInvokeAttributes.CallConvFastcall: callingConvention = CallingConvention.FastCall; break; //// //// default: ASSERT.UNREACHABLE(); break; //// } //// //// bool exactSpelling = (flags & PInvokeAttributes.NoMangle) != 0; //// bool setLastError = (flags & PInvokeAttributes.SupportsLastError) != 0; //// bool bestFitMapping = (flags & PInvokeAttributes.BestFitMask ) == PInvokeAttributes.BestFitEnabled; //// bool throwOnUnmappableChar = (flags & PInvokeAttributes.ThrowOnUnmappableCharMask) == PInvokeAttributes.ThrowOnUnmappableCharEnabled; //// bool preserveSig = (method.GetMethodImplementationFlags() & MethodImplAttributes.PreserveSig) != 0; //// //// return new DllImportAttribute( dllName, entryPoint, charSet, exactSpelling, setLastError, preserveSig, callingConvention, bestFitMapping, throwOnUnmappableChar ); //// } //// //// internal static bool IsDefined( RuntimeMethodInfo method ) //// { //// return (method.Attributes & MethodAttributes.PinvokeImpl) != 0; //// } //// //// //// internal DllImportAttribute( string dllName, string entryPoint, CharSet charSet, bool exactSpelling, bool setLastError, bool preserveSig, //// CallingConvention callingConvention, bool bestFitMapping, bool throwOnUnmappableChar ) //// { //// m_val = dllName; //// //// EntryPoint = entryPoint; //// CharSet = charSet; //// ExactSpelling = exactSpelling; //// SetLastError = setLastError; //// PreserveSig = preserveSig; //// CallingConvention = callingConvention; //// BestFitMapping = bestFitMapping; //// ThrowOnUnmappableChar = throwOnUnmappableChar; //// } internal String m_val; public DllImportAttribute( String dllName ) { m_val = dllName; } public String Value { get { return m_val; } } public String EntryPoint; public CharSet CharSet; public bool SetLastError; public bool ExactSpelling; public bool PreserveSig; public CallingConvention CallingConvention; public bool BestFitMapping; public bool ThrowOnUnmappableChar; } [AttributeUsage( AttributeTargets.Class | AttributeTargets.Struct, Inherited = false )] public unsafe sealed class StructLayoutAttribute : Attribute { //// private const int DEFAULT_PACKING_SIZE = 8; //// //// internal static Attribute GetCustomAttribute( Type type ) //// { //// if(!IsDefined( type )) //// { //// return null; //// } //// //// int pack = 0; //// int size = 0; //// //// LayoutKind layoutKind = LayoutKind.Auto; //// switch(type.Attributes & TypeAttributes.LayoutMask) //// { //// case TypeAttributes.ExplicitLayout : layoutKind = LayoutKind.Explicit ; break; //// case TypeAttributes.AutoLayout : layoutKind = LayoutKind.Auto ; break; //// case TypeAttributes.SequentialLayout: layoutKind = LayoutKind.Sequential; break; //// default: ASSERT.UNREACHABLE(); break; //// } //// //// CharSet charSet = CharSet.None; //// switch(type.Attributes & TypeAttributes.StringFormatMask) //// { //// case TypeAttributes.AnsiClass : charSet = CharSet.Ansi ; break; //// case TypeAttributes.AutoClass : charSet = CharSet.Auto ; break; //// case TypeAttributes.UnicodeClass: charSet = CharSet.Unicode; break; //// default: ASSERT.UNREACHABLE(); break; //// } //// //// type.Module.MetadataImport.GetClassLayout( type.MetadataToken, out pack, out size ); //// //// // Metadata parameter checking should not have allowed 0 for packing size. //// // The runtime later converts a packing size of 0 to 8 so do the same here //// // because it's more useful from a user perspective. //// if(pack == 0) //// { //// pack = DEFAULT_PACKING_SIZE; //// } //// //// return new StructLayoutAttribute( layoutKind, pack, size, charSet ); //// } //// //// internal static bool IsDefined( Type type ) //// { //// if(type.IsInterface || type.HasElementType || type.IsGenericParameter) //// { //// return false; //// } //// //// return true; //// } internal LayoutKind m_val; //// internal StructLayoutAttribute( LayoutKind layoutKind, int pack, int size, CharSet charSet ) //// { //// m_val = layoutKind; //// Pack = pack; //// Size = size; //// CharSet = charSet; //// } public StructLayoutAttribute( LayoutKind layoutKind ) { m_val = layoutKind; } //// public StructLayoutAttribute( short layoutKind ) //// { //// m_val = (LayoutKind)layoutKind; //// } public LayoutKind Value { get { return m_val; } } public int Pack; public int Size; public CharSet CharSet; } [Microsoft.Zelig.Internals.WellKnownType( "System_Runtime_InteropServices_FieldOffsetAttribute" )] [AttributeUsage( AttributeTargets.Field, Inherited = false )] public unsafe sealed class FieldOffsetAttribute : Attribute { //// internal static Attribute GetCustomAttribute( RuntimeFieldInfo field ) //// { //// int fieldOffset; //// //// if(field.DeclaringType != null && field.Module.MetadataImport.GetFieldOffset( field.DeclaringType.MetadataToken, field.MetadataToken, out fieldOffset )) //// { //// return new FieldOffsetAttribute( fieldOffset ); //// } //// //// return null; //// } //// //// internal static bool IsDefined( RuntimeFieldInfo field ) //// { //// return GetCustomAttribute( field ) != null; //// } internal int m_val; public FieldOffsetAttribute( int offset ) { m_val = offset; } public int Value { get { return m_val; } } } ////[AttributeUsage( AttributeTargets.Assembly | AttributeTargets.Interface | AttributeTargets.Class | AttributeTargets.Struct, Inherited = false )] ////public sealed class BestFitMappingAttribute : Attribute ////{ //// internal bool m_bestFitMapping; //// //// public BestFitMappingAttribute( bool BestFitMapping ) //// { //// m_bestFitMapping = BestFitMapping; //// } //// //// public bool BestFitMapping //// { //// get //// { //// return m_bestFitMapping; //// } //// } //// //// public bool ThrowOnUnmappableChar; ////} ////[AttributeUsage( AttributeTargets.Module, Inherited = false )] ////public sealed class DefaultCharSetAttribute : Attribute ////{ //// internal CharSet m_CharSet; //// //// public DefaultCharSetAttribute( CharSet charSet ) //// { //// m_CharSet = charSet; //// } //// //// public CharSet CharSet //// { //// get //// { //// return m_CharSet; //// } //// } ////} ////[Obsolete( "This attribute has been deprecated. Application Domains no longer respect Activation Context boundaries in IDispatch calls.", false )] ////[AttributeUsage( AttributeTargets.Assembly, Inherited = false )] ////public sealed class SetWin32ContextInIDispatchAttribute : Attribute ////{ //// public SetWin32ContextInIDispatchAttribute() //// { //// } ////} } ================================================ FILE: Zelig/Zelig/RunTime/Framework/mscorlib/System/Runtime/InteropServices/CallingConvention.cs ================================================ // ==++== // // Copyright (c) Microsoft Corporation. All rights reserved. // // ==--== //////////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////////// namespace System.Runtime.InteropServices { using System; // Used for the CallingConvention named argument to the DllImport attribute [Serializable] public enum CallingConvention { Winapi = 1, Cdecl = 2, StdCall = 3, ThisCall = 4, FastCall = 5, } } ================================================ FILE: Zelig/Zelig/RunTime/Framework/mscorlib/System/Runtime/InteropServices/CharSet.cs ================================================ // ==++== // // Copyright (c) Microsoft Corporation. All rights reserved. // // ==--== //////////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////////// namespace System.Runtime.InteropServices { using System; // Use this in P/Direct function prototypes to specify // which character set to use when marshalling Strings. // Using Ansi will marshal the strings as 1 byte char*'s. // Using Unicode will marshal the strings as 2 byte wchar*'s. // Generally you probably want to use Auto, which does the // right thing 99% of the time. [Serializable] public enum CharSet { None = 1, // User didn't specify how to marshal strings. Ansi = 2, // Strings should be marshalled as ANSI 1 byte chars. Unicode = 3, // Strings should be marshalled as Unicode 2 byte chars. Auto = 4, // Marshal Strings in the right way for the target system. } } ================================================ FILE: Zelig/Zelig/RunTime/Framework/mscorlib/System/Runtime/InteropServices/LayoutKind.cs ================================================ // ==++== // // Copyright (c) Microsoft Corporation. All rights reserved. // // ==--== //////////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////////// namespace System.Runtime.InteropServices { using System; // Used in the StructLayoutAttribute class [Serializable] public enum LayoutKind { Sequential = 0, // 0x00000008, Explicit = 2, // 0x00000010, Auto = 3, // 0x00000000, } } ================================================ FILE: Zelig/Zelig/RunTime/Framework/mscorlib/System/Runtime/InteropServices/Marshal.cs ================================================ // ==++== // // Copyright (c) Microsoft Corporation. All rights reserved. // // ==--== /*============================================================================= ** ** Class: Marshal ** ** ** Purpose: This class contains methods that are mainly used to marshal ** between unmanaged and managed types. ** ** =============================================================================*/ namespace System.Runtime.InteropServices { using System; using System.Collections.Generic; using System.Reflection; ////using System.Reflection.Emit; using System.Security; using System.Security.Permissions; using System.Text; using System.Threading; ////using System.Runtime.Remoting; ////using System.Runtime.Remoting.Activation; using System.Runtime.CompilerServices; ////using System.Runtime.Remoting.Proxies; using System.Globalization; using System.Runtime.ConstrainedExecution; ////using System.Runtime.Versioning; ////using Win32Native = Microsoft.Win32.Win32Native; ////using Microsoft.Win32.SafeHandles; //======================================================================== // All public methods, including PInvoke, are protected with linkchecks. // Remove the default demands for all PInvoke methods with this global // declaration on the class. //======================================================================== ////[SuppressUnmanagedCodeSecurityAttribute()] public static class Marshal { //// //==================================================================== //// // Defines used inside the Marshal class. //// //==================================================================== //// private const int LMEM_FIXED = 0; //// private const int LMEM_MOVEABLE = 2; //// private static readonly IntPtr HIWORDMASK = unchecked( new IntPtr( (long)0xffffffffffff0000L ) ); //// //// // Win32 has the concept of Atoms, where a pointer can either be a pointer //// // or an int. If it's less than 64K, this is guaranteed to NOT be a //// // pointer since the bottom 64K bytes are reserved in a process' page table. //// // We should be careful about deallocating this stuff. Extracted to //// // a function to avoid C# problems with lack of support for IntPtr. //// // We have 2 of these methods for slightly different semantics for NULL. //// private static bool IsWin32Atom( IntPtr ptr ) //// { //// long lPtr = (long)ptr; //// return 0 == (lPtr & (long)HIWORDMASK); //// } //// //// [ReliabilityContract( Consistency.WillNotCorruptState, Cer.Success )] //// private static bool IsNotWin32Atom( IntPtr ptr ) //// { //// long lPtr = (long)ptr; //// return 0 != (lPtr & (long)HIWORDMASK); //// } //// //// //==================================================================== //// // The default character size for the system. //// //==================================================================== //// public static readonly int SystemDefaultCharSize = 3 - Win32Native.lstrlen( new sbyte[] { 0x41, 0x41, 0, 0 } ); //// //// //==================================================================== //// // The max DBCS character size for the system. //// //==================================================================== //// public static readonly int SystemMaxDBCSCharSize = GetSystemMaxDBCSCharSize(); //// //// //// //==================================================================== //// // The name, title and description of the assembly that will contain //// // the dynamically generated interop types. //// //==================================================================== //// private const String s_strConvertedTypeInfoAssemblyName = "InteropDynamicTypes"; //// private const String s_strConvertedTypeInfoAssemblyTitle = "Interop Dynamic Types"; //// private const String s_strConvertedTypeInfoAssemblyDesc = "Type dynamically generated from ITypeInfo's"; //// private const String s_strConvertedTypeInfoNameSpace = "InteropDynamicTypes"; //// //// //// //==================================================================== //// // Helper method to retrieve the system's maximum DBCS character size. //// //==================================================================== //// [ResourceExposure( ResourceScope.None )] //// [MethodImplAttribute( MethodImplOptions.InternalCall )] //// private static extern int GetSystemMaxDBCSCharSize(); //// //// [SecurityPermissionAttribute( SecurityAction.LinkDemand, Flags = SecurityPermissionFlag.UnmanagedCode )] //// public static String PtrToStringAnsi( IntPtr ptr ) //// { //// if(Win32Native.NULL == ptr) //// { //// return null; //// } //// else if(IsWin32Atom( ptr )) //// { //// return null; //// } //// else //// { //// int nb = Win32Native.lstrlenA( ptr ); //// if(nb == 0) //// { //// return string.Empty; //// } //// else //// { //// StringBuilder sb = new StringBuilder( nb ); //// Win32Native.CopyMemoryAnsi( sb, ptr, new IntPtr( 1 + nb ) ); //// return sb.ToString(); //// } //// } //// } //// //// [ResourceExposure( ResourceScope.None )] //// [MethodImplAttribute( MethodImplOptions.InternalCall )] //// [SecurityPermissionAttribute( SecurityAction.LinkDemand, Flags = SecurityPermissionFlag.UnmanagedCode )] //// public static extern String PtrToStringAnsi( IntPtr ptr, int len ); //// //// [ResourceExposure( ResourceScope.None )] //// [MethodImplAttribute( MethodImplOptions.InternalCall )] //// [SecurityPermissionAttribute( SecurityAction.LinkDemand, Flags = SecurityPermissionFlag.UnmanagedCode )] //// public static extern String PtrToStringUni( IntPtr ptr, int len ); //// //// [SecurityPermissionAttribute( SecurityAction.LinkDemand, Flags = SecurityPermissionFlag.UnmanagedCode )] //// public static String PtrToStringAuto( IntPtr ptr, int len ) //// { //// return (SystemDefaultCharSize == 1) ? PtrToStringAnsi( ptr, len ) : PtrToStringUni( ptr, len ); //// } //// //// [SecurityPermissionAttribute( SecurityAction.LinkDemand, Flags = SecurityPermissionFlag.UnmanagedCode )] //// public static String PtrToStringUni( IntPtr ptr ) //// { //// if(Win32Native.NULL == ptr) //// { //// return null; //// } //// else if(IsWin32Atom( ptr )) //// { //// return null; //// } //// else //// { //// int nc = Win32Native.lstrlenW( ptr ); //// StringBuilder sb = new StringBuilder( nc ); //// Win32Native.CopyMemoryUni( sb, ptr, new IntPtr( 2 * (1 + nc) ) ); //// return sb.ToString(); //// } //// } //// //// [SecurityPermissionAttribute( SecurityAction.LinkDemand, Flags = SecurityPermissionFlag.UnmanagedCode )] //// public static String PtrToStringAuto( IntPtr ptr ) //// { //// if(Win32Native.NULL == ptr) //// { //// return null; //// } //// else if(IsWin32Atom( ptr )) //// { //// return null; //// } //// else //// { //// int nc = Win32Native.lstrlen( ptr ); //// StringBuilder sb = new StringBuilder( nc ); //// Win32Native.lstrcpy( sb, ptr ); //// return sb.ToString(); //// } //// } //==================================================================== // SizeOf() //==================================================================== //// [ResourceExposure( ResourceScope.None )] [MethodImplAttribute( MethodImplOptions.InternalCall )] //// [SecurityPermissionAttribute( SecurityAction.LinkDemand, Flags = SecurityPermissionFlag.UnmanagedCode )] public static extern int SizeOf( Object structure ); //// [ResourceExposure( ResourceScope.None )] [MethodImplAttribute( MethodImplOptions.InternalCall )] //// [SecurityPermissionAttribute( SecurityAction.LinkDemand, Flags = SecurityPermissionFlag.UnmanagedCode )] public static extern int SizeOf( Type t ); //// //==================================================================== //// // OffsetOf() //// //==================================================================== //// [SecurityPermissionAttribute( SecurityAction.LinkDemand, Flags = SecurityPermissionFlag.UnmanagedCode )] //// public static IntPtr OffsetOf( Type t, String fieldName ) //// { //// if(t == null) //// throw new ArgumentNullException( "t" ); //// //// FieldInfo f = t.GetField( fieldName, BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic ); //// if(f == null) //// throw new ArgumentException( Environment.GetResourceString( "Argument_OffsetOfFieldNotFound", t.FullName ), "fieldName" ); //// else if(!(f is RuntimeFieldInfo)) //// throw new ArgumentException( Environment.GetResourceString( "Argument_MustBeRuntimeFieldInfo" ), "fieldName" ); //// //// return OffsetOfHelper( ((RuntimeFieldInfo)f).GetFieldHandle().Value ); //// } //// [ResourceExposure( ResourceScope.None )] //// [MethodImplAttribute( MethodImplOptions.InternalCall )] //// private static extern IntPtr OffsetOfHelper( IntPtr f ); //// //// //==================================================================== //// // UnsafeAddrOfPinnedArrayElement() //// // //// // IMPORTANT NOTICE: This method does not do any verification on the //// // array. It must be used with EXTREME CAUTION since passing in //// // an array that is not pinned or in the fixed heap can cause //// // unexpected results ! //// //==================================================================== //// [ResourceExposure( ResourceScope.None )] //// [MethodImplAttribute( MethodImplOptions.InternalCall )] //// [SecurityPermissionAttribute( SecurityAction.LinkDemand, Flags = SecurityPermissionFlag.UnmanagedCode )] //// public static extern IntPtr UnsafeAddrOfPinnedArrayElement( Array arr, int index ); //// //// //// //==================================================================== //// // Copy blocks from CLR arrays to native memory. //// //==================================================================== //// [SecurityPermissionAttribute( SecurityAction.LinkDemand, Flags = SecurityPermissionFlag.UnmanagedCode )] //// public static void Copy( int[] source, int startIndex, IntPtr destination, int length ) //// { //// CopyToNative( source, startIndex, destination, length ); //// } //// [SecurityPermissionAttribute( SecurityAction.LinkDemand, Flags = SecurityPermissionFlag.UnmanagedCode )] //// public static void Copy( char[] source, int startIndex, IntPtr destination, int length ) //// { //// CopyToNative( source, startIndex, destination, length ); //// } //// [SecurityPermissionAttribute( SecurityAction.LinkDemand, Flags = SecurityPermissionFlag.UnmanagedCode )] //// public static void Copy( short[] source, int startIndex, IntPtr destination, int length ) //// { //// CopyToNative( source, startIndex, destination, length ); //// } //// [SecurityPermissionAttribute( SecurityAction.LinkDemand, Flags = SecurityPermissionFlag.UnmanagedCode )] //// public static void Copy( long[] source, int startIndex, IntPtr destination, int length ) //// { //// CopyToNative( source, startIndex, destination, length ); //// } //// [SecurityPermissionAttribute( SecurityAction.LinkDemand, Flags = SecurityPermissionFlag.UnmanagedCode )] //// public static void Copy( float[] source, int startIndex, IntPtr destination, int length ) //// { //// CopyToNative( source, startIndex, destination, length ); //// } //// [SecurityPermissionAttribute( SecurityAction.LinkDemand, Flags = SecurityPermissionFlag.UnmanagedCode )] //// public static void Copy( double[] source, int startIndex, IntPtr destination, int length ) //// { //// CopyToNative( source, startIndex, destination, length ); //// } //// [SecurityPermissionAttribute( SecurityAction.LinkDemand, Flags = SecurityPermissionFlag.UnmanagedCode )] //// public static void Copy( byte[] source, int startIndex, IntPtr destination, int length ) //// { //// CopyToNative( source, startIndex, destination, length ); //// } //// [SecurityPermissionAttribute( SecurityAction.LinkDemand, Flags = SecurityPermissionFlag.UnmanagedCode )] //// public static void Copy( IntPtr[] source, int startIndex, IntPtr destination, int length ) //// { //// CopyToNative( source, startIndex, destination, length ); //// } //// [ResourceExposure( ResourceScope.None )] //// [MethodImplAttribute( MethodImplOptions.InternalCall )] //// private static extern void CopyToNative( Object source, int startIndex, IntPtr destination, int length ); //// //// //==================================================================== //// // Copy blocks from native memory to CLR arrays //// //==================================================================== //// [SecurityPermissionAttribute( SecurityAction.LinkDemand, Flags = SecurityPermissionFlag.UnmanagedCode )] //// public static void Copy( IntPtr source, int[] destination, int startIndex, int length ) //// { //// CopyToManaged( source, destination, startIndex, length ); //// } //// [SecurityPermissionAttribute( SecurityAction.LinkDemand, Flags = SecurityPermissionFlag.UnmanagedCode )] //// public static void Copy( IntPtr source, char[] destination, int startIndex, int length ) //// { //// CopyToManaged( source, destination, startIndex, length ); //// } //// [SecurityPermissionAttribute( SecurityAction.LinkDemand, Flags = SecurityPermissionFlag.UnmanagedCode )] //// public static void Copy( IntPtr source, short[] destination, int startIndex, int length ) //// { //// CopyToManaged( source, destination, startIndex, length ); //// } //// [SecurityPermissionAttribute( SecurityAction.LinkDemand, Flags = SecurityPermissionFlag.UnmanagedCode )] //// public static void Copy( IntPtr source, long[] destination, int startIndex, int length ) //// { //// CopyToManaged( source, destination, startIndex, length ); //// } //// [SecurityPermissionAttribute( SecurityAction.LinkDemand, Flags = SecurityPermissionFlag.UnmanagedCode )] //// public static void Copy( IntPtr source, float[] destination, int startIndex, int length ) //// { //// CopyToManaged( source, destination, startIndex, length ); //// } //// [SecurityPermissionAttribute( SecurityAction.LinkDemand, Flags = SecurityPermissionFlag.UnmanagedCode )] //// public static void Copy( IntPtr source, double[] destination, int startIndex, int length ) //// { //// CopyToManaged( source, destination, startIndex, length ); //// } //// [SecurityPermissionAttribute( SecurityAction.LinkDemand, Flags = SecurityPermissionFlag.UnmanagedCode )] //// public static void Copy( IntPtr source, byte[] destination, int startIndex, int length ) //// { //// CopyToManaged( source, destination, startIndex, length ); //// } //// [SecurityPermissionAttribute( SecurityAction.LinkDemand, Flags = SecurityPermissionFlag.UnmanagedCode )] //// public static void Copy( IntPtr source, IntPtr[] destination, int startIndex, int length ) //// { //// CopyToManaged( source, destination, startIndex, length ); //// } //// [ResourceExposure( ResourceScope.None )] //// [MethodImplAttribute( MethodImplOptions.InternalCall )] //// private static extern void CopyToManaged( IntPtr source, Object destination, int startIndex, int length ); //// //// //==================================================================== //// // Read from memory //// //==================================================================== //// [DllImport( Win32Native.SHIM, EntryPoint = "ND_RU1" )] //// [ResourceExposure( ResourceScope.None )] //// public static extern byte ReadByte( [MarshalAs( UnmanagedType.AsAny ), In] Object ptr, int ofs ); //// //// [DllImport( Win32Native.SHIM, EntryPoint = "ND_RU1" )] //// [ResourceExposure( ResourceScope.None )] //// public static extern byte ReadByte( IntPtr ptr, int ofs ); //// //// [SecurityPermissionAttribute( SecurityAction.LinkDemand, Flags = SecurityPermissionFlag.UnmanagedCode )] //// public static byte ReadByte( IntPtr ptr ) //// { //// return ReadByte( ptr, 0 ); //// } //// //// [DllImport( Win32Native.SHIM, EntryPoint = "ND_RI2" )] //// [ResourceExposure( ResourceScope.None )] //// public static extern short ReadInt16( [MarshalAs( UnmanagedType.AsAny ), In] Object ptr, int ofs ); //// //// [DllImport( Win32Native.SHIM, EntryPoint = "ND_RI2" )] //// [ResourceExposure( ResourceScope.None )] //// public static extern short ReadInt16( IntPtr ptr, int ofs ); //// //// [SecurityPermissionAttribute( SecurityAction.LinkDemand, Flags = SecurityPermissionFlag.UnmanagedCode )] //// public static short ReadInt16( IntPtr ptr ) //// { //// return ReadInt16( ptr, 0 ); //// } //// //// [DllImport( Win32Native.SHIM, EntryPoint = "ND_RI4" ), ReliabilityContract( Consistency.WillNotCorruptState, Cer.Success )] //// [ResourceExposure( ResourceScope.None )] //// public static extern int ReadInt32( [MarshalAs( UnmanagedType.AsAny ), In] Object ptr, int ofs ); //// //// [DllImport( Win32Native.SHIM, EntryPoint = "ND_RI4" ), ReliabilityContract( Consistency.WillNotCorruptState, Cer.Success )] //// [ResourceExposure( ResourceScope.None )] //// public static extern int ReadInt32( IntPtr ptr, int ofs ); //// //// [SecurityPermissionAttribute( SecurityAction.LinkDemand, Flags = SecurityPermissionFlag.UnmanagedCode ), ReliabilityContract( Consistency.WillNotCorruptState, Cer.Success )] //// public static int ReadInt32( IntPtr ptr ) //// { //// return ReadInt32( ptr, 0 ); //// } //// //// [SecurityPermissionAttribute( SecurityAction.LinkDemand, Flags = SecurityPermissionFlag.UnmanagedCode ), ReliabilityContract( Consistency.WillNotCorruptState, Cer.Success )] //// public static IntPtr ReadIntPtr( [MarshalAs( UnmanagedType.AsAny ), In] Object ptr, int ofs ) //// { //// return (IntPtr) ReadInt32(ptr, ofs); //// } //// //// [SecurityPermissionAttribute( SecurityAction.LinkDemand, Flags = SecurityPermissionFlag.UnmanagedCode ), ReliabilityContract( Consistency.WillNotCorruptState, Cer.Success )] //// public static IntPtr ReadIntPtr( IntPtr ptr, int ofs ) //// { //// return (IntPtr) ReadInt32(ptr, ofs); //// } //// //// [SecurityPermissionAttribute( SecurityAction.LinkDemand, Flags = SecurityPermissionFlag.UnmanagedCode ), ReliabilityContract( Consistency.WillNotCorruptState, Cer.Success )] //// public static IntPtr ReadIntPtr( IntPtr ptr ) //// { //// return (IntPtr) ReadInt32(ptr, 0); //// } //// //// [DllImport( Win32Native.SHIM, EntryPoint = "ND_RI8" ), ReliabilityContract( Consistency.WillNotCorruptState, Cer.Success )] //// [ResourceExposure( ResourceScope.None )] //// public static extern long ReadInt64( [MarshalAs( UnmanagedType.AsAny ), In] Object ptr, int ofs ); //// //// [DllImport( Win32Native.SHIM, EntryPoint = "ND_RI8" ), ReliabilityContract( Consistency.WillNotCorruptState, Cer.Success )] //// [ResourceExposure( ResourceScope.None )] //// public static extern long ReadInt64( IntPtr ptr, int ofs ); //// //// [SecurityPermissionAttribute( SecurityAction.LinkDemand, Flags = SecurityPermissionFlag.UnmanagedCode ), ReliabilityContract( Consistency.WillNotCorruptState, Cer.Success )] //// public static long ReadInt64( IntPtr ptr ) //// { //// return ReadInt64( ptr, 0 ); //// } //// //// //// //==================================================================== //// // Write to memory //// //==================================================================== //// [DllImport( Win32Native.SHIM, EntryPoint = "ND_WU1" )] //// [ResourceExposure( ResourceScope.None )] //// public static extern void WriteByte( IntPtr ptr, int ofs, byte val ); //// //// [DllImport( Win32Native.SHIM, EntryPoint = "ND_WU1" )] //// [ResourceExposure( ResourceScope.None )] //// public static extern void WriteByte( [MarshalAs( UnmanagedType.AsAny ), In, Out] Object ptr, int ofs, byte val ); //// //// [SecurityPermissionAttribute( SecurityAction.LinkDemand, Flags = SecurityPermissionFlag.UnmanagedCode )] //// public static void WriteByte( IntPtr ptr, byte val ) //// { //// WriteByte( ptr, 0, val ); //// } //// //// [DllImport( Win32Native.SHIM, EntryPoint = "ND_WI2" )] //// [ResourceExposure( ResourceScope.None )] //// public static extern void WriteInt16( IntPtr ptr, int ofs, short val ); //// //// [DllImport( Win32Native.SHIM, EntryPoint = "ND_WI2" )] //// [ResourceExposure( ResourceScope.None )] //// public static extern void WriteInt16( [MarshalAs( UnmanagedType.AsAny ), In, Out] Object ptr, int ofs, short val ); //// //// [SecurityPermissionAttribute( SecurityAction.LinkDemand, Flags = SecurityPermissionFlag.UnmanagedCode )] //// public static void WriteInt16( IntPtr ptr, short val ) //// { //// WriteInt16( ptr, 0, val ); //// } //// //// [SecurityPermissionAttribute( SecurityAction.LinkDemand, Flags = SecurityPermissionFlag.UnmanagedCode )] //// public static void WriteInt16( IntPtr ptr, int ofs, char val ) //// { //// WriteInt16( ptr, ofs, (short)val ); //// } //// //// [SecurityPermissionAttribute( SecurityAction.LinkDemand, Flags = SecurityPermissionFlag.UnmanagedCode )] //// public static void WriteInt16( [In, Out]Object ptr, int ofs, char val ) //// { //// WriteInt16( ptr, ofs, (short)val ); //// } //// //// [SecurityPermissionAttribute( SecurityAction.LinkDemand, Flags = SecurityPermissionFlag.UnmanagedCode )] //// public static void WriteInt16( IntPtr ptr, char val ) //// { //// WriteInt16( ptr, 0, (short)val ); //// } //// //// [DllImport( Win32Native.SHIM, EntryPoint = "ND_WI4" )] //// [ResourceExposure( ResourceScope.None )] //// public static extern void WriteInt32( IntPtr ptr, int ofs, int val ); //// //// [DllImport( Win32Native.SHIM, EntryPoint = "ND_WI4" )] //// [ResourceExposure( ResourceScope.None )] //// public static extern void WriteInt32( [MarshalAs( UnmanagedType.AsAny ), In, Out] Object ptr, int ofs, int val ); //// //// [SecurityPermissionAttribute( SecurityAction.LinkDemand, Flags = SecurityPermissionFlag.UnmanagedCode )] //// public static void WriteInt32( IntPtr ptr, int val ) //// { //// WriteInt32( ptr, 0, val ); //// } //// //// [SecurityPermissionAttribute( SecurityAction.LinkDemand, Flags = SecurityPermissionFlag.UnmanagedCode )] //// public static void WriteIntPtr( IntPtr ptr, int ofs, IntPtr val ) //// { //// WriteInt32(ptr, ofs, (int)val); //// } //// //// [SecurityPermissionAttribute( SecurityAction.LinkDemand, Flags = SecurityPermissionFlag.UnmanagedCode )] //// public static void WriteIntPtr( [MarshalAs( UnmanagedType.AsAny ), In, Out] Object ptr, int ofs, IntPtr val ) //// { //// WriteInt32(ptr, ofs, (int)val); //// } //// //// [SecurityPermissionAttribute( SecurityAction.LinkDemand, Flags = SecurityPermissionFlag.UnmanagedCode )] //// public static void WriteIntPtr( IntPtr ptr, IntPtr val ) //// { //// WriteInt32(ptr, 0, (int)val); //// } //// //// [DllImport( Win32Native.SHIM, EntryPoint = "ND_WI8" )] //// [ResourceExposure( ResourceScope.None )] //// public static extern void WriteInt64( IntPtr ptr, int ofs, long val ); //// //// [DllImport( Win32Native.SHIM, EntryPoint = "ND_WI8" )] //// [ResourceExposure( ResourceScope.None )] //// public static extern void WriteInt64( [MarshalAs( UnmanagedType.AsAny ), In, Out] Object ptr, int ofs, long val ); //// //// [SecurityPermissionAttribute( SecurityAction.LinkDemand, Flags = SecurityPermissionFlag.UnmanagedCode )] //// public static void WriteInt64( IntPtr ptr, long val ) //// { //// WriteInt64( ptr, 0, val ); //// } //// //// //// //==================================================================== //// // GetLastWin32Error //// //==================================================================== //// [ResourceExposure( ResourceScope.None )] //// [MethodImplAttribute( MethodImplOptions.InternalCall )] //// [SecurityPermissionAttribute( SecurityAction.LinkDemand, Flags = SecurityPermissionFlag.UnmanagedCode )] //// [ReliabilityContract( Consistency.WillNotCorruptState, Cer.Success )] //// public static extern int GetLastWin32Error(); //// //// //// //==================================================================== //// // SetLastWin32Error //// //==================================================================== //// [ResourceExposure( ResourceScope.None )] //// [MethodImplAttribute( MethodImplOptions.InternalCall )] //// [ReliabilityContract( Consistency.WillNotCorruptState, Cer.Success )] //// internal static extern void SetLastWin32Error( int error ); //// //// //// //==================================================================== //// // GetHRForLastWin32Error //// //==================================================================== //// [SecurityPermissionAttribute( SecurityAction.LinkDemand, Flags = SecurityPermissionFlag.UnmanagedCode )] //// [ReliabilityContract( Consistency.WillNotCorruptState, Cer.Success )] //// public static int GetHRForLastWin32Error() //// { //// int dwLastError = GetLastWin32Error(); //// if((dwLastError & 0x80000000) == 0x80000000) //// return dwLastError; //// else //// return (dwLastError & 0x0000FFFF) | unchecked( (int)0x80070000 ); //// } //// //// //// //==================================================================== //// // Prelink //// //==================================================================== //// [SecurityPermissionAttribute( SecurityAction.LinkDemand, Flags = SecurityPermissionFlag.UnmanagedCode )] //// public static void Prelink( MethodInfo m ) //// { //// if(m == null) //// throw new ArgumentNullException( "m" ); //// //// if(!(m is RuntimeMethodInfo)) //// throw new ArgumentException( Environment.GetResourceString( "Argument_MustBeRuntimeMethodInfo" ) ); //// //// RuntimeMethodHandle method = m.MethodHandle; //// //// InternalPrelink( method.Value ); //// } //// //// [ResourceExposure( ResourceScope.None )] //// [MethodImplAttribute( MethodImplOptions.InternalCall )] //// private static extern void InternalPrelink( IntPtr m ); //// //// [SecurityPermissionAttribute( SecurityAction.LinkDemand, Flags = SecurityPermissionFlag.UnmanagedCode )] //// public static void PrelinkAll( Type c ) //// { //// if(c == null) //// throw new ArgumentNullException( "c" ); //// //// MethodInfo[] mi = c.GetMethods(); //// if(mi != null) //// { //// for(int i = 0; i < mi.Length; i++) //// { //// Prelink( mi[i] ); //// } //// } //// } //// //// //==================================================================== //// // NumParamBytes //// //==================================================================== //// [SecurityPermissionAttribute( SecurityAction.LinkDemand, Flags = SecurityPermissionFlag.UnmanagedCode )] //// public static int NumParamBytes( MethodInfo m ) //// { //// if(m == null) //// throw new ArgumentNullException( "m" ); //// //// if(!(m is RuntimeMethodInfo)) //// throw new ArgumentException( Environment.GetResourceString( "Argument_MustBeRuntimeMethodInfo" ) ); //// //// RuntimeMethodHandle method = m.GetMethodHandle(); //// //// return InternalNumParamBytes( method.Value ); //// } //// //// [ResourceExposure( ResourceScope.None )] //// [MethodImplAttribute( MethodImplOptions.InternalCall )] //// private static extern int InternalNumParamBytes( IntPtr m ); //// //// //==================================================================== //// // Win32 Exception stuff //// // These are mostly interesting for Structured exception handling, //// // but need to be exposed for all exceptions (not just SEHException). //// //==================================================================== //// [ResourceExposure( ResourceScope.None )] //// [MethodImplAttribute( MethodImplOptions.InternalCall )] //// [SecurityPermissionAttribute( SecurityAction.LinkDemand, Flags = SecurityPermissionFlag.UnmanagedCode )] //// public static extern /* struct _EXCEPTION_POINTERS* */ IntPtr GetExceptionPointers(); //// //// [ResourceExposure( ResourceScope.None )] //// [MethodImplAttribute( MethodImplOptions.InternalCall )] //// [SecurityPermissionAttribute( SecurityAction.LinkDemand, Flags = SecurityPermissionFlag.UnmanagedCode )] //// public static extern int GetExceptionCode(); //// //// //// //==================================================================== //// // Marshals data from a structure class to a native memory block. //// // If the structure contains pointers to allocated blocks and //// // "fDeleteOld" is true, this routine will call DestroyStructure() first. //// //==================================================================== //// [ResourceExposure( ResourceScope.None )] //// [MethodImplAttribute( MethodImplOptions.InternalCall ), ReliabilityContract( Consistency.WillNotCorruptState, Cer.MayFail )] //// [SecurityPermissionAttribute( SecurityAction.LinkDemand, Flags = SecurityPermissionFlag.UnmanagedCode )] //// public static extern void StructureToPtr( Object structure, IntPtr ptr, bool fDeleteOld ); //// //// //// //==================================================================== //// // Marshals data from a native memory block to a preallocated structure class. //// //==================================================================== //// [SecurityPermissionAttribute( SecurityAction.LinkDemand, Flags = SecurityPermissionFlag.UnmanagedCode )] //// public static void PtrToStructure( IntPtr ptr, Object structure ) //// { //// PtrToStructureHelper( ptr, structure, false ); //// } //// //// //// //==================================================================== //// // Creates a new instance of "structuretype" and marshals data from a //// // native memory block to it. //// //==================================================================== //// [SecurityPermissionAttribute( SecurityAction.LinkDemand, Flags = SecurityPermissionFlag.UnmanagedCode )] //// public static Object PtrToStructure( IntPtr ptr, Type structureType ) //// { //// if(ptr == Win32Native.NULL) return null; //// //// if(structureType == null) //// throw new ArgumentNullException( "structureType" ); //// //// if(structureType.IsGenericType) //// throw new ArgumentException( Environment.GetResourceString( "Argument_NeedNonGenericType" ), "structureType" ); //// //// Object structure = Activator.InternalCreateInstanceWithNoMemberAccessCheck( structureType, true ); //// PtrToStructureHelper( ptr, structure, true ); //// return structure; //// } //// //// //// //==================================================================== //// // Helper function to copy a pointer into a preallocated structure. //// //==================================================================== //// [ResourceExposure( ResourceScope.None )] //// [MethodImplAttribute( MethodImplOptions.InternalCall )] //// private static extern void PtrToStructureHelper( IntPtr ptr, Object structure, bool allowValueClasses ); //// //// //// //==================================================================== //// // Freeds all substructures pointed to by the native memory block. //// // "structureclass" is used to provide layout information. //// //==================================================================== //// [ResourceExposure( ResourceScope.None )] //// [MethodImplAttribute( MethodImplOptions.InternalCall )] //// [SecurityPermissionAttribute( SecurityAction.LinkDemand, Flags = SecurityPermissionFlag.UnmanagedCode )] //// public static extern void DestroyStructure( IntPtr ptr, Type structuretype ); //// //// //// //==================================================================== //// // Returns the HInstance for this module. Returns -1 if the module //// // doesn't have an HInstance. In Memory (Dynamic) Modules won't have //// // an HInstance. //// //==================================================================== //// [SecurityPermissionAttribute( SecurityAction.LinkDemand, Flags = SecurityPermissionFlag.UnmanagedCode )] //// [ResourceExposure( ResourceScope.Machine )] //// [ResourceConsumption( ResourceScope.Machine )] //// public static IntPtr GetHINSTANCE( Module m ) //// { //// if(m == null) //// throw new ArgumentNullException( "m" ); //// return GetHINSTANCE( m.GetNativeHandle() ); //// } //// //// [ResourceExposure( ResourceScope.Machine )] //// [DllImport( JitHelpers.QCall, CharSet = CharSet.Unicode ), SuppressUnmanagedCodeSecurity] //// private extern static IntPtr GetHINSTANCE( ModuleHandle m ); //// //// //==================================================================== //// // Throws a CLR exception based on the HRESULT. //// //==================================================================== //// [SecurityPermissionAttribute( SecurityAction.LinkDemand, Flags = SecurityPermissionFlag.UnmanagedCode )] //// public static void ThrowExceptionForHR( int errorCode ) //// { //// if(errorCode < 0) //// ThrowExceptionForHRInternal( errorCode, Win32Native.NULL ); //// } //// [SecurityPermissionAttribute( SecurityAction.LinkDemand, Flags = SecurityPermissionFlag.UnmanagedCode )] //// public static void ThrowExceptionForHR( int errorCode, IntPtr errorInfo ) //// { //// if(errorCode < 0) //// ThrowExceptionForHRInternal( errorCode, errorInfo ); //// } //// //// [ResourceExposure( ResourceScope.None )] //// [MethodImplAttribute( MethodImplOptions.InternalCall )] //// internal static extern void ThrowExceptionForHRInternal( int errorCode, IntPtr errorInfo ); //// //// //// //==================================================================== //// // Converts the HRESULT to a CLR exception. //// //==================================================================== //// [SecurityPermissionAttribute( SecurityAction.LinkDemand, Flags = SecurityPermissionFlag.UnmanagedCode )] //// public static Exception GetExceptionForHR( int errorCode ) //// { //// if(errorCode < 0) //// return GetExceptionForHRInternal( errorCode, Win32Native.NULL ); //// else //// return null; //// } //// [SecurityPermissionAttribute( SecurityAction.LinkDemand, Flags = SecurityPermissionFlag.UnmanagedCode )] //// public static Exception GetExceptionForHR( int errorCode, IntPtr errorInfo ) //// { //// if(errorCode < 0) //// return GetExceptionForHRInternal( errorCode, errorInfo ); //// else //// return null; //// } //// //// [ResourceExposure( ResourceScope.None )] //// [MethodImplAttribute( MethodImplOptions.InternalCall )] //// internal static extern Exception GetExceptionForHRInternal( int errorCode, IntPtr errorInfo ); //// //// //// //==================================================================== //// // Converts the CLR exception to an HRESULT. This function also sets //// // up an IErrorInfo for the exception. //// //==================================================================== //// [ResourceExposure( ResourceScope.None )] //// [MethodImplAttribute( MethodImplOptions.InternalCall )] //// [SecurityPermissionAttribute( SecurityAction.LinkDemand, Flags = SecurityPermissionFlag.UnmanagedCode )] //// public static extern int GetHRForException( Exception e ); //// //// //==================================================================== //// // This method is intended for compiler code generators rather //// // than applications. //// //==================================================================== //// // REVIEW: This is not in the obsolete list to be removed for Whidbey! //// [ObsoleteAttribute( "The GetUnmanagedThunkForManagedMethodPtr method has been deprecated and will be removed in a future release.", false )] //// [ResourceExposure( ResourceScope.None )] //// [MethodImplAttribute( MethodImplOptions.InternalCall )] //// [SecurityPermissionAttribute( SecurityAction.LinkDemand, Flags = SecurityPermissionFlag.UnmanagedCode )] //// public static extern IntPtr GetUnmanagedThunkForManagedMethodPtr( IntPtr pfnMethodToWrap, IntPtr pbSignature, int cbSignature ); //// //// //==================================================================== //// // This method is intended for compiler code generators rather //// // than applications. //// //==================================================================== //// // REVIEW: This is not in the obsolete list to be removed for Whidbey! //// [ObsoleteAttribute( "The GetManagedThunkForUnmanagedMethodPtr method has been deprecated and will be removed in a future release.", false )] //// [ResourceExposure( ResourceScope.None )] //// [MethodImplAttribute( MethodImplOptions.InternalCall )] //// [SecurityPermissionAttribute( SecurityAction.LinkDemand, Flags = SecurityPermissionFlag.UnmanagedCode )] //// public static extern IntPtr GetManagedThunkForUnmanagedMethodPtr( IntPtr pfnMethodToWrap, IntPtr pbSignature, int cbSignature ); //// //// //==================================================================== //// // The hosting APIs allow a sophisticated host to schedule fibers //// // onto OS threads, so long as they notify the runtime of this //// // activity. A fiber cookie can be redeemed for its managed Thread //// // object by calling the following service. //// //==================================================================== //// // REVIEW: This is not in the obsolete list to be removed for Whidbey! //// [ObsoleteAttribute( "The GetThreadFromFiberCookie method has been deprecated. Use the hosting API to perform this operation.", false )] //// [SecurityPermissionAttribute( SecurityAction.LinkDemand, Flags = SecurityPermissionFlag.UnmanagedCode )] //// public static Thread GetThreadFromFiberCookie( int cookie ) //// { //// if(cookie == 0) //// throw new ArgumentException( Environment.GetResourceString( "Argument_ArgumentZero" ), "cookie" ); //// //// return InternalGetThreadFromFiberCookie( cookie ); //// } //// //// [ResourceExposure( ResourceScope.None )] //// [MethodImplAttribute( MethodImplOptions.InternalCall )] //// private static extern Thread InternalGetThreadFromFiberCookie( int cookie ); //// //// //// //==================================================================== //// // Memory allocation and dealocation. //// //==================================================================== //// [SecurityPermissionAttribute( SecurityAction.LinkDemand, Flags = SecurityPermissionFlag.UnmanagedCode )] //// [ReliabilityContract( Consistency.WillNotCorruptState, Cer.MayFail )] //// public static IntPtr AllocHGlobal( IntPtr cb ) //// { //// IntPtr pNewMem = Win32Native.LocalAlloc_NoSafeHandle( LMEM_FIXED, cb ); //// //// if(pNewMem == Win32Native.NULL) //// { //// throw new OutOfMemoryException(); //// } //// return pNewMem; //// } //// //// [SecurityPermissionAttribute( SecurityAction.LinkDemand, Flags = SecurityPermissionFlag.UnmanagedCode )] //// [ReliabilityContract( Consistency.WillNotCorruptState, Cer.MayFail )] //// public static IntPtr AllocHGlobal( int cb ) //// { //// return AllocHGlobal( (IntPtr)cb ); //// } //// //// [SecurityPermissionAttribute( SecurityAction.LinkDemand, Flags = SecurityPermissionFlag.UnmanagedCode )] //// [ReliabilityContract( Consistency.WillNotCorruptState, Cer.Success )] //// public static void FreeHGlobal( IntPtr hglobal ) //// { //// if(IsNotWin32Atom( hglobal )) //// { //// if(Win32Native.NULL != Win32Native.LocalFree( hglobal )) //// { //// ThrowExceptionForHR( GetHRForLastWin32Error() ); //// } //// } //// } //// //// [SecurityPermissionAttribute( SecurityAction.LinkDemand, Flags = SecurityPermissionFlag.UnmanagedCode )] //// public static IntPtr ReAllocHGlobal( IntPtr pv, IntPtr cb ) //// { //// IntPtr pNewMem = Win32Native.LocalReAlloc( pv, cb, LMEM_MOVEABLE ); //// if(pNewMem == Win32Native.NULL) //// { //// throw new OutOfMemoryException(); //// } //// return pNewMem; //// } //// //// //// //==================================================================== //// // String convertions. //// //==================================================================== //// [SecurityPermissionAttribute( SecurityAction.LinkDemand, Flags = SecurityPermissionFlag.UnmanagedCode )] //// public static IntPtr StringToHGlobalAnsi( String s ) //// { //// if(s == null) //// { //// return Win32Native.NULL; //// } //// else //// { //// int nb = (s.Length + 1) * SystemMaxDBCSCharSize; //// //// // Overflow checking //// if(nb < s.Length) //// throw new ArgumentOutOfRangeException( "s" ); //// //// IntPtr len = new IntPtr( nb ); //// IntPtr hglobal = Win32Native.LocalAlloc_NoSafeHandle( LMEM_FIXED, len ); //// //// if(hglobal == Win32Native.NULL) //// { //// throw new OutOfMemoryException(); //// } //// else //// { //// Win32Native.CopyMemoryAnsi( hglobal, s, len ); //// return hglobal; //// } //// } //// } //// //// [SecurityPermissionAttribute( SecurityAction.LinkDemand, Flags = SecurityPermissionFlag.UnmanagedCode )] //// public static IntPtr StringToCoTaskMemAnsi( String s ) //// { //// if(s == null) //// { //// return Win32Native.NULL; //// } //// else //// { //// int nb = (s.Length + 1) * SystemMaxDBCSCharSize; //// //// // Overflow checking //// if(nb < s.Length) //// throw new ArgumentOutOfRangeException( "s" ); //// //// IntPtr hglobal = Win32Native.CoTaskMemAlloc( nb ); //// //// if(hglobal == Win32Native.NULL) //// { //// throw new OutOfMemoryException(); //// } //// else //// { //// Win32Native.CopyMemoryAnsi( hglobal, s, new IntPtr( nb ) ); //// return hglobal; //// } //// } //// } //// //// [SecurityPermissionAttribute( SecurityAction.LinkDemand, Flags = SecurityPermissionFlag.UnmanagedCode )] //// public static IntPtr StringToHGlobalUni( String s ) //// { //// if(s == null) //// { //// return Win32Native.NULL; //// } //// else //// { //// int nb = (s.Length + 1) * 2; //// //// // Overflow checking //// if(nb < s.Length) //// throw new ArgumentOutOfRangeException( "s" ); //// //// IntPtr len = new IntPtr( nb ); //// IntPtr hglobal = Win32Native.LocalAlloc_NoSafeHandle( LMEM_FIXED, len ); //// //// if(hglobal == Win32Native.NULL) //// { //// throw new OutOfMemoryException(); //// } //// else //// { //// Win32Native.CopyMemoryUni( hglobal, s, len ); //// return hglobal; //// } //// } //// } //// //// [SecurityPermissionAttribute( SecurityAction.LinkDemand, Flags = SecurityPermissionFlag.UnmanagedCode )] //// public static IntPtr StringToHGlobalAuto( String s ) //// { //// return (SystemDefaultCharSize == 1) ? StringToHGlobalAnsi( s ) : StringToHGlobalUni( s ); //// } //// //// //// //==================================================================== //// // check if the object is classic COM component //// //==================================================================== //// [SecurityPermissionAttribute( SecurityAction.LinkDemand, Flags = SecurityPermissionFlag.UnmanagedCode )] //// public static bool IsComObject( Object o ) //// { //// return false; //// } //// //// //// [SecurityPermissionAttribute( SecurityAction.LinkDemand, Flags = SecurityPermissionFlag.UnmanagedCode )] //// public static Delegate GetDelegateForFunctionPointer( IntPtr ptr, Type t ) //// { //// // Validate the parameters //// if(ptr == IntPtr.Zero) //// throw new ArgumentNullException( "ptr" ); //// //// if(t == null) //// throw new ArgumentNullException( "t" ); //// //// if((t as RuntimeType) == null) //// throw new ArgumentException( Environment.GetResourceString( "Argument_MustBeRuntimeType" ), "t" ); //// //// if(t.IsGenericType) //// throw new ArgumentException( Environment.GetResourceString( "Argument_NeedNonGenericType" ), "t" ); //// //// Type c = t.BaseType; //// if(c == null || (c != typeof( Delegate ) && c != typeof( MulticastDelegate ))) //// throw new ArgumentException( Environment.GetResourceString( "Arg_MustBeDelegate" ), "t" ); //// //// return GetDelegateForFunctionPointerInternal( ptr, t ); //// } //// //// [ResourceExposure( ResourceScope.None )] //// [MethodImplAttribute( MethodImplOptions.InternalCall )] //// internal static extern Delegate GetDelegateForFunctionPointerInternal( IntPtr ptr, Type t ); //// //// [SecurityPermissionAttribute( SecurityAction.LinkDemand, Flags = SecurityPermissionFlag.UnmanagedCode )] //// public static IntPtr GetFunctionPointerForDelegate( Delegate d ) //// { //// if(d == null) //// throw new ArgumentNullException( "d" ); //// //// return GetFunctionPointerForDelegateInternal( d ); //// } //// //// [ResourceExposure( ResourceScope.None )] //// [MethodImplAttribute( MethodImplOptions.InternalCall )] //// internal static extern IntPtr GetFunctionPointerForDelegateInternal( Delegate d ); //// //// [SecurityPermissionAttribute( SecurityAction.LinkDemand, Flags = SecurityPermissionFlag.UnmanagedCode )] //// public static IntPtr SecureStringToBSTR( SecureString s ) //// { //// if(s == null) //// { //// throw new ArgumentNullException( "s" ); //// } //// //// return s.ToBSTR(); //// } //// //// [SecurityPermissionAttribute( SecurityAction.LinkDemand, Flags = SecurityPermissionFlag.UnmanagedCode )] //// public static IntPtr SecureStringToCoTaskMemAnsi( SecureString s ) //// { //// if(s == null) //// { //// throw new ArgumentNullException( "s" ); //// } //// //// return s.ToAnsiStr( false ); //// } //// //// [SecurityPermissionAttribute( SecurityAction.LinkDemand, Flags = SecurityPermissionFlag.UnmanagedCode )] //// public static IntPtr SecureStringToGlobalAllocAnsi( SecureString s ) //// { //// if(s == null) //// { //// throw new ArgumentNullException( "s" ); //// } //// //// return s.ToAnsiStr( true ); //// } //// //// [SecurityPermissionAttribute( SecurityAction.LinkDemand, Flags = SecurityPermissionFlag.UnmanagedCode )] //// public static IntPtr SecureStringToCoTaskMemUnicode( SecureString s ) //// { //// if(s == null) //// { //// throw new ArgumentNullException( "s" ); //// } //// //// return s.ToUniStr( false ); //// } //// //// [SecurityPermissionAttribute( SecurityAction.LinkDemand, Flags = SecurityPermissionFlag.UnmanagedCode )] //// public static IntPtr SecureStringToGlobalAllocUnicode( SecureString s ) //// { //// if(s == null) //// { //// throw new ArgumentNullException( "s" ); //// } //// //// return s.ToUniStr( true ); //// } //// //// [SecurityPermissionAttribute( SecurityAction.LinkDemand, Flags = SecurityPermissionFlag.UnmanagedCode )] //// public static void ZeroFreeBSTR( IntPtr s ) //// { //// Win32Native.ZeroMemory( s, (uint)(Win32Native.SysStringLen( s ) * 2) ); //// FreeBSTR( s ); //// } //// //// [SecurityPermissionAttribute( SecurityAction.LinkDemand, Flags = SecurityPermissionFlag.UnmanagedCode )] //// public static void ZeroFreeCoTaskMemAnsi( IntPtr s ) //// { //// Win32Native.ZeroMemory( s, (uint)(Win32Native.lstrlenA( s )) ); //// FreeCoTaskMem( s ); //// } //// //// [SecurityPermissionAttribute( SecurityAction.LinkDemand, Flags = SecurityPermissionFlag.UnmanagedCode )] //// public static void ZeroFreeGlobalAllocAnsi( IntPtr s ) //// { //// Win32Native.ZeroMemory( s, (uint)(Win32Native.lstrlenA( s )) ); //// FreeHGlobal( s ); //// } //// //// [SecurityPermissionAttribute( SecurityAction.LinkDemand, Flags = SecurityPermissionFlag.UnmanagedCode )] //// public static void ZeroFreeCoTaskMemUnicode( IntPtr s ) //// { //// Win32Native.ZeroMemory( s, (uint)(Win32Native.lstrlenW( s ) * 2) ); //// FreeCoTaskMem( s ); //// } //// //// [SecurityPermissionAttribute( SecurityAction.LinkDemand, Flags = SecurityPermissionFlag.UnmanagedCode )] //// public static void ZeroFreeGlobalAllocUnicode( IntPtr s ) //// { //// Win32Native.ZeroMemory( s, (uint)(Win32Native.lstrlenW( s ) * 2) ); //// FreeHGlobal( s ); //// } } } ================================================ FILE: Zelig/Zelig/RunTime/Framework/mscorlib/System/Runtime/Reliability/CriticalFinalizerObject.cs ================================================ // ==++== // // Copyright (c) Microsoft Corporation. All rights reserved. // // ==--== /*============================================================ ** ** Class: CriticalFinalizerObject ** ** ** Deriving from this class will cause any finalizer you define to be critical ** (i.e. the finalizer is guaranteed to run, won't be aborted by the host and is ** run after the finalizers of other objects collected at the same time). ** ** You must possess UnmanagedCode permission in order to derive from this class. ** ** ===========================================================*/ namespace System.Runtime.ConstrainedExecution { using System; ////using System.Security.Permissions; using System.Runtime.InteropServices; ////[SecurityPermission( SecurityAction.InheritanceDemand, UnmanagedCode = true )] public abstract class CriticalFinalizerObject { //// [ReliabilityContract( Consistency.WillNotCorruptState, Cer.MayFail )] protected CriticalFinalizerObject() { } //// [ReliabilityContract( Consistency.WillNotCorruptState, Cer.Success )] ~CriticalFinalizerObject() { } } } ================================================ FILE: Zelig/Zelig/RunTime/Framework/mscorlib/System/Runtime/Reliability/PrePrepareMethodAttribute.cs ================================================ // ==++== // // Copyright (c) Microsoft Corporation. All rights reserved. // // ==--== /*============================================================ ** ** Class: PrePrepareMethodAttribute ** ** Purpose: Serves as a hint to ngen that the decorated method ** (and its statically determinable call graph) should be ** prepared (as for Constrained Execution Region use). This ** is primarily useful in the scenario where the method in ** question will be prepared explicitly at runtime and the ** author of the method knows this and wishes to avoid the ** overhead of runtime preparation. ** ** Date: December 18, 2003 ** ===========================================================*/ namespace System.Runtime.ConstrainedExecution { using System.Runtime.InteropServices; [AttributeUsage( AttributeTargets.Constructor | AttributeTargets.Method, Inherited = false )] public sealed class PrePrepareMethodAttribute : Attribute { public PrePrepareMethodAttribute() { } } } ================================================ FILE: Zelig/Zelig/RunTime/Framework/mscorlib/System/Runtime/Reliability/ReliabilityContractAttribute.cs ================================================ // ==++== // // Copyright (c) Microsoft Corporation. All rights reserved. // // ==--== /*============================================================ ** ** Class: ReliabilityContractAttribute ** ** ** Purpose: Defines a publically documentable contract for ** reliability between a method and its callers, expressing ** what state will remain consistent in the presence of ** failures (ie async exceptions like thread abort) and whether ** the method needs to be called from within a CER. ** ** ===========================================================*/ namespace System.Runtime.ConstrainedExecution { using System.Runtime.InteropServices; // ************************************************************************************************************************** // // Note that if you change either of the enums below or the constructors, fields or properties of the custom attribute itself // you must also change the logic and definitions in vm\ConstrainedExecutionRegion.cpp to match. // // ************************************************************************************************************************** ////[Serializable] ////public enum Consistency : int ////{ //// MayCorruptProcess = 0, //// MayCorruptAppDomain = 1, //// MayCorruptInstance = 2, //// WillNotCorruptState = 3, ////} //// ////[Serializable] ////public enum Cer : int ////{ //// None = 0, //// MayFail = 1, // Might fail, but the method will say it failed //// Success = 2, ////} //// ////[AttributeUsage( AttributeTargets.Assembly | AttributeTargets.Class | AttributeTargets.Struct | AttributeTargets.Constructor | AttributeTargets.Method | AttributeTargets.Interface /* | AttributeTargets.Delegate*/, Inherited = false )] ////public sealed class ReliabilityContractAttribute : Attribute ////{ //// private Consistency m_consistency; //// private Cer m_cer; //// //// public ReliabilityContractAttribute( Consistency consistencyGuarantee, Cer cer ) //// { //// m_consistency = consistencyGuarantee; //// m_cer = cer; //// } //// //// public Consistency ConsistencyGuarantee //// { //// get //// { //// return m_consistency; //// } //// } //// //// public Cer Cer //// { //// get //// { //// return m_cer; //// } //// } ////} } ================================================ FILE: Zelig/Zelig/RunTime/Framework/mscorlib/System/Runtime/Serialization/SerializationAttributes.cs ================================================ // ==++== // // Copyright (c) Microsoft Corporation. All rights reserved. // // ==--== /*============================================================ ** ** Class: OptionallySerializableAttribute ** ** ** Purpose: Various Attributes for Serialization ** ** ============================================================*/ namespace System.Runtime.Serialization { using System.Reflection; [AttributeUsage( AttributeTargets.Field, Inherited = false )] public sealed class OptionalFieldAttribute : Attribute { int versionAdded = 1; public OptionalFieldAttribute() { } public int VersionAdded { get { return this.versionAdded; } set { if(value < 1) { #if EXCEPTION_STRINGS throw new ArgumentException( Environment.GetResourceString( "Serialization_OptionalFieldVersionValue" ) ); #else throw new ArgumentException(); #endif } this.versionAdded = value; } } } [AttributeUsage( AttributeTargets.Method, Inherited = false )] public sealed class OnSerializingAttribute : Attribute { } [AttributeUsage( AttributeTargets.Method, Inherited = false )] public sealed class OnSerializedAttribute : Attribute { } [AttributeUsage( AttributeTargets.Method, Inherited = false )] public sealed class OnDeserializingAttribute : Attribute { } [AttributeUsage( AttributeTargets.Method, Inherited = false )] public sealed class OnDeserializedAttribute : Attribute { } } ================================================ FILE: Zelig/Zelig/RunTime/Framework/mscorlib/System/Runtime/Serialization/SerializationException.cs ================================================ // ==++== // // Copyright (c) Microsoft Corporation. All rights reserved. // // ==--== /*============================================================================= ** ** Class: SerializationException ** ** ** Purpose: Thrown when something goes wrong during serialization or ** deserialization. ** ** =============================================================================*/ namespace System.Runtime.Serialization { using System; using System.Runtime.Serialization; [Serializable] public class SerializationException : SystemException { // Creates a new SerializationException with its message // string set to a default message. public SerializationException() : base( Environment.GetResourceString( "Arg_SerializationException" ) ) { } public SerializationException( String message ) : base( message ) { } public SerializationException( String message, Exception innerException ) : base( message, innerException ) { } //// protected SerializationException( SerializationInfo info, StreamingContext context ) : base( info, context ) //// { //// } } } ================================================ FILE: Zelig/Zelig/RunTime/Framework/mscorlib/System/RuntimeArgumentHandle.cs ================================================ // ==++== // // Copyright (c) Microsoft Corporation. All rights reserved. // // ==--== namespace System { using System; // This value type is used for constructing System.ArgIterator. // // SECURITY : m_ptr cannot be set to anything other than null by untrusted // code. // // This corresponds to EE VARARGS cookie. // Cannot be serialized ////[System.Runtime.InteropServices.ComVisible( true )] [Microsoft.Zelig.Internals.WellKnownType( "System_RuntimeArgumentHandle" )] public struct RuntimeArgumentHandle { #pragma warning disable 649 private IntPtr m_ptr; #pragma warning restore 649 internal IntPtr Value { get { return m_ptr; } } } } ================================================ FILE: Zelig/Zelig/RunTime/Framework/mscorlib/System/RuntimeFieldHandle.cs ================================================ // ==++== // // Copyright (c) Microsoft Corporation. All rights reserved. // // ==--== #define DEBUG_PTRS namespace System { using System; using System.Reflection; ////using System.Reflection.Emit; using System.Runtime.ConstrainedExecution; using System.Diagnostics; using System.Runtime.Serialization; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; ////using System.Runtime.Versioning; ////using System.Text; using System.Globalization; ////using System.Security; ////using Microsoft.Win32.SafeHandles; ////using StackCrawlMark = System.Threading.StackCrawlMark; [Microsoft.Zelig.Internals.WellKnownType( "System_RuntimeFieldHandle" )] [Serializable] public unsafe struct RuntimeFieldHandle /*: ISerializable*/ { //// private IntPtr m_ptr; //// //// internal RuntimeFieldHandle( void* pFieldHandle ) //// { //// m_ptr = new IntPtr( pFieldHandle ); //// } //// //// public IntPtr Value //// { //// get //// { //// return m_ptr; //// } //// } [MethodImpl( MethodImplOptions.InternalCall )] internal extern bool IsNullHandle(); //// { //// return m_ptr.ToPointer() == null; //// } [MethodImpl( MethodImplOptions.InternalCall )] public extern override int GetHashCode(); //// { //// return m_ptr.GetHashCode(); //// } //// [ReliabilityContract( Consistency.WillNotCorruptState, Cer.Success )] [MethodImpl( MethodImplOptions.InternalCall )] public extern override bool Equals( object obj ); //// { //// if(!(obj is RuntimeFieldHandle)) //// return false; //// //// RuntimeFieldHandle handle = (RuntimeFieldHandle)obj; //// //// return handle.m_ptr == m_ptr; //// } //// [ReliabilityContract( Consistency.WillNotCorruptState, Cer.Success )] [MethodImpl( MethodImplOptions.InternalCall )] public unsafe extern bool Equals( RuntimeFieldHandle handle ); //// { //// return handle.m_ptr == m_ptr; //// } public static bool operator ==( RuntimeFieldHandle left, RuntimeFieldHandle right ) { return left.Equals( right ); } public static bool operator !=( RuntimeFieldHandle left, RuntimeFieldHandle right ) { return !left.Equals( right ); } //// [ResourceExposure( ResourceScope.None )] //// [MethodImpl( MethodImplOptions.InternalCall )] //// internal extern String GetName(); //// //// [ResourceExposure( ResourceScope.None )] //// [MethodImpl( MethodImplOptions.InternalCall )] //// private extern unsafe void* _GetUtf8Name(); //// //// internal unsafe Utf8String GetUtf8Name() { return new Utf8String( _GetUtf8Name() ); } //// //// [ResourceExposure( ResourceScope.None )] //// [MethodImpl( MethodImplOptions.InternalCall )] //// internal extern FieldAttributes GetAttributes(); //// //// [ResourceExposure( ResourceScope.None )] //// [MethodImpl( MethodImplOptions.InternalCall )] //// internal extern RuntimeTypeHandle GetApproxDeclaringType(); //// //// [ResourceExposure( ResourceScope.None )] //// [MethodImpl( MethodImplOptions.InternalCall )] //// internal extern int GetToken(); //// //// [ResourceExposure( ResourceScope.None )] //// [MethodImpl( MethodImplOptions.InternalCall )] //// internal extern Object GetValue( Object instance, RuntimeTypeHandle fieldType, RuntimeTypeHandle declaringType, ref bool domainInitialized ); //// //// [ResourceExposure( ResourceScope.None )] //// [MethodImpl( MethodImplOptions.InternalCall )] //// internal extern Object GetValueDirect( RuntimeTypeHandle fieldType, TypedReference obj, RuntimeTypeHandle contextType ); //// //// [ResourceExposure( ResourceScope.None )] //// [MethodImpl( MethodImplOptions.InternalCall )] //// internal extern void SetValue( Object obj, Object value, RuntimeTypeHandle fieldType, FieldAttributes fieldAttr, RuntimeTypeHandle declaringType, ref bool domainInitialized ); //// //// [ResourceExposure( ResourceScope.None )] //// [MethodImpl( MethodImplOptions.InternalCall )] //// internal extern void SetValueDirect( RuntimeTypeHandle fieldType, TypedReference obj, Object value, RuntimeTypeHandle contextType ); //// //// [ResourceExposure( ResourceScope.None )] //// [MethodImpl( MethodImplOptions.InternalCall )] //// internal extern RuntimeFieldHandle GetStaticFieldForGenericType( RuntimeTypeHandle declaringType ); //// //// [ResourceExposure( ResourceScope.None )] //// [MethodImpl( MethodImplOptions.InternalCall )] //// internal extern bool AcquiresContextFromThis(); //// //// // ISerializable interface //// private RuntimeFieldHandle( SerializationInfo info, StreamingContext context ) //// { //// if(info == null) //// { //// throw new ArgumentNullException( "info" ); //// } //// //// FieldInfo f = (RuntimeFieldInfo)info.GetValue( "FieldObj", typeof( RuntimeFieldInfo ) ); //// if(f == null) //// { //// throw new SerializationException( Environment.GetResourceString( "Serialization_InsufficientState" ) ); //// } //// //// m_ptr = f.FieldHandle.Value; //// if(m_ptr.ToPointer() == null) //// { //// throw new SerializationException( Environment.GetResourceString( "Serialization_InsufficientState" ) ); //// } //// } //// //// public void GetObjectData( SerializationInfo info, StreamingContext context ) //// { //// if(info == null) //// { //// throw new ArgumentNullException( "info" ); //// } //// //// if(m_ptr.ToPointer() == null) //// { //// throw new SerializationException( Environment.GetResourceString( "Serialization_InvalidFieldState" ) ); //// } //// //// RuntimeFieldInfo fldInfo = (RuntimeFieldInfo)RuntimeType.GetFieldInfo( this ); //// //// info.AddValue( "FieldObj", fldInfo, typeof( RuntimeFieldInfo ) ); //// } } } ================================================ FILE: Zelig/Zelig/RunTime/Framework/mscorlib/System/RuntimeMethodHandle.cs ================================================ // ==++== // // Copyright (c) Microsoft Corporation. All rights reserved. // // ==--== #define DEBUG_PTRS namespace System { using System; using System.Reflection; ////using System.Reflection.Emit; using System.Runtime.ConstrainedExecution; using System.Diagnostics; using System.Runtime.Serialization; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; ////using System.Runtime.Versioning; ////using System.Text; using System.Globalization; ////using System.Security; ////using Microsoft.Win32.SafeHandles; ////using StackCrawlMark = System.Threading.StackCrawlMark; [Microsoft.Zelig.Internals.WellKnownType( "System_RuntimeMethodHandle" )] [Serializable] public unsafe struct RuntimeMethodHandle /*: ISerializable*/ { //// internal static RuntimeMethodHandle EmptyHandle //// { //// get //// { //// return new RuntimeMethodHandle(); //// } //// } //// //// private IntPtr m_ptr; //// //// internal RuntimeMethodHandle( void* pMethod ) //// { //// m_ptr = new IntPtr( pMethod ); //// } //// //// private RuntimeMethodHandle() //// { //// } //// //// internal RuntimeMethodHandle( IntPtr pMethod ) //// { //// m_ptr = pMethod; //// } //// //// // ISerializable interface //// private RuntimeMethodHandle( SerializationInfo info, StreamingContext context ) //// { //// if(info == null) //// { //// throw new ArgumentNullException( "info" ); //// } //// //// MethodInfo m = (RuntimeMethodInfo)info.GetValue( "MethodObj", typeof( RuntimeMethodInfo ) ); //// //// m_ptr = m.MethodHandle.Value; //// //// if(m_ptr.ToPointer() == null) //// { //// throw new SerializationException( Environment.GetResourceString( "Serialization_InsufficientState" ) ); //// } //// } //// //// public void GetObjectData( SerializationInfo info, StreamingContext context ) //// { //// if(info == null) //// { //// throw new ArgumentNullException( "info" ); //// } //// //// if(m_ptr.ToPointer() == null) //// { //// throw new SerializationException( Environment.GetResourceString( "Serialization_InvalidFieldState" ) ); //// } //// //// RuntimeMethodInfo methodInfo = (RuntimeMethodInfo)RuntimeType.GetMethodBase( this ); //// //// info.AddValue( "MethodObj", methodInfo, typeof( RuntimeMethodInfo ) ); //// } //// //// public IntPtr Value //// { //// get //// { //// return m_ptr; //// } //// } [MethodImpl( MethodImplOptions.InternalCall )] public extern override int GetHashCode(); //// { //// return m_ptr.GetHashCode(); //// } //// [ReliabilityContract( Consistency.WillNotCorruptState, Cer.Success )] [MethodImpl( MethodImplOptions.InternalCall )] public extern override bool Equals( object obj ); //// { //// if(!(obj is RuntimeMethodHandle)) //// { //// return false; //// } //// //// return Equals( (RuntimeMethodHandle)obj ); //// } public static bool operator ==( RuntimeMethodHandle left, RuntimeMethodHandle right ) { return left.Equals( right ); } public static bool operator !=( RuntimeMethodHandle left, RuntimeMethodHandle right ) { return !left.Equals( right ); } //// [ReliabilityContract( Consistency.WillNotCorruptState, Cer.Success )] [MethodImpl( MethodImplOptions.InternalCall )] public extern bool Equals( RuntimeMethodHandle handle ); //// { //// return handle.m_ptr == m_ptr; //// } [MethodImpl( MethodImplOptions.InternalCall )] internal extern bool IsNullHandle(); //// { //// return m_ptr.ToPointer() == null; //// } //// [ResourceExposure( ResourceScope.None )] //// [MethodImpl( MethodImplOptions.InternalCall )] //// public extern IntPtr GetFunctionPointer(); //// //// [ResourceExposure( ResourceScope.None )] //// [MethodImpl( MethodImplOptions.InternalCall )] //// private unsafe extern void _CheckLinktimeDemands( void* module, int metadataToken ); //// //// internal void CheckLinktimeDemands( Module module, int metadataToken ) //// { //// _CheckLinktimeDemands( (void*)module.ModuleHandle.Value, metadataToken ); //// } //// //// [ResourceExposure( ResourceScope.None )] //// [MethodImpl( MethodImplOptions.InternalCall )] //// private unsafe extern bool _IsVisibleFromModule( IntPtr source ); //// //// internal bool IsVisibleFromModule( Module source ) //// { //// return _IsVisibleFromModule( source.ModuleHandle.Value ); //// } //// //// [ResourceExposure( ResourceScope.None )] //// [MethodImpl( MethodImplOptions.InternalCall )] //// private unsafe extern bool _IsVisibleFromType( IntPtr source ); //// //// internal bool IsVisibleFromType( RuntimeTypeHandle source ) //// { //// return _IsVisibleFromType( source.Value ); //// } //// //// [ResourceExposure( ResourceScope.None )] //// [MethodImpl( MethodImplOptions.InternalCall )] //// private static extern void* _GetCurrentMethod( ref StackCrawlMark stackMark ); //// //// internal static RuntimeMethodHandle GetCurrentMethod( ref StackCrawlMark stackMark ) //// { //// return new RuntimeMethodHandle( _GetCurrentMethod( ref stackMark ) ); //// } //// //// [ResourceExposure( ResourceScope.None )] //// [MethodImpl( MethodImplOptions.InternalCall )] //// internal extern MethodAttributes GetAttributes(); //// //// [ResourceExposure( ResourceScope.None )] //// [MethodImpl( MethodImplOptions.InternalCall )] //// internal extern MethodImplAttributes GetImplAttributes(); //// //// [ResourceExposure( ResourceScope.None )] //// [MethodImpl( MethodImplOptions.InternalCall )] //// internal extern string ConstructInstantiation(); //// //// [ResourceExposure( ResourceScope.None )] //// [MethodImpl( MethodImplOptions.InternalCall )] //// internal extern RuntimeTypeHandle GetDeclaringType(); //// //// [ResourceExposure( ResourceScope.None )] //// [MethodImpl( MethodImplOptions.InternalCall )] //// internal extern int GetSlot(); //// //// [ResourceExposure( ResourceScope.None )] //// [MethodImpl( MethodImplOptions.InternalCall )] //// internal extern int GetMethodDef(); //// //// [ResourceExposure( ResourceScope.None )] //// [MethodImpl( MethodImplOptions.InternalCall )] //// internal extern string GetName(); //// //// [ResourceExposure( ResourceScope.None )] //// [MethodImpl( MethodImplOptions.InternalCall )] //// private extern void* _GetUtf8Name(); //// //// internal Utf8String GetUtf8Name() //// { //// return new Utf8String( _GetUtf8Name() ); //// } //// //// [ResourceExposure( ResourceScope.None )] //// [DebuggerStepThroughAttribute] //// [Diagnostics.DebuggerHidden] //// [MethodImpl( MethodImplOptions.InternalCall )] //// private extern object _InvokeMethodFast( object target, object[] arguments, ref SignatureStruct sig, MethodAttributes methodAttributes, RuntimeTypeHandle typeOwner ); //// //// [DebuggerStepThroughAttribute] //// [Diagnostics.DebuggerHidden] //// internal object InvokeMethodFast( object target, object[] arguments, Signature sig, MethodAttributes methodAttributes, RuntimeTypeHandle typeOwner ) //// { //// SignatureStruct _sig = sig.m_signature; //// //// object obj1 = _InvokeMethodFast( target, arguments, ref _sig, methodAttributes, typeOwner ); //// //// sig.m_signature = _sig; //// //// return obj1; //// } //// //// [DebuggerStepThroughAttribute] //// [Diagnostics.DebuggerHidden] //// [ResourceExposure( ResourceScope.None )] //// [MethodImpl( MethodImplOptions.InternalCall )] //// private extern object _InvokeConstructor( object[] args, ref SignatureStruct signature, IntPtr declaringType ); //// //// [DebuggerStepThroughAttribute] //// [Diagnostics.DebuggerHidden] //// internal object InvokeConstructor( object[] args, SignatureStruct signature, RuntimeTypeHandle declaringType ) //// { //// return _InvokeConstructor( args, ref signature, declaringType.Value ); //// } //// //// [DebuggerStepThroughAttribute] //// [Diagnostics.DebuggerHidden] //// [ResourceExposure( ResourceScope.None )] //// [MethodImpl( MethodImplOptions.InternalCall )] //// private extern void _SerializationInvoke( Object target, ref SignatureStruct declaringTypeSig, SerializationInfo info, StreamingContext context ); //// //// [DebuggerStepThroughAttribute] //// [Diagnostics.DebuggerHidden] //// internal void SerializationInvoke( Object target, SignatureStruct declaringTypeSig, SerializationInfo info, StreamingContext context ) //// { //// _SerializationInvoke( target, ref declaringTypeSig, info, context ); //// } //// //// //// [ResourceExposure( ResourceScope.None )] //// [MethodImpl( MethodImplOptions.InternalCall )] //// internal extern bool IsILStub(); //// //// [ResourceExposure( ResourceScope.None )] //// [MethodImpl( MethodImplOptions.InternalCall )] //// internal extern RuntimeTypeHandle[] GetMethodInstantiation(); //// //// [ResourceExposure( ResourceScope.None )] //// [MethodImpl( MethodImplOptions.InternalCall )] //// internal extern bool HasMethodInstantiation(); //// //// [ResourceExposure( ResourceScope.None )] //// [MethodImpl( MethodImplOptions.InternalCall )] //// internal extern RuntimeMethodHandle GetInstantiatingStub( RuntimeTypeHandle declaringTypeHandle, RuntimeTypeHandle[] methodInstantiation ); //// //// internal RuntimeMethodHandle GetInstantiatingStubIfNeeded( RuntimeTypeHandle declaringTypeHandle ) //// { //// return GetInstantiatingStub( declaringTypeHandle, null ); //// } //// //// [ResourceExposure( ResourceScope.None )] //// [MethodImpl( MethodImplOptions.InternalCall )] //// internal extern RuntimeMethodHandle GetMethodFromCanonical( RuntimeTypeHandle declaringTypeHandle ); //// //// [ResourceExposure( ResourceScope.None )] //// [MethodImpl( MethodImplOptions.InternalCall )] //// internal extern bool IsGenericMethodDefinition(); //// //// [ResourceExposure( ResourceScope.None )] //// [MethodImpl( MethodImplOptions.InternalCall )] //// private extern void* _GetTypicalMethodDefinition(); //// //// internal RuntimeMethodHandle GetTypicalMethodDefinition() //// { //// return new RuntimeMethodHandle( _GetTypicalMethodDefinition() ); //// } //// //// [ResourceExposure( ResourceScope.None )] //// [MethodImpl( MethodImplOptions.InternalCall )] //// private extern void* _StripMethodInstantiation(); //// //// internal RuntimeMethodHandle StripMethodInstantiation() //// { //// return new RuntimeMethodHandle( _StripMethodInstantiation() ); //// } //// //// [ResourceExposure( ResourceScope.None )] //// [MethodImpl( MethodImplOptions.InternalCall )] //// internal extern bool IsDynamicMethod(); //// //// [ResourceExposure( ResourceScope.None )] //// [MethodImpl( MethodImplOptions.InternalCall )] //// internal extern Resolver GetResolver(); //// //// [ResourceExposure( ResourceScope.None )] //// [MethodImpl( MethodImplOptions.InternalCall )] //// internal extern void Destroy(); //// //// [ResourceExposure( ResourceScope.None )] //// [MethodImpl( MethodImplOptions.InternalCall )] //// internal extern MethodBody _GetMethodBody( IntPtr declaringType ); //// //// internal MethodBody GetMethodBody( RuntimeTypeHandle declaringType ) //// { //// return _GetMethodBody( declaringType.Value ); //// } //// //// [ResourceExposure( ResourceScope.None )] //// [MethodImpl( MethodImplOptions.InternalCall )] //// internal extern bool IsConstructor(); } } ================================================ FILE: Zelig/Zelig/RunTime/Framework/mscorlib/System/RuntimeType.cs ================================================ // ==++== // // Copyright (c) Microsoft Corporation. All rights reserved. // // ==--== namespace System { using System; using System.Reflection; using System.Runtime.ConstrainedExecution; using System.Globalization; using System.Threading; using System.Diagnostics; ////using System.Security.Permissions; using System.Collections; using System.Collections.Generic; using System.Runtime.Serialization; using System.Runtime.CompilerServices; ////using System.Security; ////using System.Text; ////using System.Reflection.Emit; ////using System.Runtime.Remoting; ////using System.Runtime.Remoting.Proxies; ////using System.Runtime.Remoting.Messaging; ////using System.Runtime.Remoting.Activation; using System.Runtime.InteropServices; ////using System.Runtime.Versioning; ////using MdSigCallingConvention = System.Signature.MdSigCallingConvention; ////using RuntimeTypeCache = System.RuntimeType.RuntimeTypeCache; ////using StackCrawlMark = System.Threading.StackCrawlMark; ////using DebuggerStepThroughAttribute = System.Diagnostics.DebuggerStepThroughAttribute; ////using MdToken = System.Reflection.MetadataToken; // this is a work around to get the concept of a calli. It's not as fast but it would be interesting to // see how it compares to the current implementation. // This delegate will disappear at some point in favor of calli ////internal delegate void CtorDelegate( Object instance ); [Microsoft.Zelig.Internals.WellKnownType( "System_RuntimeType" )] [Serializable] internal class RuntimeType : Type/*, ISerializable, ICloneable*/ { #region Definitions //// [Serializable] //// internal class RuntimeTypeCache //// { //// #region Definitions //// internal enum WhatsCached //// { //// Nothing = 0x0, //// EnclosingType = 0x1, //// } //// //// internal enum CacheType //// { //// Method, //// Constructor, //// Field, //// Property, //// Event, //// Interface, //// NestedType //// } //// //// // This method is purely an aid for NGen to statically deduce which //// // instantiations to save in the ngen image. //// // Otherwise, the JIT-compiler gets used, which is bad for working-set. //// // Note that IBC can provide this information too. //// // However, this helps in keeping the JIT-compiler out even for //// // test scenarios which do not use IBC. //// // This can be removed after V2, when we implement other schemes //// // of keeping the JIT-compiler out for generic instantiations. //// internal static void Prejitinit_HACK() //// { //// new MemberInfoCache( null ); //// new MemberInfoCache( null ); //// new MemberInfoCache( null ); //// new MemberInfoCache( null ); //// new MemberInfoCache( null ); //// new MemberInfoCache( null ); //// } //// //// private struct Filter //// { //// private Utf8String m_name; //// private MemberListType m_listType; //// //// public unsafe Filter( byte* pUtf8Name, int cUtf8Name, MemberListType listType ) //// { //// this.m_name = new Utf8String( (void*)pUtf8Name, cUtf8Name ); //// this.m_listType = listType; //// } //// //// public bool Match( Utf8String name ) //// { //// if(m_listType == MemberListType.CaseSensitive) //// return m_name.Equals( name ); //// else if(m_listType == MemberListType.CaseInsensitive) //// return m_name.EqualsCaseInsensitive( name ); //// else //// return true; //// } //// } //// //// [Serializable] //// private class MemberInfoCache where T : MemberInfo //// { //// #region Static Members //// static MemberInfoCache() //// { //// // We need to prepare some code in this class for reliable //// // execution on a per-instantiation basis. A static class //// // constructor is ideal for this since we only need to do //// // this once per-instantiation. We can't go through the //// // normal approach using RuntimeHelpers.PrepareMethod since //// // that would involve using reflection and we'd wind back up //// // here recursively. So we call through an fcall helper //// // instead. The fcall is on RuntimeType to avoid having an //// // fcall entry for a nested class (a generic one at that). //// // I've no idea if that would work, but I'm pretty sure it //// // wouldn't. Also we pass in our own base type since using //// // the mscorlib binder doesn't work for nested types (I've //// // tried that one). //// PrepareMemberInfoCache( typeof( MemberInfoCache ).TypeHandle ); //// } //// #endregion //// //// #region Private Data Members //// // MemberInfo caches //// private CerHashtable> m_csMemberInfos; //// private CerHashtable> m_cisMemberInfos; //// private CerArrayList m_root; //// private bool m_cacheComplete; //// //// // This is the strong reference back to the cache //// private RuntimeTypeCache m_runtimeTypeCache; //// #endregion //// //// #region Constructor //// internal MemberInfoCache( RuntimeTypeCache runtimeTypeCache ) //// { //// m_runtimeTypeCache = runtimeTypeCache; //// m_cacheComplete = false; //// } //// //// internal MethodBase AddMethod( RuntimeTypeHandle declaringType, RuntimeMethodHandle method, CacheType cacheType ) //// { //// Object list = null; //// MethodAttributes methodAttributes = method.GetAttributes(); //// bool isPublic = (methodAttributes & MethodAttributes.MemberAccessMask) == MethodAttributes.Public; //// bool isStatic = (methodAttributes & MethodAttributes.Static) != 0; //// bool isInherited = declaringType.Value != ReflectedTypeHandle.Value; //// BindingFlags bindingFlags = RuntimeType.FilterPreCalculate( isPublic, isInherited, isStatic ); //// switch(cacheType) //// { //// case CacheType.Method: //// List mlist = new List( 1 ); //// mlist.Add( new RuntimeMethodInfo( method, declaringType, m_runtimeTypeCache, methodAttributes, bindingFlags ) ); //// list = mlist; //// break; //// case CacheType.Constructor: //// List clist = new List( 1 ); //// clist.Add( new RuntimeConstructorInfo( method, declaringType, m_runtimeTypeCache, methodAttributes, bindingFlags ) ); //// list = clist; //// break; //// } //// //// CerArrayList cerList = new CerArrayList( (List)list ); //// //// Insert( ref cerList, null, MemberListType.HandleToInfo ); //// //// return (MethodBase)(object)cerList[0]; //// } //// //// internal FieldInfo AddField( RuntimeFieldHandle field ) //// { //// // create the runtime field info //// List list = new List( 1 ); //// FieldAttributes fieldAttributes = field.GetAttributes(); //// bool isPublic = (fieldAttributes & FieldAttributes.FieldAccessMask) == FieldAttributes.Public; //// bool isStatic = (fieldAttributes & FieldAttributes.Static) != 0; //// bool isInherited = field.GetApproxDeclaringType().Value != ReflectedTypeHandle.Value; //// BindingFlags bindingFlags = RuntimeType.FilterPreCalculate( isPublic, isInherited, isStatic ); //// list.Add( new RtFieldInfo( field, ReflectedType, m_runtimeTypeCache, bindingFlags ) ); //// //// CerArrayList cerList = new CerArrayList( (List)(object)list ); //// Insert( ref cerList, null, MemberListType.HandleToInfo ); //// //// return (FieldInfo)(object)cerList[0]; //// } //// //// private unsafe CerArrayList Populate( string name, MemberListType listType, CacheType cacheType ) //// { //// if(name == null || name.Length == 0 || //// (cacheType == CacheType.Constructor && name.FirstChar != '.' && name.FirstChar != '*')) //// { //// Filter filter = new Filter( null, 0, listType ); //// List list = null; //// //// switch(cacheType) //// { //// case CacheType.Method: //// list = PopulateMethods( filter ) as List; //// break; //// case CacheType.Field: //// list = PopulateFields( filter ) as List; //// break; //// case CacheType.Constructor: //// list = PopulateConstructors( filter ) as List; //// break; //// case CacheType.Property: //// list = PopulateProperties( filter ) as List; //// break; //// case CacheType.Event: //// list = PopulateEvents( filter ) as List; //// break; //// case CacheType.NestedType: //// list = PopulateNestedClasses( filter ) as List; //// break; //// case CacheType.Interface: //// list = PopulateInterfaces( filter ) as List; //// break; //// } //// //// CerArrayList cerList = new CerArrayList( list ); //// //// Insert( ref cerList, name, listType ); //// //// return cerList; //// } //// else //// { //// fixed(char* pName = name) //// { //// int cUtf8Name = Encoding.UTF8.GetByteCount( pName, name.Length ); //// byte* pUtf8Name = stackalloc byte[cUtf8Name]; //// Encoding.UTF8.GetBytes( pName, name.Length, pUtf8Name, cUtf8Name ); //// //// Filter filter = new Filter( pUtf8Name, cUtf8Name, listType ); //// List list = null; //// //// switch(cacheType) //// { //// case CacheType.Method: //// list = PopulateMethods( filter ) as List; //// break; //// case CacheType.Field: //// list = PopulateFields( filter ) as List; //// break; //// case CacheType.Constructor: //// list = PopulateConstructors( filter ) as List; //// break; //// case CacheType.Property: //// list = PopulateProperties( filter ) as List; //// break; //// case CacheType.Event: //// list = PopulateEvents( filter ) as List; //// break; //// case CacheType.NestedType: //// list = PopulateNestedClasses( filter ) as List; //// break; //// case CacheType.Interface: //// list = PopulateInterfaces( filter ) as List; //// break; //// } //// //// CerArrayList cerList = new CerArrayList( list ); //// //// Insert( ref cerList, name, listType ); //// //// return cerList; //// } //// } //// } //// //// // May replace the list with a new one if certain cache //// // lookups succeed. Also, may modify the contents of the list //// // after merging these new data structures with cached ones. //// private void Insert( ref CerArrayList list, string name, MemberListType listType ) //// { //// bool lockTaken = false; //// bool preallocationComplete = false; //// //// RuntimeHelpers.PrepareConstrainedRegions(); //// try //// { //// Monitor.ReliableEnter( this, ref lockTaken ); //// //// if(listType == MemberListType.CaseSensitive) //// { //// if(m_csMemberInfos == null) //// m_csMemberInfos = new CerHashtable>(); //// else //// m_csMemberInfos.Preallocate( 1 ); //// } //// else if(listType == MemberListType.CaseInsensitive) //// { //// if(m_cisMemberInfos == null) //// m_cisMemberInfos = new CerHashtable>(); //// else //// m_cisMemberInfos.Preallocate( 1 ); //// } //// //// if(m_root == null) //// m_root = new CerArrayList( list.Count ); //// else //// m_root.Preallocate( list.Count ); //// //// preallocationComplete = true; //// } //// finally //// { //// try //// { //// if(preallocationComplete) //// { //// if(listType == MemberListType.CaseSensitive) //// { //// // Ensure we always return a list that has //// // been merged with the global list. //// CerArrayList cachedList = m_csMemberInfos[name]; //// if(cachedList == null) //// { //// MergeWithGlobalList( list ); //// m_csMemberInfos[name] = list; //// } //// else //// list = cachedList; //// } //// else if(listType == MemberListType.CaseInsensitive) //// { //// // Ensure we always return a list that has //// // been merged with the global list. //// CerArrayList cachedList = m_cisMemberInfos[name]; //// if(cachedList == null) //// { //// MergeWithGlobalList( list ); //// m_cisMemberInfos[name] = list; //// } //// else //// list = cachedList; //// } //// else //// { //// MergeWithGlobalList( list ); //// } //// //// if(listType == MemberListType.All) //// { //// m_cacheComplete = true; //// } //// } //// } //// finally //// { //// if(lockTaken) //// { //// Monitor.Exit( this ); //// } //// } //// } //// } //// //// // Modifies the existing list. //// [ReliabilityContract( Consistency.WillNotCorruptState, Cer.Success )] //// private void MergeWithGlobalList( CerArrayList list ) //// { //// int cachedCount = m_root.Count; //// //// for(int i = 0; i < list.Count; i++) //// { //// T newMemberInfo = list[i]; //// T cachedMemberInfo = null; //// //// for(int j = 0; j < cachedCount; j++) //// { //// cachedMemberInfo = m_root[j]; //// //// if(newMemberInfo.CacheEquals( cachedMemberInfo )) //// { //// list.Replace( i, cachedMemberInfo ); //// break; //// } //// } //// //// if(list[i] != cachedMemberInfo) //// m_root.Add( newMemberInfo ); //// } //// } //// #endregion //// //// #region Population Logic //// private unsafe List PopulateMethods( Filter filter ) //// { //// List list = new List(); //// //// bool isInterface = //// (ReflectedTypeHandle.GetAttributes() & TypeAttributes.ClassSemanticsMask) //// == TypeAttributes.Interface; //// //// if(isInterface) //// { //// #region IsInterface //// RuntimeTypeHandle declaringInterfaceHandle = ReflectedTypeHandle; //// bool mayNeedInstantiatingStub = declaringInterfaceHandle.HasInstantiation() && !declaringInterfaceHandle.IsGenericTypeDefinition(); //// MethodDescChunkHandle chunkHandle = declaringInterfaceHandle.GetMethodDescChunk(); //// //// while(!chunkHandle.IsNullHandle()) //// { //// int methodCount = chunkHandle.GetMethodCount(); //// //// for(int i = 0; i < methodCount; i++) //// { //// RuntimeMethodHandle methodHandle = chunkHandle.GetMethodAt( i ); //// //// if(!filter.Match( methodHandle.GetUtf8Name() )) //// continue; //// //// #region Loop through all methods on the interface //// ASSERT.CONSISTENCY_CHECK( !methodHandle.IsNullHandle() ); //// ASSERT.CONSISTENCY_CHECK( LOGIC.IMPLIES( //// (methodHandle.GetAttributes() & MethodAttributes.RTSpecialName) != 0, //// methodHandle.GetName().Equals( ".ctor" ) || //// methodHandle.GetName().Equals( ".cctor" ) || //// methodHandle.GetName().Equals( "IL_STUB" ) ) ); //// ASSERT.CONSISTENCY_CHECK( (methodHandle.GetAttributes() & MethodAttributes.Abstract) != 0 ); //// ASSERT.CONSISTENCY_CHECK( (methodHandle.GetAttributes() & MethodAttributes.Virtual) != 0 ); //// //// #region Calculate Binding Flags //// MethodAttributes methodAttributes = methodHandle.GetAttributes(); //// bool isPublic = (methodAttributes & MethodAttributes.MemberAccessMask) == MethodAttributes.Public; //// bool isStatic = (methodAttributes & MethodAttributes.Static) != 0; //// bool isInherited = false; //// BindingFlags bindingFlags = RuntimeType.FilterPreCalculate( isPublic, isInherited, isStatic ); //// #endregion //// //// if((methodAttributes & MethodAttributes.RTSpecialName) != 0 || methodHandle.IsILStub()) //// continue; //// //// // if it is an instantiated type get the InstantiatedMethodDesc if needed //// if(mayNeedInstantiatingStub) //// methodHandle = methodHandle.GetInstantiatingStubIfNeeded( declaringInterfaceHandle ); //// //// RuntimeMethodInfo runtimeMethodInfo = new RuntimeMethodInfo( //// methodHandle, declaringInterfaceHandle, m_runtimeTypeCache, methodAttributes, bindingFlags ); //// //// list.Add( runtimeMethodInfo ); //// #endregion //// } //// //// chunkHandle = chunkHandle.GetNextMethodDescChunk(); //// } //// #endregion //// } //// else //// { //// #region IsClass or GenericParameter //// RuntimeTypeHandle declaringTypeHandle = ReflectedTypeHandle; //// //// while(declaringTypeHandle.IsGenericVariable()) //// declaringTypeHandle = declaringTypeHandle.GetRuntimeType().BaseType.GetTypeHandleInternal(); //// //// bool* overrides = stackalloc bool[declaringTypeHandle.GetNumVtableSlots()]; //// bool isValueType = declaringTypeHandle.GetRuntimeType().IsValueType; //// //// while(!declaringTypeHandle.IsNullHandle()) //// { //// bool mayNeedInstantiatingStub = declaringTypeHandle.HasInstantiation() && //// !declaringTypeHandle.IsGenericTypeDefinition(); //// //// int vtableSlots = declaringTypeHandle.GetNumVtableSlots(); //// MethodDescChunkHandle chunkHandle = declaringTypeHandle.GetMethodDescChunk(); //// //// while(!chunkHandle.IsNullHandle()) //// { //// int methodCount = chunkHandle.GetMethodCount(); //// //// for(int i = 0; i < methodCount; i++) //// { //// RuntimeMethodHandle methodHandle = chunkHandle.GetMethodAt( i ); //// //// if(!filter.Match( methodHandle.GetUtf8Name() )) //// continue; //// //// #region Loop through all methods on the current type //// ASSERT.CONSISTENCY_CHECK( !methodHandle.IsNullHandle() ); //// //// MethodAttributes methodAttributes = methodHandle.GetAttributes(); //// MethodAttributes methodAccess = methodAttributes & MethodAttributes.MemberAccessMask; //// //// #region Continue if this is a constructor //// ASSERT.CONSISTENCY_CHECK( //// LOGIC.IMPLIES( (methodHandle.GetAttributes() & MethodAttributes.RTSpecialName) != 0, //// methodHandle.GetName().Equals( ".ctor" ) || //// methodHandle.GetName().Equals( ".cctor" ) || //// methodHandle.GetName().Equals( "IL_STUB" ) ) ); //// //// if((methodAttributes & MethodAttributes.RTSpecialName) != 0 || methodHandle.IsILStub()) //// continue; //// #endregion //// //// #region Continue if this is a private declared on a base type //// bool isVirtual = false; //// int methodSlot = 0; //// if((methodAttributes & MethodAttributes.Virtual) != 0) //// { //// // only virtual if actually in the vtableslot range, but GetSlot will //// // assert if an EnC method, which can't be virtual, so narrow down first //// // before calling GetSlot //// methodSlot = methodHandle.GetSlot(); //// isVirtual = (methodSlot < vtableSlots); //// } //// bool isPrivate = methodAccess == MethodAttributes.Private; //// bool isPrivateVirtual = isVirtual & isPrivate; //// bool isInherited = declaringTypeHandle.Value != ReflectedTypeHandle.Value; //// if(isInherited && isPrivate && !isPrivateVirtual) //// continue; //// #endregion //// //// #region Continue if this is a virtual and is already overridden //// if(isVirtual) //// { //// ASSERT.CONSISTENCY_CHECK( //// (methodAttributes & MethodAttributes.Abstract) != 0 || //// (methodAttributes & MethodAttributes.Virtual) != 0 || //// methodHandle.GetDeclaringType().Value != declaringTypeHandle.Value ); //// //// if(overrides[methodSlot] == true) //// continue; //// //// overrides[methodSlot] = true; //// } //// else if(isValueType) //// { //// if((methodAttributes & (MethodAttributes.Virtual | MethodAttributes.Abstract)) != 0) //// continue; //// } //// else //// { //// ASSERT.CONSISTENCY_CHECK( (methodAttributes & (MethodAttributes.Virtual | MethodAttributes.Abstract)) == 0 ); //// } //// #endregion //// //// #region Calculate Binding Flags //// bool isPublic = methodAccess == MethodAttributes.Public; //// bool isStatic = (methodAttributes & MethodAttributes.Static) != 0; //// BindingFlags bindingFlags = RuntimeType.FilterPreCalculate( isPublic, isInherited, isStatic ); //// #endregion //// //// // if it is an instantiated type get the InstantiatedMethodDesc if needed //// if(mayNeedInstantiatingStub) //// methodHandle = methodHandle.GetInstantiatingStubIfNeeded( declaringTypeHandle ); //// //// RuntimeMethodInfo runtimeMethodInfo = new RuntimeMethodInfo( //// methodHandle, declaringTypeHandle, m_runtimeTypeCache, methodAttributes, bindingFlags ); //// //// list.Add( runtimeMethodInfo ); //// #endregion //// } //// //// chunkHandle = chunkHandle.GetNextMethodDescChunk(); //// } //// //// declaringTypeHandle = declaringTypeHandle.GetBaseTypeHandle(); //// } //// #endregion //// } //// //// return list; //// } //// //// private List PopulateConstructors( Filter filter ) //// { //// List list = new List(); //// //// if(ReflectedType.IsGenericParameter) //// { //// return list; //// } //// //// bool mayNeedInstantiatingStub = ReflectedTypeHandle.HasInstantiation() && //// !ReflectedTypeHandle.IsGenericTypeDefinition(); //// //// MethodDescChunkHandle chunkHandle = ReflectedTypeHandle.GetMethodDescChunk(); //// //// while(!chunkHandle.IsNullHandle()) //// { //// int methodCount = chunkHandle.GetMethodCount(); //// //// for(int i = 0; i < methodCount; i++) //// { //// RuntimeMethodHandle methodHandle = chunkHandle.GetMethodAt( i ); //// //// if(!filter.Match( methodHandle.GetUtf8Name() )) //// continue; //// //// MethodAttributes methodAttributes = methodHandle.GetAttributes(); //// //// ASSERT.CONSISTENCY_CHECK( !methodHandle.IsNullHandle() ); //// /* //// ASSERT.CONSISTENCY_CHECK( //// LOGIC.IMPLIES((methodAttributes & MethodAttributes.RTSpecialName) != 0, //// methodHandle.GetName().Equals(".ctor") || //// methodHandle.GetName().Equals(".cctor") || //// methodHandle.GetName().Equals("IL_STUB"))); //// */ //// //// if((methodAttributes & MethodAttributes.RTSpecialName) == 0) //// continue; //// //// if(methodHandle.GetName().Equals( "IL_STUB" )) //// continue; //// //// // Constructors should not be virtual or abstract //// ASSERT.CONSISTENCY_CHECK( //// (methodAttributes & MethodAttributes.Abstract) == 0 && //// (methodAttributes & MethodAttributes.Virtual) == 0 ); //// //// #region Calculate Binding Flags //// bool isPublic = (methodAttributes & MethodAttributes.MemberAccessMask) == MethodAttributes.Public; //// bool isStatic = (methodAttributes & MethodAttributes.Static) != 0; //// bool isInherited = false; //// BindingFlags bindingFlags = RuntimeType.FilterPreCalculate( isPublic, isInherited, isStatic ); //// #endregion //// //// // if it is an instantiated type get the InstantiatedMethodDesc if needed //// if(mayNeedInstantiatingStub) //// methodHandle = methodHandle.GetInstantiatingStubIfNeeded( ReflectedTypeHandle ); //// //// RuntimeConstructorInfo runtimeConstructorInfo = //// new RuntimeConstructorInfo( methodHandle, ReflectedTypeHandle, m_runtimeTypeCache, methodAttributes, bindingFlags ); //// //// list.Add( runtimeConstructorInfo ); //// } //// //// chunkHandle = chunkHandle.GetNextMethodDescChunk(); //// } //// //// return list; //// } //// //// private unsafe List PopulateFields( Filter filter ) //// { //// List list = new List(); //// //// RuntimeTypeHandle declaringTypeHandle = ReflectedTypeHandle; //// //// #region Populate all static, instance and literal fields //// while(declaringTypeHandle.IsGenericVariable()) //// declaringTypeHandle = declaringTypeHandle.GetRuntimeType().BaseType.GetTypeHandleInternal(); //// //// while(!declaringTypeHandle.IsNullHandle()) //// { //// PopulateRtFields( filter, declaringTypeHandle, list ); //// //// PopulateLiteralFields( filter, declaringTypeHandle, list ); //// //// declaringTypeHandle = declaringTypeHandle.GetBaseTypeHandle(); //// } //// #endregion //// //// #region Populate Literal Fields on Interfaces //// if(ReflectedType.IsGenericParameter) //// { //// Type[] interfaces = ReflectedTypeHandle.GetRuntimeType().BaseType.GetInterfaces(); //// //// for(int i = 0; i < interfaces.Length; i++) //// { //// // Populate literal fields defined on any of the interfaces implemented by the declaring type //// PopulateLiteralFields( filter, interfaces[i].GetTypeHandleInternal(), list ); //// PopulateRtFields( filter, interfaces[i].GetTypeHandleInternal(), list ); //// } //// } //// else //// { //// RuntimeTypeHandle[] interfaces = ReflectedTypeHandle.GetInterfaces(); //// //// if(interfaces != null) //// { //// for(int i = 0; i < interfaces.Length; i++) //// { //// // Populate literal fields defined on any of the interfaces implemented by the declaring type //// PopulateLiteralFields( filter, interfaces[i], list ); //// PopulateRtFields( filter, interfaces[i], list ); //// } //// } //// } //// #endregion //// //// return list; //// } //// //// private unsafe void PopulateRtFields( Filter filter, RuntimeTypeHandle declaringTypeHandle, List list ) //// { //// int** pResult = stackalloc int*[64]; //// int count = 64; //// //// if(!declaringTypeHandle.GetFields( pResult, &count )) //// { //// fixed(int** pBigResult = new int*[count]) //// { //// declaringTypeHandle.GetFields( pBigResult, &count ); //// PopulateRtFields( filter, pBigResult, count, declaringTypeHandle, list ); //// } //// } //// else if(count > 0) //// { //// PopulateRtFields( filter, pResult, count, declaringTypeHandle, list ); //// } //// } //// //// private unsafe void PopulateRtFields( Filter filter, //// int** ppFieldHandles, int count, RuntimeTypeHandle declaringTypeHandle, List list ) //// { //// ASSERT.PRECONDITION( !declaringTypeHandle.IsNullHandle() ); //// ASSERT.PRECONDITION( !ReflectedTypeHandle.IsNullHandle() ); //// //// bool needsStaticFieldForGeneric = declaringTypeHandle.HasInstantiation() && !declaringTypeHandle.ContainsGenericVariables(); //// bool isInherited = !declaringTypeHandle.Equals( ReflectedTypeHandle ); //// //// for(int i = 0; i < count; i++) //// { //// RuntimeFieldHandle runtimeFieldHandle = new RuntimeFieldHandle( ppFieldHandles[i] ); //// //// if(!filter.Match( runtimeFieldHandle.GetUtf8Name() )) //// continue; //// //// ASSERT.CONSISTENCY_CHECK( !runtimeFieldHandle.IsNullHandle() ); //// //// FieldAttributes fieldAttributes = runtimeFieldHandle.GetAttributes(); //// FieldAttributes fieldAccess = fieldAttributes & FieldAttributes.FieldAccessMask; //// //// if(isInherited) //// { //// if(fieldAccess == FieldAttributes.Private) //// continue; //// } //// //// #region Calculate Binding Flags //// bool isPublic = fieldAccess == FieldAttributes.Public; //// bool isStatic = (fieldAttributes & FieldAttributes.Static) != 0; //// BindingFlags bindingFlags = RuntimeType.FilterPreCalculate( isPublic, isInherited, isStatic ); //// #endregion //// //// // correct the FieldDesc if needed //// if(needsStaticFieldForGeneric && isStatic) //// runtimeFieldHandle = runtimeFieldHandle.GetStaticFieldForGenericType( declaringTypeHandle ); //// //// RuntimeFieldInfo runtimeFieldInfo = //// new RtFieldInfo( runtimeFieldHandle, declaringTypeHandle.GetRuntimeType(), m_runtimeTypeCache, bindingFlags ); //// //// list.Add( runtimeFieldInfo ); //// } //// } //// //// private unsafe void PopulateLiteralFields( Filter filter, RuntimeTypeHandle declaringTypeHandle, List list ) //// { //// ASSERT.PRECONDITION( !declaringTypeHandle.IsNullHandle() ); //// ASSERT.PRECONDITION( !ReflectedTypeHandle.IsNullHandle() ); //// //// int tkDeclaringType = declaringTypeHandle.GetToken(); //// //// // Our policy is that TypeDescs do not have metadata tokens //// if(MdToken.IsNullToken( tkDeclaringType )) //// return; //// //// MetadataImport scope = declaringTypeHandle.GetModuleHandle().GetMetadataImport(); //// int cFields = scope.EnumFieldsCount( tkDeclaringType ); //// int* tkFields = stackalloc int[cFields]; //// scope.EnumFields( tkDeclaringType, tkFields, cFields ); //// //// for(int i = 0; i < cFields; i++) //// { //// int tkField = tkFields[i]; //// ASSERT.PRECONDITION( MdToken.IsTokenOfType( tkField, MetadataTokenType.FieldDef ) ); //// ASSERT.PRECONDITION( !MdToken.IsNullToken( tkField ) ); //// //// Utf8String name; //// name = scope.GetName( tkField ); //// //// if(!filter.Match( name )) //// continue; //// //// FieldAttributes fieldAttributes; //// scope.GetFieldDefProps( tkField, out fieldAttributes ); //// //// FieldAttributes fieldAccess = fieldAttributes & FieldAttributes.FieldAccessMask; //// //// if((fieldAttributes & FieldAttributes.Literal) != 0) //// { //// bool isInherited = !declaringTypeHandle.Equals( ReflectedTypeHandle ); //// if(isInherited) //// { //// bool isPrivate = fieldAccess == FieldAttributes.Private; //// if(isPrivate) //// continue; //// } //// //// #region Calculate Binding Flags //// bool isPublic = fieldAccess == FieldAttributes.Public; //// bool isStatic = (fieldAttributes & FieldAttributes.Static) != 0; //// BindingFlags bindingFlags = RuntimeType.FilterPreCalculate( isPublic, isInherited, isStatic ); //// #endregion //// //// RuntimeFieldInfo runtimeFieldInfo = //// new MdFieldInfo( tkField, fieldAttributes, declaringTypeHandle, m_runtimeTypeCache, bindingFlags ); //// //// list.Add( runtimeFieldInfo ); //// } //// } //// } //// //// private static void AddElementTypes( Type template, IList types ) //// { //// if(!template.HasElementType) //// return; //// //// AddElementTypes( template.GetElementType(), types ); //// //// for(int i = 0; i < types.Count; i++) //// { //// if(template.IsArray) //// { //// if(template.IsSzArray) //// types[i] = types[i].MakeArrayType(); //// else //// types[i] = types[i].MakeArrayType( template.GetArrayRank() ); //// } //// else if(template.IsPointer) //// { //// types[i] = types[i].MakePointerType(); //// } //// } //// } //// //// private List PopulateInterfaces( Filter filter ) //// { //// List list = new List(); //// //// RuntimeTypeHandle declaringTypeHandle = ReflectedTypeHandle; //// //// if(!declaringTypeHandle.IsGenericVariable()) //// { //// RuntimeTypeHandle[] ifaces = ReflectedTypeHandle.GetInterfaces(); //// //// if(ifaces != null) //// { //// for(int i = 0; i < ifaces.Length; i++) //// { //// RuntimeType interfaceType = ifaces[i].GetRuntimeType(); //// //// if(!filter.Match( interfaceType.GetTypeHandleInternal().GetUtf8Name() )) //// continue; //// //// ASSERT.CONSISTENCY_CHECK( interfaceType.IsInterface ); //// list.Add( interfaceType ); //// } //// } //// //// if(ReflectedType.IsSzArray) //// { //// Type arrayType = ReflectedType.GetElementType(); //// //// if(!arrayType.IsPointer) //// { //// Type iList = typeof( IList<> ).MakeGenericType( arrayType ); //// //// if(iList.IsAssignableFrom( ReflectedType )) //// { //// if(filter.Match( iList.GetTypeHandleInternal().GetUtf8Name() )) //// list.Add( iList as RuntimeType ); //// //// Type[] iFaces = iList.GetInterfaces(); //// for(int j = 0; j < iFaces.Length; j++) //// { //// Type iFace = iFaces[j]; //// if(iFace.IsGenericType && filter.Match( iFace.GetTypeHandleInternal().GetUtf8Name() )) //// list.Add( iFaces[j] as RuntimeType ); //// } //// } //// } //// } //// } //// else //// { //// List al = new List(); //// //// // Get all constraints //// Type[] constraints = declaringTypeHandle.GetRuntimeType().GetGenericParameterConstraints(); //// //// // Populate transitive closure of all interfaces in constraint set //// for(int i = 0; i < constraints.Length; i++) //// { //// Type constraint = constraints[i]; //// if(constraint.IsInterface) //// al.Add( constraint as RuntimeType ); //// //// Type[] temp = constraint.GetInterfaces(); //// for(int j = 0; j < temp.Length; j++) //// al.Add( temp[j] as RuntimeType ); //// } //// //// // Remove duplicates //// Hashtable ht = new Hashtable(); //// for(int i = 0; i < al.Count; i++) //// { //// Type constraint = al[i] as Type; //// if(!ht.Contains( constraint )) //// ht[constraint] = constraint; //// } //// //// Type[] interfaces = new Type[ht.Values.Count]; //// ht.Values.CopyTo( interfaces, 0 ); //// //// // Populate link-list //// for(int i = 0; i < interfaces.Length; i++) //// { //// if(!filter.Match( interfaces[i].GetTypeHandleInternal().GetUtf8Name() )) //// continue; //// //// list.Add( interfaces[i] as RuntimeType ); //// } //// } //// //// return list; //// } //// //// private unsafe List PopulateNestedClasses( Filter filter ) //// { //// List list = new List(); //// //// RuntimeTypeHandle declaringTypeHandle = ReflectedTypeHandle; //// //// if(declaringTypeHandle.IsGenericVariable()) //// { //// while(declaringTypeHandle.IsGenericVariable()) //// declaringTypeHandle = declaringTypeHandle.GetRuntimeType().BaseType.GetTypeHandleInternal(); //// } //// //// int tkEnclosingType = declaringTypeHandle.GetToken(); //// //// // For example, TypeDescs do not have metadata tokens //// if(MdToken.IsNullToken( tkEnclosingType )) //// return list; //// //// ModuleHandle moduleHandle = declaringTypeHandle.GetModuleHandle(); //// MetadataImport scope = moduleHandle.GetMetadataImport(); //// //// int cNestedClasses = scope.EnumNestedTypesCount( tkEnclosingType ); //// int* tkNestedClasses = stackalloc int[cNestedClasses]; //// scope.EnumNestedTypes( tkEnclosingType, tkNestedClasses, cNestedClasses ); //// //// for(int i = 0; i < cNestedClasses; i++) //// { //// RuntimeTypeHandle nestedTypeHandle = new RuntimeTypeHandle(); //// //// try //// { //// nestedTypeHandle = moduleHandle.ResolveTypeHandle( tkNestedClasses[i] ); //// } //// catch(System.TypeLoadException) //// { //// // In a reflection emit scenario, we may have a token for a class which //// // has not been baked and hence cannot be loaded. //// continue; //// } //// //// if(!filter.Match( nestedTypeHandle.GetRuntimeType().GetTypeHandleInternal().GetUtf8Name() )) //// continue; //// //// list.Add( nestedTypeHandle.GetRuntimeType() ); //// } //// //// return list; //// } //// //// private unsafe List PopulateEvents( Filter filter ) //// { //// ASSERT.PRECONDITION( !ReflectedTypeHandle.IsNullHandle() ); //// //// Hashtable csEventInfos = new Hashtable(); //// //// RuntimeTypeHandle declaringTypeHandle = ReflectedTypeHandle; //// List list = new List(); //// //// bool isInterface = (declaringTypeHandle.GetAttributes() & TypeAttributes.ClassSemanticsMask) == TypeAttributes.Interface; //// //// if(!isInterface) //// { //// while(declaringTypeHandle.IsGenericVariable()) //// declaringTypeHandle = declaringTypeHandle.GetRuntimeType().BaseType.GetTypeHandleInternal(); //// //// // Populate associates off of the class hierarchy //// while(!declaringTypeHandle.IsNullHandle()) //// { //// PopulateEvents( filter, declaringTypeHandle, csEventInfos, list ); //// declaringTypeHandle = declaringTypeHandle.GetBaseTypeHandle(); //// } //// } //// else //// { //// // Populate associates for this interface //// PopulateEvents( filter, declaringTypeHandle, csEventInfos, list ); //// } //// //// return list; //// } //// //// private unsafe void PopulateEvents( //// Filter filter, RuntimeTypeHandle declaringTypeHandle, Hashtable csEventInfos, List list ) //// { //// int tkDeclaringType = declaringTypeHandle.GetToken(); //// //// // Arrays, Pointers, ByRef types and others generated only the fly by the RT do not have tokens. //// if(MdToken.IsNullToken( tkDeclaringType )) //// return; //// //// MetadataImport scope = declaringTypeHandle.GetModuleHandle().GetMetadataImport(); //// int cEvents = scope.EnumEventsCount( tkDeclaringType ); //// int* tkEvents = stackalloc int[cEvents]; //// scope.EnumEvents( tkDeclaringType, tkEvents, cEvents ); //// PopulateEvents( filter, declaringTypeHandle, scope, tkEvents, cEvents, csEventInfos, list ); //// } //// //// private unsafe void PopulateEvents( Filter filter, //// RuntimeTypeHandle declaringTypeHandle, MetadataImport scope, int* tkAssociates, int cAssociates, Hashtable csEventInfos, List list ) //// { //// for(int i = 0; i < cAssociates; i++) //// { //// int tkAssociate = tkAssociates[i]; //// bool isPrivate; //// //// ASSERT.PRECONDITION( !MdToken.IsNullToken( tkAssociate ) ); //// ASSERT.PRECONDITION( MdToken.IsTokenOfType( tkAssociate, MetadataTokenType.Event ) ); //// //// Utf8String name; //// name = scope.GetName( tkAssociate ); //// //// if(!filter.Match( name )) //// continue; //// //// RuntimeEventInfo eventInfo = new RuntimeEventInfo( //// tkAssociate, declaringTypeHandle.GetRuntimeType() as RuntimeType, m_runtimeTypeCache, out isPrivate ); //// //// #region Remove Inherited Privates //// if(!declaringTypeHandle.Equals( m_runtimeTypeCache.RuntimeTypeHandle ) && isPrivate) //// continue; //// #endregion //// //// #region Remove Duplicates //// if(csEventInfos[eventInfo.Name] != null) //// continue; //// //// csEventInfos[eventInfo.Name] = eventInfo; //// #endregion //// //// list.Add( eventInfo ); //// } //// } //// //// private unsafe List PopulateProperties( Filter filter ) //// { //// ASSERT.PRECONDITION( !ReflectedTypeHandle.IsNullHandle() ); //// ASSERT.CONSISTENCY_CHECK( m_csMemberInfos == null ); //// //// Hashtable csPropertyInfos = new Hashtable(); //// //// RuntimeTypeHandle declaringTypeHandle = ReflectedTypeHandle; //// List list = new List(); //// //// bool isInterface = (declaringTypeHandle.GetAttributes() & TypeAttributes.ClassSemanticsMask) == TypeAttributes.Interface; //// //// if(!isInterface) //// { //// while(declaringTypeHandle.IsGenericVariable()) //// declaringTypeHandle = declaringTypeHandle.GetRuntimeType().BaseType.GetTypeHandleInternal(); //// //// // Populate associates off of the class hierarchy //// while(!declaringTypeHandle.IsNullHandle()) //// { //// PopulateProperties( filter, declaringTypeHandle, csPropertyInfos, list ); //// declaringTypeHandle = declaringTypeHandle.GetBaseTypeHandle(); //// } //// } //// else //// { //// // Populate associates for this interface //// PopulateProperties( filter, declaringTypeHandle, csPropertyInfos, list ); //// } //// //// return list; //// } //// //// private unsafe void PopulateProperties( Filter filter, //// RuntimeTypeHandle declaringTypeHandle, Hashtable csPropertyInfos, List list ) //// { //// int tkDeclaringType = declaringTypeHandle.GetToken(); //// //// // Arrays, Pointers, ByRef types and others generated only the fly by the RT do not have tokens. //// if(MdToken.IsNullToken( tkDeclaringType )) //// return; //// //// MetadataImport scope = declaringTypeHandle.GetModuleHandle().GetMetadataImport(); //// int cProperties = scope.EnumPropertiesCount( tkDeclaringType ); //// int* tkProperties = stackalloc int[cProperties]; //// scope.EnumProperties( tkDeclaringType, tkProperties, cProperties ); //// PopulateProperties( filter, declaringTypeHandle, tkProperties, cProperties, csPropertyInfos, list ); //// } //// //// private unsafe void PopulateProperties( Filter filter, //// RuntimeTypeHandle declaringTypeHandle, int* tkAssociates, int cProperties, Hashtable csPropertyInfos, List list ) //// { //// for(int i = 0; i < cProperties; i++) //// { //// int tkAssociate = tkAssociates[i]; //// bool isPrivate; //// //// ASSERT.PRECONDITION( !MdToken.IsNullToken( tkAssociate ) ); //// ASSERT.PRECONDITION( MdToken.IsTokenOfType( tkAssociate, MetadataTokenType.Property ) ); //// //// Utf8String name; //// name = declaringTypeHandle.GetRuntimeType().Module.MetadataImport.GetName( tkAssociate ); //// //// if(!filter.Match( name )) //// continue; //// //// RuntimePropertyInfo propertyInfo = //// new RuntimePropertyInfo( //// tkAssociate, declaringTypeHandle.GetRuntimeType() as RuntimeType, m_runtimeTypeCache, out isPrivate ); //// //// #region Remove Privates //// if(!declaringTypeHandle.Equals( m_runtimeTypeCache.RuntimeTypeHandle ) && isPrivate) //// continue; //// #endregion //// //// #region Remove Duplicates //// List cache = csPropertyInfos[propertyInfo.Name] as List; //// //// if(cache == null) //// { //// cache = new List(); //// csPropertyInfos[propertyInfo.Name] = cache; //// } //// else //// { //// for(int j = 0; j < cache.Count; j++) //// { //// if(propertyInfo.EqualsSig( cache[j] )) //// { //// cache = null; //// break; //// } //// } //// } //// //// if(cache == null) //// continue; //// //// cache.Add( propertyInfo ); //// #endregion //// //// list.Add( propertyInfo ); //// } //// } //// #endregion //// //// #region NonPrivate Members //// internal CerArrayList GetMemberList( MemberListType listType, string name, CacheType cacheType ) //// { //// CerArrayList list = null; //// //// switch(listType) //// { //// case MemberListType.CaseSensitive: //// if(m_csMemberInfos == null) //// { //// return Populate( name, listType, cacheType ); //// } //// else //// { //// list = m_csMemberInfos[name]; //// //// if(list == null) //// return Populate( name, listType, cacheType ); //// //// return list; //// } //// //// case MemberListType.All: //// if(m_cacheComplete) //// return m_root; //// //// return Populate( null, listType, cacheType ); //// //// default: //// if(m_cisMemberInfos == null) //// { //// return Populate( name, listType, cacheType ); //// } //// else //// { //// list = m_cisMemberInfos[name]; //// //// if(list == null) //// return Populate( name, listType, cacheType ); //// //// return list; //// } //// } //// } //// //// internal RuntimeTypeHandle ReflectedTypeHandle //// { //// get //// { //// return m_runtimeTypeCache.RuntimeTypeHandle; //// } //// } //// internal RuntimeType ReflectedType //// { //// get //// { //// return ReflectedTypeHandle.GetRuntimeType(); //// } //// } //// #endregion //// } //// #endregion //// //// #region Private Data Members //// private WhatsCached m_whatsCached; //// private RuntimeTypeHandle m_runtimeTypeHandle; //// private RuntimeType m_runtimeType; //// private RuntimeType m_enclosingType; //// private TypeCode m_typeCode; //// private string m_name, m_fullname, m_toString, m_namespace; //// private bool m_isGlobal; //// private bool m_bIsDomainInitialized; //// private MemberInfoCache m_methodInfoCache; //// private MemberInfoCache m_constructorInfoCache; //// private MemberInfoCache m_fieldInfoCache; //// private MemberInfoCache m_interfaceCache; //// private MemberInfoCache m_nestedClassesCache; //// private MemberInfoCache m_propertyInfoCache; //// private MemberInfoCache m_eventInfoCache; //// private CerHashtable m_methodInstantiations; //// #endregion //// //// #region Constructor //// internal RuntimeTypeCache( RuntimeType runtimeType ) //// { //// m_typeCode = TypeCode.Empty; //// m_runtimeType = runtimeType; //// m_runtimeTypeHandle = runtimeType.GetTypeHandleInternal(); //// m_isGlobal = m_runtimeTypeHandle.GetModuleHandle().GetModuleTypeHandle().Equals( m_runtimeTypeHandle ); //// } //// #endregion //// //// #region Private Members //// private string ConstructName( ref string name, bool nameSpace, bool fullinst, bool assembly ) //// { //// if(name == null) //// { //// name = RuntimeTypeHandle.ConstructName( nameSpace, fullinst, assembly ); //// } //// return name; //// } //// //// private CerArrayList GetMemberList( ref MemberInfoCache m_cache, MemberListType listType, string name, CacheType cacheType ) //// where T : MemberInfo //// { //// MemberInfoCache existingCache = GetMemberCache( ref m_cache ); //// return existingCache.GetMemberList( listType, name, cacheType ); //// } //// //// private MemberInfoCache GetMemberCache( ref MemberInfoCache m_cache ) //// where T : MemberInfo //// { //// MemberInfoCache existingCache = m_cache; //// //// if(existingCache == null) //// { //// MemberInfoCache newCache = new MemberInfoCache( this ); //// existingCache = Interlocked.CompareExchange( ref m_cache, newCache, null ); //// if(existingCache == null) //// existingCache = newCache; //// } //// //// return existingCache; //// } //// #endregion //// //// #region Internal Members //// internal bool DomainInitialized //// { //// get //// { //// return m_bIsDomainInitialized; //// } //// //// set //// { //// m_bIsDomainInitialized = value; //// } //// } //// //// internal string GetName() //// { //// return ConstructName( ref m_name, false, false, false ); //// } //// //// internal unsafe string GetNameSpace() //// { //// // @Optimization - Use ConstructName to populate m_namespace //// if(m_namespace == null) //// { //// Type type = m_runtimeType; //// type = type.GetRootElementType(); //// //// while(type.IsNested) //// type = type.DeclaringType; //// //// m_namespace = type.GetTypeHandleInternal().GetModuleHandle( //// ).GetMetadataImport().GetNamespace( type.MetadataToken ).ToString(); //// } //// //// return m_namespace; //// } //// //// internal string GetToString() //// { //// return ConstructName( ref m_toString, true, false, false ); //// } //// //// internal string GetFullName() //// { //// if(!m_runtimeType.IsGenericTypeDefinition && m_runtimeType.ContainsGenericParameters) //// return null; //// //// return ConstructName( ref m_fullname, true, true, false ); //// } //// //// internal TypeCode TypeCode //// { //// get //// { //// return m_typeCode; //// } //// //// set //// { //// m_typeCode = value; //// } //// } //// //// internal unsafe RuntimeType GetEnclosingType() //// { //// if((m_whatsCached & WhatsCached.EnclosingType) == 0) //// { //// m_enclosingType = RuntimeTypeHandle.GetDeclaringType().GetRuntimeType(); //// //// m_whatsCached |= WhatsCached.EnclosingType; //// } //// //// return m_enclosingType; //// } //// //// internal bool IsGlobal //// { //// [ReliabilityContract( Consistency.WillNotCorruptState, Cer.Success )] //// get //// { //// return m_isGlobal; //// } //// } //// //// internal RuntimeType RuntimeType //// { //// get //// { //// return m_runtimeType; //// } //// } //// //// internal RuntimeTypeHandle RuntimeTypeHandle //// { //// get //// { //// return m_runtimeTypeHandle; //// } //// } //// internal void InvalidateCachedNestedType() //// { //// m_nestedClassesCache = null; //// } //// #endregion //// //// #region Caches Accessors //// internal MethodInfo GetGenericMethodInfo( RuntimeMethodHandle genericMethod ) //// { //// if(m_methodInstantiations == null) //// Interlocked.CompareExchange( ref m_methodInstantiations, new CerHashtable(), null ); //// //// RuntimeMethodInfo rmi = new RuntimeMethodInfo( //// genericMethod, genericMethod.GetDeclaringType(), this, //// genericMethod.GetAttributes(), (BindingFlags)(-1) ); //// //// RuntimeMethodInfo crmi = null; //// //// crmi = m_methodInstantiations[rmi]; //// if(crmi != null) //// return crmi; //// //// bool lockTaken = false; //// bool preallocationComplete = false; //// RuntimeHelpers.PrepareConstrainedRegions(); //// try //// { //// Monitor.ReliableEnter( this, ref lockTaken ); //// //// crmi = m_methodInstantiations[rmi]; //// if(crmi != null) //// return crmi; //// //// m_methodInstantiations.Preallocate( 1 ); //// //// preallocationComplete = true; //// } //// finally //// { //// if(preallocationComplete) //// { //// m_methodInstantiations[rmi] = rmi; //// } //// //// if(lockTaken) //// { //// Monitor.Exit( this ); //// } //// } //// //// return rmi; //// } //// //// internal CerArrayList GetMethodList( MemberListType listType, string name ) //// { //// return GetMemberList( ref m_methodInfoCache, listType, name, CacheType.Method ); //// } //// //// internal CerArrayList GetConstructorList( MemberListType listType, string name ) //// { //// return GetMemberList( ref m_constructorInfoCache, listType, name, CacheType.Constructor ); //// } //// //// internal CerArrayList GetPropertyList( MemberListType listType, string name ) //// { //// return GetMemberList( ref m_propertyInfoCache, listType, name, CacheType.Property ); //// } //// //// internal CerArrayList GetEventList( MemberListType listType, string name ) //// { //// return GetMemberList( ref m_eventInfoCache, listType, name, CacheType.Event ); //// } //// //// internal CerArrayList GetFieldList( MemberListType listType, string name ) //// { //// return GetMemberList( ref m_fieldInfoCache, listType, name, CacheType.Field ); //// } //// //// internal CerArrayList GetInterfaceList( MemberListType listType, string name ) //// { //// return GetMemberList( ref m_interfaceCache, listType, name, CacheType.Interface ); //// } //// //// internal CerArrayList GetNestedTypeList( MemberListType listType, string name ) //// { //// return GetMemberList( ref m_nestedClassesCache, listType, name, CacheType.NestedType ); //// } //// //// internal MethodBase GetMethod( RuntimeTypeHandle declaringType, RuntimeMethodHandle method ) //// { //// GetMemberCache( ref m_methodInfoCache ); //// return m_methodInfoCache.AddMethod( declaringType, method, CacheType.Method ); //// } //// //// internal MethodBase GetConstructor( RuntimeTypeHandle declaringType, RuntimeMethodHandle constructor ) //// { //// GetMemberCache( ref m_constructorInfoCache ); //// return m_constructorInfoCache.AddMethod( declaringType, constructor, CacheType.Constructor ); //// } //// //// internal FieldInfo GetField( RuntimeFieldHandle field ) //// { //// GetMemberCache( ref m_fieldInfoCache ); //// return m_fieldInfoCache.AddField( field ); //// } //// //// #endregion //// } #endregion #region Static Members #region Internal //// [ResourceExposure( ResourceScope.None )] //// [MethodImpl( MethodImplOptions.InternalCall )] //// static internal extern void PrepareMemberInfoCache( RuntimeTypeHandle rt ); //// //// internal static MethodBase GetMethodBase( ModuleHandle scope, int typeMetadataToken ) //// { //// return GetMethodBase( scope.ResolveMethodHandle( typeMetadataToken ) ); //// } //// //// internal static MethodBase GetMethodBase( Module scope, int typeMetadataToken ) //// { //// return GetMethodBase( scope.GetModuleHandle(), typeMetadataToken ); //// } //// //// internal static MethodBase GetMethodBase( RuntimeMethodHandle methodHandle ) //// { //// return GetMethodBase( RuntimeTypeHandle.EmptyHandle, methodHandle ); //// } //// //// internal unsafe static MethodBase GetMethodBase( RuntimeTypeHandle reflectedTypeHandle, RuntimeMethodHandle methodHandle ) //// { //// ASSERT.CONSISTENCY_CHECK( !reflectedTypeHandle.IsNullHandle() ); //// ASSERT.CONSISTENCY_CHECK( !methodHandle.IsNullHandle() ); //// //// if(methodHandle.IsDynamicMethod()) //// { //// Resolver resolver = methodHandle.GetResolver(); //// //// if(resolver != null) //// { //// return resolver.GetDynamicMethod(); //// } //// //// return null; //// } //// //// // verify the type/method relationship //// Type declaredType = methodHandle.GetDeclaringType().GetRuntimeType(); //// RuntimeType reflectedType = reflectedTypeHandle.GetRuntimeType(); //// //// if(reflectedType == null) //// { //// reflectedType = declaredType as RuntimeType; //// } //// //// if(reflectedType.IsArray) //// { //// MethodBase[] methodBases = reflectedType.GetMember( methodHandle.GetName(), MemberTypes.Constructor | MemberTypes.Method, //// BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance ) as MethodBase[]; //// //// bool loaderAssuredCompatible = false; //// for(int i = 0; i < methodBases.Length; i++) //// { //// if(methodBases[0].GetMethodHandle() == methodHandle) //// { //// loaderAssuredCompatible = true; //// } //// } //// //// if(!loaderAssuredCompatible) //// { //// throw new ArgumentException( String.Format( CultureInfo.CurrentCulture, Environment.GetResourceString( "Argument_ResolveMethodHandle" ), reflectedType.ToString(), declaredType.ToString() ) ); //// } //// //// declaredType = reflectedType; //// } //// else if(!declaredType.IsAssignableFrom( reflectedType )) //// { //// if(!declaredType.IsGenericType) //// { //// throw new ArgumentException( String.Format( CultureInfo.CurrentCulture, Environment.GetResourceString( "Argument_ResolveMethodHandle" ), reflectedType.ToString(), declaredType.ToString() ) ); //// } //// //// // ignoring instantiation is the ReflectedType a subtype of the DeclaringType //// Type declaringDefinition = declaredType.GetGenericTypeDefinition(); //// //// Type baseType = reflectedType; //// //// while(baseType != null) //// { //// Type baseDefinition = baseType; //// //// if(baseDefinition.IsGenericType && !baseType.IsGenericTypeDefinition) //// { //// baseDefinition = baseDefinition.GetGenericTypeDefinition(); //// } //// //// if(baseDefinition.Equals( declaringDefinition )) //// { //// break; //// } //// //// baseType = baseType.BaseType; //// } //// //// if(baseType == null) //// { //// // ignoring instantiation is the ReflectedType is not a subtype of the DeclaringType //// throw new ArgumentException( String.Format( CultureInfo.CurrentCulture, Environment.GetResourceString( "Argument_ResolveMethodHandle" ), reflectedType.ToString(), declaredType.ToString() ) ); //// } //// //// // remap the method to same method on the subclass ReflectedType //// declaredType = baseType; //// //// RuntimeTypeHandle[] methodInstantiation = methodHandle.GetMethodInstantiation(); //// //// bool bIsGenericMethodDefinition = methodHandle.IsGenericMethodDefinition(); //// //// // lookup via v-table slot the RuntimeMethodHandle on the new declaring type //// methodHandle = methodHandle.GetMethodFromCanonical( declaredType.GetTypeHandleInternal() ); //// //// // if the origional methodHandle was the definition than we don't need to rebind generic method arguments //// // because all RuntimeMethodHandles retrieved off of the cannonical method table are definitions. That's //// // why for everything else we need to rebind the generic method arguments. //// if(!bIsGenericMethodDefinition) //// { //// // rebind any generic method arguments //// if(methodInstantiation != null) //// { //// methodHandle = methodHandle.GetInstantiatingStub( declaredType.GetTypeHandleInternal(), methodInstantiation ); //// } //// else //// { //// methodHandle = methodHandle.GetInstantiatingStubIfNeeded( declaredType.GetTypeHandleInternal() ); //// } //// } //// } //// //// if(methodHandle.IsConstructor()) //// { //// return reflectedType.Cache.GetConstructor( declaredType.GetTypeHandleInternal(), methodHandle ); //// } //// //// if(methodHandle.HasMethodInstantiation() && !methodHandle.IsGenericMethodDefinition()) //// { //// return reflectedType.Cache.GetGenericMethodInfo( methodHandle ); //// } //// //// return reflectedType.Cache.GetMethod( declaredType.GetTypeHandleInternal(), methodHandle ); //// } //// //// internal bool DomainInitialized //// { //// get //// { //// return Cache.DomainInitialized; //// } //// //// set //// { //// Cache.DomainInitialized = value; //// } //// } //// //// internal unsafe static FieldInfo GetFieldInfo( RuntimeFieldHandle fieldHandle ) //// { //// return GetFieldInfo( fieldHandle.GetApproxDeclaringType(), fieldHandle ); //// } //// //// internal unsafe static FieldInfo GetFieldInfo( RuntimeTypeHandle reflectedTypeHandle, RuntimeFieldHandle fieldHandle ) //// { //// // verify the type/method relationship //// if(reflectedTypeHandle.IsNullHandle()) //// { //// reflectedTypeHandle = fieldHandle.GetApproxDeclaringType(); //// } //// else //// { //// RuntimeTypeHandle declaredTypeHandle = fieldHandle.GetApproxDeclaringType(); //// if(!reflectedTypeHandle.Equals( declaredTypeHandle )) //// { //// if(!fieldHandle.AcquiresContextFromThis() || !declaredTypeHandle.GetCanonicalHandle().Equals( reflectedTypeHandle.GetCanonicalHandle() )) //// { //// throw new ArgumentException( String.Format( //// CultureInfo.CurrentCulture, Environment.GetResourceString( "Argument_ResolveFieldHandle" ), //// reflectedTypeHandle.GetRuntimeType().ToString(), //// declaredTypeHandle.GetRuntimeType().ToString() ) ); //// } //// } //// } //// //// return reflectedTypeHandle.GetRuntimeType().Cache.GetField( fieldHandle ); //// } //// //// // Called internally //// internal unsafe static PropertyInfo GetPropertyInfo( RuntimeTypeHandle reflectedTypeHandle, int tkProperty ) //// { //// RuntimePropertyInfo property = null; //// CerArrayList candidates = reflectedTypeHandle.GetRuntimeType().Cache.GetPropertyList( MemberListType.All, null ); //// //// for(int i = 0; i < candidates.Count; i++) //// { //// property = candidates[i]; //// if(property.MetadataToken == tkProperty) //// { //// return property; //// } //// } //// //// ASSERT.UNREACHABLE(); //// throw new SystemException(); //// } //// //// private static void ThrowIfTypeNeverValidGenericArgument( Type type ) //// { //// if(type.IsPointer || type.IsByRef || type == typeof( void )) //// { //// throw new ArgumentException( String.Format( CultureInfo.CurrentCulture, Environment.GetResourceString( "Argument_NeverValidGenericArgument" ), type.ToString() ) ); //// } //// } //// //// //// internal static void SanityCheckGenericArguments( Type[] genericArguments, Type[] genericParamters ) //// { //// if(genericArguments == null) //// { //// throw new ArgumentNullException(); //// } //// //// for(int i = 0; i < genericArguments.Length; i++) //// { //// if(genericArguments[i] == null) //// { //// throw new ArgumentNullException(); //// } //// //// ThrowIfTypeNeverValidGenericArgument( genericArguments[i] ); //// } //// //// if(genericArguments.Length != genericParamters.Length) //// { //// throw new ArgumentException( String.Format( CultureInfo.CurrentCulture, Environment.GetResourceString( "Argument_NotEnoughGenArguments", genericArguments.Length, genericParamters.Length ) ) ); //// } //// } //// //// internal static void ValidateGenericArguments( MemberInfo definition, Type[] genericArguments, Exception e ) //// { //// RuntimeTypeHandle[] typeContextHandle = null; //// RuntimeTypeHandle[] methodContextHandle = null; //// Type[] genericParamters = null; //// //// if(definition is Type) //// { //// Type genericTypeDefinition = (Type)definition; //// //// genericParamters = genericTypeDefinition.GetGenericArguments(); //// typeContextHandle = new RuntimeTypeHandle[genericArguments.Length]; //// for(int i = 0; i < genericArguments.Length; i++) //// { //// typeContextHandle[i] = genericArguments[i].GetTypeHandleInternal(); //// } //// } //// else //// { //// MethodInfo genericMethodDefinition = (MethodInfo)definition; //// //// genericParamters = genericMethodDefinition.GetGenericArguments(); //// methodContextHandle = new RuntimeTypeHandle[genericArguments.Length]; //// for(int i = 0; i < genericArguments.Length; i++) //// { //// methodContextHandle[i] = genericArguments[i].GetTypeHandleInternal(); //// } //// //// Type declaringType = genericMethodDefinition.DeclaringType; //// if(declaringType != null) //// { //// typeContextHandle = declaringType.GetTypeHandleInternal().GetInstantiation(); //// } //// } //// //// for(int i = 0; i < genericArguments.Length; i++) //// { //// Type genericArgument = genericArguments[i]; //// Type genericParameter = genericParamters[i]; //// //// if(!genericParameter.GetTypeHandleInternal().SatisfiesConstraints( typeContextHandle, methodContextHandle, genericArgument.GetTypeHandleInternal() )) //// { //// throw new ArgumentException( String.Format( CultureInfo.CurrentCulture, Environment.GetResourceString( "Argument_GenConstraintViolation" ), //// i.ToString( CultureInfo.CurrentCulture ), genericArgument.ToString(), definition.ToString(), genericParameter.ToString() ), e ); //// } //// } //// } //// //// private static void SplitName( string fullname, out string name, out string ns ) //// { //// name = null; //// ns = null; //// //// if(fullname == null) //// { //// return; //// } //// //// // Get namespace //// int nsDelimiter = fullname.LastIndexOf( ".", StringComparison.Ordinal ); //// if(nsDelimiter != -1) //// { //// ns = fullname.Substring( 0, nsDelimiter ); //// int nameLength = fullname.Length - ns.Length - 1; //// if(nameLength != 0) //// { //// name = fullname.Substring( nsDelimiter + 1, nameLength ); //// } //// else //// { //// name = ""; //// } //// //// ASSERT.CONSISTENCY_CHECK( fullname.Equals( ns + "." + name ) ); //// } //// else //// { //// name = fullname; //// } //// //// } #endregion #region Filters //// internal static BindingFlags FilterPreCalculate( bool isPublic, bool isInherited, bool isStatic ) //// { //// BindingFlags bindingFlags = isPublic ? BindingFlags.Public : BindingFlags.NonPublic; //// //// if(isInherited) //// { //// // We arrange things so the DeclaredOnly flag means "include inherited members" //// bindingFlags |= BindingFlags.DeclaredOnly; //// //// if(isStatic) //// { //// bindingFlags |= BindingFlags.Static | BindingFlags.FlattenHierarchy; //// } //// else //// { //// bindingFlags |= BindingFlags.Instance; //// } //// } //// else //// { //// if(isStatic) //// { //// bindingFlags |= BindingFlags.Static; //// } //// else //// { //// bindingFlags |= BindingFlags.Instance; //// } //// } //// //// return bindingFlags; //// } //// //// private static void FilterHelper( BindingFlags bindingFlags , //// ref string name , //// bool allowPrefixLookup, //// out bool prefixLookup , //// out bool ignoreCase , //// out MemberListType listType ) //// { //// prefixLookup = false; //// ignoreCase = false; //// //// if(name != null) //// { //// if((bindingFlags & BindingFlags.IgnoreCase) != 0) //// { //// name = name.ToLower( CultureInfo.InvariantCulture ); //// ignoreCase = true; //// listType = MemberListType.CaseInsensitive; //// } //// else //// { //// listType = MemberListType.CaseSensitive; //// } //// //// if(allowPrefixLookup && name.EndsWith( "*", StringComparison.Ordinal )) //// { //// name = name.Substring( 0, name.Length - 1 ); //// prefixLookup = true; //// listType = MemberListType.All; //// } //// } //// else //// { //// listType = MemberListType.All; //// } //// } //// //// private static void FilterHelper( BindingFlags bindingFlags, ref string name, out bool ignoreCase, out MemberListType listType ) //// { //// bool prefixLookup; //// //// FilterHelper( bindingFlags, ref name, false, out prefixLookup, out ignoreCase, out listType ); //// } //// //// private static bool FilterApplyPrefixLookup( MemberInfo memberInfo, string name, bool ignoreCase ) //// { //// ASSERT.CONSISTENCY_CHECK( name != null ); //// //// if(ignoreCase) //// { //// if(!memberInfo.Name.ToLower( CultureInfo.InvariantCulture ).StartsWith( name, StringComparison.Ordinal )) //// { //// return false; //// } //// } //// else //// { //// if(!memberInfo.Name.StartsWith( name, StringComparison.Ordinal )) //// { //// return false; //// } //// } //// //// return true; //// } //// //// //// private static bool FilterApplyBase( MemberInfo memberInfo , //// BindingFlags bindingFlags , //// bool isPublic , //// bool isNonProtectedInternal, //// bool isStatic , //// string name , //// bool prefixLookup ) //// { //// #region Preconditions //// ASSERT.PRECONDITION( memberInfo != null ); //// ASSERT.PRECONDITION( name == null || (bindingFlags & BindingFlags.IgnoreCase) == 0 || (name.ToLower( CultureInfo.InvariantCulture ).Equals( name )) ); //// #endregion //// //// #region Filter by Public & Private //// if(isPublic) //// { //// if((bindingFlags & BindingFlags.Public) == 0) //// { //// return false; //// } //// } //// else //// { //// if((bindingFlags & BindingFlags.NonPublic) == 0) //// { //// return false; //// } //// } //// #endregion //// //// bool isInherited = memberInfo.DeclaringType != memberInfo.ReflectedType; //// //// #region Filter by DeclaredOnly //// if((bindingFlags & BindingFlags.DeclaredOnly) != 0 && isInherited) //// { //// return false; //// } //// #endregion //// //// #region Filter by Static & Instance //// if(memberInfo.MemberType != MemberTypes.TypeInfo && //// memberInfo.MemberType != MemberTypes.NestedType ) //// { //// if(isStatic) //// { //// if((bindingFlags & BindingFlags.FlattenHierarchy) == 0 && isInherited) //// { //// return false; //// } //// //// if((bindingFlags & BindingFlags.Static) == 0) //// { //// return false; //// } //// } //// else //// { //// if((bindingFlags & BindingFlags.Instance) == 0) //// { //// return false; //// } //// } //// } //// #endregion //// //// #region Filter by name wrt prefixLookup and implicitly by case sensitivity //// if(prefixLookup == true) //// { //// if(!FilterApplyPrefixLookup( memberInfo, name, (bindingFlags & BindingFlags.IgnoreCase) != 0 )) //// { //// return false; //// } //// } //// #endregion //// //// #region Asymmetries //// // @Asymmetry - Internal, inherited, instance, non-protected, non-virtual, non-abstract members returned //// // iff BindingFlags !DeclaredOnly, Instance and Public are present except for fields //// if(((bindingFlags & BindingFlags.DeclaredOnly) == 0) && // DeclaredOnly not present //// isInherited && // Is inherited Member //// //// (isNonProtectedInternal) && // Is non-protected internal member //// ((bindingFlags & BindingFlags.NonPublic) != 0) && // BindingFlag.NonPublic present //// //// (!isStatic) && // Is instance member //// ((bindingFlags & BindingFlags.Instance) != 0)) // BindingFlag.Instance present //// { //// MethodInfo methodInfo = memberInfo as MethodInfo; //// //// if(methodInfo == null) //// { //// return false; //// } //// //// if(!methodInfo.IsVirtual && !methodInfo.IsAbstract) //// { //// return false; //// } //// } //// #endregion //// //// return true; //// } //// //// //// private static bool FilterApplyType( Type type, BindingFlags bindingFlags, string name, bool prefixLookup, string ns ) //// { //// ASSERT.PRECONDITION( type != null ); //// ASSERT.PRECONDITION( type is RuntimeType ); //// //// bool isPublic = type.IsNestedPublic || type.IsPublic; //// bool isStatic = false; //// //// if(!RuntimeType.FilterApplyBase( type, bindingFlags, isPublic, type.IsNestedAssembly, isStatic, name, prefixLookup )) //// { //// return false; //// } //// //// if(ns != null && !type.Namespace.Equals( ns )) //// { //// return false; //// } //// //// return true; //// } //// //// //// private static bool FilterApplyMethodBaseInfo( MethodBase methodBase , //// BindingFlags bindingFlags , //// string name , //// CallingConventions callConv , //// Type[] argumentTypes, //// bool prefixLookup ) //// { //// ASSERT.PRECONDITION( methodBase != null ); //// //// #region Apply Base Filter //// bindingFlags ^= BindingFlags.DeclaredOnly; //// BindingFlags matchFlags; //// //// RuntimeMethodInfo methodInfo = methodBase as RuntimeMethodInfo; //// if(methodInfo == null) //// { //// RuntimeConstructorInfo constructorInfo = methodBase as RuntimeConstructorInfo; //// matchFlags = constructorInfo.BindingFlags; //// } //// else //// { //// matchFlags = methodInfo.BindingFlags; //// } //// //// if((bindingFlags & matchFlags) != matchFlags || //// (prefixLookup && !FilterApplyPrefixLookup( methodBase, name, (bindingFlags & BindingFlags.IgnoreCase) != 0 ))) //// { //// return false; //// } //// #endregion //// //// return FilterApplyMethodBaseInfo( methodBase, bindingFlags, callConv, argumentTypes ); //// } //// //// //// private static bool FilterApplyMethodBaseInfo( MethodBase methodBase , //// BindingFlags bindingFlags , //// CallingConventions callConv , //// Type[] argumentTypes ) //// { //// #region Check CallingConvention //// if((callConv & CallingConventions.Any) == 0) //// { //// if((callConv & CallingConventions.VarArgs) != 0 && (methodBase.CallingConvention & CallingConventions.VarArgs) == 0) //// { //// return false; //// } //// //// if((callConv & CallingConventions.Standard) != 0 && (methodBase.CallingConvention & CallingConventions.Standard) == 0) //// { //// return false; //// } //// } //// #endregion //// //// #region If argumentTypes supplied //// if(argumentTypes != null) //// { //// ParameterInfo[] parameterInfos = methodBase.GetParametersNoCopy(); //// //// if(argumentTypes.Length != parameterInfos.Length) //// { //// #region Invoke Member, Get\Set & Create Instance specific case //// // If the number of supplied arguments differs than the number in the signature AND //// // we are not filtering for a dynamic call -- InvokeMethod or CreateInstance -- filter out the method. //// if((bindingFlags & (BindingFlags.InvokeMethod | BindingFlags.CreateInstance | BindingFlags.GetProperty | BindingFlags.SetProperty)) == 0) //// { //// return false; //// } //// //// bool testForParamArray = false; //// bool excessSuppliedArguments = argumentTypes.Length > parameterInfos.Length; //// //// if(excessSuppliedArguments) //// { // more supplied arguments than parameters, additional arguments could be vararg //// #region Varargs //// // If method is not vararg, additional arguments can not be passed as vararg //// if((methodBase.CallingConvention & CallingConventions.VarArgs) == 0) //// { //// testForParamArray = true; //// } //// else //// { //// // If Binding flags did not include varargs we would have filtered this vararg method. //// // This Invariant established during callConv check. //// ASSERT.CONSISTENCY_CHECK( (callConv & CallingConventions.VarArgs) != 0 ); //// } //// #endregion //// } //// else //// {// fewer supplied arguments than parameters, missing arguments could be optional //// #region OptionalParamBinding //// if((bindingFlags & BindingFlags.OptionalParamBinding) == 0) //// { //// testForParamArray = true; //// } //// else //// { //// // From our existing code, our policy here is that if a parameterInfo //// // is optional then all subsequent parameterInfos shall be optional. //// //// // Thus, iff the first parameterInfo is not optional then this MethodInfo is no longer a canidate. //// if(!parameterInfos[argumentTypes.Length].IsOptional) //// { //// testForParamArray = true; //// } //// } //// #endregion //// } //// //// #region ParamArray //// if(testForParamArray) //// { //// if(parameterInfos.Length == 0) //// { //// return false; //// } //// //// // The last argument of the signature could be a param array. //// bool shortByMoreThanOneSuppliedArgument = argumentTypes.Length < parameterInfos.Length - 1; //// //// if(shortByMoreThanOneSuppliedArgument) //// { //// return false; //// } //// //// ParameterInfo lastParameter = parameterInfos[parameterInfos.Length - 1]; //// //// if(!lastParameter.ParameterType.IsArray) //// { //// return false; //// } //// //// if(!lastParameter.IsDefined( typeof( ParamArrayAttribute ), false )) //// { //// return false; //// } //// } //// #endregion //// //// #endregion //// } //// else //// { //// #region Exact Binding //// if((bindingFlags & BindingFlags.ExactBinding) != 0) //// { //// // Legacy behavior is to ignore ExactBinding when InvokeMember is specified. //// // Why filter by InvokeMember? If the answer is we leave this to the binder then why not leave //// // all the rest of this to the binder too? Further, what other semanitc would the binder //// // use for BindingFlags.ExactBinding besides this one? Further, why not include CreateInstance //// // in this if statement? That's just InvokeMethod with a constructor, right? //// if((bindingFlags & (BindingFlags.InvokeMethod)) == 0) //// { //// for(int i = 0; i < parameterInfos.Length; i++) //// { //// // a null argument type implies a null arg which is always a perfect match //// if(argumentTypes[i] != null && parameterInfos[i].ParameterType != argumentTypes[i]) //// { //// return false; //// } //// } //// } //// } //// #endregion //// } //// } //// #endregion //// //// return true; //// } #endregion #endregion #region Private Data Members private RuntimeTypeHandle m_handle; //// private IntPtr m_cache; //// private class TypeCacheQueue //// { //// // must be a power of 2 for this to work //// const int QUEUE_SIZE = 4; //// //// Object[] liveCache; //// //// internal TypeCacheQueue() //// { //// liveCache = new Object[QUEUE_SIZE]; //// } //// } //// private static TypeCacheQueue s_typeCache = null; #endregion #region Constructor private RuntimeType( RuntimeTypeHandle typeHandle ) { m_handle = typeHandle; } internal RuntimeType() { } #endregion #region Private\Internal Members //// [ReliabilityContract( Consistency.WillNotCorruptState, Cer.Success )] //// internal override bool CacheEquals( object o ) //// { //// RuntimeType m = o as RuntimeType; //// //// if(m == null) //// { //// return false; //// } //// //// return m.m_handle.Equals( m_handle ); //// } //// //// private new RuntimeTypeCache Cache //// { //// [ResourceExposure( ResourceScope.None )] //// [ResourceConsumption( ResourceScope.AppDomain, ResourceScope.AppDomain )] //// get //// { //// if(m_cache.IsNull()) //// { //// IntPtr newgcHandle = m_handle.GetGCHandle( GCHandleType.WeakTrackResurrection ); //// IntPtr gcHandle = Interlocked.CompareExchange( ref m_cache, newgcHandle, (IntPtr)0 ); //// if(!gcHandle.IsNull()) //// { //// m_handle.FreeGCHandle( newgcHandle ); //// } //// } //// //// RuntimeTypeCache cache = GCHandle.InternalGet( m_cache ) as RuntimeTypeCache; //// if(cache == null) //// { //// cache = new RuntimeTypeCache( this ); //// //// RuntimeTypeCache existingCache = GCHandle.InternalCompareExchange( m_cache, cache, null, false ) as RuntimeTypeCache; //// if(existingCache != null) //// { //// cache = existingCache; //// } //// if(s_typeCache == null) //// { //// s_typeCache = new TypeCacheQueue(); //// } //// //s_typeCache.Add(cache); //// } //// /* //// RuntimeTypeCache cache = m_cache as RuntimeTypeCache; //// if (cache == null) //// { //// cache = new RuntimeTypeCache(TypeHandle); //// RuntimeTypeCache existingCache = Interlocked.CompareExchange(ref m_cache, cache, null) as RuntimeTypeCache; //// if (existingCache != null) //// cache = existingCache; //// } //// */ //// ASSERT.CONSISTENCY_CHECK( cache != null ); //// return cache; //// } //// } #endregion #region Type Overrides #region Get XXXInfo Candidates //// private MethodInfo[] GetMethodCandidates( String name , //// BindingFlags bindingAttr , //// CallingConventions callConv , //// Type[] types , //// bool allowPrefixLookup ) //// { //// bool prefixLookup; //// bool ignoreCase; //// MemberListType listType; //// //// RuntimeType.FilterHelper( bindingAttr, ref name, allowPrefixLookup, out prefixLookup, out ignoreCase, out listType ); //// //// List candidates = new List(); //// CerArrayList cache = Cache.GetMethodList( listType, name ); //// //// bindingAttr ^= BindingFlags.DeclaredOnly; //// //// for(int i = 0; i < cache.Count; i++) //// { //// RuntimeMethodInfo methodInfo = cache[i]; //// //// if((bindingAttr & methodInfo.BindingFlags) == methodInfo.BindingFlags && //// FilterApplyMethodBaseInfo( methodInfo, bindingAttr, callConv, types ) && //// (!prefixLookup || RuntimeType.FilterApplyPrefixLookup( methodInfo, name, ignoreCase ))) //// { //// candidates.Add( methodInfo ); //// } //// } //// //// return candidates.ToArray(); //// } //// //// //// private ConstructorInfo[] GetConstructorCandidates( string name , //// BindingFlags bindingAttr , //// CallingConventions callConv , //// Type[] types , //// bool allowPrefixLookup ) //// { //// bool prefixLookup; //// bool ignoreCase; //// MemberListType listType; //// //// RuntimeType.FilterHelper( bindingAttr, ref name, allowPrefixLookup, out prefixLookup, out ignoreCase, out listType ); //// //// List candidates = new List(); //// CerArrayList cache = Cache.GetConstructorList( listType, name ); //// //// bindingAttr ^= BindingFlags.DeclaredOnly; //// //// for(int i = 0; i < cache.Count; i++) //// { //// RuntimeConstructorInfo constructorInfo = cache[i]; //// //// if((bindingAttr & constructorInfo.BindingFlags) == constructorInfo.BindingFlags && //// FilterApplyMethodBaseInfo( constructorInfo, bindingAttr, callConv, types ) && //// (!prefixLookup || RuntimeType.FilterApplyPrefixLookup( constructorInfo, name, ignoreCase ))) //// { //// candidates.Add( constructorInfo ); //// } //// } //// //// return candidates.ToArray(); //// } //// //// //// private PropertyInfo[] GetPropertyCandidates( String name , //// BindingFlags bindingAttr , //// Type[] types , //// bool allowPrefixLookup ) //// { //// bool prefixLookup; //// bool ignoreCase; //// MemberListType listType; //// //// RuntimeType.FilterHelper( bindingAttr, ref name, allowPrefixLookup, out prefixLookup, out ignoreCase, out listType ); //// //// List candidates = new List(); //// CerArrayList cache = Cache.GetPropertyList( listType, name ); //// //// bindingAttr ^= BindingFlags.DeclaredOnly; //// //// for(int i = 0; i < cache.Count; i++) //// { //// RuntimePropertyInfo propertyInfo = cache[i]; //// //// if((bindingAttr & propertyInfo.BindingFlags) == propertyInfo.BindingFlags && //// (!prefixLookup || RuntimeType.FilterApplyPrefixLookup( propertyInfo, name, ignoreCase )) && //// (types == null || (propertyInfo.GetIndexParameters().Length == types.Length))) //// { //// candidates.Add( propertyInfo ); //// } //// } //// //// return candidates.ToArray(); //// } //// //// //// private EventInfo[] GetEventCandidates( String name , //// BindingFlags bindingAttr , //// bool allowPrefixLookup ) //// { //// bool prefixLookup; //// bool ignoreCase; //// MemberListType listType; //// //// RuntimeType.FilterHelper( bindingAttr, ref name, allowPrefixLookup, out prefixLookup, out ignoreCase, out listType ); //// //// List candidates = new List(); //// CerArrayList cache = Cache.GetEventList( listType, name ); //// //// bindingAttr ^= BindingFlags.DeclaredOnly; //// //// for(int i = 0; i < cache.Count; i++) //// { //// RuntimeEventInfo eventInfo = cache[i]; //// //// if((bindingAttr & eventInfo.BindingFlags) == eventInfo.BindingFlags && //// (!prefixLookup || RuntimeType.FilterApplyPrefixLookup( eventInfo, name, ignoreCase ))) //// { //// candidates.Add( eventInfo ); //// } //// } //// //// return candidates.ToArray(); //// } //// //// private FieldInfo[] GetFieldCandidates( String name , //// BindingFlags bindingAttr , //// bool allowPrefixLookup ) //// { //// bool prefixLookup; //// bool ignoreCase; //// MemberListType listType; //// //// RuntimeType.FilterHelper( bindingAttr, ref name, allowPrefixLookup, out prefixLookup, out ignoreCase, out listType ); //// //// List candidates = new List(); //// CerArrayList cache = Cache.GetFieldList( listType, name ); //// //// bindingAttr ^= BindingFlags.DeclaredOnly; //// //// for(int i = 0; i < cache.Count; i++) //// { //// RuntimeFieldInfo fieldInfo = cache[i]; //// //// if((bindingAttr & fieldInfo.BindingFlags) == fieldInfo.BindingFlags && //// (!prefixLookup || FilterApplyPrefixLookup( fieldInfo, name, ignoreCase ))) //// { //// candidates.Add( fieldInfo ); //// } //// } //// //// return candidates.ToArray(); //// } //// //// private Type[] GetNestedTypeCandidates( String fullname , //// BindingFlags bindingAttr , //// bool allowPrefixLookup ) //// { //// string name; //// string ns; //// //// SplitName( fullname, out name, out ns ); //// //// bool prefixLookup; //// bool ignoreCase; //// MemberListType listType; //// //// bindingAttr &= ~BindingFlags.Static; //// //// RuntimeType.FilterHelper( bindingAttr, ref name, allowPrefixLookup, out prefixLookup, out ignoreCase, out listType ); //// //// List candidates = new List(); //// CerArrayList cache = Cache.GetNestedTypeList( listType, name ); //// //// for(int i = 0; i < cache.Count; i++) //// { //// RuntimeType nestedClass = cache[i]; //// //// if(RuntimeType.FilterApplyType( nestedClass, bindingAttr, name, prefixLookup, ns )) //// { //// candidates.Add( nestedClass ); //// } //// } //// //// return candidates.ToArray(); //// } #endregion #region Get All XXXInfos [MethodImpl( MethodImplOptions.InternalCall )] public override extern MethodInfo[] GetMethods( BindingFlags bindingAttr ); //// { //// return GetMethodCandidates( null, bindingAttr, CallingConventions.Any, null, false ); //// } //// public override ConstructorInfo[] GetConstructors( BindingFlags bindingAttr ) //// { //// return GetConstructorCandidates( null, bindingAttr, CallingConventions.Any, null, false ); //// } [MethodImpl( MethodImplOptions.InternalCall )] public override extern PropertyInfo[] GetProperties( BindingFlags bindingAttr ); //// { //// return GetPropertyCandidates( null, bindingAttr, null, false ); //// } //// public override EventInfo[] GetEvents( BindingFlags bindingAttr ) //// { //// return GetEventCandidates( null, bindingAttr, false ); //// } [MethodImpl( MethodImplOptions.InternalCall )] public override extern FieldInfo[] GetFields( BindingFlags bindingAttr ); //// { //// return GetFieldCandidates( null, bindingAttr, false ); //// } //// public override Type[] GetInterfaces() //// { //// CerArrayList candidates = this.Cache.GetInterfaceList( MemberListType.All, null ); //// //// Type[] interfaces = new Type[candidates.Count]; //// for(int i = 0; i < candidates.Count; i++) //// { //// FastArrayHandle.SetValueAt( interfaces, i, candidates[i] ); //// } //// //// return interfaces; //// } //// //// public override Type[] GetNestedTypes( BindingFlags bindingAttr ) //// { //// return GetNestedTypeCandidates( null, bindingAttr, false ); //// } [MethodImpl( MethodImplOptions.InternalCall )] public override extern MemberInfo[] GetMembers( BindingFlags bindingAttr ); //// { //// MethodInfo[] methods = GetMethodCandidates ( null, bindingAttr, CallingConventions.Any, null, false ); //// ConstructorInfo[] constructors = GetConstructorCandidates( null, bindingAttr, CallingConventions.Any, null, false ); //// PropertyInfo[] properties = GetPropertyCandidates ( null, bindingAttr, null, false ); //// EventInfo[] events = GetEventCandidates ( null, bindingAttr, false ); //// FieldInfo[] fields = GetFieldCandidates ( null, bindingAttr, false ); //// Type[] nestedTypes = GetNestedTypeCandidates ( null, bindingAttr, false ); //// //// // Interfaces are excluded from the result of GetMembers //// //// MemberInfo[] members = new MemberInfo[ methods .Length + //// constructors.Length + //// properties .Length + //// events .Length + //// fields .Length + //// nestedTypes .Length ]; //// //// int i = 0; //// //// Array.Copy( methods , 0, members, i, methods .Length ); i += methods .Length; //// Array.Copy( constructors, 0, members, i, constructors.Length ); i += constructors.Length; //// Array.Copy( properties , 0, members, i, properties .Length ); i += properties .Length; //// Array.Copy( events , 0, members, i, events .Length ); i += events .Length; //// Array.Copy( fields , 0, members, i, fields .Length ); i += fields .Length; //// Array.Copy( nestedTypes , 0, members, i, nestedTypes .Length ); i += nestedTypes .Length; //// //// ASSERT.POSTCONDITION( i == members.Length ); //// return members; //// } //// public override InterfaceMapping GetInterfaceMap( Type ifaceType ) //// { //// if(IsGenericParameter) //// { //// throw new InvalidOperationException( Environment.GetResourceString( "Arg_GenericParameter" ) ); //// } //// //// if(ifaceType == null) //// { //// throw new ArgumentNullException( "ifaceType" ); //// } //// //// if(!(ifaceType is RuntimeType)) //// { //// throw new ArgumentException( Environment.GetResourceString( "Argument_MustBeRuntimeType" ), "ifaceType" ); //// } //// //// RuntimeType ifaceRtType = ifaceType as RuntimeType; //// RuntimeTypeHandle ifaceRtTypeHandle = ifaceRtType.GetTypeHandleInternal(); //// //// int firstIfaceSlot = GetTypeHandleInternal().GetFirstSlotForInterface( ifaceRtType.GetTypeHandleInternal() ); //// ASSERT.CONSISTENCY_CHECK( ifaceType.IsInterface ); // GetFirstSlotForInterface enforces this invariant //// ASSERT.CONSISTENCY_CHECK( !IsInterface ); // GetFirstSlotForInterface enforces this invariant //// //// int ifaceSlotCount = ifaceRtTypeHandle.GetInterfaceMethodSlots(); //// int ifaceStaticMethodCount = 0; //// //// // @Optimization - Most interface have the same number of static members. //// //// // Filter out static methods //// for(int i = 0; i < ifaceSlotCount; i++) //// { //// if((ifaceRtTypeHandle.GetMethodAt( i ).GetAttributes() & MethodAttributes.Static) != 0) //// { //// ifaceStaticMethodCount++; //// } //// } //// //// int ifaceInstanceMethodCount = ifaceSlotCount - ifaceStaticMethodCount; //// //// InterfaceMapping im; //// im.InterfaceType = ifaceType; //// im.TargetType = this; //// im.InterfaceMethods = new MethodInfo[ifaceInstanceMethodCount]; //// im.TargetMethods = new MethodInfo[ifaceInstanceMethodCount]; //// //// for(int i = 0; i < ifaceSlotCount; i++) //// { //// RuntimeMethodHandle ifaceRtMethodHandle = ifaceRtTypeHandle.GetMethodAt( i ); //// //// if((ifaceRtTypeHandle.GetMethodAt( i ).GetAttributes() & MethodAttributes.Static) != 0) //// { //// continue; //// } //// //// bool mayNeedInstantiatingStub = ifaceRtTypeHandle.HasInstantiation() && !ifaceRtTypeHandle.IsGenericTypeDefinition(); //// //// // if it is an instantiated type get the InstantiatedMethodDesc if needed //// if(mayNeedInstantiatingStub) //// { //// ifaceRtMethodHandle = ifaceRtMethodHandle.GetInstantiatingStubIfNeeded( ifaceRtTypeHandle ); //// } //// //// MethodBase ifaceMethodBase = RuntimeType.GetMethodBase( ifaceRtTypeHandle, ifaceRtMethodHandle ); //// ASSERT.CONSISTENCY_CHECK( ifaceMethodBase is RuntimeMethodInfo ); //// im.InterfaceMethods[i] = (MethodInfo)ifaceMethodBase; //// //// // If the slot is -1, then virtual stub dispatch is active. //// // Should remove old "firstIfaceSlot + i" code when old behaviour disappears. //// int slot; //// if(firstIfaceSlot == -1) //// { //// slot = GetTypeHandleInternal().GetInterfaceMethodImplementationSlot( ifaceRtTypeHandle, ifaceRtMethodHandle ); //// } //// else //// { //// slot = firstIfaceSlot + i; //// } //// //// if(slot == -1) continue; //// //// //// RuntimeTypeHandle classRtTypeHandle = GetTypeHandleInternal(); //// RuntimeMethodHandle classRtMethodHandle = classRtTypeHandle.GetMethodAt( slot ); //// //// mayNeedInstantiatingStub = classRtTypeHandle.HasInstantiation() && !classRtTypeHandle.IsGenericTypeDefinition(); //// //// if(mayNeedInstantiatingStub) //// { //// classRtMethodHandle = classRtMethodHandle.GetInstantiatingStubIfNeeded( classRtTypeHandle ); //// } //// //// MethodBase rtTypeMethodBase = RuntimeType.GetMethodBase( classRtTypeHandle, classRtMethodHandle ); //// // a class may not implement all the methods of an interface (abstract class) so null is a valid value //// ASSERT.CONSISTENCY_CHECK( rtTypeMethodBase == null || rtTypeMethodBase is RuntimeMethodInfo ); //// im.TargetMethods[i] = (MethodInfo)rtTypeMethodBase; //// } //// //// return im; //// } #endregion #region Find XXXInfo [MethodImpl( MethodImplOptions.InternalCall )] protected override extern MethodInfo GetMethodImpl( String name , BindingFlags bindingAttr , Binder binder , CallingConventions callConv , Type[] types , ParameterModifier[] modifiers ); //// { //// MethodInfo[] candidates = GetMethodCandidates( name, bindingAttr, callConv, types, false ); //// if(candidates.Length == 0) //// { //// return null; //// } //// //// if(types == null || types.Length == 0) //// { //// if(candidates.Length == 1) //// { //// return candidates[0]; //// } //// else if(types == null) //// { //// for(int j = 1; j < candidates.Length; j++) //// { //// MethodInfo methodInfo = candidates[j]; //// if(!System.DefaultBinder.CompareMethodSigAndName( methodInfo, candidates[0] )) //// { //// throw new AmbiguousMatchException( Environment.GetResourceString( "Arg_AmbiguousMatchException" ) ); //// } //// } //// //// // All the methods have the exact same name and sig so return the most derived one. //// return System.DefaultBinder.FindMostDerivedNewSlotMeth( candidates, candidates.Length ) as MethodInfo; //// } //// } //// //// if(binder == null) //// { //// binder = DefaultBinder; //// } //// //// return binder.SelectMethod( bindingAttr, candidates, types, modifiers ) as MethodInfo; //// } //// protected override ConstructorInfo GetConstructorImpl( BindingFlags bindingAttr , //// Binder binder , //// CallingConventions callConvention, //// Type[] types , //// ParameterModifier[] modifiers ) //// { //// ConstructorInfo[] candidates = GetConstructorCandidates( null, bindingAttr, CallingConventions.Any, types, false ); //// //// if(binder == null) //// { //// binder = DefaultBinder; //// } //// //// if(candidates.Length == 0) //// { //// return null; //// } //// //// if(types.Length == 0 && candidates.Length == 1) //// { //// ParameterInfo[] parameters = (candidates[0]).GetParametersNoCopy(); //// if(parameters == null || parameters.Length == 0) //// { //// return candidates[0]; //// } //// } //// //// if((bindingAttr & BindingFlags.ExactBinding) != 0) //// { //// return System.DefaultBinder.ExactBinding( candidates, types, modifiers ) as ConstructorInfo; //// } //// //// return binder.SelectMethod( bindingAttr, candidates, types, modifiers ) as ConstructorInfo; //// } [MethodImpl( MethodImplOptions.InternalCall )] protected override extern PropertyInfo GetPropertyImpl( String name , BindingFlags bindingAttr , Binder binder , Type returnType , Type[] types , ParameterModifier[] modifiers ); //// { //// if(name == null) throw new ArgumentNullException(); //// //// PropertyInfo[] candidates = GetPropertyCandidates( name, bindingAttr, types, false ); //// //// if(binder == null) //// { //// binder = DefaultBinder; //// } //// //// if(candidates.Length == 0) //// { //// return null; //// } //// //// if(types == null || types.Length == 0) //// { //// // no arguments //// if(candidates.Length == 1) //// { //// if(returnType != null && returnType != candidates[0].PropertyType) //// { //// return null; //// } //// //// return candidates[0]; //// } //// else //// { //// if(returnType == null) //// { //// // if we are here we have no args or property type to select over and we have more than one property with that name //// throw new AmbiguousMatchException( Environment.GetResourceString( "Arg_AmbiguousMatchException" ) ); //// } //// } //// } //// //// if((bindingAttr & BindingFlags.ExactBinding) != 0) //// { //// return System.DefaultBinder.ExactPropertyBinding( candidates, returnType, types, modifiers ); //// } //// //// return binder.SelectProperty( bindingAttr, candidates, returnType, types, modifiers ); //// } //// public override EventInfo GetEvent( String name, BindingFlags bindingAttr ) //// { //// if(name == null) throw new ArgumentNullException(); //// //// bool ignoreCase; //// MemberListType listType; //// //// RuntimeType.FilterHelper( bindingAttr, ref name, out ignoreCase, out listType ); //// //// CerArrayList cache = Cache.GetEventList( listType, name ); //// EventInfo match = null; //// //// bindingAttr ^= BindingFlags.DeclaredOnly; //// //// for(int i = 0; i < cache.Count; i++) //// { //// RuntimeEventInfo eventInfo = cache[i]; //// //// if((bindingAttr & eventInfo.BindingFlags) == eventInfo.BindingFlags) //// { //// if(match != null) //// { //// throw new AmbiguousMatchException( Environment.GetResourceString( "Arg_AmbiguousMatchException" ) ); //// } //// //// match = eventInfo; //// } //// } //// //// return match; //// } [MethodImpl( MethodImplOptions.InternalCall )] public override extern FieldInfo GetField( String name, BindingFlags bindingAttr ); //// { //// if(name == null) throw new ArgumentNullException(); //// //// bool ignoreCase; //// MemberListType listType; //// //// RuntimeType.FilterHelper( bindingAttr, ref name, out ignoreCase, out listType ); //// //// CerArrayList cache = Cache.GetFieldList( listType, name ); //// FieldInfo match = null; //// //// bindingAttr ^= BindingFlags.DeclaredOnly; //// //// bool multipleStaticFieldMatches = false; //// //// for(int i = 0; i < cache.Count; i++) //// { //// RuntimeFieldInfo fieldInfo = cache[i]; //// //// if((bindingAttr & fieldInfo.BindingFlags) == fieldInfo.BindingFlags) //// { //// if(match != null) //// { //// if(fieldInfo.DeclaringType == match.DeclaringType) //// { //// throw new AmbiguousMatchException( Environment.GetResourceString( "Arg_AmbiguousMatchException" ) ); //// } //// //// if((match.DeclaringType.IsInterface == true) && (fieldInfo.DeclaringType.IsInterface == true)) //// { //// multipleStaticFieldMatches = true; //// } //// } //// //// if(match == null || fieldInfo.DeclaringType.IsSubclassOf( match.DeclaringType ) || match.DeclaringType.IsInterface) //// { //// match = fieldInfo; //// } //// } //// } //// //// if(multipleStaticFieldMatches && match.DeclaringType.IsInterface) //// { //// throw new AmbiguousMatchException( Environment.GetResourceString( "Arg_AmbiguousMatchException" ) ); //// } //// //// return match; //// } //// public override Type GetInterface( String fullname, bool ignoreCase ) //// { //// if(fullname == null) throw new ArgumentNullException(); //// //// BindingFlags bindingAttr = BindingFlags.Public | BindingFlags.NonPublic; //// //// bindingAttr &= ~BindingFlags.Static; //// //// if(ignoreCase) //// { //// bindingAttr |= BindingFlags.IgnoreCase; //// } //// //// string name; //// string ns; //// //// SplitName( fullname, out name, out ns ); //// //// MemberListType listType; //// //// RuntimeType.FilterHelper( bindingAttr, ref name, out ignoreCase, out listType ); //// //// CerArrayList cache = Cache.GetInterfaceList( listType, name ); //// RuntimeType match = null; //// //// for(int i = 0; i < cache.Count; i++) //// { //// RuntimeType iface = cache[i]; //// //// if(RuntimeType.FilterApplyType( iface, bindingAttr, name, false, ns )) //// { //// if(match != null) //// { //// throw new AmbiguousMatchException( Environment.GetResourceString( "Arg_AmbiguousMatchException" ) ); //// } //// //// match = iface; //// } //// } //// //// return match; //// } //// //// public override Type GetNestedType( String fullname, BindingFlags bindingAttr ) //// { //// if(fullname == null) throw new ArgumentNullException(); //// //// bindingAttr &= ~BindingFlags.Static; //// //// string name; //// string ns; //// //// SplitName( fullname, out name, out ns ); //// //// bool ignoreCase; //// MemberListType listType; //// //// RuntimeType.FilterHelper( bindingAttr, ref name, out ignoreCase, out listType ); //// //// CerArrayList cache = Cache.GetNestedTypeList( listType, name ); //// RuntimeType match = null; //// //// for(int i = 0; i < cache.Count; i++) //// { //// RuntimeType nestedType = cache[i]; //// //// if(RuntimeType.FilterApplyType( nestedType, bindingAttr, name, false, ns )) //// { //// if(match != null) //// { //// throw new AmbiguousMatchException( Environment.GetResourceString( "Arg_AmbiguousMatchException" ) ); //// } //// //// match = nestedType; //// } //// } //// //// return match; //// } //// //// public override MemberInfo[] GetMember( String name, MemberTypes type, BindingFlags bindingAttr ) //// { //// if(name == null) throw new ArgumentNullException(); //// //// MethodInfo[] methods = new MethodInfo [0]; //// ConstructorInfo[] constructors = new ConstructorInfo[0]; //// PropertyInfo[] properties = new PropertyInfo [0]; //// EventInfo[] events = new EventInfo [0]; //// FieldInfo[] fields = new FieldInfo [0]; //// Type[] nestedTypes = new Type [0]; //// //// // Methods //// if((type & MemberTypes.Method) != 0) //// { //// methods = GetMethodCandidates( name, bindingAttr, CallingConventions.Any, null, true ); //// } //// //// // Constructors //// if((type & MemberTypes.Constructor) != 0) //// { //// constructors = GetConstructorCandidates( name, bindingAttr, CallingConventions.Any, null, true ); //// } //// //// // Properties //// if((type & MemberTypes.Property) != 0) //// { //// properties = GetPropertyCandidates( name, bindingAttr, null, true ); //// } //// //// // Events //// if((type & MemberTypes.Event) != 0) //// { //// events = GetEventCandidates( name, bindingAttr, true ); //// } //// //// // Fields //// if((type & MemberTypes.Field) != 0) //// { //// fields = GetFieldCandidates( name, bindingAttr, true ); //// } //// //// // NestedTypes //// if((type & (MemberTypes.NestedType | MemberTypes.TypeInfo)) != 0) //// { //// nestedTypes = GetNestedTypeCandidates( name, bindingAttr, true ); //// } //// //// switch(type) //// { //// case MemberTypes.Method | MemberTypes.Constructor: //// MethodBase[] compressBaseses = new MethodBase[methods.Length + constructors.Length]; //// //// Array.Copy( methods , compressBaseses, methods.Length ); //// Array.Copy( constructors, 0, compressBaseses, methods.Length, constructors.Length ); //// return compressBaseses; //// //// case MemberTypes.Method: //// return methods; //// //// case MemberTypes.Constructor: //// return constructors; //// //// case MemberTypes.Field: //// return fields; //// //// case MemberTypes.Property: //// return properties; //// //// case MemberTypes.Event: //// return events; //// //// case MemberTypes.NestedType: //// return nestedTypes; //// //// case MemberTypes.TypeInfo: //// return nestedTypes; //// } //// //// MemberInfo[] compressMembers = new MemberInfo[ methods .Length + //// constructors.Length + //// properties .Length + //// events .Length + //// fields .Length + //// nestedTypes .Length ]; //// //// int i = 0; //// if(methods .Length > 0) Array.Copy( methods , 0, compressMembers, i, methods .Length ); i += methods .Length; //// if(constructors.Length > 0) Array.Copy( constructors, 0, compressMembers, i, constructors.Length ); i += constructors.Length; //// if(properties .Length > 0) Array.Copy( properties , 0, compressMembers, i, properties .Length ); i += properties .Length; //// if(events .Length > 0) Array.Copy( events , 0, compressMembers, i, events .Length ); i += events .Length; //// if(fields .Length > 0) Array.Copy( fields , 0, compressMembers, i, fields .Length ); i += fields .Length; //// if(nestedTypes .Length > 0) Array.Copy( nestedTypes , 0, compressMembers, i, nestedTypes .Length ); i += nestedTypes .Length; //// //// ASSERT.POSTCONDITION( i == compressMembers.Length ); //// return compressMembers; //// } #endregion #region Identity //// public override Module Module //// { //// get //// { //// return GetTypeHandleInternal().GetModuleHandle().GetModule(); //// } //// } public override extern Assembly Assembly { [MethodImpl( MethodImplOptions.InternalCall )] get; //// { //// return GetTypeHandleInternal().GetAssemblyHandle().GetAssembly(); //// } } public override RuntimeTypeHandle TypeHandle { get { return m_handle; } } //// [ReliabilityContract( Consistency.WillNotCorruptState, Cer.Success )] //// internal override RuntimeTypeHandle GetTypeHandleInternal() //// { //// return m_handle; //// } //// internal override TypeCode GetTypeCodeInternal() //// { //// TypeCode typeCode = Cache.TypeCode; //// //// if(typeCode != TypeCode.Empty) //// { //// return typeCode; //// } //// //// CorElementType corElementType = GetTypeHandleInternal().GetCorElementType(); //// switch(corElementType) //// { //// case CorElementType.Boolean: //// typeCode = TypeCode.Boolean; break; //// //// case CorElementType.Char: //// typeCode = TypeCode.Char; break; //// //// case CorElementType.I1: //// typeCode = TypeCode.SByte; break; //// //// case CorElementType.U1: //// typeCode = TypeCode.Byte; break; //// //// case CorElementType.I2: //// typeCode = TypeCode.Int16; break; //// //// case CorElementType.U2: //// typeCode = TypeCode.UInt16; break; //// //// case CorElementType.I4: //// typeCode = TypeCode.Int32; break; //// //// case CorElementType.U4: //// typeCode = TypeCode.UInt32; break; //// //// case CorElementType.I8: //// typeCode = TypeCode.Int64; break; //// //// case CorElementType.U8: //// typeCode = TypeCode.UInt64; break; //// //// case CorElementType.R4: //// typeCode = TypeCode.Single; break; //// //// case CorElementType.R8: //// typeCode = TypeCode.Double; break; //// //// case CorElementType.String: //// typeCode = TypeCode.String; break; //// //// case CorElementType.ValueType: //// if(this == Convert.ConvertTypes[(int)TypeCode.Decimal]) //// { //// typeCode = TypeCode.Decimal; //// } //// else if(this == Convert.ConvertTypes[(int)TypeCode.DateTime]) //// { //// typeCode = TypeCode.DateTime; //// } //// else if(this.IsEnum) //// { //// typeCode = Type.GetTypeCode( Enum.GetUnderlyingType( this ) ); //// } //// else //// { //// typeCode = TypeCode.Object; //// } //// break; //// //// default: //// if(this == Convert.ConvertTypes[(int)TypeCode.DBNull]) //// { //// typeCode = TypeCode.DBNull; //// } //// else if(this == Convert.ConvertTypes[(int)TypeCode.String]) //// { //// typeCode = TypeCode.String; //// } //// else //// { //// typeCode = TypeCode.Object; //// } //// break; //// } //// //// Cache.TypeCode = typeCode; //// //// return typeCode; //// } //// //// public override MethodBase DeclaringMethod //// { //// get //// { //// if(!IsGenericParameter) //// { //// throw new InvalidOperationException( Environment.GetResourceString( "Arg_NotGenericParameter" ) ); //// } //// //// RuntimeMethodHandle declaringMethod = GetTypeHandleInternal().GetDeclaringMethod(); //// //// if(declaringMethod.IsNullHandle()) //// { //// return null; //// } //// //// return GetMethodBase( declaringMethod.GetDeclaringType(), declaringMethod ); //// } //// } #endregion #region Hierarchy //// public override bool IsInstanceOfType( Object o ) //// { //// return GetTypeHandleInternal().IsInstanceOfType( o ); //// } public override bool IsSubclassOf( Type type ) { if(type == null) { #if EXCEPTION_STRINGS throw new ArgumentNullException( "type" ); #else throw new ArgumentNullException(); #endif } ASSERT.PRECONDITION( type is RuntimeType ); Type baseType = BaseType; while(baseType != null) { if(baseType == type) { return true; } baseType = baseType.BaseType; } // pretty much everything is a subclass of object, even interfaces // notice that interfaces are really odd because they do not have a BaseType // yet IsSubclassOf(typeof(object)) returns true if(type == typeof( Object ) && type != this) { return true; } return false; } public override extern Type BaseType { [MethodImpl( MethodImplOptions.InternalCall )] get; //// { //// if(IsInterface) //// { //// return null; //// } //// //// if(m_handle.IsGenericVariable()) //// { //// Type[] constraints = GetGenericParameterConstraints(); //// //// Type baseType = typeof( object ); //// //// for(int i = 0; i < constraints.Length; i++) //// { //// Type constraint = constraints[i]; //// //// if(constraint.IsInterface) //// { //// continue; //// } //// //// if(constraint.IsGenericParameter) //// { //// GenericParameterAttributes special; //// special = constraint.GenericParameterAttributes & GenericParameterAttributes.SpecialConstraintMask; //// //// if((special & GenericParameterAttributes.ReferenceTypeConstraint ) == 0 && //// (special & GenericParameterAttributes.NotNullableValueTypeConstraint) == 0 ) //// { //// continue; //// } //// } //// //// baseType = constraint; //// } //// //// if(baseType == typeof( object )) //// { //// GenericParameterAttributes special; //// //// special = GenericParameterAttributes & GenericParameterAttributes.SpecialConstraintMask; //// //// if((special & GenericParameterAttributes.NotNullableValueTypeConstraint) != 0) //// { //// baseType = typeof( ValueType ); //// } //// } //// //// return baseType; //// } //// //// return m_handle.GetBaseTypeHandle().GetRuntimeType(); //// } } public override Type UnderlyingSystemType { get { // Origional Comment: Return the underlying Type that represents the IReflect Object. // For expando object, this is the (Object) IReflectInstance.GetType(). For Type object it is this. return this; } } #endregion #region Name public override extern String FullName { [MethodImpl( MethodImplOptions.InternalCall )] get; //// { //// return Cache.GetFullName(); //// } } public override extern String AssemblyQualifiedName { [MethodImpl( MethodImplOptions.InternalCall )] get; //// { //// if(!IsGenericTypeDefinition && ContainsGenericParameters) //// { //// return null; //// } //// //// return Assembly.CreateQualifiedName( this.Assembly.FullName, this.FullName ); //// } } public override extern String Namespace { [MethodImpl( MethodImplOptions.InternalCall )] get; //// { //// string ns = Cache.GetNameSpace(); //// //// if(ns == null || ns.Length == 0) //// { //// return null; //// } //// //// return ns; //// } } #endregion #region Attributes //// protected override TypeAttributes GetAttributeFlagsImpl() //// { //// return m_handle.GetAttributes(); //// } //// //// public override Guid GUID //// { //// get //// { //// Guid result = new Guid(); //// //// GetGUID( ref result ); //// //// return result; //// } //// } //// //// [ResourceExposure( ResourceScope.None )] //// [MethodImpl( MethodImplOptions.InternalCall )] //// private extern void GetGUID( ref Guid result ); //// //// protected override bool IsContextfulImpl() //// { //// return GetTypeHandleInternal().IsContextful(); //// } //// //// /* //// protected override bool IsMarshalByRefImpl() //// { //// return GetTypeHandleInternal().IsMarshalByRef(); //// } //// */ //// //// protected override bool IsByRefImpl() //// { //// CorElementType corElemType = GetTypeHandleInternal().GetCorElementType(); //// //// return (corElemType == CorElementType.ByRef); //// } //// //// protected override bool IsPrimitiveImpl() //// { //// CorElementType corElemType = GetTypeHandleInternal().GetCorElementType(); //// //// return (corElemType >= CorElementType.Boolean && corElemType <= CorElementType.R8) || //// corElemType == CorElementType.I || //// corElemType == CorElementType.U; //// } //// //// protected override bool IsPointerImpl() //// { //// CorElementType corElemType = GetTypeHandleInternal().GetCorElementType(); //// //// return (corElemType == CorElementType.Ptr); //// } //// //// protected override bool IsCOMObjectImpl() //// { //// return GetTypeHandleInternal().IsComObject( false ); //// } //// //// internal override bool HasProxyAttributeImpl() //// { //// return GetTypeHandleInternal().HasProxyAttribute(); //// } //// //// protected override bool HasElementTypeImpl() //// { //// return (IsArray || IsPointer || IsByRef); //// } //// //// public override GenericParameterAttributes GenericParameterAttributes //// { //// get //// { //// if(!IsGenericParameter) //// { //// throw new InvalidOperationException( Environment.GetResourceString( "Arg_NotGenericParameter" ) ); //// } //// //// GenericParameterAttributes attributes; //// //// GetTypeHandleInternal().GetModuleHandle().GetMetadataImport().GetGenericParamProps( MetadataToken, out attributes ); //// //// return attributes; //// } //// } #endregion #region Arrays //// internal override bool IsSzArray //// { //// get //// { //// CorElementType corElemType = GetTypeHandleInternal().GetCorElementType(); //// //// return (corElemType == CorElementType.SzArray); //// } //// } //// //// protected override bool IsArrayImpl() //// { //// CorElementType corElemType = GetTypeHandleInternal().GetCorElementType(); //// //// return (corElemType == CorElementType.Array || corElemType == CorElementType.SzArray); //// } //// //// public override int GetArrayRank() //// { //// if(!IsArrayImpl()) //// { //// throw new ArgumentException( Environment.GetResourceString( "Argument_HasToBeArrayClass" ) ); //// } //// //// return GetTypeHandleInternal().GetArrayRank(); //// } [MethodImpl( MethodImplOptions.InternalCall )] public override extern Type GetElementType(); //// { //// return GetTypeHandleInternal().GetElementType().GetRuntimeType(); //// } #endregion #region Generics //// public override Type[] GetGenericArguments() //// { //// Type[] rtypes = null; //// RuntimeTypeHandle[] types = GetRootElementType().GetTypeHandleInternal().GetInstantiation(); //// //// if(types != null) //// { //// rtypes = new Type[types.Length]; //// //// for(int i = 0; i < types.Length; i++) //// { //// rtypes[i] = types[i].GetRuntimeType(); //// } //// } //// else //// { //// rtypes = new Type[0]; //// } //// //// return rtypes; //// } //// //// public override Type MakeGenericType( Type[] instantiation ) //// { //// if(instantiation == null) //// { //// throw new ArgumentNullException( "instantiation" ); //// } //// //// Type[] instantiationCopy = new Type[instantiation.Length]; //// //// for(int i = 0; i < instantiation.Length; i++) //// { //// instantiationCopy[i] = instantiation[i]; //// } //// //// instantiation = instantiationCopy; //// //// if(!IsGenericTypeDefinition) //// { //// throw new InvalidOperationException( String.Format( CultureInfo.CurrentCulture, Environment.GetResourceString( "Arg_NotGenericTypeDefinition" ), this ) ); //// } //// //// for(int i = 0; i < instantiation.Length; i++) //// { //// if(instantiation[i] == null) //// { //// throw new ArgumentNullException(); //// } //// //// if(!(instantiation[i] is RuntimeType)) //// { //// return new TypeBuilderInstantiation( this, instantiation ); //// } //// } //// //// Type[] genericParameters = GetGenericArguments(); //// //// SanityCheckGenericArguments( instantiation, genericParameters ); //// //// RuntimeTypeHandle[] typeHandles = new RuntimeTypeHandle[instantiation.Length]; //// //// for(int i = 0; i < instantiation.Length; i++) //// { //// typeHandles[i] = instantiation[i].GetTypeHandleInternal(); //// } //// //// Type ret = null; //// try //// { //// ret = m_handle.Instantiate( typeHandles ).GetRuntimeType(); //// } //// catch(TypeLoadException e) //// { //// ValidateGenericArguments( this, instantiation, e ); //// throw e; //// } //// //// return ret; //// } //// //// public override bool IsGenericTypeDefinition //// { //// get //// { //// return m_handle.IsGenericTypeDefinition(); //// } //// } //// //// public override bool IsGenericParameter //// { //// get //// { //// return m_handle.IsGenericVariable(); //// } //// } //// //// public override int GenericParameterPosition //// { //// get //// { //// if(!IsGenericParameter) //// { //// throw new InvalidOperationException( Environment.GetResourceString( "Arg_NotGenericParameter" ) ); //// } //// //// return m_handle.GetGenericVariableIndex(); //// } //// } //// //// public override Type GetGenericTypeDefinition() //// { //// if(!IsGenericType) //// { //// throw new InvalidOperationException(); //// } //// //// return m_handle.GetGenericTypeDefinition().GetRuntimeType(); //// } //// //// public override bool IsGenericType //// { //// get //// { //// return HasElementType ? false : GetTypeHandleInternal().HasInstantiation(); //// } //// } //// //// public override bool ContainsGenericParameters //// { //// get //// { //// return GetRootElementType().GetTypeHandleInternal().ContainsGenericVariables(); //// } //// } //// //// public override Type[] GetGenericParameterConstraints() //// { //// if(!IsGenericParameter) //// { //// throw new InvalidOperationException( Environment.GetResourceString( "Arg_NotGenericParameter" ) ); //// } //// //// RuntimeTypeHandle[] constraintHandles = m_handle.GetConstraints(); //// Type[] constraints = new Type[constraintHandles.Length]; //// //// for(int i = 0; i < constraints.Length; i++) //// { //// constraints[i] = constraintHandles[i].GetRuntimeType(); //// } //// //// return constraints; //// } #endregion #region Misc //// public override Type MakePointerType() //// { //// return m_handle.MakePointer().GetRuntimeType(); //// } //// //// public override Type MakeByRefType() //// { //// return m_handle.MakeByRef().GetRuntimeType(); //// } //// //// public override Type MakeArrayType() //// { //// return m_handle.MakeSZArray().GetRuntimeType(); //// } //// //// public override Type MakeArrayType( int rank ) //// { //// if(rank <= 0) //// { //// throw new IndexOutOfRangeException(); //// } //// //// return m_handle.MakeArray( rank ).GetRuntimeType(); //// } //// public override StructLayoutAttribute StructLayoutAttribute //// { //// get //// { //// return (StructLayoutAttribute)StructLayoutAttribute.GetCustomAttribute( this ); //// } //// } #endregion #region Invoke Member //// private const BindingFlags MemberBindingMask = (BindingFlags)0x000000FF; //// private const BindingFlags InvocationMask = (BindingFlags)0x0000FF00; //// private const BindingFlags BinderNonCreateInstance = BindingFlags.InvokeMethod | BinderGetSetField | BinderGetSetProperty; //// private const BindingFlags BinderGetSetProperty = BindingFlags.GetProperty | BindingFlags.SetProperty; //// private const BindingFlags BinderSetInvokeProperty = BindingFlags.InvokeMethod | BindingFlags.SetProperty; //// private const BindingFlags BinderGetSetField = BindingFlags.GetField | BindingFlags.SetField; //// private const BindingFlags BinderSetInvokeField = BindingFlags.SetField | BindingFlags.InvokeMethod; //// private const BindingFlags BinderNonFieldGetSet = (BindingFlags)0x00FFF300; //// private const BindingFlags ClassicBindingMask = BindingFlags.InvokeMethod | BindingFlags.GetProperty | BindingFlags.SetProperty | //// BindingFlags.PutDispProperty | BindingFlags.PutRefDispProperty; //// //// private static Type s_typedRef = typeof( TypedReference ); //// //// [ResourceExposure( ResourceScope.None )] //// [MethodImpl( MethodImplOptions.InternalCall )] //// static private extern bool CanValueSpecialCast( IntPtr valueType, IntPtr targetType ); //// //// [ResourceExposure( ResourceScope.None )] //// [MethodImpl( MethodImplOptions.InternalCall )] //// static private extern Object AllocateObjectForByRef( RuntimeTypeHandle type, object value ); //// //// internal unsafe Object CheckValue( Object value, Binder binder, CultureInfo culture, BindingFlags invokeAttr ) //// { //// // this method is used by invocation in reflection to check whether a value can be assigned to type. //// if(IsInstanceOfType( value )) //// { //// return value; //// } //// //// // if this is a ByRef get the element type and check if it's compatible //// bool isByRef = IsByRef; //// if(isByRef) //// { //// Type elementType = GetElementType(); //// if(elementType.IsInstanceOfType( value ) || value == null) //// { //// // need to create an instance of the ByRef if null was provided, but only if primitive, enum or value type //// return AllocateObjectForByRef( elementType.TypeHandle, value ); //// } //// } //// else if(value == null) //// { //// return value; //// } //// else if(this == s_typedRef) //// { //// // everything works for a typedref //// return value; //// } //// //// // check the strange ones courtesy of reflection: //// // - implicit cast between primitives //// // - enum treated as underlying type //// // - IntPtr and System.Reflection.Pointer to pointer types //// bool needsSpecialCast = IsPointer || IsEnum || IsPrimitive; //// if(needsSpecialCast) //// { //// Pointer pointer = value as Pointer; //// Type valueType; //// //// if(pointer != null) //// { //// valueType = pointer.GetPointerType(); //// } //// else //// { //// valueType = value.GetType(); //// } //// //// if(CanValueSpecialCast( valueType.TypeHandle.Value, TypeHandle.Value )) //// { //// if(pointer != null) //// { //// return pointer.GetPointerValue(); //// } //// else //// { //// return value; //// } //// } //// } //// //// if((invokeAttr & BindingFlags.ExactBinding) == BindingFlags.ExactBinding) //// { //// throw new ArgumentException( String.Format( CultureInfo.CurrentUICulture, Environment.GetResourceString( "Arg_ObjObjEx" ), value.GetType(), this ) ); //// } //// //// if(binder != null && binder != Type.DefaultBinder) //// { //// value = binder.ChangeType( value, this, culture ); //// if(IsInstanceOfType( value )) //// { //// return value; //// } //// //// // if this is a ByRef get the element type and check if it's compatible //// if(isByRef) //// { //// Type elementType = GetElementType(); //// if(elementType.IsInstanceOfType( value ) || value == null) //// { //// return AllocateObjectForByRef( elementType.TypeHandle, value ); //// } //// } //// else if(value == null) //// { //// return value; //// } //// //// if(needsSpecialCast) //// { //// Pointer pointer = value as Pointer; //// Type valueType; //// //// if(pointer != null) //// { //// valueType = pointer.GetPointerType(); //// } //// else //// { //// valueType = value.GetType(); //// } //// //// if(CanValueSpecialCast( valueType.TypeHandle.Value, TypeHandle.Value )) //// { //// if(pointer != null) //// { //// return pointer.GetPointerValue(); //// } //// else //// { //// return value; //// } //// } //// } //// } //// //// throw new ArgumentException( String.Format( CultureInfo.CurrentUICulture, Environment.GetResourceString( "Arg_ObjObjEx" ), value.GetType(), this ) ); //// } [DebuggerStepThroughAttribute] [Diagnostics.DebuggerHidden] [MethodImpl( MethodImplOptions.InternalCall )] public override extern Object InvokeMember( String name , BindingFlags bindingFlags , Binder binder , Object target , Object[] providedArgs , ParameterModifier[] modifiers , CultureInfo culture , String[] namedParams ); //// { //// if(IsGenericParameter) //// { //// throw new InvalidOperationException( Environment.GetResourceString( "Arg_GenericParameter" ) ); //// } //// //// #region Preconditions //// if((bindingFlags & InvocationMask) == 0) //// { //// // "Must specify binding flags describing the invoke operation required." //// throw new ArgumentException( Environment.GetResourceString( "Arg_NoAccessSpec" ), "bindingFlags" ); //// } //// //// // Provide a default binding mask if none is provided //// if((bindingFlags & MemberBindingMask) == 0) //// { //// bindingFlags |= BindingFlags.Instance | BindingFlags.Public; //// //// if((bindingFlags & BindingFlags.CreateInstance) == 0) //// { //// bindingFlags |= BindingFlags.Static; //// } //// } //// //// // There must not be more named parameters than provided arguments //// if(namedParams != null) //// { //// if(providedArgs != null) //// { //// if(namedParams.Length > providedArgs.Length) //// { //// // "Named parameter array can not be bigger than argument array." //// throw new ArgumentException( Environment.GetResourceString( "Arg_NamedParamTooBig" ), "namedParams" ); //// } //// } //// else //// { //// if(namedParams.Length != 0) //// { //// // "Named parameter array can not be bigger than argument array." //// throw new ArgumentException( Environment.GetResourceString( "Arg_NamedParamTooBig" ), "namedParams" ); //// } //// } //// } //// #endregion //// //// #region Check that any named paramters are not null //// if(namedParams != null && Array.IndexOf( namedParams, null ) != -1) //// { //// // "Named parameter value must not be null." //// throw new ArgumentException( Environment.GetResourceString( "Arg_NamedParamNull" ), "namedParams" ); //// } //// #endregion //// //// int argCnt = (providedArgs != null) ? providedArgs.Length : 0; //// //// #region Get a Binder //// if(binder == null) //// { //// binder = DefaultBinder; //// } //// //// bool bDefaultBinder = (binder == DefaultBinder); //// #endregion //// //// #region Delegate to Activator.CreateInstance //// if((bindingFlags & BindingFlags.CreateInstance) != 0) //// { //// if((bindingFlags & BindingFlags.CreateInstance) != 0 && (bindingFlags & BinderNonCreateInstance) != 0) //// { //// // "Can not specify both CreateInstance and another access type." //// throw new ArgumentException( Environment.GetResourceString( "Arg_CreatInstAccess" ), "bindingFlags" ); //// } //// //// return Activator.CreateInstance( this, bindingFlags, binder, providedArgs, culture ); //// } //// #endregion //// //// // PutDispProperty and\or PutRefDispProperty ==> SetProperty. //// if((bindingFlags & (BindingFlags.PutDispProperty | BindingFlags.PutRefDispProperty)) != 0) //// { //// bindingFlags |= BindingFlags.SetProperty; //// } //// //// #region Name //// if(name == null) //// { //// throw new ArgumentNullException( "name" ); //// } //// //// if(name.Length == 0 || name.Equals( @"[DISPID=0]" )) //// { //// name = GetDefaultMemberName(); //// //// if(name == null) //// { //// // in InvokeMember we always pretend there is a default member if none is provided and we make it ToString //// name = "ToString"; //// } //// } //// #endregion //// //// #region GetField or SetField //// bool IsGetField = (bindingFlags & BindingFlags.GetField) != 0; //// bool IsSetField = (bindingFlags & BindingFlags.SetField) != 0; //// //// if(IsGetField || IsSetField) //// { //// #region Preconditions //// if(IsGetField) //// { //// if(IsSetField) //// { //// // "Can not specify both Get and Set on a field." //// throw new ArgumentException( Environment.GetResourceString( "Arg_FldSetGet" ), "bindingFlags" ); //// } //// //// if((bindingFlags & BindingFlags.SetProperty) != 0) //// { //// // "Can not specify both GetField and SetProperty." //// throw new ArgumentException( Environment.GetResourceString( "Arg_FldGetPropSet" ), "bindingFlags" ); //// } //// } //// else //// { //// ASSERT.CONSISTENCY_CHECK( IsSetField ); //// //// if(providedArgs == null) //// { //// throw new ArgumentNullException( "providedArgs" ); //// } //// //// if((bindingFlags & BindingFlags.GetProperty) != 0) //// { //// // "Can not specify both SetField and GetProperty." //// throw new ArgumentException( Environment.GetResourceString( "Arg_FldSetPropGet" ), "bindingFlags" ); //// } //// //// if((bindingFlags & BindingFlags.InvokeMethod) != 0) //// { //// // "Can not specify Set on a Field and Invoke on a method." //// throw new ArgumentException( Environment.GetResourceString( "Arg_FldSetInvoke" ), "bindingFlags" ); //// } //// } //// #endregion //// //// #region Lookup Field //// FieldInfo selFld = null; //// FieldInfo[] flds = GetMember( name, MemberTypes.Field, bindingFlags ) as FieldInfo[]; //// //// ASSERT.CONSISTENCY_CHECK( flds != null ); //// //// if(flds.Length == 1) //// { //// selFld = flds[0]; //// } //// else if(flds.Length > 0) //// { //// selFld = binder.BindToField( bindingFlags, flds, IsGetField ? Empty.Value : providedArgs[0], culture ); //// } //// #endregion //// //// if(selFld != null) //// { //// #region Invocation on a field //// if(selFld.FieldType.IsArray || selFld.FieldType == typeof( System.Array )) //// { //// #region Invocation of an array Field //// int idxCnt; //// //// if((bindingFlags & BindingFlags.GetField) != 0) //// { //// idxCnt = argCnt; //// } //// else //// { //// idxCnt = argCnt - 1; //// } //// //// if(idxCnt > 0) //// { //// // Verify that all of the index values are ints //// int[] idx = new int[idxCnt]; //// for(int i = 0; i < idxCnt; i++) //// { //// try //// { //// idx[i] = ((IConvertible)providedArgs[i]).ToInt32( null ); //// } //// catch(InvalidCastException) //// { //// throw new ArgumentException( Environment.GetResourceString( "Arg_IndexMustBeInt" ) ); //// } //// } //// //// // Set or get the value... //// Array a = (Array)selFld.GetValue( target ); //// //// // Set or get the value in the array //// if((bindingFlags & BindingFlags.GetField) != 0) //// { //// return a.GetValue( idx ); //// } //// else //// { //// a.SetValue( providedArgs[idxCnt], idx ); //// return null; //// } //// } //// #endregion //// } //// //// if(IsGetField) //// { //// #region Get the field value //// if(argCnt != 0) //// { //// throw new ArgumentException( Environment.GetResourceString( "Arg_FldGetArgErr" ), "bindingFlags" ); //// } //// //// return selFld.GetValue( target ); //// #endregion //// } //// else //// { //// #region Set the field Value //// if(argCnt != 1) //// { //// throw new ArgumentException( Environment.GetResourceString( "Arg_FldSetArgErr" ), "bindingFlags" ); //// } //// //// selFld.SetValue( target, providedArgs[0], bindingFlags, binder, culture ); //// //// return null; //// #endregion //// } //// #endregion //// } //// //// if((bindingFlags & BinderNonFieldGetSet) == 0) //// { //// throw new MissingFieldException( FullName, name ); //// } //// } //// #endregion //// //// #region Caching Logic //// /* //// bool useCache = false; //// //// // Note that when we add something to the cache, we are careful to ensure //// // that the actual providedArgs matches the parameters of the method. Otherwise, //// // some default argument processing has occurred. We don't want anyone //// // else with the same (insufficient) number of actual arguments to get a //// // cache hit because then they would bypass the default argument processing //// // and the invocation would fail. //// if (bDefaultBinder && namedParams == null && argCnt < 6) //// useCache = true; //// //// if (useCache) //// { //// MethodBase invokeMethod = GetMethodFromCache (name, bindingFlags, argCnt, providedArgs); //// //// if (invokeMethod != null) //// return ((MethodInfo) invokeMethod).Invoke(target, bindingFlags, binder, providedArgs, culture); //// } //// */ //// #endregion //// //// #region Property PreConditions //// // @Legacy - This is RTM behavior //// bool isGetProperty = (bindingFlags & BindingFlags.GetProperty) != 0; //// bool isSetProperty = (bindingFlags & BindingFlags.SetProperty) != 0; //// //// if(isGetProperty || isSetProperty) //// { //// #region Preconditions //// if(isGetProperty) //// { //// ASSERT.CONSISTENCY_CHECK( !IsSetField ); //// //// if(isSetProperty) //// { //// throw new ArgumentException( Environment.GetResourceString( "Arg_PropSetGet" ), "bindingFlags" ); //// } //// } //// else //// { //// ASSERT.CONSISTENCY_CHECK( isSetProperty ); //// //// ASSERT.CONSISTENCY_CHECK( !IsGetField ); //// //// if((bindingFlags & BindingFlags.InvokeMethod) != 0) //// { //// throw new ArgumentException( Environment.GetResourceString( "Arg_PropSetInvoke" ), "bindingFlags" ); //// } //// } //// #endregion //// } //// #endregion //// //// MethodInfo[] finalists = null; //// MethodInfo finalist = null; //// //// #region BindingFlags.InvokeMethod //// if((bindingFlags & BindingFlags.InvokeMethod) != 0) //// { //// #region Lookup Methods //// MethodInfo[] semiFinalists = GetMember( name, MemberTypes.Method, bindingFlags ) as MethodInfo[]; //// ArrayList results = null; //// //// for(int i = 0; i < semiFinalists.Length; i++) //// { //// MethodInfo semiFinalist = semiFinalists[i]; //// ASSERT.CONSISTENCY_CHECK( semiFinalist != null ); //// //// if(!FilterApplyMethodBaseInfo( semiFinalist, bindingFlags, null, CallingConventions.Any, new Type[argCnt], false )) //// { //// continue; //// } //// //// if(finalist == null) //// { //// finalist = semiFinalist; //// } //// else //// { //// if(results == null) //// { //// results = new ArrayList( semiFinalists.Length ); //// results.Add( finalist ); //// } //// //// results.Add( semiFinalist ); //// } //// } //// //// if(results != null) //// { //// ASSERT.CONSISTENCY_CHECK( results.Count > 1 ); //// finalists = new MethodInfo[results.Count]; //// results.CopyTo( finalists ); //// } //// #endregion //// } //// #endregion //// //// ASSERT.CONSISTENCY_CHECK( LOGIC.IMPLIES( finalists != null, finalist != null ) ); //// //// #region BindingFlags.GetProperty or BindingFlags.SetProperty //// if(finalist == null && isGetProperty || isSetProperty) //// { //// #region Lookup Property //// PropertyInfo[] semiFinalists = GetMember( name, MemberTypes.Property, bindingFlags ) as PropertyInfo[]; //// ArrayList results = null; //// //// for(int i = 0; i < semiFinalists.Length; i++) //// { //// MethodInfo semiFinalist = null; //// //// if(isSetProperty) //// { //// semiFinalist = semiFinalists[i].GetSetMethod( true ); //// } //// else //// { //// semiFinalist = semiFinalists[i].GetGetMethod( true ); //// } //// //// if(semiFinalist == null) //// { //// continue; //// } //// //// if(!FilterApplyMethodBaseInfo( semiFinalist, bindingFlags, null, CallingConventions.Any, new Type[argCnt], false )) //// { //// continue; //// } //// //// if(finalist == null) //// { //// finalist = semiFinalist; //// } //// else //// { //// if(results == null) //// { //// results = new ArrayList( semiFinalists.Length ); //// results.Add( finalist ); //// } //// //// results.Add( semiFinalist ); //// } //// } //// //// if(results != null) //// { //// ASSERT.CONSISTENCY_CHECK( results.Count > 1 ); //// finalists = new MethodInfo[results.Count]; //// results.CopyTo( finalists ); //// } //// #endregion //// } //// #endregion //// //// if(finalist != null) //// { //// #region Invoke //// if(finalists == null && argCnt == 0 && finalist.GetParametersNoCopy().Length == 0 && (bindingFlags & BindingFlags.OptionalParamBinding) == 0) //// { //// //if (useCache && argCnt == props[0].GetParameters().Length) //// // AddMethodToCache(name, bindingFlags, argCnt, providedArgs, props[0]); //// //// return finalist.Invoke( target, bindingFlags, binder, providedArgs, culture ); //// } //// //// if(finalists == null) //// { //// finalists = new MethodInfo[] { finalist }; //// } //// //// if(providedArgs == null) //// { //// providedArgs = new Object[0]; //// } //// //// Object state = null; //// //// //// MethodBase invokeMethod = null; //// //// try //// { //// invokeMethod = binder.BindToMethod( bindingFlags, finalists, ref providedArgs, modifiers, culture, namedParams, out state ); //// } //// catch(MissingMethodException) //// { //// } //// //// if(invokeMethod == null) //// { //// throw new MissingMethodException( FullName, name ); //// } //// //// //if (useCache && argCnt == invokeMethod.GetParameters().Length) //// // AddMethodToCache(name, bindingFlags, argCnt, providedArgs, invokeMethod); //// //// Object result = ((MethodInfo)invokeMethod).Invoke( target, bindingFlags, binder, providedArgs, culture ); //// //// if(state != null) //// { //// binder.ReorderArgumentArray( ref providedArgs, state ); //// } //// //// return result; //// #endregion //// } //// //// throw new MissingMethodException( FullName, name ); //// } #endregion #endregion #region Object Overrides //// public override bool Equals( object obj ) //// { //// // ComObjects are identified by the instance of the Type object and not the TypeHandle. //// return obj == this; //// } //// //// public override int GetHashCode() //// { #if WIN32 //// return (int)GetTypeHandleInternal().Value; #else //// long l = (long)GetTypeHandleInternal().Value; //// return unchecked( (int)l ); #endif //// } public override String ToString() { return this.Name; //// return Cache.GetToString(); } #endregion #region ICloneable //// public Object Clone() //// { //// return this; //// } #endregion #region ISerializable //// public void GetObjectData( SerializationInfo info, StreamingContext context ) //// { //// if(info == null) //// { //// throw new ArgumentNullException( "info" ); //// } //// //// UnitySerializationHolder.GetUnitySerializationInfo( info, this ); //// } #endregion #region ICustomAttributeProvider [MethodImpl( MethodImplOptions.InternalCall )] public override extern Object[] GetCustomAttributes( bool inherit ); //// { //// return CustomAttribute.GetCustomAttributes( this, typeof( object ) as RuntimeType, inherit ); //// } [MethodImpl( MethodImplOptions.InternalCall )] public override extern Object[] GetCustomAttributes( Type attributeType, bool inherit ); //// { //// if(attributeType == null) //// { //// throw new ArgumentNullException( "attributeType" ); //// } //// //// RuntimeType attributeRuntimeType = attributeType.UnderlyingSystemType as RuntimeType; //// //// if(attributeRuntimeType == null) //// { //// throw new ArgumentException( Environment.GetResourceString( "Arg_MustBeType" ), "attributeType" ); //// } //// //// return CustomAttribute.GetCustomAttributes( this, attributeRuntimeType, inherit ); //// } [MethodImpl( MethodImplOptions.InternalCall )] public override extern bool IsDefined( Type attributeType, bool inherit ); //// { //// if(attributeType == null) //// { //// throw new ArgumentNullException( "attributeType" ); //// } //// //// RuntimeType attributeRuntimeType = attributeType.UnderlyingSystemType as RuntimeType; //// //// if(attributeRuntimeType == null) //// { //// throw new ArgumentException( Environment.GetResourceString( "Arg_MustBeType" ), "attributeType" ); //// } //// //// return CustomAttribute.IsDefined( this, attributeRuntimeType, inherit ); //// } #endregion #region MemberInfo Overrides public override extern String Name { [MethodImpl( MethodImplOptions.InternalCall )] get; //// { //// return Cache.GetName(); //// } } //// public override MemberTypes MemberType //// { //// get //// { //// if(this.IsPublic || this.IsNotPublic) //// { //// return MemberTypes.TypeInfo; //// } //// else //// { //// return MemberTypes.NestedType; //// } //// } //// } public override extern Type DeclaringType { [MethodImpl( MethodImplOptions.InternalCall )] get; //// { //// return Cache.GetEnclosingType(); //// } } //// public override Type ReflectedType //// { //// get //// { //// return DeclaringType; //// } //// } //// //// public override int MetadataToken //// { //// get //// { //// return m_handle.GetToken(); //// } //// } #endregion #region Legacy Internal //// internal void CreateInstanceCheckThis() //// { //// if(this is ReflectionOnlyType) //// { //// throw new ArgumentException( Environment.GetResourceString( "Arg_ReflectionOnlyInvoke" ) ); //// } //// //// if(ContainsGenericParameters) //// { //// throw new ArgumentException( String.Format( CultureInfo.CurrentCulture, Environment.GetResourceString( "Acc_CreateGenericEx" ), this ) ); //// } //// //// Type elementType = this.GetRootElementType(); //// //// if(elementType == typeof( ArgIterator )) //// { //// throw new NotSupportedException( String.Format( CultureInfo.CurrentCulture, Environment.GetResourceString( "Acc_CreateArgIterator" ) ) ); //// } //// //// if(elementType == typeof( void )) //// { //// throw new NotSupportedException( String.Format( CultureInfo.CurrentCulture, Environment.GetResourceString( "Acc_CreateVoid" ) ) ); //// } //// } //// //// internal Object CreateInstanceImpl( BindingFlags bindingAttr, Binder binder, Object[] args, CultureInfo culture, Object[] activationAttributes ) //// { //// CreateInstanceCheckThis(); //// //// Object server = null; //// //// try //// { //// try //// { //// // Store the activation attributes in thread local storage. //// // These attributes are later picked up by specialized //// // activation services like remote activation services to //// // influence the activation. //// if(null != activationAttributes) //// { //// ActivationServices.PushActivationAttributes( this, activationAttributes ); //// } //// //// if(args == null) //// { //// args = new Object[0]; //// } //// //// int argCnt = args.Length; //// //// // Without a binder we need to do use the default binder... //// if(binder == null) //// { //// binder = DefaultBinder; //// } //// //// // deal with the __COMObject case first. It is very special because from a reflection point of view it has no ctors //// // so a call to GetMemberCons would fail //// if(argCnt == 0 && (bindingAttr & BindingFlags.Public) != 0 && (bindingAttr & BindingFlags.Instance) != 0 //// && (IsGenericCOMObjectImpl() || IsSubclassOf( typeof( ValueType ) ))) //// { //// server = CreateInstanceImpl( ((bindingAttr & BindingFlags.NonPublic) != 0) ? false : true ); //// } //// else //// { //// MethodBase[] candidates = GetConstructors( bindingAttr ); //// ArrayList matches = new ArrayList( candidates.Length ); //// Type[] argsType = new Type[argCnt]; //// for(int i = 0; i < argCnt; i++) //// { //// if(args[i] != null) //// { //// argsType[i] = args[i].GetType(); //// } //// } //// //// //// for(int i = 0; i < candidates.Length; i++) //// { //// MethodBase canidate = candidates[i]; //// //// if(FilterApplyMethodBaseInfo( candidates[i], bindingAttr, null, CallingConventions.Any, argsType, false )) //// { //// matches.Add( candidates[i] ); //// } //// } //// //// MethodBase[] cons = new MethodBase[matches.Count]; //// matches.CopyTo( cons ); //// if(cons != null && cons.Length == 0) //// { //// cons = null; //// } //// //// if(cons == null) //// { //// // Null out activation attributes before throwing exception //// if(null != activationAttributes) //// { //// ActivationServices.PopActivationAttributes( this ); //// activationAttributes = null; //// } //// //// throw new MissingMethodException( String.Format( CultureInfo.CurrentCulture, Environment.GetResourceString( "MissingConstructor_Name" ), FullName ) ); //// } //// //// // It would be strange to have an argCnt of 0 and more than //// // one constructor. //// if(argCnt == 0 && cons.Length == 1 && (bindingAttr & BindingFlags.OptionalParamBinding) == 0) //// { //// server = Activator.CreateInstance( this, true ); //// } //// else //// { //// // MethodBase invokeMethod = binder.BindToMethod(cons,args,null,null,culture); //// MethodBase invokeMethod; //// Object state = null; //// //// try //// { //// invokeMethod = binder.BindToMethod( bindingAttr, cons, ref args, null, culture, null, out state ); //// } //// catch(MissingMethodException) //// { //// invokeMethod = null; //// } //// //// if(invokeMethod == null) //// { //// // Null out activation attributes before throwing exception //// if(null != activationAttributes) //// { //// ActivationServices.PopActivationAttributes( this ); //// activationAttributes = null; //// } //// throw new MissingMethodException( String.Format( CultureInfo.CurrentCulture, Environment.GetResourceString( "MissingConstructor_Name" ), FullName ) ); //// } //// //// // If we're creating a delegate, we're about to call a //// // constructor taking an integer to represent a target //// // method. Since this is very difficult (and expensive) //// // to verify, we're just going to demand UnmanagedCode //// // permission before allowing this. Partially trusted //// // clients can instead use Delegate.CreateDelegate, //// // which allows specification of the target method via //// // name or MethodInfo. //// //if (isDelegate) //// if(typeof( Delegate ).IsAssignableFrom( invokeMethod.DeclaringType )) //// { //// new SecurityPermission( SecurityPermissionFlag.UnmanagedCode ).Demand(); //// } //// //// server = ((ConstructorInfo)invokeMethod).Invoke( bindingAttr, binder, args, culture ); //// if(state != null) //// { //// binder.ReorderArgumentArray( ref args, state ); //// } //// } //// } //// } //// finally //// { //// // Reset the TLS to null //// if(null != activationAttributes) //// { //// ActivationServices.PopActivationAttributes( this ); //// activationAttributes = null; //// } //// } //// } //// catch(Exception) //// { //// throw; //// } //// //// //Console.WriteLine(server); //// return server; //// } //// //// // the cache entry //// class ActivatorCacheEntry //// { //// // the type to cache //// internal Type m_type; //// // the delegate containing the call to the ctor, will be replaced by an IntPtr to feed a calli with //// internal CtorDelegate m_ctor; //// internal RuntimeMethodHandle m_hCtorMethodHandle; //// // Is a security check needed before this constructor is invoked? //// internal bool m_bNeedSecurityCheck; //// // Lazy initialization was performed //// internal bool m_bFullyInitialized; //// //// internal ActivatorCacheEntry( Type t, RuntimeMethodHandle rmh, bool bNeedSecurityCheck ) //// { //// m_type = t; //// m_bNeedSecurityCheck = bNeedSecurityCheck; //// m_hCtorMethodHandle = rmh; //// } //// } //// //// //ActivatorCache //// class ActivatorCache //// { //// const int CACHE_SIZE = 16; //// //// int hash_counter; //Counter for wrap around //// ActivatorCacheEntry[] cache = new ActivatorCacheEntry[CACHE_SIZE]; //// //// ConstructorInfo delegateCtorInfo; //// PermissionSet delegateCreatePermissions; //// //// private void InitializeDelegateCreator() //// { //// // No synchronization needed here. In the worst case we create extra garbage //// PermissionSet ps = new PermissionSet( PermissionState.None ); //// //// ps.AddPermission( new ReflectionPermission( ReflectionPermissionFlag.MemberAccess ) ); //// ps.AddPermission( new SecurityPermission ( SecurityPermissionFlag .UnmanagedCode ) ); //// //// System.Threading.Thread.MemoryBarrier(); //// //// delegateCreatePermissions = ps; //// //// ConstructorInfo ctorInfo = typeof( CtorDelegate ).GetConstructor( new Type[] { typeof( Object ), typeof( IntPtr ) } ); //// //// System.Threading.Thread.MemoryBarrier(); //// delegateCtorInfo = ctorInfo; // this assignment should be last //// } //// //// private void InitializeCacheEntry( ActivatorCacheEntry ace ) //// { //// if(!ace.m_type.IsValueType) //// { //// BCLDebug.Assert( !ace.m_hCtorMethodHandle.Equals( RuntimeMethodHandle.EmptyHandle ), "Expected the default ctor method handle for a reference type." ); //// //// if(delegateCtorInfo == null) //// { //// InitializeDelegateCreator(); //// } //// //// delegateCreatePermissions.Assert(); //// //// // No synchronization needed here. In the worst case we create extra garbage //// CtorDelegate ctor = (CtorDelegate)delegateCtorInfo.Invoke( new Object[] { null, ace.m_hCtorMethodHandle.GetFunctionPointer() } ); //// //// System.Threading.Thread.MemoryBarrier(); //// ace.m_ctor = ctor; //// } //// //// ace.m_bFullyInitialized = true; //// } //// //// internal ActivatorCacheEntry GetEntry( Type t ) //// { //// int index = hash_counter; //// for(int i = 0; i < CACHE_SIZE; i++) //// { //// ActivatorCacheEntry ace = cache[index]; //// if(ace != null && (Object)ace.m_type == (Object)t) //check for type match.. //// { //// if(!ace.m_bFullyInitDialized) //// { //// InitializeCacheEntry( ace ); //// } //// return ace; //// } //// index = (index + 1) & (ActivatorCache.CACHE_SIZE - 1); //// } //// return null; //// } //// //// internal void SetEntry( ActivatorCacheEntry ace ) //// { //// // fill the the array backwards to hit the most recently filled entries first in GetEntry //// int index = (hash_counter - 1) & (ActivatorCache.CACHE_SIZE - 1); //// //// hash_counter = index; //// cache[index] = ace; //// } //// } //// //// static ActivatorCache s_ActivatorCache; //// //// // the slow path of CreateInstanceImpl //// private Object CreateInstanceSlow( bool publicOnly, bool fillCache ) //// { //// RuntimeMethodHandle runtime_ctor = RuntimeMethodHandle.EmptyHandle; //// bool bNeedSecurityCheck = true; //// bool bCanBeCached = false; //// bool bSecurityCheckOff = false; //// //// CreateInstanceCheckThis(); //// //// if(!fillCache) //// { //// bSecurityCheckOff = true; //// } //// //// Object instance = RuntimeTypeHandle.CreateInstance( this, publicOnly, bSecurityCheckOff, ref bCanBeCached, ref runtime_ctor, ref bNeedSecurityCheck ); //// //// if(bCanBeCached && fillCache) //// { //// ActivatorCache activatorCache = s_ActivatorCache; //// if(activatorCache == null) //// { //// // No synchronization needed here. In the worst case we create extra garbage //// activatorCache = new ActivatorCache(); //// //// System.Threading.Thread.MemoryBarrier(); //// s_ActivatorCache = activatorCache; //// } //// //// // cache the ctor //// ActivatorCacheEntry ace = new ActivatorCacheEntry( this, runtime_ctor, bNeedSecurityCheck ); //// //// System.Threading.Thread.MemoryBarrier(); //// activatorCache.SetEntry( ace ); //// } //// return instance; //// } //// //// [DebuggerStepThroughAttribute] //// [Diagnostics.DebuggerHidden] //// internal Object CreateInstanceImpl( bool publicOnly ) //// { //// return CreateInstanceImpl( publicOnly, false, true ); //// } //// //// [DebuggerStepThroughAttribute] //// [Diagnostics.DebuggerHidden] //// internal Object CreateInstanceImpl( bool publicOnly, bool skipVisibilityChecks, bool fillCache ) //// { //// // next line will throw for ReflectionOnly types //// RuntimeTypeHandle typeHandle = TypeHandle; //// //// ActivatorCache activatorCache = s_ActivatorCache; //// if(activatorCache != null) //// { //// ActivatorCacheEntry ace = activatorCache.GetEntry( this ); //// if(ace != null) //// { //// if(publicOnly) //// { //// if(ace.m_ctor != null && (ace.m_hCtorMethodHandle.GetAttributes() & MethodAttributes.MemberAccessMask) != MethodAttributes.Public) //// { //// throw new MissingMethodException( Environment.GetResourceString( "Arg_NoDefCTor" ) ); //// } //// } //// //// // Allocate empty object //// Object instance = typeHandle.Allocate(); //// if(ace.m_ctor != null) //// { //// // Perform security checks if needed //// if(!skipVisibilityChecks && ace.m_bNeedSecurityCheck) //// { //// MethodBase.PerformSecurityCheck( instance, ace.m_hCtorMethodHandle, TypeHandle.Value, INVOCATION_FLAGS_CONSTRUCTOR_INVOKE ); //// } //// //// // Call ctor (value types wont have any) //// try //// { //// ace.m_ctor( instance ); //// } //// catch(Exception e) //// { //// throw new TargetInvocationException( e ); //// } //// } //// //// return instance; //// } //// } //// //// return CreateInstanceSlow( publicOnly, fillCache ); //// } //// //// //End //// //// internal bool SupportsInterface( Object o ) //// { //// return TypeHandle.SupportsInterface( o ); //// } //// //// internal void InvalidateCachedNestedType() //// { //// Cache.InvalidateCachedNestedType(); //// } //// //// internal bool IsGenericCOMObjectImpl() //// { //// return m_handle.IsComObject( true ); //// } #endregion #region Legacy Static Internal //// internal static bool CanCastTo( RuntimeType fromType, RuntimeType toType ) //// { //// return fromType.GetTypeHandleInternal().CanCastTo( toType.GetTypeHandleInternal() ); //// } //// //// [ResourceExposure( ResourceScope.None )] //// [MethodImpl( MethodImplOptions.InternalCall )] //// private static extern Object _CreateEnum( IntPtr enumType, long value ); //// //// internal static Object CreateEnum( RuntimeTypeHandle enumType, long value ) //// { //// return _CreateEnum( enumType.Value, value ); //// } //// //// internal static Type PrivateGetType( String typeName, bool throwOnError, bool ignoreCase, ref StackCrawlMark stackMark ) //// { //// return PrivateGetType( typeName, throwOnError, ignoreCase, false, ref stackMark ); //// } //// //// internal static Type PrivateGetType( String typeName, bool throwOnError, bool ignoreCase, bool reflectionOnly, ref StackCrawlMark stackMark ) //// { //// unsafe //// { //// if(typeName == null) //// { //// throw new ArgumentNullException( "TypeName" ); //// } //// //// return RuntimeTypeHandle.GetTypeByName( typeName, throwOnError, ignoreCase, reflectionOnly, ref stackMark ).GetRuntimeType(); //// } //// } #endregion } } ================================================ FILE: Zelig/Zelig/RunTime/Framework/mscorlib/System/RuntimeTypeHandle.cs ================================================ // ==++== // // Copyright (c) Microsoft Corporation. All rights reserved. // // ==--== #define DEBUG_PTRS namespace System { using System; using System.Reflection; ////using System.Reflection.Emit; using System.Runtime.ConstrainedExecution; using System.Diagnostics; using System.Runtime.Serialization; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; ////using System.Runtime.Versioning; ////using System.Text; using System.Globalization; ////using System.Security; ////using Microsoft.Win32.SafeHandles; ////using StackCrawlMark = System.Threading.StackCrawlMark; [Microsoft.Zelig.Internals.WellKnownType( "System_RuntimeTypeHandle" )] [Serializable] public unsafe struct RuntimeTypeHandle /*: ISerializable*/ { //// [ResourceExposure( ResourceScope.None )] //// [MethodImpl( MethodImplOptions.InternalCall )] //// internal extern bool IsInstanceOfType( Object o ); //// //// internal unsafe static IntPtr GetTypeHelper( IntPtr th, IntPtr pGenericArgs, int cGenericArgs, IntPtr pModifiers, int cModifiers ) //// { //// RuntimeTypeHandle typeHandle = new RuntimeTypeHandle( th.ToPointer() ); //// //// Type type = typeHandle.GetRuntimeType(); //// if(type == null) //// { //// return th; //// } //// //// if(cGenericArgs > 0) //// { //// Type[] genericArgs = new Type[cGenericArgs]; //// void** arGenericArgs = (void**)pGenericArgs.ToPointer(); //// //// for(int i = 0; i < genericArgs.Length; i++) //// { //// RuntimeTypeHandle genericArg = new RuntimeTypeHandle( (void*)Marshal.ReadIntPtr( (IntPtr)arGenericArgs, i * sizeof( void* ) ) ); //// //// genericArgs[i] = Type.GetTypeFromHandle( genericArg ); //// if(genericArgs[i] == null) //// { //// return (IntPtr)0; //// } //// } //// //// type = type.MakeGenericType( genericArgs ); //// } //// //// if(cModifiers > 0) //// { //// int* arModifiers = (int*)pModifiers.ToPointer(); //// for(int i = 0; i < cModifiers; i++) //// { //// if((CorElementType)Marshal.ReadInt32( (IntPtr)arModifiers, i * sizeof( int ) ) == CorElementType.Ptr) //// { //// type = type.MakePointerType(); //// } //// else if((CorElementType)Marshal.ReadInt32( (IntPtr)arModifiers, i * sizeof( int ) ) == CorElementType.ByRef) //// { //// type = type.MakeByRefType(); //// } //// else if((CorElementType)Marshal.ReadInt32( (IntPtr)arModifiers, i * sizeof( int ) ) == CorElementType.SzArray) //// { //// type = type.MakeArrayType(); //// } //// else //// { //// type = type.MakeArrayType( Marshal.ReadInt32( (IntPtr)arModifiers, ++i * sizeof( int ) ) ); //// } //// } //// } //// //// return type.GetTypeHandleInternal().Value; //// } public static bool operator ==( RuntimeTypeHandle left, object right ) { return left.Equals( right ); } public static bool operator ==( object left, RuntimeTypeHandle right ) { return right.Equals( left ); } public static bool operator !=( RuntimeTypeHandle left, object right ) { return !left.Equals( right ); } public static bool operator !=( object left, RuntimeTypeHandle right ) { return !right.Equals( left ); } /* internal new Type GetType() { Console.WriteLine("RuntimeTypeHandle.GetType() called"); throw new Exception("RuntimeTypeHandle.GetType() called. Chances are you want to call GetRuntimeType()"); return base.GetType(); } */ //// private const int MAX_CLASS_NAME = 1024; //// internal static RuntimeTypeHandle EmptyHandle //// { //// get //// { //// return new RuntimeTypeHandle(); //// } //// } //// //// // this is the TypeHandle/MethodTable for the type ////#pragma warning disable 649 // Field 'field' is never assigned to, and will always have its default value 'value' //// private IntPtr m_ptr; ////#pragma warning restore 649 [MethodImpl( MethodImplOptions.InternalCall )] public extern override int GetHashCode(); //// { //// return m_ptr.GetHashCode(); //// } //// [ReliabilityContract( Consistency.WillNotCorruptState, Cer.Success )] [MethodImpl( MethodImplOptions.InternalCall )] public extern override bool Equals( object obj ); //// { //// if(!(obj is RuntimeTypeHandle)) //// { //// return false; //// } //// //// return Equals( (RuntimeTypeHandle)obj ); //// } //// [ReliabilityContract( Consistency.WillNotCorruptState, Cer.Success )] [MethodImpl( MethodImplOptions.InternalCall )] public extern bool Equals( RuntimeTypeHandle handle ); //// { //// return handle.m_ptr == m_ptr; //// } //// public IntPtr Value //// { //// get //// { //// return m_ptr; //// } //// } //// //// internal RuntimeTypeHandle( void* rth ) //// { //// m_ptr = new IntPtr( rth ); //// } //// //// internal RuntimeTypeHandle( IntPtr rth ) //// { //// m_ptr = rth; //// } [MethodImpl( MethodImplOptions.InternalCall )] internal extern bool IsNullHandle(); //// { //// return m_ptr.ToPointer() == null; //// } //// [ResourceExposure( ResourceScope.None )] //// [MethodImpl( MethodImplOptions.InternalCall )] //// internal static extern Object CreateInstance( RuntimeType type, bool publicOnly, bool noCheck, ref bool canBeCached, ref RuntimeMethodHandle ctor, ref bool bNeedSecurityCheck ); //// //// [ResourceExposure( ResourceScope.None )] //// [MethodImpl( MethodImplOptions.InternalCall )] //// internal extern Object CreateCaInstance( RuntimeMethodHandle ctor ); //// //// [ResourceExposure( ResourceScope.None )] //// [MethodImpl( MethodImplOptions.InternalCall )] //// internal extern Object Allocate(); //// //// [ResourceExposure( ResourceScope.None )] //// [MethodImpl( MethodImplOptions.InternalCall )] //// internal extern Object CreateInstanceForAnotherGenericParameter( Type genericParameter ); //// //// internal RuntimeType GetRuntimeType() //// { //// if(!IsNullHandle()) //// { //// return (System.RuntimeType)Type.GetTypeFromHandle( this ); //// } //// else //// { //// return null; //// } //// } //// //// [ResourceExposure( ResourceScope.None )] //// [MethodImpl( MethodImplOptions.InternalCall )] //// internal extern CorElementType GetCorElementType(); //// //// [ResourceExposure( ResourceScope.None )] //// [MethodImpl( MethodImplOptions.InternalCall )] //// private extern IntPtr _GetAssemblyHandle(); //// internal AssemblyHandle GetAssemblyHandle() //// { //// return new AssemblyHandle( _GetAssemblyHandle() ); //// } //// //// [ResourceExposure( ResourceScope.None )] //// [MethodImpl( MethodImplOptions.InternalCall )] //// [ReliabilityContract( Consistency.WillNotCorruptState, Cer.Success )] //// private extern IntPtr _GetModuleHandle(); //// //// [CLSCompliant( false )] //// [ReliabilityContract( Consistency.WillNotCorruptState, Cer.Success )] //// public ModuleHandle GetModuleHandle() //// { //// return new ModuleHandle( _GetModuleHandle() ); //// } //// //// [ResourceExposure( ResourceScope.None )] //// [MethodImpl( MethodImplOptions.InternalCall )] //// private extern void* _GetBaseTypeHandle(); //// internal RuntimeTypeHandle GetBaseTypeHandle() //// { //// return new RuntimeTypeHandle( _GetBaseTypeHandle() ); //// } //// //// [ResourceExposure( ResourceScope.None )] //// [MethodImpl( MethodImplOptions.InternalCall )] //// internal extern TypeAttributes GetAttributes(); //// //// [ResourceExposure( ResourceScope.None )] //// [MethodImpl( MethodImplOptions.InternalCall )] //// private extern void* _GetElementType(); //// internal RuntimeTypeHandle GetElementType() //// { //// return new RuntimeTypeHandle( _GetElementType() ); //// } //// //// [ResourceExposure( ResourceScope.None )] //// [MethodImpl( MethodImplOptions.InternalCall )] //// internal extern RuntimeTypeHandle GetCanonicalHandle(); //// //// [ResourceExposure( ResourceScope.None )] //// [MethodImpl( MethodImplOptions.InternalCall )] //// internal extern int GetArrayRank(); //// //// [ResourceExposure( ResourceScope.None )] //// [MethodImpl( MethodImplOptions.InternalCall )] //// internal extern int GetToken(); //// //// [ResourceExposure( ResourceScope.None )] //// [MethodImpl( MethodImplOptions.InternalCall )] //// private extern void* _GetMethodAt( int slot ); //// internal RuntimeMethodHandle GetMethodAt( int slot ) //// { //// return new RuntimeMethodHandle( _GetMethodAt( slot ) ); //// } //// //// [ResourceExposure( ResourceScope.None )] //// [MethodImpl( MethodImplOptions.InternalCall )] //// private extern void* _GetMethodDescChunk(); //// internal MethodDescChunkHandle GetMethodDescChunk() //// { //// return new MethodDescChunkHandle( _GetMethodDescChunk() ); //// } //// //// [ResourceExposure( ResourceScope.None )] //// [MethodImpl( MethodImplOptions.InternalCall )] //// internal extern bool GetFields( int** result, int* count ); //// //// [ResourceExposure( ResourceScope.None )] //// [MethodImpl( MethodImplOptions.InternalCall )] //// internal extern RuntimeTypeHandle[] GetInterfaces(); //// //// [ResourceExposure( ResourceScope.None )] //// [MethodImpl( MethodImplOptions.InternalCall )] //// internal extern RuntimeTypeHandle[] GetConstraints(); //// //// [ResourceExposure( ResourceScope.AppDomain )] //// [MethodImpl( MethodImplOptions.InternalCall )] //// internal extern IntPtr GetGCHandle( GCHandleType type ); //// //// [ResourceExposure( ResourceScope.AppDomain )] //// [MethodImpl( MethodImplOptions.InternalCall )] //// internal extern void FreeGCHandle( IntPtr handle ); //// //// [ResourceExposure( ResourceScope.None )] //// [MethodImpl( MethodImplOptions.InternalCall )] //// private extern void* _GetMethodFromToken( int tkMethodDef ); //// internal RuntimeMethodHandle GetMethodFromToken( int tkMethodDef ) //// { //// return new RuntimeMethodHandle( _GetMethodFromToken( tkMethodDef ) ); //// } //// //// [ResourceExposure( ResourceScope.None )] //// [MethodImpl( MethodImplOptions.InternalCall )] //// internal extern int GetNumVtableSlots(); //// //// [ResourceExposure( ResourceScope.None )] //// [MethodImpl( MethodImplOptions.InternalCall )] //// internal extern int GetInterfaceMethodSlots(); //// //// [ResourceExposure( ResourceScope.None )] //// [MethodImpl( MethodImplOptions.InternalCall )] //// private extern int GetFirstSlotForInterface( IntPtr interfaceHandle ); //// internal int GetFirstSlotForInterface( RuntimeTypeHandle interfaceHandle ) //// { //// return GetFirstSlotForInterface( interfaceHandle.Value ); //// } //// //// [ResourceExposure( ResourceScope.None )] //// [MethodImpl( MethodImplOptions.InternalCall )] //// private extern int GetInterfaceMethodImplementationSlot( IntPtr interfaceHandle, IntPtr interfaceMethodHandle ); //// [ResourceExposure( ResourceScope.None )] //// [ResourceConsumption( ResourceScope.AppDomain, ResourceScope.AppDomain )] //// internal int GetInterfaceMethodImplementationSlot( RuntimeTypeHandle interfaceHandle, RuntimeMethodHandle interfaceMethodHandle ) //// { //// return GetInterfaceMethodImplementationSlot( interfaceHandle.Value, interfaceMethodHandle.Value ); //// } //// //// [ResourceExposure( ResourceScope.None )] //// [MethodImpl( MethodImplOptions.InternalCall )] //// internal extern bool IsComObject( bool isGenericCOM ); //// //// [ResourceExposure( ResourceScope.None )] //// [MethodImpl( MethodImplOptions.InternalCall )] //// internal extern bool IsContextful(); //// //// [ResourceExposure( ResourceScope.None )] //// [MethodImpl( MethodImplOptions.InternalCall )] //// internal extern bool IsVisible(); //// //// [ResourceExposure( ResourceScope.None )] //// [MethodImpl( MethodImplOptions.InternalCall )] //// internal extern bool _IsVisibleFromModule( IntPtr module ); //// [ResourceExposure( ResourceScope.None )] //// [ResourceConsumption( ResourceScope.AppDomain, ResourceScope.AppDomain )] //// internal bool IsVisibleFromModule( ModuleHandle module ) //// { //// return _IsVisibleFromModule( (IntPtr)module.Value ); //// } //// //// [ResourceExposure( ResourceScope.None )] //// [MethodImpl( MethodImplOptions.InternalCall )] //// internal extern bool HasProxyAttribute(); //// //// [ResourceExposure( ResourceScope.None )] //// [MethodImpl( MethodImplOptions.InternalCall )] //// internal extern string ConstructName( bool nameSpace, bool fullInst, bool assembly ); //// //// [ResourceExposure( ResourceScope.None )] //// [MethodImpl( MethodImplOptions.InternalCall )] //// private extern void* _GetUtf8Name(); //// //// internal Utf8String GetUtf8Name() //// { //// return new Utf8String( _GetUtf8Name() ); //// } //// //// [ResourceExposure( ResourceScope.None )] //// [MethodImpl( MethodImplOptions.InternalCall )] //// private extern bool CanCastTo( IntPtr target ); //// internal bool CanCastTo( RuntimeTypeHandle target ) //// { //// return CanCastTo( target.Value ); //// } //// //// [ResourceExposure( ResourceScope.None )] //// [MethodImpl( MethodImplOptions.InternalCall )] //// internal extern RuntimeTypeHandle GetDeclaringType(); //// //// [ResourceExposure( ResourceScope.None )] //// [MethodImpl( MethodImplOptions.InternalCall )] //// private extern void* _GetDeclaringMethod(); //// internal RuntimeMethodHandle GetDeclaringMethod() //// { //// return new RuntimeMethodHandle( _GetDeclaringMethod() ); //// } //// //// [ResourceExposure( ResourceScope.None )] //// [MethodImpl( MethodImplOptions.InternalCall )] //// private extern void* _GetDefaultConstructor(); //// internal RuntimeMethodHandle GetDefaultConstructor() //// { //// return new RuntimeMethodHandle( _GetDefaultConstructor() ); //// } //// //// [ResourceExposure( ResourceScope.None )] //// [MethodImpl( MethodImplOptions.InternalCall )] //// internal extern bool SupportsInterface( object target ); //// //// [ResourceExposure( ResourceScope.None )] //// [MethodImpl( MethodImplOptions.InternalCall )] //// internal extern static void* _GetTypeByName( string name, bool throwOnError, bool ignoreCase, bool reflectionOnly, ref StackCrawlMark stackMark, bool loadTypeFromPartialName ); //// internal static RuntimeTypeHandle GetTypeByName( string name, bool throwOnError, bool ignoreCase, bool reflectionOnly, ref StackCrawlMark stackMark ) //// { //// if(name == null || name.Length == 0) //// { //// if(throwOnError) //// { //// throw new TypeLoadException( Environment.GetResourceString( "Arg_TypeLoadNullStr" ) ); //// } //// //// return new RuntimeTypeHandle(); //// } //// //// return new RuntimeTypeHandle( _GetTypeByName( name, throwOnError, ignoreCase, reflectionOnly, ref stackMark, false ) ); //// } //// //// [ResourceExposure( ResourceScope.None )] //// [MethodImpl( MethodImplOptions.InternalCall )] //// internal extern static void* _GetTypeByNameUsingCARules( string name, IntPtr scope ); //// internal static Type GetTypeByNameUsingCARules( string name, Module scope ) //// { //// if(name == null || name.Length == 0) //// { //// throw new ArgumentException(); //// } //// //// return new RuntimeTypeHandle( _GetTypeByNameUsingCARules( name, (IntPtr)scope.GetModuleHandle().Value ) ).GetRuntimeType(); //// } //// //// [ResourceExposure( ResourceScope.None )] //// [MethodImpl( MethodImplOptions.InternalCall )] //// internal extern RuntimeTypeHandle[] GetInstantiation(); //// //// [ResourceExposure( ResourceScope.None )] //// [MethodImpl( MethodImplOptions.InternalCall )] //// private extern void* _Instantiate( RuntimeTypeHandle[] inst ); //// internal RuntimeTypeHandle Instantiate( RuntimeTypeHandle[] inst ) //// { //// return new RuntimeTypeHandle( _Instantiate( inst ) ); //// } //// //// [ResourceExposure( ResourceScope.None )] //// [MethodImpl( MethodImplOptions.InternalCall )] //// private extern void* _MakeArray( int rank ); //// internal RuntimeTypeHandle MakeArray( int rank ) //// { //// return new RuntimeTypeHandle( _MakeArray( rank ) ); //// } //// //// [ResourceExposure( ResourceScope.None )] //// [MethodImpl( MethodImplOptions.InternalCall )] //// private extern void* _MakeSZArray(); //// internal RuntimeTypeHandle MakeSZArray() //// { //// return new RuntimeTypeHandle( _MakeSZArray() ); //// } //// //// [ResourceExposure( ResourceScope.None )] //// [MethodImpl( MethodImplOptions.InternalCall )] //// private extern void* _MakeByRef(); //// internal RuntimeTypeHandle MakeByRef() //// { //// return new RuntimeTypeHandle( _MakeByRef() ); //// } //// //// [ResourceExposure( ResourceScope.None )] //// [MethodImpl( MethodImplOptions.InternalCall )] //// private extern void* _MakePointer(); //// internal RuntimeTypeHandle MakePointer() //// { //// return new RuntimeTypeHandle( _MakePointer() ); //// } //// //// [ResourceExposure( ResourceScope.None )] //// [MethodImpl( MethodImplOptions.InternalCall )] //// internal extern bool HasInstantiation(); //// //// [ResourceExposure( ResourceScope.None )] //// [MethodImpl( MethodImplOptions.InternalCall )] //// private extern void* _GetGenericTypeDefinition(); //// internal RuntimeTypeHandle GetGenericTypeDefinition() //// { //// return new RuntimeTypeHandle( _GetGenericTypeDefinition() ); //// } //// //// [ResourceExposure( ResourceScope.None )] //// [MethodImpl( MethodImplOptions.InternalCall )] //// internal extern bool IsGenericTypeDefinition(); //// //// [ResourceExposure( ResourceScope.None )] //// [MethodImpl( MethodImplOptions.InternalCall )] //// internal extern bool IsGenericVariable(); //// //// [ResourceExposure( ResourceScope.None )] //// [MethodImpl( MethodImplOptions.InternalCall )] //// internal extern int GetGenericVariableIndex(); //// //// [ResourceExposure( ResourceScope.None )] //// [MethodImpl( MethodImplOptions.InternalCall )] //// internal extern bool ContainsGenericVariables(); //// //// [ResourceExposure( ResourceScope.None )] //// [MethodImpl( MethodImplOptions.InternalCall )] //// internal extern bool SatisfiesConstraints( RuntimeTypeHandle[] typeContext, RuntimeTypeHandle[] methodContext, RuntimeTypeHandle toType ); //// //// private RuntimeTypeHandle( SerializationInfo info, StreamingContext context ) //// { //// if(info == null) //// { //// throw new ArgumentNullException( "info" ); //// } //// //// Type m = (RuntimeType)info.GetValue( "TypeObj", typeof( RuntimeType ) ); //// //// m_ptr = m.TypeHandle.Value; //// //// if(m_ptr.ToPointer() == null) //// { //// throw new SerializationException( Environment.GetResourceString( "Serialization_InsufficientState" ) ); //// } //// } //// //// public void GetObjectData( SerializationInfo info, StreamingContext context ) //// { //// if(info == null) //// { //// throw new ArgumentNullException( "info" ); //// } //// //// if(m_ptr.ToPointer() == null) //// { //// throw new SerializationException( Environment.GetResourceString( "Serialization_InvalidFieldState" ) ); //// } //// //// RuntimeType type = (RuntimeType)Type.GetTypeFromHandle( this ); //// //// info.AddValue( "TypeObj", type, typeof( RuntimeType ) ); //// } } } ================================================ FILE: Zelig/Zelig/RunTime/Framework/mscorlib/System/SByte.cs ================================================ // ==++== // // Copyright (c) Microsoft Corporation. All rights reserved. // // ==--== /*============================================================ ** ** Class: SByte ** ** ** Purpose: ** ** ===========================================================*/ namespace System { using System; using System.Globalization; using System.Runtime.InteropServices; using System.Runtime.CompilerServices; // A place holder class for signed bytes. [Microsoft.Zelig.Internals.WellKnownType( "System_SByte" )] [Serializable] [CLSCompliant( false )] [StructLayout( LayoutKind.Sequential )] public struct SByte : IComparable, IFormattable, IConvertible, IComparable, IEquatable { public const sbyte MaxValue = (sbyte)0x7F ; // The maximum value that a Byte may represent: 127. public const sbyte MinValue = unchecked( (sbyte)0x80 ); // The minimum value that a Byte may represent: -128. internal sbyte m_value; // Compares this object to another object, returning an integer that // indicates the relationship. // Returns a value less than zero if this object // null is considered to be less than any instance. // If object is not of type SByte, this method throws an ArgumentException. // public int CompareTo( Object obj ) { if(obj == null) { return 1; } if(!(obj is SByte)) { #if EXCEPTION_STRINGS throw new ArgumentException( Environment.GetResourceString( "Arg_MustBeSByte" ) ); #else throw new ArgumentException(); #endif } return CompareTo( (SByte)obj ); } public int CompareTo( SByte value ) { return m_value - value; } // Determines whether two Byte objects are equal. public override bool Equals( Object obj ) { if(!(obj is SByte)) { return false; } return Equals( (SByte)obj ); } public bool Equals( SByte obj ) { return m_value == obj; } // Gets a hash code for this instance. public override int GetHashCode() { return ((int)m_value ^ (int)m_value << 8); } // Provides a string representation of a byte. public override String ToString() { return Number.FormatInt32( m_value, /*null,*/ NumberFormatInfo.CurrentInfo ); } public String ToString( IFormatProvider provider ) { return Number.FormatInt32( m_value, /*null,*/ NumberFormatInfo.GetInstance( provider ) ); } public String ToString( String format ) { return ToString( format, NumberFormatInfo.CurrentInfo ); } public String ToString( String format, IFormatProvider provider ) { return ToString( format, NumberFormatInfo.GetInstance( provider ) ); } private String ToString( String format, NumberFormatInfo info ) { if(m_value < 0 && format != null && format.Length > 0 && (format[0] == 'X' || format[0] == 'x')) { uint temp = (uint)(m_value & 0x000000FF); return Number.FormatUInt32( temp, format, info ); } return Number.FormatInt32( m_value, format, info ); } [CLSCompliant( false )] public static sbyte Parse( String s ) { return Parse( s, NumberStyles.Integer, NumberFormatInfo.CurrentInfo ); } [CLSCompliant( false )] public static sbyte Parse( String s , NumberStyles style ) { NumberFormatInfo.ValidateParseStyleInteger( style ); return Parse( s, style, NumberFormatInfo.CurrentInfo ); } [CLSCompliant( false )] public static sbyte Parse( String s , IFormatProvider provider ) { return Parse( s, NumberStyles.Integer, NumberFormatInfo.GetInstance( provider ) ); } // Parses a signed byte from a String in the given style. If // a NumberFormatInfo isn't specified, the current culture's // NumberFormatInfo is assumed. // [CLSCompliant( false )] public static sbyte Parse( String s , NumberStyles style , IFormatProvider provider ) { NumberFormatInfo.ValidateParseStyleInteger( style ); return Parse( s, style, NumberFormatInfo.GetInstance( provider ) ); } private static sbyte Parse( String s , NumberStyles style , NumberFormatInfo info ) { int i = 0; try { i = Number.ParseInt32( s, style, info ); } catch(OverflowException e) { #if EXCEPTION_STRINGS throw new OverflowException( Environment.GetResourceString( "Overflow_SByte" ), e ); #else throw new OverflowException( null, e ); #endif } if((style & NumberStyles.AllowHexSpecifier) != 0) { // We are parsing a hexadecimal number if((i < 0) || i > Byte.MaxValue) { #if EXCEPTION_STRINGS throw new OverflowException( Environment.GetResourceString( "Overflow_SByte" ) ); #else throw new OverflowException(); #endif } return (sbyte)i; } if(i < MinValue || i > MaxValue) { #if EXCEPTION_STRINGS throw new OverflowException( Environment.GetResourceString( "Overflow_SByte" ) ); #else throw new OverflowException(); #endif } return (sbyte)i; } [CLSCompliant( false )] public static bool TryParse( String s , out SByte result ) { return TryParse( s, NumberStyles.Integer, NumberFormatInfo.CurrentInfo, out result ); } [CLSCompliant( false )] public static bool TryParse( String s , NumberStyles style , IFormatProvider provider , out SByte result ) { NumberFormatInfo.ValidateParseStyleInteger( style ); return TryParse( s, style, NumberFormatInfo.GetInstance( provider ), out result ); } private static bool TryParse( String s , NumberStyles style , NumberFormatInfo info , out SByte result ) { result = 0; int i; if(!Number.TryParseInt32( s, style, info, out i )) { return false; } if((style & NumberStyles.AllowHexSpecifier) != 0) { // We are parsing a hexadecimal number if((i < 0) || i > Byte.MaxValue) { return false; } result = (sbyte)i; return true; } if(i < MinValue || i > MaxValue) { return false; } result = (sbyte)i; return true; } #region IConvertible public TypeCode GetTypeCode() { return TypeCode.SByte; } /// bool IConvertible.ToBoolean( IFormatProvider provider ) { return Convert.ToBoolean( m_value ); } /// char IConvertible.ToChar( IFormatProvider provider ) { return Convert.ToChar( m_value ); } /// sbyte IConvertible.ToSByte( IFormatProvider provider ) { return m_value; } /// byte IConvertible.ToByte( IFormatProvider provider ) { return Convert.ToByte( m_value ); } /// short IConvertible.ToInt16( IFormatProvider provider ) { return Convert.ToInt16( m_value ); } /// ushort IConvertible.ToUInt16( IFormatProvider provider ) { return Convert.ToUInt16( m_value ); } /// int IConvertible.ToInt32( IFormatProvider provider ) { return m_value; } /// uint IConvertible.ToUInt32( IFormatProvider provider ) { return Convert.ToUInt32( m_value ); } /// long IConvertible.ToInt64( IFormatProvider provider ) { return Convert.ToInt64( m_value ); } /// ulong IConvertible.ToUInt64( IFormatProvider provider ) { return Convert.ToUInt64( m_value ); } /// float IConvertible.ToSingle( IFormatProvider provider ) { return Convert.ToSingle( m_value ); } /// double IConvertible.ToDouble( IFormatProvider provider ) { return Convert.ToDouble( m_value ); } /// Decimal IConvertible.ToDecimal( IFormatProvider provider ) { return Convert.ToDecimal( m_value ); } /// DateTime IConvertible.ToDateTime( IFormatProvider provider ) { #if EXCEPTION_STRINGS throw new InvalidCastException( Environment.GetResourceString( "InvalidCast_FromTo", "SByte", "DateTime" ) ); #else throw new InvalidCastException(); #endif } /// Object IConvertible.ToType( Type type, IFormatProvider provider ) { return Convert.DefaultToType( (IConvertible)this, type, provider ); } #endregion } } ================================================ FILE: Zelig/Zelig/RunTime/Framework/mscorlib/System/Security/Attributes.cs ================================================ // ==++== // // Copyright (c) Microsoft Corporation. All rights reserved. // // ==--== namespace System.Security { using System.Runtime.InteropServices; ////// DynamicSecurityMethodAttribute: ////// Indicates that calling the target method requires space for a security ////// object to be allocated on the callers stack. This attribute is only ever ////// set on certain security methods defined within mscorlib. ////[AttributeUsage( AttributeTargets.Method, AllowMultiple = true, Inherited = false )] ////sealed internal class DynamicSecurityMethodAttribute : System.Attribute ////{ ////} //// ////// SuppressUnmanagedCodeSecurityAttribute: ////// Indicates that the target P/Invoke method(s) should skip the per-call ////// security checked for unmanaged code permission. ////[AttributeUsage( AttributeTargets.Method | AttributeTargets.Class | AttributeTargets.Interface | AttributeTargets.Delegate, AllowMultiple = true, Inherited = false )] ////sealed public class SuppressUnmanagedCodeSecurityAttribute : System.Attribute ////{ ////} // UnverifiableCodeAttribute: // Indicates that the target module contains unverifiable code. [AttributeUsage( AttributeTargets.Module, AllowMultiple = true, Inherited = false )] sealed public class UnverifiableCodeAttribute : System.Attribute { } ////// AllowPartiallyTrustedCallersAttribute: ////// Indicates that the Assembly is secure and can be used by untrusted ////// and semitrusted clients ////// For v.1, this is valid only on Assemblies, but could be expanded to ////// include Module, Method, class ////[AttributeUsage( AttributeTargets.Assembly, AllowMultiple = false, Inherited = false )] ////sealed public class AllowPartiallyTrustedCallersAttribute : System.Attribute ////{ //// public AllowPartiallyTrustedCallersAttribute() { } ////} public enum SecurityCriticalScope { Explicit = 0, Everything = 0x1 } // SecurityCriticalAttribute // Indicates that the decorated code or assembly performs security critical operations (e.g. Assert, "unsafe", LinkDemand, etc.) // The attribute can be placed on most targets, except on arguments/return values. // The attribute applies only to the specific target and not to everything underneath it (similar to 'public' qualifier) // i.e. marking an assembly SecurityCritical doesn't imply all types within the assembly are critical, // and similarly marking a type critical doesn't imply all of its members are critical // For code to perform security critical actions, both the code (e.g. method, field, etc.) and the assembly must be decorated // with the SecurityCriticalAttribute. [AttributeUsage( AttributeTargets.Assembly | AttributeTargets.Module | AttributeTargets.Class | AttributeTargets.Struct | AttributeTargets.Enum | AttributeTargets.Constructor | AttributeTargets.Method | AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Event | AttributeTargets.Interface | AttributeTargets.Delegate, AllowMultiple = false, Inherited = false )] sealed public class SecurityCriticalAttribute : System.Attribute { internal SecurityCriticalScope _val; public SecurityCriticalAttribute() { } public SecurityCriticalAttribute( SecurityCriticalScope scope ) { _val = scope; } public SecurityCriticalScope Scope { get { return _val; } } } ////// SecurityTreatAsSafeAttribute: ////// Indicates that the code may contain violations to the security critical rules (e.g. transitions from ////// critical to non-public transparent, transparent to non-public critical, etc.), has been audited for ////// security concerns and is considered security clean. ////// At assembly-scope, all rule checks will be suppressed within the assembly and for calls made against the assembly. ////// At type-scope, all rule checks will be suppressed for members within the type and for calls made against the type. ////// At member level (e.g. field and method) the code will be treated as public - i.e. no rule checks for the members. //// ////[AttributeUsage( AttributeTargets.All, //// AllowMultiple = false, //// Inherited = false )] ////sealed public class SecurityTreatAsSafeAttribute : System.Attribute ////{ //// public SecurityTreatAsSafeAttribute() { } ////} // SecuritySafeCriticalAttribute: // Indicates that the code may contain violations to the security critical rules (e.g. transitions from // critical to non-public transparent, transparent to non-public critical, etc.), has been audited for // security concerns and is considered security clean. Also indicates that the code is considered SecurityCritical. // The effect of this attribute is as if the code was marked [SecurityCritical][SecurityTreatAsSafe]. // At assembly-scope, all rule checks will be suppressed within the assembly and for calls made against the assembly. // At type-scope, all rule checks will be suppressed for members within the type and for calls made against the type. // At member level (e.g. field and method) the code will be treated as public - i.e. no rule checks for the members. [AttributeUsage(AttributeTargets.Class | AttributeTargets.Struct | AttributeTargets.Enum | AttributeTargets.Constructor | AttributeTargets.Method | AttributeTargets.Field | AttributeTargets.Interface | AttributeTargets.Delegate, AllowMultiple = false, Inherited = false )] sealed public class SecuritySafeCriticalAttribute : System.Attribute { public SecuritySafeCriticalAttribute () { } } ////// SecurityTransparentAttribute: ////// Indicates the assembly contains only transparent code. ////// Security critical actions will be restricted or converted into less critical actions. For example, ////// Assert will be restricted, SuppressUnmanagedCode, LinkDemand, unsafe, and unverifiable code will be converted ////// into Full-Demands. //// ////[AttributeUsage( AttributeTargets.Assembly, //// AllowMultiple = false, //// Inherited = false )] ////sealed public class SecurityTransparentAttribute : System.Attribute ////{ //// public SecurityTransparentAttribute() { } ////} } ================================================ FILE: Zelig/Zelig/RunTime/Framework/mscorlib/System/Security/Cryptography/X509Certificates/X509Certificate.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // namespace System.Security.Cryptography.X509Certificates { using System; using System.Runtime.CompilerServices; public class X509Certificate { private byte[] m_certificate; private string m_password; protected string m_issuer; protected string m_subject; protected DateTime m_effectiveDate; protected DateTime m_expirationDate; protected byte[] m_handle; protected byte[] m_sessionHandle; //--// public X509Certificate() { } public X509Certificate(byte[] certificate) : this(certificate, "") { } public X509Certificate(byte[] certificate, string password) { m_certificate = certificate; m_password = password; ParseCertificate(certificate, password, ref m_issuer, ref m_subject, ref m_effectiveDate, ref m_expirationDate); } public virtual string Issuer { get { return m_issuer; } } public virtual string Subject { get { return m_subject; } } public virtual DateTime GetEffectiveDate() { return m_effectiveDate; } public virtual DateTime GetExpirationDate() { return m_expirationDate; } public virtual byte[] GetRawCertData() { return m_certificate; } internal static void ParseCertificate( byte[] cert, string password, ref string issuer, ref string subject, ref DateTime effectiveDate, ref DateTime expirationDate) { throw new NotImplementedException( ); } } } ================================================ FILE: Zelig/Zelig/RunTime/Framework/mscorlib/System/Security/Permissions/HostProtectionPermission.cs ================================================ // Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. namespace System.Security.Permissions { using System; using System.IO; ////using System.Security.Util; using System.Text; using System.Threading; ////using System.Runtime.Remoting; using System.Security; using System.Runtime.Serialization; using System.Reflection; using System.Globalization; using System.Diagnostics.Contracts; // Keep this enum in sync with tools\ngen\ngen.cpp and inc\mscoree.idl [Serializable] [Flags] [System.Runtime.InteropServices.ComVisible(true)] public enum HostProtectionResource { None = 0x0, //-------------------------------- Synchronization = 0x1, SharedState = 0x2, ExternalProcessMgmt = 0x4, SelfAffectingProcessMgmt = 0x8, ExternalThreading = 0x10, SelfAffectingThreading = 0x20, SecurityInfrastructure = 0x40, UI = 0x80, MayLeakOnAbort = 0x100, //--------------------------------- All = 0x1ff, } [AttributeUsage(AttributeTargets.Method | AttributeTargets.Constructor | AttributeTargets.Class | AttributeTargets.Struct | AttributeTargets.Assembly | AttributeTargets.Delegate, AllowMultiple = true, Inherited = false)] [System.Runtime.InteropServices.ComVisible(true)] [Serializable] #if FEATURE_CORECLR // This needs to be in the asmmeta to enable SecAnnotate to successfully resolve and run the security rules. It gets marked // as internal by BCLRewriter so we are simply marking it as FriendAccessAllowed so it stays in the asmmeta. [System.Runtime.CompilerServices.FriendAccessAllowedAttribute] #endif // FEATURE_CORECLR #pragma warning disable 618 sealed public class HostProtectionAttribute : CodeAccessSecurityAttribute #pragma warning restore 618 { private HostProtectionResource m_resources = HostProtectionResource.None; public HostProtectionAttribute() #pragma warning disable 618 : base(SecurityAction.LinkDemand) #pragma warning restore 618 { } #pragma warning disable 618 public HostProtectionAttribute(SecurityAction action) #pragma warning restore 618 : base(action) { #pragma warning disable 618 if (action != SecurityAction.LinkDemand) #pragma warning restore 618 throw new ArgumentException(Environment.GetResourceString("Argument_InvalidFlag")); #if ENABLE_CONTRACTS Contract.EndContractBlock(); #endif // ENABLE_CONTRACTS } public HostProtectionResource Resources { get { return m_resources; } set { m_resources = value; } } public bool Synchronization { get { return (m_resources & HostProtectionResource.Synchronization) != 0; } set { m_resources = (value ? m_resources | HostProtectionResource.Synchronization : m_resources & ~HostProtectionResource.Synchronization); } } public bool SharedState { get { return (m_resources & HostProtectionResource.SharedState) != 0; } set { m_resources = (value ? m_resources | HostProtectionResource.SharedState : m_resources & ~HostProtectionResource.SharedState); } } public bool ExternalProcessMgmt { get { return (m_resources & HostProtectionResource.ExternalProcessMgmt) != 0; } set { m_resources = (value ? m_resources | HostProtectionResource.ExternalProcessMgmt : m_resources & ~HostProtectionResource.ExternalProcessMgmt); } } public bool SelfAffectingProcessMgmt { get { return (m_resources & HostProtectionResource.SelfAffectingProcessMgmt) != 0; } set { m_resources = (value ? m_resources | HostProtectionResource.SelfAffectingProcessMgmt : m_resources & ~HostProtectionResource.SelfAffectingProcessMgmt); } } public bool ExternalThreading { get { return (m_resources & HostProtectionResource.ExternalThreading) != 0; } set { m_resources = (value ? m_resources | HostProtectionResource.ExternalThreading : m_resources & ~HostProtectionResource.ExternalThreading); } } public bool SelfAffectingThreading { get { return (m_resources & HostProtectionResource.SelfAffectingThreading) != 0; } set { m_resources = (value ? m_resources | HostProtectionResource.SelfAffectingThreading : m_resources & ~HostProtectionResource.SelfAffectingThreading); } } [System.Runtime.InteropServices.ComVisible(true)] public bool SecurityInfrastructure { get { return (m_resources & HostProtectionResource.SecurityInfrastructure) != 0; } set { m_resources = (value ? m_resources | HostProtectionResource.SecurityInfrastructure : m_resources & ~HostProtectionResource.SecurityInfrastructure); } } public bool UI { get { return (m_resources & HostProtectionResource.UI) != 0; } set { m_resources = (value ? m_resources | HostProtectionResource.UI : m_resources & ~HostProtectionResource.UI); } } public bool MayLeakOnAbort { get { return (m_resources & HostProtectionResource.MayLeakOnAbort) != 0; } set { m_resources = (value ? m_resources | HostProtectionResource.MayLeakOnAbort : m_resources & ~HostProtectionResource.MayLeakOnAbort); } } #if DISABLED_FOR_LLILUM public override IPermission CreatePermission() { if (m_unrestricted) { return new HostProtectionPermission(PermissionState.Unrestricted); } else { return new HostProtectionPermission(m_resources); } } #endif // DISABLED_FOR_LLILUM } #if DISABLED_FOR_LLILUM [Serializable] sealed internal class HostProtectionPermission : CodeAccessPermission, IUnrestrictedPermission, IBuiltInPermission { //------------------------------------------------------ // // GLOBALS // //------------------------------------------------------ // This value is set by PermissionSet.FilterHostProtectionPermissions. It is only used for // constructing a HostProtectionException object. Changing it will not affect HostProtection. internal static volatile HostProtectionResource protectedResources = HostProtectionResource.None; //------------------------------------------------------ // // MEMBERS // //------------------------------------------------------ private HostProtectionResource m_resources; //------------------------------------------------------ // // CONSTRUCTORS // //------------------------------------------------------ public HostProtectionPermission(PermissionState state) { if (state == PermissionState.Unrestricted) Resources = HostProtectionResource.All; else if (state == PermissionState.None) Resources = HostProtectionResource.None; else throw new ArgumentException(Environment.GetResourceString("Argument_InvalidPermissionState")); } public HostProtectionPermission(HostProtectionResource resources) { Resources = resources; } //------------------------------------------------------ // // IPermission interface implementation // //------------------------------------------------------ public bool IsUnrestricted() { return Resources == HostProtectionResource.All; } //------------------------------------------------------ // // Properties // //------------------------------------------------------ public HostProtectionResource Resources { set { if (value < HostProtectionResource.None || value > HostProtectionResource.All) throw new ArgumentException(Environment.GetResourceString("Arg_EnumIllegalVal", (int)value)); Contract.EndContractBlock(); m_resources = value; } get { return m_resources; } } //------------------------------------------------------ // // IPermission interface implementation // //------------------------------------------------------ public override bool IsSubsetOf(IPermission target) { if (target == null) return m_resources == HostProtectionResource.None; if (this.GetType() != target.GetType()) throw new ArgumentException(Environment.GetResourceString("Argument_WrongType", this.GetType().FullName)); return ((uint)this.m_resources & (uint)((HostProtectionPermission)target).m_resources) == (uint)this.m_resources; } public override IPermission Union(IPermission target) { if (target == null) return (this.Copy()); if (this.GetType() != target.GetType()) throw new ArgumentException(Environment.GetResourceString("Argument_WrongType", this.GetType().FullName)); HostProtectionResource newResources = (HostProtectionResource)((uint)this.m_resources | (uint)((HostProtectionPermission)target).m_resources); return new HostProtectionPermission(newResources); } public override IPermission Intersect(IPermission target) { if (target == null) return null; if (this.GetType() != target.GetType()) throw new ArgumentException(Environment.GetResourceString("Argument_WrongType", this.GetType().FullName)); HostProtectionResource newResources = (HostProtectionResource)((uint)this.m_resources & (uint)((HostProtectionPermission)target).m_resources); if (newResources == HostProtectionResource.None) return null; return new HostProtectionPermission(newResources); } public override IPermission Copy() { return new HostProtectionPermission(m_resources); } #if FEATURE_CAS_POLICY //------------------------------------------------------ // // XML // //------------------------------------------------------ public override SecurityElement ToXml() { SecurityElement esd = CodeAccessPermission.CreatePermissionElement( this, this.GetType().FullName ); if(IsUnrestricted()) esd.AddAttribute( "Unrestricted", "true" ); else esd.AddAttribute( "Resources", XMLUtil.BitFieldEnumToString( typeof( HostProtectionResource ), Resources ) ); return esd; } public override void FromXml(SecurityElement esd) { CodeAccessPermission.ValidateElement( esd, this ); if (XMLUtil.IsUnrestricted( esd )) Resources = HostProtectionResource.All; else { String resources = esd.Attribute( "Resources" ); if (resources == null) Resources = HostProtectionResource.None; else Resources = (HostProtectionResource)Enum.Parse( typeof( HostProtectionResource ), resources ); } } #endif // FEATURE_CAS_POLICY //------------------------------------------------------ // // OBJECT OVERRIDES // //------------------------------------------------------ /// int IBuiltInPermission.GetTokenIndex() { return HostProtectionPermission.GetTokenIndex(); } internal static int GetTokenIndex() { return BuiltInPermissionIndex.HostProtectionPermissionIndex; } } #endif // DISABLED_FOR_LLILUM } ================================================ FILE: Zelig/Zelig/RunTime/Framework/mscorlib/System/Security/Permissions/PermissionAttributes.cs ================================================ // ==++== // // Copyright (c) Microsoft Corporation. All rights reserved. // // ==--== namespace System.Security.Permissions { ////using System.Security.Util; ////using System.IO; ////using System.Security.Policy; ////using System.Security.AccessControl; ////using System.Runtime.Remoting.Activation; ////using System.Text; ////using System.Runtime.Serialization.Formatters; ////using System.Threading; ////using System.Runtime.InteropServices; ////using System.Runtime.Remoting; ////using System.Runtime.Serialization; ////using System.Security.Cryptography.X509Certificates; ////using System.Runtime.Versioning; [Serializable] public enum SecurityAction { Demand = 2, // Demand permission of all caller Assert = 3, // Assert permission so callers don't need Deny = 4, // Deny permissions so checks will fail PermitOnly = 5, // Reduce permissions so check will fail LinkDemand = 6, // Demand permission of caller InheritanceDemand = 7, // Demand permission of a subclass RequestMinimum = 8, // Request minimum permissions to run RequestOptional = 9, // Request optional additional permissions RequestRefuse = 10, // Refuse to be granted these permissions } [Serializable] [AttributeUsage( AttributeTargets.Method | AttributeTargets.Constructor | AttributeTargets.Class | AttributeTargets.Struct | AttributeTargets.Assembly, AllowMultiple = true, Inherited = false )] public abstract class SecurityAttribute : System.Attribute { /// internal SecurityAction m_action; /// internal bool m_unrestricted; protected SecurityAttribute( SecurityAction action ) { m_action = action; } public SecurityAction Action { get { return m_action; } set { m_action = value; } } public bool Unrestricted { get { return m_unrestricted; } set { m_unrestricted = value; } } //// abstract public IPermission CreatePermission(); //// //// internal static unsafe IntPtr FindSecurityAttributeTypeHandle( String typeName ) //// { //// PermissionSet.s_fullTrust.Assert(); //// Type t = Type.GetType( typeName, false, false ); //// if(t == null) //// return IntPtr.Zero; //// IntPtr typeHandle = t.TypeHandle.Value; //// return typeHandle; //// } } [Serializable] [AttributeUsage( AttributeTargets.Method | AttributeTargets.Constructor | AttributeTargets.Class | AttributeTargets.Struct | AttributeTargets.Assembly, AllowMultiple = true, Inherited = false )] public abstract class CodeAccessSecurityAttribute : SecurityAttribute { protected CodeAccessSecurityAttribute( SecurityAction action ) : base( action ) { } } [Serializable] [AttributeUsage( AttributeTargets.Method | AttributeTargets.Constructor | AttributeTargets.Class | AttributeTargets.Struct | AttributeTargets.Assembly, AllowMultiple = true, Inherited = false )] sealed public class EnvironmentPermissionAttribute : CodeAccessSecurityAttribute { private String m_read = null; private String m_write = null; public EnvironmentPermissionAttribute( SecurityAction action ) : base( action ) { } public String Read { get { return m_read; } set { m_read = value; } } public String Write { get { return m_write; } set { m_write = value; } } public String All { get { #if EXCEPTION_STRINGS throw new NotSupportedException( Environment.GetResourceString( "NotSupported_GetMethod" ) ); #else throw new NotSupportedException(); #endif } set { m_write = value; m_read = value; } } //// public override IPermission CreatePermission() //// { //// if(m_unrestricted) //// { //// return new EnvironmentPermission( PermissionState.Unrestricted ); //// } //// else //// { //// EnvironmentPermission perm = new EnvironmentPermission( PermissionState.None ); //// if(m_read != null) //// perm.SetPathList( EnvironmentPermissionAccess.Read, m_read ); //// if(m_write != null) //// perm.SetPathList( EnvironmentPermissionAccess.Write, m_write ); //// return perm; //// } //// } } ////[Serializable] ////[AttributeUsage( AttributeTargets.Method | AttributeTargets.Constructor | AttributeTargets.Class | AttributeTargets.Struct | AttributeTargets.Assembly, AllowMultiple = true, Inherited = false )] ////sealed public class FileDialogPermissionAttribute : CodeAccessSecurityAttribute ////{ //// private FileDialogPermissionAccess m_access; //// //// public FileDialogPermissionAttribute( SecurityAction action ) : base( action ) //// { //// } //// //// public bool Open //// { //// get { return (m_access & FileDialogPermissionAccess.Open) != 0; } //// set { m_access = value ? m_access | FileDialogPermissionAccess.Open : m_access & ~FileDialogPermissionAccess.Open; } //// } //// //// public bool Save //// { //// get { return (m_access & FileDialogPermissionAccess.Save) != 0; } //// set { m_access = value ? m_access | FileDialogPermissionAccess.Save : m_access & ~FileDialogPermissionAccess.Save; } //// } //// //// public override IPermission CreatePermission() //// { //// if(m_unrestricted) //// { //// return new FileDialogPermission( PermissionState.Unrestricted ); //// } //// else //// { //// return new FileDialogPermission( m_access ); //// } //// } ////} //// //// ////[Serializable] ////[AttributeUsage( AttributeTargets.Method | AttributeTargets.Constructor | AttributeTargets.Class | AttributeTargets.Struct | AttributeTargets.Assembly, AllowMultiple = true, Inherited = false )] ////sealed public class FileIOPermissionAttribute : CodeAccessSecurityAttribute ////{ //// private String m_read = null; //// private String m_write = null; //// private String m_append = null; //// private String m_pathDiscovery = null; //// private String m_viewAccess = null; //// private String m_changeAccess = null; //// //// [OptionalField( VersionAdded = 2 )] //// private FileIOPermissionAccess m_allLocalFiles = FileIOPermissionAccess.NoAccess; //// //// [OptionalField( VersionAdded = 2 )] //// private FileIOPermissionAccess m_allFiles = FileIOPermissionAccess.NoAccess; //// //// public FileIOPermissionAttribute( SecurityAction action ) : base( action ) //// { //// } //// //// public String Read //// { //// get { return m_read; } //// set { m_read = value; } //// } //// //// public String Write //// { //// get { return m_write; } //// set { m_write = value; } //// } //// //// public String Append //// { //// get { return m_append; } //// set { m_append = value; } //// } //// //// public String PathDiscovery //// { //// get { return m_pathDiscovery; } //// set { m_pathDiscovery = value; } //// } //// //// public String ViewAccessControl //// { //// get { return m_viewAccess; } //// set { m_viewAccess = value; } //// } //// //// public String ChangeAccessControl //// { //// get { return m_changeAccess; } //// set { m_changeAccess = value; } //// } //// //// [Obsolete( "Please use the ViewAndModify property instead." )] //// public String All //// { //// set { m_read = value; m_write = value; m_append = value; m_pathDiscovery = value; } //// get { throw new NotSupportedException( Environment.GetResourceString( "NotSupported_GetMethod" ) ); } //// } //// //// // Read, Write, Append, PathDiscovery, but no ACL-related permissions //// public String ViewAndModify //// { //// get { throw new NotSupportedException( Environment.GetResourceString( "NotSupported_GetMethod" ) ); } //// set { m_read = value; m_write = value; m_append = value; m_pathDiscovery = value; } //// } //// //// public FileIOPermissionAccess AllFiles //// { //// get { return m_allFiles; } //// set { m_allFiles = value; } //// } //// //// public FileIOPermissionAccess AllLocalFiles //// { //// get { return m_allLocalFiles; } //// set { m_allLocalFiles = value; } //// } //// //// public override IPermission CreatePermission() //// { //// if(m_unrestricted) //// { //// return new FileIOPermission( PermissionState.Unrestricted ); //// } //// else //// { //// FileIOPermission perm = new FileIOPermission( PermissionState.None ); //// if(m_read != null) //// perm.SetPathList( FileIOPermissionAccess.Read, m_read ); //// if(m_write != null) //// perm.SetPathList( FileIOPermissionAccess.Write, m_write ); //// if(m_append != null) //// perm.SetPathList( FileIOPermissionAccess.Append, m_append ); //// if(m_pathDiscovery != null) //// perm.SetPathList( FileIOPermissionAccess.PathDiscovery, m_pathDiscovery ); //// if(m_viewAccess != null) //// perm.SetPathList( FileIOPermissionAccess.NoAccess, AccessControlActions.View, new String[] { m_viewAccess }, false ); //// if(m_changeAccess != null) //// perm.SetPathList( FileIOPermissionAccess.NoAccess, AccessControlActions.Change, new String[] { m_changeAccess }, false ); //// //// perm.AllFiles = m_allFiles; //// perm.AllLocalFiles = m_allLocalFiles; //// return perm; //// } //// } ////} //// ////[Serializable] ////[AttributeUsage( AttributeTargets.Method | AttributeTargets.Constructor | AttributeTargets.Class | AttributeTargets.Struct | AttributeTargets.Assembly, AllowMultiple = true, Inherited = false )] ////public sealed class KeyContainerPermissionAttribute : CodeAccessSecurityAttribute ////{ //// KeyContainerPermissionFlags m_flags = KeyContainerPermissionFlags.NoFlags; //// private string m_keyStore; //// private string m_providerName; //// private int m_providerType = -1; //// private string m_keyContainerName; //// private int m_keySpec = -1; //// //// public KeyContainerPermissionAttribute( SecurityAction action ) : base( action ) //// { //// } //// //// public string KeyStore //// { //// get { return m_keyStore; } //// set { m_keyStore = value; } //// } //// //// public string ProviderName //// { //// get { return m_providerName; } //// set { m_providerName = value; } //// } //// //// public int ProviderType //// { //// get { return m_providerType; } //// set { m_providerType = value; } //// } //// //// public string KeyContainerName //// { //// get { return m_keyContainerName; } //// set { m_keyContainerName = value; } //// } //// //// public int KeySpec //// { //// get { return m_keySpec; } //// set { m_keySpec = value; } //// } //// //// public KeyContainerPermissionFlags Flags //// { //// get { return m_flags; } //// set { m_flags = value; } //// } //// //// public override IPermission CreatePermission() //// { //// if(m_unrestricted) //// { //// return new KeyContainerPermission( PermissionState.Unrestricted ); //// } //// else //// { //// if(KeyContainerPermissionAccessEntry.IsUnrestrictedEntry( m_keyStore, m_providerName, m_providerType, m_keyContainerName, m_keySpec )) //// return new KeyContainerPermission( m_flags ); //// //// // create a KeyContainerPermission with a single access entry. //// KeyContainerPermission cp = new KeyContainerPermission( KeyContainerPermissionFlags.NoFlags ); //// KeyContainerPermissionAccessEntry accessEntry = new KeyContainerPermissionAccessEntry( m_keyStore, m_providerName, m_providerType, m_keyContainerName, m_keySpec, m_flags ); //// cp.AccessEntries.Add( accessEntry ); //// return cp; //// } //// } ////} //// ////// PrincipalPermissionAttribute currently derives from ////// CodeAccessSecurityAttribute, even though it's not related to code access ////// security. This is because compilers are currently looking for ////// CodeAccessSecurityAttribute as a direct parent class rather than ////// SecurityAttribute as the root class. ////[Serializable] ////[AttributeUsage( AttributeTargets.Method | AttributeTargets.Class, AllowMultiple = true, Inherited = false )] ////sealed public class PrincipalPermissionAttribute : CodeAccessSecurityAttribute ////{ //// private String m_name = null; //// private String m_role = null; //// private bool m_authenticated = true; //// //// public PrincipalPermissionAttribute( SecurityAction action ) : base( action ) //// { //// } //// //// public String Name //// { //// get { return m_name; } //// set { m_name = value; } //// } //// //// public String Role //// { //// get { return m_role; } //// set { m_role = value; } //// } //// //// public bool Authenticated //// { //// get { return m_authenticated; } //// set { m_authenticated = value; } //// } //// //// //// public override IPermission CreatePermission() //// { //// if(m_unrestricted) //// { //// return new PrincipalPermission( PermissionState.Unrestricted ); //// } //// else //// { //// return new PrincipalPermission( m_name, m_role, m_authenticated ); //// } //// } ////} //// //// //// ////[Serializable] ////[AttributeUsage( AttributeTargets.Method | AttributeTargets.Constructor | AttributeTargets.Class | AttributeTargets.Struct | AttributeTargets.Assembly, AllowMultiple = true, Inherited = false )] ////sealed public class ReflectionPermissionAttribute : CodeAccessSecurityAttribute ////{ //// private ReflectionPermissionFlag m_flag = ReflectionPermissionFlag.NoFlags; //// //// public ReflectionPermissionAttribute( SecurityAction action ) : base( action ) //// { //// } //// //// public ReflectionPermissionFlag Flags //// { //// get { return m_flag; } //// set { m_flag = value; } //// } //// //// [Obsolete( "This API has been deprecated. http://go.microsoft.com/fwlink/?linkid=14202" )] //// public bool TypeInformation //// { //// #pragma warning disable 618 //// get { return (m_flag & ReflectionPermissionFlag.TypeInformation) != 0; } //// set { m_flag = value ? m_flag | ReflectionPermissionFlag.TypeInformation : m_flag & ~ReflectionPermissionFlag.TypeInformation; } //// #pragma warning restore 618 //// } //// //// public bool MemberAccess //// { //// get { return (m_flag & ReflectionPermissionFlag.MemberAccess) != 0; } //// set { m_flag = value ? m_flag | ReflectionPermissionFlag.MemberAccess : m_flag & ~ReflectionPermissionFlag.MemberAccess; } //// } //// //// public bool ReflectionEmit //// { //// get { return (m_flag & ReflectionPermissionFlag.ReflectionEmit) != 0; } //// set { m_flag = value ? m_flag | ReflectionPermissionFlag.ReflectionEmit : m_flag & ~ReflectionPermissionFlag.ReflectionEmit; } //// } //// //// public override IPermission CreatePermission() //// { //// if(m_unrestricted) //// { //// return new ReflectionPermission( PermissionState.Unrestricted ); //// } //// else //// { //// return new ReflectionPermission( m_flag ); //// } //// } ////} //// ////[Serializable] ////[AttributeUsage( AttributeTargets.Method | AttributeTargets.Constructor | AttributeTargets.Class | AttributeTargets.Struct | AttributeTargets.Assembly, AllowMultiple = true, Inherited = false )] ////sealed public class RegistryPermissionAttribute : CodeAccessSecurityAttribute ////{ //// private String m_read = null; //// private String m_write = null; //// private String m_create = null; //// private String m_viewAcl = null; //// private String m_changeAcl = null; //// //// public RegistryPermissionAttribute( SecurityAction action ) : base( action ) //// { //// } //// //// public String Read //// { //// get { return m_read; } //// set { m_read = value; } //// } //// //// public String Write //// { //// get { return m_write; } //// set { m_write = value; } //// } //// //// public String Create //// { //// get { return m_create; } //// set { m_create = value; } //// } //// //// public String ViewAccessControl //// { //// get { return m_viewAcl; } //// set { m_viewAcl = value; } //// } //// //// public String ChangeAccessControl //// { //// get { return m_changeAcl; } //// set { m_changeAcl = value; } //// } //// //// // Read, Write, & Create, but no ACL's //// public String ViewAndModify //// { //// get { throw new NotSupportedException( Environment.GetResourceString( "NotSupported_GetMethod" ) ); } //// set { m_read = value; m_write = value; m_create = value; } //// } //// //// [Obsolete( "Please use the ViewAndModify property instead." )] //// public String All //// { //// get { throw new NotSupportedException( Environment.GetResourceString( "NotSupported_GetMethod" ) ); } //// set { m_read = value; m_write = value; m_create = value; } //// } //// //// public override IPermission CreatePermission() //// { //// if(m_unrestricted) //// { //// return new RegistryPermission( PermissionState.Unrestricted ); //// } //// else //// { //// RegistryPermission perm = new RegistryPermission( PermissionState.None ); //// if(m_read != null) //// perm.SetPathList( RegistryPermissionAccess.Read, m_read ); //// if(m_write != null) //// perm.SetPathList( RegistryPermissionAccess.Write, m_write ); //// if(m_create != null) //// perm.SetPathList( RegistryPermissionAccess.Create, m_create ); //// if(m_viewAcl != null) //// perm.SetPathList( AccessControlActions.View, m_viewAcl ); //// if(m_changeAcl != null) //// perm.SetPathList( AccessControlActions.Change, m_changeAcl ); //// //// return perm; //// } //// } ////} [Serializable] [AttributeUsage( AttributeTargets.Method | AttributeTargets.Constructor | AttributeTargets.Class | AttributeTargets.Struct | AttributeTargets.Assembly, AllowMultiple = true, Inherited = false )] sealed public class SecurityPermissionAttribute : CodeAccessSecurityAttribute { private SecurityPermissionFlag m_flag = SecurityPermissionFlag.NoFlags; public SecurityPermissionAttribute( SecurityAction action ) : base( action ) { } public SecurityPermissionFlag Flags { get { return m_flag; } set { m_flag = value; } } public bool Assertion { get { return (m_flag & SecurityPermissionFlag.Assertion) != 0; } set { m_flag = value ? m_flag | SecurityPermissionFlag.Assertion : m_flag & ~SecurityPermissionFlag.Assertion; } } public bool UnmanagedCode { get { return (m_flag & SecurityPermissionFlag.UnmanagedCode) != 0; } set { m_flag = value ? m_flag | SecurityPermissionFlag.UnmanagedCode : m_flag & ~SecurityPermissionFlag.UnmanagedCode; } } public bool SkipVerification { get { return (m_flag & SecurityPermissionFlag.SkipVerification) != 0; } set { m_flag = value ? m_flag | SecurityPermissionFlag.SkipVerification : m_flag & ~SecurityPermissionFlag.SkipVerification; } } public bool Execution { get { return (m_flag & SecurityPermissionFlag.Execution) != 0; } set { m_flag = value ? m_flag | SecurityPermissionFlag.Execution : m_flag & ~SecurityPermissionFlag.Execution; } } public bool ControlThread { get { return (m_flag & SecurityPermissionFlag.ControlThread) != 0; } set { m_flag = value ? m_flag | SecurityPermissionFlag.ControlThread : m_flag & ~SecurityPermissionFlag.ControlThread; } } public bool ControlEvidence { get { return (m_flag & SecurityPermissionFlag.ControlEvidence) != 0; } set { m_flag = value ? m_flag | SecurityPermissionFlag.ControlEvidence : m_flag & ~SecurityPermissionFlag.ControlEvidence; } } public bool ControlPolicy { get { return (m_flag & SecurityPermissionFlag.ControlPolicy) != 0; } set { m_flag = value ? m_flag | SecurityPermissionFlag.ControlPolicy : m_flag & ~SecurityPermissionFlag.ControlPolicy; } } public bool SerializationFormatter { get { return (m_flag & SecurityPermissionFlag.SerializationFormatter) != 0; } set { m_flag = value ? m_flag | SecurityPermissionFlag.SerializationFormatter : m_flag & ~SecurityPermissionFlag.SerializationFormatter; } } public bool ControlDomainPolicy { get { return (m_flag & SecurityPermissionFlag.ControlDomainPolicy) != 0; } set { m_flag = value ? m_flag | SecurityPermissionFlag.ControlDomainPolicy : m_flag & ~SecurityPermissionFlag.ControlDomainPolicy; } } public bool ControlPrincipal { get { return (m_flag & SecurityPermissionFlag.ControlPrincipal) != 0; } set { m_flag = value ? m_flag | SecurityPermissionFlag.ControlPrincipal : m_flag & ~SecurityPermissionFlag.ControlPrincipal; } } public bool ControlAppDomain { get { return (m_flag & SecurityPermissionFlag.ControlAppDomain) != 0; } set { m_flag = value ? m_flag | SecurityPermissionFlag.ControlAppDomain : m_flag & ~SecurityPermissionFlag.ControlAppDomain; } } public bool RemotingConfiguration { get { return (m_flag & SecurityPermissionFlag.RemotingConfiguration) != 0; } set { m_flag = value ? m_flag | SecurityPermissionFlag.RemotingConfiguration : m_flag & ~SecurityPermissionFlag.RemotingConfiguration; } } public bool Infrastructure { get { return (m_flag & SecurityPermissionFlag.Infrastructure) != 0; } set { m_flag = value ? m_flag | SecurityPermissionFlag.Infrastructure : m_flag & ~SecurityPermissionFlag.Infrastructure; } } public bool BindingRedirects { get { return (m_flag & SecurityPermissionFlag.BindingRedirects) != 0; } set { m_flag = value ? m_flag | SecurityPermissionFlag.BindingRedirects : m_flag & ~SecurityPermissionFlag.BindingRedirects; } } //// public override IPermission CreatePermission() //// { //// if(m_unrestricted) //// { //// return new SecurityPermission( PermissionState.Unrestricted ); //// } //// else //// { //// return new SecurityPermission( m_flag ); //// } //// } } ////[Serializable] ////[AttributeUsage( AttributeTargets.Method | AttributeTargets.Constructor | AttributeTargets.Class | AttributeTargets.Struct | AttributeTargets.Assembly, AllowMultiple = true, Inherited = false )] ////sealed public class UIPermissionAttribute : CodeAccessSecurityAttribute ////{ //// private UIPermissionWindow m_windowFlag = UIPermissionWindow.NoWindows; //// private UIPermissionClipboard m_clipboardFlag = UIPermissionClipboard.NoClipboard; //// //// public UIPermissionAttribute( SecurityAction action ) : base( action ) //// { //// } //// //// public UIPermissionWindow Window //// { //// get { return m_windowFlag; } //// set { m_windowFlag = value; } //// } //// //// public UIPermissionClipboard Clipboard //// { //// get { return m_clipboardFlag; } //// set { m_clipboardFlag = value; } //// } //// //// public override IPermission CreatePermission() //// { //// if(m_unrestricted) //// { //// return new UIPermission( PermissionState.Unrestricted ); //// } //// else //// { //// return new UIPermission( m_windowFlag, m_clipboardFlag ); //// } //// } ////} //// ////[Serializable] ////[AttributeUsage( AttributeTargets.Method | AttributeTargets.Constructor | AttributeTargets.Class | AttributeTargets.Struct | AttributeTargets.Assembly, AllowMultiple = true, Inherited = false )] ////sealed public class ZoneIdentityPermissionAttribute : CodeAccessSecurityAttribute ////{ //// private SecurityZone m_flag = SecurityZone.NoZone; //// //// public ZoneIdentityPermissionAttribute( SecurityAction action ) : base( action ) //// { //// } //// //// public SecurityZone Zone //// { //// get { return m_flag; } //// set { m_flag = value; } //// } //// //// public override IPermission CreatePermission() //// { //// if(m_unrestricted) //// { //// return new ZoneIdentityPermission( PermissionState.Unrestricted ); //// } //// else //// { //// return new ZoneIdentityPermission( m_flag ); //// } //// } ////} //// ////[Serializable] ////[AttributeUsage( AttributeTargets.Method | AttributeTargets.Constructor | AttributeTargets.Class | AttributeTargets.Struct | AttributeTargets.Assembly, AllowMultiple = true, Inherited = false )] ////sealed public class StrongNameIdentityPermissionAttribute : CodeAccessSecurityAttribute ////{ //// private String m_name = null; //// private String m_version = null; //// private String m_blob = null; //// //// public StrongNameIdentityPermissionAttribute( SecurityAction action ) : base( action ) //// { //// } //// //// public String Name //// { //// get { return m_name; } //// set { m_name = value; } //// } //// //// public String Version //// { //// get { return m_version; } //// set { m_version = value; } //// } //// //// public String PublicKey //// { //// get { return m_blob; } //// set { m_blob = value; } //// } //// //// public override IPermission CreatePermission() //// { //// if(m_unrestricted) //// { //// return new StrongNameIdentityPermission( PermissionState.Unrestricted ); //// } //// else //// { //// if(m_blob == null && m_name == null && m_version == null) //// return new StrongNameIdentityPermission( PermissionState.None ); //// //// if(m_blob == null) //// throw new ArgumentException( Environment.GetResourceString( "ArgumentNull_Key" ) ); //// //// StrongNamePublicKeyBlob blob = new StrongNamePublicKeyBlob( m_blob ); //// //// if(m_version == null || m_version.Equals( String.Empty )) //// return new StrongNameIdentityPermission( blob, m_name, null ); //// else //// return new StrongNameIdentityPermission( blob, m_name, new Version( m_version ) ); //// } //// } ////} //// //// ////[Serializable] ////[AttributeUsage( AttributeTargets.Method | AttributeTargets.Constructor | AttributeTargets.Class | AttributeTargets.Struct | AttributeTargets.Assembly, AllowMultiple = true, Inherited = false )] ////sealed public class SiteIdentityPermissionAttribute : CodeAccessSecurityAttribute ////{ //// private String m_site = null; //// //// public SiteIdentityPermissionAttribute( SecurityAction action ) : base( action ) //// { //// } //// //// public String Site //// { //// get { return m_site; } //// set { m_site = value; } //// } //// //// public override IPermission CreatePermission() //// { //// if(m_unrestricted) //// { //// return new SiteIdentityPermission( PermissionState.Unrestricted ); //// } //// else //// { //// if(m_site == null) //// return new SiteIdentityPermission( PermissionState.None ); //// //// return new SiteIdentityPermission( m_site ); //// } //// } ////} //// ////[Serializable] ////[AttributeUsage( AttributeTargets.Method | AttributeTargets.Constructor | AttributeTargets.Class | AttributeTargets.Struct | AttributeTargets.Assembly, AllowMultiple = true, Inherited = false )] ////sealed public class UrlIdentityPermissionAttribute : CodeAccessSecurityAttribute ////{ //// private String m_url = null; //// //// public UrlIdentityPermissionAttribute( SecurityAction action ) : base( action ) //// { //// } //// //// public String Url //// { //// get { return m_url; } //// set { m_url = value; } //// } //// //// public override IPermission CreatePermission() //// { //// if(m_unrestricted) //// { //// return new UrlIdentityPermission( PermissionState.Unrestricted ); //// } //// else //// { //// if(m_url == null) //// return new UrlIdentityPermission( PermissionState.None ); //// //// return new UrlIdentityPermission( m_url ); //// } //// } ////} //// ////[Serializable] ////[AttributeUsage( AttributeTargets.Method | AttributeTargets.Constructor | AttributeTargets.Class | AttributeTargets.Struct | AttributeTargets.Assembly, AllowMultiple = true, Inherited = false )] ////sealed public class PublisherIdentityPermissionAttribute : CodeAccessSecurityAttribute ////{ //// private String m_x509cert = null; //// private String m_certFile = null; //// private String m_signedFile = null; //// //// public PublisherIdentityPermissionAttribute( SecurityAction action ) : base( action ) //// { //// m_x509cert = null; //// m_certFile = null; //// m_signedFile = null; //// } //// //// public String X509Certificate //// { //// get { return m_x509cert; } //// set { m_x509cert = value; } //// } //// //// public String CertFile //// { //// get { return m_certFile; } //// [ResourceExposure( ResourceScope.Machine )] //// [ResourceConsumption( ResourceScope.Machine )] //// set { m_certFile = value; } //// } //// //// public String SignedFile //// { //// get { return m_signedFile; } //// [ResourceExposure( ResourceScope.Machine )] //// [ResourceConsumption( ResourceScope.Machine )] //// set { m_signedFile = value; } //// } //// //// [ResourceExposure( ResourceScope.Machine )] //// [ResourceConsumption( ResourceScope.Machine )] //// public override IPermission CreatePermission() //// { //// if(m_unrestricted) //// { //// return new PublisherIdentityPermission( PermissionState.Unrestricted ); //// } //// else //// { //// if(m_x509cert != null) //// { //// return new PublisherIdentityPermission( new X509Certificate( System.Security.Util.Hex.DecodeHexString( m_x509cert ) ) ); //// } //// else if(m_certFile != null) //// { //// return new PublisherIdentityPermission( System.Security.Cryptography.X509Certificates.X509Certificate.CreateFromCertFile( m_certFile ) ); //// } //// else if(m_signedFile != null) //// { //// return new PublisherIdentityPermission( System.Security.Cryptography.X509Certificates.X509Certificate.CreateFromSignedFile( m_signedFile ) ); //// } //// else //// { //// return new PublisherIdentityPermission( PermissionState.None ); //// } //// } //// } ////} //// ////[Serializable] ////[AttributeUsage( AttributeTargets.Method | AttributeTargets.Constructor | AttributeTargets.Class | AttributeTargets.Struct | AttributeTargets.Assembly, AllowMultiple = true, Inherited = false )] ////public abstract class IsolatedStoragePermissionAttribute : CodeAccessSecurityAttribute ////{ //// /// //// internal long m_userQuota; //// /// //// internal IsolatedStorageContainment m_allowed; //// //// protected IsolatedStoragePermissionAttribute( SecurityAction action ) : base( action ) //// { //// } //// //// // properties //// public long UserQuota //// { //// set //// { //// m_userQuota = value; //// } //// get //// { //// return m_userQuota; //// } //// } //// //// public IsolatedStorageContainment UsageAllowed //// { //// set //// { //// m_allowed = value; //// } //// get //// { //// return m_allowed; //// } //// } ////} //// ////[Serializable] ////[AttributeUsage( AttributeTargets.Method | AttributeTargets.Constructor | AttributeTargets.Class | AttributeTargets.Struct | AttributeTargets.Assembly, AllowMultiple = true, Inherited = false )] ////sealed public class IsolatedStorageFilePermissionAttribute : IsolatedStoragePermissionAttribute ////{ //// public IsolatedStorageFilePermissionAttribute( SecurityAction action ) : base( action ) //// { //// //// } //// public override IPermission CreatePermission() //// { //// IsolatedStorageFilePermission p; //// if(m_unrestricted) //// { //// p = new IsolatedStorageFilePermission //// ( PermissionState.Unrestricted ); //// } //// else //// { //// p = new IsolatedStorageFilePermission( PermissionState.None ); //// p.UserQuota = m_userQuota; //// p.UsageAllowed = m_allowed; //// } //// return p; //// } ////} //// ////[Serializable] ////[AttributeUsage( AttributeTargets.Method | AttributeTargets.Constructor | AttributeTargets.Class | AttributeTargets.Struct | AttributeTargets.Assembly, AllowMultiple = true, Inherited = false )] ////sealed public class PermissionSetAttribute : CodeAccessSecurityAttribute ////{ //// private String m_file; //// private String m_name; //// private bool m_unicode; //// private String m_xml; //// private String m_hex; //// //// public PermissionSetAttribute( SecurityAction action ) : base( action ) //// { //// m_unicode = false; //// } //// //// public String File //// { //// get { return m_file; } //// [ResourceExposure( ResourceScope.Machine )] //// [ResourceConsumption( ResourceScope.Machine )] //// set { m_file = value; } //// } //// //// public bool UnicodeEncoded //// { //// get { return m_unicode; } //// set { m_unicode = value; } //// } //// //// public String Name //// { //// get { return m_name; } //// set { m_name = value; } //// } //// //// public String XML //// { //// get { return m_xml; } //// set { m_xml = value; } //// } //// //// public String Hex //// { //// get { return m_hex; } //// set { m_hex = value; } //// } //// //// public override IPermission CreatePermission() //// { //// return null; //// } //// //// private PermissionSet BruteForceParseStream( Stream stream ) //// { //// Encoding[] encodings = new Encoding[] { Encoding.UTF8, Encoding.ASCII, Encoding.Unicode }; //// //// StreamReader reader = null; //// Exception exception = null; //// //// for(int i = 0; reader == null && i < encodings.Length; ++i) //// { //// try //// { //// stream.Position = 0; //// reader = new StreamReader( stream, encodings[i] ); //// //// return ParsePermissionSet( new Parser( reader ) ); //// } //// catch(Exception e1) //// { //// if(exception == null) //// exception = e1; //// } //// } //// //// throw exception; //// } //// //// private PermissionSet ParsePermissionSet( Parser parser ) //// { //// SecurityElement e = parser.GetTopElement(); //// PermissionSet permSet = new PermissionSet( PermissionState.None ); //// permSet.FromXml( e ); //// //// return permSet; //// } //// //// [ResourceExposure( ResourceScope.Machine )] //// [ResourceConsumption( ResourceScope.Machine )] //// public PermissionSet CreatePermissionSet() //// { //// if(m_unrestricted) //// return new PermissionSet( PermissionState.Unrestricted ); //// else if(m_name != null) //// return PolicyLevel.GetBuiltInSet( m_name ); //// else if(m_xml != null) //// return ParsePermissionSet( new Parser( m_xml.ToCharArray() ) ); //// else if(m_hex != null) //// return BruteForceParseStream( new MemoryStream( Util.Hex.DecodeHexString( m_hex ) ) ); //// else if(m_file != null) //// return BruteForceParseStream( new FileStream( m_file, FileMode.Open, FileAccess.Read ) ); //// else //// return new PermissionSet( PermissionState.None ); //// } ////} } ================================================ FILE: Zelig/Zelig/RunTime/Framework/mscorlib/System/Security/Permissions/PermissionState.cs ================================================ // Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. // // The Runtime policy manager. Maintains a set of IdentityMapper objects that map // inbound evidence to groups. Resolves an identity into a set of permissions // namespace System.Security.Permissions { using System; [Serializable] [System.Runtime.InteropServices.ComVisible(true)] public enum PermissionState { Unrestricted = 1, None = 0, } } ================================================ FILE: Zelig/Zelig/RunTime/Framework/mscorlib/System/Security/Permissions/SecurityPermission.cs ================================================ // ==++== // // Copyright (c) Microsoft Corporation. All rights reserved. // // ==--== // SecurityPermission.cs // namespace System.Security.Permissions { ////using System; ////using System.IO; ////using System.Security.Util; ////using System.Text; ////using System.Threading; ////using System.Runtime.Remoting; ////using System.Security; ////using System.Runtime.Serialization; ////using System.Reflection; ////using System.Globalization; [Flags] [Serializable] public enum SecurityPermissionFlag { NoFlags = 0x00, /* The following enum value is used in the EE (ASSERT_PERMISSION in security.cpp) * Should this value change, make corresponding changes there */ Assertion = 0x01, UnmanagedCode = 0x02, // Update vm\Security.h if you change this ! SkipVerification = 0x04, // Update vm\Security.h if you change this ! Execution = 0x08, ControlThread = 0x10, ControlEvidence = 0x20, ControlPolicy = 0x40, SerializationFormatter = 0x80, ControlDomainPolicy = 0x100, ControlPrincipal = 0x200, ControlAppDomain = 0x400, RemotingConfiguration = 0x800, Infrastructure = 0x1000, BindingRedirects = 0x2000, AllFlags = 0x3FFF, } ////[Serializable] ////sealed public class SecurityPermission : CodeAccessPermission, IUnrestrictedPermission, IBuiltInPermission ////{ //// private SecurityPermissionFlag m_flags; //// //// // //// // Public Constructors //// // //// //// public SecurityPermission( PermissionState state ) //// { //// if(state == PermissionState.Unrestricted) //// { //// SetUnrestricted( true ); //// } //// else if(state == PermissionState.None) //// { //// SetUnrestricted( false ); //// Reset(); //// } //// else //// { //// throw new ArgumentException( Environment.GetResourceString( "Argument_InvalidPermissionState" ) ); //// } //// } //// //// //// // SecurityPermission //// // //// public SecurityPermission( SecurityPermissionFlag flag ) //// { //// VerifyAccess( flag ); //// //// SetUnrestricted( false ); //// m_flags = flag; //// } //// //// //// //------------------------------------------------------ //// // //// // PRIVATE AND PROTECTED MODIFIERS //// // //// //------------------------------------------------------ //// //// //// private void SetUnrestricted( bool unrestricted ) //// { //// if(unrestricted) //// { //// m_flags = SecurityPermissionFlag.AllFlags; //// } //// } //// //// private void Reset() //// { //// m_flags = SecurityPermissionFlag.NoFlags; //// } //// //// //// public SecurityPermissionFlag Flags //// { //// set //// { //// VerifyAccess( value ); //// //// m_flags = value; //// } //// //// get //// { //// return m_flags; //// } //// } //// //// // //// // CodeAccessPermission methods //// // //// //// /* //// * IPermission interface implementation //// */ //// //// public override bool IsSubsetOf( IPermission target ) //// { //// if(target == null) //// { //// return m_flags == 0; //// } //// //// SecurityPermission operand = target as SecurityPermission; //// if(operand != null) //// { //// return (((int)this.m_flags) & ~((int)operand.m_flags)) == 0; //// } //// else //// { //// throw new //// ArgumentException( //// String.Format( CultureInfo.CurrentCulture, Environment.GetResourceString( "Argument_WrongType" ), this.GetType().FullName ) //// ); //// } //// //// } //// //// public override IPermission Union( IPermission target ) //// { //// if(target == null) return (this.Copy()); //// if(!VerifyType( target )) //// { //// throw new //// ArgumentException( //// String.Format( CultureInfo.CurrentCulture, Environment.GetResourceString( "Argument_WrongType" ), this.GetType().FullName ) //// ); //// } //// SecurityPermission sp_target = (SecurityPermission)target; //// if(sp_target.IsUnrestricted() || IsUnrestricted()) //// { //// return (new SecurityPermission( PermissionState.Unrestricted )); //// } //// SecurityPermissionFlag flag_union = (SecurityPermissionFlag)(m_flags | sp_target.m_flags); //// return (new SecurityPermission( flag_union )); //// } //// //// public override IPermission Intersect( IPermission target ) //// { //// if(target == null) //// return null; //// else if(!VerifyType( target )) //// { //// throw new //// ArgumentException( //// String.Format( CultureInfo.CurrentCulture, Environment.GetResourceString( "Argument_WrongType" ), this.GetType().FullName ) //// ); //// } //// //// SecurityPermission operand = (SecurityPermission)target; //// SecurityPermissionFlag isectFlags = SecurityPermissionFlag.NoFlags; //// //// if(operand.IsUnrestricted()) //// { //// if(this.IsUnrestricted()) //// return new SecurityPermission( PermissionState.Unrestricted ); //// else //// isectFlags = (SecurityPermissionFlag)this.m_flags; //// } //// else if(this.IsUnrestricted()) //// { //// isectFlags = (SecurityPermissionFlag)operand.m_flags; //// } //// else //// { //// isectFlags = (SecurityPermissionFlag)m_flags & (SecurityPermissionFlag)operand.m_flags; //// } //// //// if(isectFlags == 0) //// return null; //// else //// return new SecurityPermission( isectFlags ); //// } //// //// public override IPermission Copy() //// { //// if(IsUnrestricted()) //// return new SecurityPermission( PermissionState.Unrestricted ); //// else //// return new SecurityPermission( (SecurityPermissionFlag)m_flags ); //// } //// //// public bool IsUnrestricted() //// { //// return m_flags == SecurityPermissionFlag.AllFlags; //// } //// //// private //// void VerifyAccess( SecurityPermissionFlag type ) //// { //// if((type & ~SecurityPermissionFlag.AllFlags) != 0) //// throw new ArgumentException( String.Format( CultureInfo.CurrentCulture, Environment.GetResourceString( "Arg_EnumIllegalVal" ), (int)type ) ); //// } //// //// //// //------------------------------------------------------ //// // //// // PUBLIC ENCODING METHODS //// // //// //------------------------------------------------------ //// //// private const String _strHeaderAssertion = "Assertion"; //// private const String _strHeaderUnmanagedCode = "UnmanagedCode"; //// private const String _strHeaderExecution = "Execution"; //// private const String _strHeaderSkipVerification = "SkipVerification"; //// private const String _strHeaderControlThread = "ControlThread"; //// private const String _strHeaderControlEvidence = "ControlEvidence"; //// private const String _strHeaderControlPolicy = "ControlPolicy"; //// private const String _strHeaderSerializationFormatter = "SerializationFormatter"; //// private const String _strHeaderControlDomainPolicy = "ControlDomainPolicy"; //// private const String _strHeaderControlPrincipal = "ControlPrincipal"; //// private const String _strHeaderControlAppDomain = "ControlAppDomain"; //// //// public override SecurityElement ToXml() //// { //// SecurityElement esd = CodeAccessPermission.CreatePermissionElement( this, "System.Security.Permissions.SecurityPermission" ); //// if(!IsUnrestricted()) //// { //// esd.AddAttribute( "Flags", XMLUtil.BitFieldEnumToString( typeof( SecurityPermissionFlag ), m_flags ) ); //// } //// else //// { //// esd.AddAttribute( "Unrestricted", "true" ); //// } //// return esd; //// } //// //// public override void FromXml( SecurityElement esd ) //// { //// CodeAccessPermission.ValidateElement( esd, this ); //// if(XMLUtil.IsUnrestricted( esd )) //// { //// m_flags = SecurityPermissionFlag.AllFlags; //// return; //// } //// //// Reset(); //// SetUnrestricted( false ); //// //// String flags = esd.Attribute( "Flags" ); //// //// if(flags != null) //// m_flags = (SecurityPermissionFlag)Enum.Parse( typeof( SecurityPermissionFlag ), flags ); //// } //// //// // //// // Object Overrides //// // //// #if ZERO // Do not remove this code, usefull for debugging public override String ToString() //// { //// StringBuilder sb = new StringBuilder(); //// sb.Append("SecurityPermission("); //// if (IsUnrestricted()) //// { //// sb.Append("Unrestricted"); //// } //// else //// { //// if (GetFlag(SecurityPermissionFlag.Assertion)) //// sb.Append("Assertion; "); //// if (GetFlag(SecurityPermissionFlag.UnmanagedCode)) //// sb.Append("UnmangedCode; "); //// if (GetFlag(SecurityPermissionFlag.SkipVerification)) //// sb.Append("SkipVerification; "); //// if (GetFlag(SecurityPermissionFlag.Execution)) //// sb.Append("Execution; "); //// if (GetFlag(SecurityPermissionFlag.ControlThread)) //// sb.Append("ControlThread; "); //// if (GetFlag(SecurityPermissionFlag.ControlEvidence)) //// sb.Append("ControlEvidence; "); //// if (GetFlag(SecurityPermissionFlag.ControlPolicy)) //// sb.Append("ControlPolicy; "); //// if (GetFlag(SecurityPermissionFlag.SerializationFormatter)) //// sb.Append("SerializationFormatter; "); //// if (GetFlag(SecurityPermissionFlag.ControlDomainPolicy)) //// sb.Append("ControlDomainPolicy; "); //// if (GetFlag(SecurityPermissionFlag.ControlPrincipal)) //// sb.Append("ControlPrincipal; "); //// } //// //// sb.Append(")"); //// return sb.ToString(); //// } #endif //// //// /// //// int IBuiltInPermission.GetTokenIndex() //// { //// return SecurityPermission.GetTokenIndex(); //// } //// //// internal static int GetTokenIndex() //// { //// return BuiltInPermissionIndex.SecurityPermissionIndex; //// } //// //// // This can be used as a place-holder for SkipVerification permission //// [SecurityPermission( SecurityAction.LinkDemand, SkipVerification = true )] //// static internal void MethodWithSkipVerificationLinkDemand() { } ////} } ================================================ FILE: Zelig/Zelig/RunTime/Framework/mscorlib/System/SerializableAttribute.cs ================================================ // ==++== // // Copyright (c) Microsoft Corporation. All rights reserved. // // ==--== /*============================================================ ** ** Class: SerializableAttribute ** ** ** Purpose: Used to mark a class as being serializable ** ** ============================================================*/ namespace System { using System; using System.Reflection; [AttributeUsage( AttributeTargets.Class | AttributeTargets.Struct | AttributeTargets.Enum | AttributeTargets.Delegate, Inherited = false )] public sealed class SerializableAttribute : Attribute { //// internal static Attribute GetCustomAttribute( Type type ) //// { //// return (type.Attributes & TypeAttributes.Serializable) == TypeAttributes.Serializable ? new SerializableAttribute() : null; //// } //// internal static bool IsDefined( Type type ) //// { //// return type.IsSerializable; //// } public SerializableAttribute() { } } } ================================================ FILE: Zelig/Zelig/RunTime/Framework/mscorlib/System/Single.cs ================================================ // ==++== // // Copyright (c) Microsoft Corporation. All rights reserved. // // ==--== /*============================================================ ** ** Class: Single ** ** ** Purpose: A wrapper class for the primitive type float. ** ** ===========================================================*/ namespace System { using System; using System.Globalization; using System.Runtime.InteropServices; using System.Runtime.CompilerServices; using System.Runtime.ConstrainedExecution; [Microsoft.Zelig.Internals.WellKnownType( "System_Single" )] [Serializable] [StructLayout( LayoutKind.Sequential )] public struct Single : IComparable, IFormattable, IConvertible, IComparable, IEquatable { // // Public constants // public const float MinValue = (float)-3.40282346638528859e+38; public const float Epsilon = (float) 1.4e-45; public const float MaxValue = (float) 3.40282346638528859e+38; public const float PositiveInfinity = (float) 1.0 / (float)0.0; public const float NegativeInfinity = (float)-1.0 / (float)0.0; public const float NaN = (float) 0.0 / (float)0.0; internal float m_value; public unsafe static bool IsInfinity( float f ) { return (*(int*)(&f) & 0x7FFFFFFF) == 0x7F800000; } public unsafe static bool IsPositiveInfinity( float f ) { return *(int*)(&f) == 0x7F800000; } public unsafe static bool IsNegativeInfinity( float f ) { return *(int*)(&f) == unchecked( (int)0xFF800000 ); } //// [ReliabilityContract( Consistency.WillNotCorruptState, Cer.Success )] public static bool IsNaN( float f ) { //Jit will generate inlineable code with this // warning CS1718: Comparison to same variable #pragma warning disable 1718 if(f != f) { return true; } else { return false; } #pragma warning restore 1718 } // Compares this object to another object, returning an integer that // indicates the relationship. // Returns a value less than zero if this object // null is considered to be less than any instance. // If object is not of type Single, this method throws an ArgumentException. // public int CompareTo( Object value ) { if(value == null) { return 1; } if(value is Single) { return CompareTo( (float)value ); } #if EXCEPTION_STRINGS throw new ArgumentException( Environment.GetResourceString( "Arg_MustBeSingle" ) ); #else throw new ArgumentException(); #endif } public int CompareTo( Single value ) { if(m_value < value) return -1; if(m_value > value) return 1; if(m_value == value) return 0; // At least one of the values is NaN. if(IsNaN( m_value )) { return (IsNaN( value ) ? 0 : -1); } else // f is NaN. { return 1; } } public override bool Equals( Object obj ) { if(!(obj is Single)) { return false; } return Equals( (Single)obj ); } public bool Equals( Single obj ) { if(obj == m_value) { return true; } return IsNaN( obj ) && IsNaN( m_value ); } public unsafe override int GetHashCode() { float f = m_value; if(f == 0) { // Ensure that 0 and -0 have the same hash code return 0; } int v = *(int*)(&f); return v; } public override String ToString() { return Number.FormatSingle( m_value, /*null,*/ NumberFormatInfo.CurrentInfo ); } public String ToString( IFormatProvider provider ) { return Number.FormatSingle( m_value, /*null,*/ NumberFormatInfo.GetInstance( provider ) ); } public String ToString( String format ) { return Number.FormatSingle( m_value, format, NumberFormatInfo.CurrentInfo ); } public String ToString( String format , IFormatProvider provider ) { return Number.FormatSingle( m_value, format, NumberFormatInfo.GetInstance( provider ) ); } // Parses a float from a String in the given style. If // a NumberFormatInfo isn't specified, the current culture's // NumberFormatInfo is assumed. // // This method will not throw an OverflowException, but will return // PositiveInfinity or NegativeInfinity for a number that is too // large or too small. // public static float Parse( String s ) { return Parse( s, NumberStyles.Float | NumberStyles.AllowThousands, NumberFormatInfo.CurrentInfo ); } public static float Parse( String s , NumberStyles style ) { NumberFormatInfo.ValidateParseStyleFloatingPoint( style ); return Parse( s, style, NumberFormatInfo.CurrentInfo ); } public static float Parse( String s , IFormatProvider provider ) { return Parse( s, NumberStyles.Float | NumberStyles.AllowThousands, NumberFormatInfo.GetInstance( provider ) ); } public static float Parse( String s , NumberStyles style , IFormatProvider provider ) { NumberFormatInfo.ValidateParseStyleFloatingPoint( style ); return Parse( s, style, NumberFormatInfo.GetInstance( provider ) ); } private static float Parse( String s , NumberStyles style , NumberFormatInfo info ) { try { return Number.ParseSingle( s, style, info ); } catch(FormatException) { //If we caught a FormatException, it may be from one of our special strings. //Check the three with which we're concerned and rethrow if it's not one of //those strings. String sTrim = s.Trim(); if(sTrim.Equals( info.PositiveInfinitySymbol )) { return PositiveInfinity; } if(sTrim.Equals( info.NegativeInfinitySymbol )) { return NegativeInfinity; } if(sTrim.Equals( info.NaNSymbol )) { return NaN; } //Rethrow the previous exception; throw; } } public static Boolean TryParse( String s , out Single result ) { return TryParse( s, NumberStyles.Float | NumberStyles.AllowThousands, NumberFormatInfo.CurrentInfo, out result ); } public static Boolean TryParse( String s , NumberStyles style , IFormatProvider provider , out Single result ) { NumberFormatInfo.ValidateParseStyleFloatingPoint( style ); return TryParse( s, style, NumberFormatInfo.GetInstance( provider ), out result ); } private static Boolean TryParse( String s , NumberStyles style , NumberFormatInfo info , out Single result ) { if(s == null) { result = 0; return false; } bool success = Number.TryParseSingle( s, style, info, out result ); if(!success) { String sTrim = s.Trim(); if(sTrim.Equals( info.PositiveInfinitySymbol )) { result = PositiveInfinity; } else if(sTrim.Equals( info.NegativeInfinitySymbol )) { result = NegativeInfinity; } else if(sTrim.Equals( info.NaNSymbol )) { result = NaN; } else { return false; // We really failed } } return true; } #region IConvertible public TypeCode GetTypeCode() { return TypeCode.Single; } /// bool IConvertible.ToBoolean( IFormatProvider provider ) { return Convert.ToBoolean( m_value ); } /// char IConvertible.ToChar( IFormatProvider provider ) { #if EXCEPTION_STRINGS throw new InvalidCastException( String.Format( CultureInfo.CurrentCulture, Environment.GetResourceString( "InvalidCast_FromTo" ), "Single", "Char" ) ); #else throw new InvalidCastException(); #endif } /// sbyte IConvertible.ToSByte( IFormatProvider provider ) { return Convert.ToSByte( m_value ); } /// byte IConvertible.ToByte( IFormatProvider provider ) { return Convert.ToByte( m_value ); } /// short IConvertible.ToInt16( IFormatProvider provider ) { return Convert.ToInt16( m_value ); } /// ushort IConvertible.ToUInt16( IFormatProvider provider ) { return Convert.ToUInt16( m_value ); } /// int IConvertible.ToInt32( IFormatProvider provider ) { return Convert.ToInt32( m_value ); } /// uint IConvertible.ToUInt32( IFormatProvider provider ) { return Convert.ToUInt32( m_value ); } /// long IConvertible.ToInt64( IFormatProvider provider ) { return Convert.ToInt64( m_value ); } /// ulong IConvertible.ToUInt64( IFormatProvider provider ) { return Convert.ToUInt64( m_value ); } /// float IConvertible.ToSingle( IFormatProvider provider ) { return m_value; } /// double IConvertible.ToDouble( IFormatProvider provider ) { return Convert.ToDouble( m_value ); } /// Decimal IConvertible.ToDecimal( IFormatProvider provider ) { return Convert.ToDecimal( m_value ); } /// DateTime IConvertible.ToDateTime( IFormatProvider provider ) { #if EXCEPTION_STRINGS throw new InvalidCastException( String.Format( CultureInfo.CurrentCulture, Environment.GetResourceString( "InvalidCast_FromTo" ), "Single", "DateTime" ) ); #else throw new InvalidCastException(); #endif } /// Object IConvertible.ToType( Type type, IFormatProvider provider ) { return Convert.DefaultToType( (IConvertible)this, type, provider ); } #endregion } } ================================================ FILE: Zelig/Zelig/RunTime/Framework/mscorlib/System/StackOverflowException.cs ================================================ // ==++== // // Copyright (c) Microsoft Corporation. All rights reserved. // // ==--== /*============================================================================= ** ** Class: StackOverflowException ** ** ** Purpose: The exception class for stack overflow. ** ** =============================================================================*/ namespace System { using System; using System.Runtime.Serialization; [Serializable] public sealed class StackOverflowException : SystemException { public StackOverflowException() : base( Environment.GetResourceString( "Arg_StackOverflowException" ) ) { } public StackOverflowException( String message ) : base( message ) { } public StackOverflowException( String message, Exception innerException ) : base( message, innerException ) { } //// internal StackOverflowException( SerializationInfo info, StreamingContext context ) : base( info, context ) //// { //// } } } ================================================ FILE: Zelig/Zelig/RunTime/Framework/mscorlib/System/String.cs ================================================ // ==++== // // Copyright (c) Microsoft Corporation. All rights reserved. // // ==--== /*============================================================ ** ** Class: String ** ** ** Purpose: Contains headers for the String class. Actual implementations ** are in String.cpp ** ** ===========================================================*/ namespace System { using System; using System.Text; using System.Runtime.ConstrainedExecution; using System.Globalization; using System.Threading; using System.Collections; using System.Collections.Generic; using System.Runtime.CompilerServices; ////using System.Runtime.Versioning; ////using Microsoft.Win32; using System.Runtime.InteropServices; ////using va_list = System.ArgIterator; // // For Information on these methods, please see COMString.cpp // // The String class represents a static string of characters. Many of // the String methods perform some type of transformation on the current // instance and return the result as a new String. All comparison methods are // implemented as a part of String. As with arrays, character positions // (indices) are zero-based. // // When passing a null string into a constructor in VJ and VC, the null should be // explicitly type cast to a String. // For Example: // String s = new String((String)null); // Text.Out.WriteLine(s); // [Microsoft.Zelig.Internals.WellKnownType( "System_String" )] [Serializable] public sealed class String : IComparable, IComparable, ICloneable, IConvertible, /*IEnumerable, IEnumerable,*/ IEquatable { //These are defined in Com99/src/vm/COMStringCommon.h and must be kept in sync. private const int TrimHead = 0; private const int TrimTail = 1; private const int TrimBoth = 2; // The Empty constant holds the empty string value. //We need to call the String constructor so that the compiler doesn't mark this as a literal. //Marking this as a literal would mean that it doesn't show up as a field which we can access //from native. public static readonly String Empty = ""; // //NOTE NOTE NOTE NOTE //These fields map directly onto the fields in an EE StringObject. See object.h for the layout. // [NonSerialized] private int m_arrayLength; [NonSerialized] private int m_stringLength; [NonSerialized] private char m_firstChar; // //Native Static Methods // //// // Joins an array of strings together as one string with a separator between each original string. //// // //// public static String Join( String separator, String[] value ) //// { //// if(value == null) //// { //// throw new ArgumentNullException( "value" ); //// } //// //// return Join( separator, value, 0, value.Length ); //// } #if WIN64 private const int charPtrAlignConst = 3; private const int alignConst = 7; #else private const int charPtrAlignConst = 1; private const int alignConst = 3; #endif //// internal char FirstChar //// { //// get //// { //// return m_firstChar; //// } //// } //// //// // Joins an array of strings together as one string with a separator between each original string. //// // //// public unsafe static String Join( String separator, String[] value, int startIndex, int count ) //// { //// //Treat null as empty string. //// if(separator == null) //// { //// separator = String.Empty; //// } //// //// //Range check the array //// if(value == null) //// { //// throw new ArgumentNullException( "value" ); //// } //// //// if(startIndex < 0) //// { //// throw new ArgumentOutOfRangeException( "startIndex", Environment.GetResourceString( "ArgumentOutOfRange_StartIndex" ) ); //// } //// if(count < 0) //// { //// throw new ArgumentOutOfRangeException( "count", Environment.GetResourceString( "ArgumentOutOfRange_NegativeCount" ) ); //// } //// //// if(startIndex > value.Length - count) //// { //// throw new ArgumentOutOfRangeException( "startIndex", Environment.GetResourceString( "ArgumentOutOfRange_IndexCountBuffer" ) ); //// } //// //// //If count is 0, that skews a whole bunch of the calculations below, so just special case that. //// if(count == 0) //// { //// return String.Empty; //// } //// //// //Figure out the total length of the strings in value //// int jointLength = 0; //// int endIndex = startIndex + count - 1; //// for(int stringToJoinIndex = startIndex; stringToJoinIndex <= endIndex; stringToJoinIndex++) //// { //// if(value[stringToJoinIndex] != null) //// { //// jointLength += value[stringToJoinIndex].Length; //// } //// } //// //// //Add enough room for the separator. //// jointLength += (count - 1) * separator.Length; //// //// // Note that we may not catch all overflows with this check (since we could have wrapped around the 4gb range any number of times //// // and landed back in the positive range.) The input array might be modifed from other threads, //// // so we have to do an overflow check before each append below anyway. Those overflows will get caught down there. //// if((jointLength < 0) || ((jointLength + 1) < 0)) //// { //// throw new OutOfMemoryException(); //// } //// //// //If this is an empty string, just return. //// if(jointLength == 0) //// { //// return String.Empty; //// } //// //// string jointString = FastAllocateString( jointLength ); //// //// fixed(char* pointerToJointString = &jointString.m_firstChar) //// { //// UnSafeCharBuffer charBuffer = new UnSafeCharBuffer( pointerToJointString, jointLength ); //// //// // Append the first string first and then append each following string prefixed by the separator. //// charBuffer.AppendString( value[startIndex] ); //// for(int stringToJoinIndex = startIndex + 1; stringToJoinIndex <= endIndex; stringToJoinIndex++) //// { //// charBuffer.AppendString( separator ); //// charBuffer.AppendString( value[stringToJoinIndex] ); //// } //// BCLDebug.Assert( *(pointerToJointString + charBuffer.Length) == '\0', "String must be null-terminated!" ); //// } //// //// return jointString; //// } //// [ResourceExposure( ResourceScope.None )] [MethodImpl( MethodImplOptions.InternalCall )] internal static extern int nativeCompareOrdinal( String strA, String strB, bool bIgnoreCase ); //// [ResourceExposure( ResourceScope.None )] [MethodImpl( MethodImplOptions.InternalCall )] internal static extern int nativeCompareOrdinalEx( String strA, int indexA, String strB, int indexB, int count ); //// //This will not work in case-insensitive mode for any character greater than 0x80. //// //We'll throw an ArgumentException. //// [ResourceExposure( ResourceScope.None )] //// [MethodImpl( MethodImplOptions.InternalCall )] //// unsafe internal static extern int nativeCompareOrdinalWC( String strA, char* strBChars, bool bIgnoreCase, out bool success ); //// // //// // This is a helper method for the security team. They need to uppercase some strings (guaranteed to be less //// // than 0x80) before security is fully initialized. Without security initialized, we can't grab resources (the nlp's) //// // from the assembly. This provides a workaround for that problem and should NOT be used anywhere else. //// // //// internal unsafe static string SmallCharToUpper( string strIn ) //// { //// BCLDebug.Assert( strIn != null, "strIn" ); //// // //// // Get the length and pointers to each of the buffers. Walk the length //// // of the string and copy the characters from the inBuffer to the outBuffer, //// // capitalizing it if necessary. We assert that all of our characters are //// // less than 0x80. //// // //// int length = strIn.Length; //// String strOut = FastAllocateString( length ); //// //// fixed(char* inBuff = &strIn.m_firstChar, outBuff = &strOut.m_firstChar) //// { //// char c; //// //// int upMask = ~0x20; //// for(int i = 0; i < length; i++) //// { //// c = inBuff[i]; //// //// BCLDebug.Assert( (int)c < 0x80, "(int)c < 0x80" ); //// //// // //// // 0x20 is the difference between upper and lower characters in the lower //// // 128 ASCII characters. And this bit off to make the chars uppercase. //// // //// if(c >= 'a' && c <= 'z') //// { //// c = (char)((int)c & upMask); //// } //// //// outBuff[i] = c; //// } //// //// BCLDebug.Assert( outBuff[length] == '\0', "outBuff[length]=='\0'" ); //// } //// //// return strOut; //// } // // // NATIVE INSTANCE METHODS // // // // Search/Query methods // //// [ReliabilityContract( Consistency.WillNotCorruptState, Cer.MayFail )] private unsafe static bool EqualsHelper( String strA, String strB ) { int length = strA.Length; if(length != strB.Length) return false; fixed(char* ap = strA) fixed(char* bp = strB) { char* a = ap; char* b = bp; // This depends on the fact that the String objects are always zero terminated and // that the terminating zero is not included in the length. For odd string sizes, // the last compare will include the zero terminator. while(length > 0) { if(*(int*)a != *(int*)b) break; a += 2; b += 2; length -= 2; } return (length <= 0); } } private unsafe static int CompareOrdinalHelper( String strA, String strB ) { BCLDebug.Assert( strA != null && strB != null, "strings cannot be null!" ); int length = Math.Min( strA.Length, strB.Length ); fixed(char* ap = strA) fixed(char* bp = strB) { char* a = ap; char* b = bp; // Compare the strings four bytes at a time. The following code takes advantage of the fact that strings // always have a null terminator, so even if length is 1 here, we can still do the comparsion. while(length > 0) { if(*(int*)a != *(int*)b) { break; } a += 2; b += 2; length -= 2; } if(length > 0) { int c; // found a different int on above loop if((c = (int)*a - (int)*b) != 0) { return c; } BCLDebug.Assert( *(a + 1) != *(b + 1), "This byte must be different if we reach here!" ); return ((int)*(a + 1) - (int)*(b + 1)); } // At this point, we have compared all the characters in at least one string. // The longer string will be larger. return strA.Length - strB.Length; } } // Determines whether two strings match. //// [ReliabilityContract( Consistency.WillNotCorruptState, Cer.MayFail )] public override bool Equals( Object obj ) { String str = obj as String; if(str == null) { // exception will be thrown later for null this if(this != null) return false; } return EqualsHelper( this, str ); } // Determines whether two strings match. //// [ReliabilityContract( Consistency.WillNotCorruptState, Cer.MayFail )] public bool Equals( String value ) { if(value == null) { // exception will be thrown later for null this if(this != null) return false; } return EqualsHelper( this, value ); } public bool Equals( String value, StringComparison comparisonType ) { if(value == null || m_stringLength != value.Length) return false; return 0 == string.Compare( this, value, comparisonType ); } // Determines whether two Strings match. public static bool Equals( String a, String b ) { if((Object)a == (Object)b) { return true; } if((Object)a == null || (Object)b == null) { return false; } return EqualsHelper( a, b ); } public static bool Equals( String a, String b, StringComparison comparisonType ) { if(a != null && b != null && a.Length != b.Length) return false; return 0 == string.Compare( a, b, comparisonType ); } public static bool operator ==( String a, String b ) { return String.Equals( a, b ); } public static bool operator !=( String a, String b ) { return !String.Equals( a, b ); } // Gets the character at a specified position. // [System.Runtime.CompilerServices.IndexerName( "Chars" )] public extern char this[int index] { //// [ResourceExposure( ResourceScope.None )] [MethodImpl( MethodImplOptions.InternalCall )] get; } // Converts a substring of this string to an array of characters. Copies the // characters of this string beginning at position startIndex and ending at // startIndex + length - 1 to the character array buffer, beginning // at bufferStartIndex. // unsafe public void CopyTo( int sourceIndex, char[] destination, int destinationIndex, int count ) { if(destination == null) { #if EXCEPTION_STRINGS throw new ArgumentNullException( "destination" ); #else throw new ArgumentNullException(); #endif } if(count < 0) { #if EXCEPTION_STRINGS throw new ArgumentOutOfRangeException( "count", Environment.GetResourceString( "ArgumentOutOfRange_NegativeCount" ) ); #else throw new ArgumentOutOfRangeException(); #endif } if(sourceIndex < 0) { #if EXCEPTION_STRINGS throw new ArgumentOutOfRangeException( "sourceIndex", Environment.GetResourceString( "ArgumentOutOfRange_Index" ) ); #else throw new ArgumentOutOfRangeException(); #endif } if(count > Length - sourceIndex) { #if EXCEPTION_STRINGS throw new ArgumentOutOfRangeException( "sourceIndex", Environment.GetResourceString( "ArgumentOutOfRange_IndexCount" ) ); #else throw new ArgumentOutOfRangeException(); #endif } if(destinationIndex > destination.Length - count || destinationIndex < 0) { #if EXCEPTION_STRINGS throw new ArgumentOutOfRangeException( "destinationIndex", Environment.GetResourceString( "ArgumentOutOfRange_IndexCount" ) ); #else throw new ArgumentOutOfRangeException(); #endif } // Note: fixed does not like empty arrays if(count > 0) { fixed(char* src = &this.m_firstChar) { fixed(char* dest = destination) { Buffer.InternalMemoryCopy( src + sourceIndex, dest + destinationIndex, count ); } } } } // Returns the entire string as an array of characters. unsafe public char[] ToCharArray() { // huge performance improvement for short strings by doing this int length = Length; char[] chars = new char[length]; if(length > 0) { fixed(char* src = &this.m_firstChar) { fixed(char* dest = chars) { Buffer.InternalMemoryCopy( src, dest, length ); } } } return chars; } // Returns a substring of this string as an array of characters. // unsafe public char[] ToCharArray( int startIndex, int length ) { // Range check everything. if(startIndex < 0 || startIndex > Length || startIndex > Length - length) { #if EXCEPTION_STRINGS throw new ArgumentOutOfRangeException( "startIndex", Environment.GetResourceString( "ArgumentOutOfRange_Index" ) ); #else throw new ArgumentOutOfRangeException(); #endif } if(length < 0) { #if EXCEPTION_STRINGS throw new ArgumentOutOfRangeException( "length", Environment.GetResourceString( "ArgumentOutOfRange_Index" ) ); #else throw new ArgumentOutOfRangeException(); #endif } char[] chars = new char[length]; if(length > 0) { fixed(char* src = &this.m_firstChar) { fixed(char* dest = chars) { Buffer.InternalMemoryCopy( src + startIndex, dest, length ); } } } return chars; } public static bool IsNullOrEmpty( String value ) { return (value == null || value.Length == 0); } // Gets a hash code for this string. If strings A and B are such that A.Equals(B), then // they will return the same hash code. //// [ReliabilityContract( Consistency.WillNotCorruptState, Cer.MayFail )] public override int GetHashCode() { unsafe { fixed(char* src = this) { BCLDebug.Assert( src[this.Length] == '\0', "src[this.Length] == '\\0'" ); BCLDebug.Assert( ((int)src) % 4 == 0, "Managed string should start at 4 bytes boundary" ); #if !WIN64 int hash1 = (5381<<16) + 5381; #else int hash1 = 5381; #endif int hash2 = hash1; #if !WIN64 // 32bit machines. int* pint = (int *)src; int len = this.Length; while(len > 0) { hash1 = ((hash1 << 5) + hash1 + (hash1 >> 27)) ^ pint[0]; if(len <= 2) { break; } hash2 = ((hash2 << 5) + hash2 + (hash2 >> 27)) ^ pint[1]; pint += 2; len -= 4; } #else int c; char* s = src; while((c = s[0]) != 0) { hash1 = ((hash1 << 5) + hash1) ^ c; c = s[1]; if(c == 0) { break; } hash2 = ((hash2 << 5) + hash2) ^ c; s += 2; } #endif ////#if DEBUG //// // We want to ensure we can change our hash function daily. //// // This is perfectly fine as long as you don't persist the //// // value from GetHashCode to disk or count on String A //// // hashing before string B. Those are bugs in your code. //// hash1 ^= ThisAssembly.DailyBuildNumber; ////#endif return hash1 + (hash2 * 1566083941); } } } public int Length { get { return m_stringLength; } } //// // Gets the length of this string //// // //// // This is a EE implemented function so that the JIT can recognise is specially //// // and eliminate checks on character fetchs in a loop like: //// // for(int I = 0; I < str.Length; i++) str[i] //// // The actually code generated for this will be one instruction and will be inlined. //// // //// public extern int Length //// { //// [ResourceExposure( ResourceScope.None )] //// [MethodImpl( MethodImplOptions.InternalCall )] //// get; //// } /// internal int ArrayLength { get { return m_arrayLength; } } // Used by StringBuilder internal int Capacity { get { return m_arrayLength - 1; } } // Creates an array of strings by splitting this string at each // occurence of a separator. The separator is searched for, and if found, // the substring preceding the occurence is stored as the first element in // the array of strings. We then continue in this manner by searching // the substring that follows the occurence. On the other hand, if the separator // is not found, the array of strings will contain this instance as its only element. // If the separator is null // whitespace (i.e., Character.IsWhitespace) is used as the separator. // public String[] Split( params char[] separator ) { return Split( separator, Int32.MaxValue, StringSplitOptions.None ); } // Creates an array of strings by splitting this string at each // occurence of a separator. The separator is searched for, and if found, // the substring preceding the occurence is stored as the first element in // the array of strings. We then continue in this manner by searching // the substring that follows the occurence. On the other hand, if the separator // is not found, the array of strings will contain this instance as its only element. // If the spearator is the empty string (i.e., String.Empty), then // whitespace (i.e., Character.IsWhitespace) is used as the separator. // If there are more than count different strings, the last n-(count-1) // elements are concatenated and added as the last String. // public string[] Split( char[] separator, int count ) { return Split( separator, count, StringSplitOptions.None ); } public String[] Split( char[] separator, StringSplitOptions options ) { return Split( separator, Int32.MaxValue, options ); } public String[] Split( char[] separator, int count, StringSplitOptions options ) { if(count < 0) { #if EXCEPTION_STRINGS throw new ArgumentOutOfRangeException( "count", Environment.GetResourceString( "ArgumentOutOfRange_NegativeCount" ) ); #else throw new ArgumentOutOfRangeException(); #endif } if(options < StringSplitOptions.None || options > StringSplitOptions.RemoveEmptyEntries) { #if EXCEPTION_STRINGS throw new ArgumentException( Environment.GetResourceString( "Arg_EnumIllegalVal", (int)options ) ); #else throw new ArgumentException(); #endif } bool omitEmptyEntries = (options == StringSplitOptions.RemoveEmptyEntries); if((count == 0) || (omitEmptyEntries && this.Length == 0)) { return new String[0]; } int[] sepList = new int[Length]; int numReplaces = MakeSeparatorList( separator, ref sepList ); //Handle the special case of no replaces and special count. if(0 == numReplaces || count == 1) { String[] stringArray = new String[1]; stringArray[0] = this; return stringArray; } if(omitEmptyEntries) { return InternalSplitOmitEmptyEntries( sepList, null, numReplaces, count ); } else { return InternalSplitKeepEmptyEntries( sepList, null, numReplaces, count ); } } public String[] Split( String[] separator, StringSplitOptions options ) { return Split( separator, Int32.MaxValue, options ); } public String[] Split( String[] separator, Int32 count, StringSplitOptions options ) { if(count < 0) { #if EXCEPTION_STRINGS throw new ArgumentOutOfRangeException( "count", Environment.GetResourceString( "ArgumentOutOfRange_NegativeCount" ) ); #else throw new ArgumentOutOfRangeException(); #endif } if(options < StringSplitOptions.None || options > StringSplitOptions.RemoveEmptyEntries) { #if EXCEPTION_STRINGS throw new ArgumentException( Environment.GetResourceString( "Arg_EnumIllegalVal", (int)options ) ); #else throw new ArgumentException(); #endif } bool omitEmptyEntries = (options == StringSplitOptions.RemoveEmptyEntries); if(separator == null || separator.Length == 0) { return Split( (char[])null, count, options ); } if((count == 0) || (omitEmptyEntries && this.Length == 0)) { return new String[0]; } int[] sepList = new int[Length]; int[] lengthList = new int[Length]; int numReplaces = MakeSeparatorList( separator, ref sepList, ref lengthList ); //Handle the special case of no replaces and special count. if(0 == numReplaces || count == 1) { String[] stringArray = new String[1]; stringArray[0] = this; return stringArray; } if(omitEmptyEntries) { return InternalSplitOmitEmptyEntries( sepList, lengthList, numReplaces, count ); } else { return InternalSplitKeepEmptyEntries( sepList, lengthList, numReplaces, count ); } } // Note a few special case in this function: // If there is no separator in the string, a string array which only contains // the original string will be returned regardless of the count. // private String[] InternalSplitKeepEmptyEntries( Int32[] sepList, Int32[] lengthList, Int32 numReplaces, int count ) { BCLDebug.Assert( count >= 2, "Count>=2" ); int currIndex = 0; int arrIndex = 0; count--; int numActualReplaces = (numReplaces < count) ? numReplaces : count; //Allocate space for the new array. //+1 for the string from the end of the last replace to the end of the String. String[] splitStrings = new String[numActualReplaces + 1]; for(int i = 0; i < numActualReplaces && currIndex < Length; i++) { splitStrings[arrIndex++] = Substring( currIndex, sepList[i] - currIndex ); currIndex = sepList[i] + ((lengthList == null) ? 1 : lengthList[i]); } //Handle the last string at the end of the array if there is one. if(currIndex < Length && numActualReplaces >= 0) { splitStrings[arrIndex] = Substring( currIndex ); } else if(arrIndex == numActualReplaces) { //We had a separator character at the end of a string. Rather than just allowing //a null character, we'll replace the last element in the array with an empty string. splitStrings[arrIndex] = String.Empty; } return splitStrings; } // This function will not keep the Empty String private String[] InternalSplitOmitEmptyEntries( Int32[] sepList, Int32[] lengthList, Int32 numReplaces, int count ) { BCLDebug.Assert( count >= 2, "Count>=2" ); // Allocate array to hold items. This array may not be // filled completely in this function, we will create a // new array and copy string references to that new array. int maxItems = (numReplaces < count) ? (numReplaces + 1) : count; String[] splitStrings = new String[maxItems]; int currIndex = 0; int arrIndex = 0; for(int i = 0; i < numReplaces && currIndex < Length; i++) { if(sepList[i] - currIndex > 0) { splitStrings[arrIndex++] = Substring( currIndex, sepList[i] - currIndex ); } currIndex = sepList[i] + ((lengthList == null) ? 1 : lengthList[i]); if(arrIndex == count - 1) { // If all the remaining entries at the end are empty, skip them while(i < numReplaces - 1 && currIndex == sepList[++i]) { currIndex += ((lengthList == null) ? 1 : lengthList[i]); } break; } } // we must have at least one slot left to fill in the last string. BCLDebug.Assert( arrIndex < maxItems, "arrIndex < maxItems" ); //Handle the last string at the end of the array if there is one. if(currIndex < Length) { splitStrings[arrIndex++] = Substring( currIndex ); } String[] stringArray = splitStrings; if(arrIndex != maxItems) { stringArray = new String[arrIndex]; for(int j = 0; j < arrIndex; j++) { stringArray[j] = splitStrings[j]; } } return stringArray; } //-------------------------------------------------------------------- // This function returns number of the places within baseString where // instances of characters in Separator occur. // Args: separator -- A string containing all of the split characters. // sepList -- an array of ints for split char indicies. //-------------------------------------------------------------------- private unsafe int MakeSeparatorList( char[] separator, ref int[] sepList ) { int foundCount = 0; if(separator == null || separator.Length == 0) { fixed(char* pwzChars = &this.m_firstChar) { //If they passed null or an empty string, look for whitespace. for(int i = 0; i < Length && foundCount < sepList.Length; i++) { if(Char.IsWhiteSpace( pwzChars[i] )) { sepList[foundCount++] = i; } } } } else { int sepListCount = sepList .Length; int sepCount = separator.Length; //If they passed in a string of chars, actually look for those chars. fixed(char* pwzChars = &this.m_firstChar, pSepChars = separator) { for(int i = 0; i < Length && foundCount < sepListCount; i++) { char* pSep = pSepChars; for(int j = 0; j < sepCount; j++, pSep++) { if(pwzChars[i] == *pSep) { sepList[foundCount++] = i; break; } } } } } return foundCount; } //-------------------------------------------------------------------- // This function returns number of the places within baseString where // instances of separator strings occur. // Args: separators -- An array containing all of the split strings. // sepList -- an array of ints for split string indicies. // lengthList -- an array of ints for split string lengths. //-------------------------------------------------------------------- private unsafe int MakeSeparatorList( String[] separators, ref int[] sepList, ref int[] lengthList ) { BCLDebug.Assert( separators != null && separators.Length > 0, "separators != null && separators.Length > 0" ); int foundCount = 0; int sepListCount = sepList.Length; int sepCount = separators.Length; fixed(char* pwzChars = &this.m_firstChar) { for(int i = 0; i < Length && foundCount < sepListCount; i++) { for(int j = 0; j < separators.Length; j++) { String separator = separators[j]; if(String.IsNullOrEmpty( separator )) { continue; } Int32 currentSepLength = separator.Length; if(pwzChars[i] == separator[0] && currentSepLength <= Length - i) { if(currentSepLength == 1 || String.CompareOrdinal( this, i, separator, 0, currentSepLength ) == 0) { sepList [foundCount] = i; lengthList[foundCount] = currentSepLength; foundCount++; i += currentSepLength - 1; break; } } } } } return foundCount; } // Returns a substring of this string. // public String Substring( int startIndex ) { return this.Substring( startIndex, Length - startIndex ); } // Returns a substring of this string. // public String Substring( int startIndex, int length ) { // okay to not enforce copying in the case of Substring(0, length), since we assume // String instances are immutable. return InternalSubStringWithChecks( startIndex, length, false ); } internal String InternalSubStringWithChecks( int startIndex, int length, bool fAlwaysCopy ) { int thisLength = Length; //Bounds Checking. if(startIndex < 0) { #if EXCEPTION_STRINGS throw new ArgumentOutOfRangeException( "startIndex", Environment.GetResourceString( "ArgumentOutOfRange_StartIndex" ) ); #else throw new ArgumentOutOfRangeException(); #endif } if(startIndex > thisLength) { #if EXCEPTION_STRINGS throw new ArgumentOutOfRangeException( "startIndex", Environment.GetResourceString( "ArgumentOutOfRange_StartIndexLargerThanLength" ) ); #else throw new ArgumentOutOfRangeException(); #endif } if(length < 0) { #if EXCEPTION_STRINGS throw new ArgumentOutOfRangeException( "length", Environment.GetResourceString( "ArgumentOutOfRange_NegativeLength" ) ); #else throw new ArgumentOutOfRangeException(); #endif } if(startIndex > thisLength - length) { #if EXCEPTION_STRINGS throw new ArgumentOutOfRangeException( "length", Environment.GetResourceString( "ArgumentOutOfRange_IndexLength" ) ); #else throw new ArgumentOutOfRangeException(); #endif } if(length == 0) { return String.Empty; } return InternalSubString( startIndex, length, fAlwaysCopy ); } unsafe string InternalSubString( int startIndex, int length, bool fAlwaysCopy ) { BCLDebug.Assert( startIndex >= 0 && startIndex <= this.Length , "StartIndex is out of range!" ); BCLDebug.Assert( length >= 0 && startIndex <= this.Length - length, "length is out of range!" ); if(startIndex == 0 && length == this.Length && !fAlwaysCopy) { return this; } String result = FastAllocateString( length ); fixed(char* dest = &result.m_firstChar) { fixed(char* src = &this.m_firstChar) { Buffer.InternalMemoryCopy( src + startIndex, dest, length ); } } return result; } //This should really live on System.Globalization.CharacterInfo. However, //Trim gets called by security while resgen is running, so we can't run //CharacterInfo's class initializer (which goes to native and looks for a //resource table that hasn't yet been attached to the assembly when resgen //runs. internal static readonly char[] WhitespaceChars = { (char)0x9, (char)0xA, (char)0xB, (char)0xC, (char)0xD, (char)0x20, (char)0x85, (char)0xA0, (char)0x1680, (char)0x2000, (char)0x2001, (char)0x2002, (char)0x2003, (char)0x2004, (char)0x2005, (char)0x2006, (char)0x2007, (char)0x2008, (char)0x2009, (char)0x200A, (char)0x200B, (char)0x2028, (char)0x2029, (char)0x3000, (char)0xFEFF }; // Removes a string of characters from the ends of this string. public String Trim( params char[] trimChars ) { if(trimChars == null || trimChars.Length == 0) { trimChars = WhitespaceChars; } return TrimHelper( trimChars, TrimBoth ); } // Removes a string of characters from the beginning of this string. public String TrimStart( params char[] trimChars ) { if(trimChars == null || trimChars.Length == 0) { trimChars = WhitespaceChars; } return TrimHelper( trimChars, TrimHead ); } // Removes a string of characters from the end of this string. public String TrimEnd( params char[] trimChars ) { if(trimChars == null || trimChars.Length == 0) { trimChars = WhitespaceChars; } return TrimHelper( trimChars, TrimTail ); } //// // Creates a new string with the characters copied in from ptr. If //// // ptr is null, a string initialized to ";<;No Object>;"; (i.e., //// // String.NullString) is created. //// // //// [ResourceExposure( ResourceScope.None )] //// [CLSCompliant( false )] //// [MethodImpl( MethodImplOptions.InternalCall )] //// unsafe public extern String( char* value ); //// //// [ResourceExposure( ResourceScope.None )] //// [CLSCompliant( false )] //// [MethodImpl( MethodImplOptions.InternalCall )] //// unsafe public extern String( char* value, int startIndex, int length ); //// //// [ResourceExposure( ResourceScope.None )] //// [CLSCompliant( false )] //// [MethodImpl( MethodImplOptions.InternalCall )] //// unsafe public extern String( sbyte* value ); //// //// [ResourceExposure( ResourceScope.None )] //// [CLSCompliant( false )] //// [MethodImpl( MethodImplOptions.InternalCall )] //// unsafe public extern String( sbyte* value, int startIndex, int length ); //// //// [ResourceExposure( ResourceScope.None )] //// [CLSCompliant( false )] //// [MethodImpl( MethodImplOptions.InternalCall )] //// unsafe public extern String( sbyte* value, int startIndex, int length, Encoding enc ); //// //// unsafe static private String CreateString( sbyte* value, int startIndex, int length, Encoding enc ) //// { //// if(enc == null) //// { //// return new String( value, startIndex, length ); // default to ANSI //// } //// //// if(length < 0) //// { //// throw new ArgumentOutOfRangeException( "length", Environment.GetResourceString( "ArgumentOutOfRange_NeedNonNegNum" ) ); //// } //// //// if(startIndex < 0) //// { //// throw new ArgumentOutOfRangeException( "startIndex", Environment.GetResourceString( "ArgumentOutOfRange_StartIndex" ) ); //// } //// //// if((value + startIndex) < value) //// { //// // overflow check //// throw new ArgumentOutOfRangeException( "startIndex", Environment.GetResourceString( "ArgumentOutOfRange_PartialWCHAR" ) ); //// } //// //// byte[] b = new byte[length]; //// //// try //// { //// Buffer.memcpy( (byte*)value, startIndex, b, 0, length ); //// } //// catch(NullReferenceException) //// { //// // If we got a NullReferencException. It means the pointer or //// // the index is out of range //// throw new ArgumentOutOfRangeException( "value", Environment.GetResourceString( "ArgumentOutOfRange_PartialWCHAR" ) ); //// } //// //// return enc.GetString( b ); //// } // Helper for encodings so they can talk to our buffer directly // stringLength must be the exact size we'll expect unsafe static internal String CreateStringFromEncoding( byte* bytes , int byteLength , Encoding encoding ) { BCLDebug.Assert( bytes != null, "need a byte[]." ); BCLDebug.Assert( byteLength >= 0, "byteLength >= 0" ); // Get our string length int stringLength = encoding.GetCharCount( bytes, byteLength, null ); BCLDebug.Assert( stringLength >= 0, "stringLength >= 0" ); // They gave us an empty string if they needed one // 0 bytelength might be possible if there's something in an encoder if(stringLength == 0) { return String.Empty; } String s = FastAllocateString( stringLength ); fixed(char* pTempChars = &s.m_firstChar) { int doubleCheck = encoding.GetChars( bytes, byteLength, pTempChars, stringLength, null ); BCLDebug.Assert( stringLength == doubleCheck, "Expected encoding.GetChars to return same length as encoding.GetCharCount" ); } return s; } //// unsafe internal byte[] ConvertToAnsi_BestFit_Throw( int iMaxDBCSCharByteSize ) //// { //// const uint CP_ACP = 0; //// //// int nb; //// int cbNativeBuffer = (Length + 3) * iMaxDBCSCharByteSize; //// byte[] bytes = new byte[cbNativeBuffer]; //// //// uint flgs = 0; //// uint DefaultCharUsed = 0; //// //// fixed(byte* pbNativeBuffer = bytes) //// { //// fixed(char* pwzChar = &this.m_firstChar) //// { //// nb = Win32Native.WideCharToMultiByte( //// CP_ACP, //// flgs, //// pwzChar, //// this.Length, //// pbNativeBuffer, //// cbNativeBuffer, //// IntPtr.Zero, //// new IntPtr( &DefaultCharUsed ) ); //// } //// } //// //// if(0 != DefaultCharUsed) //// { //// throw new ArgumentException( Environment.GetResourceString( "Interop_Marshal_Unmappable_Char" ) ); //// } //// //// bytes[nb] = 0; //// return bytes; //// } //// //// // Normalization Methods //// // These just wrap calls to Normalization class //// public bool IsNormalized() //// { //// // Default to Form C //// return IsNormalized( NormalizationForm.FormC ); //// } //// //// public bool IsNormalized( NormalizationForm normalizationForm ) //// { //// if(this.IsFastSort()) //// { //// // If its FastSort && one of the 4 main forms, then its already normalized //// if(normalizationForm == NormalizationForm.FormC || //// normalizationForm == NormalizationForm.FormKC || //// normalizationForm == NormalizationForm.FormD || //// normalizationForm == NormalizationForm.FormKD) //// { //// return true; //// } //// } //// //// return Normalization.IsNormalized( this, normalizationForm ); //// } //// //// public String Normalize() //// { //// // Default to Form C //// return Normalize( NormalizationForm.FormC ); //// } //// //// public String Normalize( NormalizationForm normalizationForm ) //// { //// if(this.IsAscii()) //// { //// // If its FastSort && one of the 4 main forms, then its already normalized //// if(normalizationForm == NormalizationForm.FormC || //// normalizationForm == NormalizationForm.FormKC || //// normalizationForm == NormalizationForm.FormD || //// normalizationForm == NormalizationForm.FormKD) //// { //// return this; //// } //// } //// //// return Normalization.Normalize( this, normalizationForm ); //// } //// [ResourceExposure( ResourceScope.None )] [MethodImpl( MethodImplOptions.InternalCall )] private extern static String FastAllocateString( int length ); unsafe private static void FillStringChecked( String dest, int destPos, String src ) { int length = src.Length; if(length > dest.Length - destPos) { throw new IndexOutOfRangeException(); } fixed(char* pDest = &dest.m_firstChar) { fixed(char* pSrc = &src.m_firstChar) { Buffer.InternalMemoryCopy( pSrc, pDest + destPos, length ); } } } // Creates a new string from the characters in a subarray. The new string will // be created from the characters in value between startIndex and // startIndex + length - 1. // //// [ResourceExposure( ResourceScope.None )] [MethodImpl( MethodImplOptions.InternalCall )] public extern String( char[] value, int startIndex, int length ); // Creates a new string from the characters in a subarray. The new string will be // created from the characters in value. // //// [ResourceExposure( ResourceScope.None )] [MethodImpl( MethodImplOptions.InternalCall )] public extern String( char[] value ); //// private String CtorCharArray( char[] value ) //// { //// if(value != null && value.Length != 0) //// { //// String result = FastAllocateString( value.Length ); //// //// unsafe //// { //// fixed(char* dest = result, source = value) //// { //// Buffer.InternalMemoryCopy( source, dest, value.Length ); //// } //// } //// return result; //// } //// else //// { //// return String.Empty; //// } //// } //// //// private String CtorCharArrayStartLength( char[] value, int startIndex, int length ) //// { //// if(value == null) //// { //// throw new ArgumentNullException( "value" ); //// } //// //// if(startIndex < 0) //// { //// throw new ArgumentOutOfRangeException( "startIndex", Environment.GetResourceString( "ArgumentOutOfRange_StartIndex" ) ); //// } //// //// if(length < 0) //// { //// throw new ArgumentOutOfRangeException( "length", Environment.GetResourceString( "ArgumentOutOfRange_NegativeLength" ) ); //// } //// //// if(startIndex > value.Length - length) //// { //// throw new ArgumentOutOfRangeException( "startIndex", Environment.GetResourceString( "ArgumentOutOfRange_Index" ) ); //// } //// //// if(length > 0) //// { //// String result = FastAllocateString( length ); //// //// unsafe //// { //// fixed(char* dest = result, source = value) //// { //// Buffer.InternalMemoryCopy( source + startIndex, dest, length ); //// } //// } //// return result; //// } //// else //// { //// return String.Empty; //// } //// } //// //// private String CtorCharCount( char c, int count ) //// { //// if(count > 0) //// { //// String result = FastAllocateString( count ); //// unsafe //// { //// fixed(char* dest = result) //// { //// char* dmem = dest; //// while(((uint)dmem & 3) != 0 && count > 0) //// { //// *dmem++ = c; //// count--; //// } //// uint cc = (uint)((c << 16) | c); //// //// if(count >= 4) //// { //// count -= 4; //// do //// { //// ((uint*)dmem)[0] = cc; //// ((uint*)dmem)[1] = cc; //// dmem += 4; //// count -= 4; //// } while(count >= 0); //// } //// //// if((count & 2) != 0) //// { //// ((uint*)dmem)[0] = cc; //// dmem += 2; //// } //// //// if((count & 1) != 0) //// { //// dmem[0] = c; //// } //// } //// } //// return result; //// } //// else if(count == 0) //// { //// return String.Empty; //// } //// else //// { //// throw new ArgumentOutOfRangeException( "count", Environment.GetResourceString( "ArgumentOutOfRange_MustBeNonNegNum", "count" ) ); //// } //// } //// //// private static unsafe int wcslen( char* ptr ) //// { //// char* end = ptr; //// //// // The following code is (somewhat surprisingly!) significantly faster than a naive loop, //// // at least on x86 and the current jit. //// //// // First make sure our pointer is aligned on a dword boundary //// while(((uint)end & 3) != 0 && *end != 0) //// { //// end++; //// } //// //// if(*end != 0) //// { //// // The loop condition below works because if "end[0] & end[1]" is non-zero, that means //// // neither operand can have been zero. If is zero, we have to look at the operands individually, //// // but we hope this going to fairly rare. //// //// // In general, it would be incorrect to access end[1] if we haven't made sure //// // end[0] is non-zero. However, we know the ptr has been aligned by the loop above //// // so end[0] and end[1] must be in the same page, so they're either both accessible, or both not. //// //// while((end[0] & end[1]) != 0 || (end[0] != 0 && end[1] != 0)) //// { //// end += 2; //// } //// } //// //// // finish up with the naive loop //// for(; *end != 0; end++) //// { //// ; //// } //// //// int count = (int)(end - ptr); //// //// return count; //// } //// //// private unsafe String CtorCharPtr( char* ptr ) //// { //// BCLDebug.Assert( this == null, "this == null" ); // this is the string constructor, we allocate it //// //// if(ptr >= (char*)64000) //// { //// try //// { //// int count = wcslen( ptr ); //// String result = FastAllocateString( count ); //// //// fixed(char* dest = result) //// { //// Buffer.InternalMemoryCopy( ptr, dest, count ); //// } //// //// return result; //// } //// catch(NullReferenceException) //// { //// throw new ArgumentOutOfRangeException( "ptr", Environment.GetResourceString( "ArgumentOutOfRange_PartialWCHAR" ) ); //// } //// } //// else if(ptr == null) //// { //// return String.Empty; //// } //// else //// { //// throw new ArgumentException( Environment.GetResourceString( "Arg_MustBeStringPtrNotAtom" ) ); //// } //// } //// //// private unsafe String CtorCharPtrStartLength( char* ptr, int startIndex, int length ) //// { //// BCLDebug.Assert( this == null, "this == null" ); // this is the string constructor, we allocate it //// //// if(length < 0) //// { //// throw new ArgumentOutOfRangeException( "length", Environment.GetResourceString( "ArgumentOutOfRange_NegativeLength" ) ); //// } //// //// if(startIndex < 0) //// { //// throw new ArgumentOutOfRangeException( "startIndex", Environment.GetResourceString( "ArgumentOutOfRange_StartIndex" ) ); //// } //// //// char* pFrom = ptr + startIndex; //// if(pFrom < ptr) //// { //// // This means that the pointer operation has had an overflow //// throw new ArgumentOutOfRangeException( "startIndex", Environment.GetResourceString( "ArgumentOutOfRange_PartialWCHAR" ) ); //// } //// //// String result = FastAllocateString( length ); //// //// try //// { //// fixed(char* dest = result) //// { //// Buffer.InternalMemoryCopy( pFrom, dest, length ); //// } //// //// return result; //// } //// catch(NullReferenceException) //// { //// throw new ArgumentOutOfRangeException( "ptr", Environment.GetResourceString( "ArgumentOutOfRange_PartialWCHAR" ) ); //// } //// } //// [ResourceExposure( ResourceScope.None )] [MethodImpl( MethodImplOptions.InternalCall )] public extern String( char c, int count ); // // // INSTANCE METHODS // // // Provides a culture-correct string comparison. StrA is compared to StrB // to determine whether it is lexicographically less, equal, or greater, and then returns // either a negative integer, 0, or a positive integer; respectively. // public static int Compare( String strA, String strB ) { return CultureInfo.CurrentCulture.CompareInfo.Compare( strA, strB, CompareOptions.None ); } // Provides a culture-correct string comparison. strA is compared to strB // to determine whether it is lexicographically less, equal, or greater, and then a // negative integer, 0, or a positive integer is returned; respectively. // The case-sensitive option is set by ignoreCase // public static int Compare( String strA, String strB, bool ignoreCase ) { if(ignoreCase) { return CultureInfo.CurrentCulture.CompareInfo.Compare( strA, strB, CompareOptions.IgnoreCase ); } else { return CultureInfo.CurrentCulture.CompareInfo.Compare( strA, strB, CompareOptions.None ); } } // Provides a more flexible function for string comparision. See StringComparison // for meaning of different comparisonType. public static int Compare( String strA, String strB, StringComparison comparisonType ) { if(comparisonType < StringComparison.CurrentCulture || comparisonType > StringComparison.OrdinalIgnoreCase) { #if EXCEPTION_STRINGS throw new ArgumentException( Environment.GetResourceString( "NotSupported_StringComparison" ), "comparisonType" ); #else throw new ArgumentException(); #endif } if((Object)strA == (Object)strB) { return 0; } //they can't both be null; if(strA == null) { return -1; } if(strB == null) { return 1; } switch(comparisonType) { case StringComparison.CurrentCulture: return CultureInfo.CurrentCulture.CompareInfo.Compare( strA, strB, CompareOptions.None ); case StringComparison.CurrentCultureIgnoreCase: return CultureInfo.CurrentCulture.CompareInfo.Compare( strA, strB, CompareOptions.IgnoreCase ); case StringComparison.InvariantCulture: return CultureInfo.InvariantCulture.CompareInfo.Compare( strA, strB, CompareOptions.None ); case StringComparison.InvariantCultureIgnoreCase: return CultureInfo.InvariantCulture.CompareInfo.Compare( strA, strB, CompareOptions.IgnoreCase ); case StringComparison.Ordinal: return CompareOrdinalHelper( strA, strB ); case StringComparison.OrdinalIgnoreCase: // If both strings are ASCII strings, we can take the fast path. if(strA.IsAscii() && strB.IsAscii()) { return (String.nativeCompareOrdinal( strA, strB, true )); } #if EXCEPTION_STRINGS throw new NotSupportedException( Environment.GetResourceString( "NotSupported_StringComparison" ) ); #else throw new NotSupportedException(); #endif //// // Take the slow path. //// return TextInfo.CompareOrdinalIgnoreCase( strA, strB ); default: #if EXCEPTION_STRINGS throw new NotSupportedException( Environment.GetResourceString( "NotSupported_StringComparison" ) ); #else throw new NotSupportedException(); #endif } } //// // Provides a culture-correct string comparison. strA is compared to strB //// // to determine whether it is lexicographically less, equal, or greater, and then a //// // negative integer, 0, or a positive integer is returned; respectively. //// // The case-sensitive option is set by ignoreCase, and the culture is set //// // by culture //// // //// public static int Compare( String strA, String strB, bool ignoreCase, CultureInfo culture ) //// { //// if(culture == null) //// { //// throw new ArgumentNullException( "culture" ); //// } //// //// if(ignoreCase) //// { //// return culture.CompareInfo.Compare( strA, strB, CompareOptions.IgnoreCase ); //// } //// else //// { //// return culture.CompareInfo.Compare( strA, strB, CompareOptions.None ); //// } //// } //// //// // Determines whether two string regions match. The substring of strA beginning //// // at indexA of length count is compared with the substring of strB //// // beginning at indexB of the same length. //// // //// public static int Compare( String strA, int indexA, String strB, int indexB, int length ) //// { //// int lengthA = length; //// int lengthB = length; //// //// if(strA != null) //// { //// if(strA.Length - indexA < lengthA) //// { //// lengthA = (strA.Length - indexA); //// } //// } //// //// if(strB != null) //// { //// if(strB.Length - indexB < lengthB) //// { //// lengthB = (strB.Length - indexB); //// } //// } //// //// return CultureInfo.CurrentCulture.CompareInfo.Compare( strA, indexA, lengthA, strB, indexB, lengthB, CompareOptions.None ); //// } //// //// //// // Determines whether two string regions match. The substring of strA beginning //// // at indexA of length count is compared with the substring of strB //// // beginning at indexB of the same length. Case sensitivity is determined by the ignoreCase boolean. //// // //// public static int Compare( String strA, int indexA, String strB, int indexB, int length, bool ignoreCase ) //// { //// int lengthA = length; //// int lengthB = length; //// //// if(strA != null) //// { //// if(strA.Length - indexA < lengthA) //// { //// lengthA = (strA.Length - indexA); //// } //// } //// //// if(strB != null) //// { //// if(strB.Length - indexB < lengthB) //// { //// lengthB = (strB.Length - indexB); //// } //// } //// //// if(ignoreCase) //// { //// return CultureInfo.CurrentCulture.CompareInfo.Compare( strA, indexA, lengthA, strB, indexB, lengthB, CompareOptions.IgnoreCase ); //// } //// else //// { //// return CultureInfo.CurrentCulture.CompareInfo.Compare( strA, indexA, lengthA, strB, indexB, lengthB, CompareOptions.None ); //// } //// } //// //// // Determines whether two string regions match. The substring of strA beginning //// // at indexA of length length is compared with the substring of strB //// // beginning at indexB of the same length. Case sensitivity is determined by the ignoreCase boolean, //// // and the culture is set by culture. //// // //// public static int Compare( String strA, int indexA, String strB, int indexB, int length, bool ignoreCase, CultureInfo culture ) //// { //// if(culture == null) //// { //// throw new ArgumentNullException( "culture" ); //// } //// //// int lengthA = length; //// int lengthB = length; //// //// if(strA != null) //// { //// if(strA.Length - indexA < lengthA) //// { //// lengthA = (strA.Length - indexA); //// } //// } //// //// if(strB != null) //// { //// if(strB.Length - indexB < lengthB) //// { //// lengthB = (strB.Length - indexB); //// } //// } //// //// if(ignoreCase) //// { //// return culture.CompareInfo.Compare( strA, indexA, lengthA, strB, indexB, lengthB, CompareOptions.IgnoreCase ); //// } //// else //// { //// return culture.CompareInfo.Compare( strA, indexA, lengthA, strB, indexB, lengthB, CompareOptions.None ); //// } //// } //// //// public static int Compare( String strA, int indexA, String strB, int indexB, int length, StringComparison comparisonType ) //// { //// if(comparisonType < StringComparison.CurrentCulture || comparisonType > StringComparison.OrdinalIgnoreCase) //// { //// throw new ArgumentException( Environment.GetResourceString( "NotSupported_StringComparison" ), "comparisonType" ); //// } //// //// if(strA == null || strB == null) //// { //// if((Object)strA == (Object)strB) //// { //they're both null; //// return 0; //// } //// //// return (strA == null) ? -1 : 1; //-1 if A is null, 1 if B is null. //// } //// //// if(length < 0) //// { //// throw new ArgumentOutOfRangeException( "length", Environment.GetResourceString( "ArgumentOutOfRange_NegativeLength" ) ); //// } //// //// if(indexA < 0) //// { //// throw new ArgumentOutOfRangeException( "indexA", Environment.GetResourceString( "ArgumentOutOfRange_Index" ) ); //// } //// //// if(indexB < 0) //// { //// throw new ArgumentOutOfRangeException( "indexB", Environment.GetResourceString( "ArgumentOutOfRange_Index" ) ); //// } //// //// if(strA.Length - indexA < 0) //// { //// throw new ArgumentOutOfRangeException( "indexA", Environment.GetResourceString( "ArgumentOutOfRange_Index" ) ); //// } //// //// if(strB.Length - indexB < 0) //// { //// throw new ArgumentOutOfRangeException( "indexB", Environment.GetResourceString( "ArgumentOutOfRange_Index" ) ); //// } //// //// if((length == 0) || ((strA == strB) && (indexA == indexB))) //// { //// return 0; //// } //// //// int lengthA = length; //// int lengthB = length; //// //// if(strA != null) //// { //// if(strA.Length - indexA < lengthA) //// { //// lengthA = (strA.Length - indexA); //// } //// } //// //// if(strB != null) //// { //// if(strB.Length - indexB < lengthB) //// { //// lengthB = (strB.Length - indexB); //// } //// } //// //// switch(comparisonType) //// { //// case StringComparison.CurrentCulture: //// return CultureInfo.CurrentCulture.CompareInfo.Compare( strA, indexA, lengthA, strB, indexB, lengthB, CompareOptions.None ); //// //// case StringComparison.CurrentCultureIgnoreCase: //// return CultureInfo.CurrentCulture.CompareInfo.Compare( strA, indexA, lengthA, strB, indexB, lengthB, CompareOptions.IgnoreCase ); //// //// case StringComparison.InvariantCulture: //// return CultureInfo.InvariantCulture.CompareInfo.Compare( strA, indexA, lengthA, strB, indexB, lengthB, CompareOptions.None ); //// //// case StringComparison.InvariantCultureIgnoreCase: //// return CultureInfo.InvariantCulture.CompareInfo.Compare( strA, indexA, lengthA, strB, indexB, lengthB, CompareOptions.IgnoreCase ); //// //// case StringComparison.Ordinal: //// return nativeCompareOrdinalEx( strA, indexA, strB, indexB, length ); //// //// case StringComparison.OrdinalIgnoreCase: //// return (TextInfo.CompareOrdinalIgnoreCaseEx( strA, indexA, strB, indexB, length )); //// //// default: //// throw new ArgumentException( Environment.GetResourceString( "NotSupported_StringComparison" ) ); //// } //// //// } // Compares this object to another object, returning an integer that // indicates the relationship. This method returns a value less than 0 if this is less than value, 0 // if this is equal to value, or a value greater than 0 // if this is greater than value. Strings are considered to be // greater than all non-String objects. Note that this means sorted // arrays would contain nulls, other objects, then Strings in that order. // public int CompareTo( Object value ) { if(value == null) { return 1; } if(!(value is String)) { #if EXCEPTION_STRINGS throw new ArgumentException( Environment.GetResourceString( "Arg_MustBeString" ) ); #else throw new ArgumentException(); #endif } return CompareTo( (String)value ); } // Determines the sorting relation of StrB to the current instance. // public int CompareTo( String strB ) { if(strB == null) { return 1; } return CultureInfo.CurrentCulture.CompareInfo.Compare( this, strB, 0 ); } // Compares strA and strB using an ordinal (code-point) comparison. // public static int CompareOrdinal( String strA, String strB ) { if((Object)strA == (Object)strB) { return 0; } //they can't both be null; if(strA == null) { return -1; } if(strB == null) { return 1; } return CompareOrdinalHelper( strA, strB ); } // Compares strA and strB using an ordinal (code-point) comparison. // public static int CompareOrdinal( String strA, int indexA, String strB, int indexB, int length ) { if(strA == null || strB == null) { if((Object)strA == (Object)strB) { //they're both null; return 0; } return (strA == null) ? -1 : 1; //-1 if A is null, 1 if B is null. } return nativeCompareOrdinalEx( strA, indexA, strB, indexB, length ); } public bool Contains( string value ) { return (IndexOf( value, StringComparison.Ordinal ) >= 0); } // Determines whether a specified string is a suffix of the the current instance. // // The case-sensitive and culture-sensitive option is set by options, // and the default culture is used. // public Boolean EndsWith( String value ) { return EndsWith( value, false, null ); } public Boolean EndsWith( String value, StringComparison comparisonType ) { if((Object)value == null) { #if EXCEPTION_STRINGS throw new ArgumentNullException( "value" ); #else throw new ArgumentNullException(); #endif } if(comparisonType < StringComparison.CurrentCulture || comparisonType > StringComparison.OrdinalIgnoreCase) { #if EXCEPTION_STRINGS throw new ArgumentException( Environment.GetResourceString( "NotSupported_StringComparison" ), "comparisonType" ); #else throw new ArgumentException(); #endif } if((Object)this == (Object)value) { return true; } if(value.Length == 0) { return true; } switch(comparisonType) { case StringComparison.CurrentCulture: return CultureInfo.CurrentCulture.CompareInfo.IsSuffix( this, value, CompareOptions.None ); case StringComparison.CurrentCultureIgnoreCase: return CultureInfo.CurrentCulture.CompareInfo.IsSuffix( this, value, CompareOptions.IgnoreCase ); case StringComparison.InvariantCulture: return CultureInfo.InvariantCulture.CompareInfo.IsSuffix( this, value, CompareOptions.None ); case StringComparison.InvariantCultureIgnoreCase: return CultureInfo.InvariantCulture.CompareInfo.IsSuffix( this, value, CompareOptions.IgnoreCase ); case StringComparison.Ordinal: return this.Length < value.Length ? false : (nativeCompareOrdinalEx( this, this.Length - value.Length, value, 0, value.Length ) == 0); //// case StringComparison.OrdinalIgnoreCase: //// return this.Length < value.Length ? false : (TextInfo.CompareOrdinalIgnoreCaseEx( this, this.Length - value.Length, value, 0, value.Length ) == 0); default: #if EXCEPTION_STRINGS throw new ArgumentException( Environment.GetResourceString( "NotSupported_StringComparison" ), "comparisonType" ); #else throw new ArgumentException(); #endif } } public Boolean EndsWith( String value, Boolean ignoreCase, CultureInfo culture ) { if(value == null) { #if EXCEPTION_STRINGS throw new ArgumentNullException( "value" ); #else throw new ArgumentNullException(); #endif } if((object)this == (object)value) { return true; } CultureInfo referenceCulture = (culture == null) ? CultureInfo.CurrentCulture : culture; return referenceCulture.CompareInfo.IsSuffix( this, value, ignoreCase ? CompareOptions.IgnoreCase : CompareOptions.None ); } //// internal bool EndsWith( char value ) //// { //// int thisLen = this.Length; //// if(thisLen != 0) //// { //// if(this[thisLen - 1] == value) //// { //// return true; //// } //// } //// //// return false; //// } // Returns the index of the first occurance of value in the current instance. // The search starts at startIndex and runs thorough the next count characters. // public int IndexOf( char value ) { return IndexOf( value, 0, this.Length ); } public int IndexOf( char value, int startIndex ) { return IndexOf( value, startIndex, this.Length - startIndex ); } //// [ResourceExposure( ResourceScope.None )] [MethodImpl( MethodImplOptions.InternalCall )] public extern int IndexOf( char value, int startIndex, int count ); // Returns the index of the first occurance of any character in value in the current instance. // The search starts at startIndex and runs to endIndex-1. [startIndex,endIndex). // public int IndexOfAny( char[] anyOf ) { return IndexOfAny( anyOf, 0, this.Length ); } public int IndexOfAny( char[] anyOf, int startIndex ) { return IndexOfAny( anyOf, startIndex, this.Length - startIndex ); } //// [ResourceExposure( ResourceScope.None )] [MethodImpl( MethodImplOptions.InternalCall )] public extern int IndexOfAny( char[] anyOf, int startIndex, int count ); // Determines the position within this string of the first occurence of the specified // string, according to the specified search criteria. The search begins at // the first character of this string, it is case-sensitive and culture-sensitive, // and the default culture is used. // public int IndexOf( String value ) { return CultureInfo.CurrentCulture.CompareInfo.IndexOf( this, value ); } // Determines the position within this string of the first occurence of the specified // string, according to the specified search criteria. The search begins at // startIndex, it is case-sensitive and culture-sensitve, and the default culture is used. // public int IndexOf( String value, int startIndex ) { return CultureInfo.CurrentCulture.CompareInfo.IndexOf( this, value, startIndex ); } // Determines the position within this string of the first occurence of the specified // string, according to the specified search criteria. The search begins at // startIndex, ends at endIndex and the default culture is used. // public int IndexOf( String value, int startIndex, int count ) { if(startIndex < 0 || startIndex > this.Length) { #if EXCEPTION_STRINGS throw new ArgumentOutOfRangeException( "startIndex", Environment.GetResourceString( "ArgumentOutOfRange_Index" ) ); #else throw new ArgumentOutOfRangeException(); #endif } if(count < 0 || count > this.Length - startIndex) { #if EXCEPTION_STRINGS throw new ArgumentOutOfRangeException( "count", Environment.GetResourceString( "ArgumentOutOfRange_Count" ) ); #else throw new ArgumentOutOfRangeException(); #endif } return CultureInfo.CurrentCulture.CompareInfo.IndexOf( this, value, startIndex, count, CompareOptions.None ); } public int IndexOf( String value, StringComparison comparisonType ) { return IndexOf( value, 0, this.Length, comparisonType ); } public int IndexOf( String value, int startIndex, StringComparison comparisonType ) { return IndexOf( value, startIndex, this.Length - startIndex, comparisonType ); } public int IndexOf( String value, int startIndex, int count, StringComparison comparisonType ) { // Validate inputs if(value == null) { #if EXCEPTION_STRINGS throw new ArgumentNullException( "value" ); #else throw new ArgumentNullException(); #endif } if(startIndex < 0 || startIndex > this.Length) { #if EXCEPTION_STRINGS throw new ArgumentOutOfRangeException( "startIndex", Environment.GetResourceString( "ArgumentOutOfRange_Index" ) ); #else throw new ArgumentOutOfRangeException(); #endif } if(count < 0 || startIndex > this.Length - count) { #if EXCEPTION_STRINGS throw new ArgumentOutOfRangeException( "count", Environment.GetResourceString( "ArgumentOutOfRange_Count" ) ); #else throw new ArgumentOutOfRangeException(); #endif } switch(comparisonType) { case StringComparison.CurrentCulture: return CultureInfo.CurrentCulture.CompareInfo.IndexOf( this, value, startIndex, count, CompareOptions.None ); case StringComparison.CurrentCultureIgnoreCase: return CultureInfo.CurrentCulture.CompareInfo.IndexOf( this, value, startIndex, count, CompareOptions.IgnoreCase ); case StringComparison.InvariantCulture: return CultureInfo.InvariantCulture.CompareInfo.IndexOf( this, value, startIndex, count, CompareOptions.None ); case StringComparison.InvariantCultureIgnoreCase: return CultureInfo.InvariantCulture.CompareInfo.IndexOf( this, value, startIndex, count, CompareOptions.IgnoreCase ); case StringComparison.Ordinal: return CultureInfo.InvariantCulture.CompareInfo.IndexOf( this, value, startIndex, count, CompareOptions.Ordinal ); //// case StringComparison.OrdinalIgnoreCase: //// return TextInfo.IndexOfStringOrdinalIgnoreCase( this, value, startIndex, count ); default: #if EXCEPTION_STRINGS throw new ArgumentException( Environment.GetResourceString( "NotSupported_StringComparison" ), "comparisonType" ); #else throw new ArgumentException(); #endif } } // Returns the index of the last occurance of value in the current instance. // The search starts at startIndex and runs to endIndex. [startIndex,endIndex]. // The character at position startIndex is included in the search. startIndex is the larger // index within the string. // public int LastIndexOf( char value ) { return LastIndexOf( value, this.Length - 1, this.Length ); } public int LastIndexOf( char value, int startIndex ) { return LastIndexOf( value, startIndex, startIndex + 1 ); } //// [ResourceExposure( ResourceScope.None )] [MethodImpl( MethodImplOptions.InternalCall )] public extern int LastIndexOf( char value, int startIndex, int count ); //// // Returns the index of the last occurance of any character in value in the current instance. //// // The search starts at startIndex and runs to endIndex. [startIndex,endIndex]. //// // The character at position startIndex is included in the search. startIndex is the larger //// // index within the string. //// // //// //// public int LastIndexOfAny( char[] anyOf ) //// { //// return LastIndexOfAny( anyOf, this.Length - 1, this.Length ); //// } //// //// public int LastIndexOfAny( char[] anyOf, int startIndex ) //// { //// return LastIndexOfAny( anyOf, startIndex, startIndex + 1 ); //// } //// //// [ResourceExposure( ResourceScope.None )] //// [MethodImpl( MethodImplOptions.InternalCall )] //// public extern int LastIndexOfAny( char[] anyOf, int startIndex, int count ); //// //// //// // Returns the index of the last occurance of any character in value in the current instance. //// // The search starts at startIndex and runs to endIndex. [startIndex,endIndex]. //// // The character at position startIndex is included in the search. startIndex is the larger //// // index within the string. //// // //// public int LastIndexOf( String value ) //// { //// return LastIndexOf( value, this.Length - 1, this.Length, StringComparison.CurrentCulture ); //// } //// //// public int LastIndexOf( String value, int startIndex ) //// { //// return LastIndexOf( value, startIndex, startIndex + 1, StringComparison.CurrentCulture ); //// } //// //// public int LastIndexOf( String value, int startIndex, int count ) //// { //// if(count < 0) //// { //// throw new ArgumentOutOfRangeException( "count", Environment.GetResourceString( "ArgumentOutOfRange_Count" ) ); //// } //// //// return CultureInfo.CurrentCulture.CompareInfo.LastIndexOf( this, value, startIndex, count, CompareOptions.None ); //// } //// //// public int LastIndexOf( String value, StringComparison comparisonType ) //// { //// return LastIndexOf( value, this.Length - 1, this.Length, comparisonType ); //// } //// //// public int LastIndexOf( String value, int startIndex, StringComparison comparisonType ) //// { //// return LastIndexOf( value, startIndex, startIndex + 1, comparisonType ); //// } //// //// public int LastIndexOf( String value, int startIndex, int count, StringComparison comparisonType ) //// { //// if(value == null) //// { //// throw new ArgumentNullException( "value" ); //// } //// //// // Special case for 0 length input strings //// if(this.Length == 0 && (startIndex == -1 || startIndex == 0)) //// { //// return (value.Length == 0) ? 0 : -1; //// } //// //// // Make sure we're not out of range //// if(startIndex < 0 || startIndex > this.Length) //// { //// throw new ArgumentOutOfRangeException( "startIndex", Environment.GetResourceString( "ArgumentOutOfRange_Index" ) ); //// } //// //// // Make sure that we allow startIndex == this.Length //// if(startIndex == this.Length) //// { //// startIndex--; //// if(count > 0) //// { //// count--; //// } //// //// // If we are looking for nothing, just return 0 //// if(value.Length == 0 && count >= 0 && startIndex - count + 1 >= 0) //// { //// return startIndex; //// } //// } //// //// // 2nd have of this also catches when startIndex == MAXINT, so MAXINT - 0 + 1 == -1, which is < 0. //// if(count < 0 || startIndex - count + 1 < 0) //// { //// throw new ArgumentOutOfRangeException( "count", Environment.GetResourceString( "ArgumentOutOfRange_Count" ) ); //// } //// //// //// switch(comparisonType) //// { //// case StringComparison.CurrentCulture: //// return CultureInfo.CurrentCulture.CompareInfo.LastIndexOf( this, value, startIndex, count, CompareOptions.None ); //// //// case StringComparison.CurrentCultureIgnoreCase: //// return CultureInfo.CurrentCulture.CompareInfo.LastIndexOf( this, value, startIndex, count, CompareOptions.IgnoreCase ); //// //// case StringComparison.InvariantCulture: //// return CultureInfo.InvariantCulture.CompareInfo.LastIndexOf( this, value, startIndex, count, CompareOptions.None ); //// //// case StringComparison.InvariantCultureIgnoreCase: //// return CultureInfo.InvariantCulture.CompareInfo.LastIndexOf( this, value, startIndex, count, CompareOptions.IgnoreCase ); //// //// case StringComparison.Ordinal: //// return CultureInfo.InvariantCulture.CompareInfo.LastIndexOf( this, value, startIndex, count, CompareOptions.Ordinal ); //// //// case StringComparison.OrdinalIgnoreCase: //// return TextInfo.LastIndexOfStringOrdinalIgnoreCase( this, value, startIndex, count ); //// //// default: //// throw new ArgumentException( Environment.GetResourceString( "NotSupported_StringComparison" ), "comparisonType" ); //// } //// } //// //// // //// // //// public String PadLeft( int totalWidth ) //// { //// return PadHelper( totalWidth, ' ', false ); //// } //// //// public String PadLeft( int totalWidth, char paddingChar ) //// { //// return PadHelper( totalWidth, paddingChar, false ); //// } //// //// public String PadRight( int totalWidth ) //// { //// return PadHelper( totalWidth, ' ', true ); //// } //// //// public String PadRight( int totalWidth, char paddingChar ) //// { //// return PadHelper( totalWidth, paddingChar, true ); //// } //// //// //// [ResourceExposure( ResourceScope.None )] //// [MethodImpl( MethodImplOptions.InternalCall )] //// private extern String PadHelper( int totalWidth, char paddingChar, bool isRightPadded ); // Determines whether a specified string is a prefix of the current instance // public Boolean StartsWith( String value ) { return StartsWith( value, false, null ); } public Boolean StartsWith( String value, StringComparison comparisonType ) { if((Object)value == null) { #if EXCEPTION_STRINGS throw new ArgumentNullException( "value" ); #else throw new ArgumentNullException(); #endif } if(comparisonType < StringComparison.CurrentCulture || comparisonType > StringComparison.OrdinalIgnoreCase) { #if EXCEPTION_STRINGS throw new ArgumentException( Environment.GetResourceString( "NotSupported_StringComparison" ), "comparisonType" ); #else throw new ArgumentException(); #endif } if((Object)this == (Object)value) { return true; } if(value.Length == 0) { return true; } switch(comparisonType) { case StringComparison.CurrentCulture: return CultureInfo.CurrentCulture.CompareInfo.IsPrefix( this, value, CompareOptions.None ); case StringComparison.CurrentCultureIgnoreCase: return CultureInfo.CurrentCulture.CompareInfo.IsPrefix( this, value, CompareOptions.IgnoreCase ); case StringComparison.InvariantCulture: return CultureInfo.InvariantCulture.CompareInfo.IsPrefix( this, value, CompareOptions.None ); case StringComparison.InvariantCultureIgnoreCase: return CultureInfo.InvariantCulture.CompareInfo.IsPrefix( this, value, CompareOptions.IgnoreCase ); case StringComparison.Ordinal: if(this.Length < value.Length) { return false; } return (nativeCompareOrdinalEx( this, 0, value, 0, value.Length ) == 0); //// case StringComparison.OrdinalIgnoreCase: //// if(this.Length < value.Length) //// { //// return false; //// } //// //// return (TextInfo.CompareOrdinalIgnoreCaseEx( this, 0, value, 0, value.Length ) == 0); default: #if EXCEPTION_STRINGS throw new ArgumentException( Environment.GetResourceString( "NotSupported_StringComparison" ), "comparisonType" ); #else throw new ArgumentException(); #endif } } public Boolean StartsWith( String value, Boolean ignoreCase, CultureInfo culture ) { if(value == null) { #if EXCEPTION_STRINGS throw new ArgumentNullException( "value" ); #else throw new ArgumentNullException(); #endif } if((object)this == (object)value) { return true; } CultureInfo referenceCulture = (culture == null) ? CultureInfo.CurrentCulture : culture; return referenceCulture.CompareInfo.IsPrefix( this, value, ignoreCase ? CompareOptions.IgnoreCase : CompareOptions.None ); } // Creates a copy of this string in lower case. public String ToLower() { return this.ToLower( CultureInfo.CurrentCulture ); } // Creates a copy of this string in lower case. The culture is set by culture. public String ToLower( CultureInfo culture ) { if(culture == null) { #if EXCEPTION_STRINGS throw new ArgumentNullException( "culture" ); #else throw new ArgumentNullException(); #endif } return culture.TextInfo.ToLower( this ); } // Creates a copy of this string in lower case based on invariant culture. public String ToLowerInvariant() { return this.ToLower( CultureInfo.InvariantCulture ); } // Creates a copy of this string in upper case. public String ToUpper() { return this.ToUpper( CultureInfo.CurrentCulture ); } // Creates a copy of this string in upper case. The culture is set by culture. public String ToUpper( CultureInfo culture ) { if(culture == null) { #if EXCEPTION_STRINGS throw new ArgumentNullException( "culture" ); #else throw new ArgumentNullException(); #endif } return culture.TextInfo.ToUpper( this ); } //Creates a copy of this string in upper case based on invariant culture. public String ToUpperInvariant() { return this.ToUpper( CultureInfo.InvariantCulture ); } // Returns this string. public override String ToString() { return this; } public String ToString( IFormatProvider provider ) { return this; } // Method required for the ICloneable interface. // There's no point in cloning a string since they're immutable, so we simply return this. public Object Clone() { return this; } // Trims the whitespace from both ends of the string. Whitespace is defined by // CharacterInfo.WhitespaceChars. // public String Trim() { return TrimHelper( WhitespaceChars, TrimBoth ); } private String TrimHelper( char[] trimChars, int trimType ) { //end will point to the first non-trimmed character on the right //start will point to the first non-trimmed character on the Left int end = this.Length - 1; int start = 0; //Trim specified characters. if(trimType != TrimTail) { for(start = 0; start < this.Length; start++) { int i = 0; char ch = this[start]; for(i = 0; i < trimChars.Length; i++) { if(trimChars[i] == ch) break; } if(i == trimChars.Length) { // the character is not white space break; } } } if(trimType != TrimHead) { for(end = Length - 1; end >= start; end--) { int i = 0; char ch = this[end]; for(i = 0; i < trimChars.Length; i++) { if(trimChars[i] == ch) break; } if(i == trimChars.Length) { // the character is not white space break; } } } //Create a new STRINGREF and initialize it from the range determined above. int len = end - start + 1; if(len == this.Length) { // Don't allocate a new string is the trimmed string has not changed. return this; } else { if(len == 0) { return String.Empty; } return InternalSubString( start, len, false ); } } //// // //// // //// [ResourceExposure( ResourceScope.None )] //// [MethodImpl( MethodImplOptions.InternalCall )] //// public extern String Insert( int startIndex, String value ); //// //// // Replaces all instances of oldChar with newChar. //// // //// [ResourceExposure( ResourceScope.None )] //// [MethodImpl( MethodImplOptions.InternalCall )] public String Replace( char oldChar, char newChar ) { StringBuilder sb = new StringBuilder( this.Length ); for(var i = 0; i< Length; ++i) { char c = this[ i ]; sb.Append( c == oldChar ? newChar : c ); } return sb.ToString(); } // This method contains the same functionality as StringBuilder Replace. The only difference is that // a new String has to be allocated since Strings are immutable ////[ResourceExposure( ResourceScope.None )] ////[MethodImpl( MethodImplOptions.InternalCall )] public String Replace( String oldValue, String newValue ) { var srcString = this; var srcLength = srcString.Length; var oldValueLength = oldValue .Length; var newValueLength = newValue .Length; var indexes = FindAllOccurrences( srcString, oldValue, 0, srcLength ); int occurrences = indexes.Count; // // Allocate a string to contain the final result and fill it in place // if(occurrences > 0) { // // Allocate the new string, with the exact size needed // var dstString = new String( '\0', srcLength - (occurrences * (oldValueLength - newValueLength)) + 1 ); ReplaceStringInPlace( srcString, dstString, newValue, indexes, oldValueLength, newValueLength ); dstString.NullTerminate( ); return dstString; } return this; } internal static List FindAllOccurrences( String srcString, String value, int startIndex, int count ) { var srcLength = srcString.Length; var oldValueLength = value .Length; var indexes = new List(); if(count >= oldValueLength && startIndex < srcLength) { // // Find all occurences of the string to be replaced // int charIdx = startIndex; int endIdx = startIndex + count - oldValueLength; while(charIdx <= endIdx && count >= oldValueLength) { var charIdx2 = srcString.IndexOf( value, charIdx, count ); if(charIdx2 == -1) { break; } indexes.Add( charIdx2 ); count -= ( charIdx2 - charIdx + oldValueLength ); charIdx = charIdx2 + oldValueLength; } } return indexes; } internal static unsafe void ReplaceStringInPlace( String srcString, String dstString, String newValue, List indexes, int oldValueLength, int newValueLength ) { int occurrences = indexes.Count; if(occurrences > 0) { fixed (char* srcStringPtr = &srcString.m_firstChar) fixed (char* dstStringPtr = &dstString.m_firstChar) fixed (char* newValuePtr = &newValue.m_firstChar) { var currentIdx = 0; var srcCharIdx = 0; var dstCharIdx = 0; do { int charIdx = indexes[ currentIdx ]; var charCount = charIdx - srcCharIdx; Buffer.InternalMemoryCopy( srcStringPtr + srcCharIdx, dstStringPtr + dstCharIdx, charCount ); srcCharIdx += charCount; dstCharIdx += charCount; Buffer.InternalMemoryCopy( newValuePtr, dstStringPtr + dstCharIdx, newValueLength ); srcCharIdx += oldValueLength; dstCharIdx += newValueLength; ++currentIdx; } while(currentIdx < occurrences); Buffer.InternalMemoryCopy( srcStringPtr + srcCharIdx, dstStringPtr + dstCharIdx, srcString.Length - srcCharIdx ); } } } //// //// // //// // //// [ResourceExposure( ResourceScope.None )] //// [MethodImpl( MethodImplOptions.InternalCall )] //// public extern String Remove( int startIndex, int count ); //// //// //// // a remove that just takes a startindex. //// public string Remove( int startIndex ) //// { //// if(startIndex < 0) //// { //// throw new ArgumentOutOfRangeException( "startIndex", Environment.GetResourceString( "ArgumentOutOfRange_StartIndex" ) ); //// } //// //// if(startIndex >= Length) //// { //// throw new ArgumentOutOfRangeException( "startIndex", Environment.GetResourceString( "ArgumentOutOfRange_StartIndexLessThanLength" ) ); //// } //// //// return Substring( 0, startIndex ); //// } public static String Format( String format, Object arg0 ) { return Format( null, format, new Object[] { arg0 } ); } public static String Format( String format, Object arg0, Object arg1 ) { return Format( null, format, new Object[] { arg0, arg1 } ); } public static String Format( String format, Object arg0, Object arg1, Object arg2 ) { return Format( null, format, new Object[] { arg0, arg1, arg2 } ); } public static String Format( String format, params Object[] args ) { return Format( null, format, args ); } public static String Format( IFormatProvider provider, String format, params Object[] args ) { if(format == null || args == null) { #if EXCEPTION_STRINGS throw new ArgumentNullException( (format == null) ? "format" : "args" ); #else throw new ArgumentNullException(); #endif } StringBuilder sb = new StringBuilder( format.Length + args.Length * 8 ); sb.AppendFormat( provider, format, args ); return sb.ToString(); } unsafe public static String Copy( String str ) { if(str == null) { #if EXCEPTION_STRINGS throw new ArgumentNullException( "str" ); #else throw new ArgumentNullException(); #endif } int length = str.Length; String result = FastAllocateString( length ); fixed(char* dest = &result.m_firstChar) { fixed(char* src = &str.m_firstChar) { Buffer.InternalMemoryCopy( src, dest, length ); } } return result; } // Used by StringBuilder to avoid data corruption unsafe internal static String InternalCopy( String str ) { int length = str.Length; String result = FastAllocateString( length ); // The underlying's String can changed length is StringBuilder fixed(char* dest = &result.m_firstChar) { fixed(char* src = &str.m_firstChar) { Buffer.InternalMemoryCopy( src, dest, length ); } } return result; } public static String Concat( Object arg0 ) { if(arg0 == null) { return String.Empty; } return arg0.ToString(); } public static String Concat( Object arg0, Object arg1 ) { if(arg0 == null) { arg0 = String.Empty; } if(arg1 == null) { arg1 = String.Empty; } return Concat( arg0.ToString(), arg1.ToString() ); } public static String Concat( Object arg0, Object arg1, Object arg2 ) { if(arg0 == null) { arg0 = String.Empty; } if(arg1 == null) { arg1 = String.Empty; } if(arg2 == null) { arg2 = String.Empty; } return Concat( arg0.ToString(), arg1.ToString(), arg2.ToString() ); } //// [CLSCompliant( false )] //// public static String Concat( Object arg0, Object arg1, Object arg2, Object arg3, __arglist ) //// { //// Object[] objArgs; //// int argCount; //// //// ArgIterator args = new ArgIterator( __arglist ); //// //// //+4 to account for the 4 hard-coded arguments at the beginning of the list. //// argCount = args.GetRemainingCount() + 4; //// //// objArgs = new Object[argCount]; //// //// //Handle the hard-coded arguments //// objArgs[0] = arg0; //// objArgs[1] = arg1; //// objArgs[2] = arg2; //// objArgs[3] = arg3; //// //// //Walk all of the args in the variable part of the argument list. //// for(int i = 4; i < argCount; i++) //// { //// objArgs[i] = TypedReference.ToObject( args.GetNextArg() ); //// } //// //// return Concat( objArgs ); //// } public static String Concat( params Object[] args ) { if(args == null) { #if EXCEPTION_STRINGS throw new ArgumentNullException( "args" ); #else throw new ArgumentNullException(); #endif } String[] sArgs = new String[args.Length]; int totalLength = 0; for(int i = 0; i < args.Length; i++) { object value = args[i]; sArgs[i] = ((value == null) ? (String.Empty) : (value.ToString())); totalLength += sArgs[i].Length; // check for overflow if(totalLength < 0) { throw new OutOfMemoryException(); } } return ConcatArray( sArgs, totalLength ); } public static String Concat( String str0, String str1 ) { if(IsNullOrEmpty( str0 )) { if(IsNullOrEmpty( str1 )) { return String.Empty; } return str1; } if(IsNullOrEmpty( str1 )) { return str0; } int str0Length = str0.Length; String result = FastAllocateString( str0Length + str1.Length ); FillStringChecked( result, 0 , str0 ); FillStringChecked( result, str0Length, str1 ); return result; } public static String Concat( String str0, String str1, String str2 ) { if(str0 == null && str1 == null && str2 == null) { return String.Empty; } if(str0 == null) { str0 = String.Empty; } if(str1 == null) { str1 = String.Empty; } if(str2 == null) { str2 = String.Empty; } int totalLength = str0.Length + str1.Length + str2.Length; String result = FastAllocateString( totalLength ); FillStringChecked( result, 0 , str0 ); FillStringChecked( result, str0.Length , str1 ); FillStringChecked( result, str0.Length + str1.Length, str2 ); return result; } public static String Concat( String str0, String str1, String str2, String str3 ) { if(str0 == null && str1 == null && str2 == null && str3 == null) { return String.Empty; } if(str0 == null) { str0 = String.Empty; } if(str1 == null) { str1 = String.Empty; } if(str2 == null) { str2 = String.Empty; } if(str3 == null) { str3 = String.Empty; } int totalLength = str0.Length + str1.Length + str2.Length + str3.Length; String result = FastAllocateString( totalLength ); FillStringChecked( result, 0 , str0 ); FillStringChecked( result, str0.Length , str1 ); FillStringChecked( result, str0.Length + str1.Length , str2 ); FillStringChecked( result, str0.Length + str1.Length + str2.Length, str3 ); return result; } private static String ConcatArray( String[] values, int totalLength ) { String result = FastAllocateString( totalLength ); int currPos = 0; for(int i = 0; i < values.Length; i++) { BCLDebug.Assert( (currPos <= totalLength - values[i].Length), "[String.ConcatArray](currPos <= totalLength - values[i].Length)" ); FillStringChecked( result, currPos, values[i] ); currPos += values[i].Length; } return result; } public static String Concat( params String[] values ) { int totalLength = 0; if(values == null) { #if EXCEPTION_STRINGS throw new ArgumentNullException( "values" ); #else throw new ArgumentNullException(); #endif } // Always make a copy to prevent changing the array on another thread. String[] internalValues = new String[values.Length]; for(int i = 0; i < values.Length; i++) { string value = values[i]; internalValues[i] = ((value == null) ? (String.Empty) : (value)); totalLength += internalValues[i].Length; // check for overflow if(totalLength < 0) { throw new OutOfMemoryException(); } } return ConcatArray( internalValues, totalLength ); } public static String Intern( String str ) { return str; // BUGBUG: Should we implement interning? //// if(str == null) //// { //// throw new ArgumentNullException( "str" ); //// } //// //// return Thread.GetDomain().GetOrInternString( str ); } public static String IsInterned( String str ) { return str; // BUGBUG: Should we implement interning? //// if(str == null) //// { //// throw new ArgumentNullException( "str" ); //// } //// return Thread.GetDomain().IsStringInterned( str ); } #region IConvertible public TypeCode GetTypeCode() { return TypeCode.String; } /// bool IConvertible.ToBoolean( IFormatProvider provider ) { return Convert.ToBoolean( this, provider ); } /// char IConvertible.ToChar( IFormatProvider provider ) { return Convert.ToChar( this, provider ); } /// sbyte IConvertible.ToSByte( IFormatProvider provider ) { return Convert.ToSByte( this, provider ); } /// byte IConvertible.ToByte( IFormatProvider provider ) { return Convert.ToByte( this, provider ); } /// short IConvertible.ToInt16( IFormatProvider provider ) { return Convert.ToInt16( this, provider ); } /// ushort IConvertible.ToUInt16( IFormatProvider provider ) { return Convert.ToUInt16( this, provider ); } /// int IConvertible.ToInt32( IFormatProvider provider ) { return Convert.ToInt32( this, provider ); } /// uint IConvertible.ToUInt32( IFormatProvider provider ) { return Convert.ToUInt32( this, provider ); } /// long IConvertible.ToInt64( IFormatProvider provider ) { return Convert.ToInt64( this, provider ); } /// ulong IConvertible.ToUInt64( IFormatProvider provider ) { return Convert.ToUInt64( this, provider ); } /// float IConvertible.ToSingle( IFormatProvider provider ) { return Convert.ToSingle( this, provider ); } /// double IConvertible.ToDouble( IFormatProvider provider ) { return Convert.ToDouble( this, provider ); } /// Decimal IConvertible.ToDecimal( IFormatProvider provider ) { return Convert.ToDecimal( this, provider ); } /// DateTime IConvertible.ToDateTime( IFormatProvider provider ) { return Convert.ToDateTime( this, provider ); } /// Object IConvertible.ToType( Type type, IFormatProvider provider ) { return Convert.DefaultToType( (IConvertible)this, type, provider ); } #endregion //// // Is this a string that can be compared quickly (that is it has only characters > 0x80 //// // and not a - or ' //// [ResourceExposure( ResourceScope.None )] //// [MethodImpl( MethodImplOptions.InternalCall )] //// internal extern bool IsFastSort(); //// //// // Is this a string that only contains characters < 0x80. //// [ResourceExposure( ResourceScope.None )] [MethodImpl( MethodImplOptions.InternalCall )] internal extern bool IsAscii(); /// unsafe internal void SetChar( int index, char value ) { #if _DEBUG BCLDebug.Assert( ValidModifiableString(), "Modifiable string must not have highChars flags set" ); #endif //Bounds check and then set the actual bit. if((UInt32)index >= (UInt32)Length) { #if EXCEPTION_STRINGS throw new ArgumentOutOfRangeException( "index", Environment.GetResourceString( "ArgumentOutOfRange_Index" ) ); #else throw new ArgumentOutOfRangeException(); #endif } fixed(char* p = &this.m_firstChar) { // Set the character. p[index] = value; } } #if _DEBUG // Only used in debug build. Insure that the HighChar state information for a string is not set as known [ResourceExposure( ResourceScope.None )] [MethodImpl( MethodImplOptions.InternalCall )] private extern bool ValidModifiableString(); #endif /// unsafe internal void AppendInPlace( char value, int currentLength ) { BCLDebug.Assert( currentLength < m_arrayLength, "[String.AppendInPlace]currentLength < m_arrayLength" ); #if _DEBUG BCLDebug.Assert( ValidModifiableString(), "Modifiable string must not have highChars flags set" ); #endif fixed(char* p = &this.m_firstChar) { // Append the character. p[currentLength] = value; currentLength++; p[currentLength] = '\0'; m_stringLength = currentLength; } } /// unsafe internal void AppendInPlace( char value, int repeatCount, int currentLength ) { int newLength = currentLength + repeatCount; BCLDebug.Assert( newLength < m_arrayLength, "[String.AppendInPlace]currentLength+repeatCount < m_arrayLength" ); #if _DEBUG BCLDebug.Assert( ValidModifiableString(), "Modifiable string must not have highChars flags set" ); #endif fixed(char* p = &this.m_firstChar) { int i; for(i = currentLength; i < newLength; i++) { p[i] = value; } p[i] = '\0'; } this.m_stringLength = newLength; } /// internal unsafe void AppendInPlace( String value, int currentLength ) { int count = value.Length; int newLength = currentLength + count; BCLDebug.Assert( value != null, "[String.AppendInPlace]value!=null" ); BCLDebug.Assert( newLength < this.m_arrayLength, "[String.AppendInPlace]Length is wrong." ); #if _DEBUG BCLDebug.Assert( ValidModifiableString(), "Modifiable string must not have highChars flags set" ); #endif fixed(char* dest = &this.m_firstChar) { fixed(char* src = &value.m_firstChar) { Buffer.InternalMemoryCopy( src, dest + currentLength, count ); } dest[newLength] = '\0'; } this.m_stringLength = newLength; } internal unsafe void AppendInPlace( String value, int startIndex, int count, int currentLength ) { int newLength = currentLength + count; BCLDebug.Assert( value != null , "[String.AppendInPlace]value!=null" ); BCLDebug.Assert( newLength < this.m_arrayLength , "[String.AppendInPlace]newLength < this.m_arrayLength" ); BCLDebug.Assert( count >= 0 , "[String.AppendInPlace]count>=0" ); BCLDebug.Assert( startIndex >= 0 , "[String.AppendInPlace]startIndex>=0" ); BCLDebug.Assert( startIndex <= (value.Length - count), "[String.AppendInPlace]startIndex <= (value.Length - count)" ); #if _DEBUG BCLDebug.Assert( ValidModifiableString(), "Modifiable string must not have highChars flags set" ); #endif fixed(char* dest = &this.m_firstChar) { fixed(char* src = &value.m_firstChar) { Buffer.InternalMemoryCopy( src + startIndex, dest + currentLength, count ); } dest[newLength] = '\0'; } this.m_stringLength = newLength; } internal unsafe void AppendInPlace( char* value, int count, int currentLength ) { int newLength = currentLength + count; BCLDebug.Assert( value != null , "[String.AppendInPlace]value!=null" ); BCLDebug.Assert( newLength < this.m_arrayLength, "[String.AppendInPlace]newLength < this.m_arrayLength" ); BCLDebug.Assert( count >= 0 , "[String.AppendInPlace]count>=0" ); #if _DEBUG BCLDebug.Assert(ValidModifiableString(), "Modifiable string must not have highChars flags set"); #endif fixed(char* p = &this.m_firstChar) { Buffer.InternalMemoryCopy( value, p + currentLength, count ); p[newLength] = '\0'; } this.m_stringLength = newLength; } /// internal unsafe void AppendInPlace( char[] value, int start, int count, int currentLength ) { int newLength = currentLength + count; BCLDebug.Assert( value != null, "[String.AppendInPlace]value!=null" ); BCLDebug.Assert( newLength < this.m_arrayLength, "[String.AppendInPlace]Length is wrong." ); BCLDebug.Assert( value.Length - count >= start, "[String.AppendInPlace]value.Length-count>=start" ); #if _DEBUG BCLDebug.Assert(ValidModifiableString(), "Modifiable string must not have highChars flags set"); #endif fixed(char* dest = &this.m_firstChar) { // Note: fixed does not like empty arrays if(count > 0) { fixed(char* src = value) { Buffer.InternalMemoryCopy( src + start, dest + currentLength, count ); } } dest[newLength] = '\0'; } this.m_stringLength = newLength; } /// unsafe internal void ReplaceCharInPlace( char oldChar, char newChar, int startIndex, int count, int currentLength ) { BCLDebug.Assert( startIndex >= 0 , "[String.ReplaceCharInPlace]startIndex>0" ); BCLDebug.Assert( startIndex <= currentLength , "[String.ReplaceCharInPlace]startIndex>=Length" ); BCLDebug.Assert( (startIndex <= currentLength - count), "[String.ReplaceCharInPlace]count>0 && startIndex<=currentLength-count" ); #if _DEBUG BCLDebug.Assert( ValidModifiableString(), "Modifiable string must not have highChars flags set" ); #endif int endIndex = startIndex + count; fixed(char* p = &this.m_firstChar) { for(int i = startIndex; i < endIndex; i++) { if(p[i] == oldChar) { p[i] = newChar; } } } } /// internal static String GetStringForStringBuilder( String value, int capacity ) { BCLDebug.Assert( value != null, "[String.GetStringForStringBuilder]value!=null" ); return GetStringForStringBuilder( value, 0, value.Length, capacity ); } /// unsafe internal static String GetStringForStringBuilder( String value, int startIndex, int length, int capacity ) { BCLDebug.Assert( value != null , "[String.GetStringForStringBuilder]value!=null" ); BCLDebug.Assert( capacity >= length, "[String.GetStringForStringBuilder]capacity>=length" ); String newStr = FastAllocateString( capacity ); if(value.Length == 0) { newStr.SetLength( 0 ); // already null terminated return newStr; } fixed(char* dest = &newStr.m_firstChar) { fixed(char* src = &value.m_firstChar) { Buffer.InternalMemoryCopy( src + startIndex, dest, length ); } } newStr.SetLength( length ); // already null terminated return newStr; } /// internal unsafe void NullTerminate() { fixed(char* p = &this.m_firstChar) { p[m_stringLength] = '\0'; } } /// unsafe internal void ClearPostNullChar() { int newLength = Length + 1; if(newLength < m_arrayLength) { fixed(char* p = &this.m_firstChar) { p[newLength] = '\0'; } } } /// internal void SetLength( int newLength ) { BCLDebug.Assert( newLength <= m_arrayLength, "newLength<=m_arrayLength" ); m_stringLength = newLength; } //// public CharEnumerator GetEnumerator() //// { //// BCLDebug.Perf( false, "Avoid using String's CharEnumerator until C# special cases foreach on String - use the indexed property on String instead." ); //// return new CharEnumerator( this ); //// } //// //// IEnumerator IEnumerable.GetEnumerator() //// { //// BCLDebug.Perf( false, "Avoid using String's CharEnumerator until C# special cases foreach on String - use the indexed property on String instead." ); //// return new CharEnumerator( this ); //// } //// //// /// //// IEnumerator IEnumerable.GetEnumerator() //// { //// BCLDebug.Perf( false, "Avoid using String's CharEnumerator until C# special cases foreach on String - use the indexed property on String instead." ); //// return new CharEnumerator( this ); //// } internal unsafe void InternalSetCharNoBoundsCheck( int index, char value ) { fixed(char* p = &this.m_firstChar) { p[index] = value; } } //// // Copies the source String (byte buffer) to the destination IntPtr memory allocated with len bytes. //// internal unsafe static void InternalCopy( String src, IntPtr dest, int len ) //// { //// if(len == 0) //// { //// return; //// } //// //// fixed(char* charPtr = &src.m_firstChar) //// { //// byte* srcPtr = (byte*)charPtr; //// byte* dstPtr = (byte*)dest.ToPointer(); //// //// Buffer.memcpyimpl( srcPtr, dstPtr, len ); //// } //// } // memcopies characters inside a String. internal unsafe static void InternalMemCpy( String src, int srcOffset, String dst, int destOffset, int len ) { if(len == 0) { return; } fixed(char* srcPtr = &src.m_firstChar) { fixed(char* dstPtr = &dst.m_firstChar) { Buffer.InternalMemoryCopy( srcPtr + srcOffset, dstPtr + destOffset, len ); } } } internal unsafe void InsertInPlace( int index, String value, int repeatCount, int currentLength, int requiredLength ) { BCLDebug.Assert( requiredLength < m_arrayLength , "[String.InsertString] requiredLength < m_arrayLength" ); BCLDebug.Assert( index >= 0 , "index >= 0" ); BCLDebug.Assert( value.Length * repeatCount < m_arrayLength - index, "[String.InsertString] value.Length * repeatCount < m_arrayLength - index" ); #if _DEBUG BCLDebug.Assert( ValidModifiableString(), "Modifiable string must not have highChars flags set" ); #endif //Copy the old characters over to make room and then insert the new characters. fixed(char* srcPtr = &this.m_firstChar) { fixed(char* valuePtr = &value.m_firstChar) { Buffer.InternalBackwardMemoryCopy( srcPtr + index, srcPtr + index + value.Length * repeatCount, currentLength - index ); for(int i = 0; i < repeatCount; i++) { Buffer.InternalMemoryCopy( valuePtr, srcPtr + index + i * value.Length, value.Length ); } } } SetLength( requiredLength ); NullTerminate(); } // Note InsertInPlace char[] has slightly different semantics than the one that takes a String. internal unsafe void InsertInPlace( int index , char[] value , int startIndex , int charCount , int currentLength , int requiredLength ) { BCLDebug.Assert( requiredLength < m_arrayLength , "[String.InsertInPlace] requiredLength < m_arrayLength" ); BCLDebug.Assert( startIndex >= 0 && index >= 0 , "startIndex >= 0 && index >= 0" ); BCLDebug.Assert( charCount <= value.Length - startIndex, "[String.InsertInPlace] charCount <= value.Length - startIndex" ); BCLDebug.Assert( charCount < m_arrayLength - index , "[String.InsertInPlace]charCount < m_arrayLength - index" ); #if _DEBUG BCLDebug.Assert( ValidModifiableString(), "Modifiable string must not have highChars flags set" ); #endif //Copy the old characters over to make room and then insert the new characters. fixed(char* srcPtr = &this.m_firstChar) { fixed(char* valuePtr = value) { Buffer.InternalBackwardMemoryCopy( srcPtr + index, srcPtr + index + charCount, currentLength - index ); Buffer.InternalMemoryCopy ( valuePtr + startIndex, srcPtr + index, charCount ); } } SetLength( requiredLength ); NullTerminate(); } internal unsafe void RemoveInPlace( int index, int charCount, int currentLength ) { BCLDebug.Assert( index >= 0, "index >= 0" ); BCLDebug.Assert( charCount < m_arrayLength - index, "[String.InsertInPlace]charCount < m_arrayLength - index" ); #if _DEBUG BCLDebug.Assert(ValidModifiableString(), "Modifiable string must not have highChars flags set"); #endif //Move the remaining characters to the left and set the string length. String.InternalMemCpy( this, index + charCount, this, index, currentLength - charCount - index ); int newLength = currentLength - charCount; SetLength( newLength ); NullTerminate(); //Null terminate. } } [Flags] public enum StringSplitOptions { None = 0, RemoveEmptyEntries = 1, } } ================================================ FILE: Zelig/Zelig/RunTime/Framework/mscorlib/System/StringComparer.cs ================================================ // ==++== // // Copyright (c) Microsoft Corporation. All rights reserved. // // ==--== namespace System { using System.Collections; using System.Collections.Generic; using System.Globalization; [Serializable] public abstract class StringComparer : IComparer, IEqualityComparer, IComparer, IEqualityComparer { //// private static StringComparer _invariantCulture = new CultureAwareComparer( CultureInfo.InvariantCulture, false ); //// private static StringComparer _invariantCultureIgnoreCase = new CultureAwareComparer( CultureInfo.InvariantCulture, true ); private static StringComparer _ordinal = new OrdinalComparer(); //// private static StringComparer _ordinalIgnoreCase = new OrdinalComparerIgnoreCase(); //// public static StringComparer InvariantCulture //// { //// get //// { //// return _invariantCulture; //// } //// } //// //// public static StringComparer InvariantCultureIgnoreCase //// { //// get //// { //// return _invariantCultureIgnoreCase; //// } //// } //// //// public static StringComparer CurrentCulture //// { //// get //// { //// return new CultureAwareComparer( CultureInfo.CurrentCulture, false ); //// } //// } //// //// public static StringComparer CurrentCultureIgnoreCase //// { //// get //// { //// return new CultureAwareComparer( CultureInfo.CurrentCulture, true ); //// } //// } public static StringComparer Ordinal { get { return _ordinal; } } //// public static StringComparer OrdinalIgnoreCase //// { //// get //// { //// return _ordinalIgnoreCase; //// } //// } //// //// public static StringComparer Create( CultureInfo culture, bool ignoreCase ) //// { //// if(culture == null) //// { //// throw new ArgumentNullException( "culture" ); //// } //// //// return new CultureAwareComparer( culture, ignoreCase ); //// } public int Compare( object x, object y ) { if(x == y) return 0; if(x == null) return -1; if(y == null) return 1; String sa = x as String; if(sa != null) { String sb = y as String; if(sb != null) { return Compare( sa, sb ); } } IComparable ia = x as IComparable; if(ia != null) { return ia.CompareTo( y ); } #if EXCEPTION_STRINGS throw new ArgumentException( Environment.GetResourceString( "Argument_ImplementIComparable" ) ); #else throw new ArgumentException(); #endif } public new bool Equals( Object x, Object y ) { if(x == y) return true; if(x == null || y == null) return false; String sa = x as String; if(sa != null) { String sb = y as String; if(sb != null) { return Equals( sa, sb ); } } return x.Equals( y ); } public int GetHashCode( object obj ) { if(obj == null) { #if EXCEPTION_STRINGS throw new ArgumentNullException( "obj" ); #else throw new ArgumentNullException(); #endif } string s = obj as string; if(s != null) { return GetHashCode( s ); } return obj.GetHashCode(); } public abstract int Compare( String x, String y ); public abstract bool Equals( String x, String y ); public abstract int GetHashCode( string obj ); } ////[Serializable()] ////internal sealed class CultureAwareComparer : StringComparer ////{ //// private CompareInfo _compareInfo; //// private bool _ignoreCase; //// //// internal CultureAwareComparer( CultureInfo culture, bool ignoreCase ) //// { //// _compareInfo = culture.CompareInfo; //// _ignoreCase = ignoreCase; //// } //// //// public override int Compare( string x, string y ) //// { //// if(Object.ReferenceEquals( x, y )) return 0; //// if(x == null) return -1; //// if(y == null) return 1; //// return _compareInfo.Compare( x, y, _ignoreCase ? CompareOptions.IgnoreCase : CompareOptions.None ); //// } //// //// public override bool Equals( string x, string y ) //// { //// if(Object.ReferenceEquals( x, y )) return true; //// if(x == null || y == null) return false; //// //// return (_compareInfo.Compare( x, y, _ignoreCase ? CompareOptions.IgnoreCase : CompareOptions.None ) == 0); //// } //// //// public override int GetHashCode( string obj ) //// { //// if(obj == null) //// { //// throw new ArgumentNullException( "obj" ); //// } //// //// if(_ignoreCase) //// { //// return _compareInfo.GetHashCodeOfString( obj, CompareOptions.IgnoreCase ); //// } //// //// return _compareInfo.GetHashCodeOfString( obj, CompareOptions.None ); //// } //// //// // Equals method for the comparer itself. //// public override bool Equals( Object obj ) //// { //// CultureAwareComparer comparer = obj as CultureAwareComparer; //// if(comparer == null) //// { //// return false; //// } //// return (this._ignoreCase == comparer._ignoreCase) && (this._compareInfo.Equals( comparer._compareInfo )); //// } //// //// public override int GetHashCode() //// { //// int hashCode = _compareInfo.GetHashCode(); //// return _ignoreCase ? (~hashCode) : hashCode; //// } ////} // Provide x more optimal implementation of ordinal comparison. [Serializable()] internal sealed class OrdinalComparer : StringComparer { internal OrdinalComparer() { } public override int Compare( string x , string y ) { if(Object.ReferenceEquals( x, y )) return 0; if(x == null) return -1; if(y == null) return 1; return String.CompareOrdinal( x, y ); } public override bool Equals( string x , string y ) { if(Object.ReferenceEquals( x, y )) return true; if(x == null || y == null) return false; return x.Equals( y ); } public override int GetHashCode( string obj ) { if(obj == null) { #if EXCEPTION_STRINGS throw new ArgumentNullException( "obj" ); #else throw new ArgumentNullException(); #endif } return obj.GetHashCode(); } // Equals method for the comparer itself. public override bool Equals( Object obj ) { OrdinalComparer comparer = obj as OrdinalComparer; if(comparer == null) { return false; } return true; } public override int GetHashCode() { return "OrdinalComparer".GetHashCode(); } } ////// Provide x more optimal implementation of ordinal comparison. ////[Serializable] ////internal sealed class OrdinalComparerIgnoreCase : StringComparer ////{ //// internal OrdinalComparerIgnoreCase() //// { //// } //// //// public override int Compare( string x, string y ) //// { //// if(Object.ReferenceEquals( x, y )) return 0; //// if(x == null) return -1; //// if(y == null) return 1; //// //// return TextInfo.CompareOrdinalIgnoreCase( x, y ); //// } //// //// public override bool Equals( string x, string y ) //// { //// if(Object.ReferenceEquals( x, y )) return true; //// //// if(x == null || y == null) return false; //// //// if(x.Length != y.Length) //// { //// return false; //// } //// //// return (TextInfo.CompareOrdinalIgnoreCase( x, y ) == 0); //// } //// //// public override int GetHashCode( string obj ) //// { //// if(obj == null) //// { //// throw new ArgumentNullException( "obj" ); //// } //// //// return TextInfo.GetHashCodeOrdinalIgnoreCase( obj ); //// } //// //// // Equals method for the comparer itself. //// public override bool Equals( Object obj ) //// { //// OrdinalComparerIgnoreCase comparer = obj as OrdinalComparerIgnoreCase; //// if(comparer == null) //// { //// return false; //// } //// //// return true; //// } //// //// public override int GetHashCode() //// { //// return "OrdinalComparerIgnoreCase".GetHashCode(); //// } ////} } ================================================ FILE: Zelig/Zelig/RunTime/Framework/mscorlib/System/StringComparison.cs ================================================ // ==++== // // Copyright (c) Microsoft Corporation. All rights reserved. // // ==--== /*============================================================ ** ** Enum: StringComparison ** ** ** Purpose: A mechanism to expose a simplified infrastructure for ** Comparing strings. This enum lets you choose of the custom ** implementations provided by the runtime for the user. ** ** ===========================================================*/ namespace System { [Serializable] public enum StringComparison { CurrentCulture = 0, CurrentCultureIgnoreCase = 1, InvariantCulture = 2, InvariantCultureIgnoreCase = 3, Ordinal = 4, OrdinalIgnoreCase = 5, } } ================================================ FILE: Zelig/Zelig/RunTime/Framework/mscorlib/System/SystemException.cs ================================================ // ==++== // // Copyright (c) Microsoft Corporation. All rights reserved. // // ==--== namespace System { using System; using System.Runtime.Serialization; [Serializable] public class SystemException : Exception { #if EXCEPTION_STRINGS public SystemException() : base( Environment.GetResourceString( "Arg_SystemException" ) ) #else public SystemException() #endif { } public SystemException( String message ) : base( message ) { } public SystemException( String message, Exception innerException ) : base( message, innerException ) { } //// protected SystemException( SerializationInfo info, StreamingContext context ) : base( info, context ) //// { //// } } } ================================================ FILE: Zelig/Zelig/RunTime/Framework/mscorlib/System/TargetFrameworkAttribute.cs ================================================ //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // Copyright (c) Microsoft Corporation. All rights reserved. ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////namespace System /*============================================================ ** ** Class: TargetFrameworkAttribute ** ** ** Purpose: Identifies which SKU and version of the .NET ** Framework that a particular library was compiled against. ** Emitted by VS, and can help catch deployment problems. ** ===========================================================*/ using System; namespace System.Runtime.Versioning { [AttributeUsageAttribute(AttributeTargets.Assembly, AllowMultiple = false, Inherited = false)] public sealed class TargetFrameworkAttribute : Attribute { private String _frameworkName; // A target framework moniker private String _frameworkDisplayName; // The frameworkName parameter is intended to be the string form of a FrameworkName instance. public TargetFrameworkAttribute(String frameworkName) { if (frameworkName == null) throw new ArgumentNullException(); _frameworkName = frameworkName; } // The target framework moniker that this assembly was compiled against. // Use the FrameworkName class to interpret target framework monikers. public String FrameworkName { get { return _frameworkName; } } public String FrameworkDisplayName { get { return _frameworkDisplayName; } set { _frameworkDisplayName = value; } } } } ================================================ FILE: Zelig/Zelig/RunTime/Framework/mscorlib/System/Text/ASCIIEncoding.cs ================================================ // ==++== // // Copyright (c) Microsoft Corporation. All rights reserved. // // ==--== namespace System.Text { using System; using System.Runtime.Serialization; using System.Security.Permissions; // ASCIIEncoding // // Note that ASCIIEncoding is optimized with no best fit and ? for fallback. // It doesn't come in other flavors. // // Note: ASCIIEncoding is the only encoding that doesn't do best fit (windows has best fit). // // Note: IsAlwaysNormalized remains false because 1/2 the code points are unassigned, so they'd // use fallbacks, and we cannot guarantee that fallbacks are normalized. // [Serializable()] ////[System.Runtime.InteropServices.ComVisible( true )] public class ASCIIEncoding : Encoding { public ASCIIEncoding() : base( Encoding.CodePageASCII ) { } internal override void SetDefaultFallbacks() { // For ASCIIEncoding we just use default replacement fallback this.encoderFallback = EncoderFallback.ReplacementFallback; this.decoderFallback = DecoderFallback.ReplacementFallback; } // // WARNING: GetByteCount(string chars), GetBytes(string chars,...), and GetString(byte[] byteIndex...) // WARNING: have different variable names than EncodingNLS.cs, so this can't just be cut & pasted, // WARNING: or it'll break VB's way of calling these. // // The following methods are copied from EncodingNLS.cs. // Unfortunately EncodingNLS.cs is internal and we're public, so we have to reimpliment them here. // These should be kept in sync for the following classes: // EncodingNLS, UTF7Encoding, UTF8Encoding, UTF32Encoding, ASCIIEncoding, UnicodeEncoding // // Returns the number of bytes required to encode a range of characters in // a character array. // // All of our public Encodings that don't use EncodingNLS must have this (including EncodingNLS) // So if you fix this, fix the others. Currently those include: // EncodingNLS, UTF7Encoding, UTF8Encoding, UTF32Encoding, ASCIIEncoding, UnicodeEncoding // parent method is safe public override unsafe int GetByteCount( char[] chars , int index , int count ) { // Validate input parameters if(chars == null) { #if EXCEPTION_STRINGS throw new ArgumentNullException( "chars", Environment.GetResourceString( "ArgumentNull_Array" ) ); #else throw new ArgumentNullException(); #endif } if(index < 0 || count < 0) { #if EXCEPTION_STRINGS throw new ArgumentOutOfRangeException( (index < 0 ? "index" : "count"), Environment.GetResourceString( "ArgumentOutOfRange_NeedNonNegNum" ) ); #else throw new ArgumentOutOfRangeException(); #endif } if(chars.Length - index < count) { #if EXCEPTION_STRINGS throw new ArgumentOutOfRangeException( "chars", Environment.GetResourceString( "ArgumentOutOfRange_IndexCountBuffer" ) ); #else throw new ArgumentOutOfRangeException(); #endif } // If no input, return 0, avoid fixed empty array problem if(chars.Length == 0) { return 0; } // Just call the pointer version fixed(char* pChars = chars) { return GetByteCount( pChars + index, count, null ); } } // All of our public Encodings that don't use EncodingNLS must have this (including EncodingNLS) // So if you fix this, fix the others. Currently those include: // EncodingNLS, UTF7Encoding, UTF8Encoding, UTF32Encoding, ASCIIEncoding, UnicodeEncoding // parent method is safe public override unsafe int GetByteCount( String chars ) { // Validate input if(chars == null) { #if EXCEPTION_STRINGS throw new ArgumentNullException( "chars" ); #else throw new ArgumentNullException(); #endif } fixed(char* pChars = chars) { return GetByteCount( pChars, chars.Length, null ); } } // All of our public Encodings that don't use EncodingNLS must have this (including EncodingNLS) // So if you fix this, fix the others. Currently those include: // EncodingNLS, UTF7Encoding, UTF8Encoding, UTF32Encoding, ASCIIEncoding, UnicodeEncoding [CLSCompliant( false )] //// [System.Runtime.InteropServices.ComVisible( false )] public override unsafe int GetByteCount( char* chars , int count ) { // Validate Parameters if(chars == null) { #if EXCEPTION_STRINGS throw new ArgumentNullException( "chars", Environment.GetResourceString( "ArgumentNull_Array" ) ); #else throw new ArgumentNullException(); #endif } if(count < 0) { #if EXCEPTION_STRINGS throw new ArgumentOutOfRangeException( "count", Environment.GetResourceString( "ArgumentOutOfRange_NeedNonNegNum" ) ); #else throw new ArgumentOutOfRangeException(); #endif } // Call it with empty encoder return GetByteCount( chars, count, null ); } // Parent method is safe. // All of our public Encodings that don't use EncodingNLS must have this (including EncodingNLS) // So if you fix this, fix the others. Currently those include: // EncodingNLS, UTF7Encoding, UTF8Encoding, UTF32Encoding, ASCIIEncoding, UnicodeEncoding public override unsafe int GetBytes( String chars , int charIndex , int charCount , byte[] bytes , int byteIndex ) { if(chars == null || bytes == null) { #if EXCEPTION_STRINGS throw new ArgumentNullException( (chars == null ? "chars" : "bytes"), Environment.GetResourceString( "ArgumentNull_Array" ) ); #else throw new ArgumentNullException(); #endif } if(charIndex < 0 || charCount < 0) { #if EXCEPTION_STRINGS throw new ArgumentOutOfRangeException( (charIndex < 0 ? "charIndex" : "charCount"), Environment.GetResourceString( "ArgumentOutOfRange_NeedNonNegNum" ) ); #else throw new ArgumentOutOfRangeException(); #endif } if(chars.Length - charIndex < charCount) { #if EXCEPTION_STRINGS throw new ArgumentOutOfRangeException( "chars", Environment.GetResourceString( "ArgumentOutOfRange_IndexCount" ) ); #else throw new ArgumentOutOfRangeException(); #endif } if(byteIndex < 0 || byteIndex > bytes.Length) { #if EXCEPTION_STRINGS throw new ArgumentOutOfRangeException( "byteIndex", Environment.GetResourceString( "ArgumentOutOfRange_Index" ) ); #else throw new ArgumentOutOfRangeException(); #endif } int byteCount = bytes.Length - byteIndex; // Fixed doesn't like empty byte arrays if(bytes.Length == 0) { bytes = new byte[1]; } fixed(char* pChars = chars) { fixed(byte* pBytes = bytes) { return GetBytes( pChars + charIndex, charCount, pBytes + byteIndex, byteCount, null ); } } } // Encodes a range of characters in a character array into a range of bytes // in a byte array. An exception occurs if the byte array is not large // enough to hold the complete encoding of the characters. The // GetByteCount method can be used to determine the exact number of // bytes that will be produced for a given range of characters. // Alternatively, the GetMaxByteCount method can be used to // determine the maximum number of bytes that will be produced for a given // number of characters, regardless of the actual character values. // // All of our public Encodings that don't use EncodingNLS must have this (including EncodingNLS) // So if you fix this, fix the others. Currently those include: // EncodingNLS, UTF7Encoding, UTF8Encoding, UTF32Encoding, ASCIIEncoding, UnicodeEncoding // parent method is safe public override unsafe int GetBytes( char[] chars , int charIndex , int charCount , byte[] bytes , int byteIndex ) { // Validate parameters if(chars == null || bytes == null) { #if EXCEPTION_STRINGS throw new ArgumentNullException( (chars == null ? "chars" : "bytes"), Environment.GetResourceString( "ArgumentNull_Array" ) ); #else throw new ArgumentNullException(); #endif } if(charIndex < 0 || charCount < 0) { #if EXCEPTION_STRINGS throw new ArgumentOutOfRangeException( (charIndex < 0 ? "charIndex" : "charCount"), Environment.GetResourceString( "ArgumentOutOfRange_NeedNonNegNum" ) ); #else throw new ArgumentOutOfRangeException(); #endif } if(chars.Length - charIndex < charCount) { #if EXCEPTION_STRINGS throw new ArgumentOutOfRangeException( "chars", Environment.GetResourceString( "ArgumentOutOfRange_IndexCountBuffer" ) ); #else throw new ArgumentOutOfRangeException(); #endif } if(byteIndex < 0 || byteIndex > bytes.Length) { #if EXCEPTION_STRINGS throw new ArgumentOutOfRangeException( "byteIndex", Environment.GetResourceString( "ArgumentOutOfRange_Index" ) ); #else throw new ArgumentOutOfRangeException(); #endif } // If nothing to encode return 0, avoid fixed problem if(chars.Length == 0) { return 0; } // Just call pointer version int byteCount = bytes.Length - byteIndex; // Fixed doesn't like empty byte arrays if(bytes.Length == 0) { bytes = new byte[1]; } fixed(char* pChars = chars) { fixed(byte* pBytes = bytes) { // Remember that byteCount is # to decode, not size of array. return GetBytes( pChars + charIndex, charCount, pBytes + byteIndex, byteCount, null ); } } } // All of our public Encodings that don't use EncodingNLS must have this (including EncodingNLS) // So if you fix this, fix the others. Currently those include: // EncodingNLS, UTF7Encoding, UTF8Encoding, UTF32Encoding, ASCIIEncoding, UnicodeEncoding [CLSCompliant( false )] //// [System.Runtime.InteropServices.ComVisible( false )] public override unsafe int GetBytes( char* chars , int charCount , byte* bytes , int byteCount ) { // Validate Parameters if(bytes == null || chars == null) { #if EXCEPTION_STRINGS throw new ArgumentNullException( bytes == null ? "bytes" : "chars", Environment.GetResourceString( "ArgumentNull_Array" ) ); #else throw new ArgumentNullException(); #endif } if(charCount < 0 || byteCount < 0) { #if EXCEPTION_STRINGS throw new ArgumentOutOfRangeException( (charCount < 0 ? "charCount" : "byteCount"), Environment.GetResourceString( "ArgumentOutOfRange_NeedNonNegNum" ) ); #else throw new ArgumentOutOfRangeException(); #endif } return GetBytes( chars, charCount, bytes, byteCount, null ); } // Returns the number of characters produced by decoding a range of bytes // in a byte array. // // All of our public Encodings that don't use EncodingNLS must have this (including EncodingNLS) // So if you fix this, fix the others. Currently those include: // EncodingNLS, UTF7Encoding, UTF8Encoding, UTF32Encoding, ASCIIEncoding, UnicodeEncoding // parent method is safe public override unsafe int GetCharCount( byte[] bytes , int index , int count ) { // Validate Parameters if(bytes == null) { #if EXCEPTION_STRINGS throw new ArgumentNullException( "bytes", Environment.GetResourceString( "ArgumentNull_Array" ) ); #else throw new ArgumentNullException(); #endif } if(index < 0 || count < 0) { #if EXCEPTION_STRINGS throw new ArgumentOutOfRangeException( (index < 0 ? "index" : "count"), Environment.GetResourceString( "ArgumentOutOfRange_NeedNonNegNum" ) ); #else throw new ArgumentOutOfRangeException(); #endif } if(bytes.Length - index < count) { #if EXCEPTION_STRINGS throw new ArgumentOutOfRangeException( "bytes", Environment.GetResourceString( "ArgumentOutOfRange_IndexCountBuffer" ) ); #else throw new ArgumentOutOfRangeException(); #endif } // If no input just return 0, fixed doesn't like 0 length arrays if(bytes.Length == 0) { return 0; } // Just call pointer version fixed(byte* pBytes = bytes) { return GetCharCount( pBytes + index, count, null ); } } // All of our public Encodings that don't use EncodingNLS must have this (including EncodingNLS) // So if you fix this, fix the others. Currently those include: // EncodingNLS, UTF7Encoding, UTF8Encoding, UTF32Encoding, ASCIIEncoding, UnicodeEncoding [CLSCompliant( false )] //// [System.Runtime.InteropServices.ComVisible( false )] public override unsafe int GetCharCount( byte* bytes , int count ) { // Validate Parameters if(bytes == null) { #if EXCEPTION_STRINGS throw new ArgumentNullException( "bytes", Environment.GetResourceString( "ArgumentNull_Array" ) ); #else throw new ArgumentNullException(); #endif } if(count < 0) { #if EXCEPTION_STRINGS throw new ArgumentOutOfRangeException( "count", Environment.GetResourceString( "ArgumentOutOfRange_NeedNonNegNum" ) ); #else throw new ArgumentOutOfRangeException(); #endif } return GetCharCount( bytes, count, null ); } // All of our public Encodings that don't use EncodingNLS must have this (including EncodingNLS) // So if you fix this, fix the others. Currently those include: // EncodingNLS, UTF7Encoding, UTF8Encoding, UTF32Encoding, ASCIIEncoding, UnicodeEncoding // parent method is safe public override unsafe int GetChars( byte[] bytes , int byteIndex , int byteCount , char[] chars , int charIndex ) { // Validate Parameters if(bytes == null || chars == null) { #if EXCEPTION_STRINGS throw new ArgumentNullException( bytes == null ? "bytes" : "chars", Environment.GetResourceString( "ArgumentNull_Array" ) ); #else throw new ArgumentNullException(); #endif } if(byteIndex < 0 || byteCount < 0) { #if EXCEPTION_STRINGS throw new ArgumentOutOfRangeException( (byteIndex < 0 ? "byteIndex" : "byteCount"), Environment.GetResourceString( "ArgumentOutOfRange_NeedNonNegNum" ) ); #else throw new ArgumentOutOfRangeException(); #endif } if(bytes.Length - byteIndex < byteCount) { #if EXCEPTION_STRINGS throw new ArgumentOutOfRangeException( "bytes", Environment.GetResourceString( "ArgumentOutOfRange_IndexCountBuffer" ) ); #else throw new ArgumentOutOfRangeException(); #endif } if(charIndex < 0 || charIndex > chars.Length) { #if EXCEPTION_STRINGS throw new ArgumentOutOfRangeException( "charIndex", Environment.GetResourceString( "ArgumentOutOfRange_Index" ) ); #else throw new ArgumentOutOfRangeException(); #endif } // If no input, return 0 & avoid fixed problem if(bytes.Length == 0) { return 0; } // Just call pointer version int charCount = chars.Length - charIndex; // Fixed doesn't like empty char arrays if(chars.Length == 0) { chars = new char[1]; } fixed(byte* pBytes = bytes) { fixed(char* pChars = chars) { // Remember that charCount is # to decode, not size of array return GetChars( pBytes + byteIndex, byteCount, pChars + charIndex, charCount, null ); } } } // All of our public Encodings that don't use EncodingNLS must have this (including EncodingNLS) // So if you fix this, fix the others. Currently those include: // EncodingNLS, UTF7Encoding, UTF8Encoding, UTF32Encoding, ASCIIEncoding, UnicodeEncoding [CLSCompliant( false )] //// [System.Runtime.InteropServices.ComVisible( false )] public unsafe override int GetChars( byte* bytes , int byteCount , char* chars , int charCount ) { // Validate Parameters if(bytes == null || chars == null) { #if EXCEPTION_STRINGS throw new ArgumentNullException( bytes == null ? "bytes" : "chars", Environment.GetResourceString( "ArgumentNull_Array" ) ); #else throw new ArgumentNullException(); #endif } if(charCount < 0 || byteCount < 0) { #if EXCEPTION_STRINGS throw new ArgumentOutOfRangeException( (charCount < 0 ? "charCount" : "byteCount"), Environment.GetResourceString( "ArgumentOutOfRange_NeedNonNegNum" ) ); #else throw new ArgumentOutOfRangeException(); #endif } return GetChars( bytes, byteCount, chars, charCount, null ); } // Returns a string containing the decoded representation of a range of // bytes in a byte array. // // All of our public Encodings that don't use EncodingNLS must have this (including EncodingNLS) // So if you fix this, fix the others. Currently those include: // EncodingNLS, UTF7Encoding, UTF8Encoding, UTF32Encoding, ASCIIEncoding, UnicodeEncoding // parent method is safe public override unsafe String GetString( byte[] bytes , int byteIndex , int byteCount ) { // Validate Parameters if(bytes == null) { #if EXCEPTION_STRINGS throw new ArgumentNullException( "bytes", Environment.GetResourceString( "ArgumentNull_Array" ) ); #else throw new ArgumentNullException(); #endif } if(byteIndex < 0 || byteCount < 0) { #if EXCEPTION_STRINGS throw new ArgumentOutOfRangeException( (byteIndex < 0 ? "byteIndex" : "byteCount"), Environment.GetResourceString( "ArgumentOutOfRange_NeedNonNegNum" ) ); #else throw new ArgumentOutOfRangeException(); #endif } if(bytes.Length - byteIndex < byteCount) { #if EXCEPTION_STRINGS throw new ArgumentOutOfRangeException( "bytes", Environment.GetResourceString( "ArgumentOutOfRange_IndexCountBuffer" ) ); #else throw new ArgumentOutOfRangeException(); #endif } // Avoid problems with empty input buffer if(bytes.Length == 0) { return String.Empty; } fixed(byte* pBytes = bytes) { return String.CreateStringFromEncoding( pBytes + byteIndex, byteCount, this ); } } // // End of standard methods copied from EncodingNLS.cs // // GetByteCount // Note: We start by assuming that the output will be the same as count. Having // an encoder or fallback may change that assumption internal override unsafe int GetByteCount( char* chars , int charCount , EncoderNLS encoder ) { // Just need to ASSERT, this is called by something else internal that checked parameters already BCLDebug.Assert( charCount >= 0, "[ASCIIEncoding.GetByteCount]count is negative" ); BCLDebug.Assert( chars != null, "[ASCIIEncoding.GetByteCount]chars is null" ); // Assert because we shouldn't be able to have a null encoder. BCLDebug.Assert( encoderFallback != null, "[ASCIIEncoding.GetByteCount]Attempting to use null fallback encoder" ); char charLeftOver = (char)0; EncoderReplacementFallback fallback = null; // Start by assuming default count, then +/- for fallback characters char* charEnd = chars + charCount; // For fallback we may need a fallback buffer, we know we aren't default fallback. EncoderFallbackBuffer fallbackBuffer = null; if(encoder != null) { charLeftOver = encoder.charLeftOver; BCLDebug.Assert( charLeftOver == 0 || Char.IsHighSurrogate( charLeftOver ), "[ASCIIEncoding.GetByteCount]leftover character should be high surrogate" ); fallback = encoder.Fallback as EncoderReplacementFallback; // We mustn't have left over fallback data when counting if(encoder.InternalHasFallbackBuffer) { // We always need the fallback buffer in get bytes so we can flush any remaining ones if necessary fallbackBuffer = encoder.FallbackBuffer; if(fallbackBuffer.Remaining > 0 && encoder.m_throwOnOverflow) { #if EXCEPTION_STRINGS throw new ArgumentException( Environment.GetResourceString( "Argument_EncoderFallbackNotEmpty", this.EncodingName, encoder.Fallback.GetType() ) ); #else throw new ArgumentException(); #endif } // Set our internal fallback interesting things. fallbackBuffer.InternalInitialize( chars, charEnd, encoder, false ); } // Verify that we have no fallbackbuffer, for ASCII its always empty, so just assert BCLDebug.Assert( !encoder.m_throwOnOverflow || !encoder.InternalHasFallbackBuffer || encoder.FallbackBuffer.Remaining == 0, "[ASCIICodePageEncoding.GetByteCount]Expected empty fallback buffer" ); // if (encoder.InternalHasFallbackBuffer && encoder.FallbackBuffer.Remaining > 0) // throw new ArgumentException(Environment.GetResourceString("Argument_EncoderFallbackNotEmpty", // this.EncodingName, encoder.Fallback.GetType())); } else { fallback = this.EncoderFallback as EncoderReplacementFallback; } // If we have an encoder AND we aren't using default fallback, // then we may have a complicated count. if(fallback != null && fallback.MaxCharCount == 1) { // Replacement fallback encodes surrogate pairs as two ?? (or two whatever), so return size is always // same as input size. // Note that no existing SBCS code pages map code points to supplimentary characters, so this is easy. // We could however have 1 extra byte if the last call had an encoder and a funky fallback and // if we don't use the funky fallback this time. // Do we have an extra char left over from last time? if(charLeftOver > 0) { charCount++; } return (charCount); } // Count is more complicated if you have a funky fallback // For fallback we may need a fallback buffer, we know we're not default fallback int byteCount = 0; // We may have a left over character from last time, try and process it. if(charLeftOver > 0) { BCLDebug.Assert( Char.IsHighSurrogate( charLeftOver ), "[ASCIIEncoding.GetByteCount]leftover character should be high surrogate" ); BCLDebug.Assert( encoder != null, "[ASCIIEncoding.GetByteCount]Expected encoder" ); // Since left over char was a surrogate, it'll have to be fallen back. // Get Fallback fallbackBuffer = encoder.FallbackBuffer; fallbackBuffer.InternalInitialize( chars, charEnd, encoder, false ); // This will fallback a pair if *chars is a low surrogate fallbackBuffer.InternalFallback( charLeftOver, ref chars ); } // Now we may have fallback char[] already from the encoder // Go ahead and do it, including the fallback. char ch; while((ch = (fallbackBuffer == null) ? '\0' : fallbackBuffer.InternalGetNextChar()) != 0 || chars < charEnd) { // First unwind any fallback if(ch == 0) { // No fallback, just get next char ch = *chars; chars++; } // Check for fallback, this'll catch surrogate pairs too. // no chars >= 0x80 are allowed. if(ch > 0x7f) { if(fallbackBuffer == null) { // Initialize the buffer if(encoder == null) { fallbackBuffer = this.encoderFallback.CreateFallbackBuffer(); } else { fallbackBuffer = encoder.FallbackBuffer; } fallbackBuffer.InternalInitialize( charEnd - charCount, charEnd, encoder, false ); } // Get Fallback fallbackBuffer.InternalFallback( ch, ref chars ); continue; } // We'll use this one byteCount++; } BCLDebug.Assert( fallbackBuffer == null || fallbackBuffer.Remaining == 0, "[ASCIIEncoding.GetByteCount]Expected Empty fallback buffer" ); return byteCount; } internal override unsafe int GetBytes( char* chars , int charCount , byte* bytes , int byteCount , EncoderNLS encoder ) { // Just need to ASSERT, this is called by something else internal that checked parameters already BCLDebug.Assert( bytes != null, "[ASCIIEncoding.GetBytes]bytes is null" ); BCLDebug.Assert( byteCount >= 0, "[ASCIIEncoding.GetBytes]byteCount is negative" ); BCLDebug.Assert( chars != null, "[ASCIIEncoding.GetBytes]chars is null" ); BCLDebug.Assert( charCount >= 0, "[ASCIIEncoding.GetBytes]charCount is negative" ); // Assert because we shouldn't be able to have a null encoder. BCLDebug.Assert( encoderFallback != null, "[ASCIIEncoding.GetBytes]Attempting to use null encoder fallback" ); // Get any left over characters char charLeftOver = (char)0; EncoderReplacementFallback fallback = null; // For fallback we may need a fallback buffer, we know we aren't default fallback. EncoderFallbackBuffer fallbackBuffer = null; // prepare our end char* charEnd = chars + charCount; byte* byteStart = bytes; char* charStart = chars; if(encoder != null) { charLeftOver = encoder.charLeftOver; fallback = encoder.Fallback as EncoderReplacementFallback; // We mustn't have left over fallback data when counting if(encoder.InternalHasFallbackBuffer) { // We always need the fallback buffer in get bytes so we can flush any remaining ones if necessary fallbackBuffer = encoder.FallbackBuffer; if(fallbackBuffer.Remaining > 0 && encoder.m_throwOnOverflow) { #if EXCEPTION_STRINGS throw new ArgumentException( Environment.GetResourceString( "Argument_EncoderFallbackNotEmpty", this.EncodingName, encoder.Fallback.GetType() ) ); #else throw new ArgumentException(); #endif } // Set our internal fallback interesting things. fallbackBuffer.InternalInitialize( charStart, charEnd, encoder, true ); } BCLDebug.Assert( charLeftOver == 0 || Char.IsHighSurrogate( charLeftOver ), "[ASCIIEncoding.GetBytes]leftover character should be high surrogate" ); // Verify that we have no fallbackbuffer, for ASCII its always empty, so just assert BCLDebug.Assert( !encoder.m_throwOnOverflow || !encoder.InternalHasFallbackBuffer || encoder.FallbackBuffer.Remaining == 0, "[ASCIICodePageEncoding.GetBytes]Expected empty fallback buffer" ); // if (encoder.m_throwOnOverflow && encoder.InternalHasFallbackBuffer && // encoder.FallbackBuffer.Remaining > 0) // throw new ArgumentException(Environment.GetResourceString("Argument_EncoderFallbackNotEmpty", // this.EncodingName, encoder.Fallback.GetType())); } else { fallback = this.EncoderFallback as EncoderReplacementFallback; } // See if we do the fast default or slightly slower fallback if(fallback != null && fallback.MaxCharCount == 1) { // Fast version char cReplacement = fallback.DefaultString[0]; // Check for replacements in range, otherwise fall back to slow version. if(cReplacement <= (char)0x7f) { // We should have exactly as many output bytes as input bytes, unless there's a left // over character, in which case we may need one more. // If we had a left over character will have to add a ? (This happens if they had a funky // fallback last time, but not this time.) (We can't spit any out though // because with fallback encoder each surrogate is treated as a seperate code point) if(charLeftOver > 0) { // Have to have room // Throw even if doing no throw version because this is just 1 char, // so buffer will never be big enough if(byteCount == 0) { ThrowBytesOverflow( encoder, true ); } // This'll make sure we still have more room and also make sure our return value is correct. *(bytes++) = (byte)cReplacement; byteCount--; // We used one of the ones we were counting. } // This keeps us from overrunning our output buffer if(byteCount < charCount) { // Throw or make buffer smaller? ThrowBytesOverflow( encoder, byteCount < 1 ); // Just use what we can charEnd = chars + byteCount; } // We just do a quick copy while(chars < charEnd) { char ch2 = *(chars++); if(ch2 >= 0x0080) { *(bytes++) = (byte)cReplacement; } else { *(bytes++) = unchecked( (byte)(ch2) ); } } // Clear encoder if(encoder != null) { encoder.charLeftOver = (char)0; encoder.m_charsUsed = (int)(chars - charStart); } return (int)(bytes - byteStart); } } // Slower version, have to do real fallback. // prepare our end byte* byteEnd = bytes + byteCount; // We may have a left over character from last time, try and process it. if(charLeftOver > 0) { // Initialize the buffer BCLDebug.Assert( encoder != null, "[ASCIIEncoding.GetBytes]Expected non null encoder if we have surrogate left over" ); fallbackBuffer = encoder.FallbackBuffer; fallbackBuffer.InternalInitialize( chars, charEnd, encoder, true ); // Since left over char was a surrogate, it'll have to be fallen back. // Get Fallback // This will fallback a pair if *chars is a low surrogate fallbackBuffer.InternalFallback( charLeftOver, ref chars ); } // Now we may have fallback char[] already from the encoder // Go ahead and do it, including the fallback. char ch; while((ch = (fallbackBuffer == null) ? '\0' : fallbackBuffer.InternalGetNextChar()) != 0 || chars < charEnd) { // First unwind any fallback if(ch == 0) { // No fallback, just get next char ch = *chars; chars++; } // Check for fallback, this'll catch surrogate pairs too. // All characters >= 0x80 must fall back. if(ch > 0x7f) { // Initialize the buffer if(fallbackBuffer == null) { if(encoder == null) { fallbackBuffer = this.encoderFallback.CreateFallbackBuffer(); } else { fallbackBuffer = encoder.FallbackBuffer; } fallbackBuffer.InternalInitialize( charEnd - charCount, charEnd, encoder, true ); } // Get Fallback fallbackBuffer.InternalFallback( ch, ref chars ); // Go ahead & continue (& do the fallback) continue; } // We'll use this one // Bounds check if(bytes >= byteEnd) { // didn't use this char, we'll throw or use buffer if(fallbackBuffer == null || fallbackBuffer.bFallingBack == false) { BCLDebug.Assert( chars > charStart || bytes == byteStart, "[ASCIIEncoding.GetBytes]Expected chars to have advanced already." ); chars--; // don't use last char } else { fallbackBuffer.MovePrevious(); } // Are we throwing or using buffer? ThrowBytesOverflow( encoder, bytes == byteStart ); // throw? break; // don't throw, stop } // Go ahead and add it *bytes = unchecked( (byte)ch ); bytes++; } // Need to do encoder stuff if(encoder != null) { // Fallback stuck it in encoder if necessary, but we have to clear MustFlush cases if(fallbackBuffer != null && !fallbackBuffer.bUsedEncoder) { // Clear it in case of MustFlush encoder.charLeftOver = (char)0; } // Set our chars used count encoder.m_charsUsed = (int)(chars - charStart); } BCLDebug.Assert( fallbackBuffer == null || fallbackBuffer.Remaining == 0 || (encoder != null && !encoder.m_throwOnOverflow), "[ASCIIEncoding.GetBytes]Expected Empty fallback buffer at end" ); return (int)(bytes - byteStart); } // This is internal and called by something else, internal override unsafe int GetCharCount( byte* bytes , int count , DecoderNLS decoder ) { // Just assert, we're called internally so these should be safe, checked already BCLDebug.Assert( bytes != null, "[ASCIIEncoding.GetCharCount]bytes is null" ); BCLDebug.Assert( count >= 0, "[ASCIIEncoding.GetCharCount]byteCount is negative" ); // ASCII doesn't do best fit, so don't have to check for it, find out which decoder fallback we're using DecoderReplacementFallback fallback = null; if(decoder == null) { fallback = this.DecoderFallback as DecoderReplacementFallback; } else { fallback = decoder.Fallback as DecoderReplacementFallback; BCLDebug.Assert( !decoder.m_throwOnOverflow || !decoder.InternalHasFallbackBuffer || decoder.FallbackBuffer.Remaining == 0, "[ASCIICodePageEncoding.GetCharCount]Expected empty fallback buffer" ); } if(fallback != null && fallback.MaxCharCount == 1) { // Just return length, SBCS stay the same length because they don't map to surrogate // pairs and we don't have a decoder fallback. return count; } // Only need decoder fallback buffer if not using default replacement fallback, no best fit for ASCII DecoderFallbackBuffer fallbackBuffer = null; // Have to do it the hard way. // Assume charCount will be == count int charCount = count; byte[] byteBuffer = new byte[1]; // Do it our fast way byte* byteEnd = bytes + count; // Quick loop while(bytes < byteEnd) { // Faster if don't use *bytes++; byte b = *bytes; bytes++; // If unknown we have to do fallback count if(b >= 0x80) { if(fallbackBuffer == null) { if(decoder == null) { fallbackBuffer = this.DecoderFallback.CreateFallbackBuffer(); } else { fallbackBuffer = decoder.FallbackBuffer; } fallbackBuffer.InternalInitialize( byteEnd - count, null ); } // Use fallback buffer byteBuffer[0] = b; charCount--; // Have to unreserve the one we already allocated for b charCount += fallbackBuffer.InternalFallback( byteBuffer, bytes ); } } // Fallback buffer must be empty BCLDebug.Assert( fallbackBuffer == null || fallbackBuffer.Remaining == 0, "[ASCIIEncoding.GetCharCount]Expected Empty fallback buffer" ); // Converted sequence is same length as input return charCount; } internal override unsafe int GetChars( byte* bytes , int byteCount , char* chars , int charCount , DecoderNLS decoder ) { // Just need to ASSERT, this is called by something else internal that checked parameters already BCLDebug.Assert( bytes != null, "[ASCIIEncoding.GetChars]bytes is null" ); BCLDebug.Assert( byteCount >= 0, "[ASCIIEncoding.GetChars]byteCount is negative" ); BCLDebug.Assert( chars != null, "[ASCIIEncoding.GetChars]chars is null" ); BCLDebug.Assert( charCount >= 0, "[ASCIIEncoding.GetChars]charCount is negative" ); // Do it fast way if using ? replacement fallback byte* byteEnd = bytes + byteCount; byte* byteStart = bytes; char* charStart = chars; // Note: ASCII doesn't do best fit, but we have to fallback if they use something > 0x7f // Only need decoder fallback buffer if not using ? fallback. // ASCII doesn't do best fit, so don't have to check for it, find out which decoder fallback we're using DecoderReplacementFallback fallback = null; if(decoder == null) { fallback = this.DecoderFallback as DecoderReplacementFallback; } else { fallback = decoder.Fallback as DecoderReplacementFallback; BCLDebug.Assert( !decoder.m_throwOnOverflow || !decoder.InternalHasFallbackBuffer || decoder.FallbackBuffer.Remaining == 0, "[ASCIICodePageEncoding.GetChars]Expected empty fallback buffer" ); } if(fallback != null && fallback.MaxCharCount == 1) { // Try it the fast way char replacementChar = fallback.DefaultString[0]; // Need byteCount chars, otherwise too small buffer if(charCount < byteCount) { // Need at least 1 output byte, throw if must throw ThrowCharsOverflow( decoder, charCount < 1 ); // Not throwing, use what we can byteEnd = bytes + charCount; } // Quick loop, just do '?' replacement because we don't have fallbacks for decodings. while(bytes < byteEnd) { byte b = *(bytes++); if(b >= 0x80) { // This is an invalid byte in the ASCII encoding. *(chars++) = replacementChar; } else { *(chars++) = unchecked( (char)b ); } } // bytes & chars used are the same if(decoder != null) { decoder.m_bytesUsed = (int)(bytes - byteStart); } return (int)(chars - charStart); } // Slower way's going to need a fallback buffer DecoderFallbackBuffer fallbackBuffer = null; byte[] byteBuffer = new byte[1]; char* charEnd = chars + charCount; // Not quite so fast loop while(bytes < byteEnd) { // Faster if don't use *bytes++; byte b = *(bytes); bytes++; if(b >= 0x80) { // This is an invalid byte in the ASCII encoding. if(fallbackBuffer == null) { if(decoder == null) { fallbackBuffer = this.DecoderFallback.CreateFallbackBuffer(); } else { fallbackBuffer = decoder.FallbackBuffer; } fallbackBuffer.InternalInitialize( byteEnd - byteCount, charEnd ); } // Use fallback buffer byteBuffer[0] = b; // Note that chars won't get updated unless this succeeds if(!fallbackBuffer.InternalFallback( byteBuffer, bytes, ref chars )) { // May or may not throw, but we didn't get this byte BCLDebug.Assert( bytes > byteStart || chars == charStart, "[ASCIIEncoding.GetChars]Expected bytes to have advanced already (fallback case)" ); bytes--; // unused byte fallbackBuffer.InternalReset(); // Didn't fall this back ThrowCharsOverflow( decoder, chars == charStart ); // throw? break; // don't throw, but stop loop } } else { // Make sure we have buffer space if(chars >= charEnd) { BCLDebug.Assert( bytes > byteStart || chars == charStart, "[ASCIIEncoding.GetChars]Expected bytes to have advanced already (normal case)" ); bytes--; // unused byte ThrowCharsOverflow( decoder, chars == charStart ); // throw? break; // don't throw, but stop loop } *(chars) = unchecked( (char)b ); chars++; } } // Might have had decoder fallback stuff. if(decoder != null) { decoder.m_bytesUsed = (int)(bytes - byteStart); } // Expect Empty fallback buffer for GetChars BCLDebug.Assert( fallbackBuffer == null || fallbackBuffer.Remaining == 0, "[ASCIIEncoding.GetChars]Expected Empty fallback buffer" ); return (int)(chars - charStart); } public override int GetMaxByteCount( int charCount ) { if(charCount < 0) { #if EXCEPTION_STRINGS throw new ArgumentOutOfRangeException( "charCount", Environment.GetResourceString( "ArgumentOutOfRange_NeedNonNegNum" ) ); #else throw new ArgumentOutOfRangeException(); #endif } // Characters would be # of characters + 1 in case high surrogate is ? * max fallback long byteCount = (long)charCount + 1; if(EncoderFallback.MaxCharCount > 1) byteCount *= EncoderFallback.MaxCharCount; // 1 to 1 for most characters. Only surrogates with fallbacks have less. if(byteCount > 0x7fffffff) { #if EXCEPTION_STRINGS throw new ArgumentOutOfRangeException( "charCount", Environment.GetResourceString( "ArgumentOutOfRange_GetByteCountOverflow" ) ); #else throw new ArgumentOutOfRangeException(); #endif } return (int)byteCount; } public override int GetMaxCharCount( int byteCount ) { if(byteCount < 0) { #if EXCEPTION_STRINGS throw new ArgumentOutOfRangeException( "byteCount", Environment.GetResourceString( "ArgumentOutOfRange_NeedNonNegNum" ) ); #else throw new ArgumentOutOfRangeException(); #endif } // Just return length, SBCS stay the same length because they don't map to surrogate long charCount = (long)byteCount; // 1 to 1 for most characters. Only surrogates with fallbacks have less, unknown fallbacks could be longer. if(DecoderFallback.MaxCharCount > 1) { charCount *= DecoderFallback.MaxCharCount; } if(charCount > 0x7fffffff) { #if EXCEPTION_STRINGS throw new ArgumentOutOfRangeException( "byteCount", Environment.GetResourceString( "ArgumentOutOfRange_GetCharCountOverflow" ) ); #else throw new ArgumentOutOfRangeException(); #endif } return (int)charCount; } // True if and only if the encoding only uses single byte code points. (Ie, ASCII, 1252, etc) //// [System.Runtime.InteropServices.ComVisible( false )] public override bool IsSingleByte { get { return true; } } //// [System.Runtime.InteropServices.ComVisible( false )] public override Decoder GetDecoder() { return new DecoderNLS( this ); } //// [System.Runtime.InteropServices.ComVisible( false )] public override Encoder GetEncoder() { return new EncoderNLS( this ); } } } ================================================ FILE: Zelig/Zelig/RunTime/Framework/mscorlib/System/Text/Decoder.cs ================================================ // ==++== // // Copyright (c) Microsoft Corporation. All rights reserved. // // ==--== namespace System.Text { using System; using System.Text; ////using System.Runtime.Serialization; // A Decoder is used to decode a sequence of blocks of bytes into a // sequence of blocks of characters. Following instantiation of a decoder, // sequential blocks of bytes are converted into blocks of characters through // calls to the GetChars method. The decoder maintains state between the // conversions, allowing it to correctly decode byte sequences that span // adjacent blocks. // // Instances of specific implementations of the Decoder abstract base // class are typically obtained through calls to the GetDecoder method // of Encoding objects. // [Serializable()] public abstract class Decoder { internal DecoderFallback m_fallback = null; [NonSerialized] internal DecoderFallbackBuffer m_fallbackBuffer = null; //// internal void SerializeDecoder( SerializationInfo info ) //// { //// info.AddValue( "m_fallback", this.m_fallback ); //// } protected Decoder() { // We don't call default reset because default reset probably isn't good if we aren't initialized. } public DecoderFallback Fallback { get { return m_fallback; } set { if(value == null) { #if EXCEPTION_STRINGS throw new ArgumentNullException( "value" ); #else throw new ArgumentNullException(); #endif } // Can't change fallback if buffer is wrong if(m_fallbackBuffer != null && m_fallbackBuffer.Remaining > 0) { #if EXCEPTION_STRINGS throw new ArgumentException( Environment.GetResourceString( "Argument_FallbackBufferNotEmpty" ), "value" ); #else throw new ArgumentException(); #endif } m_fallback = value; m_fallbackBuffer = null; } } // Note: we don't test for threading here because async access to Encoders and Decoders // doesn't work anyway. public DecoderFallbackBuffer FallbackBuffer { get { if(m_fallbackBuffer == null) { if(m_fallback != null) { m_fallbackBuffer = m_fallback.CreateFallbackBuffer(); } else { m_fallbackBuffer = DecoderFallback.ReplacementFallback.CreateFallbackBuffer(); } } return m_fallbackBuffer; } } internal bool InternalHasFallbackBuffer { get { return m_fallbackBuffer != null; } } // Reset the Decoder // // Normally if we call GetChars() and an error is thrown we don't change the state of the Decoder. This // would allow the caller to correct the error condition and try again (such as if they need a bigger buffer.) // // If the caller doesn't want to try again after GetChars() throws an error, then they need to call Reset(). // // Virtual implimentation has to call GetChars with flush and a big enough buffer to clear a 0 byte string // We avoid GetMaxCharCount() because a) we can't call the base encoder and b) it might be really big. public virtual void Reset() { byte[] byteTemp = { }; char[] charTemp = new char[GetCharCount( byteTemp, 0, 0, true )]; GetChars( byteTemp, 0, 0, charTemp, 0, true ); if(m_fallbackBuffer != null) { m_fallbackBuffer.Reset(); } } // Returns the number of characters the next call to GetChars will // produce if presented with the given range of bytes. The returned value // takes into account the state in which the decoder was left following the // last call to GetChars. The state of the decoder is not affected // by a call to this method. // public abstract int GetCharCount( byte[] bytes , int index , int count ); public virtual int GetCharCount( byte[] bytes , int index , int count , bool flush ) { return GetCharCount( bytes, index, count ); } // We expect this to be the workhorse for NLS Encodings, but for existing // ones we need a working (if slow) default implimentation) [CLSCompliant( false )] public virtual unsafe int GetCharCount( byte* bytes , int count , bool flush ) { // Validate input parameters if(bytes == null) { #if EXCEPTION_STRINGS throw new ArgumentNullException( "bytes", Environment.GetResourceString( "ArgumentNull_Array" ) ); #else throw new ArgumentNullException(); #endif } if(count < 0) { #if EXCEPTION_STRINGS throw new ArgumentOutOfRangeException( "count", Environment.GetResourceString( "ArgumentOutOfRange_NeedNonNegNum" ) ); #else throw new ArgumentOutOfRangeException(); #endif } byte[] arrbyte = new byte[count]; int index; for(index = 0; index < count; index++) { arrbyte[index] = bytes[index]; } return GetCharCount( arrbyte, 0, count ); } // Decodes a range of bytes in a byte array into a range of characters // in a character array. The method decodes byteCount bytes from // bytes starting at index byteIndex, storing the resulting // characters in chars starting at index charIndex. The // decoding takes into account the state in which the decoder was left // following the last call to this method. // // An exception occurs if the character array is not large enough to // hold the complete decoding of the bytes. The GetCharCount method // can be used to determine the exact number of characters that will be // produced for a given range of bytes. Alternatively, the // GetMaxCharCount method of the Encoding that produced this // decoder can be used to determine the maximum number of characters that // will be produced for a given number of bytes, regardless of the actual // byte values. // public abstract int GetChars( byte[] bytes , int byteIndex , int byteCount , char[] chars , int charIndex ); public virtual int GetChars( byte[] bytes , int byteIndex , int byteCount , char[] chars , int charIndex , bool flush ) { return GetChars( bytes, byteIndex, byteCount, chars, charIndex ); } // We expect this to be the workhorse for NLS Encodings, but for existing // ones we need a working (if slow) default implimentation) // // WARNING WARNING WARNING // // WARNING: If this breaks it could be a security threat. Obviously we // call this internally, so you need to make sure that your pointers, counts // and indexes are correct when you call this method. // // In addition, we have internal code, which will be marked as "safe" calling // this code. However this code is dependent upon the implimentation of an // external GetChars() method, which could be overridden by a third party and // the results of which cannot be guaranteed. We use that result to copy // the char[] to our char* output buffer. If the result count was wrong, we // could easily overflow our output buffer. Therefore we do an extra test // when we copy the buffer so that we don't overflow charCount either. [CLSCompliant( false )] public virtual unsafe int GetChars( byte* bytes , int byteCount , char* chars , int charCount , bool flush ) { // Validate input parameters if(chars == null || bytes == null) { #if EXCEPTION_STRINGS throw new ArgumentNullException( chars == null ? "chars" : "bytes", Environment.GetResourceString( "ArgumentNull_Array" ) ); #else throw new ArgumentNullException(); #endif } if(byteCount < 0 || charCount < 0) { #if EXCEPTION_STRINGS throw new ArgumentOutOfRangeException( (byteCount < 0 ? "byteCount" : "charCount"), Environment.GetResourceString( "ArgumentOutOfRange_NeedNonNegNum" ) ); #else throw new ArgumentOutOfRangeException(); #endif } // Get the byte array to convert byte[] arrByte = new byte[byteCount]; int index; for(index = 0; index < byteCount; index++) { arrByte[index] = bytes[index]; } // Get the char array to fill char[] arrChar = new char[charCount]; // Do the work int result = GetChars( arrByte, 0, byteCount, arrChar, 0, flush ); // The only way this could fail is a bug in GetChars BCLDebug.Assert( result <= charCount, "Returned more chars than we have space for" ); // Copy the char array // WARNING: We MUST make sure that we don't copy too many chars. We can't // rely on result because it could be a 3rd party implimentation. We need // to make sure we never copy more than charCount chars no matter the value // of result if(result < charCount) { charCount = result; } // We check both result and charCount so that we don't accidentally overrun // our pointer buffer just because of any GetChars bug. for(index = 0; index < charCount; index++) { chars[index] = arrChar[index]; } return charCount; } // This method is used when the output buffer might not be large enough. // It will decode until it runs out of bytes, and then it will return // true if it the entire input was converted. In either case it // will also return the number of converted bytes and output characters used. // It will only throw a buffer overflow exception if the entire lenght of chars[] is // too small to store the next char. (like 0 or maybe 1 or 4 for some encodings) // We're done processing this buffer only if completed returns true. // // Might consider checking Max...Count to avoid the extra counting step. // // Note that if all of the input bytes are not consumed, then we'll do a /2, which means // that its likely that we didn't consume as many bytes as we could have. For some // applications this could be slow. (Like trying to exactly fill an output buffer from a bigger stream) public virtual void Convert( byte[] bytes , int byteIndex , int byteCount , char[] chars , int charIndex , int charCount , bool flush , out int bytesUsed , out int charsUsed , out bool completed ) { // Validate parameters if(bytes == null || chars == null) { #if EXCEPTION_STRINGS throw new ArgumentNullException( (bytes == null ? "bytes" : "chars"), Environment.GetResourceString( "ArgumentNull_Array" ) ); #else throw new ArgumentNullException(); #endif } if(byteIndex < 0 || byteCount < 0) { #if EXCEPTION_STRINGS throw new ArgumentOutOfRangeException( (byteIndex < 0 ? "byteIndex" : "byteCount"), Environment.GetResourceString( "ArgumentOutOfRange_NeedNonNegNum" ) ); #else throw new ArgumentOutOfRangeException(); #endif } if(charIndex < 0 || charCount < 0) { #if EXCEPTION_STRINGS throw new ArgumentOutOfRangeException( (charIndex < 0 ? "charIndex" : "charCount"), Environment.GetResourceString( "ArgumentOutOfRange_NeedNonNegNum" ) ); #else throw new ArgumentOutOfRangeException(); #endif } if(bytes.Length - byteIndex < byteCount) { #if EXCEPTION_STRINGS throw new ArgumentOutOfRangeException( "bytes", Environment.GetResourceString( "ArgumentOutOfRange_IndexCountBuffer" ) ); #else throw new ArgumentOutOfRangeException(); #endif } if(chars.Length - charIndex < charCount) { #if EXCEPTION_STRINGS throw new ArgumentOutOfRangeException( "chars", Environment.GetResourceString( "ArgumentOutOfRange_IndexCountBuffer" ) ); #else throw new ArgumentOutOfRangeException(); #endif } bytesUsed = byteCount; // Its easy to do if it won't overrun our buffer. while(bytesUsed > 0) { if(GetCharCount( bytes, byteIndex, bytesUsed, flush ) <= charCount) { charsUsed = GetChars( bytes, byteIndex, bytesUsed, chars, charIndex, flush ); completed = (bytesUsed == byteCount && (m_fallbackBuffer == null || m_fallbackBuffer.Remaining == 0)); return; } // Try again with 1/2 the count, won't flush then 'cause won't read it all flush = false; bytesUsed /= 2; } // Oops, we didn't have anything, we'll have to throw an overflow #if EXCEPTION_STRINGS throw new ArgumentException( Environment.GetResourceString( "Argument_ConversionOverflow" ) ); #else throw new ArgumentException(); #endif } // This is the version that uses *. // We're done processing this buffer only if completed returns true. // // Might consider checking Max...Count to avoid the extra counting step. // // Note that if all of the input bytes are not consumed, then we'll do a /2, which means // that its likely that we didn't consume as many bytes as we could have. For some // applications this could be slow. (Like trying to exactly fill an output buffer from a bigger stream) [CLSCompliant( false )] public virtual unsafe void Convert( byte* bytes , int byteCount , char* chars , int charCount , bool flush , out int bytesUsed , out int charsUsed , out bool completed ) { // Validate input parameters if(chars == null || bytes == null) { #if EXCEPTION_STRINGS throw new ArgumentNullException( chars == null ? "chars" : "bytes", Environment.GetResourceString( "ArgumentNull_Array" ) ); #else throw new ArgumentNullException(); #endif } if(byteCount < 0 || charCount < 0) { #if EXCEPTION_STRINGS throw new ArgumentOutOfRangeException( (byteCount < 0 ? "byteCount" : "charCount"), Environment.GetResourceString( "ArgumentOutOfRange_NeedNonNegNum" ) ); #else throw new ArgumentOutOfRangeException(); #endif } // Get ready to do it bytesUsed = byteCount; // Its easy to do if it won't overrun our buffer. while(bytesUsed > 0) { if(GetCharCount( bytes, bytesUsed, flush ) <= charCount) { charsUsed = GetChars( bytes, bytesUsed, chars, charCount, flush ); completed = (bytesUsed == byteCount && (m_fallbackBuffer == null || m_fallbackBuffer.Remaining == 0)); return; } // Try again with 1/2 the count, won't flush then 'cause won't read it all flush = false; bytesUsed /= 2; } // Oops, we didn't have anything, we'll have to throw an overflow #if EXCEPTION_STRINGS throw new ArgumentException( Environment.GetResourceString( "Argument_ConversionOverflow" ) ); #else throw new ArgumentException(); #endif } } } ================================================ FILE: Zelig/Zelig/RunTime/Framework/mscorlib/System/Text/DecoderBestFitFallback.cs ================================================ // ==++== // // Copyright (c) Microsoft Corporation. All rights reserved. // // ==--== // DecoderBestFitFallback.cs // // This is used internally to create best fit behavior as per the original windows best fit behavior. // namespace System.Text { using System; using System.Text; using System.Threading; [Serializable()] internal sealed class InternalDecoderBestFitFallback : DecoderFallback { // Our variables internal Encoding encoding = null; internal char[] arrayBestFit = null; internal char cReplacement = '?'; internal InternalDecoderBestFitFallback( Encoding encoding ) { // Need to load our replacement characters table. this.encoding = encoding; this.bIsMicrosoftBestFitFallback = true; } public override DecoderFallbackBuffer CreateFallbackBuffer() { return new InternalDecoderBestFitFallbackBuffer( this ); } // Maximum number of characters that this instance of this fallback could return public override int MaxCharCount { get { return 1; } } public override bool Equals( Object value ) { InternalDecoderBestFitFallback that = value as InternalDecoderBestFitFallback; if(that != null) { return (this.encoding.CodePage == that.encoding.CodePage); } return (false); } public override int GetHashCode() { return this.encoding.CodePage; } } internal sealed class InternalDecoderBestFitFallbackBuffer : DecoderFallbackBuffer { // Our variables internal char cBestFit = '\0'; internal int iCount = -1; internal int iSize; private InternalDecoderBestFitFallback oFallback; // Private object for locking instead of locking on a public type for SQL reliability work. private static Object s_InternalSyncObject; private static Object InternalSyncObject { get { if(s_InternalSyncObject == null) { Object o = new Object(); Interlocked.CompareExchange( ref s_InternalSyncObject, o, null ); } return s_InternalSyncObject; } } // Constructor public InternalDecoderBestFitFallbackBuffer( InternalDecoderBestFitFallback fallback ) { this.oFallback = fallback; if(oFallback.arrayBestFit == null) { // Lock so we don't confuse ourselves. lock(InternalSyncObject) { // Double check before we do it again. if(oFallback.arrayBestFit == null) { oFallback.arrayBestFit = fallback.encoding.GetBestFitBytesToUnicodeData(); } } } } // Fallback methods public override bool Fallback( byte[] bytesUnknown, int index ) { // We expect no previous fallback in our buffer BCLDebug.Assert( iCount < 1, "[DecoderReplacementFallbackBuffer.Fallback] Calling fallback without a previously empty buffer" ); cBestFit = TryBestFit( bytesUnknown ); if(cBestFit == '\0') { cBestFit = oFallback.cReplacement; } iCount = iSize = 1; return true; } // Default version is overridden in DecoderReplacementFallback.cs public override char GetNextChar() { // Just return cReturn, which is 0 if there's no best fit for it. return (iCount-- > 0) ? cBestFit : '\0'; } public override bool MovePrevious() { // Exception fallback doesn't have anywhere to back up to. if(iCount >= 0) { iCount++; } // Return true if we could do it. return (iCount >= 0 && iCount <= iSize); } // How many characters left to output? public override int Remaining { get { return (iCount > 0) ? iCount : 0; } } // Clear the buffer public override unsafe void Reset() { iCount = -1; byteStart = null; } // This version just counts the fallback and doesn't actually copy anything. internal unsafe override int InternalFallback( byte[] bytes, byte* pBytes ) // Right now this has both bytes and bytes[], which is silly, but we might have extra bytes, hence the // array, and we might need the index, hence the byte* { // return our replacement string Length (always 1 for InternalDecoderBestFitFallback, either // a best fit char or ? return 1; } // private helper methods private char TryBestFit( byte[] bytesCheck ) { // Need to figure out our best fit character, low is beginning of array, high is 1 AFTER end of array int lowBound = 0; int highBound = oFallback.arrayBestFit.Length; int index; char cCheck; // Check trivial case first (no best fit) if(highBound == 0) { return '\0'; } // If our array is too small or too big we can't check if(bytesCheck.Length == 0 || bytesCheck.Length > 2) { return '\0'; } if(bytesCheck.Length == 1) { cCheck = unchecked( (char)bytesCheck[0] ); } else { cCheck = unchecked( (char)((bytesCheck[0] << 8) + bytesCheck[1]) ); } // Check trivial out of range case if(cCheck < oFallback.arrayBestFit[0] || cCheck > oFallback.arrayBestFit[highBound - 2]) { return '\0'; } // Binary search the array int iDiff; while((iDiff = (highBound - lowBound)) > 6) { // Look in the middle, which is complicated by the fact that we have 2 #s for each pair, // so we don't want index to be odd because it must be word aligned. // Also note that index can never == highBound (because diff is rounded down) index = ((iDiff / 2) + lowBound) & 0xFFFE; char cTest = oFallback.arrayBestFit[index]; if(cTest == cCheck) { // We found it BCLDebug.Assert( index + 1 < oFallback.arrayBestFit.Length, "[InternalDecoderBestFitFallbackBuffer.TryBestFit]Expected replacement character at end of array" ); return oFallback.arrayBestFit[index + 1]; } else if(cTest < cCheck) { // We weren't high enough lowBound = index; } else { // We weren't low enough highBound = index; } } for(index = lowBound; index < highBound; index += 2) { if(oFallback.arrayBestFit[index] == cCheck) { // We found it BCLDebug.Assert( index + 1 < oFallback.arrayBestFit.Length, "[InternalDecoderBestFitFallbackBuffer.TryBestFit]Expected replacement character at end of array" ); return oFallback.arrayBestFit[index + 1]; } } // Char wasn't in our table return '\0'; } } } ================================================ FILE: Zelig/Zelig/RunTime/Framework/mscorlib/System/Text/DecoderExceptionFallback.cs ================================================ // ==++== // // Copyright (c) Microsoft Corporation. All rights reserved. // // ==--== // DecoderExceptionFallback.cs // namespace System.Text { using System; using System.Runtime.Serialization; using System.Globalization; [Serializable] public sealed class DecoderExceptionFallback : DecoderFallback { // Construction public DecoderExceptionFallback() { } public override DecoderFallbackBuffer CreateFallbackBuffer() { return new DecoderExceptionFallbackBuffer(); } // Maximum number of characters that this instance of this fallback could return public override int MaxCharCount { get { return 0; } } public override bool Equals( Object value ) { DecoderExceptionFallback that = value as DecoderExceptionFallback; if(that != null) { return (true); } return (false); } public override int GetHashCode() { return 879; } } public sealed class DecoderExceptionFallbackBuffer : DecoderFallbackBuffer { public override bool Fallback( byte[] bytesUnknown, int index ) { Throw( bytesUnknown, index ); return true; } public override char GetNextChar() { return (char)0; } public override bool MovePrevious() { // Exception fallback doesn't have anywhere to back up to. return false; } // Exceptions are always empty public override int Remaining { get { return 0; } } private void Throw( byte[] bytesUnknown, int index ) { // Create a string representation of our bytes. StringBuilder strBytes = new StringBuilder( bytesUnknown.Length * 3 ); int i; for(i = 0; i < bytesUnknown.Length && i < 20; i++) { strBytes.Append( "[" ); strBytes.Append( bytesUnknown[i].ToString( "X2", CultureInfo.InvariantCulture ) ); strBytes.Append( "]" ); } // In case the string's really long if(i == 20) { strBytes.Append( " ..." ); } // Known index #if EXCEPTION_STRINGS throw new DecoderFallbackException( Environment.GetResourceString( "Argument_InvalidCodePageBytesIndex", strBytes, index ), bytesUnknown, index ); #else throw new DecoderFallbackException(); #endif } } // Exception for decoding unknown byte sequences. [Serializable] public sealed class DecoderFallbackException : ArgumentException { byte[] bytesUnknown = null; int index = 0; public DecoderFallbackException() : base( Environment.GetResourceString( "Arg_ArgumentException" ) ) { //// SetErrorCode( __HResults.COR_E_ARGUMENT ); } public DecoderFallbackException( String message ) : base( message ) { //// SetErrorCode( __HResults.COR_E_ARGUMENT ); } public DecoderFallbackException( String message, Exception innerException ) : base( message, innerException ) { //// SetErrorCode( __HResults.COR_E_ARGUMENT ); } //// internal DecoderFallbackException( SerializationInfo info, StreamingContext context ) : base( info, context ) //// { //// } public DecoderFallbackException( String message, byte[] bytesUnknown, int index ) : base( message ) { this.bytesUnknown = bytesUnknown; this.index = index; } public byte[] BytesUnknown { get { return (bytesUnknown); } } public int Index { get { return this.index; } } } } ================================================ FILE: Zelig/Zelig/RunTime/Framework/mscorlib/System/Text/DecoderFallback.cs ================================================ // ==++== // // Copyright (c) Microsoft Corporation. All rights reserved. // // ==--== // using System; using System.Threading; using System.Globalization; namespace System.Text { [Serializable] public abstract class DecoderFallback { internal bool bIsMicrosoftBestFitFallback = false; private static DecoderFallback replacementFallback; // Default fallback, uses no best fit & "?" private static DecoderFallback exceptionFallback; // Private object for locking instead of locking on a internal type for SQL reliability work. private static Object s_InternalSyncObject; private static Object InternalSyncObject { get { if(s_InternalSyncObject == null) { Object o = new Object(); Interlocked.CompareExchange( ref s_InternalSyncObject, o, null ); } return s_InternalSyncObject; } } // Get each of our generic fallbacks. public static DecoderFallback ReplacementFallback { get { if(replacementFallback == null) { lock(InternalSyncObject) { if(replacementFallback == null) { replacementFallback = new DecoderReplacementFallback(); } } } return replacementFallback; } } public static DecoderFallback ExceptionFallback { get { if(exceptionFallback == null) { lock(InternalSyncObject) { if(exceptionFallback == null) { exceptionFallback = new DecoderExceptionFallback(); } } } return exceptionFallback; } } // Fallback // // Return the appropriate unicode string alternative to the character that need to fall back. // Most implimentations will be: // return new MyCustomDecoderFallbackBuffer(this); public abstract DecoderFallbackBuffer CreateFallbackBuffer(); // Maximum number of characters that this instance of this fallback could return public abstract int MaxCharCount { get; } internal bool IsMicrosoftBestFitFallback { get { return bIsMicrosoftBestFitFallback; } } } public abstract class DecoderFallbackBuffer { // Most implimentations will probably need an implimenation-specific constructor // internal methods that cannot be overriden that let us do our fallback thing // These wrap the internal methods so that we can check for people doing stuff that's too silly public abstract bool Fallback( byte[] bytesUnknown, int index ); // Get next character public abstract char GetNextChar(); // Back up a character public abstract bool MovePrevious(); // How many chars left in this fallback? public abstract int Remaining { get; } // Clear the buffer public virtual void Reset() { while(GetNextChar() != (char)0) ; } // Internal items to help us figure out what we're doing as far as error messages, etc. // These help us with our performance and messages internally internal unsafe byte* byteStart = null; internal unsafe char* charEnd = null; // Internal Reset internal unsafe void InternalReset() { byteStart = null; Reset(); } // Set the above values // This can't be part of the constructor because DecoderFallbacks would have to know how to impliment these. internal unsafe void InternalInitialize( byte* byteStart, char* charEnd ) { this.byteStart = byteStart; this.charEnd = charEnd; } // Fallback the current byte by sticking it into the remaining char buffer. // This can only be called by our encodings (other have to use the public fallback methods), so // we can use our DecoderNLS here too (except we don't). // Returns true if we are successful, false if we can't fallback the character (no buffer space) // So caller needs to throw buffer space if return false. // Right now this has both bytes and bytes[], which is silly, but we might have extra bytes, hence the // array, and we might need the index, hence the byte* // Don't touch ref chars unless we succeed internal unsafe virtual bool InternalFallback( byte[] bytes, byte* pBytes, ref char* chars ) { // Copy bytes to array (slow, but right now that's what we get to do. // byte[] bytesUnknown = new byte[count]; // for (int i = 0; i < count; i++) // bytesUnknown[i] = *(bytes++); BCLDebug.Assert( byteStart != null, "[DecoderFallback.InternalFallback]Used InternalFallback without calling InternalInitialize" ); // See if there's a fallback character and we have an output buffer then copy our string. if(this.Fallback( bytes, (int)(pBytes - byteStart - bytes.Length) )) { // Copy the chars to our output char ch; char* charTemp = chars; bool bHighSurrogate = false; while((ch = GetNextChar()) != 0) { // Make sure no mixed up surrogates if(Char.IsSurrogate( ch )) { if(Char.IsHighSurrogate( ch )) { // High Surrogate if(bHighSurrogate) { #if EXCEPTION_STRINGS throw new ArgumentException( Environment.GetResourceString( "Argument_InvalidCharSequenceNoIndex" ) ); #else throw new ArgumentException(); #endif } bHighSurrogate = true; } else { // Low surrogate if(bHighSurrogate == false) { #if EXCEPTION_STRINGS throw new ArgumentException( Environment.GetResourceString( "Argument_InvalidCharSequenceNoIndex" ) ); #else throw new ArgumentException(); #endif } bHighSurrogate = false; } } if(charTemp >= charEnd) { // No buffer space return false; } *(charTemp++) = ch; } // Need to make sure that bHighSurrogate isn't true if(bHighSurrogate) { #if EXCEPTION_STRINGS throw new ArgumentException( Environment.GetResourceString( "Argument_InvalidCharSequenceNoIndex" ) ); #else throw new ArgumentException(); #endif } // Now we aren't going to be false, so its OK to update chars chars = charTemp; } return true; } // This version just counts the fallback and doesn't actually copy anything. internal unsafe virtual int InternalFallback( byte[] bytes, byte* pBytes ) // Right now this has both bytes and bytes[], which is silly, but we might have extra bytes, hence the // array, and we might need the index, hence the byte* { // Copy bytes to array (slow, but right now that's what we get to do. // byte[] bytesUnknown = new byte[count]; // for (int i = 0; i < count; i++) // bytesUnknown[i] = *(bytes++); BCLDebug.Assert( byteStart != null, "[DecoderFallback.InternalFallback]Used InternalFallback without calling InternalInitialize" ); // See if there's a fallback character and we have an output buffer then copy our string. if(this.Fallback( bytes, (int)(pBytes - byteStart - bytes.Length) )) { int count = 0; char ch; bool bHighSurrogate = false; while((ch = GetNextChar()) != 0) { // Make sure no mixed up surrogates if(Char.IsSurrogate( ch )) { if(Char.IsHighSurrogate( ch )) { // High Surrogate if(bHighSurrogate) { #if EXCEPTION_STRINGS throw new ArgumentException( Environment.GetResourceString( "Argument_InvalidCharSequenceNoIndex" ) ); #else throw new ArgumentException(); #endif } bHighSurrogate = true; } else { // Low surrogate if(bHighSurrogate == false) { #if EXCEPTION_STRINGS throw new ArgumentException( Environment.GetResourceString( "Argument_InvalidCharSequenceNoIndex" ) ); #else throw new ArgumentException(); #endif } bHighSurrogate = false; } } count++; } // Need to make sure that bHighSurrogate isn't true if(bHighSurrogate) { #if EXCEPTION_STRINGS throw new ArgumentException( Environment.GetResourceString( "Argument_InvalidCharSequenceNoIndex" ) ); #else throw new ArgumentException(); #endif } return count; } // If no fallback return 0 return 0; } // private helper methods internal void ThrowLastBytesRecursive( byte[] bytesUnknown ) { // Create a string representation of our bytes. StringBuilder strBytes = new StringBuilder( bytesUnknown.Length * 3 ); int i; for(i = 0; i < bytesUnknown.Length && i < 20; i++) { if(strBytes.Length > 0) { strBytes.Append( " " ); } strBytes.Append( String.Format( CultureInfo.InvariantCulture, "\\x{0:X2}", bytesUnknown[i] ) ); } // In case the string's really long if(i == 20) { strBytes.Append( " ..." ); } // Throw it, using our complete bytes #if EXCEPTION_STRINGS throw new ArgumentException( Environment.GetResourceString( "Argument_RecursiveFallbackBytes", strBytes.ToString() ), "bytesUnknown" ); #else throw new ArgumentException(); #endif } } } ================================================ FILE: Zelig/Zelig/RunTime/Framework/mscorlib/System/Text/DecoderNLS.cs ================================================ // ==++== // // Copyright (c) Microsoft Corporation. All rights reserved. // // ==--== namespace System.Text { using System; using System.Text; ////using System.Runtime.Serialization; ////using System.Security.Permissions; // A Decoder is used to decode a sequence of blocks of bytes into a // sequence of blocks of characters. Following instantiation of a decoder, // sequential blocks of bytes are converted into blocks of characters through // calls to the GetChars method. The decoder maintains state between the // conversions, allowing it to correctly decode byte sequences that span // adjacent blocks. // // Instances of specific implementations of the Decoder abstract base // class are typically obtained through calls to the GetDecoder method // of Encoding objects. // [Serializable()] internal class DecoderNLS : Decoder /*, ISerializable*/ { // Remember our encoding protected Encoding m_encoding; [NonSerialized] protected bool m_mustFlush; [NonSerialized] internal bool m_throwOnOverflow; [NonSerialized] internal int m_bytesUsed; #region Serialization //// // Constructor called by serialization. called during deserialization. //// internal DecoderNLS(SerializationInfo info, StreamingContext context) //// { //// throw new NotSupportedException( //// String.Format( //// System.Globalization.CultureInfo.CurrentCulture, //// Environment.GetResourceString("NotSupported_TypeCannotDeserialized"), this.GetType())); //// } //// //// // ISerializable implementation. called during serialization. //// [SecurityPermissionAttribute(SecurityAction.LinkDemand, Flags=SecurityPermissionFlag.SerializationFormatter)] //// void ISerializable.GetObjectData(SerializationInfo info, StreamingContext context) //// { //// SerializeDecoder(info); //// info.AddValue("encoding", this.m_encoding); //// info.SetType(typeof(Encoding.DefaultDecoder)); //// } #endregion Serialization internal DecoderNLS( Encoding encoding ) { this.m_encoding = encoding; this.m_fallback = this.m_encoding.DecoderFallback; this.Reset(); } // This is used by our child deserializers internal DecoderNLS( ) { this.m_encoding = null; this.Reset(); } public override void Reset() { if (m_fallbackBuffer != null) m_fallbackBuffer.Reset(); } public override unsafe int GetCharCount(byte[] bytes, int index, int count) { return GetCharCount(bytes, index, count, false); } public override unsafe int GetCharCount(byte[] bytes, int index, int count, bool flush) { // Validate Parameters if (bytes == null) { #if EXCEPTION_STRINGS throw new ArgumentNullException("bytes", Environment.GetResourceString("ArgumentNull_Array")); #else throw new ArgumentNullException(); #endif } if (index < 0 || count < 0) { #if EXCEPTION_STRINGS throw new ArgumentOutOfRangeException((index<0 ? "index" : "count"), Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum")); #else throw new ArgumentOutOfRangeException(); #endif } if (bytes.Length - index < count) { #if EXCEPTION_STRINGS throw new ArgumentOutOfRangeException("bytes", Environment.GetResourceString("ArgumentOutOfRange_IndexCountBuffer")); #else throw new ArgumentOutOfRangeException(); #endif } // Avoid null fixed problem if (bytes.Length == 0) { bytes = new byte[1]; } // Just call pointer version fixed (byte* pBytes = bytes) { return GetCharCount(pBytes + index, count, flush); } } public unsafe override int GetCharCount(byte* bytes, int count, bool flush) { // Validate parameters if (bytes == null) { #if EXCEPTION_STRINGS throw new ArgumentNullException("bytes", Environment.GetResourceString("ArgumentNull_Array")); #else throw new ArgumentNullException(); #endif } if (count < 0) { #if EXCEPTION_STRINGS throw new ArgumentOutOfRangeException("count", Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum")); #else throw new ArgumentOutOfRangeException(); #endif } // Remember the flush this.m_mustFlush = flush; this.m_throwOnOverflow = true; // By default just call the encoding version, no flush by default return m_encoding.GetCharCount(bytes, count, this); } public override unsafe int GetChars( byte[] bytes , int byteIndex , int byteCount , char[] chars , int charIndex ) { return GetChars(bytes, byteIndex, byteCount, chars, charIndex, false); } public override unsafe int GetChars( byte[] bytes , int byteIndex , int byteCount , char[] chars , int charIndex , bool flush ) { // Validate Parameters if (bytes == null || chars == null) { #if EXCEPTION_STRINGS throw new ArgumentNullException(bytes == null ? "bytes" : "chars", Environment.GetResourceString("ArgumentNull_Array")); #else throw new ArgumentNullException(); #endif } if (byteIndex < 0 || byteCount < 0) { #if EXCEPTION_STRINGS throw new ArgumentOutOfRangeException((byteIndex<0 ? "byteIndex" : "byteCount"), Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum")); #else throw new ArgumentOutOfRangeException(); #endif } if ( bytes.Length - byteIndex < byteCount) { #if EXCEPTION_STRINGS throw new ArgumentOutOfRangeException("bytes", Environment.GetResourceString("ArgumentOutOfRange_IndexCountBuffer")); #else throw new ArgumentOutOfRangeException(); #endif } if (charIndex < 0 || charIndex > chars.Length) { #if EXCEPTION_STRINGS throw new ArgumentOutOfRangeException("charIndex", Environment.GetResourceString("ArgumentOutOfRange_Index")); #else throw new ArgumentOutOfRangeException(); #endif } // Avoid empty input fixed problem if (bytes.Length == 0) { bytes = new byte[1]; } int charCount = chars.Length - charIndex; if (chars.Length == 0) { chars = new char[1]; } // Just call pointer version fixed (byte* pBytes = bytes) { fixed (char* pChars = chars) { // Remember that charCount is # to decode, not size of array return GetChars(pBytes + byteIndex, byteCount, pChars + charIndex, charCount, flush); } } } public unsafe override int GetChars( byte* bytes , int byteCount , char* chars , int charCount , bool flush ) { // Validate parameters if (chars == null || bytes == null) { #if EXCEPTION_STRINGS throw new ArgumentNullException((chars == null ? "chars" : "bytes"), Environment.GetResourceString("ArgumentNull_Array")); #else throw new ArgumentNullException(); #endif } if (byteCount < 0 || charCount < 0) { #if EXCEPTION_STRINGS throw new ArgumentOutOfRangeException((byteCount<0 ? "byteCount" : "charCount"), Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum")); #else throw new ArgumentOutOfRangeException(); #endif } // Remember our flush m_mustFlush = flush; m_throwOnOverflow = true; // By default just call the encoding's version return m_encoding.GetChars(bytes, byteCount, chars, charCount, this); } // This method is used when the output buffer might not be big enough. // Just call the pointer version. (This gets chars) public override unsafe void Convert( byte[] bytes , int byteIndex , int byteCount , char[] chars , int charIndex , int charCount , bool flush , out int bytesUsed , out int charsUsed , out bool completed ) { // Validate parameters if (bytes == null || chars == null) { #if EXCEPTION_STRINGS throw new ArgumentNullException((bytes == null ? "bytes" : "chars"), Environment.GetResourceString("ArgumentNull_Array")); #else throw new ArgumentNullException(); #endif } if (byteIndex < 0 || byteCount < 0) { #if EXCEPTION_STRINGS throw new ArgumentOutOfRangeException((byteIndex<0 ? "byteIndex" : "byteCount"), Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum")); #else throw new ArgumentOutOfRangeException(); #endif } if (charIndex < 0 || charCount < 0) { #if EXCEPTION_STRINGS throw new ArgumentOutOfRangeException((charIndex<0 ? "charIndex" : "charCount"), Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum")); #else throw new ArgumentOutOfRangeException(); #endif } if (bytes.Length - byteIndex < byteCount) { #if EXCEPTION_STRINGS throw new ArgumentOutOfRangeException("bytes", Environment.GetResourceString("ArgumentOutOfRange_IndexCountBuffer")); #else throw new ArgumentOutOfRangeException(); #endif } if (chars.Length - charIndex < charCount) { #if EXCEPTION_STRINGS throw new ArgumentOutOfRangeException("chars", Environment.GetResourceString("ArgumentOutOfRange_IndexCountBuffer")); #else throw new ArgumentOutOfRangeException(); #endif } // Avoid empty input problem if (bytes.Length == 0) { bytes = new byte[1]; } if (chars.Length == 0) { chars = new char[1]; } // Just call the pointer version (public overrides can't do this) fixed (byte* pBytes = bytes) { fixed (char* pChars = chars) { Convert(pBytes + byteIndex, byteCount, pChars + charIndex, charCount, flush, out bytesUsed, out charsUsed, out completed); } } } // This is the version that used pointers. We call the base encoding worker function // after setting our appropriate internal variables. This is getting chars public unsafe override void Convert( byte* bytes , int byteCount , char* chars , int charCount , bool flush , out int bytesUsed , out int charsUsed , out bool completed ) { // Validate input parameters if (chars == null || bytes == null) { #if EXCEPTION_STRINGS throw new ArgumentNullException(chars == null ? "chars" : "bytes", Environment.GetResourceString("ArgumentNull_Array")); #else throw new ArgumentNullException(); #endif } if (byteCount < 0 || charCount < 0) { #if EXCEPTION_STRINGS throw new ArgumentOutOfRangeException((byteCount<0 ? "byteCount" : "charCount"), Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum")); #else throw new ArgumentOutOfRangeException(); #endif } // We don't want to throw this.m_mustFlush = flush; this.m_throwOnOverflow = false; this.m_bytesUsed = 0; // Do conversion charsUsed = this.m_encoding.GetChars(bytes, byteCount, chars, charCount, this); bytesUsed = this.m_bytesUsed; // Its completed if they've used what they wanted AND if they didn't want flush or if we are flushed completed = (bytesUsed == byteCount) && (!flush || !this.HasState) && (m_fallbackBuffer == null || m_fallbackBuffer.Remaining == 0); // Our data thingys are now full, we can return } public bool MustFlush { get { return m_mustFlush; } } // Anything left in our decoder? internal virtual bool HasState { get { return false; } } // Allow encoding to clear our must flush instead of throwing (in ThrowCharsOverflow) internal void ClearMustFlush() { m_mustFlush = false; } } } ================================================ FILE: Zelig/Zelig/RunTime/Framework/mscorlib/System/Text/DecoderReplacementFallback.cs ================================================ // ==++== // // Copyright (c) Microsoft Corporation. All rights reserved. // // ==--== // DecoderReplacementFallback.cs // namespace System.Text { using System; [Serializable] public sealed class DecoderReplacementFallback : DecoderFallback { // Our variables private String strDefault; // Construction. Default replacement fallback uses no best fit and ? replacement string public DecoderReplacementFallback() : this( "?" ) { } public DecoderReplacementFallback( String replacement ) { if(replacement == null) { #if EXCEPTION_STRINGS throw new ArgumentNullException( "replacement" ); #else throw new ArgumentNullException(); #endif } // Make sure it doesn't have bad surrogate pairs bool bFoundHigh = false; for(int i = 0; i < replacement.Length; i++) { // Found a surrogate? if(Char.IsSurrogate( replacement, i )) { // High or Low? if(Char.IsHighSurrogate( replacement, i )) { // if already had a high one, stop if(bFoundHigh) { break; // break & throw at the bFoundHIgh below } bFoundHigh = true; } else { // Low, did we have a high? if(!bFoundHigh) { // Didn't have one, make if fail when we stop bFoundHigh = true; break; } // Clear flag bFoundHigh = false; } } // If last was high we're in trouble (not surrogate so not low surrogate, so break) else if(bFoundHigh) { break; } } if(bFoundHigh) { #if EXCEPTION_STRINGS throw new ArgumentException( Environment.GetResourceString( "Argument_InvalidCharSequenceNoIndex", "replacement" ) ); #else throw new ArgumentException(); #endif } strDefault = replacement; } public String DefaultString { get { return strDefault; } } public override DecoderFallbackBuffer CreateFallbackBuffer() { return new DecoderReplacementFallbackBuffer( this ); } // Maximum number of characters that this instance of this fallback could return public override int MaxCharCount { get { return strDefault.Length; } } public override bool Equals( Object value ) { DecoderReplacementFallback that = value as DecoderReplacementFallback; if(that != null) { return (this.strDefault == that.strDefault); } return (false); } public override int GetHashCode() { return strDefault.GetHashCode(); } } public sealed class DecoderReplacementFallbackBuffer : DecoderFallbackBuffer { // Store our default string private String strDefault; int fallbackCount = -1; int fallbackIndex = -1; // Construction public DecoderReplacementFallbackBuffer( DecoderReplacementFallback fallback ) { this.strDefault = fallback.DefaultString; } // Fallback Methods public override bool Fallback( byte[] bytesUnknown, int index ) { // We expect no previous fallback in our buffer BCLDebug.Assert( fallbackCount < 1, "[DecoderReplacementFallbackBuffer.Fallback] Calling fallback without a previously empty buffer" ); // We can't call recursively but others might (note, we don't test on last char!!!) if(fallbackCount >= 1) { ThrowLastBytesRecursive( bytesUnknown ); } // Go ahead and get our fallback if(strDefault.Length == 0) { return false; } fallbackCount = strDefault.Length; fallbackIndex = -1; return true; } public override char GetNextChar() { // We want it to get < 0 because == 0 means that the current/last character is a fallback // and we need to detect recursion. We could have a flag but we already have this counter. fallbackCount--; fallbackIndex++; // Do we have anything left? 0 is now last fallback char, negative is nothing left if(fallbackCount < 0) { return (char)0; } // Need to get it out of the buffer. BCLDebug.Assert( fallbackIndex < strDefault.Length && fallbackIndex >= 0, "Index exceeds buffer range" ); return strDefault[fallbackIndex]; } public override bool MovePrevious() { // Back up one, only if we just processed the last character (or earlier) if(fallbackCount >= -1 && fallbackIndex >= 0) { fallbackIndex--; fallbackCount++; return true; } // Return false 'cause we couldn't do it. return false; } // How many characters left to output? public override int Remaining { get { // Our count is 0 for 1 character left. return (fallbackCount < 0) ? 0 : fallbackCount; } } // Clear the buffer public override unsafe void Reset() { fallbackCount = -1; fallbackIndex = -1; byteStart = null; } // This version just counts the fallback and doesn't actually copy anything. internal unsafe override int InternalFallback( byte[] bytes, byte* pBytes ) // Right now this has both bytes and bytes[], which is silly, but we might have extra bytes, hence the // array, and we might need the index, hence the byte* { // return our replacement string Length return strDefault.Length; } } } ================================================ FILE: Zelig/Zelig/RunTime/Framework/mscorlib/System/Text/Encoder.cs ================================================ // ==++== // // Copyright (c) Microsoft Corporation. All rights reserved. // // ==--== namespace System.Text { using System; using System.Text; ////using System.Runtime.Serialization; // An Encoder is used to encode a sequence of blocks of characters into // a sequence of blocks of bytes. Following instantiation of an encoder, // sequential blocks of characters are converted into blocks of bytes through // calls to the GetBytes method. The encoder maintains state between the // conversions, allowing it to correctly encode character sequences that span // adjacent blocks. // // Instances of specific implementations of the Encoder abstract base // class are typically obtained through calls to the GetEncoder method // of Encoding objects. // [Serializable()] public abstract class Encoder { internal EncoderFallback m_fallback = null; [NonSerialized] internal EncoderFallbackBuffer m_fallbackBuffer = null; //// internal void SerializeEncoder( SerializationInfo info ) //// { //// info.AddValue( "m_fallback", this.m_fallback ); //// } protected Encoder() { // We don't call default reset because default reset probably isn't good if we aren't initialized. } public EncoderFallback Fallback { get { return m_fallback; } set { if(value == null) { #if EXCEPTION_STRINGS throw new ArgumentNullException( "value" ); #else throw new ArgumentNullException(); #endif } // Can't change fallback if buffer is wrong if(m_fallbackBuffer != null && m_fallbackBuffer.Remaining > 0) { #if EXCEPTION_STRINGS throw new ArgumentException( Environment.GetResourceString( "Argument_FallbackBufferNotEmpty" ), "value" ); #else throw new ArgumentException(); #endif } m_fallback = value; m_fallbackBuffer = null; } } // Note: we don't test for threading here because async access to Encoders and Decoders // doesn't work anyway. public EncoderFallbackBuffer FallbackBuffer { get { if(m_fallbackBuffer == null) { if(m_fallback != null) { m_fallbackBuffer = m_fallback.CreateFallbackBuffer(); } else { m_fallbackBuffer = EncoderFallback.ReplacementFallback.CreateFallbackBuffer(); } } return m_fallbackBuffer; } } internal bool InternalHasFallbackBuffer { get { return m_fallbackBuffer != null; } } // Reset the Encoder // // Normally if we call GetBytes() and an error is thrown we don't change the state of the encoder. This // would allow the caller to correct the error condition and try again (such as if they need a bigger buffer.) // // If the caller doesn't want to try again after GetBytes() throws an error, then they need to call Reset(). // // Virtual implimentation has to call GetBytes with flush and a big enough buffer to clear a 0 char string // We avoid GetMaxByteCount() because a) we can't call the base encoder and b) it might be really big. public virtual void Reset() { char[] charTemp = { }; byte[] byteTemp = new byte[GetByteCount( charTemp, 0, 0, true )]; GetBytes( charTemp, 0, 0, byteTemp, 0, true ); if(m_fallbackBuffer != null) { m_fallbackBuffer.Reset(); } } // Returns the number of bytes the next call to GetBytes will // produce if presented with the given range of characters and the given // value of the flush parameter. The returned value takes into // account the state in which the encoder was left following the last call // to GetBytes. The state of the encoder is not affected by a call // to this method. // public abstract int GetByteCount( char[] chars , int index , int count , bool flush ); // We expect this to be the workhorse for NLS encodings // unfortunately for existing overrides, it has to call the [] version, // which is really slow, so avoid this method if you might be calling external encodings. [CLSCompliant( false )] public virtual unsafe int GetByteCount( char* chars , int count , bool flush ) { // Validate input parameters if(chars == null) { #if EXCEPTION_STRINGS throw new ArgumentNullException( "chars", Environment.GetResourceString( "ArgumentNull_Array" ) ); #else throw new ArgumentNullException(); #endif } if(count < 0) { #if EXCEPTION_STRINGS throw new ArgumentOutOfRangeException( "count", Environment.GetResourceString( "ArgumentOutOfRange_NeedNonNegNum" ) ); #else throw new ArgumentOutOfRangeException(); #endif } char[] arrChar = new char[count]; int index; for(index = 0; index < count; index++) { arrChar[index] = chars[index]; } return GetByteCount( arrChar, 0, count, flush ); } // Encodes a range of characters in a character array into a range of bytes // in a byte array. The method encodes charCount characters from // chars starting at index charIndex, storing the resulting // bytes in bytes starting at index byteIndex. The encoding // takes into account the state in which the encoder was left following the // last call to this method. The flush parameter indicates whether // the encoder should flush any shift-states and partial characters at the // end of the conversion. To ensure correct termination of a sequence of // blocks of encoded bytes, the last call to GetBytes should specify // a value of true for the flush parameter. // // An exception occurs if the byte array is not large enough to hold the // complete encoding of the characters. The GetByteCount method can // be used to determine the exact number of bytes that will be produced for // a given range of characters. Alternatively, the GetMaxByteCount // method of the Encoding that produced this encoder can be used to // determine the maximum number of bytes that will be produced for a given // number of characters, regardless of the actual character values. // public abstract int GetBytes( char[] chars , int charIndex , int charCount , byte[] bytes , int byteIndex , bool flush ); // We expect this to be the workhorse for NLS Encodings, but for existing // ones we need a working (if slow) default implimentation) // // WARNING WARNING WARNING // // WARNING: If this breaks it could be a security threat. Obviously we // call this internally, so you need to make sure that your pointers, counts // and indexes are correct when you call this method. // // In addition, we have internal code, which will be marked as "safe" calling // this code. However this code is dependent upon the implimentation of an // external GetBytes() method, which could be overridden by a third party and // the results of which cannot be guaranteed. We use that result to copy // the byte[] to our byte* output buffer. If the result count was wrong, we // could easily overflow our output buffer. Therefore we do an extra test // when we copy the buffer so that we don't overflow byteCount either. [CLSCompliant( false )] public virtual unsafe int GetBytes( char* chars , int charCount , byte* bytes , int byteCount , bool flush ) { // Validate input parameters if(bytes == null || chars == null) { #if EXCEPTION_STRINGS throw new ArgumentNullException( bytes == null ? "bytes" : "chars", Environment.GetResourceString( "ArgumentNull_Array" ) ); #else throw new ArgumentNullException(); #endif } if(charCount < 0 || byteCount < 0) { #if EXCEPTION_STRINGS throw new ArgumentOutOfRangeException( (charCount < 0 ? "charCount" : "byteCount"), Environment.GetResourceString( "ArgumentOutOfRange_NeedNonNegNum" ) ); #else throw new ArgumentOutOfRangeException(); #endif } // Get the char array to convert char[] arrChar = new char[charCount]; int index; for(index = 0; index < charCount; index++) { arrChar[index] = chars[index]; } // Get the byte array to fill byte[] arrByte = new byte[byteCount]; // Do the work int result = GetBytes( arrChar, 0, charCount, arrByte, 0, flush ); // The only way this could fail is a bug in GetBytes BCLDebug.Assert( result <= byteCount, "Returned more bytes than we have space for" ); // Copy the byte array // WARNING: We MUST make sure that we don't copy too many bytes. We can't // rely on result because it could be a 3rd party implimentation. We need // to make sure we never copy more than byteCount bytes no matter the value // of result if(result < byteCount) { byteCount = result; } // Don't copy too many bytes! for(index = 0; index < byteCount; index++) { bytes[index] = arrByte[index]; } return byteCount; } // This method is used to avoid running out of output buffer space. // It will encode until it runs out of chars, and then it will return // true if it the entire input was converted. In either case it // will also return the number of converted chars and output bytes used. // It will only throw a buffer overflow exception if the entire lenght of bytes[] is // too small to store the next byte. (like 0 or maybe 1 or 4 for some encodings) // We're done processing this buffer only if completed returns true. // // Might consider checking Max...Count to avoid the extra counting step. // // Note that if all of the input chars are not consumed, then we'll do a /2, which means // that its likely that we didn't consume as many chars as we could have. For some // applications this could be slow. (Like trying to exactly fill an output buffer from a bigger stream) public virtual void Convert( char[] chars , int charIndex , int charCount , byte[] bytes , int byteIndex , int byteCount , bool flush , out int charsUsed , out int bytesUsed , out bool completed ) { // Validate parameters if(chars == null || bytes == null) { #if EXCEPTION_STRINGS throw new ArgumentNullException( (chars == null ? "chars" : "bytes"), Environment.GetResourceString( "ArgumentNull_Array" ) ); #else throw new ArgumentNullException(); #endif } if(charIndex < 0 || charCount < 0) { #if EXCEPTION_STRINGS throw new ArgumentOutOfRangeException( (charIndex < 0 ? "charIndex" : "charCount"), Environment.GetResourceString( "ArgumentOutOfRange_NeedNonNegNum" ) ); #else throw new ArgumentOutOfRangeException(); #endif } if(byteIndex < 0 || byteCount < 0) { #if EXCEPTION_STRINGS throw new ArgumentOutOfRangeException( (byteIndex < 0 ? "byteIndex" : "byteCount"), Environment.GetResourceString( "ArgumentOutOfRange_NeedNonNegNum" ) ); #else throw new ArgumentOutOfRangeException(); #endif } if(chars.Length - charIndex < charCount) { #if EXCEPTION_STRINGS throw new ArgumentOutOfRangeException( "chars", Environment.GetResourceString( "ArgumentOutOfRange_IndexCountBuffer" ) ); #else throw new ArgumentOutOfRangeException(); #endif } if(bytes.Length - byteIndex < byteCount) { #if EXCEPTION_STRINGS throw new ArgumentOutOfRangeException( "bytes", Environment.GetResourceString( "ArgumentOutOfRange_IndexCountBuffer" ) ); #else throw new ArgumentOutOfRangeException(); #endif } charsUsed = charCount; // Its easy to do if it won't overrun our buffer. // Note: We don't want to call unsafe version because that might be an untrusted version // which could be really unsafe and we don't want to mix it up. while(charsUsed > 0) { if(GetByteCount( chars, charIndex, charsUsed, flush ) <= byteCount) { bytesUsed = GetBytes( chars, charIndex, charsUsed, bytes, byteIndex, flush ); completed = (charsUsed == charCount && (m_fallbackBuffer == null || m_fallbackBuffer.Remaining == 0)); return; } // Try again with 1/2 the count, won't flush then 'cause won't read it all flush = false; charsUsed /= 2; } // Oops, we didn't have anything, we'll have to throw an overflow #if EXCEPTION_STRINGS throw new ArgumentException( Environment.GetResourceString( "Argument_ConversionOverflow" ) ); #else throw new ArgumentException(); #endif } // Same thing, but using pointers // // Might consider checking Max...Count to avoid the extra counting step. // // Note that if all of the input chars are not consumed, then we'll do a /2, which means // that its likely that we didn't consume as many chars as we could have. For some // applications this could be slow. (Like trying to exactly fill an output buffer from a bigger stream) [CLSCompliant( false )] public virtual unsafe void Convert( char* chars , int charCount , byte* bytes , int byteCount , bool flush , out int charsUsed , out int bytesUsed , out bool completed ) { // Validate input parameters if(bytes == null || chars == null) { #if EXCEPTION_STRINGS throw new ArgumentNullException( bytes == null ? "bytes" : "chars", Environment.GetResourceString( "ArgumentNull_Array" ) ); #else throw new ArgumentNullException(); #endif } if(charCount < 0 || byteCount < 0) { #if EXCEPTION_STRINGS throw new ArgumentOutOfRangeException( (charCount < 0 ? "charCount" : "byteCount"), Environment.GetResourceString( "ArgumentOutOfRange_NeedNonNegNum" ) ); #else throw new ArgumentOutOfRangeException(); #endif } // Get ready to do it charsUsed = charCount; // Its easy to do if it won't overrun our buffer. while(charsUsed > 0) { if(GetByteCount( chars, charsUsed, flush ) <= byteCount) { bytesUsed = GetBytes( chars, charsUsed, bytes, byteCount, flush ); completed = (charsUsed == charCount && (m_fallbackBuffer == null || m_fallbackBuffer.Remaining == 0)); return; } // Try again with 1/2 the count, won't flush then 'cause won't read it all flush = false; charsUsed /= 2; } // Oops, we didn't have anything, we'll have to throw an overflow #if EXCEPTION_STRINGS throw new ArgumentException( Environment.GetResourceString( "Argument_ConversionOverflow" ) ); #else throw new ArgumentException(); #endif } } } ================================================ FILE: Zelig/Zelig/RunTime/Framework/mscorlib/System/Text/EncoderBestFitFallback.cs ================================================ // ==++== // // Copyright (c) Microsoft Corporation. All rights reserved. // // ==--== // EncoderBestFitFallback.cs // // This is used internally to create best fit behavior as per the original windows best fit behavior. // namespace System.Text { using System; using System.Globalization; using System.Text; using System.Threading; [Serializable()] internal class InternalEncoderBestFitFallback : EncoderFallback { // Our variables internal Encoding encoding = null; internal char[] arrayBestFit = null; internal InternalEncoderBestFitFallback( Encoding encoding ) { // Need to load our replacement characters table. this.encoding = encoding; this.bIsMicrosoftBestFitFallback = true; } public override EncoderFallbackBuffer CreateFallbackBuffer() { return new InternalEncoderBestFitFallbackBuffer( this ); } // Maximum number of characters that this instance of this fallback could return public override int MaxCharCount { get { return 1; } } public override bool Equals( Object value ) { InternalEncoderBestFitFallback that = value as InternalEncoderBestFitFallback; if(that != null) { return (this.encoding.CodePage == that.encoding.CodePage); } return (false); } public override int GetHashCode() { return this.encoding.CodePage; } } internal sealed class InternalEncoderBestFitFallbackBuffer : EncoderFallbackBuffer { // Our variables private char cBestFit = '\0'; private InternalEncoderBestFitFallback oFallback; private int iCount = -1; private int iSize; // Private object for locking instead of locking on a public type for SQL reliability work. private static Object s_InternalSyncObject; private static Object InternalSyncObject { get { if(s_InternalSyncObject == null) { Object o = new Object(); Interlocked.CompareExchange( ref s_InternalSyncObject, o, null ); } return s_InternalSyncObject; } } // Constructor public InternalEncoderBestFitFallbackBuffer( InternalEncoderBestFitFallback fallback ) { this.oFallback = fallback; if(oFallback.arrayBestFit == null) { // Lock so we don't confuse ourselves. lock(InternalSyncObject) { // Double check before we do it again. if(oFallback.arrayBestFit == null) { oFallback.arrayBestFit = fallback.encoding.GetBestFitUnicodeToBytesData(); } } } } // Fallback methods public override bool Fallback( char charUnknown, int index ) { // If we had a buffer already we're being recursive, throw, it's probably at the suspect // character in our array. // Shouldn't be able to get here for all of our code pages, table would have to be messed up. BCLDebug.Assert( iCount < 1, "[InternalEncoderBestFitFallbackBuffer.Fallback(non surrogate)] Fallback char " + ((int)cBestFit).ToString( "X4", CultureInfo.InvariantCulture ) + " caused recursive fallback" ); iCount = iSize = 1; cBestFit = TryBestFit( charUnknown ); if(cBestFit == '\0') { cBestFit = '?'; } return true; } public override bool Fallback( char charUnknownHigh, char charUnknownLow, int index ) { // Double check input surrogate pair if(!Char.IsHighSurrogate( charUnknownHigh )) { #if EXCEPTION_STRINGS throw new ArgumentOutOfRangeException( "charUnknownHigh", Environment.GetResourceString( "ArgumentOutOfRange_Range", 0xD800, 0xDBFF ) ); #else throw new ArgumentOutOfRangeException(); #endif } if(!Char.IsLowSurrogate( charUnknownLow )) { #if EXCEPTION_STRINGS throw new ArgumentOutOfRangeException( "CharUnknownLow", Environment.GetResourceString( "ArgumentOutOfRange_Range", 0xDC00, 0xDFFF ) ); #else throw new ArgumentOutOfRangeException(); #endif } // If we had a buffer already we're being recursive, throw, it's probably at the suspect // character in our array. 0 is processing last character, < 0 is not falling back // Shouldn't be able to get here, table would have to be messed up. BCLDebug.Assert( iCount < 1, "[InternalEncoderBestFitFallbackBuffer.Fallback(surrogate)] Fallback char " + ((int)cBestFit).ToString( "X4", CultureInfo.InvariantCulture ) + " caused recursive fallback" ); // Go ahead and get our fallback, surrogates don't have best fit cBestFit = '?'; iCount = iSize = 2; return true; } // Default version is overridden in EncoderReplacementFallback.cs public override char GetNextChar() { // Just return cReturn, which is 0 if there's no best fit for it. return (iCount-- > 0) ? cBestFit : '\0'; } public override bool MovePrevious() { // Exception fallback doesn't have anywhere to back up to. if(iCount >= 0) iCount++; // Return true if we could do it. return (iCount >= 0 && iCount <= iSize); } // How many characters left to output? public override int Remaining { get { return (iCount > 0) ? iCount : 0; } } // Clear the buffer public override unsafe void Reset() { iCount = -1; charStart = null; bFallingBack = false; } // private helper methods private char TryBestFit( char cUnknown ) { // Need to figure out our best fit character, low is beginning of array, high is 1 AFTER end of array int lowBound = 0; int highBound = oFallback.arrayBestFit.Length; int index; // Binary search the array int iDiff; while((iDiff = (highBound - lowBound)) > 6) { // Look in the middle, which is complicated by the fact that we have 2 #s for each pair, // so we don't want index to be odd because we want to be on word boundaries. // Also note that index can never == highBound (because diff is rounded down) index = ((iDiff / 2) + lowBound) & 0xFFFE; char cTest = oFallback.arrayBestFit[index]; if(cTest == cUnknown) { // We found it BCLDebug.Assert( index + 1 < oFallback.arrayBestFit.Length, "[InternalEncoderBestFitFallbackBuffer.TryBestFit]Expected replacement character at end of array" ); return oFallback.arrayBestFit[index + 1]; } else if(cTest < cUnknown) { // We weren't high enough lowBound = index; } else { // We weren't low enough highBound = index; } } for(index = lowBound; index < highBound; index += 2) { if(oFallback.arrayBestFit[index] == cUnknown) { // We found it BCLDebug.Assert( index + 1 < oFallback.arrayBestFit.Length, "[InternalEncoderBestFitFallbackBuffer.TryBestFit]Expected replacement character at end of array" ); return oFallback.arrayBestFit[index + 1]; } } // Char wasn't in our table return '\0'; } } } ================================================ FILE: Zelig/Zelig/RunTime/Framework/mscorlib/System/Text/EncoderExceptionFallback.cs ================================================ // ==++== // // Copyright (c) Microsoft Corporation. All rights reserved. // // ==--== // EncoderExceptionFallback.cs namespace System.Text { using System; using System.Runtime.Serialization; [Serializable] public sealed class EncoderExceptionFallback : EncoderFallback { // Construction public EncoderExceptionFallback() { } public override EncoderFallbackBuffer CreateFallbackBuffer() { return new EncoderExceptionFallbackBuffer(); } // Maximum number of characters that this instance of this fallback could return public override int MaxCharCount { get { return 0; } } public override bool Equals( Object value ) { EncoderExceptionFallback that = value as EncoderExceptionFallback; if(that != null) { return (true); } return (false); } public override int GetHashCode() { return 654; } } public sealed class EncoderExceptionFallbackBuffer : EncoderFallbackBuffer { public override bool Fallback( char charUnknown, int index ) { // Fall back our char #if EXCEPTION_STRINGS throw new EncoderFallbackException( Environment.GetResourceString( "Argument_InvalidCodePageConversionIndex", (int)charUnknown, index ), charUnknown, index ); #else throw new EncoderFallbackException(); #endif } public override bool Fallback( char charUnknownHigh, char charUnknownLow, int index ) { if(!Char.IsHighSurrogate( charUnknownHigh )) { #if EXCEPTION_STRINGS throw new ArgumentOutOfRangeException( "charUnknownHigh", Environment.GetResourceString( "ArgumentOutOfRange_Range", 0xD800, 0xDBFF ) ); #else throw new ArgumentOutOfRangeException(); #endif } if(!Char.IsLowSurrogate( charUnknownLow )) { #if EXCEPTION_STRINGS throw new ArgumentOutOfRangeException( "CharUnknownLow", Environment.GetResourceString( "ArgumentOutOfRange_Range", 0xDC00, 0xDFFF ) ); #else throw new ArgumentOutOfRangeException(); #endif } int iTemp = Char.ConvertToUtf32( charUnknownHigh, charUnknownLow ); // Fall back our char #if EXCEPTION_STRINGS throw new EncoderFallbackException( Environment.GetResourceString( "Argument_InvalidCodePageConversionIndex", iTemp, index ), charUnknownHigh, charUnknownLow, index ); #else throw new EncoderFallbackException(); #endif } public override char GetNextChar() { return (char)0; } public override bool MovePrevious() { // Exception fallback doesn't have anywhere to back up to. return false; } // Exceptions are always empty public override int Remaining { get { return 0; } } } [Serializable] public sealed class EncoderFallbackException : ArgumentException { char charUnknown; char charUnknownHigh; char charUnknownLow; int index; public EncoderFallbackException() : base( Environment.GetResourceString( "Arg_ArgumentException" ) ) { //// SetErrorCode( __HResults.COR_E_ARGUMENT ); } public EncoderFallbackException( String message ) : base( message ) { //// SetErrorCode( __HResults.COR_E_ARGUMENT ); } public EncoderFallbackException( String message, Exception innerException ) : base( message, innerException ) { //// SetErrorCode( __HResults.COR_E_ARGUMENT ); } //// internal EncoderFallbackException( SerializationInfo info, StreamingContext context ) : base( info, context ) //// { //// } internal EncoderFallbackException( String message, char charUnknown, int index ) : base( message ) { this.charUnknown = charUnknown; this.index = index; } internal EncoderFallbackException( String message, char charUnknownHigh, char charUnknownLow, int index ) : base( message ) { if(!Char.IsHighSurrogate( charUnknownHigh )) { #if EXCEPTION_STRINGS throw new ArgumentOutOfRangeException( "charUnknownHigh", Environment.GetResourceString( "ArgumentOutOfRange_Range", 0xD800, 0xDBFF ) ); #else throw new ArgumentOutOfRangeException(); #endif } if(!Char.IsLowSurrogate( charUnknownLow )) { #if EXCEPTION_STRINGS throw new ArgumentOutOfRangeException( "CharUnknownLow", Environment.GetResourceString( "ArgumentOutOfRange_Range", 0xDC00, 0xDFFF ) ); #else throw new ArgumentOutOfRangeException(); #endif } this.charUnknownHigh = charUnknownHigh; this.charUnknownLow = charUnknownLow; this.index = index; } public char CharUnknown { get { return (charUnknown); } } public char CharUnknownHigh { get { return (charUnknownHigh); } } public char CharUnknownLow { get { return (charUnknownLow); } } public int Index { get { return index; } } // Return true if the unknown character is a surrogate pair. public bool IsUnknownSurrogate() { return (this.charUnknownHigh != '\0'); } } } ================================================ FILE: Zelig/Zelig/RunTime/Framework/mscorlib/System/Text/EncoderFallback.cs ================================================ // ==++== // // Copyright (c) Microsoft Corporation. All rights reserved. // // ==--== using System; using System.Threading; namespace System.Text { [Serializable] public abstract class EncoderFallback { internal bool bIsMicrosoftBestFitFallback = false; private static EncoderFallback replacementFallback; // Default fallback, uses no best fit & "?" private static EncoderFallback exceptionFallback; // Private object for locking instead of locking on a public type for SQL reliability work. private static Object s_InternalSyncObject; private static Object InternalSyncObject { get { if(s_InternalSyncObject == null) { Object o = new Object(); Interlocked.CompareExchange( ref s_InternalSyncObject, o, null ); } return s_InternalSyncObject; } } // Get each of our generic fallbacks. public static EncoderFallback ReplacementFallback { get { if(replacementFallback == null) lock(InternalSyncObject) if(replacementFallback == null) replacementFallback = new EncoderReplacementFallback(); return replacementFallback; } } public static EncoderFallback ExceptionFallback { get { if(exceptionFallback == null) { lock(InternalSyncObject) { if(exceptionFallback == null) { exceptionFallback = new EncoderExceptionFallback(); } } } return exceptionFallback; } } // Fallback // // Return the appropriate unicode string alternative to the character that need to fall back. // Most implimentations will be: // return new MyCustomEncoderFallbackBuffer(this); public abstract EncoderFallbackBuffer CreateFallbackBuffer(); // Maximum number of characters that this instance of this fallback could return public abstract int MaxCharCount { get; } } public abstract class EncoderFallbackBuffer { // Most implimentations will probably need an implimenation-specific constructor // Public methods that cannot be overriden that let us do our fallback thing // These wrap the internal methods so that we can check for people doing stuff that's too silly public abstract bool Fallback( char charUnknown, int index ); public abstract bool Fallback( char charUnknownHigh, char charUnknownLow, int index ); // Get next character public abstract char GetNextChar(); // Back up a character public abstract bool MovePrevious(); // How many chars left in this fallback? public abstract int Remaining { get; } // Not sure if this should be public or not. // Clear the buffer public virtual void Reset() { while(GetNextChar() != (char)0) ; } // Internal items to help us figure out what we're doing as far as error messages, etc. // These help us with our performance and messages internally internal unsafe char* charStart = null; internal unsafe char* charEnd; internal EncoderNLS encoder; internal bool setEncoder; internal bool bUsedEncoder; internal bool bFallingBack = false; internal int iRecursionCount = 0; private const int iMaxRecursion = 250; // Internal Reset // For example, what if someone fails a conversion and wants to reset one of our fallback buffers? internal unsafe void InternalReset() { charStart = null; bFallingBack = false; iRecursionCount = 0; Reset(); } // Set the above values // This can't be part of the constructor because EncoderFallbacks would have to know how to impliment these. internal unsafe void InternalInitialize( char* charStart, char* charEnd, EncoderNLS encoder, bool setEncoder ) { this.charStart = charStart; this.charEnd = charEnd; this.encoder = encoder; this.setEncoder = setEncoder; this.bUsedEncoder = false; this.bFallingBack = false; this.iRecursionCount = 0; } internal char InternalGetNextChar() { char ch = GetNextChar(); bFallingBack = (ch != 0); if(ch == 0) iRecursionCount = 0; return ch; } // Fallback the current character using the remaining buffer and encoder if necessary // This can only be called by our encodings (other have to use the public fallback methods), so // we can use our EncoderNLS here too. // setEncoder is true if we're calling from a GetBytes method, false if we're calling from a GetByteCount // // Note that this could also change the contents of this.encoder, which is the same // object that the caller is using, so the caller could mess up the encoder for us // if they aren't careful. internal unsafe virtual bool InternalFallback( char ch, ref char* chars ) { // Shouldn't have null charStart BCLDebug.Assert( charStart != null, "[EncoderFallback.InternalFallbackBuffer]Fallback buffer is not initialized" ); // Get our index, remember chars was preincremented to point at next char, so have to -1 int index = (int)(chars - charStart) - 1; // See if it was a high surrogate if(Char.IsHighSurrogate( ch )) { // See if there's a low surrogate to go with it if(chars >= this.charEnd) { // Nothing left in input buffer // No input, return 0 if mustflush is false if(this.encoder != null && !this.encoder.MustFlush) { // Done, nothing to fallback if(this.setEncoder) { bUsedEncoder = true; this.encoder.charLeftOver = ch; } bFallingBack = false; return false; } } else { // Might have a low surrogate char cNext = *chars; if(Char.IsLowSurrogate( cNext )) { // If already falling back then fail if(bFallingBack && iRecursionCount++ > iMaxRecursion) ThrowLastCharRecursive( Char.ConvertToUtf32( ch, cNext ) ); // Next is a surrogate, add it as surrogate pair, and increment chars chars++; bFallingBack = Fallback( ch, cNext, index ); return bFallingBack; } // Next isn't a low surrogate, just fallback the high surrogate } } // If already falling back then fail if(bFallingBack && iRecursionCount++ > iMaxRecursion) ThrowLastCharRecursive( (int)ch ); // Fall back our char bFallingBack = Fallback( ch, index ); return bFallingBack; } // private helper methods internal void ThrowLastCharRecursive( int charRecursive ) { // Throw it, using our complete character #if EXCEPTION_STRINGS throw new ArgumentException( Environment.GetResourceString( "Argument_RecursiveFallback", charRecursive ), "chars" ); #else throw new ArgumentException(); #endif } } } ================================================ FILE: Zelig/Zelig/RunTime/Framework/mscorlib/System/Text/EncoderNLS.cs ================================================ // ==++== // // Copyright (c) Microsoft Corporation. All rights reserved. // // ==--== namespace System.Text { using System; using System.Text; ////using System.Runtime.Serialization; ////using System.Security.Permissions; // An Encoder is used to encode a sequence of blocks of characters into // a sequence of blocks of bytes. Following instantiation of an encoder, // sequential blocks of characters are converted into blocks of bytes through // calls to the GetBytes method. The encoder maintains state between the // conversions, allowing it to correctly encode character sequences that span // adjacent blocks. // // Instances of specific implementations of the Encoder abstract base // class are typically obtained through calls to the GetEncoder method // of Encoding objects. // [Serializable] internal class EncoderNLS : Encoder /*, ISerializable*/ { // Need a place for the last left over character, most of our encodings use this internal char charLeftOver; protected Encoding m_encoding; [NonSerialized] protected bool m_mustFlush; [NonSerialized] internal bool m_throwOnOverflow; [NonSerialized] internal int m_charsUsed; #region Serialization //// // Constructor called by serialization. called during deserialization. //// internal EncoderNLS(SerializationInfo info, StreamingContext context) //// { //// throw new NotSupportedException( //// String.Format( //// System.Globalization.CultureInfo.CurrentCulture, //// Environment.GetResourceString("NotSupported_TypeCannotDeserialized"), this.GetType())); //// } //// //// // ISerializable implementation. called during serialization. //// [SecurityPermissionAttribute(SecurityAction.LinkDemand, Flags=SecurityPermissionFlag.SerializationFormatter)] //// void ISerializable.GetObjectData(SerializationInfo info, StreamingContext context) //// { //// SerializeEncoder(info); //// info.AddValue("encoding", this.m_encoding); //// info.AddValue("charLeftOver", this.charLeftOver); //// info.SetType(typeof(Encoding.DefaultEncoder)); //// } #endregion Serialization internal EncoderNLS(Encoding encoding) { this.m_encoding = encoding; this.m_fallback = this.m_encoding.EncoderFallback; this.Reset(); } // This one is used when deserializing (like UTF7Encoding.Encoder) internal EncoderNLS() { this.m_encoding = null; this.Reset(); } public override void Reset() { this.charLeftOver = (char)0; if (m_fallbackBuffer != null) { m_fallbackBuffer.Reset(); } } public override unsafe int GetByteCount( char[] chars , int index , int count , bool flush ) { // Validate input parameters if (chars == null) { #if EXCEPTION_STRINGS throw new ArgumentNullException( "chars", Environment.GetResourceString("ArgumentNull_Array")); #else throw new ArgumentNullException(); #endif } if (index < 0 || count < 0) { #if EXCEPTION_STRINGS throw new ArgumentOutOfRangeException((index<0 ? "index" : "count"), Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum")); #else throw new ArgumentOutOfRangeException(); #endif } if (chars.Length - index < count) { #if EXCEPTION_STRINGS throw new ArgumentOutOfRangeException("chars", Environment.GetResourceString("ArgumentOutOfRange_IndexCountBuffer")); #else throw new ArgumentOutOfRangeException(); #endif } // Avoid empty input problem if (chars.Length == 0) { chars = new char[1]; } // Just call the pointer version fixed (char* pChars = chars) { return GetByteCount(pChars + index, count, flush); } } public unsafe override int GetByteCount( char* chars , int count , bool flush ) { // Validate input parameters if (chars == null) { #if EXCEPTION_STRINGS throw new ArgumentNullException( "chars", Environment.GetResourceString("ArgumentNull_Array")); #else throw new ArgumentNullException(); #endif } if (count < 0) { #if EXCEPTION_STRINGS throw new ArgumentOutOfRangeException("count", Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum")); #else throw new ArgumentOutOfRangeException(); #endif } this.m_mustFlush = flush; this.m_throwOnOverflow = true; return m_encoding.GetByteCount(chars, count, this); } public override unsafe int GetBytes( char[] chars , int charIndex , int charCount , byte[] bytes , int byteIndex , bool flush ) { // Validate parameters if (chars == null || bytes == null) { #if EXCEPTION_STRINGS throw new ArgumentNullException((chars == null ? "chars" : "bytes"), Environment.GetResourceString("ArgumentNull_Array")); #else throw new ArgumentNullException(); #endif } if (charIndex < 0 || charCount < 0) { #if EXCEPTION_STRINGS throw new ArgumentOutOfRangeException((charIndex<0 ? "charIndex" : "charCount"), Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum")); #else throw new ArgumentOutOfRangeException(); #endif } if (chars.Length - charIndex < charCount) { #if EXCEPTION_STRINGS throw new ArgumentOutOfRangeException("chars", Environment.GetResourceString("ArgumentOutOfRange_IndexCountBuffer")); #else throw new ArgumentOutOfRangeException(); #endif } if (byteIndex < 0 || byteIndex > bytes.Length) { #if EXCEPTION_STRINGS throw new ArgumentOutOfRangeException("byteIndex", Environment.GetResourceString("ArgumentOutOfRange_Index")); #else throw new ArgumentOutOfRangeException(); #endif } if (chars.Length == 0) { chars = new char[1]; } int byteCount = bytes.Length - byteIndex; if (bytes.Length == 0) { bytes = new byte[1]; } // Just call pointer version fixed (char* pChars = chars) { fixed (byte* pBytes = bytes) { // Remember that charCount is # to decode, not size of array. return GetBytes(pChars + charIndex, charCount, pBytes + byteIndex, byteCount, flush); } } } public unsafe override int GetBytes( char* chars , int charCount , byte* bytes , int byteCount , bool flush ) { // Validate parameters if (chars == null || bytes == null) { #if EXCEPTION_STRINGS throw new ArgumentNullException((chars == null ? "chars" : "bytes"), Environment.GetResourceString("ArgumentNull_Array")); #else throw new ArgumentNullException(); #endif } if (byteCount < 0 || charCount < 0) { #if EXCEPTION_STRINGS throw new ArgumentOutOfRangeException((byteCount<0 ? "byteCount" : "charCount"), Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum")); #else throw new ArgumentOutOfRangeException(); #endif } this.m_mustFlush = flush; this.m_throwOnOverflow = true; return m_encoding.GetBytes(chars, charCount, bytes, byteCount, this); } // This method is used when your output buffer might not be large enough for the entire result. // Just call the pointer version. (This gets bytes) public override unsafe void Convert( char[] chars , int charIndex , int charCount , byte[] bytes , int byteIndex , int byteCount , bool flush , out int charsUsed , out int bytesUsed , out bool completed ) { // Validate parameters if (chars == null || bytes == null) { #if EXCEPTION_STRINGS throw new ArgumentNullException((chars == null ? "chars" : "bytes"), Environment.GetResourceString("ArgumentNull_Array")); #else throw new ArgumentNullException(); #endif } if (charIndex < 0 || charCount < 0) { #if EXCEPTION_STRINGS throw new ArgumentOutOfRangeException((charIndex<0 ? "charIndex" : "charCount"), Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum")); #else throw new ArgumentOutOfRangeException(); #endif } if (byteIndex < 0 || byteCount < 0) { #if EXCEPTION_STRINGS throw new ArgumentOutOfRangeException((byteIndex<0 ? "byteIndex" : "byteCount"), Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum")); #else throw new ArgumentOutOfRangeException(); #endif } if (chars.Length - charIndex < charCount) { #if EXCEPTION_STRINGS throw new ArgumentOutOfRangeException("chars", Environment.GetResourceString("ArgumentOutOfRange_IndexCountBuffer")); #else throw new ArgumentOutOfRangeException(); #endif } if (bytes.Length - byteIndex < byteCount) { #if EXCEPTION_STRINGS throw new ArgumentOutOfRangeException("bytes", Environment.GetResourceString("ArgumentOutOfRange_IndexCountBuffer")); #else throw new ArgumentOutOfRangeException(); #endif } // Avoid empty input problem if (chars.Length == 0) { chars = new char[1]; } if (bytes.Length == 0) { bytes = new byte[1]; } // Just call the pointer version (can't do this for non-msft encoders) fixed (char* pChars = chars) { fixed (byte* pBytes = bytes) { Convert(pChars + charIndex, charCount, pBytes + byteIndex, byteCount, flush, out charsUsed, out bytesUsed, out completed); } } } // This is the version that uses pointers. We call the base encoding worker function // after setting our appropriate internal variables. This is getting bytes public override unsafe void Convert( char* chars , int charCount , byte* bytes , int byteCount , bool flush , out int charsUsed , out int bytesUsed , out bool completed ) { // Validate input parameters if (bytes == null || chars == null) { #if EXCEPTION_STRINGS throw new ArgumentNullException(bytes == null ? "bytes" : "chars", Environment.GetResourceString("ArgumentNull_Array")); #else throw new ArgumentNullException(); #endif } if (charCount < 0 || byteCount < 0) { #if EXCEPTION_STRINGS throw new ArgumentOutOfRangeException((charCount<0 ? "charCount" : "byteCount"), Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum")); #else throw new ArgumentOutOfRangeException(); #endif } // We don't want to throw this.m_mustFlush = flush; this.m_throwOnOverflow = false; this.m_charsUsed = 0; // Do conversion bytesUsed = this.m_encoding.GetBytes(chars, charCount, bytes, byteCount, this); charsUsed = this.m_charsUsed; // Its completed if they've used what they wanted AND if they didn't want flush or if we are flushed completed = (charsUsed == charCount) && (!flush || !this.HasState) && (m_fallbackBuffer == null || m_fallbackBuffer.Remaining == 0); // Our data thingys are now full, we can return } public Encoding Encoding { get { return m_encoding; } } public bool MustFlush { get { return m_mustFlush; } } // Anything left in our encoder? internal virtual bool HasState { get { return (this.charLeftOver != (char)0); } } // Allow encoding to clear our must flush instead of throwing (in ThrowBytesOverflow) internal void ClearMustFlush() { m_mustFlush = false; } } } ================================================ FILE: Zelig/Zelig/RunTime/Framework/mscorlib/System/Text/EncoderReplacementFallback.cs ================================================ // ==++== // // Copyright (c) Microsoft Corporation. All rights reserved. // // ==--== // EncoderReplacementFallback.cs // namespace System.Text { using System; [Serializable] public sealed class EncoderReplacementFallback : EncoderFallback { // Our variables private String strDefault; // Construction. Default replacement fallback uses no best fit and ? replacement string public EncoderReplacementFallback() : this( "?" ) { } public EncoderReplacementFallback( String replacement ) { // Must not be null if(replacement == null) { #if EXCEPTION_STRINGS throw new ArgumentNullException( "replacement" ); #else throw new ArgumentNullException(); #endif } // Make sure it doesn't have bad surrogate pairs bool bFoundHigh = false; for(int i = 0; i < replacement.Length; i++) { // Found a surrogate? if(Char.IsSurrogate( replacement, i )) { // High or Low? if(Char.IsHighSurrogate( replacement, i )) { // if already had a high one, stop if(bFoundHigh) { break; // break & throw at the bFoundHIgh below } bFoundHigh = true; } else { // Low, did we have a high? if(!bFoundHigh) { // Didn't have one, make if fail when we stop bFoundHigh = true; break; } // Clear flag bFoundHigh = false; } } // If last was high we're in trouble (not surrogate so not low surrogate, so break) else if(bFoundHigh) { break; } } if(bFoundHigh) { #if EXCEPTION_STRINGS throw new ArgumentException( Environment.GetResourceString( "Argument_InvalidCharSequenceNoIndex", "replacement" ) ); #else throw new ArgumentException(); #endif } strDefault = replacement; } public String DefaultString { get { return strDefault; } } public override EncoderFallbackBuffer CreateFallbackBuffer() { return new EncoderReplacementFallbackBuffer( this ); } // Maximum number of characters that this instance of this fallback could return public override int MaxCharCount { get { return strDefault.Length; } } public override bool Equals( Object value ) { EncoderReplacementFallback that = value as EncoderReplacementFallback; if(that != null) { return (this.strDefault == that.strDefault); } return (false); } public override int GetHashCode() { return strDefault.GetHashCode(); } } public sealed class EncoderReplacementFallbackBuffer : EncoderFallbackBuffer { // Store our default string private String strDefault; int fallbackCount = -1; int fallbackIndex = -1; // Construction public EncoderReplacementFallbackBuffer( EncoderReplacementFallback fallback ) { // 2X in case we're a surrogate pair this.strDefault = fallback.DefaultString + fallback.DefaultString; } // Fallback Methods public override bool Fallback( char charUnknown, int index ) { // If we had a buffer already we're being recursive, throw, it's probably at the suspect // character in our array. if(fallbackCount >= 1) { // If we're recursive we may still have something in our buffer that makes this a surrogate if(char.IsHighSurrogate( charUnknown ) && fallbackCount >= 0 && char.IsLowSurrogate( strDefault[fallbackIndex + 1] )) { ThrowLastCharRecursive( Char.ConvertToUtf32( charUnknown, strDefault[fallbackIndex + 1] ) ); } // Nope, just one character ThrowLastCharRecursive( unchecked( (int)charUnknown ) ); } // Go ahead and get our fallback // Divide by 2 because we aren't a surrogate pair fallbackCount = strDefault.Length / 2; fallbackIndex = -1; return fallbackCount != 0; } public override bool Fallback( char charUnknownHigh, char charUnknownLow, int index ) { // Double check input surrogate pair if(!Char.IsHighSurrogate( charUnknownHigh )) { #if EXCEPTION_STRINGS throw new ArgumentOutOfRangeException( "charUnknownHigh", Environment.GetResourceString( "ArgumentOutOfRange_Range", 0xD800, 0xDBFF ) ); #else throw new ArgumentOutOfRangeException(); #endif } if(!Char.IsLowSurrogate( charUnknownLow )) { #if EXCEPTION_STRINGS throw new ArgumentOutOfRangeException( "CharUnknownLow", Environment.GetResourceString( "ArgumentOutOfRange_Range", 0xDC00, 0xDFFF ) ); #else throw new ArgumentOutOfRangeException(); #endif } // If we had a buffer already we're being recursive, throw, it's probably at the suspect // character in our array. if(fallbackCount >= 1) { ThrowLastCharRecursive( Char.ConvertToUtf32( charUnknownHigh, charUnknownLow ) ); } // Go ahead and get our fallback fallbackCount = strDefault.Length; fallbackIndex = -1; return fallbackCount != 0; } public override char GetNextChar() { // We want it to get < 0 because == 0 means that the current/last character is a fallback // and we need to detect recursion. We could have a flag but we already have this counter. fallbackCount--; fallbackIndex++; // Do we have anything left? 0 is now last fallback char, negative is nothing left if(fallbackCount < 0) { return (char)0; } // Need to get it out of the buffer. BCLDebug.Assert( fallbackIndex < strDefault.Length && fallbackIndex >= 0, "Index exceeds buffer range" ); return strDefault[fallbackIndex]; } public override bool MovePrevious() { // Back up one, only if we just processed the last character (or earlier) if(fallbackCount >= -1 && fallbackIndex >= 0) { fallbackIndex--; fallbackCount++; return true; } // Return false 'cause we couldn't do it. return false; } // How many characters left to output? public override int Remaining { get { // Our count is 0 for 1 character left. return (fallbackCount < 0) ? 0 : fallbackCount; } } // Clear the buffer public override unsafe void Reset() { fallbackCount = -1; fallbackIndex = 0; charStart = null; bFallingBack = false; } } } ================================================ FILE: Zelig/Zelig/RunTime/Framework/mscorlib/System/Text/Encoding.cs ================================================ // ==++== // // Copyright (c) Microsoft Corporation. All rights reserved. // // ==--== namespace System.Text { using System; using System.Collections; ////using System.Runtime.Remoting; using System.Runtime.Serialization; using System.Globalization; using System.Security.Permissions; using System.Threading; using System.Text; using System.Runtime.CompilerServices; ////using Win32Native = Microsoft.Win32.Win32Native; // This abstract base class represents a character encoding. The class provides // methods to convert arrays and strings of Unicode characters to and from // arrays of bytes. A number of Encoding implementations are provided in // the System.Text package, including: // // ASCIIEncoding, which encodes Unicode characters as single 7-bit // ASCII characters. This encoding only supports character values between 0x00 // and 0x7F. // BaseCodePageEncoding, which encapsulates a Windows code page. Any // installed code page can be accessed through this encoding, and conversions // are performed using the WideCharToMultiByte and // MultiByteToWideChar Windows API functions. // UnicodeEncoding, which encodes each Unicode character as two // consecutive bytes. Both little-endian (code page 1200) and big-endian (code // page 1201) encodings are recognized. // UTF7Encoding, which encodes Unicode characters using the UTF-7 // encoding (UTF-7 stands for UCS Transformation Format, 7-bit form). This // encoding supports all Unicode character values, and can also be accessed // as code page 65000. // UTF8Encoding, which encodes Unicode characters using the UTF-8 // encoding (UTF-8 stands for UCS Transformation Format, 8-bit form). This // encoding supports all Unicode character values, and can also be accessed // as code page 65001. // UTF32Encoding, both 12000 (little endian) & 12001 (big endian) // // In addition to directly instantiating Encoding objects, an // application can use the ForCodePage, GetASCII, // GetDefault, GetUnicode, GetUTF7, and GetUTF8 // methods in this class to obtain encodings. // // Through an encoding, the GetBytes method is used to convert arrays // of characters to arrays of bytes, and the GetChars method is used to // convert arrays of bytes to arrays of characters. The GetBytes and // GetChars methods maintain no state between conversions, and are // generally intended for conversions of complete blocks of bytes and // characters in one operation. When the data to be converted is only available // in sequential blocks (such as data read from a stream) or when the amount of // data is so large that it needs to be divided into smaller blocks, an // application may choose to use a Decoder or an Encoder to // perform the conversion. Decoders and encoders allow sequential blocks of // data to be converted and they maintain the state required to support // conversions of data that spans adjacent blocks. Decoders and encoders are // obtained using the GetDecoder and GetEncoder methods. // // The core GetBytes and GetChars methods require the caller // to provide the destination buffer and ensure that the buffer is large enough // to hold the entire result of the conversion. When using these methods, // either directly on an Encoding object or on an associated // Decoder or Encoder, an application can use one of two methods // to allocate destination buffers. // // The GetByteCount and GetCharCount methods can be used to // compute the exact size of the result of a particular conversion, and an // appropriately sized buffer for that conversion can then be allocated. // The GetMaxByteCount and GetMaxCharCount methods can be // be used to compute the maximum possible size of a conversion of a given // number of bytes or characters, and a buffer of that size can then be reused // for multiple conversions. // // The first method generally uses less memory, whereas the second method // generally executes faster. // [Serializable()] public abstract class Encoding : ICloneable { //// private static Encoding defaultEncoding; private static Encoding unicodeEncoding; //// private static Encoding bigEndianUnicode; //// private static Encoding utf7Encoding; private static Encoding utf8Encoding; //// private static Encoding utf32Encoding; private static Encoding asciiEncoding; //// private static Encoding latin1Encoding; //// private static Hashtable encodings; //// //// // //// // The following values are from mlang.idl. These values //// // should be in sync with those in mlang.idl. //// // //// private const int MIMECONTF_MAILNEWS = 0x00000001; //// private const int MIMECONTF_BROWSER = 0x00000002; //// private const int MIMECONTF_SAVABLE_MAILNEWS = 0x00000100; //// private const int MIMECONTF_SAVABLE_BROWSER = 0x00000200; //// //// // Special Case Code Pages //// private const int CodePageDefault = 0; //// private const int CodePageNoOEM = 1; // OEM Code page not supported //// private const int CodePageNoMac = 2; // MAC code page not supported //// private const int CodePageNoThread = 3; // Thread code page not supported //// private const int CodePageNoSymbol = 42; // Symbol code page not supported //// private const int CodePageUnicode = 1200; // Unicode //// private const int CodePageBigEndian = 1201; // Big Endian Unicode //// private const int CodePageWindows1252 = 1252; // Windows 1252 code page //// //// // 20936 has same code page as 10008, so we'll special case it //// private const int CodePageMacGB2312 = 10008; //// private const int CodePageGB2312 = 20936; //// private const int CodePageMacKorean = 10003; //// private const int CodePageDLLKorean = 20949; //// //// // ISO 2022 Code Pages //// private const int ISO2022JP = 50220; //// private const int ISO2022JPESC = 50221; //// private const int ISO2022JPSISO = 50222; //// private const int ISOKorean = 50225; //// private const int ISOSimplifiedCN = 50227; //// private const int EUCJP = 51932; //// private const int ChineseHZ = 52936; // HZ has ~}~{~~ sequences //// //// // 51936 is the same as 936 //// private const int DuplicateEUCCN = 51936; //// private const int EUCCN = 936; //// //// private const int EUCKR = 51949; // Latin 1 & ASCII Code Pages internal const int CodePageASCII = 20127; // ASCII //// internal const int ISO_8859_1 = 28591; // Latin1 //// //// // ISCII //// private const int ISCIIAssemese = 57006; //// private const int ISCIIBengali = 57003; //// private const int ISCIIDevanagari = 57002; //// private const int ISCIIGujarathi = 57010; //// private const int ISCIIKannada = 57008; //// private const int ISCIIMalayalam = 57009; //// private const int ISCIIOriya = 57007; //// private const int ISCIIPanjabi = 57011; //// private const int ISCIITamil = 57004; //// private const int ISCIITelugu = 57005; //// //// // GB18030 //// private const int GB18030 = 54936; //// //// // Other //// private const int ISO_8859_8I = 38598; //// private const int ISO_8859_8_Visual = 28598; //// //// // 50229 is currently unsupported // "Chinese Traditional (ISO-2022)" //// private const int ENC50229 = 50229; //// //// // Special code pages //// private const int CodePageUTF7 = 65000; //// private const int CodePageUTF8 = 65001; //// private const int CodePageUTF32 = 12000; //// private const int CodePageUTF32BE = 12001; internal int m_codePage = 0; //// // dataItem should be internal (not private). otherwise it will break during the deserialization //// // of the data came from Everett //// internal CodePageDataItem dataItem = null; //// //// [NonSerialized] //// internal bool m_deserializedFromEverett = false; // Because of encoders we may be read only [OptionalField( VersionAdded = 2 )] private bool m_isReadOnly = true; // Encoding (encoder) fallback [OptionalField( VersionAdded = 2 )] internal EncoderFallback encoderFallback = null; [OptionalField( VersionAdded = 2 )] internal DecoderFallback decoderFallback = null; // Useful for Encodings whose GetPreamble method must return an // empty byte array. internal static readonly byte[] emptyByteArray = new byte[0]; protected Encoding() : this( 0 ) { } protected Encoding( int codePage ) { // Validate code page if(codePage < 0) { #if EXCEPTION_STRINGS throw new ArgumentOutOfRangeException( "codePage" ); #else throw new ArgumentOutOfRangeException(); #endif } // Remember code page m_codePage = codePage; // Use default encoder/decoder fallbacks this.SetDefaultFallbacks(); } // Default fallback that we'll use. internal virtual void SetDefaultFallbacks() { // For UTF-X encodings, we use a replacement fallback with an empty string, // For ASCII we use "?" replacement fallback, etc. this.encoderFallback = new InternalEncoderBestFitFallback( this ); this.decoderFallback = new InternalDecoderBestFitFallback( this ); } //// #region Serialization //// internal void OnDeserializing() //// { //// // intialize the optional Whidbey fields //// encoderFallback = null; //// decoderFallback = null; //// m_isReadOnly = true; //// } //// //// internal void OnDeserialized() //// { //// if(encoderFallback == null || decoderFallback == null) //// { //// m_deserializedFromEverett = true; //// SetDefaultFallbacks(); //// } //// } //// //// [OnDeserializing] //// private void OnDeserializing( StreamingContext ctx ) //// { //// OnDeserializing(); //// } //// //// //// [OnDeserialized] //// private void OnDeserialized( StreamingContext ctx ) //// { //// OnDeserialized(); //// } //// //// [OnSerializing] //// private void OnSerializing( StreamingContext ctx ) //// { //// // to be consistent with SerializeEncoding //// dataItem = null; //// } //// //// // the following two methods are used for the inherited classes which implemented ISerializable //// // Deserialization Helper //// internal void DeserializeEncoding( SerializationInfo info, StreamingContext context ) //// { //// // Any info? //// if(info == null) throw new ArgumentNullException( "info" ); //// //// // All versions have a code page //// this.m_codePage = (int)info.GetValue( "m_codePage", typeof( int ) ); //// //// // We can get dataItem on the fly if needed, and the index is different between versions //// // so ignore whatever dataItem data we get from Everett. //// this.dataItem = null; //// //// // See if we have a code page //// try //// { //// // //// // Try Whidbey V2.0 Fields //// // //// //// this.m_isReadOnly = (bool)info.GetValue( "m_isReadOnly", typeof( bool ) ); //// //// this.encoderFallback = (EncoderFallback)info.GetValue( "encoderFallback", typeof( EncoderFallback ) ); //// this.decoderFallback = (DecoderFallback)info.GetValue( "decoderFallback", typeof( DecoderFallback ) ); //// } //// catch(SerializationException) //// { //// // //// // Didn't have Whidbey things, must be Everett //// // //// this.m_deserializedFromEverett = true; //// //// // May as well be read only //// this.m_isReadOnly = true; //// SetDefaultFallbacks(); //// } //// } //// //// // Serialization Helper //// internal void SerializeEncoding( SerializationInfo info, StreamingContext context ) //// { //// // Any Info? //// if(info == null) throw new ArgumentNullException( "info" ); //// //// // These are new V2.0 Whidbey stuff //// info.AddValue( "m_isReadOnly", this.m_isReadOnly ); //// info.AddValue( "encoderFallback", this.EncoderFallback ); //// info.AddValue( "decoderFallback", this.DecoderFallback ); //// //// // These were in Everett V1.1 as well //// info.AddValue( "m_codePage", this.m_codePage ); //// //// // This was unique to Everett V1.1 //// info.AddValue( "dataItem", (CodePageDataItem)null ); //// //// // Everett duplicated these fields, so these are needed for portability //// info.AddValue( "Encoding+m_codePage", this.m_codePage ); //// info.AddValue( "Encoding+dataItem", (CodePageDataItem)null ); //// } //// //// #endregion Serialization //// // Converts a byte array from one encoding to another. The bytes in the //// // bytes array are converted from srcEncoding to //// // dstEncoding, and the returned value is a new byte array //// // containing the result of the conversion. //// // //// //// public static byte[] Convert( Encoding srcEncoding, Encoding dstEncoding, //// byte[] bytes ) //// { //// if(bytes == null) //// throw new ArgumentNullException( "bytes" ); //// return Convert( srcEncoding, dstEncoding, bytes, 0, bytes.Length ); //// } //// //// // Converts a range of bytes in a byte array from one encoding to another. //// // This method converts count bytes from bytes starting at //// // index index from srcEncoding to dstEncoding, and //// // returns a new byte array containing the result of the conversion. //// // //// //// public static byte[] Convert( Encoding srcEncoding, Encoding dstEncoding, //// byte[] bytes, int index, int count ) //// { //// if(srcEncoding == null || dstEncoding == null) //// { //// throw new ArgumentNullException( (srcEncoding == null ? "srcEncoding" : "dstEncoding"), //// Environment.GetResourceString( "ArgumentNull_Array" ) ); //// } //// if(bytes == null) //// { //// throw new ArgumentNullException( "bytes", //// Environment.GetResourceString( "ArgumentNull_Array" ) ); //// } //// return dstEncoding.GetBytes( srcEncoding.GetChars( bytes, index, count ) ); //// } //// //// // Private object for locking instead of locking on a public type for SQL reliability work. //// private static Object s_InternalSyncObject; //// private static Object InternalSyncObject //// { //// get //// { //// if(s_InternalSyncObject == null) //// { //// Object o = new Object(); //// Interlocked.CompareExchange( ref s_InternalSyncObject, o, null ); //// } //// return s_InternalSyncObject; //// } //// } //// //// //// public static Encoding GetEncoding( int codepage ) //// { //// // //// // NOTE: If you add a new encoding that can be get by codepage, be sure to //// // add the corresponding item in EncodingTable. //// // Otherwise, the code below will throw exception when trying to call //// // EncodingTable.GetDataItem(). //// // //// if(codepage < 0 || codepage > 65535) //// { //// throw new ArgumentOutOfRangeException( //// "codepage", Environment.GetResourceString( "ArgumentOutOfRange_Range", //// 0, 65535 ) ); //// } //// //// // Our Encoding //// Encoding result = null; //// //// // See if we have a hash table with our encoding in it already. //// if(encodings != null) //// result = (Encoding)encodings[codepage]; //// //// if(result == null) //// { //// // Don't conflict with ourselves //// lock(InternalSyncObject) //// { //// // Need a new hash table //// if(encodings == null) encodings = new Hashtable(); //// //// // Double check that we don't have one in the table (in case another thread beat us here) //// if((result = (Encoding)encodings[codepage]) != null) //// return result; //// //// // Special case the commonly used Encoding classes here, then call //// // GetEncodingRare to avoid loading classes like MLangCodePageEncoding //// // and ASCIIEncoding. ASP.NET uses UTF-8 & ISO-8859-1. //// switch(codepage) //// { //// case CodePageDefault: // 0, default code page //// result = Encoding.Default; //// break; //// case CodePageUnicode: // 1200, Unicode //// result = Unicode; //// break; //// case CodePageBigEndian: // 1201, big endian unicode //// result = BigEndianUnicode; //// break; //// case CodePageWindows1252: // 1252, Windows //// result = new SBCSCodePageEncoding( codepage ); //// break; //// case CodePageUTF8: // 65001, UTF8 //// result = UTF8; //// break; //// //// // These are (hopefully) not very common, but also shouldn't slow us down much and make default //// // case able to handle more code pages by calling GetEncodingCodePage //// case CodePageNoOEM: // 1 //// case CodePageNoMac: // 2 //// case CodePageNoThread: // 3 //// case CodePageNoSymbol: // 42 //// // Win32 also allows the following special code page values. We won't allow them except in the //// // CP_ACP case. //// // #define CP_ACP 0 // default to ANSI code page //// // #define CP_OEMCP 1 // default to OEM code page //// // #define CP_MACCP 2 // default to MAC code page //// // #define CP_THREAD_ACP 3 // current thread's ANSI code page //// // #define CP_SYMBOL 42 // SYMBOL translations //// throw new ArgumentException( Environment.GetResourceString( //// "Argument_CodepageNotSupported", codepage ), "codepage" ); //// //// // Have to do ASCII and Latin 1 first so they don't get loaded as code pages //// case CodePageASCII: // 20127 //// result = ASCII; //// break; //// case ISO_8859_1: // 28591 //// result = Latin1; //// break; //// default: //// { //// // 1st assume its a code page. //// result = GetEncodingCodePage( codepage ); //// if(result == null) //// result = GetEncodingRare( codepage ); //// break; //// } //// } //// encodings.Add( codepage, result ); //// } //// //// } //// return result; //// } //// //// //// public static Encoding GetEncoding( int codepage, //// EncoderFallback encoderFallback, DecoderFallback decoderFallback ) //// { //// // Get the default encoding (which is cached and read only) //// Encoding baseEncoding = GetEncoding( codepage ); //// //// // Clone it and set the fallback //// Encoding fallbackEncoding = (Encoding)baseEncoding.Clone(); //// fallbackEncoding.EncoderFallback = encoderFallback; //// fallbackEncoding.DecoderFallback = decoderFallback; //// //// return fallbackEncoding; //// } //// //// private static Encoding GetEncodingRare( int codepage ) //// { //// BCLDebug.Assert( codepage != 0 && codepage != 1200 && codepage != 1201 && codepage != 65001, //// "[Encoding.GetEncodingRare]This code page (" + codepage + ") isn't supported by GetEncodingRare!" ); //// Encoding result; //// switch(codepage) //// { //// case CodePageUTF7: // 65000 //// result = UTF7; //// break; //// case CodePageUTF32: // 12000 //// result = UTF32; //// break; //// case CodePageUTF32BE: // 12001 //// result = new UTF32Encoding( true, true ); //// break; //// case ISCIIAssemese: //// case ISCIIBengali: //// case ISCIIDevanagari: //// case ISCIIGujarathi: //// case ISCIIKannada: //// case ISCIIMalayalam: //// case ISCIIOriya: //// case ISCIIPanjabi: //// case ISCIITamil: //// case ISCIITelugu: //// result = new ISCIIEncoding( codepage ); //// break; //// // GB2312-80 uses same code page for 20936 and mac 10008 //// case CodePageMacGB2312: //// // case CodePageGB2312: //// // result = new DBCSCodePageEncoding(codepage, EUCCN); //// result = new DBCSCodePageEncoding( CodePageMacGB2312, CodePageGB2312 ); //// break; //// //// // Mac Korean 10003 and 20949 are the same //// case CodePageMacKorean: //// result = new DBCSCodePageEncoding( CodePageMacKorean, CodePageDLLKorean ); //// break; //// // GB18030 Code Pages //// case GB18030: //// result = new GB18030Encoding(); //// break; //// // ISO2022 Code Pages //// case ISOKorean: //// // case ISOSimplifiedCN //// case ChineseHZ: //// case ISO2022JP: // JIS JP, full-width Katakana mode (no half-width Katakana) //// case ISO2022JPESC: // JIS JP, esc sequence to do Katakana. //// case ISO2022JPSISO: // JIS JP with Shift In/ Shift Out Katakana support //// result = new ISO2022Encoding( codepage ); //// break; //// // Duplicate EUC-CN (51936) just calls a base code page 936, //// // so does ISOSimplifiedCN (50227), which's gotta be broken //// case DuplicateEUCCN: //// case ISOSimplifiedCN: //// result = new DBCSCodePageEncoding( codepage, EUCCN ); // Just maps to 936 //// break; //// case EUCJP: //// result = new EUCJPEncoding(); //// break; //// case EUCKR: //// result = new DBCSCodePageEncoding( codepage, CodePageDLLKorean ); // Maps to 20949 //// break; //// case ENC50229: //// throw new NotSupportedException( Environment.GetResourceString( "NotSupported_CodePage50229" ) ); //// case ISO_8859_8I: //// result = new SBCSCodePageEncoding( codepage, ISO_8859_8_Visual ); // Hebrew maps to a different code page //// break; //// default: //// // Not found, already tried codepage table code pages in GetEncoding() //// throw new NotSupportedException( //// Environment.GetResourceString( "NotSupported_NoCodepageData", codepage ) ); //// } //// return result; //// } //// //// private static Encoding GetEncodingCodePage( int CodePage ) //// { //// // Single Byte or Double Byte Code Page? (0 if not found) //// int i = BaseCodePageEncoding.GetCodePageByteSize( CodePage ); //// if(i == 1) return new SBCSCodePageEncoding( CodePage ); //// else if(i == 2) return new DBCSCodePageEncoding( CodePage ); //// //// // Return null if we didn't find one. //// return null; //// } //// //// // Returns an Encoding object for a given name or a given code page value. //// // //// //// public static Encoding GetEncoding( String name ) //// { //// // //// // NOTE: If you add a new encoding that can be requested by name, be sure to //// // add the corresponding item in EncodingTable. //// // Otherwise, the code below will throw exception when trying to call //// // EncodingTable.GetCodePageFromName(). //// // //// return (GetEncoding( EncodingTable.GetCodePageFromName( name ) )); //// } //// //// // Returns an Encoding object for a given name or a given code page value. //// // //// //// public static Encoding GetEncoding( String name, //// EncoderFallback encoderFallback, DecoderFallback decoderFallback ) //// { //// // //// // NOTE: If you add a new encoding that can be requested by name, be sure to //// // add the corresponding item in EncodingTable. //// // Otherwise, the code below will throw exception when trying to call //// // EncodingTable.GetCodePageFromName(). //// // //// return (GetEncoding( EncodingTable.GetCodePageFromName( name ), encoderFallback, decoderFallback )); //// } //// //// // Return a list of all EncodingInfo objects describing all of our encodings //// //// public static EncodingInfo[] GetEncodings() //// { //// return EncodingTable.GetEncodings(); //// } public virtual byte[] GetPreamble() { return emptyByteArray; } //// private void GetDataItem() //// { //// if(dataItem == null) //// { //// dataItem = EncodingTable.GetCodePageDataItem( m_codePage ); //// if(dataItem == null) //// { //// throw new NotSupportedException( //// Environment.GetResourceString( "NotSupported_NoCodepageData", m_codePage ) ); //// } //// } //// } //// //// // Returns the name for this encoding that can be used with mail agent body tags. //// // If the encoding may not be used, the string is empty. //// //// public virtual String BodyName //// { //// get //// { //// if(dataItem == null) //// { //// GetDataItem(); //// } //// return (dataItem.BodyName); //// } //// } // Returns the human-readable description of the encoding ( e.g. Hebrew (DOS)). public virtual String EncodingName { get { return (Environment.GetResourceString( "Globalization.cp_" + m_codePage )); } } //// // Returns the name for this encoding that can be used with mail agent header //// // tags. If the encoding may not be used, the string is empty. //// //// public virtual String HeaderName //// { //// get //// { //// if(dataItem == null) //// { //// GetDataItem(); //// } //// return (dataItem.HeaderName); //// } //// } //// //// // Returns the array of IANA-registered names for this encoding. If there is an //// // IANA preferred name, it is the first name in the array. //// //// public virtual String WebName //// { //// get //// { //// if(dataItem == null) //// { //// GetDataItem(); //// } //// return (dataItem.WebName); //// } //// } //// //// // Returns the windows code page that most closely corresponds to this encoding. //// //// public virtual int WindowsCodePage //// { //// get //// { //// if(dataItem == null) //// { //// GetDataItem(); //// } //// return (dataItem.UIFamilyCodePage); //// } //// } //// //// //// // True if and only if the encoding is used for display by browsers clients. //// //// public virtual bool IsBrowserDisplay //// { //// get //// { //// if(dataItem == null) //// { //// GetDataItem(); //// } //// return ((dataItem.Flags & MIMECONTF_BROWSER) != 0); //// } //// } //// //// // True if and only if the encoding is used for saving by browsers clients. //// //// public virtual bool IsBrowserSave //// { //// get //// { //// if(dataItem == null) //// { //// GetDataItem(); //// } //// return ((dataItem.Flags & MIMECONTF_SAVABLE_BROWSER) != 0); //// } //// } //// //// // True if and only if the encoding is used for display by mail and news clients. //// //// public virtual bool IsMailNewsDisplay //// { //// get //// { //// if(dataItem == null) //// { //// GetDataItem(); //// } //// return ((dataItem.Flags & MIMECONTF_MAILNEWS) != 0); //// } //// } //// //// //// // True if and only if the encoding is used for saving documents by mail and //// // news clients //// //// public virtual bool IsMailNewsSave //// { //// get //// { //// if(dataItem == null) //// { //// GetDataItem(); //// } //// return ((dataItem.Flags & MIMECONTF_SAVABLE_MAILNEWS) != 0); //// } //// } // True if and only if the encoding only uses single byte code points. (Ie, ASCII, 1252, etc) public virtual bool IsSingleByte { get { return false; } } public EncoderFallback EncoderFallback { get { return encoderFallback; } set { if(this.IsReadOnly) { #if EXCEPTION_STRINGS throw new InvalidOperationException( Environment.GetResourceString( "InvalidOperation_ReadOnly" ) ); #else throw new InvalidOperationException(); #endif } if(value == null) { #if EXCEPTION_STRINGS throw new ArgumentNullException( "value" ); #else throw new ArgumentNullException(); #endif } encoderFallback = value; } } public DecoderFallback DecoderFallback { get { return decoderFallback; } set { if(this.IsReadOnly) { #if EXCEPTION_STRINGS throw new InvalidOperationException( Environment.GetResourceString( "InvalidOperation_ReadOnly" ) ); #else throw new InvalidOperationException(); #endif } if(value == null) { #if EXCEPTION_STRINGS throw new ArgumentNullException( "value" ); #else throw new ArgumentNullException(); #endif } decoderFallback = value; } } public virtual Object Clone() { Encoding newEncoding = (Encoding)this.MemberwiseClone(); // New one should be readable newEncoding.m_isReadOnly = false; return newEncoding; } public bool IsReadOnly { get { return (m_isReadOnly); } } // Returns an encoding for the ASCII character set. The returned encoding // will be an instance of the ASCIIEncoding class. // public static Encoding ASCII { get { if(asciiEncoding == null) asciiEncoding = new ASCIIEncoding(); return asciiEncoding; } } // Returns an encoding for the Latin1 character set. The returned encoding // will be an instance of the Latin1Encoding class. // // This is for our optimizations private static extern Encoding Latin1 { [MethodImpl( MethodImplOptions.InternalCall )] get; //// { //// if(latin1Encoding == null) latin1Encoding = new Latin1Encoding(); //// return latin1Encoding; //// } } // Returns the number of bytes required to encode the given character // array. // public virtual int GetByteCount( char[] chars ) { if(chars == null) { #if EXCEPTION_STRINGS throw new ArgumentNullException( "chars", Environment.GetResourceString( "ArgumentNull_Array" ) ); #else throw new ArgumentNullException(); #endif } return GetByteCount( chars, 0, chars.Length ); } public virtual int GetByteCount( String s ) { if(s == null) { #if EXCEPTION_STRINGS throw new ArgumentNullException( "s" ); #else throw new ArgumentNullException(); #endif } char[] chars = s.ToCharArray(); return GetByteCount( chars, 0, chars.Length ); } // Returns the number of bytes required to encode a range of characters in // a character array. // public abstract int GetByteCount( char[] chars , int index , int count ); // We expect this to be the workhorse for NLS encodings // unfortunately for existing overrides, it has to call the [] version, // which is really slow, so this method should be avoided if you're calling // a 3rd party encoding. [CLSCompliant( false )] public virtual unsafe int GetByteCount( char* chars , int count ) { // Validate input parameters if(chars == null) { #if EXCEPTION_STRINGS throw new ArgumentNullException( "chars", Environment.GetResourceString( "ArgumentNull_Array" ) ); #else throw new ArgumentNullException(); #endif } if(count < 0) { #if EXCEPTION_STRINGS throw new ArgumentOutOfRangeException( "count", Environment.GetResourceString( "ArgumentOutOfRange_NeedNonNegNum" ) ); #else throw new ArgumentOutOfRangeException(); #endif } char[] arrChar = new char[count]; int index; for(index = 0; index < count; index++) { arrChar[index] = chars[index]; } return GetByteCount( arrChar, 0, count ); } // For NLS Encodings, workhorse takes an encoder (may be null) // Always validate parameters before calling internal version, which will only assert. internal virtual unsafe int GetByteCount( char* chars , int count , EncoderNLS encoder ) { return GetByteCount( chars, count ); } // Returns a byte array containing the encoded representation of the given // character array. // public virtual byte[] GetBytes( char[] chars ) { if(chars == null) { #if EXCEPTION_STRINGS throw new ArgumentNullException( "chars", Environment.GetResourceString( "ArgumentNull_Array" ) ); #else throw new ArgumentNullException(); #endif } return GetBytes( chars, 0, chars.Length ); } // Returns a byte array containing the encoded representation of a range // of characters in a character array. // public virtual byte[] GetBytes( char[] chars , int index , int count ) { byte[] result = new byte[GetByteCount( chars, index, count )]; GetBytes( chars, index, count, result, 0 ); return result; } // Encodes a range of characters in a character array into a range of bytes // in a byte array. An exception occurs if the byte array is not large // enough to hold the complete encoding of the characters. The // GetByteCount method can be used to determine the exact number of // bytes that will be produced for a given range of characters. // Alternatively, the GetMaxByteCount method can be used to // determine the maximum number of bytes that will be produced for a given // number of characters, regardless of the actual character values. // public abstract int GetBytes( char[] chars , int charIndex , int charCount , byte[] bytes , int byteIndex ); // Returns a byte array containing the encoded representation of the given // string. // public virtual byte[] GetBytes( String s ) { if(s == null) { #if EXCEPTION_STRINGS throw new ArgumentNullException( "s", Environment.GetResourceString( "ArgumentNull_String" ) ); #else throw new ArgumentNullException(); #endif } char[] chars = s.ToCharArray(); return GetBytes( chars, 0, chars.Length ); } public virtual int GetBytes( String s , int charIndex , int charCount , byte[] bytes , int byteIndex ) { if(s == null) { #if EXCEPTION_STRINGS throw new ArgumentNullException( "s" ); #else throw new ArgumentNullException(); #endif } return GetBytes( s.ToCharArray(), charIndex, charCount, bytes, byteIndex ); } // This is our internal workhorse // Always validate parameters before calling internal version, which will only assert. internal virtual unsafe int GetBytes( char* chars , int charCount , byte* bytes , int byteCount , EncoderNLS encoder ) { return GetBytes( chars, charCount, bytes, byteCount ); } // We expect this to be the workhorse for NLS Encodings, but for existing // ones we need a working (if slow) default implimentation) // // WARNING WARNING WARNING // // WARNING: If this breaks it could be a security threat. Obviously we // call this internally, so you need to make sure that your pointers, counts // and indexes are correct when you call this method. // // In addition, we have internal code, which will be marked as "safe" calling // this code. However this code is dependent upon the implimentation of an // external GetBytes() method, which could be overridden by a third party and // the results of which cannot be guaranteed. We use that result to copy // the byte[] to our byte* output buffer. If the result count was wrong, we // could easily overflow our output buffer. Therefore we do an extra test // when we copy the buffer so that we don't overflow byteCount either. [CLSCompliant( false )] public virtual unsafe int GetBytes( char* chars , int charCount , byte* bytes , int byteCount ) { // Validate input parameters if(bytes == null || chars == null) { #if EXCEPTION_STRINGS throw new ArgumentNullException( bytes == null ? "bytes" : "chars", Environment.GetResourceString( "ArgumentNull_Array" ) ); #else throw new ArgumentNullException(); #endif } if(charCount < 0 || byteCount < 0) { #if EXCEPTION_STRINGS throw new ArgumentOutOfRangeException( (charCount < 0 ? "charCount" : "byteCount"), Environment.GetResourceString( "ArgumentOutOfRange_NeedNonNegNum" ) ); #else throw new ArgumentOutOfRangeException(); #endif } // Get the char array to convert char[] arrChar = new char[charCount]; int index; for(index = 0; index < charCount; index++) { arrChar[index] = chars[index]; } // Get the byte array to fill byte[] arrByte = new byte[byteCount]; // Do the work int result = GetBytes( arrChar, 0, charCount, arrByte, 0 ); // The only way this could fail is a bug in GetBytes BCLDebug.Assert( result <= byteCount, "[Encoding.GetBytes]Returned more bytes than we have space for" ); // Copy the byte array // WARNING: We MUST make sure that we don't copy too many bytes. We can't // rely on result because it could be a 3rd party implimentation. We need // to make sure we never copy more than byteCount bytes no matter the value // of result if(result < byteCount) { byteCount = result; } // Copy the data, don't overrun our array! for(index = 0; index < byteCount; index++) { bytes[index] = arrByte[index]; } return byteCount; } // Returns the number of characters produced by decoding the given byte // array. // public virtual int GetCharCount( byte[] bytes ) { if(bytes == null) { #if EXCEPTION_STRINGS throw new ArgumentNullException( "bytes", Environment.GetResourceString( "ArgumentNull_Array" ) ); #else throw new ArgumentNullException(); #endif } return GetCharCount( bytes, 0, bytes.Length ); } // Returns the number of characters produced by decoding a range of bytes // in a byte array. // public abstract int GetCharCount( byte[] bytes , int index , int count ); // We expect this to be the workhorse for NLS Encodings, but for existing // ones we need a working (if slow) default implimentation) [CLSCompliant( false )] public virtual unsafe int GetCharCount( byte* bytes , int count ) { // Validate input parameters if(bytes == null) { #if EXCEPTION_STRINGS throw new ArgumentNullException( "bytes", Environment.GetResourceString( "ArgumentNull_Array" ) ); #else throw new ArgumentNullException(); #endif } if(count < 0) { #if EXCEPTION_STRINGS throw new ArgumentOutOfRangeException( "count", Environment.GetResourceString( "ArgumentOutOfRange_NeedNonNegNum" ) ); #else throw new ArgumentOutOfRangeException(); #endif } byte[] arrbyte = new byte[count]; for(int index = 0; index < count; index++) { arrbyte[index] = bytes[index]; } return GetCharCount( arrbyte, 0, count ); } // This is our internal workhorse // Always validate parameters before calling internal version, which will only assert. internal virtual unsafe int GetCharCount( byte* bytes , int count , DecoderNLS decoder ) { return GetCharCount( bytes, count ); } // Returns a character array containing the decoded representation of a // given byte array. // public virtual char[] GetChars( byte[] bytes ) { if(bytes == null) { #if EXCEPTION_STRINGS throw new ArgumentNullException( "bytes", Environment.GetResourceString( "ArgumentNull_Array" ) ); #else throw new ArgumentNullException(); #endif } return GetChars( bytes, 0, bytes.Length ); } // Returns a character array containing the decoded representation of a // range of bytes in a byte array. // public virtual char[] GetChars( byte[] bytes , int index , int count ) { char[] result = new char[GetCharCount( bytes, index, count )]; GetChars( bytes, index, count, result, 0 ); return result; } // Decodes a range of bytes in a byte array into a range of characters in a // character array. An exception occurs if the character array is not large // enough to hold the complete decoding of the bytes. The // GetCharCount method can be used to determine the exact number of // characters that will be produced for a given range of bytes. // Alternatively, the GetMaxCharCount method can be used to // determine the maximum number of characterss that will be produced for a // given number of bytes, regardless of the actual byte values. // public abstract int GetChars( byte[] bytes , int byteIndex , int byteCount , char[] chars , int charIndex ); // We expect this to be the workhorse for NLS Encodings, but for existing // ones we need a working (if slow) default implimentation) // // WARNING WARNING WARNING // // WARNING: If this breaks it could be a security threat. Obviously we // call this internally, so you need to make sure that your pointers, counts // and indexes are correct when you call this method. // // In addition, we have internal code, which will be marked as "safe" calling // this code. However this code is dependent upon the implimentation of an // external GetChars() method, which could be overridden by a third party and // the results of which cannot be guaranteed. We use that result to copy // the char[] to our char* output buffer. If the result count was wrong, we // could easily overflow our output buffer. Therefore we do an extra test // when we copy the buffer so that we don't overflow charCount either. [CLSCompliant( false )] public virtual unsafe int GetChars( byte* bytes , int byteCount , char* chars , int charCount ) { // Validate input parameters if(chars == null || bytes == null) { #if EXCEPTION_STRINGS throw new ArgumentNullException( chars == null ? "chars" : "bytes", Environment.GetResourceString( "ArgumentNull_Array" ) ); #else throw new ArgumentNullException(); #endif } if(byteCount < 0 || charCount < 0) { #if EXCEPTION_STRINGS throw new ArgumentOutOfRangeException( (byteCount < 0 ? "byteCount" : "charCount"), Environment.GetResourceString( "ArgumentOutOfRange_NeedNonNegNum" ) ); #else throw new ArgumentOutOfRangeException(); #endif } // Get the byte array to convert byte[] arrByte = new byte[byteCount]; for(int index = 0; index < byteCount; index++) { arrByte[index] = bytes[index]; } // Get the char array to fill char[] arrChar = new char[charCount]; // Do the work int result = GetChars( arrByte, 0, byteCount, arrChar, 0 ); // The only way this could fail is a bug in GetChars BCLDebug.Assert( result <= charCount, "[Encoding.GetChars]Returned more chars than we have space for" ); // Copy the char array // WARNING: We MUST make sure that we don't copy too many chars. We can't // rely on result because it could be a 3rd party implimentation. We need // to make sure we never copy more than charCount chars no matter the value // of result if(result < charCount) { charCount = result; } // Copy the data, don't overrun our array! for(int index = 0; index < charCount; index++) { chars[index] = arrChar[index]; } return charCount; } // This is our internal workhorse // Always validate parameters before calling internal version, which will only assert. internal virtual unsafe int GetChars( byte* bytes , int byteCount , char* chars , int charCount , DecoderNLS decoder ) { return GetChars( bytes, byteCount, chars, charCount ); } // Returns the code page identifier of this encoding. The returned value is // an integer between 0 and 65535 if the encoding has a code page // identifier, or -1 if the encoding does not represent a code page. // public virtual int CodePage { get { return m_codePage; } } //// // IsAlwaysNormalized //// // Returns true if the encoding is always normalized for the specified encoding form //// //// public bool IsAlwaysNormalized() //// { //// return this.IsAlwaysNormalized( NormalizationForm.FormC ); //// } //// //// //// public virtual bool IsAlwaysNormalized( NormalizationForm form ) //// { //// // Assume false unless the encoding knows otherwise //// return false; //// } // Returns a Decoder object for this encoding. The returned object // can be used to decode a sequence of bytes into a sequence of characters. // Contrary to the GetChars family of methods, a Decoder can // convert partial sequences of bytes into partial sequences of characters // by maintaining the appropriate state between the conversions. // // This default implementation returns a Decoder that simply // forwards calls to the GetCharCount and GetChars methods to // the corresponding methods of this encoding. Encodings that require state // to be maintained between successive conversions should override this // method and return an instance of an appropriate Decoder // implementation. // public virtual Decoder GetDecoder() { return new DefaultDecoder( this ); } //// private static Encoding CreateDefaultEncoding() //// { //// Encoding enc; //// int codePage = Win32Native.GetACP(); //// //// // For US English, we can save some startup working set by not calling //// // GetEncoding(int codePage) since JITting GetEncoding will force us to load //// // all the Encoding classes for ASCII, UTF7 & UTF8, & UnicodeEncoding. //// if(codePage == 1252) //// enc = new SBCSCodePageEncoding( codePage ); //// else //// enc = GetEncoding( codePage ); //// //// return (enc); //// } // Returns an encoding for the system's current ANSI code page. // public static Encoding Default { get { throw new NotImplementedException(); //// if(defaultEncoding == null) //// { //// defaultEncoding = CreateDefaultEncoding(); //// } //// return defaultEncoding; } } // Returns an Encoder object for this encoding. The returned object // can be used to encode a sequence of characters into a sequence of bytes. // Contrary to the GetBytes family of methods, an Encoder can // convert partial sequences of characters into partial sequences of bytes // by maintaining the appropriate state between the conversions. // // This default implementation returns an Encoder that simply // forwards calls to the GetByteCount and GetBytes methods to // the corresponding methods of this encoding. Encodings that require state // to be maintained between successive conversions should override this // method and return an instance of an appropriate Encoder // implementation. // public virtual Encoder GetEncoder() { return new DefaultEncoder( this ); } // Returns the maximum number of bytes required to encode a given number of // characters. This method can be used to determine an appropriate buffer // size for byte arrays passed to the GetBytes method of this // encoding or the GetBytes method of an Encoder for this // encoding. All encodings must guarantee that no buffer overflow // exceptions will occur if buffers are sized according to the results of // this method. // // WARNING: If you're using something besides the default replacement encoder fallback, // then you could have more bytes than this returned from an actual call to GetBytes(). // public abstract int GetMaxByteCount( int charCount ); // Returns the maximum number of characters produced by decoding a given // number of bytes. This method can be used to determine an appropriate // buffer size for character arrays passed to the GetChars method of // this encoding or the GetChars method of a Decoder for this // encoding. All encodings must guarantee that no buffer overflow // exceptions will occur if buffers are sized according to the results of // this method. // public abstract int GetMaxCharCount( int byteCount ); // Returns a string containing the decoded representation of a given byte // array. // public virtual String GetString( byte[] bytes ) { if(bytes == null) { #if EXCEPTION_STRINGS throw new ArgumentNullException( "bytes", Environment.GetResourceString( "ArgumentNull_Array" ) ); #else throw new ArgumentNullException(); #endif } return GetString( bytes, 0, bytes.Length ); } // Returns a string containing the decoded representation of a range of // bytes in a byte array. // // Internally we override this for performance // public virtual String GetString( byte[] bytes , int index , int count ) { return new String( GetChars( bytes, index, count ) ); } // Returns an encoding for Unicode format. The returned encoding will be // an instance of the UnicodeEncoding class. // // It will use little endian byte order, but will detect // input in big endian if it finds a byte order mark per Unicode 2.0. // public static Encoding Unicode { get { if(unicodeEncoding == null) unicodeEncoding = new UnicodeEncoding( false, true ); return unicodeEncoding; } } //// // Returns an encoding for Unicode format. The returned encoding will be //// // an instance of the UnicodeEncoding class. //// // //// // It will use big endian byte order, but will detect //// // input in little endian if it finds a byte order mark per Unicode 2.0. //// // //// //// public static Encoding BigEndianUnicode //// { //// get //// { //// if(bigEndianUnicode == null) bigEndianUnicode = new UnicodeEncoding( true, true ); //// return bigEndianUnicode; //// } //// } //// //// // Returns an encoding for the UTF-7 format. The returned encoding will be //// // an instance of the UTF7Encoding class. //// // //// //// public static Encoding UTF7 //// { //// get //// { //// if(utf7Encoding == null) utf7Encoding = new UTF7Encoding(); //// return utf7Encoding; //// } //// } // Returns an encoding for the UTF-8 format. The returned encoding will be // an instance of the UTF8Encoding class. // public static Encoding UTF8 { get { if(utf8Encoding == null) utf8Encoding = new UTF8Encoding( true ); return utf8Encoding; } } //// // Returns an encoding for the UTF-32 format. The returned encoding will be //// // an instance of the UTF32Encoding class. //// // //// //// public static Encoding UTF32 //// { //// get //// { //// if(utf32Encoding == null) utf32Encoding = new UTF32Encoding( false, true ); //// return utf32Encoding; //// } //// } public override bool Equals( Object value ) { Encoding that = value as Encoding; if(that != null) { return (m_codePage == that.m_codePage) && (EncoderFallback.Equals( that.EncoderFallback )) && (DecoderFallback.Equals( that.DecoderFallback )); } return (false); } public override int GetHashCode() { return m_codePage + this.EncoderFallback.GetHashCode() + this.DecoderFallback.GetHashCode(); } internal virtual char[] GetBestFitUnicodeToBytesData() { // Normally we don't have any best fit data. return new char[0]; } internal virtual char[] GetBestFitBytesToUnicodeData() { // Normally we don't have any best fit data. return new char[0]; } internal void ThrowBytesOverflow() { // Special message to include fallback type in case fallback's GetMaxCharCount is broken // This happens if user has implimented an encoder fallback with a broken GetMaxCharCount #if EXCEPTION_STRINGS throw new ArgumentException( Environment.GetResourceString( "Argument_EncodingConversionOverflowBytes", EncodingName, EncoderFallback.GetType() ), "bytes" ); #else throw new ArgumentException(); #endif } internal void ThrowBytesOverflow( EncoderNLS encoder , bool nothingEncoded ) { if(encoder == null || encoder.m_throwOnOverflow || nothingEncoded) { if(encoder != null && encoder.InternalHasFallbackBuffer) { encoder.FallbackBuffer.InternalReset(); } // Special message to include fallback type in case fallback's GetMaxCharCount is broken // This happens if user has implimented an encoder fallback with a broken GetMaxCharCount ThrowBytesOverflow(); } // If we didn't throw, we are in convert and have to remember our flushing encoder.ClearMustFlush(); } internal void ThrowCharsOverflow() { // Special message to include fallback type in case fallback's GetMaxCharCount is broken // This happens if user has implimented a decoder fallback with a broken GetMaxCharCount #if EXCEPTION_STRINGS throw new ArgumentException( Environment.GetResourceString( "Argument_EncodingConversionOverflowChars", EncodingName, DecoderFallback.GetType() ), "chars" ); #else throw new ArgumentException(); #endif } internal void ThrowCharsOverflow( DecoderNLS decoder , bool nothingDecoded ) { if(decoder == null || decoder.m_throwOnOverflow || nothingDecoded) { if(decoder != null && decoder.InternalHasFallbackBuffer) { decoder.FallbackBuffer.InternalReset(); } // Special message to include fallback type in case fallback's GetMaxCharCount is broken // This happens if user has implimented a decoder fallback with a broken GetMaxCharCount ThrowCharsOverflow(); } // If we didn't throw, we are in convert and have to remember our flushing decoder.ClearMustFlush(); } [Serializable] internal class DefaultEncoder : Encoder /*, ISerializable, IObjectReference*/ { private Encoding m_encoding; [NonSerialized] internal char charLeftOver; public DefaultEncoder( Encoding encoding ) { m_encoding = encoding; } //// // Constructor called by serialization, have to handle deserializing from Everett //// internal DefaultEncoder( SerializationInfo info, StreamingContext context ) //// { //// if(info == null) throw new ArgumentNullException( "info" ); //// //// // All we have is our encoding //// this.m_encoding = (Encoding)info.GetValue( "encoding", typeof( Encoding ) ); //// //// try //// { //// this.m_fallback = (EncoderFallback)info.GetValue( "m_fallback", typeof( EncoderFallback ) ); //// this.charLeftOver = (Char)info.GetValue( "charLeftOver", typeof( Char ) ); //// } //// catch(SerializationException) //// { //// } //// } //// //// // Just get it from GetEncoding //// public Object GetRealObject( StreamingContext context ) //// { //// Encoder encoder = m_encoding.GetEncoder(); //// if(m_fallback != null) //// encoder.m_fallback = m_fallback; //// if(charLeftOver != (char)0) //// { //// EncoderNLS encoderNls = encoder as EncoderNLS; //// if(encoderNls != null) //// encoderNls.charLeftOver = charLeftOver; //// } //// return encoder; //// } //// //// // ISerializable implementation, get data for this object //// [SecurityPermissionAttribute( SecurityAction.LinkDemand, Flags = SecurityPermissionFlag.SerializationFormatter )] //// void ISerializable.GetObjectData( SerializationInfo info, StreamingContext context ) //// { //// // Any info? //// if(info == null) throw new ArgumentNullException( "info" ); //// //// // All we have is our encoding //// info.AddValue( "encoding", this.m_encoding ); //// } // Returns the number of bytes the next call to GetBytes will // produce if presented with the given range of characters and the given // value of the flush parameter. The returned value takes into // account the state in which the encoder was left following the last call // to GetBytes. The state of the encoder is not affected by a call // to this method. // public override int GetByteCount( char[] chars, int index, int count, bool flush ) { return m_encoding.GetByteCount( chars, index, count ); } public unsafe override int GetByteCount( char* chars, int count, bool flush ) { return m_encoding.GetByteCount( chars, count ); } // Encodes a range of characters in a character array into a range of bytes // in a byte array. The method encodes charCount characters from // chars starting at index charIndex, storing the resulting // bytes in bytes starting at index byteIndex. The encoding // takes into account the state in which the encoder was left following the // last call to this method. The flush parameter indicates whether // the encoder should flush any shift-states and partial characters at the // end of the conversion. To ensure correct termination of a sequence of // blocks of encoded bytes, the last call to GetBytes should specify // a value of true for the flush parameter. // // An exception occurs if the byte array is not large enough to hold the // complete encoding of the characters. The GetByteCount method can // be used to determine the exact number of bytes that will be produced for // a given range of characters. Alternatively, the GetMaxByteCount // method of the Encoding that produced this encoder can be used to // determine the maximum number of bytes that will be produced for a given // number of characters, regardless of the actual character values. // public override int GetBytes( char[] chars, int charIndex, int charCount, byte[] bytes, int byteIndex, bool flush ) { return m_encoding.GetBytes( chars, charIndex, charCount, bytes, byteIndex ); } public unsafe override int GetBytes( char* chars, int charCount, byte* bytes, int byteCount, bool flush ) { return m_encoding.GetBytes( chars, charCount, bytes, byteCount ); } } [Serializable()] internal class DefaultDecoder : Decoder /*, ISerializable, IObjectReference*/ { private Encoding m_encoding; public DefaultDecoder( Encoding encoding ) { m_encoding = encoding; } //// // Constructor called by serialization, have to handle deserializing from Everett //// internal DefaultDecoder( SerializationInfo info, StreamingContext context ) //// { //// // Any info? //// if(info == null) throw new ArgumentNullException( "info" ); //// //// // All we have is our encoding //// this.m_encoding = (Encoding)info.GetValue( "encoding", typeof( Encoding ) ); //// //// try //// { //// this.m_fallback = (DecoderFallback)info.GetValue( "m_fallback", typeof( DecoderFallback ) ); //// } //// catch(SerializationException) //// { //// m_fallback = null; //// } //// } //// //// // Just get it from GetEncoding //// public Object GetRealObject( StreamingContext context ) //// { //// Decoder decoder = m_encoding.GetDecoder(); //// if(m_fallback != null) //// decoder.m_fallback = m_fallback; //// //// return decoder; //// } //// //// // ISerializable implementation, get data for this object //// [SecurityPermissionAttribute( SecurityAction.LinkDemand, Flags = SecurityPermissionFlag.SerializationFormatter )] //// void ISerializable.GetObjectData( SerializationInfo info, StreamingContext context ) //// { //// // Any info? //// if(info == null) throw new ArgumentNullException( "info" ); //// //// // All we have is our encoding //// info.AddValue( "encoding", this.m_encoding ); //// } // Returns the number of characters the next call to GetChars will // produce if presented with the given range of bytes. The returned value // takes into account the state in which the decoder was left following the // last call to GetChars. The state of the decoder is not affected // by a call to this method. // public override int GetCharCount( byte[] bytes, int index, int count ) { return GetCharCount( bytes, index, count, false ); } public override int GetCharCount( byte[] bytes, int index, int count, bool flush ) { return m_encoding.GetCharCount( bytes, index, count ); } public unsafe override int GetCharCount( byte* bytes, int count, bool flush ) { // By default just call the encoding version, no flush by default return m_encoding.GetCharCount( bytes, count ); } // Decodes a range of bytes in a byte array into a range of characters // in a character array. The method decodes byteCount bytes from // bytes starting at index byteIndex, storing the resulting // characters in chars starting at index charIndex. The // decoding takes into account the state in which the decoder was left // following the last call to this method. // // An exception occurs if the character array is not large enough to // hold the complete decoding of the bytes. The GetCharCount method // can be used to determine the exact number of characters that will be // produced for a given range of bytes. Alternatively, the // GetMaxCharCount method of the Encoding that produced this // decoder can be used to determine the maximum number of characters that // will be produced for a given number of bytes, regardless of the actual // byte values. // public override int GetChars( byte[] bytes, int byteIndex, int byteCount, char[] chars, int charIndex ) { return GetChars( bytes, byteIndex, byteCount, chars, charIndex, false ); } public override int GetChars( byte[] bytes, int byteIndex, int byteCount, char[] chars, int charIndex, bool flush ) { return m_encoding.GetChars( bytes, byteIndex, byteCount, chars, charIndex ); } public unsafe override int GetChars( byte* bytes, int byteCount, char* chars, int charCount, bool flush ) { // By default just call the encoding's version return m_encoding.GetChars( bytes, byteCount, chars, charCount ); } } //// internal class EncodingCharBuffer //// { //// unsafe char* chars; //// unsafe char* charStart; //// unsafe char* charEnd; //// int charCountResult = 0; //// Encoding enc; //// DecoderNLS decoder; //// unsafe byte* byteStart; //// unsafe byte* byteEnd; //// unsafe byte* bytes; //// DecoderFallbackBuffer fallbackBuffer; //// //// internal unsafe EncodingCharBuffer( Encoding enc, DecoderNLS decoder, char* charStart, int charCount, //// byte* byteStart, int byteCount ) //// { //// this.enc = enc; //// this.decoder = decoder; //// //// this.chars = charStart; //// this.charStart = charStart; //// this.charEnd = charStart + charCount; //// //// this.byteStart = byteStart; //// this.bytes = byteStart; //// this.byteEnd = byteStart + byteCount; //// //// if(this.decoder == null) //// this.fallbackBuffer = enc.DecoderFallback.CreateFallbackBuffer(); //// else //// this.fallbackBuffer = this.decoder.FallbackBuffer; //// //// // If we're getting chars or getting char count we don't expect to have //// // to remember fallbacks between calls (so it should be empty) //// BCLDebug.Assert( fallbackBuffer.Remaining == 0, //// "[Encoding.EncodingCharBuffer.EncodingCharBuffer]Expected empty fallback buffer for getchars/charcount" ); //// fallbackBuffer.InternalInitialize( bytes, charEnd ); //// } //// //// internal unsafe bool AddChar( char ch, int numBytes ) //// { //// if(chars != null) //// { //// if(chars >= charEnd) //// { //// // Throw maybe //// bytes -= numBytes; // Didn't encode these bytes //// enc.ThrowCharsOverflow( decoder, bytes <= byteStart ); // Throw? //// return false; // No throw, but no store either //// } //// //// *(chars++) = ch; //// } //// charCountResult++; //// return true; //// } //// //// internal unsafe bool AddChar( char ch ) //// { //// return AddChar( ch, 1 ); //// } //// //// //// internal unsafe bool AddChar( char ch1, char ch2, int numBytes ) //// { //// // Need room for 2 chars //// if(chars >= charEnd - 1) //// { //// // Throw maybe //// bytes -= numBytes; // Didn't encode these bytes //// enc.ThrowCharsOverflow( decoder, bytes <= byteStart ); // Throw? //// return false; // No throw, but no store either //// } //// return AddChar( ch1, numBytes ) && AddChar( ch2, numBytes ); //// } //// //// internal unsafe void AdjustBytes( int count ) //// { //// bytes += count; //// } //// //// internal unsafe bool MoreData //// { //// get //// { //// return bytes < byteEnd; //// } //// } //// //// // Do we have count more bytes? //// internal unsafe bool EvenMoreData( int count ) //// { //// return (bytes <= byteEnd - count); //// } //// //// // GetNextByte shouldn't be called unless the caller's already checked more data or even more data, //// // but we'll double check just to make sure. //// internal unsafe byte GetNextByte() //// { //// BCLDebug.Assert( bytes < byteEnd, "[EncodingCharBuffer.GetNextByte]Expected more date" ); //// if(bytes >= byteEnd) //// return 0; //// return *(bytes++); //// } //// //// internal unsafe int BytesUsed //// { //// get //// { //// return (int)(bytes - byteStart); //// } //// } //// //// internal unsafe bool Fallback( byte fallbackByte ) //// { //// // Build our buffer //// byte[] byteBuffer = new byte[] { fallbackByte }; //// //// // Do the fallback and add the data. //// return Fallback( byteBuffer ); //// } //// //// internal unsafe bool Fallback( byte byte1, byte byte2 ) //// { //// // Build our buffer //// byte[] byteBuffer = new byte[] { byte1, byte2 }; //// //// // Do the fallback and add the data. //// return Fallback( byteBuffer ); //// } //// //// internal unsafe bool Fallback( byte byte1, byte byte2, byte byte3, byte byte4 ) //// { //// // Build our buffer //// byte[] byteBuffer = new byte[] { byte1, byte2, byte3, byte4 }; //// //// // Do the fallback and add the data. //// return Fallback( byteBuffer ); //// } //// //// internal unsafe bool Fallback( byte[] byteBuffer ) //// { //// // Do the fallback and add the data. //// if(chars != null) //// { //// char* pTemp = chars; //// if(fallbackBuffer.InternalFallback( byteBuffer, bytes, ref chars ) == false) //// { //// // Throw maybe //// bytes -= byteBuffer.Length; // Didn't use how many ever bytes we're falling back //// fallbackBuffer.InternalReset(); // We didn't use this fallback. //// enc.ThrowCharsOverflow( decoder, chars == charStart ); // Throw? //// return false; // No throw, but no store either //// } //// charCountResult += unchecked( (int)(chars - pTemp) ); //// } //// else //// { //// charCountResult += fallbackBuffer.InternalFallback( byteBuffer, bytes ); //// } //// //// return true; //// } //// //// internal unsafe int Count //// { //// get //// { //// return charCountResult; //// } //// } //// } //// //// internal class EncodingByteBuffer //// { //// unsafe byte* bytes; //// unsafe byte* byteStart; //// unsafe byte* byteEnd; //// unsafe char* chars; //// unsafe char* charStart; //// unsafe char* charEnd; //// int byteCountResult = 0; //// Encoding enc; //// EncoderNLS encoder; //// internal EncoderFallbackBuffer fallbackBuffer; //// //// internal unsafe EncodingByteBuffer( Encoding inEncoding, EncoderNLS inEncoder, //// byte* inByteStart, int inByteCount, char* inCharStart, int inCharCount ) //// { //// this.enc = inEncoding; //// this.encoder = inEncoder; //// //// this.charStart = inCharStart; //// this.chars = inCharStart; //// this.charEnd = inCharStart + inCharCount; //// //// this.bytes = inByteStart; //// this.byteStart = inByteStart; //// this.byteEnd = inByteStart + inByteCount; //// //// if(this.encoder == null) //// this.fallbackBuffer = enc.EncoderFallback.CreateFallbackBuffer(); //// else //// { //// this.fallbackBuffer = this.encoder.FallbackBuffer; //// // If we're not converting we must not have data in our fallback buffer //// if(encoder.m_throwOnOverflow && encoder.InternalHasFallbackBuffer && //// this.fallbackBuffer.Remaining > 0) //// throw new ArgumentException( Environment.GetResourceString( "Argument_EncoderFallbackNotEmpty", //// encoder.Encoding.EncodingName, encoder.Fallback.GetType() ) ); //// } //// fallbackBuffer.InternalInitialize( chars, charEnd, encoder, bytes != null ); //// } //// //// internal unsafe bool AddByte( byte b, int moreBytesExpected ) //// { //// BCLDebug.Assert( moreBytesExpected >= 0, "[EncodingByteBuffer.AddByte]expected non-negative moreBytesExpected" ); //// if(bytes != null) //// { //// if(bytes >= byteEnd - moreBytesExpected) //// { //// // Throw maybe. Check which buffer to back up (only matters if Converting) //// this.MovePrevious( true ); // Throw if necessary //// return false; // No throw, but no store either //// } //// //// *(bytes++) = b; //// } //// byteCountResult++; //// return true; //// } //// //// internal unsafe bool AddByte( byte b1 ) //// { //// return (AddByte( b1, 0 )); //// } //// //// internal unsafe bool AddByte( byte b1, byte b2 ) //// { //// return (AddByte( b1, b2, 0 )); //// } //// //// internal unsafe bool AddByte( byte b1, byte b2, int moreBytesExpected ) //// { //// return (AddByte( b1, 1 + moreBytesExpected ) && AddByte( b2, moreBytesExpected )); //// } //// //// internal unsafe bool AddByte( byte b1, byte b2, byte b3 ) //// { //// return AddByte( b1, b2, b3, (int)0 ); //// } //// //// internal unsafe bool AddByte( byte b1, byte b2, byte b3, int moreBytesExpected ) //// { //// return (AddByte( b1, 2 + moreBytesExpected ) && //// AddByte( b2, 1 + moreBytesExpected ) && //// AddByte( b3, moreBytesExpected )); //// } //// //// internal unsafe bool AddByte( byte b1, byte b2, byte b3, byte b4 ) //// { //// return (AddByte( b1, 3 ) && //// AddByte( b2, 2 ) && //// AddByte( b3, 1 ) && //// AddByte( b4, 0 )); //// } //// //// internal unsafe void MovePrevious( bool bThrow ) //// { //// if(fallbackBuffer.bFallingBack) //// fallbackBuffer.MovePrevious(); // don't use last fallback //// else //// { //// BCLDebug.Assert( chars > charStart || //// ((bThrow == true) && (bytes == byteStart)), //// "[EncodingByteBuffer.MovePrevious]expected previous data or throw" ); //// if(chars > charStart) //// chars--; // don't use last char //// } //// //// if(bThrow) //// enc.ThrowBytesOverflow( encoder, bytes == byteStart ); // Throw? (and reset fallback if not converting) //// } //// //// internal unsafe bool Fallback( char charFallback ) //// { //// // Do the fallback //// return fallbackBuffer.InternalFallback( charFallback, ref chars ); //// } //// //// internal unsafe bool MoreData //// { //// get //// { //// // See if fallbackBuffer is not empty or if there's data left in chars buffer. //// return ((fallbackBuffer.Remaining > 0) || (chars < charEnd)); //// } //// } //// //// internal unsafe char GetNextChar() //// { //// // See if there's something in our fallback buffer //// char cReturn = fallbackBuffer.InternalGetNextChar(); //// //// // Nothing in the fallback buffer, return our normal data. //// if(cReturn == 0) //// { //// if(chars < charEnd) //// cReturn = *(chars++); //// } //// //// return cReturn; //// } //// //// internal unsafe int CharsUsed //// { //// get //// { //// return (int)(chars - charStart); //// } //// } //// //// internal unsafe int Count //// { //// get //// { //// return byteCountResult; //// } //// } //// } } } ================================================ FILE: Zelig/Zelig/RunTime/Framework/mscorlib/System/Text/StringBuilder.cs ================================================ // ==++== // // Copyright (c) Microsoft Corporation. All rights reserved. // // ==--== /*============================================================ ** ** Class: StringBuilder ** ** ** Purpose: implementation of the StringBuilder ** class. ** ===========================================================*/ namespace System.Text { using System.Text; using System.Runtime.Serialization; using System; using System.Runtime.CompilerServices; using System.Threading; using System.Globalization; ////using System.Runtime.Versioning; // This class represents a mutable string. It is convenient for situations in // which it is desirable to modify a string, perhaps by removing, replacing, or // inserting characters, without creating a new String subsequent to // each modification. // // The methods contained within this class do not return a new StringBuilder // object unless specified otherwise. This class may be used in conjunction with the String // class to carry out modifications upon strings. // // When passing null into a constructor in VJ and VC, the null // should be explicitly type cast. // For Example: // StringBuilder sb1 = new StringBuilder((StringBuilder)null); // StringBuilder sb2 = new StringBuilder((String)null); // Console.WriteLine(sb1); // Console.WriteLine(sb2); // [Serializable] public sealed class StringBuilder /*: ISerializable*/ { // // // CLASS VARIABLES // // internal Thread m_currentThread = Thread.CurrentThread; internal int m_MaxCapacity = 0; // // making m_StringValue volatile to guarantee reading order in some places. // internal volatile String m_StringValue = null; // // // STATIC CONSTANTS // // internal const int DefaultCapacity = 16; //// private const String CapacityField = "Capacity"; //// private const String MaxCapacityField = "m_MaxCapacity"; //// private const String StringValueField = "m_StringValue"; //// private const String ThreadIDField = "m_currentThread"; // // //CONSTRUCTORS // // // Creates a new empty string builder (i.e., it represents String.Empty) // with the default capacity (16 characters). public StringBuilder() : this( DefaultCapacity ) { } // Create a new empty string builder (i.e., it represents String.Empty) // with the specified capacity. public StringBuilder( int capacity ) : this( String.Empty, capacity ) { } // Creates a new string builder from the specified string. If value // is a null String (i.e., if it represents String.NullString) // then the new string builder will also be null (i.e., it will also represent // String.NullString). // public StringBuilder( String value ) : this( value, DefaultCapacity ) { } // Creates a new string builder from the specified string with the specified // capacity. If value is a null String (i.e., if it represents // String.NullString) then the new string builder will also be null // (i.e., it will also represent String.NullString). // The maximum number of characters this string may contain is set by capacity. // public StringBuilder( String value, int capacity ) : this( value, 0, ((value != null) ? value.Length : 0), capacity ) { } // Creates a new string builder from the specifed substring with the specified // capacity. The maximum number of characters is set by capacity. // public StringBuilder( String value, int startIndex, int length, int capacity ) { if(capacity < 0) { #if EXCEPTION_STRINGS throw new ArgumentOutOfRangeException( "capacity", String.Format( CultureInfo.CurrentCulture, Environment.GetResourceString( "ArgumentOutOfRange_MustBePositive" ), "capacity" ) ); #else throw new ArgumentOutOfRangeException(); #endif } if(length < 0) { #if EXCEPTION_STRINGS throw new ArgumentOutOfRangeException( "length", String.Format( CultureInfo.CurrentCulture, Environment.GetResourceString( "ArgumentOutOfRange_MustBeNonNegNum" ), "length" ) ); #else throw new ArgumentOutOfRangeException(); #endif } if(startIndex < 0) { #if EXCEPTION_STRINGS throw new ArgumentOutOfRangeException( "startIndex", Environment.GetResourceString( "ArgumentOutOfRange_StartIndex" ) ); #else throw new ArgumentOutOfRangeException(); #endif } if(value == null) { value = String.Empty; } if(startIndex > value.Length - length) { #if EXCEPTION_STRINGS throw new ArgumentOutOfRangeException( "length", Environment.GetResourceString( "ArgumentOutOfRange_IndexLength" ) ); #else throw new ArgumentOutOfRangeException(); #endif } m_MaxCapacity = Int32.MaxValue; if(capacity == 0) { capacity = DefaultCapacity; } while(capacity < length) { capacity *= 2; // If we overflow, we should just use length as capacity. // There is no reason we should throw an exception in this case if the system is able // to allocate the string. if(capacity < 0) { capacity = length; break; } } m_StringValue = String.GetStringForStringBuilder( value, startIndex, length, capacity ); } // Creates an empty StringBuilder with a minimum capacity of capacity // and a maximum capacity of maxCapacity. public StringBuilder( int capacity, int maxCapacity ) { if(capacity > maxCapacity) { #if EXCEPTION_STRINGS throw new ArgumentOutOfRangeException( "capacity", Environment.GetResourceString( "ArgumentOutOfRange_Capacity" ) ); #else throw new ArgumentOutOfRangeException(); #endif } if(maxCapacity < 1) { #if EXCEPTION_STRINGS throw new ArgumentOutOfRangeException( "maxCapacity", Environment.GetResourceString( "ArgumentOutOfRange_SmallMaxCapacity" ) ); #else throw new ArgumentOutOfRangeException(); #endif } if(capacity < 0) { #if EXCEPTION_STRINGS throw new ArgumentOutOfRangeException( "capacity", String.Format( CultureInfo.CurrentCulture, Environment.GetResourceString( "ArgumentOutOfRange_MustBePositive" ), "capacity" ) ); #else throw new ArgumentOutOfRangeException(); #endif } if(capacity == 0) { capacity = Math.Min( DefaultCapacity, maxCapacity ); } m_StringValue = String.GetStringForStringBuilder( String.Empty, capacity ); m_MaxCapacity = maxCapacity; } //// private StringBuilder( SerializationInfo info, StreamingContext context ) //// { //// if(info == null) //// throw new ArgumentNullException( "info" ); //// //// int persistedCapacity = 0; //// string persistedString = null; //// int persistedMaxCapacity = Int32.MaxValue; //// bool capacityPresent = false; //// //// // Get the data //// SerializationInfoEnumerator enumerator = info.GetEnumerator(); //// while(enumerator.MoveNext()) //// { //// switch(enumerator.Name) //// { //// case MaxCapacityField: //// persistedMaxCapacity = info.GetInt32( MaxCapacityField ); //// break; //// case StringValueField: //// persistedString = info.GetString( StringValueField ); //// break; //// case CapacityField: //// persistedCapacity = info.GetInt32( CapacityField ); //// capacityPresent = true; //// break; //// default: //// // Note: deliberately ignore "m_currentThread" which earlier //// // verisions incorrectly persisted. //// // Ignore other fields for forward compatability. //// break; //// } //// //// } //// //// // Check values and set defaults //// if(persistedString == null) //// { //// persistedString = String.Empty; //// } //// if(persistedMaxCapacity < 1 || persistedString.Length > persistedMaxCapacity) //// { //// throw new SerializationException( Environment.GetResourceString( "Serialization_StringBuilderMaxCapacity" ) ); //// } //// //// if(!capacityPresent) //// { //// // StringBuilder in V1.X did not persist the Capacity, so this is a valid legacy code path. //// persistedCapacity = DefaultCapacity; //// if(persistedCapacity < persistedString.Length) //// { //// persistedCapacity = persistedString.Length; //// } //// if(persistedCapacity > persistedMaxCapacity) //// { //// persistedCapacity = persistedMaxCapacity; //// } //// } //// if(persistedCapacity < 0 || persistedCapacity < persistedString.Length || persistedCapacity > persistedMaxCapacity) //// { //// throw new SerializationException( Environment.GetResourceString( "Serialization_StringBuilderCapacity" ) ); //// } //// //// // Assign //// m_MaxCapacity = persistedMaxCapacity; //// m_StringValue = String.GetStringForStringBuilder( persistedString, 0, persistedString.Length, persistedCapacity ); //// VerifyClassInvariant(); //// } //// //// void ISerializable.GetObjectData( SerializationInfo info, StreamingContext context ) //// { //// if(info == null) //// { //// throw new ArgumentNullException( "info" ); //// } //// //// VerifyClassInvariant(); //// //// info.AddValue( MaxCapacityField, m_MaxCapacity ); //// info.AddValue( CapacityField, Capacity ); //// info.AddValue( StringValueField, m_StringValue ); //// // Note: persist "m_currentThread" to be compatible with old versions //// info.AddValue( ThreadIDField, 0 ); //// } //// //// [System.Diagnostics.Conditional( "_DEBUG" )] //// private void VerifyClassInvariant() //// { //// BCLDebug.Assert( m_MaxCapacity >= 1, "Invalid StringBuilder" ); //// BCLDebug.Assert( Capacity >= 0 && Capacity <= m_MaxCapacity, "Invalid StringBuilder" ); //// BCLDebug.Assert( m_StringValue != null && Capacity >= m_StringValue.Length, "Invalid StringBuilder" ); //// } private String GetThreadSafeString( out Thread th ) { // Following two reads (m_StringValue, m_currentThread) needs to happen in order. // This is guaranteed by making the fields volatile. // See ReplaceString method for details. String temp = m_StringValue; th = Thread.CurrentThread; if(m_currentThread == th) return temp; return String.GetStringForStringBuilder( temp, temp.Capacity ); } public int Capacity { get { return m_StringValue.Capacity; } //-1 to account for terminating null. set { Thread th; String currentString = GetThreadSafeString( out th ); if(value < 0) { #if EXCEPTION_STRINGS throw new ArgumentOutOfRangeException( "value", Environment.GetResourceString( "ArgumentOutOfRange_NegativeCapacity" ) ); #else throw new ArgumentOutOfRangeException(); #endif } if(value < currentString.Length) { #if EXCEPTION_STRINGS throw new ArgumentOutOfRangeException( "value", Environment.GetResourceString( "ArgumentOutOfRange_SmallCapacity" ) ); #else throw new ArgumentOutOfRangeException(); #endif } if(value > MaxCapacity) { #if EXCEPTION_STRINGS throw new ArgumentOutOfRangeException( "value", Environment.GetResourceString( "ArgumentOutOfRange_Capacity" ) ); #else throw new ArgumentOutOfRangeException(); #endif } int currCapacity = currentString.Capacity; //If we already have the correct capacity, bail out early. if(value != currCapacity) { //Allocate a new String with the capacity and copy all of our old characters //into it. We've already guaranteed that our String will fit within that capacity. //We don't need to worry about the COW bit because we're always allocating a new String. String newString = String.GetStringForStringBuilder( currentString, value ); ReplaceString( th, newString ); } } } public int MaxCapacity { get { return m_MaxCapacity; } } // Read-Only Property // Ensures that the capacity of this string builder is at least the specified value. // If capacity is greater than the capacity of this string builder, then the capacity // is set to capacity; otherwise the capacity is unchanged. // public int EnsureCapacity( int capacity ) { if(capacity < 0) { #if EXCEPTION_STRINGS throw new ArgumentOutOfRangeException( "capacity", Environment.GetResourceString( "ArgumentOutOfRange_NegativeCapacity" ) ); #else throw new ArgumentOutOfRangeException(); #endif } Thread th; String currentString = GetThreadSafeString( out th ); //If we need more space or the COW bit is set, copy the buffer. if(!NeedsAllocation( currentString, capacity )) { return currentString.Capacity; } String newString = GetNewString( currentString, capacity ); ReplaceString( th, newString ); return newString.Capacity; } public override String ToString() { // // We assume that their read of m_currentThread will always occur after read of m_StringValue. // If these reads get re-ordered then it is possible to get a currentString owned by some other // (mutating) thread and yet think, according to currentThread, that such was not the case. // This is acheived by marking m_StringValue as volatile. // String currentString = m_StringValue; Thread currentThread = m_currentThread; // // Note calling ToString the second time or from a different thread will cause allocation of a new string. // If we do not make a copy if currentThread is IntPtr.Zero, we will have following race: // // (1) Thread T1 completes a mutation of the string and will become the owner. // T1 then starts another mutation operation and // A thread interleaving happens at this point. // (2) Thread T2 starts a ToString operation. T2 reads m_StringValue into its local currentString variable. // A thread interleaving happens at this point. // (3) Thread T3 finshes a mutation of the string in the StringBuilder , performing the ReplaceString call. // Thread T3 then starts a ToString operation. Assuming the string is not wasting excessive space, // T3 will proceeds to call ClearPostNullChar, registers NOBODY as the owner, and returns the string. // A thread interleaving happens at this point. // (4) Thread T2 resumes execution. T2 reads m_currentThread and sees that NOBODY is the registered owner // Assuming its currentString is not wasting excessive space, T2 will return the same string that thread T1 is // in the middle of mutating. // if(currentThread != Thread.CurrentThread) { return String.InternalCopy( currentString ); } if((2 * currentString.Length) < currentString.ArrayLength) { return String.InternalCopy( currentString ); } currentString.ClearPostNullChar(); m_currentThread = null; return currentString; } // Converts a substring of this string builder to a String. public String ToString( int startIndex, int length ) { // We here enforce the policy copying underlying String data in all cases, since StringBuilder // uses the the internal m_StringValue reference mutably. return m_StringValue.InternalSubStringWithChecks( startIndex, length, true ); } // Sets the length of the String in this buffer. If length is less than the current // instance, the StringBuilder is truncated. If length is greater than the current // instance, nulls are appended. The capacity is adjusted to be the same as the length. public int Length { get { return m_StringValue.Length; } set { Thread th; String currentString = GetThreadSafeString( out th ); if(value == 0) { //the user is trying to clear the string currentString.SetLength( 0 ); ReplaceString( th, currentString ); return; } int currentLength = currentString.Length; int newlength = value; //If our length is less than 0 or greater than our Maximum capacity, bail. if(newlength < 0) { #if EXCEPTION_STRINGS throw new ArgumentOutOfRangeException( "newlength", Environment.GetResourceString( "ArgumentOutOfRange_NegativeLength" ) ); #else throw new ArgumentOutOfRangeException(); #endif } if(newlength > MaxCapacity) { #if EXCEPTION_STRINGS throw new ArgumentOutOfRangeException( "capacity", Environment.GetResourceString( "ArgumentOutOfRange_SmallCapacity" ) ); #else throw new ArgumentOutOfRangeException(); #endif } //Jump out early if our requested length our currentlength. //This will be a pretty rare branch. if(newlength == currentLength) { return; } //If the StringBuilder has never been converted to a string, simply set the length //without allocating a new string. if(newlength <= currentString.Capacity) { if(newlength > currentLength) { for(int i = currentLength; i < newlength; i++) // This is a rare case anyway. currentString.InternalSetCharNoBoundsCheck( i, '\0' ); } currentString.InternalSetCharNoBoundsCheck( newlength, '\0' ); //Null terminate. currentString.SetLength( newlength ); ReplaceString( th, currentString ); return; } // CopyOnWrite set we need to allocate a String int newCapacity = (newlength > currentString.Capacity) ? newlength : currentString.Capacity; String newString = String.GetStringForStringBuilder( currentString, newCapacity ); //We know exactly how many characters we need, so embed that knowledge in the String. newString.SetLength( newlength ); ReplaceString( th, newString ); } } [System.Runtime.CompilerServices.IndexerName( "Chars" )] public char this[int index] { get { return m_StringValue[index]; } set { Thread th; String currentString = GetThreadSafeString( out th ); currentString.SetChar( index, value ); ReplaceString( th, currentString ); } } // Appends a character at the end of this string builder. The capacity is adjusted as needed. public StringBuilder Append( char value, int repeatCount ) { if(repeatCount == 0) { return this; } if(repeatCount < 0) { #if EXCEPTION_STRINGS throw new ArgumentOutOfRangeException( "repeatCount", Environment.GetResourceString( "ArgumentOutOfRange_NegativeCount" ) ); #else throw new ArgumentOutOfRangeException(); #endif } Thread th; String currentString = GetThreadSafeString( out th ); int currentLength = currentString.Length; int requiredLength = currentLength + repeatCount; if(requiredLength < 0) throw new OutOfMemoryException(); if(!NeedsAllocation( currentString, requiredLength )) { currentString.AppendInPlace( value, repeatCount, currentLength ); ReplaceString( th, currentString ); return this; } String newString = GetNewString( currentString, requiredLength ); newString.AppendInPlace( value, repeatCount, currentLength ); ReplaceString( th, newString ); return this; } // Appends an array of characters at the end of this string builder. The capacity is adjusted as needed. public StringBuilder Append( char[] value, int startIndex, int charCount ) { int requiredLength; if(value == null) { if(startIndex == 0 && charCount == 0) { return this; } #if EXCEPTION_STRINGS throw new ArgumentNullException( "value" ); #else throw new ArgumentNullException(); #endif } if(charCount == 0) { return this; } if(startIndex < 0) { #if EXCEPTION_STRINGS throw new ArgumentOutOfRangeException( "startIndex", Environment.GetResourceString( "ArgumentOutOfRange_GenericPositive" ) ); #else throw new ArgumentOutOfRangeException(); #endif } if(charCount < 0) { #if EXCEPTION_STRINGS throw new ArgumentOutOfRangeException( "count", Environment.GetResourceString( "ArgumentOutOfRange_GenericPositive" ) ); #else throw new ArgumentOutOfRangeException(); #endif } if(charCount > value.Length - startIndex) { #if EXCEPTION_STRINGS throw new ArgumentOutOfRangeException( "count", Environment.GetResourceString( "ArgumentOutOfRange_Index" ) ); #else throw new ArgumentOutOfRangeException(); #endif } Thread th; String currentString = GetThreadSafeString( out th ); int currentLength = currentString.Length; requiredLength = currentLength + charCount; if(NeedsAllocation( currentString, requiredLength )) { String newString = GetNewString( currentString, requiredLength ); newString.AppendInPlace( value, startIndex, charCount, currentLength ); ReplaceString( th, newString ); } else { currentString.AppendInPlace( value, startIndex, charCount, currentLength ); ReplaceString( th, currentString ); } return this; } // Appends a copy of this string at the end of this string builder. public StringBuilder Append( String value ) { //If the value being added is null, eat the null //and return. if(value == null) { return this; } Thread th; String currentString = GetThreadSafeString( out th ); int currentLength = currentString.Length; int requiredLength = currentLength + value.Length; if(NeedsAllocation( currentString, requiredLength )) { String newString = GetNewString( currentString, requiredLength ); newString.AppendInPlace( value, currentLength ); ReplaceString( th, newString ); } else { currentString.AppendInPlace( value, currentLength ); ReplaceString( th, currentString ); } return this; } internal unsafe StringBuilder Append( char* value, int count ) { //If the value being added is null, eat the null //and return. if(value == null) { return this; } Thread th; String currentString = GetThreadSafeString( out th ); int currentLength = currentString.Length; int requiredLength = currentLength + count; if(NeedsAllocation( currentString, requiredLength )) { String newString = GetNewString( currentString, requiredLength ); newString.AppendInPlace( value, count, currentLength ); ReplaceString( th, newString ); } else { currentString.AppendInPlace( value, count, currentLength ); ReplaceString( th, currentString ); } return this; } #if WIN64 // STUBS_AS_IL [ResourceExposure(ResourceScope.None)] [MethodImplAttribute(MethodImplOptions.InternalCall)] internal unsafe extern void ReplaceBufferInternal(char* newBuffer, int newLength); [ResourceExposure(ResourceScope.None)] [MethodImplAttribute(MethodImplOptions.InternalCall)] internal unsafe extern void ReplaceBufferAnsiInternal(sbyte* newBuffer, int newLength); #endif // WIN64 // STUBS_AS_IL private bool NeedsAllocation( String currentString, int requiredLength ) { //<= accounts for the terminating 0 which we require on strings. return (currentString.ArrayLength <= requiredLength); } private String GetNewString( String currentString, int requiredLength ) { int newCapacity; int maxCapacity = m_MaxCapacity; if(requiredLength < 0) { throw new OutOfMemoryException(); } if(requiredLength > maxCapacity) { #if EXCEPTION_STRINGS throw new ArgumentOutOfRangeException( "requiredLength", Environment.GetResourceString( "ArgumentOutOfRange_SmallCapacity" ) ); #else throw new ArgumentOutOfRangeException(); #endif } newCapacity = (currentString.Capacity) * 2; // To force a predicatable growth of 160,320 etc. for testing purposes if(newCapacity < requiredLength) { newCapacity = requiredLength; } if(newCapacity > maxCapacity) { newCapacity = maxCapacity; } if(newCapacity <= 0) { #if EXCEPTION_STRINGS throw new ArgumentOutOfRangeException( "newCapacity", Environment.GetResourceString( "ArgumentOutOfRange_NegativeCapacity" ) ); #else throw new ArgumentOutOfRangeException(); #endif } return String.GetStringForStringBuilder( currentString, newCapacity ); } private void ReplaceString( Thread th, String value ) { BCLDebug.Assert( value != null, "[StringBuilder.ReplaceString]value!=null" ); // Following two writes (m_currentThread, m_StringValue) needs to happen in order. // This is guaranteed by making the fields volatile. // // If two threads are modifying the same StringBuilder at the same time, // we don't want them to use the same StringValue. This is done by comparing // owner thread id against current thread id in GetThreadSafeString. // Here we need to guarantee the ordering of writes to make sure if the another thread // see the change we have done to m_StringValue, it will see the change to m_currentThread as well. // m_currentThread = th; // new owner m_StringValue = value; } // Appends a copy of the characters in value from startIndex to startIndex + // count at the end of this string builder. public StringBuilder Append( String value, int startIndex, int count ) { //If the value being added is null, eat the null //and return. if(value == null) { if(startIndex == 0 && count == 0) { return this; } #if EXCEPTION_STRINGS throw new ArgumentNullException( "value" ); #else throw new ArgumentNullException(); #endif } if(count <= 0) { if(count == 0) { return this; } #if EXCEPTION_STRINGS throw new ArgumentOutOfRangeException( "count", Environment.GetResourceString( "ArgumentOutOfRange_GenericPositive" ) ); #else throw new ArgumentOutOfRangeException(); #endif } if(startIndex < 0 || (startIndex > value.Length - count)) { #if EXCEPTION_STRINGS throw new ArgumentOutOfRangeException( "startIndex", Environment.GetResourceString( "ArgumentOutOfRange_Index" ) ); #else throw new ArgumentOutOfRangeException(); #endif } Thread th; String currentString = GetThreadSafeString( out th ); int currentLength = currentString.Length; int requiredLength = currentLength + count; if(NeedsAllocation( currentString, requiredLength )) { String newString = GetNewString( currentString, requiredLength ); newString.AppendInPlace( value, startIndex, count, currentLength ); ReplaceString( th, newString ); } else { currentString.AppendInPlace( value, startIndex, count, currentLength ); ReplaceString( th, currentString ); } return this; } public StringBuilder AppendLine() { return Append( Environment.NewLine ); } public StringBuilder AppendLine( string value ) { Append( value ); return Append( Environment.NewLine ); } public void CopyTo( int sourceIndex, char[] destination, int destinationIndex, int count ) { if(destination == null) { #if EXCEPTION_STRINGS throw new ArgumentNullException( "destination" ); #else throw new ArgumentNullException(); #endif } if(count < 0) { #if EXCEPTION_STRINGS throw new ArgumentOutOfRangeException( Environment.GetResourceString( "Arg_NegativeArgCount" ), "count" ); #else throw new ArgumentOutOfRangeException(); #endif } if(destinationIndex < 0) { #if EXCEPTION_STRINGS throw new ArgumentOutOfRangeException( Environment.GetResourceString( "ArgumentOutOfRange_MustBeNonNegNum", "destinationIndex" ), "destinationIndex" ); #else throw new ArgumentOutOfRangeException(); #endif } if(destinationIndex > destination.Length - count) { #if EXCEPTION_STRINGS throw new ArgumentException( Environment.GetResourceString( "ArgumentOutOfRange_OffsetOut" ) ); #else throw new ArgumentException(); #endif } Thread th; String currentString = GetThreadSafeString( out th ); int currentLength = currentString.Length; if(sourceIndex < 0 || sourceIndex > currentLength) { #if EXCEPTION_STRINGS throw new ArgumentOutOfRangeException( Environment.GetResourceString( "ArgumentOutOfRange_Index" ) ); #else throw new ArgumentOutOfRangeException(); #endif } if(sourceIndex > currentLength - count) { #if EXCEPTION_STRINGS throw new ArgumentException( Environment.GetResourceString( "Arg_LongerThanSrcString" ) ); #else throw new ArgumentException(); #endif } // following fixed statement will throw exception for empty array. if(count == 0) { return; } unsafe { fixed(char* dest = &destination[destinationIndex], tsrc = currentString) { char* src = tsrc + sourceIndex; Buffer.InternalMemoryCopy( src, dest, count ); } } } // Inserts multiple copies of a string into this string builder at the specified position. // Existing characters are shifted to make room for the new text. // The capacity is adjusted as needed. If value equals String.Empty, this // string builder is not changed. // public unsafe StringBuilder Insert( int index, String value, int count ) { Thread th; String currentString = GetThreadSafeString( out th ); int currentLength = currentString.Length; //Range check the index. if(index < 0 || index > currentLength) { #if EXCEPTION_STRINGS throw new ArgumentOutOfRangeException( "index", Environment.GetResourceString( "ArgumentOutOfRange_Index" ) ); #else throw new ArgumentOutOfRangeException(); #endif } if(count < 0) { #if EXCEPTION_STRINGS throw new ArgumentOutOfRangeException( "count", Environment.GetResourceString( "ArgumentOutOfRange_NeedNonNegNum" ) ); #else throw new ArgumentOutOfRangeException(); #endif } //If value is null, empty or count is 0, do nothing. This is ECMA standard. if(value == null || value.Length == 0 || count == 0) { return this; } //Calculate the new length, ensure that we have the space and set the space variable for this buffer int requiredLength; try { requiredLength = checked( currentLength + (value.Length * count) ); } catch(OverflowException) { throw new OutOfMemoryException(); } if(NeedsAllocation( currentString, requiredLength )) { String newString = GetNewString( currentString, requiredLength ); newString.InsertInPlace( index, value, count, currentLength, requiredLength ); ReplaceString( th, newString ); } else { currentString.InsertInPlace( index, value, count, currentLength, requiredLength ); ReplaceString( th, currentString ); } return this; } // Property. // Removes the specified characters from this string builder. // The length of this string builder is reduced by // length, but the capacity is unaffected. // public StringBuilder Remove( int startIndex, int length ) { Thread th; String currentString = GetThreadSafeString( out th ); int currentLength = currentString.Length; if(length < 0) { #if EXCEPTION_STRINGS throw new ArgumentOutOfRangeException( "length", Environment.GetResourceString( "ArgumentOutOfRange_NegativeLength" ) ); #else throw new ArgumentOutOfRangeException(); #endif } if(startIndex < 0) { #if EXCEPTION_STRINGS throw new ArgumentOutOfRangeException( "startIndex", Environment.GetResourceString( "ArgumentOutOfRange_StartIndex" ) ); #else throw new ArgumentOutOfRangeException(); #endif } if(length > currentLength - startIndex) { #if EXCEPTION_STRINGS throw new ArgumentOutOfRangeException( "index", Environment.GetResourceString( "ArgumentOutOfRange_Index" ) ); #else throw new ArgumentOutOfRangeException(); #endif } currentString.RemoveInPlace( startIndex, length, currentLength ); ReplaceString( th, currentString ); return this; } // // // PUBLIC INSTANCE FUNCTIONS // // /*====================================Append==================================== ** ==============================================================================*/ // Appends a boolean to the end of this string builder. // The capacity is adjusted as needed. public StringBuilder Append( bool value ) { return Append( value.ToString() ); } // Appends an sbyte to this string builder. // The capacity is adjusted as needed. [CLSCompliant( false )] public StringBuilder Append( sbyte value ) { return Append( value.ToString( CultureInfo.CurrentCulture ) ); } // Appends a ubyte to this string builder. // The capacity is adjusted as needed. public StringBuilder Append( byte value ) { return Append( value.ToString( CultureInfo.CurrentCulture ) ); } // Appends a character at the end of this string builder. The capacity is adjusted as needed. public StringBuilder Append( char value ) { Thread th; String currentString = GetThreadSafeString( out th ); int currentLength = currentString.Length; if(!NeedsAllocation( currentString, currentLength + 1 )) { currentString.AppendInPlace( value, currentLength ); ReplaceString( th, currentString ); return this; } String newString = GetNewString( currentString, currentLength + 1 ); newString.AppendInPlace( value, currentLength ); ReplaceString( th, newString ); return this; } // Appends a short to this string builder. // The capacity is adjusted as needed. public StringBuilder Append( short value ) { return Append( value.ToString( CultureInfo.CurrentCulture ) ); } // Appends an int to this string builder. // The capacity is adjusted as needed. public StringBuilder Append( int value ) { return Append( value.ToString( CultureInfo.CurrentCulture ) ); } // Appends a long to this string builder. // The capacity is adjusted as needed. public StringBuilder Append( long value ) { return Append( value.ToString( CultureInfo.CurrentCulture ) ); } // Appends a float to this string builder. // The capacity is adjusted as needed. public StringBuilder Append( float value ) { return Append( value.ToString( CultureInfo.CurrentCulture ) ); } // Appends a double to this string builder. // The capacity is adjusted as needed. public StringBuilder Append( double value ) { return Append( value.ToString( CultureInfo.CurrentCulture ) ); } public StringBuilder Append( decimal value ) { return Append( value.ToString( CultureInfo.CurrentCulture ) ); } // Appends an ushort to this string builder. // The capacity is adjusted as needed. [CLSCompliant( false )] public StringBuilder Append( ushort value ) { return Append( value.ToString( CultureInfo.CurrentCulture ) ); } // Appends an uint to this string builder. // The capacity is adjusted as needed. [CLSCompliant( false )] public StringBuilder Append( uint value ) { return Append( value.ToString( CultureInfo.CurrentCulture ) ); } // Appends an unsigned long to this string builder. // The capacity is adjusted as needed. [CLSCompliant( false )] public StringBuilder Append( ulong value ) { return Append( value.ToString( CultureInfo.CurrentCulture ) ); } // Appends an Object to this string builder. // The capacity is adjusted as needed. public StringBuilder Append( Object value ) { if(null == value) { //Appending null is now a no-op. return this; } return Append( value.ToString() ); } // Appends all of the characters in value to the current instance. public StringBuilder Append( char[] value ) { if(null == value) { return this; } int valueLength = value.Length; Thread th; String currentString = GetThreadSafeString( out th ); int currentLength = currentString.Length; int requiredLength = currentLength + value.Length; if(NeedsAllocation( currentString, requiredLength )) { String newString = GetNewString( currentString, requiredLength ); newString.AppendInPlace( value, 0, valueLength, currentLength ); ReplaceString( th, newString ); } else { currentString.AppendInPlace( value, 0, valueLength, currentLength ); ReplaceString( th, currentString ); } return this; } /*====================================Insert==================================== ** ==============================================================================*/ // Returns a reference to the StringBuilder with ; value inserted into // the buffer at index. Existing characters are shifted to make room for the new text. // The capacity is adjusted as needed. If value equals String.Empty, the // StringBuilder is not changed. // public StringBuilder Insert( int index, String value ) { if(value == null) // This is to do the index validation return Insert( index, value, 0 ); else return Insert( index, value, 1 ); } // Returns a reference to the StringBuilder with ; value inserted into // the buffer at index. Existing characters are shifted to make room for the new text. // The capacity is adjusted as needed. If value equals String.Empty, the // StringBuilder is not changed. // public StringBuilder Insert( int index, bool value ) { return Insert( index, value.ToString(), 1 ); } // Returns a reference to the StringBuilder with ; value inserted into // the buffer at index. Existing characters are shifted to make room for the new text. // The capacity is adjusted as needed. If value equals String.Empty, the // StringBuilder is not changed. // [CLSCompliant( false )] public StringBuilder Insert( int index, sbyte value ) { return Insert( index, value.ToString( CultureInfo.CurrentCulture ), 1 ); } // Returns a reference to the StringBuilder with ; value inserted into // the buffer at index. Existing characters are shifted to make room for the new text. // The capacity is adjusted as needed. If value equals String.Empty, the // StringBuilder is not changed. // public StringBuilder Insert( int index, byte value ) { return Insert( index, value.ToString( CultureInfo.CurrentCulture ), 1 ); } // Returns a reference to the StringBuilder with ; value inserted into // the buffer at index. Existing characters are shifted to make room for the new text. // The capacity is adjusted as needed. If value equals String.Empty, the // StringBuilder is not changed. // public StringBuilder Insert( int index, short value ) { return Insert( index, value.ToString( CultureInfo.CurrentCulture ), 1 ); } // Returns a reference to the StringBuilder with ; value inserted into // the buffer at index. Existing characters are shifted to make room for the new text. // The capacity is adjusted as needed. If value equals String.Empty, the // StringBuilder is not changed. // public StringBuilder Insert( int index, char value ) { return Insert( index, Char.ToString( value ), 1 ); } // Returns a reference to the StringBuilder with ; value inserted into // the buffer at index. Existing characters are shifted to make room for the new text. // The capacity is adjusted as needed. If value equals String.Empty, the // StringBuilder is not changed. // public StringBuilder Insert( int index, char[] value ) { if(null == value) { return Insert( index, value, 0, 0 ); } return Insert( index, value, 0, value.Length ); } // Returns a reference to the StringBuilder with charCount characters from // value inserted into the buffer at index. Existing characters are shifted // to make room for the new text and capacity is adjusted as required. If value is null, the StringBuilder // is unchanged. Characters are taken from value starting at position startIndex. public StringBuilder Insert( int index, char[] value, int startIndex, int charCount ) { Thread th; String currentString = GetThreadSafeString( out th ); int currentLength = currentString.Length; //Range check the index. if(index < 0 || index > currentLength) { #if EXCEPTION_STRINGS throw new ArgumentOutOfRangeException( "index", Environment.GetResourceString( "ArgumentOutOfRange_Index" ) ); #else throw new ArgumentOutOfRangeException(); #endif } //If they passed in a null char array, just jump out quickly. if(value == null) { if(startIndex == 0 && charCount == 0) { return this; } #if EXCEPTION_STRINGS throw new ArgumentNullException( Environment.GetResourceString( "ArgumentNull_String" ) ); #else throw new ArgumentNullException(); #endif } //Range check the array. if(startIndex < 0) { #if EXCEPTION_STRINGS throw new ArgumentOutOfRangeException( "startIndex", Environment.GetResourceString( "ArgumentOutOfRange_StartIndex" ) ); #else throw new ArgumentOutOfRangeException(); #endif } if(charCount < 0) { #if EXCEPTION_STRINGS throw new ArgumentOutOfRangeException( "count", Environment.GetResourceString( "ArgumentOutOfRange_GenericPositive" ) ); #else throw new ArgumentOutOfRangeException(); #endif } if(startIndex > value.Length - charCount) { #if EXCEPTION_STRINGS throw new ArgumentOutOfRangeException( "startIndex", Environment.GetResourceString( "ArgumentOutOfRange_Index" ) ); #else throw new ArgumentOutOfRangeException(); #endif } if(charCount == 0) { // There is no data to insert, so just return. return this; } int requiredLength = currentLength + charCount; if(NeedsAllocation( currentString, requiredLength )) { String newString = GetNewString( currentString, requiredLength ); newString.InsertInPlace( index, value, startIndex, charCount, currentLength, requiredLength ); ReplaceString( th, newString ); } else { currentString.InsertInPlace( index, value, startIndex, charCount, currentLength, requiredLength ); ReplaceString( th, currentString ); } return this; } // Returns a reference to the StringBuilder with ; value inserted into // the buffer at index. Existing characters are shifted to make room for the new text. // The capacity is adjusted as needed. If value equals String.Empty, the // StringBuilder is not changed. // public StringBuilder Insert( int index, int value ) { return Insert( index, value.ToString( CultureInfo.CurrentCulture ), 1 ); } // Returns a reference to the StringBuilder with ; value inserted into // the buffer at index. Existing characters are shifted to make room for the new text. // The capacity is adjusted as needed. If value equals String.Empty, the // StringBuilder is not changed. // public StringBuilder Insert( int index, long value ) { return Insert( index, value.ToString( CultureInfo.CurrentCulture ), 1 ); } // Returns a reference to the StringBuilder with ; value inserted into // the buffer at index. Existing characters are shifted to make room for the new text. // The capacity is adjusted as needed. If value equals String.Empty, the // StringBuilder is not changed. // public StringBuilder Insert( int index, float value ) { return Insert( index, value.ToString( CultureInfo.CurrentCulture ), 1 ); } // Returns a reference to the StringBuilder with ; value inserted into // the buffer at index. Existing characters are shifted to make room for the new text. // The capacity is adjusted as needed. If value equals String.Empty, the // StringBuilder is not changed. // public StringBuilder Insert( int index, double value ) { return Insert( index, value.ToString( CultureInfo.CurrentCulture ), 1 ); } public StringBuilder Insert( int index, decimal value ) { return Insert( index, value.ToString( CultureInfo.CurrentCulture ), 1 ); } // Returns a reference to the StringBuilder with value inserted into // the buffer at index. Existing characters are shifted to make room for the new text. // The capacity is adjusted as needed. // [CLSCompliant( false )] public StringBuilder Insert( int index, ushort value ) { return Insert( index, value.ToString( CultureInfo.CurrentCulture ), 1 ); } // Returns a reference to the StringBuilder with value inserted into // the buffer at index. Existing characters are shifted to make room for the new text. // The capacity is adjusted as needed. // [CLSCompliant( false )] public StringBuilder Insert( int index, uint value ) { return Insert( index, value.ToString( CultureInfo.CurrentCulture ), 1 ); } // Returns a reference to the StringBuilder with value inserted into // the buffer at index. Existing characters are shifted to make room for the new text. // The capacity is adjusted as needed. // [CLSCompliant( false )] public StringBuilder Insert( int index, ulong value ) { return Insert( index, value.ToString( CultureInfo.CurrentCulture ), 1 ); } // Returns a reference to this string builder with value inserted into // the buffer at index. Existing characters are shifted to make room for the // new text. The capacity is adjusted as needed. If value equals String.Empty, the // StringBuilder is not changed. No changes are made if value is null. // public StringBuilder Insert( int index, Object value ) { //If we get a null if(null == value) { return this; } return Insert( index, value.ToString(), 1 ); } public StringBuilder AppendFormat( String format, Object arg0 ) { return AppendFormat( null, format, new Object[] { arg0 } ); } public StringBuilder AppendFormat( String format, Object arg0, Object arg1 ) { return AppendFormat( null, format, new Object[] { arg0, arg1 } ); } public StringBuilder AppendFormat( String format, Object arg0, Object arg1, Object arg2 ) { return AppendFormat( null, format, new Object[] { arg0, arg1, arg2 } ); } public StringBuilder AppendFormat( String format, params Object[] args ) { return AppendFormat( null, format, args ); } private static void FormatError() { #if EXCEPTION_STRINGS throw new FormatException( Environment.GetResourceString( "Format_InvalidString" ) ); #else throw new FormatException(); #endif } public StringBuilder AppendFormat( IFormatProvider provider, String format, params Object[] args ) { if(format == null || args == null) { #if EXCEPTION_STRINGS throw new ArgumentNullException( (format == null) ? "format" : "args" ); #else throw new ArgumentNullException(); #endif } char[] chars = format.ToCharArray( 0, format.Length ); int pos = 0; int len = chars.Length; char ch = '\x0'; ICustomFormatter cf = null; if(provider != null) { cf = (ICustomFormatter)provider.GetFormat( typeof( ICustomFormatter ) ); } while(true) { int p = pos; int i = pos; while(pos < len) { ch = chars[pos]; pos++; if(ch == '}') { if(pos < len && chars[pos] == '}') // Treat as escape character for }} pos++; else FormatError(); } if(ch == '{') { if(pos < len && chars[pos] == '{') // Treat as escape character for {{ pos++; else { pos--; break; } } chars[i++] = ch; } if(i > p) Append( chars, p, i - p ); if(pos == len) break; pos++; if(pos == len || (ch = chars[pos]) < '0' || ch > '9') FormatError(); int index = 0; do { index = index * 10 + ch - '0'; pos++; if(pos == len) FormatError(); ch = chars[pos]; } while(ch >= '0' && ch <= '9' && index < 1000000); if(index >= args.Length) #if EXCEPTION_STRINGS throw new FormatException( Environment.GetResourceString( "Format_IndexOutOfRange" ) ); #else throw new FormatException(); #endif while(pos < len && (ch = chars[pos]) == ' ') pos++; bool leftJustify = false; int width = 0; if(ch == ',') { pos++; while(pos < len && chars[pos] == ' ') pos++; if(pos == len) FormatError(); ch = chars[pos]; if(ch == '-') { leftJustify = true; pos++; if(pos == len) FormatError(); ch = chars[pos]; } if(ch < '0' || ch > '9') FormatError(); do { width = width * 10 + ch - '0'; pos++; if(pos == len) FormatError(); ch = chars[pos]; } while(ch >= '0' && ch <= '9' && width < 1000000); } while(pos < len && (ch = chars[pos]) == ' ') pos++; Object arg = args[index]; String fmt = null; if(ch == ':') { pos++; p = pos; i = pos; while(true) { if(pos == len) FormatError(); ch = chars[pos]; pos++; if(ch == '{') { if(pos < len && chars[pos] == '{') // Treat as escape character for {{ pos++; else FormatError(); } else if(ch == '}') { if(pos < len && chars[pos] == '}') // Treat as escape character for }} pos++; else { pos--; break; } } chars[i++] = ch; } if(i > p) fmt = new String( chars, p, i - p ); } if(ch != '}') FormatError(); pos++; String s = null; if(cf != null) { s = cf.Format( fmt, arg, provider ); } if(s == null) { if(arg is IFormattable) { s = ((IFormattable)arg).ToString( fmt, provider ); } else if(arg != null) { s = arg.ToString(); } } if(s == null) s = String.Empty; int pad = width - s.Length; if(!leftJustify && pad > 0) Append( ' ', pad ); Append( s ); if(leftJustify && pad > 0) Append( ' ', pad ); } return this; } // Returns a reference to the current StringBuilder with all instances of oldString // replaced with newString. If startIndex and count are specified, // we only replace strings completely contained in the range of startIndex to startIndex + // count. The strings to be replaced are checked on an ordinal basis (e.g. not culture aware). If // newValue is null, instances of oldValue are removed (e.g. replaced with nothing.). // public StringBuilder Replace( String oldValue, String newValue ) { return Replace( oldValue, newValue, 0, Length ); } //// [ResourceExposure( ResourceScope.None )] //////[MethodImplAttribute( MethodImplOptions.InternalCall )] //////public extern StringBuilder Replace( String oldValue, String newValue, int startIndex, int count ); public StringBuilder Replace( String oldValue, String newValue, int startIndex, int count ) { Thread th = null; var srcString = GetThreadSafeString( out th ); var srcLength = srcString.Length; var oldValueLength = oldValue .Length; var newValueLength = newValue .Length; var indexes = String.FindAllOccurrences( srcString, oldValue, startIndex, count ); int occurrences = indexes.Count; // // Allocate a string to contain the final result and fill it in place // if(occurrences > 0) { // // Allocate the new string, with the exact size needed // int requiredLength = srcLength - (occurrences * (oldValueLength - newValueLength)); // // Create a new string if the new value is longer than the old or we have not enough storage // if(NeedsAllocation( srcString, requiredLength ) || oldValueLength < newValueLength) { String newString = GetNewString( srcString, requiredLength ); String.ReplaceStringInPlace( srcString, newString, newValue, indexes, oldValueLength, newValueLength ); newString.SetLength( requiredLength ); newString.NullTerminate( ); ReplaceString( th, newString ); } else { String.ReplaceStringInPlace( srcString, srcString, newValue, indexes, oldValueLength, newValueLength ); srcString.SetLength( requiredLength ); srcString.NullTerminate( ); ReplaceString( th, srcString ); } } return this; } public bool Equals( StringBuilder sb ) { if(sb == null) return false; return ((this.Capacity == sb.Capacity) && (this.MaxCapacity == sb.MaxCapacity) && (this.m_StringValue.Equals( sb.m_StringValue ))); } // Returns a StringBuilder with all instances of oldChar replaced with // newChar. The size of the StringBuilder is unchanged because we're only // replacing characters. If startIndex and count are specified, we // only replace characters in the range from startIndex to startIndex+count // public StringBuilder Replace( char oldChar, char newChar ) { return Replace( oldChar, newChar, 0, this.Length ); } public StringBuilder Replace( char oldChar, char newChar, int startIndex, int count ) { Thread th; String currentString = GetThreadSafeString( out th ); int currentLength = currentString.Length; if(startIndex > currentLength) { #if EXCEPTION_STRINGS throw new ArgumentOutOfRangeException( "startIndex", Environment.GetResourceString( "ArgumentOutOfRange_Index" ) ); #else throw new ArgumentOutOfRangeException(); #endif } if(count < 0 || startIndex > currentLength - count) { #if EXCEPTION_STRINGS throw new ArgumentOutOfRangeException( "count", Environment.GetResourceString( "ArgumentOutOfRange_Index" ) ); #else throw new ArgumentOutOfRangeException(); #endif } BCLDebug.Assert( !NeedsAllocation( currentString, currentLength ), "New allocation should not happen!" ); currentString.ReplaceCharInPlace( oldChar, newChar, startIndex, count, currentLength ); ReplaceString( th, currentString ); return this; } public StringBuilder Clear() { m_StringValue.SetLength( 0 ); return this; } } } ================================================ FILE: Zelig/Zelig/RunTime/Framework/mscorlib/System/Text/UTF8Encoding.cs ================================================ // ==++== // // Copyright (c) Microsoft Corporation. All rights reserved. // // ==--== // The worker functions in this file was optimized for performance. If you make changes // you should use care to consider all of the interesting cases. // The code of all worker functions in this file is written twice: Once as as a slow loop, and the // second time as a fast loop. The slow loops handles all special cases, throws exceptions, etc. // The fast loops attempts to blaze through as fast as possible with optimistic range checks, // processing multiple characters at a time, and falling back to the slow loop for all special cases. // This define can be used to turn off the fast loops. Useful for finding whether // the problem is fastloop-specific. #define FASTLOOP namespace System.Text { using System; using System.Globalization; using System.Runtime.Serialization; using System.Security.Permissions; // Encodes text into and out of UTF-8. UTF-8 is a way of writing // Unicode characters with variable numbers of bytes per character, // optimized for the lower 127 ASCII characters. It's an efficient way // of encoding US English in an internationalizable way. // // Don't override IsAlwaysNormalized because it is just a Unicode Transformation and could be confused. // // The UTF-8 byte order mark is simply the Unicode byte order mark // (0xFEFF) written in UTF-8 (0xEF 0xBB 0xBF). The byte order mark is // used mostly to distinguish UTF-8 text from other encodings, and doesn't // switch the byte orderings. [Serializable] ////[System.Runtime.InteropServices.ComVisible( true )] public class UTF8Encoding : Encoding { /* bytes bits UTF-8 representation ----- ---- ----------------------------------- 1 7 0vvvvvvv 2 11 110vvvvv 10vvvvvv 3 16 1110vvvv 10vvvvvv 10vvvvvv 4 21 11110vvv 10vvvvvv 10vvvvvv 10vvvvvv ----- ---- ----------------------------------- Surrogate: Real Unicode value = (HighSurrogate - 0xD800) * 0x400 + (LowSurrogate - 0xDC00) + 0x10000 */ private const int UTF8_CODEPAGE = 65001; // Yes, the idea of emitting U+FEFF as a UTF-8 identifier has made it into // the standard. private bool emitUTF8Identifier = false; private bool isThrowException = false; public UTF8Encoding() : this( false ) { } public UTF8Encoding( bool encoderShouldEmitUTF8Identifier ) : this( encoderShouldEmitUTF8Identifier, false ) { } public UTF8Encoding( bool encoderShouldEmitUTF8Identifier, bool throwOnInvalidBytes ) : base( UTF8_CODEPAGE ) { this.emitUTF8Identifier = encoderShouldEmitUTF8Identifier; this.isThrowException = throwOnInvalidBytes; // Encoding's constructor already did this, but it'll be wrong if we're throwing exceptions if(this.isThrowException) { SetDefaultFallbacks(); } } internal override void SetDefaultFallbacks() { // For UTF-X encodings, we use a replacement fallback with an empty string if(this.isThrowException) { this.encoderFallback = EncoderFallback.ExceptionFallback; this.decoderFallback = DecoderFallback.ExceptionFallback; } else { this.encoderFallback = new EncoderReplacementFallback( String.Empty ); this.decoderFallback = new DecoderReplacementFallback( String.Empty ); } } // // WARNING: GetByteCount(string chars) // WARNING: has different variable names than EncodingNLS.cs, so this can't just be cut & pasted, // WARNING: otherwise it'll break VB's way of declaring these. // // The following methods are copied from EncodingNLS.cs. // Unfortunately EncodingNLS.cs is internal and we're public, so we have to reimpliment them here. // These should be kept in sync for the following classes: // EncodingNLS, UTF7Encoding, UTF8Encoding, UTF32Encoding, ASCIIEncoding, UnicodeEncoding // // Returns the number of bytes required to encode a range of characters in // a character array. // // All of our public Encodings that don't use EncodingNLS must have this (including EncodingNLS) // So if you fix this, fix the others. Currently those include: // EncodingNLS, UTF7Encoding, UTF8Encoding, UTF32Encoding, ASCIIEncoding, UnicodeEncoding // parent method is safe public override unsafe int GetByteCount( char[] chars , int index , int count ) { // Validate input parameters if(chars == null) { #if EXCEPTION_STRINGS throw new ArgumentNullException( "chars", Environment.GetResourceString( "ArgumentNull_Array" ) ); #else throw new ArgumentNullException(); #endif } if(index < 0 || count < 0) { #if EXCEPTION_STRINGS throw new ArgumentOutOfRangeException( (index < 0 ? "index" : "count"), Environment.GetResourceString( "ArgumentOutOfRange_NeedNonNegNum" ) ); #else throw new ArgumentOutOfRangeException(); #endif } if(chars.Length - index < count) { #if EXCEPTION_STRINGS throw new ArgumentOutOfRangeException( "chars", Environment.GetResourceString( "ArgumentOutOfRange_IndexCountBuffer" ) ); #else throw new ArgumentOutOfRangeException(); #endif } // If no input, return 0, avoid fixed empty array problem if(chars.Length == 0) { return 0; } // Just call the pointer version fixed(char* pChars = chars) { return GetByteCount( pChars + index, count, null ); } } // All of our public Encodings that don't use EncodingNLS must have this (including EncodingNLS) // So if you fix this, fix the others. Currently those include: // EncodingNLS, UTF7Encoding, UTF8Encoding, UTF32Encoding, ASCIIEncoding, UnicodeEncoding // parent method is safe public override unsafe int GetByteCount( String chars ) { // Validate input if(chars == null) { #if EXCEPTION_STRINGS throw new ArgumentNullException( "s" ); #else throw new ArgumentNullException(); #endif } fixed(char* pChars = chars) { return GetByteCount( pChars, chars.Length, null ); } } // All of our public Encodings that don't use EncodingNLS must have this (including EncodingNLS) // So if you fix this, fix the others. Currently those include: // EncodingNLS, UTF7Encoding, UTF8Encoding, UTF32Encoding, ASCIIEncoding, UnicodeEncoding [CLSCompliant( false )] //// [System.Runtime.InteropServices.ComVisible( false )] public override unsafe int GetByteCount( char* chars , int count ) { // Validate Parameters if(chars == null) { #if EXCEPTION_STRINGS throw new ArgumentNullException( "chars", Environment.GetResourceString( "ArgumentNull_Array" ) ); #else throw new ArgumentNullException(); #endif } if(count < 0) { #if EXCEPTION_STRINGS throw new ArgumentOutOfRangeException( "count", Environment.GetResourceString( "ArgumentOutOfRange_NeedNonNegNum" ) ); #else throw new ArgumentOutOfRangeException(); #endif } // Call it with empty encoder return GetByteCount( chars, count, null ); } // Parent method is safe. // All of our public Encodings that don't use EncodingNLS must have this (including EncodingNLS) // So if you fix this, fix the others. Currently those include: // EncodingNLS, UTF7Encoding, UTF8Encoding, UTF32Encoding, ASCIIEncoding, UnicodeEncoding public override unsafe int GetBytes( String s , int charIndex , int charCount , byte[] bytes , int byteIndex ) { if(s == null || bytes == null) { #if EXCEPTION_STRINGS throw new ArgumentNullException( (s == null ? "s" : "bytes"), Environment.GetResourceString( "ArgumentNull_Array" ) ); #else throw new ArgumentNullException(); #endif } if(charIndex < 0 || charCount < 0) { #if EXCEPTION_STRINGS throw new ArgumentOutOfRangeException( (charIndex < 0 ? "charIndex" : "charCount"), Environment.GetResourceString( "ArgumentOutOfRange_NeedNonNegNum" ) ); #else throw new ArgumentOutOfRangeException(); #endif } if(s.Length - charIndex < charCount) { #if EXCEPTION_STRINGS throw new ArgumentOutOfRangeException( "s", Environment.GetResourceString( "ArgumentOutOfRange_IndexCount" ) ); #else throw new ArgumentOutOfRangeException(); #endif } if(byteIndex < 0 || byteIndex > bytes.Length) { #if EXCEPTION_STRINGS throw new ArgumentOutOfRangeException( "byteIndex", Environment.GetResourceString( "ArgumentOutOfRange_Index" ) ); #else throw new ArgumentOutOfRangeException(); #endif } int byteCount = bytes.Length - byteIndex; // Fixed doesn't like 0 length arrays. if(bytes.Length == 0) { bytes = new byte[1]; } fixed(char* pChars = s) { fixed(byte* pBytes = bytes) { return GetBytes( pChars + charIndex, charCount, pBytes + byteIndex, byteCount, null ); } } } // Encodes a range of characters in a character array into a range of bytes // in a byte array. An exception occurs if the byte array is not large // enough to hold the complete encoding of the characters. The // GetByteCount method can be used to determine the exact number of // bytes that will be produced for a given range of characters. // Alternatively, the GetMaxByteCount method can be used to // determine the maximum number of bytes that will be produced for a given // number of characters, regardless of the actual character values. // // All of our public Encodings that don't use EncodingNLS must have this (including EncodingNLS) // So if you fix this, fix the others. Currently those include: // EncodingNLS, UTF7Encoding, UTF8Encoding, UTF32Encoding, ASCIIEncoding, UnicodeEncoding // parent method is safe public override unsafe int GetBytes( char[] chars , int charIndex , int charCount , byte[] bytes , int byteIndex ) { // Validate parameters if(chars == null || bytes == null) { #if EXCEPTION_STRINGS throw new ArgumentNullException( (chars == null ? "chars" : "bytes"), Environment.GetResourceString( "ArgumentNull_Array" ) ); #else throw new ArgumentNullException(); #endif } if(charIndex < 0 || charCount < 0) { #if EXCEPTION_STRINGS throw new ArgumentOutOfRangeException( (charIndex < 0 ? "charIndex" : "charCount"), Environment.GetResourceString( "ArgumentOutOfRange_NeedNonNegNum" ) ); #else throw new ArgumentOutOfRangeException(); #endif } if(chars.Length - charIndex < charCount) { #if EXCEPTION_STRINGS throw new ArgumentOutOfRangeException( "chars", Environment.GetResourceString( "ArgumentOutOfRange_IndexCountBuffer" ) ); #else throw new ArgumentOutOfRangeException(); #endif } if(byteIndex < 0 || byteIndex > bytes.Length) { #if EXCEPTION_STRINGS throw new ArgumentOutOfRangeException( "byteIndex", Environment.GetResourceString( "ArgumentOutOfRange_Index" ) ); #else throw new ArgumentOutOfRangeException(); #endif } // If nothing to encode return 0, avoid fixed problem if(chars.Length == 0) { return 0; } // Just call pointer version int byteCount = bytes.Length - byteIndex; // Fixed doesn't like 0 length arrays. if(bytes.Length == 0) { bytes = new byte[1]; } fixed(char* pChars = chars) { fixed(byte* pBytes = bytes) { // Remember that byteCount is # to decode, not size of array. return GetBytes( pChars + charIndex, charCount, pBytes + byteIndex, byteCount, null ); } } } // All of our public Encodings that don't use EncodingNLS must have this (including EncodingNLS) // So if you fix this, fix the others. Currently those include: // EncodingNLS, UTF7Encoding, UTF8Encoding, UTF32Encoding, ASCIIEncoding, UnicodeEncoding [CLSCompliant( false )] //// [System.Runtime.InteropServices.ComVisible( false )] public override unsafe int GetBytes( char* chars , int charCount , byte* bytes , int byteCount ) { // Validate Parameters if(bytes == null || chars == null) { #if EXCEPTION_STRINGS throw new ArgumentNullException( bytes == null ? "bytes" : "chars", Environment.GetResourceString( "ArgumentNull_Array" ) ); #else throw new ArgumentNullException(); #endif } if(charCount < 0 || byteCount < 0) { #if EXCEPTION_STRINGS throw new ArgumentOutOfRangeException( (charCount < 0 ? "charCount" : "byteCount"), Environment.GetResourceString( "ArgumentOutOfRange_NeedNonNegNum" ) ); #else throw new ArgumentOutOfRangeException(); #endif } return GetBytes( chars, charCount, bytes, byteCount, null ); } // Returns the number of characters produced by decoding a range of bytes // in a byte array. // // All of our public Encodings that don't use EncodingNLS must have this (including EncodingNLS) // So if you fix this, fix the others. Currently those include: // EncodingNLS, UTF7Encoding, UTF8Encoding, UTF32Encoding, ASCIIEncoding, UnicodeEncoding // parent method is safe public override unsafe int GetCharCount( byte[] bytes , int index , int count ) { // Validate Parameters if(bytes == null) { #if EXCEPTION_STRINGS throw new ArgumentNullException( "bytes", Environment.GetResourceString( "ArgumentNull_Array" ) ); #else throw new ArgumentNullException(); #endif } if(index < 0 || count < 0) { #if EXCEPTION_STRINGS throw new ArgumentOutOfRangeException( (index < 0 ? "index" : "count"), Environment.GetResourceString( "ArgumentOutOfRange_NeedNonNegNum" ) ); #else throw new ArgumentOutOfRangeException(); #endif } if(bytes.Length - index < count) { #if EXCEPTION_STRINGS throw new ArgumentOutOfRangeException( "bytes", Environment.GetResourceString( "ArgumentOutOfRange_IndexCountBuffer" ) ); #else throw new ArgumentOutOfRangeException(); #endif } // If no input just return 0, fixed doesn't like 0 length arrays. if(bytes.Length == 0) { return 0; } // Just call pointer version fixed(byte* pBytes = bytes) { return GetCharCount( pBytes + index, count, null ); } } // All of our public Encodings that don't use EncodingNLS must have this (including EncodingNLS) // So if you fix this, fix the others. Currently those include: // EncodingNLS, UTF7Encoding, UTF8Encoding, UTF32Encoding, ASCIIEncoding, UnicodeEncoding [CLSCompliant( false )] //// [System.Runtime.InteropServices.ComVisible( false )] public override unsafe int GetCharCount( byte* bytes , int count ) { // Validate Parameters if(bytes == null) { #if EXCEPTION_STRINGS throw new ArgumentNullException( "bytes", Environment.GetResourceString( "ArgumentNull_Array" ) ); #else throw new ArgumentNullException(); #endif } if(count < 0) { #if EXCEPTION_STRINGS throw new ArgumentOutOfRangeException( "count", Environment.GetResourceString( "ArgumentOutOfRange_NeedNonNegNum" ) ); #else throw new ArgumentOutOfRangeException(); #endif } return GetCharCount( bytes, count, null ); } // All of our public Encodings that don't use EncodingNLS must have this (including EncodingNLS) // So if you fix this, fix the others. Currently those include: // EncodingNLS, UTF7Encoding, UTF8Encoding, UTF32Encoding, ASCIIEncoding, UnicodeEncoding // parent method is safe public override unsafe int GetChars( byte[] bytes , int byteIndex , int byteCount , char[] chars , int charIndex ) { // Validate Parameters if(bytes == null || chars == null) { #if EXCEPTION_STRINGS throw new ArgumentNullException( bytes == null ? "bytes" : "chars", Environment.GetResourceString( "ArgumentNull_Array" ) ); #else throw new ArgumentNullException(); #endif } if(byteIndex < 0 || byteCount < 0) { #if EXCEPTION_STRINGS throw new ArgumentOutOfRangeException( (byteIndex < 0 ? "byteIndex" : "byteCount"), Environment.GetResourceString( "ArgumentOutOfRange_NeedNonNegNum" ) ); #else throw new ArgumentOutOfRangeException(); #endif } if(bytes.Length - byteIndex < byteCount) { #if EXCEPTION_STRINGS throw new ArgumentOutOfRangeException( "bytes", Environment.GetResourceString( "ArgumentOutOfRange_IndexCountBuffer" ) ); #else throw new ArgumentOutOfRangeException(); #endif } if(charIndex < 0 || charIndex > chars.Length) { #if EXCEPTION_STRINGS throw new ArgumentOutOfRangeException( "charIndex", Environment.GetResourceString( "ArgumentOutOfRange_Index" ) ); #else throw new ArgumentOutOfRangeException(); #endif } // If no input, return 0 & avoid fixed problem if(bytes.Length == 0) { return 0; } // Just call pointer version int charCount = chars.Length - charIndex; // Fixed doesn't like 0 length arrays. if(chars.Length == 0) { chars = new char[1]; } fixed(byte* pBytes = bytes) { fixed(char* pChars = chars) { // Remember that charCount is # to decode, not size of array return GetChars( pBytes + byteIndex, byteCount, pChars + charIndex, charCount, null ); } } } // All of our public Encodings that don't use EncodingNLS must have this (including EncodingNLS) // So if you fix this, fix the others. Currently those include: // EncodingNLS, UTF7Encoding, UTF8Encoding, UTF32Encoding, ASCIIEncoding, UnicodeEncoding [CLSCompliant( false )] //// [System.Runtime.InteropServices.ComVisible( false )] public unsafe override int GetChars( byte* bytes , int byteCount , char* chars , int charCount ) { // Validate Parameters if(bytes == null || chars == null) { #if EXCEPTION_STRINGS throw new ArgumentNullException( bytes == null ? "bytes" : "chars", Environment.GetResourceString( "ArgumentNull_Array" ) ); #else throw new ArgumentNullException(); #endif } if(charCount < 0 || byteCount < 0) { #if EXCEPTION_STRINGS throw new ArgumentOutOfRangeException( (charCount < 0 ? "charCount" : "byteCount"), Environment.GetResourceString( "ArgumentOutOfRange_NeedNonNegNum" ) ); #else throw new ArgumentOutOfRangeException(); #endif } return GetChars( bytes, byteCount, chars, charCount, null ); } // Returns a string containing the decoded representation of a range of // bytes in a byte array. // // All of our public Encodings that don't use EncodingNLS must have this (including EncodingNLS) // So if you fix this, fix the others. Currently those include: // EncodingNLS, UTF7Encoding, UTF8Encoding, UTF32Encoding, ASCIIEncoding, UnicodeEncoding // parent method is safe //// [System.Runtime.InteropServices.ComVisible( false )] public override unsafe String GetString( byte[] bytes , int index , int count ) { // Validate Parameters if(bytes == null) { #if EXCEPTION_STRINGS throw new ArgumentNullException( "bytes", Environment.GetResourceString( "ArgumentNull_Array" ) ); #else throw new ArgumentNullException(); #endif } if(index < 0 || count < 0) { #if EXCEPTION_STRINGS throw new ArgumentOutOfRangeException( (index < 0 ? "index" : "count"), Environment.GetResourceString( "ArgumentOutOfRange_NeedNonNegNum" ) ); #else throw new ArgumentOutOfRangeException(); #endif } if(bytes.Length - index < count) { #if EXCEPTION_STRINGS throw new ArgumentOutOfRangeException( "bytes", Environment.GetResourceString( "ArgumentOutOfRange_IndexCountBuffer" ) ); #else throw new ArgumentOutOfRangeException(); #endif } // Avoid problems with empty input buffer if(bytes.Length == 0) return String.Empty; fixed(byte* pBytes = bytes) { return String.CreateStringFromEncoding( pBytes + index, count, this ); } } // // End of standard methods copied from EncodingNLS.cs // // To simplify maintenance, the structure of GetByteCount and GetBytes should be // kept the same as much as possible internal override unsafe int GetByteCount( char* chars , int count , EncoderNLS baseEncoder ) { BCLDebug.Assert( chars != null, "[UTF8Encoding.GetByteCount]chars!=null" ); BCLDebug.Assert( count >= 0, "[UTF8Encoding.GetByteCount]count >=0" ); // For fallback we may need a fallback buffer. // We wait to initialize it though in case we don't have any broken input unicode EncoderFallbackBuffer fallbackBuffer = null; char* pSrc = chars; char* pEnd = pSrc + count; // Start by assuming we have as many as count int byteCount = count; int ch = 0; if(baseEncoder != null) { UTF8Encoder encoder = (UTF8Encoder)baseEncoder; ch = encoder.surrogateChar; // We mustn't have left over fallback data when counting if(encoder.InternalHasFallbackBuffer) { if((fallbackBuffer = encoder.FallbackBuffer).Remaining > 0) { #if EXCEPTION_STRINGS throw new ArgumentException( Environment.GetResourceString( "Argument_EncoderFallbackNotEmpty", this.EncodingName, encoder.Fallback.GetType() ) ); #else throw new ArgumentException(); #endif } // Set our internal fallback interesting things. fallbackBuffer.InternalInitialize( chars, pEnd, encoder, false ); } } for(; ; ) { // SLOWLOOP: does all range checks, handles all special cases, but it is slow if(pSrc >= pEnd) { if(ch == 0) { // Unroll any fallback that happens at the end ch = fallbackBuffer != null ? fallbackBuffer.InternalGetNextChar() : 0; if(ch > 0) { byteCount++; goto ProcessChar; } } else { // Case of surrogates in the fallback. if(fallbackBuffer != null && fallbackBuffer.bFallingBack) { BCLDebug.Assert( ch >= 0xD800 && ch <= 0xDBFF, "[UTF8Encoding.GetBytes]expected high surrogate, not 0x" + ((int)ch).ToString( "X4", CultureInfo.InvariantCulture ) ); ch = fallbackBuffer.InternalGetNextChar(); byteCount++; if(InRange( ch, CharUnicodeInfo.LOW_SURROGATE_START, CharUnicodeInfo.LOW_SURROGATE_END )) { ch = 0xfffd; byteCount++; goto EncodeChar; } else if(ch > 0) { goto ProcessChar; } else { byteCount--; // ignore last one. break; } } } if(ch <= 0) { break; } if(baseEncoder != null && !baseEncoder.MustFlush) { break; } // attempt to encode the partial surrogate (will fallback or ignore it), it'll also subtract 1. byteCount++; goto EncodeChar; } if(ch > 0) { BCLDebug.Assert( ch >= 0xD800 && ch <= 0xDBFF, "[UTF8Encoding.GetBytes]expected high surrogate, not 0x" + ((int)ch).ToString( "X4", CultureInfo.InvariantCulture ) ); // use separate helper variables for local contexts so that the jit optimizations // won't get confused about the variable lifetimes int cha = *pSrc; // count the pending surrogate byteCount++; // In previous byte, we encountered a high surrogate, so we are expecting a low surrogate here. // if (IsLowSurrogate(cha)) { if(InRange( cha, CharUnicodeInfo.LOW_SURROGATE_START, CharUnicodeInfo.LOW_SURROGATE_END )) { // Don't need a real # because we're just counting, anything > 0x7ff ('cept surrogate) will do. ch = 0xfffd; // ch = cha + (ch << 10) + // (0x10000 // - CharUnicodeInfo.LOW_SURROGATE_START // - (CharUnicodeInfo.HIGH_SURROGATE_START << 10) ); // Use this next char pSrc++; } // else ch is still high surrogate and encoding will fail (so don't add count) // attempt to encode the surrogate or partial surrogate goto EncodeChar; } // If we've used a fallback, then we have to check for it if(fallbackBuffer != null) { ch = fallbackBuffer.InternalGetNextChar(); if(ch > 0) { // We have an extra byte we weren't expecting. byteCount++; goto ProcessChar; } } // read next char. The JIT optimization seems to be getting confused when // compiling "ch = *pSrc++;", so rather use "ch = *pSrc; pSrc++;" instead ch = *pSrc; pSrc++; ProcessChar: // if (IsHighSurrogate(ch)) { if(InRange( ch, CharUnicodeInfo.HIGH_SURROGATE_START, CharUnicodeInfo.HIGH_SURROGATE_END )) { // we will count this surrogate next time around byteCount--; continue; } // either good char or partial surrogate EncodeChar: // throw exception on partial surrogate if necessary // if (IsLowSurrogate(ch) || IsHighSurrogate(ch)) if(InRange( ch, CharUnicodeInfo.HIGH_SURROGATE_START, CharUnicodeInfo.LOW_SURROGATE_END )) { // Lone surrogates aren't allowed // Have to make a fallback buffer if we don't have one if(fallbackBuffer == null) { // wait on fallbacks if we can // For fallback we may need a fallback buffer if(baseEncoder == null) { fallbackBuffer = this.encoderFallback.CreateFallbackBuffer(); } else { fallbackBuffer = baseEncoder.FallbackBuffer; } // Set our internal fallback interesting things. fallbackBuffer.InternalInitialize( chars, chars + count, baseEncoder, false ); } // Do our fallback. Actually we already know its a mixed up surrogate, // so the ref pSrc isn't gonna do anything. fallbackBuffer.InternalFallback( unchecked( (char)ch ), ref pSrc ); // Ignore it if we don't throw (we had preallocated this ch) byteCount--; ch = 0; continue; } // Count them if(ch > 0x7F) { if(ch > 0x7FF) { // the extra surrogate byte was compensated by the second surrogate character // (2 surrogates make 4 bytes. We've already counted 2 bytes, 1 per char) byteCount++; } byteCount++; } #if WIN64 // check for overflow if (byteCount < 0) { break; } #endif #if FASTLOOP // If still have fallback don't do fast loop if(fallbackBuffer != null && (ch = fallbackBuffer.InternalGetNextChar()) != 0) { // We're reserving 1 byte for each char by default byteCount++; goto ProcessChar; } int availableChars = PtrDiff( pEnd, pSrc ); // don't fall into the fast decoding loop if we don't have enough characters if(availableChars <= 13) { // try to get over the remainder of the ascii characters fast though char* pLocalEnd = pEnd; // hint to get pLocalEnd enregistered while(pSrc < pLocalEnd) { ch = *pSrc; pSrc++; if(ch > 0x7F) { goto ProcessChar; } } // we are done break; } #if WIN64 // make sure that we won't get a silent overflow inside the fast loop // (Fall out to slow loop if we have this many characters) availableChars &= 0x0FFFFFFF; #endif // To compute the upper bound, assume that all characters are ASCII characters at this point, // the boundary will be decreased for every non-ASCII character we encounter // Also, we need 3 + 4 chars reserve for the unrolled ansi decoding loop and for decoding of surrogates char* pStop = pSrc + availableChars - (3 + 4); while(pSrc < pStop) { ch = *pSrc; pSrc++; if(ch > 0x7F) // Not ASCII { if(ch > 0x7FF) // Not 2 Byte { if((ch & 0xF800) == 0xD800) // See if its a Surrogate { goto LongCode; } byteCount++; } byteCount++; } // get pSrc aligned if((unchecked( (int)pSrc ) & 0x2) != 0) { ch = *pSrc; pSrc++; if(ch > 0x7F) // Not ASCII { if(ch > 0x7FF) // Not 2 Byte { if((ch & 0xF800) == 0xD800) // See if its a Surrogate { goto LongCode; } byteCount++; } byteCount++; } } // Run 2 * 4 characters at a time! while(pSrc < pStop) { ch = *(int*)pSrc; int chc = *(int*)(pSrc + 2); if(((ch | chc) & unchecked( (int)0xFF80FF80 )) != 0) // See if not ASCII { if(((ch | chc) & unchecked( (int)0xF800F800 )) != 0) // See if not 2 Byte { goto LongCodeWithMask; } if((ch & unchecked( (int)0xFF800000 )) != 0) // Actually 0x07800780 is all we care about (4 bits) { byteCount++; } if((ch & unchecked( (int)0xFF80 )) != 0) { byteCount++; } if((chc & unchecked( (int)0xFF800000 )) != 0) { byteCount++; } if((chc & unchecked( (int)0xFF80 )) != 0) { byteCount++; } } pSrc += 4; ch = *(int*)pSrc; chc = *(int*)(pSrc + 2); if(((ch | chc) & unchecked( (int)0xFF80FF80 )) != 0) // See if not ASCII { if(((ch | chc) & unchecked( (int)0xF800F800 )) != 0) // See if not 2 Byte { goto LongCodeWithMask; } if((ch & unchecked( (int)0xFF800000 )) != 0) { byteCount++; } if((ch & unchecked( (int)0xFF80 )) != 0) { byteCount++; } if((chc & unchecked( (int)0xFF800000 )) != 0) { byteCount++; } if((chc & unchecked( (int)0xFF80 )) != 0) { byteCount++; } } pSrc += 4; } break; LongCodeWithMask: #if BIGENDIAN // be careful about the sign extension ch = (int)(((uint)ch) >> 16); #else // BIGENDIAN ch = (char)ch; #endif // BIGENDIAN pSrc++; if(ch <= 0x7F) { continue; } LongCode: // use separate helper variables for slow and fast loop so that the jit optimizations // won't get confused about the variable lifetimes if(ch > 0x7FF) { // if (IsLowSurrogate(ch) || IsHighSurrogate(ch)) if(InRange( ch, CharUnicodeInfo.HIGH_SURROGATE_START, CharUnicodeInfo.LOW_SURROGATE_END )) { // 4 byte encoding - high surrogate + low surrogate int chd = *pSrc; if( // !IsHighSurrogate(ch) // low without high -> bad ch > CharUnicodeInfo.HIGH_SURROGATE_END || // !IsLowSurrogate(chd) // high not followed by low -> bad !InRange( chd, CharUnicodeInfo.LOW_SURROGATE_START, CharUnicodeInfo.LOW_SURROGATE_END )) { // Back up and drop out to slow loop to figure out error pSrc--; break; } pSrc++; // byteCount - this byte is compensated by the second surrogate character } byteCount++; } byteCount++; // byteCount - the last byte is already included } #endif // FASTLOOP // no pending char at this point ch = 0; } #if WIN64 // check for overflow if (byteCount < 0) { throw new ArgumentException( Environment.GetResourceString("Argument_ConversionOverflow")); } #endif BCLDebug.Assert( fallbackBuffer == null || fallbackBuffer.Remaining == 0, "[UTF8Encoding.GetByteCount]Expected Empty fallback buffer" ); return byteCount; } // diffs two char pointers using unsigned arithmetic. The unsigned arithmetic // is good enough for us, and it tends to generate better code than the signed // arithmetic generated by default unsafe private static int PtrDiff( char* a , char* b ) { return (int)(((uint)((byte*)a - (byte*)b)) >> 1); } // byte* flavor just for parity unsafe private static int PtrDiff( byte* a , byte* b ) { return (int)(a - b); } private static bool InRange( int ch , int start , int end ) { return (uint)(ch - start) <= (uint)(end - start); } // Our workhorse // Note: We ignore mismatched surrogates, unless the exception flag is set in which case we throw internal override unsafe int GetBytes( char* chars , int charCount , byte* bytes , int byteCount , EncoderNLS baseEncoder ) { BCLDebug.Assert( chars != null, "[UTF8Encoding.GetBytes]chars!=null" ); BCLDebug.Assert( byteCount >= 0, "[UTF8Encoding.GetBytes]byteCount >=0" ); BCLDebug.Assert( charCount >= 0, "[UTF8Encoding.GetBytes]charCount >=0" ); BCLDebug.Assert( bytes != null, "[UTF8Encoding.GetBytes]bytes!=null" ); UTF8Encoder encoder = null; // For fallback we may need a fallback buffer. // We wait to initialize it though in case we don't have any broken input unicode EncoderFallbackBuffer fallbackBuffer = null; char* pSrc = chars; byte* pTarget = bytes; char* pEnd = pSrc + charCount; byte* pAllocatedBufferEnd = pTarget + byteCount; int ch = 0; // assume that JIT will enregister pSrc, pTarget and ch if(baseEncoder != null) { encoder = (UTF8Encoder)baseEncoder; ch = encoder.surrogateChar; // We mustn't have left over fallback data when counting if(encoder.InternalHasFallbackBuffer) { // We always need the fallback buffer in get bytes so we can flush any remaining ones if necessary fallbackBuffer = encoder.FallbackBuffer; if(fallbackBuffer.Remaining > 0 && encoder.m_throwOnOverflow) { #if EXCEPTION_STRINGS throw new ArgumentException( Environment.GetResourceString( "Argument_EncoderFallbackNotEmpty", this.EncodingName, encoder.Fallback.GetType() ) ); #else throw new ArgumentException(); #endif } // Set our internal fallback interesting things. fallbackBuffer.InternalInitialize( chars, pEnd, encoder, true ); } } for(; ; ) { // SLOWLOOP: does all range checks, handles all special cases, but it is slow if(pSrc >= pEnd) { if(ch == 0) { // Check if there's anthing left to get out of the fallback buffer ch = fallbackBuffer != null ? fallbackBuffer.InternalGetNextChar() : 0; if(ch > 0) { goto ProcessChar; } } else { // Case of leftover surrogates in the fallback buffer if(fallbackBuffer != null && fallbackBuffer.bFallingBack) { BCLDebug.Assert( ch >= 0xD800 && ch <= 0xDBFF, "[UTF8Encoding.GetBytes]expected high surrogate, not 0x" + ((int)ch).ToString( "X4", CultureInfo.InvariantCulture ) ); int cha = ch; ch = fallbackBuffer.InternalGetNextChar(); if(InRange( ch, CharUnicodeInfo.LOW_SURROGATE_START, CharUnicodeInfo.LOW_SURROGATE_END )) { ch = ch + (cha << 10) + (0x10000 - CharUnicodeInfo.LOW_SURROGATE_START - (CharUnicodeInfo.HIGH_SURROGATE_START << 10)); goto EncodeChar; } else if(ch > 0) { goto ProcessChar; } else { break; } } } // attempt to encode the partial surrogate (will fail or ignore) if(ch > 0 && (encoder == null || encoder.MustFlush)) { goto EncodeChar; } // We're done break; } if(ch > 0) { // We have a high surrogate left over from a previous loop. BCLDebug.Assert( ch >= 0xD800 && ch <= 0xDBFF, "[UTF8Encoding.GetBytes]expected high surrogate, not 0x" + ((int)ch).ToString( "X4", CultureInfo.InvariantCulture ) ); // use separate helper variables for local contexts so that the jit optimizations // won't get confused about the variable lifetimes int cha = *pSrc; // In previous byte, we encountered a high surrogate, so we are expecting a low surrogate here. // if (IsLowSurrogate(cha)) { if(InRange( cha, CharUnicodeInfo.LOW_SURROGATE_START, CharUnicodeInfo.LOW_SURROGATE_END )) { ch = cha + (ch << 10) + (0x10000 - CharUnicodeInfo.LOW_SURROGATE_START - (CharUnicodeInfo.HIGH_SURROGATE_START << 10)); pSrc++; } // else ch is still high surrogate and encoding will fail // attempt to encode the surrogate or partial surrogate goto EncodeChar; } // If we've used a fallback, then we have to check for it if(fallbackBuffer != null) { ch = fallbackBuffer.InternalGetNextChar(); if(ch > 0) goto ProcessChar; } // read next char. The JIT optimization seems to be getting confused when // compiling "ch = *pSrc++;", so rather use "ch = *pSrc; pSrc++;" instead ch = *pSrc; pSrc++; ProcessChar: // if (IsHighSurrogate(ch)) { if(InRange( ch, CharUnicodeInfo.HIGH_SURROGATE_START, CharUnicodeInfo.HIGH_SURROGATE_END )) { continue; } // either good char or partial surrogate EncodeChar: // throw exception on partial surrogate if necessary // if (IsLowSurrogate(ch) || IsHighSurrogate(ch)) if(InRange( ch, CharUnicodeInfo.HIGH_SURROGATE_START, CharUnicodeInfo.LOW_SURROGATE_END )) { // Lone surrogates aren't allowed, we have to do fallback for them // Have to make a fallback buffer if we don't have one if(fallbackBuffer == null) { // wait on fallbacks if we can // For fallback we may need a fallback buffer if(baseEncoder == null) { fallbackBuffer = this.encoderFallback.CreateFallbackBuffer(); } else { fallbackBuffer = baseEncoder.FallbackBuffer; } // Set our internal fallback interesting things. fallbackBuffer.InternalInitialize( chars, pEnd, baseEncoder, true ); } // Do our fallback. Actually we already know its a mixed up surrogate, // so the ref pSrc isn't gonna do anything. fallbackBuffer.InternalFallback( unchecked( (char)ch ), ref pSrc ); // Ignore it if we don't throw ch = 0; continue; } // Count bytes needed int bytesNeeded = 1; if(ch > 0x7F) { if(ch > 0x7FF) { if(ch > 0xFFFF) { bytesNeeded++; // 4 bytes (surrogate pair) } bytesNeeded++; // 3 bytes (800-FFFF) } bytesNeeded++; // 2 bytes (80-7FF) } if(pTarget > pAllocatedBufferEnd - bytesNeeded) { // Left over surrogate from last time will cause pSrc == chars, so we'll throw if(fallbackBuffer != null && fallbackBuffer.bFallingBack) { fallbackBuffer.MovePrevious(); // Didn't use this fallback char if(ch > 0xFFFF) { fallbackBuffer.MovePrevious(); // Was surrogate, didn't use 2nd part either} } } else { pSrc--; // Didn't use this char if(ch > 0xFFFF) { pSrc--; // Was surrogate, didn't use 2nd part either} } } BCLDebug.Assert( pSrc >= chars || pTarget == bytes, "[UTF8Encoding.GetBytes]Expected pSrc to be within buffer or to throw with insufficient room." ); ThrowBytesOverflow( encoder, pTarget == bytes ); // Throw if we must ch = 0; // Nothing left over (we backed up to start of pair if supplimentary) break; } if(ch <= 0x7F) { *pTarget = (byte)ch; } else { // use separate helper variables for local contexts so that the jit optimizations // won't get confused about the variable lifetimes int chb; if(ch <= 0x7FF) { // 2 byte encoding chb = (byte)(unchecked( (sbyte)0xC0 ) | (ch >> 6)); } else { if(ch <= 0xFFFF) { chb = (byte)(unchecked( (sbyte)0xE0 ) | (ch >> 12)); } else { *pTarget = (byte)(unchecked( (sbyte)0xF0 ) | (ch >> 18)); pTarget++; chb = unchecked( (sbyte)0x80 ) | (ch >> 12) & 0x3F; } *pTarget = (byte)chb; pTarget++; chb = unchecked( (sbyte)0x80 ) | (ch >> 6) & 0x3F; } *pTarget = (byte)chb; pTarget++; *pTarget = (byte)(unchecked( (sbyte)0x80 ) | ch & 0x3F); } pTarget++; #if FASTLOOP // If still have fallback don't do fast loop if(fallbackBuffer != null && (ch = fallbackBuffer.InternalGetNextChar()) != 0) { goto ProcessChar; } int availableChars = PtrDiff( pEnd, pSrc ); int availableBytes = PtrDiff( pAllocatedBufferEnd, pTarget ); // don't fall into the fast decoding loop if we don't have enough characters // Note that if we don't have enough bytes, pStop will prevent us from entering the fast loop. if(availableChars <= 13) { // we are hoping for 1 byte per char if(availableBytes < availableChars) { // not enough output room. no pending bits at this point ch = 0; continue; } // try to get over the remainder of the ascii characters fast though char* pLocalEnd = pEnd; // hint to get pLocalEnd enregistered while(pSrc < pLocalEnd) { ch = *pSrc; pSrc++; // Not ASCII, need more than 1 byte per char if(ch > 0x7F) { goto ProcessChar; } *pTarget = (byte)ch; pTarget++; } // we are done, let ch be 0 to clear encoder ch = 0; break; } // we need at least 1 byte per character, but Convert might allow us to convert // only part of the input, so try as much as we can. Reduce charCount if necessary if(availableBytes < availableChars) { availableChars = availableBytes; } // FASTLOOP: // - optimistic range checks // - fallbacks to the slow loop for all special cases, exception throwing, etc. // To compute the upper bound, assume that all characters are ASCII characters at this point, // the boundary will be decreased for every non-ASCII character we encounter // Also, we need 5 chars reserve for the unrolled ansi decoding loop and for decoding of surrogates // If there aren't enough bytes for the output, then pStop will be <= pSrc and will bypass the loop. char* pStop = pSrc + availableChars - 5; while(pSrc < pStop) { ch = *pSrc; pSrc++; if(ch > 0x7F) { goto LongCode; } *pTarget = (byte)ch; pTarget++; // get pSrc aligned if((unchecked( (int)pSrc ) & 0x2) != 0) { ch = *pSrc; pSrc++; if(ch > 0x7F) { goto LongCode; } *pTarget = (byte)ch; pTarget++; } // Run 4 characters at a time! while(pSrc < pStop) { ch = *(int*)pSrc; int chc = *(int*)(pSrc + 2); if(((ch | chc) & unchecked( (int)0xFF80FF80 )) != 0) { goto LongCodeWithMask; } // Unfortunately, this is endianess sensitive #if BIGENDIAN *pTarget = (byte)(ch>>16); *(pTarget+1) = (byte)ch; pSrc += 4; *(pTarget+2) = (byte)(chc>>16); *(pTarget+3) = (byte)chc; pTarget += 4; #else // BIGENDIAN *pTarget = (byte)ch; *(pTarget + 1) = (byte)(ch >> 16); pSrc += 4; *(pTarget + 2) = (byte)chc; *(pTarget + 3) = (byte)(chc >> 16); pTarget += 4; #endif // BIGENDIAN } continue; LongCodeWithMask: #if BIGENDIAN // be careful about the sign extension ch = (int)(((uint)ch) >> 16); #else // BIGENDIAN ch = (char)ch; #endif // BIGENDIAN pSrc++; if(ch > 0x7F) { goto LongCode; } *pTarget = (byte)ch; pTarget++; continue; LongCode: // use separate helper variables for slow and fast loop so that the jit optimizations // won't get confused about the variable lifetimes int chd; if(ch <= 0x7FF) { // 2 byte encoding chd = unchecked( (sbyte)0xC0 ) | (ch >> 6); } else { // if (!IsLowSurrogate(ch) && !IsHighSurrogate(ch)) if(!InRange( ch, CharUnicodeInfo.HIGH_SURROGATE_START, CharUnicodeInfo.LOW_SURROGATE_END )) { // 3 byte encoding chd = unchecked( (sbyte)0xE0 ) | (ch >> 12); } else { // 4 byte encoding - high surrogate + low surrogate // if (!IsHighSurrogate(ch)) if(ch > CharUnicodeInfo.HIGH_SURROGATE_END) { // low without high -> bad, try again in slow loop pSrc -= 1; break; } chd = *pSrc; pSrc++; // if (!IsLowSurrogate(chd)) { if(!InRange( chd, CharUnicodeInfo.LOW_SURROGATE_START, CharUnicodeInfo.LOW_SURROGATE_END )) { // high not followed by low -> bad, try again in slow loop pSrc -= 2; break; } ch = chd + (ch << 10) + (0x10000 - CharUnicodeInfo.LOW_SURROGATE_START - (CharUnicodeInfo.HIGH_SURROGATE_START << 10)); *pTarget = (byte)(unchecked( (sbyte)0xF0 ) | (ch >> 18)); // pStop - this byte is compensated by the second surrogate character // 2 input chars require 4 output bytes. 2 have been anticipated already // and 2 more will be accounted for by the 2 pStop-- calls below. pTarget++; chd = unchecked( (sbyte)0x80 ) | (ch >> 12) & 0x3F; } *pTarget = (byte)chd; pStop--; // 3 byte sequence for 1 char, so need pStop-- and the one below too. pTarget++; chd = unchecked( (sbyte)0x80 ) | (ch >> 6) & 0x3F; } *pTarget = (byte)chd; pStop--; // 2 byte sequence for 1 char so need pStop--. pTarget++; *pTarget = (byte)(unchecked( (sbyte)0x80 ) | ch & 0x3F); // pStop - this byte is already included pTarget++; } BCLDebug.Assert( pTarget <= pAllocatedBufferEnd, "[UTF8Encoding.GetBytes]pTarget <= pAllocatedBufferEnd" ); #endif // FASTLOOP // no pending char at this point ch = 0; } // Do we have to set the encoder bytes? if(encoder != null) { BCLDebug.Assert( !encoder.MustFlush || ch == 0, "[UTF8Encoding.GetBytes] Expected no mustflush or 0 leftover ch " + ch.ToString( "X2", CultureInfo.InvariantCulture ) ); encoder.surrogateChar = ch; encoder.m_charsUsed = (int)(pSrc - chars); } BCLDebug.Assert( fallbackBuffer == null || fallbackBuffer.Remaining == 0 || baseEncoder == null || !baseEncoder.m_throwOnOverflow, "[UTF8Encoding.GetBytes]Expected empty fallback buffer if not converting" ); return (int)(pTarget - bytes); } // These are bitmasks used to maintain the state in the decoder. They occupy the higher bits // while the actual character is being built in the lower bits. They are shifted together // with the actual bits of the character. // bits 30 & 31 are used for pending bits fixup private const int FinalByte = 1 << 29; private const int SupplimentarySeq = 1 << 28; private const int ThreeByteSeq = 1 << 27; // Note: We throw exceptions on individually encoded surrogates and other non-shortest forms. // If exceptions aren't turned on, then we drop all non-shortest &individual surrogates. // // To simplify maintenance, the structure of GetCharCount and GetChars should be // kept the same as much as possible internal override unsafe int GetCharCount( byte* bytes , int count , DecoderNLS baseDecoder ) { BCLDebug.Assert( count >= 0, "[UTF8Encoding.GetCharCount]count >=0" ); BCLDebug.Assert( bytes != null, "[UTF8Encoding.GetCharCount]bytes!=null" ); // Initialize stuff byte* pSrc = bytes; byte* pEnd = pSrc + count; // Start by assuming we have as many as count, charCount always includes the adjustment // for the character being decoded int charCount = count; int ch = 0; DecoderFallbackBuffer fallback = null; if(baseDecoder != null) { UTF8Decoder decoder = (UTF8Decoder)baseDecoder; ch = decoder.bits; charCount -= (ch >> 30); // Adjust char count for # of expected bytes and expected output chars. // Shouldn't have anything in fallback buffer for GetCharCount // (don't have to check m_throwOnOverflow for count) BCLDebug.Assert( !decoder.InternalHasFallbackBuffer || decoder.FallbackBuffer.Remaining == 0, "[UTF8Encoding.GetCharCount]Expected empty fallback buffer at start" ); } for(; ; ) { // SLOWLOOP: does all range checks, handles all special cases, but it is slow if(pSrc >= pEnd) { break; } if(ch == 0) { // no pending bits goto ReadChar; } // read next byte. The JIT optimization seems to be getting confused when // compiling "ch = *pSrc++;", so rather use "ch = *pSrc; pSrc++;" instead int cha = *pSrc; pSrc++; // we are expecting to see trailing bytes like 10vvvvvv if((cha & unchecked( (sbyte)0xC0 )) != 0x80) { // This can be a valid starting byte for another UTF8 byte sequence, so let's put // the current byte back, and try to see if this is a valid byte for another UTF8 byte sequence pSrc--; charCount += (ch >> 30); goto InvalidByteSequence; } // fold in the new byte ch = (ch << 6) | (cha & 0x3F); if((ch & FinalByte) == 0) { BCLDebug.Assert( (ch & (SupplimentarySeq | ThreeByteSeq)) != 0, "[UTF8Encoding.GetChars]Invariant volation" ); if((ch & SupplimentarySeq) != 0) { if((ch & (FinalByte >> 6)) != 0) { // this is 3rd byte (of 4 byte supplimentary) - nothing to do continue; } // 2nd byte, check for non-shortest form of supplimentary char and the valid // supplimentary characters in range 0x010000 - 0x10FFFF at the same time if(!InRange( ch & 0x1F0, 0x10, 0x100 )) { goto InvalidByteSequence; } } else { // Must be 2nd byte of a 3-byte sequence // check for non-shortest form of 3 byte seq if((ch & (0x1F << 5)) == 0 || // non-shortest form (ch & (0xF800 >> 6)) == (0xD800 >> 6)) // illegal individually encoded surrogate { goto InvalidByteSequence; } } continue; } // ready to punch // adjust for surrogates in non-shortest form if((ch & (SupplimentarySeq | 0x1F0000)) == SupplimentarySeq) { charCount--; } goto EncodeChar; InvalidByteSequence: // this code fragment should be close to the gotos referencing it // Have to do fallback for invalid bytes if(fallback == null) { if(baseDecoder == null) { fallback = this.decoderFallback.CreateFallbackBuffer(); } else { fallback = baseDecoder.FallbackBuffer; } fallback.InternalInitialize( bytes, null ); } charCount += FallbackInvalidByteSequence( pSrc, ch, fallback ); ch = 0; continue; ReadChar: ch = *pSrc; pSrc++; ProcessChar: if(ch > 0x7F) { // If its > 0x7F, its start of a new multi-byte sequence // Long sequence, so unreserve our char. charCount--; // bit 6 has to be non-zero for start of multibyte chars. if((ch & 0x40) == 0) { // Unexpected trail byte goto InvalidByteSequence; } // start a new long code if((ch & 0x20) != 0) { if((ch & 0x10) != 0) { // 4 byte encoding - supplimentary character (2 surrogates) ch &= 0x0F; // check that bit 4 is zero and the valid supplimentary character // range 0x000000 - 0x10FFFF at the same time if(ch > 0x04) { ch |= 0xf0; goto InvalidByteSequence; } // Add bit flags so that when we check new characters & rotate we'll be flagged correctly. // Final byte flag, count fix if we don't make final byte & supplimentary sequence flag. ch |= (FinalByte >> 3 * 6) | // Final byte is 3 more bytes from now (1 << 30) | // If it dies on next byte we'll need an extra char (3 << (30 - 2 * 6)) | // If it dies on last byte we'll need to subtract a char (SupplimentarySeq) | (SupplimentarySeq >> 6) | (SupplimentarySeq >> 2 * 6) | (SupplimentarySeq >> 3 * 6); // Our character count will be 2 characters for these 4 bytes, so subtract another char charCount--; } else { // 3 byte encoding // Add bit flags so that when we check new characters & rotate we'll be flagged correctly. ch = (ch & 0x0F) | ((FinalByte >> 2 * 6) | (1 << 30) | (ThreeByteSeq) | (ThreeByteSeq >> 6) | (ThreeByteSeq >> 2 * 6)); // We'll expect 1 character for these 3 bytes, so subtract another char. charCount--; } } else { // 2 byte encoding ch &= 0x1F; // check for non-shortest form if(ch <= 1) { ch |= 0xc0; goto InvalidByteSequence; } // Add bit flags so we'll be flagged correctly ch |= (FinalByte >> 6); } continue; } EncodeChar: #if FASTLOOP int availableBytes = PtrDiff( pEnd, pSrc ); // don't fall into the fast decoding loop if we don't have enough bytes if(availableBytes <= 13) { // try to get over the remainder of the ascii characters fast though byte* pLocalEnd = pEnd; // hint to get pLocalEnd enregistered while(pSrc < pLocalEnd) { ch = *pSrc; pSrc++; if(ch > 0x7F) { goto ProcessChar; } } // we are done ch = 0; break; } // To compute the upper bound, assume that all characters are ASCII characters at this point, // the boundary will be decreased for every non-ASCII character we encounter // Also, we need 7 chars reserve for the unrolled ansi decoding loop and for decoding of multibyte sequences byte* pStop = pSrc + availableBytes - 7; while(pSrc < pStop) { ch = *pSrc; pSrc++; if(ch > 0x7F) { goto LongCode; } // get pSrc 2-byte aligned if((unchecked( (int)pSrc ) & 0x1) != 0) { ch = *pSrc; pSrc++; if(ch > 0x7F) { goto LongCode; } } // get pSrc 4-byte aligned if((unchecked( (int)pSrc ) & 0x2) != 0) { ch = *(ushort*)pSrc; if((ch & 0x8080) != 0) { goto LongCodeWithMask16; } pSrc += 2; } // Run 8 characters at a time! while(pSrc < pStop) { ch = *(int*)pSrc; int chb = *(int*)(pSrc + 4); if(((ch | chb) & unchecked( (int)0x80808080 )) != 0) { goto LongCodeWithMask32; } pSrc += 8; } break; #if BIGENDIAN LongCodeWithMask32: // be careful about the sign extension ch = (int)(((uint)ch) >> 16); LongCodeWithMask16: ch = (int)(((uint)ch) >> 8); #else // BIGENDIAN LongCodeWithMask32: LongCodeWithMask16: ch &= 0xFF; #endif // BIGENDIAN pSrc++; if(ch <= 0x7F) { continue; } LongCode: int chc = *pSrc; pSrc++; if( // bit 6 has to be zero (ch & 0x40) == 0 || // we are expecting to see trailing bytes like 10vvvvvv (chc & unchecked( (sbyte)0xC0 )) != 0x80) { goto BadLongCode; } chc &= 0x3F; // start a new long code if((ch & 0x20) != 0) { // fold the first two bytes together chc |= (ch & 0x0F) << 6; if((ch & 0x10) != 0) { // 4 byte encoding - surrogate ch = *pSrc; if( // check that bit 4 is zero, the non-shortest form of surrogate // and the valid surrogate range 0x000000 - 0x10FFFF at the same time !InRange( chc >> 4, 0x01, 0x10 ) || // we are expecting to see trailing bytes like 10vvvvvv (ch & unchecked( (sbyte)0xC0 )) != 0x80) { goto BadLongCode; } chc = (chc << 6) | (ch & 0x3F); ch = *(pSrc + 1); // we are expecting to see trailing bytes like 10vvvvvv if((ch & unchecked( (sbyte)0xC0 )) != 0x80) { goto BadLongCode; } pSrc += 2; // extra byte charCount--; } else { // 3 byte encoding ch = *pSrc; if( // check for non-shortest form of 3 byte seq (chc & (0x1F << 5)) == 0 || // Can't have surrogates here. (chc & (0xF800 >> 6)) == (0xD800 >> 6) || // we are expecting to see trailing bytes like 10vvvvvv (ch & unchecked( (sbyte)0xC0 )) != 0x80) { goto BadLongCode; } pSrc++; // extra byte charCount--; } } else { // 2 byte encoding // check for non-shortest form if((ch & 0x1E) == 0) { goto BadLongCode; } } // extra byte charCount--; } #endif // FASTLOOP // no pending bits at this point ch = 0; continue; BadLongCode: pSrc -= 2; ch = 0; continue; } // May have a problem if we have to flush if(ch != 0) { // We were already adjusting for these, so need to unadjust charCount += (ch >> 30); if(baseDecoder == null || baseDecoder.MustFlush) { // Have to do fallback for invalid bytes if(fallback == null) { if(baseDecoder == null) { fallback = this.decoderFallback.CreateFallbackBuffer(); } else { fallback = baseDecoder.FallbackBuffer; } fallback.InternalInitialize( bytes, null ); } charCount += FallbackInvalidByteSequence( pSrc, ch, fallback ); } } // Shouldn't have anything in fallback buffer for GetCharCount // (don't have to check m_throwOnOverflow for count) BCLDebug.Assert( fallback == null || fallback.Remaining == 0, "[UTF8Encoding.GetCharCount]Expected empty fallback buffer at end" ); return charCount; } // WARNING: If we throw an error, then System.Resources.ResourceReader calls this method. // So if we're really broken, then that could also throw an error... recursively. // So try to make sure GetChars can at least process all uses by // System.Resources.ResourceReader! // // Note: We throw exceptions on individually encoded surrogates and other non-shortest forms. // If exceptions aren't turned on, then we drop all non-shortest &individual surrogates. // // To simplify maintenance, the structure of GetCharCount and GetChars should be // kept the same as much as possible internal override unsafe int GetChars( byte* bytes , int byteCount , char* chars , int charCount , DecoderNLS baseDecoder ) { BCLDebug.Assert( chars != null, "[UTF8Encoding.GetChars]chars!=null" ); BCLDebug.Assert( byteCount >= 0, "[UTF8Encoding.GetChars]count >=0" ); BCLDebug.Assert( charCount >= 0, "[UTF8Encoding.GetChars]charCount >=0" ); BCLDebug.Assert( bytes != null, "[UTF8Encoding.GetChars]bytes!=null" ); byte* pSrc = bytes; char* pTarget = chars; byte* pEnd = pSrc + byteCount; char* pAllocatedBufferEnd = pTarget + charCount; int ch = 0; DecoderFallbackBuffer fallback = null; if(baseDecoder != null) { UTF8Decoder decoder = (UTF8Decoder)baseDecoder; ch = decoder.bits; // Shouldn't have anything in fallback buffer for GetChars // (don't have to check m_throwOnOverflow for chars, we always use all or none so always should be empty) BCLDebug.Assert( !decoder.InternalHasFallbackBuffer || decoder.FallbackBuffer.Remaining == 0, "[UTF8Encoding.GetChars]Expected empty fallback buffer at start" ); } for(; ; ) { // SLOWLOOP: does all range checks, handles all special cases, but it is slow if(pSrc >= pEnd) { break; } if(ch == 0) { // no pending bits goto ReadChar; } // read next byte. The JIT optimization seems to be getting confused when // compiling "ch = *pSrc++;", so rather use "ch = *pSrc; pSrc++;" instead int cha = *pSrc; pSrc++; // we are expecting to see trailing bytes like 10vvvvvv if((cha & unchecked( (sbyte)0xC0 )) != 0x80) { // This can be a valid starting byte for another UTF8 byte sequence, so let's put // the current byte back, and try to see if this is a valid byte for another UTF8 byte sequence pSrc--; goto InvalidByteSequence; } // fold in the new byte ch = (ch << 6) | (cha & 0x3F); if((ch & FinalByte) == 0) { // Not at last byte yet BCLDebug.Assert( (ch & (SupplimentarySeq | ThreeByteSeq)) != 0, "[UTF8Encoding.GetChars]Invariant volation" ); if((ch & SupplimentarySeq) != 0) { // Its a 4-byte supplimentary sequence if((ch & (FinalByte >> 6)) != 0) { // this is 3rd byte of 4 byte sequence - nothing to do continue; } // 2nd byte of 4 bytes // check for non-shortest form of surrogate and the valid surrogate // range 0x000000 - 0x10FFFF at the same time if(!InRange( ch & 0x1F0, 0x10, 0x100 )) { goto InvalidByteSequence; } } else { // Must be 2nd byte of a 3-byte sequence // check for non-shortest form of 3 byte seq if((ch & (0x1F << 5)) == 0 || // non-shortest form (ch & (0xF800 >> 6)) == (0xD800 >> 6)) // illegal individually encoded surrogate { goto InvalidByteSequence; } } continue; } // ready to punch // surrogate in shortest form? // Might be possible to get rid of this? Already did non-shortest check for 4-byte sequence when reading 2nd byte? if((ch & (SupplimentarySeq | 0x1F0000)) > SupplimentarySeq) { // let the range check for the second char throw the exception if(pTarget < pAllocatedBufferEnd) { *pTarget = (char)(((ch >> 10) & 0x7FF) + unchecked( (short)((CharUnicodeInfo.HIGH_SURROGATE_START - (0x10000 >> 10))) )); pTarget++; ch = (ch & 0x3FF) + unchecked( (int)(CharUnicodeInfo.LOW_SURROGATE_START) ); } } goto EncodeChar; InvalidByteSequence: // this code fragment should be close to the gotos referencing it // Have to do fallback for invalid bytes if(fallback == null) { if(baseDecoder == null) { fallback = this.decoderFallback.CreateFallbackBuffer(); } else { fallback = baseDecoder.FallbackBuffer; } fallback.InternalInitialize( bytes, pAllocatedBufferEnd ); } // This'll back us up the appropriate # of bytes if we didn't get anywhere if(!FallbackInvalidByteSequence( ref pSrc, ch, fallback, ref pTarget )) { // Ran out of buffer space // Need to throw an exception? BCLDebug.Assert( pSrc >= bytes || pTarget == chars, "[UTF8Encoding.GetChars]Expected to throw or remain in byte buffer after fallback" ); fallback.InternalReset(); ThrowCharsOverflow( baseDecoder, pTarget == chars ); ch = 0; break; } BCLDebug.Assert( pSrc >= bytes, "[UTF8Encoding.GetChars]Expected invalid byte sequence to have remained within the byte array" ); ch = 0; continue; ReadChar: ch = *pSrc; pSrc++; ProcessChar: if(ch > 0x7F) { // If its > 0x7F, its start of a new multi-byte sequence // bit 6 has to be non-zero if((ch & 0x40) == 0) { goto InvalidByteSequence; } // start a new long code if((ch & 0x20) != 0) { if((ch & 0x10) != 0) { // 4 byte encoding - supplimentary character (2 surrogates) ch &= 0x0F; // check that bit 4 is zero and the valid supplimentary character // range 0x000000 - 0x10FFFF at the same time if(ch > 0x04) { ch |= 0xf0; goto InvalidByteSequence; } ch |= (FinalByte >> 3 * 6) | (1 << 30) | (3 << (30 - 2 * 6)) | (SupplimentarySeq) | (SupplimentarySeq >> 6) | (SupplimentarySeq >> 2 * 6) | (SupplimentarySeq >> 3 * 6); } else { // 3 byte encoding ch = (ch & 0x0F) | ((FinalByte >> 2 * 6) | (1 << 30) | (ThreeByteSeq) | (ThreeByteSeq >> 6) | (ThreeByteSeq >> 2 * 6)); } } else { // 2 byte encoding ch &= 0x1F; // check for non-shortest form if(ch <= 1) { ch |= 0xc0; goto InvalidByteSequence; } ch |= (FinalByte >> 6); } continue; } EncodeChar: // write the pending character if(pTarget >= pAllocatedBufferEnd) { // Fix chars so we make sure to throw if we didn't output anything ch &= 0x1fffff; if(ch > 0x7f) { if(ch > 0x7ff) { if(ch >= CharUnicodeInfo.LOW_SURROGATE_START && ch <= CharUnicodeInfo.LOW_SURROGATE_END) { pSrc--; // It was 4 bytes pTarget--; // 1 was stored already, but we can't remember 1/2, so back up } else if(ch > 0xffff) { pSrc--; // It was 4 bytes, nothing was stored } pSrc--; // It was at least 3 bytes } pSrc--; // It was at least 2 bytes } pSrc--; // Throw that we don't have enough room (pSrc could be < chars if we had started to process // a 4 byte sequence alredy) BCLDebug.Assert( pSrc >= bytes || pTarget == chars, "[UTF8Encoding.GetChars]Expected pSrc to be within input buffer or throw due to no output]" ); ThrowCharsOverflow( baseDecoder, pTarget == chars ); // Don't store ch in decoder, we already backed up to its start ch = 0; // Didn't throw, just use this buffer size. break; } *pTarget = (char)ch; pTarget++; #if FASTLOOP int availableChars = PtrDiff( pAllocatedBufferEnd, pTarget ); int availableBytes = PtrDiff( pEnd, pSrc ); // don't fall into the fast decoding loop if we don't have enough bytes // Test for availableChars is done because pStop would be <= pTarget. if(availableBytes <= 13) { // we may need as many as 1 character per byte if(availableChars < availableBytes) { // not enough output room. no pending bits at this point ch = 0; continue; } // try to get over the remainder of the ascii characters fast though byte* pLocalEnd = pEnd; // hint to get pLocalEnd enregistered while(pSrc < pLocalEnd) { ch = *pSrc; pSrc++; if(ch > 0x7F) goto ProcessChar; *pTarget = (char)ch; pTarget++; } // we are done ch = 0; break; } // we may need as many as 1 character per byte, so reduce the byte count if necessary. // If availableChars is too small, pStop will be before pTarget and we won't do fast loop. if(availableChars < availableBytes) { availableBytes = availableChars; } // To compute the upper bound, assume that all characters are ASCII characters at this point, // the boundary will be decreased for every non-ASCII character we encounter // Also, we need 7 chars reserve for the unrolled ansi decoding loop and for decoding of multibyte sequences char* pStop = pTarget + availableBytes - 7; while(pTarget < pStop) { ch = *pSrc; pSrc++; if(ch > 0x7F) { goto LongCode; } *pTarget = (char)ch; pTarget++; // get pSrc to be 2-byte aligned if((unchecked( (int)pSrc ) & 0x1) != 0) { ch = *pSrc; pSrc++; if(ch > 0x7F) { goto LongCode; } *pTarget = (char)ch; pTarget++; } // get pSrc to be 4-byte aligned if((unchecked( (int)pSrc ) & 0x2) != 0) { ch = *(ushort*)pSrc; if((ch & 0x8080) != 0) { goto LongCodeWithMask16; } // Unfortunately, this is endianess sensitive #if BIGENDIAN *pTarget = (char)((ch >> 8) & 0x7F); pSrc += 2; *(pTarget+1) = (char)(ch & 0x7F); pTarget += 2; #else // BIGENDIAN *pTarget = (char)(ch & 0x7F); pSrc += 2; *(pTarget + 1) = (char)((ch >> 8) & 0x7F); pTarget += 2; #endif // BIGENDIAN } // Run 8 characters at a time! while(pTarget < pStop) { ch = *(int*)pSrc; int chb = *(int*)(pSrc + 4); if(((ch | chb) & unchecked( (int)0x80808080 )) != 0) { goto LongCodeWithMask32; } // Unfortunately, this is endianess sensitive #if BIGENDIAN *pTarget = (char)((ch >> 24) & 0x7F); *(pTarget+1) = (char)((ch >> 16) & 0x7F); *(pTarget+2) = (char)((ch >> 8) & 0x7F); *(pTarget+3) = (char)(ch & 0x7F); pSrc += 8; *(pTarget+4) = (char)((chb >> 24) & 0x7F); *(pTarget+5) = (char)((chb >> 16) & 0x7F); *(pTarget+6) = (char)((chb >> 8) & 0x7F); *(pTarget+7) = (char)(chb & 0x7F); pTarget += 8; #else // BIGENDIAN *pTarget = (char)(ch & 0x7F); *(pTarget + 1) = (char)((ch >> 8) & 0x7F); *(pTarget + 2) = (char)((ch >> 16) & 0x7F); *(pTarget + 3) = (char)((ch >> 24) & 0x7F); pSrc += 8; *(pTarget + 4) = (char)(chb & 0x7F); *(pTarget + 5) = (char)((chb >> 8) & 0x7F); *(pTarget + 6) = (char)((chb >> 16) & 0x7F); *(pTarget + 7) = (char)((chb >> 24) & 0x7F); pTarget += 8; #endif // BIGENDIAN } break; #if BIGENDIAN LongCodeWithMask32: // be careful about the sign extension ch = (int)(((uint)ch) >> 16); LongCodeWithMask16: ch = (int)(((uint)ch) >> 8); #else // BIGENDIAN LongCodeWithMask32: LongCodeWithMask16: ch &= 0xFF; #endif // BIGENDIAN pSrc++; if(ch <= 0x7F) { *pTarget = (char)ch; pTarget++; continue; } LongCode: int chc = *pSrc; pSrc++; if( // bit 6 has to be zero (ch & 0x40) == 0 || // we are expecting to see trailing bytes like 10vvvvvv (chc & unchecked( (sbyte)0xC0 )) != 0x80) { goto BadLongCode; } chc &= 0x3F; // start a new long code if((ch & 0x20) != 0) { // fold the first two bytes together chc |= (ch & 0x0F) << 6; if((ch & 0x10) != 0) { // 4 byte encoding - surrogate ch = *pSrc; if( // check that bit 4 is zero, the non-shortest form of surrogate // and the valid surrogate range 0x000000 - 0x10FFFF at the same time !InRange( chc >> 4, 0x01, 0x10 ) || // we are expecting to see trailing bytes like 10vvvvvv (ch & unchecked( (sbyte)0xC0 )) != 0x80) { goto BadLongCode; } chc = (chc << 6) | (ch & 0x3F); ch = *(pSrc + 1); // we are expecting to see trailing bytes like 10vvvvvv if((ch & unchecked( (sbyte)0xC0 )) != 0x80) { goto BadLongCode; } pSrc += 2; ch = (chc << 6) | (ch & 0x3F); *pTarget = (char)(((ch >> 10) & 0x7FF) + unchecked( (short)(CharUnicodeInfo.HIGH_SURROGATE_START - (0x10000 >> 10)) )); pTarget++; ch = (ch & 0x3FF) + unchecked( (short)(CharUnicodeInfo.LOW_SURROGATE_START) ); // extra byte, we're already planning 2 chars for 2 of these bytes, // but the big loop is testing the target against pStop, so we need // to subtract 2 more or we risk overrunning the input. Subtract // one here and one below. pStop--; } else { // 3 byte encoding ch = *pSrc; if( // check for non-shortest form of 3 byte seq (chc & (0x1F << 5)) == 0 || // Can't have surrogates here. (chc & (0xF800 >> 6)) == (0xD800 >> 6) || // we are expecting to see trailing bytes like 10vvvvvv (ch & unchecked( (sbyte)0xC0 )) != 0x80) { goto BadLongCode; } pSrc++; ch = (chc << 6) | (ch & 0x3F); // extra byte, we're only expecting 1 char for each of these 3 bytes, // but the loop is testing the target (not source) against pStop, so // we need to subtract 2 more or we risk overrunning the input. // Subtract 1 here and one more below pStop--; } } else { // 2 byte encoding ch &= 0x1F; // check for non-shortest form if(ch <= 1) { goto BadLongCode; } ch = (ch << 6) | chc; } *pTarget = (char)ch; pTarget++; // extra byte, we're only expecting 1 char for each of these 2 bytes, // but the loop is testing the target (not source) against pStop. // subtract an extra count from pStop so that we don't overrun the input. pStop--; } #endif // FASTLOOP BCLDebug.Assert( pTarget <= pAllocatedBufferEnd, "[UTF8Encoding.GetChars]pTarget <= pAllocatedBufferEnd" ); // no pending bits at this point ch = 0; continue; BadLongCode: pSrc -= 2; ch = 0; continue; } if(ch != 0 && (baseDecoder == null || baseDecoder.MustFlush)) { // Have to do fallback for invalid bytes if(fallback == null) { if(baseDecoder == null) { fallback = this.decoderFallback.CreateFallbackBuffer(); } else { fallback = baseDecoder.FallbackBuffer; } fallback.InternalInitialize( bytes, pAllocatedBufferEnd ); } // This'll back us up the appropriate # of bytes if we didn't get anywhere if(!FallbackInvalidByteSequence( ref pSrc, ch, fallback, ref pTarget )) { BCLDebug.Assert( pSrc >= bytes || pTarget == chars, "[UTF8Encoding.GetChars]Expected to throw or remain in byte buffer while flushing" ); // Ran out of buffer space // Need to throw an exception? fallback.InternalReset(); ThrowCharsOverflow( baseDecoder, pTarget == chars ); } BCLDebug.Assert( pSrc >= bytes, "[UTF8Encoding.GetChars]Expected flushing invalid byte sequence to have remained within the byte array" ); ch = 0; } if(baseDecoder != null) { UTF8Decoder decoder = (UTF8Decoder)baseDecoder; // If we're storing flush data we expect all bits to be used or else // we're stuck in the middle of a conversion BCLDebug.Assert( !baseDecoder.MustFlush || ch == 0 || !baseDecoder.m_throwOnOverflow, "[UTF8Encoding.GetChars]Expected no must flush or no left over bits or no throw on overflow." ); // Remember our leftover bits. decoder.bits = ch; baseDecoder.m_bytesUsed = (int)(pSrc - bytes); } // Shouldn't have anything in fallback buffer for GetChars // (don't have to check m_throwOnOverflow for chars) BCLDebug.Assert( fallback == null || fallback.Remaining == 0, "[UTF8Encoding.GetChars]Expected empty fallback buffer at end" ); return PtrDiff( pTarget, chars ); } // During GetChars we had an invalid byte sequence // pSrc is backed up to the start of the bad sequence if we didn't have room to // fall it back. Otherwise pSrc remains wher it is. private unsafe bool FallbackInvalidByteSequence( ref byte* pSrc , int ch , DecoderFallbackBuffer fallback , ref char* pTarget ) { // Get our byte[] byte* pStart = pSrc; byte[] bytesUnknown = GetBytesUnknown( ref pStart, ch ); // Do the actual fallback if(!fallback.InternalFallback( bytesUnknown, pSrc, ref pTarget )) { // Oops, it failed, back up to pStart pSrc = pStart; return false; } // It worked return true; } // During GetCharCount we had an invalid byte sequence // pSrc is used to find the index that points to the invalid bytes, // however the byte[] contains the fallback bytes (in case the index is -1) private unsafe int FallbackInvalidByteSequence( byte* pSrc , int ch , DecoderFallbackBuffer fallback ) { // Get our byte[] byte[] bytesUnknown = GetBytesUnknown( ref pSrc, ch ); // Do the actual fallback int count = fallback.InternalFallback( bytesUnknown, pSrc ); // # of fallback chars expected. // Note that we only get here for "long" sequences, and have already unreserved // the count that we prereserved for the input bytes return count; } // Note that some of these bytes may have come from a previous fallback, so we cannot // just decrement the pointer and use the values we read. In those cases we have // to regenerate the original values. private unsafe byte[] GetBytesUnknown( ref byte* pSrc, int ch ) { // Get our byte[] byte[] bytesUnknown = null; // See if it was a plain char // (have to check >= 0 because we have all sorts of wierd bit flags) if(ch < 0x100 && ch >= 0) { pSrc--; bytesUnknown = new byte[] { unchecked( (byte)ch ) }; } // See if its an unfinished 2 byte sequence else if((ch & (SupplimentarySeq | ThreeByteSeq)) == 0) { pSrc--; bytesUnknown = new byte[] { unchecked( (byte)((ch & 0x1F) | 0xc0) ) }; } // So now we're either 2nd byte of 3 or 4 byte sequence or // we hit a non-trail byte or we ran out of space for 3rd byte of 4 byte sequence // 1st check if its a 4 byte sequence else if((ch & SupplimentarySeq) != 0) { // 3rd byte of 4 byte sequence? if((ch & (FinalByte >> 6)) != 0) { // 3rd byte of 4 byte sequence pSrc -= 3; bytesUnknown = new byte[] { unchecked((byte)(((ch >> 12) & 0x07) | 0xF0)), unchecked((byte)(((ch >> 6) & 0x3F) | 0x80)), unchecked((byte)(((ch ) & 0x3F) | 0x80)) }; } else if((ch & (FinalByte >> 12)) != 0) { // 2nd byte of a 4 byte sequence pSrc -= 2; bytesUnknown = new byte[] { unchecked((byte)(((ch >> 6) & 0x07) | 0xF0)), unchecked((byte)(((ch ) & 0x3F) | 0x80)) }; } else { // 4th byte of a 4 byte sequence pSrc--; bytesUnknown = new byte[] { unchecked( (byte)(((ch) & 0x07) | 0xF0) ) }; } } else { // 2nd byte of 3 byte sequence? if((ch & (FinalByte >> 6)) != 0) { // So its 2nd byte of a 3 byte sequence pSrc -= 2; bytesUnknown = new byte[] { unchecked((byte)(((ch >> 6) & 0x0F) | 0xE0)), unchecked((byte)(((ch ) & 0x3F) | 0x80)) }; } else { // 1st byte of a 3 byte sequence pSrc--; bytesUnknown = new byte[] { unchecked( (byte)(((ch) & 0x0F) | 0xE0) ) }; } } return bytesUnknown; } public override Decoder GetDecoder() { return new UTF8Decoder( this ); } public override Encoder GetEncoder() { return new UTF8Encoder( this ); } public override int GetMaxByteCount( int charCount ) { if(charCount < 0) { #if EXCEPTION_STRINGS throw new ArgumentOutOfRangeException( "charCount", Environment.GetResourceString( "ArgumentOutOfRange_NeedNonNegNum" ) ); #else throw new ArgumentOutOfRangeException(); #endif } // Characters would be # of characters + 1 in case left over high surrogate is ? * max fallback long byteCount = (long)charCount + 1; if(EncoderFallback.MaxCharCount > 1) { byteCount *= EncoderFallback.MaxCharCount; } // Max 3 bytes per char. (4 bytes per 2 chars for surrogates) byteCount *= 3; if(byteCount > 0x7fffffff) { #if EXCEPTION_STRINGS throw new ArgumentOutOfRangeException( "charCount", Environment.GetResourceString( "ArgumentOutOfRange_GetByteCountOverflow" ) ); #else throw new ArgumentOutOfRangeException(); #endif } return (int)byteCount; } public override int GetMaxCharCount( int byteCount ) { if(byteCount < 0) { #if EXCEPTION_STRINGS throw new ArgumentOutOfRangeException( "byteCount", Environment.GetResourceString( "ArgumentOutOfRange_NeedNonNegNum" ) ); #else throw new ArgumentOutOfRangeException(); #endif } // Figure out our length, 1 char per input byte + 1 char if 1st byte is last byte of 4 byte surrogate pair long charCount = ((long)byteCount + 1); // Non-shortest form would fall back, so get max count from fallback. // So would 11... followed by 11..., so you could fall back every byte if(DecoderFallback.MaxCharCount > 1) { charCount *= DecoderFallback.MaxCharCount; } if(charCount > 0x7fffffff) { #if EXCEPTION_STRINGS throw new ArgumentOutOfRangeException( "byteCount", Environment.GetResourceString( "ArgumentOutOfRange_GetCharCountOverflow" ) ); #else throw new ArgumentOutOfRangeException(); #endif } return (int)charCount; } public override byte[] GetPreamble() { if(emitUTF8Identifier) { // Allocate new array to prevent users from modifying it. return new byte[3] { 0xEF, 0xBB, 0xBF }; } else { return Encoding.emptyByteArray; } } public override bool Equals( Object value ) { UTF8Encoding that = value as UTF8Encoding; if(that != null) { return (emitUTF8Identifier == that.emitUTF8Identifier) && // (isThrowException == that.isThrowException) && // Same as encoder/decoderfallbacks being exception (EncoderFallback.Equals( that.EncoderFallback )) && (DecoderFallback.Equals( that.DecoderFallback )); } return (false); } public override int GetHashCode() { //Not great distribution, but this is relatively unlikely to be used as the key in a hashtable. return this.EncoderFallback.GetHashCode() + this.DecoderFallback.GetHashCode() + UTF8_CODEPAGE + (emitUTF8Identifier ? 1 : 0); } [Serializable] internal class UTF8Encoder : EncoderNLS /*, ISerializable*/ { // We must save a high surrogate value until the next call, looking // for a low surrogate value. internal int surrogateChar; public UTF8Encoder( UTF8Encoding encoding ) : base( encoding ) { // base calls reset } //// // Constructor called by serialization, have to handle deserializing from Everett //// internal UTF8Encoder( SerializationInfo info, StreamingContext context ) //// { //// // Any info? //// if(info == null) //// { //// throw new ArgumentNullException( "info" ); //// } //// //// // Get common info //// this.m_encoding = (Encoding)info.GetValue( "encoding", typeof( Encoding ) ); //// //// // SurrogateChar happens to mean the same thing //// this.surrogateChar = (int)info.GetValue( "surrogateChar", typeof( int ) ); //// //// try //// { //// this.m_fallback = (EncoderFallback)info.GetValue( "m_fallback", typeof( EncoderFallback ) ); //// } //// catch(SerializationException) //// { //// this.m_fallback = null; //// } //// } //// //// // ISerializable implementation, get data for this object //// [SecurityPermissionAttribute( SecurityAction.LinkDemand, Flags = SecurityPermissionFlag.SerializationFormatter )] //// void ISerializable.GetObjectData( SerializationInfo info, StreamingContext context ) //// { //// // Any info? //// if(info == null) throw new ArgumentNullException( "info" ); //// //// // Save Whidbey data //// // Just need Everett maxCharSize (BaseCodePageEncoding) or m_maxByteSize (MLangBaseCodePageEncoding) //// info.AddValue( "encoding", this.m_encoding ); //// info.AddValue( "surrogateChar", this.surrogateChar ); //// //// info.AddValue( "m_fallback", this.m_fallback ); //// //// // Extra stuff for Everett that Whidbey doesn't use //// info.AddValue( "storedSurrogate", this.surrogateChar > 0 ? true : false ); //// info.AddValue( "mustFlush", false ); // Everett doesn't actually use this either, but it accidently serialized it! //// } public override void Reset() { this.surrogateChar = 0; if(m_fallbackBuffer != null) { m_fallbackBuffer.Reset(); } } // Anything left in our encoder? internal override bool HasState { get { return (this.surrogateChar != 0); } } } [Serializable()] internal class UTF8Decoder : DecoderNLS /*, ISerializable*/ { // We'll need to remember the previous information. See the comments around definition // of FinalByte for details. internal int bits; public UTF8Decoder( UTF8Encoding encoding ) : base( encoding ) { // base calls reset } //// // Constructor called by serialization, have to handle deserializing from Everett //// internal UTF8Decoder( SerializationInfo info, StreamingContext context ) //// { //// // Any info? //// if(info == null) throw new ArgumentNullException( "info" ); //// //// // Get common info //// this.m_encoding = (Encoding)info.GetValue( "encoding", typeof( Encoding ) ); //// //// try //// { //// // Get whidbey version of bits //// this.bits = (int)info.GetValue( "wbits", typeof( int ) ); //// this.m_fallback = (DecoderFallback)info.GetValue( "m_fallback", typeof( DecoderFallback ) ); //// } //// catch(SerializationException) //// { //// // Everett calls bits bits instead of wbits, so this is Everett //// this.bits = 0; //// this.m_fallback = null; //// } //// } //// //// // ISerializable implementation, get data for this object //// [SecurityPermissionAttribute( SecurityAction.LinkDemand, Flags = SecurityPermissionFlag.SerializationFormatter )] //// void ISerializable.GetObjectData( SerializationInfo info, StreamingContext context ) //// { //// // Any info? //// if(info == null) throw new ArgumentNullException( "info" ); //// //// // Save new Whidbey data //// info.AddValue( "encoding", this.m_encoding ); //// info.AddValue( "wbits", this.bits ); // Special whidbey bits name //// info.AddValue( "m_fallback", this.m_fallback ); //// //// // Everett has extra stuff, we set it all to 0 in case this deserializes in Everett //// info.AddValue( "bits", (int)0 ); //// info.AddValue( "trailCount", (int)0 ); //// info.AddValue( "isSurrogate", false ); //// info.AddValue( "byteSequence", (int)0 ); //// } public override void Reset() { this.bits = 0; if(m_fallbackBuffer != null) { m_fallbackBuffer.Reset(); } } // Anything left in our decoder? internal override bool HasState { get { return (this.bits != 0); } } } } } ================================================ FILE: Zelig/Zelig/RunTime/Framework/mscorlib/System/Text/UnicodeEncoding.cs ================================================ // ==++== // // Copyright (c) Microsoft Corporation. All rights reserved. // // ==--== // // Don't override IsAlwaysNormalized because it is just a Unicode Transformation and could be confused. // namespace System.Text { using System; using System.Globalization; using System.Runtime.Serialization; using System.Security.Permissions; [Serializable] ////[System.Runtime.InteropServices.ComVisible( true )] public class UnicodeEncoding : Encoding { [OptionalField( VersionAdded = 2 )] internal bool isThrowException = false; internal bool bigEndian = false; internal bool byteOrderMark = true; // Unicode version 2.0 character size in bytes // Why's this _)(*@&#)(*&@#$ thing public !!!!! public const int CharSize = 2; public UnicodeEncoding() : this( false, true ) { } public UnicodeEncoding( bool bigEndian, bool byteOrderMark ) : this( bigEndian, byteOrderMark, false ) { } public UnicodeEncoding( bool bigEndian, bool byteOrderMark, bool throwOnInvalidBytes ) : base( bigEndian ? 1201 : 1200 ) //Set the data item. { this.isThrowException = throwOnInvalidBytes; this.bigEndian = bigEndian; this.byteOrderMark = byteOrderMark; // Encoding's constructor already did this, but it'll be wrong if we're throwing exceptions if(this.isThrowException) { SetDefaultFallbacks(); } } //// #region Serialization //// [OnDeserializing] //// private void OnDeserializing( StreamingContext ctx ) //// { //// // In Everett it is false. Whidbey will overwrite this value. //// isThrowException = false; //// } //// #endregion Serialization internal override void SetDefaultFallbacks() { // For UTF-X encodings, we use a replacement fallback with an empty string if(this.isThrowException) { this.encoderFallback = EncoderFallback.ExceptionFallback; this.decoderFallback = DecoderFallback.ExceptionFallback; } else { this.encoderFallback = new EncoderReplacementFallback( String.Empty ); this.decoderFallback = new DecoderReplacementFallback( String.Empty ); } } // // The following methods are copied from EncodingNLS.cs. // Unfortunately EncodingNLS.cs is internal and we're public, so we have to reimpliment them here. // These should be kept in sync for the following classes: // EncodingNLS, UTF7Encoding, UTF8Encoding, UTF32Encoding, ASCIIEncoding, UnicodeEncoding // // Returns the number of bytes required to encode a range of characters in // a character array. // // All of our public Encodings that don't use EncodingNLS must have this (including EncodingNLS) // So if you fix this, fix the others. Currently those include: // EncodingNLS, UTF7Encoding, UTF8Encoding, UTF32Encoding, ASCIIEncoding, UnicodeEncoding // parent method is safe public override unsafe int GetByteCount( char[] chars, int index, int count ) { // Validate input parameters if(chars == null) { #if EXCEPTION_STRINGS throw new ArgumentNullException( "chars", Environment.GetResourceString( "ArgumentNull_Array" ) ); #else throw new ArgumentNullException(); #endif } if(index < 0 || count < 0) { #if EXCEPTION_STRINGS throw new ArgumentOutOfRangeException( (index < 0 ? "index" : "count"), Environment.GetResourceString( "ArgumentOutOfRange_NeedNonNegNum" ) ); #else throw new ArgumentOutOfRangeException(); #endif } if(chars.Length - index < count) { #if EXCEPTION_STRINGS throw new ArgumentOutOfRangeException( "chars", Environment.GetResourceString( "ArgumentOutOfRange_IndexCountBuffer" ) ); #else throw new ArgumentOutOfRangeException(); #endif } // If no input, return 0, avoid fixed empty array problem if(chars.Length == 0) { return 0; } // Just call the pointer version fixed(char* pChars = chars) { return GetByteCount( pChars + index, count, null ); } } // All of our public Encodings that don't use EncodingNLS must have this (including EncodingNLS) // So if you fix this, fix the others. Currently those include: // EncodingNLS, UTF7Encoding, UTF8Encoding, UTF32Encoding, ASCIIEncoding, UnicodeEncoding // parent method is safe public override unsafe int GetByteCount( String s ) { // Validate input if(s == null) { #if EXCEPTION_STRINGS throw new ArgumentNullException( "s" ); #else throw new ArgumentNullException(); #endif } fixed(char* pChars = s) { return GetByteCount( pChars, s.Length, null ); } } // All of our public Encodings that don't use EncodingNLS must have this (including EncodingNLS) // So if you fix this, fix the others. Currently those include: // EncodingNLS, UTF7Encoding, UTF8Encoding, UTF32Encoding, ASCIIEncoding, UnicodeEncoding [CLSCompliant( false )] //// [System.Runtime.InteropServices.ComVisible( false )] public override unsafe int GetByteCount( char* chars , int count ) { // Validate Parameters if(chars == null) { #if EXCEPTION_STRINGS throw new ArgumentNullException( "chars", Environment.GetResourceString( "ArgumentNull_Array" ) ); #else throw new ArgumentNullException(); #endif } if(count < 0) { #if EXCEPTION_STRINGS throw new ArgumentOutOfRangeException( "count", Environment.GetResourceString( "ArgumentOutOfRange_NeedNonNegNum" ) ); #else throw new ArgumentOutOfRangeException(); #endif } // Call it with empty encoder return GetByteCount( chars, count, null ); } // Parent method is safe. // All of our public Encodings that don't use EncodingNLS must have this (including EncodingNLS) // So if you fix this, fix the others. Currently those include: // EncodingNLS, UTF7Encoding, UTF8Encoding, UTF32Encoding, ASCIIEncoding, UnicodeEncoding public override unsafe int GetBytes( String s , int charIndex , int charCount , byte[] bytes , int byteIndex ) { if(s == null || bytes == null) { #if EXCEPTION_STRINGS throw new ArgumentNullException( (s == null ? "s" : "bytes"), Environment.GetResourceString( "ArgumentNull_Array" ) ); #else throw new ArgumentNullException(); #endif } if(charIndex < 0 || charCount < 0) { #if EXCEPTION_STRINGS throw new ArgumentOutOfRangeException( (charIndex < 0 ? "charIndex" : "charCount"), Environment.GetResourceString( "ArgumentOutOfRange_NeedNonNegNum" ) ); #else throw new ArgumentOutOfRangeException(); #endif } if(s.Length - charIndex < charCount) { #if EXCEPTION_STRINGS throw new ArgumentOutOfRangeException( "s", Environment.GetResourceString( "ArgumentOutOfRange_IndexCount" ) ); #else throw new ArgumentOutOfRangeException(); #endif } if(byteIndex < 0 || byteIndex > bytes.Length) { #if EXCEPTION_STRINGS throw new ArgumentOutOfRangeException( "byteIndex", Environment.GetResourceString( "ArgumentOutOfRange_Index" ) ); #else throw new ArgumentOutOfRangeException(); #endif } int byteCount = bytes.Length - byteIndex; // Fixed doesn't like 0 length arrays. if(bytes.Length == 0) { bytes = new byte[1]; } fixed(char* pChars = s) { fixed(byte* pBytes = bytes) { return GetBytes( pChars + charIndex, charCount, pBytes + byteIndex, byteCount, null ); } } } // Encodes a range of characters in a character array into a range of bytes // in a byte array. An exception occurs if the byte array is not large // enough to hold the complete encoding of the characters. The // GetByteCount method can be used to determine the exact number of // bytes that will be produced for a given range of characters. // Alternatively, the GetMaxByteCount method can be used to // determine the maximum number of bytes that will be produced for a given // number of characters, regardless of the actual character values. // // All of our public Encodings that don't use EncodingNLS must have this (including EncodingNLS) // So if you fix this, fix the others. Currently those include: // EncodingNLS, UTF7Encoding, UTF8Encoding, UTF32Encoding, ASCIIEncoding, UnicodeEncoding // parent method is safe public override unsafe int GetBytes( char[] chars , int charIndex , int charCount , byte[] bytes , int byteIndex ) { // Validate parameters if(chars == null || bytes == null) { #if EXCEPTION_STRINGS throw new ArgumentNullException( (chars == null ? "chars" : "bytes"), Environment.GetResourceString( "ArgumentNull_Array" ) ); #else throw new ArgumentNullException(); #endif } if(charIndex < 0 || charCount < 0) { #if EXCEPTION_STRINGS throw new ArgumentOutOfRangeException( (charIndex < 0 ? "charIndex" : "charCount"), Environment.GetResourceString( "ArgumentOutOfRange_NeedNonNegNum" ) ); #else throw new ArgumentOutOfRangeException(); #endif } if(chars.Length - charIndex < charCount) { #if EXCEPTION_STRINGS throw new ArgumentOutOfRangeException( "chars", Environment.GetResourceString( "ArgumentOutOfRange_IndexCountBuffer" ) ); #else throw new ArgumentOutOfRangeException(); #endif } if(byteIndex < 0 || byteIndex > bytes.Length) { #if EXCEPTION_STRINGS throw new ArgumentOutOfRangeException( "byteIndex", Environment.GetResourceString( "ArgumentOutOfRange_Index" ) ); #else throw new ArgumentOutOfRangeException(); #endif } // If nothing to encode return 0, avoid fixed problem if(chars.Length == 0) { return 0; } // Just call pointer version int byteCount = bytes.Length - byteIndex; // Fixed doesn't like 0 length arrays. if(bytes.Length == 0) { bytes = new byte[1]; } fixed(char* pChars = chars) { fixed(byte* pBytes = bytes) { // Remember that byteCount is # to decode, not size of array. return GetBytes( pChars + charIndex, charCount, pBytes + byteIndex, byteCount, null ); } } } // All of our public Encodings that don't use EncodingNLS must have this (including EncodingNLS) // So if you fix this, fix the others. Currently those include: // EncodingNLS, UTF7Encoding, UTF8Encoding, UTF32Encoding, ASCIIEncoding, UnicodeEncoding [CLSCompliant( false )] //// [System.Runtime.InteropServices.ComVisible( false )] public override unsafe int GetBytes( char* chars , int charCount , byte* bytes , int byteCount ) { // Validate Parameters if(bytes == null || chars == null) { #if EXCEPTION_STRINGS throw new ArgumentNullException( bytes == null ? "bytes" : "chars", Environment.GetResourceString( "ArgumentNull_Array" ) ); #else throw new ArgumentNullException(); #endif } if(charCount < 0 || byteCount < 0) { #if EXCEPTION_STRINGS throw new ArgumentOutOfRangeException( (charCount < 0 ? "charCount" : "byteCount"), Environment.GetResourceString( "ArgumentOutOfRange_NeedNonNegNum" ) ); #else throw new ArgumentOutOfRangeException(); #endif } return GetBytes( chars, charCount, bytes, byteCount, null ); } // Returns the number of characters produced by decoding a range of bytes // in a byte array. // // All of our public Encodings that don't use EncodingNLS must have this (including EncodingNLS) // So if you fix this, fix the others. Currently those include: // EncodingNLS, UTF7Encoding, UTF8Encoding, UTF32Encoding, ASCIIEncoding, UnicodeEncoding // parent method is safe public override unsafe int GetCharCount( byte[] bytes , int index , int count ) { // Validate Parameters if(bytes == null) { #if EXCEPTION_STRINGS throw new ArgumentNullException( "bytes", Environment.GetResourceString( "ArgumentNull_Array" ) ); #else throw new ArgumentNullException(); #endif } if(index < 0 || count < 0) { #if EXCEPTION_STRINGS throw new ArgumentOutOfRangeException( (index < 0 ? "index" : "count"), Environment.GetResourceString( "ArgumentOutOfRange_NeedNonNegNum" ) ); #else throw new ArgumentOutOfRangeException(); #endif } if(bytes.Length - index < count) { #if EXCEPTION_STRINGS throw new ArgumentOutOfRangeException( "bytes", Environment.GetResourceString( "ArgumentOutOfRange_IndexCountBuffer" ) ); #else throw new ArgumentOutOfRangeException(); #endif } // If no input just return 0, fixed doesn't like 0 length arrays if(bytes.Length == 0) { return 0; } // Just call pointer version fixed(byte* pBytes = bytes) { return GetCharCount( pBytes + index, count, null ); } } // All of our public Encodings that don't use EncodingNLS must have this (including EncodingNLS) // So if you fix this, fix the others. Currently those include: // EncodingNLS, UTF7Encoding, UTF8Encoding, UTF32Encoding, ASCIIEncoding, UnicodeEncoding [CLSCompliant( false )] //// [System.Runtime.InteropServices.ComVisible( false )] public override unsafe int GetCharCount( byte* bytes , int count ) { // Validate Parameters if(bytes == null) { #if EXCEPTION_STRINGS throw new ArgumentNullException( "bytes", Environment.GetResourceString( "ArgumentNull_Array" ) ); #else throw new ArgumentNullException(); #endif } if(count < 0) { #if EXCEPTION_STRINGS throw new ArgumentOutOfRangeException( "count", Environment.GetResourceString( "ArgumentOutOfRange_NeedNonNegNum" ) ); #else throw new ArgumentOutOfRangeException(); #endif } return GetCharCount( bytes, count, null ); } // All of our public Encodings that don't use EncodingNLS must have this (including EncodingNLS) // So if you fix this, fix the others. Currently those include: // EncodingNLS, UTF7Encoding, UTF8Encoding, UTF32Encoding, ASCIIEncoding, UnicodeEncoding // parent method is safe public override unsafe int GetChars( byte[] bytes , int byteIndex , int byteCount , char[] chars , int charIndex ) { // Validate Parameters if(bytes == null || chars == null) { #if EXCEPTION_STRINGS throw new ArgumentNullException( bytes == null ? "bytes" : "chars", Environment.GetResourceString( "ArgumentNull_Array" ) ); #else throw new ArgumentNullException(); #endif } if(byteIndex < 0 || byteCount < 0) { #if EXCEPTION_STRINGS throw new ArgumentOutOfRangeException( (byteIndex < 0 ? "byteIndex" : "byteCount"), Environment.GetResourceString( "ArgumentOutOfRange_NeedNonNegNum" ) ); #else throw new ArgumentOutOfRangeException(); #endif } if(bytes.Length - byteIndex < byteCount) { #if EXCEPTION_STRINGS throw new ArgumentOutOfRangeException( "bytes", Environment.GetResourceString( "ArgumentOutOfRange_IndexCountBuffer" ) ); #else throw new ArgumentOutOfRangeException(); #endif } if(charIndex < 0 || charIndex > chars.Length) { #if EXCEPTION_STRINGS throw new ArgumentOutOfRangeException( "charIndex", Environment.GetResourceString( "ArgumentOutOfRange_Index" ) ); #else throw new ArgumentOutOfRangeException(); #endif } // If no input, return 0 & avoid fixed problem if(bytes.Length == 0) { return 0; } // Just call pointer version int charCount = chars.Length - charIndex; // Fixed doesn't like 0 length arrays. if(chars.Length == 0) { chars = new char[1]; } fixed(byte* pBytes = bytes) { fixed(char* pChars = chars) { // Remember that charCount is # to decode, not size of array return GetChars( pBytes + byteIndex, byteCount, pChars + charIndex, charCount, null ); } } } // All of our public Encodings that don't use EncodingNLS must have this (including EncodingNLS) // So if you fix this, fix the others. Currently those include: // EncodingNLS, UTF7Encoding, UTF8Encoding, UTF32Encoding, ASCIIEncoding, UnicodeEncoding [CLSCompliant( false )] //// [System.Runtime.InteropServices.ComVisible( false )] public unsafe override int GetChars( byte* bytes, int byteCount, char* chars, int charCount ) { // Validate Parameters if(bytes == null || chars == null) { #if EXCEPTION_STRINGS throw new ArgumentNullException( bytes == null ? "bytes" : "chars", Environment.GetResourceString( "ArgumentNull_Array" ) ); #else throw new ArgumentNullException(); #endif } if(charCount < 0 || byteCount < 0) { #if EXCEPTION_STRINGS throw new ArgumentOutOfRangeException( (charCount < 0 ? "charCount" : "byteCount"), Environment.GetResourceString( "ArgumentOutOfRange_NeedNonNegNum" ) ); #else throw new ArgumentOutOfRangeException(); #endif } return GetChars( bytes, byteCount, chars, charCount, null ); } // Returns a string containing the decoded representation of a range of // bytes in a byte array. // // All of our public Encodings that don't use EncodingNLS must have this (including EncodingNLS) // So if you fix this, fix the others. Currently those include: // EncodingNLS, UTF7Encoding, UTF8Encoding, UTF32Encoding, ASCIIEncoding, UnicodeEncoding // parent method is safe //// [System.Runtime.InteropServices.ComVisible( false )] public override unsafe String GetString( byte[] bytes, int index, int count ) { // Validate Parameters if(bytes == null) { #if EXCEPTION_STRINGS throw new ArgumentNullException( "bytes", Environment.GetResourceString( "ArgumentNull_Array" ) ); #else throw new ArgumentNullException(); #endif } if(index < 0 || count < 0) { #if EXCEPTION_STRINGS throw new ArgumentOutOfRangeException( (index < 0 ? "index" : "count"), Environment.GetResourceString( "ArgumentOutOfRange_NeedNonNegNum" ) ); #else throw new ArgumentOutOfRangeException(); #endif } if(bytes.Length - index < count) { #if EXCEPTION_STRINGS throw new ArgumentOutOfRangeException( "bytes", Environment.GetResourceString( "ArgumentOutOfRange_IndexCountBuffer" ) ); #else throw new ArgumentOutOfRangeException(); #endif } // Avoid problems with empty input buffer if(bytes.Length == 0) { return String.Empty; } fixed(byte* pBytes = bytes) { return String.CreateStringFromEncoding( pBytes + index, count, this ); } } // // End of standard methods copied from EncodingNLS.cs // internal override unsafe int GetByteCount( char* chars , int count , EncoderNLS encoder ) { BCLDebug.Assert( chars != null, "[UnicodeEncoding.GetByteCount]chars!=null" ); BCLDebug.Assert( count >= 0, "[UnicodeEncoding.GetByteCount]count >=0" ); // Start by assuming each char gets 2 bytes int byteCount = count << 1; // Check for overflow in byteCount // (If they were all invalid chars, this would actually be wrong, // but that's a ridiculously large # so we're not concerned about that case) if(byteCount < 0) { #if EXCEPTION_STRINGS throw new ArgumentOutOfRangeException( "count", Environment.GetResourceString( "ArgumentOutOfRange_GetByteCountOverflow" ) ); #else throw new ArgumentOutOfRangeException(); #endif } char* charStart = chars; char* charEnd = chars + count; char charLeftOver = (char)0; bool wasHereBefore = false; // Need -1 to check 2 at a time. If we have an even #, longChars will go // from longEnd - 1/2 long to longEnd + 1/2 long. If we're odd, longChars // will go from longEnd - 1 long to longEnd. (Might not get to use this) ulong* longEnd = (ulong*)(charEnd - 3); // For fallback we may need a fallback buffer EncoderFallbackBuffer fallbackBuffer = null; if(encoder != null) { charLeftOver = encoder.charLeftOver; // Assume extra bytes to encode charLeftOver if it existed if(charLeftOver > 0) { byteCount += 2; } // We mustn't have left over fallback data when counting if(encoder.InternalHasFallbackBuffer) { if((fallbackBuffer = encoder.FallbackBuffer).Remaining > 0) { #if EXCEPTION_STRINGS throw new ArgumentException( Environment.GetResourceString( "Argument_EncoderFallbackNotEmpty", this.EncodingName, encoder.Fallback.GetType() ) ); #else throw new ArgumentException(); #endif } // Set our internal fallback interesting things. fallbackBuffer.InternalInitialize( charStart, charEnd, encoder, false ); } } char ch; TryAgain: while(((ch = (fallbackBuffer == null) ? (char)0 : fallbackBuffer.InternalGetNextChar()) != 0) || chars < charEnd) { // First unwind any fallback if(ch == 0) { // No fallback, maybe we can do it fast #if !NO_FAST_UNICODE_LOOP #if BIGENDIAN // If endianess is backwards then each pair of bytes would be backwards. if ( bigEndian && #else if(!bigEndian && #endif // BIGENDIAN #if WIN64 // 64 bit CPU needs to be long aligned for this to work. charLeftOver == 0 && (unchecked((long)chars) & 7) == 0) #else charLeftOver == 0 && (unchecked( (int)chars ) & 3) == 0) #endif { // Need new char* so we can check 4 at a time ulong* longChars = (ulong*)chars; while(longChars < longEnd) { if(((ulong)(0x8000800080008000) & *longChars) != 0) { // See if all 4 of those are bad... // Surrogate pairs are "backwards" for little endian machines read in as one // Mask off surrogate bits ulong uTemp = (0xd800d800d800d800 & *longChars) ^ 0xd800d800d800d800; // Check each of the 4 chars. 0 for those 16 bits means it was a surrogate if((uTemp & 0xFFFF000000000000) == 0 || (uTemp & 0x0000FFFF00000000) == 0 || (uTemp & 0x00000000FFFF0000) == 0 || (uTemp & 0x000000000000FFFF) == 0) { // Does it happen to have 4 good surrogates? #if BIGENDIAN if (((0xdc00dc00dc00dc00 & *longChars) ^ 0xd800dc00d800dc00) != 0) #else if(((0xdc00dc00dc00dc00 & *longChars) ^ 0xdc00d800dc00d800) != 0) #endif { // If it wasn't 4 good surrogates then fall through to slow loop break; } } // It was a good value, we'll use these 4 characters } // We already counted these four chars, go to next long. longChars++; } chars = (char*)longChars; if(chars >= charEnd) { break; } } #endif // !NO_FAST_UNICODE_LOOP // No fallback, just get next char ch = *chars; chars++; } else { // We weren't preallocating fallback space. byteCount += 2; } // Check for high or low surrogates if(ch >= 0xd800 && ch <= 0xdfff) { // Was it a high surrogate? if(ch <= 0xdbff) { // Its a high surrogate, if we already had a high surrogate do its fallback if(charLeftOver > 0) { // Unwind the current character, this should be safe because we // don't have leftover data in the fallback, so chars must have // advanced already. BCLDebug.Assert( chars > charStart, "[UnicodeEncoding.GetByteCount]Expected chars to have advanced in unexpected high surrogate" ); chars--; // If previous high surrogate deallocate 2 bytes byteCount -= 2; // Fallback the previous surrogate // Need to initialize fallback buffer? if(fallbackBuffer == null) { if(encoder == null) { fallbackBuffer = this.encoderFallback.CreateFallbackBuffer(); } else { fallbackBuffer = encoder.FallbackBuffer; } // Set our internal fallback interesting things. fallbackBuffer.InternalInitialize( charStart, charEnd, encoder, false ); } fallbackBuffer.InternalFallback( charLeftOver, ref chars ); // Now no high surrogate left over charLeftOver = (char)0; continue; } // Remember this high surrogate charLeftOver = ch; continue; } // Its a low surrogate if(charLeftOver == 0) { // Expected a previous high surrogate. // Don't count this one (we'll count its fallback if necessary) byteCount -= 2; // fallback this one // Need to initialize fallback buffer? if(fallbackBuffer == null) { if(encoder == null) { fallbackBuffer = this.encoderFallback.CreateFallbackBuffer(); } else { fallbackBuffer = encoder.FallbackBuffer; } // Set our internal fallback interesting things. fallbackBuffer.InternalInitialize( charStart, charEnd, encoder, false ); } fallbackBuffer.InternalFallback( ch, ref chars ); continue; } // Valid surrogate pair, add our charLeftOver charLeftOver = (char)0; continue; } else if(charLeftOver > 0) { // Expected a low surrogate, but this char is normal // Rewind the current character, fallback previous character. // this should be safe because we don't have leftover data in the // fallback, so chars must have advanced already. BCLDebug.Assert( chars > charStart, "[UnicodeEncoding.GetByteCount]Expected chars to have advanced when expected low surrogate" ); chars--; // fallback previous chars // Need to initialize fallback buffer? if(fallbackBuffer == null) { if(encoder == null) { fallbackBuffer = this.encoderFallback.CreateFallbackBuffer(); } else { fallbackBuffer = encoder.FallbackBuffer; } // Set our internal fallback interesting things. fallbackBuffer.InternalInitialize( charStart, charEnd, encoder, false ); } fallbackBuffer.InternalFallback( charLeftOver, ref chars ); // Ignore charLeftOver or throw byteCount -= 2; charLeftOver = (char)0; continue; } // Ok we had something to add (already counted) } // Don't allocate space for left over char if(charLeftOver > 0) { byteCount -= 2; // If we have to flush, stick it in fallback and try again if(encoder == null || encoder.MustFlush) { if(wasHereBefore) { // Throw it, using our complete character #if EXCEPTION_STRINGS throw new ArgumentException( Environment.GetResourceString( "Argument_RecursiveFallback", charLeftOver ), "chars" ); #else throw new ArgumentException(); #endif } else { // Need to initialize fallback buffer? if(fallbackBuffer == null) { if(encoder == null) { fallbackBuffer = this.encoderFallback.CreateFallbackBuffer(); } else { fallbackBuffer = encoder.FallbackBuffer; } // Set our internal fallback interesting things. fallbackBuffer.InternalInitialize( charStart, charEnd, encoder, false ); } fallbackBuffer.InternalFallback( charLeftOver, ref chars ); charLeftOver = (char)0; wasHereBefore = true; goto TryAgain; } } } // Shouldn't have anything in fallback buffer for GetByteCount // (don't have to check m_throwOnOverflow for count) BCLDebug.Assert( fallbackBuffer == null || fallbackBuffer.Remaining == 0, "[UnicodeEncoding.GetByteCount]Expected empty fallback buffer at end" ); // Don't remember fallbackBuffer.encoder for counting return byteCount; } internal override unsafe int GetBytes( char* chars , int charCount , byte* bytes , int byteCount , EncoderNLS encoder ) { BCLDebug.Assert( chars != null, "[UnicodeEncoding.GetBytes]chars!=null" ); BCLDebug.Assert( byteCount >= 0, "[UnicodeEncoding.GetBytes]byteCount >=0" ); BCLDebug.Assert( charCount >= 0, "[UnicodeEncoding.GetBytes]charCount >=0" ); BCLDebug.Assert( bytes != null, "[UnicodeEncoding.GetBytes]bytes!=null" ); char charLeftOver = (char)0; char ch; bool wasHereBefore = false; byte* byteEnd = bytes + byteCount; char* charEnd = chars + charCount; byte* byteStart = bytes; char* charStart = chars; // For fallback we may need a fallback buffer EncoderFallbackBuffer fallbackBuffer = null; // Get our encoder, but don't clear it yet. if(encoder != null) { charLeftOver = encoder.charLeftOver; // We mustn't have left over fallback data when counting if(encoder.InternalHasFallbackBuffer) { // We always need the fallback buffer in get bytes so we can flush any remaining ones if necessary fallbackBuffer = encoder.FallbackBuffer; if(fallbackBuffer.Remaining > 0 && encoder.m_throwOnOverflow) { #if EXCEPTION_STRINGS throw new ArgumentException( Environment.GetResourceString( "Argument_EncoderFallbackNotEmpty", this.EncodingName, encoder.Fallback.GetType() ) ); #else throw new ArgumentException(); #endif } // Set our internal fallback interesting things. fallbackBuffer.InternalInitialize( charStart, charEnd, encoder, false ); } } TryAgain: while(((ch = (fallbackBuffer == null) ? (char)0 : fallbackBuffer.InternalGetNextChar()) != 0) || chars < charEnd) { // First unwind any fallback if(ch == 0) { // No fallback, maybe we can do it fast #if !NO_FAST_UNICODE_LOOP #if BIGENDIAN // If endianess is backwards then each pair of bytes would be backwards. if ( bigEndian && #else if(!bigEndian && #endif // BIGENDIAN #if WIN64 // 64 bit CPU needs to be long aligned for this to work, 32 bit CPU needs to be 32 bit aligned (unchecked((long)chars) & 7) == 0 && (unchecked((long)bytes) & 7) == 0 && #else (unchecked( (int)chars ) & 3) == 0 && (unchecked( (int)bytes ) & 3) == 0 && #endif // WIN64 charLeftOver == 0) { // Need -1 to check 2 at a time. If we have an even #, longChars will go // from longEnd - 1/2 long to longEnd + 1/2 long. If we're odd, longChars // will go from longEnd - 1 long to longEnd. (Might not get to use this) // We can only go iCount units (limited by shorter of char or byte buffers. ulong* longEnd = (ulong*)(chars - 3 + (((byteEnd - bytes) >> 1 < charEnd - chars) ? (byteEnd - bytes) >> 1 : charEnd - chars)); // Need new char* so we can check 4 at a time ulong* longChars = (ulong*)chars; ulong* longBytes = (ulong*)bytes; while(longChars < longEnd) { if(((ulong)(0x8000800080008000) & *longChars) != 0) { // See if all 4 of those are bad... // Surrogate pairs are "backwards" for little endian machines read in as one // Mask off surrogate bits ulong uTemp = (0xd800d800d800d800 & *longChars) ^ 0xd800d800d800d800; // Check each of the 4 chars. 0 for those 16 bits means it was a surrogate if((uTemp & 0xFFFF000000000000) == 0 || (uTemp & 0x0000FFFF00000000) == 0 || (uTemp & 0x00000000FFFF0000) == 0 || (uTemp & 0x000000000000FFFF) == 0) { // Does it happen to have 4 good surrogates? #if BIGENDIAN if (((0xdc00dc00dc00dc00 & *longChars) ^ 0xd800dc00d800dc00) != 0) #else if(((0xdc00dc00dc00dc00 & *longChars) ^ 0xdc00d800dc00d800) != 0) #endif // BIGENDIAN { // If it wasn't 4 good surrogates then fall through to slow loop break; } // Use these 4 lucky ordered surrogate pairs. } // Use these 4 high, but not surrogates } // We can use these 4 chars. *longBytes = *longChars; longChars++; longBytes++; } chars = (char*)longChars; bytes = (byte*)longBytes; if(chars >= charEnd) { break; } } // Not aligned, but maybe we can still be somewhat faster // Also somehow this optimizes the above loop? It seems to cause something above // to get enregistered, but I haven't figured out how to make that happen without this loop. else if((charLeftOver == 0) && #if BIGENDIAN bigEndian && #else !bigEndian && #endif // BIGENDIAN #if WIN64 (unchecked((long)chars) & 7) != (unchecked((long)bytes) & 7) && // Only do this if chars & bytes are out of line, otherwise faster loop'll be faster next time #else (unchecked( (int)chars ) & 3) != (unchecked( (int)bytes ) & 3) && // Only do this if chars & bytes are out of line, otherwise faster loop'll be faster next time #endif // WIN64 (unchecked( (int)(bytes) ) & 1) == 0) { // # to use long iCount = ((byteEnd - bytes) >> 1 < charEnd - chars) ? (byteEnd - bytes) >> 1 : charEnd - chars; // Need new char* char* charOut = ((char*)bytes); // a char* for our output char* tempEnd = chars + iCount - 1; // Our end pointer while(chars < tempEnd) { if(*chars >= (char)0xd800 && *chars <= (char)0xdfff) { // break for fallback for low surrogate if(*chars >= 0xdc00) { break; } // break if next one's not a low surrogate (will do fallback) if(*(chars + 1) < 0xdc00 || *(chars + 1) > 0xdfff) { break; } // They both exist, use them } // If 2nd char is surrogate & this one isn't then only add one else if(*(chars + 1) >= (char)0xd800 && *(chars + 1) <= 0xdfff) { *charOut = *chars; charOut++; chars++; continue; } *charOut = *chars; *(charOut + 1) = *(chars + 1); charOut += 2; chars += 2; } bytes = (byte*)charOut; if(chars >= charEnd) { break; } } #endif // !NO_FAST_UNICODE_LOOP // No fallback, just get next char ch = *chars; chars++; } // Check for high or low surrogates if(ch >= 0xd800 && ch <= 0xdfff) { // Was it a high surrogate? if(ch <= 0xdbff) { // Its a high surrogate, see if we already had a high surrogate if(charLeftOver > 0) { // Unwind the current character, this should be safe because we // don't have leftover data in the fallback, so chars must have // advanced already. BCLDebug.Assert( chars > charStart, "[UnicodeEncoding.GetBytes]Expected chars to have advanced in unexpected high surrogate" ); chars--; // Fallback the previous surrogate // Might need to create our fallback buffer if(fallbackBuffer == null) { if(encoder == null) { fallbackBuffer = this.encoderFallback.CreateFallbackBuffer(); } else { fallbackBuffer = encoder.FallbackBuffer; } // Set our internal fallback interesting things. fallbackBuffer.InternalInitialize( charStart, charEnd, encoder, true ); } fallbackBuffer.InternalFallback( charLeftOver, ref chars ); charLeftOver = (char)0; continue; } // Remember this high surrogate charLeftOver = ch; continue; } // Its a low surrogate if(charLeftOver == 0) { // We'll fall back this one // Might need to create our fallback buffer if(fallbackBuffer == null) { if(encoder == null) { fallbackBuffer = this.encoderFallback.CreateFallbackBuffer(); } else { fallbackBuffer = encoder.FallbackBuffer; } // Set our internal fallback interesting things. fallbackBuffer.InternalInitialize( charStart, charEnd, encoder, true ); } fallbackBuffer.InternalFallback( ch, ref chars ); continue; } // Valid surrogate pair, add our charLeftOver if(bytes + 3 >= byteEnd) { // Not enough room to add this surrogate pair if(fallbackBuffer != null && fallbackBuffer.bFallingBack) { // These must have both been from the fallbacks. // Both of these MUST have been from a fallback because if the 1st wasn't // from a fallback, then a high surrogate followed by an illegal char // would've caused the high surrogate to fall back. If a high surrogate // fell back, then it was consumed and both chars came from the fallback. fallbackBuffer.MovePrevious(); // Didn't use either fallback surrogate fallbackBuffer.MovePrevious(); } else { // If we don't have enough room, then either we should've advanced a while // or we should have bytes==byteStart and throw below BCLDebug.Assert( chars > charStart + 1 || bytes == byteStart,"[UnicodeEncoding.GetBytes]Expected chars to have when no room to add surrogate pair" ); chars -= 2; // Didn't use either surrogate } ThrowBytesOverflow( encoder, bytes == byteStart ); // Throw maybe (if no bytes written) charLeftOver = (char)0; // we'll retry it later break; // Didn't throw, but stop 'til next time. } if(bigEndian) { *(bytes++) = (byte)(charLeftOver >> 8); *(bytes++) = (byte)charLeftOver; } else { *(bytes++) = (byte)charLeftOver; *(bytes++) = (byte)(charLeftOver >> 8); } charLeftOver = (char)0; } else if(charLeftOver > 0) { // Expected a low surrogate, but this char is normal // Rewind the current character, fallback previous character. // this should be safe because we don't have leftover data in the // fallback, so chars must have advanced already. BCLDebug.Assert( chars > charStart, "[UnicodeEncoding.GetBytes]Expected chars to have advanced after expecting low surrogate" ); chars--; // fallback previous chars // Might need to create our fallback buffer if(fallbackBuffer == null) { if(encoder == null) { fallbackBuffer = this.encoderFallback.CreateFallbackBuffer(); } else { fallbackBuffer = encoder.FallbackBuffer; } // Set our internal fallback interesting things. fallbackBuffer.InternalInitialize( charStart, charEnd, encoder, true ); } fallbackBuffer.InternalFallback( charLeftOver, ref chars ); // Ignore charLeftOver or throw charLeftOver = (char)0; continue; } // Ok, we have a char to add if(bytes + 1 >= byteEnd) { // Couldn't add this char if(fallbackBuffer != null && fallbackBuffer.bFallingBack) { fallbackBuffer.MovePrevious(); // Not using this fallback char } else { // Lonely charLeftOver (from previous call) would've been caught up above, // so this must be a case where we've already read an input char. BCLDebug.Assert( chars > charStart, "[UnicodeEncoding.GetBytes]Expected chars to have advanced for failed fallback" ); chars--; // Not using this char } ThrowBytesOverflow( encoder, bytes == byteStart ); // Throw maybe (if no bytes written) break; // didn't throw, just stop } if(bigEndian) { *(bytes++) = (byte)(ch >> 8); *(bytes++) = (byte)ch; } else { *(bytes++) = (byte)ch; *(bytes++) = (byte)(ch >> 8); } } // Don't allocate space for left over char if(charLeftOver > 0) { // If we aren't flushing we need to fall this back if(encoder == null || encoder.MustFlush) { if(wasHereBefore) { // Throw it, using our complete character #if EXCEPTION_STRINGS throw new ArgumentException( Environment.GetResourceString( "Argument_RecursiveFallback", charLeftOver ), "chars" ); #else throw new ArgumentException(); #endif } else { // If we have to flush, stick it in fallback and try again // Might need to create our fallback buffer if(fallbackBuffer == null) { if(encoder == null) { fallbackBuffer = this.encoderFallback.CreateFallbackBuffer(); } else { fallbackBuffer = encoder.FallbackBuffer; } // Set our internal fallback interesting things. fallbackBuffer.InternalInitialize( charStart, charEnd, encoder, true ); } // If we're not flushing, this'll remember the left over character. fallbackBuffer.InternalFallback( charLeftOver, ref chars ); charLeftOver = (char)0; wasHereBefore = true; goto TryAgain; } } } // Not flushing, remember it in the encoder if(encoder != null) { encoder.charLeftOver = charLeftOver; encoder.m_charsUsed = (int)(chars - charStart); } // Remember charLeftOver if we must, or clear it if we're flushing // (charLeftOver should be 0 if we're flushing) BCLDebug.Assert( (encoder != null && !encoder.MustFlush) || charLeftOver == (char)0, "[UnicodeEncoding.GetBytes] Expected no left over characters if flushing" ); BCLDebug.Assert( fallbackBuffer == null || fallbackBuffer.Remaining == 0 || encoder == null || !encoder.m_throwOnOverflow, "[UnicodeEncoding.GetBytes]Expected empty fallback buffer if not converting" ); // We used to copy it fast, but this doesn't check for surrogates // System.IO.__UnmanagedMemoryStream.memcpyimpl(bytes, (byte*)chars, usedByteCount); return (int)(bytes - byteStart); } internal override unsafe int GetCharCount( byte* bytes , int count , DecoderNLS baseDecoder ) { BCLDebug.Assert( bytes != null, "[UnicodeEncoding.GetCharCount]bytes!=null" ); BCLDebug.Assert( count >= 0, "[UnicodeEncoding.GetCharCount]count >=0" ); UnicodeEncoding.Decoder decoder = (UnicodeEncoding.Decoder)baseDecoder; byte* byteEnd = bytes + count; byte* byteStart = bytes; // Need last vars int lastByte = -1; char lastChar = (char)0; // Start by assuming same # of chars as bytes int charCount = count >> 1; // Need -1 to check 2 at a time. If we have an even #, longBytes will go // from longEnd - 1/2 long to longEnd + 1/2 long. If we're odd, longBytes // will go from longEnd - 1 long to longEnd. (Might not get to use this) ulong* longEnd = (ulong*)(byteEnd - 7); // For fallback we may need a fallback buffer DecoderFallbackBuffer fallbackBuffer = null; if(decoder != null) { lastByte = decoder.lastByte; lastChar = decoder.lastChar; // Assume extra char if last char was around if(lastChar > 0) { charCount++; } // Assume extra char if extra last byte makes up odd # of input bytes if(lastByte >= 0 && (count & 1) == 1) { charCount++; } // Shouldn't have anything in fallback buffer for GetCharCount // (don't have to check m_throwOnOverflow for count) BCLDebug.Assert( !decoder.InternalHasFallbackBuffer || decoder.FallbackBuffer.Remaining == 0, "[UnicodeEncoding.GetCharCount]Expected empty fallback buffer at start" ); } while(bytes < byteEnd) { // If we're aligned then maybe we can do it fast // This'll hurt if we're unaligned because we'll always test but never be aligned #if !NO_FAST_UNICODE_LOOP #if BIGENDIAN if (bigEndian && #else // BIGENDIAN if(!bigEndian && #endif // BIGENDIAN #if WIN64 // win64 has to be long aligned (unchecked((long)bytes) & 7) == 0 && #else (unchecked( (int)bytes ) & 3) == 0 && #endif // WIN64 lastByte == -1 && lastChar == 0) { // Need new char* so we can check 4 at a time ulong* longBytes = (ulong*)bytes; while(longBytes < longEnd) { if(((ulong)(0x8000800080008000) & *longBytes) != 0) { // See if all 4 of those are bad... // Surrogate pairs are "backwards" for little endian machines read in as one // Mask off surrogate bits ulong uTemp = (0xd800d800d800d800 & *longBytes) ^ 0xd800d800d800d800; // Check each of the 4 chars. 0 for those 16 bits means it was a surrogate if((uTemp & 0xFFFF000000000000) == 0 || (uTemp & 0x0000FFFF00000000) == 0 || (uTemp & 0x00000000FFFF0000) == 0 || (uTemp & 0x000000000000FFFF) == 0) { // Does it happen to have 4 good surrogates? #if BIGENDIAN if (((0xdc00dc00dc00dc00 & *longBytes) ^ 0xd800dc00d800dc00) != 0) #else if(((0xdc00dc00dc00dc00 & *longBytes) ^ 0xdc00d800dc00d800) != 0) #endif // BIGENDIAN { // If it wasn't 4 good surrogates then fall through to slow loop break; } // Use these 4 lucky ordered surrogate pairs. } // Use these 4 high, but not surrogates } // We can use these 4 chars. longBytes++; } bytes = (byte*)longBytes; if(bytes >= byteEnd) { break; } } #endif // !NO_FAST_UNICODE_LOOP // Get 1st byte if(lastByte < 0) { lastByte = *bytes++; if(bytes >= byteEnd) break; } // Get full char char ch; if(bigEndian) { ch = (char)(lastByte << 8 | *(bytes++)); } else { ch = (char)(*(bytes++) << 8 | lastByte); } lastByte = -1; // See if the char's valid if(ch >= 0xd800 && ch <= 0xdfff) { // Was it a high surrogate? if(ch <= 0xdbff) { // Its a high surrogate, if we had one then do fallback for previous one if(lastChar > 0) { // Ignore previous bad high surrogate charCount--; // Get fallback for previous high surrogate // Note we have to reconstruct bytes because some may have been in decoder byte[] byteBuffer = null; if(bigEndian) { byteBuffer = new byte[] { unchecked( (byte)(lastChar >> 8) ), unchecked( (byte)lastChar ) }; } else { byteBuffer = new byte[] { unchecked( (byte)lastChar ), unchecked( (byte)(lastChar >> 8) ) }; } if(fallbackBuffer == null) { if(decoder == null) { fallbackBuffer = this.decoderFallback.CreateFallbackBuffer(); } else { fallbackBuffer = decoder.FallbackBuffer; } // Set our internal fallback interesting things. fallbackBuffer.InternalInitialize( byteStart, null ); } // Get fallback. charCount += fallbackBuffer.InternalFallback( byteBuffer, bytes ); } // Ignore the last one which fell back already, // and remember the new high surrogate lastChar = ch; continue; } // Its a low surrogate if(lastChar == 0) { // Expected a previous high surrogate charCount--; // Get fallback for this low surrogate // Note we have to reconstruct bytes because some may have been in decoder byte[] byteBuffer = null; if(bigEndian) { byteBuffer = new byte[] { unchecked( (byte)(ch >> 8) ), unchecked( (byte)ch ) }; } else { byteBuffer = new byte[] { unchecked( (byte)ch ), unchecked( (byte)(ch >> 8) ) }; } if(fallbackBuffer == null) { if(decoder == null) { fallbackBuffer = this.decoderFallback.CreateFallbackBuffer(); } else { fallbackBuffer = decoder.FallbackBuffer; } // Set our internal fallback interesting things. fallbackBuffer.InternalInitialize( byteStart, null ); } charCount += fallbackBuffer.InternalFallback( byteBuffer, bytes ); // Ignore this one (we already did its fallback) continue; } // Valid surrogate pair, already counted. lastChar = (char)0; } else if(lastChar > 0) { // Had a high surrogate, expected a low surrogate // Uncount the last high surrogate charCount--; // fall back the high surrogate. byte[] byteBuffer = null; if(bigEndian) { byteBuffer = new byte[] { unchecked( (byte)(lastChar >> 8) ), unchecked( (byte)lastChar ) }; } else { byteBuffer = new byte[] { unchecked( (byte)lastChar ), unchecked( (byte)(lastChar >> 8) ) }; } if(fallbackBuffer == null) { if(decoder == null) { fallbackBuffer = this.decoderFallback.CreateFallbackBuffer(); } else { fallbackBuffer = decoder.FallbackBuffer; } // Set our internal fallback interesting things. fallbackBuffer.InternalInitialize( byteStart, null ); } // Already subtracted high surrogate charCount += fallbackBuffer.InternalFallback( byteBuffer, bytes ); // Not left over now, clear previous high surrogate and continue to add current char lastChar = (char)0; } // Valid char, already counted } // Extra space if we can't use decoder if(decoder == null || decoder.MustFlush) { if(lastChar > 0) { // No hanging high surrogates allowed, do fallback and remove count for it charCount--; byte[] byteBuffer = null; if(bigEndian) { byteBuffer = new byte[] { unchecked( (byte)(lastChar >> 8) ), unchecked( (byte)lastChar ) }; } else { byteBuffer = new byte[] { unchecked( (byte)lastChar ), unchecked( (byte)(lastChar >> 8) ) }; } if(fallbackBuffer == null) { if(decoder == null) { fallbackBuffer = this.decoderFallback.CreateFallbackBuffer(); } else { fallbackBuffer = decoder.FallbackBuffer; } // Set our internal fallback interesting things. fallbackBuffer.InternalInitialize( byteStart, null ); } charCount += fallbackBuffer.InternalFallback( byteBuffer, bytes ); lastChar = (char)0; } if(lastByte >= 0) { if(fallbackBuffer == null) { if(decoder == null) { fallbackBuffer = this.decoderFallback.CreateFallbackBuffer(); } else { fallbackBuffer = decoder.FallbackBuffer; } // Set our internal fallback interesting things. fallbackBuffer.InternalInitialize( byteStart, null ); } // No hanging odd bytes allowed if must flush charCount += fallbackBuffer.InternalFallback( new byte[] { unchecked( (byte)lastByte ) }, bytes ); lastByte = -1; } } // If we had a high surrogate left over, we can't count it if(lastChar > 0) { charCount--; } // Shouldn't have anything in fallback buffer for GetCharCount // (don't have to check m_throwOnOverflow for count) BCLDebug.Assert( fallbackBuffer == null || fallbackBuffer.Remaining == 0, "[UnicodeEncoding.GetCharCount]Expected empty fallback buffer at end" ); return charCount; } internal override unsafe int GetChars( byte* bytes , int byteCount , char* chars , int charCount , DecoderNLS baseDecoder ) { BCLDebug.Assert( chars != null, "[UnicodeEncoding.GetChars]chars!=null" ); BCLDebug.Assert( byteCount >= 0, "[UnicodeEncoding.GetChars]byteCount >=0" ); BCLDebug.Assert( charCount >= 0, "[UnicodeEncoding.GetChars]charCount >=0" ); BCLDebug.Assert( bytes != null, "[UnicodeEncoding.GetChars]bytes!=null" ); UnicodeEncoding.Decoder decoder = (UnicodeEncoding.Decoder)baseDecoder; // Need last vars int lastByte = -1; char lastChar = (char)0; // Get our decoder (but don't clear it yet) if(decoder != null) { lastByte = decoder.lastByte; lastChar = decoder.lastChar; // Shouldn't have anything in fallback buffer for GetChars // (don't have to check m_throwOnOverflow for chars) BCLDebug.Assert( !decoder.InternalHasFallbackBuffer || decoder.FallbackBuffer.Remaining == 0, "[UnicodeEncoding.GetChars]Expected empty fallback buffer at start" ); } // For fallback we may need a fallback buffer DecoderFallbackBuffer fallbackBuffer = null; byte* byteEnd = bytes + byteCount; char* charEnd = chars + charCount; byte* byteStart = bytes; char* charStart = chars; while(bytes < byteEnd) { // If we're aligned then maybe we can do it fast // This'll hurt if we're unaligned because we'll always test but never be aligned #if !NO_FAST_UNICODE_LOOP #if BIGENDIAN if (bigEndian && #else // BIGENDIAN if(!bigEndian && #endif // BIGENDIAN #if WIN64 // win64 has to be long aligned (unchecked((long)chars) & 7) == 0 && (unchecked((long)bytes) & 7) == 0 && #else (unchecked( (int)chars ) & 3) == 0 && (unchecked( (int)bytes ) & 3) == 0 && #endif // WIN64 lastByte == -1 && lastChar == 0) { // Need -1 to check 2 at a time. If we have an even #, longChars will go // from longEnd - 1/2 long to longEnd + 1/2 long. If we're odd, longChars // will go from longEnd - 1 long to longEnd. (Might not get to use this) // We can only go iCount units (limited by shorter of char or byte buffers. ulong* longEnd = (ulong*)(bytes - 7 + (((byteEnd - bytes) >> 1 < charEnd - chars) ? (byteEnd - bytes) : (charEnd - chars) << 1)); // Need new char* so we can check 4 at a time ulong* longBytes = (ulong*)bytes; ulong* longChars = (ulong*)chars; while(longBytes < longEnd) { if(((ulong)(0x8000800080008000) & *longBytes) != 0) { // See if all 4 of those are bad... // Surrogate pairs are "backwards" for little endian machines read in as one // Mask off surrogate bits ulong uTemp = (0xd800d800d800d800 & *longBytes) ^ 0xd800d800d800d800; // Check each of the 4 chars. 0 for those 16 bits means it was a surrogate if((uTemp & 0xFFFF000000000000) == 0 || (uTemp & 0x0000FFFF00000000) == 0 || (uTemp & 0x00000000FFFF0000) == 0 || (uTemp & 0x000000000000FFFF) == 0) { // Does it happen to have 4 good surrogates? #if BIGENDIAN if (((0xdc00dc00dc00dc00 & *longBytes) ^ 0xd800dc00d800dc00) != 0) #else if(((0xdc00dc00dc00dc00 & *longBytes) ^ 0xdc00d800dc00d800) != 0) #endif // BIGENDIAN { // If it wasn't 4 good surrogates then fall through to slow loop break; } // Use these 4 lucky ordered surrogate pairs. } // Use these 4 high, but not surrogates } // We can use these 4 chars. *longChars = *longBytes; longBytes++; longChars++; } chars = (char*)longChars; bytes = (byte*)longBytes; if(bytes >= byteEnd) { break; } } #endif // !NO_FAST_UNICODE_LOOP // Get 1st byte if(lastByte < 0) { lastByte = *bytes++; continue; } // Get full char char ch; if(bigEndian) { ch = (char)(lastByte << 8 | *(bytes++)); } else { ch = (char)(*(bytes++) << 8 | lastByte); } lastByte = -1; // See if the char's valid if(ch >= 0xd800 && ch <= 0xdfff) { // Was it a high surrogate? if(ch <= 0xdbff) { // Its a high surrogate, if we had one then do fallback for previous one if(lastChar > 0) { // Get fallback for previous high surrogate // Note we have to reconstruct bytes because some may have been in decoder byte[] byteBuffer = null; if(bigEndian) { byteBuffer = new byte[] { unchecked( (byte)(lastChar >> 8) ), unchecked( (byte)lastChar ) }; } else { byteBuffer = new byte[] { unchecked( (byte)lastChar ), unchecked( (byte)(lastChar >> 8) ) }; } if(fallbackBuffer == null) { if(decoder == null) { fallbackBuffer = this.decoderFallback.CreateFallbackBuffer(); } else { fallbackBuffer = decoder.FallbackBuffer; } // Set our internal fallback interesting things. fallbackBuffer.InternalInitialize( byteStart, charEnd ); } if(!fallbackBuffer.InternalFallback( byteBuffer, bytes, ref chars )) { // couldn't fall back lonely surrogate // We either advanced bytes or chars should == charStart and throw below BCLDebug.Assert( bytes >= byteStart + 2 || chars == charStart, "[UnicodeEncoding.GetChars]Expected bytes to have advanced or no output (bad surrogate)" ); bytes -= 2; // didn't use these 2 bytes fallbackBuffer.InternalReset(); ThrowCharsOverflow( decoder, chars == charStart );// Might throw, if no chars output break; // couldn't fallback but didn't throw } } // Ignore the previous high surrogate which fell back already, // yet remember the current high surrogate for next time. lastChar = ch; continue; } // Its a low surrogate if(lastChar == 0) { // Expected a previous high surrogate // Get fallback for this low surrogate // Note we have to reconstruct bytes because some may have been in decoder byte[] byteBuffer = null; if(bigEndian) { byteBuffer = new byte[] { unchecked( (byte)(ch >> 8) ), unchecked( (byte)ch ) }; } else { byteBuffer = new byte[] { unchecked( (byte)ch ), unchecked( (byte)(ch >> 8) ) }; } if(fallbackBuffer == null) { if(decoder == null) { fallbackBuffer = this.decoderFallback.CreateFallbackBuffer(); } else { fallbackBuffer = decoder.FallbackBuffer; } // Set our internal fallback interesting things. fallbackBuffer.InternalInitialize( byteStart, charEnd ); } if(!fallbackBuffer.InternalFallback( byteBuffer, bytes, ref chars )) { // couldn't fall back lonely surrogate // We either advanced bytes or chars should == charStart and throw below BCLDebug.Assert( bytes >= byteStart + 2 || chars == charStart, "[UnicodeEncoding.GetChars]Expected bytes to have advanced or no output (lonely surrogate)" ); bytes -= 2; // didn't use these 2 bytes fallbackBuffer.InternalReset(); ThrowCharsOverflow( decoder, chars == charStart );// Might throw, if no chars output break; // couldn't fallback but didn't throw } // Didn't throw, ignore this one (we already did its fallback) continue; } // Valid surrogate pair, add our lastChar (will need 2 chars) if(chars >= charEnd - 1) { // couldn't find room for this surrogate pair // We either advanced bytes or chars should == charStart and throw below BCLDebug.Assert( bytes >= byteStart + 2 || chars == charStart, "[UnicodeEncoding.GetChars]Expected bytes to have advanced or no output (surrogate pair)" ); bytes -= 2; // didn't use these 2 bytes ThrowCharsOverflow( decoder, chars == charStart );// Might throw, if no chars output // Leave lastChar for next call to Convert() break; // couldn't fallback but didn't throw } *chars++ = lastChar; lastChar = (char)0; } else if(lastChar > 0) { // Had a high surrogate, expected a low surrogate, fall back the high surrogate. byte[] byteBuffer = null; if(bigEndian) { byteBuffer = new byte[] { unchecked( (byte)(lastChar >> 8) ), unchecked( (byte)lastChar ) }; } else { byteBuffer = new byte[] { unchecked( (byte)lastChar ), unchecked( (byte)(lastChar >> 8) ) }; } if(fallbackBuffer == null) { if(decoder == null) { fallbackBuffer = this.decoderFallback.CreateFallbackBuffer(); } else { fallbackBuffer = decoder.FallbackBuffer; } // Set our internal fallback interesting things. fallbackBuffer.InternalInitialize( byteStart, charEnd ); } if(!fallbackBuffer.InternalFallback( byteBuffer, bytes, ref chars )) { // couldn't fall back high surrogate, or char that would be next // We either advanced bytes or chars should == charStart and throw below BCLDebug.Assert( bytes >= byteStart + 2 || chars == charStart, "[UnicodeEncoding.GetChars]Expected bytes to have advanced or no output (no low surrogate)" ); bytes -= 2; // didn't use these 2 bytes fallbackBuffer.InternalReset(); ThrowCharsOverflow( decoder, chars == charStart );// Might throw, if no chars output break; // couldn't fallback but didn't throw } // Not left over now, clear previous high surrogate and continue to add current char lastChar = (char)0; } // Valid char, room for it? if(chars >= charEnd) { // 2 bytes couldn't fall back // We either advanced bytes or chars should == charStart and throw below BCLDebug.Assert( bytes >= byteStart + 2 || chars == charStart, "[UnicodeEncoding.GetChars]Expected bytes to have advanced or no output (normal)" ); bytes -= 2; // didn't use these bytes ThrowCharsOverflow( decoder, chars == charStart );// Might throw, if no chars output break; // couldn't fallback but didn't throw } // add it *chars++ = ch; } // Remember our decoder if we must if(decoder == null || decoder.MustFlush) { if(lastChar > 0) { // No hanging high surrogates allowed, do fallback and remove count for it byte[] byteBuffer = null; if(bigEndian) { byteBuffer = new byte[] { unchecked( (byte)(lastChar >> 8) ), unchecked( (byte)lastChar ) }; } else { byteBuffer = new byte[] { unchecked( (byte)lastChar ), unchecked( (byte)(lastChar >> 8) ) }; } if(fallbackBuffer == null) { if(decoder == null) { fallbackBuffer = this.decoderFallback.CreateFallbackBuffer(); } else { fallbackBuffer = decoder.FallbackBuffer; } // Set our internal fallback interesting things. fallbackBuffer.InternalInitialize( byteStart, charEnd ); } if(!fallbackBuffer.InternalFallback( byteBuffer, bytes, ref chars )) { // 2 bytes couldn't fall back // We either advanced bytes or chars should == charStart and throw below BCLDebug.Assert( bytes >= byteStart + 2 || chars == charStart, "[UnicodeEncoding.GetChars]Expected bytes to have advanced or no output (decoder)" ); bytes -= 2; // didn't use these bytes if(lastByte >= 0) { bytes--; // had an extra last byte hanging around } fallbackBuffer.InternalReset(); ThrowCharsOverflow( decoder, chars == charStart );// Might throw, if no chars output // We'll remember these in our decoder though bytes += 2; if(lastByte >= 0) { bytes++; } goto End; } // done with this one lastChar = (char)0; } if(lastByte >= 0) { if(fallbackBuffer == null) { if(decoder == null) { fallbackBuffer = this.decoderFallback.CreateFallbackBuffer(); } else { fallbackBuffer = decoder.FallbackBuffer; } // Set our internal fallback interesting things. fallbackBuffer.InternalInitialize( byteStart, charEnd ); } // No hanging odd bytes allowed if must flush if(!fallbackBuffer.InternalFallback( new byte[] { unchecked( (byte)lastByte ) }, bytes, ref chars )) { // odd byte couldn't fall back bytes--; // didn't use this byte fallbackBuffer.InternalReset(); ThrowCharsOverflow( decoder, chars == charStart );// Might throw, if no chars output // didn't throw, but we'll remember it in the decoder bytes++; goto End; } // Didn't fail, clear buffer lastByte = -1; } } End: // Remember our decoder if we must if(decoder != null) { BCLDebug.Assert( (decoder.MustFlush == false) || ((lastChar == (char)0) && (lastByte == -1)), "[UnicodeEncoding.GetChars] Expected no left over chars or bytes if flushing" // + " " + ((int)lastChar).ToString("X4") + " " + lastByte.ToString("X2") ); decoder.m_bytesUsed = (int)(bytes - byteStart); decoder.lastChar = lastChar; decoder.lastByte = lastByte; } // Used to do this the old way // System.IO.__UnmanagedMemoryStream.memcpyimpl((byte*)chars, bytes, byteCount); // Shouldn't have anything in fallback buffer for GetChars // (don't have to check m_throwOnOverflow for count or chars) BCLDebug.Assert( fallbackBuffer == null || fallbackBuffer.Remaining == 0, "[UnicodeEncoding.GetChars]Expected empty fallback buffer at end" ); return (int)(chars - charStart); } //// [System.Runtime.InteropServices.ComVisible( false )] public override System.Text.Encoder GetEncoder() { return new EncoderNLS( this ); } public override System.Text.Decoder GetDecoder() { return new UnicodeEncoding.Decoder( this ); } public override byte[] GetPreamble() { if(byteOrderMark) { // Note - we must allocate new byte[]'s here to prevent someone // from modifying a cached byte[]. if(bigEndian) { return new byte[2] { 0xfe, 0xff }; } else { return new byte[2] { 0xff, 0xfe }; } } return emptyByteArray; } public override int GetMaxByteCount( int charCount ) { if(charCount < 0) { #if EXCEPTION_STRINGS throw new ArgumentOutOfRangeException( "charCount", Environment.GetResourceString( "ArgumentOutOfRange_NeedNonNegNum" ) ); #else throw new ArgumentOutOfRangeException(); #endif } // Characters would be # of characters + 1 in case left over high surrogate is ? * max fallback long byteCount = (long)charCount + 1; if(EncoderFallback.MaxCharCount > 1) byteCount *= EncoderFallback.MaxCharCount; // 2 bytes per char byteCount <<= 1; if(byteCount > 0x7fffffff) { #if EXCEPTION_STRINGS throw new ArgumentOutOfRangeException( "charCount", Environment.GetResourceString( "ArgumentOutOfRange_GetByteCountOverflow" ) ); #else throw new ArgumentOutOfRangeException(); #endif } return (int)byteCount; } public override int GetMaxCharCount( int byteCount ) { if(byteCount < 0) { #if EXCEPTION_STRINGS throw new ArgumentOutOfRangeException( "byteCount", Environment.GetResourceString( "ArgumentOutOfRange_NeedNonNegNum" ) ); #else throw new ArgumentOutOfRangeException(); #endif } // long because byteCount could be biggest int. // 1 char per 2 bytes. Round up in case 1 left over in decoder. // Round up using &1 in case byteCount is max size // Might also need an extra 1 if there's a left over high surrogate in the decoder. long charCount = (long)(byteCount >> 1) + (byteCount & 1) + 1; // Don't forget fallback (in case they have a bunch of lonely surrogates or something bizzare like that) if(DecoderFallback.MaxCharCount > 1) { charCount *= DecoderFallback.MaxCharCount; } if(charCount > 0x7fffffff) { #if EXCEPTION_STRINGS throw new ArgumentOutOfRangeException( "byteCount", Environment.GetResourceString( "ArgumentOutOfRange_GetCharCountOverflow" ) ); #else throw new ArgumentOutOfRangeException(); #endif } return (int)charCount; } public override bool Equals( Object value ) { UnicodeEncoding that = value as UnicodeEncoding; if(that != null) { // // Big Endian Unicode has different code page (1201) than small Endian one (1200), // so we still have to check m_codePage here. // return (CodePage == that.CodePage) && byteOrderMark == that.byteOrderMark && // isThrowException == that.isThrowException && // Same as Encoder/Decoder being exception fallbacks bigEndian == that.bigEndian && (EncoderFallback.Equals( that.EncoderFallback )) && (DecoderFallback.Equals( that.DecoderFallback )); } return (false); } public override int GetHashCode() { return CodePage + this.EncoderFallback.GetHashCode() + this.DecoderFallback.GetHashCode() + (byteOrderMark ? 4 : 0) + (bigEndian ? 8 : 0); } [Serializable] private class Decoder : System.Text.DecoderNLS /*, ISerializable*/ { internal int lastByte = -1; internal char lastChar = '\0'; public Decoder( UnicodeEncoding encoding ) : base( encoding ) { // base calls reset } //// // Constructor called by serialization, have to handle deserializing from Everett //// internal Decoder( SerializationInfo info, StreamingContext context ) //// { //// // Any info? //// if(info == null) throw new ArgumentNullException( "info" ); //// //// // Get Common Info //// this.lastByte = (int)info.GetValue( "lastByte", typeof( int ) ); //// //// try //// { //// // Try the encoding, which is only serialized in Whidbey //// this.m_encoding = (Encoding)info.GetValue( "m_encoding", typeof( Encoding ) ); //// this.lastChar = (char)info.GetValue( "lastChar", typeof( char ) ); //// this.m_fallback = (DecoderFallback)info.GetValue( "m_fallback", typeof( DecoderFallback ) ); //// } //// catch(SerializationException) //// { //// // Everett didn't serialize the UnicodeEncoding, get the default one //// bool bigEndian = (bool)info.GetValue( "bigEndian", typeof( bool ) ); //// this.m_encoding = new UnicodeEncoding( bigEndian, false ); //// } //// } //// //// // ISerializable implementation, get data for this object //// [SecurityPermissionAttribute( SecurityAction.LinkDemand, Flags = SecurityPermissionFlag.SerializationFormatter )] //// void ISerializable.GetObjectData( SerializationInfo info, StreamingContext context ) //// { //// // Any info? //// if(info == null) throw new ArgumentNullException( "info" ); //// //// // Save Whidbey data //// info.AddValue( "m_encoding", this.m_encoding ); //// info.AddValue( "m_fallback", this.m_fallback ); //// info.AddValue( "lastChar", this.lastChar ); // Unused by everett so it'll probably get lost //// info.AddValue( "lastByte", this.lastByte ); //// //// // Everett Only //// info.AddValue( "bigEndian", ((UnicodeEncoding)(this.m_encoding)).bigEndian ); //// } public override void Reset() { lastByte = -1; lastChar = '\0'; if(m_fallbackBuffer != null) { m_fallbackBuffer.Reset(); } } // Anything left in our decoder? internal override bool HasState { get { return (this.lastByte != -1 || this.lastChar != '\0'); } } } } } ================================================ FILE: Zelig/Zelig/RunTime/Framework/mscorlib/System/ThreadStaticAttribute.cs ================================================ // ==++== // // Copyright (c) Microsoft Corporation. All rights reserved. // // ==--== /*============================================================ ** ** File: ThreadStaticAttribute.cs ** ** ** Purpose: Custom attribute to indicate that the field should be treated ** as a static relative to a thread. ** ** ** ===========================================================*/ namespace System { using System; [AttributeUsage( AttributeTargets.Field, Inherited = false )] [Serializable] public class ThreadStaticAttribute : Attribute { public ThreadStaticAttribute() { } } } ================================================ FILE: Zelig/Zelig/RunTime/Framework/mscorlib/System/Threading/ApartmentState.cs ================================================ // ==++== // // Copyright (c) Microsoft Corporation. All rights reserved. // // ==--== /*============================================================================= ** ** Class: ApartmentState ** ** ** Purpose: Enum to represent the different threading models ** ** =============================================================================*/ namespace System.Threading { [Serializable()] public enum ApartmentState { /*========================================================================= ** Constants for thread apartment states. =========================================================================*/ STA = 0, MTA = 1, Unknown = 2 } } ================================================ FILE: Zelig/Zelig/RunTime/Framework/mscorlib/System/Threading/AutoResetEvent.cs ================================================ // ==++== // // Copyright (c) Microsoft Corporation. All rights reserved. // // ==--== /*============================================================================= ** ** Class: AutoResetEvent ** ** ** Purpose: An example of a WaitHandle class ** ** =============================================================================*/ namespace System.Threading { using System; using System.Security.Permissions; using System.Runtime.InteropServices; [HostProtection( Synchronization = true, ExternalThreading = true )] public sealed class AutoResetEvent : EventWaitHandle { public AutoResetEvent( bool initialState ) : base( initialState, EventResetMode.AutoReset ) { } } } ================================================ FILE: Zelig/Zelig/RunTime/Framework/mscorlib/System/Threading/CancellationToken.cs ================================================ // Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. // //////////////////////////////////////////////////////////////////////////////// #pragma warning disable 0420 // turn off 'a reference to a volatile field will not be treated as volatile' during CAS. using System; using System.Diagnostics; using System.Runtime.InteropServices; using System.Security.Permissions; using System.Diagnostics.Contracts; namespace System.Threading { /// /// Propagates notification that operations should be canceled. /// /// /// /// A may be created directly in an unchangeable canceled or non-canceled state /// using the CancellationToken's constructors. However, to have a CancellationToken that can change /// from a non-canceled to a canceled state, /// CancellationTokenSource must be used. /// CancellationTokenSource exposes the associated CancellationToken that may be canceled by the source through its /// Token property. /// /// /// Once canceled, a token may not transition to a non-canceled state, and a token whose /// is false will never change to one that can be canceled. /// /// /// All members of this struct are thread-safe and may be used concurrently from multiple threads. /// /// [ComVisible(false)] [HostProtection(Synchronization = true, ExternalThreading = true)] [DebuggerDisplay("IsCancellationRequested = {IsCancellationRequested}")] public struct CancellationToken { private readonly static Action s_ActionToActionObjShunt = new Action(ActionToActionObjShunt); // The backing TokenSource. // if null, it implicitly represents the same thing as new CancellationToken(false). // When required, it will be instantiated to reflect this. private CancellationTokenSource m_source; //!! warning. If more fields are added, the assumptions in CreateLinkedToken may no longer be valid /* Properties */ /// /// Returns an empty CancellationToken value. /// /// /// The value returned by this property will be non-cancelable by default. /// public static CancellationToken None { get { return default(CancellationToken); } } /// /// Gets whether cancellation has been requested for this token. /// /// Whether cancellation has been requested for this token. /// /// /// This property indicates whether cancellation has been requested for this token, /// either through the token initially being construted in a canceled state, or through /// calling Cancel /// on the token's associated . /// /// /// If this property is true, it only guarantees that cancellation has been requested. /// It does not guarantee that every registered handler /// has finished executing, nor that cancellation requests have finished propagating /// to all registered handlers. Additional synchronization may be required, /// particularly in situations where related objects are being canceled concurrently. /// /// public bool IsCancellationRequested { get { return (m_source != null) && m_source.IsCancellationRequested; } } /// /// Gets whether this token is capable of being in the canceled state. /// /// /// If CanBeCanceled returns false, it is guaranteed that the token will never transition /// into a canceled state, meaning that will never /// return true. /// public bool CanBeCanceled { get { return (m_source != null) && m_source.CanBeCanceled; } } /// /// Gets a that is signaled when the token is canceled. /// /// Accessing this property causes a WaitHandle /// to be instantiated. It is preferable to only use this property when necessary, and to then /// dispose the associated instance at the earliest opportunity (disposing /// the source will dispose of this allocated handle). The handle should not be closed or disposed directly. /// /// The associated CancellationTokenSource has been disposed. public WaitHandle WaitHandle { get { if (m_source == null) { m_source = CancellationTokenSource.InternalGetStaticSource(canceled: false); } return m_source.WaitHandle; } } // public CancellationToken() // this constructor is implicit for structs // -> this should behaves exactly as for new CancellationToken(false) /// /// Internal constructor only a CancellationTokenSource should create a CancellationToken /// internal CancellationToken(CancellationTokenSource source) { m_source = source; } /// /// Initializes the CancellationToken. /// /// /// The canceled state for the token. /// /// /// Tokens created with this constructor will remain in the canceled state specified /// by the parameter. If is false, /// both and will be false. /// If is true, /// both and will be true. /// public CancellationToken(bool canceled) : this() { if (canceled) { m_source = CancellationTokenSource.InternalGetStaticSource(canceled); } } /// /// Registers a delegate that will be called when this CancellationToken is canceled. /// /// /// /// If this token is already in the canceled state, the /// delegate will be run immediately and synchronously. Any exception the delegate generates will be /// propagated out of this method call. /// /// /// The current ExecutionContext, if one exists, will be captured /// along with the delegate and will be used when executing it. /// /// /// The delegate to be executed when the CancellationToken is canceled. /// The instance that can /// be used to deregister the callback. /// is null. public CancellationTokenRegistration Register(Action callback) { if (callback == null) throw new ArgumentNullException(nameof(callback)); return Register(s_ActionToActionObjShunt, callback, useSynchronizationContext: false); } /// /// Registers a delegate that will be called when this /// CancellationToken is canceled. /// /// /// /// If this token is already in the canceled state, the /// delegate will be run immediately and synchronously. Any exception the delegate generates will be /// propagated out of this method call. /// /// /// The current ExecutionContext, if one exists, will be captured /// along with the delegate and will be used when executing it. /// /// /// The delegate to be executed when the CancellationToken is canceled. /// A Boolean value that indicates whether to capture /// the current SynchronizationContext and use it /// when invoking the . /// The instance that can /// be used to deregister the callback. /// is null. public CancellationTokenRegistration Register(Action callback, bool useSynchronizationContext) { if (callback == null) { throw new ArgumentNullException(nameof(callback)); } return Register(s_ActionToActionObjShunt, callback, useSynchronizationContext); } /// /// Registers a delegate that will be called when this /// CancellationToken is canceled. /// /// /// /// If this token is already in the canceled state, the /// delegate will be run immediately and synchronously. Any exception the delegate generates will be /// propagated out of this method call. /// /// /// The current ExecutionContext, if one exists, will be captured /// along with the delegate and will be used when executing it. /// /// /// The delegate to be executed when the CancellationToken is canceled. /// The state to pass to the when the delegate is invoked. This may be null. /// The instance that can /// be used to deregister the callback. /// is null. public CancellationTokenRegistration Register(Action callback, object state) { if (callback == null) { throw new ArgumentNullException(nameof(callback)); } return Register(callback, state, useSynchronizationContext: false); } /// /// Registers a delegate that will be called when this /// CancellationToken is canceled. /// /// /// /// If this token is already in the canceled state, the /// delegate will be run immediately and synchronously. Any exception the delegate generates will be /// propagated out of this method call. /// /// /// The current ExecutionContext, if one exists, /// will be captured along with the delegate and will be used when executing it. /// /// /// The delegate to be executed when the CancellationToken is canceled. /// The state to pass to the when the delegate is invoked. This may be null. /// A Boolean value that indicates whether to capture /// the current SynchronizationContext and use it /// when invoking the . /// The instance that can /// be used to deregister the callback. /// is null. /// The associated CancellationTokenSource has been disposed. public CancellationTokenRegistration Register(Action callback, object state, bool useSynchronizationContext) { if (callback == null) { throw new ArgumentNullException(nameof(callback)); } if (!CanBeCanceled) { // Nothing to do for tokens than can never reach the canceled state. Give them a dummy registration. return new CancellationTokenRegistration(); } return m_source.RegisterCallback(callback, state); } /// /// Determines whether the current CancellationToken instance is equal to the /// specified token. /// /// The other CancellationToken to which to compare this /// instance. /// True if the instances are equal; otherwise, false. Two tokens are equal if they are associated /// with the same CancellationTokenSource or if they were both constructed /// from public CancellationToken constructors and their values are equal. public bool Equals(CancellationToken other) { // If both sources are null, then both tokens represent the Empty token. if ((m_source == null) && (other.m_source == null)) { return true; } // one is null but other has inflated the default source // these are only equal if the inflated one is the staticSource(false) if (m_source == null) { return other.m_source == CancellationTokenSource.InternalGetStaticSource(false); } if (other.m_source == null) { return m_source == CancellationTokenSource.InternalGetStaticSource(false); } // general case, we check if the sources are identical return m_source == other.m_source; } /// /// Determines whether the current CancellationToken instance is equal to the /// specified . /// /// The other object to which to compare this instance. /// True if is a CancellationToken /// and if the two instances are equal; otherwise, false. Two tokens are equal if they are associated /// with the same CancellationTokenSource or if they were both constructed /// from public CancellationToken constructors and their values are equal. /// An associated CancellationTokenSource has been disposed. public override bool Equals(object other) { if (other is CancellationToken) { return Equals((CancellationToken)other); } return false; } /// /// Serves as a hash function for a CancellationToken. /// /// A hash code for the current CancellationToken instance. public override int GetHashCode() { if (m_source == null) { // Link to the common source so that we have a source to interrogate. return CancellationTokenSource.InternalGetStaticSource(false).GetHashCode(); } return m_source.GetHashCode(); } /// /// Determines whether two CancellationToken instances are equal. /// /// The first instance. /// The second instance. /// True if the instances are equal; otherwise, false. /// An associated CancellationTokenSource has been disposed. public static bool operator ==(CancellationToken left, CancellationToken right) { return left.Equals(right); } /// /// Determines whether two CancellationToken instances are not equal. /// /// The first instance. /// The second instance. /// True if the instances are not equal; otherwise, false. /// An associated CancellationTokenSource has been disposed. public static bool operator !=(CancellationToken left, CancellationToken right) { return !left.Equals(right); } /// /// Throws a OperationCanceledException if /// this token has had cancellation requested. /// /// /// This method provides functionality equivalent to: /// /// if (token.IsCancellationRequested) /// throw new OperationCanceledException(token); /// /// /// The token has had cancellation requested. /// The associated CancellationTokenSource has been disposed. public void ThrowIfCancellationRequested() { if (IsCancellationRequested) { ThrowOperationCanceledException(); } } internal void ThrowIfSourceDisposed() { if ((m_source != null) && m_source.IsDisposed) { throw new ObjectDisposedException(null, "The CancellationTokenSource associated with this CancellationToken has been disposed."); } } // Throws an OCE; separated out to enable better inlining of ThrowIfCancellationRequested private void ThrowOperationCanceledException() { throw new OperationCanceledException("The operation was canceled.", this); } private static void ActionToActionObjShunt(object obj) { Action action = obj as Action; #if ENABLE_CONTRACTS Contract.Assert(action != null, "Expected an Action here"); #endif // ENABLE_CONTRACTS action(); } } } ================================================ FILE: Zelig/Zelig/RunTime/Framework/mscorlib/System/Threading/CancellationTokenRegistration.cs ================================================ // Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using System; using System.Diagnostics.Contracts; using System.Security.Permissions; using System.Runtime.CompilerServices; namespace System.Threading { /// /// Represents a callback delegate that has been registered with a CancellationToken. /// /// /// To unregister a callback, dispose the corresponding Registration instance. /// [HostProtection(Synchronization = true, ExternalThreading = true)] public struct CancellationTokenRegistration : IEquatable, IDisposable { private readonly CancellationCallbackInfo m_callbackInfo; internal CancellationTokenRegistration(CancellationCallbackInfo callbackInfo) { m_callbackInfo = callbackInfo; } /// /// Attempts to deregister the item. If it's already being run, this may fail. Entails a full memory fence. /// /// True if the callback was found and deregistered, false otherwise. [FriendAccessAllowed] internal bool TryDeregister() { if (m_callbackInfo?.CancellationTokenSource == null) //can be null for dummy registrations. { return false; } return m_callbackInfo.CancellationTokenSource.TryDeregisterCallback(m_callbackInfo); } /// /// Disposes of the registration and unregisters the target callback from the associated /// CancellationToken. If the target callback is /// currently executing this method will wait until it completes, except in the degenerate cases where a /// callback method deregisters itself. /// public void Dispose() { // Remove this callback registration from the invocation list. If that fails, wait for the callback to complete. if (!TryDeregister()) { m_callbackInfo?.CancellationTokenSource?.WaitForCallbackToComplete(m_callbackInfo); } } /// /// Determines whether two CancellationTokenRegistration /// instances are equal. /// /// The first instance. /// The second instance. /// True if the instances are equal; otherwise, false. public static bool operator ==(CancellationTokenRegistration left, CancellationTokenRegistration right) { return left.Equals(right); } /// /// Determines whether two CancellationTokenRegistration instances are not equal. /// /// The first instance. /// The second instance. /// True if the instances are not equal; otherwise, false. public static bool operator !=(CancellationTokenRegistration left, CancellationTokenRegistration right) { return !left.Equals(right); } /// /// Determines whether the current CancellationTokenRegistration instance is equal to the /// specified . /// /// The other object to which to compare this instance. /// True, if both this and are equal. False, otherwise. /// Two CancellationTokenRegistration instances are equal if /// they both refer to the output of a single call to the same Register method of a /// CancellationToken. /// public override bool Equals(object obj) { return ((obj is CancellationTokenRegistration) && Equals((CancellationTokenRegistration)obj)); } /// /// Determines whether the current CancellationToken instance is equal to the /// specified . /// /// The other CancellationTokenRegistration to which to compare this instance. /// True, if both this and are equal. False, otherwise. /// Two CancellationTokenRegistration instances are equal if /// they both refer to the output of a single call to the same Register method of a /// CancellationToken. /// public bool Equals(CancellationTokenRegistration other) { return m_callbackInfo == other.m_callbackInfo; } /// /// Serves as a hash function for a CancellationTokenRegistration.. /// /// A hash code for the current CancellationTokenRegistration instance. public override int GetHashCode() { if (m_callbackInfo == null) { return 0; } return m_callbackInfo.GetHashCode(); } } } ================================================ FILE: Zelig/Zelig/RunTime/Framework/mscorlib/System/Threading/CancellationTokenSource.cs ================================================ // Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. #pragma warning disable 0420 // //////////////////////////////////////////////////////////////////////////////// using System; using System.Security; using System.Collections.Generic; using System.Runtime.InteropServices; using System.Security.Permissions; using System.Diagnostics.Contracts; namespace System.Threading { /// /// Signals to a that it should be canceled. /// /// /// /// is used to instantiate a /// (via the source's Token property) /// that can be handed to operations that wish to be notified of cancellation or that can be used to /// register asynchronous operations for cancellation. That token may have cancellation requested by /// calling to the source's Cancel /// method. /// /// /// All members of this class, except Dispose, are thread-safe and may be used /// concurrently from multiple threads. /// /// [ComVisible(false)] [HostProtection(Synchronization = true, ExternalThreading = true)] public class CancellationTokenSource : IDisposable { // Legal values for m_state private const int NOT_CANCELED = 0; private const int NOTIFYING = 1; private const int NOTIFYING_COMPLETE = 2; private const int CANNOT_BE_CANCELED = 3; // Static sources that can be used as the backing source for 'fixed' CancellationTokens that never change state. private static readonly CancellationTokenSource s_preCanceled = new CancellationTokenSource(true); private static readonly CancellationTokenSource s_notCancelable = new CancellationTokenSource(false); private static readonly TimerCallback s_timerCallback = new TimerCallback(TimerCallbackLogic); private static readonly object s_callbackSentinel = new object(); private volatile int m_state; private object m_callbacks; // This will be either s_callbackSentinel or a List. private bool m_disposed; private volatile Timer m_timer; private volatile ManualResetEvent m_kernelEvent; private volatile Thread m_currentCallbackThread; private volatile CancellationCallbackInfo m_executingCallback; #if DISABLED_FOR_LLILUM private CancellationTokenRegistration[] m_linkingRegistrations; //lazily initialized if required. private static readonly Action s_LinkedTokenCancelDelegate = new Action(LinkedTokenCancelDelegate); #endif // DISABLED_FOR_LLILUM #if DISABLED_FOR_LLILUM private static void LinkedTokenCancelDelegate(object source) { CancellationTokenSource cts = source as CancellationTokenSource; Contract.Assert(source != null); cts.Cancel(); } #endif // DISABLED_FOR_LLILUM /// /// Initializes the . /// public CancellationTokenSource() { } /// /// Constructs a that will be canceled after a specified time span. /// /// The time span to wait before canceling this /// /// The exception that is thrown when is less than -1 or greater than Int32.MaxValue. /// /// /// /// The countdown for the delay starts during the call to the constructor. When the delay expires, /// the constructed is canceled, if it has /// not been canceled already. /// /// /// Subsequent calls to CancelAfter will reset the delay for the constructed /// , if it has not been /// canceled already. /// /// public CancellationTokenSource(TimeSpan delay) { long totalMilliseconds = (long)delay.TotalMilliseconds; if ((totalMilliseconds < -1) || (totalMilliseconds > int.MaxValue)) { throw new ArgumentOutOfRangeException(nameof(delay)); } m_timer = new Timer(s_timerCallback, this, (int)totalMilliseconds, -1); } /// /// Constructs a that will be canceled after a specified time span. /// /// The time span to wait before canceling this /// /// The exception that is thrown when is less than -1. /// /// /// /// The countdown for the millisecondsDelay starts during the call to the constructor. When the millisecondsDelay expires, /// the constructed is canceled (if it has /// not been canceled already). /// /// /// Subsequent calls to CancelAfter will reset the millisecondsDelay for the constructed /// , if it has not been /// canceled already. /// /// public CancellationTokenSource(int millisecondsDelay) { if (millisecondsDelay < -1) { throw new ArgumentOutOfRangeException(nameof(millisecondsDelay)); } m_timer = new Timer(s_timerCallback, this, millisecondsDelay, -1); } /// /// Initializes static source with a preset status. /// /// Whether the source should be pre-canceled. private CancellationTokenSource(bool canceled) { m_state = canceled ? NOTIFYING_COMPLETE : CANNOT_BE_CANCELED; } /// /// Gets whether cancellation has been requested for this CancellationTokenSource. /// /// Whether cancellation has been requested for this CancellationTokenSource. /// /// /// This property indicates whether cancellation has been requested for this token source, such as /// due to a call to its /// Cancel method. /// /// /// If this property returns true, it only guarantees that cancellation has been requested. It does not /// guarantee that every handler registered with the corresponding token has finished executing, nor /// that cancellation requests have finished propagating to all registered handlers. Additional /// synchronization may be required, particularly in situations where related objects are being /// canceled concurrently. /// /// public bool IsCancellationRequested { get { int state = m_state; return (state == NOTIFYING) || (state == NOTIFYING_COMPLETE); } } /// /// Gets the CancellationToken /// associated with this . /// /// The CancellationToken /// associated with this . /// The token source has been /// disposed. public CancellationToken Token { get { ThrowIfDisposed(); return new CancellationToken(this); } } internal bool CanBeCanceled { get { return m_state != CANNOT_BE_CANCELED; } } internal WaitHandle WaitHandle { get { ThrowIfDisposed(); // fast path if already allocated. if (m_kernelEvent != null) { return m_kernelEvent; } // lazy-init the mre. ManualResetEvent mre = new ManualResetEvent(false); if (Interlocked.CompareExchange(ref m_kernelEvent, mre, null) != null) { ((IDisposable)mre).Dispose(); } // There is a race condition between checking IsCancellationRequested and setting the event. // However, at this point, the kernel object definitely exists and the cases are: // 1. if IsCancellationRequested = true, then we will call Set() // 2. if IsCancellationRequested = false, then Cancel will see that the event exists, and will call Set(). if (IsCancellationRequested) { m_kernelEvent.Set(); } return m_kernelEvent; } } internal bool IsDisposed { get { return m_disposed; } } /// /// Communicates a request for cancellation. /// /// /// /// The associated will be /// notified of the cancellation and will transition to a state where /// IsCancellationRequested returns true. /// Any callbacks or cancelable operations /// registered with the will be executed. /// /// /// Cancelable operations and callbacks registered with the token should not throw exceptions. /// However, this overload of Cancel will aggregate any exceptions thrown into a , /// such that one callback throwing an exception will not prevent other registered callbacks from being executed. /// /// /// The that was captured when each callback was registered /// will be reestablished when the callback is invoked. /// /// /// An aggregate exception containing all the exceptions thrown /// by the registered callbacks on the associated . /// This has been disposed. public void Cancel() { Cancel(false); } /// /// Communicates a request for cancellation. /// /// /// /// The associated will be /// notified of the cancellation and will transition to a state where /// IsCancellationRequested returns true. /// Any callbacks or cancelable operations /// registered with the will be executed. /// /// /// Cancelable operations and callbacks registered with the token should not throw exceptions. /// If is true, an exception will immediately propagate out of the /// call to Cancel, preventing the remaining callbacks and cancelable operations from being processed. /// If is false, this overload will aggregate any /// exceptions thrown into a , /// such that one callback throwing an exception will not prevent other registered callbacks from being executed. /// /// /// The that was captured when each callback was registered /// will be reestablished when the callback is invoked. /// /// /// Specifies whether exceptions should immediately propagate. /// An aggregate exception containing all the exceptions thrown /// by the registered callbacks on the associated . /// This has been disposed. public void Cancel(bool throwOnFirstException) { ThrowIfDisposed(); // Do nothing if we've already been canceled. if (IsCancellationRequested) { return; } // If we're the first to signal cancellation, do the main extra work. if (NOT_CANCELED == Interlocked.CompareExchange(ref m_state, NOTIFYING, NOT_CANCELED)) { // Dispose of the timer, if any. m_timer?.Dispose(); // If the kernel event is null at this point, it will be set during lazy construction. m_kernelEvent?.Set(); m_currentCallbackThread = Thread.CurrentThread; // - late enlisters to the Canceled event will have their callbacks called immediately in the Register() methods. // - Callbacks are not called inside a lock. // - After transition, no more delegates will be added to the // - list of handlers, and hence it can be consumed and cleared at leisure by ExecuteCallbackHandlers. ExecuteCallbackHandlers(throwOnFirstException); #if ENABLE_CONTRACTS Contract.Assert(IsCancellationCompleted, "Expected cancellation to have finished."); #endif // ENABLE_CONTRACTS } } /// /// Schedules a Cancel operation on this . /// /// The time span to wait before canceling this . /// /// The exception thrown when this has been disposed. /// /// /// The exception thrown when is less than -1 or /// greater than Int32.MaxValue. /// /// /// /// The countdown for the delay starts during this call. When the delay expires, /// this is canceled, if it has /// not been canceled already. /// /// /// Subsequent calls to CancelAfter will reset the delay for this /// , if it has not been /// canceled already. /// /// public void CancelAfter(TimeSpan delay) { long totalMilliseconds = (long)delay.TotalMilliseconds; if ((totalMilliseconds < -1) || (totalMilliseconds > int.MaxValue)) { throw new ArgumentOutOfRangeException(nameof(delay)); } CancelAfter((int)totalMilliseconds); } /// /// Schedules a Cancel operation on this . /// /// The time span to wait before canceling this . /// /// The exception thrown when this has been disposed. /// /// /// The exception thrown when is less than -1. /// /// /// /// The countdown for the millisecondsDelay starts during this call. When the millisecondsDelay expires, /// this is canceled, if it has /// not been canceled already. /// /// /// Subsequent calls to CancelAfter will reset the millisecondsDelay for this /// , if it has not been /// canceled already. /// /// public void CancelAfter(int millisecondsDelay) { ThrowIfDisposed(); if (millisecondsDelay < -1) { throw new ArgumentOutOfRangeException(nameof(millisecondsDelay)); } if (IsCancellationRequested) { return; } throw new NotImplementedException(); #if DISABLED_FOR_LLILUM // There is a race condition here as a Cancel could occur between the check of // IsCancellationRequested and the creation of the timer. This is benign; in the // worst case, a timer will be created that has no effect when it expires. // Also, if Dispose() is called right here (after ThrowIfDisposed(), before timer // creation), it would result in a leaked Timer object (at least until the timer // expired and Disposed itself). But this would be considered bad behavior, as // Dispose() is not thread-safe and should not be called concurrently with CancelAfter(). if (m_timer == null) { // Lazily initialize the timer in a thread-safe fashion. // Initially set to "never go off" because we don't want to take a // chance on a timer "losing" the initialization and then // cancelling the token before it (the timer) can be disposed. Timer newTimer = new Timer(s_timerCallback, this, -1, -1); if (Interlocked.CompareExchange(ref m_timer, newTimer, null) != null) { // We did not initialize the timer. Dispose the new timer. newTimer.Dispose(); } } // It is possible that m_timer has already been disposed, so we must do // the following in a try/catch block. try { m_timer.Change(millisecondsDelay, -1); } catch (ObjectDisposedException) { // Just eat the exception. There is no other way to tell that // the timer has been disposed, and even if there were, there // would not be a good way to deal with the observe/dispose // race condition. } #endif // DISABLED_FOR_LLILUM } /// /// Creates a CancellationTokenSource that will be in the canceled state /// when any of the source tokens are in the canceled state. /// /// The first CancellationToken to observe. /// The second CancellationToken to observe. /// A CancellationTokenSource that is linked /// to the source tokens. public static CancellationTokenSource CreateLinkedTokenSource(CancellationToken token1, CancellationToken token2) { throw new NotImplementedException(); #if DISABLED_FOR_LLILUM CancellationTokenSource linkedTokenSource = new CancellationTokenSource(); bool token2CanBeCanceled = token2.CanBeCanceled; if (token1.CanBeCanceled) { linkedTokenSource.m_linkingRegistrations = new CancellationTokenRegistration[token2CanBeCanceled ? 2 : 1]; // there will be at least 1 and at most 2 linkings linkedTokenSource.m_linkingRegistrations[0] = token1.InternalRegisterWithoutEC(s_LinkedTokenCancelDelegate, linkedTokenSource); } if (token2CanBeCanceled) { int index = 1; if (linkedTokenSource.m_linkingRegistrations == null) { linkedTokenSource.m_linkingRegistrations = new CancellationTokenRegistration[1]; // this will be the only linking index = 0; } linkedTokenSource.m_linkingRegistrations[index] = token2.InternalRegisterWithoutEC(s_LinkedTokenCancelDelegate, linkedTokenSource); } return linkedTokenSource; #endif // DISABLED_FOR_LLILUM } /// /// Creates a CancellationTokenSource that will be in the canceled state /// when any of the source tokens are in the canceled state. /// /// The CancellationToken instances to observe. /// A CancellationTokenSource that is linked /// to the source tokens. /// is null. public static CancellationTokenSource CreateLinkedTokenSource(params CancellationToken[] tokens) { throw new NotImplementedException(); #if DISABLED_FOR_LLILUM if (tokens == null) { throw new ArgumentNullException(nameof(tokens)); } if (tokens.Length == 0) { throw new ArgumentException("No tokens were supplied."); } // a defensive copy is not required as the array has value-items that have only a single IntPtr field, // hence each item cannot be null itself, and reads of the payloads cannot be torn. Contract.EndContractBlock(); CancellationTokenSource linkedTokenSource = new CancellationTokenSource(); linkedTokenSource.m_linkingRegistrations = new CancellationTokenRegistration[tokens.Length]; for (int i = 0; i < tokens.Length; i++) { if (tokens[i].CanBeCanceled) { linkedTokenSource.m_linkingRegistrations[i] = tokens[i].InternalRegisterWithoutEC(s_LinkedTokenCancelDelegate, linkedTokenSource); } // Empty slots in the array will be default(CancellationTokenRegistration), which are nops to Dispose. // Based on usage patterns, such occurrences should also be rare, such that it's not worth resizing // the array and incurring the related costs. } return linkedTokenSource; #endif // DISABLED_FOR_LLILUM } /// /// Releases the resources used by this . /// /// /// This method is not thread-safe for any other concurrent calls. /// public void Dispose() { Dispose(true); GC.SuppressFinalize(this); } /// /// Releases the unmanaged resources used by the class and optionally releases the managed resources. /// /// true to release both managed and unmanaged resources; false to release only unmanaged resources. protected virtual void Dispose(bool disposing) { // NOTE: This is intentionally exposed as "protected" rather than "internal" to match CoreCLR's interface. if (disposing) { // We specifically tolerate that a callback can be deregistered after the CTS has been disposed and/or // concurrently with cts.Dispose(). This is safe without locks because the reg.Dispose() only mutates a // sparseArrayFragment and then reads from properties of the CTS that are not invalidated by cts.Dispose(). // // We also tolerate that a callback can be registered after the CTS has been disposed. This is safe // without locks because InternalRegister is tolerant of m_registeredCallbacksLists becoming null during // its execution. However, we run the acceptable risk of m_registeredCallbacksLists getting reinitialized // to non-null if there is a race between Dispose and Register, in which case this instance may // unnecessarily hold onto a registered callback. But that's no worse than if Dispose wasn't safe to use // concurrently, as Dispose would never be called, and thus no handlers would be dropped. if (m_disposed) { return; } m_timer?.Dispose(); #if DISABLED_FOR_LLILUM var linkingRegistrations = m_linkingRegistrations; if (linkingRegistrations != null) { m_linkingRegistrations = null; // free for GC once we're done enumerating for (int i = 0; i < linkingRegistrations.Length; i++) { linkingRegistrations[i].Dispose(); } } // Registered callbacks are now either complete or will never run, due to guarantees made by ctr.Dispose() // so we can now perform main disposal work without risk of linking callbacks trying to use this CTS. m_registeredCallbacksLists = null; // free for GC. #endif // DISABLED_FOR_LLILUM if (m_kernelEvent != null) { m_kernelEvent.Close(); // the critical cleanup to release an OS handle m_kernelEvent = null; // free for GC. } m_disposed = true; } } /// /// Throws an exception if the source has been disposed. /// internal void ThrowIfDisposed() { if (m_disposed) { throw new ObjectDisposedException(null, "The CancellationTokenSource has been disposed."); } } internal CancellationTokenRegistration RegisterCallback(Action callback, object stateForCallback) { CancellationCallbackInfo callbackInfo = TryRegisterCallback(callback, stateForCallback); if (callbackInfo == null) { callback(stateForCallback); return new CancellationTokenRegistration(); } return new CancellationTokenRegistration(callbackInfo); } /// /// Registers a callback object and returns the wrapped callback info. /// /// Callback information if successful; otherwise null. internal CancellationCallbackInfo TryRegisterCallback(Action callback, object stateForCallback) { ThrowIfDisposed(); #if ENABLE_CONTRACTS // The CancellationToken has already checked that the token is cancelable before calling this method. Contract.Assert(CanBeCanceled, "Cannot register for uncancelable token src"); #endif // ENABLE_CONTRACTS // If this source has already been canceled, we'll run the callback synchronously and skip the registration. if (IsCancellationRequested) { return null; } // Ensure that the callbacks list exists. In the event that we hit a very narrow race, we'll temporarily // allocate an extra list and drop it. This is acceptable overhead to keep the implementation light. if (m_callbacks == null) { var newCallbacks = new List(1); Interlocked.CompareExchange(ref m_callbacks, newCallbacks, null); } // Resample m_callbacks in case there was a race above. This is guaranteed to be either a list or the // s_callbackSentinel token. var list = m_callbacks as List; // If the list is null, we must already be executing callbacks, so execute this one synchronously. if (list == null) { return null; } lock (list) { // It's possible for invocation to begin right after we snap the list, so check the sentinel again. if (m_callbacks == s_callbackSentinel) { return null; } CancellationCallbackInfo callbackInfo = new CancellationCallbackInfo(callback, stateForCallback, this); list.Add(callbackInfo); return callbackInfo; } } internal bool TryDeregisterCallback(CancellationCallbackInfo callbackInfo) { var callbacks = m_callbacks as List; if (callbacks == null) { return false; } lock (callbacks) { // It's possible for invocation to begin right after we snap the list, so check the sentinel again. if (m_callbacks == s_callbackSentinel) { return false; } return callbacks.Remove(callbackInfo); } } /// /// Invoke the Canceled event. /// /// /// The handlers are invoked synchronously in LIFO order. /// private void ExecuteCallbackHandlers(bool throwOnFirstException) { #if ENABLE_CONTRACTS Contract.Assert(IsCancellationRequested, "ExecuteCallbackHandlers should only be called after setting IsCancellationRequested->true"); #endif // ENABLE_CONTRACTS // Design decision: call the delegates in LIFO order so that callbacks fire 'deepest first'. This is // intended to help with nesting scenarios so that child enlisters cancel before their parents. object callbackObject = Interlocked.Exchange(ref m_callbacks, s_callbackSentinel); // Trivial case: If we have no callbacks to call, we're done. if (callbackObject == null) { m_state = NOTIFYING_COMPLETE; return; } List exceptionList = null; try { #if ENABLE_CONTRACTS Contract.Assert(callbackObject != s_callbackSentinel, "ExecuteCallbackHandlers should only be called once."); #endif // ENABLE_CONTRACTS // We don't want to invoke these callbacks under a lock, so create a copy. CancellationCallbackInfo[] callbacks; lock (callbackObject) { callbacks = ((List)callbackObject).ToArray(); } for (int i = callbacks.Length - 1; i >= 0; --i) { try { m_executingCallback = callbacks[i]; m_executingCallback.Invoke(); } catch (Exception ex) { if (throwOnFirstException) { throw; } if (exceptionList == null) { exceptionList = new List(); } exceptionList.Add(ex); } } } finally { m_state = NOTIFYING_COMPLETE; m_executingCallback = null; m_currentCallbackThread = null; } if (exceptionList != null) { #if ENABLE_CONTRACTS Contract.Assert(exceptionList.Count > 0, "Expected exception count > 0"); #endif // ENABLE_CONTRACTS throw new AggregateException(exceptionList); } } /// /// InternalGetStaticSource() /// /// Whether the source should be set. /// A static source to be shared among multiple tokens. internal static CancellationTokenSource InternalGetStaticSource(bool canceled) { return canceled ? s_preCanceled : s_notCancelable; } /// /// Wait for a singlre callback to complete. It's OK to call this method after the callback has already finished, /// but calling this before the target callback has started is not allowed. /// /// The callback to wait for. internal void WaitForCallbackToComplete(CancellationCallbackInfo callbackInfo) { // Design decision: In order to avoid deadlocks, we won't block if the callback is being executed on the // current thread. It's generally poor form to do this, but it does happen in consumer code. if ((m_state == NOTIFYING) && (m_currentCallbackThread != Thread.CurrentThread)) { // It's OK to spin here since callbacks are expected to be relatively fast and calling this wait method // should be relatively rare. SpinWait spinWait = new SpinWait(); while (m_executingCallback == callbackInfo) { spinWait.SpinOnce(); } } } private static void TimerCallbackLogic(object obj) { CancellationTokenSource cts = (CancellationTokenSource)obj; // Cancel the source; handle a race condition with cts.Dispose() if (!cts.m_disposed) { // There is a small window for a race condition where a cts.Dispose can sneak // in right here. I'll wrap the cts.Cancel() in a try/catch to proof us // against this race condition. try { cts.Cancel(); // will take care of disposing of m_timer } catch (ObjectDisposedException) { // If the ODE was not due to the target cts being disposed, then propagate the ODE. if (!cts.m_disposed) { throw; } } } } } /// /// A helper class for collating the various bits of information required to execute /// cancellation callbacks. /// internal class CancellationCallbackInfo { internal readonly Action Callback; internal readonly object StateForCallback; internal readonly CancellationTokenSource CancellationTokenSource; internal CancellationCallbackInfo( Action callback, object stateForCallback, CancellationTokenSource cancellationTokenSource) { Callback = callback; StateForCallback = stateForCallback; CancellationTokenSource = cancellationTokenSource; } [SecuritySafeCritical] internal void Invoke() { Callback(StateForCallback); } } } ================================================ FILE: Zelig/Zelig/RunTime/Framework/mscorlib/System/Threading/EventResetMode.cs ================================================ // ==++== // // Copyright (c) Microsoft Corporation. All rights reserved. // // ==--== /*============================================================================= ** ** Enum: EventResetMode ** ** ** Purpose: Enum to determine the Event type to create ** ** =============================================================================*/ namespace System.Threading { using System.Runtime.InteropServices; public enum EventResetMode { AutoReset = 0, ManualReset = 1, } } ================================================ FILE: Zelig/Zelig/RunTime/Framework/mscorlib/System/Threading/EventWaitHandle.cs ================================================ // ==++== // // Copyright (c) Microsoft Corporation. All rights reserved. // // ==--== /*============================================================================= ** ** Class: EventWaitHandle ** ** ** Purpose: Base class for representing Events ** ** =============================================================================*/ namespace System.Threading { using System; using System.Threading; using System.Runtime.CompilerServices; using System.Security.Permissions; ////using System.IO; ////using Microsoft.Win32; ////using Microsoft.Win32.SafeHandles; using System.Runtime.InteropServices; ////using System.Runtime.Versioning; ////using System.Security.AccessControl; [HostProtection( Synchronization = true, ExternalThreading = true )] public class EventWaitHandle : WaitHandle { //// [ResourceExposure( ResourceScope.None )] //// [ResourceConsumption( ResourceScope.Machine, ResourceScope.Machine )] [MethodImpl( MethodImplOptions.InternalCall )] public extern EventWaitHandle( bool initialState, EventResetMode mode ); //// : this( initialState, mode, null ) //// { //// } //// [SecurityPermissionAttribute( SecurityAction.LinkDemand, Flags = SecurityPermissionFlag.UnmanagedCode )] //// [ResourceExposure( ResourceScope.Machine )] //// [ResourceConsumption( ResourceScope.Machine )] //// public EventWaitHandle( bool initialState, EventResetMode mode, string name ) //// { //// if(name != null && name.Length > System.IO.Path.MAX_PATH) //// { //// throw new ArgumentException( Environment.GetResourceString( "Argument_WaitHandleNameTooLong", name ) ); //// } //// //// SafeWaitHandle handle = null; //// switch(mode) //// { //// case EventResetMode.ManualReset: //// handle = Win32Native.CreateEvent( null, true, initialState, name ); //// break; //// //// case EventResetMode.AutoReset: //// handle = Win32Native.CreateEvent( null, false, initialState, name ); //// break; //// //// default: //// throw new ArgumentException( Environment.GetResourceString( "Argument_InvalidFlag", name ) ); //// }; //// //// if(handle.IsInvalid) //// { //// int errorCode = Marshal.GetLastWin32Error(); //// //// handle.SetHandleAsInvalid(); //// //// if(name != null && name.Length != 0 && errorCode == Win32Native.ERROR_INVALID_HANDLE) //// { //// throw new WaitHandleCannotBeOpenedException( Environment.GetResourceString( "Threading.WaitHandleCannotBeOpenedException_InvalidHandle", name ) ); //// } //// //// __Error.WinIOError( errorCode, "" ); //// } //// //// SetHandleInternal( handle ); //// } //// //// [SecurityPermissionAttribute( SecurityAction.LinkDemand, Flags = SecurityPermissionFlag.UnmanagedCode )] //// [ResourceExposure( ResourceScope.Machine )] //// [ResourceConsumption( ResourceScope.Machine )] //// public EventWaitHandle( bool initialState, EventResetMode mode, string name, out bool createdNew ) //// : this( initialState, mode, name, out createdNew, null ) //// { //// } //// //// [SecurityPermissionAttribute( SecurityAction.LinkDemand, Flags = SecurityPermissionFlag.UnmanagedCode )] //// [ResourceExposure( ResourceScope.Machine )] //// [ResourceConsumption( ResourceScope.Machine )] //// public unsafe EventWaitHandle( bool initialState, EventResetMode mode, string name, out bool createdNew, EventWaitHandleSecurity eventSecurity ) //// { //// if(name != null && name.Length > System.IO.Path.MAX_PATH) //// { //// throw new ArgumentException( Environment.GetResourceString( "Argument_WaitHandleNameTooLong", name ) ); //// } //// //// Win32Native.SECURITY_ATTRIBUTES secAttrs = null; //// //// // For ACL's, get the security descriptor from the EventWaitHandleSecurity. //// if(eventSecurity != null) //// { //// secAttrs = new Win32Native.SECURITY_ATTRIBUTES(); //// secAttrs.nLength = (int)Marshal.SizeOf( secAttrs ); //// //// byte[] sd = eventSecurity.GetSecurityDescriptorBinaryForm(); //// byte* pSecDescriptor = stackalloc byte[sd.Length]; //// Buffer.memcpy( sd, 0, pSecDescriptor, 0, sd.Length ); //// secAttrs.pSecurityDescriptor = pSecDescriptor; //// } //// //// SafeWaitHandle handle = null; //// Boolean isManualReset; //// switch(mode) //// { //// case EventResetMode.ManualReset: //// isManualReset = true; //// break; //// //// case EventResetMode.AutoReset: //// isManualReset = false; //// break; //// //// default: //// throw new ArgumentException( Environment.GetResourceString( "Argument_InvalidFlag", name ) ); //// }; //// //// handle = Win32Native.CreateEvent( secAttrs, isManualReset, initialState, name ); //// //// int errorCode = Marshal.GetLastWin32Error(); //// //// if(handle.IsInvalid) //// { //// handle.SetHandleAsInvalid(); //// //// if(name != null && name.Length != 0 && errorCode == Win32Native.ERROR_INVALID_HANDLE) //// { //// throw new WaitHandleCannotBeOpenedException( Environment.GetResourceString( "Threading.WaitHandleCannotBeOpenedException_InvalidHandle", name ) ); //// } //// //// __Error.WinIOError( errorCode, name ); //// } //// //// createdNew = errorCode != Win32Native.ERROR_ALREADY_EXISTS; //// SetHandleInternal( handle ); //// } //// //// [ResourceExposure( ResourceScope.Machine )] //// [ResourceConsumption( ResourceScope.Machine )] //// private EventWaitHandle( SafeWaitHandle handle ) //// { //// SetHandleInternal( handle ); //// } //// //// [SecurityPermissionAttribute( SecurityAction.LinkDemand, Flags = SecurityPermissionFlag.UnmanagedCode )] //// [ResourceExposure( ResourceScope.Machine )] //// [ResourceConsumption( ResourceScope.Machine )] //// public static EventWaitHandle OpenExisting( string name ) //// { //// return OpenExisting( name, EventWaitHandleRights.Modify | EventWaitHandleRights.Synchronize ); //// } //// //// [SecurityPermissionAttribute( SecurityAction.LinkDemand, Flags = SecurityPermissionFlag.UnmanagedCode )] //// [ResourceExposure( ResourceScope.Machine )] //// [ResourceConsumption( ResourceScope.Machine )] //// public static EventWaitHandle OpenExisting( string name, EventWaitHandleRights rights ) //// { //// if(name == null) //// { //// throw new ArgumentNullException( "name", Environment.GetResourceString( "ArgumentNull_WithParamName" ) ); //// } //// //// if(name.Length == 0) //// { //// throw new ArgumentException( Environment.GetResourceString( "Argument_EmptyName" ), "name" ); //// } //// //// if(name != null && name.Length > System.IO.Path.MAX_PATH) //// { //// throw new ArgumentException( Environment.GetResourceString( "Argument_WaitHandleNameTooLong", name ) ); //// } //// //// //// SafeWaitHandle myHandle = Win32Native.OpenEvent( (int)rights, false, name ); //// //// if(myHandle.IsInvalid) //// { //// int errorCode = Marshal.GetLastWin32Error(); //// //// if(errorCode == Win32Native.ERROR_FILE_NOT_FOUND || errorCode == Win32Native.ERROR_INVALID_NAME) //// { //// throw new WaitHandleCannotBeOpenedException(); //// } //// //// if(name != null && name.Length != 0 && errorCode == Win32Native.ERROR_INVALID_HANDLE) //// { //// throw new WaitHandleCannotBeOpenedException( Environment.GetResourceString( "Threading.WaitHandleCannotBeOpenedException_InvalidHandle", name ) ); //// } //// //// //this is for passed through Win32Native Errors //// __Error.WinIOError( errorCode, "" ); //// } //// //// return new EventWaitHandle( myHandle ); //// } [MethodImpl( MethodImplOptions.InternalCall )] public extern bool Reset(); //// { //// bool res = Win32Native.ResetEvent( safeWaitHandle ); //// if(!res) //// { //// __Error.WinIOError(); //// } //// //// return res; //// } [MethodImpl( MethodImplOptions.InternalCall )] public extern bool Set(); //// { //// bool res = Win32Native.SetEvent( safeWaitHandle ); //// if(!res) //// { //// __Error.WinIOError(); //// } //// //// return res; //// } //// //// public EventWaitHandleSecurity GetAccessControl() //// { //// return new EventWaitHandleSecurity( safeWaitHandle, AccessControlSections.Access | AccessControlSections.Owner | AccessControlSections.Group ); //// } //// //// public void SetAccessControl( EventWaitHandleSecurity eventSecurity ) //// { //// if(eventSecurity == null) //// { //// throw new ArgumentNullException( "eventSecurity" ); //// } //// //// eventSecurity.Persist( safeWaitHandle ); //// } } } ================================================ FILE: Zelig/Zelig/RunTime/Framework/mscorlib/System/Threading/Interlocked.cs ================================================ // ==++== // // Copyright (c) Microsoft Corporation. All rights reserved. // // ==--== namespace System.Threading { using System; ////using System.Security.Permissions; using System.Runtime.CompilerServices; using System.Runtime.ConstrainedExecution; ////using System.Runtime.Versioning; // After much discussion, we decided the Interlocked class doesn't need // any HPA's for synchronization or external threading. They hurt C#'s // codegen for the yield keyword, and arguably they didn't protect much. // Instead, they penalized people (and compilers) for writing threadsafe // code. public static class Interlocked { /****************************** * Increment * Implemented: int * long *****************************/ //// [ResourceExposure( ResourceScope.None )] [MethodImpl( MethodImplOptions.InternalCall )] //// [ReliabilityContract( Consistency.WillNotCorruptState, Cer.Success )] public static extern int Increment( ref int location ); //// [ResourceExposure( ResourceScope.None )] [MethodImpl( MethodImplOptions.InternalCall )] public static extern long Increment( ref long location ); /****************************** * Decrement * Implemented: int * long *****************************/ //// [ResourceExposure( ResourceScope.None )] [MethodImpl( MethodImplOptions.InternalCall )] //// [ReliabilityContract( Consistency.WillNotCorruptState, Cer.Success )] public static extern int Decrement( ref int location ); //// [ResourceExposure( ResourceScope.None )] [MethodImpl( MethodImplOptions.InternalCall )] public static extern long Decrement( ref long location ); /****************************** * Exchange * Implemented: int * long * float * double * Object * IntPtr *****************************/ //// [ResourceExposure( ResourceScope.None )] [MethodImpl( MethodImplOptions.InternalCall )] //// [ReliabilityContract( Consistency.WillNotCorruptState, Cer.Success )] public static extern int Exchange( ref int location1, int value ); //// [ResourceExposure( ResourceScope.None )] [MethodImpl( MethodImplOptions.InternalCall )] public static extern long Exchange( ref long location1, long value ); //// [ResourceExposure( ResourceScope.None )] [MethodImpl( MethodImplOptions.InternalCall )] public static extern float Exchange( ref float location1, float value ); //// [ResourceExposure( ResourceScope.None )] [MethodImpl( MethodImplOptions.InternalCall )] public static extern double Exchange( ref double location1, double value ); //// [ResourceExposure( ResourceScope.None )] [MethodImpl( MethodImplOptions.InternalCall )] //// [ReliabilityContract( Consistency.WillNotCorruptState, Cer.Success )] public static extern Object Exchange( ref Object location1, Object value ); //// [ResourceExposure( ResourceScope.None )] [MethodImpl( MethodImplOptions.InternalCall )] //// [ReliabilityContract( Consistency.WillNotCorruptState, Cer.Success )] public static extern IntPtr Exchange( ref IntPtr location1, IntPtr value ); //// [ReliabilityContract( Consistency.WillNotCorruptState, Cer.Success )] [MethodImpl( MethodImplOptions.InternalCall )] public static extern T Exchange( ref T location1, T value ) where T : class; //// { //// _Exchange( __makeref(location1), __makeref(value) ); //// //Since value is a local we use trash its data on return //// // The Exchange replaces the data with new data //// // so after the return "value" contains the original location1 //// //See ExchangeGeneric for more details //// return value; //// } //// //// [ResourceExposure( ResourceScope.None )] //// [MethodImpl( MethodImplOptions.InternalCall )] //// [ReliabilityContract( Consistency.WillNotCorruptState, Cer.Success )] //// private static extern void _Exchange( TypedReference location1, TypedReference value ); /****************************** * CompareExchange * Implemented: int * long * float * double * Object * IntPtr *****************************/ //// [ResourceExposure( ResourceScope.None )] [MethodImpl( MethodImplOptions.InternalCall )] //// [ReliabilityContract( Consistency.WillNotCorruptState, Cer.Success )] public static extern int CompareExchange( ref int location1, int value, int comparand ); //// [ResourceExposure( ResourceScope.None )] [MethodImpl( MethodImplOptions.InternalCall )] public static extern long CompareExchange( ref long location1, long value, long comparand ); //// [ResourceExposure( ResourceScope.None )] [MethodImpl( MethodImplOptions.InternalCall )] public static extern float CompareExchange( ref float location1, float value, float comparand ); //// [ResourceExposure( ResourceScope.None )] [MethodImpl( MethodImplOptions.InternalCall )] public static extern double CompareExchange( ref double location1, double value, double comparand ); //// [ResourceExposure( ResourceScope.None )] [MethodImpl( MethodImplOptions.InternalCall )] //// [ReliabilityContract( Consistency.WillNotCorruptState, Cer.Success )] public static extern Object CompareExchange( ref Object location1, Object value, Object comparand ); //// [ResourceExposure( ResourceScope.None )] [MethodImpl( MethodImplOptions.InternalCall )] //// [ReliabilityContract( Consistency.WillNotCorruptState, Cer.Success )] public static extern IntPtr CompareExchange( ref IntPtr location1, IntPtr value, IntPtr comparand ); //// [ReliabilityContract( Consistency.WillNotCorruptState, Cer.Success )] [MethodImpl( MethodImplOptions.InternalCall )] public static extern T CompareExchange( ref T location1, T value, T comparand ) where T : class; //// { //// _CompareExchange( __makeref(location1), __makeref(value), comparand ); //// //Since value is a local we use trash its data on return //// // The Exchange replaces the data with new data //// // so after the return "value" contains the original location1 //// //See CompareExchangeGeneric for more details //// return value; //// } //// //// [ResourceExposure( ResourceScope.None )] //// [MethodImpl( MethodImplOptions.InternalCall )] //// [ReliabilityContract( Consistency.WillNotCorruptState, Cer.Success )] //// private static extern void _CompareExchange( TypedReference location1, TypedReference value, Object comparand ); /****************************** * Add * Implemented: int * long *****************************/ //// [ResourceExposure( ResourceScope.None )] //// [MethodImpl( MethodImplOptions.InternalCall )] //// [ReliabilityContract( Consistency.WillNotCorruptState, Cer.Success )] //// internal static extern int ExchangeAdd( ref int location1, int value ); //// //// [ResourceExposure( ResourceScope.None )] //// [MethodImpl( MethodImplOptions.InternalCall )] //// internal static extern long ExchangeAdd( ref long location1, long value ); [MethodImpl( MethodImplOptions.InternalCall )] //// [ReliabilityContract( Consistency.WillNotCorruptState, Cer.Success )] public static extern int Add( ref int location1, int value ); //// { //// return ExchangeAdd( ref location1, value ) + value; //// } [MethodImpl( MethodImplOptions.InternalCall )] //// [ReliabilityContract( Consistency.WillNotCorruptState, Cer.Success )] public static extern long Add( ref long location1, long value ); //// { //// return ExchangeAdd( ref location1, value ) + value; //// } /****************************** * Read *****************************/ public static long Read( ref long location ) { return Interlocked.CompareExchange( ref location, 0, 0 ); } } } ================================================ FILE: Zelig/Zelig/RunTime/Framework/mscorlib/System/Threading/ManualResetEvent.cs ================================================ // ==++== // // Copyright (c) Microsoft Corporation. All rights reserved. // // ==--== /*============================================================================= ** ** Class: ManualResetEvent ** ** ** Purpose: An example of a WaitHandle class ** ** =============================================================================*/ namespace System.Threading { using System; using System.Security.Permissions; using System.Runtime.InteropServices; [HostProtection( Synchronization = true, ExternalThreading = true )] public sealed class ManualResetEvent : EventWaitHandle { public ManualResetEvent( bool initialState ) : base( initialState, EventResetMode.ManualReset ) { } } } ================================================ FILE: Zelig/Zelig/RunTime/Framework/mscorlib/System/Threading/Monitor.cs ================================================ // ==++== // // Copyright (c) Microsoft Corporation. All rights reserved. // // ==--== /*============================================================================= ** ** Class: Monitor ** ** ** Purpose: Synchronizes access to a shared resource or region of code in a multi-threaded ** program. ** ** =============================================================================*/ namespace System.Threading { using System; using System.Security.Permissions; ////using System.Runtime.Remoting; using System.Threading; using System.Runtime.CompilerServices; using System.Runtime.ConstrainedExecution; ////using System.Runtime.Versioning; [HostProtection( Synchronization = true, ExternalThreading = true )] public static class Monitor { /*========================================================================= ** Obtain the monitor lock of obj. Will block if another thread holds the lock ** Will not block if the current thread holds the lock, ** however the caller must ensure that the same number of Exit ** calls are made as there were Enter calls. ** ** Exceptions: ArgumentNullException if object is null. =========================================================================*/ //// [ResourceExposure( ResourceScope.None )] [MethodImpl( MethodImplOptions.InternalCall )] public static extern void Enter( Object obj ); //// // This should be made public in a future version. //// // Use a ref bool instead of out to ensure that unverifiable code must //// // initialize this value to something. If we used out, the value //// // could be uninitialized if we threw an exception in our prolog. //// [ResourceExposure( ResourceScope.None )] //// [MethodImpl( MethodImplOptions.InternalCall )] //// internal static extern void ReliableEnter( Object obj, ref bool tookLock ); public static void Enter( Object obj, ref bool lockTaken ) { if(obj == null) { throw new ArgumentNullException(); } // The input must be false. if (lockTaken == true) { lockTaken = false; throw new ArgumentException(); } //The output is true if the lock is acquired; otherwise, the output is // false. The output is set even if an exception occurs during the attempt // to acquire the lock. Enter(obj); lockTaken = true; } /*========================================================================= ** Release the monitor lock. If one or more threads are waiting to acquire the ** lock, and the current thread has executed as many Exits as ** Enters, one of the threads will be unblocked and allowed to proceed. ** ** Exceptions: ArgumentNullException if object is null. ** SynchronizationLockException if the current thread does not ** own the lock. =========================================================================*/ //// [ResourceExposure( ResourceScope.None )] //// [ReliabilityContract( Consistency.WillNotCorruptState, Cer.Success )] [MethodImpl( MethodImplOptions.InternalCall )] public static extern void Exit( Object obj ); /*========================================================================= ** Similar to Enter, but will never block. That is, if the current thread can ** acquire the monitor lock without blocking, it will do so and TRUE will ** be returned. Otherwise FALSE will be returned. ** ** Exceptions: ArgumentNullException if object is null. =========================================================================*/ public static bool TryEnter( Object obj ) { return TryEnterTimeout( obj, 0 ); } /*========================================================================= ** Version of TryEnter that will block, but only up to a timeout period ** expressed in milliseconds. If timeout == Timeout.Infinite the method ** becomes equivalent to Enter. ** ** Exceptions: ArgumentNullException if object is null. ** ArgumentException if timeout < 0. =========================================================================*/ public static bool TryEnter( Object obj, int millisecondsTimeout ) { return TryEnterTimeout( obj, millisecondsTimeout ); } public static bool TryEnter( Object obj, TimeSpan timeout ) { long tm = (long)timeout.TotalMilliseconds; if(tm < -1 || tm > (long)Int32.MaxValue) { #if EXCEPTION_STRINGS throw new ArgumentOutOfRangeException( "timeout", Environment.GetResourceString( "ArgumentOutOfRange_NeedNonNegOrNegative1" ) ); #else throw new ArgumentOutOfRangeException(); #endif } return TryEnterTimeout( obj, (int)tm ); } //// [ResourceExposure( ResourceScope.None )] [MethodImpl( MethodImplOptions.InternalCall )] private static extern bool TryEnterTimeout( Object obj, int timeout ); /*======================================================================== ** Waits for notification from the object (via a Pulse/PulseAll). ** timeout indicates how long to wait before the method returns. ** This method acquires the monitor waithandle for the object ** If this thread holds the monitor lock for the object, it releases it. ** On exit from the method, it obtains the monitor lock back. ** If exitContext is true then the synchronization domain for the context ** (if in a synchronized context) is exited before the wait and reacquired ** ** Exceptions: ArgumentNullException if object is null. ========================================================================*/ //// [ResourceExposure( ResourceScope.None )] [MethodImpl( MethodImplOptions.InternalCall )] private static extern bool ObjWait( bool exitContext, int millisecondsTimeout, Object obj ); public static bool Wait( Object obj, int millisecondsTimeout, bool exitContext ) { if(obj == null) { #if EXCEPTION_STRINGS throw new ArgumentNullException( "obj" ); #else throw new ArgumentNullException(); #endif } return ObjWait( exitContext, millisecondsTimeout, obj ); } public static bool Wait( Object obj, TimeSpan timeout, bool exitContext ) { long tm = (long)timeout.TotalMilliseconds; if(tm < -1 || tm > (long)Int32.MaxValue) { #if EXCEPTION_STRINGS throw new ArgumentOutOfRangeException( "timeout", Environment.GetResourceString( "ArgumentOutOfRange_NeedNonNegOrNegative1" ) ); #else throw new ArgumentOutOfRangeException(); #endif } return Wait( obj, (int)tm, exitContext ); } public static bool Wait( Object obj, int millisecondsTimeout ) { return Wait( obj, millisecondsTimeout, false ); } public static bool Wait( Object obj, TimeSpan timeout ) { long tm = (long)timeout.TotalMilliseconds; if(tm < -1 || tm > (long)Int32.MaxValue) { #if EXCEPTION_STRINGS throw new ArgumentOutOfRangeException( "timeout", Environment.GetResourceString( "ArgumentOutOfRange_NeedNonNegOrNegative1" ) ); #else throw new ArgumentOutOfRangeException(); #endif } return Wait( obj, (int)tm, false ); } public static bool Wait( Object obj ) { return Wait( obj, Timeout.Infinite, false ); } /*======================================================================== ** Sends a notification to a single waiting object. * Exceptions: SynchronizationLockException if this method is not called inside * a synchronized block of code. ========================================================================*/ //// [ResourceExposure( ResourceScope.None )] [MethodImpl( MethodImplOptions.InternalCall )] private static extern void ObjPulse( Object obj ); public static void Pulse( Object obj ) { if(obj == null) { #if EXCEPTION_STRINGS throw new ArgumentNullException( "obj" ); #else throw new ArgumentNullException(); #endif } ObjPulse( obj ); } /*======================================================================== ** Sends a notification to all waiting objects. ========================================================================*/ //// [ResourceExposure( ResourceScope.None )] [MethodImpl( MethodImplOptions.InternalCall )] private static extern void ObjPulseAll( Object obj ); public static void PulseAll( Object obj ) { if(obj == null) { #if EXCEPTION_STRINGS throw new ArgumentNullException( "obj" ); #else throw new ArgumentNullException(); #endif } ObjPulseAll( obj ); } } } ================================================ FILE: Zelig/Zelig/RunTime/Framework/mscorlib/System/Threading/Mutex.cs ================================================ // ==++== // // Copyright (c) Microsoft Corporation. All rights reserved. // // ==--== /*============================================================================= ** ** Class: Mutex ** ** ** Purpose: synchronization primitive that can also be used for interprocess synchronization ** ** =============================================================================*/ namespace System.Threading { using System; using System.Threading; using System.Runtime.CompilerServices; using System.Security.Permissions; ////using System.IO; ////using Microsoft.Win32; ////using Microsoft.Win32.SafeHandles; using System.Runtime.InteropServices; using System.Runtime.ConstrainedExecution; ////using System.Runtime.Versioning; ////using System.Security.Principal; ////using System.Security; ////using System.Security.AccessControl; [HostProtection( Synchronization = true, ExternalThreading = true )] public sealed class Mutex : WaitHandle { //// static bool dummyBool; //// //// [SecurityPermissionAttribute( SecurityAction.LinkDemand, Flags = SecurityPermissionFlag.UnmanagedCode )] //// [ReliabilityContract( Consistency.WillNotCorruptState, Cer.MayFail )] //// [ResourceExposure( ResourceScope.None )] //// [ResourceConsumption( ResourceScope.Machine, ResourceScope.Machine )] //// public Mutex( bool initiallyOwned, String name, out bool createdNew ) //// : this( initiallyOwned, name, out createdNew, null ) //// { //// } //// //// [SecurityPermissionAttribute( SecurityAction.LinkDemand, Flags = SecurityPermissionFlag.UnmanagedCode )] //// [ReliabilityContract( Consistency.WillNotCorruptState, Cer.MayFail )] //// [ResourceExposure( ResourceScope.Machine )] //// [ResourceConsumption( ResourceScope.Machine )] //// public unsafe Mutex( bool initiallyOwned, String name, out bool createdNew, MutexSecurity mutexSecurity ) //// { //// if(name != null && name.Length < System.IO.Path.MAX_PATH) //// { //// throw new ArgumentException( Environment.GetResourceString( "Argument_WaitHandleNameTooLong", name ) ); //// } //// //// Win32Native.SECURITY_ATTRIBUTES secAttrs = null; //// //// // For ACL's, get the security descriptor from the MutexSecurity. //// if(mutexSecurity != null) //// { //// secAttrs = new Win32Native.SECURITY_ATTRIBUTES(); //// secAttrs.nLength = (int)Marshal.SizeOf( secAttrs ); //// //// byte[] sd = mutexSecurity.GetSecurityDescriptorBinaryForm(); //// byte* pSecDescriptor = stackalloc byte[sd.Length]; //// Buffer.memcpy( sd, 0, pSecDescriptor, 0, sd.Length ); //// secAttrs.pSecurityDescriptor = pSecDescriptor; //// } //// //// SafeWaitHandle mutexHandle = null; //// bool newMutex = false; //// //// RuntimeHelpers.CleanupCode cleanupCode = new RuntimeHelpers.CleanupCode( MutexCleanupCode ); //// MutexCleanupInfo cleanupInfo = new MutexCleanupInfo ( mutexHandle, false ); //// //// RuntimeHelpers.ExecuteCodeWithGuaranteedCleanup( //// delegate( object userData ) //// { // try block //// RuntimeHelpers.PrepareConstrainedRegions(); //// try //// { //// } //// finally //// { //// if(initiallyOwned) //// { //// cleanupInfo.inCriticalRegion = true; //// //// Thread.BeginThreadAffinity(); //// Thread.BeginCriticalRegion(); //// } //// } //// //// int errorCode = 0; //// RuntimeHelpers.PrepareConstrainedRegions(); //// try //// { //// } //// finally //// { //// errorCode = CreateMutexHandle( initiallyOwned, name, secAttrs, out mutexHandle ); //// } //// //// if(mutexHandle.IsInvalid) //// { //// mutexHandle.SetHandleAsInvalid(); //// if(name != null && name.Length != 0 && errorCode == Win32Native.ERROR_INVALID_HANDLE) //// { //// throw new WaitHandleCannotBeOpenedException( Environment.GetResourceString( "Threading.WaitHandleCannotBeOpenedException_InvalidHandle", name ) ); //// } //// //// __Error.WinIOError( errorCode, name ); //// } //// //// newMutex = errorCode != Win32Native.ERROR_ALREADY_EXISTS; //// //// SetHandleInternal( mutexHandle ); //// mutexHandle.SetAsMutex(); //// //// hasThreadAffinity = true; //// //// }, //// cleanupCode, //// cleanupInfo ); //// //// createdNew = newMutex; //// } //// //// [PrePrepareMethod] //// private void MutexCleanupCode( Object userData, bool exceptionThrown ) //// { //// MutexCleanupInfo cleanupInfo = (MutexCleanupInfo)userData; //// //// // If hasThreadAffinity isnt true, weve thrown an exception in the above try, and we must free the mutex //// // on this OS thread before ending our thread affninity. //// if(!hasThreadAffinity) //// { //// if(cleanupInfo.mutexHandle != null && !cleanupInfo.mutexHandle.IsInvalid) //// { //// if(cleanupInfo.inCriticalRegion) //// { //// Win32Native.ReleaseMutex( cleanupInfo.mutexHandle ); //// } //// //// cleanupInfo.mutexHandle.Dispose(); //// } //// //// if(cleanupInfo.inCriticalRegion) //// { //// Thread.EndCriticalRegion(); //// Thread.EndThreadAffinity(); //// } //// } //// } //// //// internal class MutexCleanupInfo //// { //// internal SafeWaitHandle mutexHandle; //// internal bool inCriticalRegion; //// //// internal MutexCleanupInfo( SafeWaitHandle mutexHandle, bool inCriticalRegion ) //// { //// this.mutexHandle = mutexHandle; //// this.inCriticalRegion = inCriticalRegion; //// } //// } //// //// [SecurityPermissionAttribute( SecurityAction.LinkDemand, Flags = SecurityPermissionFlag.UnmanagedCode )] //// [ReliabilityContract( Consistency.WillNotCorruptState, Cer.MayFail )] //// [ResourceExposure( ResourceScope.Machine )] //// [ResourceConsumption( ResourceScope.Machine )] //// public Mutex( bool initiallyOwned, String name ) : this( initiallyOwned, name, out dummyBool ) //// { //// } //// //// [ReliabilityContract( Consistency.WillNotCorruptState, Cer.MayFail )] //// [ResourceExposure( ResourceScope.None )] //// [ResourceConsumption( ResourceScope.Machine, ResourceScope.Machine )] //// public Mutex( bool initiallyOwned ) : this( initiallyOwned, null, out dummyBool ) //// { //// } //// //// [ReliabilityContract( Consistency.WillNotCorruptState, Cer.MayFail )] //// [ResourceExposure( ResourceScope.None )] //// [ResourceConsumption( ResourceScope.Machine, ResourceScope.Machine )] //// public Mutex() : this( false, null, out dummyBool ) //// { //// } //// //// [ResourceExposure( ResourceScope.Machine )] //// [ResourceConsumption( ResourceScope.Machine )] //// [ReliabilityContract( Consistency.WillNotCorruptState, Cer.MayFail )] //// private Mutex( SafeWaitHandle handle ) //// { //// SetHandleInternal( handle ); //// handle.SetAsMutex(); //// hasThreadAffinity = true; //// } //// //// [SecurityPermissionAttribute( SecurityAction.LinkDemand, Flags = SecurityPermissionFlag.UnmanagedCode )] //// [ResourceExposure( ResourceScope.Machine )] //// [ResourceConsumption( ResourceScope.Machine )] //// public static Mutex OpenExisting( string name ) //// { //// return OpenExisting( name, MutexRights.Modify | MutexRights.Synchronize ); //// } //// //// [SecurityPermissionAttribute( SecurityAction.LinkDemand, Flags = SecurityPermissionFlag.UnmanagedCode )] //// [ResourceExposure( ResourceScope.Machine )] //// [ResourceConsumption( ResourceScope.Machine )] //// public static Mutex OpenExisting( string name, MutexRights rights ) //// { //// if(name == null) //// { //// throw new ArgumentNullException( "name", Environment.GetResourceString( "ArgumentNull_WithParamName" ) ); //// } //// //// if(name.Length == 0) //// { //// throw new ArgumentException( Environment.GetResourceString( "Argument_EmptyName" ), "name" ); //// } //// if(name.Length > System.IO.Path.MAX_PATH) //// { //// throw new ArgumentException( Environment.GetResourceString( "Argument_WaitHandleNameTooLong", name ) ); //// } //// //// //// // To allow users to view & edit the ACL's, call OpenMutex //// // with parameters to allow us to view & edit the ACL. This will //// // fail if we don't have permission to view or edit the ACL's. //// // If that happens, ask for less permissions. //// SafeWaitHandle myHandle = Win32Native.OpenMutex( (int)rights, false, name ); //// //// int errorCode = 0; //// if(myHandle.IsInvalid) //// { //// errorCode = Marshal.GetLastWin32Error(); //// //// if(Win32Native.ERROR_FILE_NOT_FOUND == errorCode || Win32Native.ERROR_INVALID_NAME == errorCode) //// { //// throw new WaitHandleCannotBeOpenedException(); //// } //// //// if(null != name && 0 != name.Length && Win32Native.ERROR_INVALID_HANDLE == errorCode) //// { //// throw new WaitHandleCannotBeOpenedException( Environment.GetResourceString( "Threading.WaitHandleCannotBeOpenedException_InvalidHandle", name ) ); //// } //// //// // this is for passed through Win32Native Errors //// __Error.WinIOError( errorCode, name ); //// } //// //// return new Mutex( myHandle ); //// } //// //// // Note: To call ReleaseMutex, you must have an ACL granting you //// // MUTEX_MODIFY_STATE rights (0x0001). The other interesting value //// // in a Mutex's ACL is MUTEX_ALL_ACCESS (0x1F0001). //// [ReliabilityContract( Consistency.WillNotCorruptState, Cer.MayFail )] //// public void ReleaseMutex() //// { //// if(Win32Native.ReleaseMutex( safeWaitHandle )) //// { //// Thread.EndCriticalRegion(); //// Thread.EndThreadAffinity(); //// } //// else //// { //// throw new ApplicationException( Environment.GetResourceString( "Arg_SynchronizationLockException" ) ); //// } //// } //// //// [ResourceExposure( ResourceScope.Machine )] //// [ResourceConsumption( ResourceScope.Machine )] //// [ReliabilityContract( Consistency.WillNotCorruptState, Cer.MayFail )] //// static int CreateMutexHandle( bool initiallyOwned, String name, Win32Native.SECURITY_ATTRIBUTES securityAttribute, out SafeWaitHandle mutexHandle ) //// { //// int errorCode; //// bool fReservedMutexObtained = false; //// bool fAffinity = false; //// //// while(true) //// { //// mutexHandle = Win32Native.CreateMutex( securityAttribute, initiallyOwned, name ); //// errorCode = Marshal.GetLastWin32Error(); //// if(!mutexHandle.IsInvalid) //// { //// break; //// } //// //// if(errorCode == Win32Native.ERROR_ACCESS_DENIED) //// { //// // If a mutex with the name already exists, OS will try to open it with FullAccess. //// // It might fail if we don't have enough access. In that case, we try to open the mutex will modify and synchronize access. //// // //// //// RuntimeHelpers.PrepareConstrainedRegions(); //// try //// { //// try //// { //// } //// finally //// { //// Thread.BeginThreadAffinity(); //// fAffinity = true; //// } //// AcquireReservedMutex( ref fReservedMutexObtained ); //// mutexHandle = Win32Native.OpenMutex( Win32Native.MUTEX_MODIFY_STATE | Win32Native.SYNCHRONIZE, false, name ); //// if(!mutexHandle.IsInvalid) //// { //// errorCode = Win32Native.ERROR_ALREADY_EXISTS; //// } //// else //// { //// errorCode = Marshal.GetLastWin32Error(); //// } //// } //// finally //// { //// if(fReservedMutexObtained) //// { //// ReleaseReservedMutex(); //// } //// if(fAffinity) //// { //// Thread.EndThreadAffinity(); //// } //// } //// //// // There could be a race here, the other owner of the mutex can free the mutex, //// // We need to retry creation in that case. //// if(errorCode != Win32Native.ERROR_FILE_NOT_FOUND) //// { //// if(errorCode == Win32Native.ERROR_SUCCESS) //// { //// errorCode = Win32Native.ERROR_ALREADY_EXISTS; //// } //// break; //// } //// } //// else //// { //// break; //// } //// } //// return errorCode; //// } //// //// public MutexSecurity GetAccessControl() //// { //// return new MutexSecurity( safeWaitHandle, AccessControlSections.Access | AccessControlSections.Owner | AccessControlSections.Group ); //// } //// //// public void SetAccessControl( MutexSecurity mutexSecurity ) //// { //// if(mutexSecurity == null) //// throw new ArgumentNullException( "mutexSecurity" ); //// //// mutexSecurity.Persist( safeWaitHandle ); //// } //// //// //// // Enables workaround for known OS bug at //// // http://support.microsoft.com/default.aspx?scid=kb;en-us;889318 //// // One machine-wide mutex serializes all OpenMutex and CloseHandle operations. //// [ResourceExposure( ResourceScope.None )] //// [ResourceConsumption( ResourceScope.Machine, ResourceScope.Machine )] //// [ReliabilityContract( Consistency.WillNotCorruptState, Cer.MayFail )] //// internal static unsafe void AcquireReservedMutex( ref bool bHandleObtained ) //// { //// SafeWaitHandle mutexHandle = null; //// int errorCode; //// //// bHandleObtained = false; //// if(s_ReservedMutex == null) //// { //// //// // Create a maximally-permissive security descriptor, to ensure we never get an //// // ACCESS_DENIED error when calling CreateMutex //// MutexSecurity sec = new MutexSecurity(); //// SecurityIdentifier everyoneSid = new SecurityIdentifier( WellKnownSidType.WorldSid, null ); //// sec.AddAccessRule( new MutexAccessRule( everyoneSid, MutexRights.FullControl, AccessControlType.Allow ) ); //// //// // For ACL's, get the security descriptor from the MutexSecurity. //// Win32Native.SECURITY_ATTRIBUTES secAttrs = new Win32Native.SECURITY_ATTRIBUTES(); //// secAttrs.nLength = (int)Marshal.SizeOf( secAttrs ); //// //// byte[] sd = sec.GetSecurityDescriptorBinaryForm(); //// byte* bytesOnStack = stackalloc byte[sd.Length]; //// Buffer.memcpy( sd, 0, bytesOnStack, 0, sd.Length ); //// secAttrs.pSecurityDescriptor = bytesOnStack; //// //// RuntimeHelpers.PrepareConstrainedRegions(); //// try //// { //// } //// finally //// { //// mutexHandle = Win32Native.CreateMutex( secAttrs, false, c_ReservedMutexName ); //// //// // need to set specially, since this mutex cannot lock on itself while closing itself. //// mutexHandle.SetAsReservedMutex(); //// } //// //// errorCode = Marshal.GetLastWin32Error(); //// if(mutexHandle.IsInvalid) //// { //// mutexHandle.SetHandleAsInvalid(); //// __Error.WinIOError( errorCode, c_ReservedMutexName ); //// } //// //// Mutex m = new Mutex( mutexHandle ); //// //// Interlocked.CompareExchange( ref s_ReservedMutex, m, null ); //// } //// //// //// RuntimeHelpers.PrepareConstrainedRegions(); //// try //// { //// } //// finally //// { //// try //// { //// s_ReservedMutex.WaitOne(); //// bHandleObtained = true; //// } //// catch(AbandonedMutexException) //// { //// // we don't care if another process holding the Mutex was killed //// bHandleObtained = true; //// } //// } //// } //// //// [ReliabilityContract( Consistency.WillNotCorruptState, Cer.MayFail )] //// internal static void ReleaseReservedMutex() //// { //// BCLDebug.Assert( s_ReservedMutex != null, "ReleaseReservedMutex called without prior call to AcquireReservedMutex!" ); //// //// s_ReservedMutex.ReleaseMutex(); //// } } } ================================================ FILE: Zelig/Zelig/RunTime/Framework/mscorlib/System/Threading/ParameterizedThreadStart.cs ================================================ // ==++== // // Copyright (c) Microsoft Corporation. All rights reserved. // // ==--== /*============================================================================= ** ** Class: ParameterizedThreadStart ** ** ** Purpose: This class is a Delegate which defines the start method ** for starting a thread. That method must match this delegate. ** ** =============================================================================*/ namespace System.Threading { using System.Threading; ////using System.Security.Permissions; using System.Runtime.InteropServices; public delegate void ParameterizedThreadStart( object obj ); } ================================================ FILE: Zelig/Zelig/RunTime/Framework/mscorlib/System/Threading/SpinWait.cs ================================================ // Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. // =+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+ // // // // Central spin logic used across the entire code-base. // // =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=- using System; using System.Runtime.ConstrainedExecution; using System.Security.Permissions; using System.Threading; using System.Diagnostics.Contracts; using System.Diagnostics.CodeAnalysis; namespace System.Threading { // SpinWait is just a little value type that encapsulates some common spinning // logic. It ensures we always yield on single-proc machines (instead of using busy // waits), and that we work well on HT. It encapsulates a good mixture of spinning // and real yielding. It's a value type so that various areas of the engine can use // one by allocating it on the stack w/out unnecessary GC allocation overhead, e.g.: // // void f() { // SpinWait wait = new SpinWait(); // while (!p) { wait.SpinOnce(); } // ... // } // // Internally it just maintains a counter that is used to decide when to yield, etc. // // A common usage is to spin before blocking. In those cases, the NextSpinWillYield // property allows a user to decide to fall back to waiting once it returns true: // // void f() { // SpinWait wait = new SpinWait(); // while (!p) { // if (wait.NextSpinWillYield) { /* block! */ } // else { wait.SpinOnce(); } // } // ... // } /// /// Provides support for spin-based waiting. /// /// /// /// encapsulates common spinning logic. On single-processor machines, yields are /// always used instead of busy waits, and on computers with Intel processors employing Hyper-Threading /// technology, it helps to prevent hardware thread starvation. SpinWait encapsulates a good mixture of /// spinning and true yielding. /// /// /// is a value type, which means that low-level code can utilize SpinWait without /// fear of unnecessary allocation overheads. SpinWait is not generally useful for ordinary applications. /// In most cases, you should use the synchronization classes provided by the .NET Framework, such as /// . For most purposes where spin waiting is required, however, /// the type should be preferred over the method. /// /// /// While SpinWait is designed to be used in concurrent applications, it is not designed to be /// used from multiple threads concurrently. SpinWait's members are not thread-safe. If multiple /// threads must spin, each should use its own instance of SpinWait. /// /// [HostProtection(Synchronization = true, ExternalThreading = true)] public struct SpinWait { // These constants determine the frequency of yields versus spinning. The // numbers may seem fairly arbitrary, but were derived with at least some // thought in the design document. I fully expect they will need to change // over time as we gain more experience with performance. internal const int YIELD_THRESHOLD = 10; // When to switch over to a true yield. internal const int SLEEP_0_EVERY_HOW_MANY_TIMES = 5; // After how many yields should we Sleep(0)? internal const int SLEEP_1_EVERY_HOW_MANY_TIMES = 20; // After how many yields should we Sleep(1)? // The number of times we've spun already. private int m_count; /// /// Gets the number of times has been called on this instance. /// public int Count { get { return m_count; } } /// /// Gets whether the next call to will yield the processor, triggering a /// forced context switch. /// /// Whether the next call to will yield the processor, triggering a /// forced context switch. /// /// On a single-CPU machine, always yields the processor. On machines with /// multiple CPUs, may yield after an unspecified number of calls. /// public bool NextSpinWillYield { //// get { return m_count > YIELD_THRESHOLD || PlatformHelper.IsSingleProcessor; } get { return true; } } /// /// Performs a single spin. /// /// /// This is typically called in a loop, and may change in behavior based on the number of times a /// has been called thus far on this instance. /// public void SpinOnce() { if (NextSpinWillYield) { // // We must yield. // // We prefer to call Thread.Yield first, triggering a SwitchToThread. This // unfortunately doesn't consider all runnable threads on all OS SKUs. In // some cases, it may only consult the runnable threads whose ideal processor // is the one currently executing code. Thus we occasionally issue a call to // Sleep(0), which considers all runnable threads at equal priority. Even this // is insufficient since we may be spin waiting for lower priority threads to // execute; we therefore must call Sleep(1) once in a while too, which considers // all runnable threads, regardless of ideal processor and priority, but may // remove the thread from the scheduler's queue for 10+ms, if the system is // configured to use the (default) coarse-grained system timer. // #if !FEATURE_CORECLR //// CdsSyncEtwBCLProvider.Log.SpinWait_NextSpinWillYield(); #endif int yieldsSoFar = (m_count >= YIELD_THRESHOLD ? m_count - YIELD_THRESHOLD : m_count); if ((yieldsSoFar % SLEEP_1_EVERY_HOW_MANY_TIMES) == (SLEEP_1_EVERY_HOW_MANY_TIMES - 1)) { Thread.Sleep(1); } else if ((yieldsSoFar % SLEEP_0_EVERY_HOW_MANY_TIMES) == (SLEEP_0_EVERY_HOW_MANY_TIMES - 1)) { Thread.Sleep(0); } else { Thread.Yield(); } } else { // // Otherwise, we will spin. // // We do this using the CLR's SpinWait API, which is just a busy loop that // issues YIELD/PAUSE instructions to ensure multi-threaded CPUs can react // intelligently to avoid starving. (These are NOOPs on other CPUs.) We // choose a number for the loop iteration count such that each successive // call spins for longer, to reduce cache contention. We cap the total // number of spins we are willing to tolerate to reduce delay to the caller, // since we expect most callers will eventually block anyway. // Thread.SpinWait(4 << m_count); } // Finally, increment our spin counter. m_count = (m_count == int.MaxValue ? YIELD_THRESHOLD : m_count + 1); } /// /// Resets the spin counter. /// /// /// This makes and behave as though no calls /// to had been issued on this instance. If a instance /// is reused many times, it may be useful to reset it to avoid yielding too soon. /// public void Reset() { m_count = 0; } #region Static Methods /// /// Spins until the specified condition is satisfied. /// /// A delegate to be executed over and over until it returns true. /// The argument is null. public static void SpinUntil(Func condition) { #if DEBUG bool result = #endif SpinUntil(condition, Timeout.Infinite); #if DEBUG #if ENABLE_CONTRACTS Contract.Assert(result); #endif // ENABLE_CONTRACTS #endif } /// /// Spins until the specified condition is satisfied or until the specified timeout is expired. /// /// A delegate to be executed over and over until it returns true. /// /// A that represents the number of milliseconds to wait, /// or a TimeSpan that represents -1 milliseconds to wait indefinitely. /// True if the condition is satisfied within the timeout; otherwise, false /// The argument is null. /// is a negative number /// other than -1 milliseconds, which represents an infinite time-out -or- timeout is greater than /// . public static bool SpinUntil(Func condition, TimeSpan timeout) { // Validate the timeout Int64 totalMilliseconds = (Int64)timeout.TotalMilliseconds; if (totalMilliseconds < -1 || totalMilliseconds > Int32.MaxValue) { throw new System.ArgumentOutOfRangeException( "timeout", timeout, Environment.GetResourceString("SpinWait_SpinUntil_TimeoutWrong")); } // Call wait with the timeout milliseconds return SpinUntil(condition, (int)timeout.TotalMilliseconds); } /// /// Spins until the specified condition is satisfied or until the specified timeout is expired. /// /// A delegate to be executed over and over until it returns true. /// The number of milliseconds to wait, or (-1) to wait indefinitely. /// True if the condition is satisfied within the timeout; otherwise, false /// The argument is null. /// is a /// negative number other than -1, which represents an infinite time-out. public static bool SpinUntil(Func condition, int millisecondsTimeout) { if (millisecondsTimeout < Timeout.Infinite) { throw new ArgumentOutOfRangeException( "millisecondsTimeout", millisecondsTimeout, Environment.GetResourceString("SpinWait_SpinUntil_TimeoutWrong")); } if (condition == null) { throw new ArgumentNullException("condition", Environment.GetResourceString("SpinWait_SpinUntil_ArgumentNull")); } uint startTime = 0; if (millisecondsTimeout != 0 && millisecondsTimeout != Timeout.Infinite) { startTime = TimeoutHelper.GetTime(); } SpinWait spinner = new SpinWait(); while (!condition()) { if (millisecondsTimeout == 0) { return false; } spinner.SpinOnce(); if (millisecondsTimeout != Timeout.Infinite && spinner.NextSpinWillYield) { if (millisecondsTimeout <= (TimeoutHelper.GetTime() - startTime)) { return false; } } } return true; } #endregion } /// /// A helper class to capture a start time using Environment.TickCout as a time in milliseconds, also updates a given timeout bu subtracting the current time from /// the start time /// internal static class TimeoutHelper { /// /// Returns the Environment.TickCount as a start time in milliseconds as a uint, TickCount tools over from postive to negative every ~ 25 days /// then ~25 days to back to positive again, uint is sued to ignore the sign and double the range to 50 days /// /// public static uint GetTime() { return (uint)Environment.TickCount; } /// /// Helper function to measure and update the elapsed time /// /// The first time (in milliseconds) observed when the wait started /// The orginal wait timeoutout in milliseconds /// The new wait time in milliseconds, -1 if the time expired public static int UpdateTimeOut(uint startTime, int originalWaitMillisecondsTimeout) { #if ENABLE_CONTRACTS // The function must be called in case the time out is not infinite Contract.Assert(originalWaitMillisecondsTimeout != Timeout.Infinite); #endif // ENABLE_CONTRACTS uint elapsedMilliseconds = (GetTime() - startTime); // Check the elapsed milliseconds is greater than max int because this property is uint if (elapsedMilliseconds > int.MaxValue) { return 0; } // Subtract the elapsed time from the current wait time int currentWaitTimeout = originalWaitMillisecondsTimeout - (int)elapsedMilliseconds; ; if (currentWaitTimeout <= 0) { return 0; } return currentWaitTimeout; } } } ================================================ FILE: Zelig/Zelig/RunTime/Framework/mscorlib/System/Threading/Tasks/GenericTask.cs ================================================ // Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. // =+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+ // // // // A task that produces a value. // // =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=- using System; using System.Security.Permissions; using System.Diagnostics; using System.Diagnostics.Contracts; using System.Runtime.CompilerServices; // Disable the "reference to volatile field not treated as volatile" error. #pragma warning disable 0420 namespace System.Threading.Tasks { // Special internal struct that we use to signify that we are not interested in a Task's result. internal struct VoidTaskResult { } /// /// Represents an asynchronous operation that produces a result at some time in the future. /// /// /// The type of the result produced by this . /// /// /// /// instances may be created in a variety of ways. The most common approach is by /// using the task's property to retrieve a instance that can be used to create tasks for several /// purposes. For example, to create a that runs a function, the factory's StartNew /// method may be used: /// /// // C# /// var t = Task<int>.Factory.StartNew(() => GenerateResult()); /// - or - /// var t = Task.Factory.StartNew(() => GenerateResult()); /// /// ' Visual Basic /// Dim t = Task<int>.Factory.StartNew(Function() GenerateResult()) /// - or - /// Dim t = Task.Factory.StartNew(Function() GenerateResult()) /// /// /// /// The class also provides constructors that initialize the task but that do not /// schedule it for execution. For performance reasons, the StartNew method should be the /// preferred mechanism for creating and scheduling computational tasks, but for scenarios where creation /// and scheduling must be separated, the constructors may be used, and the task's /// Start /// method may then be used to schedule the task for execution at a later time. /// /// /// All members of , except for /// Dispose, are thread-safe /// and may be used from multiple threads concurrently. /// /// [HostProtection(Synchronization = true, ExternalThreading = true)] [DebuggerDisplay("Id = {Id}, Status = {Status}, Method = {DebuggerDisplayMethodDescription}, Result = {DebuggerDisplayResultDescription}")] public class Task : Task #if SUPPORT_IOBSERVABLE , IObservable #endif // SUPPORT_IOBSERVABLE { internal TResult m_result; // The value itself, if set. // Construct a promise-style task without any options. internal Task() : base() { } // Construct a pre-completed Task internal Task(TResult result) : base(false, default(CancellationToken)) { m_result = result; } /// /// Create a pre-canceled or pre-completed task. /// /// Whether the task is pre-canceled. If so, the task will be initialized to Canceled /// state. Otherwise, the task will be initialized in the RanToCompletion state. /// If not canceled, the final result of the task. /// If canceled, the token that triggered cancellation. internal Task(bool canceled, TResult result, CancellationToken cancellationToken) : base(true, cancellationToken) { m_result = result; } /// /// Initializes a new with the specified function. /// /// /// The delegate that represents the code to execute in the task. When the function has completed, /// the task's property will be set to return the result value of the function. /// /// /// The argument is null. /// public Task(Func function) : base(function, null, default(CancellationToken), TaskCreationOptions.None, InternalTaskOptions.None) { } /// /// Initializes a new with the specified function. /// /// /// The delegate that represents the code to execute in the task. When the function has completed, /// the task's property will be set to return the result value of the function. /// /// The to be assigned to this task. /// /// The argument is null. /// /// The provided CancellationToken /// has already been disposed. /// public Task(Func function, CancellationToken cancellationToken) : base(function, null, cancellationToken, TaskCreationOptions.None, InternalTaskOptions.None) { } /// /// Initializes a new with the specified function and creation options. /// /// /// The delegate that represents the code to execute in the task. When the function has completed, /// the task's property will be set to return the result value of the function. /// /// /// The TaskCreationOptions used to /// customize the task's behavior. /// /// /// The argument is null. /// /// /// The argument specifies an invalid value for . /// public Task(Func function, TaskCreationOptions creationOptions) : base(function, null, default(CancellationToken), creationOptions, InternalTaskOptions.None) { } /// /// Initializes a new with the specified function and creation options. /// /// /// The delegate that represents the code to execute in the task. When the function has completed, /// the task's property will be set to return the result value of the function. /// /// The that will be assigned to the new task. /// /// The TaskCreationOptions used to /// customize the task's behavior. /// /// /// The argument is null. /// /// /// The argument specifies an invalid value for . /// /// The provided CancellationToken /// has already been disposed. /// public Task(Func function, CancellationToken cancellationToken, TaskCreationOptions creationOptions) : base(function, null, cancellationToken, creationOptions, InternalTaskOptions.None) { } /// /// Initializes a new with the specified function and state. /// /// /// The delegate that represents the code to execute in the task. When the function has completed, /// the task's property will be set to return the result value of the function. /// /// An object representing data to be used by the action. /// /// The argument is null. /// public Task(Func function, object state) : base(function, state, default(CancellationToken), TaskCreationOptions.None, InternalTaskOptions.None) { } /// /// Initializes a new with the specified action, state, and options. /// /// /// The delegate that represents the code to execute in the task. When the function has completed, /// the task's property will be set to return the result value of the function. /// /// An object representing data to be used by the function. /// The to be assigned to the new task. /// /// The argument is null. /// /// The provided CancellationToken /// has already been disposed. /// public Task(Func function, object state, CancellationToken cancellationToken) : base(function, state, cancellationToken, TaskCreationOptions.None, InternalTaskOptions.None) { } /// /// Initializes a new with the specified action, state, and options. /// /// /// The delegate that represents the code to execute in the task. When the function has completed, /// the task's property will be set to return the result value of the function. /// /// An object representing data to be used by the function. /// /// The TaskCreationOptions used to /// customize the task's behavior. /// /// /// The argument is null. /// /// /// The argument specifies an invalid value for . /// public Task(Func function, object state, TaskCreationOptions creationOptions) : base(function, state, default(CancellationToken), creationOptions, InternalTaskOptions.None) { } /// /// Initializes a new with the specified action, state, and options. /// /// /// The delegate that represents the code to execute in the task. When the function has completed, /// the task's property will be set to return the result value of the function. /// /// An object representing data to be used by the function. /// The to be assigned to the new task. /// /// The TaskCreationOptions used to /// customize the task's behavior. /// /// /// The argument is null. /// /// /// The argument specifies an invalid value for . /// /// The provided CancellationToken /// has already been disposed. /// public Task(Func function, object state, CancellationToken cancellationToken, TaskCreationOptions creationOptions) : base(function, state, cancellationToken, creationOptions, InternalTaskOptions.None) { } internal Task(Delegate function, object state, CancellationToken cancellationToken, TaskCreationOptions options, InternalTaskOptions internalOptions) : base(function, state, cancellationToken, options, internalOptions) { } /// /// Gets the result value of this . /// /// /// The get accessor for this property ensures that the asynchronous operation is complete before /// returning. Once the result of the computation is available, it is stored and will be returned /// immediately on later calls to . /// [DebuggerBrowsable(DebuggerBrowsableState.Never)] public TResult Result { get { if (!IsRanToCompletion) { // If the result has not been calculated yet, wait for it. if (!IsCompleted) { InternalWait(Timeout.Infinite, default(CancellationToken)); } #if DISABLED_FOR_LLILUM // Throw an exception if appropriate. if (!IsRanToCompletion) { ThrowIfExceptional(includeTaskCanceledExceptions: true); } #endif // DISABLED_FOR_LLILUM } #if ENABLE_CONTRACTS // We shouldn't be here if the result has not been set. Contract.Assert(IsRanToCompletion, "Task.Result getter: Expected result to have been set."); #endif // ENABLE_CONTRACTS return m_result; } } #if DISABLED_FOR_LLILUM /// /// Provides access to factory methods for creating instances. /// /// /// The factory returned from is a default instance /// of , as would result from using /// the default constructor on the factory type. /// public new static TaskFactory Factory { get { return s_Factory; } } #endif // DISABLED_FOR_LLILUM #region Await Support /// Gets an awaiter used to await this . /// An awaiter instance. /// This method is intended for compiler user rather than use directly in code. public new TaskAwaiter GetAwaiter() { return new TaskAwaiter(this); } /// Configures an awaiter used to await this . /// /// true to attempt to marshal the continuation back to the original context captured; otherwise, false. /// /// An object used to await this task. public new ConfiguredTaskAwaitable ConfigureAwait(bool continueOnCapturedContext) { return new ConfiguredTaskAwaitable(this, continueOnCapturedContext); } #endregion Await Support #region Continuation methods #region Action> continuations /// /// Creates a continuation that executes when the target completes. /// /// /// An action to run when the completes. When run, the delegate will be /// passed the completed task as an argument. /// /// A new continuation . /// /// The returned will not be scheduled for execution until the current task has /// completed, whether it completes due to running to completion successfully, faulting due to an /// unhandled exception, or exiting out early due to being canceled. /// /// /// The argument is null. /// public Task ContinueWith(Action> continuationAction) { return ContinueWith(continuationAction, default(CancellationToken), TaskContinuationOptions.None, TaskScheduler.Default); } /// /// Creates a continuation that executes when the target completes. /// /// /// An action to run when the completes. When run, the delegate will be /// passed the completed task as an argument. /// /// The that will be assigned to the new continuation task. /// A new continuation . /// /// The returned will not be scheduled for execution until the current task has /// completed, whether it completes due to running to completion successfully, faulting due to an /// unhandled exception, or exiting out early due to being canceled. /// /// /// The argument is null. /// /// The provided CancellationToken /// has already been disposed. /// public Task ContinueWith(Action> continuationAction, CancellationToken cancellationToken) { return ContinueWith(continuationAction, cancellationToken, TaskContinuationOptions.None, TaskScheduler.Default); } /// /// Creates a continuation that executes when the target completes. /// /// /// An action to run when the completes. When run, the delegate will be /// passed the completed task as an argument. /// /// /// The to associate with the continuation task and to use for its execution. /// /// A new continuation . /// /// The returned will not be scheduled for execution until the current task has /// completed, whether it completes due to running to completion successfully, faulting due to an /// unhandled exception, or exiting out early due to being canceled. /// /// /// The argument is null. /// /// /// The argument is null. /// public Task ContinueWith(Action> continuationAction, TaskScheduler scheduler) { return ContinueWith(continuationAction, default(CancellationToken), TaskContinuationOptions.None, scheduler); } /// /// Creates a continuation that executes when the target completes. /// /// /// An action to run when the completes. When run, the delegate will be /// passed the completed task as an argument. /// /// /// Options for when the continuation is scheduled and how it behaves. This includes criteria, such /// as OnlyOnCanceled, as /// well as execution options, such as ExecuteSynchronously. /// /// A new continuation . /// /// The returned will not be scheduled for execution until the current task has /// completed. If the continuation criteria specified through the parameter are not met, the continuation task will be canceled /// instead of scheduled. /// /// /// The argument is null. /// /// /// The argument specifies an invalid value for TaskContinuationOptions. /// public Task ContinueWith(Action> continuationAction, TaskContinuationOptions continuationOptions) { return ContinueWith(continuationAction, default(CancellationToken), continuationOptions, TaskScheduler.Default); } /// /// Creates a continuation that executes when the target completes. /// /// /// An action to run when the completes. When run, the delegate will be /// passed the completed task as an argument. /// /// The that will be assigned to the new continuation task. /// /// Options for when the continuation is scheduled and how it behaves. This includes criteria, such /// as OnlyOnCanceled, as /// well as execution options, such as ExecuteSynchronously. /// /// /// The to associate with the continuation task and to use for its /// execution. /// /// A new continuation . /// /// The returned will not be scheduled for execution until the current task has /// completed. If the criteria specified through the parameter /// are not met, the continuation task will be canceled instead of scheduled. /// /// /// The argument is null. /// /// /// The argument specifies an invalid value for TaskContinuationOptions. /// /// /// The argument is null. /// /// The provided CancellationToken /// has already been disposed. /// public Task ContinueWith( Action> continuationAction, CancellationToken cancellationToken, TaskContinuationOptions continuationOptions, TaskScheduler scheduler) { if (continuationAction == null) { throw new ArgumentNullException(nameof(continuationAction)); } if (scheduler != TaskScheduler.Default) { throw new NotImplementedException(); } TaskCreationOptions creationOptions = CreationOptionsFromContinuationOptions(continuationOptions); var continuationTask = new ContinuationTaskFromResultTask(this, continuationAction, null, cancellationToken, creationOptions); ContinueWithCore(continuationTask, continuationOptions); return continuationTask; } #endregion Action> continuations #region Action, object> continuations /// /// Creates a continuation that executes when the target completes. /// /// /// An action to run when the completes. When run, the delegate will be /// passed the completed task and the caller-supplied state object as arguments. /// /// An object representing data to be used by the continuation action. /// A new continuation . /// /// The returned will not be scheduled for execution until the current task has /// completed, whether it completes due to running to completion successfully, faulting due to an /// unhandled exception, or exiting out early due to being canceled. /// /// /// The argument is null. /// public Task ContinueWith(Action, object> continuationAction, object state) { return ContinueWith(continuationAction, state, default(CancellationToken), TaskContinuationOptions.None, TaskScheduler.Default); } /// /// Creates a continuation that executes when the target completes. /// /// /// An action to run when the completes. When run, the delegate will be /// passed the completed task and the caller-supplied state object as arguments. /// /// An object representing data to be used by the continuation action. /// The that will be assigned to the new continuation task. /// A new continuation . /// /// The returned will not be scheduled for execution until the current task has /// completed, whether it completes due to running to completion successfully, faulting due to an /// unhandled exception, or exiting out early due to being canceled. /// /// /// The argument is null. /// /// The provided CancellationToken /// has already been disposed. /// public Task ContinueWith( Action, object> continuationAction, object state, CancellationToken cancellationToken) { return ContinueWith(continuationAction, state, cancellationToken, TaskContinuationOptions.None, TaskScheduler.Default); } /// /// Creates a continuation that executes when the target completes. /// /// /// An action to run when the completes. When run, the delegate will be /// passed the completed task and the caller-supplied state object as arguments. /// /// An object representing data to be used by the continuation action. /// /// The to associate with the continuation task and to use for its execution. /// /// A new continuation . /// /// The returned will not be scheduled for execution until the current task has /// completed, whether it completes due to running to completion successfully, faulting due to an /// unhandled exception, or exiting out early due to being canceled. /// /// /// The argument is null. /// /// /// The argument is null. /// public Task ContinueWith(Action, object> continuationAction, object state, TaskScheduler scheduler) { return ContinueWith(continuationAction, state, default(CancellationToken), TaskContinuationOptions.None, scheduler); } /// /// Creates a continuation that executes when the target completes. /// /// /// An action to run when the completes. When run, the delegate will be /// passed the completed task and the caller-supplied state object as arguments. /// /// An object representing data to be used by the continuation action. /// /// Options for when the continuation is scheduled and how it behaves. This includes criteria, such /// as OnlyOnCanceled, as /// well as execution options, such as ExecuteSynchronously. /// /// A new continuation . /// /// The returned will not be scheduled for execution until the current task has /// completed. If the continuation criteria specified through the parameter are not met, the continuation task will be canceled /// instead of scheduled. /// /// /// The argument is null. /// /// /// The argument specifies an invalid value for TaskContinuationOptions. /// public Task ContinueWith( Action, object> continuationAction, object state, TaskContinuationOptions continuationOptions) { return ContinueWith(continuationAction, state, default(CancellationToken), continuationOptions, TaskScheduler.Default); } /// /// Creates a continuation that executes when the target completes. /// /// /// An action to run when the completes. When run, the delegate will be /// passed the completed task and the caller-supplied state object as arguments. /// /// An object representing data to be used by the continuation action. /// The that will be assigned to the new continuation task. /// /// Options for when the continuation is scheduled and how it behaves. This includes criteria, such /// as OnlyOnCanceled, as /// well as execution options, such as ExecuteSynchronously. /// /// /// The to associate with the continuation task and to use for its /// execution. /// /// A new continuation . /// /// The returned will not be scheduled for execution until the current task has /// completed. If the criteria specified through the parameter /// are not met, the continuation task will be canceled instead of scheduled. /// /// /// The argument is null. /// /// /// The argument specifies an invalid value for TaskContinuationOptions. /// /// /// The argument is null. /// /// The provided CancellationToken /// has already been disposed. /// public Task ContinueWith( Action, object> continuationAction, object state, CancellationToken cancellationToken, TaskContinuationOptions continuationOptions, TaskScheduler scheduler) { if (continuationAction == null) { throw new ArgumentNullException(nameof(continuationAction)); } if (scheduler != TaskScheduler.Default) { throw new NotImplementedException(); } TaskCreationOptions creationOptions = CreationOptionsFromContinuationOptions(continuationOptions); var continuationTask = new ContinuationTaskFromResultTask(this, continuationAction, state, cancellationToken, creationOptions); ContinueWithCore(continuationTask, continuationOptions); return continuationTask; } #endregion Action, object> continuations #region Func,TNewResult> continuations /// /// Creates a continuation that executes when the target completes. /// /// /// The type of the result produced by the continuation. /// /// /// A function to run when the completes. When run, the delegate will be /// passed the completed task as an argument. /// /// A new continuation . /// /// The returned will not be scheduled for execution until the current /// task has completed, whether it completes due to running to completion successfully, faulting due /// to an unhandled exception, or exiting out early due to being canceled. /// /// /// The argument is null. /// public Task ContinueWith(Func, TNewResult> continuationFunction) { return ContinueWith(continuationFunction, default(CancellationToken), TaskContinuationOptions.None, TaskScheduler.Default); } /// /// Creates a continuation that executes when the target completes. /// /// /// The type of the result produced by the continuation. /// /// /// A function to run when the completes. When run, the delegate will be /// passed the completed task as an argument. /// /// The that will be assigned to the new task. /// A new continuation . /// /// The returned will not be scheduled for execution until the current /// task has completed, whether it completes due to running to completion successfully, faulting due /// to an unhandled exception, or exiting out early due to being canceled. /// /// /// The argument is null. /// /// The provided CancellationToken /// has already been disposed. /// public Task ContinueWith(Func, TNewResult> continuationFunction, CancellationToken cancellationToken) { return ContinueWith(continuationFunction, cancellationToken, TaskContinuationOptions.None, TaskScheduler.Default); } /// /// Creates a continuation that executes when the target completes. /// /// /// The type of the result produced by the continuation. /// /// /// A function to run when the completes. When run, the delegate will be /// passed the completed task as an argument. /// /// /// The to associate with the continuation task and to use for its execution. /// /// A new continuation . /// /// The returned will not be scheduled for execution until the current task has /// completed, whether it completes due to running to completion successfully, faulting due to an /// unhandled exception, or exiting out early due to being canceled. /// /// /// The argument is null. /// /// /// The argument is null. /// public Task ContinueWith( Func, TNewResult> continuationFunction, TaskScheduler scheduler) { return ContinueWith(continuationFunction, default(CancellationToken), TaskContinuationOptions.None, scheduler); } /// /// Creates a continuation that executes when the target completes. /// /// /// The type of the result produced by the continuation. /// /// /// A function to run when the completes. When run, the delegate will be /// passed the completed task as an argument. /// /// /// Options for when the continuation is scheduled and how it behaves. This includes criteria, such /// as OnlyOnCanceled, as /// well as execution options, such as ExecuteSynchronously. /// /// A new continuation . /// /// /// The returned will not be scheduled for execution until the current /// task has completed, whether it completes due to running to completion successfully, faulting due /// to an unhandled exception, or exiting out early due to being canceled. /// /// /// The , when executed, should return a . This task's completion state will be transferred to the task returned /// from the ContinueWith call. /// /// /// /// The argument is null. /// /// /// The argument specifies an invalid value for TaskContinuationOptions. /// public Task ContinueWith( Func, TNewResult> continuationFunction, TaskContinuationOptions continuationOptions) { return ContinueWith(continuationFunction, default(CancellationToken), continuationOptions, TaskScheduler.Default); } /// /// Creates a continuation that executes when the target completes. /// /// /// The type of the result produced by the continuation. /// /// /// A function to run when the completes. When run, the delegate will be passed as /// an argument this completed task. /// /// The that will be assigned to the new task. /// /// Options for when the continuation is scheduled and how it behaves. This includes criteria, such /// as OnlyOnCanceled, as /// well as execution options, such as ExecuteSynchronously. /// /// /// The to associate with the continuation task and to use for its /// execution. /// /// A new continuation . /// /// /// The returned will not be scheduled for execution until the current task has /// completed, whether it completes due to running to completion successfully, faulting due to an /// unhandled exception, or exiting out early due to being canceled. /// /// /// The , when executed, should return a . /// This task's completion state will be transferred to the task returned from the /// ContinueWith call. /// /// /// /// The argument is null. /// /// /// The argument specifies an invalid value for TaskContinuationOptions. /// /// /// The argument is null. /// /// The provided CancellationToken /// has already been disposed. /// public Task ContinueWith( Func, TNewResult> continuationFunction, CancellationToken cancellationToken, TaskContinuationOptions continuationOptions, TaskScheduler scheduler) { if (continuationFunction == null) { throw new ArgumentNullException(nameof(continuationFunction)); } if (scheduler != TaskScheduler.Default) { throw new NotImplementedException(); } TaskCreationOptions creationOptions = CreationOptionsFromContinuationOptions(continuationOptions); var continuationTask = new ContinuationResultTaskFromResultTask(this, continuationFunction, null, cancellationToken, creationOptions); ContinueWithCore(continuationTask, continuationOptions); return continuationTask; } #endregion Func,TNewResult> continuations #region Func, object,TNewResult> continuations /// /// Creates a continuation that executes when the target completes. /// /// /// The type of the result produced by the continuation. /// /// /// A function to run when the completes. When run, the delegate will be /// passed the completed task and the caller-supplied state object as arguments. /// /// An object representing data to be used by the continuation function. /// A new continuation . /// /// The returned will not be scheduled for execution until the current /// task has completed, whether it completes due to running to completion successfully, faulting due /// to an unhandled exception, or exiting out early due to being canceled. /// /// /// The argument is null. /// public Task ContinueWith( Func, object, TNewResult> continuationFunction, object state) { return ContinueWith(continuationFunction, state, default(CancellationToken), TaskContinuationOptions.None, TaskScheduler.Default); } /// /// Creates a continuation that executes when the target completes. /// /// /// The type of the result produced by the continuation. /// /// /// A function to run when the completes. When run, the delegate will be /// passed the completed task and the caller-supplied state object as arguments. /// /// An object representing data to be used by the continuation function. /// The that will be assigned to the new task. /// A new continuation . /// /// The returned will not be scheduled for execution until the current /// task has completed, whether it completes due to running to completion successfully, faulting due /// to an unhandled exception, or exiting out early due to being canceled. /// /// /// The argument is null. /// /// The provided CancellationToken /// has already been disposed. /// public Task ContinueWith( Func, object, TNewResult> continuationFunction, object state, CancellationToken cancellationToken) { return ContinueWith(continuationFunction, state, cancellationToken, TaskContinuationOptions.None, TaskScheduler.Default); } /// /// Creates a continuation that executes when the target completes. /// /// /// The type of the result produced by the continuation. /// /// /// A function to run when the completes. When run, the delegate will be /// passed the completed task and the caller-supplied state object as arguments. /// /// An object representing data to be used by the continuation function. /// /// The to associate with the continuation task and to use for its execution. /// /// A new continuation . /// /// The returned will not be scheduled for execution until the current task has /// completed, whether it completes due to running to completion successfully, faulting due to an /// unhandled exception, or exiting out early due to being canceled. /// /// /// The argument is null. /// /// /// The argument is null. /// public Task ContinueWith( Func, object, TNewResult> continuationFunction, object state, TaskScheduler scheduler) { return ContinueWith(continuationFunction, state, default(CancellationToken), TaskContinuationOptions.None, TaskScheduler.Default); } /// /// Creates a continuation that executes when the target completes. /// /// /// The type of the result produced by the continuation. /// /// /// A function to run when the completes. When run, the delegate will be /// passed the completed task and the caller-supplied state object as arguments. /// /// An object representing data to be used by the continuation function. /// /// Options for when the continuation is scheduled and how it behaves. This includes criteria, such /// as OnlyOnCanceled, as /// well as execution options, such as ExecuteSynchronously. /// /// A new continuation . /// /// /// The returned will not be scheduled for execution until the current /// task has completed, whether it completes due to running to completion successfully, faulting due /// to an unhandled exception, or exiting out early due to being canceled. /// /// /// The , when executed, should return a . This task's completion state will be transferred to the task returned /// from the ContinueWith call. /// /// /// /// The argument is null. /// /// /// The argument specifies an invalid value for TaskContinuationOptions. /// public Task ContinueWith( Func, object, TNewResult> continuationFunction, object state, TaskContinuationOptions continuationOptions) { return ContinueWith(continuationFunction, state, default(CancellationToken), continuationOptions, TaskScheduler.Default); } /// /// Creates a continuation that executes when the target completes. /// /// /// The type of the result produced by the continuation. /// /// /// A function to run when the completes. When run, the delegate will be /// passed the completed task and the caller-supplied state object as arguments. /// /// An object representing data to be used by the continuation function. /// The that will be assigned to the new task. /// /// Options for when the continuation is scheduled and how it behaves. This includes criteria, such /// as OnlyOnCanceled, as /// well as execution options, such as ExecuteSynchronously. /// /// /// The to associate with the continuation task and to use for its /// execution. /// /// A new continuation . /// /// /// The returned will not be scheduled for execution until the current task has /// completed, whether it completes due to running to completion successfully, faulting due to an /// unhandled exception, or exiting out early due to being canceled. /// /// /// The , when executed, should return a . /// This task's completion state will be transferred to the task returned from the /// ContinueWith call. /// /// /// /// The argument is null. /// /// /// The argument specifies an invalid value for TaskContinuationOptions. /// /// /// The argument is null. /// /// The provided CancellationToken /// has already been disposed. /// public Task ContinueWith( Func, object, TNewResult> continuationFunction, object state, CancellationToken cancellationToken, TaskContinuationOptions continuationOptions, TaskScheduler scheduler) { if (continuationFunction == null) { throw new ArgumentNullException(nameof(continuationFunction)); } if (scheduler != TaskScheduler.Default) { throw new NotImplementedException(); } TaskCreationOptions creationOptions = CreationOptionsFromContinuationOptions(continuationOptions); var continuationTask = new ContinuationResultTaskFromResultTask(this, continuationFunction, state, cancellationToken, creationOptions); ContinueWithCore(continuationTask, continuationOptions); return continuationTask; } #endregion Func, object,TNewResult> continuations #endregion Continuation methods /// /// Subscribes an to receive notification of the final state of this . /// /// /// The to call on task completion. If this Task throws an exception, /// observer.OnError is called with this Task's AggregateException. If this Task RanToCompletion, /// observer.OnNext is called with this Task's result, followed by a call to observer.OnCompleted. /// If this Task is Canceled, observer.OnError is called with a TaskCanceledException /// containing this Task's CancellationToken /// /// An IDisposable object . /// /// The argument is null. /// #if SUPPORT_IOBSERVABLE IDisposable IObservable.Subscribe(IObserver observer) { if (observer == null) throw new System.ArgumentNullException(nameof(observer)); var continuationTask = this.ContinueWith(delegate(Task observedTask, object taskObserverObject) { IObserver taskObserver = (IObserver)taskObserverObject; if (observedTask.IsFaulted) taskObserver.OnError(observedTask.Exception); else if (observedTask.IsCanceled) taskObserver.OnError(new TaskCanceledException(observedTask)); else { taskObserver.OnNext(observedTask.Result); taskObserver.OnCompleted(); } }, observer, TaskScheduler.Default); return new DisposableSubscription(this, continuationTask); } #endif // SUPPORT_IOBSERVABLE internal override void Invoke() { var function = m_action as Func; if (function != null) { m_result = function(); return; } var functionWithState = m_action as Func; if (functionWithState != null) { m_result = functionWithState(m_stateObject); return; } // This task's m_action isn't set, which means it must be a special Promise-type task. throw new InvalidOperationException(); } /// /// Helper for setting a result for promise-style tasks. /// /// /// Returns true if successful, false if not. internal bool TrySetResult(TResult result) { if (IsCompleted) { return false; } #if ENABLE_CONTRACTS Contract.Assert(m_action == null, "Task.TrySetResult(): non-null m_action"); #endif // ENABLE_CONTRACTS // Immediately transition to RanToCompletion before setting the result. Though this does introduce a narrow // race if someone is rapidly polling the completion status, this pattern should not be used in the wild. if (!AtomicStateUpdate(TaskStatus.RanToCompletion)) { return false; } m_result = result; FinishContinuations(); return true; } /// /// Helper for canceling promise-style tasks. /// /// Token to transfer to this task. /// Returns true if successful, false if not. internal bool TrySetCanceled(CancellationToken tokenToRecord) { // Immediately transition to Canceled state before setting the result. Though this does introduce a narrow // race if someone is rapidly polling the completion status, this pattern should not be used in the wild. if (!AtomicStateUpdate(TaskStatus.Canceled)) { return false; } RecordInternalCancellationRequest(tokenToRecord); FinishContinuations(); return true; } } #if SUPPORT_IOBSERVABLE // Class that calls RemoveContinuation if Dispose() is called before task completion internal class DisposableSubscription : IDisposable { private Task _notifyObserverContinuationTask; private Task _observedTask; internal DisposableSubscription(Task observedTask, Task notifyObserverContinuationTask) { _observedTask = observedTask; _notifyObserverContinuationTask = notifyObserverContinuationTask; } void IDisposable.Dispose() { Task localObservedTask = _observedTask; Task localNotifyingContinuationTask = _notifyObserverContinuationTask; if (localObservedTask != null && localNotifyingContinuationTask != null && !localObservedTask.IsCompleted) { localObservedTask.RemoveContinuation(localNotifyingContinuationTask); } _observedTask = null; _notifyObserverContinuationTask = null; } } #endif // SUPPORT_IOBSERVABLE } ================================================ FILE: Zelig/Zelig/RunTime/Framework/mscorlib/System/Threading/Tasks/Task.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // using System; using System.Collections.Generic; using System.Diagnostics; using System.Runtime.CompilerServices; using System.Security; using System.Security.Permissions; namespace System.Threading.Tasks { /// /// Represents the current stage in the lifecycle of a . /// public enum TaskStatus { /// /// The task has been initialized but has not yet been scheduled. /// Created, /// /// The task is waiting to be activated and scheduled internally by the .NET Framework infrastructure. /// WaitingForActivation, /// /// The task has been scheduled for execution but has not yet begun executing. /// WaitingToRun, /// /// The task is running but has not yet completed. /// Running, /// /// The task has finished executing and is implicitly waiting for /// attached child tasks to complete. /// WaitingForChildrenToComplete, /// /// The task completed execution successfully. /// RanToCompletion, /// /// The task acknowledged cancellation by throwing an OperationCanceledException with its own CancellationToken /// while the token was in signaled state, or the task's CancellationToken was already signaled before the /// task started executing. /// Canceled, /// /// The task completed due to an unhandled exception. /// Faulted } /// /// Represents an asynchronous operation. /// /// /// /// instances may be created in a variety of ways. The most common approach is by /// using the Task type's property to retrieve a instance that can be used to create tasks for several /// purposes. For example, to create a that runs an action, the factory's StartNew /// method may be used: /// /// // C# /// var t = Task.Factory.StartNew(() => DoAction()); /// /// ' Visual Basic /// Dim t = Task.Factory.StartNew(Function() DoAction()) /// /// /// /// The class also provides constructors that initialize the Task but that do not /// schedule it for execution. For performance reasons, TaskFactory's StartNew method should be the /// preferred mechanism for creating and scheduling computational tasks, but for scenarios where creation /// and scheduling must be separated, the constructors may be used, and the task's /// method may then be used to schedule the task for execution at a later time. /// /// /// All members of , except for , are thread-safe /// and may be used from multiple threads concurrently. /// /// /// For operations that return values, the class /// should be used. /// /// /// For developers implementing custom debuggers, several internal and private members of Task may be /// useful (these may change from release to release). The Int32 m_taskId field serves as the backing /// store for the property, however accessing this field directly from a debugger may be /// more efficient than accessing the same value through the property's getter method (the /// s_taskIdCounter Int32 counter is used to retrieve the next available ID for a Task). Similarly, the /// Int32 m_stateFlags field stores information about the current lifecycle stage of the Task, /// information also accessible through the property. The m_action System.Object /// field stores a reference to the Task's delegate, and the m_stateObject System.Object field stores the /// async state passed to the Task by the developer. Finally, for debuggers that parse stack frames, the /// InternalWait method serves a potential marker for when a Task is entering a wait operation. /// /// [HostProtection(Synchronization = true, ExternalThreading = true)] [DebuggerDisplay("Id = {Id}, Status = {Status}, Method = {DebuggerDisplayMethodDescription}")] public class Task : IAsyncResult, IDisposable { /// /// This class encapsulates rarely used properties. We keep these separate to limit the size of the most common /// types of tasks. /// private class ContingentProperties { public CancellationToken CancellationToken; public CancellationTokenRegistration CancellationRegistration; } private static readonly string multiTaskContinuation_EmptyTaskList = "The tasks argument contains no tasks."; private static readonly string multiTaskContinuation_NullTask = "The tasks argument included a null value."; private static readonly object s_taskCompletionSentinel = new object(); private static Task s_completedTask; private static int s_taskIdCounter; // In spirit these are "protected", but we want to hide them from external assemblies. internal readonly object m_action; // The body of the task. Might be Action, Action Action, or Func. internal readonly object m_stateObject; // A state object that can be optionally supplied, passed to action. private readonly int m_creationOptions; private int m_taskId; private object m_continuationObject; // Continuations to run when this task is complete. May be a single action or a list. private volatile int m_status; private volatile ContingentProperties m_contingentProperties; /// /// Constructor for use with promise-style tasks that aren't configurable. /// internal Task() { m_status = (int)TaskStatus.WaitingForActivation; m_creationOptions = (int)InternalTaskOptions.PromiseTask; } /// /// Initializes a new with the specified action. /// /// The delegate that represents the code to execute in the Task. /// The argument is null. public Task(Action action) { m_action = action; } /// /// Initializes a new with the specified action and CancellationToken. /// /// The delegate that represents the code to execute in the Task. /// The CancellationToken /// that will be assigned to the new Task. /// The argument is null. /// The provided CancellationToken /// has already been disposed. /// public Task(Action action, CancellationToken cancellationToken) : this(action, null, cancellationToken, TaskCreationOptions.None, InternalTaskOptions.None) { } /// /// Initializes a new with the specified action and creation options. /// /// The delegate that represents the code to execute in the task. /// /// The TaskCreationOptions used to /// customize the Task's behavior. /// /// /// The argument is null. /// /// /// The argument specifies an invalid value for . /// public Task(Action action, TaskCreationOptions creationOptions) : this(action, null, default(CancellationToken), creationOptions, InternalTaskOptions.None) { } /// /// Initializes a new with the specified action and creation options. /// /// The delegate that represents the code to execute in the task. /// The that will be assigned to the new task. /// /// The TaskCreationOptions used to /// customize the Task's behavior. /// /// /// The argument is null. /// /// /// The argument specifies an invalid value for . /// /// The provided CancellationToken /// has already been disposed. /// public Task(Action action, CancellationToken cancellationToken, TaskCreationOptions creationOptions) : this(action, null, cancellationToken, creationOptions, InternalTaskOptions.None) { } /// /// Initializes a new with the specified action and state. /// /// The delegate that represents the code to execute in the task. /// An object representing data to be used by the action. /// /// The argument is null. /// public Task(Action action, object state) { m_action = action; m_stateObject = state; } /// /// Initializes a new with the specified action, state, snd options. /// /// The delegate that represents the code to execute in the task. /// An object representing data to be used by the action. /// The that will be assigned to the new task. /// /// The argument is null. /// /// The provided CancellationToken /// has already been disposed. /// public Task(Action action, object state, CancellationToken cancellationToken) : this(action, state, cancellationToken, TaskCreationOptions.None, InternalTaskOptions.None) { } /// /// Initializes a new with the specified action, state, snd options. /// /// The delegate that represents the code to execute in the task. /// An object representing data to be used by the action. /// /// The TaskCreationOptions used to /// customize the Task's behavior. /// /// /// The argument is null. /// /// /// The argument specifies an invalid value for . /// public Task(Action action, object state, TaskCreationOptions creationOptions) : this(action, state, default(CancellationToken), creationOptions, InternalTaskOptions.None) { } /// /// Initializes a new with the specified action, state, snd options. /// /// The delegate that represents the code to execute in the task. /// An object representing data to be used by the action. /// The that will be assigned to the new task. /// /// The TaskCreationOptions used to /// customize the Task's behavior. /// /// /// The argument is null. /// /// /// The argument specifies an invalid value for . /// /// The provided CancellationToken /// has already been disposed. /// public Task( Action action, object state, CancellationToken cancellationToken, TaskCreationOptions creationOptions) : this(action, state, default(CancellationToken), creationOptions, InternalTaskOptions.None) { } /// /// Create a pre-canceled or pre-completed task. /// /// Whether the task is pre-canceled. If so, the task will be initialized to Canceled /// state. Otherwise, the task will be initialized in the RanToCompletion state. /// If canceled, the token that triggered cancellation. internal Task(bool canceled, CancellationToken cancellationToken) { if (canceled) { m_status = (int)TaskStatus.Canceled; m_contingentProperties = new ContingentProperties(); m_contingentProperties.CancellationToken = cancellationToken; } else { m_status = (int)TaskStatus.RanToCompletion; } } internal Task( Delegate action, object state, CancellationToken cancellationToken, TaskCreationOptions creationOptions, InternalTaskOptions internalOptions) { if (action == null) { throw new ArgumentNullException(nameof(action)); } const TaskCreationOptions supportedOptions = TaskCreationOptions.PreferFairness | TaskCreationOptions.LongRunning | TaskCreationOptions.DenyChildAttach | TaskCreationOptions.HideScheduler; if ((creationOptions & ~supportedOptions) != 0) { throw new ArgumentOutOfRangeException(null, nameof(creationOptions)); } m_action = action; m_stateObject = state; m_creationOptions = (int)creationOptions | (int)internalOptions; // Continuation and promise tasks start in "WaitingForActivation" instead of "Created" to prevent user // scheduling of the task, as well as to signal to an outside observer that this is not a user-created task. if ((internalOptions & InternalTaskOptions.ContinuationTask) != 0) { m_status = (int)TaskStatus.WaitingForActivation; } // If we have a non-default cancellation token, assign it last. This can alter m_status. if (cancellationToken.CanBeCanceled) { m_contingentProperties = new ContingentProperties(); m_contingentProperties.CancellationToken = cancellationToken; cancellationToken.ThrowIfSourceDisposed(); if (cancellationToken.IsCancellationRequested) { InternalCancel(); } else { m_contingentProperties.CancellationRegistration = cancellationToken.Register(InternalCancel); } } } /// /// Update the state of the task. This protects against invalid state transitions, including trying to transition /// to a state we're already in. /// /// The state to transition to. /// True if the transition was completed successfully, false if the transition was invalid. internal bool AtomicStateUpdate(TaskStatus newStatus) { for (;;) { TaskStatus oldStatus = (TaskStatus)m_status; // The TaskStatus enum is ordered by precedence, so this simple check prevents most // invalid state transitions. Other prohibitions are handled below. if (oldStatus >= newStatus) { return false; } // Explicitly forbid tasks moving from system-scheduled to user-scheduled. If this // task is waiting for activation, it's already scheduled to run. if ((oldStatus == TaskStatus.WaitingForActivation) && (newStatus == TaskStatus.WaitingToRun)) { return false; } // Forbid cancellation of tasks that have already begun invoking. if ((newStatus == TaskStatus.Canceled) && (oldStatus >= TaskStatus.Running)) { return false; } if (Interlocked.CompareExchange(ref m_status, (int)newStatus, (int)oldStatus) == (int)oldStatus) { return true; } } } /// /// Starts the , scheduling it for execution to the current TaskScheduler. /// /// /// A task may only be started and run only once. Any attempts to schedule a task a second time /// will result in an exception. /// /// /// The is not in a valid state to be started. It may have already been started, /// executed, or canceled, or it may have been created in a manner that doesn't support direct /// scheduling. /// public void Start() { if (!AtomicStateUpdate(TaskStatus.WaitingToRun)) { throw new InvalidOperationException(); } if (!Start(runSynchronously: false)) { throw new InvalidOperationException(); } } #if DISABLED_FOR_LLILUM /// /// Starts the , scheduling it for execution to the specified TaskScheduler. /// /// /// A task may only be started and run only once. Any attempts to schedule a task a second time will /// result in an exception. /// /// /// The TaskScheduler with which to associate /// and execute this task. /// /// /// The argument is null. /// /// /// The is not in a valid state to be started. It may have already been started, /// executed, or canceled, or it may have been created in a manner that doesn't support direct /// scheduling. /// public void Start(TaskScheduler scheduler) { throw new NotImplementedException(); } #endif // DISABLED_FOR_LLILUM /// /// Runs the synchronously on the current TaskScheduler. /// /// /// /// A task may only be started and run only once. Any attempts to schedule a task a second time will /// result in an exception. /// /// /// Tasks executed with will be associated with the current TaskScheduler. /// /// /// If the target scheduler does not support running this Task on the current thread, the Task will /// be scheduled for execution on the scheduler, and the current thread will block until the /// Task has completed execution. /// /// /// /// The is not in a valid state to be started. It may have already been started, /// executed, or canceled, or it may have been created in a manner that doesn't support direct /// scheduling. /// public void RunSynchronously() { // Explicitly forbid continuations and promise-style tasks from being externally run. if (Status == TaskStatus.WaitingForActivation) { throw new InvalidOperationException(); } if (!Start(runSynchronously: true)) { throw new InvalidOperationException(); } } #if DISABLED_FOR_LLILUM /// /// Runs the synchronously on the scheduler provided. /// /// /// /// A task may only be started and run only once. Any attempts to schedule a task a second time will /// result in an exception. /// /// /// If the target scheduler does not support running this Task on the current thread, the Task will /// be scheduled for execution on the scheduler, and the current thread will block until the /// Task has completed execution. /// /// /// /// The is not in a valid state to be started. It may have already been started, /// executed, or canceled, or it may have been created in a manner that doesn't support direct /// scheduling. /// /// The parameter /// is null. /// The scheduler on which to attempt to run this task inline. public void RunSynchronously(TaskScheduler scheduler) { throw new NotImplementedException(); } #endif // DISABLED_FOR_LLILUM /// /// Gets a unique ID for this Task instance. /// /// /// Task IDs are assigned on-demand and do not necessarily represent the order in the which Task /// instances were created. /// public int Id { get { if (m_taskId == 0) { m_taskId = Interlocked.Increment(ref s_taskIdCounter); } return m_taskId; } } #if DISABLED_FOR_LLILUM /// /// Returns the unique ID of the currently executing Task. /// public static int? CurrentId { get { return t_currentTask?.Id; } } #endif // DISABLED_FOR_LLILUM /// /// Gets the Exception that caused the Task to end prematurely. If the Task completed successfully or has not yet thrown any /// exceptions, this will return null. /// /// /// Tasks that throw unhandled exceptions store the resulting exception and propagate it wrapped in a /// in calls to Wait /// or in accesses to the property. Any exceptions not observed by the time /// the Task instance is garbage collected will be propagated on the finalizer thread. /// public AggregateException Exception { get { // TODO: Track thrown exceptions and return them here. return null; } } /// /// Gets the TaskStatus of this Task. /// public TaskStatus Status { get { return (TaskStatus)m_status; } } internal bool IsRanToCompletion { get { return Status == TaskStatus.RanToCompletion; } } internal bool IsContinuation { get { return (m_creationOptions & (int)InternalTaskOptions.ContinuationTask) != 0; } } /// /// Gets whether this Task instance has completed /// execution due to being canceled. /// /// /// A Task will complete in Canceled state either if its CancellationToken /// was marked for cancellation before the task started executing, or if the task acknowledged the cancellation request on /// its already signaled CancellationToken by throwing an /// OperationCanceledException that bears the same /// CancellationToken. /// public bool IsCanceled { get { return Status == TaskStatus.Canceled; } } /// /// Gets whether this Task has completed. /// /// /// will return true when the Task is in one of the three /// final states: RanToCompletion, /// Faulted, or /// Canceled. /// public bool IsCompleted { get { switch (Status) { case TaskStatus.RanToCompletion: case TaskStatus.Canceled: case TaskStatus.Faulted: return true; } return false; } } /// /// Gets the TaskCreationOptions used /// to create this task. /// public TaskCreationOptions CreationOptions { get { return (TaskCreationOptions)(m_creationOptions & (int)~InternalTaskOptions.InternalOptionsMask); } } /// /// Gets a that can be used to wait for the task to /// complete. /// /// /// Using the wait functionality provided by /// should be preferred over using for similar /// functionality. /// /// /// The has been disposed. /// WaitHandle IAsyncResult.AsyncWaitHandle { get { throw new NotImplementedException(); } } /// /// Gets the state object supplied when the Task was created, /// or null if none was supplied. /// public object AsyncState { get { return m_stateObject; } } /// /// Gets an indication of whether the asynchronous operation completed synchronously. /// /// true if the asynchronous operation completed synchronously; otherwise, false. bool IAsyncResult.CompletedSynchronously { get { return false; } } #if DISABLED_FOR_LLILUM /// /// Provides access to factory methods for creating and instances. /// /// /// The factory returned from is a default instance /// of , as would result from using /// the default constructor on TaskFactory. /// public static TaskFactory Factory { get { return s_factory; } } #endif // DISABLED_FOR_LLILUM /// Gets a task that's already been completed successfully. /// May not always return the same instance. public static Task CompletedTask { get { if (s_completedTask == null) { // There exists a race condition in that we can overwrite s_completedTask. We don't depend on // referential identity, however, so the race is benign. s_completedTask = new Task(false, default(CancellationToken)); } return s_completedTask; } } /// /// Gets whether the completed due to an unhandled exception. /// /// /// If is true, the Task's will be equal to /// TaskStatus.Faulted, and its /// property will be non-null. /// public bool IsFaulted { get { return Status == TaskStatus.Faulted; } } internal CancellationToken CancellationToken { get { // We should have ensured contingent props are non-null by the time this is called, so no need to check. return m_contingentProperties.CancellationToken; } } /// /// Disposes the , releasing all of its unmanaged resources. /// /// /// Unlike most of the members of , this method is not thread-safe. /// Also, may only be called on a that is in one of /// the final states: RanToCompletion, /// Faulted, or /// Canceled. /// /// /// The exception that is thrown if the is not in /// one of the final states: RanToCompletion, /// Faulted, or /// Canceled. /// public void Dispose() { Dispose(true); GC.SuppressFinalize(this); } /// /// Disposes the , releasing all of its unmanaged resources. /// /// /// A Boolean value that indicates whether this method is being called due to a call to . /// /// /// Unlike most of the members of , this method is not thread-safe. /// protected virtual void Dispose(bool disposing) { if (disposing) { // Task must be completed to dispose if (!IsCompleted) { throw new InvalidOperationException("A task may only be disposed if it is in a completion state (RanToCompletion, Faulted or Canceled)."); } // Nothing to do in this implementation. } } #region Await Support /// Gets an awaiter used to await this . /// An awaiter instance. /// This method is intended for compiler user rather than use directly in code. public TaskAwaiter GetAwaiter() { return new TaskAwaiter(this); } /// Configures an awaiter used to await this . /// /// true to attempt to marshal the continuation back to the original context captured; otherwise, false. /// /// An object used to await this task. public ConfiguredTaskAwaitable ConfigureAwait(bool continueOnCapturedContext) { return new ConfiguredTaskAwaitable(this, continueOnCapturedContext); } #if DISABLED_FOR_LLILUM /// Creates an awaitable that asynchronously yields back to the current context when awaited. /// /// A context that, when awaited, will asynchronously transition back into the current context at the /// time of the await. If the current SynchronizationContext is non-null, that is treated as the current context. /// Otherwise, TaskScheduler.Current is treated as the current context. /// public static YieldAwaitable Yield() { return new YieldAwaitable(); } #endif // DISABLED_FOR_LLILUM #endregion Await Support /// /// Waits for the to complete execution. /// /// /// The was canceled -or- an exception was thrown during /// the execution of the . /// public void Wait() { Wait(Timeout.Infinite); } /// /// Waits for the to complete execution. /// /// /// A that represents the number of milliseconds to wait, or a that represents -1 milliseconds to wait indefinitely. /// /// /// true if the completed execution within the allotted time; otherwise, false. /// /// /// The was canceled -or- an exception was thrown during the execution of the . /// /// /// is a negative number other than -1 milliseconds, which represents an /// infinite time-out -or- timeout is greater than /// . /// public bool Wait(TimeSpan timeout) { long totalMilliseconds = (long)timeout.TotalMilliseconds; if (totalMilliseconds < -1 || totalMilliseconds > Int32.MaxValue) { throw new ArgumentOutOfRangeException(nameof(timeout)); } return InternalWait((int)totalMilliseconds, default(CancellationToken)); } /// Waits for the to complete execution. /// /// /// A to observe while waiting for the task to complete. /// /// /// The was canceled. /// /// /// The was canceled -or- an exception was thrown during the execution of the . /// public void Wait(CancellationToken cancellationToken) { Wait(Timeout.Infinite, cancellationToken); } private sealed class SetOnInvokeEvent : ITaskCompletionAction { private ManualResetEvent m_event; internal SetOnInvokeEvent() { m_event = new ManualResetEvent(false); } public void Invoke(Task completedTask) { m_event.Set(); } public bool Wait(int timeout, CancellationToken cancellationToken) { if (cancellationToken.CanBeCanceled) { throw new NotImplementedException("ManualResetEvent.WaitOne does not yet support cancellation."); } return m_event.WaitOne(timeout, false); } } /// /// Waits for the to complete execution. /// /// /// The number of milliseconds to wait, or (-1) to /// wait indefinitely. /// true if the completed execution within the allotted time; otherwise, /// false. /// /// /// is a negative number other than -1, which represents an /// infinite time-out. /// /// /// The was canceled -or- an exception was thrown during the execution of the . /// public bool Wait(int millisecondsTimeout) { return Wait(millisecondsTimeout, default(CancellationToken)); } /// /// Waits for the to complete execution. /// /// /// The number of milliseconds to wait, or (-1) to /// wait indefinitely. /// /// /// A to observe while waiting for the task to complete. /// /// /// true if the completed execution within the allotted time; otherwise, false. /// /// /// The was canceled -or- an exception was thrown during the execution of the . /// /// /// is a negative number other than -1, which represents an /// infinite time-out. /// /// /// The was canceled. /// public bool Wait(int millisecondsTimeout, CancellationToken cancellationToken) { if (millisecondsTimeout < -1) { throw new ArgumentOutOfRangeException(nameof(millisecondsTimeout)); } // Skip waiting if we already know the task is done. if (IsRanToCompletion) { return true; } // Wait and return if we're still not done. if (!InternalWait(millisecondsTimeout, cancellationToken)) { return false; } if (!IsRanToCompletion) { // If cancellation was requested and the task was canceled, throw an OperationCanceledException. This is // prioritized ahead of the ThrowIfExceptional call to bring more determinism to cases where the same // token is used to cancel the Wait and to cancel the Task. Otherwise, there's a race condition between // whether the Wait or the Task observes the cancellation request first, and different exceptions result // from the different cases. if (IsCanceled) { cancellationToken.ThrowIfCancellationRequested(); } #if DISABLED_FOR_LLILUM // If an exception occurred, or the task was cancelled, throw an exception. ThrowIfExceptional(includeTaskCanceledExceptions: true); #endif // DISABLED_FOR_LLILUM } return true; } internal bool InternalWait(int millisecondsTimeout, CancellationToken cancellationToken) { if (IsCompleted) { return true; } bool infiniteWait = millisecondsTimeout == Timeout.Infinite; uint startTimeTicks = infiniteWait ? 0 : (uint)Environment.TickCount; bool returnValue = false; var completionEvent = new SetOnInvokeEvent(); try { AddCompletionAction(completionEvent); if (infiniteWait) { returnValue = completionEvent.Wait(Timeout.Infinite, cancellationToken); } else { uint elapsedTimeTicks = ((uint)Environment.TickCount) - startTimeTicks; if (elapsedTimeTicks < millisecondsTimeout) { returnValue = completionEvent.Wait((int)(millisecondsTimeout - elapsedTimeTicks), cancellationToken); } } } finally { if (!IsCompleted) { RemoveContinuation(completionEvent); } // Note: We don't dispose completionEvent here since the continuation may still be // running. Instead, the continuation will dispose just before returning. } return returnValue; } #region Continuation methods #region Action continuation /// /// Creates a continuation that executes when the target completes. /// /// /// An action to run when the completes. When run, the delegate will be /// passed the completed task as an argument. /// /// A new continuation . /// /// The returned will not be scheduled for execution until the current task has /// completed, whether it completes due to running to completion successfully, faulting due to an /// unhandled exception, or exiting out early due to being canceled. /// /// /// The argument is null. /// public Task ContinueWith(Action continuationAction) { return ContinueWith(continuationAction, default(CancellationToken), TaskContinuationOptions.None, TaskScheduler.Default); } /// /// Creates a continuation that executes when the target completes. /// /// /// An action to run when the completes. When run, the delegate will be /// passed the completed task as an argument. /// /// The that will be assigned to the new continuation task. /// A new continuation . /// /// The returned will not be scheduled for execution until the current task has /// completed, whether it completes due to running to completion successfully, faulting due to an /// unhandled exception, or exiting out early due to being canceled. /// /// /// The argument is null. /// /// The provided CancellationToken /// has already been disposed. /// public Task ContinueWith(Action continuationAction, CancellationToken cancellationToken) { return ContinueWith(continuationAction, cancellationToken, TaskContinuationOptions.None, TaskScheduler.Default); } /// /// Creates a continuation that executes when the target completes. /// /// /// An action to run when the completes. When run, the delegate will be /// passed the completed task as an argument. /// /// /// The to associate with the continuation task and to use for its execution. /// /// A new continuation . /// /// The returned will not be scheduled for execution until the current task has /// completed, whether it completes due to running to completion successfully, faulting due to an /// unhandled exception, or exiting out early due to being canceled. /// /// /// The argument is null. /// /// /// The argument is null. /// public Task ContinueWith(Action continuationAction, TaskScheduler scheduler) { return ContinueWith(continuationAction, default(CancellationToken), TaskContinuationOptions.None, scheduler); } /// /// Creates a continuation that executes when the target completes. /// /// /// An action to run when the completes. When run, the delegate will be /// passed the completed task as an argument. /// /// /// Options for when the continuation is scheduled and how it behaves. This includes criteria, such /// as OnlyOnCanceled, as /// well as execution options, such as ExecuteSynchronously. /// /// A new continuation . /// /// The returned will not be scheduled for execution until the current task has /// completed. If the continuation criteria specified through the parameter are not met, the continuation task will be canceled /// instead of scheduled. /// /// /// The argument is null. /// /// /// The argument specifies an invalid value for TaskContinuationOptions. /// public Task ContinueWith(Action continuationAction, TaskContinuationOptions continuationOptions) { return ContinueWith(continuationAction, default(CancellationToken), continuationOptions, TaskScheduler.Default); } /// /// Creates a continuation that executes when the target completes. /// /// /// An action to run when the completes. When run, the delegate will be /// passed the completed task as an argument. /// /// /// Options for when the continuation is scheduled and how it behaves. This includes criteria, such /// as OnlyOnCanceled, as /// well as execution options, such as ExecuteSynchronously. /// /// The that will be assigned to the new continuation task. /// /// The to associate with the continuation task and to use for its /// execution. /// /// A new continuation . /// /// The returned will not be scheduled for execution until the current task has /// completed. If the criteria specified through the parameter /// are not met, the continuation task will be canceled instead of scheduled. /// /// /// The argument is null. /// /// /// The argument specifies an invalid value for TaskContinuationOptions. /// /// /// The argument is null. /// /// The provided CancellationToken /// has already been disposed. /// public Task ContinueWith( Action continuationAction, CancellationToken cancellationToken, TaskContinuationOptions continuationOptions, TaskScheduler scheduler) { if (continuationAction == null) { throw new ArgumentNullException(nameof(continuationAction)); } if (scheduler != TaskScheduler.Default) { throw new NotImplementedException(); } TaskCreationOptions creationOptions = CreationOptionsFromContinuationOptions(continuationOptions); var continuationTask = new ContinuationTaskFromTask(this, continuationAction, null, cancellationToken, creationOptions); ContinueWithCore(continuationTask, continuationOptions); return continuationTask; } #endregion Action continuation #region Action continuation /// /// Creates a continuation that executes when the target completes. /// /// /// An action to run when the completes. When run, the delegate will be /// passed the completed task as and the caller-supplied state object as arguments. /// /// An object representing data to be used by the continuation action. /// A new continuation . /// /// The returned will not be scheduled for execution until the current task has /// completed, whether it completes due to running to completion successfully, faulting due to an /// unhandled exception, or exiting out early due to being canceled. /// /// /// The argument is null. /// public Task ContinueWith(Action continuationAction, object state) { return ContinueWith(continuationAction, state, default(CancellationToken), TaskContinuationOptions.None, TaskScheduler.Default); } /// /// Creates a continuation that executes when the target completes. /// /// /// An action to run when the completes. When run, the delegate will be /// passed the completed task and the caller-supplied state object as arguments. /// /// An object representing data to be used by the continuation action. /// The that will be assigned to the new continuation task. /// A new continuation . /// /// The returned will not be scheduled for execution until the current task has /// completed, whether it completes due to running to completion successfully, faulting due to an /// unhandled exception, or exiting out early due to being canceled. /// /// /// The argument is null. /// /// The provided CancellationToken /// has already been disposed. /// public Task ContinueWith(Action continuationAction, object state, CancellationToken cancellationToken) { return ContinueWith(continuationAction, state, cancellationToken, TaskContinuationOptions.None, TaskScheduler.Default); } /// /// Creates a continuation that executes when the target completes. /// /// /// An action to run when the completes. When run, the delegate will be /// passed the completed task and the caller-supplied state object as arguments. /// /// An object representing data to be used by the continuation action. /// /// The to associate with the continuation task and to use for its execution. /// /// A new continuation . /// /// The returned will not be scheduled for execution until the current task has /// completed, whether it completes due to running to completion successfully, faulting due to an /// unhandled exception, or exiting out early due to being canceled. /// /// /// The argument is null. /// /// /// The argument is null. /// public Task ContinueWith(Action continuationAction, object state, TaskScheduler scheduler) { return ContinueWith(continuationAction, state, default(CancellationToken), TaskContinuationOptions.None, scheduler); } /// /// Creates a continuation that executes when the target completes. /// /// /// An action to run when the completes. When run, the delegate will be /// passed the completed task and the caller-supplied state object as arguments. /// /// An object representing data to be used by the continuation action. /// /// Options for when the continuation is scheduled and how it behaves. This includes criteria, such /// as OnlyOnCanceled, as /// well as execution options, such as ExecuteSynchronously. /// /// A new continuation . /// /// The returned will not be scheduled for execution until the current task has /// completed. If the continuation criteria specified through the parameter are not met, the continuation task will be canceled /// instead of scheduled. /// /// /// The argument is null. /// /// /// The argument specifies an invalid value for TaskContinuationOptions. /// public Task ContinueWith(Action continuationAction, object state, TaskContinuationOptions continuationOptions) { return ContinueWith(continuationAction, state, default(CancellationToken), continuationOptions, TaskScheduler.Default); } /// /// Creates a continuation that executes when the target completes. /// /// /// An action to run when the completes. When run, the delegate will be /// passed the completed task and the caller-supplied state object as arguments. /// /// An object representing data to be used by the continuation action. /// /// Options for when the continuation is scheduled and how it behaves. This includes criteria, such /// as OnlyOnCanceled, as /// well as execution options, such as ExecuteSynchronously. /// /// The that will be assigned to the new continuation task. /// /// The to associate with the continuation task and to use for its /// execution. /// /// A new continuation . /// /// The returned will not be scheduled for execution until the current task has /// completed. If the criteria specified through the parameter /// are not met, the continuation task will be canceled instead of scheduled. /// /// /// The argument is null. /// /// /// The argument specifies an invalid value for TaskContinuationOptions. /// /// /// The argument is null. /// /// The provided CancellationToken /// has already been disposed. /// public Task ContinueWith( Action continuationAction, object state, CancellationToken cancellationToken, TaskContinuationOptions continuationOptions, TaskScheduler scheduler) { if (continuationAction == null) { throw new ArgumentNullException(nameof(continuationAction)); } if (scheduler != TaskScheduler.Default) { throw new NotImplementedException(); } TaskCreationOptions creationOptions = CreationOptionsFromContinuationOptions(continuationOptions); var continuationTask = new ContinuationTaskFromTask(this, continuationAction, state, cancellationToken, creationOptions); ContinueWithCore(continuationTask, continuationOptions); return continuationTask; } #endregion Action continuation #region Func continuation /// /// Creates a continuation that executes when the target completes. /// /// /// The type of the result produced by the continuation. /// /// /// A function to run when the completes. When run, the delegate will be /// passed the completed task as an argument. /// /// A new continuation . /// /// The returned will not be scheduled for execution until the current task has /// completed, whether it completes due to running to completion successfully, faulting due to an /// unhandled exception, or exiting out early due to being canceled. /// /// /// The argument is null. /// public Task ContinueWith(Func continuationFunction) { return ContinueWith(continuationFunction, default(CancellationToken), TaskContinuationOptions.None, TaskScheduler.Default); } /// /// Creates a continuation that executes when the target completes. /// /// /// The type of the result produced by the continuation. /// /// /// A function to run when the completes. When run, the delegate will be /// passed the completed task as an argument. /// /// The that will be assigned to the new continuation task. /// A new continuation . /// /// The returned will not be scheduled for execution until the current task has /// completed, whether it completes due to running to completion successfully, faulting due to an /// unhandled exception, or exiting out early due to being canceled. /// /// /// The argument is null. /// /// The provided CancellationToken /// has already been disposed. /// public Task ContinueWith(Func continuationFunction, CancellationToken cancellationToken) { return ContinueWith(continuationFunction, cancellationToken, TaskContinuationOptions.None, TaskScheduler.Default); } /// /// Creates a continuation that executes when the target completes. /// /// /// The type of the result produced by the continuation. /// /// /// A function to run when the completes. When run, the delegate will be /// passed the completed task as an argument. /// /// /// The to associate with the continuation task and to use for its execution. /// /// A new continuation . /// /// The returned will not be scheduled for execution until the current task has /// completed, whether it completes due to running to completion successfully, faulting due to an /// unhandled exception, or exiting out early due to being canceled. /// /// /// The argument is null. /// /// /// The argument is null. /// public Task ContinueWith(Func continuationFunction, TaskScheduler scheduler) { return ContinueWith(continuationFunction, default(CancellationToken), TaskContinuationOptions.None, scheduler); } /// /// Creates a continuation that executes when the target completes. /// /// /// The type of the result produced by the continuation. /// /// /// A function to run when the completes. When run, the delegate will be /// passed the completed task as an argument. /// /// /// Options for when the continuation is scheduled and how it behaves. This includes criteria, such /// as OnlyOnCanceled, as /// well as execution options, such as ExecuteSynchronously. /// /// A new continuation . /// /// The returned will not be scheduled for execution until the current task has /// completed. If the continuation criteria specified through the parameter are not met, the continuation task will be canceled /// instead of scheduled. /// /// /// The argument is null. /// /// /// The argument specifies an invalid value for TaskContinuationOptions. /// public Task ContinueWith( Func continuationFunction, TaskContinuationOptions continuationOptions) { return ContinueWith(continuationFunction, default(CancellationToken), continuationOptions, TaskScheduler.Default); } /// /// Creates a continuation that executes when the target completes. /// /// /// The type of the result produced by the continuation. /// /// /// A function to run when the completes. When run, the delegate will be /// passed the completed task as an argument. /// /// The that will be assigned to the new continuation task. /// /// Options for when the continuation is scheduled and how it behaves. This includes criteria, such /// as OnlyOnCanceled, as /// well as execution options, such as ExecuteSynchronously. /// /// /// The to associate with the continuation task and to use for its /// execution. /// /// A new continuation . /// /// The returned will not be scheduled for execution until the current task has /// completed. If the criteria specified through the parameter /// are not met, the continuation task will be canceled instead of scheduled. /// /// /// The argument is null. /// /// /// The argument specifies an invalid value for TaskContinuationOptions. /// /// /// The argument is null. /// /// The provided CancellationToken /// has already been disposed. /// public Task ContinueWith( Func continuationFunction, CancellationToken cancellationToken, TaskContinuationOptions continuationOptions, TaskScheduler scheduler) { if (continuationFunction == null) { throw new ArgumentNullException(nameof(continuationFunction)); } if (scheduler != TaskScheduler.Default) { throw new NotImplementedException(); } TaskCreationOptions creationOptions = CreationOptionsFromContinuationOptions(continuationOptions); var continuationTask = new ContinuationResultTaskFromTask(this, continuationFunction, null, cancellationToken, creationOptions); ContinueWithCore(continuationTask, continuationOptions); return continuationTask; } #endregion Func continuation #region Func continuation /// /// Creates a continuation that executes when the target completes. /// /// /// The type of the result produced by the continuation. /// /// /// A function to run when the completes. When run, the delegate will be /// passed the completed task and the caller-supplied state object as arguments. /// /// An object representing data to be used by the continuation function. /// A new continuation . /// /// The returned will not be scheduled for execution until the current task has /// completed, whether it completes due to running to completion successfully, faulting due to an /// unhandled exception, or exiting out early due to being canceled. /// /// /// The argument is null. /// public Task ContinueWith(Func continuationFunction, object state) { return ContinueWith(continuationFunction, state, default(CancellationToken), TaskContinuationOptions.None, TaskScheduler.Default); } /// /// Creates a continuation that executes when the target completes. /// /// /// The type of the result produced by the continuation. /// /// /// A function to run when the completes. When run, the delegate will be /// passed the completed task and the caller-supplied state object as arguments. /// /// An object representing data to be used by the continuation function. /// The that will be assigned to the new continuation task. /// A new continuation . /// /// The returned will not be scheduled for execution until the current task has /// completed, whether it completes due to running to completion successfully, faulting due to an /// unhandled exception, or exiting out early due to being canceled. /// /// /// The argument is null. /// /// The provided CancellationToken /// has already been disposed. /// public Task ContinueWith( Func continuationFunction, object state, CancellationToken cancellationToken) { return ContinueWith(continuationFunction, state, cancellationToken, TaskContinuationOptions.None, TaskScheduler.Default); } /// /// Creates a continuation that executes when the target completes. /// /// /// The type of the result produced by the continuation. /// /// /// A function to run when the completes. When run, the delegate will be /// passed the completed task and the caller-supplied state object as arguments. /// /// An object representing data to be used by the continuation function. /// /// The to associate with the continuation task and to use for its execution. /// /// A new continuation . /// /// The returned will not be scheduled for execution until the current task has /// completed, whether it completes due to running to completion successfully, faulting due to an /// unhandled exception, or exiting out early due to being canceled. /// /// /// The argument is null. /// /// /// The argument is null. /// public Task ContinueWith( Func continuationFunction, object state, TaskScheduler scheduler) { return ContinueWith(continuationFunction, state, default(CancellationToken), TaskContinuationOptions.None, scheduler); } /// /// Creates a continuation that executes when the target completes. /// /// /// The type of the result produced by the continuation. /// /// /// A function to run when the completes. When run, the delegate will be /// passed the completed task and the caller-supplied state object as arguments. /// /// An object representing data to be used by the continuation function. /// /// Options for when the continuation is scheduled and how it behaves. This includes criteria, such /// as OnlyOnCanceled, as /// well as execution options, such as ExecuteSynchronously. /// /// A new continuation . /// /// The returned will not be scheduled for execution until the current task has /// completed. If the continuation criteria specified through the parameter are not met, the continuation task will be canceled /// instead of scheduled. /// /// /// The argument is null. /// /// /// The argument specifies an invalid value for TaskContinuationOptions. /// public Task ContinueWith( Func continuationFunction, object state, TaskContinuationOptions continuationOptions) { return ContinueWith(continuationFunction, state, default(CancellationToken), continuationOptions, TaskScheduler.Default); } /// /// Creates a continuation that executes when the target completes. /// /// /// The type of the result produced by the continuation. /// /// /// A function to run when the completes. When run, the delegate will be /// passed the completed task and the caller-supplied state object as arguments. /// /// An object representing data to be used by the continuation function. /// The that will be assigned to the new continuation task. /// /// Options for when the continuation is scheduled and how it behaves. This includes criteria, such /// as OnlyOnCanceled, as /// well as execution options, such as ExecuteSynchronously. /// /// /// The to associate with the continuation task and to use for its /// execution. /// /// A new continuation . /// /// The returned will not be scheduled for execution until the current task has /// completed. If the criteria specified through the parameter /// are not met, the continuation task will be canceled instead of scheduled. /// /// /// The argument is null. /// /// /// The argument specifies an invalid value for TaskContinuationOptions. /// /// /// The argument is null. /// /// The provided CancellationToken /// has already been disposed. /// public Task ContinueWith( Func continuationFunction, object state, CancellationToken cancellationToken, TaskContinuationOptions continuationOptions, TaskScheduler scheduler) { if (continuationFunction == null) { throw new ArgumentNullException(nameof(continuationFunction)); } if (scheduler != TaskScheduler.Default) { throw new NotImplementedException(); } TaskCreationOptions creationOptions = CreationOptionsFromContinuationOptions(continuationOptions); var continuationTask = new ContinuationResultTaskFromTask(this, continuationFunction, state, cancellationToken, creationOptions); ContinueWithCore(continuationTask, continuationOptions); return continuationTask; } #endregion Func continuation #endregion Continuation methods /// /// Waits for all of the provided objects to complete execution. /// /// /// An array of instances on which to wait. /// /// /// The argument is null. /// /// /// The argument contains a null element. /// /// /// At least one of the instances was canceled -or- an exception was thrown during /// the execution of at least one of the instances. /// ////[MethodImpl(MethodImplOptions.NoOptimization)] // this is needed for the parallel debugger public static void WaitAll(params Task[] tasks) { WaitAll(tasks, Timeout.Infinite); } /// /// Waits for all of the provided objects to complete execution. /// /// /// true if all of the instances completed execution within the allotted time; /// otherwise, false. /// /// /// An array of instances on which to wait. /// /// /// A that represents the number of milliseconds to wait, or a that represents -1 milliseconds to wait indefinitely. /// /// /// The argument is null. /// /// /// The argument contains a null element. /// /// /// At least one of the instances was canceled -or- an exception was thrown during /// the execution of at least one of the instances. /// /// /// is a negative number other than -1 milliseconds, which represents an /// infinite time-out -or- timeout is greater than /// . /// ////[MethodImpl(MethodImplOptions.NoOptimization)] // this is needed for the parallel debugger public static bool WaitAll(Task[] tasks, TimeSpan timeout) { long totalMilliseconds = (long)timeout.TotalMilliseconds; if ((totalMilliseconds < -1) || (totalMilliseconds > Int32.MaxValue)) { throw new ArgumentOutOfRangeException(nameof(timeout)); } return WaitAll(tasks, (int)totalMilliseconds); } /// /// Waits for all of the provided objects to complete execution. /// /// /// true if all of the instances completed execution within the allotted time; /// otherwise, false. /// /// /// The number of milliseconds to wait, or (-1) to /// wait indefinitely. /// An array of instances on which to wait. /// /// /// The argument is null. /// /// /// The argument contains a null element. /// /// /// At least one of the instances was canceled -or- an exception was thrown during /// the execution of at least one of the instances. /// /// /// is a negative number other than -1, which represents an /// infinite time-out. /// ////[MethodImpl(MethodImplOptions.NoOptimization)] // this is needed for the parallel debugger public static bool WaitAll(Task[] tasks, int millisecondsTimeout) { return WaitAll(tasks, millisecondsTimeout, default(CancellationToken)); } /// /// Waits for all of the provided objects to complete execution. /// /// /// true if all of the instances completed execution within the allotted time; /// otherwise, false. /// /// /// An array of instances on which to wait. /// /// /// A to observe while waiting for the tasks to complete. /// /// /// The argument is null. /// /// /// The argument contains a null element. /// /// /// At least one of the instances was canceled -or- an exception was thrown during /// the execution of at least one of the instances. /// /// /// The was canceled. /// ////[MethodImpl(MethodImplOptions.NoOptimization)] // this is needed for the parallel debugger public static void WaitAll(Task[] tasks, CancellationToken cancellationToken) { WaitAll(tasks, Timeout.Infinite, cancellationToken); } /// /// Waits for all of the provided objects to complete execution. /// /// /// true if all of the instances completed execution within the allotted time; /// otherwise, false. /// /// /// An array of instances on which to wait. /// /// /// The number of milliseconds to wait, or (-1) to /// wait indefinitely. /// /// /// A to observe while waiting for the tasks to complete. /// /// /// The argument is null. /// /// /// The argument contains a null element. /// /// /// At least one of the instances was canceled -or- an exception was thrown during /// the execution of at least one of the instances. /// /// /// is a negative number other than -1, which represents an /// infinite time-out. /// /// /// The was canceled. /// ////[MethodImpl(MethodImplOptions.NoOptimization)] // this is needed for the parallel debugger public static bool WaitAll(Task[] tasks, int millisecondsTimeout, CancellationToken cancellationToken) { if (tasks == null) { throw new ArgumentNullException(nameof(tasks)); } if (millisecondsTimeout < -1) { throw new ArgumentOutOfRangeException(nameof(millisecondsTimeout)); } if (tasks.Length == 0) { return true; } Task allCompleted = WhenAll(tasks); return allCompleted.Wait(millisecondsTimeout, cancellationToken); } /// /// Waits for any of the provided objects to complete execution. /// /// /// An array of instances on which to wait. /// /// The index of the completed task in the array argument. /// /// The argument is null. /// /// /// The argument contains a null element. /// ////[MethodImpl(MethodImplOptions.NoOptimization)] // this is needed for the parallel debugger public static int WaitAny(params Task[] tasks) { return WaitAny(tasks, Timeout.Infinite); } /// /// Waits for any of the provided objects to complete execution. /// /// /// An array of instances on which to wait. /// /// /// A that represents the number of milliseconds to wait, or a that represents -1 milliseconds to wait indefinitely. /// /// /// The index of the completed task in the array argument, or -1 if the /// timeout occurred. /// /// /// The argument is null. /// /// /// The argument contains a null element. /// /// /// is a negative number other than -1 milliseconds, which represents an /// infinite time-out -or- timeout is greater than /// . /// ////[MethodImpl(MethodImplOptions.NoOptimization)] // this is needed for the parallel debugger public static int WaitAny(Task[] tasks, TimeSpan timeout) { long totalMilliseconds = (long)timeout.TotalMilliseconds; if ((totalMilliseconds < -1) || (totalMilliseconds > Int32.MaxValue)) { throw new ArgumentOutOfRangeException(nameof(timeout)); } return WaitAny(tasks, (int)totalMilliseconds); } /// /// Waits for any of the provided objects to complete execution. /// /// /// An array of instances on which to wait. /// /// /// A to observe while waiting for a task to complete. /// /// /// The index of the completed task in the array argument. /// /// /// The argument is null. /// /// /// The argument contains a null element. /// /// /// The was canceled. /// ////[MethodImpl(MethodImplOptions.NoOptimization)] // this is needed for the parallel debugger public static int WaitAny(Task[] tasks, CancellationToken cancellationToken) { return WaitAny(tasks, Timeout.Infinite, cancellationToken); } /// /// Waits for any of the provided objects to complete execution. /// /// /// An array of instances on which to wait. /// /// /// The number of milliseconds to wait, or (-1) to /// wait indefinitely. /// /// /// The index of the completed task in the array argument, or -1 if the /// timeout occurred. /// /// /// The argument is null. /// /// /// The argument contains a null element. /// /// /// is a negative number other than -1, which represents an /// infinite time-out. /// ////[MethodImpl(MethodImplOptions.NoOptimization)] // this is needed for the parallel debugger public static int WaitAny(Task[] tasks, int millisecondsTimeout) { return WaitAny(tasks, millisecondsTimeout, default(CancellationToken)); } /// /// Waits for any of the provided objects to complete execution. /// /// /// An array of instances on which to wait. /// /// /// The number of milliseconds to wait, or (-1) to /// wait indefinitely. /// /// /// A to observe while waiting for a task to complete. /// /// /// The index of the completed task in the array argument, or -1 if the /// timeout occurred. /// /// /// The argument is null. /// /// /// The argument contains a null element. /// /// /// is a negative number other than -1, which represents an /// infinite time-out. /// /// /// The was canceled. /// ////[MethodImpl(MethodImplOptions.NoOptimization)] // this is needed for the parallel debugger public static int WaitAny(Task[] tasks, int millisecondsTimeout, CancellationToken cancellationToken) { if (tasks == null) { throw new ArgumentNullException(nameof(tasks)); } if (millisecondsTimeout < -1) { throw new ArgumentOutOfRangeException(nameof(millisecondsTimeout)); } if (tasks.Length == 0) { return -1; } Task firstCompleted = WhenAny(tasks); if (!firstCompleted.Wait(millisecondsTimeout, cancellationToken)) { return -1; } return Array.IndexOf(tasks, firstCompleted.Result); } #region FromResult / FromException / FromCancellation /// Creates a that's completed successfully with the specified result. /// The type of the result returned by the task. /// The result to store into the completed task. /// The successfully completed task. public static Task FromResult(TResult result) { return new Task(result); } #if DISABLED_FOR_LLILUM /// Creates a that's completed exceptionally with the specified exception. /// The type of the result returned by the task. /// The exception with which to complete the task. /// The faulted task. public static Task FromException(Exception exception) { return FromException(exception); } /// Creates a that's completed exceptionally with the specified exception. /// The type of the result returned by the task. /// The exception with which to complete the task. /// The faulted task. public static Task FromException(Exception exception) { if (exception == null) { throw new ArgumentNullException(nameof(exception)); } throw new NotImplementedException(); } #endif // DISABLED_FOR_LLILUM /// Creates a that's completed due to cancellation with the specified token. /// The token with which to complete the task. /// The canceled task. public static Task FromCanceled(CancellationToken cancellationToken) { if (!cancellationToken.IsCancellationRequested) { throw new ArgumentOutOfRangeException(nameof(cancellationToken)); } return new Task(true, cancellationToken); } /// Creates a that's completed due to cancellation with the specified token. /// The type of the result returned by the task. /// The token with which to complete the task. /// The canceled task. public static Task FromCanceled(CancellationToken cancellationToken) { if (!cancellationToken.IsCancellationRequested) { throw new ArgumentOutOfRangeException(nameof(cancellationToken)); } return new Task(false, default(TResult), cancellationToken); } #if DISABLED_FOR_LLILUM /// Creates a that's completed due to cancellation with the specified exception. /// The type of the result returned by the task. /// The exception with which to complete the task. /// The canceled task. internal static Task FromCancellation(OperationCanceledException exception) { if (exception == null) { throw new ArgumentNullException(nameof(exception)); } throw new NotImplementedException(); } #endif // DISABLED_FOR_LLILUM #endregion FromResult / FromException / FromCancellation #region Run methods /// /// Queues the specified work to run on the ThreadPool and returns a Task handle for that work. /// /// The work to execute asynchronously /// A Task that represents the work queued to execute in the ThreadPool. /// /// The parameter was null. /// public static Task Run(Action action) { var task = new Task(action); task.Start(); return task; } /// /// Queues the specified work to run on the ThreadPool and returns a Task handle for that work. /// /// The work to execute asynchronously /// A cancellation token that should be used to cancel the work /// A Task that represents the work queued to execute in the ThreadPool. /// /// The parameter was null. /// /// /// The associated with was disposed. /// public static Task Run(Action action, CancellationToken cancellationToken) { var task = new Task(action, cancellationToken); task.Start(); return task; } /// /// Queues the specified work to run on the ThreadPool and returns a Task(TResult) handle for that work. /// /// The work to execute asynchronously /// A Task(TResult) that represents the work queued to execute in the ThreadPool. /// /// The parameter was null. /// public static Task Run(Func function) { return Run(function, default(CancellationToken)); } /// /// Queues the specified work to run on the ThreadPool and returns a Task(TResult) handle for that work. /// /// The work to execute asynchronously /// A cancellation token that should be used to cancel the work /// A Task(TResult) that represents the work queued to execute in the ThreadPool. /// /// The parameter was null. /// /// /// The associated with was disposed. /// public static Task Run(Func function, CancellationToken cancellationToken) { if (function == null) { throw new ArgumentNullException(nameof(function)); } var task = new Task(function, cancellationToken); task.Start(); return task; } /// /// Queues the specified work to run on the ThreadPool and returns a proxy for the /// Task returned by . /// /// The work to execute asynchronously /// A Task that represents a proxy for the Task returned by . /// /// The parameter was null. /// public static Task Run(Func function) { return Run(function, default(CancellationToken)); } /// /// Queues the specified work to run on the ThreadPool and returns a proxy for the /// Task returned by . /// /// The work to execute asynchronously /// A cancellation token that should be used to cancel the work /// A Task that represents a proxy for the Task returned by . /// /// The parameter was null. /// /// /// The associated with was disposed. /// public static Task Run(Func function, CancellationToken cancellationToken) { if (function == null) { throw new ArgumentNullException(nameof(function)); } var task = new Task(function, cancellationToken); task.Start(); return new UnwrapPromise(task); } /// /// Queues the specified work to run on the ThreadPool and returns a proxy for the /// Task(TResult) returned by . /// /// The type of the result returned by the proxy Task. /// The work to execute asynchronously /// A Task(TResult) that represents a proxy for the Task(TResult) returned by . /// /// The parameter was null. /// public static Task Run(Func> function) { return Run(function, default(CancellationToken)); } /// /// Queues the specified work to run on the ThreadPool and returns a proxy for the /// Task(TResult) returned by . /// /// The type of the result returned by the proxy Task. /// The work to execute asynchronously /// A cancellation token that should be used to cancel the work /// A Task(TResult) that represents a proxy for the Task(TResult) returned by . /// /// The parameter was null. /// public static Task Run(Func> function, CancellationToken cancellationToken) { if (function == null) { throw new ArgumentNullException(nameof(function)); } var task = new Task>(function, cancellationToken); task.Start(); return new UnwrapPromise(task); } #endregion Run methods #region Delay methods /// /// Creates a Task that will complete after a time delay. /// /// The time span to wait before completing the returned Task /// A Task that represents the time delay /// /// The is less than -1 or greater than Int32.MaxValue. /// /// /// After the specified time delay, the Task is completed in RanToCompletion state. /// public static Task Delay(TimeSpan delay) { long totalMilliseconds = (long)delay.TotalMilliseconds; if ((totalMilliseconds < -1) || (totalMilliseconds > Int32.MaxValue)) { throw new ArgumentOutOfRangeException("delay"); } return Delay((int)totalMilliseconds); } /// /// Creates a Task that will complete after a time delay. /// /// The time span to wait before completing the returned Task /// The cancellation token that will be checked prior to completing the returned Task /// A Task that represents the time delay /// /// The is less than -1 or greater than Int32.MaxValue. /// /// /// The provided has already been disposed. /// /// /// If the cancellation token is signaled before the specified time delay, then the Task is completed in /// Canceled state. Otherwise, the Task is completed in RanToCompletion state once the specified time /// delay has expired. /// public static Task Delay(TimeSpan delay, CancellationToken cancellationToken) { long totalMilliseconds = (long)delay.TotalMilliseconds; if ((totalMilliseconds < -1) || (totalMilliseconds > Int32.MaxValue)) { throw new ArgumentOutOfRangeException("delay"); } return Delay((int)totalMilliseconds, cancellationToken); } /// /// Creates a Task that will complete after a time delay. /// /// The number of milliseconds to wait before completing the returned Task /// A Task that represents the time delay /// /// The is less than -1. /// /// /// After the specified time delay, the Task is completed in RanToCompletion state. /// public static Task Delay(int millisecondsDelay) { return Delay(millisecondsDelay, default(CancellationToken)); } /// /// Creates a Task that will complete after a time delay. /// /// The number of milliseconds to wait before completing the returned Task /// The cancellation token that will be checked prior to completing the returned Task /// A Task that represents the time delay /// /// The is less than -1. /// /// /// The provided has already been disposed. /// /// /// If the cancellation token is signaled before the specified time delay, then the Task is completed in /// Canceled state. Otherwise, the Task is completed in RanToCompletion state once the specified time /// delay has expired. /// public static Task Delay(int millisecondsDelay, CancellationToken cancellationToken) { // Throw on non-sensical time if (millisecondsDelay < -1) { throw new ArgumentOutOfRangeException(nameof(millisecondsDelay)); } // Short-cuts for pre-canceled and already-complete timers. if (cancellationToken.IsCancellationRequested) { return Task.FromCanceled(cancellationToken); } else if (millisecondsDelay == 0) { return CompletedTask; } var promise = new DelayPromise(cancellationToken); if (cancellationToken.CanBeCanceled) { promise.Registration = cancellationToken.Register(DelayPromise.Complete, promise); } // Don't bother scheduling an infinite timer. if (millisecondsDelay != Timeout.Infinite) { promise.Timer = new Timer(DelayPromise.Complete, promise, millisecondsDelay, Timeout.Infinite); } return promise; } #endregion Delay methods #region WhenAll /// /// Creates a task that will complete when all of the supplied tasks have completed. /// /// The tasks to wait on for completion. /// A task that represents the completion of all of the supplied tasks. /// /// /// If any of the supplied tasks completes in a faulted state, the returned task will also complete in a Faulted state, /// where its exceptions will contain the aggregation of the set of unwrapped exceptions from each of the supplied tasks. /// /// /// If none of the supplied tasks faulted but at least one of them was canceled, the returned task will end in the Canceled state. /// /// /// If none of the tasks faulted and none of the tasks were canceled, the resulting task will end in the RanToCompletion state. /// /// /// If the supplied array/enumerable contains no tasks, the returned task will immediately transition to a RanToCompletion /// state before it's returned to the caller. /// /// /// /// The argument was null. /// /// /// The collection contained a null task. /// public static Task WhenAll(IEnumerable tasks) { if (tasks == null) { throw new ArgumentNullException(nameof(tasks)); } int taskCount = 0; foreach (var task in tasks) { if (task == null) { throw new ArgumentException(multiTaskContinuation_NullTask, nameof(tasks)); } ++taskCount; } if (taskCount == 0) { return CompletedTask; } var promise = new WhenAllPromise(taskCount); foreach (var task in tasks) { task.AddCompletionAction(promise); } return promise; } /// /// Creates a task that will complete when all of the supplied tasks have completed. /// /// The tasks to wait on for completion. /// A task that represents the completion of all of the supplied tasks. /// /// /// If any of the supplied tasks completes in a faulted state, the returned task will also complete in a Faulted state, /// where its exceptions will contain the aggregation of the set of unwrapped exceptions from each of the supplied tasks. /// /// /// If none of the supplied tasks faulted but at least one of them was canceled, the returned task will end in the Canceled state. /// /// /// If none of the tasks faulted and none of the tasks were canceled, the resulting task will end in the RanToCompletion state. /// /// /// If the supplied array/enumerable contains no tasks, the returned task will immediately transition to a RanToCompletion /// state before it's returned to the caller. /// /// /// /// The argument was null. /// /// /// The array contained a null task. /// public static Task WhenAll(params Task[] tasks) { if (tasks == null) { throw new ArgumentNullException(nameof(tasks)); } if (tasks.Length == 0) { return CompletedTask; } var promise = new WhenAllPromise(tasks.Length); foreach (var task in tasks) { task.AddCompletionAction(promise); } return promise; } /// /// Creates a task that will complete when all of the supplied tasks have completed. /// /// The tasks to wait on for completion. /// A task that represents the completion of all of the supplied tasks. /// /// /// If any of the supplied tasks completes in a faulted state, the returned task will also complete in a Faulted state, /// where its exceptions will contain the aggregation of the set of unwrapped exceptions from each of the supplied tasks. /// /// /// If none of the supplied tasks faulted but at least one of them was canceled, the returned task will end in the Canceled state. /// /// /// If none of the tasks faulted and none of the tasks were canceled, the resulting task will end in the RanToCompletion state. /// The Result of the returned task will be set to an array containing all of the results of the /// supplied tasks in the same order as they were provided (e.g. if the input tasks array contained t1, t2, t3, the output /// task's Result will return an TResult[] where arr[0] == t1.Result, arr[1] == t2.Result, and arr[2] == t3.Result). /// /// /// If the supplied array/enumerable contains no tasks, the returned task will immediately transition to a RanToCompletion /// state before it's returned to the caller. The returned TResult[] will be an array of 0 elements. /// /// /// /// The argument was null. /// /// /// The collection contained a null task. /// public static Task WhenAll(IEnumerable> tasks) { if (tasks == null) { throw new ArgumentNullException(nameof(tasks)); } var tasksCopy = CopyTaskCollection(tasks); if (tasksCopy == null) { return new Task(new TResult[0]); } return new WhenAllPromise(tasksCopy); } /// /// Creates a task that will complete when all of the supplied tasks have completed. /// /// The tasks to wait on for completion. /// A task that represents the completion of all of the supplied tasks. /// /// /// If any of the supplied tasks completes in a faulted state, the returned task will also complete in a Faulted state, /// where its exceptions will contain the aggregation of the set of unwrapped exceptions from each of the supplied tasks. /// /// /// If none of the supplied tasks faulted but at least one of them was canceled, the returned task will end in the Canceled state. /// /// /// If none of the tasks faulted and none of the tasks were canceled, the resulting task will end in the RanToCompletion state. /// The Result of the returned task will be set to an array containing all of the results of the /// supplied tasks in the same order as they were provided (e.g. if the input tasks array contained t1, t2, t3, the output /// task's Result will return an TResult[] where arr[0] == t1.Result, arr[1] == t2.Result, and arr[2] == t3.Result). /// /// /// If the supplied array/enumerable contains no tasks, the returned task will immediately transition to a RanToCompletion /// state before it's returned to the caller. The returned TResult[] will be an array of 0 elements. /// /// /// /// The argument was null. /// /// /// The array contained a null task. /// public static Task WhenAll(params Task[] tasks) { if (tasks == null) { throw new ArgumentNullException(nameof(tasks)); } var tasksCopy = CopyTaskCollection(tasks); if (tasksCopy == null) { return new Task(new TResult[0]); } return new WhenAllPromise(tasksCopy); } #endregion WhenAll #region WhenAny /// /// Creates a task that will complete when any of the supplied tasks have completed. /// /// The tasks to wait on for completion. /// A task that represents the completion of one of the supplied tasks. The return Task's Result is the task that completed. /// /// The returned task will complete when any of the supplied tasks has completed. The returned task will always end in the RanToCompletion state /// with its Result set to the first task to complete. This is true even if the first task to complete ended in the Canceled or Faulted state. /// /// /// The argument was null. /// /// /// The array contained a null task, or was empty. /// public static Task WhenAny(params Task[] tasks) { if (tasks == null) { throw new ArgumentNullException(nameof(tasks)); } if (tasks.Length == 0) { throw new ArgumentException(multiTaskContinuation_EmptyTaskList, nameof(tasks)); } #if ENABLE_CONTRACTS Contract.EndContractBlock(); #endif // ENABLE_CONTRACTS var promise = new WhenAnyPromise(); foreach (var task in tasks) { task.AddCompletionAction(promise); } return promise; } /// /// Creates a task that will complete when any of the supplied tasks have completed. /// /// The tasks to wait on for completion. /// A task that represents the completion of one of the supplied tasks. The return Task's Result is the task that completed. /// /// The returned task will complete when any of the supplied tasks has completed. The returned task will always end in the RanToCompletion state /// with its Result set to the first task to complete. This is true even if the first task to complete ended in the Canceled or Faulted state. /// /// /// The argument was null. /// /// /// The collection contained a null task, or was empty. /// public static Task WhenAny(IEnumerable tasks) { if (tasks == null) { throw new ArgumentNullException(nameof(tasks)); } var promise = new WhenAnyPromise(); bool haveTasks = false; foreach (var task in tasks) { haveTasks = true; task.AddCompletionAction(promise); } if (!haveTasks) { throw new ArgumentException(multiTaskContinuation_EmptyTaskList); } return promise; } /// /// Creates a task that will complete when any of the supplied tasks have completed. /// /// The tasks to wait on for completion. /// A task that represents the completion of one of the supplied tasks. The return Task's Result is the task that completed. /// /// The returned task will complete when any of the supplied tasks has completed. The returned task will always end in the RanToCompletion state /// with its Result set to the first task to complete. This is true even if the first task to complete ended in the Canceled or Faulted state. /// /// /// The argument was null. /// /// /// The array contained a null task, or was empty. /// public static Task> WhenAny(params Task[] tasks) { if (tasks == null) { throw new ArgumentNullException(nameof(tasks)); } if (tasks.Length == 0) { throw new ArgumentException(multiTaskContinuation_EmptyTaskList, nameof(tasks)); } #if ENABLE_CONTRACTS Contract.EndContractBlock(); #endif // ENABLE_CONTRACTS var promise = new WhenAnyPromise(); foreach (var task in tasks) { task.AddCompletionAction(promise); } return promise; } /// /// Creates a task that will complete when any of the supplied tasks have completed. /// /// The tasks to wait on for completion. /// A task that represents the completion of one of the supplied tasks. The return Task's Result is the task that completed. /// /// The returned task will complete when any of the supplied tasks has completed. The returned task will always end in the RanToCompletion state /// with its Result set to the first task to complete. This is true even if the first task to complete ended in the Canceled or Faulted state. /// /// /// The argument was null. /// /// /// The collection contained a null task, or was empty. /// public static Task> WhenAny(IEnumerable> tasks) { if (tasks == null) { throw new ArgumentNullException(nameof(tasks)); } var promise = new WhenAnyPromise(); bool haveTasks = false; foreach (var task in tasks) { haveTasks = true; task.AddCompletionAction(promise); } if (!haveTasks) { throw new ArgumentException(multiTaskContinuation_EmptyTaskList); } return promise; } #endregion WhenAny internal static TaskCreationOptions CreationOptionsFromContinuationOptions(TaskContinuationOptions continuationOptions) { // This is used a couple of times below const TaskContinuationOptions notOnAnything = TaskContinuationOptions.NotOnCanceled | TaskContinuationOptions.NotOnFaulted | TaskContinuationOptions.NotOnRanToCompletion; const TaskContinuationOptions creationOptionsMask = TaskContinuationOptions.PreferFairness | TaskContinuationOptions.LongRunning | TaskContinuationOptions.DenyChildAttach | TaskContinuationOptions.HideScheduler | TaskContinuationOptions.AttachedToParent | TaskContinuationOptions.RunContinuationsAsynchronously; const TaskContinuationOptions supportedOptionsMask = TaskContinuationOptions.PreferFairness | TaskContinuationOptions.LongRunning | TaskContinuationOptions.DenyChildAttach | TaskContinuationOptions.HideScheduler | TaskContinuationOptions.RunContinuationsAsynchronously | TaskContinuationOptions.NotOnRanToCompletion | TaskContinuationOptions.NotOnFaulted | TaskContinuationOptions.NotOnCanceled | TaskContinuationOptions.ExecuteSynchronously; // Check that LongRunning and ExecuteSynchronously are not specified together TaskContinuationOptions illegalMask = TaskContinuationOptions.ExecuteSynchronously | TaskContinuationOptions.LongRunning; if ((continuationOptions & illegalMask) == illegalMask) { throw new ArgumentOutOfRangeException(nameof(continuationOptions), "The specified TaskContinuationOptions combined LongRunning and ExecuteSynchronously. Synchronous continuations should not be long running."); } // Check that no illegal options were specified if ((continuationOptions & ~supportedOptionsMask) != 0) { throw new ArgumentOutOfRangeException(nameof(continuationOptions)); } // Check that we didn't specify "not on anything" if ((continuationOptions & notOnAnything) == notOnAnything) { throw new ArgumentOutOfRangeException(nameof(continuationOptions), "The specified TaskContinuationOptions excluded all continuation kinds."); } // This passes over all but LazyCancellation, which has no representation in TaskCreationOptions return (TaskCreationOptions)(continuationOptions & creationOptionsMask); } internal bool Start(bool runSynchronously) { if (runSynchronously) { return OnComplete(); } else { ThreadPool.QueueUserWorkItem(task => ((Task)task).OnComplete(), this); } return true; } internal void InternalCancel() { // Try to update the status. We don't try to remove this from the running thread pool, but we'll skip // calling Invoke if this succeeds. Note that tasks in the Running or RanToCompletion status will not be // canceled. AtomicStateUpdate(TaskStatus.Canceled); } internal virtual void Invoke() { var action = m_action as Action; if (action != null) { action(); return; } var actionWithState = m_action as Action; if (actionWithState != null) { actionWithState(m_stateObject); return; } // This task's m_action isn't set, which means it must be a special Promise-type task. throw new InvalidOperationException(); } internal void ContinueWithCore(Task continuationTask, TaskContinuationOptions continuationOptions) { var continuation = new TaskContinuation(continuationTask, continuationOptions); // Register the continuation. If synchronous execution is requested, this may actually invoke it here. if (!AddTaskContinuation(continuation, addBeforeOthers: false)) { continuation.RunOrSchedule(this); } } /// /// Sets a continuation onto the . /// The continuation is scheduled to run in the current synchronization context is one exists, /// otherwise in the current task scheduler. /// /// The action to invoke when the has completed. /// Whether to flow ExecutionContext across the await. /// A stack crawl mark tied to execution context. /// The awaiter was not properly initialized. [SecurityCritical] internal void SetContinuationForAwait(Action continuationAction) { #if ENABLE_CONTRACTS Contract.Requires(continuationAction != null); #endif // ENABLE_CONTRACTS // Try to add the continuation cheaply, without a wrapper. If we fail, the task is complete; schedule it on // the thread pool. We must do this to avoid stack overflow on particularly long await chains. if (!AddTaskContinuation(continuationAction, addBeforeOthers: false)) { Run(continuationAction); } } private bool OnComplete() { if (AtomicStateUpdate(TaskStatus.Running)) { try { Invoke(); AtomicStateUpdate(TaskStatus.RanToCompletion); } catch { // TODO: Record caught exceptions. AtomicStateUpdate(TaskStatus.Faulted); } } m_contingentProperties?.CancellationRegistration.Dispose(); FinishContinuations(); return true; } private void AddCompletionAction(ITaskCompletionAction action) { if (!AddTaskContinuation(action, addBeforeOthers: true)) { action.Invoke(this); } } private bool AddTaskContinuation(object tc, bool addBeforeOthers) { // Make sure that, if someone calls ContinueWith right after waiting for the predecessor to complete, we // don't queue up a continuation. if (IsCompleted) { return false; } // If this is the first continuation, avoid allocation of a list by slamming it directly into the object // pointer. This saves on allocations for the trivial single-continuation case. if ((m_continuationObject != null) || (Interlocked.CompareExchange(ref m_continuationObject, tc, null) != null)) { // We must have already added a continuation at some point, which means we must go to the complex case. return AddTaskContinuationComplex(tc, addBeforeOthers); } return true; } /// /// Support method for AddTaskContinuation that takes care of multi-continuation logic. This method assumes that /// m_continuationObject is not null. That case was taken care of in the calling method, AddTaskContinuation(). /// /// The task to queue. /// True if the task should be added at the beginning of the list. /// True if and only if the continuation was successfully queued. private bool AddTaskContinuationComplex(object tc, bool addBeforeOthers) { // NOTE: This logic was pulled from Task.cs in the CoreCLR. It has been modified for reduced memory usage // and clarity. object oldValue = m_continuationObject; // Logic for the case where we were previously storing a single continuation. if ((oldValue != s_taskCompletionSentinel) && !(oldValue is List)) { // Construct a new TaskContinuation list with the old value. We start with a relatively small explicit // capacity, as it's rare that a task will have more than a few continuations. List newList = new List(4); newList.Add(oldValue); // Swap out the old continuation for the new list. Interlocked.CompareExchange(ref m_continuationObject, newList, oldValue); // We might be racing against another thread converting the single into a list, or we might be racing // against task completion, so resample "list" below. } // m_continuationObject is guaranteed at this point to be either a List or s_taskCompletionSentinel. List list = m_continuationObject as List; // If list is null, it can only mean that s_taskCompletionSentinel has been exchanged into // m_continuationObject. Thus, the task has completed and we should fail to add the continuation. if (list == null) { return false; } lock (list) { // It is possible for the task to complete right after we snap the copy of the list. If so, then fall // through and return false without queuing the continuation. if (m_continuationObject == s_taskCompletionSentinel) { return false; } if (addBeforeOthers) { list.Insert(0, tc); } else { list.Add(tc); } } return true; } /// /// Removes a continuation from m_continuationObject. /// /// The continuation object to remove. private void RemoveContinuation(object tc) { object continuationObject = m_continuationObject; // If the task is completed, do nothing. The continuations have already been run, or are currently running. if (continuationObject == s_taskCompletionSentinel) { return; } List list = continuationObject as List; if (list == null) { // This is not a list. If we have a single object (the one we want to remove) we try to replace it // with an empty list. Note we cannot go back to a null state, since it will mess up the // AddTaskContinuation logic. if (Interlocked.CompareExchange(ref m_continuationObject, new List(), continuationObject) == continuationObject) { // Exchange was successful so we can skip the last comparison return; } // If we fail it means that either AddContinuation won the race condition and m_continuationObject is // now a List that contains the element we want to remove, or FinishContinuations set the // s_taskCompletionSentinel. We'll inspect it again below. list = m_continuationObject as List; } // We must resample list, as it may have changed above. if (list != null) { lock (list) { // There is a small chance that this task completed since we took a local snapshot into // continuationsLocalRef. In that case, just return; we don't want to be manipulating the // continuation list as it is being processed. if (m_continuationObject == s_taskCompletionSentinel) { return; } list.Remove(continuationObject); } } } /// /// Runs all of the continuations, as appropriate. /// internal void FinishContinuations() { // Atomically store the fact that this task is completing. From this point on, the adding of continuations // will result in the continuations being run/launched directly rather than being added to the continuation // list. object continuationObject = Interlocked.Exchange(ref m_continuationObject, s_taskCompletionSentinel); if ((continuationObject != null) && (continuationObject != s_taskCompletionSentinel)) { var continuationsAsList = continuationObject as List; if (continuationsAsList == null) { InvokeSingleContinuation(continuationObject); } else { foreach (var continuationObj in continuationsAsList) { InvokeSingleContinuation(continuationObj); } } } } /// /// Transfer a cancellation token from another task. This should only be used for promise tasks where no /// cancellation token was supplied when the task was created. /// /// internal void RecordInternalCancellationRequest(CancellationToken tokenToRecord) { #if ENABLE_CONTRACTS Contract.Assert(m_cancellationToken == default(CancellationToken)); #endif // ENABLE_CONTRACTS // Store the supplied cancellation token as this task's token. // Waiting on this task will then result in an OperationCanceledException containing this token. if (tokenToRecord != default(CancellationToken)) { m_contingentProperties = new ContingentProperties(); m_contingentProperties.CancellationToken = tokenToRecord; } } /// /// Invokes a single continuation. /// /// The continuation to invoke. private void InvokeSingleContinuation(object continuationObj) { // Continuation created through public methods, exposed as a task. var continuationTask = continuationObj as TaskContinuation; if (continuationTask != null) { continuationTask.RunOrSchedule(this); return; } // System-created continuation, lighter weight and not necessarily a task. var completionAction = continuationObj as ITaskCompletionAction; if (completionAction != null) { completionAction.Invoke(this); return; } // Raw action, scheduled through TaskAwaiter. var rawAction = continuationObj as Action; if (rawAction != null) { rawAction.Invoke(); return; } } private static T[] CopyTaskCollection(IEnumerable tasks) where T : Task { int taskCount; // Count the tasks in a separate pass to save on allocations. var taskCollection = tasks as ICollection; if (taskCollection != null) { taskCount = taskCollection.Count; } else { taskCount = 0; foreach (var task in tasks) { ++taskCount; } } if (taskCount == 0) { return null; } var tasksCopy = new T[taskCount]; int i = 0; foreach (var task in tasks) { if (task == null) { throw new ArgumentException(multiTaskContinuation_NullTask, nameof(tasks)); } tasksCopy[i] = task; ++i; } return tasksCopy; } #region Promise helpers private sealed class DelayPromise : Task { internal readonly CancellationToken Token; internal CancellationTokenRegistration Registration; internal Timer Timer; internal DelayPromise(CancellationToken token) : base() { Token = token; } internal static void Complete(object thisObj) { ((DelayPromise)thisObj).Complete(); } internal void Complete() { if (Token.IsCancellationRequested) { TrySetCanceled(Token); } else { TrySetResult(default(VoidTaskResult)); } Timer?.Dispose(); Registration.Dispose(); } } private sealed class WhenAllPromise : Task, ITaskCompletionAction { private int m_count; private Task m_canceledTask; internal WhenAllPromise(int taskCount) : base() { m_count = taskCount; } public void Invoke(Task completedTask) { // Cache the first antecedent that gets canceled. if (completedTask.IsCanceled) { Interlocked.CompareExchange(ref m_canceledTask, completedTask, null); } if (Interlocked.Decrement(ref m_count) == 0) { if (m_canceledTask == null) { TrySetResult(default(VoidTaskResult)); } else { TrySetCanceled(m_canceledTask.CancellationToken); } m_canceledTask = null; } } } private sealed class WhenAllPromise : Task, ITaskCompletionAction { private Task[] m_tasks; private int m_count; internal WhenAllPromise(Task[] tasks) : base() { m_tasks = tasks; m_count = tasks.Length; // This must be done last as it can result in synchronous invocation. foreach (var task in tasks) { task.AddCompletionAction(this); } } public void Invoke(Task completedTask) { if (Interlocked.Decrement(ref m_count) == 0) { var results = new TResult[m_tasks.Length]; for (int i = 0; i < m_tasks.Length; ++i) { Task task = m_tasks[i]; if (task.IsFaulted) { // TODO: Implement this when we can throw exceptions. break; } else if (task.IsCanceled) { TrySetCanceled(task.CancellationToken); break; } else { results[i] = task.Result; } // Avoid holding onto tasks. m_tasks[i] = null; } // If we didn't find a faulted or canceled task, try to set the result. if (!IsCompleted) { TrySetResult(results); } m_tasks = null; } } } private sealed class WhenAnyPromise : Task, ITaskCompletionAction { public void Invoke(Task completedTask) { TrySetResult(completedTask); } } private sealed class WhenAnyPromise : Task>, ITaskCompletionAction { public void Invoke(Task completedTask) { TrySetResult((Task)completedTask); } } /// /// This class acts as a proxy for compiler-created tasks which have not yet been allocated. It wraps a generic /// task which will create and return a started inner task when invoked. The results of this inner task are then /// transferred on its completion to this proxy and exposed as if this object was itself the inner task. /// /// The result type of the inner task. private class UnwrapPromise : Task, ITaskCompletionAction { enum InvokeState { WaitingOnOuter = 0, WaitingOnInner, Done, } private InvokeState m_state; public UnwrapPromise(Task outerTask) : base() { outerTask.AddCompletionAction(this); } public void Invoke(Task completedTask) { switch (m_state) { case InvokeState.WaitingOnOuter: ProcessCompletedOuterTask(completedTask); break; case InvokeState.WaitingOnInner: TrySetFromTask(completedTask, lookForOce: false); m_state = InvokeState.Done; break; #if ENABLE_CONTRACTS default: Contract.Assert(false, "UnwrapPromise in illegal state."); break; #endif // ENABLE_CONTRACTS } } private void ProcessCompletedOuterTask(Task task) { switch (task.Status) { case TaskStatus.Canceled: case TaskStatus.Faulted: TrySetFromTask(task, lookForOce: true); m_state = InvokeState.Done; break; case TaskStatus.RanToCompletion: Task innerTask; // Pull the inner task out of the completed outer task. var taskOfTask = task as Task>; // Either a Task or a Task> if (taskOfTask == null) { innerTask = ((Task)task).Result; } else { innerTask = taskOfTask.Result; } // Queue up this completion action again on the inner task. if (innerTask == null) { TrySetCanceled(default(CancellationToken)); m_state = InvokeState.Done; } else { // Set the state before we add the completion, in case it invokes synchronously. m_state = InvokeState.WaitingOnInner; task.AddCompletionAction(this); } break; } } /// Transfer the completion status from "task" to ourself. /// The source task whose results should be transfered to this promise. /// Whether or not to look for OperationCanceledExceptions in task's exceptions if it faults. private void TrySetFromTask(Task task, bool lookForOce) { switch (task.Status) { case TaskStatus.Canceled: TrySetCanceled(task.CancellationToken); break; case TaskStatus.Faulted: // BUGBUG: Implement this when we can throw exceptions. BCLDebug.Assert(false, "Exceptions not yet supported by Tasks."); break; case TaskStatus.RanToCompletion: // Transfer the result if we have one. Otherwise, assume the inner task is non-generic. var taskTResult = task as Task; if (taskTResult != null) { TrySetResult(taskTResult.Result); } break; } } } #endregion Promise helpers } /// /// Specifies flags that control optional behavior for the creation and execution of tasks. /// // NOTE: These options are a subset of TaskContinuationsOptions, thus before adding a flag check it is // not already in use. [Flags] [Serializable] public enum TaskCreationOptions { /// /// Specifies that the default behavior should be used. /// None = 0x0, /// /// A hint to a TaskScheduler to schedule a /// task in as fair a manner as possible, meaning that tasks scheduled sooner will be more likely to /// be run sooner, and tasks scheduled later will be more likely to be run later. /// PreferFairness = 0x01, /// /// Specifies that a task will be a long-running, course-grained operation. It provides a hint to the /// TaskScheduler that oversubscription may be /// warranted. /// LongRunning = 0x02, /// /// Specifies that a task is attached to a parent in the task hierarchy. /// AttachedToParent = 0x04, /// /// Specifies that an InvalidOperationException will be thrown if an attempt is made to attach a child task to the created task. /// DenyChildAttach = 0x08, /// /// Prevents the ambient scheduler from being seen as the current scheduler in the created task. This means that operations /// like StartNew or ContinueWith that are performed in the created task will see TaskScheduler.Default as the current scheduler. /// HideScheduler = 0x10, // 0x20 is already being used in TaskContinuationOptions /// /// Forces continuations added to the current task to be executed asynchronously. /// This option has precedence over TaskContinuationOptions.ExecuteSynchronously /// RunContinuationsAsynchronously = 0x40 } [Flags] internal enum InternalTaskOptions { None = 0x0, InternalOptionsMask = 0x0000FF00, // Internal options begin here. These should generally match up with the ones in CoreCLR, when possible. ContinuationTask = 0x0200, PromiseTask = 0x0400, } /// /// Specifies flags that control optional behavior for the creation and execution of continuation tasks. /// [Flags] [Serializable] public enum TaskContinuationOptions { /// /// Default = "Continue on any, no task options, run asynchronously" /// Specifies that the default behavior should be used. Continuations, by default, will /// be scheduled when the antecedent task completes, regardless of the task's final TaskStatus. /// None = 0, // These are identical to their meanings and values in TaskCreationOptions /// /// A hint to a TaskScheduler to schedule a /// task in as fair a manner as possible, meaning that tasks scheduled sooner will be more likely to /// be run sooner, and tasks scheduled later will be more likely to be run later. /// PreferFairness = 0x01, /// /// Specifies that a task will be a long-running, course-grained operation. It provides /// a hint to the TaskScheduler that /// oversubscription may be warranted. /// LongRunning = 0x02, /// /// Specifies that a task is attached to a parent in the task hierarchy. /// AttachedToParent = 0x04, /// /// Specifies that an InvalidOperationException will be thrown if an attempt is made to attach a child task to the created task. /// DenyChildAttach = 0x08, /// /// Prevents the ambient scheduler from being seen as the current scheduler in the created task. This means that operations /// like StartNew or ContinueWith that are performed in the created task will see TaskScheduler.Default as the current scheduler. /// HideScheduler = 0x10, /// /// In the case of continuation cancellation, prevents completion of the continuation until the antecedent has completed. /// LazyCancellation = 0x20, /// /// Forces continuations added to the current task to be executed asynchronously. /// This option has precedence over TaskContinuationOptions.ExecuteSynchronously /// RunContinuationsAsynchronously = 0x40, // These are specific to continuations /// /// Specifies that the continuation task should not be scheduled if its antecedent ran to completion. /// This option is not valid for multi-task continuations. /// NotOnRanToCompletion = 0x10000, /// /// Specifies that the continuation task should not be scheduled if its antecedent threw an unhandled /// exception. This option is not valid for multi-task continuations. /// NotOnFaulted = 0x20000, /// /// Specifies that the continuation task should not be scheduled if its antecedent was canceled. This /// option is not valid for multi-task continuations. /// NotOnCanceled = 0x40000, /// /// Specifies that the continuation task should be scheduled only if its antecedent ran to /// completion. This option is not valid for multi-task continuations. /// OnlyOnRanToCompletion = NotOnFaulted | NotOnCanceled, /// /// Specifies that the continuation task should be scheduled only if its antecedent threw an /// unhandled exception. This option is not valid for multi-task continuations. /// OnlyOnFaulted = NotOnRanToCompletion | NotOnCanceled, /// /// Specifies that the continuation task should be scheduled only if its antecedent was canceled. /// This option is not valid for multi-task continuations. /// OnlyOnCanceled = NotOnRanToCompletion | NotOnFaulted, /// /// Specifies that the continuation task should be executed synchronously. With this option /// specified, the continuation will be run on the same thread that causes the antecedent task to /// transition into its final state. If the antecedent is already complete when the continuation is /// created, the continuation will run on the thread creating the continuation. Only very /// short-running continuations should be executed synchronously. /// ExecuteSynchronously = 0x80000 } internal interface ITaskCompletionAction { void Invoke(Task completedTask); } } ================================================ FILE: Zelig/Zelig/RunTime/Framework/mscorlib/System/Threading/Tasks/TaskCanceledException.cs ================================================ // Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. // =+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+ // // // // An exception for task cancellations. // // =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=- using System; using System.Runtime.InteropServices; using System.Runtime.Serialization; namespace System.Threading.Tasks { /// /// Represents an exception used to communicate task cancellation. /// [Serializable] public class TaskCanceledException : OperationCanceledException { [NonSerialized] private Task m_canceledTask; // The task which has been canceled. /// /// Initializes a new instance of the class. /// #if EXCEPTION_STRINGS public TaskCanceledException() : base(Environment.GetResourceString("TaskCanceledException_ctor_DefaultMessage")) #else // EXCEPTION_STRINGS public TaskCanceledException() #endif // EXCEPTION_STRINGS { } /// /// Initializes a new instance of the /// class with a specified error message. /// /// The error message that explains the reason for the exception. public TaskCanceledException(string message) : base(message) { } /// /// Initializes a new instance of the /// class with a specified error message and a reference to the inner exception that is the cause of /// this exception. /// /// The error message that explains the reason for the exception. /// The exception that is the cause of the current exception. public TaskCanceledException(string message, Exception innerException) : base(message, innerException) { } /// /// Initializes a new instance of the class /// with a reference to the that has been canceled. /// /// A task that has been canceled. public TaskCanceledException(Task task) : base( #if EXCEPTION_STRINGS Environment.GetResourceString("TaskCanceledException_ctor_DefaultMessage"), #else // EXCEPTION_STRINGS null, #endif // EXCEPTION_STRINGS (task != null) ? task.CancellationToken : default(CancellationToken)) { m_canceledTask = task; } #if DISABLED_FOR_LLILUM /// /// Initializes a new instance of the /// class with serialized data. /// /// The that holds the serialized object data about the exception being thrown. /// The that contains contextual information about the source or destination. protected TaskCanceledException(SerializationInfo info, StreamingContext context) : base(info, context) { } #endif // DISABLED_FOR_LLILUM /// /// Gets the task associated with this exception. /// /// /// It is permissible for no Task to be associated with a /// , in which case /// this property will return null. /// public Task Task { get { return m_canceledTask; } } } } ================================================ FILE: Zelig/Zelig/RunTime/Framework/mscorlib/System/Threading/Tasks/TaskContinuation.cs ================================================ using System; namespace System.Threading.Tasks { // Task type used to implement: Task ContinueWith(Action,...>) internal sealed class ContinuationTaskFromTask : Task { private Task m_antecedant; public ContinuationTaskFromTask( Task antecedent, Delegate action, object state, CancellationToken cancellationToken, TaskCreationOptions creationOptions) : base(action, state, cancellationToken, creationOptions, InternalTaskOptions.ContinuationTask) { } internal override void Invoke() { // Get and null out the antecedent. This is crucial to avoid a memory leak with long chains of continuations. Task antecedent = m_antecedant; m_antecedant = null; #if ENABLE_CONTRACTS Contract.Assert(antecedent != null, "No antecedent was set for the task continuation."); #endif // ENABLE_CONTRACTS var action = m_action as Action; if (action != null) { action(antecedent); return; } var actionWithState = m_action as Action; if (actionWithState != null) { actionWithState(antecedent, m_stateObject); return; } #if ENABLE_CONTRACTS Contract.Assert(false, "Invalid m_action in ContinuationTaskFromTask."); #endif // ENABLE_CONTRACTS } } // Task type used to implement: Task ContinueWith(Action,...>) internal sealed class ContinuationTaskFromResultTask : Task { private Task m_antecedant; public ContinuationTaskFromResultTask( Task antecedent, Delegate action, object state, CancellationToken cancellationToken, TaskCreationOptions creationOptions) : base(action, state, cancellationToken, creationOptions, InternalTaskOptions.ContinuationTask) { } internal override void Invoke() { // Get and null out the antecedent. This is crucial to avoid a memory leak with long chains of continuations. Task antecedent = m_antecedant; m_antecedant = null; #if ENABLE_CONTRACTS Contract.Assert(antecedent != null, "No antecedent was set for the task continuation."); #endif // ENABLE_CONTRACTS var action = m_action as Action>; if (action != null) { action(antecedent); return; } var actionWithState = m_action as Action, object>; if (actionWithState != null) { actionWithState(antecedent, m_stateObject); return; } #if ENABLE_CONTRACTS Contract.Assert(false, "Invalid m_action in ContinuationTaskFromResultTask"); #endif // ENABLE_CONTRACTS } } // Task type used to implement: Task ContinueWith(Func,...>) internal sealed class ContinuationResultTaskFromTask : Task { private Task m_antecedant; public ContinuationResultTaskFromTask( Task antecedent, Delegate function, object state, CancellationToken cancellationToken, TaskCreationOptions creationOptions) : base(function, state, cancellationToken, creationOptions, InternalTaskOptions.ContinuationTask) { } internal override void Invoke() { // Get and null out the antecedent. This is crucial to avoid a memory leak with long chains of continuations. Task antecedent = m_antecedant; m_antecedant = null; #if ENABLE_CONTRACTS Contract.Assert(antecedent != null, "No antecedent was set for the task continuation."); #endif // ENABLE_CONTRACTS var func = m_action as Func; if (func != null) { m_result = func(antecedent); return; } var funcWithState = m_action as Func; if (funcWithState != null) { m_result = funcWithState(antecedent, m_stateObject); return; } #if ENABLE_CONTRACTS Contract.Assert(false, "Invalid m_action in ContinuationResultTaskFromResultTask"); #endif // ENABLE_CONTRACTS } } // Task type used to implement: Task ContinueWith(Func,...>) internal sealed class ContinuationResultTaskFromResultTask : Task { private Task m_antecedant; public ContinuationResultTaskFromResultTask( Task antecedent, Delegate function, object state, CancellationToken cancellationToken, TaskCreationOptions creationOptions) : base(function, state, cancellationToken, creationOptions, InternalTaskOptions.ContinuationTask) { } internal override void Invoke() { // Get and null out the antecedent. This is crucial to avoid a memory leak with long chains of continuations. Task antecedent = m_antecedant; m_antecedant = null; #if ENABLE_CONTRACTS Contract.Assert(antecedent != null, "No antecedent was set for the task continuation."); #endif // ENABLE_CONTRACTS var func = m_action as Func, TResult>; if (func != null) { m_result = func(antecedent); return; } var funcWithState = m_action as Func, object, TResult>; if (funcWithState != null) { m_result = funcWithState(antecedent, m_stateObject); return; } #if ENABLE_CONTRACTS Contract.Assert(false, "Invalid m_action in ContinuationResultTaskFromResultTask"); #endif // ENABLE_CONTRACTS } } /// /// Wrapper class to simplify invocation of continuation tasks. /// internal class TaskContinuation { private readonly Task m_task; private readonly TaskContinuationOptions m_continuationOptions; public TaskContinuation(Task continuationTask, TaskContinuationOptions continuationOptions) { m_task = continuationTask; m_continuationOptions = continuationOptions; } public void RunOrSchedule(Task antecedent) { TaskStatus status = antecedent.Status; switch (status) { case TaskStatus.RanToCompletion: if ((m_continuationOptions & TaskContinuationOptions.NotOnRanToCompletion) != 0) { m_task.InternalCancel(); return; } break; case TaskStatus.Canceled: if ((m_continuationOptions & TaskContinuationOptions.NotOnCanceled) != 0) { m_task.InternalCancel(); return; } break; case TaskStatus.Faulted: if ((m_continuationOptions & TaskContinuationOptions.NotOnFaulted) != 0) { m_task.InternalCancel(); return; } break; } bool runSynchronously = ((m_continuationOptions & TaskContinuationOptions.ExecuteSynchronously) != 0) && ((antecedent.CreationOptions & TaskCreationOptions.RunContinuationsAsynchronously) == 0); m_task.Start(runSynchronously); } } } ================================================ FILE: Zelig/Zelig/RunTime/Framework/mscorlib/System/Threading/Tasks/TaskScheduler.cs ================================================ // Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using System; using System.Collections.Generic; using System.Security; using System.Security.Permissions; using System.Diagnostics; namespace System.Threading.Tasks { /// /// Represents an abstract scheduler for tasks. /// /// /// /// TaskScheduler acts as the extension point for all /// pluggable scheduling logic. This includes mechanisms such as how to schedule a task for execution, and /// how scheduled tasks should be exposed to debuggers. /// /// /// All members of the abstract type are thread-safe /// and may be used from multiple threads concurrently. /// /// [DebuggerDisplay("Id={Id}")] [HostProtection(Synchronization = true, ExternalThreading = true)] ////[PermissionSet(SecurityAction.InheritanceDemand, Unrestricted = true)] public abstract class TaskScheduler { //////////////////////////////////////////////////////////// // // User Provided Methods and Properties // /// /// Queues a Task to the scheduler. /// /// /// /// A class derived from TaskScheduler /// implements this method to accept tasks being scheduled on the scheduler. /// A typical implementation would store the task in an internal data structure, which would /// be serviced by threads that would execute those tasks at some time in the future. /// /// /// This method is only meant to be called by the .NET Framework and /// should not be called directly by the derived class. This is necessary /// for maintaining the consistency of the system. /// /// /// The Task to be queued. /// The argument is null. [SecurityCritical] protected internal abstract void QueueTask(Task task); /// /// Determines whether the provided Task /// can be executed synchronously in this call, and if it can, executes it. /// /// /// /// A class derived from TaskScheduler implements this function to /// support inline execution of a task on a thread that initiates a wait on that task object. Inline /// execution is optional, and the request may be rejected by returning false. However, better /// scalability typically results the more tasks that can be inlined, and in fact a scheduler that /// inlines too little may be prone to deadlocks. A proper implementation should ensure that a /// request executing under the policies guaranteed by the scheduler can successfully inline. For /// example, if a scheduler uses a dedicated thread to execute tasks, any inlining requests from that /// thread should succeed. /// /// /// If a scheduler decides to perform the inline execution, it should do so by calling to the base /// TaskScheduler's /// TryExecuteTask method with the provided task object, propagating /// the return value. It may also be appropriate for the scheduler to remove an inlined task from its /// internal data structures if it decides to honor the inlining request. Note, however, that under /// some circumstances a scheduler may be asked to inline a task that was not previously provided to /// it with the method. /// /// /// The derived scheduler is responsible for making sure that the calling thread is suitable for /// executing the given task as far as its own scheduling and execution policies are concerned. /// /// /// The Task to be /// executed. /// A Boolean denoting whether or not task has previously been /// queued. If this parameter is True, then the task may have been previously queued (scheduled); if /// False, then the task is known not to have been queued, and this call is being made in order to /// execute the task inline without queueing it. /// A Boolean value indicating whether the task was executed inline. /// The argument is /// null. /// The was already /// executed. [SecurityCritical] protected abstract bool TryExecuteTaskInline(Task task, bool taskWasPreviouslyQueued); /// /// Generates an enumerable of Task instances /// currently queued to the scheduler waiting to be executed. /// /// /// /// A class derived from implements this method in order to support /// integration with debuggers. This method will only be invoked by the .NET Framework when the /// debugger requests access to the data. The enumerable returned will be traversed by debugging /// utilities to access the tasks currently queued to this scheduler, enabling the debugger to /// provide a representation of this information in the user interface. /// /// /// It is important to note that, when this method is called, all other threads in the process will /// be frozen. Therefore, it's important to avoid synchronization with other threads that may lead to /// blocking. If synchronization is necessary, the method should prefer to throw a /// than to block, which could cause a debugger to experience delays. Additionally, this method and /// the enumerable returned must not modify any globally visible state. /// /// /// The returned enumerable should never be null. If there are currently no queued tasks, an empty /// enumerable should be returned instead. /// /// /// For developers implementing a custom debugger, this method shouldn't be called directly, but /// rather this functionality should be accessed through the internal wrapper method /// GetScheduledTasksForDebugger: /// internal Task[] GetScheduledTasksForDebugger(). This method returns an array of tasks, /// rather than an enumerable. In order to retrieve a list of active schedulers, a debugger may use /// another internal method: internal static TaskScheduler[] GetTaskSchedulersForDebugger(). /// This static method returns an array of all active TaskScheduler instances. /// GetScheduledTasksForDebugger then may be used on each of these scheduler instances to retrieve /// the list of scheduled tasks for each. /// /// /// An enumerable that allows traversal of tasks currently queued to this scheduler. /// /// /// This scheduler is unable to generate a list of queued tasks at this time. /// [SecurityCritical] protected abstract IEnumerable GetScheduledTasks(); /// /// Indicates the maximum concurrency level this /// is able to support. /// public virtual Int32 MaximumConcurrencyLevel { get { return Int32.MaxValue; } } /// /// Attempts to dequeue a Task that was previously queued to /// this scheduler. /// /// The Task to be dequeued. /// A Boolean denoting whether the argument was successfully dequeued. /// The argument is null. [SecurityCritical] protected internal virtual bool TryDequeue(Task task) { return false; } /// /// Notifies the scheduler that a work item has made progress. /// internal virtual void NotifyWorkItemProgress() { } /// /// Indicates whether this is a custom scheduler, in which case the safe code paths will be taken upon task entry /// using a CAS to transition from queued state to executing. /// internal virtual bool RequiresAtomicStartTransition { get { return true; } } //////////////////////////////////////////////////////////// // // Constructors and public properties // /// /// Initializes the . /// protected TaskScheduler() { } /// /// Gets the default TaskScheduler instance. /// public static TaskScheduler Default { get { #if DISABLED_FOR_LLILUM return s_defaultTaskScheduler; #else // DISABLED_FOR_LLILUM return null; #endif // DISABLED_FOR_LLILUM } } /// /// Gets the TaskScheduler /// associated with the currently executing task. /// /// /// When not called from within a task, will return the scheduler. /// public static TaskScheduler Current { get { #if DISABLED_FOR_LLILUM TaskScheduler current = InternalCurrent; return current ?? TaskScheduler.Default; #else // DISABLED_FOR_LLILUM return null; #endif // DISABLED_FOR_LLILUM } } /// /// Creates a /// associated with the current . /// /// /// All Task instances queued to /// the returned scheduler will be executed through a call to the /// Post method /// on that context. /// /// /// A associated with /// the current SynchronizationContext, as /// determined by SynchronizationContext.Current. /// /// /// The current SynchronizationContext may not be used as a TaskScheduler. /// public static TaskScheduler FromCurrentSynchronizationContext() { #if DISABLED_FOR_LLILUM return new SynchronizationContextTaskScheduler(); #else // DISABLED_FOR_LLILUM throw new NotImplementedException(); #endif // DISABLED_FOR_LLILUM } /// /// Gets the unique ID for this . /// public Int32 Id { get { #if DISABLED_FOR_LLILUM if (m_taskSchedulerId == 0) { int newId = 0; // We need to repeat if Interlocked.Increment wraps around and returns 0. // Otherwise next time this scheduler's Id is queried it will get a new value do { newId = Interlocked.Increment(ref s_taskSchedulerIdCounter); } while (newId == 0); Interlocked.CompareExchange(ref m_taskSchedulerId, newId, 0); } return m_taskSchedulerId; #else // DISABLED_FOR_LLILUM throw new NotImplementedException(); #endif // DISABLED_FOR_LLILUM } } /// /// Attempts to execute the provided Task /// on this scheduler. /// /// /// /// Scheduler implementations are provided with Task /// instances to be executed through either the method or the /// method. When the scheduler deems it appropriate to run the /// provided task, should be used to do so. TryExecuteTask handles all /// aspects of executing a task, including action invocation, exception handling, state management, /// and lifecycle control. /// /// /// must only be used for tasks provided to this scheduler by the .NET /// Framework infrastructure. It should not be used to execute arbitrary tasks obtained through /// custom mechanisms. /// /// /// /// A Task object to be executed. /// /// The is not associated with this scheduler. /// /// A Boolean that is true if was successfully executed, false if it /// was not. A common reason for execution failure is that the task had previously been executed or /// is in the process of being executed by another thread. [SecurityCritical] protected bool TryExecuteTask(Task task) { #if DISABLED_FOR_LLILUM if (task.ExecutingTaskScheduler != this) { throw new InvalidOperationException(Environment.GetResourceString("TaskScheduler_ExecuteTask_WrongTaskScheduler")); } return task.ExecuteEntry(true); #else // DISABLED_FOR_LLILUM throw new NotImplementedException(); #endif // DISABLED_FOR_LLILUM } //////////////////////////////////////////////////////////// // // Events // private static EventHandler _unobservedTaskException; private static readonly object _unobservedTaskExceptionLockObject = new object(); /// /// Occurs when a faulted 's unobserved exception is about to trigger exception escalation /// policy, which, by default, would terminate the process. /// /// /// This AppDomain-wide event provides a mechanism to prevent exception /// escalation policy (which, by default, terminates the process) from triggering. /// Each handler is passed a /// instance, which may be used to examine the exception and to mark it as observed. /// public static event EventHandler UnobservedTaskException { [System.Security.SecurityCritical] add { if (value != null) { #if DISABLED_FOR_LLILUM RuntimeHelpers.PrepareContractedDelegate(value); #endif // DISABLED_FOR_LLILUM lock (_unobservedTaskExceptionLockObject) _unobservedTaskException += value; } } [System.Security.SecurityCritical] remove { lock (_unobservedTaskExceptionLockObject) _unobservedTaskException -= value; } } //////////////////////////////////////////////////////////// // // Internal methods // // This is called by the TaskExceptionHolder finalizer. internal static void PublishUnobservedTaskException(object sender, UnobservedTaskExceptionEventArgs ueea) { // Lock this logic to prevent just-unregistered handlers from being called. lock (_unobservedTaskExceptionLockObject) { // Since we are under lock, it is technically no longer necessary // to make a copy. It is done here for convenience. EventHandler handler = _unobservedTaskException; if (handler != null) { handler(sender, ueea); } } } /// /// Provides an array of all queued Task instances /// for the debugger. /// /// /// The returned array is populated through a call to . /// Note that this function is only meant to be invoked by a debugger remotely. /// It should not be called by any other codepaths. /// /// An array of Task instances. /// /// This scheduler is unable to generate a list of queued tasks at this time. /// [SecurityCritical] internal Task[] GetScheduledTasksForDebugger() { // this can throw InvalidOperationException indicating that they are unable to provide the info // at the moment. We should let the debugger receive that exception so that it can indicate it in the UI IEnumerable activeTasksSource = GetScheduledTasks(); if (activeTasksSource == null) return null; // If it can be cast to an array, use it directly Task[] activeTasksArray = activeTasksSource as Task[]; if (activeTasksArray == null) { activeTasksArray = (new List(activeTasksSource)).ToArray(); } // touch all Task.Id fields so that the debugger doesn't need to do a lot of cross-proc calls to generate them foreach (Task t in activeTasksArray) { int tmp = t.Id; } return activeTasksArray; } } /// /// Provides data for the event that is raised when a faulted 's /// exception goes unobserved. /// /// /// The Exception property is used to examine the exception without marking it /// as observed, whereas the method is used to mark the exception /// as observed. Marking the exception as observed prevents it from triggering exception escalation policy /// which, by default, terminates the process. /// public class UnobservedTaskExceptionEventArgs : EventArgs { private AggregateException m_exception; internal bool m_observed = false; /// /// Initializes a new instance of the class /// with the unobserved exception. /// /// The Exception that has gone unobserved. public UnobservedTaskExceptionEventArgs(AggregateException exception) { m_exception = exception; } /// /// Marks the as "observed," thus preventing it /// from triggering exception escalation policy which, by default, terminates the process. /// public void SetObserved() { m_observed = true; } /// /// Gets whether this exception has been marked as "observed." /// public bool Observed { get { return m_observed; } } /// /// The Exception that went unobserved. /// public AggregateException Exception { get { return m_exception; } } } } ================================================ FILE: Zelig/Zelig/RunTime/Framework/mscorlib/System/Threading/Thread.cs ================================================ // ==++== // // Copyright (c) Microsoft Corporation. All rights reserved. // // ==--== /*============================================================================= ** ** Class: Thread ** ** ** Purpose: Class for creating and managing a thread. ** ** =============================================================================*/ namespace System.Threading { using System; using System.Threading; using System.Runtime.InteropServices; ////using System.Runtime.Remoting.Contexts; ////using System.Runtime.Remoting.Messaging; using System.Diagnostics; using System.Security.Permissions; ////using System.Security.Principal; using System.Globalization; using System.Collections.Generic; using System.Runtime.Serialization; using System.Runtime.CompilerServices; using System.Runtime.ConstrainedExecution; ////using System.Security; ////using System.Runtime.Versioning; ////internal delegate Object InternalCrossContextDelegate( Object[] args ); ////internal class ThreadHelper ////{ //// Delegate m_start; //// Object m_startArg = null; //// ExecutionContext m_executionContext = null; //// //// internal ThreadHelper( Delegate start ) //// { //// m_start = start; //// } //// //// internal void SetExecutionContextHelper( ExecutionContext ec ) //// { //// m_executionContext = ec; //// } //// //// static internal ContextCallback s_ccb = new ContextCallback( ThreadStart_Context ); //// //// static internal void ThreadStart_Context( Object state ) //// { //// ThreadHelper t = (ThreadHelper)state; //// if(t.m_start is ThreadStart) //// { //// ((ThreadStart)t.m_start)(); //// } //// else //// { //// ((ParameterizedThreadStart)t.m_start)( t.m_startArg ); //// } //// } //// //// // call back helper //// internal void ThreadStart( object obj ) //// { //// m_startArg = obj; //// //// if(m_executionContext != null) //// { //// ExecutionContext.Run( m_executionContext, s_ccb, (Object)this ); //// } //// else //// { //// ((ParameterizedThreadStart)m_start)( obj ); //// } //// } //// //// // call back helper //// internal void ThreadStart() //// { //// if(m_executionContext != null) //// { //// ExecutionContext.Run( m_executionContext, s_ccb, (Object)this ); //// } //// else //// { //// ((ThreadStart)m_start)(); //// } //// } ////} // deliberately not [serializable] [Microsoft.Zelig.Internals.WellKnownType( "System_Threading_Thread" )] public sealed class Thread : CriticalFinalizerObject { //// /*========================================================================= //// ** Data accessed from managed code that needs to be defined in //// ** ThreadBaseObject to maintain alignment between the two classes. //// ** DON'T CHANGE THESE UNLESS YOU MODIFY ThreadBaseObject in vm\object.h //// =========================================================================*/ //// private Context m_Context; //// //// private ExecutionContext m_ExecutionContext; // this call context follows the logical thread private String m_Name; //// private Delegate m_Delegate; // Delegate //// //// private Object[][] m_ThreadStaticsBuckets; // Holder for thread statics //// private int[] m_ThreadStaticsBits; // Bit-markers for slot availability //// private CultureInfo m_CurrentCulture; //// private CultureInfo m_CurrentUICulture; //// private Object m_ThreadStartArg; //// //// /*========================================================================= //// ** The base implementation of Thread is all native. The following fields //// ** should never be used in the C# code. They are here to define the proper //// ** space so the thread object may be allocated. DON'T CHANGE THESE UNLESS //// ** YOU MODIFY ThreadBaseObject in vm\object.h //// =========================================================================*/ ////#pragma warning disable 169 ////#pragma warning disable 414 // These fields are not used from managed. //// // IntPtrs need to be together, and before ints, because IntPtrs are 64-bit //// // fields on 64-bit platforms, where they will be sorted together. //// //// private IntPtr DONT_USE_InternalThread; // Pointer //// private int m_Priority; // INT32 ////#pragma warning restore 414 ////#pragma warning restore 169 //// //// /*========================================================================= //// ** This manager is responsible for storing the global data that is //// ** shared amongst all the thread local stores. //// =========================================================================*/ //// static private LocalDataStoreMgr s_LocalDataStoreMgr; //// //// /*========================================================================= //// ** Thread-local data store //// =========================================================================*/ //// [ThreadStatic] //// static private LocalDataStoreHolder s_LocalDataStore; //// //// // Has to be in sync with THREAD_STATICS_BUCKET_SIZE in vm/threads.cpp //// private const int STATICS_BUCKET_SIZE = 32; /*========================================================================= ** Creates a new Thread object which will begin execution at ** start.ThreadStart on a new thread when the Start method is called. ** ** Exceptions: ArgumentNullException if start == null. =========================================================================*/ [MethodImpl( MethodImplOptions.InternalCall )] public extern Thread( ThreadStart start ); //// { //// if(start == null) //// { //// throw new ArgumentNullException( "start" ); //// } //// //// SetStartHelper( (Delegate)start, 0 ); //0 will setup Thread with default stackSize //// } //// public Thread( ThreadStart start, int maxStackSize ) //// { //// if(start == null) //// { //// throw new ArgumentNullException( "start" ); //// } //// //// if(0 > maxStackSize) //// { //// throw new ArgumentOutOfRangeException( "maxStackSize", Environment.GetResourceString( "ArgumentOutOfRange_NeedNonNegNum" ) ); //// } //// //// SetStartHelper( (Delegate)start, maxStackSize ); //// } //// //// public Thread( ParameterizedThreadStart start ) //// { //// if(start == null) //// { //// throw new ArgumentNullException( "start" ); //// } //// //// SetStartHelper( (Delegate)start, 0 ); //// } //// //// public Thread( ParameterizedThreadStart start, int maxStackSize ) //// { //// if(start == null) //// { //// throw new ArgumentNullException( "start" ); //// } //// //// if(0 > maxStackSize) //// { //// throw new ArgumentOutOfRangeException( "maxStackSize", Environment.GetResourceString( "ArgumentOutOfRange_NeedNonNegNum" ) ); //// } //// //// SetStartHelper( (Delegate)start, maxStackSize ); //// } //// //// [ResourceExposure( ResourceScope.None )] //// [MethodImpl( MethodImplOptions.InternalCall )] //// public extern override int GetHashCode(); public extern int ManagedThreadId { //// [ResourceExposure( ResourceScope.None )] //// [ReliabilityContract( Consistency.WillNotCorruptState, Cer.Success )] [MethodImpl( MethodImplOptions.InternalCall )] get; } /*========================================================================= ** Spawns off a new thread which will begin executing at the ThreadStart ** method on the IThreadable interface passed in the constructor. Once the ** thread is dead, it cannot be restarted with another call to Start. ** ** Exceptions: ThreadStateException if the thread has already been started. =========================================================================*/ [HostProtection( Synchronization = true, ExternalThreading = true )] [MethodImpl( MethodImplOptions.InternalCall )] public extern void Start(); //// { //// // Attach current thread's security principal object to the new //// // thread. Be careful not to bind the current thread to a principal //// // if it's not already bound. //// if(m_Delegate != null) //// { //// // If we reach here with a null delegate, something is broken. But we'll let the StartInternal method take care of //// // reporting an error. Just make sure we dont try to dereference a null delegate. //// ThreadHelper t = (ThreadHelper)(m_Delegate.Target); //// //// ExecutionContext ec = ExecutionContext.Capture(); //// //// ExecutionContext.ClearSyncContext( ec ); //// //// t.SetExecutionContextHelper( ec ); //// } //// //// IPrincipal principal = (IPrincipal)CallContext.Principal; //// //// StackCrawlMark stackMark = StackCrawlMark.LookForMyCaller; //// //// StartInternal( principal, ref stackMark ); //// } //// [HostProtection( Synchronization = true, ExternalThreading = true )] //// public void Start( object parameter ) //// { //// //In the case of a null delegate (second call to start on same thread) //// // StartInternal method will take care of the error reporting //// if(m_Delegate is ThreadStart) //// { //// //We expect the thread to be setup with a ParameterizedThreadStart //// // if this constructor is called. //// //If we got here then that wasn't the case //// throw new InvalidOperationException( Environment.GetResourceString( "InvalidOperation_ThreadWrongThreadStart" ) ); //// } //// //// m_ThreadStartArg = parameter; //// Start(); //// } //// //// [ReliabilityContract( Consistency.WillNotCorruptState, Cer.Success )] //// internal ExecutionContext GetExecutionContextNoCreate() //// { //// return m_ExecutionContext; //// } //// //// //// public ExecutionContext ExecutionContext //// { //// [ReliabilityContract( Consistency.WillNotCorruptState, Cer.MayFail )] //// get //// { //// if(m_ExecutionContext == null && this == Thread.CurrentThread) //// { //// m_ExecutionContext = new ExecutionContext(); //// m_ExecutionContext.Thread = this; //// } //// //// return m_ExecutionContext; //// } //// } //// //// [ReliabilityContract( Consistency.WillNotCorruptState, Cer.Success )] //// internal void SetExecutionContext( ExecutionContext value ) //// { //// m_ExecutionContext = value; //// if(value != null) //// { //// m_ExecutionContext.Thread = this; //// } //// } //// //// //// [ResourceExposure( ResourceScope.None )] //// [MethodImpl( MethodImplOptions.InternalCall )] //// private extern void StartInternal( IPrincipal principal, ref StackCrawlMark stackMark ); //// //// //// [ResourceExposure( ResourceScope.None )] //// [MethodImpl( MethodImplOptions.InternalCall )] //// [ReliabilityContract( Consistency.WillNotCorruptState, Cer.Success )] //// internal extern IntPtr SetAppDomainStack( SafeCompressedStackHandle csHandle ); //// //// [ResourceExposure( ResourceScope.None )] //// [MethodImpl( MethodImplOptions.InternalCall )] //// [ReliabilityContract( Consistency.WillNotCorruptState, Cer.Success )] //// internal extern void RestoreAppDomainStack( IntPtr appDomainStack ); //// //// //// // Helper method to get a logical thread ID for StringBuilder (for //// // correctness) and for FileStream's async code path (for perf, to //// // avoid creating a Thread instance). //// [ResourceExposure( ResourceScope.None )] //// [MethodImpl( MethodImplOptions.InternalCall )] //// internal extern static IntPtr InternalGetCurrentThread(); //// //// /*========================================================================= //// ** Raises a ThreadAbortException in the thread, which usually //// ** results in the thread's death. The ThreadAbortException is a special //// ** exception that is not catchable. The finally clauses of all try //// ** statements will be executed before the thread dies. This includes the //// ** finally that a thread might be executing at the moment the Abort is raised. //// ** The thread is not stopped immediately--you must Join on the //// ** thread to guarantee it has stopped. //// ** It is possible for a thread to do an unbounded amount of computation in //// ** the finally's and thus indefinitely delay the threads death. //// ** If Abort() is called on a thread that has not been started, the thread //// ** will abort when Start() is called. //// ** If Abort is called twice on the same thread, a DuplicateThreadAbort //// ** exception is thrown. //// =========================================================================*/ //// //// [SecurityPermissionAttribute( SecurityAction.Demand, ControlThread = true )] //// public void Abort( Object stateInfo ) //// { //// // If two aborts come at the same time, it is possible that the state info //// // gets set by one, and the actual abort gets delivered by another. But this //// // is not distinguishable by an application. //// // The accessor helper will only set the value if it isn't already set, //// // and that particular bit of native code can test much faster than this //// // code could, because testing might cause a cross-appdomain marshalling. //// AbortReason = stateInfo; //// //// // Note: we demand ControlThread permission, then call AbortInternal directly //// // rather than delegating to the Abort() function below. We do this to ensure //// // that only callers with ControlThread are allowed to change the AbortReason //// // of the thread. We call AbortInternal directly to avoid demanding the same //// // permission twice. //// AbortInternal(); //// } //// [SecurityPermissionAttribute( SecurityAction.Demand, ControlThread = true )] public void Abort() { throw new NotImplementedException(); //// AbortInternal(); } //// // Internal helper (since we can't place security demands on //// // ecalls/fcalls). //// [ResourceExposure( ResourceScope.None )] //// [MethodImpl( MethodImplOptions.InternalCall )] //// private extern void AbortInternal(); //// //// /*========================================================================= //// ** Resets a thread abort. //// ** Should be called by trusted code only //// =========================================================================*/ //// [SecurityPermissionAttribute( SecurityAction.Demand, ControlThread = true )] //// public static void ResetAbort() //// { //// Thread thread = Thread.CurrentThread; //// if((thread.ThreadState & ThreadState.AbortRequested) == 0) //// { //// throw new ThreadStateException( Environment.GetResourceString( "ThreadState_NoAbortRequested" ) ); //// } //// //// thread.ResetAbortNative(); //// thread.ClearAbortReason(); //// } //// //// [ResourceExposure( ResourceScope.None )] //// [MethodImpl( MethodImplOptions.InternalCall )] //// private extern void ResetAbortNative(); //// //// /*========================================================================= //// ** Interrupts a thread that is inside a Wait(), Sleep() or Join(). If that //// ** thread is not currently blocked in that manner, it will be interrupted //// ** when it next begins to block. //// =========================================================================*/ //// [SecurityPermission( SecurityAction.Demand, ControlThread = true )] //// public void Interrupt() //// { //// InterruptInternal(); //// } //// //// // Internal helper (since we can't place security demands on //// // ecalls/fcalls). //// [ResourceExposure( ResourceScope.None )] //// [MethodImpl( MethodImplOptions.InternalCall )] //// private extern void InterruptInternal(); /*========================================================================= ** Returns the priority of the thread. ** ** Exceptions: ThreadStateException if the thread is dead. =========================================================================*/ public extern ThreadPriority Priority { [MethodImpl( MethodImplOptions.InternalCall )] get; //// { //// return (ThreadPriority)GetPriorityNative(); //// } [HostProtection( SelfAffectingThreading = true )] [MethodImpl( MethodImplOptions.InternalCall )] set; //// { //// SetPriorityNative( (int)value ); //// } } //// [ResourceExposure( ResourceScope.None )] //// [MethodImpl( MethodImplOptions.InternalCall )] //// private extern int GetPriorityNative(); //// //// [ResourceExposure( ResourceScope.None )] //// [MethodImpl( MethodImplOptions.InternalCall )] //// private extern void SetPriorityNative( int priority ); /*========================================================================= ** Returns true if the thread has been started and is not dead. =========================================================================*/ public extern bool IsAlive { [MethodImpl(MethodImplOptions.InternalCall)] get; } //// [ResourceExposure( ResourceScope.None )] //// [MethodImpl( MethodImplOptions.InternalCall )] //// private extern bool IsAliveNative(); //// //// /*========================================================================= //// ** Returns true if the thread is a threadpool thread. //// =========================================================================*/ //// public bool IsThreadPoolThread //// { //// get //// { //// return IsThreadpoolThreadNative(); //// } //// } //// //// [ResourceExposure( ResourceScope.None )] //// [MethodImpl( MethodImplOptions.InternalCall )] //// private extern bool IsThreadpoolThreadNative(); //// //// /*========================================================================= //// ** Waits for the thread to die. //// ** //// ** Exceptions: ThreadInterruptedException if the thread is interrupted while waiting. //// ** ThreadStateException if the thread has not been started yet. //// =========================================================================*/ //// [ResourceExposure( ResourceScope.None )] //// [MethodImpl( MethodImplOptions.InternalCall )] //// [HostProtection( Synchronization = true, ExternalThreading = true )] //// private extern void JoinInternal(); [HostProtection( Synchronization = true, ExternalThreading = true )] [MethodImpl( MethodImplOptions.InternalCall )] public extern void Join(); //// { //// JoinInternal(); //// } //// /*========================================================================= //// ** Waits for the thread to die or for timeout milliseconds to elapse. //// ** Returns true if the thread died, or false if the wait timed out. If //// ** Timeout.Infinite is given as the parameter, no timeout will occur. //// ** //// ** Exceptions: ArgumentException if timeout < 0. //// ** ThreadInterruptedException if the thread is interrupted while waiting. //// ** ThreadStateException if the thread has not been started yet. //// =========================================================================*/ //// [ResourceExposure( ResourceScope.None )] //// [MethodImpl( MethodImplOptions.InternalCall )] //// [HostProtection( Synchronization = true, ExternalThreading = true )] //// private extern bool JoinInternal( int millisecondsTimeout ); [HostProtection( Synchronization = true, ExternalThreading = true )] [MethodImpl( MethodImplOptions.InternalCall )] public extern bool Join( int millisecondsTimeout ); //// { //// return JoinInternal( millisecondsTimeout ); //// } [HostProtection( Synchronization = true, ExternalThreading = true )] [MethodImpl( MethodImplOptions.InternalCall )] public extern bool Join( TimeSpan timeout ); //// { //// long tm = (long)timeout.TotalMilliseconds; //// if(tm < -1 || tm > (long)Int32.MaxValue) //// { //// throw new ArgumentOutOfRangeException( "timeout", Environment.GetResourceString( "ArgumentOutOfRange_NeedNonNegOrNegative1" ) ); //// } //// //// return Join( (int)tm ); //// } /*========================================================================= ** Suspends the current thread for timeout milliseconds. If timeout == 0, ** forces the thread to give up the remainer of its timeslice. If timeout ** == Timeout.Infinite, no timeout will occur. ** ** Exceptions: ArgumentException if timeout < 0. ** ThreadInterruptedException if the thread is interrupted while sleeping. =========================================================================*/ //// [ResourceExposure( ResourceScope.None )] //// [MethodImpl( MethodImplOptions.InternalCall )] //// private static extern void SleepInternal( int millisecondsTimeout ); [MethodImpl( MethodImplOptions.InternalCall )] public static extern void Sleep( int millisecondsTimeout ); //// { //// SleepInternal( millisecondsTimeout ); //// } [MethodImpl( MethodImplOptions.InternalCall )] public static extern void Sleep( TimeSpan timeout ); //// { //// long tm = (long)timeout.TotalMilliseconds; //// if(tm < -1 || tm > (long)Int32.MaxValue) //// { //// throw new ArgumentOutOfRangeException( "timeout", Environment.GetResourceString( "ArgumentOutOfRange_NeedNonNegOrNegative1" ) ); //// } //// //// Sleep( (int)tm ); //// } /* wait for a length of time proportial to 'iterations'. Each iteration is should only take a few machine instructions. Calling this API is preferable to coding a explict busy loop because the hardware can be informed that it is busy waiting. */ [System.Security.SecurityCritical] // auto-generated [MethodImplAttribute(MethodImplOptions.InternalCall)] [HostProtection(Synchronization=true,ExternalThreading=true)] //// [ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)] private static extern void SpinWaitInternal(int iterations); [System.Security.SecuritySafeCritical] // auto-generated [HostProtection(Synchronization=true,ExternalThreading=true)] //// [ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)] public static void SpinWait(int iterations) { SpinWaitInternal(iterations); } [System.Security.SecurityCritical] // auto-generated //// [DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)] //// [SuppressUnmanagedCodeSecurity] [HostProtection(Synchronization = true, ExternalThreading = true)] //// [ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)] private static extern bool YieldInternal(); [System.Security.SecuritySafeCritical] // auto-generated [HostProtection(Synchronization = true, ExternalThreading = true)] //// [ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)] public static bool Yield() { return YieldInternal(); } public extern static Thread CurrentThread { //// [ReliabilityContract( Consistency.WillNotCorruptState, Cer.MayFail )] [MethodImpl( MethodImplOptions.InternalCall )] get; //// { //// Thread th = GetFastCurrentThreadNative(); //// if(th == null) //// { //// th = GetCurrentThreadNative(); //// } //// return th; //// } } //// [ResourceExposure( ResourceScope.None )] //// [MethodImpl( MethodImplOptions.InternalCall )] //// [ReliabilityContract( Consistency.WillNotCorruptState, Cer.MayFail )] //// private static extern Thread GetCurrentThreadNative(); //// //// [ResourceExposure( ResourceScope.None )] //// [MethodImpl( MethodImplOptions.InternalCall )] //// [ReliabilityContract( Consistency.WillNotCorruptState, Cer.MayFail )] //// private static extern Thread GetFastCurrentThreadNative(); //// //// private void SetStartHelper( Delegate start, int maxStackSize ) //// { //// ThreadHelper threadStartCallBack = new ThreadHelper( start ); //// if(start is ThreadStart) //// { //// SetStart( new ThreadStart( threadStartCallBack.ThreadStart ), maxStackSize ); //// } //// else //// { //// SetStart( new ParameterizedThreadStart( threadStartCallBack.ThreadStart ), maxStackSize ); //// } //// } //// //// /*========================================================================= //// ** PRIVATE Sets the IThreadable interface for the thread. Assumes that //// ** start != null. //// =========================================================================*/ //// [ResourceExposure( ResourceScope.None )] //// [MethodImpl( MethodImplOptions.InternalCall )] //// private extern void SetStart( Delegate start, int maxStackSize ); //// //// /*========================================================================= //// ** Clean up the thread when it goes away. //// =========================================================================*/ //// [ReliabilityContract( Consistency.WillNotCorruptState, Cer.Success )] //// ~Thread() //// { //// // Delegate to the unmanaged portion. //// InternalFinalize(); //// } //// //// [ResourceExposure( ResourceScope.None )] //// [ReliabilityContract( Consistency.WillNotCorruptState, Cer.Success )] //// [MethodImpl( MethodImplOptions.InternalCall )] //// private extern void InternalFinalize(); /*========================================================================= ** Return whether or not this thread is a background thread. Background ** threads do not affect when the Execution Engine shuts down. ** ** Exceptions: ThreadStateException if the thread is dead. =========================================================================*/ public extern bool IsBackground { [MethodImpl( MethodImplOptions.InternalCall )] get; //// { //// return IsBackgroundNative(); //// } [HostProtection( SelfAffectingThreading = true )] [MethodImpl( MethodImplOptions.InternalCall )] set; //// { //// SetBackgroundNative( value ); //// } } //// [ResourceExposure( ResourceScope.None )] //// [MethodImpl( MethodImplOptions.InternalCall )] //// private extern bool IsBackgroundNative(); //// //// [ResourceExposure( ResourceScope.None )] //// [MethodImpl( MethodImplOptions.InternalCall )] //// private extern void SetBackgroundNative( bool isBackground ); //// //// //// /*========================================================================= //// ** Return the thread state as a consistent set of bits. This is more //// ** general then IsAlive or IsBackground. //// =========================================================================*/ //// public ThreadState ThreadState //// { //// get //// { //// return (ThreadState)GetThreadStateNative(); //// } //// } //// //// [ResourceExposure( ResourceScope.None )] //// [MethodImpl( MethodImplOptions.InternalCall )] //// private extern int GetThreadStateNative(); //// //// /*========================================================================= //// ** Allocates an un-named data slot. The slot is allocated on ALL the //// ** threads. //// =========================================================================*/ //// [HostProtection( SharedState = true, ExternalThreading = true )] //// public static LocalDataStoreSlot AllocateDataSlot() //// { //// return LocalDataStoreManager.AllocateDataSlot(); //// } //// //// /*========================================================================= //// ** Allocates a named data slot. The slot is allocated on ALL the //// ** threads. Named data slots are "public" and can be manipulated by //// ** anyone. //// =========================================================================*/ //// [HostProtection( SharedState = true, ExternalThreading = true )] //// public static LocalDataStoreSlot AllocateNamedDataSlot( String name ) //// { //// return LocalDataStoreManager.AllocateNamedDataSlot( name ); //// } //// //// /*========================================================================= //// ** Looks up a named data slot. If the name has not been used, a new slot is //// ** allocated. Named data slots are "public" and can be manipulated by //// ** anyone. //// =========================================================================*/ //// [HostProtection( SharedState = true, ExternalThreading = true )] //// public static LocalDataStoreSlot GetNamedDataSlot( String name ) //// { //// return LocalDataStoreManager.GetNamedDataSlot( name ); //// } //// //// /*========================================================================= //// ** Frees a named data slot. The slot is allocated on ALL the //// ** threads. Named data slots are "public" and can be manipulated by //// ** anyone. //// =========================================================================*/ //// [HostProtection( SharedState = true, ExternalThreading = true )] //// public static void FreeNamedDataSlot( String name ) //// { //// LocalDataStoreManager.FreeNamedDataSlot( name ); //// } //// //// /*========================================================================= //// ** Retrieves the value from the specified slot on the current thread, for that thread's current domain. //// =========================================================================*/ //// [HostProtection( SharedState = true, ExternalThreading = true )] //// [ResourceExposure( ResourceScope.AppDomain )] //// public static Object GetData( LocalDataStoreSlot slot ) //// { //// LocalDataStoreHolder dls = s_LocalDataStore; //// if(dls == null) //// { //// // Make sure to validate the slot even if we take the quick path //// LocalDataStoreManager.ValidateSlot( slot ); //// return null; //// } //// //// return dls.Store.GetData( slot ); //// } //// //// /*========================================================================= //// ** Sets the data in the specified slot on the currently running thread, for that thread's current domain. //// =========================================================================*/ //// [HostProtection( SharedState = true, ExternalThreading = true )] //// [ResourceExposure( ResourceScope.AppDomain )] //// public static void SetData( LocalDataStoreSlot slot, Object data ) //// { //// LocalDataStoreHolder dls = s_LocalDataStore; //// //// // Create new DLS if one hasn't been created for this domain for this thread //// if(dls == null) //// { //// dls = LocalDataStoreManager.CreateLocalDataStore(); //// //// s_LocalDataStore = dls; //// } //// //// dls.Store.SetData( slot, data ); //// } //// //// [ResourceExposure( ResourceScope.None )] //// [MethodImpl( MethodImplOptions.InternalCall )] //// static extern private bool nativeGetSafeCulture( Thread t, int appDomainId, bool isUI, ref CultureInfo safeCulture ); //// //// // As the culture can be customized object then we cannot hold any //// // reference to it before we check if it is safe because the app domain //// // owning this customized culture may get unloaded while executing this //// // code. To achieve that we have to do the check using nativeGetSafeCulture //// // as the thread cannot get interrupted during the FCALL. //// // If the culture is safe (not customized or created in current app domain) //// // then the FCALL will return a reference to that culture otherwise the //// // FCALL will return failure. In case of failure we'll return the default culture. //// // If the app domain owning a customized culture that is set to teh thread and this //// // app domain get unloaded there is a code to clean up the culture from the thread //// // using the code in AppDomain::ReleaseDomainStores. //// //// public CultureInfo CurrentUICulture //// { //// get //// { //// // Fetch a local copy of m_CurrentUICulture to //// // avoid races that malicious user can introduce //// if(m_CurrentUICulture == null) //// { //// return CultureInfo.UserDefaultUICulture; //// } //// //// CultureInfo culture = null; //// //// if(!nativeGetSafeCulture( this, GetDomainID(), true, ref culture ) || culture == null) //// { //// return CultureInfo.UserDefaultUICulture; //// } //// //// return culture; //// } //// //// [HostProtection( ExternalThreading = true )] //// set //// { //// if(value == null) //// { //// throw new ArgumentNullException( "value" ); //// } //// //// //If they're trying to use a Culture with a name that we can't use in resource lookup, //// //don't even let them set it on the thread. //// CultureInfo.VerifyCultureName( value, true ); //// //// if(nativeSetThreadUILocale( value.LCID ) == false) //// { //// throw new ArgumentException( Environment.GetResourceString( "Argument_InvalidResourceCultureName", value.Name ) ); //// } //// //// value.StartCrossDomainTracking(); //// //// m_CurrentUICulture = value; //// } //// } //// //// // This returns the exposed context for a given context ID. //// [ResourceExposure( ResourceScope.None )] //// [MethodImpl( MethodImplOptions.InternalCall )] //// static extern private bool nativeSetThreadUILocale( int LCID ); // As the culture can be customized object then we cannot hold any // reference to it before we check if it is safe because the app domain // owning this customized culture may get unloaded while executing this // code. To achieve that we have to do the check using nativeGetSafeCulture // as the thread cannot get interrupted during the FCALL. // If the culture is safe (not customized or created in current app domain) // then the FCALL will return a reference to that culture otherwise the // FCALL will return failure. In case of failure we'll return the default culture. // If the app domain owning a customized culture that is set to teh thread and this // app domain get unloaded there is a code to clean up the culture from the thread // using the code in AppDomain::ReleaseDomainStores. public CultureInfo CurrentCulture { get { //// // Fetch a local copy of m_CurrentCulture to //// // avoid races that malicious user can introduce //// if(m_CurrentCulture == null) //// { return CultureInfo.UserDefaultCulture; //// } //// //// CultureInfo culture = null; //// //// if(!nativeGetSafeCulture( this, GetDomainID(), false, ref culture ) || culture == null) //// { //// return CultureInfo.UserDefaultCulture; //// } //// //// return culture; } //// [SecurityPermission( SecurityAction.Demand, ControlThread = true )] //// set //// { //// if(value == null) //// { //// throw new ArgumentNullException( "value" ); //// } //// //// CultureInfo.CheckNeutral( value ); //// //// //If we can't set the nativeThreadLocale, we'll just let it stay //// //at whatever value it had before. This allows people who use //// //just managed code not to be limited by the underlying OS. //// CultureInfo.nativeSetThreadLocale( value.LCID ); //// //// value.StartCrossDomainTracking(); //// //// m_CurrentCulture = value; //// } } //// /*=============================================================== //// ====================== Thread Statics =========================== //// ===============================================================*/ //// private int ReserveSlot() //// { //// // This is called by the thread on itself so no need for locks //// if(m_ThreadStaticsBuckets == null) //// { //// BCLDebug.Assert( STATICS_BUCKET_SIZE % 32 == 0, "STATICS_BUCKET_SIZE should be a multiple of 32" ); //// //// // allocate bucket holder //// // do not publish the data until all the intialization is done, in case of asynchronized exceptions //// Object[][] newBuckets = new Object[1][]; //// //// SetIsThreadStaticsArray( newBuckets ); //// //// // allocate the first bucket //// newBuckets[0] = new Object[STATICS_BUCKET_SIZE]; //// SetIsThreadStaticsArray( newBuckets[0] ); //// //// int[] newBits = new int[newBuckets.Length * STATICS_BUCKET_SIZE / 32]; //// //// // use memset! //// for(int i = 0; i < newBits.Length; i++) //// { //// newBits[i] = unchecked( (int)0xffffffff ); //// } //// //// // block the 0th position, we don't want any static to have //// // slot #0 (we use it to indicate invalid slot) //// newBits[0] &= ~1; //// //// // also we clear the bit for slot #1, as that is the one we will be returning //// newBits[0] &= ~2; //// //// // now publish the arrays //// // the write order matters here, because we check m_ThreadStaticsBuckets for initialization, //// // we should write it at the last //// m_ThreadStaticsBits = newBits; //// m_ThreadStaticsBuckets = newBuckets; //// //// return 1; //// } //// int slot = FindSlot(); //// //// // slot == 0 => all slots occupied //// if(slot == 0) //// { //// // We need to expand. Allocate a new bucket //// int oldLength = m_ThreadStaticsBuckets.Length; //// int oldLengthBits = m_ThreadStaticsBits.Length; //// //// int newLength = m_ThreadStaticsBuckets.Length + 1; //// Object[][] newBuckets = new Object[newLength][]; //// SetIsThreadStaticsArray( newBuckets ); //// //// int newLengthBits = newLength * STATICS_BUCKET_SIZE / 32; //// int[] newBits = new int[newLengthBits]; //// //// // Copy old buckets into new holder //// Array.Copy( m_ThreadStaticsBuckets, newBuckets, m_ThreadStaticsBuckets.Length ); //// //// // Allocate new buckets //// for(int i = oldLength; i < newLength; i++) //// { //// newBuckets[i] = new Object[STATICS_BUCKET_SIZE]; //// SetIsThreadStaticsArray( newBuckets[i] ); //// } //// //// //// // Copy old bits into new bit array //// Array.Copy( m_ThreadStaticsBits, newBits, m_ThreadStaticsBits.Length ); //// //// // Initalize new bits //// for(int i = oldLengthBits; i < newLengthBits; i++) //// { //// newBits[i] = unchecked( (int)0xffffffff ); //// } //// //// // Return the first slot in the expanded area //// newBits[oldLengthBits] &= ~1; //// //// // warning: if exceptions happen between the two writes, we are in a corrupted state //// // but the chances are very low //// m_ThreadStaticsBits = newBits; //// m_ThreadStaticsBuckets = newBuckets; //// //// return oldLength * STATICS_BUCKET_SIZE; //// } //// //// return slot; //// } //// //// int FindSlot() //// { #if DEBUG //// BCLDebug.Assert( m_ThreadStaticsBits != null, "m_ThreadStaticsBits must already be initialized" ); //// if(m_ThreadStaticsBits.Length != 0) //// { //// BCLDebug.Assert( m_ThreadStaticsBuckets != null && m_ThreadStaticsBits.Length == m_ThreadStaticsBuckets.Length * STATICS_BUCKET_SIZE / 32, //// "m_ThreadStaticsBuckets must already be intialized" ); //// //// for(int j = 0; j < m_ThreadStaticsBuckets.Length; j++) //// { //// BCLDebug.Assert( m_ThreadStaticsBuckets[j] != null && m_ThreadStaticsBuckets[j].Length == STATICS_BUCKET_SIZE, //// "m_ThreadStaticsBuckets must already be initialized" ); //// } //// } #endif //DEBUG //// //// int slot = 0; // 0 is not a valid slot number //// int bits = 0; //// int i; //// bool bFound = false; //// //// if(m_ThreadStaticsBits.Length != 0 && m_ThreadStaticsBits.Length != m_ThreadStaticsBuckets.Length * STATICS_BUCKET_SIZE / 32) //// { //// return 0; //// } //// //// for(i = 0; i < m_ThreadStaticsBits.Length; i++) //// { //// bits = m_ThreadStaticsBits[i]; //// if(bits != 0) //// { //// if((bits & 0xffff) != 0) //// { //// bits = bits & 0xffff; //// } //// else //// { //// bits = (bits >> 16) & 0xffff; //// slot += 16; //// } //// //// if((bits & 0xff) != 0) //// { //// bits = bits & 0xff; //// } //// else //// { //// slot += 8; //// bits = (bits >> 8) & 0xff; //// } //// //// int j; //// for(j = 0; j < 8; j++) //// { //// if((bits & (1 << j)) != 0) //// { //// bFound = true; //// break; //// } //// } //// //// BCLDebug.Assert( j < 8, "Bad bits?" ); //// //// slot += j; //// //// m_ThreadStaticsBits[i] &= ~(1 << slot); //// break; //// } //// } //// //// if(bFound) //// { //// slot = slot + 32 * i; //// } //// //// BCLDebug.Assert( bFound || slot == 0, "Bad bits" ); //// return slot; //// } //// /*=============================================================*/ //// //// /*====================================================================== //// ** Current thread context is stored in a slot in the thread local store //// ** CurrentContext gets the Context from the slot. //// ======================================================================*/ //// //// public static Context CurrentContext //// { //// [SecurityPermissionAttribute( SecurityAction.LinkDemand, Flags = SecurityPermissionFlag.Infrastructure )] //// get //// { //// return CurrentThread.GetCurrentContextInternal(); //// } //// } //// //// internal Context GetCurrentContextInternal() //// { //// if(m_Context == null) //// { //// m_Context = Context.DefaultContext; //// } //// //// return m_Context; //// } //// //// [HostProtection( SharedState = true, ExternalThreading = true )] //// internal LogicalCallContext GetLogicalCallContext() //// { //// return ExecutionContext.LogicalCallContext; //// } //// //// [HostProtection( SharedState = true, ExternalThreading = true )] //// internal LogicalCallContext SetLogicalCallContext( LogicalCallContext callCtx ) //// { //// LogicalCallContext oldCtx = ExecutionContext.LogicalCallContext; //// //// ExecutionContext.LogicalCallContext = callCtx; //// //// return oldCtx; //// } //// //// internal IllogicalCallContext GetIllogicalCallContext() //// { //// return ExecutionContext.IllogicalCallContext; //// } //// //// // Get and set thread's current principal (for role based security). //// public static IPrincipal CurrentPrincipal //// { //// get //// { //// lock(CurrentThread) //// { //// IPrincipal principal = (IPrincipal)CallContext.Principal; //// if(principal == null) //// { //// principal = GetDomain().GetThreadPrincipal(); //// //// CallContext.Principal = principal; //// } //// //// return principal; //// } //// } //// //// [SecurityPermissionAttribute( SecurityAction.Demand, Flags = SecurityPermissionFlag.ControlPrincipal )] //// set //// { //// CallContext.Principal = value; //// } //// } //// //// // Private routine called from unmanaged code to set an initial //// // principal for a newly created thread. //// private void SetPrincipalInternal( IPrincipal principal ) //// { //// GetLogicalCallContext().SecurityData.Principal = principal; //// } //// //// // This returns the exposed context for a given context ID. //// [ResourceExposure( ResourceScope.None )] //// [MethodImpl( MethodImplOptions.InternalCall )] //// internal static extern Context GetContextInternal( IntPtr id ); //// //// [ResourceExposure( ResourceScope.None )] //// [MethodImpl( MethodImplOptions.InternalCall )] //// internal extern Object InternalCrossContextCallback( Context ctx, IntPtr ctxID, Int32 appDomainID, InternalCrossContextDelegate ftnToCall, Object[] args ); //// //// internal Object InternalCrossContextCallback( Context ctx, InternalCrossContextDelegate ftnToCall, Object[] args ) //// { //// return InternalCrossContextCallback( ctx, ctx.InternalContextID, 0, ftnToCall, args ); //// } //// //// // CompleteCrossContextCallback is called by the EE after transitioning to the requested context //// private static Object CompleteCrossContextCallback( InternalCrossContextDelegate ftnToCall, Object[] args ) //// { //// return ftnToCall( args ); //// } //// //// /*====================================================================== //// ** Returns the current domain in which current thread is running. //// ======================================================================*/ //// //// [ResourceExposure( ResourceScope.None )] //// [MethodImpl( MethodImplOptions.InternalCall )] //// private static extern AppDomain GetDomainInternal(); //// //// [ResourceExposure( ResourceScope.None )] //// [MethodImpl( MethodImplOptions.InternalCall )] //// private static extern AppDomain GetFastDomainInternal(); //// //// public static AppDomain GetDomain() //// { //// if(CurrentThread.m_Context == null) //// { //// AppDomain ad; //// ad = GetFastDomainInternal(); //// if(ad == null) //// { //// ad = GetDomainInternal(); //// } //// //// return ad; //// } //// else //// { //// BCLDebug.Assert( GetDomainInternal() == CurrentThread.m_Context.AppDomain, "AppDomains on the managed & unmanaged threads should match" ); //// return CurrentThread.m_Context.AppDomain; //// } //// } //// //// //// /* //// * This returns a unique id to identify an appdomain. //// */ //// public static int GetDomainID() //// { //// return GetDomain().GetId(); //// } // Retrieves the name of the thread. // public String Name { get { return m_Name; } [HostProtection( ExternalThreading = true )] set { lock(this) { if(m_Name != null) { #if EXCEPTION_STRINGS throw new InvalidOperationException( Environment.GetResourceString( "InvalidOperation_WriteOnce" ) ); #else throw new InvalidOperationException(); #endif } m_Name = value; //// InformThreadNameChangeEx( this, m_Name ); } } } //// [ResourceExposure( ResourceScope.None )] //// [MethodImpl( MethodImplOptions.InternalCall )] //// internal static extern void InformThreadNameChangeEx( Thread t, String name ); //// //// internal Object AbortReason //// { //// get //// { //// object result = null; //// //// try //// { //// result = GetAbortReason(); //// } //// catch(Exception e) //// { //// throw new InvalidOperationException( Environment.GetResourceString( "InvalidOperation_ExceptionStateCrossAppDomain" ), e ); //// } //// //// return result; //// } //// //// set //// { //// SetAbortReason( value ); //// } //// } /* * This marks the beginning of a critical code region. */ [HostProtection( Synchronization = true, ExternalThreading = true )] //// [ResourceExposure( ResourceScope.None )] [MethodImpl( MethodImplOptions.InternalCall )] //// [ReliabilityContract( Consistency.WillNotCorruptState, Cer.MayFail )] public static extern void BeginCriticalRegion(); /* * This marks the end of a critical code region. */ [HostProtection( Synchronization = true, ExternalThreading = true )] //// [ResourceExposure( ResourceScope.None )] [MethodImpl( MethodImplOptions.InternalCall )] //// [ReliabilityContract( Consistency.WillNotCorruptState, Cer.Success )] public static extern void EndCriticalRegion(); //// /* //// * This marks the beginning of a code region that requires thread affinity. //// */ //// [SecurityPermissionAttribute( SecurityAction.LinkDemand, ControlThread = true )] //// [ResourceExposure( ResourceScope.None )] //// [MethodImpl( MethodImplOptions.InternalCall )] //// [ReliabilityContract( Consistency.WillNotCorruptState, Cer.MayFail )] //// public static extern void BeginThreadAffinity(); //// //// /* //// * This marks the end of a code region that requires thread affinity. //// */ //// [SecurityPermissionAttribute( SecurityAction.LinkDemand, ControlThread = true )] //// [ResourceExposure( ResourceScope.None )] //// [MethodImpl( MethodImplOptions.InternalCall )] //// [ReliabilityContract( Consistency.WillNotCorruptState, Cer.MayFail )] //// public static extern void EndThreadAffinity(); /*========================================================================= ** Volatile Read & Write and MemoryBarrier methods. ** Provides the ability to read and write values ensuring that the values ** are read/written each time they are accessed. =========================================================================*/ [MethodImpl( MethodImplOptions.NoInlining )] // disable optimizations public static byte VolatileRead( ref byte address ) { byte ret = address; MemoryBarrier(); // Call MemoryBarrier to ensure the proper semantic in a portable way. return ret; } [MethodImpl( MethodImplOptions.NoInlining )] // disable optimizations public static short VolatileRead( ref short address ) { short ret = address; MemoryBarrier(); // Call MemoryBarrier to ensure the proper semantic in a portable way. return ret; } [MethodImpl( MethodImplOptions.NoInlining )] // disable optimizations public static int VolatileRead( ref int address ) { int ret = address; MemoryBarrier(); // Call MemoryBarrier to ensure the proper semantic in a portable way. return ret; } [MethodImpl( MethodImplOptions.NoInlining )] // disable optimizations public static long VolatileRead( ref long address ) { long ret = address; MemoryBarrier(); // Call MemoryBarrier to ensure the proper semantic in a portable way. return ret; } [CLSCompliant( false )] [MethodImpl( MethodImplOptions.NoInlining )] // disable optimizations public static sbyte VolatileRead( ref sbyte address ) { sbyte ret = address; MemoryBarrier(); // Call MemoryBarrier to ensure the proper semantic in a portable way. return ret; } [CLSCompliant( false )] [MethodImpl( MethodImplOptions.NoInlining )] // disable optimizations public static ushort VolatileRead( ref ushort address ) { ushort ret = address; MemoryBarrier(); // Call MemoryBarrier to ensure the proper semantic in a portable way. return ret; } [CLSCompliant( false )] [MethodImpl( MethodImplOptions.NoInlining )] // disable optimizations public static uint VolatileRead( ref uint address ) { uint ret = address; MemoryBarrier(); // Call MemoryBarrier to ensure the proper semantic in a portable way. return ret; } [MethodImpl( MethodImplOptions.NoInlining )] // disable optimizations public static IntPtr VolatileRead( ref IntPtr address ) { IntPtr ret = address; MemoryBarrier(); // Call MemoryBarrier to ensure the proper semantic in a portable way. return ret; } [CLSCompliant( false )] [MethodImpl( MethodImplOptions.NoInlining )] // disable optimizations public static UIntPtr VolatileRead( ref UIntPtr address ) { UIntPtr ret = address; MemoryBarrier(); // Call MemoryBarrier to ensure the proper semantic in a portable way. return ret; } [CLSCompliant( false )] [MethodImpl( MethodImplOptions.NoInlining )] // disable optimizations public static ulong VolatileRead( ref ulong address ) { ulong ret = address; MemoryBarrier(); // Call MemoryBarrier to ensure the proper semantic in a portable way. return ret; } [MethodImpl( MethodImplOptions.NoInlining )] // disable optimizations public static float VolatileRead( ref float address ) { float ret = address; MemoryBarrier(); // Call MemoryBarrier to ensure the proper semantic in a portable way. return ret; } [MethodImpl( MethodImplOptions.NoInlining )] // disable optimizations public static double VolatileRead( ref double address ) { double ret = address; MemoryBarrier(); // Call MemoryBarrier to ensure the proper semantic in a portable way. return ret; } [MethodImpl( MethodImplOptions.NoInlining )] // disable optimizations public static Object VolatileRead( ref Object address ) { Object ret = address; MemoryBarrier(); // Call MemoryBarrier to ensure the proper semantic in a portable way. return ret; } [MethodImpl( MethodImplOptions.NoInlining )] // disable optimizations public static void VolatileWrite( ref byte address, byte value ) { MemoryBarrier(); // Call MemoryBarrier to ensure the proper semantic in a portable way. address = value; } [MethodImpl( MethodImplOptions.NoInlining )] // disable optimizations public static void VolatileWrite( ref short address, short value ) { MemoryBarrier(); // Call MemoryBarrier to ensure the proper semantic in a portable way. address = value; } [MethodImpl( MethodImplOptions.NoInlining )] // disable optimizations public static void VolatileWrite( ref int address, int value ) { MemoryBarrier(); // Call MemoryBarrier to ensure the proper semantic in a portable way. address = value; } [MethodImpl( MethodImplOptions.NoInlining )] // disable optimizations public static void VolatileWrite( ref long address, long value ) { MemoryBarrier(); // Call MemoryBarrier to ensure the proper semantic in a portable way. address = value; } [CLSCompliant( false )] [MethodImpl( MethodImplOptions.NoInlining )] // disable optimizations public static void VolatileWrite( ref sbyte address, sbyte value ) { MemoryBarrier(); // Call MemoryBarrier to ensure the proper semantic in a portable way. address = value; } [CLSCompliant( false )] [MethodImpl( MethodImplOptions.NoInlining )] // disable optimizations public static void VolatileWrite( ref ushort address, ushort value ) { MemoryBarrier(); // Call MemoryBarrier to ensure the proper semantic in a portable way. address = value; } [CLSCompliant( false )] [MethodImpl( MethodImplOptions.NoInlining )] // disable optimizations public static void VolatileWrite( ref uint address, uint value ) { MemoryBarrier(); // Call MemoryBarrier to ensure the proper semantic in a portable way. address = value; } [MethodImpl( MethodImplOptions.NoInlining )] // disable optimizations public static void VolatileWrite( ref IntPtr address, IntPtr value ) { MemoryBarrier(); // Call MemoryBarrier to ensure the proper semantic in a portable way. address = value; } [CLSCompliant( false )] [MethodImpl( MethodImplOptions.NoInlining )] // disable optimizations public static void VolatileWrite( ref UIntPtr address, UIntPtr value ) { MemoryBarrier(); // Call MemoryBarrier to ensure the proper semantic in a portable way. address = value; } [CLSCompliant( false )] [MethodImpl( MethodImplOptions.NoInlining )] // disable optimizations public static void VolatileWrite( ref ulong address, ulong value ) { MemoryBarrier(); // Call MemoryBarrier to ensure the proper semantic in a portable way. address = value; } [MethodImpl( MethodImplOptions.NoInlining )] // disable optimizations public static void VolatileWrite( ref float address, float value ) { MemoryBarrier(); // Call MemoryBarrier to ensure the proper semantic in a portable way. address = value; } [MethodImpl( MethodImplOptions.NoInlining )] // disable optimizations public static void VolatileWrite( ref double address, double value ) { MemoryBarrier(); // Call MemoryBarrier to ensure the proper semantic in a portable way. address = value; } [MethodImpl( MethodImplOptions.NoInlining )] // disable optimizations public static void VolatileWrite( ref Object address, Object value ) { MemoryBarrier(); // Call MemoryBarrier to ensure the proper semantic in a portable way. address = value; } //// [ResourceExposure( ResourceScope.None )] [MethodImpl( MethodImplOptions.InternalCall )] public static extern void MemoryBarrier(); //// //We need to mark thread statics array for AppDomain leak checking purpose //// [ResourceExposure( ResourceScope.None )] //// [MethodImpl( MethodImplOptions.InternalCall )] //// private static extern void SetIsThreadStaticsArray( Object o ); //// //// private static LocalDataStoreMgr LocalDataStoreManager //// { //// get //// { //// if(s_LocalDataStoreMgr == null) //// { //// Interlocked.CompareExchange( ref s_LocalDataStoreMgr, new LocalDataStoreMgr(), null ); //// } //// //// return s_LocalDataStoreMgr; //// } //// } //// //// // Helper function to set the AbortReason for a thread abort. //// // Checks that they're not alredy set, and then atomically updates //// // the reason info (object + ADID). //// [ResourceExposure( ResourceScope.None )] //// [MethodImpl( MethodImplOptions.InternalCall )] //// internal extern void SetAbortReason( Object o ); //// //// // Helper function to retrieve the AbortReason from a thread //// // abort. Will perform cross-AppDomain marshalling if the object //// // lives in a different AppDomain from the requester. //// [ResourceExposure( ResourceScope.None )] //// [MethodImpl( MethodImplOptions.InternalCall )] //// internal extern Object GetAbortReason(); //// //// // Helper function to clear the AbortReason. Takes care of //// // AppDomain related cleanup if required. //// [ResourceExposure( ResourceScope.None )] //// [MethodImpl( MethodImplOptions.InternalCall )] //// internal extern void ClearAbortReason(); } // End of class Thread // declaring a local var of this enum type and passing it by ref into a function that needs to do a // stack crawl will both prevent inlining of the calle and pass an ESP point to stack crawl to // Declaring these in EH clauses is illegal; they must declared in the main method body [Serializable] internal enum StackCrawlMark { LookForMe = 0, LookForMyCaller = 1, LookForMyCallersCaller = 2, LookForThread = 3, } } ================================================ FILE: Zelig/Zelig/RunTime/Framework/mscorlib/System/Threading/ThreadAbortException.cs ================================================ // ==++== // // Copyright (c) Microsoft Corporation. All rights reserved. // // ==--== /*============================================================================= ** ** Class: ThreadAbortException ** ** ** Purpose: An exception class which is thrown into a thread to cause it to ** abort. This is a special non-catchable exception and results in ** the thread's death. This is thrown by the VM only and can NOT be ** thrown by any user thread, and subclassing this is useless. ** ** =============================================================================*/ namespace System.Threading { using System; using System.Runtime.Serialization; using System.Runtime.CompilerServices; [Serializable] public sealed class ThreadAbortException : SystemException { private ThreadAbortException() : base( GetMessageFromNativeResources( ExceptionMessageKind.ThreadAbort ) ) { } //required for serialization //// internal ThreadAbortException( SerializationInfo info, StreamingContext context ) : base( info, context ) //// { //// } //// public Object ExceptionState //// { //// get //// { //// return Thread.CurrentThread.AbortReason; //// } //// } } } ================================================ FILE: Zelig/Zelig/RunTime/Framework/mscorlib/System/Threading/ThreadPool.cs ================================================ // ==++== // // Copyright (c) Microsoft Corporation. All rights reserved. // // ==--== /*============================================================================= ** ** Class: ThreadPool ** ** ** Purpose: Class for creating and managing a threadpool ** ** =============================================================================*/ /* * Below you'll notice two sets of APIs that are separated by the * use of 'Unsafe' in their names. The unsafe versions are called * that because they do not propagate the calling stack onto the * worker thread. This allows code to lose the calling stack and * thereby elevate its security privileges. Note that this operation * is much akin to the combined ability to control security policy * and control security evidence. With these privileges, a person * can gain the right to load assemblies that are fully trusted which * then assert full trust and can call any code they want regardless * of the previous stack information. */ namespace System.Threading { using System; using System.Security; using System.Threading; ////using System.Runtime.Remoting; using System.Security.Permissions; ////using Microsoft.Win32; using System.Runtime.CompilerServices; using System.Runtime.ConstrainedExecution; using System.Runtime.InteropServices; ////using System.Runtime.Versioning; ////internal sealed class RegisteredWaitHandleSafe : CriticalFinalizerObject ////{ //// private static readonly IntPtr InvalidHandle = Win32Native.INVALID_HANDLE_VALUE; //// private IntPtr registeredWaitHandle; //// private WaitHandle m_internalWaitObject; //// private bool bReleaseNeeded = false; //// private int m_lock = 0; //// //// internal RegisteredWaitHandleSafe() //// { //// registeredWaitHandle = InvalidHandle; //// } //// //// internal IntPtr GetHandle() //// { //// return registeredWaitHandle; //// } //// //// internal void SetHandle( IntPtr handle ) //// { //// registeredWaitHandle = handle; //// } //// //// [ResourceExposure( ResourceScope.None )] //// [ResourceConsumption( ResourceScope.Machine, ResourceScope.Machine )] //// [ReliabilityContract( Consistency.WillNotCorruptState, Cer.MayFail )] //// internal void SetWaitObject( WaitHandle waitObject ) //// { //// // needed for DangerousAddRef //// RuntimeHelpers.PrepareConstrainedRegions(); //// try //// { //// } //// finally //// { //// m_internalWaitObject = waitObject; //// if(waitObject != null) //// { //// m_internalWaitObject.SafeWaitHandle.DangerousAddRef( ref bReleaseNeeded ); //// } //// } //// } //// //// [ResourceExposure( ResourceScope.None )] //// [ResourceConsumption( ResourceScope.Machine, ResourceScope.Machine )] //// [ReliabilityContract( Consistency.WillNotCorruptState, Cer.MayFail )] //// internal bool Unregister( //// WaitHandle waitObject // object to be notified when all callbacks to delegates have completed //// ) //// { //// bool result = false; //// // needed for DangerousRelease //// RuntimeHelpers.PrepareConstrainedRegions(); //// try //// { //// } //// finally //// { //// // lock(this) cannot be used reliably in Cer since thin lock could be //// // promoted to syncblock and that is not a guaranteed operation //// bool bLockTaken = false; //// do //// { //// if(Interlocked.CompareExchange( ref m_lock, 1, 0 ) == 0) //// { //// bLockTaken = true; //// try //// { //// if(ValidHandle()) //// { //// result = UnregisterWaitNative( GetHandle(), waitObject == null ? null : waitObject.SafeWaitHandle ); //// if(result == true) //// { //// if(bReleaseNeeded) //// { //// m_internalWaitObject.SafeWaitHandle.DangerousRelease(); //// bReleaseNeeded = false; //// } //// // if result not true don't release/suppress here so finalizer can make another attempt //// SetHandle( InvalidHandle ); //// m_internalWaitObject = null; //// GC.SuppressFinalize( this ); //// } //// } //// } //// finally //// { //// m_lock = 0; //// } //// } //// Thread.SpinWait( 1 ); // yield to processor //// } //// while(!bLockTaken); //// } //// return result; //// } //// //// private bool ValidHandle() //// { //// return (registeredWaitHandle != InvalidHandle && registeredWaitHandle != IntPtr.Zero); //// } //// //// [ResourceExposure( ResourceScope.None )] //// [ResourceConsumption( ResourceScope.Machine, ResourceScope.Machine )] //// ~RegisteredWaitHandleSafe() //// { //// // if the app has already unregistered the wait, there is nothing to cleanup //// // we can detect this by checking the handle. Normally, there is no race here //// // so no need to protect reading of handle. However, if this object gets //// // resurrected and then someone does an unregister, it would introduce a race //// //// // PrepareConstrainedRegions call not needed since finalizer already in Cer //// //// // lock(this) cannot be used reliably even in Cer since thin lock could be //// // promoted to syncblock and that is not a guaranteed operation //// //// bool bLockTaken = false; //// do //// { //// if(Interlocked.CompareExchange( ref m_lock, 1, 0 ) == 0) //// { //// bLockTaken = true; //// try //// { //// if(ValidHandle()) //// { //// WaitHandleCleanupNative( registeredWaitHandle ); //// if(bReleaseNeeded) //// { //// m_internalWaitObject.SafeWaitHandle.DangerousRelease(); //// bReleaseNeeded = false; //// } //// SetHandle( InvalidHandle ); //// m_internalWaitObject = null; //// } //// } //// finally //// { //// m_lock = 0; //// } //// } //// Thread.SpinWait( 1 ); // yield to processor //// } //// while(!bLockTaken); //// } //// //// [ResourceExposure( ResourceScope.Machine )] //// [MethodImplAttribute( MethodImplOptions.InternalCall )] //// private static extern void WaitHandleCleanupNative( IntPtr handle ); //// //// [ResourceExposure( ResourceScope.Machine )] //// [MethodImplAttribute( MethodImplOptions.InternalCall )] //// private static extern bool UnregisterWaitNative( IntPtr handle, SafeHandle waitObject ); ////} //// ////public sealed class RegisteredWaitHandle : MarshalByRefObject ////{ //// private RegisteredWaitHandleSafe internalRegisteredWait; //// //// internal RegisteredWaitHandle() //// { //// internalRegisteredWait = new RegisteredWaitHandleSafe(); //// } //// //// internal void SetHandle( IntPtr handle ) //// { //// internalRegisteredWait.SetHandle( handle ); //// } //// //// internal void SetWaitObject( WaitHandle waitObject ) //// { //// internalRegisteredWait.SetWaitObject( waitObject ); //// } //// //// //// // This is the only public method on this class //// public bool Unregister( //// WaitHandle waitObject // object to be notified when all callbacks to delegates have completed //// ) //// { //// return internalRegisteredWait.Unregister( waitObject ); //// } ////} public delegate void WaitCallback( Object state ); public delegate void WaitOrTimerCallback( Object state, bool timedOut ); // signalled or timed out ////internal class _ThreadPoolWaitCallback ////{ //// WaitCallback _waitCallback; //// ExecutionContext _executionContext; //// Object _state; //// //// static internal ContextCallback _ccb = new ContextCallback( WaitCallback_Context ); //// static internal void WaitCallback_Context( Object state ) //// { //// _ThreadPoolWaitCallback obj = (_ThreadPoolWaitCallback)state; //// obj._waitCallback( obj._state ); //// } //// //// //// internal _ThreadPoolWaitCallback( WaitCallback waitCallback, Object state, bool compressStack, ref StackCrawlMark stackMark ) //// { //// _waitCallback = waitCallback; //// _state = state; //// if(compressStack && !ExecutionContext.IsFlowSuppressed()) //// { //// // clone the exection context //// _executionContext = ExecutionContext.Capture( ref stackMark ); //// ExecutionContext.ClearSyncContext( _executionContext ); //// } //// } //// //// // call back helper //// static internal void PerformWaitCallback( Object state ) //// { //// _ThreadPoolWaitCallback helper = (_ThreadPoolWaitCallback)state; //// //// BCLDebug.Assert( helper != null, "Null state passed to PerformWaitCallback!" ); //// // call directly if it is an unsafe call OR EC flow is suppressed //// if(helper._executionContext == null) //// { //// WaitCallback callback = helper._waitCallback; //// callback( helper._state ); //// } //// else //// { //// ExecutionContext.Run( helper._executionContext, _ccb, helper ); //// } //// } ////}; //// ////internal class _ThreadPoolWaitOrTimerCallback ////{ //// WaitOrTimerCallback _waitOrTimerCallback; //// ExecutionContext _executionContext; //// Object _state; //// static private ContextCallback _ccbt = new ContextCallback( WaitOrTimerCallback_Context_t ); //// static private ContextCallback _ccbf = new ContextCallback( WaitOrTimerCallback_Context_f ); //// //// internal _ThreadPoolWaitOrTimerCallback( WaitOrTimerCallback waitOrTimerCallback, Object state, bool compressStack, ref StackCrawlMark stackMark ) //// { //// _waitOrTimerCallback = waitOrTimerCallback; //// _state = state; //// if(compressStack && !ExecutionContext.IsFlowSuppressed()) //// { //// // capture the exection context //// _executionContext = ExecutionContext.Capture( ref stackMark ); //// ExecutionContext.ClearSyncContext( _executionContext ); //// } //// } //// static private void WaitOrTimerCallback_Context_t( Object state ) //// { //// WaitOrTimerCallback_Context( state, true ); //// } //// static private void WaitOrTimerCallback_Context_f( Object state ) //// { //// WaitOrTimerCallback_Context( state, false ); //// } //// //// static private void WaitOrTimerCallback_Context( Object state, bool timedOut ) //// { //// _ThreadPoolWaitOrTimerCallback helper = (_ThreadPoolWaitOrTimerCallback)state; //// helper._waitOrTimerCallback( helper._state, timedOut ); //// } //// //// //// // call back helper //// static internal void PerformWaitOrTimerCallback( Object state, bool timedOut ) //// { //// _ThreadPoolWaitOrTimerCallback helper = (_ThreadPoolWaitOrTimerCallback)state; //// BCLDebug.Assert( helper != null, "Null state passed to PerformWaitOrTimerCallback!" ); //// // call directly if it is an unsafe call OR EC flow is suppressed //// if(helper._executionContext == null) //// { //// WaitOrTimerCallback callback = helper._waitOrTimerCallback; //// callback( helper._state, timedOut ); //// } //// else //// { //// if(timedOut) //// ExecutionContext.Run( helper._executionContext.CreateCopy(), _ccbt, helper ); //// else //// ExecutionContext.Run( helper._executionContext.CreateCopy(), _ccbf, helper ); //// } //// } ////}; //// ////[CLSCompliant( false )] ////unsafe public delegate void IOCompletionCallback( uint errorCode, // Error code //// uint numBytes, // No. of bytes transferred //// NativeOverlapped* pOVERLAP // ptr to OVERLAP structure //// ); [HostProtection( Synchronization = true, ExternalThreading = true )] public static class ThreadPool { //// [SecurityPermissionAttribute( SecurityAction.Demand, ControlThread = true )] [MethodImpl( MethodImplOptions.InternalCall )] public extern static bool SetMaxThreads( int workerThreads , int completionPortThreads ); //// { //// return SetMaxThreadsNative( workerThreads, completionPortThreads ); //// } //// public static void GetMaxThreads( out int workerThreads , //// out int completionPortThreads ) //// { //// GetMaxThreadsNative( out workerThreads, out completionPortThreads ); //// } //// //// [SecurityPermissionAttribute( SecurityAction.Demand, ControlThread = true )] //// public static bool SetMinThreads( int workerThreads , //// int completionPortThreads ) //// { //// return SetMinThreadsNative( workerThreads, completionPortThreads ); //// } //// //// public static void GetMinThreads( out int workerThreads , //// out int completionPortThreads ) //// { //// GetMinThreadsNative( out workerThreads, out completionPortThreads ); //// } //// //// public static void GetAvailableThreads( out int workerThreads , //// out int completionPortThreads ) //// { //// GetAvailableThreadsNative( out workerThreads, out completionPortThreads ); //// } //// //// // throws RegisterWaitException //// [CLSCompliant( false )] //// public static RegisteredWaitHandle RegisterWaitForSingleObject( WaitHandle waitObject , //// WaitOrTimerCallback callBack , //// Object state , //// uint millisecondsTimeOutInterval , //// bool executeOnlyOnce ) //// { //// StackCrawlMark stackMark = StackCrawlMark.LookForMyCaller; //// //// return RegisterWaitForSingleObject( waitObject, callBack, state, millisecondsTimeOutInterval, executeOnlyOnce, ref stackMark, true ); //// } //// //// // throws RegisterWaitException //// [CLSCompliant( false )] //// [SecurityPermissionAttribute( SecurityAction.LinkDemand, Flags = SecurityPermissionFlag.ControlEvidence | SecurityPermissionFlag.ControlPolicy )] //// public static RegisteredWaitHandle UnsafeRegisterWaitForSingleObject( WaitHandle waitObject , //// WaitOrTimerCallback callBack , //// Object state , //// uint millisecondsTimeOutInterval , //// bool executeOnlyOnce ) //// { //// StackCrawlMark stackMark = StackCrawlMark.LookForMyCaller; //// //// return RegisterWaitForSingleObject( waitObject, callBack, state, millisecondsTimeOutInterval, executeOnlyOnce, ref stackMark, false ); //// } //// //// //// // throws RegisterWaitException //// private static RegisteredWaitHandle RegisterWaitForSingleObject( WaitHandle waitObject , //// WaitOrTimerCallback callBack , //// Object state , //// uint millisecondsTimeOutInterval , //// bool executeOnlyOnce , //// ref StackCrawlMark stackMark , //// bool compressStack ) //// { //// if(RemotingServices.IsTransparentProxy( waitObject )) //// { //// throw new InvalidOperationException( Environment.GetResourceString( "InvalidOperation_WaitOnTransparentProxy" ) ); //// } //// //// RegisteredWaitHandle registeredWaitHandle = new RegisteredWaitHandle(); //// //// if(callBack != null) //// { //// _ThreadPoolWaitOrTimerCallback callBackHelper = new _ThreadPoolWaitOrTimerCallback( callBack, state, compressStack, ref stackMark ); //// state = (Object)callBackHelper; //// // call SetWaitObject before native call so that waitObject won't be closed before threadpoolmgr registration //// // this could occur if callback were to fire before SetWaitObject does its addref //// registeredWaitHandle.SetWaitObject( waitObject ); //// IntPtr nativeRegisteredWaitHandle = RegisterWaitForSingleObjectNative( waitObject, //// state, //// millisecondsTimeOutInterval, //// executeOnlyOnce, //// registeredWaitHandle, //// ref stackMark, //// compressStack ); //// registeredWaitHandle.SetHandle( nativeRegisteredWaitHandle ); //// } //// else //// { //// throw new ArgumentNullException( "WaitOrTimerCallback" ); //// } //// //// return registeredWaitHandle; //// } //// //// //// // throws RegisterWaitException //// public static RegisteredWaitHandle RegisterWaitForSingleObject( WaitHandle waitObject , //// WaitOrTimerCallback callBack , //// Object state , //// int millisecondsTimeOutInterval , //// bool executeOnlyOnce ) //// { //// if(millisecondsTimeOutInterval < -1) //// { //// throw new ArgumentOutOfRangeException( "millisecondsTimeOutInterval", Environment.GetResourceString( "ArgumentOutOfRange_NeedNonNegOrNegative1" ) ); //// } //// //// StackCrawlMark stackMark = StackCrawlMark.LookForMyCaller; //// //// return RegisterWaitForSingleObject( waitObject, callBack, state, (UInt32)millisecondsTimeOutInterval, executeOnlyOnce, ref stackMark, true ); //// } //// //// // throws RegisterWaitException //// [SecurityPermissionAttribute( SecurityAction.LinkDemand, Flags = SecurityPermissionFlag.ControlEvidence | SecurityPermissionFlag.ControlPolicy )] //// public static RegisteredWaitHandle UnsafeRegisterWaitForSingleObject( WaitHandle waitObject , //// WaitOrTimerCallback callBack , //// Object state , //// int millisecondsTimeOutInterval , //// bool executeOnlyOnce ) //// { //// if(millisecondsTimeOutInterval < -1) //// { //// throw new ArgumentOutOfRangeException( "millisecondsTimeOutInterval", Environment.GetResourceString( "ArgumentOutOfRange_NeedNonNegOrNegative1" ) ); //// } //// //// StackCrawlMark stackMark = StackCrawlMark.LookForMyCaller; //// //// return RegisterWaitForSingleObject( waitObject, callBack, state, (UInt32)millisecondsTimeOutInterval, executeOnlyOnce, ref stackMark, false ); //// } //// //// // throws RegisterWaitException //// public static RegisteredWaitHandle RegisterWaitForSingleObject( WaitHandle waitObject , //// WaitOrTimerCallback callBack , //// Object state , //// long millisecondsTimeOutInterval , //// bool executeOnlyOnce ) //// { //// if(millisecondsTimeOutInterval < -1) //// { //// throw new ArgumentOutOfRangeException( "millisecondsTimeOutInterval", Environment.GetResourceString( "ArgumentOutOfRange_NeedNonNegOrNegative1" ) ); //// } //// //// StackCrawlMark stackMark = StackCrawlMark.LookForMyCaller; //// //// return RegisterWaitForSingleObject( waitObject, callBack, state, (UInt32)millisecondsTimeOutInterval, executeOnlyOnce, ref stackMark, true ); //// } //// //// // throws RegisterWaitException //// [SecurityPermissionAttribute( SecurityAction.LinkDemand, Flags = SecurityPermissionFlag.ControlEvidence | SecurityPermissionFlag.ControlPolicy )] //// public static RegisteredWaitHandle UnsafeRegisterWaitForSingleObject( WaitHandle waitObject , //// WaitOrTimerCallback callBack , //// Object state , //// long millisecondsTimeOutInterval , //// bool executeOnlyOnce ) //// { //// if(millisecondsTimeOutInterval < -1) //// { //// throw new ArgumentOutOfRangeException( "millisecondsTimeOutInterval", Environment.GetResourceString( "ArgumentOutOfRange_NeedNonNegOrNegative1" ) ); //// } //// //// StackCrawlMark stackMark = StackCrawlMark.LookForMyCaller; //// //// return RegisterWaitForSingleObject( waitObject, callBack, state, (UInt32)millisecondsTimeOutInterval, executeOnlyOnce, ref stackMark, false ); //// } //// //// //// public static RegisteredWaitHandle RegisterWaitForSingleObject( WaitHandle waitObject , //// WaitOrTimerCallback callBack , //// Object state , //// TimeSpan timeout , //// bool executeOnlyOnce ) //// { //// long tm = (long)timeout.TotalMilliseconds; //// if(tm < -1) //// { //// throw new ArgumentOutOfRangeException( "timeout", Environment.GetResourceString( "ArgumentOutOfRange_NeedNonNegOrNegative1" ) ); //// } //// if(tm > (long)Int32.MaxValue) //// { //// throw new ArgumentOutOfRangeException( "timeout", Environment.GetResourceString( "ArgumentOutOfRange_LessEqualToIntegerMaxVal" ) ); //// } //// //// StackCrawlMark stackMark = StackCrawlMark.LookForMyCaller; //// //// return RegisterWaitForSingleObject( waitObject, callBack, state, (UInt32)tm, executeOnlyOnce, ref stackMark, true ); //// } //// //// [SecurityPermissionAttribute( SecurityAction.LinkDemand, Flags = SecurityPermissionFlag.ControlEvidence | SecurityPermissionFlag.ControlPolicy )] //// public static RegisteredWaitHandle UnsafeRegisterWaitForSingleObject( WaitHandle waitObject , //// WaitOrTimerCallback callBack , //// Object state , //// TimeSpan timeout , //// bool executeOnlyOnce ) //// { //// long tm = (long)timeout.TotalMilliseconds; //// if(tm < -1) //// { //// throw new ArgumentOutOfRangeException( "timeout", Environment.GetResourceString( "ArgumentOutOfRange_NeedNonNegOrNegative1" ) ); //// } //// //// if(tm > (long)Int32.MaxValue) //// { //// throw new ArgumentOutOfRangeException( "timeout", Environment.GetResourceString( "ArgumentOutOfRange_LessEqualToIntegerMaxVal" ) ); //// } //// //// StackCrawlMark stackMark = StackCrawlMark.LookForMyCaller; //// //// return RegisterWaitForSingleObject( waitObject, callBack, state, (UInt32)tm, executeOnlyOnce, ref stackMark, false ); //// } [MethodImpl( MethodImplOptions.InternalCall )] public extern static bool QueueUserWorkItem( WaitCallback callBack , Object state ); //// { //// StackCrawlMark stackMark = StackCrawlMark.LookForMyCaller; //// //// return QueueUserWorkItemHelper( callBack, state, ref stackMark, true ); //// } [MethodImpl( MethodImplOptions.InternalCall )] public extern static bool QueueUserWorkItem( WaitCallback callBack ); //// { //// StackCrawlMark stackMark = StackCrawlMark.LookForMyCaller; //// //// return QueueUserWorkItemHelper( callBack, null, ref stackMark, true ); //// } //// [SecurityPermissionAttribute( SecurityAction.LinkDemand, Flags = SecurityPermissionFlag.ControlEvidence | SecurityPermissionFlag.ControlPolicy )] //// public static bool UnsafeQueueUserWorkItem( WaitCallback callBack , //// Object state ) //// { //// StackCrawlMark stackMark = StackCrawlMark.LookForMyCaller; //// //// return QueueUserWorkItemHelper( callBack, state, ref stackMark, false ); //// } //// //// private static bool QueueUserWorkItemHelper( WaitCallback callBack , //// Object state , //// ref StackCrawlMark stackMark , //// bool compressStack ) //// { //// if(callBack != null) //// { //// _ThreadPoolWaitCallback callBackHelper = new _ThreadPoolWaitCallback( callBack, state, compressStack, ref stackMark ); //// //// state = (Object)callBackHelper; //// //// return QueueUserWorkItem( state, ref stackMark, compressStack ); //// } //// else //// { //// throw new ArgumentNullException( "WaitCallback" ); //// } //// } //// //// [ResourceExposure( ResourceScope.None )] //// [MethodImplAttribute( MethodImplOptions.InternalCall )] //// private static extern bool QueueUserWorkItem( Object state, ref StackCrawlMark stackMark, bool compressStack ); //// //// [ResourceExposure( ResourceScope.None )] //// [MethodImplAttribute( MethodImplOptions.InternalCall )] //// unsafe private static extern bool PostQueuedCompletionStatus( NativeOverlapped* overlapped ); //// //// [CLSCompliant( false )] //// [SecurityPermissionAttribute( SecurityAction.LinkDemand, Flags = SecurityPermissionFlag.ControlEvidence | SecurityPermissionFlag.ControlPolicy )] //// unsafe public static bool UnsafeQueueNativeOverlapped( NativeOverlapped* overlapped ) //// { //// return PostQueuedCompletionStatus( overlapped ); //// } //// //// // Native methods: //// //// [ResourceExposure( ResourceScope.None )] //// [MethodImplAttribute( MethodImplOptions.InternalCall )] //// private static extern bool SetMinThreadsNative( int workerThreads, int completionPortThreads ); //// //// [ResourceExposure( ResourceScope.None )] //// [MethodImplAttribute( MethodImplOptions.InternalCall )] //// private static extern bool SetMaxThreadsNative( int workerThreads, int completionPortThreads ); //// //// [ResourceExposure( ResourceScope.None )] //// [MethodImplAttribute( MethodImplOptions.InternalCall )] //// private static extern void GetMinThreadsNative( out int workerThreads, out int completionPortThreads ); //// //// [ResourceExposure( ResourceScope.None )] //// [MethodImplAttribute( MethodImplOptions.InternalCall )] //// private static extern void GetMaxThreadsNative( out int workerThreads, out int completionPortThreads ); //// //// [ResourceExposure( ResourceScope.None )] //// [MethodImplAttribute( MethodImplOptions.InternalCall )] //// private static extern void GetAvailableThreadsNative( out int workerThreads, out int completionPortThreads ); //// //// [ResourceExposure( ResourceScope.None )] //// [MethodImplAttribute( MethodImplOptions.InternalCall )] //// private static extern IntPtr RegisterWaitForSingleObjectNative( WaitHandle waitHandle , //// Object state , //// uint timeOutInterval , //// bool executeOnlyOnce , //// RegisteredWaitHandle registeredWaitHandle , //// ref StackCrawlMark stackMark , //// bool compressStack ); //// //// [Obsolete( "ThreadPool.BindHandle(IntPtr) has been deprecated. Please use ThreadPool.BindHandle(SafeHandle) instead.", false )] //// [SecurityPermissionAttribute( SecurityAction.Demand, Flags = SecurityPermissionFlag.UnmanagedCode )] //// public static bool BindHandle( IntPtr osHandle ) //// { //// return BindIOCompletionCallbackNative( osHandle ); //// } //// //// [SecurityPermissionAttribute( SecurityAction.Demand, Flags = SecurityPermissionFlag.UnmanagedCode )] //// public static bool BindHandle( SafeHandle osHandle ) //// { //// if(osHandle == null) //// { //// throw new ArgumentNullException( "osHandle" ); //// } //// //// bool ret = false; //// bool mustReleaseSafeHandle = false; //// RuntimeHelpers.PrepareConstrainedRegions(); //// try //// { //// osHandle.DangerousAddRef( ref mustReleaseSafeHandle ); //// ret = BindIOCompletionCallbackNative( osHandle.DangerousGetHandle() ); //// } //// finally //// { //// if(mustReleaseSafeHandle) //// { //// osHandle.DangerousRelease(); //// } //// } //// return ret; //// } //// //// [ResourceExposure( ResourceScope.None )] //// [MethodImplAttribute( MethodImplOptions.InternalCall )] //// [ReliabilityContract( Consistency.WillNotCorruptState, Cer.MayFail )] //// private static extern bool BindIOCompletionCallbackNative( IntPtr fileHandle ); } } ================================================ FILE: Zelig/Zelig/RunTime/Framework/mscorlib/System/Threading/ThreadPriority.cs ================================================ // ==++== // // Copyright (c) Microsoft Corporation. All rights reserved. // // ==--== /*============================================================================= ** ** Class: ThreadPriority ** ** ** Purpose: Enums for the priorities of a Thread ** ** =============================================================================*/ namespace System.Threading { using System.Threading; [Serializable()] public enum ThreadPriority { /*========================================================================= ** Constants for thread priorities. =========================================================================*/ Lowest = 0, BelowNormal = 1, Normal = 2, AboveNormal = 3, Highest = 4, } } ================================================ FILE: Zelig/Zelig/RunTime/Framework/mscorlib/System/Threading/ThreadStart.cs ================================================ // ==++== // // Copyright (c) Microsoft Corporation. All rights reserved. // // ==--== /*============================================================================= ** ** Class: ThreadStart ** ** ** Purpose: This class is a Delegate which defines the start method ** for starting a thread. That method must match this delegate. ** ** =============================================================================*/ namespace System.Threading { ////using System.Security.Permissions; using System.Threading; // Define the delegate // NOTE: If you change the signature here, there is code in COMSynchronization // that invokes this delegate in native. public delegate void ThreadStart(); } ================================================ FILE: Zelig/Zelig/RunTime/Framework/mscorlib/System/Threading/ThreadStartException.cs ================================================ // ==++== // // Copyright (c) Microsoft Corporation. All rights reserved. // // ==--== namespace System.Threading { using System; using System.Runtime.Serialization; using System.Runtime.InteropServices; [Serializable] public sealed class ThreadStartException : SystemException { private ThreadStartException() : base( Environment.GetResourceString( "Arg_ThreadStartException" ) ) { } private ThreadStartException( Exception reason ) : base( Environment.GetResourceString( "Arg_ThreadStartException" ), reason ) { } //// internal ThreadStartException( SerializationInfo info, StreamingContext context ) : base( info, context ) //// { //// } } } ================================================ FILE: Zelig/Zelig/RunTime/Framework/mscorlib/System/Threading/ThreadState.cs ================================================ // ==++== // // Copyright (c) Microsoft Corporation. All rights reserved. // // ==--== /*============================================================================= ** ** Class: ThreadState ** ** ** Purpose: Enum to represent the different thread states ** ** =============================================================================*/ namespace System.Threading { [Flags] [Serializable] public enum ThreadState { /*========================================================================= ** Constants for thread states. =========================================================================*/ Running = 0x000, StopRequested = 0x001, SuspendRequested = 0x002, Background = 0x004, Unstarted = 0x008, Stopped = 0x010, WaitSleepJoin = 0x020, Suspended = 0x040, AbortRequested = 0x080, Aborted = 0x100, } } ================================================ FILE: Zelig/Zelig/RunTime/Framework/mscorlib/System/Threading/ThreadStateException.cs ================================================ // ==++== // // Copyright (c) Microsoft Corporation. All rights reserved. // // ==--== /*============================================================================= ** ** Class: ThreadStateException ** ** ** Purpose: An exception class to indicate that the Thread class is in an ** invalid state for the method. ** ** =============================================================================*/ namespace System.Threading { using System; using System.Runtime.Serialization; [Serializable] public class ThreadStateException : SystemException { public ThreadStateException() : base( Environment.GetResourceString( "Arg_ThreadStateException" ) ) { } public ThreadStateException( String message ) : base( message ) { } public ThreadStateException( String message, Exception innerException ) : base( message, innerException ) { } //// protected ThreadStateException( SerializationInfo info, StreamingContext context ) : base( info, context ) //// { //// } } } ================================================ FILE: Zelig/Zelig/RunTime/Framework/mscorlib/System/Threading/Timeout.cs ================================================ // ==++== // // Copyright (c) Microsoft Corporation. All rights reserved. // // ==--== namespace System.Threading { using System; using System.Threading; // A constant used by methods that take a timeout (Object.Wait, Thread.Sleep // etc) to indicate that no timeout should occur. // // @todo: this should become an enum. //This class has only static members and does not require serialization. public static class Timeout { public const int Infinite = -1; } } ================================================ FILE: Zelig/Zelig/RunTime/Framework/mscorlib/System/Threading/Timer.cs ================================================ // ==++== // // Copyright (c) Microsoft Corporation. All rights reserved. // // ==--== /*============================================================================= ** ** Class: TimerQueue ** ** ** Purpose: Class for creating and managing a threadpool ** ** =============================================================================*/ namespace System.Threading { using System; using System.Threading; using System.Security; using System.Security.Permissions; ////using Microsoft.Win32; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using System.Runtime.ConstrainedExecution; ////using System.Runtime.Versioning; ////internal class _TimerCallback ////{ //// TimerCallback m_timerCallback; //// ExecutionContext m_executionContext; //// Object m_state; //// //// static internal ContextCallback s_ccb = new ContextCallback( TimerCallback_Context ); //// //// static internal void TimerCallback_Context( Object state ) //// { //// _TimerCallback helper = (_TimerCallback)state; //// //// helper.m_timerCallback( helper.m_state ); //// } //// //// internal _TimerCallback( TimerCallback timerCallback, Object state, ref StackCrawlMark stackMark ) //// { //// m_timerCallback = timerCallback; //// m_state = state; //// //// if(!ExecutionContext.IsFlowSuppressed()) //// { //// m_executionContext = ExecutionContext.Capture( ref stackMark ); //// //// ExecutionContext.ClearSyncContext( m_executionContext ); //// } //// } //// //// // call back helper //// static internal void PerformTimerCallback( Object state ) //// { //// _TimerCallback helper = (_TimerCallback)state; //// //// BCLDebug.Assert( helper != null, "Null state passed to PerformTimerCallback!" ); //// //// // call directly if EC flow is suppressed //// if(helper.m_executionContext == null) //// { //// TimerCallback callback = helper.m_timerCallback; //// //// callback( helper.m_state ); //// } //// else //// { //// // From this point on we can use useExecutionContext for this callback //// ExecutionContext.Run( helper.m_executionContext.CreateCopy(), s_ccb, helper ); //// } //// } ////} public delegate void TimerCallback( Object state ); ////[HostProtection( Synchronization = true, ExternalThreading = true )] ////internal sealed class TimerBase : CriticalFinalizerObject /*, IDisposable*/ ////{ #pragma warning disable 169 //// private IntPtr m_timerHandle; //// private IntPtr m_delegateInfo; #pragma warning restore 169 //// private int m_timerDeleted; //// private int m_lock = 0; //// //// ~TimerBase() //// { //// // lock(this) cannot be used reliably in Cer since thin lock could be //// // promoted to syncblock and that is not a guaranteed operation //// bool bLockTaken = false; //// //// do //// { //// if(Interlocked.CompareExchange( ref m_lock, 1, 0 ) == 0) //// { //// bLockTaken = true; //// //// try //// { //// DeleteTimerNative( null ); //// } //// finally //// { //// m_lock = 0; //// } //// } //// //// Thread.SpinWait( 1 ); // yield to processor //// } //// while(!bLockTaken); //// } //// //// internal void AddTimer( TimerCallback callback , //// Object state , //// UInt32 dueTime , //// UInt32 period , //// ref StackCrawlMark stackMark ) //// { //// if(callback != null) //// { //// _TimerCallback callbackHelper = new _TimerCallback( callback, state, ref stackMark ); //// //// state = (Object)callbackHelper; //// //// AddTimerNative( state, dueTime, period, ref stackMark ); //// //// m_timerDeleted = 0; //// } //// else //// { //// throw new ArgumentNullException( "TimerCallback" ); //// } //// } //// //// [ReliabilityContract( Consistency.WillNotCorruptState, Cer.MayFail )] //// internal bool ChangeTimer( UInt32 dueTime, UInt32 period ) //// { //// bool status = false; //// bool bLockTaken = false; //// //// // prepare here to prevent threadabort from occuring which could //// // destroy m_lock state. lock(this) can't be used due to critical //// // finalizer and thinlock/syncblock escalation. //// RuntimeHelpers.PrepareConstrainedRegions(); //// try //// { //// } //// finally //// { //// do //// { //// if(Interlocked.CompareExchange( ref m_lock, 1, 0 ) == 0) //// { //// bLockTaken = true; //// try //// { //// if(m_timerDeleted != 0) //// { //// throw new ObjectDisposedException( null, Environment.GetResourceString( "ObjectDisposed_Generic" ) ); //// } //// //// status = ChangeTimerNative( dueTime, period ); //// } //// finally //// { //// m_lock = 0; //// } //// } //// //// Thread.SpinWait( 1 ); // yield to processor //// } //// while(!bLockTaken); //// } //// //// return status; //// //// } //// //// [ReliabilityContract( Consistency.WillNotCorruptState, Cer.MayFail )] //// [ResourceExposure( ResourceScope.None )] //// [ResourceConsumption( ResourceScope.Machine, ResourceScope.Machine )] //// internal bool Dispose( WaitHandle notifyObject ) //// { //// bool status = false; //// bool bLockTaken = false; //// //// RuntimeHelpers.PrepareConstrainedRegions(); //// try //// { //// } //// finally //// { //// do //// { //// if(Interlocked.CompareExchange( ref m_lock, 1, 0 ) == 0) //// { //// bLockTaken = true; //// //// try //// { //// status = DeleteTimerNative( notifyObject.SafeWaitHandle ); //// } //// finally //// { //// m_lock = 0; //// } //// } //// //// Thread.SpinWait( 1 ); // yield to processor //// } //// while(!bLockTaken); //// GC.SuppressFinalize( this ); //// } //// //// return status; //// } //// //// [ReliabilityContract( Consistency.WillNotCorruptState, Cer.MayFail )] //// public void Dispose() //// { //// bool bLockTaken = false; //// //// RuntimeHelpers.PrepareConstrainedRegions(); //// try //// { //// } //// finally //// { //// do //// { //// if(Interlocked.CompareExchange( ref m_lock, 1, 0 ) == 0) //// { //// bLockTaken = true; //// //// try //// { //// DeleteTimerNative( null ); //// } //// finally //// { //// m_lock = 0; //// } //// } //// //// Thread.SpinWait( 1 ); // yield to processor //// } //// while(!bLockTaken); //// GC.SuppressFinalize( this ); //// } //// } //// //// [ResourceExposure( ResourceScope.None )] //// [MethodImpl( MethodImplOptions.InternalCall )] //// private extern void AddTimerNative( Object state , //// UInt32 dueTime , //// UInt32 period , //// ref StackCrawlMark stackMark ); //// //// [ResourceExposure( ResourceScope.None )] //// [MethodImpl( MethodImplOptions.InternalCall )] //// private extern bool ChangeTimerNative( UInt32 dueTime, UInt32 period ); //// //// [ResourceExposure( ResourceScope.None )] //// [MethodImpl( MethodImplOptions.InternalCall )] //// private extern bool DeleteTimerNative( SafeHandle notifyObject ); //// ////} [HostProtection( Synchronization = true, ExternalThreading = true )] public sealed class Timer : MarshalByRefObject, IDisposable { //// private const UInt32 MAX_SUPPORTED_TIMEOUT = (uint)0xfffffffe; //// //// private TimerBase timerBase; [MethodImpl( MethodImplOptions.InternalCall )] public extern Timer( TimerCallback callback , Object state , int dueTime , int period ); //// { //// if(dueTime < -1) //// { //// throw new ArgumentOutOfRangeException( "dueTime", Environment.GetResourceString( "ArgumentOutOfRange_NeedNonNegOrNegative1" ) ); //// } //// //// if(period < -1) //// { //// throw new ArgumentOutOfRangeException( "period", Environment.GetResourceString( "ArgumentOutOfRange_NeedNonNegOrNegative1" ) ); //// } //// //// StackCrawlMark stackMark = StackCrawlMark.LookForMyCaller; //// //// TimerSetup( callback, state, (UInt32)dueTime, (UInt32)period, ref stackMark ); //// } [MethodImpl( MethodImplOptions.InternalCall )] public extern Timer( TimerCallback callback , Object state , TimeSpan dueTime , TimeSpan period ); //// { //// long dueTm = (long)dueTime.TotalMilliseconds; //// if(dueTm < -1) //// { //// throw new ArgumentOutOfRangeException( "dueTm", Environment.GetResourceString( "ArgumentOutOfRange_NeedNonNegOrNegative1" ) ); //// } //// if(dueTm > MAX_SUPPORTED_TIMEOUT) //// { //// throw new ArgumentOutOfRangeException( "dueTm", Environment.GetResourceString( "ArgumentOutOfRange_TimeoutTooLarge" ) ); //// } //// //// long periodTm = (long)period.TotalMilliseconds; //// if(periodTm < -1) //// { //// throw new ArgumentOutOfRangeException( "periodTm", Environment.GetResourceString( "ArgumentOutOfRange_NeedNonNegOrNegative1" ) ); //// } //// if(periodTm > MAX_SUPPORTED_TIMEOUT) //// { //// throw new ArgumentOutOfRangeException( "periodTm", Environment.GetResourceString( "ArgumentOutOfRange_PeriodTooLarge" ) ); //// } //// //// StackCrawlMark stackMark = StackCrawlMark.LookForMyCaller; //// //// TimerSetup( callback, state, (UInt32)dueTm, (UInt32)periodTm, ref stackMark ); //// } //// [CLSCompliant( false )] //// public Timer( TimerCallback callback, //// Object state , //// UInt32 dueTime , //// UInt32 period ) //// { //// StackCrawlMark stackMark = StackCrawlMark.LookForMyCaller; //// //// TimerSetup( callback, state, dueTime, period, ref stackMark ); //// } //// //// public Timer( TimerCallback callback, //// Object state , //// long dueTime , //// long period ) //// { //// if(dueTime < -1) //// { //// throw new ArgumentOutOfRangeException( "dueTime", Environment.GetResourceString( "ArgumentOutOfRange_NeedNonNegOrNegative1" ) ); //// } //// //// if(period < -1) //// { //// throw new ArgumentOutOfRangeException( "period", Environment.GetResourceString( "ArgumentOutOfRange_NeedNonNegOrNegative1" ) ); //// } //// //// if(dueTime > MAX_SUPPORTED_TIMEOUT) //// { //// throw new ArgumentOutOfRangeException( "dueTime", Environment.GetResourceString( "ArgumentOutOfRange_TimeoutTooLarge" ) ); //// } //// //// if(period > MAX_SUPPORTED_TIMEOUT) //// { //// throw new ArgumentOutOfRangeException( "period", Environment.GetResourceString( "ArgumentOutOfRange_PeriodTooLarge" ) ); //// } //// //// StackCrawlMark stackMark = StackCrawlMark.LookForMyCaller; //// //// TimerSetup( callback, state, (UInt32)dueTime, (UInt32)period, ref stackMark ); //// } [MethodImpl( MethodImplOptions.InternalCall )] public extern Timer( TimerCallback callback ); //// { //// int dueTime = -1; // we want timer to be registered, but not activated. Requires caller to call //// int period = -1; // Change after a timer instance is created. This is to avoid the potential //// // for a timer to be fired before the returned value is assigned to the variable, //// // potentially causing the callback to reference a bogus value (if passing the timer to the callback). //// //// StackCrawlMark stackMark = StackCrawlMark.LookForMyCaller; //// //// TimerSetup( callback, this, (UInt32)dueTime, (UInt32)period, ref stackMark ); //// } //// //// private void TimerSetup( TimerCallback callback , //// Object state , //// UInt32 dueTime , //// UInt32 period , //// ref StackCrawlMark stackMark ) //// { //// timerBase = new TimerBase(); //// //// timerBase.AddTimer( callback, state, (UInt32)dueTime, (UInt32)period, ref stackMark ); //// } [MethodImpl( MethodImplOptions.InternalCall )] public extern bool Change( int dueTime, int period ); //// { //// if(dueTime < -1) //// { //// throw new ArgumentOutOfRangeException( "dueTime", Environment.GetResourceString( "ArgumentOutOfRange_NeedNonNegOrNegative1" ) ); //// } //// //// if(period < -1) //// { //// throw new ArgumentOutOfRangeException( "period", Environment.GetResourceString( "ArgumentOutOfRange_NeedNonNegOrNegative1" ) ); //// } //// //// return timerBase.ChangeTimer( (UInt32)dueTime, (UInt32)period ); //// } [MethodImpl( MethodImplOptions.InternalCall )] public extern bool Change( TimeSpan dueTime, TimeSpan period ); //// { //// return Change( (long)dueTime.TotalMilliseconds, (long)period.TotalMilliseconds ); //// } //// //// [CLSCompliant( false )] //// public bool Change( UInt32 dueTime, UInt32 period ) //// { //// return timerBase.ChangeTimer( dueTime, period ); //// } [MethodImpl( MethodImplOptions.InternalCall )] public extern bool Change( long dueTime, long period ); //// { //// if(dueTime < -1) //// { //// throw new ArgumentOutOfRangeException( "dueTime", Environment.GetResourceString( "ArgumentOutOfRange_NeedNonNegOrNegative1" ) ); //// } //// //// if(period < -1) //// { //// throw new ArgumentOutOfRangeException( "period", Environment.GetResourceString( "ArgumentOutOfRange_NeedNonNegOrNegative1" ) ); //// } //// //// if(dueTime > MAX_SUPPORTED_TIMEOUT) //// { //// throw new ArgumentOutOfRangeException( "dueTime", Environment.GetResourceString( "ArgumentOutOfRange_TimeoutTooLarge" ) ); //// } //// //// if(period > MAX_SUPPORTED_TIMEOUT) //// { //// throw new ArgumentOutOfRangeException( "period", Environment.GetResourceString( "ArgumentOutOfRange_PeriodTooLarge" ) ); //// } //// //// return timerBase.ChangeTimer( (UInt32)dueTime, (UInt32)period ); //// } //// //// public bool Dispose( WaitHandle notifyObject ) //// { //// if(notifyObject == null) //// { //// throw new ArgumentNullException( "notifyObject" ); //// } //// //// return timerBase.Dispose( notifyObject ); //// } [MethodImpl( MethodImplOptions.InternalCall )] public extern void Dispose(); //// { //// timerBase.Dispose(); //// } } } ================================================ FILE: Zelig/Zelig/RunTime/Framework/mscorlib/System/Threading/Volatile.cs ================================================ // Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. // using System; using System.Runtime.InteropServices; using System.Runtime.Versioning; using System.Runtime.ConstrainedExecution; using System.Runtime.CompilerServices; using System.Runtime; using System.Security; namespace System.Threading { #if DISABLED_FOR_LLILUM // // Methods for accessing memory with volatile semantics. These are preferred over Thread.VolatileRead // and Thread.VolatileWrite, as these are implemented more efficiently. // // (We cannot change the implementations of Thread.VolatileRead/VolatileWrite without breaking code // that relies on their overly-strong ordering guarantees.) // // The actual implementations of these methods are typically supplied by the VM at JIT-time, because C# does // not allow us to express a volatile read/write from/to a byref arg. // See getILIntrinsicImplementationForVolatile() in jitinterface.cpp. // public static class Volatile { //// [ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)] public static bool Read(ref bool location) { // // The VM will replace this with a more efficient implementation. // var value = location; Thread.MemoryBarrier(); return value; } //// [ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)] [CLSCompliant(false)] public static sbyte Read(ref sbyte location) { // // The VM will replace this with a more efficient implementation. // var value = location; Thread.MemoryBarrier(); return value; } //// [ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)] public static byte Read(ref byte location) { // // The VM will replace this with a more efficient implementation. // var value = location; Thread.MemoryBarrier(); return value; } //// [ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)] public static short Read(ref short location) { // // The VM will replace this with a more efficient implementation. // var value = location; Thread.MemoryBarrier(); return value; } //// [ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)] [CLSCompliant(false)] public static ushort Read(ref ushort location) { // // The VM will replace this with a more efficient implementation. // var value = location; Thread.MemoryBarrier(); return value; } //// [ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)] public static int Read(ref int location) { // // The VM will replace this with a more efficient implementation. // var value = location; Thread.MemoryBarrier(); return value; } //// [ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)] [CLSCompliant(false)] public static uint Read(ref uint location) { // // The VM will replace this with a more efficient implementation. // var value = location; Thread.MemoryBarrier(); return value; } //// [ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)] public static long Read(ref long location) { // // On 32-bit machines, we use this implementation, since an ordinary volatile read // would not be atomic. // // On 64-bit machines, the VM will replace this with a more efficient implementation. // return Interlocked.CompareExchange(ref location, 0, 0); } //// [ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)] [CLSCompliant(false)] [SecuritySafeCritical] // contains unsafe code public static ulong Read(ref ulong location) { unsafe { // // There is no overload of Interlocked.Exchange that accepts a ulong. So we have // to do some pointer tricks to pass our arguments to the overload that takes a long. // fixed (ulong* pLocation = &location) { return (ulong)Interlocked.CompareExchange(ref *(long*)pLocation, 0, 0); } } } //// [ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)] public static IntPtr Read(ref IntPtr location) { // // The VM will replace this with a more efficient implementation. // var value = location; Thread.MemoryBarrier(); return value; } //// [ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)] [CLSCompliant(false)] public static UIntPtr Read(ref UIntPtr location) { // // The VM will replace this with a more efficient implementation. // var value = location; Thread.MemoryBarrier(); return value; } //// [ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)] public static float Read(ref float location) { // // The VM will replace this with a more efficient implementation. // var value = location; Thread.MemoryBarrier(); return value; } //// [ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)] public static double Read(ref double location) { // // On 32-bit machines, we use this implementation, since an ordinary volatile read // would not be atomic. // // On 64-bit machines, the VM will replace this with a more efficient implementation. // return Interlocked.CompareExchange(ref location, 0, 0); } //// [ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)] [SecuritySafeCritical] //the intrinsic implementation of this method contains unverifiable code public static T Read(ref T location) where T : class { // // The VM will replace this with a more efficient implementation. // var value = location; Thread.MemoryBarrier(); return value; } //// [ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)] public static void Write(ref bool location, bool value) { // // The VM will replace this with a more efficient implementation. // Thread.MemoryBarrier(); location = value; } //// [ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)] [CLSCompliant(false)] public static void Write(ref sbyte location, sbyte value) { // // The VM will replace this with a more efficient implementation. // Thread.MemoryBarrier(); location = value; } //// [ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)] public static void Write(ref byte location, byte value) { // // The VM will replace this with a more efficient implementation. // Thread.MemoryBarrier(); location = value; } //// [ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)] public static void Write(ref short location, short value) { // // The VM will replace this with a more efficient implementation. // Thread.MemoryBarrier(); location = value; } //// [ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)] [CLSCompliant(false)] public static void Write(ref ushort location, ushort value) { // // The VM will replace this with a more efficient implementation. // Thread.MemoryBarrier(); location = value; } //// [ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)] public static void Write(ref int location, int value) { // // The VM will replace this with a more efficient implementation. // Thread.MemoryBarrier(); location = value; } //// [ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)] [CLSCompliant(false)] public static void Write(ref uint location, uint value) { // // The VM will replace this with a more efficient implementation. // Thread.MemoryBarrier(); location = value; } //// [ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)] public static void Write(ref long location, long value) { // // On 32-bit machines, we use this implementation, since an ordinary volatile write // would not be atomic. // // On 64-bit machines, the VM will replace this with a more efficient implementation. // Interlocked.Exchange(ref location, value); } //// [ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)] [CLSCompliant(false)] [SecuritySafeCritical] // contains unsafe code public static void Write(ref ulong location, ulong value) { // // On 32-bit machines, we use this implementation, since an ordinary volatile write // would not be atomic. // // On 64-bit machines, the VM will replace this with a more efficient implementation. // unsafe { // // There is no overload of Interlocked.Exchange that accepts a ulong. So we have // to do some pointer tricks to pass our arguments to the overload that takes a long. // fixed (ulong* pLocation = &location) { Interlocked.Exchange(ref *(long*)pLocation, (long)value); } } } //// [ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)] public static void Write(ref IntPtr location, IntPtr value) { // // The VM will replace this with a more efficient implementation. // Thread.MemoryBarrier(); location = value; } //// [ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)] [CLSCompliant(false)] public static void Write(ref UIntPtr location, UIntPtr value) { // // The VM will replace this with a more efficient implementation. // Thread.MemoryBarrier(); location = value; } //// [ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)] public static void Write(ref float location, float value) { // // The VM will replace this with a more efficient implementation. // Thread.MemoryBarrier(); location = value; } //// [ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)] public static void Write(ref double location, double value) { // // On 32-bit machines, we use this implementation, since an ordinary volatile write // would not be atomic. // // On 64-bit machines, the VM will replace this with a more efficient implementation. // Interlocked.Exchange(ref location, value); } //// [ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)] [SecuritySafeCritical] //the intrinsic implementation of this method contains unverifiable code public static void Write(ref T location, T value) where T : class { // // The VM will replace this with a more efficient implementation. // Thread.MemoryBarrier(); location = value; } } #endif // DISABLED_FOR_LLILUM } ================================================ FILE: Zelig/Zelig/RunTime/Framework/mscorlib/System/Threading/WaitHandle.cs ================================================ // ==++== // // Copyright (c) Microsoft Corporation. All rights reserved. // // ==--== /*============================================================================= ** ** Class: WaitHandle (this name is NOT definitive) ** ** ** Purpose: Class to represent all synchronization objects in the runtime (that allow multiple wait) ** ** =============================================================================*/ namespace System.Threading { using System; using System.Threading; ////using System.Runtime.Remoting; ////using System.Security.Permissions; using System.Runtime.CompilerServices; ////using Microsoft.Win32.SafeHandles; ////using System.Runtime.Versioning; using System.Runtime.ConstrainedExecution; ////using Win32Native = Microsoft.Win32.Win32Native; public abstract class WaitHandle : MarshalByRefObject, IDisposable { //// public const int WaitTimeout = 0x102; //// //// private const int MAX_WAITHANDLES = 64; //// //// private const int WAIT_OBJECT_0 = 0; //// private const int WAIT_ABANDONED = 0x80; //// private const int WAIT_FAILED = 0x7FFFFFFF; //// private const int ERROR_TOO_MANY_POSTS = 0x12A; //// //// //// protected static readonly IntPtr InvalidHandle = Win32Native.INVALID_HANDLE_VALUE; //// //// ////#pragma warning disable 414 // Field is not used from managed. //// private IntPtr waitHandle; // !!! DO NOT MOVE THIS FIELD. (See defn of WAITHANDLEREF in object.h - has hardcoded access to this field.) ////#pragma warning restore 414 //// //// internal SafeWaitHandle safeWaitHandle; //// //// internal bool hasThreadAffinity; //// //// protected WaitHandle() //// { //// safeWaitHandle = null; //// waitHandle = InvalidHandle; //// hasThreadAffinity = false; //// } //// //// public SafeWaitHandle SafeWaitHandle //// { //// [SecurityPermissionAttribute( SecurityAction.LinkDemand, Flags = SecurityPermissionFlag.UnmanagedCode )] //// [SecurityPermissionAttribute( SecurityAction.InheritanceDemand, Flags = SecurityPermissionFlag.UnmanagedCode )] //// [ResourceExposure( ResourceScope.Machine )] //// [ResourceConsumption( ResourceScope.Machine )] //// [ReliabilityContract( Consistency.WillNotCorruptState, Cer.MayFail )] //// get //// { //// if(safeWaitHandle == null) //// { //// safeWaitHandle = new SafeWaitHandle( InvalidHandle, false ); //// } //// //// return safeWaitHandle; //// } //// //// [SecurityPermissionAttribute( SecurityAction.LinkDemand, Flags = SecurityPermissionFlag.UnmanagedCode )] //// [SecurityPermissionAttribute( SecurityAction.InheritanceDemand, Flags = SecurityPermissionFlag.UnmanagedCode )] //// [ResourceExposure( ResourceScope.Machine )] //// [ResourceConsumption( ResourceScope.Machine )] //// [ReliabilityContract( Consistency.WillNotCorruptState, Cer.Success )] //// set //// { //// // Set safeWaitHandle and waitHandle in a CER so we won't take //// // a thread abort between the statements and leave the wait //// // handle in an invalid state. Note this routine is not thread //// // safe however. //// RuntimeHelpers.PrepareConstrainedRegions(); //// try //// { //// } //// finally //// { //// if(value == null) //// { //// safeWaitHandle = null; //// waitHandle = InvalidHandle; //// } //// else //// { //// safeWaitHandle = value; //// waitHandle = safeWaitHandle.DangerousGetHandle(); //// } //// } //// } //// } //// //// // Assembly-private version that doesn't do a security check. Reduces the //// // number of link-time security checks when reading & writing to a file, //// // and helps avoid a link time check while initializing security (If you //// // call a Serialization method that requires security before security //// // has started up, the link time check will start up security, run //// // serialization code for some security attribute stuff, call into //// // FileStream, which will then call Sethandle, which requires a link time //// // security check.). While security has fixed that problem, we still //// // don't need to do a linktime check here. //// [ResourceExposure( ResourceScope.Machine )] //// [ResourceConsumption( ResourceScope.Machine )] //// internal void SetHandleInternal( SafeWaitHandle handle ) //// { //// safeWaitHandle = handle; //// waitHandle = handle.DangerousGetHandle(); //// } [MethodImpl( MethodImplOptions.InternalCall )] public virtual extern bool WaitOne( int millisecondsTimeout, bool exitContext ); //// { //// if(millisecondsTimeout < Timeout.Infinite) //// { //// throw new ArgumentOutOfRangeException( "millisecondsTimeout", Environment.GetResourceString( "ArgumentOutOfRange_NeedNonNegOrNegative1" ) ); //// } //// //// return WaitOne( (long)millisecondsTimeout, exitContext ); //// } [MethodImpl( MethodImplOptions.InternalCall )] public virtual extern bool WaitOne( TimeSpan timeout, bool exitContext ); //// { //// long tm = (long)timeout.TotalMilliseconds; //// if(Timeout.Infinite > tm || (long)Int32.MaxValue < tm) //// { //// throw new ArgumentOutOfRangeException( "timeout", Environment.GetResourceString( "ArgumentOutOfRange_NeedNonNegOrNegative1" ) ); //// } //// //// return WaitOne( tm, exitContext ); //// } public virtual bool WaitOne() { return WaitOne( Timeout.Infinite, false ); } //// [MethodImpl( MethodImplOptions.InternalCall )] //// private extern bool WaitOne( long timeout, bool exitContext ); //// { //// if(safeWaitHandle == null) //// { //// throw new ObjectDisposedException( null, Environment.GetResourceString( "ObjectDisposed_Generic" ) ); //// } //// //// int ret = WaitOneNative( safeWaitHandle, (uint)timeout, hasThreadAffinity, exitContext ); //// if(ret == WAIT_ABANDONED) //// { //// throw new AbandonedMutexException(); //// } //// //// return (ret != WaitTimeout); //// } //// //// //// [ResourceExposure( ResourceScope.None )] //// [MethodImpl( MethodImplOptions.InternalCall )] //// private static extern int WaitOneNative( SafeWaitHandle waitHandle, uint millisecondsTimeout, bool hasThreadAffinity, bool exitContext ); //// //// /*======================================================================== //// ** Waits for signal from all the objects. //// ** timeout indicates how long to wait before the method returns. //// ** This method will return either when all the object have been pulsed //// ** or timeout milliseonds have elapsed. //// ** If exitContext is true then the synchronization domain for the context //// ** (if in a synchronized context) is exited before the wait and reacquired //// ========================================================================*/ //// //// [ResourceExposure( ResourceScope.None )] //// [MethodImpl( MethodImplOptions.InternalCall )] //// [ReliabilityContract( Consistency.WillNotCorruptState, Cer.MayFail )] //// private static extern int WaitMultiple( WaitHandle[] waitHandles, int millisecondsTimeout, bool exitContext, bool WaitAll ); [MethodImpl( MethodImplOptions.InternalCall )] public static extern bool WaitAll( WaitHandle[] waitHandles, int millisecondsTimeout, bool exitContext ); //// { //// if(waitHandles == null || waitHandles.Length == 0) //// { //// throw new ArgumentNullException( "waitHandles" ); //// } //// //// if(waitHandles.Length > MAX_WAITHANDLES) //// { //// throw new NotSupportedException( Environment.GetResourceString( "NotSupported_MaxWaitHandles" ) ); //// } //// //// if(millisecondsTimeout < -1) //// { //// throw new ArgumentOutOfRangeException( "millisecondsTimeout", Environment.GetResourceString( "ArgumentOutOfRange_NeedNonNegOrNegative1" ) ); //// } //// //// WaitHandle[] internalWaitHandles = new WaitHandle[waitHandles.Length]; //// for(int i = 0; i < waitHandles.Length; i++) //// { //// internalWaitHandles[i] = waitHandles[i]; //// if(internalWaitHandles[i] == null) //// { //// throw new ArgumentNullException( Environment.GetResourceString( "ArgumentNull_ArrayElement" ) ); //// } //// } //// //// int ret = WaitMultiple( internalWaitHandles, millisecondsTimeout, exitContext, true /* waitall*/ ); //// if((WAIT_ABANDONED <= ret) && (WAIT_ABANDONED + internalWaitHandles.Length > ret)) //// { //// //In the case of WaitAll the OS will only provide the //// // information that mutex was abandoned. //// // It won't tell us which one. So we can't set the Index or provide access to the Mutex //// throw new AbandonedMutexException(); //// } //// //// for(int i = 0; i < internalWaitHandles.Length; i++) //// { //// GC.KeepAlive( internalWaitHandles[i] ); //// } //// //// return (ret != WaitTimeout); //// } //// //// public static bool WaitAll( WaitHandle[] waitHandles , //// TimeSpan timeout , //// bool exitContext ) //// { //// long tm = (long)timeout.TotalMilliseconds; //// if(tm < -1 || tm > (long)Int32.MaxValue) //// { //// throw new ArgumentOutOfRangeException( "timeout", Environment.GetResourceString( "ArgumentOutOfRange_NeedNonNegOrNegative1" ) ); //// } //// //// return WaitAll( waitHandles, (int)tm, exitContext ); //// } /*======================================================================== ** Shorthand for WaitAll with timeout = Timeout.Infinite and exitContext = true ========================================================================*/ public static bool WaitAll( WaitHandle[] waitHandles ) { return WaitAll( waitHandles, Timeout.Infinite, true ); } //// /*======================================================================== //// ** Waits for notification from any of the objects. //// ** timeout indicates how long to wait before the method returns. //// ** This method will return either when either one of the object have been //// ** signalled or timeout milliseonds have elapsed. //// ** If exitContext is true then the synchronization domain for the context //// ** (if in a synchronized context) is exited before the wait and reacquired //// ========================================================================*/ //// //// [ReliabilityContract( Consistency.WillNotCorruptState, Cer.MayFail )] [MethodImpl( MethodImplOptions.InternalCall )] public static extern int WaitAny( WaitHandle[] waitHandles, int millisecondsTimeout, bool exitContext ); //// { //// if(waitHandles == null) //// { //// throw new ArgumentNullException( "waitHandles" ); //// } //// //// if(MAX_WAITHANDLES < waitHandles.Length) //// { //// throw new NotSupportedException( Environment.GetResourceString( "NotSupported_MaxWaitHandles" ) ); //// } //// //// if(millisecondsTimeout < -1) //// { //// throw new ArgumentOutOfRangeException( "millisecondsTimeout", Environment.GetResourceString( "ArgumentOutOfRange_NeedNonNegOrNegative1" ) ); //// } //// //// WaitHandle[] internalWaitHandles = new WaitHandle[waitHandles.Length]; //// for(int i = 0; i < waitHandles.Length; i++) //// { //// internalWaitHandles[i] = waitHandles[i]; //// } //// //// int ret = WaitMultiple( internalWaitHandles, millisecondsTimeout, exitContext, false /* waitany*/ ); //// for(int i = 0; i < internalWaitHandles.Length; i++) //// { //// GC.KeepAlive( internalWaitHandles[i] ); //// } //// //// if((WAIT_ABANDONED <= ret) && (WAIT_ABANDONED + internalWaitHandles.Length > ret)) //// { //// int mutexIndex = ret - WAIT_ABANDONED; //// if(0 <= mutexIndex && mutexIndex < internalWaitHandles.Length) //// { //// throw new AbandonedMutexException( mutexIndex, internalWaitHandles[mutexIndex] ); //// } //// else //// { //// throw new AbandonedMutexException(); //// } //// } //// else //// { //// return ret; //// } //// } //// //// [ReliabilityContract( Consistency.WillNotCorruptState, Cer.MayFail )] //// public static int WaitAny( WaitHandle[] waitHandles , //// TimeSpan timeout , //// bool exitContext ) //// { //// long tm = (long)timeout.TotalMilliseconds; //// if(tm < -1 || tm > (long)Int32.MaxValue) //// { //// throw new ArgumentOutOfRangeException( "timeout", Environment.GetResourceString( "ArgumentOutOfRange_NeedNonNegOrNegative1" ) ); //// } //// //// return WaitAny( waitHandles, (int)tm, exitContext ); //// } /*======================================================================== ** Shorthand for WaitAny with timeout = Timeout.Infinite and exitContext = true ========================================================================*/ //// [ReliabilityContract( Consistency.WillNotCorruptState, Cer.MayFail )] public static int WaitAny( WaitHandle[] waitHandles ) { return WaitAny( waitHandles, Timeout.Infinite, true ); } //// /*================================================= //// == //// == SignalAndWait //// == //// ==================================================*/ //// //// [ResourceExposure( ResourceScope.None )] //// [MethodImpl( MethodImplOptions.InternalCall )] //// private static extern int SignalAndWaitOne( SafeWaitHandle waitHandleToSignal , //// SafeWaitHandle waitHandleToWaitOn , //// int millisecondsTimeout, //// bool hasThreadAffinity , //// bool exitContext ); //// //// public static bool SignalAndWait( WaitHandle toSignal , //// WaitHandle toWaitOn ) //// { //// return SignalAndWait( toSignal, toWaitOn, -1, false ); //// } //// //// public static bool SignalAndWait( WaitHandle toSignal , //// WaitHandle toWaitOn , //// TimeSpan timeout , //// bool exitContext ) //// { //// long tm = (long)timeout.TotalMilliseconds; //// if(tm < -1 || tm > (long)Int32.MaxValue) //// { //// throw new ArgumentOutOfRangeException( "timeout", Environment.GetResourceString( "ArgumentOutOfRange_NeedNonNegOrNegative1" ) ); //// } //// //// return SignalAndWait( toSignal, toWaitOn, (int)tm, exitContext ); //// } //// //// public static bool SignalAndWait( WaitHandle toSignal , //// WaitHandle toWaitOn , //// int millisecondsTimeout, //// bool exitContext ) //// { //// if(toSignal == null) //// { //// throw new ArgumentNullException( "toSignal" ); //// } //// //// if(toWaitOn == null) //// { //// throw new ArgumentNullException( "toWaitOn" ); //// } //// //// if(millisecondsTimeout < -1) //// { //// throw new ArgumentOutOfRangeException( "millisecondsTimeout", Environment.GetResourceString( "ArgumentOutOfRange_NeedNonNegOrNegative1" ) ); //// } //// //// int ret = SignalAndWaitOne( toSignal.safeWaitHandle, toWaitOn.safeWaitHandle, millisecondsTimeout, toWaitOn.hasThreadAffinity, exitContext ); //// //// if(ret != WAIT_FAILED && toSignal.hasThreadAffinity) //// { //// Thread.EndCriticalRegion(); //// Thread.EndThreadAffinity(); //// } //// //// if(ret == WAIT_ABANDONED) //// { //// throw new AbandonedMutexException(); //// } //// //// if(ret == ERROR_TOO_MANY_POSTS) //// { //// throw new InvalidOperationException( Environment.GetResourceString( "Threading.WaitHandleTooManyPosts" ) ); //// } //// //// //Object was signaled //// if(ret == WAIT_OBJECT_0) //// { //// return true; //// } //// //// //Timeout //// return false; //// } public virtual void Close() { Dispose( true ); //// GC.nativeSuppressFinalize( this ); } protected virtual void Dispose( bool explicitDisposing ) { //// if(safeWaitHandle != null) //// { //// safeWaitHandle.Close(); //// } } /// void IDisposable.Dispose() { Dispose( true ); //// GC.nativeSuppressFinalize( this ); } } } ================================================ FILE: Zelig/Zelig/RunTime/Framework/mscorlib/System/ThrowHelper.cs ================================================ // ==++== // // Copyright (c) Microsoft Corporation. All rights reserved. // // ==--== namespace System { // This file defines an internal class used to throw exceptions in BCL code. // The main purpose is to reduce code size. // // The old way to throw an exception generates quite a lot IL code and assembly code. // Following is an example: // C# source // throw new ArgumentNullException("key", Environment.GetResourceString("ArgumentNull_Key")); // IL code: // IL_0003: ldstr "key" // IL_0008: ldstr "ArgumentNull_Key" // IL_000d: call string System.Environment::GetResourceString(string) // IL_0012: newobj instance void System.ArgumentNullException::.ctor(string,string) // IL_0017: throw // which is 21bytes in IL. // // So we want to get rid of the ldstr and call to Environment.GetResource in IL. // In order to do that, I created two enums: ExceptionResource, ExceptionArgument to represent the // argument name and resource name in a small integer. The source code will be changed to // ThrowHelper.ThrowArgumentNullException(ExceptionArgument.key, ExceptionResource.ArgumentNull_Key); // // The IL code will be 7 bytes. // IL_0008: ldc.i4.4 // IL_0009: ldc.i4.4 // IL_000a: call void System.ThrowHelper::ThrowArgumentNullException(valuetype System.ExceptionArgument) // IL_000f: ldarg.0 // // This will also reduce the Jitted code size a lot. // // It is very important we do this for generic classes because we can easily generate the same code // multiple times for different instantiation. // // // Jit will generates the code to throw exception at the end of a method, thus we can reduce working // set if the user code will never throw an exception. However Jit doesn't know anything about the // methods in ThrowHelper, so it will not moves the instructions to the end. // This is not a problem for ngened code because we will probably move the code based on profile data(hopefully.) // // For jitted code, it doesn't make much difference. The only advantage of moving the code to the end is to // improve cache locality. This doesn't make much different on newer processor like P4. // using System.Runtime.CompilerServices; using System.Runtime.Serialization; internal static class ThrowHelper { [MethodImpl( MethodImplOptions.NoInlining )] internal static void ThrowArgumentOutOfRangeException() { ThrowHelper.ThrowArgumentOutOfRangeException( ExceptionArgument.index, ExceptionResource.ArgumentOutOfRange_Index ); } internal static void ThrowWrongKeyTypeArgumentException( object key, Type targetType ) { #if EXCEPTION_STRINGS throw new ArgumentException( Environment.GetResourceString( "Arg_WrongType", key, targetType ), "key" ); #else throw new ArgumentException(); #endif } internal static void ThrowWrongValueTypeArgumentException( object value, Type targetType ) { #if EXCEPTION_STRINGS throw new ArgumentException( Environment.GetResourceString( "Arg_WrongType", value, targetType ), "value" ); #else throw new ArgumentException(); #endif } internal static void ThrowKeyNotFoundException() { throw new System.Collections.Generic.KeyNotFoundException(); } internal static void ThrowArgumentException( ExceptionResource resource ) { #if EXCEPTION_STRINGS throw new ArgumentException( Environment.GetResourceString( GetResourceName( resource ) ) ); #else throw new ArgumentException(); #endif } internal static void ThrowArgumentException( ExceptionResource resource, ExceptionArgument argument ) { #if EXCEPTION_STRINGS throw new ArgumentException( Environment.GetResourceString( GetResourceName( resource ) ), GetArgumentName( argument ) ); #else throw new ArgumentException(); #endif } internal static void ThrowArgumentNullException( ExceptionArgument argument ) { #if EXCEPTION_STRINGS throw new ArgumentNullException( GetArgumentName( argument ) ); #else throw new ArgumentNullException(); #endif } internal static void ThrowArgumentOutOfRangeException( ExceptionArgument argument ) { #if EXCEPTION_STRINGS throw new ArgumentOutOfRangeException( GetArgumentName( argument ) ); #else throw new ArgumentOutOfRangeException(); #endif } internal static void ThrowArgumentOutOfRangeException( ExceptionArgument argument, ExceptionResource resource ) { #if EXCEPTION_STRINGS throw new ArgumentOutOfRangeException( GetArgumentName( argument ), Environment.GetResourceString( GetResourceName( resource ) ) ); #else throw new ArgumentOutOfRangeException(); #endif } internal static void ThrowInvalidOperationException( ExceptionResource resource ) { #if EXCEPTION_STRINGS throw new InvalidOperationException( Environment.GetResourceString( GetResourceName( resource ) ) ); #else throw new InvalidOperationException(); #endif } internal static void ThrowSerializationException( ExceptionResource resource ) { #if EXCEPTION_STRINGS throw new SerializationException( Environment.GetResourceString( GetResourceName( resource ) ) ); #else throw new SerializationException(); #endif } //// internal static void ThrowSecurityException( ExceptionResource resource ) //// { //// throw new System.Security.SecurityException( Environment.GetResourceString( GetResourceName( resource ) ) ); //// } internal static void ThrowNotSupportedException( ExceptionResource resource ) { #if EXCEPTION_STRINGS throw new NotSupportedException( Environment.GetResourceString( GetResourceName( resource ) ) ); #else throw new NotSupportedException(); #endif } //// internal static void ThrowUnauthorizedAccessException( ExceptionResource resource ) //// { //// throw new UnauthorizedAccessException( Environment.GetResourceString( GetResourceName( resource ) ) ); //// } //// //// internal static void ThrowObjectDisposedException( string objectName, ExceptionResource resource ) //// { //// throw new ObjectDisposedException( objectName, Environment.GetResourceString( GetResourceName( resource ) ) ); //// } // Allow nulls for reference types and Nullable, but not for value types. internal static void IfNullAndNullsAreIllegalThenThrow( object value, ExceptionArgument argName ) { // Note that default(T) is not equal to null for value types except when T is Nullable. if(value == null && !(default( T ) == null)) { ThrowHelper.ThrowArgumentNullException( argName ); } } // // This function will convert an ExceptionArgument enum value to the argument name string. // internal static string GetArgumentName( ExceptionArgument argument ) { string argumentName = null; switch(argument) { case ExceptionArgument.array: argumentName = "array"; break; case ExceptionArgument.arrayIndex: argumentName = "arrayIndex"; break; case ExceptionArgument.capacity: argumentName = "capacity"; break; case ExceptionArgument.collection: argumentName = "collection"; break; case ExceptionArgument.list: argumentName = "list"; break; case ExceptionArgument.converter: argumentName = "converter"; break; case ExceptionArgument.count: argumentName = "count"; break; case ExceptionArgument.dictionary: argumentName = "dictionary"; break; case ExceptionArgument.dictionaryCreationThreshold: argumentName = "dictionaryCreationThreshold"; break; case ExceptionArgument.index: argumentName = "index"; break; case ExceptionArgument.info: argumentName = "info"; break; case ExceptionArgument.key: argumentName = "key"; break; case ExceptionArgument.match: argumentName = "match"; break; case ExceptionArgument.obj: argumentName = "obj"; break; case ExceptionArgument.queue: argumentName = "queue"; break; case ExceptionArgument.stack: argumentName = "stack"; break; case ExceptionArgument.startIndex: argumentName = "startIndex"; break; case ExceptionArgument.value: argumentName = "value"; break; case ExceptionArgument.name: argumentName = "name"; break; case ExceptionArgument.mode: argumentName = "mode"; break; case ExceptionArgument.item: argumentName = "item"; break; default: BCLDebug.Assert( false, "The enum value is not defined, please checked ExceptionArgumentName Enum." ); return string.Empty; } return argumentName; } // // This function will convert an ExceptionResource enum value to the resource string. // internal static string GetResourceName( ExceptionResource resource ) { string resourceName = null; switch(resource) { case ExceptionResource.Argument_ImplementIComparable: resourceName = "Argument_ImplementIComparable"; break; case ExceptionResource.Argument_AddingDuplicate: resourceName = "Argument_AddingDuplicate"; break; case ExceptionResource.ArgumentOutOfRange_BiggerThanCollection: resourceName = "ArgumentOutOfRange_BiggerThanCollection"; break; case ExceptionResource.ArgumentOutOfRange_Count: resourceName = "ArgumentOutOfRange_Count"; break; case ExceptionResource.ArgumentOutOfRange_Index: resourceName = "ArgumentOutOfRange_Index"; break; case ExceptionResource.ArgumentOutOfRange_InvalidThreshold: resourceName = "ArgumentOutOfRange_InvalidThreshold"; break; case ExceptionResource.ArgumentOutOfRange_ListInsert: resourceName = "ArgumentOutOfRange_ListInsert"; break; case ExceptionResource.ArgumentOutOfRange_NeedNonNegNum: resourceName = "ArgumentOutOfRange_NeedNonNegNum"; break; case ExceptionResource.ArgumentOutOfRange_SmallCapacity: resourceName = "ArgumentOutOfRange_SmallCapacity"; break; case ExceptionResource.Arg_ArrayPlusOffTooSmall: resourceName = "Arg_ArrayPlusOffTooSmall"; break; case ExceptionResource.Arg_RankMultiDimNotSupported: resourceName = "Arg_RankMultiDimNotSupported"; break; case ExceptionResource.Arg_NonZeroLowerBound: resourceName = "Arg_NonZeroLowerBound"; break; case ExceptionResource.Argument_InvalidArrayType: resourceName = "Argument_InvalidArrayType"; break; case ExceptionResource.Argument_InvalidOffLen: resourceName = "Argument_InvalidOffLen"; break; case ExceptionResource.Argument_ItemNotExist: resourceName = "Argument_ItemNotExist"; break; case ExceptionResource.InvalidOperation_CannotRemoveFromStackOrQueue: resourceName = "InvalidOperation_CannotRemoveFromStackOrQueue"; break; case ExceptionResource.InvalidOperation_EmptyQueue: resourceName = "InvalidOperation_EmptyQueue"; break; case ExceptionResource.InvalidOperation_EnumOpCantHappen: resourceName = "InvalidOperation_EnumOpCantHappen"; break; case ExceptionResource.InvalidOperation_EnumFailedVersion: resourceName = "InvalidOperation_EnumFailedVersion"; break; case ExceptionResource.InvalidOperation_EmptyStack: resourceName = "InvalidOperation_EmptyStack"; break; case ExceptionResource.InvalidOperation_EnumNotStarted: resourceName = "InvalidOperation_EnumNotStarted"; break; case ExceptionResource.InvalidOperation_EnumEnded: resourceName = "InvalidOperation_EnumEnded"; break; case ExceptionResource.NotSupported_KeyCollectionSet: resourceName = "NotSupported_KeyCollectionSet"; break; case ExceptionResource.NotSupported_ReadOnlyCollection: resourceName = "NotSupported_ReadOnlyCollection"; break; case ExceptionResource.NotSupported_ValueCollectionSet: resourceName = "NotSupported_ValueCollectionSet"; break; case ExceptionResource.NotSupported_SortedListNestedWrite: resourceName = "NotSupported_SortedListNestedWrite"; break; case ExceptionResource.Serialization_InvalidOnDeser: resourceName = "Serialization_InvalidOnDeser"; break; case ExceptionResource.Serialization_MissingKeys: resourceName = "Serialization_MissingKeys"; break; case ExceptionResource.Serialization_NullKey: resourceName = "Serialization_NullKey"; break; case ExceptionResource.Argument_InvalidType: resourceName = "Argument_InvalidType"; break; case ExceptionResource.Argument_InvalidArgumentForComparison: resourceName = "Argument_InvalidArgumentForComparison"; break; case ExceptionResource.InvalidOperation_NoValue: resourceName = "InvalidOperation_NoValue"; break; case ExceptionResource.InvalidOperation_RegRemoveSubKey: resourceName = "InvalidOperation_RegRemoveSubKey"; break; case ExceptionResource.Arg_RegSubKeyAbsent: resourceName = "Arg_RegSubKeyAbsent"; break; case ExceptionResource.Arg_RegSubKeyValueAbsent: resourceName = "Arg_RegSubKeyValueAbsent"; break; case ExceptionResource.Arg_RegKeyDelHive: resourceName = "Arg_RegKeyDelHive"; break; case ExceptionResource.Security_RegistryPermission: resourceName = "Security_RegistryPermission"; break; case ExceptionResource.Arg_RegSetStrArrNull: resourceName = "Arg_RegSetStrArrNull"; break; case ExceptionResource.Arg_RegSetMismatchedKind: resourceName = "Arg_RegSetMismatchedKind"; break; case ExceptionResource.UnauthorizedAccess_RegistryNoWrite: resourceName = "UnauthorizedAccess_RegistryNoWrite"; break; case ExceptionResource.ObjectDisposed_RegKeyClosed: resourceName = "ObjectDisposed_RegKeyClosed"; break; case ExceptionResource.Arg_RegKeyStrLenBug: resourceName = "Arg_RegKeyStrLenBug"; break; case ExceptionResource.Argument_InvalidRegistryKeyPermissionCheck: resourceName = "Argument_InvalidRegistryKeyPermissionCheck"; break; case ExceptionResource.NotSupported_InComparableType: resourceName = "NotSupported_InComparableType"; break; default: BCLDebug.Assert( false, "The enum value is not defined, please checked ExceptionArgumentName Enum." ); return string.Empty; } return resourceName; } } // // The convention for this enum is using the argument name as the enum name // internal enum ExceptionArgument { obj , dictionary , dictionaryCreationThreshold, array , info , key , collection , list , match , converter , queue , stack , capacity , index , startIndex , value , count , arrayIndex , name , mode , item , } // // The convention for this enum is using the resource name as the enum name // internal enum ExceptionResource { Argument_ImplementIComparable , Argument_InvalidType , Argument_InvalidArgumentForComparison , Argument_InvalidRegistryKeyPermissionCheck , ArgumentOutOfRange_NeedNonNegNum , Arg_ArrayPlusOffTooSmall , Arg_NonZeroLowerBound , Arg_RankMultiDimNotSupported , Arg_RegKeyDelHive , Arg_RegKeyStrLenBug , Arg_RegSetStrArrNull , Arg_RegSetMismatchedKind , Arg_RegSubKeyAbsent , Arg_RegSubKeyValueAbsent , Argument_AddingDuplicate , Serialization_InvalidOnDeser , Serialization_MissingKeys , Serialization_NullKey , Argument_InvalidArrayType , NotSupported_KeyCollectionSet , NotSupported_ValueCollectionSet , ArgumentOutOfRange_SmallCapacity , ArgumentOutOfRange_Index , Argument_InvalidOffLen , Argument_ItemNotExist , ArgumentOutOfRange_Count , ArgumentOutOfRange_InvalidThreshold , ArgumentOutOfRange_ListInsert , NotSupported_ReadOnlyCollection , InvalidOperation_CannotRemoveFromStackOrQueue, InvalidOperation_EmptyQueue , InvalidOperation_EnumOpCantHappen , InvalidOperation_EnumFailedVersion , InvalidOperation_EmptyStack , ArgumentOutOfRange_BiggerThanCollection , InvalidOperation_EnumNotStarted , InvalidOperation_EnumEnded , NotSupported_SortedListNestedWrite , InvalidOperation_NoValue , InvalidOperation_RegRemoveSubKey , Security_RegistryPermission , UnauthorizedAccess_RegistryNoWrite , ObjectDisposed_RegKeyClosed , NotSupported_InComparableType } } ================================================ FILE: Zelig/Zelig/RunTime/Framework/mscorlib/System/TimeSpan.cs ================================================ // ==++== // // Copyright (c) Microsoft Corporation. All rights reserved. // // ==--== namespace System { using System; using System.Runtime.CompilerServices; using System.Text; // TimeSpan represents a duration of time. A TimeSpan can be negative // or positive. // // TimeSpan is internally represented as a number of milliseconds. While // this maps well into units of time such as hours and days, any // periods longer than that aren't representable in a nice fashion. // For instance, a month can be between 28 and 31 days, while a year // can contain 365 or 364 days. A decade can have between 1 and 3 leapyears, // depending on when you map the TimeSpan into the calendar. This is why // we do not provide Years() or Months(). // [Serializable] public struct TimeSpan /*: IComparable, IComparable, IEquatable*/ { public const long TicksPerMillisecond = 10000; public const long TicksPerSecond = TicksPerMillisecond * 1000; public const long TicksPerMinute = TicksPerSecond * 60; public const long TicksPerHour = TicksPerMinute * 60; public const long TicksPerDay = TicksPerHour * 24; private const double MillisecondsPerTick = 1.0 / TicksPerMillisecond; private const double SecondsPerTick = 1.0 / TicksPerSecond; private const double MinutesPerTick = 1.0 / TicksPerMinute; private const double HoursPerTick = 1.0 / TicksPerHour; private const double DaysPerTick = 1.0 / TicksPerDay; private const int MillisPerSecond = 1000; private const int MillisPerMinute = MillisPerSecond * 60; private const int MillisPerHour = MillisPerMinute * 60; private const int MillisPerDay = MillisPerHour * 24; private const long MaxSeconds = Int64.MaxValue / TicksPerSecond; private const long MinSeconds = Int64.MinValue / TicksPerSecond; private const long MaxMilliSeconds = Int64.MaxValue / TicksPerMillisecond; private const long MinMilliSeconds = Int64.MinValue / TicksPerMillisecond; public static readonly TimeSpan Zero = new TimeSpan( 0 ); public static readonly TimeSpan MaxValue = new TimeSpan( Int64.MaxValue ); public static readonly TimeSpan MinValue = new TimeSpan( Int64.MinValue ); // internal so that DateTime doesn't have to call an extra get // method for some arithmetic operations. internal long m_ticks; public TimeSpan( long ticks ) { m_ticks = ticks; } public TimeSpan( int hours, int minutes, int seconds ) { m_ticks = TimeToTicks( hours, minutes, seconds ); } public TimeSpan( int days, int hours, int minutes, int seconds ) : this( days, hours, minutes, seconds, 0 ) { } public TimeSpan( int days, int hours, int minutes, int seconds, int milliseconds ) { Int64 totalMilliSeconds = ((Int64)days * 3600 * 24 + (Int64)hours * 3600 + (Int64)minutes * 60 + seconds) * 1000 + milliseconds; if(totalMilliSeconds > MaxMilliSeconds || totalMilliSeconds < MinMilliSeconds) { #if EXCEPTION_STRINGS throw new ArgumentOutOfRangeException( null, Environment.GetResourceString( "Overflow_TimeSpanTooLong" ) ); #else throw new ArgumentOutOfRangeException(); #endif } m_ticks = (long)totalMilliSeconds * TicksPerMillisecond; } public long Ticks { get { return m_ticks; } } public int Days { get { return (int)(m_ticks / TicksPerDay); } } public int Hours { get { return (int)((m_ticks / TicksPerHour) % 24); } } public int Milliseconds { get { return (int)((m_ticks / TicksPerMillisecond) % 1000); } } public int Minutes { get { return (int)((m_ticks / TicksPerMinute) % 60); } } public int Seconds { get { return (int)((m_ticks / TicksPerSecond) % 60); } } public double TotalDays { get { return ((double)m_ticks) * DaysPerTick; } } public double TotalHours { get { return (double)m_ticks * HoursPerTick; } } public double TotalMilliseconds { get { double temp = (double)m_ticks * MillisecondsPerTick; if(temp > MaxMilliSeconds) { return (double)MaxMilliSeconds; } if(temp < MinMilliSeconds) { return (double)MinMilliSeconds; } return temp; } } public double TotalMinutes { get { return (double)m_ticks * MinutesPerTick; } } public double TotalSeconds { get { return (double)m_ticks * SecondsPerTick; } } public TimeSpan Add( TimeSpan ts ) { long result = m_ticks + ts.m_ticks; // Overflow if signs of operands was identical and result's // sign was opposite. // >> 63 gives the sign bit (either 64 1's or 64 0's). if((m_ticks >> 63 == ts.m_ticks >> 63) && (m_ticks >> 63 != result >> 63)) { #if EXCEPTION_STRINGS throw new OverflowException( Environment.GetResourceString( "Overflow_TimeSpanTooLong" ) ); #else throw new OverflowException(); #endif } return new TimeSpan( result ); } // Compares two TimeSpan values, returning an integer that indicates their // relationship. // public static int Compare( TimeSpan t1, TimeSpan t2 ) { return t1.CompareTo( t2 ); } // Returns a value less than zero if this object public int CompareTo( Object value ) { if(value == null) return 1; if(!(value is TimeSpan)) { #if EXCEPTION_STRINGS throw new ArgumentException( Environment.GetResourceString( "Arg_MustBeTimeSpan" ) ); #else throw new ArgumentException(); #endif } return CompareTo( (TimeSpan)value ); } public int CompareTo( TimeSpan value ) { long t = value.m_ticks; if(m_ticks > t) return 1; if(m_ticks < t) return -1; return 0; } public static TimeSpan FromDays( double value ) { return Interval( value, MillisPerDay ); } public TimeSpan Duration() { if(m_ticks == TimeSpan.MinValue.m_ticks) { #if EXCEPTION_STRINGS throw new OverflowException( Environment.GetResourceString( "Overflow_Duration" ) ); #else throw new OverflowException(); #endif } return new TimeSpan( m_ticks >= 0 ? m_ticks : -m_ticks ); } public override bool Equals( Object obj ) { if(!(obj is TimeSpan)) { return false; } return Equals( (TimeSpan)obj ); } public bool Equals( TimeSpan obj ) { return m_ticks == obj.m_ticks; } public static bool Equals( TimeSpan t1, TimeSpan t2 ) { return t1.Equals( t2 ); } public override int GetHashCode() { return (int)m_ticks ^ (int)(m_ticks >> 32); } public static TimeSpan FromHours( double value ) { return Interval( value, MillisPerHour ); } private static TimeSpan Interval( double value, int scale ) { if(Double.IsNaN( value )) { #if EXCEPTION_STRINGS throw new ArgumentException( Environment.GetResourceString( "Arg_CannotBeNaN" ) ); #else throw new ArgumentException(); #endif } double tmp = value * scale; double millis = tmp + (value >= 0 ? 0.5 : -0.5); if((millis > Int64.MaxValue / TicksPerMillisecond) || (millis < Int64.MinValue / TicksPerMillisecond)) { #if EXCEPTION_STRINGS throw new OverflowException( Environment.GetResourceString( "Overflow_TimeSpanTooLong" ) ); #else throw new OverflowException(); #endif } return new TimeSpan( (long)millis * TicksPerMillisecond ); } public static TimeSpan FromMilliseconds( double value ) { return Interval( value, 1 ); } public static TimeSpan FromMinutes( double value ) { return Interval( value, MillisPerMinute ); } public TimeSpan Negate() { if(m_ticks == TimeSpan.MinValue.m_ticks) { #if EXCEPTION_STRINGS throw new OverflowException( Environment.GetResourceString( "Overflow_NegateTwosCompNum" ) ); #else throw new OverflowException(); #endif } return new TimeSpan( -m_ticks ); } // Constructs a TimeSpan from a string. Leading and trailing white // space characters are allowed. // [MethodImpl( MethodImplOptions.InternalCall )] public static extern TimeSpan Parse( String s ); //// { //// return new TimeSpan( new StringParser().Parse( s ) ); //// } //// //// public static Boolean TryParse( String s, out TimeSpan result ) //// { //// long longResult; //// //// if(new StringParser().TryParse( s, out longResult )) //// { //// result = new TimeSpan( longResult ); //// return true; //// } //// else //// { //// result = TimeSpan.Zero; //// return false; //// } //// } public static TimeSpan FromSeconds( double value ) { return Interval( value, MillisPerSecond ); } public TimeSpan Subtract( TimeSpan ts ) { long result = m_ticks - ts.m_ticks; // Overflow if signs of operands was different and result's // sign was opposite from the first argument's sign. // >> 63 gives the sign bit (either 64 1's or 64 0's). if((m_ticks >> 63 != ts.m_ticks >> 63) && (m_ticks >> 63 != result >> 63)) { #if EXCEPTION_STRINGS throw new OverflowException( Environment.GetResourceString( "Overflow_TimeSpanTooLong" ) ); #else throw new OverflowException(); #endif } return new TimeSpan( result ); } public static TimeSpan FromTicks( long value ) { return new TimeSpan( value ); } internal static long TimeToTicks( int hour, int minute, int second ) { // totalSeconds is bounded by 2^31 * 2^12 + 2^31 * 2^8 + 2^31, // which is less than 2^44, meaning we won't overflow totalSeconds. long totalSeconds = (long)hour * 3600 + (long)minute * 60 + (long)second; if(totalSeconds > MaxSeconds || totalSeconds < MinSeconds) { #if EXCEPTION_STRINGS throw new ArgumentOutOfRangeException( null, Environment.GetResourceString( "Overflow_TimeSpanTooLong" ) ); #else throw new ArgumentOutOfRangeException(); #endif } return totalSeconds * TicksPerSecond; } //// private String IntToString( int n, int digits ) //// { //// return ParseNumbers.IntToString( n, 10, digits, '0', 0 ); //// } public override String ToString() { StringBuilder sb = new StringBuilder(); int day = (int)(m_ticks / TicksPerDay); long time = m_ticks % TicksPerDay; if(m_ticks < 0) { sb.Append( "-" ); day = -day; time = -time; } if(day != 0) { sb.Append( day ); sb.Append( "." ); } sb.AppendFormat( "{0:D2}:{1:D2}:{2:D2}", (int)(time / TicksPerHour % 24), (int)(time / TicksPerMinute % 60), (int)(time / TicksPerSecond % 60) ); int t = (int)(time % TicksPerSecond); if(t != 0) { sb.AppendFormat( ".{0:D7}", t ); } return sb.ToString(); } public static TimeSpan operator -( TimeSpan t ) { if(t.m_ticks == TimeSpan.MinValue.m_ticks) { #if EXCEPTION_STRINGS throw new OverflowException( Environment.GetResourceString( "Overflow_NegateTwosCompNum" ) ); #else throw new OverflowException(); #endif } return new TimeSpan( -t.m_ticks ); } public static TimeSpan operator -( TimeSpan t1, TimeSpan t2 ) { return t1.Subtract( t2 ); } public static TimeSpan operator +( TimeSpan t ) { return t; } public static TimeSpan operator +( TimeSpan t1, TimeSpan t2 ) { return t1.Add( t2 ); } public static bool operator ==( TimeSpan t1, TimeSpan t2 ) { return t1.m_ticks == t2.m_ticks; } public static bool operator !=( TimeSpan t1, TimeSpan t2 ) { return t1.m_ticks != t2.m_ticks; } public static bool operator <( TimeSpan t1, TimeSpan t2 ) { return t1.m_ticks < t2.m_ticks; } public static bool operator <=( TimeSpan t1, TimeSpan t2 ) { return t1.m_ticks <= t2.m_ticks; } public static bool operator >( TimeSpan t1, TimeSpan t2 ) { return t1.m_ticks > t2.m_ticks; } public static bool operator >=( TimeSpan t1, TimeSpan t2 ) { return t1.m_ticks >= t2.m_ticks; } //// private struct StringParser //// { //// private enum ParseError //// { //// Format = 1, //// Overflow = 2, //// OverflowHoursMinutesSeconds = 3, //// ArgumentNull = 4, //// } //// //// private String str; //// private char ch; //// private int pos; //// private int len; //// private ParseError error; //// //// internal void NextChar() //// { //// if(pos < len) pos++; //// //// ch = pos < len ? str[pos] : (char)0; //// } //// //// internal char NextNonDigit() //// { //// for(i = pos; i < len; i++) //// { //// char ch = str[i]; //// //// if(ch < '0' || ch > '9') return ch; //// } //// //// return (char)0; //// } //// //// internal long Parse( String s ) //// { //// long value; //// //// if(TryParse( s, out value )) //// { //// return value; //// } //// else //// { //// switch(error) //// { //// case ParseError.ArgumentNull: //// throw new ArgumentNullException( "s" ); //// //// case ParseError.Format: //// throw new FormatException( Environment.GetResourceString( "Format_InvalidString" ) ); //// //// case ParseError.Overflow: //// throw new OverflowException( Environment.GetResourceString( "Overflow_TimeSpanTooLong" ) ); //// //// case ParseError.OverflowHoursMinutesSeconds: //// throw new OverflowException( Environment.GetResourceString( "Overflow_TimeSpanElementTooLarge" ) ); //// //// default: //// BCLDebug.Assert( false, "Unknown error: " + error.ToString() ); //// return 0; //// } //// } //// } //// //// internal bool TryParse( String s, out long value ) //// { //// value = 0; //// if(s == null) //// { //// error = ParseError.ArgumentNull; //// return false; //// } //// //// str = s; //// len = s.Length; //// pos = -1; //// //// NextChar(); //// SkipBlanks(); //// //// bool negative = false; //// if(ch == '-') //// { //// negative = true; //// NextChar(); //// } //// //// long time; //// //// if(NextNonDigit() == ':') //// { //// if(!ParseTime( out time )) //// { //// return false; //// } //// } //// else //// { //// int days; //// //// if(!ParseInt( (int)(0x7FFFFFFFFFFFFFFFL / TicksPerDay), out days )) //// { //// return false; //// } //// //// time = days * TicksPerDay; //// if(ch == '.') //// { //// NextChar(); //// long remainingTime; //// if(!ParseTime( out remainingTime )) //// { //// return false; //// } //// //// time += remainingTime; //// } //// } //// //// if(negative) //// { //// time = -time; //// // Allow -0 as well //// if(time > 0) //// { //// error = ParseError.Overflow; //// return false; //// } //// } //// else //// { //// if(time < 0) //// { //// error = ParseError.Overflow; //// return false; //// } //// } //// //// SkipBlanks(); //// if(pos < len) //// { //// error = ParseError.Format; //// return false; //// } //// //// value = time; //// return true; //// } //// //// internal bool ParseInt( int max, out int i ) //// { //// i = 0; //// int p = pos; //// while(ch >= '0' && ch <= '9') //// { //// if((i & 0xF0000000) != 0) //// { //// error = ParseError.Overflow; //// return false; //// } //// //// i = i * 10 + ch - '0'; //// if(i < 0) //// { //// error = ParseError.Overflow; //// return false; //// } //// NextChar(); //// } //// //// if(p == pos) //// { //// error = ParseError.Format; //// return false; //// } //// //// if(i > max) //// { //// error = ParseError.Overflow; //// return false; //// } //// //// return true; //// } //// //// internal bool ParseTime( out long time ) //// { //// time = 0; //// //// int unit; //// //// if(!ParseInt( 23, out unit )) //// { //// if(error == ParseError.Overflow) //// { //// error = ParseError.OverflowHoursMinutesSeconds; //// } //// return false; //// } //// //// time = unit * TicksPerHour; //// if(ch != ':') //// { //// error = ParseError.Format; //// return false; //// } //// //// NextChar(); //// if(!ParseInt( 59, out unit )) //// { //// if(error == ParseError.Overflow) //// { //// error = ParseError.OverflowHoursMinutesSeconds; //// } //// return false; //// } //// //// time += unit * TicksPerMinute; //// if(ch == ':') //// { //// NextChar(); //// //// // allow seconds with the leading zero //// if(ch != '.') //// { //// if(!ParseInt( 59, out unit )) //// { //// if(error == ParseError.Overflow) //// { //// error = ParseError.OverflowHoursMinutesSeconds; //// } //// return false; //// } //// time += unit * TicksPerSecond; //// } //// //// if(ch == '.') //// { //// NextChar(); //// int f = (int)TicksPerSecond; //// while(f > 1 && ch >= '0' && ch <= '9') //// { //// f /= 10; //// time += (ch - '0') * f; //// NextChar(); //// } //// } //// } //// //// return true; //// } //// //// internal void SkipBlanks() //// { //// while(ch == ' ' || ch == '\t') NextChar(); //// } //// } } } ================================================ FILE: Zelig/Zelig/RunTime/Framework/mscorlib/System/TimeZone.cs ================================================ // ==++== // // Copyright (c) Microsoft Corporation. All rights reserved. // // ==--== /*============================================================ ** ** Class: TimeZone ** ** ** Purpose: ** This class is used to represent a TimeZone. It ** has methods for converting a DateTime to UTC from local time ** and to local time from UTC and methods for getting the ** standard name and daylight name of the time zone. ** ** The only TimeZone that we support in version 1 is the ** CurrentTimeZone as determined by the system timezone. ** ** ============================================================*/ namespace System { using System; using System.Text; using System.Threading; using System.Collections; using System.Globalization; [Serializable] public abstract class TimeZone { private static TimeZone currentTimeZone = null; // Private object for locking instead of locking on a public type for SQL reliability work. private static Object s_InternalSyncObject; private static Object InternalSyncObject { get { if(s_InternalSyncObject == null) { Object o = new Object(); Interlocked.CompareExchange( ref s_InternalSyncObject, o, null ); } return s_InternalSyncObject; } } protected TimeZone() { } public static TimeZone CurrentTimeZone { get { //Grabbing the cached value is required at the top of this function so that //we don't incur a race condition with the ResetTimeZone method below. TimeZone tz = currentTimeZone; if(tz == null) { lock(InternalSyncObject) { if(currentTimeZone == null) { currentTimeZone = new CurrentSystemTimeZone(); } tz = currentTimeZone; } } return (tz); } } //This method is called by CultureInfo.ClearCachedData in response to control panel //change events. It must be synchronized because otherwise there is a race condition //with the CurrentTimeZone property above. internal static void ResetTimeZone() { if(currentTimeZone != null) { lock(InternalSyncObject) { currentTimeZone = null; } } } public abstract String StandardName { get; } public abstract String DaylightName { get; } public abstract TimeSpan GetUtcOffset( DateTime time ); // // Converts the specified datatime to the Universal time base on the current timezone // public virtual DateTime ToUniversalTime( DateTime time ) { if(time.Kind == DateTimeKind.Utc) { return time; } long tickCount = time.Ticks - GetUtcOffset( time ).Ticks; if(tickCount > DateTime.MaxTicks) { return new DateTime( DateTime.MaxTicks, DateTimeKind.Utc ); } if(tickCount < DateTime.MinTicks) { return new DateTime( DateTime.MinTicks, DateTimeKind.Utc ); } return new DateTime( tickCount, DateTimeKind.Utc ); } // // Convert the specified datetime value from UTC to the local time based on the time zone. // public virtual DateTime ToLocalTime( DateTime time ) { if(time.Kind == DateTimeKind.Local) { return time; } Boolean isAmbiguousLocalDst = false; Int64 offset = ((CurrentSystemTimeZone)(TimeZone.CurrentTimeZone)).GetUtcOffsetFromUniversalTime( time, ref isAmbiguousLocalDst ); return new DateTime( time.Ticks + offset, DateTimeKind.Local, isAmbiguousLocalDst ); } // Return an array of DaylightTime which reflects the daylight saving periods in a particular year. // We currently only support having one DaylightSavingTime per year. // If daylight saving time is not used in this timezone, null will be returned. public abstract DaylightTime GetDaylightChanges( int year ); public virtual bool IsDaylightSavingTime( DateTime time ) { return (IsDaylightSavingTime( time, GetDaylightChanges( time.Year ) )); } // Check if the specified time is in a daylight saving time. Allows the user to // specify the array of Daylight Saving Times. public static bool IsDaylightSavingTime( DateTime time, DaylightTime daylightTimes ) { return CalculateUtcOffset( time, daylightTimes ) != TimeSpan.Zero; } // // NOTENOTE: Implementation detail // In the transition from standard time to daylight saving time, // if we convert local time to Universal time, we can have the // following (take PST as an example): // Local Universal UTC Offset // ----- --------- ---------- // 01:00AM 09:00 -8:00 // 02:00 (=> 03:00) 10:00 -8:00 [This time doesn't actually exist, but it can be created from DateTime] // 03:00 10:00 -7:00 // 04:00 11:00 -7:00 // 05:00 12:00 -7:00 // // So from 02:00 - 02:59:59, we should return the standard offset, instead of the daylight saving offset. // // In the transition from daylight saving time to standard time, // if we convert local time to Universal time, we can have the // following (take PST as an example): // Local Universal UTC Offset // ----- --------- ---------- // 01:00AM 08:00 -7:00 // 02:00 (=> 01:00) 09:00 -8:00 // 02:00 10:00 -8:00 // 03:00 11:00 -8:00 // 04:00 12:00 -8:00 // // So in this case, the 02:00 does exist after the first 2:00 rolls back to 01:00. We don't need to special case this. // But note that there are two 01:00 in the local time. // // And imagine if the daylight saving offset is negative (although this does not exist in real life) // In the transition from standard time to daylight saving time, // if we convert local time to Universal time, we can have the // following (take PST as an example, but the daylight saving offset is -01:00): // Local Universal UTC Offset // ----- --------- ---------- // 01:00AM 09:00 -8:00 // 02:00 (=> 01:00) 10:00 -9:00 // 02:00 11:00 -9:00 // 03:00 12:00 -9:00 // 04:00 13:00 -9:00 // 05:00 14:00 -9:00 // // So in this case, the 02:00 does exist after the first 2:00 rolls back to 01:00. We don't need to special case this. // // In the transition from daylight saving time to standard time, // if we convert local time to Universal time, we can have the // following (take PST as an example, daylight saving offset is -01:00): // // Local Universal UTC Offset // ----- --------- ---------- // 01:00AM 10:00 -9:00 // 02:00 (=> 03:00) 11:00 -9:00 // 03:00 11:00 -8:00 // 04:00 12:00 -8:00 // 05:00 13:00 -8:00 // 06:00 14:00 -8:00 // // So from 02:00 - 02:59:59, we should return the daylight saving offset, instead of the standard offset. // internal static TimeSpan CalculateUtcOffset( DateTime time, DaylightTime daylightTimes ) { if(daylightTimes == null) { return TimeSpan.Zero; } DateTimeKind kind = time.Kind; if(kind == DateTimeKind.Utc) { return TimeSpan.Zero; } DateTime startTime; DateTime endTime; // startTime and endTime represent the period from either the start of DST to the end and includes the // potentially overlapped times startTime = daylightTimes.Start + daylightTimes.Delta; endTime = daylightTimes.End; // For normal time zones, the ambiguous hour is the last hour of daylight saving when you wind the // clock back. It is theoretically possible to have a positive delta, (which would really be daylight // reduction time), where you would have to wind the clock back in the begnning. DateTime ambiguousStart; DateTime ambiguousEnd; if(daylightTimes.Delta.Ticks > 0) { ambiguousStart = endTime - daylightTimes.Delta; ambiguousEnd = endTime; } else { ambiguousStart = startTime; ambiguousEnd = startTime - daylightTimes.Delta; } Boolean isDst = false; if(startTime > endTime) { // In southern hemisphere, the daylight saving time starts later in the year, and ends in the beginning of next year. // Note, the summer in the southern hemisphere begins late in the year. if(time >= startTime || time < endTime) { isDst = true; } } else if(time >= startTime && time < endTime) { // In northern hemisphere, the daylight saving time starts in the middle of the year. isDst = true; } // If this date was previously converted from a UTC date and we were able to detect that the local // DateTime would be ambiguous, this data is stored in the DateTime to resolve this ambiguity. if(isDst && time >= ambiguousStart && time < ambiguousEnd) { isDst = time.IsAmbiguousDaylightSavingTime(); } if(isDst) { return daylightTimes.Delta; } return TimeSpan.Zero; } } } ================================================ FILE: Zelig/Zelig/RunTime/Framework/mscorlib/System/TimeoutException.cs ================================================ // ==++== // // Copyright (c) Microsoft Corporation. All rights reserved. // // ==--== /*============================================================================= ** ** Class: TimeoutException ** ** ** Purpose: Exception class for Timeout ** ** =============================================================================*/ namespace System { using System.Runtime.Serialization; [Serializable()] ////[System.Runtime.InteropServices.ComVisible( true )] public class TimeoutException : SystemException { #if EXCEPTION_STRINGS public TimeoutException() : base( Environment.GetResourceString( "Arg_TimeoutException" ) ) #else public TimeoutException() #endif { //// SetErrorCode( __HResults.COR_E_TIMEOUT ); } public TimeoutException( String message ) : base( message ) { //// SetErrorCode( __HResults.COR_E_TIMEOUT ); } public TimeoutException( String message, Exception innerException ) : base( message, innerException ) { //// SetErrorCode( __HResults.COR_E_TIMEOUT ); } // //This constructor is required for serialization. // //// protected TimeoutException( SerializationInfo info, StreamingContext context ) : base( info, context ) //// { //// } } } ================================================ FILE: Zelig/Zelig/RunTime/Framework/mscorlib/System/Type.cs ================================================ // ==++== // // Copyright (c) Microsoft Corporation. All rights reserved. // // ==--== //////////////////////////////////////////////////////////////////////////////// namespace System { using System; using System.Reflection; ////using System.Reflection.Emit; ////using System.Reflection.Cache; using System.Threading; ////using System.Runtime.Remoting; using System.Runtime.InteropServices; using System.Runtime.CompilerServices; ////using System.Security.Permissions; using System.Collections.Generic; ////using System.Runtime.Versioning; using CultureInfo = System.Globalization.CultureInfo; ////using SignatureHelper = System.Reflection.Emit.SignatureHelper; ////using StackCrawlMark = System.Threading.StackCrawlMark; ////using DebuggerStepThroughAttribute = System.Diagnostics.DebuggerStepThroughAttribute; [Serializable] public abstract class Type : MemberInfo, IReflect { //// public static readonly MemberFilter FilterAttribute; //// public static readonly MemberFilter FilterName; //// public static readonly MemberFilter FilterNameIgnoreCase; //// //// public static readonly Object Missing = System.Reflection.Missing.Value; //// //// public static readonly char Delimiter = '.'; //// //// // EmptyTypes is used to indicate that we are looking for someting without any parameters. //// public readonly static Type[] EmptyTypes = new Type[0]; //// //// // The Default binder. We create a single one and expose that. //// private static object defaultBinder; // private convenience data private const BindingFlags DefaultLookup = BindingFlags.Instance | BindingFlags.Static | BindingFlags.Public; //// private static readonly Type valueType = typeof( System.ValueType ); //// private static readonly Type enumType = typeof( System.Enum ); //// private static readonly Type objectType = typeof( System.Object ); //// // Because the current compiler doesn't support static delegates //// // the _Filters object is an object that we create to contain all of //// // the filters. //// //private static final Type _filterClass = new RuntimeType(); //// static Type() //// { //// __Filters _filterClass = new __Filters(); //// //// FilterAttribute = new MemberFilter( _filterClass.FilterAttribute ); //// FilterName = new MemberFilter( _filterClass.FilterName ); //// FilterNameIgnoreCase = new MemberFilter( _filterClass.FilterIgnoreCase ); //// } // Prevent from begin created, and allow subclass // to create. protected Type() { } // MemberInfo Methods.... // The Member type Field. public override MemberTypes MemberType { get { return System.Reflection.MemberTypes.TypeInfo; } } //// // Return the class that declared this Field. //// public override Type DeclaringType //// { //// get //// { //// return this; //// } //// } public virtual MethodBase DeclaringMethod { get { return null; } } //// // Return the class that was used to obtain this field. //// public override Type ReflectedType //// { //// get //// { //// return this; //// } //// } //////////////////////////////////////////////////////////////////////////////// // This is a static method that returns a Class based upon the name of the class // (this name needs to be fully qualified with the package name and is // case-sensitive by default). //// // this method is required so Object.GetType is not made virtual by the compiler // public new Type GetType() { return base.GetType(); } //// public static Type GetType( String typeName, bool throwOnError, bool ignoreCase ) //// { //// unsafe //// { //// StackCrawlMark stackMark = StackCrawlMark.LookForMyCaller; //// //// return RuntimeType.PrivateGetType( typeName, throwOnError, ignoreCase, ref stackMark ); //// } //// } //// //// public static Type GetType( String typeName, bool throwOnError ) //// { //// unsafe //// { //// StackCrawlMark stackMark = StackCrawlMark.LookForMyCaller; //// //// return RuntimeType.PrivateGetType( typeName, throwOnError, false, ref stackMark ); //// } //// } //// //// public static Type GetType( String typeName ) //// { //// unsafe //// { //// StackCrawlMark stackMark = StackCrawlMark.LookForMyCaller; //// //// return RuntimeType.PrivateGetType( typeName, false, false, ref stackMark ); //// } //// } //// //// public static Type ReflectionOnlyGetType( String typeName, bool throwIfNotFound, bool ignoreCase ) //// { //// unsafe //// { //// StackCrawlMark stackMark = StackCrawlMark.LookForMyCaller; //// //// return RuntimeType.PrivateGetType( typeName, throwIfNotFound, ignoreCase, true /*reflectionOnly*/, ref stackMark ); //// } //// } //// //// public virtual Type MakePointerType() //// { //// throw new NotSupportedException(); //// } //// //// public virtual StructLayoutAttribute StructLayoutAttribute //// { //// get //// { //// throw new NotSupportedException(); //// } //// } //// //// public virtual Type MakeByRefType() //// { //// throw new NotSupportedException(); //// } //// //// public virtual Type MakeArrayType() //// { //// throw new NotSupportedException(); //// } //// //// public virtual Type MakeArrayType( int rank ) //// { //// throw new NotSupportedException(); //// } //// //// internal string SigToString() //// { //// Type elementType = this; //// //// while(elementType.HasElementType) //// { //// elementType = elementType.GetElementType(); //// } //// //// if(elementType.IsNested) //// { //// return Name; //// } //// //// string sigToString = ToString(); //// //// if(elementType.IsPrimitive || //// elementType == typeof( void ) || //// elementType == typeof( TypedReference )) //// { //// sigToString = sigToString.Substring( @"System.".Length ); //// } //// //// return sigToString; //// } //// //// // GetTypeCode //// // This method will return a TypeCode for the passed //// // type. //// public static TypeCode GetTypeCode( Type type ) //// { //// if(type == null) //// { //// return TypeCode.Empty; //// } //// //// return type.GetTypeCodeInternal(); //// } //// //// internal virtual TypeCode GetTypeCodeInternal() //// { //// Type type = this; //// if(type is SymbolType) //// { //// return TypeCode.Object; //// } //// //// if(type is TypeBuilder) //// { //// TypeBuilder typeBuilder = (TypeBuilder)type; //// if(typeBuilder.IsEnum == false) //// { //// return TypeCode.Object; //// } //// //// // if it is an Enum, just let the underlyingSystemType do the work //// } //// //// if(type != type.UnderlyingSystemType) //// { //// return Type.GetTypeCode( type.UnderlyingSystemType ); //// } //// //// return TypeCode.Object; //// } //// //// // Property representing the GUID associated with a class. //// public abstract Guid GUID //// { //// get; //// } //// //// // Return the Default binder used by the system. //// static public Binder DefaultBinder //// { //// get //// { //// // Allocate the default binder if it hasn't been allocated yet. //// if(defaultBinder == null) //// { //// CreateBinder(); //// } //// //// return defaultBinder as Binder; //// } //// } //// //// static private void CreateBinder() //// { //// if(defaultBinder == null) //// { //// object binder = new DefaultBinder(); //// //// Interlocked.CompareExchange( ref defaultBinder, binder, null ); //// } //// } //// //// // Description of the Binding Process. //// // We must invoke a method that is accessable and for which the provided //// // parameters have the most specific match. A method may be called if //// // 1. The number of parameters in the method declaration equals the number of //// // arguments provided to the invocation //// // 2. The type of each argument can be converted by the binder to the //// // type of the type of the parameter. //// // //// // The binder will find all of the matching methods. These method are found based //// // upon the type of binding requested (MethodInvoke, Get/Set Properties). The set //// // of methods is filtered by the name, number of arguments and a set of search modifiers //// // defined in the Binder. //// // //// // After the method is selected, it will be invoked. Accessability is checked //// // at that point. The search may be control which set of methods are searched based //// // upon the accessibility attribute associated with the method. //// // //// // The BindToMethod method is responsible for selecting the method to be invoked. //// // For the default binder, the most specific method will be selected. //// // //// // This will invoke a specific member... public abstract Object InvokeMember( String name , BindingFlags invokeAttr , Binder binder , Object target , Object[] args , ParameterModifier[] modifiers , CultureInfo culture , String[] namedParameters ); //// [DebuggerStepThroughAttribute] //// [Diagnostics.DebuggerHidden] //// public Object InvokeMember( String name , //// BindingFlags invokeAttr, //// Binder binder , //// Object target , //// Object[] args , //// CultureInfo culture ) //// { //// return InvokeMember( name, invokeAttr, binder, target, args, null, culture, null ); //// } //// //// [DebuggerStepThroughAttribute] //// [Diagnostics.DebuggerHidden] //// public Object InvokeMember( String name , //// BindingFlags invokeAttr, //// Binder binder , //// Object target , //// Object[] args ) //// { //// return InvokeMember( name, invokeAttr, binder, target, args, null, null, null ); //// } //// //// //// // Module Property associated with a class. //// public new abstract Module Module //// { //// get; //// } // Assembly Property associated with a class. public abstract Assembly Assembly { get; } // A class handle is a unique integer value associated with // each class. The handle is unique during the process life time. public abstract RuntimeTypeHandle TypeHandle { get; } //// internal virtual RuntimeTypeHandle GetTypeHandleInternal() //// { //// return TypeHandle; //// } //// [ResourceExposure( ResourceScope.None )] [MethodImpl( MethodImplOptions.InternalCall )] public static extern RuntimeTypeHandle GetTypeHandle( Object o ); // Given a class handle, this will return the class for that handle. //// [ResourceExposure( ResourceScope.None )] [MethodImpl( MethodImplOptions.InternalCall )] public static extern Type GetTypeFromHandle( RuntimeTypeHandle handle ); // Return the fully qualified name. The name does contain the namespace. public abstract String FullName { get; } // Return the name space of the class. public abstract String Namespace { get; } public abstract String AssemblyQualifiedName { get; } //// public virtual int GetArrayRank() //// { //// throw new NotSupportedException( Environment.GetResourceString( "NotSupported_SubclassOverride" ) ); //// } // Returns the base class for a class. If this is an interface or has // no base class null is returned. Object is the only Type that does not // have a base class. public abstract Type BaseType { get; } //// // GetConstructor //// // This method will search for the specified constructor. For constructors, //// // unlike everything else, the default is to not look for static methods. The //// // reason is that we don't typically expose the class initializer. //// public ConstructorInfo GetConstructor( BindingFlags bindingAttr , //// Binder binder , //// CallingConventions callConvention, //// Type[] types , //// ParameterModifier[] modifiers ) //// { //// // Must provide some types (Type[0] for nothing) //// if(types == null) //// { //// throw new ArgumentNullException( "types" ); //// } //// for(int i = 0; i < types.Length; i++) //// { //// if(types[i] == null) //// { //// throw new ArgumentNullException( "types" ); //// } //// } //// //// return GetConstructorImpl( bindingAttr, binder, callConvention, types, modifiers ); //// } //// //// public ConstructorInfo GetConstructor( BindingFlags bindingAttr, //// Binder binder , //// Type[] types , //// ParameterModifier[] modifiers ) //// { //// return GetConstructorImpl( bindingAttr, binder, CallingConventions.Any, types, modifiers ); //// } //// //// public ConstructorInfo GetConstructor( Type[] types ) //// { //// // The arguments are checked in the called version of GetConstructor. //// return GetConstructor( BindingFlags.Public | BindingFlags.Instance, null, types, null ); //// } //// //// abstract protected ConstructorInfo GetConstructorImpl( BindingFlags bindingAttr , //// Binder binder , //// CallingConventions callConvention, //// Type[] types , //// ParameterModifier[] modifiers ); //// //// // GetConstructors() //// // This routine will return an array of all constructors supported by the class. //// // Unlike everything else, the default is to not look for static methods. The //// // reason is that we don't typically expose the class initializer. //// public ConstructorInfo[] GetConstructors() //// { //// return GetConstructors( BindingFlags.Public | BindingFlags.Instance ); //// } //// //// public abstract ConstructorInfo[] GetConstructors( BindingFlags bindingAttr ); //// //// public ConstructorInfo TypeInitializer //// { //// get //// { //// return GetConstructorImpl( BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic, //// null, //// CallingConventions.Any, //// Type.EmptyTypes, //// null ); //// } //// } // Return a method based upon the passed criteria. The name of the method // must be provided, and exception is thrown if it is not. The bindingAttr // parameter indicates if non-public methods should be searched. The types // array indicates the types of the parameters being looked for. public MethodInfo GetMethod( String name , BindingFlags bindingAttr , Binder binder , CallingConventions callConvention, Type[] types , ParameterModifier[] modifiers ) { if(name == null) { #if EXCEPTION_STRINGS throw new ArgumentNullException( "name" ); #else throw new ArgumentNullException(); #endif } if(types == null) { #if EXCEPTION_STRINGS throw new ArgumentNullException( "types" ); #else throw new ArgumentNullException(); #endif } for(int i = 0; i < types.Length; i++) { if(types[i] == null) { #if EXCEPTION_STRINGS throw new ArgumentNullException( "types" ); #else throw new ArgumentNullException(); #endif } } return GetMethodImpl( name, bindingAttr, binder, callConvention, types, modifiers ); } public MethodInfo GetMethod( String name , BindingFlags bindingAttr, Binder binder , Type[] types , ParameterModifier[] modifiers ) { return GetMethod( name, bindingAttr, binder, CallingConventions.Any, types, modifiers ); } //// public MethodInfo GetMethod( String name, Type[] types, ParameterModifier[] modifiers ) //// { //// return GetMethod( name, Type.DefaultLookup, null, CallingConventions.Any, types, modifiers ); //// } //// //// public MethodInfo GetMethod( String name, Type[] types ) //// { //// return GetMethod( name, Type.DefaultLookup, null, CallingConventions.Any, types, null ); //// } public MethodInfo GetMethod( String name, BindingFlags bindingAttr ) { if(name == null) { #if EXCEPTION_STRINGS throw new ArgumentNullException( "name" ); #else throw new ArgumentNullException(); #endif } return GetMethodImpl( name, bindingAttr, null, CallingConventions.Any, null, null ); } //// public MethodInfo GetMethod( String name ) //// { //// return GetMethod( name, Type.DefaultLookup ); //// } protected abstract MethodInfo GetMethodImpl( String name , BindingFlags bindingAttr , Binder binder , CallingConventions callConvention, Type[] types , ParameterModifier[] modifiers ); // GetMethods // This routine will return all the methods implemented by the class public MethodInfo[] GetMethods() { return GetMethods( Type.DefaultLookup ); } public abstract MethodInfo[] GetMethods( BindingFlags bindingAttr ); // GetField // Get Field will return a specific field based upon name public FieldInfo GetField( String name ) { return GetField( name, Type.DefaultLookup ); } public abstract FieldInfo GetField( String name, BindingFlags bindingAttr ); // GetFields // Get fields will return a full array of fields implemented by a class public FieldInfo[] GetFields() { return GetFields( Type.DefaultLookup ); } public abstract FieldInfo[] GetFields( BindingFlags bindingAttr ); //// // GetInterface //// // This method will return an interface (as a class) based upon //// // the passed in name. //// public Type GetInterface( String name ) //// { //// return GetInterface( name, false ); //// } //// //// public abstract Type GetInterface( String name, bool ignoreCase ); //// //// // GetInterfaces //// // This method will return all of the interfaces implemented by a //// // class //// public abstract Type[] GetInterfaces(); //// //// // FindInterfaces //// // This method will filter the interfaces supported the class //// public virtual Type[] FindInterfaces( TypeFilter filter, Object filterCriteria ) //// { //// if(filter == null) //// { //// throw new ArgumentNullException( "filter" ); //// } //// //// Type[] c = GetInterfaces(); //// int cnt = 0; //// //// for(int i = 0; i < c.Length; i++) //// { //// if(!filter( c[i], filterCriteria )) //// { //// c[i] = null; //// } //// else //// { //// cnt++; //// } //// } //// //// if(cnt == c.Length) //// { //// return c; //// } //// //// Type[] ret = new Type[cnt]; //// //// cnt = 0; //// //// for(int i = 0; i < c.Length; i++) //// { //// if(c[i] != null) //// { //// ret[cnt++] = c[i]; //// } //// } //// //// return ret; //// } //// //// // GetEvent //// // This method will return a event by name if it is found. //// // null is returned if the event is not found //// public EventInfo GetEvent( String name ) //// { //// return GetEvent( name, Type.DefaultLookup ); //// } //// //// public abstract EventInfo GetEvent( String name, BindingFlags bindingAttr ); //// //// // GetEvents //// // This method will return an array of EventInfo. If there are not Events //// // an empty array will be returned. //// //// virtual public EventInfo[] GetEvents() //// { //// return GetEvents( Type.DefaultLookup ); //// } //// //// public abstract EventInfo[] GetEvents( BindingFlags bindingAttr ); // Return a property based upon the passed criteria. The nameof the // parameter must be provided. public PropertyInfo GetProperty( String name , BindingFlags bindingAttr, Binder binder , Type returnType , Type[] types , ParameterModifier[] modifiers ) { if(name == null) { #if EXCEPTION_STRINGS throw new ArgumentNullException( "name" ); #else throw new ArgumentNullException(); #endif } if(types == null) { #if EXCEPTION_STRINGS throw new ArgumentNullException( "types" ); #else throw new ArgumentNullException(); #endif } return GetPropertyImpl( name, bindingAttr, binder, returnType, types, modifiers ); } //// public PropertyInfo GetProperty( String name , //// Type returnType , //// Type[] types , //// ParameterModifier[] modifiers ) //// { //// return GetProperty( name, Type.DefaultLookup, null, returnType, types, modifiers ); //// } public PropertyInfo GetProperty( String name, BindingFlags bindingAttr ) { if(name == null) { #if EXCEPTION_STRINGS throw new ArgumentNullException( "name" ); #else throw new ArgumentNullException(); #endif } return GetPropertyImpl( name, bindingAttr, null, null, null, null ); } //// public PropertyInfo GetProperty( String name, Type returnType, Type[] types ) //// { //// return GetProperty( name, Type.DefaultLookup, null, returnType, types, null ); //// } //// //// public PropertyInfo GetProperty( String name, Type[] types ) //// { //// return GetProperty( name, Type.DefaultLookup, null, null, types, null ); //// } //// //// public PropertyInfo GetProperty( String name, Type returnType ) //// { //// if(name == null) //// { //// throw new ArgumentNullException( "name" ); //// } //// //// if(returnType == null) //// { //// throw new ArgumentNullException( "returnType" ); //// } //// //// return GetPropertyImpl( name, Type.DefaultLookup, null, returnType, null, null ); //// } //// //// public PropertyInfo GetProperty( String name ) //// { //// if(name == null) //// { //// throw new ArgumentNullException( "name" ); //// } //// //// return GetPropertyImpl( name, Type.DefaultLookup, null, null, null, null ); //// } protected abstract PropertyInfo GetPropertyImpl( String name , BindingFlags bindingAttr, Binder binder , Type returnType , Type[] types , ParameterModifier[] modifiers ); // GetProperties // This method will return an array of all of the properties defined // for a Type. public PropertyInfo[] GetProperties() { return GetProperties( Type.DefaultLookup ); } public abstract PropertyInfo[] GetProperties( BindingFlags bindingAttr ); //// // GetNestedTypes() //// // This set of method will return any nested types that are found inside //// // of the type. //// public Type[] GetNestedTypes() //// { //// return GetNestedTypes( Type.DefaultLookup ); //// } //// //// public abstract Type[] GetNestedTypes( BindingFlags bindingAttr ); //// //// // GetNestedType() //// public Type GetNestedType( String name ) //// { //// return GetNestedType( name, Type.DefaultLookup ); //// } //// //// public abstract Type GetNestedType( String name, BindingFlags bindingAttr ); //// //// // GetMember //// // This method will return all of the members which match the specified string //// // passed into the method //// public MemberInfo[] GetMember( String name ) //// { //// return GetMember( name, Type.DefaultLookup ); //// } //// public virtual MemberInfo[] GetMember( String name, BindingFlags bindingAttr ) { return GetMember( name, MemberTypes.All, bindingAttr ); } public virtual MemberInfo[] GetMember( String name, MemberTypes type, BindingFlags bindingAttr ) { #if EXCEPTION_STRINGS throw new NotSupportedException( Environment.GetResourceString( "NotSupported_SubclassOverride" ) ); #else throw new NotSupportedException(); #endif } // GetMembers // This will return a Member array of all of the members of a class public MemberInfo[] GetMembers() { return GetMembers( Type.DefaultLookup ); } public abstract MemberInfo[] GetMembers( BindingFlags bindingAttr ); //// // GetDefaultMembers //// // This will return a MemberInfo that has been marked with the //// // DefaultMemberAttribute //// public virtual MemberInfo[] GetDefaultMembers() //// { //// // See if we have cached the default member name //// String defaultMember = (String)this.Cache[CacheObjType.DefaultMember]; //// //// if(defaultMember == null) //// { //// // Get all of the custom attributes //// //// CustomAttributeData attr = null; //// //// for(Type t = this; t != null; t = t.BaseType) //// { //// IList attrs = CustomAttributeData.GetCustomAttributes( t ); //// for(int i = 0; i < attrs.Count; i++) //// { //// if(attrs[i].Constructor.DeclaringType == typeof( DefaultMemberAttribute )) //// { //// attr = attrs[i]; //// break; //// } //// } //// //// if(attr != null) //// { //// break; //// } //// } //// //// if(attr == null) //// { //// return new MemberInfo[0]; //// } //// //// defaultMember = attr.ConstructorArguments[0].Value as string; //// this.Cache[CacheObjType.DefaultMember] = defaultMember; //// } //// //// MemberInfo[] members = GetMember( defaultMember ); //// if(members == null) //// { //// members = new MemberInfo[0]; //// } //// return members; //// } //// //// internal virtual String GetDefaultMemberName() //// { //// // See if we have cached the default member name //// String defaultMember = (String)this.Cache[CacheObjType.DefaultMember]; //// //// if(defaultMember == null) //// { //// Object[] attrs = GetCustomAttributes( typeof( DefaultMemberAttribute ), true ); //// //// // We assume that there is only one DefaultMemberAttribute (Allow multiple = false) //// if(attrs.Length > 1) //// { //// throw new ExecutionEngineException( Environment.GetResourceString( "ExecutionEngine_InvalidAttribute" ) ); //// } //// //// if(attrs.Length == 0) //// { //// return null; //// } //// //// defaultMember = ((DefaultMemberAttribute)attrs[0]).MemberName; //// //// this.Cache[CacheObjType.DefaultMember] = defaultMember; //// } //// //// return defaultMember; //// } //// //// // FindMembers //// // This will return a filtered version of the member information //// public virtual MemberInfo[] FindMembers( MemberTypes memberType, BindingFlags bindingAttr, MemberFilter filter, Object filterCriteria ) //// { //// // Define the work arrays //// MethodInfo[] m = null; //// ConstructorInfo[] c = null; //// FieldInfo[] f = null; //// PropertyInfo[] p = null; //// EventInfo[] e = null; //// Type[] t = null; //// //// int i = 0; //// int cnt = 0; // Total Matchs //// //// // Check the methods //// if((memberType & System.Reflection.MemberTypes.Method) != 0) //// { //// m = GetMethods( bindingAttr ); //// if(filter != null) //// { //// for(i = 0; i < m.Length; i++) //// { //// if(!filter( m[i], filterCriteria )) //// { //// m[i] = null; //// } //// else //// { //// cnt++; //// } //// } //// } //// else //// { //// cnt += m.Length; //// } //// } //// //// // Check the constructors //// if((memberType & System.Reflection.MemberTypes.Constructor) != 0) //// { //// c = GetConstructors( bindingAttr ); //// if(filter != null) //// { //// for(i = 0; i < c.Length; i++) //// { //// if(!filter( c[i], filterCriteria )) //// { //// c[i] = null; //// } //// else //// { //// cnt++; //// } //// } //// } //// else //// { //// cnt += c.Length; //// } //// } //// //// // Check the fields //// if((memberType & System.Reflection.MemberTypes.Field) != 0) //// { //// f = GetFields( bindingAttr ); //// if(filter != null) //// { //// for(i = 0; i < f.Length; i++) //// { //// if(!filter( f[i], filterCriteria )) //// { //// f[i] = null; //// } //// else //// { //// cnt++; //// } //// } //// } //// else //// { //// cnt += f.Length; //// } //// } //// //// // Check the Properties //// if((memberType & System.Reflection.MemberTypes.Property) != 0) //// { //// p = GetProperties( bindingAttr ); //// if(filter != null) //// { //// for(i = 0; i < p.Length; i++) //// { //// if(!filter( p[i], filterCriteria )) //// { //// p[i] = null; //// } //// else //// { //// cnt++; //// } //// } //// } //// else //// { //// cnt += p.Length; //// } //// } //// //// // Check the Events //// if((memberType & System.Reflection.MemberTypes.Event) != 0) //// { //// e = GetEvents(); //// if(filter != null) //// { //// for(i = 0; i < e.Length; i++) //// { //// if(!filter( e[i], filterCriteria )) //// { //// e[i] = null; //// } //// else //// { //// cnt++; //// } //// } //// } //// else //// { //// cnt += e.Length; //// } //// } //// //// // Check the Types //// if((memberType & System.Reflection.MemberTypes.NestedType) != 0) //// { //// t = GetNestedTypes( bindingAttr ); //// if(filter != null) //// { //// for(i = 0; i < t.Length; i++) //// { //// if(!filter( t[i], filterCriteria )) //// { //// t[i] = null; //// } //// else //// { //// cnt++; //// } //// } //// } //// else //// { //// cnt += t.Length; //// } //// } //// //// // Allocate the Member Info //// MemberInfo[] ret = new MemberInfo[cnt]; //// //// // Copy the Methods //// cnt = 0; //// if(m != null) //// { //// for(i = 0; i < m.Length; i++) //// { //// if(m[i] != null) //// { //// ret[cnt++] = m[i]; //// } //// } //// } //// //// // Copy the Constructors //// if(c != null) //// { //// for(i = 0; i < c.Length; i++) //// { //// if(c[i] != null) //// { //// ret[cnt++] = c[i]; //// } //// } //// } //// //// // Copy the Fields //// if(f != null) //// { //// for(i = 0; i < f.Length; i++) //// { //// if(f[i] != null) //// { //// ret[cnt++] = f[i]; //// } //// } //// } //// //// // Copy the Properties //// if(p != null) //// { //// for(i = 0; i < p.Length; i++) //// { //// if(p[i] != null) //// { //// ret[cnt++] = p[i]; //// } //// } //// } //// //// // Copy the Events //// if(e != null) //// { //// for(i = 0; i < e.Length; i++) //// { //// if(e[i] != null) //// { //// ret[cnt++] = e[i]; //// } //// } //// } //// //// // Copy the Types //// if(t != null) //// { //// for(i = 0; i < t.Length; i++) //// { //// if(t[i] != null) //// { //// ret[cnt++] = t[i]; //// } //// } //// } //// //// return ret; //// } //// //// //////////////////////////////////////////////////////////////////////////////// //// // //// // Attributes //// // //// // The attributes are all treated as read-only properties on a class. Most of //// // these boolean properties have flag values defined in this class and act like //// // a bit mask of attributes. There are also a set of boolean properties that //// // relate to the classes relationship to other classes and to the state of the //// // class inside the runtime. //// // //// //////////////////////////////////////////////////////////////////////////////// //// //// public bool IsNested //// { //// get //// { //// return DeclaringType != null; //// } //// } //// //// // The attribute property on the Type. //// public TypeAttributes Attributes //// { //// get //// { //// return GetAttributeFlagsImpl(); //// } //// } //// //// public virtual GenericParameterAttributes GenericParameterAttributes //// { //// get //// { //// throw new NotSupportedException(); //// } //// } //// //// public bool IsVisible //// { //// get //// { //// return GetTypeHandleInternal().IsVisible(); //// } //// } //// //// public bool IsNotPublic //// { //// get //// { //// return ((GetAttributeFlagsImpl() & TypeAttributes.VisibilityMask) == TypeAttributes.NotPublic); //// } //// } //// //// public bool IsPublic //// { //// get //// { //// return ((GetAttributeFlagsImpl() & TypeAttributes.VisibilityMask) == TypeAttributes.Public); //// } //// } //// //// public bool IsNestedPublic //// { //// get //// { //// return ((GetAttributeFlagsImpl() & TypeAttributes.VisibilityMask) == TypeAttributes.NestedPublic); //// } //// } //// //// public bool IsNestedPrivate //// { //// get //// { //// return ((GetAttributeFlagsImpl() & TypeAttributes.VisibilityMask) == TypeAttributes.NestedPrivate); //// } //// } //// //// public bool IsNestedFamily //// { //// get //// { //// return ((GetAttributeFlagsImpl() & TypeAttributes.VisibilityMask) == TypeAttributes.NestedFamily); //// } //// } //// //// public bool IsNestedAssembly //// { //// get //// { //// return ((GetAttributeFlagsImpl() & TypeAttributes.VisibilityMask) == TypeAttributes.NestedAssembly); //// } //// } //// //// public bool IsNestedFamANDAssem //// { //// get //// { //// return ((GetAttributeFlagsImpl() & TypeAttributes.VisibilityMask) == TypeAttributes.NestedFamANDAssem); //// } //// } //// //// public bool IsNestedFamORAssem //// { //// get //// { //// return ((GetAttributeFlagsImpl() & TypeAttributes.VisibilityMask) == TypeAttributes.NestedFamORAssem); //// } //// } //// //// public bool IsAutoLayout //// { //// get //// { //// return ((GetAttributeFlagsImpl() & TypeAttributes.LayoutMask) == TypeAttributes.AutoLayout); //// } //// } //// //// public bool IsLayoutSequential //// { //// get //// { //// return ((GetAttributeFlagsImpl() & TypeAttributes.LayoutMask) == TypeAttributes.SequentialLayout); //// } //// } //// //// public bool IsExplicitLayout //// { //// get //// { //// return ((GetAttributeFlagsImpl() & TypeAttributes.LayoutMask) == TypeAttributes.ExplicitLayout); //// } //// } public extern bool IsClass { [MethodImpl( MethodImplOptions.InternalCall )] get; //// { //// return ((GetAttributeFlagsImpl() & TypeAttributes.ClassSemanticsMask) == TypeAttributes.Class && !IsSubclassOf( Type.valueType )); //// } } //// public bool IsInterface //// { //// get //// { //// return ((GetAttributeFlagsImpl() & TypeAttributes.ClassSemanticsMask) == TypeAttributes.Interface); //// } //// } public extern bool IsValueType { [MethodImpl( MethodImplOptions.InternalCall )] get; //// { //// return IsValueTypeImpl(); //// } } //// public bool IsAbstract //// { //// get //// { //// return ((GetAttributeFlagsImpl() & TypeAttributes.Abstract) != 0); //// } //// } //// //// public bool IsSealed //// { //// get //// { //// return ((GetAttributeFlagsImpl() & TypeAttributes.Sealed) != 0); //// } //// } //// //// public bool IsEnum //// { //// get //// { //// return IsSubclassOf( Type.enumType ); //// } //// } //// //// public bool IsSpecialName //// { //// get //// { //// return ((GetAttributeFlagsImpl() & TypeAttributes.SpecialName) != 0); //// } //// } //// //// public bool IsImport //// { //// get //// { //// return ((GetAttributeFlagsImpl() & TypeAttributes.Import) != 0); //// } //// } //// //// public bool IsSerializable //// { //// get //// { //// return (((GetAttributeFlagsImpl() & TypeAttributes.Serializable) != 0) || (this.QuickSerializationCastCheck())); //// } //// } //// //// private bool QuickSerializationCastCheck() //// { //// Type c = this.UnderlyingSystemType; //// while(c != null) //// { //// if(c == typeof( Enum ) || c == typeof( Delegate )) //// { //// return true; //// } //// //// c = c.BaseType; //// } //// //// return false; //// } //// //// public bool IsAnsiClass //// { //// get //// { //// return ((GetAttributeFlagsImpl() & TypeAttributes.StringFormatMask) == TypeAttributes.AnsiClass); //// } //// } //// //// public bool IsUnicodeClass //// { //// get //// { //// return ((GetAttributeFlagsImpl() & TypeAttributes.StringFormatMask) == TypeAttributes.UnicodeClass); //// } //// } //// //// public bool IsAutoClass //// { //// get //// { //// return ((GetAttributeFlagsImpl() & TypeAttributes.StringFormatMask) == TypeAttributes.AutoClass); //// } //// } //// //// // These are not backed up by attributes. Instead they are implemented //// // based internally. //// public bool IsArray //// { //// get //// { //// return IsArrayImpl(); //// } //// } //// //// internal virtual bool IsSzArray //// { //// get //// { //// return false; //// } //// } //// //// public virtual bool IsGenericType //// { //// get //// { //// return false; //// } //// } //// //// public virtual bool IsGenericTypeDefinition //// { //// get //// { //// return false; //// } //// } //// //// public virtual bool IsGenericParameter //// { //// get //// { //// return false; //// } //// } //// //// public virtual int GenericParameterPosition //// { //// get //// { //// throw new InvalidOperationException( Environment.GetResourceString( "Arg_NotGenericParameter" ) ); //// } //// } //// //// public virtual bool ContainsGenericParameters //// { //// get //// { //// if(HasElementType) //// { //// return GetRootElementType().ContainsGenericParameters; //// } //// //// if(IsGenericParameter) //// { //// return true; //// } //// //// if(!IsGenericType) //// { //// return false; //// } //// //// Type[] genericArguments = GetGenericArguments(); //// for(int i = 0; i < genericArguments.Length; i++) //// { //// if(genericArguments[i].ContainsGenericParameters) //// { //// return true; //// } //// } //// //// return false; //// } //// } //// //// public virtual Type[] GetGenericParameterConstraints() //// { //// if(!IsGenericParameter) //// { //// throw new InvalidOperationException( Environment.GetResourceString( "Arg_NotGenericParameter" ) ); //// } //// //// throw new InvalidOperationException(); //// } public extern bool IsByRef { [MethodImpl( MethodImplOptions.InternalCall )] get; //// { //// return IsByRefImpl(); //// } } //// public bool IsPointer //// { //// get //// { //// return IsPointerImpl(); //// } //// } //// //// public bool IsPrimitive //// { //// get //// { //// return IsPrimitiveImpl(); //// } //// } //// //// public bool IsCOMObject //// { //// get //// { //// return IsCOMObjectImpl(); //// } //// } //// //// public bool HasElementType //// { //// get //// { //// return HasElementTypeImpl(); //// } //// } //// //// public bool IsContextful //// { //// get //// { //// return IsContextfulImpl(); //// } //// } //// //// public bool IsMarshalByRef //// { //// get //// { //// return IsMarshalByRefImpl(); //// } //// } //// //// internal bool HasProxyAttribute //// { //// get //// { //// return HasProxyAttributeImpl(); //// } //// } //// //// // Protected routine to determine if this class represents a value class //// protected virtual bool IsValueTypeImpl() //// { //// Type type = this; //// if(type == Type.valueType || type == Type.enumType) //// { //// return false; //// } //// //// return IsSubclassOf( Type.valueType ); //// } //// //// // Protected routine to get the attributes. //// protected abstract TypeAttributes GetAttributeFlagsImpl(); //// //// // Protected routine to determine if this class represents an Array //// protected abstract bool IsArrayImpl(); //// //// // Protected routine to determine if this class is a ByRef //// protected abstract bool IsByRefImpl(); //// //// // Protected routine to determine if this class is a Pointer //// protected abstract bool IsPointerImpl(); //// //// // Protected routine to determine if this class represents a primitive type //// protected abstract bool IsPrimitiveImpl(); //// //// // Protected routine to determine if this class represents a COM object //// protected abstract bool IsCOMObjectImpl(); //// //// public virtual Type MakeGenericType( params Type[] typeArguments ) { throw new NotSupportedException( Environment.GetResourceString( "NotSupported_SubclassOverride" ) ); } //// //// //// // Protected routine to determine if this class is contextful //// protected virtual bool IsContextfulImpl() //// { //// return typeof( ContextBoundObject ).IsAssignableFrom( this ); //// } //// //// //// // Protected routine to determine if this class is marshaled by ref //// protected virtual bool IsMarshalByRefImpl() //// { //// return typeof( MarshalByRefObject ).IsAssignableFrom( this ); //// } //// //// internal virtual bool HasProxyAttributeImpl() //// { //// // We will override this in RuntimeType //// return false; //// } public abstract Type GetElementType(); //// public virtual Type[] GetGenericArguments() //// { //// throw new NotSupportedException( Environment.GetResourceString( "NotSupported_SubclassOverride" ) ); //// } //// //// public virtual Type GetGenericTypeDefinition() //// { //// throw new NotSupportedException( Environment.GetResourceString( "NotSupported_SubclassOverride" ) ); //// } //// //// protected abstract bool HasElementTypeImpl(); //// //// internal virtual Type GetRootElementType() //// { //// Type rootElementType = this; //// //// while(rootElementType.HasElementType) //// { //// rootElementType = rootElementType.GetElementType(); //// } //// //// return rootElementType; //// } // Return the underlying Type that represents the IReflect Object. For expando object, // this is the (Object) IReflectInstance.GetType(). For Type object it is this. public abstract Type UnderlyingSystemType { get; } // Returns true of this class is a true subclass of c. Everything // else returns false. If this class and c are the same class false is // returned. // public virtual bool IsSubclassOf( Type c ) { Type p = this; if(p == c) { return false; } while(p != null) { if(p == c) { return true; } p = p.BaseType; } return false; } // Returns true if the object passed is assignable to an instance of this class. // Everything else returns false. // public virtual bool IsInstanceOfType( Object o ) { if(this is RuntimeType) { return IsInstanceOfType( o ); } if(o == null) { return false; } //// // For transparent proxies we have to check the cast //// // using remoting specific facilities. //// if(RemotingServices.IsTransparentProxy( o )) //// { //// return (null != RemotingServices.CheckCast( o, this )); //// } //// //// if(IsInterface && o.GetType().IsCOMObject) //// { //// if(this is RuntimeType) //// { //// return ((RuntimeType)this).SupportsInterface( o ); //// } //// } return IsAssignableFrom( o.GetType() ); } // Returns true if an instance of Type c may be assigned // to an instance of this class. Return false otherwise. // public virtual bool IsAssignableFrom( Type c ) { throw new NotImplementedException(); //// if(c == null) //// { //// return false; //// } //// //// try //// { //// RuntimeType fromType = c .UnderlyingSystemType as RuntimeType; //// RuntimeType toType = this.UnderlyingSystemType as RuntimeType; //// //// if(fromType == null || toType == null) //// { //// ////// special case for TypeBuilder //// ////TypeBuilder fromTypeBuilder = c as TypeBuilder; //// ////if(fromTypeBuilder == null) //// ////{ //// //// return false; //// ////} //// //// //// ////if(TypeBuilder.IsTypeEqual( this, c )) //// ////{ //// //// return true; //// ////} //// //// //// ////// If fromTypeBuilder is a subclass of this class, then c can be cast to this type. //// ////if(fromTypeBuilder.IsSubclassOf( this )) //// ////{ //// //// return true; //// ////} //// //// //// ////if(this.IsInterface == false) //// ////{ //// //// return false; //// ////} //// //// //// ////// now is This type a base type on one of the interface impl? //// ////Type[] interfaces = fromTypeBuilder.GetInterfaces(); //// ////for(int i = 0; i < interfaces.Length; i++) //// ////{ //// //// if(TypeBuilder.IsTypeEqual( interfaces[i], this )) //// //// { //// //// return true; //// //// } //// //// if(interfaces[i].IsSubclassOf( this )) //// //// { //// //// return true; //// //// } //// ////} //// return false; //// } //// //// bool b = RuntimeType.CanCastTo( fromType, toType ); //// //// return b; //// } //// catch(ArgumentException) //// { //// } //// //// // Check for interfaces //// if(IsInterface) //// { //// Type[] ifaces = c.GetInterfaces(); //// for(int i = 0; i < ifaces.Length; i++) //// { //// if(this == ifaces[i]) //// { //// return true; //// } //// } //// } //// else if(IsGenericParameter) //// { //// Type[] constraints = GetGenericParameterConstraints(); //// for(int i = 0; i < constraints.Length; i++) //// { //// if(!constraints[i].IsAssignableFrom( c )) //// { //// return false; //// } //// } //// //// return true; //// } //// // Check the class relationship //// else //// { //// while(c != null) //// { //// if(c == this) //// { //// return true; //// } //// //// c = c.BaseType; //// } //// } //// //// return false; } //// // ToString //// // Print the String Representation of the Type //// public override String ToString() //// { //// return "Type: " + Name; //// } // This method will return an array of classes based upon the array of // types. public static Type[] GetTypeArray( Object[] args ) { if(args == null) { #if EXCEPTION_STRINGS throw new ArgumentNullException( "args" ); #else throw new ArgumentNullException(); #endif } Type[] cls = new Type[args.Length]; for(int i = 0; i < cls.Length; i++) { if(args[i] == null) { throw new ArgumentNullException(); } cls[i] = args[i].GetType(); } return cls; } public override bool Equals( Object o ) { if(!(o is Type)) { return false; } return Equals( (Type)o ); } public bool Equals( Type o ) { if(o == null) { return false; } //Miguel: switched to pointer comparison to avoid circular ref //return (this.UnderlyingSystemType == o.UnderlyingSystemType); return ( object )this == ( object )o; } public override int GetHashCode() { Type SystemType = UnderlyingSystemType; if(SystemType != this) { return SystemType.GetHashCode(); } return base.GetHashCode(); } public static bool operator ==( Type left, Type right ) { if ((object)left == null) { return (object)right == null; } if ((object)right == null) { return false; } return left.Equals( right ); } public static bool operator !=( Type left, Type right ) { return !(left == right); } //// // GetInterfaceMap //// // This method will return an interface mapping for the interface //// // requested. It will throw an argument exception if the Type doesn't //// // implemenet the interface. //// public virtual InterfaceMapping GetInterfaceMap( Type interfaceType ) //// { //// throw new NotSupportedException( Environment.GetResourceString( "NotSupported_SubclassOverride" ) ); //// } //// //// // This is used by Remoting //// internal static Type ResolveTypeRelativeTo( String typeName, int offset, int count, Type serverType ) //// { //// Type type = ResolveTypeRelativeToBaseTypes( typeName, offset, count, serverType ); //// if(type == null) //// { //// // compare against the interface list //// // GetInterfaces() returns a complete list of interfaces this type supports //// Type[] interfaces = serverType.GetInterfaces(); //// foreach(Type iface in interfaces) //// { //// String ifaceTypeName = iface.FullName; //// if(ifaceTypeName.Length == count) //// { //// if(String.CompareOrdinal( typeName, offset, ifaceTypeName, 0, count ) == 0) //// { //// return iface; //// } //// } //// } //// } //// //// return type; //// } // ResolveTypeRelativeTo //// //// // This is used by Remoting //// internal static Type ResolveTypeRelativeToBaseTypes( String typeName, int offset, int count, Type serverType ) //// { //// // typeName is excepted to contain the full type name //// // offset is the start of the full type name within typeName //// // count us the number of characters in the full type name //// // serverType is the type of the server object //// //// if((typeName == null) || (serverType == null)) //// { //// return null; //// } //// //// String serverTypeName = serverType.FullName; //// if(serverTypeName.Length == count) //// { //// if(String.CompareOrdinal( typeName, offset, serverTypeName, 0, count ) == 0) //// { //// return serverType; //// } //// } //// //// return ResolveTypeRelativeToBaseTypes( typeName, offset, count, serverType.BaseType ); //// } // ResolveTypeRelativeTo } } ================================================ FILE: Zelig/Zelig/RunTime/Framework/mscorlib/System/TypeCode.cs ================================================ // ==++== // // Copyright (c) Microsoft Corporation. All rights reserved. // // ==--== // The TypeCode enum represents the type code of an object. To obtain the // TypeCode for a given object, use the Value.GetTypeCode() method. The // TypeCode.Empty value represents a null object reference. The TypeCode.Object // value represents an object that doesn't implement the IValue interface. The // TypeCode.DBNull value represents the database null, which is distinct and // different from a null reference. The other type codes represent values that // use the given simple type encoding. // // Note that when an object has a given TypeCode, there is no guarantee that // the object is an instance of the corresponding System.XXX value class. For // example, an object with the type code TypeCode.Int32 might actually be an // instance of a nullable 32-bit integer type (with a value that isn't the // database null). // // There are no type codes for "Missing", "Error", "IDispatch", and "IUnknown". // These types of values are instead represented as classes. When the type code // of an object is TypeCode.Object, a further instance-of check can be used to // determine if the object is one of these values. namespace System { [Serializable] public enum TypeCode { Empty = 0, // Null reference Object = 1, // Instance that isn't a value DBNull = 2, // Database null value Boolean = 3, // Boolean Char = 4, // Unicode character SByte = 5, // Signed 8-bit integer Byte = 6, // Unsigned 8-bit integer Int16 = 7, // Signed 16-bit integer UInt16 = 8, // Unsigned 16-bit integer Int32 = 9, // Signed 32-bit integer UInt32 = 10, // Unsigned 32-bit integer Int64 = 11, // Signed 64-bit integer UInt64 = 12, // Unsigned 64-bit integer Single = 13, // IEEE 32-bit float Double = 14, // IEEE 64-bit double Decimal = 15, // Decimal DateTime = 16, // DateTime String = 18, // Unicode character string } } ================================================ FILE: Zelig/Zelig/RunTime/Framework/mscorlib/System/TypedReference.cs ================================================ // ==++== // // Copyright (c) Microsoft Corporation. All rights reserved. // // ==--== //////////////////////////////////////////////////////////////////////////////// // Void // This class represents the void return type //////////////////////////////////////////////////////////////////////////////// namespace System { // TypedReference is basically only ever seen on the call stack, and in param arrays. // These are blob that must be dealt with by the compiler. using System; using System.Reflection; using System.Runtime.CompilerServices; ////using System.Security.Permissions; ////using System.Runtime.Versioning; using CultureInfo = System.Globalization.CultureInfo; using FieldInfo = System.Reflection.FieldInfo; [Microsoft.Zelig.Internals.WellKnownType( "System_TypedReference" )] [CLSCompliant( false )] public struct TypedReference { private IntPtr Value; private IntPtr Type; //// [CLSCompliant( false )] //// [ReflectionPermission( SecurityAction.LinkDemand, MemberAccess = true )] //// public static TypedReference MakeTypedReference( Object target, FieldInfo[] flds ) //// { //// if(target == null) //// { //// throw new ArgumentNullException( "target" ); //// } //// //// if(flds == null) //// { //// throw new ArgumentNullException( "flds" ); //// } //// //// if(flds.Length == 0) //// { //// throw new ArgumentException( Environment.GetResourceString( "Arg_ArrayZeroError" ) ); //// } //// else //// { //// RuntimeFieldHandle[] fields = new RuntimeFieldHandle[flds.Length]; //// //// // For proper handling of Nullable don't change GetType() to something like 'IsAssignableFrom' //// // Currently we can't make a TypedReference to fields of Nullable, which is fine. //// Type targetType = target.GetType(); //// for(int i = 0; i < flds.Length; i++) //// { //// FieldInfo field = flds[i]; //// if(!(field is RuntimeFieldInfo)) //// { //// throw new ArgumentException( Environment.GetResourceString( "Argument_MustBeRuntimeFieldInfo" ) ); //// } //// else if(field.IsInitOnly || field.IsStatic) //// { //// throw new ArgumentException( Environment.GetResourceString( "Argument_TypedReferenceInvalidField" ) ); //// } //// //// if(targetType != field.DeclaringType && !targetType.IsSubclassOf( field.DeclaringType )) //// { //// throw new MissingMemberException( Environment.GetResourceString( "MissingMemberTypeRef" ) ); //// } //// //// Type fieldType = field.FieldType; //// if(fieldType.IsPrimitive) //// { //// throw new ArgumentException( Environment.GetResourceString( "Arg_TypeRefPrimitve" ) ); //// } //// //// if(i < flds.Length - 1) //// { //// if(!fieldType.IsValueType) //// { //// throw new MissingMemberException( Environment.GetResourceString( "MissingMemberNestErr" ) ); //// } //// } //// //// fields[i] = field.FieldHandle; //// targetType = fieldType; //// } //// //// TypedReference result = new TypedReference(); //// // reference to TypedReference is banned, so have to pass result as pointer //// unsafe //// { //// InternalMakeTypedReference( &result, target, fields, targetType.TypeHandle ); //// } //// //// return result; //// } //// } //// //// [ResourceExposure( ResourceScope.None )] //// [MethodImplAttribute( MethodImplOptions.InternalCall )] //// // reference to TypedReference is banned, so have to pass result as pointer //// private unsafe static extern void InternalMakeTypedReference( void* result, Object target, RuntimeFieldHandle[] flds, RuntimeTypeHandle lastFieldType ); public override int GetHashCode() { if(Type == IntPtr.Zero) { return 0; } else { return __reftype(this).GetHashCode(); } } public override bool Equals( Object o ) { #if EXCEPTION_STRINGS throw new NotSupportedException( Environment.GetResourceString( "NotSupported_NYI" ) ); #else throw new NotSupportedException(); #endif } public unsafe static Object ToObject( TypedReference value ) { return InternalToObject( &value ); } //// [ResourceExposure( ResourceScope.None )] [MethodImplAttribute( MethodImplOptions.InternalCall )] internal unsafe extern static Object InternalToObject( void* value ); internal bool IsNull { get { return Value.IsNull() && Type.IsNull(); } } public static Type GetTargetType( TypedReference value ) { return __reftype(value); } public static RuntimeTypeHandle TargetTypeToken( TypedReference value ) { return __reftype(value).TypeHandle; } // This may cause the type to be changed. [CLSCompliant( false )] public unsafe static void SetTypedReference( TypedReference target, Object value ) { InternalSetTypedReference( &target, value ); } //// [ResourceExposure( ResourceScope.None )] [MethodImplAttribute( MethodImplOptions.InternalCall )] internal unsafe extern static void InternalSetTypedReference( void* target, Object value ); // Internal method for getting a raw pointer for handles in JitHelpers. // The reference has to point into a local stack variable in order so it can not be moved by the GC. internal IntPtr GetPointerOnStack() { #if _DEBUG BCLDebug.Assert(IsAddressInStack(Value), "Pointer not in the stack!"); #endif return Value; } #if _DEBUG [ResourceExposure(ResourceScope.None)] [MethodImplAttribute(MethodImplOptions.InternalCall)] extern static bool IsAddressInStack(IntPtr ptr); #endif } } ================================================ FILE: Zelig/Zelig/RunTime/Framework/mscorlib/System/UInt16.cs ================================================ // ==++== // // Copyright (c) Microsoft Corporation. All rights reserved. // // ==--== /*============================================================ ** ** Class: UInt16 ** ** Purpose: This class will encapsulate a short and provide an ** Object representation of it. ** ** ===========================================================*/ namespace System { using System; using System.Globalization; using System.Runtime.InteropServices; using System.Runtime.CompilerServices; // Wrapper for unsigned 16 bit integers. [Microsoft.Zelig.Internals.WellKnownType( "System_UInt16" )] [Serializable] [CLSCompliant( false )] [StructLayout( LayoutKind.Sequential )] public struct UInt16 : IComparable, IFormattable, IConvertible, IComparable, IEquatable { public const ushort MaxValue = (ushort)0xFFFF; public const ushort MinValue = 0x0000; internal ushort m_value; // Compares this object to another object, returning an integer that // indicates the relationship. // Returns a value less than zero if this object // null is considered to be less than any instance. // If object is not of type UInt16, this method throws an ArgumentException. // public int CompareTo( Object value ) { if(value == null) { return 1; } if(value is UInt16) { return CompareTo( (UInt16)value ); } #if EXCEPTION_STRINGS throw new ArgumentException( Environment.GetResourceString( "Arg_MustBeUInt16" ) ); #else throw new ArgumentException(); #endif } public int CompareTo( UInt16 value ) { return ((int)m_value - (int)value); } public override bool Equals( Object obj ) { if(!(obj is UInt16)) { return false; } return Equals( (UInt16)obj ); } public bool Equals( UInt16 obj ) { return m_value == obj; } // Returns a HashCode for the UInt16 public override int GetHashCode() { return (int)m_value; } // Converts the current value to a String in base-10 with no extra padding. public override String ToString() { return Number.FormatUInt32( m_value, /*null,*/ NumberFormatInfo.CurrentInfo ); } public String ToString( IFormatProvider provider ) { return Number.FormatUInt32( m_value, /*null,*/ NumberFormatInfo.GetInstance( provider ) ); } public String ToString( String format ) { return Number.FormatUInt32( m_value, format, NumberFormatInfo.CurrentInfo ); } public String ToString( String format, IFormatProvider provider ) { return Number.FormatUInt32( m_value, format, NumberFormatInfo.GetInstance( provider ) ); } public static ushort Parse( String s ) { return Parse( s, NumberStyles.Integer, NumberFormatInfo.CurrentInfo ); } [CLSCompliant( false )] public static ushort Parse( String s , NumberStyles style ) { NumberFormatInfo.ValidateParseStyleInteger( style ); return Parse( s, style, NumberFormatInfo.CurrentInfo ); } [CLSCompliant( false )] public static ushort Parse( String s , IFormatProvider provider ) { return Parse( s, NumberStyles.Integer, NumberFormatInfo.GetInstance( provider ) ); } [CLSCompliant( false )] public static ushort Parse( String s , NumberStyles style , IFormatProvider provider ) { NumberFormatInfo.ValidateParseStyleInteger( style ); return Parse( s, style, NumberFormatInfo.GetInstance( provider ) ); } private static ushort Parse( String s , NumberStyles style , NumberFormatInfo info ) { uint i = 0; try { i = Number.ParseUInt32( s, style, info ); } catch(OverflowException e) { #if EXCEPTION_STRINGS throw new OverflowException( Environment.GetResourceString( "Overflow_UInt16" ), e ); #else throw new OverflowException( null, e); #endif } if(i > MaxValue) { #if EXCEPTION_STRINGS throw new OverflowException( Environment.GetResourceString( "Overflow_UInt16" ) ); #else throw new OverflowException(); #endif } return (ushort)i; } [CLSCompliant( false )] public static bool TryParse( String s , out UInt16 result ) { return TryParse( s, NumberStyles.Integer, NumberFormatInfo.CurrentInfo, out result ); } [CLSCompliant( false )] public static bool TryParse( String s , NumberStyles style , IFormatProvider provider , out UInt16 result ) { NumberFormatInfo.ValidateParseStyleInteger( style ); return TryParse( s, style, NumberFormatInfo.GetInstance( provider ), out result ); } private static bool TryParse( String s , NumberStyles style , NumberFormatInfo info , out UInt16 result ) { result = 0; UInt32 i; if(!Number.TryParseUInt32( s, style, info, out i )) { return false; } if(i > MaxValue) { return false; } result = (UInt16)i; return true; } #region IConvertible public TypeCode GetTypeCode() { return TypeCode.UInt16; } /// bool IConvertible.ToBoolean( IFormatProvider provider ) { return Convert.ToBoolean( m_value ); } /// char IConvertible.ToChar( IFormatProvider provider ) { return Convert.ToChar( m_value ); } /// sbyte IConvertible.ToSByte( IFormatProvider provider ) { return Convert.ToSByte( m_value ); } /// byte IConvertible.ToByte( IFormatProvider provider ) { return Convert.ToByte( m_value ); } /// short IConvertible.ToInt16( IFormatProvider provider ) { return Convert.ToInt16( m_value ); } /// ushort IConvertible.ToUInt16( IFormatProvider provider ) { return m_value; } /// int IConvertible.ToInt32( IFormatProvider provider ) { return Convert.ToInt32( m_value ); } /// uint IConvertible.ToUInt32( IFormatProvider provider ) { return Convert.ToUInt32( m_value ); } /// long IConvertible.ToInt64( IFormatProvider provider ) { return Convert.ToInt64( m_value ); } /// ulong IConvertible.ToUInt64( IFormatProvider provider ) { return Convert.ToUInt64( m_value ); } /// float IConvertible.ToSingle( IFormatProvider provider ) { return Convert.ToSingle( m_value ); } /// double IConvertible.ToDouble( IFormatProvider provider ) { return Convert.ToDouble( m_value ); } /// Decimal IConvertible.ToDecimal( IFormatProvider provider ) { return Convert.ToDecimal( m_value ); } /// DateTime IConvertible.ToDateTime( IFormatProvider provider ) { #if EXCEPTION_STRINGS throw new InvalidCastException( String.Format( CultureInfo.CurrentCulture, Environment.GetResourceString( "InvalidCast_FromTo" ), "UInt16", "DateTime" ) ); #else throw new InvalidCastException(); #endif } /// Object IConvertible.ToType( Type type, IFormatProvider provider ) { return Convert.DefaultToType( (IConvertible)this, type, provider ); } #endregion } } ================================================ FILE: Zelig/Zelig/RunTime/Framework/mscorlib/System/UInt32.cs ================================================ // ==++== // // Copyright (c) Microsoft Corporation. All rights reserved. // // ==--== /*============================================================ ** ** Class: UInt32 ** ** ** Purpose: This class will encapsulate an uint and ** provide an Object representation of it. ** ** ===========================================================*/ namespace System { using System; using System.Globalization; using System.Runtime.InteropServices; using System.Runtime.CompilerServices; // * Wrapper for unsigned 32 bit integers. [Microsoft.Zelig.Internals.WellKnownType( "System_UInt32" )] [Serializable] [CLSCompliant( false )] [System.Runtime.InteropServices.StructLayout( LayoutKind.Sequential )] public struct UInt32 : IComparable, IFormattable, IConvertible, IComparable, IEquatable { public const uint MaxValue = (uint)0xFFFFFFFF; public const uint MinValue = 0U; private uint m_value; // Compares this object to another object, returning an integer that // indicates the relationship. // Returns a value less than zero if this object // null is considered to be less than any instance. // If object is not of type UInt32, this method throws an ArgumentException. // public int CompareTo( Object value ) { if(value == null) { return 1; } if(value is UInt32) { return CompareTo( (uint)value ); } #if EXCEPTION_STRINGS throw new ArgumentException( Environment.GetResourceString( "Arg_MustBeUInt32" ) ); #else throw new ArgumentException(); #endif } public int CompareTo( UInt32 value ) { // Need to use compare because subtraction will wrap // to positive for very large neg numbers, etc. if(m_value < value) return -1; if(m_value > value) return 1; return 0; } public override bool Equals( Object obj ) { if(!(obj is UInt32)) { return false; } return Equals( (UInt32)obj ); } public bool Equals( UInt32 obj ) { return m_value == obj; } // The absolute value of the int contained. public override int GetHashCode() { return ((int)m_value); } // The base 10 representation of the number with no extra padding. public override String ToString() { return Number.FormatUInt32( m_value, /*null,*/ NumberFormatInfo.CurrentInfo ); } public String ToString( IFormatProvider provider ) { return Number.FormatUInt32( m_value, /*null,*/ NumberFormatInfo.GetInstance( provider ) ); } public String ToString( String format ) { return Number.FormatUInt32( m_value, format, NumberFormatInfo.CurrentInfo ); } public String ToString( String format , IFormatProvider provider ) { return Number.FormatUInt32( m_value, format, NumberFormatInfo.GetInstance( provider ) ); } [CLSCompliant( false )] public static uint Parse( String s ) { return Number.ParseUInt32( s, NumberStyles.Integer, NumberFormatInfo.CurrentInfo ); } [CLSCompliant( false )] public static uint Parse( String s , NumberStyles style ) { NumberFormatInfo.ValidateParseStyleInteger( style ); return Number.ParseUInt32( s, style, NumberFormatInfo.CurrentInfo ); } [CLSCompliant( false )] public static uint Parse( String s , IFormatProvider provider ) { return Number.ParseUInt32( s, NumberStyles.Integer, NumberFormatInfo.GetInstance( provider ) ); } [CLSCompliant( false )] public static uint Parse( String s , NumberStyles style , IFormatProvider provider ) { NumberFormatInfo.ValidateParseStyleInteger( style ); return Number.ParseUInt32( s, style, NumberFormatInfo.GetInstance( provider ) ); } [CLSCompliant( false )] public static bool TryParse( String s , out UInt32 result ) { return Number.TryParseUInt32( s, NumberStyles.Integer, NumberFormatInfo.CurrentInfo, out result ); } [CLSCompliant( false )] public static bool TryParse( String s , NumberStyles style , IFormatProvider provider , out UInt32 result ) { NumberFormatInfo.ValidateParseStyleInteger( style ); return Number.TryParseUInt32( s, style, NumberFormatInfo.GetInstance( provider ), out result ); } #region IConvertible public TypeCode GetTypeCode() { return TypeCode.UInt32; } /// bool IConvertible.ToBoolean( IFormatProvider provider ) { return Convert.ToBoolean( m_value ); } /// char IConvertible.ToChar( IFormatProvider provider ) { return Convert.ToChar( m_value ); } /// sbyte IConvertible.ToSByte( IFormatProvider provider ) { return Convert.ToSByte( m_value ); } /// byte IConvertible.ToByte( IFormatProvider provider ) { return Convert.ToByte( m_value ); } /// short IConvertible.ToInt16( IFormatProvider provider ) { return Convert.ToInt16( m_value ); } /// ushort IConvertible.ToUInt16( IFormatProvider provider ) { return Convert.ToUInt16( m_value ); } /// int IConvertible.ToInt32( IFormatProvider provider ) { return Convert.ToInt32( m_value ); } /// uint IConvertible.ToUInt32( IFormatProvider provider ) { return m_value; } /// long IConvertible.ToInt64( IFormatProvider provider ) { return Convert.ToInt64( m_value ); } /// ulong IConvertible.ToUInt64( IFormatProvider provider ) { return Convert.ToUInt64( m_value ); } /// float IConvertible.ToSingle( IFormatProvider provider ) { return Convert.ToSingle( m_value ); } /// double IConvertible.ToDouble( IFormatProvider provider ) { return Convert.ToDouble( m_value ); } /// Decimal IConvertible.ToDecimal( IFormatProvider provider ) { return Convert.ToDecimal( m_value ); } /// DateTime IConvertible.ToDateTime( IFormatProvider provider ) { #if EXCEPTION_STRINGS throw new InvalidCastException( String.Format( CultureInfo.CurrentCulture, Environment.GetResourceString( "InvalidCast_FromTo" ), "UInt32", "DateTime" ) ); #else throw new InvalidCastException(); #endif } /// Object IConvertible.ToType( Type type, IFormatProvider provider ) { return Convert.DefaultToType( (IConvertible)this, type, provider ); } #endregion } } ================================================ FILE: Zelig/Zelig/RunTime/Framework/mscorlib/System/UInt64.cs ================================================ // ==++== // // Copyright (c) Microsoft Corporation. All rights reserved. // // ==--== /*============================================================ ** ** Class: UInt64 ** ** Purpose: This class will encapsulate an unsigned long and ** provide an Object representation of it. ** ** ===========================================================*/ namespace System { using System; using System.Globalization; using System.Runtime.InteropServices; using System.Runtime.CompilerServices; // Wrapper for unsigned 64 bit integers. [Microsoft.Zelig.Internals.WellKnownType( "System_UInt64" )] [Serializable] [CLSCompliant( false )] [StructLayout( LayoutKind.Sequential )] public struct UInt64 : IComparable, IFormattable, IConvertible, IComparable, IEquatable { public const ulong MaxValue = (ulong)0xFFFFFFFFFFFFFFFFL; public const ulong MinValue = 0x0; private ulong m_value; // Compares this object to another object, returning an integer that // indicates the relationship. // Returns a value less than zero if this object // null is considered to be less than any instance. // If object is not of type UInt64, this method throws an ArgumentException. // public int CompareTo( Object value ) { if(value == null) { return 1; } if(value is UInt64) { return CompareTo( (UInt64)value ); } #if EXCEPTION_STRINGS throw new ArgumentException( Environment.GetResourceString( "Arg_MustBeUInt64" ) ); #else throw new ArgumentException(); #endif } public int CompareTo( UInt64 value ) { // Need to use compare because subtraction will wrap // to positive for very large neg numbers, etc. if(m_value < value) return -1; if(m_value > value) return 1; return 0; } public override bool Equals( Object obj ) { if(!(obj is UInt64)) { return false; } return Equals( (UInt64)obj ); } public bool Equals( UInt64 obj ) { return m_value == obj; } // The value of the lower 32 bits XORed with the uppper 32 bits. public override int GetHashCode() { return ((int)m_value) ^ (int)(m_value >> 32); } public override String ToString() { return Number.FormatUInt64( m_value, /*null,*/ NumberFormatInfo.CurrentInfo ); } public String ToString( IFormatProvider provider ) { return Number.FormatUInt64( m_value, /*null,*/ NumberFormatInfo.GetInstance( provider ) ); } public String ToString( String format ) { return Number.FormatUInt64( m_value, format, NumberFormatInfo.CurrentInfo ); } public String ToString( String format , IFormatProvider provider ) { return Number.FormatUInt64( m_value, format, NumberFormatInfo.GetInstance( provider ) ); } [CLSCompliant( false )] public static ulong Parse( String s ) { return Number.ParseUInt64( s, NumberStyles.Integer, NumberFormatInfo.CurrentInfo ); } [CLSCompliant( false )] public static ulong Parse( String s , NumberStyles style ) { NumberFormatInfo.ValidateParseStyleInteger( style ); return Number.ParseUInt64( s, style, NumberFormatInfo.CurrentInfo ); } [CLSCompliant( false )] public static ulong Parse( string s , IFormatProvider provider ) { return Number.ParseUInt64( s, NumberStyles.Integer, NumberFormatInfo.GetInstance( provider ) ); } [CLSCompliant( false )] public static ulong Parse( String s , NumberStyles style , IFormatProvider provider ) { NumberFormatInfo.ValidateParseStyleInteger( style ); return Number.ParseUInt64( s, style, NumberFormatInfo.GetInstance( provider ) ); } [CLSCompliant( false )] public static Boolean TryParse( String s , out UInt64 result ) { return Number.TryParseUInt64( s, NumberStyles.Integer, NumberFormatInfo.CurrentInfo, out result ); } [CLSCompliant( false )] public static Boolean TryParse( String s , NumberStyles style , IFormatProvider provider , out UInt64 result ) { NumberFormatInfo.ValidateParseStyleInteger( style ); return Number.TryParseUInt64( s, style, NumberFormatInfo.GetInstance( provider ), out result ); } #region IConvertible public TypeCode GetTypeCode() { return TypeCode.UInt64; } /// bool IConvertible.ToBoolean( IFormatProvider provider ) { return Convert.ToBoolean( m_value ); } /// char IConvertible.ToChar( IFormatProvider provider ) { return Convert.ToChar( m_value ); } /// sbyte IConvertible.ToSByte( IFormatProvider provider ) { return Convert.ToSByte( m_value ); } /// byte IConvertible.ToByte( IFormatProvider provider ) { return Convert.ToByte( m_value ); } /// short IConvertible.ToInt16( IFormatProvider provider ) { return Convert.ToInt16( m_value ); } /// ushort IConvertible.ToUInt16( IFormatProvider provider ) { return Convert.ToUInt16( m_value ); } /// int IConvertible.ToInt32( IFormatProvider provider ) { return Convert.ToInt32( m_value ); } /// uint IConvertible.ToUInt32( IFormatProvider provider ) { return Convert.ToUInt32( m_value ); } /// long IConvertible.ToInt64( IFormatProvider provider ) { return Convert.ToInt64( m_value ); } /// ulong IConvertible.ToUInt64( IFormatProvider provider ) { return m_value; } /// float IConvertible.ToSingle( IFormatProvider provider ) { return Convert.ToSingle( m_value ); } /// double IConvertible.ToDouble( IFormatProvider provider ) { return Convert.ToDouble( m_value ); } /// Decimal IConvertible.ToDecimal( IFormatProvider provider ) { return Convert.ToDecimal( m_value ); } /// DateTime IConvertible.ToDateTime( IFormatProvider provider ) { #if EXCEPTION_STRINGS throw new InvalidCastException( String.Format( CultureInfo.CurrentCulture, Environment.GetResourceString( "InvalidCast_FromTo" ), "UInt64", "DateTime" ) ); #else throw new InvalidCastException(); #endif } /// Object IConvertible.ToType( Type type, IFormatProvider provider ) { return Convert.DefaultToType( (IConvertible)this, type, provider ); } #endregion } } ================================================ FILE: Zelig/Zelig/RunTime/Framework/mscorlib/System/UIntPtr.cs ================================================ // ==++== // // Copyright (c) Microsoft Corporation. All rights reserved. // // ==--== /*============================================================ ** ** Class: UIntPtr ** ** ** Purpose: Platform independent integer ** ** ===========================================================*/ namespace System { using System; using System.Globalization; using System.Runtime.Serialization; [Microsoft.Zelig.Internals.WellKnownType( "System_UIntPtr" )] [Serializable] [CLSCompliant( false )] public struct UIntPtr /*: ISerializable*/ { public static readonly UIntPtr Zero; unsafe private void* m_value; public unsafe UIntPtr( uint value ) { m_value = (void*)value; } public unsafe UIntPtr(ulong value) { m_value = (void*)checked((uint)value); } [CLSCompliant( false )] public unsafe UIntPtr( void* value ) { m_value = value; } //// private unsafe UIntPtr( SerializationInfo info, StreamingContext context ) //// { //// ulong l = info.GetUInt64( "value" ); //// //// if(l > UInt32.MaxValue) //// { //// throw new ArgumentException( Environment.GetResourceString( "Serialization_InvalidPtrValue" ) ); //// } //// //// m_value = (void*)l; //// } //// //// unsafe void ISerializable.GetObjectData( SerializationInfo info, StreamingContext context ) //// { //// if(info == null) //// { //// throw new ArgumentNullException( "info" ); //// } //// //// info.AddValue( "value", (ulong)m_value ); //// } public unsafe override bool Equals( Object obj ) { if(obj is UIntPtr) { return (m_value == ((UIntPtr)obj).m_value); } return false; } public unsafe override int GetHashCode() { return unchecked( (int)((long)m_value) ) & 0x7fffffff; } public unsafe uint ToUInt32() { return (uint)m_value; } public unsafe ulong ToUInt64() { return (ulong)m_value; } //// public unsafe override String ToString() //// { //// return ((uint)m_value).ToString( CultureInfo.InvariantCulture ); //// } public static explicit operator UIntPtr( uint value ) { return new UIntPtr( value ); } public static explicit operator UIntPtr (ulong value) { return new UIntPtr(value); } public unsafe static explicit operator uint( UIntPtr value ) { return (uint)value.m_value; } public unsafe static explicit operator ulong (UIntPtr value) { return (ulong)value.m_value; } [CLSCompliant( false )] public static unsafe explicit operator UIntPtr( void* value ) { return new UIntPtr( value ); } [CLSCompliant( false )] public static unsafe explicit operator void*( UIntPtr value ) { return value.ToPointer(); } public unsafe static bool operator ==( UIntPtr value1, UIntPtr value2 ) { return value1.m_value == value2.m_value; } public unsafe static bool operator !=( UIntPtr value1, UIntPtr value2 ) { return value1.m_value != value2.m_value; } public static int Size { get { return 4; } } [CLSCompliant( false )] public unsafe void* ToPointer() { return m_value; } } } ================================================ FILE: Zelig/Zelig/RunTime/Framework/mscorlib/System/UnSafeCharBuffer.cs ================================================ // ==++== // // Copyright (c) Microsoft Corporation. All rights reserved. // // ==--== /*============================================================ ** ** Class: UnSafeBuffer ** ** Purpose: A class to detect incorrect usage of UnSafeBuffer ** ** ===========================================================*/ namespace System { using System.Diagnostics; unsafe internal struct UnSafeCharBuffer { char* m_buffer; int m_totalSize; int m_length; public UnSafeCharBuffer( char* buffer, int bufferSize ) { BCLDebug.Assert( buffer != null , "buffer pointer can't be null." ); BCLDebug.Assert( bufferSize >= 0, "buffer size can't be negative." ); m_buffer = buffer; m_totalSize = bufferSize; m_length = 0; } public void AppendString( string stringToAppend ) { if(String.IsNullOrEmpty( stringToAppend )) { return; } if((m_totalSize - m_length) < stringToAppend.Length) { throw new IndexOutOfRangeException(); } fixed(char* pointerToString = stringToAppend) { Buffer.InternalMemoryCopy( pointerToString, m_buffer + m_length, stringToAppend.Length ); } m_length += stringToAppend.Length; BCLDebug.Assert( m_length <= m_totalSize, "Buffer has been overflowed!" ); } public int Length { get { return m_length; } } } } ================================================ FILE: Zelig/Zelig/RunTime/Framework/mscorlib/System/UnauthorizedAccessException.cs ================================================ // ==++== // // Copyright (c) Microsoft Corporation. All rights reserved. // // ==--== /*============================================================ ** ** Class: UnauthorizedAccessException ** ** ** Purpose: An exception for OS 'access denied' types of ** errors, including IO and limited security types ** of errors. ** ** ===========================================================*/ using System; using System.Runtime.Serialization; namespace System { // The UnauthorizedAccessException is thrown when access errors // occur from IO or other OS methods. [Serializable()] public class UnauthorizedAccessException : SystemException { public UnauthorizedAccessException() : base( Environment.GetResourceString( "Arg_UnauthorizedAccessException" ) ) { //// SetErrorCode( __HResults.COR_E_UNAUTHORIZEDACCESS ); } public UnauthorizedAccessException( String message ) : base( message ) { //// SetErrorCode( __HResults.COR_E_UNAUTHORIZEDACCESS ); } public UnauthorizedAccessException( String message, Exception inner ) : base( message, inner ) { //// SetErrorCode( __HResults.COR_E_UNAUTHORIZEDACCESS ); } //// protected UnauthorizedAccessException( SerializationInfo info, StreamingContext context ) : base( info, context ) //// { //// } } } ================================================ FILE: Zelig/Zelig/RunTime/Framework/mscorlib/System/ValueType.cs ================================================ // ==++== // // Copyright (c) Microsoft Corporation. All rights reserved. // // ==--== /*============================================================ ** ** Class: ValueType ** ** ** Purpose: Base class for all value classes. ** ** ===========================================================*/ namespace System { using System; using System.Reflection; using System.Runtime.CompilerServices; ////using System.Runtime.Versioning; [Microsoft.Zelig.Internals.WellKnownType( "System_ValueType" )] [Serializable] public abstract class ValueType { //// public override bool Equals( Object obj ) //// { //// BCLDebug.Perf( false, "ValueType::Equals is not fast. " + this.GetType().FullName + " should override Equals(Object)" ); //// //// if(obj == null) //// { //// return false; //// } //// //// RuntimeType thisType = (RuntimeType)this.GetType(); //// RuntimeType thatType = (RuntimeType)obj .GetType(); //// //// if(thatType != thisType) //// { //// return false; //// } //// //// Object thisObj = (Object)this; //// Object thisResult; //// Object thatResult; //// //// // if there are no GC references in this object we can avoid reflection //// // and do a fast memcmp //// if(CanCompareBits( this )) //// { //// return FastEqualsCheck( thisObj, obj ); //// } //// //// FieldInfo[] thisFields = thisType.GetFields( BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic ); //// //// for(int i = 0; i < thisFields.Length; i++) //// { //// thisResult = ((RtFieldInfo)thisFields[i]).InternalGetValue( thisObj, false ); //// thatResult = ((RtFieldInfo)thisFields[i]).InternalGetValue( obj, false ); //// //// if(thisResult == null) //// { //// if(thatResult != null) //// { //// return false; //// } //// } //// else if(!thisResult.Equals( thatResult )) //// { //// return false; //// } //// } //// //// return true; //// } //// //// [ResourceExposure( ResourceScope.None )] //// [MethodImpl( MethodImplOptions.InternalCall )] //// private static extern bool CanCompareBits( Object obj ); //// //// [ResourceExposure( ResourceScope.None )] //// [MethodImpl( MethodImplOptions.InternalCall )] //// private static extern bool FastEqualsCheck( Object a, Object b ); /*=================================GetHashCode================================== **Action: Our algorithm for returning the hashcode is a little bit complex. We look ** for the first non-static field and get it's hashcode. If the type has no ** non-static fields, we return the hashcode of the type. We can't take the ** hashcode of a static member because if that member is of the same type as ** the original type, we'll end up in an infinite loop. **Returns: The hashcode for the type. **Arguments: None. **Exceptions: None. ==============================================================================*/ //// [ResourceExposure( ResourceScope.None )] //// [MethodImpl( MethodImplOptions.InternalCall )] //// public extern override int GetHashCode(); //// public override String ToString() //// { //// return this.GetType().ToString(); //// } } } ================================================ FILE: Zelig/Zelig/RunTime/Framework/mscorlib/System/Version.cs ================================================ //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // Copyright (c) Microsoft Corporation. All rights reserved. //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// namespace System { using System.Globalization; // A Version object contains four hierarchical numeric components: major, minor, // revision and build. Revision and build may be unspecified, which is represented // internally as a -1. By definition, an unspecified component matches anything // (both unspecified and specified), and an unspecified component is "less than" any // specified component. public sealed class Version // : ICloneable, IComparable, IComparable, IEquatable { // AssemblyName depends on the order staying the same private int m_major; private int m_minor; private int m_build; // = -1; private int m_revision; // = -1; //--// public static bool operator==( Version v1, Version v2 ) { if(object.ReferenceEquals( v1, null )) { return object.ReferenceEquals( v2, null ); } return v1.Equals( v2 ); } public static bool operator !=( Version v1, Version v2 ) { return !( v1 == v2 ); } public static bool operator >( Version v1, Version v2 ) { return v2 < v1; } public static bool operator >=( Version v1, Version v2 ) { return v2 <= v1; } public static bool operator <( Version v1, Version v2 ) { if(v1 == null) { throw new ArgumentNullException( "v1" ); } return v1.CompareTo( v2 ) < 0; } public static bool operator <=( Version v1, Version v2 ) { if(v1 == null) { throw new ArgumentNullException( "v1" ); } return v1.CompareTo( v2 ) <= 0; } //--// public Version(int major, int minor, int build, int revision) { if(major < 0 || minor < 0 || revision < 0 || build < 0) throw new ArgumentOutOfRangeException( ); m_major = major; m_minor = minor; m_revision = revision; m_build = build; } public Version(int major, int minor) { if (major < 0) throw new ArgumentOutOfRangeException(); if (minor < 0) throw new ArgumentOutOfRangeException(); m_major = major; m_minor = minor; // Other 2 initialize to -1 as it done on desktop and CE m_build = -1; m_revision = -1; } // Properties for setting and getting version numbers public int Major { get { return m_major; } } public int Minor { get { return m_minor; } } public int Revision { get { return m_revision; } } public int Build { get { return m_build; } } public override bool Equals(Object obj) { if(((Object)obj == null ) || ( !( obj is Version ) )) { return false; } Version v = (Version)obj; // check that major, minor, build & revision numbers match if( ( this.m_major != v.m_major ) || ( this.m_minor != v.m_minor ) || ( this.m_build != v.m_build ) || ( this.m_revision != v.m_revision )) { return false; } return true; } public int CompareTo( Version value ) { if(value == null) { return 1; } if(this.m_major != value.m_major) { if(this.m_major > value.m_major) { return 1; } return -1; } else if(this.m_minor != value.m_minor) { if(this.m_minor > value.m_minor) { return 1; } return -1; } else if(this.m_build != value.m_build) { if(this.m_build > value.m_build) { return 1; } return -1; } else { if(this.m_revision == value.m_revision) { return 0; } if(this.m_revision > value.m_revision) { return 1; } return -1; } } public override int GetHashCode( ) { return 0 | (this.m_major & 15) << 28 | (this.m_minor & 255) << 20 | (this.m_build & 255) << 12 | (this.m_revision & 4095); } public override String ToString() { string retStr = m_major + "." + m_minor; // Adds m_build and then m_revision if they are positive. They could be -1 in this case not added. if (m_build >= 0) { retStr += "." + m_build; if (m_revision >= 0) { retStr += "." + m_revision; } } return retStr; } } } ================================================ FILE: Zelig/Zelig/RunTime/Framework/mscorlib/System/Void.cs ================================================ // ==++== // // Copyright (c) Microsoft Corporation. All rights reserved. // // ==--== //////////////////////////////////////////////////////////////////////////////// // Void // This class represents the void return type //////////////////////////////////////////////////////////////////////////////// namespace System { using System; [Microsoft.Zelig.Internals.WellKnownType( "System_Void" )] [Serializable] public struct Void { } } ================================================ FILE: Zelig/Zelig/RunTime/Framework/mscorlib/System/WeakReference.cs ================================================ // ==++== // // Copyright (c) Microsoft Corporation. All rights reserved. // // ==--== /*============================================================ ** ** Class: WeakReference ** ** Purpose: A wrapper for establishing a WeakReference to an Object. ** ===========================================================*/ namespace System { using System; ////using System.Runtime.Remoting; using System.Runtime.Serialization; ////using System.Security.Permissions; using System.Runtime.InteropServices; using System.Runtime.CompilerServices; using System.Threading; ////[SecurityPermissionAttribute( SecurityAction.InheritanceDemand, Flags = SecurityPermissionFlag.UnmanagedCode )] [Microsoft.Zelig.Internals.WellKnownType( "System_WeakReference" )] [Serializable] public class WeakReference /*: ISerializable*/ { //// // Most methods using m_handle should use GC.KeepAlive(this) //// // to avoid potential handle recycling attacks. The GC special //// // cases the finalizer for WeakReference & only clears them //// // when all threads are suspended, but you might still run into //// // problems if your code is at least partially interruptible. //// // It's just too much complexity to think about. //// internal IntPtr m_handle; //// internal bool m_IsLongReference; // Creates a new WeakReference that keeps track of target. // Assumes a Short Weak Reference (ie TrackResurrection is false.) // public WeakReference( Object target ) : this( target, false ) { } //Creates a new WeakReference that keeps track of target. // [MethodImpl( MethodImplOptions.InternalCall )] public extern WeakReference( Object target, bool trackResurrection ); //// { //// m_IsLongReference = trackResurrection; //// m_handle = GCHandle.InternalAlloc( target, trackResurrection ? GCHandleType.WeakTrackResurrection : GCHandleType.Weak ); //// } //// //// //// protected WeakReference( SerializationInfo info, StreamingContext context ) //// { //// if(info == null) //// { //// throw new ArgumentNullException( "info" ); //// } //// //// Object temp = info.GetValue( "TrackedObject", typeof( Object ) ); //// //// m_IsLongReference = info.GetBoolean( "TrackResurrection" ); //// m_handle = GCHandle.InternalAlloc( temp, m_IsLongReference ? GCHandleType.WeakTrackResurrection : GCHandleType.Weak ); //// } //Determines whether or not this instance of WeakReference still refers to an object //that has not been collected. // public virtual extern bool IsAlive { [MethodImpl( MethodImplOptions.InternalCall )] get; //// { //// IntPtr h = m_handle; //// //// // In determining whether it is valid to use this object, we need to at least expose this //// // without throwing an exception. //// if(h == IntPtr.Zero) //// { //// return false; //// } //// //// bool result = (GCHandle.InternalGet( h ) != null); //// //// // This call to KeepAlive is necessary to prevent the WeakReference finalizer from being called before the result is computed //// h = Thread.VolatileRead( ref m_handle ); //// //// GC.KeepAlive( this ); //// //// return (h == IntPtr.Zero) ? false : result; //// } } //// //Returns a boolean indicating whether or not we're tracking objects until they're collected (true) //// //or just until they're finalized (false). //// // //// public virtual bool TrackResurrection //// { //// get //// { //// return m_IsLongReference; //// } //// } //Gets the Object stored in the handle if it's accessible. // Or sets it. // public virtual extern Object Target { [MethodImpl( MethodImplOptions.InternalCall )] get; //// { //// IntPtr h = m_handle; //// // Should only happen when used illegally, like using a //// // WeakReference from a finalizer. //// if(h == IntPtr.Zero) //// { //// return null; //// } //// //// Object o = GCHandle.InternalGet( h ); //// //// // Ensure this WeakReference doesn't get finalized while we're //// // in this method. //// h = Thread.VolatileRead( ref m_handle ); //// //// GC.KeepAlive( this ); //// //// return (h == IntPtr.Zero) ? null : o; //// } [MethodImpl( MethodImplOptions.InternalCall )] set; //// { //// IntPtr h = m_handle; //// if(h == IntPtr.Zero) //// { //// throw new InvalidOperationException( Environment.GetResourceString( "InvalidOperation_HandleIsNotInitialized" ) ); //// } //// //// // There is a race w/ finalization where m_handle gets set to //// // NULL and the WeakReference becomes invalid. Here we have to //// // do the following in order: //// // //// // 1. Get the old object value //// // 2. Get m_handle //// // 3. HndInterlockedCompareExchange(m_handle, newValue, oldValue); //// // //// // If the interlocked-cmp-exchange fails, then either we lost a race //// // with another updater, or we lost a race w/ the finalizer. In //// // either case, we can just let the other guy win. //// Object oldValue = GCHandle.InternalGet( h ); //// //// h = m_handle; //// if(h == IntPtr.Zero) //// { //// throw new InvalidOperationException( Environment.GetResourceString( "InvalidOperation_HandleIsNotInitialized" ) ); //// } //// //// GCHandle.InternalCompareExchange( h, value, oldValue, false /* isPinned */); //// //// // Ensure we don't have any handle recycling attacks in this //// // method where the finalizer frees the handle. //// GC.KeepAlive( this ); //// } } //// // Free all system resources associated with this reference. //// // //// // Note: The WeakReference finalizer is not actually run, but //// // treated specially in gc.cpp's ScanForFinalization //// // This is needed for subclasses deriving from WeakReference, however. //// ~WeakReference() //// { //// IntPtr old_handle = m_handle; //// if(old_handle != IntPtr.Zero) //// { //// if(old_handle == Interlocked.CompareExchange( ref m_handle, IntPtr.Zero, old_handle )) //// { //// GCHandle.InternalFree( old_handle ); //// } //// } //// } //// //// public virtual void GetObjectData( SerializationInfo info, StreamingContext context ) //// { //// if(info == null) //// { //// throw new ArgumentNullException( "info" ); //// } //// //// info.AddValue( "TrackedObject", Target, typeof( Object ) ); //// info.AddValue( "TrackResurrection", m_IsLongReference ); //// } } } ================================================ FILE: Zelig/Zelig/RunTime/Framework/mscorlib/ZeligHooks/TypeDependencyAttribute.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // namespace Microsoft.Zelig.Internals { using System; [WellKnownType( "Microsoft_Zelig_Internals_TypeDependencyAttribute" )] [AttributeUsage( AttributeTargets.Struct | AttributeTargets.Class | AttributeTargets.Interface, AllowMultiple = true, Inherited = false)] internal sealed class TypeDependencyAttribute : Attribute { internal Type Type; public TypeDependencyAttribute( Type type ) { this.Type = type; } } } ================================================ FILE: Zelig/Zelig/RunTime/Framework/mscorlib/ZeligHooks/WellKnownFieldAttribute.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // namespace Microsoft.Zelig.Internals { using System; [WellKnownType( "Microsoft_Zelig_Internals_WellKnownFieldAttribute" )] [AttributeUsage(AttributeTargets.Field)] internal class WellKnownFieldAttribute : Attribute { // // State // internal readonly string FieldName; // // Constructor Methods // internal WellKnownFieldAttribute( string fieldName ) { this.FieldName = fieldName; } } } ================================================ FILE: Zelig/Zelig/RunTime/Framework/mscorlib/ZeligHooks/WellKnownMethodAttribute.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // namespace Microsoft.Zelig.Internals { using System; [WellKnownType( "Microsoft_Zelig_Internals_WellKnownMethodAttribute" )] [AttributeUsage(AttributeTargets.Constructor | AttributeTargets.Method )] internal class WellKnownMethodAttribute : Attribute { // // State // internal readonly string FieldName; // // Constructor Methods // internal WellKnownMethodAttribute( string fieldName ) { this.FieldName = fieldName; } } } ================================================ FILE: Zelig/Zelig/RunTime/Framework/mscorlib/ZeligHooks/WellKnownTypeAttribute.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // namespace Microsoft.Zelig.Internals { using System; [AttributeUsage( AttributeTargets.Class | AttributeTargets.Struct | AttributeTargets.Enum | AttributeTargets.Interface )] internal class WellKnownTypeAttribute : Attribute { // // State // internal readonly string TypeName; // // Constructor Methods // internal WellKnownTypeAttribute( string typeName ) { this.TypeName = typeName; } } } ================================================ FILE: Zelig/Zelig/RunTime/Framework/mscorlib/mscorlib.csproj ================================================  true true false Debug AnyCPU 9.0.21022 2.0 {186F31A3-EF89-4A25-B2D5-20060501AA01} Library Properties mscorlib mscorlib $(LlilumBuildRoot)\Target\obj\$(MSBuildProjectName)\ v4.5 true full false $(LlilumBuildRoot)\Target\bin\$(Configuration)\ DEBUG;TRACE prompt 4 true true AllRules.ruleset AnyCPU false pdbonly true $(LlilumBuildRoot)\Target\bin\$(Configuration)\ TRACE prompt 4 true true true AllRules.ruleset AnyCPU false true full false $(LlilumBuildRoot)\Target\bin\$(Configuration)\ TRACE;DEBUG prompt 4 AnyCPU true true true AllRules.ruleset false Code Code $(IntermediateOutputPath)runtimemetadataversion.rsp ================================================ FILE: Zelig/Zelig/RunTime/Framework/mscorlib_UnitTest/Files.Designer.cs ================================================ //------------------------------------------------------------------------------ // // This code was generated by a tool. // Runtime Version:4.0.30319.18444 // // Changes to this file may cause incorrect behavior and will be lost if // the code is regenerated. // //------------------------------------------------------------------------------ namespace mscorlib_UnitTest { using System; /// /// A strongly-typed resource class, for looking up localized strings, etc. /// // This class was auto-generated by the StronglyTypedResourceBuilder // class via a tool like ResGen or Visual Studio. // To add or remove a member, edit your .ResX file then rerun ResGen // with the /str option, or rebuild your VS project. [global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Resources.Tools.StronglyTypedResourceBuilder", "4.0.0.0")] [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] [global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()] internal class Files { private static global::System.Resources.ResourceManager resourceMan; private static global::System.Globalization.CultureInfo resourceCulture; [global::System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")] internal Files() { } /// /// Returns the cached ResourceManager instance used by this class. /// [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)] internal static global::System.Resources.ResourceManager ResourceManager { get { if (object.ReferenceEquals(resourceMan, null)) { global::System.Resources.ResourceManager temp = new global::System.Resources.ResourceManager("mscorlib_UnitTest.Files", typeof(Files).Assembly); resourceMan = temp; } return resourceMan; } } /// /// Overrides the current thread's CurrentUICulture property for all /// resource lookups using this strongly typed resource class. /// [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)] internal static global::System.Globalization.CultureInfo Culture { get { return resourceCulture; } set { resourceCulture = value; } } /// /// Looks up a localized resource of type System.Byte[]. /// internal static byte[] ZeligRefreshBinaryDrop { get { object obj = ResourceManager.GetObject("ZeligRefreshBinaryDrop", resourceCulture); return ((byte[])(obj)); } } } } ================================================ FILE: Zelig/Zelig/RunTime/Framework/mscorlib_UnitTest/Files.resx ================================================  text/microsoft-resx 2.0 System.Resources.ResXResourceReader, System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 System.Resources.ResXResourceWriter, System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 Resources\ZeligRefreshBinaryDrop.cmd;System.Byte[], mscorlib, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 ================================================ FILE: Zelig/Zelig/RunTime/Framework/mscorlib_UnitTest/Program.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // //#define INCLUDE_BASIC_TESTS //#define INCLUDE_VERIFICATION //#define GC_TEST_MULTIPOINTER_STRUCTS //#define GC_STRESS //#define BITFIELD_TEST namespace mscorlib_UnitTest { using System; using System.Collections.Generic; using System.Runtime.CompilerServices; using RT = Microsoft.Zelig.Runtime; public class Program { #if BITFIELD_TEST public enum EnumBitField { Test1, Test2, Test3, } [RT.MemoryMappedPeripheral(Base=0x08000000U,Length=0x00000020U)] public class BitFieldTest { [RT.BitFieldPeripheral(PhysicalType=typeof(uint))] public struct BitFieldReg { [RT.BitFieldRegister(Position=0,Size= 3)] public uint Field1; [RT.BitFieldRegister(Position=3,Size= 2)] public uint Field2; [RT.BitFieldRegister(Position=5,Size=10)] public EnumBitField Field3; [RT.BitFieldRegister(Position=31,Size=1)] public bool Field4; [RT.BitFieldSplitRegister(Position=16,Size=4,Offset=4)] [RT.BitFieldSplitRegister(Position=20,Size=4,Offset=0)] public int Field5; } [RT.Register(Offset=0)] public BitFieldReg reg1; // // Access Methods // public static extern BitFieldTest Instance { [RT.SingletonFactory()] [MethodImpl( MethodImplOptions.InternalCall )] get; } } static void TestBitField() { BitFieldTest bft = BitFieldTest.Instance; bft.reg1.Field1 = 2; bft.reg1.Field2 += 2; bft.reg1.Field5++; var reg1 = bft.reg1; if(reg1.Field4) { reg1.Field3 = EnumBitField.Test3; } bft.reg1 = reg1; BitFieldTest.BitFieldReg reg2 = new BitFieldTest.BitFieldReg(); reg2.Field1 = 12; reg2.Field2 = 2; reg2.Field5 = -2; bft.reg1 = reg2; } #endif class TestFinalizer { int m_a; public TestFinalizer( int a ) { m_a = a; } ~TestFinalizer() { Console.WriteLine( "{0}", m_a ); } } static void TestFinalizers() { for(int i = 0; i < 10; i++) { var a = new TestFinalizer( i + 100 ); var b = new TestFinalizer( i + 200 ); GC.Collect(); GC.WaitForPendingFinalizers(); } } static void TestSyncBlocks() { for(int i = 0; i < 10; i++) { object obj = new object(); lock(obj) { object obj2 = new object(); lock(obj2) { } GC.Collect(); GC.WaitForPendingFinalizers(); } } } static string TestArrayInitializers() { try { int[] a = new int[] { 1, 2, 3, 4, 5 }; char[] b = new char[] { 'a', 'b', 'c' }; string[] c = new string[] { "a", "b", "c" }; byte[] payload = Files.ZeligRefreshBinaryDrop; object obj = c; ICloneable cld = (ICloneable)obj; object obj2 = cld;//.Clone(); string[] c2 = (string[])obj; Buffer.BlockCopy( a, 0 * sizeof(int), a, 3 * sizeof(int), 2 * sizeof(int) ); Buffer.BlockCopy( a, 1 * sizeof(int), a, 0 * sizeof(int), 2 * sizeof(int) ); ICollection< string > icoll = c; foreach(var s in icoll) { Console.WriteLine( s ); } return c2[0]; } catch(Exception ex) { return ex.Message; } } static int[] TestArrayBoundChecks( int[] a , int c1 , int c2 ) { for(int i = 0; i < a.Length; i++) { if(i < c1 && (i < c2 || i > c2)) { a[i] = 3; } if(i < c1 || (i < c2 && i >= 2)) { a[i] = 4; } a[i] *= 2; } return a; } static void TestArrayBoundChecks() { int[] a = new int[] { 1, 2, 3, 4, 5 }; TestArrayBoundChecks( a, 3, 5 ); } static int TestCheckedOperations( int a , int b , int c ) { byte aB = (byte)a; byte bB = (byte)b; byte cB = (byte)c; byte rB = checked( (byte)(cB + bB + cB) ); return rB; } public abstract class Sub1 { public abstract int Code(); } public class Sub2 : Sub1 { public override int Code() { return 2; } } public class Sub3 : Sub2 { public override int Code() { return 3; } } public class Sub4 : Sub2 { public override int Code() { return 4; } } class DelegateTester { delegate int DelegateTest( int a ); static int StaticDelegateTarget( int a ) { return a * a; } int InstanceDelegateTarget( int a ) { return a * a; } internal virtual int VirtualDelegateTarget( int a ) { return a * a; } internal static void Run() { DelegateTest tst; DelegateTester pThis = new SubDelegateTester(); tst = StaticDelegateTarget ; tst( 2 ); tst = pThis.InstanceDelegateTarget; tst( 2 ); tst = pThis.VirtualDelegateTarget ; tst( 2 ); } } class SubDelegateTester : DelegateTester { internal override int VirtualDelegateTarget( int a ) { return a * a + 5; } } [RT.NoInline] private static float[] TestNumeric( float a , float b , float c ) { float[] res = new float[32]; int i = 0; res[i++] = - b; res[i++] = a + b; res[i++] = a - b; res[i++] = b - a; res[i++] = a + c; res[i++] = a - c; res[i++] = c - a; res[i++] = a * b; res[i++] = a / b; res[i++] = a < b ? 1 : 0; res[i++] = a == b ? 1 : 0; res[i++] = a > b ? 1 : 0; return res; } [RT.NoInline] private static double[] TestNumeric( double a , double b , double c ) { double[] res = new double[32]; int i = 0; res[i++] = - b; res[i++] = a + b; res[i++] = a - b; res[i++] = b - a; res[i++] = a + c; res[i++] = a - c; res[i++] = c - a; res[i++] = a * b; res[i++] = a / b; res[i++] = a < b ? 1 : 0; res[i++] = a == b ? 1 : 0; res[i++] = a > b ? 1 : 0; return res; } //--// private static void TestFloatingPoint() { System.Diagnostics.Stopwatch stopwatch = new System.Diagnostics.Stopwatch(); for(int loop = 0; loop < 32; loop++) { stopwatch.Start(); float[] res1 = TestNumeric( 1.3f, 3.5f, 0f ); float[] res2 = TestNumeric( 1.3f, -3.5f, 0f ); stopwatch.Stop(); long val = stopwatch.ElapsedTicks; stopwatch.Reset(); } for(int loop = 0; loop < 32; loop++) { double[] res1 = TestNumeric( 1.3d, 3.5d, 0d ); double[] res2 = TestNumeric( 1.3d, -3.5d, 0d ); } } private static void TestList() { var lst = new List< int >(); lst.Add( 1 ); lst.Add( 2 ); lst.Add( 3 ); lst.Add( 4 ); lst.Contains( 3 ); lst.Contains( 5 ); var lst2 = new List< string >(); lst2.Add( "test1" ); lst2.Add( "test2" ); lst2.Add( "test3" ); lst2.Add( "test4" ); lst2.Contains( "test3" ); lst2.Contains( "test5" ); } private static int TestDictionary() { var dictInt = new Dictionary< int, int >(); dictInt[1] = 10; dictInt[2] = 20; dictInt[3] = 30; dictInt[4] = 40; int val = dictInt[3]; var dict = new Dictionary< string, int >( StringComparer.Ordinal ); dict["test" ] = 1; dict["test2"] = 2; dict["TEST" ] = 3; dict["TEST2"] = 4; int res = dict["TEST"]; return res; } private static void TestExceptions() { try { try { Debug.Print( "Exception: 1" ); } finally { Debug.Print( "Exception: 2" ); try { Exception e = new Exception( "test" ); throw e; } catch { Debug.Print( "Exception: 2b" ); throw; } finally { Debug.Print( "Exception: 3" ); } } } catch(Exception) { Debug.Print( "Exception: 4" ); } finally { Debug.Print( "Exception: 5" ); } } private static void TestEvents() { System.Threading.AutoResetEvent ev1 = new System.Threading.AutoResetEvent( false ); System.Threading.AutoResetEvent ev2 = new System.Threading.AutoResetEvent( false ); object obj = new object(); int count = 0; System.Threading.Thread thread1 = new System.Threading.Thread( delegate() { for(int i = 0; i < 16; i++) { ev1.WaitOne(); ev2.Set(); lock(obj) { System.Threading.Thread.Sleep( 10 ); count++; } } } ); System.Threading.Thread thread2 = new System.Threading.Thread( delegate() { for(int i = 0; i < 16; i++) { ev2.WaitOne(); ev1.Set(); lock(obj) { System.Threading.Thread.Sleep( 10 ); count++; } } } ); thread1.Start(); thread2.Start(); ev1.Set(); thread1.Join(); thread2.Join(); } private static void TestTime() { DateTime now; int val; now = DateTime.Now; now = DateTime.Now; now = DateTime.Now; val = now.Year; val = now.Month; val = now.Day; val = now.Hour; val = now.Minute; val = now.Second; val = now.Millisecond; Microsoft.Zelig.Runtime.DateTimeImpl.SetUtcTime( TimeZone.CurrentTimeZone.ToUniversalTime( new DateTime( 2003, 1, 1 ) ) ); now = DateTime.Now; now = DateTime.Now; now = DateTime.Now; val = now.Year; val = now.Month; val = now.Day; val = now.Hour; val = now.Minute; val = now.Second; val = now.Millisecond; } private static void TestTimers() { int count = 0; System.Threading.Timer timer = new System.Threading.Timer( delegate( object state ) { count++; } ); timer.Change( 20, System.Threading.Timeout.Infinite ); System.Threading.Thread.Sleep( 100 ); timer.Change( 20, 1 ); System.Threading.Thread.Sleep( 100 ); timer.Dispose(); System.Threading.Thread.Sleep( 100 ); } private static string[] TestToString() { string[] res = new string[32]; int i = 0; res[i++] = int .MaxValue.ToString(); res[i++] = ((int)0) .ToString(); res[i++] = int .MinValue.ToString(); res[i++] = 123 .ToString( "00000" ); res[i++] = char .MaxValue.ToString(); res[i++] = ((char)0) .ToString(); res[i++] = char .MinValue.ToString(); res[i++] = long .MaxValue.ToString(); res[i++] = ((long)0) .ToString(); res[i++] = long .MinValue.ToString(); res[i++] = 3.14f.ToString(); res[i++] = 10f .ToString(); res[i++] = 0.1f .ToString(); res[i++] = float .MaxValue.ToString(); res[i++] = float .MinValue.ToString(); res[i++] = double.MaxValue.ToString(); res[i++] = double.MinValue.ToString(); System.Text.StringBuilder sb = new System.Text.StringBuilder(); sb.AppendFormat( "Test {0:X8} {2} {1} End", 234, "", -212 ); res[i++] = sb.ToString(); return res; } private static void TestGenericOpenClasses() { var obj = new GenericClassTest(); for(int i = 0; i < 20; i++) { obj.Test1( i, i * 2 ); } } private static int TestMethodInjection() { TargetForInjection obj = new TargetForInjection(); int c = 4; return obj.EmptyMethod( 2, 3, ref c ); } struct TestTrackStack { public object a; public object b; public object c; public object d; } static TestTrackStack Start( object a , object b , object c , object d ) { TestTrackStack st = new TestTrackStack(); st.a = a; st.b = b; st.c = c; st.d = d; return st; } private static void GCStress( ref object p, object s ) { GC.Collect(); p = s; } static unsafe void Main() { #if INCLUDE_VERIFICATION mscorlib_UnitTest.Verification.Verify.RunVerification(); #endif //--// #if GC_TEST_MULTIPOINTER_STRUCTS TestTrackStack st = Start( 1, 2, 3, 4 ); Console.WriteLine( "{0}", st.a ); GC.Collect(); Console.WriteLine( "{0}", st.b ); GC.Collect(); Console.WriteLine( "{0}", st.c ); GC.Collect(); Console.WriteLine( "{0}", st.d ); GC.Collect(); #elif GC_STRESS while(true) { TestFloatingPoint(); object[] array = new object[120]; array[3] = array; GCStress( ref array[5], array ); } #elif BITFIELD_TEST TestTrackStack st = Start( 1, 2, 3, 4 ); st.d = 23; TestBitField(); #else TestFinalizers(); TestSyncBlocks(); TestArrayBoundChecks(); TestCheckedOperations( 2, 3, 4 ); DelegateTester.Run(); TestArrayInitializers(); TestToString(); TestList(); TestDictionary(); TestFloatingPoint(); TestExceptions(); TestEvents(); TestTime(); TestTimers(); TestGenericOpenClasses(); TestMethodInjection(); #endif } } } ================================================ FILE: Zelig/Zelig/RunTime/Framework/mscorlib_UnitTest/Properties/AssemblyInfo.cs ================================================ using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; // General Information about an assembly is controlled through the following // set of attributes. Change these attribute values to modify the information // associated with an assembly. [assembly: AssemblyTitle( "mscorlib_UnitTest" )] [assembly: AssemblyDescription( "" )] [assembly: AssemblyConfiguration( "" )] [assembly: AssemblyCompany( "Microsoft" )] [assembly: AssemblyProduct( "mscorlib_UnitTest" )] [assembly: AssemblyCopyright( "Copyright © Microsoft 2006" )] [assembly: AssemblyTrademark( "" )] [assembly: AssemblyCulture( "" )] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. //[assembly: ComVisible( false )] // The following GUID is for the ID of the typelib if this project is exposed to COM //[assembly: Guid( "790c97c2-f14c-473e-a9eb-1b72d95bad30" )] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // [assembly: AssemblyVersion( "1.0.0.0" )] [assembly: AssemblyFileVersion( "1.0.0.0" )] ================================================ FILE: Zelig/Zelig/RunTime/Framework/mscorlib_UnitTest/Resources/ZeligRefreshBinaryDrop.cmd ================================================ @echo off setlocal cd/d %SDXROOT%\Zelig if /I "%1" == "full" (set msbuild_opt=/t:Rebuild) msbuild Zelig.sln %msbuild_opt% /p:Configuration=Debug msbuild Zelig.sln %msbuild_opt% /p:Configuration=Release cd %SDXROOT%\Zelig\BinaryDrop sd edit ... rd/s/q %SDXROOT%\Zelig\BinaryDrop md %SDXROOT%\Zelig\BinaryDrop\Host md %SDXROOT%\Zelig\BinaryDrop\Target xcopy/s/e %SDXROOT%\ZeligBuild\Host\bin %SDXROOT%\Zelig\BinaryDrop\Host xcopy/s/e %SDXROOT%\ZeligBuild\Target\bin %SDXROOT%\Zelig\BinaryDrop\Target del/s *.vshost.exe* sd add ... sd online ... sd revert -a ... ================================================ FILE: Zelig/Zelig/RunTime/Framework/mscorlib_UnitTest/Test_OpenClasses.cs ================================================ namespace mscorlib_UnitTest { using System; using System.Collections.Generic; using System.Runtime.CompilerServices; using Microsoft.Zelig.Runtime; public class BaseClassToExtend1 { public static int s_b = 1; int m_a; public BaseClassToExtend1( int a ) { m_a = a; } private int Test1( int a ) { return a + 1; } public int Test2( int b ) { return b; } } [ExtendClass(typeof(BaseClassToExtend1))] class ExtensionTest1 { public static int s_c = 3; int m_b; [MergeWithTargetImplementation] public ExtensionTest1( int a ) { m_b = a; } [AliasForBaseMethod( "Test1" )] [MethodImpl( MethodImplOptions.InternalCall )] private extern int BaseTest1( int a ); private int Test1( int a ) { return a + 2; } public int SubTest1( int a ) { return BaseTest1( a + 1 ); } } //--// class TargetForInjection { public int EmptyMethod( int a, int b, ref int c ) { return a + b; } } [ExtendClass(typeof(TargetForInjection), NoConstructors=true)] class SourceForInjection1 { [InjectAtEntryPoint] public void EmptyMethod( int a, int b, ref int c ) { c = a - b; } [InjectAtExitPoint] public int EmptyMethod( int a, int b, ref int c, int res ) { return res * a; } } [ExtendClass(typeof(TargetForInjection), NoConstructors=true, ProcessAfter=typeof(SourceForInjection1))] class SourceForInjection2 { [InjectAtEntryPoint] public void EmptyMethod( int a, int b, ref int c ) { c = c * 2; } [InjectAtExitPoint] public int EmptyMethod( int a, int b, ref int c, int res ) { return res - 10; } } public class BaseGenericClassToExtend< T > { [NoInline] public T Test1( T a , T b ) { return a; } } [ExtendClass(typeof(BaseGenericClassToExtend<>), NoConstructors=true)] class GenericExtensionTest { [NoInline] public T Test1( T a , T b ) { return b; } } public class GenericClassTest : BaseGenericClassToExtend { } } ================================================ FILE: Zelig/Zelig/RunTime/Framework/mscorlib_UnitTest/Verify.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // namespace mscorlib_UnitTest { using System; using System.Threading; using System.Collections; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using System.Reflection; public class Debug { [Microsoft.Zelig.Runtime.NoInline] public static void Print( string txt ) { //throw new NotImplementedException(); } public static int AvailableMemory() { return 0;//throw new NotImplementedException(); } } } namespace mscorlib_UnitTest.Verification { using System; using System.Threading; using System.Collections; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using System.Reflection; class Foo { } class Bar { } class TestReferences { void Method1( ref int a ) { a = a + 1; } void Method2( ref object o ) { o = o.GetType(); } void Method3( ref Type t ) { t = t.BaseType; } void Method4( ref DateTime d ) { d = d.Add( new TimeSpan( 1, 2, 3, 4, 5 ) ); } void Tester() { int i = 13; int[] i_a = new int[10]; object o = "Test"; object[] o_a = new object[5]; Type t = this.GetType(); DateTime d = DateTime.Now; Method1( ref i ); Method1( ref i_a[2] ); Method2( ref o ); Method2( ref o_a[3] ); Method3( ref t ); Method4( ref d ); } } public class TestReferences2 { static void Test1( int v ) { Debug.Print( "Test1: " + v + " " + v.GetType().FullName ); } static void Test2( ref int v ) { Debug.Print( "Test2: " + v + " " + v.GetType().FullName ); v++; } static void Test3( Enum v ) { Debug.Print( "Test3: " + v + " " + v.GetType().FullName ); } static void Test4( ref Enum v ) { Debug.Print( "Test4: " + v + " " + v.GetType().FullName ); v = Resources.Tag.TIME; } static void Test5( TestEnum v ) { Debug.Print( "Test5: " + v + " " + v.GetType().FullName ); } static void Test6( ref TestEnum v ) { Debug.Print( "Test6: " + v + " " + v.GetType().FullName ); v++; } static void Test7( DateTime v ) { Debug.Print( "Test7: " + v.ToString() + " " + v.GetType().FullName ); } static void Test8( ref DateTime v ) { Debug.Print( "Test8: " + v.ToString() + " " + v.GetType().FullName ); v += new TimeSpan( 1, 1, 1 ); } static void Test9( object v ) { Debug.Print( "Test9: " + v.ToString() + " " + v.GetType().FullName ); } static void TestA( ref object v ) { Debug.Print( "TestA: " + v.ToString() + " " + v.GetType().FullName ); v = 1; } static public void TestPlain() { int i = 100; TestEnum e = TestEnum.P1; Enum e2 = e; DateTime d = DateTime.Now; Test2( ref i ); Test1( i ); Test4( ref e2 ); Test3( e2 ); Test6( ref e ); Test5( e ); Test8( ref d ); Test7( d ); } static public void TestArray() { int [] i = new int [1]; i [0] = 100; TestEnum[] e = new TestEnum[1]; e [0] = TestEnum.P1; Enum [] e2 = new Enum [1]; e2[0] = e[0]; DateTime[] d = new DateTime[1]; d [0] = DateTime.Now; object [] o = new object [1]; o [0] = 3.0; Test2( ref i [0] ); Test1( i [0] ); Test4( ref e2[0] ); Test3( e2[0] ); Test6( ref e [0] ); Test5( e [0] ); Test8( ref d [0] ); Test7( d [0] ); TestA( ref o [0] ); Test9( o [0] ); } } public class TestSpecialValueTypes { static int DateTimeByRef( ref DateTime dt ) { int res = dt.Month; dt += new TimeSpan( 0, 1, 2 ); Debug.Print( "DateTimeByRef " + dt.ToString() ); return res; } static public void DateTimeUsage() { DateTime dt1; DateTime dt2 = DateTime.Now; int day = dt2.Day; dt1 = dt2; object o = dt1; Debug.Print( "Type " + o.GetType().FullName ); DateTime[] da1 = new DateTime[2]; DateTimeByRef( ref da1[0] ); DateTimeByRef( ref dt1 ); Debug.Print( "DateTimeUsage " + dt1 .ToString() ); Debug.Print( "DateTimeUsage " + da1[0].ToString() ); Debug.Print( "DateTimeUsage " + da1[1].ToString() ); } } // [AttributeUsage(AttributeTargets.All,Inherited=true)] // public class Local2Attribute : Microsoft.SPOT.LocalAttribute // { // public Local2Attribute( string name ) : base(name) // { // this.length = 20; // } // // public Local2Attribute( string name, int length ) : base(name) // { // this.length = length; // } // // public string extra; // } // // [AttributeUsage(AttributeTargets.All,Inherited=true)] // public class Local3Attribute : Attribute // { // public string info; // } // // public enum EnumTester // { // [Microsoft.SPOT.LocalAttribute("name of Value1", active=true , length=32)] Value1 = 12, // [Microsoft.SPOT.LocalAttribute("name of Value2", active=false, length=64)] Value2 = 14, // [Local3 (info="name of Value2" )] Value3 = 15, // } // // [Microsoft.SPOT.Local("name of AttributeTester|name of AttributeTester|name of AttributeTester|name of AttributeTester|name of AttributeTester|name of AttributeTester", active=false)] // public class AttributeTester // { // [Local2("name of Field1", 66, active=true)] // public int Field1; // // [Local2("name of Method1", length=100, target=typeof(Value), extra="we")] // public void Method1( int i ) // { // } // } [StructLayout(LayoutKind.Sequential)] struct Value { public int i1; public int i2; public string s1; public Value( int i ) { i1 = i; i2 = 0; s1 = null; } public int Result() { return i1 + i2; } } enum TestEnum :byte { P1 = 1, P2 = 2, P3 = 3, } enum TestEnum2 :short { S1 = 1, S2 = 2, S3 = 3, } public class Resources { public enum Tag { TIME, } } delegate int Compute( int a, int b, Value v ); delegate void OnKey( int a ); interface Interface { short Method1( int c ); int Method2( int a, int b, Value v ); } //--// ////public class InvokeTestBed ////{ //// public enum FooEnum //// { //// Blah, //// } //// //// public void MethodInt( int t ) //// { //// Debug.Print( t.GetType().ToString() ); //// } //// //// public void MethodEnum( FooEnum t ) //// { //// Debug.Print( t.GetType().ToString() ); //// } ////} //--// public class FinalizeTest { protected int m_id; public FinalizeTest( int id ) { m_id = id; } ~FinalizeTest() { Debug.Print( "~FinalizeTest " + m_id ); Thread.Sleep( 100 ); } } public class FinalizeTest2 : FinalizeTest { public FinalizeTest m_child; public FinalizeTest2( int id ) : base( id ) { m_child = new FinalizeTest( id + 1 ); } ~FinalizeTest2() { Debug.Print( "~FinalizeTest2 " + m_id ); if(m_id == 4 && m_child != null) { System.GC.SuppressFinalize( m_child ); } } } //--// class Verify : Interface { [Serializable] public struct DayState { //If the temperature is unknown, it is sent down as sbyte.MinValue (-128) public sbyte m_high; public sbyte m_low; public DayState( sbyte high, sbyte low ) { m_high = high; m_low = low; } } public class Sub1 { public interface SubInterface { short Method1( int c ); } public class Sub2 : SubInterface { short Verify.Sub1.SubInterface.Method1( int c ) { return 1; } } } //static int s_i = 1; //static string s_s = "test static"; static object s_o = new Object(); OnKey m_onKey; public void Thread_Start1() { const int limit = 100000; for(int i=1000000; i<1000000+limit;i++) { } } public short Method1( int c ) { return (short)(c * 10); } public int Method2( int a, int b, Value v ) { Thread.Sleep( 50 ); return a + b + v.i1; } public int Method2( int a, int b, Value v, DateTime dt ) { Thread.Sleep( 50 ); return a + b + v.i1; } static public int Method2_b( int a, int b, Value v ) { return a + b * v.i1; } static public int Method3( int a, out int b, ref int c ) { b = a + c; c = a * 2; return a + b + c; } [MethodImplAttribute(MethodImplOptions.Synchronized)] public int Method4( params int[] a ) { return a.Length; } [MethodImplAttribute(MethodImplOptions.Synchronized)] static public int Method4s( params int[] a ) { return a.Length; } public void Method5( TestEnum e ) { switch(e) { case TestEnum.P1: Debug.Print( "P1" ); break; case TestEnum.P2: Debug.Print( "P2" ); break; case TestEnum.P3: Debug.Print( "P3" ); break; } } public void Method6( Enum e ) { Debug.Print( "Enum: " + e.GetType().FullName ); Method6( ref e ); } public void Method6( object state ) { Debug.Print( "Timer: " + DateTime.Now.ToString() + " " + state.GetType().FullName ); } public void Method6( ref Enum e ) { Debug.Print( "EnumByRef: " + e.GetType().FullName ); } public void TestEvent1( int a ) { Debug.Print( "TestEvent1: " + a ); } static public void TestEvent2( int a ) { Debug.Print( "TestEvent2: " + a ); } static public void TestEvent3( int a ) { Debug.Print( "TestEvent3: " + a ); } //--// private void TestNumeric() { int i; int s1 = 1242323; long l1 = 1298182; long l2 = -1242323; long[] l3 = new long[5]; ulong ul1 = 1298182; ulong ul2 = 1242323; ulong[] ul3 = new ulong[5]; long[] sl3 = new long[5]; double[] fl3 = new double[4]; ul3[0] = ul1 + ul2; ul3[1] = ul1 - ul2; ul3[2] = ul1 * ul2; ul3[3] = ul1 / ul2; ul3[4] = ul1 % ul2; for(i=0; i" + s2.Trim () + "<" ); Debug.Print( "Trim : >" + s2.TrimEnd () + "<" ); Debug.Print( "Trim : >" + s2.TrimStart() + "<" ); s2 = "!@# white space !@#"; Debug.Print( "Trim : >" + s2.Trim ( '!', '@', '#' ) + "<" ); Debug.Print( "Trim : >" + s2.TrimEnd ( '!', '@', '#' ) + "<" ); Debug.Print( "Trim : >" + s2.TrimStart( '!', '@', '#' ) + "<" ); Debug.Print( "IndexOf: " + s2.IndexOf( 'w' ) ); Debug.Print( "IndexOf: " + s2.IndexOf( 'w', 4 ) ); Debug.Print( "IndexOf: " + s2.IndexOf( 'w', 10 ) ); Debug.Print( "IndexOf: " + s2.IndexOf( 'w', 4, 7 ) ); Debug.Print( "IndexOf: " + s2.IndexOf( 'w', 4, 3 ) ); Debug.Print( "IndexOfAny : " + s2.IndexOfAny ( new char[] { 'a', 'd' } ) ); Debug.Print( "IndexOf : " + s2.IndexOf ( "spa" ) ); Debug.Print( "LastIndexOf: " + s2.LastIndexOf( ' ' ) ); Debug.Print( "IndexOf: " + "Multiple\nLines\nTest".IndexOf( '\n' ) ); Debug.Print( "ToUpper: " + "Multiple Cases Test".ToUpper() ); Debug.Print( "ToLower: " + "Multiple Cases Test".ToLower() ); s2 = new string( '#', 80 ); Debug.Print( ".ctor : >" + s2 + "<" ); ca = new char[4]; ca[0] = 'a'; ca[1] = 'b'; ca[2] = 'c'; ca[3] = 'd'; s2 = new string( ca ); Debug.Print( ".ctor : >" + s2 + "<" ); s2 = new string( ca, 1, 2 ); Debug.Print( ".ctor : >" + s2 + "<" ); } private void TestValueTypes() { Interface itf = this; Value v1 = new Value( 1 ); Value v2; v1.i1 = 2; v2 = v1; v2.i1 = itf.Method1( 1 ); v2.i2 = itf.Method2( 1, 2, v1 ); } private int TestDayState( ref DayState a ) { a.m_low *= 2; return a.m_high; } private void TestValueTypeArrayReferences() { DayState[] nat_cities = new DayState[2]; int i = 1; nat_cities[i] = new DayState( 50, 37 ); DayState d = nat_cities[i]; Debug.Print( "High assign = " + d .m_high ); Debug.Print( "High direct = " + nat_cities[i].m_high ); d.m_low = 10; TestDayState( ref d ); Debug.Print( "Low assign = " + d.m_low ); nat_cities[i].m_low = 15; TestDayState( ref nat_cities[i] ); Debug.Print( "Low direct = " + nat_cities[i].m_low ); } private int TestBoxing() { Value v1 = new Value( 1 ); int i; try { object o1 = v1; object o2 = 3; o1.Equals( new Value() ); Value v3 = (Value)o1; int i3 = (int)o2; Debug.Print( "Int: " + i3 ); Debug.Print( "Val: " + v3.i1 ); } catch(Exception e) { Debug.Print( "Exception: " + e ); i = 1; } finally { i = 2; } return i; } private void TestExceptions() { try { try { Debug.Print( "Exception: 1" ); } finally { Debug.Print( "Exception: 2" ); try { Exception e = new Exception( "test" ); throw e; } catch { Debug.Print( "Exception: 2b" ); throw; } finally { Debug.Print( "Exception: 3" ); } } } catch(Exception) { Debug.Print( "Exception: 4" ); } finally { Debug.Print( "Exception: 5" ); } // // Nesting test // try { try { Debug.Print( "Exception: 1" ); } catch(Exception) { Debug.Print( "Exception: 3" ); } finally { Debug.Print( "Exception: 4" ); } try { Debug.Print( "Exception: 5" ); throw new Exception(); } catch(Exception) { Debug.Print( "Exception: 7" ); } finally { Debug.Print( "Exception: 8" ); throw new Exception(); } } catch(Exception) { try { Debug.Print( "Exception: 10" ); } catch { Debug.Print( "Exception: 11" ); } } finally { Debug.Print( "Exception: 12" ); } } private void TestArrays() { object[] ar = new Object[20]; int a = 1; int c = 4; ////////////////////////////////////////////////////////////////////////////////////// // // Array tests. // ar[0] = this; string[] ars = new string[10]; ars[0] = "test"; ars[2] = "test2"; foreach(string s in ars) { int len = s != null ? s.Length : 0; } object[] ar2 = new object[5]; System.Array.Copy( ar, 0, ar2, 2, 3 ); Debug.Print( "System.Array.Copy: " + (ar2[2] != null) ); Debug.Print( "System.Array.Clear: " + (ar[0] != null) ); System.Array.Clear( ar, 0, ar.Length ); Debug.Print( "System.Array.Clear: " + (ar[0] != null) ); try { string[] ar3 = new string[10]; object[] ar4 = ar3; DateTime[] ar5 = new DateTime[2]; ar[0] = this; System.Array.Copy( ar, ar4, 10 ); Debug.Print( "System.Array.Copy: Incompatible types: FAIL" ); } catch { Debug.Print( "System.Array.Copy: Incompatible types: SUCCESS" ); } ////////////////////////////////////////////////////////////////////////////////////// // // More array tests and Exception tests. // string s1 = a.ToString(); ar[1] = a; c = (int)ar[1]; } private void TestArrayList() { ArrayList lst = new ArrayList(); int i; Debug.Print( "System.ArrayList.Add : " + lst.Add( 1 ) ); Debug.Print( "System.ArrayList.Add : " + lst.Add( "test" ) ); Debug.Print( "System.ArrayList.Contains : " + lst.Contains( 1 ) ); lst.Insert( 1, "ll" ); Debug.Print( "System.ArrayList.IndexOf : " + lst.IndexOf( "test" ) ); i = 0; foreach(object o in lst) { Debug.Print( "System.ArrayList.Enum : " + i++ + " " + o ); } //--// lst = new ArrayList(); lst.Add( "string" ); lst.Add( "test" ); lst.Add( null ); string[] arS = new string[3]; lst.CopyTo( arS ); //--// lst = new ArrayList(); lst.Add( new Foo() ); lst.Add( null ); Foo[] arO = new Foo[3]; lst.CopyTo( arO ); //--// lst = new ArrayList(); lst.Add( TestEnum.P2 ); TestEnum[] arE = new TestEnum[3]; lst.CopyTo( arE ); Debug.Print( "lst.CopyTo( arE ); " + arE[0].ToString() ); //--// lst = new ArrayList(); lst.Add( 12 ); lst.Add( 532 ); lst.Add( 12 ); int[] arI = new int[3]; lst.CopyTo( arI ); ArrayList lst2 = (ArrayList)lst.Clone(); Debug.Print( "System.ArrayList.Clone " + (lst2.Count == lst.Count) ); lst2.RemoveAt( 0 ); Debug.Print( "System.ArrayList.Clone " + (lst2[0] == lst[1]) ); try { lst.CopyTo( arS ); Debug.Print( "Invalid lst.CopyTo( arS ); FAILURE" ); } catch { Debug.Print( "Invalid lst.CopyTo( arS ); SUCCESS" ); } try { lst[1] = (byte)12; lst.CopyTo( arI ); Debug.Print( "Invalid lst.CopyTo( arI ); FAILURE" ); } catch { Debug.Print( "Invalid lst.CopyTo( arI ); SUCCESS" ); } try { arI = new int[1]; lst.CopyTo( arI ); Debug.Print( "Invalid lst.CopyTo( arI ); FAILURE" ); } catch { Debug.Print( "Invalid lst.CopyTo( arI ); SUCCESS" ); } } private void TestDelegates() { Interface itf = this; Value v1 = new Value( 1 ); Compute cmp = new Compute( itf.Method2 ); Compute cmp2 = new Compute( Verify.Method2_b ); cmp ( 1, 2, v1 ); cmp2( 1, 2, v1 ); this.m_onKey += new OnKey( this .TestEvent1 ); this.m_onKey += new OnKey( Verify.TestEvent2 ); this.m_onKey += new OnKey( Verify.TestEvent3 ); this.m_onKey -= new OnKey( Verify.TestEvent2 ); this.m_onKey -= new OnKey( Verify.TestEvent3 ); this.m_onKey -= new OnKey( Verify.TestEvent3 ); // Removing entry not in the list. Should do nothing. this.m_onKey += new OnKey( Verify.TestEvent3 ); this.m_onKey += new OnKey( Verify.TestEvent2 ); this.m_onKey += new OnKey( Verify.TestEvent2 ); // Adding entry already in the list. Should do nothing. this.m_onKey( 12 ); //// Verify testWeak = new Verify( 1, 2 ); //// //// this.m_onKey = (OnKey)Microsoft.SPOT.WeakDelegate.Combine( this.m_onKey, new OnKey( testWeak.TestEvent1 ) ); //// this.m_onKey -= new OnKey( Verify.TestEvent3 ); //// this.m_onKey += new OnKey( Verify.TestEvent3 ); //// this.m_onKey( 12 ); //// //// testWeak = null; System.GC.Collect(); this.m_onKey( 12 ); this.m_onKey -= new OnKey( Verify.TestEvent3 ); } //// private void TestGetType( string typeName, bool fShouldExist ) //// { //// Type t = Type.GetType( typeName ); //// bool fExist = (t != null); //// string res = (fExist == fShouldExist) ? "OK" : "FAIL"; //// //// Debug.Print( typeName + " : " + res ); //// } //// //// private void TestReflection() //// { //// Interface itf = this; //// Compute cmp = new Compute( itf.Method2 ); //// //// object cmp_m = cmp.Method; //// object cmp_t = cmp.Target; //// Type t1; //// //// t1 = typeof(string[]); //// t1 = cmp.GetType(); //// t1 = this.GetType(); //// //// TestGetType( "System.Object" , true ); //// TestGetType( "Microsoft.SPOT.Verification.Verify+Sub1+Sub2" , true ); //// TestGetType( "Microsoft.SPOT.Verification.Verify+Sub3" , false ); //// TestGetType( "Microsoft.SPOT.Verification.Verify+Sub1+Sub2+Sub3", false ); //// //// ConstructorInfo ci = t1.GetConstructor( new Type[] { typeof(int), typeof(int) } ); //// object resCI = ci.Invoke( new Object[] { 2, 12 } ); //// //// MethodInfo mi = t1.GetMethod( "Method1", new Type[] { typeof(int) } ); //// //// object res = mi.Invoke( this, new Object[] { 2 } ); //// if(res is short) //// { //// Debug.Print( "Invoke: " + (short)res ); //// } //// else //// { //// Debug.Print( "Invoke: " ); //// } //// //// Type[] at = Microsoft.SPOT.Reflection.GetTypesImplementingInterface( typeof(Interface) ); //// if(at != null) //// { //// foreach(Type t2 in at) //// { //// ConstructorInfo ci2 = t2.GetConstructor( new Type[] { typeof(int), typeof(int) } ); //// object resCI2 = ci2.Invoke( new Object[] { 2, 12 } ); //// //// Interface itf2 = (Interface)resCI2; //// } //// } //// //// Assembly[] aa = Microsoft.SPOT.Reflection.GetAssemblies(); //// foreach(Assembly a in aa) //// { //// Debug.Print( "name: " + a.FullName + " - " + Microsoft.SPOT.Reflection.GetAssemblyHash( a ) ); //// } //// //// // Type t3 = typeof(string[,]); //// //// // Value v2 = new Value( 3 ); //// // int i2 = v2.Result(); //// //// // v.i1 = itf.Method1( 1 ); //// // v.i2 = itf.Method2( 1, 2, v ); //// //// object oCls = this; //// bool ba = oCls is Interface; //// bool bb = oCls is Type; //// bool bc = oCls is Verify; //// //// FooBar.TestFOO(); //// FooBar.TestBAR(); //// //// typeof(InvokeTestBed).GetMethod( "MethodInt" ).Invoke( new InvokeTestBed(), new object [] { 1 } ); //// typeof(InvokeTestBed).GetMethod( "MethodEnum" ).Invoke( new InvokeTestBed(), new object [] { InvokeTestBed.FooEnum.Blah } ); //// } private void TestThread_AbortWorker() { try { while(true); } catch(ThreadAbortException e) { Debug.Print( "ThreadAbortException: " + e.ToString() ); } catch( Exception e1 ) { Debug.Print( "Generic Exception: " + e1.ToString() ); } finally { Debug.Print( "Finally block" ); } } public void TestThread_Abort() { Thread t = new Thread( new ThreadStart( TestThread_AbortWorker ) ); t.Start(); Thread.Sleep(1000); t.Abort(); Thread.Sleep(1000); t.Join(); } //--// private void TestDateTime() { DateTime dt1; DateTime dt1b; DateTime dt2; TimeSpan ts1; TimeSpan ts2 = new TimeSpan( 1, 0, 0 ); TimeSpan ts3 = new TimeSpan( 1, 0, 0, 0 ); dt1 = new DateTime( 2003, 1, 1 ); Debug.Print( "Microsoft.SPOT.ExtendedTimeZone.c_TicksTo20030101 " + dt1.ToString() ); dt1 = dt1.Add( ts2 ) ; Debug.Print( "dt1 = dt1.Add( ts2 ) " + dt1.ToString() ); dt1 = dt1.AddTicks( 10 * 1000 * 1000 ); Debug.Print( "dt1 = dt1.AddTicks( 10 * 1000 * 1000 ) " + dt1.ToString() ); Debug.Print( "dt1.Date " + dt1.Date.ToString() ); Debug.Print( "dt1.Ticks " + dt1.Ticks.ToString() ); Debug.Print( "dt1.TimeOfDay " + dt1.TimeOfDay.ToString() ); ts1 = dt1.Subtract( new DateTime( 2003, 1, 1 ) ); Debug.Print( ts1.ToString() ); dt1 = dt1.Subtract( ts3 ); Debug.Print( "dt1 = dt1.Subtract( ts3 ) " + dt1.ToString() ); dt2 = dt1 + ts2 ; Debug.Print( "dt2 = dt1 + ts2 " + dt2.ToString() ); dt2 = dt1 - ts2 ; Debug.Print( "dt2 = dt1 - ts2 " + dt2.ToString() ); ts1 = dt1 - dt2 ; Debug.Print( "ts1 = dt1 - dt2 " + ts1.ToString() ); dt1b = dt1; Debug.Print( "(dt1 < dt2) " + (dt1 < dt2 ) ); Debug.Print( "(dt1 > dt2) " + (dt1 > dt2 ) ); Debug.Print( "(dt1 >= dt2) " + (dt1 >= dt2 ) ); Debug.Print( "(dt1 <= dt2) " + (dt1 <= dt2 ) ); Debug.Print( "(dt1 >= dt1) " + (dt1 >= dt1b) ); Debug.Print( "(dt1 <= dt1) " + (dt1 <= dt1b) ); Debug.Print( "(dt1 == dt1) " + (dt1 == dt1b) ); Debug.Print( "(dt1 != dt1) " + (dt1 != dt1b) ); Debug.Print( "DateTime.Compare( dt1, dt2 ) " + DateTime.Compare( dt1, dt2 ) ); Debug.Print( "DateTime.Compare( dt2, dt1 ) " + DateTime.Compare( dt2, dt1 ) ); Debug.Print( "DateTime.Compare( dt1, dt1 ) " + DateTime.Compare( dt1, dt1 ) ); Debug.Print( "DateTime.Equals ( dt1, dt1 ) " + DateTime.Equals ( dt1, dt1 ) ); Debug.Print( "DateTime.Equals ( dt1, dt2 ) " + DateTime.Equals ( dt1, dt2 ) ); Debug.Print( "dt1.AddMilliseconds( 1.0 ) " + dt1.AddMilliseconds( 1.0 ).ToString() ); Debug.Print( "dt1.AddSeconds ( 1.0 ) " + dt1.AddSeconds ( 1.0 ).ToString() ); Debug.Print( "dt1.AddMinutes ( 1.0 ) " + dt1.AddMinutes ( 1.0 ).ToString() ); Debug.Print( "dt1.AddHours ( 1.0 ) " + dt1.AddHours ( 1.0 ).ToString() ); Debug.Print( "dt1.AddDays ( 1.9 ) " + dt1.AddDays ( 1.9 ).ToString() ); } private void TestTimeSpan() { TimeSpan ts1 = new TimeSpan( 1, 2, 3, 4, 567 ); Debug.Print( "ts1.Ticks " + ts1.Ticks .ToString() ); Debug.Print( "ts1.Days " + ts1.Days .ToString() ); Debug.Print( "ts1.Hours " + ts1.Hours .ToString() ); Debug.Print( "ts1.Minutes " + ts1.Minutes .ToString() ); Debug.Print( "ts1.Seconds " + ts1.Seconds .ToString() ); Debug.Print( "ts1.Milliseconds " + ts1.Milliseconds.ToString() ); Debug.Print( "ts1.Add( ts1 ) " + ts1.Add( ts1 ) .ToString() ); Debug.Print( "-ts1 " + (-ts1) .ToString() ); Debug.Print( "-ts1.Duration " + (-ts1).Duration().ToString() ); } private void TestTime() { DateTime dt = DateTime.Now; Debug.Print( dt.ToString() ); TimeSpan ts = new TimeSpan( 1, 20, 12, 30, 100 ); Debug.Print( ts.ToString() ); ts = ts.Add( new TimeSpan( 0, 0, 10 ) ); Debug.Print( ts.ToString() ); DateTime dt2 = dt; dt = dt.Add( ts ); Debug.Print( dt.ToString() ); TimeSpan ts2 = dt.Subtract( dt2 ); Debug.Print( ts2.ToString() ); Debug.Print( ts2.Days.ToString() ); Debug.Print( ts2.Hours.ToString() ); Debug.Print( ts2.Minutes.ToString() ); Debug.Print( ts2.Seconds.ToString() ); dt = dt.Subtract( ts ); Debug.Print( dt.ToString() ); Debug.Print( TimeSpan.MaxValue.ToString() ); Debug.Print( TimeSpan.Zero .ToString() ); Debug.Print( TimeSpan.MinValue.ToString() ); Debug.Print( DateTime.MaxValue.ToString() ); Debug.Print( DateTime.MinValue.ToString() ); Debug.Print( "############################" ); } private void WaitButton() { Thread.Sleep( 1000 ); } private void TestTimers() { Timer timer = new Timer( new TimerCallback( this.Method6 ), 1, 1000, 2000 ); Thread t = new Thread( new ThreadStart( this.Thread_Start1 ) ); t.Start(); for(int i=0; i<10; i++) { } WaitButton(); ////////////////////////////////////////////////////////////////////////////////////// // // More Timer and Threading tests. // timer.Change( 1000, 500 ); t.Abort(); t.Join(); Debug.Print( "Timer wait" ); // // Test timer object release // timer = new Timer( new TimerCallback( this.Method6 ), "test", new TimeSpan( 1000 * 10000 ), new TimeSpan( 1000 * 10000 ) ); timer = null; Debug.Print( "Timer alive..." ); Thread.Sleep( 3000 ); System.GC.Collect(); Debug.Print( "Timer should be dead. Press button to continue." ); WaitButton(); //// Microsoft.SPOT.ExtendedTimer timer2; //// //// Debug.Print( "Extended Timer 1" ); //// timer2 = new Microsoft.SPOT.ExtendedTimer( new TimerCallback( this.Method6 ), "test", 1000, 1000 ); //// Thread.Sleep( 3000 ); //// timer2.Dispose(); //// //// Debug.Print( "Extended Timer 2" ); //// timer2 = new Microsoft.SPOT.ExtendedTimer( new TimerCallback( this.Method6 ), "test", new DateTime( 2012, 12, 1, 14, 0, 2 ), new TimeSpan( 1000 * 10000 ) ); //// Debug.Print( "Now: " + DateTime.Now.ToString() ); //// Thread.Sleep( 1000 ); //// //// Microsoft.SPOT.Hardware.Utility.SetLocalTime( new DateTime( 2012, 12, 1, 14, 0, 0 ) ); //// Debug.Print( "Now: " + DateTime.Now.ToString() ); //// Thread.Sleep( 4000 ); //// timer2.Dispose(); //// //// Debug.Print( "Extended Timer 3" ); //// Thread.Sleep( 500 ); //// //// timer2 = new Microsoft.SPOT.ExtendedTimer( new TimerCallback( this.Method6 ), "test", Microsoft.SPOT.ExtendedTimer.TimeEvents.Minute ); //// Microsoft.SPOT.Hardware.Utility.SetLocalTime( new DateTime( 2012, 12, 1, 14, 0, 58 ) ); //// Debug.Print( "Now: " + DateTime.Now.ToString() ); //// //// Debug.Print( "Waiting on TimeEvents.Minute. Press button to continue." ); WaitButton(); //// //// timer2.Dispose(); //// //// Debug.Print( "Extended Timer 4" ); //// timer2 = new Microsoft.SPOT.ExtendedTimer( new TimerCallback( this.Method6 ), "test", Microsoft.SPOT.ExtendedTimer.TimeEvents.Hour ); //// Microsoft.SPOT.Hardware.Utility.SetLocalTime( new DateTime( 2012, 12, 1, 14, 59, 58 ) ); //// Debug.Print( "Now: " + DateTime.Now.ToString() ); //// //// Debug.Print( "Waiting on TimeEvents.Hour. Press button to continue." ); WaitButton(); //// //// Debug.Print( "Last Expiration: " + timer2.LastExpiration.ToString() ); //// timer2.Dispose(); //// //// Debug.Print( "Extended Timer 5" ); //// timer2 = new Microsoft.SPOT.ExtendedTimer( new TimerCallback( this.Method6 ), "test", Microsoft.SPOT.ExtendedTimer.TimeEvents.SetTime ); //// //// Debug.Print( "Press button to change time." ); WaitButton(); //// Microsoft.SPOT.Hardware.Utility.SetLocalTime( new DateTime( 2012, 12, 2, 14, 59, 58 ) ); //// Debug.Print( "Now: " + DateTime.Now.ToString() ); //// Debug.Print( "Waiting on TimeEvents.SetTime. Press button to continue." ); WaitButton(); //// //// timer2.Dispose(); } //// private void TestRegionConfiguration() //// { //// DateTime dt_20030101 = new DateTime( 2003, 01, 01 ); //// DateTime dt_20030420 = new DateTime( 2003, 04, 20 ); //// DateTime dt_20030430 = new DateTime( 2003, 04, 30 ); // Wednesday //// DateTime dt_20030501 = new DateTime( 2003, 05, 01 ); //// DateTime dt_20030502 = new DateTime( 2003, 05, 02 ); //// //// DateTime dt_Sunday = dt_20030101.AddDays( DayOfWeek.Sunday - dt_20030101.DayOfWeek ); //// DateTime dt_Monday = dt_Sunday.AddDays( 1 ); //// DateTime dt_Tuesday = dt_Sunday.AddDays( 2 ); //// DateTime dt_Wednesday = dt_Sunday.AddDays( 3 ); //// DateTime dt_Thursday = dt_Sunday.AddDays( 4 ); //// DateTime dt_Friday = dt_Sunday.AddDays( 5 ); //// DateTime dt_Saturday = dt_Sunday.AddDays( 6 ); //// //// //// TimeSpan ts_080000 = new TimeSpan( 8, 0, 0 ); //// TimeSpan ts_170000 = new TimeSpan( 17, 0, 0 ); //// TimeSpan ts_180000 = new TimeSpan( 18, 0, 0 ); //// TimeSpan ts_200000 = new TimeSpan( 20, 0, 0 ); //// } private void TestFinalizers() { FinalizeTest ft1 = new FinalizeTest ( 1 ); FinalizeTest ft2 = new FinalizeTest2( 2 ); FinalizeTest ft3 = new FinalizeTest2( 4 ); System.GC.Collect(); Debug.Print( "GC 0: " + Debug.AvailableMemory() ); //Debug.DumpHeap(); ft1 = null; ft2 = null; ft3 = null; for(int i=1; i<10; i++) { System.GC.Collect(); Debug.Print( "GC " + i + ": " + Debug.AvailableMemory() ); //Debug.DumpHeap(); System.GC.WaitForPendingFinalizers(); //Thread.Sleep( 70 ); } } //// private void TestWeakReferences() //// { //// RPC_test.RecordSub r1 = new RPC_test.RecordSub(); //// System.WeakReference weak = new System.WeakReference( r1 ); //// //// System.GC.Collect(); //// Debug.Print( "Weak reference: " + weak.IsAlive ); //// //// r1 = null; //// //// System.GC.Collect(); //// Debug.Print( "Weak reference: " + weak.IsAlive ); //// //// //--// //// //// Microsoft.SPOT.ExtendedWeakReference restore; //// Microsoft.SPOT.ExtendedWeakReference weak2; //// ArrayList lst = new ArrayList(); //// int i; //// //// lst = new ArrayList(); //// //// while((restore = Microsoft.SPOT.ExtendedWeakReference.Recover( typeof(DateTime), 0 )) != null) //// { //// lst.Add( restore ); //// } //// //// for(i=0; i Debug AnyCPU 9.0.20706 2.0 {186F31A3-EF89-4A25-B2D5-20060509AA02} Exe Properties mscorlib_UnitTest mscorlib_UnitTest $(LlilumBuildRoot)\Target\obj\$(MSBuildProjectName)\ v4.5 true full false $(LlilumBuildRoot)\Target\bin\$(Configuration)\ DEBUG;TRACE prompt 4 true true true AllRules.ruleset AnyCPU false pdbonly true $(LlilumBuildRoot)\Target\bin\$(Configuration)\ TRACE prompt 4 true true true AllRules.ruleset AnyCPU false true full false $(LlilumBuildRoot)\Target\bin\$(Configuration)\ AnyCPU TRACE;DEBUG true true true false True True Files.resx {186F31A3-EF89-4A25-B2D5-20060501AA01} mscorlib False {186F31A3-EF89-4A25-B2D5-20061218AA01} Common False {186F31A3-EF89-4A25-B2D5-20060509AA01} Kernel False {186F31A3-EF89-4A25-B2D5-20060720AA01} TypeSystem False {186F31A3-EF89-4A25-B2D5-20070702AA01} system False Designer ResXFileCodeGenerator Files.Designer.cs ================================================ FILE: Zelig/Zelig/RunTime/Framework/system/Properties/AssemblyInfo.cs ================================================ using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; // General Information about an assembly is controlled through the following // set of attributes. Change these attribute values to modify the information // associated with an assembly. [assembly: AssemblyTitle( "System" )] [assembly: AssemblyDescription( "" )] [assembly: AssemblyConfiguration( "" )] [assembly: AssemblyCompany( "Microsoft" )] [assembly: AssemblyProduct( "System" )] [assembly: AssemblyCopyright( "Copyright © Microsoft" )] [assembly: AssemblyTrademark( "" )] [assembly: AssemblyCulture( "" )] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Revision and Build Numbers // by using the '*' as shown below: [assembly: AssemblyVersion( "4.5.0.0" )] [assembly: AssemblyFileVersion( "4.5.0.0" )] [assembly: System.CLSCompliant(false)] ================================================ FILE: Zelig/Zelig/RunTime/Framework/system/System/CodeDOM/Compiler/GeneratedCodeAttribute.cs ================================================ //------------------------------------------------------------------------------ // // Copyright (c) Microsoft Corporation. All rights reserved. // //------------------------------------------------------------------------------ namespace System.CodeDom.Compiler { [AttributeUsage( AttributeTargets.All, Inherited = false, AllowMultiple = false )] public sealed class GeneratedCodeAttribute : Attribute { private readonly string tool; private readonly string version; public GeneratedCodeAttribute( string tool, string version ) { this.tool = tool; this.version = version; } public string Tool { get { return this.tool; } } public string Version { get { return this.version; } } } } ================================================ FILE: Zelig/Zelig/RunTime/Framework/system/System/Collections/Generic/LinkedList.cs ================================================ namespace System.Collections.Generic { using System; using System.Diagnostics; using System.Runtime.Serialization; using System.Security.Permissions; [Serializable()] ////[DebuggerTypeProxy( typeof( System_CollectionDebugView<> ) )] ////[DebuggerDisplay( "Count = {Count}" )] public class LinkedList : ICollection, System.Collections.ICollection/*, ISerializable, IDeserializationCallback*/ { // This LinkedList is a doubly-Linked circular list. internal LinkedListNode head; internal int count; internal int version; private Object _syncRoot; //// private SerializationInfo siInfo; //A temporary variable which we need during deserialization. //// //// // names for serialization //// const String VersionName = "Version"; //// const String CountName = "Count"; //// const String ValuesName = "Data"; public LinkedList() { } public LinkedList( IEnumerable collection ) { if(collection == null) { #if EXCEPTION_STRINGS throw new ArgumentNullException( "collection" ); #else throw new ArgumentNullException(); #endif } foreach(T item in collection) { AddLast( item ); } } //// protected LinkedList( SerializationInfo info, StreamingContext context ) //// { //// siInfo = info; //// } public int Count { get { return count; } } public LinkedListNode First { get { return head; } } public LinkedListNode Last { get { return head == null ? null : head.prev; } } bool ICollection.IsReadOnly { get { return false; } } void ICollection.Add( T value ) { AddLast( value ); } public LinkedListNode AddAfter( LinkedListNode node , T value ) { ValidateNode( node ); LinkedListNode result = new LinkedListNode( node.list, value ); InternalInsertNodeBefore( node.next, result ); return result; } public void AddAfter( LinkedListNode node , LinkedListNode newNode ) { ValidateNode( node ); ValidateNewNode( newNode ); InternalInsertNodeBefore( node.next, newNode ); newNode.list = this; } public LinkedListNode AddBefore( LinkedListNode node , T value ) { ValidateNode( node ); LinkedListNode result = new LinkedListNode( node.list, value ); InternalInsertNodeBefore( node, result ); if(node == head) { head = result; } return result; } public void AddBefore( LinkedListNode node , LinkedListNode newNode ) { ValidateNode( node ); ValidateNewNode( newNode ); InternalInsertNodeBefore( node, newNode ); newNode.list = this; if(node == head) { head = newNode; } } public LinkedListNode AddFirst( T value ) { LinkedListNode result = new LinkedListNode( this, value ); if(head == null) { InternalInsertNodeToEmptyList( result ); } else { InternalInsertNodeBefore( head, result ); head = result; } return result; } public void AddFirst( LinkedListNode node ) { ValidateNewNode( node ); if(head == null) { InternalInsertNodeToEmptyList( node ); } else { InternalInsertNodeBefore( head, node ); head = node; } node.list = this; } public LinkedListNode AddLast( T value ) { LinkedListNode result = new LinkedListNode( this, value ); if(head == null) { InternalInsertNodeToEmptyList( result ); } else { InternalInsertNodeBefore( head, result ); } return result; } public void AddLast( LinkedListNode node ) { ValidateNewNode( node ); if(head == null) { InternalInsertNodeToEmptyList( node ); } else { InternalInsertNodeBefore( head, node ); } node.list = this; } public void Clear() { LinkedListNode current = head; while(current != null) { LinkedListNode temp = current; current = current.Next; // use Next the instead of "next", otherwise it will loop forever temp.Invalidate(); } head = null; count = 0; version++; } public bool Contains( T value ) { return Find( value ) != null; } public void CopyTo( T[] array, int index ) { if(array == null) { #if EXCEPTION_STRINGS throw new ArgumentNullException( "array" ); #else throw new ArgumentNullException(); #endif } if(index < 0 || index > array.Length) { #if EXCEPTION_STRINGS throw new ArgumentOutOfRangeException( "index" ); //, SR.GetString( SR.IndexOutOfRange, index ) ); #else throw new ArgumentOutOfRangeException(); #endif } if(array.Length - index < Count) { throw new ArgumentException(); // SR.GetString( SR.Arg_InsufficientSpace ) ); } LinkedListNode node = head; if(node != null) { do { array[index++] = node.item; node = node.next; } while(node != head); } } public LinkedListNode Find( T value ) { LinkedListNode node = head; EqualityComparer c = EqualityComparer.Default; if(node != null) { if(value != null) { do { if(c.Equals( node.item, value )) { return node; } node = node.next; } while(node != head); } else { do { if(node.item == null) { return node; } node = node.next; } while(node != head); } } return null; } public LinkedListNode FindLast( T value ) { if(head == null) return null; LinkedListNode last = head.prev; LinkedListNode node = last; EqualityComparer c = EqualityComparer.Default; if(node != null) { if(value != null) { do { if(c.Equals( node.item, value )) { return node; } node = node.prev; } while(node != last); } else { do { if(node.item == null) { return node; } node = node.prev; } while(node != last); } } return null; } public Enumerator GetEnumerator() { return new Enumerator( this ); } IEnumerator IEnumerable.GetEnumerator() { return GetEnumerator(); } public bool Remove( T value ) { LinkedListNode node = Find( value ); if(node != null) { InternalRemoveNode( node ); return true; } return false; } public void Remove( LinkedListNode node ) { ValidateNode( node ); InternalRemoveNode( node ); } public void RemoveFirst() { if(head == null) { throw new InvalidOperationException(); // SR.GetString( SR.LinkedListEmpty ) ); } InternalRemoveNode( head ); } public void RemoveLast() { if(head == null) { throw new InvalidOperationException(); // SR.GetString( SR.LinkedListEmpty ) ); } InternalRemoveNode( head.prev ); } //// [SecurityPermissionAttribute( SecurityAction.LinkDemand, Flags = SecurityPermissionFlag.SerializationFormatter )] //// public virtual void GetObjectData( SerializationInfo info, StreamingContext context ) //// { //// // Customized serialization for LinkedList. //// // We need to do this because it will be too expensive to Serialize each node. //// // This will give us the flexiblility to change internal implementation freely in future. //// if(info == null) //// { //// throw new ArgumentNullException( "info" ); //// } //// info.AddValue( VersionName, version ); //// info.AddValue( CountName, count ); //This is the length of the bucket array. //// if(count != 0) //// { //// T[] array = new T[Count]; //// CopyTo( array, 0 ); //// info.AddValue( ValuesName, array, typeof( T[] ) ); //// } //// } //// //// public virtual void OnDeserialization( Object sender ) //// { //// if(siInfo == null) //// { //// return; //Somebody had a dependency on this Dictionary and fixed us up before the ObjectManager got to it. //// } //// //// int realVersion = siInfo.GetInt32( VersionName ); //// int count = siInfo.GetInt32( CountName ); //// //// if(count != 0) //// { //// T[] array = (T[])siInfo.GetValue( ValuesName, typeof( T[] ) ); //// //// if(array == null) //// { //// throw new SerializationException( SR.GetString( SR.Serialization_MissingValues ) ); //// } //// for(int i = 0; i < array.Length; i++) //// { //// AddLast( array[i] ); //// } //// } //// else //// { //// head = null; //// } //// //// version = realVersion; //// siInfo = null; //// } private void InternalInsertNodeBefore( LinkedListNode node, LinkedListNode newNode ) { newNode.next = node; newNode.prev = node.prev; node.prev.next = newNode; node.prev = newNode; version++; count++; } private void InternalInsertNodeToEmptyList( LinkedListNode newNode ) { //Debug.Assert( head == null && count == 0, "LinkedList must be empty when this method is called!" ); newNode.next = newNode; newNode.prev = newNode; head = newNode; version++; count++; } internal void InternalRemoveNode( LinkedListNode node ) { //Debug.Assert( node.list == this, "Deleting the node from another list!" ); //Debug.Assert( head != null, "This method shouldn't be called on empty list!" ); if(node.next == node) { //Debug.Assert( count == 1 && head == node, "this should only be true for a list with only one node" ); head = null; } else { node.next.prev = node.prev; node.prev.next = node.next; if(head == node) { head = node.next; } } node.Invalidate(); count--; version++; } internal void ValidateNewNode( LinkedListNode node ) { if(node == null) { #if EXCEPTION_STRINGS throw new ArgumentNullException( "node" ); #else throw new ArgumentNullException(); #endif } if(node.list != null) { throw new InvalidOperationException(); // SR.GetString( SR.LinkedListNodeIsAttached ) ); } } internal void ValidateNode( LinkedListNode node ) { if(node == null) { #if EXCEPTION_STRINGS throw new ArgumentNullException( "node" ); #else throw new ArgumentNullException(); #endif } if(node.list != this) { throw new InvalidOperationException(); // SR.GetString( SR.ExternalLinkedListNode ) ); } } bool System.Collections.ICollection.IsSynchronized { get { return false; } } object System.Collections.ICollection.SyncRoot { get { if(_syncRoot == null) { System.Threading.Interlocked.CompareExchange( ref _syncRoot, new Object(), null ); } return _syncRoot; } } void System.Collections.ICollection.CopyTo( Array array, int index ) { if(array == null) { #if EXCEPTION_STRINGS throw new ArgumentNullException( "array" ); #else throw new ArgumentNullException(); #endif } if(array.Rank != 1) { throw new ArgumentException(); // SR.GetString( SR.Arg_MultiRank ) ); } if(array.GetLowerBound( 0 ) != 0) { throw new ArgumentException(); // SR.GetString( SR.Arg_NonZeroLowerBound ) ); } if(index < 0) { #if EXCEPTION_STRINGS throw new ArgumentOutOfRangeException( "index" ); //, SR.GetString( SR.IndexOutOfRange, index ) ); #else throw new ArgumentOutOfRangeException(); #endif } if(array.Length - index < Count) { throw new ArgumentException(); // SR.GetString( SR.Arg_InsufficientSpace ) ); } T[] tArray = array as T[]; if(tArray != null) { CopyTo( tArray, index ); } else { // // Catch the obvious case assignment will fail. // We can found all possible problems by doing the check though. // For example, if the element type of the Array is derived from T, // we can't figure out if we can successfully copy the element beforehand. // Type targetType = array.GetType().GetElementType(); Type sourceType = typeof( T ); if(!(targetType.IsAssignableFrom( sourceType ) || sourceType.IsAssignableFrom( targetType ))) { throw new ArgumentException(); // SR.GetString( SR.Invalid_Array_Type ) ); } object[] objects = array as object[]; if(objects == null) { throw new ArgumentException(); // SR.GetString( SR.Invalid_Array_Type ) ); } LinkedListNode node = head; try { if(node != null) { do { objects[index++] = node.item; node = node.next; } while(node != head); } } catch(ArrayTypeMismatchException) { throw new ArgumentException(); // SR.GetString( SR.Invalid_Array_Type ) ); } } } System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator() { return GetEnumerator(); } [Serializable()] public struct Enumerator : IEnumerator, System.Collections.IEnumerator/*, ISerializable, IDeserializationCallback*/ { private LinkedList list; private LinkedListNode node; private int version; private T current; private int index; //// private SerializationInfo siInfo; //A temporary variable which we need during deserialization. //// //// const string LinkedListName = "LinkedList"; //// const string CurrentValueName = "Current"; //// const string VersionName = "Version"; //// const string IndexName = "Index"; //// internal Enumerator( LinkedList list ) { this.list = list; version = list.version; node = list.head; current = default( T ); index = 0; //// siInfo = null; } //// internal Enumerator( SerializationInfo info, StreamingContext context ) //// { //// siInfo = info; //// list = null; //// version = 0; //// node = null; //// current = default( T ); //// index = 0; //// } public T Current { get { return current; } } object System.Collections.IEnumerator.Current { get { if(index == 0 || (index == list.Count + 1)) { ThrowHelper.ThrowInvalidOperationException( ExceptionResource.InvalidOperation_EnumOpCantHappen ); } return current; } } public bool MoveNext() { if(version != list.version) { throw new InvalidOperationException(); // SR.GetString( SR.InvalidOperation_EnumFailedVersion ) ); } if(node == null) { index = list.Count + 1; return false; } ++index; current = node.item; node = node.next; if(node == list.head) { node = null; } return true; } void System.Collections.IEnumerator.Reset() { if(version != list.version) { throw new InvalidOperationException(); // SR.GetString( SR.InvalidOperation_EnumFailedVersion ) ); } current = default( T ); node = list.head; index = 0; } public void Dispose() { } //// void ISerializable.GetObjectData( SerializationInfo info, StreamingContext context ) //// { //// if(info == null) //// { //// throw new ArgumentNullException( "info" ); //// } //// //// info.AddValue( LinkedListName, list ); //// info.AddValue( VersionName, version ); //// info.AddValue( CurrentValueName, current ); //// info.AddValue( IndexName, index ); //// } //// //// void IDeserializationCallback.OnDeserialization( Object sender ) //// { //// if(list != null) //// { //// return; //Somebody had a dependency on this Dictionary and fixed us up before the ObjectManager got to it. //// } //// //// if(siInfo == null) //// { //// throw new SerializationException( SR.GetString( SR.Serialization_InvalidOnDeser ) ); //// } //// //// list = (LinkedList)siInfo.GetValue( LinkedListName, typeof( LinkedList ) ); //// version = siInfo.GetInt32( VersionName ); //// current = (T)siInfo.GetValue( CurrentValueName, typeof( T ) ); //// index = siInfo.GetInt32( IndexName ); //// //// if(list.siInfo != null) //// { //// list.OnDeserialization( sender ); //// } //// //// if(index == list.Count + 1) //// { // end of enumeration //// node = null; //// } //// else //// { //// node = list.First; //// // We don't care if we can point to the correct node if the LinkedList was changed //// // MoveNext will throw upon next call and Current has the correct value. //// if(node != null && index != 0) //// { //// for(int i = 0; i < index; i++) //// { //// node = node.next; //// } //// if(node == list.First) //// { //// node = null; //// } //// } //// } //// siInfo = null; //// } } } // Note following class is not serializable since we customized the serialization of LinkedList. public sealed class LinkedListNode { internal LinkedList list; internal LinkedListNode next; internal LinkedListNode prev; internal T item; public LinkedListNode( T value ) { this.item = value; } internal LinkedListNode( LinkedList list , T value ) { this.list = list; this.item = value; } public LinkedList List { get { return list; } } public LinkedListNode Next { get { return next == null || next == list.head ? null : next; } } public LinkedListNode Previous { get { return prev == null || this == list.head ? null : prev; } } public T Value { get { return item; } set { item = value; } } internal void Invalidate() { list = null; next = null; prev = null; } } } ================================================ FILE: Zelig/Zelig/RunTime/Framework/system/System/Collections/Generic/Queue.cs ================================================ // ==++== // // Copyright (c) Microsoft Corporation. All rights reserved. // // ==--== /*============================================================================= ** ** Class: Queue ** ** Purpose: A circular-array implementation of a generic queue. ** ** Date: January 28, 2003 ** =============================================================================*/ namespace System.Collections.Generic { using System; using System.Security.Permissions; using System.Diagnostics; // A simple Queue of generic objects. Internally it is implemented as a // circular buffer, so Enqueue can be O(n). Dequeue is O(1). ////[DebuggerTypeProxy( typeof( System_QueueDebugView<> ) )] ////[DebuggerDisplay( "Count = {Count}" )] [Serializable()] public class Queue : IEnumerable, System.Collections.ICollection { private T[] _array; private int _head; // First valid element in the queue private int _tail; // Last valid element in the queue private int _size; // Number of elements. private int _version; [NonSerialized] private Object _syncRoot; private const int _MinimumGrow = 4; private const int _ShrinkThreshold = 32; private const int _GrowFactor = 200; // double each time private const int _DefaultCapacity = 4; static T[] _emptyArray = new T[0]; // Creates a queue with room for capacity objects. The default initial // capacity and grow factor are used. /// public Queue() { _array = _emptyArray; } // Creates a queue with room for capacity objects. The default grow factor // is used. // /// public Queue( int capacity ) { if(capacity < 0) { ThrowHelper.ThrowArgumentOutOfRangeException( ExceptionArgument.capacity, ExceptionResource.ArgumentOutOfRange_NeedNonNegNum ); } _array = new T[capacity]; _head = 0; _tail = 0; _size = 0; } // Fills a Queue with the elements of an ICollection. Uses the enumerator // to get each of the elements. // /// public Queue( IEnumerable collection ) { if(collection == null) ThrowHelper.ThrowArgumentNullException( ExceptionArgument.collection ); _array = new T[_DefaultCapacity]; _size = 0; _version = 0; using(IEnumerator en = collection.GetEnumerator()) { while(en.MoveNext()) { Enqueue( en.Current ); } } } /// public int Count { get { return _size; } } /// bool System.Collections.ICollection.IsSynchronized { get { return false; } } Object System.Collections.ICollection.SyncRoot { get { if(_syncRoot == null) { System.Threading.Interlocked.CompareExchange( ref _syncRoot, new Object(), null ); } return _syncRoot; } } // Removes all Objects from the queue. /// public void Clear() { if(_head < _tail) Array.Clear( _array, _head, _size ); else { Array.Clear( _array, _head, _array.Length - _head ); Array.Clear( _array, 0, _tail ); } _head = 0; _tail = 0; _size = 0; _version++; } // CopyTo copies a collection into an Array, starting at a particular // index into the array. // /// public void CopyTo( T[] array, int arrayIndex ) { if(array == null) { ThrowHelper.ThrowArgumentNullException( ExceptionArgument.array ); } if(arrayIndex < 0 || arrayIndex > array.Length) { ThrowHelper.ThrowArgumentOutOfRangeException( ExceptionArgument.arrayIndex, ExceptionResource.ArgumentOutOfRange_Index ); } int arrayLen = array.Length; if(arrayLen - arrayIndex < _size) { ThrowHelper.ThrowArgumentException( ExceptionResource.Argument_InvalidOffLen ); } int numToCopy = (arrayLen - arrayIndex < _size) ? (arrayLen - arrayIndex) : _size; if(numToCopy == 0) return; int firstPart = (_array.Length - _head < numToCopy) ? _array.Length - _head : numToCopy; Array.Copy( _array, _head, array, arrayIndex, firstPart ); numToCopy -= firstPart; if(numToCopy > 0) { Array.Copy( _array, 0, array, arrayIndex + _array.Length - _head, numToCopy ); } } void System.Collections.ICollection.CopyTo( Array array, int index ) { if(array == null) { ThrowHelper.ThrowArgumentNullException( ExceptionArgument.array ); } if(array.Rank != 1) { ThrowHelper.ThrowArgumentException( ExceptionResource.Arg_RankMultiDimNotSupported ); } if(array.GetLowerBound( 0 ) != 0) { ThrowHelper.ThrowArgumentException( ExceptionResource.Arg_NonZeroLowerBound ); } int arrayLen = array.Length; if(index < 0 || index > arrayLen) { ThrowHelper.ThrowArgumentOutOfRangeException( ExceptionArgument.index, ExceptionResource.ArgumentOutOfRange_Index ); } if(arrayLen - index < _size) { ThrowHelper.ThrowArgumentException( ExceptionResource.Argument_InvalidOffLen ); } int numToCopy = (arrayLen - index < _size) ? arrayLen - index : _size; if(numToCopy == 0) return; try { int firstPart = (_array.Length - _head < numToCopy) ? _array.Length - _head : numToCopy; Array.Copy( _array, _head, array, index, firstPart ); numToCopy -= firstPart; if(numToCopy > 0) { Array.Copy( _array, 0, array, index + _array.Length - _head, numToCopy ); } } catch(ArrayTypeMismatchException) { ThrowHelper.ThrowArgumentException( ExceptionResource.Argument_InvalidArrayType ); } } // Adds item to the tail of the queue. // /// public void Enqueue( T item ) { if(_size == _array.Length) { int newcapacity = (int)((long)_array.Length * (long)_GrowFactor / 100); if(newcapacity < _array.Length + _MinimumGrow) { newcapacity = _array.Length + _MinimumGrow; } SetCapacity( newcapacity ); } _array[_tail] = item; //// _tail = (_tail + 1) % _array.Length; int tailNext = _tail + 1; _tail = (tailNext == _array.Length) ? 0 : tailNext; _size++; _version++; } // GetEnumerator returns an IEnumerator over this Queue. This // Enumerator will support removing. // /// public Enumerator GetEnumerator() { return new Enumerator( this ); } /// /// IEnumerator IEnumerable.GetEnumerator() { return new Enumerator( this ); } System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator() { return new Enumerator( this ); } // Removes the object at the head of the queue and returns it. If the queue // is empty, this method simply returns null. /// public T Dequeue() { if(_size == 0) ThrowHelper.ThrowInvalidOperationException( ExceptionResource.InvalidOperation_EmptyQueue ); T removed = _array[_head]; _array[_head] = default( T ); //// _head = (_head + 1) % _array.Length; int headNext = _head + 1; _head = (headNext == _array.Length) ? 0 : headNext; _size--; _version++; return removed; } // Returns the object at the head of the queue. The object remains in the // queue. If the queue is empty, this method throws an // InvalidOperationException. /// public T Peek() { if(_size == 0) ThrowHelper.ThrowInvalidOperationException( ExceptionResource.InvalidOperation_EmptyQueue ); return _array[_head]; } // Returns true if the queue contains at least one object equal to item. // Equality is determined using item.Equals(). // // Exceptions: ArgumentNullException if item == null. /// public bool Contains( T item ) { int index = _head; int count = _size; EqualityComparer c = EqualityComparer.Default; while(count-- > 0) { if(((Object)item) == null) { if(((Object)_array[index]) == null) return true; } else if(_array[index] != null && c.Equals( _array[index], item )) { return true; } //// index = (index + 1) % _array.Length; index = (index + 1); if(index == _array.Length) { index = 0; } } return false; } internal T GetElement( int i ) { return _array[(_head + i) % _array.Length]; } // Iterates over the objects in the queue, returning an array of the // objects in the Queue, or an empty array if the queue is empty. // The order of elements in the array is first in to last in, the same // order produced by successive calls to Dequeue. /// public T[] ToArray() { T[] arr = new T[_size]; if(_size == 0) return arr; if(_head < _tail) { Array.Copy( _array, _head, arr, 0, _size ); } else { Array.Copy( _array, _head, arr, 0, _array.Length - _head ); Array.Copy( _array, 0, arr, _array.Length - _head, _tail ); } return arr; } // PRIVATE Grows or shrinks the buffer to hold capacity objects. Capacity // must be >= _size. private void SetCapacity( int capacity ) { T[] newarray = new T[capacity]; if(_size > 0) { if(_head < _tail) { Array.Copy( _array, _head, newarray, 0, _size ); } else { Array.Copy( _array, _head, newarray, 0, _array.Length - _head ); Array.Copy( _array, 0, newarray, _array.Length - _head, _tail ); } } _array = newarray; _head = 0; _tail = (_size == capacity) ? 0 : _size; _version++; } public void TrimExcess() { int threshold = (int)(((double)_array.Length) * 0.9); if(_size < threshold) { SetCapacity( _size ); } } // Implements an enumerator for a Queue. The enumerator uses the // internal version number of the list to ensure that no modifications are // made to the list while an enumeration is in progress. /// [Serializable()] public struct Enumerator : IEnumerator, System.Collections.IEnumerator { private Queue _q; private int _index; // -1 = not started, -2 = ended/disposed private int _version; private T _currentElement; internal Enumerator( Queue q ) { _q = q; _version = _q._version; _index = -1; _currentElement = default( T ); } /// public void Dispose() { _index = -2; _currentElement = default( T ); } /// public bool MoveNext() { if(_version != _q._version) ThrowHelper.ThrowInvalidOperationException( ExceptionResource.InvalidOperation_EnumFailedVersion ); if(_index == -2) return false; _index++; if(_index == _q._size) { _index = -2; _currentElement = default( T ); return false; } _currentElement = _q.GetElement( _index ); return true; } /// public T Current { get { if(_index < 0) { if(_index == -1) ThrowHelper.ThrowInvalidOperationException( ExceptionResource.InvalidOperation_EnumNotStarted ); else ThrowHelper.ThrowInvalidOperationException( ExceptionResource.InvalidOperation_EnumEnded ); } return _currentElement; } } Object System.Collections.IEnumerator.Current { get { if(_index < 0) { if(_index == -1) ThrowHelper.ThrowInvalidOperationException( ExceptionResource.InvalidOperation_EnumNotStarted ); else ThrowHelper.ThrowInvalidOperationException( ExceptionResource.InvalidOperation_EnumEnded ); } return _currentElement; } } void System.Collections.IEnumerator.Reset() { if(_version != _q._version) ThrowHelper.ThrowInvalidOperationException( ExceptionResource.InvalidOperation_EnumFailedVersion ); _index = -1; _currentElement = default( T ); } } } } ================================================ FILE: Zelig/Zelig/RunTime/Framework/system/System/ComponentModel/Component.cs ================================================ //------------------------------------------------------------------------------ // // Copyright (c) Microsoft Corporation. All rights reserved. // //------------------------------------------------------------------------------ namespace System.ComponentModel { using System; ////using System.ComponentModel.Design; ////using System.ComponentModel.Design.Serialization; using System.Runtime.InteropServices; using System.Security.Permissions; /// /// Provides the default implementation for the /// /// interface and enables object-sharing between applications. /// ////[ComVisible( true )] ////[ClassInterface( ClassInterfaceType.AutoDispatch )] ////[DesignerCategory( "Component" )] public class Component : MarshalByRefObject, IComponent { /// /// Static hask key for the Disposed event. This field is read-only. /// private static readonly object EventDisposed = new object(); private ISite site; private EventHandlerList events; ~Component() { Dispose( false ); } /// /// This property returns true if the component is in a mode that supports /// raising events. By default, components always support raising their events /// and therefore this method always returns true. You can override this method /// in a deriving class and change it to return false when needed. if the return /// value of this method is false, the EventList collection returned by the Events /// property will always return null for an event. Events can still be added and /// removed from the collection, but retrieving them through the collection's Item /// property will always return null. /// protected virtual bool CanRaiseEvents { get { return true; } } /// /// Internal API that allows the event handler list class to access the /// CanRaiseEvents property. /// internal bool CanRaiseEventsInternal { get { return CanRaiseEvents; } } /// /// Adds a event handler to listen to the Disposed event on the component. /// //// [Browsable( false )] [EditorBrowsable( EditorBrowsableState.Advanced )] public event EventHandler Disposed { add { Events.AddHandler( EventDisposed, value ); } remove { Events.RemoveHandler( EventDisposed, value ); } } /// /// Gets the list of event handlers that are attached to this component. /// protected EventHandlerList Events { get { if(events == null) { events = new EventHandlerList( this ); } return events; } } /// /// /// Gets or sets the site of the /// . /// /// //// [Browsable( false )] //// [DesignerSerializationVisibility( DesignerSerializationVisibility.Hidden )] public virtual ISite Site { get { return site; } set { site = value; } } /// /// /// Disposes of the /// . /// /// [System.Diagnostics.CodeAnalysis.SuppressMessage( "Microsoft.Usage", "CA2213:DisposableFieldsShouldBeDisposed" )] public void Dispose() { Dispose( true ); GC.SuppressFinalize( this ); } /// /// /// Disposes all the resources associated with this component. /// If disposing is false then you must never touch any other /// managed objects, as they may already be finalized. When /// in this state you should dispose any native resources /// that you have a reference to. /// /// /// When disposing is true then you should dispose all data /// and objects you have references to. The normal implementation /// of this method would look something like: /// /// /// public void Dispose() { /// Dispose(true); /// GC.SuppressFinalize(this); /// } /// /// protected virtual void Dispose(bool disposing) { /// if (disposing) { /// if (myobject != null) { /// myobject.Dispose(); /// myobject = null; /// } /// } /// if (myhandle != IntPtr.Zero) { /// NativeMethods.Release(myhandle); /// myhandle = IntPtr.Zero; /// } /// } /// /// ~MyClass() { /// Dispose(false); /// } /// /// /// For base classes, you should never override the Finalier (~Class in C#) /// or the Dispose method that takes no arguments, rather you should /// always override the Dispose method that takes a bool. /// /// /// protected override void Dispose(bool disposing) { /// if (disposing) { /// if (myobject != null) { /// myobject.Dispose(); /// myobject = null; /// } /// } /// if (myhandle != IntPtr.Zero) { /// NativeMethods.Release(myhandle); /// myhandle = IntPtr.Zero; /// } /// base.Dispose(disposing); /// } /// /// protected virtual void Dispose( bool disposing ) { if(disposing) { lock(this) { if(site != null && site.Container != null) { site.Container.Remove( this ); } if(events != null) { EventHandler handler = (EventHandler)events[EventDisposed]; if(handler != null) handler( this, EventArgs.Empty ); } } } } // Returns the component's container. // /// /// /// Returns the /// that contains the /// . /// /// //// [Browsable( false )] //// [DesignerSerializationVisibility( DesignerSerializationVisibility.Hidden )] public IContainer Container { get { ISite s = site; return s == null ? null : s.Container; } } /// /// /// Returns an object representing a service provided by /// the /// . /// /// protected virtual object GetService( Type service ) { ISite s = site; return ((s == null) ? null : s.GetService( service )); } /// /// /// Gets a value indicating whether the /// is currently in design mode. /// /// //// [Browsable( false )] //// [DesignerSerializationVisibility( DesignerSerializationVisibility.Hidden )] protected bool DesignMode { get { ISite s = site; return (s == null) ? false : s.DesignMode; } } /// /// /// /// Returns a containing the name of the , if any. This method should not be /// overridden. For /// internal use only. /// /// public override String ToString() { ISite s = site; if(s != null) return s.Name + " [" + GetType().FullName + "]"; else return GetType().FullName; } } } ================================================ FILE: Zelig/Zelig/RunTime/Framework/system/System/ComponentModel/ComponentCollection.cs ================================================ //------------------------------------------------------------------------------ // // Copyright (c) Microsoft Corporation. All rights reserved. // // // This class was generated by a tool. // Runtime Version: 1.0.2204.0 // // Changes to this file may cause incorrect behavior and will be lost if // the code is regenerated. // //------------------------------------------------------------------------------ using System.Diagnostics.CodeAnalysis; /* This class has the HostProtectionAttribute. The purpose of this attribute is to enforce host-specific programming model guidelines, not security behavior. Suppress FxCop message - BUT REVISIT IF ADDING NEW SECURITY ATTRIBUTES. */ [assembly: SuppressMessage("Microsoft.Security", "CA2122:DoNotIndirectlyExposeMethodsWithLinkDemands", Scope="member", Target="System.ComponentModel.ComponentCollection..ctor(System.ComponentModel.IComponent[])")] [assembly: SuppressMessage("Microsoft.Security", "CA2122:DoNotIndirectlyExposeMethodsWithLinkDemands", Scope="member", Target="System.ComponentModel.ComponentCollection.get_Item(System.String):System.ComponentModel.IComponent")] namespace System.ComponentModel { using System; using System.Collections; using System.ComponentModel; using System.Globalization; using System.Security.Permissions; /** The component in the container identified by name. */ /// /// /// Gets a specific in the /// . /// /// ////[System.Runtime.InteropServices.ComVisible( true )] ////[HostProtection( Synchronization = true )] public class ComponentCollection : ReadOnlyCollectionBase { /// /// [To be supplied.] /// public ComponentCollection( IComponent[] components ) { InnerList.AddRange( components ); } /** The component in the container identified by name. */ /// /// /// Gets a specific in the /// . /// /// public virtual IComponent this[string name] { get { if(name != null) { IList list = InnerList; foreach(IComponent comp in list) { if(comp != null && comp.Site != null && comp.Site.Name != null && string.Equals( comp.Site.Name, name, StringComparison.OrdinalIgnoreCase )) { return comp; } } } return null; } } /** The component in the container identified by index. */ /// /// /// Gets a specific in the /// . /// /// public virtual IComponent this[int index] { get { return (IComponent)InnerList[index]; } } /// /// [To be supplied.] /// public void CopyTo( IComponent[] array, int index ) { InnerList.CopyTo( array, index ); } } } ================================================ FILE: Zelig/Zelig/RunTime/Framework/system/System/ComponentModel/EditorBrowsableAttribute.cs ================================================ //------------------------------------------------------------------------------ // // Copyright (c) Microsoft Corporation. All rights reserved. // //------------------------------------------------------------------------------ namespace System.ComponentModel { using System.Security.Permissions; /// /// [To be supplied.] /// [AttributeUsage( AttributeTargets.Class | AttributeTargets.Struct | AttributeTargets.Enum | AttributeTargets.Constructor | AttributeTargets.Method | AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Event | AttributeTargets.Delegate | AttributeTargets.Interface )] public sealed class EditorBrowsableAttribute : Attribute { private EditorBrowsableState browsableState; /// /// [To be supplied.] /// public EditorBrowsableAttribute( EditorBrowsableState state ) { browsableState = state; } /// /// [To be supplied.] /// public EditorBrowsableAttribute() : this( EditorBrowsableState.Always ) { } /// /// [To be supplied.] /// public EditorBrowsableState State { get { return browsableState; } } public override bool Equals( object obj ) { if(obj == this) { return true; } EditorBrowsableAttribute other = obj as EditorBrowsableAttribute; return (other != null) && other.browsableState == browsableState; } public override int GetHashCode() { return base.GetHashCode(); } } /// /// [To be supplied.] /// public enum EditorBrowsableState { /// /// [To be supplied.] /// Always, /// /// [To be supplied.] /// Never, /// /// [To be supplied.] /// Advanced } } ================================================ FILE: Zelig/Zelig/RunTime/Framework/system/System/ComponentModel/EventHandlerList.cs ================================================ //------------------------------------------------------------------------------ // // Copyright (c) Microsoft Corporation. All rights reserved. // //------------------------------------------------------------------------------ namespace System.ComponentModel { using System; using System.Diagnostics.CodeAnalysis; using System.Security.Permissions; /// /// Provides a simple list of delegates. This class cannot be inherited. /// ////[HostProtection( SharedState = true )] public sealed class EventHandlerList : IDisposable { ListEntry head; Component parent; /// /// Creates a new event handler list. /// [SuppressMessage( "Microsoft.Security", "CA2122:DoNotIndirectlyExposeMethodsWithLinkDemands" )] public EventHandlerList() { } /// /// Creates a new event handler list. The parent component is used to check the component's /// CanRaiseEvents property. /// [SuppressMessage( "Microsoft.Security", "CA2122:DoNotIndirectlyExposeMethodsWithLinkDemands" )] internal EventHandlerList( Component parent ) { this.parent = parent; } /// /// Gets or sets the delegate for the specified key. /// public Delegate this[object key] { [SuppressMessage( "Microsoft.Security", "CA2122:DoNotIndirectlyExposeMethodsWithLinkDemands" )] get { ListEntry e = null; if(parent == null || parent.CanRaiseEventsInternal) { e = Find( key ); } if(e != null) { return e.handler; } else { return null; } } set { ListEntry e = Find( key ); if(e != null) { e.handler = value; } else { head = new ListEntry( key, value, head ); } } } /// /// [To be supplied.] /// [SuppressMessage( "Microsoft.Security", "CA2122:DoNotIndirectlyExposeMethodsWithLinkDemands" )] public void AddHandler( object key, Delegate value ) { ListEntry e = Find( key ); if(e != null) { e.handler = Delegate.Combine( e.handler, value ); } else { head = new ListEntry( key, value, head ); } } /// allows you to add a list of events to this list public void AddHandlers( EventHandlerList listToAddFrom ) { ListEntry currentListEntry = listToAddFrom.head; while(currentListEntry != null) { AddHandler( currentListEntry.key, currentListEntry.handler ); currentListEntry = currentListEntry.next; } } /// /// [To be supplied.] /// public void Dispose() { head = null; } private ListEntry Find( object key ) { ListEntry found = head; while(found != null) { if(found.key == key) { break; } found = found.next; } return found; } /// /// [To be supplied.] /// [SuppressMessage( "Microsoft.Security", "CA2122:DoNotIndirectlyExposeMethodsWithLinkDemands" )] public void RemoveHandler( object key , Delegate value ) { ListEntry e = Find( key ); if(e != null) { e.handler = Delegate.Remove( e.handler, value ); } // else... no error for removal of non-existant delegate // } private sealed class ListEntry { internal ListEntry next; internal object key; internal Delegate handler; public ListEntry( object key , Delegate handler , ListEntry next ) { this.next = next; this.key = key; this.handler = handler; } } } } ================================================ FILE: Zelig/Zelig/RunTime/Framework/system/System/ComponentModel/IComponent.cs ================================================ //------------------------------------------------------------------------------ // // Copyright (c) Microsoft Corporation. All rights reserved. // //------------------------------------------------------------------------------ namespace System.ComponentModel { using System; ////using System.ComponentModel.Design; ////using System.ComponentModel.Design.Serialization; /* * A "component" is an object that can be placed in a container. * * In this context, "containment" refers to logical containment, not visual * containment. Components and containers can be used in a variety of * scenarios, including both visual and non-visual scenarios. * * To be a component, a class implements the IComponent interface, and provides * a parameter-less constructor. * * A component interacts with its container primarily through a container- * provided "site". */ // Interfaces don't need to be serializable /// /// Provides functionality required by all components. /// #pragma warning disable 0618 ////[RootDesignerSerializer( "System.ComponentModel.Design.Serialization.RootCodeDomSerializer, " + AssemblyRef.SystemDesign, "System.ComponentModel.Design.Serialization.CodeDomSerializer, " + AssemblyRef.SystemDesign, true )] #pragma warning restore 0618 ////[Designer( "System.ComponentModel.Design.ComponentDesigner, " + AssemblyRef.SystemDesign, typeof( IDesigner ) )] ////[Designer( "System.Windows.Forms.Design.ComponentDocumentDesigner, " + AssemblyRef.SystemDesign, typeof( IRootDesigner ) )] ////[TypeConverter( typeof( ComponentConverter ) )] ////[System.Runtime.InteropServices.ComVisible( true )] public interface IComponent : IDisposable { // The site of the component. /// /// When implemented by a class, gets or sets /// the associated /// with the . /// ISite Site { get; set; } /// /// Adds a event handler to listen to the Disposed event on the component. /// event EventHandler Disposed; } } ================================================ FILE: Zelig/Zelig/RunTime/Framework/system/System/ComponentModel/IContainer.cs ================================================ //------------------------------------------------------------------------------ // // Copyright (c) Microsoft Corporation. All rights reserved. // //------------------------------------------------------------------------------ namespace System.ComponentModel { /* * A "container" is an object that logically contains zero or more child * components. * * In this context, "containment" refers to logical containment, not visual * containment. Components and containers can be used in a variety of * scenarios, including both visual and non-visual scenarios. */ // Interfaces don't need to be serializable /// /// Provides /// functionality for containers. Containers are objects that logically contain zero or more components. /// ////[System.Runtime.InteropServices.ComVisible( true )] public interface IContainer : IDisposable { // Adds a component to the container. /// /// Adds the specified to the /// at the end of the list. /// void Add( IComponent component ); // Adds a component to the container. /// /// Adds the specified to the /// at the end of the list, and assigns a name to the component. /// void Add( IComponent component, String name ); // The components in the container. /// /// Gets all the components in the . /// ComponentCollection Components { get; } // Removes a component from the container. /// /// Removes a component from the . /// void Remove( IComponent component ); } } ================================================ FILE: Zelig/Zelig/RunTime/Framework/system/System/ComponentModel/ISite.cs ================================================ //------------------------------------------------------------------------------ // // Copyright (c) Microsoft Corporation. All rights reserved. // //------------------------------------------------------------------------------ namespace System.ComponentModel { using System; /* * Containers use sites to manage and communicate their child components. * * A site is a convenient place for a container to store container-specific * per-component information. The canonical example of such a piece of * information is the name of the component. * * To be a site, a class implements the ISite interface. */ // Interfaces don't need to be serializable /// /// Provides functionality required by sites. Sites bind /// a to a /// and enable communication between them, as well as provide a way /// for the container to manage its components. /// ////[System.Runtime.InteropServices.ComVisible( true )] public interface ISite : IServiceProvider { // The component sited by this component site. /// /// When implemented by a class, gets the component associated with the . /// IComponent Component { get; } // The container in which the component is sited. /// /// When implemented by a class, gets the container associated with the . /// IContainer Container { get; } // Indicates whether the component is in design mode. /// /// When implemented by a class, determines whether the component is in design mode. /// bool DesignMode { get; } // The name of the component. // /// /// When implemented by a class, gets or sets the name of /// the component associated with the . /// String Name { get; set; } } } ================================================ FILE: Zelig/Zelig/RunTime/Framework/system/System/Diagnostics/Debug.cs ================================================ //------------------------------------------------------------------------------ // // Copyright (c) Microsoft Corporation. All rights reserved. // //------------------------------------------------------------------------------ /* */ //#define DEBUG namespace System.Diagnostics { using System; using System.Collections; using System.Security.Permissions; using System.Globalization; /// /// Provides a set of properties and /// methods /// for debugging code. /// public static class Debug { /// /// Gets /// the collection of listeners that is monitoring the debug /// output. /// public static TraceListenerCollection Listeners { [SecurityPermission( SecurityAction.LinkDemand, Flags = SecurityPermissionFlag.UnmanagedCode )] [HostProtection( SharedState = true )] get { return TraceInternal.Listeners; } } /// /// Gets or sets a value indicating whether should be called on the /// /// after every write. /// public static bool AutoFlush { [SecurityPermission( SecurityAction.LinkDemand, Flags = SecurityPermissionFlag.UnmanagedCode )] get { return TraceInternal.AutoFlush; } [SecurityPermission( SecurityAction.LinkDemand, Flags = SecurityPermissionFlag.UnmanagedCode )] set { TraceInternal.AutoFlush = value; } } /// /// Gets or sets /// the indent level. /// public static int IndentLevel { get { return TraceInternal.IndentLevel; } set { TraceInternal.IndentLevel = value; } } /// /// Gets or sets the number of spaces in an indent. /// public static int IndentSize { get { return TraceInternal.IndentSize; } set { TraceInternal.IndentSize = value; } } /// /// Clears the output buffer, and causes buffered data to /// be written to the . /// [System.Diagnostics.Conditional( "DEBUG" )] public static void Flush( ) { TraceInternal.Flush( ); } /// /// Clears the output buffer, and then closes the so that they no longer receive /// debugging output. /// [System.Diagnostics.Conditional( "DEBUG" )] [SecurityPermission( SecurityAction.LinkDemand, Flags = SecurityPermissionFlag.UnmanagedCode )] public static void Close( ) { TraceInternal.Close( ); } /// /// Checks for a condition, and outputs the callstack if the condition is . /// [System.Diagnostics.Conditional( "DEBUG" )] public static void Assert( bool condition ) { if(condition == false) { throw new ArgumentException(); } TraceInternal.Assert( condition ); } /// /// Checks for a condition, and displays a message if the condition is /// . /// [System.Diagnostics.Conditional( "DEBUG" )] public static void Assert( bool condition , string message ) { if(condition == false) { #if EXCEPTION_STRINGS throw new ArgumentException( message ); #else throw new ArgumentException(); #endif } TraceInternal.Assert( condition, message ); } /// /// Checks for a condition, and displays both the specified messages if the condition /// is . /// [System.Diagnostics.Conditional( "DEBUG" )] public static void Assert( bool condition , string message , string detailMessage ) { if(condition == false) { #if EXCEPTION_STRINGS throw new ArgumentException( message ); #else throw new ArgumentException(); #endif } TraceInternal.Assert( condition, message, detailMessage ); } /// /// Emits or displays a message for an assertion that always fails. /// [System.Diagnostics.Conditional( "DEBUG" )] public static void Fail( string message ) { TraceInternal.Fail( message ); } /// /// Emits or displays both messages for an assertion that always fails. /// [System.Diagnostics.Conditional( "DEBUG" )] public static void Fail( string message , string detailMessage ) { TraceInternal.Fail( message, detailMessage ); } [System.Diagnostics.Conditional( "DEBUG" )] public static void Print( string message ) { TraceInternal.WriteLine( message ); } [System.Diagnostics.Conditional( "DEBUG" )] public static void Print( string format , params object[] args ) { TraceInternal.WriteLine( String.Format( CultureInfo.InvariantCulture, format, args ) ); } /// /// Writes a message to the trace listeners in the collection. /// [System.Diagnostics.Conditional( "DEBUG" )] public static void Write( string message ) { TraceInternal.Write( message ); } /// /// Writes the name of the value /// parameter to the trace listeners in the collection. /// [System.Diagnostics.Conditional( "DEBUG" )] public static void Write( object value ) { TraceInternal.Write( value ); } /// /// Writes a category name and message /// to the trace listeners in the collection. /// [System.Diagnostics.Conditional( "DEBUG" )] public static void Write( string message , string category ) { TraceInternal.Write( message, category ); } /// /// Writes a category name and the name of the value parameter to the trace /// listeners in the collection. /// [System.Diagnostics.Conditional( "DEBUG" )] public static void Write( object value , string category ) { TraceInternal.Write( value, category ); } /// /// Writes a message followed by a line terminator to the trace listeners in the /// collection. The default line terminator /// is a carriage return followed by a line feed (\r\n). /// [System.Diagnostics.Conditional( "DEBUG" )] public static void WriteLine( string message ) { TraceInternal.WriteLine( message ); } /// /// Writes the name of the value /// parameter followed by a line terminator to the /// trace listeners in the collection. The default line /// terminator is a carriage return followed by a line feed (\r\n). /// [System.Diagnostics.Conditional( "DEBUG" )] public static void WriteLine( object value ) { TraceInternal.WriteLine( value ); } /// /// Writes a category name and message followed by a line terminator to the trace /// listeners in the collection. The default line /// terminator is a carriage return followed by a line feed (\r\n). /// [System.Diagnostics.Conditional( "DEBUG" )] public static void WriteLine( string message , string category ) { TraceInternal.WriteLine( message, category ); } /// /// Writes a category name and the name of the value /// parameter followed by a line /// terminator to the trace listeners in the collection. The /// default line terminator is a carriage return followed by a line feed (\r\n). /// [System.Diagnostics.Conditional( "DEBUG" )] public static void WriteLine( object value , string category ) { TraceInternal.WriteLine( value, category ); } /// /// Writes a message to the trace listeners in the collection /// if a condition is /// . /// [System.Diagnostics.Conditional( "DEBUG" )] public static void WriteIf( bool condition , string message ) { TraceInternal.WriteIf( condition, message ); } /// /// Writes the name of the value /// parameter to the trace listeners in the /// collection if a condition is /// . /// [System.Diagnostics.Conditional( "DEBUG" )] public static void WriteIf( bool condition , object value ) { TraceInternal.WriteIf( condition, value ); } /// /// Writes a category name and message /// to the trace listeners in the /// collection if a condition is /// . /// [System.Diagnostics.Conditional( "DEBUG" )] public static void WriteIf( bool condition , string message , string category ) { TraceInternal.WriteIf( condition, message, category ); } /// /// Writes a category name and the name of the value /// parameter to the trace /// listeners in the collection if a condition is /// . /// [System.Diagnostics.Conditional( "DEBUG" )] public static void WriteIf( bool condition , object value , string category ) { TraceInternal.WriteIf( condition, value, category ); } /// /// Writes a message followed by a line terminator to the trace listeners in the /// collection if a condition is /// . The default line terminator is a carriage return followed /// by a line feed (\r\n). /// [System.Diagnostics.Conditional( "DEBUG" )] public static void WriteLineIf( bool condition , string message ) { TraceInternal.WriteLineIf( condition, message ); } /// /// Writes the name of the value /// parameter followed by a line terminator to the /// trace listeners in the collection if a condition is /// . The default line terminator is a carriage return followed /// by a line feed (\r\n). /// [System.Diagnostics.Conditional( "DEBUG" )] public static void WriteLineIf( bool condition , object value ) { TraceInternal.WriteLineIf( condition, value ); } /// /// Writes a category name and message /// followed by a line terminator to the trace /// listeners in the collection if a condition is /// . The default line terminator is a carriage return followed /// by a line feed (\r\n). /// [System.Diagnostics.Conditional( "DEBUG" )] public static void WriteLineIf( bool condition , string message , string category ) { TraceInternal.WriteLineIf( condition, message, category ); } /// /// Writes a category name and the name of the value parameter followed by a line /// terminator to the trace listeners in the collection /// if a condition is . The default line terminator is a carriage /// return followed by a line feed (\r\n). /// [System.Diagnostics.Conditional( "DEBUG" )] public static void WriteLineIf( bool condition , object value , string category ) { TraceInternal.WriteLineIf( condition, value, category ); } /// /// [To be supplied.] /// [System.Diagnostics.Conditional( "DEBUG" )] public static void Indent() { TraceInternal.Indent(); } /// /// [To be supplied.] /// [System.Diagnostics.Conditional( "DEBUG" )] public static void Unindent() { TraceInternal.Unindent(); } } } ================================================ FILE: Zelig/Zelig/RunTime/Framework/system/System/Diagnostics/DefaultTraceListener.cs ================================================ //------------------------------------------------------------------------------ // // Copyright (c) Microsoft Corporation. All rights reserved. // //------------------------------------------------------------------------------ #define DEBUG #define TRACE namespace System.Diagnostics { using System; using System.IO; using System.Text; using System.Collections; using System.Reflection; using System.Runtime.InteropServices; using System.Security.Permissions; using System.Security; using Microsoft.Win32; using System.Globalization; using System.Runtime.Versioning; using Runtime.CompilerServices; /// /// Provides /// the default output methods and behavior for tracing. /// [HostProtection(Synchronization=true)] public class DefaultTraceListener : TraceListener { //////bool assertUIEnabled; string logFileName; bool settingsInitialized; const int internalWriteSize = 16384; /// /// Initializes a new instance of the class with /// Default as its . /// public DefaultTraceListener() : base("Default") { } ///////// ///////// [To be supplied.] ///////// //////public bool AssertUiEnabled { ////// get { ////// if (!settingsInitialized) InitializeSettings(); ////// return assertUIEnabled; ////// } ////// set { ////// if (!settingsInitialized) InitializeSettings(); ////// assertUIEnabled = value; ////// } //////} /// /// [To be supplied.] /// public string LogFileName { //////[ResourceExposure(ResourceScope.Machine)] //////[ResourceConsumption(ResourceScope.Machine)] get { if (!settingsInitialized) InitializeSettings(); return logFileName; } //////[ResourceExposure(ResourceScope.Machine)] //////[ResourceConsumption(ResourceScope.Machine)] set { if (!settingsInitialized) InitializeSettings(); logFileName = value; } } /// /// /// Emits or displays a message /// and a stack trace for an assertion that /// always fails. /// /// public override void Fail(string message) { Fail(message, null); } /// /// /// Emits or displays messages and a stack trace for an assertion that /// always fails. /// /// public override void Fail(string message, string detailMessage) { //////StackTrace stack = new StackTrace(0, true); //////int userStackFrameIndex = 0; string stackTrace; //////bool uiPermission = UiPermission; //////try { ////// stackTrace = stack.ToString(); //////} //////catch { ////// stackTrace = ""; //////} stackTrace = ""; WriteAssert(stackTrace, message, detailMessage); //////if (AssertUiEnabled && uiPermission) { ////// AssertWrapper.ShowAssert(stackTrace, stack.GetFrame(userStackFrameIndex), message, detailMessage); //////} } //////[ResourceExposure(ResourceScope.None)] //////[ResourceConsumption(ResourceScope.Machine, ResourceScope.Machine)] private void InitializeSettings() { // don't use the property setters here to avoid infinite recursion. //////assertUIEnabled = DiagnosticsConfiguration.AssertUIEnabled; //////logFileName = DiagnosticsConfiguration.LogFileName; settingsInitialized = true; } private void WriteAssert(string stackTrace, string message, string detailMessage) { //////string assertMessage = SR.GetString(SR.DebugAssertBanner) + Environment.NewLine ////// + SR.GetString(SR.DebugAssertShortMessage) + Environment.NewLine ////// + message + Environment.NewLine ////// + SR.GetString(SR.DebugAssertLongMessage) + Environment.NewLine + ////// detailMessage + Environment.NewLine ////// + stackTrace; string assertMessage = "Assert!" + Environment.NewLine + "Message:" + Environment.NewLine + message + Environment.NewLine + "Details:" + Environment.NewLine + detailMessage + Environment.NewLine + stackTrace; WriteLine( assertMessage); } //////[ResourceExposure(ResourceScope.None)] //////[ResourceConsumption(ResourceScope.Machine, ResourceScope.Machine)] private void WriteToLogFile( string message, bool useWriteLine ) { try { FileInfo file = new FileInfo(LogFileName); using(Stream stream = file.Open( FileMode.OpenOrCreate )) { using(StreamWriter writer = new StreamWriter( stream )) { stream.Position = stream.Length; if(useWriteLine) writer.WriteLine( message ); else writer.Write( message ); } } } catch /*(Exception e)*/ { //////WriteLine(SR.GetString(SR.ExceptionOccurred, LogFileName, e.ToString()), false); } } /// /// /// Writes the output to the OutputDebugString /// API and /// to System.Diagnostics.Debugger.Log. /// /// public override void Write(string message) { Write(message, true); } //////[ResourceExposure(ResourceScope.None)] //////[ResourceConsumption(ResourceScope.Machine, ResourceScope.Machine)] private void Write(string message, bool useLogFile) { if (NeedIndent) WriteIndent(); // really huge messages mess up both VS and dbmon, so we chop it up into // reasonable chunks if it's too big if (message == null || message.Length <= internalWriteSize) { internalWrite(message); } else { int offset; for (offset = 0; offset < message.Length - internalWriteSize; offset += internalWriteSize) { internalWrite(message.Substring(offset, internalWriteSize)); } internalWrite(message.Substring(offset)); } //////if (useLogFile && LogFileName.Length != 0) ////// WriteToLogFile(message, false); } void internalWrite(string message) { //////if (Debugger.IsLogging()) { ////// Debugger.Log(0, null, message); //////} else { if (message == null) /*SafeNativeMethods.*/OutputDebugString(String.Empty); else /*SafeNativeMethods.*/OutputDebugString(message); //////} } [MethodImpl( MethodImplOptions.InternalCall )] public static extern void OutputDebugString(String message); /// /// /// Writes the output to the OutputDebugString /// API and to System.Diagnostics.Debugger.Log /// followed by a line terminator. /// /// public override void WriteLine(string message) { WriteLine(message, true); } private void WriteLine(string message, bool useLogFile) { if (NeedIndent) WriteIndent(); // I do the concat here to make sure it goes as one call to the output. // we would save a stringbuilder operation by calling Write twice. Write(message + Environment.NewLine, useLogFile); NeedIndent = true; } ///////// ///////// It returns true if the current permission set allows an assert dialog to be displayed. ///////// //////private static bool UiPermission { ////// get { ////// bool uiPermission = false; ////// try { ////// new UIPermission(UIPermissionWindow.SafeSubWindows).Demand(); ////// uiPermission = true; ////// } ////// catch { ////// } ////// return uiPermission; ////// } //////} } } ================================================ FILE: Zelig/Zelig/RunTime/Framework/system/System/Diagnostics/Stopwatch.cs ================================================ // ==++== // // Copyright (c) Microsoft Corporation. All rights reserved. // // ==--== /*============================================================ ** ** Class: Stopwatch ** ** Purpose: Implementation for Stopwatch class. ** ** Date: Nov 27, 2002 ** ===========================================================*/ namespace System.Diagnostics { using System; using System.Runtime.CompilerServices; // This class uses high-resolution performance counter if installed hardware // does not support it. Otherwise, the class will fall back to DateTime class // and uses ticks as a measurement. public class Stopwatch { private const long TicksPerMillisecond = 10000; private const long TicksPerSecond = TicksPerMillisecond * 1000; private long elapsed; private long startTimeStamp; private bool isRunning; // "Frequency" stores the frequency of the high-resolution performance counter, // if one exists. Otherwise it will store TicksPerSecond. // The frequency cannot change while the system is running, // so we only need to initialize it once. public static readonly long Frequency; public static readonly bool IsHighResolution; // performance-counter frequency, in counts per ticks. // This can speed up conversion from high frequency performance-counter // to ticks. private static readonly double tickFrequency; static Stopwatch() { bool succeeded = QueryPerformanceFrequency( out Frequency ); if(!succeeded) { IsHighResolution = false; Frequency = TicksPerSecond; tickFrequency = 1; } else { IsHighResolution = true; tickFrequency = TicksPerSecond; tickFrequency /= Frequency; } } public Stopwatch() { Reset(); } public void Start() { // Calling start on a running Stopwatch is a no-op. if(!isRunning) { startTimeStamp = GetTimestamp(); isRunning = true; } } public static Stopwatch StartNew() { Stopwatch s = new Stopwatch(); s.Start(); return s; } public void Stop() { // Calling stop on a stopped Stopwatch is a no-op. if(isRunning) { long endTimeStamp = GetTimestamp(); long elapsedThisPeriod = endTimeStamp - startTimeStamp; elapsed += elapsedThisPeriod; isRunning = false; if(elapsed < 0) { // When measuring small time periods the StopWatch.Elapsed* // properties can return negative values. This is due to // bugs in the basic input/output system (BIOS) or the hardware // abstraction layer (HAL) on machines with variable-speed CPUs // (e.g. Intel SpeedStep). elapsed = 0; } } } public void Reset() { elapsed = 0; isRunning = false; startTimeStamp = 0; } public bool IsRunning { get { return isRunning; } } public TimeSpan Elapsed { get { return new TimeSpan( GetElapsedDateTimeTicks() ); } } public long ElapsedMilliseconds { get { return GetElapsedDateTimeTicks() / TicksPerMillisecond; } } public long ElapsedTicks { get { return GetRawElapsedTicks(); } } public static long GetTimestamp() { if(IsHighResolution) { long timestamp = 0; QueryPerformanceCounter( out timestamp ); return timestamp; } else { return DateTime.UtcNow.Ticks; } } // Get the elapsed ticks. private long GetRawElapsedTicks() { long timeElapsed = elapsed; if(isRunning) { // If the StopWatch is running, add elapsed time since // the Stopwatch is started last time. long currentTimeStamp = GetTimestamp(); long elapsedUntilNow = currentTimeStamp - startTimeStamp; timeElapsed += elapsedUntilNow; } return timeElapsed; } // Get the elapsed ticks. private long GetElapsedDateTimeTicks() { long rawTicks = GetRawElapsedTicks(); if(IsHighResolution) { // convert high resolution perf counter to DateTime ticks double dticks = rawTicks; dticks *= tickFrequency; return unchecked( (long)dticks ); } else { return rawTicks; } } //--// [MethodImpl( MethodImplOptions.InternalCall )] private static extern bool QueryPerformanceFrequency( out long Frequency ); [MethodImpl( MethodImplOptions.InternalCall )] private static extern void QueryPerformanceCounter( out long timestamp ); } } ================================================ FILE: Zelig/Zelig/RunTime/Framework/system/System/Diagnostics/Trace.cs ================================================ //------------------------------------------------------------------------------ // // Copyright (c) Microsoft Corporation. All rights reserved. // //------------------------------------------------------------------------------ /* */ #define TRACE namespace System.Diagnostics { using System; using System.Collections; using System.Security.Permissions; using System.Threading; /// /// Provides a set of properties and methods to trace the execution of your code. /// public sealed class Trace { //// private static CorrelationManager correlationManager = null; // not creatble... // private Trace() { } /// /// Gets the collection of listeners that is monitoring the trace output. /// public static TraceListenerCollection Listeners { [HostProtection( SharedState = true )] get { // Do a full damand //////new SecurityPermission( SecurityPermissionFlag.UnmanagedCode ).Demand( ); return TraceInternal.Listeners; } } /// /// /// Gets or sets whether should be called on the after every write. /// /// public static bool AutoFlush { [SecurityPermission( SecurityAction.LinkDemand, Flags = SecurityPermissionFlag.UnmanagedCode )] get { return TraceInternal.AutoFlush; } [SecurityPermission( SecurityAction.LinkDemand, Flags = SecurityPermissionFlag.UnmanagedCode )] set { TraceInternal.AutoFlush = value; } } public static bool UseGlobalLock { [SecurityPermission( SecurityAction.LinkDemand, Flags = SecurityPermissionFlag.UnmanagedCode )] get { return TraceInternal.UseGlobalLock; } [SecurityPermission( SecurityAction.LinkDemand, Flags = SecurityPermissionFlag.UnmanagedCode )] set { TraceInternal.UseGlobalLock = value; } } //////public static CorrelationManager CorrelationManager //////{ ////// [SecurityPermission( SecurityAction.LinkDemand, Flags = SecurityPermissionFlag.UnmanagedCode )] ////// get ////// { ////// if(correlationManager == null) ////// correlationManager = new CorrelationManager( ); ////// return correlationManager; ////// } //////} /// /// Gets or sets the indent level. /// public static int IndentLevel { get { return TraceInternal.IndentLevel; } set { TraceInternal.IndentLevel = value; } } /// /// /// Gets or sets the number of spaces in an indent. /// /// public static int IndentSize { get { return TraceInternal.IndentSize; } set { TraceInternal.IndentSize = value; } } /// /// Clears the output buffer, and causes buffered data to /// be written to the . /// [System.Diagnostics.Conditional( "TRACE" )] public static void Flush() { TraceInternal.Flush( ); } /// /// Clears the output buffer, and then closes the so that they no /// longer receive debugging output. /// [System.Diagnostics.Conditional( "TRACE" )] public static void Close() { //// // Do a full damand //// new SecurityPermission( SecurityPermissionFlag.UnmanagedCode ).Demand(); //// TraceInternal.Close( ); } /// /// Checks for a condition, and outputs the callstack if the /// condition /// is . /// [System.Diagnostics.Conditional( "TRACE" )] public static void Assert( bool condition ) { TraceInternal.Assert( condition ); } /// /// Checks for a condition, and displays a message if the condition is /// . /// [System.Diagnostics.Conditional( "TRACE" )] public static void Assert( bool condition, string message ) { TraceInternal.Assert( condition, message ); } /// /// Checks for a condition, and displays both messages if the condition /// is . /// [System.Diagnostics.Conditional( "TRACE" )] public static void Assert( bool condition, string message, string detailMessage ) { TraceInternal.Assert( condition, message, detailMessage ); } /// /// Emits or displays a message for an assertion that always fails. /// [System.Diagnostics.Conditional( "TRACE" )] public static void Fail( string message ) { TraceInternal.Fail( message ); } /// /// Emits or displays both messages for an assertion that always fails. /// [System.Diagnostics.Conditional( "TRACE" )] public static void Fail( string message, string detailMessage ) { TraceInternal.Fail( message, detailMessage ); } public static void Refresh() { //// DiagnosticsConfiguration.Refresh(); //// Switch.RefreshAll(); //// TraceSource.RefreshAll(); } [System.Diagnostics.Conditional( "TRACE" )] public static void TraceInformation( string message ) { TraceInternal.TraceEvent( TraceEventType.Information, 0, message, null ); } [System.Diagnostics.Conditional( "TRACE" )] public static void TraceInformation( string format , params object[] args ) { TraceInternal.TraceEvent( TraceEventType.Information, 0, format, args ); } [System.Diagnostics.Conditional( "TRACE" )] public static void TraceWarning( string message ) { TraceInternal.TraceEvent( TraceEventType.Warning, 0, message, null ); } [System.Diagnostics.Conditional( "TRACE" )] public static void TraceWarning( string format , params object[] args ) { TraceInternal.TraceEvent( TraceEventType.Warning, 0, format, args ); } [System.Diagnostics.Conditional( "TRACE" )] public static void TraceError( string message ) { TraceInternal.TraceEvent( TraceEventType.Error, 0, message, null ); } [System.Diagnostics.Conditional( "TRACE" )] public static void TraceError( string format , params object[] args ) { TraceInternal.TraceEvent( TraceEventType.Error, 0, format, args ); } /// /// Writes a message to the trace listeners in the /// collection. /// [System.Diagnostics.Conditional( "TRACE" )] public static void Write( string message ) { TraceInternal.Write( message ); } /// /// Writes the name of the /// parameter to the trace listeners in the collection. /// [System.Diagnostics.Conditional( "TRACE" )] public static void Write( object value ) { TraceInternal.Write( value ); } /// /// Writes a category name and message to the trace listeners /// in the collection. /// [System.Diagnostics.Conditional( "TRACE" )] public static void Write( string message , string category ) { TraceInternal.Write( message, category ); } /// /// Writes a category name and the name of the value parameter to the trace listeners /// in the collection. /// [System.Diagnostics.Conditional( "TRACE" )] public static void Write( object value , string category ) { TraceInternal.Write( value, category ); } /// /// Writes a message followed by a line terminator to the /// trace listeners in the collection. /// The default line terminator is a carriage return followed by a line feed (\r\n). /// [System.Diagnostics.Conditional( "TRACE" )] public static void WriteLine( string message ) { TraceInternal.WriteLine( message ); } /// /// Writes the name of the parameter followed by a line terminator to the trace listeners in the collection. The default line /// terminator is a carriage return followed by a line feed (\r\n). /// [System.Diagnostics.Conditional( "TRACE" )] public static void WriteLine( object value ) { TraceInternal.WriteLine( value ); } /// /// Writes a category name and message followed by a line terminator to the trace /// listeners in the /// collection. The default line terminator is a carriage return followed by a line /// feed (\r\n). /// [System.Diagnostics.Conditional( "TRACE" )] public static void WriteLine( string message , string category ) { TraceInternal.WriteLine( message, category ); } /// /// Writes a name and the name of the parameter followed by a line /// terminator to the trace listeners in the collection. The default line /// terminator is a carriage return followed by a line feed (\r\n). /// [System.Diagnostics.Conditional( "TRACE" )] public static void WriteLine( object value , string category ) { TraceInternal.WriteLine( value, category ); } /// /// Writes a message to the trace listeners in the collection /// if a condition is . /// [System.Diagnostics.Conditional( "TRACE" )] public static void WriteIf( bool condition , string message ) { TraceInternal.WriteIf( condition, message ); } /// /// Writes the name of the /// parameter to the trace listeners in the collection if a condition is /// . /// [System.Diagnostics.Conditional( "TRACE" )] public static void WriteIf( bool condition , object value ) { TraceInternal.WriteIf( condition, value ); } /// /// Writes a category name and message to the trace listeners in the /// collection if a condition is . /// [System.Diagnostics.Conditional( "TRACE" )] public static void WriteIf( bool condition , string message , string category ) { TraceInternal.WriteIf( condition, message, category ); } /// /// Writes a category name and the name of the parameter to the trace /// listeners in the collection /// if a condition is . /// [System.Diagnostics.Conditional( "TRACE" )] public static void WriteIf( bool condition , object value , string category ) { TraceInternal.WriteIf( condition, value, category ); } /// /// Writes a message followed by a line terminator to the trace listeners in the /// collection if a condition is /// . The default line terminator is a carriage return followed /// by a line feed (\r\n). /// [System.Diagnostics.Conditional( "TRACE" )] public static void WriteLineIf( bool condition , string message ) { TraceInternal.WriteLineIf( condition, message ); } /// /// Writes the name of the parameter followed by a line terminator to the /// trace listeners in the collection /// if a condition is /// . The default line /// terminator is a carriage return followed by a line feed (\r\n). /// [System.Diagnostics.Conditional( "TRACE" )] public static void WriteLineIf( bool condition , object value ) { TraceInternal.WriteLineIf( condition, value ); } /// /// Writes a category name and message followed by a line terminator to the trace /// listeners in the collection if a condition is /// . The default line terminator is a carriage return followed by a line feed (\r\n). /// [System.Diagnostics.Conditional( "TRACE" )] public static void WriteLineIf( bool condition , string message , string category ) { TraceInternal.WriteLineIf( condition, message, category ); } /// /// Writes a category name and the name of the parameter followed by a line /// terminator to the trace listeners in the collection /// if a is . The /// default line terminator is a carriage return followed by a line feed (\r\n). /// [System.Diagnostics.Conditional( "TRACE" )] public static void WriteLineIf( bool condition , object value , string category ) { TraceInternal.WriteLineIf( condition, value, category ); } /// /// [To be supplied.] /// [System.Diagnostics.Conditional( "TRACE" )] public static void Indent() { TraceInternal.Indent(); } /// /// [To be supplied.] /// [System.Diagnostics.Conditional( "TRACE" )] public static void Unindent() { TraceInternal.Unindent(); } } } ================================================ FILE: Zelig/Zelig/RunTime/Framework/system/System/Diagnostics/TraceEventCache.cs ================================================ //------------------------------------------------------------------------------ // // Copyright (c) Microsoft Corporation. All rights reserved. // //------------------------------------------------------------------------------ using System.Threading; using System.Security.Permissions; using System.Collections; using System.Globalization; namespace System.Diagnostics { public class TraceEventCache { //////private static volatile int processId; //////private static volatile string processName; private long timeStamp = -1; private DateTime dateTime = DateTime.MinValue; //////private string stackTrace = null; //////internal Guid ActivityId { ////// get { return Trace.CorrelationManager.ActivityId; } //////} //////public string Callstack //////{ ////// get ////// { ////// if(stackTrace == null) ////// stackTrace = Environment.StackTrace; ////// //////else ////// ////// new EnvironmentPermission( PermissionState.Unrestricted ).Demand( ); ////// return stackTrace; ////// } //////} //////public Stack LogicalOperationStack { ////// get { ////// return Trace.CorrelationManager.LogicalOperationStack; ////// } //////} public Stack LogicalOperationStack { get { return new Stack(); } } public DateTime DateTime { get { if (dateTime == DateTime.MinValue) dateTime = DateTime.UtcNow; return dateTime; } } public int ProcessId { //////[ResourceExposure(ResourceScope.Process)] // Returns the current process's pid //////[ResourceConsumption(ResourceScope.Process)] get { return GetProcessId(); } } public string ThreadId { get { return GetThreadId().ToString(CultureInfo.InvariantCulture); } } public long Timestamp { get { if (timeStamp == -1) timeStamp = Stopwatch.GetTimestamp(); return timeStamp ; } } //////[ResourceExposure(ResourceScope.None)] //////[ResourceConsumption(ResourceScope.Machine, ResourceScope.Machine)] //////private static void InitProcessInfo() { ////// // Demand unmanaged code permission ////// new SecurityPermission(SecurityPermissionFlag.UnmanagedCode).Demand(); ////// if (processName == null) { ////// Process p = Process.GetCurrentProcess(); ////// try { ////// processId = p.Id; ////// processName = p.ProcessName; ////// } ////// finally { ////// p.Dispose(); ////// } ////// } //////} //////[ResourceExposure(ResourceScope.Process)] internal static int GetProcessId() { //////InitProcessInfo(); //////return processId; return 42; } internal static string GetProcessName() { //////InitProcessInfo(); //////return processName; return "llilum"; } internal static int GetThreadId() { return Thread.CurrentThread.ManagedThreadId; } } } ================================================ FILE: Zelig/Zelig/RunTime/Framework/system/System/Diagnostics/TraceEventType.cs ================================================ //------------------------------------------------------------------------------ // // Copyright (c) Microsoft Corporation. All rights reserved. // //------------------------------------------------------------------------------ using System; using System.ComponentModel; namespace System.Diagnostics { public enum TraceEventType { Critical = 0x01, Error = 0x02, Warning = 0x04, Information = 0x08, Verbose = 0x10, [EditorBrowsable(EditorBrowsableState.Advanced)] Start = 0x0100, [EditorBrowsable(EditorBrowsableState.Advanced)] Stop = 0x0200, [EditorBrowsable(EditorBrowsableState.Advanced)] Suspend = 0x0400, [EditorBrowsable(EditorBrowsableState.Advanced)] Resume = 0x0800, [EditorBrowsable(EditorBrowsableState.Advanced)] Transfer = 0x1000, } } ================================================ FILE: Zelig/Zelig/RunTime/Framework/system/System/Diagnostics/TraceFilter.cs ================================================ //------------------------------------------------------------------------------ // // Copyright (c) Microsoft Corporation. All rights reserved. // //------------------------------------------------------------------------------ using System; namespace System.Diagnostics { public abstract class TraceFilter { internal string initializeData; public abstract bool ShouldTrace(TraceEventCache cache, string source, TraceEventType eventType, int id, string formatOrMessage, object[] args, object data1, object[] data); internal bool ShouldTrace(TraceEventCache cache, string source, TraceEventType eventType, int id, string formatOrMessage) { return ShouldTrace(cache, source, eventType, id, formatOrMessage, null, null, null); } internal bool ShouldTrace(TraceEventCache cache, string source, TraceEventType eventType, int id, string formatOrMessage, object[] args) { return ShouldTrace(cache, source, eventType, id, formatOrMessage, args, null, null); } internal bool ShouldTrace(TraceEventCache cache, string source, TraceEventType eventType, int id, string formatOrMessage, object[] args, object data1) { return ShouldTrace(cache, source, eventType, id, formatOrMessage, args, data1, null); } } } ================================================ FILE: Zelig/Zelig/RunTime/Framework/system/System/Diagnostics/TraceInternal.cs ================================================ //------------------------------------------------------------------------------ // // Copyright (c) Microsoft Corporation. All rights reserved. // //------------------------------------------------------------------------------ namespace System.Diagnostics { using System.Threading; using System.IO; using System.Security.Permissions; using System.Collections; internal static class TraceInternal { //////private static volatile string appName = null; static volatile TraceListenerCollection listeners; static volatile bool autoFlush; static volatile bool useGlobalLock; [ThreadStatic] static int indentLevel; static volatile int indentSize; static volatile bool settingsInitialized; // this is internal so TraceSource can use it. We want to lock on the same object because both TraceInternal and // TraceSource could be writing to the same listeners at the same time. internal static readonly object critSec = new object(); public static TraceListenerCollection Listeners { get { InitializeSettings(); if (listeners == null) { lock (critSec) { if (listeners == null) { // We only need to check that the main section exists. Everything else will get // created for us if it doesn't exist already. //////SystemDiagnosticsSection configSectionSav = DiagnosticsConfiguration.SystemDiagnosticsSection; //////if (configSectionSav != null) { ////// listeners = configSectionSav.Trace.Listeners.GetRuntimeObject(); //////} //////else { // If machine.config was deleted the code will get to here // supply at least something to prevent the world from coming to // an abrupt end. listeners = new TraceListenerCollection(); TraceListener defaultListener = new DefaultTraceListener(); defaultListener.IndentLevel = indentLevel; defaultListener.IndentSize = indentSize; listeners.Add(defaultListener); //////} } } } return listeners; } } internal static string AppName { get { //////if (appName == null) { ////// new EnvironmentPermission(EnvironmentPermissionAccess.Read, "Path").Assert(); ////// appName = Path.GetFileName(Environment.GetCommandLineArgs()[0]); //////} //////return appName; return "llilum"; } } public static bool AutoFlush { get { InitializeSettings(); return autoFlush; } set { InitializeSettings(); autoFlush = value; } } public static bool UseGlobalLock { get { InitializeSettings(); return useGlobalLock; } set { InitializeSettings(); useGlobalLock = value; } } public static int IndentLevel { get { return indentLevel; } set { // Use global lock lock (critSec) { // We don't want to throw here -- it is very bad form to have debug or trace // code throw exceptions! if (value < 0) { value = 0; } indentLevel = value; if (listeners != null) { foreach (TraceListener listener in Listeners) { listener.IndentLevel = indentLevel; } } } } } public static int IndentSize { get { InitializeSettings(); return indentSize; } set { InitializeSettings(); SetIndentSize(value); } } static void SetIndentSize(int value) { // Use global lock lock (critSec) { // We don't want to throw here -- it is very bad form to have debug or trace // code throw exceptions! if (value < 0) { value = 0; } indentSize = value; if (listeners != null) { foreach (TraceListener listener in Listeners) { listener.IndentSize = indentSize; } } } } public static void Indent() { // Use global lock lock (critSec) { InitializeSettings(); if (indentLevel < Int32.MaxValue) { indentLevel++; } foreach (TraceListener listener in Listeners) { listener.IndentLevel = indentLevel; } } } public static void Unindent() { // Use global lock lock (critSec) { InitializeSettings(); if (indentLevel > 0) { indentLevel--; } foreach (TraceListener listener in Listeners) { listener.IndentLevel = indentLevel; } } } public static void Flush() { if (listeners != null) { if (UseGlobalLock) { lock (critSec) { foreach (TraceListener listener in Listeners) { listener.Flush(); } } } else { foreach (TraceListener listener in Listeners) { if (!listener.IsThreadSafe) { lock (listener) { listener.Flush(); } } else { listener.Flush(); } } } } } public static void Close() { if (listeners != null) { // Use global lock lock (critSec) { foreach (TraceListener listener in Listeners) { listener.Close(); } } } } public static void Assert(bool condition) { if (condition) return; Fail(string.Empty); } public static void Assert(bool condition, string message) { if (condition) return; Fail(message); } public static void Assert(bool condition, string message, string detailMessage) { if (condition) return; Fail(message, detailMessage); } public static void Fail(string message) { if (UseGlobalLock) { lock (critSec) { foreach (TraceListener listener in Listeners) { listener.Fail(message); if (AutoFlush) listener.Flush(); } } } else { foreach (TraceListener listener in Listeners) { if (!listener.IsThreadSafe) { lock (listener) { listener.Fail(message); if (AutoFlush) listener.Flush(); } } else { listener.Fail(message); if (AutoFlush) listener.Flush(); } } } } public static void Fail(string message, string detailMessage) { if (UseGlobalLock) { lock (critSec) { foreach (TraceListener listener in Listeners) { listener.Fail(message, detailMessage); if (AutoFlush) listener.Flush(); } } } else { foreach (TraceListener listener in Listeners) { if (!listener.IsThreadSafe) { lock (listener) { listener.Fail(message, detailMessage); if (AutoFlush) listener.Flush(); } } else { listener.Fail(message, detailMessage); if (AutoFlush) listener.Flush(); } } } } private static void InitializeSettings() { // we want to redo this logic exactly once if the last time we entered the config // system was still initializing. (ASURT 111941, VSWhidbey 149552) //////if (!settingsInitialized || (defaultInitialized && DiagnosticsConfiguration.IsInitialized())) { ////// // we should avoid 2 threads altering the state concurrently for predictable behavior ////// // though it may not be strictly necessary at present ////// lock(critSec) { ////// if (!settingsInitialized || (defaultInitialized && DiagnosticsConfiguration.IsInitialized())) { ////// defaultInitialized = DiagnosticsConfiguration.IsInitializing(); ////// // Getting IndentSize and AutoFlush will load config on demand. ////// // If we load config and there are trace listeners added, we'll ////// // end up recursing, but that recursion will be stopped in ////// // DiagnosticsConfiguration.Initialize() ////// SetIndentSize(DiagnosticsConfiguration.IndentSize); ////// autoFlush = DiagnosticsConfiguration.AutoFlush; ////// useGlobalLock = DiagnosticsConfiguration.UseGlobalLock; ////// settingsInitialized = true; ////// } ////// } //////} if (!settingsInitialized) { // we should avoid 2 threads altering the state concurrently for predictable behavior // though it may not be strictly necessary at present lock(critSec) { if (!settingsInitialized) { // Getting IndentSize and AutoFlush will load config on demand. // If we load config and there are trace listeners added, we'll // end up recursing, but that recursion will be stopped in // DiagnosticsConfiguration.Initialize() SetIndentSize(2); useGlobalLock = true; settingsInitialized = true; } } } } // This method refreshes all the data from the configuration file, so that updated to the configuration file are mirrored // in the System.Diagnostics.Trace class static internal void Refresh() { lock (critSec) { settingsInitialized = false; listeners = null; } InitializeSettings(); } public static void TraceEvent(TraceEventType eventType, int id, string format, params object[] args) { TraceEventCache EventCache = new TraceEventCache(); if (UseGlobalLock) { lock (critSec) { if (args == null) { foreach (TraceListener listener in Listeners) { listener.TraceEvent(EventCache, AppName, eventType, id, format); if (AutoFlush) listener.Flush(); } } else { foreach (TraceListener listener in Listeners) { listener.TraceEvent(EventCache, AppName, eventType, id, format, args); if (AutoFlush) listener.Flush(); } } } } else { if (args == null) { foreach (TraceListener listener in Listeners) { if (!listener.IsThreadSafe) { lock (listener) { listener.TraceEvent(EventCache, AppName, eventType, id, format); if (AutoFlush) listener.Flush(); } } else { listener.TraceEvent(EventCache, AppName, eventType, id, format); if (AutoFlush) listener.Flush(); } } } else { foreach (TraceListener listener in Listeners) { if (!listener.IsThreadSafe) { lock (listener) { listener.TraceEvent(EventCache, AppName, eventType, id, format, args); if (AutoFlush) listener.Flush(); } } else { listener.TraceEvent(EventCache, AppName, eventType, id, format, args); if (AutoFlush) listener.Flush(); } } } } } public static void Write(string message) { if (UseGlobalLock) { lock (critSec) { foreach (TraceListener listener in Listeners) { listener.Write(message); if (AutoFlush) listener.Flush(); } } } else { foreach (TraceListener listener in Listeners) { if (!listener.IsThreadSafe) { lock (listener) { listener.Write(message); if (AutoFlush) listener.Flush(); } } else { listener.Write(message); if (AutoFlush) listener.Flush(); } } } } public static void Write(object value) { if (UseGlobalLock) { lock (critSec) { foreach (TraceListener listener in Listeners) { listener.Write(value); if (AutoFlush) listener.Flush(); } } } else { foreach (TraceListener listener in Listeners) { if (!listener.IsThreadSafe) { lock (listener) { listener.Write(value); if (AutoFlush) listener.Flush(); } } else { listener.Write(value); if (AutoFlush) listener.Flush(); } } } } public static void Write(string message, string category) { if (UseGlobalLock) { lock (critSec) { foreach (TraceListener listener in Listeners) { listener.Write(message, category); if (AutoFlush) listener.Flush(); } } } else { foreach (TraceListener listener in Listeners) { if (!listener.IsThreadSafe) { lock (listener) { listener.Write(message, category); if (AutoFlush) listener.Flush(); } } else { listener.Write(message, category); if (AutoFlush) listener.Flush(); } } } } public static void Write(object value, string category) { if (UseGlobalLock) { lock (critSec) { foreach (TraceListener listener in Listeners) { listener.Write(value, category); if (AutoFlush) listener.Flush(); } } } else { foreach (TraceListener listener in Listeners) { if (!listener.IsThreadSafe) { lock (listener) { listener.Write(value, category); if (AutoFlush) listener.Flush(); } } else { listener.Write(value, category); if (AutoFlush) listener.Flush(); } } } } public static void WriteLine(string message) { if (UseGlobalLock) { lock (critSec) { foreach (TraceListener listener in Listeners) { listener.WriteLine(message); if (AutoFlush) listener.Flush(); } } } else { foreach (TraceListener listener in Listeners) { if (!listener.IsThreadSafe) { lock (listener) { listener.WriteLine(message); if (AutoFlush) listener.Flush(); } } else { listener.WriteLine(message); if (AutoFlush) listener.Flush(); } } } } public static void WriteLine(object value) { if (UseGlobalLock) { lock (critSec) { foreach (TraceListener listener in Listeners) { listener.WriteLine(value); if (AutoFlush) listener.Flush(); } } } else { foreach (TraceListener listener in Listeners) { if (!listener.IsThreadSafe) { lock (listener) { listener.WriteLine(value); if (AutoFlush) listener.Flush(); } } else { listener.WriteLine(value); if (AutoFlush) listener.Flush(); } } } } public static void WriteLine(string message, string category) { if (UseGlobalLock) { lock (critSec) { foreach (TraceListener listener in Listeners) { listener.WriteLine(message, category); if (AutoFlush) listener.Flush(); } } } else { foreach (TraceListener listener in Listeners) { if (!listener.IsThreadSafe) { lock (listener) { listener.WriteLine(message, category); if (AutoFlush) listener.Flush(); } } else { listener.WriteLine(message, category); if (AutoFlush) listener.Flush(); } } } } public static void WriteLine(object value, string category) { if (UseGlobalLock) { lock (critSec) { foreach (TraceListener listener in Listeners) { listener.WriteLine(value, category); if (AutoFlush) listener.Flush(); } } } else { foreach (TraceListener listener in Listeners) { if (!listener.IsThreadSafe) { lock (listener) { listener.WriteLine(value, category); if (AutoFlush) listener.Flush(); } } else { listener.WriteLine(value, category); if (AutoFlush) listener.Flush(); } } } } public static void WriteIf(bool condition, string message) { if (condition) Write(message); } public static void WriteIf(bool condition, object value) { if (condition) Write(value); } public static void WriteIf(bool condition, string message, string category) { if (condition) Write(message, category); } public static void WriteIf(bool condition, object value, string category) { if (condition) Write(value, category); } public static void WriteLineIf(bool condition, string message) { if (condition) WriteLine(message); } public static void WriteLineIf(bool condition, object value) { if (condition) WriteLine(value); } public static void WriteLineIf(bool condition, string message, string category) { if (condition) WriteLine(message, category); } public static void WriteLineIf(bool condition, object value, string category) { if (condition) WriteLine(value, category); } } } ================================================ FILE: Zelig/Zelig/RunTime/Framework/system/System/Diagnostics/TraceListener.cs ================================================ //------------------------------------------------------------------------------ // // Copyright (c) Microsoft Corporation. All rights reserved. // //------------------------------------------------------------------------------ /* */ namespace System.Diagnostics { using System; using System.Text; using System.Security.Permissions; using System.Globalization; using System.Runtime.InteropServices; using System.Collections; /// /// Provides the base class for the listeners who /// monitor trace and debug output. /// [HostProtection(Synchronization=true)] public abstract class TraceListener : MarshalByRefObject, IDisposable { int indentLevel; int indentSize = 4; TraceOptions traceOptions = TraceOptions.None; bool needIndent = true; string listenerName; TraceFilter filter = null; //////StringDictionary attributes; internal string initializeData; /// /// Initializes a new instance of the class. /// protected TraceListener () { } /// /// Initializes a new instance of the class using the specified name as the /// listener. /// protected TraceListener(string name) { this.listenerName = name; } //////public StringDictionary Attributes { ////// get { ////// if (attributes == null) ////// attributes = new StringDictionary(); ////// return attributes; ////// } //////} /// /// Gets or sets a name for this . /// public virtual string Name { get { return (listenerName == null) ? "" : listenerName; } set { listenerName = value; } } public virtual bool IsThreadSafe { get { return false; } } /// /// public void Dispose() { Dispose(true); GC.SuppressFinalize(this); } /// /// protected virtual void Dispose(bool disposing) { return; } /// /// When overridden in a derived class, closes the output stream /// so that it no longer receives tracing or debugging output. /// public virtual void Close() { return; } /// /// When overridden in a derived class, flushes the output buffer. /// public virtual void Flush() { return; } /// /// Gets or sets the indent level. /// public int IndentLevel { get { return indentLevel; } set { indentLevel = (value < 0) ? 0 : value; } } /// /// Gets or sets the number of spaces in an indent. /// public int IndentSize { get { return indentSize; } set { if (value < 0) throw new ArgumentOutOfRangeException(/*"IndentSize", value, SR.GetString(SR.TraceListenerIndentSize)*/); indentSize = value; } } [ ComVisible(false) ] public TraceFilter Filter { get { return filter; } set { filter = value; } } /// /// Gets or sets a value indicating whether an indent is needed. /// protected bool NeedIndent { get { return needIndent; } set { needIndent = value; } } [ ComVisible(false) ] public TraceOptions TraceOutputOptions { get { return traceOptions; } set { if (( (int) value >> 6) != 0) { throw new ArgumentOutOfRangeException("value"); } traceOptions = value; } } //////internal void SetAttributes(Hashtable attribs) { ////// TraceUtils.VerifyAttributes(attribs, GetSupportedAttributes(), this); ////// attributes = new StringDictionary(); ////// attributes.ReplaceHashtable(attribs); //////} /// /// Emits or displays a message for an assertion that always fails. /// public virtual void Fail(string message) { Fail(message, null); } /// /// Emits or displays messages for an assertion that always fails. /// public virtual void Fail(string message, string detailMessage) { StringBuilder failMessage = new StringBuilder(); failMessage.Append("TraceListenerFail:"/*SR.GetString(SR.TraceListenerFail)*/); failMessage.Append(" "); failMessage.Append(message); if (detailMessage != null) { failMessage.Append(" "); failMessage.Append(detailMessage); } WriteLine(failMessage.ToString()); } virtual protected internal string[] GetSupportedAttributes() { return null; } /// /// When overridden in a derived class, writes the specified /// message to the listener you specify in the derived class. /// public abstract void Write(string message); /// /// Writes the name of the parameter to the listener you specify when you inherit from the /// class. /// public virtual void Write(object o) { if (Filter != null && !Filter.ShouldTrace(null, "", TraceEventType.Verbose, 0, null, null, o)) return; if (o == null) return; Write(o.ToString()); } /// /// Writes a category name and a message to the listener you specify when you /// inherit from the /// class. /// public virtual void Write(string message, string category) { if (Filter != null && !Filter.ShouldTrace(null, "", TraceEventType.Verbose, 0, message)) return; if (category == null) Write(message); else Write(category + ": " + ((message == null) ? string.Empty : message)); } /// /// Writes a category name and the name of the parameter to the listener you /// specify when you inherit from the /// class. /// public virtual void Write(object o, string category) { if (Filter != null && !Filter.ShouldTrace(null, "", TraceEventType.Verbose, 0, category, null, o)) return; if (category == null) Write(o); else Write(o == null ? "" : o.ToString(), category); } /// /// Writes the indent to the listener you specify when you /// inherit from the /// class, and resets the property to . /// protected virtual void WriteIndent() { NeedIndent = false; for (int i = 0; i < indentLevel; i++) { if (indentSize == 4) Write(" "); else { for (int j = 0; j < indentSize; j++) { Write(" "); } } } } /// /// When overridden in a derived class, writes a message to the listener you specify in /// the derived class, followed by a line terminator. The default line terminator is a carriage return followed /// by a line feed (\r\n). /// public abstract void WriteLine(string message); /// /// Writes the name of the parameter to the listener you specify when you inherit from the class, followed by a line terminator. The default line terminator is a /// carriage return followed by a line feed /// (\r\n). /// public virtual void WriteLine(object o) { if (Filter != null && !Filter.ShouldTrace(null, "", TraceEventType.Verbose, 0, null, null, o)) return; WriteLine(o == null ? "" : o.ToString()); } /// /// Writes a category name and a message to the listener you specify when you /// inherit from the class, /// followed by a line terminator. The default line terminator is a carriage return followed by a line feed (\r\n). /// public virtual void WriteLine(string message, string category) { if (Filter != null && !Filter.ShouldTrace(null, "", TraceEventType.Verbose, 0, message)) return; if (category == null) WriteLine(message); else WriteLine(category + ": " + ((message == null) ? string.Empty : message)); } /// /// Writes a category /// name and the name of the parameter to the listener you /// specify when you inherit from the /// class, followed by a line terminator. The default line terminator is a carriage /// return followed by a line feed (\r\n). /// public virtual void WriteLine(object o, string category) { if (Filter != null && !Filter.ShouldTrace(null, "", TraceEventType.Verbose, 0, category, null, o)) return; WriteLine(o == null ? "" : o.ToString(), category); } // new write methods used by TraceSource [ ComVisible(false) ] public virtual void TraceData(TraceEventCache eventCache, String source, TraceEventType eventType, int id, object data) { if (Filter != null && !Filter.ShouldTrace(eventCache, source, eventType, id, null, null, data)) return; WriteHeader(source, eventType, id); string datastring = String.Empty; if (data != null) datastring = data.ToString(); WriteLine(datastring); WriteFooter(eventCache); } [ ComVisible(false) ] public virtual void TraceData(TraceEventCache eventCache, String source, TraceEventType eventType, int id, params object[] data) { if (Filter != null && !Filter.ShouldTrace(eventCache, source, eventType, id, null, null, null, data)) return; WriteHeader(source, eventType, id); StringBuilder sb = new StringBuilder(); if (data != null) { for (int i=0; i< data.Length; i++) { if (i != 0) sb.Append(", "); if (data[i] != null) sb.Append(data[i].ToString()); } } WriteLine(sb.ToString()); WriteFooter(eventCache); } [ ComVisible(false) ] public virtual void TraceEvent(TraceEventCache eventCache, String source, TraceEventType eventType, int id) { TraceEvent(eventCache, source, eventType, id, String.Empty); } // All other TraceEvent methods come through this one. [ ComVisible(false) ] public virtual void TraceEvent(TraceEventCache eventCache, String source, TraceEventType eventType, int id, string message) { if (Filter != null && !Filter.ShouldTrace(eventCache, source, eventType, id, message)) return; WriteHeader(source, eventType, id); WriteLine(message); WriteFooter(eventCache); } [ ComVisible(false) ] public virtual void TraceEvent(TraceEventCache eventCache, String source, TraceEventType eventType, int id, string format, params object[] args) { if (Filter != null && !Filter.ShouldTrace(eventCache, source, eventType, id, format, args)) return; WriteHeader(source, eventType, id); if (args != null) WriteLine(String.Format(CultureInfo.InvariantCulture, format, args)); else WriteLine(format); WriteFooter(eventCache); } [ ComVisible(false) ] public virtual void TraceTransfer(TraceEventCache eventCache, String source, int id, string message, Guid relatedActivityId) { TraceEvent(eventCache, source, TraceEventType.Transfer, id, message + ", relatedActivityId=" + relatedActivityId.ToString()); } private void WriteHeader(String source, TraceEventType eventType, int id) { Write(String.Format(CultureInfo.InvariantCulture, "{0} {1}: {2} : ", source, eventType.ToString(), id.ToString(CultureInfo.InvariantCulture))); } //////[ResourceExposure(ResourceScope.None)] //////[ResourceConsumption(ResourceScope.Machine, ResourceScope.Machine)] private void WriteFooter(TraceEventCache eventCache) { if (eventCache == null) return; indentLevel++; if (IsEnabled(TraceOptions.ProcessId)) WriteLine("ProcessId=" + eventCache.ProcessId); if (IsEnabled(TraceOptions.LogicalOperationStack)) { Write("LogicalOperationStack="); Stack operationStack = eventCache.LogicalOperationStack; bool first = true; foreach (Object obj in operationStack) { if (!first) Write(", "); else first = false; Write(obj.ToString()); } WriteLine(String.Empty); } if (IsEnabled(TraceOptions.ThreadId)) WriteLine("ThreadId=" + eventCache.ThreadId); if (IsEnabled(TraceOptions.DateTime)) WriteLine("DateTime=" + eventCache.DateTime.ToString("o"/*, CultureInfo.InvariantCulture*/)); if (IsEnabled(TraceOptions.Timestamp)) WriteLine("Timestamp=" + eventCache.Timestamp); //////if (IsEnabled(TraceOptions.Callstack)) ////// WriteLine("Callstack=" + eventCache.Callstack); indentLevel--; } internal bool IsEnabled(TraceOptions opts) { return (opts & TraceOutputOptions) != 0; } } } ================================================ FILE: Zelig/Zelig/RunTime/Framework/system/System/Diagnostics/TraceListeners.cs ================================================ //------------------------------------------------------------------------------ // // Copyright (c) Microsoft Corporation. All rights reserved. // //------------------------------------------------------------------------------ /* */ namespace System.Diagnostics { using System; using System.Collections; using Microsoft.Win32; /// /// Provides a thread-safe list of . A thread-safe list is synchronized. /// public class TraceListenerCollection : IList { ArrayList list; internal TraceListenerCollection() { list = new ArrayList(1); } /// /// Gets or sets the at /// the specified index. /// public TraceListener this[int i] { get { return (TraceListener)list[i]; } set { InitializeListener(value); list[i] = value; } } /// /// Gets the first in the list with the specified name. /// public TraceListener this[string name] { get { foreach (TraceListener listener in this) { if (listener.Name == name) return listener; } return null; } } /// /// /// Gets the number of listeners in the list. /// /// public int Count { get { return list.Count; } } /// /// Adds a to the list. /// public int Add(TraceListener listener) { InitializeListener(listener); lock (TraceInternal.critSec) { return list.Add(listener); } } /// /// [To be supplied.] /// public void AddRange(TraceListener[] value) { if (value == null) { throw new ArgumentNullException("value"); } for (int i = 0; ((i) < (value.Length)); i = ((i) + (1))) { this.Add(value[i]); } } /// /// [To be supplied.] /// public void AddRange(TraceListenerCollection value) { if (value == null) { throw new ArgumentNullException("value"); } int currentCount = value.Count; for (int i = 0; i < currentCount; i = ((i) + (1))) { this.Add(value[i]); } } /// /// /// Clears all the listeners from the /// list. /// /// public void Clear() { list = new ArrayList(); } /// /// Checks whether the list contains the specified /// listener. /// public bool Contains(TraceListener listener) { return ((IList)this).Contains(listener); } /// /// Copies a section of the current list to the specified array at the specified /// index. /// public void CopyTo(TraceListener[] listeners, int index) { ((ICollection)this).CopyTo((Array) listeners, index); } /// /// /// Gets an enumerator for this list. /// /// public IEnumerator GetEnumerator() { return list.GetEnumerator(); } internal void InitializeListener(TraceListener listener) { if (listener == null) throw new ArgumentNullException("listener"); listener.IndentSize = TraceInternal.IndentSize; listener.IndentLevel = TraceInternal.IndentLevel; } /// /// Gets the index of the specified listener. /// public int IndexOf(TraceListener listener) { return ((IList)this).IndexOf(listener); } /// /// Inserts the listener at the specified index. /// public void Insert(int index, TraceListener listener) { InitializeListener(listener); lock (TraceInternal.critSec) { list.Insert(index, listener); } } /// /// /// Removes the specified instance of the class from the list. /// /// public void Remove(TraceListener listener) { ((IList)this).Remove(listener); } /// /// Removes the first listener in the list that has the /// specified name. /// public void Remove(string name) { TraceListener listener = this[name]; if (listener != null) ((IList)this).Remove(listener); } /// /// Removes the at the specified index. /// public void RemoveAt(int index) { lock (TraceInternal.critSec) { list.RemoveAt(index); } } /// object IList.this[int index] { get { return list[index]; } set { TraceListener listener = value as TraceListener; if (listener == null) throw new ArgumentException(/*SR.GetString(SR.MustAddListener),"value"*/); InitializeListener(listener); list[index] = listener; } } /// bool IList.IsReadOnly { get { return false; } } /// bool IList.IsFixedSize { get { return false; } } /// int IList.Add(object value) { TraceListener listener = value as TraceListener; if (listener == null) throw new ArgumentException(/*SR.GetString(SR.MustAddListener),"value"*/); InitializeListener(listener); lock (TraceInternal.critSec) { return list.Add(value); } } /// bool IList.Contains(object value) { return list.Contains(value); } /// int IList.IndexOf(object value) { return list.IndexOf(value); } /// void IList.Insert(int index, object value) { TraceListener listener = value as TraceListener; if (listener == null) throw new ArgumentException(/*SR.GetString(SR.MustAddListener),"value"*/); InitializeListener(listener); lock (TraceInternal.critSec) { list.Insert(index, value); } } /// void IList.Remove(object value) { lock (TraceInternal.critSec) { list.Remove(value); } } /// object ICollection.SyncRoot { get { return this; } } /// bool ICollection.IsSynchronized { get { return true; } } /// void ICollection.CopyTo(Array array, int index) { lock (TraceInternal.critSec) { list.CopyTo(array, index); } } } } ================================================ FILE: Zelig/Zelig/RunTime/Framework/system/System/Diagnostics/TraceOption.cs ================================================ //------------------------------------------------------------------------------ // // Copyright (c) Microsoft Corporation. All rights reserved. // //------------------------------------------------------------------------------ namespace System.Diagnostics { [Flags] public enum TraceOptions { None = 0, LogicalOperationStack = 0x01, DateTime= 0x02, Timestamp= 0x04, ProcessId= 0x08, ThreadId= 0x10, Callstack= 0x20, } } ================================================ FILE: Zelig/Zelig/RunTime/Framework/system/System/HTTP/System.Net.AuthenticationType.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // namespace System.Net { /// /// Network authentication type. /// Currently supports: /// Basic Authentication /// Microsoft Live Id Delegate Authentication /// public enum AuthenticationType { /// /// /// Basic, /// /// /// WindowsLive }; } ================================================ FILE: Zelig/Zelig/RunTime/Framework/system/System/HTTP/System.Net.HttpListener.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // namespace System.Net { using System.Net.Sockets; using System.Collections; using System.Threading; ////using Microsoft.SPOT.Net.Security; /// /// Provides a simple, programmatically controlled HTTP protocol listener. /// This class cannot be inherited. /// /// /// This class enables using a socket to receive data that uses the HTTP /// protocol. /// public class HttpListener { /// /// Indicates whether the listener is waiting on an http or https /// connection. /// bool m_isHttpsConnection; /// /// The certificate to send during https authentication. /// //////X509Certificate m_httpsCert; /// /// This value is the number of connections that can be ready but are /// not retrieved through the Accept call. /// /// /// This value is passed to the Listen method of the socket. /// private const int MaxCountOfPendingConnections = 10; /// /// The time we keep connection idle with HTTP 1.1 /// This is one minute. /// internal const int DefaultKeepAliveMilliseconds = 60000; /// /// Server socket for incoming connections. /// private Socket m_listener; /// /// The MAXIMUM length, in kilobytes (1024 bytes), of the request /// headers. /// internal int m_maxResponseHeadersLen; /// /// Event that indicates arrival of new event from client. /// private AutoResetEvent m_requestArrived; /// /// The queue of connected networks streams with pending client data. /// Queue m_inputStreamsQueue; /// /// Port number for the server socket. /// private int m_port; /// /// Indicates whether the listener is started and is currently accepting /// connections. /// private bool m_serviceRunning; /// /// Indicates whether the listener has been closed /// private bool m_closed; /// /// Array of connected client sockets. /// private ArrayList m_clientStreams; /// /// Http Thread for accepting new connections. /// private Thread m_thAccept; /// /// Creates an HTTP or HTTPS listener on the standard ports. /// /// Prefix ( http or https ) to start listen /// In the desktop version of .NET, the constructor for this /// class has no arguments. public HttpListener(string prefix) { InitListener(prefix, -1); } /// /// Creates an HTTP or HTTPS listener on the specified port. /// /// The prefix for the service, either "http" or /// "https". /// The port to start listening on. If -1, the /// default port is used (port 80 for http, or port 443 for https). /// /// In the desktop version of .NET, the constructor for this /// class has no arguments. public HttpListener(string prefix, int port) { InitListener(prefix, port); } /// /// Initializes the listener. /// /// The prefix for the service, either "http" or /// "https". /// The port to start listening on. If -1, the /// default port is used (port 80 for http, or port 443 for https). /// private void InitListener(string prefix, int port) { switch (prefix.ToLower()) { case "http": { m_isHttpsConnection = false; m_port = Uri.HttpDefaultPort; break; } case "https": { m_isHttpsConnection = true; m_port = Uri.HttpsDefaultPort; break; } default: throw new ArgumentException("Prefix should be http or https"); } if (port != -1) { m_port = port; } // Default members initialization m_maxResponseHeadersLen = 4; m_requestArrived = new AutoResetEvent(false); m_inputStreamsQueue = new Queue(); m_clientStreams = new ArrayList(); } /// /// Adds a new output stream to the list of connected streams. /// /// This is an internal function, not visible to the user. /// /// The stream to add. internal void AddClientStream(OutputNetworkStreamWrapper clientStream) { lock(m_clientStreams) { m_clientStreams.Add(clientStream); } } /// /// Removes the specified output stream from the list of connected /// streams. /// /// The stream to remove. internal void RemoveClientStream(OutputNetworkStreamWrapper clientStream) { lock(m_clientStreams) { for (int i = 0; i < m_clientStreams.Count; i++) { if (clientStream == m_clientStreams[i]) { m_clientStreams.RemoveAt(i); break; } } } } /// /// Packages together an HttpListener and a socket. /// /// This class is used to package together an HttpListener and a socket. /// We need to start new thread and pass 2 parameters - instance of listener and socket. /// For that purpose we create class that keeps references to both listerner and socket and /// start thread using member function of this class as delegate. /// Internal class not visible to user. private class HttpListernerAndStream { internal HttpListernerAndStream(HttpListener listener, OutputNetworkStreamWrapper outputStream) { m_listener = listener; m_outStream = outputStream; } internal HttpListener m_listener; internal OutputNetworkStreamWrapper m_outStream; // Forwards to waiting function of the listener. internal void AddToWaitingConnections() { m_listener.WaitingConnectionThreadFunc(m_outStream); } } internal void AddToWaitingConnections(OutputNetworkStreamWrapper outputStream) { // Create a thread that blocks onsocket.Poll - basically waits for new data from client. HttpListernerAndStream listAndSock = new HttpListernerAndStream(this, outputStream); // Creates new thread to wait on data Thread thWaitData = new Thread(listAndSock.AddToWaitingConnections); thWaitData.Start(); } /// /// Waits for new data from the client. /// private void WaitingConnectionThreadFunc(OutputNetworkStreamWrapper outputStream) { try { // This is a blocking call waiting for more data. outputStream.m_socket.Poll(DefaultKeepAliveMilliseconds * 1000, SelectMode.SelectRead); if (outputStream.m_socket.Available > 0) { // Add this connected stream to the list. lock (m_inputStreamsQueue) { m_inputStreamsQueue.Enqueue(outputStream); } // Set event that client stream or exception is added to the queue. m_requestArrived.Set(); } else // If no data available - means connection was close on other side or timed out. { outputStream.Dispose(); } } catch { } } /// /// Shuts down the HttpListener object immediately, /// discarding all currently queued requests. /// /// This method disposes of all resources held by this /// listener. Any pending requests are unable to complete. To shut /// down the HttpListener object after processing /// currently queued requests, use the /// method. /// /// After calling this method, you will receive an /// if you attempt to use this /// HttpListener. /// /// public void Abort() { lock (this) { // First we shut down the service. Close(); // Now we need to go through list of all client sockets and close all of them. // This will cause exceptions on read/write operations on these sockets. foreach (OutputNetworkStreamWrapper netStream in m_clientStreams) { netStream.Close(); } m_clientStreams.Clear(); } if (m_thAccept != null) { m_thAccept.Join(); } } /// /// Waits for new connections from the client. /// /// On new connections, this method enques the new input /// network stream and sets an event that a new connection is available. /// private void AcceptThreadFunc() { Thread.CurrentThread.Priority = ThreadPriority.AboveNormal; // If there was no exception up to this point, means we succeded to start listening. m_serviceRunning = true; int retry = 0; // The Start function is waiting on this event. We set it to indicate that // thread that waits for connections is already started. m_requestArrived.Set(); // The value of m_serviceStarted normally is changed from other thread by calling Stop. while (m_serviceRunning) { Socket clientSock; // Need to create NetworkStream or SSL stream depending on protocol used. NetworkStream netStream = null; try { // It is important that multithread access to m_listener.Accept(); is not locked. // If it was locked - then Close or Stop would be blocked potnetially for ever while waiting for connection. // This is a blocking call waiting for connection. clientSock = m_listener.Accept(); retry = 0; try { // set NoDelay to increase HTTP(s) response times clientSock.SetSocketOption(SocketOptionLevel.Tcp, SocketOptionName.NoDelay, true); } catch { } } catch (SocketException) { if (retry > 5) { // If request to stop listener flag is set or locking call is interupted return // On exception we stop the service and record the exception. if (m_serviceRunning && !m_closed) { Stop(); } // Set event to unblock thread waiting for accept. m_requestArrived.Set(); break; } retry++; continue; } catch { // If request to stop listener flag is set or locking call is interupted return // On exception we stop the service and record the exception. if (m_serviceRunning && !m_closed) { Stop(); } // Set event to unblock thread waiting for accept. m_requestArrived.Set(); break; } try { if (!m_isHttpsConnection) { // This is case of normal HTTP. Create network stream. netStream = new NetworkStream(clientSock, true); } else { throw new NotImplementedException( ); //////// This is the case of https. //////// Once connection estiblished need to create secure stream and authenticate server. //////netStream = new SslStream(clientSock); //////SslProtocols[] sslProtocols = new SslProtocols[] { SslProtocols.Default }; //////// Throws exception if fails. //////((SslStream)netStream).AuthenticateAsServer(m_httpsCert, SslVerification.NoVerification, sslProtocols); //////netStream.ReadTimeout = 10000; } } catch(SocketException) { if (netStream != null) { netStream.Dispose(); } else { clientSock.Close(); } m_requestArrived.Set(); // try again continue; } // Add this connected stream to the list. lock (m_inputStreamsQueue) { m_inputStreamsQueue.Enqueue(new OutputNetworkStreamWrapper(clientSock, netStream)); } // Set event that client stream or exception is added to the queue. m_requestArrived.Set(); } } /// /// Allows this instance to receive incoming requests. /// /// This method must be called before you call the /// method. If /// the service was already started, the call has no effect. After you /// have started an HttpListener object, you can use /// the method to stop it. /// public void Start() { lock (this) { if(m_closed) throw new ObjectDisposedException( "System.Net.HttpListener" ); // If service was already started, the call has no effect. if (m_serviceRunning) { return; } m_listener = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); try { // set NoDelay to increase HTTP(s) response times m_listener.SetSocketOption(SocketOptionLevel.Tcp, SocketOptionName.NoDelay, true); } catch {} try { // Start server socket to accept incoming connections. m_listener.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReuseAddress, true); } catch {} IPEndPoint endPoint = new IPEndPoint(IPAddress.GetDefaultLocalAddress(), m_port); m_listener.Bind(endPoint); // Starts to listen to maximum of 10 connections. m_listener.Listen(MaxCountOfPendingConnections); // Create a thread that blocks on m_listener.Accept() - basically waits for connection from client. m_thAccept = new Thread(AcceptThreadFunc); m_thAccept.Start(); // Waits for thread that calls Accept to start. m_requestArrived.WaitOne(); } } /// /// Shuts down the HttpListener after processing all /// currently queued requests. /// /// After calling this method, you can no longer use the /// HttpListener object. To temporarily pause an /// HttpListener object, use the /// method. public void Close() { lock(this) { // close does not throw try { Stop(); } catch { } m_closed = true; } } /// /// Causes this instance to stop receiving incoming requests. /// /// If this instance is already stopped, calling this method /// has no effect. /// /// After you have stopped an HttpListener object, /// you can use the method /// to restart it. /// /// public void Stop() { // Need to lock access to object, because Stop can be called from a // different thread. lock (this) { if (m_closed) throw new ObjectDisposedException( "System.Net.HttpListener" ); m_serviceRunning = false; // We close the server socket that listen for incoming connection. // Connections that already accepted are processed. // Connections that has been in queue for server socket, but not accepted, are lost. if(m_listener != null) { m_listener.Close(); m_listener = null; m_requestArrived.Set(); } } } /// /// Waits for an incoming request and returns when one is received. /// /// /// An object that /// represents a client request. /// /// A socket call failed. Check the /// exception's ErrorCode property to determine the cause of the exception. /// This object has not been started or is /// currently stopped or The HttpListener does not have any Uniform Resource Identifier /// (URI) prefixes to respond to. /// This object is closed. /// This example shows how to call the /// GetContext method. /// /// HttpListener myListener = new HttpListener("http", -1); /// myListener.Start(); /// while (true) /// { /// HttpListenerResponse response = null; /// try /// { /// Debug.Print("Waiting for requests"); /// HttpListenerContext context = myListener.GetContext(); /// /// public HttpListenerContext GetContext() { // Protects access for simulteneous call for GetContext and Close or Stop. lock (this) { if (m_closed) throw new ObjectDisposedException( "System.Net.HttpListener" ); if (!m_serviceRunning) throw new InvalidOperationException(); } // Try to get context until service is running. while (m_serviceRunning) { // Before waiting for event we need to look for pending connections. lock (m_inputStreamsQueue) { if (m_inputStreamsQueue.Count > 0) { OutputNetworkStreamWrapper outputStreamWrap = m_inputStreamsQueue.Dequeue() as OutputNetworkStreamWrapper; if (outputStreamWrap != null) { return new HttpListenerContext(outputStreamWrap, this); } } } // Waits for new connection to arrive on new or existing socket. m_requestArrived.WaitOne(); } return null; } /// /// Gets whether the HttpListener service was started /// and is waiting for client connections. /// /// true if the /// HttpListener was started; otherwise, /// false. public bool IsListening { get { return m_serviceRunning; } } /// /// Gets or sets the maximum allowed length of the response headers, in /// KB. /// /// The length, in kilobytes (1024 bytes), of the response /// headers. /// /// The length of the response header includes the response status line /// and any extra control characters that are received as part of the /// HTTP protocol. A value of -1 means no limit is imposed on the /// response headers; a value of 0 means that all requests fail. If /// this property is not explicitly set, it defaults to 4 (KB). /// public int MaximumResponseHeadersLength { get { return m_maxResponseHeadersLen; } set { if (value <= 0 && value != -1) { throw new ArgumentOutOfRangeException(); } m_maxResponseHeadersLen = value; } } ///////// ///////// The certificate used if HttpListener implements an https ///////// server. ///////// //////public X509Certificate HttpsCert //////{ ////// get { return m_httpsCert; } ////// set { m_httpsCert = value; } //////} } } ================================================ FILE: Zelig/Zelig/RunTime/Framework/system/System/HTTP/System.Net.HttpListenerContext.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // namespace System.Net { using System.Net.Sockets; /// /// Provides access to the request and response objects used by the /// HttpListener class. This class cannot be inherited. /// public class HttpListenerContext { /// /// A flag that indicates whether an HTTP request was parsed. /// /// /// The HTTP request is parsed upon the first access to the Request to /// Response property. Access to that property might be done from a /// different thread than the thread that is used for construction of /// the HttpListenerContext. /// bool m_isHTTPRequestParsed; /// /// Member with network stream connected to client. /// This stream is used for writing data. /// This stream owns the socket. /// private OutputNetworkStreamWrapper m_clientOutputStream; /// /// Member with network stream connected to client. /// This stream is used for Reading data. /// This stream does not own the socket. /// private InputNetworkStreamWrapper m_clientInputStream; /// /// Instance of the request from client. /// it is a server side representation of HttpWebRequest. /// It is the same data, but instead of composing request we parse it. /// private HttpListenerRequest m_clientRequest; /// /// Instance of the response to client. /// /// private HttpListenerResponse m_responseToClient; /// /// Internal constructor, used each time client connects. /// /// The stream that is connected to the client. A stream is needed, to /// provide information about the connected client. /// See also the class. /// /// TBD internal HttpListenerContext(OutputNetworkStreamWrapper clientStream, HttpListener httpListener) { // Saves the stream. m_clientOutputStream = clientStream; // Input stream does not own socket. m_clientInputStream = new InputNetworkStreamWrapper(clientStream.m_stream, clientStream.m_socket, false, null); // Constructs request and response classes. m_clientRequest = new HttpListenerRequest(m_clientInputStream, httpListener.m_maxResponseHeadersLen); // Closing reponse to client causes removal from clientSocketsList. // Thus we need to pass clientSocketsList to client response. m_responseToClient = new HttpListenerResponse(m_clientOutputStream, httpListener); // There is incoming connection HTTP connection. Add new Socket to the list of connected sockets // The socket is removed from this array after correponding HttpListenerResponse is closed. httpListener.AddClientStream(m_clientOutputStream); // Set flag that HTTP request was not parsed yet. // It will be parsed on first access to m_ClientRequest or m_ResponseToClient m_isHTTPRequestParsed = false; } public void Reset() { m_isHTTPRequestParsed = false; m_clientRequest.Reset(); } /// /// Gets the HttpListenerRequest that represents a /// client's request for a resource. /// /// An HttpListenerRequest object that /// represents the client request. public HttpListenerRequest Request { get { if (!m_isHTTPRequestParsed) { m_clientRequest.ParseHTTPRequest(); // After request parsed check for "transfer-ecoding" header. If it is chunked, change stream property. // If m_EnableChunkedDecoding is set to true, then readig from stream automatically processing chunks. string chunkedVal = m_clientRequest.Headers[HttpKnownHeaderNames.TransferEncoding]; if (chunkedVal != null && chunkedVal.ToLower() == "chunked") { m_clientInputStream.m_enableChunkedDecoding = true; } m_isHTTPRequestParsed = true; } return m_clientRequest; } } /// /// Gets the HttpListenerResponse object that will be /// sent to the client in response to the client's request. /// /// An HttpListenerResponse object used to /// send a response back to the client. public HttpListenerResponse Response { get { if (!m_isHTTPRequestParsed) { m_clientRequest.ParseHTTPRequest(); m_isHTTPRequestParsed = true; } return m_responseToClient; } } public void Close() { Close(-2); } /// /// Closes the stream attached to this listener context. /// public void Close(int lingerValue) { try { if (m_clientOutputStream != null) { try { if(m_clientOutputStream.m_socket != null) { m_clientOutputStream.m_socket.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.Linger, lingerValue); } } catch{} } if (m_responseToClient != null) { m_responseToClient.Close(); m_responseToClient = null; } // Close the underlying stream if (m_clientOutputStream != null) { m_clientOutputStream.Dispose(); m_clientOutputStream = null; } if (m_clientInputStream != null) { m_clientInputStream.Dispose(); m_clientInputStream = null; } } catch { } } } } ================================================ FILE: Zelig/Zelig/RunTime/Framework/system/System/HTTP/System.Net.HttpListenerRequest.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // namespace System.Net { using System; using System.IO; /// /// Describes an incoming HTTP request to an /// object. /// /// /// When a client makes a request to a Uniform Resource Identifier (URI) /// handled by an HttpListener object, the /// HttpListener provides an /// object that contains /// information about the sender, the request, and the response that is sent /// to the client. The /// property returns the HttpListenerRequest object that /// describes the request. /// /// The HttpListenerRequest object contains information /// about the request, such as the request /// string, /// string, and /// request body data (see the /// /// property). /// /// To reply to the request, you must get the associated response using the /// property. /// public class HttpListenerRequest { /// /// The original string with the request. For example, /// "GET /Index.htm HTTP/1.1". /// private string m_requestString; /// /// The maximum length of the request headers, in KB (1024 bytes). /// private int m_maxResponseHeadersLen; /// /// The verb of the request parsed from m_RequestString. /// private string m_requestVerb; /// /// URL of request parsed from m_RequestString. /// private string m_rawURL; /// /// HTTP version from m_RequestString. /// private Version m_requestHttpVer; /// /// Indicates whether the client requests a persistent connection. /// If client did not specify "Connection" header - default is false. /// private bool m_keepAlive = false; /// /// The request Headers From HTTP client. /// private WebHeaderCollection m_httpRequestHeaders = new WebHeaderCollection(true); /// /// Member with network stream connected to client. /// /// private InputNetworkStreamWrapper m_clientStream; /// /// The length of the content in the body of the request, if a body is /// present. /// long m_contentLength; /// /// Keep NetworkCredential if user have send user name and password. /// private NetworkCredential m_networkCredentials; /// /// Constructs a HttpListenerRequest is created by HttpListenerContext. /// /// Network stream to the client. /// TBD internal HttpListenerRequest(InputNetworkStreamWrapper clientStream, int maxHeaderLen) { m_clientStream = clientStream; // maxHeaderLen is in kilobytes (Desktop designer decided so). If -1 just maximum integer value m_maxResponseHeadersLen = maxHeaderLen == -1 ? 0x7FFFFFFF : maxHeaderLen * 1024; // If not set, default for content length is -1 m_contentLength = -1; } public void Reset() { m_httpRequestHeaders = new WebHeaderCollection(true); m_contentLength = -1; } /// /// Parses request from client. /// Fills /// - HTTP Verb. /// - HTTP version. /// - Content Length. /// - Fills generic value name pair in WEB header collection. /// internal void ParseHTTPRequest() { // This is the request line. m_requestString = m_clientStream.Read_HTTP_Line(HttpWebRequest.maxHTTPLineLength).Trim(); // Split request line into 3 strings - VERB, URL and HTTP version. char[] delimiter = { ' ' }; string[] requestStr = m_requestString.Split(delimiter); // requestStr should consist of 3 parts. if (requestStr.Length < 3) { throw new ProtocolViolationException("Invalid HTTP request String: " + m_requestString); } // We have at least 3 strings. Fills the proper fields m_requestVerb = requestStr[0]; m_rawURL = requestStr[1]; // Process third string. It should be either http/1.1 or http/1.0 string httpVerLowerCase = requestStr[2].ToLower(); if (httpVerLowerCase.Equals("http/1.1")) { m_requestHttpVer = HttpVersion.Version11; } else if (httpVerLowerCase.Equals("http/1.0")) { m_requestHttpVer = HttpVersion.Version10; } else { throw new ProtocolViolationException("Unsupported HTTP version: " + requestStr[2]); } // Now it is list of HTTP headers: string line; int headersLen = m_maxResponseHeadersLen; while ((line = m_clientStream.Read_HTTP_Header(HttpWebRequest.maxHTTPLineLength)).Length > 0) { // line.Length is used for the header. Substruct it. headersLen -= line.Length; // If total length used for header is exceeded, we break if (headersLen < 0) { throw new ProtocolViolationException("Http Headers exceeding: " + m_maxResponseHeadersLen); } int sepIdx = line.IndexOf(':'); if (sepIdx == -1) { throw new ProtocolViolationException("Invalid HTTP Header: " + line); } string headerName = line.Substring(0, sepIdx).Trim(); string headerValue = line.Substring(sepIdx + 1).Trim(); string matchableHeaderName = headerName.ToLower(); // Adds new header to collection. m_httpRequestHeaders.AddInternal(headerName, headerValue); // Now we check the value - name pair. For some of them we need to initilize member variables. headerName = headerName.ToLower(); // If it is connection header if (headerName == "connection") { // If value is "Keep-Alive" ( lower case now ), set m_KeepAlive to true; headerValue = headerValue.ToLower(); m_keepAlive = headerValue == "keep-alive"; } // If user supplied user name and password - parse it and store in m_NetworkCredentials if (headerName == "authorization") { int sepSpace = headerValue.IndexOf(' '); string authType = headerValue.Substring(0, sepSpace); if (authType.ToLower() == "basic") { string authInfo = headerValue.Substring(sepSpace + 1); // authInfo is base64 encoded username and password. byte[] authInfoDecoded = Convert.FromBase64String(authInfo); char[] authInfoDecChar = System.Text.Encoding.UTF8.GetChars(authInfoDecoded); string strAuthInfo = new string(authInfoDecChar); // The strAuthInfo comes in format username:password. Parse it. int sepColon = strAuthInfo.IndexOf(':'); if (sepColon != -1) { m_networkCredentials = new NetworkCredential(strAuthInfo.Substring(0, sepColon), strAuthInfo.Substring(sepColon + 1)); } } } } // Http headers were processed. Now we search for content length. string strContentLen = m_httpRequestHeaders[HttpKnownHeaderNames.ContentLength]; if (strContentLen != null) { try { m_contentLength = Convert.ToInt32(strContentLen); } catch (Exception) { throw new ProtocolViolationException("Invalid content length in request: " + strContentLen); } } } /// /// Gets the HTTP method specified by the client. /// /// A String that contains the method used in /// the request. public string HttpMethod { get { return m_requestVerb; } } /// /// Gets the URL information (without the host and port) requested by /// the client. /// /// A String that contains the raw URL for /// this request. /// /// This URL information is the URL requested in the first request line. /// public string RawUrl { get { return m_rawURL; } } /// /// Gets the MIME types accepted by the client. /// /// A String array that contains the type /// names specified in the request's Accept header, or a null reference /// if the client request did not include an Accept header. public string[] AcceptTypes { get { return m_httpRequestHeaders.GetValues(HttpKnownHeaderNames.Accept); } } /// /// Gets the length of the body data included in the request. /// /// /// The Content-Length header expresses the length, in bytes, of the /// body data that accompanies the request. /// enumeration. /// /// The value from the request's Content-Length header. This /// value is -1 if the content length is not known. public long ContentLength64 { get { return m_contentLength; } } /// /// Gets the MIME type of the body data included in the request. /// /// A String that contains the text of the /// request's Content-Type header. public string ContentType { get { return m_httpRequestHeaders[HttpKnownHeaderNames.ContentType]; } } /// /// Gets the collection of header name/value pairs sent in the request. /// /// A WebHeaderCollection that contains the /// HTTP headers included in the request. public WebHeaderCollection Headers { get { return m_httpRequestHeaders; } } /// /// Gets a stream that contains the body data sent by the client. /// /// A readable Stream object that contains the /// bytes sent by the client in the body of the request. This property /// returns Null if no data is sent with the request. /// public Stream InputStream { get { return m_clientStream; } } /// /// Gets a Boolean value that indicates whether the client sending this /// request is authenticated. /// /// /// Because authentication is not supported, returns /// false. /// /// Because authentication is not supported, returns /// false. public bool IsAuthenticated { get { return false; } } /// /// Gets a value that indicates whether the /// client requests a persistent connection. /// /// /// This property is set during parsing of HTTP header. /// /// true if the connection should be kept /// open; otherwise, false. public bool KeepAlive { get { return m_keepAlive; } } /// /// Gets the server IP address and port number to which the request is /// directed. Not currently supported. /// /// An IPEndPoint that represents the IP /// address that the request is sent to. /// public IPEndPoint LocalEndPoint { get { return (IPEndPoint)m_clientStream.m_socket.LocalEndPoint; } } /// /// Gets the HTTP version used by the requesting client. /// /// /// The capabilities of different HTTP versions are specified in the /// documents available at http://www.rfc-editor.org. /// /// A Version that identifies the client's /// version of HTTP. public Version ProtocolVersion { get { return m_requestHttpVer; } } /// /// Gets the client IP address and port number from which the request /// originated. /// /// An IPEndPoint that represents the IP /// address and port number from which the request originated. public IPEndPoint RemoteEndPoint { get { return (IPEndPoint)m_clientStream.m_socket.RemoteEndPoint; } } /// /// Gets the Uri object requested by the client. Not currently /// supported. /// public Uri Url { get { return new Uri(m_rawURL, UriKind.Relative); } } /// /// Gets the user agent presented by the client. /// /// A String object that contains the text of /// the request's User-Agent header. /// /// public string UserAgent { get { return m_httpRequestHeaders[HttpKnownHeaderNames.UserAgent]; } } /// /// Gets the server IP address and port number to which the request is /// directed. /// /// A String that contains the host address /// information. public string UserHostAddress { get { return ((IPEndPoint)m_clientStream.m_socket.LocalEndPoint).Address.ToString(); } } /// /// Gets the DNS name and, if provided, the port number specified by the /// client. /// /// A String value that contains the text of the request's Host header. public string UserHostName { get { return m_httpRequestHeaders[HttpKnownHeaderNames.UserAgent]; } } /// /// Return NetworkCredential if user have send user name and password. /// public NetworkCredential Credentials { get { return m_networkCredentials; } } /// /// Gets the natural languages that are preferred for the response. /// /// A String array that contains the languages /// specified in the request's AcceptLanguage header, /// or null if the client request did not include an /// AcceptLanguage header. public string[] UserLanguages { get { return m_httpRequestHeaders.GetValues(HttpKnownHeaderNames.AcceptLanguage); } } } } ================================================ FILE: Zelig/Zelig/RunTime/Framework/system/System/HTTP/System.Net.HttpListenerResponse.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // namespace System.Net { using System; using System.IO; using System.Text; /// /// Represents a response to a request being handled by an /// object. /// public sealed class HttpListenerResponse : IDisposable { /// /// A flag that indicates whether the response was already sent. /// private bool m_wasResponseSent = false; /// /// A flag that indicates that the response was closed. /// Writing to client is not allowed after response is closed. /// private bool m_isResponseClosed = false; /// /// The length of the content of the response. /// long m_contentLength = -1; /// /// The response headers from the HTTP client. /// private WebHeaderCollection m_httpResponseHeaders = new WebHeaderCollection(true); /// /// The HTTP version for the response. /// private Version m_version = new Version(1, 1); /// /// Indicates whether the server requests a persistent connection. /// Persistent connection is used if KeepAlive is true /// in both the request and the response. /// private bool m_keepAlive = false; /// /// Encoding for this response's OutputStream. /// private Encoding m_encoding = Encoding.UTF8; /// /// Keeps content type for the response, set by user application. /// private string m_contentType; /// /// Response status code. /// private int m_responseStatusCode = (int)HttpStatusCode.OK; /// /// Array of connected client streams /// private HttpListener m_listener; /// /// Member with network stream connected to client. /// After call to Close() the stream is closed, no further writing allowed. /// private OutputNetworkStreamWrapper m_clientStream; /// /// The value of the HTTP Location header in this response. /// private string m_redirectLocation; /// /// Response uses chunked transfer encoding. /// private bool m_sendChunked = false; /// /// text description of the HTTP status code returned to the client. /// private string m_statusDescription; /// /// Throws InvalidOperationException is HTTP response was sent. /// Called before setting of properties. /// private void ThrowIfResponseSent( ) { if(m_wasResponseSent) { throw new InvalidOperationException( ); } } /// /// HttpListenerResponse is created by HttpListenerContext /// /// Network stream to the client /// TBD internal HttpListenerResponse( OutputNetworkStreamWrapper clientStream, HttpListener httpListener ) { // Sets the delegate, so SendHeaders will be called on first write. clientStream.HeadersDelegate = new OutputNetworkStreamWrapper.SendHeadersDelegate( SendHeaders ); // Saves network stream as member. m_clientStream = clientStream; // Saves list of client streams. m_clientStream is removed from clientStreamsList during Close(). m_listener = httpListener; } /// /// Updates the HTTP WEB header collection to prepare it for request. /// For each property set it adds member to m_httpResponseHeaders. /// m_httpResponseHeaders is serializes to string and sent to client. /// private void PrepareHeaders( ) { // Adds content length if it was present. if(m_contentLength != -1) { m_httpResponseHeaders.ChangeInternal( HttpKnownHeaderNames.ContentLength, m_contentLength.ToString( ) ); } // Since we do not support persistent connection, send close always. string connection = m_keepAlive ? "Keep-Alive" : "Close"; m_httpResponseHeaders.ChangeInternal( HttpKnownHeaderNames.Connection, connection ); // Adds content type if user set it: if(m_contentType != null) { m_httpResponseHeaders.AddWithoutValidate( HttpKnownHeaderNames.ContentType, m_contentType ); } if(m_redirectLocation != null) { m_httpResponseHeaders.AddWithoutValidate( HttpKnownHeaderNames.Location, m_redirectLocation ); m_responseStatusCode = (int)HttpStatusCode.Redirect; } } /// /// Composes HTTP response line based on /// /// private string ComposeHTTPResponse( ) { // Starts with HTTP string resp = "HTTP/"; // Adds version of HTTP resp += m_version.ToString( ); // Add status code. resp += " " + m_responseStatusCode; // Adds description if(m_statusDescription == null) { resp += " " + GetStatusDescription( m_responseStatusCode ); } else // User provided description is present. { resp += " " + m_statusDescription; } // Add line termindation. resp += "\r\n"; return resp; } /// /// Sends HTTP status and headers to client. /// private void SendHeaders( ) { // As first step we disable the callback to SendHeaders, so m_clientStream.Write would not call // SendHeaders() again. m_clientStream.HeadersDelegate = null; // Creates encoder, generates headers and sends the data. Encoding encoder = Encoding.UTF8; byte[] statusLine = encoder.GetBytes(ComposeHTTPResponse()); m_clientStream.Write( statusLine, 0, statusLine.Length ); // Prepares/Updates WEB header collection. PrepareHeaders( ); // Serialise WEB header collection to byte array. byte[] pHeaders = m_httpResponseHeaders.ToByteArray(); // Sends the headers m_clientStream.Write( pHeaders, 0, pHeaders.Length ); m_wasResponseSent = true; } /// /// Gets or sets the HTTP status code to be returned to the client. /// /// An Int32 value that specifies the /// for the requested resource. /// The default is OK, indicating that the server /// successfully processed the client's request and included the /// requested resource in the response body. public int StatusCode { get { return m_responseStatusCode; } set { ThrowIfResponseSent( ); m_responseStatusCode = value; } } /// /// Gets or sets the number of bytes in the body data included in the /// response. /// /// The value of the response's Content-Length /// header. public long ContentLength64 { get { return m_contentLength; } set { ThrowIfResponseSent( ); m_contentLength = value; } } /// /// Gets or sets the collection of header name/value pairs that is /// returned by the server. /// /// A WebHeaderCollection instance that /// contains all the explicitly set HTTP headers to be included in the /// response. public WebHeaderCollection Headers { get { return m_httpResponseHeaders; } set { ThrowIfResponseSent( ); m_httpResponseHeaders = value; } } /// /// Gets or sets whether the server requests a persistent connection. /// /// true if the server requests a persistent /// connection; otherwise, false. The default is /// true. public bool KeepAlive { get { return m_keepAlive; } set { m_keepAlive = value; } } /// /// Gets a Stream object to which a response can be /// written. /// /// A Stream object to which a response can be /// written. /// /// The first write to the output stream sends a response to the client. /// public Stream OutputStream { get { if(m_isResponseClosed) { throw new ObjectDisposedException( "Response has been sent" ); } return m_clientStream; } } /// /// Gets or sets the HTTP version that is used for the response. /// /// A Version object indicating the version of /// HTTP used when responding to the client. This property is obsolete. /// public Version ProtocolVersion { get { return m_version; } set { ThrowIfResponseSent( ); m_version = value; } } /// /// Gets or sets the value of the HTTP Location /// header in this response. /// /// A String that contains the absolute URL to /// be sent to the client in the Location header. /// public string RedirectLocation { get { return m_redirectLocation; } set { ThrowIfResponseSent( ); m_redirectLocation = value; } } /// /// Gets or sets whether the response uses chunked transfer encoding. /// /// true if the response is set to use chunked /// transfer encoding; otherwise, false. The default /// is false. public bool SendChunked { get { return m_sendChunked; } set { ThrowIfResponseSent( ); m_sendChunked = value; } } /// /// Gets or sets the encoding for this response's /// OutputStream. /// /// An Encoding object suitable for use with /// the data in the /// property, /// or null reference if no encoding is specified. /// /// /// Only UTF8 encoding is supported. /// public Encoding ContentEncoding { get { return m_encoding; } set { ThrowIfResponseSent( ); m_encoding = value; } } /// /// Gets or sets the MIME type of the returned content. /// /// A String instance that contains the text /// of the response's Content-Type header. public string ContentType { get { return m_contentType; } set { ThrowIfResponseSent( ); m_contentType = value; } } /// /// Gets or sets a text description of the HTTP status code that is /// returned to the client. /// /// The text description of the HTTP status code returned to the /// client. public string StatusDescription { get { return m_statusDescription; } set { ThrowIfResponseSent( ); m_statusDescription = value; } } public void Detach( ) { if(!m_isResponseClosed) { if(!m_wasResponseSent) { SendHeaders( ); } m_isResponseClosed = true; } } /// /// Sends the response to the client and releases the resources held by /// this HttpListenerResponse instance. /// /// /// This method flushes data to the client and closes the network /// connection. /// public void Close( ) { if(!m_isResponseClosed) { try { if(!m_wasResponseSent) { SendHeaders( ); } } finally { // Removes from the list of streams and closes the socket. ( (IDisposable)this ).Dispose( ); } } } /// /// Closes the socket and sends the response if it was not done earlier /// and the socket is present. /// void IDisposable.Dispose( ) { if(!m_isResponseClosed) { try { // Iterates over list of client connections and remove its stream from it. m_listener.RemoveClientStream( m_clientStream ); m_clientStream.Flush( ); // If KeepAlive is true, if(m_keepAlive) { // Then socket is tramsferred to the list of waiting for new data. m_listener.AddToWaitingConnections( m_clientStream ); } else // If not KeepAlive then close { m_clientStream.Dispose( ); } } catch { } m_isResponseClosed = true; } GC.SuppressFinalize( this ); } /// /// Called to close the socket if necessary. /// ~HttpListenerResponse( ) { ( (IDisposable)this ).Dispose( ); } /// /// Return default Description based in response status code. /// /// HTTP status code /// /// Default string with description. /// internal static string GetStatusDescription( int code ) { switch(code) { case 100: return "Continue"; case 101: return "Switching Protocols"; case 102: return "Processing"; case 200: return "OK"; case 201: return "Created"; case 202: return "Accepted"; case 203: return "Non-Authoritative Information"; case 204: return "No Content"; case 205: return "Reset Content"; case 206: return "Partial Content"; case 207: return "Multi-Status"; case 300: return "Multiple Choices"; case 301: return "Moved Permanently"; case 302: return "Found"; case 303: return "See Other"; case 304: return "Not Modified"; case 305: return "Use Proxy"; case 307: return "Temporary Redirect"; case 400: return "Bad Request"; case 401: return "Unauthorized"; case 402: return "Payment Required"; case 403: return "Forbidden"; case 404: return "Not Found"; case 405: return "Method Not Allowed"; case 406: return "Not Acceptable"; case 407: return "Proxy Authentication Required"; case 408: return "Request Timeout"; case 409: return "Conflict"; case 410: return "Gone"; case 411: return "Length Required"; case 412: return "Precondition Failed"; case 413: return "Request Entity Too Large"; case 414: return "Request-Uri Too Long"; case 415: return "Unsupported Media Type"; case 416: return "Requested Range Not Satisfiable"; case 417: return "Expectation Failed"; case 422: return "Unprocessable Entity"; case 423: return "Locked"; case 424: return "Failed Dependency"; case 500: return "Internal Server Error"; case 501: return "Not Implemented"; case 502: return "Bad Gateway"; case 503: return "Service Unavailable"; case 504: return "Gateway Timeout"; case 505: return "Http Version Not Supported"; case 507: return "Insufficient Storage"; } return ""; } } } ================================================ FILE: Zelig/Zelig/RunTime/Framework/system/System/HTTP/System.Net.HttpStatusCode.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // namespace System.Net { // Any int can be cast to a HttpStatusCode to allow checking for non http1.1 // codes. /// /// Contains the values of status codes defined for HTTP. /// /// ///

Status codes indicate categories, as follows:

///

1xx -- Informational.

///

2xx -- Successful.

///

3xx -- Redirection.

///

4xx -- Client Error.

///

5xx -- Server Error.

///
public enum HttpStatusCode { /// Informational -- 1xx. /// Equivalent to HTTP status 100. Indicates that the client can continue with its /// request. Continue = 100, /// Equivalent to HTTP status 101. Indicates that the protocol version or protocol /// is being changed. SwitchingProtocols = 101, /// Successful -- 2xx. /// Equivalent to HTTP status 200. Indicates that the request succeeded and that /// the requested information is in the response. This is the most common status code to /// receive. OK = 200, /// Equivalent to HTTP status 201. Indicates that the request resulted in a new /// resource created before the response was sent. Created = 201, /// Equivalent to HTTP status 202. Indicates that the request has been accepted for /// further processing. Accepted = 202, /// Equivalent to HTTP status 203. Indicates that the returned metainformation is /// from a cached copy instead of the origin server and therefore may be incorrect. NonAuthoritativeInformation = 203, /// Equivalent to HTTP status 204. Indicates that the request has been successfully /// processed and that the response is intentionally blank. NoContent = 204, /// Equivalent to HTTP status 205. Indicates that the client should reset (not /// reload) the current resource. ResetContent = 205, /// Equivalent to HTTP status 206. Indicates that the response is a /// partial response as requested by a GET request that includes a byte range. PartialContent = 206, /// Redirection -- 3xx. /// Equivalent to HTTP status 300. Indicates that the requested information has /// multiple representations. The default action is to treat this status as a redirect and /// follow the contents of the Location header associated with this response. /// If the property is /// false, MultipleChoices will cause an exception to /// be thrown. /// MultipleChoices is a synonym for Ambiguous. MultipleChoices = 300, /// Equivalent to HTTP status 300. Indicates that the requested /// information has multiple representations. The default action is to treat this status as /// a redirect and follow the contents of the Location header associated with this response. /// If the property is /// false, Ambiguous will cause an exception to be /// thrown. /// Ambiguous is a synonym for MultipleChoices. Ambiguous = 300, /// Equivalent to HTTP status 301. Indicates that the requested information has /// been moved to the URI specified in the Location header. The default action when this /// status is received is to follow the Location header associated with the response. /// MovedPermanently is a synonym for Moved. MovedPermanently = 301, /// Equivalent to HTTP status 301. Indicates that the requested information /// has been moved to the URI specified in the Location header. The default action when this /// status is received is to follow the Location header associated with the response. When /// the original request method was POST, the redirected request will use the GET method. /// Moved is a synonym for MovedPermanently. Moved = 301, /// Equivalent to HTTP status 302. Indicates that the requested information is /// located at the URI specified in the Location header. The default action when this status /// is received is to follow the Location header associated with the response. When the /// original request method was POST, the redirected request will use the GET method. /// If the property is /// false, Found will cause an exception to be thrown. /// Found is a synonym for Redirect. Found = 302, /// Equivalent to HTTP status 302. Indicates that the requested information is /// located at the URI specified in the Location header. The default action when this status /// is received is to follow the Location header associated with the response. When the /// original request method was POST, the redirected request will use the GET method. /// If the property is /// false, Redirect will cause an exception to be /// thrown. /// Redirect is a synonym for Found. Redirect = 302, /// Equivalent to HTTP status 303. Automatically redirects the client to /// the URI specified in the Location header as the result of a POST. The request to the /// resource specified by the Location header will be made with a GET. /// If the property is /// false, SeeOther will cause an exception to be /// thrown. /// SeeOther is a synonym for RedirectMethod. SeeOther = 303, /// Equivalent to HTTP status 303. Automatically redirects the /// client to the URI specified in the Location header as the result of a POST. The request /// to the resource specified by the Location header will be made with a GET. /// If the property is /// false, RedirectMethod will cause an exception to /// be thrown. /// RedirectMethod is a synonym for SeeOther. RedirectMethod = 303, /// Equivalent to HTTP status 304. Indicates that the client's cached copy is /// up-to-date. The contents of the resource are not transferred. NotModified = 304, /// Equivalent to HTTP status 305. Indicates that the request should use the proxy /// server at the URI specified in the Location header. UseProxy = 305, /// Equivalent to HTTP status 306. This value is a proposed extension to the HTTP/1.1 /// specification that is not fully specified. Unused = 306, /// Equivalent to HTTP status 307. Indicates that the request information is /// located at the URI specified in the Location header. The default action when this status /// is received is to follow the Location header associated with the response. When the /// original request method was POST, the redirected request will also use the POST method. /// If the property is /// false, TemporaryRedirect will cause an exception /// to be thrown. /// TemporaryRedirect is a synonym for RedirectKeepVerb. TemporaryRedirect = 307, /// Equivalent to HTTP status 307. Indicates that the request /// information is located at the URI specified in the Location header. The default action /// when this status is received is to follow the Location header associated with the /// response. When the original request method was POST, the redirected request will also /// use the POST method. /// If the property is /// false, RedirectKeepVerb will cause an exception to /// be thrown. /// RedirectKeepVerb is a synonym for TemporaryRedirect. RedirectKeepVerb = 307, /// Client Error -- 4xx. /// Equivalent to HTTP status 400. Indicates that the request could not be /// understood by the server. BadRequest is sent when no other error is /// applicable, or if the exact error is unknown or does not have its own error code. BadRequest = 400, /// Equivalent to HTTP status 401. Indicates that the requested /// resource requires authentication. The WWW-Authenticate header contains the details of /// how to perform the authentication. Unauthorized = 401, /// Equivalent to HTTP status 402. Reserved for future use. PaymentRequired = 402, /// Equivalent to HTTP status 403. Indicates that the server refuses to /// fulfill the request. Forbidden = 403, /// Equivalent to HTTP status 404. Indicates that the requested resource /// does not exist on the server. NotFound = 404, /// Equivalent to HTTP status 405. Indicates that the request /// method (POST or GET) is not allowed on the requested resource. MethodNotAllowed = 405, /// Equivalent to HTTP status 406. Indicates that the client has /// indicated with Accept headers that it will not accept any of the available /// representations of the resource. NotAcceptable = 406, /// Equivalent to HTTP status 407. Indicates that the /// requested proxy requires authentication. The Proxy-authenticate header contains the /// details of how to perform the authentication. ProxyAuthenticationRequired = 407, /// Equivalent to HTTP status 408. Indicates that the client did not /// send a request within the time the server was expecting the request. RequestTimeout = 408, /// Equivalent to HTTP status 409. Indicates that the request could not be /// carried out because of a conflict on the server. Conflict = 409, /// Equivalent to HTTP status 410. Indicates that the requested resource is no /// longer available. Gone = 410, /// Equivalent to HTTP status 411. Indicates that the required /// Content-length header is missing. LengthRequired = 411, /// Equivalent to HTTP status 412. Indicates that a condition /// set for this request failed, and the request cannot be carried out. Conditions are set /// with conditional request headers like If-Match, If-None-Match, or If-Unmodified-Since. PreconditionFailed = 412, /// Equivalent to HTTP status 413. Indicates that the request /// is too large for the server to process. RequestEntityTooLarge = 413, /// Equivalent to HTTP status 414. Indicates that the URI is too /// long. RequestUriTooLong = 414, /// Equivalent to HTTP status 415. Indicates that the request /// is an unsupported type. UnsupportedMediaType = 415, /// Equivalent to HTTP status 416. Indicates that the /// range of data requested from the resource cannot be returned, either because the /// beginning of the range is before the beginning of the resource, or the end of the range /// is after the end of the resource. RequestedRangeNotSatisfiable = 416, /// Equivalent to HTTP status 417. Indicates that an expectation /// given in an Expect header could not be met by the server. ExpectationFailed = 417, /// Server Error -- 5xx. /// Equivalent to HTTP status 500. Indicates that a generic /// error has occurred on the server. InternalServerError = 500, /// Equivalent to HTTP status 501. Indicates that the server does /// not support the requested function. NotImplemented = 501, /// Equivalent to HTTP status 502. Indicates that an intermediate proxy /// server received a bad response from another proxy or the origin server. BadGateway = 502, /// Equivalent to HTTP status 503. Indicates that the server is /// temporarily unavailable, usually due to high load or maintenance. ServiceUnavailable = 503, /// Equivalent to HTTP status 504. Indicates that an intermediate /// proxy server timed out while waiting for a response from another proxy or the origin /// server. GatewayTimeout = 504, /// Equivalent to HTTP status 505. Indicates that the /// requested HTTP version is not supported by the server. HttpVersionNotSupported = 505, }; // enum HttpStatusCode /// /// Range for the HTTP status codes. /// internal enum HttpStatusRange { /// TBD MaxOkStatus = 299, /// TBD MaxRedirectionStatus = 399 }; // enum HttpStatusRange /* Fielding, et al. Standards Track [Page 3] RFC 2616 HTTP/1.1 June 1999 10.1 Informational 1xx ...........................................57 10.1.1 100 Continue .............................................58 10.1.2 101 Switching Protocols ..................................58 10.2 Successful 2xx ..............................................58 10.2.1 200 OK ...................................................58 10.2.2 201 Created ..............................................59 10.2.3 202 Accepted .............................................59 10.2.4 203 Non-Authoritative Information ........................59 10.2.5 204 No Content ...........................................60 10.2.6 205 Reset Content ........................................60 10.2.7 206 Partial Content ......................................60 10.3 Redirection 3xx .............................................61 10.3.1 300 Multiple Choices .....................................61 10.3.2 301 Moved Permanently ....................................62 10.3.3 302 Found ................................................62 10.3.4 303 See Other ............................................63 10.3.5 304 Not Modified .........................................63 10.3.6 305 Use Proxy ............................................64 10.3.7 306 (Unused) .............................................64 10.3.8 307 Temporary Redirect ...................................65 10.4 Client Error 4xx ............................................65 10.4.1 400 Bad Request .........................................65 10.4.2 401 Unauthorized ........................................66 10.4.3 402 Payment Required ....................................66 10.4.4 403 Forbidden ...........................................66 10.4.5 404 Not Found ...........................................66 10.4.6 405 Method Not Allowed ..................................66 10.4.7 406 Not Acceptable ......................................67 10.4.8 407 Proxy Authentication Required .......................67 10.4.9 408 Request Timeout .....................................67 10.4.10 409 Conflict ............................................67 10.4.11 410 Gone ................................................68 10.4.12 411 Length Required .....................................68 10.4.13 412 Precondition Failed .................................68 10.4.14 413 Request Entity Too Large ............................69 10.4.15 414 Request-URI Too Long ................................69 10.4.16 415 Unsupported Media Type ..............................69 10.4.17 416 Requested Range Not Satisfiable .....................69 10.4.18 417 Expectation Failed ..................................70 10.5 Server Error 5xx ............................................70 10.5.1 500 Internal Server Error ................................70 10.5.2 501 Not Implemented ......................................70 10.5.3 502 Bad Gateway ..........................................70 10.5.4 503 Service Unavailable ..................................70 10.5.5 504 Gateway Timeout ......................................71 10.5.6 505 HTTP Version Not Supported ...........................71 */ } // namespace System.Net ================================================ FILE: Zelig/Zelig/RunTime/Framework/system/System/HTTP/System.Net.HttpVersion.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // namespace System.Net { /// /// Defines the HTTP version numbers that are supported by the /// and /// classes. /// public class HttpVersion { /// /// Defines a instance for HTTP 1.0. /// public static readonly Version Version10 = new Version(1, 0); /// /// Defines a instance for HTTP 1.1. /// public static readonly Version Version11 = new Version(1, 1); } // class HttpVersion } // namespace System.Net ================================================ FILE: Zelig/Zelig/RunTime/Framework/system/System/HTTP/System.Net.HttpWebRequest.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // namespace System.Net { using System; using System.Collections; using System.IO; using System.Net.Sockets; using System.Text; using System.Threading; //using Microsoft.SPOT; //using Microsoft.SPOT.Net.Security; /// /// This is the class that we use to create HTTP and requests. /// Used to register prefix "http" with WEB Request class. /// internal class HttpRequestCreator : IWebRequestCreate { internal HttpRequestCreator() { } /// /// Creates an HttpWebRequest. We register /// for HTTP and HTTPS URLs, and this method is called when a request /// needs to be created for one of those. /// /// Url for request being created. /// The newly created HttpWebRequest. public WebRequest Create(Uri Url) { return new HttpWebRequest(Url); } } // class HttpRequestCreator /// /// Provides an HTTP-specific implementation of the class. /// /// This class does the main work of the request: it collects the header information /// from the user, exposes the Stream for outgoing entity data, and processes the incoming /// request. public class HttpWebRequest : WebRequest { /// /// Array list of connected streams. /// This is static list, keeps all "stay live" sockets. /// private static ArrayList s_connectedStreams; /// /// Timer that checks on open connections and closes them if they are /// idle for a long time. /// private static Timer s_dropOldConnectionsTimer; /// /// Tracks the global state of Http engine. /// private static bool s_initialized; /// /// If a response was created then Dispose on the Request will not dispose the underlying stream. /// private bool m_responseCreated; /// /// Timer callback. Called periodically and closes all connections that /// are idle for long time. /// /// Unused static private void CheckPersistentConnections(object unused) { int count = s_connectedStreams.Count; // The fastest way to exit out - if there are no sockets in the list - exit out. if (count > 0) { DateTime curTime = DateTime.Now; lock (s_connectedStreams) { count = s_connectedStreams.Count; for (int i = count-1; i >= 0; i--) { InputNetworkStreamWrapper streamWrapper = (InputNetworkStreamWrapper)s_connectedStreams[i]; TimeSpan timePassed = streamWrapper.m_lastUsed - curTime; // If the socket is old, then close and remove from the list. if (timePassed.Milliseconds > HttpListener.DefaultKeepAliveMilliseconds) { s_connectedStreams.RemoveAt(i); // Closes the socket to release resources. streamWrapper.Dispose(); } } // turn off the timer if there are no active streams if(s_connectedStreams.Count > 0) { s_dropOldConnectionsTimer.Change( HttpListener.DefaultKeepAliveMilliseconds, System.Threading.Timeout.Infinite ); } } } } /// /// Registers HttpRequestCreator as the creator for the "http" prefix. /// static HttpWebRequest() { s_initialized = false; s_connectedStreams = new ArrayList(); } internal static void Initialize( ) { if(s_initialized == false) { lock (s_connectedStreams) { if(s_initialized == false) { s_dropOldConnectionsTimer = new Timer(CheckPersistentConnections, null, System.Threading.Timeout.Infinite, System.Threading.Timeout.Infinite); // Creates instance of HttpRequestCreator. HttpRequestCreator creates HttpWebRequest // Register prefix. HttpWebRequest handles both http and https HttpRequestCreator creator = new HttpRequestCreator(); RegisterPrefix( "http:", creator ); RegisterPrefix( "https:", creator ); s_initialized = true; } } } } /// /// Closes a response stream, if present. /// /// Not used. protected override void Dispose(bool disposing) { if(m_requestStream != null) { if(!m_responseCreated) { RemoveStreamFromPool(m_requestStream); m_requestStream.Dispose(); } } base.Dispose(disposing); } /// /// The length in KB of the default maximum for response headers /// received. /// /// /// The default configuration file sets this value to 4 kilobytes. /// static int defaultMaxResponseHeadersLen = 4; /// /// Default delay on the Stream.Read and Stream.Write operations /// private const int DefaultReadWriteTimeout = 5 * 60 * 1000; // 5 minutes /// /// maximum length of the line in reponse line /// internal const int maxHTTPLineLength = 4000; /// /// Delegate that can be called on Continue Response /// private HttpContinueDelegate m_continueDelegate; /// /// HTTP verb. /// private string m_method; /// /// The Headers for the HTTP request. /// private WebHeaderCollection m_httpRequestHeaders; /// /// Controls how writes are handled. /// private HttpWriteMode m_httpWriteMode; /// /// The URI that we do the request for. /// private Uri m_originalUrl; /// /// Content length of the request message on POST. /// private long m_contentLength; /// /// The HTTP version for this request. /// private Version m_version; /// /// Timeout for Read And Write on the Stream that we return through /// GetResponse().GetResponseStream() and GetRequestStream() /// private int m_readWriteTimeout; /// /// Proxy to use for connection. /// private IWebProxy m_proxy; /// /// Whether to use persistent connections. /// private bool m_keepAlive; /// /// An array of certificates used to verify servers that support https. /// /// /// The client application sets these certificates to the /// HttpWebRequest. When the server certificate is received, it /// is validated with certificates in this array. /// //////X509Certificate[] m_caCerts; /// /// The number of people using the connection. Must reference-count this /// stuff. Except reference counting is apparently insufficient. I'm going to flag each section /// that uses the parser with a constant, and twiddle the flags for /// adding and removing connections. /// internal const int k_noConnection = 0x0; private const int k_parserFlag = 0x1; private const int k_writeStreamFlag = 0x2; private const int k_readStreamFlag = 0x4; private const int k_abortFlag = 0x8; internal int m_connectionUsers = 0; /// /// Static instance of decoder to convert received bytes from network /// stream into text of the response line and WEB headers. /// static private Decoder UTF8decoder = System.Text.Encoding.UTF8.GetDecoder(); /// /// Invalid characters that cannot be found in a valid method-verb. /// private static readonly char[] k_invalidMethodChars = new char[]{' ', '\r', '\t', '\n'}; /// /// The maximum length, in kilobytes (1024 bytes), of the response /// headers. /// private int m_maxResponseHeadersLen = defaultMaxResponseHeadersLen; /// /// The response from the server. /// private HttpStatusCode m_responseStatus = (HttpStatusCode)0; /// /// true if we have a response, or a transport error while constructing the response /// private bool m_responseComplete = false; /// /// This is non-null if there was an error. If this is true, then there is no valid HttpWebResponse. /// private WebException m_errorResponse = null; /// /// Buffer size for reading from the server /// private const int k_readBlockLength = 2048; /// /// This is the maximum amount of data which can be buffered at any time /// and have a failed match. In other words, if we receive this much /// data, and can't parse it in any useful way, assume an error. /// private const int k_maximumBufferSize = 8192; /// /// True if the request has been started, false otherwise. Disables /// setting of many header properties. /// private bool m_requestSent; /// /// This is the request stream, if it has been created. /// private InputNetworkStreamWrapper m_requestStream; /// /// Whether or not data should be buffered when sent. /// Data is always buffered though (given redirects and stuff). /// private bool m_allowWriteStreamBuffering; /// /// The timeout value for this request. /// private int m_timeout; /// /// Keep NetworkCredential if user have send user name and password. /// private NetworkCredential m_NetworkCredentials; /// /// Gets or sets the timeout value in milliseconds for the /// and /// methods. /// /// The number of milliseconds to wait before the request times /// out. The default is 100,000 milliseconds (100 seconds). /// /// Overrides the property /// of WebRequest. public override int Timeout { get { return m_timeout; } set { if (value < 0 && value != System.Threading.Timeout.Infinite) { throw new ArgumentOutOfRangeException("value"); } m_timeout = value; } } /// /// Set or Get NetworkCredential if user have send user name and password. /// public NetworkCredential Credentials { get { return m_NetworkCredentials; } set { m_NetworkCredentials = value; } } ///////// ///////// Gets or sets the array of certificates used to authenticate https ///////// servers. These certificates are used only for https connections; ///////// http connections do not require them. ///////// //////public X509Certificate[] HttpsAuthentCerts //////{ ////// get { return m_caCerts; } ////// set { m_caCerts = value; } //////} /// /// Gets or sets a timeout in milliseconds when writing to or reading /// from a stream. /// /// The number of milliseconds before the writing or reading /// times out. The default value is 300,000 milliseconds (5 minutes). /// /// This property is used to control the timeout when calling /// and . /// This property affects Streams returned from /// GetResponse().() /// and /// GetResponse().(). /// public int ReadWriteTimeout { get { return m_readWriteTimeout; } set { // we can't change timeouts after the request has been sent if (m_requestSent) throw new InvalidOperationException("Cannot change timeout after request submitted "); if (value <= 0 && value != System.Threading.Timeout.Infinite) { throw new ArgumentOutOfRangeException("value"); } m_readWriteTimeout = value; } } /// /// The HTTP status code returned by the server. /// internal HttpStatusCode ResponseStatusCode { get { return m_responseStatus; } } /// /// Return if error is present in response. /// /// true if error happened, false otherwise internal bool hasError() { return m_errorResponse != null; } /// /// Gets the original Uniform Resource Identifier (URI) of the request. /// /// /// The URI object was created by the constructor and is always /// non-null. The URI object will always be the base URI, because /// automatic re-directs aren't supported. /// /// A Uri that contains the URI of the Internet resource passed /// to the WebRequest. method. /// public override Uri RequestUri { get { return m_originalUrl; } } /// /// Gets the URI for this request. /// /// A Uri that identifies the Internet /// resource that actually responds to the request. The default is the /// URI used by the /// WebRequest. method to /// initialize the request. /// /// /// This value is always the same as the /// /// property, because automatic re-direction isn't supported. /// public Uri Address { get { return m_originalUrl; } } /// /// Gets or sets a value that indicates whether to buffer the data sent /// to the Internet resource. /// /// true to enable buffering of the data sent /// to the Internet resource; false to disable buffering. The /// default is true. public bool AllowWriteStreamBuffering { get { return m_allowWriteStreamBuffering; } set { m_allowWriteStreamBuffering = value; } } /// /// Gets or sets the Content-Length of the request entity body. /// /// The number of bytes of data to send to the Internet resource. /// The default is -1, which indicates the property has not been set and /// that there is no request data to send. /// /// Getting this property returns the last value set, or -1 if no value /// has been set. Setting it sets the content length, and the /// application must write that much data to the stream. This property /// interacts with /// HttpWebRequest.. /// public override long ContentLength { get { return m_contentLength; } set { //no race. Don't need interlocked if (true == m_requestSent) throw new InvalidOperationException(); if (value < 0) throw new ArgumentOutOfRangeException("Content length cannot be negative: " + value); m_contentLength = value; //if a content length is set, then we cannot send chunked data. m_httpWriteMode = HttpWriteMode.Write; } } /// /// Gets or sets the delegate used to signal on Continue callback. /// /// A delegate that implements the callback method that executes /// when an HTTP Continue response is returned from the Internet /// resource. The default value is null. /// /// This property gets or sets the delegate method called when an HTTP /// 100-continue response is received from the Internet resource. /// public HttpContinueDelegate ContinueDelegate { get { return m_continueDelegate; } set { m_continueDelegate = value; } } /// /// Gets a value that indicates whether the request should follow /// redirection responses. This value is always /// false, because Autodirect isn't supported. /// /// This value is always false, because /// Autodirect isn't supported. public bool AllowAutoRedirect { get { return false; } } /// /// Gets the maximum number of automatic redirections. This value is /// always zero, because auto-redirection isn't supported. /// /// This value is always zero, because auto-redirection isn't /// supported. public int MaximumAutomaticRedirections { get { return 0; } } /// /// Gets or sets the HTTP method of this request. /// /// The request method to use to contact the Internet resource. /// The default value is GET. /// /// This method represents the initial origin verb, which is unchanged /// and unaffected by redirects. /// public override string Method { get { return m_method; } set { if (ValidationHelper.IsBlankString(value)) { throw new ArgumentException("Blank Method Set: " + value); } if (value.IndexOfAny(k_invalidMethodChars) != -1) { throw new ArgumentException("Invalid Method Set: " + value); } m_method = value; } } /// /// Gets or sets whether to use a persistent connection, if available. /// /// true if the request to the Internet resource should /// contain a Connection HTTP header with the value Keep-alive; /// otherwise, false. The default is true. public bool KeepAlive { get { return m_keepAlive; } set { m_keepAlive = value; } } /// /// Gets or sets the maximum allowed length of the response headers. /// /// The length, in kilobytes (1024 bytes), of the response /// headers. /// /// The length of the response header includes the response status line /// and any extra control characters that are received as part of HTTP /// protocol. A value of -1 means no limit is imposed on the response /// headers; a value of 0 means that all requests fail. If this /// property is not explicitly set, it defaults to the value of the /// /// property. /// public int MaximumResponseHeadersLength { get { return m_maxResponseHeadersLen; } set { if (value <= 0 && value != -1) { throw new ArgumentOutOfRangeException(); } m_maxResponseHeadersLen = value; } } /// /// Gets or sets the default maximum allowed length of the response /// headers. /// /// The default maximum allowed length of the response headers. /// /// /// On creation of an HttpWebRequest instance, this /// value is used for the /// /// property. /// public static int DefaultMaximumResponseHeadersLength { get { return defaultMaxResponseHeadersLen; } set { if (value <= 0 && value != -1) { throw new ArgumentOutOfRangeException(); } defaultMaxResponseHeadersLen = value; } } /// /// A collection of HTTP headers stored as name/value pairs. /// /// A WebHeaderCollection that contains the name/value /// pairs that make up the headers for the HTTP request. /// /// The following header values are set through properties on the /// HttpWebRequest class: Accept, Connection, /// Content-Length, Content-Type, Expect, Range, Referer, /// Transfer-Encoding, and User-Agent. Trying to set these header /// values by using /// WebHeaderCollection.() /// will raise an exception. Date and Host are set internally. /// public override WebHeaderCollection Headers { get { return m_httpRequestHeaders; } set { // we can't change headers after they've already been sent if (m_requestSent) throw new InvalidOperationException("Cannot change headers after request submitted"); WebHeaderCollection webHeaders = value; WebHeaderCollection newWebHeaders = new WebHeaderCollection(true); // Copy And Validate - // Handle the case where their object tries to change // name, value pairs after they call set, so therefore, // we need to clone their headers. for (int i = 0; i < webHeaders.AllKeys.Length; i++) { newWebHeaders.Add(webHeaders.AllKeys[i], webHeaders[webHeaders.AllKeys[i]]); } m_httpRequestHeaders = newWebHeaders; } } /// /// Gets or sets the proxy for the request. /// /// The object to use to proxy /// the request. null indicates that no proxy will be used. public override IWebProxy Proxy { get { return m_proxy; } set { if (m_requestSent) throw new InvalidOperationException("Cannot change proxy after request submitted"); if (value == null) throw new ArgumentNullException(); m_proxy = value; } } /// /// Gets or sets the state of chunk transfer send mode. /// /// true to send data to the Internet resource in /// segments; otherwise, false. The default value is /// false. /// /// If true, bits are uploaded and written using the /// Chunked property of HttpWriteMode. /// public bool SendChunked { get { return m_httpWriteMode == HttpWriteMode.Chunked; } set { //no race. Don't need interlocked if (true == m_requestSent) { throw new InvalidOperationException("Cannot set \"chunked\" after request submitted"); } if (value) { m_httpWriteMode = HttpWriteMode.Chunked; } else { if (m_contentLength >= 0) { m_httpWriteMode = HttpWriteMode.Write; } else { m_httpWriteMode = HttpWriteMode.None; } } } } /// /// Gets or sets the HTTP protocol version for this request. /// /// The HTTP version to use for the request. The default is /// . public Version ProtocolVersion { get { return m_version; } set { if (!value.Equals(HttpVersion.Version10) && !value.Equals(HttpVersion.Version11)) { throw new ArgumentException("Invalid HTTP Verion: " + value); } m_version = new Version(value.Major, value.Minor); } } /// /// Private method for removing duplicate code which removes and adds /// headers that are marked private. /// /// The name of the HTTP header. /// The value of the HTTP header. private void SetSpecialHeaders(String HeaderName, String value) { value = WebHeaderCollection.CheckBadChars(value, true); m_httpRequestHeaders.RemoveInternal(HeaderName); if (value != null && value.Length != 0) { m_httpRequestHeaders.AddInternal(HeaderName, value); } } /// /// Gets or sets the type of the entity body (the value of the content /// type). /// /// The value of the Content-type HTTP header. The /// default value is null. /// /// Setting to null clears the content-type. /// public override String ContentType { get { return m_httpRequestHeaders[HttpKnownHeaderNames.ContentType]; } set { SetSpecialHeaders(HttpKnownHeaderNames.ContentType, value); } } /// /// Gets or sets the TransferEncoding HTTP header. /// /// The value of the Transfer-encoding HTTP header. The /// default value is null. /// /// null clears the transfer encoding except for the /// Chunked setting. /// public String TransferEncoding { get { return m_httpRequestHeaders[HttpKnownHeaderNames.TransferEncoding]; } set { bool fChunked; // on blank string, remove current header if (ValidationHelper.IsBlankString(value)) { // if the value is blank, then remove the header m_httpRequestHeaders.RemoveInternal(HttpKnownHeaderNames.TransferEncoding); return; } // if not, check if the user is trying to set chunked: string newValue = value.ToLower(); fChunked = (newValue.IndexOf("chunked") != -1); // prevent them from adding chunked, or from adding an Encoding // without turing on chunked, the reason is due to the HTTP // Spec which prevents additional encoding types from being // used without chunked if (fChunked) { throw new ArgumentException("Cannot add \"Encoding\" and set \"chunked\""); } else if (m_httpWriteMode != HttpWriteMode.Chunked) { throw new InvalidOperationException("Need HttpWriteMode.Chunked to be current mode"); } else { m_httpRequestHeaders.CheckUpdate(HttpKnownHeaderNames.TransferEncoding, value); } } } /// /// Gets or sets the value of the Accept HTTP header. /// /// The value of the Accept HTTP header. The default /// value is null. public String Accept { get { return m_httpRequestHeaders[HttpKnownHeaderNames.Accept]; } set { SetSpecialHeaders(HttpKnownHeaderNames.Accept, value); } } /// /// Gets or sets the value of the Referer HTTP header. /// /// The value of the Referer HTTP header. The default /// value is null. /// This header value is misspelled intentionally. public String Referer { get { return m_httpRequestHeaders[HttpKnownHeaderNames.Referer]; } set { SetSpecialHeaders(HttpKnownHeaderNames.Referer, value); } } /// /// Gets or sets the value of the User-Agent HTTP header. /// /// The value of the User-agent HTTP header. The default /// value is null. public String UserAgent { get { return m_httpRequestHeaders[HttpKnownHeaderNames.UserAgent]; } set { SetSpecialHeaders(HttpKnownHeaderNames.UserAgent, value); } } /// /// Gets or sets the value of the Expect HTTP header. /// /// The contents of the Expect HTTP header. The default /// value is null. /// When setting this property, null clears the /// Expect (except for the 100-continue value). public String Expect { get { return m_httpRequestHeaders[HttpKnownHeaderNames.Expect]; } set { // on blank string, remove current header if (ValidationHelper.IsBlankString(value)) { m_httpRequestHeaders.RemoveInternal(HttpKnownHeaderNames.Expect); return; } m_httpRequestHeaders.CheckUpdate(HttpKnownHeaderNames.Expect, value); } } /// /// Gets the IfModifiedSince value of /// HttpKnownHeaderNames. /// /// A that contains the contents of /// the If-Modified-Since HTTP header. The default value is the /// current date and time. /// /// The setter for this property isn't supported, because a function /// that formats the time isn't implemented. /// /// null clears the /// IfModifiedSince header. /// public DateTime IfModifiedSince { get { string ifmodHeaderValue = m_httpRequestHeaders[HttpKnownHeaderNames.IfModifiedSince]; if (ifmodHeaderValue == null) { return DateTime.Now; } return HttpProtocolUtils.string2date(ifmodHeaderValue); } // Set is not supported at this moment. It is needed for server. //set //{ // SetSpecialHeaders(HttpKnownHeaderNames.IfModifiedSince, // HttpProtocolUtils.date2string(value)); //} } /// /// Constructs an instance of the HTTP Protocol class and initalizes it /// to the basic header state. /// /// The Url object for which we're creating. internal HttpWebRequest(Uri Url) { m_requestSent = false; m_originalUrl = Url; m_httpWriteMode = HttpWriteMode.None; m_keepAlive = true; m_httpRequestHeaders = new WebHeaderCollection(true); m_httpWriteMode = HttpWriteMode.None; m_contentLength = -1; m_version = HttpVersion.Version11; m_allowWriteStreamBuffering = false; m_method = "GET"; m_timeout = WebRequest.DefaultTimeout; m_readWriteTimeout = DefaultReadWriteTimeout; m_proxy = WebRequest.DefaultWebProxy; m_responseCreated = false; } public void Reset() { m_requestSent = false; m_responseCreated = false; m_contentLength = -1; m_httpWriteMode = HttpWriteMode.None; m_httpRequestHeaders = new WebHeaderCollection(true); } /// /// Gets whether a response has been received from an Internet resource. /// /// true if a response has been received; otherwise, /// false. public bool HaveResponse { get { return (m_responseComplete); } } /// /// Adds a byte range header to the request for a specified range. /// /// The start of the range. /// The end of the range. public void AddRange(int from, int to) { AddRange("bytes", from, to); } /// /// Adds a range header to a request for a specific range from the /// beginning or end of the requested data. /// /// Start of the range. The end of the range is the /// end of the existing data. public void AddRange(int range) { AddRange("bytes", range); } /// /// Adds a range header to a request for a specified range. /// /// The description of the range, such as /// "bytes". /// The start of the range. /// The end of the range. /// /// would normally be /// specified as "bytes", since this is the only range specifier /// recognized by most HTTP servers. Setting /// to some other string allows /// support for custom range specifiers other than bytes. The /// byte-range specifier is defined in RFC 2616 by the IETF. public void AddRange(string rangeSpecifier, int from, int to) { // Do some range checking before assembling the header if ((from < 0) || (to < 0) || (from > to)) { throw new ArgumentOutOfRangeException(); } // Add it if (!AddRange(rangeSpecifier, from.ToString(), to.ToString())) { throw new InvalidOperationException(); } } /// /// Adds a range header to a request for a specific range from the /// beginning or end of the requested data. /// /// The description of the range, such as /// "bytes". /// The range value. public void AddRange(string rangeSpecifier, int range) { if (!AddRange(rangeSpecifier, range.ToString(), (range >= 0) ? "" : null)) { throw new InvalidOperationException(); } } /// /// Adds or extends a range header. /// /// Range specifier /// Start of range /// End of range /// TBD /// /// Various range types can be specified via /// , but only one type of Range /// request will be made; for example, a byte-range request, or a /// row-range request. Range types cannot be mixed. /// private bool AddRange(string rangeSpecifier, string from, string to) { // Checks for NULL rangeSpecifier if (rangeSpecifier == null) { throw new ArgumentNullException(); } // Checks for Valid characters in rangeSpecifier if (!WebHeaderCollection.IsValidToken(rangeSpecifier)) { throw new ArgumentException(); } // Add range specifier or appends to existing one string curRange = m_httpRequestHeaders[HttpKnownHeaderNames.Range]; if ((curRange == null) || (curRange.Length == 0)) { curRange = rangeSpecifier + "="; } else { if (String.Compare(curRange.Substring(0, curRange.IndexOf('=')), rangeSpecifier) != 0) { return false; } curRange = string.Empty; } curRange += from.ToString(); if (to != null) { curRange += "-" + to; } m_httpRequestHeaders.SetAddVerified(HttpKnownHeaderNames.Range, curRange); return true; } /// /// This function is called first in GetRequestStream() and throws exception /// if conditions are not correct. /// private void ValidateGetRequestStream() { // TransferEncoding is set to a value and SendChunked is false. if (TransferEncoding != null && SendChunked == false) { throw new InvalidOperationException(); } // ProtocolViolationException The Method property is GET or HEAD. if (m_method == "GET" || m_method == "HEAD") { throw new ProtocolViolationException("HTTP Method is incorrect: " + Method); } // Condition for exception - KeepAlive is true, AllowWriteStreamBuffering is false, // ContentLength is -1, SendChunked is false. if (m_method == "PUT" || m_method == "POST") { if (ContentLength == -1 && SendChunked == false) { throw new ProtocolViolationException("Content lenght must be present for this request"); } } } /// /// Updates the HTTP WEB header collection to prepare it for request. /// private void PrepareHeaders() { // Depending on protocol version we update HTTP headers collection. if (!(m_version.Equals(HttpVersion.Version10))) { if (m_httpWriteMode == HttpWriteMode.Write) { m_httpRequestHeaders.ChangeInternal(HttpKnownHeaderNames.ContentLength, m_contentLength.ToString()); } else if (m_httpWriteMode == HttpWriteMode.Chunked) { m_httpRequestHeaders.AddInternal(HttpKnownHeaderNames.TransferEncoding, "chunked"); } // Set keepAlive header, we always send it, do not rely in defaults. // Basically we send "Connection:Close" or "Connection:Keep-Alive" string connectionValue; if (m_keepAlive) { connectionValue = "Keep-Alive"; } else { connectionValue = "Close"; } m_httpRequestHeaders.ChangeInternal(HttpKnownHeaderNames.Connection, connectionValue); } //1.0 path else { //1.0 doesn't support chunking SendChunked = false; //1.0 doesn't support keep alive m_keepAlive = false; if (m_httpWriteMode == HttpWriteMode.Write) { m_httpRequestHeaders.ChangeInternal(HttpKnownHeaderNames.ContentLength, m_contentLength.ToString()); } } m_httpRequestHeaders.ChangeInternal(HttpKnownHeaderNames.Host, ConnectHostAndPort()); // Adds user name and password for basic Http authentication. if (m_NetworkCredentials != null && m_NetworkCredentials.AuthenticationType == AuthenticationType.Basic) { // If credentials are supplied, we need to add header like "Authorization: Basic QWxhZGRpbjpvcGVuIHNlc2FtZQ==" // where QWxhZGRpbjpvcGVuIHNlc2FtZQ== is b64 encoded user name and password orginating as username:password. string userInfo = ""; if (m_NetworkCredentials.UserName != null) { userInfo += m_NetworkCredentials.UserName; } userInfo += ":"; if (m_NetworkCredentials.Password != null) { userInfo += m_NetworkCredentials.Password; } // Encode user info. byte[] buffer = Encoding.UTF8.GetBytes(userInfo); string userNameAndPassEncoded = buffer != null ? Convert.ToBase64String(buffer) : ""; string authValue = "Basic " + userNameAndPassEncoded; m_httpRequestHeaders.ChangeInternal(HttpKnownHeaderNames.Authorization, authValue); } m_requestSent = true; } /// /// Return string with remote Host and Port if port is not default. /// Need update for HTTPS. /// /// String with host Url and port corresponding to target Uri. internal string ConnectHostAndPort() { string retStr = m_originalUrl.Host; if (m_originalUrl.Port != 80) { retStr += ":" + m_originalUrl.Port; } return retStr; } /// /// Removes the given stream from the connection pool /// internal static void RemoveStreamFromPool(InputNetworkStreamWrapper stream) { lock (s_connectedStreams) { if (s_connectedStreams.Contains(stream)) { s_connectedStreams.Remove(stream); } } } /// /// Returns network stream connected to server. It could be a proxy or a /// real server Uri. /// /// Uri that describes the proxy server. /// Uri that describes the target (real) server. /// Nerwork stream connected to server. private InputNetworkStreamWrapper EstablishConnection(Uri proxyServer, Uri targetServer) { InputNetworkStreamWrapper retStream = null; // Create a socket and set reuse true. // But before creating new socket we look in the list of existing sockets. If socket for this host already // exist - use it. No need to create new socket. string remoteServer = targetServer.Host + ":" + targetServer.Port; lock (s_connectedStreams) { ArrayList removeStreamList = new ArrayList(); for (int i = 0; i < s_connectedStreams.Count; i++) { InputNetworkStreamWrapper inputStream = (InputNetworkStreamWrapper)s_connectedStreams[i]; if (inputStream.m_rmAddrAndPort == remoteServer && !inputStream.m_inUse) { // Re-use the connected socket. // But first we need to know that socket is not closed. try { // If socket is closed ( from this or other side ) the call throws exception. if (inputStream.m_socket.Poll(1, SelectMode.SelectWrite)) { // No exception, good we can condtinue and re-use connected stream. // Control flow returning here means persistent connection actually works. inputStream.m_inUse = true; inputStream.m_lastUsed = DateTime.Now; retStream = inputStream; break; } else { removeStreamList.Add(inputStream); } } catch (Exception) { removeStreamList.Add(inputStream); } } } for (int i = 0; i < removeStreamList.Count; i++) { InputNetworkStreamWrapper removeStream = (InputNetworkStreamWrapper)removeStreamList[i]; // Means socket was closed. Remove it from the list. s_connectedStreams.Remove(removeStream); removeStream.Dispose(); } } if (retStream == null) { // Existing connection did not worked. Need to establish new one. IPAddress address = null; UriHostNameType hostNameType = proxyServer.HostNameType; if (hostNameType == UriHostNameType.IPv4) { address = IPAddress.Parse(proxyServer.Host); } else if (hostNameType == UriHostNameType.Dns) { IPHostEntry hostEntry = null; try { hostEntry = Dns.GetHostEntry(proxyServer.Host); } catch(SocketException se) { throw new WebException("host not available", se, WebExceptionStatus.ConnectFailure, null); } int addressListSize = hostEntry.AddressList.Length; for (int i = 0; i < addressListSize; i++) { if ((address = hostEntry.AddressList[i]) != null) { break; } } if (address == null) { throw new WebException("Unable to resolve Dns entry to valid IPv4 Address", WebExceptionStatus.NameResolutionFailure); } } else { throw new WebException("Only IPv4 or Dns host names allowed."); } // If socket was not found in waiting connections, then we create new one. Socket socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); try { socket.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReuseAddress, true); } catch{} try { socket.SetSocketOption(SocketOptionLevel.Tcp, SocketOptionName.NoDelay, true); } catch{} // Connect to remote endpoint try { IPEndPoint remoteEP = new IPEndPoint(address, proxyServer.Port); socket.Connect((EndPoint)remoteEP); } catch (SocketException e) { throw new WebException("connection failed", e, WebExceptionStatus.ConnectFailure, null); } bool isHttps = m_originalUrl.Scheme == "https"; // We have connected socket. Create request stream retStream = new InputNetworkStreamWrapper(new NetworkStream(socket), socket, !isHttps, proxyServer.Host + ":" + proxyServer.Port); //////// For https proxy works differenly from http. //////if (isHttps) //////{ ////// // If proxy is set, then for https we need to send "CONNECT" command to proxy. ////// // Once this command is send, the socket from proxy works as if it is the socket to the destination server. ////// if (proxyServer != targetServer) ////// { ////// String request = "CONNECT " + remoteServer + " HTTP/" + ProtocolVersion + "\r\n\r\n"; ////// Byte[] bytesToSend = Encoding.UTF8.GetBytes(request); ////// retStream.Write(bytesToSend, 0, bytesToSend.Length); ////// // Now proxy should respond with the connected status. If it is successul, then we are good to go. ////// CoreResponseData respData = ParseHTTPResponse(retStream, m_keepAlive); ////// if (respData.m_statusCode != (int)HttpStatusCode.OK) ////// { ////// throw new WebException("Proxy returned " + respData.m_statusCode, WebExceptionStatus.ConnectFailure); ////// } ////// } ////// // Once connection estiblished need to create secure stream and authenticate server. ////// SslStream sslStream = new SslStream(retStream.m_Socket); ////// // Throws exception is fails. ////// sslStream.AuthenticateAsClient(m_originalUrl.Host, null, m_caCerts, SslVerification.CertificateRequired, SslProtocols.Default); ////// // Changes the stream to SSL stream. ////// retStream.m_Stream = sslStream; ////// // Changes the address. Originally socket was connected to proxy, now as if it connected to m_originalUrl.Host on m_originalUrl.Port ////// retStream.m_rmAddrAndPort = m_originalUrl.Host + ":" + m_originalUrl.Port; //////} lock (s_connectedStreams) { s_connectedStreams.Add(retStream); // if the current stream list is empty then start the timer that drops unused connections. if (s_connectedStreams.Count == 1) { s_dropOldConnectionsTimer.Change(HttpListener.DefaultKeepAliveMilliseconds, System.Threading.Timeout.Infinite); } } } return retStream; } /// /// Submits request to the WEB server. /// private void SubmitRequest() { // We have connected socket. Create request stream // If proxy is set - connect to proxy server. if(m_requestStream == null) { if (m_proxy == null) { // Direct connection to target server. m_requestStream = EstablishConnection(m_originalUrl, m_originalUrl); } else // Connection through proxy. We create network stream connected to proxy { Uri proxyUri = m_proxy.GetProxy(m_originalUrl); if (m_originalUrl.Scheme == "https") { // For HTTPs we still need to know the target name to decide on persistent connection. m_requestStream = EstablishConnection(proxyUri, m_originalUrl); } else { // For normal HTTP all requests go to proxy m_requestStream = EstablishConnection(proxyUri, proxyUri); } } } // We have connected stream. Set the timeout from HttpWebRequest m_requestStream.WriteTimeout = m_readWriteTimeout; m_requestStream.ReadTimeout = m_readWriteTimeout; // Now we need to write headers. First we update headers. PrepareHeaders(); // Now send request string and headers. byte[] dataToSend = GetHTTPRequestData(); #if DEBUG // In debug mode print the request. It helps a lot to troubleshoot the issues. int byteUsed, charUsed; bool completed = false; char[] charBuf = new char[dataToSend.Length]; UTF8decoder.Convert(dataToSend, 0, dataToSend.Length, charBuf, 0, charBuf.Length, true, out byteUsed, out charUsed, out completed); string strSend = new string(charBuf); Console.WriteLine(strSend); #endif // Writes this data to the network stream. m_requestStream.Write(dataToSend, 0, dataToSend.Length); m_requestSent = true; } /// /// Reads and parses HTTP response from server. /// After return of function HTTP response is read. /// /// Network stream connected to server. /// TBD /// CoreResponseData that describes server response. private CoreResponseData ParseHTTPResponse(InputNetworkStreamWrapper inStream, bool defaultKeepAlive) { // CoreResponseData keeps all the information of the response. CoreResponseData ret = new CoreResponseData(); // maximumHeadersLength is maximum total length of http header. Basically this is amount // of memory used for headers. int headersLength = m_maxResponseHeadersLen == -1 ? 0x7FFFFFFF : m_maxResponseHeadersLen * 1024; ret.m_shouldClose = !defaultKeepAlive; // Parse the request line. string line = inStream.Read_HTTP_Line(maxHTTPLineLength).Trim(); // Cutoff white spaces int currentOffset = 0; for (; currentOffset < line.Length && ' ' != line[currentOffset]; ++currentOffset) ; // find HTTP version, read http/1.x string httpVersionString = line.Substring(0, currentOffset).ToLower(); if (httpVersionString.Equals("http/1.1")) { ret.m_version = HttpVersion.Version11; } else if (httpVersionString.Equals("http/1.0")) { ret.m_version = HttpVersion.Version10; } else { ret.m_status = WebExceptionStatus.ServerProtocolViolation; ret.m_exceptionMessage = "Unknown http version: " + httpVersionString; return ret; } //advance to the status code for (; currentOffset < line.Length && ' ' == line[currentOffset]; ++currentOffset) ; // Read the status code int codeStart = currentOffset; for (; currentOffset < line.Length && ' ' != line[currentOffset]; ++currentOffset) ; int statusCode = -1; try { string statusCodeStr = line.Substring(codeStart, currentOffset - codeStart); statusCode = Convert.ToInt32(statusCodeStr); } catch (Exception e) { ret.m_status = WebExceptionStatus.ServerProtocolViolation; ret.m_exceptionMessage = "Missing status code in HTTP reply"; ret.m_innerException = e; return ret; } // If we get here - status code should be read. ret.m_statusCode = statusCode; // Advance to the status message. The message is optional for (; currentOffset < line.Length && ' ' != line[currentOffset]; ++currentOffset) ; ret.m_statusDescription = line.Substring(currentOffset); ret.m_headers = new WebHeaderCollection(true); ret.m_chunked = false; ret.m_contentLength = -1; while ((line = inStream.Read_HTTP_Header(maxHTTPLineLength)).Length > 0) { // line.Length is used for the header. Substruct it. headersLength -= line.Length; // If total length used for header is exceeded, we break if (headersLength < 0) { ret.m_status = WebExceptionStatus.ServerProtocolViolation; ret.m_exceptionMessage = "Headers size exceed limit"; return ret; } // Now parse the header. int sepIdx = line.IndexOf(':'); if (sepIdx == -1) { ret.m_status = WebExceptionStatus.ServerProtocolViolation; ret.m_exceptionMessage = "Illegal header format: " + line; return ret; } string headerName = line.Substring(0, sepIdx); string headerValue = line.Substring(sepIdx + 1).TrimStart(null); string matchableHeaderName = headerName.ToLower(); ret.m_headers.AddInternal(headerName, headerValue); if (matchableHeaderName.Equals("content-length")) { try { ret.m_contentLength = Convert.ToInt32(headerValue); // set the response stream length for the input stream, so that an EOF will be read // if the caller tries to read base the response content length inStream.m_bytesLeftInResponse = ret.m_contentLength; } catch (Exception e) { ret.m_status = WebExceptionStatus.ServerProtocolViolation; ret.m_exceptionMessage = "Content length NAN: " + headerValue; ret.m_innerException = e; return ret; } } else if (matchableHeaderName.Equals("transfer-encoding")) { if (headerValue.ToLower().IndexOf("chunked") != -1) { ret.m_chunked = true; } } else if (matchableHeaderName.Equals("connection")) { if (headerValue.ToLower().IndexOf(HttpKnownHeaderValues.close) != -1) { ret.m_shouldClose = true; } } } return ret; } /// /// Event handler for the web request timeout. This handler will be invoked if the response takes longer than the value /// indicated by the property Timeout. /// /// private void OnRequestTimeout(object arg) { if(m_requestStream != null && m_requestStream.m_socket != null) { try { // Close the socket to kill the operation m_requestStream.m_socket.Close(); } catch { } finally { m_requestStream.m_inUse = false; } } } /// /// Returns a response from an Internet resource. Overrides the /// WebRequest. /// method. /// /// The response from the Internet resource. public override WebResponse GetResponse() { HttpWebResponse response = null; try { // If response was not sent, Submit the request. if (!m_requestSent) { SubmitRequest(); } CoreResponseData respData = null; // reset the total response bytes for the new request. m_requestStream.m_bytesLeftInResponse = -1; // create the request timeout timer. This will kill the operation if it takes longer than specified by the Timeout property. // The underlying socket will be closed to end the web request using (Timer tmr = new Timer(new TimerCallback(OnRequestTimeout), null, m_timeout, System.Threading.Timeout.Infinite)) { // Processes response from server. Request stream should already be there. respData = ParseHTTPResponse(m_requestStream, m_keepAlive); if (respData.m_statusCode == (int)HttpStatusCode.Continue) { if (m_continueDelegate != null) { m_continueDelegate(respData.m_statusCode, respData.m_headers); } else { respData = ParseHTTPResponse(m_requestStream, m_keepAlive); } } } response = new HttpWebResponse(m_method, m_originalUrl, respData, this); // Now we look if response has chunked encoding. If it is chunked, we need to set flag in m_requestStream we return. if (respData.m_chunked) { m_requestStream.m_enableChunkedDecoding = true; } // Currently the request and response are the same network streams, but we optimize later. response.SetResponseStream(m_requestStream); m_responseStatus = response.StatusCode; m_responseCreated = true; } catch(SocketException se) { if (m_requestStream != null) { m_requestStream.m_inUse = false; if (m_requestStream.m_socket != null) { this.m_requestStream.m_socket.Close(); } } throw new WebException("", se); } catch(Exception e) { throw new WebException("", e); } return response; } /// /// Submits a request with HTTP headers to the server, and returns a /// Stream object to use to write request data. /// /// A Stream to use to write request data. /// Used for POST of PUT requests. public override Stream GetRequestStream() { // Validates the call to GetRequestStream. Throws exception on errors. ValidateGetRequestStream(); // Submits the request. try { SubmitRequest(); } catch { if(m_requestStream != null) { RemoveStreamFromPool(m_requestStream); m_requestStream.Dispose(); } throw; } // Return the stream return m_requestStream.CloneStream(); } /// /// Constucts WEB exception if error is detected during parsing. /// /// Inner exception network exception /// Partially constructed HttpWebResponse /// WebException instance private static WebException protocolError(Exception inner, HttpWebResponse resp) { HttpStatusCode statusCode = resp.StatusCode; int sr = (int)statusCode; string message = "(" + ((int)statusCode) + ")"; string description; description = resp.StatusDescription; if (description != null && description.Length > 0) message += " " + description; message = "Server returned error" + message; return new WebException(message, inner, WebExceptionStatus.ProtocolError, resp); } internal bool m_sentHeaders = false; private bool hasEntityData() { if (m_httpWriteMode != HttpWriteMode.None) return true; else return false; } private bool canWrite() { return !KnownVerbs.GetHttpVerbType(Method).m_ContentBodyNotAllowed; } /// /// Retrieves HTTP request as bytes array. Used to create a request /// message. /// /// Byte array with HTTP request. This data is sent through network. private byte[] GetHTTPRequestData() { //step 1 - compute the length of the headers. string statusLine; // Connect verbs require CONNECT host:port if (Method.ToUpper().Equals("CONNECT")) { statusLine = "CONNECT " + Address.Host + ":" + Address.Port + " HTTP/" + ProtocolVersion + "\r\n"; } else if (m_proxy != null && m_originalUrl.Scheme != "https") { statusLine = Method + " " + Address.AbsoluteUri + " HTTP/" + ProtocolVersion + "\r\n"; } else { statusLine = Method + " " + Address.AbsolutePath + " HTTP/" + ProtocolVersion + "\r\n"; // .PathAndQuery } //most intrinsic headers are stored in the webheaders class //content length is not. int headersLength = statusLine.Length; //extra header lengths. Includes extension headers. headersLength += Headers.byteLength(); byte[] headerBytes = new byte[headersLength]; int currentOffset = 0; //store the request line currentOffset += copyString(statusLine, headerBytes, currentOffset); //now for the general headers currentOffset += Headers.copyTo(headerBytes, currentOffset); return headerBytes; } /// /// Converts array to string by casting bytes to chars. /// /// Array with byte data. /// Offset to start convertion. /// Count of bytes to convert to string. /// String converted from byte array. private static string toEAscii(byte[] data, int offset, int count) { char[] output = new char[count]; for (int i = 0; i < count; ++i) { output[i] = (char)data[offset + i]; } return new string(output, 0, count); } /// /// Convert string to array of bytes /// /// string to convert /// array of bytes converted from string internal static byte[] fromEAscii(string data) { byte[] ret = new byte[data.Length]; for (int i = 0; i < data.Length; ++i) { ret[i] = (byte)data[i]; } return ret; } /// /// This function returns true if the response code from the server /// (i.e. 304) MUST NOT have any entity data. I will artificially set /// the content length in the stream to zero, so that reading... /// /// HTTP response code /// true if the specified response code is one of the /// defined values; otherwise, false. private bool setContentLengthToZero(HttpStatusCode responseCode) { switch (responseCode) { case HttpStatusCode.SwitchingProtocols: case HttpStatusCode.ResetContent: case HttpStatusCode.NotModified: case HttpStatusCode.NoContent: case HttpStatusCode.UseProxy: return true; default: return false; } } /// /// Copies a string into an array of bytes. /// /// A String to copy. /// Output array. /// Offset to start placing data in array. /// Count of bytes copied private static int copyString(String src, byte[] bytes, int offset) { int i; for (i = 0; i < src.Length; ++i) bytes[offset + i] = (byte)src[i]; return i; } }; // class HttpWebRequest } // namespace System.Net ================================================ FILE: Zelig/Zelig/RunTime/Framework/system/System/HTTP/System.Net.HttpWebResponse.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // namespace System.Net { using System; using System.Collections; using System.Globalization; using System.IO; using System.Net; using System.Net.Sockets; using System.Reflection; using System.Text; using System.Threading; using System.Diagnostics; /// /// Handles retrieval of HTTP Response headers, and handles data reads. /// /// This class should never be created directly, but rather should /// be created by the /// HttpWebRequest. /// method. /// public class HttpWebResponse : WebResponse { /// /// The Web request object that was used for this response. /// We need it to access KeepAlive property. /// private HttpWebRequest m_httpWebRequest; /// /// Response URI generated by the request. /// private Uri m_url; /// /// response Method gernated by the request /// private string m_method; /// /// ConnectStream - for reading actual data /// private InputNetworkStreamWrapper m_responseStream; /// /// Collection of HTTP headers returned by server /// private WebHeaderCollection m_httpResponseHeaders; /// /// Content Length needed for semantics, -1 if chunked /// private long m_contentLength = -1; /// /// The HTTP version for the response. /// private Version m_version; /// /// The status code from the response. /// private int m_statusCode; /// /// the description of the status returned by the server. /// private String m_statusDescription; /// /// Retrieves a response header object. /// /// A WebHeaderCollection that contains the header /// information returned with the response. public override WebHeaderCollection Headers { get { return m_httpResponseHeaders; } } /// /// Gets the length of the content returned by the request. /// /// /// This property contains the value of the Content-Length header /// that is returned with the response. If the Content-Length /// header is not set in the response, this property is set to -1. /// /// The number of bytes returned by the request. Content length /// does not include header information. public override long ContentLength { get { return m_contentLength; } } /// /// TBD /// /// TBD internal long InternalContentLength { set { m_contentLength = value; } } /// /// Gets the method that is used to encode the body of the response. /// /// /// This property contains the value of the Content-Encoding /// header returned with the response; that is, the encoding used for /// the response. /// /// A string that describes the method that is used to encode the /// body of the response. public String ContentEncoding { get { return GetResponseHeader(HttpKnownHeaderNames.ContentEncoding); } } /// /// Gets the content type of the response. /// /// A string that contains the content type of the response. /// /// /// This property contains the value of the Content-Type header /// returned with the response. /// public override string ContentType { get { return GetResponseHeader(HttpKnownHeaderNames.ContentType); } } /// /// Gets the name of the server that sent the response. /// /// A string that contains the name of the server that sent the /// response. public string Server { get { return GetResponseHeader(HttpKnownHeaderNames.Server); } } /// /// Gets the value of the Last-Modified header, which indicates the last /// time the document was modified. /// /// A that contains the date and /// time that the contents of the response were modified. public DateTime LastModified { get { string lastmodHeaderValue = m_httpResponseHeaders[HttpKnownHeaderNames.LastModified]; if (lastmodHeaderValue == null) { return DateTime.Now; } return HttpProtocolUtils.string2date(lastmodHeaderValue); } } /// /// Gets the status of the HTTP response, as a number. /// /// /// For status code values, see . /// /// One of the HttpStatusCode values. public HttpStatusCode StatusCode { get { return (HttpStatusCode)m_statusCode; } } /// /// Gets the status description returned with the response. /// /// A string that describes the status of the response. public string StatusDescription { get { return m_statusDescription; } } /// /// Gets the version of the HTTP protocol that is used in the response. /// /// A Version that contains the HTTP protocol version of /// the response. public Version ProtocolVersion { get { return m_version; } #if DEBUG set { m_version = value; } #endif } /// /// Gets the stream used for reading the body of the response from the /// server. /// /// A network stream to read body of the message. public override Stream GetResponseStream() { Stream retVal = m_responseStream.CloneStream(); m_responseStream.m_dataStart = m_responseStream.m_dataEnd = 0; return retVal; } /// /// Sets the response stream. /// /// /// /// Used internally during creation of HttpWebResponse. /// internal void SetResponseStream(InputNetworkStreamWrapper stream) { m_responseStream = stream; } /// /// Creates WEB response based on information known just after parsing the status line. /// /// Http Verb /// TBD /// Response data /// TBD internal HttpWebResponse(string method, Uri responseUrl, CoreResponseData data, HttpWebRequest httpWebReq) { m_httpWebRequest = httpWebReq; m_method = method; m_url = responseUrl; m_version = data.m_version; m_statusCode = data.m_statusCode; m_statusDescription = data.m_statusDescription; m_httpResponseHeaders = data.m_headers; m_contentLength = data.m_contentLength; } /// /// Gets the contents of a header that was returned with the response. /// /// HTTP header to search for matching header on. /// The matched entry, if found. /// public string GetResponseHeader(string headerName) { string headerValue = m_httpResponseHeaders[headerName]; return ((headerValue == null) ? String.Empty : headerValue); } /// /// Gets the final Response URI, that includes any /// changes that may have transpired from the orginal Request. /// /// A Uri that contains the URI of the Internet resource /// that responded to the request. public override Uri ResponseUri { get { return m_url; } } /// /// Gets the method that is used to return the response. /// /// A string that contains the HTTP method that is used to return /// the response. public string Method { get { return m_method; } } /// /// Closes a response stream, if present. /// /// Not used. protected override void Dispose(bool disposing) { if (m_responseStream != null) { bool closeConnection = true; if (m_httpWebRequest.KeepAlive) { string connValue = null; // Check if server have sent use "Connection:Close" if (m_httpResponseHeaders != null) connValue = m_httpResponseHeaders[HttpKnownHeaderNames.Connection]; // If server had not send this header or value is not "close", then we keep connection. closeConnection = connValue == null || connValue.ToLower() == HttpKnownHeaderValues.close; } // If it is not in the list - Add it if (closeConnection) { // Add new socket and port used to connect to the list of sockets. // Save connected socket and Destination IP End Point, so it can be used next time. // But first we need to validate that this socket is already not in the list. We do not want same socket to be twice in the list. HttpWebRequest.RemoveStreamFromPool(m_responseStream); // Closing connection socket. m_responseStream.Dispose(); } else { m_responseStream.ReleaseStream(); } // Set flag that we already completed work on this stream. m_responseStream = null; } base.Dispose(disposing); } } // class HttpWebResponse } // namespace System.Net ================================================ FILE: Zelig/Zelig/RunTime/Framework/system/System/HTTP/System.Net.IWebProxy.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // namespace System.Net { using System; /// /// Provides the base interface for implementing proxy access for the /// class. /// public interface IWebProxy { /// /// Returns the URI of a proxy. /// /// The destination URI. /// A Uri instance that contains the URI of the proxy /// used to contact . Uri GetProxy(Uri destination); /// /// Indicates whether the proxy should not be used for the specified /// host. /// /// The host to check, to determine whether the proxy /// is needed to access it. /// Whether the proxy should not be used for the specified /// host. bool IsBypassed(Uri host); } } ================================================ FILE: Zelig/Zelig/RunTime/Framework/system/System/HTTP/System.Net.IWebRequestCreate.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // namespace System.Net { /// /// The interface for creating class /// objects. /// public interface IWebRequestCreate { /// /// Creates an instance of a class derived from /// WebRequest. /// /// The URI for initialization of the class that is /// derived from WebRequest. /// /// An instance of the class that is derived from /// WebRequest. /// WebRequest Create(Uri uri); } // interface IWebRequestCreate } // namespace System.Net ================================================ FILE: Zelig/Zelig/RunTime/Framework/system/System/HTTP/System.Net.Internal.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // namespace System.Net { using System.Collections; using System.Globalization; using System.IO; using System.Net.Sockets; using System.Runtime.InteropServices; using System.Runtime.CompilerServices; using System.Text; using System.Threading; internal class WebRequestPrefixElement { public string Prefix; public IWebRequestCreate Creator; public WebRequestPrefixElement(string P, IWebRequestCreate C) { Prefix = P; Creator = C; } } // class PrefixListElement /// /// Used during parsing to capture all the information contained in the http /// status line and headers. /// internal class CoreResponseData { // Basic response information. internal int m_statusCode; internal string m_statusDescription; internal WebHeaderCollection m_headers; internal Version m_version; // Variables for the end of entity mark. internal bool m_chunked; internal long m_contentLength; internal bool m_shouldClose; // The web status. internal WebExceptionStatus m_status; internal string m_exceptionMessage; internal Exception m_innerException; } /// /// Contains known HTTP header names. /// public class HttpKnownHeaderNames { /// The Cache-Control HTTP header. public const string CacheControl = "Cache-Control"; /// The Connection HTTP header. public const string Connection = "Connection"; /// The Date HTTP header. public const string Date = "Date"; /// The Keep-Alive HTTP header. public const string KeepAlive = "Keep-Alive"; /// The Pragma HTTP header. public const string Pragma = "Pragma"; /// The Proxy-Connection HTTP header. public const string ProxyConnection = "Proxy-Connection"; /// The Trailer HTTP header. public const string Trailer = "Trailer"; /// The Transfer-Encoding HTTP header. public const string TransferEncoding = "Transfer-Encoding"; /// The Upgrade HTTP header. public const string Upgrade = "Upgrade"; /// The Via HTTP header. public const string Via = "Via"; /// The Warning HTTP header. public const string Warning = "Warning"; /// The Content-Length HTTP header. public const string ContentLength = "Content-Length"; /// The Content-Type HTTP header. public const string ContentType = "Content-Type"; /// The Content-ID HTTP header. public const string ContentID = "Content-ID"; /// The Content-Encoding HTTP header. public const string ContentEncoding = "Content-Encoding"; /// The Content-Transfer-Encoding HTTP header. public const string ContentTransferEncoding = "Content-Transfer-Encoding"; /// The Content-Language HTTP header. public const string ContentLanguage = "Content-Language"; /// The Content-Location HTTP header. public const string ContentLocation = "Content-Location"; /// The Content-Range HTTP header. public const string ContentRange = "Content-Range"; /// The Expires HTTP header. public const string Expires = "Expires"; /// The Last-Modified HTTP header. public const string LastModified = "Last-Modified"; /// The Age HTTP header. public const string Age = "Age"; /// The Location HTTP header. public const string Location = "Location"; /// The Proxy-Authenticate HTTP header. public const string ProxyAuthenticate = "Proxy-Authenticate"; /// The Retry-After HTTP header. public const string RetryAfter = "Retry-After"; /// The Server HTTP header. public const string Server = "Server"; /// The Set-Cookie HTTP header. public const string SetCookie = "Set-Cookie"; /// The Set-Cookie2 HTTP header. public const string SetCookie2 = "Set-Cookie2"; /// The Vary HTTP header. public const string Vary = "Vary"; /// The WWW-Authenticate HTTP header. public const string WWWAuthenticate = "WWW-Authenticate"; /// The Accept HTTP header. public const string Accept = "Accept"; /// The Accept-Charset HTTP header. public const string AcceptCharset = "Accept-Charset"; /// The Accept-Encoding HTTP header. public const string AcceptEncoding = "Accept-Encoding"; /// The Accept-Language HTTP header. public const string AcceptLanguage = "Accept-Language"; /// The Authorization HTTP header. public const string Authorization = "Authorization"; /// The Cookie HTTP header. public const string Cookie = "Cookie"; /// The Cookie2 HTTP header. public const string Cookie2 = "Cookie2"; /// The Expect HTTP header. public const string Expect = "Expect"; /// The From HTTP header. public const string From = "From"; /// The Host HTTP header. public const string Host = "Host"; /// The If-Match HTTP header. public const string IfMatch = "If-Match"; /// The If-Modified-Since HTTP header. public const string IfModifiedSince = "If-Modified-Since"; /// The If-None-Match HTTP header. public const string IfNoneMatch = "If-None-Match"; /// The If-Range HTTP header. public const string IfRange = "If-Range"; /// The If-Unmodified-Since HTTP header. public const string IfUnmodifiedSince = "If-Unmodified-Since"; /// The Max-Forwards HTTP header. public const string MaxForwards = "Max-Forwards"; /// The Proxy-Authorization HTTP header. public const string ProxyAuthorization = "Proxy-Authorization"; /// The Referer HTTP header. public const string Referer = "Referer"; /// The Range HTTP header. public const string Range = "Range"; /// The User-Agent HTTP header. public const string UserAgent = "User-Agent"; /// The Content-MD5 HTTP header. public const string ContentMD5 = "Content-MD5"; /// The ETag HTTP header. public const string ETag = "ETag"; /// The TE HTTP header. public const string TE = "TE"; /// The Allow HTTP header. public const string Allow = "Allow"; /// The Accept-Ranges HTTP header. public const string AcceptRanges = "Accept-Ranges"; /// The MIME-Version HTTP header. public const string MimeVersion = "MIME-Version"; } /// /// TBD /// internal class HttpKnownHeaderValues { /// TBD public const string close = "close"; } /* File: httpreq.cs Summary: Basic HTTP Protocol support for HttpWeb request Class. Contains the implimention of various HTTP primitives. Classes: HttpWebReques Functions: ---------------------------------------------------------------------------- This file is part of the Microsoft COM+ Netclasses. Copyright (C) 1998-1999 Microsoft Corporation. All rights reserved. ==========================================================================+*/ // - seperate HTTP header names/header data // - improve/check var/func naming // - stress parsering cases // - Chunked transfer needs a better algorithm, to prevent over copying // - keep-alive /// /// Represents the method that notifies callers when a continue response is /// received by the client. /// /// The numeric value of the HTTP status from the /// server. /// The headers returned with the 100-continue /// response from the server. public delegate void HttpContinueDelegate(int StatusCode, WebHeaderCollection httpHeaders); /// /// Controls the way an entity body is posted. /// internal enum HttpWriteMode { Chunked = 1, Write = 2, None = 0, Prebuffer = 3 } /// /// Known Verbs are verbs that require special handling. /// internal class KnownVerbs { // This is a placeholder for Verb properties. The following two bools can most likely be // combined into a single Enum type. And the Verb can be incorporated. internal struct HttpVerb { // require content body to be sent internal bool m_RequireContentBody; // not allowed to send content body internal bool m_ContentBodyNotAllowed; // special semantics for a connect request internal bool m_ConnectRequest; // response will not have content body internal bool m_ExpectNoContentResponse; /* * XXX * * Wed 10/10/2001 * This should only be used by KnownVerbs * */ internal string m_name; internal HttpVerb(string name, bool RequireContentBody, bool ContentBodyNotAllowed, bool ConnectRequest, bool ExpectNoContentResponse) { m_name = name; m_RequireContentBody = RequireContentBody; m_ContentBodyNotAllowed = ContentBodyNotAllowed; m_ConnectRequest = ConnectRequest; m_ExpectNoContentResponse = ExpectNoContentResponse; } } // Force an an init, before we use them private static HttpVerb[] m_knownVerbs; static KnownVerbs() { m_knownVerbs = new HttpVerb[5]; m_knownVerbs[0] = new HttpVerb("GET", false, true, false, false); m_knownVerbs[1] = new HttpVerb("POST", true, false, false, false); m_knownVerbs[2] = new HttpVerb("HEAD", false, true, false, true); m_knownVerbs[3] = new HttpVerb("PUT", true, false, false, false); /* * XXX * * Mon 02/25/2002 * I've changed this from the desktop. There is no entity response * in a connect request. It won't be there, and don't close it. * */ m_knownVerbs[4] = new HttpVerb("CONNECT", false, true, true, true); // default Verb DefaultVerb = new HttpVerb("", false, false, false, false); } // default verb, contains default properties for an unidentifable verb. private static HttpVerb DefaultVerb; internal static HttpVerb GetHttpVerbType(String name) { for (int i = 0; i < m_knownVerbs.Length; ++i) { HttpVerb v = m_knownVerbs[i]; if (0 == string.Compare(v.m_name, name)) return v; } return DefaultVerb; } } /// /// A collection of utility functions for HTTP usage. /// internal class HttpProtocolUtils { private HttpProtocolUtils() { } /// /// Parse String to DateTime format. /// /// String with date. /// DateTime object that represent the same value as in input string. internal static DateTime string2date(String S) { DateTime dtOut; if (HttpDateParse.ParseHttpDate( S, out dtOut)) { return dtOut; } else { throw new Exception("Invalid Date in HTTP header"); } } } } // namespace System.Net ================================================ FILE: Zelig/Zelig/RunTime/Framework/system/System/HTTP/System.Net.NetworkCredential.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // namespace System.Net { /// /// Class that keeps user name and password. /// public class NetworkCredential { private string m_userName; private string m_password; private AuthenticationType m_authenticationType; /// /// Construct class with empty user name and password /// public NetworkCredential() { } /// /// Constructs credientials and initializes them by provided user name and pssword /// /// /// public NetworkCredential(string userName, string password) : this(userName, password, AuthenticationType.Basic) { } /// /// Initializes a new instance of the class. /// /// Name of the user. /// The password. /// Type of the authentication. public NetworkCredential(string userName, string password, AuthenticationType authenticationType) { UserName = userName; Password = password; AuthenticationType = authenticationType; } /// /// Set or get user name. /// public string UserName { get { return m_userName; } set { m_userName = value; } } /// /// Set or get password. /// public string Password { get { return m_password; } set { m_password = value; } } /// /// Gets or sets the type of the authentication. /// /// The type of the authentication. public AuthenticationType AuthenticationType { get { return m_authenticationType; } set { m_authenticationType = value; } } } // class NetworkCredential } // namespace System.Net ================================================ FILE: Zelig/Zelig/RunTime/Framework/system/System/HTTP/System.Net.ProtocolViolationException.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // namespace System.Net { /// /// The exception that is thrown when an error is made while using a network /// protocol. /// public class ProtocolViolationException : InvalidOperationException { // constructors /// /// Initializes a new instance of the /// ProtocolViolationException class. /// public ProtocolViolationException() { } /// /// Initializes a new instance of the /// ProtocolViolationException class with the /// specified message. /// /// The error message string. public ProtocolViolationException(string message) : base(message) { } } // class ProtocolViolationException } // namespace System.Net ================================================ FILE: Zelig/Zelig/RunTime/Framework/system/System/HTTP/System.Net.WebException.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // namespace System.Net { using System; /*++ Copyright (c) 2000 Microsoft Corporation Abstract: Contains the defintion for the WebException object. This is a subclass of Exception that contains a WebExceptionStatus and possible a reference to a WebResponse. Original Author: Henry Sanders (henrysa) 03-Feb-2000 Environment: COM+ Managed Code Revision History: 03-Feb-2000 henrysa Created * Feb 2009 - Updated for Micro Framework. --*/ /// /// Defines the exception that is thrown by /// instances when an error occurs. /// /// /// This class is a subclass of InvalidOperationException /// that contains a WebExceptionStatus and possibly a /// reference to a WebResponse. The /// WebResponse is only present if there is a response /// from the remote server. /// public class WebException : InvalidOperationException { private WebExceptionStatus m_Status; private WebResponse m_Response; /// /// The default constructor. /// public WebException() { } /// /// Constructs a WebException based on the specified /// message string. /// /// The message string for the exception. public WebException(string message) : base(message) { } /// /// Constructs a WebException based on the specified /// message string and inner exception. /// /// The message string for the exception. /// The exception that caused this /// exception. public WebException(string message, Exception innerException) : base(message, innerException) { } /// /// Constructs a WebException based on the specified /// message string and WebExceptionStatus. /// /// The message string for the exception. /// The network status of the exception. public WebException(string message, WebExceptionStatus status) : base(message) { m_Status = status; } /// /// Constructs a WebException based on the specified /// message string, inner exception, /// , and /// . /// /// Message string for exception. /// The exception that caused this exception. /// /// The network status of the exception. /// The WebResponse we have. /// public WebException(string message, Exception inner, WebExceptionStatus status, WebResponse response) : base(message, inner) { m_Status = status; m_Response = response; } /// /// Gets the WebExceptionStatus code. /// /// One of the WebExceptionStatus values. public WebExceptionStatus Status { get { return m_Status; } } /// /// Gets the response that the remote host returned. /// /// If a response is available from the Internet resource, a /// WebResponse instance that contains the error /// response from an Internet resource; otherwise, /// null. public WebResponse Response { get { return m_Response; } } }; // class WebException } // namespace System.Net ================================================ FILE: Zelig/Zelig/RunTime/Framework/system/System/HTTP/System.Net.WebHeaders.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // [assembly: System.Runtime.CompilerServices.InternalsVisibleTo("Microsoft.SPOT.Net.LiveIdAuthentication")] //--// namespace System.Net { using System.Collections; using System.Text; /// /// Contains a name/value pair that is used in an HTTP header. /// internal class HeaderValuePair { public HeaderValuePair(string hd, string val) { headerAsKey = hd; value = val; } // Pair of value and header. public string headerAsKey; public string value; } /// /// Keeps an array of name/value pairs that are in HTTP headers. /// internal class HeaderValueCollection : ArrayList { /// /// Searches in the collection for the header with the same name. /// /// The header to seach for. /// The name/value pair if found; otherwise, null. /// /// Header comparison is case-insensitive. /// /// In the desktop and Compact Framework versions of .NET, the array is /// represented by a hash table. /// /// public HeaderValuePair GetValuePair(string header) { string lowerHeader = header.ToLower(); for (int i = 0; i < this.Count; i++) { if (((HeaderValuePair)this[i]).headerAsKey.ToLower() == lowerHeader) { return (HeaderValuePair)this[i]; } } return null; } /// /// Adds a header and a value for the header into the collection. /// /// String for header /// String for value /// /// If the specified header is already present, the value is appended to /// that header. /// public void Add(string header, string value) { // Checks is we already have the header. HeaderValuePair pair = GetValuePair(header); // If found, adds valus to existing valies. if (pair != null) { pair.value += "," + value; } else // if not found - then we add it. { base.Add(new HeaderValuePair(header, value)); } } /// /// Replaces the previous values for the header with the new value. /// /// Header name /// New value public void Set(string header, string value) { // Remove previous header. RemoveHeader(header); // Add new value(s) base.Add(new HeaderValuePair(header, value)); } /// /// Removes the header that has the specified name. /// /// /// public bool RemoveHeader(string header) { int totalElemCount = Count; string lowerHeader = header.ToLower(); for (int i = 0; i < totalElemCount; i++) { // If name matches - remove this header. if (((HeaderValuePair)this[i]).headerAsKey.ToLower() == lowerHeader) { RemoveAt(i); return true; } } return false; } } /// /// Contains protocol headers associated with a request or response. /// Manages name-value pairs for HTTP headers. /// /// /// This class includes additional methods, including HTTP parsing of a /// collection into a buffer that can be sent. /// /// Headers are validated when attempting to add them. /// /// public class WebHeaderCollection { /// /// Data and constants. /// private const int ApproxAveHeaderLineSize = 30; private static readonly HeaderInfoTable HInfo = new HeaderInfoTable(); /// /// Array list of headers and values /// private HeaderValueCollection head_val_coll = new HeaderValueCollection(); /// /// true if this object is created for internal use, in this case /// we turn on checking when adding special headers. /// private bool m_IsHttpWebHeaderObject = false; /// /// Adds header name/value pair to collection. Does not check if /// multiple values are allowed. /// /// Name in header /// Value in header internal void AddWithoutValidate(string headerName, string headerValue) { headerName = CheckBadChars(headerName, false); headerValue = CheckBadChars(headerValue, true); head_val_coll.Add(headerName, headerValue); } /// /// Adds header name/value pair to collection. /// If multi value allowed for this header name - adds new one /// If multi value is not allowed, replace the old value with new one /// /// Name in header /// Value in header internal void SetAddVerified(string name, string value) { if (HInfo[name].AllowMultiValues) { head_val_coll.Add(name, value); } else { head_val_coll.Set(name, value); } } // The below 3 methods are for fast headers manipulation, bypassing all // the checks. /// /// Just internal fast add. /// /// /// internal void AddInternal(string headerName, string headerValue) { head_val_coll.Add(headerName, headerValue); } /// /// Internal fast channge /// /// /// internal void ChangeInternal(string name, string value) { head_val_coll.Set(name, value); } /// /// Internal remove of header. /// /// internal void RemoveInternal(string name) { head_val_coll.RemoveHeader(name); } /// /// Changes to new value. Check for illegal characters first. /// /// /// internal void CheckUpdate(string name, string value) { value = CheckBadChars(value, true); ChangeInternal(name, value); } /// /// Throws an error if invalid chars are found in the header name or /// value. /// /// The header name or header value string to /// check. /// Whether the name parameter is a header /// name or a header value. /// internal static string CheckBadChars(string name, bool isHeaderValue) { if (name == null || name.Length == 0) { // empty name is invlaid if (!isHeaderValue) { throw new ArgumentException(); } // empty value is OK return string.Empty; } if (isHeaderValue) { // VALUE check // Trim spaces from both ends name = name.Trim(); // First, check for correctly formed multi-line value // Second, check for absence of CTL characters bool crlf = false; for (int i = 0; i < name.Length; ++i) { char c = name[i]; if (c == 127 || (c < ' ' && !(c == '\t' || c == '\r' || c == '\n'))) { throw new ArgumentException(); } if (crlf) { if (!(c == ' ' || c == '\t')) { throw new ArgumentException(); } crlf = false; } else { if (c == '\n') { crlf = true; } } } } else { // NAME check // First, check for absence of separators and spaces if (name.IndexOfAny(ValidationHelper.InvalidParamChars) != -1) { throw new ArgumentException(); } // Second, check for non CTL ASCII-7 characters (32-126) if (ContainsNonAsciiChars(name)) { throw new ArgumentException(); } } return name; } internal static bool IsValidToken(string token) { return (token.Length > 0) && (token.IndexOfAny(ValidationHelper.InvalidParamChars) == -1) && !ContainsNonAsciiChars(token); } internal static bool ContainsNonAsciiChars(string token) { for (int i = 0; i < token.Length; ++i) { if ((token[i] < 0x20) || (token[i] > 0x7e)) { return true; } } return false; } /// /// Throws an exception if the user passed in a reserved string as the /// header name. /// /// internal void ThrowOnRestrictedHeader(string headerName) { if (m_IsHttpWebHeaderObject && HInfo[headerName].IsRestricted) { throw new ArgumentException("Cannot update restricted header: " + headerName); } } // Our Public METHOD set, most are inherited from NameValueCollection, // not all methods from NameValueCollection are listed, even though // usable. // // This includes: // Add(name, value) // Add(header) // this[name] {set, get} // Remove(name), returns bool // Remove(name), returns void // Set(name, value) // ToString() // // SplitValue(name, value) // ToByteArray() // ParseHeaders(char [], ...) // ParseHeaders(byte [], ...) /// /// Inserts a header with the specified name and value into the /// collection. /// /// The name of the header that is being added to the /// collection. /// The content of the header that is being added /// (its header-value). If a header with the specified name already /// exists, this value is concatenated onto the existing header. /// /// If a header with the specified name already exists, the header that /// is being added is concatenated onto the existing header. /// /// Throws an exception if the specified header name is the name of a /// special header. /// /// public void Add(string name, string value) { // Special headers are listed in the RestrictedHeaders object. name = CheckBadChars(name, false); ThrowOnRestrictedHeader(name); value = CheckBadChars(value, true); head_val_coll.Add(name, value); } /// /// Inserts a new header into the collection. /// /// A header name/value pair, in the format /// "myHeaderName:myValue". /// /// This method expects a string with the format "myName:myValue", and /// parses the two parts out. /// /// If a header with the specified name already exists, the header that /// is being added is concatenated onto the existing header. /// /// /// Throws an exception if the specified header name is the name of a /// special header. /// /// public void Add(string header) { // Special headers are listed in the RestrictedHeaders object. if (ValidationHelper.IsBlankString(header)) { throw new ArgumentNullException(); } int colpos = header.IndexOf(':'); // check for badly formed header passed in if (colpos < 0) { throw new ArgumentException(); } string name = header.Substring(0, colpos); string value = header.Substring(colpos + 1); name = CheckBadChars(name, false); ThrowOnRestrictedHeader(name); value = CheckBadChars(value, true); head_val_coll.Add(name, value); } /// /// Sets the specified header to the specified value. /// /// The header to set. /// The content of the header to set. /// /// Includes validation. /// Throws an exception if the specified header name is the name of a /// special header. /// public void Set(String name, String value) { // Special headers are listed in the RestrictedHeaders object. if (ValidationHelper.IsBlankString(name)) { throw new ArgumentNullException("name"); } name = CheckBadChars(name, false); ThrowOnRestrictedHeader(name); value = CheckBadChars(value, true); head_val_coll.Set(name, value); } /// /// Removes the specified header from the collection. /// /// The name of the header to remove. /// /// Throws an exception if the specified header name is the name of a /// special header. /// public void Remove(string name) { // Special headers are listed in the RestrictedHeaders object. if (ValidationHelper.IsBlankString(name)) { throw new ArgumentNullException("name"); // netcf.20937 } ThrowOnRestrictedHeader(name); name = CheckBadChars(name, false); head_val_coll.RemoveHeader(name); } /// /// Returns the values for the specified header name. /// /// The name of the header. /// An array of parsed string objects. /// /// Takes a header name and returns a string array representing /// the individual values for that header. For example, if the headers /// contain the following line: /// /// Accept: text/plain, text/html /// /// then GetValues("Accept") returns an array of /// two strings: "text/plain" and "text/html". /// public string[] GetValues(string header) { // Get the value pair for the header. HeaderInfo Info = HInfo[header]; HeaderValuePair pair = head_val_coll.GetValuePair(header); // If header not present or value string not present or empty - // return null. if (pair == null || pair.value == null || pair.value.Length == 0) { return null; } // Header present. Parse the value string. There is non-empty value // string. if (Info == null || !Info.AllowMultiValues) { string[] retVal = new string[1]; retVal[0] = pair.value; return retVal; } // Multivalue header return Info.Parser(pair.value); } /// /// Generates a string representation of the headers, that is ready to /// be sent except for it being in String format. /// /// A string representation of the headers. /// /// The format looks like the following: /// /// Header-Name: Header-Value\r\n /// Header-Name2: Header-Value2\r\n /// ... /// Header-NameN: Header-ValueN\r\n /// \r\n /// /// public override string ToString() { // Iterates on all headers and add them line by line in form: // header: value string retString = ""; for (int i = 0; i < head_val_coll.Count; i++) { // Try to be most efficient by calling Concat. // There is no Concat with 5 arguments. retString = String.Concat(retString, ((HeaderValuePair)head_val_coll[i]).headerAsKey, ": ", ((HeaderValuePair)head_val_coll[i]).value); retString = String.Concat(retString, "\r\n"); } // Adds extra line return at the end of headers. retString = String.Concat(retString, "\r\n"); // Return concatinated headers and return retString; } /// /// Generates a byte array representation of the headers, that is ready /// to be sent. /// /// An array of bytes. /// /// This method serializes the headers into a byte array that can be /// sent over the network. The format looks like: /// /// Header-Name1: Header-Value1\r\n /// Header-Name2: Header-Value2\r\n /// ... /// Header-NameN: Header-ValueN\r\n /// \r\n /// /// public byte[] ToByteArray() { // Performance Note: We aren't doing a single copy/covert run, // because (according to Demitry), it's cheaper to copy the headers // twice than to call the UNICODE-to-ANSI conversion code many // times. (The code before used to know the size of the output.) // Make sure the buffer is big enough. string tempStr = ToString(); // Use the String of headers, convert to Char Array, then convert to // Bytes, serializing finally into the buffer, along the way. byte[] buffer = Encoding.UTF8.GetBytes(tempStr); return buffer; } /// /// Tests whether the specified HTTP header can be set. /// /// Name for the header. /// /// /// Throws an exception if the header name is blank, contains illegal /// characters, or contains characters that are reserved by the HTTP /// protocol. /// public static bool IsRestricted(string headerName) { if (ValidationHelper.IsBlankString(headerName)) { throw new ArgumentNullException("headerName"); } return HInfo[CheckBadChars(headerName, false)].IsRestricted; } /// /// Creates an empty collection of WEB headers. /// public WebHeaderCollection() { } /// /// Private constructor, called internally. /// /// Whether this is an HTTP headers /// object. internal WebHeaderCollection(bool internalCreate) { m_IsHttpWebHeaderObject = internalCreate; } /// /// Calculates the number of bytes needed to store the headers. /// /// internal int byteLength() { int ret = 0; // Runs for all collection and adds length of header and value // strings for (int i = 0; i < head_val_coll.Count; i++) { ret += ((HeaderValuePair)head_val_coll[i]).headerAsKey.Length; ret += 2; //for the ": " ret += ((HeaderValuePair)head_val_coll[i]).value.Length; ret += 2; //for the "\r\n" } ret += 2; //for the final "\r\n" return ret; } /// /// Returns the string value for the header. /// /// The name of the header. /// A string containing the value. If no value is present, /// returns null. public string this[string header] { get { HeaderValuePair pair = head_val_coll.GetValuePair(header); // If header is not present, then pair is null. Return null // string if (pair == null) { return null; } // Pair was found. Return the value string of it return pair.value; } } /// /// Gets the number of headers in the collection. /// /// An Int32 indicating the number of headers in a /// request. public int Count { get { return head_val_coll.Count; } } /// /// Gets all header names (keys) in the collection. /// /// An array of type String containing all header names in /// a Web request. public string[] AllKeys { get { ArrayList tempCollection = new ArrayList(); for (int i = 0; i < head_val_coll.Count; i++) { tempCollection.Add(((HeaderValuePair)head_val_coll[i]).headerAsKey); } string[] stringArray = new string[tempCollection.Count]; return (string[])tempCollection.ToArray(typeof(string)); } } /// /// Copies the headers into the byte array starting at bytes[offset]. /// If the byte array is too small to hold the data, an /// ArgumentException is thrown. /// /// The array to copy. /// The offset to the beginning of the data to be /// copied into the WEB Headers collection. /// How many bytes were copied. internal int copyTo(byte[] bytes, int offset) { // Create array representing the headers byte[] headersBytes = ToByteArray(); // Copy to destination headersBytes.CopyTo(bytes, offset); // Return count of bytes copied. return headersBytes.Length; } }; // class WebHeaderCollection } // namespace System.Net ================================================ FILE: Zelig/Zelig/RunTime/Framework/system/System/HTTP/System.Net.WebProxy.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // namespace System.Net { /// /// Contains HTTP proxy settings for the /// class. /// public class WebProxy : IWebProxy { // true means DO NOT use proxy on local connections. // false means use proxy for local network connections. private bool m_bypassOnLocal; private Uri m_proxyAddress; // Uri of proxy itself /// /// Initializes an empty instance of the WebProxy class. /// /// /// The URI of the proxy can be set later, using the /// property. /// public WebProxy() : this((Uri)null, false) { } /// /// Initializes a new instance of the WebProxy class /// from the specified instance. /// /// A Uri instance that /// contains the address of the proxy server. public WebProxy(Uri Address) : this(Address, false) { } /// /// Initializes a new instance of the WebProxy class /// with the specified instance and bypass /// setting. /// /// A Uri instance that /// contains the address of the proxy server. /// Indicates whether to bypass the WebProxy /// on local network addresses. public WebProxy(Uri Address, bool BypassOnLocal) { m_proxyAddress = Address; m_bypassOnLocal = BypassOnLocal; } /// /// Initializes a new instance of the WebProxy class /// with the specified host and port number. /// /// The name of the proxy host, such as: contoso /// The port number on the host to use, such as: /// 80 /// /// The WebProxy instance is initialized with the /// property set /// to a instance of the form: http://Host:Port /// public WebProxy(string Host, int Port) : this(new Uri("http://" + Host + ":" + Port.ToString()), false) { } /// /// Initializes a new instance of the WebProxy class /// with the specified URI. /// /// The URI address of the proxy server. /// /// The WebProxy instance is initialized with the /// property set to a /// instance containing the /// Address string. /// /// For the new instance of the WebProxy class, /// "Bypass on local addresses" is set to false. /// /// public WebProxy(string Address) : this(CreateProxyUri(Address), false) { } /// /// Initializes a new instance of the WebProxy class /// with the specified URI and bypass setting. /// /// The URI of the proxy server. /// Indicates whether to bypass the proxy /// when accessing local addresses. public WebProxy(string Address, bool BypassOnLocal) : this(CreateProxyUri(Address), BypassOnLocal) { } /// /// Gets or sets the address of the proxy server. /// /// A instance that contains the address /// of the proxy server. public Uri Address { get { return m_proxyAddress; } set { m_proxyAddress = value; } } /// /// Gets or sets whether to bypass the proxy server for local /// addresses. /// true to bypass the proxy server for local /// addresses; otherwise, false. public bool BypassProxyOnLocal { get { return m_bypassOnLocal; } set { m_bypassOnLocal = value; } } /// /// Returns the proxied URI for a request. /// /// The Uri instance of the /// requested Internet resource. /// The Uri instance of the Internet /// resource, if the resource is on the bypass list; otherwise, the /// Uri instance of the proxy. /// public Uri GetProxy(Uri destination) { if (IsBypassed(destination)) { return destination; } Uri proxy = m_proxyAddress; if (proxy != null) { return proxy; } return destination; } /// /// Maps a string to a Uri. /// /// The Url for creation of the Uri. /// The new Uri corresponding to the Url. private static Uri CreateProxyUri(string Address) { if (Address == null) { return null; } // Original code was IndexOf("://", StringComparison.Ordinal), // changed to IndexOf("://") we only support ASCII in .NET MF. if (Address.IndexOf("://") == -1) { Address = "http://" + Address; } return new Uri(Address); } /// /// Checks whether the supplied Uri represents a local address. /// /// The Uri to check. /// trueif the address is local; otherwise, /// false. private bool IsLocal(Uri host) { string hostString = host.Host; int dot = hostString.IndexOf('.'); if (dot == -1) { return true; } return false; } /// /// Indicates whether to use the proxy server for the specified host. /// /// The Uri instance of the host /// to check for proxy use. /// true if the proxy server should not be /// used for the host; otherwise, false. public bool IsBypassed(Uri host) { if (host.IsLoopback) { return true; // bypass localhost from using a proxy. } if ((m_proxyAddress == null) || (m_bypassOnLocal && IsLocal(host))) { return true; // bypass when non .'s and no proxy on local } else { return false; } } }; // class WebProxy } // namespace System.Net ================================================ FILE: Zelig/Zelig/RunTime/Framework/system/System/HTTP/System.Net.WebRequest.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // namespace System.Net { using System; using System.Collections; using System.IO; /// /// Makes a request to a Uniform Resource Identifier (URI). This is an /// abstract class. /// /// /// This is the base class of all Web resource/protocol objects. This class /// provides common methods, data and proprties for making the top-level /// request. /// public abstract class WebRequest : MarshalByRefObject, IDisposable { internal const int DefaultTimeout = 100000; // default timeout is 100 seconds // (ASP .NET is 90 seconds) // Lock to syncronize update of s_PrefixList private static object g_listLock = new object(); // List of WebRequestPrefixElement that keeps prefix ( string ) and // IWebRequestCreate private static ArrayList s_PrefixList = new ArrayList(); private static IWebProxy s_defaultProxy = null; /// /// Initializes a new instance of the /// class. /// protected WebRequest() { } ~WebRequest() { Dispose(false); } public void Dispose() { Dispose(true); GC.SuppressFinalize(this); } protected virtual void Dispose(bool disposing) { } /// /// When overridden in a descendant class, gets or sets the protocol /// method to use in this request. /// /// /// This property gets or sets the verb to this request, such as GET or /// POST for HTTP. /// /// The protocol method to use in this request. public virtual string Method { get { throw new NotSupportedException(); } set { throw new NotSupportedException(); } } /// /// When overridden in a descendant class, gets the URI of the Internet /// resource associated with the request. /// /// /// This property is read-only, since the Uri can be specified only on /// creation. /// /// A Uri representing the resource associated /// with the request. /// public virtual Uri RequestUri { // read-only get { throw new NotSupportedException(); } } /// /// When overridden in a descendant class, gets or sets the name of the /// connection group for the request. /// /// /// This property serves as a way of grouping connections. /// /// The name of the connection group for the request. public virtual string ConnectionGroupName { get { throw new NotSupportedException(); } set { throw new NotSupportedException(); } } /// /// When overridden in a descendant class, gets or sets the collection /// of header name/value pairs associated with the request. /// /// A WebHeaderCollection containing the /// header name/value pairs associated with this request. public virtual WebHeaderCollection Headers { // read-only get { throw new NotSupportedException(); } set { throw new NotSupportedException(); } } /// /// When overridden in a descendant class, gets or sets the content /// length of the request data being sent. /// /// /// The content length is the length of the message with the verb. /// It is useful only with verbs that actually support a message, such /// as POST; it is not used for the GET verb. /// /// The number of bytes of request data being sent. public virtual long ContentLength { get { throw new NotSupportedException(); } set { throw new NotSupportedException(); } } /// /// When overridden in a descendant class, gets or sets the content type /// of the request data being sent. /// /// /// The content length is the length of the message with the verb. /// It is useful only with verbs that actually support a message, such /// as POST; it is not used for the GET verb. /// /// The content type of the request data. public virtual string ContentType { get { throw new NotSupportedException(); } set { throw new NotSupportedException(); } } /// /// Gets or sets the length of time, in milliseconds, before the request /// times out. /// /// The length of time, in milliseconds, until the request times /// out, or the value Timeout.Infinite to indicate that the request does /// not time out. The default value is defined by the descendant /// class. public virtual int Timeout { get { throw new NotSupportedException(); } set { throw new NotSupportedException(); } } /// /// Gets or sets the global HTTP proxy. /// The DefaultWebProxy property determines the default proxy that all WebRequest instances use if the request /// supports proxies and no proxy is set explicitly using the Proxy property. Proxies are currently supported /// by HttpWebRequest. /// public static IWebProxy DefaultWebProxy { get { return s_defaultProxy; } set { s_defaultProxy = value; } } /// /// When overridden in a descendant class, gets or sets the network /// proxy to use to access this Internet resource. /// /// The IWebProxy to use to access the /// Internet resource. public virtual IWebProxy Proxy { get { throw new NotSupportedException(); } set { throw new NotSupportedException(); } } /// /// When overridden in a descendant class, returns a /// Stream for writing data to the Internet resource. /// /// A Stream for writing data to the /// Internet resource. public virtual Stream GetRequestStream() { // DataStream may need to be extended to URLDataStream or somesuch. // We might need to be able to get the data available. This should // be a method of the stream, not of the net classes. Also, we need // to know whether the stream is seekable. Only streams via cache // and via socket with Content-Length are seekable. throw new NotSupportedException(); } /// /// When overridden in a descendant class, returns a response to an /// Internet request. /// /// A WebResponse containing the response to /// the Internet request. public virtual WebResponse GetResponse() { throw new NotSupportedException(); } /// /// Initializes a new WebRequest instance for the /// specified URI scheme, such as http://, https://, or file://. /// /// The URI that identifies the Internet /// resource. /// Newly created WebRequest. /// A WebRequest descendant for the specific URI scheme. /// /// /// This is the main creation routine. The specified Uri is looked up /// in the prefix match table, and the appropriate handler is invoked to /// create the object. /// public static WebRequest Create(string requestUriString) { return CreateInternal(new Uri(requestUriString)); } /// /// Creates a WebRequest. /// /// A containing the /// URI of the requested resource. /// A WebRequest descendant for the specified /// URI scheme. /// /// This is the main creation routine. The specified Uri is looked up /// in the prefix match table, and the appropriate handler is invoked to /// create the object. /// public static WebRequest Create(Uri requestUri) { return CreateInternal(requestUri); } /// /// Registers a WebRequest descendant for the /// specified URI. /// /// The complete URI or URI prefix that the /// WebRequest descendant services. /// The create method that the /// WebRequest calls to create the /// WebRequest descendant. /// true. public static bool RegisterPrefix(string prefix, IWebRequestCreate creator) { if (prefix == null || creator == null) { throw new ArgumentNullException(); } // Changes prefix to lower becuase it is case insensitive. prefix = prefix.ToLower(); lock (g_listLock) { // Iterate over list of prefixes and checks if this one is // already present. for (int i = 0; i < s_PrefixList.Count; i++) { if (((WebRequestPrefixElement)s_PrefixList[i]).Prefix == prefix) { return false; } } // This is a new prefix, add it. s_PrefixList.Add(new WebRequestPrefixElement(prefix, creator)); } return true; } private static int ComparePrefixString(string Url, string prefix, int prefixLen) { for (int i = 0; i < prefixLen; i++) { if (Url[i] != prefix[i]) { return Url[i] < prefix[i] ? -1 : 1; } } // Actually the URL starts by prefix. return 0; } private static WebRequest CreateInternal(Uri requestUri) { if (requestUri == null) { throw new ArgumentNullException(); } HttpWebRequest.Initialize( ); // Makes LookupUri lowercase since we need case-insensitive compare // with prefix string lookupUri = requestUri.AbsoluteUri.ToLower(); int lookupUriLent = lookupUri.Length; // Walk down the list of prefixes. int prefixListCount = s_PrefixList.Count; for (int i = 0; i < prefixListCount; i++) { WebRequestPrefixElement Current = (WebRequestPrefixElement)s_PrefixList[i]; // See if this prefix is short enough. int prefixLen = Current.Prefix.Length; if (lookupUriLent >= prefixLen) { // It is. See if these match. if (ComparePrefixString(lookupUri, Current.Prefix, prefixLen) == 0) { return Current.Creator.Create(requestUri); } } } throw new NotSupportedException(); } } // class WebRequest } // namespace System.Net ================================================ FILE: Zelig/Zelig/RunTime/Framework/system/System/HTTP/System.Net.WebResponse.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // namespace System.Net { using System; using System.IO; /// /// Provides a response from a Uniform Resource Identifier (URI). This is /// an abstract class. /// /// /// This is the abstract base class for all WebResponse /// objects. /// public abstract class WebResponse : MarshalByRefObject, IDisposable { /// /// Initializes a new instance of the WebResponse /// class. /// protected WebResponse() { } /// /// When overridden in a descendant class, gets or sets the content /// length of data being received. /// /// The number of bytes returned from the Internet /// resource. public virtual long ContentLength { get { throw new NotSupportedException(); } set { throw new NotSupportedException(); } } /// /// When overridden in a derived class, gets or sets the content type of /// the data being received. /// /// A string that contains the content type of the /// response. public virtual string ContentType { get { throw new NotSupportedException(); } set { throw new NotSupportedException(); } } /// /// When overridden in a descendant class, returns the data stream from /// the Internet resource. /// /// An instance of the class for /// reading data from the Internet resource. public virtual Stream GetResponseStream() { throw new NotSupportedException(); } /// /// When overridden in a derived class, gets the URI of the Internet /// resource that actually responded to the request. /// /// An instance of the class that /// contains the URI of the Internet resource that actually responded to /// the request. /// /// This property gets the final Response URI, that includes any changes /// that may have transpired from the orginal request. /// public virtual Uri ResponseUri { // read-only get { throw new NotSupportedException(); } } /// /// When overridden in a derived class, gets a collection of header /// name-value pairs associated with this request. /// /// An instance of the /// class that contains /// header values associated with this response. public virtual WebHeaderCollection Headers { get { throw new NotSupportedException(); } } ~WebResponse() { Dispose(false); } /// /// When overridden by a descendant class, closes the response stream. /// public virtual void Close() { Dispose(true); GC.SuppressFinalize(this); } public void Dispose() { Close(); } protected virtual void Dispose(bool disposing) { } } // class WebResponse } // namespace System.Net ================================================ FILE: Zelig/Zelig/RunTime/Framework/system/System/HTTP/System.Net.WebStatus.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // namespace System.Net { /// /// Defines status codes for the /// class. /// public enum WebExceptionStatus { /// No error was encountered. Success = 0, /// The name resolver service could not resolve the host name. /// NameResolutionFailure = 1, /// The remote service point could not be contacted at the /// transport level. ConnectFailure = 2, /// A complete response was not received from the remote /// server. ReceiveFailure = 3, /// A complete request could not be sent to the remote /// server. SendFailure = 4, /// The request was a piplined request and the connection was /// closed before the response was received. PipelineFailure = 5, /// The request was canceled or an unclassifiable error /// occurred. This is the default value for /// . RequestCanceled = 6, /// The response received from the server was complete but /// indicated a protocol-level error. For example, an HTTP protocol /// error such as 401 Access Denied would use this status. ProtocolError = 7, /// The connection was prematurely closed. ConnectionClosed = 8, /// A server certificate could not be validated. TrustFailure = 9, /// An error occurred while establishing a connection using /// SSL. SecureChannelFailure = 10, /// The server response was not a valid HTTP /// response. ServerProtocolViolation = 11, /// The connection for a request that specifies the Keep-alive /// header was closed unexpectedly. KeepAliveFailure = 12, /// An internal asynchronous request is pending. Pending = 13, /// No response was received during the time-out period for a /// request. Timeout = 14, /// The name resolver service could not resolve the proxy host /// name. ProxyNameResolutionFailure = 15 } // enum WebStatus } // namespace System.Net ================================================ FILE: Zelig/Zelig/RunTime/Framework/system/System/HTTP/System.Net._HeaderInfo.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // namespace System.Net { internal delegate string[] HeaderParser(string value); /// /// Internal supporting class for validation of HTTP Web Headers. /// internal class HeaderInfo { internal bool IsRestricted; internal HeaderParser Parser; /// /// Note that the HeaderName field is not always valid, and should not /// be used after initialization. In particular, the HeaderInfo returned /// for an unknown header will not have the correct header name. /// internal string HeaderName; internal bool AllowMultiValues; internal HeaderInfo(string name, bool restricted, bool multi, HeaderParser p) { HeaderName = name; IsRestricted = restricted; Parser = p; AllowMultiValues = multi; } } } // namespace System.Net ================================================ FILE: Zelig/Zelig/RunTime/Framework/system/System/HTTP/System.Net._HeaderInfoTable.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // namespace System.Net { using System.Collections; using System.Globalization; /// /// Internal class with utilities to validate HTTP headers. /// internal class HeaderInfoTable { private static HeaderInfo[] HeaderTable; private static HeaderParser SingleParser = new HeaderParser(ParseSingleValue); private static HeaderParser MultiParser = new HeaderParser(ParseMultiValue); private static string[] ParseSingleValue(string value) { return new string[1] { value }; } /// /// Parses single HTTP header and separates values delimited by comma. /// Like "Content-Type: text, HTML". The value string "text, HTML" will se parsed into 2 strings. /// /// Value string with possible multivalue /// Array of strings with single value in each. private static string[] ParseMultiValue(string value) { ArrayList tempCollection = new ArrayList(); bool inquote = false; int chIndex = 0; char[] vp = new char[value.Length]; string singleValue; for (int i = 0; i < value.Length; i++) { if (value[i] == '\"') { inquote = !inquote; } else if ((value[i] == ',') && !inquote) { singleValue = new String(vp, 0, chIndex); tempCollection.Add(singleValue.Trim()); chIndex = 0; continue; } vp[chIndex++] = value[i]; } // // Now add the last of the header values to the stringtable. // if (chIndex != 0) { singleValue = new String(vp, 0, chIndex); tempCollection.Add(singleValue.Trim()); } return (string[])tempCollection.ToArray(typeof(string)); } /// /// Header info for non-standard headers. /// private static HeaderInfo UnknownHeaderInfo = new HeaderInfo(String.Empty, false, false, SingleParser); private static bool m_Initialized = Initialize(); /// /// Initialize table with infomation for HTTP WEB headers. /// /// private static bool Initialize() { HeaderTable = new HeaderInfo[] { new HeaderInfo(HttpKnownHeaderNames.Age, false, false, SingleParser), new HeaderInfo(HttpKnownHeaderNames.Allow, false, true, MultiParser), new HeaderInfo(HttpKnownHeaderNames.Accept, true, true, MultiParser), new HeaderInfo(HttpKnownHeaderNames.Authorization, false, true, MultiParser), new HeaderInfo(HttpKnownHeaderNames.AcceptRanges, false, true, MultiParser), new HeaderInfo(HttpKnownHeaderNames.AcceptCharset, false, true, MultiParser), new HeaderInfo(HttpKnownHeaderNames.AcceptEncoding, false, true, MultiParser), new HeaderInfo(HttpKnownHeaderNames.AcceptLanguage, false, true, MultiParser), new HeaderInfo(HttpKnownHeaderNames.Cookie, false, true, MultiParser), new HeaderInfo(HttpKnownHeaderNames.Connection, true, true, MultiParser), new HeaderInfo(HttpKnownHeaderNames.ContentMD5, false, false, SingleParser), new HeaderInfo(HttpKnownHeaderNames.ContentType, false, false, SingleParser), new HeaderInfo(HttpKnownHeaderNames.CacheControl, false, true, MultiParser), new HeaderInfo(HttpKnownHeaderNames.ContentRange, false, false, SingleParser), new HeaderInfo(HttpKnownHeaderNames.ContentLength, true, false, SingleParser), new HeaderInfo(HttpKnownHeaderNames.ContentEncoding, false, true, MultiParser), new HeaderInfo(HttpKnownHeaderNames.ContentLanguage, false, true, MultiParser), new HeaderInfo(HttpKnownHeaderNames.ContentLocation, false, false, SingleParser), new HeaderInfo(HttpKnownHeaderNames.Date, false, false, SingleParser), new HeaderInfo(HttpKnownHeaderNames.ETag, false, false, SingleParser), new HeaderInfo(HttpKnownHeaderNames.Expect, true, true, MultiParser), new HeaderInfo(HttpKnownHeaderNames.Expires, false, false, SingleParser), new HeaderInfo(HttpKnownHeaderNames.From, false, false, SingleParser), new HeaderInfo(HttpKnownHeaderNames.Host, true, false, SingleParser), new HeaderInfo(HttpKnownHeaderNames.IfMatch, false, true, MultiParser), new HeaderInfo(HttpKnownHeaderNames.IfRange, false, false, SingleParser), new HeaderInfo(HttpKnownHeaderNames.IfNoneMatch, false, true, MultiParser), new HeaderInfo(HttpKnownHeaderNames.IfModifiedSince, true, false, SingleParser), new HeaderInfo(HttpKnownHeaderNames.IfUnmodifiedSince, false, false, SingleParser), new HeaderInfo(HttpKnownHeaderNames.Location, false, false, SingleParser), new HeaderInfo(HttpKnownHeaderNames.LastModified, false, false, SingleParser), new HeaderInfo(HttpKnownHeaderNames.MaxForwards, false, false, SingleParser), new HeaderInfo(HttpKnownHeaderNames.Pragma, false, true, MultiParser), new HeaderInfo(HttpKnownHeaderNames.ProxyAuthenticate, false, true, MultiParser), new HeaderInfo(HttpKnownHeaderNames.ProxyAuthorization, false, true, MultiParser), new HeaderInfo(HttpKnownHeaderNames.ProxyConnection, true, true, MultiParser), new HeaderInfo(HttpKnownHeaderNames.Range, true, true, MultiParser), new HeaderInfo(HttpKnownHeaderNames.Referer, true, false, SingleParser), new HeaderInfo(HttpKnownHeaderNames.RetryAfter, false, false, SingleParser), new HeaderInfo(HttpKnownHeaderNames.Server, false, false, SingleParser), new HeaderInfo(HttpKnownHeaderNames.SetCookie, false, true, MultiParser), new HeaderInfo(HttpKnownHeaderNames.SetCookie2, false, true, MultiParser), new HeaderInfo(HttpKnownHeaderNames.TE, false, true, MultiParser), new HeaderInfo(HttpKnownHeaderNames.Trailer, false, true, MultiParser), new HeaderInfo(HttpKnownHeaderNames.TransferEncoding, true , true, MultiParser), new HeaderInfo(HttpKnownHeaderNames.Upgrade, false, true, MultiParser), new HeaderInfo(HttpKnownHeaderNames.UserAgent, true, false, SingleParser), new HeaderInfo(HttpKnownHeaderNames.Via, false, true, MultiParser), new HeaderInfo(HttpKnownHeaderNames.Vary, false, true, MultiParser), new HeaderInfo(HttpKnownHeaderNames.Warning, false, true, MultiParser), new HeaderInfo(HttpKnownHeaderNames.WWWAuthenticate, false, true, SingleParser) }; return true; } /// /// Return HTTP header information from specified name of HTTP header. /// /// Name for HTTP header /// HTTP header information internal HeaderInfo this[string name] { get { // Return headerInfo with the same name string lowerCaseName = name.ToLower(); for (int i = 0; i < HeaderTable.Length; i++) { if (HeaderTable[i].HeaderName.ToLower() == lowerCaseName) { return HeaderTable[i]; } } // Return unknownInfo, instead of NULL return UnknownHeaderInfo; } } } // class HeaderInfoTable } // namespace System.Net ================================================ FILE: Zelig/Zelig/RunTime/Framework/system/System/HTTP/System.Net._HttpDateParse.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // namespace System.Net { /// /// Internal class that parses the string with date in HTTP headers to DateTime object. /// internal class HttpDateParse { /// /// Bse for decimal numbers /// private const int BASE_DEC = 10; /// /// Date indicies used to figure out what each entry is. /// private const int DATE_INDEX_DAY_OF_WEEK = 0; private const int DATE_1123_INDEX_DAY = 1; private const int DATE_1123_INDEX_MONTH = 2; private const int DATE_1123_INDEX_YEAR = 3; private const int DATE_1123_INDEX_HRS = 4; private const int DATE_1123_INDEX_MINS = 5; private const int DATE_1123_INDEX_SECS = 6; private const int DATE_ANSI_INDEX_MONTH = 1; private const int DATE_ANSI_INDEX_DAY = 2; private const int DATE_ANSI_INDEX_HRS = 3; private const int DATE_ANSI_INDEX_MINS = 4; private const int DATE_ANSI_INDEX_SECS = 5; private const int DATE_ANSI_INDEX_YEAR = 6; private const int DATE_INDEX_TZ = 7; private const int DATE_INDEX_LAST = DATE_INDEX_TZ; private const int MAX_FIELD_DATE_ENTRIES = (DATE_INDEX_LAST + 1); // // DATE_TOKEN's DWORD values used to determine what day/month we're on // private const int DATE_TOKEN_JANUARY = 1; private const int DATE_TOKEN_FEBRUARY = 2; private const int DATE_TOKEN_MARCH = 3; private const int DATE_TOKEN_APRIL = 4; private const int DATE_TOKEN_MAY = 5; private const int DATE_TOKEN_JUNE = 6; private const int DATE_TOKEN_JULY = 7; private const int DATE_TOKEN_AUGUST = 8; private const int DATE_TOKEN_SEPTEMBER = 9; private const int DATE_TOKEN_OCTOBER = 10; private const int DATE_TOKEN_NOVEMBER = 11; private const int DATE_TOKEN_DECEMBER = 12; private const int DATE_TOKEN_LAST_MONTH = (DATE_TOKEN_DECEMBER + 1); private const int DATE_TOKEN_SUNDAY = 0; private const int DATE_TOKEN_MONDAY = 1; private const int DATE_TOKEN_TUESDAY = 2; private const int DATE_TOKEN_WEDNESDAY = 3; private const int DATE_TOKEN_THURSDAY = 4; private const int DATE_TOKEN_FRIDAY = 5; private const int DATE_TOKEN_SATURDAY = 6; private const int DATE_TOKEN_LAST_DAY = (DATE_TOKEN_SATURDAY + 1); private const int DATE_TOKEN_GMT = -1000; private const int DATE_TOKEN_LAST = DATE_TOKEN_GMT; private const int DATE_TOKEN_ERROR = (DATE_TOKEN_LAST + 1); // // MAKE_UPPER - takes an assumed lower character and bit manipulates into a upper. // (make sure the character is Lower case alpha char to begin, // otherwise it corrupts) // private static char MAKE_UPPER(char c) { if (c >= 'a' && c <= 'z') { c -= (char)('a' - 'A'); } return c; } /*++ Routine Description: Arguments: lpszDay - Return Value: DWORD Success - The Correct date token, 0-6 for day of the week, 1-14 for month, etc Failure - DATE_TOKEN_ERROR --*/ /// /// Looks at the first three bytes of string to determine if we're looking /// at a Day of the Week, or Month, or "GMT" string. Is inlined so that /// the compiler can optimize this code into the caller FInternalParseHttpDate. /// /// Array of characters respresenting of the string in question. /// Staring index to for the time date in the string /// private static int MapDayMonthToDword( char[] lpszDay, int index ) { switch (MAKE_UPPER(lpszDay[index])) { // make uppercase case 'A': switch (MAKE_UPPER(lpszDay[index + 1])) { case 'P': return DATE_TOKEN_APRIL; case 'U': return DATE_TOKEN_AUGUST; } return DATE_TOKEN_ERROR; case 'D': return DATE_TOKEN_DECEMBER; case 'F': switch (MAKE_UPPER(lpszDay[index + 1])) { case 'R': return DATE_TOKEN_FRIDAY; case 'E': return DATE_TOKEN_FEBRUARY; } return DATE_TOKEN_ERROR; case 'G': return DATE_TOKEN_GMT; case 'M': switch (MAKE_UPPER(lpszDay[index + 1])) { case 'O': return DATE_TOKEN_MONDAY; case 'A': switch (MAKE_UPPER(lpszDay[index + 2])) { case 'R': return DATE_TOKEN_MARCH; case 'Y': return DATE_TOKEN_MAY; } // fall through to error break; } return DATE_TOKEN_ERROR; case 'N': return DATE_TOKEN_NOVEMBER; case 'J': switch (MAKE_UPPER(lpszDay[index + 1])) { case 'A': return DATE_TOKEN_JANUARY; case 'U': switch (MAKE_UPPER(lpszDay[index + 2])) { case 'N': return DATE_TOKEN_JUNE; case 'L': return DATE_TOKEN_JULY; } // fall through to error break; } return DATE_TOKEN_ERROR; case 'O': return DATE_TOKEN_OCTOBER; case 'S': switch (MAKE_UPPER(lpszDay[index + 1])) { case 'A': return DATE_TOKEN_SATURDAY; case 'U': return DATE_TOKEN_SUNDAY; case 'E': return DATE_TOKEN_SEPTEMBER; } return DATE_TOKEN_ERROR; case 'T': switch (MAKE_UPPER(lpszDay[index + 1])) { case 'U': return DATE_TOKEN_TUESDAY; case 'H': return DATE_TOKEN_THURSDAY; } return DATE_TOKEN_ERROR; case 'U': return DATE_TOKEN_GMT; case 'W': return DATE_TOKEN_WEDNESDAY; } return DATE_TOKEN_ERROR; } /// /// Parses through a ANSI, RFC850, or RFC1123 date format and covents it into /// a FILETIME/SYSTEMTIME time format. /// /// Important this a time-critical function and should only be changed /// with the intention of optimizing or a critical need work item. /// /// /// String with the date time information /// /// Out DateTime object. Used to return Systime if needed. /// Success - TRUE, Failure - FALSE public static bool ParseHttpDate( String DateString, out DateTime dtOut ) { int index = 0; int i = 0, iLastLettered = -1; bool fIsANSIDateFormat = false; int[] rgdwDateParseResults = new int[MAX_FIELD_DATE_ENTRIES]; bool fRet = true; char[] lpInputBuffer = DateString.ToCharArray(); dtOut = new DateTime(0); // // Date Parsing v2 (1 more to go), and here is how it works... // We take a date string and churn through it once, converting // integers to integers, Month,Day, and GMT strings into integers, // and all is then placed IN order in a temp array. // // At the completetion of the parse stage, we simple look at // the data, and then map the results into the correct // places in the SYSTIME structure. Simple, No allocations, and // No dirting the data. // // The end of the function does something munging and pretting // up of the results to handle the year 2000, and TZ offsets // Note: do we need to fully handle TZs anymore? // while (index < DateString.Length && i < MAX_FIELD_DATE_ENTRIES) { if (lpInputBuffer[index] >= '0' && lpInputBuffer[index] <= '9') { // // we have a numerical entry, scan through it and convent to DWORD // rgdwDateParseResults[i] = 0; do { rgdwDateParseResults[i] *= BASE_DEC; rgdwDateParseResults[i] += (lpInputBuffer[index] - '0'); index++; } while (index < DateString.Length && lpInputBuffer[index] >= '0' && lpInputBuffer[index] <= '9'); i++; // next token } else if ((lpInputBuffer[index] >= 'A' && lpInputBuffer[index] <= 'Z') || (lpInputBuffer[index] >= 'a' && lpInputBuffer[index] <= 'z')) { // // we have a string, should be a day, month, or GMT // lets skim to the end of the string // rgdwDateParseResults[i] = MapDayMonthToDword(lpInputBuffer, index); iLastLettered = i; // We want to ignore the possibility of a time zone such as PST or EST in a non-standard // date format such as "Thu Dec 17 16:01:28 PST 1998" (Notice that the year is _after_ the time zone if ((rgdwDateParseResults[i] == DATE_TOKEN_ERROR) && !(fIsANSIDateFormat && (i == DATE_ANSI_INDEX_YEAR))) { fRet = false; goto quit; } // // At this point if we have a vaild string // at this index, we know for sure that we're // looking at a ANSI type DATE format. // if (i == DATE_ANSI_INDEX_MONTH) { fIsANSIDateFormat = true; } // // Read past the end of the current set of alpha characters, // as MapDayMonthToDword only peeks at a few characters // do { index++; } while (index < DateString.Length && ((lpInputBuffer[index] >= 'A' && lpInputBuffer[index] <= 'Z') || (lpInputBuffer[index] >= 'a' && lpInputBuffer[index] <= 'z'))); i++; // next token } else { // // For the generic case its either a space, comma, semi-colon, etc. // the point is we really don't care, nor do we need to waste time // worring about it (the orginal code did). The point is we // care about the actual date information, So we just advance to the // next lexume. // index++; } } // // We're finished parsing the string, now take the parsed tokens // and turn them to the actual structured information we care about. // So we build lpSysTime from the Array, using a local if none is passed in. // int year; int month; int day; int hour; int minute; int second; int millisecond; millisecond = 0; if (fIsANSIDateFormat) { day = rgdwDateParseResults[DATE_ANSI_INDEX_DAY]; month = rgdwDateParseResults[DATE_ANSI_INDEX_MONTH]; hour = rgdwDateParseResults[DATE_ANSI_INDEX_HRS]; minute = rgdwDateParseResults[DATE_ANSI_INDEX_MINS]; second = rgdwDateParseResults[DATE_ANSI_INDEX_SECS]; if (iLastLettered != DATE_ANSI_INDEX_YEAR) { year = rgdwDateParseResults[DATE_ANSI_INDEX_YEAR]; } else { // Warning! This is a hack to get around the toString/toGMTstring fiasco (where the timezone is // appended at the end. (See above) year = rgdwDateParseResults[DATE_INDEX_TZ]; } } else { day = rgdwDateParseResults[DATE_1123_INDEX_DAY]; month = rgdwDateParseResults[DATE_1123_INDEX_MONTH]; year = rgdwDateParseResults[DATE_1123_INDEX_YEAR]; hour = rgdwDateParseResults[DATE_1123_INDEX_HRS]; minute = rgdwDateParseResults[DATE_1123_INDEX_MINS]; second = rgdwDateParseResults[DATE_1123_INDEX_SECS]; } // // Normalize the year, 90 == 1990, handle the year 2000, 02 == 2002 // This is Year 2000 handling folks!!! We get this wrong and // we all look bad. // if (year < 100) { year += ((year < 80) ? 2000 : 1900); } // // if we got misformed time, then plug in the current time // !lpszHrs || !lpszMins || !lpszSec // if ((i < 4) || (day > 31) || (hour > 23) || (minute > 59) || (second > 59)) { fRet = false; goto quit; } // // Now do the DateTime conversion // dtOut = new DateTime(year, month, day, hour, minute, second, millisecond); // // Hack: we want the system time to be accurate. This is _suhlow_ // The time passed in is in the local time zone; we have to convert this into GMT. // //////if (iLastLettered == DATE_ANSI_INDEX_YEAR) //////{ ////// // this should be an unusual case. ////// dtOut = dtOut.ToUniversalTime(); //////} // // If we have an Offset to another Time Zone // then convert to appropriate GMT time // if ((i > DATE_INDEX_TZ && rgdwDateParseResults[DATE_INDEX_TZ] != DATE_TOKEN_GMT)) { // // if we received +/-nnnn as offset (hhmm), modify the output FILETIME // double offset; offset = (double)rgdwDateParseResults[DATE_INDEX_TZ]; dtOut.AddHours(offset); } // In the end, we leave it all in LocalTime dtOut = dtOut.ToLocalTime(); quit: return fRet; } } } // namespace System.Net ================================================ FILE: Zelig/Zelig/RunTime/Framework/system/System/HTTP/System.Net._InputNetworkStreamWrapper.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // namespace System.Net { using System.Runtime.CompilerServices; using System.Net.Sockets; using System.IO; using System.Threading; /// /// The InputNetworkStreamWrapper is used to re-implement calls to NetworkStream.Read /// It has internal buffer and during initial read operation it places available data from socket into buffer. /// Later it releases data to Stream.Read calls. /// It also provides direct access to bufferet data for internal code. /// It provides possibility to "unread" or probe data - meaning user can read byte of data and then return it back to stream. /// internal class InputNetworkStreamWrapper : Stream { static private System.Text.Decoder UTF8decoder = System.Text.Encoding.UTF8.GetDecoder(); static private System.Text.Encoding UTF8Encoding = System.Text.Encoding.UTF8; /// /// Actual network or SSL stream connected to the server. /// It could be SSL stream, so NetworkStream is not exact type, m_Stream would be derived from NetworkStream /// internal NetworkStream m_stream; /// /// Last time this stream was used ( used to timeout idle connections ). /// internal DateTime m_lastUsed; /// /// This is a socket connected to client. /// InputNetworkStreamWrapper owns the socket, not NetworkStream. /// If connection is persistent, then the m_Socket is transferred to the list of /// internal Socket m_socket; /// /// Determines is the NetworkStream owns the socket /// internal bool m_ownsSocket; /// /// Address and port used for connection of the socket. It is in form of Address:Port ( like www.microsoft.com:80 ) /// internal string m_rmAddrAndPort; /// /// Determines if the stream is currently in use or not. /// internal bool m_inUse; /// /// Buffer for one line of HTTP header. /// private byte[] m_lineBuf; /// /// Internal buffer size for read caching /// private const int read_buffer_size = 256; /// /// Internal buffer for read caching /// internal byte[] m_readBuffer; /// /// End of valid data in internal buffer. /// internal int m_dataEnd; /// /// Start of valid data in internal buffer. /// internal int m_dataStart; /// /// Indicates that the stream has chunking encoding. /// We remove chunk markers and stop reading after end of last chunk. /// internal bool m_enableChunkedDecoding; /// /// Chunk data that we are currently decoding. /// private Chunk m_chunk; /// /// Inidcates the stream wrapper object is a clone and they underlying stream should not be disposed /// private bool m_isClone; /// /// Http web responses can contain the Content-Length of the response. In these cases, we would like the stream to return an EOF indication /// if the caller tries to read past the content length. /// internal long m_bytesLeftInResponse; /// /// Refills internal buffer from network. /// [MethodImplAttribute(MethodImplOptions.Synchronized)] private int RefillInternalBuffer() { #if DEBUG if (m_dataStart != m_dataEnd) { Console.WriteLine("Internal ERROR in InputNetworkStreamWrapper"); m_dataStart = m_dataEnd = 0; } #endif // m_dataStart should be equal to m_dataEnd. Purge buffered data. m_dataStart = m_dataEnd = 0; // Read up to read_buffer_size, but less data can be read. // This function does not try to block, so it reads available data or 1 byte at least. int readCount = (int)m_stream.Length; if ( readCount > read_buffer_size ) { readCount = read_buffer_size; } else if (readCount == 0) { readCount = 1; } m_dataEnd = m_stream.Read(m_readBuffer, 0, readCount); return m_dataEnd; } /// /// Resets position in internal buffers to zeroes. /// internal void ResetState() { m_dataStart = m_dataEnd = 0; m_enableChunkedDecoding = false; m_chunk = null; } /// /// Passes socket parameter to the base. /// Base Network stream never owns the stream. /// Socket is directly closed by class that contains InputNetworkStreamWrapper or transferred to /// list of idle sockets. /// /// TBD /// TBD /// TBD /// TBD internal InputNetworkStreamWrapper( NetworkStream stream, Socket socket, bool ownsSocket, string rmAddrAndPort) { m_stream = stream; m_socket = socket; m_ownsSocket = ownsSocket; m_rmAddrAndPort = rmAddrAndPort; m_inUse = true; // negative value indicates no length is set, in which case we will continue to read upon the callers request m_bytesLeftInResponse = -1; // Start with 80 (0x50) byte buffer for string. If string longer, we double it each time. m_lineBuf = new byte[0x50]; m_readBuffer = new byte[read_buffer_size]; } /// /// Re-implements reading of data to network stream. /// /// Buffer with data to write to HTTP client /// Offset at which to use data from buffer /// Count of bytes to write. public override int Read(byte[] buffer, int offset, int size) { // If chunking decoding is not needed - perform normal read. if (!m_enableChunkedDecoding) { return ReadInternal(buffer, offset, size); } // With chunking decoding there are 4 cases: // 1. We are at the beginning of chunk. Then we read chunk header and fill m_chunk. // 2. We are in the middle of chunk. Then it is kind of normal read, but no more than chunk length. // 3. We are close to the end of chunk. Then we read maximum of data in the chunk and set m_chunk to null. // 4. We already read last chunk of zero size. Return with zero bytes read. if (m_chunk == null) { // We are in the beginnig of the chunk. Create new chunk and continue. This is case 1. m_chunk = GetChunk(); } // First validate that chunk is more than zero in size. The last chunk is zero size and it indicates end of data. if (m_chunk.m_Size == 0) { // Nothing to read and actually it is the end of the message body. It is "case 4". return 0; } // Check if request to read is larger than remaining data in the chunk. if (size > m_chunk.m_Size - m_chunk.m_OffsetIntoChunk) { // We set size to the maximum data remaining the the chunk. This is the case 3. size = (int)(m_chunk.m_Size - m_chunk.m_OffsetIntoChunk); } // Ok, we know that we are in process of reading chunk data. This is case 2. // size is already adjusted to the maximum data remaining in the chunk. int retVal = ReadInternal(buffer, offset, size); // Adjust offset into chunk by amount of data read. retVal could be less than size. m_chunk.m_OffsetIntoChunk += (uint)retVal; // If we reached end of chunk, then set m_chunk to null. This indicates that chunk was completed. if (m_chunk.m_OffsetIntoChunk == m_chunk.m_Size) { m_chunk = null; } return retVal; } /// /// Clears the read buffer and reads from the underlying stream until no more data is available. /// public void FlushReadBuffer() { byte[] buffer = new byte[1024]; int waitTimeUs = m_bytesLeftInResponse == 0 ? 500000 : 1000000; try { while (m_socket.Poll(waitTimeUs, SelectMode.SelectRead)) { int avail = m_socket.Available; if(avail == 0) break; while (avail > 0) { int bytes = m_stream.Read(buffer, 0, avail > buffer.Length ? buffer.Length : avail); if (bytes <= 0) break; avail -= bytes; if (m_bytesLeftInResponse > 0) m_bytesLeftInResponse -= bytes; } } } catch { } m_dataEnd = m_dataStart = 0; m_bytesLeftInResponse = -1; } private void ReleaseThread() { FlushReadBuffer(); m_lastUsed = DateTime.Now; ResetState(); m_inUse = false; } /// /// Flushes the read buffer and resets the streams parameters. When in used in conjunction with the HttpWebRequest class /// this method enables this stream to be re-used. /// public void ReleaseStream() { Thread th = new Thread(new ThreadStart(ReleaseThread)); th.Start(); } /// /// Re-implements reading of data to network stream. /// /// Buffer with data to write to HTTP client /// Offset at which to use data from buffer /// Count of bytes to write. public int ReadInternal(byte[] buffer, int offset, int size) { // Need to init return value to zero explicitly, otherwise warning generated. int retVal = 0; // As first step we copy the buffered data if present int dataBuffered = m_dataEnd - m_dataStart; if (dataBuffered > 0) { int dataToCopy = size < dataBuffered ? size : dataBuffered; for (int i = 0; i < dataToCopy; i++) { buffer[offset + i] = m_readBuffer[m_dataStart + i]; } m_dataStart += dataToCopy; offset += dataToCopy; size -= dataToCopy; retVal += dataToCopy; } // // Now we check if more data is needed. // if m_BytesLeftInResponse == -1 , then we don't known the content length of the response // if m_BytesLeftInResponse is > retVal, then the data in the internal buffer (above) was less than the // the total content length of the response stream // In either case, we need to read more data to fullfill the read request // if (size > 0 && (m_bytesLeftInResponse == -1 || m_bytesLeftInResponse > retVal)) { // If buffering desired and requested data is less than internal buffer size // then we read into internal buffer. if (size < read_buffer_size) { if(0 == RefillInternalBuffer()) return 0; dataBuffered = m_dataEnd - m_dataStart; if (dataBuffered > 0) { int dataToCopy = size < dataBuffered ? size : dataBuffered; for (int i = 0; i < dataToCopy; i++) { buffer[offset + i] = m_readBuffer[m_dataStart + i]; } m_dataStart += dataToCopy; offset += dataToCopy; size -= dataToCopy; retVal += dataToCopy; } } else // Do not replentish internal buffer. Read rest of data directly { retVal += m_stream.Read(buffer, offset, size); } } // update the bytes left in response if(m_bytesLeftInResponse > 0) { m_bytesLeftInResponse -= retVal; // in case there were more bytes in the buffer than we expected make sure the next call returns 0 if(m_bytesLeftInResponse < 0) m_bytesLeftInResponse = 0; } return retVal; } /// /// Impletments Write for the stream. /// Since we do not have write buffering, all we do is delegate to the m_Stream. /// /// Buffer to write /// Start offset to write data /// Count of bytes to write public override void Write(byte[] buffer, int offset, int count) { m_stream.Write(buffer, offset, count); } /// /// Since we do not have write buffering, all we do is delegate to the m_Stream. /// public override void Flush() { m_stream.Flush(); } /// /// Return true if stream support reading. /// public override bool CanRead { get { return m_stream.CanRead; } } /// /// Return true if stream supports seeking /// public override bool CanSeek { get { return m_stream.CanSeek; } } /// /// Return true if timeout is applicable to the stream /// public override bool CanTimeout { get { return m_stream.CanTimeout; } } /// /// Return true if stream support writing. /// public override bool CanWrite { get { return m_stream.CanWrite; } } /// /// Gets the length of the data available on the stream. /// /// The length of the data available on the stream. /// Add data cached in the stream buffer to available on socket public override long Length { get { return m_enableChunkedDecoding && m_chunk != null ? m_chunk.m_Size : m_stream.Length + m_dataEnd - m_dataStart; } } /// /// Position is not supported for NetworkStream /// public override long Position { get { throw new NotSupportedException(); } set { throw new NotSupportedException(); } } /// /// Seekking is not suported on network streams /// /// Offset to seek /// Relative origin of the seek /// public override long Seek(long offset, SeekOrigin origin) { throw new NotSupportedException(); } /// /// Setting of length is not supported /// /// Length to set public override void SetLength(long value) { throw new NotSupportedException(); } /// /// Timeout for read operations. /// public override int ReadTimeout { get { return m_stream.ReadTimeout; } set { m_stream.ReadTimeout = value; } } /// /// Timeout for write operations. /// public override int WriteTimeout { get { return m_stream.WriteTimeout; } set { m_stream.WriteTimeout = value; } } public Stream CloneStream() { InputNetworkStreamWrapper clone = this.MemberwiseClone() as InputNetworkStreamWrapper; clone.m_isClone = true; return clone; } /// /// Overrides the Dispose Behavior /// protected override void Dispose(bool disposing) { m_inUse = false; if (!m_isClone) { m_stream.Close(); if(m_ownsSocket) { m_socket.Close(); } } base.Dispose(disposing); } /// /// Reads one line from steam, terminated by \r\n or by \n. /// /// Maxinun length of the line. If line is longer than maxLineLength exception is thrown /// String that represents the line, not including \r\n or by \n internal string Read_HTTP_Line( int maxLineLength ) { int curPos = 0; bool readLineComplete = false; while (!readLineComplete) { // We need to read character by character. For efficiency we need stream that implements internal bufferting. // We cannot read more than one character at a time, since this one could be the last. int maxCurSize = m_lineBuf.Length - 1; maxCurSize = maxCurSize < maxLineLength ? maxCurSize : maxLineLength; while (curPos < maxCurSize) { // If data available, Reads one byte of data. if (m_dataEnd - m_dataStart > 0) { // Very special code for reading of one character. m_lineBuf[curPos] = m_readBuffer[m_dataStart]; ++curPos; ++m_dataStart; } else { // Refill internal buffer and read one character. if(0 == RefillInternalBuffer()) { readLineComplete = true; break; } m_lineBuf[curPos] = m_readBuffer[m_dataStart]; ++curPos; ++m_dataStart; } // Accoring to HTTP spec HTTP headers lines should be separated by "\r\n" // Still spec requires for testing of "\n" only. So we test both if (m_lineBuf[curPos - 1] == '\r' || m_lineBuf[curPos - 1] == '\n') { // Next character should be '\n' if previous was '\r' if (m_lineBuf[curPos - 1] == '\r') { // If data available, Reads one byte of data. if (m_dataEnd - m_dataStart > 0) { // Very special code for reading of one character. m_lineBuf[curPos] = m_readBuffer[m_dataStart]; ++curPos; ++m_dataStart; } else { // Refill internal buffer and read one character. if(0 == RefillInternalBuffer()) { readLineComplete = true; break; } m_lineBuf[curPos] = m_readBuffer[m_dataStart]; ++curPos; ++m_dataStart; } } readLineComplete = true; break; } } // If we reached limit of the line size, just throw protocol violation exception. if (curPos == maxLineLength) { throw new WebException("Line too long", WebExceptionStatus.ServerProtocolViolation); } // There was no place in the m_lineBuf or end of line reached. if (!readLineComplete) { // Need to allocate larger m_lineBuf and copy existing line there. byte[] newLineBuf = new byte[m_lineBuf.Length * 2]; // Copy data to new array m_lineBuf.CopyTo(newLineBuf, 0); // Re-assign. Now m_lineBuf is twice as long and keeps the same data. m_lineBuf = newLineBuf; } } // Now we need to convert from byte array to string. if (curPos - 2 > 0) { int byteUsed, charUsed; bool completed = false; char[] charBuf = new char[curPos - 2]; UTF8decoder.Convert(m_lineBuf, 0, curPos - 2, charBuf, 0, charBuf.Length, true, out byteUsed, out charUsed, out completed); return new string(charBuf); } else if(curPos == 0) { throw new SocketException(SocketError.ConnectionAborted); } return ""; } /// /// Preview the byte in the input stream without removing it. /// /// Next byte in the stream. private byte PeekByte() { // Refills internal buffer if there is no more data if (m_dataEnd == m_dataStart) { if(0 == RefillInternalBuffer()) throw new SocketException(SocketError.ConnectionAborted); } return m_readBuffer[m_dataStart]; } /// /// Returns the byte in the input stream and removes it. /// /// Next byte in the stream. public override int ReadByte() { // Refills internal buffer if there is no more data if (m_dataEnd == m_dataStart) { if(0 == RefillInternalBuffer()) throw new SocketException(SocketError.ConnectionAborted); } // Very similar to Peek, but moves current position to next byte. return m_readBuffer[m_dataStart++]; } /// /// Writes single byte to stream /// /// public override void WriteByte(byte value) { m_stream.WriteByte(value); } /// /// Reads HTTP header from input stream. /// HTTP header can be wrapped on multiple lines. /// If next line starts by white space or tab - means it is continuing current header. /// Thus we need to use PeekByte() to check next byte without removing it from stream. /// /// Maximum length of the header /// internal string Read_HTTP_Header(int maxLineLength) { string strHeader = Read_HTTP_Line(maxLineLength); int headLineLen = strHeader.Length; // If line is empty - means the last one. Just return it. if (headLineLen == 0) { return strHeader; } maxLineLength -= headLineLen; // Check next byte in the stream. If it is ' ' or '\t' - next line is continuation of existing header. while (maxLineLength > 0 ) { byte nextByte = PeekByte(); // If next byte is not white space or tab, then we are done. if (!(nextByte == ' ' || nextByte == '\t')) { return strHeader; } // If we got here - means next line starts by white space or tab. Need to read it and append it. string strLine = Read_HTTP_Line(maxLineLength); // Decrease by amount of data read maxLineLength -= strLine.Length; // Adds it to the header. strHeader += strLine; } // If we come here - means HTTP header exceedes maximum length. throw new WebException("HTTP header too long", WebExceptionStatus.ServerProtocolViolation); } /// /// Retrieve information of the chunk. /// /// private Chunk GetChunk() { Chunk nextChunk = new Chunk(); bool parsing = true; ChunkState state = ChunkState.InitialLF; byte[] buffer = new byte[1024]; byte[] data; int dataByte = 0; while (parsing) { int readByte = ReadByte(); switch (readByte) { case 13: //CR if (state == ChunkState.InitialLF) break; data = new byte[dataByte]; Array.Copy(buffer, data, dataByte); switch (state) { case ChunkState.Size: nextChunk.m_Size = (uint)Convert.ToInt32(new string(UTF8Encoding.GetChars(data)), 16); dataByte = 0; break; case ChunkState.Value: dataByte = 0; break; default: throw new ProtocolViolationException("Wrong state for CR"); } state = ChunkState.LF; break; case 10: //LF switch (state) { case ChunkState.LF: parsing = false; break; case ChunkState.InitialLF: state = ChunkState.Size; break; default: throw new ProtocolViolationException("Incorrectly formated Chunk - Unexpected Line Feed"); } break; case 59: // ; if (state == ChunkState.Size) { data = new byte[dataByte]; Array.Copy(buffer, data, dataByte); nextChunk.m_Size = (uint)Convert.ToInt32(new string(UTF8Encoding.GetChars(data)),16); dataByte = 0; } else throw new ProtocolViolationException("Incorrectly formated Chunk"); state = ChunkState.Name; break; case 61: // = if (state == ChunkState.Name) { dataByte = 0; } else throw new ProtocolViolationException("Incorrectly formated Chunk"); state = ChunkState.Value; break; default: if (state == ChunkState.InitialLF) state = ChunkState.Size; buffer[dataByte] = (byte)readByte; dataByte++; if (state == ChunkState.LF) throw new ProtocolViolationException("Unexpected data after Line Feed"); break; } } return nextChunk; } private enum ChunkState { Size, Name, Value, LF, InitialLF } private class Chunk { public uint m_Size; public uint m_OffsetIntoChunk; } } } ================================================ FILE: Zelig/Zelig/RunTime/Framework/system/System/HTTP/System.Net._OutputNetworkStreamWrapper.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // namespace System.Net { using System.Net.Sockets; using System.IO; /// /// The OutputNetworkStreamWrapper is used to re-implement calls to NetworkStream.Write /// On first write HttpListenerResponse needs to send HTTP headers to client. /// internal class OutputNetworkStreamWrapper : Stream { /// /// This is a socket connected to client. /// OutputNetworkStreamWrapper owns the socket, not NetworkStream. /// If connection is persistent, then the m_Socket is transferred to the list of /// internal Socket m_socket; /// /// Actual network or SSL stream connected to the client. /// It could be SSL stream, so NetworkStream is not exact type, m_Stream would be derived from NetworkStream /// internal NetworkStream m_stream; /// /// Type definition of delegate for sending of HTTP headers. /// internal delegate void SendHeadersDelegate(); /// /// If not null - indicates whether we have sent headers or not. /// Calling of delegete sends HTTP headers to client - HttpListenerResponse.SendHeaders() /// private SendHeadersDelegate m_headersSend; /// /// Just passes parameters to the base. /// Socket is not owned by base NetworkStream /// /// /// public OutputNetworkStreamWrapper(Socket socket, NetworkStream stream) { m_socket = socket; m_stream = stream; } /// /// Sets the delegate for sending of headers. /// internal SendHeadersDelegate HeadersDelegate { set { m_headersSend = value; } } /// /// Return true if stream support reading. /// public override bool CanRead { get { return false; } } /// /// Return true if stream supports seeking /// public override bool CanSeek { get { return false; } } /// /// Return true if timeout is applicable to the stream /// public override bool CanTimeout { get { return m_stream.CanTimeout; } } /// /// Return true if stream support writing. It should be true, as this is output stream. /// public override bool CanWrite { get { return true; } } /// /// Gets the length of the data available on the stream. /// Since this is output stream reading is not allowed and length does not have meaning. /// /// The length of the data available on the stream. public override long Length { get { throw new NotSupportedException(); } } /// /// Position is not supported for NetworkStream /// public override long Position { get { throw new NotSupportedException(); } set { throw new NotSupportedException(); } } /// /// Timeout for read operations. /// public override int ReadTimeout { get { return m_stream.ReadTimeout; } set { m_stream.ReadTimeout = value; } } /// /// Timeout for write operations. /// public override int WriteTimeout { get { return m_stream.WriteTimeout; } set { m_stream.WriteTimeout = value; } } /// /// Closes the stream. Verifies that HTTP response is sent before closing. /// public override void Close() { if (m_headersSend != null) { // Calls HttpListenerResponse.SendHeaders. HttpListenerResponse.SendHeaders sets m_headersSend to null. m_headersSend(); } m_stream.Close(); m_stream = null; m_socket = null; } /// /// Flushes the stream. Verifies that HTTP response is sent before flushing. /// public override void Flush() { if (m_headersSend != null) { // Calls HttpListenerResponse.SendHeaders. HttpListenerResponse.SendHeaders sets m_headersSend to null. m_headersSend(); } m_stream.Flush(); } /// /// This putput stream, so read is not supported. /// /// public override int Read(byte[] buffer, int offset, int count) { throw new NotSupportedException(); } /// /// This putput stream, so read is not supported. /// /// public override int ReadByte() { throw new NotSupportedException(); } /// /// Seeking is not suported on network streams /// /// Offset to seek /// Relative origin of the seek /// public override long Seek(long offset, SeekOrigin origin) { throw new NotSupportedException(); } /// /// Setting length is not suported on network streams /// /// Length to set /// public override void SetLength(long value) { throw new NotSupportedException(); } /// /// Writes single byte to the stream. /// /// Byte value to write. public override void WriteByte(byte value) { m_stream.WriteByte(value); } /// /// Re-implements writing of data to network stream. /// The only functionality - on first write it sends HTTP headers. /// Then calls base /// /// Buffer with data to write to HTTP client /// Offset at which to use data from buffer /// Count of bytes to write. public override void Write(byte[] buffer, int offset, int size) { if (m_headersSend != null) { // Calls HttpListenerResponse.SendHeaders. HttpListenerResponse.SendHeaders sets m_headersSend to null. m_headersSend(); } m_stream.Write(buffer, offset, size); } } } ================================================ FILE: Zelig/Zelig/RunTime/Framework/system/System/HTTP/System.Net._ValidationHelper.cs ================================================ namespace System.Net { using System; /// /// Internal support class for Validation related stuff. /// internal class ValidationHelper { public static string[] EmptyArray = new string[0]; public static string[] MakeEmptyArrayNull(string[] stringArray) { if (stringArray == null || stringArray.Length == 0) { return null; } else { return stringArray; } } public static string MakeStringNull(string stringValue) { if (stringValue == null || stringValue.Length == 0) { return null; } else { return stringValue; } } public static string MakeStringEmpty(string stringValue) { if (stringValue == null || stringValue.Length == 0) { return String.Empty; } else { return stringValue; } } public static bool IsBlankString(string stringValue) { if (stringValue == null || stringValue.Length == 0) { return true; } else { return false; } } public static short ValidatePort(int port) { if ((port < IPEndPoint.MinPort) || (port > IPEndPoint.MaxPort)) { // If upper 16b is not zero... throw new ArgumentOutOfRangeException("port"); // Then this is not valid port } return (short)port; } public static bool ValidateTcpPort(int port) { // on false, API should throw new ArgumentOutOfRangeException("port"); return port >= IPEndPoint.MinPort && port <= IPEndPoint.MaxPort; } public static void ValidateRange(int actual, int fromAllowed, int toAllowed) { if (actual > toAllowed || actual < fromAllowed) { throw new ArgumentOutOfRangeException("value"); } } public static string ExceptionMessage(Exception exception) { if (exception == null) { return string.Empty; } if (exception.InnerException == null) { return exception.Message; } return exception.Message + " (" + ExceptionMessage(exception.InnerException) + ")"; } internal static readonly char[] InvalidParamChars = new char[]{ '(', ')', '<', '>', '@', ',', ';', ':', '\\', '"', '\'', '/', '[', ']', '?', '=', '{', '}', ' ', '\t', '\r', '\n'}; } } ================================================ FILE: Zelig/Zelig/RunTime/Framework/system/System/HTTP/System.Uri.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // namespace System { /// /// Defines the kinds of s for the /// method and several /// methods. /// public enum UriKind { /// /// The kind of the Uri is indeterminate. /// RelativeOrAbsolute = 0, /// /// The Uri is an absolute Uri. /// Absolute = 1, /// /// The Uri is a relative Uri. /// Relative = 2, } /// /// Defines host name types for the http and https protocols. /// method. /// public enum UriHostNameType { /// /// The type of the host name is not supplied. /// Unknown = 0, /// /// The host is set, but the type cannot be determined. /// Basic = 1, /// /// The host name is a domain name system (DNS) style host name. /// Dns = 2, /// /// The host name is an Internet Protocol (IP) version 4 host address. /// IPv4 = 3, /// /// The host name is an Internet Protocol (IP) version 6 host address. /// IPv6 = 4, } /// /// Provides an object representation of a uniform resource identifier (URI) /// and easy access to the parts of the URI. /// public class Uri { private int DefaultPort(string scheme) { switch (scheme) { case "http": return 80; case "https": return 443; case "ftp": return 21; case "gopher": return 70; case "nntp": return 119; case "telnet": return 23; case "ldap": return 389; case "mailto": return 25; case "net.tcp": return 808; case "ws": return 80; default: return UnknownPort; } } /// /// Defines flags kept in m_Flags variable. /// protected enum Flags { /// /// Flag value for loopback host /// LoopbackHost = 0x00400000 } /// /// Default port for http protocol - 80 /// public const int HttpDefaultPort = 80; /// /// Default port for https protocol - 443 /// public const int HttpsDefaultPort = 443; /// /// Constant to indicate that port for this protocol is unknown /// protected const int UnknownPort = -1; /// /// Type of the host. /// protected UriHostNameType m_hostNameType; /// /// Member variable that keeps port used by this uri. /// protected int m_port = UnknownPort; /// /// Member variable that keeps internal flags/ /// protected int m_Flags = 0; /// /// Member varialbe that keeps absolute path. /// protected string m_AbsolutePath = null; /// /// Member varialbe that keeps original string passed to Uri constructor. /// protected string m_OriginalUriString = null; /// /// Member varialbe that keeps scheme of Uri. /// protected string m_scheme = null; /// /// Member varialbe that keeps host name ( http and https ). /// protected string m_host = ""; /// /// Member varialbe that keeps boolean if Uri is absolute. /// protected bool m_isAbsoluteUri = false; /// /// Member varialbe that tells if path is UNC ( Universal Naming Convention ) /// In this class it is always false, but can be changed in derived classes. /// protected bool m_isUnc = false; /// /// Member variable that keeps absolute uri (generated in method ParseUriString) /// protected string m_absoluteUri = null; /// /// Initializes a new instance of the class /// with the specified URI. /// /// /// This constructor parses the URI string, therefore it can be used to /// validate a URI. /// /// A URI. /// /// The is null. /// /// ///

The is empty.

///

-or-

The scheme specified in /// is not correctly formed.

///

-or-

contains too many /// slashes.

///

-or-

The password specified in /// is not valid.

///

-or-

The host name specified in /// is not valid.

///

-or-

The file name specified in /// is not valid.

///

-or-

The user name specified in /// is not valid.

///

-or-

The host or authority name specified in /// cannot be terminated by backslashes. ///

///

-or-

The port number specified in /// is not valid or cannot be parsed.

///

-or-

The length of exceeds /// 65534 characters.

///

-or-

The length of the scheme specified in /// exceeds 1023 characters.

///

-or-

There is an invalid character sequence in /// .

///

-or-

The MS-DOS path specified in /// must start with c:\\.

///
public Uri(string uriString) { ConstructAbsoluteUri(uriString); } /// /// Constructs an absolute Uri from a URI string. /// /// A URI. /// /// See . /// protected void ConstructAbsoluteUri(string uriString) { // ParseUriString provides full validation including testing for // null. ParseUriString(uriString); m_OriginalUriString = uriString; } /// /// Constructs Uri from string and enumeration that tell what is the type of Uri. /// /// String to construct Uri from /// Type of Uri to construct public Uri(string uriString, UriKind kind) { // ParseUriString provides full validation including testing for null. switch (kind) { case UriKind.Absolute: { ConstructAbsoluteUri(uriString); break; } // Do not support unknown type of Uri. User should decide what he wants. case UriKind.RelativeOrAbsolute: { throw new ArgumentException(); } // Relative Uri. Store in original string. case UriKind.Relative: { // Validates the relative Uri. ValidateUriPart(uriString, 0); m_OriginalUriString = uriString; break; } } m_OriginalUriString = uriString; } /// /// Validates that part of Uri after sheme is valid for unknown Uri scheme /// /// Uri string /// Index in the string where Uri part ( after scheme ) starts protected void ValidateUriPart(string uriString, int startIndex) { // Check for valid alpha numeric characters int pathLength = uriString.Length - startIndex; // This is unknown scheme. We do validate following rules: // 1. All character values are less than 128. For characters it means they are more than zero. // 2. All charaters are >= 32. Lower values are control characters. // 3. If there is %, then there should be 2 hex digits which are 0-10 and A-F or a-f. for (int i = startIndex; i < pathLength; ++i) { //if (!(IsAlphaNumeric(uriString[i]) || uriString[i] == '+' || uriString[i] == '-' || uriString[i] == '.')) // If character is upper ( in signed more than 127, then value is negative ). char value = uriString[i]; if (value < 32) { throw new ArgumentException("Invalid char: " + value); } // If it is percent, then there should be 2 hex digits after. if (value == '%') { if (pathLength - i < 3) { throw new ArgumentException("No data after %"); } // There are at least 2 characters. Check their values for (int j = 1; j < 3; j++) { char nextVal = uriString[i + j]; if (!((nextVal >= '0' && nextVal <= '9') || (nextVal >= 'A' && nextVal <= 'F') || (nextVal >= 'a' && nextVal <= 'f') ) ) { throw new ArgumentException("Invalid char after %: " + value); } } // Moves i by 2 up to bypass verified characters. i += 2; } } } /// /// Internal method parses a URI string into Uri variables /// /// A Uri. /// /// The is null. /// /// /// See constructor description. /// protected void ParseUriString(string uriString) { int startIndex = 0; int endIndex = 0; // Check for null or empty string. if (uriString == null || uriString.Length == 0) { throw new ArgumentNullException(); } uriString = uriString.Trim(); // Check for presence of ':'. Colon always should be present in URI. if (uriString.IndexOf(':') == -1) { throw new ArgumentException(); } string uriStringLower = uriString.ToLower(); // If this is a urn parse and return if(uriStringLower.IndexOf( "urn:", startIndex ) == 0) { ValidateUrn( uriString ); return; } // If the uri is a relative path parse and return if(uriString[0] == '/') { ValidateRelativePath(uriString); return; } // Validate Scheme endIndex = uriString.IndexOf(':'); m_scheme = uriString.Substring(0, endIndex); if (!IsAlpha(m_scheme[0])) { throw new ArgumentException(); } for (int i = 1; i < m_scheme.Length; ++i) { if (!(IsAlphaNumeric(m_scheme[i]) || m_scheme[i] == '+' || m_scheme[i] == '-' || m_scheme[i] == '.')) { throw new ArgumentException(); } } // Get past the colon startIndex = endIndex + 1; if (startIndex >= uriString.Length) { throw new ArgumentException(); } // Get host, port and absolute path bool bRooted = ParseSchemeSpecificPart(uriString, startIndex); if ((m_scheme == "file" || m_scheme == "mailto") && m_host.Length == 0) { m_hostNameType = UriHostNameType.Basic; } else if (m_host.Length == 0) { m_hostNameType = UriHostNameType.Unknown; } else if (m_host[0] == '[') { if (!IsIPv6(m_host)) { throw new ArgumentException(); } m_hostNameType = UriHostNameType.IPv6; } else if (IsIPv4(m_host)) { m_hostNameType = UriHostNameType.IPv4; } else { m_hostNameType = UriHostNameType.Dns; } if (m_host != null) { if (m_host == "localhost" || m_host == "loopback" || (m_scheme == "file" || m_scheme == "mailto") && m_host.Length == 0) { m_Flags |= m_Flags | (int)Flags.LoopbackHost; } } m_absoluteUri = m_scheme + ":" + (bRooted ? "//" : string.Empty) + m_host + ((DefaultPort(m_scheme) == m_port) ? string.Empty : ":" + m_port.ToString()) + (m_scheme == "file" && m_AbsolutePath.Length >= 2 && IsAlpha(m_AbsolutePath[0]) && m_AbsolutePath[1] == ':' ? "/" : string.Empty) + m_AbsolutePath; m_isAbsoluteUri = true; m_isUnc = m_scheme == "file" && m_host.Length > 0; } /// /// Parse Scheme-specific part of uri for host, port and absolute path /// Briefed syntax abstracted from .NET FX: /// Group 1 - http, https, ftp, file, gopher, nntp, telnet, ldap, net.tcp and net.pipe /// Must be rooted. The 1st segment is authority. Empty path should be replace as '/' /// /// Group 2 - file /// Reminder: Treat all '\' as '/' /// If it starts with only one '/', host should be empty /// Otherwise, all leading '/' should be ignored before searching for 1st segment. The 1st segment is host /// /// Group 3 - news and uuid /// Authority always be empty. Everything goes to path. /// /// Group 4 - mailto and all other shemes /// The 1st segment is authority iff it was not rooted. /// /// Group 5 - all other schemes /// The 1st segment is authority iff it was rooted. Empty path should be replace as '/' /// /// Scheme-specific part of uri protected bool ParseSchemeSpecificPart(string sUri, int iStart) { bool bRooted = sUri.Length >= iStart + 2 && sUri.Substring(iStart, 2) == "//"; bool bAbsoluteUriRooted; string sAuthority; switch (m_scheme) { case "http": case "https": case "ftp": case "gopher": case "nntp": case "telnet": case "ldap": case "net.tcp": case "net.pipe": if (!bRooted) { throw new ArgumentException(); } bAbsoluteUriRooted = bRooted; Split(sUri, iStart + 2, out sAuthority, out m_AbsolutePath, true); break; case "file": if (!bRooted) { throw new ArgumentException(); } sUri = sUri.Substring(iStart + 2); if (sUri.Length > 0) { var array = sUri.ToCharArray(); for (int i = 0; i < array.Length; i++) { if (array[i] == '\\') { array[i] = '/'; } } sUri = new string(array); } string sTrimmed = sUri.TrimStart('/'); if (sTrimmed.Length >= 2 && IsAlpha(sTrimmed[0]) && sTrimmed[1] == ':') { //Windows style path if (sTrimmed.Length < 3 || sTrimmed[2] != '/') { throw new ArgumentException(); } sAuthority = string.Empty; m_AbsolutePath = sTrimmed; } else { //Unix style path if (sUri.Length - sTrimmed.Length == 1 || sTrimmed.Length == 0) { sAuthority = string.Empty; m_AbsolutePath = sUri.Length > 0 ? sUri : "/"; } else { Split(sTrimmed, 0, out sAuthority, out m_AbsolutePath, true); } } bAbsoluteUriRooted = bRooted; break; case "news": case "uuid": sAuthority = string.Empty; m_AbsolutePath = sUri.Substring(iStart); bAbsoluteUriRooted = false; break; case "mailto": if (bRooted) { sAuthority = string.Empty; m_AbsolutePath = sUri.Substring(iStart); } else { Split(sUri, iStart, out sAuthority, out m_AbsolutePath, false); } bAbsoluteUriRooted = false; break; default: if (bRooted) { Split(sUri, iStart + 2, out sAuthority, out m_AbsolutePath, true); } else { sAuthority = string.Empty; m_AbsolutePath = sUri.Substring(iStart); } bAbsoluteUriRooted = bRooted; break; } int iPortSplitter = sAuthority.LastIndexOf(':'); if (iPortSplitter < 0 || sAuthority.LastIndexOf(']') > iPortSplitter) { m_host = sAuthority; m_port = DefaultPort(m_scheme); } else { m_host = sAuthority.Substring(0, iPortSplitter); m_port = Convert.ToInt32(sAuthority.Substring(iPortSplitter + 1)); } return bAbsoluteUriRooted; } protected void Split(string sUri, int iStart, out string sAuthority, out string sPath, bool bReplaceEmptyPath) { int iSplitter = sUri.IndexOf('/', iStart); if (iSplitter < 0) { sAuthority = sUri.Substring(iStart); sPath = string.Empty; } else { sAuthority = sUri.Substring(iStart, iSplitter - iStart); sPath = sUri.Substring(iSplitter); } if (bReplaceEmptyPath && sPath.Length == 0) { sPath = "/"; } } /// /// Returns if host name is IP adress 4 bytes. Like 192.1.1.1 /// /// string with host name /// True if name is string with IPv4 address protected bool IsIPv4(String host) { int dots = 0; int number = 0; bool haveNumber = false; int length = host.Length; for (int i = 0; i < length; i++) { char ch = host[i]; if (ch <= '9' && ch >= '0') { haveNumber = true; number = number * 10 + (host[i] - '0'); if (number > 255) { return false; } } else if (ch == '.') { if (!haveNumber) { return false; } ++dots; haveNumber = false; number = 0; } else { return false; } } return (dots == 3) && haveNumber; } protected bool IsIPv6(string host) { return host[0] == '[' && host[host.Length - 1] == ']'; } /// /// Parses urn string into Uri variables. /// Parsing is restricted to basic urn:NamespaceID, urn:uuid formats only. /// /// A Uri. /// /// The is null. /// /// /// See the constructor description. /// protected void ValidateUrn(string uri) { bool invalidUrn = false; // If this is a urn:uuid validate the uuid if (uri.ToLower().IndexOf("urn:uuid:", 0) == 0) { char[] tempUUID = uri.Substring(9).ToLower().ToCharArray(); int length = tempUUID.Length; int uuidSegmentCount = 0; int[] delimiterIndexes = { 8, 13, 18, 23 }; for (int i = 0; i < length; ++i) { // Make sure these are valid hex numbers numbers if (!IsHex(tempUUID[i]) && tempUUID[i] != '-') { invalidUrn = true; break; } else { // Check each segment length if (tempUUID[i] == '-') { if (uuidSegmentCount > 3) { invalidUrn = true; break; } if (i != delimiterIndexes[uuidSegmentCount]) { invalidUrn = true; break; } ++uuidSegmentCount; } } } m_AbsolutePath = uri.Substring(4); } // Else validate against RFC2141 else { string lowerUrn = uri.Substring(4).ToLower(); char[] tempUrn = lowerUrn.ToCharArray(); // Validate the NamespaceID (NID) int index = lowerUrn.IndexOf(':'); if (index == -1) throw new ArgumentException(); int i = 0; for (i = 0; i < index; ++i) { // Make sure these are valid hex numbers numbers if (!IsAlphaNumeric(tempUrn[i]) && tempUrn[i] != '-') { invalidUrn = true; break; } } // Validate the Namespace String tempUrn = lowerUrn.Substring(index + 1).ToCharArray(); int urnLength = tempUrn.Length; if (!invalidUrn && urnLength != 0) { string otherChars = "()+,-.:=@;$_!*'"; for (i = 0; i < urnLength; ++i) { if (!IsAlphaNumeric(tempUrn[i]) && !IsHex(tempUrn[i]) && tempUrn[i] != '%' && otherChars.IndexOf(tempUrn[i]) == -1) { invalidUrn = true; break; } } m_AbsolutePath = uri.Substring(4); } } if (invalidUrn) throw new ArgumentNullException(); // Set Uri properties m_host = ""; m_isAbsoluteUri = true; m_isUnc = false; m_hostNameType = UriHostNameType.Unknown; m_port = UnknownPort; m_scheme = "urn"; m_absoluteUri = uri; return; } /// /// Parses relative Uri into variables. /// /// A Uri. /// /// The is null. /// /// /// See constructor description. /// protected void ValidateRelativePath(string uri) { // Check for null if (uri == null || uri.Length == 0) throw new ArgumentNullException(); // Check for "//" if (uri[1] == '/') throw new ArgumentException(); // Check for alphnumeric and special characters for (int i = 1; i < uri.Length; ++i) if (!IsAlphaNumeric(uri[i]) && ("()+,-.:=@;$_!*'").IndexOf(uri[i]) == -1) throw new ArgumentException(); m_AbsolutePath = uri.Substring(1); m_host = ""; m_isAbsoluteUri = false; m_isUnc = false; m_hostNameType = UriHostNameType.Unknown; m_port = UnknownPort; } public override int GetHashCode() { return base.GetHashCode(); } public override bool Equals(object o) { return this == (Uri)o; } public static bool operator ==(Uri lhs, Uri rhs) { object l = lhs, r = rhs; if (l == null) { return (r == null); } else if (r == null) { return false; } else { if (lhs.m_isAbsoluteUri && rhs.m_isAbsoluteUri) { return lhs.m_AbsolutePath.ToLower() == rhs.m_AbsolutePath.ToLower(); } else { return lhs.m_OriginalUriString.ToLower() == rhs.m_OriginalUriString.ToLower(); } } } public static bool operator !=(Uri lhs, Uri rhs) { object l = lhs, r = rhs; if (l == null) { return (r != null); } else if (r == null) { return true; } else { if (lhs.m_isAbsoluteUri && rhs.m_isAbsoluteUri) { return lhs.m_AbsolutePath.ToLower() != rhs.m_AbsolutePath.ToLower(); } else { return lhs.m_OriginalUriString.ToLower() != rhs.m_OriginalUriString.ToLower(); } } } /// /// Checks to see if the character value is an alpha character. /// /// The character to evaluate. /// true if the character is Alpha; /// otherwise, false. protected bool IsAlpha(char testChar) { return (testChar >= 'A' && testChar <= 'Z') || (testChar >= 'a' && testChar <= 'z'); } /// /// Checks to see if the character value is an alpha or numeric. /// /// The character to evaluate. /// true if the character is Alpha or /// numeric; otherwise, false. protected bool IsAlphaNumeric(char testChar) { return (testChar >= 'A' && testChar <= 'Z') || (testChar >= 'a' && testChar <= 'z') || (testChar >= '0' && testChar <= '9'); } /// /// Checks to see if the character value is Hex. /// /// The character to evaluate. /// true if the character is a valid Hex /// character; otherwise, false. protected bool IsHex(char testChar) { return (testChar >= 'A' && testChar <= 'F') || (testChar >= 'a' && testChar <= 'f') || (testChar >= '0' && testChar <= '9'); } /// /// Gets the type of the host name specified in the URI. /// /// A member of the /// enumeration. public UriHostNameType HostNameType { get { return m_hostNameType; } } /// /// Gets the port number of this URI. /// /// An Int32 value containing the port number /// for this URI. /// /// This instance represents a relative URI, and this property is valid /// only for absolute URIs. /// public int Port { get { if (m_isAbsoluteUri == false) throw new InvalidOperationException(); return m_port; } } /// /// Gets whether the instance is absolute. /// /// true if the Uri /// instance is absolute; otherwise, false. public bool IsAbsoluteUri { get { return m_isAbsoluteUri; } } /// /// Gets whether the specified is a universal /// naming convention (UNC) path. /// /// true if the is a /// UNC path; otherwise, false. /// /// This instance represents a relative URI, and this property is valid /// only for absolute URIs. /// public bool IsUnc { get { if (m_isAbsoluteUri == false) throw new InvalidOperationException(); return m_isUnc; } } /// /// Gets a local operating-system representation of a file name. /// /// A String containing the local /// operating-system representation of a file name. /// /// This instance represents a relative URI, and this property is valid /// only for absolute URIs. /// public string AbsolutePath { get { if (m_isAbsoluteUri == false) throw new InvalidOperationException(); return m_AbsolutePath; } } /// /// Gets the original URI string that was passed to the Uri constructor. /// public string OriginalString { get { // The original string was saved in m_OriginalUriString. return m_OriginalUriString; } } /// /// Gets a string containing the absolute uri or entire uri of this instance. /// /// A String containing the entire URI. /// public string AbsoluteUri { get { if (m_isAbsoluteUri == false) throw new InvalidOperationException(); return m_absoluteUri; } } /// /// Gets the scheme name for this URI. /// /// A String containing the scheme for this /// URI, converted to lowercase. /// /// This instance represents a relative URI, and this property is valid only /// for absolute URIs. /// public string Scheme { get { if (m_isAbsoluteUri == false) throw new InvalidOperationException(); return m_scheme; } } /// /// Gets the host component of this instance. /// /// A String containing the host name. This /// is usually the DNS host name or IP address of the server. public string Host { get { return m_host; } } /// /// Gets whether the specified refers to the /// local host. /// /// true if the host specified in the Uri is /// the local computer; otherwise, false. public bool IsLoopback { get { return (m_Flags & (int)Flags.LoopbackHost) != 0; } } /// /// Indicates whether the string is well-formed by attempting to /// construct a URI with the string. /// /// A URI. /// The type of the URI in /// . /// /// true if the string was well-formed in accordance /// with RFC 2396 and RFC 2732; otherwise false. /// public static bool IsWellFormedUriString(string uriString, UriKind uriKind) { try { // If absolute Uri was passed - create Uri object. switch (uriKind) { case UriKind.Absolute: { Uri testUri = new Uri(uriString); if (testUri.IsAbsoluteUri) { return true; } return false; } case UriKind.Relative: { Uri testUri = new Uri(uriString, UriKind.Relative); if (!testUri.IsAbsoluteUri) { return true; } return false; } default: return false; } } catch { return false; } } } } ================================================ FILE: Zelig/Zelig/RunTime/Framework/system/System/IO/Ports/Handshake.cs ================================================ // ==++== // // Copyright (c) Microsoft Corporation. All rights reserved. // // ==--== /*============================================================ ** ** Type: Handshake ** ** Purpose: Handshake enum type defined here. ** ** Date: August 2002 ** ===========================================================*/ namespace System.IO.Ports { public enum Handshake { None, XOnXOff, RequestToSend, RequestToSendXOnXOff } } ================================================ FILE: Zelig/Zelig/RunTime/Framework/system/System/IO/Ports/InternalResources.cs ================================================ // ==++== // // Copyright (c) Microsoft Corporation. All rights reserved. // // ==--== /*============================================================ ** ** Class: InternalResources ** ** Date: August 2002 ** ===========================================================*/ namespace System.IO.Ports { using System.IO; using System.Security; using System.Resources; using System.Globalization; using System.Collections; using System.Security.Permissions; using System.Text; using System.Configuration.Assemblies; using System.Runtime.InteropServices; using System.Reflection; using System.Diagnostics; ////using Microsoft.Win32; using System.Runtime.CompilerServices; internal static class InternalResources { // Beginning of static Error methods internal static void EndOfFile() { //// throw new EndOfStreamException( SR.GetString( SR.IO_EOF_ReadBeyondEOF ) ); #if EXCEPTION_STRINGS throw new EndOfStreamException( "IO_EOF_ReadBeyondEOF" ); #else throw new EndOfStreamException(); #endif } //// internal static String GetMessage( int errorCode ) //// { //// StringBuilder sb = new StringBuilder( 512 ); //// int result = SafeNativeMethods.FormatMessage( NativeMethods.FORMAT_MESSAGE_IGNORE_INSERTS | //// NativeMethods.FORMAT_MESSAGE_FROM_SYSTEM | NativeMethods.FORMAT_MESSAGE_ARGUMENT_ARRAY, //// new HandleRef( null, IntPtr.Zero ), errorCode, 0, sb, sb.Capacity, IntPtr.Zero ); //// if(result != 0) //// { //// // result is the # of characters copied to the StringBuilder on NT, //// // but on Win9x, it appears to be the number of MBCS bytes. //// // Just give up and return the String as-is... //// String s = sb.ToString(); //// return s; //// } //// else //// { //// return SR.GetString( SR.IO_UnknownError, errorCode ); //// } //// } internal static void FileNotOpen() { //// throw new ObjectDisposedException( null, SR.GetString( SR.Port_not_open ) ); #if EXCEPTION_STRINGS throw new ObjectDisposedException( null, "SR.Port_not_open" ); #else throw new ObjectDisposedException( null ); #endif } internal static void WrongAsyncResult() { //// throw new ArgumentException( SR.GetString( SR.Arg_WrongAsyncResult ) ); #if EXCEPTION_STRINGS throw new ArgumentException( "Arg_WrongAsyncResult" ); #else throw new ArgumentException(); #endif } internal static void EndReadCalledTwice() { // Should ideally be InvalidOperationExc but we can't maintain parity with Stream and SerialStream without some work //// throw new ArgumentException( SR.GetString( SR.InvalidOperation_EndReadCalledMultiple ) ); #if EXCEPTION_STRINGS throw new ArgumentException( "InvalidOperation_EndReadCalledMultiple" ); #else throw new ArgumentException(); #endif } internal static void EndWriteCalledTwice() { // Should ideally be InvalidOperationExc but we can't maintain parity with Stream and SerialStream without some work //// throw new ArgumentException( SR.GetString( SR.InvalidOperation_EndWriteCalledMultiple ) ); #if EXCEPTION_STRINGS throw new ArgumentException( "InvalidOperation_EndWriteCalledMultiple" ); #else throw new ArgumentException(); #endif } internal static void WinIOError() { throw new NotImplementedException(); //// int errorCode = Marshal.GetLastWin32Error(); //// WinIOError( errorCode, String.Empty ); } //// internal static void WinIOError( string str ) //// { //// int errorCode = Marshal.GetLastWin32Error(); //// WinIOError( errorCode, str ); //// } //// //// // After calling GetLastWin32Error(), it clears the last error field, //// // so you must save the HResult and pass it to this method. This method //// // will determine the appropriate exception to throw dependent on your //// // error, and depending on the error, insert a string into the message //// // gotten from the ResourceManager. //// internal static void WinIOError( int errorCode, String str ) //// { //// switch(errorCode) //// { //// case NativeMethods.ERROR_FILE_NOT_FOUND: //// case NativeMethods.ERROR_PATH_NOT_FOUND: //// if(str.Length == 0) //// throw new IOException( SR.GetString( SR.IO_PortNotFound ) ); //// else //// throw new IOException( SR.GetString( SR.IO_PortNotFoundFileName, str ) ); //// //// case NativeMethods.ERROR_ACCESS_DENIED: //// if(str.Length == 0) //// throw new UnauthorizedAccessException( SR.GetString( SR.UnauthorizedAccess_IODenied_NoPathName ) ); //// else //// throw new UnauthorizedAccessException( SR.GetString( SR.UnauthorizedAccess_IODenied_Path, str ) ); //// //// case NativeMethods.ERROR_FILENAME_EXCED_RANGE: //// throw new PathTooLongException( SR.GetString( SR.IO_PathTooLong ) ); //// //// case NativeMethods.ERROR_SHARING_VIOLATION: //// // error message. //// if(str.Length == 0) //// throw new IOException( SR.GetString( SR.IO_SharingViolation_NoFileName ) ); //// else //// throw new IOException( SR.GetString( SR.IO_SharingViolation_File, str ) ); //// //// default: //// throw new IOException( GetMessage( errorCode ), MakeHRFromErrorCode( errorCode ) ); //// } //// } //// //// // Use this to translate error codes like the above into HRESULTs like //// // 0x80070006 for ERROR_INVALID_HANDLE //// internal static int MakeHRFromErrorCode( int errorCode ) //// { //// return unchecked( ((int)0x80070000) | errorCode ); //// } } } ================================================ FILE: Zelig/Zelig/RunTime/Framework/system/System/IO/Ports/Parity.cs ================================================ // ==++== // // Copyright (c) Microsoft Corporation. All rights reserved. // // ==--== /*============================================================ ** ** Type: Parity ** ** Purpose: Parity enum type defined here. ** ** Date: August 2002 ** ===========================================================*/ namespace System.IO.Ports { public enum Parity { None = 0, // NativeMethods.NOPARITY, Odd = 1, // NativeMethods.ODDPARITY, Even = 2, // NativeMethods.EVENPARITY, Mark = 3, // NativeMethods.MARKPARITY, Space = 4, // NativeMethods.SPACEPARITY } } ================================================ FILE: Zelig/Zelig/RunTime/Framework/system/System/IO/Ports/SerialErrors.cs ================================================ // ==++== // // Copyright (c) Microsoft Corporation. All rights reserved. // // ==--== /*============================================================ ** ** Type: SerialError ** ** Purpose: Describes the types of serial port errors. ** ** Date: August 2002 ** ** ===========================================================*/ namespace System.IO.Ports { public enum SerialError { TXFull = 0x100, // NativeMethods.CE_TXFULL, RXOver = 0x001, // NativeMethods.CE_RXOVER, Overrun = 0x002, // NativeMethods.CE_OVERRUN, RXParity = 0x004, // NativeMethods.CE_PARITY, Frame = 0x008, // NativeMethods.CE_FRAME, } public class SerialErrorReceivedEventArgs : EventArgs { private SerialError errorType; internal SerialErrorReceivedEventArgs( SerialError eventCode ) { errorType = eventCode; } public SerialError EventType { get { return errorType; } } } public delegate void SerialErrorReceivedEventHandler( object sender, SerialErrorReceivedEventArgs e ); } ================================================ FILE: Zelig/Zelig/RunTime/Framework/system/System/IO/Ports/SerialPinChanges.cs ================================================ // ==++== // // Copyright (c) Microsoft Corporation. All rights reserved. // // ==--== /*============================================================ ** ** Type: SerialPinChange ** ** Purpose: Used to describe which pin has changed on a PinChanged event. ** ** Date: August 2002 ** ** ===========================================================*/ namespace System.IO.Ports { public enum SerialPinChange { CtsChanged = 0x008, // NativeMethods.EV_CTS, DsrChanged = 0x010, // NativeMethods.EV_DSR, CDChanged = 0x020, // NativeMethods.EV_RLSD, Ring = 0x100, // NativeMethods.EV_RING, Break = 0x040, // NativeMethods.EV_BREAK, } public class SerialPinChangedEventArgs : EventArgs { private SerialPinChange pinChanged; internal SerialPinChangedEventArgs( SerialPinChange eventCode ) { pinChanged = eventCode; } public SerialPinChange EventType { get { return pinChanged; } } } public delegate void SerialPinChangedEventHandler( object sender, SerialPinChangedEventArgs e ); } ================================================ FILE: Zelig/Zelig/RunTime/Framework/system/System/IO/Ports/SerialPort.cs ================================================ // ==++== // // Copyright (c) Microsoft Corporation. All rights reserved. // // ==--== /*============================================================ ** ** Class: SerialPort ** ** Purpose: SerialPort wraps an internal SerialStream class, ** : providing a high but complete level of Serial Port I/O functionality ** : over the handle/Win32 object level of the SerialStream. ** ** ** Date: August 2002 ** ===========================================================*/ namespace System.IO.Ports { using System; using System.ComponentModel; using System.Collections; using System.Diagnostics; using System.IO; using System.Text; using System.Security; using System.Security.Permissions; ////using Microsoft.Win32; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; ////using System.Runtime.Versioning; ////[MonitoringDescription(SR.SerialPortDesc)] public class SerialPort : System.ComponentModel.Component { public const int InfiniteTimeout = -1; // ---------- default values -------------* private const int defaultDataBits = 8; private const Parity defaultParity = Parity.None; private const StopBits defaultStopBits = StopBits.One; private const Handshake defaultHandshake = Handshake.None; private const int defaultBufferSize = 1024; private const string defaultPortName = "COM1"; private const int defaultBaudRate = 9600; private const bool defaultDtrEnable = false; private const bool defaultRtsEnable = false; private const bool defaultDiscardNull = false; private const byte defaultParityReplace = (byte)'?'; private const int defaultReceivedBytesThreshold = 1; private const int defaultReadTimeout = SerialPort.InfiniteTimeout; private const int defaultWriteTimeout = SerialPort.InfiniteTimeout; private const int defaultReadBufferSize = 4096; private const int defaultWriteBufferSize = 2048; private const int maxDataBits = 8; private const int minDataBits = 5; private const string defaultNewLine = "\n"; //// private const string SERIAL_NAME = @"\Device\Serial"; // --------- members supporting exposed properties ------------* private int baudRate = defaultBaudRate; private int dataBits = defaultDataBits; private Parity parity = defaultParity; private StopBits stopBits = defaultStopBits; private string portName = defaultPortName; private Encoding encoding = System.Text.Encoding.ASCII; // ASCII is default encoding for modem communication, etc. private Decoder decoder = System.Text.Encoding.ASCII.GetDecoder(); private int maxByteCountForSingleChar = System.Text.Encoding.ASCII.GetMaxByteCount( 1 ); private Handshake handshake = defaultHandshake; private int readTimeout = defaultReadTimeout; private int writeTimeout = defaultWriteTimeout; private int receivedBytesThreshold = defaultReceivedBytesThreshold; private bool discardNull = defaultDiscardNull; private bool dtrEnable = defaultDtrEnable; private bool rtsEnable = defaultRtsEnable; private byte parityReplace = defaultParityReplace; private string newLine = defaultNewLine; private int readBufferSize = defaultReadBufferSize; private int writeBufferSize = defaultWriteBufferSize; // ---------- members for internal support ---------* private SerialStream internalSerialStream = null; private byte[] inBuffer = new byte[defaultBufferSize]; private int readPos = 0; // position of next byte to read in the read buffer. readPos <= readLen private int readLen = 0; // position of first unreadable byte => CachedBytesToRead is the number of readable bytes left. private char[] oneChar = new char[1]; private char[] singleCharBuffer = null; // ------ event members ------------------* //public event EventHandler Disposed; //// [MonitoringDescription(SR.SerialErrorReceived)] public event SerialErrorReceivedEventHandler ErrorReceived; //// [MonitoringDescription(SR.SerialPinChanged)] public event SerialPinChangedEventHandler PinChanged; //// [MonitoringDescription(SR.SerialDataReceived)] public event SerialDataReceivedEventHandler DataReceived; //--- component properties---------------* // ---- SECTION: public properties --------------* // Note: information about port properties passes in ONE direction: from SerialPort to // its underlying Stream. No changes are able to be made in the important properties of // the stream and its behavior, so no reflection back to SerialPort is necessary. // Gets the internal SerialStream object. Used to pass essence of SerialPort to another Stream wrapper. //// [Browsable(false)] //// [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] public Stream BaseStream { get { EnsureOpened(); return internalSerialStream; } } //// [Browsable(true)] //// [DefaultValue(defaultBaudRate)] //// [MonitoringDescription(SR.BaudRate)] public int BaudRate { get { return baudRate; } set { if(value <= 0) { #if EXCEPTION_STRINGS throw new ArgumentOutOfRangeException( "BaudRate", "ArgumentOutOfRange_NeedPosNum" ); #else throw new ArgumentOutOfRangeException(); #endif //// throw new ArgumentOutOfRangeException( "BaudRate", SR.GetString( SR.ArgumentOutOfRange_NeedPosNum ) ); } if(IsOpen) { internalSerialStream.BaudRate = value; } baudRate = value; } } //// [Browsable(false)] //// [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] public bool BreakState { get { EnsureOpened(); return internalSerialStream.BreakState; } set { EnsureOpened(); internalSerialStream.BreakState = value; } } // includes all bytes available on serial driver's output buffer. Note that we do not internally buffer output bytes in SerialPort. //// [Browsable(false)] //// [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] public int BytesToWrite { get { EnsureOpened(); return internalSerialStream.BytesToWrite; } } // includes all bytes available on serial driver's input buffer as well as bytes internally buffered int the SerialPort class. //// [Browsable(false)] //// [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] public int BytesToRead { get { EnsureOpened(); return internalSerialStream.BytesToRead + CachedBytesToRead; // count the number of bytes we have in the internal buffer too. } } private int CachedBytesToRead { get { return readLen - readPos; } } //// [Browsable(false)] //// [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] public bool CDHolding { get { EnsureOpened(); return internalSerialStream.CDHolding; } } //// [Browsable(false)] //// [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] public bool CtsHolding { get { EnsureOpened(); return internalSerialStream.CtsHolding; } } //// [Browsable(true)] //// [DefaultValue(defaultDataBits)] //// [MonitoringDescription(SR.DataBits)] public int DataBits { get { return dataBits; } set { if(value < minDataBits || value > maxDataBits) { #if EXCEPTION_STRINGS throw new ArgumentOutOfRangeException( "DataBits", "ArgumentOutOfRange_Bounds_Lower_Upper" ); #else throw new ArgumentOutOfRangeException(); #endif //// throw new ArgumentOutOfRangeException( "DataBits", SR.GetString( SR.ArgumentOutOfRange_Bounds_Lower_Upper, minDataBits, maxDataBits ) ); } if(IsOpen) { internalSerialStream.DataBits = value; } dataBits = value; } } //// [Browsable(true)] //// [DefaultValue(defaultDiscardNull)] //// [MonitoringDescription(SR.DiscardNull)] public bool DiscardNull { get { return discardNull; } set { if(IsOpen) { internalSerialStream.DiscardNull = value; } discardNull = value; } } //// [Browsable(false)] //// [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] public bool DsrHolding { get { EnsureOpened(); return internalSerialStream.DsrHolding; } } //// [Browsable(true)] //// [DefaultValue(defaultDtrEnable)] //// [MonitoringDescription(SR.DtrEnable)] public bool DtrEnable { get { if(IsOpen) { dtrEnable = internalSerialStream.DtrEnable; } return dtrEnable; } set { if(IsOpen) { internalSerialStream.DtrEnable = value; } dtrEnable = value; } } // Allows specification of an arbitrary encoding for the reading and writing functions of the port // which deal with chars and strings. Set by default in the code to System.Text.ASCIIEncoding(), which // is the standard text encoding for modem commands and most of serial communication. // Clearly not designable. //// [Browsable(false)] //// [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] //// [MonitoringDescription(SR.Encoding)] public Encoding Encoding { get { return encoding; } set { if(value == null) { #if EXCEPTION_STRINGS throw new ArgumentNullException( "Encoding" ); #else throw new ArgumentNullException(); #endif } //// // Limit the encodings we support to some known ones. The code pages < 50000 represent all of the single-byte //// // and double-byte code pages. Code page 54936 is GB18030. Finally we check that the encoding's assembly //// // is mscorlib, so we don't get any weird user encodings that happen to set a code page less than 50000. //// if(!(value is ASCIIEncoding || value is UTF8Encoding || value is UnicodeEncoding || value is UTF32Encoding || //// ((value.CodePage < 50000 || value.CodePage == 54936) && value.GetType().Assembly == typeof( String ).Assembly))) //// { //// throw new ArgumentException( SR.GetString( SR.NotSupportedEncoding, value.WebName ), "value" ); //// } encoding = value; decoder = encoding.GetDecoder(); // This is somewhat of an approximate guesstimate to get the max char[] size needed to encode a single character maxByteCountForSingleChar = encoding.GetMaxByteCount( 1 ); singleCharBuffer = null; } } //// [Browsable(true)] //// [DefaultValue(defaultHandshake)] //// [MonitoringDescription(SR.Handshake)] public Handshake Handshake { get { return handshake; } set { if(value < Handshake.None || value > Handshake.RequestToSendXOnXOff) { #if EXCEPTION_STRINGS throw new ArgumentOutOfRangeException( "Handshake", "ArgumentOutOfRange_Enum" ); #else throw new ArgumentOutOfRangeException(); #endif //// throw new ArgumentOutOfRangeException( "Handshake", SR.GetString( SR.ArgumentOutOfRange_Enum ) ); } if(IsOpen) { internalSerialStream.Handshake = value; } handshake = value; } } private void EnsureOpened() { if(!IsOpen) { #if EXCEPTION_STRINGS throw new InvalidOperationException( "BaseStream_Invalid_Not_Open" ); #else throw new InvalidOperationException(); #endif } } private void EnsureClosed() { if(IsOpen) { #if EXCEPTION_STRINGS throw new InvalidOperationException( "Cant_be_set_when_open" ); #else throw new InvalidOperationException(); #endif } } // true only if the Open() method successfully called on this SerialPort object, without Close() being called more recently. //// [Browsable(false)] public bool IsOpen { get { return (internalSerialStream != null && internalSerialStream.IsOpen); } } //// [Browsable(false)] //// [DefaultValue(defaultNewLine)] //// [MonitoringDescription(SR.NewLine)] public string NewLine { get { return newLine; } set { if(value == null) { throw new ArgumentNullException(); } if(value.Length == 0) { #if EXCEPTION_STRINGS throw new ArgumentException( "InvalidNullEmptyArgument" ); #else throw new ArgumentException(); #endif //// throw new ArgumentException( SR.GetString( SR.InvalidNullEmptyArgument, "NewLine" ) ); } newLine = value; } } //// [Browsable(true)] //// [DefaultValue(defaultParity)] //// [MonitoringDescription(SR.Parity)] public Parity Parity { get { return parity; } set { if(value < Parity.None || value > Parity.Space) { #if EXCEPTION_STRINGS throw new ArgumentOutOfRangeException( "Parity", "ArgumentOutOfRange_Enum" ); #else throw new ArgumentOutOfRangeException(); #endif //// throw new ArgumentOutOfRangeException( "Parity", SR.GetString( SR.ArgumentOutOfRange_Enum ) ); } if(IsOpen) { internalSerialStream.Parity = value; } parity = value; } } //// [Browsable(true)] //// [DefaultValue(defaultParityReplace)] //// [MonitoringDescription(SR.ParityReplace)] public byte ParityReplace { get { return parityReplace; } set { if(IsOpen) { internalSerialStream.ParityReplace = value; } parityReplace = value; } } // Note that the communications port cannot be meaningfully re-set when the port is open, // and so once set by the constructor becomes read-only. //// [Browsable(true)] //// [DefaultValue(defaultPortName)] //// [MonitoringDescription(SR.PortName)] public string PortName { get { return portName; } //// [ResourceExposure( ResourceScope.Machine )] set { if(value == null) { #if EXCEPTION_STRINGS throw new ArgumentNullException( "PortName" ); #else throw new ArgumentNullException(); #endif } if(value.Length == 0) { #if EXCEPTION_STRINGS throw new ArgumentException( "PortNameEmpty_String" ); #else throw new ArgumentException(); #endif //// throw new ArgumentException( SR.GetString( SR.PortNameEmpty_String ), "PortName" ); } //// // disallow access to device resources beginning with @"\\", instead requiring "COM2:", etc. //// // Note that this still allows freedom in mapping names to ports, etc., but blocks security leaks. //// if(value.StartsWith( "\\\\", StringComparison.Ordinal )) //// { //// throw new ArgumentException( SR.GetString( SR.Arg_SecurityException ), "PortName" ); //// } EnsureClosed(); portName = value; } } //// [Browsable( true )] //// [DefaultValue( defaultReadBufferSize )] //// [MonitoringDescription( SR.ReadBufferSize )] public int ReadBufferSize { get { return readBufferSize; } set { if(value <= 0) { #if EXCEPTION_STRINGS throw new ArgumentOutOfRangeException( "value" ); #else throw new ArgumentOutOfRangeException(); #endif } EnsureClosed(); readBufferSize = value; } } // timeout for all read operations. May be set to SerialPort.InfiniteTimeout, 0, or any positive value //// [Browsable( true )] //// [DefaultValue( SerialPort.InfiniteTimeout )] //// [MonitoringDescription( SR.ReadTimeout )] public int ReadTimeout { get { return readTimeout; } set { if(value < 0 && value != SerialPort.InfiniteTimeout) { #if EXCEPTION_STRINGS throw new ArgumentOutOfRangeException( "ReadTimeout", "ArgumentOutOfRange_Timeout" ); #else throw new ArgumentOutOfRangeException(); #endif //// throw new ArgumentOutOfRangeException( "ReadTimeout", SR.GetString( SR.ArgumentOutOfRange_Timeout ) ); } if(IsOpen) { internalSerialStream.ReadTimeout = value; } readTimeout = value; } } //// [Browsable( true )] //// [DefaultValue( defaultReceivedBytesThreshold )] //// [MonitoringDescription( SR.ReceivedBytesThreshold )] // If we have the SerialData.Chars event set, this property indicates the number of bytes necessary // to exist in our buffers before the event is thrown. This is useful if we expect to receive n-byte // packets and can only act when we have this many, etc. public int ReceivedBytesThreshold { get { return receivedBytesThreshold; } set { if(value <= 0) { #if EXCEPTION_STRINGS throw new ArgumentOutOfRangeException( "ReceivedBytesThreshold", "ArgumentOutOfRange_NeedPosNum" ); #else throw new ArgumentOutOfRangeException(); #endif //// throw new ArgumentOutOfRangeException( "ReceivedBytesThreshold", SR.GetString( SR.ArgumentOutOfRange_NeedPosNum ) ); } receivedBytesThreshold = value; if(IsOpen) { // fake the call to our event handler in case the threshold has been set lower // than how many bytes we currently have. SerialDataReceivedEventArgs args = new SerialDataReceivedEventArgs( SerialData.Chars ); CatchReceivedEvents( this, args ); } } } //// [Browsable( true )] //// [DefaultValue( defaultRtsEnable )] //// [MonitoringDescription( SR.RtsEnable )] public bool RtsEnable { get { if(IsOpen) { rtsEnable = internalSerialStream.RtsEnable; } return rtsEnable; } set { if(IsOpen) { internalSerialStream.RtsEnable = value; } rtsEnable = value; } } // StopBits represented in C# as StopBits enum type and in Win32 as an integer 1, 2, or 3. //// [Browsable( true )] //// [DefaultValue( defaultStopBits )] //// [MonitoringDescription( SR.StopBits )] public StopBits StopBits { get { return stopBits; } set { // this range check looks wrong, but it really is correct. One = 1, Two = 2, and OnePointFive = 3 if(value < StopBits.One || value > StopBits.OnePointFive) { #if EXCEPTION_STRINGS throw new ArgumentOutOfRangeException( "StopBits", "ArgumentOutOfRange_Enum" ); #else throw new ArgumentOutOfRangeException(); #endif //// throw new ArgumentOutOfRangeException( "StopBits", SR.GetString( SR.ArgumentOutOfRange_Enum ) ); } if(IsOpen) { internalSerialStream.StopBits = value; } stopBits = value; } } //// [Browsable( true )] //// [DefaultValue( defaultWriteBufferSize )] //// [MonitoringDescription( SR.WriteBufferSize )] public int WriteBufferSize { get { return writeBufferSize; } set { if(value <= 0) { #if EXCEPTION_STRINGS throw new ArgumentOutOfRangeException( "value" ); #else throw new ArgumentOutOfRangeException(); #endif } EnsureClosed(); writeBufferSize = value; } } // timeout for all write operations. May be set to SerialPort.InfiniteTimeout or any positive value //// [Browsable( true )] //// [DefaultValue( defaultWriteTimeout )] //// [MonitoringDescription( SR.WriteTimeout )] public int WriteTimeout { get { return writeTimeout; } set { if(value <= 0 && value != SerialPort.InfiniteTimeout) { #if EXCEPTION_STRINGS throw new ArgumentOutOfRangeException( "WriteTimeout", "ArgumentOutOfRange_WriteTimeout" ); #else throw new ArgumentOutOfRangeException(); #endif //// throw new ArgumentOutOfRangeException( "WriteTimeout", SR.GetString( SR.ArgumentOutOfRange_WriteTimeout ) ); } if(IsOpen) { internalSerialStream.WriteTimeout = value; } writeTimeout = value; } } // -------- SECTION: constructors -----------------* public SerialPort( System.ComponentModel.IContainer container ) { /// /// Required for Windows.Forms Class Composition Designer support /// container.Add( this ); } public SerialPort() { } // Non-design SerialPort constructors here chain, using default values for members left unspecified by parameters // Note: Calling SerialPort() does not open a port connection but merely instantiates an object. // : A connection must be made using SerialPort's Open() method. //// [ResourceExposure( ResourceScope.Machine )] //// [ResourceConsumption( ResourceScope.Machine )] public SerialPort( string portName ) : this( portName, defaultBaudRate, defaultParity, defaultDataBits, defaultStopBits ) { } //// [ResourceExposure( ResourceScope.Machine )] //// [ResourceConsumption( ResourceScope.Machine )] public SerialPort( string portName , int baudRate ) : this( portName, baudRate, defaultParity, defaultDataBits, defaultStopBits ) { } //// [ResourceExposure( ResourceScope.Machine )] //// [ResourceConsumption( ResourceScope.Machine )] public SerialPort( string portName , int baudRate , Parity parity ) : this( portName, baudRate, parity, defaultDataBits, defaultStopBits ) { } //// [ResourceExposure( ResourceScope.Machine )] //// [ResourceConsumption( ResourceScope.Machine )] public SerialPort( string portName , int baudRate , Parity parity , int dataBits ) : this( portName, baudRate, parity, dataBits, defaultStopBits ) { } // all the magic happens in the call to the instance's .Open() method. // Internally, the SerialStream constructor opens the file handle, sets the device // control block and associated Win32 structures, and begins the event-watching cycle. //// [ResourceExposure( ResourceScope.Machine )] //// [ResourceConsumption( ResourceScope.Machine )] public SerialPort( string portName , int baudRate , Parity parity , int dataBits , StopBits stopBits ) { this.PortName = portName; this.BaudRate = baudRate; this.Parity = parity; this.DataBits = dataBits; this.StopBits = stopBits; } // Calls internal Serial Stream's Close() method on the internal Serial Stream. public void Close() { Dispose( true ); } protected override void Dispose( bool disposing ) { if(disposing) { if(IsOpen) { internalSerialStream.Flush(); internalSerialStream.Close(); internalSerialStream = null; } } base.Dispose( disposing ); } public void DiscardInBuffer() { EnsureOpened(); internalSerialStream.DiscardInBuffer(); readPos = 0; readLen = 0; } public void DiscardOutBuffer() { EnsureOpened(); internalSerialStream.DiscardOutBuffer(); } //// [ResourceExposure( ResourceScope.Machine )] //// [ResourceConsumption( ResourceScope.Machine )] [MethodImpl( MethodImplOptions.InternalCall )] public static extern string[] GetPortNames(); //// { //// RegistryKey baseKey = null; //// RegistryKey serialKey = null; //// //// String[] portNames = null; //// //// RegistryPermission registryPermission = new RegistryPermission( RegistryPermissionAccess.Read, //// @"HKEY_LOCAL_MACHINE\HARDWARE\DEVICEMAP\SERIALCOMM" ); //// registryPermission.Assert(); //// //// try //// { //// baseKey = Registry.LocalMachine; //// serialKey = baseKey.OpenSubKey( @"HARDWARE\DEVICEMAP\SERIALCOMM", false ); //// //// if(serialKey != null) //// { //// //// string[] deviceNames = serialKey.GetValueNames(); //// portNames = new String[deviceNames.Length]; //// //// for(int i = 0; i < deviceNames.Length; i++) //// portNames[i] = (string)serialKey.GetValue( deviceNames[i] ); //// } //// } //// finally //// { //// if(baseKey != null) //// baseKey.Close(); //// //// if(serialKey != null) //// serialKey.Close(); //// //// RegistryPermission.RevertAssert(); //// } //// //// // If serialKey didn't exist for some reason //// if(portNames == null) //// portNames = new String[0]; //// //// return portNames; //// } // SerialPort is open <=> SerialPort has an associated SerialStream. // The two statements are functionally equivalent here, so this method basically calls underlying Stream's // constructor from the main properties specified in SerialPort: baud, stopBits, parity, dataBits, // comm portName, handshaking, and timeouts. //// [ResourceExposure( ResourceScope.None )] // Look at Name property //// [ResourceConsumption( ResourceScope.Machine, ResourceScope.Machine )] public void Open() { EnsureClosed(); //// // Demand unmanaged code permission //// new SecurityPermission( SecurityPermissionFlag.UnmanagedCode ).Demand(); internalSerialStream = SerialStream.Create( portName, baudRate, parity, dataBits, stopBits, readBufferSize, writeBufferSize, readTimeout, writeTimeout, handshake, dtrEnable, rtsEnable, discardNull, parityReplace ); if(internalSerialStream == null) { #if EXCEPTION_STRINGS throw new ArgumentException( "Arg_InvalidSerialPort", "portName" ); #else throw new ArgumentException(); #endif //// throw new ArgumentException( SR.GetString( SR.Arg_InvalidSerialPort ), "portName" ); } internalSerialStream.ErrorReceived += new SerialErrorReceivedEventHandler( CatchErrorEvents ); internalSerialStream.PinChanged += new SerialPinChangedEventHandler ( CatchPinChangedEvents ); internalSerialStream.DataReceived += new SerialDataReceivedEventHandler ( CatchReceivedEvents ); } // Read Design pattern: // : ReadChar() returns the first available full char if found before, throws TimeoutExc if timeout. // : Read(byte[] buffer..., int count) returns all data available before read timeout expires up to *count* bytes // : Read(char[] buffer..., int count) returns all data available before read timeout expires up to *count* chars. // : Note, this does not return "half-characters". // : ReadByte() is the binary analogue of the first one. // : ReadLine(): returns null string on timeout, saves received data in buffer // : ReadAvailable(): returns all full characters which are IMMEDIATELY available. public int Read( byte[] buffer, int offset, int count ) { EnsureOpened(); if(buffer == null) { #if EXCEPTION_STRINGS throw new ArgumentNullException( "buffer", "ArgumentNull_Buffer" ); #else throw new ArgumentNullException(); #endif //// throw new ArgumentNullException( "buffer", SR.GetString( SR.ArgumentNull_Buffer ) ); } if(offset < 0) { #if EXCEPTION_STRINGS throw new ArgumentOutOfRangeException( "offset", "ArgumentOutOfRange_NeedNonNegNumRequired" ); #else throw new ArgumentOutOfRangeException(); #endif //// throw new ArgumentOutOfRangeException( "offset", SR.GetString( SR.ArgumentOutOfRange_NeedNonNegNumRequired ) ); } if(count < 0) { #if EXCEPTION_STRINGS throw new ArgumentOutOfRangeException( "count", "ArgumentOutOfRange_NeedNonNegNumRequired" ); #else throw new ArgumentOutOfRangeException(); #endif //// throw new ArgumentOutOfRangeException( "count", SR.GetString( SR.ArgumentOutOfRange_NeedNonNegNumRequired ) ); } if(buffer.Length - offset < count) { #if EXCEPTION_STRINGS throw new ArgumentException( "Argument_InvalidOffLen" ); #else throw new ArgumentException(); #endif //// throw new ArgumentException( SR.GetString( SR.Argument_InvalidOffLen ) ); } int bytesReadToBuffer = 0; // if any bytes available in internal buffer, return those without calling any read ops. if(CachedBytesToRead >= 1) { bytesReadToBuffer = Math.Min( CachedBytesToRead, count ); Buffer.BlockCopy( inBuffer, readPos, buffer, offset, bytesReadToBuffer ); readPos += bytesReadToBuffer; if(bytesReadToBuffer == count) { if(readPos == readLen) // just a check to see if we can reset buffer} { readPos = 0; readLen = 0; } return count; } // if we have read some bytes but there's none immediately available, return. if(BytesToRead == 0) { return bytesReadToBuffer; } } //Debug.Assert( CachedBytesToRead == 0, "there should be nothing left in our internal buffer" ); readLen = 0; readPos = 0; int bytesLeftToRead = count - bytesReadToBuffer; // request to read the requested number of bytes to fulfill the contract, // doesn't matter if we time out. We still return all the data we have available. bytesReadToBuffer += internalSerialStream.Read( buffer, offset + bytesReadToBuffer, bytesLeftToRead ); decoder.Reset(); return bytesReadToBuffer; } // publicly exposed "ReadOneChar"-type: Read() // reads one full character from the stream public int ReadChar() { EnsureOpened(); return ReadOneChar( readTimeout ); } // gets next available full character, which may be from the buffer, the stream, or both. // this takes size^2 time at most, where *size* is the maximum size of any one character in an encoding. // The user can call Read(1) to mimic this functionality. // We can replace ReadOneChar with Read at some point private int ReadOneChar( int timeout ) { int nextByte; int timeUsed = 0; //Debug.Assert( IsOpen, "ReadOneChar - port not open" ); // case 1: we have >= 1 character in the internal buffer. if(decoder.GetCharCount( inBuffer, readPos, CachedBytesToRead ) != 0) { int beginReadPos = readPos; // get characters from buffer. do { readPos++; } while(decoder.GetCharCount( inBuffer, beginReadPos, readPos - beginReadPos ) < 1); try { decoder.GetChars( inBuffer, beginReadPos, readPos - beginReadPos, oneChar, 0 ); } catch { // Handle surrogate chars correctly, restore readPos readPos = beginReadPos; throw; } return oneChar[0]; } else { // need to return immediately. if(timeout == 0) { // read all bytes in the serial driver in here. Make sure we ask for at least 1 byte // so that we get the proper timeout behavior int bytesInStream = internalSerialStream.BytesToRead; if(bytesInStream == 0) { bytesInStream = 1; } MaybeResizeBuffer( bytesInStream ); readLen += internalSerialStream.Read( inBuffer, readLen, bytesInStream ); // read all immediately avail. // If what we have in the buffer is not enough, throw TimeoutExc // if we are reading surrogate char then ReadBufferIntoChars // will throw argexc and that is okay as readPos is not altered if(ReadBufferIntoChars( oneChar, 0, 1, false ) == 0) { throw new TimeoutException(); } return oneChar[0]; } // case 2: we need to read from outside to find this. // timeout is either infinite or positive. int startTicks = Environment.TickCount; do { if(timeout == SerialPort.InfiniteTimeout) { nextByte = internalSerialStream.ReadByte( InfiniteTimeout ); } else if(timeout - timeUsed >= 0) { nextByte = internalSerialStream.ReadByte( timeout - timeUsed ); timeUsed = Environment.TickCount - startTicks; } else { throw new TimeoutException(); } MaybeResizeBuffer( 1 ); inBuffer[readLen++] = (byte)nextByte; // we must add to the end of the buffer } while(decoder.GetCharCount( inBuffer, readPos, readLen - readPos ) < 1); } // If we are reading surrogate char then this will throw argexc // we need not deal with that exc because we have not altered readPos yet. decoder.GetChars( inBuffer, readPos, readLen - readPos, oneChar, 0 ); // Everything should be out of inBuffer now. We'll just reset the pointers. readLen = 0; readPos = 0; return oneChar[0]; } // Will return 'n' (1 < n < count) characters (or) TimeoutExc public int Read( char[] buffer , int offset , int count ) { EnsureOpened(); if(buffer == null) { #if EXCEPTION_STRINGS throw new ArgumentNullException( "buffer", "ArgumentNull_Buffer" ); #else throw new ArgumentNullException(); #endif //// throw new ArgumentNullException( "buffer", SR.GetString( SR.ArgumentNull_Buffer ) ); } if(offset < 0) { #if EXCEPTION_STRINGS throw new ArgumentOutOfRangeException( "offset", "ArgumentOutOfRange_NeedNonNegNumRequired" ); #else throw new ArgumentOutOfRangeException(); #endif //// throw new ArgumentOutOfRangeException( "offset", SR.GetString( SR.ArgumentOutOfRange_NeedNonNegNumRequired ) ); } if(count < 0) { #if EXCEPTION_STRINGS throw new ArgumentOutOfRangeException( "count", "ArgumentOutOfRange_NeedNonNegNumRequired" ); #else throw new ArgumentOutOfRangeException(); #endif //// throw new ArgumentOutOfRangeException( "count", SR.GetString( SR.ArgumentOutOfRange_NeedNonNegNumRequired ) ); } if(buffer.Length - offset < count) { #if EXCEPTION_STRINGS throw new ArgumentException( "Argument_InvalidOffLen" ); #else throw new ArgumentException(); #endif //// throw new ArgumentException( SR.GetString( SR.Argument_InvalidOffLen ) ); } return InternalRead( buffer, offset, count, readTimeout, false ); } private int InternalRead( char[] buffer , int offset , int count , int timeout , bool countMultiByteCharsAsOne ) { //Debug.Assert( IsOpen, "port not open!" ); //Debug.Assert( buffer != null, "invalid buffer!" ); //Debug.Assert( offset >= 0, "invalid offset!" ); //Debug.Assert( count >= 0, "invalid count!" ); //Debug.Assert( buffer.Length - offset >= count, "invalid offset/count!" ); if(count == 0) { return 0; // immediately return on zero chars desired. This simplifies things later. } // Get the startticks before we read the underlying stream int startTicks = Environment.TickCount; // read everything else into internal buffer, which we know we can do instantly, and see if we NOW have enough. int bytesInStream = internalSerialStream.BytesToRead; MaybeResizeBuffer( bytesInStream ); readLen += internalSerialStream.Read( inBuffer, readLen, bytesInStream ); // should execute instantaneously. int charsWeAlreadyHave = decoder.GetCharCount( inBuffer, readPos, CachedBytesToRead ); // full chars already in our buffer if(charsWeAlreadyHave > 0) { // we found some chars after reading everything the SerialStream had to offer. We'll return what we have // rather than wait for more. return ReadBufferIntoChars( buffer, offset, count, countMultiByteCharsAsOne ); } if(timeout == 0) { throw new TimeoutException(); } // else: we need to do incremental reads from the stream. // ----- // our internal algorithm for finding exactly n characters is a bit complicated, but must overcome the // hurdle of NEVER READING TOO MANY BYTES from the Stream, since we can time out. A variable-length encoding // allows anywhere between minimum and maximum bytes per char times number of chars to be the exactly correct // target, and we have to take care not to overuse GetCharCount(). The problem is that GetCharCount() will never tell // us if we've read "half" a character in our current set of collected bytes; it underestimates. // size = maximum bytes per character in the encoding. n = number of characters requested. // Solution I: Use ReadOneChar() to read successive characters until we get to n. // Read calls: size * n; GetCharCount calls: size * n; each byte "counted": size times. // Solution II: Use a binary reduction and backtracking to reduce the number of calls. // Read calls: size * log n; GetCharCount calls: size * log n; each byte "counted": size * (log n) / n times. // We use the second, more complicated solution here. Note log is actually log_(size/size - 1)... // we need to read some from the stream // read *up to* the maximum number of bytes from the stream // we can read more since we receive everything instantaneously, and we don't have enough, // so when we do receive any data, it will be necessary and sufficient. int justRead; int maxReadSize = Encoding.GetMaxByteCount( count ); do { MaybeResizeBuffer( maxReadSize ); readLen += internalSerialStream.Read( inBuffer, readLen, maxReadSize ); justRead = ReadBufferIntoChars( buffer, offset, count, countMultiByteCharsAsOne ); if(justRead > 0) { return justRead; } } while(timeout == SerialPort.InfiniteTimeout || (timeout - GetElapsedTime( Environment.TickCount, startTicks ) > 0)); // must've timed out w/o getting a character. throw new TimeoutException(); } // ReadBufferIntoChars reads from Serial Port's inBuffer up to *count* chars and // places them in *buffer* starting at *offset*. // This does not call any stream Reads, and so takes "no time". // If the buffer specified is insufficient to accommodate surrogate characters // the call to underlying Decoder.GetChars will throw argexc. private int ReadBufferIntoChars( char[] buffer , int offset , int count , bool countMultiByteCharsAsOne ) { //Debug.Assert( count != 0, "Count should never be zero. We will probably see bugs further down if count is 0." ); int bytesToRead = Math.Min( count, CachedBytesToRead ); // There are lots of checks to determine if this really is a single byte encoding with no // funky fallbacks that would make it not single byte DecoderReplacementFallback fallback = encoding.DecoderFallback as DecoderReplacementFallback; if(encoding.IsSingleByte && encoding.GetMaxCharCount( bytesToRead ) == bytesToRead && fallback != null && fallback.MaxCharCount == 1) { // kill ASCII/ANSI encoding easily. // read at least one and at most *count* characters decoder.GetChars( inBuffer, readPos, bytesToRead, buffer, offset ); readPos += bytesToRead; if(readPos == readLen) { readPos = 0; readLen = 0; } return bytesToRead; } else { // // We want to turn inBuffer into at most count chars. This algorithm basically works like this: // 1) Take the largest step possible that won't give us too many chars // 2) If we find some chars, walk backwards until we find exactly how many bytes // they occupy. lastFullCharPos points to the end of the full chars. // 3) if we don't have enough chars for the buffer, goto #1 int totalBytesExamined = 0; // total number of Bytes in inBuffer we've looked at int totalCharsFound = 0; // total number of chars we've found in inBuffer, totalCharsFound <= totalBytesExamined int currentBytesToExamine; // the number of additional bytes to examine for characters int currentCharsFound; // the number of additional chars found after examining currentBytesToExamine extra bytes int lastFullCharPos = readPos; // first index AFTER last full char read, capped at ReadLen. do { currentBytesToExamine = Math.Min( count - totalCharsFound, readLen - readPos - totalBytesExamined ); if(currentBytesToExamine <= 0) { break; } totalBytesExamined += currentBytesToExamine; // recalculate currentBytesToExamine so that it includes leftover bytes from the last iteration. currentBytesToExamine = readPos + totalBytesExamined - lastFullCharPos; // make sure we don't go beyond the end of the valid data that we have. //Debug.Assert( (lastFullCharPos + currentBytesToExamine) <= readLen, "We should never be attempting to read more bytes than we have" ); currentCharsFound = decoder.GetCharCount( inBuffer, lastFullCharPos, currentBytesToExamine ); if(currentCharsFound > 0) { if((totalCharsFound + currentCharsFound) > count) { // Multibyte unicode sequence (possibly surrogate chars) // at the end of the buffer. We should not split the sequence, // instead return with less chars now and defer reading them // until next time if(!countMultiByteCharsAsOne) { break; } // If we are here it is from ReadTo which attempts to read one logical character // at a time. The supplied singleCharBuffer should be large enough to accommodate // this multi-byte char //Debug.Assert( (buffer.Length - offset - totalCharsFound) >= currentCharsFound, "internal buffer to read one full unicode char sequence is not sufficient!" ); } // go backwards until we know we have a full set of currentCharsFound bytes with no extra lead-bytes. int foundCharsByteLength = currentBytesToExamine; do { foundCharsByteLength--; } while(decoder.GetCharCount( inBuffer, lastFullCharPos, foundCharsByteLength ) == currentCharsFound); // Fill into destination buffer all the COMPLETE characters we've read. // If the buffer specified is insufficient to accommodate surrogate character // the call to underlying Decoder.GetChars will throw argexc. We need not // deal with this exc because we have not altered readPos yet. decoder.GetChars( inBuffer, lastFullCharPos, foundCharsByteLength + 1, buffer, offset + totalCharsFound ); lastFullCharPos = lastFullCharPos + foundCharsByteLength + 1; // update the end position of last known char. } totalCharsFound += currentCharsFound; } while((totalCharsFound < count) && (totalBytesExamined < CachedBytesToRead)); readPos = lastFullCharPos; if(readPos == readLen) { readPos = 0; readLen = 0; } return totalCharsFound; } } public int ReadByte() { EnsureOpened(); if(readLen != readPos) // stuff left in buffer, so we can read from it { return inBuffer[readPos++]; } decoder.Reset(); return internalSerialStream.ReadByte(); // otherwise, ask the stream. } public string ReadExisting() { EnsureOpened(); byte[] bytesReceived = new byte[BytesToRead]; if(readPos < readLen) { // stuff in internal buffer Buffer.BlockCopy( inBuffer, readPos, bytesReceived, 0, CachedBytesToRead ); } internalSerialStream.Read( bytesReceived, CachedBytesToRead, bytesReceived.Length - (CachedBytesToRead) ); // get everything // Read full characters and leave partial input in the buffer. Encoding.GetCharCount doesn't work because // it returns fallback characters on partial input, meaning that it overcounts. Instead, we use // GetCharCount from the decoder and tell it to preserve state, so that it returns the count of full // characters. Note that we don't actually want it to preserve state, so we call the decoder as if it's // preserving state and then call Reset in between calls. This uses a local decoder instead of the class // member decoder because that one may preserve state across SerialPort method calls. Decoder localDecoder = Encoding.GetDecoder(); int numCharsReceived = localDecoder.GetCharCount( bytesReceived, 0, bytesReceived.Length ); int lastFullCharIndex = bytesReceived.Length; if(numCharsReceived == 0) { Buffer.BlockCopy( bytesReceived, 0, inBuffer, 0, bytesReceived.Length ); // put it all back! // don't change readPos. --> readPos == 0? readPos = 0; readLen = bytesReceived.Length; return ""; } do { localDecoder.Reset(); lastFullCharIndex--; } while(localDecoder.GetCharCount( bytesReceived, 0, lastFullCharIndex ) == numCharsReceived); readPos = 0; readLen = bytesReceived.Length - (lastFullCharIndex + 1); Buffer.BlockCopy( bytesReceived, lastFullCharIndex + 1, inBuffer, 0, bytesReceived.Length - (lastFullCharIndex + 1) ); return Encoding.GetString( bytesReceived, 0, lastFullCharIndex + 1 ); } public string ReadLine() { return ReadTo( NewLine ); } public string ReadTo( string value ) { EnsureOpened(); if(value == null) { #if EXCEPTION_STRINGS throw new ArgumentNullException( "value" ); #else throw new ArgumentNullException(); #endif } if(value.Length == 0) { #if EXCEPTION_STRINGS throw new ArgumentException( "InvalidNullEmptyArgument" ); #else throw new ArgumentException(); #endif //// throw new ArgumentException( SR.GetString( SR.InvalidNullEmptyArgument, "value" ) ); } int numCharsRead; int timeUsed = 0; int timeNow; StringBuilder currentLine = new StringBuilder(); char lastValueChar = value[value.Length - 1]; // for timeout issues, best to read everything already on the stream into our buffers. // first make sure inBuffer is big enough int bytesInStream = internalSerialStream.BytesToRead; MaybeResizeBuffer( bytesInStream ); readLen += internalSerialStream.Read( inBuffer, readLen, bytesInStream ); int beginReadPos = readPos; if(singleCharBuffer == null) { // This is somewhat of an approximate guesstimate to get the max char[] size needed to encode a single character singleCharBuffer = new char[maxByteCountForSingleChar]; } try { while(true) { if(readTimeout == InfiniteTimeout) { numCharsRead = InternalRead( singleCharBuffer, 0, 1, readTimeout, true ); } else if(readTimeout - timeUsed >= 0) { timeNow = Environment.TickCount; numCharsRead = InternalRead( singleCharBuffer, 0, 1, readTimeout - timeUsed, true ); timeUsed += Environment.TickCount - timeNow; } else { throw new TimeoutException(); } //Debug.Assert( (numCharsRead > 0), "possible bug in ReadBufferIntoChars, reading surrogate char?" ); currentLine.Append( singleCharBuffer, 0, numCharsRead ); if(lastValueChar == (char)singleCharBuffer[numCharsRead - 1] && (currentLine.Length >= value.Length)) { // we found the last char in the value string. See if the rest is there. No need to // recompare the last char of the value string. bool found = true; for(int i = 2; i <= value.Length; i++) { if(value[value.Length - i] != currentLine[currentLine.Length - i]) { found = false; break; } } if(found) { // we found the search string. Exclude it from the return string. string ret = currentLine.ToString( 0, currentLine.Length - value.Length ); if(readPos == readLen) readPos = readLen = 0; return ret; } } } } catch { // We probably got here due to timeout. // We will try our best to restore the internal states, it's tricky! // 0) Save any existing data // 1) Restore readPos to the original position upon entering ReadTo // 2) Set readLen to the number of bytes read since entering ReadTo // 3) Restore inBuffer so that it contains the bytes from currentLine, resizing if necessary. // 4) Append the buffer with any saved data from 0) byte[] readBuffer = encoding.GetBytes( currentLine.ToString() ); // We will compact the data by default if(readBuffer.Length > 0) { int bytesToSave = CachedBytesToRead; byte[] savBuffer = new byte[bytesToSave]; if(bytesToSave > 0) Buffer.BlockCopy( inBuffer, readPos, savBuffer, 0, bytesToSave ); readPos = 0; readLen = 0; MaybeResizeBuffer( readBuffer.Length + bytesToSave ); Buffer.BlockCopy( readBuffer, 0, inBuffer, readLen, readBuffer.Length ); readLen += readBuffer.Length; if(bytesToSave > 0) { Buffer.BlockCopy( savBuffer, 0, inBuffer, readLen, bytesToSave ); readLen += bytesToSave; } } throw; } } // Writes string to output, no matter string's length. public void Write( string text ) { EnsureOpened(); if(text == null) { #if EXCEPTION_STRINGS throw new ArgumentNullException( "text" ); #else throw new ArgumentNullException(); #endif } if(text.Length == 0) { return; } byte[] bytesToWrite; bytesToWrite = encoding.GetBytes( text ); internalSerialStream.Write( bytesToWrite, 0, bytesToWrite.Length, writeTimeout ); } // encoding-dependent Write-chars method. // Probably as performant as direct conversion from ASCII to bytes, since we have to cast anyway (we can just call GetBytes) public void Write( char[] buffer , int offset , int count ) { EnsureOpened(); if(buffer == null) { #if EXCEPTION_STRINGS throw new ArgumentNullException( "buffer" ); #else throw new ArgumentNullException(); #endif } if(offset < 0) { #if EXCEPTION_STRINGS throw new ArgumentOutOfRangeException( "offset", "ArgumentOutOfRange_NeedNonNegNumRequired" ); #else throw new ArgumentOutOfRangeException(); #endif //// throw new ArgumentOutOfRangeException( "offset", SR.GetString( SR.ArgumentOutOfRange_NeedNonNegNumRequired ) ); } if(count < 0) { #if EXCEPTION_STRINGS throw new ArgumentOutOfRangeException( "count", "ArgumentOutOfRange_NeedNonNegNumRequired" ); #else throw new ArgumentOutOfRangeException(); #endif //// throw new ArgumentOutOfRangeException( "count", SR.GetString( SR.ArgumentOutOfRange_NeedNonNegNumRequired ) ); } if(buffer.Length - offset < count) { #if EXCEPTION_STRINGS throw new ArgumentException( "Argument_InvalidOffLen" ); #else throw new ArgumentException(); #endif //// throw new ArgumentException( SR.GetString( SR.Argument_InvalidOffLen ) ); } if(buffer.Length == 0) return; byte[] byteArray = Encoding.GetBytes( buffer, offset, count ); Write( byteArray, 0, byteArray.Length ); } // Writes a specified section of a byte buffer to output. public void Write( byte[] buffer , int offset , int count ) { EnsureOpened(); if(buffer == null) { #if EXCEPTION_STRINGS throw new ArgumentNullException( "buffer", "ArgumentNull_Buffer" ); #else throw new ArgumentNullException(); #endif //// throw new ArgumentNullException( "buffer", SR.GetString( SR.ArgumentNull_Buffer ) ); } if(offset < 0) { #if EXCEPTION_STRINGS throw new ArgumentOutOfRangeException( "offset", "ArgumentOutOfRange_NeedNonNegNumRequired" ); #else throw new ArgumentOutOfRangeException(); #endif //// throw new ArgumentOutOfRangeException( "offset", SR.GetString( SR.ArgumentOutOfRange_NeedNonNegNumRequired ) ); } if(count < 0) { #if EXCEPTION_STRINGS throw new ArgumentOutOfRangeException( "count", "ArgumentOutOfRange_NeedNonNegNumRequired" ); #else throw new ArgumentOutOfRangeException(); #endif //// throw new ArgumentOutOfRangeException( "count", SR.GetString( SR.ArgumentOutOfRange_NeedNonNegNumRequired ) ); } if(buffer.Length - offset < count) { #if EXCEPTION_STRINGS throw new ArgumentException( "Argument_InvalidOffLen" ); #else throw new ArgumentException(); #endif //// throw new ArgumentException( SR.GetString( SR.Argument_InvalidOffLen ) ); } if(buffer.Length == 0) { return; } internalSerialStream.Write( buffer, offset, count, writeTimeout ); } public void WriteLine( string text ) { Write( text + NewLine ); } // ----- SECTION: internal utility methods ----------------* // included here just to use the event filter to block unwanted invocations of the Serial Port's events. // Plus, this enforces the requirement on the received event that the number of buffered bytes >= receivedBytesThreshold private void CatchErrorEvents( object src , SerialErrorReceivedEventArgs e ) { SerialErrorReceivedEventHandler eventHandler = ErrorReceived; SerialStream stream = internalSerialStream; if((eventHandler != null) && (stream != null)) { lock(stream) { if(stream.IsOpen) { eventHandler( this, e ); } } } } private void CatchPinChangedEvents( object src , SerialPinChangedEventArgs e ) { SerialPinChangedEventHandler eventHandler = PinChanged; SerialStream stream = internalSerialStream; if((eventHandler != null) && (stream != null)) { lock(stream) { if(stream.IsOpen) { eventHandler( this, e ); } } } } private void CatchReceivedEvents( object src , SerialDataReceivedEventArgs e ) { SerialDataReceivedEventHandler eventHandler = DataReceived; SerialStream stream = internalSerialStream; if((eventHandler != null) && (stream != null)) { lock(stream) { // SerialStream might be closed between the time the event runner // pumped this event and the time the threadpool thread end up // invoking this event handler. The above lock and IsOpen check // ensures that we raise the event only when the port is open bool raiseEvent = false; try { raiseEvent = stream.IsOpen && (SerialData.Eof == e.EventType || BytesToRead >= receivedBytesThreshold); } catch { // Ignore and continue. SerialPort might have been closed already! } finally { if(raiseEvent) { eventHandler( this, e ); // here, do your reading, etc. } } } } } } private void CompactBuffer() { Buffer.BlockCopy( inBuffer, readPos, inBuffer, 0, CachedBytesToRead ); readLen = CachedBytesToRead; readPos = 0; } // This method guarantees that our inBuffer is big enough. The parameter passed in is // the number of bytes that our code is going to add to inBuffer. MaybeResizeBuffer will // do one of three things depending on how much data is already in the buffer and how // much will be added: // 1) Nothing. The current buffer is big enough to hold it all // 2) Compact the existing data and keep the current buffer. // 3) Create a new, larger buffer and compact the existing data into it. private void MaybeResizeBuffer( int additionalByteLength ) { // Case 1. No action needed if(additionalByteLength + readLen <= inBuffer.Length) { return; } // Case 2. Compact if(CachedBytesToRead + additionalByteLength <= inBuffer.Length / 2) { CompactBuffer(); } else { // Case 3. Create a new buffer int newLength = Math.Max( CachedBytesToRead + additionalByteLength, inBuffer.Length * 2 ); //Debug.Assert( inBuffer.Length >= readLen, "ResizeBuffer - readLen > inBuffer.Length" ); byte[] newBuffer = new byte[newLength]; // only copy the valid data from inBuffer, and put it at the beginning of newBuffer. Buffer.BlockCopy( inBuffer, readPos, newBuffer, 0, CachedBytesToRead ); readLen = CachedBytesToRead; readPos = 0; inBuffer = newBuffer; } } private static int GetElapsedTime( int currentTickCount , int startTickCount ) { int elapsedTime = unchecked( currentTickCount - startTickCount ); return (elapsedTime >= 0) ? (int)elapsedTime : Int32.MaxValue; } } } ================================================ FILE: Zelig/Zelig/RunTime/Framework/system/System/IO/Ports/SerialReceived.cs ================================================ // ==++== // // Copyright (c) Microsoft Corporation. All rights reserved. // // ==--== /*============================================================ ** ** Type: SerialData ** ** Purpose: Describes the types of receive events. ** ** Date: August 2002 ** ** ===========================================================*/ namespace System.IO.Ports { public enum SerialData { Chars = 0x01, // NativeMethods.EV_RXCHAR, Eof = 0x02, // NativeMethods.EV_RXFLAG, } public class SerialDataReceivedEventArgs : EventArgs { internal SerialData receiveType; internal SerialDataReceivedEventArgs( SerialData eventCode ) { receiveType = eventCode; } public SerialData EventType { get { return receiveType; } } } public delegate void SerialDataReceivedEventHandler( object sender, SerialDataReceivedEventArgs e ); } ================================================ FILE: Zelig/Zelig/RunTime/Framework/system/System/IO/Ports/SerialStream.cs ================================================ // ==++== // // Copyright (c) Microsoft Corporation. All rights reserved. // // ==--== /*============================================================================= ** ** Class: SerialStream ** ** Purpose: Class for enabling low-level sync and async control over a serial ** : communications resource. ** ** Date: August, 2002 ** =============================================================================*/ // Notes about the SerialStream: // * The stream is always opened via the SerialStream constructor. // * The handleProtector guarantees ownership of the file handle, so that it may not be // * unnaturally closed by another process or thread. Thus, since all properties are available // * only when the object exists, the object's properties can be queried only when the SerialStream // * object is instantiated (i.e. "open"). // * Handles to serial communications resources here always: // * 1) own the handle // * 2) are opened for asynchronous operation // * 3) set access at the level of FileAccess.ReadWrite // * 4) Allow for reading AND writing // * 5) Disallow seeking, since they encapsulate a file of type FILE_TYPE_CHAR namespace System.IO.Ports { using System; using System.IO; using System.Text; using System.ComponentModel; using System.Resources; using System.Runtime; using System.Security; using System.Security.Permissions; using System.Runtime.InteropServices; using System.Diagnostics; using System.Collections; ////using Microsoft.Win32; ////using Microsoft.Win32.SafeHandles; using System.Threading; ////using System.Runtime.Remoting.Messaging; using System.Runtime.CompilerServices; using System.Globalization; ////using System.Runtime.Versioning; public abstract class SerialStream : Stream { //// internal static class NativeMethods //// { //// internal const int MAXDWORD = -1; // note this is 0xfffffff, or UInt32.MaxValue, here used as an int //// //// internal const byte DEFAULTXONCHAR = 17; //// internal const byte DEFAULTXOFFCHAR = 19; //// internal const byte EOFCHAR = 26; //// //// // The following are unique to the SerialPort/SerialStream classes //// internal const byte ONESTOPBIT = 0; //// internal const byte ONE5STOPBITS = 1; //// internal const byte TWOSTOPBITS = 2; //// //// internal const int MS_CTS_ON = 0x10; //// internal const int MS_DSR_ON = 0x20; //// internal const int MS_RING_ON = 0x40; //// internal const int MS_RLSD_ON = 0x80; //// //// internal const int EV_RXCHAR = 0x01; //// internal const int EV_RXFLAG = 0x02; //// internal const int EV_CTS = 0x08; //// internal const int EV_DSR = 0x10; //// internal const int EV_RLSD = 0x20; //// internal const int EV_BREAK = 0x40; //// internal const int EV_ERR = 0x80; //// internal const int EV_RING = 0x100; //// internal const int ALL_EVENTS = 0x1fb; // don't use EV_TXEMPTY //// //// internal const int PURGE_TXABORT = 0x0001; // Kill the pending/current writes to the comm port. //// internal const int PURGE_RXABORT = 0x0002; // Kill the pending/current reads to the comm port. //// internal const int PURGE_TXCLEAR = 0x0004; // Kill the transmit queue if there. //// internal const int PURGE_RXCLEAR = 0x0008; // Kill the typeahead buffer if there. //// } //// //// internal static class UnsafeNativeMethods //// { //// //////////////////// Serial Port structs //////////////////// //// // Declaration for C# representation of Win32 Device Control Block (DCB) //// // structure. Note that all flag properties are encapsulated in the Flags field here, //// // and accessed/set through SerialStream's GetDcbFlag(...) and SetDcbFlag(...) methods. //// internal struct DCB //// { //// public uint BaudRate; //// //// public bool Flags_BINARY; //// public bool Flags_PARITY; //// public bool Flags_OUTXCTSFLOW; //// public bool Flags_OUTXDSRFLOW; //// public bool Flags_DTRCONTROL; //// public bool Flags_DSRSENSITIVITY; //// public bool Flags_TXCONTINUEONXOFF; //// public bool Flags_OUTX; //// public bool Flags_INX; //// public bool Flags_ERRORCHAR; //// public bool Flags_NULL; //// public bool Flags_RTSCONTROL; //// public bool Flags_ABORTONOERROR; //// //// public ushort XonLim; //// public ushort XoffLim; //// public byte ByteSize; //// public byte Parity; //// public byte StopBits; //// public byte XonChar; //// public byte XoffChar; //// public byte ErrorChar; //// public byte EofChar; //// public byte EvtChar; //// } //// //// // Declaration for C# representation of Win32 COMSTAT structure associated with //// // a file handle to a serial communications resource. SerialStream's //// // InBufferBytes and OutBufferBytes directly expose cbInQue and cbOutQue to reading, respectively. //// internal struct COMSTAT //// { //// public uint Flags; //// public uint cbInQue; //// public uint cbOutQue; //// } //// //// // Declaration for C# representation of Win32 COMMTIMEOUTS //// // structure associated with a file handle to a serial communications resource. //// ///Currently the only set fields are ReadTotalTimeoutConstant //// // and WriteTotalTimeoutConstant. //// internal struct COMMTIMEOUTS //// { //// public int ReadIntervalTimeout; //// public int ReadTotalTimeoutMultiplier; //// public int ReadTotalTimeoutConstant; //// public int WriteTotalTimeoutMultiplier; //// public int WriteTotalTimeoutConstant; //// } //// //// // Declaration for C# representation of Win32 COMMPROP //// // structure associated with a file handle to a serial communications resource. //// // Currently the only fields used are dwMaxTxQueue, dwMaxRxQueue, and dwMaxBaud //// // to ensure that users provide appropriate settings to the SerialStream constructor. //// internal struct COMMPROP //// { //// public ushort wPacketLength; //// public ushort wPacketVersion; //// public int dwServiceMask; //// public int dwReserved1; //// public int dwMaxTxQueue; //// public int dwMaxRxQueue; //// public int dwMaxBaud; //// public int dwProvSubType; //// public int dwProvCapabilities; //// public int dwSettableParams; //// public int dwSettableBaud; //// public ushort wSettableData; //// public ushort wSettableStopParity; //// public int dwCurrentTxQueue; //// public int dwCurrentRxQueue; //// public int dwProvSpec1; //// public int dwProvSpec2; //// public char wcProvChar; //// } //// //////////////////// end Serial Port structs //////////////////// //// //// [MethodImpl( MethodImplOptions.InternalCall )] //// internal static extern bool SetCommState( object _handle, ref DCB dcb ); //// //// [MethodImpl( MethodImplOptions.InternalCall )] //// internal static extern bool SetCommBreak( object _handle ); //// //// [MethodImpl( MethodImplOptions.InternalCall )] //// internal static extern bool ClearCommBreak( object _handle ); //// //// [MethodImpl( MethodImplOptions.InternalCall )] //// internal static extern bool SetCommTimeouts( object _handle, ref COMMTIMEOUTS commTimeouts ); //// //// [MethodImpl( MethodImplOptions.InternalCall )] //// internal static extern bool GetCommModemStatus( object _handle, ref int pinStatus ); //// //// [MethodImpl( MethodImplOptions.InternalCall )] //// internal static extern bool ClearCommError( object _handle, ref int errorCode, ref COMSTAT comStat ); //// //// [MethodImpl( MethodImplOptions.InternalCall )] //// internal static extern bool GetCommProperties( object _handle, ref COMMPROP commProp ); //// //// [MethodImpl( MethodImplOptions.InternalCall )] //// internal static extern void SetCommMask( object _handle, int p ); //// //// [MethodImpl( MethodImplOptions.InternalCall )] //// internal static extern bool PurgeComm( object _handle, int p ); //// //// [MethodImpl( MethodImplOptions.InternalCall )] //// internal static extern void FlushFileBuffers( object _handle ); //// //// [MethodImpl( MethodImplOptions.InternalCall )] //// internal static extern bool SetupComm( object _handle, int readBufferSize, int writeBufferSize ); //// //// [MethodImpl( MethodImplOptions.InternalCall )] //// internal static extern bool GetCommState( object _handle, ref DCB dcb ); //// //// [MethodImpl( MethodImplOptions.InternalCall )] //// internal static extern bool ClearCommError( object handle, ref int errors, IntPtr intPtr ); //// } //// //// const int errorEvents = (int)SerialError.Frame | //// (int)SerialError.Overrun | //// (int)SerialError.RXOver | //// (int)SerialError.RXParity | //// (int)SerialError.TXFull; //// //// const int receivedEvents = (int)SerialData.Chars | //// (int)SerialData.Eof; //// //// const int pinChangedEvents = (int)SerialPinChange.Break | //// (int)SerialPinChange.CDChanged | //// (int)SerialPinChange.CtsChanged | //// (int)SerialPinChange.Ring | //// (int)SerialPinChange.DsrChanged; //// //// const int infiniteTimeoutConst = -2; //// // members supporting properties exposed to SerialPort //// private string portName; //// private byte parityReplace = (byte)'?'; //// private bool inBreak = false; // port is initially in non-break state //// private Handshake handshake; //// private bool rtsEnable = false; //// //// // The internal C# representations of Win32 structures necessary for communication //// // hold most of the internal "fields" maintaining information about the port. //// private UnsafeNativeMethods.DCB dcb; //// private UnsafeNativeMethods.COMMTIMEOUTS commTimeouts; //// private UnsafeNativeMethods.COMSTAT comStat; //// private UnsafeNativeMethods.COMMPROP commProp; //// //// // internal-use members //// // private const long dsrTimeout = 0L; -- Not used anymore. //// private const int maxDataBits = 8; //// private const int minDataBits = 5; //// internal EventLoopRunner eventRunner; //// //// private byte[] tempBuf; // used to avoid multiple array allocations in ReadByte() //// //// // called whenever any async i/o operation completes. //// private unsafe static readonly IOCompletionCallback IOCallback = new IOCompletionCallback( SerialStream.AsyncFSCallback ); // three different events, also wrapped by SerialPort. internal event SerialDataReceivedEventHandler DataReceived; // called when one character is received. internal event SerialPinChangedEventHandler PinChanged; // called when any of the pin/ring-related triggers occurs internal event SerialErrorReceivedEventHandler ErrorReceived; // called when any runtime error occurs on the port (frame, overrun, parity, etc.) // ----SECTION: inherited properties from Stream class ------------* // These six properites are required for SerialStream to inherit from the abstract Stream class. // Note four of them are always true or false, and two of them throw exceptions, so these // are not usefully queried by applications which know they have a SerialStream, etc... public override bool CanRead { get { return this.IsOpen; } } public override bool CanSeek { get { return false; } } public override bool CanTimeout { get { return this.IsOpen; } } public override bool CanWrite { get { return this.IsOpen; } } public override long Length { get { #if EXCEPTION_STRINGS throw new NotSupportedException( "NotSupported_UnseekableStream" ); #else throw new NotSupportedException(); #endif //// throw new NotSupportedException( SR.GetString( SR.NotSupported_UnseekableStream ) ); } } public override long Position { get { #if EXCEPTION_STRINGS throw new NotSupportedException( "NotSupported_UnseekableStream" ); #else throw new NotSupportedException(); #endif //// throw new NotSupportedException( SR.GetString( SR.NotSupported_UnseekableStream ) ); } set { #if EXCEPTION_STRINGS throw new NotSupportedException( "NotSupported_UnseekableStream" ); #else throw new NotSupportedException(); #endif //// throw new NotSupportedException( SR.GetString( SR.NotSupported_UnseekableStream ) ); } } // ----- new get-set properties -----------------* // Standard port properties, also called from SerialPort // BaudRate may not be settable to an arbitrary integer between dwMinBaud and dwMaxBaud, // and is limited only by the serial driver. Typically about twelve values such // as Winbase.h's CBR_110 through CBR_256000 are used. public abstract int BaudRate { //get { return (int) dcb.BaudRate; } set; //// { //// if(value <= 0 || (value > commProp.dwMaxBaud && commProp.dwMaxBaud > 0)) //// { //// // if no upper bound on baud rate imposed by serial driver, note that argument must be positive //// if(commProp.dwMaxBaud == 0) //// { //// throw new ArgumentOutOfRangeException( "baudRate", SR.GetString( SR.ArgumentOutOfRange_NeedPosNum ) ); //// } //// else //// { //// // otherwise, we can present the bounds on the baud rate for this driver //// throw new ArgumentOutOfRangeException( "baudRate", SR.GetString( SR.ArgumentOutOfRange_Bounds_Lower_Upper, 0, commProp.dwMaxBaud ) ); //// } //// } //// //// // Set only if it's different. Rollback to previous values if setting fails. //// // This pattern occurs through most of the other properties in this class. //// if(value != dcb.BaudRate) //// { //// int baudRateOld = (int)dcb.BaudRate; //// dcb.BaudRate = (uint)value; //// //// if(UnsafeNativeMethods.SetCommState( _handle, ref dcb ) == false) //// { //// dcb.BaudRate = (uint)baudRateOld; //// InternalResources.WinIOError(); //// } //// } //// } } public abstract bool BreakState { get; //// { //// return inBreak; //// } set; //// { //// if(value) //// { //// if(UnsafeNativeMethods.SetCommBreak( _handle ) == false) //// { //// InternalResources.WinIOError(); //// } //// inBreak = true; //// } //// else //// { //// if(UnsafeNativeMethods.ClearCommBreak( _handle ) == false) //// { //// InternalResources.WinIOError(); //// } //// //// inBreak = false; //// } //// } } public abstract int DataBits { //get { return (int) dcb.ByteSize; } set; //// { //// //Debug.Assert( !(value < minDataBits || value > maxDataBits), "An invalid value was passed to DataBits" ); //// //// if(value != dcb.ByteSize) //// { //// byte byteSizeOld = dcb.ByteSize; //// dcb.ByteSize = (byte)value; //// //// if(UnsafeNativeMethods.SetCommState( _handle, ref dcb ) == false) //// { //// dcb.ByteSize = byteSizeOld; //// InternalResources.WinIOError(); //// } //// } //// } } public abstract bool DiscardNull { set; //// { //// bool fNullOld = dcb.Flags_NULL; //// if(value != fNullOld) //// { //// dcb.Flags_NULL = value; //// //// if(UnsafeNativeMethods.SetCommState( _handle, ref dcb ) == false) //// { //// dcb.Flags_NULL = fNullOld; //// InternalResources.WinIOError(); //// } //// } //// } } public abstract bool DtrEnable { get; //// { //// return dcb.Flags_DTRCONTROL; //// } set; //// { //// bool fDtrControlOld = dcb.Flags_DTRCONTROL; //// //// if(value != fDtrControlOld) //// { //// dcb.Flags_DTRCONTROL = value; //// //// if(UnsafeNativeMethods.SetCommState( _handle, ref dcb ) == false) //// { //// dcb.Flags_DTRCONTROL = fDtrControlOld; //// InternalResources.WinIOError(); //// } //// } //// } } public abstract Handshake Handshake { set; //// { //// //// //Debug.Assert( !(value < System.IO.Ports.Handshake.None || value > System.IO.Ports.Handshake.RequestToSendXOnXOff), "An invalid value was passed to Handshake" ); //// //// if(value != handshake) //// { //// // in the DCB, handshake affects the fRtsControl, fOutxCtsFlow, and fInX, fOutX fields, //// // so we must save everything in that closure before making any changes. //// Handshake handshakeOld = handshake; //// //// bool fInOutXOld = dcb.Flags_INX; //// bool fOutxCtsFlowOld = dcb.Flags_OUTXCTSFLOW; //// bool fRtsControlOld = dcb.Flags_RTSCONTROL; //// //// handshake = value; //// //// bool fInXOutXFlag = (handshake == Handshake.XOnXOff || handshake == Handshake.RequestToSendXOnXOff); //// //// dcb.Flags_INX = fInXOutXFlag; //// dcb.Flags_OUTX = fInXOutXFlag; //// dcb.Flags_OUTXCTSFLOW = (handshake == Handshake.RequestToSend || handshake == Handshake.RequestToSendXOnXOff); //// //// if((handshake == Handshake.RequestToSend || //// handshake == Handshake.RequestToSendXOnXOff)) //// { //// dcb.Flags_RTSCONTROL = true; //// } //// else //// { //// dcb.Flags_RTSCONTROL = false; //// } //// //// if(UnsafeNativeMethods.SetCommState( _handle, ref dcb ) == false) //// { //// handshake = handshakeOld; //// //// dcb.Flags_INX = fInOutXOld; //// dcb.Flags_OUTX = fInOutXOld; //// dcb.Flags_OUTXCTSFLOW = fOutxCtsFlowOld; //// dcb.Flags_RTSCONTROL = fRtsControlOld; //// //// InternalResources.WinIOError(); //// } //// } //// } } public abstract bool IsOpen { get; //// { //// return _handle != null && !eventRunner.ShutdownLoop; //// } } public abstract Parity Parity { set; //// { //// //Debug.Assert( !(value < Parity.None || value > Parity.Space), "An invalid value was passed to Parity" ); //// //// if((byte)value != dcb.Parity) //// { //// byte parityOld = dcb.Parity; //// //// // in the DCB structure, the parity setting also potentially effects: //// // fParity, fErrorChar, ErrorChar //// // so these must be saved as well. //// bool fParityOld = dcb.Flags_PARITY; //// byte ErrorCharOld = dcb.ErrorChar; //// bool fErrorCharOld = dcb.Flags_ERRORCHAR; //// //// dcb.Parity = (byte)value; //// //// bool parityFlag = (dcb.Parity != (byte)Parity.None); //// dcb.Flags_PARITY = parityFlag; //// //// if(parityFlag) //// { //// dcb.Flags_ERRORCHAR = (parityReplace != '\0'); //// dcb.ErrorChar = parityReplace; //// } //// else //// { //// dcb.Flags_ERRORCHAR = false; //// dcb.ErrorChar = (byte)'\0'; //// } //// //// if(UnsafeNativeMethods.SetCommState( _handle, ref dcb ) == false) //// { //// dcb.Parity = parityOld; //// dcb.ErrorChar = ErrorCharOld; //// dcb.Flags_PARITY = fParityOld; //// dcb.Flags_ERRORCHAR = fErrorCharOld; //// //// InternalResources.WinIOError(); //// } //// } //// } } // ParityReplace is the eight-bit character which replaces any bytes which // ParityReplace affects the equivalent field in the DCB structure: ErrorChar, and // the DCB flag fErrorChar. public abstract byte ParityReplace { set; //// { //// if(value != parityReplace) //// { //// byte parityReplaceOld = parityReplace; //// byte errorCharOld = dcb.ErrorChar; //// bool fErrorCharOld = dcb.Flags_ERRORCHAR; //// //// parityReplace = value; //// if(dcb.Flags_PARITY) //// { //// dcb.Flags_ERRORCHAR = (parityReplace != '\0'); //// dcb.ErrorChar = parityReplace; //// } //// else //// { //// dcb.Flags_ERRORCHAR = false; //// dcb.ErrorChar = (byte)'\0'; //// } //// //// if(UnsafeNativeMethods.SetCommState( _handle, ref dcb ) == false) //// { //// parityReplace = parityReplaceOld; //// dcb.Flags_ERRORCHAR = fErrorCharOld; //// dcb.ErrorChar = errorCharOld; //// //// InternalResources.WinIOError(); //// } //// } //// } } // Timeouts are considered to be TOTAL time for the Read/Write operation and to be in milliseconds. // Timeouts are translated into DCB structure as follows: // Desired timeout => ReadTotalTimeoutConstant ReadTotalTimeoutMultiplier ReadIntervalTimeout // 0 0 0 MAXDWORD // 0 < n < infinity n MAXDWORD MAXDWORD // infinity infiniteTimeoutConst MAXDWORD MAXDWORD // // rationale for "infinity": There does not exist in the COMMTIMEOUTS structure a way to // *wait indefinitely for any byte, return when found*. Instead, if we set ReadTimeout // to infinity, SerialStream's EndRead loops if infiniteTimeoutConst mills have elapsed // without a byte received. Note that this is approximately 24 days, so essentially // most practical purposes effectively equate 24 days with an infinite amount of time // on a serial port connection. //// public override int ReadTimeout //// { //// get //// { //// int constant = commTimeouts.ReadTotalTimeoutConstant; //// //// return (constant == infiniteTimeoutConst) ? SerialPort.InfiniteTimeout : constant; //// } //// //// set //// { //// if(value < 0 && value != SerialPort.InfiniteTimeout) //// { //// throw new ArgumentOutOfRangeException( "ReadTimeout", SR.GetString( SR.ArgumentOutOfRange_Timeout ) ); //// } //// //// if(_handle == null) //// { //// InternalResources.FileNotOpen(); //// } //// //// int oldReadConstant = commTimeouts.ReadTotalTimeoutConstant; //// int oldReadInterval = commTimeouts.ReadIntervalTimeout; //// int oldReadMultipler = commTimeouts.ReadTotalTimeoutMultiplier; //// //// // NOTE: this logic should match what is in the constructor //// if(value == 0) //// { //// commTimeouts.ReadTotalTimeoutConstant = 0; //// commTimeouts.ReadTotalTimeoutMultiplier = 0; //// commTimeouts.ReadIntervalTimeout = NativeMethods.MAXDWORD; //// } //// else if(value == SerialPort.InfiniteTimeout) //// { //// // SetCommTimeouts doesn't like a value of -1 for some reason, so //// // we'll use -2(infiniteTimeoutConst) to represent infinite. //// commTimeouts.ReadTotalTimeoutConstant = infiniteTimeoutConst; //// commTimeouts.ReadTotalTimeoutMultiplier = NativeMethods.MAXDWORD; //// commTimeouts.ReadIntervalTimeout = NativeMethods.MAXDWORD; //// } //// else //// { //// commTimeouts.ReadTotalTimeoutConstant = value; //// commTimeouts.ReadTotalTimeoutMultiplier = NativeMethods.MAXDWORD; //// commTimeouts.ReadIntervalTimeout = NativeMethods.MAXDWORD; //// } //// //// if(UnsafeNativeMethods.SetCommTimeouts( _handle, ref commTimeouts ) == false) //// { //// commTimeouts.ReadTotalTimeoutConstant = oldReadConstant; //// commTimeouts.ReadTotalTimeoutMultiplier = oldReadMultipler; //// commTimeouts.ReadIntervalTimeout = oldReadInterval; //// //// InternalResources.WinIOError(); //// } //// } //// } public abstract bool RtsEnable { get; //// { //// return dcb.Flags_RTSCONTROL; //// } set; //// { //// if((handshake == Handshake.RequestToSend || handshake == Handshake.RequestToSendXOnXOff)) //// { //// throw new InvalidOperationException( SR.GetString( SR.CantSetRtsWithHandshaking ) ); //// } //// //// if(value != rtsEnable) //// { //// bool fRtsControlOld = dcb.Flags_RTSCONTROL; //// //// rtsEnable = value; //// dcb.Flags_RTSCONTROL = value; //// //// if(UnsafeNativeMethods.SetCommState( _handle, ref dcb ) == false) //// { //// dcb.Flags_RTSCONTROL = fRtsControlOld; //// //// // set it back to the old value on a failure //// rtsEnable = !rtsEnable; //// InternalResources.WinIOError(); //// } //// } //// } } // StopBits represented in C# as StopBits enum type and in Win32 as an integer 1, 2, or 3. public abstract StopBits StopBits { set; //// { //// //Debug.Assert( !(value < StopBits.One || value > StopBits.OnePointFive), "An invalid value was passed to StopBits" ); //// //// byte nativeValue; //// //// if (value == StopBits.One ) nativeValue = (byte)NativeMethods.ONESTOPBIT; //// else if(value == StopBits.OnePointFive) nativeValue = (byte)NativeMethods.ONE5STOPBITS; //// else nativeValue = (byte)NativeMethods.TWOSTOPBITS; //// //// if(nativeValue != dcb.StopBits) //// { //// byte stopBitsOld = dcb.StopBits; //// //// dcb.StopBits = nativeValue; //// //// if(UnsafeNativeMethods.SetCommState( _handle, ref dcb ) == false) //// { //// dcb.StopBits = stopBitsOld; //// //// InternalResources.WinIOError(); //// } //// } //// } } // note: WriteTimeout must be either SerialPort.InfiniteTimeout or POSITIVE. // a timeout of zero implies that every Write call throws an exception. //// public override int WriteTimeout //// { //// get //// { //// int timeout = commTimeouts.WriteTotalTimeoutConstant; //// //// return (timeout == 0) ? SerialPort.InfiniteTimeout : timeout; //// } //// //// set //// { //// if(value <= 0 && value != SerialPort.InfiniteTimeout) //// { //// throw new ArgumentOutOfRangeException( "WriteTimeout", SR.GetString( SR.ArgumentOutOfRange_WriteTimeout ) ); //// } //// //// if(_handle == null) //// { //// InternalResources.FileNotOpen(); //// } //// //// int oldWriteConstant = commTimeouts.WriteTotalTimeoutConstant; //// //// commTimeouts.WriteTotalTimeoutConstant = ((value == SerialPort.InfiniteTimeout) ? 0 : value); //// //// if(UnsafeNativeMethods.SetCommTimeouts( _handle, ref commTimeouts ) == false) //// { //// commTimeouts.WriteTotalTimeoutConstant = oldWriteConstant; //// //// InternalResources.WinIOError(); //// } //// } //// } // CDHolding, CtsHolding, DsrHolding query the current state of each of the carrier, the CTS pin, // and the DSR pin, respectively. Read-only. // All will throw exceptions if the port is not open. public abstract bool CDHolding { get; //// { //// int pinStatus = 0; //// //// if(UnsafeNativeMethods.GetCommModemStatus( _handle, ref pinStatus ) == false) //// { //// InternalResources.WinIOError(); //// } //// //// return (NativeMethods.MS_RLSD_ON & pinStatus) != 0; //// } } public abstract bool CtsHolding { get; //// { //// int pinStatus = 0; //// //// if(UnsafeNativeMethods.GetCommModemStatus( _handle, ref pinStatus ) == false) //// { //// InternalResources.WinIOError(); //// } //// //// return (NativeMethods.MS_CTS_ON & pinStatus) != 0; //// } } public abstract bool DsrHolding { get; //// { //// int pinStatus = 0; //// //// if(UnsafeNativeMethods.GetCommModemStatus( _handle, ref pinStatus ) == false) //// { //// InternalResources.WinIOError(); //// } //// //// return (NativeMethods.MS_DSR_ON & pinStatus) != 0; //// } } // Fills comStat structure from an unmanaged function // to determine the number of bytes waiting in the serial driver's internal receive buffer. public abstract int BytesToRead { get; //// { //// int errorCode = 0; // "ref" arguments need to have values, as opposed to "out" arguments //// //// if(UnsafeNativeMethods.ClearCommError( _handle, ref errorCode, ref comStat ) == false) //// { //// InternalResources.WinIOError(); //// } //// //// return (int)comStat.cbInQue; //// } } // Fills comStat structure from an unmanaged function // to determine the number of bytes waiting in the serial driver's internal transmit buffer. public abstract int BytesToWrite { get; //// { //// int errorCode = 0; // "ref" arguments need to be set before method invocation, as opposed to "out" arguments //// //// if(UnsafeNativeMethods.ClearCommError( _handle, ref errorCode, ref comStat ) == false) //// { //// InternalResources.WinIOError(); //// } //// //// return (int)comStat.cbOutQue; //// } } // -----------SECTION: constructor --------------------------* [MethodImpl( MethodImplOptions.InternalCall )] internal static extern SerialStream Create( string portName , int baudRate , Parity parity , int dataBits , StopBits stopBits , int readBufferSize , int writeBufferSize , int readTimeout , int writeTimeout , Handshake handshake , bool dtrEnable , bool rtsEnable , bool discardNull , byte parityReplace ); // this method is used by SerialPort upon SerialStream's creation //// [ResourceExposure( ResourceScope.Machine )] //// [ResourceConsumption( ResourceScope.Machine )] //// internal SerialStream( string portName , //// int baudRate , //// Parity parity , //// int dataBits , //// StopBits stopBits , //// int readTimeout , //// int writeTimeout , //// Handshake handshake , //// bool dtrEnable , //// bool rtsEnable , //// bool discardNull , //// byte parityReplace ) //// { //// if((portName == null) || !portName.StartsWith( "COM", StringComparison.OrdinalIgnoreCase )) //// throw new ArgumentException( "Arg_InvalidSerialPort", "portName" ); //// throw new ArgumentException( SR.GetString( SR.Arg_InvalidSerialPort ), "portName" ); //// //// //Error checking done in SerialPort. //// //// SafeFileHandle tempHandle = UnsafeNativeMethods.CreateFile( "\\\\.\\" + portName, //// NativeMethods.GENERIC_READ | NativeMethods.GENERIC_WRITE, //// 0, // comm devices must be opened w/exclusive-access //// IntPtr.Zero, // no security attributes //// UnsafeNativeMethods.OPEN_EXISTING, // comm devices must use OPEN_EXISTING //// flags, //// IntPtr.Zero // hTemplate must be NULL for comm devices //// ); //// //// if(tempHandle.IsInvalid) //// { //// InternalResources.WinIOError( portName ); //// } //// //// try //// { //// int fileType = UnsafeNativeMethods.GetFileType( tempHandle ); //// //// // Allowing FILE_TYPE_UNKNOWN for legitimate serial device such as USB to serial adapter device //// if((fileType != UnsafeNativeMethods.FILE_TYPE_CHAR) && (fileType != UnsafeNativeMethods.FILE_TYPE_UNKNOWN)) //// throw new ArgumentException( "Arg_InvalidSerialPort", "portName" ); //// throw new ArgumentException( SR.GetString( SR.Arg_InvalidSerialPort ), "portName" ); //// //// _handle = tempHandle; //// //// // set properties of the stream that exist as members in SerialStream //// this.portName = portName; //// this.handshake = handshake; //// this.parityReplace = parityReplace; //// //// tempBuf = new byte[1]; // used in ReadByte() //// //// // Fill COMMPROPERTIES struct, which has our maximum allowed baud rate. //// // Call a serial specific API such as GetCommModemStatus which would fail //// // in case the device is not a legitimate serial device. For instance, //// // some illegal FILE_TYPE_UNKNOWN device (or) "LPT1" on Win9x //// // trying to pass for serial will be caught here. GetCommProperties works //// // fine for "LPT1" on Win9x, so that alone can't be relied here to //// // detect non serial devices. //// //// commProp = new UnsafeNativeMethods.COMMPROP(); //// int pinStatus = 0; //// //// if(!UnsafeNativeMethods.GetCommProperties ( _handle, ref commProp ) || //// !UnsafeNativeMethods.GetCommModemStatus( _handle, ref pinStatus ) ) //// { //// // If the portName they have passed in is a FILE_TYPE_CHAR but not a serial port, //// // for example "LPT1", this API will fail. For this reason we handle the error message specially. //// int errorCode = Marshal.GetLastWin32Error(); //// if((errorCode == NativeMethods.ERROR_INVALID_PARAMETER) || (errorCode == NativeMethods.ERROR_INVALID_HANDLE)) //// { //// throw new ArgumentException( SR.GetString( SR.Arg_InvalidSerialPortExtended ), "portName" ); //// } //// else //// { //// InternalResources.WinIOError( errorCode, string.Empty ); //// } //// //// InternalResources.WinIOError(); //// } //// //// if(commProp.dwMaxBaud != 0 && baudRate > commProp.dwMaxBaud) //// { //// throw new ArgumentOutOfRangeException( "baudRate", SR.GetString( SR.Max_Baud, commProp.dwMaxBaud ) ); //// } //// //// //// comStat = new UnsafeNativeMethods.COMSTAT(); //// // create internal DCB structure, initialize according to Platform SDK //// // standard: ms-help://MS.MSNDNQTR.2002APR.1003/hardware/commun_965u.htm //// dcb = new UnsafeNativeMethods.DCB(); //// //// // set constant properties of the DCB //// InitializeDCB( baudRate, parity, dataBits, stopBits, discardNull ); //// //// this.DtrEnable = dtrEnable; //// //// // query and cache the initial RtsEnable value //// // so that set_RtsEnable can do the (value != rtsEnable) optimization //// this.rtsEnable = dcb.Flags_RTSCONTROL; //// //// // now set this.RtsEnable to the specified value. //// // Handshake takes precedence, this will be a nop if //// // handshake is either RequestToSend or RequestToSendXOnXOff //// if((handshake != Handshake.RequestToSend && handshake != Handshake.RequestToSendXOnXOff)) //// { //// this.RtsEnable = rtsEnable; //// } //// //// // NOTE: this logic should match what is in the ReadTimeout property //// if(readTimeout == 0) //// { //// commTimeouts.ReadTotalTimeoutConstant = 0; //// commTimeouts.ReadTotalTimeoutMultiplier = 0; //// commTimeouts.ReadIntervalTimeout = NativeMethods.MAXDWORD; //// } //// else if(readTimeout == SerialPort.InfiniteTimeout) //// { //// // SetCommTimeouts doesn't like a value of -1 for some reason, so //// // we'll use -2(infiniteTimeoutConst) to represent infinite. //// commTimeouts.ReadTotalTimeoutConstant = infiniteTimeoutConst; //// commTimeouts.ReadTotalTimeoutMultiplier = NativeMethods.MAXDWORD; //// commTimeouts.ReadIntervalTimeout = NativeMethods.MAXDWORD; //// } //// else //// { //// commTimeouts.ReadTotalTimeoutConstant = readTimeout; //// commTimeouts.ReadTotalTimeoutMultiplier = NativeMethods.MAXDWORD; //// commTimeouts.ReadIntervalTimeout = NativeMethods.MAXDWORD; //// } //// //// commTimeouts.WriteTotalTimeoutMultiplier = 0; //// commTimeouts.WriteTotalTimeoutConstant = ((writeTimeout == SerialPort.InfiniteTimeout) ? 0 : writeTimeout); //// //// // set unmanaged timeout structure //// if(UnsafeNativeMethods.SetCommTimeouts( _handle, ref commTimeouts ) == false) //// { //// InternalResources.WinIOError(); //// } //// //// // monitor all events except TXEMPTY //// UnsafeNativeMethods.SetCommMask( _handle, NativeMethods.ALL_EVENTS ); //// //// // prep. for starting event cycle. //// eventRunner = new EventLoopRunner( this ); //// Thread eventLoopThread = new Thread( new ThreadStart( eventRunner.WaitForCommEvent ) ); //// eventLoopThread.IsBackground = true; //// eventLoopThread.Start(); //// } //// catch //// { //// // if there are any exceptions after the call to CreateFile, we need to be sure to close the //// // handle before we let them continue up. //// tempHandle.Close(); //// _handle = null; //// throw; //// } //// } ~SerialStream() { Dispose( false ); } //// protected override void Dispose( bool disposing ) //// { //// // Signal the other side that we're closing. Should do regardless of whether we've called //// // Close() or not Dispose() //// if(_handle != null && !_handle.IsInvalid) //// { //// try //// { //// eventRunner.endEventLoop = true; //// Thread.MemoryBarrier(); //// //// // turn off all events and signal WaitCommEvent //// UnsafeNativeMethods.SetCommMask( _handle, 0 ); //// if(!UnsafeNativeMethods.EscapeCommFunction( _handle, NativeMethods.CLRDTR )) //// { //// // should not happen //// InternalResources.WinIOError(); //// } //// //// if(!_handle.IsClosed) //// Flush(); //// //// eventRunner.waitCommEventWaitHandle.Set(); //// DiscardInBuffer(); //// DiscardOutBuffer(); //// //// if(disposing && eventRunner != null) //// { //// // now we need to wait for the event loop to tell us it's done. Without this we could get into a race where the //// // event loop kept the port open even after Dispose ended. //// eventRunner.eventLoopEndedSignal.WaitOne(); //// eventRunner.eventLoopEndedSignal.Close(); //// eventRunner.waitCommEventWaitHandle.Close(); //// } //// } //// finally //// { //// // If we are disposing synchronize closing with raising SerialPort events //// if(disposing) //// { //// lock(this) //// { //// _handle.Close(); //// _handle = null; //// } //// } //// else //// { //// _handle.Close(); //// _handle = null; //// } //// base.Dispose( disposing ); //// } //// } //// } // -----SECTION: all public methods ------------------* //// // User-accessible async read method. Returns SerialStreamAsyncResult : IAsyncResult //// [HostProtection( ExternalThreading = true )] //// public override IAsyncResult BeginRead( byte[] array , //// int offset , //// int numBytes , //// AsyncCallback userCallback , //// object stateObject ) //// { //// if(array == null) //// { //// throw new ArgumentNullException( "array" ); //// } //// //// if(offset < 0) //// { //// throw new ArgumentOutOfRangeException( "offset", SR.GetString( SR.ArgumentOutOfRange_NeedNonNegNumRequired ) ); //// } //// //// if(numBytes < 0) //// { //// throw new ArgumentOutOfRangeException( "numBytes", SR.GetString( SR.ArgumentOutOfRange_NeedNonNegNumRequired ) ); //// } //// //// if(array.Length - offset < numBytes) //// { //// throw new ArgumentException( SR.GetString( SR.Argument_InvalidOffLen ) ); //// } //// //// if(_handle == null) //// { //// InternalResources.FileNotOpen(); //// } //// //// int oldtimeout = ReadTimeout; //// this.ReadTimeout = SerialPort.InfiniteTimeout; //// IAsyncResult result; //// try //// { //// result = base.BeginRead( array, offset, numBytes, userCallback, stateObject ); //// } //// finally //// { //// ReadTimeout = oldtimeout; //// } //// return result; //// } //// // User-accessible async write method. Returns SerialStreamAsyncResult : IAsyncResult //// // Throws an exception if port is in break state. //// [HostProtection( ExternalThreading = true )] //// public override IAsyncResult BeginWrite( byte[] array , //// int offset , //// int numBytes , //// AsyncCallback userCallback , //// object stateObject ) //// { //// if(inBreak) //// { //// throw new InvalidOperationException( SR.GetString( SR.In_Break_State ) ); //// } //// //// if(array == null) //// { //// throw new ArgumentNullException( "array" ); //// } //// //// if(offset < 0) //// { //// throw new ArgumentOutOfRangeException( "offset", SR.GetString( SR.ArgumentOutOfRange_NeedNonNegNumRequired ) ); //// } //// //// if(numBytes < 0) //// { //// throw new ArgumentOutOfRangeException( "numBytes", SR.GetString( SR.ArgumentOutOfRange_NeedNonNegNumRequired ) ); //// } //// //// if(array.Length - offset < numBytes) //// { //// throw new ArgumentException( SR.GetString( SR.Argument_InvalidOffLen ) ); //// } //// //// if(_handle == null) //// { //// InternalResources.FileNotOpen(); //// } //// //// int oldtimeout = WriteTimeout; //// WriteTimeout = SerialPort.InfiniteTimeout; //// IAsyncResult result; //// try //// { //// result = base.BeginWrite( array, offset, numBytes, userCallback, stateObject ); //// } //// finally //// { //// WriteTimeout = oldtimeout; //// } //// return result; //// } // Uses Win32 method to dump out the receive buffer; analagous to MSComm's "InBufferCount = 0" public abstract void DiscardInBuffer(); //// { //// if(UnsafeNativeMethods.PurgeComm( _handle, NativeMethods.PURGE_RXCLEAR | NativeMethods.PURGE_RXABORT ) == false) //// { //// InternalResources.WinIOError(); //// } //// } // Uses Win32 method to dump out the xmit buffer; analagous to MSComm's "OutBufferCount = 0" public abstract void DiscardOutBuffer(); //// { //// if(UnsafeNativeMethods.PurgeComm( _handle, NativeMethods.PURGE_TXCLEAR | NativeMethods.PURGE_TXABORT ) == false) //// { //// InternalResources.WinIOError(); //// } //// } //// // Async companion to BeginRead. //// // Note, assumed IAsyncResult argument is of derived type SerialStreamAsyncResult, //// // and throws an exception if untrue. //// public override int EndRead( IAsyncResult asyncResult ) //// { //// return base.EndRead( asyncResult ); //// } //// // Async companion to BeginWrite. //// // Note, assumed IAsyncResult argument is of derived type SerialStreamAsyncResult, //// // and throws an exception if untrue. //// // Also fails if called in port's break state. //// public unsafe override void EndWrite( IAsyncResult asyncResult ) //// { //// base.EndWrite( asyncResult ); //// } //// // Flush dumps the contents of the serial driver's internal read and write buffers. //// // We actually expose the functionality for each, but fulfilling Stream's contract //// // requires a Flush() method. Fails if handle closed. //// // Note: Serial driver's write buffer is *already* attempting to write it, so we can only wait until it finishes. //// public override void Flush() //// { //// if(_handle == null) //// { //// throw new ObjectDisposedException( SR.GetString( SR.Port_not_open ) ); //// } //// //// UnsafeNativeMethods.FlushFileBuffers( _handle ); //// } // Blocking read operation, returning the number of bytes read from the stream. public override int Read( [In, Out] byte[] array , int offset , int count ) { return Read( array, offset, count, ReadTimeout ); } public abstract int Read( [In, Out] byte[] array , int offset , int count , int timeout ); //// { //// if(array == null) //// { //// throw new ArgumentNullException( "array", SR.GetString( SR.ArgumentNull_Buffer ) ); //// } //// //// if(offset < 0) //// { //// throw new ArgumentOutOfRangeException( "offset", SR.GetString( SR.ArgumentOutOfRange_NeedNonNegNumRequired ) ); //// } //// //// if(count < 0) //// { //// throw new ArgumentOutOfRangeException( "count", SR.GetString( SR.ArgumentOutOfRange_NeedNonNegNumRequired ) ); //// } //// //// if(array.Length - offset < count) //// { //// throw new ArgumentException( SR.GetString( SR.Argument_InvalidOffLen ) ); //// } //// //// if(count == 0) //// { //// return 0; // return immediately if no bytes requested; no need for overhead. //// } //// //// //Debug.Assert( timeout == SerialPort.InfiniteTimeout || timeout >= 0, "Serial Stream Read - called with timeout " + timeout ); //// //// // Check to see we have no handle-related error, since the port's always supposed to be open. //// if(_handle == null) InternalResources.FileNotOpen(); //// //// int numBytes = 0; //// int hr; //// //// numBytes = ReadFileNative( array, offset, count, null, out hr ); //// if(numBytes == -1) //// { //// InternalResources.WinIOError(); //// } //// //// if(numBytes == 0) //// { //// throw new TimeoutException(); //// } //// //// return numBytes; //// } public override int ReadByte() { return ReadByte( ReadTimeout ); } public abstract int ReadByte( int timeout ); //// { //// if(_handle == null) //// { //// InternalResources.FileNotOpen(); //// } //// //// int numBytes = 0; //// int hr; //// //// numBytes = ReadFileNative( tempBuf, 0, 1, null, out hr ); //// if(numBytes == -1) //// { //// InternalResources.WinIOError(); //// } //// //// if(numBytes == 0) //// { //// throw new TimeoutException(); //// } //// //// return tempBuf[0]; //// } public override long Seek( long offset, SeekOrigin origin ) { #if EXCEPTION_STRINGS throw new NotSupportedException( "NotSupported_UnseekableStream" ); #else throw new NotSupportedException(); #endif //// throw new NotSupportedException( SR.GetString( SR.NotSupported_UnseekableStream ) ); } public override void SetLength( long value ) { #if EXCEPTION_STRINGS throw new NotSupportedException( "NotSupported_UnseekableStream" ); #else throw new NotSupportedException(); #endif //// throw new NotSupportedException( SR.GetString( SR.NotSupported_UnseekableStream ) ); } public override void Write( byte[] array , int offset , int count ) { Write( array, offset, count, WriteTimeout ); } public abstract void Write( byte[] array , int offset , int count , int timeout ); //// { //// if(inBreak) //// { //// throw new InvalidOperationException( SR.GetString( SR.In_Break_State ) ); //// } //// //// if(array == null) //// { //// throw new ArgumentNullException( "buffer", SR.GetString( SR.ArgumentNull_Array ) ); //// } //// //// if(offset < 0) //// { //// throw new ArgumentOutOfRangeException( "offset", SR.GetString( SR.ArgumentOutOfRange_NeedPosNum ) ); //// } //// //// if(count < 0) //// { //// throw new ArgumentOutOfRangeException( "count", SR.GetString( SR.ArgumentOutOfRange_NeedPosNum ) ); //// } //// //// if(count == 0) //// { //// return; // no need to expend overhead in creating asyncResult, etc. //// } //// //// if(array.Length - offset < count) //// { //// throw new ArgumentException( "count", SR.GetString( SR.ArgumentOutOfRange_OffsetOut ) ); //// } //// //// //Debug.Assert( timeout == SerialPort.InfiniteTimeout || timeout >= 0, "Serial Stream Write - write timeout is " + timeout ); //// //// // check for open handle, though the port is always supposed to be open //// if(_handle == null) InternalResources.FileNotOpen(); //// //// int numBytes; //// int hr; //// //// numBytes = WriteFileNative( array, offset, count, null, out hr ); //// if(numBytes == -1) //// { //// InternalResources.WinIOError(); //// } //// //// if(numBytes == 0) //// { //// throw new TimeoutException( SR.GetString( SR.Write_timed_out ) ); //// } //// } // use default timeout as argument to WriteByte override with timeout arg public override void WriteByte( byte value ) { WriteByte( value, WriteTimeout ); } public abstract void WriteByte( byte value , int timeout ); //// { //// if(inBreak) //// { //// throw new InvalidOperationException( SR.GetString( SR.In_Break_State ) ); //// } //// //// if(_handle == null) //// { //// InternalResources.FileNotOpen(); //// } //// //// tempBuf[0] = value; //// //// //// int numBytes; //// int hr; //// //// numBytes = WriteFileNative( tempBuf, 0, 1, null, out hr ); //// if(numBytes == -1) //// { //// InternalResources.WinIOError(); //// } //// //// if(numBytes == 0) //// { //// throw new TimeoutException( SR.GetString( SR.Write_timed_out ) ); //// } //// //// return; //// } // --------SUBSECTION: internal-use methods ----------------------* // ------ internal DCB-supporting methods ------- * //// // Initializes unmananged DCB struct, to be called after opening communications resource. //// // assumes we have already: baudRate, parity, dataBits, stopBits //// // should only be called in SerialStream(...) //// private void InitializeDCB( int baudRate , //// Parity parity , //// int dataBits , //// StopBits stopBits , //// bool discardNull ) //// { //// // first get the current dcb structure setup //// if(UnsafeNativeMethods.GetCommState( _handle, ref dcb ) == false) //// { //// InternalResources.WinIOError(); //// } //// //// // set parameterized properties //// dcb.BaudRate = (uint)baudRate; //// dcb.ByteSize = (byte)dataBits; //// //// //// switch(stopBits) //// { //// case StopBits.One: //// dcb.StopBits = NativeMethods.ONESTOPBIT; //// break; //// case StopBits.OnePointFive: //// dcb.StopBits = NativeMethods.ONE5STOPBITS; //// break; //// case StopBits.Two: //// dcb.StopBits = NativeMethods.TWOSTOPBITS; //// break; //// default: //// //Debug.Assert( false, "Invalid value for stopBits" ); //// break; //// } //// //// dcb.Parity = (byte)parity; //// // SetDcbFlag, GetDcbFlag expose access to each of the relevant bits of the 32-bit integer //// // storing all flags of the DCB. C# provides no direct means of manipulating bit fields, so //// // this is the solution. //// dcb.Flags_PARITY = (parity != Parity.None); //// //// dcb.Flags_BINARY = true; // always true for communications resources //// //// // set DCB fields implied by default and the arguments given. //// // Boolean fields in C# must become 1, 0 to properly set the bit flags in the unmanaged DCB struct //// //// dcb.Flags_OUTXCTSFLOW = (handshake == Handshake.RequestToSend || handshake == Handshake.RequestToSendXOnXOff); //// dcb.Flags_OUTXDSRFLOW = false; // dsrTimeout is always set to 0. //// dcb.Flags_DTRCONTROL = false; //// dcb.Flags_DSRSENSITIVITY = false; //// dcb.Flags_INX = (handshake == Handshake.XOnXOff || handshake == Handshake.RequestToSendXOnXOff); //// dcb.Flags_OUTX = (handshake == Handshake.XOnXOff || handshake == Handshake.RequestToSendXOnXOff); //// //// // if no parity, we have no error character (i.e. ErrorChar = '\0' or null character) //// if(parity != Parity.None) //// { //// dcb.Flags_ERRORCHAR = (parityReplace != '\0'); //// dcb.ErrorChar = parityReplace; //// } //// else //// { //// dcb.Flags_ERRORCHAR = false; //// dcb.ErrorChar = (byte)'\0'; //// } //// //// // this method only runs once in the constructor, so we only have the default value to use. //// // Later the user may change this via the NullDiscard property. //// dcb.Flags_NULL = discardNull; //// //// //// // Setting RTS control, which is RTS_CONTROL_HANDSHAKE if RTS / RTS-XOnXOff handshaking //// // used, RTS_ENABLE (RTS pin used during operation) if rtsEnable true but XOnXoff / No handshaking //// // used, and disabled otherwise. //// if(handshake == Handshake.RequestToSend || //// handshake == Handshake.RequestToSendXOnXOff ) //// { //// dcb.Flags_RTSCONTROL = true; //// } //// else //// { //// dcb.Flags_RTSCONTROL = false; //// } //// //// dcb.XonChar = NativeMethods.DEFAULTXONCHAR; // may be exposed later but for now, constant //// dcb.XoffChar = NativeMethods.DEFAULTXOFFCHAR; //// //// // minimum number of bytes allowed in each buffer before flow control activated //// // heuristically, this has been set at 1/4 of the buffer size //// dcb.XonLim = dcb.XoffLim = (ushort)(commProp.dwCurrentRxQueue / 4); //// //// dcb.EofChar = NativeMethods.EOFCHAR; //// //// //OLD MSCOMM: dcb.EvtChar = (byte) 0; //// // now changed to make use of RXFlag WaitCommEvent event => Eof WaitForCommEvent event //// dcb.EvtChar = NativeMethods.EOFCHAR; //// //// // set DCB structure //// if(UnsafeNativeMethods.SetCommState( _handle, ref dcb ) == false) //// { //// InternalResources.WinIOError(); //// } //// } // ----SUBSECTION: internal methods supporting public read/write methods-------* // ----SECTION: internal classes --------* //// internal sealed class EventLoopRunner //// { //// private WeakReference streamWeakReference; //// internal ManualResetEvent eventLoopEndedSignal = new ManualResetEvent( false ); //// internal ManualResetEvent waitCommEventWaitHandle = new ManualResetEvent( false ); //// private object handle; //// internal bool endEventLoop; //// //// WaitCallback callErrorEvents; //// WaitCallback callReceiveEvents; //// WaitCallback callPinEvents; //// //// internal EventLoopRunner( SerialStream stream ) //// { //// handle = stream._handle; //// streamWeakReference = new WeakReference( stream ); //// //// callErrorEvents = new WaitCallback( CallErrorEvents ); //// callReceiveEvents = new WaitCallback( CallReceiveEvents ); //// callPinEvents = new WaitCallback( CallPinEvents ); //// } //// //// internal bool ShutdownLoop //// { //// get //// { //// return endEventLoop; //// } //// } //// //// // This is the blocking method that waits for an event to occur. It wraps the SDK's WaitCommEvent function. //// [ResourceExposure( ResourceScope.None )] //// [ResourceConsumption( ResourceScope.Machine, ResourceScope.Machine )] //// internal unsafe void WaitForCommEvent() //// { //// int unused = 0; //// bool doCleanup = false; //// NativeOverlapped* intOverlapped = null; //// while(!ShutdownLoop) //// { //// SerialStreamAsyncResult asyncResult = null; //// if(isAsync) //// { //// asyncResult = new SerialStreamAsyncResult(); //// asyncResult._userCallback = null; //// asyncResult._userStateObject = null; //// asyncResult._isWrite = false; //// //// // we're going to use _numBytes for something different in this loop. In this case, both //// // freeNativeOverlappedCallback and this thread will decrement that value. Whichever one decrements it //// // to zero will be the one to free the native overlapped. This guarantees the overlapped gets freed //// // after both the callback and GetOverlappedResult have had a chance to use it. //// asyncResult._numBytes = 2; //// asyncResult._waitHandle = waitCommEventWaitHandle; //// //// waitCommEventWaitHandle.Reset(); //// Overlapped overlapped = new Overlapped( 0, 0, waitCommEventWaitHandle.SafeWaitHandle.DangerousGetHandle(), asyncResult ); //// // Pack the Overlapped class, and store it in the async result //// intOverlapped = overlapped.Pack( freeNativeOverlappedCallback, null ); //// } //// //// int eventsOccurred = 0; //// //// if(UnsafeNativeMethods.WaitCommEvent( handle, ref eventsOccurred, intOverlapped ) == false) //// { //// int hr = Marshal.GetLastWin32Error(); //// if(hr == NativeMethods.ERROR_ACCESS_DENIED) //// { //// doCleanup = true; //// break; //// } //// if(hr == NativeMethods.ERROR_IO_PENDING) //// { //// //Debug.Assert( isAsync, "The port is not open for async, so we should not get ERROR_IO_PENDING from WaitCommEvent" ); //// int error; //// //// // if we get IO pending, MSDN says we should wait on the WaitHandle, then call GetOverlappedResult //// // to get the results of WaitCommEvent. //// bool success = waitCommEventWaitHandle.WaitOne(); //// //Debug.Assert( success, "waitCommEventWaitHandle.WaitOne() returned error " + Marshal.GetLastWin32Error() ); //// //// do //// { //// // NOTE: GetOverlappedResult will modify the original pointer passed into WaitCommEvent. //// success = UnsafeNativeMethods.GetOverlappedResult( handle, intOverlapped, ref unused, false ); //// error = Marshal.GetLastWin32Error(); //// } //// while(error == NativeMethods.ERROR_IO_INCOMPLETE && !ShutdownLoop && !success); //// //// if(!success) //// { //// // Ignore ERROR_IO_INCOMPLETE and ERROR_INVALID_PARAMETER, because there's a chance we'll get //// // one of those while shutting down //// if(!((error == NativeMethods.ERROR_IO_INCOMPLETE || error == NativeMethods.ERROR_INVALID_PARAMETER) && ShutdownLoop)) //// //Debug.Assert( false, "GetOverlappedResult returned error, we might leak intOverlapped memory" + error.ToString( CultureInfo.InvariantCulture ) ); //// } //// } //// else if(hr != NativeMethods.ERROR_INVALID_PARAMETER) //// { //// // ignore ERROR_INVALID_PARAMETER errors. WaitCommError seems to return this //// // when SetCommMask is changed while it's blocking (like we do in Dispose()) //// //Debug.Assert( false, "WaitCommEvent returned error " + hr ); //// } //// } //// //// if(!ShutdownLoop) //// CallEvents( eventsOccurred ); //// //// if(isAsync) //// { //// //// if(Interlocked.Decrement( ref asyncResult._numBytes ) == 0) //// Overlapped.Free( intOverlapped ); //// } //// } //// if(doCleanup) //// { //// // the rest will be handled in Dispose() //// endEventLoop = true; //// Overlapped.Free( intOverlapped ); //// } //// eventLoopEndedSignal.Set(); //// } //// //// private unsafe void FreeNativeOverlappedCallback( uint errorCode, uint numBytes, NativeOverlapped* pOverlapped ) //// { //// // Unpack overlapped //// Overlapped overlapped = Overlapped.Unpack( pOverlapped ); //// //// // Extract the async result from overlapped structure //// SerialStreamAsyncResult asyncResult = //// (SerialStreamAsyncResult)overlapped.AsyncResult; //// //// if(Interlocked.Decrement( ref asyncResult._numBytes ) == 0) //// Overlapped.Free( pOverlapped ); //// } //// //// private void CallEvents( int nativeEvents ) //// { //// // EV_ERR includes only CE_FRAME, CE_OVERRUN, and CE_RXPARITY //// // To catch errors such as CE_RXOVER, we need to call CleanCommErrors bit more regularly. //// // EV_RXCHAR is perhaps too loose an event to look for overflow errors but a safe side to err... //// if((nativeEvents & (NativeMethods.EV_ERR | NativeMethods.EV_RXCHAR)) != 0) //// { //// int errors = 0; //// if(UnsafeNativeMethods.ClearCommError( handle, ref errors, IntPtr.Zero ) == false) //// { //// //// //InternalResources.WinIOError(); //// //// // We don't want to throw an exception from the background thread which is un-catchable and hence tear down the process. //// // At present we don't have a first class event that we can raise for this class of fatal errors. One possibility is //// // to overload SeralErrors event to include another enum (perhaps CE_IOE) that we can use for this purpose. //// // In the absene of that, it is better to eat this error silently than tearing down the process (lesser of the evil). //// // This uncleared comm error will most likely blow up when the device is accessed by other APIs (such as Read) on the //// // main thread and hence become known. It is bit roundabout but acceptable. //// // //// // Shutdown the event runner loop (probably bit drastic but we did come across a fatal error). //// // Defer actual dispose chores until finalization though. //// endEventLoop = true; //// Thread.MemoryBarrier(); //// return; //// } //// //// errors = errors & errorEvents; //// // TODO: what about CE_BREAK? Is this the same as EV_BREAK? EV_BREAK happens as one of the pin events, //// // but CE_BREAK is returned from ClreaCommError. //// // TODO: what about other error conditions not covered by the enum? Should those produce some other error? //// //// if(errors != 0) //// { //// ThreadPool.QueueUserWorkItem( callErrorEvents, errors ); //// } //// } //// //// // now look for pin changed and received events. //// if((nativeEvents & pinChangedEvents) != 0) //// { //// ThreadPool.QueueUserWorkItem( callPinEvents, nativeEvents ); //// } //// //// if((nativeEvents & receivedEvents) != 0) //// { //// ThreadPool.QueueUserWorkItem( callReceiveEvents, nativeEvents ); //// } //// } //// //// //// private void CallErrorEvents( object state ) //// { //// int errors = (int)state; //// SerialStream stream = (SerialStream)streamWeakReference.Target; //// if(stream == null) //// return; //// //// if(stream.ErrorReceived != null) //// { //// if((errors & (int)SerialError.TXFull) != 0) //// stream.ErrorReceived( stream, new SerialErrorReceivedEventArgs( SerialError.TXFull ) ); //// //// if((errors & (int)SerialError.RXOver) != 0) //// stream.ErrorReceived( stream, new SerialErrorReceivedEventArgs( SerialError.RXOver ) ); //// //// if((errors & (int)SerialError.Overrun) != 0) //// stream.ErrorReceived( stream, new SerialErrorReceivedEventArgs( SerialError.Overrun ) ); //// //// if((errors & (int)SerialError.RXParity) != 0) //// stream.ErrorReceived( stream, new SerialErrorReceivedEventArgs( SerialError.RXParity ) ); //// //// if((errors & (int)SerialError.Frame) != 0) //// stream.ErrorReceived( stream, new SerialErrorReceivedEventArgs( SerialError.Frame ) ); //// } //// //// stream = null; //// } //// //// private void CallReceiveEvents( object state ) //// { //// int nativeEvents = (int)state; //// SerialStream stream = (SerialStream)streamWeakReference.Target; //// if(stream == null) //// return; //// //// if(stream.DataReceived != null) //// { //// if((nativeEvents & (int)SerialData.Chars) != 0) //// stream.DataReceived( stream, new SerialDataReceivedEventArgs( SerialData.Chars ) ); //// if((nativeEvents & (int)SerialData.Eof) != 0) //// stream.DataReceived( stream, new SerialDataReceivedEventArgs( SerialData.Eof ) ); //// } //// //// stream = null; //// } //// //// private void CallPinEvents( object state ) //// { //// int nativeEvents = (int)state; //// //// SerialStream stream = (SerialStream)streamWeakReference.Target; //// if(stream == null) //// return; //// //// if(stream.PinChanged != null) //// { //// if((nativeEvents & (int)SerialPinChange.CtsChanged) != 0) //// stream.PinChanged( stream, new SerialPinChangedEventArgs( SerialPinChange.CtsChanged ) ); //// //// if((nativeEvents & (int)SerialPinChange.DsrChanged) != 0) //// stream.PinChanged( stream, new SerialPinChangedEventArgs( SerialPinChange.DsrChanged ) ); //// //// if((nativeEvents & (int)SerialPinChange.CDChanged) != 0) //// stream.PinChanged( stream, new SerialPinChangedEventArgs( SerialPinChange.CDChanged ) ); //// //// if((nativeEvents & (int)SerialPinChange.Ring) != 0) //// stream.PinChanged( stream, new SerialPinChangedEventArgs( SerialPinChange.Ring ) ); //// //// if((nativeEvents & (int)SerialPinChange.Break) != 0) //// stream.PinChanged( stream, new SerialPinChangedEventArgs( SerialPinChange.Break ) ); //// } //// //// stream = null; //// } //// //// } //// // This is an internal object implementing IAsyncResult with fields //// // for all of the relevant data necessary to complete the IO operation. //// // This is used by AsyncFSCallback and all async methods. //// unsafe internal sealed class SerialStreamAsyncResult : IAsyncResult //// { //// // User code callback //// internal AsyncCallback _userCallback; //// //// internal Object _userStateObject; //// //// internal bool _isWrite; // Whether this is a read or a write //// internal bool _isComplete; //// internal bool _completedSynchronously; // Which thread called callback //// //// internal ManualResetEvent _waitHandle; //// internal int _EndXxxCalled; // Whether we've called EndXxx already. //// internal int _numBytes; // number of bytes read OR written //// internal int _errorCode; //// internal NativeOverlapped* _overlapped; //// //// public Object AsyncState //// { //// get { return _userStateObject; } //// } //// //// public bool IsCompleted //// { //// get { return _isComplete; } //// } //// //// public WaitHandle AsyncWaitHandle //// { //// get //// { //// /* //// // Consider uncommenting this someday soon - the EventHandle //// // in the Overlapped struct is really useless half of the //// // time today since the OS doesn't signal it. If users call //// // EndXxx after the OS call happened to complete, there's no //// // reason to create a synchronization primitive here. Fixing //// // this will save us some perf, assuming we can correctly //// // initialize the ManualResetEvent. //// if (_waitHandle == null) { //// ManualResetEvent mre = new ManualResetEvent(false); //// if (_overlapped != null && _overlapped->EventHandle != IntPtr.Zero) //// mre.Handle = _overlapped->EventHandle; //// if (_isComplete) //// mre.Set(); //// _waitHandle = mre; //// } //// */ //// return _waitHandle; //// } //// } //// //// // Returns true iff the user callback was called by the thread that //// // called BeginRead or BeginWrite. If we use an async delegate or //// // threadpool thread internally, this will be false. This is used //// // by code to determine whether a successive call to BeginRead needs //// // to be done on their main thread or in their callback to avoid a //// // stack overflow on many reads or writes. //// public bool CompletedSynchronously //// { //// get { return _completedSynchronously; } //// } //// } } } ================================================ FILE: Zelig/Zelig/RunTime/Framework/system/System/IO/Ports/StopBits.cs ================================================ // ==++== // // Copyright (c) Microsoft Corporation. All rights reserved. // // ==--== /*============================================================ ** ** Type: System.IO.Ports.StopBits ** ** Purpose: StopBits enum type defined ** ** Date: August 2002 ** ===========================================================*/ namespace System.IO.Ports { public enum StopBits { None = 1, //Default is 1 bit One = 1, Two = 2, OnePointFive = 3, } } ================================================ FILE: Zelig/Zelig/RunTime/Framework/system/System/Net/DNS.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // namespace System.Net { using System.Net.Sockets; using NativeSocket = Microsoft.Llilum.Net.SocketNative; public static class Dns { public static IPHostEntry GetHostEntry(string hostNameOrAddress) { //Do we need to try to pase this as an Address???? string canonicalName; byte[][] addresses; NativeSocket.getaddrinfo(hostNameOrAddress, out canonicalName, out addresses); int cAddresses = addresses.Length; IPAddress[] ipAddresses = new IPAddress[cAddresses]; IPHostEntry ipHostEntry = new IPHostEntry(); for (int i = 0; i < cAddresses; i++) { byte[] address = addresses[i]; SocketAddress sockAddress = new SocketAddress(address); AddressFamily family; family = (AddressFamily)address[1]; if (family == AddressFamily.InterNetwork) { //This only works with IPv4 addresses uint ipAddr = 0; ipAddr |= ((uint)address[7] << 24) & 0xFF000000; ipAddr |= ((uint)address[6] << 16) & 0x00FF0000; ipAddr |= ((uint)address[5] << 8) & 0x0000FF00; ipAddr |= ((uint)address[4]) & 0x000000FF; ipAddresses[i] = new IPAddress((long)ipAddr); } } ipHostEntry.hostName = canonicalName; ipHostEntry.addressList = ipAddresses; return ipHostEntry; } } } ================================================ FILE: Zelig/Zelig/RunTime/Framework/system/System/Net/EndPoint.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // namespace System.Net { using System; // Generic abstraction to identify network addresses /// /// /// Identifies a network address. /// /// [Serializable] public abstract class EndPoint { public abstract SocketAddress Serialize(); public abstract EndPoint Create(SocketAddress socketAddress); }; // abstract class EndPoint } // namespace System.Net ================================================ FILE: Zelig/Zelig/RunTime/Framework/system/System/Net/IPAddress.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // namespace System.Net { using Runtime.CompilerServices; using System.Net.Sockets; /// /// Provides an internet protocol (IP) address. /// [Serializable] public class IPAddress { public static readonly IPAddress Any = new IPAddress(0x0000000000000000); public static readonly IPAddress Loopback = new IPAddress(0x000000000100007F); //--// internal long m_Address; public IPAddress(long newAddress) { if (newAddress < 0 || newAddress > 0x00000000FFFFFFFF) { // BUG: This always throws. Needs investigation //throw new ArgumentOutOfRangeException(); } m_Address = newAddress; } public IPAddress(byte[] newAddressBytes) : this(((((newAddressBytes[3] << 0x18) | (newAddressBytes[2] << 0x10)) | (newAddressBytes[1] << 0x08)) | newAddressBytes[0]) & ((long)0xFFFFFFFF)) { } public override bool Equals(object obj) { IPAddress addr = obj as IPAddress; if (obj == null) return false; return this.m_Address == addr.m_Address; } public override int GetHashCode() { return (int)this.m_Address; } public byte[] GetAddressBytes() { return new byte[] { (byte)(m_Address), (byte)(m_Address >> 8), (byte)(m_Address >> 16), (byte)(m_Address >> 24) }; } public AddressFamily AddressFamily { get { return AddressFamily.InterNetwork; } } public static IPAddress Parse(string ipString) { if (ipString == null) throw new ArgumentNullException(); ulong ipAddress = 0L; int lastIndex = 0; int shiftIndex = 0; ulong mask = 0x00000000000000FF; ulong octet = 0L; int length = ipString.Length; for (int i = 0; i < length; ++i) { // Parse to '.' or end of IP address if (ipString[i] == '.' || i == length - 1) // If the IP starts with a '.' // or a segment is longer than 3 characters or shiftIndex > last bit position throw. if (i == 0 || i - lastIndex > 3 || shiftIndex > 24) { throw new ArgumentException(); } else { i = i == length - 1 ? ++i : i; octet = (ulong)(ConvertStringToInt32(ipString.Substring(lastIndex, i - lastIndex)) & 0x00000000000000FF); ipAddress = ipAddress + (ulong)((octet << shiftIndex) & mask); lastIndex = i + 1; shiftIndex = shiftIndex + 8; mask = (mask << 8); } } return new IPAddress((long)ipAddress); } public override string ToString() { return ((byte)(m_Address)).ToString() + "." + ((byte)(m_Address >> 8)).ToString() + "." + ((byte)(m_Address >> 16)).ToString() + "." + ((byte)(m_Address >> 24)).ToString(); } //--// //////////////////////////////////////////////////////////////////////////////////////// // this method ToInt32 is part of teh Convert class which we will bring over later // at that time we will get rid of this code // /// /// Converts the specified System.String representation of a number to an equivalent /// 32-bit signed integer. /// /// A System.String containing a number to convert. /// /// A 32-bit signed integer equivalent to the value of value.-or- Zero if value /// is null. /// /// /// Value represents a number less than System.Int32.MinValue or greater than /// System.Int32.MaxValue. /// /// /// The value parameter is null. /// /// /// Value does not consist of an optional sign followed by a sequence of digits /// (zero through nine). /// private static int ConvertStringToInt32(string value) { char[] num = value.ToCharArray(); int result = 0; bool isNegative = false; int signIndex = 0; if (num[0] == '-') { isNegative = true; signIndex = 1; } else if (num[0] == '+') { signIndex = 1; } int exp = 1; for (int i = num.Length - 1; i >= signIndex; i--) { if (num[i] < '0' || num[i] > '9') { throw new ArgumentException(); } result += ((num[i] - '0') * exp); exp *= 10; } return (isNegative) ? (-1 * result) : result; } // this method ToInt32 is part of teh Convert class which we will bring over later //////////////////////////////////////////////////////////////////////////////////////// public static IPAddress GetDefaultLocalAddress() { // Special conditions are implemented here because of a ptoblem with GetHostEntry // on the digi device and NetworkInterface from the emulator. // In the emulator we must use GetHostEntry. // On the device and Windows NetworkInterface works and is preferred. try { string localAddress = GetDefaultLocalAddressImpl(); if (string.IsNullOrEmpty(localAddress)) { return IPAddress.Parse(localAddress); } } catch { } try { IPAddress localAddress = null; IPHostEntry hostEntry = Dns.GetHostEntry(""); int cnt = hostEntry.AddressList.Length; for (int i = 0; i < cnt; ++i) { if ((localAddress = hostEntry.AddressList[i]) != null) { if(localAddress.m_Address != 0) { return localAddress; } } } } catch { } return IPAddress.Any; } [MethodImplAttribute(MethodImplOptions.InternalCall)] private extern static string GetDefaultLocalAddressImpl(); } // class IPAddress } // namespace System.Net ================================================ FILE: Zelig/Zelig/RunTime/Framework/system/System/Net/IPEndPoint.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // namespace System.Net { using System.Net.Sockets; [Serializable] public class IPEndPoint : EndPoint { public const int MinPort = 0x00000000; public const int MaxPort = 0x0000FFFF; private IPAddress m_Address; private int m_Port; public IPEndPoint(long address, int port) { m_Port = port; m_Address = new IPAddress(address); } public IPEndPoint(IPAddress address, int port) { m_Port = port; m_Address = address; } public IPAddress Address { get { return m_Address; } } public int Port { get { return m_Port; } } public override SocketAddress Serialize() { // create a new SocketAddress // SocketAddress socketAddress = new SocketAddress(AddressFamily.InterNetwork, SocketAddress.IPv4AddressSize); byte[] buffer = socketAddress.m_Buffer; // // populate it // buffer[2] = unchecked((byte)(this.m_Port >> 8)); buffer[3] = unchecked((byte)(this.m_Port)); buffer[4] = unchecked((byte)(this.m_Address.m_Address)); buffer[5] = unchecked((byte)(this.m_Address.m_Address >> 8)); buffer[6] = unchecked((byte)(this.m_Address.m_Address >> 16)); buffer[7] = unchecked((byte)(this.m_Address.m_Address >> 24)); return socketAddress; } public override EndPoint Create(SocketAddress socketAddress) { // strip out of SocketAddress information on the EndPoint // byte[] buf = socketAddress.m_Buffer; BCLDebug.Assert(socketAddress.Family == AddressFamily.InterNetwork, "" ); int port = (int)( (buf[2] << 8 & 0xFF00) | (buf[3]) ); long address = (long)( (buf[4] & 0x000000FF) | (buf[5] << 8 & 0x0000FF00) | (buf[6] << 16 & 0x00FF0000) | (buf[7] << 24) ) & 0x00000000FFFFFFFF; IPEndPoint created = new IPEndPoint(address, port); return created; } public override string ToString() { return m_Address.ToString() + ":" + m_Port.ToString(); } public override bool Equals(object obj) { IPEndPoint ep = obj as IPEndPoint; if (ep == null) { return false; } return ep.m_Address.Equals(m_Address) && ep.m_Port == m_Port; } public override int GetHashCode() { return this.m_Address.GetHashCode() ^ this.m_Port; } } // class IPEndPoint } // namespace System.Net ================================================ FILE: Zelig/Zelig/RunTime/Framework/system/System/Net/IPHostEntry.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // namespace System.Net { public class IPHostEntry { internal string hostName; internal IPAddress[] addressList; public string HostName { get { return hostName; } } public IPAddress[] AddressList { get { return addressList; } } } // class IPHostEntry } // namespace System.Net ================================================ FILE: Zelig/Zelig/RunTime/Framework/system/System/Net/Internal/SocketNative.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // [assembly: System.Runtime.CompilerServices.InternalsVisibleTo( "System" )] [assembly: System.Runtime.CompilerServices.InternalsVisibleTo( "Microsoft.Zelig.Runtime" )] namespace Microsoft.Llilum.Net { using System.Runtime.CompilerServices; internal static class SocketNative { public const int FIONREAD = 0x4004667F; [MethodImplAttribute(MethodImplOptions.InternalCall)] public static extern int socket(int family, int type, int protocol); [MethodImplAttribute(MethodImplOptions.InternalCall)] public static extern int bind(int socket, byte[] address); [MethodImplAttribute(MethodImplOptions.InternalCall)] public static extern int connect(int socket, byte[] address, bool fThrowOnWouldBlock); [MethodImplAttribute(MethodImplOptions.InternalCall)] public static extern int send(int socket, byte[] buf, int offset, int count, int flags, int timeout_ms); [MethodImplAttribute(MethodImplOptions.InternalCall)] public static extern int recv(int socket, byte[] buf, int offset, int count, int flags, int timeout_ms); [MethodImplAttribute(MethodImplOptions.InternalCall)] public static extern int close(int socket); [MethodImplAttribute(MethodImplOptions.InternalCall)] public static extern int listen(int socket, int backlog); [MethodImplAttribute(MethodImplOptions.InternalCall)] public static extern int accept(int socket); //Non standard non-blocking api [MethodImplAttribute(MethodImplOptions.InternalCall)] public static extern void getaddrinfo(string name, out string canonicalName, out byte[][] addresses); [MethodImplAttribute(MethodImplOptions.InternalCall)] public static extern void shutdown(int socket, int how, out int err); [MethodImplAttribute(MethodImplOptions.InternalCall)] public static extern int sendto(int socket, byte[] buf, int offset, int count, int flags, int timeout_ms, byte[] address); [MethodImplAttribute(MethodImplOptions.InternalCall)] public static extern int recvfrom(int socket, byte[] buf, int offset, int count, int flags, int timeout_ms, ref byte[] address); [MethodImplAttribute(MethodImplOptions.InternalCall)] public static extern void getpeername(int socket, out byte[] address); [MethodImplAttribute(MethodImplOptions.InternalCall)] public static extern void getsockname(int socket, out byte[] address); [MethodImplAttribute(MethodImplOptions.InternalCall)] public static extern void getsockopt(int socket, int level, int optname, byte[] optval, out uint optlen); [MethodImplAttribute(MethodImplOptions.InternalCall)] public static extern void setsockopt(int socket, int level, int optname, byte[] optval); [MethodImplAttribute(MethodImplOptions.InternalCall)] public static extern bool poll(int socket, int mode, int microSeconds); [MethodImplAttribute(MethodImplOptions.InternalCall)] public static extern void ioctl(int socket, uint cmd, ref uint arg); } } ================================================ FILE: Zelig/Zelig/RunTime/Framework/system/System/Net/SocketAddress.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // namespace System.Net { using System; using System.Net.Sockets; public class SocketAddress { internal const int IPv4AddressSize = 16; internal byte[] m_Buffer; public AddressFamily Family { get { return (AddressFamily)(m_Buffer[0] | (m_Buffer[1] << 8)); } } internal SocketAddress(byte[] address) { m_Buffer = address; } public SocketAddress(AddressFamily family, int size) { BCLDebug.Assert( size > 2, "" ); m_Buffer = new byte[size]; //(size / IntPtr.Size + 2) * IntPtr.Size];//sizeof DWORD m_Buffer[0] = unchecked((byte)((int)family )); m_Buffer[1] = unchecked((byte)((int)family >> 8)); } public int Size { get { return m_Buffer.Length; } } public byte this[int offset] { get { return m_Buffer[offset]; } set { m_Buffer[offset] = value; } } } // class SocketAddress } // namespace System.Net ================================================ FILE: Zelig/Zelig/RunTime/Framework/system/System/Net/SocketException.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // namespace System.Net.Sockets { using System; [Serializable] public class SocketException : Exception { private int _errorCode; public SocketException(SocketError errorCode) { _errorCode = (int)errorCode; } public int ErrorCode { get { return _errorCode; } } }; // class SocketException } // namespace System.Net ================================================ FILE: Zelig/Zelig/RunTime/Framework/system/System/Net/Sockets/AddressFamily.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // namespace System.Net.Sockets { /// /// /// Specifies the address families that an instance of the /// class can use. /// /// public enum AddressFamily { /// /// [To be supplied.] /// Unknown = -1, // Unknown /// /// [To be supplied.] /// Unspecified = 0, // unspecified /// /// [To be supplied.] /// Unix = 1, // local to host (pipes, portals) /// /// [To be supplied.] /// InterNetwork = 2, // internetwork: UDP, TCP, etc. /// /// [To be supplied.] /// ImpLink = 3, // arpanet imp addresses /// /// [To be supplied.] /// Pup = 4, // pup protocols: e.g. BSP /// /// [To be supplied.] /// Chaos = 5, // mit CHAOS protocols /// /// [To be supplied.] /// NS = 6, // XEROX NS protocols /// /// [To be supplied.] /// Ipx = NS, // IPX and SPX /// /// [To be supplied.] /// Iso = 7, // ISO protocols /// /// [To be supplied.] /// Osi = Iso, // OSI is ISO /// /// [To be supplied.] /// Ecma = 8, // european computer manufacturers /// /// [To be supplied.] /// DataKit = 9, // datakit protocols /// /// [To be supplied.] /// Ccitt = 10, // CCITT protocols, X.25 etc /// /// [To be supplied.] /// Sna = 11, // IBM SNA /// /// [To be supplied.] /// DecNet = 12, // DECnet /// /// [To be supplied.] /// DataLink = 13, // Direct data link interface /// /// [To be supplied.] /// Lat = 14, // LAT /// /// [To be supplied.] /// HyperChannel = 15, // NSC Hyperchannel /// /// [To be supplied.] /// AppleTalk = 16, // AppleTalk /// /// [To be supplied.] /// NetBios = 17, // NetBios-style addresses /// /// [To be supplied.] /// VoiceView = 18, // VoiceView /// /// [To be supplied.] /// FireFox = 19, // FireFox /// /// [To be supplied.] /// Banyan = 21, // Banyan /// /// [To be supplied.] /// Atm = 22, // Native ATM Services /// /// [To be supplied.] /// InterNetworkV6 = 23, // Internetwork Version 6 /// /// [To be supplied.] /// Cluster = 24, // Microsoft Wolfpack /// /// [To be supplied.] /// Ieee12844 = 25, // IEEE 1284.4 WG AF /// /// [To be supplied.] /// Irda = 26, // IrDA /// /// [To be supplied.] /// NetworkDesigners = 28, // Network Designers OSI & gateway enabled protocols /// /// [To be supplied.] /// Max = 29, // Max }; // enum AddressFamily } // namespace System.Net.Sockets ================================================ FILE: Zelig/Zelig/RunTime/Framework/system/System/Net/Sockets/NetworkStream.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // namespace System.Net.Sockets { using System.IO; using System.Net; // Summary: // Provides the underlying stream of data for network access. public class NetworkStream : Stream { // Summary: // Internal members internal Socket m_socket; // Internal Socket object protected int m_socketType; // Internal property used to store the socket type protected EndPoint m_remoteEndPoint; // Internal endpoint ref used for dgram sockets private bool m_ownsSocket; // Internal flags protected bool m_disposed; // Summary: // Creates a new instance of the System.Net.Sockets.NetworkStream class for // the specified System.Net.Sockets.Socket. // // Parameters: // socket: // The System.Net.Sockets.Socket that the System.Net.Sockets.NetworkStream will // use to send and receive data. // // Exceptions: // System.ArgumentNullException: // socket is null. // // System.IO.IOException: // socket is not connected.-or- The System.Net.Sockets.Socket.SocketType property // of socket is not System.Net.Sockets.SocketType.Stream.-or- socket is in a // nonblocking state. public NetworkStream(Socket socket) : this(socket, false) { } // // Summary: // Initializes a new instance of the System.Net.Sockets.NetworkStream class // for the specified System.Net.Sockets.Socket with the specified System.Net.Sockets.Socket // ownership. // // Parameters: // ownsSocket: // true to indicate that the System.Net.Sockets.NetworkStream will take ownership // of the System.Net.Sockets.Socket; otherwise, false. // // socket: // The System.Net.Sockets.Socket that the System.Net.Sockets.NetworkStream will // use to send and receive data. // // Exceptions: // System.IO.IOException: // socket is not connected.-or- The value of the System.Net.Sockets.Socket.SocketType // property of socket is not System.Net.Sockets.SocketType.Stream.-or- socket // is in a nonblocking state. // // System.ArgumentNullException: // socket is null. public NetworkStream(Socket socket, bool ownsSocket) { if (socket == null) throw new ArgumentNullException(); // This should throw a SocketException if not connected try { m_remoteEndPoint = socket.RemoteEndPoint; } catch (Exception e) { int errCode = (int)socket.GetSocketOption(SocketOptionLevel.Socket, SocketOptionName.Error); throw new IOException(errCode.ToString(), e); } // Set the internal socket m_socket = socket; m_socketType = (int)m_socket.GetSocketOption(SocketOptionLevel.Socket, SocketOptionName.Type); m_ownsSocket = ownsSocket; } // Summary: // Gets a value that indicates whether the System.Net.Sockets.NetworkStream // supports reading. // // Returns: // true if data can be read from the stream; otherwise, false. The default value // is true. public override bool CanRead { get { return true; } } // // Summary: // Gets a value that indicates whether the stream supports seeking. This property // is not currently supported.This property always returns false. // // Returns: // false in all cases to indicate that System.Net.Sockets.NetworkStream cannot // seek a specific location in the stream. public override bool CanSeek { get { return false; } } // // Summary: // Indicates whether timeout properties are usable for System.Net.Sockets.NetworkStream. // // Returns: // true in all cases. public override bool CanTimeout { get { return true; } } // // Summary: // Gets a value that indicates whether the System.Net.Sockets.NetworkStream // supports writing. // // Returns: // true if data can be written to the System.Net.Sockets.NetworkStream; otherwise, // false. The default value is true. public override bool CanWrite { get { return true; } } public override int ReadTimeout { get { return m_socket.ReceiveTimeout; } set { if (value == 0 || value < System.Threading.Timeout.Infinite) throw new ArgumentOutOfRangeException(); m_socket.ReceiveTimeout = value; } } public override int WriteTimeout { get { return m_socket.SendTimeout; } set { if (value == 0 || value < System.Threading.Timeout.Infinite) throw new ArgumentOutOfRangeException(); m_socket.SendTimeout = value; } } // // Summary: // Gets the length of the data available on the stream. // // Returns: // The length of the data available on the stream. // // Exceptions: // InvalidOperationException - when socket is disposed. public override long Length { get { if (m_disposed == true) throw new ObjectDisposedException( "" ); if (m_socket.m_handle == -1) throw new IOException(); return m_socket.Available; } } // // Summary: // Gets or sets the current position in the stream. This property is not currently // supported and always throws a System.NotSupportedException. // // Returns: // The current position in the stream. // // Exceptions: // System.NotSupportedException: // Any use of this property. public override long Position { get { throw new NotSupportedException(); } set { throw new NotSupportedException(); } } public virtual bool DataAvailable { get { if (m_disposed == true) throw new ObjectDisposedException( "" ); if (m_socket.m_handle == -1) throw new IOException(); return (m_socket.Available > 0); } } // // Summary: // Closes the System.Net.Sockets.NetworkStream after waiting the specified time // to allow data to be sent. // // Parameters: // timeout: // A 32-bit signed integer that specifies how long to wait to send any remaining // data before closing. // // Exceptions: // System.ArgumentOutOfRangeException: // timeout is less than -1. public void Close(int timeout) { if (timeout < -1) throw new ArgumentOutOfRangeException(); System.Threading.Thread.Sleep(timeout); Close(); } // // Summary: // Releases the unmanaged resources used by the System.Net.Sockets.NetworkStream // and optionally releases the managed resources. // // Parameters: // disposing: // true to release both managed and unmanaged resources; false to release only // unmanaged resources. protected override void Dispose(bool disposing) { if (!m_disposed) { try { if (disposing) { if (m_ownsSocket == true) m_socket.Close(); } } finally { m_disposed = true; } } } // // Summary: // Flushes data from the stream. This method is reserved for future use. public override void Flush() { } // // Summary: // Reads data from the System.Net.Sockets.NetworkStream. // // Parameters: // offset: // The location in buffer to begin storing the data to. // // size: // The number of bytes to read from the System.Net.Sockets.NetworkStream. // // buffer: // An array of type System.Byte that is the location in memory to store data // read from the System.Net.Sockets.NetworkStream. // // Returns: // The number of bytes read from the System.Net.Sockets.NetworkStream. // // Exceptions: // System.IO.IOException: // The underlying System.Net.Sockets.Socket is closed. // // System.ArgumentNullException: // buffer is null. // // System.ObjectDisposedException: // The System.Net.Sockets.NetworkStream is closed.-or- There is a failure reading // from the network. // // System.ArgumentOutOfRangeException: // offset is less than 0.-or- offset is greater than the length of buffer.-or- // size is less than 0.-or- size is greater than the length of buffer minus // the value of the offset parameter. -or-An error occurred when accessing the // socket. See the Remarks section for more information. public override int Read(byte[] buffer, int offset, int count) { if (m_disposed) throw new ObjectDisposedException( "" ); if (m_socket.m_handle == -1) throw new IOException(); if (buffer == null) throw new ArgumentNullException(); if (offset < 0 || offset > buffer.Length) throw new ArgumentOutOfRangeException(); if (count < 0 || count > buffer.Length - offset) throw new ArgumentOutOfRangeException(); int available = m_socket.Available; // we will need to read using thr timeout specified // if there is data available we can return with that data only // the underlying socket infrastructure will handle the timeout if (count > available && available > 0) { count = available; } if (m_socketType == (int)SocketType.Stream) { return m_socket.Receive(buffer, offset, count, SocketFlags.None); } else if (m_socketType == (int)SocketType.Dgram) { return m_socket.ReceiveFrom(buffer, offset, count, SocketFlags.None, ref m_remoteEndPoint); } else { throw new NotSupportedException(); } } // // Summary: // Sets the current position of the stream to the given value. This method is // not currently supported and always throws a System.NotSupportedException. // // Parameters: // offset: // This parameter is not used. // // origin: // This parameter is not used. // // Returns: // The position in the stream. // // Exceptions: // System.NotSupportedException: // Any use of this property. public override long Seek(long offset, SeekOrigin origin) { throw new NotSupportedException(); } // // Summary: // Sets the length of the stream. This method always throws a System.NotSupportedException. // // Parameters: // value: // This parameter is not used. // // Exceptions: // System.NotSupportedException: // Any use of this property. public override void SetLength(long value) { throw new NotSupportedException(); } // // Summary: // Writes data to the System.Net.Sockets.NetworkStream. // // Parameters: // offset: // The location in buffer from which to start writing data. // // size: // The number of bytes to write to the System.Net.Sockets.NetworkStream. // // buffer: // An array of type System.Byte that contains the data to write to the System.Net.Sockets.NetworkStream. // // Exceptions: // System.ArgumentOutOfRangeException: // offset is less than 0.-or- offset is greater than the length of buffer.-or- // size is less than 0.-or- size is greater than the length of buffer minus // the value of the offset parameter. // // System.ObjectDisposedException: // The System.Net.Sockets.NetworkStream is closed.-or- There was a failure reading // from the network. // // System.IO.IOException: // There was a failure while writing to the network. -or-An error occurred when // accessing the socket. See the Remarks section for more information. // // System.ArgumentNullException: // buffer is null. public override void Write(byte[] buffer, int offset, int count) { if (m_disposed) throw new ObjectDisposedException( "" ); if (m_socket.m_handle == -1) throw new IOException(); if (buffer == null) throw new ArgumentNullException(); if (offset < 0 || offset > buffer.Length) throw new ArgumentOutOfRangeException(); if (count < 0 || count > buffer.Length - offset) throw new ArgumentOutOfRangeException(); int bytesSent = 0; if (m_socketType == (int)SocketType.Stream) { bytesSent = m_socket.Send(buffer, offset, count, SocketFlags.None); } else if (m_socketType == (int)SocketType.Dgram) { bytesSent = m_socket.SendTo(buffer, offset, count, SocketFlags.None, m_socket.RemoteEndPoint); } else { throw new NotSupportedException(); } if (bytesSent != count) throw new IOException(); } } } ================================================ FILE: Zelig/Zelig/RunTime/Framework/system/System/Net/Sockets/ProtocolFamily.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // namespace System.Net.Sockets { /// /// /// Specifies the type of protocol that an instance of the /// class can use. /// /// public enum ProtocolFamily { /// /// [To be supplied.] /// Unknown = AddressFamily.Unknown, /// /// [To be supplied.] /// Unspecified = AddressFamily.Unspecified, /// /// [To be supplied.] /// Unix = AddressFamily.Unix, /// /// [To be supplied.] /// InterNetwork = AddressFamily.InterNetwork, /// /// [To be supplied.] /// ImpLink = AddressFamily.ImpLink, /// /// [To be supplied.] /// Pup = AddressFamily.Pup, /// /// [To be supplied.] /// Chaos = AddressFamily.Chaos, /// /// [To be supplied.] /// NS = AddressFamily.NS, /// /// [To be supplied.] /// Ipx = AddressFamily.Ipx, /// /// [To be supplied.] /// Iso = AddressFamily.Iso, /// /// [To be supplied.] /// Osi = AddressFamily.Osi, /// /// [To be supplied.] /// Ecma = AddressFamily.Ecma, /// /// [To be supplied.] /// DataKit = AddressFamily.DataKit, /// /// [To be supplied.] /// Ccitt = AddressFamily.Ccitt, /// /// [To be supplied.] /// Sna = AddressFamily.Sna, /// /// [To be supplied.] /// DecNet = AddressFamily.DecNet, /// /// [To be supplied.] /// DataLink = AddressFamily.DataLink, /// /// [To be supplied.] /// Lat = AddressFamily.Lat, /// /// [To be supplied.] /// HyperChannel = AddressFamily.HyperChannel, /// /// [To be supplied.] /// AppleTalk = AddressFamily.AppleTalk, /// /// [To be supplied.] /// NetBios = AddressFamily.NetBios, /// /// [To be supplied.] /// VoiceView = AddressFamily.VoiceView, /// /// [To be supplied.] /// FireFox = AddressFamily.FireFox, /// /// [To be supplied.] /// Banyan = AddressFamily.Banyan, /// /// [To be supplied.] /// Atm = AddressFamily.Atm, /// /// [To be supplied.] /// InterNetworkV6 = AddressFamily.InterNetworkV6, /// /// [To be supplied.] /// Cluster = AddressFamily.Cluster, /// /// [To be supplied.] /// Ieee12844 = AddressFamily.Ieee12844, /// /// [To be supplied.] /// Irda = AddressFamily.Irda, /// /// [To be supplied.] /// NetworkDesigners = AddressFamily.NetworkDesigners, /// /// [To be supplied.] /// Max = AddressFamily.Max, }; // enum ProtocolFamily } // namespace System.Net.Sockets ================================================ FILE: Zelig/Zelig/RunTime/Framework/system/System/Net/Sockets/ProtocolType.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // namespace System.Net.Sockets { /// /// /// Specifies the protocols that the class supports. /// /// public enum ProtocolType { /// /// [To be supplied.] /// IP = 0, // dummy for IP /// /// [To be supplied.] /// IPv6HopByHopOptions = 0, /// /// [To be supplied.] /// Icmp = 1, // control message protocol /// /// [To be supplied.] /// Igmp = 2, // group management protocol /// /// [To be supplied.] /// Ggp = 3, // gateway^2 (deprecated) /// /// [To be supplied.] /// IPv4 = 4, /// /// [To be supplied.] /// Tcp = 6, // tcp /// /// [To be supplied.] /// Pup = 12, // pup /// /// [To be supplied.] /// Udp = 17, // user datagram protocol /// /// [To be supplied.] /// Idp = 22, // xns idp /// /// [To be supplied.] /// IPv6 = 41, // IPv4 /// /// [To be supplied.] /// IPv6RoutingHeader = 43, // IPv6RoutingHeader /// /// [To be supplied.] /// IPv6FragmentHeader = 44, // IPv6FragmentHeader /// /// [To be supplied.] /// IPSecEncapsulatingSecurityPayload = 50, // IPSecEncapsulatingSecurityPayload /// /// [To be supplied.] /// IPSecAuthenticationHeader = 51, // IPSecAuthenticationHeader /// /// [To be supplied.] /// IcmpV6 = 58, // IcmpV6 /// /// [To be supplied.] /// IPv6NoNextHeader = 59, // IPv6NoNextHeader /// /// [To be supplied.] /// IPv6DestinationOptions = 60, // IPv6DestinationOptions /// /// [To be supplied.] /// ND = 77, // UNOFFICIAL net disk proto /// /// [To be supplied.] /// Raw = 255, // raw IP packet /// /// [To be supplied.] /// Unspecified = 0, /// /// [To be supplied.] /// Ipx = 1000, /// /// [To be supplied.] /// Spx = 1256, /// /// [To be supplied.] /// SpxII = 1257, /// /// [To be supplied.] /// Unknown = -1, // unknown protocol type } // enum ProtocolType } // namespace System.Net.Sockets ================================================ FILE: Zelig/Zelig/RunTime/Framework/system/System/Net/Sockets/SelectMode.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // namespace System.Net.Sockets { using System; /// /// /// Specifies the mode for polling the status of a socket. /// /// public enum SelectMode { /// /// /// Poll the read status of a socket. /// /// SelectRead = 0, /// /// /// Poll the write status of a socket. /// /// SelectWrite = 1, /// /// /// Poll the error status of a socket. /// /// SelectError = 2 } // enum SelectMode } // namespace System.Net.Sockets ================================================ FILE: Zelig/Zelig/RunTime/Framework/system/System/Net/Sockets/Socket.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // [assembly: System.Runtime.CompilerServices.InternalsVisibleTo( "System.Net.Security" )] namespace System.Net.Sockets { using System.Net; using System.Runtime.CompilerServices; using System.Threading; using NativeSocket = Microsoft.Llilum.Net.SocketNative; public class Socket : IDisposable { private readonly bool m_fBlocking = true; internal int m_handle = -1; private EndPoint m_localEndPoint = null; // timeout values are stored in uSecs since the Poll method requires it. private int m_recvTimeout = System.Threading.Timeout.Infinite; private int m_sendTimeout = System.Threading.Timeout.Infinite; public Socket(AddressFamily addressFamily, SocketType socketType, ProtocolType protocolType) { m_handle = NativeSocket.socket((int)addressFamily, (int)socketType, (int)protocolType); } private Socket(int handle) { m_handle = handle; } public int Available { get { if (m_handle == -1) { throw new ObjectDisposedException( "" ); } uint cBytes = 0; NativeSocket.ioctl(this.m_handle, NativeSocket.FIONREAD, ref cBytes); return (int)cBytes; } } private EndPoint GetEndPoint(bool fLocal) { if (m_handle == -1) { throw new ObjectDisposedException( "" ); } EndPoint ep = null; if (m_localEndPoint == null) { m_localEndPoint = new IPEndPoint(IPAddress.Any, 0); } byte[] address = null; if (fLocal) { NativeSocket.getsockname(this.m_handle, out address); } else { NativeSocket.getpeername(this.m_handle, out address); } SocketAddress socketAddress = new SocketAddress(address); ep = m_localEndPoint.Create(socketAddress); if (fLocal) { m_localEndPoint = ep; } return ep; } public EndPoint LocalEndPoint { get { return GetEndPoint(true); } } public EndPoint RemoteEndPoint { get { return GetEndPoint(false); } } public int ReceiveTimeout { get { return m_recvTimeout; } set { if (value < Timeout.Infinite) throw new ArgumentOutOfRangeException(); // desktop implementation treats 0 as infinite m_recvTimeout = ((value == 0) ? Timeout.Infinite : value); } } public int SendTimeout { get { return m_sendTimeout; } set { if (value < Timeout.Infinite) throw new ArgumentOutOfRangeException(); // desktop implementation treats 0 as infinite m_sendTimeout = ((value == 0) ? Timeout.Infinite : value); } } public void Bind(EndPoint localEP) { if (m_handle == -1) { throw new ObjectDisposedException( "" ); } NativeSocket.bind(this.m_handle, localEP.Serialize().m_Buffer); m_localEndPoint = localEP; } public void Connect(EndPoint remoteEP) { if (m_handle == -1) { throw new ObjectDisposedException( "" ); } NativeSocket.connect(this.m_handle, remoteEP.Serialize().m_Buffer, !m_fBlocking); if (m_fBlocking) { Poll(-1, SelectMode.SelectWrite); } } public void Close() { ((IDisposable)this).Dispose(); } public void Listen(int backlog) { if (m_handle == -1) { throw new ObjectDisposedException( "" ); } NativeSocket.listen(this.m_handle, backlog); } public Socket Accept() { if (m_handle == -1) { throw new ObjectDisposedException( "" ); } int socketHandle; if (m_fBlocking) { Poll(-1, SelectMode.SelectRead); } socketHandle = NativeSocket.accept(this.m_handle); Socket socket = new Socket(socketHandle); socket.m_localEndPoint = this.m_localEndPoint; return socket; } public int Send(byte[] buffer, int size, SocketFlags socketFlags) { return Send(buffer, 0, size, socketFlags); } public int Send(byte[] buffer, SocketFlags socketFlags) { return Send(buffer, 0, buffer != null ? buffer.Length : 0, socketFlags); } public int Send(byte[] buffer) { return Send(buffer, 0, buffer != null ? buffer.Length : 0, SocketFlags.None); } public int Send(byte[] buffer, int offset, int size, SocketFlags socketFlags) { if (m_handle == -1) { throw new ObjectDisposedException( "" ); } return NativeSocket.send(this.m_handle, buffer, offset, size, (int)socketFlags, m_sendTimeout); } public int SendTo(byte[] buffer, int offset, int size, SocketFlags socketFlags, EndPoint remoteEP) { if (m_handle == -1) { throw new ObjectDisposedException( "" ); } byte[] address = remoteEP.Serialize().m_Buffer; return NativeSocket.sendto(this.m_handle, buffer, offset, size, (int)socketFlags, m_sendTimeout, address); } public int SendTo(byte[] buffer, int size, SocketFlags socketFlags, EndPoint remoteEP) { return SendTo(buffer, 0, size, socketFlags, remoteEP); } public int SendTo(byte[] buffer, SocketFlags socketFlags, EndPoint remoteEP) { return SendTo(buffer, 0, buffer != null ? buffer.Length : 0, socketFlags, remoteEP); } public int SendTo(byte[] buffer, EndPoint remoteEP) { return SendTo(buffer, 0, buffer != null ? buffer.Length : 0, SocketFlags.None, remoteEP); } public int Receive(byte[] buffer, int size, SocketFlags socketFlags) { return Receive(buffer, 0, size, socketFlags); } public int Receive(byte[] buffer, SocketFlags socketFlags) { return Receive(buffer, 0, buffer != null ? buffer.Length : 0, socketFlags); } public int Receive(byte[] buffer) { return Receive(buffer, 0, buffer != null ? buffer.Length : 0, SocketFlags.None); } public int Receive(byte[] buffer, int offset, int size, SocketFlags socketFlags) { if (m_handle == -1) { throw new ObjectDisposedException( "" ); } return NativeSocket.recv(this.m_handle, buffer, offset, size, (int)socketFlags, m_recvTimeout); } public int ReceiveFrom(byte[] buffer, int offset, int size, SocketFlags socketFlags, ref EndPoint remoteEP) { if (m_handle == -1) { throw new ObjectDisposedException( "" ); } byte[] address = remoteEP.Serialize().m_Buffer; int len = 0; len = NativeSocket.recvfrom(this.m_handle, buffer, offset, size, (int)socketFlags, m_recvTimeout, ref address); SocketAddress socketAddress = new SocketAddress(address); remoteEP = remoteEP.Create(socketAddress); return len; } public int ReceiveFrom(byte[] buffer, int size, SocketFlags socketFlags, ref EndPoint remoteEP) { return ReceiveFrom(buffer, 0, size, socketFlags, ref remoteEP); } public int ReceiveFrom(byte[] buffer, SocketFlags socketFlags, ref EndPoint remoteEP) { return ReceiveFrom(buffer, 0, buffer != null ? buffer.Length : 0, socketFlags, ref remoteEP); } public int ReceiveFrom(byte[] buffer, ref EndPoint remoteEP) { return ReceiveFrom(buffer, 0, buffer != null ? buffer.Length : 0, SocketFlags.None, ref remoteEP); } public void SetSocketOption(SocketOptionLevel optionLevel, SocketOptionName optionName, int optionValue) { if (m_handle == -1) { throw new ObjectDisposedException( "" ); } byte[] val = new byte[4] { (byte)(optionValue >> 0), (byte)(optionValue >> 8), (byte)(optionValue >> 16), (byte)(optionValue >> 24) }; switch (optionName) { case SocketOptionName.SendTimeout: m_sendTimeout = optionValue; break; case SocketOptionName.ReceiveTimeout: m_recvTimeout = optionValue; break; } NativeSocket.setsockopt(this.m_handle, (int)optionLevel, (int)optionName, val); } public void SetSocketOption(SocketOptionLevel optionLevel, SocketOptionName optionName, bool optionValue) { SetSocketOption(optionLevel, optionName, (optionValue ? 1 : 0)); } public void SetSocketOption(SocketOptionLevel optionLevel, SocketOptionName optionName, byte[] optionValue) { if (m_handle == -1) { throw new ObjectDisposedException( "" ); } NativeSocket.setsockopt(this.m_handle, (int)optionLevel, (int)optionName, optionValue); } public object GetSocketOption(SocketOptionLevel optionLevel, SocketOptionName optionName) { if (optionName == SocketOptionName.DontLinger || optionName == SocketOptionName.AddMembership || optionName == SocketOptionName.DropMembership) { //special case linger? throw new NotSupportedException(); } byte[] val = new byte[4]; GetSocketOption(optionLevel, optionName, val); int iVal = (val[0] << 0 | val[1] << 8 | val[2] << 16 | val[3] << 24); return (object)iVal; } public void GetSocketOption(SocketOptionLevel optionLevel, SocketOptionName optionName, byte[] val) { if (m_handle == -1) { throw new ObjectDisposedException( "" ); } uint optlen; NativeSocket.getsockopt(this.m_handle, (int)optionLevel, (int)optionName, val, out optlen); if(optlen > val.Length) { throw new ArgumentException(nameof(val)); } } public bool Poll(int microSeconds, SelectMode mode) { if (m_handle == -1) { throw new ObjectDisposedException( "" ); } return NativeSocket.poll(this.m_handle, (int)mode, microSeconds); } [MethodImplAttribute(MethodImplOptions.Synchronized)] protected virtual void Dispose(bool disposing) { if (m_handle != -1) { NativeSocket.close(this.m_handle); m_handle = -1; } } void IDisposable.Dispose() { Dispose(true); GC.SuppressFinalize(this); } ~Socket() { Dispose(false); } } } ================================================ FILE: Zelig/Zelig/RunTime/Framework/system/System/Net/Sockets/SocketErrors.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // namespace System.Net.Sockets { /// /// /// Defines socket error constants. /// /// public enum SocketError : int { /// /// /// The operation completed succesfully. /// /// Success = 0, /// /// /// The socket has an error. /// /// SocketError = (-1), /* * Windows Sockets definitions of regular Microsoft C error constants */ /// /// /// A blocking socket call was canceled. /// /// Interrupted = (10000 + 4), //WSAEINTR /// /// /// [To be supplied.] /// /// //WSAEBADF = (10000+9), // /// /// /// Permission denied. /// /// AccessDenied = (10000 + 13), //WSAEACCES /// /// /// Bad address. /// /// Fault = (10000 + 14), //WSAEFAULT /// /// /// Invalid argument. /// /// InvalidArgument = (10000 + 22), //WSAEINVAL /// /// /// Too many open /// files. /// /// TooManyOpenSockets = (10000 + 24), //WSAEMFILE /* * Windows Sockets definitions of regular Berkeley error constants */ /// /// /// Resource temporarily unavailable. /// /// WouldBlock = (10000 + 35), //WSAEWOULDBLOCK /// /// /// Operation now in progress. /// /// InProgress = (10000 + 36), // WSAEINPROGRESS /// /// /// Operation already in progress. /// /// AlreadyInProgress = (10000 + 37), //WSAEALREADY /// /// /// Socket operation on nonsocket. /// /// NotSocket = (10000 + 38), //WSAENOTSOCK /// /// /// Destination address required. /// /// DestinationAddressRequired = (10000 + 39), //WSAEDESTADDRREQ /// /// /// Message too long. /// /// MessageSize = (10000 + 40), //WSAEMSGSIZE /// /// /// Protocol wrong type for socket. /// /// ProtocolType = (10000 + 41), //WSAEPROTOTYPE /// /// /// Bad protocol option. /// /// ProtocolOption = (10000 + 42), //WSAENOPROTOOPT /// /// /// Protocol not supported. /// /// ProtocolNotSupported = (10000 + 43), //WSAEPROTONOSUPPORT /// /// /// Socket type not supported. /// /// SocketNotSupported = (10000 + 44), //WSAESOCKTNOSUPPORT /// /// /// Operation not supported. /// /// OperationNotSupported = (10000 + 45), //WSAEOPNOTSUPP /// /// /// Protocol family not supported. /// /// ProtocolFamilyNotSupported = (10000 + 46), //WSAEPFNOSUPPORT /// /// /// Address family not supported by protocol family. /// /// AddressFamilyNotSupported = (10000 + 47), //WSAEAFNOSUPPORT /// /// Address already in use. /// AddressAlreadyInUse = (10000 + 48), // WSAEADDRINUSE /// /// /// Cannot assign requested address. /// /// AddressNotAvailable = (10000 + 49), //WSAEADDRNOTAVAIL /// /// /// Network is down. /// /// NetworkDown = (10000 + 50), //WSAENETDOWN /// /// /// Network is unreachable. /// /// NetworkUnreachable = (10000 + 51), //WSAENETUNREACH /// /// /// Network dropped connection on reset. /// /// NetworkReset = (10000 + 52), //WSAENETRESET /// /// /// Software caused connection to abort. /// /// ConnectionAborted = (10000 + 53), //WSAECONNABORTED /// /// /// Connection reset by peer. /// /// ConnectionReset = (10000 + 54), //WSAECONNRESET /// /// No buffer space available. /// NoBufferSpaceAvailable = (10000 + 55), //WSAENOBUFS /// /// /// Socket is already connected. /// /// IsConnected = (10000 + 56), //WSAEISCONN /// /// /// Socket is not connected. /// /// NotConnected = (10000 + 57), //WSAENOTCONN /// /// /// Cannot send after socket shutdown. /// /// Shutdown = (10000 + 58), //WSAESHUTDOWN /// /// /// Connection timed out. /// /// TimedOut = (10000 + 60), //WSAETIMEDOUT /// /// /// Connection refused. /// /// ConnectionRefused = (10000 + 61), //WSAECONNREFUSED /// /// /// Host is down. /// /// HostDown = (10000 + 64), //WSAEHOSTDOWN /// /// /// No route to host. /// /// HostUnreachable = (10000 + 65), //WSAEHOSTUNREACH /// /// /// Too many processes. /// /// ProcessLimit = (10000 + 67), //WSAEPROCLIM /// /// /// [To be supplied.] /// /// /* * Extended Windows Sockets error constant definitions */ /// /// /// Network subsystem is unavailable. /// /// SystemNotReady = (10000 + 91), //WSASYSNOTREADY /// /// /// Winsock.dll out of range. /// /// VersionNotSupported = (10000 + 92), //WSAVERNOTSUPPORTED /// /// /// Successful startup not yet performed. /// /// NotInitialized = (10000 + 93), //WSANOTINITIALISED // WSAEREMOTE = (10000+71), /// /// /// Graceful shutdown in progress. /// /// Disconnecting = (10000 + 101), //WSAEDISCON TypeNotFound = (10000 + 109), //WSATYPE_NOT_FOUND /* * Error return codes from gethostbyname() and gethostbyaddr() * = (when using the resolver). Note that these errors are * retrieved via WSAGetLastError() and must therefore follow * the rules for avoiding clashes with error numbers from * specific implementations or language run-time systems. * For this reason the codes are based at 10000+1001. * Note also that [WSA]NO_ADDRESS is defined only for * compatibility purposes. */ /// /// /// Host not found (Authoritative Answer: Host not found). /// /// HostNotFound = (10000 + 1001), //WSAHOST_NOT_FOUND /// /// /// Nonauthoritative host not found (Non-Authoritative: Host not found, or SERVERFAIL). /// /// TryAgain = (10000 + 1002), //WSATRY_AGAIN /// /// /// This is a nonrecoverable error (Non recoverable errors, FORMERR, REFUSED, NOTIMP). /// /// NoRecovery = (10000 + 1003), //WSANO_RECOVERY /// /// /// Valid name, no data record of requested type. /// /// NoData = (10000 + 1004), //WSANO_DATA } } ================================================ FILE: Zelig/Zelig/RunTime/Framework/system/System/Net/Sockets/SocketFlags.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // namespace System.Net.Sockets { using System; /// /// /// Provides constant values for socket messages. /// /// //UEUE [Flags] public enum SocketFlags { /// /// /// Use no flags for this call. /// /// None = 0x0000, /// /// /// Process out-of-band data. /// /// OutOfBand = 0x0001, /// /// /// Peek at incoming message. /// /// Peek = 0x0002, /// /// /// Send without using routing tables. /// /// DontRoute = 0x0004, // see: http://as400bks.rochester.ibm.com/pubs/html/as400/v4r5/ic2978/info/apis/recvms.htm MaxIOVectorLength = 0x0010, /// /// /// Partial send or recv for message. /// /// Truncated = 0x0100, ControlDataTruncated = 0x0200, Broadcast = 0x0400, Multicast = 0x0800, Partial = 0x8000, }; // enum SocketFlags /* MSG_DONTROUTE Specifies that the data should not be subject to routing. A WinSock service provider may choose to ignore this flag;. MSG_OOB Send out-of-band data (stream style socket such as SOCK_STREAM only). MSG_PARTIAL Specifies that lpBuffers only contains a partial message. Note that the error code WSAEOPNOTSUPP will be returnedthis flag is ignored by transports which do not support partial message transmissions. MSG_INTERRUPT // not supported (Win16) Specifies that the function is being called in interrupt context. The service provider must not make any Windows systems calls. Note that this is applicable only to Win16 environments and only for protocols that have the XP1_INTERRUPT bit set in the PROTOCOL_INFO struct. */ } // namespace System.Net.Sockets ================================================ FILE: Zelig/Zelig/RunTime/Framework/system/System/Net/Sockets/SocketOptionLevel.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // namespace System.Net.Sockets { // // Option flags per-socket. // /// /// /// Defines socket option levels for the class. /// /// //UEUE public enum SocketOptionLevel { /// /// /// Indicates socket options apply to the socket itself. /// /// Socket = 0xffff, /// /// /// Indicates socket options apply to IP sockets. /// /// IP = ProtocolType.IP, /// /// /// Indicates socket options apply to IPv6 sockets. /// /// IPv6 = ProtocolType.IPv6, /// /// /// Indicates socket options apply to Tcp sockets. /// /// Tcp = ProtocolType.Tcp, /// /// /// Indicates socket options apply to Udp sockets. /// /// //UEUE Udp = ProtocolType.Udp, }; // enum SocketOptionLevel } // namespace System.Net.Sockets ================================================ FILE: Zelig/Zelig/RunTime/Framework/system/System/Net/Sockets/SocketOptionName.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // namespace System.Net.Sockets { // // Option names per-socket. // /// /// /// Defines socket option names for the class. /// /// //UEUE public enum SocketOptionName { // // good for SocketOptionLevel.Socket // /// /// Record debugging information. /// Debug = 0x0001, // turn on debugging info recording /// /// Socket is listening. /// AcceptConnection = 0x0002, // socket has had listen() /// /// /// Allows the socket to be bound to an address that is already in use. /// /// ReuseAddress = 0x0004, // allow local address reuse /// /// /// Send keep-alives. /// /// KeepAlive = 0x0008, // keep connections alive /// /// /// Do not route, send directly to interface addresses. /// /// DontRoute = 0x0010, // just use interface addresses /// /// /// Permit sending broadcast messages on the socket. /// /// Broadcast = 0x0020, // permit sending of broadcast msgs /// /// /// Bypass hardware when possible. /// /// UseLoopback = 0x0040, // bypass hardware when possible /// /// /// Linger on close if unsent data is present. /// /// Linger = 0x0080, // linger on close if data present /// /// /// Receives out-of-band data in the normal data stream. /// /// OutOfBandInline = 0x0100, // leave received OOB data in line /// /// /// Close socket gracefully without lingering. /// /// DontLinger = ~Linger, /// /// /// Enables a socket to be bound for exclusive access. /// /// ExclusiveAddressUse = ~ReuseAddress, // disallow local address reuse /// /// /// Specifies the total per-socket buffer space reserved for sends. This is /// unrelated to the maximum message size or the size of a TCP window. /// /// SendBuffer = 0x1001, // send buffer size /// /// /// Send low water mark. /// /// ReceiveBuffer = 0x1002, // receive buffer size /// /// /// Specifies the total per-socket buffer space reserved for receives. This is unrelated to the maximum message size or the size of a TCP window. /// /// SendLowWater = 0x1003, // send low-water mark /// /// /// Receive low water mark. /// /// ReceiveLowWater = 0x1004, // receive low-water mark /// /// /// Send timeout. /// /// SendTimeout = 0x1005, // send timeout /// /// /// Receive timeout. /// /// ReceiveTimeout = 0x1006, // receive timeout /// /// /// Get error status and clear. /// /// Error = 0x1007, // get error status and clear /// /// /// Get socket type. /// /// Type = 0x1008, // get socket type /// /// /// Maximum queue length that can be specified by . /// /// MaxConnections = 0x7fffffff, // Maximum queue length specifiable by listen. // // the following values are taken from ws2tcpip.h, // note that these are understood only by ws2_32.dll and are not backwards compatible // with the values found in winsock.h which are understood by wsock32.dll. // // // good for SocketOptionLevel.IP // /// /// /// IP options. /// /// IPOptions = 1, /// /// /// Header is included with data. /// /// HeaderIncluded = 2, /// /// /// IP type of service and preced. /// /// TypeOfService = 3, /// /// /// IP time to live. /// /// IpTimeToLive = 4, /// /// /// IP multicast interface. /// - Additional comments by mbolien: /// multicast interface You provide it with an SOCKADDR_IN, and that tells the /// system that it should receive multicast messages on that interface (if you /// have more than one interface). Binding the socket is not sufficient, since /// if the Ethernet hardware isnt set up to grab the multicast packets, it wont /// do good to bind the socket. Kinda like raw sockets. Unless you /// put the Ethernet card in promiscuous mode, youll only get stuff sent to and /// from your machine. /// /// MulticastInterface = 9, /// /// /// IP multicast time to live. /// /// MulticastTimeToLive = 10, /// /// /// IP Multicast loopback. /// /// MulticastLoopback = 11, /// /// /// Add an IP group membership. /// /// AddMembership = 12, /// /// /// Drop an IP group membership. /// /// DropMembership = 13, /// /// /// Don't fragment IP datagrams. /// /// DontFragment = 14, /// /// /// Join IP group/source. /// /// AddSourceMembership = 15, /// /// /// Leave IP group/source. /// /// DropSourceMembership = 16, /// /// /// Block IP group/source. /// /// BlockSource = 17, /// /// /// Unblock IP group/source. /// /// UnblockSource = 18, /// /// /// Receive packet information for ipv4. /// /// PacketInformation = 19, // //good for ipv6 // HopLimit = 21, //IPV6_HOPLIMIT // // good for SocketOptionLevel.Tcp // /// /// /// Disables the Nagle algorithm for send coalescing. /// /// NoDelay = 1, /// /// [To be supplied.] /// BsdUrgent = 2, Expedited = 2, // // good for SocketOptionLevel.Udp // /// /// [To be supplied.] /// NoChecksum = 1, /// /// /// Udp-Lite checksum coverage. /// /// ChecksumCoverage = 20, UpdateAcceptContext = 0x700B, UpdateConnectContext = 0x7010, }; // enum SocketOptionName } // namespace System.Net.Sockets ================================================ FILE: Zelig/Zelig/RunTime/Framework/system/System/Net/Sockets/SocketType.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // namespace System.Net.Sockets { /// /// /// Specifies the type of socket an instance of the class represents. /// /// public enum SocketType { /// /// [To be supplied.] /// Stream = 1, // stream socket /// /// [To be supplied.] /// Dgram = 2, // datagram socket /// /// [To be supplied.] /// Raw = 3, // raw-protocolinterface /// /// [To be supplied.] /// Rdm = 4, // reliably-delivered message /// /// [To be supplied.] /// Seqpacket = 5, // sequenced packet stream /// /// [To be supplied.] /// Unknown = -1, // Unknown socket type } // enum SocketType } // namespace System.Net.Sockets ================================================ FILE: Zelig/Zelig/RunTime/Framework/system/system.csproj ================================================  Debug AnyCPU 9.0.21022 2.0 {186F31A3-EF89-4A25-B2D5-20070702AA01} Library Properties System System $(LlilumBuildRoot)\Target\obj\$(MSBuildProjectName)\ v4.5 true full false $(LlilumBuildRoot)\Target\bin\$(Configuration)\ DEBUG;TRACE prompt 4 true true true AllRules.ruleset AnyCPU false pdbonly true $(LlilumBuildRoot)\Target\bin\$(Configuration)\ TRACE prompt 4 true true true AllRules.ruleset AnyCPU false true full false $(LlilumBuildRoot)\Target\bin\$(Configuration)\ DEBUG;TRACE true AnyCPU true false {186F31A3-EF89-4A25-B2D5-20060501AA01} mscorlib False ================================================ FILE: Zelig/Zelig/RunTime/Zelig/Common/Attributes/CallQualifiers/ActivationRecordEvents.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // namespace Microsoft.Zelig.Runtime { using System; [TypeSystem.AllowCompileTimeIntrospection] public enum ActivationRecordEvents { EnteringException , Constructing , ReadyForUse , ReadyForTearDown , ReturnToCaller , ReturnFromException, LongJump , NonReachable , } } ================================================ FILE: Zelig/Zelig/RunTime/Zelig/Common/Attributes/CallQualifiers/BottomOfCallStackAttribute.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // namespace Microsoft.Zelig.Runtime { using System; [TypeSystem.WellKnownType( "Microsoft_Zelig_Runtime_BottomOfCallStackAttribute" )] [AttributeUsage(AttributeTargets.Constructor | AttributeTargets.Method )] public sealed class BottomOfCallStackAttribute : Attribute { } } ================================================ FILE: Zelig/Zelig/RunTime/Zelig/Common/Attributes/CallQualifiers/CanAllocateOnReturnAttribute.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // namespace Microsoft.Zelig.Runtime { using System; // // Using this attribute tells the system that the heap is ready for use // after a call to the method. This is mainly useful during bootstrap. // [TypeSystem.WellKnownType( "Microsoft_Zelig_Runtime_CanAllocateOnReturnAttribute" )] [AttributeUsage(AttributeTargets.Constructor | AttributeTargets.Method )] public sealed class CanAllocateOnReturnAttribute : Attribute { } } ================================================ FILE: Zelig/Zelig/RunTime/Zelig/Common/Attributes/CallQualifiers/CannotAllocateAttribute.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // namespace Microsoft.Zelig.Runtime { using System; [TypeSystem.WellKnownType( "Microsoft_Zelig_Runtime_CannotAllocateAttribute" )] [AttributeUsage(AttributeTargets.Constructor | AttributeTargets.Method )] public sealed class CannotAllocateAttribute : Attribute { } } ================================================ FILE: Zelig/Zelig/RunTime/Zelig/Common/Attributes/CallQualifiers/DebuggerHookHandlerAttribute.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // namespace Microsoft.Zelig.Runtime { using System; [TypeSystem.AllowCompileTimeIntrospection] public enum DebuggerHook { None , FlushInstructionCache , FlushDataCache , GetFullProcessorContext, GetSoftBreakpointTable , } public struct SoftBreakpointDescriptor { public UIntPtr Address; public uint Value; } [TypeSystem.WellKnownType( "Microsoft_Zelig_Runtime_DebuggerHookHandlerAttribute" )] [AttributeUsage(AttributeTargets.Method)] public sealed class DebuggerHookHandlerAttribute : Attribute { // // State // public readonly DebuggerHook Kind; // // Constructor Methods // public DebuggerHookHandlerAttribute( DebuggerHook kind ) { this.Kind = kind; } } } ================================================ FILE: Zelig/Zelig/RunTime/Zelig/Common/Attributes/CallQualifiers/DisableBoundsChecksAttribute.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // namespace Microsoft.Zelig.Runtime { using System; [TypeSystem.WellKnownType( "Microsoft_Zelig_Runtime_DisableBoundsChecksAttribute" )] [AttributeUsage(AttributeTargets.Constructor | AttributeTargets.Method )] public sealed class DisableBoundsChecksAttribute : Attribute { // // State // public bool ApplyRecursively; } } ================================================ FILE: Zelig/Zelig/RunTime/Zelig/Common/Attributes/CallQualifiers/DisableNullChecksAttribute.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // namespace Microsoft.Zelig.Runtime { using System; [TypeSystem.WellKnownType( "Microsoft_Zelig_Runtime_DisableNullChecksAttribute" )] [AttributeUsage(AttributeTargets.Constructor | AttributeTargets.Method )] public sealed class DisableNullChecksAttribute : Attribute { // // State // public bool ApplyRecursively; } } ================================================ FILE: Zelig/Zelig/RunTime/Zelig/Common/Attributes/CallQualifiers/ExportedMethodAttribute.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // namespace Microsoft.Zelig.Runtime { using System; [TypeSystem.WellKnownType( "Microsoft_Zelig_Runtime_ExportedMethodAttribute" )] [AttributeUsage(AttributeTargets.Method)] public sealed class ExportedMethodAttribute : Attribute { } } ================================================ FILE: Zelig/Zelig/RunTime/Zelig/Common/Attributes/CallQualifiers/HardwareExceptionHandlerAttribute.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // namespace Microsoft.Zelig.Runtime { using System; [TypeSystem.AllowCompileTimeIntrospection] public enum HardwareException { None , VectorTable , // Not really an exception, but a bootstrap for the exception table. Bootstrap , // Not really an exception, but the entry point into the system at boot. LongJump , // Not really an exception, but a marker for loading a full register context. Reset , UndefinedInstruction, PrefetchAbort , DataAbort , Interrupt , FastInterrupt , SoftwareInterrupt , NMI , Fault , SysTick , PendSV , Service , Debug , } [TypeSystem.WellKnownType( "Microsoft_Zelig_Runtime_HardwareExceptionHandlerAttribute" )] [AttributeUsage(AttributeTargets.Method)] public sealed class HardwareExceptionHandlerAttribute : Attribute { // // State // public readonly HardwareException Origin; // // Constructor Methods // public HardwareExceptionHandlerAttribute( HardwareException origin ) { this.Origin = origin; } } } ================================================ FILE: Zelig/Zelig/RunTime/Zelig/Common/Attributes/CallQualifiers/ImportedMethodReferenceAttribute.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // namespace Microsoft.Zelig.Runtime { using System; [TypeSystem.WellKnownType( "Microsoft_Zelig_Runtime_ImportedMethodReferenceAttribute" )] [AttributeUsage(AttributeTargets.Method)] public sealed class ImportedMethodReferenceAttribute : Attribute { internal InteropFileType m_type; internal string m_file; internal string m_methodName; public enum InteropFileType { ArmELF, UserDefinedFlag = 0x80000 } private ImportedMethodReferenceAttribute() { } public ImportedMethodReferenceAttribute(InteropFileType importFileType, string fileName) : this( importFileType, fileName, null ) { } public ImportedMethodReferenceAttribute( InteropFileType importFileType, string fileName, string methodName ) { m_type = importFileType; m_file = fileName; m_methodName = methodName; } } } ================================================ FILE: Zelig/Zelig/RunTime/Zelig/Common/Attributes/CallQualifiers/InlineAttribute.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // namespace Microsoft.Zelig.Runtime { using System; [TypeSystem.WellKnownType( "Microsoft_Zelig_Runtime_InlineAttribute" )] [AttributeUsage(AttributeTargets.Constructor | AttributeTargets.Method )] public sealed class InlineAttribute : Attribute { } } ================================================ FILE: Zelig/Zelig/RunTime/Zelig/Common/Attributes/CallQualifiers/NoInlineAttribute.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // namespace Microsoft.Zelig.Runtime { using System; [TypeSystem.WellKnownType( "Microsoft_Zelig_Runtime_NoInlineAttribute" )] [AttributeUsage(AttributeTargets.Constructor | AttributeTargets.Method )] public sealed class NoInlineAttribute : Attribute { } } ================================================ FILE: Zelig/Zelig/RunTime/Zelig/Common/Attributes/CallQualifiers/NoReturnAttribute.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // namespace Microsoft.Zelig.Runtime { using System; [TypeSystem.WellKnownType( "Microsoft_Zelig_Runtime_NoReturnAttribute" )] [AttributeUsage(AttributeTargets.Constructor | AttributeTargets.Method )] public sealed class NoReturnAttribute : Attribute { } } ================================================ FILE: Zelig/Zelig/RunTime/Zelig/Common/Attributes/CallQualifiers/SaveFullProcessorContextAttribute.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // namespace Microsoft.Zelig.Runtime { using System; [TypeSystem.WellKnownType( "Microsoft_Zelig_Runtime_SaveFullProcessorContextAttribute" )] [AttributeUsage(AttributeTargets.Method)] public sealed class SaveFullProcessorContextAttribute : Attribute { } } ================================================ FILE: Zelig/Zelig/RunTime/Zelig/Common/Attributes/CallQualifiers/StackAvailableOnReturnAttribute.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // namespace Microsoft.Zelig.Runtime { using System; // // Using this attribute tells the system that the stack pointer is good // after a call to the method. This is mainly useful during bootstrap. // [TypeSystem.WellKnownType( "Microsoft_Zelig_Runtime_StackAvailableOnReturnAttribute" )] [AttributeUsage(AttributeTargets.Constructor | AttributeTargets.Method )] public sealed class StackAvailableOnReturnAttribute : Attribute { } } ================================================ FILE: Zelig/Zelig/RunTime/Zelig/Common/Attributes/CallQualifiers/StackNotAvailableAttribute.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // namespace Microsoft.Zelig.Runtime { using System; // // For methods marked with this attribute, the stack pointer is undefined on entry, // so the system should generate code to does not access the stack. // [TypeSystem.WellKnownType( "Microsoft_Zelig_Runtime_StackNotAvailableAttribute" )] [AttributeUsage(AttributeTargets.Constructor | AttributeTargets.Method )] public sealed class StackNotAvailableAttribute : Attribute { } } ================================================ FILE: Zelig/Zelig/RunTime/Zelig/Common/Attributes/CompileTimeOptions/AlignmentRequirementsAttribute.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // namespace Microsoft.Zelig.Runtime { using System; [TypeSystem.WellKnownType( "Microsoft_Zelig_Runtime_AlignmentRequirementsAttribute" )] [AttributeUsage(AttributeTargets.Method | AttributeTargets.Field)] public sealed class AlignmentRequirementsAttribute : Attribute { // // State // public readonly uint Alignment; public readonly int AlignmentOffset; // // Constructor Methods // public AlignmentRequirementsAttribute( uint alignment , int alignmentOffset ) { this.Alignment = alignment; this.AlignmentOffset = alignmentOffset; } } } ================================================ FILE: Zelig/Zelig/RunTime/Zelig/Common/Attributes/CompileTimeOptions/ConfigurationOptionAttribute.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // namespace Microsoft.Zelig.Runtime { using System; // // Use this attribute on a field if you need to guaranteed that // it will be included in an image when its declaring type is, // even if the field is not explicitly referenced by the application. // [TypeSystem.WellKnownType( "Microsoft_Zelig_Runtime_ConfigurationOptionAttribute" )] [AttributeUsage( AttributeTargets.Field | AttributeTargets.Method )] public class ConfigurationOptionAttribute : Attribute { // // State // public readonly string Name; // // Constructor Methods // public ConfigurationOptionAttribute( string name ) { this.Name = name; } } } ================================================ FILE: Zelig/Zelig/RunTime/Zelig/Common/Attributes/CompileTimeOptions/ForceDevirtualizationAttribute.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // namespace Microsoft.Zelig.Runtime { using System; // // At times, we use abstract classes to model extensibility points in the system, // to supply a nice abstraction for things like processor initialization, memory subsystems, etc. // // However we don't really expect to have multiple subclasses in active use at the same time. // It wouldn't make sense to have two processor models, for example. // // Use this attribute to tell the system that a single subclass should be present. // [TypeSystem.WellKnownType( "Microsoft_Zelig_Runtime_ForceDevirtualizationAttribute" )] [AttributeUsage(AttributeTargets.Class | AttributeTargets.Struct | AttributeTargets.Interface )] public sealed class ForceDevirtualizationAttribute : Attribute { } } ================================================ FILE: Zelig/Zelig/RunTime/Zelig/Common/Attributes/CompileTimeOptions/ImplicitInstanceAttribute.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // namespace Microsoft.Zelig.Runtime { using System; // // At times, we use abstract classes to model extensibility points in the system, // to supply a nice abstraction for things like processor initialization, garbage collection, etc. // // However it's not like we actually have some memory for an instance of these classes. // The classes are used only to get access to the virtual method syntax. // // Use this attribute to tell the system that the "this" parameter doesn't really exist and it should be passed around. // [TypeSystem.WellKnownType( "Microsoft_Zelig_Runtime_ImplicitInstanceAttribute" )] [AttributeUsage(AttributeTargets.Class | AttributeTargets.Struct | AttributeTargets.Interface )] public sealed class ImplicitInstanceAttribute : Attribute { } } ================================================ FILE: Zelig/Zelig/RunTime/Zelig/Common/Attributes/CompileTimeOptions/MemoryRequirementsAttribute.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // namespace Microsoft.Zelig.Runtime { using System; [Flags] [TypeSystem.AllowCompileTimeIntrospection] public enum MemoryAttributes : uint { RAM = 0x00000001, FLASH = 0x00000002, ROM = 0x00000004, Peripheral = 0x00000008, LocationMask = 0x0000000F, Static = 0x00000010, Dynamic = 0x00000020, Stack = 0x00000040, InternalMemory = 0x00000080, ExternalMemory = 0x00000100, RandomAccessMemory = 0x00000200, BlockBasedMemory = 0x00000400, ConfiguredAtEntryPoint = 0x00000800, LoadedAtEntrypoint = 0x00001000, Allocated = 0x80000000u, } [TypeSystem.WellKnownType( "Microsoft_Zelig_Runtime_MemoryRequirementsAttribute" )] [AttributeUsage(AttributeTargets.Method | AttributeTargets.Field)] public sealed class MemoryRequirementsAttribute : Attribute { // // State // public readonly MemoryAttributes Requirements; // // Constructor Methods // public MemoryRequirementsAttribute( MemoryAttributes requirements ) { this.Requirements = requirements; } } } ================================================ FILE: Zelig/Zelig/RunTime/Zelig/Common/Attributes/CompileTimeOptions/MemoryUsageAttribute.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // namespace Microsoft.Zelig.Runtime { using System; [Flags] [TypeSystem.AllowCompileTimeIntrospection] public enum MemoryUsage : uint { Undefined = 0x00000000, Code = 0x00000001, DataRW = 0x00000002, DataRO = 0x00000004, Relocation = 0x00000008, HotCode = 0x00000010, ColdCode = 0x00000020, VectorsTable = 0x00000040, Bootstrap = 0x00000080, Booter = 0x00000100, // Hold bootstrap image. Stack = 0x00000200, Heap = 0x00000400, } [TypeSystem.WellKnownType( "Microsoft_Zelig_Runtime_MemoryUsageAttribute" )] [AttributeUsage(AttributeTargets.Method | AttributeTargets.Field)] public sealed class MemoryUsageAttribute : Attribute { // // State // public readonly MemoryUsage Usage; public string SectionName; public bool ContentsUninitialized; public bool AllocateFromHighAddress; // // Constructor Methods // public MemoryUsageAttribute( MemoryUsage usage ) { this.Usage = usage; } } } ================================================ FILE: Zelig/Zelig/RunTime/Zelig/Common/Attributes/CompileTimeOptions/SingletonFactoryAttribute.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // namespace Microsoft.Zelig.Runtime { using System; [TypeSystem.WellKnownType( "Microsoft_Zelig_Runtime_SingletonFactoryAttribute" )] [AttributeUsage(AttributeTargets.Constructor | AttributeTargets.Method )] public sealed class SingletonFactoryAttribute : Attribute { public bool ReadOnly; public Type Fallback; } } ================================================ FILE: Zelig/Zelig/RunTime/Zelig/Common/Attributes/HardwareModeling/BitFieldPeripheralAttribute.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // namespace Microsoft.Zelig.Runtime { using System; [TypeSystem.WellKnownType( "Microsoft_Zelig_Runtime_BitFieldPeripheralAttribute" )] [AttributeUsage(AttributeTargets.Struct,AllowMultiple=false)] public sealed class BitFieldPeripheralAttribute : Attribute { // // State // public Type PhysicalType; } } ================================================ FILE: Zelig/Zelig/RunTime/Zelig/Common/Attributes/HardwareModeling/BitFieldRegisterAttribute.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // namespace Microsoft.Zelig.Runtime { using System; [Flags] [TypeSystem.AllowCompileTimeIntrospection] public enum BitFieldModifier : uint { ReadOnly = 0x00000001, WriteOnly = 0x00000002, UseReadMask = 0x00000004, UseWriteMask = 0x00000008, } [TypeSystem.WellKnownType( "Microsoft_Zelig_Runtime_BitFieldRegisterAttribute" )] [AttributeUsage(AttributeTargets.Field,AllowMultiple=false)] public sealed class BitFieldRegisterAttribute : Attribute { // // State // public uint Position; public uint Size; public BitFieldModifier Modifiers; public uint ReadsAs; public uint WritesAs; } } ================================================ FILE: Zelig/Zelig/RunTime/Zelig/Common/Attributes/HardwareModeling/BitFieldSplitRegisterAttribute.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // namespace Microsoft.Zelig.Runtime { using System; [TypeSystem.WellKnownType( "Microsoft_Zelig_Runtime_BitFieldSplitRegisterAttribute" )] [AttributeUsage(AttributeTargets.Field,AllowMultiple=true)] public sealed class BitFieldSplitRegisterAttribute : Attribute { // // State // public uint Position; public uint Size; public uint Offset; public BitFieldModifier Modifiers; public uint ReadsAs; public uint WritesAs; } } ================================================ FILE: Zelig/Zelig/RunTime/Zelig/Common/Attributes/HardwareModeling/MemoryMappedPeripheralAttribute.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // namespace Microsoft.Zelig.Runtime { using System; [TypeSystem.WellKnownType( "Microsoft_Zelig_Runtime_MemoryMappedPeripheralAttribute" )] [AttributeUsage(AttributeTargets.Class | AttributeTargets.Struct ,AllowMultiple=false)] public sealed class MemoryMappedPeripheralAttribute : Attribute { // // State // public uint Base; public uint Length; } } ================================================ FILE: Zelig/Zelig/RunTime/Zelig/Common/Attributes/HardwareModeling/RegisterAttribute.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // namespace Microsoft.Zelig.Runtime { using System; [TypeSystem.WellKnownType( "Microsoft_Zelig_Runtime_RegisterAttribute" )] [AttributeUsage(AttributeTargets.Field,AllowMultiple=false)] public sealed class RegisterAttribute : Attribute { // // State // public uint Offset; public uint Size; public int Instances; } } ================================================ FILE: Zelig/Zelig/RunTime/Zelig/Common/Attributes/OpenClasses/AliasForBaseFieldAttribute.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // namespace Microsoft.Zelig.Runtime { using System; // // This gives an explicit name to a field you want to use from the target class, but you cannot name. // [TypeSystem.WellKnownType( "Microsoft_Zelig_Runtime_AliasForBaseFieldAttribute" )] [AttributeUsage(AttributeTargets.Field)] public sealed class AliasForBaseFieldAttribute : Attribute { // // State // public string Target; // // Constructor Methods // public AliasForBaseFieldAttribute() { } public AliasForBaseFieldAttribute( string target ) { this.Target = target; } } } ================================================ FILE: Zelig/Zelig/RunTime/Zelig/Common/Attributes/OpenClasses/AliasForBaseMethodAttribute.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // namespace Microsoft.Zelig.Runtime { using System; // // This gives an explicit name to a method you want to call in the target class, but you cannot name. // [TypeSystem.WellKnownType( "Microsoft_Zelig_Runtime_AliasForBaseMethodAttribute" )] [AttributeUsage(AttributeTargets.Method)] public sealed class AliasForBaseMethodAttribute : Attribute { // // State // public string Target; // // Constructor Methods // public AliasForBaseMethodAttribute( string target ) { this.Target = target; } } } ================================================ FILE: Zelig/Zelig/RunTime/Zelig/Common/Attributes/OpenClasses/AliasForSuperMethodAttribute.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // namespace Microsoft.Zelig.Runtime { using System; // // This gives an explicit name to a method you want to call in the target's super class, but you cannot name. // [TypeSystem.WellKnownType( "Microsoft_Zelig_Runtime_AliasForSuperMethodAttribute" )] [AttributeUsage(AttributeTargets.Method)] public sealed class AliasForSuperMethodAttribute : Attribute { // // State // public string Target; // // Constructor Methods // public AliasForSuperMethodAttribute( string target ) { this.Target = target; } } } ================================================ FILE: Zelig/Zelig/RunTime/Zelig/Common/Attributes/OpenClasses/AliasForTargetMethodAttribute.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // namespace Microsoft.Zelig.Runtime { using System; // // This gives an explicit name to the method you want to override, instead of relying on name matching. // [TypeSystem.WellKnownType( "Microsoft_Zelig_Runtime_AliasForTargetMethodAttribute" )] [AttributeUsage(AttributeTargets.Method)] public sealed class AliasForTargetMethodAttribute : Attribute { // // State // public string Target; // // Constructor Methods // public AliasForTargetMethodAttribute( string target ) { this.Target = target; } } } ================================================ FILE: Zelig/Zelig/RunTime/Zelig/Common/Attributes/OpenClasses/CapabilitiesFilterAttribute.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // namespace Microsoft.Zelig.Runtime { using System; [TypeSystem.WellKnownType( "Microsoft_Zelig_Runtime_CapabilitiesFilterAttribute" )] [AttributeUsage(AttributeTargets.Method, AllowMultiple=false)] public sealed class CapabilitiesFilterAttribute : Attribute { // // State // public uint RequiredCapabilities; // // Constructor Methods // public CapabilitiesFilterAttribute( ) { } } } ================================================ FILE: Zelig/Zelig/RunTime/Zelig/Common/Attributes/OpenClasses/DiscardTargetImplementationAttribute.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // namespace Microsoft.Zelig.Runtime { using System; // // The default behavior is to discard the overridden method, but this doesn't work for constructors. // So, instead of picking a default, the code has to explain what to do. // // // With this attribute, the system will try to just use the new implementation, based on different cases: // // 1) There's no matching constructor => Fail. // 2) There's a matching constructor => Substitute the initialization of the overridden object with the current one. // // // Use paired with 'AliasForMethod' to guide how to merge, // so you can name otherwise unnameable entities, like constructors. // [TypeSystem.WellKnownType( "Microsoft_Zelig_Runtime_DiscardTargetImplementationAttribute" )] [AttributeUsage(AttributeTargets.Constructor)] public sealed class DiscardTargetImplementationAttribute : Attribute { } } ================================================ FILE: Zelig/Zelig/RunTime/Zelig/Common/Attributes/OpenClasses/ExtendClassAttribute.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // namespace Microsoft.Zelig.Runtime { using System; // // This attribute tells the system that the type under constructor is not a real type, // it should be used only add/change methods and fields to an existing type. // // The overriding type should either derive from the target one, derive from the same super type, or derive from object. // // There could be an issue with constructors, since their code points to the super type, which could be incompatible. // The system should automatically correct the obvious cases and abort on ambiguous ones. // [TypeSystem.WellKnownType( "Microsoft_Zelig_Runtime_ExtendClassAttribute" )] [AttributeUsage(AttributeTargets.Class | AttributeTargets.Struct )] public sealed class ExtendClassAttribute : Attribute { // // State // public Type Target; public string TargetByWellKnownName; public bool NoConstructors; public Type ProcessAfter; public string CodeGeneratorFilter; public uint PlatformFamilyFilter; public uint PlatformVersionFilter; public uint PlatformVFPSupportFilter; // // Constructor Methods // public ExtendClassAttribute( Type target ) { this.Target = target; } public ExtendClassAttribute( string target ) { this.TargetByWellKnownName = target; } } } ================================================ FILE: Zelig/Zelig/RunTime/Zelig/Common/Attributes/OpenClasses/InjectAtEntryPointAttribute.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // namespace Microsoft.Zelig.Runtime { using System; // // This gives you an opportunity to look at the input values of a method. // // To inject into a method like this one: // // TargetMethod( ) // // you have to use a signature like this one: // // void InjectedMethod( ) // [TypeSystem.WellKnownType( "Microsoft_Zelig_Runtime_InjectAtEntryPointAttribute" )] [AttributeUsage(AttributeTargets.Method)] public sealed class InjectAtEntryPointAttribute : Attribute { } } ================================================ FILE: Zelig/Zelig/RunTime/Zelig/Common/Attributes/OpenClasses/InjectAtExitPointAttribute.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // namespace Microsoft.Zelig.Runtime { using System; // // This gives you an opportunity to look at the result value of a method. // // To inject into a method like this one: // // TargetMethod( ) // // you have to use a signature like this one: // // InjectedMethod( , ) // [TypeSystem.WellKnownType( "Microsoft_Zelig_Runtime_InjectAtExitPointAttribute" )] [AttributeUsage(AttributeTargets.Method)] public sealed class InjectAtExitPointAttribute : Attribute { } } ================================================ FILE: Zelig/Zelig/RunTime/Zelig/Common/Attributes/OpenClasses/MergeWithTargetImplementationAttribute.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // namespace Microsoft.Zelig.Runtime { using System; // // The default behavior is to discard the overridden method, but this doesn't work for constructors. // So, instead of picking a default, the code has to explain what to do. // // // With this attribute, the system will try to automatically merge the code for the constructors, based on different cases: // // 1) There's no matching constructor // a) Default constructor is missing => Fail, it's not clear what should happen. // b) Default constructor is present => Merge the initialization of the overridden object with the current one. // // 2) There's a matching constructor => Merge the initialization of the overridden object with the current one. // // // Use paired with 'AliasForMethod' to guide how to merge, // so you can name otherwise unnameable entities, like constructors. // [TypeSystem.WellKnownType( "Microsoft_Zelig_Runtime_MergeWithTargetImplementationAttribute" )] [AttributeUsage(AttributeTargets.Constructor)] public sealed class MergeWithTargetImplementationAttribute : Attribute { } } ================================================ FILE: Zelig/Zelig/RunTime/Zelig/Common/Attributes/OpenClasses/ProductFilterAttribute.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // namespace Microsoft.Zelig.Runtime { using System; [TypeSystem.WellKnownType( "Microsoft_Zelig_Runtime_ProductFilterAttribute" )] [AttributeUsage(AttributeTargets.Class, AllowMultiple=true)] public sealed class ProductFilterAttribute : Attribute { // // State // public readonly String ProductFilter; // // Constructor Methods // public ProductFilterAttribute( String product ) { this.ProductFilter = product; } } } ================================================ FILE: Zelig/Zelig/RunTime/Zelig/Common/Attributes/OpenClasses/SingletonFactoryPlatformFilter.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // namespace Microsoft.Zelig.Runtime { using System; // // The default behavior is to discard the overridden method, but this doesn't work for constructors. // So, instead of picking a default, the code has to explain what to do. // // // With this attribute, the system will try to automatically merge the code for the constructors, based on different cases: // // 1) There's no matching constructor // a) Default constructor is missing => Fail, it's not clear what should happen. // b) Default constructor is present => Merge the initialization of the overridden object with the current one. // // 2) There's a matching constructor => Merge the initialization of the overridden object with the current one. // // // Use paired with 'AliasForMethod' to guide how to merge, // so you can name otherwise unnameable entities, like constructors. // [TypeSystem.WellKnownType( "Microsoft_Zelig_Runtime_SingletonFactoryPlatformFilterAttributer" )] public sealed class SingletonFactoryPlatformFilterAttribute : Attribute { // // State // public string Target; // // Constructor Methods // public SingletonFactoryPlatformFilterAttribute( String filter ) { this.Target = filter; } } } ================================================ FILE: Zelig/Zelig/RunTime/Zelig/Common/Attributes/TypeSystem/AllowCompileTimeIntrospectionAttribute.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // namespace Microsoft.Zelig.Runtime.TypeSystem { using System; [AttributeUsage(AttributeTargets.Class | AttributeTargets.Struct | AttributeTargets.Enum )] public class AllowCompileTimeIntrospectionAttribute : Attribute { } } ================================================ FILE: Zelig/Zelig/RunTime/Zelig/Common/Attributes/TypeSystem/AssumeReferencedAttribute.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // namespace Microsoft.Zelig.Runtime.TypeSystem { using System; // // Use this attribute on a field if you need to guaranteed that // it will be included in an image when its declaring type is, // even if the field is not explicitly referenced by the application. // [WellKnownType( "Microsoft_Zelig_Runtime_TypeSystem_AssumeReferencedAttribute" )] [AttributeUsage( AttributeTargets.Field )] public class AssumeReferencedAttribute : Attribute { } } ================================================ FILE: Zelig/Zelig/RunTime/Zelig/Common/Attributes/TypeSystem/DisableAutomaticReferenceCountingAttribute.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // namespace Microsoft.Zelig.Runtime.TypeSystem { using System; /// /// Attribute for methods that should be excluded from automatically injecting reference /// counting code (i.e. initialize reference count when allocating an object, add and release /// reference when needed). /// The attribute can also be apply to a class or a struct, in which case, all methods in the /// class / sturct will be excluded from the automatic reference counting code injection. /// [WellKnownType( "Microsoft_Zelig_Runtime_TypeSystem_DisableAutomaticReferenceCountingAttribute" )] [AttributeUsage( AttributeTargets.Class | AttributeTargets.Struct | AttributeTargets.Method | AttributeTargets.Constructor | AttributeTargets.Property )] public class DisableAutomaticReferenceCountingAttribute : Attribute { } } ================================================ FILE: Zelig/Zelig/RunTime/Zelig/Common/Attributes/TypeSystem/DisableReferenceCountingAttribute.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // namespace Microsoft.Zelig.Runtime.TypeSystem { using System; [WellKnownType( "Microsoft_Zelig_Runtime_TypeSystem_DisableReferenceCountingAttribute" )] [AttributeUsage( AttributeTargets.Class )] public class DisableReferenceCountingAttribute : Attribute { } } ================================================ FILE: Zelig/Zelig/RunTime/Zelig/Common/Attributes/TypeSystem/GarbageCollectionExtensionAttribute.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // namespace Microsoft.Zelig.Runtime.TypeSystem { using System; [WellKnownType( "Microsoft_Zelig_Runtime_TypeSystem_GarbageCollectionExtensionAttribute" )] [AttributeUsage(AttributeTargets.Class)] public class GarbageCollectionExtensionAttribute : Attribute { // // State // public readonly Type Target; // // Constructor Methods // public GarbageCollectionExtensionAttribute( Type target ) { this.Target = target; } } } ================================================ FILE: Zelig/Zelig/RunTime/Zelig/Common/Attributes/TypeSystem/GenerateUnsafeCastAttribute.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // namespace Microsoft.Zelig.Runtime.TypeSystem { using System; [WellKnownType( "Microsoft_Zelig_Runtime_TypeSystem_GenerateUnsafeCastAttribute" )] [AttributeUsage(AttributeTargets.Method)] public class GenerateUnsafeCastAttribute : Attribute { } } ================================================ FILE: Zelig/Zelig/RunTime/Zelig/Common/Attributes/TypeSystem/LinkToRuntimeTypeAttribute.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // namespace Microsoft.Zelig.Runtime.TypeSystem { using System; [AttributeUsage(AttributeTargets.Field)] public class LinkToRuntimeTypeAttribute : Attribute { // // State // public readonly Type Target; // // Constructor Methods // public LinkToRuntimeTypeAttribute( Type target ) { this.Target = target; } } } ================================================ FILE: Zelig/Zelig/RunTime/Zelig/Common/Attributes/TypeSystem/NoVTableAttribute.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // namespace Microsoft.Zelig.Runtime.TypeSystem { using System; [TypeSystem.WellKnownType( "Microsoft_Zelig_Runtime_TypeSystem_NoVTableAttribute" )] [AttributeUsage(AttributeTargets.Class)] public class NoVTableAttribute : Attribute { } } ================================================ FILE: Zelig/Zelig/RunTime/Zelig/Common/Attributes/TypeSystem/SkipDuringGarbageCollectionAttribute.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // namespace Microsoft.Zelig.Runtime.TypeSystem { using System; // // Use this attribute on a field if you need to treat it specially during garbage collection. // [WellKnownType( "Microsoft_Zelig_Runtime_TypeSystem_SkipDuringGarbageCollectionAttribute" )] [AttributeUsage( AttributeTargets.Field )] public class SkipDuringGarbageCollectionAttribute : Attribute { } } ================================================ FILE: Zelig/Zelig/RunTime/Zelig/Common/Attributes/TypeSystem/TypeDependencyAttribute.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // namespace Microsoft.Zelig.Runtime.TypeSystem { using System; [WellKnownType( "Microsoft_Zelig_Runtime_TypeSystem_TypeDependencyAttribute" )] [AttributeUsage( AttributeTargets.Struct | AttributeTargets.Class | AttributeTargets.Interface, AllowMultiple = true, Inherited = false)] public sealed class TypeDependencyAttribute : Attribute { internal Type Type; public TypeDependencyAttribute( Type type ) { this.Type = type; } } } ================================================ FILE: Zelig/Zelig/RunTime/Zelig/Common/Attributes/TypeSystem/WellKnownFieldAttribute.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // namespace Microsoft.Zelig.Runtime.TypeSystem { using System; [WellKnownType( "Microsoft_Zelig_Runtime_TypeSystem_WellKnownFieldAttribute" )] [AttributeUsage(AttributeTargets.Field)] public class WellKnownFieldAttribute : Attribute { // // State // public readonly string FieldName; // // Constructor Methods // public WellKnownFieldAttribute( string fieldName ) { this.FieldName = fieldName; } } } ================================================ FILE: Zelig/Zelig/RunTime/Zelig/Common/Attributes/TypeSystem/WellKnownMethodAttribute.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // namespace Microsoft.Zelig.Runtime.TypeSystem { using System; [WellKnownType( "Microsoft_Zelig_Runtime_TypeSystem_WellKnownMethodAttribute" )] [AttributeUsage(AttributeTargets.Constructor | AttributeTargets.Method )] public class WellKnownMethodAttribute : Attribute { // // State // public readonly string FieldName; // // Constructor Methods // public WellKnownMethodAttribute( string fieldName ) { this.FieldName = fieldName; } } } ================================================ FILE: Zelig/Zelig/RunTime/Zelig/Common/Attributes/TypeSystem/WellKnownTypeAttribute.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // namespace Microsoft.Zelig.Runtime.TypeSystem { using System; [AttributeUsage( AttributeTargets.Class | AttributeTargets.Struct | AttributeTargets.Enum | AttributeTargets.Interface )] public class WellKnownTypeAttribute : Attribute { // // State // public readonly string TypeName; // // Constructor Methods // public WellKnownTypeAttribute( string typeName ) { this.TypeName = typeName; } } } ================================================ FILE: Zelig/Zelig/RunTime/Zelig/Common/Attributes/TypeSystem/WellKnownTypeLookupAttribute.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // namespace Microsoft.Zelig.Runtime.TypeSystem { using System; [AttributeUsage(AttributeTargets.Field)] public class WellKnownTypeLookupAttribute : Attribute { // // State // public readonly string AssemblyName; public readonly string Namespace; public readonly string Name; // // Constructor Methods // public WellKnownTypeLookupAttribute( string assemblyName , string nameSpace , string name ) { this.AssemblyName = assemblyName; this.Namespace = nameSpace; this.Name = name; } } } ================================================ FILE: Zelig/Zelig/RunTime/Zelig/Common/Collections/BitVector.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // namespace Microsoft.Zelig { using System; using System.Collections; using System.Collections.Generic; public class BitVector { const int c_BitsPerWord = 32; const int c_MinWords = 4; const uint c_WordMask = 0xFFFFFFFFU; //--// public static readonly BitVector[] SharedEmptyArray = new BitVector[0]; //--// // // State // private uint[] m_bitArray; internal int m_cardinalityCache; internal int m_version; // // Constructor Methods // public BitVector() : this( c_MinWords * c_BitsPerWord ) { } public BitVector( int size ) { int arraySize = (size + c_BitsPerWord - 1) / c_BitsPerWord; if(arraySize < c_MinWords) { arraySize = c_MinWords; } m_bitArray = new uint[arraySize]; m_cardinalityCache = 0; m_version = 0; } public BitVector( uint[] state ) { m_bitArray = ArrayUtility.CopyNotNullArray( state ); m_cardinalityCache = -1; m_version = 0; } //--// // // Helper Methods // public static BitVector[] AllocateBitVectors( int num , int size ) { BitVector[] res = new BitVector[num]; for(int i = 0; i < num; i++) { res[i] = new BitVector( size ); } return res; } public static BitVector[] Pivot( BitVector[] arrayXbyY , int sizeX , int sizeY ) { CHECKS.ASSERT( arrayXbyY.Length == sizeX, "Incorrect input array" ); BitVector[] arrayYbyX = AllocateBitVectors( sizeY, sizeX ); for(int posX = 0; posX < sizeX; posX++) { BitVector vecX = arrayXbyY[posX]; CHECKS.ASSERT( vecX.Size >= sizeY, "Incorrect input array" ); if(vecX.m_cardinalityCache != 0) { for(int posY = 0; posY < sizeY; posY += c_BitsPerWord) { uint word = vecX.m_bitArray[posY / c_BitsPerWord]; while(word != 0) { int bitPos = GetPositionOfFirstBitSet( word ); word = word & ~(1U << bitPos); BitVector vecY = arrayYbyX[posY + bitPos]; vecY.m_bitArray[posX / c_BitsPerWord] |= 1U << (posX % c_BitsPerWord); vecY.m_cardinalityCache++; } } } } return arrayYbyX; } //--// public override bool Equals( object other ) { if(other is BitVector) { return Equals( (BitVector)other ); } return false; } public override int GetHashCode() { uint hash = 1234; for(int i = m_bitArray.Length; i >= 0; i--) { hash = (hash << 4) ^ (hash >> 28) ^ m_bitArray[i]; } return (int)((hash >> 32) ^ hash); } //--// public static bool operator ==( BitVector left , BitVector right ) { if((object)left == null) { return (object)right == null; } if((object)right == null) { return false; } return left.Equals( right ); } public static bool operator !=( BitVector left , BitVector right ) { return !(left == right); } public bool Equals( BitVector other ) { // // Fast negative check. // if(m_cardinalityCache != other.m_cardinalityCache) { if( m_cardinalityCache >= 0 && other.m_cardinalityCache >= 0 ) { return false; } } uint[] myArray = this .m_bitArray; uint[] otherArray = other .m_bitArray; int otherSize = otherArray.Length; int mySize = myArray.Length; int minimum = Math.Min( mySize, otherSize ); for(int i = minimum - 1; i >= 0; i--) { if(myArray[i] != otherArray[i]) { return false; } } if(mySize < otherSize) { for(int i = mySize; i < otherSize; i++) { if(otherArray[i] != 0) { return false; } } } else { for(int i = otherSize; i < mySize; i++) { if(myArray[i] != 0) { return false; } } } return true; } public BitVector Clone() { BitVector res = (BitVector)MemberwiseClone(); res.m_bitArray = ArrayUtility.CopyNotNullArray( m_bitArray ); return res; } public uint[] ToDirectArray() { m_cardinalityCache = -1; m_version++; return m_bitArray; } //--// public bool Get( int index ) { int arrayIndex = index / c_BitsPerWord; if(arrayIndex < m_bitArray.Length) { uint mask = 1U << (index % c_BitsPerWord); return (m_bitArray[arrayIndex] & mask) != 0; } return false; } public bool Set( int index ) { BumpVersion(); EnsureCapacityInBits( index + 1 ); int arrayIndex = index / c_BitsPerWord; uint old = m_bitArray[arrayIndex]; uint mask = 1U << (index % c_BitsPerWord); uint newVal = old | mask; bool fChanged = (newVal != old); if(fChanged) { m_bitArray[arrayIndex] = newVal; if(m_cardinalityCache != -1) { m_cardinalityCache++; } } return fChanged; } public bool Clear( int index ) { BumpVersion(); EnsureCapacityInBits( index + 1 ); int arrayIndex = index / c_BitsPerWord; uint old = m_bitArray[arrayIndex]; uint mask = 1U << (index % c_BitsPerWord); uint newVal = old & ~mask; bool fChanged = (newVal != old); if(fChanged) { m_bitArray[arrayIndex] = newVal; if(m_cardinalityCache != -1) { m_cardinalityCache--; } } return fChanged; } //--// public void SetRange( int start , int size ) { if(size == 0) return; EnsureCapacityInBits( start + size ); if(m_cardinalityCache == 0) { m_cardinalityCache = size; } else { m_cardinalityCache = -1; } int i = start / c_BitsPerWord; start = start % c_BitsPerWord; if(start != 0) { uint mask = c_WordMask; if(size + start < c_BitsPerWord) { mask >>= (c_BitsPerWord - size); size = 0; } else { size -= (c_BitsPerWord - start); } m_bitArray[i++] |= mask << start; } while(size >= c_BitsPerWord) { m_bitArray[i++] = c_WordMask; size -= c_BitsPerWord; } if(size > 0) { m_bitArray[i] |= c_WordMask >> (c_BitsPerWord - size); } } public void ClearRange( int start , int size ) { if(size == 0) return; EnsureCapacityInBits( start + size ); if(m_cardinalityCache != 0) { m_cardinalityCache = -1; } int i = start / c_BitsPerWord; start = start % c_BitsPerWord; if(start != 0) { uint mask = c_WordMask; if(size + start < c_BitsPerWord) { mask >>= (c_BitsPerWord - size); size = 0; } else { size -= (c_BitsPerWord - start); } m_bitArray[i++] &= ~(mask << start); } while(size >= c_BitsPerWord) { m_bitArray[i++] = 0; size -= c_BitsPerWord; } if(size > 0) { m_bitArray[i] &= ~(c_WordMask >> (c_BitsPerWord - size)); } } public bool GetRange( out int low , out int high ) { uint[] array = m_bitArray; int size = array.Length; int pos = 0; while(pos < size) { uint word = array[pos]; if(word != 0) { low = pos * c_BitsPerWord + GetPositionOfFirstBitSet( word ); pos = size; while(--pos >= 0) { word = array[pos]; if(word != 0) { high = pos * c_BitsPerWord + GetPositionOfLastBitSet( word ); return true; } } } pos++; } low = int.MaxValue; high = int.MinValue; return false; } public void ClearAll() { if(m_cardinalityCache == 0) { return; // Nothing to do. } for(int i = 0; i < m_bitArray.Length; i++) { m_bitArray[i] = 0; } m_cardinalityCache = 0; } //--// public bool this[int i] { get { return Get( i ); } set { if(value) { Set( i ); } else { Clear( i ); } } } public int Size { get { return m_bitArray.Length * c_BitsPerWord; } } public int Cardinality { get { if(m_cardinalityCache == -1) { uint card = 0; for(int i = m_bitArray.Length - 1; i >= 0; i--) { uint value = m_bitArray[i]; if(value != 0) { card += CountBits( value ); } } m_cardinalityCache = (int)card; } return m_cardinalityCache; } } public bool IsEmpty { get { if(m_cardinalityCache >= 0) { return (m_cardinalityCache == 0); } for(int i = m_bitArray.Length - 1; i >= 0; i--) { if(m_bitArray[i] != 0) { return false; } } return true; } } //--// public void Assign( BitVector other ) { BumpVersion(); uint[] otherArray = other.m_bitArray; int otherSize = otherArray.Length; int mySize = m_bitArray.Length; int size = Math.Max( mySize, otherSize ); EnsureCapacityInWords( size ); uint[] myArray = m_bitArray; m_cardinalityCache = other.m_cardinalityCache; //--// for(int i = size; --i >= otherSize; ) // Clear excess part. { myArray[i] = 0; } for(int i = otherSize; --i >= 0; ) // Copy common part. { myArray[i] = otherArray[i]; } } public void AndInPlace( BitVector other ) { BumpVersion(); uint[] otherArray = other.m_bitArray; int otherSize = otherArray.Length; int mySize = m_bitArray.Length; int size = Math.Max( mySize, otherSize ); EnsureCapacityInWords( size ); uint[] myArray = m_bitArray; m_cardinalityCache = -1; //--// for(int i = size; --i >= otherSize; ) // Clear excess part. { myArray[i] = 0; } for(int i = otherSize; --i >= 0; ) // And common part. { myArray[i] &= otherArray[i]; } } public void OrInPlace( BitVector other ) { BumpVersion(); uint[] otherArray = other.m_bitArray; int otherSize = otherArray.Length; int mySize = m_bitArray.Length; int size = Math.Max( mySize, otherSize ); EnsureCapacityInWords( size ); uint[] myArray = m_bitArray; m_cardinalityCache = -1; //--// for(int i = otherSize; --i >= 0; ) // Or common part (leave excess part as is). { myArray[i] |= otherArray[i]; } } public void XorInPlace( BitVector other ) { BumpVersion(); uint[] otherArray = other.m_bitArray; int otherSize = otherArray.Length; int mySize = m_bitArray.Length; int size = Math.Max( mySize, otherSize ); EnsureCapacityInWords( size ); uint[] myArray = m_bitArray; m_cardinalityCache = -1; //--// for(int i = otherSize; --i >= 0; ) // Xor common part (leave excess part as is). { myArray[i] ^= otherArray[i]; } } public void DifferenceInPlace( BitVector other ) { BumpVersion(); uint[] otherArray = other.m_bitArray; int otherSize = otherArray.Length; int mySize = m_bitArray.Length; int size = Math.Max( mySize, otherSize ); EnsureCapacityInWords( size ); uint[] myArray = m_bitArray; m_cardinalityCache = -1; //--// for(int i = otherSize; --i >= 0; ) // Diff common part (leave excess part as is). { myArray[i] &= ~otherArray[i]; } } public bool IsIntersectionEmpty( BitVector other ) { uint[] myArray = this .m_bitArray; uint[] otherArray = other .m_bitArray; int mySize = myArray .Length; int otherSize = otherArray.Length; int minSize = Math.Min( mySize, otherSize ); for(int i = minSize; --i >= 0; ) // Check common part. { if((myArray[i] & otherArray[i]) != 0) { return false; } } return true; } public bool IsFullyContainedIn( BitVector other ) { uint[] myArray = this .m_bitArray; uint[] otherArray = other .m_bitArray; int mySize = myArray .Length; int otherSize = otherArray.Length; int maxSize = Math.Max( mySize, otherSize ); for(int i = maxSize; --i >= 0; ) // Check the maximal overlap. { uint myValue = (i < mySize ) ? myArray [i] : 0; uint otherValue = (i < otherSize) ? otherArray[i] : 0; if((myValue & otherValue) != myValue) { return false; } } return true; } //--// public void And( BitVector left , BitVector right ) { BumpVersion(); uint[] leftArray = left .m_bitArray; uint[] rightArray = right.m_bitArray; int leftSize = leftArray .Length; int rightSize = rightArray.Length; int maxSize = Math.Max( leftSize, rightSize ); int minSize = Math.Min( leftSize, rightSize ); EnsureCapacityInWords( maxSize ); uint[] myArray = m_bitArray; int mySize = myArray.Length; m_cardinalityCache = -1; //--// for(int i = mySize; --i >= minSize; ) // Clear part not in common. { myArray[i] = 0; } for(int i = minSize; --i >= 0; ) // And part in common. { myArray[i] = leftArray[i] & rightArray[i]; } } public void Or( BitVector left , BitVector right ) { BumpVersion(); uint[] leftArray = left .m_bitArray; uint[] rightArray = right.m_bitArray; int leftSize = leftArray .Length; int rightSize = rightArray.Length; int maxSize = Math.Max( leftSize, rightSize ); int minSize = Math.Min( leftSize, rightSize ); EnsureCapacityInWords( maxSize ); uint[] myArray = m_bitArray; int mySize = myArray.Length; m_cardinalityCache = -1; //--// for(int i = mySize; --i >= maxSize; ) // Clear part not in common. { myArray[i] = 0; } if(leftSize < maxSize) // Copy non-overlapping part. { for(int i = maxSize; --i >= minSize; ) { myArray[i] = rightArray[i]; } } else { for(int i = maxSize; --i >= minSize; ) { myArray[i] = leftArray[i]; } } for(int i = minSize; --i >= 0; ) // Or part in common. { myArray[i] = leftArray[i] | rightArray[i]; } } public void Xor( BitVector left , BitVector right ) { BumpVersion(); uint[] leftArray = left .m_bitArray; uint[] rightArray = right.m_bitArray; int leftSize = leftArray .Length; int rightSize = rightArray.Length; int maxSize = Math.Max( leftSize, rightSize ); int minSize = Math.Min( leftSize, rightSize ); EnsureCapacityInWords( maxSize ); uint[] myArray = m_bitArray; int mySize = myArray.Length; m_cardinalityCache = -1; //--// for(int i = mySize; --i >= maxSize; ) // Clear excess part. { myArray[i] = 0; } if(leftSize < maxSize) // Copy non-overlapping part. { for(int i = maxSize; --i >= minSize; ) { myArray[i] = rightArray[i]; } } else { for(int i = maxSize; --i >= minSize; ) { myArray[i] = leftArray[i]; } } for(int i = minSize; --i >= 0; ) // Xor part in common. { myArray[i] = leftArray[i] ^ rightArray[i]; } } public void Difference( BitVector left , BitVector right ) { BumpVersion(); uint[] leftArray = left .m_bitArray; uint[] rightArray = right.m_bitArray; int leftSize = leftArray .Length; int rightSize = rightArray.Length; int maxSize = Math.Max( leftSize, rightSize ); int minSize = Math.Min( leftSize, rightSize ); EnsureCapacityInWords( maxSize ); uint[] myArray = m_bitArray; int mySize = myArray.Length; m_cardinalityCache = -1; //--// for(int i = mySize; --i >= maxSize; ) // Clear excess part. { myArray[i] = 0; } if(leftSize < maxSize) { for(int i = maxSize; --i >= minSize; ) // Clear non-overlapping part (left is smaller, so it's always zero). { myArray[i] = 0; } } else { for(int i = maxSize; --i >= minSize; ) // Copy non-overlapping part (right is smaller, so it's always zero). { myArray[i] = leftArray[i]; } } for(int i = minSize; --i >= 0; ) // Diff common part. { myArray[i] = leftArray[i] & ~rightArray[i]; } } // // BEWARE: Since we don't track the exact number of bits, // complement affects more bits than it might be expected. // // For example, creating a BitVector with all bits set and then complementing it // doesn't return zero as the cardinality of the vector, as expected, but 32 - % 32. // public void Complement() { BumpVersion(); int size = m_bitArray.Length; // complement one word at a time for(int i = 0; i < size; i++) { m_bitArray[i] = ~m_bitArray[i]; } if(m_cardinalityCache >= 0) { m_cardinalityCache = (size * c_BitsPerWord) - m_cardinalityCache; } } //--// //// public static BitVector operator & ( BitVector left , //// BitVector right ) //// { //// BitVector res = left.Clone(); //// //// res.AndInPlace( right ); //// //// return res; //// } //// //// public static BitVector operator | ( BitVector left , //// BitVector right ) //// { //// BitVector res = left.Clone(); //// //// res.OrInPlace( right ); //// //// return res; //// } //// //// public static BitVector operator ^ ( BitVector left , //// BitVector right ) //// { //// BitVector res = left.Clone(); //// //// res.XorInPlace( right ); //// //// return res; //// } //// //// public static BitVector operator - ( BitVector left , //// BitVector right ) //// { //// BitVector res = left.Clone(); //// //// res.DifferenceInPlace( right ); //// //// return res; //// } //// //// public static BitVector operator ~ ( BitVector left ) //// { //// BitVector res = left.Clone(); //// //// res.Complement(); //// //// return res; //// } //--// public Enumerator GetEnumerator() { return new Enumerator( this ); } //--// // // Helper Methods // protected void BumpVersion() { #if DEBUG m_version++; #endif } protected void EnsureCapacityInBits( int bits ) { int arraySize = (bits + c_BitsPerWord - 1) / c_BitsPerWord; EnsureCapacityInWords( arraySize ); } protected void EnsureCapacityInWords( int arraySize ) { int size = m_bitArray.Length; if(size < arraySize) { uint[] oldArray = m_bitArray; m_bitArray = new uint[arraySize]; Array.Copy( oldArray, m_bitArray, size ); } } //--// public static uint CountBits( uint value ) { // // In-place adder tree: // // perform 16 1-bit adds, // 8 2-bit adds, // 4 4-bit adds, // 2 8-bit adds, and // 1 16-bit add. // value = ((value >> 1) & 0x55555555) + (value & 0x55555555); value = ((value >> 2) & 0x33333333) + (value & 0x33333333); value = ((value >> 4) & 0x0F0F0F0F) + (value & 0x0F0F0F0F); value = ((value >> 8) & 0x00FF00FF) + (value & 0x00FF00FF); value = ((value >> 16) & 0x0000FFFF) + (value & 0x0000FFFF); return value; } public static int GetPositionOfFirstBitSet( uint w ) { int bitPos = 0; if((w & 0xFFFF) == 0) { w >>= 16; bitPos += 16; } if((w & 0x00FF) == 0) { w >>= 8; bitPos += 8; } if((w & 0x000F) == 0) { w >>= 4; bitPos += 4; } if((w & 0x0003) == 0) { w >>= 2; bitPos += 2; } if((w & 0x0001) == 0) { w >>= 1; bitPos += 1; } return bitPos; } public static int GetPositionOfFirstBitSet( ulong w ) { uint wHi = (uint)(w >> 32); uint wLo = (uint) w; if(wLo != 0) { return GetPositionOfFirstBitSet( wLo ); } else { return GetPositionOfFirstBitSet( wHi ); } } public static int GetPositionOfLastBitSet( uint w ) { int bitPos = 0; if((w >> 16) != 0) { w >>= 16; bitPos += 16; } if((w >> 8) != 0) { w >>= 8; bitPos += 8; } if((w >> 4) != 0) { w >>= 4; bitPos += 4; } if((w >> 2) != 0) { w >>= 2; bitPos += 2; } if((w >> 1) != 0) { w >>= 1; bitPos += 1; } return bitPos; } public static int GetPositionOfLastBitSet( ulong w ) { uint wHi = (uint)(w >> 32); uint wLo = (uint) w; if(wHi != 0) { return GetPositionOfLastBitSet( wHi ) + 32; } else { return GetPositionOfLastBitSet( wLo ); } } /////////////////////////////////////////// public struct Enumerator { // // State // private readonly BitVector m_owner; private readonly int m_version; private uint m_word; private int m_index; private int m_current; // // Constructor Methods // internal Enumerator( BitVector owner ) { m_owner = owner; m_version = owner.m_version; m_word = m_owner.m_bitArray[0]; m_index = 0; m_current = -1; } public void Dispose() { } public bool MoveNext() { #if DEBUG if(m_version != m_owner.m_version) { throw new InvalidOperationException( "Enumerator version check failed" ); } #endif if(hasMoreElements()) { m_current = nextInt(); return true; } else { m_current = -2; return false; } } public int Current { get { if(m_current == -1) { throw new InvalidOperationException( "Enumerator not started" ); } else if(m_current == -2) { throw new InvalidOperationException( "Enumerator is empty" ); } else { return m_current; } } } //--// private bool hasMoreElements() { uint[] array = m_owner.m_bitArray; int size = array.Length; while(m_word == 0 && ++m_index < size) { m_word = array[m_index]; } return (m_word != 0); } private int nextInt() { int bitPos = GetPositionOfFirstBitSet( m_word ); m_word = m_word & ~(1U << bitPos); return bitPos + m_index * c_BitsPerWord; } } // // Debug Methods // public override String ToString() { System.Text.StringBuilder result = new System.Text.StringBuilder( "{" ); bool empty = true; int size = m_bitArray.Length; int bitNumber = 0; for(int arrayIndex = 0; arrayIndex < size; arrayIndex++) { uint bits = m_bitArray[arrayIndex]; if(bits != 0) { uint mask = 1; while(mask != 0) { if((bits & mask) != 0) { if(empty) { empty = false; } else { result = result.Append( ", " ); } result = result.Append( bitNumber ); } bitNumber++; mask <<= 1; } } else { bitNumber += 32; } } result = result.Append( "}" ); return result.ToString(); } } } ================================================ FILE: Zelig/Zelig/RunTime/Zelig/Common/Collections/GrowOnlyHashTable.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // //#define DETECT_HIGH_COLLISION_RATES namespace Microsoft.Zelig { using System; using System.Collections; using System.Collections.Generic; public class GrowOnlyHashTable< TKey, TValue > { // // State // private int[] m_buckets; private int[] m_entries_HashCode; // Lower 31 bits of hash code, -1 if unused private int[] m_entries_Next; // Index of next entry, -1 if last private TKey[] m_entries_Key; // Key of entry private TValue[] m_entries_Value; // Value of entry private int m_bucketThreshold; private int m_count; private int m_version; private IEqualityComparer< TKey > m_comparer; private KeyEnumerable m_keys; private ValueEnumerable m_values; // // Constructor Methods // protected GrowOnlyHashTable() : this( EqualityComparer< TKey >.Default ) { } internal GrowOnlyHashTable( IEqualityComparer< TKey > comparer ) { m_comparer = comparer; } // // Access Methods // public int Count { get { return m_count; } } public TValue this[TKey key] { get { int i = FindEntry( key ); if(i >= 0) { return m_entries_Value[i]; } throw new Exception( "Key Not Found" ); } set { Insert( key, value, false ); } } public KeyEnumerable Keys { get { if(m_keys == null) { m_keys = new KeyEnumerable( this ); } return m_keys; } } public ValueEnumerable Values { get { if(m_values == null) { m_values = new ValueEnumerable( this ); } return m_values; } } public GrowOnlyHashTable< TKey, TValue > CloneSettings() { return new GrowOnlyHashTable< TKey, TValue >( m_comparer ); } public GrowOnlyHashTable CloneSettingsAndSize() { GrowOnlyHashTable res = new GrowOnlyHashTable( m_comparer ); res.Initialize( this.Count ); return res; } public GrowOnlyHashTable< TKey, TValue > Clone() { GrowOnlyHashTable< TKey, TValue > copy = CloneSettings(); if(m_count > 0) { copy.m_buckets = ArrayUtility.CopyNotNullArray( m_buckets ); copy.m_entries_HashCode = ArrayUtility.CopyNotNullArray( m_entries_HashCode ); copy.m_entries_Next = ArrayUtility.CopyNotNullArray( m_entries_Next ); copy.m_entries_Key = ArrayUtility.CopyNotNullArray( m_entries_Key ); copy.m_entries_Value = ArrayUtility.CopyNotNullArray( m_entries_Value ); copy.m_bucketThreshold = m_bucketThreshold; copy.m_count = m_count; } return copy; } // // Helper Methods // public void Clear() { m_buckets = null; m_entries_HashCode = null; m_entries_Next = null; m_entries_Key = null; m_entries_Value = null; m_bucketThreshold = 0; m_count = 0; m_version++; } public void RefreshHashCodes() { for(int i = 0; i < m_count; i++) { m_entries_HashCode[i] = m_comparer.GetHashCode( m_entries_Key[i] ) & 0x7FFFFFFF; } RebuildBuckets(); } public bool TryGetKey( TKey key , out TKey value ) { int i = FindEntry( key ); if(i >= 0) { value = m_entries_Key[i]; return true; } value = default( TKey ); return false; } public bool TryGetValue( TKey key , out TValue value ) { int i = FindEntry( key ); if(i >= 0) { value = m_entries_Value[i]; return true; } value = default( TValue ); return false; } public TKey GetKey( TKey key ) { int i = FindEntry( key ); if(i >= 0) { return m_entries_Key[i]; } return default( TKey ); } public TValue GetValue( TKey key ) { int i = FindEntry( key ); if(i >= 0) { return m_entries_Value[i]; } return default( TValue ); } public void Add( TKey key , TValue value ) { Insert( key, value, true ); } public bool Update( TKey key , TValue value ) { return Insert( key, value, false ); } public bool ContainsKey( TKey key ) { return FindEntry( key ) >= 0; } public bool ContainsValue( TValue value ) { return FindValue( value ) >= 0; } public bool ContainsValue( TValue value , out TKey key ) { int pos = FindValue( value ); if(pos >= 0) { key = m_entries_Key[pos]; return true; } else { key = default( TKey ); return false; } } public void Merge( GrowOnlyHashTable< TKey, TValue > target ) { for(int i = 0; i < target.m_count; i++) { this[ target.m_entries_Key[i] ] = target.m_entries_Value[i]; } } public KeyValuePair< TKey, TValue >[] ToArray() { KeyValuePair< TKey, TValue >[] res = new KeyValuePair< TKey, TValue >[m_count]; for(int i = 0; i < m_count; i++) { res[i] = new KeyValuePair< TKey, TValue >( m_entries_Key[i], m_entries_Value[i] ); } return res; } public TKey[] KeysToArray() { TKey[] res = new TKey[m_count]; if(m_count > 0) { Array.Copy( m_entries_Key, res, m_count ); } return res; } public TValue[] ValuesToArray() { TValue[] res = new TValue[m_count]; if(m_count > 0) { Array.Copy( m_entries_Value, res, m_count ); } return res; } public void Load( TKey[] keys , TValue[] values ) { int size = keys.Length; Initialize( size ); m_count = size; m_version++; Array.Copy( keys , m_entries_Key , size ); Array.Copy( values, m_entries_Value, size ); RefreshHashCodes(); } //--// private void Initialize( int capacity ) { int size = HashHelpers.GetPrime( capacity ); m_buckets = new int [size]; m_entries_HashCode = new int [size]; m_entries_Next = new int [size]; m_entries_Key = new TKey [size]; m_entries_Value = new TValue[size]; m_bucketThreshold = 3 * size / 4; } private void Resize() { int newSize = HashHelpers.GetPrime( m_count * 2 ); int[] newBuckets = new int [newSize]; int[] newEntries_HashCode = new int [newSize]; int[] newEntries_Next = new int [newSize]; TKey[] newEntries_Key = new TKey [newSize]; TValue[] newEntries_Value = new TValue[newSize]; Array.Copy( m_entries_HashCode, 0, newEntries_HashCode, 0, m_count ); Array.Copy( m_entries_Key , 0, newEntries_Key , 0, m_count ); Array.Copy( m_entries_Value , 0, newEntries_Value , 0, m_count ); m_buckets = newBuckets; m_entries_HashCode = newEntries_HashCode; m_entries_Next = newEntries_Next; m_entries_Key = newEntries_Key; m_entries_Value = newEntries_Value; m_bucketThreshold = 3 * newSize / 4; RebuildBuckets(); } private void RebuildBuckets() { if(m_buckets != null) { int size = m_buckets.Length; Array.Clear( m_buckets, 0, size ); for(int i = 0; i < m_count; i++) { int bucket = m_entries_HashCode[i] % size; m_entries_Next[i] = m_buckets[bucket]; m_buckets[bucket] = i + 1; } } } private int FindEntry( TKey key ) { if(m_buckets != null) { int hashCode = m_comparer.GetHashCode( key ) & 0x7FFFFFFF; for(int i = m_buckets[hashCode % m_buckets.Length]; i-- > 0; i = m_entries_Next[i]) { if(m_entries_HashCode[i] == hashCode && m_comparer.Equals( m_entries_Key[i], key )) { return i; } } } return -1; } private int FindValue( TValue value ) { if(value == null) { for(int i = 0; i < m_count; i++) { if(m_entries_Value[i] == null) { return i; } } } else { EqualityComparer c = EqualityComparer.Default; for(int i = 0; i < m_count; i++) { if(c.Equals( m_entries_Value[i], value )) { return i; } } } return -1; } #if DETECT_HIGH_COLLISION_RATES uint m_collisions = 0; #endif private bool Insert( TKey key , TValue value , bool unique ) { if(m_buckets == null) { Initialize( 32 ); } int hashCode = m_comparer.GetHashCode( key ) & 0x7FFFFFFF; int targetBucket = hashCode % m_buckets.Length; for(int i = m_buckets[targetBucket]; i-- > 0; i = m_entries_Next[i]) { if(m_entries_HashCode[i] == hashCode && m_comparer.Equals( m_entries_Key[i], key )) { if(unique) { throw new Exception( "Duplicate Key" ); } m_entries_Value[i] = value; m_version++; return true; } } if(m_count >= m_bucketThreshold) { #if DETECT_HIGH_COLLISION_RATES double collRate = (double)m_collisions / (double)m_count; if(collRate > 0.40 && m_count > 1000) { Console.WriteLine( "***** HIGH COLLISION RATE" ); Console.WriteLine( "***** Collision Rate: {0}", collRate ); Console.WriteLine( "***** KEY TYPE: " + key.GetType() ); Console.WriteLine( "***** Total Hash Count: {0}", m_count ); } m_collisions = 0; #endif Resize(); targetBucket = hashCode % m_buckets.Length; } int index = m_count++; #if DETECT_HIGH_COLLISION_RATES if(m_buckets[targetBucket] != 0) m_collisions++; #endif m_entries_HashCode[index] = hashCode; m_entries_Next [index] = m_buckets[targetBucket]; m_entries_Key [index] = key; m_entries_Value [index] = value; m_buckets[targetBucket] = index + 1; m_version++; return false; } //--// // // Debug Methods // public void Dump() { for(int i = 0; i < m_count; i++) { Console.WriteLine( "{0} = {1} => {2}", i, m_entries_Key[i], m_entries_Value[i] ); } } //--//--//--//--//--//--//--//--// public sealed class KeyEnumerable { // // State // private GrowOnlyHashTable< TKey, TValue > m_owner; // // Constructor Methods // public KeyEnumerable( GrowOnlyHashTable< TKey, TValue > owner ) { m_owner = owner; } public Enumerator< TKey > GetEnumerator() { return new Enumerator< TKey >( m_owner, m_owner.m_entries_Key ); } } public sealed class ValueEnumerable { // // State // private GrowOnlyHashTable< TKey, TValue > m_owner; // // Constructor Methods // public ValueEnumerable( GrowOnlyHashTable< TKey, TValue > owner ) { m_owner = owner; } public Enumerator< TValue > GetEnumerator() { return new Enumerator< TValue >( m_owner, m_owner.m_entries_Value ); } } public struct Enumerator { // // State // private GrowOnlyHashTable< TKey, TValue > m_owner; private int m_index; private int m_version; private T[] m_values; // // Constructor Methods // internal Enumerator( GrowOnlyHashTable< TKey, TValue > owner , T[] values ) { m_owner = owner; m_version = owner.m_version; m_index = 0; m_values = values; } public void Dispose() { } public bool MoveNext() { if(m_version != m_owner.m_version) { throw new Exception( "Dictionary changed" ); } if(m_index < m_owner.m_count) { m_index++; return true; } return false; } public T Current { get { return m_values[m_index-1]; } } void Reset() { if(m_version != m_owner.m_version) { throw new Exception( "Dictionary changed" ); } m_index = 0; } } } } ================================================ FILE: Zelig/Zelig/RunTime/Zelig/Common/Collections/GrowOnlyList.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // namespace Microsoft.Zelig { using System; using System.Collections; using System.Collections.Generic; public class GrowOnlyList< T > { class Cluster { internal const int DefaultCapacity = 4; internal const int MaxCapacity = 256; // // State // internal Cluster m_next; internal readonly T[] m_elements; internal int m_pos; // // Costructor Methods // internal Cluster( int capacity ) { m_elements = new T[capacity]; m_pos = 0; } // // Helper Methods // internal Cluster Add( T obj ) { int capacity = m_elements.Length; if(m_pos == capacity) { m_next = new Cluster( Math.Min( capacity * 2, MaxCapacity ) ); return m_next.Add( obj ); } m_elements[m_pos++] = obj; return this; } } // // State // private Cluster m_first; private Cluster m_last; private int m_count; // // Costructor Methods // public GrowOnlyList() { Clear(); } // // Helper Methods // public void Clear() { m_first = new Cluster( Cluster.DefaultCapacity ); m_last = m_first; m_count = 0; } public void Add( T obj ) { m_last = m_last.Add( obj ); m_count++; } //--// public Enumerator GetEnumerator() { return new Enumerator( this ); } // // Access Methods // public int Count { get { return m_count; } } public T this[int index] { get { if(index >= 0 && index < m_count) { for(Cluster cluster = m_first; cluster != null; cluster = cluster.m_next) { if(index < cluster.m_pos) { return cluster.m_elements[index]; } index -= cluster.m_pos; } } throw new ArgumentOutOfRangeException(); } set { if(index >= 0 && index < m_count) { for(Cluster cluster = m_first; cluster != null; cluster = cluster.m_next) { if(index < cluster.m_pos) { cluster.m_elements[index] = value; return; } index -= cluster.m_pos; } } throw new ArgumentOutOfRangeException(); } } //--//--//--//--//--//--//--//--// public struct Enumerator { // // State // private Cluster m_first; private Cluster m_current; private int m_index; // // Constructor Methods // internal Enumerator( GrowOnlyList< T > list ) { m_first = list.m_first; m_current = m_first; m_index = 0; } public void Dispose() { } public bool MoveNext() { while(m_current != null) { if(m_index < m_current.m_pos) { m_index++; return true; } m_current = m_current.m_next; m_index = 0; } return false; } public T Current { get { return m_current.m_elements[m_index-1]; } } void Reset() { m_current = m_first; m_index = 0; } } } } ================================================ FILE: Zelig/Zelig/RunTime/Zelig/Common/Collections/GrowOnlySet.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // namespace Microsoft.Zelig { using System; using System.Collections; using System.Collections.Generic; public class GrowOnlySet< TKey > { // // State // private int[] m_buckets; private int[] m_entries_HashCode; // Lower 31 bits of hash code, -1 if unused private int[] m_entries_Next; // Index of next entry, -1 if last private TKey[] m_entries_Key; // Key of entry private int m_count; private int m_version; private IEqualityComparer< TKey > m_comparer; // // Constructor Methods // protected GrowOnlySet() : this( EqualityComparer< TKey >.Default ) { } internal GrowOnlySet( IEqualityComparer< TKey > comparer ) { m_comparer = comparer; } // // Helper Methods // public void Clear() { m_buckets = null; m_entries_HashCode = null; m_entries_Next = null; m_entries_Key = null; m_count = 0; m_version++; } public void RefreshHashCodes() { for(int i = 0; i < m_count; i++) { m_entries_HashCode[i] = m_comparer.GetHashCode( m_entries_Key[i] ) & 0x7FFFFFFF; } RebuildBuckets(); } public bool Insert( TKey key ) { if(m_buckets == null) { Initialize( 0 ); } int hashCode = m_comparer.GetHashCode( key ) & 0x7FFFFFFF; int targetBucket = hashCode % m_buckets.Length; for(int i = m_buckets[targetBucket]; i-- > 0; i = m_entries_Next[i]) { if(m_entries_HashCode[i] == hashCode && m_comparer.Equals( m_entries_Key[i], key )) { return true; } } if(m_count == m_entries_HashCode.Length) { Resize(); targetBucket = hashCode % m_buckets.Length; } int index = m_count++; m_entries_HashCode[index] = hashCode; m_entries_Next [index] = m_buckets[targetBucket]; m_entries_Key [index] = key; m_buckets[targetBucket] = index + 1; m_version++; return false; } public TKey MakeUnique( TKey key ) { TKey oldKey; if(Contains( key, out oldKey )) { return oldKey; } Insert( key ); return key; } public bool Contains( TKey key ) { return FindEntry( key ) >= 0; } public bool Contains( TKey key , out TKey value ) { int i = FindEntry( key ); if(i >= 0) { value = m_entries_Key[i]; return true; } value = default( TKey ); return false; } public Enumerator GetEnumerator() { return new Enumerator( this, m_entries_Key ); } public void Merge( GrowOnlySet< TKey > target ) { int num = target.m_count; TKey[] keys = target.m_entries_Key; for(int i = 0; i < num; i++) { this.Insert( keys[i] ); } } public TKey[] ToArray() { TKey[] res = new TKey[m_count]; if(m_count > 0) { Array.Copy( m_entries_Key, res, m_count ); } return res; } public void Load( TKey[] keys ) { int size = keys.Length; Initialize( size ); m_count = size; m_version++; Array.Copy( keys, m_entries_Key, size ); RefreshHashCodes(); } //--// private void Initialize( int capacity ) { int size = HashHelpers.GetPrime( capacity ); m_buckets = new int [size]; m_entries_HashCode = new int [size]; m_entries_Next = new int [size]; m_entries_Key = new TKey[size]; } private void Resize() { int newSize = HashHelpers.GetPrime( m_count * 2 ); int[] newBuckets = new int [newSize]; int[] newEntries_HashCode = new int [newSize]; int[] newEntries_Next = new int [newSize]; TKey[] newEntries_Key = new TKey[newSize]; Array.Copy( m_entries_HashCode, 0, newEntries_HashCode, 0, m_count ); Array.Copy( m_entries_Key , 0, newEntries_Key , 0, m_count ); m_buckets = newBuckets; m_entries_HashCode = newEntries_HashCode; m_entries_Next = newEntries_Next; m_entries_Key = newEntries_Key; RebuildBuckets(); } private void RebuildBuckets() { if(m_buckets != null) { int size = m_buckets.Length; Array.Clear( m_buckets, 0, size ); for(int i = 0; i < m_count; i++) { int bucket = m_entries_HashCode[i] % size; m_entries_Next[i] = m_buckets[bucket]; m_buckets[bucket] = i + 1; } } } private int FindEntry( TKey key ) { if(m_buckets != null) { int hashCode = m_comparer.GetHashCode( key ) & 0x7FFFFFFF; for(int i = m_buckets[hashCode % m_buckets.Length]; i-- > 0; i = m_entries_Next[i]) { if(m_entries_HashCode[i] == hashCode && m_comparer.Equals( m_entries_Key[i], key )) { return i; } } } return -1; } //--// // // Access Methods // public int Count { get { return m_count; } } public GrowOnlySet< TKey > CloneSettings() { return new GrowOnlySet< TKey >( m_comparer ); } public GrowOnlySet< TKey > Clone() { GrowOnlySet< TKey > copy = CloneSettings(); if(m_count > 0) { copy.m_buckets = ArrayUtility.CopyNotNullArray( m_buckets ); copy.m_entries_HashCode = ArrayUtility.CopyNotNullArray( m_entries_HashCode ); copy.m_entries_Next = ArrayUtility.CopyNotNullArray( m_entries_Next ); copy.m_entries_Key = ArrayUtility.CopyNotNullArray( m_entries_Key ); copy.m_count = m_count; } return copy; } //--// // // Debug Methods // public void Dump() { for(int i = 0; i < m_count; i++) { Console.WriteLine( "{0} = {1}", i, m_entries_Key[i] ); } } //--//--//--//--//--//--//--//--// public struct Enumerator { // // State // private GrowOnlySet< TKey > m_dictionary; private int m_index; private int m_version; private TKey[] m_values; // // Constructor Methods // internal Enumerator( GrowOnlySet< TKey > dictionary , TKey[] values ) { m_dictionary = dictionary; m_version = dictionary.m_version; m_index = 0; m_values = values; } public void Dispose() { } public bool MoveNext() { if(m_version != m_dictionary.m_version) { throw new Exception( "Dictionary changed" ); } if(m_index < m_dictionary.m_count) { m_index++; return true; } return false; } public TKey Current { get { return m_values[m_index-1]; } } void Reset() { if(m_version != m_dictionary.m_version) { throw new Exception( "Dictionary changed" ); } m_index = 0; } } } } ================================================ FILE: Zelig/Zelig/RunTime/Zelig/Common/Collections/HashHelpers.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // namespace Microsoft.Zelig { using System; internal static class HashHelpers { // Table of prime numbers to use as hash table sizes. // The entry used for capacity is the smallest prime number in this array // that is larger than twice the previous capacity. internal static readonly int[] primes = { 3, 7, 11, 17, 23, 29, 37, 47, 59, 71, 89, 107, 131, 163, 197, 239, 293, 353, 431, 521, 631, 761, 919, 1103, 1327, 1597, 1931, 2333, 2801, 3371, 4049, 4861, 5839, 7013, 8419, 10103, 12143, 14591, 17519, 21023, 25229, 30293, 36353, 43627, 52361, 62851, 75431, 90523, 108631, 130363, 156437, 187751, 225307, 270371, 324449, 389357, 467237, 560689, 672827, 807403, 968897, 1162687, 1395263, 1674319, 2009191, 2411033, 2893249, 3471899, 4166287, 4999559, 5999471, 7199369 }; internal static int GetPrime( int min ) { if(min < 0) { throw new ArgumentException( "Wrong min value" ); } for(int i = 0; i < primes.Length; i++) { int prime = primes[i]; if(prime >= min) return prime; } // // Well, if your hashtable has 7 million entries, // using a non-prime number for the bucket size is the least of your problems... // return min; } } } ================================================ FILE: Zelig/Zelig/RunTime/Zelig/Common/Collections/ReferenceEqualityComparer.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // namespace Microsoft.Zelig { using System; using System.Collections.Generic; public class ReferenceEqualityComparer : IEqualityComparer where T : class { public bool Equals( T x , T y ) { return Object.ReferenceEquals( x, y ); } public int GetHashCode( T obj ) { return obj != null ? obj.GetHashCode() : 0; } } } ================================================ FILE: Zelig/Zelig/RunTime/Zelig/Common/Collections/UniqueList.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // namespace Microsoft.Zelig.Collections.Generic { using System; using System.Collections.Generic; public class UniqueList : List where T : IEquatable< T > { // // Constructor Methods // public UniqueList() : base() { } public UniqueList( int capacity ) : base( capacity ) { } // // Helper Methods // public void AddUnique( T item ) { for(int i = 0; i < this.Count; i++) { if(this[i].Equals( item )) { return; } } Add( item ); } public int UniqueIndexOf( T item ) { for(int i = 0; i < this.Count; i++) { if(this[i].Equals( item )) { return i; } } return -1; } public bool ContainsUnique( T item ) { for(int i = 0; i < this.Count; i++) { if(this[i].Equals( item )) { return true; } } return false; } } } ================================================ FILE: Zelig/Zelig/RunTime/Zelig/Common/Collections/WeakEqualityComparer.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // namespace Microsoft.Zelig { using System; using System.Collections.Generic; public class WeakEqualityComparer : IEqualityComparer { public bool Equals( T x , T y ) { if(x is ValueType && y is ValueType) { return Object.Equals( x, y ); } if(x is string && y is string) { return 0 == string.Compare( x as string, y as string ); } return Object.ReferenceEquals( x, y ); } public int GetHashCode( T obj ) { return obj != null ? obj.GetHashCode() : 0; } } } ================================================ FILE: Zelig/Zelig/RunTime/Zelig/Common/Common.csproj ================================================  Debug AnyCPU {186F31A3-EF89-4A25-B2D5-20061218AA01} Library Properties Microsoft.Zelig.Runtime Microsoft.Zelig.Runtime.Common $(LlilumBuildRoot)\Host\obj\$(MSBuildProjectName)\ v4.5 true full false $(LlilumBuildRoot)\Host\bin\$(Configuration)\ DEBUG;TRACE prompt 4 true true AllRules.ruleset AnyCPU false pdbonly true $(LlilumBuildRoot)\Host\bin\$(Configuration)\ TRACE prompt 4 true true AllRules.ruleset AnyCPU false true full false $(LlilumBuildRoot)\Host\bin\$(Configuration)\ AnyCPU TRACE;DEBUG true true false 3.5 {186F31A3-EF89-4A25-B2D5-20070519AA01} ArmProcessor ================================================ FILE: Zelig/Zelig/RunTime/Zelig/Common/Configuration/Attributes/AbstractDefaultsAttribute.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // namespace Microsoft.Zelig.Configuration.Environment { using System; using System.Collections.Generic; public abstract class AbstractDefaultsAttribute : Attribute { // // State // public readonly string Member; public readonly object Value; protected bool m_merge; // // Constructor Methods // protected AbstractDefaultsAttribute( string member , object value ) { this.Member = member; this.Value = value; } // // Access Methods // public bool Merge { get { return m_merge; } } } } ================================================ FILE: Zelig/Zelig/RunTime/Zelig/Common/Configuration/Attributes/AllowedOptionsAttribute.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // namespace Microsoft.Zelig.Configuration.Environment { using System; using System.Collections.Generic; [AttributeUsage( AttributeTargets.Field, AllowMultiple=false)] public sealed class AllowedOptionsAttribute : Attribute { // // State // public Type[] Targets; // // Constructor Methods // public AllowedOptionsAttribute( params Type[] targets ) { this.Targets = targets; } } } ================================================ FILE: Zelig/Zelig/RunTime/Zelig/Common/Configuration/Attributes/DefaultsAttribute.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // namespace Microsoft.Zelig.Configuration.Environment { using System; using System.Collections.Generic; [AttributeUsage( AttributeTargets.Class | AttributeTargets.Field , AllowMultiple=true )] public sealed class DefaultsAttribute : AbstractDefaultsAttribute { // // Constructor Methods // public DefaultsAttribute( string member , bool value ) : base( member, value ) { } public DefaultsAttribute( string member , int value ) : base( member, value ) { } public DefaultsAttribute( string member , uint value ) : base( member, value ) { } public DefaultsAttribute( string member , long value ) : base( member, value ) { } public DefaultsAttribute( string member , ulong value ) : base( member, value ) { } public DefaultsAttribute( string member , string value ) : base( member, value ) { } public DefaultsAttribute( string member , Type value ) : base( member, value ) { } } } ================================================ FILE: Zelig/Zelig/RunTime/Zelig/Common/Configuration/Attributes/DependsOnAttribute.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // namespace Microsoft.Zelig.Configuration.Environment { using System; using System.Collections.Generic; [AttributeUsage( AttributeTargets.Class, AllowMultiple=true )] public sealed class DependsOnAttribute : Attribute { // // State // public Type Target; // // Constructor Methods // public DependsOnAttribute( Type target ) { this.Target = target; } } } ================================================ FILE: Zelig/Zelig/RunTime/Zelig/Common/Configuration/Attributes/DisplayNameAttribute.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // namespace Microsoft.Zelig.Configuration.Environment { using System; using System.Collections.Generic; [AttributeUsage( AttributeTargets.Class | AttributeTargets.Field )] public sealed class DisplayNameAttribute : Attribute { // // State // public string Value; // // Constructor Methods // public DisplayNameAttribute( string value ) { this.Value = value; } } } ================================================ FILE: Zelig/Zelig/RunTime/Zelig/Common/Configuration/Attributes/EnumDefaultsAttribute.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // namespace Microsoft.Zelig.Configuration.Environment { using System; using System.Collections.Generic; [AttributeUsage( AttributeTargets.Class | AttributeTargets.Field , AllowMultiple=true )] public sealed class EnumDefaultsAttribute : AbstractDefaultsAttribute { // // Constructor Methods // public EnumDefaultsAttribute( string member , Runtime.MemoryAttributes value ) : base( member, value ) { } } } ================================================ FILE: Zelig/Zelig/RunTime/Zelig/Common/Configuration/Attributes/HardwareModelAttribute.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // namespace Microsoft.Zelig.Configuration.Environment { using System; using System.Collections.Generic; [AttributeUsage( AttributeTargets.Class | AttributeTargets.Field , AllowMultiple=true )] public sealed class HardwareModelAttribute : Attribute { public enum Kind { Engine , Memory , Peripheral , PeripheralsGroup, Interop , } // // State // public Type Target; public Kind TargetKind; // // Constructor Methods // public HardwareModelAttribute( Type target , Kind kind ) { this.Target = target; this.TargetKind = kind; } } } ================================================ FILE: Zelig/Zelig/RunTime/Zelig/Common/Configuration/Attributes/LinkToConfigurationOptionAttribute.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // namespace Microsoft.Zelig.Configuration.Environment { using System; using System.Collections.Generic; [AttributeUsage( AttributeTargets.Field, AllowMultiple=false)] public sealed class LinkToConfigurationOptionAttribute : Attribute { // // State // public string Name; // // Constructor Methods // public LinkToConfigurationOptionAttribute( string name ) { this.Name = name; } } } ================================================ FILE: Zelig/Zelig/RunTime/Zelig/Common/Configuration/Attributes/MemorySectionAttribute.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // namespace Microsoft.Zelig.Configuration.Environment { using System; using System.Collections.Generic; [AttributeUsage( AttributeTargets.Field, AllowMultiple=false )] public sealed class MemorySectionAttribute : Attribute { // // State // public Runtime.MemoryUsage Usage; public string Name; public Type ExtensionHandler; // // Constructor Methods // public MemorySectionAttribute( Runtime.MemoryUsage usage ) { this.Usage = usage; } } } ================================================ FILE: Zelig/Zelig/RunTime/Zelig/Common/Configuration/Attributes/MergeEnumDefaultsAttribute.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // namespace Microsoft.Zelig.Configuration.Environment { using System; using System.Collections.Generic; [AttributeUsage( AttributeTargets.Class | AttributeTargets.Field , AllowMultiple=true )] public sealed class MergeEnumDefaultsAttribute : AbstractDefaultsAttribute { // // Constructor Methods // public MergeEnumDefaultsAttribute( string member , Runtime.MemoryAttributes value ) : base( member, value ) { m_merge = true; } } } ================================================ FILE: Zelig/Zelig/RunTime/Zelig/Common/Configuration/Attributes/RequiresAttribute.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // namespace Microsoft.Zelig.Configuration.Environment { using System; using System.Collections.Generic; [AttributeUsage( AttributeTargets.Class | AttributeTargets.Field , AllowMultiple=true )] public sealed class RequiresAttribute : Attribute { // // State // public string Member; public object Value; // // Constructor Methods // public RequiresAttribute( string member , uint value ) { this.Member = member; this.Value = value; } public RequiresAttribute( string member , bool value ) { this.Member = member; this.Value = value; } public RequiresAttribute( string member , string value ) { this.Member = member; this.Value = value; } public RequiresAttribute( string member , Type value ) { this.Member = member; this.Value = value; } } } ================================================ FILE: Zelig/Zelig/RunTime/Zelig/Common/Configuration/Attributes/ReserveBlockAttribute.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // namespace Microsoft.Zelig.Configuration.Environment { using System; using System.Collections.Generic; [AttributeUsage( AttributeTargets.Field, AllowMultiple=true )] public sealed class ReserveBlockAttribute : Attribute { // // State // public uint Offset; public uint Size; public string Reason; // // Constructor Methods // public ReserveBlockAttribute( uint offset , uint size ) { this.Offset = offset; this.Size = size; } } } ================================================ FILE: Zelig/Zelig/RunTime/Zelig/Common/Configuration/Categories/AbstractCategory.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // namespace Microsoft.Zelig.Configuration.Environment { using System; using System.Collections.Generic; public abstract class AbstractCategory { public class ValueChoices { // // State // GrowOnlyHashTable< System.Reflection.FieldInfo, List< object > > m_ht; // // Constructor Methods // public ValueChoices() { m_ht = HashTableFactory.New< System.Reflection.FieldInfo, List< object > >(); } // // Helper Methods // public void Add( System.Reflection.FieldInfo fi , object val ) { HashTableWithListFactory.AddUnique( m_ht, fi, val ); } // // Access Methods // public GrowOnlyHashTable< System.Reflection.FieldInfo, List< object > >.KeyEnumerable Keys { get { return m_ht.Keys; } } public List< object > this[System.Reflection.FieldInfo fi] { get { List< object > lst; m_ht.TryGetValue( fi, out lst ); return lst; } } } public sealed class ValueContext { // // State // public AbstractCategory Holder; public System.Reflection.FieldInfo Field; public int Index; public object Value; // // Equality Methods // public override bool Equals( object obj ) { if(obj is ValueContext) // Since the class is sealed (no subclasses allowed), there's no need to compare using .GetType() { ValueContext other = (ValueContext)obj; if(this.Holder == other.Holder && this.Field == other.Field && this.Index == other.Index && this.Value == other.Value ) { return true; } } return false; } public override int GetHashCode() { return this.Field.GetHashCode(); } // // Helper Methods // public T GetAttribute< T >() where T : Attribute { return ReflectionHelper.GetAttribute< T >( this.Field, false ); } // // Debug Methods // public override string ToString() { if(this.Value == null) { return ""; } else { return this.Value.ToString(); } } } // // State // private ValueChoices m_values; public Type Model; // // Constructor Methods // protected AbstractCategory() { m_values = new ValueChoices(); } // // Helper Methods // public void ApplyDefaultValues() { GrowOnlySet< AbstractCategory > visited = SetFactory.NewWithReferenceEquality< AbstractCategory >(); ApplyDefaultValues( visited ); } private void ApplyDefaultValues( GrowOnlySet< AbstractCategory > visited ) { if(visited.Insert( this ) == false) { foreach(System.Reflection.FieldInfo fi in m_values.Keys) { List< object > lst = m_values[fi]; if(lst.Count == 1) { object val = lst[0]; IConvertible itf = val as IConvertible; if(itf != null) { val = itf.ToType( fi.FieldType, null ); } fi.SetValue( this, val ); } else { Type t = fi.FieldType; if(t.IsClass) { fi.SetValue( this, null ); } else if(t.IsValueType) { fi.SetValue( this, Activator.CreateInstance( t ) ); } } foreach(object o in lst) { AbstractCategory sub = o as AbstractCategory; if(sub != null) { sub.ApplyDefaultValues( visited ); } AbstractCategory[] subArray = o as AbstractCategory[]; if(subArray != null) { foreach(AbstractCategory subElement in subArray) { subElement.ApplyDefaultValues( visited ); } } } } if(this.Model == null) { if(this is EngineCategory) { this.Model = FindHardwareModel( this, HardwareModelAttribute.Kind.Engine ); } else if(this is MemoryCategory) { this.Model = FindHardwareModel( this, HardwareModelAttribute.Kind.Memory ); } } } } //--// public List< ValueContext > SearchPossibleValues( Type type ) { GrowOnlySet< AbstractCategory > visited = SetFactory.NewWithReferenceEquality< AbstractCategory >(); List < ValueContext > lst = new List< ValueContext >(); SearchPossibleValues( visited, lst, type ); return lst; } private void SearchPossibleValues( GrowOnlySet< AbstractCategory > visited , List < ValueContext > lst , Type type ) { if(visited.Insert( this ) == false) { foreach(System.Reflection.FieldInfo fi in m_values.Keys) { object val = fi.GetValue( this ); if(val != null) { ExpandPossibleValues( visited, lst, type, fi, val ); } else { foreach(object o in m_values[fi]) { ExpandPossibleValues( visited, lst, type, fi, o ); } } } } } private void ExpandPossibleValues( GrowOnlySet< AbstractCategory > visited , List < ValueContext > lst , Type type , System.Reflection.FieldInfo fi , object o ) { if(type.IsInstanceOfType( o )) { ValueContext ctx = new ValueContext(); ctx.Holder = this; ctx.Field = fi; ctx.Value = o; lst.Add( ctx ); } AbstractCategory sub = o as AbstractCategory; if(sub != null) { sub.SearchPossibleValues( visited, lst, type ); } } //--// public T SearchValue< T >() { List< ValueContext > lst = SearchValues( typeof(T) ); if(lst.Count == 1) { return (T)lst[0].Value; } return default(T); } public T[] SearchValues< T >() { List< ValueContext > lst = SearchValues( typeof(T) ); T[] res = new T[lst.Count]; for(int i = 0; i < lst.Count; i++) { res[i] = (T)lst[i].Value; } return res; } public List< ValueContext > SearchValues( Type type ) { GrowOnlySet< AbstractCategory > visited = SetFactory.NewWithReferenceEquality< AbstractCategory >(); List < ValueContext > lst = new List< ValueContext >(); SearchValues( visited, lst, type, null ); return lst; } //--// public List< ValueContext > SearchValuesWithAttributes( Type attributeType ) { GrowOnlySet< AbstractCategory > visited = SetFactory.NewWithReferenceEquality< AbstractCategory >(); List < ValueContext > lst = new List< ValueContext >(); SearchValues( visited, lst, null, attributeType ); return lst; } private void SearchValues( GrowOnlySet< AbstractCategory > visited , List < ValueContext > lst , Type type , Type attributeType ) { if(visited.Insert( this ) == false) { foreach(System.Reflection.FieldInfo fi in ReflectionHelper.GetAllInstanceFields( this.GetType() )) { object val = fi.GetValue( this ); if(val != null) { Array valArray = val as Array; if(valArray != null) { for(int i = 0; i < valArray.Length; i++) { SearchValues( visited, lst, type, attributeType, fi, i, valArray.GetValue( i ) ); } } else { SearchValues( visited, lst, type, attributeType, fi, -1, val ); } } } } } private void SearchValues( GrowOnlySet< AbstractCategory > visited , List < ValueContext > lst , Type type , Type attributeType , System.Reflection.FieldInfo fi , int index , object val ) { bool fAdd = false; if(attributeType != null) { foreach(var attrib in fi.GetCustomAttributes( attributeType, false )) { fAdd = true; } } if(type != null) { if(type.IsInstanceOfType( val )) { fAdd = true; } } if(fAdd) { ValueContext ctx = new ValueContext(); ctx.Holder = this; ctx.Field = fi; ctx.Index = index; ctx.Value = val; lst.Add( ctx ); } AbstractCategory sub = val as AbstractCategory; if(sub != null) { sub.SearchValues( visited, lst, type, attributeType ); } } public static Type FindHardwareModel( object obj , HardwareModelAttribute.Kind kind ) { foreach(HardwareModelAttribute attrib in ReflectionHelper.GetAttributes< HardwareModelAttribute >( obj, true )) { if(attrib.TargetKind == kind) { return attrib.Target; } } return null; } public static Type FindHardwareModel( System.Reflection.MemberInfo mi , HardwareModelAttribute.Kind kind ) { foreach(HardwareModelAttribute attrib in ReflectionHelper.GetAttributes< HardwareModelAttribute >( mi, true )) { if(attrib.TargetKind == kind) { return attrib.Target; } } return null; } //--// public T GetService() { return (T)GetServiceInner( typeof(T) ); } protected virtual object GetServiceInner( Type t ) { return null; } // // Access Methods // public ValueChoices PossibleValues { get { return m_values; } } // // Debug Methods // public override string ToString() { DisplayNameAttribute attrib = ReflectionHelper.GetAttribute< DisplayNameAttribute >( this, true ); if(attrib != null) { return attrib.Value; } return base.ToString(); } } } ================================================ FILE: Zelig/Zelig/RunTime/Zelig/Common/Configuration/Categories/BusAttachedCategory.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // namespace Microsoft.Zelig.Configuration.Environment { using System; using System.Collections.Generic; public abstract class BusAttachedCategory : AbstractCategory { // // State // public Type ConnectedToBus; } } ================================================ FILE: Zelig/Zelig/RunTime/Zelig/Common/Configuration/Categories/BusControllerCategory.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // namespace Microsoft.Zelig.Configuration.Environment { using System; using System.Collections.Generic; public abstract class BusControllerCategory : MemoryCategory { protected BusControllerCategory() { this.BaseAddress = 0; this.SizeInBytes = 1L << 32; // A bus controller looks at the whole address range. } } } ================================================ FILE: Zelig/Zelig/RunTime/Zelig/Common/Configuration/Categories/CacheControllerCategory.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // namespace Microsoft.Zelig.Configuration.Environment { using System; using System.Collections.Generic; public abstract class CacheControllerCategory : BusControllerCategory { public abstract uint GetUncacheableAddress( uint address ); } } ================================================ FILE: Zelig/Zelig/RunTime/Zelig/Common/Configuration/Categories/CompilationSetupCategory.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // namespace Microsoft.Zelig.Configuration.Environment { using System; using System.Collections.Generic; public abstract class CompilationSetupCategory : AbstractCategory { // // State // public Type Platform; public Type CallingConvention; public Type Product; public Type MemoryMap; } } ================================================ FILE: Zelig/Zelig/RunTime/Zelig/Common/Configuration/Categories/DisplayCategory.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // namespace Microsoft.Zelig.Configuration.Environment { using System; using System.Collections.Generic; public abstract class DisplayCategory : MemoryCategory { } } ================================================ FILE: Zelig/Zelig/RunTime/Zelig/Common/Configuration/Categories/EngineCategory.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // namespace Microsoft.Zelig.Configuration.Environment { using System; using System.Collections.Generic; using Microsoft.Zelig.TargetModel.ArmProcessor; public abstract class EngineCategory : AbstractCategory { public abstract object Instantiate(InstructionSet iset); } } ================================================ FILE: Zelig/Zelig/RunTime/Zelig/Common/Configuration/Categories/FlashMemoryCategory.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // namespace Microsoft.Zelig.Configuration.Environment { using System; using System.Collections.Generic; public abstract class FlashMemoryCategory : MemoryCategory { } } ================================================ FILE: Zelig/Zelig/RunTime/Zelig/Common/Configuration/Categories/InteropCategory.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // namespace Microsoft.Zelig.Configuration.Environment { using System; using System.Collections.Generic; public class InteropCategory : BusAttachedCategory { } } ================================================ FILE: Zelig/Zelig/RunTime/Zelig/Common/Configuration/Categories/JtagLoaderCategory.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // namespace Microsoft.Zelig.Configuration.Environment { using System; using System.Collections.Generic; public abstract class JtagLoaderCategory : AbstractCategory { // // State // [DisplayName("Driver Name of the Target")] public string DriverName; [DisplayName("Clock Speed to Use When Running")] public int Speed; [DisplayName("Can Set Breakpoints During Reset")] public bool CanSetBreakpointsDuringReset; //--// protected GrowOnlyHashTable< uint, byte[] > m_loaderData; protected uint m_entryPoint; // // Constructor Methods // protected JtagLoaderCategory() { m_loaderData = HashTableFactory.New< uint, byte[] >(); } // // Access Methods // public GrowOnlyHashTable< uint, byte[] > LoaderData { get { return m_loaderData; } } public uint EntryPoint { get { return m_entryPoint; } } } } ================================================ FILE: Zelig/Zelig/RunTime/Zelig/Common/Configuration/Categories/LoaderCompilationSetupCategory.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // namespace Microsoft.Zelig.Configuration.Environment { using System; using System.Collections.Generic; public abstract class LoaderCompilationSetupCategory : CompilationSetupCategory { [LinkToConfigurationOption("ExcludeDebuggerHooks")] public bool ExcludeDebuggerHooks = true; } } ================================================ FILE: Zelig/Zelig/RunTime/Zelig/Common/Configuration/Categories/MemoryCategory.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // namespace Microsoft.Zelig.Configuration.Environment { using System; using System.Collections.Generic; public abstract class MemoryCategory : BusAttachedCategory { // // State // public uint BaseAddress; public ulong SizeInBytes; public uint WordSize; public uint WaitStates; public Runtime.MemoryAttributes Characteristics; // // Helper Methods // public bool InRange( uint address ) { return this.BaseAddress <= address && address < this.EndAddress; } // // Access Methods // public uint EndAddress { get { return (uint)(this.BaseAddress + this.SizeInBytes); } } public bool IsRAM { get { return (this.Characteristics & Runtime.MemoryAttributes.RAM) == Runtime.MemoryAttributes.RAM; } } } } ================================================ FILE: Zelig/Zelig/RunTime/Zelig/Common/Configuration/Categories/MemoryMapCategory.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // namespace Microsoft.Zelig.Configuration.Environment { using System; using System.Collections.Generic; public abstract class MemoryMapCategory : AbstractCategory { } } ================================================ FILE: Zelig/Zelig/RunTime/Zelig/Common/Configuration/Categories/PeripheralCategory.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // namespace Microsoft.Zelig.Configuration.Environment { using System; using System.Collections.Generic; public class PeripheralCategory : BusAttachedCategory { } } ================================================ FILE: Zelig/Zelig/RunTime/Zelig/Common/Configuration/Categories/ProcessorCategory.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // namespace Microsoft.Zelig.Configuration.Environment { using System; using System.Collections.Generic; public abstract class ProcessorCategory : AbstractCategory { [DisplayName("Processor Clock Frequency")] [LinkToConfigurationOption("System__CoreClockFrequency")] public ulong CoreClockFrequency; [DisplayName("Peripherals Clock Frequency")] [LinkToConfigurationOption("System__PeripheralsClockFrequency")] public ulong PeripheralsClockFrequency; [DisplayName("RealTime Clock Frequency")] [LinkToConfigurationOption("System__RealTimeClockFrequency")] public ulong RealTimeClockFrequency; [DisplayName("Number of Threads in Thread Pool")] [LinkToConfigurationOption("System__Runtime_DefaultThreadPoolThreads")] public int DefaultThreadPoolThreads; [DisplayName("Number of Threads in Timer Pool")] [LinkToConfigurationOption("System__Runtime_DefaultTimerPooThreads")] public int DefaultTimerPoolThreads; } } ================================================ FILE: Zelig/Zelig/RunTime/Zelig/Common/Configuration/Categories/ProductCategory.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // namespace Microsoft.Zelig.Configuration.Environment { using System; using System.Collections.Generic; public abstract class ProductCategory : AbstractCategory { // // Helper Methods // public MemoryCategory FindMemory( uint address ) { foreach(var mem in this.SearchValues< MemoryCategory >()) { if(mem.InRange( address )) { return mem; } } return null; } public RamMemoryCategory FindAnyBootstrapRAM() { const Runtime.MemoryAttributes mask = Runtime.MemoryAttributes.ConfiguredAtEntryPoint | Runtime.MemoryAttributes.RandomAccessMemory; foreach(RamMemoryCategory mem in this.SearchValues< RamMemoryCategory >()) { if((mem.Characteristics & mask) == mask) { return mem; } } return null; } } } ================================================ FILE: Zelig/Zelig/RunTime/Zelig/Common/Configuration/Categories/RamMemoryCategory.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // namespace Microsoft.Zelig.Configuration.Environment { using System; using System.Collections.Generic; public abstract class RamMemoryCategory : MemoryCategory { } } ================================================ FILE: Zelig/Zelig/RunTime/Zelig/Common/Configuration/ImageSection.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // namespace Microsoft.Zelig.Configuration.Environment { using System; using System.Collections.Generic; public class ImageSection { // // State // private uint m_address; private byte[] m_payload; private string m_sectionName; private Runtime.MemoryAttributes m_attributes; private Runtime.MemoryUsage m_usage; // // Constructor Methods // public ImageSection( uint address , byte[] payload , string sectionName , Runtime.MemoryAttributes attributes , Runtime.MemoryUsage usage ) { m_address = address; m_payload = payload; m_sectionName = sectionName; m_attributes = attributes; m_usage = usage; } // // Helper Methods // public bool InRange( uint address ) { return (m_address <= address && address < m_address + m_payload.Length); } // // Access Methods // public bool NeedsRelocation { get { if((m_usage & Runtime.MemoryUsage .Relocation ) != 0 || (m_attributes & Runtime.MemoryAttributes.LoadedAtEntrypoint) != 0 ) { return false; } else { return true; } } } public uint Address { get { return m_address; } } public byte[] Payload { get { return m_payload; } } public string SectionName { get { return m_sectionName; } } public Runtime.MemoryAttributes Attributes { get { return m_attributes; } } public Runtime.MemoryUsage Usage { get { return m_usage; } } } } ================================================ FILE: Zelig/Zelig/RunTime/Zelig/Common/Configuration/Interfaces/IMemoryMapper.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // namespace Microsoft.Zelig.Configuration.Environment { using System; using System.Collections.Generic; public interface IMemoryMapper { uint GetCacheableAddress( uint address ); uint GetUncacheableAddress( uint address ); } } ================================================ FILE: Zelig/Zelig/RunTime/Zelig/Common/Debugging/DebugInfo.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // namespace Microsoft.Zelig.Debugging { using System; using System.Text; public sealed class DebugInfo { public static DebugInfo[] SharedEmptyArray = new DebugInfo[0]; // // State // public String SrcFileName; public String MethodName; public int BeginLineNumber; public int BeginColumn; public int EndLineNumber; public int EndColumn; // // Constructor Methods // public DebugInfo( String srcFileName, int beginLineNumber, int beginColumn, int endLineNumber, int endColumn ) : this( srcFileName, null, beginLineNumber, beginColumn, endLineNumber, endColumn ) { } public DebugInfo( String srcFileName , String methodName , int beginLineNumber , int beginColumn , int endLineNumber , int endColumn ) { this.SrcFileName = srcFileName; this.MethodName = methodName; this.BeginLineNumber = beginLineNumber; this.BeginColumn = beginColumn; this.EndLineNumber = endLineNumber; this.EndColumn = endColumn; } private DebugInfo( String srcFileName , String methodName , int lineNumber ) { SetMarkerForLine( srcFileName, methodName, lineNumber ); } // To prevent problems with assembly circular dependencies // this is of type System.Object, but ultimately at this point, should // always be a Microsoft.Zelig.Runtime.TypeSystem.MethodRepresentation // This is used in conversion to LLVM debug information, particularly // when handling inlined code. For IL instructions that had no debug // information or compiler generated IR operators this will be null. public object Scope { get; set; } // // Equality Methods // public override bool Equals( object obj ) { if(obj is DebugInfo) { DebugInfo other = (DebugInfo)obj; if(this.SrcFileName == other.SrcFileName && this.MethodName == other.MethodName && this.BeginLineNumber == other.BeginLineNumber && this.BeginColumn == other.BeginColumn && this.EndLineNumber == other.EndLineNumber && this.EndColumn == other.EndColumn ) { return true; } } return false; } public override int GetHashCode() { Byte[] crcData = System.Text.UTF8Encoding.UTF8.GetBytes(SrcFileName); return (int)CRC32.Compute( crcData, (uint)this.BeginLineNumber ); } // // Helper Methods // public static DebugInfo CreateMarkerForLine( string srcFileName , string methodName , int lineNumber ) { return new DebugInfo( srcFileName, methodName, lineNumber ); } public void SetMarkerForLine( string srcFileName , string methodName , int lineNumber ) { this.SrcFileName = srcFileName; this.MethodName = methodName; this.BeginLineNumber = lineNumber; this.BeginColumn = int.MinValue; this.EndLineNumber = lineNumber; this.EndColumn = int.MaxValue; } public DebugInfo ComputeIntersection( DebugInfo other ) { if(other == null) { return null; } int compareBeginLine = this.BeginLineNumber.CompareTo( other.BeginLineNumber ); int beginLineNumber; int beginColumn; if(compareBeginLine < 0) { beginLineNumber = other.BeginLineNumber; beginColumn = other.BeginColumn; } else { beginLineNumber = this.BeginLineNumber; if(compareBeginLine > 0) { beginColumn = this.BeginColumn; } else { beginColumn = Math.Max( this.BeginColumn, other.BeginColumn ); } } //--// int compareEndLine = this.EndLineNumber.CompareTo( other.EndLineNumber ); int endLineNumber; int endColumn; if(compareEndLine > 0) { endLineNumber = other.EndLineNumber; endColumn = other.EndColumn; } else { endLineNumber = this.EndLineNumber; if(compareEndLine < 0) { endColumn = this.EndColumn; } else { endColumn = Math.Min( this.EndColumn, other.EndColumn ); } } if((beginLineNumber > endLineNumber ) || (beginLineNumber == endLineNumber && beginColumn >= endColumn) ) { return null; } return new DebugInfo( null, MethodName, beginLineNumber, beginColumn, endLineNumber, endColumn ); } public bool IsContainedIn( DebugInfo other ) { if(this.SrcFileName != other.SrcFileName) { return false; } int compareBeginLine = this.BeginLineNumber.CompareTo( other.BeginLineNumber ); if(compareBeginLine < 0) { return false; } if(compareBeginLine == 0 && this.BeginColumn < other.BeginColumn) { return false; } //--// int compareEndLine = this.EndLineNumber.CompareTo( other.EndLineNumber ); if(compareEndLine > 0) { return false; } if(compareEndLine == 0 && this.EndColumn > other.EndColumn) { return false; } return true; } // // Debug Methods // public override String ToString() { StringBuilder s = new StringBuilder(); s.AppendFormat( " ; [{0}:{1}-{2}:{3}] {4}", this.BeginLineNumber, this.BeginColumn, this.EndLineNumber, this.EndColumn, this.SrcFileName ); return s.ToString(); } } } ================================================ FILE: Zelig/Zelig/RunTime/Zelig/Common/Debugging/MethodDebugInfo.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // namespace Microsoft.Zelig.Debugging { using System; using System.Text; public sealed class MethodDebugInfo { // // State // public readonly String[] LocalVarNames; // // Constructor Methods // public MethodDebugInfo( String[] localVarNames ) { this.LocalVarNames = localVarNames; } } } ================================================ FILE: Zelig/Zelig/RunTime/Zelig/Common/Exceptions/AssertionViolationException.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // namespace Microsoft.Zelig { using System; public class AssertionViolationException : Exception { // // Constructor Methods // private AssertionViolationException( string reason ) : base( reason ) { } public static AssertionViolationException Create( string format , params object[] args ) { return new AssertionViolationException( String.Format( format, args ) ); } } } ================================================ FILE: Zelig/Zelig/RunTime/Zelig/Common/Exceptions/IncorrectEncodingException.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // namespace Microsoft.Zelig { using System; public class IncorrectEncodingException : Exception { // // Constructor Methods // private IncorrectEncodingException( string reason ) : base( reason ) { } public static IncorrectEncodingException Create( string format , params object[] args ) { return new IncorrectEncodingException( String.Format( format, args ) ); } } } ================================================ FILE: Zelig/Zelig/RunTime/Zelig/Common/Exceptions/NotSupportedException.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // namespace Microsoft.Zelig { using System; public class FeatureNotSupportedException : Exception { // // Constructor Methods // private FeatureNotSupportedException( string reason ) : base( reason ) { } public static FeatureNotSupportedException Create( string format , params object[] args ) { return new FeatureNotSupportedException( String.Format( format, args ) ); } } } ================================================ FILE: Zelig/Zelig/RunTime/Zelig/Common/Exceptions/TypeConsistencyErrorException.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // namespace Microsoft.Zelig { using System; public class TypeConsistencyErrorException : Exception { // // Constructor Methods // private TypeConsistencyErrorException( string reason ) : base( reason ) { } public static TypeConsistencyErrorException Create( string format , params object[] args ) { return new TypeConsistencyErrorException( String.Format( format, args ) ); } } } ================================================ FILE: Zelig/Zelig/RunTime/Zelig/Common/Helpers/AddressMath.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // namespace Microsoft.Zelig { using System; using RT = Microsoft.Zelig.Runtime; public static class AddressMath { [RT.Inline] public static int Compare( UIntPtr left , UIntPtr right ) { return left.ToUInt32().CompareTo( right.ToUInt32() ); } [RT.Inline] public static bool IsLessThan( UIntPtr left , UIntPtr right ) { return left.ToUInt32() < right.ToUInt32(); } [RT.Inline] public static bool IsLessThanOrEqual( UIntPtr left , UIntPtr right ) { return left.ToUInt32() <= right.ToUInt32(); } [RT.Inline] public static bool IsGreaterThan( UIntPtr left , UIntPtr right ) { return left.ToUInt32() > right.ToUInt32(); } [RT.Inline] public static bool IsGreaterThanOrEqual( UIntPtr left , UIntPtr right ) { return left.ToUInt32() >= right.ToUInt32(); } [RT.Inline] public static bool IsInRange( UIntPtr value , UIntPtr rangeStart , UIntPtr rangeEnd ) { return rangeStart.ToUInt32() <= value.ToUInt32() && value.ToUInt32() < rangeEnd.ToUInt32(); } //--// [RT.Inline] public static UIntPtr Max( UIntPtr left , UIntPtr right ) { return new UIntPtr( Math.Max( left.ToUInt32(), right.ToUInt32() ) ); } [RT.Inline] public static UIntPtr Min( UIntPtr left , UIntPtr right ) { return new UIntPtr( Math.Min( left.ToUInt32(), right.ToUInt32() ) ); } //--// [RT.Inline] public static int Distance( UIntPtr start , UIntPtr end ) { return (int)end.ToUInt32() - (int)start.ToUInt32(); } [RT.Inline] public static uint RangeSize( UIntPtr start , UIntPtr end ) { return end.ToUInt32() - start.ToUInt32(); } //--// [RT.Inline] public unsafe static UIntPtr Increment( UIntPtr ptr , uint offset ) { return new UIntPtr( (byte*)ptr.ToPointer() + offset ); } [RT.Inline] public unsafe static UIntPtr Decrement( UIntPtr ptr , uint offset ) { return new UIntPtr( (byte*)ptr.ToPointer() - offset ); } //--// [RT.Inline] public static uint AlignToWordBoundary( uint value ) { return (value + (sizeof(uint)-1)) & ~(uint)(sizeof(uint)-1); } [RT.Inline] public static uint AlignToDWordBoundary(uint value) { return (value + (sizeof(ulong) - 1)) & ~(uint)(sizeof(ulong) - 1); } [RT.Inline] public static UIntPtr AlignToDWordBoundary(UIntPtr value) { return new UIntPtr(AlignToDWordBoundary(value.ToUInt32())); } public static uint AlignToBoundary( uint value , uint alignment ) { uint off = value % alignment; return off != 0 ? value + alignment - off : value; } public static UIntPtr AlignToBoundary( UIntPtr value , uint alignment ) { uint offset = value.ToUInt32() % alignment; if(offset == 0) { return value; } return AddressMath.Increment( value, alignment - offset ); } //--// [RT.Inline] public static UIntPtr AlignToLowerBoundary( UIntPtr value , uint alignment ) { return new UIntPtr( value.ToUInt32() & ~(alignment - 1) ); } [RT.Inline] public static uint IndexRelativeToLowerBoundary( UIntPtr value , uint alignment ) { return value.ToUInt32() / alignment; } //--//--// [RT.Inline] public unsafe static bool IsAlignedTo64bits( void* ptr ) { return IsAlignedTo64bits( new UIntPtr( ptr ) ); } [RT.Inline] public static bool IsAlignedTo64bits( uint ptr ) { return IsAlignedTo64bits( new UIntPtr( ptr ) ); } [RT.Inline] public static bool IsAlignedTo64bits( UIntPtr ptr ) { return (ptr.ToUInt32() & (sizeof(ulong)-1)) == 0; } //--// [RT.Inline] public unsafe static bool IsAlignedTo32bits( void* ptr ) { return IsAlignedTo32bits( new UIntPtr( ptr ) ); } [RT.Inline] public static bool IsAlignedTo32bits( uint ptr ) { return IsAlignedTo32bits( new UIntPtr( ptr ) ); } [RT.Inline] public static bool IsAlignedTo32bits( UIntPtr ptr ) { return (ptr.ToUInt32() & (sizeof(uint)-1)) == 0; } //--// [RT.Inline] public unsafe static bool IsAlignedTo16bits( void* ptr ) { return IsAlignedTo16bits( new UIntPtr( ptr ) ); } [RT.Inline] public static bool IsAlignedTo16bits( uint ptr ) { return IsAlignedTo16bits( new UIntPtr( ptr ) ); } [RT.Inline] public static bool IsAlignedTo16bits( UIntPtr ptr ) { return (ptr.ToUInt32() & (sizeof(ushort)-1)) == 0; } //--// [RT.Inline] public static bool IsMultipleOf64bits( int value ) { return (value & (sizeof(ulong)-1)) == 0; } [RT.Inline] public static bool IsMultipleOf32bits( int value ) { return (value & (sizeof(uint)-1)) == 0; } [RT.Inline] public static bool IsMultipleOf16bits( int value ) { return (value & (sizeof(ushort)-1)) == 0; } } } ================================================ FILE: Zelig/Zelig/RunTime/Zelig/Common/Helpers/ArrayUtility.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // namespace Microsoft.Zelig { using System; using System.Collections; using System.Collections.Generic; public static class ArrayUtility { public static T[] EnsureSizeOfNotNullArray( T[] array , int size ) { int diff = size - array.Length; if(diff > 0) { return IncreaseSizeOfNotNullArray( array, diff ); } return array; } public static T[] IncreaseSizeOfNotNullArray( T[] array , int extra ) { int len = array.Length; T[] res = new T[len+extra]; Array.Copy( array, res, len ); return res; } //--// public static int FindInNotNullArray( T[] array , T element ) { int len = array.Length; for(int i = 0; i < len; i++) { if(array[i].Equals( element ) == true) { return i; } } return -1; } public static int FindReferenceInNotNullArray( T[] array , T element ) where T : class { int len = array.Length; for(int i = 0; i < len; i++) { if(Object.ReferenceEquals( array[i], element ) == true) { return i; } } return -1; } //--// public static T[] CopyNotNullArray( T[] array ) { int len = array.Length; T[] res = new T[len]; Array.Copy( array, res, len ); return res; } //--// public static T[] ExtractSliceFromNotNullArray( T[] array , int offset , int count ) { T[] res = new T[count]; Array.Copy( array, offset, res, 0, count ); return res; } //--// public static T[] TrimNullArray( T[] array , int maxLength ) { if(array.Length > maxLength) { return ExtractSliceFromNotNullArray( array, 0, maxLength ); } else { return array; } } //--// public static T[] AppendToArray( T[] array , T element ) { if(array == null) { return new T[] { element }; } else { return AppendToNotNullArray( array, element ); } } public static T[] AppendToNotNullArray( T[] array , T element ) { int len = array.Length; T[] res = new T[len+1]; if(len > 0) { Array.Copy( array, res, len ); } res[len] = element; return res; } public static T[] AppendArrayToArray( T[] array , T[] array2 ) { if(array == null) { return array2; } if(array2 == null) { return array; } return AppendNotNullArrayToNotNullArray( array, array2 ); } public static T[] AppendNotNullArrayToNotNullArray( T[] array , T[] array2 ) { int len2 = array2.Length; if(len2 == 0) { return array; } int len = array.Length; if(len == 0) { return array2; } T[] res = new T[len+len2]; Array.Copy( array , 0, res, 0, len ); Array.Copy( array2, 0, res, len, len2 ); return res; } //--// public static T[] InsertAtHeadOfArray( T[] array , T element ) { if(array == null) { return new T[] { element }; } else { return InsertAtHeadOfNotNullArray( array, element ); } } public static T[] InsertAtHeadOfNotNullArray( T[] array , T element ) { int len = array.Length; T[] res = new T[len+1]; if(len > 0) { Array.Copy( array, 0, res, 1, len ); } res[0] = element; return res; } //--// public static T[] InsertAtPositionOfArray( T[] array , int position , T element ) { if(array == null) { return new T[] { element }; } else { return InsertAtPositionOfNotNullArray( array, position, element ); } } public static T[] InsertAtPositionOfNotNullArray( T[] array , int position , T element ) { int len = array.Length; if(len == position) { return AppendToNotNullArray( array, element ); } T[] res = new T[len+1]; Array.Copy( array, 0 , res, 0 , position ); Array.Copy( array, position, res, position+1, len - position ); res[position] = element; return res; } public static T[] InsertNotNullArrayAtPositionOfNotNullArray( T[] array , int position , T[] array2 ) { int len2 = array2.Length; if(len2 == 0) { return array; } int len = array.Length; T[] res = new T[len+len2]; Array.Copy( array , 0 , res, 0 , position ); Array.Copy( array2, 0 , res, position , len2 ); Array.Copy( array , position, res, position + len2, len - position ); return res; } //--// public static T[] AddUniqueToArray( T[] array , T element ) { if(array == null) { return new T[] { element }; } else { return AddUniqueToNotNullArray( array, element ); } } public static T[] AddUniqueToNotNullArray( T[] array , T element ) { if(FindInNotNullArray( array, element ) < 0) { return AppendToNotNullArray( array, element ); } else { return array; } } //--// public static T[] ReplaceAtPositionOfArray( T[] array , int position , T element ) { if(array != null) { array = ReplaceAtPositionOfNotNullArray( array, position, element ); } return array; } public static T[] ReplaceAtPositionOfNotNullArray( T[] array , int position , T element ) { array = CopyNotNullArray( array ); array[position] = element; return array; } //--// public static T[] RemoveAtPositionFromNotNullArray( T[] array , int pos ) { return RemoveAtPositionFromNotNullArray( array, pos, 1 ); } public static T[] RemoveAtPositionFromNotNullArray( T[] array , int pos , int count ) { int len = array.Length; T[] res = new T[len-count]; Array.Copy( array, 0 , res, 0 , pos ); Array.Copy( array, pos + count, res, pos, len - count - pos ); return res; } public static T[] RemoveUniqueFromNotNullArray( T[] array , T element ) { int pos = FindInNotNullArray( array, element ); if(pos >= 0) { return RemoveAtPositionFromNotNullArray( array, pos ); } else { return array; } } //--// public static bool ArraySameLength( T[] s , T[] d ) { int sLen = s != null ? s.Length : 0; int dLen = d != null ? d.Length : 0; return(sLen == dLen); } public static bool ArrayReferenceEqualsNotNull( T[] s , T[] d , int offset ) { int sLen = s.Length; int dLen = d.Length; if(sLen == dLen) { for(int i = offset; i < sLen; i++) { if(Object.ReferenceEquals( s[i], d[i] ) == false) { return false; } } return true; } return false; } public static bool ArrayEqualsNotNull( T[] s , T[] d , int offset ) { int sLen = s.Length; int dLen = d.Length; if(sLen == dLen) { for(int i = offset; i < sLen; i++) { if(Object.Equals( s[i], d[i] ) == false) { return false; } } return true; } return false; } public static bool SameContents( T[] s , T[] d ) { if(s != null) { if(d == null) { return false; } foreach(T v in s) { if(FindInNotNullArray( d, v ) < 0) { return false; } } foreach(T v in d) { if(FindInNotNullArray( s, v ) < 0) { return false; } } } else { if(d != null) { return false; } } return true; } public static bool ArrayEquals( T[] s , T[] d ) { int sLen = s != null ? s.Length : 0; int dLen = d != null ? d.Length : 0; if(sLen == dLen) { for(int i = 0; i < sLen; i++) { if(Object.Equals( s[i], d[i] ) == false) { return false; } } return true; } return false; } public static bool ByteArrayEquals( byte[] s , byte[] d ) { int sLen = s != null ? s.Length : 0; int dLen = d != null ? d.Length : 0; if(sLen == dLen) { for(int i = 0; i < sLen; i++) { if(s[i] != d[i]) { return false; } } return true; } return false; } public static bool ByteArrayEquals( byte[] s , int sOffset , byte[] d , int dOffset , int count ) { int sLen = s != null ? s.Length : 0; int dLen = d != null ? d.Length : 0; while(--count >= 0) { if(sOffset >= sLen || dOffset >= dLen ) { return false; } if(s[sOffset++] != d[dOffset++]) { return false; } } return true; } public static bool UIntArrayEquals( uint[] s , uint[] d ) { int sLen = s != null ? s.Length : 0; int dLen = d != null ? d.Length : 0; if(sLen == dLen) { for(int i = 0; i < sLen; i++) { if(s[i] != d[i]) { return false; } } return true; } return false; } } } ================================================ FILE: Zelig/Zelig/RunTime/Zelig/Common/Helpers/CRC32.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // namespace Microsoft.Zelig { using System; public static class CRC32 { static uint[] c_CRCTable = new uint[256] { 0x00000000, 0x04C11DB7, 0x09823B6E, 0x0D4326D9, 0x130476DC, 0x17C56B6B, 0x1A864DB2, 0x1E475005, 0x2608EDB8, 0x22C9F00F, 0x2F8AD6D6, 0x2B4BCB61, 0x350C9B64, 0x31CD86D3, 0x3C8EA00A, 0x384FBDBD, 0x4C11DB70, 0x48D0C6C7, 0x4593E01E, 0x4152FDA9, 0x5F15ADAC, 0x5BD4B01B, 0x569796C2, 0x52568B75, 0x6A1936C8, 0x6ED82B7F, 0x639B0DA6, 0x675A1011, 0x791D4014, 0x7DDC5DA3, 0x709F7B7A, 0x745E66CD, 0x9823B6E0, 0x9CE2AB57, 0x91A18D8E, 0x95609039, 0x8B27C03C, 0x8FE6DD8B, 0x82A5FB52, 0x8664E6E5, 0xBE2B5B58, 0xBAEA46EF, 0xB7A96036, 0xB3687D81, 0xAD2F2D84, 0xA9EE3033, 0xA4AD16EA, 0xA06C0B5D, 0xD4326D90, 0xD0F37027, 0xDDB056FE, 0xD9714B49, 0xC7361B4C, 0xC3F706FB, 0xCEB42022, 0xCA753D95, 0xF23A8028, 0xF6FB9D9F, 0xFBB8BB46, 0xFF79A6F1, 0xE13EF6F4, 0xE5FFEB43, 0xE8BCCD9A, 0xEC7DD02D, 0x34867077, 0x30476DC0, 0x3D044B19, 0x39C556AE, 0x278206AB, 0x23431B1C, 0x2E003DC5, 0x2AC12072, 0x128E9DCF, 0x164F8078, 0x1B0CA6A1, 0x1FCDBB16, 0x018AEB13, 0x054BF6A4, 0x0808D07D, 0x0CC9CDCA, 0x7897AB07, 0x7C56B6B0, 0x71159069, 0x75D48DDE, 0x6B93DDDB, 0x6F52C06C, 0x6211E6B5, 0x66D0FB02, 0x5E9F46BF, 0x5A5E5B08, 0x571D7DD1, 0x53DC6066, 0x4D9B3063, 0x495A2DD4, 0x44190B0D, 0x40D816BA, 0xACA5C697, 0xA864DB20, 0xA527FDF9, 0xA1E6E04E, 0xBFA1B04B, 0xBB60ADFC, 0xB6238B25, 0xB2E29692, 0x8AAD2B2F, 0x8E6C3698, 0x832F1041, 0x87EE0DF6, 0x99A95DF3, 0x9D684044, 0x902B669D, 0x94EA7B2A, 0xE0B41DE7, 0xE4750050, 0xE9362689, 0xEDF73B3E, 0xF3B06B3B, 0xF771768C, 0xFA325055, 0xFEF34DE2, 0xC6BCF05F, 0xC27DEDE8, 0xCF3ECB31, 0xCBFFD686, 0xD5B88683, 0xD1799B34, 0xDC3ABDED, 0xD8FBA05A, 0x690CE0EE, 0x6DCDFD59, 0x608EDB80, 0x644FC637, 0x7A089632, 0x7EC98B85, 0x738AAD5C, 0x774BB0EB, 0x4F040D56, 0x4BC510E1, 0x46863638, 0x42472B8F, 0x5C007B8A, 0x58C1663D, 0x558240E4, 0x51435D53, 0x251D3B9E, 0x21DC2629, 0x2C9F00F0, 0x285E1D47, 0x36194D42, 0x32D850F5, 0x3F9B762C, 0x3B5A6B9B, 0x0315D626, 0x07D4CB91, 0x0A97ED48, 0x0E56F0FF, 0x1011A0FA, 0x14D0BD4D, 0x19939B94, 0x1D528623, 0xF12F560E, 0xF5EE4BB9, 0xF8AD6D60, 0xFC6C70D7, 0xE22B20D2, 0xE6EA3D65, 0xEBA91BBC, 0xEF68060B, 0xD727BBB6, 0xD3E6A601, 0xDEA580D8, 0xDA649D6F, 0xC423CD6A, 0xC0E2D0DD, 0xCDA1F604, 0xC960EBB3, 0xBD3E8D7E, 0xB9FF90C9, 0xB4BCB610, 0xB07DABA7, 0xAE3AFBA2, 0xAAFBE615, 0xA7B8C0CC, 0xA379DD7B, 0x9B3660C6, 0x9FF77D71, 0x92B45BA8, 0x9675461F, 0x8832161A, 0x8CF30BAD, 0x81B02D74, 0x857130C3, 0x5D8A9099, 0x594B8D2E, 0x5408ABF7, 0x50C9B640, 0x4E8EE645, 0x4A4FFBF2, 0x470CDD2B, 0x43CDC09C, 0x7B827D21, 0x7F436096, 0x7200464F, 0x76C15BF8, 0x68860BFD, 0x6C47164A, 0x61043093, 0x65C52D24, 0x119B4BE9, 0x155A565E, 0x18197087, 0x1CD86D30, 0x029F3D35, 0x065E2082, 0x0B1D065B, 0x0FDC1BEC, 0x3793A651, 0x3352BBE6, 0x3E119D3F, 0x3AD08088, 0x2497D08D, 0x2056CD3A, 0x2D15EBE3, 0x29D4F654, 0xC5A92679, 0xC1683BCE, 0xCC2B1D17, 0xC8EA00A0, 0xD6AD50A5, 0xD26C4D12, 0xDF2F6BCB, 0xDBEE767C, 0xE3A1CBC1, 0xE760D676, 0xEA23F0AF, 0xEEE2ED18, 0xF0A5BD1D, 0xF464A0AA, 0xF9278673, 0xFDE69BC4, 0x89B8FD09, 0x8D79E0BE, 0x803AC667, 0x84FBDBD0, 0x9ABC8BD5, 0x9E7D9662, 0x933EB0BB, 0x97FFAD0C, 0xAFB010B1, 0xAB710D06, 0xA6322BDF, 0xA2F33668, 0xBCB4666D, 0xB8757BDA, 0xB5365D03, 0xB1F740B4 }; //////////////////////////////////////////////////////////////////////////////////////////// public static uint Compute( byte[] buf , int offset , int length , uint crc ) { while(length-- > 0) { crc = c_CRCTable[((crc >> 24) ^ (buf[offset++])) & 0xFF] ^ (crc << 8); } return crc; } public static uint Compute( byte val , uint crc ) { return c_CRCTable[((crc >> 24) ^ (val)) & 0xff] ^ (crc << 8); } public static uint Compute( byte[] buf , uint crc ) { return Compute( buf, 0, buf.Length, crc ); } } } ================================================ FILE: Zelig/Zelig/RunTime/Zelig/Common/Helpers/Checks.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // namespace Microsoft.Zelig { using System; public static class CHECKS { public static bool ENABLED { get { #if DEBUG || CHECKS_ASSERT return true; #else return false; #endif } } [System.Diagnostics.Conditional( "DEBUG" )] [System.Diagnostics.Conditional( "CHECKS_ASSERT" )] public static void ASSERT( bool res , string text ) { if(res == false) { throw AssertionViolationException.Create( text ); } } [System.Diagnostics.Conditional( "DEBUG" )] [System.Diagnostics.Conditional( "CHECKS_ASSERT" )] public static void ASSERT( bool res , string text , object arg1 ) { if(res == false) { throw AssertionViolationException.Create( text, arg1 ); } } [System.Diagnostics.Conditional( "DEBUG" )] [System.Diagnostics.Conditional( "CHECKS_ASSERT" )] public static void ASSERT( bool res , string text , object arg1 , object arg2 ) { if(res == false) { throw AssertionViolationException.Create( text, arg1, arg2 ); } } [System.Diagnostics.Conditional( "DEBUG" )] [System.Diagnostics.Conditional( "CHECKS_ASSERT" )] public static void ASSERT( bool res , string text , object arg1 , object arg2 , object arg3 ) { if(res == false) { throw AssertionViolationException.Create( text, arg1, arg2, arg3 ); } } [System.Diagnostics.Conditional( "DEBUG" )] [System.Diagnostics.Conditional( "CHECKS_ASSERT" )] public static void ASSERT( bool res , string text , params object[] args ) { if(res == false) { throw AssertionViolationException.Create( text, args ); } } } } ================================================ FILE: Zelig/Zelig/RunTime/Zelig/Common/Helpers/DataConversion.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // namespace Microsoft.Zelig { using System; using System.Collections; using System.Collections.Generic; public static class DataConversion { public static TypeCode GetTypeCode( object val ) { var res = GetTypeCodeNoPointers( val ); if(res != TypeCode.Empty) { return res; } if(val is IntPtr ) return TypeCode.Int32; if(val is UIntPtr) return TypeCode.UInt32; return TypeCode.Empty; } public static TypeCode GetTypeCodeNoPointers( object val ) { var valItf = val as IConvertible; if(valItf != null) { return valItf.GetTypeCode(); } return TypeCode.Empty; } public static unsafe float GetFloatFromBytes( uint val ) { return *((float*)&val); } public static unsafe double GetDoubleFromBytes( ulong val ) { return *((double*)&val); } public static unsafe uint GetFloatAsBytes( float val ) { return *((uint*)&val); } public static unsafe ulong GetDoubleAsBytes( double val ) { return *((ulong*)&val); } public static unsafe uint GetFragmentOfNumber( object number , int offset ) { uint* ptr; uint size; switch(GetTypeCodeNoPointers( number )) { case TypeCode.UInt32: { uint val = (uint)number; ptr = (uint*)&val; size = sizeof(uint); } break; case TypeCode.Int32: { int val = (int)number; ptr = (uint*)&val; size = sizeof(int); } break; case TypeCode.UInt64: { ulong val = (ulong)number; ptr = (uint*)&val; size = sizeof(ulong); } break; case TypeCode.Int64: { long val = (long)number; ptr = (uint*)&val; size = sizeof(long); } break; case TypeCode.Single: { float val = (float)number; ptr = (uint*)&val; size = sizeof(float); } break; case TypeCode.Double: { double val = (double)number; ptr = (uint*)&val; size = sizeof(double); } break; default: return 0; } if(offset * sizeof(uint) < size) { return ptr[offset]; } return 0; } public static bool GetAsRawUlong( object valIn , out ulong valOut ) { if(valIn is float) { valOut = (ulong)GetFloatAsBytes( (float)valIn ) ; return true; } if(valIn is double) { valOut = (ulong)GetDoubleAsBytes( (double )valIn ) ; return true; } return GetAsUnsignedInteger( valIn, out valOut ); } public static bool GetAsUnsignedInteger( object valIn , out ulong valOut ) { switch(GetTypeCodeNoPointers( valIn )) { case TypeCode.Boolean: valOut = (ulong) ((bool )valIn ? 1u : 0u); break; case TypeCode.Char : valOut = (ulong) (char )valIn ; break; case TypeCode.Byte : valOut = (ulong) (byte )valIn ; break; case TypeCode.UInt16 : valOut = (ulong) (ushort )valIn ; break; case TypeCode.UInt32 : valOut = (ulong) (uint )valIn ; break; case TypeCode.UInt64 : valOut = (ulong) (ulong )valIn ; break; case TypeCode.SByte : valOut = (ulong)(long) (sbyte )valIn ; break; case TypeCode.Int16 : valOut = (ulong)(long) (short )valIn ; break; case TypeCode.Int32 : valOut = (ulong)(long) (int )valIn ; break; case TypeCode.Int64 : valOut = (ulong) (long )valIn ; break; default: if(valIn is IntPtr ) { valOut = (ulong)(long)((IntPtr )valIn).ToInt32 (); break; } if(valIn is UIntPtr) { valOut = (ulong) ((UIntPtr)valIn).ToUInt32(); break; } valOut = 0; return false; } return true; } public static bool GetAsSignedInteger( object valIn , out long valOut ) { ulong valOutUnsigned; if(GetAsUnsignedInteger( valIn, out valOutUnsigned )) { valOut = (long)valOutUnsigned; return true; } else { valOut = 0; return false; } } public static bool GetFloatingPoint( object valIn , out double valOut ) { if(valIn is float) { valOut = (double)(float)valIn; return true; } if(valIn is double) { valOut = (double )valIn; return true; } valOut = 0; return false; } } } ================================================ FILE: Zelig/Zelig/RunTime/Zelig/Common/Helpers/HashTableFactory.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // namespace Microsoft.Zelig { using System; using System.Collections; using System.Collections.Generic; public static class HashTableFactory { public static GrowOnlyHashTable< TKey, TValue > New< TKey, TValue >() { return new GrowOnlyHashTable< TKey, TValue >( EqualityComparer< TKey >.Default ); } public static GrowOnlyHashTable< TKey, TValue > NewWithReferenceEquality< TKey, TValue >() where TKey : class { return new GrowOnlyHashTable< TKey, TValue >( new ReferenceEqualityComparer< TKey >() ); } public static GrowOnlyHashTable< TKey, TValue > NewWithWeakEquality< TKey, TValue >() { return new GrowOnlyHashTable< TKey, TValue >( new WeakEqualityComparer< TKey >() ); } public static GrowOnlyHashTable< TKey, TValue > NewWithComparer< TKey, TValue >( IEqualityComparer< TKey > comparer ) { return new GrowOnlyHashTable< TKey, TValue >( comparer ); } } } ================================================ FILE: Zelig/Zelig/RunTime/Zelig/Common/Helpers/HashTableWithListFactory.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // namespace Microsoft.Zelig { using System; using System.Collections; using System.Collections.Generic; public static class HashTableWithListFactory { public static bool Create< TKey, TValue >( GrowOnlyHashTable< TKey, List< TValue > > ht , TKey key , out List< TValue > lst ) { if(ht.TryGetValue( key, out lst ) == false) { lst = new List< TValue >(); ht[key] = lst; return false; } return true; } public static List< TValue > Create< TKey, TValue >( GrowOnlyHashTable< TKey, List< TValue > > ht , TKey key ) { List< TValue > lst; Create( ht, key, out lst ); return lst; } public static List< TValue > Add< TKey, TValue >( GrowOnlyHashTable< TKey, List< TValue > > ht , TKey key , TValue value ) { List< TValue > lst = Create( ht, key ); lst.Add( value ); return lst; } public static List< TValue > AddUnique< TKey, TValue >( GrowOnlyHashTable< TKey, List< TValue > > ht , TKey key , TValue value ) { List< TValue > lst = Create( ht, key ); if(lst.Contains( value ) == false) { lst.Add( value ); } return lst; } } } ================================================ FILE: Zelig/Zelig/RunTime/Zelig/Common/Helpers/HashTableWithSetFactory.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // namespace Microsoft.Zelig { using System; using System.Collections; using System.Collections.Generic; public static class HashTableWithSetFactory { public static bool Create< TKey, TValue >( GrowOnlyHashTable< TKey, GrowOnlySet< TValue > > ht , TKey key , out GrowOnlySet< TValue > set ) { if(ht.TryGetValue( key, out set ) == false) { set = SetFactory.New< TValue >(); ht[key] = set; return false; } return true; } public static GrowOnlySet< TValue > Create< TKey, TValue >( GrowOnlyHashTable< TKey, GrowOnlySet< TValue > > ht , TKey key ) { GrowOnlySet< TValue > set; Create( ht, key, out set ); return set; } public static GrowOnlySet< TValue > Add< TKey, TValue >( GrowOnlyHashTable< TKey, GrowOnlySet< TValue > > ht , TKey key , TValue value ) { GrowOnlySet< TValue > set = Create( ht, key ); set.Insert( value ); return set; } //--// public static bool CreateWithReferenceEquality< TKey, TValue >( GrowOnlyHashTable< TKey, GrowOnlySet< TValue > > ht , TKey key , out GrowOnlySet< TValue > set ) where TValue : class { if(ht.TryGetValue( key, out set ) == false) { set = SetFactory.NewWithReferenceEquality< TValue >(); ht[key] = set; return false; } return true; } public static GrowOnlySet< TValue > CreateWithReferenceEquality< TKey, TValue >( GrowOnlyHashTable< TKey, GrowOnlySet< TValue > > ht , TKey key ) where TValue : class { GrowOnlySet< TValue > set; CreateWithReferenceEquality( ht, key, out set ); return set; } public static GrowOnlySet< TValue > AddWithReferenceEquality< TKey, TValue >( GrowOnlyHashTable< TKey, GrowOnlySet< TValue > > ht , TKey key , TValue value ) where TValue : class { GrowOnlySet< TValue > set = CreateWithReferenceEquality( ht, key ); set.Insert( value ); return set; } } } ================================================ FILE: Zelig/Zelig/RunTime/Zelig/Common/Helpers/ReflectionHelper.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // namespace Microsoft.Zelig { using System; using System.Collections; using System.Collections.Generic; public static class ReflectionHelper { public static System.Reflection.FieldInfo[] GetAllFields( Type t ) { return t.GetFields( System.Reflection.BindingFlags.Public | System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.Static ); } public static System.Reflection.FieldInfo[] GetAllInstanceFields( Type t ) { return t.GetFields( System.Reflection.BindingFlags.Public | System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.Instance ); } public static System.Reflection.FieldInfo[] GetAllPublicInstanceFields( Type t ) { return t.GetFields( System.Reflection.BindingFlags.Public | System.Reflection.BindingFlags.Instance ); } //--// public static System.Reflection.PropertyInfo[] GetAllProperties( Type t ) { return t.GetProperties( System.Reflection.BindingFlags.Public | System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.Static ); } public static System.Reflection.PropertyInfo[] GetAllInstanceProperties( Type t ) { return t.GetProperties( System.Reflection.BindingFlags.Public | System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.Instance ); } public static System.Reflection.PropertyInfo[] GetAllPublicInstanceProperties( Type t ) { return t.GetProperties( System.Reflection.BindingFlags.Public | System.Reflection.BindingFlags.Instance ); } //--// public static System.Reflection.MethodInfo[] GetAllMethods( Type t ) { return t.GetMethods( System.Reflection.BindingFlags.Public | System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.Static ); } public static System.Reflection.MethodInfo[] GetAllInstanceMethods( Type t ) { return t.GetMethods( System.Reflection.BindingFlags.Public | System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.Instance ); } public static System.Reflection.MethodInfo[] GetAllPublicInstanceMethods( Type t ) { return t.GetMethods( System.Reflection.BindingFlags.Public | System.Reflection.BindingFlags.Instance ); } //--// public static bool HasAttribute< T >( object obj , bool fInherit ) { return HasAttribute< T >( obj.GetType(), fInherit ); } public static bool HasAttribute< T >( System.Reflection.MemberInfo mi , bool fInherit ) { return mi.GetCustomAttributes( typeof( T ), fInherit ).Length > 0; } //--// public static T GetAttribute< T >( object obj , bool fInherit ) { return GetAttribute< T >( obj.GetType(), fInherit ); } public static T GetAttribute< T >( System.Reflection.MemberInfo mi , bool fInherit ) { T[] res = GetAttributes< T >( mi, fInherit ); if(res.Length == 1) { return res[0]; } return default(T); } //--// public static T[] GetAttributes< T >( object obj , bool fInherit ) { return GetAttributes< T >( obj.GetType(), fInherit ); } public static T[] GetAttributes< T >( System.Reflection.MemberInfo mi , bool fInherit ) { object[] objArray = mi.GetCustomAttributes( typeof( T ), fInherit ); T[] typedArray = new T[objArray.Length]; Array.Copy( objArray, typedArray, objArray.Length ); return typedArray; } } } ================================================ FILE: Zelig/Zelig/RunTime/Zelig/Common/Helpers/SetFactory.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // namespace Microsoft.Zelig { using System; using System.Collections; using System.Collections.Generic; public static class SetFactory { public static GrowOnlySet< TKey > New< TKey >() { return new GrowOnlySet< TKey >( EqualityComparer< TKey >.Default ); } public static GrowOnlySet< TKey > NewWithReferenceEquality< TKey >() where TKey : class { return new GrowOnlySet< TKey >( new ReferenceEqualityComparer< TKey >() ); } public static GrowOnlySet< TKey > NewWithWeakEquality< TKey >() { return new GrowOnlySet< TKey >( new WeakEqualityComparer< TKey >() ); } public static GrowOnlySet< TKey > NewWithComparer< TKey >( IEqualityComparer< TKey > comparer ) { return new GrowOnlySet< TKey >( comparer ); } } } ================================================ FILE: Zelig/Zelig/RunTime/Zelig/Common/PerformanceCounters/ContextualTiming.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // //#define COLLECT_PERFORMANCE_DATA namespace Microsoft.Zelig.PerformanceCounters { using System; using System.Collections.Generic; #if COLLECT_PERFORMANCE_DATA public struct ContextualTiming : IDisposable { class State { // // State // internal object m_context; internal string m_reason; internal Timing m_counter; internal int m_recursionCount; internal GrowOnlyHashTable< State, Timing.Nested > m_children; // // Constructor Methods // internal State( object context , string reason ) { m_context = context; m_reason = reason; } // // Equality Methods // public override bool Equals( object obj ) { if(obj is State) { State other = (State)obj; if(m_reason == other.m_reason) { return Object.ReferenceEquals( m_context, other.m_context ); } } return false; } public override int GetHashCode() { return m_context.GetHashCode(); } // // Helper Methods // internal void Include( State other , long exclusiveTime ) { if(m_children == null) { m_children = HashTableFactory.New< State, Timing.Nested >(); } Timing.Nested child; if(m_children.TryGetValue( other, out child ) == false) { child = new Timing.Nested(); m_children[other] = child; } child.Sum( exclusiveTime ); } } // // State // /************/ static List < GrowOnlySet< State > > s_threads; [ThreadStatic] static GrowOnlySet< State > s_states; [ThreadStatic] static List < State > s_activeStates; State m_state; int m_gcCount; // // Constructor Methods // public ContextualTiming( object context , string reason ) { if(context == null) { m_state = null; m_gcCount = 0; return; } Timing.Suspend(); if(s_states == null) { s_states = SetFactory.New< State >(); s_activeStates = new List< State >(); lock(typeof(State)) { if(s_threads == null) { s_threads = new List< GrowOnlySet< State > >(); } s_threads.Add( s_states ); } } State state = new State( context, reason ); if(s_states.Contains( state, out m_state ) == false) { m_state = state; s_states.Insert( state ); } if(m_state.m_recursionCount++ == 0) { s_activeStates.Add( m_state ); Timing.Resume(); m_state.m_counter.Start(); m_gcCount = GC.CollectionCount( 0 ); } else { Timing.Resume(); m_gcCount = 0; } } // // Helper Methods // public void Dispose() { if(m_state != null) { if(m_state.m_recursionCount-- == 1) { long exclusiveTime = m_state.m_counter.Stop( false ); int gcCount = GC.CollectionCount( 0 ); Timing.Suspend(); int top = s_activeStates.Count - 1; CHECKS.ASSERT( s_activeStates[top].Equals( m_state ), "Incorrect nesting of contextual timing" ); s_activeStates.RemoveAt( top ); while(--top >= 0) { State other = s_activeStates[top]; other.Include( m_state, exclusiveTime ); if(m_gcCount == gcCount) { other.m_counter.SetGcCount( gcCount ); } } Timing.Resume(); } } } // // Access Methods // public long TotalInclusiveTicks { get { return m_state.m_counter.TotalInclusiveTicks; } } public long TotalInclusiveMicroSeconds { get { return m_state.m_counter.TotalInclusiveMicroSeconds; } } public long TotalExclusiveTicks { get { return m_state.m_counter.TotalExclusiveTicks; } } public long TotalExclusiveMicroSeconds { get { return m_state.m_counter.TotalExclusiveMicroSeconds; } } public int Hits { get { return m_state.m_counter.Hits; } } // // Debug Methods // public static bool IsEnabled() { return true; } public static void DumpAllByType( System.IO.TextWriter textWriter ) { GrowOnlyHashTable< string, List< State > > lookup = HashTableFactory.New< string, List< State > >(); GrowOnlyHashTable< string, long > lookupCost = HashTableFactory.New< string, long >(); foreach(GrowOnlySet< State > set in s_threads) { foreach(State st in set) { string key = st.m_context.ToString();; if(HashTableWithListFactory.Add( lookup, key, st ).Count == 1) { lookupCost[key] = 0; } lookupCost[key] += st.m_counter.TotalInclusiveMicroSeconds; } } string[] keyArray = lookup.KeysToArray(); Array.Sort( keyArray, delegate ( string left, string right ) { return lookupCost[right].CompareTo( lookupCost[left] ); } ); foreach(string key in keyArray) { State[] states = SortByMostExpensive( lookup[key].ToArray() ); //--// long totalInclusiveMicroSeconds = 0; long totalExclusiveMicroSeconds = 0; int totalHits = 0; foreach(State st in states) { totalInclusiveMicroSeconds += st.m_counter.TotalInclusiveMicroSeconds; totalExclusiveMicroSeconds += st.m_counter.TotalExclusiveMicroSeconds; totalHits += st.m_counter.Hits; } textWriter.Write( "Key = {0}: ", key ); Emit( textWriter, "Exclusive", false, totalExclusiveMicroSeconds, totalHits ); Emit( textWriter, "Inclusive", false, totalInclusiveMicroSeconds, totalHits ); textWriter.WriteLine(); foreach(State st in states) { long inclusiveMicroSeconds = st.m_counter.TotalInclusiveMicroSeconds; long exclusiveMicroSeconds = st.m_counter.TotalExclusiveMicroSeconds; int hits = st.m_counter.Hits; textWriter.Write( " " ); Emit( textWriter, "Exclusive", true, exclusiveMicroSeconds, hits ); Emit( textWriter, "Inclusive", true, inclusiveMicroSeconds, hits ); textWriter.WriteLine( " | {0}", st.m_reason ); if(st.m_children != null) { GrowOnlyHashTable< Timing.Nested, State > childrenInverted = GetInvertedHashTable( st.m_children ); foreach(Timing.Nested childCounter in SortByMostExpensive( childrenInverted.KeysToArray() )) { State child = childrenInverted[childCounter]; textWriter.Write( " " ); Emit( textWriter, "Child Exc", true, childCounter.TotalExclusiveMicroSeconds, childCounter.Hits ); if(child.m_context != st.m_context) { textWriter.WriteLine( " | {0,-30} / {1}", child.m_reason, child.m_context ); } else { textWriter.WriteLine( " | {0}", child.m_reason ); } } } textWriter.WriteLine(); } textWriter.WriteLine(); } } public static void DumpAllByReason( System.IO.TextWriter textWriter ) { GrowOnlyHashTable< string, List< State > > lookup = HashTableFactory.New< string, List< State > >(); GrowOnlyHashTable< string, long > lookupCost = HashTableFactory.New< string, long >(); foreach(GrowOnlySet< State > set in s_threads) { foreach(State st in set) { string key = st.m_reason; List< State > lst; if(lookup.TryGetValue( key, out lst ) == false) { lst = new List< State >(); lookup [key] = lst; lookupCost[key] = 0; } lookupCost[key] += st.m_counter.TotalInclusiveMicroSeconds; lst.Add( st ); } } string[] keyArray = lookup.KeysToArray(); Array.Sort( keyArray, delegate ( string left, string right ) { return lookupCost[right].CompareTo( lookupCost[left] ); } ); foreach(string key in keyArray) { State[] states = SortByMostExpensive( lookup[key].ToArray() ); //--// long totalInclusiveMicroSeconds = 0; long totalExclusiveMicroSeconds = 0; int totalHits = 0; foreach(State st in states) { totalInclusiveMicroSeconds += st.m_counter.TotalInclusiveMicroSeconds; totalExclusiveMicroSeconds += st.m_counter.TotalExclusiveMicroSeconds; totalHits += st.m_counter.Hits; } textWriter.Write( "Key = {0}: ", key ); Emit( textWriter, "Exclusive", false, totalExclusiveMicroSeconds, totalHits ); Emit( textWriter, "Inclusive", false, totalInclusiveMicroSeconds, totalHits ); textWriter.WriteLine(); foreach(State st in states) { long inclusiveMicroSeconds = st.m_counter.TotalInclusiveMicroSeconds; long exclusiveMicroSeconds = st.m_counter.TotalExclusiveMicroSeconds; int hits = st.m_counter.Hits; textWriter.Write( " " ); Emit( textWriter, "Exclusive", true, exclusiveMicroSeconds, hits ); Emit( textWriter, "Inclusive", true, inclusiveMicroSeconds, hits ); textWriter.WriteLine( " | {0}", st.m_context ); if(st.m_children != null) { GrowOnlyHashTable< Timing.Nested, State > childrenInverted = GetInvertedHashTable( st.m_children ); foreach(Timing.Nested childCounter in SortByMostExpensive( childrenInverted.KeysToArray() )) { State child = childrenInverted[childCounter]; textWriter.Write( " " ); Emit( textWriter, "Child Exc", true, childCounter.TotalExclusiveMicroSeconds, childCounter.Hits ); if(child.m_context != st.m_context) { textWriter.WriteLine( " | {0,-30} / {1}", child.m_reason, child.m_context ); } else { textWriter.WriteLine( " | {0}", child.m_reason ); } } } textWriter.WriteLine(); } textWriter.WriteLine(); } } private static GrowOnlyHashTable< Timing.Nested, State > GetInvertedHashTable( GrowOnlyHashTable< State, Timing.Nested > ht ) { GrowOnlyHashTable< Timing.Nested, State > htInverted = HashTableFactory.NewWithReferenceEquality< Timing.Nested, State >(); htInverted.Load( ht.ValuesToArray(), ht.KeysToArray() ); return htInverted; } private static Timing.Nested[] SortByMostExpensive( Timing.Nested[] children ) { Array.Sort( children, delegate ( Timing.Nested left, Timing.Nested right ) { long leftUSec = left .TotalExclusiveMicroSeconds; long rightUSec = right.TotalExclusiveMicroSeconds; return rightUSec.CompareTo( leftUSec ); } ); return children; } private static State[] SortByMostExpensive( State[] states ) { Array.Sort( states, delegate ( State left, State right ) { long leftUSec = left .m_counter.TotalInclusiveMicroSeconds; long rightUSec = right.m_counter.TotalInclusiveMicroSeconds; return rightUSec.CompareTo( leftUSec ); } ); return states; } private static State[] SortByReason( State[] states ) { Array.Sort( states, delegate ( State left, State right ) { return left.m_reason.CompareTo( right.m_reason ); } ); return states; } private static void Emit( System.IO.TextWriter textWriter , string text , bool fAlign , long totalMicroSeconds , int totalHits ) { string fmt; if(fAlign) { fmt = " {0} => {1,10} uSec/{2,10} [{3,10:F1} uSec per hit]"; } else { fmt = " {0} => {1} uSec/{2} [{3} uSec per hit]"; } textWriter.Write( fmt, text, totalMicroSeconds, totalHits, totalHits > 0 ? (float)totalMicroSeconds / (float)totalHits : 0 ); } } #else public struct ContextualTiming : IDisposable { public ContextualTiming( object context , string reason ) { } public void Dispose() { } // // Access Methods // public long TotalInclusiveTicks { get { return 0; } } public long TotalInclusiveMicroSeconds { get { return 0; } } public long TotalExclusiveTicks { get { return 0; } } public long TotalExclusiveMicroSeconds { get { return 0; } } // // Debug Methods // public static bool IsEnabled() { return false; } public static void DumpAllByType( System.IO.TextWriter textWriter ) { } public static void DumpAllByReason( System.IO.TextWriter textWriter ) { } } #endif } ================================================ FILE: Zelig/Zelig/RunTime/Zelig/Common/PerformanceCounters/Timing.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // namespace Microsoft.Zelig.PerformanceCounters { using System; using System.Collections.Generic; using System.Runtime.InteropServices; public struct Timing { public class Nested { // // State // long m_exclusiveTime; int m_hits; // // Helper Methods // public void Sum( long exclusiveTime ) { m_exclusiveTime += exclusiveTime; m_hits += 1; } //--// // // Access Methods // public long TotalExclusiveTicks { get { return m_exclusiveTime; } } public long TotalExclusiveMicroSeconds { get { return (long)(m_exclusiveTime * s_toMicroSeconds); } } public int Hits { get { return m_hits; } } } class ThreadState { // // State // internal long m_overheadTotal; internal long m_overheadExclusive; internal int m_suspendCount; internal long m_suspendStart; internal int m_overheadQuery; // // Helper Methods // internal void Calibrate() { const int averagingRuns = 16 * 1024; const int averagingThreshold = 20; int averagingCount = 0; int averagingBestCount = 0; int averagingBestValue = 0; for(int i = 0; i < averagingRuns; i++) { Timing sampler1 = new Timing(); Timing sampler2 = new Timing(); Timing sampler3 = new Timing(); sampler1.Start(); sampler2.Start(); sampler3.Start(); sampler3.Stop ( false ); sampler2.Stop ( false ); sampler1.Stop ( false ); int diff = (int)sampler1.TotalInclusiveTicks; if(-10 < diff && diff < 100) { averagingCount++; if(averagingCount == averagingThreshold) { return; } } else { if(averagingBestCount < averagingCount) { averagingBestCount = averagingCount; averagingBestValue = m_overheadQuery; } averagingCount = 1; } if(m_overheadQuery == 0) { m_overheadQuery = diff; } else { m_overheadQuery += diff / 8; } } m_overheadQuery = averagingBestValue; } internal long GetTimestamp() { long res = System.Diagnostics.Stopwatch.GetTimestamp(); m_overheadTotal += m_overheadQuery; return res - m_overheadTotal; } } // // State // /************/ static double s_toMicroSeconds; [ThreadStatic] static ThreadState s_threadState; long m_startInclusive; long m_startExclusive; int m_gcCount; long m_totalInclusive; long m_totalExclusive; int m_hits; bool m_active; // // Helper Methods // private static ThreadState GetThreadState() { ThreadState ts = s_threadState; if(ts == null) { ts = new ThreadState(); s_threadState = ts; ts.Calibrate(); } return ts; } public static void Suspend() { ThreadState ts = GetThreadState(); if(ts.m_suspendCount++ == 0) { ts.m_suspendStart = ts.GetTimestamp(); } } public static void Resume() { ThreadState ts = GetThreadState(); if(--ts.m_suspendCount == 0) { long end = ts.GetTimestamp(); ts.m_overheadTotal += end - ts.m_suspendStart; } } public void Start() { ThreadState ts = GetThreadState(); CHECKS.ASSERT( ts.m_suspendCount == 0, "Cannot start performance timer while it's suspended." ); CHECKS.ASSERT( m_active == false, "Found recursive use of performance counter" ); m_startExclusive = ts.m_overheadExclusive; m_gcCount = GC.CollectionCount( 0 ); m_active = true; m_startInclusive = ts.GetTimestamp(); } public long Sample() { ThreadState ts = s_threadState; CHECKS.ASSERT( ts.m_suspendCount == 0, "Cannot stop performance timer while it's suspended." ); long end = ts.GetTimestamp(); return end - m_startInclusive; } public long Stop( bool fIgnoreGC ) { ThreadState ts = s_threadState; CHECKS.ASSERT( ts.m_suspendCount == 0, "Cannot stop performance timer while it's suspended." ); long end = ts.GetTimestamp(); if(fIgnoreGC == false && m_gcCount != GC.CollectionCount( 0 )) { // // A GC happened between Start and Stop, throw away the whole sample. // ts.m_overheadTotal += end - m_startInclusive; m_active = false; return 0; } else { long diff = end - m_startInclusive; long diffOverhead = ts.m_overheadExclusive - m_startExclusive; long diffExclusive = diff - diffOverhead; m_totalInclusive += diff; m_totalExclusive += diffExclusive; m_hits += 1; m_active = false; ts.m_overheadExclusive += diffExclusive; return diffExclusive; } } public void SetGcCount( int gcCount ) { m_gcCount = gcCount; } //--// static Timing() { s_toMicroSeconds = 1000000.0 / System.Diagnostics.Stopwatch.Frequency; } // // Access Methods // public static long ToMicroSeconds( long ticks ) { return (long)(ticks * s_toMicroSeconds); } public long TotalInclusiveTicks { get { return m_totalInclusive; } } public long TotalInclusiveMicroSeconds { get { return ToMicroSeconds( m_totalInclusive ); } } public float InclusiveTicksPerHit { get { return m_hits > 0 ? (float)m_totalInclusive / (float)m_hits : 0; } } public long TotalExclusiveTicks { get { return m_totalExclusive; } } public long TotalExclusiveMicroSeconds { get { return ToMicroSeconds( m_totalExclusive ); } } public float ExclusiveTicksPerHit { get { return m_hits > 0 ? (float)m_totalExclusive / (float)m_hits : 0; } } public int Hits { get { return m_hits; } } // // Debug Methods // public override string ToString() { return string.Format( "{0} - {1}", this.ExclusiveTicksPerHit, this.InclusiveTicksPerHit ); } } } ================================================ FILE: Zelig/Zelig/RunTime/Zelig/Common/Properties/AssemblyInfo.cs ================================================ using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; // General Information about an assembly is controlled through the following // set of attributes. Change these attribute values to modify the information // associated with an assembly. [assembly: AssemblyTitle( "Microsoft.Zelig.Runtime.Common" )] [assembly: AssemblyDescription( "" )] [assembly: AssemblyConfiguration( "" )] [assembly: AssemblyCompany( "Microsoft" )] [assembly: AssemblyProduct( "Microsoft.Zelig.Runtime.Common" )] [assembly: AssemblyCopyright( "Copyright © Microsoft 2006" )] [assembly: AssemblyTrademark( "" )] [assembly: AssemblyCulture( "" )] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible( false )] //// The following GUID is for the ID of the typelib if this project is exposed to COM //[assembly: Guid( "c2e5a31b-4e85-4692-a487-79f792176810" )] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Revision and Build Numbers // by using the '*' as shown below: [assembly: AssemblyVersion( "1.0.0.0" )] [assembly: AssemblyFileVersion( "1.0.0.0" )] ================================================ FILE: Zelig/Zelig/RunTime/Zelig/CommonPC/CommonPC.csproj ================================================  Debug AnyCPU 9.0.21022 2.0 {186F31A3-EF89-4A25-B2D5-20070601AA01} Library Properties Microsoft.Zelig.Runtime Microsoft.Zelig.Runtime.CommonPC $(LlilumBuildRoot)\Host\obj\$(MSBuildProjectName)\ v4.5 true full false $(LlilumBuildRoot)\Host\bin\$(Configuration)\ DEBUG;TRACE prompt 4 true true AllRules.ruleset AnyCPU false pdbonly true $(LlilumBuildRoot)\Host\bin\$(Configuration)\ TRACE prompt 4 true true AllRules.ruleset AnyCPU false true full false $(LlilumBuildRoot)\Host\bin\$(Configuration)\ TRACE;DEBUG true AnyCPU false 3.5 ================================================ FILE: Zelig/Zelig/RunTime/Zelig/CommonPC/Properties/AssemblyInfo.cs ================================================ using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; // General Information about an assembly is controlled through the following // set of attributes. Change these attribute values to modify the information // associated with an assembly. [assembly: AssemblyTitle( "Microsoft.Zelig.Runtime.CommonPC" )] [assembly: AssemblyDescription( "" )] [assembly: AssemblyConfiguration( "" )] [assembly: AssemblyCompany( "Microsoft" )] [assembly: AssemblyProduct( "Microsoft.Zelig.Runtime.CommonPC" )] [assembly: AssemblyCopyright( "Copyright © Microsoft 2007" )] [assembly: AssemblyTrademark( "" )] [assembly: AssemblyCulture( "" )] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible( false )] //// The following GUID is for the ID of the typelib if this project is exposed to COM //[assembly: Guid( "c2e5a31b-4e85-4692-a487-79f792176810" )] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Revision and Build Numbers // by using the '*' as shown below: [assembly: AssemblyVersion( "1.0.0.0" )] [assembly: AssemblyFileVersion( "1.0.0.0" )] ================================================ FILE: Zelig/Zelig/RunTime/Zelig/CommonPC/XmlHelper.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // namespace Microsoft.Zelig { using System; using System.Collections; using System.Collections.Generic; public static class XmlHelper { public static System.Xml.XmlElement AddElement( System.Xml.XmlDocument doc , string name ) { System.Xml.XmlElement subNode = doc.CreateElement( name ); doc.AppendChild( subNode ); return subNode; } public static System.Xml.XmlElement AddElement( System.Xml.XmlNode node , string name ) { System.Xml.XmlElement subNode = node.OwnerDocument.CreateElement( name ); node.AppendChild( subNode ); return subNode; } //--// public static System.Xml.XmlAttribute AddAttribute( System.Xml.XmlNode node , string name , string value ) { System.Xml.XmlAttribute attrib = node.OwnerDocument.CreateAttribute( name ); if(value != null) { attrib.Value = value; } node.Attributes.Append( attrib ); return attrib; } public static System.Xml.XmlAttribute AddAttribute( System.Xml.XmlNode node , string name , bool value ) { return AddAttribute( node, name, value.ToString() ); } public static System.Xml.XmlAttribute AddAttribute( System.Xml.XmlNode node , string name , int value ) { return AddAttribute( node, name, value.ToString() ); } public static System.Xml.XmlAttribute AddAttribute( System.Xml.XmlNode node , string name , uint value ) { return AddAttribute( node, name, string.Format( "0x{0:X8}", value ) ); } public static System.Xml.XmlAttribute AddAttribute( System.Xml.XmlNode node , string name , DateTime value ) { return AddAttribute( node, name, value.ToString() ); } public static System.Xml.XmlAttribute AddAttribute( System.Xml.XmlNode node , string name , Guid value ) { return AddAttribute( node, name, value.ToString() ); } //--// public static System.Xml.XmlAttribute FindAttribute( System.Xml.XmlNode node , string name ) { if(node != null) { foreach(System.Xml.XmlAttribute attrib in node.Attributes) { if(attrib.Name == name) { return attrib; } } } return null; } public static string GetAttribute( System.Xml.XmlNode node , string name ) { System.Xml.XmlAttribute attrib = FindAttribute( node, name ); if(attrib != null) { return attrib.Value; } return null; } public static bool GetAttribute( System.Xml.XmlNode node , string name , bool defaultValue ) { string val = GetAttribute( node, name ); bool res; if(val != null && bool.TryParse( val, out res )) { return res; } return defaultValue; } public static int GetAttribute( System.Xml.XmlNode node , string name , int defaultValue ) { string val = GetAttribute( node, name ); int res; if(val != null && int.TryParse( val, out res )) { return res; } return defaultValue; } public static uint GetAttribute( System.Xml.XmlNode node , string name , uint defaultValue ) { string val = GetAttribute( node, name ); uint res; if(val != null) { if(uint.TryParse( val, out res )) { return res; } if(val.StartsWith( "0x" ) && uint.TryParse( val.Substring( 2 ), System.Globalization.NumberStyles.AllowHexSpecifier, null, out res )) { return res; } } return defaultValue; } public static Guid GetAttribute( System.Xml.XmlNode node , string name , Guid defaultValue ) { string val = GetAttribute( node, name ); if(val != null) { try { return new Guid( val ); } catch { } } return defaultValue; } public static DateTime GetAttribute( System.Xml.XmlNode node , string name , DateTime defaultValue ) { string val = GetAttribute( node, name ); DateTime res; if(val != null && DateTime.TryParse( val, out res )) { return res; } return defaultValue; } } } ================================================ FILE: Zelig/Zelig/RunTime/Zelig/Kernel/Bootstrap.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // // Enables basic low-level self-tests for arithmetic and method calls. //#define SELF_TEST_BASIC // Enables memory self-tests to validate garbage collection techniques. //#define SELF_TEST_MEMORY // Enables self-tests covering null/bounds/overflow checks. //#define SELF_TEST_CHECKS namespace Microsoft.Zelig.Runtime { using System; using System.Runtime.CompilerServices; using TS = Microsoft.Zelig.Runtime.TypeSystem; // // During bootstrap there's the problem of where to put the machine stack and what to do with it afterwards. // Instead of statically allocating the stack, we change the memory initialization order. // // 1) All the available memory is assigned to the heap manager. This includes also the memory currently used for the stack. // 2) The heap is constructed, but the memory is not cleared. // 3) An array of words is allocated. This overlaps the current stack, by virtue of the way the memory is allocated // (from the top of the memory, instead of from the bottom). // [We wrap all free memory into a managed object (a uint[]), an allocation that is less than the full free block is // just a decrement of the array length. This is cheaper than moving the free block and relinking it]. // 4) All free memory is cleared, so that future allocations already have the correct memory state (all zeros). // 5) We pass the previously allocated array to the ThreadManager, that will use it for the stack of the Idle thread. // 6) We create the Idle Thread and context switch to it. // This is the trick that allows to reclaim all memory: we'll never go back to the original context, // so all its state can be discarded. // The new thread will overwrite the same location but that's OK. And all memory is managed (AKA: it has a valid ObjectHeader to describe it). // public static class Bootstrap { [NoReturn] [CannotAllocate] [StackNotAvailable] [BottomOfCallStack] [HardwareExceptionHandler( HardwareException.Reset )] public static void EntryPoint() { PreInitialization(); Initialization(); } [NoInline] [NoReturn] [TS.WellKnownMethod( "Bootstrap_Initialization" )] public static unsafe void Initialization() { #if SELF_TEST_BASIC SelfTest.SelfTest__Bootstrap( ); #endif // SELF_TEST_BASIC // // This should only minimally setup hardware so that the system is functional. // For example, all the peripherals have been added to the address space, // memory has been initialized and operated at the nominal rate, the CPU runs at // the correct clock frequency, etc. // HardwareInitialization(); // // This only initializes the heap. // HeapInitialization(); // // This initializes the main software services, like object allocation, type system, thread manager, etc. // SoftwareInitialization( Device.Instance.BootstrapStack ); #if SELF_TEST_CHECKS SelfTest.SelfTest__Checks(); #endif // SELF_TEST_CHECKS #if SELF_TEST_MEMORY SelfTest.SelfTest__Memory(); #endif // SELF_TEST_MEMORY // // Once all the software services have been initialized, we can activate the hardware. // Activating the hardware might require starting threads, associated delegate with callbacks, etc. // HardwareActivation(); // // After the hardware is ready, we can start the software services, which will use the hardware one. // SoftwareActivation(); // // Time to start execution of user app by delegating to the thread manager ThreadManager.Instance.StartThreads(); } //--// [Inline] [StackAvailableOnReturn] private static void PreInitialization() { Device dev = Device.Instance; dev.PreInitializeProcessorAndMemory(); dev.MoveCodeToProperLocation(); } [NoInline] private static void HardwareInitialization() { Processor.Instance.InitializeProcessor(); Memory.Instance.InitializeMemory(); Peripherals.Instance.Initialize(); } [NoInline] [CanAllocateOnReturn] [TS.WellKnownMethod( "Bootstrap_HeapInitialization" )] private static void HeapInitialization() { MemoryManager mm = MemoryManager.Instance; mm.InitializeMemoryManager(); mm.InitializationComplete(); } [TS.WellKnownMethod( "Bootstrap_ReferenceCountingInitialization" )] private static void ReferenceCountingInitialization() { ThreadManager.InitializeForReferenceCounting( ); } [NoInline] [CanAllocateOnReturn] private static void SoftwareInitialization( uint[] systemStack ) { ThreadManager.Instance.InitializeBeforeStaticConstructors(); TypeSystemManager.Instance.InitializeTypeSystemManager(); ThreadManager.Instance.InitializeAfterStaticConstructors( systemStack ); GarbageCollectionManager.Instance.InitializeGarbageCollectionManager(); } [NoInline] private static void HardwareActivation() { Storage.Instance.InitializeStorage(); Peripherals.Instance.Activate(); } [NoInline] private static void SoftwareActivation() { ThreadManager.Instance.Activate(); } } } ================================================ FILE: Zelig/Zelig/RunTime/Zelig/Kernel/FrameworkOverrides/ActivatorImpl.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // namespace Microsoft.Zelig.Runtime { using System; using TS = Microsoft.Zelig.Runtime.TypeSystem; [ExtendClass(typeof(System.Activator), NoConstructors=true)] public class ActivatorImpl { // // State // // // Constructor Methods // //--// // // Helper Methods // [TS.WellKnownMethod( "ActivatorImpl_CreateInstanceInner" )] public static extern object CreateInstanceInner( Type t ); //--// // // Access Methods // } } ================================================ FILE: Zelig/Zelig/RunTime/Zelig/Kernel/FrameworkOverrides/ArrayImpl.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // namespace Microsoft.Zelig.Runtime { using System; using System.Collections.Generic; using TS = Microsoft.Zelig.Runtime.TypeSystem; [ExtendClass(typeof(System.Array), NoConstructors=true)] public class ArrayImpl { // // State // [TS.WellKnownField( "ArrayImpl_m_numElements" )] internal uint m_numElements; // // Constructor Methods // private ArrayImpl() { m_numElements = 0; } //--// // // Helper Methods // public int GetUpperBound( int dimension ) { TS.VTable vTable = TS.VTable.Get( this ); TS.TypeRepresentation ts = vTable.TypeInfo; if(ts is TS.SzArrayReferenceTypeRepresentation) { return (int)(m_numElements - 1); } TS.MultiArrayReferenceTypeRepresentation ts2 = (TS.MultiArrayReferenceTypeRepresentation)ts; return (int)ts2.Dimensions[dimension].m_upperBound; } public int GetLowerBound( int dimension ) { TS.VTable vTable = TS.VTable.Get( this ); TS.TypeRepresentation ts = vTable.TypeInfo; if(ts is TS.SzArrayReferenceTypeRepresentation) { return 0; } TS.MultiArrayReferenceTypeRepresentation ts2 = (TS.MultiArrayReferenceTypeRepresentation)ts; return (int)ts2.Dimensions[dimension].m_lowerBound; } public static unsafe void Clear( ArrayImpl array , int index , int length ) { if(index < 0 || length < 0 ) { throw new IndexOutOfRangeException(); } int indexEnd = index + length; if(indexEnd > array.Length) { throw new IndexOutOfRangeException(); } TS.VTable vTable = TS.VTable.Get( array ); void* voidPtr = array.GetPointerToElement( (uint)index ); void* voidPtrEnd = array.GetPointerToElement( (uint)indexEnd ); if((vTable.ElementSize & 3) == 0) { // // Word aligned. // uint* ptr = (uint*)voidPtr; uint* ptrEnd = (uint*)voidPtrEnd; while(ptr < ptrEnd) { *ptr++ = 0; } } else { byte* ptr = (byte*)voidPtr; byte* ptrEnd = (byte*)voidPtrEnd; while(ptr < ptrEnd) { *ptr++ = 0; } } } internal static unsafe void Copy( ArrayImpl sourceArray , int sourceIndex , ArrayImpl destinationArray , int destinationIndex , int length , bool reliable ) { if(sourceIndex < 0 || destinationIndex < 0 || length < 0 ) { throw new IndexOutOfRangeException(); } int sourceIndexEnd = sourceIndex + length; if(sourceIndexEnd > sourceArray.Length) { throw new IndexOutOfRangeException(); } int destinationIndexEnd = destinationIndex + length; if(destinationIndexEnd > destinationArray.Length) { throw new IndexOutOfRangeException(); } TS.VTable vTableSource = TS.VTable.Get( sourceArray ); TS.VTable vTableDestination = TS.VTable.Get( destinationArray ); if(vTableSource != vTableDestination) { throw new NotSupportedException(); } void* voidSourcePtr = sourceArray .GetPointerToElement( (uint)sourceIndex ); void* voidDestinationPtr = destinationArray.GetPointerToElement( (uint)destinationIndex ); if(voidSourcePtr != voidDestinationPtr) { BufferImpl.InternalMemoryMove( (byte*)voidSourcePtr, (byte*)voidDestinationPtr, length * (int)vTableSource.ElementSize ); } } //--// // // This is used to cast between an object and and ArrayImpl, which is not possible in C#. // [TS.GenerateUnsafeCast] public extern static ArrayImpl CastAsArray( object target ); // // This is used to cast between an object and and ArrayImpl, which is not possible in C#. // [TS.GenerateUnsafeCast] public extern Array CastThisAsArray(); // // This is used to get the pointer to the data, which is not possible in C#. // [Inline] public unsafe uint* GetDataPointer() { fixed(uint* ptr = &m_numElements) { return &ptr[1]; } } // // This is used to get the pointer to the data, which is not possible in C#. // public unsafe void* GetPointerToElement( uint index ) { byte* ptr = (byte*)GetDataPointer(); return &ptr[index * this.ElementSize]; } // // This is used to get the pointer to the data, which is not possible in C#. // public unsafe uint* GetEndDataPointer() { return (uint*)GetPointerToElement( m_numElements ); } //--// internal void SetLength( uint numElements ) { m_numElements = numElements; } //--// [NoInline] [NoReturn] internal static void Throw_FixedSizeCollection() { #if EXCEPTION_STRINGS throw new NotSupportedException( "NotSupported_FixedSizeCollection" ); #else throw new NotSupportedException(); #endif } [NoInline] [NoReturn] internal static void Throw_ReadOnlyCollection() { #if EXCEPTION_STRINGS throw new NotSupportedException( "NotSupported_ReadOnlyCollection" ); #else throw new NotSupportedException(); #endif } [NoInline] internal static void EnsureSZArray( Array array ) { if(array != null && array.Rank != 1) { #if EXCEPTION_STRINGS throw new ArgumentException( "Rank_MultiDimNotSupported" ); #else throw new ArgumentException(); #endif } } // //--// // // Access Methods // public int Length { [Inline] [TS.WellKnownMethod( "ArrayImpl_get_Length" )] get { return (int)m_numElements; } } public uint Size { [Inline] get { return m_numElements * this.ElementSize; } } public uint ElementSize { [Inline] get { return TS.VTable.Get( this ).ElementSize; } } public int Rank { get { TS.VTable vTable = TS.VTable.Get( this ); TS.TypeRepresentation ts = vTable.TypeInfo; if(ts is TS.SzArrayReferenceTypeRepresentation) { return 1; } TS.MultiArrayReferenceTypeRepresentation ts2 = (TS.MultiArrayReferenceTypeRepresentation)ts; return (int)ts2.Dimensions.Length; } } //--// public static uint[] InitializeFromRawMemory( UIntPtr baseAddress, uint sizeInBytes ) { BugCheck.Assert( sizeInBytes % 4 == 0, BugCheck.StopCode.IncorrectArgument ); TS.VTable vTable = TS.VTable.GetFromType( typeof(uint[]) ); uint numOfElements = (sizeInBytes - MemoryFreeBlock.FixedSize() ) / sizeof( uint ); uint[] externalRepresentation = (uint[])TypeSystemManager.Instance.InitializeArray( baseAddress, vTable, numOfElements, referenceCounting: false ); ObjectHeader oh = ObjectHeader.Unpack( externalRepresentation ); oh.MultiUseWord = (int)(ObjectHeader.GarbageCollectorFlags.FreeBlock | ObjectHeader.GarbageCollectorFlags.Unmarked); return externalRepresentation; } } //---------------------------------------------------------------------------------------- // ! READ THIS BEFORE YOU WORK ON THIS CLASS. // // This class is needed to allow an SZ array of type T[] to expose IList, // IList, etc., etc. all the way up to IList. When the following call is // made: // // ((IList) (new U[n])).SomeIListMethod() // // the interface stub dispatcher treats this as a special case, loads up SZArrayHelper, // finds the corresponding generic method (matched simply by method name), instantiates // it for type and executes it. // // The "T" will reflect the interface used to invoke the method. The actual runtime "this" will be // array that is castable to "T[]" (i.e. for primitivs and valuetypes, it will be exactly // "T[]" - for orefs, it may be a "U[]" where U derives from T.) //---------------------------------------------------------------------------------------- [TS.WellKnownType( "Microsoft_Zelig_Runtime_SZArrayHelper" )] static class SZArrayHelper { // ----------------------------------------------------------- // ------- Implement IEnumerable interface methods -------- // ----------------------------------------------------------- [Inline] internal static IEnumerator GetEnumerator( T[] _this ) { //! Warning: "this" is an array, not an SZArrayHelper. See comments above //! or you may introduce a security hole! return new SZGenericArrayEnumerator( _this ); } // ----------------------------------------------------------- // ------- Implement ICollection interface methods -------- // ----------------------------------------------------------- [Inline] internal static void CopyTo( T[] _this , T[] array , int index ) { ArrayImpl.EnsureSZArray( array ); Array.Copy( _this, 0, array, index, _this.Length ); } [Inline] internal static int get_Count( T[] _this ) { return _this.Length; } // ----------------------------------------------------------- // ---------- Implement IList interface methods ----------- // ----------------------------------------------------------- [Inline] internal static T get_Item( T[] _this , int index ) { //// if((uint)index >= (uint)_this.Length) //// { //// ThrowHelper.ThrowArgumentOutOfRangeException(); //// } return _this[index]; } [Inline] internal static void set_Item( T[] _this , int index , T value ) { //// if((uint)index >= (uint)_this.Length) //// { //// ThrowHelper.ThrowArgumentOutOfRangeException(); //// } _this[index] = value; } [Inline] internal static void Add( T[] _this , T value ) { ArrayImpl.Throw_FixedSizeCollection(); } [Inline] internal static bool Contains( T[] _this , T value ) { return Array.IndexOf( _this, value ) != -1; } [Inline] internal static bool get_IsReadOnly( T[] _this ) { return true; } [Inline] internal static void Clear( T[] _this ) { ArrayImpl.Throw_ReadOnlyCollection(); } [Inline] internal static int IndexOf( T[] _this , T value ) { return Array.IndexOf( _this, value ); } [Inline] internal static void Insert( T[] _this , int index , T value ) { // Not meaningful for arrays ArrayImpl.Throw_FixedSizeCollection(); } [Inline] internal static bool Remove( T[] _this , T value ) { // Not meaningful for arrays ArrayImpl.Throw_FixedSizeCollection(); return false; } [Inline] internal static void RemoveAt( T[] _this , int index ) { // Not meaningful for arrays ArrayImpl.Throw_FixedSizeCollection(); } // This is a normal generic Enumerator for SZ arrays. It doesn't have any of the "this" voodoo // that SZArrayHelper does. // [Serializable] private sealed class SZGenericArrayEnumerator : System.Collections.Generic.IEnumerator { private T[] m_array; private int m_index; private int m_endIndex; // cache array length, since it's a little slow. internal SZGenericArrayEnumerator( T[] array ) { //// BCLDebug.Assert( array.Rank == 1 && array.GetLowerBound( 0 ) == 0, "SZArrayEnumerator only works on single dimension arrays w/ a lower bound of zero." ); m_array = array; m_index = -1; m_endIndex = array.Length; } public bool MoveNext() { if(m_index < m_endIndex) { m_index++; return (m_index < m_endIndex); } return false; } public T Current { get { //// if(m_index < 0) //// { //// throw new InvalidOperationException( Environment.GetResourceString( ResId.InvalidOperation_EnumNotStarted ) ); //// } //// //// if(m_index >= m_endIndex) //// { //// throw new InvalidOperationException( Environment.GetResourceString( ResId.InvalidOperation_EnumEnded ) ); //// } return m_array[m_index]; } } object System.Collections.IEnumerator.Current { get { return Current; } } void System.Collections.IEnumerator.Reset() { m_index = -1; } public void Dispose() { } } } } ================================================ FILE: Zelig/Zelig/RunTime/Zelig/Kernel/FrameworkOverrides/BufferImpl.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // #define LLVM namespace Microsoft.Zelig.Runtime { using System; using TS = Microsoft.Zelig.Runtime.TypeSystem; [ExtendClass(typeof(System.Buffer), NoConstructors=true, ProcessAfter=typeof(ArrayImpl))] public static class BufferImpl { // // Helper Methods // public unsafe static void BlockCopy( ArrayImpl src , int srcOffset , ArrayImpl dst , int dstOffset , int count ) { TS.VTable vtSrc = TS.VTable.Get( src ); TS.VTable vtDst = TS.VTable.Get( dst ); if((vtSrc.TypeInfo.ContainedType is TS.ScalarTypeRepresentation) == false) { #if EXCEPTION_STRINGS throw new NotSupportedException( "Not a scalar" ); #else throw new NotSupportedException(); #endif } if((vtDst.TypeInfo.ContainedType is TS.ScalarTypeRepresentation) == false) { #if EXCEPTION_STRINGS throw new NotSupportedException( "Not a scalar" ); #else throw new NotSupportedException(); #endif } if(count < 0) { #if EXCEPTION_STRINGS throw new IndexOutOfRangeException( "count" ); #else throw new IndexOutOfRangeException(); #endif } if(srcOffset < 0 || (uint)(srcOffset + count) > src.Size) { #if EXCEPTION_STRINGS throw new IndexOutOfRangeException( "src" ); #else throw new IndexOutOfRangeException(); #endif } if(dstOffset < 0 || (uint)(dstOffset + count) > dst.Size) { #if EXCEPTION_STRINGS throw new IndexOutOfRangeException( "dst" ); #else throw new IndexOutOfRangeException(); #endif } byte* srcPtr = (byte*)src.GetDataPointer(); byte* dstPtr = (byte*)dst.GetDataPointer(); InternalMemoryMove( &srcPtr[srcOffset], &dstPtr[dstOffset], count ); } internal unsafe static void InternalBlockCopy( ArrayImpl src , int srcOffset , ArrayImpl dst , int dstOffset , int count ) { BugCheck.Assert( TS.VTable.Get( src ) == TS.VTable.Get( dst ), BugCheck.StopCode.IncorrectArgument ); if(count < 0) { #if EXCEPTION_STRINGS throw new IndexOutOfRangeException( "count" ); #else throw new IndexOutOfRangeException(); #endif } if(srcOffset < 0 || (uint)(srcOffset + count) > src.Size) { #if EXCEPTION_STRINGS throw new IndexOutOfRangeException( "src" ); #else throw new IndexOutOfRangeException(); #endif } if(dstOffset < 0 || (uint)(dstOffset + count) > dst.Size) { #if EXCEPTION_STRINGS throw new IndexOutOfRangeException( "dst" ); #else throw new IndexOutOfRangeException(); #endif } byte* srcPtr = (byte*)src.GetDataPointer(); byte* dstPtr = (byte*)dst.GetDataPointer(); InternalMemoryMove( &srcPtr[srcOffset], &dstPtr[dstOffset], count ); } //--//--// [DisableNullChecks] #if LLVM [NoInline] // Disable inlining so we always have a chance to replace the method. #endif // LLVM [TS.WellKnownMethod("System_Buffer_InternalMemoryCopy")] internal unsafe static void InternalMemoryCopy( byte* src , byte* dst , int count ) { BugCheck.Assert( count >= 0, BugCheck.StopCode.NegativeIndex ); if(AddressMath.IsAlignedTo32bits( src ) && AddressMath.IsAlignedTo32bits( dst ) ) { int count32 = count / 4; InternalMemoryCopy( (uint*)src, (uint*)dst, count32 ); int count2 = count32 * 4; src += count2; dst += count2; count -= count2; } else if(AddressMath.IsAlignedTo16bits( src ) && AddressMath.IsAlignedTo16bits( dst ) ) { int count16 = count / 2; InternalMemoryCopy( (ushort*)src, (ushort*)dst, count16 ); int count2 = count16 * 2; src += count2; dst += count2; count -= count2; } if(count > 0) { while(count >= 4) { var v0 = src[0]; var v1 = src[1]; var v2 = src[2]; var v3 = src[3]; dst[0] = v0; dst[1] = v1; dst[2] = v2; dst[3] = v3; dst += 4; src += 4; count -= 4; } if((count & 2) != 0) { var v0 = src[0]; var v1 = src[1]; dst[0] = v0; dst[1] = v1; dst += 2; src += 2; } if((count & 1) != 0) { dst[0] = src[0]; } } } [Inline] internal unsafe static void InternalMemoryCopy( sbyte* src , sbyte* dst , int count ) { InternalMemoryCopy( (byte*)src, (byte*)dst, count ); } //--// [DisableNullChecks] internal unsafe static void InternalMemoryCopy( ushort* src , ushort* dst , int count ) { #if LLVM InternalMemoryCopy((byte*)src, (byte*)dst, count * sizeof(ushort)); #else // LLVM BugCheck.Assert( count >= 0, BugCheck.StopCode.NegativeIndex ); if(AddressMath.IsAlignedTo32bits( src ) && AddressMath.IsAlignedTo32bits( dst ) ) { int count32 = count / 2; InternalMemoryCopy( (uint*)src, (uint*)dst, count32 ); int count2 = count32 * 2; src += count2; dst += count2; count -= count2; } if(count > 0) { while(count >= 4) { var v0 = src[0]; var v1 = src[1]; var v2 = src[2]; var v3 = src[3]; dst[0] = v0; dst[1] = v1; dst[2] = v2; dst[3] = v3; dst += 4; src += 4; count -= 4; } if((count & 2) != 0) { var v0 = src[0]; var v1 = src[1]; dst[0] = v0; dst[1] = v1; dst += 2; src += 2; } if((count & 1) != 0) { dst[0] = src[0]; } } #endif // LLVM } [Inline] internal unsafe static void InternalMemoryCopy( short* src , short* dst , int count ) { InternalMemoryCopy( (ushort*)src, (ushort*)dst, count ); } [Inline] internal unsafe static void InternalMemoryCopy( char* src , char* dst , int count ) { InternalMemoryCopy( (ushort*)src, (ushort*)dst, count ); } //--// [DisableNullChecks] internal unsafe static void InternalMemoryCopy( uint* src , uint* dst , int count ) { #if LLVM InternalMemoryCopy((byte*)src, (byte*)dst, count * sizeof(uint)); #else // LLVM BugCheck.Assert( count >= 0, BugCheck.StopCode.NegativeIndex ); if(count > 0) { while(count >= 4) { var v0 = src[0]; var v1 = src[1]; var v2 = src[2]; var v3 = src[3]; dst[0] = v0; dst[1] = v1; dst[2] = v2; dst[3] = v3; dst += 4; src += 4; count -= 4; } if((count & 2) != 0) { var v0 = src[0]; var v1 = src[1]; dst[0] = v0; dst[1] = v1; dst += 2; src += 2; } if((count & 1) != 0) { dst[0] = src[0]; } } #endif // LLVM } [Inline] internal unsafe static void InternalMemoryCopy( int* src , int* dst , int count ) { InternalMemoryCopy( (uint*)src, (uint*)dst, count ); } //--//--// [DisableNullChecks] #if LLVM [NoInline] // Disable inlining so we always have a chance to replace the method. #endif // LLVM [TS.WellKnownMethod( "System_Buffer_InternalBackwardMemoryCopy" )] internal unsafe static void InternalBackwardMemoryCopy( byte* src , byte* dst , int count ) { BugCheck.Assert( count >= 0, BugCheck.StopCode.NegativeIndex ); src += count; dst += count; if(AddressMath.IsAlignedTo32bits( src ) && AddressMath.IsAlignedTo32bits( dst ) ) { uint* src2 = (uint*)src; uint* dst2 = (uint*)dst; int count32 = count / 4; src2 -= count32; dst2 -= count32; InternalBackwardMemoryCopy( src2, dst2, count32 ); int count2 = count32 * 4; src = (byte*)src2; dst = (byte*)dst2; count -= count2; } else if(AddressMath.IsAlignedTo16bits( src ) && AddressMath.IsAlignedTo16bits( dst ) ) { ushort* src2 = (ushort*)src; ushort* dst2 = (ushort*)dst; int count16 = count / 2; src2 -= count16; dst2 -= count16; InternalBackwardMemoryCopy( src2, dst2, count16 ); int count2 = count16 * 2; src = (byte*)src2; dst = (byte*)dst2; count -= count2; } if(count > 0) { while(count >= 4) { dst -= 4; src -= 4; count -= 4; var v0 = src[0]; var v1 = src[1]; var v2 = src[2]; var v3 = src[3]; dst[0] = v0; dst[1] = v1; dst[2] = v2; dst[3] = v3; } if((count & 2) != 0) { dst -= 2; src -= 2; var v0 = src[0]; var v1 = src[1]; dst[0] = v0; dst[1] = v1; } if((count & 1) != 0) { dst -= 1; src -= 1; dst[0] = src[0]; } } } [Inline] internal unsafe static void InternalBackwardMemoryCopy( sbyte* src , sbyte* dst , int count ) { InternalBackwardMemoryCopy( (byte*)src, (byte*)dst, count ); } //--// [DisableNullChecks] internal unsafe static void InternalBackwardMemoryCopy( ushort* src , ushort* dst , int count ) { #if LLVM InternalBackwardMemoryCopy( (byte*)src, (byte*)dst, count * sizeof( ushort ) ); #else // LLVM BugCheck.Assert( count >= 0, BugCheck.StopCode.NegativeIndex ); src += count; dst += count; if(AddressMath.IsAlignedTo32bits( src ) && AddressMath.IsAlignedTo32bits( dst ) ) { uint* src2 = (uint*)src; uint* dst2 = (uint*)dst; int count32 = count / 2; src2 -= count32; dst2 -= count32; InternalBackwardMemoryCopy( src2, dst2, count32 ); int count2 = count32 * 2; src = (ushort*)src2; dst = (ushort*)dst2; count -= count2; } if(count > 0) { while(count >= 4) { dst -= 4; src -= 4; count -= 4; var v0 = src[0]; var v1 = src[1]; var v2 = src[2]; var v3 = src[3]; dst[0] = v0; dst[1] = v1; dst[2] = v2; dst[3] = v3; } if((count & 2) != 0) { dst -= 2; src -= 2; var v0 = src[0]; var v1 = src[1]; dst[0] = v0; dst[1] = v1; } if((count & 1) != 0) { dst -= 1; src -= 1; dst[0] = src[0]; } } #endif // LLVM } [Inline] internal unsafe static void InternalBackwardMemoryCopy( short* src , short* dst , int count ) { InternalBackwardMemoryCopy( (ushort*)src, (ushort*)dst, count ); } [Inline] internal unsafe static void InternalBackwardMemoryCopy( char* src , char* dst , int count ) { InternalBackwardMemoryCopy( (ushort*)src, (ushort*)dst, count ); } //--// [DisableNullChecks] internal unsafe static void InternalBackwardMemoryCopy( uint* src , uint* dst , int count ) { #if LLVM InternalBackwardMemoryCopy( (byte*)src, (byte*)dst, count * sizeof( uint ) ); #else // LLVM BugCheck.Assert( count >= 0, BugCheck.StopCode.NegativeIndex ); if(count > 0) { src += count; dst += count; while(count >= 4) { dst -= 4; src -= 4; count -= 4; var v0 = src[0]; var v1 = src[1]; var v2 = src[2]; var v3 = src[3]; dst[0] = v0; dst[1] = v1; dst[2] = v2; dst[3] = v3; } if((count & 2) != 0) { dst -= 2; src -= 2; var v0 = src[0]; var v1 = src[1]; dst[0] = v0; dst[1] = v1; } if((count & 1) != 0) { dst -= 1; src -= 1; dst[0] = src[0]; } } #endif // LLVM } [Inline] internal unsafe static void InternalBackwardMemoryCopy( int* src , int* dst , int count ) { InternalBackwardMemoryCopy( (uint*)src, (uint*)dst, count ); } //--//--// internal unsafe static void InternalMemoryMove( byte* src , byte* dst , int count ) { BugCheck.Assert( count >= 0, BugCheck.StopCode.NegativeIndex ); if(src <= dst && dst < &src[count]) { InternalBackwardMemoryCopy( src, dst, count ); } else { InternalMemoryCopy( src, dst, count ); } } [Inline] internal unsafe static void InternalMemoryMove( sbyte* src , sbyte* dst , int count ) { InternalMemoryMove( (byte*)src, (byte*)dst, count ); } //--// internal unsafe static void InternalMemoryMove( ushort* src , ushort* dst , int count ) { BugCheck.Assert( count >= 0, BugCheck.StopCode.NegativeIndex ); if(src <= dst && dst < &src[count]) { InternalBackwardMemoryCopy( src, dst, count ); } else { InternalMemoryCopy( src, dst, count ); } } [Inline] internal unsafe static void InternalMemoryMove( short* src , short* dst , int count ) { InternalMemoryMove( (ushort*)src, (ushort*)dst, count ); } [Inline] internal unsafe static void InternalMemoryMove( char* src , char* dst , int count ) { InternalMemoryMove( (ushort*)src, (ushort*)dst, count ); } //--// internal unsafe static void InternalMemoryMove( uint* src , uint* dst , int count ) { BugCheck.Assert( count >= 0, BugCheck.StopCode.NegativeIndex ); if(src <= dst && dst < &src[count]) { InternalBackwardMemoryCopy( src, dst, count ); } else { InternalMemoryCopy( src, dst, count ); } } [Inline] internal unsafe static void InternalMemoryMove( int* src , int* dst , int count ) { InternalMemoryMove( (uint*)src, (uint*)dst, count ); } } } ================================================ FILE: Zelig/Zelig/RunTime/Zelig/Kernel/FrameworkOverrides/ConsoleImpl.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // namespace Microsoft.Zelig.Runtime { using System; using TS = Microsoft.Zelig.Runtime.TypeSystem; [ExtendClass(typeof(System.Console))] public static class ConsoleImpl { // // Helper Methods // [NoInline] public static void WriteLine() { BugCheck.WriteLine( "" ); } [NoInline] public static void WriteLine( String value ) { BugCheck.WriteLine( value ); } [NoInline] public static void WriteLine( String format , Object arg0 ) { BugCheck.WriteLineFormat( format, arg0 ); } [NoInline] public static void WriteLine( String format , Object arg0 , Object arg1 ) { BugCheck.WriteLineFormat( format, arg0, arg1 ); } [NoInline] public static void WriteLine( String format , Object arg0 , Object arg1 , Object arg2 ) { BugCheck.WriteLineFormat( format, arg0, arg1, arg2 ); } [NoInline] public static void WriteLine( String format , params Object[] arg ) { BugCheck.WriteLineFormat( format, arg ); } } } ================================================ FILE: Zelig/Zelig/RunTime/Zelig/Kernel/FrameworkOverrides/CurrentSystemTimeZoneImpl.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // namespace Microsoft.Zelig.Runtime { using System; using TS = Microsoft.Zelig.Runtime.TypeSystem; [ExtendClass("System_CurrentSystemTimeZone", NoConstructors=true)] public class CurrentSystemTimeZoneImpl { // // Helper Methods // internal static int nativeGetTimeZoneMinuteOffset() { return -9 * 60; } internal static String nativeGetDaylightName() { return ""; } internal static String nativeGetStandardName() { return ""; } internal static short[] nativeGetDaylightChanges() { return new short[] { 0, 3, 0, 2, 2, 0, 0, 0, 0, 11, 0, 1, 2, 0, 0, 0, 60 }; } } } ================================================ FILE: Zelig/Zelig/RunTime/Zelig/Kernel/FrameworkOverrides/DateTimeImpl.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // namespace Microsoft.Zelig.Runtime { using System; using TS = Microsoft.Zelig.Runtime.TypeSystem; [ExtendClass(typeof(System.DateTime), NoConstructors=true)] public struct DateTimeImpl { // // State // static SchedulerTimeSpan s_reference = (SchedulerTime)new DateTime( 2007, 1, 1 ) - SchedulerTime.MinValue; // // Helper Methods // internal static ulong GetSystemTimeAsDateTimeTicks() { SchedulerTime now = SchedulerTime.Now + s_reference; DateTime now2 = (DateTime)now; return (ulong)now2.Ticks; } public static void SetUtcTime( DateTime newTime ) { SchedulerTime now = SchedulerTime.Now; TimeSpan diff = newTime - (DateTime)now; s_reference = (SchedulerTimeSpan)diff; } } } ================================================ FILE: Zelig/Zelig/RunTime/Zelig/Kernel/FrameworkOverrides/DelegateImpl.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // namespace Microsoft.Zelig.Runtime { using System; using TS = Microsoft.Zelig.Runtime.TypeSystem; [ExtendClass(typeof(System.Delegate))] public class DelegateImpl { // // State // // m_target is the object we will invoke on [TS.WellKnownField( "DelegateImpl_m_target" )] internal Object m_target; // m_codePtr is a pointer to the method we will invoke [TS.WellKnownField( "DelegateImpl_m_codePtr" )] internal TS.CodePointer m_codePtr; // // Constructor Methods // [MergeWithTargetImplementation] internal DelegateImpl( Object target , TS.CodePointer codePtr ) { m_target = target; m_codePtr = codePtr; } //--// public override bool Equals( Object obj ) { if(obj == null || !InternalEqualTypes( this, obj )) { return false; } DelegateImpl d = obj as DelegateImpl; if(d == null) { return false; } return (m_target == d.m_target && m_codePtr.Target == d.m_codePtr.Target); } public override int GetHashCode() { return m_codePtr.Target.GetHashCode(); } //--// public static bool operator ==( DelegateImpl d1 , DelegateImpl d2 ) { if((Object)d1 == null) { return (Object)d2 == null; } return d1.Equals( d2 ); } public static bool operator !=( DelegateImpl d1 , DelegateImpl d2 ) { if((Object)d1 == null) { return (Object)d2 != null; } return !d1.Equals( d2 ); } public static DelegateImpl Combine( DelegateImpl a, DelegateImpl b ) { // boundary conditions -- if either (or both) delegates is null return the other. if((Object)a == null) // cast to object for a more efficient test { return b; } if((Object)b == null) // cast to object for a more efficient test { return a; } if(!InternalEqualTypes( a, b )) { #if EXCEPTION_STRINGS throw new ArgumentException( "Arg_DlgtTypeMis" ); #else throw new ArgumentException(); #endif } return a.CombineImpl( b ); } public static DelegateImpl Remove( DelegateImpl source, DelegateImpl value ) { if(source == null) { return null; } if(value == null) { return source; } if(!InternalEqualTypes( source, value )) { #if EXCEPTION_STRINGS throw new ArgumentException( "Arg_DlgtTypeMis" ); #else throw new ArgumentException(); #endif } return source.RemoveImpl( value ); } //--// protected virtual Object GetTarget() { return m_target; } protected virtual System.Reflection.MethodInfo GetMethodImpl() { return TypeSystemManager.CodePointerToMethodInfo( m_codePtr ); } protected virtual DelegateImpl CombineImpl( DelegateImpl d ) { #if EXCEPTION_STRINGS throw new MulticastNotSupportedException( "Multicast_Combine" ); #else throw new MulticastNotSupportedException(); #endif } protected virtual DelegateImpl RemoveImpl( DelegateImpl d ) { return d.Equals( this ) ? null : this; } //--// public TS.CodePointer InnerGetCodePointer() { return m_codePtr; } internal System.Reflection.MethodInfo InnerGetMethod() { return TypeSystemManager.CodePointerToMethodInfo( m_codePtr ); } [Inline] protected static bool InternalEqualTypes( object a , object b ) { return TS.VTable.SameType( a, b ); } } } ================================================ FILE: Zelig/Zelig/RunTime/Zelig/Kernel/FrameworkOverrides/Diagnostics/DebuggerImpl.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // namespace Microsoft.Zelig.Runtime { using System; using System.Runtime.CompilerServices; using TS = Microsoft.Zelig.Runtime.TypeSystem; [ExtendClass(typeof(System.Diagnostics.Debugger), NoConstructors=true)] public class DebuggerImpl { [Inline] public static void Break() { Processor.Instance.Breakpoint(); } private static bool IsDebuggerAttached() { var proc = Processor.Instance; if(proc is Microsoft.Zelig.Runtime.TargetPlatform.ARMv7.ProcessorARMv7M) { return Microsoft.Zelig.Runtime.TargetPlatform.ARMv7.ProcessorARMv7M.IsDebuggerConnected; } return false; } public static void Log( int level, String category, String message ) { BugCheck.Log( "Level: " + level.ToString() + ", Category: " + category + ", message: " + message ); } } } ================================================ FILE: Zelig/Zelig/RunTime/Zelig/Kernel/FrameworkOverrides/Diagnostics/StopwatchImpl.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // namespace Microsoft.Zelig.Runtime { using System; using System.Runtime.CompilerServices; using TS = Microsoft.Zelig.Runtime.TypeSystem; [ExtendClass(typeof(System.Diagnostics.Stopwatch), NoConstructors=true)] public class StopwatchImpl { static uint s_lastCounter; static uint s_highPart; public static bool QueryPerformanceFrequency( out long Frequency ) { Frequency = (long)Peripherals.Instance.GetPerformanceCounterFrequency(); return true; } public static void QueryPerformanceCounter( out long timestamp ) { uint counter = Peripherals.Instance.ReadPerformanceCounter(); if(counter < s_lastCounter) // Detected wrap around. { s_highPart++; } s_lastCounter = counter; timestamp = (long)(MathImpl.InsertHighPart( s_highPart ) + counter); } } } ================================================ FILE: Zelig/Zelig/RunTime/Zelig/Kernel/FrameworkOverrides/EnvironmentImpl.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // namespace Microsoft.Zelig.Runtime { using System; using TS = Microsoft.Zelig.Runtime.TypeSystem; [ExtendClass(typeof(Environment))] internal static class EnvironmentImpl { public static int TickCount { get { return (int)SchedulerTime.Now.Units; } } } } ================================================ FILE: Zelig/Zelig/RunTime/Zelig/Kernel/FrameworkOverrides/GCImpl.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // namespace Microsoft.Zelig.Runtime { using System; using System.Runtime.CompilerServices; using TS = Microsoft.Zelig.Runtime.TypeSystem; [ExtendClass(typeof(System.GC), NoConstructors=true)] public class GCImpl { // // State // // // Constructor Methods // //--// // // Helper Methods // [NoInline] public static void KeepAlive( Object obj ) { // // This is just a method that cannot be inlined, // so you can guarantee that your reference is kept alive up to this method call. // } [NoInline] public static void Collect() { GarbageCollectionManager.Instance.Collect(); } [NoInline] public static long GetTotalMemory( bool forceFullCollection ) { if(forceFullCollection) { Collect(); } return GarbageCollectionManager.Instance.GetTotalMemory(); } [NoInline] public static int CollectionCount( int generation ) { // BUGBUG: Add implementation!!! return 0; } public static void WaitForPendingFinalizers() { Finalizer.WaitForPendingFinalizers(); } public static void SuppressFinalize( Object obj ) { Finalizer.SuppressFinalize( obj ); } public static void ReRegisterForFinalize( Object obj ) { Finalizer.ReRegisterForFinalize( obj ); } // // Access Methods // } } ================================================ FILE: Zelig/Zelig/RunTime/Zelig/Kernel/FrameworkOverrides/Globalization/CompareInfoImpl.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // namespace Microsoft.Zelig.Runtime { using System; using System.Runtime.CompilerServices; using TS = Microsoft.Zelig.Runtime.TypeSystem; [ExtendClass(typeof(System.Globalization.CompareInfo), NoConstructors=true)] public class CompareInfoImpl { // // State // // // Constructor Methods // // // Helper Methods // unsafe private static int IndexOfString( String source, String value, int startIndex, int count, int options ) { // // Most parameter validation on source performed already at the framework level, we can just work on the values here // if(value == null) { throw new ArgumentNullException( ); } if(value == String.Empty) { return startIndex; } int sourceLen = source.Length; int valueLen = value .Length; if(valueLen > sourceLen) { return -1; } // // Cannot find value when there is no longer enough space // int end = Math.Min( startIndex + count, sourceLen - valueLen + 1 ); if(startIndex > end) { return -1; } fixed(char* ptrS = (string)(object)source) fixed(char* ptrV = (string)(object)value) { for(int i = startIndex; i < end; i++) { if(ptrS[i] == ptrV[0]) { bool match = true; for(int j = 1; j < valueLen; j++) { if(ptrS[i + j] != ptrV[j]) { match = false; break; } } if(match) { return i; } } } } return -1; } // // Access Methods // } } ================================================ FILE: Zelig/Zelig/RunTime/Zelig/Kernel/FrameworkOverrides/Globalization/TextInfoImpl.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // namespace Microsoft.Zelig.Runtime { using System; using System.Runtime.CompilerServices; using TS = Microsoft.Zelig.Runtime.TypeSystem; [ExtendClass(typeof(System.Globalization.TextInfo), NoConstructors=true)] public class TextInfoImpl { // // State // // // Constructor Methods // // // Helper Methods // public virtual char ToLower( char c ) { if(c >= 'A' && c <= 'Z') { return (char)(c - 'A' + 'a'); } return c; } public virtual String ToLower( String str ) { if(str == null) { return null; } System.Text.StringBuilder sb = new System.Text.StringBuilder( str.Length ); for( int i = 0; i < str.Length; ++i ) { sb.Append( ToLower( str[ i ] ) ); } return sb.ToString(); } public virtual char ToUpper( char c ) { if(c >= 'a' && c <= 'z') { return (char)(c - 'a' + 'A'); } return c; } public virtual String ToUpper( String str ) { if(str == null) { return null; } System.Text.StringBuilder sb = new System.Text.StringBuilder( str.Length ); for(int i = 0; i < str.Length; ++i ) { sb.Append( ToUpper( str[ i ] ) ); } return sb.ToString(); } // // Access Methods // } } ================================================ FILE: Zelig/Zelig/RunTime/Zelig/Kernel/FrameworkOverrides/MathImpl.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // namespace Microsoft.Zelig.Runtime { using System; using TS = Microsoft.Zelig.Runtime.TypeSystem; [ExtendClass(typeof(Math))] internal static class MathImpl { public static float Abs( float value ) { if(value < 0) return -value; return value; } public static double Abs( double value ) { if(value < 0) return -value; return value; } public static double Exp( double x ) { const double Exp = Math.E; const double ExpHalfFactor = 1.6487212707001281468486507878142; // E^0.5 const double ExpStep6 = 1.0; const double ExpStep5 = ExpStep6 / 2; const double ExpStep4 = ExpStep5 / 3; const double ExpStep3 = ExpStep4 / 4; const double ExpStep2 = ExpStep3 / 5; const double ExpStep1 = ExpStep2 / 6; int sign; // Reduce range to [0.0,1.0] if (x < 0) { x = -x; sign = -1; } else { sign = 1; } double result = 1.0; while(x > 1.0) { x -= 1.0; result *= Exp; } // Reduce range to [0.0,0.5] if (x > 0.5) { x -= 0.5; result *= ExpHalfFactor; } double temp; temp = ExpStep1 * x; temp = (temp + ExpStep2) * x; temp = (temp + ExpStep3) * x; temp = (temp + ExpStep4) * x; temp = (temp + ExpStep5) * x; temp = (temp + ExpStep6) * x; result *= (temp + 1.0); if (sign == -1) { result = 1 / result; } return result; } public static double Log10( double x ) { const double c_Ln10 = 2.3025850929940456840179914546844; const double c_OneOverLn10 = 1.0 / c_Ln10; return Log( x ) * c_OneOverLn10; } public static double Log( double x ) { const double LnTwo = 0.69314718055994530941723212145818; const double LogStep1 = -0.0064535442; const double LogStep2 = 0.0360884937; const double LogStep3 = 0.0953293897; const double LogStep4 = 0.1676540711; const double LogStep5 = 0.2407338084; const double LogStep6 = 0.3317990258; const double LogStep7 = 0.4998741238; const double LogStep8 = 0.9999964239; if(x == 0) { return Double.MinValue; } else if (x < 0) { return 0; } double result = 0; while (x > 2.0) { result += LnTwo; x /= 2; } while (x < 1) { result -= LnTwo; x *= 2; } x -= 1.0; double temp; temp = LogStep1 * x; temp = (temp + LogStep2) * x; temp = (temp - LogStep3) * x; temp = (temp + LogStep4) * x; temp = (temp - LogStep5) * x; temp = (temp + LogStep6) * x; temp = (temp - LogStep7) * x; temp = (temp + LogStep8) * x; result += temp; return result; } public static double Pow( double x , double y ) { return Math.Exp( y * Math.Log( x ) ); } public static double Atan( double x ) { bool fNegate = false; if(x < 0) { x = -x; fNegate = true; } x = x % ( Math.PI * 2 ); if(x > Math.PI) { x -= Math.PI; fNegate = !fNegate; } if(x > ( Math.PI / 2 )) { x = Math.PI - x; } double absX = x; if(fNegate) x = -x; return ( Math.PI / 4.0 ) * x - x * ( absX - 1 ) * ( 0.2447 + 0.0663 * absX ); } public static double Sin( double x ) { bool fNegate = false; if(x < 0) { x = -x; fNegate = true; } x = x % (Math.PI * 2); if(x > Math.PI) { x -= Math.PI; fNegate = !fNegate; } if(x > (Math.PI/2)) { x = Math.PI - x; } double y = x * x; double res; res = - 0.0000000239; res = res * y + 0.0000027526; res = res * y - 0.0001984090; res = res * y + 0.0083333315; res = res * y - 0.1666666664; res = res * y + 1; res = res * x; if(fNegate) { return -res; } else { return res; } } public static double Cos( double x ) { x = Math.Abs( x ); x = x % (Math.PI * 2); bool fNegate = false; if(x > Math.PI) { x -= Math.PI; fNegate = !fNegate; } if(x > (Math.PI/2)) { x = Math.PI - x; fNegate = !fNegate; } double y = x * x; double res; res = - 0.0000002605; res = res * y + 0.0000247609; res = res * y - 0.0013888397; res = res * y + 0.0416666418; res = res * y - 0.4999999963; res = res * y + 1; if(fNegate) { return -res; } else { return res; } } public static double Sqrt( double x ) { if(x < 0) { throw new ArithmeticException(); } if(x == 0) { return 0; } double precision = 0.001; double oldResult = -1; double newResult = 1; while(Math.Abs( newResult - oldResult ) > precision) { oldResult = newResult; newResult = (oldResult * oldResult + x) / (2 * oldResult); } return newResult; } public static double Round( double a ) { return (double)(long)a; } public static double Floor( double a ) { double b = Math.Round( a ); return (b > a) ? b - 1.0 : b; } public static double Ceiling( double a ) { double b = Math.Round( a ); return (b < a) ? b + 1.0 : b; } [Inline] public static uint ExtractHighPart( ulong val ) { return (uint)(val >> 32); } [Inline] public static uint ExtractLowPart( ulong val ) { return (uint)val; } [Inline] public static ulong InsertHighPart( uint val ) { return (ulong)val << 32; } [Inline] public static bool IsPositive( uint val ) { return (int)val >= 0; } [Inline] public static bool IsNegative( uint val ) { return (int)val < 0; } [Inline] public static bool IsPositive( ulong val ) { return (int)ExtractHighPart( val ) >= 0; } [Inline] public static bool IsNegative( ulong val ) { return (int)ExtractHighPart( val ) < 0; } } } ================================================ FILE: Zelig/Zelig/RunTime/Zelig/Kernel/FrameworkOverrides/MulticastDelegateImpl.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // namespace Microsoft.Zelig.Runtime { using System; using TS = Microsoft.Zelig.Runtime.TypeSystem; [ExtendClass(typeof(System.MulticastDelegate))] public class MulticastDelegateImpl : DelegateImpl { // // State // [TS.WellKnownField( "MulticastDelegateImpl_m_invocationList" )] internal DelegateImpl[] m_invocationList; // // Constructor Methods // [MergeWithTargetImplementation] [TS.WellKnownMethod( "MulticastDelegateImpl_MulticastDelegateImpl" )] internal MulticastDelegateImpl( Object target , TS.CodePointer codePtr ) : base( target, codePtr ) { } //--// // equals returns true IIF the delegate is not null and has the // same target, method and invocation list as this object public override bool Equals( Object obj ) { if(obj == null || !InternalEqualTypes( this, obj )) { return false; } MulticastDelegateImpl d = obj as MulticastDelegateImpl; if(d == null) { return false; } if(ArrayUtility.ArrayEquals( m_invocationList, d.m_invocationList ) == false) { return false; } // now we can call on the base return base.Equals( d ); } public override int GetHashCode() { DelegateImpl[] invocationList = m_invocationList; if(invocationList == null) { return base.GetHashCode(); } else { int hash = 0; foreach(DelegateImpl d in invocationList) { hash = hash * 33 + d.GetHashCode(); } return hash; } } //--// // This method will combine this delegate with the passed delegate to form a new delegate. protected override sealed DelegateImpl CombineImpl( DelegateImpl follow ) { MulticastDelegateImpl dFollow = follow as MulticastDelegateImpl; if(dFollow == null) { return this; } DelegateImpl[] thisList = this .m_invocationList; DelegateImpl[] followList = dFollow.m_invocationList; int thisLen = thisList != null ? thisList .Length : 1; int followLen = followList != null ? followList.Length : 1; DelegateImpl[] res = new DelegateImpl[thisLen + followLen]; if(thisList != null) { Array.Copy( thisList, 0, res, 0, thisLen ); } else { res[0] = this; } if(followList != null) { Array.Copy( followList, 0, res, thisLen, followLen ); } else { res[thisLen] = dFollow; } return NewMulticastDelegate( res ); } // This method currently looks backward on the invocation list // for an element that has Delegate based equality with value. (Doesn't // look at the invocation list.) If this is found we remove it from // this list and return a new delegate. If its not found a copy of the // current list is returned. protected override sealed DelegateImpl RemoveImpl( DelegateImpl value ) { DelegateImpl[] invocationList = m_invocationList; if(invocationList == null) { if(this == value) { // // Special case: multicast with only one delegate in it => result is empty; // return null; } } else { for(int i = invocationList.Length; --i >= 0; ) { if(invocationList[i].Equals( value )) { if(invocationList.Length == 2) { // // Special case: multicast with only two delegates in it => result is the other. // return invocationList[1-i]; } DelegateImpl[] res = ArrayUtility.RemoveAtPositionFromNotNullArray( invocationList, i ); return NewMulticastDelegate( res ); } } } return this; } // This method returns the Invocation list of this multicast delegate. public DelegateImpl[] GetInvocationList() { if(m_invocationList != null) { return ArrayUtility.CopyNotNullArray( m_invocationList ); } else { return new DelegateImpl[] { this }; } } protected override Object GetTarget() { DelegateImpl dlg; if(m_invocationList == null) { dlg = this; } else { DelegateImpl[] lst = m_invocationList; dlg = lst[lst.Length - 1]; } return dlg.m_target; } protected override System.Reflection.MethodInfo GetMethodImpl() { DelegateImpl dlg; if(m_invocationList == null) { dlg = this; } else { DelegateImpl[] lst = m_invocationList; dlg = lst[lst.Length - 1]; } return dlg.InnerGetMethod(); } //--// internal MulticastDelegateImpl NewMulticastDelegate( DelegateImpl[] invocationList ) { // First, allocate a new multicast delegate just like this one, i.e. same type as the this object MulticastDelegateImpl result = (MulticastDelegateImpl)this.MemberwiseClone(); result.m_invocationList = invocationList; return result; } } } ================================================ FILE: Zelig/Zelig/RunTime/Zelig/Kernel/FrameworkOverrides/NumberImpl.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // namespace Microsoft.Zelig.Runtime { using System; using TS = Microsoft.Zelig.Runtime.TypeSystem; using System.Globalization; [ExtendClass(typeof(System.Number), NoConstructors = true)] public class NumberImpl { //private string ToString(char fmt, int digits, System.Globalization.NumberFormatInfo info) //{ // throw new NotImplementedException(); //} internal unsafe static Int32 ParseInt32(String s, NumberStyles style, NumberFormatInfo info) { Int32 ret = 0; if (style == NumberStyles.HexNumber) { char[] chars = s.ToCharArray(); int cnt = chars.Length; for (int i = 0; i < cnt; i++) { char c = chars[i]; ret <<= 4; if (c > 'Z') { c -= (char)('a' - 'A'); } if (c >= 'A') { if (c <= 'F') ret += c - 'A'; else throw new ArgumentOutOfRangeException(); } else if (c <= '9' && c >= '0') { ret += c - '0'; } else { throw new ArgumentOutOfRangeException(); } } } else if(style == NumberStyles.Integer) { char[] chars = s.ToCharArray(); int cnt = chars.Length; for (int i = 0; i < cnt; i++) { char c = chars[i]; ret *= 10; if (c <= '9' && c >= '0') { ret += c - '0'; } else { throw new ArgumentOutOfRangeException(); } } } else { throw new NotImplementedException(); } return ret; } } } ================================================ FILE: Zelig/Zelig/RunTime/Zelig/Kernel/FrameworkOverrides/ObjectImpl.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // // Enable this macro to shift object pointers from the beginning of the header to the beginning of the payload. #define CANONICAL_OBJECT_POINTERS namespace Microsoft.Zelig.Runtime { using System; using System.Runtime.CompilerServices; using TS = Microsoft.Zelig.Runtime.TypeSystem; [ExtendClass(typeof(System.Object), NoConstructors=true)] public class ObjectImpl { [AliasForBaseMethod( "Finalize" )] [MethodImpl( MethodImplOptions.InternalCall )] public extern virtual void FinalizeImpl(); [NoInline] public new Type GetType() { return TS.VTable.Get( this ).Type; } protected unsafe new Object MemberwiseClone() { TS.VTable vTable = TS.VTable.Get( this ); object obj = TypeSystemManager.Instance.AllocateObject( vTable ); byte* src = (byte*)GetFieldPointer(); byte* dst = (byte*)((ObjectImpl)obj).GetFieldPointer(); int size = (int)vTable.BaseSize; Buffer.InternalMemoryCopy( src, dst, size ); return obj; } public override bool Equals( Object obj ) { return Object.ReferenceEquals( this, obj ); } public override int GetHashCode() { return SyncBlockTable.GetHashCode( this ); } [Inline] public UIntPtr GetFieldPointer() { #if CANONICAL_OBJECT_POINTERS return ToPointer(); #else // CANONICAL_OBJECT_POINTERS return AddressMath.Increment(ToPointer(), ObjectHeader.HeaderSize); #endif // CANONICAL_OBJECT_POINTERS } [Inline] public static ObjectImpl FromFieldPointer(UIntPtr fieldPointer) { #if CANONICAL_OBJECT_POINTERS return FromPointer(fieldPointer); #else // CANONICAL_OBJECT_POINTERS return FromPointer(AddressMath.Decrement(fieldPointer, ObjectHeader.HeaderSize)); #endif // CANONICAL_OBJECT_POINTERS } [TS.GenerateUnsafeCast] public extern UIntPtr ToPointer(); [TS.GenerateUnsafeCast] public extern static ObjectImpl FromPointer( UIntPtr ptr ); [TS.WellKnownMethod( "Object_NullCheck" )] [MethodImpl( MethodImplOptions.InternalCall )] public extern static void NullCheck( object a ); } } ================================================ FILE: Zelig/Zelig/RunTime/Zelig/Kernel/FrameworkOverrides/Reflection/MemberInfoImpl.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // namespace Microsoft.Zelig.Runtime { using System; using TS = Microsoft.Zelig.Runtime.TypeSystem; [ExtendClass(typeof(System.Reflection.MemberInfo), NoConstructors=true)] public abstract class MemberInfoImpl { // // State // // // Constructor Methods // // // Helper Methods // // // Access Methods // public abstract String Name { get; } public abstract Type DeclaringType { get; } } } ================================================ FILE: Zelig/Zelig/RunTime/Zelig/Kernel/FrameworkOverrides/Reflection/RuntimeFieldHandleImpl.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // namespace Microsoft.Zelig.Runtime { using System; using TS = Microsoft.Zelig.Runtime.TypeSystem; [TS.AllowCompileTimeIntrospection] [ExtendClass(typeof(System.RuntimeFieldHandle), NoConstructors=true)] public struct RuntimeFieldHandleImpl { // // State // [TS.WellKnownField( "RuntimeFieldHandleImpl_m_value" )] internal TS.FieldRepresentation m_value; // // Constructor Methods // internal RuntimeFieldHandleImpl( TS.FieldRepresentation value ) { m_value = value; } //--// // // Helper Methods // public override int GetHashCode() { return m_value.GetHashCode(); } public override bool Equals( object obj ) { if(!(obj is RuntimeFieldHandleImpl)) { return false; } return Equals( (RuntimeFieldHandleImpl)obj ); } public bool Equals( RuntimeFieldHandleImpl handle ) { return this.m_value == handle.m_value; } //--// internal bool IsNullHandle() { return m_value == null; } //--// // // Access Methods // } } ================================================ FILE: Zelig/Zelig/RunTime/Zelig/Kernel/FrameworkOverrides/Reflection/RuntimeMethodHandleImpl.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // namespace Microsoft.Zelig.Runtime { using System; using TS = Microsoft.Zelig.Runtime.TypeSystem; [TS.AllowCompileTimeIntrospection] [ExtendClass(typeof(System.RuntimeMethodHandle), NoConstructors=true)] public unsafe struct RuntimeMethodHandleImpl { // // State // [TS.WellKnownField( "RuntimeMethodHandleImpl_m_value" )] internal TS.MethodRepresentation m_value; // // Constructor Methods // internal RuntimeMethodHandleImpl( TS.MethodRepresentation value ) { m_value = value; } //--// // // Helper Methods // public override int GetHashCode() { return m_value.GetHashCode(); } public override bool Equals( object obj ) { if(!(obj is RuntimeMethodHandleImpl)) { return false; } return Equals( (RuntimeMethodHandleImpl)obj ); } public bool Equals( RuntimeMethodHandleImpl handle ) { return this.m_value == handle.m_value; } //--// internal bool IsNullHandle() { return m_value == null; } //--// // // Access Methods // } } ================================================ FILE: Zelig/Zelig/RunTime/Zelig/Kernel/FrameworkOverrides/Reflection/RuntimeTypeHandleImpl.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // namespace Microsoft.Zelig.Runtime { using System; using TS = Microsoft.Zelig.Runtime.TypeSystem; [TS.AllowCompileTimeIntrospection] [ExtendClass(typeof(System.RuntimeTypeHandle), NoConstructors=true)] public unsafe struct RuntimeTypeHandleImpl { // // State // [TS.WellKnownField( "RuntimeTypeHandleImpl_m_value" )] internal TS.VTable m_value; // // Constructor Methods // internal RuntimeTypeHandleImpl( TS.VTable value ) { m_value = value; } //--// // // Helper Methods // public override int GetHashCode() { return m_value.GetHashCode(); } public override bool Equals( object obj ) { if(!(obj is RuntimeTypeHandleImpl)) { return false; } return Equals( (RuntimeTypeHandleImpl)obj ); } public bool Equals( RuntimeTypeHandleImpl handle ) { return this.m_value == handle.m_value; } //--// internal bool IsNullHandle() { return m_value == null; } //--// // // Access Methods // // // Debug Methods // public override string ToString() { return m_value.ToString(); } } } ================================================ FILE: Zelig/Zelig/RunTime/Zelig/Kernel/FrameworkOverrides/Resources/ResourceManagerImpl.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // namespace Microsoft.Zelig.Runtime { using System; using System.Globalization; using TS = Microsoft.Zelig.Runtime.TypeSystem; [ExtendClass(typeof(System.Resources.ResourceManager), NoConstructors=true)] public class ResourceManagerImpl { // // State // #pragma warning disable 649 [TS.WellKnownField( "ResourceManagerImpl_s_resources" )] static TS.ResourceRepresentation[] s_resources; [AliasForBaseField] internal string BaseNameField; [AliasForBaseField] internal System.Reflection.Assembly MainAssembly; #pragma warning restore 649 // // Helper Methods // [NoInline] [TS.WellKnownMethod( "ResourceManagerImpl_GetString1" )] public virtual String GetString( String name ) { return (string)GetObject( name, (CultureInfo)null, true ); } [NoInline] [TS.WellKnownMethod( "ResourceManagerImpl_GetString2" )] public virtual String GetString( String name , CultureInfo culture ) { return (string)GetObject( name, culture, true ); } [NoInline] [TS.WellKnownMethod( "ResourceManagerImpl_GetObject1" )] public virtual Object GetObject( String name ) { return GetObject( name, (CultureInfo)null, true ); } [NoInline] [TS.WellKnownMethod( "ResourceManagerImpl_GetObject2" )] public virtual Object GetObject( String name , CultureInfo culture ) { return GetObject( name, culture, true ); } internal Object GetObject( String name , CultureInfo culture , bool wrapUnmanagedMemStream ) { foreach(TS.ResourceRepresentation res in s_resources) { if(res.Name == BaseNameField) { if(res.Values != null) { foreach(TS.ResourceRepresentation.Pair pair in res.Values) { if(pair.Key == name) { return pair.Value; } } } } } return null; } } } ================================================ FILE: Zelig/Zelig/RunTime/Zelig/Kernel/FrameworkOverrides/Runtime/CompilerServices/JitHelpersImpl.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // namespace Microsoft.Zelig.Runtime { using System; using TS = Microsoft.Zelig.Runtime.TypeSystem; [ExtendClass(typeof(System.Runtime.CompilerServices.JitHelpers), NoConstructors=true)] internal static class JitHelpersImpl { static internal int UnsafeEnumCast( T val ) where T : struct { return ToInt( val ); } static internal long UnsafeEnumCastLong( T val ) where T : struct { return ToLong( val ); } [TS.GenerateUnsafeCast] static internal extern int ToInt( T val ); [TS.GenerateUnsafeCast] static internal extern long ToLong( T val ); } } ================================================ FILE: Zelig/Zelig/RunTime/Zelig/Kernel/FrameworkOverrides/Runtime/CompilerServices/RuntimeHelpersImpl.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // namespace Microsoft.Zelig.Runtime { using System; using TS = Microsoft.Zelig.Runtime.TypeSystem; [ExtendClass(typeof(System.Runtime.CompilerServices.RuntimeHelpers), NoConstructors=true)] public static class RuntimeHelpersImpl { [TS.WellKnownMethod( "RuntimeHelpers_InitializeArray" )] public static extern void InitializeArray( Array array , RuntimeFieldHandle fldHandle ); [Inline] [TS.WellKnownMethod( "RuntimeHelpers_InitializeArray2" )] private static void InitializeArray2( Array array , Array value ) { Array.Copy( value, array, value.Length ); } // // Access Methods // public static extern int OffsetToStringData { [TS.WellKnownMethod( "RuntimeHelpers_get_OffsetToStringData")] get; } } } ================================================ FILE: Zelig/Zelig/RunTime/Zelig/Kernel/FrameworkOverrides/Runtime/InteropServices/MarshalImpl.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // namespace Microsoft.Zelig.Runtime { using System; using TS = Microsoft.Zelig.Runtime.TypeSystem; [ExtendClass(typeof(System.Runtime.InteropServices.Marshal), NoConstructors=true)] public static class MarshalImpl { [TS.WellKnownMethod( "MarshalImpl_SizeOf__Object" )] public static int SizeOf( Object structure ) { TS.VTable vt = TS.VTable.Get( structure ); return (int)vt.BaseSize; } //[Inline] [TS.WellKnownMethod( "MarshalImpl_SizeOf__Type" )] public static int SizeOf( Type t ) { TS.VTable vt = TS.VTable.GetFromType( t ); return (int)vt.BaseSize; } } } ================================================ FILE: Zelig/Zelig/RunTime/Zelig/Kernel/FrameworkOverrides/RuntimeTypeImpl.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // namespace Microsoft.Zelig.Runtime { using System; using TS = Microsoft.Zelig.Runtime.TypeSystem; [TS.WellKnownType( "Microsoft_Zelig_Runtime_RuntimeTypeImpl" )] [ExtendClass("System_RuntimeType", NoConstructors=true, ProcessAfter=typeof(RuntimeTypeHandleImpl))] public class RuntimeTypeImpl : TypeImpl { // // State // #pragma warning disable 649 [TS.WellKnownField( "RuntimeTypeImpl_m_handle" )] [AliasForBaseField] internal RuntimeTypeHandleImpl m_handle; #pragma warning restore 649 // // Constructor Methods // //--// // // Helper Methods // //--// // // Access Methods // public override System.Reflection.Assembly Assembly { get { return null; } } public override Type BaseType { get { TS.TypeRepresentation baseTd = m_handle.m_value.TypeInfo.Extends; return (baseTd != null) ? baseTd.VirtualTable.Type : null; } } public override String Name { get { TS.TypeRepresentation td = m_handle.m_value.TypeInfo; return td.FullName; } } public override String FullName { get { TS.TypeRepresentation td = m_handle.m_value.TypeInfo; return td.FullName; } } public override String AssemblyQualifiedName { get { //// if(!IsGenericTypeDefinition && ContainsGenericParameters) //// { //// return null; //// } //// return System.Reflection.Assembly.CreateQualifiedName( this.Assembly.FullName, this.FullName ); return this.FullName; } } public override String Namespace { get { TS.TypeRepresentation td = m_handle.m_value.TypeInfo; return td.Namespace; } } public override Type DeclaringType { get { return (Type)(object)this; } } //--// protected override bool IsValueTypeInner { get { return m_handle.m_value.TypeInfo is TS.ValueTypeRepresentation; } } } } ================================================ FILE: Zelig/Zelig/RunTime/Zelig/Kernel/FrameworkOverrides/StringImpl.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // namespace Microsoft.Zelig.Runtime { using System; using System.Runtime.CompilerServices; using TS = Microsoft.Zelig.Runtime.TypeSystem; [ExtendClass(typeof(System.String))] public class StringImpl { // // State // // // Aliasing to mark fields in mscorlib as well-known. // #pragma warning disable 649 [TS.AssumeReferenced] [TS.WellKnownField( "StringImpl_ArrayLength" )] [AliasForBaseField] internal int m_arrayLength; [TS.AssumeReferenced] [TS.WellKnownField( "StringImpl_StringLength" )] [AliasForBaseField] internal int m_stringLength; [TS.AssumeReferenced] [TS.WellKnownField( "StringImpl_FirstChar" )] [AliasForBaseField] internal char m_firstChar; #pragma warning restore 649 // // Constructor Methods // [DiscardTargetImplementation] [TS.WellKnownMethod( "StringImpl_ctor_charArray_int_int" )] public unsafe StringImpl( char[] value , int startIndex , int length ) { //// BCLDebug.Assert( startIndex >= 0 && startIndex <= this.Length , "StartIndex is out of range!" ); //// BCLDebug.Assert( length >= 0 && startIndex <= this.Length - length, "length is out of range!" ); if(length < 0 || length > m_stringLength || startIndex < 0 || (startIndex + length) > value.Length ) { ThreadImpl.ThrowIndexOutOfRangeException(); } if(length > 0) { fixed(char* dest = &this.m_firstChar) { fixed(char* src = &value[startIndex]) { Buffer.InternalMemoryCopy( src, dest, length); } } } } [DiscardTargetImplementation] [TS.WellKnownMethod( "StringImpl_ctor_charArray" )] public StringImpl( char[] value ) : this( value, 0, value.Length ) { } [DiscardTargetImplementation] [TS.WellKnownMethod( "StringImpl_ctor_char_int" )] public unsafe StringImpl( char c , int count ) { if(count < 0 || count > m_stringLength) { ThreadImpl.ThrowIndexOutOfRangeException(); } fixed(char* dest = &this.m_firstChar) { char* ptr = dest; while(--count >= 0) { *ptr++ = c; } } } //--// // // Helper Methods // [TS.WellKnownMethod( "StringImpl_FastAllocateString" )] private static StringImpl FastAllocateString( int length ) { StringImpl res = (StringImpl)(object)TypeSystemManager.Instance.AllocateString( TS.VTable.GetFromType( typeof(string) ), length + 1 ); res.m_stringLength = length; return res; } [TS.WellKnownMethod( "StringImpl_FastAllocateReferenceCountingString" )] [TS.DisableAutomaticReferenceCounting] private static StringImpl FastAllocateReferenceCountingString( int length ) { StringImpl res = (StringImpl)(object)TypeSystemManager.Instance.AllocateReferenceCountingString( TS.VTable.GetFromType( typeof( string ) ), length + 1 ); res.m_stringLength = length; return res; } // // Aliasing to mark methods in mscorlib as well-known. // public unsafe int LastIndexOf( char value, int startIndex, int count ) { int retVal = -1; if(m_stringLength == 0 ) return -1; if(startIndex < 0 ) throw new ArgumentOutOfRangeException(); if(count < 0 ) throw new ArgumentOutOfRangeException(); if(startIndex >= m_stringLength) throw new ArgumentOutOfRangeException(); if(count > startIndex + 1) throw new ArgumentOutOfRangeException(); int end = startIndex - count + 1; fixed(char* ptr = (string)(object)this) { for(int index = startIndex; index >= end; index--) { if(ptr[index] == value) { retVal = index; break; } } } return retVal; } public unsafe int IndexOf( char value, int startIndex, int count ) { int retVal = -1; if(m_stringLength == 0 ) return -1; if(startIndex < 0 ) throw new ArgumentOutOfRangeException(); if(count < 0 ) throw new ArgumentOutOfRangeException(); if(startIndex + count > m_stringLength) throw new ArgumentOutOfRangeException(); int end = count + startIndex; fixed(char* ptr = (string)(object)this) { for(int index = startIndex; index < end; index++) { if(ptr[index] == value) { retVal = index; break; } } } return retVal; } public unsafe int IndexOfAny( char[] anyOf, int startIndex, int count ) { if(startIndex + count > m_stringLength) throw new IndexOutOfRangeException(); UInt64[] mask = new UInt64[2]; char minC = char.MaxValue, maxC = char.MinValue; int minIdx = startIndex, maxIdx = startIndex + count - 1; int cAny = anyOf.Length; for(int i = cAny; --i >= 0; ) { char c = anyOf[i]; if(c < minC) minC = c; if(c > maxC) maxC = c; if(c < 128) { if(c < 64) mask[0] |= 1ul << c; else mask[1] |= 1ul << ( c - 64 ); } } fixed(char* pS = (string)(object)this) { count += startIndex; for(int i = startIndex; i < count; i++) { char c = pS[i]; if(c == minC) return i; if(c == maxC) return i; if(c > minC && c < maxC) { if(c < 128) { if(c < 64) { if(0 != ( mask[0] & 1ul << c )) return i; } else { if(0 != ( mask[1] & 1ul << ( c - 64 ) )) return i; } } else { for(int j = cAny; --j >= 0; ) { if(c == anyOf[j]) { return i + startIndex; } } } } } } return -1; } // // This is used to cast between an object and and ArrayImpl, which is not possible in C#. // [TS.GenerateUnsafeCast] internal extern static StringImpl CastAsString( object target ); // // This is used to cast between an object and and ArrayImpl, which is not possible in C#. // [TS.GenerateUnsafeCast] internal extern String CastThisAsString(); [Inline] internal unsafe char* GetDataPointer( ) { fixed (char* ptr = &m_firstChar) { return ptr; } } //--// // // Access Methods // [System.Runtime.CompilerServices.IndexerName( "Chars" )] public unsafe char this[int index] { get { if(index >= 0 && index < m_stringLength) { fixed(char* ptr = (string)(object)this) { return ptr[index]; } } throw new IndexOutOfRangeException(); } } } } ================================================ FILE: Zelig/Zelig/RunTime/Zelig/Kernel/FrameworkOverrides/Threading/EventWaitHandleImpl.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // namespace Microsoft.Zelig.Runtime { using System; using System.Runtime.CompilerServices; using TS = Microsoft.Zelig.Runtime.TypeSystem; [ExtendClass(typeof(System.Threading.EventWaitHandle))] public class EventWaitHandleImpl : WaitHandleImpl { protected sealed class EventWaitableObject : Synchronization.WaitableObject { // // State // private EventWaitHandleImpl m_owner; // // Constructor Methods // internal EventWaitableObject(EventWaitHandleImpl owner) { m_owner = owner; } // // Helper Methods // public override bool Acquire(SchedulerTime timeout) { ThreadImpl thisThread = ThreadImpl.CurrentThread; BugCheck.Assert(thisThread != null, BugCheck.StopCode.NoCurrentThread); // // Let's try to shortcut the acquisition of the event. // if (m_owner.m_state) { using (SmartHandles.InterruptState.Disable()) { if (m_owner.m_state) { if (m_owner.m_mode == System.Threading.EventResetMode.AutoReset) { m_owner.m_state = false; } return true; } } } using (Synchronization.WaitingRecord.Holder holder = Synchronization.WaitingRecord.Holder.Get(thisThread, this, timeout)) { while (true) { using (SmartHandles.InterruptState.Disable()) { if (holder.ShouldTryToAcquire) { if (m_owner.m_state) { if (m_owner.m_mode == System.Threading.EventResetMode.AutoReset) { m_owner.m_state = false; } return true; } } } if (holder.RequestProcessed) { return holder.RequestFulfilled; } } } } public override void Release() { while (true) { ThreadImpl wakeUpThread; using (SmartHandles.InterruptState.Disable()) { if (m_owner.m_state == false) { return; } Synchronization.WaitingRecord wr = m_listWaiting.FirstTarget(); if (wr == null) { return; } wakeUpThread = wr.Source; wr.RequestFulfilled = true; if (m_owner.m_mode == System.Threading.EventResetMode.AutoReset) { m_owner.m_state = false; } } wakeUpThread.Wakeup(); } } // // Access Methods // } // // State // internal bool m_state; internal System.Threading.EventResetMode m_mode; // // Constructor Methods // [DiscardTargetImplementation] public EventWaitHandleImpl(bool initialState, System.Threading.EventResetMode mode) { m_state = initialState; m_mode = mode; //--// m_handle = new EventWaitableObject(this); } // // Helper Methods // public bool Reset() { m_state = false; return true; } public bool Set() { m_state = true; m_handle.Release(); return true; } } } ================================================ FILE: Zelig/Zelig/RunTime/Zelig/Kernel/FrameworkOverrides/Threading/InterlockedImpl.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // #define USE_LLVM_INTRINSICS namespace Microsoft.Zelig.Runtime { using System; using System.Runtime.CompilerServices; using TS = Microsoft.Zelig.Runtime.TypeSystem; using ISA = TargetModel.ArmProcessor.InstructionSetVersion; [ExtendClass(typeof(System.Threading.Interlocked), NoConstructors=true, PlatformVersionFilter=(ISA.Platform_Version__ARMv7_all | ISA.Platform_Version__x86))] public static class InterlockedImpl { // // Helper Methods // public static int Increment( ref int location ) { return InternalAdd( ref location, 1 ); } public static long Increment( ref long location ) { using(SmartHandles.InterruptState.DisableAll()) { return ++location; } } public static int Decrement( ref int location ) { return InternalAdd( ref location, -1 ); } public static long Decrement( ref long location ) { using(SmartHandles.InterruptState.DisableAll()) { return --location; } } public static int Exchange( ref int location1 , int value ) { return InternalExchange( ref location1, value ); } public static long Exchange( ref long location1 , long value ) { using(SmartHandles.InterruptState.DisableAll()) { long oldValue = location1; location1 = value; return oldValue; } } public static float Exchange( ref float location1 , float value ) { return InternalExchange( ref location1, value ); } public static double Exchange( ref double location1 , double value ) { using(SmartHandles.InterruptState.DisableAll()) { double oldValue = location1; location1 = value; return oldValue; } } public static Object Exchange( ref Object location1 , Object value ) { return InternalExchange( ref location1, value ); } public static IntPtr Exchange( ref IntPtr location1, IntPtr value ) { return InternalExchange( ref location1, value ); } public static T Exchange( ref T location1 , T value ) where T : class { return InternalExchange( ref location1, value ); } //--// public static int CompareExchange( ref int location1 , int value , int comparand ) { return InternalCompareExchange( ref location1, value, comparand ); } public static long CompareExchange( ref long location1 , long value , long comparand ) { using(SmartHandles.InterruptState.DisableAll()) { long oldValue = location1; if(oldValue == comparand) { location1 = value; } return oldValue; } } public static float CompareExchange( ref float location1 , float value , float comparand ) { return InternalCompareExchange( ref location1, value, comparand ); } public static double CompareExchange( ref double location1 , double value , double comparand ) { using(SmartHandles.InterruptState.DisableAll()) { double oldValue = location1; if(oldValue == comparand) { location1 = value; } return oldValue; } } public static Object CompareExchange( ref Object location1 , Object value , Object comparand ) { return InternalCompareExchange( ref location1, value, comparand ); } public static IntPtr CompareExchange( ref IntPtr location1 , IntPtr value , IntPtr comparand ) { return InternalCompareExchange( ref location1, value, comparand ); } public static T CompareExchange( ref T location1 , T value , T comparand ) where T : class { return InternalCompareExchange( ref location1, value, comparand ); } public static int Add( ref int location1 , int value ) { return InternalAdd( ref location1, value ); } public static long Add( ref long location1 , long value ) { using(SmartHandles.InterruptState.DisableAll()) { long res = location1 + value; location1 = res; return res; } } //--// #if USE_LLVM_INTRINSICS [NoInline] // Disable inlining so we always have a chance to replace the method. #else [Inline] #endif [TS.WellKnownMethod( "InterlockedImpl_InternalExchange_int" )] internal static int InternalExchange( ref int location1, int value ) { #if USE_LLVM_INTRINSICS BugCheck.Assert( false, BugCheck.StopCode.InvalidOperation ); return 0; #else using(SmartHandles.InterruptState.DisableAll( )) { int oldValue = location1; location1 = value; return oldValue; } #endif } #if USE_LLVM_INTRINSICS [NoInline] // Disable inlining so we always have a chance to replace the method. #else [Inline] #endif [TS.WellKnownMethod( "InterlockedImpl_InternalExchange_float" )] internal static float InternalExchange( ref float location1, float value ) { #if USE_LLVM_INTRINSICS BugCheck.Assert( false, BugCheck.StopCode.InvalidOperation ); return 0.0f; #else using(SmartHandles.InterruptState.DisableAll( )) { float oldValue = location1; location1 = value; return oldValue; } #endif } #if USE_LLVM_INTRINSICS [NoInline] // Disable inlining so we always have a chance to replace the method. #else [Inline] #endif [TS.WellKnownMethod( "InterlockedImpl_InternalExchange_IntPtr" )] internal static IntPtr InternalExchange( ref IntPtr location1, IntPtr value ) { #if USE_LLVM_INTRINSICS BugCheck.Assert( false, BugCheck.StopCode.InvalidOperation ); return IntPtr.Zero; #else using(SmartHandles.InterruptState.DisableAll( )) { IntPtr oldValue = location1; location1 = value; return oldValue; } #endif } #if USE_LLVM_INTRINSICS [NoInline] // Disable inlining so we always have a chance to replace the method. #else [Inline] #endif [TS.WellKnownMethod( "InterlockedImpl_InternalExchange_Template" )] [TS.DisableAutomaticReferenceCounting] internal static T InternalExchange( ref T location1, T value ) where T : class { #if USE_LLVM_INTRINSICS BugCheck.Assert( false, BugCheck.StopCode.InvalidOperation ); return null; #else using(SmartHandles.InterruptState.DisableAll( )) { T oldValue = location1; location1 = value; return oldValue; } #endif } #if USE_LLVM_INTRINSICS [NoInline] // Disable inlining so we always have a chance to replace the method. #else [Inline] #endif [TS.WellKnownMethod( "InterlockedImpl_InternalCompareExchange_int" )] internal static int InternalCompareExchange( ref int location1, int value, int comparand ) { #if USE_LLVM_INTRINSICS BugCheck.Assert( false, BugCheck.StopCode.InvalidOperation ); return 0; #else using(SmartHandles.InterruptState.DisableAll( )) { int oldValue = location1; if(oldValue == comparand) { location1 = value; } return oldValue; } #endif } #if USE_LLVM_INTRINSICS [NoInline] // Disable inlining so we always have a chance to replace the method. #else [Inline] #endif [TS.WellKnownMethod( "InterlockedImpl_InternalCompareExchange_float" )] internal static float InternalCompareExchange( ref float location1, float value, float comparand ) { #if USE_LLVM_INTRINSICS BugCheck.Assert( false, BugCheck.StopCode.InvalidOperation ); return 0.0f; #else using(SmartHandles.InterruptState.DisableAll( )) { float oldValue = location1; if(oldValue == comparand) { location1 = value; } return oldValue; } #endif } #if USE_LLVM_INTRINSICS [NoInline] // Disable inlining so we always have a chance to replace the method. #else [Inline] #endif [TS.WellKnownMethod( "InterlockedImpl_InternalCompareExchange_IntPtr" )] internal static IntPtr InternalCompareExchange( ref IntPtr location1, IntPtr value, IntPtr comparand ) { #if USE_LLVM_INTRINSICS BugCheck.Assert( false, BugCheck.StopCode.InvalidOperation ); return IntPtr.Zero; #else using(SmartHandles.InterruptState.DisableAll( )) { IntPtr oldValue = location1; if(oldValue == comparand) { location1 = value; } return oldValue; } #endif } #if USE_LLVM_INTRINSICS [NoInline] // Disable inlining so we always have a chance to replace the method. #else [Inline] #endif [TS.WellKnownMethod( "InterlockedImpl_InternalCompareExchange_Template" )] [TS.DisableAutomaticReferenceCounting] internal static T InternalCompareExchange( ref T location1, T value, T comparand ) where T : class { #if USE_LLVM_INTRINSICS BugCheck.Assert( false, BugCheck.StopCode.InvalidOperation ); return null; #else using(SmartHandles.InterruptState.DisableAll( )) { T oldValue = location1; if(Object.ReferenceEquals( oldValue, comparand )) { location1 = value; } return oldValue; } #endif } #if USE_LLVM_INTRINSICS [NoInline] // Disable inlining so we always have a chance to replace the method. #else [Inline] #endif [TS.WellKnownMethod( "InterlockedImpl_InternalAdd_int" )] internal static int InternalAdd( ref int location1, int value ) { #if USE_LLVM_INTRINSICS BugCheck.Assert( false, BugCheck.StopCode.InvalidOperation ); return 0; #else using(SmartHandles.InterruptState.DisableAll( )) { int res = location1 + value; location1 = res; return res; } #endif } } } ================================================ FILE: Zelig/Zelig/RunTime/Zelig/Kernel/FrameworkOverrides/Threading/InterlockedImpl_ARMv6M.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // namespace Microsoft.Zelig.Runtime { using System; using System.Runtime.CompilerServices; using TS = Microsoft.Zelig.Runtime.TypeSystem; using ISA = TargetModel.ArmProcessor.InstructionSetVersion; [ExtendClass(typeof(System.Threading.Interlocked), NoConstructors=true, PlatformVersionFilter=(ISA.Platform_Version__ARMv6M | ISA.Platform_Version__ARM_legacy))] public static class InterlockedImpl_ARMv6M { // // Helper Methods // public static int Increment( ref int location ) { return InternalAdd( ref location, 1 ); } public static long Increment( ref long location ) { using(SmartHandles.InterruptState.DisableAll()) { return ++location; } } public static int Decrement( ref int location ) { return InternalAdd( ref location, -1 ); } public static long Decrement( ref long location ) { using(SmartHandles.InterruptState.DisableAll()) { return --location; } } public static int Exchange( ref int location1 , int value ) { return InternalExchange( ref location1, value ); } public static long Exchange( ref long location1 , long value ) { using(SmartHandles.InterruptState.DisableAll()) { long oldValue = location1; location1 = value; return oldValue; } } public static float Exchange( ref float location1 , float value ) { return InternalExchange( ref location1, value ); } public static double Exchange( ref double location1 , double value ) { using(SmartHandles.InterruptState.DisableAll()) { double oldValue = location1; location1 = value; return oldValue; } } public static Object Exchange( ref Object location1 , Object value ) { return InternalExchange( ref location1, value ); } public static IntPtr Exchange( ref IntPtr location1, IntPtr value ) { return InternalExchange( ref location1, value ); } public static T Exchange( ref T location1 , T value ) where T : class { return InternalExchange( ref location1, value ); } //--// public static int CompareExchange( ref int location1 , int value , int comparand ) { return InternalCompareExchange( ref location1, value, comparand ); } public static long CompareExchange( ref long location1 , long value , long comparand ) { using(SmartHandles.InterruptState.DisableAll()) { long oldValue = location1; if(oldValue == comparand) { location1 = value; } return oldValue; } } public static float CompareExchange( ref float location1 , float value , float comparand ) { return InternalCompareExchange( ref location1, value, comparand ); } public static double CompareExchange( ref double location1 , double value , double comparand ) { using(SmartHandles.InterruptState.DisableAll()) { double oldValue = location1; if(oldValue == comparand) { location1 = value; } return oldValue; } } public static Object CompareExchange( ref Object location1 , Object value , Object comparand ) { return InternalCompareExchange( ref location1, value, comparand ); } public static IntPtr CompareExchange( ref IntPtr location1 , IntPtr value , IntPtr comparand ) { return InternalCompareExchange( ref location1, value, comparand ); } public static T CompareExchange( ref T location1 , T value , T comparand ) where T : class { return InternalCompareExchange( ref location1, value, comparand ); } public static int Add( ref int location1 , int value ) { return InternalAdd( ref location1, value ); } public static long Add( ref long location1 , long value ) { using(SmartHandles.InterruptState.DisableAll()) { long res = location1 + value; location1 = res; return res; } } //--// [Inline] [TS.WellKnownMethod( "InterlockedImpl_InternalExchange_int" )] internal static int InternalExchange( ref int location1, int value ) { using(SmartHandles.InterruptState.DisableAll( )) { int oldValue = location1; location1 = value; return oldValue; } } [Inline] [TS.WellKnownMethod( "InterlockedImpl_InternalExchange_float" )] internal static float InternalExchange( ref float location1, float value ) { using(SmartHandles.InterruptState.DisableAll( )) { float oldValue = location1; location1 = value; return oldValue; } } [Inline] [TS.WellKnownMethod( "InterlockedImpl_InternalExchange_IntPtr" )] internal static IntPtr InternalExchange( ref IntPtr location1, IntPtr value ) { using(SmartHandles.InterruptState.DisableAll( )) { IntPtr oldValue = location1; location1 = value; return oldValue; } } [Inline] [TS.WellKnownMethod( "InterlockedImpl_InternalExchange_Template" )] [TS.DisableAutomaticReferenceCounting] internal static T InternalExchange( ref T location1, T value ) where T : class { using(SmartHandles.InterruptState.DisableAll( )) { T oldValue = location1; location1 = value; return oldValue; } } [Inline] [TS.WellKnownMethod( "InterlockedImpl_InternalCompareExchange_int" )] internal static int InternalCompareExchange( ref int location1, int value, int comparand ) { using(SmartHandles.InterruptState.DisableAll( )) { int oldValue = location1; if(oldValue == comparand) { location1 = value; } return oldValue; } } [Inline] [TS.WellKnownMethod( "InterlockedImpl_InternalCompareExchange_float" )] internal static float InternalCompareExchange( ref float location1, float value, float comparand ) { using(SmartHandles.InterruptState.DisableAll( )) { float oldValue = location1; if(oldValue == comparand) { location1 = value; } return oldValue; } } [Inline] [TS.WellKnownMethod( "InterlockedImpl_InternalCompareExchange_IntPtr" )] internal static IntPtr InternalCompareExchange( ref IntPtr location1, IntPtr value, IntPtr comparand ) { using(SmartHandles.InterruptState.DisableAll( )) { IntPtr oldValue = location1; if(oldValue == comparand) { location1 = value; } return oldValue; } } [Inline] [TS.WellKnownMethod( "InterlockedImpl_InternalCompareExchange_Template" )] [TS.DisableAutomaticReferenceCounting] internal static T InternalCompareExchange( ref T location1, T value, T comparand ) where T : class { using(SmartHandles.InterruptState.DisableAll( )) { T oldValue = location1; if(Object.ReferenceEquals( oldValue, comparand )) { location1 = value; } return oldValue; } } [Inline] [TS.WellKnownMethod( "InterlockedImpl_InternalAdd_int" )] internal static int InternalAdd( ref int location1, int value ) { using(SmartHandles.InterruptState.DisableAll( )) { int res = location1 + value; location1 = res; return res; } } } } ================================================ FILE: Zelig/Zelig/RunTime/Zelig/Kernel/FrameworkOverrides/Threading/MonitorImpl.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // namespace Microsoft.Zelig.Runtime { using System; using System.Threading; using System.Runtime.CompilerServices; using TS = Microsoft.Zelig.Runtime.TypeSystem; [ExtendClass(typeof(System.Threading.Monitor))] public static class MonitorImpl { // // Helper Methods // [NoInline] public static void Enter( Object obj ) { SyncBlockTable.GetLock( obj ).Acquire(); } [NoInline] public static void Exit( Object obj ) { SyncBlockTable.GetLock( obj ).Release(); } [NoInline] private static bool TryEnterTimeout( Object obj , int millisecondsTimeout ) { return SyncBlockTable.GetLock( obj ).Acquire( (SchedulerTime)millisecondsTimeout ); } [NoInline] private static bool ObjWait( bool exitContext , int millisecondsTimeout , Object obj ) { throw new NotImplementedException(); } [NoInline] private static void ObjPulse( Object obj ) { throw new NotImplementedException(); } [NoInline] private static void ObjPulseAll( Object obj ) { throw new NotImplementedException(); } } } ================================================ FILE: Zelig/Zelig/RunTime/Zelig/Kernel/FrameworkOverrides/Threading/ThreadImpl.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // namespace Microsoft.Zelig.Runtime { using System; using System.Threading; using System.Runtime.CompilerServices; using TS = Microsoft.Zelig.Runtime.TypeSystem; //[ExtendClass(typeof(System.Threading.Thread), PlatformFilter = "ARM")] [ExtendClass(typeof(System.Threading.Thread))] public class ThreadImpl { // // State // [TS.WellKnownField( "ThreadImpl_s_currentThread" )] private static ThreadImpl s_currentThread; private static int s_managedThreadId; //--// private int m_managedThreadId; private bool m_fBackground; [TS.WellKnownField( "ThreadImpl_m_currentException" )] private Exception m_currentException; private ThreadPriority m_priority; private readonly ThreadStart m_start; private uint[] m_stack; private readonly Processor.Context m_swappedOutContext; private readonly Processor.Context m_throwContext; private volatile ThreadState m_state; private readonly KernelNode< ThreadImpl > m_registrationLink; private readonly KernelNode< ThreadImpl > m_schedulingLink; private ManualResetEvent m_joinEvent; private readonly KernelList< Synchronization.WaitableObject > m_ownedObjects; private readonly KernelList< Synchronization.WaitingRecord > m_pendingObjects; private KernelPerformanceCounter m_activeTime; private ReleaseReferenceHelper m_releaseReferenceHelper; // // HACK: We have a bug in the liveness of multi-pointer structure. We have to use a class instead. // internal Synchronization.WaitingRecord.Holder m_holder; // // Constructor Methods // [DiscardTargetImplementation] public ThreadImpl( System.Threading.ThreadStart start ) : this( start, new uint[ ThreadManager.Instance.DefaultStackSize / sizeof( uint ) ] ) // move to configuration?? { } [TS.WellKnownMethod( "ThreadImpl_ctor" )] [DiscardTargetImplementation] public ThreadImpl( System.Threading.ThreadStart start , uint[] stack ) { m_holder = new Synchronization.WaitingRecord.Holder(); m_managedThreadId = (int)0x12340000 | Interlocked.Increment( ref s_managedThreadId ); m_start = start; m_stack = stack; m_swappedOutContext = Processor.Instance.AllocateProcessorContext(this); m_throwContext = Processor.Instance.AllocateProcessorContext(this); m_state = ThreadState.Unstarted; m_registrationLink = new KernelNode< ThreadImpl >( this ); m_schedulingLink = new KernelNode< ThreadImpl >( this ); m_ownedObjects = new KernelList< Synchronization.WaitableObject >(); m_pendingObjects = new KernelList< Synchronization.WaitingRecord >(); m_priority = ThreadPriority.Normal; ThreadStart entrypoint = Entrypoint; m_swappedOutContext.PopulateFromDelegate( entrypoint, m_stack ); #if DEBUG_CTX_SWITCH unsafe { BugCheck.Log( "Thread 0x%x, ctx 0x%x: stack 0x%x (0x%x -> 0x%x)", (int)ObjectHeader.Unpack( this ).ToPointer( ), (int)ObjectHeader.Unpack( m_swappedOutContext ).ToPointer( ), (int)m_swappedOutContext.StackPointer, (int)ArrayImpl.CastAsArray( stack ).GetDataPointer( ), (int)m_swappedOutContext.BaseStackPointer ); } #endif } [TS.WellKnownMethod( "ThreadImpl_AllocateReleaseReferenceHelper" )] private void AllocateReleaseReferenceHelper() { m_releaseReferenceHelper = new ReleaseReferenceHelper( ); } internal enum BootstrapThread { BootstrapThread } [TS.DisableAutomaticReferenceCounting] [DiscardTargetImplementation] internal ThreadImpl(BootstrapThread bst) { if (bst == BootstrapThread.BootstrapThread) { m_releaseReferenceHelper = new ReleaseReferenceHelper(0, 0); } } //--// // // Helper Methods // public void Start() { if((m_state & ThreadState.Unstarted) == 0) { #if EXCEPTION_STRINGS throw new ThreadStateException( "Thread already started" ); #else throw new ThreadStateException(); #endif } m_state &= ~ThreadState.Unstarted; ThreadManager.Instance.AddThread( this ); } public void Join() { Join( Timeout.Infinite ); } public bool Join( int timeout ) { return Join( TimeSpan.FromMilliseconds( timeout ) ); } public bool Join( TimeSpan timeout ) { if((m_state & ThreadState.Unstarted) != 0) { #if EXCEPTION_STRINGS throw new ThreadStateException( "Thread not started" ); #else throw new ThreadStateException(); #endif } if((m_state & ThreadState.Stopped) != 0) { return true; } ManualResetEvent joinEvent = m_joinEvent; if(joinEvent == null) { joinEvent = new ManualResetEvent( false ); ManualResetEvent joinEventOld = Interlocked.CompareExchange( ref m_joinEvent, joinEvent, null ); if(joinEventOld != null) { joinEvent = joinEventOld; } } // // Recheck after the creation of the event, in case of a race condition. // if((m_state & ThreadState.Stopped) != 0) { return true; } return joinEvent.WaitOne( timeout, false ); } public static void Sleep( int millisecondsTimeout ) { ThreadManager.Instance.Sleep( (SchedulerTime)millisecondsTimeout ); } public static void Sleep( TimeSpan timeout ) { ThreadManager.Instance.Sleep( (SchedulerTime)timeout ); } public static void BeginCriticalRegion() { } public static void EndCriticalRegion() { } //--// public void SetupForExceptionHandling( uint mode ) { m_swappedOutContext.SetupForExceptionHandling( mode ); } // TODO: Find out a better implementation of this attribute. It seems to corrupt the registers for class member functions // (in debug builds especially). // [BottomOfCallStack()] private void Entrypoint() { try { m_start(); } catch { } m_state |= ThreadState.StopRequested; ThreadManager.Instance.RemoveThread( this ); } //--// public void ReleasedProcessor() { BugCheck.AssertInterruptsOff(); m_activeTime.Stop(); if((m_state & ThreadState.StopRequested) != 0) { Stop(); } } public void AcquiredProcessor() { BugCheck.AssertInterruptsOff(); m_activeTime.Start(); } //--// public void Yield() { ThreadManager.Instance.Yield(); } public void RegisterWait( KernelNode< Synchronization.WaitingRecord > node ) { BugCheck.AssertInterruptsOff(); SchedulerTime timeout = node.Target.Timeout; if(timeout == SchedulerTime.MaxValue) { // // No timeout, add at end. // m_pendingObjects.InsertAtTail( node ); } else { // // Insert in order. // KernelNode< Synchronization.WaitingRecord > node2 = m_pendingObjects.StartOfForwardWalk; bool fInvalidateTimer = true; while(node2.IsValidForForwardMove) { if(node2.Target.Timeout > timeout) { break; } node2 = node2.Next; fInvalidateTimer = false; } node.InsertBefore(node2); if(fInvalidateTimer) { ThreadManager.Instance.InvalidateNextWaitTimer(); } } } public void UnregisterWait( KernelNode< Synchronization.WaitingRecord > node ) { BugCheck.AssertInterruptsOff(); node.RemoveFromList(); SchedulerTime timeout = node.Target.Timeout; if(timeout != SchedulerTime.MaxValue) { ThreadManager.Instance.InvalidateNextWaitTimer(); } } public SchedulerTime GetFirstTimeout() { BugCheck.AssertInterruptsOff(); Synchronization.WaitingRecord wr = m_pendingObjects.FirstTarget(); return wr != null ? wr.Timeout : SchedulerTime.MaxValue; } public void ProcessWaitExpiration( SchedulerTime currentTime ) { BugCheck.AssertInterruptsOff(); KernelNode< Synchronization.WaitingRecord > node = m_pendingObjects.StartOfForwardWalk; bool fWakeup = false; while(node.IsValidForForwardMove) { Synchronization.WaitingRecord wr = node.Target; // // The items are kept sorted, so we can stop at the first failure. // if(wr.Timeout > currentTime) { break; } else { KernelNode< Synchronization.WaitingRecord > nodeNext = node.Next; wr.RequestFulfilled = false; fWakeup = true; node = nodeNext; } } if(fWakeup) { Wakeup(); } } public void Wakeup() { ThreadManager.Instance.Wakeup( this ); } //--// public void AcquiredWaitableObject( Synchronization.WaitableObject waitableObject ) { using(SmartHandles.InterruptState.Disable()) { m_ownedObjects.InsertAtTail( waitableObject.OwnershipLink ); } } public void ReleasedWaitableObject( Synchronization.WaitableObject waitableObject ) { using(SmartHandles.InterruptState.Disable()) { waitableObject.OwnershipLink.RemoveFromList(); } } //--// public void Stop() { ThreadManager.Instance.RetireThread( this ); m_state |= ThreadState.Stopped; if(m_joinEvent != null) { m_joinEvent.Set(); } } public void Detach() { using(SmartHandles.InterruptState.Disable()) { while(true) { Synchronization.WaitingRecord wr = m_pendingObjects.FirstTarget(); if(wr == null) { break; } wr.RequestFulfilled = false; } while(true) { Synchronization.WaitableObject wo = m_ownedObjects.FirstTarget(); if(wo == null) { break; } wo.Release(); } m_schedulingLink .RemoveFromList(); m_registrationLink.RemoveFromList(); } } //--// public bool IsAtSafePoint( Processor.Context ctx ) { if(m_start == null) { // // Interrupt threads don't have an entry point. They are always at a safe point with regard to the garbage collector. // return true; } if((m_state & ThreadState.Unstarted) != 0) { return true; } if((m_state & ThreadState.StopRequested) != 0) { return false; } ctx.Populate( this.SwappedOutContext ); while(true) { TS.CodeMap cm = TS.CodeMap.ResolveAddressToCodeMap( ctx.ProgramCounter ); BugCheck.Assert( cm != null, BugCheck.StopCode.UnwindFailure ); // // TODO: Check to see if the method is marked as a NoGC one. // if(ctx.Unwind() == false) { return true; } } } //--// [Inline] public static SmartHandles.SwapCurrentThread SwapCurrentThread( ThreadImpl newThread ) { return new SmartHandles.SwapCurrentThread( newThread ); } [Inline] public static SmartHandles.SwapCurrentThreadUnderInterrupt SwapCurrentThreadUnderInterrupt( ThreadImpl newThread ) { return new SmartHandles.SwapCurrentThreadUnderInterrupt( newThread ); } //--// [NoInline] [TS.WellKnownMethod( "ThreadImpl_GetCurrentException" )] public static Exception GetCurrentException() { return ThreadImpl.CurrentThread.CurrentException; } //--// [NoInline] [NoReturn] [TS.WellKnownMethod( "ThreadImpl_ThrowNullException" )] internal static void ThrowNullException() { throw new NullReferenceException(); } [NoInline] [NoReturn] [TS.WellKnownMethod( "ThreadImpl_ThrowIndexOutOfRangeException" )] internal static void ThrowIndexOutOfRangeException() { throw new IndexOutOfRangeException(); } [NoInline] [NoReturn] [TS.WellKnownMethod( "ThreadImpl_ThrowOverflowException" )] internal static void ThrowOverflowException() { throw new OverflowException(); } [NoInline] [NoReturn] [TS.WellKnownMethod( "ThreadImpl_ThrowNotImplementedException" )] internal static void ThrowNotImplementedException() { throw new NotImplementedException(); } //--// // // Access Methods // public int ManagedThreadId { get { return m_managedThreadId; } } public bool IsBackground { get { return m_fBackground; } set { m_fBackground = value; } } public ThreadPriority Priority { get { return m_priority; } set { m_priority = value; } } public bool IsAlive { get { if((m_state & ThreadState.Unstarted) != 0) { return false; } if((m_state & ThreadState.Stopped) != 0) { return false; } return true; } } public Processor.Context SwappedOutContext { get { return m_swappedOutContext; } } public Processor.Context ThrowContext { get { return m_throwContext; } } public KernelNode< ThreadImpl > RegistrationLink { get { return m_registrationLink; } } public KernelNode< ThreadImpl > SchedulingLink { get { return m_schedulingLink; } } public ThreadState State { get { return m_state; } set { m_state = value; } } public bool IsWaiting { [Inline] get { return (m_state & ThreadState.WaitSleepJoin) != 0; } } public Exception CurrentException { get { return m_currentException; } set { m_currentException = value; } } public KernelPerformanceCounter ActiveTime { get { return m_activeTime; } } public ReleaseReferenceHelper ReleaseReference { [Inline] get { return m_releaseReferenceHelper; } } public static ThreadImpl CurrentThread { [Inline] [TS.WellKnownMethod( "ThreadImpl_get_CurrentThread" )] get { ThreadImpl curThread = ThreadManager.Instance.CurrentThread; if(curThread != null) { return curThread; } else { return s_currentThread; } } [Inline] set { s_currentThread = value; } } } } ================================================ FILE: Zelig/Zelig/RunTime/Zelig/Kernel/FrameworkOverrides/Threading/ThreadPoolImpl.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // namespace Microsoft.Zelig.Runtime { using System; using System.Collections.Generic; using System.Threading; using System.Runtime.CompilerServices; using TS = Microsoft.Zelig.Runtime.TypeSystem; [ExtendClass(typeof(System.Threading.ThreadPool))] public static class ThreadPoolImpl { const int c_RecycleLimit = 32; internal class WorkItem { // // State // internal WaitCallback m_callBack; internal Object m_state; } internal class Engine { Queue< WorkItem > m_queue; Queue< WorkItem > m_queueFree; AutoResetEvent m_wakeup; int m_maxThreads; int m_activeThreads; int m_busyThreads; // // Helper Methods // internal Engine( ) { m_queue = new Queue< WorkItem >(); m_queueFree = new Queue< WorkItem >(); m_wakeup = new AutoResetEvent( false ); m_maxThreads = Configuration.DefaultThreadPoolThreads; } internal Engine( int maxThreads ) : this() { m_maxThreads = maxThreads; } // // Helper Methods // internal void Queue( WaitCallback callBack , Object state ) { WorkItem item = null; if(m_queueFree.Count > 0) { lock(m_queueFree) { if(m_queueFree.Count > 0) { item = m_queueFree.Dequeue(); } } } if(item == null) { item = new WorkItem(); } item.m_callBack = callBack; item.m_state = state; int count; lock(m_queue) { m_queue.Enqueue( item ); count = m_queue.Count; } if(count == 1) { m_wakeup.Set(); } int active = m_activeThreads; if(active == m_busyThreads) { if(active < m_maxThreads) { if(Interlocked.CompareExchange( ref m_activeThreads, active + 1, active ) == active) { Thread worker = new Thread( Worker ); worker.IsBackground = true; worker.Start(); } } } } internal void SetMaxThreads( int workerThreads ) { m_maxThreads = workerThreads; m_wakeup.Set(); } private void Worker() { while(m_activeThreads <= m_maxThreads) { m_wakeup.WaitOne(); while(m_queue.Count > 0) { WorkItem item; int count; lock(m_queue) { count = m_queue.Count; if(count > 0) { item = m_queue.Dequeue(); count--; } else { item = null; } } if(item != null) { if(count != 0) { m_wakeup.Set(); } WaitCallback callBack = item.m_callBack; object state = item.m_state; if(m_queueFree.Count < c_RecycleLimit) { item.m_callBack = null; item.m_state = null; lock(m_queueFree) { m_queueFree.Enqueue( item ); } } Interlocked.Increment( ref m_busyThreads ); try { callBack( state ); } catch { } Interlocked.Decrement( ref m_busyThreads ); } } } Interlocked.Decrement( ref m_activeThreads ); } } // // State // private static Engine s_engine = new Engine(); //--// // // Helper Methods // public static bool QueueUserWorkItem( WaitCallback callBack , Object state ) { s_engine.Queue( callBack, state ); return true; } [Inline] public static bool QueueUserWorkItem( WaitCallback callBack ) { return QueueUserWorkItem( callBack, null ); } public static bool SetMaxThreads( int workerThreads , int completionPortThreads ) { s_engine.SetMaxThreads( workerThreads ); return true; } //--// // // Access Methods // } } ================================================ FILE: Zelig/Zelig/RunTime/Zelig/Kernel/FrameworkOverrides/Threading/TimerImpl.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // namespace Microsoft.Zelig.Runtime { using System; using System.Collections.Generic; using System.Threading; using System.Runtime.CompilerServices; using TS = Microsoft.Zelig.Runtime.TypeSystem; [ExtendClass(typeof(System.Threading.Timer))] public class TimerImpl : IDisposable { [ImplicitInstance] [ForceDevirtualization] public abstract class TimerPool { class EmptyTimerPool : TimerPool { internal override void InitializeTimerPool( ) { throw new NotImplementedException( ); } internal override void Activate( KernelNode node ) { throw new NotImplementedException( ); } internal override void Deactivate( KernelNode node ) { throw new NotImplementedException( ); } } //--// internal abstract void InitializeTimerPool( ); internal abstract void Activate( KernelNode< TimerImpl > node ); internal abstract void Deactivate( KernelNode< TimerImpl > node ); public static extern TimerPool Instance { [SingletonFactory(Fallback = typeof(EmptyTimerPool))] [MethodImpl(MethodImplOptions.InternalCall)] get; } } // // A timer pool that grows as needed in an unbounded fashion // public abstract class UnboundedAsynchTimerPool : TimerPool { // // For the unbounded timer pool, the max number of handlers refers to // the cached idle workers ready for dispatching // private static readonly int c_MaxIdleHandlers = Configuration.DefaultTimerPoolThreads; //--// internal class CallbackHandler { // // State // UnboundedAsynchTimerPool m_owner; Thread m_thread; AutoResetEvent m_event; KernelNode< TimerImpl > m_node; // // Constructor Methods // internal CallbackHandler( UnboundedAsynchTimerPool owner ) { m_owner = owner; m_thread = new Thread( Worker ); m_event = new AutoResetEvent( false ); m_thread.Start(); } // // Helper Methods // internal void Process( KernelNode< TimerImpl > node ) { m_node = node; m_event.Set(); } internal void Shutdown() { m_node = null; m_event.Set(); } private void Worker() { while(true) { m_event.WaitOne(); KernelNode< TimerImpl > node = m_node; if(node == null) { break; } TimerImpl target = node.Target; node.Target.Execute(); m_owner.Done( this, node ); } } } //--// // // State // KernelList< TimerImpl > m_timers; Thread m_controller; EventWaitHandleImpl m_controllerWakeup; Queue< CallbackHandler > m_idleHandlers; // // Constructor Methods // internal override void InitializeTimerPool( ) { m_timers = new KernelList< TimerImpl >(); m_controllerWakeup = new EventWaitHandleImpl( false, System.Threading.EventResetMode.AutoReset ); m_controller = new Thread( ControllerMethod ); m_idleHandlers = new Queue< CallbackHandler >(); m_controller.Start(); } // // Helper Methods // internal override void Activate( KernelNode< TimerImpl > node ) { lock(this) { TimerImpl timer = node.Target; if(timer.m_fExecuting == false) { node.RemoveFromList(); // // Insert in order. // SchedulerTime nextTrigger = timer.m_nextTrigger; KernelNode< TimerImpl > node2 = m_timers.StartOfForwardWalk; bool fSignalController = true; while(node2.IsValidForForwardMove) { if(node2.Target.m_nextTrigger > nextTrigger) { break; } node2 = node2.Next; fSignalController = false; } node.InsertBefore( node2 ); if(fSignalController) { m_controllerWakeup.Set(); } } } } internal override void Deactivate( KernelNode< TimerImpl > node ) { lock(this) { node.Target.m_nextTrigger = SchedulerTime.MaxValue; // // No need to wake up the controller, even if this is the first timer on the list. // At most the controller will wake up early for the next timer, not late. // node.RemoveFromList(); } } internal void Done( CallbackHandler worker, KernelNode< TimerImpl > node ) { lock(this) { if(m_idleHandlers.Count < c_MaxIdleHandlers) { m_idleHandlers.Enqueue( worker ); worker = null; } //--// TimerImpl timer = node.Target; if(timer.IsDisposed == false) { if(timer.m_nextTrigger != SchedulerTime.MaxValue) { Activate( node ); } } } if(worker != null) { worker.Shutdown(); } } //--// private void ControllerMethod() { while(true) { SchedulerTime waitFor = SchedulerTime.MaxValue; SchedulerTime now = SchedulerTime.Now; while(true) { KernelNode< TimerImpl > node; lock(this) { node = m_timers.FirstNode(); if(node != null) { TimerImpl timer = node.Target; if(timer.m_nextTrigger <= now) { node.RemoveFromList(); timer.PrepareForExecution(); } else { waitFor = timer.m_nextTrigger; node = null; } } } if(node == null) { break; } CallbackHandler worker = FetchIdleWorker(); worker.Process( node ); } m_controllerWakeup.WaitOne( waitFor, false ); } } private CallbackHandler FetchIdleWorker() { CallbackHandler worker; lock(this) { if(m_idleHandlers.Count > 0) { worker = m_idleHandlers.Dequeue(); } else { worker = null; } } if(worker == null) { worker = new CallbackHandler( this ); } return worker; } } //--// //--// //--// // // A timer pool that relies on synchronous execution from a single thread out of a dispatch queue // public abstract class SyncDispatcherTimerPool : TimerPool { // // State // protected KernelList< TimerImpl > m_timers; protected Thread m_controller; protected EventWaitHandleImpl m_controllerWakeup; // // Constructor Methods // internal override void InitializeTimerPool( ) { m_timers = new KernelList< TimerImpl >(); m_controllerWakeup = new EventWaitHandleImpl( false, System.Threading.EventResetMode.AutoReset ); m_controller = new Thread( ControllerMethod ); m_controller.Start(); } // // Helper Methods // internal override void Activate( KernelNode< TimerImpl > node ) { lock(this) { TimerImpl timer = node.Target; if(timer.m_fExecuting == false) { node.RemoveFromList(); // // Insert in order. // SchedulerTime nextTrigger = timer.m_nextTrigger; KernelNode< TimerImpl > node2 = m_timers.StartOfForwardWalk; bool fSignalController = true; while(node2.IsValidForForwardMove) { if(node2.Target.m_nextTrigger > nextTrigger) { break; } node2 = node2.Next; fSignalController = false; } node.InsertBefore( node2 ); if(fSignalController) { m_controllerWakeup.Set(); } } } } internal override void Deactivate( KernelNode< TimerImpl > node ) { lock(this) { node.Target.m_nextTrigger = SchedulerTime.MaxValue; // // No need to wake up the controller, even if this is the first timer on the list. // At most the controller will wake up early for the next timer, not late. // node.RemoveFromList(); } } internal void Done( KernelNode< TimerImpl > node ) { lock(this) { TimerImpl timer = node.Target; if(timer.IsDisposed == false) { if(timer.m_nextTrigger != SchedulerTime.MaxValue) { Activate( node ); } } } } [DisableNullChecks] protected virtual void Dispatch( KernelNode< TimerImpl > node ) { ExecuteWrapper( node ); } [Inline] [DisableNullChecks] protected void ExecuteWrapper( object state ) { var node = (KernelNode< TimerImpl >)state; node.Target.Execute( ); Done( node ); } //--// private void ControllerMethod() { while(true) { SchedulerTime waitFor = SchedulerTime.MaxValue; SchedulerTime now = SchedulerTime.Now; while(true) { KernelNode< TimerImpl > node; lock(this) { node = m_timers.FirstNode(); if(node != null) { TimerImpl timer = node.Target; if(timer.m_nextTrigger <= now) { node.RemoveFromList(); timer.PrepareForExecution(); } else { waitFor = timer.m_nextTrigger; node = null; } } } if(node == null) { break; } Dispatch( node ); } m_controllerWakeup.WaitOne( waitFor, false ); } } } //--// //--// //--// // // A timer pool that delegates to a thread pool of finite size // public abstract class BoundedAsynchTimerPool : SyncDispatcherTimerPool { // // For the bounded timer pool, the max numbers of handlers refers to // the actual maximum number of workers available for dispatching at any time // private static readonly int c_MaxHandlers = Configuration.DefaultTimerPoolThreads; // // State // ThreadPoolImpl.Engine m_threadPool; // // Constructor Methods // internal override void InitializeTimerPool( ) { base.InitializeTimerPool( ); m_threadPool = new ThreadPoolImpl.Engine( c_MaxHandlers ); } // // Helper Methods // [DisableNullChecks] protected override void Dispatch( KernelNode< TimerImpl > node ) { m_threadPool.Queue( ExecuteWrapper, node ); } } //--// //--// //--// // // State // //static UnboundedTimerPool s_pool; private static bool s_initialized; TimerCallback m_callback; object m_state; SchedulerTimeSpan m_dueTime; SchedulerTimeSpan m_period; KernelNode< TimerImpl > m_node; SchedulerTime m_nextTrigger; bool m_fExecuting; // // Constructor Methods // [DiscardTargetImplementation] private TimerImpl() { m_node = new KernelNode< TimerImpl >( this ); m_nextTrigger = SchedulerTime.MaxValue; } [DiscardTargetImplementation] public TimerImpl( TimerCallback callback , Object state , int dueTime , int period ) : this() { m_callback = callback; m_state = state; Change( dueTime, period ); } [DiscardTargetImplementation] public TimerImpl( TimerCallback callback , Object state , TimeSpan dueTime , TimeSpan period ) : this() { m_callback = callback; m_state = state; Change( dueTime, period ); } [DiscardTargetImplementation] public TimerImpl( TimerCallback callback ) : this() { m_callback = callback; Change( Timeout.Infinite, Timeout.Infinite ); } // // Helper Methods // public bool Change( int dueTime , int period ) { if(this.IsDisposed) { return false; } Deactivate(); if(period < 0) { if(period < Timeout.Infinite) { #if EXCEPTION_STRINGS throw new ArgumentOutOfRangeException( "period" ); #else throw new ArgumentOutOfRangeException(); #endif } m_period = SchedulerTimeSpan.MaxValue; } else { m_period = SchedulerTimeSpan.FromMilliseconds( period ); } if(dueTime < 0) { if(dueTime < Timeout.Infinite) { #if EXCEPTION_STRINGS throw new ArgumentOutOfRangeException( "dueTime" ); #else throw new ArgumentOutOfRangeException(); #endif } m_dueTime = SchedulerTimeSpan.MaxValue; } else { m_dueTime = SchedulerTimeSpan.FromMilliseconds( dueTime ); SetInitialTrigger(); Activate(); } return true; } public bool Change( TimeSpan dueTime , TimeSpan period ) { if(this.IsDisposed) { return false; } Deactivate(); if(period.Ticks < 0) { m_period = SchedulerTimeSpan.MaxValue; } else { m_period = (SchedulerTimeSpan)period; } if(dueTime.Ticks < 0) { m_dueTime = SchedulerTimeSpan.MaxValue; } else { m_dueTime = (SchedulerTimeSpan)dueTime; SetInitialTrigger(); Activate(); } return true; } public bool Change( long dueTime , long period ) { if(this.IsDisposed) { return false; } Deactivate(); if(period < 0) { if(period < Timeout.Infinite) { #if EXCEPTION_STRINGS throw new ArgumentOutOfRangeException( "period" ); #else throw new ArgumentOutOfRangeException(); #endif } m_period = SchedulerTimeSpan.MaxValue; } else { m_period = SchedulerTimeSpan.FromMilliseconds( period ); } if(dueTime < 0) { if(dueTime < Timeout.Infinite) { #if EXCEPTION_STRINGS throw new ArgumentOutOfRangeException( "dueTime" ); #else throw new ArgumentOutOfRangeException(); #endif } m_dueTime = SchedulerTimeSpan.MaxValue; } else { m_dueTime = SchedulerTimeSpan.FromMilliseconds( dueTime ); SetInitialTrigger(); Activate(); } return true; } public void Dispose() { this.Pool.Deactivate( m_node ); m_callback = null; m_state = null; } //--// private void SetInitialTrigger() { m_nextTrigger = SchedulerTime.Now + m_dueTime; } private void SetNextTrigger() { if(m_period != SchedulerTimeSpan.MaxValue) { m_nextTrigger += m_period; } else { m_nextTrigger = SchedulerTime.MaxValue; } } private void Activate() { this.Pool.Activate( m_node ); } private void Deactivate() { this.Pool.Deactivate( m_node ); } //--// void PrepareForExecution() { m_fExecuting = true; } void Execute() { TimerCallback callback; object state; lock(this.Pool) { callback = m_callback; state = m_state; if(callback != null) { SetNextTrigger(); } } try { if(callback != null) { callback( state ); } } catch { } m_fExecuting = false; } // // Access Methods // internal TimerCallback Callback { get { return m_callback; } } private bool IsDisposed { get { return m_callback == null; } } private TimerPool Pool { [Inline] get { var pool = TimerPool.Instance; if(s_initialized == false) { lock(pool) { if(s_initialized == false) { pool.InitializeTimerPool( ); s_initialized = true; } } } return pool; } } } } ================================================ FILE: Zelig/Zelig/RunTime/Zelig/Kernel/FrameworkOverrides/Threading/WaitHandleImpl.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // namespace Microsoft.Zelig.Runtime { using System; using System.Runtime.CompilerServices; using TS = Microsoft.Zelig.Runtime.TypeSystem; [ExtendClass(typeof(System.Threading.WaitHandle))] public abstract class WaitHandleImpl : MarshalByRefObject { // // State // protected Synchronization.WaitableObject m_handle; // // Constructor Methods // [DiscardTargetImplementation] protected WaitHandleImpl() { } // // Helper Methods // public virtual bool WaitOne( int millisecondsTimeout , bool exitContext ) { return WaitOne( (SchedulerTime)millisecondsTimeout, exitContext ); } public virtual bool WaitOne( TimeSpan timeout , bool exitContext ) { return WaitOne( (SchedulerTime)timeout, exitContext ); } public static bool WaitAll( WaitHandleImpl[] waitHandles , int millisecondsTimeout , bool exitContext ) { throw new NotImplementedException(); } public static int WaitAny( WaitHandleImpl[] waitHandles , int millisecondsTimeout , bool exitContext ) { throw new NotImplementedException(); } protected virtual void Dispose( bool explicitDisposing ) { Synchronization.WaitableObject handle = System.Threading.Interlocked.Exchange( ref m_handle, null ); if(handle != null) { handle.Dispose(); } } //--// public bool WaitOne( SchedulerTime timeout , bool exitContext ) { return m_handle.Acquire( timeout ); } } } ================================================ FILE: Zelig/Zelig/RunTime/Zelig/Kernel/FrameworkOverrides/TypeImpl.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // namespace Microsoft.Zelig.Runtime { using System; using TS = Microsoft.Zelig.Runtime.TypeSystem; [TS.WellKnownType( "Microsoft_Zelig_Runtime_TypeImpl" )] [ExtendClass(typeof(System.Type), NoConstructors=true, ProcessAfter=typeof(RuntimeTypeHandleImpl))] public abstract class TypeImpl : MemberInfoImpl { // // State // // // Constructor Methods // //--// // // Helper Methods // //[Inline] [TS.WellKnownMethod( "TypeImpl_GetTypeFromHandle" )] public static Type GetTypeFromHandle( RuntimeTypeHandleImpl handle ) { TS.VTable vt = handle.m_value; return (vt != null) ? vt.Type : null; } // // Access Methods // public abstract System.Reflection.Assembly Assembly { get; } public abstract Type BaseType { get; } public abstract String FullName { get; } public abstract String Namespace { get; } public abstract String AssemblyQualifiedName { get; } public bool IsValueType { get { return IsValueTypeInner; } } //--// protected abstract bool IsValueTypeInner { get; } } } ================================================ FILE: Zelig/Zelig/RunTime/Zelig/Kernel/FrameworkOverrides/WeakReferenceImpl.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // namespace Microsoft.Zelig.Runtime { using System; using TS = Microsoft.Zelig.Runtime.TypeSystem; [ExtendClass(typeof(System.WeakReference))] public class WeakReferenceImpl { [TS.GarbageCollectionExtension(typeof(WeakReferenceImpl))] class Handler : GarbageCollectionExtensionHandler { [TS.SkipDuringGarbageCollection] WeakReferenceImpl m_head; public override void StartOfMarkPhase( GarbageCollectionManager gc ) { m_head = null; } public override void Mark( GarbageCollectionManager gc , object target ) { var obj = (WeakReferenceImpl)target; if(gc.IsMarked( obj.Target )) { return; } obj.m_next = m_head; m_head = obj; } public override void EndOfMarkPhase( GarbageCollectionManager gc ) { } public override void StartOfSweepPhase( GarbageCollectionManager gc ) { for(var ptr = m_head; ptr != null; ptr = ptr.m_next) { if(!gc.IsMarked( ptr.m_target )) { ptr.m_target = null; } } } public override void Sweep( GarbageCollectionManager gc , object target ) { } public override void EndOfSweepPhase( GarbageCollectionManager gc ) { } } // // State // [TS.SkipDuringGarbageCollection] object m_target; [TS.SkipDuringGarbageCollection] WeakReferenceImpl m_next; // // Constructor Methods // [DiscardTargetImplementation] public WeakReferenceImpl( Object target , bool trackResurrection ) { m_target = target; } // // Access Methods // //Determines whether or not this instance of WeakReference still refers to an object //that has not been collected. // public virtual bool IsAlive { get { return m_target != null; } } //Gets the Object stored in the handle if it's accessible. // Or sets it. // public virtual Object Target { get { return m_target; } set { m_target = value; } } } } ================================================ FILE: Zelig/Zelig/RunTime/Zelig/Kernel/FrameworkOverrides_Llilum/Devices/Adc/AdcPinImpl.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // namespace Microsoft.Zelig.Runtime { using Microsoft.Llilum.Devices.Adc; [ExtendClass(typeof(AdcPin), NoConstructors = true)] class AdcPinImpl { public static AdcChannel TryAcquireAdcPin(int pinNumber) { return AdcProvider.Instance.CreateAdcPin(pinNumber); } } } ================================================ FILE: Zelig/Zelig/RunTime/Zelig/Kernel/FrameworkOverrides_Llilum/Devices/Adc/AdcProvider.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // namespace Microsoft.Zelig.Runtime { using System; using System.Runtime.CompilerServices; using Microsoft.Llilum.Devices.Adc; [ImplicitInstance] [ForceDevirtualization] public abstract class AdcProvider { private sealed class EmptyAdcProvider : AdcProvider { public override AdcChannel CreateAdcPin(int pinNumber) { throw new NotImplementedException(); } } public abstract AdcChannel CreateAdcPin(int pinNumber); public static extern AdcProvider Instance { [SingletonFactory(Fallback = typeof(EmptyAdcProvider))] [MethodImpl(MethodImplOptions.InternalCall)] get; } } } ================================================ FILE: Zelig/Zelig/RunTime/Zelig/Kernel/FrameworkOverrides_Llilum/Devices/Gpio/GpioPinImpl.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // namespace Microsoft.Zelig.Runtime { using Microsoft.Llilum.Devices.Gpio; [ExtendClass(typeof(GpioPin), NoConstructors = true)] class GpioPinImpl { public static GpioPin TryAcquireGpioPin(int pinNumber) { return GpioProvider.Instance.CreateGpioPin(pinNumber); } public static int GetBoardPinCount() { return HardwareProvider.Instance.PinCount; } } } ================================================ FILE: Zelig/Zelig/RunTime/Zelig/Kernel/FrameworkOverrides_Llilum/Devices/Gpio/GpioProvider.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // namespace Microsoft.Zelig.Runtime { using System; using System.Runtime.CompilerServices; using Microsoft.Llilum.Devices.Gpio; [ImplicitInstance] [ForceDevirtualization] public abstract class GpioProvider { private sealed class EmptyGpioProvider : GpioProvider { public override GpioPin CreateGpioPin(int pinNumber) { throw new NotImplementedException(); } //////public override void RemapInterrupts( ) //////{ ////// throw new NotImplementedException(); //////} public override int GetGpioPinIRQNumber(int pinNumber) { throw new NotImplementedException(); } } public abstract GpioPin CreateGpioPin(int pinNumber); //////public abstract void RemapInterrupts( ); public abstract int GetGpioPinIRQNumber(int pinNumber); public static extern GpioProvider Instance { [SingletonFactory(Fallback = typeof(EmptyGpioProvider))] [MethodImpl(MethodImplOptions.InternalCall)] get; } } } ================================================ FILE: Zelig/Zelig/RunTime/Zelig/Kernel/FrameworkOverrides_Llilum/Devices/I2c/I2cDeviceImpl.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // namespace Microsoft.Zelig.Runtime { using Microsoft.Llilum.Devices.I2c; [ExtendClass(typeof(I2cDevice), NoConstructors = true)] public class I2cDeviceImpl { public static I2cChannel TryAcquireI2cChannel(int port) { I2cChannelInfo channelInfo = I2cProvider.Instance.GetI2cChannelInfo(port); return TryAcquireI2cChannel(channelInfo); } public static I2cChannel TryAcquireI2cChannel(II2cChannelInfo channelInfo) { I2cProvider i2cProvider = I2cProvider.Instance; if (channelInfo == null) { return null; } return i2cProvider.CreateI2cChannel(channelInfo); } } } ================================================ FILE: Zelig/Zelig/RunTime/Zelig/Kernel/FrameworkOverrides_Llilum/Devices/I2c/I2cProvider.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // namespace Microsoft.Zelig.Runtime { using System; using System.Collections; using System.Runtime.CompilerServices; using Microsoft.Llilum.Devices.I2c; public class I2cChannelInfo : II2cChannelInfo { public int PortIndex { get; set; } public int SclPin { get; set; } public int SdaPin { get; set; } } [ImplicitInstance] [ForceDevirtualization] public abstract class I2cProvider { sealed class EmptyI2cProvider : I2cProvider { public override I2cChannel CreateI2cChannel(II2cChannelInfo channelInfo) { throw new NotImplementedException(); } public override I2cChannelInfo GetI2cChannelInfo(int id) { throw new NotImplementedException(); } } public abstract I2cChannel CreateI2cChannel(II2cChannelInfo channelInfo); public abstract I2cChannelInfo GetI2cChannelInfo(int id); public static extern I2cProvider Instance { [SingletonFactory(Fallback = typeof(EmptyI2cProvider))] [MethodImpl(MethodImplOptions.InternalCall)] get; } } } ================================================ FILE: Zelig/Zelig/RunTime/Zelig/Kernel/FrameworkOverrides_Llilum/Devices/Pwm/PwmPinImpl.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // namespace Microsoft.Zelig.Runtime { using Microsoft.Llilum.Devices.Pwm; [ExtendClass(typeof(PwmPin), NoConstructors = true)] class PwmPinImpl { public static PwmChannel TryAcquirePwmPin(int pinNumber) { return PwmProvider.Instance.TryCreatePwmPin(pinNumber); } } } ================================================ FILE: Zelig/Zelig/RunTime/Zelig/Kernel/FrameworkOverrides_Llilum/Devices/Pwm/PwmProvider.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // namespace Microsoft.Zelig.Runtime { using System; using System.Runtime.CompilerServices; using Microsoft.Llilum.Devices.Pwm; [ImplicitInstance] [ForceDevirtualization] public abstract class PwmProvider { private sealed class EmptyPwmProvider : PwmProvider { public override PwmChannel TryCreatePwmPin(int pinNumber) { throw new NotImplementedException(); } } public abstract PwmChannel TryCreatePwmPin(int pinNumber); public static extern PwmProvider Instance { [SingletonFactory(Fallback = typeof(EmptyPwmProvider))] [MethodImpl(MethodImplOptions.InternalCall)] get; } } } ================================================ FILE: Zelig/Zelig/RunTime/Zelig/Kernel/FrameworkOverrides_Llilum/Devices/Spi/SpiDeviceImpl.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // namespace Microsoft.Zelig.Runtime { using Microsoft.Llilum.Devices.Spi; //--// [ExtendClass(typeof(SpiDevice), NoConstructors = true)] public class SpiDeviceImpl { public static SpiChannel TryAcquireSpiChannel(int port, bool writeOnly) { SpiChannelInfo channelInfo = SpiProvider.Instance.GetSpiChannelInfo(port); return TryAcquireSpiChannel(channelInfo, channelInfo.DefaultChipSelect, writeOnly); } public static SpiChannel TryAcquireSpiChannel(ISpiChannelInfo channelInfo, int chipSelectPin, bool writeOnly) { SpiProvider spiProvider = SpiProvider.Instance; if (channelInfo != null) { // Ensure all pins are available if (!HardwareProvider.Instance.TryReservePins(channelInfo.Mosi, writeOnly ? HardwareProvider.Instance.InvalidPin : channelInfo.Miso, channelInfo.Sclk, chipSelectPin)) { return null; } return spiProvider.CreateSpiChannel(channelInfo); } return null; } public static bool TryChangeCsPin(int oldPin, int newPin) { HardwareProvider provider = HardwareProvider.Instance; // If pin is invalid, short circuit the if statement, and skip pin reservation if (newPin == provider.InvalidPin || provider.TryReservePins(newPin)) { provider.ReleasePins(oldPin); return true; } else { return false; } } public static void ReleaseSpiPins(ISpiChannelInfo channelInfo, int csPin) { HardwareProvider.Instance.ReleasePins(channelInfo.Mosi, channelInfo.Miso, channelInfo.Sclk, csPin); } } } ================================================ FILE: Zelig/Zelig/RunTime/Zelig/Kernel/FrameworkOverrides_Llilum/Devices/Spi/SpiProvider.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // namespace Microsoft.Zelig.Runtime { using System; using System.Collections; using System.Runtime.CompilerServices; using Microsoft.Llilum.Devices.Spi; public class SpiChannelInfo : ISpiChannelInfo { public int Mosi { get; set; } public int Miso { get; set; } public int Sclk { get; set; } public int DefaultChipSelect { get; set; } public int SetupTime { get; set; } public int HoldTime { get; set; } public bool ActiveLow { get; set; } } [ImplicitInstance] [ForceDevirtualization] public abstract class SpiProvider { private sealed class EmptySpiProvider : SpiProvider { public override bool SpiBusySupported { get { throw new NotImplementedException(); } } public override SpiChannel CreateSpiChannel(ISpiChannelInfo channelInfo) { throw new NotImplementedException(); } public override SpiChannelInfo GetSpiChannelInfo(int id) { throw new NotImplementedException(); } } public abstract SpiChannel CreateSpiChannel(ISpiChannelInfo channelInfo); public abstract SpiChannelInfo GetSpiChannelInfo(int id); public abstract bool SpiBusySupported { get; } public static extern SpiProvider Instance { [SingletonFactory(Fallback = typeof(EmptySpiProvider))] [MethodImpl(MethodImplOptions.InternalCall)] get; } } } ================================================ FILE: Zelig/Zelig/RunTime/Zelig/Kernel/FrameworkOverrides_System/Diagnostics/DefaultTraceListernerImpl.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // namespace Microsoft.Zelig.Runtime { using System; [ExtendClass( typeof( System.Diagnostics.DefaultTraceListener ), NoConstructors = true )] public class DefaultTraceListenerImpl { public static void OutputDebugString( String message ) { BugCheck.Log( message ); } } } ================================================ FILE: Zelig/Zelig/RunTime/Zelig/Kernel/FrameworkOverrides_System/IO/MediaManagerImpl.cs ================================================ // ==++== // // Copyright (c) Microsoft Corporation. All rights reserved. // // ==--== namespace Microsoft.Zelig.Runtime { using System; using System.IO; using System.Runtime.CompilerServices; using RT = Microsoft.Zelig.Runtime; using TS = Microsoft.Zelig.Runtime.TypeSystem; [ExtendClass( typeof( System.IO.VolumeInfo ) )] public class VolumeInfoImpl { uint m_volumeHandle; static bool s_isFsInit = false; static object s_lock = new object(); private static void EnsureInit() { if(!s_isFsInit) { lock(s_lock) { if(!s_isFsInit) { FileSystemVolumeList.AddRamBlockStorageFileStream(); s_isFsInit = true; } } } } //[RT.ImportedMethodReference( RT.ImportedMethodReferenceAttribute.InteropFileType.ArmELF, c_VolumeInfoLibrary )] [DiscardTargetImplementation] public VolumeInfoImpl( String volumeName ) { EnsureInit(); m_volumeHandle = FileSystemVolumeList.FindVolume( volumeName, volumeName.Length ); } //[RT.ImportedMethodReference( RT.ImportedMethodReferenceAttribute.InteropFileType.ArmELF, c_VolumeInfoLibrary )] [DiscardTargetImplementation] internal VolumeInfoImpl( uint volumePtr ) { EnsureInit(); m_volumeHandle = volumePtr; } //[RT.ImportedMethodReference( RT.ImportedMethodReferenceAttribute.InteropFileType.ArmELF, c_VolumeInfoLibrary )] public void Refresh() { } //[RT.ImportedMethodReference( RT.ImportedMethodReferenceAttribute.InteropFileType.ArmELF, c_VolumeInfoLibrary )] public static VolumeInfo[] GetVolumes() { int cnt = 0; EnsureInit(); HR.ThrowOnFailure( FileSystemVolumeList.GetVolumes( null, ref cnt ) ); uint[] volIds = new uint[cnt]; if(cnt > 0) { HR.ThrowOnFailure( FileSystemVolumeList.GetVolumes( volIds, ref cnt ) ); } VolumeInfo[] vols = new VolumeInfo[cnt]; for(int i = 0; i < cnt; i++) { vols[i] = new VolumeInfo( volIds[i] ); } return vols; } //[RT.ImportedMethodReference( RT.ImportedMethodReferenceAttribute.InteropFileType.ArmELF, c_VolumeInfoLibrary )] //public static String[] GetFileSystems() //{ // return new String[0]; //} //[RT.ImportedMethodReference( RT.ImportedMethodReferenceAttribute.InteropFileType.ArmELF, c_VolumeInfoLibrary )] //public void FlushAll() //{ //} public string Name { get { char[] name = new char[32]; int len = name.Length; HR.ThrowOnFailure( FileSystemVolume.GetName( m_volumeHandle, name, ref len ) ); return new string( name, 0, len ); } } public string FileSystem { get { char[] name = new char[32]; int len = name.Length; HR.ThrowOnFailure( FileSystemVolume.GetFileSystem( m_volumeHandle, name, ref len ) ); return new string( name, 0, len ); } } public string VolumeLabel { get { char[] name = new char[32]; int len = name.Length; HR.ThrowOnFailure( FileSystemVolume.GetLabel( m_volumeHandle, name, ref len ) ); return new string( name, 0, len ); } } public long TotalSize { get { long retVal = 0, avail = 0; HR.ThrowOnFailure( FileSystemVolume.GetSize( m_volumeHandle, ref avail, ref retVal ) ); return retVal; } } //public uint FileSystemFlags //{ // get { return 0; } //} //public uint DeviceFlags //{ // get { return 0; } //} //public uint SerialNumber //{ // get { return 0; } //} public long TotalFreeSpace { get { long retVal = 0, avail = 0; HR.ThrowOnFailure( FileSystemVolume.GetSize( m_volumeHandle, ref avail, ref retVal ) ); return avail; } } } [ExtendClass( typeof( System.IO.RemovableMedia ) )] public static class RemovableMediaImpl { //[RT.ImportedMethodReference( RT.ImportedMethodReferenceAttribute.InteropFileType.ArmELF, c_RemovableMediaLibrary )] private static void MountRemovableVolumes() { } } } ================================================ FILE: Zelig/Zelig/RunTime/Zelig/Kernel/FrameworkOverrides_System/IO/NativeFileImpl.cs ================================================ // ==++== // // Copyright (c) Microsoft Corporation. All rights reserved. // // ==--== namespace Microsoft.Zelig.Runtime { using System; using System.IO; using System.Runtime.CompilerServices; using RT = Microsoft.Zelig.Runtime; using TS = Microsoft.Zelig.Runtime.TypeSystem; using System.Runtime.InteropServices; [ExtendClass( typeof( System.IO.NativeFileStream ))] internal class NativeFileStreamImpl { uint m_fileHandle; uint m_volumeHandle; internal static string[] SplitVolumeFromPath( string path ) { string[] values = new string[2]; path = path.TrimStart( '\\' ); if(path.Length == 0) #if EXCEPTION_STRINGS throw new IOException( "InvalidPath" ); #else throw new IOException(); #endif int idx = path.IndexOf( '\\' ); if(idx == -1) { idx = path.Length; values[1] = "\\"; } else { // include the '\\' values[1] = path.Substring( idx, path.Length - idx ); } values[0] = path.Substring( 0, idx ); return values; } [DiscardTargetImplementation] internal NativeFileStreamImpl( string path, int bufferSize ) { if(bufferSize < 0) throw new ArgumentException(); string[] paths = SplitVolumeFromPath( path ); m_volumeHandle = FileSystemVolumeList.FindVolume( paths[0], paths[0].Length ); HRESULT hr = FileSystemVolume.Open( m_volumeHandle, paths[1], ref m_fileHandle ); HR.ThrowOnFailure( hr ); } //[RT.ImportedMethodReference( RT.ImportedMethodReferenceAttribute.InteropFileType.ArmELF, c_NativeFileLibrary )] public int Read( byte[] buf, int offset, int count, int timeout ) { int bytesRead = 0; if(buf == null ) throw new ArgumentNullException(); if(count < 0 || offset < 0 ) throw new ArgumentOutOfRangeException(); if(offset + count > buf.Length) throw new ArgumentException(); HRESULT hr = FileSystemVolume.Read( m_volumeHandle, m_fileHandle, buf, offset, count, ref bytesRead ); HR.ThrowOnFailure( hr ); return bytesRead; } //[RT.ImportedMethodReference( RT.ImportedMethodReferenceAttribute.InteropFileType.ArmELF, c_NativeFileLibrary )] public int Write( byte[] buf, int offset, int count, int timeout ) { int bytesWritten = 0; if(buf == null ) throw new ArgumentNullException(); if(count < 0 || offset < 0 ) throw new ArgumentOutOfRangeException(); if(offset + count > buf.Length) throw new ArgumentException(); HRESULT hr = FileSystemVolume.Write( m_volumeHandle, m_fileHandle, buf, offset, count, ref bytesWritten ); HR.ThrowOnFailure( hr ); return bytesWritten; } //[RT.ImportedMethodReference( RT.ImportedMethodReferenceAttribute.InteropFileType.ArmELF, c_NativeFileLibrary )] public long Seek( long offset, uint origin ) { long pos = 0; HRESULT hr = FileSystemVolume.Seek( m_volumeHandle, m_fileHandle, offset, origin, ref pos ); HR.ThrowOnFailure( hr ); return pos; } //[RT.ImportedMethodReference( RT.ImportedMethodReferenceAttribute.InteropFileType.ArmELF, c_NativeFileLibrary )] public void Flush() { HRESULT hr = FileSystemVolume.Flush( m_volumeHandle, m_fileHandle ); HR.ThrowOnFailure( hr ); } //[RT.ImportedMethodReference( RT.ImportedMethodReferenceAttribute.InteropFileType.ArmELF, c_NativeFileLibrary )] public long GetLength() { long len = 0; HRESULT hr = FileSystemVolume.GetLength( m_volumeHandle, m_fileHandle, ref len ); HR.ThrowOnFailure( hr ); return len; } //[RT.ImportedMethodReference( RT.ImportedMethodReferenceAttribute.InteropFileType.ArmELF, c_NativeFileLibrary )] public void SetLength( long length ) { if(length < 0) { throw new ArgumentOutOfRangeException(); } HRESULT hr = FileSystemVolume.SetLength( m_volumeHandle, m_fileHandle, length ); HR.ThrowOnFailure( hr ); } //[RT.ImportedMethodReference( RT.ImportedMethodReferenceAttribute.InteropFileType.ArmELF, c_NativeFileLibrary )] public void GetStreamProperties( out bool canRead, out bool canWrite, out bool canSeek ) { StreamDriverDetails sdd = new StreamDriverDetails(); HRESULT hr = FileSystemVolume.GetDriverDetails( m_volumeHandle, m_fileHandle, ref sdd ); HR.ThrowOnFailure( hr ); canRead = sdd.canRead != 0; canWrite = sdd.canWrite != 0; canSeek = sdd.canSeek != 0; } //[RT.ImportedMethodReference( RT.ImportedMethodReferenceAttribute.InteropFileType.ArmELF, c_NativeFileLibrary )] public void Close() { HRESULT hr = FileSystemVolume.Close( m_volumeHandle, m_fileHandle ); HR.ThrowOnFailure( hr ); } } [ExtendClass( typeof( System.IO.NativeFindFile ), NoConstructors=false)] internal class NativeFindFileImpl { uint m_fileFindHandle; uint m_volumeHandle; [DiscardTargetImplementation] internal NativeFindFileImpl( string path, string searchPattern ) { string[] paths = NativeFileStreamImpl.SplitVolumeFromPath( path ); m_volumeHandle = FileSystemVolumeList.FindVolume( paths[0], paths[0].Length ); HRESULT hr = FileSystemVolume.FindOpen( m_volumeHandle, paths[1], ref m_fileFindHandle ); HR.ThrowOnFailure( hr ); } //[RT.ImportedMethodReference( RT.ImportedMethodReferenceAttribute.InteropFileType.ArmELF, c_NativeFileFindLibrary )] public NativeFileInfo GetNext() { FileInfo findData = new FileInfo(); NativeFileInfo retVal = new NativeFileInfo(); char[] fileName = new char[256]; int found = 0; int fileNameLen = fileName.Length; HRESULT hr = FileSystemVolume.FindNext( m_volumeHandle, m_fileFindHandle, ref findData, fileName, ref fileNameLen, ref found ); HR.ThrowOnFailure( hr ); if(found != 0) { retVal.Attributes = findData.Attributes; retVal.CreationTime = findData.CreationTime; retVal.FileName = new string( fileName, 0, fileNameLen ); retVal.LastAccessTime = findData.LastAccessTime; retVal.LastWriteTime = findData.LastWriteTime; retVal.Size = findData.Size; return retVal; } return null; } //[RT.ImportedMethodReference( RT.ImportedMethodReferenceAttribute.InteropFileType.ArmELF, c_NativeFileFindLibrary )] public void Close() { HRESULT hr = FileSystemVolume.FindClose( m_volumeHandle, m_fileFindHandle ); HR.ThrowOnFailure( hr ); } //[RT.ImportedMethodReference( RT.ImportedMethodReferenceAttribute.InteropFileType.ArmELF, c_NativeFileFindLibrary )] public static NativeFileInfo GetFileInfo( String path ) { FileInfo fileInfo = new FileInfo(); int found = 0; string[] paths = NativeFileStreamImpl.SplitVolumeFromPath( path ); uint volumeHandle = FileSystemVolumeList.FindVolume( paths[0], paths[0].Length ); HRESULT hr = FileSystemVolume.GetFileInfo( volumeHandle, paths[1], ref fileInfo, ref found ); HR.ThrowOnFailure( hr ); if(found != 0) { NativeFileInfo nfi = new NativeFileInfo(); nfi.FileName = path; nfi.Attributes = fileInfo.Attributes; nfi.CreationTime = fileInfo.CreationTime; nfi.LastAccessTime = fileInfo.LastAccessTime; nfi.LastWriteTime = fileInfo.LastWriteTime; nfi.Size = fileInfo.Size; return nfi; } return null; } } [ExtendClass( typeof( System.IO.NativeIO ))] internal static class NativeIOImpl { //[RT.ImportedMethodReference( RT.ImportedMethodReferenceAttribute.InteropFileType.ArmELF, c_NativeIOLibrary )] internal static void Format( String nameSpace, String fileSystem, String volumeLabel, uint parameter ) { uint volHandle = FileSystemVolumeList.FindVolume( nameSpace, nameSpace.Length ); HR.ThrowOnFailure( FileSystemVolume.Format( volHandle, volumeLabel, parameter ) ); } //[RT.ImportedMethodReference( RT.ImportedMethodReferenceAttribute.InteropFileType.ArmELF, c_NativeIOLibrary )] internal static void Delete( string path ) { string[] paths = NativeFileStreamImpl.SplitVolumeFromPath( path ); uint volHandle = FileSystemVolumeList.FindVolume( paths[0], paths[0].Length ); HR.ThrowOnFailure( FileSystemVolume.Delete( volHandle, paths[1] ) ); } //[RT.ImportedMethodReference( RT.ImportedMethodReferenceAttribute.InteropFileType.ArmELF, c_NativeIOLibrary )] internal static bool Move( string sourceFileName, string destFileName ) { string []pathsSrc = NativeFileStreamImpl.SplitVolumeFromPath( sourceFileName ); string []pathsDst = NativeFileStreamImpl.SplitVolumeFromPath( destFileName ); string volSrc = pathsSrc[0]; if(volSrc != pathsDst[0]) #if EXCEPTION_STRINGS throw new InvalidOperationException( "Cannot move between volumes" ); #else throw new InvalidOperationException(); #endif uint volHandle = FileSystemVolumeList.FindVolume( volSrc, volSrc.Length ); return HR.Succeeded( FileSystemVolume.Move( volHandle, pathsSrc[1], pathsDst[1] ) ); } //[RT.ImportedMethodReference( RT.ImportedMethodReferenceAttribute.InteropFileType.ArmELF, c_NativeIOLibrary )] internal static void CreateDirectory( string path ) { string[] paths = NativeFileStreamImpl.SplitVolumeFromPath( path ); uint volHandle = FileSystemVolumeList.FindVolume( paths[0], paths[0].Length ); HR.ThrowOnFailure( FileSystemVolume.CreateDirectory( volHandle, paths[1] ) ); } //[RT.ImportedMethodReference( RT.ImportedMethodReferenceAttribute.InteropFileType.ArmELF, c_NativeIOLibrary )] internal static uint GetAttributes( string path ) { uint attribs = 0; string[] paths = NativeFileStreamImpl.SplitVolumeFromPath( path ); uint volHandle = FileSystemVolumeList.FindVolume( paths[0], paths[0].Length ); HR.ThrowOnFailure( FileSystemVolume.GetAttributes( volHandle, paths[1], ref attribs ) ); return attribs; } //[RT.ImportedMethodReference( RT.ImportedMethodReferenceAttribute.InteropFileType.ArmELF, c_NativeIOLibrary )] internal static void SetAttributes( string path, uint attributes ) { string[] paths = NativeFileStreamImpl.SplitVolumeFromPath( path ); uint volHandle = FileSystemVolumeList.FindVolume( paths[0], paths[0].Length ); HR.ThrowOnFailure( FileSystemVolume.SetAttributes( volHandle, paths[1], attributes ) ); } } internal enum HRESULT : int { SUCCEED = 0, } internal enum HR_Faculty : ushort { IO = 0x4f00, FileIO = 0x6000, InvalidDriver = 0x6100, FileNotFound = 0x6200, DirectoryNotFound = 0x6300, VolumeNotFound = 0x6400, PathTooLong = 0x6500, DirectoryNotEmpty = 0x6600, UnauthorizedAccess = 0x6700, PathAlreadyExists = 0x6800, TooManyOpenHandles = 0x6900, InvalidParameter = 0x7d00, ArgumentNull = 0x4e00, OutOfRange = 0x2500, NullReference = 0x2100, NotImplemented = 0x4a00, } internal class HR { internal static bool Succeeded( HRESULT hr ) { return hr >= 0; } internal static bool Failed( HRESULT hr ) { return hr < 0; } internal static uint GetCode( HRESULT hr ) { return (uint)hr & 0xFFFF; } internal static HR_Faculty GetFacility( HRESULT hr ) { return (HR_Faculty)(((uint)hr >> 16) & 0x7FFF); } internal static void ThrowOnFailure( HRESULT hr ) { if((int)hr < 0) { switch(HR.GetFacility( hr )) { case HR_Faculty.NotImplemented: throw new NotImplementedException(); case HR_Faculty.OutOfRange: throw new ArgumentOutOfRangeException(); case HR_Faculty.NullReference: case HR_Faculty.ArgumentNull: throw new ArgumentNullException(); case HR_Faculty.InvalidParameter: throw new ArgumentException(); case HR_Faculty.IO: case HR_Faculty.FileIO: case HR_Faculty.InvalidDriver: case HR_Faculty.FileNotFound: case HR_Faculty.DirectoryNotFound: case HR_Faculty.VolumeNotFound: case HR_Faculty.PathTooLong: case HR_Faculty.DirectoryNotEmpty: case HR_Faculty.UnauthorizedAccess: case HR_Faculty.PathAlreadyExists: case HR_Faculty.TooManyOpenHandles: default: #if EXCEPTION_STRINGS throw new IOException( "HRESULT: " + ( (uint)hr ).ToString() ); #else throw new IOException(); #endif } } } } [StructLayout( LayoutKind.Explicit )] internal struct FileInfo { [FieldOffset( 0 )] internal uint Attributes; [FieldOffset( 8 )] internal Int64 CreationTime; [FieldOffset( 16 )] internal Int64 LastAccessTime; [FieldOffset( 24 )] internal Int64 LastWriteTime; [FieldOffset( 32 )] internal Int64 Size; }; [StructLayout( LayoutKind.Explicit )] public struct StreamDriverDetails { [FieldOffset( 0 )] public int BufferingStrategy; [FieldOffset( 4 )] public IntPtr inputBuffer; [FieldOffset( 8 )] public IntPtr outputBuffer; [FieldOffset( 12 )] public int inputBufferSize; [FieldOffset( 16 )] public int outputBufferSize; [FieldOffset( 20 )] public int canRead; [FieldOffset( 24 )] public int canWrite; [FieldOffset( 28 )] public int canSeek; [FieldOffset( 32 )] public int readTimeout; [FieldOffset( 36 )] public int writeTimeout; } internal class FileSystemVolume { const string c_FileSystemVolumeLibrary = @"BlockStorageFileSystem.obj"; //[RT.ImportedMethodReference( RT.ImportedMethodReferenceAttribute.InteropFileType.ArmELF, c_FileSystemVolumeLibrary )] //internal extern static bool InitializeVolume ( uint volumeHandle ); //[RT.ImportedMethodReference( RT.ImportedMethodReferenceAttribute.InteropFileType.ArmELF, c_FileSystemVolumeLibrary )] //internal extern static bool UninitializeVolume( uint volumeHandle ); [RT.ImportedMethodReference( RT.ImportedMethodReferenceAttribute.InteropFileType.ArmELF, c_FileSystemVolumeLibrary )] internal extern static HRESULT Format ( uint volumeHandle, string volumeLabel, uint parameters ); //[RT.ImportedMethodReference( RT.ImportedMethodReferenceAttribute.InteropFileType.ArmELF, c_FileSystemVolumeLibrary )] //internal extern static HRESULT GetSizeInfo ( uint volumeHandle, ref Int64 totalSize, ref Int64 totalFreeSpace ); //[RT.ImportedMethodReference( RT.ImportedMethodReferenceAttribute.InteropFileType.ArmELF, c_FileSystemVolumeLibrary )] //internal extern static HRESULT FlushAll ( uint volumeHandle ); [RT.ImportedMethodReference( RT.ImportedMethodReferenceAttribute.InteropFileType.ArmELF, c_FileSystemVolumeLibrary )] internal extern static HRESULT FindOpen ( uint volumeHandle, string path, ref uint findHandle ); [RT.ImportedMethodReference( RT.ImportedMethodReferenceAttribute.InteropFileType.ArmELF, c_FileSystemVolumeLibrary )] internal extern static HRESULT FindNext ( uint volumeHandle, uint findHandle, ref FileInfo findData, char[] fileName, ref int fileNameLen, ref int found ); [RT.ImportedMethodReference( RT.ImportedMethodReferenceAttribute.InteropFileType.ArmELF, c_FileSystemVolumeLibrary )] internal extern static HRESULT FindClose ( uint volumeHandle, uint findHandle ); [RT.ImportedMethodReference( RT.ImportedMethodReferenceAttribute.InteropFileType.ArmELF, c_FileSystemVolumeLibrary )] internal extern static HRESULT GetFileInfo ( uint volumeHandle, string path, ref FileInfo fileInfo, ref int found ); [RT.ImportedMethodReference( RT.ImportedMethodReferenceAttribute.InteropFileType.ArmELF, c_FileSystemVolumeLibrary )] internal extern static HRESULT CreateDirectory ( uint volumeHandle, string path ); [RT.ImportedMethodReference( RT.ImportedMethodReferenceAttribute.InteropFileType.ArmELF, c_FileSystemVolumeLibrary )] internal extern static HRESULT Move ( uint volumeHandle, string oldPath, string newPath ); [RT.ImportedMethodReference( RT.ImportedMethodReferenceAttribute.InteropFileType.ArmELF, c_FileSystemVolumeLibrary )] internal extern static HRESULT Delete ( uint volumeHandle, string path ); [RT.ImportedMethodReference( RT.ImportedMethodReferenceAttribute.InteropFileType.ArmELF, c_FileSystemVolumeLibrary )] internal extern static HRESULT GetAttributes ( uint volumeHandle, string path, ref uint attributes ); [RT.ImportedMethodReference( RT.ImportedMethodReferenceAttribute.InteropFileType.ArmELF, c_FileSystemVolumeLibrary )] internal extern static HRESULT SetAttributes ( uint volumeHandle, string path, uint attributes ); [RT.ImportedMethodReference( RT.ImportedMethodReferenceAttribute.InteropFileType.ArmELF, c_FileSystemVolumeLibrary )] internal extern static HRESULT GetDriverDetails ( uint volumeHandle, uint handle, ref StreamDriverDetails details ); [RT.ImportedMethodReference( RT.ImportedMethodReferenceAttribute.InteropFileType.ArmELF, c_FileSystemVolumeLibrary )] internal extern static HRESULT Open ( uint volumeHandle, string path, ref uint handle ); [RT.ImportedMethodReference( RT.ImportedMethodReferenceAttribute.InteropFileType.ArmELF, c_FileSystemVolumeLibrary )] internal extern static HRESULT Close ( uint volumeHandle, uint handle ); [RT.ImportedMethodReference( RT.ImportedMethodReferenceAttribute.InteropFileType.ArmELF, c_FileSystemVolumeLibrary )] internal extern static HRESULT Read ( uint volumeHandle, uint handle, byte[] buffer, int offset, int count, ref int bytesRead ); [RT.ImportedMethodReference( RT.ImportedMethodReferenceAttribute.InteropFileType.ArmELF, c_FileSystemVolumeLibrary )] internal extern static HRESULT Write ( uint volumeHandle, uint handle, byte[] buffer, int offset, int count, ref int bytesWritten ); [RT.ImportedMethodReference( RT.ImportedMethodReferenceAttribute.InteropFileType.ArmELF, c_FileSystemVolumeLibrary )] internal extern static HRESULT Flush ( uint volumeHandle, uint handle ); [RT.ImportedMethodReference( RT.ImportedMethodReferenceAttribute.InteropFileType.ArmELF, c_FileSystemVolumeLibrary )] internal extern static HRESULT Seek ( uint volumeHandle, uint handle, Int64 offset, uint origin, ref Int64 position ); [RT.ImportedMethodReference( RT.ImportedMethodReferenceAttribute.InteropFileType.ArmELF, c_FileSystemVolumeLibrary )] internal extern static HRESULT GetLength ( uint volumeHandle, uint handle, ref Int64 length ); [RT.ImportedMethodReference( RT.ImportedMethodReferenceAttribute.InteropFileType.ArmELF, c_FileSystemVolumeLibrary )] internal extern static HRESULT SetLength( uint volumeHandle, uint handle, Int64 length ); [RT.ImportedMethodReference( RT.ImportedMethodReferenceAttribute.InteropFileType.ArmELF, c_FileSystemVolumeLibrary )] internal extern static HRESULT GetName ( uint volumeHandle, char[] name, ref int nameLen ); [RT.ImportedMethodReference( RT.ImportedMethodReferenceAttribute.InteropFileType.ArmELF, c_FileSystemVolumeLibrary )] internal extern static HRESULT GetLabel ( uint volumeHandle, char[] label, ref int labelLen ); [RT.ImportedMethodReference( RT.ImportedMethodReferenceAttribute.InteropFileType.ArmELF, c_FileSystemVolumeLibrary )] internal extern static HRESULT GetFileSystem ( uint volumeHandle, char[] fileSystem, ref int fileSystemLen ); [RT.ImportedMethodReference( RT.ImportedMethodReferenceAttribute.InteropFileType.ArmELF, c_FileSystemVolumeLibrary )] internal extern static HRESULT GetSize ( uint volumeHandle, ref long availSize, ref long totalSize ); //--// //[RT.ImportedMethodReference( RT.ImportedMethodReferenceAttribute.InteropFileType.ArmELF, c_FileSystemVolumeLibrary )] //internal extern static bool ValidateStreamDriver(); //[RT.ImportedMethodReference( RT.ImportedMethodReferenceAttribute.InteropFileType.ArmELF, c_FileSystemVolumeLibrary )] //internal extern static bool ValidateFind(); }; internal class FileSystemVolumeList { // internal static bool InitializeVolumes(); // internal static bool UninitializeVolumes(); // internal static uint AddVolume( string nameSpace, uint serialNumber, uint deviceFlags, // BlockStorageDevice blockStorageDevice, uint volumeId, bool init ); // internal static bool RemoveVolume( FileSystemVolume fsv, bool uninit ); const string c_RamBSDriverLibrary = @"BlockStorageFileSystem.obj"; //[RT.ImportedMethodReference( RT.ImportedMethodReferenceAttribute.InteropFileType.ArmELF, c_RamBSDriverLibrary )] //internal extern static uint GetFirstVolume(); //[RT.ImportedMethodReference( RT.ImportedMethodReferenceAttribute.InteropFileType.ArmELF, c_RamBSDriverLibrary )] //internal extern static uint GetNextVolume( ref FileSystemVolume volume ); [RT.ImportedMethodReference( RT.ImportedMethodReferenceAttribute.InteropFileType.ArmELF, c_RamBSDriverLibrary )] internal extern static HRESULT GetVolumes( uint[] volume, ref int volumeCount ); //[RT.ImportedMethodReference( RT.ImportedMethodReferenceAttribute.InteropFileType.ArmELF, c_RamBSDriverLibrary )] //internal extern static uint GetNumVolumes(); [RT.ImportedMethodReference( RT.ImportedMethodReferenceAttribute.InteropFileType.ArmELF, c_RamBSDriverLibrary )] internal extern static uint FindVolume( string nameSpace, int namespaceLen ); [RT.ImportedMethodReference( RT.ImportedMethodReferenceAttribute.InteropFileType.ArmELF, c_RamBSDriverLibrary )] internal extern static void AddRamBlockStorageFileStream(); //[RT.ImportedMethodReference( RT.ImportedMethodReferenceAttribute.InteropFileType.ArmELF, c_FileSystemVolumeListLibrary )] //internal extern static bool Contains( uint volumeId ); }; } ================================================ FILE: Zelig/Zelig/RunTime/Zelig/Kernel/FrameworkOverrides_System/IO/Ports/BaseSerialStream.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // namespace Microsoft.Zelig.Runtime { using System; using System.Collections.Generic; using System.Threading; using System.Runtime.CompilerServices; using PORTS = System.IO.Ports; using TS = Microsoft.Zelig.Runtime.TypeSystem; public abstract class BaseSerialStream : System.IO.Ports.SerialStream { public struct Configuration { // // State // public readonly string PortName; public int BaudRate; public PORTS.Parity Parity; public int DataBits; public PORTS.StopBits StopBits; public int ReadBufferSize; public int WriteBufferSize; public int ReadTimeout; public int WriteTimeout; public PORTS.Handshake Handshake; public bool DtrEnable; public bool RtsEnable; public bool CtsEnable; public bool DiscardNull; public byte ParityReplace; public int TxPin; public int RxPin; public int CtsPin; public int RtsPin; // // Constructor Methods // public Configuration(string portName) { this.PortName = portName; this.BaudRate = 9600; this.Parity = PORTS.Parity.None; this.DataBits = 8; this.StopBits = PORTS.StopBits.One; this.ReadBufferSize = 256; this.WriteBufferSize = 256; this.ReadTimeout = Timeout.Infinite; this.WriteTimeout = Timeout.Infinite; this.Handshake = PORTS.Handshake.None; this.DtrEnable = false; this.RtsEnable = false; this.CtsEnable = false; this.DiscardNull = false; this.ParityReplace = 0; // Temporary variable here to avoid multiple virtual calls int invalidPin = HardwareProvider.Instance.InvalidPin; this.TxPin = invalidPin; this.RxPin = invalidPin; this.CtsPin = invalidPin; this.RtsPin = invalidPin; } } // // State // protected Configuration m_cfg; protected KernelCircularBuffer m_receiveQueue; protected KernelCircularBuffer m_transmitQueue; // // Constructor Methods // protected BaseSerialStream(ref Configuration cfg) { m_cfg = cfg; m_receiveQueue = new KernelCircularBuffer(cfg.ReadBufferSize); m_transmitQueue = new KernelCircularBuffer(cfg.WriteBufferSize); } // // Helper Methods // public override void DiscardInBuffer() { using (SmartHandles.InterruptState.Disable()) { m_receiveQueue.Clear(); } } public override void DiscardOutBuffer() { using (SmartHandles.InterruptState.Disable()) { m_transmitQueue.Clear(); } } public override int Read(byte[] array, int offset, int count, int timeout) { int got = 0; while (got < count) { byte val; if (!m_receiveQueue.DequeueBlocking(timeout, out val)) { if (timeout != 0) { throw new TimeoutException(); } break; } array[offset++] = val; got++; } return got; } public override int ReadByte(int timeout) { byte val; if (!m_receiveQueue.DequeueBlocking(timeout, out val)) { if (timeout != 0) { throw new TimeoutException(); } return -1; } return val; } public override void Write(byte[] array, int offset, int count, int timeout) { for (int pos = 0; pos < count; pos++) { if (!m_transmitQueue.EnqueueBlocking(timeout, array[offset])) { throw new TimeoutException(); } offset++; } } public override void WriteByte(byte value, int timeout) { if (!m_transmitQueue.EnqueueBlocking(timeout, value)) { throw new TimeoutException(); } } // TODO: Consider Yield or SpinWait // TODO: This also won't do anything as Write isn't currently async public override void Flush() { while (!m_transmitQueue.IsEmpty) { Thread.Sleep(0); } } // // Access Methods // public override int BaudRate { set { throw new NotImplementedException(); } } public override bool BreakState { get { throw new NotImplementedException(); } set { throw new NotImplementedException(); } } public override int DataBits { set { throw new NotImplementedException(); } } public override bool DiscardNull { set { throw new NotImplementedException(); } } public override bool DtrEnable { get { throw new NotImplementedException(); } set { throw new NotImplementedException(); } } public override System.IO.Ports.Handshake Handshake { set { throw new NotImplementedException(); } } public override System.IO.Ports.Parity Parity { set { throw new NotImplementedException(); } } public override byte ParityReplace { set { throw new NotImplementedException(); } } public override int ReadTimeout { get { return m_cfg.ReadTimeout; } set { m_cfg.ReadTimeout = value; } } public override bool RtsEnable { get { throw new NotImplementedException(); } set { throw new NotImplementedException(); } } public override System.IO.Ports.StopBits StopBits { set { throw new NotImplementedException(); } } public override int WriteTimeout { get { return m_cfg.WriteTimeout; } set { m_cfg.WriteTimeout = value; } } public override bool CDHolding { get { throw new NotImplementedException(); } } public override bool CtsHolding { get { throw new NotImplementedException(); } } public override bool DsrHolding { get { throw new NotImplementedException(); } } public override int BytesToRead { get { return m_receiveQueue.Count; } } public override int BytesToWrite { get { return m_transmitQueue.Count; } } } } ================================================ FILE: Zelig/Zelig/RunTime/Zelig/Kernel/FrameworkOverrides_System/IO/Ports/SerialPortImpl.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // namespace Microsoft.Zelig.Runtime { using System; using System.Collections.Generic; using System.Threading; using System.Runtime.CompilerServices; using TS = Microsoft.Zelig.Runtime.TypeSystem; [ExtendClass(typeof(System.IO.Ports.SerialPort),NoConstructors=true)] public class SerialPortImpl { // // Helper Methods // public static string[] GetPortNames() { return SerialPortsManager.Instance.GetPortNames(); } } } ================================================ FILE: Zelig/Zelig/RunTime/Zelig/Kernel/FrameworkOverrides_System/IO/Ports/SerialStreamImpl.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // namespace Microsoft.Zelig.Runtime { using System; using System.Collections.Generic; using System.Threading; using System.Runtime.CompilerServices; using TS = Microsoft.Zelig.Runtime.TypeSystem; [ExtendClass(typeof(System.IO.Ports.SerialStream), NoConstructors = true)] public class SerialStreamImpl { // // Helper Methods // internal static System.IO.Ports.SerialStream Create(string portName, int baudRate, System.IO.Ports.Parity parity, int dataBits, System.IO.Ports.StopBits stopBits, int readBufferSize, int writeBufferSize, int readTimeout, int writeTimeout, System.IO.Ports.Handshake handshake, bool dtrEnable, bool rtsEnable, bool discardNull, byte parityReplace) { var cfg = new BaseSerialStream.Configuration(portName) { BaudRate = baudRate, Parity = parity, DataBits = dataBits, StopBits = stopBits, ReadBufferSize = readBufferSize, WriteBufferSize = writeBufferSize, ReadTimeout = readTimeout, WriteTimeout = writeTimeout, Handshake = handshake, DtrEnable = dtrEnable, RtsEnable = rtsEnable, DiscardNull = discardNull, ParityReplace = parityReplace, }; return SerialPortsManager.Instance.Open(ref cfg); } } } ================================================ FILE: Zelig/Zelig/RunTime/Zelig/Kernel/FrameworkOverrides_System/Net/IPAddressImpl.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // namespace Microsoft.Zelig.Runtime { using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Net; [ExtendClass(typeof(IPAddress), NoConstructors = true)] public abstract class IPAddressImpl { public static string GetDefaultLocalAddressImpl() { return NetworkInterfaceProvider.Instance.GetDefaultLocalAddress(); } } } ================================================ FILE: Zelig/Zelig/RunTime/Zelig/Kernel/FrameworkOverrides_System/Net/NetworkInterfaceProvider.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // namespace Microsoft.Zelig.Runtime { using System; using System.Runtime.CompilerServices; [ImplicitInstance] [ForceDevirtualization] public abstract class NetworkInterfaceProvider { private sealed class EmptyNetworkInterfaceProvider : NetworkInterfaceProvider { public override int Connect(uint timeout) { throw new NotImplementedException(); } public override int Disconnect() { throw new NotImplementedException(); } public override string GetDefaultLocalAddress() { throw new NotImplementedException(); } public override string GetGatewayAddress() { throw new NotImplementedException(); } public override string GetIPAddress() { throw new NotImplementedException(); } public override string GetMacAddress() { throw new NotImplementedException(); } public override string GetMask() { throw new NotImplementedException(); } public override int GetNetworkInterfaceCount() { throw new NotImplementedException(); } public override int InitializeEthernet() { return -1; // Fail } public override int InitializeEthernet(string ipAddress, string mask, string gateway) { return -1; // Fail } public override uint IPv4AddressFromString(string ipAddress) { throw new NotImplementedException(); } public override void RemapInterrupts() { throw new NotImplementedException(); } } public abstract int InitializeEthernet(); public abstract int InitializeEthernet(string ipAddress, string mask, string gateway); public abstract int Connect(uint timeout); public abstract int Disconnect(); public abstract int GetNetworkInterfaceCount(); public abstract string GetIPAddress(); public abstract string GetMacAddress(); public abstract string GetGatewayAddress(); public abstract string GetMask(); public abstract uint IPv4AddressFromString(string ipAddress); public abstract string GetDefaultLocalAddress(); public abstract void RemapInterrupts(); //--// public static extern NetworkInterfaceProvider Instance { [SingletonFactory(Fallback = typeof(EmptyNetworkInterfaceProvider))] [MethodImpl(MethodImplOptions.InternalCall)] get; } } } ================================================ FILE: Zelig/Zelig/RunTime/Zelig/Kernel/FrameworkOverrides_System/Net/SocketNativeImpl.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // namespace Microsoft.Zelig.Runtime { [ExtendClass(typeof(Microsoft.Llilum.Net.SocketNative), NoConstructors = true)] public abstract class SocketNativeImpl { public static int socket(int family, int type, int protocol) { return SocketProvider.Instance.socket(family, type, protocol); } public static int bind(int socket, byte[] address) { return SocketProvider.Instance.bind(socket, address); } public static int connect(int socket, byte[] address, bool fThrowOnWouldBlock) { return SocketProvider.Instance.connect(socket, address, fThrowOnWouldBlock); } public static int send(int socket, byte[] buf, int offset, int count, int flags, int timeout_ms) { return SocketProvider.Instance.send(socket, buf, offset, count, flags, timeout_ms); } public static int recv(int socket, byte[] buf, int offset, int count, int flags, int timeout_ms) { return SocketProvider.Instance.recv(socket, buf, offset, count, flags, timeout_ms); } public static int close(int socket) { return SocketProvider.Instance.close(socket); } public static int listen(int socket, int backlog) { return SocketProvider.Instance.listen(socket, backlog); } public static int accept(int socket) { return SocketProvider.Instance.accept(socket); } public static void getaddrinfo(string name, out string canonicalName, out byte[][] addresses) { SocketProvider.Instance.getaddrinfo(name, out canonicalName, out addresses); } public static void shutdown(int socket, int how, out int err) { SocketProvider.Instance.shutdown(socket, how, out err); } public static int sendto(int socket, byte[] buf, int offset, int count, int flags, int timeout_ms, byte[] address) { return SocketProvider.Instance.sendto(socket, buf, offset, count, flags, timeout_ms, address); } public static int recvfrom(int socket, byte[] buf, int offset, int count, int flags, int timeout_ms, ref byte[] address) { return SocketProvider.Instance.recvfrom(socket, buf, offset, count, flags, timeout_ms, ref address); } public static void getpeername(int socket, out byte[] address) { SocketProvider.Instance.getpeername(socket, out address); } public static void getsockname(int socket, out byte[] address) { SocketProvider.Instance.getsockname(socket, out address); } public static void getsockopt(int socket, int level, int optname, byte[] optval, out uint optlen) { SocketProvider.Instance.getsockopt(socket, level, optname, optval, out optlen); } public static void setsockopt(int socket, int level, int optname, byte[] optval) { SocketProvider.Instance.setsockopt(socket, level, optname, optval); } public static bool poll(int socket, int mode, int microSeconds) { return SocketProvider.Instance.poll(socket, mode, microSeconds); } public static void ioctl(int socket, uint cmd, ref uint arg) { SocketProvider.Instance.ioctl(socket, cmd, ref arg); } } } ================================================ FILE: Zelig/Zelig/RunTime/Zelig/Kernel/FrameworkOverrides_System/Net/SocketProvider.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // namespace Microsoft.Zelig.Runtime { using System; using System.Runtime.CompilerServices; [ImplicitInstance] [ForceDevirtualization] public abstract class SocketProvider { private sealed class EmptySocketProvider : SocketProvider { public override int accept(int socket) { throw new NotImplementedException(); } public override int bind(int socket, byte[] address) { throw new NotImplementedException(); } public override int close(int socket) { throw new NotImplementedException(); } public override int connect(int socket, byte[] address, bool fThrowOnWouldBlock) { throw new NotImplementedException(); } public override int getaddrinfo(string name, out string canonicalName, out byte[][] addresses) { throw new NotImplementedException(); } public override int getpeername(int socket, out byte[] address) { throw new NotImplementedException(); } public override int getsockname(int socket, out byte[] address) { throw new NotImplementedException(); } public override int getsockopt(int socket, int level, int optname, byte[] optval, out uint optlen) { throw new NotImplementedException(); } public override int ioctl(int socket, uint cmd, ref uint arg) { throw new NotImplementedException(); } public override int listen(int socket, int backlog) { throw new NotImplementedException(); } public override bool poll(int socket, int mode, int microSeconds) { throw new NotImplementedException(); } public override int recv(int socket, byte[] buf, int offset, int count, int flags, int timeout_ms) { throw new NotImplementedException(); } public override int recvfrom(int socket, byte[] buf, int offset, int count, int flags, int timeout_ms, ref byte[] address) { throw new NotImplementedException(); } public override int send(int socket, byte[] buf, int offset, int count, int flags, int timeout_ms) { throw new NotImplementedException(); } public override int sendto(int socket, byte[] buf, int offset, int count, int flags, int timeout_ms, byte[] address) { throw new NotImplementedException(); } public override int setsockopt(int socket, int level, int optname, byte[] optval) { throw new NotImplementedException(); } public override void shutdown(int socket, int how, out int err) { throw new NotImplementedException(); } public override int socket(int family, int type, int protocol) { throw new NotImplementedException(); } } public abstract int socket(int family, int type, int protocol); public abstract int bind(int socket, byte[] address); public abstract int connect(int socket, byte[] address, bool fThrowOnWouldBlock); public abstract int send(int socket, byte[] buf, int offset, int count, int flags, int timeout_ms); public abstract int recv(int socket, byte[] buf, int offset, int count, int flags, int timeout_ms); public abstract int close(int socket); public abstract int listen(int socket, int backlog); public abstract int accept(int socket); //Non standard non-blocking api public abstract int getaddrinfo(string name, out string canonicalName, out byte[][] addresses); public abstract void shutdown(int socket, int how, out int err); public abstract int sendto(int socket, byte[] buf, int offset, int count, int flags, int timeout_ms, byte[] address); public abstract int recvfrom(int socket, byte[] buf, int offset, int count, int flags, int timeout_ms, ref byte[] address); public abstract int getpeername(int socket, out byte[] address); public abstract int getsockname(int socket, out byte[] address); public abstract int getsockopt(int socket, int level, int optname, byte[] optval, out uint optlen); public abstract int setsockopt(int socket, int level, int optname, byte[] optval); public abstract bool poll(int socket, int mode, int microSeconds); public abstract int ioctl(int socket, uint cmd, ref uint arg); public static extern SocketProvider Instance { [SingletonFactory(Fallback = typeof(EmptySocketProvider))] [MethodImpl(MethodImplOptions.InternalCall)] get; } } } ================================================ FILE: Zelig/Zelig/RunTime/Zelig/Kernel/FrameworkOverrides_Windows/Devices/Adc/AdcControllerImpl.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // namespace Microsoft.Zelig.Runtime { using Windows.Devices.Adc; using Microsoft.Llilum.Devices.Adc; [ExtendClass(typeof(AdcController), NoConstructors = true)] public class AdcControllerImpl { public static IAdcChannelInfoUwp GetAdcProviderInfo() { return AdcProviderUwp.Instance.GetAdcChannelInfo(); } } } ================================================ FILE: Zelig/Zelig/RunTime/Zelig/Kernel/FrameworkOverrides_Windows/Devices/Adc/AdcProviderUwp.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // namespace Microsoft.Zelig.Runtime { using System; using System.Collections; using System.Runtime.CompilerServices; using Microsoft.Llilum.Devices.Adc; public class AdcChannelInfoUwp : IAdcChannelInfoUwp { public int[] AdcPinNumbers { get; set; } public int MaxValue { get; set; } public int MinValue { get; set; } public int ResolutionInBits { get; set; } } [ImplicitInstance] [ForceDevirtualization] public abstract class AdcProviderUwp { private sealed class EmptyAdcProviderUwp : AdcProviderUwp { public override AdcChannelInfoUwp GetAdcChannelInfo() { throw new NotImplementedException(); } } public abstract AdcChannelInfoUwp GetAdcChannelInfo(); public static extern AdcProviderUwp Instance { [SingletonFactory(Fallback = typeof(EmptyAdcProviderUwp))] [MethodImpl(MethodImplOptions.InternalCall)] get; } } } ================================================ FILE: Zelig/Zelig/RunTime/Zelig/Kernel/FrameworkOverrides_Windows/Devices/I2c/I2cDeviceImplUwp.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // namespace Microsoft.Zelig.Runtime { using Windows.Devices.I2c; using Llilum = Microsoft.Llilum.Devices.I2c; [ExtendClass(typeof(I2cDevice), NoConstructors = true)] public class I2cDeviceImplUwp { /// /// Returns an array of I2C channel identifiers /// /// I2C channel identifiers public static string[] GetI2cChannels() { return I2cProviderUwp.Instance.GetI2cChannels(); } public static Llilum.II2cChannelInfo GetI2cChannelInfo(string busId) { return I2cProviderUwp.Instance.GetI2cChannelInfo(busId); } } } ================================================ FILE: Zelig/Zelig/RunTime/Zelig/Kernel/FrameworkOverrides_Windows/Devices/I2c/I2cProviderUwp.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // namespace Microsoft.Zelig.Runtime { using System; using System.Collections; using System.Runtime.CompilerServices; using Microsoft.Llilum.Devices.I2c; [ImplicitInstance] [ForceDevirtualization] public abstract class I2cProviderUwp { sealed class EmptyI2cProviderUwp : I2cProviderUwp { public override I2cChannelInfo GetI2cChannelInfo(string busId) { throw new NotImplementedException(); } public override string[] GetI2cChannels() { throw new NotImplementedException(); } } public abstract I2cChannelInfo GetI2cChannelInfo(string busId); public abstract string[] GetI2cChannels(); public static extern I2cProviderUwp Instance { [SingletonFactory(Fallback = typeof(EmptyI2cProviderUwp))] [MethodImpl(MethodImplOptions.InternalCall)] get; } } } ================================================ FILE: Zelig/Zelig/RunTime/Zelig/Kernel/FrameworkOverrides_Windows/Devices/Pwm/PwmControllerImpl.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // namespace Microsoft.Zelig.Runtime { using Windows.Devices.Pwm; using Microsoft.Llilum.Devices.Pwm; [ExtendClass(typeof(PwmController), NoConstructors = true)] public class PwmControllerImpl { public static IPwmChannelInfoUwp GetPwmProviderInfo() { return PwmProviderUwp.Instance.GetPwmChannelInfo(); } } } ================================================ FILE: Zelig/Zelig/RunTime/Zelig/Kernel/FrameworkOverrides_Windows/Devices/Pwm/PwmProviderUwp.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // namespace Microsoft.Zelig.Runtime { using System; using System.Collections; using System.Runtime.CompilerServices; using Microsoft.Llilum.Devices.Pwm; public class PwmChannelInfoUwp : IPwmChannelInfoUwp { public int MaxFrequency { get; set; } public int MinFrequency { get; set; } public int[] PwmPinNumbers { get; set; } } [ImplicitInstance] [ForceDevirtualization] public abstract class PwmProviderUwp { private sealed class EmptyPwmProviderUwp : PwmProviderUwp { public override PwmChannelInfoUwp GetPwmChannelInfo() { throw new NotImplementedException(); } } public abstract PwmChannelInfoUwp GetPwmChannelInfo(); public static extern PwmProviderUwp Instance { [SingletonFactory(Fallback = typeof(EmptyPwmProviderUwp))] [MethodImpl(MethodImplOptions.InternalCall)] get; } } } ================================================ FILE: Zelig/Zelig/RunTime/Zelig/Kernel/FrameworkOverrides_Windows/Devices/Spi/SpiDeviceImplUwp.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // namespace Microsoft.Zelig.Runtime { using Llilum = Microsoft.Llilum.Devices.Spi; using Windows.Devices.Spi; using Windows.Devices.Spi.Provider; //--// [ExtendClass( typeof( SpiDevice ), NoConstructors = true )] public class SpiDeviceImplUwp { /// /// Returns SPI channel characteristics that are defined in each Board provider /// /// SPI bus identifier public static Llilum.ISpiChannelInfoUwp GetSpiChannelInfo( string busId ) { return SpiProviderUwp.Instance.GetSpiChannelInfo(busId); } /// /// Gets the string identifiers of SPI busses /// /// Array of SPI busIds public static string[] GetSpiChannels() { return SpiProviderUwp.Instance.GetSpiChannels(); } } } ================================================ FILE: Zelig/Zelig/RunTime/Zelig/Kernel/FrameworkOverrides_Windows/Devices/Spi/SpiProviderUwp.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // namespace Microsoft.Zelig.Runtime { using System; using System.Collections; using System.Runtime.CompilerServices; using Microsoft.Llilum.Devices.Spi; //--// public class SpiChannelInfoUwp : ISpiChannelInfoUwp { public int ChipSelectLines { get; set; } public int MaxFreq { get; set; } public int MinFreq { get; set; } public bool Supports16 { get; set; } // In order for the Board assemblies to not take a dependency on the framework, // we need to set the channel info through a class-specific property and // expose it through the regular interface public SpiChannelInfo ChannelInfoKernel { get; set; } public ISpiChannelInfo ChannelInfo { get { return ChannelInfoKernel; } } } [ImplicitInstance] [ForceDevirtualization] public abstract class SpiProviderUwp { private sealed class EmptySpiProviderUwp : SpiProviderUwp { public override SpiChannelInfoUwp GetSpiChannelInfo(string busId) { throw new NotImplementedException(); } public override string[] GetSpiChannels() { throw new NotImplementedException(); } } public abstract SpiChannelInfoUwp GetSpiChannelInfo(string busId); public abstract string[] GetSpiChannels(); public static extern SpiProviderUwp Instance { [SingletonFactory(Fallback = typeof(EmptySpiProviderUwp))] [MethodImpl(MethodImplOptions.InternalCall)] get; } } } ================================================ FILE: Zelig/Zelig/RunTime/Zelig/Kernel/GarbageCollectors/ConservativeMarkAndSweepCollector.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // namespace Microsoft.Zelig.Runtime { using System; public abstract class ConservativeMarkAndSweepCollector : MarkAndSweepCollector { class ConservativeStackWalker : MarkAndSweepStackWalker { ConservativeMarkAndSweepCollector m_owner; internal ConservativeStackWalker( ConservativeMarkAndSweepCollector owner ) { m_owner = owner; } public unsafe void Process( Processor.Context ctx ) { // Go through each entry in the stack UIntPtr* end = (UIntPtr*)ctx.BaseStackPointer.ToUInt32( ); UIntPtr* current = (UIntPtr*)ctx.StackPointer.ToUInt32( ); while(current < end) { m_owner.VisitInternalPointer( *current ); current++; } } } //--// protected override int MarkStackForObjectsSize { get { return 256; } } protected override int MarkStackForArraysSize { get { return 32; } } //--// protected override MarkAndSweepStackWalker CreateStackWalker( ) { return new ConservativeStackWalker( this ); } //--// protected override bool IsThisAGoodPlaceToStopTheWorld( ) { return true; } } } ================================================ FILE: Zelig/Zelig/RunTime/Zelig/Kernel/GarbageCollectors/MarkAndSweepCollector.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // //#define GC_PRECISE_PROFILING //#define DEBUG_MARK_SWEEP namespace Microsoft.Zelig.Runtime { using System; using System.Runtime.CompilerServices; using TS = Microsoft.Zelig.Runtime.TypeSystem; public abstract class MarkAndSweepCollector : GarbageCollectionManager { protected interface MarkAndSweepStackWalker { void Process( Processor.Context ctx ); } //--// struct MarkStackForArrays { // // State // private UIntPtr m_address; private uint m_elementSize; private int m_numOfElements; private TS.VTable m_vTableElement; // // Helper Methods // #if !GC_PRECISE_PROFILING [Inline] #endif internal unsafe void Push( ArrayImpl array , uint elementSize , int numOfElements , TS.VTable vTableElement ) { m_address = new UIntPtr( array.GetDataPointer() ); m_elementSize = elementSize; m_numOfElements = numOfElements; m_vTableElement = vTableElement; } #if !GC_PRECISE_PROFILING [Inline] #endif internal unsafe void Visit( MarkAndSweepCollector owner ) { UIntPtr address = m_address; TS.VTable vTable = m_vTableElement; if(--m_numOfElements == 0) { // // Pop entry. // m_address = new UIntPtr(); m_vTableElement = null; owner.m_markStackForArrays_Pos--; } else { // // Move to next element. // m_address = AddressMath.Increment( m_address, m_elementSize ); } if(vTable != null) { owner.VisitHeapObjectFields( address, vTable ); } else { UIntPtr* ptr = (UIntPtr*)address.ToPointer(); UIntPtr obj = ptr[0]; if(obj != UIntPtr.Zero) { owner.VisitHeapObject( obj ); } } } } // // State // private OutOfMemoryException m_outOfMemoryException; private MarkAndSweepStackWalker m_stackWalker; private bool m_fFirstLevel; private UIntPtr[] m_maskStackForObjects; private int m_maskStackForObjects_Pos; private MarkStackForArrays[] m_markStackForArrays; private int m_markStackForArrays_Pos; private ObjectHeader.GarbageCollectorFlags m_markForNonHeap; private uint[] m_trackFreeBlocks; private int m_perf_gapCount; private int m_perf_freeCount; private int m_perf_deadCount; private int m_perf_objectCount; private int m_perf_stat_calls; private uint m_perf_stat_freeMem; private long m_perf_time_baseline; private long m_perf_time_start; private long m_perf_time_walk; private long m_perf_time_global; private long m_perf_time_sweep; private long m_perf_time_ret; // // Helper Methods // protected virtual int MarkStackForObjectsSize { get { return 1024; } } protected virtual int MarkStackForArraysSize { get { return 128; } } //--// protected abstract MarkAndSweepStackWalker CreateStackWalker( ); public unsafe override void InitializeGarbageCollectionManager() { m_outOfMemoryException = new OutOfMemoryException(); m_stackWalker = CreateStackWalker(); m_maskStackForObjects = new UIntPtr [ MarkStackForObjectsSize ]; m_markStackForArrays = new MarkStackForArrays[ MarkStackForArraysSize ]; if(Configuration.TraceFreeBlocks) { m_trackFreeBlocks = new uint[32]; } //--// foreach(var handler in this.ExtensionHandlers) { handler.Initialize(); } //--// MemorySegment* heapLow = null; MemorySegment* heapHigh = null; for(MemorySegment* heap = MemoryManager.Instance.StartOfHeap; heap != null; heap = heap->Next) { if(heapLow == null || AddressMath.IsGreaterThan( heapLow->Beginning, heap->Beginning )) { heapLow = heap; } if(heapHigh == null || AddressMath.IsLessThan( heapHigh->End, heap->End )) { heapHigh = heap; } } BugCheck.Assert( heapLow != null && heapHigh != null, BugCheck.StopCode.NoMemory ); BrickTable.Instance.Initialize( heapLow->Beginning.ToUInt32(), heapHigh->End.ToUInt32() ); RebuildBrickTable(); if(Configuration.ValidateHeap) { VerifyBrickTable(); } } [Inline] public override void NotifyNewObject( UIntPtr ptr , uint size ) { BrickTable.Instance.MarkObject( ptr, size ); } public override UIntPtr FindObject( UIntPtr interiorPtr ) { UIntPtr address = BrickTable.Instance.FindLowerBoundForObjectPointer( interiorPtr ); if(address != UIntPtr.Zero) { while(true) { ObjectHeader oh = ObjectHeader.CastAsObjectHeader( address ); ObjectHeader.GarbageCollectorFlags flags = oh.GarbageCollectorState; switch(flags) { case ObjectHeader.GarbageCollectorFlags.FreeBlock | ObjectHeader.GarbageCollectorFlags.Unmarked: case ObjectHeader.GarbageCollectorFlags.FreeBlock | ObjectHeader.GarbageCollectorFlags.Marked : { UIntPtr nextAddress = oh.GetNextObjectPointer(); if(AddressMath.IsLessThan( interiorPtr, nextAddress )) { // // Don't return the address of a heap free block. // return UIntPtr.Zero; } address = nextAddress; } break; case ObjectHeader.GarbageCollectorFlags.GapPlug | ObjectHeader.GarbageCollectorFlags.Unmarked: case ObjectHeader.GarbageCollectorFlags.GapPlug | ObjectHeader.GarbageCollectorFlags.Marked : address = AddressMath.Increment( address, sizeof(uint) ); break; case ObjectHeader.GarbageCollectorFlags.ReadOnlyObject | ObjectHeader.GarbageCollectorFlags.Unmarked: case ObjectHeader.GarbageCollectorFlags.ReadOnlyObject | ObjectHeader.GarbageCollectorFlags.Marked : BugCheck.Raise( BugCheck.StopCode.HeapCorruptionDetected ); return UIntPtr.Zero; case ObjectHeader.GarbageCollectorFlags.UnreclaimableObject | ObjectHeader.GarbageCollectorFlags.Unmarked: case ObjectHeader.GarbageCollectorFlags.UnreclaimableObject | ObjectHeader.GarbageCollectorFlags.Marked : BugCheck.Raise( BugCheck.StopCode.HeapCorruptionDetected ); return UIntPtr.Zero; case ObjectHeader.GarbageCollectorFlags.NormalObject | ObjectHeader.GarbageCollectorFlags.Unmarked: case ObjectHeader.GarbageCollectorFlags.NormalObject | ObjectHeader.GarbageCollectorFlags.Marked : case ObjectHeader.GarbageCollectorFlags.SpecialHandlerObject | ObjectHeader.GarbageCollectorFlags.Unmarked: case ObjectHeader.GarbageCollectorFlags.SpecialHandlerObject | ObjectHeader.GarbageCollectorFlags.Marked: case ObjectHeader.GarbageCollectorFlags.AllocatedRawBytes | ObjectHeader.GarbageCollectorFlags.Unmarked: case ObjectHeader.GarbageCollectorFlags.AllocatedRawBytes | ObjectHeader.GarbageCollectorFlags.Marked: { UIntPtr nextAddress = oh.GetNextObjectPointer(); if(AddressMath.IsLessThan( interiorPtr, nextAddress )) { return oh.Pack( ).ToPointer( ); } address = nextAddress; } break; default: BugCheck.Raise( BugCheck.StopCode.HeapCorruptionDetected ); return UIntPtr.Zero; } } } return UIntPtr.Zero; } public override uint Collect() { #if DEBUG_MARK_SWEEP BugCheck.Log( "Collecting on Thread 0x%x", (int)ObjectHeader.Unpack( ThreadManager.Instance.CurrentThread ).ToPointer( ) ); #endif if(Configuration.CollectPerformanceStatistics) { m_perf_stat_calls++; m_perf_time_baseline = System.Diagnostics.Stopwatch.GetTimestamp(); } uint mem; long gcTime; // Take the memory manager lock so we make sure there's no in-process memory allocation as we // mark and sweep the memory. using(SmartHandles.YieldLockHolder hnd = new SmartHandles.YieldLockHolder( MemoryManager.Lock )) { while(true) { using(SmartHandles.InterruptState hnd2 = SmartHandles.InterruptState.Disable()) { if(IsThisAGoodPlaceToStopTheWorld()) { if(Configuration.CollectPerformanceStatistics) { m_perf_time_start = System.Diagnostics.Stopwatch.GetTimestamp() - m_perf_time_baseline; } long gc_start = 0; long gc_stop = 0; if(Configuration.CollectMinimalPerformanceStatistics) { gc_start = System.Diagnostics.Stopwatch.GetTimestamp(); } StartCollection(); if(Configuration.CollectMinimalPerformanceStatistics) { gc_stop = System.Diagnostics.Stopwatch.GetTimestamp(); } gcTime = gc_stop - gc_start; mem = MemoryManager.Instance.AvailableMemory; if(Configuration.CollectPerformanceStatistics) { m_perf_time_ret = System.Diagnostics.Stopwatch.GetTimestamp() - m_perf_time_baseline; m_perf_stat_freeMem = mem; } break; } } ThreadImpl.CurrentThread.Yield(); } } foreach(var handler in this.ExtensionHandlers) { handler.RestartExecution(); } DumpFreeBlockTracking(); if(Configuration.CollectMinimalPerformanceStatistics) { BugCheck.WriteLineFormat( "GC: Free mem: {0} Time: {1}msec", mem, ToMilliseconds( gcTime ) ); } if(Configuration.CollectPerformanceStatistics) { BugCheck.WriteLineFormat( "m_perf_gapCount : {0,9}", m_perf_gapCount ); BugCheck.WriteLineFormat( "m_perf_freeCount : {0,9}", m_perf_freeCount ); BugCheck.WriteLineFormat( "m_perf_deadCount : {0,9}", m_perf_deadCount ); BugCheck.WriteLineFormat( "m_perf_objectCount: {0,9}", m_perf_objectCount ); BugCheck.WriteLineFormat( "m_perf_time_start : {0}msec", ToMilliseconds( m_perf_time_start ) ); BugCheck.WriteLineFormat( "m_perf_time_walk : {0}msec", ToMilliseconds( m_perf_time_walk ) ); BugCheck.WriteLineFormat( "m_perf_time_global: {0}msec", ToMilliseconds( m_perf_time_global ) ); BugCheck.WriteLineFormat( "m_perf_time_sweep : {0}msec", ToMilliseconds( m_perf_time_sweep ) ); BugCheck.WriteLineFormat( "m_perf_time_ret : {0}msec", ToMilliseconds( m_perf_time_ret ) ); } return mem; } private static int ToMilliseconds( long ticks ) { return (int)(1000.0 * ticks / System.Diagnostics.Stopwatch.Frequency); } public override long GetTotalMemory() { return MemoryManager.Instance.AllocatedMemory; } public override void ThrowOutOfMemory( TS.VTable vTable ) { throw m_outOfMemoryException; } public override bool IsMarked( object obj ) { if(obj == null) { return true; } ObjectHeader oh = ObjectHeader.Unpack( obj ); ObjectHeader.GarbageCollectorFlags flags = oh.GarbageCollectorState; switch(flags) { case ObjectHeader.GarbageCollectorFlags.ReadOnlyObject | ObjectHeader.GarbageCollectorFlags.Unmarked: case ObjectHeader.GarbageCollectorFlags.ReadOnlyObject | ObjectHeader.GarbageCollectorFlags.Marked : case ObjectHeader.GarbageCollectorFlags.UnreclaimableObject | ObjectHeader.GarbageCollectorFlags.Unmarked: case ObjectHeader.GarbageCollectorFlags.UnreclaimableObject | ObjectHeader.GarbageCollectorFlags.Marked : return true; case ObjectHeader.GarbageCollectorFlags.NormalObject | ObjectHeader.GarbageCollectorFlags.Unmarked: case ObjectHeader.GarbageCollectorFlags.SpecialHandlerObject | ObjectHeader.GarbageCollectorFlags.Unmarked: return false; case ObjectHeader.GarbageCollectorFlags.NormalObject | ObjectHeader.GarbageCollectorFlags.Marked : case ObjectHeader.GarbageCollectorFlags.SpecialHandlerObject | ObjectHeader.GarbageCollectorFlags.Marked : return true; default: BugCheck.Raise( BugCheck.StopCode.HeapCorruptionDetected ); return false; } } public override void ExtendMarking( object obj ) { var objImpl = (ObjectImpl)obj; if(objImpl != null) { VisitHeapObject( objImpl.ToPointer() ); } } //--// protected virtual bool IsThisAGoodPlaceToStopTheWorld() { ThreadImpl thisThread = ThreadImpl.CurrentThread; Processor.Context ctx = thisThread.ThrowContext; // Reuse the throw context for the current thread to unwind the stack. // // TODO: LT72: Only the RT.Threadmanager can implement this method correctly at this time // ThreadManager tm = ThreadManager.Instance; for(KernelNode< ThreadImpl > node = tm.StartOfForwardWalkThroughAllThreads; node.IsValidForForwardMove; node = node.Next) { ThreadImpl thread = node.Target; if(thread == thisThread) { continue; } if(thread.IsAtSafePoint( ctx ) == false) { return false; } } return true; } private void StartCollection() { m_fFirstLevel = true; m_maskStackForObjects_Pos = -1; m_markStackForArrays_Pos = -1; m_markForNonHeap ^= ObjectHeader.GarbageCollectorFlags.Marked; foreach(var handler in this.ExtensionHandlers) { handler.StartOfMarkPhase( this ); } WalkStackFrames(); if(Configuration.CollectPerformanceStatistics) { m_perf_time_walk = System.Diagnostics.Stopwatch.GetTimestamp() - m_perf_time_baseline; } MarkGlobalRoot(); ProcessMarkStack(); foreach(var handler in this.ExtensionHandlers) { handler.EndOfMarkPhase( this ); } if(Configuration.CollectPerformanceStatistics) { m_perf_time_global = System.Diagnostics.Stopwatch.GetTimestamp() - m_perf_time_baseline; } foreach(var handler in this.ExtensionHandlers) { handler.StartOfSweepPhase( this ); } Sweep(); foreach(var handler in this.ExtensionHandlers) { handler.EndOfSweepPhase( this ); } if(Configuration.CollectPerformanceStatistics) { m_perf_time_sweep = System.Diagnostics.Stopwatch.GetTimestamp() - m_perf_time_baseline; } if(Configuration.ValidateHeap) { VerifyBrickTable(); } } protected virtual void WalkStackFrames() { ThreadImpl thisThread = ThreadImpl.CurrentThread; Processor.Context ctx = thisThread.ThrowContext; // Reuse the throw context for the current thread to unwind the stack. // // TODO: LT72: Only the RT.Threadmanager can implement this method correctly at this time // ThreadManager tm = ThreadManager.Instance; for(KernelNode< ThreadImpl > node = tm.StartOfForwardWalkThroughAllThreads; node.IsValidForForwardMove; node = node.Next) { ThreadImpl thread = node.Target; if(thread == thisThread) { ctx.Populate(); } else { ctx.Populate( thread.SwappedOutContext ); } #if DEBUG_MARK_SWEEP BugCheck.Log( "Walking thread stack 0x%x, 0x%x -> 0x%x", (int)ObjectHeader.Unpack( thread ).ToPointer( ), (int)ctx.StackPointer, (int)ctx.BaseStackPointer ); #endif m_stackWalker.Process( ctx ); } } private void MarkGlobalRoot() { object root = TS.GlobalRoot.Instance; UIntPtr address = ((ObjectImpl)root).ToPointer(); VisitHeapObject( address ); } private unsafe void Sweep() { ResetFreeBlockTracking(); var brickTable = BrickTable.Instance; brickTable.Reset(); if(Configuration.CollectPerformanceStatistics) { m_perf_gapCount = 0; m_perf_freeCount = 0; m_perf_deadCount = 0; m_perf_objectCount = 0; } for(MemorySegment* heap = MemoryManager.Instance.StartOfHeap; heap != null; heap = heap->Next) { UIntPtr address = heap->FirstBlock; UIntPtr end = heap->End; bool fLastWasFree = false; UIntPtr freeStart = UIntPtr.Zero; heap->FirstFreeBlock = null; heap->LastFreeBlock = null; while(AddressMath.IsLessThan( address, end )) { ObjectHeader oh = ObjectHeader.CastAsObjectHeader( address ); ObjectHeader.GarbageCollectorFlags flags = oh.GarbageCollectorState; bool fFree = true; UIntPtr addressNext; switch(flags) { case ObjectHeader.GarbageCollectorFlags.FreeBlock | ObjectHeader.GarbageCollectorFlags.Unmarked: case ObjectHeader.GarbageCollectorFlags.FreeBlock | ObjectHeader.GarbageCollectorFlags.Marked : if(Configuration.CollectPerformanceStatistics) { m_perf_freeCount++; } addressNext = oh.GetNextObjectPointer(); break; case ObjectHeader.GarbageCollectorFlags.GapPlug | ObjectHeader.GarbageCollectorFlags.Unmarked: case ObjectHeader.GarbageCollectorFlags.GapPlug | ObjectHeader.GarbageCollectorFlags.Marked : if(Configuration.CollectPerformanceStatistics) { m_perf_gapCount++; } addressNext = AddressMath.Increment( address, sizeof(uint) ); break; case ObjectHeader.GarbageCollectorFlags.ReadOnlyObject | ObjectHeader.GarbageCollectorFlags.Unmarked: case ObjectHeader.GarbageCollectorFlags.ReadOnlyObject | ObjectHeader.GarbageCollectorFlags.Marked : BugCheck.Raise( BugCheck.StopCode.HeapCorruptionDetected ); return; case ObjectHeader.GarbageCollectorFlags.UnreclaimableObject | ObjectHeader.GarbageCollectorFlags.Unmarked: case ObjectHeader.GarbageCollectorFlags.UnreclaimableObject | ObjectHeader.GarbageCollectorFlags.Marked : BugCheck.Raise( BugCheck.StopCode.HeapCorruptionDetected ); return; case ObjectHeader.GarbageCollectorFlags.NormalObject | ObjectHeader.GarbageCollectorFlags.Unmarked: case ObjectHeader.GarbageCollectorFlags.AllocatedRawBytes | ObjectHeader.GarbageCollectorFlags.Unmarked: if(Configuration.CollectPerformanceStatistics) { m_perf_deadCount++; } #if DEBUG_MARK_SWEEP BugCheck.Log( "Object swept up: 0x%08x, size: %d", (int)oh.ToPointer( ), (int)oh.TotalSize ); String name; if(flags == ObjectHeader.GarbageCollectorFlags.AllocatedRawBytes) { name = ""; } else { var type = oh.VirtualTable.TypeInfo; if(type is TS.SzArrayReferenceTypeRepresentation) { var arrayType = (TS.SzArrayReferenceTypeRepresentation)type; BugCheck.Log( "Array of:" ); name = arrayType.UnderlyingType.Name ?? ""; } else { name = type?.Name ?? ""; } } BugCheck.Log( name ); #endif addressNext = oh.GetNextObjectPointer(); break; case ObjectHeader.GarbageCollectorFlags.NormalObject | ObjectHeader.GarbageCollectorFlags.Marked : case ObjectHeader.GarbageCollectorFlags.AllocatedRawBytes | ObjectHeader.GarbageCollectorFlags.Marked : if(Configuration.CollectPerformanceStatistics) { m_perf_objectCount++; } addressNext = oh.GetNextObjectPointer(); oh.GarbageCollectorState = (flags & ~ObjectHeader.GarbageCollectorFlags.Marked); brickTable.MarkObject( address, AddressMath.RangeSize( address, addressNext ) ); fFree = false; break; case ObjectHeader.GarbageCollectorFlags.SpecialHandlerObject | ObjectHeader.GarbageCollectorFlags.Unmarked: if(Configuration.CollectPerformanceStatistics) { m_perf_deadCount++; } addressNext = oh.GetNextObjectPointer(); break; case ObjectHeader.GarbageCollectorFlags.SpecialHandlerObject | ObjectHeader.GarbageCollectorFlags.Marked : { if(Configuration.CollectPerformanceStatistics) { m_perf_objectCount++; } addressNext = oh.GetNextObjectPointer(); var ext = FindExtensionHandler( oh.VirtualTable ); if(ext == null) { BugCheck.Raise( BugCheck.StopCode.HeapCorruptionDetected ); } else { ext.Sweep( this, oh.Pack() ); } oh.GarbageCollectorState = (flags & ~ObjectHeader.GarbageCollectorFlags.Marked); brickTable.MarkObject( address, AddressMath.RangeSize( address, addressNext ) ); fFree = false; break; } default: BugCheck.Raise( BugCheck.StopCode.HeapCorruptionDetected ); return; } if(fLastWasFree != fFree) { if(fFree) { freeStart = address; } else { TrackFreeBlock( freeStart, address ); heap->LinkNewFreeBlock( freeStart, address ); } fLastWasFree = fFree; } address = addressNext; } if(fLastWasFree) { TrackFreeBlock( freeStart, end ); heap->LinkNewFreeBlock( freeStart, end ); } } } //--// private void ResetFreeBlockTracking() { if(Configuration.TraceFreeBlocks) { Array.Clear( m_trackFreeBlocks, 0, m_trackFreeBlocks.Length ); } } private void TrackFreeBlock( UIntPtr start , UIntPtr end ) { if(Configuration.TraceFreeBlocks) { uint size = AddressMath.RangeSize( start, end ); for(int i = 0; i < 32; i++) { if(size < (1u << i)) { m_trackFreeBlocks[i]++; break; } } } } private void DumpFreeBlockTracking() { if(Configuration.TraceFreeBlocks) { for(int i = 0; i < 32; i++) { if(m_trackFreeBlocks[i] != 0) { BugCheck.WriteLineFormat( "Size: {0,9} = {1}", 1u << i, m_trackFreeBlocks[i] ); } } } } //--// [NoInline] protected void VisitInternalPointer( UIntPtr address ) { VisitInternalPointerInline( address ); } [NoInline] protected void VisitHeapObject( UIntPtr address ) { VisitHeapObjectInline( address ); } #if !GC_PRECISE_PROFILING [Inline] #endif private void VisitInternalPointerInline( UIntPtr address ) { UIntPtr objAddress = FindObject( address ); if(objAddress != UIntPtr.Zero) { VisitHeapObject( objAddress ); } } #if !GC_PRECISE_PROFILING [Inline] #endif private void VisitHeapObjectInline( UIntPtr address ) { if(Configuration.ValidateHeap) { BugCheck.Assert( MemoryManager.Instance.RefersToMemory( address ), BugCheck.StopCode.NotAMemoryReference ); } ObjectHeader oh = ObjectHeader.Unpack( ObjectImpl.FromPointer( address ) ); ObjectHeader.GarbageCollectorFlags flags = oh.GarbageCollectorState; switch(flags) { case ObjectHeader.GarbageCollectorFlags.FreeBlock | ObjectHeader.GarbageCollectorFlags.Unmarked: case ObjectHeader.GarbageCollectorFlags.FreeBlock | ObjectHeader.GarbageCollectorFlags.Marked : return; case ObjectHeader.GarbageCollectorFlags.GapPlug | ObjectHeader.GarbageCollectorFlags.Unmarked: case ObjectHeader.GarbageCollectorFlags.GapPlug | ObjectHeader.GarbageCollectorFlags.Marked : return; case ObjectHeader.GarbageCollectorFlags.ReadOnlyObject | ObjectHeader.GarbageCollectorFlags.Unmarked: case ObjectHeader.GarbageCollectorFlags.ReadOnlyObject | ObjectHeader.GarbageCollectorFlags.Marked : return; case ObjectHeader.GarbageCollectorFlags.AllocatedRawBytes | ObjectHeader.GarbageCollectorFlags.Unmarked: oh.GarbageCollectorState = flags | ObjectHeader.GarbageCollectorFlags.Marked; return; case ObjectHeader.GarbageCollectorFlags.AllocatedRawBytes | ObjectHeader.GarbageCollectorFlags.Marked: return; case ObjectHeader.GarbageCollectorFlags.UnreclaimableObject | ObjectHeader.GarbageCollectorFlags.Unmarked: if(m_markForNonHeap == ObjectHeader.GarbageCollectorFlags.Unmarked) { return; } flags ^= ObjectHeader.GarbageCollectorFlags.Marked; break; case ObjectHeader.GarbageCollectorFlags.UnreclaimableObject | ObjectHeader.GarbageCollectorFlags.Marked : if(m_markForNonHeap == ObjectHeader.GarbageCollectorFlags.Marked) { return; } flags ^= ObjectHeader.GarbageCollectorFlags.Marked; break; case ObjectHeader.GarbageCollectorFlags.NormalObject | ObjectHeader.GarbageCollectorFlags.Unmarked: flags |= ObjectHeader.GarbageCollectorFlags.Marked; break; case ObjectHeader.GarbageCollectorFlags.NormalObject | ObjectHeader.GarbageCollectorFlags.Marked : return; case ObjectHeader.GarbageCollectorFlags.SpecialHandlerObject | ObjectHeader.GarbageCollectorFlags.Unmarked: { var ext = FindExtensionHandler( oh.VirtualTable ); if(ext == null) { BugCheck.Raise( BugCheck.StopCode.HeapCorruptionDetected ); } else { ext.Mark( this, oh.Pack() ); } flags |= ObjectHeader.GarbageCollectorFlags.Marked; break; } case ObjectHeader.GarbageCollectorFlags.SpecialHandlerObject | ObjectHeader.GarbageCollectorFlags.Marked : return; default: { BugCheck.Log ( "Corruption! address=0x%08x, flags=0x%08x", (int)address.ToUInt32( ), (int)flags ); BugCheck.Raise( BugCheck.StopCode.HeapCorruptionDetected ); } return; } oh.GarbageCollectorState = flags; TS.VTable vTable = oh.VirtualTable; if(vTable.IsArray) { PushArrayReference( address, vTable ); } else { PushObjectReference( address, vTable ); } } [NoInline] private void VisitHeapObjectFields( UIntPtr fieldAddress , TS.VTable vTable ) { VisitHeapObjectFieldsInline( fieldAddress, vTable ); } #if !GC_PRECISE_PROFILING [Inline] #endif private void VisitHeapObjectFieldsInline( UIntPtr fieldAddress , TS.VTable vTable ) { TS.GCInfo.Pointer[] pointers = vTable.GCInfo.Pointers; int numOfPointers = pointers.Length; for(int i = 0; i < numOfPointers; i++) { VisitHeapObjectField( fieldAddress, ref pointers[i] ); } } #if !GC_PRECISE_PROFILING [Inline] #endif private unsafe void VisitHeapObjectField( UIntPtr fieldAddress , ref TS.GCInfo.Pointer pointer ) { UIntPtr* field = (UIntPtr*)fieldAddress.ToPointer( ); UIntPtr referenceAddress = field[pointer.OffsetInWords]; if(referenceAddress != UIntPtr.Zero) { switch(pointer.Kind) { case TS.GCInfo.Kind.Heap: VisitHeapObjectInline( referenceAddress ); break; case TS.GCInfo.Kind.Internal: case TS.GCInfo.Kind.Potential: VisitInternalPointerInline( referenceAddress ); break; } } } #if !GC_PRECISE_PROFILING [Inline] #endif private void PushObjectReference( UIntPtr address , TS.VTable vTable ) { TS.GCInfo.Pointer[] pointers = vTable.GCInfo.Pointers; if(pointers == null) { // // No pointers, nothing to do. // return; } if(m_fFirstLevel) { m_fFirstLevel = false; int numOfPointers = pointers.Length; UIntPtr fieldAddress = ObjectImpl.FromPointer( address ).GetFieldPointer( ); for(int i = 0; i < numOfPointers; i++) { VisitHeapObjectField( fieldAddress, ref pointers[i] ); } ProcessMarkStack(); m_fFirstLevel = true; } else { BugCheck.Assert( m_maskStackForObjects_Pos < MarkStackForObjectsSize - 1, BugCheck.StopCode.NoMarkStack ); m_maskStackForObjects[++m_maskStackForObjects_Pos] = address; } } #if !GC_PRECISE_PROFILING [Inline] #endif private void PushArrayReference( UIntPtr address , TS.VTable vTable ) { ArrayImpl array = ArrayImpl.CastAsArray( ObjectImpl.FromPointer( address ) ); int numOfElements = array.Length; if(numOfElements == 0) { // // Empty array, nothing to do. // return; } TS.VTable vTableElement = vTable.TypeInfo.ContainedType.VirtualTable; if(vTableElement.IsValueType) { if(vTableElement.GCInfo.Pointers == null) { // // It's an array of value types with no pointers, no need to push it. // return; } // // The address is for an array with embedded structures. // } else { // // The address is for an object reference. // vTableElement = null; } BugCheck.Assert( m_markStackForArrays_Pos < MarkStackForArraysSize - 1, BugCheck.StopCode.NoMarkStack ); m_markStackForArrays[++m_markStackForArrays_Pos].Push( array, vTable.ElementSize, numOfElements, vTableElement ); if(m_fFirstLevel) { m_fFirstLevel = false; ProcessMarkStack(); m_fFirstLevel = true; } } private void ProcessMarkStack() { while(true) { int pos; pos = m_maskStackForObjects_Pos; if(pos >= 0) { UIntPtr address = m_maskStackForObjects[pos]; m_maskStackForObjects_Pos = pos - 1; ObjectImpl obj = ObjectImpl.FromPointer( address ); TS.VTable vTable = TS.VTable.Get( obj ); VisitHeapObjectFieldsInline( obj.GetFieldPointer(), vTable ); continue; } pos = m_markStackForArrays_Pos; if(pos >= 0) { m_markStackForArrays[pos].Visit( this ); continue; } break; } } //--// private unsafe void RebuildBrickTable() { var brickTable = BrickTable.Instance; brickTable.Reset(); for(MemorySegment* heap = MemoryManager.Instance.StartOfHeap; heap != null; heap = heap->Next) { UIntPtr address = heap->FirstBlock; UIntPtr end = heap->End; while(AddressMath.IsLessThan( address, end )) { ObjectHeader oh = ObjectHeader.CastAsObjectHeader( address ); ObjectHeader.GarbageCollectorFlags flags = oh.GarbageCollectorState; switch(flags) { case ObjectHeader.GarbageCollectorFlags.FreeBlock | ObjectHeader.GarbageCollectorFlags.Unmarked: case ObjectHeader.GarbageCollectorFlags.FreeBlock | ObjectHeader.GarbageCollectorFlags.Marked : { UIntPtr addressNext = oh.GetNextObjectPointer(); // // The arrays used to wrap the free blocks are marked as outside the heap. // We should not add them to the brick table, because otherwise the whole brick table will look allocated // and we don't care for pointers into the free list. // address = addressNext; } break; case ObjectHeader.GarbageCollectorFlags.GapPlug | ObjectHeader.GarbageCollectorFlags.Unmarked: case ObjectHeader.GarbageCollectorFlags.GapPlug | ObjectHeader.GarbageCollectorFlags.Marked : address = AddressMath.Increment( address, sizeof(uint) ); break; case ObjectHeader.GarbageCollectorFlags.ReadOnlyObject | ObjectHeader.GarbageCollectorFlags.Unmarked: case ObjectHeader.GarbageCollectorFlags.ReadOnlyObject | ObjectHeader.GarbageCollectorFlags.Marked : BugCheck.Raise( BugCheck.StopCode.HeapCorruptionDetected ); return; case ObjectHeader.GarbageCollectorFlags.UnreclaimableObject | ObjectHeader.GarbageCollectorFlags.Unmarked: case ObjectHeader.GarbageCollectorFlags.UnreclaimableObject | ObjectHeader.GarbageCollectorFlags.Marked : BugCheck.Raise( BugCheck.StopCode.HeapCorruptionDetected ); return; case ObjectHeader.GarbageCollectorFlags.NormalObject | ObjectHeader.GarbageCollectorFlags.Unmarked: case ObjectHeader.GarbageCollectorFlags.NormalObject | ObjectHeader.GarbageCollectorFlags.Marked : case ObjectHeader.GarbageCollectorFlags.SpecialHandlerObject | ObjectHeader.GarbageCollectorFlags.Unmarked: case ObjectHeader.GarbageCollectorFlags.SpecialHandlerObject | ObjectHeader.GarbageCollectorFlags.Marked : case ObjectHeader.GarbageCollectorFlags.AllocatedRawBytes | ObjectHeader.GarbageCollectorFlags.Unmarked: case ObjectHeader.GarbageCollectorFlags.AllocatedRawBytes | ObjectHeader.GarbageCollectorFlags.Marked : { UIntPtr addressNext = oh.GetNextObjectPointer(); brickTable.MarkObject( address, AddressMath.RangeSize( address, addressNext ) ); address = addressNext; } break; default: BugCheck.Raise( BugCheck.StopCode.HeapCorruptionDetected ); return; } } } } //--// [TS.WellKnownMethod( "DebugBrickTable_VerifyBrickTable" )] private unsafe void VerifyBrickTable() { for(MemorySegment* heap = MemoryManager.Instance.StartOfHeap; heap != null; heap = heap->Next) { UIntPtr address = heap->FirstBlock; UIntPtr end = heap->End; while(AddressMath.IsLessThan( address, end )) { FindObject( AddressMath.Increment( address, sizeof(uint) ) ); ObjectHeader oh = ObjectHeader.CastAsObjectHeader( address ); ObjectHeader.GarbageCollectorFlags flags = oh.GarbageCollectorState; switch(flags) { case ObjectHeader.GarbageCollectorFlags.FreeBlock | ObjectHeader.GarbageCollectorFlags.Unmarked: case ObjectHeader.GarbageCollectorFlags.FreeBlock | ObjectHeader.GarbageCollectorFlags.Marked : { UIntPtr addressNext = oh.GetNextObjectPointer(); address = addressNext; } break; case ObjectHeader.GarbageCollectorFlags.GapPlug | ObjectHeader.GarbageCollectorFlags.Unmarked: case ObjectHeader.GarbageCollectorFlags.GapPlug | ObjectHeader.GarbageCollectorFlags.Marked : address = AddressMath.Increment( address, sizeof(uint) ); break; case ObjectHeader.GarbageCollectorFlags.ReadOnlyObject | ObjectHeader.GarbageCollectorFlags.Unmarked: case ObjectHeader.GarbageCollectorFlags.ReadOnlyObject | ObjectHeader.GarbageCollectorFlags.Marked : BugCheck.Raise( BugCheck.StopCode.HeapCorruptionDetected ); return; case ObjectHeader.GarbageCollectorFlags.UnreclaimableObject | ObjectHeader.GarbageCollectorFlags.Unmarked: case ObjectHeader.GarbageCollectorFlags.UnreclaimableObject | ObjectHeader.GarbageCollectorFlags.Marked : BugCheck.Raise( BugCheck.StopCode.HeapCorruptionDetected ); return; case ObjectHeader.GarbageCollectorFlags.NormalObject | ObjectHeader.GarbageCollectorFlags.Unmarked: case ObjectHeader.GarbageCollectorFlags.NormalObject | ObjectHeader.GarbageCollectorFlags.Marked : case ObjectHeader.GarbageCollectorFlags.SpecialHandlerObject | ObjectHeader.GarbageCollectorFlags.Unmarked: case ObjectHeader.GarbageCollectorFlags.SpecialHandlerObject | ObjectHeader.GarbageCollectorFlags.Marked : case ObjectHeader.GarbageCollectorFlags.AllocatedRawBytes | ObjectHeader.GarbageCollectorFlags.Unmarked: case ObjectHeader.GarbageCollectorFlags.AllocatedRawBytes | ObjectHeader.GarbageCollectorFlags.Marked : { UIntPtr addressNext = oh.GetNextObjectPointer(); address = addressNext; } break; default: BugCheck.Raise( BugCheck.StopCode.HeapCorruptionDetected ); return; } } } } // // Access Methods // } } ================================================ FILE: Zelig/Zelig/RunTime/Zelig/Kernel/GarbageCollectors/PreciseMarkAndSweepCollector.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // namespace Microsoft.Zelig.Runtime { using System; using TS = Microsoft.Zelig.Runtime.TypeSystem; public abstract class PreciseMarkAndSweepCollector : MarkAndSweepCollector { class PreciseStackWalker : TS.CodeMapDecoderCallback, MarkAndSweepStackWalker { // // State // const int c_StackMarkSize = 8 * sizeof( uint ); PreciseMarkAndSweepCollector m_owner; UIntPtr m_pc; uint m_registerMask_Scratched; uint m_registerMask_Heap; uint m_registerMask_Internal; uint m_registerMask_Potential; uint m_stackMask_Heap; uint m_stackMask_Internal; uint m_stackMask_Potential; uint m_stackLow; uint m_stackHigh; bool m_done; // // Constructor Methods // internal PreciseStackWalker( PreciseMarkAndSweepCollector owner ) { m_owner = owner; } // // Helper Methods // public override bool RegisterEnter( UIntPtr address, uint num, PointerKind kind ) { if(AddressMath.IsGreaterThan( address, m_pc )) { return false; } uint mask = 1u << (int)num; switch(kind) { case PointerKind.Heap: m_registerMask_Heap |= mask; break; case PointerKind.Internal: m_registerMask_Internal |= mask; break; case PointerKind.Potential: m_registerMask_Potential |= mask; break; } return true; } public override bool RegisterLeave( UIntPtr address, uint num ) { if(AddressMath.IsGreaterThan( address, m_pc )) { return false; } uint mask = ~( 1u << (int)num ); m_registerMask_Heap &= mask; m_registerMask_Internal &= mask; m_registerMask_Potential &= mask; return true; } public override bool StackEnter( UIntPtr address, uint offset, PointerKind kind ) { if(AddressMath.IsGreaterThan( address, m_pc )) { return false; } if(m_stackLow <= offset && offset < m_stackHigh) { uint mask = ( 1u << (int)( offset - m_stackLow ) ); switch(kind) { case PointerKind.Heap: m_stackMask_Heap |= mask; break; case PointerKind.Internal: m_stackMask_Internal |= mask; break; case PointerKind.Potential: m_stackMask_Potential |= mask; break; } } if(offset >= m_stackHigh) { m_done = false; } return true; } public override bool StackLeave( UIntPtr address, uint offset ) { if(AddressMath.IsGreaterThan( address, m_pc )) { return false; } if(m_stackLow <= offset && offset < m_stackHigh) { uint mask = ~( 1u << (int)( offset - m_stackLow ) ); m_stackMask_Heap &= mask; m_stackMask_Internal &= mask; m_stackMask_Potential &= mask; } if(offset >= m_stackHigh) { m_done = false; } return true; } //--// public unsafe void Process( Processor.Context ctx ) { // // All registers should be considered. // m_registerMask_Scratched = 0; while(true) { m_pc = ctx.ProgramCounter; m_stackLow = 0; m_stackHigh = c_StackMarkSize; //--// TS.CodeMap cm = TS.CodeMap.ResolveAddressToCodeMap( m_pc ); BugCheck.Assert( cm != null, BugCheck.StopCode.UnwindFailure ); int idx = cm.FindRange( m_pc ); BugCheck.Assert( idx >= 0, BugCheck.StopCode.UnwindFailure ); while(true) { m_registerMask_Heap = 0; m_registerMask_Internal = 0; m_registerMask_Potential = 0; m_stackMask_Heap = 0; m_stackMask_Internal = 0; m_stackMask_Potential = 0; m_done = true; cm.Ranges[ idx ].Decode( this ); // // On the first pass, mark the objects pointed to by live registers. // if(m_stackLow == 0) { uint set = m_registerMask_Heap | m_registerMask_Internal | m_registerMask_Potential; set &= ~m_registerMask_Scratched; if(set != 0) { uint mask = 1u; for(int regNum = 0; regNum < 16; regNum++, mask <<= 1) { if(( set & mask ) != 0) { UIntPtr ptr = ctx.GetRegisterByIndex( (uint)regNum ); if(ptr != UIntPtr.Zero) { if(( m_registerMask_Heap & mask ) != 0) { m_owner.VisitHeapObject( ptr ); } else { m_owner.VisitInternalPointer( ptr ); } } } } } } { uint set = m_stackMask_Heap | m_stackMask_Internal | m_stackMask_Potential; if(set != 0) { uint mask = 1u; for(int offset = 0; offset < c_StackMarkSize; offset++, mask <<= 1) { if(( set & mask ) != 0) { UIntPtr* stack = (UIntPtr*)ctx.StackPointer.ToPointer( ); UIntPtr ptr = stack[ m_stackLow + offset ]; if(ptr != UIntPtr.Zero) { if(( m_stackMask_Heap & mask ) != 0) { m_owner.VisitHeapObject( ptr ); } else { m_owner.VisitInternalPointer( ptr ); } } } } } } if(m_done) { break; } m_stackLow += c_StackMarkSize; m_stackHigh += c_StackMarkSize; } // // Exclude scratched registers from the set of live registers. // m_registerMask_Scratched = ctx.ScratchedIntegerRegisters; if(ctx.Unwind( ) == false) { break; } } } } //--// protected override int MarkStackForObjectsSize { get { return 1024; } } protected override int MarkStackForArraysSize { get { return 128; } } protected override MarkAndSweepStackWalker CreateStackWalker( ) { return new PreciseStackWalker( this ); } } } ================================================ FILE: Zelig/Zelig/RunTime/Zelig/Kernel/GarbageCollectors/ReferenceCountingCollector.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // namespace Microsoft.Zelig.Runtime { using System; using System.Runtime.InteropServices; using TS = Microsoft.Zelig.Runtime.TypeSystem; [TS.WellKnownType("Microsoft_Zelig_Runtime_ReferenceCountingCollector")] public abstract class ReferenceCountingCollector : GarbageCollectionManager { #if REFCOUNT_STAT [TS.WellKnownMethod( "ReferenceCountingCollector_LoadAndAddReference" )] [TS.DisableAutomaticReferenceCounting] internal static Object LoadAndAddReference( ref Object target ) { Object obj = LoadAndAddReferenceNative( ref target ); ObjectHeader.RecordAddReference( obj ); ObjectHeader.s_LoadAndAddRefCalled++; return obj; } [DllImport( "C" )] internal static extern Object LoadAndAddReferenceNative( ref Object target ); #else //REFCOUNT_STAT [TS.WellKnownMethod( "ReferenceCountingCollector_LoadAndAddReference" )] [DllImport( "C" )] internal static extern Object LoadAndAddReferenceNative( ref Object target ); #endif //REFCOUNT_STAT [TS.WellKnownMethod( "ReferenceCountingCollector_Swap" )] [TS.DisableAutomaticReferenceCounting] [NoInline] internal static void Swap( ref Object target, Object value ) { #if REFCOUNT_STAT ObjectHeader.RecordAddReference( value ); ObjectHeader.s_SwapCalled++; #endif //REFCOUNT_STAT Object oldValue = ReferenceCountingExchange( ref target, value ); ObjectHeader.ReleaseReference( oldValue ); } [TS.WellKnownMethod( "ReferenceCountingCollector_ReferenceCountingExchange" )] [DllImport( "C" )] private static extern Object ReferenceCountingExchange( ref Object location1, Object value ); [TS.WellKnownMethod( "ReferenceCountingCollector_ReferenceCountingCompareExchange" )] [DllImport( "C" )] private static extern Object ReferenceCountingCompareExchange( ref Object location1, Object value, Object comparand ); //--// public override void InitializeGarbageCollectionManager( ) { } public override void NotifyNewObject( UIntPtr ptr, uint size ) { } public override UIntPtr FindObject( UIntPtr interiorPtr ) { return UIntPtr.Zero; } public override uint Collect( ) { return 0; } public override long GetTotalMemory( ) { return 0; } public override void ThrowOutOfMemory( TS.VTable vTable ) { BugCheck.Raise( BugCheck.StopCode.NoMemory ); } public override bool IsMarked( object target ) { return true; } public override void ExtendMarking( object target ) { } } [TS.WellKnownType("Microsoft_Zelig_Runtime_StrictReferenceCountingCollector")] public abstract class StrictReferenceCountingCollector : ReferenceCountingCollector { } } ================================================ FILE: Zelig/Zelig/RunTime/Zelig/Kernel/HardwareModel/Device.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // namespace Microsoft.Zelig.Runtime { using System; using System.Runtime.CompilerServices; [ImplicitInstance] [ForceDevirtualization] public abstract class Device { protected static BugCheck.StopCode m_bugCheckCode; const int DefaultStackSize = 512; [MemoryUsage(MemoryUsage.Stack, ContentsUninitialized=true, AllocateFromHighAddress=true)] static readonly uint[] s_bootstrapStack = new uint[DefaultStackSize / sizeof(uint)]; // // Helper Methods // public abstract void PreInitializeProcessorAndMemory(); public abstract void MoveCodeToProperLocation(); public virtual void ProcessBugCheck( BugCheck.StopCode code ) { Device.m_bugCheckCode = code; while(true) { Peripherals.Instance.WaitForInterrupt(); } } public virtual void ProcessLog(string format) { } public virtual void ProcessLog(string format, int p1) { } public virtual void ProcessLog(string format, int p1, int p2) { } public virtual void ProcessLog(string format, int p1, int p2, int p3) { } public virtual void ProcessLog(string format, int p1, int p2, int p3, int p4) { } public virtual void ProcessLog(string format, int p1, int p2, int p3, int p4, int p5) { } // // Access Methods // public static extern Device Instance { [SingletonFactory(ReadOnly=true)] [MethodImpl( MethodImplOptions.InternalCall )] get; } public virtual uint[] BootstrapStack { get { return s_bootstrapStack; } } public unsafe UIntPtr BootstrapStackPointer { [NoInline] get { var stack = this.BootstrapStack; fixed(uint* ptr = stack) { return new UIntPtr( &ptr[stack.Length] ); } } } } } ================================================ FILE: Zelig/Zelig/RunTime/Zelig/Kernel/HardwareModel/HardwareProvider.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // namespace Microsoft.Zelig.Runtime { using System; using System.Collections; using System.Runtime.CompilerServices; using Windows.Devices.Gpio.Provider; //--// [ImplicitInstance] [ForceDevirtualization] public abstract class HardwareProvider { private static object pinLock = new object(); // // See below in default ctor: the singleton factory currently does not yet support creating parameterized objects // we need to use a ceiling value until we invoke the defautl ctor that will ask the actual number of pins to the // concrete HW Provider (e.g. mBed HW provider) // Consider that LPC1768 board has 32 exposed pins and K64F has 64 pins only // static BitArray m_reservedPins = new BitArray(256); //--// //protected HardwareProvider( ) //{ // // BUGBUGBUG: fix singleton factory to call the default ctor when available // m_used = new BitArray( this.PinCount ); //} // // Serial Discovery // public abstract string[] GetSerialPorts(); public abstract bool GetSerialPinsFromPortName(string portName, out int txPin, out int rxPin, out int rtsPin, out int ctsPin); // // Gpio discovery and reservation service // /// /// Returns how many pins on the board are accessible to the user. This /// includes also pins tied to peripherals, such as SPI, etc. /// public abstract int PinCount { get; } /// /// Returns the sequential pin index used by the reservation service from the pin number provides by the /// OEM, usually through the OEM specific board provider assembly /// /// /// public abstract int PinToIndex(int pin); public abstract int InvalidPin { get; } // // Gpio reservation // public bool TryReservePins(params int[] pins) { int failIndex = -1; lock(pinLock) { for(int i = 0; i < pins.Length; i++) { // Do not try to release NC pins if(InvalidPin != pins[i]) { int index = PinToIndex(pins[i]); if(m_reservedPins[index] == true) { failIndex = i; break; } m_reservedPins[index] = true; } } if(failIndex > 0) { for(int i = 0; i < failIndex; i++) { // Do not touch NC pins if(InvalidPin != pins[i]) { int index = PinToIndex(pins[i]); m_reservedPins[index] = false; } } return false; } return true; } } public void ReleasePins(params int[] pins) { lock(pinLock) { foreach(int pin in pins) { // Don't touch NC pins if(InvalidPin != pin) { int index = PinToIndex(pin); if(m_reservedPins[index] == true) { m_reservedPins[index] = false; } } } } } // // Factory methods // public static extern HardwareProvider Instance { [SingletonFactory()] [MethodImpl(MethodImplOptions.InternalCall)] get; } } } ================================================ FILE: Zelig/Zelig/RunTime/Zelig/Kernel/HardwareModel/Memory.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // namespace Microsoft.Zelig.Runtime { using System; using System.Runtime.CompilerServices; using TS = Microsoft.Zelig.Runtime.TypeSystem; [ImplicitInstance] [ForceDevirtualization] public abstract class Memory { [TS.AllowCompileTimeIntrospection] public class Range { public enum SubstractionAction { RemoveNothing , RemoveStart , RemoveMiddle , RemoveEnd , RemoveEverything, } // // State // public readonly UIntPtr Start; public readonly UIntPtr End; public readonly string SectionName; public readonly MemoryAttributes Attributes; public readonly MemoryUsage Usage; public readonly Type ExtensionHandler; // // Constructor Methods // public Range( UIntPtr start , UIntPtr end , string sectionName , MemoryAttributes attributes , MemoryUsage usage , Type extensionHandler ) { this.Start = start; this.End = end; this.SectionName = sectionName; this.Attributes = attributes; this.Usage = usage; this.ExtensionHandler = extensionHandler; } // // Equality Methods // public bool Equals( Range other ) { if(this.Start == other.Start && this.End == other.End && this.Attributes == other.Attributes ) { return true; } return false; } public static bool ArrayEquals( Range[] left , Range[] right ) { int leftLen = left != null ? left .Length : 0; int rightLen = right != null ? right.Length : 0; if(leftLen == rightLen) { for(int i = 0; i < leftLen; i++) { if(left[i].Equals( right[i] ) == false) { return false; } } return true; } return false; } // // Helper Methods // public Range CloneSettings( UIntPtr start , UIntPtr end ) { return new Runtime.Memory.Range( start, end, this.SectionName, this.Attributes, this.Usage, this.ExtensionHandler ); } public bool Contains( uint address ) { return AddressMath.IsInRange( new UIntPtr( address ), this.Start, this.End ); } public SubstractionAction ComputeSubstraction( UIntPtr blockStart , UIntPtr blockEnd ) { bool fIsStartToTheLeft = AddressMath.IsGreaterThanOrEqual( this.Start, blockStart ); bool fIsStartToTheRight = AddressMath.IsLessThanOrEqual ( this.End , blockStart ); bool fIsEndToTheLeft = AddressMath.IsGreaterThanOrEqual( this.Start, blockEnd ); bool fIsEndToTheRight = AddressMath.IsLessThanOrEqual ( this.End , blockEnd ); if(fIsEndToTheLeft || fIsStartToTheRight) { return SubstractionAction.RemoveNothing; } if(fIsStartToTheLeft && fIsEndToTheRight) { return SubstractionAction.RemoveEverything; } if(!fIsStartToTheLeft && !fIsEndToTheRight) { return SubstractionAction.RemoveMiddle; } return fIsStartToTheLeft ? SubstractionAction.RemoveStart : SubstractionAction.RemoveEnd; } // // Access Methods // public uint Size { get { return AddressMath.RangeSize( this.Start, this.End ); } } } [TS.AllowCompileTimeIntrospection] public class RelocationInfo { // // State // private UIntPtr m_destination; private uint m_size; [TS.WellKnownField( "RelocationInfo_m_data" )] private uint[] m_data; // // Constructor Methods // public RelocationInfo( UIntPtr destination , uint[] data , int offset , int count ) { m_destination = destination; m_size = (uint)count; m_data = ArrayUtility.ExtractSliceFromNotNullArray( data, offset, count ); } public RelocationInfo( UIntPtr destination , uint clearSize ) { m_destination = destination; m_size = clearSize; m_data = null; } // // Equality Methods // public bool Equals( ref RelocationInfo other ) { if(this.m_destination == other.m_destination && this.m_size == other.m_size ) { return ArrayUtility.UIntArrayEquals( this.m_data, other.m_data ); } return false; } public static bool ArrayEquals( RelocationInfo[] left , RelocationInfo[] right ) { int leftLen = left != null ? left .Length : 0; int rightLen = right != null ? right.Length : 0; if(leftLen == rightLen) { for(int i = 0; i < leftLen; i++) { if(left[i].Equals( ref right[i] ) == false) { return false; } } return true; } return false; } // // Access Methods // public bool IsEraseBlock { get { return m_data == null; } } public uint SizeInWords { get { return m_size; } } public unsafe UIntPtr Start { get { ArrayImpl array = ArrayImpl.CastAsArray( m_data ); return new UIntPtr( array.GetDataPointer() ); } } public UIntPtr End { get { return AddressMath.Increment( this.Start, m_size * sizeof(uint) ); } } public UIntPtr Destination { get { return m_destination; } } } //--// // // State // #pragma warning disable 649 // These fields are populated at code generation. [TS.WellKnownField( "Memory_m_availableMemory" )] private readonly Range[] m_availableMemory; [TS.WellKnownField( "Memory_m_relocationInfo" )] private readonly RelocationInfo[] m_relocationInfo; #pragma warning restore 649 // // Helper Methods // public abstract void InitializeMemory(); [DisableNullChecks( ApplyRecursively=true )] [DisableBoundsChecks( ApplyRecursively=true )] [MemoryUsage(MemoryUsage.Bootstrap)] public virtual unsafe void ExecuteImageRelocation() { RelocationInfo[] array = m_relocationInfo; for(int i = 0; i < array.Length; i++) { RelocationInfo ri = array[i]; if(ri.IsEraseBlock) { UIntPtr destinationEnd = AddressMath.Increment( ri.Destination, ri.SizeInWords * sizeof( uint ) ); Memory.Zero(ri.Destination, destinationEnd); } else { Buffer.InternalMemoryMove( (byte*)ri.Start.ToPointer(), (byte*)ri.Destination.ToPointer(), (int)AddressMath.RangeSize( ri.Start, ri.End ) ); } } } //--// [Inline] [DisableNullChecks] public static void Zero( UIntPtr start , UIntPtr end ) { Fill( start, end, 0 ); } [Inline] public static void Dirty( UIntPtr start , UIntPtr end ) { Fill( start, end, 0xDD ); } [Inline] [DisableNullChecks] public static unsafe void Fill( UIntPtr start , UIntPtr end , byte value ) { byte* startPtr = (byte*)start.ToPointer(); byte* endPtr = (byte*)end. ToPointer(); Fill( startPtr, (int)(endPtr - startPtr), value ); } [NoInline] [TS.WellKnownMethod( "Microsoft_Zelig_Runtime_Memory_Fill" )] public static unsafe void Fill( byte* dst, int size, byte value ) { byte* end = dst + size; while( dst < end ) { *dst = value; ++dst; } } // // Access Methods // public static extern Memory Instance { [SingletonFactory(ReadOnly=true)] [MethodImpl( MethodImplOptions.InternalCall )] get; } public Range[] AvailableMemory { get { return m_availableMemory; } } public RelocationInfo[] RelocationData { get { return m_relocationInfo; } } } } ================================================ FILE: Zelig/Zelig/RunTime/Zelig/Kernel/HardwareModel/Peripherals.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // namespace Microsoft.Zelig.Runtime { using System; using System.Runtime.CompilerServices; [ImplicitInstance] [ForceDevirtualization] public abstract class Peripherals { public delegate void Continuation(); // // Helper Methods // public abstract void Initialize(); public abstract void Activate(); public abstract void EnableInterrupt( uint index ); public abstract void DisableInterrupt( uint index ); public abstract void CauseInterrupt(); public abstract void ContinueUnderNormalInterrupt( Continuation dlg ); public abstract void WaitForInterrupt(); public abstract void ProcessInterrupt(); public abstract void ProcessFastInterrupt(); //--// public abstract ulong GetPerformanceCounterFrequency(); public abstract uint ReadPerformanceCounter(); // // Access Methods // public static extern Peripherals Instance { [SingletonFactory()] [MethodImpl( MethodImplOptions.InternalCall )] get; } } } ================================================ FILE: Zelig/Zelig/RunTime/Zelig/Kernel/HardwareModel/Processor.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // namespace Microsoft.Zelig.Runtime { using System; using System.Runtime.CompilerServices; [ImplicitInstance] [ForceDevirtualization] public abstract class Processor { [ForceDevirtualization] public abstract class Context { // // State // public bool InPrologue; public bool InEpilogue; protected readonly ThreadImpl m_owner; // // Helper Methods // protected Context(ThreadImpl owner) { m_owner = owner; } public abstract void Populate(); public abstract void Populate( Context context ); public abstract void PopulateFromDelegate( Delegate dlg, uint[] stack ); public abstract void SetupForExceptionHandling( uint mode ); public abstract bool Unwind(); public abstract void SwitchTo(); public abstract UIntPtr GetRegisterByIndex( uint idx ); public abstract void SetRegisterByIndex( uint idx , UIntPtr value ); // // Access Methods // public abstract UIntPtr StackPointer { get; set; } public abstract UIntPtr BaseStackPointer { get; } public abstract uint ExcReturn { get; set; } public abstract UIntPtr ProgramCounter { get; set; } public abstract uint ScratchedIntegerRegisters { get; } public ThreadImpl OwnerThread { get { return m_owner; } } } // // Helper Methods // public abstract void InitializeProcessor(); public abstract Context AllocateProcessorContext(ThreadImpl owner); //--// public abstract bool AreInterruptsDisabled(); public virtual bool AreInterruptsEnabled() { return !AreAllInterruptsDisabled(); } public abstract bool AreAllInterruptsDisabled( ); //--// public virtual bool AreFaultsDisabled( ) { return true; } //--// public abstract UIntPtr GetCacheableAddress( UIntPtr ptr ); public abstract UIntPtr GetUncacheableAddress( UIntPtr ptr ); public abstract void FlushCacheLine( UIntPtr target ); //--// public abstract void Breakpoint(); //--// [MethodImpl(MethodImplOptions.InternalCall)] public extern static int Delay( int count ); [Inline] public static void Delay( uint timeNanosec , uint clockFrequency ) { Delay( (int)(timeNanosec / 1E9 * clockFrequency) ); } [Inline] public static void DelayMicroseconds( uint timeMicrosec ) { Delay( (int)(timeMicrosec / 1E6 * Configuration.CoreClockFrequency) ); } // // Access Methods // public static extern Processor Instance { [SingletonFactory(ReadOnly=true)] [MethodImpl( MethodImplOptions.InternalCall )] get; } } } ================================================ FILE: Zelig/Zelig/RunTime/Zelig/Kernel/HardwareModel/Storage.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // namespace Microsoft.Zelig.Runtime { using System; using System.Runtime.CompilerServices; using TS = Microsoft.Zelig.Runtime.TypeSystem; [ImplicitInstance] [ForceDevirtualization] public abstract class Storage { private class EmptyStorage : Storage { public override bool EraseSectors( UIntPtr addressStart, UIntPtr addressEnd ) { throw new NotImplementedException( ); } public override void InitializeStorage( ) { } public override void Read( UIntPtr address, byte[] buffer, uint offset, uint numBytes ) { throw new NotImplementedException( ); } public override byte ReadByte( UIntPtr address ) { throw new NotImplementedException( ); } public override ushort ReadShort( UIntPtr address ) { throw new NotImplementedException( ); } public override uint ReadWord( UIntPtr address ) { throw new NotImplementedException( ); } public override void RebootDevice( ) { throw new NotImplementedException( ); } public override void SubstituteFirmware( UIntPtr addressDestination, UIntPtr addressSource, uint numBytes ) { throw new NotImplementedException( ); } public override bool Write( UIntPtr address, byte[] buffer, uint offset, uint numBytes ) { throw new NotImplementedException( ); } public override bool WriteByte( UIntPtr address, byte val ) { throw new NotImplementedException( ); } public override bool WriteShort( UIntPtr address, ushort val ) { throw new NotImplementedException( ); } public override bool WriteWord( UIntPtr address, uint val ) { throw new NotImplementedException( ); } } // // State // // // Helper Methods // public abstract void InitializeStorage(); //--// public abstract bool EraseSectors( UIntPtr addressStart , UIntPtr addressEnd ); public abstract bool WriteByte ( UIntPtr address, byte val ); public abstract bool WriteShort( UIntPtr address, ushort val ); public abstract bool WriteWord ( UIntPtr address, uint val ); public abstract bool Write( UIntPtr address , byte[] buffer , uint offset , uint numBytes ); //--// public abstract byte ReadByte ( UIntPtr address ); public abstract ushort ReadShort( UIntPtr address ); public abstract uint ReadWord ( UIntPtr address ); public abstract void Read( UIntPtr address , byte[] buffer , uint offset , uint numBytes ); public abstract void SubstituteFirmware( UIntPtr addressDestination , UIntPtr addressSource , uint numBytes ); public abstract void RebootDevice(); //--// // // Access Methods // public static extern Storage Instance { [SingletonFactory(Fallback = typeof(EmptyStorage))] [MethodImpl( MethodImplOptions.InternalCall )] get; } } } ================================================ FILE: Zelig/Zelig/RunTime/Zelig/Kernel/HardwareModel/TargetPlatform/ARMv4/Coprocessor14.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // namespace Microsoft.Zelig.Runtime.TargetPlatform.ARMv4 { using System; using TS = Microsoft.Zelig.Runtime.TypeSystem; using EncDef = Microsoft.Zelig.TargetModel.ArmProcessor.EncodingDefinition; public static class Coprocessor14 { [Inline] public static void WriteDebugCommData( uint value ) { ProcessorARMv4.MoveToCoprocessor( 14, 0, 1, 0, 0, value ); } [Inline] public static uint ReadDebugCommData() { return ProcessorARMv4.MoveFromCoprocessor( 14, 0, 1, 0, 0 ); } [Inline] public static uint ReadDebugCommStatus() { return ProcessorARMv4.MoveFromCoprocessor( 14, 0, 0, 0, 0 ); } //--// [Inline] public static bool CanWriteDCC() { return (ReadDebugCommStatus() & 2) == 0; } [Inline] public static bool CanReadDCC() { return (ReadDebugCommStatus() & 1) != 0; } public static void WriteDCC( uint value ) { while(!CanWriteDCC()) { } WriteDebugCommData( value ); } public static uint ReadDCC() { while(!CanReadDCC()) { } return ReadDebugCommData(); } //--// public static bool WriteDCCWithTimeout( uint value , int timeout ) { while((ReadDebugCommStatus() & 2) != 0) { if(--timeout < 0) { return false; } } WriteDebugCommData( value ); return true; } public static bool ReadDCCWithTimeout( out uint value , int timeout ) { while((ReadDebugCommStatus() & 1) != 0) { if(--timeout < 0) { value = 0; return false; } } value = ReadDebugCommData(); return true; } } } ================================================ FILE: Zelig/Zelig/RunTime/Zelig/Kernel/HardwareModel/TargetPlatform/ARMv4/Coprocessor15.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // namespace Microsoft.Zelig.Runtime.TargetPlatform.ARMv4 { using System; using TS = Microsoft.Zelig.Runtime.TypeSystem; using EncDef = Microsoft.Zelig.TargetModel.ArmProcessor.EncodingDefinition; public static class Coprocessor15 { public const uint c_ControlRegister__Vector = (1U << 13); // Exception Vector Relocation (V). // 0 = Base address of exception vectors is 0x0000,0000 // 1 = Base address of exception vectors is 0xFFFF,0000 // public const uint c_ControlRegister__ICache = (1U << 12); // Instruction Cache Enable/Disable (I) // 0 = Disabled // 1 = Enabled // public const uint c_ControlRegister__BTB = (1U << 11); // Branch Target Buffer Enable (Z) // 0 = Disabled // 1 = Enabled // public const uint c_ControlRegister__RomProt = (1U << 9); // ROM Protection (R) // This selects the access checks performed by the memory // management unit. See the ARM Architecture Reference // Manual for more information. // public const uint c_ControlRegister__SysProt = (1U << 8); // System Protection (S) // This selects the access checks performed by the memory // management unit. See the ARM Architecture Reference // Manual for more information. // public const uint c_ControlRegister__BigEndian = (1U << 7); // Big/Little Endian (B) // 0 = Little-endian operation // 1 = Big-endian operation // public const uint c_ControlRegister__DCache = (1U << 2); // Data cache enable/disable (C) // 0 = Disabled // 1 = Enabled // public const uint c_ControlRegister__AlignmentFault = (1U << 1); // Alignment fault enable/disable (A) // 0 = Disabled // 1 = Enabled // public const uint c_ControlRegister__MMU = (1U << 0); // Memory management unit enable/disable (M) // 0 = Disabled // 1 = Enabled // // // Helper Methods // [Inline] public static unsafe void InvalidateCaches() { ProcessorARMv4.MoveToCoprocessor( 15, 0, 7, 7, 0, 0 ); } [Inline] public static unsafe void InvalidateICache() { ProcessorARMv4.MoveToCoprocessor( 15, 0, 7, 5, 0, 0 ); } [Inline] public static unsafe void InvalidateICache( UIntPtr target ) { ProcessorARMv4.MoveToCoprocessor( 15, 0, 7, 5, 1, target.ToUInt32() ); } [Inline] public static unsafe void InvalidateDCache() { ProcessorARMv4.MoveToCoprocessor( 15, 0, 7, 6, 0, 0 ); } [Inline] public static unsafe void InvalidateDCache( UIntPtr target ) { ProcessorARMv4.MoveToCoprocessor( 15, 0, 7, 6, 1, target.ToUInt32() ); } [Inline] public static unsafe void CleanDCache( UIntPtr target ) { ProcessorARMv4.MoveToCoprocessor( 15, 0, 7, 10, 1, target.ToUInt32() ); } [Inline] public static unsafe void CleanAndInvalidateDCache( UIntPtr target ) { ProcessorARMv4.MoveToCoprocessor( 15, 0, 7, 14, 1, target.ToUInt32() ); } //--// [Inline] public static unsafe void TestAndCleanDCache() { while((ProcessorARMv4.MoveFromCoprocessor( 15, 0, 7, 10, 3 ) & (1u << 30)) == 0) { } } [Inline] public static unsafe void TestCleanAndInvalidateDCache() { while((ProcessorARMv4.MoveFromCoprocessor( 15, 0, 7, 14, 3 ) & (1u << 30)) == 0) { } } [Inline] public static unsafe void DrainWriteBuffer() { ProcessorARMv4.MoveToCoprocessor( 15, 0, 7, 10, 4, 0 ); } [Inline] public static unsafe void WaitForInterrupt() { ProcessorARMv4.MoveToCoprocessor( 15, 0, 7, 0, 4, 0 ); } [Inline] public static unsafe void InvalidateMMUTLBs() { ProcessorARMv4.MoveToCoprocessor( 15, 0, 8, 7, 0, 0 ); } [Inline] public static unsafe void SetDomainAccessControl( uint val ) { // // Domain access control. // ProcessorARMv4.MoveToCoprocessor( 15, 0, 3, 0, 0, val ); } [Inline] public static unsafe void SetTranslationTableBaseRegister( uint* ptr ) { // // Write the Translation Table Base Register. // ProcessorARMv4.MoveToCoprocessor( 15, 0, 2, 0, 0, new UIntPtr( ptr ).ToUInt32() ); } //--//--// [Inline] public static void ResetControlRegisterBits( uint mask ) { uint reg = ProcessorARMv4.MoveFromCoprocessor( 15, 0, 1, 0, 0 ); // MRC p15, 0, , c1, c0, 0 ; read control register reg &= ~mask; ProcessorARMv4.MoveToCoprocessor( 15, 0, 1, 0, 0, reg ); } [Inline] public static void SetControlRegisterBits( uint mask ) { uint reg = ProcessorARMv4.MoveFromCoprocessor( 15, 0, 1, 0, 0 ); // MRC p15, 0, , c1, c0, 0 ; read control register reg |= mask; ProcessorARMv4.MoveToCoprocessor( 15, 0, 1, 0, 0, reg ); } } } ================================================ FILE: Zelig/Zelig/RunTime/Zelig/Kernel/HardwareModel/TargetPlatform/ARMv4/InterruptsSafeHandleARMv4.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // namespace Microsoft.Zelig.Runtime.TargetPlatform.ARMv4.SmartHandles { using System; using ISA = TargetModel.ArmProcessor.InstructionSetVersion; [ExtendClass( typeof(Runtime.SmartHandles.InterruptState), PlatformVersionFilter=ISA.Platform_Version__ARM_legacy )] public struct InterruptStateARMv4 : IDisposable { // // State // uint m_cpsr; // // Constructor Methods // [DiscardTargetImplementation()] [Inline] public InterruptStateARMv4( uint cpsr ) { m_cpsr = cpsr; } // // Helper Methods // [Inline] public void Dispose() { ProcessorARMv4.SetMode( m_cpsr ); } [Inline] public void Toggle() { uint cpsr = ProcessorARMv4.GetStatusRegister(); ProcessorARMv4.SetMode( m_cpsr ); ProcessorARMv4.Nop ( ); ProcessorARMv4.SetMode( cpsr ); } //--// [Inline] public static InterruptStateARMv4 Disable() { return new InterruptStateARMv4( ProcessorARMv4.DisableInterrupts() ); } [Inline] public static InterruptStateARMv4 DisableAll() { return new InterruptStateARMv4( ProcessorARMv4.DisableAllInterrupts() ); } [Inline] public static InterruptStateARMv4 Enable() { return new InterruptStateARMv4( ProcessorARMv4.EnableInterrupts() ); } [Inline] public static InterruptStateARMv4 EnableAll() { return new InterruptStateARMv4( ProcessorARMv4.EnableAllInterrupts() ); } // // Access Methods // [Inline] public uint GetPreviousState() { return m_cpsr; } public HardwareException GetCurrentExceptionMode() { switch(m_cpsr & ProcessorARMv4.c_psr_mode) { case ProcessorARMv4.c_psr_mode_FIQ : return HardwareException.FastInterrupt; case ProcessorARMv4.c_psr_mode_IRQ : return HardwareException.Interrupt; case ProcessorARMv4.c_psr_mode_SVC : return HardwareException.SoftwareInterrupt; case ProcessorARMv4.c_psr_mode_ABORT: return HardwareException.DataAbort; } return HardwareException.None; } } } ================================================ FILE: Zelig/Zelig/RunTime/Zelig/Kernel/HardwareModel/TargetPlatform/ARMv4/MMUv4.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // namespace Microsoft.Zelig.Runtime.TargetPlatform.ARMv4 { using System; using TS = Microsoft.Zelig.Runtime.TypeSystem; public static class MMUv4 { public const uint FirstLevelKind__Fault = 0x00; public const uint FirstLevelKind__Coarse = 0x11; public const uint FirstLevelKind__Section = 0x12; public const uint FirstLevelKind__Fine = 0x13; public const uint FirstLevelKind__MASK = 0x13; public const int FirstLevelKind__AP__shift = 10; public const uint FirstLevelKind__Cacheable = 1U << 3; public const uint FirstLevelKind__Buffered = 1U << 2; //--// public const uint CoarseKind__Fault = 0x00; public const uint CoarseKind__Large = 0x01; public const uint CoarseKind__Small = 0x02; public const uint CoarseKind__Tiny = 0x03; public const uint CoarseKind__MASK = 0x03; public const uint CoarseKind__Cacheable = 1U << 3; public const uint CoarseKind__Buffered = 1U << 2; public const int CoarseKind__AP0__shift = 4; public const int CoarseKind__AP1__shift = 6; public const int CoarseKind__AP2__shift = 8; public const int CoarseKind__AP3__shift = 10; //--// public const uint AP__NoAccess = 0; public const uint AP__Client = 1; public const uint AP__Reserved = 2; public const uint AP__Manager = 3; public const uint AP__MASK = 3; //--// private const uint c_TLB_FirstLevelSlots = 4 * 1024; private const uint c_TLB_FirstLevelSize = c_TLB_FirstLevelSlots * sizeof(uint); private const uint c_TLB_FirstLevelOffset = 1024 * 1024; public const uint c_TLB_SecondLevelSlots = 256; public const uint c_TLB_SecondLevelSize = c_TLB_SecondLevelSlots * sizeof(uint); private const uint c_TLB_SecondLevelOffset = 4 * 1024; public const uint c_SectionSize = 1024 * 1024; public const uint c_CoarsePageSize = 4 * 1024; // // State // [AlignmentRequirements( c_TLB_FirstLevelSize, sizeof(uint) )] static uint[] s_TLB_FirstLevel = new uint[c_TLB_FirstLevelSlots]; //--// public static unsafe void EnableTLB() { #if SLOW const uint mask = Coprocessor15.c_ControlRegister__ICache | Coprocessor15.c_ControlRegister__DCache ; #else const uint mask = Coprocessor15.c_ControlRegister__ICache | Coprocessor15.c_ControlRegister__DCache | Coprocessor15.c_ControlRegister__MMU ; #endif // // Disable MMU and caches. // Coprocessor15.ResetControlRegisterBits( mask ); Coprocessor15.InvalidateMMUTLBs(); Coprocessor15.InvalidateCaches(); Coprocessor15.DrainWriteBuffer(); Coprocessor15.SetDomainAccessControl( 0xFFFFFFFF ); fixed(uint* ptr = s_TLB_FirstLevel) { Coprocessor15.SetTranslationTableBaseRegister( ptr ); } // // Enable MMU and caches. // Coprocessor15.SetControlRegisterBits( mask ); ProcessorARMv4.Nop(); ProcessorARMv4.Nop(); // // Invalidate MMU TLBs. // Coprocessor15.InvalidateMMUTLBs(); } public static void ClearTLB() { for(int pos = 0; pos < s_TLB_FirstLevel.Length; pos++) { s_TLB_FirstLevel[pos] = FirstLevelKind__Fault; } } public static void ConfigureRangeAsSections( UIntPtr startAddress , UIntPtr endAddress , UIntPtr physicalAddress , uint AP , bool fCacheable , bool fBuffered ) { uint bits = FirstLevelKind__Section | ((AP & AP__MASK) << FirstLevelKind__AP__shift); if(fCacheable) bits |= FirstLevelKind__Cacheable; if(fBuffered ) bits |= FirstLevelKind__Buffered; for(int diff = AddressMath.Distance( startAddress, endAddress ); diff > 0; diff -= (int)c_TLB_FirstLevelOffset) { UIntPtr baseAddress = AddressMath.AlignToLowerBoundary ( physicalAddress, c_SectionSize ); uint index = AddressMath.IndexRelativeToLowerBoundary( startAddress , c_TLB_FirstLevelOffset ); s_TLB_FirstLevel[index] = baseAddress.ToUInt32() | bits; startAddress = AddressMath.Increment( startAddress , c_TLB_FirstLevelOffset ); physicalAddress = AddressMath.Increment( physicalAddress, c_TLB_FirstLevelOffset ); } } public static unsafe void ConfigureRangeAsCoarsePages( UIntPtr startAddress , UIntPtr endAddress , uint[] secondLevelDescriptor ) { fixed(uint* physicalAddressPtr = secondLevelDescriptor) { UIntPtr physicalAddress = new UIntPtr( physicalAddressPtr ); uint bits = FirstLevelKind__Coarse; for(int diff = AddressMath.Distance( startAddress, endAddress ); diff > 0; diff -= (int)c_TLB_FirstLevelOffset) { UIntPtr baseAddress = AddressMath.AlignToLowerBoundary ( physicalAddress, c_TLB_SecondLevelSize ); uint index = AddressMath.IndexRelativeToLowerBoundary( startAddress , c_TLB_FirstLevelOffset ); s_TLB_FirstLevel[index] = baseAddress.ToUInt32() | bits; startAddress = AddressMath.Increment( startAddress , c_TLB_FirstLevelOffset ); physicalAddress = AddressMath.Increment( physicalAddress, c_TLB_FirstLevelOffset ); } } } public static void ConfigureSecondLevelAsSmallPages( UIntPtr startAddress , UIntPtr endAddress , UIntPtr physicalAddress , uint[] secondLevelDescriptor , uint AP , bool fCacheable , bool fBuffered ) { uint bits = CoarseKind__Small; bits |= (AP & AP__MASK) << CoarseKind__AP0__shift; bits |= (AP & AP__MASK) << CoarseKind__AP1__shift; bits |= (AP & AP__MASK) << CoarseKind__AP2__shift; bits |= (AP & AP__MASK) << CoarseKind__AP3__shift; if(fCacheable) bits |= CoarseKind__Cacheable; if(fBuffered ) bits |= CoarseKind__Buffered; for(int diff = AddressMath.Distance( startAddress, endAddress ); diff > 0; diff -= (int)c_CoarsePageSize) { UIntPtr baseAddress = AddressMath.AlignToLowerBoundary ( physicalAddress, c_CoarsePageSize ); uint index = AddressMath.IndexRelativeToLowerBoundary( startAddress , c_CoarsePageSize ); secondLevelDescriptor[index] = baseAddress.ToUInt32() | bits; startAddress = AddressMath.Increment( startAddress , c_CoarsePageSize ); physicalAddress = AddressMath.Increment( physicalAddress, c_CoarsePageSize ); } } //--// public static void AddCacheableSection( uint start , uint end , uint physical ) { ConfigureRangeAsSections( new UIntPtr( start ), new UIntPtr( end ), new UIntPtr( physical ), MMUv4.AP__Manager, true, true ); } public static void AddUncacheableSection( uint start , uint end , uint physical ) { ConfigureRangeAsSections( new UIntPtr( start ), new UIntPtr( end ), new UIntPtr( physical ), MMUv4.AP__Manager, false, false ); } public static void AddCoarsePages( uint start , uint end , uint[] table ) { MMUv4.ConfigureRangeAsCoarsePages( new UIntPtr( start ), new UIntPtr( end ), table ); } public static void AddCacheableCoarsePages( uint start , uint end , uint physical , uint[] table ) { ConfigureSecondLevelAsSmallPages( new UIntPtr( start ), new UIntPtr( end ), new UIntPtr( physical ), table, MMUv4.AP__Manager, true, true ); } } } ================================================ FILE: Zelig/Zelig/RunTime/Zelig/Kernel/HardwareModel/TargetPlatform/ARMv4/ProcessorARMv4.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // namespace Microsoft.Zelig.Runtime.TargetPlatform.ARMv4 { using System; using TS = Microsoft.Zelig.Runtime.TypeSystem; using EncDef = Microsoft.Zelig.TargetModel.ArmProcessor.EncodingDefinition_ARM; public abstract partial class ProcessorARMv4 : Processor { public const int c_psr_bit_T = EncDef.c_psr_bit_T; public const int c_psr_bit_F = EncDef.c_psr_bit_F; public const int c_psr_bit_I = EncDef.c_psr_bit_I; public const int c_psr_bit_V = EncDef.c_psr_bit_V; public const int c_psr_bit_C = EncDef.c_psr_bit_C; public const int c_psr_bit_Z = EncDef.c_psr_bit_Z; public const int c_psr_bit_N = EncDef.c_psr_bit_N; public const uint c_psr_T = EncDef.c_psr_T; public const uint c_psr_F = EncDef.c_psr_F; public const uint c_psr_I = EncDef.c_psr_I; public const uint c_psr_V = EncDef.c_psr_V; public const uint c_psr_C = EncDef.c_psr_C; public const uint c_psr_Z = EncDef.c_psr_Z; public const uint c_psr_N = EncDef.c_psr_N; //--// public const uint c_psr_mode = EncDef.c_psr_mode; public const uint c_psr_mode_USER = EncDef.c_psr_mode_USER; public const uint c_psr_mode_FIQ = EncDef.c_psr_mode_FIQ; public const uint c_psr_mode_IRQ = EncDef.c_psr_mode_IRQ; public const uint c_psr_mode_SVC = EncDef.c_psr_mode_SVC; public const uint c_psr_mode_ABORT = EncDef.c_psr_mode_ABORT; public const uint c_psr_mode_UNDEF = EncDef.c_psr_mode_UNDEF; public const uint c_psr_mode_SYS = EncDef.c_psr_mode_SYS; public const uint c_psr_field_c = EncDef.c_psr_field_c; public const uint c_psr_field_x = EncDef.c_psr_field_x; public const uint c_psr_field_s = EncDef.c_psr_field_s; public const uint c_psr_field_f = EncDef.c_psr_field_f; public const uint c_psr_field_ALL = EncDef.c_psr_field_ALL; //--// public const uint c_InterruptsOff = EncDef.c_psr_I; public const uint c_AllInterruptsOff = EncDef.c_psr_I | EncDef.c_psr_F; public static class MethodWrapperHelpers { [TS.WellKnownMethod( "Microsoft_Zelig_ProcessorARMv4_MethodWrapperHelpers_ScratchedRegisters" )] public static extern uint ScratchedRegisters(); [TS.WellKnownMethod( "Microsoft_Zelig_ProcessorARMv4_MethodWrapperHelpers_PushRegisters" )] public static extern void PushRegisters( uint indexRegister , bool fWriteBackIndexRegister , bool fAddComputedRegisters , uint registerMask ); [TS.WellKnownMethod( "Microsoft_Zelig_ProcessorARMv4_MethodWrapperHelpers_PopRegisters" )] public static extern void PopRegisters( uint indexRegister , bool fWriteBackIndexRegister , bool fAddComputedRegisters , bool fRestoreSPSR , uint registerMask ); [TS.WellKnownMethod( "Microsoft_Zelig_ProcessorARMv4_MethodWrapperHelpers_PushStackFrame" )] public static extern void PushStackFrame(); [TS.WellKnownMethod( "Microsoft_Zelig_ProcessorARMv4_MethodWrapperHelpers_PopStackFrame" )] public static extern void PopStackFrame(); [Inline] public static void AdjustLinkAddress( uint offset ) { ProcessorARMv4.SetRegister( EncDef.c_register_lr, AddressMath.Decrement( ProcessorARMv4.GetRegister( EncDef.c_register_lr ), offset ) ); } [Inline] public static void PushStackPointer( uint offset ) { ProcessorARMv4.SetRegister( EncDef.c_register_sp, AddressMath.Decrement( ProcessorARMv4.GetRegister( EncDef.c_register_sp ), offset ) ); } [Inline] public static void PopStackPointer( uint offset ) { ProcessorARMv4.SetRegister( EncDef.c_register_sp, AddressMath.Increment( ProcessorARMv4.GetRegister( EncDef.c_register_sp ), offset ) ); } } [TS.WellKnownType( "Microsoft_Zelig_ProcessorARMv4_MethodWrapper" )] public sealed class MethodWrapper : AbstractMethodWrapper { public const uint DisableInterruptsMask = EncDef.c_psr_I | EncDef.c_psr_F; private const uint ExtraRegistersSize = 3 * sizeof(uint); [Inline] [DisableNullChecks(ApplyRecursively=true)] public override void Prologue( string typeFullName , string methodFullName , TS.MethodRepresentation.BuildTimeAttributes attribs ) { AddActivationRecordEvent( ActivationRecordEvents.Constructing ); if((attribs & TS.MethodRepresentation.BuildTimeAttributes.StackNotAvailable) == 0) { MethodWrapperHelpers.PushRegisters( EncDef.c_register_sp, true, true, EncDef.c_register_lst_lr ); MethodWrapperHelpers.PushStackFrame(); } AddActivationRecordEvent( ActivationRecordEvents.ReadyForUse ); } [Inline] [DisableNullChecks(ApplyRecursively=true)] public unsafe override void Prologue( string typeFullName , string methodFullName , TS.MethodRepresentation.BuildTimeAttributes attribs , HardwareException he ) { AddActivationRecordEvent( ActivationRecordEvents.EnteringException ); AddActivationRecordEvent( ActivationRecordEvents.Constructing ); switch(he) { case HardwareException.UndefinedInstruction: MethodWrapperHelpers.AdjustLinkAddress( 4 ); break; // Point to the undefined instruction. case HardwareException.PrefetchAbort : MethodWrapperHelpers.AdjustLinkAddress( 4 ); break; case HardwareException.DataAbort : MethodWrapperHelpers.AdjustLinkAddress( 8 ); break; case HardwareException.Interrupt : MethodWrapperHelpers.AdjustLinkAddress( 4 ); break; case HardwareException.FastInterrupt : MethodWrapperHelpers.AdjustLinkAddress( 4 ); break; case HardwareException.SoftwareInterrupt : break; // Skip the SWI instruction. } switch(he) { case HardwareException.VectorTable: case HardwareException.Bootstrap: case HardwareException.LongJump: case HardwareException.Reset: // // No prologue for these. // AddActivationRecordEvent( ActivationRecordEvents.ReadyForUse ); return; } MethodWrapperHelpers.PushRegisters( EncDef.c_register_sp, true, true, EncDef.c_register_lst_lr ); if((attribs & TS.MethodRepresentation.BuildTimeAttributes.SaveFullProcessorContext) != 0) { MethodWrapperHelpers.PushStackPointer( ExtraRegistersSize ); } var ptr = (Context.RegistersOnStack*)GetRegister( EncDef.c_register_sp ).ToPointer(); MethodWrapperHelpers.PushStackFrame(); if((attribs & TS.MethodRepresentation.BuildTimeAttributes.SaveFullProcessorContext) != 0) { switch(he) { case HardwareException.UndefinedInstruction: PrepareStackForException( EncDef.c_psr_mode_UNDEF, ptr ); break; case HardwareException.PrefetchAbort : PrepareStackForException( EncDef.c_psr_mode_ABORT, ptr ); break; case HardwareException.DataAbort : PrepareStackForException( EncDef.c_psr_mode_ABORT, ptr ); break; case HardwareException.Interrupt : PrepareStackForException( EncDef.c_psr_mode_IRQ , ptr ); break; case HardwareException.FastInterrupt : PrepareStackForException( EncDef.c_psr_mode_FIQ , ptr ); break; case HardwareException.SoftwareInterrupt : PrepareStackForException( EncDef.c_psr_mode_SYS , ptr ); break; } } AddActivationRecordEvent( ActivationRecordEvents.ReadyForUse ); } [Inline] [DisableNullChecks(ApplyRecursively=true)] public override void Epilogue( string typeFullName , string methodFullName , TS.MethodRepresentation.BuildTimeAttributes attribs ) { AddActivationRecordEvent( ActivationRecordEvents.ReadyForTearDown ); if((attribs & TS.MethodRepresentation.BuildTimeAttributes.NoReturn) == 0) { MethodWrapperHelpers.PopStackFrame(); AddActivationRecordEvent( ActivationRecordEvents.ReturnToCaller ); MethodWrapperHelpers.PopRegisters( EncDef.c_register_sp, true, true, false, EncDef.c_register_lst_pc ); AddActivationRecordEvent( ActivationRecordEvents.NonReachable ); } else { // // The method is not supposed to return, but we have to put something here, // because the stack crawling code will look for this spot during stack unwinding... // Breakpoint( 0x1 ); AddActivationRecordEvent( ActivationRecordEvents.NonReachable ); } } [Inline] [DisableNullChecks(ApplyRecursively=true)] public unsafe override void Epilogue( string typeFullName , string methodFullName , TS.MethodRepresentation.BuildTimeAttributes attribs , HardwareException he ) { AddActivationRecordEvent( ActivationRecordEvents.ReadyForTearDown ); switch(he) { case HardwareException.VectorTable: case HardwareException.Bootstrap: case HardwareException.Reset: return; case HardwareException.LongJump: { var ptr = (Context.RegistersOnStack*)GetRegister( EncDef.c_register_r1 ).ToPointer(); SetRegister( EncDef.c_register_sp, ptr->SP ); SetRegister( EncDef.c_register_lr, ptr->LR ); SetRegister( EncDef.c_register_r1, new UIntPtr( &ptr->R0 ) ); AddActivationRecordEvent( ActivationRecordEvents.LongJump ); MethodWrapperHelpers.PopRegisters( EncDef.c_register_r1, false, true, false, EncDef.c_register_lst_pc ); AddActivationRecordEvent( ActivationRecordEvents.NonReachable ); } return; default: { MethodWrapperHelpers.PopStackFrame(); if((attribs & TS.MethodRepresentation.BuildTimeAttributes.SaveFullProcessorContext) != 0) { var ptr = (Context.RegistersOnStack*)GetRegister( EncDef.c_register_sp ).ToPointer(); switch(he) { case HardwareException.UndefinedInstruction: RestoreStackForException( EncDef.c_psr_mode_UNDEF, ptr ); break; case HardwareException.PrefetchAbort : RestoreStackForException( EncDef.c_psr_mode_ABORT, ptr ); break; case HardwareException.DataAbort : RestoreStackForException( EncDef.c_psr_mode_ABORT, ptr ); break; case HardwareException.Interrupt : RestoreStackForException( EncDef.c_psr_mode_IRQ , ptr ); break; case HardwareException.FastInterrupt : RestoreStackForException( EncDef.c_psr_mode_FIQ , ptr ); break; case HardwareException.SoftwareInterrupt : RestoreStackForException( EncDef.c_psr_mode_SYS , ptr ); break; } MethodWrapperHelpers.PopStackPointer( ExtraRegistersSize ); } AddActivationRecordEvent( ActivationRecordEvents.ReturnFromException ); MethodWrapperHelpers.PopRegisters( EncDef.c_register_sp, true, true, true, EncDef.c_register_lst_pc ); AddActivationRecordEvent( ActivationRecordEvents.NonReachable ); } return; } } [Inline] private static unsafe void PrepareStackForException( uint mode , Context.RegistersOnStack* ptr ) { // // Keep interrupts disabled. // mode |= DisableInterruptsMask; // // Get CSPR of the calling context. // var CPSR = GetSavedStatusRegister(); // // Save it. // ptr->CPSR = CPSR; // // Disable interrupts. // CPSR |= DisableInterruptsMask; // // Go back to the previous mode. // SetStatusRegister( EncDef.c_psr_field_c, CPSR ); // // Save unbanked R13 and R14. // ptr->LR = GetRegister( EncDef.c_register_lr ); ptr->SP = GetRegister( EncDef.c_register_sp ); // // Switch back to the exception handling mode. // SetStatusRegister( EncDef.c_psr_field_c, mode ); // // R1 should point to the Register Context on the stack. // SetRegister( EncDef.c_register_r1, new UIntPtr( ptr ) ); } [Inline] private static unsafe void RestoreStackForException( uint mode , Context.RegistersOnStack* ptr ) { // // Keep interrupts disabled. // mode |= DisableInterruptsMask; // // Get CSPR of the calling context. // var CPSR = ptr->CPSR; // // Restore the SPSR // SetSavedStatusRegister( EncDef.c_psr_field_ALL, CPSR ); // // Disable interrupts. // CPSR |= DisableInterruptsMask; // // Go back to the previous mode. // SetStatusRegister( EncDef.c_psr_field_c, CPSR ); // // Save unbanked R13 and R14. // SetRegister( EncDef.c_register_lr, ptr->LR ); SetRegister( EncDef.c_register_sp, ptr->SP ); // // Switch back to the exception handling mode. // SetStatusRegister( EncDef.c_psr_field_c, mode ); } } //--// // // Helper Methods // [TS.WellKnownMethod( "ProcessorARM_SetRegister" )] public static extern void SetRegister( uint reg , UIntPtr value ); [TS.WellKnownMethod( "ProcessorARM_GetRegister" )] public static extern UIntPtr GetRegister( uint reg ); [TS.WellKnownMethod( "ProcessorARM_SetSystemRegister" )] public static extern void SetSystemRegister( uint reg , uint value ); [TS.WellKnownMethod( "ProcessorARM_GetSystemRegister" )] public static extern uint GetSystemRegister( uint reg ); //--// [TS.WellKnownMethod( "ProcessorARM_SetStatusRegister" )] public static extern void SetStatusRegister( uint fields , uint value ); [TS.WellKnownMethod( "ProcessorARM_GetStatusRegister" )] public static extern uint GetStatusRegister(); [TS.WellKnownMethod( "ProcessorARM_SetSavedStatusRegister" )] public static extern void SetSavedStatusRegister( uint fields , uint value ); [TS.WellKnownMethod( "ProcessorARM_GetSavedStatusRegister" )] public static extern uint GetSavedStatusRegister(); //--// [TS.WellKnownMethod( "ProcessorARM_MoveToCoprocessor" )] public static extern void MoveToCoprocessor( uint CpNum , uint Op1 , uint CRn , uint CRm , uint Op2 , uint value ); [TS.WellKnownMethod( "ProcessorARM_MoveFromCoprocessor" )] public static extern uint MoveFromCoprocessor( uint CpNum , uint Op1 , uint CRn , uint CRm , uint Op2 ); [TS.WellKnownMethod( "ProcessorARM_Breakpoint" )] public static extern void Breakpoint( uint value ); //--// public override void FlushCacheLine( UIntPtr target ) { } //--//--// [Inline] public override bool AreInterruptsDisabled() { uint cpsr = GetStatusRegister(); return (cpsr & c_InterruptsOff) == c_InterruptsOff; } public override bool AreAllInterruptsDisabled() { uint cpsr = GetStatusRegister(); return (cpsr & c_AllInterruptsOff) == c_AllInterruptsOff; } //--//--// [Inline] public static uint DisableInterrupts() { uint cpsr = GetStatusRegister(); SetStatusRegister( c_psr_field_c, cpsr | c_InterruptsOff ); return cpsr; } [Inline] public static uint DisableAllInterrupts() { uint cpsr = GetStatusRegister(); SetStatusRegister( c_psr_field_c, cpsr | c_AllInterruptsOff ); return cpsr; } //--// [Inline] public static uint EnableInterrupts() { uint cpsr = GetStatusRegister(); SetStatusRegister( c_psr_field_c, cpsr & ~c_InterruptsOff ); return cpsr; } [Inline] public static uint EnableAllInterrupts() { uint cpsr = GetStatusRegister(); SetStatusRegister( c_psr_field_c, cpsr & ~c_AllInterruptsOff ); return cpsr; } //--// [Inline] public override void Breakpoint() { Breakpoint( 0 ); } //--// [Inline] public static void SetMode( uint cpsr ) { SetStatusRegister( c_psr_field_c, cpsr ); } [NoInline] [MemoryUsage(MemoryUsage.Bootstrap)] public static void Nop() { // // Do-nothing method just to flush the pipeline. // } //--// [NoReturn()] [BottomOfCallStack()] [HardwareExceptionHandler(HardwareException.Bootstrap)] private static void Bootstrap() { // // WARNING! // WARNING! Keep this method empty!!!! // WARNING! // // We need a way to bootstrap code generation for the entrypoint into the system, which is not a regular piece of code. // It's only composed of a single absolute branch to the entrypoint. // // The code responsible for emitting the opcode for the return operator will detect that // this method is decorated with the Bootstrap flag and it will generate the proper code. // // WARNING! // WARNING! Keep this method empty!!!! // WARNING! // } [NoInline] [NoReturn()] [BottomOfCallStack()] [HardwareExceptionHandler(HardwareException.VectorTable)] private static void VectorsTable() { // // WARNING! // WARNING! Keep this method empty!!!! // WARNING! // // We need a way to bootstrap code generation for the vector table, which is not a regular piece of code. // It's only composed of branches and the location of the branches is mandated by the hardware. // // The code responsible for emitting the opcode for the return operator will detect that // this method is decorated with the VectorTable flag and it will generate the proper code. // // WARNING! // WARNING! Keep this method empty!!!! // WARNING! // } //--// static readonly SoftBreakpointDescriptor[] s_softBreakpointTable = new SoftBreakpointDescriptor[128]; [NoInline] [BottomOfCallStack] [MemoryUsage( MemoryUsage.Bootstrap )] [DebuggerHookHandler( DebuggerHook.GetSoftBreakpointTable )] static SoftBreakpointDescriptor[] GetSoftBreakpointTable() { SoftBreakpointDescriptor[] res = s_softBreakpointTable; Processor.Instance.Breakpoint(); return res; } public static unsafe uint DebuggerAwareRead( uint* ptr ) { uint val = *ptr; if(val == 0xE1200070) // BKPT opcode { UIntPtr address = new UIntPtr( ptr ); for(int i = 0; i < s_softBreakpointTable.Length; i++) { var address2 = s_softBreakpointTable[i].Address; if(address2 == new UIntPtr( 0 )) { break; } if(address2 == address) { return s_softBreakpointTable[i].Value; } } } return val; } } [ExtendClass( typeof( Microsoft.Zelig.Runtime.Processor ) )] internal class ProcessorImpl { [MergeWithTargetImplementation] internal ProcessorImpl() { } [NoInline] [MemoryUsage( MemoryUsage.Bootstrap )] public static int Delay( int count ) { const int fixedOverhead = 16; const int perRoundCost = 6; count -= fixedOverhead; while(count > 0) { count -= perRoundCost; } return count; } } } ================================================ FILE: Zelig/Zelig/RunTime/Zelig/Kernel/HardwareModel/TargetPlatform/ARMv4/ProcessorARMv4_ContextSwitch.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // namespace Microsoft.Zelig.Runtime.TargetPlatform.ARMv4 { using System; using System.Runtime.InteropServices; using Microsoft.Zelig.TargetModel.ArmProcessor; using TS = Microsoft.Zelig.Runtime.TypeSystem; using EncDef = Microsoft.Zelig.TargetModel.ArmProcessor.EncodingDefinition_ARM; public abstract partial class ProcessorARMv4 : Processor { protected static EncDef s_Encoding = (EncodingDefinition_ARM)CurrentInstructionSetEncoding.GetEncoding(); //--// public abstract new class Context : Processor.Context { // // WARNING: Don't assume the actual layout of the structure is sequential!!! // WARNING: The code generator rearranges the fields to minimize the cost of a context switch!!! // [TS.WellKnownType( "Microsoft_Zelig_ProcessorARMv4_RegistersOnStack" )] [StructLayout( LayoutKind.Sequential, Pack = 4 )] public struct RegistersOnStack { public const uint StackRegister = EncDef.c_register_sp; public const uint LinkRegister = EncDef.c_register_lr; public const uint ProgramCounterRegister = EncDef.c_register_pc; // // State // [TS.AssumeReferenced] public uint CPSR; [TS.AssumeReferenced] public UIntPtr SP; [TS.AssumeReferenced] public UIntPtr LR; [TS.AssumeReferenced] public UIntPtr R0; [TS.AssumeReferenced] public UIntPtr R1; [TS.AssumeReferenced] public UIntPtr R2; [TS.AssumeReferenced] public UIntPtr R3; [TS.AssumeReferenced] public UIntPtr R4; [TS.AssumeReferenced] public UIntPtr R5; [TS.AssumeReferenced] public UIntPtr R6; [TS.AssumeReferenced] public UIntPtr R7; [TS.AssumeReferenced] public UIntPtr R8; [TS.AssumeReferenced] public UIntPtr R9; [TS.AssumeReferenced] public UIntPtr R10; [TS.AssumeReferenced] public UIntPtr R11; [TS.AssumeReferenced] public UIntPtr R12; [TS.AssumeReferenced] public UIntPtr PC; // // Helper Methods // internal unsafe UIntPtr* GetRegisterPointer( uint idx ) { switch(idx) { case 0: fixed(UIntPtr* ptr = &this.R0 ) { return ptr; }; case 1: fixed(UIntPtr* ptr = &this.R1 ) { return ptr; }; case 2: fixed(UIntPtr* ptr = &this.R2 ) { return ptr; }; case 3: fixed(UIntPtr* ptr = &this.R3 ) { return ptr; }; case 4: fixed(UIntPtr* ptr = &this.R4 ) { return ptr; }; case 5: fixed(UIntPtr* ptr = &this.R5 ) { return ptr; }; case 6: fixed(UIntPtr* ptr = &this.R6 ) { return ptr; }; case 7: fixed(UIntPtr* ptr = &this.R7 ) { return ptr; }; case 8: fixed(UIntPtr* ptr = &this.R8 ) { return ptr; }; case 9: fixed(UIntPtr* ptr = &this.R9 ) { return ptr; }; case 10: fixed(UIntPtr* ptr = &this.R10) { return ptr; }; case 11: fixed(UIntPtr* ptr = &this.R11) { return ptr; }; case 12: fixed(UIntPtr* ptr = &this.R12) { return ptr; }; case 13: fixed(UIntPtr* ptr = &this.SP ) { return ptr; }; case 14: fixed(UIntPtr* ptr = &this.LR ) { return ptr; }; case 15: fixed(UIntPtr* ptr = &this.PC ) { return ptr; }; } return null; } public void Assign( ref RegistersOnStack other ) { //// fixed(RegistersOnStack* dst = &this) //// { //// fixed(RegistersOnStack* src = &other) //// { //// UIntPtr dstStart = new UIntPtr( dst ); //// UIntPtr srcStart = new UIntPtr( src ); //// UIntPtr srcEnd = AddressMath.Increment( srcStart, (uint)Marshal.SizeOf( typeof(RegistersOnStack) ) ); //// //// Memory.CopyNonOverlapping( srcStart, srcEnd, dstStart ); //// } //// } this.R0 = other.R0; this.R1 = other.R1; this.R2 = other.R2; this.R3 = other.R3; this.R4 = other.R4; this.R5 = other.R5; this.R6 = other.R6; this.R7 = other.R7; this.R8 = other.R8; this.R9 = other.R9; this.R10 = other.R10; this.R11 = other.R11; this.R12 = other.R12; this.SP = other.SP; this.LR = other.LR; this.PC = other.PC; this.CPSR = other.CPSR; } } // // State // const uint c_STMFD_Mask = 0xFFFF0000; const uint c_STMFD_Opcode = 0xE92D0000; const uint c_SUBSP_Mask = 0xFFFFF000; const uint c_SUBSP_Opcode = 0xE24DD000; //--// const uint c_LDMFD_Mask = 0xFFFF0000; const uint c_LDMFD_Opcode = 0xE8BD0000; //--// public RegistersOnStack Registers; // // Constructor Methods // public Context(ThreadImpl owner) : base(owner) { } // // Helper Methods // [NoInline] public override void Populate() { GetAllTheRegisters(); // // Now we have all the registers at this method boundary, unwind one more time and we have the state at the caller's site. // Unwind(); } [NoInline] public override void Populate( Processor.Context context ) { Context ctx = (Context)context; this.Registers.Assign( ref ctx.Registers ); } [NoInline] public unsafe override void PopulateFromDelegate( Delegate dlg, uint[] stack ) { DelegateImpl dlgImpl = (DelegateImpl)(object)dlg; ArrayImpl stackImpl = (ArrayImpl )(object)stack; ObjectImpl objImpl = (ObjectImpl )(object)dlg.Target; this.Registers.CPSR = c_psr_mode_SYS; this.Registers.PC = new UIntPtr( dlgImpl.InnerGetCodePointer().Target.ToPointer() ); this.Registers.SP = new UIntPtr( stackImpl.GetEndDataPointer() ); this.Registers.R0 = objImpl.ToPointer(); } [NoInline] public override void SetupForExceptionHandling( uint mode ) { using(Runtime.SmartHandles.InterruptState.DisableAll()) { UIntPtr stack = this.Registers.SP; uint oldMode = GetStatusRegister(); // // Enter target mode, with interrupts disabled. // SetStatusRegister( c_psr_field_c, c_psr_I | c_psr_F | mode ); SetRegister( Context.RegistersOnStack.StackRegister, stack ); // // Switch back to original mode. // SetStatusRegister( c_psr_field_c, oldMode ); } } [NoInline] public unsafe override bool Unwind() { UIntPtr pc = this.ProgramCounter; TS.CodeMap cm = TS.CodeMap.ResolveAddressToCodeMap( pc ); this.InPrologue = false; this.InEpilogue = false; if(cm != null) { for(int i = 0; i < cm.Ranges.Length; i++) { TS.CodeMap.Range rng = cm.Ranges[i]; if((rng.Flags & TS.CodeMap.Flags.EntryPoint) != 0) { if((rng.Flags & TS.CodeMap.Flags.BottomOfCallStack) != 0) { return false; } UIntPtr sp = this.StackPointer; UIntPtr address = rng.Start; uint regRestoreMap = 0; uint stackAdjustment = 0; bool fReturnAddressinLR = false; bool fDone = false; if(pc == address) { // // We are at the beginning of a method, the return address is in LR for sure. // fReturnAddressinLR = true; // // The PC has not executed the next prologue instruction, stop processing. // fDone = true; this.InPrologue = true; } if(fDone == false) { if((rng.Flags & TS.CodeMap.Flags.HasIntRegisterSave) != 0) { uint* ptr = (uint*)address.ToPointer(); uint opcode_STMFD = DebuggerAwareRead( ptr++ ); address = new UIntPtr( ptr ); if((opcode_STMFD & c_STMFD_Mask) == c_STMFD_Opcode) { regRestoreMap = opcode_STMFD & 0xFFFF; } else { //CHECKS.ASSERT( false, "Expecting a STMFD opcode, got 0x{0:X8}", opcode_STMFD ); return false; } } else { // // No register push, the return address is in LR for sure. // fReturnAddressinLR = true; } } if(pc == address) { // // The PC has not executed the next prologue instruction, stop processing. // fDone = true; this.InPrologue = true; } if(fDone == false) { if((rng.Flags & TS.CodeMap.Flags.HasStackAdjustment) != 0) { uint* ptr = (uint*)address.ToPointer(); uint opcode_SUBSP = DebuggerAwareRead( ptr ); if((opcode_SUBSP & c_SUBSP_Mask) == c_SUBSP_Opcode) { stackAdjustment = s_Encoding.get_DataProcessing_ImmediateValue( opcode_SUBSP ); } else { //CHECKS.ASSERT( false, "Expecting a STMFD opcode, got 0x{0:X8}", opcode_SUBSP ); return false; } } } //--// // // Deal with method epilogue: if we are on one of the return instructions, we need to restore less state. // uint opcode = *(uint*)pc.ToPointer(); if((opcode & c_LDMFD_Mask) == c_LDMFD_Opcode) { stackAdjustment = 0; } //--// sp = AddressMath.Increment( sp, stackAdjustment ); if(fReturnAddressinLR) { this.Registers.PC = this.Registers.LR; } else { UIntPtr* src = (UIntPtr*)sp.ToPointer(); for(uint idx = 0; idx < 16; idx++) { if((regRestoreMap & (1u << (int)idx)) != 0) { // // Prologue saves LR, but we need to restore it as PC. // uint regIdx = (idx == RegistersOnStack.LinkRegister) ? RegistersOnStack.ProgramCounterRegister : idx; UIntPtr* dst = this.Registers.GetRegisterPointer( regIdx ); *dst = *src++; } } sp = new UIntPtr( src ); } this.StackPointer = sp; return true; } } } return false; } [NoInline] public override void SwitchTo() { LongJump( ref this.Registers ); } public override unsafe UIntPtr GetRegisterByIndex( uint idx ) { return *(this.Registers.GetRegisterPointer( idx )); } public override unsafe void SetRegisterByIndex( uint idx , UIntPtr value ) { *(this.Registers.GetRegisterPointer( idx )) = value; } //--// [NoInline] [SaveFullProcessorContext] private unsafe void GetAllTheRegisters() { this.Registers.SP = GetRegister( RegistersOnStack.StackRegister ); this.Registers.PC = GetRegister( RegistersOnStack.ProgramCounterRegister ); Unwind(); } //--// [NoInline] [NoReturn()] [HardwareExceptionHandler(HardwareException.LongJump)] static void LongJump( ref RegistersOnStack registers ) { // // WARNING! // WARNING! Keep this method empty!!!! // WARNING! // // We need a way to make a long jump as part of the exception handling code. // // The code responsible for emitting the prologue of the method will detect that // this method is decorated with the ContextSwitch flag and it will generate the proper code. // // WARNING! // WARNING! Keep this method empty!!!! // WARNING! // } //--// [Inline] public static void InterruptHandlerWithContextSwitch( ref RegistersOnStack registers ) { Peripherals.Instance.ProcessInterrupt(); ThreadManager tm = ThreadManager.Instance; // // We keep looping until the current and next threads are the same, // because when swapping out a dead thread, we might wake up a different thread. // while(tm.ShouldContextSwitch) { ContextSwitch( tm, ref registers ); } } [Inline] public static void InterruptHandlerWithoutContextSwitch() { Peripherals.Instance.ProcessInterrupt(); } [Inline] public static void FastInterruptHandlerWithoutContextSwitch() { Peripherals.Instance.ProcessFastInterrupt(); } [Inline] public static void GenericSoftwareInterruptHandler( ref RegistersOnStack registers ) { } //--// private static void ContextSwitch( ThreadManager tm , ref RegistersOnStack registers ) { ThreadImpl currentThread = tm.CurrentThread; ThreadImpl nextThread = tm.NextThread; Context ctx; if(currentThread != null) { ctx = (Context)currentThread.SwappedOutContext; ctx.Registers.Assign( ref registers ); } ctx = (Context)nextThread.SwappedOutContext; registers.Assign( ref ctx.Registers ); tm.CurrentThread = nextThread; ThreadImpl.CurrentThread = nextThread; } // // Access Methods // public override UIntPtr StackPointer { get { return this.Registers.SP; } set { this.Registers.SP = value; } } public override UIntPtr BaseStackPointer { get { return (UIntPtr)0; } } public override uint ExcReturn { get { return 0; } set { } } public override UIntPtr ProgramCounter { get { return this.Registers.PC; } set { this.Registers.PC = value; } } public override uint ScratchedIntegerRegisters { get { return MethodWrapperHelpers.ScratchedRegisters(); } } } } } ================================================ FILE: Zelig/Zelig/RunTime/Zelig/Kernel/HardwareModel/TargetPlatform/ARMv5/ProcessorARMv5.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // namespace Microsoft.Zelig.Runtime.TargetPlatform.ARMv5 { using System; public abstract partial class ProcessorARMv5 : ARMv4.ProcessorARMv4 { //--// public override unsafe void FlushCacheLine( UIntPtr target ) { ARMv4.Coprocessor15.CleanDCache ( target ); ARMv4.Coprocessor15.DrainWriteBuffer( ); ARMv4.Coprocessor15.InvalidateICache( target ); } //--// [NoInline] public static void EnableRunFastMode() { } protected static void InitializeCache() { ARMv4.Coprocessor15.InvalidateICache(); ARMv4.Coprocessor15.InvalidateDCache(); // // Enable ICache // ARMv4.Coprocessor15.SetControlRegisterBits( ARMv4.Coprocessor15.c_ControlRegister__ICache ); } } } ================================================ FILE: Zelig/Zelig/RunTime/Zelig/Kernel/HardwareModel/TargetPlatform/ARMv5/ProcessorARMv5_ContextSwitch.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // namespace Microsoft.Zelig.Runtime.TargetPlatform.ARMv5 { using System; using System.Runtime.InteropServices; using Microsoft.Zelig.TargetModel.ArmProcessor; using TS = Microsoft.Zelig.Runtime.TypeSystem; using EncDef = Microsoft.Zelig.TargetModel.ArmProcessor.EncodingDefinition_ARM; using EncDef_VFP = Microsoft.Zelig.TargetModel.ArmProcessor.EncodingDefinition_VFP_ARM; public abstract partial class ProcessorARMv5 { public abstract new class Context : Processor.Context { // // WARNING: Don't assume the actual layout of the structure is sequential!!! // WARNING: The code generator rearranges the fields to minimize the cost of a context switch!!! // [TS.WellKnownType( "Microsoft_Zelig_ProcessorARMv5_RegistersOnStack" )] [StructLayout( LayoutKind.Sequential, Pack = 4 )] public struct RegistersOnStack { public const uint StackRegister = EncDef.c_register_sp; public const uint LinkRegister = EncDef.c_register_lr; public const uint ProgramCounterRegister = EncDef.c_register_pc; // // State // [TS.AssumeReferenced] public uint CPSR; [TS.AssumeReferenced] public UIntPtr SP; [TS.AssumeReferenced] public UIntPtr LR; [TS.AssumeReferenced] public UIntPtr R0; [TS.AssumeReferenced] public UIntPtr R1; [TS.AssumeReferenced] public UIntPtr R2; [TS.AssumeReferenced] public UIntPtr R3; [TS.AssumeReferenced] public UIntPtr R4; [TS.AssumeReferenced] public UIntPtr R5; [TS.AssumeReferenced] public UIntPtr R6; [TS.AssumeReferenced] public UIntPtr R7; [TS.AssumeReferenced] public UIntPtr R8; [TS.AssumeReferenced] public UIntPtr R9; [TS.AssumeReferenced] public UIntPtr R10; [TS.AssumeReferenced] public UIntPtr R11; [TS.AssumeReferenced] public UIntPtr R12; [TS.AssumeReferenced] public UIntPtr PC; // // Helper Methods // internal unsafe UIntPtr* GetRegisterPointer( uint idx ) { switch(idx) { case 0: fixed(UIntPtr* ptr = &this.R0 ) { return ptr; }; case 1: fixed(UIntPtr* ptr = &this.R1 ) { return ptr; }; case 2: fixed(UIntPtr* ptr = &this.R2 ) { return ptr; }; case 3: fixed(UIntPtr* ptr = &this.R3 ) { return ptr; }; case 4: fixed(UIntPtr* ptr = &this.R4 ) { return ptr; }; case 5: fixed(UIntPtr* ptr = &this.R5 ) { return ptr; }; case 6: fixed(UIntPtr* ptr = &this.R6 ) { return ptr; }; case 7: fixed(UIntPtr* ptr = &this.R7 ) { return ptr; }; case 8: fixed(UIntPtr* ptr = &this.R8 ) { return ptr; }; case 9: fixed(UIntPtr* ptr = &this.R9 ) { return ptr; }; case 10: fixed(UIntPtr* ptr = &this.R10) { return ptr; }; case 11: fixed(UIntPtr* ptr = &this.R11) { return ptr; }; case 12: fixed(UIntPtr* ptr = &this.R12) { return ptr; }; case 13: fixed(UIntPtr* ptr = &this.SP ) { return ptr; }; case 14: fixed(UIntPtr* ptr = &this.LR ) { return ptr; }; case 15: fixed(UIntPtr* ptr = &this.PC ) { return ptr; }; } return null; } public void Assign( ref RegistersOnStack other ) { this.R0 = other.R0; this.R1 = other.R1; this.R2 = other.R2; this.R3 = other.R3; this.R4 = other.R4; this.R5 = other.R5; this.R6 = other.R6; this.R7 = other.R7; this.R8 = other.R8; this.R9 = other.R9; this.R10 = other.R10; this.R11 = other.R11; this.R12 = other.R12; this.SP = other.SP; this.LR = other.LR; this.PC = other.PC; this.CPSR = other.CPSR; } } // // State // const uint c_STMFD_Mask = 0xFFFF0000; const uint c_STMFD_Opcode = 0xE92D0000; const uint c_SUBSP_Mask = 0xFFFFF000; const uint c_SUBSP_Opcode = 0xE24DD000; //--// const uint c_LDMFD_Mask = 0xFFFF0000; const uint c_LDMFD_Opcode = 0xE8BD0000; //--// public RegistersOnStack Registers; // // Constructor Methods // public Context(ThreadImpl owner) : base(owner) { } // // Helper Methods // [NoInline] public override void Populate() { GetAllTheRegisters(); // // Now we have all the registers at this method boundary, unwind one more time and we have the state at the caller's site. // Unwind(); } [NoInline] public override void Populate( Processor.Context context ) { Context ctx = (Context)context; this.Registers.Assign( ref ctx.Registers ); } [NoInline] public unsafe override void PopulateFromDelegate( Delegate dlg, uint[] stack ) { DelegateImpl dlgImpl = (DelegateImpl)(object)dlg; ArrayImpl stackImpl = (ArrayImpl )(object)stack; ObjectImpl objImpl = (ObjectImpl )(object)dlg.Target; this.Registers.CPSR = c_psr_mode_SYS; this.Registers.PC = new UIntPtr( dlgImpl.InnerGetCodePointer().Target.ToPointer() ); this.Registers.SP = new UIntPtr( stackImpl.GetEndDataPointer() ); this.Registers.R0 = objImpl.ToPointer(); } [NoInline] public override void SetupForExceptionHandling( uint mode ) { using(Runtime.SmartHandles.InterruptState.DisableAll()) { UIntPtr stack = this.Registers.SP; uint oldMode = GetStatusRegister(); // // Enter target mode, with interrupts disabled. // SetStatusRegister( c_psr_field_c, c_psr_I | c_psr_F | mode ); SetRegister( Context.RegistersOnStack.StackRegister, stack ); // // Switch back to original mode. // SetStatusRegister( c_psr_field_c, oldMode ); } } [NoInline] public unsafe override bool Unwind() { UIntPtr pc = this.ProgramCounter; TS.CodeMap cm = TS.CodeMap.ResolveAddressToCodeMap( pc ); this.InPrologue = false; this.InEpilogue = false; if(cm != null) { for(int i = 0; i < cm.Ranges.Length; i++) { TS.CodeMap.Range rng = cm.Ranges[i]; if((rng.Flags & TS.CodeMap.Flags.EntryPoint) != 0) { if((rng.Flags & TS.CodeMap.Flags.BottomOfCallStack) != 0) { return false; } UIntPtr sp = this.StackPointer; UIntPtr address = rng.Start; uint regRestoreMap = 0; uint stackAdjustment = 0; bool fReturnAddressinLR = false; bool fDone = false; if(pc == address) { // // We are at the beginning of a method, the return address is in LR for sure. // fReturnAddressinLR = true; // // The PC has not executed the next prologue instruction, stop processing. // fDone = true; this.InPrologue = true; } if(fDone == false) { if((rng.Flags & TS.CodeMap.Flags.HasIntRegisterSave) != 0) { uint* ptr = (uint*)address.ToPointer(); uint opcode_STMFD = DebuggerAwareRead( ptr++ ); address = new UIntPtr( ptr ); if((opcode_STMFD & c_STMFD_Mask) == c_STMFD_Opcode) { regRestoreMap = opcode_STMFD & 0xFFFF; } else { //CHECKS.ASSERT( false, "Expecting a STMFD opcode, got 0x{0:X8}", opcode_STMFD ); return false; } } else { // // No register push, the return address is in LR for sure. // fReturnAddressinLR = true; } } if(pc == address) { // // The PC has not executed the next prologue instruction, stop processing. // fDone = true; this.InPrologue = true; } if(pc == address) { // // The PC has not executed the next prologue instruction, stop processing. // fDone = true; this.InPrologue = true; } if(fDone == false) { if((rng.Flags & TS.CodeMap.Flags.HasStackAdjustment) != 0) { uint* ptr = (uint*)address.ToPointer(); uint opcode_SUBSP = DebuggerAwareRead( ptr ); if((opcode_SUBSP & c_SUBSP_Mask) == c_SUBSP_Opcode) { stackAdjustment = s_Encoding.get_DataProcessing_ImmediateValue( opcode_SUBSP ); } else { //CHECKS.ASSERT( false, "Expecting a STMFD opcode, got 0x{0:X8}", opcode_SUBSP ); return false; } } } // // Deal with method epilogue: if we are on one of the return instructions, we need to restore less state. // uint opcode = *(uint*)pc.ToPointer(); if((opcode & c_LDMFD_Mask) == c_LDMFD_Opcode) { stackAdjustment = 0; } //--// sp = AddressMath.Increment( sp, stackAdjustment ); if(fReturnAddressinLR) { this.Registers.PC = this.Registers.LR; } else { UIntPtr* src = (UIntPtr*)sp.ToPointer(); for(uint idx = 0; idx < 16; idx++) { if((regRestoreMap & (1u << (int)idx)) != 0) { // // Prologue saves LR, but we need to restore it as PC. // uint regIdx = (idx == RegistersOnStack.LinkRegister) ? RegistersOnStack.ProgramCounterRegister : idx; UIntPtr* dst = this.Registers.GetRegisterPointer( regIdx ); *dst = *src++; } } sp = new UIntPtr( src ); } this.StackPointer = sp; return true; } } } return false; } [NoInline] public override void SwitchTo() { LongJump( ref this.Registers ); } public override unsafe UIntPtr GetRegisterByIndex( uint idx ) { return *(this.Registers.GetRegisterPointer( idx )); } public override unsafe void SetRegisterByIndex( uint idx , UIntPtr value ) { *(this.Registers.GetRegisterPointer( idx )) = value; } //--// [NoInline] [SaveFullProcessorContext] private unsafe void GetAllTheRegisters() { this.Registers.SP = GetRegister( RegistersOnStack.StackRegister ); this.Registers.PC = GetRegister( RegistersOnStack.ProgramCounterRegister ); Unwind(); } //--// [NoInline] [NoReturn()] [HardwareExceptionHandler(HardwareException.LongJump)] static void LongJump( ref RegistersOnStack registers ) { // // WARNING! // WARNING! Keep this method empty!!!! // WARNING! // // We need a way to make a long jump as part of the exception handling code. // // The code responsible for emitting the prologue of the method will detect that // this method is decorated with the ContextSwitch flag and it will generate the proper code. // // WARNING! // WARNING! Keep this method empty!!!! // WARNING! // } //--// static uint fault_DFSR; static uint fault_IFSR; static uint fault_FAR; [NoInline] [NoReturn()] [HardwareExceptionHandler(HardwareException.UndefinedInstruction)] [MemoryUsage(MemoryUsage.Bootstrap)] static void UndefinedInstruction() { fault_DFSR = MoveFromCoprocessor( 15, 0, 5, 0, 0 ); fault_IFSR = MoveFromCoprocessor( 15, 0, 5, 0, 1 ); fault_FAR = MoveFromCoprocessor( 15, 0, 6, 0, 0 ); Processor.Instance.Breakpoint(); } [NoInline] [NoReturn()] [HardwareExceptionHandler(HardwareException.PrefetchAbort)] [MemoryUsage(MemoryUsage.Bootstrap)] static void PrefetchAbort() { fault_DFSR = MoveFromCoprocessor( 15, 0, 5, 0, 0 ); fault_IFSR = MoveFromCoprocessor( 15, 0, 5, 0, 1 ); fault_FAR = MoveFromCoprocessor( 15, 0, 6, 0, 0 ); Processor.Instance.Breakpoint(); } [NoInline] [NoReturn()] [HardwareExceptionHandler(HardwareException.DataAbort)] [MemoryUsage(MemoryUsage.Bootstrap)] static void DataAbort() { fault_DFSR = MoveFromCoprocessor( 15, 0, 5, 0, 0 ); fault_IFSR = MoveFromCoprocessor( 15, 0, 5, 0, 1 ); fault_FAR = MoveFromCoprocessor( 15, 0, 6, 0, 0 ); Processor.Instance.Breakpoint(); } //--// [Inline] public static void InterruptHandlerWithContextSwitch( ref RegistersOnStack registers ) { Peripherals.Instance.ProcessInterrupt(); ThreadManager tm = ThreadManager.Instance; // // We keep looping until the current and next threads are the same, // because when swapping out a dead thread, we might wake up a different thread. // while(tm.ShouldContextSwitch) { ContextSwitch( tm, ref registers ); } } [Inline] public static void InterruptHandlerWithoutContextSwitch() { Peripherals.Instance.ProcessInterrupt(); } [Inline] public static void FastInterruptHandlerWithoutContextSwitch() { Peripherals.Instance.ProcessFastInterrupt(); } [Inline] public static void GenericSoftwareInterruptHandler( ref RegistersOnStack registers ) { } //--// private static void ContextSwitch( ThreadManager tm , ref RegistersOnStack registers ) { ThreadImpl currentThread = tm.CurrentThread; ThreadImpl nextThread = tm.NextThread; Context ctx; if(currentThread != null) { ctx = (Context)currentThread.SwappedOutContext; ctx.Registers.Assign( ref registers ); } ctx = (Context)nextThread.SwappedOutContext; registers.Assign( ref ctx.Registers ); tm.CurrentThread = nextThread; ThreadImpl.CurrentThread = nextThread; } // // Access Methods // public override UIntPtr StackPointer { get { return this.Registers.SP; } set { this.Registers.SP = value; } } public override UIntPtr BaseStackPointer { get { return (UIntPtr)0; } } public override UIntPtr ProgramCounter { get { return this.Registers.PC; } set { this.Registers.PC = value; } } public override uint ScratchedIntegerRegisters { get { return MethodWrapperHelpers.ScratchedRegisters(); } } } } } ================================================ FILE: Zelig/Zelig/RunTime/Zelig/Kernel/HardwareModel/TargetPlatform/ARMv5_VFP/BinaryOperations.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // namespace Microsoft.Zelig.Runtime.TargetPlatform.ARMv5_VFP.Helpers { using System; using System.Runtime.CompilerServices; using TS = Microsoft.Zelig.Runtime.TypeSystem; internal static class BinaryOperations { [TS.WellKnownMethod( "SoftVFP_BinaryOperations_FloatRem" )] internal static float FloatRem( float left , float right ) { return left - (int)(left / right) * right; } //--// [TS.WellKnownMethod( "SoftVFP_BinaryOperations_DoubleRem" )] internal static double DoubleRem( double left , double right ) { return left - (long)(left / right) * right; } } } ================================================ FILE: Zelig/Zelig/RunTime/Zelig/Kernel/HardwareModel/TargetPlatform/ARMv5_VFP/Convert.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // namespace Microsoft.Zelig.Runtime.TargetPlatform.ARMv5_VFP.Helpers { using System; using System.Runtime.CompilerServices; using TS = Microsoft.Zelig.Runtime.TypeSystem; internal static class Convert { const float c_float_32bit = 65536.0f * 65536.0f; const double c_double_32bit = 65536.0 * 65536.0; [TS.WellKnownMethod( "SoftVFP_Convert_LongToFloat" )] internal static float LongToFloat( long val , bool fOverflow ) { int valHi = (int)(val >> 32); uint valLo = (uint) val ; float resHi = (float)valHi * c_float_32bit; float resLo = (float)valLo; return resHi + resLo; } [TS.WellKnownMethod( "SoftVFP_Convert_UnsignedLongToFloat" )] internal static float UnsignedLongToFloat( ulong val , bool fOverflow ) { uint valHi = (uint)(val >> 32); uint valLo = (uint) val ; float resHi = (float)valHi * c_float_32bit; float resLo = (float)valLo; return resHi + resLo; } //--// [TS.WellKnownMethod( "SoftVFP_Convert_LongToDouble" )] internal static double LongToDouble( long val , bool fOverflow ) { int valHi = (int)(val >> 32); uint valLo = (uint) val ; double resHi = (double)valHi * c_double_32bit; double resLo = (double)valLo; return resHi + resLo; } [TS.WellKnownMethod( "SoftVFP_Convert_UnsignedLongToDouble" )] internal static double UnsignedLongToDouble( ulong val , bool fOverflow ) { uint valHi = (uint)(val >> 32); uint valLo = (uint) val ; double resHi = (double)valHi * c_double_32bit; double resLo = (double)valLo; return resHi + resLo; } //--// [TS.WellKnownMethod( "SoftVFP_Convert_FloatToLong" )] internal static long FloatToLong( float val , bool fOverflow ) { int resHi = (int)(val / c_float_32bit); int resLo = (int)(val - resHi * c_float_32bit); return ((long)resHi << 32) + (long)resLo; } [TS.WellKnownMethod( "SoftVFP_Convert_FloatToUnsignedLong" )] internal static ulong FloatToUnsignedLong( float val , bool fOverflow ) { uint resHi = (uint)(val / c_float_32bit); uint resLo = (uint)(val - resHi * c_float_32bit); return ((ulong)resHi << 32) + (ulong)resLo; } [TS.WellKnownMethod( "SoftVFP_Convert_DoubleToLong" )] internal static long DoubleToLong( double val , bool fOverflow ) { int resHi = (int)(val / c_double_32bit); int resLo = (int)(val - resHi * c_double_32bit); return ((long)resHi << 32) + (long)resLo; } [TS.WellKnownMethod( "SoftVFP_Convert_DoubleToUnsignedLong" )] internal static ulong DoubleToUnsignedLong( double val , bool fOverflow ) { uint resHi = (uint)(val / c_double_32bit); uint resLo = (uint)(val - resHi * c_double_32bit); return ((ulong)resHi << 32) + (ulong)resLo; } } } ================================================ FILE: Zelig/Zelig/RunTime/Zelig/Kernel/HardwareModel/TargetPlatform/ARMv5_VFP/ProcessorARMv5_VFP.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // namespace Microsoft.Zelig.Runtime.TargetPlatform.ARMv5 { using System; using Microsoft.Zelig.TargetModel.ArmProcessor; using TS = Microsoft.Zelig.Runtime.TypeSystem; using EncDef = Microsoft.Zelig.TargetModel.ArmProcessor.EncodingDefinition_ARM; using EncDef_VFP = Microsoft.Zelig.TargetModel.ArmProcessor.EncodingDefinition_VFP_ARM; public abstract partial class ProcessorARMv5_VFP : ARMv4.ProcessorARMv4 { public static class MethodWrapperHelpers_VFP { [TS.WellKnownMethod( "Microsoft_Zelig_ProcessorARMv5_VFP_MethodWrapperHelpers_PushFpRegisters" )] public static extern void PushFpRegisters( uint indexRegister , bool fWriteBackIndexRegister , bool fAddComputedRegisters , uint registerLow , uint registerHigh ); [TS.WellKnownMethod( "Microsoft_Zelig_ProcessorARMv5_VFP_MethodWrapperHelpers_PopFpRegisters" )] public static extern void PopFpRegisters( uint indexRegister , bool fWriteBackIndexRegister , bool fAddComputedRegisters , uint registerLow , uint registerHigh ); } [TS.WellKnownType( "Microsoft_Zelig_ProcessorARMv5_VFP_MethodWrapper" )] public sealed class MethodWrapper_VFP : AbstractMethodWrapper { public const uint DisableInterruptsMask = EncDef.c_psr_I | EncDef.c_psr_F; [Inline] [DisableNullChecks(ApplyRecursively=true)] public override void Prologue( string typeFullName , string methodFullName , TS.MethodRepresentation.BuildTimeAttributes attribs ) { AddActivationRecordEvent( ActivationRecordEvents.Constructing ); if((attribs & TS.MethodRepresentation.BuildTimeAttributes.StackNotAvailable) == 0) { MethodWrapperHelpers.PushRegisters( EncDef.c_register_sp, true, true, EncDef.c_register_lst_lr ); MethodWrapperHelpers_VFP.PushFpRegisters( EncDef.c_register_sp, true, true, uint.MaxValue, uint.MinValue ); MethodWrapperHelpers.PushStackFrame(); } AddActivationRecordEvent( ActivationRecordEvents.ReadyForUse ); } [Inline] [DisableNullChecks(ApplyRecursively=true)] public unsafe override void Prologue( string typeFullName , string methodFullName , TS.MethodRepresentation.BuildTimeAttributes attribs , HardwareException he ) { AddActivationRecordEvent( ActivationRecordEvents.EnteringException ); AddActivationRecordEvent( ActivationRecordEvents.Constructing ); switch(he) { case HardwareException.UndefinedInstruction: MethodWrapperHelpers.AdjustLinkAddress( 4 ); break; // Point to the undefined instruction. case HardwareException.PrefetchAbort : MethodWrapperHelpers.AdjustLinkAddress( 4 ); break; case HardwareException.DataAbort : MethodWrapperHelpers.AdjustLinkAddress( 8 ); break; case HardwareException.Interrupt : MethodWrapperHelpers.AdjustLinkAddress( 4 ); break; case HardwareException.FastInterrupt : MethodWrapperHelpers.AdjustLinkAddress( 4 ); break; case HardwareException.SoftwareInterrupt : break; // Skip the SWI instruction. } switch(he) { case HardwareException.VectorTable: case HardwareException.Bootstrap: case HardwareException.LongJump: case HardwareException.Reset: // // No prologue for these. // AddActivationRecordEvent( ActivationRecordEvents.ReadyForUse ); return; } MethodWrapperHelpers.PushRegisters( EncDef.c_register_sp, true, true, EncDef.c_register_lst_lr ); MethodWrapperHelpers_VFP.PushFpRegisters( EncDef.c_register_sp, true, true, uint.MaxValue, uint.MinValue ); if((attribs & TS.MethodRepresentation.BuildTimeAttributes.SaveFullProcessorContext) != 0) { MethodWrapperHelpers.PushStackPointer( 5 * sizeof(uint) ); } var ptr = (Context.RegistersOnStack*)GetRegister( EncDef.c_register_sp ).ToPointer(); MethodWrapperHelpers.PushStackFrame(); if((attribs & TS.MethodRepresentation.BuildTimeAttributes.SaveFullProcessorContext) != 0) { switch(he) { case HardwareException.UndefinedInstruction: PrepareStackForException( EncDef.c_psr_mode_UNDEF, ptr ); break; case HardwareException.PrefetchAbort : PrepareStackForException( EncDef.c_psr_mode_ABORT, ptr ); break; case HardwareException.DataAbort : PrepareStackForException( EncDef.c_psr_mode_ABORT, ptr ); break; case HardwareException.Interrupt : PrepareStackForException( EncDef.c_psr_mode_IRQ , ptr ); break; case HardwareException.FastInterrupt : PrepareStackForException( EncDef.c_psr_mode_FIQ , ptr ); break; case HardwareException.SoftwareInterrupt : PrepareStackForException( EncDef.c_psr_mode_SYS , ptr ); break; } } AddActivationRecordEvent( ActivationRecordEvents.ReadyForUse ); } [Inline] [DisableNullChecks(ApplyRecursively=true)] public override void Epilogue( string typeFullName , string methodFullName , TS.MethodRepresentation.BuildTimeAttributes attribs ) { AddActivationRecordEvent( ActivationRecordEvents.ReadyForTearDown ); if((attribs & TS.MethodRepresentation.BuildTimeAttributes.NoReturn) == 0) { MethodWrapperHelpers.PopStackFrame(); AddActivationRecordEvent( ActivationRecordEvents.ReturnToCaller ); MethodWrapperHelpers_VFP.PopFpRegisters( EncDef.c_register_sp, true, true, uint.MaxValue, uint.MinValue ); MethodWrapperHelpers.PopRegisters( EncDef.c_register_sp, true, true, false, EncDef.c_register_lst_pc ); AddActivationRecordEvent( ActivationRecordEvents.NonReachable ); } else { // // The method is not supposed to return, but we have to put something here, // because the stack crawling code will look for this spot during stack unwinding... // Breakpoint( 0x1 ); AddActivationRecordEvent( ActivationRecordEvents.NonReachable ); } } [Inline] [DisableNullChecks(ApplyRecursively=true)] public unsafe override void Epilogue( string typeFullName , string methodFullName , TS.MethodRepresentation.BuildTimeAttributes attribs , HardwareException he ) { AddActivationRecordEvent( ActivationRecordEvents.ReadyForTearDown ); switch(he) { case HardwareException.VectorTable: case HardwareException.Bootstrap: case HardwareException.Reset: return; case HardwareException.LongJump: { var ptr = (Context.RegistersOnStack*)GetRegister( EncDef.c_register_r1 ).ToPointer(); SetSystemRegister( EncDef_VFP.c_register_FPSCR, ptr->FPSCR ); SetRegister ( EncDef .c_register_sp , ptr->SP ); SetRegister ( EncDef .c_register_lr , ptr->LR ); SetRegister ( EncDef .c_register_r1 , new UIntPtr( &ptr->S0 ) ); AddActivationRecordEvent( ActivationRecordEvents.LongJump ); MethodWrapperHelpers_VFP.PopFpRegisters( EncDef.c_register_r1, true , true , uint.MaxValue, uint.MinValue ); MethodWrapperHelpers .PopRegisters ( EncDef.c_register_r1, false, true, false, EncDef.c_register_lst_pc ); AddActivationRecordEvent( ActivationRecordEvents.NonReachable ); } return; default: { MethodWrapperHelpers.PopStackFrame(); if((attribs & TS.MethodRepresentation.BuildTimeAttributes.SaveFullProcessorContext) != 0) { var ptr = (Context.RegistersOnStack*)GetRegister( EncDef.c_register_sp ).ToPointer(); switch(he) { case HardwareException.UndefinedInstruction: RestoreStackForException( EncDef.c_psr_mode_UNDEF, ptr ); break; case HardwareException.PrefetchAbort : RestoreStackForException( EncDef.c_psr_mode_ABORT, ptr ); break; case HardwareException.DataAbort : RestoreStackForException( EncDef.c_psr_mode_ABORT, ptr ); break; case HardwareException.Interrupt : RestoreStackForException( EncDef.c_psr_mode_IRQ , ptr ); break; case HardwareException.FastInterrupt : RestoreStackForException( EncDef.c_psr_mode_FIQ , ptr ); break; case HardwareException.SoftwareInterrupt : RestoreStackForException( EncDef.c_psr_mode_SYS , ptr ); break; } MethodWrapperHelpers.PopStackPointer( 5 * sizeof(uint) ); } AddActivationRecordEvent( ActivationRecordEvents.ReturnFromException ); MethodWrapperHelpers_VFP.PopFpRegisters( EncDef.c_register_sp, true, true, uint.MaxValue, uint.MinValue ); MethodWrapperHelpers.PopRegisters( EncDef.c_register_sp, true, true, true, EncDef.c_register_lst_pc ); AddActivationRecordEvent( ActivationRecordEvents.NonReachable ); } return; } } [Inline] private static unsafe void PrepareStackForException( uint mode , Context.RegistersOnStack* ptr ) { // // Keep interrupts disabled. // mode |= DisableInterruptsMask; // // Get CSPR of the calling context. // var CPSR = GetSavedStatusRegister(); // // Save it. // ptr->CPSR = CPSR; // // Disable interrupts. // CPSR |= DisableInterruptsMask; // // Go back to the previous mode. // SetStatusRegister( EncDef.c_psr_field_c, CPSR ); // // Save unbanked R13 and R14 plus FP status. // ptr->FPSCR = GetSystemRegister( EncDef_VFP.c_register_FPSCR ); ptr->FPEXC = GetSystemRegister( EncDef_VFP.c_register_FPEXC ); ptr->LR = GetRegister ( EncDef .c_register_lr ); ptr->SP = GetRegister ( EncDef .c_register_sp ); // // Switch back to the exception handling mode. // SetStatusRegister( EncDef.c_psr_field_c, mode ); // // R1 should point to the Register Context on the stack. // SetRegister( EncDef.c_register_r1, new UIntPtr( ptr ) ); } [Inline] private static unsafe void RestoreStackForException( uint mode , Context.RegistersOnStack* ptr ) { // // Keep interrupts disabled. // mode |= DisableInterruptsMask; // // Get CSPR of the calling context. // var CPSR = ptr->CPSR; // // Restore the SPSR // SetSavedStatusRegister( EncDef.c_psr_field_ALL, CPSR ); // // Disable interrupts. // CPSR |= DisableInterruptsMask; // // Go back to the previous mode. // SetStatusRegister( EncDef.c_psr_field_c, CPSR ); // // Save unbanked R13 and R14 plus FP status. // SetSystemRegister( EncDef_VFP.c_register_FPSCR, ptr->FPSCR ); SetSystemRegister( EncDef_VFP.c_register_FPEXC, ptr->FPEXC ); SetRegister ( EncDef .c_register_lr , ptr->LR ); SetRegister ( EncDef .c_register_sp , ptr->SP ); // // Switch back to the exception handling mode. // SetStatusRegister( EncDef.c_psr_field_c, mode ); } } // // Helper Methods // [TS.WellKnownMethod( "ProcessorARM_SetRegisterFP32" )] public static extern void SetRegisterFP32( uint reg , float value ); [TS.WellKnownMethod( "ProcessorARM_SetRegisterFP64" )] public static extern void SetRegisterFP64( uint reg , double value ); [TS.WellKnownMethod( "ProcessorARM_GetRegisterFP32" )] public static extern float GetRegisterFP32( uint reg ); [TS.WellKnownMethod( "ProcessorARM_GetRegisterFP64" )] public static extern double GetRegisterFP64( uint reg ); //--// public override unsafe void FlushCacheLine( UIntPtr target ) { ARMv4.Coprocessor15.CleanDCache ( target ); ARMv4.Coprocessor15.DrainWriteBuffer( ); ARMv4.Coprocessor15.InvalidateICache( target ); } //--// [NoInline] public static void EnableRunFastMode() { SetSystemRegister( EncDef_VFP.c_register_FPEXC, EncDef_VFP.c_fpexc_EN ); uint fpscr = GetSystemRegister( EncDef_VFP.c_register_FPSCR ); fpscr &= ~(EncDef_VFP.c_fpscr_IOE | EncDef_VFP.c_fpscr_DZE | EncDef_VFP.c_fpscr_OFE | EncDef_VFP.c_fpscr_UFE | EncDef_VFP.c_fpscr_IXE | EncDef_VFP.c_fpscr_IDE ); fpscr |= EncDef_VFP.c_fpscr_DN | EncDef_VFP.c_fpscr_FZ; SetSystemRegister( EncDef_VFP.c_register_FPSCR, fpscr ); } //--// protected static void InitializeCache() { ARMv4.Coprocessor15.InvalidateICache(); ARMv4.Coprocessor15.InvalidateDCache(); // // Enable ICache // ARMv4.Coprocessor15.SetControlRegisterBits( ARMv4.Coprocessor15.c_ControlRegister__ICache ); } } } ================================================ FILE: Zelig/Zelig/RunTime/Zelig/Kernel/HardwareModel/TargetPlatform/ARMv5_VFP/ProcessorARMv5_VFP_ContextSwitch.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // namespace Microsoft.Zelig.Runtime.TargetPlatform.ARMv5 { using System; using System.Runtime.InteropServices; using Microsoft.Zelig.TargetModel.ArmProcessor; using TS = Microsoft.Zelig.Runtime.TypeSystem; using EncDef = Microsoft.Zelig.TargetModel.ArmProcessor.EncodingDefinition_ARM; using EncDef_VFP = Microsoft.Zelig.TargetModel.ArmProcessor.EncodingDefinition_VFP_ARM; public abstract partial class ProcessorARMv5_VFP { public abstract new class Context : Processor.Context { // // WARNING: Don't assume the actual layout of the structure is sequential!!! // WARNING: The code generator rearranges the fields to minimize the cost of a context switch!!! // [TS.WellKnownType( "Microsoft_Zelig_ProcessorARMv5_VFP_RegistersOnStack" )] [StructLayout( LayoutKind.Sequential, Pack = 4 )] public struct RegistersOnStack { public const uint StackRegister = EncDef.c_register_sp; public const uint LinkRegister = EncDef.c_register_lr; public const uint ProgramCounterRegister = EncDef.c_register_pc; // // State // [TS.AssumeReferenced] public uint FPSCR; [TS.AssumeReferenced] public uint FPEXC; [TS.AssumeReferenced] public uint CPSR; [TS.AssumeReferenced] public UIntPtr SP; [TS.AssumeReferenced] public UIntPtr LR; [TS.AssumeReferenced] public float S0; [TS.AssumeReferenced] public float S1; [TS.AssumeReferenced] public float S2; [TS.AssumeReferenced] public float S3; [TS.AssumeReferenced] public float S4; [TS.AssumeReferenced] public float S5; [TS.AssumeReferenced] public float S6; [TS.AssumeReferenced] public float S7; [TS.AssumeReferenced] public float S8; [TS.AssumeReferenced] public float S9; [TS.AssumeReferenced] public float S10; [TS.AssumeReferenced] public float S11; [TS.AssumeReferenced] public float S12; [TS.AssumeReferenced] public float S13; [TS.AssumeReferenced] public float S14; [TS.AssumeReferenced] public float S15; [TS.AssumeReferenced] public float S16; [TS.AssumeReferenced] public float S17; [TS.AssumeReferenced] public float S18; [TS.AssumeReferenced] public float S19; [TS.AssumeReferenced] public float S20; [TS.AssumeReferenced] public float S21; [TS.AssumeReferenced] public float S22; [TS.AssumeReferenced] public float S23; [TS.AssumeReferenced] public float S24; [TS.AssumeReferenced] public float S25; [TS.AssumeReferenced] public float S26; [TS.AssumeReferenced] public float S27; [TS.AssumeReferenced] public float S28; [TS.AssumeReferenced] public float S29; [TS.AssumeReferenced] public float S30; [TS.AssumeReferenced] public float S31; [TS.AssumeReferenced] public UIntPtr R0; [TS.AssumeReferenced] public UIntPtr R1; [TS.AssumeReferenced] public UIntPtr R2; [TS.AssumeReferenced] public UIntPtr R3; [TS.AssumeReferenced] public UIntPtr R4; [TS.AssumeReferenced] public UIntPtr R5; [TS.AssumeReferenced] public UIntPtr R6; [TS.AssumeReferenced] public UIntPtr R7; [TS.AssumeReferenced] public UIntPtr R8; [TS.AssumeReferenced] public UIntPtr R9; [TS.AssumeReferenced] public UIntPtr R10; [TS.AssumeReferenced] public UIntPtr R11; [TS.AssumeReferenced] public UIntPtr R12; [TS.AssumeReferenced] public UIntPtr PC; // // Helper Methods // internal unsafe UIntPtr* GetRegisterPointer( uint idx ) { switch(idx) { case 0: fixed(UIntPtr* ptr = &this.R0 ) { return ptr; }; case 1: fixed(UIntPtr* ptr = &this.R1 ) { return ptr; }; case 2: fixed(UIntPtr* ptr = &this.R2 ) { return ptr; }; case 3: fixed(UIntPtr* ptr = &this.R3 ) { return ptr; }; case 4: fixed(UIntPtr* ptr = &this.R4 ) { return ptr; }; case 5: fixed(UIntPtr* ptr = &this.R5 ) { return ptr; }; case 6: fixed(UIntPtr* ptr = &this.R6 ) { return ptr; }; case 7: fixed(UIntPtr* ptr = &this.R7 ) { return ptr; }; case 8: fixed(UIntPtr* ptr = &this.R8 ) { return ptr; }; case 9: fixed(UIntPtr* ptr = &this.R9 ) { return ptr; }; case 10: fixed(UIntPtr* ptr = &this.R10) { return ptr; }; case 11: fixed(UIntPtr* ptr = &this.R11) { return ptr; }; case 12: fixed(UIntPtr* ptr = &this.R12) { return ptr; }; case 13: fixed(UIntPtr* ptr = &this.SP ) { return ptr; }; case 14: fixed(UIntPtr* ptr = &this.LR ) { return ptr; }; case 15: fixed(UIntPtr* ptr = &this.PC ) { return ptr; }; } return null; } internal unsafe float* GetFPRegisterPointer( uint idx ) { switch(idx) { case 0: fixed(float* ptr = &this.S0 ) { return ptr; }; case 1: fixed(float* ptr = &this.S1 ) { return ptr; }; case 2: fixed(float* ptr = &this.S2 ) { return ptr; }; case 3: fixed(float* ptr = &this.S3 ) { return ptr; }; case 4: fixed(float* ptr = &this.S4 ) { return ptr; }; case 5: fixed(float* ptr = &this.S5 ) { return ptr; }; case 6: fixed(float* ptr = &this.S6 ) { return ptr; }; case 7: fixed(float* ptr = &this.S7 ) { return ptr; }; case 8: fixed(float* ptr = &this.S8 ) { return ptr; }; case 9: fixed(float* ptr = &this.S9 ) { return ptr; }; case 10: fixed(float* ptr = &this.S10) { return ptr; }; case 11: fixed(float* ptr = &this.S11) { return ptr; }; case 12: fixed(float* ptr = &this.S12) { return ptr; }; case 13: fixed(float* ptr = &this.S13) { return ptr; }; case 14: fixed(float* ptr = &this.S14) { return ptr; }; case 15: fixed(float* ptr = &this.S15) { return ptr; }; case 16: fixed(float* ptr = &this.S16) { return ptr; }; case 17: fixed(float* ptr = &this.S17) { return ptr; }; case 18: fixed(float* ptr = &this.S18) { return ptr; }; case 19: fixed(float* ptr = &this.S19) { return ptr; }; case 20: fixed(float* ptr = &this.S20) { return ptr; }; case 21: fixed(float* ptr = &this.S21) { return ptr; }; case 22: fixed(float* ptr = &this.S22) { return ptr; }; case 23: fixed(float* ptr = &this.S23) { return ptr; }; case 24: fixed(float* ptr = &this.S24) { return ptr; }; case 25: fixed(float* ptr = &this.S25) { return ptr; }; case 26: fixed(float* ptr = &this.S26) { return ptr; }; case 27: fixed(float* ptr = &this.S27) { return ptr; }; case 28: fixed(float* ptr = &this.S28) { return ptr; }; case 29: fixed(float* ptr = &this.S29) { return ptr; }; case 30: fixed(float* ptr = &this.S30) { return ptr; }; case 31: fixed(float* ptr = &this.S31) { return ptr; }; } return null; } public void Assign( ref RegistersOnStack other ) { this.R0 = other.R0; this.R1 = other.R1; this.R2 = other.R2; this.R3 = other.R3; this.R4 = other.R4; this.R5 = other.R5; this.R6 = other.R6; this.R7 = other.R7; this.R8 = other.R8; this.R9 = other.R9; this.R10 = other.R10; this.R11 = other.R11; this.R12 = other.R12; this.SP = other.SP; this.LR = other.LR; this.PC = other.PC; this.CPSR = other.CPSR; this.S0 = other.S0; this.S1 = other.S1; this.S2 = other.S2; this.S3 = other.S3; this.S4 = other.S4; this.S5 = other.S5; this.S6 = other.S6; this.S7 = other.S7; this.S8 = other.S8; this.S9 = other.S9; this.S10 = other.S10; this.S11 = other.S11; this.S12 = other.S12; this.S13 = other.S13; this.S14 = other.S14; this.S15 = other.S15; this.S16 = other.S16; this.S17 = other.S17; this.S18 = other.S18; this.S19 = other.S19; this.S20 = other.S20; this.S21 = other.S21; this.S22 = other.S22; this.S23 = other.S23; this.S24 = other.S24; this.S25 = other.S25; this.S26 = other.S26; this.S27 = other.S27; this.S28 = other.S28; this.S29 = other.S29; this.S30 = other.S30; this.S31 = other.S31; this.FPSCR = other.FPSCR; } } // // State // const uint c_STMFD_Mask = 0xFFFF0000; const uint c_STMFD_Opcode = 0xE92D0000; const uint c_FSTMFDD_Mask = 0xFFFF0F00; const uint c_FSTMFDD_Opcode = 0xED2D0B00; const uint c_SUBSP_Mask = 0xFFFFF000; const uint c_SUBSP_Opcode = 0xE24DD000; //--// const uint c_FLDMFDD_Mask = 0xFFFF0F00; const uint c_FLDMFDD_Opcode = 0xECBD0B00; const uint c_LDMFD_Mask = 0xFFFF0000; const uint c_LDMFD_Opcode = 0xE8BD0000; //--// public RegistersOnStack Registers; // // Constructor Methods // public Context(ThreadImpl owner) : base(owner) { } // // Helper Methods // [NoInline] public override void Populate() { GetAllTheRegisters(); // // Now we have all the registers at this method boundary, unwind one more time and we have the state at the caller's site. // Unwind(); } [NoInline] public override void Populate( Processor.Context context ) { Context ctx = (Context)context; this.Registers.Assign( ref ctx.Registers ); } [NoInline] public unsafe override void PopulateFromDelegate( Delegate dlg, uint[] stack ) { DelegateImpl dlgImpl = (DelegateImpl)(object)dlg; ArrayImpl stackImpl = (ArrayImpl )(object)stack; ObjectImpl objImpl = (ObjectImpl )(object)dlg.Target; this.Registers.CPSR = c_psr_mode_SYS; this.Registers.PC = new UIntPtr( dlgImpl.InnerGetCodePointer().Target.ToPointer() ); this.Registers.SP = new UIntPtr( stackImpl.GetEndDataPointer() ); this.Registers.FPSCR = EncDef_VFP.c_fpscr_DN | EncDef_VFP.c_fpscr_FZ; this.Registers.R0 = objImpl.ToPointer(); } [NoInline] public override void SetupForExceptionHandling( uint mode ) { using(Runtime.SmartHandles.InterruptState.DisableAll()) { UIntPtr stack = this.Registers.SP; uint oldMode = GetStatusRegister(); // // Enter target mode, with interrupts disabled. // SetStatusRegister( c_psr_field_c, c_psr_I | c_psr_F | mode ); SetRegister( Context.RegistersOnStack.StackRegister, stack ); // // Switch back to original mode. // SetStatusRegister( c_psr_field_c, oldMode ); } } [NoInline] public unsafe override bool Unwind() { UIntPtr pc = this.ProgramCounter; TS.CodeMap cm = TS.CodeMap.ResolveAddressToCodeMap( pc ); this.InPrologue = false; this.InEpilogue = false; if(cm != null) { for(int i = 0; i < cm.Ranges.Length; i++) { TS.CodeMap.Range rng = cm.Ranges[i]; if((rng.Flags & TS.CodeMap.Flags.EntryPoint) != 0) { if((rng.Flags & TS.CodeMap.Flags.BottomOfCallStack) != 0) { return false; } UIntPtr sp = this.StackPointer; UIntPtr address = rng.Start; uint regRestoreMap = 0; uint regFpRestore = 0; uint regFpRestoreCount = 0; uint stackAdjustment = 0; bool fReturnAddressinLR = false; bool fDone = false; if(pc == address) { // // We are at the beginning of a method, the return address is in LR for sure. // fReturnAddressinLR = true; // // The PC has not executed the next prologue instruction, stop processing. // fDone = true; this.InPrologue = true; } if(fDone == false) { if((rng.Flags & TS.CodeMap.Flags.HasIntRegisterSave) != 0) { uint* ptr = (uint*)address.ToPointer(); uint opcode_STMFD = DebuggerAwareRead( ptr++ ); address = new UIntPtr( ptr ); if((opcode_STMFD & c_STMFD_Mask) == c_STMFD_Opcode) { regRestoreMap = opcode_STMFD & 0xFFFF; } else { //CHECKS.ASSERT( false, "Expecting a STMFD opcode, got 0x{0:X8}", opcode_STMFD ); return false; } } else { // // No register push, the return address is in LR for sure. // fReturnAddressinLR = true; } } if(pc == address) { // // The PC has not executed the next prologue instruction, stop processing. // fDone = true; this.InPrologue = true; } if(fDone == false) { if((rng.Flags & TS.CodeMap.Flags.HasFpRegisterSave) != 0) { uint* ptr = (uint*)address.ToPointer(); uint opcode_FSTMFDD = DebuggerAwareRead( ptr++ ); address = new UIntPtr( ptr ); if((opcode_FSTMFDD & c_FSTMFDD_Mask) == c_FSTMFDD_Opcode) { regFpRestore = ((opcode_FSTMFDD & 0x0000F000) >> 12) * 2; regFpRestoreCount = (opcode_FSTMFDD & 0x000000FF); } else { //CHECKS.ASSERT( false, "Expecting a FSTMFDD opcode, got 0x{0:X8}", opcode_FSTMFDD ); return false; } } } if(pc == address) { // // The PC has not executed the next prologue instruction, stop processing. // fDone = true; this.InPrologue = true; } if(fDone == false) { if((rng.Flags & TS.CodeMap.Flags.HasStackAdjustment) != 0) { uint* ptr = (uint*)address.ToPointer(); uint opcode_SUBSP = DebuggerAwareRead( ptr ); if((opcode_SUBSP & c_SUBSP_Mask) == c_SUBSP_Opcode) { stackAdjustment = s_Encoding.get_DataProcessing_ImmediateValue( opcode_SUBSP ); } else { //CHECKS.ASSERT( false, "Expecting a STMFD opcode, got 0x{0:X8}", opcode_SUBSP ); return false; } } } // // Deal with method epilogue: if we are on one of the return instructions, we need to restore less state. // uint opcode = *(uint*)pc.ToPointer(); if((opcode & c_FLDMFDD_Mask) == c_FLDMFDD_Opcode) { stackAdjustment = 0; } if((opcode & c_LDMFD_Mask) == c_LDMFD_Opcode) { stackAdjustment = 0; regFpRestoreCount = 0; } //--// sp = AddressMath.Increment( sp, stackAdjustment ); if(fReturnAddressinLR) { this.Registers.PC = this.Registers.LR; } else { UIntPtr* src = (UIntPtr*)sp.ToPointer(); while(regFpRestoreCount > 0) { UIntPtr* dst = (UIntPtr*)this.Registers.GetFPRegisterPointer( regFpRestore ); *dst = *src++; regFpRestore++; regFpRestoreCount--; } for(uint idx = 0; idx < 16; idx++) { if((regRestoreMap & (1u << (int)idx)) != 0) { // // Prologue saves LR, but we need to restore it as PC. // uint regIdx = (idx == RegistersOnStack.LinkRegister) ? RegistersOnStack.ProgramCounterRegister : idx; UIntPtr* dst = this.Registers.GetRegisterPointer( regIdx ); *dst = *src++; } } sp = new UIntPtr( src ); } this.StackPointer = sp; return true; } } } return false; } [NoInline] public override void SwitchTo() { LongJump( ref this.Registers ); } public override unsafe UIntPtr GetRegisterByIndex( uint idx ) { return *(this.Registers.GetRegisterPointer( idx )); } public override unsafe void SetRegisterByIndex( uint idx , UIntPtr value ) { *(this.Registers.GetRegisterPointer( idx )) = value; } //--// [NoInline] [SaveFullProcessorContext] private unsafe void GetAllTheRegisters() { this.Registers.SP = GetRegister( RegistersOnStack.StackRegister ); this.Registers.PC = GetRegister( RegistersOnStack.ProgramCounterRegister ); Unwind(); } //--// [NoInline] [NoReturn()] [HardwareExceptionHandler(HardwareException.LongJump)] static void LongJump( ref RegistersOnStack registers ) { // // WARNING! // WARNING! Keep this method empty!!!! // WARNING! // // We need a way to make a long jump as part of the exception handling code. // // The code responsible for emitting the prologue of the method will detect that // this method is decorated with the ContextSwitch flag and it will generate the proper code. // // WARNING! // WARNING! Keep this method empty!!!! // WARNING! // } //--// static uint fault_DFSR; static uint fault_IFSR; static uint fault_FAR; [NoInline] [NoReturn()] [HardwareExceptionHandler(HardwareException.UndefinedInstruction)] [MemoryUsage(MemoryUsage.Bootstrap)] static void UndefinedInstruction() { fault_DFSR = MoveFromCoprocessor( 15, 0, 5, 0, 0 ); fault_IFSR = MoveFromCoprocessor( 15, 0, 5, 0, 1 ); fault_FAR = MoveFromCoprocessor( 15, 0, 6, 0, 0 ); Processor.Instance.Breakpoint(); } [NoInline] [NoReturn()] [HardwareExceptionHandler(HardwareException.PrefetchAbort)] [MemoryUsage(MemoryUsage.Bootstrap)] static void PrefetchAbort() { fault_DFSR = MoveFromCoprocessor( 15, 0, 5, 0, 0 ); fault_IFSR = MoveFromCoprocessor( 15, 0, 5, 0, 1 ); fault_FAR = MoveFromCoprocessor( 15, 0, 6, 0, 0 ); Processor.Instance.Breakpoint(); } [NoInline] [NoReturn()] [HardwareExceptionHandler(HardwareException.DataAbort)] [MemoryUsage(MemoryUsage.Bootstrap)] static void DataAbort() { fault_DFSR = MoveFromCoprocessor( 15, 0, 5, 0, 0 ); fault_IFSR = MoveFromCoprocessor( 15, 0, 5, 0, 1 ); fault_FAR = MoveFromCoprocessor( 15, 0, 6, 0, 0 ); Processor.Instance.Breakpoint(); } //--// [Inline] public static void InterruptHandlerWithContextSwitch( ref RegistersOnStack registers ) { Peripherals.Instance.ProcessInterrupt(); ThreadManager tm = ThreadManager.Instance; // // We keep looping until the current and next threads are the same, // because when swapping out a dead thread, we might wake up a different thread. // while(tm.ShouldContextSwitch) { ContextSwitch( tm, ref registers ); } } [Inline] public static void InterruptHandlerWithoutContextSwitch() { Peripherals.Instance.ProcessInterrupt(); } [Inline] public static void FastInterruptHandlerWithoutContextSwitch() { Peripherals.Instance.ProcessFastInterrupt(); } [Inline] public static void GenericSoftwareInterruptHandler( ref RegistersOnStack registers ) { } //--// private static void ContextSwitch( ThreadManager tm , ref RegistersOnStack registers ) { ThreadImpl currentThread = tm.CurrentThread; ThreadImpl nextThread = tm.NextThread; Context ctx; if(currentThread != null) { ctx = (Context)currentThread.SwappedOutContext; ctx.Registers.Assign( ref registers ); } ctx = (Context)nextThread.SwappedOutContext; registers.Assign( ref ctx.Registers ); tm.CurrentThread = nextThread; ThreadImpl.CurrentThread = nextThread; } // // Access Methods // public override UIntPtr StackPointer { get { return this.Registers.SP; } set { this.Registers.SP = value; } } public override UIntPtr BaseStackPointer { get { return (UIntPtr)0; } } public override uint ExcReturn { get { return 0; } set { } } public override UIntPtr ProgramCounter { get { return this.Registers.PC; } set { this.Registers.PC = value; } } public override uint ScratchedIntegerRegisters { get { return MethodWrapperHelpers.ScratchedRegisters(); } } } } } ================================================ FILE: Zelig/Zelig/RunTime/Zelig/Kernel/HardwareModel/TargetPlatform/ARMv6/InterruptsSafeHandleARMv6M.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // namespace Microsoft.Zelig.Runtime.TargetPlatform.ARMv6.SmartHandles { using System; using ISA = TargetModel.ArmProcessor.InstructionSetVersion; [ExtendClass( typeof(Runtime.SmartHandles.InterruptState), PlatformVersionFilter=ISA.Platform_Version__ARMv6M )] public struct InterruptStateARMv6M : IDisposable { // // State // private static ProcessorARMv6M.ISR_NUMBER s_softwareExceptionMode = ProcessorARMv6M.ISR_NUMBER.SVCall; //--// private uint m_basepri; // // Constructor Methods // [DiscardTargetImplementation()] [Inline] public InterruptStateARMv6M( uint basepri ) { m_basepri = basepri; } // // Helper Methods // [Inline] public void Dispose() { ProcessorARMv6M.SetPriMaskRegister( m_basepri ); } [Inline] public void Toggle() { uint basepri = ProcessorARMv6M.SetPriMaskRegister( m_basepri ); ProcessorARMv6MForLlvm.Nop(); ProcessorARMv6M.SetPriMaskRegister( basepri ); } //--// [Inline] public static InterruptStateARMv6M Disable() { return new InterruptStateARMv6M( ProcessorARMv6M.DisableInterrupts( ) ); } [Inline] public static InterruptStateARMv6M DisableAll( ) { return new InterruptStateARMv6M( ProcessorARMv6M.DisableInterrupts( ) ); } [Inline] public static InterruptStateARMv6M Enable() { return new InterruptStateARMv6M( ProcessorARMv6M.EnableInterrupts( ) ); } [Inline] public static InterruptStateARMv6M EnableAll( ) { return new InterruptStateARMv6M( ProcessorARMv6M.EnableInterrupts( ) ); } // // Access Methods // [Inline] public uint GetPreviousState() { return m_basepri; } public HardwareException GetCurrentExceptionMode() { ProcessorARMv6M.ISR_NUMBER ex = GetMode(); if(ex == ProcessorARMv6M.ISR_NUMBER.ThreadMode) { return HardwareException.None; } switch(ex) { case ProcessorARMv6M.ISR_NUMBER.NMI : return HardwareException.NMI; case ProcessorARMv6M.ISR_NUMBER.HardFault : return HardwareException.Fault; case ProcessorARMv6M.ISR_NUMBER.SVCall : return HardwareException.Service; case ProcessorARMv6M.ISR_NUMBER.ReservedForDebug: return HardwareException.Debug; case ProcessorARMv6M.ISR_NUMBER.PendSV : return HardwareException.PendSV; case ProcessorARMv6M.ISR_NUMBER.SysTick : return HardwareException.SysTick; case ProcessorARMv6M.ISR_NUMBER.Reset : case ProcessorARMv6M.ISR_NUMBER.Reserved4 : case ProcessorARMv6M.ISR_NUMBER.Reserved5 : case ProcessorARMv6M.ISR_NUMBER.Reserved6 : case ProcessorARMv6M.ISR_NUMBER.Reserved7 : case ProcessorARMv6M.ISR_NUMBER.Reserved8 : case ProcessorARMv6M.ISR_NUMBER.Reserved9 : case ProcessorARMv6M.ISR_NUMBER.Reserved10 : case ProcessorARMv6M.ISR_NUMBER.Reserved13 : BugCheck.Assert( false, BugCheck.StopCode.IllegalMode ); break; default : return HardwareException.Interrupt; } return HardwareException.Interrupt; } //--// private ProcessorARMv6M.ISR_NUMBER GetMode( ) { return s_softwareExceptionMode | (ProcessorARMv6M.ISR_NUMBER)(ProcessorARMv6M.CMSIS_STUB_SCB__get_IPSR( ) & 0x1FF); } [Inline] internal static void SetSoftwareExceptionMode( ) { s_softwareExceptionMode = ProcessorARMv6M.ISR_NUMBER.SVCall; } [Inline] internal static void ResetSoftwareExceptionMode( ) { s_softwareExceptionMode = ProcessorARMv6M.ISR_NUMBER.ThreadMode; } } } ================================================ FILE: Zelig/Zelig/RunTime/Zelig/Kernel/HardwareModel/TargetPlatform/ARMv6/ProcessorARMv6M.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // #define SPIN_ON_SLEEP namespace Microsoft.Zelig.Runtime.TargetPlatform.ARMv6 { using System; using System.Runtime.InteropServices; using TS = Microsoft.Zelig.Runtime.TypeSystem; using RT = Microsoft.Zelig.Runtime; public abstract partial class ProcessorARMv6M : Runtime.Processor { public enum IRQn_Type : int { // Cortex-M Processor IRQ number, from cmsis implementation Reset_IRQn = -42, /*!< Exception#: 1 Reset (not actually defined as an IRQn_Type) */ NonMaskableInt_IRQn = -14, /*!< Exception#: 2 Non Maskable Interrupt */ HardFault_IRQn = -13, /*!< Exception#: 3 Non Maskable Interrupt */ Reserved_IRQn12 = -12, /*!< Exception#: 4 Reserved */ Reserved_IRQn11 = -11, /*!< Exception#: 5 Reserved */ Reserved_IRQn10 = -10, /*!< Exception#: 6 Reserved */ Reserved_IRQn9 = -9, /*!< Exception#: 7 Reserved */ Reserved_IRQn8 = -8, /*!< Exception#: 8 Reserved */ Reserved_IRQn7 = -7, /*!< Exception#: 9 Reserved */ Reserved_IRQn6 = -6, /*!< Exception#: 10 Reserved */ SVCall_IRQn = -5, /*!< Exception#: 11 Cortex-M0[plus] SV Call Interrupt */ Reserved_IRQn4 = -4, /*!< Exception#: 12 Cortex-M0[plus] Debug Monitor Interrupt */ Reserved_IRQn3 = -3, /*!< Exception#: 13 Reserved */ PendSV_IRQn = -2, /*!< Exception#: 14 Cortex-M0[plus] Pend SV Interrupt */ SysTick_IRQn_Optional = -1, /*!< Exception#: 15 Cortex-M0[plus] System Tick Interrupt (OPTIONAL!) */ //--// AnyInterrupt16 = 0, //--// Invalid = 0xFFFF, } public enum ISR_NUMBER : uint { // Cortex-M Processor exception Numbers, as reported by the IPSR ThreadMode = 0, Reset = 1, NMI = 2, HardFault = 3, Reserved4 = 4, Reserved5 = 5, Reserved6 = 6, Reserved7 = 7, Reserved8 = 8, Reserved9 = 9, Reserved10 = 10, SVCall = 11, ReservedForDebug = 12, Reserved13 = 13, PendSV = 14, SysTick = 15, //--// Peripheral = 16, Last = 240, } public enum SVC_Code : byte { SupervisorCall__LongJump = 0x11, SupervisorCall__StartThreads = 0x12, SupervisorCall__RetireThread = 0x13, SupervisorCall__SnapshotProcessModeRegisters = 0x14, } // // Exception priorities // public const uint c_Priority__MASK = 0x000000FFu; public const uint c_Priority__NeverDisabled = 0x00000000u; public const uint c_Priority__Highest = 0x00000001u; public const uint c_Priority__Lowest = 0x000000FFu; public const uint c_Priority__HigherThanAnyWeOwn = 0x00000004u; public const uint c_Priority__SVCCall = 0x00000005u; public const uint c_Priority__Default = 0x00000007u; public const uint c_Priority__SystemTimer = c_Priority__Default; public const uint c_Priority__SysTick = c_Priority__Default; public const uint c_Priority__GenericPeripherals = c_Priority__Default + 1; public const uint c_Priority__PendSV = 0x0000000Eu; //--// #region Registers and Fields Definitions // // Interrupts management // In the simplest case, we will use the PRIMASK against a BASEPRI of 0x00000000, which is the reset value // public const uint c_PRIMASK__InterruptsOff = 0x00000001; public const uint c_PRIMASK__InterruptsOn = 0x00000000; public const uint c_FAULTMASK__FaultsOff = 0x00000001; public const uint c_FAULTMASK__FaultsOn = 0x00000000; public const uint c_FAULTMASK__AreFaultsOff = c_FAULTMASK__FaultsOff << 1; // // PSR register // public const uint c_psr_InitialValue = 0x01000000; // just Thumb state set // // CONTROL register // public const uint c_CONTROL__MASK = 0x00000003; public const uint c_CONTROL__MASK_PRIVILEGE = 0x00000001; // // stack pointer // public const int c_CONTROL__SPSEL_SHIFT = 1; public const uint c_CONTROL__SPSEL_MASK = 0x1u << c_CONTROL__SPSEL_SHIFT; public const uint c_CONTROL__SPSEL_MSP = 0x0u << c_CONTROL__SPSEL_SHIFT; public const uint c_CONTROL__SPSEL_PSP = 0x1u << c_CONTROL__SPSEL_SHIFT; // // privilege // public const int c_CONTROL__nPRIV_SHIFT = 0; public const uint c_CONTROL__nPRIV_MASK = 0x1u << c_CONTROL__nPRIV_SHIFT; public const uint c_CONTROL__nPRIV_PRIV = 0x0u << c_CONTROL__nPRIV_SHIFT; public const uint c_CONTROL__nPRIV_UNPRIV = 0x1u << c_CONTROL__nPRIV_SHIFT; // // Modes // public const uint c_CONTROL__MODE__HNDLR = c_CONTROL__SPSEL_MSP | c_CONTROL__nPRIV_PRIV; public const uint c_CONTROL__MODE__THRD_PRIV = c_CONTROL__SPSEL_PSP | c_CONTROL__nPRIV_PRIV; public const uint c_CONTROL__MODE__THRD_UNPRIV = c_CONTROL__SPSEL_PSP | c_CONTROL__nPRIV_UNPRIV; // // EXC_RETURN // public const uint c_MODE_RETURN__HANDLER_MSP = 0xFFFFFFF1; // handler will return in handler mode using the MSP public const uint c_MODE_RETURN__THREAD_MSP = 0xFFFFFFF9; // handler will return in thread mode using the MSP public const uint c_MODE_RETURN__THREAD_PSP = 0xFFFFFFFD; // handler will return in thread mode using the PSP // // SCR // public const uint c_SCR__MASK = 0x0000001F; public const int c_SCR__SLEEPONEXIT__SHIFT = 1; public const uint c_SCR__SLEEPONEXIT__MASK = 1u << c_SCR__SLEEPONEXIT__SHIFT; public const uint c_SCR__SLEEPONEXIT__NO_SLEEP = 0u << c_SCR__SLEEPONEXIT__SHIFT; public const uint c_SCR__SLEEPONEXIT__SLEEP = 1u << c_SCR__SLEEPONEXIT__SHIFT; public const int c_SCR__SLEEPDEEP__SHIFT = 2; public const uint c_SCR__SLEEPDEEP__MASK = 1u << c_SCR__SLEEPDEEP__SHIFT; public const uint c_SCR__SLEEPDEEP__SLEEP = 0u << c_SCR__SLEEPDEEP__SHIFT; public const uint c_SCR__SLEEPDEEP__DEEP = 1u << c_SCR__SLEEPDEEP__SHIFT; public const int c_SCR__SEVONPEND__SHIFT = 4; public const uint c_SCR__SEVONPEND__MASK = 1u << c_SCR__SEVONPEND__SHIFT; public const uint c_SCR__SEVONPEND__ENONLY = 0u << c_SCR__SEVONPEND__SHIFT; public const uint c_SCR__SEVONPEND__ALL = 1u << c_SCR__SEVONPEND__SHIFT; // // CCR // public const uint c_CCR__MASK = 0x000003FF; public const int c_CCR__UNALIGN_TRP__SHIFT = 3; public const uint c_CCR__UNALIGN_TRP__MASK = 1u << c_CCR__UNALIGN_TRP__SHIFT; public const uint c_CCR__UNALIGN_TRP__NOTRAP = 0u << c_CCR__UNALIGN_TRP__SHIFT; public const uint c_CCR__UNALIGN_TRP__TRAP = 1u << c_CCR__UNALIGN_TRP__SHIFT; public const int c_CCR__STKALIGN__SHIFT = 9; public const uint c_CCR__STKALIGN__MASK = 1u << c_CCR__STKALIGN__SHIFT; public const uint c_CCR__STKALIGN__4 = 0u << c_CCR__STKALIGN__SHIFT; public const uint c_CCR__STKALIGN__8 = 1u << c_CCR__STKALIGN__SHIFT; public const uint c_CCR_STD_CONFIG_4 = (c_CCR__STKALIGN__4 | c_CCR__UNALIGN_TRP__NOTRAP) & c_CCR__MASK; public const uint c_CCR_STD_CONFIG_8 = (c_CCR__STKALIGN__8 | c_CCR__UNALIGN_TRP__NOTRAP) & c_CCR__MASK; // // ICSR // public const uint c_ICSR__MASK = 0xFFFFFFFF; public const uint c_ICSR__ALLOWED_MASK = 0x9E400000; public const int c_ICSR__PENDSTCLR__SHIFT = 25; public const uint c_ICSR__PENDSTCLR__MASK = 1u << c_ICSR__PENDSTCLR__SHIFT; public const uint c_ICSR__PENDSTCLR__SET = 1u << c_ICSR__PENDSTCLR__SHIFT; public const int c_ICSR__PENDSTSET__SHIFT = 26; public const uint c_ICSR__PENDSTSET__MASK = 1u << c_ICSR__PENDSTSET__SHIFT; public const uint c_ICSR__PENDSTSET__SET = 1u << c_ICSR__PENDSTSET__SHIFT; public const int c_ICSR__PENDSVCLR__SHIFT = 27; public const uint c_ICSR__PENDSVCLR__MASK = 1u << c_ICSR__PENDSVCLR__SHIFT; public const uint c_ICSR__PENDSVCLR__SET = 1u << c_ICSR__PENDSVCLR__SHIFT; public const int c_ICSR__PENDSVSET__SHIFT = 28; public const uint c_ICSR__PENDSVSET__MASK = 1u << c_ICSR__PENDSVSET__SHIFT; public const uint c_ICSR__PENDSVSET__SET = 1u << c_ICSR__PENDSVSET__SHIFT; public const int c_ICSR__NMIPENDSET__SHIFT = 31; public const uint c_ICSR__NMIPENDSET__MASK = 1u << c_ICSR__NMIPENDSET__SHIFT; public const uint c_ICSR__NMIPENDSET__SET = 1u << c_ICSR__NMIPENDSET__SHIFT; #endregion //--// // // Helper Methods // public override void InitializeProcessor( ) { // // We want to run ISRs in privilged Handler mode using the Main Stack Pointer and all the other tasks // in privileged Thread mode using the Process Stack Pointer. // // We will assume that native context switching is possible when processor initialization is carried out in // Handler/Privileged mode. Of course that is not a complete guarantee. After carrying out the initailization of the // idle thread task, we will let the initialization thread return to thread mode upon first context switch as per classic // technique mentioned below, from ARM reference manual. As switching the mode is carried out naturally by // setting the appropriate flag, there is nothing else we need to do at initialization time. See context switch code // in thread manager as well. // // From ARMv-7M Architecture Reference Manual. // // // By default, Thread mode uses the MSP. To switch the stack pointer used in Thread mode to the // PSP, either: // - use the MSR instruction to set the Active stack pointer bit to 1 // - perform an exception return to Thread mode with the appropriate EXC_RETURN value // ////// ////// ////// ////// Table 2-17 Exception return behavior ////// ////// EXC_RETURN Description ////// ========================================================================= ////// 0xFFFFFF[F|E]1 Return to Handler mode. ////// Exception return gets state [and FP state] from the main ////// stack (MSP). ////// Execution uses MSP after return. ////// ////// 0xFFFFFF[F|E]9 Return to Thread mode. ////// Exception Return get state [and FP state] from the main ////// stack (MSP). ////// Execution uses MSP after return. ////// ////// 0xFFFFFF[F|E]D Return to Thread mode. ////// Exception return gets state [and FP state] from the process ////// stack (PSP). ////// Execution uses PSP after return. ////// ////// All other values Reserved. ////// // // Disable interrupts, but not faults // DisableInterrupts( ); // // Ensure privileged Handler mode to boot // if(!VerifyHandlerMode()) { RT.BugCheck.Log( "Cannot bootstrap in Thread mode" ); RT.BugCheck.Assert( false, RT.BugCheck.StopCode.FailedBootstrap ); } // // Enforce reset behavior: // - only enabled interrupts or events can wakeup the processor, disabled interrupts are excluded // - sleep by turning off clock to main proc (not deep) // - do not sleep when returning to thread mode // SetSystemControlRegister( c_SCR__SLEEPONEXIT__NO_SLEEP | c_SCR__SLEEPDEEP__SLEEP | c_SCR__SEVONPEND__ENONLY ); // Enforce 8 bytes alignment // SetCCR( c_CCR_STD_CONFIG_4 ); } internal static void SetCCR( uint val ) { // NOTE: LWIP uses memory functions on addresses which are not 8 byte aligned // This prevents faults from occurring from those memory accesses CUSTOM_STUB_SCB_set_CCR( val ); } internal static void RaiseSystemHandler( uint mask ) { BugCheck.Assert( ((mask & ~(c_ICSR__ALLOWED_MASK)) == 0), BugCheck.StopCode.IncorrectArgument ); CUSTOM_STUB_SCB_ICSR_RaiseSystemException( mask ); } public static unsafe void RaiseSupervisorCall( SVC_Code code ) { switch(code) { case SVC_Code.SupervisorCall__LongJump: CUSTOM_STUB_RaiseSupervisorCallForLongJump( ); break; case SVC_Code.SupervisorCall__StartThreads: CUSTOM_STUB_RaiseSupervisorCallForStartThreads( ); break; case SVC_Code.SupervisorCall__RetireThread: CUSTOM_STUB_RaiseSupervisorCallForRetireThread( ); break; case SVC_Code.SupervisorCall__SnapshotProcessModeRegisters: // // Cause a SVC call to transition to Handler mode and // snapshot the Processmode registers // CUSTOM_STUB_RaiseSupervisorCallForSnapshotProcessModeRegisters( ); break; default: throw new ArgumentException( "Request SVC does not exists or is not supported" ); } } public static bool IsAnyExceptionActive( ) { return ( ( (ISR_NUMBER)CUSTOM_STUB_SCB_IPSR_GetCurrentISRNumber( ) ) != ISR_NUMBER.ThreadMode ); } public static void InitiateContextSwitch( ) { RaiseSystemHandler( c_ICSR__PENDSTSET__SET ) ; } public static void CompleteContextSwitch( ) { RaiseSystemHandler( c_ICSR__PENDSVSET__SET ) ; } internal void SetSystemControlRegister( uint flags ) { CUSTOM_STUB_SCB_SCR_SetSystemControlRegister( flags ); } public static void WaitForEvent( ) { #if SPIN_ON_SLEEP while(true) { } #else CMSIS_STUB_POWER_WaitForEvent( ); #endif } public static void SendEvent( ) { CMSIS_STUB_POWER_SendEvent( ); } public static void WaitForInterrupt( ) { #if SPIN_ON_SLEEP while(true) { } #else CMSIS_STUB_POWER_WaitForInterrupt( ); #endif } //--// private static void DisableSystemHandler( IRQn_Type ex ) { BugCheck.Assert( (ex < 0), BugCheck.StopCode.IncorrectArgument ); uint mask = 0; switch(ex) { case IRQn_Type.Reset_IRQn : case IRQn_Type.NonMaskableInt_IRQn: case IRQn_Type.HardFault_IRQn : // Cannot enable or disable NMI, Reset or HardFault //BugCheck.Assert( false, BugCheck.StopCode.IllegalMode ); break; case IRQn_Type.SVCall_IRQn : case IRQn_Type.PendSV_IRQn : case IRQn_Type.SysTick_IRQn_Optional: // NOT IMPLEMENTED: call NVIC //BugCheck.Assert( false, BugCheck.StopCode.IncorrectArgument ); break; default: BugCheck.Assert( false, BugCheck.StopCode.IncorrectArgument ); break; } CUSTOM_STUB_SCB_SHCRS_DisableSystemHandler( mask ); } // // Cache // public override UIntPtr GetCacheableAddress( UIntPtr ptr ) { // Cortex-M7 actually has a cache, so override the method return ptr; } public override UIntPtr GetUncacheableAddress( UIntPtr ptr ) { // Cortex-M7 actually has a cache, so override the method return ptr; } public override void FlushCacheLine( UIntPtr target ) { } //--// [Inline] public override bool AreInterruptsDisabled( ) { return GetPriMaskRegister() == 1; } public override bool AreAllInterruptsDisabled( ) { return AreInterruptsDisabled( ); } public override void Breakpoint( ) { Breakpoint( 0xa5a5a5a5 ); } //--//--// public static uint EnableInterrupts( ) { return SetPriMaskRegister( c_PRIMASK__InterruptsOn ); } public static uint DisableInterrupts( ) { return SetPriMaskRegister( c_PRIMASK__InterruptsOff ); } public static bool VerifyHandlerMode( ) { uint control = CMSIS_STUB_SCB__get_CONTROL( ); return ((control & c_CONTROL__SPSEL_MASK) == c_CONTROL__SPSEL_MSP); } //--// [Inline] internal static uint GetPriMaskRegister( ) { return CMSIS_STUB_SCB__get_PRIMASK( ); } [Inline] internal static uint SetPriMaskRegister( uint basepri ) { return CMSIS_STUB_SCB__set_PRIMASK( basepri ); } //--// // // We will implement the intrernal methods below with CMSIS-Core or custom stubs // [DllImport( "C" )] internal static extern uint CUSTOM_STUB_DebuggerConnected( ); [DllImport( "C" )] internal static extern uint CUSTOM_STUB_GetProgramCounter( ); [DllImport( "C" )] internal static extern uint CMSIS_STUB_SCB__get_CONTROL( ); [DllImport( "C" )] internal static extern void CMSIS_STUB_SCB__set_CONTROL( uint control ); [DllImport( "C" )] internal static extern uint CMSIS_STUB_SCB__get_IPSR( ); [DllImport( "C" )] internal static extern uint CMSIS_STUB_SCB__get_APSR( ); [DllImport( "C" )] internal static extern uint CMSIS_STUB_SCB__get_xPSR( ); [DllImport( "C" )] internal static extern uint CMSIS_STUB_SCB__get_PSP( ); [DllImport( "C" )] internal static extern void CMSIS_STUB_SCB__set_PSP( uint topOfProcStack ); [DllImport("C")] internal static unsafe extern void* CMSIS_STUB_SCB__get_MSP_ResetValue(); [DllImport("C")] internal static extern uint CMSIS_STUB_SCB__get_MSP_StackSize(); [DllImport( "C" )] internal static extern uint CMSIS_STUB_SCB__get_MSP( ); [DllImport( "C" )] internal static extern void CMSIS_STUB_SCB__set_MSP( uint topOfMainStack ); [DllImport( "C" )] internal static extern uint CMSIS_STUB_SCB__get_PRIMASK( ); [DllImport( "C" )] internal static extern uint CMSIS_STUB_SCB__set_PRIMASK( uint priMask ); [DllImport( "C" )] internal static extern void CMSIS_STUB_SCB__Enable_Irq( ); [DllImport( "C" )] internal static extern void CMSIS_STUB_SCB__Disable_Irq( ); // // !!! Cortex M0 only !!! // [DllImport( "C" )] internal static extern void CUSTOM_STUB_SCB_set_CCR( uint value ); [DllImport( "C" )] internal static extern void CUSTOM_STUB_SCB_SHCRS_DisableSystemHandler( uint ex ); [DllImport( "C" )] internal static extern void CUSTOM_STUB_SCB_ICSR_RaiseSystemException( uint ex ); [DllImport( "C" )] internal static extern void CUSTOM_STUB_RaiseSupervisorCallForLongJump( ); [DllImport( "C" )] internal static extern void CUSTOM_STUB_RaiseSupervisorCallForStartThreads( ); [DllImport( "C" )] internal static extern void CUSTOM_STUB_RaiseSupervisorCallForRetireThread( ); [DllImport( "C" )] internal static extern void CUSTOM_STUB_RaiseSupervisorCallForSnapshotProcessModeRegisters( ); [DllImport( "C" )] internal static extern void CUSTOM_STUB_SetExcReturn( uint ret ); [DllImport( "C" )] internal static extern int CUSTOM_STUB_SCB_IPSR_GetCurrentISRNumber( ); [DllImport( "C" )] internal static extern int CUSTOM_STUB_SCB_SCR_GetSystemControlRegister( ); [DllImport( "C" )] internal static extern void CUSTOM_STUB_SCB_SCR_SetSystemControlRegister( uint scr ); [DllImport( "C" )] private static extern void CMSIS_STUB_POWER_WaitForEvent( ); [DllImport( "C" )] private static extern void CMSIS_STUB_POWER_SendEvent( ); [DllImport( "C" )] private static extern void CMSIS_STUB_POWER_WaitForInterrupt( ); //--// //--// //--// // // Utility methods // [TS.WellKnownMethod( "ProcessorARMv6_Breakpoint" )] [DllImport( "C" )] public static extern void Breakpoint( uint value ); } } ================================================ FILE: Zelig/Zelig/RunTime/Zelig/Kernel/HardwareModel/TargetPlatform/ARMv6/ProcessorARMv6MForLlvm.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // #define SPIN_ON_SLEEP namespace Microsoft.Zelig.Runtime.TargetPlatform.ARMv6 { using System; using System.Runtime.InteropServices; using TS = Microsoft.Zelig.Runtime.TypeSystem; using RT = Microsoft.Zelig.Runtime; public abstract partial class ProcessorARMv6MForLlvm : ProcessorARMv6M { public struct StandardFrame { public UIntPtr R0; public UIntPtr R1; public UIntPtr R2; public UIntPtr R3; public UIntPtr R12; public UIntPtr LR; public UIntPtr PC; public UIntPtr PSR; } //--// [TS.WellKnownType( "Microsoft_Zelig_ARMv6ForLlvm_MethodWrapper" )] public sealed class MethodWrapperLlvm : AbstractMethodWrapper { [Inline] [DisableNullChecks( ApplyRecursively = true )] public override void Prologue( string typeFullName, string methodFullName, TS.MethodRepresentation.BuildTimeAttributes attribs ) { } [Inline] [DisableNullChecks( ApplyRecursively = true )] public unsafe override void Prologue( string typeFullName, string methodFullName, TS.MethodRepresentation.BuildTimeAttributes attribs, HardwareException he ) { } [Inline] [DisableNullChecks( ApplyRecursively = true )] public override void Epilogue( string typeFullName, string methodFullName, TS.MethodRepresentation.BuildTimeAttributes attribs ) { } [Inline] [DisableNullChecks( ApplyRecursively = true )] public unsafe override void Epilogue( string typeFullName, string methodFullName, TS.MethodRepresentation.BuildTimeAttributes attribs, HardwareException he ) { } } // // Helper Methods // //--// [Inline] protected static unsafe UIntPtr GetMainStackPointerAtReset() { return new UIntPtr(CMSIS_STUB_SCB__get_MSP_ResetValue()); } internal static UIntPtr GetMainStackPointerBottom() { UIntPtr stackBottom = AddressMath.Decrement(GetMainStackPointerAtReset(), GetMainStackSize()); return stackBottom; } [Inline] protected static uint GetMainStackSize() { return CMSIS_STUB_SCB__get_MSP_StackSize(); } [Inline] protected static UIntPtr GetMainStackPointer( ) { return new UIntPtr( CMSIS_STUB_SCB__get_MSP() ); } [Inline] protected static void SetMainStackPointer( UIntPtr topOfMainStack ) { CMSIS_STUB_SCB__set_MSP( topOfMainStack.ToUInt32() ); } [Inline] protected static UIntPtr GetProcessStackPointer( ) { return new UIntPtr( CMSIS_STUB_SCB__get_PSP( ) ); } [Inline] protected static void SetProcessStackPointer( UIntPtr topOfProcessStack ) { CMSIS_STUB_SCB__set_PSP( topOfProcessStack.ToUInt32() ); } protected static void SwitchToHandlerPrivilegedMode( ) { uint control = CMSIS_STUB_SCB__get_CONTROL( ); control &= ~c_CONTROL__MASK; control |= c_CONTROL__MODE__HNDLR; CMSIS_STUB_SCB__set_CONTROL( control & c_CONTROL__MASK ); } protected static void SwitchToThreadUnprivilegedMode( ) { uint control = CMSIS_STUB_SCB__get_CONTROL( ); control &= ~c_CONTROL__MASK; control |= c_CONTROL__MODE__THRD_UNPRIV; CMSIS_STUB_SCB__set_CONTROL( control & c_CONTROL__MASK ); } protected static void SwitchToThreadPrivilegedMode( ) { uint control = CMSIS_STUB_SCB__get_CONTROL( ); control &= ~c_CONTROL__MASK; control |= c_CONTROL__MODE__THRD_PRIV; CMSIS_STUB_SCB__set_CONTROL( control & c_CONTROL__MASK ); } protected static void SwitchToPrivilegedMode( ) { uint control = CMSIS_STUB_SCB__get_CONTROL( ); control &= ~c_CONTROL__MASK_PRIVILEGE; control |= c_CONTROL__nPRIV_PRIV; CMSIS_STUB_SCB__set_CONTROL( control & c_CONTROL__MASK ); } protected static void SwitchToUnprivilegedMode( ) { uint control = CMSIS_STUB_SCB__get_CONTROL( ); control &= ~c_CONTROL__MASK_PRIVILEGE; control |= c_CONTROL__nPRIV_UNPRIV; CMSIS_STUB_SCB__set_CONTROL( control & c_CONTROL__MASK ); } protected static void SetExcReturn( uint ret ) { CUSTOM_STUB_SetExcReturn( ret ); } // // Fault diagnostic // protected static uint GetProgramCounter() { return CUSTOM_STUB_GetProgramCounter( ); } protected static bool DebuggerConnected() { return false; } [RT.Inline] protected static unsafe StandardFrame* PointerToStdFrame( UIntPtr SP ) { return (StandardFrame*)SP.ToPointer( ); } // // All overridable exceptions // //////[RT.BottomOfCallStack( )] //////[RT.HardwareExceptionHandler( RT.HardwareException.NMI )] //////[RT.ExportedMethod] //////private static void NMI_Handler( ) //////{ ////// // ////// // The processor clears the FAULTMASK bit to 0 on exit from any exception handler except the NMI handler. ////// // ////// EnableFaults( ); //////} /// /// Hard Fault is caused by Bus Fault, Memory Management Fault, or Usage Fault if their handler /// cannot be executed. /// [RT.CapabilitiesFilter(RequiredCapabilities = TargetModel.ArmProcessor.InstructionSetVersion.Platform_Version__ARMv6M)] [RT.HardwareExceptionHandler( RT.HardwareException.Fault )] [RT.ExportedMethod] private static void HardFault_Handler_Zelig( uint sp ) { while(true) { Peripherals.Instance.WaitForInterrupt(); } } //--// [DllImport( "C" )] protected static extern unsafe uint* CUSTOM_STUB_FetchSoftwareFrameSnapshot( ); //--// //--// //--// // // Utility methods // [DllImport( "C" )] public static extern void Nop( ); } } ================================================ FILE: Zelig/Zelig/RunTime/Zelig/Kernel/HardwareModel/TargetPlatform/ARMv6/ProcessorARMv6MForLlvm_ContextSwitch.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // //#define DEBUG_CTX_SWITCH //#define DEBUG_CTX_FRAME_SNAPSHOT using System.Runtime.InteropServices; namespace Microsoft.Zelig.Runtime.TargetPlatform.ARMv6 { using System; using EncDef = Microsoft.Zelig.TargetModel.ArmProcessor.EncodingDefinition; using TS = Microsoft.Zelig.Runtime.TypeSystem; using RT = Microsoft.Zelig.Runtime; public abstract partial class ProcessorARMv6MForLlvm { //--// // // Part of Context may be defined in the model for the targeted sub-system, e.g. Mbed or CMSIS-Core for ARM processors // public abstract new class Context : Processor.Context { [StructLayout( LayoutKind.Sequential, Pack = 4 )] public struct SoftwareFrame { [TS.AssumeReferenced] public uint EXC_RETURN; [TS.AssumeReferenced] public uint CONTROL; [TS.AssumeReferenced] public UIntPtr R4; [TS.AssumeReferenced] public UIntPtr R5; [TS.AssumeReferenced] public UIntPtr R6; [TS.AssumeReferenced] public UIntPtr R7; [TS.AssumeReferenced] public UIntPtr R8; [TS.AssumeReferenced] public UIntPtr R9; [TS.AssumeReferenced] public UIntPtr R10; [TS.AssumeReferenced] public UIntPtr R11; }; [StructLayout( LayoutKind.Sequential, Pack = 4 )] public struct HardwareFrame { [TS.AssumeReferenced] public UIntPtr R0; [TS.AssumeReferenced] public UIntPtr R1; [TS.AssumeReferenced] public UIntPtr R2; [TS.AssumeReferenced] public UIntPtr R3; [TS.AssumeReferenced] public UIntPtr R12; [TS.AssumeReferenced] public UIntPtr LR; [TS.AssumeReferenced] public UIntPtr PC; [TS.AssumeReferenced] public UIntPtr PSR; }; [TS.WellKnownType( "Microsoft_Zelig_ProcessorARMv6_RegistersOnStack" )] [StructLayout( LayoutKind.Sequential, Pack = 4 )] public struct RegistersOnStack { public const uint StackRegister = EncDef.c_register_sp; public const uint LinkRegister = EncDef.c_register_lr; public const uint ProgramCounterRegister = EncDef.c_register_pc; // // State // // SW stack frame: pushed by PendSV_Handler public SoftwareFrame SoftwareFrameRegisters; // HW stack frame: pushed upon entering PendSV_Handler public HardwareFrame HardwareFrameRegisters; // // Helper Methods // public static unsafe uint TotalFrameSize { [RT.Inline] get { return HWFrameSize + SwitcherFrameSize; } } public static unsafe uint HWFrameSize { [RT.Inline] get { return (uint)sizeof( HardwareFrame ); } } public static unsafe uint SwitcherFrameSize { [RT.Inline] get { return (uint)sizeof( SoftwareFrame ); } } //--// public UIntPtr GetRegisterValue( uint idx ) { switch(idx) { case 0: return HardwareFrameRegisters.R0; case 1: return HardwareFrameRegisters.R1; case 2: return HardwareFrameRegisters.R2; case 3: return HardwareFrameRegisters.R3; case 4: return SoftwareFrameRegisters.R4; case 5: return SoftwareFrameRegisters.R5; case 6: return SoftwareFrameRegisters.R6; case 7: return SoftwareFrameRegisters.R7; case 8: return SoftwareFrameRegisters.R8; case 9: return SoftwareFrameRegisters.R9; case 10: return SoftwareFrameRegisters.R10; case 11: return SoftwareFrameRegisters.R11; case 12: return HardwareFrameRegisters.R12; case 14: return HardwareFrameRegisters.LR; case 15: return HardwareFrameRegisters.PC; } return UIntPtr.Zero; } } //--// // // This is the pointer to the base of the stack. Useful for stack walking. // protected UIntPtr BaseSP; // // This is the pointer to the last known position of the stack pointer // For a long jump this points to the end of the SW context to install // protected UIntPtr SP; // // Return value for mode transitions // protected uint EXC_RETURN; //--// protected Context( RT.ThreadImpl owner ) : base(owner) { } // // Overrides // public override unsafe void SwitchTo( ) { BugCheck.Assert( ProcessorARMv6M.IsAnyExceptionActive( ) == false, BugCheck.StopCode.IllegalMode ); // // Enable context switch through SVC call that will fall back into Thread/PSP mode onto // whatever thread the standard thread manager intended to switch into // SmartHandles.InterruptStateARMv6M.ResetSoftwareExceptionMode( ); SmartHandles.InterruptStateARMv6M.EnableAll( ); // // The long jump selects the current thread's context and sets its EXC_RETURN value // ProcessorARMv6M.RaiseSupervisorCall( SVC_Code.SupervisorCall__LongJump ); #if DEBUG_CTX_SWITCH BugCheck.Log( "!!!!!!!!!!!!!!!!!!!!! ERROR !!!!!!!!!!!!!!!!!!!!!!!" ); BugCheck.Log( "!!! Back after Long Jump after, Ctx Switch Failed !!!" ); BugCheck.Log( "!!!!!!!!!!!!!!!!!!!!! ERROR !!!!!!!!!!!!!!!!!!!!!!!" ); #endif RT.BugCheck.Assert( false, BugCheck.StopCode.IllegalMode ); } public override void Populate( ) { // // This would be called on the throw context, but in ARMv7M we do not have one // ThreadImpl thisThread = ThreadImpl.CurrentThread; Processor.Context ctx = thisThread.SwappedOutContext; this.BaseSP = ctx.BaseStackPointer; this.SP = GetProcessStackPointer(); this.EXC_RETURN = ctx.ExcReturn; } public override void Populate( Processor.Context context ) { this.BaseSP = context.BaseStackPointer; this.SP = context.StackPointer; this.EXC_RETURN = context.ExcReturn; } public unsafe override void PopulateFromDelegate( Delegate dlg, uint[] stack ) { DelegateImpl dlgImpl = (DelegateImpl)(object)dlg; ArrayImpl stackImpl = (ArrayImpl )(object)stack; ObjectImpl objImpl = (ObjectImpl )(object)dlg.Target; // // Save the initial stack pointer // In the general case the SP will be at the top of the current frame we are building // When we do a LongJump though, or we start the thread first, we will have to use the base stack pointer // this.BaseSP = AddressMath.AlignToLowerBoundary( new UIntPtr( stackImpl.GetEndDataPointer( ) ), 8 ); this.SP = AddressMath.Decrement( this.BaseSP, RegistersOnStack.TotalFrameSize ); this.EXC_RETURN = c_MODE_RETURN__THREAD_PSP; // // Initial SP must still be within the stack array // RT.BugCheck.Assert( stackImpl.GetDataPointer( ) <= this.SP.ToPointer( ), BugCheck.StopCode.StackCorruptionDetected ); RegistersOnStack* firstFrame = GetFrame(this.SP); // // build the first stack frame // firstFrame->HardwareFrameRegisters.PC = new UIntPtr( dlgImpl.InnerGetCodePointer( ).Target.ToPointer( ) ); firstFrame->HardwareFrameRegisters.PSR = new UIntPtr( c_psr_InitialValue ); firstFrame->SoftwareFrameRegisters.EXC_RETURN = c_MODE_RETURN__THREAD_PSP; firstFrame->SoftwareFrameRegisters.CONTROL = c_CONTROL__MODE__THRD_PRIV; firstFrame->HardwareFrameRegisters.R0 = objImpl.ToPointer( ); #if DEBUG_CTX_SWITCH RT.BugCheck.Log( "[PFD-ctx] EXC=0x%08x, PSR=0x%08x, PC=0x%08x, R0=0x%08x, SP(aligned)=0x%08x", (int)firstFrame->SoftwareFrameRegisters.EXC_RETURN, (int)firstFrame->HardwareFrameRegisters.PSR.ToUInt32( ), (int)firstFrame->HardwareFrameRegisters.PC.ToUInt32( ), (int)firstFrame->HardwareFrameRegisters.R0.ToUInt32( ), (int)this.SP.ToUInt32( ) ); RT.BugCheck.Log( "[PFD-stackImpl] SP(start)=0x%08x, SP(end)=0x%08x, SP(length)=0x%08x, SP(offset)=0x%08x", (int)( stackImpl.GetDataPointer( ) ), (int)( stackImpl.GetEndDataPointer( ) ), (int)( stackImpl.GetEndDataPointer( ) - stackImpl.GetDataPointer( ) ), (int)( (int)stackImpl.GetEndDataPointer( ) - this.SP.ToUInt32( ) ) ); #endif } public override void SetupForExceptionHandling( uint mode ) { // // Stop any exception from happening // using(Runtime.SmartHandles.InterruptState.DisableAll()) { // // Retrieve the MSP< which we will use to handle exceptions // UIntPtr stack = GetMainStackPointer(); //// //// Enter target mode, with interrupts disabled. //// //SwitchToHandlerPrivilegedMode( ); // // Set the stack pointer in the context to be the current MSP // this.BaseSP = GetMainStackPointerAtReset(); this.SP = stack; this.EXC_RETURN = c_MODE_RETURN__THREAD_MSP; //// //// Switch back to original mode //// //SwitchToThreadUnprivilegedMode( ); } } #region Tracking Collector and Exceptions public override bool Unwind( ) { throw new Exception( "Unwind not implemented" ); } public override UIntPtr GetRegisterByIndex( uint idx ) { return Snapshot.GetRegisterValue( idx ); } public override unsafe void SetRegisterByIndex( uint idx, UIntPtr value ) { BugCheck.Assert( false, BugCheck.StopCode.InvalidOperation ); } #endregion private static UIntPtr ContextSwitch( ThreadManager tm, UIntPtr stackPointer ) { ThreadImpl currentThread = tm.CurrentThread; ThreadImpl nextThread = tm.NextThread; Context ctx; if(currentThread != null) { ctx = (Context)currentThread.SwappedOutContext; // // update SP as well as the EXC_RETURN address // unsafe { ctx.EXC_RETURN = GetFrame(stackPointer)->SoftwareFrameRegisters.EXC_RETURN; } ctx.StackPointer = stackPointer; } ctx = (Context)nextThread.SwappedOutContext; // // Pass EXC_RETURN down to the native portion of the // PendSV handler we need to offset to the beginning of the frame // SetExcReturn( ctx.EXC_RETURN ); // // Update thread manager state and Thread.CurrentThread static field // tm.CurrentThread = nextThread; ThreadImpl.CurrentThread = nextThread; return ctx.StackPointer; } //--// //--// //--// private static unsafe void FirstLongJump( ) { LongJump( ); } private static unsafe void LongJump( ) { // // Retrieve next context from ThreadManager // Context currentThreadCtx = (ProcessorARMv6MForLlvm.Context)ThreadManager.Instance.CurrentThread.SwappedOutContext; // // Set the PSP at R0 so that returning from the SVC handler will complete the work // SetProcessStackPointer( AddressMath.Increment( currentThreadCtx.StackPointer, ProcessorARMv6MForLlvm.Context.RegistersOnStack.SwitcherFrameSize ) ); SetExcReturn( currentThreadCtx.EXC_RETURN ); // // SWitch to unprivileged mode before jumping to our thread // This can only be enabled when we have a model for allowing tasks // to enable/disable interrupts // //ProcessorARMv6M.SwitchToUnprivilegedMode( ); } private static unsafe void LongJumpForRetireThread( ) { LongJump( ); } // // Access Methods // public override UIntPtr StackPointer { get { return this.SP; } set { this.SP = value; } } public override UIntPtr BaseStackPointer { [RT.Inline] get { return this.BaseSP; } } public override uint ExcReturn { [RT.Inline] get { return this.EXC_RETURN; } [RT.Inline] set { this.EXC_RETURN = value; } } public override UIntPtr ProgramCounter { get { //return Registers.PC; return (UIntPtr)0; } set { //Registers.PC = value; } } public override uint ScratchedIntegerRegisters { get { return 0; } } //--// [RT.Inline] internal static unsafe Context.RegistersOnStack* GetFrame( UIntPtr SP ) { return (Context.RegistersOnStack*)SP.ToPointer( ); } private static unsafe void SnapshotActiveFrame( ref Context.RegistersOnStack frame ) { //// //// Can run in handler mode only //// //BugCheck.Assert( VerifyHandlerMode( ), BugCheck.StopCode.IllegalMode ); //// //// Retrieve PSP and snapshot the frame that was pushed by the SVC handler //// //UIntPtr psp = GetProcessStackPointer( ); //Context.RegistersOnStack* snapshot = GetFrame( psp ); //frame.HardwareFrameRegisters = snapshot->HardwareFrameRegisters; //frame.SoftwareFrameRegisters = snapshot->SoftwareFrameRegisters; } // // Helpers // [Inline] public static void InterruptHandlerWithContextSwitch( UIntPtr stackPtr ) { Peripherals.Instance.ProcessInterrupt( ); ThreadManager tm = ThreadManager.Instance; // We keep looping until the current and next threads are the same, because // when swapping out a dead thread, we might wake up a different thread. while(tm.ShouldContextSwitch) { ContextSwitch( tm, stackPtr ); } } [Inline] public static void InterruptHandlerWithoutContextSwitch( ) { Peripherals.Instance.ProcessInterrupt( ); } [Inline] public static void FastInterruptHandlerWithoutContextSwitch( ) { Peripherals.Instance.ProcessFastInterrupt( ); } [Inline] public static void GenericSoftwareInterruptHandler( ref RegistersOnStack registers ) { } //--// [Inline] private static unsafe void PrepareStackForException( uint mode, Context.RegistersOnStack* ptr ) { // // EXC_RETURN to go back to previous mode. // // TODO: // // Save unbanked R4 -R11. // // TODO: // // Switch back to the exception handling mode. // // TODO: // // R1 should point to the Register Context on the stack. // // TODO: //SetRegister( EncDef.c_register_r1, new UIntPtr( ptr ) ); } [Inline] private static unsafe void RestoreStackForException( uint mode, Context.RegistersOnStack* ptr ) { // // EXC_RETUNR to go back to previous mode. // // TODO: // // Save unbanked R4 -R11. // // TODO: // // Switch back to the exception handling mode. // // TODO: // // R1 should point to the Register Context on the stack. // // TODO: //SetRegister( EncDef.c_register_r1, new UIntPtr( ptr ) ); } // // All overridable exceptions for Ctx switch // [RT.CapabilitiesFilter( RequiredCapabilities=TargetModel.ArmProcessor.InstructionSetVersion.Platform_Version__ARMv6M)] [RT.HardwareExceptionHandler( RT.HardwareException.Service )] [RT.ExportedMethod] private static unsafe void SVC_Handler_Zelig( uint* args ) { SVC_Code svc_number = (SVC_Code)((byte*)args[6])[-2]; // svc number is at stacked PC offset - 2 bytes switch(svc_number) { case SVC_Code.SupervisorCall__LongJump: LongJump( ); break; case SVC_Code.SupervisorCall__StartThreads: FirstLongJump( ); break; case SVC_Code.SupervisorCall__RetireThread: LongJumpForRetireThread( ); break; case SVC_Code.SupervisorCall__SnapshotProcessModeRegisters: UpdateFrame( ref ProcessorARMv6MForLlvm.Snapshot, CUSTOM_STUB_FetchSoftwareFrameSnapshot( ) ); break; default: BugCheck.Assert( false, BugCheck.StopCode.Impossible ); break; } } [RT.CapabilitiesFilter( RequiredCapabilities=TargetModel.ArmProcessor.InstructionSetVersion.Platform_Version__ARMv6M)] [RT.HardwareExceptionHandler( RT.HardwareException.Interrupt )] [RT.ExportedMethod] private static UIntPtr PendSV_Handler_Zelig( UIntPtr stackPtr ) { using(SmartHandles.InterruptStateARMv6M.Disable( )) { return ContextSwitch(ThreadManager.Instance, stackPtr ); } } [RT.CapabilitiesFilter( RequiredCapabilities=TargetModel.ArmProcessor.InstructionSetVersion.Platform_VFP__SoftVFP )] [RT.HardwareExceptionHandler( RT.HardwareException.Interrupt )] [RT.ExportedMethod] private static void AnyInterrupt( UIntPtr stackPtr ) { using(RT.SmartHandles.InterruptState.Disable( )) { InterruptHandlerWithContextSwitch( stackPtr ); } } } //--// // // State // public static Context.RegistersOnStack Snapshot; // // Helper methods // //--// [RT.CapabilitiesFilter(RequiredCapabilities = TargetModel.ArmProcessor.InstructionSetVersion.Platform_Version__ARMv6M)] [ExportedMethod] private static unsafe void CUSTOM_STUB_NotifySoftwareFrameSnapshot( void* frame, int size ) { BugCheck.Assert( size * sizeof( uint ) == Context.RegistersOnStack.TotalFrameSize, BugCheck.StopCode.StackCorruptionDetected ); uint* registers = (uint*)frame; UpdateFrame( ref Snapshot, registers ); } protected static unsafe void UpdateFrame( ref Context.RegistersOnStack snapshot, uint* registers ) { #if DEBUG_CTX_FRAME_SNAPSHOT BugCheck.Log( "[Last Active Frame] EXC=0x%08x, PSR=0x%08x, PC=0x%08x", (int)registers[ 0 ], (int)registers[ 17 ], (int)registers[ 16 ] ); BugCheck.Log( "[Last Active Frame] R0=0x%08x, R1=0x%08x, R2=0x%08x, R3=0x%08x, R12=0x%08x", (int)registers[ 10 ], (int)registers[ 11 ], (int)registers[ 12 ], (int)registers[ 13 ], (int)registers[ 14 ] ); #endif snapshot.SoftwareFrameRegisters.EXC_RETURN = registers[ 0 ]; snapshot.SoftwareFrameRegisters.CONTROL = registers[ 1 ]; snapshot.SoftwareFrameRegisters.R4 = new UIntPtr( registers[ 2 ] ); snapshot.SoftwareFrameRegisters.R5 = new UIntPtr( registers[ 3 ] ); snapshot.SoftwareFrameRegisters.R6 = new UIntPtr( registers[ 4 ] ); snapshot.SoftwareFrameRegisters.R7 = new UIntPtr( registers[ 5 ] ); snapshot.SoftwareFrameRegisters.R8 = new UIntPtr( registers[ 6 ] ); snapshot.SoftwareFrameRegisters.R9 = new UIntPtr( registers[ 7 ] ); snapshot.SoftwareFrameRegisters.R10 = new UIntPtr( registers[ 8 ] ); snapshot.SoftwareFrameRegisters.R11 = new UIntPtr( registers[ 9 ] ); //--// snapshot.HardwareFrameRegisters.R0 = new UIntPtr( registers[ 10 ] ); snapshot.HardwareFrameRegisters.R1 = new UIntPtr( registers[ 11 ] ); snapshot.HardwareFrameRegisters.R2 = new UIntPtr( registers[ 12 ] ); snapshot.HardwareFrameRegisters.R3 = new UIntPtr( registers[ 13 ] ); snapshot.HardwareFrameRegisters.R12 = new UIntPtr( registers[ 14 ] ); snapshot.HardwareFrameRegisters.LR = new UIntPtr( registers[ 15 ] ); snapshot.HardwareFrameRegisters.PC = new UIntPtr( registers[ 16 ] ); snapshot.HardwareFrameRegisters.PSR = new UIntPtr( registers[ 17 ] ); } } } ================================================ FILE: Zelig/Zelig/RunTime/Zelig/Kernel/HardwareModel/TargetPlatform/ARMv7/InterruptsSafeHandleARMv7M.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // namespace Microsoft.Zelig.Runtime.TargetPlatform.ARMv7.SmartHandles { using System; using ISA = TargetModel.ArmProcessor.InstructionSetVersion; [ExtendClass( typeof(Runtime.SmartHandles.InterruptState), PlatformVersionFilter=ISA.Platform_Version__ARMv7M )] public struct InterruptStateARMv7M : IDisposable { // // State // uint m_basepri; // // Constructor Methods // [DiscardTargetImplementation()] [Inline] public InterruptStateARMv7M( uint basepri ) { m_basepri = basepri; } // // Helper Methods // [Inline] public void Dispose() { ProcessorARMv7M.DisableInterruptsWithPriorityLevelLowerOrEqualTo( m_basepri ); } [Inline] public void Toggle() { uint basepri = ProcessorARMv7M.SetBasePriRegister( m_basepri ); ProcessorARMv7MForLlvm.Nop(); ProcessorARMv7M.SetBasePriRegister( basepri ); } //--// [Inline] public static InterruptStateARMv7M Disable() { return new InterruptStateARMv7M( ProcessorARMv7M.DisableInterrupts( ) ); } [Inline] public static InterruptStateARMv7M DisableAll( ) { return new InterruptStateARMv7M( ProcessorARMv7M.DisableInterrupts( ) ); } [Inline] public static InterruptStateARMv7M Enable() { return new InterruptStateARMv7M( ProcessorARMv7M.EnableInterrupts( ) ); } [Inline] public static InterruptStateARMv7M EnableAll( ) { return new InterruptStateARMv7M( ProcessorARMv7M.EnableInterrupts( ) ); } // // Access Methods // [Inline] public uint GetPreviousState() { return m_basepri; } public HardwareException GetCurrentExceptionMode() { ProcessorARMv7M.ISR_NUMBER ex = GetMode(); if(ex == ProcessorARMv7M.ISR_NUMBER.ThreadMode) { return HardwareException.None; } switch(ex) { case ProcessorARMv7M.ISR_NUMBER.NMI : return HardwareException.NMI; case ProcessorARMv7M.ISR_NUMBER.HardFault : return HardwareException.Fault; case ProcessorARMv7M.ISR_NUMBER.MemManage : return HardwareException.Fault; case ProcessorARMv7M.ISR_NUMBER.BusFault : return HardwareException.Fault; case ProcessorARMv7M.ISR_NUMBER.UsageFault : return HardwareException.Fault; case ProcessorARMv7M.ISR_NUMBER.SVCall : return HardwareException.Service; case ProcessorARMv7M.ISR_NUMBER.ReservedForDebug: return HardwareException.Debug; case ProcessorARMv7M.ISR_NUMBER.PendSV : return HardwareException.PendSV; case ProcessorARMv7M.ISR_NUMBER.SysTick : return HardwareException.SysTick; case ProcessorARMv7M.ISR_NUMBER.Reset : case ProcessorARMv7M.ISR_NUMBER.Reserved7 : case ProcessorARMv7M.ISR_NUMBER.Reserved8 : case ProcessorARMv7M.ISR_NUMBER.Reserved9 : case ProcessorARMv7M.ISR_NUMBER.Reserved10 : case ProcessorARMv7M.ISR_NUMBER.Reserved13 : BugCheck.Assert( false, BugCheck.StopCode.IllegalMode ); break; default : return HardwareException.Interrupt; } return HardwareException.Interrupt; } //--// private ProcessorARMv7M.ISR_NUMBER GetMode( ) { return (ProcessorARMv7M.ISR_NUMBER)(ProcessorARMv7M.CMSIS_STUB_SCB__get_IPSR( ) & 0x1FF); } } } ================================================ FILE: Zelig/Zelig/RunTime/Zelig/Kernel/HardwareModel/TargetPlatform/ARMv7/ProcessorARMv7M.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // //#define SPIN_ON_SLEEP namespace Microsoft.Zelig.Runtime.TargetPlatform.ARMv7 { using System; using System.Runtime.InteropServices; using TS = Microsoft.Zelig.Runtime.TypeSystem; using RT = Microsoft.Zelig.Runtime; public abstract partial class ProcessorARMv7M : RT.Processor { public enum IRQn_Type : int { // Cortex-M Processor IRQ number, from cmsis implementation Reset_IRQn = -42, /*!< Exception#: 1 Reset (not actually defined as an IRQn_Type) */ NonMaskableInt_IRQn = -14, /*!< Exception#: 2 Non Maskable Interrupt */ HardFault_IRQn = -13, /*!< Exception#: 3 Non Maskable Interrupt */ MemoryManagement_IRQn = -12, /*!< Exception#: 4 Cortex-M3/4 Memory Management Interrupt */ BusFault_IRQn = -11, /*!< Exception#: 5 Cortex-M3/4 Bus Fault Interrupt */ UsageFault_IRQn = -10, /*!< Exception#: 6 Cortex-M3/4 Usage Fault Interrupt */ Reserved_IRQn9 = -9, /*!< Exception#: 7 Reserved */ Reserved_IRQn8 = -8, /*!< Exception#: 8 Reserved */ Reserved_IRQn7 = -7, /*!< Exception#: 9 Reserved */ Reserved_IRQn6 = -6, /*!< Exception#: 10 Reserved */ SVCall_IRQn = -5, /*!< Exception#: 11 Cortex-M3/4 SV Call Interrupt */ DebugMonitor_IRQn = -4, /*!< Exception#: 12 Cortex-M3/4 Debug Monitor Interrupt */ Reserved_IRQn3 = -3, /*!< Exception#: 13 Reserved */ PendSV_IRQn = -2, /*!< Exception#: 14 Cortex-M3/4 Pend SV Interrupt */ SysTick_IRQn = -1, /*!< Exception#: 15 Cortex-M3/4 System Tick Interrupt */ //--// AnyInterrupt16 = 0, //--// Invalid = 0xFFFF, } public enum ISR_NUMBER : uint { // Cortex-M Processor exception Numbers, as reported by the IPSR ThreadMode = 0, Reset = 1, NMI = 2, HardFault = 3, MemManage = 4, BusFault = 5, UsageFault = 6, Reserved7 = 7, Reserved8 = 8, Reserved9 = 9, Reserved10 = 10, SVCall = 11, ReservedForDebug = 12, Reserved13 = 13, PendSV = 14, SysTick = 15, //--// Peripheral = 16, Last = 240, } public enum SVC_Code : byte { SupervisorCall__LongJump = 0x11, SupervisorCall__StartThreads = 0x12, SupervisorCall__RetireThread = 0x13, SupervisorCall__SnapshotProcessModeRegisters = 0x14, } // // Exception priorities // public const uint c_Priority__MASK = 0x000000FFu; public const uint c_Priority__NeverDisabled = 0x00000000u; public const uint c_Priority__Highest = 0x00000001u; public const uint c_Priority__Lowest = 0x000000FFu; public const uint c_Priority__HigherThanAnyWeOwn = 0x00000004u; public const uint c_Priority__SVCCall = 0x00000005u; public const uint c_Priority__Default = 0x00000007u; public const uint c_Priority__SystemTimer = c_Priority__Default; public const uint c_Priority__SysTick = c_Priority__Default; public const uint c_Priority__GenericPeripherals = c_Priority__Default + 1; public const uint c_Priority__PendSV = 0x0000000Eu; #region Registers and Fields Definitions // // Interrupts management // In the simplest case, we will use the PRIMASK against a BASEPRI of 0x00000000, which is the reset value // public const uint c_PRIMASK__InterruptsOff = 0x00000001; public const uint c_PRIMASK__InterruptsOn = 0x00000000; public const uint c_FAULTMASK__FaultsOff = 0x00000001; public const uint c_FAULTMASK__FaultsOn = 0x00000000; public const uint c_FAULTMASK__AreFaultsOff = c_FAULTMASK__FaultsOff << 1; // // PSR register // public const uint c_psr_InitialValue = 0x01000000; // just Thumb state set // // CONTROL register // public const uint c_CONTROL__MASK = 0x00000003; public const uint c_CONTROL__MASK_PRIVILEGE = 0x00000001; // // stack pointer // public const int c_CONTROL__SPSEL_SHIFT = 1; public const uint c_CONTROL__SPSEL_MASK = 0x1u << c_CONTROL__SPSEL_SHIFT; public const uint c_CONTROL__SPSEL_MSP = 0x0u << c_CONTROL__SPSEL_SHIFT; public const uint c_CONTROL__SPSEL_PSP = 0x1u << c_CONTROL__SPSEL_SHIFT; // // privilege // public const int c_CONTROL__nPRIV_SHIFT = 0; public const uint c_CONTROL__nPRIV_MASK = 0x1u << c_CONTROL__nPRIV_SHIFT; public const uint c_CONTROL__nPRIV_PRIV = 0x0u << c_CONTROL__nPRIV_SHIFT; public const uint c_CONTROL__nPRIV_UNPRIV = 0x1u << c_CONTROL__nPRIV_SHIFT; // // Modes // public const uint c_CONTROL__MODE__HNDLR = c_CONTROL__SPSEL_MSP | c_CONTROL__nPRIV_PRIV; public const uint c_CONTROL__MODE__THRD_PRIV = c_CONTROL__SPSEL_PSP | c_CONTROL__nPRIV_PRIV; public const uint c_CONTROL__MODE__THRD_UNPRIV = c_CONTROL__SPSEL_PSP | c_CONTROL__nPRIV_UNPRIV; // // EXC_RETURN // public const uint c_MODE_RETURN__HANDLER_MSP = 0xFFFFFFF1; // handler will return in handler mode using the MSP public const uint c_MODE_RETURN__THREAD_MSP = 0xFFFFFFF9; // handler will return in thread mode using the MSP public const uint c_MODE_RETURN__THREAD_PSP = 0xFFFFFFFD; // handler will return in thread mode using the PSP // // SCR // public const uint c_SCR__MASK = 0x0000001F; public const int c_SCR__SLEEPONEXIT__SHIFT = 1; public const uint c_SCR__SLEEPONEXIT__MASK = 1u << c_SCR__SLEEPONEXIT__SHIFT; public const uint c_SCR__SLEEPONEXIT__NO_SLEEP = 0u << c_SCR__SLEEPONEXIT__SHIFT; public const uint c_SCR__SLEEPONEXIT__SLEEP = 1u << c_SCR__SLEEPONEXIT__SHIFT; public const int c_SCR__SLEEPDEEP__SHIFT = 2; public const uint c_SCR__SLEEPDEEP__MASK = 1u << c_SCR__SLEEPDEEP__SHIFT; public const uint c_SCR__SLEEPDEEP__SLEEP = 0u << c_SCR__SLEEPDEEP__SHIFT; public const uint c_SCR__SLEEPDEEP__DEEP = 1u << c_SCR__SLEEPDEEP__SHIFT; public const int c_SCR__SEVONPEND__SHIFT = 4; public const uint c_SCR__SEVONPEND__MASK = 1u << c_SCR__SEVONPEND__SHIFT; public const uint c_SCR__SEVONPEND__ENONLY = 0u << c_SCR__SEVONPEND__SHIFT; public const uint c_SCR__SEVONPEND__ALL = 1u << c_SCR__SEVONPEND__SHIFT; // // CCR // public const uint c_CCR__MASK = 0x000003FF; public const int c_CCR__NONBASETHRDENA__SHIFT = 0; public const uint c_CCR__NONBASETHRDENA__MASK = 1u << c_CCR__NONBASETHRDENA__SHIFT; public const uint c_CCR__NONBASETHRDENA__NO_EX = 0u << c_CCR__NONBASETHRDENA__SHIFT; public const uint c_CCR__NONBASETHRDENA__ANY = 1u << c_CCR__NONBASETHRDENA__SHIFT; public const int c_CCR__UNALIGN_TRP__SHIFT = 3; public const uint c_CCR__UNALIGN_TRP__MASK = 1u << c_CCR__UNALIGN_TRP__SHIFT; public const uint c_CCR__UNALIGN_TRP__NOTRAP = 0u << c_CCR__UNALIGN_TRP__SHIFT; public const uint c_CCR__UNALIGN_TRP__TRAP = 1u << c_CCR__UNALIGN_TRP__SHIFT; public const int c_CCR__DIV_0_TRP__SHIFT = 4; public const uint c_CCR__DIV_0_TRP__MASK = 1u << c_CCR__DIV_0_TRP__SHIFT; public const uint c_CCR__DIV_0_TRP__NOTRAP = 0u << c_CCR__DIV_0_TRP__SHIFT; public const uint c_CCR__DIV_0_TRP__TRAP = 1u << c_CCR__DIV_0_TRP__SHIFT; public const int c_CCR__STKALIGN__SHIFT = 9; public const uint c_CCR__STKALIGN__MASK = 1u << c_CCR__STKALIGN__SHIFT; public const uint c_CCR__STKALIGN__4 = 0u << c_CCR__STKALIGN__SHIFT; public const uint c_CCR__STKALIGN__8 = 1u << c_CCR__STKALIGN__SHIFT; public const uint c_CCR_STD_CONFIG_4 = (c_CCR__STKALIGN__4 | c_CCR__DIV_0_TRP__TRAP | c_CCR__UNALIGN_TRP__NOTRAP | c_CCR__NONBASETHRDENA__ANY) & c_CCR__MASK; public const uint c_CCR_STD_CONFIG_8 = (c_CCR__STKALIGN__8 | c_CCR__DIV_0_TRP__TRAP | c_CCR__UNALIGN_TRP__NOTRAP | c_CCR__NONBASETHRDENA__ANY) & c_CCR__MASK; // // ICSR // public const uint c_ICSR__MASK = 0xFFFFFFFF; public const uint c_ICSR__ALLOWED_MASK = 0x9E400000; public const int c_ICSR__PENDSTCLR__SHIFT = 25; public const uint c_ICSR__PENDSTCLR__MASK = 1u << c_ICSR__PENDSTCLR__SHIFT; public const uint c_ICSR__PENDSTCLR__SET = 1u << c_ICSR__PENDSTCLR__SHIFT; public const int c_ICSR__PENDSTSET__SHIFT = 26; public const uint c_ICSR__PENDSTSET__MASK = 1u << c_ICSR__PENDSTSET__SHIFT; public const uint c_ICSR__PENDSTSET__SET = 1u << c_ICSR__PENDSTSET__SHIFT; public const int c_ICSR__PENDSVCLR__SHIFT = 27; public const uint c_ICSR__PENDSVCLR__MASK = 1u << c_ICSR__PENDSVCLR__SHIFT; public const uint c_ICSR__PENDSVCLR__SET = 1u << c_ICSR__PENDSVCLR__SHIFT; public const int c_ICSR__PENDSVSET__SHIFT = 28; public const uint c_ICSR__PENDSVSET__MASK = 1u << c_ICSR__PENDSVSET__SHIFT; public const uint c_ICSR__PENDSVSET__SET = 1u << c_ICSR__PENDSVSET__SHIFT; public const int c_ICSR__NMIPENDSET__SHIFT = 31; public const uint c_ICSR__NMIPENDSET__MASK = 1u << c_ICSR__NMIPENDSET__SHIFT; public const uint c_ICSR__NMIPENDSET__SET = 1u << c_ICSR__NMIPENDSET__SHIFT; // // SHCSR // public const uint c_SHCSR__MASK = 0xFFF7FD8B; public const int c_SHCSR__MEMFAULTENA__SHIFT = 16; public const uint c_SHCSR__MEMFAULTENA__MASK = 1u << c_SHCSR__MEMFAULTENA__SHIFT; public const uint c_SHCSR__MEMFAULTENA__ENABLE = 1u << c_SHCSR__MEMFAULTENA__SHIFT; public const uint c_SHCSR__MEMFAULTENA__DISABLE = 0u << c_SHCSR__MEMFAULTENA__SHIFT; public const int c_SHCSR__BUSFAULTENA__SHIFT = 17; public const uint c_SHCSR__BUSFAULTENA__MASK = 1u << c_SHCSR__BUSFAULTENA__SHIFT; public const uint c_SHCSR__BUSFAULTENA__ENABLE = 1u << c_SHCSR__BUSFAULTENA__SHIFT; public const uint c_SHCSR__BUSFAULTENA__DISABLE = 0u << c_SHCSR__BUSFAULTENA__SHIFT; public const int c_SHCSR__USGFAULTENA__SHIFT = 18; public const uint c_SHCSR__USGFAULTENA__MASK = 1u << c_SHCSR__USGFAULTENA__SHIFT; public const uint c_SHCSR__USGFAULTENA__ENABLE = 1u << c_SHCSR__USGFAULTENA__SHIFT; public const uint c_SHCSR__USGFAULTENA__DISABLE = 0u << c_SHCSR__USGFAULTENA__SHIFT; //--// public const int c_SCB_SHCSR_USGFAULTENA__SHIFT = 18; public const uint c_SCB_SHCSR_USGFAULTENA__MASK = 1u << c_SCB_SHCSR_USGFAULTENA__SHIFT; public const uint c_SCB_SHCSR_USGFAULTENA__SET = 1u << c_SCB_SHCSR_USGFAULTENA__SHIFT; public const int c_SCB_SHCSR_BUSFAULTENA__SHIFT = 17; public const uint c_SCB_SHCSR_BUSFAULTENA__MASK = 1u << c_SCB_SHCSR_BUSFAULTENA__SHIFT; public const uint c_SCB_SHCSR_BUSFAULTENA__SET = 1u << c_SCB_SHCSR_BUSFAULTENA__SHIFT; public const int c_SCB_SHCSR_MEMFAULTENA__SHIFT = 16; public const uint c_SCB_SHCSR_MEMFAULTENA__SET = 1u << c_SCB_SHCSR_MEMFAULTENA__SHIFT; //--// public const int c_SCB_HFSR_FORCED_SHIFT = 30; public const uint c_SCB_HFSR_FORCED_MASK = 1u << c_SCB_HFSR_FORCED_SHIFT; public const uint c_SCB_HFSR_FORCED_FORCED = 1u << c_SCB_HFSR_FORCED_SHIFT; // escalated hard fault public const int c_SCB_HFSR_VECTTBL_SHIFT = 1; public const uint c_SCB_HFSR_VECTTBL_MASK = 1u << c_SCB_HFSR_VECTTBL_SHIFT; public const uint c_SCB_HFSR_VECTTBL_READ = 1u << c_SCB_HFSR_VECTTBL_SHIFT; // fault on vector table read //--// public const int c_SCB_CFSR_MEMFAULT_SHIFT = 0; public const uint c_SCB_CFSR_MEMFAULT_MASK = 0xFFu << c_SCB_CFSR_MEMFAULT_SHIFT; public const uint c_SCB_CFSR_MEMFAULT_IACCVIOL = 0x01u << c_SCB_CFSR_MEMFAULT_SHIFT; // instruction access violation public const uint c_SCB_CFSR_MEMFAULT_DACCVIOL = 0x02u << c_SCB_CFSR_MEMFAULT_SHIFT; // load or store at invalid address public const uint c_SCB_CFSR_MEMFAULT_MUNSTKERR = 0x08u << c_SCB_CFSR_MEMFAULT_SHIFT; // memory access fault on unstacking public const uint c_SCB_CFSR_MEMFAULT_MSTKERR = 0x10u << c_SCB_CFSR_MEMFAULT_SHIFT; // memory access fault on stacking public const uint c_SCB_CFSR_MEMFAULT_MLSPERR = 0x20u << c_SCB_CFSR_MEMFAULT_SHIFT; // fault on lazy state preservation public const uint c_SCB_CFSR_MEMFAULT_MMFARVALID = 0x80u << c_SCB_CFSR_MEMFAULT_SHIFT; public const int c_SCB_CFSR_BUSFAULT_SHIFT = 8; public const uint c_SCB_CFSR_BUSFAULT_MASK = 0xFFu << c_SCB_CFSR_BUSFAULT_SHIFT; public const uint c_SCB_CFSR_BUSFAULT_IBUSERR = 0x01u << c_SCB_CFSR_BUSFAULT_SHIFT; // bus error on instruction fetch and attempted execution public const uint c_SCB_CFSR_BUSFAULT_PRECISERR = 0x02u << c_SCB_CFSR_BUSFAULT_SHIFT; // stacked PC points to actual location of fault public const uint c_SCB_CFSR_BUSFAULT_IMPRCISERR = 0x04u << c_SCB_CFSR_BUSFAULT_SHIFT; // unknow fault location public const uint c_SCB_CFSR_BUSFAULT_UNSTKERR = 0x08u << c_SCB_CFSR_BUSFAULT_SHIFT; // bus fault on unstacking public const uint c_SCB_CFSR_BUSFAULT_STKERR = 0x10u << c_SCB_CFSR_BUSFAULT_SHIFT; // bus fault on stacking public const uint c_SCB_CFSR_MEMFAULT_LSPERR = 0x20u << c_SCB_CFSR_MEMFAULT_SHIFT; // fault on lazy state preservation public const uint c_SCB_CFSR_BUSFAULT_BFARVALID = 0x80u << c_SCB_CFSR_BUSFAULT_SHIFT; public const int c_SCB_CFSR_USGFAULT_SHIFT = 16; public const uint c_SCB_CFSR_USGFAULT_MASK = 0xFFFFu << c_SCB_CFSR_USGFAULT_SHIFT; public const uint c_SCB_CFSR_USGFAULT_UNDEFINSTR = 0x0001u << c_SCB_CFSR_USGFAULT_SHIFT; // undefined instruction public const uint c_SCB_CFSR_USGFAULT_INVSTATE = 0x0002u << c_SCB_CFSR_USGFAULT_SHIFT; // instruction makes illegal use of the EPSR public const uint c_SCB_CFSR_USGFAULT_INVPC = 0x0004u << c_SCB_CFSR_USGFAULT_SHIFT; // illegal load of EXC_RETURN to the PC, as a result of an invalid context, or an invalid EXC_RETURN value public const uint c_SCB_CFSR_USGFAULT_NOPC = 0x0008u << c_SCB_CFSR_USGFAULT_SHIFT; // coprocessor access public const uint c_SCB_CFSR_USGFAULT_UNALIGNED = 0x0100u << c_SCB_CFSR_USGFAULT_SHIFT; // unaligned access public const uint c_SCB_CFSR_USGFAULT_DIVBYZERO = 0x0200u << c_SCB_CFSR_USGFAULT_SHIFT; // divide by zero public const uint c_COREDEBUG_DHCSR_CONNECTED = 0x00000001; #endregion //--// // // Helper methods // public override void InitializeProcessor( ) { // // We want to run ISRs in privileged Handler mode using the Main Stack Pointer and all the other tasks // in privileged Thread mode using the Process Stack Pointer. // // We will assume that native context switching is possible when processor initialization is carried out in // Handler/Privileged mode. Of course that is not a complete guarantee. After carrying out the initialization of the // idle thread task, we will let the initialization thread return to thread mode upon first context switch as per classic // technique mentioned below, from ARM reference manual. As switching the mode is carried out naturally by // setting the appropriate flag, there is nothing else we need to do at initialization time. See context switch code // in thread manager as well. // // From ARMv-7M Architecture Reference Manual. // // // By default, Thread mode uses the MSP. To switch the stack pointer used in Thread mode to the // PSP, either: // - use the MSR instruction to set the Active stack pointer bit to 1 // - perform an exception return to Thread mode with the appropriate EXC_RETURN value // ////// ////// ////// ////// Table 2-17 Exception return behavior ////// ////// EXC_RETURN Description ////// ========================================================================= ////// 0xFFFFFF[F|E]1 Return to Handler mode. ////// Exception return gets state [and FP state] from the main ////// stack (MSP). ////// Execution uses MSP after return. ////// ////// 0xFFFFFF[F|E]9 Return to Thread mode. ////// Exception Return get state [and FP state] from the main ////// stack (MSP). ////// Execution uses MSP after return. ////// ////// 0xFFFFFF[F|E]D Return to Thread mode. ////// Exception return gets state [and FP state] from the process ////// stack (PSP). ////// Execution uses PSP after return. ////// ////// All other values Reserved. ////// // // Disable interrupts, but not faults // DisableInterrupts( ); // // Ensure privileged Handler mode to boot // if(!VerifyHandlerMode( )) { RT.BugCheck.Log( "Cannot bootstrap in Thread mode" ); RT.BugCheck.Assert( false, RT.BugCheck.StopCode.FailedBootstrap ); } // // Enforce reset behavior: // - only enabled interrupts or events can wakeup the processor, disabled interrupts are excluded // - sleep by turning off clock to main proc (not deep) // - do not sleep when returning to thread mode // SetSystemControlRegister( c_SCR__SLEEPONEXIT__NO_SLEEP | c_SCR__SLEEPDEEP__SLEEP | c_SCR__SEVONPEND__ENONLY ); // Enforce 8 bytes alignment // SetCCR( c_CCR_STD_CONFIG_4 ); // // Enable system exceptions we intercept // EnableSystemHandler( IRQn_Type.HardFault_IRQn ); EnableSystemHandler( IRQn_Type.BusFault_IRQn ); EnableSystemHandler( IRQn_Type.MemoryManagement_IRQn ); EnableSystemHandler( IRQn_Type.UsageFault_IRQn ); } //--// // // Cache // public override UIntPtr GetCacheableAddress( UIntPtr ptr ) { // Cortex-M7 actually has a cache, so override the method return ptr; } public override UIntPtr GetUncacheableAddress( UIntPtr ptr ) { // Cortex-M7 actually has a cache, so override the method return ptr; } public override void FlushCacheLine( UIntPtr target ) { } //--// [Inline] public override bool AreInterruptsDisabled( ) { return (GetBasePriRegister( ) <= c_Priority__Highest); } [Inline] public override bool AreFaultsDisabled( ) { uint faultmask = CMSIS_STUB_SCB__get_FAULTMASK( ); return (faultmask & c_FAULTMASK__FaultsOff) == c_FAULTMASK__FaultsOff; } public override bool AreAllInterruptsDisabled( ) { return AreInterruptsDisabled( ) && AreFaultsDisabled( ); } public override void Breakpoint( ) { Breakpoint( 0xa5a5a5a5 ); } //--// public static uint EnableInterrupts( ) { return DisableInterruptsWithPriorityLevelLowerOrEqualTo( c_Priority__Lowest ); } public static uint DisableInterrupts( ) { return DisableInterruptsWithPriorityLevelLowerOrEqualTo( c_Priority__Highest ); } public static uint EnableFaults( ) { uint faultmask = CMSIS_STUB_SCB__get_FAULTMASK(); CMSIS_STUB_SCB__Enable_Fault_Irq( ); return faultmask << 1; } public static uint DisableFaults( ) { uint faultmask = CMSIS_STUB_SCB__get_FAULTMASK( ); CMSIS_STUB_SCB__Disable_Fault_Irq( ); // since faults and interrupts have the same mask we need to differentiate return faultmask << 1; } public static uint EnableAllInterrupts( ) { return EnableInterrupts( ) | EnableFaults( ); } public static uint DisableAllInterrupts( ) { return DisableInterrupts( ) | DisableFaults( ); } public static uint DisableInterruptsWithPriorityLevelLowerOrEqualTo( uint basepri ) { return SetBasePriRegister( basepri ); } public static bool IsDebuggerConnected { get { return CUSTOM_STUB_DebuggerConnected( ) == c_COREDEBUG_DHCSR_CONNECTED; } } //--// [Inline] internal static uint GetBasePriRegister( ) { return CMSIS_STUB_SCB__get_BASEPRI( ); } [Inline] internal static uint SetBasePriRegister( uint basepri ) { return CMSIS_STUB_SCB__set_BASEPRI( basepri ); } internal static void RaiseSystemHandler( uint mask ) { BugCheck.Assert( ((mask & ~(c_ICSR__ALLOWED_MASK)) == 0), BugCheck.StopCode.IncorrectArgument ); CUSTOM_STUB_SCB_ICSR_RaiseSystemException( mask ); } public static unsafe void RaiseSupervisorCall( SVC_Code code ) { switch(code) { case SVC_Code.SupervisorCall__LongJump: CUSTOM_STUB_RaiseSupervisorCallForLongJump( ); break; case SVC_Code.SupervisorCall__StartThreads: CUSTOM_STUB_RaiseSupervisorCallForStartThreads( ); break; case SVC_Code.SupervisorCall__RetireThread: CUSTOM_STUB_RaiseSupervisorCallForRetireThread( ); break; case SVC_Code.SupervisorCall__SnapshotProcessModeRegisters: // // Cause a SVC call to transition to Handler mode and // snapshot the Processmode registers // CUSTOM_STUB_RaiseSupervisorCallForSnapshotProcessModeRegisters( ); break; default: throw new ArgumentException( "Request SVC does not exists or is not supported" ); } } public static bool IsAnyExceptionActive( ) { return (((ISR_NUMBER)CUSTOM_STUB_SCB_IPSR_GetCurrentISRNumber( )) != ISR_NUMBER.ThreadMode); } public static void InitiateContextSwitch( ) { RaiseSystemHandler( c_ICSR__PENDSTSET__SET ); } public static void CompleteContextSwitch( ) { RaiseSystemHandler( c_ICSR__PENDSVSET__SET ); } public static void WaitForEvent( ) { #if SPIN_ON_SLEEP while(true) { } #else CMSIS_STUB_POWER_WaitForEvent( ); #endif } public static void SendEvent( ) { CMSIS_STUB_POWER_SendEvent( ); } public static void WaitForInterrupt( ) { #if SPIN_ON_SLEEP while(true) { } #else CMSIS_STUB_POWER_WaitForInterrupt( ); #endif } protected abstract void RemapInterrupt( IRQn_Type IRQn, Action isr ); protected void SetSystemControlRegister( uint flags ) { CUSTOM_STUB_SCB_SCR_SetSystemControlRegister( flags ); } protected static bool VerifyHandlerMode( ) { uint control = CMSIS_STUB_SCB__get_CONTROL( ); return ((control & c_CONTROL__SPSEL_MASK) == c_CONTROL__SPSEL_MSP); } protected static void EnableSystemHandler( IRQn_Type ex ) { BugCheck.Assert( (ex < 0), BugCheck.StopCode.IncorrectArgument ); uint mask = 0; switch(ex) { case IRQn_Type.DebugMonitor_IRQn: // Not implemented, we should never do this BugCheck.Assert( false, BugCheck.StopCode.IllegalMode ); break; case IRQn_Type.PendSV_IRQn: case IRQn_Type.SysTick_IRQn: // Should use NVIC for this ones BugCheck.Assert( false, BugCheck.StopCode.IncorrectArgument ); break; case IRQn_Type.Reset_IRQn : case IRQn_Type.NonMaskableInt_IRQn: case IRQn_Type.SVCall_IRQn : case IRQn_Type.HardFault_IRQn : // always enabled break; case IRQn_Type.MemoryManagement_IRQn: mask = c_SHCSR__MEMFAULTENA__ENABLE; break; case IRQn_Type.BusFault_IRQn: mask = c_SHCSR__BUSFAULTENA__ENABLE; break; case IRQn_Type.UsageFault_IRQn: mask = c_SHCSR__USGFAULTENA__ENABLE; break; default: BugCheck.Assert( false, BugCheck.StopCode.IncorrectArgument ); break; } CUSTOM_STUB_SCB_SHCRS_EnableSystemHandler( mask ); } protected static void DisableSystemHandler( IRQn_Type ex ) { BugCheck.Assert( (ex < 0), BugCheck.StopCode.IncorrectArgument ); uint mask = 0; switch(ex) { case IRQn_Type.Reset_IRQn: case IRQn_Type.NonMaskableInt_IRQn: case IRQn_Type.HardFault_IRQn: // Cannot enable or disable NMI, Reset or HardFault //BugCheck.Assert( false, BugCheck.StopCode.IllegalMode ); break; case IRQn_Type.SVCall_IRQn: case IRQn_Type.DebugMonitor_IRQn: // Not implemented, we should never do this //BugCheck.Assert( false, BugCheck.StopCode.IllegalMode ); break; case IRQn_Type.PendSV_IRQn: case IRQn_Type.SysTick_IRQn: // NOT IMPLEMENTED: call NVIC //BugCheck.Assert( false, BugCheck.StopCode.IncorrectArgument ); break; case IRQn_Type.MemoryManagement_IRQn: mask = c_SHCSR__MEMFAULTENA__DISABLE; break; case IRQn_Type.BusFault_IRQn: mask = c_SHCSR__BUSFAULTENA__DISABLE; break; case IRQn_Type.UsageFault_IRQn: mask = c_SHCSR__USGFAULTENA__DISABLE; break; default: BugCheck.Assert( false, BugCheck.StopCode.IncorrectArgument ); break; } CUSTOM_STUB_SCB_SHCRS_DisableSystemHandler( mask ); } //--// private static void SetCCR( uint val ) { // NOTE: LWIP uses memory functions on addresses which are not 8 byte aligned // This prevents faults from occurring from those memory accesses CUSTOM_STUB_SCB_set_CCR( val ); } #region Native methods helpers // // We will implement the intrernal methods below with CMSIS-Core or custom stubs // [DllImport( "C" )] internal static extern uint CUSTOM_STUB_DebuggerConnected( ); [DllImport( "C" )] internal static extern uint CUSTOM_STUB_GetProgramCounter( ); [DllImport( "C" )] internal static extern uint CUSTOM_STUB_SCB__get_HFSR( ); [DllImport( "C" )] internal static extern uint CUSTOM_STUB_SCB__get_CFSR( ); [DllImport( "C" )] internal static extern uint CUSTOM_STUB_SCB__get_MMFAR( ); [DllImport( "C" )] internal static extern uint CUSTOM_STUB_SCB__get_BFAR( ); [DllImport( "C" )] internal static extern uint CMSIS_STUB_SCB__get_CONTROL( ); [DllImport( "C" )] internal static extern void CMSIS_STUB_SCB__set_CONTROL( uint control ); [DllImport( "C" )] internal static extern uint CMSIS_STUB_SCB__get_IPSR( ); [DllImport( "C" )] internal static extern uint CMSIS_STUB_SCB__get_APSR( ); [DllImport( "C" )] internal static extern uint CMSIS_STUB_SCB__get_xPSR( ); [DllImport( "C" )] internal static extern uint CMSIS_STUB_SCB__get_PSP( ); [DllImport( "C" )] internal static extern void CMSIS_STUB_SCB__set_PSP( uint topOfProcStack ); [DllImport( "C" )] internal static unsafe extern void* CMSIS_STUB_SCB__get_MSP_ResetValue( ); [DllImport( "C" )] internal static extern uint CMSIS_STUB_SCB__get_MSP_StackSize( ); [DllImport( "C" )] internal static extern uint CMSIS_STUB_SCB__get_MSP( ); [DllImport( "C" )] internal static extern void CMSIS_STUB_SCB__set_MSP( uint topOfMainStack ); [DllImport( "C" )] internal static extern uint CMSIS_STUB_SCB__get_PRIMASK( ); [DllImport( "C" )] internal static extern void CMSIS_STUB_SCB__set_PRIMASK( uint priMask ); [DllImport( "C" )] internal static extern void CMSIS_STUB_SCB__Enable_Irq( ); [DllImport( "C" )] internal static extern void CMSIS_STUB_SCB__Disable_Irq( ); // // !!! Cortex M3/4 only !!! // [DllImport( "C" )] internal static extern void CMSIS_STUB_SCB__Enable_Fault_Irq( ); [DllImport( "C" )] internal static extern void CMSIS_STUB_SCB__Disable_Fault_Irq( ); [DllImport( "C" )] internal static extern uint CMSIS_STUB_SCB__get_BASEPRI( ); [DllImport( "C" )] internal static extern uint CMSIS_STUB_SCB__set_BASEPRI( uint basePri ); [DllImport( "C" )] internal static extern uint CMSIS_STUB_SCB__get_FAULTMASK( ); [DllImport( "C" )] internal static extern void CMSIS_STUB_SCB__set_FAULTMASK( uint faultMask ); [DllImport( "C" )] internal static extern void CUSTOM_STUB_SCB_set_CCR( uint value ); [DllImport( "C" )] internal static extern void CUSTOM_STUB_SCB_SHCRS_EnableSystemHandler( uint ex ); [DllImport( "C" )] internal static extern void CUSTOM_STUB_SCB_SHCRS_DisableSystemHandler( uint ex ); [DllImport( "C" )] internal static extern void CUSTOM_STUB_SCB_ICSR_RaiseSystemException( uint ex ); [DllImport( "C" )] internal static extern void CUSTOM_STUB_RaiseSupervisorCallForLongJump( ); [DllImport( "C" )] internal static extern void CUSTOM_STUB_RaiseSupervisorCallForStartThreads( ); [DllImport( "C" )] internal static extern void CUSTOM_STUB_RaiseSupervisorCallForRetireThread( ); [DllImport( "C" )] internal static extern void CUSTOM_STUB_RaiseSupervisorCallForSnapshotProcessModeRegisters( ); [DllImport( "C" )] internal static extern void CUSTOM_STUB_SetExcReturn( uint ret ); [DllImport( "C" )] internal static extern int CUSTOM_STUB_SCB_IPSR_GetCurrentISRNumber( ); [DllImport( "C" )] internal static extern int CUSTOM_STUB_SCB_SCR_GetSystemControlRegister( ); [DllImport( "C" )] internal static extern void CUSTOM_STUB_SCB_SCR_SetSystemControlRegister( uint scr ); [DllImport( "C" )] internal static extern void CMSIS_STUB_POWER_WaitForEvent( ); [DllImport( "C" )] internal static extern void CMSIS_STUB_POWER_SendEvent( ); [DllImport( "C" )] internal static extern void CMSIS_STUB_POWER_WaitForInterrupt( ); //--// [DllImport( "C" )] internal static extern unsafe uint* CUSTOM_STUB_FetchSoftwareFrameSnapshot( ); //--// //--// //--// // // Utility methods // [TS.WellKnownMethod( "ProcessorARMv7_Breakpoint" )] [DllImport( "C" )] public static extern void Breakpoint( uint value ); #endregion } } ================================================ FILE: Zelig/Zelig/RunTime/Zelig/Kernel/HardwareModel/TargetPlatform/ARMv7/ProcessorARMv7MForLlvm.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // //#define SPIN_ON_SLEEP namespace Microsoft.Zelig.Runtime.TargetPlatform.ARMv7 { using System; using System.Runtime.InteropServices; using TS = Microsoft.Zelig.Runtime.TypeSystem; using EncDef = Microsoft.Zelig.TargetModel.ArmProcessor.EncodingDefinition_ARM; using RT = Microsoft.Zelig.Runtime; using ARMv4; using TargetModel.ArmProcessor; public abstract partial class ProcessorARMv7MForLlvm : ProcessorARMv7M { public struct StandardFrame { public UIntPtr R0; public UIntPtr R1; public UIntPtr R2; public UIntPtr R3; public UIntPtr R12; public UIntPtr LR; public UIntPtr PC; public UIntPtr PSR; } //--// [TS.WellKnownType( "Microsoft_Zelig_ARMv7ForLlvm_MethodWrapper" )] public sealed class MethodWrapperLlvm : AbstractMethodWrapper { [Inline] [DisableNullChecks( ApplyRecursively = true )] public override void Prologue( string typeFullName, string methodFullName, TS.MethodRepresentation.BuildTimeAttributes attribs ) { } [Inline] [DisableNullChecks( ApplyRecursively = true )] public unsafe override void Prologue( string typeFullName, string methodFullName, TS.MethodRepresentation.BuildTimeAttributes attribs, HardwareException he ) { } [Inline] [DisableNullChecks( ApplyRecursively = true )] public override void Epilogue( string typeFullName, string methodFullName, TS.MethodRepresentation.BuildTimeAttributes attribs ) { } [Inline] [DisableNullChecks( ApplyRecursively = true )] public unsafe override void Epilogue( string typeFullName, string methodFullName, TS.MethodRepresentation.BuildTimeAttributes attribs, HardwareException he ) { } } // // Helper Methods // //--// [DllImport( "C" )] public static extern void Nop( ); //--// [Inline] internal static unsafe UIntPtr GetMainStackPointerAtReset( ) { return new UIntPtr( CMSIS_STUB_SCB__get_MSP_ResetValue( ) ); } internal static UIntPtr GetMainStackPointerBottom( ) { UIntPtr stackBottom = AddressMath.Decrement(GetMainStackPointerAtReset(), GetMainStackSize()); return stackBottom; } [Inline] internal static uint GetMainStackSize( ) { return CMSIS_STUB_SCB__get_MSP_StackSize( ); } [Inline] internal static UIntPtr GetMainStackPointer( ) { return new UIntPtr( CMSIS_STUB_SCB__get_MSP( ) ); } [Inline] internal static void SetMainStackPointer( UIntPtr topOfMainStack ) { CMSIS_STUB_SCB__set_MSP( topOfMainStack.ToUInt32( ) ); } [Inline] internal static UIntPtr GetProcessStackPointer( ) { return new UIntPtr( CMSIS_STUB_SCB__get_PSP( ) ); } [Inline] internal static void SetProcessStackPointer( UIntPtr topOfProcessStack ) { CMSIS_STUB_SCB__set_PSP( topOfProcessStack.ToUInt32( ) ); } protected static void SwitchToHandlerPrivilegedMode( ) { uint control = CMSIS_STUB_SCB__get_CONTROL( ); control &= ~c_CONTROL__MASK; control |= c_CONTROL__MODE__HNDLR; CMSIS_STUB_SCB__set_CONTROL( control & c_CONTROL__MASK ); } protected static void SwitchToThreadUnprivilegedMode( ) { uint control = CMSIS_STUB_SCB__get_CONTROL( ); control &= ~c_CONTROL__MASK; control |= c_CONTROL__MODE__THRD_UNPRIV; CMSIS_STUB_SCB__set_CONTROL( control & c_CONTROL__MASK ); } protected static void SwitchToThreadPrivilegedMode( ) { uint control = CMSIS_STUB_SCB__get_CONTROL( ); control &= ~c_CONTROL__MASK; control |= c_CONTROL__MODE__THRD_PRIV; CMSIS_STUB_SCB__set_CONTROL( control & c_CONTROL__MASK ); } protected static void SwitchToPrivilegedMode( ) { uint control = CMSIS_STUB_SCB__get_CONTROL( ); control &= ~c_CONTROL__MASK_PRIVILEGE; control |= c_CONTROL__nPRIV_PRIV; CMSIS_STUB_SCB__set_CONTROL( control & c_CONTROL__MASK ); } protected static void SwitchToUnprivilegedMode( ) { uint control = CMSIS_STUB_SCB__get_CONTROL( ); control &= ~c_CONTROL__MASK_PRIVILEGE; control |= c_CONTROL__nPRIV_UNPRIV; CMSIS_STUB_SCB__set_CONTROL( control & c_CONTROL__MASK ); } internal static void SetExcReturn( uint ret ) { CUSTOM_STUB_SetExcReturn( ret ); } //--// #region Fault handlers helpers // // Fault diagnostic // protected static bool WasHardFaultForced( ) { return (CUSTOM_STUB_SCB__get_HFSR( ) & c_SCB_HFSR_FORCED_FORCED) == c_SCB_HFSR_FORCED_FORCED; } protected static bool WasHardFaultOnVectorTableRead( ) { return (CUSTOM_STUB_SCB__get_HFSR( ) & c_SCB_HFSR_VECTTBL_READ) == c_SCB_HFSR_VECTTBL_READ; } protected static bool IsMemFaultAddressValid( ) { return (CUSTOM_STUB_SCB__get_CFSR( ) & c_SCB_CFSR_MEMFAULT_MMFARVALID) == c_SCB_CFSR_MEMFAULT_MMFARVALID; } protected static bool IsBusFaultAddressValid( ) { return (CUSTOM_STUB_SCB__get_CFSR( ) & c_SCB_CFSR_BUSFAULT_BFARVALID) == c_SCB_CFSR_BUSFAULT_BFARVALID; } protected static bool IsBusFaultAddressPrecise( ) { return (CUSTOM_STUB_SCB__get_CFSR( ) & c_SCB_CFSR_BUSFAULT_PRECISERR) == c_SCB_CFSR_BUSFAULT_PRECISERR; } protected static uint GetProgramCounter( ) { return CUSTOM_STUB_GetProgramCounter( ); } //--// [RT.Inline] protected static unsafe StandardFrame* PointerToStdFrame( UIntPtr SP ) { return (StandardFrame*)SP.ToPointer( ); } /// /// Hard Fault handler. /// protected static void HandleHardFault( ) { if(IsDebuggerConnected) { if(WasHardFaultOnVectorTableRead( )) { BugCheck.Raise( BugCheck.StopCode.Fault_Vectors ); } if(WasHardFaultForced( )) { BugCheck.Raise( BugCheck.StopCode.ForcedHardFault ); } // TODO BugCheck.Raise( BugCheck.StopCode.Fault_Unknown ); } else { while(true) { Peripherals.Instance.WaitForInterrupt( ); } } } /// /// Detects memory access violations to regions that are defined in the Memory Management Unit (MPU). /// For example code execution from a memory region with read/write access only. /// protected static void HandleMemoryAccessFault( ref StandardFrame registers ) { uint CFSR = CUSTOM_STUB_SCB__get_CFSR( ); BugCheck.Log( "CFSR =0x%08x", (int)CFSR ); BugCheck.Log( "MMFAR=0x%08x", (int)CUSTOM_STUB_SCB__get_MMFAR( ) ); BugCheck.Log( "PC =0x%08x", (int)registers.PC.ToUInt32( ) ); if((CFSR & c_SCB_CFSR_MEMFAULT_MSTKERR) != 0) { BugCheck.Log( "Memory access fault on exception entry" ); } if((CFSR & c_SCB_CFSR_MEMFAULT_MUNSTKERR) != 0) { BugCheck.Log( "Memory access fault on exception exit" ); } if((CFSR & c_SCB_CFSR_MEMFAULT_DACCVIOL) != 0) { BugCheck.Log( "Data access violation" ); } if((CFSR & c_SCB_CFSR_MEMFAULT_IACCVIOL) != 0) { BugCheck.Log( "Instruction access violation" ); } if(IsMemFaultAddressValid( )) { BugCheck.Log( "Mem Fault Address=0x%08x", (int)CUSTOM_STUB_SCB__get_MMFAR( ) ); Breakpoint( CUSTOM_STUB_SCB__get_MMFAR( ) ); } else { BugCheck.Log( "Invalid Mem Fault Address" ); Breakpoint( CFSR ); } } /// /// Detects memory access errors on instruction fetch, data read/write, interrupt vector fetch, and /// register stacking (save/restore) on interrupt (entry/exit). /// protected static void HandleBusFault( ref StandardFrame registers ) { uint CFSR = CUSTOM_STUB_SCB__get_CFSR( ); BugCheck.Log( "CFSR=0x%08x", (int)CFSR ); BugCheck.Log( "BFAR=0x%08x", (int)CUSTOM_STUB_SCB__get_BFAR( ) ); BugCheck.Log( "PC =0x%08x", (int)registers.PC.ToUInt32( ) ); if((CFSR & c_SCB_CFSR_BUSFAULT_STKERR) != 0) { BugCheck.Log( "Stacking error on entry" ); } if((CFSR & c_SCB_CFSR_BUSFAULT_UNSTKERR) != 0) { BugCheck.Log( "Stacking error on exit" ); } if((CFSR & c_SCB_CFSR_BUSFAULT_IBUSERR) != 0) { BugCheck.Log( "Prefetch abort" ); } if(IsBusFaultAddressValid( ) && IsBusFaultAddressPrecise( )) { BugCheck.Log( "Bus Fault Address=0x%08x", (int)CUSTOM_STUB_SCB__get_BFAR( ) ); Breakpoint( CUSTOM_STUB_SCB__get_BFAR( ) ); } else { BugCheck.Log( "Invalid or imprecise Bus Fault Address" ); Breakpoint( CFSR ); } } /// /// Detects execution of undefined instructions, unaligned memory access for load/store multiple. /// When enabled, divide-by-zero and other unaligned memory accesses are also detected. /// protected static void HandleUsageFault( ref StandardFrame registers ) { uint CFSR = CUSTOM_STUB_SCB__get_CFSR( ); BugCheck.Log( "CFSR=0x%08x", (int)CFSR ); BugCheck.Log( "PC =0x%08x", (int)registers.PC.ToUInt32( ) ); if((CFSR & c_SCB_CFSR_USGFAULT_DIVBYZERO) != 0) { BugCheck.Log( "Divide by zero" ); } if((CFSR & c_SCB_CFSR_USGFAULT_UNALIGNED) != 0) { BugCheck.Log( "Unaligned access" ); } if((CFSR & c_SCB_CFSR_USGFAULT_INVPC) != 0) { BugCheck.Log( "Invalid PC load on EXC_RETURN" ); } if((CFSR & c_SCB_CFSR_USGFAULT_NOPC) != 0) { BugCheck.Log( "No coprocessor" ); } if((CFSR & c_SCB_CFSR_USGFAULT_INVSTATE) != 0) { BugCheck.Log( "Illegal use of the EPSR" ); } if((CFSR & c_SCB_CFSR_USGFAULT_UNDEFINSTR) != 0) { BugCheck.Log( "Undefined instruction" ); } } #endregion #region Fault handlers /// /// Hard Fault is caused by Bus Fault, Memory Management Fault, or Usage Fault if their handler /// cannot be executed. /// [RT.CapabilitiesFilter( RequiredCapabilities = TargetModel.ArmProcessor.InstructionSetVersion.Platform_Version__ARMv7M )] [RT.HardwareExceptionHandler( RT.HardwareException.Fault )] [RT.ExportedMethod] private static void Zelig_Exception_HardFault_Handler( uint sp ) { HandleHardFault( ); } [RT.CapabilitiesFilter( RequiredCapabilities = TargetModel.ArmProcessor.InstructionSetVersion.Platform_Version__ARMv7M )] [RT.HardwareExceptionHandler( RT.HardwareException.Fault )] [RT.ExportedMethod] private static unsafe void Zelig_Exception_MemManage_Handler( uint sp ) { StandardFrame* regs = PointerToStdFrame( new UIntPtr( sp ) ); HandleMemoryAccessFault( ref *regs ); } [RT.CapabilitiesFilter( RequiredCapabilities = TargetModel.ArmProcessor.InstructionSetVersion.Platform_Version__ARMv7M )] [RT.HardwareExceptionHandler( RT.HardwareException.Fault )] [RT.ExportedMethod] private static unsafe void Zelig_Exception_UsageFault_Handler( uint sp ) { StandardFrame* regs = PointerToStdFrame( new UIntPtr( sp ) ); HandleUsageFault( ref *regs ); } [RT.CapabilitiesFilter( RequiredCapabilities = TargetModel.ArmProcessor.InstructionSetVersion.Platform_Version__ARMv7M )] [RT.HardwareExceptionHandler( RT.HardwareException.Fault )] [RT.ExportedMethod] private static unsafe void Zelig_Exception_BusFault_Handler( uint sp ) { StandardFrame* regs = PointerToStdFrame( new UIntPtr( sp ) ); HandleBusFault( ref *regs ); } #endregion } } ================================================ FILE: Zelig/Zelig/RunTime/Zelig/Kernel/HardwareModel/TargetPlatform/ARMv7/ProcessorARMv7MForLlvm_ContextSwitch.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // #define SPIN_ON_SLEEP //#define DEBUG_CTX_SWITCH //#define DEBUG_CTX_FRAME_SNAPSHOT using System.Runtime.InteropServices; namespace Microsoft.Zelig.Runtime.TargetPlatform.ARMv7 { using System; using EncDef = Microsoft.Zelig.TargetModel.ArmProcessor.EncodingDefinition; using TS = Microsoft.Zelig.Runtime.TypeSystem; using RT = Microsoft.Zelig.Runtime; public abstract partial class ProcessorARMv7MForLlvm { //--// // // Part of Context may be defined in the model for the targeted sub-system, e.g. Mbed or CMSIS-Core for ARM processors // public abstract new class Context : Processor.Context { [StructLayout( LayoutKind.Sequential, Pack = 4 )] public struct SoftwareFrame { [TS.AssumeReferenced] public uint EXC_RETURN; [TS.AssumeReferenced] public uint CONTROL; [TS.AssumeReferenced] public UIntPtr R4; [TS.AssumeReferenced] public UIntPtr R5; [TS.AssumeReferenced] public UIntPtr R6; [TS.AssumeReferenced] public UIntPtr R7; [TS.AssumeReferenced] public UIntPtr R8; [TS.AssumeReferenced] public UIntPtr R9; [TS.AssumeReferenced] public UIntPtr R10; [TS.AssumeReferenced] public UIntPtr R11; }; [StructLayout( LayoutKind.Sequential, Pack = 4 )] public struct HardwareFrame { [TS.AssumeReferenced] public UIntPtr R0; [TS.AssumeReferenced] public UIntPtr R1; [TS.AssumeReferenced] public UIntPtr R2; [TS.AssumeReferenced] public UIntPtr R3; [TS.AssumeReferenced] public UIntPtr R12; [TS.AssumeReferenced] public UIntPtr LR; [TS.AssumeReferenced] public UIntPtr PC; [TS.AssumeReferenced] public UIntPtr PSR; }; [StructLayout( LayoutKind.Sequential, Pack = 4 )] public struct RegistersOnStack { public const uint StackRegister = EncDef.c_register_sp; public const uint LinkRegister = EncDef.c_register_lr; public const uint ProgramCounterRegister = EncDef.c_register_pc; // // State // // SW stack frame: pushed by PendSV_Handler public SoftwareFrame SoftwareFrameRegisters; // HW stack frame: pushed upon entering PendSV_Handler public HardwareFrame HardwareFrameRegisters; // // Helper Methods // public static unsafe uint TotalFrameSize { [RT.Inline] get { return HWFrameSize + SwitcherFrameSize; } } public static unsafe uint HWFrameSize { [RT.Inline] get { return (uint)sizeof( HardwareFrame ); } } public static unsafe uint SwitcherFrameSize { [RT.Inline] get { return (uint)sizeof( SoftwareFrame ); } } //--// public UIntPtr GetRegisterValue( uint idx ) { switch(idx) { case 0: return HardwareFrameRegisters.R0; case 1: return HardwareFrameRegisters.R1; case 2: return HardwareFrameRegisters.R2; case 3: return HardwareFrameRegisters.R3; case 4: return SoftwareFrameRegisters.R4; case 5: return SoftwareFrameRegisters.R5; case 6: return SoftwareFrameRegisters.R6; case 7: return SoftwareFrameRegisters.R7; case 8: return SoftwareFrameRegisters.R8; case 9: return SoftwareFrameRegisters.R9; case 10: return SoftwareFrameRegisters.R10; case 11: return SoftwareFrameRegisters.R11; case 12: return HardwareFrameRegisters.R12; case 14: return HardwareFrameRegisters.LR; case 15: return HardwareFrameRegisters.PC; } return UIntPtr.Zero; } } //--// // // This is the pointer to the base of the stack. Useful for stack walking. // protected UIntPtr BaseSP; // // This is the pointer to the last known position of the stack pointer // For a long jump this points to the end of the SW context to install // protected UIntPtr SP; // // Return value for mode transitions // protected uint EXC_RETURN; //--// public Context(RT.ThreadImpl owner) : base(owner) { } // // Overrides // public override unsafe void SwitchTo( ) { // // The long jump selects the current thread's context and sets its EXC_RETURN value // ProcessorARMv7MForLlvm.RaiseSupervisorCall( SVC_Code.SupervisorCall__LongJump ); #if DEBUG_CTX_SWITCH BugCheck.Log( "!!!!!!!!!!!!!!!!!!!!! ERROR !!!!!!!!!!!!!!!!!!!!!!!" ); BugCheck.Log( "!!! Back after Long Jump after, Ctx Switch Failed !!!" ); BugCheck.Log( "!!!!!!!!!!!!!!!!!!!!! ERROR !!!!!!!!!!!!!!!!!!!!!!!" ); #endif RT.BugCheck.Assert( false, BugCheck.StopCode.IllegalMode ); } public override void Populate( ) { // // This would be called on the throw context, but in ARMv7M we do not have one // ThreadImpl thisThread = ThreadImpl.CurrentThread; Processor.Context ctx = thisThread.SwappedOutContext; this.BaseSP = ctx.BaseStackPointer; this.SP = GetProcessStackPointer(); this.EXC_RETURN = ctx.ExcReturn; } public override void Populate( Processor.Context context ) { this.BaseSP = context.BaseStackPointer; this.SP = context.StackPointer; this.EXC_RETURN = context.ExcReturn; } public unsafe override void PopulateFromDelegate( Delegate dlg, uint[] stack ) { DelegateImpl dlgImpl = (DelegateImpl)(object)dlg; ArrayImpl stackImpl = (ArrayImpl )(object)stack; ObjectImpl objImpl = (ObjectImpl )(object)dlg.Target; // // Save the initial stack pointer // In the general case the SP will be at the top of the current frame we are building // When we do a LongJump though, or we start the thread first, we will have to use the base stack pointer // this.BaseSP = AddressMath.AlignToLowerBoundary( new UIntPtr( stackImpl.GetEndDataPointer( ) ), 8 ); this.SP = AddressMath.Decrement( this.BaseSP, RegistersOnStack.TotalFrameSize ); this.EXC_RETURN = c_MODE_RETURN__THREAD_PSP; // // Initial SP must still be within the stack array // RT.BugCheck.Assert( stackImpl.GetDataPointer( ) <= this.SP.ToPointer( ), BugCheck.StopCode.StackCorruptionDetected ); RegistersOnStack* firstFrame = GetFrame(this.SP); // // build the first stack frame // firstFrame->HardwareFrameRegisters.PC = new UIntPtr( dlgImpl.InnerGetCodePointer( ).Target.ToPointer( ) ); firstFrame->HardwareFrameRegisters.PSR = new UIntPtr( c_psr_InitialValue ); firstFrame->SoftwareFrameRegisters.EXC_RETURN = c_MODE_RETURN__THREAD_PSP; firstFrame->SoftwareFrameRegisters.CONTROL = c_CONTROL__MODE__THRD_PRIV; firstFrame->HardwareFrameRegisters.R0 = objImpl.ToPointer( ); #if DEBUG_CTX_SWITCH RT.BugCheck.Log( "[PFD-ctx] EXC=0x%08x, PSR=0x%08x, PC=0x%08x, R0=0x%08x, SP(aligned)=0x%08x", (int)firstFrame->SoftwareFrameRegisters.EXC_RETURN, (int)firstFrame->HardwareFrameRegisters.PSR.ToUInt32( ), (int)firstFrame->HardwareFrameRegisters.PC.ToUInt32( ), (int)firstFrame->HardwareFrameRegisters.R0.ToUInt32( ), (int)this.SP.ToUInt32( ) ); RT.BugCheck.Log( "[PFD-stackImpl] SP(start)=0x%08x, SP(end)=0x%08x, SP(length)=0x%08x, SP(offset)=0x%08x", (int)( stackImpl.GetDataPointer( ) ), (int)( stackImpl.GetEndDataPointer( ) ), (int)( stackImpl.GetEndDataPointer( ) - stackImpl.GetDataPointer( ) ), (int)( (int)stackImpl.GetEndDataPointer( ) - this.SP.ToUInt32( ) ) ); #endif } public override void SetupForExceptionHandling( uint mode ) { // // Stop any exception from happening // using(Runtime.SmartHandles.InterruptState.DisableAll()) { // // Retrieve the MSP< which we will use to handle exceptions // UIntPtr stack = GetMainStackPointer(); //// //// Enter target mode, with interrupts disabled. //// //SwitchToHandlerPrivilegedMode( ); // // Set the stack pointer in the context to be the current MSP // this.BaseSP = GetMainStackPointerAtReset(); this.SP = stack; this.EXC_RETURN = c_MODE_RETURN__THREAD_MSP; //// //// Switch back to original mode //// //SwitchToThreadUnprivilegedMode( ); } } #region Tracking Collector and Exceptions public override bool Unwind( ) { throw new Exception( "Unwind not implemented" ); } public override UIntPtr GetRegisterByIndex( uint idx ) { return Snapshot.GetRegisterValue( idx ); } public override unsafe void SetRegisterByIndex( uint idx, UIntPtr value ) { BugCheck.Assert( false, BugCheck.StopCode.InvalidOperation ); } #endregion private static UIntPtr ContextSwitch( ThreadManager tm, UIntPtr stackPointer ) { ThreadImpl currentThread = tm.CurrentThread; ThreadImpl nextThread = tm.NextThread; Context ctx; #if DEBUG_CTX_SWITCH BugCheck.Log( "ContextSwitch from thread 0x%x to 0x%x", (int)ObjectHeader.Unpack( currentThread )?.ToPointer( ), (int)ObjectHeader.Unpack( nextThread ).ToPointer( ) ); #endif if(currentThread != null) { ctx = (Context)currentThread.SwappedOutContext; // // update SP as well as the EXC_RETURN address // unsafe { ctx.EXC_RETURN = GetFrame(stackPointer)->SoftwareFrameRegisters.EXC_RETURN; } ctx.StackPointer = stackPointer; } ctx = (Context)nextThread.SwappedOutContext; // // Pass EXC_RETURN down to the native portion of the // PendSV handler we need to offset to the beginning of the frame // SetExcReturn( ctx.EXC_RETURN ); // // Update thread manager state and Thread.CurrentThread static field // tm.CurrentThread = nextThread; ThreadImpl.CurrentThread = nextThread; return ctx.StackPointer; } //--// //--// //--// private static unsafe void FirstLongJump( ) { LongJump( ); } private static unsafe void LongJump( ) { // // Retrieve next context from ThreadManager // Context currentThreadCtx = (ProcessorARMv7MForLlvm.Context)ThreadManager.Instance.CurrentThread.SwappedOutContext; // // Set the PSP at R0 so that returning from the SVC handler will complete the work // SetProcessStackPointer( AddressMath.Increment( currentThreadCtx.StackPointer, ProcessorARMv7MForLlvm.Context.RegistersOnStack.SwitcherFrameSize ) ); SetExcReturn( currentThreadCtx.EXC_RETURN ); // // SWitch to unprivileged mode before jumping to our thread // This can only be enabled when we have a model for allowing tasks // to enable/disable interrupts // //ProcessorARMv7MForLlvm.SwitchToUnprivilegedMode( ); } private static unsafe void LongJumpForRetireThread( ) { LongJump( ); } // // Access Methods // public override UIntPtr StackPointer { get { return this.SP; } set { this.SP = value; } } public override UIntPtr BaseStackPointer { [RT.Inline] get { return this.BaseSP; } } public override uint ExcReturn { [RT.Inline] get { return this.EXC_RETURN; } [RT.Inline] set { this.EXC_RETURN = value; } } public override UIntPtr ProgramCounter { get { //return Registers.PC; return (UIntPtr)0; } set { //Registers.PC = value; } } public override uint ScratchedIntegerRegisters { get { return 0; } } //--// [RT.Inline] internal static unsafe Context.RegistersOnStack* GetFrame( UIntPtr SP ) { return (Context.RegistersOnStack*)SP.ToPointer( ); } private static unsafe void SnapshotActiveFrame( ref Context.RegistersOnStack frame ) { //// //// Can run in handler mode only //// //BugCheck.Assert( VerifyHandlerMode( ), BugCheck.StopCode.IllegalMode ); //// //// Retrieve PSP and snapshot the frame that was pushed by the SVC handler //// //UIntPtr psp = GetProcessStackPointer( ); //Context.RegistersOnStack* snapshot = GetFrame( psp ); //frame.HardwareFrameRegisters = snapshot->HardwareFrameRegisters; //frame.SoftwareFrameRegisters = snapshot->SoftwareFrameRegisters; } // // Helpers // [Inline] public static void InterruptHandlerWithContextSwitch( UIntPtr stackPointer ) { Peripherals.Instance.ProcessInterrupt( ); ThreadManager tm = ThreadManager.Instance; // We keep looping until the current and next threads are the same, because // when swapping out a dead thread, we might wake up a different thread. while(tm.ShouldContextSwitch) { ContextSwitch( tm, stackPointer ); } } [Inline] public static void InterruptHandlerWithoutContextSwitch( ) { Peripherals.Instance.ProcessInterrupt( ); } [Inline] public static void FastInterruptHandlerWithoutContextSwitch( ) { Peripherals.Instance.ProcessFastInterrupt( ); } [Inline] public static void GenericSoftwareInterruptHandler( ref RegistersOnStack registers ) { } //--// [Inline] private static unsafe void PrepareStackForException( uint mode, Context.RegistersOnStack* ptr ) { // // EXC_RETURN to go back to previous mode. // // TODO: // // Save unbanked R4 -R11. // // TODO: // // Switch back to the exception handling mode. // // TODO: // // R1 should point to the Register Context on the stack. // // TODO: //SetRegister( EncDef.c_register_r1, new UIntPtr( ptr ) ); } [Inline] private static unsafe void RestoreStackForException( uint mode, Context.RegistersOnStack* ptr ) { // // EXC_RETUNR to go back to previous mode. // // TODO: // // Save unbanked R4 -R11. // // TODO: // // Switch back to the exception handling mode. // // TODO: // // R1 should point to the Register Context on the stack. // // TODO: //SetRegister( EncDef.c_register_r1, new UIntPtr( ptr ) ); } // // All overridable exceptions for Ctx switch // [RT.CapabilitiesFilter( RequiredCapabilities = TargetModel.ArmProcessor.InstructionSetVersion.Platform_VFP__SoftVFP )] [RT.HardwareExceptionHandler( RT.HardwareException.Service )] [RT.ExportedMethod] private static unsafe void SVC_Handler_Zelig( uint* args ) { SVC_Code svc_number = (SVC_Code)((byte*)args[6])[-2]; // svc number is at stacked PC offset - 2 bytes switch(svc_number) { case SVC_Code.SupervisorCall__LongJump: LongJump( ); break; case SVC_Code.SupervisorCall__StartThreads: FirstLongJump( ); break; case SVC_Code.SupervisorCall__RetireThread: LongJumpForRetireThread( ); break; case SVC_Code.SupervisorCall__SnapshotProcessModeRegisters: UpdateFrame( ref ProcessorARMv7MForLlvm.Snapshot, CUSTOM_STUB_FetchSoftwareFrameSnapshot( ) ); break; default: BugCheck.Assert( false, BugCheck.StopCode.Impossible ); break; } } [RT.CapabilitiesFilter( RequiredCapabilities=TargetModel.ArmProcessor.InstructionSetVersion.Platform_VFP__SoftVFP )] [RT.HardwareExceptionHandler( RT.HardwareException.Interrupt )] [RT.ExportedMethod] private static UIntPtr PendSV_Handler_Zelig( UIntPtr stackPtr ) { using(RT.SmartHandles.InterruptState.Disable( )) { return ContextSwitch( ThreadManager.Instance, stackPtr ); } } // // Handles interrupts through the interrupts controller polling mechanism // (suitable for ARMv4/5 an for polling approach) // [RT.CapabilitiesFilter( RequiredCapabilities=TargetModel.ArmProcessor.InstructionSetVersion.Platform_VFP__SoftVFP )] [RT.HardwareExceptionHandler( RT.HardwareException.Interrupt )] [RT.ExportedMethod] private static void AnyInterrupt( UIntPtr stackPtr ) { using(RT.SmartHandles.InterruptState.Disable( )) { InterruptHandlerWithContextSwitch( stackPtr ); } } } // // Handles interrupts through the native platform direct invokation // [NoInline] [RT.DisableNullChecks] public static void ExclusiveAccessExceptionHandler( Action isr ) { using(RT.SmartHandles.InterruptState.Disable( )) { using(RT.SmartHandles.SwapCurrentThreadUnderInterrupt hnd = ThreadManager.InstallInterruptThread( )) { isr( ); } } } //--// // // State // public static Context.RegistersOnStack Snapshot; // // Helper methods // //--// [RT.CapabilitiesFilter( RequiredCapabilities=TargetModel.ArmProcessor.InstructionSetVersion.Platform_Version__ARMv7M )] [ExportedMethod] private static unsafe void CUSTOM_STUB_NotifySoftwareFrameSnapshot( void* frame, int size ) { BugCheck.Assert( size * sizeof( uint ) == Context.RegistersOnStack.TotalFrameSize, BugCheck.StopCode.StackCorruptionDetected ); uint* registers = (uint*)frame; UpdateFrame( ref Snapshot, registers ); } internal static unsafe void UpdateFrame( ref Context.RegistersOnStack snapshot, uint* registers ) { #if DEBUG_CTX_FRAME_SNAPSHOT BugCheck.Log( "[Last Active Frame] EXC=0x%08x, PSR=0x%08x, PC=0x%08x", (int)registers[ 0 ], (int)registers[ 17 ], (int)registers[ 16 ] ); BugCheck.Log( "[Last Active Frame] R0=0x%08x, R1=0x%08x, R2=0x%08x, R3=0x%08x, R12=0x%08x", (int)registers[ 10 ], (int)registers[ 11 ], (int)registers[ 12 ], (int)registers[ 13 ], (int)registers[ 14 ] ); BugCheck.Log( "[Last Active Frame] R4=0x%08x, R5=0x%08x, R6=0x%08x, R7=0x%08x", (int)registers[ 2 ], (int)registers[ 3 ], (int)registers[ 4 ], (int)registers[ 5 ] ); BugCheck.Log( "[Last Active Frame] R8=0x%08x, R9=0x%08x, R10=0x%08x, R11=0x%08x", (int)registers[ 6 ], (int)registers[ 7 ], (int)registers[ 8 ], (int)registers[ 9 ] ); #endif snapshot.SoftwareFrameRegisters.EXC_RETURN = registers[ 0 ]; snapshot.SoftwareFrameRegisters.CONTROL = registers[ 1 ]; snapshot.SoftwareFrameRegisters.R4 = new UIntPtr( registers[ 2 ] ); snapshot.SoftwareFrameRegisters.R5 = new UIntPtr( registers[ 3 ] ); snapshot.SoftwareFrameRegisters.R6 = new UIntPtr( registers[ 4 ] ); snapshot.SoftwareFrameRegisters.R7 = new UIntPtr( registers[ 5 ] ); snapshot.SoftwareFrameRegisters.R8 = new UIntPtr( registers[ 6 ] ); snapshot.SoftwareFrameRegisters.R9 = new UIntPtr( registers[ 7 ] ); snapshot.SoftwareFrameRegisters.R10 = new UIntPtr( registers[ 8 ] ); snapshot.SoftwareFrameRegisters.R11 = new UIntPtr( registers[ 9 ] ); //--// snapshot.HardwareFrameRegisters.R0 = new UIntPtr( registers[ 10 ] ); snapshot.HardwareFrameRegisters.R1 = new UIntPtr( registers[ 11 ] ); snapshot.HardwareFrameRegisters.R2 = new UIntPtr( registers[ 12 ] ); snapshot.HardwareFrameRegisters.R3 = new UIntPtr( registers[ 13 ] ); snapshot.HardwareFrameRegisters.R12 = new UIntPtr( registers[ 14 ] ); snapshot.HardwareFrameRegisters.LR = new UIntPtr( registers[ 15 ] ); snapshot.HardwareFrameRegisters.PC = new UIntPtr( registers[ 16 ] ); snapshot.HardwareFrameRegisters.PSR = new UIntPtr( registers[ 17 ] ); } } } ================================================ FILE: Zelig/Zelig/RunTime/Zelig/Kernel/HardwareModel/TargetPlatform/ARMv7_VFP/ProcessorARMv7MForLlvm_VFP.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // namespace Microsoft.Zelig.Runtime.TargetPlatform.ARMv7 { using System; using System.Runtime.InteropServices; public abstract partial class ProcessorARMv7MForLlvm_VFP : ProcessorARMv7M_VFP { } } ================================================ FILE: Zelig/Zelig/RunTime/Zelig/Kernel/HardwareModel/TargetPlatform/ARMv7_VFP/ProcessorARMv7MForLlvm_VFP_ContextSwitch.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // //#define DEBUG_CTX_SWITCH using System.Runtime.InteropServices; namespace Microsoft.Zelig.Runtime.TargetPlatform.ARMv7 { using System; using EncDef = Microsoft.Zelig.TargetModel.ArmProcessor.EncodingDefinition; using TS = Microsoft.Zelig.Runtime.TypeSystem; using RT = Microsoft.Zelig.Runtime; public abstract partial class ProcessorARMv7MForLlvm_VFP { //--// // // Part of Context may be defined in the model for the targeted sub-system, e.g. Mbed or CMSIS-Core for ARM processors // public abstract unsafe new class Context : Processor.Context { [StructLayout(LayoutKind.Sequential, Pack = 4)] public struct SoftwareFrame { // SW stack frame: pushed by PendSV_Handler // SW stack frame [TS.AssumeReferenced] public uint EXC_RETURN; [TS.AssumeReferenced] public uint CONTROL; [TS.AssumeReferenced] public UIntPtr R4; [TS.AssumeReferenced] public UIntPtr R5; [TS.AssumeReferenced] public UIntPtr R6; [TS.AssumeReferenced] public UIntPtr R7; [TS.AssumeReferenced] public UIntPtr R8; [TS.AssumeReferenced] public UIntPtr R9; [TS.AssumeReferenced] public UIntPtr R10; [TS.AssumeReferenced] public UIntPtr R11; } [StructLayout(LayoutKind.Sequential, Pack = 4)] public struct SoftwareFloatingPointFrame { // SW stack frame for FP [TS.AssumeReferenced] public float S16; [TS.AssumeReferenced] public float S17; [TS.AssumeReferenced] public float S18; [TS.AssumeReferenced] public float S19; [TS.AssumeReferenced] public float S20; [TS.AssumeReferenced] public float S21; [TS.AssumeReferenced] public float S22; [TS.AssumeReferenced] public float S23; [TS.AssumeReferenced] public float S24; [TS.AssumeReferenced] public float S25; [TS.AssumeReferenced] public float S26; [TS.AssumeReferenced] public float S27; [TS.AssumeReferenced] public float S28; [TS.AssumeReferenced] public float S29; [TS.AssumeReferenced] public float S30; [TS.AssumeReferenced] public float S31; } [StructLayout(LayoutKind.Sequential, Pack = 4)] public struct HardwareFrame { // HW stack frame: pushed upon entering PendSV_Handler [TS.AssumeReferenced] public UIntPtr R0; [TS.AssumeReferenced] public UIntPtr R1; [TS.AssumeReferenced] public UIntPtr R2; [TS.AssumeReferenced] public UIntPtr R3; [TS.AssumeReferenced] public UIntPtr R12; [TS.AssumeReferenced] public UIntPtr LR; [TS.AssumeReferenced] public UIntPtr PC; [TS.AssumeReferenced] public UIntPtr PSR; // HW stack frame for FP [TS.AssumeReferenced] public float S0; [TS.AssumeReferenced] public float S1; [TS.AssumeReferenced] public float S2; [TS.AssumeReferenced] public float S3; [TS.AssumeReferenced] public float S4; [TS.AssumeReferenced] public float S5; [TS.AssumeReferenced] public float S6; [TS.AssumeReferenced] public float S7; [TS.AssumeReferenced] public float S8; [TS.AssumeReferenced] public float S9; [TS.AssumeReferenced] public float S10; [TS.AssumeReferenced] public float S11; [TS.AssumeReferenced] public float S12; [TS.AssumeReferenced] public float S13; [TS.AssumeReferenced] public float S14; [TS.AssumeReferenced] public float S15; [TS.AssumeReferenced] public UIntPtr FPSCR_1; [TS.AssumeReferenced] public UIntPtr FPSCR_2; } [TS.WellKnownType( "Microsoft_Zelig_ProcessorARMv7ForLlvm_VFP_RegistersOnStack" )] [StructLayout(LayoutKind.Sequential)] public struct RegistersOnStackFullFPContext { public const uint StackRegister = EncDef.c_register_sp; public const uint LinkRegister = EncDef.c_register_lr; public const uint ProgramCounterRegister = EncDef.c_register_pc; // // State // public SoftwareFrame SoftwareFrameRegisters; public SoftwareFloatingPointFrame SoftwareFloatingPointFrameRegisters; public HardwareFrame HardwareFrameRegisters; // // Helper Methods // public static unsafe uint TotalFrameSize { [RT.Inline] get { return HWFrameSize + SwitcherFrameSize; } } public static unsafe uint HWFrameSize { [RT.Inline] get { return (uint)sizeof(HardwareFrame); } } public static unsafe uint SwitcherFrameSize { [RT.Inline] get { return (uint)(sizeof(SoftwareFrame) + sizeof(SoftwareFloatingPointFrame)); } } } [StructLayout(LayoutKind.Sequential)] public struct RegistersOnStackNoFPContext { public const uint StackRegister = EncDef.c_register_sp; public const uint LinkRegister = EncDef.c_register_lr; public const uint ProgramCounterRegister = EncDef.c_register_pc; // // State // public SoftwareFrame SoftwareFrameRegisters; public HardwareFrame HardwareFrameRegisters; // // Helper Methods // public static unsafe uint TotalFrameSize { [RT.Inline] get { return HWFrameSize + SwitcherFrameSize; } } public static unsafe uint HWFrameSize { [RT.Inline] get { return (uint)sizeof(HardwareFrame); } } public static unsafe uint SwitcherFrameSize { [RT.Inline] get { return (uint)sizeof(SoftwareFrame); } } //--// internal unsafe UIntPtr* GetRegisterPointer( uint idx ) { switch(idx) { case 0: fixed(UIntPtr* ptr = &this.HardwareFrameRegisters.R0 ) { return ptr; }; case 1: fixed(UIntPtr* ptr = &this.HardwareFrameRegisters.R1 ) { return ptr; }; case 2: fixed(UIntPtr* ptr = &this.HardwareFrameRegisters.R2 ) { return ptr; }; case 3: fixed(UIntPtr* ptr = &this.HardwareFrameRegisters.R3 ) { return ptr; }; case 4: fixed(UIntPtr* ptr = &this.SoftwareFrameRegisters.R4 ) { return ptr; }; case 5: fixed(UIntPtr* ptr = &this.SoftwareFrameRegisters.R5 ) { return ptr; }; case 6: fixed(UIntPtr* ptr = &this.SoftwareFrameRegisters.R6 ) { return ptr; }; case 7: fixed(UIntPtr* ptr = &this.SoftwareFrameRegisters.R7 ) { return ptr; }; case 8: fixed(UIntPtr* ptr = &this.SoftwareFrameRegisters.R8 ) { return ptr; }; case 9: fixed(UIntPtr* ptr = &this.SoftwareFrameRegisters.R9 ) { return ptr; }; case 10: fixed(UIntPtr* ptr = &this.SoftwareFrameRegisters.R10) { return ptr; }; case 11: fixed(UIntPtr* ptr = &this.SoftwareFrameRegisters.R11) { return ptr; }; case 12: fixed(UIntPtr* ptr = &this.HardwareFrameRegisters.R12) { return ptr; }; case 13: throw new ArgumentException( "" ); case 14: fixed(UIntPtr* ptr = &this.HardwareFrameRegisters.LR ) { return ptr; }; case 15: fixed(UIntPtr* ptr = &this.HardwareFrameRegisters.PC ) { return ptr; }; } return null; } } //--// // // This is the pointer to the base of the stack. Usefull for stack walking. // protected UIntPtr BaseSP; // // This is the pointer to the last known position of the stack pointer // For a long jump this points to the end of the SW context to install // protected UIntPtr SP; // // Return value for mode transitions // protected uint EXC_RETURN; // // Track VFP status // protected bool m_isFullContext; //--// public Context(RT.ThreadImpl owner) : base(owner) { } // // Overrides // public override void SwitchTo( ) { // The long jump selects the current thread's context and sets its EXC_RETURN value ProcessorARMv7M.RaiseSupervisorCall( ProcessorARMv7M.SVC_Code.SupervisorCall__LongJump ); #if DEBUG_CTX_SWITCH BugCheck.Log( "!!!!!!!!!!!!!!!!!!!!! ERROR !!!!!!!!!!!!!!!!!!!!!!!" ); BugCheck.Log( "!!! Back after Long Jump after, Ctx Switch Failed !!!" ); BugCheck.Log( "!!!!!!!!!!!!!!!!!!!!! ERROR !!!!!!!!!!!!!!!!!!!!!!!" ); #endif RT.BugCheck.Assert( false, BugCheck.StopCode.IllegalMode ); } public override void Populate( ) { // // This woudl be called on the throw context, but in ARMv7M we do not have one // ThreadImpl thisThread = ThreadImpl.CurrentThread; Processor.Context ctx = thisThread.SwappedOutContext; this.BaseSP = ctx.BaseStackPointer; this.SP = ProcessorARMv7MForLlvm.GetProcessStackPointer( ); this.EXC_RETURN = ctx.ExcReturn; } public override void Populate( Processor.Context context ) { this.BaseSP = context.BaseStackPointer; this.SP = context.StackPointer; this.EXC_RETURN = context.ExcReturn; } public unsafe override void PopulateFromDelegate( Delegate dlg, uint[] stack ) { DelegateImpl dlgImpl = (DelegateImpl)(object)dlg; ArrayImpl stackImpl = (ArrayImpl )(object)stack; ObjectImpl objImpl = (ObjectImpl )(object)dlg.Target; // // Save the initial stack pointer // In the general case the SP will be at the top of the current frame we are building // When we do a LongJump though, or we start the thread first, we will have to use the base stack pointer // this.BaseSP = AddressMath.AlignToLowerBoundary( new UIntPtr( stackImpl.GetEndDataPointer( ) ), 8 ); this.SP = AddressMath.Decrement( this.BaseSP, RegistersOnStackNoFPContext.TotalFrameSize ); this.EXC_RETURN = c_MODE_RETURN__THREAD_PSP; // // Initial SP must still be within the stack array // RT.BugCheck.Assert( stackImpl.GetDataPointer( ) <= this.SP.ToPointer( ), BugCheck.StopCode.StackCorruptionDetected ); // // build the first stack frame // RegistersOnStackNoFPContext* firstFrame = GetSimpleFrame(this.SP); firstFrame->HardwareFrameRegisters.PC = new UIntPtr( dlgImpl.InnerGetCodePointer().Target.ToPointer() ); firstFrame->HardwareFrameRegisters.R0 = objImpl.ToPointer(); firstFrame->HardwareFrameRegisters.PSR = new UIntPtr(ProcessorARMv7M.c_psr_InitialValue); firstFrame->SoftwareFrameRegisters.EXC_RETURN = c_MODE_RETURN__THREAD_PSP; // !!! here we assume that no context starts with FP context active !!! firstFrame->SoftwareFrameRegisters.CONTROL = c_CONTROL__MODE__THRD_PRIV; #if DEBUG_CTX_SWITCH RT.BugCheck.Log( "[PFD-ctx] EXC=0x%08x, PSR=0x%08x, PC=0x%08x, R0=0x%08x, SP(aligned)=0x%08x", (int)firstFrame->EXC_RETURN, (int)firstFrame->PSR.ToUInt32( ), (int)firstFrame->PC.ToUInt32( ), (int)firstFrame->R0.ToUInt32( ), (int)this.SP.ToUInt32( ) ); RT.BugCheck.Log( "[PFD-stackImpl] SP(start)=0x%08x, SP(end)=0x%08x, SP(length)=0x%08x, SP(offset)=0x%08x", (int)( stackImpl.GetDataPointer( ) ), (int)( stackImpl.GetEndDataPointer( ) ), (int)( stackImpl.GetEndDataPointer( ) - stackImpl.GetDataPointer( ) ), (int)( (int)stackImpl.GetEndDataPointer( ) - this.SP.ToUInt32( ) ) ); #endif } public override void SetupForExceptionHandling(uint mode) { // // Stop any exception from happening // using (Runtime.SmartHandles.InterruptState.DisableAll()) { // // Retrieve the MSP< which we will use to handle exceptions // UIntPtr stack = ProcessorARMv7MForLlvm.GetMainStackPointer(); //// //// Enter target mode, with interrupts disabled. //// //SwitchToHandlerPrivilegedMode( ); // // Set the stack pointer in the context to be the current MSP // this.BaseSP = ProcessorARMv7MForLlvm.GetMainStackPointerAtReset( ); this.SP = stack; this.EXC_RETURN = c_MODE_RETURN__THREAD_MSP; //// //// Switch back to original mode //// //SwitchToThreadUnprivilegedMode( ); } } #region Tracking Collector and Exceptions public override bool Unwind( ) { throw new Exception( "Unwind not implemented" ); } public override unsafe UIntPtr GetRegisterByIndex( uint idx ) { RegistersOnStackNoFPContext* frame = GetSimpleFrame(this.SP); return *( frame->GetRegisterPointer( idx ) ); } public override unsafe void SetRegisterByIndex( uint idx, UIntPtr value ) { BugCheck.Assert( false, BugCheck.StopCode.InvalidOperation ); } #endregion private static UIntPtr ContextSwitch( ThreadManager tm, UIntPtr stackPointer, bool isFullFrame ) { ThreadImpl currentThread = tm.CurrentThread; ThreadImpl nextThread = tm.NextThread; Context ctx; if(currentThread != null) { ctx = (Context)currentThread.SwappedOutContext; // // update SP as well as the EXC_RETURN address // ctx.IsFullContext = isFullFrame; ctx.EXC_RETURN = isFullFrame ? GetFullFrame(stackPointer) ->SoftwareFrameRegisters.EXC_RETURN : GetSimpleFrame(stackPointer)->SoftwareFrameRegisters.EXC_RETURN; ctx.StackPointer = stackPointer; } ctx = (Context)nextThread.SwappedOutContext; // // Pass EXC_RETURN down to the native portion of the // PendSV handler we need to offset to the beginning of the frame // ProcessorARMv7MForLlvm.SetExcReturn( ctx.EXC_RETURN ); // // Update thread manager state and Thread.CurrentThread static field // tm.CurrentThread = nextThread; ThreadImpl.CurrentThread = nextThread; return ctx.StackPointer; } //--// //--// //--// private static unsafe void FirstLongJump( ) { LongJump( ); } private static unsafe void LongJump( ) { // // Retrieve next context from ThreadManager // Context currentThreadCtx = (ProcessorARMv7MForLlvm_VFP.Context)ThreadManager.Instance.CurrentThread.SwappedOutContext; // // Set the PSP at R0 so that returning from the SVC handler will complete the work // ProcessorARMv7MForLlvm.SetProcessStackPointer( AddressMath.Increment( currentThreadCtx.StackPointer, currentThreadCtx.IsFullContext ? RegistersOnStackFullFPContext.SwitcherFrameSize : RegistersOnStackNoFPContext.SwitcherFrameSize ) ); ProcessorARMv7MForLlvm.SetExcReturn( currentThreadCtx.EXC_RETURN ); // // SWitch to unprivileged mode before jumping to our thread // This can only be enabled when we have a model for allowing tasks // to enable/disable interrupts // //ProcessorARMv7M.SwitchToUnprivilegedMode( ); } private static unsafe void LongJumpForRetireThread( ) { LongJump( ); } // // Access Methods // public override UIntPtr StackPointer { [RT.Inline] get { return this.SP; } [RT.Inline] set { this.SP = value; } } public override UIntPtr BaseStackPointer { [RT.Inline] get { return this.BaseSP; } } public override uint ExcReturn { [RT.Inline] get { return this.EXC_RETURN; } [RT.Inline] set { this.EXC_RETURN = value; } } public bool IsFullContext { [RT.Inline] get { return this.m_isFullContext; } [RT.Inline] set { this.m_isFullContext = value; } } public override UIntPtr ProgramCounter { get { //return Registers.PC; return (UIntPtr)0; } set { //Registers.PC = value; } } public override uint ScratchedIntegerRegisters { get { return 0; } } //--// [RT.Inline] internal static unsafe Context.RegistersOnStackFullFPContext* GetFullFrame( UIntPtr SP ) { return (Context.RegistersOnStackFullFPContext*)SP.ToPointer( ); } [RT.Inline] internal static unsafe Context.RegistersOnStackNoFPContext* GetSimpleFrame( UIntPtr SP ) { return (Context.RegistersOnStackNoFPContext*)SP.ToPointer( ); } private static unsafe void SnapshotActiveFrame( ref Context.RegistersOnStackNoFPContext frame ) { //// //// Can run in handler mode only //// //BugCheck.Assert( VerifyHandlerMode( ), BugCheck.StopCode.IllegalMode ); //// //// Retrieve PSP and snapshot the frame that was pushed by the SVC handler //// //UIntPtr psp = GetProcessStackPointer( ); //Context.RegistersOnStackNoFPContext* snapshot = GetSimpleFrame( psp ); //frame.HardwareFrameRegisters = snapshot->HardwareFrameRegisters; //frame.SoftwareFrameRegisters = snapshot->SoftwareFrameRegisters; } // // Helpers // [Inline] public static void InterruptHandlerWithContextSwitch( UIntPtr stackPtr ) { Peripherals.Instance.ProcessInterrupt( ); ThreadManager tm = ThreadManager.Instance; // // We keep looping until the current and next threads are the same, // because when swapping out a dead thread, we might wake up a different thread. // while(tm.ShouldContextSwitch) { ContextSwitch( tm, stackPtr, false ); } } [Inline] public static void InterruptHandlerWithoutContextSwitch( ) { Peripherals.Instance.ProcessInterrupt( ); } [Inline] public static void FastInterruptHandlerWithoutContextSwitch( ) { Peripherals.Instance.ProcessFastInterrupt( ); } [Inline] public static void GenericSoftwareInterruptHandler( ref RegistersOnStackNoFPContext registers ) { } //--// [Inline] private static unsafe void PrepareStackForException( uint mode, RegistersOnStackNoFPContext* ptr ) { // // EXC_RETURN to go back to previous mode. // // TODO: // // Save unbanked R4 -R11. // // TODO: // // Switch back to the exception handling mode. // // TODO: // // R1 should point to the Register Context on the stack. // // TODO: //SetRegister( EncDef.c_register_r1, new UIntPtr( ptr ) ); } [Inline] private static unsafe void RestoreStackForException( uint mode, RegistersOnStackNoFPContext* ptr ) { // // EXC_RETUNR to go back to previous mode. // // TODO: // // Save unbanked R4 -R11. // // TODO: // // Switch back to the exception handling mode. // // TODO: // // R1 should point to the Register Context on the stack. // // TODO: //SetRegister( EncDef.c_register_r1, new UIntPtr( ptr ) ); } // // All overridable exceptions for Ctx Switch // [RT.CapabilitiesFilter( RequiredCapabilities=TargetModel.ArmProcessor.InstructionSetVersion.Platform_VFP__HardVFP )] [RT.HardwareExceptionHandler( RT.HardwareException.Interrupt )] [RT.ExportedMethod] private static unsafe void SVC_Handler_Zelig_VFP_NoFPContext( uint* args ) { SVC_Code svc_number = (SVC_Code)((byte*)args[6])[-2]; // svc number is at stacked PC offset - 2 bytes switch(svc_number) { case SVC_Code.SupervisorCall__LongJump: LongJump( ); break; case SVC_Code.SupervisorCall__StartThreads: FirstLongJump( ); break; case SVC_Code.SupervisorCall__RetireThread: LongJumpForRetireThread( ); break; case SVC_Code.SupervisorCall__SnapshotProcessModeRegisters: ProcessorARMv7MForLlvm.UpdateFrame( ref ProcessorARMv7MForLlvm.Snapshot, CUSTOM_STUB_FetchSoftwareFrameSnapshot( ) ); break; default: BugCheck.Assert( false, BugCheck.StopCode.Impossible ); break; } } [RT.CapabilitiesFilter( RequiredCapabilities=TargetModel.ArmProcessor.InstructionSetVersion.Platform_VFP__HardVFP )] [RT.HardwareExceptionHandler( RT.HardwareException.Interrupt )] [RT.ExportedMethod] private static UIntPtr PendSV_Handler_Zelig_VFP( UIntPtr stackPointer, uint isParitalStack ) { using(RT.SmartHandles.InterruptState.Disable( )) { return ContextSwitch( ThreadManager.Instance, stackPointer, isParitalStack == 0 ); } } [RT.CapabilitiesFilter( RequiredCapabilities=TargetModel.ArmProcessor.InstructionSetVersion.Platform_VFP__HardVFP )] [RT.HardwareExceptionHandler( RT.HardwareException.Interrupt )] [RT.ExportedMethod] private static void AnyInterrupt( UIntPtr stackPtr ) { using(RT.SmartHandles.InterruptState.Disable( )) { InterruptHandlerWithContextSwitch( stackPtr ); } } } // // State // internal static Context.RegistersOnStackNoFPContext Snapshot; } } ================================================ FILE: Zelig/Zelig/RunTime/Zelig/Kernel/HardwareModel/TargetPlatform/ARMv7_VFP/ProcessorARMv7M_VFP.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // namespace Microsoft.Zelig.Runtime.TargetPlatform.ARMv7 { using System; using System.Runtime.InteropServices; public abstract partial class ProcessorARMv7M_VFP : ProcessorARMv7M { // // Floating point context // public const int c_CONTROL__FPCA_SHIFT = 2; public const uint c_CONTROL__FPCA_MASK = 0x1u << c_CONTROL__FPCA_SHIFT; public const uint c_CONTROL__FPCA_INACTIVE = 0x0u << c_CONTROL__FPCA_SHIFT; public const uint c_CONTROL__FPCA_ACTIVE = 0x1u << c_CONTROL__FPCA_SHIFT; // // FP control // public const int c_FPCCR__ASPEN_SHIFT = 31; public const uint c_FPCCR__ASPEN_MASK = 0x1u << c_FPCCR__ASPEN_SHIFT; public const uint c_FPCCR__ASPEN_ENABLED = 0x1u << c_FPCCR__ASPEN_SHIFT; public const int c_FPCCR__LSPEN_SHIFT = 30; public const uint c_FPCCR__LSPEN_MASK = 0x1u << c_FPCCR__LSPEN_SHIFT; public const uint c_FPCCR__LSPEN_ENABLED = 0x1u << c_FPCCR__LSPEN_SHIFT; // // EXC_RETURN // public const uint c_MODE_RETURN__HANDLER_MSP_VFP = 0xFFFFFFE1; // handler will return in handler mode using the MSP public const uint c_MODE_RETURN__THREAD_MSP_VFP = 0xFFFFFFE9; // handler will return in thread mode using the MSP public const uint c_MODE_RETURN__THREAD_PSP_VFP = 0xFFFFFFED; // handler will return in thread mode using the PSP // // Helper Methods // public override void InitializeProcessor( ) { base.InitializeProcessor( ); DisableLazyStacking( ); } //--// // // Cache // public override UIntPtr GetCacheableAddress( UIntPtr ptr ) { // Cortex-M7 actually has a cache, so override the method return ptr; } public override UIntPtr GetUncacheableAddress( UIntPtr ptr ) { // Cortex-M7 actually has a cache, so override the method return ptr; } public override void FlushCacheLine( UIntPtr target ) { } //--// protected void EnableLazyStacking() { uint value = CUSTOM_STUB_SCB__get_FPCCR( ); value |= c_FPCCR__LSPEN_ENABLED; CUSTOM_STUB_SCB__set_FPCCR( value ); } protected void DisableLazyStacking() { uint value = CUSTOM_STUB_SCB__get_FPCCR( ); value &= ~c_FPCCR__LSPEN_ENABLED; CUSTOM_STUB_SCB__set_FPCCR( value ); } protected bool IsFPContextActiveOnCurrentMode() { return ( ( CMSIS_STUB_SCB__get_CONTROL( ) & c_CONTROL__FPCA_ACTIVE ) == c_CONTROL__FPCA_ACTIVE ); } //--// [DllImport( "C" )] private static extern uint CUSTOM_STUB_SCB__get_FPCCR( ); [DllImport( "C" )] private static extern void CUSTOM_STUB_SCB__set_FPCCR( uint value ); [DllImport( "C" )] private static extern bool CUSTOM_STUB_IsFPContextActiveOnCurrentMode( ); } } ================================================ FILE: Zelig/Zelig/RunTime/Zelig/Kernel/HardwareModel/TargetPlatform/AbstractMethodWrapper.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // namespace Microsoft.Zelig.Runtime { using System; using TS = Microsoft.Zelig.Runtime.TypeSystem; public abstract class AbstractMethodWrapper { [TS.WellKnownMethod( "Microsoft_Zelig_Runtime_AbstractMethodWrapper_AddActivationRecordEvent" )] protected static extern void AddActivationRecordEvent( ActivationRecordEvents ev ); [TS.WellKnownMethod( "Microsoft_Zelig_Runtime_AbstractMethodWrapper_Prologue" )] public abstract void Prologue( string typeFullName , string methodFullName , TS.MethodRepresentation.BuildTimeAttributes attribs ); [TS.WellKnownMethod( "Microsoft_Zelig_Runtime_AbstractMethodWrapper_Prologue2" )] public abstract void Prologue( string typeFullName , string methodFullName , TS.MethodRepresentation.BuildTimeAttributes attribs , HardwareException he ); [TS.WellKnownMethod( "Microsoft_Zelig_Runtime_AbstractMethodWrapper_Epilogue" )] public abstract void Epilogue( string typeFullName , string methodFullName , TS.MethodRepresentation.BuildTimeAttributes attribs ); [TS.WellKnownMethod( "Microsoft_Zelig_Runtime_AbstractMethodWrapper_Epilogue2" )] public abstract void Epilogue( string typeFullName , string methodFullName , TS.MethodRepresentation.BuildTimeAttributes attribs , HardwareException he ); } } ================================================ FILE: Zelig/Zelig/RunTime/Zelig/Kernel/Helpers/BinaryOperations.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // namespace Microsoft.Zelig.Runtime.Helpers { using System; using System.Runtime.CompilerServices; using TS = Microsoft.Zelig.Runtime.TypeSystem; internal static class BinaryOperations { [TS.WellKnownMethod( "Helpers_BinaryOperations_IntDiv" )] internal static int IntDiv( int left , int right ) { bool fReverse; if(left < 0) { left = unchecked(-left); fReverse = true; } else { fReverse = false; } if(right < 0) { right = unchecked(-right); fReverse = !fReverse; } int res = (int)((uint)left / (uint)right); if(fReverse) { res = -res; } return res; } [TS.WellKnownMethod( "Helpers_BinaryOperations_IntRem" )] internal static int IntRem( int left , int right ) { return left - (left / right) * right; } //--// [TS.WellKnownMethod( "Helpers_BinaryOperations_UintDiv" )] internal static uint UintDiv( uint dividend , uint divisor ) { if(divisor == 0) { throw new DivideByZeroException(); } uint res = 0; int shift = 0; while(dividend > divisor) { if(MathImpl.IsNegative( divisor )) { break; } divisor *= 2; shift++; } while(shift >= 0) { res *= 2; if(dividend >= divisor) { dividend -= divisor; res += 1; if(dividend == 0) { res <<= shift; break; } } divisor /= 2; shift--; } return res; } [TS.WellKnownMethod( "Helpers_BinaryOperations_UintRem" )] internal static uint UintRem( uint dividend , uint divisor ) { if(divisor == 0) { throw new DivideByZeroException(); } int shift = 0; while(dividend > divisor) { if(MathImpl.IsNegative( divisor )) { break; } divisor *= 2; shift++; } while(shift >= 0) { if(dividend >= divisor) { dividend -= divisor; if(dividend == 0) { break; } } divisor /= 2; shift--; } return dividend; } //--// [TS.WellKnownMethod( "Helpers_BinaryOperations_LongMul" )] internal static long LongMul( long left , long right ) { bool fReverse; if(left < 0) { left = unchecked(-left); fReverse = true; } else { fReverse = false; } if(right < 0) { right = unchecked(-right); fReverse = !fReverse; } ulong leftU = unchecked( (ulong)left ); ulong rightU = unchecked( (ulong)right ); long res = (long)(leftU * rightU); if(fReverse) { res = -res; } return res; } [TS.WellKnownMethod( "Helpers_BinaryOperations_LongDiv" )] internal static long LongDiv( long left , long right ) { bool fReverse; if(left < 0) { left = unchecked(-left); fReverse = true; } else { fReverse = false; } if(right < 0) { right = unchecked(-right); fReverse = !fReverse; } ulong leftU = unchecked( (ulong)left ); ulong rightU = unchecked( (ulong)right ); long res = (long)(leftU / rightU); if(fReverse) { res = -res; } return res; } [TS.WellKnownMethod( "Helpers_BinaryOperations_LongRem" )] internal static long LongRem( long left , long right ) { return left - (left / right) * right; } [Inline] [TS.WellKnownMethod( "Helpers_BinaryOperations_LongShl" )] internal static long LongShl( long left , int shift ) { if(shift == 0) { return left; } else { uint leftHigh = (uint)(left >> 32); uint leftLow = (uint) left ; if(shift >= 32) { if(shift >= 64) { return 0; } else { return (long)(((ulong)(leftLow << (shift - 32))) << 32); } } else { uint resHigh = (leftHigh << shift) | (leftLow >> (32 - shift)); uint resLow = (leftLow << shift); return (long)(((ulong)resHigh << 32) | (ulong)resLow); } } } [Inline] [TS.WellKnownMethod( "Helpers_BinaryOperations_LongShr" )] internal static long LongShr( long left , int shift ) { if(shift == 0) { return left; } else { int leftHigh = (int )(left >> 32); uint leftLow = (uint) left ; if(shift >= 32) { if(shift >= 64) { // // Just return the sign. // return (long)((int)leftHigh >> 31); } else { return (long)((int)leftHigh >> (shift - 32)); } } else { int resHigh = (leftHigh >> shift); uint resLow = (leftLow >> shift) | ((uint)leftHigh << (32 - shift)); return (long)(((ulong)resHigh << 32) | (ulong)resLow); } } } //--// [Inline] [TS.WellKnownMethod( "Helpers_BinaryOperations_UlongMul" )] internal static ulong UlongMul( ulong left , ulong right ) { uint leftHigh = (uint)(left >> 32); uint leftLow = (uint) left ; uint rightHigh = (uint)(right >> 32); uint rightLow = (uint) right ; uint mid1 = (uint)((ulong)leftLow * (ulong)rightHigh); uint mid2 = (uint)((ulong)leftHigh * (ulong)rightLow ); return ((ulong)leftLow * (ulong)rightLow ) + ((ulong)mid1 << 32 ) + ((ulong)mid2 << 32 ) ; } [TS.WellKnownMethod( "Helpers_BinaryOperations_UlongDiv" )] internal static ulong UlongDiv( ulong dividend , ulong divisor ) { if(divisor == 0) { throw new DivideByZeroException(); } ulong res = 0; int shift = 0; while(dividend > divisor) { if(MathImpl.IsNegative( divisor )) { break; } divisor *= 2; shift++; } while(shift >= 0) { res *= 2; if(dividend >= divisor) { dividend -= divisor; res += 1; if(dividend == 0) { res <<= shift; break; } } divisor /= 2; shift--; } return res; } [TS.WellKnownMethod( "Helpers_BinaryOperations_UlongRem" )] internal static ulong UlongRem( ulong dividend , ulong divisor ) { if(divisor == 0) { throw new DivideByZeroException(); } int shift = 0; while(dividend > divisor) { if(MathImpl.IsNegative( divisor )) { break; } divisor *= 2; shift++; } while(shift >= 0) { if(dividend >= divisor) { dividend -= divisor; if(dividend == 0) { break; } } divisor /= 2; shift--; } return dividend; } [Inline] [TS.WellKnownMethod( "Helpers_BinaryOperations_UlongShl" )] internal static ulong UlongShl( ulong left , int shift ) { if(shift == 0) { return left; } else { uint leftHigh = (uint)(left >> 32); uint leftLow = (uint) left ; if(shift >= 32) { if(shift >= 64) { return 0; } else { return ((ulong)(leftLow << (shift - 32))) << 32; } } else { uint resHigh = (leftHigh << shift) | (leftLow >> (32 - shift)); uint resLow = (leftLow << shift); return (((ulong)resHigh << 32) | (ulong)resLow); } } } [Inline] [TS.WellKnownMethod( "Helpers_BinaryOperations_UlongShr" )] internal static ulong UlongShr( ulong left , int shift ) { if(shift == 0) { return left; } else { uint leftHigh = (uint)(left >> 32); uint leftLow = (uint) left ; if(shift >= 32) { if(shift >= 64) { return 0; } else { return (ulong)(leftHigh >> (shift - 32)); } } else { uint resHigh = (leftHigh >> shift); uint resLow = (leftLow >> shift) | (leftHigh << (32 - shift)); return (((ulong)resHigh << 32) | (ulong)resLow); } } } //--// [TS.WellKnownMethod( "SoftFP_BinaryOperations_FloatAdd" )] internal static float FloatAdd( float left , float right ) { FloatImplementation fiLeft = new FloatImplementation( left ); FloatImplementation fiRight = new FloatImplementation( right ); fiLeft.Add( ref fiRight ); return fiLeft.ToFloat(); } [TS.WellKnownMethod( "SoftFP_BinaryOperations_FloatSub" )] internal static float FloatSub( float left , float right ) { FloatImplementation fiLeft = new FloatImplementation( left ); FloatImplementation fiRight = new FloatImplementation( right ); fiLeft.Sub( ref fiRight ); return fiLeft.ToFloat(); } [TS.WellKnownMethod( "SoftFP_BinaryOperations_FloatMul" )] internal static float FloatMul( float left , float right ) { FloatImplementation fiLeft = new FloatImplementation( left ); FloatImplementation fiRight = new FloatImplementation( right ); fiLeft.Mul( ref fiRight ); return fiLeft.ToFloat(); } [TS.WellKnownMethod( "SoftFP_BinaryOperations_FloatDiv" )] internal static float FloatDiv( float left , float right ) { FloatImplementation fiLeft = new FloatImplementation( left ); FloatImplementation fiRight = new FloatImplementation( right ); fiLeft.Div( ref fiRight ); return fiLeft.ToFloat(); } [TS.WellKnownMethod( "SoftFP_BinaryOperations_FloatRem" )] internal static float FloatRem( float left , float right ) { return left - (int)(left / right) * right; } //--// [TS.WellKnownMethod( "SoftFP_BinaryOperations_DoubleAdd" )] internal static double DoubleAdd( double left , double right ) { DoubleImplementation diLeft = new DoubleImplementation( left ); DoubleImplementation diRight = new DoubleImplementation( right ); diLeft.Add( ref diRight ); return diLeft.ToDouble(); } [TS.WellKnownMethod( "SoftFP_BinaryOperations_DoubleSub" )] internal static double DoubleSub( double left , double right ) { DoubleImplementation diLeft = new DoubleImplementation( left ); DoubleImplementation diRight = new DoubleImplementation( right ); diLeft.Sub( ref diRight ); return diLeft.ToDouble(); } [TS.WellKnownMethod( "SoftFP_BinaryOperations_DoubleMul" )] internal static double DoubleMul( double left , double right ) { DoubleImplementation diLeft = new DoubleImplementation( left ); DoubleImplementation diRight = new DoubleImplementation( right ); diLeft.Mul( ref diRight ); return diLeft.ToDouble(); } [TS.WellKnownMethod( "SoftFP_BinaryOperations_DoubleDiv" )] internal static double DoubleDiv( double left , double right ) { DoubleImplementation diLeft = new DoubleImplementation( left ); DoubleImplementation diRight = new DoubleImplementation( right ); diLeft.Div( ref diRight ); return diLeft.ToDouble(); } [TS.WellKnownMethod( "SoftFP_BinaryOperations_DoubleRem" )] internal static double DoubleRem( double left , double right ) { return left - (long)(left / right) * right; } } } ================================================ FILE: Zelig/Zelig/RunTime/Zelig/Kernel/Helpers/CompareAndSet.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // namespace Microsoft.Zelig.Runtime.Helpers { using System; using System.Runtime.CompilerServices; using TS = Microsoft.Zelig.Runtime.TypeSystem; internal static class CompareAndSet { [TS.WellKnownMethod( "SoftFP_CompareAndSet_FloatEqual" )] internal static bool FloatEqual( float left , float right ) { FloatImplementation fiLeft = new FloatImplementation( left ); FloatImplementation fiRight = new FloatImplementation( right ); return fiLeft.Compare( ref fiRight ) == 0; } [TS.WellKnownMethod( "SoftFP_CompareAndSet_FloatGreaterOrEqual" )] internal static bool FloatGreaterOrEqual( float left , float right ) { FloatImplementation fiLeft = new FloatImplementation( left ); FloatImplementation fiRight = new FloatImplementation( right ); return fiLeft.Compare( ref fiRight ) >= 0; } [TS.WellKnownMethod( "SoftFP_CompareAndSet_FloatGreater" )] internal static bool FloatGreater( float left , float right ) { FloatImplementation fiLeft = new FloatImplementation( left ); FloatImplementation fiRight = new FloatImplementation( right ); return fiLeft.Compare( ref fiRight ) > 0; } [TS.WellKnownMethod( "SoftFP_CompareAndSet_FloatLessOrEqual" )] internal static bool FloatLessOrEqual( float left , float right ) { FloatImplementation fiLeft = new FloatImplementation( left ); FloatImplementation fiRight = new FloatImplementation( right ); return fiLeft.Compare( ref fiRight ) <= 0; } [TS.WellKnownMethod( "SoftFP_CompareAndSet_FloatLess" )] internal static bool FloatLess( float left , float right ) { FloatImplementation fiLeft = new FloatImplementation( left ); FloatImplementation fiRight = new FloatImplementation( right ); return fiLeft.Compare( ref fiRight ) < 0; } [TS.WellKnownMethod( "SoftFP_CompareAndSet_FloatNotEqual" )] internal static bool FloatNotEqual( float left , float right ) { FloatImplementation fiLeft = new FloatImplementation( left ); FloatImplementation fiRight = new FloatImplementation( right ); return fiLeft.Compare( ref fiRight ) != 0; } //--// [TS.WellKnownMethod( "SoftFP_CompareAndSet_DoubleEqual" )] internal static bool DoubleEqual( double left , double right ) { DoubleImplementation diLeft = new DoubleImplementation( left ); DoubleImplementation diRight = new DoubleImplementation( right ); return diLeft.Compare( ref diRight ) == 0; } [TS.WellKnownMethod( "SoftFP_CompareAndSet_DoubleGreaterOrEqual" )] internal static bool DoubleGreaterOrEqual( double left , double right ) { DoubleImplementation diLeft = new DoubleImplementation( left ); DoubleImplementation diRight = new DoubleImplementation( right ); return diLeft.Compare( ref diRight ) >= 0; } [TS.WellKnownMethod( "SoftFP_CompareAndSet_DoubleGreater" )] internal static bool DoubleGreater( double left , double right ) { DoubleImplementation diLeft = new DoubleImplementation( left ); DoubleImplementation diRight = new DoubleImplementation( right ); return diLeft.Compare( ref diRight ) > 0; } [TS.WellKnownMethod( "SoftFP_CompareAndSet_DoubleLessOrEqual" )] internal static bool DoubleLessOrEqual( double left , double right ) { DoubleImplementation diLeft = new DoubleImplementation( left ); DoubleImplementation diRight = new DoubleImplementation( right ); return diLeft.Compare( ref diRight ) <= 0; } [TS.WellKnownMethod( "SoftFP_CompareAndSet_DoubleLess" )] internal static bool DoubleLess( double left , double right ) { DoubleImplementation diLeft = new DoubleImplementation( left ); DoubleImplementation diRight = new DoubleImplementation( right ); return diLeft.Compare( ref diRight ) < 0; } [TS.WellKnownMethod( "SoftFP_CompareAndSet_DoubleNotEqual" )] internal static bool DoubleNotEqual( double left , double right ) { DoubleImplementation diLeft = new DoubleImplementation( left ); DoubleImplementation diRight = new DoubleImplementation( right ); return diLeft.Compare( ref diRight ) != 0; } } } ================================================ FILE: Zelig/Zelig/RunTime/Zelig/Kernel/Helpers/Convert.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // namespace Microsoft.Zelig.Runtime.Helpers { using System; using System.Runtime.CompilerServices; using TS = Microsoft.Zelig.Runtime.TypeSystem; internal static class Convert { [TS.WellKnownMethod( "SoftFP_Convert_IntToFloat" )] internal static float IntToFloat( int val , bool fOverflow ) { FloatImplementation fi = new FloatImplementation( val, fOverflow ); return fi.ToFloat(); } [TS.WellKnownMethod( "SoftFP_Convert_LongToFloat" )] internal static float LongToFloat( long val , bool fOverflow ) { FloatImplementation fi = new FloatImplementation( val, fOverflow ); return fi.ToFloat(); } [TS.WellKnownMethod( "SoftFP_Convert_UnsignedIntToFloat" )] internal static float UnsignedIntToFloat( uint val , bool fOverflow ) { FloatImplementation fi = new FloatImplementation( val, fOverflow ); return fi.ToFloat(); } [TS.WellKnownMethod( "SoftFP_Convert_UnsignedLongToFloat" )] internal static float UnsignedLongToFloat( ulong val , bool fOverflow ) { FloatImplementation fi = new FloatImplementation( val, fOverflow ); return fi.ToFloat(); } [TS.WellKnownMethod( "SoftFP_Convert_DoubleToFloat" )] internal static float DoubleToFloat( double val , bool fOverflow ) { DoubleImplementation di = new DoubleImplementation( val ); FloatImplementation fi = new FloatImplementation ( ref di, fOverflow ); return fi.ToFloat(); } //--// [TS.WellKnownMethod( "SoftFP_Convert_IntToDouble" )] internal static double IntToDouble( int val , bool fOverflow ) { DoubleImplementation di = new DoubleImplementation( val, fOverflow ); return di.ToDouble(); } [TS.WellKnownMethod( "SoftFP_Convert_LongToDouble" )] internal static double LongToDouble( long val , bool fOverflow ) { DoubleImplementation di = new DoubleImplementation( val, fOverflow ); return di.ToDouble(); } [TS.WellKnownMethod( "SoftFP_Convert_UnsignedIntToDouble" )] internal static double UnsignedIntToDouble( uint val , bool fOverflow ) { DoubleImplementation di = new DoubleImplementation( val, fOverflow ); return di.ToDouble(); } [TS.WellKnownMethod( "SoftFP_Convert_UnsignedLongToDouble" )] internal static double UnsignedLongToDouble( ulong val , bool fOverflow ) { DoubleImplementation di = new DoubleImplementation( val, fOverflow ); return di.ToDouble(); } [TS.WellKnownMethod( "SoftFP_Convert_FloatToDouble" )] internal static double FloatToDouble( float val , bool fOverflow ) { FloatImplementation fi = new FloatImplementation ( val ); DoubleImplementation di = new DoubleImplementation( ref fi, fOverflow ); return di.ToDouble(); } //--// [TS.WellKnownMethod( "SoftFP_Convert_FloatToInt" )] internal static int FloatToInt( float val , bool fOverflow ) { FloatImplementation fi = new FloatImplementation( val ); return fi.ToInt( fOverflow ); } [TS.WellKnownMethod( "SoftFP_Convert_FloatToUnsignedInt" )] internal static uint FloatToUnsignedInt( float val , bool fOverflow ) { FloatImplementation fi = new FloatImplementation( val ); return fi.ToUnsignedInt( fOverflow ); } [TS.WellKnownMethod( "SoftFP_Convert_DoubleToInt" )] internal static int DoubleToInt( double val , bool fOverflow ) { DoubleImplementation di = new DoubleImplementation( val ); return di.ToInt( fOverflow ); } [TS.WellKnownMethod( "SoftFP_Convert_DoubleToUnsignedInt" )] internal static uint DoubleToUnsignedInt( double val , bool fOverflow ) { DoubleImplementation di = new DoubleImplementation( val ); return di.ToUnsignedInt( fOverflow ); } //--// [TS.WellKnownMethod( "SoftFP_Convert_FloatToLong" )] internal static long FloatToLong( float val , bool fOverflow ) { FloatImplementation fi = new FloatImplementation( val ); return fi.ToLong( fOverflow ); } [TS.WellKnownMethod( "SoftFP_Convert_FloatToUnsignedLong" )] internal static ulong FloatToUnsignedLong( float val , bool fOverflow ) { FloatImplementation fi = new FloatImplementation( val ); return fi.ToUnsignedLong( fOverflow ); } [TS.WellKnownMethod( "SoftFP_Convert_DoubleToLong" )] internal static long DoubleToLong( double val , bool fOverflow ) { DoubleImplementation di = new DoubleImplementation( val ); return di.ToLong( fOverflow ); } [TS.WellKnownMethod( "SoftFP_Convert_DoubleToUnsignedLong" )] internal static ulong DoubleToUnsignedLong( double val , bool fOverflow ) { DoubleImplementation di = new DoubleImplementation( val ); return di.ToUnsignedLong( fOverflow ); } } } ================================================ FILE: Zelig/Zelig/RunTime/Zelig/Kernel/Helpers/DoubleImplementation.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // namespace Microsoft.Zelig.Runtime.Helpers { using System; using System.Runtime.CompilerServices; using TS = Microsoft.Zelig.Runtime.TypeSystem; internal struct DoubleImplementation { const int c_Mantissa_Size = 53; const int c_Mantissa_Shift = 64 - c_Mantissa_Size; const int c_Mantissa_Range = 63; const ulong c_Mantissa_One = (1ul << c_Mantissa_Range); const int c_Exponent_Size = 11; const uint c_Exponent_Mask = (1u << c_Exponent_Size) - 1; const int c_Exponent_Shift = 32 - c_Exponent_Size - 1; const int c_Exponent_Bias = (1 << c_Exponent_Size) / 2 - 1; const int c_Sign_Shift = 32 - 1; const uint c_Sign_Mask = 1u; // // State // internal ulong m_mantissa; internal int m_exponent; internal uint m_sign; //// internal bool m_fFinite; // // Constructor Methods // //[Inline] internal unsafe DoubleImplementation( double val ) { ulong rawVal = *(ulong*)&val; m_exponent = (int)((MathImpl.ExtractHighPart( rawVal ) >> c_Exponent_Shift) & c_Exponent_Mask) - c_Exponent_Bias; m_sign = MathImpl.ExtractHighPart( rawVal ) >> c_Sign_Shift; ulong mantissa = rawVal << c_Mantissa_Shift; if(m_exponent > -c_Exponent_Bias) { mantissa |= c_Mantissa_One; } m_mantissa = mantissa; } //[Inline] internal DoubleImplementation( int val , bool fOverflow ) { if(val == 0) { m_mantissa = 0; m_exponent = -c_Exponent_Bias; m_sign = 0; } else { ulong valU; if(val < 0) { valU = (ulong)unchecked( (uint)-val ); m_sign = c_Sign_Mask; } else { valU = (ulong)unchecked( (uint)val ); m_sign = 0; } m_exponent = c_Mantissa_Range; m_mantissa = 0; //--// Renormalize_Range0to2( valU ); } } //[Inline] internal DoubleImplementation( uint val , bool fOverflow ) { m_sign = 0; if(val == 0) { m_mantissa = 0; m_exponent = -c_Exponent_Bias; } else { m_exponent = c_Mantissa_Range; m_mantissa = 0; //--// Renormalize_Range0to2( (ulong)val ); } } //[Inline] internal DoubleImplementation( long val , bool fOverflow ) { if(val == 0) { m_mantissa = 0; m_exponent = -c_Exponent_Bias; m_sign = 0; } else { ulong valU; if(val < 0) { valU = unchecked( (ulong)-val ); m_sign = c_Sign_Mask; } else { valU = unchecked( (ulong)val ); m_sign = 0; } m_exponent = c_Mantissa_Range; m_mantissa = 0; //--// Renormalize_Range0to2( valU ); } } //[Inline] internal DoubleImplementation( ulong val , bool fOverflow ) { m_sign = 0; if(val == 0) { m_mantissa = 0; m_exponent = -c_Exponent_Bias; } else { m_exponent = c_Mantissa_Range; m_mantissa = 0; //--// Renormalize_Range0to2( val ); } } //[Inline] internal DoubleImplementation( ref FloatImplementation fi , bool fOverflow ) { m_mantissa = MathImpl.InsertHighPart( fi.m_mantissa ); m_exponent = fi.m_exponent; m_sign = fi.m_sign; } // // Helper Methods // [Inline] internal void Negate() { m_sign ^= c_Sign_Mask; } //[Inline] internal int Compare( ref DoubleImplementation right ) { int dir = (this.m_sign != 0) ? -1 : 1; if(this.m_sign != right.m_sign) { return dir; } else { int diff = (this.m_exponent - right.m_exponent); if(diff == 0) { return dir * this.m_mantissa.CompareTo( right.m_mantissa ); } else if(diff > 0) { return dir; } else { return -dir; } } } //[Inline] internal void Add( ref DoubleImplementation right ) { if(this.m_sign != right.m_sign) { DoubleImplementation tmp = right; tmp.Negate(); Sub( ref tmp ); } else { int diff = (this.m_exponent - right.m_exponent); ulong tmp; // // Shift down to prevent overflow. // ulong valLeft = this .m_mantissa >> 1; ulong valRight = right.m_mantissa >> 1; if(diff == 0) { tmp = valLeft + valRight; } else if(diff > 0) { if(diff <= c_Mantissa_Range) { tmp = valLeft + (valRight >> diff); } else { // // Too small, nothing to do. // tmp = valLeft; } } else { diff = -diff; this.m_exponent = right.m_exponent; if(diff <= c_Mantissa_Range) { tmp = valRight += (valLeft >> diff); } else { // // Too small, nothing to do. // tmp = valRight; } } this.m_exponent++; //This accounts for the right shift to avoid overflow. Renormalize_Range0to2( tmp ); } } //[Inline] internal void Sub( ref DoubleImplementation right ) { if(this.m_sign != right.m_sign) { DoubleImplementation tmp = right; tmp.Negate(); Add( ref tmp ); } else { int diff = (this.m_exponent - right.m_exponent); ulong tmp; ulong valLeft = this .m_mantissa; ulong valRight = right.m_mantissa; if(diff == 0) { if(valLeft >= valRight) { tmp = valLeft - valRight; } else { this.Negate(); tmp = valRight - valLeft; } } else if(diff > 0) { if(diff <= c_Mantissa_Range) { tmp = valLeft - (valRight >> diff); } else { // // Too small, nothing to do. // tmp = valLeft; } } else { diff = -diff; this.Negate(); this.m_exponent = right.m_exponent; if(diff <= c_Mantissa_Range) { tmp = valRight - (valLeft >> diff); } else { // // Too small, nothing to do. // tmp = valRight; } } Renormalize_Range0to2( tmp ); } } //[Inline] internal void Mul( ref DoubleImplementation right ) { this.m_sign ^= right.m_sign; this.m_exponent += right.m_exponent; ulong tmp; tmp = MathImpl.ExtractHighPart( this .m_mantissa ); tmp *= MathImpl.ExtractHighPart( right.m_mantissa ); if(MathImpl.ExtractLowPart( this.m_mantissa ) != 0) { ulong tmp2; tmp2 = MathImpl.ExtractLowPart ( this .m_mantissa ); tmp2 *= MathImpl.ExtractHighPart( right.m_mantissa ); tmp += (tmp2 >> 32); } if(MathImpl.ExtractLowPart( right.m_mantissa ) != 0) { ulong tmp2; tmp2 = MathImpl.ExtractHighPart( this .m_mantissa ); tmp2 *= MathImpl.ExtractLowPart ( right.m_mantissa ); tmp += (tmp2 >> 32); } // // Result will be between 0x4000_0000_0000_0000 (1.0) and 0xFFFF_FFFE_0000_0001 (<4.0). // if(MathImpl.IsNegative( tmp )) // It means it's more than 2.0. { this.m_mantissa = tmp; this.m_exponent += 1; } else { this.m_mantissa = tmp << 1; } } //[Inline] internal void Div( ref DoubleImplementation right ) { this.m_sign ^= right.m_sign; this.m_exponent -= right.m_exponent; ulong tmp; // // BUGBUG: We need to use 64x64 division, not 64x32. // tmp = this .m_mantissa ; tmp /= MathImpl.ExtractHighPart( right.m_mantissa ); // // Result will be between 0x4000_0000 (0.5) and 0xFFFF_FFFF (~2.0). // Renormalize_Range0to2( tmp << 31 ); } //--// //[Inline] internal unsafe double ToDouble() { if(m_mantissa == 0) { m_exponent = -c_Exponent_Bias; } uint rawValHigh; ulong rawVal; rawVal = (m_mantissa & ~c_Mantissa_One ) >> c_Mantissa_Shift; rawValHigh = ((uint)(m_exponent + c_Exponent_Bias) & c_Exponent_Mask) << c_Exponent_Shift; rawValHigh |= m_sign << c_Sign_Shift; rawVal |= MathImpl.InsertHighPart( rawValHigh ); return *(double*)&rawVal; } //[Inline] internal unsafe int ToInt( bool fOverflow ) { ulong val = m_mantissa; int rightShift = c_Mantissa_Range - m_exponent; if(rightShift < 0) { if(fOverflow) { throw new OverflowException(); } val = 0xFFFFFFFFu; } else { if(rightShift > c_Mantissa_Range) { val = 0; } else { val >>= rightShift; } } if(m_sign != 0) { return -(int)val; } else { return (int)val; } } //[Inline] internal unsafe uint ToUnsignedInt( bool fOverflow ) { ulong val = m_mantissa; int rightShift = c_Mantissa_Range - m_exponent; if(rightShift < 0) { if(fOverflow) { throw new OverflowException(); } val = 0xFFFFFFFFu; } else { if(rightShift > c_Mantissa_Range) { val = 0; } else { val >>= rightShift; } } if(m_sign != 0) { return (uint)-(long)val; } else { return (uint)val; } } //[Inline] internal unsafe long ToLong( bool fOverflow ) { ulong val = m_mantissa; int rightShift = c_Mantissa_Range - m_exponent; if(rightShift < 0) { int leftShift = -rightShift; if(leftShift > c_Mantissa_Range) { if(fOverflow) { throw new OverflowException(); } val = 0xFFFFFFFFFFFFFFFFu; } else { val <<= leftShift; } } else if(rightShift > 0) { if(rightShift > c_Mantissa_Range) { val = 0; } else { val >>= (rightShift - 1); val += 1; val >>= 1; } } if(m_sign != 0) { return -(long)val; } else { return (long)val; } } //[Inline] internal unsafe ulong ToUnsignedLong( bool fOverflow ) { ulong val = m_mantissa; int rightShift = c_Mantissa_Range - m_exponent; if(rightShift < 0) { int leftShift = -rightShift; if(leftShift > c_Mantissa_Range) { if(fOverflow) { throw new OverflowException(); } val = 0xFFFFFFFFFFFFFFFFu; } else { val <<= leftShift; } } else if(rightShift > 0) { if(rightShift > c_Mantissa_Range) { val = 0; } else { val >>= (rightShift - 1); val += 1; val >>= 1; } } if(m_sign != 0) { return (ulong)-(long)val; } else { return val; } } //--// [Inline] private void Renormalize_Range0to2( ulong val ) { if(val == 0) { m_mantissa = 0; m_exponent = 0; } else { while(MathImpl.IsPositive( val )) // Less than 1. { val *= 2; m_exponent--; } m_mantissa = val; } } // // Access Methods // internal bool IsFinite { get { throw new NotImplementedException(); } } } } ================================================ FILE: Zelig/Zelig/RunTime/Zelig/Kernel/Helpers/FloatImplementation.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // namespace Microsoft.Zelig.Runtime.Helpers { using System; using System.Runtime.CompilerServices; using TS = Microsoft.Zelig.Runtime.TypeSystem; internal struct FloatImplementation { const int c_Mantissa_Size = 24; const int c_Mantissa_Shift = 32 - c_Mantissa_Size; const int c_Mantissa_Range = 31; const uint c_Mantissa_One = (1u << c_Mantissa_Range); const int c_Exponent_Size = 8; const uint c_Exponent_Mask = (1u << c_Exponent_Size) - 1; const int c_Exponent_Shift = 32 - c_Exponent_Size - 1; const int c_Exponent_Bias = (1 << c_Exponent_Size) / 2 - 1; const int c_Sign_Shift = 32 - 1; const uint c_Sign_Mask = 1u; // // State // internal uint m_mantissa; internal int m_exponent; internal uint m_sign; //// internal bool m_fFinite; // // Constructor Methods // //[Inline] internal unsafe FloatImplementation( float val ) { uint rawVal = *(uint*)&val; m_exponent = (int)((rawVal >> c_Exponent_Shift) & c_Exponent_Mask) - c_Exponent_Bias; m_sign = rawVal >> c_Sign_Shift; uint mantissa = rawVal << c_Mantissa_Shift; if(m_exponent > -c_Exponent_Bias) { mantissa |= c_Mantissa_One; } m_mantissa = mantissa; } //[Inline] internal FloatImplementation( int val , bool fOverflow ) { if(val == 0) { m_mantissa = 0; m_exponent = -c_Exponent_Bias; m_sign = 0; } else { uint valU; if(val < 0) { valU = unchecked( (uint)-val ); m_sign = c_Sign_Mask; } else { valU = unchecked( (uint)val ); m_sign = 0; } m_exponent = c_Mantissa_Range; m_mantissa = 0; //--// Renormalize_Range0to2( valU ); } } //[Inline] internal FloatImplementation( uint val , bool fOverflow ) { m_sign = 0; if(val == 0) { m_mantissa = 0; m_exponent = -c_Exponent_Bias; } else { m_exponent = c_Mantissa_Range; m_mantissa = 0; //--// Renormalize_Range0to2( val ); } } //[Inline] internal FloatImplementation( long val , bool fOverflow ) { if(val == 0) { m_mantissa = 0; m_exponent = -c_Exponent_Bias; m_sign = 0; } else { ulong valU; if(val < 0) { valU = unchecked( (ulong)-val ); m_sign = c_Sign_Mask; } else { valU = unchecked( (ulong)val ); m_sign = 0; } m_exponent = c_Mantissa_Range; m_mantissa = 0; //--// while(MathImpl.IsNegative( valU )) // It means it's more than one. { valU >>= 1; m_exponent += 1; } Renormalize_Range0to2( (uint)valU ); } } //[Inline] internal FloatImplementation( ulong val , bool fOverflow ) { m_sign = 0; if(val == 0) { m_mantissa = 0; m_exponent = -c_Exponent_Bias; } else { m_exponent = c_Mantissa_Range; m_mantissa = 0; //--// while(MathImpl.IsNegative( val )) // It means it's more than one. { val >>= 1; m_exponent += 1; } Renormalize_Range0to2( (uint)val ); } } //[Inline] internal FloatImplementation( ref DoubleImplementation di , bool fOverflow ) { m_mantissa = (uint)(di.m_mantissa >> 32); m_exponent = di.m_exponent; m_sign = di.m_sign; if(m_exponent > c_Exponent_Bias) { if(fOverflow) { throw new OverflowException(); } m_exponent = c_Exponent_Bias; m_mantissa = 0xFFFFFFFFu; } else if(m_exponent < -c_Exponent_Bias) { m_exponent = 0; m_mantissa = c_Mantissa_One; } } // // Helper Methods // [Inline] internal void Negate() { m_sign ^= c_Sign_Mask; } //[Inline] internal int Compare( ref FloatImplementation right ) { int dir = (this.m_sign != 0) ? -1 : 1; if(this.m_sign != right.m_sign) { return dir; } else { int diff = (this.m_exponent - right.m_exponent); if(diff == 0) { return dir * this.m_mantissa.CompareTo( right.m_mantissa ); } else if(diff > 0) { return dir; } else { return -dir; } } } //[Inline] internal void Add( ref FloatImplementation right ) { if(this.m_sign != right.m_sign) { FloatImplementation tmp = right; tmp.Negate(); Sub( ref tmp ); } else { int diff = (this.m_exponent - right.m_exponent); ulong tmp; if(diff == 0) { tmp = this .m_mantissa; tmp += right.m_mantissa; } else if(diff > 0) { if(diff <= c_Mantissa_Range) { tmp = this .m_mantissa; tmp += (right.m_mantissa >> diff); } else { // // Too small, nothing to do. // tmp = this.m_mantissa; } } else { diff = -diff; this.m_exponent = right.m_exponent; if(diff <= c_Mantissa_Range) { tmp = right.m_mantissa; tmp += (this .m_mantissa >> diff); } else { // // Too small, nothing to do. // tmp = right.m_mantissa; } } Renormalize_Range1to4( tmp ); } } //[Inline] internal void Sub( ref FloatImplementation right ) { if(this.m_sign != right.m_sign) { FloatImplementation tmp = right; tmp.Negate(); Add( ref tmp ); } else { int diff = (this.m_exponent - right.m_exponent); uint tmp; if(diff == 0) { if(this.m_mantissa >= right.m_mantissa) { tmp = this .m_mantissa; tmp -= right.m_mantissa; } else { this.Negate(); tmp = right.m_mantissa; tmp -= this .m_mantissa; } } else if(diff > 0) { if(diff <= c_Mantissa_Range) { tmp = this .m_mantissa; tmp -= (right.m_mantissa >> diff); } else { // // Too small, nothing to do. // tmp = this.m_mantissa; } } else { diff = -diff; this.Negate(); this.m_exponent = right.m_exponent; if(diff <= c_Mantissa_Range) { tmp = right.m_mantissa; tmp -= (this .m_mantissa >> diff); } else { // // Too small, nothing to do. // tmp = right.m_mantissa; } } Renormalize_Range0to2( tmp ); } } //[Inline] internal void Mul( ref FloatImplementation right ) { this.m_sign ^= right.m_sign; this.m_exponent += right.m_exponent; ulong tmp; tmp = (ulong)this .m_mantissa; tmp *= (ulong)right.m_mantissa; // // Result will be between 0x4000_0000_0000_0000 (1.0) and 0xFFFF_FFFE_0000_0001 (<4.0). // if(MathImpl.IsNegative( tmp )) // It means it's more than 2.0. { this.m_mantissa = (uint)(tmp >> (c_Mantissa_Range+1)); this.m_exponent += 1; } else { this.m_mantissa = (uint)(tmp >> c_Mantissa_Range); } } //[Inline] internal void Div( ref FloatImplementation right ) { this.m_sign ^= right.m_sign; this.m_exponent -= right.m_exponent; ulong tmp; tmp = ((ulong)this .m_mantissa) << 31; tmp /= (ulong)right.m_mantissa; // // Result will be between 0x4000_0000 (0.5) and 0xFFFF_FFFF (~2.0). // Renormalize_Range0to2( (uint)tmp ); } //--// //[Inline] internal unsafe float ToFloat() { if(m_mantissa == 0) { m_exponent = -c_Exponent_Bias; } uint rawVal; rawVal = (m_mantissa & ~c_Mantissa_One ) >> c_Mantissa_Shift; rawVal |= ((uint)(m_exponent + c_Exponent_Bias) & c_Exponent_Mask) << c_Exponent_Shift; rawVal |= m_sign << c_Sign_Shift; return *(float*)&rawVal; } //[Inline] internal unsafe int ToInt( bool fOverflow ) { uint val = m_mantissa; int rightShift = c_Mantissa_Range - m_exponent; if(rightShift < 0) { if(fOverflow) { throw new OverflowException(); } val = 0xFFFFFFFFu; } else { if(rightShift > c_Mantissa_Range) { val = 0; } else { val >>= rightShift; } } if(m_sign != 0) { return -(int)val; } else { return (int)val; } } //[Inline] internal unsafe uint ToUnsignedInt( bool fOverflow ) { uint val = m_mantissa; int rightShift = c_Mantissa_Range - m_exponent; if(rightShift < 0) { if(fOverflow) { throw new OverflowException(); } val = 0xFFFFFFFFu; } else { if(rightShift > c_Mantissa_Range) { val = 0; } else { val >>= rightShift; } } if(m_sign != 0) { return (uint)(-(long)val); } else { return (uint)val; } } //[Inline] internal unsafe long ToLong( bool fOverflow ) { ulong val = m_mantissa; int rightShift = c_Mantissa_Range - m_exponent; if(rightShift < 0) { int leftShift = -rightShift; if(leftShift > c_Mantissa_Range) { if(fOverflow) { throw new OverflowException(); } val = 0xFFFFFFFFFFFFFFFFu; } else { val <<= leftShift; } } else if(rightShift > 0) { if(rightShift > c_Mantissa_Range) { val = 0; } else { val >>= (rightShift - 1); val += 1; val >>= 1; } } if(m_sign != 0) { return -(long)val; } else { return (long)val; } } //[Inline] internal unsafe ulong ToUnsignedLong( bool fOverflow ) { ulong val = m_mantissa; int rightShift = c_Mantissa_Range - m_exponent; if(rightShift < 0) { int leftShift = -rightShift; if(leftShift > c_Mantissa_Range) { if(fOverflow) { throw new OverflowException(); } val = 0xFFFFFFFFFFFFFFFFu; } else { val <<= leftShift; } } else if(rightShift > 0) { if(rightShift > c_Mantissa_Range) { val = 0; } else { val >>= (rightShift - 1); val += 1; val >>= 1; } } if(m_sign != 0) { return (ulong)(-(long)val); } else { return val; } } //--// [Inline] private void Renormalize_Range1to4( ulong val ) { if((uint)(val >> 32) != 0) // It means it's more than one. { m_mantissa = (uint)(val >> 1); m_exponent += 1; } else { m_mantissa = (uint)val; } } [Inline] private void Renormalize_Range0to2( uint val ) { if(val == 0) { m_mantissa = 0; m_exponent = 0; } else { while(val < c_Mantissa_One) { val *= 2; m_exponent--; } m_mantissa = val; } } // // Access Methods // internal bool IsFinite { get { throw new NotImplementedException(); } } } } ================================================ FILE: Zelig/Zelig/RunTime/Zelig/Kernel/Helpers/UnaryOperations.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // namespace Microsoft.Zelig.Runtime.Helpers { using System; using System.Runtime.CompilerServices; using TS = Microsoft.Zelig.Runtime.TypeSystem; internal static class UnaryOperations { [TS.WellKnownMethod( "SoftFP_UnaryOperations_FloatNeg" )] internal static float FloatNeg( float val ) { FloatImplementation fiVal = new FloatImplementation( val ); fiVal.Negate(); return fiVal.ToFloat(); } [TS.WellKnownMethod( "SoftFP_UnaryOperations_FloatFinite" )] internal static float FloatFinite( float val ) { FloatImplementation fiVal = new FloatImplementation( val ); if(fiVal.IsFinite == false) { throw new NotFiniteNumberException(); } return val; } //--// [TS.WellKnownMethod( "SoftFP_UnaryOperations_DoubleNeg" )] internal static double DoubleNeg( double val ) { DoubleImplementation diVal = new DoubleImplementation( val ); diVal.Negate(); return diVal.ToDouble(); } [TS.WellKnownMethod( "SoftFP_UnaryOperations_DoubleFinite" )] internal static double DoubleFinite( double val ) { DoubleImplementation diVal = new DoubleImplementation( val ); if(diVal.IsFinite == false) { throw new NotFiniteNumberException(); } return val; } } } ================================================ FILE: Zelig/Zelig/RunTime/Zelig/Kernel/Kernel.csproj ================================================  Debug AnyCPU 9.0.21022 2.0 {186F31A3-EF89-4A25-B2D5-20060509AA01} Library Properties Microsoft.Zelig.Runtime Microsoft.Zelig.Runtime $(LlilumBuildRoot)\Host\obj\$(MSBuildProjectName)\ v4.5 true full false $(LlilumBuildRoot)\Host\bin\$(Configuration)\ DEBUG;TRACE prompt 4 true true true AllRules.ruleset AnyCPU false pdbonly true $(LlilumBuildRoot)\Host\bin\$(Configuration)\ TRACE prompt 4 true true true AllRules.ruleset AnyCPU false true full false $(LlilumBuildRoot)\Host\bin\$(Configuration)\ TRACE;DEBUG AnyCPU true true true false {186F31A3-EF89-4A25-B2D5-20070519AA01} ArmProcessor False {46478CA2-8163-47A0-8C65-3ACFC21CE57F} Win32Processor False {186F31A3-EF89-4A25-B2D5-20060501AA01} mscorlib False {186F31A3-EF89-4A25-B2D5-20070702AA01} system False {186F31A3-EF89-4A25-B2D5-20061218AA01} Common False {186F31A3-EF89-4A25-B2D5-20060720AA01} TypeSystem False {d68ee51b-a898-4a77-97d8-c61254cac122} Microsoft.Llilum.Devices {dc8c38d7-780b-4b13-8ace-9050e39cc51c} Windows 3.5 ================================================ FILE: Zelig/Zelig/RunTime/Zelig/Kernel/ManagedHeap/BrickTable.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // namespace Microsoft.Zelig.Runtime { using System; using System.Runtime.CompilerServices; using TS = Microsoft.Zelig.Runtime.TypeSystem; // BrickTable is a helper used by the mark and sweep GC to map an internal pointer to a known // heap object pointer. It works by dividing all the heaps into multiple pages of size c_PageSize, and // mapping each page to a short in m_bricks. The short value indicates the offset from the beginning // of the page to the first valid heap object in that page, or, in the case where the beginning of // the page is at the middle of a valid heap object, the offset (which will be negative) to that heap // object. // // For example: // (Assume the page size is 10 for the purpose of this example and easy math) // // 0 1 2 3 // Addr: 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 // Heap: [Free][HeapObj1][HeapObj2 ][Free ] // Pages: [ 3 ][ -2 ][ -12 ][ uninit ] // public class BrickTable { private const uint c_PageSize = 2048; private const int c_BrickEncoding_Uninitialized = 0x33; private const int c_BrickEncoding_MaxBacktrackingOffset = short.MinValue; private const int c_BrickEncoding_SafeBacktrackingOffset = c_BrickEncoding_MaxBacktrackingOffset / 2; // // State // private uint m_lowestAddress; private uint m_maxRelativeAddress; private short[] m_bricks; // // Helper Methods // public void Initialize( uint lowestAddress , uint highestAddress ) { uint numPages = ((highestAddress - lowestAddress) / c_PageSize); // // Allocate one extra page, to make it easier to deal with corner cases. // numPages = AddressMath.AlignToWordBoundary( numPages + 1 ); // // Important: initialize the address range last, because the allocation of the array will cause an invocation of MarkObject. // m_bricks = new short[numPages]; m_lowestAddress = lowestAddress; m_maxRelativeAddress = highestAddress - lowestAddress; } [TS.WellKnownMethod( "DebugBrickTable_Reset" )] public unsafe void Reset() { ArrayImpl array = ArrayImpl.CastAsArray( m_bricks ); uint* start = array.GetDataPointer (); uint* end = array.GetEndDataPointer(); Memory.Fill( (byte*)start, (int)(end - start) * sizeof(uint), c_BrickEncoding_Uninitialized ); } [DisableBoundsChecks(ApplyRecursively=true)] [DisableNullChecks (ApplyRecursively=true)] [TS.WellKnownMethod( "DebugBrickTable_MarkObject" )] public unsafe void MarkObject( UIntPtr objectPtr , uint objectSize ) { uint address = objectPtr.ToUInt32(); uint relAddress = address - m_lowestAddress; if(relAddress < m_maxRelativeAddress) { int startOffset = (int)(relAddress % c_PageSize); short* ptr = GetPagePointer( relAddress ); short* endPagePtr = GetPagePointer( relAddress + objectSize - 1 ); // // Only update if the new pointer is lower than the previous one. // This automatically covers the case of an uninitialized brick. // { int value = *ptr; if(value > startOffset) { *ptr = (short)startOffset; } } // // If an object straddles more than one page, mark all the covered pages with a backtrack marker. // while(++ptr <= endPagePtr) { startOffset -= (int)c_PageSize; // // Limit offset to fit in the brick slot. // if(startOffset <= c_BrickEncoding_MaxBacktrackingOffset) { startOffset = c_BrickEncoding_MaxBacktrackingOffset; } *ptr = (short)startOffset; } } } [DisableBoundsChecks(ApplyRecursively=true)] [DisableNullChecks (ApplyRecursively=true)] [TS.WellKnownMethod( "DebugBrickTable_FindLowerBoundForObjectPointer" )] public unsafe UIntPtr FindLowerBoundForObjectPointer( UIntPtr interiorPtr ) { uint address = interiorPtr.ToUInt32(); uint relAddress = address - m_lowestAddress; if(relAddress < m_maxRelativeAddress) { uint page = relAddress / c_PageSize; fixed(short* firstPagePtr = &m_bricks[0]) { short* ptr = &firstPagePtr[page]; uint pageAddress = m_lowestAddress + page * c_PageSize; while(firstPagePtr <= ptr) { int value = *ptr; // // Offset too large, move by a few pages and retry. // if(value < c_BrickEncoding_SafeBacktrackingOffset) { ptr += c_BrickEncoding_SafeBacktrackingOffset / c_PageSize; pageAddress = (uint)(pageAddress + c_BrickEncoding_SafeBacktrackingOffset); continue; } if(value > c_PageSize) { break; } uint firstAddress = (uint)(pageAddress + value); if(firstAddress <= address) { return new UIntPtr( firstAddress ); } // // The interior pointer is less than the first object's address, // it could be pointing into an object from the previous page. // ptr -= 1; pageAddress -= c_PageSize; } } } return UIntPtr.Zero; } [Inline] private unsafe short* GetPagePointer( uint relAddress ) { uint startPage = relAddress / c_PageSize; fixed(short* startPagePtr = &m_bricks[startPage]) { return startPagePtr; } } // // Access Methods // public static extern BrickTable Instance { [SingletonFactory()] [MethodImpl( MethodImplOptions.InternalCall )] get; } } } ================================================ FILE: Zelig/Zelig/RunTime/Zelig/Kernel/ManagedHeap/Finalizer.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // namespace Microsoft.Zelig.Runtime { using System; using System.Threading; using TS = Microsoft.Zelig.Runtime.TypeSystem; public class Finalizer { internal class Tracker { [TS.GarbageCollectionExtension(typeof(Tracker))] class Handler : GarbageCollectionExtensionHandler { // // State // KernelList< Tracker > m_workList; Thread m_worker; bool m_fNewItems; // // Helper Methods // public override void Initialize() { m_workList = new KernelList< Tracker >(); m_worker = new Thread( Worker ); } public override void StartOfMarkPhase( GarbageCollectionManager gc ) { } public override void Mark( GarbageCollectionManager gc , object target ) { } public override void EndOfMarkPhase( GarbageCollectionManager gc ) { } public override void StartOfSweepPhase( GarbageCollectionManager gc ) { var node = s_list.StartOfForwardWalk; while(node.IsValidForForwardMove) { var nextNode = node.Next; var ptr = node.Target; var target = ptr.m_target; if(!gc.IsMarked( target )) { if(ptr.m_fFinalized) { // // Already finalized, drop the tracker. // node.RemoveFromList(); } else { // // Keep target alive and move the tracker to the work list. // gc.ExtendMarking( target ); ptr.m_targetKeepAlive = target; ptr.m_fFinalized = true; m_workList.InsertAtTail( node ); m_fNewItems = true; } } node = nextNode; } } public override void Sweep( GarbageCollectionManager gc , object target ) { } public override void EndOfSweepPhase( GarbageCollectionManager gc ) { } public override void RestartExecution() { if(m_fNewItems) { m_fNewItems = false; s_notifyStop .Reset(); s_notifyStart.Set (); if(m_worker.IsAlive == false) { m_worker.Start(); } } } //--// void Worker() { while(true) { s_notifyStart.WaitOne(); var node = m_workList.StartOfForwardWalk; while(node.IsValidForForwardMove) { var nextNode = node.Next; // // Add the tracker back to the normal list, it will be reclaimed on the next GC cycle. // lock(s_list) { s_list.InsertAtTail( node ); } var ptr = node.Target; var obj = (ObjectImpl)ptr.m_targetKeepAlive; ptr.m_targetKeepAlive = null; obj.FinalizeImpl(); node = nextNode; } s_notifyStop.Set(); } } } // // State // readonly KernelNode< Tracker > m_node; [TS.SkipDuringGarbageCollection] readonly object m_target; object m_targetKeepAlive; bool m_fFinalized; // // Constructor Methods // internal Tracker( object obj ) { m_node = new KernelNode< Tracker >( this ); m_target = obj; } // // Helper Methods // internal static void Allocate( object obj ) { var tracker = new Tracker( obj ); lock(s_list) { s_list.InsertAtTail( tracker.m_node ); } } internal static void SetFinalizationFlag( object obj , bool val ) { lock(s_list) { for(var node = s_list.StartOfForwardWalk; node.IsValidForForwardMove; node = node.Next) { var ptr = node.Target; if(ptr.m_target == obj) { ptr.m_fFinalized = val; return; } } } } } // // State // static readonly KernelList< Tracker> s_list = new KernelList< Tracker >(); static readonly AutoResetEvent s_notifyStart = new AutoResetEvent ( false ); static readonly ManualResetEvent s_notifyStop = new ManualResetEvent( true ); // // Helper Methods // [TS.WellKnownMethod( "Finalizer_Allocate" )] internal static void Allocate( object obj ) { Tracker.Allocate( obj ); } internal static void WaitForPendingFinalizers() { s_notifyStop.WaitOne(); } internal static void SuppressFinalize( object obj ) { Tracker.SetFinalizationFlag( obj, true ); } internal static void ReRegisterForFinalize( object obj ) { Tracker.SetFinalizationFlag( obj, false ); } } } ================================================ FILE: Zelig/Zelig/RunTime/Zelig/Kernel/ManagedHeap/GarbageCollectionExtensionHandler.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // namespace Microsoft.Zelig.Runtime { using System; using TS = Microsoft.Zelig.Runtime.TypeSystem; public abstract class GarbageCollectionExtensionHandler { // // Helper Methods. // public virtual void Initialize() { } public abstract void StartOfMarkPhase( GarbageCollectionManager gc ); public abstract void Mark( GarbageCollectionManager gc , object target ); public abstract void EndOfMarkPhase( GarbageCollectionManager gc ); public abstract void StartOfSweepPhase( GarbageCollectionManager gc ); public abstract void Sweep( GarbageCollectionManager gc , object target ); public abstract void EndOfSweepPhase( GarbageCollectionManager gc ); public virtual void RestartExecution() { } // // Access Methods // } } ================================================ FILE: Zelig/Zelig/RunTime/Zelig/Kernel/ManagedHeap/MemoryFreeBlock.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // // Enable this macro to shift object pointers from the beginning of the header to the beginning of the payload. #define CANONICAL_OBJECT_POINTERS namespace Microsoft.Zelig.Runtime { using System; using TS = Microsoft.Zelig.Runtime.TypeSystem; [TS.DisableAutomaticReferenceCounting] public unsafe struct MemoryFreeBlock { // // State // public MemoryFreeBlock* Next; public MemoryFreeBlock* Previous; // // Helper Methods. // [Inline] public byte[] Pack() { fixed(MemoryFreeBlock* ptr = &this) { return CastAsArray( AddressMath.Decrement( new UIntPtr( ptr ), PointerOffset ) ); } } public static MemoryFreeBlock* Unpack( byte[] ptr ) { ArrayImpl array = ArrayImpl.CastAsArray( ptr ); return (MemoryFreeBlock*)array.GetDataPointer(); } [TS.GenerateUnsafeCast] private extern static byte[] CastAsArray( UIntPtr ptr ); //--// public uint Size() { byte[] array = Pack(); return (uint)array.Length + FixedSize(); } public ObjectHeader ToObjectHeader() { return ObjectHeader.Unpack(Pack()); } public UIntPtr ToObjectHeaderPointer() { return ToObjectHeader().ToPointer(); } [TS.WellKnownMethod("DebugGC_MemoryFreeBlock_ZeroFreeMemory")] public void ZeroFreeMemory() { byte[] array = Pack(); byte* ptr = (byte*)ArrayImpl.CastAsArray( array ).GetDataPointer(); UIntPtr start = new UIntPtr( ptr + sizeof(MemoryFreeBlock) ); UIntPtr end = new UIntPtr( ptr + array.Length ); Memory.Zero( start, end ); } [TS.WellKnownMethod("DebugGC_MemoryFreeBlock_DirtyFreeMemory")] public void DirtyFreeMemory() { byte[] array = Pack(); byte* ptr = (byte*)ArrayImpl.CastAsArray( array ).GetDataPointer(); UIntPtr start = new UIntPtr( ptr + sizeof(MemoryFreeBlock) ); UIntPtr end = new UIntPtr( ptr + array.Length ); Memory.Dirty( start, end ); } [TS.WellKnownMethod("DebugGC_MemoryFreeBlock_Allocate")] public UIntPtr Allocate( ref MemorySegment memorySegment, uint size ) { ArrayImpl array = ArrayImpl.CastAsArray( Pack() ); uint fixedSize = FixedSize(); uint numElements = (uint)array.Length; uint availableSize = numElements + fixedSize; if(size <= availableSize) { uint left = availableSize - size; numElements -= size; if(left <= MinimumSpaceRequired()) { fixed(MemoryFreeBlock* ptr = &this) { memorySegment.RemoveFreeBlock( ptr ); } ObjectHeader oh = ObjectHeader.Unpack( array ); if(MemoryManager.Configuration.TrashFreeMemory) { DirtyHeader( oh.ToPointer() ); } else { ZeroHeader( oh.ToPointer() ); } if(left > 0) { oh.InsertPlug( left ); } } else { // // Resize the array, as a way of marking memory allocation. // array.SetLength( numElements ); } UIntPtr newAllocation = new UIntPtr( (byte*)array.GetDataPointer() + numElements ); ObjectHeader.CastAsObjectHeader( newAllocation ).InitializeAllocatedRawBytes( size ); return newAllocation; } return UIntPtr.Zero; } private static uint PointerOffset { [Inline] get { #if CANONICAL_OBJECT_POINTERS return (uint)System.Runtime.InteropServices.Marshal.SizeOf(typeof(ArrayImpl)); #else // CANONICAL_OBJECT_POINTERS return FixedSize(); #endif // CANONICAL_OBJECT_POINTERS } } [Inline] public static uint FixedSize() { int size; size = System.Runtime.InteropServices.Marshal.SizeOf( typeof(ObjectHeader) ); size += System.Runtime.InteropServices.Marshal.SizeOf( typeof(ArrayImpl ) ); return (uint)size; } [Inline] public static uint MinimumSpaceRequired() { return FixedSize() + (uint)sizeof(MemoryFreeBlock); } //--// [TS.WellKnownMethod("DebugGC_MemoryFreeBlock_InitializeFromRawMemory")] public static MemoryFreeBlock* InitializeFromRawMemory( UIntPtr baseAddress, uint sizeInBytes ) { TS.VTable vTable = TS.VTable.GetFromType( typeof(byte[]) ); uint numOfElements = sizeInBytes - FixedSize(); byte[] externalRepresentation = (byte[])TypeSystemManager.Instance.InitializeArray( baseAddress, vTable, numOfElements, referenceCounting: false ); ObjectHeader oh = ObjectHeader.Unpack( externalRepresentation ); oh.MultiUseWord = (int)(ObjectHeader.GarbageCollectorFlags.FreeBlock | ObjectHeader.GarbageCollectorFlags.Unmarked); return Unpack( externalRepresentation ); } public static void ZeroHeader( UIntPtr address ) { Memory.Zero( address, AddressMath.Increment( address, MinimumSpaceRequired() ) ); } public static void DirtyHeader( UIntPtr address ) { Memory.Dirty( address, AddressMath.Increment( address, MinimumSpaceRequired() ) ); } // // Access Methods // public uint AvailableMemory { get { byte[] array = Pack(); return FixedSize() + (uint)array.Length; } } } } ================================================ FILE: Zelig/Zelig/RunTime/Zelig/Kernel/ManagedHeap/MemorySegment.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // namespace Microsoft.Zelig.Runtime { using System; using TS = Microsoft.Zelig.Runtime.TypeSystem; [TS.DisableAutomaticReferenceCounting] public unsafe struct MemorySegment { // // State // public MemorySegment* Next; public MemorySegment* Previous; public UIntPtr Beginning; public UIntPtr End; public MemoryAttributes Attributes; public MemoryFreeBlock* FirstFreeBlock; public MemoryFreeBlock* LastFreeBlock; // // Helper Methods // [TS.WellKnownMethod("DebugGC_MemorySegment_Initialize")] public void Initialize() { fixed (MemorySegment* seg = &this) { UIntPtr firstBlockPtr = this.FirstBlock; uint size = AddressMath.RangeSize(firstBlockPtr, seg->End); MemoryFreeBlock* firstBlock = MemoryFreeBlock.InitializeFromRawMemory(firstBlockPtr, size); seg->FirstFreeBlock = firstBlock; seg->LastFreeBlock = firstBlock; firstBlock->Next = null; firstBlock->Previous = null; } } public void ZeroFreeMemory() { for(MemoryFreeBlock* ptr = this.FirstFreeBlock; ptr != null; ptr = ptr->Next) { ptr->ZeroFreeMemory(); } } public void DirtyFreeMemory() { for(MemoryFreeBlock* ptr = this.FirstFreeBlock; ptr != null; ptr = ptr->Next) { ptr->DirtyFreeMemory(); } } public UIntPtr Allocate( uint size ) { for(MemoryFreeBlock* ptr = this.FirstFreeBlock; ptr != null; ptr = ptr->Next) { UIntPtr res = ptr->Allocate( ref this, size ); if(res != UIntPtr.Zero) { Log("Allocated %d bytes from free block 0x%x at 0x%x", (int)size, (int)ptr, (int)res.ToUInt32()); return res; } } return UIntPtr.Zero; } [TS.WellKnownMethod("DebugGC_MemorySegment_LinkNewFreeBlock")] public MemoryFreeBlock* LinkNewFreeBlock( UIntPtr start , UIntPtr end ) { uint size = AddressMath.RangeSize( start, end ); if(size >= MemoryFreeBlock.MinimumSpaceRequired()) { MemoryFreeBlock* ptr = MemoryFreeBlock.InitializeFromRawMemory( start, size ); if(MemoryManager.Configuration.TrashFreeMemory) { ptr->DirtyFreeMemory(); } else { ptr->ZeroFreeMemory(); } if(this.FirstFreeBlock == null) { this.FirstFreeBlock = ptr; } MemoryFreeBlock* ptrLast = this.LastFreeBlock; if(ptrLast != null) { ptrLast->Next = ptr; } this.LastFreeBlock = ptr; ptr->Previous = ptrLast; ptr->Next = null; return ptr; } else { ObjectHeader oh = ObjectHeader.CastAsObjectHeader( start ); oh.InsertPlug( size ); return null; } } public void Release(UIntPtr address) { UIntPtr newFreeBlockBaseAddress = address; uint newFreeBlockSize = ObjectHeader.CastAsObjectHeader(address).TotalSize; Log("MemorySegment(0x%x).Release - address 0x%x, size: %d", (int)this.Beginning.ToUInt32(), (int)address.ToUInt32(), (int)newFreeBlockSize); // Find the position in the FreeBlock linked list where it should go Log("Locating insertion point..."); MemoryFreeBlock* insertAfter = null; for (MemoryFreeBlock* current = this.FirstFreeBlock; current != null; current = current->Next) { UIntPtr startAddress = new UIntPtr(current); Log(" looking at FreeBlock 0x%x", (int)startAddress.ToUInt32()); if (AddressMath.IsGreaterThan(address, startAddress)) { insertAfter = current; } else { break; } } // We now have the place to insert the new free block! Log("InsertAfter FreeBlock 0x%x", (int)insertAfter); // But first, we have to see if we should merge with adjacent free blocks // instead of creating a brand new one. bool mergeWithPrevious = false; bool mergeWithNext = false; if (insertAfter != null) { ObjectHeader previousBlockObjectHeader = insertAfter->ToObjectHeader(); UIntPtr previousBlockEndAddress = previousBlockObjectHeader.GetNextObjectPointer(); Log("Comparing with previous FreeBlock baseAddress 0x%x, end 0x%x", (int)previousBlockObjectHeader.ToPointer().ToUInt32(), (int)previousBlockEndAddress.ToUInt32()); if (previousBlockEndAddress == address) { // We need to merge with the previous block newFreeBlockBaseAddress = previousBlockObjectHeader.ToPointer(); newFreeBlockSize += previousBlockObjectHeader.TotalSize; mergeWithPrevious = true; Log("Need to merge with previous block! New address 0x%x, size:%d", (int)newFreeBlockBaseAddress.ToUInt32(), (int)newFreeBlockSize); } } MemoryFreeBlock* nextBlock = (insertAfter != null) ? insertAfter->Next : this.FirstFreeBlock; if (nextBlock != null) { UIntPtr nextBlockBaseAddress = nextBlock->ToObjectHeaderPointer(); Log("Comparing with next FreeBlock 0x%x (base address 0x%x)", (int)nextBlock, (int)nextBlockBaseAddress.ToUInt32()); if (AddressMath.Increment(newFreeBlockBaseAddress, newFreeBlockSize) == nextBlockBaseAddress) { // We need to merge with the next block newFreeBlockSize += ObjectHeader.CastAsObjectHeader(nextBlockBaseAddress).TotalSize; mergeWithNext = true; Log("Need to merge with next block! New address 0x%x, size:%d", (int)newFreeBlockBaseAddress.ToUInt32(), (int)newFreeBlockSize); } } if (!mergeWithPrevious) { // Unless previous block was a free block, look for gap before the object to be deleted uint* target = (uint*)newFreeBlockBaseAddress.ToPointer(); uint* limit = (uint*)this.Beginning.ToPointer(); Log("Checking for plug gap before starting from 0x%x...", (int)target); while ((target > limit) && (*(target - 1) == (uint)ObjectHeader.GarbageCollectorFlags.GapPlug)) { target--; Log(" Found potential plug gap at 0x%x", (int)target); } // If we detect any gap plugs before the object we are freeing, we need to // walk the ObjectHeader chain to ensure that they are indeed gap plugs, rather // than valid data that just happen to look like GarbageCollectorFlags.GapPlug if (AddressMath.IsLessThan(new UIntPtr(target), newFreeBlockBaseAddress)) { UIntPtr objectPointer = (insertAfter != null) ? insertAfter->ToObjectHeader().GetNextObjectPointer() : this.FirstBlock; UIntPtr gapStart = new UIntPtr(target); Log("Verifying plug gap starting at object header address 0x%x", (int)objectPointer.ToUInt32()); while (AddressMath.IsLessThan(objectPointer, gapStart)) { ObjectHeader oh = ObjectHeader.CastAsObjectHeader(objectPointer); if (oh.GarbageCollectorStateWithoutMutableBits == ObjectHeader.GarbageCollectorFlags.GapPlug) { objectPointer = AddressMath.Increment(objectPointer, sizeof(uint)); } else { objectPointer = oh.GetNextObjectPointer(); } Log(" Next object header address 0x%x", (int)objectPointer.ToUInt32()); } // At this point, oh >= gapStart if (AddressMath.IsInRange(objectPointer, gapStart, newFreeBlockBaseAddress)) // Note, IsInRange instead of == since it's possible that some of the GapPlug markings are real data { uint gapSize = AddressMath.RangeSize(objectPointer, newFreeBlockBaseAddress); newFreeBlockBaseAddress = objectPointer; newFreeBlockSize += gapSize; Log(" Plug gap of size %d found! New address 0x%x, size:%d", (int)gapSize, (int)newFreeBlockBaseAddress.ToUInt32(), (int)newFreeBlockSize); } } } if (!mergeWithNext) { // Unless next block was a free block, look for gap after the object to be deleted uint* target = (uint*)AddressMath.Increment(newFreeBlockBaseAddress, newFreeBlockSize).ToPointer(); uint* limit = (uint*)this.End.ToPointer(); Log("Checking for plug gap after starting from 0x%x...", (int)target); while ((target < limit) && (*target == (uint)ObjectHeader.GarbageCollectorFlags.GapPlug)) { newFreeBlockSize += sizeof(uint); Log(" Found plug gap at 0x%x, new size: %d", (int)target, (int)newFreeBlockSize); target++; } } // Once we get here, we have gather all the information and have the correct newFreeBlockAddress and // newFreeBlockSize. It's now time to manipulate the free list. if (mergeWithPrevious || mergeWithNext) { // Note that in the case where mergeWithPrevious and mergeWithNext is both true // we will do both and return early. if (mergeWithNext) { // Remove the next block from the linked list, so we can add a new (combined) one later RemoveFreeBlock(nextBlock); Log("Removing next block 0x%x", (int)nextBlock); } if (mergeWithPrevious) { // Merging with previous block can be done easily by increasing the size of the previous block ArrayImpl array = ArrayImpl.CastAsArray(insertAfter->Pack()); array.SetLength(newFreeBlockSize - MemoryFreeBlock.FixedSize()); Log("Merging with previous block, new array length: %d", array.Length); return; } } if (newFreeBlockSize >= MemoryFreeBlock.MinimumSpaceRequired()) { // If the block is big enough for a MemoryFreeBlock, build one and insert it into the free list MemoryFreeBlock* newFreeBlock = MemoryFreeBlock.InitializeFromRawMemory(newFreeBlockBaseAddress, newFreeBlockSize); InsertFreeBlock(newFreeBlock, insertAfter); Log("New free block: address 0x%x (0x%x), size %d", (int)newFreeBlock, (int)newFreeBlockBaseAddress.ToUInt32(), (int)newFreeBlockSize); } else { // Otherwise, insert gap plugs instead. ObjectHeader.CastAsObjectHeader(newFreeBlockBaseAddress).InsertPlug(newFreeBlockSize); Log("Not big enough for a new free block! Insert %d bytes of gap plugs starting at address 0x%x", (int)newFreeBlockSize, (int)newFreeBlockBaseAddress.ToUInt32()); } } [TS.WellKnownMethod("DebugGC_MemorySegment_RemoveFreeBlock")] public void RemoveFreeBlock( MemoryFreeBlock* ptr ) { MemoryFreeBlock* ptrNext = ptr->Next; MemoryFreeBlock* ptrPrev = ptr->Previous; if(ptrNext != null ) ptrNext->Previous = ptrPrev; if(ptrPrev != null ) ptrPrev->Next = ptrNext; if(ptr == this.FirstFreeBlock) this.FirstFreeBlock = ptrNext; if(ptr == this.LastFreeBlock ) this.LastFreeBlock = ptrPrev; } private void InsertFreeBlock(MemoryFreeBlock* ptr, MemoryFreeBlock* insertAfter) { if (insertAfter == null) { // Insert at head ptr->Next = this.FirstFreeBlock; this.FirstFreeBlock = ptr; } else { ptr->Next = insertAfter->Next; } if (ptr->Next != null) { ptr->Next->Previous = ptr; } else { // The new block is at the end of the list this.LastFreeBlock = ptr; } ptr->Previous = insertAfter; if (ptr->Previous != null) { ptr->Previous->Next = ptr; } } [Inline] public static uint MinimumSpaceRequired() { int size; size = System.Runtime.InteropServices.Marshal.SizeOf( typeof(MemorySegment) ); size += (int)MemoryFreeBlock.MinimumSpaceRequired(); return (uint)size; } internal void ConsistencyCheck(bool dumpMemory) { if (dumpMemory) { BugCheck.Log("MemorySegment 0x%x -> 0x%x", (int)this.Beginning.ToUInt32(), (int)this.End.ToUInt32()); BugCheck.Log("FirstFreeBlock: 0x%x / LastFreeBlock: 0x%x", (int)this.FirstFreeBlock, (int)this.LastFreeBlock); } if (this.FirstFreeBlock == null) { BugCheck.Assert( this.LastFreeBlock == null, BugCheck.StopCode.HeapCorruptionDetected ); BugCheck.Assert( this.AvailableMemory == 0, BugCheck.StopCode.HeapCorruptionDetected ); } else { BugCheck.Assert( this.FirstFreeBlock->Previous == null, BugCheck.StopCode.HeapCorruptionDetected ); BugCheck.Assert( this.LastFreeBlock != null, BugCheck.StopCode.HeapCorruptionDetected ); BugCheck.Assert( this.LastFreeBlock->Next == null, BugCheck.StopCode.HeapCorruptionDetected ); // A generous estimation of how many free blocks are possible given the size of this memory segment uint maxFreeBlocksPossible = (AddressMath.RangeSize(this.FirstBlock, this.End) / MemoryFreeBlock.MinimumSpaceRequired()) + 1; if (dumpMemory) { BugCheck.Log("Walking MemoryFreeBlock..."); } uint freeBlockCount = 0; for (MemoryFreeBlock* current = this.FirstFreeBlock; current != null; current = current->Next) { if (dumpMemory) { BugCheck.Log("FreeBlock: 0x%x, prev:0x%x, next: 0x%x, size:%d", (int)current, (int)current->Previous, (int)current->Next, (int)current->Size()); } BugCheck.Assert(AddressMath.IsInRange(current->ToObjectHeaderPointer(), this.Beginning, this.End), BugCheck.StopCode.HeapCorruptionDetected); if (current->Next == null) { BugCheck.Assert(current == this.LastFreeBlock, BugCheck.StopCode.HeapCorruptionDetected); } else { BugCheck.Assert(current->Next->Previous == current, BugCheck.StopCode.HeapCorruptionDetected); BugCheck.Assert(AddressMath.IsLessThan(current->ToObjectHeaderPointer(), current->Next->ToObjectHeaderPointer()), BugCheck.StopCode.HeapCorruptionDetected); } freeBlockCount++; if (freeBlockCount == maxFreeBlocksPossible) { // We've looped too long, either the linked list is looping or something else is horribly wrong. BugCheck.Raise(BugCheck.StopCode.HeapCorruptionDetected); break; } } } if (dumpMemory) { BugCheck.Log("Walking object pointers..."); } UIntPtr objectPointer = this.FirstBlock; MemoryFreeBlock* nextExpectedFreeBlock = this.FirstFreeBlock; bool wasFreeBlock = false; bool wasGapPlug = false; while (AddressMath.IsLessThan(objectPointer, this.End)) { BugCheck.Assert(AddressMath.IsAlignedTo32bits(objectPointer), BugCheck.StopCode.HeapCorruptionDetected); ObjectHeader oh = ObjectHeader.CastAsObjectHeader(objectPointer); ObjectHeader.GarbageCollectorFlags gcFlags = oh.GarbageCollectorStateWithoutMutableBits; bool isFreeBlock = gcFlags == ObjectHeader.GarbageCollectorFlags.FreeBlock; bool isGapPlug = gcFlags == ObjectHeader.GarbageCollectorFlags.GapPlug; bool isAllocatedRawBytes = gcFlags == ObjectHeader.GarbageCollectorFlags.AllocatedRawBytes; if (dumpMemory) { int fga = 0; if (isFreeBlock) fga += 100; if (isGapPlug) fga += 10; if (isAllocatedRawBytes) fga += 1; BugCheck.Log("oh:0x%x, gcFlags:%x(fb/gp/arp:%03d), size %d", (int)objectPointer.ToUInt32(), (int)gcFlags, fga, isGapPlug ? sizeof(uint) : (int)oh.TotalSize); if (!isAllocatedRawBytes && !isFreeBlock && !isGapPlug) { var type = oh.VirtualTable.TypeInfo; if (type is TS.SzArrayReferenceTypeRepresentation) { var arrayType = (TS.SzArrayReferenceTypeRepresentation)type; BugCheck.Log("Array of:"); BugCheck.Log(arrayType.UnderlyingType.Name ?? ""); } else { BugCheck.Log(type?.Name ?? ""); } } } if (isFreeBlock) { // Ensure the current free block is in the free block list BugCheck.Assert(nextExpectedFreeBlock != null && nextExpectedFreeBlock->ToObjectHeader() == oh, BugCheck.StopCode.HeapCorruptionDetected); nextExpectedFreeBlock = nextExpectedFreeBlock->Next; } if (wasFreeBlock || wasGapPlug) { // Adjacent free blocks or free block next to gap plugs are not allowed BugCheck.Assert(!isFreeBlock, BugCheck.StopCode.HeapCorruptionDetected); } if (wasFreeBlock) { // A free block next to gap plugs is not allowed BugCheck.Assert(!isGapPlug, BugCheck.StopCode.HeapCorruptionDetected); } // Move to next object pointer if (isGapPlug) { objectPointer = AddressMath.Increment(objectPointer, sizeof(uint)); } else { objectPointer = oh.GetNextObjectPointer(); } wasFreeBlock = isFreeBlock; wasGapPlug = isGapPlug; } // Make sure we are exactly at the end of the memory segment and // we visited every free block that was in the free block list BugCheck.Assert(objectPointer == this.End, BugCheck.StopCode.HeapCorruptionDetected); BugCheck.Assert(nextExpectedFreeBlock == null, BugCheck.StopCode.HeapCorruptionDetected); if (dumpMemory) { BugCheck.Log("MemorySegment Done"); } } internal bool IsObjectAlive( UIntPtr ptr ) { UIntPtr objectPointer = this.FirstBlock; while(AddressMath.IsInRange( ptr, objectPointer, this.End )) { ObjectHeader oh = ObjectHeader.CastAsObjectHeader(objectPointer); ObjectHeader.GarbageCollectorFlags gcFlags = oh.GarbageCollectorStateWithoutMutableBits; if(ptr == objectPointer) { return ( gcFlags != ObjectHeader.GarbageCollectorFlags.FreeBlock ) && ( gcFlags != ObjectHeader.GarbageCollectorFlags.GapPlug ); } // Move to next object pointer if(gcFlags == ObjectHeader.GarbageCollectorFlags.GapPlug) { objectPointer = AddressMath.Increment( objectPointer, sizeof( uint ) ); } else { objectPointer = oh.GetNextObjectPointer( ); } } return false; } #if MEMORYSEGMENT_LOG private static void Log(string format) { BugCheck.Log(format); } private static void Log(string format, int p1) { BugCheck.Log(format, p1); } private static void Log(string format, int p1, int p2) { BugCheck.Log(format, p1, p2); } private static void Log(string format, int p1, int p2, int p3) { BugCheck.Log(format, p1, p2, p3); } private static void Log(string format, int p1, int p2, int p3, int p4) { BugCheck.Log(format, p1, p2, p3, p4); } private static void Log(string format, int p1, int p2, int p3, int p4, int p5) { BugCheck.Log(format, p1, p2, p3, p4, p5); } #else private static void Log(string format) { } private static void Log(string format, int p1) { } private static void Log(string format, int p1, int p2) { } private static void Log(string format, int p1, int p2, int p3) { } private static void Log(string format, int p1, int p2, int p3, int p4) { } private static void Log(string format, int p1, int p2, int p3, int p4, int p5) { } #endif // // Access Methods // public UIntPtr FirstBlock { get { fixed (MemorySegment* seg = &this) { return AddressMath.AlignToDWordBoundary(new UIntPtr(&seg[1])); } } } public uint AvailableMemory { get { uint total = 0; for(MemoryFreeBlock* ptr = this.FirstFreeBlock; ptr != null; ptr = ptr->Next) { total += ptr->AvailableMemory; } return total; } } public uint AllocatedMemory { get { return AddressMath.RangeSize( this.FirstBlock, this.End ) - this.AvailableMemory; } } } } ================================================ FILE: Zelig/Zelig/RunTime/Zelig/Kernel/ManagedHeap/ObjectHeader.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // // Enable this macro to shift object pointers from the beginning of the header to the beginning of the payload. #define CANONICAL_OBJECT_POINTERS #define LLVM namespace Microsoft.Zelig.Runtime { using System; using System.Runtime.InteropServices; using TS = Microsoft.Zelig.Runtime.TypeSystem; [TS.WellKnownType("Microsoft_Zelig_Runtime_ObjectHeader")] [TS.NoVTable] [TS.DisableAutomaticReferenceCounting] [TS.DisableReferenceCounting] public class ObjectHeader { // Note the GarbageCollectorMask has to be the last byte, we rely on this in GarbageCollectorState property const uint GarbageCollectorMask = 0x000000FF; const int GarbageCollectorShift = 0; const uint ExtensionKindMask = 0x00000300; const int ExtensionKindShift = 8; const uint ExtensionPayloadMask = 0x00FFFC00; const int ExtensionPayloadShift = 10; public const uint ReferenceCountMask = 0xFF000000; public const int ReferenceCountShift = 24; [Flags] public enum GarbageCollectorFlags : uint { Unmarked = 0x00000000, Marked = 0x00000001, MutableMask = 0x00000001, FreeBlock = 0 << 1, // Free block. GapPlug = 1 << 1, // Used to mark free space that cannot be reclaimed due to fragmentation. ReadOnlyObject = 2 << 1, // This object is stored in read-only memory. UnreclaimableObject = 3 << 1, // This object is stored outside the garbage-collected heap. NormalObject = 4 << 1, // Normal object. SpecialHandlerObject = 5 << 1, // This object has a GC extension handler. AllocatedRawBytes = 6 << 1, // Allocated bytes that have not been initialized yet } public enum ExtensionKinds : uint { Empty = 0, HashCode, SyncBlock, } // // State // [TS.WellKnownField( "ObjectHeader_MultiUseWord" )] public volatile int MultiUseWord; [TS.WellKnownField( "ObjectHeader_VirtualTable" )] public TS.VTable VirtualTable; // // Don't allow object creation, this is not a real class, it's more of a struct. // private ObjectHeader() { } // // Helper Methods // #if CANONICAL_OBJECT_POINTERS public ObjectImpl Pack() { UIntPtr address = AddressMath.Increment(ToPointer(), HeaderSize); return ObjectImpl.FromPointer(address); } public static ObjectHeader Unpack(object obj) { UIntPtr address = AddressMath.Decrement(((ObjectImpl)obj).ToPointer(), HeaderSize); return CastAsObjectHeader(address); } #else // CANONICAL_OBJECT_POINTERS [TS.GenerateUnsafeCast] public extern ObjectImpl Pack(); [TS.GenerateUnsafeCast] public extern static ObjectHeader Unpack( object obj ); #endif // CANONICAL_OBJECT_POINTERS [TS.GenerateUnsafeCast] public extern UIntPtr ToPointer(); [TS.GenerateUnsafeCast] public extern static ObjectHeader CastAsObjectHeader( UIntPtr ptr ); [Inline] public unsafe UIntPtr GetNextObjectPointer() { return AddressMath.Increment( ToPointer(), this.TotalSize ); } public static uint HeaderSize { [Inline] get { return (uint)System.Runtime.InteropServices.Marshal.SizeOf(typeof(ObjectHeader)); } } public uint ObjectSize { get { uint arrayLength = (uint)ArrayImpl.CastAsArray((Object)this.Pack()).Length; return ComputeObjectSize(this.VirtualTable, arrayLength); } } public uint TotalSize { get { uint size; if(this.GarbageCollectorStateWithoutMutableBits == GarbageCollectorFlags.AllocatedRawBytes) { size = this.AllocatedRawBytesSize; } else { size = HeaderSize + ObjectSize; } return size; } } public static uint ComputeObjectSize(TS.VTable vTable, uint arrayLength) { uint size = vTable.BaseSize + vTable.ElementSize * arrayLength; // Every object should have a payload if (size == 0) { size = 1; } return AddressMath.AlignToDWordBoundary(size); } [TS.WellKnownMethod("DebugGC_ObjectHeader_InsertPlug")] public unsafe void InsertPlug( uint size ) { UIntPtr address = this.ToPointer(); uint* dst = (uint*)address.ToPointer(); var bytesLeft = size; while(bytesLeft >= sizeof(uint)) { *dst++ = (uint)GarbageCollectorFlags.GapPlug; bytesLeft -= sizeof(uint); } } [Inline] public void InitializeAllocatedRawBytes( uint size ) { this.MultiUseWord = (int)GarbageCollectorFlags.AllocatedRawBytes; this.AllocatedRawBytesSize = size; } //--// public void UpdateExtension( ExtensionKinds kind, int payload ) { BugCheck.Assert( this.IsImmutable == false, BugCheck.StopCode.SyncBlockCorruption ); while(true) { var oldValue = this.MultiUseWord; uint newValue = ((uint)kind << ExtensionKindShift) | ((uint)payload << ExtensionPayloadShift) | ((uint)oldValue & GarbageCollectorMask); // CS0420: a reference to a volatile field will not be treated as volatile #pragma warning disable 420 var oldValue2 = System.Threading.Interlocked.CompareExchange( ref this.MultiUseWord, (int)newValue, oldValue ); #pragma warning restore 420 if(oldValue2 == oldValue) { break; } } } #if REFCOUNT_STAT internal static int s_RefCountedObjectsAllocated = 0; internal static int s_RefCountedObjectsFreed = 0; internal static int s_AddRefCalled = 0; internal static int s_ReleaseCalled = 0; internal static int s_NoOpAddRefCalled = 0; internal static int s_NoOpReleaseCalled = 0; internal static int s_NonRCAddRefCalled = 0; internal static int s_NonRCReleaseCalled = 0; internal static int s_LoadAndAddRefCalled = 0; internal static int s_SwapCalled = 0; // Special Non-native version of AddReference for REFCOUNT_STAT [TS.WellKnownMethod( "ObjectHeader_AddReference" )] static public void AddReference( Object obj ) { RecordAddReference( obj ); if(obj != null) { ObjectHeader oh = ObjectHeader.Unpack( obj ); if(oh.HasReferenceCount) { oh.ModifyReferenceCount( /*delta*/1 ); } } } #else //REFCOUNT_STAT [TS.WellKnownMethod( "ObjectHeader_AddReference" )] [DllImport( "C" )] static public extern void AddReference( Object obj ); #endif //REFCOUNT_STAT [DllImport( "C" )] static public extern int ReleaseReferenceNative( Object obj ); [TS.WellKnownMethod( "ObjectHeader_ReleaseReference" )] [TS.DisableAutomaticReferenceCounting] static public void ReleaseReference( Object obj ) { #if REFCOUNT_STAT RecordReleaseReference( obj ); #endif //REFCOUNT_STAT if(ReleaseReferenceNative( obj ) == 0) { ThreadImpl.CurrentThread.ReleaseReference.DeleteObject( ObjectHeader.Unpack( obj ) ); } } #if REFCOUNT_STAT public static void RecordAddReference( Object obj ) { if(obj != null) { if(!ObjectHeader.Unpack( obj ).HasReferenceCount) { s_NonRCAddRefCalled++; } s_AddRefCalled++; } else { s_NoOpAddRefCalled++; } } public static void RecordReleaseReference( Object obj ) { if(obj != null) { s_ReleaseCalled++; if(!ObjectHeader.Unpack( obj ).HasReferenceCount) { s_NonRCReleaseCalled++; } } else { s_NoOpReleaseCalled++; } } #endif //REFCOUNT_STAT public static void DumpRefCountStat( bool reset ) { #if REFCOUNT_STAT var RefCountedObjectsAllocated = s_RefCountedObjectsAllocated; var RefCountedObjectsFreed = s_RefCountedObjectsFreed; var AddRefCalled = s_AddRefCalled; var ReleaseCalled = s_ReleaseCalled; var NoOpAddRefCalled = s_NoOpAddRefCalled; var NoOpReleaseCalled = s_NoOpReleaseCalled; var NonRCAddRefCalled = s_NonRCAddRefCalled; var NonRCReleaseCalled = s_NonRCReleaseCalled; var LoadAndAddRefCalled = s_LoadAndAddRefCalled; var SwapCalled = s_SwapCalled; BugCheck.Log( "RC objects alloced:%d freed:%d", RefCountedObjectsAllocated, RefCountedObjectsFreed ); BugCheck.Log( "AddRefs: %d (%d nop / %d nonRC)", AddRefCalled + NoOpAddRefCalled, NoOpAddRefCalled, NonRCAddRefCalled ); BugCheck.Log( "Releases: %d (%d nop / %d nonRC)", ReleaseCalled + NoOpReleaseCalled, NoOpReleaseCalled, NonRCReleaseCalled ); BugCheck.Log( "LoadAndAddReference: %d, Swap: %d", LoadAndAddRefCalled, SwapCalled ); if (reset) { s_RefCountedObjectsAllocated = 0; s_RefCountedObjectsFreed = 0; s_AddRefCalled = 0; s_ReleaseCalled = 0; s_NoOpAddRefCalled = 0; s_NoOpReleaseCalled = 0; s_NonRCAddRefCalled = 0; s_NonRCReleaseCalled = 0; s_LoadAndAddRefCalled = 0; s_SwapCalled = 0; } #endif //REFCOUNT_STAT } [Inline] internal bool DecrementReferenceCount() { int newMultiUseWord = ModifyReferenceCount( /*delta*/-1 ); bool delete = ( newMultiUseWord & ReferenceCountMask ) == 0; #if REFCOUNT_STAT s_ReleaseCalled++; if (delete) { s_RefCountedObjectsFreed++; } #endif //REFCOUNT_STAT return delete; } [Inline] private int ModifyReferenceCount( int delta ) { #pragma warning disable 420 // a reference to a volatile field will not be treated as volatile var result = InterlockedImpl.InternalAdd( ref this.MultiUseWord, delta << ReferenceCountShift ); #pragma warning restore 420 #if DEBUG_REFCOUNT var ptr = ToPointer( ); var refCount = ( result & ReferenceCountMask ) >> ReferenceCountShift; var isAlive = MemoryManager.Instance.IsObjectAlive( ptr ); if(!isAlive) { BugCheck.Log( "Attempting to modifying ref count of a dead object!!" ); } if(delta > 0) { BugCheck.Log( "AddRef (0x%x) %d +", (int)ptr, (int)refCount ); BugCheck.Assert( refCount > 1, BugCheck.StopCode.HeapCorruptionDetected ); } else { BugCheck.Log( "Release(0x%x) %d -", (int)ptr, (int)refCount ); BugCheck.Assert( refCount >= 0, BugCheck.StopCode.HeapCorruptionDetected ); } BugCheck.Assert( isAlive, BugCheck.StopCode.HeapCorruptionDetected ); #endif //DEBUG_REFCOUNT return result; } // // Access Methods // public unsafe GarbageCollectorFlags GarbageCollectorState { [Inline] get { #pragma warning disable 420 // a reference to a volatile field will not be treated as volatile fixed(int* ptr = &this.MultiUseWord) #pragma warning restore 420 { byte* flags = (byte*)ptr; return (GarbageCollectorFlags)(uint)*flags; } } [Inline] set { #pragma warning disable 420 // a reference to a volatile field will not be treated as volatile fixed(int* ptr = &this.MultiUseWord) #pragma warning restore 420 { byte* flags = (byte*)ptr; *flags = (byte)(uint)value; } } } public GarbageCollectorFlags GarbageCollectorStateWithoutMutableBits { [Inline] get { return (this.GarbageCollectorState & ~GarbageCollectorFlags.MutableMask); } } public ExtensionKinds ExtensionKind { [Inline] get { return (ExtensionKinds)((this.MultiUseWord & ExtensionKindMask) >> ExtensionKindShift); } } public bool IsImmutable { [Inline] get { return this.GarbageCollectorStateWithoutMutableBits == GarbageCollectorFlags.ReadOnlyObject; } } public int Payload { [Inline] get { return (int)(((uint)this.MultiUseWord & ExtensionPayloadMask) >> ExtensionPayloadShift); } } public bool HasReferenceCount { [Inline] get { return ( this.MultiUseWord & ReferenceCountMask ) != 0; } } internal unsafe uint AllocatedRawBytesSize { [Inline] get { #pragma warning disable 420 // a reference to a volatile field will not be treated as volatile fixed (int* ptr = &this.MultiUseWord) #pragma warning restore 420 { uint* size = (uint*)( ptr + 1 ); return *size; } } [Inline] private set { #pragma warning disable 420 // a reference to a volatile field will not be treated as volatile fixed (int* ptr = &this.MultiUseWord) #pragma warning restore 420 { uint* size = (uint*)( ptr + 1 ); *size = value; } } } //--// // // Extension Methods // [ExtendClass(typeof(TS.VTable), NoConstructors=true, ProcessAfter=typeof(TypeImpl))] class VTableImpl { [Inline] public static TS.VTable Get( object a ) { ObjectImpl.NullCheck( a ); ObjectHeader oh = ObjectHeader.Unpack( a ); return oh.VirtualTable; } [Inline] public static TS.VTable GetFromTypeHandle( RuntimeTypeHandleImpl hnd ) { return hnd.m_value; } } } } ================================================ FILE: Zelig/Zelig/RunTime/Zelig/Kernel/ManagedHeap/ReleaseReferenceHelper.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // namespace Microsoft.Zelig.Runtime { using System; using TS = Microsoft.Zelig.Runtime.TypeSystem; [TS.DisableAutomaticReferenceCounting] [TS.DisableReferenceCounting] public class ReleaseReferenceHelper { private const int c_defaultObjectStackCapacity = 100; private const int c_defaultArrayStackCapacity = 10; private ObjectHeader[] m_objectStack; private int m_objectStackPos; // Helper struct to store the tracking information when traversing through // the arrays. struct ArrayInfo { private UIntPtr m_address; private uint m_elementSize; private uint m_numOfElementsLeft; private TS.VTable m_vTableElement; // Populate the struct with the specified array public unsafe void Push( ArrayImpl array, uint elementSize, uint numOfElements, TS.VTable vTableElement ) { m_address = new UIntPtr( array.GetEndDataPointer( ) ); m_elementSize = elementSize; m_numOfElementsLeft = numOfElements; m_vTableElement = vTableElement; } // Clear the struct and return the address of the array's ObjectHeader public ObjectHeader Pop( ) { BugCheck.Assert( m_numOfElementsLeft == 0, BugCheck.StopCode.InvalidOperation ); // Need to calculate the address of the array's ObjectHeader to return UIntPtr arrayImplAddress = AddressMath.Decrement(m_address, (uint)System.Runtime.InteropServices.Marshal.SizeOf(typeof(ArrayImpl))); Object arrayObject = ObjectImpl.FromFieldPointer(arrayImplAddress); ObjectHeader arrayObjectHeader = ObjectHeader.Unpack(arrayObject); m_address = UIntPtr.Zero; m_vTableElement = null; return arrayObjectHeader; } // Get the next set of element to visit. Return true when we've reached the last one. public bool GetNext( out UIntPtr address, out TS.VTable vTable ) { // Move to the previous element m_address = AddressMath.Decrement( m_address, m_elementSize ); m_numOfElementsLeft--; address = m_address; vTable = m_vTableElement; return m_numOfElementsLeft == 0; } } private ArrayInfo[] _arrayStack; private int _arrayStackPos; public ReleaseReferenceHelper( ) : this( c_defaultObjectStackCapacity, c_defaultArrayStackCapacity ) { } public ReleaseReferenceHelper( int objectStackCapacity, int arrayStackCapacity ) { m_objectStack = ( objectStackCapacity > 0 ) ? new ObjectHeader[ objectStackCapacity ] : null; m_objectStackPos = 0; _arrayStack = ( arrayStackCapacity > 0 ) ? new ArrayInfo[ arrayStackCapacity ] : null; _arrayStackPos = 0; } public void DeleteObject( ObjectHeader oh ) { Log( "DeleteObject 0x%x", (int)oh.ToPointer( ) ); if(oh.VirtualTable.IsArray) { PushToArrayStack( oh ); } else { PushToObjectStack( oh ); } while(true) { if(!this.IsObjectStackEmpty) { VisitObjectStack( ); continue; } if(!this.IsArrayStackEmpty) { VisitArrayStack( ); continue; } break; } } // Helper that decrement the ref count of oh, and if necessary, // Add the zombie objects to the appropriate stack. // Return true if the ref count reaches 0. private bool DecrementRefCount( ObjectHeader oh ) { if(oh.HasReferenceCount && oh.DecrementReferenceCount()) { if(oh.VirtualTable.IsArray) { PushToArrayStack( oh ); } else { PushToObjectStack( oh ); } return true; } return false; } // Helper that goes through each of the interesting field and decrement // their ref counts. Note that the baseAddress is at the start of the fields. private unsafe void DecrementFieldsRefCount( UIntPtr baseAddress, TS.VTable vTable ) { TS.GCInfo.Pointer[] pointers = vTable.GCInfo.Pointers; int numOfPointers = (pointers != null) ? pointers.Length : 0; UIntPtr* fieldAddress = (UIntPtr*)baseAddress.ToPointer(); Log( "DecrementFieldsRefCount baseAddress:0x%x, numPointers:%d", (int)baseAddress.ToUInt32( ), numOfPointers ); for(int i = 0; i < numOfPointers; i++) { TS.GCInfo.Pointer pointer = pointers[i]; UIntPtr referenceAddress = fieldAddress[pointer.OffsetInWords]; Log( "Pointer %d: kind:%d, offset:%d, ref:0x%x", i, (int)pointer.Kind, pointer.OffsetInWords, (int)referenceAddress.ToUInt32( ) ); if(referenceAddress != UIntPtr.Zero && pointer.Kind == TS.GCInfo.Kind.Heap) { DecrementRefCount( ObjectHeader.Unpack( ObjectImpl.FromPointer( referenceAddress ) ) ); } } } // Helper that calls the finalizer and free up the memory. private void DeleteObjectFromMemory( ObjectHeader oh ) { Log( "Releasing oh:0x%x from memory.", (int)oh.ToPointer( ) ); oh.Pack().FinalizeImpl( ); MemoryManager.Instance.Release( oh.ToPointer() ); } // Helper called by the main loop to iterate through the object stack. private void VisitObjectStack( ) { ObjectHeader oh = PopFromObjectStack(); Log( "VisitObjectStack address:0x%x", (int)oh.ToPointer() ); UIntPtr baseAddress = oh.Pack().GetFieldPointer(); DecrementFieldsRefCount( baseAddress, oh.VirtualTable ); DeleteObjectFromMemory( oh ); } // Helper called by the main loop to iterate through the array stack. private unsafe void VisitArrayStack( ) { UIntPtr address; TS.VTable vTable; bool isLast = _arrayStack[_arrayStackPos - 1].GetNext(out address, out vTable); Log( "VisitArrayStack address:0x%x", (int)address.ToUInt32( ) ); if(vTable != null) { // address points to a struct, so visit each field of the struct and // decrement the ref count accordingly DecrementFieldsRefCount( address, vTable ); } else { // address points to an object, so make sure it's not null and decrement // its ref count UIntPtr obj = *(UIntPtr*)address.ToPointer(); if(obj != UIntPtr.Zero) { DecrementRefCount( ObjectHeader.Unpack( ObjectImpl.FromPointer( obj ) ) ); } } if(isLast) { // When we've gone through all the elements in this array, we can safely delete // array object from memory DeleteObjectFromMemory( PopFromArrayStack( ) ); } } private void PushToObjectStack( ObjectHeader oh ) { if(m_objectStack != null && m_objectStackPos < m_objectStack.Length - 1) { Log( "Adding 0x%x to delete object stack at pos:%d", (int)oh.ToPointer(), m_objectStackPos ); m_objectStack[ m_objectStackPos++ ] = oh; } } private void PushToArrayStack( ObjectHeader oh ) { ArrayImpl array = ArrayImpl.CastAsArray(oh.Pack()); uint numOfElements = (uint)array.Length; if(numOfElements == 0) { // Empty array, we can just delete the array object itself and return. DeleteObjectFromMemory( oh ); return; } TS.VTable vTableElement = oh.VirtualTable.TypeInfo.ContainedType.VirtualTable; if(vTableElement.IsValueType) { if(vTableElement.GCInfo.Pointers == null) { // It's an array of value types with no pointers, no need to push it. // Just delete the array object and return. DeleteObjectFromMemory( oh ); return; } // This is an array of structs. } else { // This is an array of objects, which has its own vTable embedded in its ObjectHeader, // so set vTableElement to null to indicate such. vTableElement = null; } if(_arrayStack != null && _arrayStackPos < _arrayStack.Length - 1) { Log( "Adding 0x%x (len %d) to delete array stack at pos:%d", (int)oh.ToPointer( ), (int)numOfElements, _arrayStackPos ); _arrayStack[ _arrayStackPos++ ].Push( array, oh.VirtualTable.ElementSize, numOfElements, vTableElement ); } } private ObjectHeader PopFromObjectStack( ) { ObjectHeader oh = m_objectStack[--m_objectStackPos]; Log( "Removing 0x%x from delete object stack at pos:%d", (int)oh.ToPointer( ), m_objectStackPos ); return oh; } private ObjectHeader PopFromArrayStack( ) { ObjectHeader oh = _arrayStack[--_arrayStackPos].Pop(); Log( "Removing 0x%x from delete array stack at pos:%d", (int)oh.ToPointer( ), _arrayStackPos ); return oh; } private bool IsObjectStackEmpty { get { return m_objectStackPos == 0; } } private bool IsArrayStackEmpty { get { return _arrayStackPos == 0; } } #if RELEASEREFERENCEHELPER_LOG private static void Log( string format ) { BugCheck.Log( format ); } private static void Log( string format, int p1 ) { BugCheck.Log( format, p1 ); } private static void Log( string format, int p1, int p2 ) { BugCheck.Log( format, p1, p2 ); } private static void Log( string format, int p1, int p2, int p3 ) { BugCheck.Log( format, p1, p2, p3 ); } private static void Log( string format, int p1, int p2, int p3, int p4 ) { BugCheck.Log( format, p1, p2, p3, p4 ); } private static void Log( string format, int p1, int p2, int p3, int p4, int p5 ) { BugCheck.Log( format, p1, p2, p3, p4, p5 ); } #else private static void Log( string format ) { } private static void Log( string format, int p1 ) { } private static void Log( string format, int p1, int p2 ) { } private static void Log( string format, int p1, int p2, int p3 ) { } private static void Log( string format, int p1, int p2, int p3, int p4 ) { } private static void Log( string format, int p1, int p2, int p3, int p4, int p5 ) { } #endif } } ================================================ FILE: Zelig/Zelig/RunTime/Zelig/Kernel/ManagedHeap/SyncBlock.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // namespace Microsoft.Zelig.Runtime { using System; using TS = Microsoft.Zelig.Runtime.TypeSystem; internal class SyncBlock { [TS.GarbageCollectionExtension(typeof(SyncBlock))] class Handler : GarbageCollectionExtensionHandler { [TS.SkipDuringGarbageCollection] SyncBlock m_head; public override void StartOfMarkPhase( GarbageCollectionManager gc ) { m_head = null; } public override void Mark( GarbageCollectionManager gc , object target ) { var obj = (SyncBlock)target; if(gc.IsMarked( obj.m_associatedObject )) { return; } obj.m_next = m_head; m_head = obj; } public override void EndOfMarkPhase( GarbageCollectionManager gc ) { } public override void StartOfSweepPhase( GarbageCollectionManager gc ) { for(var ptr = m_head; ptr != null;) { var ptrNext = ptr.m_next; ptr.m_next = null; if(!gc.IsMarked( ptr.m_associatedObject )) { ptr.AddToFreeList(); } ptr = ptrNext; } } public override void Sweep( GarbageCollectionManager gc , object target ) { } public override void EndOfSweepPhase( GarbageCollectionManager gc ) { } } // // State // [TS.SkipDuringGarbageCollection] object m_associatedObject; SyncBlock m_next; /******************************/ readonly int m_index; /******************************/ int m_hashCode; /******************************/ Synchronization.CriticalSection m_lock; int m_counterUse; int m_counterFree; // // Helper Methods // internal SyncBlock( int index ) { m_index = index; AddToFreeList(); } internal void Prepare( object target , int hashCode ) { m_associatedObject = target; m_hashCode = hashCode; } internal void AddToFreeList() { var table = SyncBlockTable.Instance; m_associatedObject = null; m_lock = null; m_counterFree++; while(true) { var first = table.m_freeList; m_next = first; if(System.Threading.Interlocked.CompareExchange( ref table.m_freeList, this, first ) == first) { break; } } } internal static SyncBlock ExtractFromFreeList() { var table = SyncBlockTable.Instance; while(true) { var first = table.m_freeList; if(first == null) { return null; } var next = first.m_next; if(System.Threading.Interlocked.CompareExchange( ref table.m_freeList, next, first ) == first) { first.m_counterUse++; first.m_next = null; return first; } } } // // Access Methods // internal Synchronization.CriticalSection Lock { get { return TypeSystemManager.AtomicAllocator( ref m_lock ); } } internal object AssociatedObject { get { return m_associatedObject; } } internal int HashCode { get { return m_hashCode; } set { m_hashCode = value; } } internal int Index { get { return m_index; } } } } ================================================ FILE: Zelig/Zelig/RunTime/Zelig/Kernel/ManagedHeap/SyncBlockTable.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // namespace Microsoft.Zelig.Runtime { using System; using System.Runtime.CompilerServices; using TS = Microsoft.Zelig.Runtime.TypeSystem; public class SyncBlockTable { internal const int BlocksInACluster = 32; // // State // private Synchronization.YieldLock m_lock; private SyncBlock[][] m_clusters; internal SyncBlock m_freeList; private int m_uniqueHashCode; // // Helper Methods // public static int GetHashCode( object target ) { ObjectHeader oh = ObjectHeader.Unpack( target ); int hashCode; switch(oh.ExtensionKind) { case ObjectHeader.ExtensionKinds.HashCode: return oh.Payload; case ObjectHeader.ExtensionKinds.Empty: using(var hnd = new SmartHandles.YieldLockHolder( Instance.Lock )) { if(oh.IsImmutable == false) { // // Check again, under lock, in case we had a race condition. // if(oh.ExtensionKind == ObjectHeader.ExtensionKinds.Empty) { hashCode = Instance.m_uniqueHashCode++; oh.UpdateExtension( ObjectHeader.ExtensionKinds.HashCode, hashCode ); return hashCode; } } } break; } //--// int idx = AssignSyncBlock( target ); hashCode = Instance.GetHashCode( idx ); GC.KeepAlive( target ); return hashCode; } public static Synchronization.CriticalSection GetLock( object target ) { BugCheck.Assert(null != target, BugCheck.StopCode.SyncBlockCorruption ); int idx = AssignSyncBlock( target ); Synchronization.CriticalSection res = Instance.GetLock( idx ); GC.KeepAlive( target ); return res; } //--// [Inline] private static int AssignSyncBlock( object obj ) { BugCheck.Assert(null != obj, BugCheck.StopCode.SyncBlockCorruption); ObjectHeader oh = ObjectHeader.Unpack( obj ); if(oh.ExtensionKind == ObjectHeader.ExtensionKinds.SyncBlock) { return oh.Payload; } return Instance.AssignSyncBlockSlow( obj ); } private int AssignSyncBlockSlow( object obj ) { ObjectHeader oh = ObjectHeader.Unpack( obj ); using(new SmartHandles.YieldLockHolder( this.Lock )) { // // Check again, under lock, in case we had a race condition. // if(oh.ExtensionKind == ObjectHeader.ExtensionKinds.SyncBlock) { return oh.Payload; } int idx = -1; if(oh.IsImmutable) { if(m_clusters != null) { foreach(var blocks in m_clusters) { for(int pos = 0; pos < BlocksInACluster; pos++) { var sb = blocks[pos]; if(sb.AssociatedObject == obj) { idx = sb.Index; break; } } if(idx >= 0) { break; } } } } if(idx < 0) { while(true) { var sb = SyncBlock.ExtractFromFreeList(); if(sb != null) { sb.Prepare( obj, m_uniqueHashCode++ ); idx = sb.Index; break; } ExpandClusters(); } } switch(oh.ExtensionKind) { case ObjectHeader.ExtensionKinds.Empty: // // Hash code automatically assigned. // break; case ObjectHeader.ExtensionKinds.HashCode: // // Copy hash code from header. // SetHashCode( idx, oh.Payload ); break; case ObjectHeader.ExtensionKinds.SyncBlock: BugCheck.Raise( BugCheck.StopCode.SyncBlockCorruption ); break; default: // // Not implemented yet, so it has to be a corruption. // BugCheck.Raise( BugCheck.StopCode.SyncBlockCorruption ); break; } if(oh.IsImmutable == false) { oh.UpdateExtension( ObjectHeader.ExtensionKinds.SyncBlock, idx ); } return idx; } } //--// public int GetHashCode( int idx ) { int clusterIndex = idx / BlocksInACluster; int blockIndex = idx % BlocksInACluster; return m_clusters[clusterIndex][blockIndex].HashCode; } public void SetHashCode( int idx , int hashCode ) { int clusterIndex = idx / BlocksInACluster; int blockIndex = idx % BlocksInACluster; m_clusters[clusterIndex][blockIndex].HashCode = hashCode; } public Synchronization.CriticalSection GetLock( int idx ) { int clusterIndex = idx / BlocksInACluster; int blockIndex = idx % BlocksInACluster; return m_clusters[clusterIndex][blockIndex].Lock; } //--// private void ExpandClusters() { int clusterIndex = (m_clusters == null) ? 0 : m_clusters.Length; var blocks = new SyncBlock[BlocksInACluster]; // // Link each block to the next one, except for the last one. // int index = clusterIndex * BlocksInACluster; for(int i = 0; i < BlocksInACluster; i++) { blocks[i] = new SyncBlock( index++ ); } m_clusters = ArrayUtility.AppendToArray( m_clusters, blocks ); } // // Access Methods // public static extern SyncBlockTable Instance { [SingletonFactory()] [MethodImpl( MethodImplOptions.InternalCall )] get; } public Synchronization.YieldLock Lock { get { return TypeSystemManager.AtomicAllocator( ref m_lock ); } } } } ================================================ FILE: Zelig/Zelig/RunTime/Zelig/Kernel/MemoryManagers/LinearMemoryManager.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // namespace Microsoft.Zelig.Runtime { using System; using System.Runtime.CompilerServices; using TS = Microsoft.Zelig.Runtime.TypeSystem; public abstract class LinearMemoryManager : MemoryManager { // // Helper Methods // public override void InitializeMemoryManager() { base.InitializeMemoryManager(); Memory.Range[] ranges = Memory.Instance.AvailableMemory; foreach(Memory.Range rng in ranges) { if((rng.Usage & MemoryUsage .Heap ) != 0 && (rng.Attributes & MemoryAttributes.Allocated) == 0 ) { AddLinearSection( rng.Start, rng.End, rng.Attributes ); } } } public override void InitializationComplete() { if(MemoryManager.Configuration.TrashFreeMemory) { DirtyFreeMemory(); } else { ZeroFreeMemory(); } } //--// public override unsafe UIntPtr Allocate( uint size ) { BugCheck.Assert( MemoryManager.Lock.IsHeldByCurrentThread( ), BugCheck.StopCode.HeapCorruptionDetected ); MemorySegment* ptr = m_active; if(ptr != null) { UIntPtr res = ptr->Allocate( size ); if(res != UIntPtr.Zero) { GarbageCollectionManager.Instance.NotifyNewObject( res, size ); return res; } } ptr = m_heapHead; while(ptr != null) { UIntPtr res = ptr->Allocate( size ); if(res != UIntPtr.Zero) { m_active = ptr; GarbageCollectionManager.Instance.NotifyNewObject( res, size ); return res; } ptr = ptr->Next; } return UIntPtr.Zero; } public override unsafe void Release(UIntPtr address) { if (address != UIntPtr.Zero) { using (SmartHandles.YieldLockHolder hnd = new SmartHandles.YieldLockHolder(MemoryManager.Lock)) { for (MemorySegment* heap = m_heapHead; heap != null; heap = heap->Next) { if (AddressMath.IsInRange(address, heap->Beginning, heap->End)) { heap->Release(address); } } } } } public override bool RefersToMemory( UIntPtr address ) { foreach(Memory.Range rng in Memory.Instance.AvailableMemory) { if(AddressMath.IsInRange( address, rng.Start, rng.End )) { return true; } } return false; } internal override void ConsistencyCheck() { ConsistencyCheck(dumpMemory:false); } internal override void DumpMemory() { ConsistencyCheck(dumpMemory:true); } private unsafe void ConsistencyCheck(bool dumpMemory) { for (MemorySegment* heap = m_heapHead; heap != null; heap = heap->Next) { heap->ConsistencyCheck(dumpMemory); } } internal override unsafe bool IsObjectAlive( UIntPtr ptr ) { for(MemorySegment* heap = m_heapHead; heap != null; heap = heap->Next) { if(AddressMath.IsInRange( ptr, heap->Beginning, heap->End )) { return heap->IsObjectAlive( ptr ); } } return false; } } } ================================================ FILE: Zelig/Zelig/RunTime/Zelig/Kernel/Properties/AssemblyInfo.cs ================================================ using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; // General Information about an assembly is controlled through the following // set of attributes. Change these attribute values to modify the information // associated with an assembly. [assembly: AssemblyTitle( "Microsoft.Zelig.Runtime" )] [assembly: AssemblyDescription( "" )] [assembly: AssemblyConfiguration( "" )] [assembly: AssemblyCompany( "Microsoft" )] [assembly: AssemblyProduct( "Microsoft.Zelig.Runtime" )] [assembly: AssemblyCopyright( "Copyright © Microsoft 2006" )] [assembly: AssemblyTrademark( "" )] [assembly: AssemblyCulture( "" )] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible( false )] //// The following GUID is for the ID of the typelib if this project is exposed to COM //[assembly: Guid( "c2e5a31b-4e85-4692-a487-79f792176810" )] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Revision and Build Numbers // by using the '*' as shown below: [assembly: AssemblyVersion( "1.0.0.0" )] [assembly: AssemblyFileVersion( "1.0.0.0" )] [assembly: InternalsVisibleTo("Microsoft.Zelig.LlilumOSAbstraction")] ================================================ FILE: Zelig/Zelig/RunTime/Zelig/Kernel/SelfTest.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // // Enable more verbose diagnostic output which can overwhelm normal test results. //#define VERBOSE_LOGGING using System.Runtime.InteropServices; namespace Microsoft.Zelig.Runtime { using TypeSystem; using System; using System.Threading; internal static class SelfTest { [DllImport( "C" )] public static unsafe extern int GetANumber( ); [DllImport( "C" )] public static unsafe extern void BreakWithTrap( ); [DllImport( "C" )] public static unsafe extern void Breakpoint( uint n ); internal static bool AlwaysTrueNonOptimizableCondition() { return GetANumber( ) >= 42; } internal static bool AlwaysFalseNonOptimizableCondition() { return GetANumber( ) < 42; } internal static void NonOptimizableCall() { SELFTEST_ASSERT( AlwaysTrueNonOptimizableCondition() ); } // // Zelig Self Test - Early bootstrap, no heap: // integers, pointers and value types // [NoInline] internal static unsafe void SELFTEST_ASSERT( bool expression ) { if( !expression ) { BugCheck.Log( "!!! TEST FAILED !!!" ); BreakWithTrap( ); } } [NoInline] internal static unsafe void SELFTEST_LOG( string format ) { BugCheck.Log( format ); } [NoInline] internal static unsafe void SELFTEST_LOG( string format, int p1 ) { BugCheck.Log( format, p1 ); } //--// //--// //--// #region Basic math and flow controls private static int FibonacciInterative( int num ) { int a = 0, b = 1, c = 0; if( num == 1 ) return 1; for( int i = 1; i < num; i++ ) { c = a + b; a = b; b = c; } return c; } private static int FibonacciRecursive( int num ) { if( num <= 1 ) { return num; } return FibonacciRecursive( num - 1 ) + FibonacciRecursive( num - 2 ); } private static void SelfTest__Test__Fibonacci( ) { const int iter_0 = 0; const int iter_1 = 1; const int iter_2 = 1; const int iter_3 = 2; const int iter_4 = 3; const int iter_5 = 5; const int iter_6 = 8; const int iter_7 = 13; const int iter_8 = 21; const int iter_9 = 34; const int iter_10 = 55; const int iter_11 = 89; const int iter_12 = 144; const int iter_13 = 233; const int iter_14 = 377; const int iter_15 = 610; int iterations = 16; int count = -1; while( ++count < iterations ) { int rec = FibonacciRecursive( count ); switch( count ) { case 0: SELFTEST_ASSERT( rec == iter_0 ); break; case 1: SELFTEST_ASSERT( rec == iter_1 ); break; case 2: SELFTEST_ASSERT( rec == iter_2 ); break; case 3: SELFTEST_ASSERT( rec == iter_3 ); break; case 4: SELFTEST_ASSERT( rec == iter_4 ); break; case 5: SELFTEST_ASSERT( rec == iter_5 ); break; case 6: SELFTEST_ASSERT( rec == iter_6 ); break; case 7: SELFTEST_ASSERT( rec == iter_7 ); break; case 8: SELFTEST_ASSERT( rec == iter_8 ); break; case 9: SELFTEST_ASSERT( rec == iter_9 ); break; case 10: SELFTEST_ASSERT( rec == iter_10 ); break; case 11: SELFTEST_ASSERT( rec == iter_11 ); break; case 12: SELFTEST_ASSERT( rec == iter_12 ); break; case 13: SELFTEST_ASSERT( rec == iter_13 ); break; case 14: SELFTEST_ASSERT( rec == iter_14 ); break; case 15: SELFTEST_ASSERT( rec == iter_15 ); break; default: SELFTEST_ASSERT( false ); break; } } } private static void SelfTest__Test__CallsAndControls( ) { const int iterations = 25; int count = 0; while( count++ < iterations ) { int rec = FibonacciRecursive( count ); int ite = FibonacciInterative( count ); SELFTEST_ASSERT( ite == rec ); } } #endregion Basic math and flow controls #region Native types, basic casts private static void SelfTest__Test__NativeTypes_IntCasts() { const int mask = ( 1 << 16 ) - 1; // Get a number smaller than 16 bits and shift it to the high word. int seed = GetANumber() % mask; SELFTEST_ASSERT( seed < mask ); int i = seed << 16; // Downcast the number and ensure low bits are zero. short s = ( short )i; SELFTEST_ASSERT( s == 0 ); } private static void SelfTest__Test__NativeTypes_FloatCasts() { int intValue = GetANumber(); double d = intValue; float f = ( float )d; SELFTEST_ASSERT( f == intValue ); } private static void SelfTest__Test__NativeTypes_IntToFloatCasts() { int intValue = GetANumber(); double d = intValue; float f = intValue; SELFTEST_ASSERT( d == f ); } #endregion Native types, basic casts #region Value Types struct ToCopy { public int i; public char c; } private static void SelfTest__Test__ValueTypes_Copy() { // Explicit field assignment ToCopy a; a.i = 1; a.c = 'a'; SELFTEST_ASSERT( a.i == 1 && a.c == 'a' ); // Initializer lists ToCopy b = new ToCopy { i = 2, c = 'b' }; SELFTEST_ASSERT( b.i == 2 && b.c == 'b' ); // Basic copy on initialization ToCopy copy = a; SELFTEST_ASSERT( a.i == 1 && a.c == 'a' ); SELFTEST_ASSERT( copy.i == 1 && copy.c == 'a' ); // Assignment after initialization copy = b; SELFTEST_ASSERT( b.i == 2 && b.c == 'b' ); SELFTEST_ASSERT( copy.i == 2 && copy.c == 'b' ); // Pass by value should not modify. ModifyPassByValue( copy ); SELFTEST_ASSERT( copy.i == 2 && copy.c == 'b' ); // Pass by ref should modify. ModifyPassByRef( ref copy ); SELFTEST_ASSERT( copy.i == 3 && copy.c == 'c' ); // Copy from return value. copy = ReturnByValue( ); SELFTEST_ASSERT( copy.i == 2 && copy.c == 'b' ); } private static void ModifyPassByValue( ToCopy byValue ) { byValue.i = 3; byValue.c = 'c'; } private static void ModifyPassByRef( ref ToCopy byValue ) { byValue.i = 3; byValue.c = 'c'; } private static ToCopy ReturnByValue() { return new ToCopy { i = 2, c = 'b' }; } private struct Mixed { public int ii; public byte bb; public long ll; public static Mixed operator +( Mixed a, Mixed b ) { Mixed c; c.ii = a.ii + b.ii; c.bb = ( byte )( a.bb + b.bb ); c.ll = a.ll + b.ll; return c; } } private static void SelfTest__Test__ValueTypes_PassByValue( ) { Mixed a; a.ii = 5; a.bb = 10; a.ll = 20; const int delta = 1; Mixed b; b.ii = 5 + delta; b.bb = 10 + delta; b.ll = 5 + delta; Mixed c = PassByValue( a, b ); SELFTEST_ASSERT( c.ii == a.ii + b.ii ); SELFTEST_ASSERT( c.bb == a.bb + b.bb ); SELFTEST_ASSERT( c.ll == a.ll + b.ll ); } private static Mixed PassByValue( Mixed a, Mixed b ) { return a + b; } private static void SelfTest__Test__ValueTypes_PassByRef( ) { Mixed a; a.ii = 5; a.bb = 10; a.ll = 20; const int delta = 1; Mixed b; b.ii = 5 + delta; b.bb = 10 + delta; b.ll = 5 + delta; Mixed aa = a; Mixed bb = b; Mixed c = PassByRef( ref a, ref b ); Mixed d = aa + bb; SELFTEST_ASSERT( c.ii == a.ii + b.ii ); SELFTEST_ASSERT( c.bb == a.bb + b.bb ); SELFTEST_ASSERT( c.ll == a.ll + b.ll ); SELFTEST_ASSERT( d.ii == aa.ii + bb.ii ); SELFTEST_ASSERT( d.bb == aa.bb + bb.bb ); SELFTEST_ASSERT( d.ll == aa.ll + bb.ll ); } private static Mixed PassByRef( ref Mixed a, ref Mixed b ) { a += b; b += a; return a + b; } #endregion Value Types //--// //--// //--// internal unsafe static void SelfTest__Bootstrap( ) { // // Basic math and flow controls // SelfTest__Test__Fibonacci( ); SelfTest__Test__CallsAndControls( ); // // Native types, basic casts // SelfTest__Test__NativeTypes_IntCasts( ); SelfTest__Test__NativeTypes_FloatCasts( ); SelfTest__Test__NativeTypes_IntToFloatCasts( ); // // Value Types // SelfTest__Test__ValueTypes_Copy( ); SelfTest__Test__ValueTypes_PassByValue( ); SelfTest__Test__ValueTypes_PassByRef( ); // // pointers... // SelfTest__Test__Pointers_Conversions_1( ); SelfTest__Test__Pointers_Conversions_2( ); SelfTest__Test__Pointers_Conversions_3( ); SelfTest__Test__Pointers_Conversions_4( ); SelfTest__Test__RawPointers_Arithmetic_Pointer_1( ); SelfTest__Test__RawPointers_Arithmetic_Pointer_2( ); SelfTest__Test__RawPointers_Arithmetic_Values_1 ( ); SelfTest__Test__RawPointers_Arithmetic_Values_2 ( ); SelfTest__Test__Pointers_PassByValue( ); SelfTest__Test__Pointers_PassByRef( ); // // ...else... // SelfTest__Test__Integers_Conversions( ); SelfTest__Test__Integers_PassByValue( ); SelfTest__Test__Integers_PassByRef( ); // Trap end of tests. BugCheck.Log("!!! ALL TESTS PASSED !!!"); BreakWithTrap(); } internal static void SelfTest__Checks() { SelfTest__Checks__Null_StaticReadonly(); SelfTest__Checks__Null_LocalScope(); SelfTest__Checks__Null_Complex(); SelfTest__Checks__Bounds(); SelfTest__Checks__Overflow(); // Trap end of tests. BugCheck.Log("!!! ALL TESTS PASSED !!!"); BreakWithTrap(); } internal static void SelfTest__Memory() { SelfTest__Memory__BoxUnbox(); SelfTest__Memory__Delegates(); SelfTest__Memory__BasicAllocation1(); SelfTest__Memory__BasicAllocation2(); SelfTest__Memory__BasicAllocation3(); SelfTest__Memory__GapPlugTest1(); SelfTest__Memory__GapPlugTest2(); SelfTest__Memory__GapPlugTest3(); SelfTest__Memory__GapPlugTest4(); SelfTest__Memory__GapPlugTest5(); SelfTest__Memory__GapPlugTest6(); SelfTest__Memory__Random(); SelfTest__Memory__BasicAddrefRelease1( ); SelfTest__Memory__BasicAddrefRelease2( ); SelfTest__Memory__BasicAddrefRelease3( ); SelfTest__Memory__BasicAddrefRelease4( ); SelfTest__Memory__BasicAddrefRelease5( ); SelfTest__Memory__BasicAddrefRelease6( ); SelfTest__Memory__BasicAddrefRelease7( ); SelfTest__Memory__RefCountGC1( ); SelfTest__Memory__RefCountGC2( ); SelfTest__Memory__RefCountGC3( ); SelfTest__Memory__RefCountGC4( ); SelfTest__Memory__RefCountGC5( ); SelfTest__Memory__RefCountGC6( ); SelfTest__Memory__RefCountGC7( ); SelfTest__Memory__RefCountGC8( ); SelfTest__Memory__RefCountGC9( ); SelfTest__Memory__RefCountGC10( ); SelfTest__Memory__RefCountGC11( ); SelfTest__Memory__RefCountGC12( ); SelfTest__Interlocked__Add_int( ); SelfTest__Interlocked__Add_long( ); SelfTest__Interlocked__Increment_int( ); SelfTest__Interlocked__Increment_long( ); SelfTest__Interlocked__Decrement_int( ); SelfTest__Interlocked__Decrement_long( ); SelfTest__Interlocked__Exchange_int( ); SelfTest__Interlocked__Exchange_long( ); SelfTest__Interlocked__Exchange_float( ); SelfTest__Interlocked__Exchange_double( ); SelfTest__Interlocked__Exchange_Object( ); SelfTest__Interlocked__Exchange_IntPtr( ); SelfTest__Interlocked__Exchange_Template( ); SelfTest__Interlocked__CompareExchange_int( ); SelfTest__Interlocked__CompareExchange_long( ); SelfTest__Interlocked__CompareExchange_float( ); SelfTest__Interlocked__CompareExchange_double( ); SelfTest__Interlocked__CompareExchange_Object( ); SelfTest__Interlocked__CompareExchange_IntPtr( ); SelfTest__Interlocked__CompareExchange_Template( ); // Trap end of tests. BugCheck.Log("!!! ALL TESTS PASSED !!!"); BreakWithTrap(); } #region Checks tests static readonly string AlwaysNull = null; static readonly string NeverNull = "Never null"; private static void SelfTest__Checks__Null_StaticReadonly() { SELFTEST_ASSERT(NeverNull.Length == 10); if (AlwaysFalseNonOptimizableCondition()) { SELFTEST_ASSERT(AlwaysNull.Length != 10); // This should always throw a null reference exception. } } private static void SelfTest__Checks__Null_LocalScope() { object alwaysNull = null; object neverNull = new object(); object sometimesNull = new object(); SELFTEST_ASSERT(!neverNull.Equals(null)); SELFTEST_ASSERT(!sometimesNull.Equals(null)); if (AlwaysFalseNonOptimizableCondition()) { SELFTEST_ASSERT(alwaysNull.Equals(null)); // This should always throw a null reference exception. sometimesNull = null; SELFTEST_ASSERT(sometimesNull.Equals(null)); // This should always throw a null reference exception. } } private static void SelfTest__Checks__Null_Complex() { // Test multiple levels of indirection (array access to provable null/not-null). var array = new object[] { new object(), null }; SELFTEST_ASSERT(!array[0].Equals(null)); if (AlwaysFalseNonOptimizableCondition()) { SELFTEST_ASSERT(array[1].Equals(null)); // This should always throw a null reference exception. } } private static void SelfTest__Checks__Bounds() { var array = new int[] { 0, 1, 2 }; SELFTEST_ASSERT(array[1] == 1); if (AlwaysFalseNonOptimizableCondition()) { // Obscure the value (-1) from the compiler. int number = GetANumber(); int negative = number - number - 1; SELFTEST_ASSERT(array[negative] != 0); // This should always throw a bounds exception. SELFTEST_ASSERT(array[3] != 0); // This should always throw a bounds exception. } } private static void SelfTest__Checks__Overflow() { int maxInt = int.MaxValue; SELFTEST_ASSERT(unchecked(maxInt + 1) == int.MinValue); if (AlwaysFalseNonOptimizableCondition()) { SELFTEST_ASSERT(checked(maxInt + 1) == int.MinValue); // This should always throw an overflow exception. } } #endregion Checks tests #region Boehm Collector Tests private static void SelfTest__Boehm__TriggerCollect() { //SELFTEST_LOG("TriggerCollect"); bool fSuccess = false; int count = 1024 * 1024; while(count-- > 0) { var hello = String.Concat( "Hello" + ", " + "world" ); if(hello == null) { fSuccess = false; break; } SELFTEST_LOG( hello ); } if(fSuccess) { SELFTEST_LOG( "TriggerCollect Succeeded." ); } else { SELFTEST_LOG( "TriggerCollect Failed." ); } } #endregion #region Memory Tests private const uint ArrayFixedSize = 3 * sizeof(uint); // 2 for ObjectHelper (MultiUseWord and VTable), 1 for length private const uint StandardAllocSize = 32; private const uint GapSize = (ArrayFixedSize - sizeof(uint)); // Not enough for a free block private const uint AllocSizeForGap = StandardAllocSize - GapSize; struct BasicStruct { public int Value; public int GetValue() { return Value; } public override int GetHashCode() { // Return something easily verifiable. return 17; } } private static object GetBoxedInt() { return 49; } private static void SelfTest__Memory__BoxUnbox() { BugCheck.Log("BoxUnbox Started..."); // Boxing on initialization int intVal = 5; object boxedInt = intVal; SELFTEST_ASSERT(boxedInt is int); SELFTEST_ASSERT((int)boxedInt == intVal); // Ensure identity. object boxedInt2 = intVal; SELFTEST_ASSERT(boxedInt.Equals(boxedInt2)); SELFTEST_ASSERT(!ReferenceEquals(boxedInt, boxedInt2)); // Ensure modifying boxed copy does not alter stack value. boxedInt = 19; SELFTEST_ASSERT(intVal == 5); SELFTEST_ASSERT((int)boxedInt == 19); // Method calls on value types vs. boxed objects. BasicStruct structVal = new BasicStruct { Value = 7 }; SELFTEST_ASSERT(structVal.GetValue() == 7); // Unconstrained call (no box). SELFTEST_ASSERT(structVal.GetHashCode() == 17); // Constrained call (no box). SELFTEST_ASSERT(!structVal.Equals(boxedInt)); // Boxed call to object. // Unboxing works on returned values. object boxedInt3 = GetBoxedInt(); SELFTEST_ASSERT((int)boxedInt3 == 49); BugCheck.Log("BoxUnbox Succeeded."); } internal delegate void SelfTest_Delegate(object arg); internal class DelegateHandlersBase { internal virtual void VirtualHandler(object arg) { // Intentionally fail the test. BugCheck.Log("Failed test: Called an overridden method."); SELFTEST_ASSERT(false); } } internal class DelegateHandlers : DelegateHandlersBase { static internal object s_testArg; internal object TestArg; internal static void StaticHandler(object arg) { SELFTEST_ASSERT(arg == s_testArg); } internal void InstanceHandler(object arg) { SELFTEST_ASSERT(arg == TestArg); } internal override void VirtualHandler(object arg) { SELFTEST_ASSERT(arg == TestArg); } } private static void SelfTest__Memory__Delegates() { BugCheck.Log("Delegates Started..."); object testObject = new object(); DelegateHandlers.s_testArg = testObject; BugCheck.Log(" Testing static delegate..."); SelfTest_Delegate staticDel = DelegateHandlers.StaticHandler; staticDel(testObject); var handlers = new DelegateHandlers(); handlers.TestArg = testObject; BugCheck.Log(" Testing instance delegate..."); SelfTest_Delegate instanceDel = handlers.InstanceHandler; instanceDel(testObject); BugCheck.Log(" Testing virtual delegate..."); SelfTest_Delegate virtualDel = handlers.VirtualHandler; virtualDel(testObject); BugCheck.Log("Delegates Succeeded."); } [DisableAutomaticReferenceCounting] private static UIntPtr AllocHelper(uint size) { var allocSize = (size < ArrayFixedSize + 1) ? ArrayFixedSize + 1 : size; byte[] array = new byte[allocSize - ArrayFixedSize]; for (uint i = 0; i < array.Length; i++) { array[i] = (byte)(i & 0xff); } var oh = ObjectHeader.Unpack(array); var ptr = oh.ToPointer(); #if VERBOSE_LOGGING BugCheck.Log("Allocated oh = 0x%x of total size %d", (int)ptr.ToUInt32(), (int)oh.TotalSize); #endif // VERBOSE_LOGGING return ptr; } [DisableAutomaticReferenceCounting] private static UIntPtr AllocHelperWithFakeGap(uint size) { var allocSize = (size < ArrayFixedSize + 1) ? ArrayFixedSize + 1 : size; uint[] array = new uint[(allocSize - ArrayFixedSize + sizeof(uint) - 1)/sizeof(uint)]; for (uint i = 0; i < array.Length; i++) { array[i] = (uint)ObjectHeader.GarbageCollectorFlags.GapPlug; } var oh = ObjectHeader.Unpack(array); var ptr = oh.ToPointer(); #if VERBOSE_LOGGING BugCheck.Log("Allocated oh = 0x%x of total size %d with fake gaps", (int)ptr.ToUInt32(), (int)oh.TotalSize); #endif // VERBOSE_LOGGING return ptr; } // [Free][Obj1][*] // Alloc Obj1 // [Free ][*] // Free Obj1 <=== Merge free block with previous free block [DisableAutomaticReferenceCounting] private static void SelfTest__Memory__BasicAllocation1() { BugCheck.Log("BasicAllocation1 Started..."); var obj1 = AllocHelper(StandardAllocSize); MemoryManager.Instance.ConsistencyCheck(); MemoryManager.Instance.Release(obj1); MemoryManager.Instance.ConsistencyCheck(); BugCheck.Log("BasicAllocation1 Succeeded."); } //[Free][Obj2][Obj1][*] // Alloc Obj1, Obj2 //[Free][Obj2][Free][*] // Free Obj1 <=== Merge free block alone //[Free ][*] // Free Obj2 <=== Merge free block with previous and next free block [DisableAutomaticReferenceCounting] private static void SelfTest__Memory__BasicAllocation2() { BugCheck.Log("BasicAllocation2 Started..."); var obj1 = AllocHelper(StandardAllocSize); var obj2 = AllocHelper(StandardAllocSize); MemoryManager.Instance.Release(obj1); MemoryManager.Instance.ConsistencyCheck(); MemoryManager.Instance.Release(obj2); MemoryManager.Instance.ConsistencyCheck(); BugCheck.Log("BasicAllocation2 Succeeded."); } //[Free][Obj3][Obj2][Obj1][*] // Alloc Obj1, Obj2, Obj3 //[Free][Obj3][Obj2][Free][*] // Free Obj1 //[Free][Obj3][Free ][*] // Free Obj2 <=== Merge free block with next free block //[Free ][*] // Free Obj3 [DisableAutomaticReferenceCounting] private static void SelfTest__Memory__BasicAllocation3() { BugCheck.Log("BasicAllocation3 Started..."); var obj1 = AllocHelper(StandardAllocSize); var obj2 = AllocHelper(StandardAllocSize); var obj3 = AllocHelper(StandardAllocSize); MemoryManager.Instance.Release(obj1); MemoryManager.Instance.Release(obj2); MemoryManager.Instance.ConsistencyCheck(); // Clean up MemoryManager.Instance.Release(obj3); MemoryManager.Instance.ConsistencyCheck(); BugCheck.Log("BasicAllocation3 Succeeded."); } //[gap][Obj1][*] // Alloc Obj1 <== Alloc with gaps //[Free ][*] // Free Obj1 <== Merge free block with previous gaps [DisableAutomaticReferenceCounting] private static unsafe void SelfTest__Memory__GapPlugTest1() { BugCheck.Log("GapPlugTest1 Started..."); MemoryManager.Instance.ConsistencyCheck(); uint firstFreeBlockSize = MemoryManager.Instance.StartOfHeap->FirstFreeBlock->AvailableMemory; var obj1 = AllocHelper(firstFreeBlockSize - GapSize); MemoryManager.Instance.ConsistencyCheck(); MemoryManager.Instance.Release(obj1); MemoryManager.Instance.ConsistencyCheck(); BugCheck.Log("GapPlugTest1 Succeeded."); } //[Obj2][Obj1 ][*] // Alloc Obj1, Obj2 //[Obj2][Free ][*] // Free Obj1 //[Obj2][gap][Obj3][*] // Alloc Obj3 //[Free ][Obj3][*] // Free Obj2 <== [DisableAutomaticReferenceCounting] private static unsafe void SelfTest__Memory__GapPlugTest2() { BugCheck.Log("GapPlugTest2 Started..."); uint firstFreeBlockSize = MemoryManager.Instance.StartOfHeap->FirstFreeBlock->AvailableMemory; var obj1 = AllocHelper(StandardAllocSize); var obj2 = AllocHelper(firstFreeBlockSize - StandardAllocSize); // Fill up the first block MemoryManager.Instance.Release(obj1); var obj3 = AllocHelper(AllocSizeForGap); MemoryManager.Instance.Release(obj2); MemoryManager.Instance.ConsistencyCheck(); // Cleanup MemoryManager.Instance.Release(obj3); MemoryManager.Instance.ConsistencyCheck(); BugCheck.Log("GapPlugTest2 Succeeded."); } //[gap][Obj2][Obj1 ][*] // Alloc Obj1, Obj2 //[gap][Obj2][Free ][*] // Free Obj1 //[gap][Obj2][gap][Obj3][*] // Alloc Obj3 //[Free ][Obj3][*] // Free Obj2 <== [DisableAutomaticReferenceCounting] private static unsafe void SelfTest__Memory__GapPlugTest3() { BugCheck.Log("GapPlugTest3 Started..."); uint firstFreeBlockSize = MemoryManager.Instance.StartOfHeap->FirstFreeBlock->AvailableMemory; var obj1 = AllocHelper(StandardAllocSize); var obj2 = AllocHelper(firstFreeBlockSize - StandardAllocSize - GapSize); MemoryManager.Instance.Release(obj1); var obj3 = AllocHelper(AllocSizeForGap); MemoryManager.Instance.Release(obj2); MemoryManager.Instance.ConsistencyCheck(); // Cleanup MemoryManager.Instance.Release(obj3); MemoryManager.Instance.ConsistencyCheck(); BugCheck.Log("GapPlugTest3 Succeeded."); } //[Obj2][Obj1 ][*] // Alloc Obj1, Obj2 (filled with fake gaps) //[Obj2][Free ][*] // Free Obj1 //[Obj2][gap][Obj3][*] // Alloc Obj3 //[Obj2][Free ][*] // Free Obj3 <== Merge with previous gaps following fake gaps [DisableAutomaticReferenceCounting] private static unsafe void SelfTest__Memory__GapPlugTest4() { BugCheck.Log("GapPlugTest4 Started..."); uint firstFreeBlockSize = MemoryManager.Instance.StartOfHeap->FirstFreeBlock->AvailableMemory; var obj1 = AllocHelper(firstFreeBlockSize - StandardAllocSize); var obj2 = AllocHelperWithFakeGap(StandardAllocSize); // Fill up the first block MemoryManager.Instance.Release(obj1); var obj3 = AllocHelper(firstFreeBlockSize - StandardAllocSize - GapSize); MemoryManager.Instance.Release(obj3); MemoryManager.Instance.ConsistencyCheck(); // Cleanup MemoryManager.Instance.Release(obj2); MemoryManager.Instance.ConsistencyCheck(); BugCheck.Log("GapPlugTest4 Succeeded."); } //[gap][Obj2][Obj1 ][*] // Alloc Obj1, Obj2 //[gap][Obj2][Free ][*] // Free Obj1 //[Free ][*] // Free Obj2 <== Merge with previous gaps and next free block [DisableAutomaticReferenceCounting] private static unsafe void SelfTest__Memory__GapPlugTest5() { BugCheck.Log("GapPlugTest5 Started..."); uint firstFreeBlockSize = MemoryManager.Instance.StartOfHeap->FirstFreeBlock->AvailableMemory; var obj1 = AllocHelper(StandardAllocSize); var obj2 = AllocHelper(firstFreeBlockSize - StandardAllocSize - GapSize); MemoryManager.Instance.Release(obj1); MemoryManager.Instance.Release(obj2); MemoryManager.Instance.ConsistencyCheck(); BugCheck.Log("GapPlugTest5 Succeeded."); } //[Free][Obj2][Obj1 ][*] // Alloc Obj1, Obj2 //[Free][Obj2][Free ][*] // Free Obj1 //[Free][Obj2][gap][Obj3][*] // Alloc Obj3 //[Free ][Obj3][*] // Free Obj2 <== Merge with previous free block and next gaps [DisableAutomaticReferenceCounting] private static unsafe void SelfTest__Memory__GapPlugTest6() { BugCheck.Log("GapPlugTest6 Started..."); var obj1 = AllocHelper(StandardAllocSize); var obj2 = AllocHelper(StandardAllocSize); MemoryManager.Instance.Release(obj1); var obj3 = AllocHelper(AllocSizeForGap); MemoryManager.Instance.Release(obj2); MemoryManager.Instance.ConsistencyCheck(); // Cleanup MemoryManager.Instance.Release(obj3); MemoryManager.Instance.ConsistencyCheck(); BugCheck.Log("GapPlugTest6 Succeeded."); } [DisableAutomaticReferenceCounting] private static unsafe void SelfTest__Memory__Random() { BugCheck.Log("Random Started..."); UIntPtr[] array = new UIntPtr[100]; Random rand = new Random(); for (uint i = 0; i < array.Length; i++) { array[i] = UIntPtr.Zero; } uint firstFreeBlockSize = MemoryManager.Instance.StartOfHeap->FirstFreeBlock->AvailableMemory; int maxAllocSize = (int)(firstFreeBlockSize / 2 / array.Length); maxAllocSize = maxAllocSize - maxAllocSize % sizeof(uint); for (uint i = 0; i < 1000; i++) { var target = rand.Next(array.Length); if (array[target] == UIntPtr.Zero) { uint allocSize = (uint)rand.Next(maxAllocSize); bool useFakeGap = (rand.Next(2) == 0); if (useFakeGap) { #if VERBOSE_LOGGING BugCheck.Log("%04d>>>> array[%d] = AllocHelperWithFakeGap(%d);", (int)i, target, (int)allocSize); #endif // VERBOSE_LOGGING array[target] = AllocHelperWithFakeGap(allocSize); } else { #if VERBOSE_LOGGING BugCheck.Log("%04d>>>> array[%d] = AllocHelper(%d);", (int)i, target, (int)allocSize); #endif // VERBOSE_LOGGING array[target] = AllocHelper(allocSize); } } else { #if VERBOSE_LOGGING BugCheck.Log("%04d>>>> MemoryManager.Instance.Release(array[%d]); array[%d] = UIntPtr.Zero;", (int)i, target, target); #endif // VERBOSE_LOGGING MemoryManager.Instance.Release(array[target]); array[target] = UIntPtr.Zero; } MemoryManager.Instance.ConsistencyCheck(); } // Cleanup for (uint i = 0; i < array.Length; i++) { MemoryManager.Instance.Release(array[i]); } MemoryManager.Instance.Release(ObjectHeader.Unpack(rand).ToPointer()); MemoryManager.Instance.Release(ObjectHeader.Unpack(array).ToPointer()); MemoryManager.Instance.ConsistencyCheck(); BugCheck.Log("Random Succeeded."); } #endregion // Memory Tests #region AddRef/Release Tests [DisableAutomaticReferenceCounting] private static void InitializeReferenceCount( object obj ) { ObjectHeader oh = ObjectHeader.Unpack( obj ); oh.MultiUseWord |= ( 1 << ObjectHeader.ReferenceCountShift ); } [DisableReferenceCounting] [DisableAutomaticReferenceCounting] private class Node { public Node _node1; public Node _node2; public Node[] _nodeArray; private Node( Node node1, Node node2, Node[] nodeArray ) { _node1 = node1; ObjectHeader.AddReference( node1 ); _node2 = node2; ObjectHeader.AddReference( node2 ); _nodeArray = nodeArray; ObjectHeader.AddReference( nodeArray ); } static public Node New( out UIntPtr ptr, Node node1, Node node2 ) { return New( out ptr, node1, node2, null ); } static public Node New( out UIntPtr ptr, Node node1, Node node2, Node[] nodeArray ) { Node node = new Node(node1, node2, nodeArray); InitializeReferenceCount( node ); ptr = ObjectHeader.Unpack( node ).ToPointer( ); return node; } static public Node[] NewArray( out UIntPtr ptr, int length, Node node0 ) { return NewArray( out ptr, length, node0, null, null ); } static public Node[] NewArray( out UIntPtr ptr, int length, Node node0, Node node1 ) { return NewArray( out ptr, length, node0, node1, null ); } static public Node[] NewArray( out UIntPtr ptr, int length, Node node0, Node node1, Node node2 ) { Node[] nodeArray = new Node[length]; InitializeReferenceCount( nodeArray ); if(length > 0) { nodeArray[ 0 ] = node0; ObjectHeader.AddReference( node0 ); if(length > 1) { nodeArray[ 1 ] = node1; ObjectHeader.AddReference( node1 ); if(length > 2) { nodeArray[ 2 ] = node2; ObjectHeader.AddReference( node2 ); } } } ptr = ObjectHeader.Unpack( nodeArray ).ToPointer( ); return nodeArray; } } [DisableAutomaticReferenceCounting] private struct NodeStruct { public Node _node1; public Node _node2; public Node[] _nodeArray; public void Set( Node node1, Node node2 ) { Set( node1, node2, null ); } public void Set( Node node1, Node node2, Node[] nodeArray ) { _node1 = node1; ObjectHeader.AddReference( node1 ); _node2 = node2; ObjectHeader.AddReference( node2 ); _nodeArray = nodeArray; ObjectHeader.AddReference( nodeArray ); } static public NodeStruct[] NewArray( out UIntPtr ptr, int length ) { NodeStruct[] nodeArray = new NodeStruct[length]; InitializeReferenceCount( nodeArray ); ptr = ObjectHeader.Unpack( nodeArray ).ToPointer( ); return nodeArray; } } // Releasing 1 single reference type [DisableAutomaticReferenceCounting] private static void SelfTest__Memory__BasicAddrefRelease1( ) { BugCheck.Log( "BasicAddrefRelease1 Started..." ); uint availableMemoryBefore = MemoryManager.Instance.AvailableMemory; BugCheck.Log( "Available memory before = %d", (int)availableMemoryBefore ); UIntPtr nodePtr; var node = Node.New(out nodePtr, null, null); ObjectHeader.ReleaseReference( node ); node = null; BugCheck.Assert( !MemoryManager.Instance.IsObjectAlive( nodePtr ), BugCheck.StopCode.HeapCorruptionDetected ); uint availableMemoryAfter = MemoryManager.Instance.AvailableMemory; BugCheck.Log( "Available memory after = %d", (int)availableMemoryAfter ); BugCheck.Assert( availableMemoryBefore == availableMemoryAfter, BugCheck.StopCode.HeapCorruptionDetected ); BugCheck.Log( "BasicAddrefRelease1 Succeeded." ); } // Cascading releases // [1] // / \ // [2] [3] // / /\ // [4] [5][6] [DisableAutomaticReferenceCounting] private static void SelfTest__Memory__BasicAddrefRelease2( ) { BugCheck.Log( "BasicAddrefRelease2 Started..." ); uint availableMemoryBefore = MemoryManager.Instance.AvailableMemory; BugCheck.Log( "Available memory before = %d", (int)availableMemoryBefore ); UIntPtr node4Ptr; var node4 = Node.New(out node4Ptr, null, null); UIntPtr node5Ptr; var node5 = Node.New(out node5Ptr, null, null); UIntPtr node6Ptr; var node6 = Node.New(out node6Ptr, null, null); UIntPtr node2Ptr; var node2 = Node.New(out node2Ptr, node4, null); UIntPtr node3Ptr; var node3 = Node.New(out node3Ptr, node5, node6); UIntPtr node1Ptr; var node1 = Node.New(out node1Ptr, node2, node3); ObjectHeader.ReleaseReference( node2 ); node2 = null; ObjectHeader.ReleaseReference( node3 ); node3 = null; ObjectHeader.ReleaseReference( node4 ); node4 = null; ObjectHeader.ReleaseReference( node5 ); node5 = null; ObjectHeader.ReleaseReference( node6 ); node6 = null; ObjectHeader.ReleaseReference( node1 ); node1 = null; BugCheck.Assert( !MemoryManager.Instance.IsObjectAlive( node1Ptr ), BugCheck.StopCode.HeapCorruptionDetected ); BugCheck.Assert( !MemoryManager.Instance.IsObjectAlive( node2Ptr ), BugCheck.StopCode.HeapCorruptionDetected ); BugCheck.Assert( !MemoryManager.Instance.IsObjectAlive( node3Ptr ), BugCheck.StopCode.HeapCorruptionDetected ); BugCheck.Assert( !MemoryManager.Instance.IsObjectAlive( node4Ptr ), BugCheck.StopCode.HeapCorruptionDetected ); BugCheck.Assert( !MemoryManager.Instance.IsObjectAlive( node5Ptr ), BugCheck.StopCode.HeapCorruptionDetected ); BugCheck.Assert( !MemoryManager.Instance.IsObjectAlive( node6Ptr ), BugCheck.StopCode.HeapCorruptionDetected ); uint availableMemoryAfter = MemoryManager.Instance.AvailableMemory; BugCheck.Log( "Available memory after = %d", (int)availableMemoryAfter ); BugCheck.Assert( availableMemoryBefore == availableMemoryAfter, BugCheck.StopCode.HeapCorruptionDetected ); BugCheck.Log( "BasicAddrefRelease2 Succeeded." ); } // Do not free objects that are not ref-counted [DisableAutomaticReferenceCounting] private static void SelfTest__Memory__BasicAddrefRelease3( ) { BugCheck.Log( "BasicAddrefRelease3 Started..." ); uint availableMemoryBefore = MemoryManager.Instance.AvailableMemory; BugCheck.Log( "Available memory before = %d", (int)availableMemoryBefore ); var node2 = new Exception("node2", null); UIntPtr node2Ptr = ObjectHeader.Unpack(node2).ToPointer(); var node1 = new Exception("node1", node2); InitializeReferenceCount( node1 ); UIntPtr node1Ptr = ObjectHeader.Unpack(node1).ToPointer(); node2 = null; ObjectHeader.ReleaseReference( node1 ); node1 = null; BugCheck.Assert( !MemoryManager.Instance.IsObjectAlive( node1Ptr ), BugCheck.StopCode.HeapCorruptionDetected ); BugCheck.Assert( MemoryManager.Instance.IsObjectAlive( node2Ptr ), BugCheck.StopCode.HeapCorruptionDetected ); MemoryManager.Instance.Release( node2Ptr ); uint availableMemoryAfter = MemoryManager.Instance.AvailableMemory; BugCheck.Log( "Available memory after = %d", (int)availableMemoryAfter ); BugCheck.Assert( availableMemoryBefore == availableMemoryAfter, BugCheck.StopCode.HeapCorruptionDetected ); BugCheck.Log( "BasicAddrefRelease3 Succeeded." ); } // Releasing a reference to an array of a reference type // node2 ----------------------\ // nodeRoot --> [ 0 ] [null] [ 2 ] // / \__________/ // [1] [DisableAutomaticReferenceCounting] private static void SelfTest__Memory__BasicAddrefRelease4( ) { BugCheck.Log( "BasicAddrefRelease4 Started..." ); uint availableMemoryBefore = MemoryManager.Instance.AvailableMemory; BugCheck.Log( "Available memory before = %d", (int)availableMemoryBefore ); UIntPtr node2Ptr; var node2 = Node.New(out node2Ptr, null, null); UIntPtr node1Ptr; var node1 = Node.New(out node1Ptr, null, null); UIntPtr node0Ptr; var node0 = Node.New(out node0Ptr, node1, node2); UIntPtr nodeArrayPtr; var nodeArray = Node.NewArray(out nodeArrayPtr, 3, node0, null, node2); UIntPtr nodeRootPtr; var nodeRoot = Node.New(out nodeRootPtr, null, null, nodeArray); ObjectHeader.ReleaseReference( node0 ); node0 = null; ObjectHeader.ReleaseReference( node1 ); node1 = null; ObjectHeader.ReleaseReference( nodeArray ); nodeArray = null; ObjectHeader.ReleaseReference( nodeRoot ); nodeRoot = null; BugCheck.Assert( !MemoryManager.Instance.IsObjectAlive( nodeRootPtr ), BugCheck.StopCode.HeapCorruptionDetected ); BugCheck.Assert( !MemoryManager.Instance.IsObjectAlive( nodeArrayPtr ), BugCheck.StopCode.HeapCorruptionDetected ); BugCheck.Assert( !MemoryManager.Instance.IsObjectAlive( node0Ptr ), BugCheck.StopCode.HeapCorruptionDetected ); BugCheck.Assert( !MemoryManager.Instance.IsObjectAlive( node1Ptr ), BugCheck.StopCode.HeapCorruptionDetected ); BugCheck.Assert( MemoryManager.Instance.IsObjectAlive( node2Ptr ), BugCheck.StopCode.HeapCorruptionDetected ); ObjectHeader.ReleaseReference( node2 ); node2 = null; BugCheck.Assert( !MemoryManager.Instance.IsObjectAlive( node2Ptr ), BugCheck.StopCode.HeapCorruptionDetected ); uint availableMemoryAfter = MemoryManager.Instance.AvailableMemory; BugCheck.Log( "Available memory after = %d", (int)availableMemoryAfter ); BugCheck.Assert( availableMemoryBefore == availableMemoryAfter, BugCheck.StopCode.HeapCorruptionDetected ); BugCheck.Log( "BasicAddrefRelease4 Succeeded." ); } // Releasing reference to an array of a struct (value type) // nodeStructArray --> [ ] [ ] [ ] // /\ | || // [0] [1] | [2] // \| // emptyArray [DisableAutomaticReferenceCounting] private static void SelfTest__Memory__BasicAddrefRelease5( ) { BugCheck.Log( "BasicAddrefRelease5 Started..." ); uint availableMemoryBefore = MemoryManager.Instance.AvailableMemory; BugCheck.Log( "Available memory before = %d", (int)availableMemoryBefore ); UIntPtr node2Ptr; var node2 = Node.New(out node2Ptr, null, null); UIntPtr emptyArrayPtr; var emptyArray = Node.NewArray(out emptyArrayPtr, 0, null); UIntPtr node1Ptr; var node1 = Node.New(out node1Ptr, null, null, emptyArray); UIntPtr node0Ptr; var node0 = Node.New(out node0Ptr, node1, node2); UIntPtr nodeStructArrayPtr; var nodeStructArray = NodeStruct.NewArray(out nodeStructArrayPtr, 3); nodeStructArray[ 0 ].Set( node0, node1 ); nodeStructArray[ 1 ].Set( null, null, emptyArray ); nodeStructArray[ 2 ].Set( node2, node2 ); ObjectHeader.ReleaseReference( node0 ); node0 = null; ObjectHeader.ReleaseReference( node2 ); node2 = null; ObjectHeader.ReleaseReference( emptyArray ); emptyArray = null; ObjectHeader.ReleaseReference( nodeStructArray ); nodeStructArray = null; BugCheck.Assert( !MemoryManager.Instance.IsObjectAlive( nodeStructArrayPtr ), BugCheck.StopCode.HeapCorruptionDetected ); BugCheck.Assert( !MemoryManager.Instance.IsObjectAlive( node0Ptr ), BugCheck.StopCode.HeapCorruptionDetected ); BugCheck.Assert( MemoryManager.Instance.IsObjectAlive( node1Ptr ), BugCheck.StopCode.HeapCorruptionDetected ); BugCheck.Assert( !MemoryManager.Instance.IsObjectAlive( node2Ptr ), BugCheck.StopCode.HeapCorruptionDetected ); BugCheck.Assert( MemoryManager.Instance.IsObjectAlive( emptyArrayPtr ), BugCheck.StopCode.HeapCorruptionDetected ); // Still held by node1 ObjectHeader.ReleaseReference( node1 ); node1 = null; BugCheck.Assert( !MemoryManager.Instance.IsObjectAlive( node1Ptr ), BugCheck.StopCode.HeapCorruptionDetected ); BugCheck.Assert( !MemoryManager.Instance.IsObjectAlive( emptyArrayPtr ), BugCheck.StopCode.HeapCorruptionDetected ); uint availableMemoryAfter = MemoryManager.Instance.AvailableMemory; BugCheck.Log( "Available memory after = %d", (int)availableMemoryAfter ); BugCheck.Assert( availableMemoryBefore == availableMemoryAfter, BugCheck.StopCode.HeapCorruptionDetected ); BugCheck.Log( "BasicAddrefRelease5 Succeeded." ); } // Releasing reference to a primitive array [DisableAutomaticReferenceCounting] private static void SelfTest__Memory__BasicAddrefRelease6( ) { BugCheck.Log( "BasicAddrefRelease6 Started..." ); uint availableMemoryBefore = MemoryManager.Instance.AvailableMemory; BugCheck.Log( "Available memory before = %d", (int)availableMemoryBefore ); var intArray = new int[10]; InitializeReferenceCount( intArray ); UIntPtr intArrayPtr = ObjectHeader.Unpack(intArray).ToPointer(); for(int i = 0; i < intArray.Length; i++) { intArray[ i ] = i; } ObjectHeader.ReleaseReference( intArray ); intArray = null; BugCheck.Assert( !MemoryManager.Instance.IsObjectAlive( intArrayPtr ), BugCheck.StopCode.HeapCorruptionDetected ); uint availableMemoryAfter = MemoryManager.Instance.AvailableMemory; BugCheck.Log( "Available memory after = %d", (int)availableMemoryAfter ); BugCheck.Assert( availableMemoryBefore == availableMemoryAfter, BugCheck.StopCode.HeapCorruptionDetected ); BugCheck.Log( "BasicAddrefRelease6 Succeeded." ); } // Circular reference // [0] // / \ // ,-[1] [2a]-. // \_/ / \ // [2b] | // \__/ [DisableAutomaticReferenceCounting] private static void SelfTest__Memory__BasicAddrefRelease7( ) { BugCheck.Log( "BasicAddrefRelease7 Started..." ); uint availableMemoryBefore = MemoryManager.Instance.AvailableMemory; BugCheck.Log( "Available memory before = %d", (int)availableMemoryBefore ); // Node 1 points to itself UIntPtr node1Ptr; var node1 = Node.New(out node1Ptr, null, null); node1._node1 = node1; ObjectHeader.AddReference( node1 ); // Node 2a and 2b creates a circular reference UIntPtr node2aPtr; var node2a = Node.New(out node2aPtr, null, null); UIntPtr node2bPtr; var node2b = Node.New(out node2bPtr, node2a, null); node2a._node2 = node2b; ObjectHeader.AddReference( node2b ); UIntPtr node0Ptr; var node0 = Node.New(out node0Ptr, node1, node2a); ObjectHeader.ReleaseReference( node1 ); node1 = null; ObjectHeader.ReleaseReference( node2a ); node2a = null; ObjectHeader.ReleaseReference( node2b ); node2b = null; ObjectHeader.ReleaseReference( node0 ); node0 = null; BugCheck.Assert( !MemoryManager.Instance.IsObjectAlive( node0Ptr ), BugCheck.StopCode.HeapCorruptionDetected ); BugCheck.Assert( MemoryManager.Instance.IsObjectAlive( node1Ptr ), BugCheck.StopCode.HeapCorruptionDetected ); BugCheck.Assert( MemoryManager.Instance.IsObjectAlive( node2aPtr ), BugCheck.StopCode.HeapCorruptionDetected ); BugCheck.Assert( MemoryManager.Instance.IsObjectAlive( node2bPtr ), BugCheck.StopCode.HeapCorruptionDetected ); MemoryManager.Instance.Release( node1Ptr ); MemoryManager.Instance.Release( node2aPtr ); MemoryManager.Instance.Release( node2bPtr ); uint availableMemoryAfter = MemoryManager.Instance.AvailableMemory; BugCheck.Log( "Available memory after = %d", (int)availableMemoryAfter ); BugCheck.Assert( availableMemoryBefore == availableMemoryAfter, BugCheck.StopCode.HeapCorruptionDetected ); BugCheck.Log( "BasicAddrefRelease7 Succeeded." ); } #endregion // AddRef/Release Tests #region Interlocked Tests private static void SelfTest__Interlocked__Add_int() { BugCheck.Log( "Interlocked Add int Started..." ); int i = 0; BugCheck.Log( "Before: i = %d", i ); int newi = Interlocked.Add( ref i, 10 ); BugCheck.Log( "After: i = %d, newi = %d", i, newi ); BugCheck.Assert( i == 10 && newi == i, BugCheck.StopCode.Impossible ); BugCheck.Log( "Interlocked Add int Succeeded." ); } private static void SelfTest__Interlocked__Add_long( ) { BugCheck.Log( "Interlocked Add long Started..." ); long l = 110; BugCheck.Log( "Before: l = %d", (int)l ); long newl = Interlocked.Add( ref l, 10L ); BugCheck.Log( "After: l = %d, newl = %d", (int)l, (int)newl ); BugCheck.Assert( l == 120 && newl == l, BugCheck.StopCode.Impossible ); BugCheck.Log( "Interlocked Add long Succeeded." ); } private static void SelfTest__Interlocked__Increment_int( ) { BugCheck.Log( "Interlocked Increment int Started..." ); int i = 0; BugCheck.Log( "Before: i = %d", (int)i ); int newi = Interlocked.Increment( ref i ); BugCheck.Log( "After: i = %d, newi = %d", (int)i, (int)newi ); BugCheck.Assert( i == 1 && newi == i, BugCheck.StopCode.Impossible ); BugCheck.Log( "Interlocked Increment int Succeeded." ); } private static void SelfTest__Interlocked__Increment_long( ) { BugCheck.Log( "Interlocked Increment long Started..." ); long l = 3; BugCheck.Log( "Before: l = %d", (int)l ); long newl = Interlocked.Increment( ref l ); BugCheck.Log( "After: l = %d, newl = %d", (int)l, (int)newl ); BugCheck.Assert( l == 4 && newl == l, BugCheck.StopCode.Impossible ); BugCheck.Log( "Interlocked Increment long Succeeded." ); } private static void SelfTest__Interlocked__Decrement_int( ) { BugCheck.Log( "Interlocked Decrement int Started..." ); int i = 0; BugCheck.Log( "Before: i = %d", (int)i ); int newi = Interlocked.Decrement( ref i ); BugCheck.Log( "After: i = %d, newi = %d", (int)i, (int)newi ); BugCheck.Assert( i == -1 && newi == i, BugCheck.StopCode.Impossible ); BugCheck.Log( "Interlocked Decrement int Succeeded." ); } private static void SelfTest__Interlocked__Decrement_long( ) { BugCheck.Log( "Interlocked Decrement long Started..." ); long l = 20; BugCheck.Log( "Before: l = %d", (int)l ); long newl = Interlocked.Decrement( ref l ); BugCheck.Log( "After: l = %d, newl = %d", (int)l, (int)newl ); BugCheck.Assert( l == 19 && newl == l, BugCheck.StopCode.Impossible ); BugCheck.Log( "Interlocked Decrement long Succeeded." ); } private static void SelfTest__Interlocked__Exchange_int( ) { BugCheck.Log( "Interlocked Exchange int Started..." ); int i = 5; BugCheck.Log( "Before: i = %d", (int)i ); int oldi = Interlocked.Exchange( ref i, 10 ); BugCheck.Log( "After: i = %d, oldi = %d", (int)i, (int)oldi ); BugCheck.Assert( i == 10 && oldi == 5, BugCheck.StopCode.Impossible ); BugCheck.Log( "Interlocked Exchange int Succeeded." ); } private static void SelfTest__Interlocked__Exchange_long( ) { BugCheck.Log( "Interlocked Exchange long Started..." ); long l = 20; BugCheck.Log( "Before: l = %d", (int)l ); long oldl = Interlocked.Exchange( ref l, 100 ); BugCheck.Log( "After: l = %d, oldl = %d", (int)l, (int)oldl ); BugCheck.Assert( l == 100 && oldl == 20, BugCheck.StopCode.Impossible ); BugCheck.Log( "Interlocked Exchange long Succeeded." ); } private static void SelfTest__Interlocked__Exchange_float( ) { BugCheck.Log( "Interlocked Exchange float Started..." ); float f = 100.0f; BugCheck.Log( "Before: f = %d", (int)f ); float oldf = Interlocked.Exchange( ref f, 50.0f ); BugCheck.Log( "After: f = %d, oldf = %d", (int)f, (int)oldf ); BugCheck.Assert( f == 50.0f && oldf == 100.0f, BugCheck.StopCode.Impossible ); BugCheck.Log( "Interlocked Exchange float Succeeded." ); } private static void SelfTest__Interlocked__Exchange_double( ) { BugCheck.Log( "Interlocked Exchange double Started..." ); double d = 1000.0d; BugCheck.Log( "Before: d = %d", (int)d ); double oldd = Interlocked.Exchange( ref d, 51.0d ); BugCheck.Log( "After: d = %d, oldd = %d", (int)d, (int)oldd ); BugCheck.Assert( d == 51.0d && oldd == 1000.0d, BugCheck.StopCode.Impossible ); BugCheck.Log( "Interlocked Exchange double Succeeded." ); } class Boo { public Boo(int i) { this.i = i; } public int i; } private static void SelfTest__Interlocked__Exchange_Object( ) { BugCheck.Log( "Interlocked Exchange Object Started..." ); Object o = new Boo( 0x123 ); Object copy = o; Object sub = new Boo( 0x234 ); BugCheck.Log( "Before: o = 0x%x, sub = 0x%x", (int)ObjectHeader.Unpack( o ).ToPointer( ), (int)ObjectHeader.Unpack( sub ).ToPointer( ) ); Object oldo = Interlocked.Exchange( ref o, sub ); BugCheck.Log( "After: o = 0x%x, oldo = 0x%x", (int)ObjectHeader.Unpack( o ).ToPointer( ), (int)ObjectHeader.Unpack( oldo ).ToPointer( ) ); BugCheck.Assert( o == sub && oldo == copy, BugCheck.StopCode.Impossible ); BugCheck.Log( "Interlocked Exchange Object Succeeded." ); } private static void SelfTest__Interlocked__Exchange_IntPtr( ) { BugCheck.Log( "Interlocked Exchange IntPtr Started..." ); IntPtr ptr = new IntPtr( 0x123 ); IntPtr copy = ptr; IntPtr sub = new IntPtr( 0x456 ); BugCheck.Log( "Before: ptr = 0x%x, sub = 0x%x", (int)ptr, (int)sub); IntPtr oldptr = Interlocked.Exchange( ref ptr, sub ); BugCheck.Log( "After: ptr = 0x%x, oldptr = 0x%x", (int)ptr, (int)oldptr ); BugCheck.Assert( ptr == sub && oldptr == copy, BugCheck.StopCode.Impossible ); BugCheck.Log( "Interlocked Exchange IntPtr Succeeded." ); } private static void SelfTest__Interlocked__Exchange_Template( ) { BugCheck.Log( "Interlocked Exchange Template Started..." ); UIntPtr nodeptr; Node node = Node.New( out nodeptr, null, null ); Node copy = node; UIntPtr subptr; Node sub = Node.New( out subptr, null, null ); BugCheck.Log( "Before: node = 0x%x, sub = 0x%x", (int)nodeptr, (int)subptr ); Node oldnode = Interlocked.Exchange( ref node, sub ); BugCheck.Log( "After: node = 0x%x, oldnode = 0x%x", (int)ObjectHeader.Unpack( node ).ToPointer( ), (int)ObjectHeader.Unpack( oldnode ).ToPointer( ) ); BugCheck.Assert( node == sub && oldnode == copy, BugCheck.StopCode.Impossible ); BugCheck.Log( "Interlocked Exchange Template Succeeded." ); } private static void SelfTest__Interlocked__CompareExchange_int( ) { BugCheck.Log( "Interlocked CompareExchange int Started..." ); int i = 5; BugCheck.Log( "Before: i = %d", (int)i ); int oldi = Interlocked.CompareExchange( ref i, 10, 5 ); BugCheck.Log( "After: i = %d, oldi = %d", (int)i, (int)oldi ); BugCheck.Assert( i == 10 && oldi == 5, BugCheck.StopCode.Impossible ); BugCheck.Log( "Interlocked CompareExchange int Succeeded." ); } private static void SelfTest__Interlocked__CompareExchange_long( ) { BugCheck.Log( "Interlocked CompareExchange long Started..." ); long l = 20; BugCheck.Log( "Before: l = %d", (int)l ); long oldl = Interlocked.CompareExchange( ref l, 100, 20 ); BugCheck.Log( "After: l = %d, oldl = %d", (int)l, (int)oldl ); BugCheck.Assert( l == 100 && oldl == 20, BugCheck.StopCode.Impossible ); BugCheck.Log( "Interlocked CompareExchange long Succeeded." ); } private static void SelfTest__Interlocked__CompareExchange_float( ) { BugCheck.Log( "Interlocked CompareExchange float Started..." ); float f = 100.0f; BugCheck.Log( "Before: f = %d", (int)f ); float oldf = Interlocked.CompareExchange( ref f, 50.0f, 100.0f ); BugCheck.Log( "After: f = %d, oldf = %d", (int)f, (int)oldf ); BugCheck.Assert( f == 50.0f && oldf == 100.0f, BugCheck.StopCode.Impossible ); BugCheck.Log( "Interlocked CompareExchange float Succeeded." ); } private static void SelfTest__Interlocked__CompareExchange_double( ) { BugCheck.Log( "Interlocked CompareExchange double Started..." ); double d = 1000.0d; BugCheck.Log( "Before: d = %d", (int)d ); double oldd = Interlocked.CompareExchange( ref d, 51.0d, 1000.0d ); BugCheck.Log( "After: d = %d, oldd = %d", (int)d, (int)oldd ); BugCheck.Assert( d == 51.0d && oldd == 1000.0d, BugCheck.StopCode.Impossible ); BugCheck.Log( "Interlocked CompareExchange double Succeeded." ); } private static void SelfTest__Interlocked__CompareExchange_Object( ) { BugCheck.Log( "Interlocked CompareExchange Object Started..." ); Object o = new Object( ); Object copy = o; Object sub = new Object( ); BugCheck.Log( "Before: o = 0x%x, sub = 0x%x", (int)ObjectHeader.Unpack( o ).ToPointer( ), (int)ObjectHeader.Unpack( sub ).ToPointer( ) ); Object oldo = Interlocked.CompareExchange( ref o, sub, copy ); BugCheck.Log( "After: o = 0x%x, oldo = 0x%x", (int)ObjectHeader.Unpack( o ).ToPointer( ), (int)ObjectHeader.Unpack( oldo ).ToPointer( ) ); BugCheck.Assert( o == sub && oldo == copy, BugCheck.StopCode.Impossible ); BugCheck.Log( "Interlocked CompareExchange Object Succeeded." ); } private static void SelfTest__Interlocked__CompareExchange_IntPtr( ) { BugCheck.Log( "Interlocked CompareExchange IntPtr Started..." ); IntPtr ptr = new IntPtr( 0x123 ); IntPtr copy = ptr; IntPtr sub = new IntPtr( 0x456 ); BugCheck.Log( "Before: ptr = 0x%x, sub = 0x%x", (int)ptr, (int)sub ); IntPtr oldptr = Interlocked.CompareExchange( ref ptr, sub, copy ); BugCheck.Log( "After: ptr = 0x%x, oldptr = 0x%x", (int)ptr, (int)oldptr ); BugCheck.Assert( ptr == sub && oldptr == copy, BugCheck.StopCode.Impossible ); BugCheck.Log( "Interlocked CompareExchange IntPtr Succeeded." ); } private static void SelfTest__Interlocked__CompareExchange_Template( ) { BugCheck.Log( "Interlocked CompareExchange Template Started..." ); UIntPtr nodeptr; Node node = Node.New( out nodeptr, null, null ); Node copy = node; UIntPtr subptr; Node sub = Node.New( out subptr, null, null ); BugCheck.Log( "Before: node = 0x%x, sub = 0x%x", (int)nodeptr, (int)subptr ); Node oldnode = Interlocked.CompareExchange( ref node, sub, copy ); BugCheck.Log( "After: node = 0x%x, oldnode = 0x%x", (int)ObjectHeader.Unpack( node ).ToPointer( ), (int)ObjectHeader.Unpack( oldnode ).ToPointer( ) ); BugCheck.Assert( node == sub && oldnode == copy, BugCheck.StopCode.Impossible ); BugCheck.Log( "Interlocked CompareExchange Template Succeeded." ); } #endregion // Interlocked Tests #region RefCount GC Tests private class GCNode { static int s_nextId = 1; public static GCNode s_node; public int _id; public GCNode _node1; public GCNode _node2; public GCNode( GCNode node1, GCNode node2 ) { _node1 = node1; _node2 = node2; _id = s_nextId++; } [NoInline] public static void ClearStaticNode() { s_node = null; } } private static void RefCountGC1_Helper() { GCNode node1 = new GCNode( null, null ); BugCheck.Log( "Node1 created: id= %d", node1._id ); node1 = new GCNode( null, null ); BugCheck.Log( "Node1 replaced by: id= %d", node1._id ); } private static void SelfTest__Memory__RefCountGC1( ) { BugCheck.Log( "RefCountGC1 Started..." ); uint availableMemoryBefore = MemoryManager.Instance.AvailableMemory; BugCheck.Log( "Available memory before = %d", (int)availableMemoryBefore ); RefCountGC1_Helper( ); uint availableMemoryAfter = MemoryManager.Instance.AvailableMemory; BugCheck.Log( "Available memory after = %d", (int)availableMemoryAfter ); BugCheck.Assert( availableMemoryBefore == availableMemoryAfter, BugCheck.StopCode.HeapCorruptionDetected ); BugCheck.Log( "RefCountGC1 Succeeded." ); } [NoInline] private static GCNode GetNewGCNode( ) { return new GCNode( null, null ); } [NoInline] private static void GetNewGCNode( out GCNode node ) { node = new GCNode( null, null ); } [NoInline] private static void GetNewGCNodeRef( ref GCNode node ) { if(node != null) { node = new GCNode( null, null ); } } private static void RefCountGC2_Helper( ) { GCNode node1 = GetNewGCNode( ); BugCheck.Assert( MemoryManager.Instance.IsObjectAlive( ObjectHeader.Unpack( node1 ).ToPointer( )), BugCheck.StopCode.HeapCorruptionDetected ); BugCheck.Log( "Node1 created: id= %d", node1._id ); node1 = new GCNode( null, null ); BugCheck.Log( "Node1 replaced by: id= %d", node1._id ); } private static void SelfTest__Memory__RefCountGC2( ) { BugCheck.Log( "RefCountGC2 Started..." ); uint availableMemoryBefore = MemoryManager.Instance.AvailableMemory; BugCheck.Log( "Available memory before = %d", (int)availableMemoryBefore ); RefCountGC2_Helper( ); uint availableMemoryAfter = MemoryManager.Instance.AvailableMemory; BugCheck.Log( "Available memory after = %d", (int)availableMemoryAfter ); BugCheck.Assert( availableMemoryBefore == availableMemoryAfter, BugCheck.StopCode.HeapCorruptionDetected ); BugCheck.Log( "RefCountGC2 Succeeded." ); } private static void RefCountGC3_Helper( ) { GCNode node1 = new GCNode( null, null ); BugCheck.Log( "Node1 created: id= %d", node1._id ); GCNode node2 = new GCNode( null, null ); BugCheck.Log( "Node2 created: id= %d", node2._id ); node1 = node2; BugCheck.Log( "Node1 is now: id= %d", node1._id ); BugCheck.Log( "Node2 is now: id= %d", node2._id ); } private static void SelfTest__Memory__RefCountGC3( ) { BugCheck.Log( "RefCountGC3 Started..." ); uint availableMemoryBefore = MemoryManager.Instance.AvailableMemory; BugCheck.Log( "Available memory before = %d", (int)availableMemoryBefore ); RefCountGC3_Helper( ); uint availableMemoryAfter = MemoryManager.Instance.AvailableMemory; BugCheck.Log( "Available memory after = %d", (int)availableMemoryAfter ); BugCheck.Assert( availableMemoryBefore == availableMemoryAfter, BugCheck.StopCode.HeapCorruptionDetected ); BugCheck.Log( "RefCountGC3 Succeeded." ); } private static void RefCountGC4_Helper( ) { GCNode node0 = new GCNode( null, null ); int node0Id = node0._id; BugCheck.Log( "Node0 created: id= %d", node0Id ); GCNode node1 = new GCNode( null, null ); int node1Id = node1._id; BugCheck.Log( "Node1 created: id= %d", node1Id ); GCNode node2 = new GCNode( node1, null ); int node2Id = node2._id; BugCheck.Log( "Node2 created: id= %d", node2Id ); BugCheck.Log( "Node2._node1 is: id= %d", node2._node1._id ); BugCheck.Assert( node2._node1._id == node1Id, BugCheck.StopCode.HeapCorruptionDetected ); node1 = node2; BugCheck.Log( "Node1 is now: id= %d", node1._id ); BugCheck.Log( "Node2._node1 is now: id= %d", node2._node1._id ); BugCheck.Assert( MemoryManager.Instance.IsObjectAlive( ObjectHeader.Unpack( node2._node1 ).ToPointer( ) ), BugCheck.StopCode.HeapCorruptionDetected ); BugCheck.Assert( node1._id == node2Id, BugCheck.StopCode.HeapCorruptionDetected ); node2._node1 = node0; BugCheck.Log( "Node2._node1 is now: id= %d", node2._node1._id ); BugCheck.Assert( node2._node1._id == node0Id, BugCheck.StopCode.HeapCorruptionDetected ); } private static void SelfTest__Memory__RefCountGC4( ) { BugCheck.Log( "RefCountGC4 Started..." ); uint availableMemoryBefore = MemoryManager.Instance.AvailableMemory; BugCheck.Log( "Available memory before = %d", (int)availableMemoryBefore ); RefCountGC4_Helper( ); uint availableMemoryAfter = MemoryManager.Instance.AvailableMemory; BugCheck.Log( "Available memory after = %d", (int)availableMemoryAfter ); BugCheck.Assert( availableMemoryBefore == availableMemoryAfter, BugCheck.StopCode.HeapCorruptionDetected ); BugCheck.Log( "RefCountGC4 Succeeded." ); } private static void RefCountGC5_Helper( ) { GCNode node1 = new GCNode( null, null ); int node1Id = node1._id; BugCheck.Log( "Node1 created: id= %d", node1Id ); GCNode.s_node = new GCNode( node1, null ); BugCheck.Log( "s_node created: id= %d", GCNode.s_node._id ); BugCheck.Log( "s_node._node1 is: id= %d", GCNode.s_node._node1._id ); BugCheck.Assert( GCNode.s_node._node1._id == node1Id, BugCheck.StopCode.HeapCorruptionDetected ); GCNode.s_node = node1; BugCheck.Log( "s_node is now: id= %d", GCNode.s_node._id ); BugCheck.Assert( GCNode.s_node._id == node1Id, BugCheck.StopCode.HeapCorruptionDetected ); } private static void SelfTest__Memory__RefCountGC5( ) { BugCheck.Log( "RefCountGC5 Started..." ); uint availableMemoryBefore = MemoryManager.Instance.AvailableMemory; BugCheck.Log( "Available memory before = %d", (int)availableMemoryBefore ); RefCountGC5_Helper( ); uint availableMemoryAfter = MemoryManager.Instance.AvailableMemory; BugCheck.Log( "Available memory after helper = %d", (int)availableMemoryAfter ); GCNode.ClearStaticNode( ); availableMemoryAfter = MemoryManager.Instance.AvailableMemory; BugCheck.Log( "Available memory after clear = %d", (int)availableMemoryAfter ); BugCheck.Assert( availableMemoryBefore == availableMemoryAfter, BugCheck.StopCode.HeapCorruptionDetected ); BugCheck.Log( "RefCountGC5 Succeeded." ); } private static void RefCountGC6_Helper( ) { GCNode[] nodeArray = new GCNode[ 3 ]; for(int repeat = 0; repeat < 2; repeat++) { for(int i = 0; i < nodeArray.Length; i++) { nodeArray[ i ] = new GCNode( null, null ); BugCheck.Log( "NodeArray[%d] created: id= %d", i, nodeArray[ i ]._id ); } } for(int i = 0; i < nodeArray.Length; i++) { nodeArray[ i ] = null; BugCheck.Log( "NodeArray[%d] set to null.", i ); } } private static void SelfTest__Memory__RefCountGC6( ) { BugCheck.Log( "RefCountGC6 Started..." ); uint availableMemoryBefore = MemoryManager.Instance.AvailableMemory; BugCheck.Log( "Available memory before = %d", (int)availableMemoryBefore ); RefCountGC6_Helper( ); uint availableMemoryAfter = MemoryManager.Instance.AvailableMemory; BugCheck.Log( "Available memory after = %d", (int)availableMemoryAfter ); BugCheck.Assert( availableMemoryBefore == availableMemoryAfter, BugCheck.StopCode.HeapCorruptionDetected ); BugCheck.Log( "RefCountGC6 Succeeded." ); } private static void RefCountGC7_Helper( ) { GCNode node = new GCNode( null, null ); BugCheck.Log( "Node created: id= %d", node._id ); GetNewGCNode( out node ); BugCheck.Assert( MemoryManager.Instance.IsObjectAlive( ObjectHeader.Unpack( node ).ToPointer( ) ), BugCheck.StopCode.HeapCorruptionDetected ); BugCheck.Log( "Node is now: id= %d", node._id ); node = new GCNode( null, null ); BugCheck.Log( "Node replaced by: id= %d", node._id ); } private static void SelfTest__Memory__RefCountGC7( ) { BugCheck.Log( "RefCountGC7 Started..." ); uint availableMemoryBefore = MemoryManager.Instance.AvailableMemory; BugCheck.Log( "Available memory before = %d", (int)availableMemoryBefore ); RefCountGC7_Helper( ); uint availableMemoryAfter = MemoryManager.Instance.AvailableMemory; BugCheck.Log( "Available memory after = %d", (int)availableMemoryAfter ); BugCheck.Assert( availableMemoryBefore == availableMemoryAfter, BugCheck.StopCode.HeapCorruptionDetected ); BugCheck.Log( "RefCountGC7 Succeeded." ); } private static void RefCountGC8_Helper( ) { GCNode node = new GCNode( null, null ); BugCheck.Log( "Node created: id= %d", node._id ); GetNewGCNodeRef( ref node ); BugCheck.Assert( MemoryManager.Instance.IsObjectAlive( ObjectHeader.Unpack( node ).ToPointer( ) ), BugCheck.StopCode.HeapCorruptionDetected ); BugCheck.Log( "Node is now: id= %d", node._id ); node = new GCNode( null, null ); BugCheck.Log( "Node replaced by: id= %d", node._id ); } private static void SelfTest__Memory__RefCountGC8( ) { BugCheck.Log( "RefCountGC8 Started..." ); uint availableMemoryBefore = MemoryManager.Instance.AvailableMemory; BugCheck.Log( "Available memory before = %d", (int)availableMemoryBefore ); RefCountGC8_Helper( ); uint availableMemoryAfter = MemoryManager.Instance.AvailableMemory; BugCheck.Log( "Available memory after = %d", (int)availableMemoryAfter ); BugCheck.Assert( availableMemoryBefore == availableMemoryAfter, BugCheck.StopCode.HeapCorruptionDetected ); BugCheck.Log( "RefCountGC8 Succeeded." ); } private static void RefCountGC9_Helper( ) { GCNode node1 = new GCNode( null, null ); BugCheck.Log( "Node1 created: id= %d", node1._id ); UIntPtr node1Ptr = ObjectHeader.Unpack( node1 ).ToPointer( ); BugCheck.Log( "Node1ptr = %x", (int)node1Ptr ); Object nodeObj = ObjectHeader.CastAsObjectHeader( node1Ptr ).Pack( ); BugCheck.Log( "NodeObj = %x", (int)ObjectHeader.Unpack( nodeObj ).ToPointer( ) ); GCNode node2 = (GCNode)nodeObj; BugCheck.Log( "node2 is: id= %d", node2._id ); } private static void SelfTest__Memory__RefCountGC9( ) { BugCheck.Log( "RefCountGC9 Started..." ); uint availableMemoryBefore = MemoryManager.Instance.AvailableMemory; BugCheck.Log( "Available memory before = %d", (int)availableMemoryBefore ); RefCountGC9_Helper( ); uint availableMemoryAfter = MemoryManager.Instance.AvailableMemory; BugCheck.Log( "Available memory after = %d", (int)availableMemoryAfter ); BugCheck.Assert( availableMemoryBefore == availableMemoryAfter, BugCheck.StopCode.HeapCorruptionDetected ); BugCheck.Log( "RefCountGC9 Succeeded." ); } private static void RefCountGC10_Helper( ) { String a = new string( 'a', 3 ); String b = "bbb"; char[] array = { 'c', 'c', 'c' }; String c = new string( array ); BugCheck.Log( a ); BugCheck.Log( b ); BugCheck.Log( c ); String concat = a + b + c; BugCheck.Log( concat ); } private static void SelfTest__Memory__RefCountGC10( ) { BugCheck.Log( "RefCountGC10 Started..." ); uint availableMemoryBefore = MemoryManager.Instance.AvailableMemory; BugCheck.Log( "Available memory before = %d", (int)availableMemoryBefore ); RefCountGC10_Helper( ); uint availableMemoryAfter = MemoryManager.Instance.AvailableMemory; BugCheck.Log( "Available memory after = %d", (int)availableMemoryAfter ); BugCheck.Assert( availableMemoryBefore == availableMemoryAfter, BugCheck.StopCode.HeapCorruptionDetected ); BugCheck.Log( "RefCountGC10 Succeeded." ); } private static GCNode RefCountGC11_SetupHelper() { var node = new GCNode( new GCNode( null, null ), null ); BugCheck.Log( "Node created: id= %d", node._id ); BugCheck.Log( "Node.node1 created: id= %d", node._node1._id ); return node; } private static void RefCountGC11_ExchangeHelper( GCNode node ) { var node1 = new GCNode( null, null ); BugCheck.Log( "Node created: id= %d", node1._id ); var oldNode1 = Interlocked.Exchange( ref node._node1, node1 ); BugCheck.Assert( MemoryManager.Instance.IsObjectAlive( ObjectHeader.Unpack( oldNode1 ).ToPointer( ) ), BugCheck.StopCode.HeapCorruptionDetected ); } private static void RefCountGC11_CompareExchangeHelper( GCNode node ) { var node1 = node._node1; var newNode1 = new GCNode( null, null ); BugCheck.Log( "Node created: id= %d", newNode1._id ); var oldNode1 = Interlocked.CompareExchange( ref node._node1, newNode1, null ); BugCheck.Assert( MemoryManager.Instance.IsObjectAlive( ObjectHeader.Unpack( oldNode1 ).ToPointer( ) ), BugCheck.StopCode.HeapCorruptionDetected ); oldNode1 = Interlocked.CompareExchange( ref node._node1, newNode1, node1 ); BugCheck.Assert( MemoryManager.Instance.IsObjectAlive( ObjectHeader.Unpack( oldNode1 ).ToPointer( ) ), BugCheck.StopCode.HeapCorruptionDetected ); } private static void RefCountGC11_Helper( ) { GCNode node = RefCountGC11_SetupHelper( ); RefCountGC11_ExchangeHelper( node ); BugCheck.Log( "Node.node1 is now: id= %d", node._node1._id ); BugCheck.Assert( MemoryManager.Instance.IsObjectAlive( ObjectHeader.Unpack( node._node1 ).ToPointer( ) ), BugCheck.StopCode.HeapCorruptionDetected ); RefCountGC11_CompareExchangeHelper( node ); BugCheck.Log( "Node.node1 is now: id= %d", node._node1._id ); BugCheck.Assert( MemoryManager.Instance.IsObjectAlive( ObjectHeader.Unpack( node._node1 ).ToPointer( ) ), BugCheck.StopCode.HeapCorruptionDetected ); } private static void SelfTest__Memory__RefCountGC11( ) { BugCheck.Log( "RefCountGC11 Started..." ); uint availableMemoryBefore = MemoryManager.Instance.AvailableMemory; BugCheck.Log( "Available memory before = %d", (int)availableMemoryBefore ); RefCountGC11_Helper( ); uint availableMemoryAfter = MemoryManager.Instance.AvailableMemory; BugCheck.Log( "Available memory after = %d", (int)availableMemoryAfter ); BugCheck.Assert( availableMemoryBefore == availableMemoryAfter, BugCheck.StopCode.HeapCorruptionDetected ); BugCheck.Log( "RefCountGC11 Succeeded." ); } private static void RefCountGC12_Helper() { GCNode node = new GCNode(null, null); UIntPtr nodeptr = ObjectHeader.Unpack(node).ToPointer(); Object result; for(int i = 0; i < 10; i++) { result = RefCountGC12_Helper1(node); BugCheck.Assert(MemoryManager.Instance.IsObjectAlive(nodeptr), BugCheck.StopCode.HeapCorruptionDetected); } } [NoInline] private static object RefCountGC12_Helper1(object obj) { if (obj != null) { obj = RefCountGC12_Helper2(obj); } return obj; } [NoInline] public static object RefCountGC12_Helper2(object obj) { return obj; } private static void SelfTest__Memory__RefCountGC12( ) { BugCheck.Log( "RefCountGC12 Started..." ); uint availableMemoryBefore = MemoryManager.Instance.AvailableMemory; BugCheck.Log( "Available memory before = %d", (int)availableMemoryBefore ); RefCountGC12_Helper( ); uint availableMemoryAfter = MemoryManager.Instance.AvailableMemory; BugCheck.Log( "Available memory after = %d", (int)availableMemoryAfter ); BugCheck.Assert( availableMemoryBefore == availableMemoryAfter, BugCheck.StopCode.HeapCorruptionDetected ); BugCheck.Log( "RefCountGC12 Succeeded." ); } #endregion RefCount GC Tests //--// //--// //--// #region pointers basic private static unsafe void SelfTest__Test__RawPointers_Arithmetic_Pointer_1( ) { // // Pointer arithmetic, 1 value // int pointed = 42; int* a = &pointed; int* aa = &pointed; a += 1; SELFTEST_ASSERT( a == aa + 1 ); } private static unsafe void SelfTest__Test__RawPointers_Arithmetic_Pointer_2( ) { // // Pointer arithmetic, 2 values // int pointed = 42; int* a = &pointed; int* b = &pointed; int* aa = &pointed; int* bb = &pointed; a += 1; b += 2; SELFTEST_ASSERT( a == aa + 1 ); SELFTEST_ASSERT( b == bb + 2 ); } private static unsafe void SelfTest__Test__RawPointers_Arithmetic_Values_1( ) { // // Pointer arithmetic, 2 values // int pointed = 42; /*const*/ int const_pointed = 42; int* a = &pointed; int* aa = &const_pointed; *a += 1; SELFTEST_ASSERT( *a == *aa + 1 ); } private static unsafe void SelfTest__Test__RawPointers_Arithmetic_Values_2( ) { // // Pointer arithmetic, 2 values // int pointed = 42; /*const*/ int const_pointed = 42; int* a = &pointed; int* b = &pointed; int* aa = &const_pointed; int* bb = &const_pointed; *a += 1; *b += 2; SELFTEST_ASSERT( *a == *aa + 3 ); SELFTEST_ASSERT( *b == *bb + 3 ); } private static void SelfTest__Test__Pointers_Conversions_1( ) { IntPtr a = ( IntPtr )0x10004000; int aa = a.ToInt32( ); SELFTEST_ASSERT( aa == 0x10004000 ); } private static void SelfTest__Test__Pointers_Conversions_2( ) { IntPtr a = ( IntPtr )0x10004000; IntPtr b = ( IntPtr )0x10004000; int aa = a.ToInt32( ); int bb = b.ToInt32( ); SELFTEST_ASSERT( a == b ); SELFTEST_ASSERT( aa == bb ); } private static void SelfTest__Test__Pointers_Conversions_3( ) { UIntPtr a = ( UIntPtr )0x10004000; uint aa = a.ToUInt32( ); SELFTEST_ASSERT( aa == 0x10004000 ); } private static void SelfTest__Test__Pointers_Conversions_4( ) { UIntPtr a = ( UIntPtr )0x10004000; UIntPtr b = ( UIntPtr )0x10004000; uint aa = a.ToUInt32( ); uint bb = b.ToUInt32( ); SELFTEST_ASSERT( a == b ); SELFTEST_ASSERT( aa == bb ); } private static void SelfTest__Test__Pointers_PassByValue( ) { IntPtr a = ( IntPtr )10; IntPtr b = ( IntPtr )10; PassByValue( a, b ); SELFTEST_ASSERT( a.ToInt32( ) == 10 ); SELFTEST_ASSERT( b.ToInt32( ) == 10 ); SELFTEST_ASSERT( ( a.ToInt32( ) == b.ToInt32( ) ) ); SELFTEST_ASSERT( ( a.ToInt32( ) + b.ToInt32( ) ) == 20); } private static void PassByValue( IntPtr a, IntPtr b ) { int val = 5; a = ( IntPtr )val; b = ( IntPtr )val; } private static void SelfTest__Test__Pointers_PassByRef( ) { IntPtr a = ( IntPtr )10; IntPtr b = ( IntPtr )11; PassByRef( ref a, ref b ); SELFTEST_ASSERT( a.ToInt32( ) == 5 ); SELFTEST_ASSERT( b.ToInt32( ) == 5 ); SELFTEST_ASSERT( ( a.ToInt32( ) == b.ToInt32( ) ) ); SELFTEST_ASSERT( ( a.ToInt32( ) + b.ToInt32( ) ) == 10); } private static void PassByRef( ref IntPtr a, ref IntPtr b ) { int val = 5; a = ( IntPtr )val; b = ( IntPtr )val; } #endregion pointers basic //--// //--// //--// #region pointers advanced private struct Foo { public IntPtr barSigned; public int dummyNativeInt; public byte dummy; public Int32 dummyInt; public UIntPtr barUnsigned; } private static void SelfTest__Test__ValueType_Pointer_ByteDummy( ) { byte b = ( byte )0xFF; Foo foo1; foo1.barSigned = ( IntPtr )10; foo1.dummyNativeInt = 7; foo1.dummy = b; foo1.dummyInt = 15; foo1.barUnsigned = ( UIntPtr )20; Foo foo2; foo2.barSigned = ( IntPtr )5; foo2.dummyNativeInt = 7; foo2.dummy = b; foo2.dummyInt = 15; foo2.barUnsigned = ( UIntPtr )15; SELFTEST_ASSERT( ( ( int )foo1.barSigned ) == ( ( int )foo2.barSigned ) + 5 ); SELFTEST_ASSERT( ( ( int )foo1.barUnsigned ) == ( ( int )foo2.barUnsigned ) + 5 ); SELFTEST_ASSERT( foo1.dummy == foo2.dummy ); SELFTEST_ASSERT( foo1.dummyInt == foo2.dummyInt ); SELFTEST_ASSERT( foo1.dummyNativeInt == foo2.dummyNativeInt ); PassByRef( ref foo1, ref foo2 ); SELFTEST_ASSERT( ( ( int )foo1.barSigned ) == ( ( int )foo2.barSigned ) + 5 ); SELFTEST_ASSERT( ( ( int )foo1.barUnsigned ) == ( ( int )foo2.barUnsigned ) + 5 ); SELFTEST_ASSERT( foo1.dummy == foo2.dummy ); SELFTEST_ASSERT( foo1.dummyInt == foo2.dummyInt + 5 ); SELFTEST_ASSERT( foo1.dummyNativeInt == foo2.dummyNativeInt + 5 ); } private static void PassByRef( ref Foo foo1, ref Foo foo2 ) { foo1.barSigned = ( IntPtr )50; foo1.barUnsigned = ( UIntPtr )60; foo1.dummyInt = 65; foo1.dummyNativeInt = ( Int32 )75; foo2.barSigned = ( IntPtr )45; foo2.barUnsigned = ( UIntPtr )55; foo2.dummyInt = 60; foo2.dummyNativeInt = ( Int32 )70; } private unsafe struct FooBytePointer { public IntPtr barSigned; public byte* dummy; public UIntPtr barUnsigned; } private static unsafe void SelfTest__Test__ValueType_Pointer_BytePointerDummy( ) { byte b = ( byte )0xFF; FooBytePointer foo1; foo1.barSigned = ( IntPtr )10; foo1.dummy = &b; foo1.barUnsigned = ( UIntPtr )20; FooBytePointer foo2; foo2.barSigned = ( IntPtr )5; foo2.dummy = &b; foo2.barUnsigned = ( UIntPtr )15; SELFTEST_ASSERT( ( ( int )foo1.barSigned ) == ( ( int )foo2.barSigned ) + 5 ); SELFTEST_ASSERT( ( ( int )foo1.barUnsigned ) == ( ( int )foo2.barUnsigned ) + 5 ); SELFTEST_ASSERT( foo1.dummy == foo2.dummy ); PassByRef( ref foo1, ref foo2 ); SELFTEST_ASSERT( ( ( int )foo1.barSigned ) == ( ( int )foo2.barSigned ) + 5 ); SELFTEST_ASSERT( ( ( int )foo1.barUnsigned ) == ( ( int )foo2.barUnsigned ) + 5 ); SELFTEST_ASSERT( foo1.dummy == foo2.dummy ); } private static void PassByRef( ref FooBytePointer foo1, ref FooBytePointer foo2 ) { foo1.barSigned = ( IntPtr )50; foo1.barUnsigned = ( UIntPtr )60; foo2.barSigned = ( IntPtr )45; foo2.barUnsigned = ( UIntPtr )55; } #endregion pointers advanced //--// //--// //--// #region integers private static void SelfTest__Test__Integers_Conversions( ) { #region up #region signed // // up - int to long // int a3 = 10; long b3 = a3; SELFTEST_ASSERT( a3 == b3 ); // // up - short to int // short a4 = 10; int b4 = a4; SELFTEST_ASSERT( a4 == b4 ); // // up - sbyte to int // sbyte a5 = 10; int b5 = a5; SELFTEST_ASSERT( a5 == b5 ); #endregion signed #region unsigned // // up - uint to ulong // uint a31 = 10; ulong b31 = a31; SELFTEST_ASSERT( a31 == b31 ); // // up - ushort to uint // ushort a41 = 10; uint b41 = a41; SELFTEST_ASSERT( a41 == b41 ); // // up - byte to uint // byte a51 = 10; uint b51 = a51; SELFTEST_ASSERT( a51 == b51 ); #endregion unsigned #endregion up #region down #region signed // // down - long to int // long a = 10; int b = ( int )a; SELFTEST_ASSERT( a == b ); // // down - int to short // int a0 = 10; short b0 = ( short )a; SELFTEST_ASSERT( a0 == b0 ); // // down - int to byte // int a1 = 10; byte b1 = ( byte )a1; SELFTEST_ASSERT( a1 == b1 ); #endregion signed #region unsigned // // down - ulong to uint // ulong a6 = 10; uint b6 = ( uint )a6; SELFTEST_ASSERT( a6 == b6 ); // // down - uint to ushort // uint a7 = 10; ushort b7 = ( ushort )a7; SELFTEST_ASSERT( a7 == b7 ); // // down - uint to byte // uint a8 = 10; byte b8 = ( byte )a8; SELFTEST_ASSERT( a8 == b8 ); #endregion unsigned #endregion down } //--// //--// //--// private static void SelfTest__Test__Integers_PassByValue( ) { int a = GetANumber(); int b = GetANumber(); SELFTEST_ASSERT( a + b == PassByValue( a, b ) ); } private static int PassByValue( int a, int b ) { return a + b; } private static void SelfTest__Test__Integers_PassByRef( ) { int a = GetANumber(); int b = GetANumber(); int c = a + b; PassByRef( ref a, ref b ); SELFTEST_ASSERT( c + 3 == a + b ); } private static void PassByRef( ref int a, ref int b ) { a += 1; b += 2; } #endregion integers } } ================================================ FILE: Zelig/Zelig/RunTime/Zelig/Kernel/SmartHandles/CriticalSectionHolder.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // namespace Microsoft.Zelig.Runtime.SmartHandles { using System; using System.Runtime.CompilerServices; using TS = Microsoft.Zelig.Runtime.TypeSystem; public struct CriticalSectionHolder : IDisposable { // // State // Synchronization.CriticalSection m_target; // // Constructor Methods // [Inline] public CriticalSectionHolder( Synchronization.CriticalSection target ) { m_target = target; target.Acquire(); } // // Helper Methods // [Inline] public void Dispose() { m_target.Release(); } } } ================================================ FILE: Zelig/Zelig/RunTime/Zelig/Kernel/SmartHandles/InterruptState.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // namespace Microsoft.Zelig.Runtime.SmartHandles { using System; using System.Runtime.CompilerServices; using TS = Microsoft.Zelig.Runtime.TypeSystem; // // These methods are not really implemented as internal call, // a open class will provide the implementation, based on the target platform. // public struct InterruptState : IDisposable { // // Constructor Methods // [MethodImpl( MethodImplOptions.InternalCall )] public extern InterruptState( uint cpsr ); // // Helper Methods // [MethodImpl( MethodImplOptions.InternalCall )] public extern void Dispose(); [MethodImpl( MethodImplOptions.InternalCall )] public extern void Toggle(); //--// [MethodImpl( MethodImplOptions.InternalCall )] public static extern InterruptState Disable(); [MethodImpl( MethodImplOptions.InternalCall )] public static extern InterruptState DisableAll(); [MethodImpl( MethodImplOptions.InternalCall )] public static extern InterruptState Enable(); [MethodImpl( MethodImplOptions.InternalCall )] public static extern InterruptState EnableAll(); // // Access Methods // [MethodImpl( MethodImplOptions.InternalCall )] public extern uint GetPreviousState(); [MethodImpl( MethodImplOptions.InternalCall )] public extern HardwareException GetCurrentExceptionMode(); } } ================================================ FILE: Zelig/Zelig/RunTime/Zelig/Kernel/SmartHandles/SwapCurrentThread.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // namespace Microsoft.Zelig.Runtime.SmartHandles { using System; using System.Runtime.CompilerServices; using TS = Microsoft.Zelig.Runtime.TypeSystem; public struct SwapCurrentThread : IDisposable { // // State // ThreadImpl m_previousThread; // // Constructor Methods // internal SwapCurrentThread( ThreadImpl newThread ) { using(SmartHandles.InterruptState.DisableAll()) { m_previousThread = ThreadImpl.CurrentThread; ThreadImpl.CurrentThread = newThread; } } // // Helper Methods // public void Dispose() { using(SmartHandles.InterruptState.DisableAll()) { ThreadImpl.CurrentThread = m_previousThread; } } } } ================================================ FILE: Zelig/Zelig/RunTime/Zelig/Kernel/SmartHandles/SwapCurrentThreadUnderInterrupt.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // namespace Microsoft.Zelig.Runtime.SmartHandles { using System; using System.Runtime.CompilerServices; using TS = Microsoft.Zelig.Runtime.TypeSystem; public struct SwapCurrentThreadUnderInterrupt : IDisposable { // // State // ThreadImpl m_previousThread; internal ThreadImpl PreviousThread { get { return m_previousThread; } } // // Constructor Methods // internal SwapCurrentThreadUnderInterrupt( ThreadImpl newThread ) { BugCheck.AssertInterruptsOff(); m_previousThread = ThreadImpl.CurrentThread; #if USE_THREAD_PERFORMANCE_COUNTER if(m_previousThread != null) { m_previousThread.ReleasedProcessor(); } newThread.AcquiredProcessor(); #endif // USE_THREAD_PERFORMANCE_COUNTER ThreadImpl.CurrentThread = newThread; } // // Helper Methods // public void Dispose() { BugCheck.AssertInterruptsOff(); ThreadImpl newThread = ThreadImpl.CurrentThread; #if USE_THREAD_PERFORMANCE_COUNTER if(newThread != null) { newThread.ReleasedProcessor(); } if(m_previousThread != null) { m_previousThread.AcquiredProcessor(); } #endif // USE_THREAD_PERFORMANCE_COUNTER ThreadImpl.CurrentThread = m_previousThread; } } } ================================================ FILE: Zelig/Zelig/RunTime/Zelig/Kernel/SmartHandles/YieldLockHolder.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // namespace Microsoft.Zelig.Runtime.SmartHandles { using System; using System.Runtime.CompilerServices; using TS = Microsoft.Zelig.Runtime.TypeSystem; public struct YieldLockHolder : IDisposable { // // State // Synchronization.YieldLock m_target; ThreadImpl m_thisThread; System.Threading.ThreadPriority m_thisThreadPriority; // // Constructor Methods // [Inline] public YieldLockHolder( Synchronization.YieldLock target ) { m_target = target; m_thisThread = ThreadImpl.CurrentThread; m_thisThreadPriority = (null != m_thisThread) ? m_thisThread.Priority : System.Threading.ThreadPriority.Normal; target.Acquire(m_thisThread); } // // Helper Methods // [Inline] public void Dispose() { m_target.Release(m_thisThread); //restore original priority in case //we were bumped during lock-execution by a higher priority thread. if ((null != m_thisThread) && (m_thisThread.Priority != m_thisThreadPriority)) { m_thisThread.Priority = m_thisThreadPriority; } } } } ================================================ FILE: Zelig/Zelig/RunTime/Zelig/Kernel/Support/BugCheck.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // namespace Microsoft.Zelig.Runtime { using System; using System.Runtime.CompilerServices; using TS = Microsoft.Zelig.Runtime.TypeSystem; public static class BugCheck { public enum StopCode { InterruptsNotDisabled , InterruptsNotEnabled , UnwindFailure , KernelNodeStillLinked , NoCurrentThread , ExpectingReadyThread , NoFreeSyncBlock , SyncBlockCorruption , NegativeIndex , IncorrectArgument , NoMemory , NoMarkStack , NotAMemoryReference , HeapCorruptionDetected , IllegalMode , IllegalConfiguration , FailedBootstrap , IllegalSchedule , CtxSwitchFailed , StackCorruptionDetected , InvalidSupervisorCall , InvalidOperation , Impossible , Fault_Vectors , ForcedHardFault , Fault_Unknown , } // // Helper Methods // [Inline] public static void Assert( bool condition , StopCode code ) { if(!condition) { Raise( code ); } } [NoReturn] [NoInline] [TS.WellKnownMethod( "BugCheck_Raise" )] public static void Raise( StopCode code ) { Device.Instance.ProcessBugCheck( code ); } public static void Log(string format) { Device.Instance.ProcessLog(format); } public static void Log(string format, int p1) { Device.Instance.ProcessLog(format, p1); } public static void Log(string format, int p1, int p2) { Device.Instance.ProcessLog(format, p1, p2); } public static void Log(string format, int p1, int p2, int p3) { Device.Instance.ProcessLog(format, p1, p2, p3); } public static void Log(string format, int p1, int p2, int p3, int p4) { Device.Instance.ProcessLog(format, p1, p2, p3, p4); } public static void Log(string format, int p1, int p2, int p3, int p4, int p5) { Device.Instance.ProcessLog(format, p1, p2, p3, p4, p5); } //--// public static void AssertInterruptsOff() { Assert( Processor.Instance.AreInterruptsDisabled(), BugCheck.StopCode.InterruptsNotDisabled ); } public static void AssertInterruptsOn() { Assert( Processor.Instance.AreInterruptsEnabled(), BugCheck.StopCode.InterruptsNotEnabled ); } //--// [NoInline] [TS.WellKnownMethod( "BugCheck_WriteLine" )] public static void WriteLine( string text ) { BugCheck.Log( text ); } public static void WriteLineFormat( string fmt , params object[] parms ) { WriteLine( string.Format( fmt, parms ) ); } } } ================================================ FILE: Zelig/Zelig/RunTime/Zelig/Kernel/Support/KernelCircularBuffer.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // namespace Microsoft.Zelig.Runtime { using System; using System.Threading; using System.Runtime.CompilerServices; public sealed class KernelCircularBuffer< T > { // // State // private readonly int m_size; private readonly T[] m_array; private readonly ManualResetEvent m_writerEvent; private readonly ManualResetEvent m_readerEvent; private int m_count; private int m_writerPos; private int m_readerPos; // // Constructor Methods // public KernelCircularBuffer( int size ) { m_size = size; m_array = new T[size]; m_writerEvent = new ManualResetEvent( true ); m_readerEvent = new ManualResetEvent( false ); m_count = 0; m_writerPos = 0; m_readerPos = 0; } // // Helper Methods // public void Clear() { BugCheck.AssertInterruptsOff(); m_writerEvent.Set (); m_readerEvent.Reset(); m_count = 0; m_writerPos = 0; m_readerPos = 0; } public bool Peek( out T val ) { BugCheck.AssertInterruptsOff(); if(this.IsEmpty) { val = default(T); return false; } else { val = m_array[m_readerPos]; return true; } } //--// public bool EnqueueNonblocking( T val ) { BugCheck.AssertInterruptsOff(); if(this.IsFull) { return false; } if(this.IsEmpty) { m_readerEvent.Set(); } int pos = m_writerPos; m_array[pos] = val; m_writerPos = NextPosition( pos ); m_count++; if(this.IsFull) { m_writerEvent.Reset(); } return true; } public bool DequeueNonblocking( out T val ) { BugCheck.AssertInterruptsOff(); if(this.IsEmpty) { val = default(T); return false; } if(this.IsFull) { m_writerEvent.Set(); } int pos = m_readerPos; val = m_array[pos]; m_readerPos = NextPosition( pos ); m_count--; if(this.IsEmpty) { m_readerEvent.Reset(); } return true; } //--// public void EnqueueBlocking( T val ) { BugCheck.AssertInterruptsOn(); while(true) { bool fSent; using(SmartHandles.InterruptState.Disable()) { fSent = EnqueueNonblocking( val ); } if(fSent) { return; } m_writerEvent.WaitOne(); } } public T DequeueBlocking() { BugCheck.AssertInterruptsOn(); while(true) { bool fReceived; T val; using(SmartHandles.InterruptState.Disable()) { fReceived = DequeueNonblocking( out val ); } if(fReceived) { return val; } m_readerEvent.WaitOne(); } } //--// public bool EnqueueBlocking( int timeout , T val ) { BugCheck.AssertInterruptsOn(); while(true) { bool fSent; using(SmartHandles.InterruptState.Disable()) { fSent = EnqueueNonblocking( val ); } if(fSent) { return true; } if(m_writerEvent.WaitOne( timeout, false ) == false) { return false; } } } public bool DequeueBlocking( int timeout , out T val ) { BugCheck.AssertInterruptsOn(); while(true) { bool fReceived; using(SmartHandles.InterruptState.Disable()) { fReceived = DequeueNonblocking( out val ); } if(fReceived) { return true; } if(m_readerEvent.WaitOne( timeout, false ) == false) { return false; } } } [Inline] private int DequeueMultipleNonblocking(ref T[] val, int offset, int maxCount) { int totalRead = 0; if (maxCount == 0 || this.IsEmpty) { return 0; } if (this.IsFull) { m_writerEvent.Set(); } // // Potentially read twice since the data could loop around the circular // buffer. // for (int i = 0; i < 2; i++) { int countToRead = maxCount; int availableLinear = m_size - m_writerPos; if (m_count < availableLinear) { availableLinear = m_count; } if (availableLinear < countToRead) { countToRead = availableLinear; } Array.Copy(m_array, m_readerPos, val, offset, countToRead); m_readerPos = NextPosition(m_readerPos + countToRead - 1); m_count -= countToRead; maxCount -= countToRead; offset += countToRead; totalRead += countToRead; if (m_count == 0 || maxCount == 0) { break; } } if (this.IsEmpty) { m_readerEvent.Reset(); } return totalRead; } public int DequeueMultipleBlocking(ref T[] val, int offset, int maxCount, int timeout) { int countRead = 0; BugCheck.AssertInterruptsOn(); if (val.Length < offset + maxCount) { throw new ArgumentException(); } using (SmartHandles.InterruptState.Disable()) { countRead = DequeueMultipleNonblocking(ref val, offset, maxCount); } if (countRead == 0) { if (!m_readerEvent.WaitOne(timeout, false)) { throw new TimeoutException(); } using (SmartHandles.InterruptState.Disable()) { countRead += DequeueMultipleNonblocking(ref val, offset, maxCount); } } return countRead; } //--// [Inline] private int NextPosition( int val ) { val = val + 1; if(val == m_size) { return 0; } return val; } [Inline] private int PreviousPosition( int val ) { if(val == 0) { val = m_size; } return val - 1; } // // Access Methods // public int Count { get { return m_count; } } public int RemainingCapacity { get { return m_size - m_count; } } public bool IsEmpty { [Inline] get { return m_count == 0; } } public bool IsFull { [Inline] get { return m_count == m_size; } } } } ================================================ FILE: Zelig/Zelig/RunTime/Zelig/Kernel/Support/KernelList.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // namespace Microsoft.Zelig.Runtime { using System; using System.Runtime.CompilerServices; public sealed class KernelList< T > { // // State // private KernelNode< T > m_head; private KernelNode< T > m_tail; // // Constructor Methods // public KernelList() { m_head = new KernelNode< T >( default(T) ); m_tail = new KernelNode< T >( default(T) ); m_head.Next = m_tail; m_tail.Previous = m_head; } // // Helper Methods // public void InsertAtTail( KernelNode< T > node ) { node.InsertBefore( m_tail ); } public KernelNode< T > FirstNode() { KernelNode< T > node = m_head.Next; if(node != m_tail) { return node; } return null; } public T FirstTarget() { KernelNode< T > node = m_head.Next; if(node != m_tail) { return node.Target; } return default(T); } public KernelNode< T > LastNode() { KernelNode< T > node = m_tail.Previous; if(node != m_head) { return node; } return null; } public T LastTarget() { KernelNode< T > node = m_tail.Previous; if(node != m_head) { return node.Target; } return default( T ); } //--// public KernelNode< T > ExtractFirstNode() { KernelNode< T > node = m_head.Next; if(node != m_tail) { node.RemoveFromList(); return node; } return null; } // // Access Methods // public KernelNode< T > StartOfForwardWalk { get { return m_head.Next; } } public KernelNode< T > StartOfForBackwardWalk { get { return m_tail.Previous; } } } } ================================================ FILE: Zelig/Zelig/RunTime/Zelig/Kernel/Support/KernelNode.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // namespace Microsoft.Zelig.Runtime { using System; using System.Runtime.CompilerServices; public sealed class KernelNode< T > { // // State // private KernelNode< T > m_next; private KernelNode< T > m_previous; private T m_target; // // Constructor Methods // public KernelNode( T target ) { m_target = target; } // // Helper Methods // public void InsertBefore( KernelNode< T > place ) { if(m_next != null) { RemoveFromList_NoClear(); } KernelNode< T > prev = place.m_previous; prev.ConnectToNext( this ); this.ConnectToNext( place ); } public void RemoveFromList() { if(m_next != null) { RemoveFromList_NoClear(); } m_next = null; m_previous = null; } public KernelNode< T > MoveToNext() { KernelNode< T > node = this.Next; if(node.Next != null) { return node; } return null; } public KernelNode< T > MoveToPrevious() { KernelNode< T > node = this.Previous; if(node.Previous != null) { return node; } return null; } //--// [Inline] private void RemoveFromList_NoClear() { KernelNode< T > next = m_next; KernelNode< T > prev = m_previous; next.m_previous = prev; prev.m_next = next; } [Inline] private void ConnectToNext( KernelNode< T > next ) { this.m_next = next; next.m_previous = this; } public bool VerifyUnlinked() { return m_next == null && m_previous == null; } // // Access Methods // public bool IsLinked { get { return m_next != null; } } public bool IsValidForForwardMove { get { return m_next != null; } } public bool IsValidForBackwardMove { get { return m_previous == null; } } public KernelNode< T > Next { get { return m_next; } internal set { m_next = value; } } public KernelNode< T > Previous { get { return m_previous; } internal set { m_previous = value; } } public T Target { get { return m_target; } } } } ================================================ FILE: Zelig/Zelig/RunTime/Zelig/Kernel/Support/KernelPerformanceCounter.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // namespace Microsoft.Zelig.Runtime { using System; using System.Runtime.CompilerServices; public struct KernelPerformanceCounter { // // State // uint m_hits; uint m_start; ulong m_total; // // Helper Methods // public void Start() { m_start = Peripherals.Instance.ReadPerformanceCounter(); } public void Stop() { m_hits += 1; m_total += (Peripherals.Instance.ReadPerformanceCounter() - m_start); } public void Merge( KernelPerformanceCounter other ) { m_hits += other.m_hits; m_total += other.m_total; } } } ================================================ FILE: Zelig/Zelig/RunTime/Zelig/Kernel/Support/LandingPadResult.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // namespace Microsoft.Zelig.Runtime { using System; using TS = Microsoft.Zelig.Runtime.TypeSystem; [TS.WellKnownType("Microsoft_Zelig_Runtime_LandingPadResult")] internal struct LandingPadResult { // WARNING: Modify these fields only with extreme caution. LLVM expects landing pad result // types to be a struct with two members. No fields may be added or removed, even if unused. // The types and meaning of these fields are implementation dependent, and strongly tied to // the personality function that creates the result. See LLOS_Personality for more details. public IntPtr Exception; public int Selector; } } ================================================ FILE: Zelig/Zelig/RunTime/Zelig/Kernel/Synchronization/CriticalSection.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // namespace Microsoft.Zelig.Runtime.Synchronization { using System; using System.Runtime.CompilerServices; public sealed class CriticalSection : WaitableObject { public static class Configuration { public static bool ImmediatelyTransferOwnership { [ConfigurationOption("CriticalSection__ImmediatelyTransferOwnership")] get { return false; } } public static bool AvoidPriorityInversionOnRelease { [ConfigurationOption("CriticalSection__AvoidPriorityInversionOnRelease")] get { return false; } } } // // State // volatile ThreadImpl m_ownerThread; volatile int m_nestingCount; // // Constructor Methods // public CriticalSection() { } // // Helper Methods // public override bool Acquire( SchedulerTime timeout ) { ThreadImpl thisThread = ThreadImpl.CurrentThread; if(thisThread == null) { // // Special case for boot code path: all locks are transparent. // return true; } // // Fast shortcut for non-contended case. // if(m_ownerThread == null) { #if ENABLE_GENERICS_BUG #pragma warning disable 420 if(System.Threading.Interlocked.CompareExchange< ThreadImpl >( ref m_ownerThread, thisThread, null ) == null) #pragma warning restore 420 { thisThread.AcquiredWaitableObject( this ); return true; } #endif // ENABLE_GENERICS_BUG } // // Fast shortcut for nested calls. // if(m_ownerThread == thisThread) { m_nestingCount++; return true; } using(Synchronization.WaitingRecord.Holder holder = WaitingRecord.Holder.Get( thisThread, this, timeout )) { while(true) { bool fNotify = false; bool fResult = false; using(SmartHandles.InterruptState.Disable()) { if(holder.ShouldTryToAcquire) { if(m_ownerThread == null) { m_ownerThread = thisThread; fNotify = true; fResult = true; } else { if(m_ownerThread == thisThread) { m_nestingCount++; fResult = true; } } } } if(fNotify) { thisThread.AcquiredWaitableObject( this ); } if(fResult) { return fResult; } if(holder.RequestProcessed) { return holder.RequestFulfilled; } } } } public override void Release() { ThreadImpl thisThread = ThreadImpl.CurrentThread; if(thisThread == null) { // // Special case for boot code path: all locks are transparent. // return; } if(m_ownerThread != thisThread) { #if EXCEPTION_STRINGS throw new Exception( "Releasing waitable object not owned by thread" ); #else throw new Exception(); #endif } if(m_nestingCount > 0) { m_nestingCount--; return; } thisThread.ReleasedWaitableObject( this ); ThreadImpl ownerThread = null; ThreadImpl wakeupThread = null; using(SmartHandles.InterruptState.Disable()) { WaitingRecord wr = m_listWaiting.FirstTarget(); if(wr != null) { wakeupThread = wr.Source; if( Configuration.ImmediatelyTransferOwnership || (Configuration.AvoidPriorityInversionOnRelease && thisThread.Priority < wakeupThread.Priority) ) { ownerThread = wakeupThread; wr.RequestFulfilled = true; } } m_ownerThread = ownerThread; } if(ownerThread != null) { ownerThread.AcquiredWaitableObject( this ); } if(wakeupThread != null) { wakeupThread.Wakeup(); } } //--// // // Access Methods // } } ================================================ FILE: Zelig/Zelig/RunTime/Zelig/Kernel/Synchronization/WaitableObject.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // namespace Microsoft.Zelig.Runtime.Synchronization { using System; using System.Runtime.CompilerServices; public abstract class WaitableObject { // // State // protected KernelNode< WaitableObject > m_ownershipLink; protected KernelList< WaitingRecord > m_listWaiting; // // Constructor Methods // protected WaitableObject() { m_ownershipLink = new KernelNode< WaitableObject >( this ); m_listWaiting = new KernelList< WaitingRecord >(); } // // Helper Methods // public abstract bool Acquire( SchedulerTime timeout ); public abstract void Release(); //--// public bool Acquire() { return Acquire( SchedulerTime.MaxValue ); } public void Dispose() { using(SmartHandles.InterruptState.Disable()) { WaitingRecord wr; while((wr = m_listWaiting.FirstTarget()) != null) { wr.RequestFulfilled = false; } } } //--// public void RegisterWait( KernelNode< WaitingRecord > node ) { m_listWaiting.InsertAtTail( node ); } public void UnregisterWait( KernelNode< WaitingRecord > node ) { node.RemoveFromList(); } // // Access Methods // public KernelNode< WaitableObject > OwnershipLink { get { return m_ownershipLink; } } } } ================================================ FILE: Zelig/Zelig/RunTime/Zelig/Kernel/Synchronization/WaitingRecord.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // namespace Microsoft.Zelig.Runtime.Synchronization { using System; using System.Runtime.CompilerServices; public sealed class WaitingRecord { // // HACK: We have a bug in the liveness of multi-pointer structure. We have to use a class instead. // /// public struct Holder : IDisposable public class Holder : IDisposable { // // State // ThreadImpl m_thread; Synchronization.WaitableObject m_waitableObject; SchedulerTime m_timeout; WaitingRecord m_wr; // // Constructor Methods // internal Holder() { } // // Helper Methods // public void Dispose() { if(m_wr != null) { using(SmartHandles.InterruptState.Disable()) { m_wr.Recycle(); m_thread = null; m_waitableObject = null; m_wr = null; } } } // // HACK: We have a bug in the liveness of multi-pointer structure. We have to use a class instead. Use this instead of the parametrized constructor. public static Holder Get(ThreadImpl thread, Synchronization.WaitableObject waitableObject, SchedulerTime timeout) { Holder hld = thread.m_holder; hld.m_thread = thread; hld.m_waitableObject = waitableObject; hld.m_timeout = timeout; hld.m_wr = null; return hld; } // // Access Methods // public bool ShouldTryToAcquire { get { return m_wr == null || m_wr.Processed == false; } } public bool RequestProcessed { get { // // We do two passes through the acquire phase. // // On the first pass, we don't allocate a WaitingRecord, we just try to acquire the resource. // If that fails, we allocate a WaitingRecord, connect it and // // On the second pass, we retry to acquire the resource and if that fails, we simply wait. // if(m_wr == null) { m_wr = WaitingRecord.GetInstance(m_thread, m_waitableObject, m_timeout); using(SmartHandles.InterruptState.Disable()) { m_wr.Connect(); } return false; } else { m_wr.Wait(); return m_wr.Processed; } } } public bool RequestFulfilled { get { return m_wr.RequestFulfilled; } } } // // State // const int RecycleLimit = 32; static KernelList< WaitingRecord > s_recycledList; static int s_recycledCount; KernelNode< WaitingRecord > m_linkTowardSource; KernelNode< WaitingRecord > m_linkTowardTarget; ThreadImpl m_source; WaitableObject m_target; SchedulerTime m_timeout; volatile bool m_processed; volatile bool m_fulfilled; // // Constructor Methods // static WaitingRecord() { s_recycledList = new KernelList(); using(SmartHandles.InterruptState.Disable()) { while(s_recycledCount < RecycleLimit) { WaitingRecord wr = new WaitingRecord(); wr.Recycle(); } } } private WaitingRecord() { m_linkTowardSource = new KernelNode(this); m_linkTowardTarget = new KernelNode(this); } // // Helper Methods // static WaitingRecord GetInstance(ThreadImpl source, WaitableObject target, SchedulerTime timeout) { BugCheck.AssertInterruptsOn(); WaitingRecord wr = null; if(s_recycledCount > 0) { using(SmartHandles.InterruptState.Disable()) { KernelNode< WaitingRecord > node = s_recycledList.ExtractFirstNode(); if(node != null) { wr = node.Target; s_recycledCount--; } } } if(wr == null) { wr = new WaitingRecord(); } wr.m_source = source; wr.m_target = target; wr.m_timeout = timeout; return wr; } void Connect() { BugCheck.AssertInterruptsOff(); m_target.RegisterWait(m_linkTowardTarget); m_source.RegisterWait(m_linkTowardSource); } void Wait() { ThreadManager.Instance.SwitchToWait(this); } void Recycle() { BugCheck.AssertInterruptsOff(); Disconnect(); if(s_recycledCount < RecycleLimit) { m_processed = false; m_fulfilled = false; s_recycledCount++; s_recycledList.InsertAtTail(m_linkTowardTarget); } } void Disconnect() { BugCheck.AssertInterruptsOff(); if(m_linkTowardSource.IsLinked) { m_source.UnregisterWait(m_linkTowardSource); } if(m_linkTowardTarget.IsLinked) { m_target.UnregisterWait(m_linkTowardTarget); } m_target = null; m_source = null; } // // Access Methods // public ThreadImpl Source { get { return m_source; } } public WaitableObject Target { get { return m_target; } } public SchedulerTime Timeout { get { return m_timeout; } } public bool Processed { get { return m_processed; } } public bool RequestFulfilled { get { return m_fulfilled; } set { if(m_processed == false) { using(SmartHandles.InterruptState.Disable()) { m_fulfilled = value; m_processed = true; Disconnect(); } } } } } } ================================================ FILE: Zelig/Zelig/RunTime/Zelig/Kernel/Synchronization/YieldLock.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // namespace Microsoft.Zelig.Runtime.Synchronization { using System; using System.Runtime.CompilerServices; public sealed class YieldLock { // // State // volatile ThreadImpl m_ownerThread; volatile int m_nestingCount; // // Constructor Methods // public YieldLock() { } // // Helper Methods // public void Acquire(ThreadImpl thisThread) { if(thisThread == null) { // // Special case for boot code path: all locks are transparent. // return; } while(true) { using(SmartHandles.InterruptState.Disable()) { if(m_ownerThread == null) { m_ownerThread = thisThread; return; } if(m_ownerThread == thisThread) { m_nestingCount++; return; } //bump priority to prevent priority inversion problems if ((int)m_ownerThread.Priority < (int)thisThread.Priority) { m_ownerThread.Priority = thisThread.Priority; } } thisThread.Yield(); } } public void Release(ThreadImpl thisThread) { if(thisThread == null) { // // Special case for boot code path: all locks are transparent. // return; } if(m_ownerThread != thisThread) { #if EXCEPTION_STRINGS throw new Exception( "Releasing waitable object not owned by thread" ); #else throw new Exception(); #endif } if(m_nestingCount > 0) { m_nestingCount--; return; } m_ownerThread = null; } public bool IsHeldByCurrentThread() { return ThreadImpl.CurrentThread == m_ownerThread; } // // Access Methods // } } ================================================ FILE: Zelig/Zelig/RunTime/Zelig/Kernel/SystemServices/Configuration.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // namespace Microsoft.Zelig.Runtime { using System; using System.Runtime.CompilerServices; using TS = Microsoft.Zelig.Runtime.TypeSystem; public static class Configuration { // // Calls to this method get redirected to the EntryPoint of the application. // [TS.WellKnownMethod( "Configuration_ExecuteApplication" )] public static extern void ExecuteApplication(); public static ulong CoreClockFrequency { [ConfigurationOption("System__CoreClockFrequency")] get { return 0; } } public static ulong RealTimeClockFrequency { [ConfigurationOption("System__RealTimeClockFrequency")] get { return 0; } } public static int DefaultThreadPoolThreads { [ConfigurationOption("System__Runtime_DefaultThreadPoolThreads")] get { return 2; } } public static int DefaultTimerPoolThreads { [ConfigurationOption("System__Runtime_DefaultTimerPooThreads")] get { return 1; } } } } ================================================ FILE: Zelig/Zelig/RunTime/Zelig/Kernel/SystemServices/GarbageCollectionManager.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // namespace Microsoft.Zelig.Runtime { using System; using System.Runtime.CompilerServices; using TS = Microsoft.Zelig.Runtime.TypeSystem; [ImplicitInstance] [ForceDevirtualization] [TS.WellKnownType("Microsoft_Zelig_Runtime_GarbageCollectionManager")] public abstract class GarbageCollectionManager { public static class Configuration { public static bool CollectMinimalPerformanceStatistics { [ConfigurationOption("GarbageCollectionManager__CollectMinimalPerformanceStatistics")] get { return false; } } public static bool CollectPerformanceStatistics { [ConfigurationOption("GarbageCollectionManager__CollectPerformanceStatistics")] get { return false; } } public static bool TraceFreeBlocks { [ConfigurationOption("GarbageCollectionManager__TraceFreeBlocks")] get { return false; } } public static bool ValidateHeap { [ConfigurationOption("GarbageCollectionManager__ValidateHeap")] get { return false; } } } class EmptyManager : GarbageCollectionManager { public override void InitializeGarbageCollectionManager() { } public override void NotifyNewObject( UIntPtr ptr , uint size ) { } public override UIntPtr FindObject( UIntPtr interiorPtr ) { return UIntPtr.Zero; } public override uint Collect() { return 0; } public override long GetTotalMemory() { return 0; } public override void ThrowOutOfMemory( TS.VTable vTable ) { BugCheck.Raise( BugCheck.StopCode.NoMemory ); } public override bool IsMarked( object target ) { return true; } public override void ExtendMarking( object target ) { } } // // State // #pragma warning disable 649 // These fields are populated at code generation. [TS.WellKnownField( "GarbageCollectionManager_m_extensionTargets" )] private readonly TS.VTable[] m_extensionTargets; [TS.WellKnownField( "GarbageCollectionManager_m_extensionHandlers" )] private readonly GarbageCollectionExtensionHandler[] m_extensionHandlers; #pragma warning restore 649 // // Helper Methods // public abstract void InitializeGarbageCollectionManager(); public abstract void NotifyNewObject( UIntPtr ptr , uint size ); public abstract UIntPtr FindObject( UIntPtr interiorPtr ); public abstract uint Collect(); public abstract long GetTotalMemory(); public abstract void ThrowOutOfMemory( TS.VTable vTable ); //--// public abstract bool IsMarked ( object target ); public abstract void ExtendMarking( object target ); [Inline] public GarbageCollectionExtensionHandler FindExtensionHandler( TS.VTable vTable ) { for(int i = 0; i < m_extensionTargets.Length; i++) { if(m_extensionTargets[i] == vTable) { return m_extensionHandlers[i]; } } return null; } // // Access Methods // public static extern GarbageCollectionManager Instance { [SingletonFactory(Fallback=typeof(EmptyManager))] [MethodImpl( MethodImplOptions.InternalCall )] get; } public GarbageCollectionExtensionHandler[] ExtensionHandlers { get { return m_extensionHandlers; } } } } ================================================ FILE: Zelig/Zelig/RunTime/Zelig/Kernel/SystemServices/MemoryManager.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // namespace Microsoft.Zelig.Runtime { using System; using System.Runtime.CompilerServices; using TS = Microsoft.Zelig.Runtime.TypeSystem; [ImplicitInstance] [ForceDevirtualization] [TS.DisableAutomaticReferenceCounting] [TS.DisableReferenceCounting] public abstract unsafe class MemoryManager { public static class Configuration { public static bool TrashFreeMemory { [ConfigurationOption("MemoryManager__TrashFreeMemory")] get { return true; } } } sealed class EmptyManager : MemoryManager { // // Helper Methods // public override void InitializeMemoryManager() { } //--// public override void ZeroFreeMemory() { } public override UIntPtr Allocate( uint size ) { return new UIntPtr( 0 ); } public override void Release(UIntPtr address) { } public override bool RefersToMemory( UIntPtr address ) { return true; } } // // State // protected MemorySegment* m_heapHead; protected MemorySegment* m_heapTail; protected MemorySegment* m_active; // // Helper Methods // public virtual void InitializeMemoryManager() { m_heapHead = null; m_heapTail = null; m_active = null; } public virtual void InitializationComplete() { } public virtual void ZeroFreeMemory() { MemorySegment* ptr = m_heapHead; while(ptr != null) { ptr->ZeroFreeMemory(); ptr = ptr->Next; } } public virtual void DirtyFreeMemory() { MemorySegment* ptr = m_heapHead; while(ptr != null) { ptr->DirtyFreeMemory(); ptr = ptr->Next; } } internal virtual void ConsistencyCheck() { } internal virtual void DumpMemory() { } internal virtual bool IsObjectAlive( UIntPtr ptr ) { throw new NotImplementedException( ); } [TS.WellKnownMethod( "MemoryManager_Allocate" )] public abstract UIntPtr Allocate( uint size ); [TS.WellKnownMethod("MemoryManager_Release")] public abstract void Release(UIntPtr address); public abstract bool RefersToMemory( UIntPtr address ); [ExportedMethod] public static UIntPtr AllocateFromManagedHeap( uint size ) { // Force all heap allocations to be multiples of 8-bytes so that we guarantee // 8-byte alignment for all allocations. size = AddressMath.AlignToDWordBoundary( size + ObjectHeader.HeaderSize ); UIntPtr ptr; using(SmartHandles.YieldLockHolder hnd = new SmartHandles.YieldLockHolder( MemoryManager.Lock )) { ptr = Instance.Allocate( size ); if(ptr == UIntPtr.Zero) { GarbageCollectionManager.Instance.Collect( ); ptr = Instance.Allocate( size ); if(ptr == UIntPtr.Zero) { GarbageCollectionManager.Instance.ThrowOutOfMemory( null ); } } } // MemoryManager.Allocate returns pointer with object header initialized as AllocatedRawBytes, // which is already what we want. So just shift the pointer by the size of object header // (since the callers are interop code that have no concept of object header) and we're done! return AddressMath.Increment( ptr, ObjectHeader.HeaderSize ); } [ExportedMethod] public static void FreeFromManagedHeap( UIntPtr address ) { if(address != UIntPtr.Zero) { // Since AllocateFromManagedHeap returns pointer that were offset by object header size, // we need to reverse it before handing it to Release() Instance.Release( AddressMath.Decrement( address, ObjectHeader.HeaderSize ) ); } } //--// protected void AddLinearSection( UIntPtr beginning , UIntPtr end , MemoryAttributes attributes ) { uint size = AddressMath.RangeSize( beginning, end ); if(size >= MemorySegment.MinimumSpaceRequired()) { MemorySegment* seg = (MemorySegment*)beginning.ToPointer(); seg->Next = null; seg->Previous = m_heapTail; seg->Beginning = beginning; seg->End = end; seg->Attributes = attributes; if(m_heapHead == null) { m_heapHead = seg; } if(m_heapTail != null) { m_heapTail->Next = seg; } m_heapTail = seg; seg->Initialize(); } } // // Access Methods // public static extern MemoryManager Instance { [SingletonFactory(Fallback=typeof(EmptyManager))] [MethodImpl( MethodImplOptions.InternalCall )] get; } public static extern Synchronization.YieldLock Lock { [SingletonFactory()] [MethodImpl( MethodImplOptions.InternalCall )] get; } public MemorySegment* StartOfHeap { get { return m_heapHead; } } public uint AvailableMemory { get { uint total = 0; for(MemorySegment* heap = m_heapHead; heap != null; heap = heap->Next) { total += heap->AvailableMemory; } return total; } } public uint AllocatedMemory { get { uint total = 0; for(MemorySegment* heap = m_heapHead; heap != null; heap = heap->Next) { total += heap->AllocatedMemory; } return total; } } } } ================================================ FILE: Zelig/Zelig/RunTime/Zelig/Kernel/SystemServices/SchedulerTime.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // namespace Microsoft.Zelig.Runtime { using System; using System.Runtime.CompilerServices; using TS = Microsoft.Zelig.Runtime.TypeSystem; public struct SchedulerTime : IEquatable< SchedulerTime > { // // State // public static readonly SchedulerTime MinValue = new SchedulerTime( ulong.MinValue ); public static readonly SchedulerTime MaxValue = new SchedulerTime( ulong.MaxValue ); private ulong m_units; // // Constructor Methods // private SchedulerTime( ulong units ) { m_units = units; } // // Equality Methods // public override bool Equals( Object obj ) { if(obj is SchedulerTime) { SchedulerTime other = (SchedulerTime)obj; return this.Equals( other ); } return false; } public override int GetHashCode() { return m_units.GetHashCode(); } public bool Equals( SchedulerTime other ) { return m_units == other.m_units; } public static bool Equals( SchedulerTime t1 , SchedulerTime t2 ) { return t1.Equals( t2 ); } // // Helper Methods // public static int Compare( SchedulerTime t1 , SchedulerTime t2 ) { return t1.m_units.CompareTo( t1.m_units ); } public SchedulerTime Add( SchedulerTimeSpan value ) { if(value == SchedulerTimeSpan.MaxValue) { return MaxValue; } else if(value == SchedulerTimeSpan.MinValue) { return MinValue; } return new SchedulerTime( m_units + (ulong)value.DeltaUnits ); } public SchedulerTime Add( TimeSpan value ) { return Add( (SchedulerTimeSpan)value ); } public SchedulerTime Subtract( SchedulerTimeSpan value ) { if(value == SchedulerTimeSpan.MaxValue) { return MinValue; } else if(value == SchedulerTimeSpan.MinValue) { return MaxValue; } return new SchedulerTime( m_units - (ulong)value.DeltaUnits ); } public SchedulerTime Subtract( TimeSpan value ) { return Subtract( (SchedulerTimeSpan)value ); } //--// public static explicit operator SchedulerTime ( int milliseconds ) { return new SchedulerTime( ConvertFromMillisecondsToUnits( milliseconds ) ); } public static explicit operator SchedulerTime ( TimeSpan ts ) { return new SchedulerTime( ConvertFromTimeSpanTicksToUnits( ts.Ticks ) ); } public static explicit operator SchedulerTime ( DateTime dt ) { return new SchedulerTime( ConvertFromDateTimeTicksToUnits( dt.Ticks ) ); } public static explicit operator DateTime ( SchedulerTime t ) { return new DateTime( ConvertFromUnitsToDateTimeTicks( t.m_units ) ); } public static SchedulerTime operator +( SchedulerTime t , SchedulerTimeSpan ts ) { return t.Add( ts ); } public static SchedulerTime operator +( SchedulerTime t , TimeSpan ts ) { return t.Add( ts ); } public static SchedulerTime operator -( SchedulerTime t , SchedulerTimeSpan ts ) { return t.Subtract( ts ); } public static SchedulerTime operator -( SchedulerTime t , TimeSpan ts ) { return t.Subtract( ts ); } public static SchedulerTimeSpan operator -( SchedulerTime t1 , SchedulerTime t2 ) { return new SchedulerTimeSpan( (long)t1.m_units - (long)t2.m_units ); } [Inline] public static bool operator ==( SchedulerTime t1 , SchedulerTime t2 ) { return t1.m_units == t2.m_units; } [Inline] public static bool operator !=( SchedulerTime t1 , SchedulerTime t2 ) { return t1.m_units != t2.m_units; } [Inline] public static bool operator <( SchedulerTime t1 , SchedulerTime t2 ) { return t1.m_units < t2.m_units; } [Inline] public static bool operator <=( SchedulerTime t1 , SchedulerTime t2 ) { return t1.m_units <= t2.m_units; } [Inline] public static bool operator >( SchedulerTime t1 , SchedulerTime t2 ) { return t1.m_units > t2.m_units; } [Inline] public static bool operator >=( SchedulerTime t1 , SchedulerTime t2 ) { return t1.m_units >= t2.m_units; } //--// public static SchedulerTime FromUnits( ulong units ) { return new SchedulerTime( units ); } //--// // // These have to be implemented by the overriding class extension. // [MethodImpl( MethodImplOptions.InternalCall )] private static extern ulong ConvertFromMillisecondsToUnits( int milliSeconds ); [MethodImpl( MethodImplOptions.InternalCall )] private static extern ulong ConvertFromTimeSpanTicksToUnits( long ticks ); [MethodImpl( MethodImplOptions.InternalCall )] private static extern ulong ConvertFromDateTimeTicksToUnits( long ticks ); [MethodImpl( MethodImplOptions.InternalCall )] private static extern long ConvertFromUnitsToDateTimeTicks( ulong units ); [MethodImpl( MethodImplOptions.InternalCall )] private extern static ulong GetCurrentTime(); //--// // // Access Methods // public static SchedulerTime Now { get { return new SchedulerTime( GetCurrentTime() ); } } public ulong Units { get { return m_units; } } } } ================================================ FILE: Zelig/Zelig/RunTime/Zelig/Kernel/SystemServices/SchedulerTimeSpan.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // namespace Microsoft.Zelig.Runtime { using System; using System.Runtime.CompilerServices; using TS = Microsoft.Zelig.Runtime.TypeSystem; public struct SchedulerTimeSpan : IEquatable< SchedulerTimeSpan > { // // State // public static readonly SchedulerTimeSpan MinValue = new SchedulerTimeSpan( long.MinValue ); public static readonly SchedulerTimeSpan MaxValue = new SchedulerTimeSpan( long.MaxValue ); private long m_deltaUnits; // // Constructor Methods // internal SchedulerTimeSpan( long deltaUnits ) { m_deltaUnits = deltaUnits; } // // Equality Methods // public override bool Equals( Object obj ) { if(obj is SchedulerTimeSpan) { SchedulerTimeSpan other = (SchedulerTimeSpan)obj; return this.Equals( other ); } return false; } public override int GetHashCode() { return m_deltaUnits.GetHashCode(); } public bool Equals( SchedulerTimeSpan other ) { return m_deltaUnits == other.m_deltaUnits; } public static bool Equals( SchedulerTimeSpan ts1 , SchedulerTimeSpan ts2 ) { return ts1.Equals( ts2 ); } // // Helper Methods // public static int Compare( SchedulerTimeSpan ts1 , SchedulerTimeSpan ts2 ) { return ts1.m_deltaUnits.CompareTo( ts1.m_deltaUnits ); } public SchedulerTimeSpan Add( SchedulerTimeSpan value ) { if(value == SchedulerTimeSpan.MaxValue) { return MaxValue; } else if(value == SchedulerTimeSpan.MinValue) { return MinValue; } return new SchedulerTimeSpan( m_deltaUnits + value.m_deltaUnits ); } public SchedulerTimeSpan Add( TimeSpan value ) { return Add( (SchedulerTimeSpan)value ); } public SchedulerTimeSpan Subtract( SchedulerTimeSpan value ) { if(value == SchedulerTimeSpan.MaxValue) { return MinValue; } else if(value == SchedulerTimeSpan.MinValue) { return MaxValue; } return new SchedulerTimeSpan( m_deltaUnits - value.m_deltaUnits ); } public SchedulerTimeSpan Subtract( TimeSpan value ) { return Subtract( (SchedulerTimeSpan)value ); } //--// public static SchedulerTimeSpan FromMilliseconds( long milliSeconds ) { return new SchedulerTimeSpan( ConvertFromMillisecondsToDeltaUnits( milliSeconds ) ); } public static explicit operator SchedulerTimeSpan ( TimeSpan ts ) { return new SchedulerTimeSpan( ConvertFromTimeSpanTicksToDeltaUnits( ts.Ticks ) ); } public static explicit operator TimeSpan ( SchedulerTimeSpan ts ) { return new TimeSpan( ConvertFromDeltaUnitsToTimeSpanTicks( ts.m_deltaUnits ) ); } public static long ToMilliseconds( SchedulerTimeSpan ts ) { return ConvertFromDeltaUnitsToMilliseconds( ts.m_deltaUnits ); } //--// public static SchedulerTimeSpan operator +( SchedulerTimeSpan ts1 , TimeSpan ts2 ) { return ts1.Add( ts2 ); } public static SchedulerTimeSpan operator -( SchedulerTimeSpan ts1 , TimeSpan ts2 ) { return ts1.Subtract( ts2 ); } public static SchedulerTimeSpan operator -( SchedulerTimeSpan ts1 , SchedulerTimeSpan ts2 ) { return ts1.Subtract( ts2 ); } [Inline] public static bool operator ==( SchedulerTimeSpan ts1 , SchedulerTimeSpan ts2 ) { return ts1.m_deltaUnits == ts2.m_deltaUnits; } [Inline] public static bool operator !=( SchedulerTimeSpan ts1 , SchedulerTimeSpan ts2 ) { return ts1.m_deltaUnits != ts2.m_deltaUnits; } [Inline] public static bool operator <( SchedulerTimeSpan ts1 , SchedulerTimeSpan ts2 ) { return ts1.m_deltaUnits < ts2.m_deltaUnits; } [Inline] public static bool operator <=( SchedulerTimeSpan ts1 , SchedulerTimeSpan ts2 ) { return ts1.m_deltaUnits <= ts2.m_deltaUnits; } [Inline] public static bool operator >( SchedulerTimeSpan ts1 , SchedulerTimeSpan ts2 ) { return ts1.m_deltaUnits > ts2.m_deltaUnits; } [Inline] public static bool operator >=( SchedulerTimeSpan ts1 , SchedulerTimeSpan ts2 ) { return ts1.m_deltaUnits >= ts2.m_deltaUnits; } //--// // // These have to be implemented by the overriding class extension. // [MethodImpl( MethodImplOptions.InternalCall )] private static extern long ConvertFromMillisecondsToDeltaUnits( long milliSeconds ); [MethodImpl( MethodImplOptions.InternalCall )] private static extern long ConvertFromTimeSpanTicksToDeltaUnits( long ticks ); [MethodImpl( MethodImplOptions.InternalCall )] private static extern long ConvertFromDeltaUnitsToTimeSpanTicks( long deltaUnits ); [MethodImpl( MethodImplOptions.InternalCall )] private static extern long ConvertFromDeltaUnitsToMilliseconds( long deltaUnits ); //--// // // Access Methods // public long DeltaUnits { get { return m_deltaUnits; } } } } ================================================ FILE: Zelig/Zelig/RunTime/Zelig/Kernel/SystemServices/SerialPortsManager.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // namespace Microsoft.Zelig.Runtime { using System; using System.Runtime.CompilerServices; [ImplicitInstance] [ForceDevirtualization] public abstract class SerialPortsManager { class EmptyManager : SerialPortsManager { // // Helper Methods // public override void Initialize() { } public override string[] GetPortNames() { return null; } public override System.IO.Ports.SerialStream Open( ref BaseSerialStream.Configuration cfg ) { return null; } } // // Helper Methods // public abstract void Initialize(); public abstract string[] GetPortNames(); public abstract System.IO.Ports.SerialStream Open( ref BaseSerialStream.Configuration cfg ); // // Access Methods // public static extern SerialPortsManager Instance { [SingletonFactory(Fallback=typeof(EmptyManager))] [MethodImpl( MethodImplOptions.InternalCall )] get; } } } ================================================ FILE: Zelig/Zelig/RunTime/Zelig/Kernel/SystemServices/Threading/ARMv5ThreadManager.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // namespace Microsoft.Zelig.Runtime { using System; using System.Runtime.CompilerServices; using TS = Microsoft.Zelig.Runtime.TypeSystem; [SingletonFactoryPlatformFilter("ARM")] public abstract class ARMv5ThreadManager : ThreadManager { // // State // protected ThreadImpl m_interruptThread; protected ThreadImpl m_fastInterruptThread; protected ThreadImpl m_abortThread; protected ThreadImpl m_undefThread; //--// public override void InitializeAfterStaticConstructors( uint[] systemStack ) { base.InitializeAfterStaticConstructors( systemStack ); m_interruptThread = new ThreadImpl( null, new uint[512] ); m_fastInterruptThread = new ThreadImpl( null, new uint[512] ); m_abortThread = new ThreadImpl( null, new uint[128] ); m_undefThread = new ThreadImpl( null, new uint[128] ); // // These threads are never started, so we have to manually register them, to enable the debugger to see them. // RegisterThread( m_interruptThread ); RegisterThread( m_fastInterruptThread ); RegisterThread( m_abortThread ); RegisterThread( m_undefThread ); //--// m_interruptThread .SetupForExceptionHandling( TargetPlatform.ARMv4.ProcessorARMv4.c_psr_mode_IRQ ); m_fastInterruptThread.SetupForExceptionHandling( TargetPlatform.ARMv4.ProcessorARMv4.c_psr_mode_FIQ ); m_abortThread .SetupForExceptionHandling( TargetPlatform.ARMv4.ProcessorARMv4.c_psr_mode_ABORT ); m_undefThread .SetupForExceptionHandling( TargetPlatform.ARMv4.ProcessorARMv4.c_psr_mode_UNDEF ); } public override ThreadImpl InterruptThread { get { return m_interruptThread; } } public override ThreadImpl FastInterruptThread { get { return m_fastInterruptThread; } } public override ThreadImpl AbortThread { get { return m_abortThread; } } protected override void IdleThread( ) { //BugCheck.Log( "!!!!!!!!!!!!!!!!!!!!!!!!!!!" ); //BugCheck.Log( "!!! Idle thread running !!!" ); //BugCheck.Log( "!!!!!!!!!!!!!!!!!!!!!!!!!!!" ); SmartHandles.InterruptState.EnableAll( ); while(true) { //BugCheck.Log( "!!!!!!!!!!!!!!!!!!!!!!!!!!!" ); //BugCheck.Log( "!!! sleeping !!!" ); //BugCheck.Log( "!!!!!!!!!!!!!!!!!!!!!!!!!!!" ); Peripherals.Instance.WaitForInterrupt(); } } } } ================================================ FILE: Zelig/Zelig/RunTime/Zelig/Kernel/SystemServices/Threading/ARMv6ThreadManager.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // namespace Microsoft.Zelig.Runtime { using ARMv6 = Microsoft.Zelig.Runtime.TargetPlatform.ARMv6; public abstract class ARMv6ThreadManager : ThreadManager { public const uint c_TimeQuantumMsec = 20; //--// // // Helper methods // public override unsafe void StartThreads( ) { // // The standard thread manager will set the current thread to be the // idle thread before letting the scheduler pick up the next target. // that means that the Context Switch code will find a current thread and // will try to update the stack pointer of its context to the psp value on // the processor. We need to initialize the PSP value to whatever // we want the context switch to persist in the current (i.e. idle) thread // context. As for the general case, the Idle Thread context stack pointer // is initialized to be the end of the first frame, which though really never // ran. So we will initialized the actual psp register to the base of the // Idle Thread stack pointer at this stage. // // // We willl context switch through SVC call that will fall back into Thread/PSP mode onto // whatever thread the standard thread manager intended to switch into. We will keep interrupts // disabled until we are ready to fire the first SVC request. // //TargetPlatform.ARMv6.SmartHandles.InterruptStateARMv6M.SetSoftwareExceptionMode( ); // // Let the standard thread manager set up the next thread to run and request the switch to its context // It will be a switch to the idle thread (bootstrap thread) // base.StartThreads( ); // // Never come back from this! // //BugCheck.Log( "!!!!!!!!!!!!!!!!!!! ERROR !!!!!!!!!!!!!!!!!!!!!"); //BugCheck.Log( "!!! Back in Thread Manager, Ctx Switch Failed !!!"); //BugCheck.Log( "!!!!!!!!!!!!!!!!!!! ERROR !!!!!!!!!!!!!!!!!!!!!"); BugCheck.Assert( false, BugCheck.StopCode.CtxSwitchFailed ); } public override void RemoveThread( ThreadImpl thread ) { // // This should schedule a context switch // base.RemoveThread( thread ); // // If context switch was not already performed, we need to jump else where // ARMv6.ProcessorARMv6M.RaiseSupervisorCall( ARMv6.ProcessorARMv6M.SVC_Code.SupervisorCall__RetireThread ); // // We should never get here // BugCheck.Assert( false, BugCheck.StopCode.CtxSwitchFailed ); } protected override void IdleThread( ) { ARMv6.ProcessorARMv6M.InitiateContextSwitch( ); SmartHandles.InterruptState.EnableAll( ); while(true) { Peripherals.Instance.WaitForInterrupt(); } } } } ================================================ FILE: Zelig/Zelig/RunTime/Zelig/Kernel/SystemServices/Threading/ARMv7ThreadManager.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // namespace Microsoft.Zelig.Runtime { using ARMv7 = Microsoft.Zelig.Runtime.TargetPlatform.ARMv7; public abstract class ARMv7ThreadManager : ThreadManager { public const uint c_TimeQuantumMsec = 20; //--// // // Helper methods // public override unsafe void StartThreads( ) { // // The standard thread manager will set the current thread to be the // idle thread before letting the scheduler pick up the next target. // that means that the Context Switch code will find a current thread and // will try to update the stack pointer of its context to the psp value on // the processor. We need to initialize the PSP value to whatever // we want the context switch to persist in the current (i.e. idle) thread // context. As for the general case, the Idle Thread context stack pointer // is initialized to be the end of the first frame, which though really never // ran. So we will initialized the actual psp register to the base of the // Idle Thread stack pointer at this stage. // // // Enable context switch through SVC call that will fall back into Thread/PSP mode onto // whatever thread the standard thread manager intended to switch into // ARMv7.ProcessorARMv7M.DisableInterruptsWithPriorityLevelLowerOrEqualTo( ARMv7.ProcessorARMv7M.c_Priority__SVCCall + 1 ); // // Let the standard thread manager set up the next thread to run and request the switch to its context // It will be a switch to the idle thread (bootstrap thread) // base.StartThreads( ); // // Never come back from this! // //BugCheck.Log( "!!!!!!!!!!!!!!!!!!! ERROR !!!!!!!!!!!!!!!!!!!!!"); //BugCheck.Log( "!!! Back in Thread Manager, Ctx Switch Failed !!!"); //BugCheck.Log( "!!!!!!!!!!!!!!!!!!! ERROR !!!!!!!!!!!!!!!!!!!!!"); BugCheck.Assert( false, BugCheck.StopCode.CtxSwitchFailed ); } public override void RemoveThread( ThreadImpl thread ) { // // This should schedule a context switch // base.RemoveThread( thread ); // // If context switch was not already performed, we need to jump else where // ARMv7.ProcessorARMv7M.RaiseSupervisorCall( ARMv7.ProcessorARMv7M.SVC_Code.SupervisorCall__RetireThread ); // // We should never get here // BugCheck.Assert( false, BugCheck.StopCode.CtxSwitchFailed ); } // // Access methods // protected override void IdleThread( ) { //BugCheck.Log( "!!!!!!!!!!!!!!!!!!!!!!!!!!!" ); //BugCheck.Log( "!!! Idle thread running !!!" ); //BugCheck.Log( "!!!!!!!!!!!!!!!!!!!!!!!!!!!" ); ARMv7.ProcessorARMv7M.InitiateContextSwitch( ); SmartHandles.InterruptState.EnableAll( ); while(true) { //BugCheck.Log( "!!!!!!!!!!!!!!!!!!!!!!!!!!!" ); //BugCheck.Log( "!!! sleeping !!!" ); //BugCheck.Log( "!!!!!!!!!!!!!!!!!!!!!!!!!!!" ); Peripherals.Instance.WaitForInterrupt(); } } } } ================================================ FILE: Zelig/Zelig/RunTime/Zelig/Kernel/SystemServices/Threading/ThreadManager.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // #define ARMv7 namespace Microsoft.Zelig.Runtime { using System; using System.Runtime.CompilerServices; using TS = Microsoft.Zelig.Runtime.TypeSystem; [ImplicitInstance] [ForceDevirtualization] [TS.WellKnownType( "Microsoft_Zelig_Runtime_ThreadManager" )] public abstract class ThreadManager { class EmptyManager : ThreadManager { // // State // // // Helper Methods // public override void InitializeBeforeStaticConstructors() { } public override void InitializeAfterStaticConstructors( uint[] systemStack ) { } public override void Activate() { } public override void Reschedule() { } public override void SetNextWaitTimer( SchedulerTime nextTimeout ) { } public override void CancelQuantumTimer() { } public override void SetNextQuantumTimer() { } public override void SetNextQuantumTimer( SchedulerTime nextTimeout ) { } public override ThreadImpl InterruptThread { get { return null; } } public override ThreadImpl FastInterruptThread { get { return null; } } public override ThreadImpl AbortThread { get { return null; } } protected override void IdleThread( ) { } } // // State // protected KernelList< ThreadImpl > m_allThreads; protected KernelList< ThreadImpl > m_readyThreads; protected KernelList< ThreadImpl > m_waitingThreads; protected ThreadImpl m_mainThread; protected ThreadImpl m_idleThread; protected EventWaitHandleImpl m_neverSignaledEvent; protected bool m_noInvalidateNextWaitTimerRecursion; //--// protected ThreadImpl m_runningThread; protected ThreadImpl m_nextThread; protected KernelPerformanceCounter m_deadThreadsTime; // // Helper Methods // public virtual int DefaultStackSize { get { return 2048; } } [TS.DisableAutomaticReferenceCounting] public static void InitializeForReferenceCounting() { // Set up a dummy bootstrap thread with a fake release reference helper as part of the // heap initialization when the reference counting garbage collection is turned on. // This is so that if ReleaseReference needs to call CurrentThread.ReleaseReferenceHelper // before the main thread is established, it can behave predictably. ThreadImpl.CurrentThread = new ThreadImpl( ThreadImpl.BootstrapThread.BootstrapThread ); } [TS.DisableAutomaticReferenceCounting] [TS.WellKnownMethod( "ThreadManager_CleanupBootstrapThread" )] private static void CleanupBootstrapThread( ) { var dummyThread = ThreadImpl.CurrentThread; var releaseRefHelper = dummyThread.ReleaseReference; ThreadImpl.CurrentThread = null; MemoryManager.Instance.Release( ObjectHeader.Unpack( dummyThread ).ToPointer( ) ); MemoryManager.Instance.Release( ObjectHeader.Unpack( releaseRefHelper ).ToPointer( ) ); } [NoInline] [TS.WellKnownMethod( "ThreadManager_CleanupBootstrapThreadIfNeeded" )] private static void CleanupBootstrapThreadIfNeeded() { // Injection site for reference counting GC to call CleanupBootstrapThread() } public virtual void InitializeBeforeStaticConstructors() { // // Create the first active thread. // m_mainThread = new ThreadImpl( MainThread ); CleanupBootstrapThreadIfNeeded( ); // // We need to have a current thread during initialization, in case some static constructors try to access it. // ThreadImpl.CurrentThread = m_mainThread; } public virtual void InitializeAfterStaticConstructors( uint[] systemStack ) { m_allThreads = new KernelList< ThreadImpl >(); m_readyThreads = new KernelList< ThreadImpl >(); m_waitingThreads = new KernelList< ThreadImpl >(); m_idleThread = new ThreadImpl( IdleThread, systemStack ); m_neverSignaledEvent = new EventWaitHandleImpl( false, System.Threading.EventResetMode.ManualReset ); // // These threads are never started, so we have to manually register them, to enable the debugger to see them. // RegisterThread( m_idleThread ); } public virtual void Activate() { } [NoReturn] public virtual void StartThreads() { // // 'm_runningThread' should never be null once the interrupts have been enabled, so we have to set it here. // ThreadImpl bootstrapThread = m_idleThread; m_runningThread = bootstrapThread; #if USE_THREAD_PERFORMANCE_COUNTER bootstrapThread.AcquiredProcessor(); #endif // USE_THREAD_PERFORMANCE_COUNTER // // Start the first active thread. // m_mainThread.Start(); // // Long jump to the idle thread context, which will re-enable interrupts and // cause the first context switch to the process stack of this thread // bootstrapThread.SwappedOutContext.SwitchTo(); } //--// // // Helper Methods // protected void RegisterThread( ThreadImpl thread ) { BugCheck.AssertInterruptsOff(); m_allThreads.InsertAtTail( thread.RegistrationLink ); } public virtual void AddThread( ThreadImpl thread ) { BugCheck.Assert( thread.SchedulingLink.VerifyUnlinked(), BugCheck.StopCode.KernelNodeStillLinked ); using(SmartHandles.InterruptState hnd = SmartHandles.InterruptState.Disable()) { RegisterThread( thread ); InsertInPriorityOrder( thread ); RescheduleAndRequestContextSwitchIfNeeded( hnd.GetCurrentExceptionMode() ); } } public virtual void RemoveThread( ThreadImpl thread ) { using(SmartHandles.InterruptState hnd = SmartHandles.InterruptState.Disable()) { thread.Detach(); if(thread == m_runningThread) { RescheduleAndRequestContextSwitchIfNeeded( hnd.GetCurrentExceptionMode() ); } else { // // If the thread is not the running one, it won't get a chance to execute the Stop method. // thread.Stop(); } } } public virtual void RetireThread( ThreadImpl thread ) { m_deadThreadsTime.Merge( thread.ActiveTime ); } //--// public virtual void Yield() { BugCheck.AssertInterruptsOn(); ThreadImpl thisThread = ThreadImpl.CurrentThread; BugCheck.Assert( thisThread != null, BugCheck.StopCode.NoCurrentThread ); using (SmartHandles.InterruptState hnd = SmartHandles.InterruptState.Disable()) { InsertInPriorityOrder(thisThread); RescheduleAndRequestContextSwitchIfNeeded(HardwareException.None); } } public virtual void SwitchToWait( Synchronization.WaitingRecord wr ) { BugCheck.AssertInterruptsOn(); using(SmartHandles.InterruptState hnd = SmartHandles.InterruptState.Disable()) { if(wr.Processed == false) { ThreadImpl thread = wr.Source; m_waitingThreads.InsertAtTail( thread.SchedulingLink ); thread.State |= System.Threading.ThreadState.WaitSleepJoin; InvalidateNextWaitTimer(); RescheduleAndRequestContextSwitchIfNeeded( hnd.GetCurrentExceptionMode() ); while(thread.IsWaiting) { hnd.Toggle(); } } } } public virtual void Wakeup( ThreadImpl thread ) { using(SmartHandles.InterruptState hnd = SmartHandles.InterruptState.Disable()) { if(thread.IsWaiting) { thread.State &= ~System.Threading.ThreadState.WaitSleepJoin; InsertInPriorityOrder( thread ); RescheduleAndRequestContextSwitchIfNeeded( hnd.GetCurrentExceptionMode() ); } } } public virtual void TimeQuantumExpired( ) { //#if !ARMv7 BugCheck.AssertInterruptsOff( ); //b#endif InsertInPriorityOrder( m_runningThread ); Reschedule( ); } public virtual void SetNextQuantumTimerIfNeeded() { ThreadImpl nextThread = m_nextThread; if(nextThread == m_idleThread) { CancelQuantumTimer(); // No need to set a timer, we are just idling. } else { ThreadImpl lastThread = m_readyThreads.LastTarget(); // // If the next thread is not an idle thread, there has to be a ready thread. // BugCheck.Assert( lastThread != null, BugCheck.StopCode.ExpectingReadyThread ); if(lastThread == nextThread) { CancelQuantumTimer(); // Only one ready thread, no need to preempt it. } else { SetNextQuantumTimer(); } } } public void RescheduleAndRequestContextSwitchIfNeeded( HardwareException mode ) { //BugCheck.Log( "Mode: %d", (int)mode ); Reschedule(); //////#if ARMv7 ////// // ////// // Timer will fire to ths point, and for the time being they are actual interrupts, although they should ////// // just be user mode handlers from the controller thread ////// // We therefore need to pick the case if System timer exception and let it go as if it was a normal thread mode ////// // handler. When we enable the interrupts controller this case will be automatically take care of and we ////// // can remove this #if ////// // ////// if(mode == HardwareException.None || mode == HardwareException.Interrupt ) //////#else if(mode == HardwareException.None || mode == HardwareException.SysTick || mode == HardwareException.Interrupt) //////#endif { if(this.ShouldContextSwitch) { Peripherals.Instance.CauseInterrupt( ); } } } public virtual void Reschedule() { SelectNextThreadToRun(); } public void SelectNextThreadToRun() { using(SmartHandles.InterruptState.Disable()) { ThreadImpl thread = m_readyThreads.FirstTarget(); m_nextThread = thread != null ? thread : m_idleThread; SetNextQuantumTimerIfNeeded(); } } // // Extensibility // public abstract void SetNextWaitTimer( SchedulerTime nextTimeout ); public abstract void CancelQuantumTimer(); public abstract void SetNextQuantumTimer(); public abstract void SetNextQuantumTimer( SchedulerTime nextTimeout ); public abstract ThreadImpl InterruptThread { get; } public abstract ThreadImpl FastInterruptThread { get; } public abstract ThreadImpl AbortThread { get; } //--// public void InvalidateNextWaitTimer() { if(m_noInvalidateNextWaitTimerRecursion == false) { ComputeNextTimeout(); } } protected void WaitExpired( SchedulerTime currentTime ) { m_noInvalidateNextWaitTimerRecursion = true; KernelNode< ThreadImpl > node = m_waitingThreads.StartOfForwardWalk; while(node.IsValidForForwardMove) { KernelNode< ThreadImpl > nodeNext = node.Next; node.Target.ProcessWaitExpiration( currentTime ); node = nodeNext; } m_noInvalidateNextWaitTimerRecursion = false; ComputeNextTimeout(); } private void ComputeNextTimeout() { SchedulerTime nextTimeout = SchedulerTime.MaxValue; KernelNode< ThreadImpl > node = m_waitingThreads.StartOfForwardWalk; while(node.IsValidForForwardMove) { SchedulerTime threadTimeout = node.Target.GetFirstTimeout(); if(nextTimeout > threadTimeout) { nextTimeout = threadTimeout; } node = node.Next; } SetNextWaitTimer( nextTimeout ); } //--// public void Sleep( SchedulerTime schedulerTime ) { m_neverSignaledEvent.WaitOne( schedulerTime, false ); } //--// [Inline] public static SmartHandles.SwapCurrentThreadUnderInterrupt InstallInterruptThread() { return ThreadImpl.SwapCurrentThreadUnderInterrupt( ThreadManager.Instance.InterruptThread ); } [Inline] public static SmartHandles.SwapCurrentThreadUnderInterrupt InstallFastInterruptThread() { return ThreadImpl.SwapCurrentThreadUnderInterrupt( ThreadManager.Instance.FastInterruptThread ); } [Inline] public static SmartHandles.SwapCurrentThreadUnderInterrupt InstallAbortThread() { return ThreadImpl.SwapCurrentThreadUnderInterrupt( ThreadManager.Instance.AbortThread ); } //--// protected void InsertInPriorityOrder( ThreadImpl thread ) { // // Idle thread must never enter the set of the ready threads // if(thread == m_idleThread) { return; } // // Insert in order. // var node = m_readyThreads.StartOfForwardWalk; var pri = thread.Priority; while(node.IsValidForForwardMove) { if(node.Target.Priority < pri) { break; } node = node.Next; } thread.SchedulingLink.InsertBefore( node ); thread.State &= ~System.Threading.ThreadState.WaitSleepJoin; } protected abstract void IdleThread( ); private void MainThread() { while(true) { try { //BugCheck.Log( "[MainThreads] !!! EXECUTING APP !!!" ); //BugCheck.Log( "[MainThreads] !!! EXECUTING APP !!!" ); //BugCheck.Log( "[MainThreads] !!! EXECUTING APP !!!" ); Configuration.ExecuteApplication(); } catch { } BugCheck.Raise( BugCheck.StopCode.NoCurrentThread ); } } // // Access Methods // public static extern ThreadManager Instance { [SingletonFactory(Fallback=typeof(EmptyManager))] [MethodImpl( MethodImplOptions.InternalCall )] get; } public virtual ThreadImpl CurrentThread { get { return m_runningThread; } set { #if !ARMv7 // // For ARMv7 we are using the async PendSV exception, which is delivered with ISRs enabled // BugCheck.AssertInterruptsOff(); #endif ThreadImpl oldValue = m_runningThread; if(oldValue != value) { #if USE_THREAD_PERFORMANCE_COUNTER oldValue.ReleasedProcessor(); #endif // USE_THREAD_PERFORMANCE_COUNTER m_runningThread = value; #if USE_THREAD_PERFORMANCE_COUNTER value.AcquiredProcessor(); #endif // USE_THREAD_PERFORMANCE_COUNTER SetNextQuantumTimerIfNeeded(); } } } public ThreadImpl NextThread { get { return m_nextThread; } } public virtual bool ShouldContextSwitch { [Inline] get { return m_runningThread != m_nextThread; } } public KernelNode< ThreadImpl > StartOfForwardWalkThroughAllThreads { get { return m_allThreads.StartOfForwardWalk; } } } } ================================================ FILE: Zelig/Zelig/RunTime/Zelig/Kernel/SystemServices/TypeSystemManager.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // namespace Microsoft.Zelig.Runtime { using System; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using TS = Microsoft.Zelig.Runtime.TypeSystem; [ImplicitInstance] [ForceDevirtualization] public abstract class TypeSystemManager { class EmptyManager : TypeSystemManager { [NoInline] public override Object AllocateObject(TS.VTable vTable) { return null; } [NoInline] public override Object AllocateReferenceCountingObject(TS.VTable vTable) { return null; } [NoInline] public override Object AllocateObjectWithExtensions(TS.VTable vTable) { return null; } [NoInline] public override Array AllocateArray(TS.VTable vTable, uint length) { return null; } [NoInline] public override Array AllocateReferenceCountingArray(TS.VTable vTable, uint length) { return null; } [NoInline] public override Array AllocateArrayNoClear(TS.VTable vTable, uint length) { return null; } [NoInline] public override String AllocateString(TS.VTable vTable, int length) { return null; } [NoInline] public override String AllocateReferenceCountingString(TS.VTable vTable, int length) { return null; } } // // Helper Methods // public virtual void InitializeTypeSystemManager() { InvokeStaticConstructors(); } [Inline] [TS.DisableAutomaticReferenceCounting] public object InitializeObject( UIntPtr memory, TS.VTable vTable, bool referenceCounting) { ObjectHeader oh = ObjectHeader.CastAsObjectHeader(memory); oh.VirtualTable = vTable; if (referenceCounting) { oh.MultiUseWord = (int)((1 << ObjectHeader.ReferenceCountShift) | (int)ObjectHeader.GarbageCollectorFlags.NormalObject | (int)ObjectHeader.GarbageCollectorFlags.Unmarked); #if REFCOUNT_STAT ObjectHeader.s_RefCountedObjectsAllocated++; #endif #if DEBUG_REFCOUNT BugCheck.Log( "InitRC (0x%x), new count = 1 +", (int)oh.ToPointer( ) ); #endif } else { oh.MultiUseWord = (int)(ObjectHeader.GarbageCollectorFlags.NormalObject | ObjectHeader.GarbageCollectorFlags.Unmarked); } return oh.Pack(); } [Inline] [TS.DisableAutomaticReferenceCounting] public object InitializeObjectWithExtensions(UIntPtr memory, TS.VTable vTable) { ObjectHeader oh = ObjectHeader.CastAsObjectHeader(memory); oh.VirtualTable = vTable; oh.MultiUseWord = (int)(ObjectHeader.GarbageCollectorFlags.SpecialHandlerObject | ObjectHeader.GarbageCollectorFlags.Unmarked); return oh.Pack(); } [Inline] [TS.DisableAutomaticReferenceCounting] public Array InitializeArray( UIntPtr memory, TS.VTable vTable, uint length, bool referenceCounting) { object obj = InitializeObject(memory, vTable, referenceCounting); ArrayImpl array = ArrayImpl.CastAsArray(obj); array.m_numElements = length; return array.CastThisAsArray(); } [Inline] [TS.DisableAutomaticReferenceCounting] public String InitializeString(UIntPtr memory, TS.VTable vTable, int length, bool referenceCounting) { object obj = InitializeObject(memory, vTable, referenceCounting); StringImpl str = StringImpl.CastAsString(obj); str.m_arrayLength = length; return str.CastThisAsString(); } [TS.WellKnownMethod("TypeSystemManager_AllocateObject")] [TS.DisableAutomaticReferenceCounting] public abstract Object AllocateObject(TS.VTable vTable); [TS.WellKnownMethod("TypeSystemManager_AllocateReferenceCountingObject")] [TS.DisableAutomaticReferenceCounting] public abstract Object AllocateReferenceCountingObject(TS.VTable vTable); [TS.WellKnownMethod("TypeSystemManager_AllocateObjectWithExtensions")] [TS.DisableAutomaticReferenceCounting] public abstract Object AllocateObjectWithExtensions(TS.VTable vTable); [TS.WellKnownMethod("TypeSystemManager_AllocateArray")] [TS.DisableAutomaticReferenceCounting] public abstract Array AllocateArray(TS.VTable vTable, uint length); [TS.WellKnownMethod("TypeSystemManager_AllocateReferenceCountingArray")] [TS.DisableAutomaticReferenceCounting] public abstract Array AllocateReferenceCountingArray(TS.VTable vTable, uint length); [TS.WellKnownMethod("TypeSystemManager_AllocateArrayNoClear")] [TS.DisableAutomaticReferenceCounting] public abstract Array AllocateArrayNoClear(TS.VTable vTable, uint length); [TS.WellKnownMethod("TypeSystemManager_AllocateString")] [TS.DisableAutomaticReferenceCounting] public abstract String AllocateString(TS.VTable vTable, int length); [TS.DisableAutomaticReferenceCounting] public abstract String AllocateReferenceCountingString(TS.VTable vTable, int length); //--// [Inline] public static T AtomicAllocator(ref T obj) where T : class, new() { if (obj == null) { return AtomicAllocatorSlow(ref obj); } return obj; } [NoInline] private static T AtomicAllocatorSlow(ref T obj) where T : class, new() { T newObj = new T(); System.Threading.Interlocked.CompareExchange(ref obj, newObj, default(T)); return obj; } //--// public static System.Reflection.MethodInfo CodePointerToMethodInfo(TS.CodePointer ptr) { throw new NotImplementedException(); } //--// [NoInline] [TS.WellKnownMethod("TypeSystemManager_InvokeStaticConstructors")] private void InvokeStaticConstructors() { // // WARNING! // WARNING! Keep this method empty!!!! // WARNING! // // We need a way to inject calls to the static constructors that are reachable. // This is the empty vessel for those calls. // // WARNING! // WARNING! Keep this method empty!!!! // WARNING! // } [TS.WellKnownMethod("TypeSystemManager_CastToType")] public static object CastToType(object obj, TS.VTable expected) { if (obj != null) { obj = CastToTypeNoThrow(obj, expected); if (obj == null) { throw new InvalidCastException(); } } return obj; } [TS.WellKnownMethod("TypeSystemManager_CastToTypeNoThrow")] public static object CastToTypeNoThrow(object obj, TS.VTable expected) { if (obj != null) { TS.VTable got = TS.VTable.Get(obj); if (expected.CanBeAssignedFrom(got) == false) { return null; } } return obj; } //--// [TS.WellKnownMethod("TypeSystemManager_CastToSealedType")] public static object CastToSealedType(object obj, TS.VTable expected) { if (obj != null) { obj = CastToSealedTypeNoThrow(obj, expected); if (obj == null) { throw new InvalidCastException(); } } return obj; } [TS.WellKnownMethod("TypeSystemManager_CastToSealedTypeNoThrow")] public static object CastToSealedTypeNoThrow(object obj, TS.VTable expected) { if (obj != null) { TS.VTable got = TS.VTable.Get(obj); if (got != expected) { return null; } } return obj; } //--// [TS.WellKnownMethod("TypeSystemManager_CastToInterface")] public static object CastToInterface(object obj, TS.VTable expected) { if (obj != null) { obj = CastToInterfaceNoThrow(obj, expected); if (obj == null) { throw new InvalidCastException(); } } return obj; } [TS.WellKnownMethod("TypeSystemManager_CastToInterfaceNoThrow")] public static object CastToInterfaceNoThrow(object obj, TS.VTable expected) { if (obj != null) { TS.VTable got = TS.VTable.Get(obj); if (got.ImplementsInterface(expected)) { return obj; } } return null; } //--// [NoReturn] [NoInline] [TS.WellKnownMethod("TypeSystemManager_Throw")] public virtual void Throw(Exception obj) { ThreadImpl.CurrentThread.CurrentException = obj; UIntPtr exception = Unwind.LLOS_AllocateException(obj, Unwind.ExceptionClass); Unwind.LLOS_Unwind_RaiseException(exception); } [NoReturn] [NoInline] [TS.WellKnownMethod("TypeSystemManager_Rethrow")] public virtual void Rethrow() { MemoryManager.Instance.DumpMemory( ); Throw(ThreadImpl.CurrentThread.CurrentException); } // // Access Methods // public static extern TypeSystemManager Instance { [TS.WellKnownMethod("TypeSystemManager_get_Instance")] [SingletonFactory(Fallback = typeof(EmptyManager))] [MethodImpl(MethodImplOptions.InternalCall)] get; } } } ================================================ FILE: Zelig/Zelig/RunTime/Zelig/Kernel/SystemServices/Unwind.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // // Note: This implementation was written to match the Itanium ABI. For further details, please // reference the Itanium ABI (http://mentorembedded.github.io/cxx-abi/abi-eh.html) and LLVM's // libc++abi (http://libcxxabi.llvm.org/). #define ARM_EABI namespace Microsoft.Zelig.Runtime { using System; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using Microsoft.Zelig.Runtime.TypeSystem; public static class Unwind { /// /// Status flags describing the unwind phase and options. Should match _Unwind_Action in ABI. /// [Flags] public enum UnwindActions { SearchPhase = 0x01, // Mutually exclusive with CleanupPhase CleanupPhase = 0x02, // Mutually exclusive with SearchPhase HandlerFrame = 0x04, ForceUnwind = 0x08, EndOfStack = 0x16, } /// /// Result of any given unwind operation; values should match _Unwind_Reason_Code. /// public enum UnwindReasonCode { NoReason = 0, ForeignExceptionCaught, Phase2Error, Phase1Error, NormalStop, EndOfStack, HandlerFound, InstallContext, ContinueUnwind, Failure, } /// /// DWARF encoding types for variable-length data. /// [Flags] private enum DwarfEncoding : byte { // Encoding types: Pointer = 0x00, Uleb128 = 0x01, Udata2 = 0x02, Udata4 = 0x03, Udata8 = 0x04, Sleb128 = 0x09, Sdata2 = 0x0a, Sdata4 = 0x0b, Sdata8 = 0x0c, TypeMask = 0x0f, // Encoding modifiers: Absolute = 0x00, PcRelative = 0x10, TextRelative = 0x20, DataRelative = 0x30, FunctionRelative = 0x40, Aligned = 0x50, ModifierMask = 0x70, // Special values: Indirect = 0x80, Omit = 0xff, } internal const ulong ExceptionClass = 0x000023435446534d; // "MSFTC#\0\0" [ExportedMethod] static public unsafe UnwindReasonCode LLOS_Unwind_Personality( UnwindActions actions, UInt64 exceptionClass, UIntPtr exceptionObject, UIntPtr context) { // TODO: Should we execute cleanup pads? if (exceptionClass != ExceptionClass) { // We have been notified of a foreign exception being thrown, and we therefore need to // execute cleanup landing pads. return UnwindReasonCode.ContinueUnwind; } byte* lsda = (byte*)LLOS_Unwind_GetLanguageSpecificData(context); if (lsda == null) { return UnwindReasonCode.ContinueUnwind; } // Get the current instruction pointer and offset it before next instruction in the current // frame which threw the exception. ulong pc = (ulong)LLOS_Unwind_GetIP(context) - 1; // Get beginning current frame's code (as defined by the emitted dwarf code) ulong funcStart = (ulong)LLOS_Unwind_GetRegionStart(context); ulong pcOffset = pc - funcStart; // Get the landing pad's base address; defaults to the start of the function. DwarfEncoding landingPadBaseEncoding = (DwarfEncoding)(*lsda); ++lsda; if (landingPadBaseEncoding != DwarfEncoding.Omit) { funcStart = ReadEncodedPointer(ref lsda, landingPadBaseEncoding); } DwarfEncoding typeEncoding = (DwarfEncoding)(*lsda); ++lsda; // Get the type info list; this is an array of pointers to type info, in our case VTable*. // It points to the end of the table and expects a one-based index. UIntPtr classInfo = UIntPtr.Zero; if (typeEncoding != DwarfEncoding.Omit) { ulong classInfoOffset = ReadULEB128(ref lsda); classInfo = (UIntPtr)(lsda + classInfoOffset); } DwarfEncoding callSiteEncoding = (DwarfEncoding)(*lsda); ++lsda; uint callSiteTableLength = (uint)ReadULEB128(ref lsda); byte* callSiteTableStart = lsda; byte* callSiteTableEnd = callSiteTableStart + callSiteTableLength; byte* actionTableStart = callSiteTableEnd; byte* callSitePtr = callSiteTableStart; UIntPtr landingPad = UIntPtr.Zero; ulong actionEntry = 0; // Walk the call sites to find which region the PC falls in. while (callSitePtr < callSiteTableEnd) { // These values are offsets from the function start. ulong start = ReadEncodedPointer(ref callSitePtr, callSiteEncoding); ulong length = ReadEncodedPointer(ref callSitePtr, callSiteEncoding); ulong pad = ReadEncodedPointer(ref callSitePtr, callSiteEncoding); // One-based currentByte offset into the action table. actionEntry = ReadULEB128(ref callSitePtr); if ((start <= pcOffset) && (pcOffset < (start + length))) { // Landing pad may be zero to indicate this region has no handlers. landingPad = (UIntPtr)pad; break; } } if (landingPad == UIntPtr.Zero) { // No landing pad for this frame. return UnwindReasonCode.ContinueUnwind; } landingPad = AddressMath.Increment(landingPad, (uint)funcStart); // Action entry of zero means this is a cleanup pad. if (actionEntry == 0) { if (((actions & UnwindActions.CleanupPhase) != 0) && ((actions & UnwindActions.HandlerFrame) == 0)) { return UnwindReasonCode.HandlerFound; } return UnwindReasonCode.ContinueUnwind; } object thrownException = LLOS_GetExceptionObject(exceptionObject); byte* action = actionTableStart + actionEntry - 1; for (int i = 0; true; ++i) { ulong typeIndex = ReadSLEB128(ref action); if (typeIndex > 0) { // This is a catch clause. Get the associated vtable and see if it matches the thrown exception. bool foundMatch = false; VTable entryVTable = GetEntryVTable(typeIndex, typeEncoding, classInfo); if (entryVTable == null) { // Null clause means we should match anything. foundMatch = true; } else if (TypeSystemManager.CastToTypeNoThrow(thrownException, entryVTable) != null) { // Thrown exception is a subclass of the clause's vtable. foundMatch = true; } if (foundMatch) { if ((actions & UnwindActions.SearchPhase) != 0) { return UnwindReasonCode.HandlerFound; } if ((actions & UnwindActions.HandlerFrame) != 0) { LLOS_Unwind_SetRegisters(context, landingPad, exceptionObject, (UIntPtr)(i + 1)); return UnwindReasonCode.InstallContext; } // If this isn't a search or a handler phase, then it must be a force unwind. if ((actions & UnwindActions.ForceUnwind) == 0) { LLOS_Terminate(); } } } else if (typeIndex == 0) { // This is a cleanup pad. If this is the cleanup phase, handle it. We intentionally // pass an invalid (zero) selector so the landing pad doesn't execute any catch handlers. if (((actions & UnwindActions.CleanupPhase) != 0) && ((actions & UnwindActions.HandlerFrame) == 0)) { LLOS_Unwind_SetRegisters(context, landingPad, exceptionObject, UIntPtr.Zero); return UnwindReasonCode.InstallContext; } } else { // This is a filter clause; ignore it. } // Move to the next handler. If there isn't one, we didn't find an appropriate clause. byte* tempAction = action; ulong actionOffset = ReadSLEB128(ref tempAction); if (actionOffset == 0) { return UnwindReasonCode.ContinueUnwind; } action += actionOffset; } } private static unsafe VTable GetEntryVTable( ulong typeIndex, DwarfEncoding typeEncoding, UIntPtr classInfo) { UIntPtr typePointer = AddressMath.Decrement(classInfo, (uint)typeIndex * GetEncodingSize(typeEncoding)); #if ARM_EABI UIntPtr offset = *(UIntPtr*)typePointer; if (offset == UIntPtr.Zero) { return null; } UIntPtr vtablePointer = AddressMath.Increment(typePointer, offset.ToUInt32()); #else // ARM_EABI byte* tempTypePointer = (byte*)typePointer.ToPointer(); UIntPtr vtablePointer = (UIntPtr)ReadEncodedPointer(ref tempTypePointer, typeEncoding); #endif // ARM_EABI // Note: We need to adjust the VTable pointer past the object header due to the LLVM bug cited // in Translate_LandingPadOperator. When this issue is resolved we can remove the adjustment. return (VTable)(object)ObjectHeader.CastAsObjectHeader(vtablePointer).Pack(); } // Decode an unsigned leb128 value and advance the data pointer. // See (7.6) Variable Length Data in: http://dwarfstd.org/doc/DWARF4.pdf private static unsafe ulong ReadULEB128(ref byte* data) { ulong result = 0; int shift = 0; byte currentByte; do { currentByte = *(data++); result |= ((ulong)(currentByte & 0x7f)) << shift; shift += 7; } while ((currentByte & 0x80) != 0); return result; } // Decode a signed leb128 value and advance the data pointer. // See (7.6) Variable Length Data in: http://dwarfstd.org/doc/DWARF4.pdf private static unsafe ulong ReadSLEB128(ref byte* data) { ulong result = 0; int shift = 0; byte currentByte; do { currentByte = *(data++); result |= ((ulong)(currentByte & 0x7f)) << shift; shift += 7; } while ((currentByte & 0x80) != 0); // If the high bit is set on the last (highest order) byte, sign-extend the entire value. if (((currentByte & 0x40) != 0) && (shift < (sizeof(ulong) * 8))) { result |= (ulong.MaxValue << shift); } return result; } // Decode a pointer value and advance the data pointer. private static unsafe ulong ReadEncodedPointer(ref byte* data, DwarfEncoding encoding) { if (encoding == DwarfEncoding.Omit) { return 0; } ulong result = 0; switch (encoding & DwarfEncoding.TypeMask) { case DwarfEncoding.Pointer: result = (*(UIntPtr*)data).ToUInt64(); data += sizeof(UIntPtr); break; case DwarfEncoding.Udata2: case DwarfEncoding.Sdata2: result = *(UInt16*)data; data += sizeof(UInt16); break; case DwarfEncoding.Udata4: case DwarfEncoding.Sdata4: result = *(UInt32*)data; data += sizeof(UInt32); break; case DwarfEncoding.Udata8: case DwarfEncoding.Sdata8: result = *(UInt64*)data; data += sizeof(UInt64); break; case DwarfEncoding.Uleb128: result = ReadULEB128(ref data); break; case DwarfEncoding.Sleb128: result = ReadSLEB128(ref data); break; default: LLOS_Terminate(); break; } // Adjust the value. switch (encoding & DwarfEncoding.ModifierMask) { case DwarfEncoding.Absolute: break; case DwarfEncoding.PcRelative: if (result != 0) { result += (ulong)data; } break; default: LLOS_Terminate(); break; } // Indirect the value if necessary. if ((encoding & DwarfEncoding.Indirect) != 0) { result = *(ulong*)result; } return result; } private static uint GetEncodingSize(DwarfEncoding encoding) { if (encoding == DwarfEncoding.Omit) { return 0; } switch (encoding & DwarfEncoding.TypeMask) { case DwarfEncoding.Pointer: return (uint)System.Runtime.InteropServices.Marshal.SizeOf(typeof(UIntPtr)); case DwarfEncoding.Udata2: case DwarfEncoding.Sdata2: return 2; case DwarfEncoding.Udata4: case DwarfEncoding.Sdata4: return 4; case DwarfEncoding.Udata8: case DwarfEncoding.Sdata8: return 8; default: LLOS_Terminate(); return 0; } } [DllImport("C")] internal static extern UIntPtr LLOS_AllocateException(object exception, UInt64 exceptionClass); [DllImport("C")] internal static extern object LLOS_GetExceptionObject(UIntPtr exception); [DllImport("C")] internal static extern UIntPtr LLOS_Unwind_GetIP(UIntPtr context); [DllImport("C")] internal static extern UIntPtr LLOS_Unwind_GetLanguageSpecificData(UIntPtr context); [DllImport("C")] internal static extern UIntPtr LLOS_Unwind_GetRegionStart(UIntPtr context); [DllImport("C")] internal static extern void LLOS_Unwind_SetRegisters( UIntPtr context, UIntPtr landingPad, UIntPtr exceptionObject, UIntPtr selector); [NoReturn] [DllImport("C")] internal static extern void LLOS_Unwind_RaiseException(UIntPtr exceptionObject); [NoReturn] [DllImport("C")] internal static extern void LLOS_Terminate(); } } ================================================ FILE: Zelig/Zelig/RunTime/Zelig/Kernel/TypeSystemManagers/DefaultTypeSystemManager.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // namespace Microsoft.Zelig.Runtime { using System; using System.Runtime.CompilerServices; using TS = Microsoft.Zelig.Runtime.TypeSystem; [TS.DisableAutomaticReferenceCounting] public abstract class DefaultTypeSystemManager : TypeSystemManager { [NoInline] public override Object AllocateObject( TS.VTable vTable ) { uint size = ComputeObjectSize( vTable ); UIntPtr ptr; object obj; using(SmartHandles.YieldLockHolder hnd = new SmartHandles.YieldLockHolder( MemoryManager.Lock )) { ptr = AllocateInner( vTable, size ); obj = InitializeObject( ptr, vTable, referenceCounting: false ); } if(MemoryManager.Configuration.TrashFreeMemory) { Memory.Zero( ( (ObjectImpl)obj ).GetFieldPointer( ), AddressMath.Increment( ptr, size ) ); } return obj; } [NoInline] public override Object AllocateReferenceCountingObject( TS.VTable vTable ) { uint size = ComputeObjectSize( vTable ); UIntPtr ptr; object obj; using(SmartHandles.YieldLockHolder hnd = new SmartHandles.YieldLockHolder( MemoryManager.Lock )) { ptr = AllocateInner( vTable, size ); obj = InitializeObject( ptr, vTable, referenceCounting: true ); } if(MemoryManager.Configuration.TrashFreeMemory) { Memory.Zero( ( (ObjectImpl)obj ).GetFieldPointer( ), AddressMath.Increment( ptr, size ) ); } return obj; } [NoInline] public override Object AllocateObjectWithExtensions( TS.VTable vTable ) { uint size = ComputeObjectSize( vTable ); UIntPtr ptr; object obj; using(SmartHandles.YieldLockHolder hnd = new SmartHandles.YieldLockHolder( MemoryManager.Lock )) { ptr = AllocateInner( vTable, size ); obj = InitializeObjectWithExtensions( ptr, vTable ); } if(MemoryManager.Configuration.TrashFreeMemory) { Memory.Zero( ( (ObjectImpl)obj ).GetFieldPointer( ), AddressMath.Increment( ptr, size ) ); } return obj; } [NoInline] public override Array AllocateArray( TS.VTable vTable , uint length ) { uint size = ComputeArraySize( vTable, length ); UIntPtr ptr; Array array; using(SmartHandles.YieldLockHolder hnd = new SmartHandles.YieldLockHolder( MemoryManager.Lock )) { ptr = AllocateInner( vTable, size ); array = InitializeArray( ptr, vTable, length, referenceCounting: false ); } if(MemoryManager.Configuration.TrashFreeMemory) { unsafe { Memory.Zero( (UIntPtr)ArrayImpl.CastAsArray( array ).GetDataPointer( ), AddressMath.Increment( ptr, size ) ); } } return array; } [NoInline] public override Array AllocateReferenceCountingArray( TS.VTable vTable, uint length ) { uint size = ComputeArraySize( vTable, length ); UIntPtr ptr; Array array; using(SmartHandles.YieldLockHolder hnd = new SmartHandles.YieldLockHolder( MemoryManager.Lock )) { ptr = AllocateInner( vTable, size ); array = InitializeArray( ptr, vTable, length, referenceCounting: true ); } if(MemoryManager.Configuration.TrashFreeMemory) { unsafe { Memory.Zero( (UIntPtr)ArrayImpl.CastAsArray( array ).GetDataPointer( ), AddressMath.Increment( ptr, size ) ); } } return array; } [NoInline] public override Array AllocateArrayNoClear( TS.VTable vTable , uint length ) { uint size = ComputeArraySize( vTable, length ); UIntPtr ptr; Array array; using(SmartHandles.YieldLockHolder hnd = new SmartHandles.YieldLockHolder( MemoryManager.Lock )) { ptr = AllocateInner( vTable, size ); array = InitializeArray( ptr, vTable, length, referenceCounting: false ); } return array; } [NoInline] public override String AllocateString( TS.VTable vTable , int length ) { uint size = ComputeArraySize( vTable, (uint)length ); UIntPtr ptr; String str; using(SmartHandles.YieldLockHolder hnd = new SmartHandles.YieldLockHolder( MemoryManager.Lock )) { ptr = AllocateInner( vTable, size ); str = InitializeString( ptr, vTable, length, referenceCounting: false ); } if(MemoryManager.Configuration.TrashFreeMemory) { unsafe { Memory.Zero( (UIntPtr)StringImpl.CastAsString( str ).GetDataPointer( ), AddressMath.Increment( ptr, size ) ); } } return str; } [NoInline] public override String AllocateReferenceCountingString( TS.VTable vTable , int length ) { uint size = ComputeArraySize( vTable, (uint)length ); UIntPtr ptr; String str; using(SmartHandles.YieldLockHolder hnd = new SmartHandles.YieldLockHolder( MemoryManager.Lock )) { ptr = AllocateInner( vTable, size ); str = InitializeString( ptr, vTable, length, referenceCounting: true ); } if(MemoryManager.Configuration.TrashFreeMemory) { unsafe { Memory.Zero( (UIntPtr)StringImpl.CastAsString( str ).GetDataPointer( ), AddressMath.Increment( ptr, size ) ); } } return str; } //--// public static uint ComputeObjectSize(TS.VTable vTable) { return ObjectHeader.HeaderSize + ObjectHeader.ComputeObjectSize(vTable, arrayLength: 0); } public static uint ComputeArraySize(TS.VTable vTable, uint length) { return ObjectHeader.HeaderSize + ObjectHeader.ComputeObjectSize(vTable, length); } //--// [TS.WellKnownMethod("DebugGC_DefaultTypeSystemManager_AllocateInner")] private UIntPtr AllocateInner( TS.VTable vTable , uint size ) { UIntPtr ptr = MemoryManager.Instance.Allocate( size ); if(ptr == UIntPtr.Zero) { GarbageCollectionManager.Instance.Collect(); ptr = MemoryManager.Instance.Allocate( size ); if(ptr == UIntPtr.Zero) { GarbageCollectionManager.Instance.ThrowOutOfMemory( vTable ); } } return ptr; } } } ================================================ FILE: Zelig/Zelig/RunTime/Zelig/LlilumCMSIS-RTOS/API/CmsisObject.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // namespace Microsoft.Zelig.LlilumOSAbstraction.CmsisRtos { using System; using Microsoft.Zelig.Runtime; using RT = Microsoft.Zelig.Runtime; internal class CmsisObject : IDisposable { // // State // private static RT.KernelList s_objects = new RT.KernelList(); //--// private readonly RT.KernelNode m_registrationLink; //--// // // Constructors // protected CmsisObject() { RT.BugCheck.Assert( RT.TargetPlatform.ARMv7.ProcessorARMv7M.IsAnyExceptionActive() == false, BugCheck.StopCode.IllegalMode ); m_registrationLink = new RT.KernelNode( this ); Register( this ); } internal static void Register( CmsisObject obj ) { using(RT.SmartHandles.InterruptState.DisableAll()) { s_objects.InsertAtTail( obj.RegistrationLink ); } } internal static void Deregister( CmsisObject obj ) { using(RT.SmartHandles.InterruptState.DisableAll()) { obj.RegistrationLink.RemoveFromList( ); } } protected virtual void Dispose( bool disposing ) { Deregister( this ); } ~CmsisObject( ) { Dispose( false ); } public void Dispose( ) { Dispose( true ); GC.SuppressFinalize(this); } // // Helper methods // public static CmsisObject GetObject( UIntPtr ptr ) { using(RT.SmartHandles.InterruptState.DisableAll( )) { RT.KernelNode< CmsisObject > node = s_objects.StartOfForwardWalk; while(node.IsValidForForwardMove) { var node2 = (ObjectImpl)(object)node.Target; if(node2.ToPointer( ) == ptr) { break; } node = node.Next; } if(node.IsValidForForwardMove) { return node.Target; } } return null; } public static CmsisObject FindObject( object cmp ) where T: CmsisObject { using(RT.SmartHandles.InterruptState.DisableAll( )) { RT.KernelNode< CmsisObject > node = s_objects.StartOfForwardWalk; while(node.IsValidForForwardMove) { CmsisObject obj = (CmsisObject)node.Target; if(obj is T) { if(( (T)obj ).SameObject( cmp )) { return obj; } } node = node.Next; } } return null; } // // Access Methods // protected RT.KernelNode RegistrationLink { get { return m_registrationLink; } } protected virtual bool SameObject( object cmp ) { return this == cmp; } } } ================================================ FILE: Zelig/Zelig/RunTime/Zelig/LlilumCMSIS-RTOS/API/CmsisRtos.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // namespace Microsoft.Zelig.LlilumOSAbstraction.CmsisRtos { using System; using System.Runtime.InteropServices; using System.Threading; using RT = Microsoft.Zelig.Runtime; public static class CmsisRtos { // // !!! keep in sync with same enums and structures in cmsis_os.h // public enum osStatus { osOK = 0, ///< function completed; no error or event occurred. osEventSignal = 0x08, ///< function completed; signal event occurred. osEventMessage = 0x10, ///< function completed; message event occurred. osEventMail = 0x20, ///< function completed; mail event occurred. osEventTimeout = 0x40, ///< function completed; timeout occurred. osErrorParameter = 0x80, ///< parameter error: a mandatory parameter was missing or specified an incorrect object. osErrorResource = 0x81, ///< resource not available: a specified resource was not available. osErrorTimeoutResource = 0xC1, ///< resource not available within given time: a specified resource was not available within the timeout period. osErrorISR = 0x82, ///< not allowed in ISR context: the function cannot be called from interrupt service routines. osErrorISRRecursive = 0x83, ///< function called multiple times from ISR with same object. osErrorPriority = 0x84, ///< system cannot determine priority or thread has illegal priority. osErrorNoMemory = 0x85, ///< system is out of memory: it was impossible to allocate or reserve memory for the operation. osErrorValue = 0x86, ///< value of a parameter is out of range. osErrorOS = 0xFF, ///< unspecified RTOS error: run-time error but no other error message fits. os_status_reserved = 0x7FFFFFFF ///< prevent from enum down-size compiler optimization. } //--// //[StructLayout( LayoutKind.Sequential, Pack = 4 )] //public struct osEvent__value //{ // public uint v; // public UIntPtr p; // public int signals; //} [StructLayout( LayoutKind.Sequential, Pack = 4 )] public struct osEvent { public osStatus status; public UIntPtr value; public UIntPtr def; public osEvent( osStatus status ) { this.status = status; this.value = UIntPtr.Zero; this.def = UIntPtr.Zero; } public static osEvent ErrorParameter { get { return new osEvent(osStatus.osErrorParameter); } } public static osEvent ErrorValue { get { return new osEvent(osStatus.osErrorValue); } } public static osEvent OK { get { return new osEvent(osStatus.osOK); } } public static osEvent Timeout { get { return new osEvent(osStatus.osEventTimeout); } } public static osEvent ErrorISR { get { return new osEvent(osStatus.osErrorISR); } } public static osEvent Message { get { return new osEvent(osStatus.osEventMessage); } } internal osEvent With(UIntPtr message) { this.value = message; return this; } } //--// public enum OsPriority { osPriorityIdle = -3, ///< priority: idle (lowest) osPriorityLow = -2, ///< priority: low osPriorityBelowNormal = -1, ///< priority: below normal osPriorityNormal = 0, ///< priority: normal (default) osPriorityAboveNormal = +1, ///< priority: above normal osPriorityHigh = +2, ///< priority: high osPriorityRealtime = +3, ///< priority: realtime (highest) osPriorityError = 0x84 ///< system cannot determine priority or thread has illegal priority }; internal static ThreadPriority ConvertPriority( OsPriority pri ) { switch(pri) { case OsPriority.osPriorityIdle : return ThreadPriority.Lowest; case OsPriority.osPriorityLow : return ThreadPriority.Lowest; case OsPriority.osPriorityBelowNormal : return ThreadPriority.BelowNormal; case OsPriority.osPriorityNormal : return ThreadPriority.Normal; case OsPriority.osPriorityAboveNormal : return ThreadPriority.Normal; case OsPriority.osPriorityHigh : return ThreadPriority.AboveNormal; case OsPriority.osPriorityRealtime : return ThreadPriority.Highest; case OsPriority.osPriorityError : default: throw new ArgumentException( ); } } //--// [StructLayout( LayoutKind.Sequential, Pack = 4 )] public struct osMessageQDef_t { public uint queue_sz; public uint item_sz; public UIntPtr pool; } [StructLayout( LayoutKind.Sequential, Pack = 4 )] public struct os_messageQ_cb { } //--// [StructLayout( LayoutKind.Sequential, Pack = 4 )] public struct osMutexDef_t { public uint dummy; } [StructLayout( LayoutKind.Sequential, Pack = 4 )] public struct os_mutex_cb { //public uint dummy; } //--// [StructLayout( LayoutKind.Sequential, Pack = 4 )] public struct oPoolQDef_t { public uint pool_sz; public uint item_sz; public UIntPtr pool; } [StructLayout( LayoutKind.Sequential, Pack = 4 )] public struct os_pool_cb { //public UIntPtr dummy; } //--// [StructLayout( LayoutKind.Sequential, Pack = 4 )] public struct osSemaphoreDef_t { public uint dummy; } [StructLayout( LayoutKind.Sequential, Pack = 4 )] public struct os_semaphore_cb { //public uint dummy; } //--// [StructLayout( LayoutKind.Sequential, Pack = 4 )] public struct osThreadDef_t { public UIntPtr pthread; // this is the code pointer for a delegate (function pointer) type 'typedef void(* os_pthread)(void const *argument)' public OsPriority tpriority; public uint instances; public uint stackSize; } [StructLayout( LayoutKind.Sequential, Pack = 4 )] public struct os_thread_cb { //UIntPtr dummy; } // o~~o~~o~~o~~o~~o~~o~~o~~o~~o~~o~~o~~o~~o~~o~~o~~o~~o~~o~~o~~o~~o~~o~~o~~o~~o~~o~~o~~o~~o~~o~~o~~o~~o~~o~~o~~o~~o~~o // // o~~o~~o~~o~~o~~o~~o~~o~~o~~o~~o~~o~~o~~o~~o~~o~~o~~o~~o~~o~~o~~o~~o~~o~~o~~o~~o~~o~~o~~o~~o~~o~~o~~o~~o~~o~~o~~o~~o // // o~~o~~o~~o~~o~~o~~o~~o~~o~~o~~o~~o~~o~~o~~o~~o~~o~~o~~o~~o~~o~~o~~o~~o~~o~~o~~o~~o~~o~~o~~o~~o~~o~~o~~o~~o~~o~~o~~o // // // Wait/Delay // [RT.ExportedMethod] public static osStatus osDelay( uint millisec ) { if(RT.TargetPlatform.ARMv7.ProcessorARMv7M.IsAnyExceptionActive( )) { RT.BugCheck.Raise( Runtime.BugCheck.StopCode.IllegalMode ); return osStatus.osErrorISR; } RT.TargetPlatform.ARMv7.ProcessorARMv7M.DelayMicroseconds( millisec * 1000 ); return osStatus.osEventTimeout; } [RT.ExportedMethod] public static osStatus osWaitEx( uint millisec, ref osEvent ev ) { if(RT.TargetPlatform.ARMv7.ProcessorARMv7M.IsAnyExceptionActive( )) { ev.status = osStatus.osErrorParameter; return osStatus.osErrorParameter; } RT.TargetPlatform.ARMv7.ProcessorARMv7M.DelayMicroseconds( millisec * 1000 ); return osStatus.osEventTimeout; } // o~~o~~o~~o~~o~~o~~o~~o~~o~~o~~o~~o~~o~~o~~o~~o~~o~~o~~o~~o~~o~~o~~o~~o~~o~~o~~o~~o~~o~~o~~o~~o~~o~~o~~o~~o~~o~~o~~o // // o~~o~~o~~o~~o~~o~~o~~o~~o~~o~~o~~o~~o~~o~~o~~o~~o~~o~~o~~o~~o~~o~~o~~o~~o~~o~~o~~o~~o~~o~~o~~o~~o~~o~~o~~o~~o~~o~~o // // o~~o~~o~~o~~o~~o~~o~~o~~o~~o~~o~~o~~o~~o~~o~~o~~o~~o~~o~~o~~o~~o~~o~~o~~o~~o~~o~~o~~o~~o~~o~~o~~o~~o~~o~~o~~o~~o~~o // // // Message Queue // [RT.ExportedMethod] public static unsafe os_messageQ_cb* osMessageCreate( osMessageQDef_t* queue_def, os_thread_cb* thread_id ) { var msgQueue = CmsisRtosMessageQueue.Create( queue_def->queue_sz ); return (os_messageQ_cb*)msgQueue.ToPointer( ); } [RT.ExportedMethod] public static unsafe osStatus osMessageGetEx( os_messageQ_cb* queue_id, uint millisec, ref osEvent ev ) { if(queue_id == null) { ev.status = osStatus.osErrorParameter; return osStatus.osErrorParameter; } var msgQueue = CmsisRtosMessageQueue.ToObject( (UIntPtr)queue_id ); if(msgQueue == null) { ev.status = osStatus.osErrorParameter; return osStatus.osErrorParameter; } UIntPtr message; if(msgQueue.TryGetMessage( (int)millisec, out message ) == false) { if(millisec == 0) { ev.status = osStatus.osOK; return osStatus.osOK; } ev.status = osStatus.osEventTimeout; return osStatus.osEventTimeout; } ev.status = osStatus.osEventMessage; ev.value = message; return osStatus.osEventMessage; } [RT.ExportedMethod] public static unsafe osStatus osMessagePut( os_messageQ_cb* queue_id, uint info, uint millisec ) { if(queue_id == null) { return osStatus.osErrorParameter; } var msgQueue = CmsisRtosMessageQueue.ToObject( (UIntPtr)queue_id ); if(msgQueue == null) { return osStatus.osErrorParameter; } if(msgQueue.TryPutMessage( new UIntPtr( info ), (int)millisec ) == false) { if(millisec == 0) { return osStatus.osOK; } return osStatus.osErrorTimeoutResource; } return osStatus.osOK; } [RT.ExportedMethod] public static unsafe osStatus osMessageDelete( os_messageQ_cb* queue_id ) { if(queue_id == null) { return osStatus.osErrorParameter; } var msgQueue = CmsisRtosMessageQueue.ToObject( (UIntPtr)queue_id ); if(msgQueue == null) { return osStatus.osErrorParameter; } msgQueue.Dispose( ); return osStatus.osOK; } // o~~o~~o~~o~~o~~o~~o~~o~~o~~o~~o~~o~~o~~o~~o~~o~~o~~o~~o~~o~~o~~o~~o~~o~~o~~o~~o~~o~~o~~o~~o~~o~~o~~o~~o~~o~~o~~o~~o // // o~~o~~o~~o~~o~~o~~o~~o~~o~~o~~o~~o~~o~~o~~o~~o~~o~~o~~o~~o~~o~~o~~o~~o~~o~~o~~o~~o~~o~~o~~o~~o~~o~~o~~o~~o~~o~~o~~o // // o~~o~~o~~o~~o~~o~~o~~o~~o~~o~~o~~o~~o~~o~~o~~o~~o~~o~~o~~o~~o~~o~~o~~o~~o~~o~~o~~o~~o~~o~~o~~o~~o~~o~~o~~o~~o~~o~~o // // // Mutex // [RT.ExportedMethod] public static unsafe os_mutex_cb* osMutexCreate( osMutexDef_t* mutex_def ) { var mutex = CmsisRtosMutex.Create(); return (os_mutex_cb*)mutex.ToPointer( ); } [RT.ExportedMethod] public static unsafe osStatus osMutexWait( os_mutex_cb* mutex_id, uint millisec ) { if(RT.TargetPlatform.ARMv7.ProcessorARMv7M.IsAnyExceptionActive( )) { RT.BugCheck.Raise( Runtime.BugCheck.StopCode.IllegalMode ); return osStatus.osErrorISR; } if(mutex_id == null) { return osStatus.osErrorParameter; } var mutex = CmsisRtosMutex.ToObject( (UIntPtr)mutex_id ); if(mutex == null) { return osStatus.osErrorParameter; } var locked = mutex.Lock( (int)millisec ); if(locked) { return osStatus.osOK; } if(millisec == 0) { return osStatus.osErrorResource; } return osStatus.osErrorTimeoutResource; } [RT.ExportedMethod] public static unsafe osStatus osMutexRelease( os_mutex_cb* mutex_id ) { if(RT.TargetPlatform.ARMv7.ProcessorARMv7M.IsAnyExceptionActive( )) { RT.BugCheck.Raise( Runtime.BugCheck.StopCode.IllegalMode ); return osStatus.osErrorISR; } if(mutex_id == null) { return osStatus.osErrorParameter; } var mutex = CmsisRtosMutex.ToObject( (UIntPtr)mutex_id ); if(mutex == null) { return osStatus.osErrorParameter; } mutex.Unlock( ); return osStatus.osOK; } [RT.ExportedMethod] public static unsafe osStatus osMutexDelete( os_mutex_cb* mutex_id ) { if(RT.TargetPlatform.ARMv7.ProcessorARMv7M.IsAnyExceptionActive( )) { RT.BugCheck.Raise( Runtime.BugCheck.StopCode.IllegalMode ); return osStatus.osErrorISR; } if(mutex_id == null) { return osStatus.osErrorParameter; } var mutex = CmsisRtosMutex.ToObject( (UIntPtr)mutex_id ); if(mutex == null) { return osStatus.osErrorParameter; } mutex.Dispose( ); return osStatus.osOK; } // o~~o~~o~~o~~o~~o~~o~~o~~o~~o~~o~~o~~o~~o~~o~~o~~o~~o~~o~~o~~o~~o~~o~~o~~o~~o~~o~~o~~o~~o~~o~~o~~o~~o~~o~~o~~o~~o~~o // // o~~o~~o~~o~~o~~o~~o~~o~~o~~o~~o~~o~~o~~o~~o~~o~~o~~o~~o~~o~~o~~o~~o~~o~~o~~o~~o~~o~~o~~o~~o~~o~~o~~o~~o~~o~~o~~o~~o // // o~~o~~o~~o~~o~~o~~o~~o~~o~~o~~o~~o~~o~~o~~o~~o~~o~~o~~o~~o~~o~~o~~o~~o~~o~~o~~o~~o~~o~~o~~o~~o~~o~~o~~o~~o~~o~~o~~o // // // Semaphore // [RT.ExportedMethod] public static unsafe os_semaphore_cb* osSemaphoreCreate( osSemaphoreDef_t* semaphore_def, int count ) { var sem = CmsisRtosSemaphore.Create( count ); return (os_semaphore_cb*)sem.ToPointer( ); } [RT.ExportedMethod] public static unsafe int osSemaphoreWaitEx( os_semaphore_cb* semaphore_id, uint millisec ) { if(RT.TargetPlatform.ARMv7.ProcessorARMv7M.IsAnyExceptionActive( )) { RT.BugCheck.Raise( Runtime.BugCheck.StopCode.IllegalMode ); } if(semaphore_id == null) { return 0; } var sem = CmsisRtosSemaphore.ToObject( (UIntPtr)semaphore_id ); if(sem == null) { return 0; } return sem.Acquire( (int)millisec ); } [RT.ExportedMethod] public static unsafe osStatus osSemaphoreRelease( os_semaphore_cb* semaphore_id ) { if(semaphore_id == null) { return osStatus.osErrorParameter; } var sem = CmsisRtosSemaphore.ToObject( (UIntPtr)semaphore_id ); if(sem == null) { return osStatus.osErrorParameter; } //////if(Microsoft.Zelig.Runtime.TargetPlatform.ARMv7.ProcessorARMv7M.IsAnyExceptionActive( )) //////{ ////// using(RT.SmartHandles.InterruptState.Disable( )) ////// { ////// using(RT.SmartHandles.SwapCurrentThreadUnderInterrupt hnd = RT.ThreadManager.InstallInterruptThread( )) ////// { ////// sem.Release( ); ////// } ////// } //////} //////else //////{ sem.Release( ); //////} return osStatus.osOK; } [RT.ExportedMethod] public static unsafe osStatus osSemaphoreDelete( os_semaphore_cb* semaphore_id ) { if(RT.TargetPlatform.ARMv7.ProcessorARMv7M.IsAnyExceptionActive( )) { RT.BugCheck.Raise( RT.BugCheck.StopCode.IllegalMode ); return osStatus.osErrorISR; } if(semaphore_id == null) { return osStatus.osErrorParameter; } var sem = CmsisRtosSemaphore.ToObject( (UIntPtr)semaphore_id ); if(sem == null) { return osStatus.osErrorParameter; } sem.Dispose( ); return osStatus.osOK; } // o~~o~~o~~o~~o~~o~~o~~o~~o~~o~~o~~o~~o~~o~~o~~o~~o~~o~~o~~o~~o~~o~~o~~o~~o~~o~~o~~o~~o~~o~~o~~o~~o~~o~~o~~o~~o~~o~~o // // o~~o~~o~~o~~o~~o~~o~~o~~o~~o~~o~~o~~o~~o~~o~~o~~o~~o~~o~~o~~o~~o~~o~~o~~o~~o~~o~~o~~o~~o~~o~~o~~o~~o~~o~~o~~o~~o~~o // // o~~o~~o~~o~~o~~o~~o~~o~~o~~o~~o~~o~~o~~o~~o~~o~~o~~o~~o~~o~~o~~o~~o~~o~~o~~o~~o~~o~~o~~o~~o~~o~~o~~o~~o~~o~~o~~o~~o // // // Thread // [RT.ExportedMethod] public static unsafe os_thread_cb* osThreadCreate( osThreadDef_t* thread_def, UIntPtr arg ) { var th = CmsisRtosThread.Create( thread_def->pthread , ConvertPriority( thread_def->tpriority ), thread_def->stackSize , arg ); return (os_thread_cb*)th.ToPointer( ); } [RT.ExportedMethod] public static unsafe os_thread_cb* osThreadGetId( ) { return (os_thread_cb*)CmsisRtosThread.GetId( Thread.CurrentThread ); } } } ================================================ FILE: Zelig/Zelig/RunTime/Zelig/LlilumCMSIS-RTOS/API/CmsisRtosMessageQueue.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // namespace Microsoft.Zelig.LlilumOSAbstraction.CmsisRtos { using System; using System.Collections; using Microsoft.Zelig.Runtime; using Microsoft.Zelig.Runtime.TypeSystem; internal class CmsisRtosMessageQueue : CmsisObject { private readonly KernelCircularBuffer m_messages; //--// public static CmsisRtosMessageQueue Create( uint queueSize ) { return new CmsisRtosMessageQueue( queueSize ); } private CmsisRtosMessageQueue( uint queueSize ) : base() { m_messages = new KernelCircularBuffer( (int)queueSize ); } //--// protected override void Dispose( bool fDisposing ) { base.Dispose( fDisposing ); //////UIntPtr message; //////while(TryGetMessage( 0, out message )) //////{ //////} } //--// // // Helper methods // public unsafe bool TryGetMessage( int millisec, out UIntPtr message ) { if(m_messages.DequeueBlocking( millisec, out message )) { return true; } return false; } public unsafe bool TryPutMessage( UIntPtr message, int millisec ) { if(m_messages.EnqueueBlocking( millisec, message )) { return true; } return false; } //--// [GenerateUnsafeCast] internal extern UIntPtr ToPointer(); [GenerateUnsafeCast] internal extern static CmsisRtosMessageQueue ToObject(UIntPtr mutex); } } ================================================ FILE: Zelig/Zelig/RunTime/Zelig/LlilumCMSIS-RTOS/API/CmsisRtosMutex.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // namespace Microsoft.Zelig.LlilumOSAbstraction.CmsisRtos { using System; using System.Threading; using TS = Microsoft.Zelig.Runtime.TypeSystem; internal class CmsisRtosMutex : CmsisObject { private readonly object m_sync; //--// public static CmsisRtosMutex Create( ) { return new CmsisRtosMutex(); } private CmsisRtosMutex( ) : base() { m_sync = new object( ); } //--// protected override void Dispose( bool fDisposing ) { base.Dispose( fDisposing ); //////Unlock( ); } //--// // // Helper methods // public bool Lock( int millisec ) { if(millisec < 0) { Monitor.Enter( m_sync ); } else { if(Monitor.TryEnter( m_sync, millisec )) { return true; } return false; } return true; } public void Unlock( ) { Monitor.Exit( m_sync ); } //--// [TS.GenerateUnsafeCast] internal extern UIntPtr ToPointer( ); [TS.GenerateUnsafeCast] internal extern static CmsisRtosMutex ToObject( UIntPtr mutex ); } } ================================================ FILE: Zelig/Zelig/RunTime/Zelig/LlilumCMSIS-RTOS/API/CmsisRtosSemaphore.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // namespace Microsoft.Zelig.LlilumOSAbstraction.CmsisRtos { using System; using System.Threading; using RT = Microsoft.Zelig.Runtime; using TS = Microsoft.Zelig.Runtime.TypeSystem; using LLOS = Microsoft.Zelig.LlilumOSAbstraction; internal class CmsisRtosSemaphore : CmsisObject { private readonly AutoResetEvent m_free; private int m_count; //--// public static CmsisRtosSemaphore Create( int count ) { return new CmsisRtosSemaphore(count); } private CmsisRtosSemaphore( int count ) : base() { m_count = count; m_free = new AutoResetEvent( false ); } //--// protected override void Dispose( bool fDisposing ) { base.Dispose( fDisposing ); //////if(m_count == 0) //////{ ////// Release( ); //////} } //--// // // Helper methods // public unsafe int Acquire( int timeout ) { bool fAcquired = false; var start = (uint)LLOS.HAL.Timer.LLOS_SYSTEM_TIMER_GetTicks(null); do { while(m_count == 0) { if(m_free.WaitOne( timeout, false ) == false) { return -1; } } using(RT.SmartHandles.InterruptState.DisableAll( )) { // // Some other thread may just have stolen this semaphore, and // and we may have to sleep again // if(m_count > 0) { --m_count; fAcquired = true; } else { if(timeout >= 0) { timeout -= (int)( ( (uint)LLOS.HAL.Timer.LLOS_SYSTEM_TIMER_GetTicks( null ) - start ) / 1000 ); if(timeout < 0) { return -1; } } } } } while(fAcquired == false); return m_count; } public void Release( ) { using(RT.SmartHandles.InterruptState.DisableAll()) { ++m_count; m_free.Set( ); } } //--// [TS.GenerateUnsafeCast] internal extern UIntPtr ToPointer( ); [TS.GenerateUnsafeCast] internal extern static CmsisRtosSemaphore ToObject( UIntPtr semaphore ); } } ================================================ FILE: Zelig/Zelig/RunTime/Zelig/LlilumCMSIS-RTOS/API/CmsisRtosThread.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // namespace Microsoft.Zelig.LlilumOSAbstraction.CmsisRtos { using System; using System.Runtime.InteropServices; using System.Threading; using RT = Microsoft.Zelig.Runtime; using TS = Microsoft.Zelig.Runtime.TypeSystem; internal class CmsisRtosThread : CmsisObject { private RT.ThreadImpl m_thread; private UIntPtr m_codePtr; private UIntPtr m_arg; //--// public static unsafe CmsisRtosThread Create( UIntPtr codePtr, ThreadPriority priority, uint stackSize, UIntPtr arg ) { return new CmsisRtosThread( codePtr, priority, stackSize, arg ); } private unsafe CmsisRtosThread( UIntPtr codePtr, ThreadPriority priority, uint stackSize, UIntPtr arg ) : base() { m_arg = arg; m_codePtr = codePtr; m_thread = new RT.ThreadImpl( ThreadProcedure, new uint[ stackSize ] ); m_thread.Priority = priority; m_thread.Start( ); } //--// protected override void Dispose( bool fDisposing ) { base.Dispose( fDisposing ); //////m_thread.Detach( ); //////if(m_thread != RT.ThreadImpl.CurrentThread) //////{ ////// m_thread.Join( ); //////} } //--// // // Helper methods // public void Terminate() { Dispose( ); } public static UIntPtr GetId( Thread thread ) { var th = CmsisObject.FindObject( thread ); if(th == null) { return UIntPtr.Zero; } return ( (CmsisRtosThread)th ).Id; } public UIntPtr Id { get { return ToPointer( ); } } //--// protected override bool SameObject( object cmp ) { return m_thread == cmp; } //--// private unsafe void ThreadProcedure() { LLOS_lwIPTaskRun( m_codePtr.ToPointer(), m_arg.ToPointer() ); } //--// [DllImport("C")] private static unsafe extern void LLOS_lwIPTaskRun( void* codePtr, void* arg ); //--// [TS.GenerateUnsafeCast] internal extern UIntPtr ToPointer(); [TS.GenerateUnsafeCast] internal extern static CmsisRtosThread ToObject( UIntPtr thread ); } } ================================================ FILE: Zelig/Zelig/RunTime/Zelig/LlilumCMSIS-RTOS/LlilumCMSIS-RTOS.csproj ================================================  Debug AnyCPU 9.0.21022 2.0 {93219A45-914C-44B7-A6CB-66849879C8B1} Library Properties Microsoft.Zelig.Llilum.CMSIS.RTOS Microsoft.Zelig.LlilumCMSIS-RTOS $(LlilumBuildRoot)\Host\obj\$(MSBuildProjectName)\ v4.5 true full false $(LlilumBuildRoot)\Host\bin\$(Configuration)\ DEBUG;TRACE prompt 4 true true true AllRules.ruleset AnyCPU false pdbonly true $(LlilumBuildRoot)\Host\bin\$(Configuration)\ TRACE prompt 4 true true true AllRules.ruleset AnyCPU false true full false $(LlilumBuildRoot)\Host\bin\$(Configuration)\ TRACE;DEBUG AnyCPU true true true false {186F31A3-EF89-4A25-B2D5-20060509AA01} Kernel False {186F31A3-EF89-4A25-B2D5-20060501AA01} mscorlib False {186F31A3-EF89-4A25-B2D5-20070702AA01} system False {186F31A3-EF89-4A25-B2D5-20060509AA01} Kernel False {186F31A3-EF89-4A25-B2D5-20060720AA01} TypeSystem False {186f31a3-ef89-4a25-b2d5-20061218aa01} Common {20dc2cf5-8eed-4231-9743-6bab96be465c} LlilumOSAbstraction 3.5 Native\cc.h Native\checksum.c Native\memcpy.c Native\perf.h Native\sys_arch.c Native\sys_arch.h Native\cmsis_os.h ================================================ FILE: Zelig/Zelig/RunTime/Zelig/LlilumCMSIS-RTOS/Properties/AssemblyInfo.cs ================================================ using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; // General Information about an assembly is controlled through the following // set of attributes. Change these attribute values to modify the information // associated with an assembly. [assembly: AssemblyTitle( "Microsoft.Zelig.Runtime" )] [assembly: AssemblyDescription( "" )] [assembly: AssemblyConfiguration( "" )] [assembly: AssemblyCompany( "Microsoft" )] [assembly: AssemblyProduct( "Microsoft.Zelig.Runtime" )] [assembly: AssemblyCopyright( "Copyright © Microsoft 2006" )] [assembly: AssemblyTrademark( "" )] [assembly: AssemblyCulture( "" )] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible( false )] //// The following GUID is for the ID of the typelib if this project is exposed to COM //[assembly: Guid( "c2e5a31b-4e85-4692-a487-79f792176810" )] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Revision and Build Numbers // by using the '*' as shown below: [assembly: AssemblyVersion( "1.0.0.0" )] [assembly: AssemblyFileVersion( "1.0.0.0" )] [assembly: InternalsVisibleTo("Microsoft.Zelig.LlilumOSAbstraction")] [assembly: InternalsVisibleTo("Microsoft.Zelig.LlilumCMSIS-RTOS")] ================================================ FILE: Zelig/Zelig/RunTime/Zelig/LlilumCMSIS-RTOS/ReadMe.txt ================================================  ================================== CMSIS-RTOS API compliant library ================================== Please read about CMSIS-RTOS specification here: https://www.keil.com/pack/doc/CMSIS/RTOS/html/index.html Also please see documentaiton for CMSIS-RTOS API here: https://www.keil.com/pack/doc/CMSIS/RTOS/html/group___c_m_s_i_s___r_t_o_s.html A CMSIS-RTOS compliant port is a library and a header file that matches the following template: https://www.keil.com/pack/doc/CMSIS/RTOS/html/cmsis__os_8h.html. You can read here as to how use a CMSIS-RTOS implementation: https://www.keil.com/pack/doc/CMSIS/RTOS/html/_using_o_s.html LLILUM CMSIS-RTOS implementation is an assembly that exports static methods from the Microsoft.Zelig.LlilumOSAbstraction.API.CmsisRTOS class. The function names match the corresponding names in CMSIS-RTOS/ A C-wrapper could easily be provided to make it a formally compliant port. ================================================ FILE: Zelig/Zelig/RunTime/Zelig/LlilumOSAbstraction/API/IO/Adc.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // namespace Microsoft.Zelig.LlilumOSAbstraction.API.IO { using System.Runtime.InteropServices; public enum AdcDirection { Input = 0, Output, }; public static class Adc { [DllImport( "C" )] public static unsafe extern uint LLOS_ADC_Initialize(uint pinName, AdcDirection direction, AdcContext** channel); [DllImport( "C" )] public static unsafe extern void LLOS_ADC_Uninitialize(AdcContext* channel); [DllImport( "C" )] public static unsafe extern uint LLOS_ADC_ReadRaw(AdcContext* channel, int* value); [DllImport( "C" )] public static unsafe extern uint LLOS_ADC_WriteRaw(AdcContext* channel, int value); [DllImport( "C" )] public static unsafe extern uint LLOS_ADC_Read(AdcContext* channel, float* value); [DllImport( "C" )] public static unsafe extern uint LLOS_ADC_Write(AdcContext* channel, float value); [DllImport( "C" )] public static unsafe extern uint LLOS_ADC_GetPrecisionBits(AdcContext* channel, uint* pPrecisionBits); } public unsafe struct AdcContext { }; } ================================================ FILE: Zelig/Zelig/RunTime/Zelig/LlilumOSAbstraction/API/IO/Ethernet.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // namespace Microsoft.Zelig.LlilumOSAbstraction.API.IO { using System.Runtime.InteropServices; public static unsafe class EthernetInterface { [DllImport("C")] public static extern uint LLOS_ethernet_address_from_string(char* address, uint addrlen); [DllImport("C")] public static extern int LLOS_ethernet_dhcp_init(); [DllImport("C")] public static extern int LLOS_ethernet_staticIP_init(char* ip, uint ipLen, char* mask, uint maskLen, char* gateway, uint gatewayLen); [DllImport("C")] public static extern int LLOS_ethernet_connect(uint timeout); [DllImport("C")] public static extern int LLOS_ethernet_disconnect(); [DllImport("C")] public static extern int LLOS_ethernet_get_macAddress(char* address, uint bufferLen); [DllImport("C")] public static extern int LLOS_ethernet_get_IPv4Address(char* address, uint bufferLen); [DllImport("C")] public static extern int LLOS_ethernet_get_gatewayIPv4Address(char* address, uint bufferLen); [DllImport("C")] public static extern int LLOS_ethernet_get_networkIPv4Mask(char* mask, uint bufferLen); } } ================================================ FILE: Zelig/Zelig/RunTime/Zelig/LlilumOSAbstraction/API/IO/Gpio.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // namespace Microsoft.Zelig.LlilumOSAbstraction.API.IO { using Runtime; using System; using System.Runtime.InteropServices; public enum GpioPinResistor { Default = 0, PullNone, Pullup, Pulldown, OpenDrain, Repeater, }; public enum GpioPinEdge { None = 0, RisingEdge, FallingEdge, BothEdges, LevelLow, LevelHigh, } public enum GpioPinPolarity { Normal = 0, Inverted, } public enum GpioPinDirection { Input = 0, Output, } public unsafe delegate void LLOS_GPIO_InterruptCallback( GpioContext* pGpioCtx, UIntPtr callbackCtx, GpioPinEdge edge); public static class Gpio { [DllImport( "C" )] public static unsafe extern uint LLOS_GPIO_AllocatePin( int pinNumber, GpioContext** ppGpioCtx ); [DllImport( "C" )] public static unsafe extern void LLOS_GPIO_FreePin( GpioContext* pGpioCtx ); public static unsafe uint LLOS_GPIO_EnablePin( GpioContext* pin, GpioPinEdge edge, LLOS_GPIO_InterruptCallback callback, UIntPtr callbackCtx ) { UIntPtr callbackPtr = UIntPtr.Zero; if(callback != null) { DelegateImpl dlg = (DelegateImpl)(object)callback; callbackPtr = new UIntPtr( dlg.InnerGetCodePointer( ).Target.ToPointer( ) ); } return LLOS_GPIO_EnablePin( pin, edge, callbackPtr, callbackCtx ); } [DllImport( "C" )] private static unsafe extern uint LLOS_GPIO_EnablePin( GpioContext* pGpioCtx, GpioPinEdge edge, UIntPtr callback, UIntPtr callbackCtx ); [DllImport( "C" )] public static unsafe extern uint LLOS_GPIO_DisablePin( GpioContext* pGpioCtx ); [DllImport( "C" )] public static unsafe extern uint LLOS_GPIO_SetPolarity( GpioContext* pin, GpioPinPolarity polarity ); [DllImport( "C" )] public static unsafe extern uint LLOS_GPIO_SetMode( GpioContext* pin, GpioPinResistor resistor ); [DllImport( "C" )] public static unsafe extern uint LLOS_GPIO_SetDirection( GpioContext* pin, GpioPinDirection direction ); [DllImport( "C" )] public static unsafe extern uint LLOS_GPIO_SetDebounce( GpioContext* pin, ulong debounce_time ); [DllImport( "C" )] public static unsafe extern uint LLOS_GPIO_Write( GpioContext* pin, int value ); [DllImport( "C" )] public static unsafe extern int LLOS_GPIO_Read( GpioContext* pin ); } public unsafe struct GpioContext { }; } ================================================ FILE: Zelig/Zelig/RunTime/Zelig/LlilumOSAbstraction/API/IO/I2C.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // namespace Microsoft.Zelig.LlilumOSAbstraction.API.IO { using System.Runtime.InteropServices; public static class I2C { [DllImport( "C" )] public static unsafe extern uint LLOS_I2C_Initialize( int sdaPin, int sclPin, I2CContext** pChannel ); [DllImport( "C" )] public static unsafe extern void LLOS_I2C_Uninitialize( I2CContext* channel ); [DllImport( "C" )] public static unsafe extern uint LLOS_I2C_SetFrequency( I2CContext* channel, uint frequencyHz ); [DllImport( "C" )] public static unsafe extern uint LLOS_I2C_Enable( I2CContext* channel ); [DllImport( "C" )] public static unsafe extern uint LLOS_I2C_Disable( I2CContext* channel ); [DllImport( "C" )] public static unsafe extern uint LLOS_I2C_Write( I2CContext* channel, uint address, byte* pBuffer, int offset, int* pLength, uint stop ); [DllImport( "C" )] public static unsafe extern uint LLOS_I2C_Read( I2CContext* channel, uint address, byte* pBuffer, int offset, int* pLength, uint stop ); [DllImport( "C" )] public static unsafe extern uint LLOS_I2C_Reset( I2CContext* channel ); } public unsafe struct I2CContext { }; } ================================================ FILE: Zelig/Zelig/RunTime/Zelig/LlilumOSAbstraction/API/IO/Pwm.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // namespace Microsoft.Zelig.LlilumOSAbstraction.API.IO { using System.Runtime.InteropServices; public enum PwmPolarity { Normal = 0, Inverted, }; public enum PwmPrescaler { Div1 = 0, Div2, Div4, Div8, Div16, Div64, Div256, Div1024 }; public static class Pwm { [DllImport( "C" )] public static unsafe extern uint LLOS_PWM_Initialize(uint pinName, PwmContext** channel); [DllImport( "C" )] public static unsafe extern void LLOS_PWM_Uninitialize(PwmContext* channel); [DllImport( "C" )] public static unsafe extern uint LLOS_PWM_SetDutyCycle(PwmContext* channel, uint dutyCycleNumerator, uint dutyCycleDenominator); [DllImport( "C" )] public static unsafe extern uint LLOS_PWM_SetPeriod(PwmContext* channel, uint periodMicroSeconds); [DllImport( "C" )] public static unsafe extern uint LLOS_PWM_SetPulseWidth(PwmContext* channel, uint widthMicroSeconds); [DllImport( "C" )] public static unsafe extern uint LLOS_PWM_SetPolarity(PwmContext* channel, PwmPolarity polarity); [DllImport( "C" )] public static unsafe extern uint LLOS_PWM_SetPrescaler(PwmContext* channel, PwmPrescaler prescaler); [DllImport( "C" )] public static unsafe extern uint LLOS_PWM_Start(PwmContext* channel); [DllImport( "C" )] public static unsafe extern uint LLOS_PWM_Stop(PwmContext* channel); } public unsafe struct PwmContext { } } ================================================ FILE: Zelig/Zelig/RunTime/Zelig/LlilumOSAbstraction/API/IO/SerialPort.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // namespace Microsoft.Zelig.LlilumOSAbstraction.API.IO { using System; using System.Runtime.InteropServices; using Microsoft.Zelig.Runtime; public enum SerialPortParity : uint { None = 0, Odd, Even, Mark, Space, }; public enum SerialPortStopBits : uint { None = 0, One, Two, OnePointFive }; // // !!!WARNING!!! This structure MUST be identical to the C structure LLOS_SERIAL_Config in llos_serial.h // [StructLayout( LayoutKind.Sequential, Pack = 4 )] public struct SerialPortConfiguration { public uint BaudRate; public SerialPortParity Parity; public uint DataBits; public SerialPortStopBits StopBits; public uint SoftwareFlowControlValue; }; public enum SerialPortEvent { Rx = 0, Tx, }; public enum SerialPortIrq { IrqRx = 0, IrqTx, IrqBoth }; public unsafe delegate void SerialPortInterruptHandler(SerialPortContext* port, UIntPtr callbackCtx, SerialPortEvent serialEvent); public static class SerialPort { [DllImport( "C" )] public static unsafe extern uint LLOS_SERIAL_Open(int rxPin, int txPin, SerialPortConfiguration **ppConfiguration, SerialPortContext** pChannel); [DllImport( "C" )] public static unsafe extern void LLOS_SERIAL_Close(SerialPortContext* channel); [DllImport( "C" )] public static unsafe extern uint LLOS_SERIAL_Enable(SerialPortContext* channel, SerialPortIrq irq); [DllImport( "C" )] public static unsafe extern uint LLOS_SERIAL_Disable(SerialPortContext* channel, SerialPortIrq irq); [DllImport( "C" )] public static unsafe extern uint LLOS_SERIAL_SetFlowControl(SerialPortContext* channel, int rtsPin, int ctsPin); [DllImport( "C" )] public static unsafe extern uint LLOS_SERIAL_Configure(SerialPortContext* channel, SerialPortConfiguration* pConfiguration); [DllImport( "C" )] public static unsafe extern uint LLOS_SERIAL_Read(SerialPortContext* channel, byte* pBuffer, int offset, int* pLength); [DllImport( "C" )] public static unsafe extern uint LLOS_SERIAL_Write(SerialPortContext* channel, byte* pBuffer, int offset, int length); [DllImport( "C" )] public static unsafe extern uint LLOS_SERIAL_Flush(SerialPortContext* channel); [DllImport( "C" )] public static unsafe extern uint LLOS_SERIAL_Clear(SerialPortContext* channel); public static unsafe uint LLOS_SERIAL_SetCallback(SerialPortContext* channel, SerialPortInterruptHandler callback, UIntPtr callbackContext) { UIntPtr callbackPtr = UIntPtr.Zero; if(callback != null) { DelegateImpl dlg = (DelegateImpl)(object)callback; callbackPtr = new UIntPtr( dlg.InnerGetCodePointer( ).Target.ToPointer( ) ); } return LLOS_SERIAL_SetCallback( channel, callbackPtr, callbackContext ); } [DllImport( "C" )] private static unsafe extern uint LLOS_SERIAL_SetCallback(SerialPortContext* channel, UIntPtr callback, UIntPtr callbackContext); [DllImport( "C" )] public static unsafe extern uint LLOS_SERIAL_CanRead(SerialPortContext* channel, uint *pCanRead); [DllImport( "C" )] public static unsafe extern uint LLOS_SERIAL_CanWrite(SerialPortContext* channel, uint *pCanWrite); } public unsafe struct SerialPortContext { }; } ================================================ FILE: Zelig/Zelig/RunTime/Zelig/LlilumOSAbstraction/API/IO/Socket.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // namespace Microsoft.Zelig.LlilumOSAbstraction.API.IO { using System.Runtime.InteropServices; public static unsafe class SocketNative { [DllImport("C")] public static extern int LLOS_lwip_socket(int family, int type, int protocol); [DllImport("C")] public static extern int LLOS_lwip_bind(int socket, byte[] address); [DllImport("C")] public static extern int LLOS_lwip_connect(int socket, byte* address, bool fThrowOnWouldBlock); [DllImport("C")] public static extern int LLOS_lwip_send(int socket, byte* buf, int count, int flags, int timeout_ms); [DllImport("C")] public static extern int LLOS_lwip_recv(int socket, byte* buf, int count, int flags, int timeout_ms); [DllImport("C")] public static extern int LLOS_lwip_close(int socket); [DllImport("C")] public static extern int LLOS_lwip_listen(int socket, int backlog); [DllImport("C")] public static extern int LLOS_lwip_accept(int socket, byte* address, uint* addrlen); //Non standard non-blocking api [DllImport("C")] public static extern int LLOS_lwip_getaddrinfo(char* name, uint namelen, byte* canonicalName, uint canonicalNameBufferSize, byte* addresses, uint addressesBufferSize); [DllImport("C")] public static extern int LLOS_lwip_shutdown(int socket, int how); [DllImport("C")] public static extern int LLOS_lwip_sendto(int socket, byte* buf, int count, int flags, int timeout_ms, byte* address, uint tolen); [DllImport("C")] public static extern int LLOS_lwip_recvfrom(int socket, byte* buf, int count, int flags, int timeout_ms, byte* address, uint* fromlen); [DllImport("C")] public static extern int LLOS_lwip_getpeername(int socket, byte* address, uint* namelen); [DllImport("C")] public static extern int LLOS_lwip_getsockname(int socket, byte* address, uint* namelen); [DllImport("C")] public static extern int LLOS_lwip_getsockopt(int socket, int level, int optname, byte* optval, uint* optlen); [DllImport("C")] public static extern int LLOS_lwip_setsockopt(int socket, int level, int optname, byte* optval, uint optlen); [DllImport("C")] public static extern bool LLOS_lwip_poll(int socket, int mode, int microSeconds); [DllImport("C")] public static extern int LLOS_lwip_ioctl(int socket, uint cmd, uint* arg); } } ================================================ FILE: Zelig/Zelig/RunTime/Zelig/LlilumOSAbstraction/API/IO/Spi.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // namespace Microsoft.Zelig.LlilumOSAbstraction.API.IO { using Runtime; using System; using System.Runtime.InteropServices; // // !!!WARNING!!! This structure MUST be identical to the C structure LLOS_SPI_ControllerConfig in llos_spi.h // Also note that the boolean fields (loopbackMode, MSBTransferMode, etc.) are defined as uint values. The // bool type gets reduced to 1 byte values which would not map to the underlying C/C++ structure where boolean // values are 32 bits. // [StructLayout( LayoutKind.Sequential, Pack = 4 )] public struct SpiConfig { public uint ChipSelect; public uint LoopbackMode; public uint MSBTransferMode; public uint ActiveLow; public uint InversePolarity; public uint ClockIdleLevel; public uint ClockSamplingEdge; public uint Master; public uint PhaseMode; public uint DataWidth; public uint ClockRateHz; public uint ChipSelectSetupCycles; public uint ChipSelectHoldCycles; public uint BusyPin; }; public enum SpiAction { SpiWrite = 0, SpiRead, SpiTransceive, SpiError, }; public unsafe delegate void LLOS_SPI_Callback(SpiContext* channel, UIntPtr callbackCtx, SpiAction edge); public static class Spi { [DllImport( "C" )] public static unsafe extern uint LLOS_SPI_Initialize( uint mosi, uint miso, uint sclk, uint chipSelect, SpiContext** channel, SpiConfig** configuration ); [DllImport( "C" )] public static unsafe extern void LLOS_SPI_Uninitialize( SpiContext* channel ); [DllImport( "C" )] public static unsafe extern uint LLOS_SPI_Configure( SpiContext* channel, SpiConfig* config ); public static unsafe uint LLOS_SPI_SetCallback( SpiContext* channel, LLOS_SPI_Callback callback, UIntPtr context ) { UIntPtr callback_ptr = UIntPtr.Zero; if(callback != null) { DelegateImpl dlg = (DelegateImpl)(object)callback; callback_ptr = new UIntPtr( dlg.InnerGetCodePointer( ).Target.ToPointer( ) ); } return LLOS_SPI_SetCallback( channel, callback_ptr, context ); } [DllImport( "C" )] private static unsafe extern uint LLOS_SPI_SetCallback( SpiContext* channel, UIntPtr callback, UIntPtr context ); [DllImport( "C" )] public static unsafe extern uint LLOS_SPI_SetFrequency( SpiContext* channel, uint frequencyHz ); [DllImport( "C" )] public static unsafe extern uint LLOS_SPI_Transfer( SpiContext* channel, byte* txBuffer, int txOffset, int txCount, byte* rxBuffer, int rxOffset, int rxCount, int rxStartOffset ); [DllImport( "C" )] public static unsafe extern uint LLOS_SPI_Write( SpiContext* channel, byte* txBuffer, int txOffset, int txCount ); [DllImport( "C" )] public static unsafe extern uint LLOS_SPI_Read( SpiContext* channel, byte* rxBuffer, int rxOffset, int rxCount, int rxStartOffset ); [DllImport( "C" )] public static unsafe extern uint LLOS_SPI_IsBusy( SpiContext* channel, uint* isBusy ); [DllImport( "C" )] public static unsafe extern uint LLOS_SPI_Suspend( SpiContext* channel ); [DllImport( "C" )] public static unsafe extern uint LLOS_SPI_Resume( SpiContext* channel ); } public unsafe struct SpiContext { } } ================================================ FILE: Zelig/Zelig/RunTime/Zelig/LlilumOSAbstraction/API/RuntimeMemory.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // namespace Microsoft.Zelig.LlilumOSAbstraction.API { using System.Runtime.InteropServices; public static class RuntimeMemory { [DllImport( "C" )] public static unsafe extern uint LLOS_MEMORY_GetMaxHeapSize( out uint pMaxHeapSize ); [DllImport( "C" )] public static unsafe extern uint LLOS_MEMORY_GetDefaultManagedStackSize( ); [DllImport( "C" )] public static unsafe extern uint LLOS_MEMORY_Allocate( uint size, byte fill, out void* pAllocation ); [DllImport( "C" )] public static unsafe extern uint LLOS_MEMORY_Reallocate( void* allocation, out void* newAllocation ); [DllImport( "C" )] public static unsafe extern void LLOS_MEMORY_Free( void* address ); } } ================================================ FILE: Zelig/Zelig/RunTime/Zelig/LlilumOSAbstraction/HAL/Clock.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // namespace Microsoft.Zelig.LlilumOSAbstraction.HAL { using System; using System.Runtime.InteropServices; public static class Clock { [DllImport( "C" )] public static unsafe extern ulong LLOS_CLOCK_GetClockTicks( ); [DllImport( "C" )] public static unsafe extern ulong LLOS_CLOCK_GetClockFrequency( ); [DllImport( "C" )] public static unsafe extern ulong LLOS_CLOCK_GetPerformanceCounter( ); [DllImport( "C" )] public static unsafe extern ulong LLOS_CLOCK_GetPerformanceCounterFrequency( ); [DllImport( "C" )] public static unsafe extern uint LLOS_CLOCK_DelayCycles(uint cycles); [DllImport( "C" )] public static unsafe extern uint LLOS_CLOCK_Delay(uint microSeconds); } } ================================================ FILE: Zelig/Zelig/RunTime/Zelig/LlilumOSAbstraction/HAL/Mutex.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // namespace Microsoft.Zelig.LlilumOSAbstraction.HAL { using System; using System.Runtime.InteropServices; public static class Mutex { [DllImport( "C" )] public static unsafe extern uint LLOS_MUTEX_CreateGlobalLock( ref UIntPtr mutexHandle ); [DllImport( "C" )] public static unsafe extern uint LLOS_MUTEX_Create( UIntPtr attributes, UIntPtr name, ref UIntPtr mutexHandle ); [DllImport( "C" )] public static unsafe extern uint LLOS_MUTEX_Acquire( UIntPtr mutexHandle, int timeout ); [DllImport( "C" )] public static unsafe extern uint LLOS_MUTEX_Release( UIntPtr mutexHandle ); [DllImport( "C" )] public static unsafe extern uint LLOS_MUTEX_CurrentThreadHasLock( UIntPtr mutexHandle ); [DllImport( "C" )] public static unsafe extern uint LLOS_MUTEX_Delete( UIntPtr mutexHandle ); } } ================================================ FILE: Zelig/Zelig/RunTime/Zelig/LlilumOSAbstraction/HAL/Thread.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // namespace Microsoft.Zelig.LlilumOSAbstraction.HAL { using Runtime; using System; using System.Runtime.InteropServices; public static class Thread { public enum ThreadPriority { Lowest = 0, BelowNormal, Normal, AboveNormal, Highest, } public static unsafe uint LLOS_THREAD_CreateThread(Delegate dlgEntry, ThreadImpl thread, ref UIntPtr threadHandle ) { UIntPtr threadEntry; UIntPtr threadParam; UIntPtr managedThread; DelegateImpl dlg = (DelegateImpl)(object)dlgEntry; threadEntry = new UIntPtr( dlg.InnerGetCodePointer( ).Target.ToPointer( ) ); threadParam = ( (ObjectImpl)dlgEntry.Target ).ToPointer( ); managedThread = ( (ObjectImpl)(object)thread ).ToPointer( ); return LLOS_THREAD_CreateThread( threadEntry, threadParam, managedThread, 8*1024, ref threadHandle ); } //--// [DllImport( "C" )] private static unsafe extern uint LLOS_THREAD_CreateThread( UIntPtr threadEntry, UIntPtr threadParameter, UIntPtr managedThread, uint stackSize, ref UIntPtr threadHandle ); [DllImport( "C" )] public static unsafe extern uint LLOS_THREAD_DeleteThread( UIntPtr threadHandle ); [DllImport( "C" )] public static unsafe extern uint LLOS_THREAD_Start( UIntPtr threadHandle ); [DllImport( "C" )] public static unsafe extern uint LLOS_THREAD_Yield( ); [DllImport( "C" )] public static unsafe extern uint LLOS_THREAD_Signal(UIntPtr threadHandle); [DllImport( "C" )] public static unsafe extern uint LLOS_THREAD_Wait(UIntPtr threadHandle, int timeoutMs); [DllImport( "C" )] public static unsafe extern void LLOS_THREAD_Sleep( int timeoutMs ); [DllImport( "C" )] public static unsafe extern uint LLOS_THREAD_GetCurrentThread( ref UIntPtr threadHandle ); [DllImport( "C" )] public static unsafe extern uint LLOS_THREAD_SetPriority( UIntPtr threadHandle, ThreadPriority threadPriority ); [DllImport( "C" )] public static unsafe extern uint LLOS_THREAD_GetPriority( UIntPtr threadHandle, out ThreadPriority threadPriority ); [DllImport( "C" )] public static unsafe extern uint LLOS_THREAD_GetMainStackAddress( ); [DllImport( "C" )] public static unsafe extern uint LLOS_THREAD_GetMainStackSize( ); } } ================================================ FILE: Zelig/Zelig/RunTime/Zelig/LlilumOSAbstraction/HAL/Timer.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // namespace Microsoft.Zelig.LlilumOSAbstraction.HAL { using Runtime; using System; using System.Runtime.InteropServices; public unsafe delegate void TimerCallback( UIntPtr context, ulong time ); public static class Timer { public static unsafe uint LLOS_SYSTEM_TIMER_AllocateTimer( TimerCallback callback, UIntPtr callbackContext, ulong microsecondsFromNow, TimerContext** pTimer ) { UIntPtr callbackPtr = UIntPtr.Zero; UIntPtr callbackCtx = UIntPtr.Zero; if(callback != null) { DelegateImpl dlg = (DelegateImpl)(object)callback; callbackPtr = new UIntPtr( dlg.InnerGetCodePointer( ).Target.ToPointer( ) ); callbackCtx = ( (ObjectImpl)callback.Target ).ToPointer( ); } return LLOS_SYSTEM_TIMER_AllocateTimer( callbackPtr, callbackContext != UIntPtr.Zero ? callbackContext : callbackCtx, microsecondsFromNow, pTimer ); } [DllImport( "C" )] public static unsafe extern ulong LLOS_SYSTEM_TIMER_GetTicks( TimerContext* pTimer ); [DllImport( "C" )] public static unsafe extern ulong LLOS_SYSTEM_TIMER_GetTimerFrequency( TimerContext* pTimer ); [DllImport( "C" )] private static unsafe extern uint LLOS_SYSTEM_TIMER_AllocateTimer( UIntPtr callback, UIntPtr callbackContext, ulong microsecondsFromNow, TimerContext** pTimer ); [DllImport( "C" )] public static unsafe extern void LLOS_SYSTEM_TIMER_FreeTimer( TimerContext* pTimer ); [DllImport( "C" )] public static unsafe extern uint LLOS_SYSTEM_TIMER_ScheduleTimer( TimerContext* pTimer, ulong microsecondsFromNow ); } public unsafe struct TimerContext { }; } ================================================ FILE: Zelig/Zelig/RunTime/Zelig/LlilumOSAbstraction/LlilumErrors.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // namespace Microsoft.Zelig.LlilumOSAbstraction { using System; using RT = Microsoft.Zelig.Runtime; public static class LlilumErrors { public const uint S_OK = 0; public const uint S_FALSE = 1; public const uint E_NOTIMPL = 0xCA000000; public const uint E_IO = 0xCF000000; public const uint E_INVALID_OPERATION = 0xD6000000; public const uint E_OUT_OF_MEMORY = 0xFA000000; public const uint E_NOT_SUPPORTED = 0xF7000000; public const uint E_INVALID_PARAMETER = 0xFD000000; public const uint E_TIMEOUT = 0xFE000000; public const uint E_FAIL = 0xFF000000; public static bool Succeeded( uint result ) { return ( result & 0x80000000UL ) == 0; } public static bool Failed( uint result ) { return ( result & 0x80000000UL ) != 0; } public static void ThrowOnError(uint result, bool ignoreNotSupportedOrImplemented) { if( Failed( result ) ) { switch( result ) { case E_NOTIMPL: if(!ignoreNotSupportedOrImplemented) { throw new NotImplementedException( ); } break; case E_INVALID_OPERATION: throw new InvalidOperationException( ); case E_OUT_OF_MEMORY: throw new OutOfMemoryException( ); case E_NOT_SUPPORTED: if(!ignoreNotSupportedOrImplemented) { throw new NotSupportedException( ); } break; case E_INVALID_PARAMETER: throw new ArgumentException( ); case E_TIMEOUT: throw new TimeoutException( ); case E_IO: case E_FAIL: default: throw new Exception( ); } } } [RT.ExportedMethod] public static void LLOS_Die() { RT.BugCheck.Raise( Runtime.BugCheck.StopCode.Fault_Unknown ); } } } ================================================ FILE: Zelig/Zelig/RunTime/Zelig/LlilumOSAbstraction/LlilumOSAbstraction.csproj ================================================  Debug AnyCPU 9.0.21022 2.0 {20DC2CF5-8EED-4231-9743-6BAB96BE465C} Library Properties Microsoft.Zelig.LlilumOSAbstraction Microsoft.Zelig.LlilumOSAbstraction $(LlilumBuildRoot)\Host\obj\$(MSBuildProjectName)\ v4.5 true full false $(LlilumBuildRoot)\Host\bin\$(Configuration)\ DEBUG;TRACE prompt 4 true true true AllRules.ruleset AnyCPU false pdbonly true $(LlilumBuildRoot)\Host\bin\$(Configuration)\ TRACE prompt 4 true true true AllRules.ruleset AnyCPU false true full false $(LlilumBuildRoot)\Host\bin\$(Configuration)\ TRACE;DEBUG AnyCPU true true true false {186F31A3-EF89-4A25-B2D5-20060509AA01} Kernel False {186F31A3-EF89-4A25-B2D5-20060501AA01} mscorlib False {186F31A3-EF89-4A25-B2D5-20070702AA01} system False {186F31A3-EF89-4A25-B2D5-20060509AA01} Kernel False {186F31A3-EF89-4A25-B2D5-20060720AA01} TypeSystem False {186f31a3-ef89-4a25-b2d5-20061218aa01} Common 3.5 Native\IO\llos_analog.h Native\IO\llos_gpio.h Native\IO\llos_i2c.h Native\IO\llos_pwm.h Native\IO\llos_serial.h Native\IO\llos_spi.h Native\API\llos_memory.h Native\Debug\llos_debug.h Native\HAL\llos_clock.h Native\HAL\llos_mutex.h Native\HAL\llos_system_timer.h Native\HAL\llos_thread.h Native\llos_error.h Native\llos_platform.h Native\llos_types.h ================================================ FILE: Zelig/Zelig/RunTime/Zelig/LlilumOSAbstraction/Native/API/RuntimeMemory.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // namespace Microsoft.Zelig.LlilumOSAbstraction.API { using System.Runtime.InteropServices; public static class RuntimeMemory { [DllImport( "C" )] public static unsafe extern uint LLOS_MEMORY_GetMaxHeapSize( out uint pMaxHeapSize ); [DllImport( "C" )] public static unsafe extern uint LLOS_MEMORY_Allocate( uint size, byte fill, out void* pAllocation ); [DllImport( "C" )] public static unsafe extern uint LLOS_MEMORY_Reallocate( void* allocation, out void* newAllocation ); [DllImport( "C" )] public static unsafe extern void LLOS_MEMORY_Free( void* address ); } } ================================================ FILE: Zelig/Zelig/RunTime/Zelig/TypeSystem/AssemblyRepresentation.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // namespace Microsoft.Zelig.Runtime.TypeSystem { using System; using System.Collections.Generic; public sealed class AssemblyRepresentation { public struct VersionData { // // This is just a copy of Microsoft.Zelig.MetaData.AssemblyFlags, needed to break the dependency of TypeSystem from MetaData. // public enum AssemblyFlags { PublicKey = 0x0001, // The assembly ref holds the full (unhashed) public key. CompatibilityMask = 0x0070, SideBySideCompatible = 0x0000, // The assembly is side by side compatible. NonSideBySideAppDomain = 0x0010, // The assembly cannot execute with other versions if they are executing in the same application domain. NonSideBySideProcess = 0x0020, // The assembly cannot execute with other versions if they are executing in the same process. NonSideBySideMachine = 0x0030, // The assembly cannot execute with other versions if they are executing on the same machine. EnableJITcompileTracking = 0x8000, // From "DebuggableAttribute". DisableJITcompileOptimizer = 0x4000 // From "DebuggableAttribute". } // // State // public short MajorVersion; public short MinorVersion; public short BuildNumber; public short RevisionNumber; public AssemblyFlags Flags; public byte[] PublicKey; // // Helper Methods // public bool IsCompatible( ref VersionData ver , bool exact ) { // BUGBUG: This ignores the strong name of an assembly. if(this.MajorVersion < ver.MajorVersion ) return false; if(this.MajorVersion > ver.MajorVersion && !exact) return true; if(this.MinorVersion < ver.MinorVersion ) return false; if(this.MinorVersion > ver.MinorVersion && !exact) return true; if(this.BuildNumber < ver.BuildNumber ) return false; if(this.BuildNumber > ver.BuildNumber && !exact) return true; if(this.RevisionNumber < ver.RevisionNumber ) return false; if(this.RevisionNumber > ver.RevisionNumber && !exact) return true; return true; } public void ApplyTransformation( TransformationContext context ) { context.Transform( ref this.MajorVersion ); context.Transform( ref this.MinorVersion ); context.Transform( ref this.BuildNumber ); context.Transform( ref this.RevisionNumber ); context.Transform( ref this.Flags ); context.Transform( ref this.PublicKey ); } // // Access Methods // // // Debug Methods // public override String ToString() { System.Text.StringBuilder sb = new System.Text.StringBuilder( "MetaDataVersion(" ); sb.Append( MajorVersion ); sb.Append( "," ); sb.Append( MinorVersion ); sb.Append( "," ); sb.Append( BuildNumber ); sb.Append( "," ); sb.Append( RevisionNumber ); sb.Append( "," ); sb.Append( Flags ); sb.Append( ",[" ); // BUGBUG: ArrayReader.AppendAsString( sb, PublicKey ); sb.Append( "])" ); return sb.ToString(); } } // // State // private string m_name; private VersionData m_version; // // Constructor Methods // public AssemblyRepresentation( string name , ref VersionData version ) { CHECKS.ASSERT( name != null, "Cannot create an AssemblyRepresentation without a name" ); m_name = name; m_version = version; } // // MetaDataEquality Methods // public override bool Equals( object obj ) { if(obj is AssemblyRepresentation) { AssemblyRepresentation other = (AssemblyRepresentation)obj; if(m_name == other.m_name) { if(m_version.IsCompatible( ref other.m_version, true )) { return true; } } } return false; } public override int GetHashCode() { return m_name.GetHashCode() ^ (int)m_version.MajorVersion ^ (int)m_version.MinorVersion ^ (int)m_version.BuildNumber ^ (int)m_version.RevisionNumber; } //--// // // Helper Methods // public void ApplyTransformation( TransformationContext context ) { context.Push( this ); context.Transform( ref m_name ); context.Transform( ref m_version ); context.Pop(); } //--// // // Access Methods // public VersionData Version { get { return m_version; } } public String Name { get { return m_name; } } } } ================================================ FILE: Zelig/Zelig/RunTime/Zelig/TypeSystem/BaseRepresentation.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // namespace Microsoft.Zelig.Runtime.TypeSystem { using System; using System.Collections.Generic; using System.Threading; [DisableReferenceCounting] public abstract class BaseRepresentation { // // State // protected static int s_identity; private int m_identity; //--// protected CustomAttributeAssociationRepresentation[] m_customAttributes; //--// // // Constructor Methods // protected BaseRepresentation() { m_identity = Interlocked.Increment( ref s_identity ); m_customAttributes = CustomAttributeAssociationRepresentation.SharedEmptyArray; } // // MetaDataEquality Methods // public abstract bool EqualsThroughEquivalence( object obj , EquivalenceSet set ); public static bool EqualsThroughEquivalence( BaseRepresentation left , BaseRepresentation right , EquivalenceSet set ) { if(Object.ReferenceEquals( left, right )) { return true; } if(left != null && right != null) { return left.EqualsThroughEquivalence( right, set ); } return false; } public static bool ArrayEqualsThroughEquivalence( T[] s , T[] d , EquivalenceSet set ) where T : BaseRepresentation { return ArrayEqualsThroughEquivalence( s, d, 0, -1, set ); } public static bool ArrayEqualsThroughEquivalence( T[] s , T[] d , int offset , int count , EquivalenceSet set ) where T : BaseRepresentation { int sLen = s != null ? s.Length : 0; int dLen = d != null ? d.Length : 0; if(count < 0) { if(sLen != dLen) { return false; } count = sLen - offset; } else { if(sLen < count + offset || dLen < count + offset ) { return false; } } while(count > 0) { if(EqualsThroughEquivalence( s[offset], d[offset], set ) == false) { return false; } offset++; count--; } return true; } //--// // // Helper Methods // public virtual void ApplyTransformation( TransformationContext context ) { context.Push( this ); context.Transform( ref m_customAttributes ); context.Pop(); } //--// public void AddCustomAttribute( CustomAttributeAssociationRepresentation cca ) { m_customAttributes = ArrayUtility.AddUniqueToNotNullArray( m_customAttributes, cca ); } public void CopyCustomAttribute( CustomAttributeAssociationRepresentation caa ) { AddCustomAttribute( new CustomAttributeAssociationRepresentation( caa.CustomAttribute, this, caa.ParameterIndex ) ); } public void RemoveCustomAttribute( CustomAttributeAssociationRepresentation cca ) { m_customAttributes = ArrayUtility.RemoveUniqueFromNotNullArray( m_customAttributes, cca ); } public void RemoveCustomAttribute( CustomAttributeRepresentation ca ) { foreach(CustomAttributeAssociationRepresentation caa in m_customAttributes) { if(caa.CustomAttribute == ca) { RemoveCustomAttribute( caa ); } } } public bool HasCustomAttribute( TypeRepresentation target ) { return FindCustomAttribute( target, -1 ) != null; } public CustomAttributeRepresentation FindCustomAttribute( TypeRepresentation target ) { return FindCustomAttribute( target, -1 ); } public List FindCustomAttributes( TypeRepresentation target ) { var lst = new List(); FindCustomAttributes( target, lst ); return lst; } public CustomAttributeRepresentation FindCustomAttribute( TypeRepresentation target , int index ) { return FindCustomAttribute( target, -1, index ); } public virtual void EnumerateCustomAttributes( CustomAttributeAssociationEnumerationCallback callback ) { foreach(CustomAttributeAssociationRepresentation caa in m_customAttributes) { callback( caa ); } } //--// protected CustomAttributeRepresentation FindCustomAttribute( TypeRepresentation target , int paramIndex , int index ) { int pos = index >= 0 ? 0 : index; // So we don't have the double check in the loop. foreach(CustomAttributeAssociationRepresentation caa in m_customAttributes) { if(caa.CustomAttribute.Constructor.OwnerType == target && caa.ParameterIndex == paramIndex ) { if(index == pos) { return caa.CustomAttribute; } pos++; } } return null; } protected void FindCustomAttributes( TypeRepresentation target, List lst ) { foreach(CustomAttributeAssociationRepresentation caa in m_customAttributes) { if(caa.CustomAttribute.Constructor.OwnerType == target) { lst.Add( caa.CustomAttribute ); } } } //--// internal virtual void ProhibitUse( TypeSystem.Reachability reachability , bool fApply ) { reachability.ExpandProhibition( this ); foreach(CustomAttributeAssociationRepresentation caa in m_customAttributes) { reachability.ExpandProhibition( caa ); } } internal virtual void Reduce( TypeSystem.Reachability reachability , bool fApply ) { for(int i = m_customAttributes.Length; --i >= 0; ) { CustomAttributeAssociationRepresentation caa = m_customAttributes[i]; CHECKS.ASSERT( reachability.Contains( caa.Target ) == true, "{0} cannot be reachable since its owner is not in the Reachability set", caa ); if(reachability.Contains( caa.CustomAttribute.Constructor ) == false) { CHECKS.ASSERT( reachability.Contains( caa ) == false, "{0} cannot belong to both the Reachability and the Prohibition set", caa ); CHECKS.ASSERT( reachability.Contains( caa.CustomAttribute ) == false, "{0} cannot belong to both the Reachability and the Prohibition set", caa.CustomAttribute ); reachability.ExpandProhibition( caa ); reachability.ExpandProhibition( caa.CustomAttribute ); if(fApply) { if(m_customAttributes.Length == 1) { m_customAttributes = CustomAttributeAssociationRepresentation.SharedEmptyArray; return; } m_customAttributes = ArrayUtility.RemoveAtPositionFromNotNullArray( m_customAttributes, i ); } } } } //--// // // Access Methods // public int Identity { get { return m_identity; } } public CustomAttributeAssociationRepresentation[] CustomAttributes { get { return m_customAttributes; } } //--// // // Debug Methods // } } ================================================ FILE: Zelig/Zelig/RunTime/Zelig/TypeSystem/CodeMap.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // namespace Microsoft.Zelig.Runtime.TypeSystem { using System; using System.Collections.Generic; using TS = Microsoft.Zelig.Runtime.TypeSystem; [TS.AllowCompileTimeIntrospection] public class CodeMap { [Flags] [TS.AllowCompileTimeIntrospection] public enum Flags : uint { NormalCode = 0x00000001, EntryPoint = 0x00000002, ExceptionHandler = 0x00000004, InterruptHandler = 0x00000008, ColdSection = 0x00000010, BottomOfCallStack = 0x00000020, HasStackAdjustment = 0x10000000, HasFpStatusRegisterSave = 0x20000000, HasFpRegisterSave = 0x40000000, HasIntRegisterSave = 0x80000000, } [Flags] [TS.AllowCompileTimeIntrospection] public enum EncodedStackWalk : byte { RegisterMask = 0x0F, NotARegister = 0x0F, // Since PC is 15, and there's no need to track PC changes. StackOffsetMask = 0x1F, // Offset in WORDs. StackOffsetMax = 0x1D, // Offset in WORDs. StackOffset8BitExtender = 0x1E, // Next Pointer Tracking is a full 8bit stack offset. StackOffset16BitExtender = 0x1F, // Next Pointer Tracking is a full 16bit stack offset. ModeMask = 0x1F, TrackingHeapPointers = 0x00, // This is the default. TrackingInternalPointers = 0x01, TrackingPotentialPointers = 0x02, SkipMask = 0x1F, // How many opcodes to skip. SkipMax = 0x1F, EffectMask = 0xE0, EnterRegisterSet = 0x00, LeaveRegisterSet = 0x20, EnterStack = 0x40, LeaveStack = 0x60, SetMode = 0x80, EffectReserved2 = 0xA0, SkipToOpcode = 0xE0, } [TS.AllowCompileTimeIntrospection] public struct Range { public static readonly Range[] SharedEmptyArray = new Range[0]; //--// // // State // public Flags Flags; public UIntPtr Start; public UIntPtr End; public EncodedStackWalk[] StackWalk; // // Equality Methods // public bool SameContents( ref Range other ) { if(this.Flags == other.Flags && this.Start == other.Start && this.End == other.End ) { return EncodedStackWalkArrayEquals( this.StackWalk, other.StackWalk ); } return false; } // // Helper Methods // public bool Contains( UIntPtr address ) { return AddressMath.IsInRange( address, this.Start, this.End ); } public void Decode( CodeMapDecoderCallback callback ) { if(this.StackWalk != null) { UIntPtr address = this.Start; CodeMapDecoderCallback.PointerKind kind = CodeMapDecoderCallback.PointerKind.Heap; // This is the default. for(int pos = 0; pos < this.StackWalk.Length; ) { EncodedStackWalk val = this.StackWalk[pos++]; EncodedStackWalk effectVal = val & EncodedStackWalk.EffectMask; switch(effectVal) { case EncodedStackWalk.EnterRegisterSet: if(callback.RegisterEnter( address, (uint)(val & EncodedStackWalk.RegisterMask), kind ) == false) { return; } break; case EncodedStackWalk.LeaveRegisterSet: if(callback.RegisterLeave( address, (uint)(val & EncodedStackWalk.RegisterMask) ) == false) { return; } break; case EncodedStackWalk.EnterStack: case EncodedStackWalk.LeaveStack: { uint offset = (uint)(val & EncodedStackWalk.StackOffsetMask); switch(offset) { case (uint)EncodedStackWalk.StackOffset8BitExtender: offset = (uint)this.StackWalk[pos++]; break; case (uint)EncodedStackWalk.StackOffset16BitExtender: offset = (uint)this.StackWalk[pos++]; offset |= (uint)this.StackWalk[pos++] << 8; break; } if(effectVal == EncodedStackWalk.EnterStack) { if(callback.StackEnter( address, offset, kind ) == false) { return; } } else { if(callback.StackLeave( address, offset ) == false) { return; } } } break; case EncodedStackWalk.SetMode: switch(val & EncodedStackWalk.ModeMask) { case EncodedStackWalk.TrackingHeapPointers: kind = CodeMapDecoderCallback.PointerKind.Heap; break; case EncodedStackWalk.TrackingInternalPointers: kind = CodeMapDecoderCallback.PointerKind.Internal; break; case EncodedStackWalk.TrackingPotentialPointers: kind = CodeMapDecoderCallback.PointerKind.Potential; break; } break; case EncodedStackWalk.SkipToOpcode: address = AddressMath.Increment( address, (uint)(val & EncodedStackWalk.SkipMask) * sizeof(uint) ); break; } } } } public static bool EncodedStackWalkArrayEquals( EncodedStackWalk[] s , EncodedStackWalk[] d ) { int sLen = s != null ? s.Length : 0; int dLen = d != null ? d.Length : 0; if(sLen == dLen) { for(int i = 0; i < sLen; i++) { if(s[i] != d[i]) { return false; } } return true; } return false; } // // Debug Methods // public override string ToString() { System.Text.StringBuilder sb = new System.Text.StringBuilder(); sb.AppendFormat( "Range[0x{0:X8}-0x{1:X8} {2} {3} Entries]", this.Start.ToUInt32(), this.End.ToUInt32(), this.Flags, this.StackWalk != null ? this.StackWalk.Length : 0 ); if(this.StackWalk != null) { uint address = this.Start.ToUInt32(); for(int pos = 0; pos < this.StackWalk.Length; ) { EncodedStackWalk val = this.StackWalk[pos++]; EncodedStackWalk effectVal = val & EncodedStackWalk.EffectMask; sb.Append( Environment.NewLine ); switch(effectVal) { case EncodedStackWalk.EnterRegisterSet: sb.AppendFormat( "Enter Reg{0}", (uint)(val & EncodedStackWalk.RegisterMask) ); break; case EncodedStackWalk.LeaveRegisterSet: sb.AppendFormat( "Leave Reg{0}", (uint)(val & EncodedStackWalk.RegisterMask) ); break; case EncodedStackWalk.EnterStack: case EncodedStackWalk.LeaveStack: { uint offset = (uint)(val & EncodedStackWalk.StackOffsetMask); switch(offset) { case (uint)EncodedStackWalk.StackOffset8BitExtender: offset = (uint)this.StackWalk[pos++]; break; case (uint)EncodedStackWalk.StackOffset16BitExtender: offset = (uint)this.StackWalk[pos++]; offset |= (uint)this.StackWalk[pos++] << 8; break; } if(effectVal == EncodedStackWalk.EnterStack) { sb.AppendFormat( "Enter Stack{0}", offset ); } else { sb.AppendFormat( "Leave Stack{0}", offset ); } } break; case EncodedStackWalk.SetMode: switch(val & EncodedStackWalk.ModeMask) { case EncodedStackWalk.TrackingHeapPointers: sb.Append( "Switch to Tracking Heap Pointers" ); break; case EncodedStackWalk.TrackingInternalPointers: sb.Append( "Switch to Tracking Internal Pointers" ); break; case EncodedStackWalk.TrackingPotentialPointers: sb.Append( "Switch to Tracking Potential Pointers" ); break; } break; case EncodedStackWalk.SkipToOpcode: address += (uint)(val & EncodedStackWalk.SkipMask) * sizeof(uint); sb.AppendFormat( "Skip to 0x{0:X8}", address ); break; } } } return sb.ToString(); } } // // All the CodeMap instances are put in an address-sorted array, adding an extra entry with no CodeMap to act as a sentinel. // This array will be used to resolve an address to a piece of code. // A CodeMap instance can appear more than once, if it's been split into multiple chunks. // [TS.AllowCompileTimeIntrospection] public struct ReverseIndex { // // State // public UIntPtr Address; public CodeMap Code; // // Equality Methods // public static bool SameArrayContents( ReverseIndex[] left , ReverseIndex[] right ) { int leftLen = left != null ? left .Length : 0; int rightLen = right != null ? right.Length : 0; if(leftLen == rightLen) { for(int i = 0; i < leftLen; i++) { if(left[i].SameContents( ref right[i] ) == false) { return false; } } return true; } return false; } public bool SameContents( ref ReverseIndex other ) { if(this.Address == other.Address) { return CodeMap.SameContents( this.Code, other.Code ); } return false; } } //--// // // State // [WellKnownField( "CodeMap_LookupAddress" )] public static ReverseIndex[] LookupAddress; [WellKnownField( "CodeMap_Target" )] public MethodRepresentation Target; [WellKnownField( "CodeMap_Ranges" )] public Range[] Ranges; [WellKnownField( "CodeMap_ExceptionMap" )] public ExceptionMap ExceptionMap; // // Equality Methods // public static bool SameContents( CodeMap left , CodeMap right ) { if(Object.ReferenceEquals( left, right )) { return true; } if(left != null && right != null) { if(Object.ReferenceEquals( left.Target, right.Target )) { if(ExceptionMap.SameContents( left.ExceptionMap, right.ExceptionMap )) { Range[] leftRanges = left .Ranges; Range[] rightRanges = right.Ranges; int leftLen = leftRanges != null ? leftRanges .Length : 0; int rightLen = rightRanges != null ? rightRanges.Length : 0; if(leftLen == rightLen) { for(int i = 0; i < leftLen; i++) { if(leftRanges[i].SameContents( ref rightRanges[i] ) == false) { return false; } } return true; } } } } return false; } public bool SameContents( CodeMap other ) { if(Object.ReferenceEquals( this.Target, other.Target )) { if(ExceptionMap.SameContents( this.ExceptionMap, other.ExceptionMap )) { Range[] thisRanges = this .Ranges; Range[] rightRanges = other.Ranges; int thisLen = thisRanges != null ? thisRanges .Length : 0; int rightLen = rightRanges != null ? rightRanges.Length : 0; if(thisLen == rightLen) { for(int i = 0; i < thisLen; i++) { if(thisRanges[i].SameContents( ref rightRanges[i] ) == false) { return false; } } return true; } } } return false; } // // Helper Methods // [NoInline] public int FindRange( UIntPtr address ) { for(int i = 0; i < this.Ranges.Length; i++) { if(this.Ranges[i].Contains( address )) { return i; } } return -1; } [NoInline] public static CodeMap ResolveAddressToCodeMap( UIntPtr address ) { return ResolveAddressToCodeMap( address, CodeMap.LookupAddress ); } [NoInline] [DisableBoundsChecks] public static CodeMap ResolveAddressToCodeMap( UIntPtr address , CodeMap.ReverseIndex[] table ) { if(table != null) { int low = 0; int high = table.Length - 2; // The last item is sentinel, so we don't need to check "mid+1 < length". while(low <= high) { int mid = (high + low) / 2; if(AddressMath.IsLessThan( address, table[mid].Address )) { high = mid - 1; } else if(AddressMath.IsGreaterThanOrEqual( address, table[mid+1].Address )) { low = mid + 1; } else { return table[mid].Code; } } } return null; } } } ================================================ FILE: Zelig/Zelig/RunTime/Zelig/TypeSystem/CodeMapDecoderCallback.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // namespace Microsoft.Zelig.Runtime.TypeSystem { using System; using System.Collections.Generic; using TS = Microsoft.Zelig.Runtime.TypeSystem; public abstract class CodeMapDecoderCallback { public enum PointerKind { Heap , Internal , Potential, } public abstract bool RegisterEnter( UIntPtr address, uint num , PointerKind kind ); public abstract bool RegisterLeave( UIntPtr address, uint num ); public abstract bool StackEnter ( UIntPtr address, uint offset, PointerKind kind ); public abstract bool StackLeave ( UIntPtr address, uint offset ); } } ================================================ FILE: Zelig/Zelig/RunTime/Zelig/TypeSystem/CodePointer.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // namespace Microsoft.Zelig.Runtime.TypeSystem { using System; using System.Collections.Generic; [WellKnownType( "Microsoft_Zelig_Runtime_TypeSystem_CodePointer" )] public struct CodePointer { // // State // [WellKnownField( "CodePointer_Target" )] public IntPtr Target; // // Equality Methods // public bool SameContents( ref CodePointer other ) { return (this.Target == other.Target); } // // Access Methods // public bool IsValid { get { return this.Target.ToInt32() != 0; } } } } ================================================ FILE: Zelig/Zelig/RunTime/Zelig/TypeSystem/ConversionContext.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // namespace Microsoft.Zelig.Runtime.TypeSystem { using System; using System.Collections.Generic; public struct ConversionContext { // // State // public TypeRepresentation m_typeContextOwner; public TypeRepresentation[] m_typeContext; public MethodRepresentation m_methodContextOwner; public TypeRepresentation[] m_methodContext; //--// public void Initialize() { SetContextAsTypeParameters( TypeRepresentation.SharedEmptyArray ); } //--// public bool SameContents( ref ConversionContext other ) { if(m_typeContextOwner == other.m_typeContextOwner && m_methodContextOwner == other.m_methodContextOwner ) { if(ArrayUtility.ArrayEquals( m_typeContext , other.m_typeContext ) && ArrayUtility.ArrayEquals( m_methodContext, other.m_methodContext ) ) { return true; } } return false; } //--// // // Helper Methods // public void SetContextAsType( TypeRepresentation td ) { CHECKS.ASSERT( td != null, "'td' cannot be null" ); m_typeContextOwner = td; m_typeContext = td.GenericParameters; m_methodContextOwner = null; m_methodContext = TypeRepresentation.SharedEmptyArray; } public void SetContextAsTypeParameters( TypeRepresentation[] parameters ) { CHECKS.ASSERT( parameters != null, "'parameters' cannot be null" ); m_typeContextOwner = null; m_typeContext = parameters; m_methodContextOwner = null; m_methodContext = TypeRepresentation.SharedEmptyArray; } public void AdjustContextAsType( int numParameters ) { // // When expanding a nested class, we need to expand the enclosing class. // If both the nested class and the enclosing class are generics, we need to drop type parameters // when we switch to the enclosing class. // if(m_typeContext.Length > numParameters) { m_typeContext = ArrayUtility.ExtractSliceFromNotNullArray( m_typeContext, 0, numParameters ); } } public void SetContextAsMethod( MethodRepresentation md ) { CHECKS.ASSERT( md != null, "'md' cannot be null" ); m_methodContextOwner = md; m_methodContext = md.GenericParameters; } public void SetContextAsMethodParameters( TypeRepresentation[] parameters ) { CHECKS.ASSERT( parameters != null, "'parameters' cannot be null" ); m_methodContextOwner = null; m_methodContext = parameters; } //--// // // Debug Methods // public override string ToString() { System.Text.StringBuilder sb = new System.Text.StringBuilder(); InnerToString( sb ); return sb.ToString(); } internal void InnerToString( System.Text.StringBuilder sb ) { if(m_typeContext != null && m_typeContext.Length > 0) { sb.Append( " => Type:[" ); for(int i = 0; i < m_typeContext.Length; i++) { if(i != 0) sb.Append( "," ); sb.Append( m_typeContext[i] ); } sb.Append( "]" ); } else if(m_typeContextOwner != null) { sb.Append( " => " ); sb.Append( m_typeContextOwner ); } if(m_methodContext != null && m_methodContext.Length > 0) { sb.Append( " => Method:[" ); for(int i = 0; i < m_methodContext.Length; i++) { if(i != 0) sb.Append( "," ); sb.Append( m_methodContext[i] ); } sb.Append( "]" ); } else if(m_methodContextOwner != null) { sb.Append( " => " ); sb.Append( m_methodContextOwner ); } } } } ================================================ FILE: Zelig/Zelig/RunTime/Zelig/TypeSystem/CustomAttributeAssociationRepresentation.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // namespace Microsoft.Zelig.Runtime.TypeSystem { using System; using System.Collections.Generic; public delegate void CustomAttributeAssociationEnumerationCallback( CustomAttributeAssociationRepresentation caa ); public sealed class CustomAttributeAssociationRepresentation { public static readonly CustomAttributeAssociationRepresentation[] SharedEmptyArray = new CustomAttributeAssociationRepresentation[0]; // // State // private CustomAttributeRepresentation m_ca; private BaseRepresentation m_target; private int m_paramIndex; // // Constructor Methods // public CustomAttributeAssociationRepresentation( CustomAttributeRepresentation ca , BaseRepresentation target , int paramIndex ) { m_ca = ca; m_target = target; m_paramIndex = paramIndex; } // // MetaDataEquality Methods // public override bool Equals( object obj ) { if(obj is CustomAttributeAssociationRepresentation) { CustomAttributeAssociationRepresentation other = (CustomAttributeAssociationRepresentation)obj; if(m_ca == other.m_ca && m_target == other.m_target && m_paramIndex == other.m_paramIndex ) { return true; } } return false; } public override int GetHashCode() { return m_ca.GetHashCode(); } //--// // // Helper Methods // public void ApplyTransformation( TransformationContext context ) { context.Push( this ); context.Transform( ref m_ca ); context.Transform( ref m_target ); context.Transform( ref m_paramIndex ); context.Pop(); } //--// // // Access Methods // public CustomAttributeRepresentation CustomAttribute { get { return m_ca; } } public BaseRepresentation Target { get { return m_target; } } public int ParameterIndex { get { return m_paramIndex; } } } } ================================================ FILE: Zelig/Zelig/RunTime/Zelig/TypeSystem/CustomAttributeRepresentation.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // namespace Microsoft.Zelig.Runtime.TypeSystem { using System; using System.Collections.Generic; public sealed class CustomAttributeRepresentation { public static readonly CustomAttributeRepresentation[] SharedEmptyArray = new CustomAttributeRepresentation[0]; // // State // private MethodRepresentation m_constructor; private object[] m_fixedArgsValues; private string[] m_namedArgs; private object[] m_namedArgsValues; // // Constructor Methods // public CustomAttributeRepresentation( MethodRepresentation constructor , object[] fixedArgsValues , string[] namedArgs , object[] namedArgsValues ) { CHECKS.ASSERT( constructor != null, "Cannot create CustomAttributeRepresentation without supporting metadata" ); m_constructor = constructor; m_fixedArgsValues = fixedArgsValues; m_namedArgs = namedArgs; m_namedArgsValues = namedArgsValues; } // // MetaDataEquality Methods // public override bool Equals( object obj ) { if(obj is CustomAttributeRepresentation) { CustomAttributeRepresentation other = (CustomAttributeRepresentation)obj; if(m_constructor == other.m_constructor) { if(ArrayUtility.ArrayEquals( m_fixedArgsValues, other.m_fixedArgsValues ) && ArrayUtility.ArrayEquals( m_namedArgs , other.m_namedArgs ) && ArrayUtility.ArrayEquals( m_namedArgsValues, other.m_namedArgsValues ) ) { return true; } } } return false; } public override int GetHashCode() { return m_constructor.GetHashCode(); } //--// // // Helper Methods // public void ApplyTransformation( TransformationContext context ) { context.Push( this ); context.Transform( ref m_constructor ); context.Transform( ref m_fixedArgsValues ); context.Transform( ref m_namedArgs ); context.Transform( ref m_namedArgsValues ); context.Pop(); } //--// public bool HasNamedArg( string name ) { return GetNamedArgIndex( name ) >= 0; } public object GetNamedArg( string name ) { int i = GetNamedArgIndex( name ); if(i >= 0) { return m_namedArgsValues[i]; } return null; } public bool TryToGetNamedArg< T >( string name , out T val ) { return TryToGetNamedArg( name, out val, default(T) ); } public bool TryToGetNamedArg< T >( string name , out T val , T defaultVal ) { int i = GetNamedArgIndex( name ); if(i >= 0) { val = (T)m_namedArgsValues[i]; return true; } else { val = defaultVal; return false; } } public T GetNamedArg< T >( string name ) { object val = GetNamedArg( name ); if(val != null) { return (T)val; } else { return default(T); } } public T GetNamedArg< T >( string name , T defaultVal ) { object val = GetNamedArg( name ); if(val != null) { return (T)val; } else { return defaultVal; } } private int GetNamedArgIndex( string name ) { for(int i = 0; i < m_namedArgs.Length; i++) { if(m_namedArgs[i] == name) { return i; } } return -1; } //--// // // Access Methods // public MethodRepresentation Constructor { get { return m_constructor; } } public object[] FixedArgsValues { get { return m_fixedArgsValues; } } public string[] NamedArgs { get { return m_namedArgs; } } public object[] NamedArgsValues { get { return m_namedArgsValues; } } } } ================================================ FILE: Zelig/Zelig/RunTime/Zelig/TypeSystem/Environment/IConfigurationProvider.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // namespace Microsoft.Zelig.Runtime.TypeSystem { using System; using System.Collections.Generic; using System.IO; using System.Runtime.CompilerServices; public interface IConfigurationProvider { bool GetValue( string optionName , out object val ); } } ================================================ FILE: Zelig/Zelig/RunTime/Zelig/TypeSystem/Environment/IEnvironmentProvider.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // namespace Microsoft.Zelig.Runtime.TypeSystem { using System; using System.Collections.Generic; using System.IO; using System.Runtime.CompilerServices; public interface IEnvironmentProvider { object GetService( Type t ); } } ================================================ FILE: Zelig/Zelig/RunTime/Zelig/TypeSystem/EquivalenceSet.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // namespace Microsoft.Zelig.Runtime.TypeSystem { using System; using System.Collections.Generic; public class EquivalenceSet { public delegate bool EquivalenceDelegation( BaseRepresentation context1, BaseRepresentation br1, BaseRepresentation context2, BaseRepresentation br2 ); // // State // EquivalenceDelegation m_dlg; GrowOnlySet< BaseRepresentation > m_equivalence; // // Constructor Methods // public EquivalenceSet( EquivalenceDelegation dlg ) { m_dlg = dlg; m_equivalence = SetFactory.NewWithReferenceEquality< BaseRepresentation >(); } // // Helper Methods // public void AddEquivalencePair( BaseRepresentation br1 , BaseRepresentation br2 ) { m_equivalence.Insert( br1 ); m_equivalence.Insert( br2 ); } public bool AreEquivalent( BaseRepresentation context1 , BaseRepresentation br1 , BaseRepresentation context2 , BaseRepresentation br2 ) { if(m_equivalence.Contains( br1 ) && m_equivalence.Contains( br2 ) ) { return true; } if(m_dlg != null) { return m_dlg( context1, br1, context2, br2 ); } return false; } } } ================================================ FILE: Zelig/Zelig/RunTime/Zelig/TypeSystem/ExceptionMap.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // namespace Microsoft.Zelig.Runtime.TypeSystem { using System; using System.Collections.Generic; using TS = Microsoft.Zelig.Runtime.TypeSystem; [TS.AllowCompileTimeIntrospection] public class ExceptionMap { [TS.AllowCompileTimeIntrospection] public struct Handler { public static readonly Handler[] SharedEmptyArray = new Handler[0]; // // State // public VTable Filter; public CodePointer HandlerCode; // // Equality Methods // public bool SameContents( ref Handler other ) { if(this.Filter == other.Filter) { return this.HandlerCode.SameContents( ref other.HandlerCode ); } return false; } } [TS.AllowCompileTimeIntrospection] public struct Range { public static readonly Range[] SharedEmptyArray = new Range[0]; // // State // public UIntPtr Start; public UIntPtr End; public Handler[] Handlers; // // Equality Methods // public bool SameContents( ref Range other ) { if(this.Start == other.Start && this.End == other.End ) { Handler[] thisHandlers = this .Handlers; Handler[] otherHandlers = other.Handlers; int thisLen = thisHandlers != null ? thisHandlers .Length : 0; int otherLen = otherHandlers != null ? otherHandlers.Length : 0; if(thisLen == otherLen) { for(int i = 0; i < thisLen; i++) { if(thisHandlers[i].SameContents( ref otherHandlers[i] ) == false) { return false; } } return true; } } return false; } public bool Contains( UIntPtr address ) { return AddressMath.IsInRange( address, this.Start, this.End ); } public CodePointer Match( UIntPtr address , VTable exception ) { if(Contains( address )) { Handler[] handlers = this.Handlers; for(int i = 0; i < handlers.Length; i++) { VTable filter = handlers[i].Filter; if(filter == null || filter.CanBeAssignedFrom( exception )) { return handlers[i].HandlerCode; } } } return new CodePointer(); } } //--// // // State // [WellKnownField( "ExceptionMap_Ranges" )] public Range[] Ranges; // // Equality Methods // public static bool SameContents( ExceptionMap left , ExceptionMap right ) { if(Object.ReferenceEquals( left, right )) { return true; } if(left != null && right != null) { return left.SameContents( right ); } return false; } public bool SameContents( ExceptionMap other ) { Range[] thisRanges = this .Ranges; Range[] otherRanges = other.Ranges; int thisLen = thisRanges != null ? thisRanges .Length : 0; int otherLen = otherRanges != null ? otherRanges.Length : 0; if(thisLen == otherLen) { for(int i = 0; i < thisLen; i++) { if(thisRanges[i].SameContents( ref otherRanges[i] ) == false) { return false; } } return true; } return false; } [NoInline] public CodePointer ResolveAddressToHandler( UIntPtr address , VTable exception ) { Range[] ranges = this.Ranges; if(ranges != null) { for(int i = 0; i < ranges.Length; i++) { CodePointer res = ranges[i].Match( address, exception ); if(res.IsValid) { return res; } } } return new CodePointer(); } } } ================================================ FILE: Zelig/Zelig/RunTime/Zelig/TypeSystem/Fields/FieldRepresentation.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // namespace Microsoft.Zelig.Runtime.TypeSystem { using System; using System.Collections.Generic; public abstract class FieldRepresentation : BaseRepresentation { // // This is just a copy of Microsoft.Zelig.MetaData.FieldAttributes, needed to break the dependency of TypeSystem from MetaData. // // Also, it's extended to 32bits, to allow extra values. // [Flags] public enum Attributes : uint { FieldAccessMask = 0x00000007, // member access mask - Use this mask to retrieve accessibility information. PrivateScope = 0x00000000, // Member not referenceable. Private = 0x00000001, // Accessible only by the parent type. FamANDAssem = 0x00000002, // Accessible by sub-types only in this Assembly. Assembly = 0x00000003, // Accessibly by anyone in the Assembly. Family = 0x00000004, // Accessible only by type and sub-types. FamORAssem = 0x00000005, // Accessibly by sub-types anywhere, plus anyone in assembly. Public = 0x00000006, // Accessibly by anyone who has visibility to this scope. // end member access mask // field contract attributes. Static = 0x00000010, // Defined on type, else per instance. InitOnly = 0x00000020, // Field may only be initialized, not written to after init. Literal = 0x00000040, // Value is compile time constant. NotSerialized = 0x00000080, // Field does not have to be serialized when type is remoted. SpecialName = 0x00000200, // field is special. Name describes how. // interop attributes PinvokeImpl = 0x00002000, // Implementation is forwarded through pinvoke. // Reserved flags for runtime use only. ReservedMask = 0x00009500, RTSpecialName = 0x00000400, // Runtime(metadata internal APIs) should check name encoding. HasFieldMarshal = 0x00001000, // Field has marshalling information. HasDefault = 0x00008000, // Field has default. HasFieldRVA = 0x00000100, // Field has RVA. // // Values exclusive to Zelig. // IsVolatile = 0x00010000, HasSingleAssignment = 0x00020000, NeverNull = 0x00040000, HasFixedSize = 0x00080000, } public static readonly FieldRepresentation[] SharedEmptyArray = new FieldRepresentation[0]; // // State // protected TypeRepresentation m_ownerType; protected Attributes m_flags; protected string m_name; protected TypeRepresentation m_fieldType; // // This is populated by the DetectConstants analysis. // protected int m_fixedSize; // // This field is synthesized from the analysis of the type hierarchy and the type characteristics. // private int m_offset; // // Constructor Methods // protected FieldRepresentation( TypeRepresentation ownerType , string name ) { CHECKS.ASSERT( ownerType != null, "Cannot create a FieldRepresentation without an owner" ); CHECKS.ASSERT( name != null, "Cannot create a FieldRepresentation without a name" ); m_ownerType = ownerType; m_name = name; m_offset = ownerType is ScalarTypeRepresentation ? 0 : int.MinValue; } // // MetaDataEquality Methods // public override bool EqualsThroughEquivalence( object obj , EquivalenceSet set ) { if(obj is FieldRepresentation) { FieldRepresentation other = (FieldRepresentation)obj; if( m_name == other.m_name && EqualsThroughEquivalence( m_ownerType , other.m_ownerType, set ) && EqualsThroughEquivalence( m_fieldType , other.m_fieldType, set ) ) { CHECKS.ASSERT( this.GetType() == other.GetType(), "Found two inconsistent FieldRepresentation" ); return true; } } return false; } public override bool Equals( object obj ) { return this.EqualsThroughEquivalence( obj, null ); } public override int GetHashCode() { return m_name .GetHashCode() ^ m_ownerType.GetHashCode(); } public static bool operator ==( FieldRepresentation left , FieldRepresentation right ) { return Object.Equals( left, right ); } public static bool operator !=( FieldRepresentation left , FieldRepresentation right ) { return !(left == right); } //--// // // Helper Methods // protected void Done( TypeSystem typeSystem ) { typeSystem.NotifyNewFieldComplete( this ); } internal void PerformFieldAnalysis( TypeSystem typeSystem , ref ConversionContext context ) { MetaData.Normalized.MetaDataField metadata = typeSystem.GetAssociatedMetaData( this ); MetaData.Normalized.SignatureType sig = metadata.FieldSignature.TypeSignature; m_flags = (Attributes)metadata.Flags; m_fieldType = typeSystem.ConvertToIR( sig, context ); if(sig.Modifiers != null) { TypeRepresentation[] modifiers = new TypeRepresentation[sig.Modifiers.Length]; TypeRepresentation tdIsVolatile = typeSystem.WellKnownTypes.System_Runtime_CompilerServices_IsVolatile; for(int i = 0; i < modifiers.Length; i++) { modifiers[i] = typeSystem.ConvertToIR( sig.Modifiers[i], context ); if(modifiers[i] == tdIsVolatile) { m_flags |= Attributes.IsVolatile; } } } Done( typeSystem ); } internal void ProcessCustomAttributes( TypeSystem typeSystem , ref ConversionContext context ) { MetaData.Normalized.MetaDataField metadata = typeSystem.GetAssociatedMetaData( this ); typeSystem.ConvertToIR( metadata.CustomAttributes, context, this, -1 ); } //--// public override void ApplyTransformation( TransformationContext context ) { context.Push( this ); base.ApplyTransformation( context ); context.Transform( ref m_ownerType ); context.Transform( ref m_flags ); context.Transform( ref m_name ); context.Transform( ref m_fieldType ); context.Transform( ref m_fixedSize ); context.Transform( ref m_offset ); context.Pop(); } //--// // // Access Methods // public TypeRepresentation OwnerType { get { return m_ownerType; } } public Attributes Flags { get { return m_flags; } set { m_flags = value; } } public string Name { get { return m_name; } } public TypeRepresentation FieldType { get { return m_fieldType; } } public int FixedSize { get { return m_fixedSize; } set { m_fixedSize = value; m_flags |= Attributes.HasFixedSize; } } public bool IsOpenField { get { return m_fieldType.IsOpenType; } } //--// public bool ValidLayout { get { return m_offset >= 0; } } public int Offset { get { CHECKS.ASSERT( this.ValidLayout, "Cannot access 'Offset' property on field '{0}' before the field has been laid out", this ); return m_offset; } set { m_offset = value; } } //--// // // Debug Methods // public string ToShortString() { System.Text.StringBuilder sb = new System.Text.StringBuilder(); PrettyToString( sb, false ); return sb.ToString(); } protected void PrettyToString( System.Text.StringBuilder sb , bool fPrefix ) { m_fieldType.PrettyToString( sb, fPrefix, true ); sb.Append( " " ); if(m_ownerType != null) { m_ownerType.PrettyToString( sb, fPrefix, false ); sb.Append( "::" ); } sb.Append( m_name ); } } } ================================================ FILE: Zelig/Zelig/RunTime/Zelig/TypeSystem/Fields/InstanceFieldRepresentation.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // namespace Microsoft.Zelig.Runtime.TypeSystem { using System; using System.Collections.Generic; public sealed class InstanceFieldRepresentation : FieldRepresentation { // // State // internal StaticFieldRepresentation m_implementationOf; // // Constructor Methods // public InstanceFieldRepresentation( TypeRepresentation ownerType , string name ) : base( ownerType, name ) { } public InstanceFieldRepresentation( TypeRepresentation ownerType , string name , TypeRepresentation fieldType ) : base( ownerType, name ) { m_fieldType = fieldType; } //--// // // Helper Methods // public override void ApplyTransformation( TransformationContext context ) { context.Push( this ); base.ApplyTransformation( context ); context.Transform( ref m_implementationOf ); context.Pop(); } //--// public void LinkAsImplementationOf( StaticFieldRepresentation fd ) { fd .m_implementedBy = this; this.m_implementationOf = fd; this.m_flags = fd.Flags & ~Attributes.Static; this.m_fixedSize = fd.FixedSize; } //--// // // Access Methods // public StaticFieldRepresentation ImplementationOf { get { return m_implementationOf; } } //--// // // Debug Methods // public override String ToString() { System.Text.StringBuilder sb = new System.Text.StringBuilder( "InstanceFieldRepresentation(" ); PrettyToString( sb, true ); if(m_implementationOf != null) { sb.AppendFormat( ", implements {0}::{1}", m_implementationOf.OwnerType.FullNameWithAbbreviation, m_implementationOf.Name ); } sb.Append( ")" ); return sb.ToString(); } } } ================================================ FILE: Zelig/Zelig/RunTime/Zelig/TypeSystem/Fields/StaticFieldRepresentation.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // namespace Microsoft.Zelig.Runtime.TypeSystem { using System; using System.Collections.Generic; public sealed class StaticFieldRepresentation : FieldRepresentation { // // State // internal InstanceFieldRepresentation m_implementedBy; // // Constructor Methods // public StaticFieldRepresentation( TypeRepresentation ownerType , string name ) : base( ownerType, name ) { } //--// // // Helper Methods // public override void ApplyTransformation( TransformationContext context ) { context.Push( this ); base.ApplyTransformation( context ); context.Transform( ref m_implementedBy ); context.Pop(); } // // Access Methods // public InstanceFieldRepresentation ImplementedBy { get { return m_implementedBy; } } //--// // // Debug Methods // public override String ToString() { System.Text.StringBuilder sb = new System.Text.StringBuilder( "StaticFieldRepresentation(" ); PrettyToString( sb, true ); if(m_implementedBy != null) { sb.AppendFormat( ", implemented by {0}::{1}", m_implementedBy.OwnerType.FullNameWithAbbreviation, m_implementedBy.Name ); } sb.Append( ")" ); return sb.ToString(); } } } ================================================ FILE: Zelig/Zelig/RunTime/Zelig/TypeSystem/GCInfo.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // namespace Microsoft.Zelig.Runtime.TypeSystem { using System; using System.Collections.Generic; public struct GCInfo { public enum Kind : short { Invalid , NotAPointer , AggregateType, Heap , Internal , Potential , // For IntPtr and UIntPtr, treat them as potential pointers that have been pinned. } public struct Pointer { public Kind Kind; public short OffsetInWords; } //--// // // State // public Pointer[] Pointers; //--// // // Access Methods // } } ================================================ FILE: Zelig/Zelig/RunTime/Zelig/TypeSystem/GenericInstantiationClosure.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // //#define TYPESYSTEM_DEBUG_GENERICINSTANTIATIONCLOUSURE namespace Microsoft.Zelig.Runtime.TypeSystem { using System; using System.Collections.Generic; using Microsoft.Zelig.MetaData.Normalized; internal class GenericInstantiationClosure { class Lookup : GrowOnlyHashTable< MetaDataTypeDefinitionGeneric, bool > { } class Roots : GrowOnlyHashTable< MetaDataTypeDefinitionPartiallyDelayedTypeParameter, Edges > { } class Edges : GrowOnlyHashTable< MetaDataTypeDefinitionPartiallyDelayedTypeParameter, Edge > { } class Edge { internal const bool Expanding = true; internal const bool NotExpanding = false; // // State // private bool m_status; private int m_visitIndex; // // Constructor Methods // internal Edge( bool status ) { m_status = status; m_visitIndex = -1; } internal void Unvisit() { m_visitIndex = -1; } internal int VisitIndex { get { return m_visitIndex; } set { m_visitIndex = value; } } internal bool IsExpanding { get { return m_status == Expanding; } } internal bool IsVisited { get { return m_visitIndex != -1; } } } class Nodes : GrowOnlySet< MetaDataTypeDefinitionGenericInstantiation > { } class TypeSet : GrowOnlyHashTable< MetaDataTypeDefinitionAbstract, MetaDataTypeDefinitionAbstract > { } // // State // private readonly Lookup m_genericRecursionCheck = new Lookup(); //--// internal bool VerifyFiniteInstantiationOfGenericType( MetaDataTypeDefinitionGeneric td ) { bool res; if(m_genericRecursionCheck.TryGetValue( td, out res ) == false) { Roots roots = new Roots(); Nodes nodes = new Nodes(); TypeSet set = new TypeSet(); TypeSet setExpand = new TypeSet(); TypeSet setResN = new TypeSet(); TypeSet setResNplus1 = new TypeSet(); TypeSet setResTmp; //// Console.WriteLine(); //// Console.WriteLine(); //// Console.WriteLine(); setResN[td] = td; while(setResN.Count > 0) { setResNplus1.Clear(); foreach(MetaDataTypeDefinitionAbstract tdNext in setResN.Keys) { if(set.ContainsKey( tdNext ) == false) { set[tdNext] = tdNext; setExpand.Clear(); ExpandIfNotPresent( tdNext, setExpand ); foreach(MetaDataTypeDefinitionAbstract tdGenNext in setExpand.Keys) { if(tdGenNext is MetaDataTypeDefinitionGeneric) { CollectGenericInstantiations( setResNplus1, (MetaDataTypeDefinitionGeneric)tdGenNext ); } } foreach(MetaDataTypeDefinitionAbstract tdGenNext in setResNplus1.Values) { if(tdGenNext is MetaDataTypeDefinitionGenericInstantiation) { MetaDataTypeDefinitionGenericInstantiation tdGenInst = (MetaDataTypeDefinitionGenericInstantiation)tdGenNext; nodes.Insert( tdGenInst ); } if(tdGenNext is MetaDataTypeDefinitionGeneric) { MetaDataTypeDefinitionGeneric tdGen = (MetaDataTypeDefinitionGeneric)tdGenNext; for(int i = 0; i < tdGen.GenericParams.Length; i++) { MetaDataTypeDefinitionPartiallyDelayedTypeParameter param = new MetaDataTypeDefinitionPartiallyDelayedTypeParameter( tdGen, i ); roots[param] = new Edges(); } } } } } setResTmp = setResN; setResN = setResNplus1; setResNplus1 = setResTmp; } setResN.Clear(); foreach(MetaDataTypeDefinitionGenericInstantiation tdGenInst in nodes) { ComputeEdges( roots, setResN, tdGenInst ); } //// Console.WriteLine(); //// Dump( roots ); res = (FindExpandingCycle( roots ) == false); m_genericRecursionCheck[td] = res; } return res; } //--// private void ComputeEdges( Roots roots , TypeSet set , MetaDataTypeDefinitionGenericInstantiation td ) { if(set.ContainsKey( td ) == false) { set[td] = td; MetaDataTypeDefinitionGeneric tdGen = td.GenericType; for(int i = 0; i < tdGen.GenericParams.Length; i++) { MetaDataTypeDefinitionPartiallyDelayedTypeParameter param = new MetaDataTypeDefinitionPartiallyDelayedTypeParameter( tdGen, i ); ComputeEdges( roots, set, param, td.InstantiationParams[i].Type, true ); } } } private void ComputeEdges( Roots roots , TypeSet set , MetaDataTypeDefinitionPartiallyDelayedTypeParameter param , MetaDataTypeDefinitionAbstract td , bool fFirstLevel ) { if(td is MetaDataTypeDefinitionPartiallyDelayedTypeParameter) { MetaDataTypeDefinitionPartiallyDelayedTypeParameter param2 = (MetaDataTypeDefinitionPartiallyDelayedTypeParameter)td; Edges edges; if(roots.TryGetValue( param2, out edges ) == false) { edges = new Edges(); roots[param2] = edges; } if(fFirstLevel) { // // Add non-expanding edge. // // If an edge is already present, there are two cases: // // 1) It's a non-expanding edge => state is already correct. // 2) It's an expanding edge => state should not be changed. // // so only update if not present. // if(edges.ContainsKey( param ) == false) { //// Console.WriteLine( "Add NonExpanding {0} -> {1}", param2.FullName, param.FullName ); edges[param] = new Edge( Edge.NotExpanding ); } } else { // // Add expanding edge. // // If an edge is already present, there are two cases: // // 1) It's a non-expanding edge => state should be changed to expanding. // 2) It's an expanding edge => state is already correct. // // so always update. // //// Console.WriteLine( "Add Expanding {0} -> {1}", param2.FullName, param.FullName ); edges[param] = new Edge( Edge.Expanding ); } } else if(td is MetaDataTypeDefinitionPartiallyDelayedMethodParameter) { // BUGBUG: Not Implemented. } else if(td is MetaDataTypeDefinitionGenericInstantiation) { MetaDataTypeDefinitionGenericInstantiation td2 = (MetaDataTypeDefinitionGenericInstantiation)td; MetaDataTypeDefinitionGeneric tdGen = td2.GenericType; for(int i = 0; i < tdGen.GenericParams.Length; i++) { ComputeEdges( roots, set, param, td2.InstantiationParams[i].Type, false ); } ComputeEdges( roots, set, td2 ); } else if(td is MetaDataTypeDefinitionByRef) { MetaDataTypeDefinitionByRef td2 = (MetaDataTypeDefinitionByRef)td; ComputeEdges( roots, set, param, td2.BaseType, false ); } else if(td is MetaDataTypeDefinitionArray) { MetaDataTypeDefinitionArray td2 = (MetaDataTypeDefinitionArray)td; ComputeEdges( roots, set, param, td2.ObjectType, true ); } else if(td is MetaDataTypeDefinition) { } else { throw TypeConsistencyErrorException.Create( "Internal error during ComputeEdges" ); } } //--// private bool FindExpandingCycle( Roots roots ) { foreach(MetaDataTypeDefinitionPartiallyDelayedTypeParameter param in roots.Keys) { if(FindExpandingCycle( roots, param, -1, 0 )) { #if TYPESYSTEM_DEBUG_GENERICINSTANTIATIONCLOUSURE Console.WriteLine( "Loop {0}", param.FullName ); #endif return true; } } return false; } private bool FindExpandingCycle( Roots roots , MetaDataTypeDefinitionPartiallyDelayedTypeParameter paramS , int expandingMark , int currentMark ) { Edges edges; if(roots.TryGetValue( paramS, out edges )) { foreach(MetaDataTypeDefinitionPartiallyDelayedTypeParameter paramD in edges.Keys) { Edge edge = edges[paramD]; if(edge.IsVisited) { int loopMark = edge.VisitIndex; if(loopMark <= expandingMark) { #if TYPESYSTEM_DEBUG_GENERICINSTANTIATIONCLOUSURE Console.WriteLine( "Found expanding cycle:" ); Dump( roots ); #endif return true; } return false; } edge.VisitIndex = currentMark; if(FindExpandingCycle( roots, paramD, edge.IsExpanding ? currentMark : expandingMark, currentMark+1 )) { #if TYPESYSTEM_DEBUG_GENERICINSTANTIATIONCLOUSURE Console.WriteLine( "Loop {0}", paramD.FullName ); #endif return true; } edge.Unvisit(); } } return false; } #if TYPESYSTEM_DEBUG_GENERICINSTANTIATIONCLOUSURE private void Dump( Roots roots ) { foreach(MetaDataTypeDefinitionPartiallyDelayedTypeParameter paramS in roots.Keys) { Edges edges = roots[paramS]; foreach(MetaDataTypeDefinitionPartiallyDelayedTypeParameter paramD in edges.Keys) { Edge edge = edges[paramD]; Console.WriteLine( "{0} {1}{2} {3}", paramS.FullName, edge.IsVisited ? "*" : "", edge.IsExpanding ? "=>" : "->", paramD.FullName ); } } } #endif //--// private void ExpandIfNotPresent( MetaDataTypeDefinitionAbstract td , TypeSet set ) { if(td.IsOpenType && set.ContainsKey( td ) == false) { set[td] = td; if(td is MetaDataTypeDefinitionGenericInstantiation) { MetaDataTypeDefinitionGenericInstantiation td2 = (MetaDataTypeDefinitionGenericInstantiation)td; ExpandIfNotPresent( td2.GenericType, set ); foreach(SignatureType td3 in td2.InstantiationParams) { ExpandIfNotPresent( td3.Type, set ); } } else if(td is MetaDataTypeDefinitionByRef) { MetaDataTypeDefinitionByRef td2 = (MetaDataTypeDefinitionByRef)td; ExpandIfNotPresent( td2.BaseType, set ); } else if(td is MetaDataTypeDefinitionArray) { MetaDataTypeDefinitionArray td2 = (MetaDataTypeDefinitionArray)td; ExpandIfNotPresent( td2.ObjectType, set ); } } } //--// private void CollectGenericInstantiations( TypeSet set , MetaDataTypeDefinitionGeneric td ) { CheckAndAddToGenericInstantiationsList( set, td, null, td.Extends ); if(td.Interfaces != null) { foreach(MetaDataTypeDefinitionAbstract itf in td.Interfaces) { CheckAndAddToGenericInstantiationsList( set, td, null, itf ); } } if(td.Fields != null) { foreach(MetaDataField fd in td.Fields) { CheckAndAddToGenericInstantiationsList( set, td, null, fd.FieldSignature.TypeSignature.Type ); } } if(td.Methods != null) { foreach(MetaDataMethodBase md in td.Methods) { SignatureMethod sig = md.Signature; CheckAndAddToGenericInstantiationsList( set, td, md, sig.ReturnType.Type ); if(sig.Parameters != null) { foreach(SignatureType arg in sig.Parameters) { CheckAndAddToGenericInstantiationsList( set, td, md, arg.Type ); } } if(md.Locals != null) { foreach(SignatureType local in md.Locals) { CheckAndAddToGenericInstantiationsList( set, td, md, local.Type ); } } if(md.Instructions != null) { foreach(Instruction instr in md.Instructions) { object arg = instr.Argument; if(arg != null) { if(arg is MetaDataTypeDefinitionAbstract) { MetaDataTypeDefinitionAbstract tdArg = (MetaDataTypeDefinitionAbstract)arg; CheckAndAddToGenericInstantiationsList( set, td, md, tdArg ); } else if(arg is MetaDataField) { MetaDataField fdArg = (MetaDataField)arg; CheckAndAddToGenericInstantiationsList( set, td, md, fdArg.Owner ); } else if(arg is MetaDataMethodBase) { MetaDataMethodBase mdArg = (MetaDataMethodBase)arg; CheckAndAddToGenericInstantiationsList( set, td, md, mdArg.Owner ); } else if(arg is MetaDataMethodGenericInstantiation) { MetaDataMethodGenericInstantiation mdArg = (MetaDataMethodGenericInstantiation)arg; MetaDataMethodAbstract mdBase = mdArg.BaseMethod; if(mdBase is MetaDataMethodBase) { MetaDataMethodBase mdBase2 = (MetaDataMethodBase)mdBase; CheckAndAddToGenericInstantiationsList( set, td, mdBase2, mdBase2.Owner ); } else if(mdBase is MetaDataMethodWithContext) { MetaDataMethodWithContext mdBase2 = (MetaDataMethodWithContext)mdBase; CheckAndAddToGenericInstantiationsList( set, td, md , mdBase2.ContextType ); CheckAndAddToGenericInstantiationsList( set, td, mdBase2.BaseMethod, mdBase2.BaseMethod.Owner ); } } else if(arg is MetaDataMethodWithContext) { MetaDataMethodWithContext mdArg = (MetaDataMethodWithContext)arg; CheckAndAddToGenericInstantiationsList( set, td, md, mdArg.ContextType ); CheckAndAddToGenericInstantiationsList( set, td, md, mdArg.BaseMethod.Owner ); } } } } } } } private void CheckAndAddToGenericInstantiationsList( TypeSet set , MetaDataTypeDefinitionGeneric contextType , MetaDataMethodBase contextMethod , MetaDataTypeDefinitionAbstract td ) { if(ContainsGenericParameters( td )) { set[td] = Substitute( contextType, contextMethod as MetaDataMethodGeneric, td ); } } private bool ContainsGenericParameters( MetaDataTypeDefinitionAbstract td ) { return td != null && td.IsOpenType; } //--// private MetaDataTypeDefinitionAbstract Substitute( MetaDataTypeDefinitionGeneric contextType , MetaDataMethodGeneric contextMethod , MetaDataTypeDefinitionAbstract td ) { if(td is MetaDataTypeDefinitionGenericInstantiation) { MetaDataTypeDefinitionGenericInstantiation td2 = (MetaDataTypeDefinitionGenericInstantiation)td; SignatureType[] instantiationParams = td2.InstantiationParams; SignatureType[] genericParameters = new SignatureType[instantiationParams.Length]; for(int i = 0; i < instantiationParams.Length; i++) { genericParameters[i] = SignatureType.CreateUnique( Substitute( contextType, contextMethod, instantiationParams[i].Type ) ); } return td2.Specialize( genericParameters ); } else if(td is MetaDataTypeDefinitionByRef) { MetaDataTypeDefinitionByRef td2 = (MetaDataTypeDefinitionByRef)td; return Substitute( contextType, contextMethod, td2.BaseType ); } else if(td is MetaDataTypeDefinitionArray) { MetaDataTypeDefinitionArray td2 = (MetaDataTypeDefinitionArray)td; return Substitute( contextType, contextMethod, td2.ObjectType ); } else if(td is MetaDataTypeDefinitionDelayed) { MetaDataTypeDefinitionDelayed td2 = (MetaDataTypeDefinitionDelayed)td; if(td2.IsMethodParameter) { return new MetaDataTypeDefinitionPartiallyDelayedMethodParameter( contextMethod, td2.ParameterNumber ); } else { return new MetaDataTypeDefinitionPartiallyDelayedTypeParameter( contextType, td2.ParameterNumber ); } } else { return td; } } } } ================================================ FILE: Zelig/Zelig/RunTime/Zelig/TypeSystem/GenericParameterDefinition.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // namespace Microsoft.Zelig.Runtime.TypeSystem { using System; using System.Collections.Generic; public struct GenericParameterDefinition { // // This is just a copy of Microsoft.Zelig.MetaData.GenericParameterAttributes, needed to break the dependency of TypeSystem from MetaData. // [Flags] public enum Attributes : ushort { VarianceMask = 0x0003, NonVariant = 0x0000, // The generic parameter is non-variant Covariant = 0x0001, // The generic parameter is covariant Contravariant = 0x0002, // The generic parameter is contravariant SpecialConstraintMask = 0x001C, ReferenceTypeConstraint = 0x0004, // The generic parameter has the class special constraint NotNullableValueTypeConstraint = 0x0008, // The generic parameter has the valuetype special constraint DefaultConstructorConstraint = 0x0010, // The generic parameter has the .ctor special constraint } //--// // // State // public Attributes Flags; public String Name; public TypeRepresentation[] Constraints; //--// // // Helper Methods // public void ApplyTransformation( TransformationContext context ) { context.Transform( ref Flags ); context.Transform( ref Name ); context.Transform( ref Constraints ); } //--// public bool IsCompatible( ref GenericParameterDefinition paramDef ) { return ArrayUtility.ArrayEqualsNotNull( this.Constraints, paramDef.Constraints, 0 ); } } } ================================================ FILE: Zelig/Zelig/RunTime/Zelig/TypeSystem/GlobalRoot.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // namespace Microsoft.Zelig.Runtime.TypeSystem { using System; using System.Collections.Generic; using System.Runtime.CompilerServices; // // This class is used internally to hold all the storage for static fields and other global entries. // [WellKnownType( "Microsoft_Zelig_Runtime_TypeSystem_GlobalRoot" )] public class GlobalRoot { // // Constructor Methods // internal GlobalRoot() { } // // Access Methods // public static extern GlobalRoot Instance { [SingletonFactory()] [MethodImpl( MethodImplOptions.InternalCall )] get; } } } ================================================ FILE: Zelig/Zelig/RunTime/Zelig/TypeSystem/InstantiationContext.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // namespace Microsoft.Zelig.Runtime.TypeSystem { using System; using System.Collections.Generic; public class InstantiationContext { // // State // private readonly GrowOnlySet< TypeRepresentation > m_uniqueTypes; private readonly GrowOnlySet< FieldRepresentation > m_uniqueFields; private readonly GrowOnlySet< MethodRepresentation > m_uniqueMethods; private readonly GrowOnlySet< CustomAttributeRepresentation > m_uniqueAttributes; private readonly GrowOnlySet< ResourceRepresentation > m_uniqueResources; private readonly TypeRepresentation[] m_typeParameters; private readonly TypeRepresentation[] m_methodParameters; // // Constructor Methods // public InstantiationContext() { m_uniqueTypes = SetFactory.New< TypeRepresentation >(); m_uniqueFields = SetFactory.New< FieldRepresentation >(); m_uniqueMethods = SetFactory.New< MethodRepresentation >(); m_uniqueAttributes = SetFactory.New< CustomAttributeRepresentation >(); m_uniqueResources = SetFactory.New< ResourceRepresentation >(); m_typeParameters = TypeRepresentation.SharedEmptyArray; m_methodParameters = TypeRepresentation.SharedEmptyArray; } private InstantiationContext( InstantiationContext template , TypeRepresentation[] typeParameters , TypeRepresentation[] methodParameters ) { m_uniqueTypes = template.m_uniqueTypes; m_uniqueFields = template.m_uniqueFields; m_uniqueMethods = template.m_uniqueMethods; m_uniqueAttributes = template.m_uniqueAttributes; m_uniqueResources = template.m_uniqueResources; m_typeParameters = typeParameters != null ? typeParameters : TypeRepresentation.SharedEmptyArray; m_methodParameters = methodParameters != null ? methodParameters : TypeRepresentation.SharedEmptyArray; } // // Helper Methods // public InstantiationContext SetParameters( TypeRepresentation[] typeParameters , TypeRepresentation[] methodParameters ) { return new InstantiationContext( this, typeParameters, methodParameters ); } //--// public TypeRepresentation Lookup( TypeRepresentation td , bool fAdd ) { TypeRepresentation tdRes; if(m_uniqueTypes.Contains( td, out tdRes )) { return tdRes; } if(fAdd) { m_uniqueTypes.Insert( td ); } return null; } public FieldRepresentation Lookup( FieldRepresentation fd , bool fAdd ) { FieldRepresentation fdRes; if(m_uniqueFields.Contains( fd, out fdRes )) { return fdRes; } if(fAdd) { m_uniqueFields.Insert( fd ); } return null; } public MethodRepresentation Lookup( MethodRepresentation md , bool fAdd ) { MethodRepresentation mdRes; if(m_uniqueMethods.Contains( md, out mdRes )) { return mdRes; } if(fAdd) { m_uniqueMethods.Insert( md ); } return null; } public CustomAttributeRepresentation Lookup( CustomAttributeRepresentation ca , bool fAdd ) { CustomAttributeRepresentation caRes; if(m_uniqueAttributes.Contains( ca, out caRes )) { return caRes; } if(fAdd) { m_uniqueAttributes.Insert( ca ); } return null; } public ResourceRepresentation Lookup( ResourceRepresentation res , bool fAdd ) { ResourceRepresentation resRes; if(m_uniqueResources.Contains( res, out resRes )) { return resRes; } if(fAdd) { m_uniqueResources.Insert( res ); } return null; } //--// public TypeRepresentation Instantiate( TypeRepresentation td ) { if(td == null || td.IsOpenType == false) { return td; } return td.Instantiate( this ); } public TypeRepresentation[] Instantiate( TypeRepresentation[] tdArray ) { if(tdArray == null) { return tdArray; } int len = tdArray.Length; TypeRepresentation[] tdArrayRes = new TypeRepresentation[len]; bool fChanged = false; for(int i = 0; i < len; i++) { TypeRepresentation td = tdArray[i]; TypeRepresentation tdRes = Instantiate( td ); tdArrayRes[i] = tdRes; if(Object.ReferenceEquals( td, tdRes ) == false) { fChanged = true; } } return fChanged ? tdArrayRes : tdArray; } public MethodRepresentation Instantiate( MethodRepresentation md ) { throw new NotImplementedException(); } public MethodRepresentation[] Instantiate( MethodRepresentation[] mdArray ) { if(mdArray == null) { return mdArray; } int len = mdArray.Length; MethodRepresentation[] mdArrayRes = new MethodRepresentation[len]; bool fChanged = false; for(int i = 0; i < len; i++) { MethodRepresentation md = mdArray[i]; MethodRepresentation mdRes = Instantiate( md ); mdArrayRes[i] = mdRes; if(Object.ReferenceEquals( md, mdRes ) == false) { fChanged = true; } } return fChanged ? mdArrayRes : mdArray; } public FieldRepresentation Instantiate( FieldRepresentation fd ) { throw new NotImplementedException(); } public FieldRepresentation[] Instantiate( FieldRepresentation[] fdArray ) { if(fdArray == null) { return fdArray; } int len = fdArray.Length; FieldRepresentation[] fdArrayRes = new FieldRepresentation[len]; bool fChanged = false; for(int i = 0; i < len; i++) { FieldRepresentation fd = fdArray[i]; FieldRepresentation fdRes = Instantiate( fd ); fdArrayRes[i] = fdRes; if(Object.ReferenceEquals( fd, fdRes ) == false) { fChanged = true; } } return fChanged ? fdArrayRes : fdArray; } //--// public void RefreshHashCodes() { m_uniqueTypes .RefreshHashCodes(); m_uniqueFields .RefreshHashCodes(); m_uniqueMethods .RefreshHashCodes(); m_uniqueAttributes.RefreshHashCodes(); m_uniqueResources .RefreshHashCodes(); } // // Access Methods // public TypeRepresentation[] TypeParameters { get { return m_typeParameters; } } public TypeRepresentation[] MethodParameters { get { return m_methodParameters; } } // // Debug Methods // public override string ToString() { System.Text.StringBuilder sb = new System.Text.StringBuilder(); if(this.m_typeParameters.Length > 0) { sb.Append( "Type:[" ); for(int i = 0; i < this.m_typeParameters.Length; i++) { if(i != 0) sb.Append( "," ); sb.Append( this.m_typeParameters[i] ); } sb.Append( "]" ); } if(this.m_methodParameters.Length > 0) { sb.Append( " => Method:[" ); for(int i = 0; i < this.m_methodParameters.Length; i++) { if(i != 0) sb.Append( "," ); sb.Append( this.m_methodParameters[i] ); } sb.Append( "]" ); } return sb.ToString(); } } } ================================================ FILE: Zelig/Zelig/RunTime/Zelig/TypeSystem/Methods/ConstructorMethodRepresentation.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // //#define TRANSFORMATIONCONTEXT__USE_EMIT namespace Microsoft.Zelig.Runtime.TypeSystem { using System; using System.Collections.Generic; #if TRANSFORMATIONCONTEXT__USE_EMIT [AllowCompileTimeIntrospection] #endif public sealed class ConstructorMethodRepresentation : InstanceMethodRepresentation { // // Constructor Methods // public ConstructorMethodRepresentation( TypeRepresentation ownerType , GenericContext genericContext ) : base( ownerType, genericContext ) { } //--// // // Helper Methods // protected override MethodRepresentation AllocateInstantiation( InstantiationContext ic , TypeRepresentation ownerType , GenericContext genericContext ) { return new ConstructorMethodRepresentation( ownerType, genericContext ); } //--// public void Override( TypeSystem typeSystem , ConstructorMethodRepresentation mdSource ) { CloneSettings( typeSystem, mdSource ); //--// m_flags &= ~Attributes.Abstract; m_flags &= ~Attributes.SpecialName; m_flags &= ~Attributes.PinvokeImpl; m_flags &= ~Attributes.UnmanagedExport; } //--// // // Debug Methods // public override String ToString() { System.Text.StringBuilder sb = new System.Text.StringBuilder( "ConstructorMethodRepresentation(" ); PrettyToString( sb ); sb.Append( ")" ); return sb.ToString(); } } } ================================================ FILE: Zelig/Zelig/RunTime/Zelig/TypeSystem/Methods/FinalMethodRepresentation.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // namespace Microsoft.Zelig.Runtime.TypeSystem { using System; using System.Collections.Generic; #if TRANSFORMATIONCONTEXT__USE_EMIT [AllowCompileTimeIntrospection] #endif public sealed class FinalMethodRepresentation : VirtualMethodRepresentation { // // Constructor Methods // public FinalMethodRepresentation( TypeRepresentation ownerType , GenericContext genericContext ) : base( ownerType, genericContext ) { } //--// // // Helper Methods // //--// // // Debug Methods // public override String ToString() { System.Text.StringBuilder sb = new System.Text.StringBuilder( "FinalMethodRepresentation(" ); PrettyToString( sb ); sb.Append( ")" ); return sb.ToString(); } } } ================================================ FILE: Zelig/Zelig/RunTime/Zelig/TypeSystem/Methods/FinalizerMethodRepresentation.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // // #define TRANSFORMATIONCONTEXT__USE_EMIT namespace Microsoft.Zelig.Runtime.TypeSystem { using System; using System.Collections.Generic; #if TRANSFORMATIONCONTEXT__USE_EMIT [AllowCompileTimeIntrospection] #endif public sealed class FinalizerMethodRepresentation : VirtualMethodRepresentation { // // Constructor Methods // public FinalizerMethodRepresentation( TypeRepresentation ownerType , GenericContext genericContext ) : base( ownerType, genericContext ) { } //--// // // Helper Methods // protected override MethodRepresentation AllocateInstantiation( InstantiationContext ic , TypeRepresentation ownerType , GenericContext genericContext ) { return new FinalizerMethodRepresentation( ownerType, genericContext ); } //--// // // Debug Methods // public override String ToString() { System.Text.StringBuilder sb = new System.Text.StringBuilder( "FinalizerMethodRepresentation(" ); PrettyToString( sb ); sb.Append( ")" ); return sb.ToString(); } } } ================================================ FILE: Zelig/Zelig/RunTime/Zelig/TypeSystem/Methods/InstanceMethodRepresentation.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // namespace Microsoft.Zelig.Runtime.TypeSystem { using System; using System.Collections.Generic; public abstract class InstanceMethodRepresentation : MethodRepresentation { // // Constructor Methods // protected InstanceMethodRepresentation( TypeRepresentation ownerType , GenericContext genericContext ) : base( ownerType, genericContext ) { } //--// // // Debug Methods // public override String ToString() { System.Text.StringBuilder sb = new System.Text.StringBuilder( "InstanceMethodRepresentation(" ); PrettyToString( sb ); sb.Append( ")" ); return sb.ToString(); } } } ================================================ FILE: Zelig/Zelig/RunTime/Zelig/TypeSystem/Methods/MethodImplRepresentation.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // namespace Microsoft.Zelig.Runtime.TypeSystem { using System; using System.Collections.Generic; public sealed class MethodImplRepresentation { public static readonly MethodImplRepresentation[] SharedEmptyArray = new MethodImplRepresentation[0]; // // State // private MethodRepresentation m_body; private MethodRepresentation m_declaration; // // Constructor Methods // public MethodImplRepresentation( MethodRepresentation body , MethodRepresentation declaration ) { m_body = body; m_declaration = declaration; } // // MetaDataEquality Methods // public bool EqualsThroughEquivalence( object obj , EquivalenceSet set ) { if(obj is MethodImplRepresentation) { MethodImplRepresentation other = (MethodImplRepresentation)obj; if(BaseRepresentation.EqualsThroughEquivalence( m_body , other.m_body , set ) && BaseRepresentation.EqualsThroughEquivalence( m_declaration, other.m_declaration, set ) ) { return true; } } return false; } public override bool Equals( object obj ) { return this.EqualsThroughEquivalence( obj, null ); } public override int GetHashCode() { return m_body.GetHashCode(); } //--// // // Helper Methods // public void ApplyTransformation( TransformationContext context ) { context.Push( this ); context.Transform( ref m_body ); context.Transform( ref m_declaration ); context.Pop(); } //--// internal void ProhibitUse( TypeSystem.Reachability reachability , bool fApply ) { reachability.ExpandProhibition( this ); } // // Access Methods // public MethodRepresentation Body { get { return m_body; } } public MethodRepresentation Declaration { get { return m_declaration; } } //--// // // Debug Methods // public override String ToString() { System.Text.StringBuilder sb = new System.Text.StringBuilder( "MethodImplRepresentation(" ); sb.AppendFormat( "{0} => {1}", m_declaration.ToShortString(), m_body.ToShortString() ); sb.Append( ")" ); return sb.ToString(); } } } ================================================ FILE: Zelig/Zelig/RunTime/Zelig/TypeSystem/Methods/MethodRepresentation.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // namespace Microsoft.Zelig.Runtime.TypeSystem { using System; using System.Collections.Generic; public abstract class MethodRepresentation : BaseRepresentation { // // This is just a copy of Microsoft.Zelig.MetaData.MethodAttributes, needed to break the dependency of TypeSystem from MetaData. // [Flags] public enum Attributes : ushort { // member access attributes MemberAccessMask = 0x0007, // Use this mask to retrieve accessibility information. PrivateScope = 0x0000, // Member not referenceable. Private = 0x0001, // Accessible only by the parent type. FamANDAssem = 0x0002, // Accessible by sub-types only in this Assembly. Assem = 0x0003, // Accessibly by anyone in the Assembly. Family = 0x0004, // Accessible only by type and sub-types. FamORAssem = 0x0005, // Accessibly by sub-types anywhere, plus anyone in assembly. Public = 0x0006, // Accessibly by anyone who has visibility to this scope. // method contract attributes. Static = 0x0010, // Defined on type, else per instance. Final = 0x0020, // Method may not be overridden. Virtual = 0x0040, // Method virtual. HideBySig = 0x0080, // Method hides by name+sig, else just by name. // vtable layout mask - Use this mask to retrieve vtable attributes. VtableLayoutMask = 0x0100, ReuseSlot = 0x0000, // The default. NewSlot = 0x0100, // Method always gets a new slot in the vtable. Strict = 0x0200, // method implementation attributes. Abstract = 0x0400, // Method does not provide an implementation. SpecialName = 0x0800, // Method is special. Name describes how. // interop attributes PinvokeImpl = 0x2000, // Implementation is forwarded through pinvoke. UnmanagedExport = 0x0008, // Managed method exported via thunk to unmanaged code. // Reserved flags for runtime use only. ReservedMask = 0xD000, RTSpecialName = 0x1000, // Runtime should check name encoding. HasSecurity = 0x4000, // Method has security associate with it. RequireSecObject = 0x8000 // Method calls another method containing security code. } [Flags] public enum BuildTimeAttributes : uint { Inline = 0x00000001, NoInline = 0x00000002, BottomOfCallStack = 0x00000010, SaveFullProcessorContext = 0x00000020, NoReturn = 0x00000040, CanAllocate = 0x00000100, CannotAllocate = 0x00000200, CanAllocateOnReturn = 0x00000400, StackAvailable = 0x00001000, StackNotAvailable = 0x00002000, StackAvailableOnReturn = 0x00004000, EnableBoundsChecks = 0x00010000, DisableDeepBoundsChecks = 0x00020000, DisableBoundsChecks = 0x00040000, EnableNullChecks = 0x00100000, DisableNullChecks = 0x00200000, DisableDeepNullChecks = 0x00400000, //LON: 2/16/09 Exported = 0x01000000, Imported = 0x02000000, } public sealed class GenericContext { // // State // private MethodRepresentation m_template; private TypeRepresentation[] m_parameters; private GenericParameterDefinition[] m_parametersDefinition; // // Constructor Methods // public GenericContext( MethodRepresentation template, TypeRepresentation[] parameters ) { m_template = template; m_parameters = parameters; } //--// // // Helper Methods // public void ApplyTransformation( TransformationContext context ) { context.Push( this ); context.Transform( ref m_template ); context.Transform( ref m_parameters ); context.Transform( ref m_parametersDefinition ); context.Pop( ); } //--// // // Helper Methods // internal void CompleteIdentity( TypeSystem typeSystem, MetaData.Normalized.MetaDataGenericMethodParam[] genericParams, ref ConversionContext localContext ) { if( m_template == null ) { m_parametersDefinition = new GenericParameterDefinition[ genericParams.Length ]; for( int i = 0; i < genericParams.Length; i++ ) { CHECKS.ASSERT( genericParams[ i ].Number == i, "Found out of sync Generic Type Parameter definition" ); typeSystem.Analyze_GenericParameterDefinition( genericParams[ i ], ref m_parametersDefinition[ i ], ref localContext ); } } } //--// // // Access Methods // public MethodRepresentation Template { get { return m_template; } } public TypeRepresentation[] Parameters { get { return m_parameters; } } public GenericParameterDefinition[] ParametersDefinition { get { return m_parametersDefinition; } } public bool IsOpenMethod { get { if( m_parametersDefinition != null ) { if( m_parameters.Length == 0 ) { return true; } foreach( TypeRepresentation td in m_parameters ) { if( td.IsOpenType ) { return true; } } } return false; } } } public static readonly MethodRepresentation[] SharedEmptyArray = new MethodRepresentation[ 0 ]; // // State // protected TypeRepresentation m_ownerType; protected Attributes m_flags; protected BuildTimeAttributes m_buildFlags; protected string m_name; protected TypeRepresentation m_returnType; protected TypeRepresentation[] m_thisPlusArguments; protected string[] m_argumentNames; protected GenericContext m_genericContext; // // This field is used during code generation to point to the CodeRepresentation for the method. // protected object m_code; protected CodePointer m_codePointer; protected CodeMap m_codeMap; // // Only used for dumps // protected string m_fullName; public Debugging.DebugInfo DebugInfo { get { return m_DebugInfo; } set { m_DebugInfo = value; } } private Debugging.DebugInfo m_DebugInfo; // // Constructor Methods // protected MethodRepresentation( TypeRepresentation ownerType, GenericContext genericContext ) { CHECKS.ASSERT( ownerType != null, "Cannot create a MethodRepresentation without supporting metadata" ); m_ownerType = ownerType; m_genericContext = genericContext; } //--// // // MetaDataEquality Methods // public override bool EqualsThroughEquivalence( object obj, EquivalenceSet set ) { if( obj is MethodRepresentation ) { MethodRepresentation other = ( MethodRepresentation )obj; if ( m_flags == other.m_flags && m_buildFlags == other.m_buildFlags && m_name == other.m_name && EqualsThroughEquivalence( m_ownerType, other.m_ownerType, set ) && EqualsThroughEquivalence( m_returnType, other.m_returnType, set ) && ArrayEqualsThroughEquivalence( m_thisPlusArguments, other.m_thisPlusArguments, set ) && ArrayEqualsThroughEquivalence( this.GenericParameters, other.GenericParameters, set ) ) { CHECKS.ASSERT( this.GetType( ) == other.GetType( ), "Found two inconsistent MethodRepresentation" ); return true; } } return false; } public override bool Equals( object obj ) { return this.EqualsThroughEquivalence( obj, null ); } public override int GetHashCode( ) { return m_ownerType.GetHashCode( ) ^ ToShortString( ).GetHashCode( ); } public static bool operator ==( MethodRepresentation left, MethodRepresentation right ) { return Object.Equals( left, right ); } public static bool operator !=( MethodRepresentation left, MethodRepresentation right ) { return !( left == right ); } //--// // // Helper Methods // protected void Done( TypeSystem typeSystem ) { typeSystem.NotifyNewMethodComplete( this ); } internal void CompleteIdentity( TypeSystem typeSystem, ref ConversionContext context, MetaData.Normalized.MetaDataMethodAbstract md ) { if( md is MetaData.Normalized.MetaDataMethodBase ) { MetaData.Normalized.MetaDataMethodBase md2 = ( MetaData.Normalized.MetaDataMethodBase )md; m_flags = ( Attributes )md2.Flags; m_name = md2.Name; #if GENERICS_DEBUG if(m_ownerType.ToString().Contains( "Microsoft.Zelig.Runtime.KernelNode`1" ) && m_name == "InsertBefore") { } #endif ConversionContext localContext; SetLocalContext( out localContext, ref context ); m_returnType = typeSystem.ConvertToIR( md2.Signature.ReturnType, localContext ); // // We populate the arguments array with all the parameters that will be needed to call the method, 'this' pointer included. // MetaData.Normalized.SignatureType[] parameters = md2.Signature.Parameters; int argNum = parameters == null ? 0 : parameters.Length; m_thisPlusArguments = new TypeRepresentation[ 1 + argNum ]; for( int i = 0; i < argNum; i++ ) { m_thisPlusArguments[ 1 + i ] = typeSystem.ConvertToIR( parameters[ i ], localContext ); } //--// #if GENERICS TypeRepresentation td = typeSystem.CreateDelayedVersionOfGenericTypeIfNecessary( m_ownerType ); #else TypeRepresentation td = m_ownerType; #endif // // Methods for value types get a managed pointer to the value type as the "this" argument. // if( td is ValueTypeRepresentation ) { td = typeSystem.CreateManagedPointerToType( ( ValueTypeRepresentation )td ); } m_thisPlusArguments[ 0 ] = td; //--// if( md2 is MetaData.Normalized.MetaDataMethodGeneric ) { MetaData.Normalized.MetaDataMethodGeneric md3 = ( MetaData.Normalized.MetaDataMethodGeneric )md2; MetaData.Normalized.MetaDataGenericMethodParam[] genericParams = md3.GenericParams; if( genericParams != null ) { CHECKS.ASSERT( m_genericContext != null, "Defining a generic method, but {0} doesn't have a generic context", this ); m_genericContext.CompleteIdentity( typeSystem, genericParams, ref localContext ); } } } } internal void PerformMethodAnalysis( TypeSystem typeSystem, ref ConversionContext context ) { ConversionContext localContext; SetLocalContext( out localContext, ref context ); #if GENERICS typeSystem.QueueDelayedMethodAnalysis( this, ref localContext ); #else if( this.IsOpenMethod == false && this.OwnerType.IsOpenType == false ) { typeSystem.QueueDelayedMethodAnalysis( this, ref localContext ); } #endif typeSystem.QueueDelayedCustomAttributeAnalysis( this, ref localContext ); } internal void PerformDelayedCustomAttributeAnalysis( TypeSystem typeSystem, ref ConversionContext context ) { MetaData.Normalized.MetaDataMethodBase metadata = typeSystem.GetAssociatedMetaData( this ); typeSystem.ConvertToIR( metadata.CustomAttributes, context, this, -1 ); MetaData.Normalized.MetaDataParam[] paramList = metadata.ParamList; if( paramList != null ) { bool fGot = false; m_argumentNames = new string[ m_thisPlusArguments.Length ]; if( this is InstanceMethodRepresentation ) { m_argumentNames[ 0 ] = "this"; } foreach( MetaData.Normalized.MetaDataParam param in paramList ) { m_argumentNames[ param.Sequence ] = param.Name; if( param.CustomAttributes != null ) { fGot = true; } } if( fGot ) { for( int paramIndex = 0; paramIndex < paramList.Length; paramIndex++ ) { typeSystem.ConvertToIR( paramList[ paramIndex ].CustomAttributes, context, this, paramIndex ); } } } Done( typeSystem ); } //--// private void SetLocalContext( out ConversionContext localContext, ref ConversionContext context ) { localContext = context; if( this.OwnerType is ArrayReferenceTypeRepresentation ) { ; // The only methods on array types are system-generated, so keep the context as passed in. } else { localContext.SetContextAsType( this.OwnerType ); localContext.SetContextAsMethod( this ); } } //--// internal void CloneSettings( TypeSystem typeSystem, MethodRepresentation mdSource ) { m_flags = mdSource.m_flags; m_name = mdSource.m_name; m_returnType = mdSource.m_returnType; m_thisPlusArguments = ArrayUtility.CopyNotNullArray( mdSource.m_thisPlusArguments ); m_argumentNames = mdSource.m_argumentNames; TypeRepresentation td = m_ownerType; // Instance method for value types get a managed pointer to the value type as the "this" argument. if( td is ValueTypeRepresentation ) { td = typeSystem.GetManagedPointerToType( ( ValueTypeRepresentation )td ); } m_thisPlusArguments[ 0 ] = td; } //--// internal void PrepareToSubstitute( MethodRepresentation md ) { if( this is VirtualMethodRepresentation ) { if( md is VirtualMethodRepresentation ) { // // Make sure the "slottiness" is the same. // this.VTableLayoutFlags = md.VTableLayoutFlags; } else { throw TypeConsistencyErrorException.Create( "Cannot substitute a non-virtual method with a virtual one: {0} => {1}", this, md ); } } else { if( md is VirtualMethodRepresentation ) { throw TypeConsistencyErrorException.Create( "Cannot substitute a virtual method with a non-virtual one: {0} => {1}", this, md ); } } } //--// public override void ApplyTransformation( TransformationContext context ) { context.Push( this ); base.ApplyTransformation( context ); context.Transform( ref m_DebugInfo ); context.Transform( ref m_ownerType ); context.Transform( ref m_flags ); context.Transform( ref m_buildFlags ); context.Transform( ref m_name ); context.Transform( ref m_returnType ); context.Transform( ref m_thisPlusArguments ); context.Transform( ref m_argumentNames ); context.Transform( ref m_genericContext ); context.Transform( ref m_code ); context.Transform( ref m_codePointer ); context.TransformGeneric( ref m_codeMap ); context.Pop( ); } //--// public MethodRepresentation Instantiate( InstantiationContext ic ) { TypeRepresentation ownerType = ic.Instantiate( m_ownerType ); GenericContext genericContext = new GenericContext( this, ic.MethodParameters ); MethodRepresentation instantiatedMd = AllocateInstantiation( ic, ownerType, genericContext ); instantiatedMd.PopulateInstantiation( this, ic ); MethodRepresentation instantiatedMdRes = ic.Lookup( instantiatedMd, true ); if( instantiatedMdRes != null ) { return instantiatedMdRes; } else { ownerType.AddMethod( instantiatedMd ); return instantiatedMd; } } protected abstract MethodRepresentation AllocateInstantiation( InstantiationContext ic, TypeRepresentation ownerType, GenericContext genericContext ); protected virtual void PopulateInstantiation( MethodRepresentation mdTemplate, InstantiationContext ic ) { m_flags = mdTemplate.m_flags; m_buildFlags = mdTemplate.m_buildFlags; m_name = mdTemplate.m_name; m_returnType = ic.Instantiate( mdTemplate.m_returnType ); m_thisPlusArguments = ic.Instantiate( mdTemplate.m_thisPlusArguments ); m_argumentNames = mdTemplate.m_argumentNames; } //--// internal void CreateCodePointer( TypeSystem typeSystem ) { if( m_codePointer.Target == IntPtr.Zero ) { if( this.IsOpenMethod == false && m_ownerType.IsOpenType == false ) { m_codePointer = typeSystem.CreateCodePointer( this ); } } } // // Access Methods // public TypeRepresentation OwnerType { get { return m_ownerType; } } public Attributes Flags { get { return m_flags; } } public Attributes VTableLayoutFlags { get { return m_flags & MethodRepresentation.Attributes.VtableLayoutMask; } set { m_flags &= ~MethodRepresentation.Attributes.VtableLayoutMask; m_flags |= value & MethodRepresentation.Attributes.VtableLayoutMask; } } public BuildTimeAttributes BuildTimeFlags { get { return m_buildFlags; } set { m_buildFlags = value; } } public BuildTimeAttributes ExpandedBuildTimeFlags { get { var res = m_buildFlags; var tdTemplate = this.GenericTemplate; if( tdTemplate != null ) { res |= tdTemplate.ExpandedBuildTimeFlags; } return res; } } public bool HasBuildTimeFlag( BuildTimeAttributes bta ) { return ( this.ExpandedBuildTimeFlags & bta ) != 0; } public string Name { get { return m_name; } } public string FullyQualifiedName { get { if(m_fullName == null) { m_fullName = ToShortStringNoReturnValue( ); } return m_fullName; } } public TypeRepresentation ReturnType { get { return m_returnType; } } public TypeRepresentation[] ThisPlusArguments { get { return m_thisPlusArguments; } } public string[] ArgumentNames { get { return m_argumentNames; } } public bool IsGenericInstantiation { get { return this.IsOpenMethod == false && this.GenericParameters.Length > 0; } } public GenericContext Generic { get { return m_genericContext; } } public MethodRepresentation GenericTemplate { get { if( m_genericContext != null ) { return m_genericContext.Template; } return null; } } public TypeRepresentation[] GenericParameters { get { if( m_genericContext != null ) { return m_genericContext.Parameters; } return TypeRepresentation.SharedEmptyArray; } } public GenericParameterDefinition[] GenericParametersDefinition { get { if( m_genericContext != null ) { return m_genericContext.ParametersDefinition; } return null; } } public bool IsOpenMethod { get { if( m_genericContext != null ) { if( m_genericContext.IsOpenMethod ) { return true; } } return false; } } public Attributes MemberAccess { get { return m_flags & MethodRepresentation.Attributes.MemberAccessMask; } } //--// public object Code { get { return m_code; } set { m_code = value; } } public CodePointer CodePointer { get { return m_codePointer; } } public CodeMap CodeMap { get { return m_codeMap; } set { m_codeMap = value; } } //--// public CustomAttributeRepresentation FindCustomAttributeForParam( TypeRepresentation target, int param ) { return FindCustomAttributeForParam( target, param, -1 ); } public CustomAttributeRepresentation FindCustomAttributeForParam( TypeRepresentation target, int param, int index ) { return FindCustomAttribute( target, param, index ); } //--// public MethodRepresentation FindOverriddenMethod( ) { TypeRepresentation td = m_ownerType; while( true ) { td = td.Extends; if( td == null ) { break; } MethodRepresentation md = td.FindMatch( m_name, this, null ); if( md != null ) { return md; } } return null; } //--// public bool MatchNameAndSignature( string name, MethodRepresentation sig, EquivalenceSet set ) { return m_name == name && MatchSignature( sig, set ); } public bool MatchNameAndSignature( string name, TypeRepresentation returnType, TypeRepresentation[] thisPlusArguments, EquivalenceSet set ) { return m_name == name && MatchSignature( returnType, thisPlusArguments, set ); } public bool MatchSignature( MethodRepresentation sig, EquivalenceSet set ) { return MatchSignature( sig.m_returnType, sig.m_thisPlusArguments, set ); } public bool MatchSignature( TypeRepresentation returnType, TypeRepresentation[] thisPlusArguments, EquivalenceSet set ) { // // Don't compare the first argument, a method signature does not include any 'this' pointer. // if( ArrayEqualsThroughEquivalence( thisPlusArguments, m_thisPlusArguments, 1, -1, set ) ) { if( returnType.CanBeAssignedFrom( m_returnType, set ) ) { return true; } } return false; } //--// public int FindInterfaceTableIndex( ) { InterfaceTypeRepresentation itf = m_ownerType as InterfaceTypeRepresentation; if( itf != null ) { return ArrayUtility.FindInNotNullArray( itf.FindInterfaceTable( itf ), this ); } return -1; } public int FindVirtualTableIndex( ) { MethodRepresentation[] methodTable = m_ownerType.MethodTable; return ArrayUtility.FindInNotNullArray( methodTable, this ); } public MethodRepresentation FindVirtualTarget( TypeRepresentation tdTarget ) { if( tdTarget.MethodTable == null ) { // // Gracefully fail if method tables have not been initialized. // return null; } InterfaceTypeRepresentation itf = m_ownerType as InterfaceTypeRepresentation; if( itf == null ) { CHECKS.ASSERT( tdTarget.IsSubClassOf( m_ownerType, null ) || tdTarget == m_ownerType, "Cannot find virtual target in a super class" ); return tdTarget.MethodTable[ FindVirtualTableIndex( ) ]; } else { MethodRepresentation[] mdArray = tdTarget.FindInterfaceTable( itf ); CHECKS.ASSERT( mdArray != null, "Target {0} does not implement interface {1}", tdTarget.FullNameWithAbbreviation, itf.FullName ); return mdArray[ FindInterfaceTableIndex( ) ]; } } //--// // // Debug Methods // public String ToShortString() { System.Text.StringBuilder sb = new System.Text.StringBuilder(); PrettyToString(sb, includePrefix:true, includeReturnValue:true); return sb.ToString(); } public String ToShortStringNoReturnValue() { System.Text.StringBuilder sb = new System.Text.StringBuilder(); PrettyToString(sb, includePrefix: true, includeReturnValue:false); return sb.ToString(); } protected void PrettyToString(System.Text.StringBuilder sb) { PrettyToString(sb, includePrefix: true, includeReturnValue:true); } private void PrettyToString( System.Text.StringBuilder sb, bool includePrefix, bool includeReturnValue) { if (includePrefix) { if (this.IsOpenMethod) { sb.Append("generic "); } } if (includeReturnValue) { if (m_returnType != null) { m_returnType.PrettyToString(sb, includePrefix, true); sb.Append(" "); } } m_ownerType.PrettyToString(sb, includePrefix, false); sb.Append("::"); sb.Append(m_name); if (m_genericContext != null) { sb.Append("<"); TypeRepresentation[] parameters = m_genericContext.Parameters; if (parameters.Length > 0) { for (int i = 0; i < parameters.Length; i++) { if (i != 0) sb.Append(","); parameters[i].PrettyToString(sb, includePrefix, true); } } else { GenericParameterDefinition[] defs = m_genericContext.ParametersDefinition; if (defs != null) { for (int i = 0; i < defs.Length; i++) { if (i != 0) sb.Append(", "); TypeRepresentation[] genericParamConstraints = defs[i].Constraints; if (genericParamConstraints.Length > 0) { sb.Append("("); for (int j = 0; j < genericParamConstraints.Length; j++) { TypeRepresentation td = genericParamConstraints[j]; if (j != 0) { sb.Append(", "); } td.PrettyToString(sb, false, true); } sb.Append(")"); } sb.Append(defs[i].Name); } } } sb.Append(">"); } sb.Append("("); if (m_thisPlusArguments != null) { for (int i = 1; i < m_thisPlusArguments.Length; i++) { if (i != 1) sb.Append(","); TypeRepresentation arg = m_thisPlusArguments[i]; if (arg != null) { arg.PrettyToString(sb, includePrefix, true); } } } else { sb.Append("...pending..."); } sb.Append(")"); } public String ToSignatureString() { System.Text.StringBuilder sb = new System.Text.StringBuilder(); if (m_returnType != null) { m_returnType.PrettyToString(sb, fPrefix: false, fWithAbbreviations: true); sb.Append(" "); } sb.Append("("); if (m_thisPlusArguments != null) { int start = (this is StaticMethodRepresentation) ? 1 : 0; for (int i = start; i < m_thisPlusArguments.Length; i++) { if (i != start) sb.Append(","); TypeRepresentation arg = m_thisPlusArguments[i]; if (arg != null) { arg.PrettyToString(sb, fPrefix: false, fWithAbbreviations: true); } } } else { sb.Append("...pending..."); } sb.Append(")"); return sb.ToString(); } } } ================================================ FILE: Zelig/Zelig/RunTime/Zelig/TypeSystem/Methods/NotVirtualMethodRepresentation.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // namespace Microsoft.Zelig.Runtime.TypeSystem { using System; using System.Collections.Generic; #if TRANSFORMATIONCONTEXT__USE_EMIT [AllowCompileTimeIntrospection] #endif public sealed class NonVirtualMethodRepresentation : InstanceMethodRepresentation { // // Constructor Methods // public NonVirtualMethodRepresentation( TypeRepresentation ownerType , GenericContext genericContext ) : base( ownerType, genericContext ) { } //--// // // Helper Methods // protected override MethodRepresentation AllocateInstantiation( InstantiationContext ic , TypeRepresentation ownerType , GenericContext genericContext ) { return new NonVirtualMethodRepresentation( ownerType, genericContext ); } //--// // // Debug Methods // public override String ToString() { System.Text.StringBuilder sb = new System.Text.StringBuilder( "NonVirtualMethodRepresentation(" ); PrettyToString( sb ); sb.Append( ")" ); return sb.ToString(); } } } ================================================ FILE: Zelig/Zelig/RunTime/Zelig/TypeSystem/Methods/RuntimeMethodRepresentation.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // namespace Microsoft.Zelig.Runtime.TypeSystem { using System; using System.Collections.Generic; #if TRANSFORMATIONCONTEXT__USE_EMIT [AllowCompileTimeIntrospection] #endif public sealed class RuntimeMethodRepresentation : InstanceMethodRepresentation { // // Constructor Methods // public RuntimeMethodRepresentation( TypeRepresentation ownerType , GenericContext genericContext ) : base( ownerType, genericContext ) { } //--// // // Helper Methods // protected override MethodRepresentation AllocateInstantiation( InstantiationContext ic , TypeRepresentation ownerType , GenericContext genericContext ) { return new RuntimeMethodRepresentation( ownerType, genericContext ); } //--// // // Debug Methods // public override String ToString() { System.Text.StringBuilder sb = new System.Text.StringBuilder( "RuntimeMethodRepresentation(" ); PrettyToString( sb ); sb.Append( ")" ); return sb.ToString(); } } } ================================================ FILE: Zelig/Zelig/RunTime/Zelig/TypeSystem/Methods/StaticConstructorMethodRepresentation.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // namespace Microsoft.Zelig.Runtime.TypeSystem { using System; using System.Collections.Generic; #if TRANSFORMATIONCONTEXT__USE_EMIT [AllowCompileTimeIntrospection] #endif public sealed class StaticConstructorMethodRepresentation : StaticMethodRepresentation { // // Constructor Methods // public StaticConstructorMethodRepresentation( TypeRepresentation ownerType , GenericContext genericContext ) : base( ownerType, genericContext ) { } //--// // // Helper Methods // //--// // // Debug Methods // public override String ToString() { System.Text.StringBuilder sb = new System.Text.StringBuilder( "StaticConstructorMethodRepresentation(" ); PrettyToString( sb ); sb.Append( ")" ); return sb.ToString(); } } } ================================================ FILE: Zelig/Zelig/RunTime/Zelig/TypeSystem/Methods/StaticMethodRepresentation.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // namespace Microsoft.Zelig.Runtime.TypeSystem { using System; using System.Collections.Generic; #if TRANSFORMATIONCONTEXT__USE_EMIT [AllowCompileTimeIntrospection] #endif public class StaticMethodRepresentation : MethodRepresentation { // // Constructor Methods // public StaticMethodRepresentation( TypeRepresentation ownerType , GenericContext genericContext ) : base( ownerType, genericContext ) { } //--// // // Helper Methods // protected override MethodRepresentation AllocateInstantiation( InstantiationContext ic , TypeRepresentation ownerType , GenericContext genericContext ) { return new StaticMethodRepresentation( ownerType, genericContext ); } //--// // // Debug Methods // public override String ToString() { System.Text.StringBuilder sb = new System.Text.StringBuilder( "StaticMethodRepresentation(" ); PrettyToString( sb ); sb.Append( ")" ); return sb.ToString(); } } } ================================================ FILE: Zelig/Zelig/RunTime/Zelig/TypeSystem/Methods/VirtualMethodRepresentation.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // namespace Microsoft.Zelig.Runtime.TypeSystem { using System; using System.Collections.Generic; #if TRANSFORMATIONCONTEXT__USE_EMIT [AllowCompileTimeIntrospection] #endif public class VirtualMethodRepresentation : InstanceMethodRepresentation { // // Constructor Methods // public VirtualMethodRepresentation( TypeRepresentation ownerType , GenericContext genericContext ) : base( ownerType, genericContext ) { } //--// // // Helper Methods // protected override MethodRepresentation AllocateInstantiation( InstantiationContext ic , TypeRepresentation ownerType , GenericContext genericContext ) { return new VirtualMethodRepresentation( ownerType, genericContext ); } //--// internal void Override( TypeSystem typeSystem , VirtualMethodRepresentation mdSource ) { CloneSettings( typeSystem, mdSource ); //--// if((m_ownerType.Flags & TypeRepresentation.Attributes.Sealed) != 0) { m_flags |= Attributes.Final; } this.VTableLayoutFlags = Attributes.ReuseSlot; m_flags &= ~Attributes.Abstract; m_flags &= ~Attributes.SpecialName; m_flags &= ~Attributes.PinvokeImpl; m_flags &= ~Attributes.UnmanagedExport; } //--// // // Debug Methods // public override String ToString() { System.Text.StringBuilder sb = new System.Text.StringBuilder( "VirtualMethodRepresentation(" ); PrettyToString( sb ); sb.Append( ")" ); return sb.ToString(); } } } ================================================ FILE: Zelig/Zelig/RunTime/Zelig/TypeSystem/Properties/AssemblyInfo.cs ================================================ using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; // General Information about an assembly is controlled through the following // set of attributes. Change these attribute values to modify the information // associated with an assembly. [assembly: AssemblyTitle( "Microsoft.Zelig.Runtime.TypeSystem" )] [assembly: AssemblyDescription( "" )] [assembly: AssemblyConfiguration( "" )] [assembly: AssemblyCompany( "Microsoft" )] [assembly: AssemblyProduct( "Microsoft.Zelig.Runtime.TypeSystem" )] [assembly: AssemblyCopyright( "Copyright © Microsoft 2006" )] [assembly: AssemblyTrademark( "" )] [assembly: AssemblyCulture( "" )] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible( false )] //// The following GUID is for the ID of the typelib if this project is exposed to COM //[assembly: Guid( "57de0ebe-e971-4cb9-8985-5f6b66934a91" )] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Revision and Build Numbers // by using the '*' as shown below: [assembly: AssemblyVersion( "1.0.0.0" )] [assembly: AssemblyFileVersion( "1.0.0.0" )] ================================================ FILE: Zelig/Zelig/RunTime/Zelig/TypeSystem/ResourceRepresentation.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // namespace Microsoft.Zelig.Runtime.TypeSystem { using System; using System.Collections.Generic; public sealed class ResourceRepresentation { // // This is just a copy of Microsoft.Zelig.MetaData.ManifestResourceAttributes, needed to break the dependency of TypeSystem from MetaData. // [Flags] public enum Attributes { VisibilityMask = 0x0007, Public = 0x0001, // The Resource is exported from the Assembly. Private = 0x0002 // The Resource is private to the Assembly. } [AllowCompileTimeIntrospection] public class Pair { // // State // public readonly string Key; public readonly object Value; // // Constructor Methods // public Pair( string key , object value ) { this.Key = key; this.Value = value; } } // // State // private AssemblyRepresentation m_owner; private Attributes m_flags; private string m_name; private Pair[] m_values; // // Constructor Methods // public ResourceRepresentation( AssemblyRepresentation owner ) { m_owner = owner; } // // MetaDataEquality Methods // public override bool Equals( object obj ) { if(obj is ResourceRepresentation) { ResourceRepresentation other = (ResourceRepresentation)obj; if(m_owner == other.m_owner && m_name == other.m_name ) { return true; } } return false; } public override int GetHashCode() { return m_name.GetHashCode(); } //--// // // Helper Methods // public void ApplyTransformation( TransformationContext context ) { context.Push( this ); context.Transform( ref m_owner ); context.Transform( ref m_flags ); context.Transform( ref m_name ); context.Transform( ref m_values ); context.Pop(); } //--// internal void CompleteIdentity( TypeSystem typeSystem , ref ConversionContext context , MetaData.Normalized.MetaDataManifestResource res ) { m_flags = (Attributes)res.Flags; m_name = res.Name; string suffix = ".resources"; if(m_name.EndsWith( suffix )) { m_name = m_name.Substring( 0, m_name.Length - suffix.Length ); } var table = res.Values; if(table != null) { int pos = 0; int num = table.Count; Pair[] pairs = new Pair[num]; foreach(string key in table.Keys) { pairs[pos++] = new Pair( key, table[key] ); } m_values = pairs; } } //--// // // Access Methods // public AssemblyRepresentation Owner { get { return m_owner; } } public Attributes Flags { get { return m_flags; } } public string Name { get { return m_name; } } public Pair[] Values { get { return m_values; } } } } ================================================ FILE: Zelig/Zelig/RunTime/Zelig/TypeSystem/StackEquivalentType.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // namespace Microsoft.Zelig.Runtime.TypeSystem { using System; using System.Collections.Generic; public enum StackEquivalentType { Void , Int32 , Int64 , NativeInt, Float , Pointer , Object , } } ================================================ FILE: Zelig/Zelig/RunTime/Zelig/TypeSystem/TransformationContext.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // //#define TRANSFORMATIONCONTEXT__USE_EMIT //#define TRANSFORMATIONCONTEXT_SHOWALLMETHODSTODEBUGGER namespace Microsoft.Zelig.Runtime.TypeSystem { using System; using System.Collections.Generic; public interface ITransformationContextTarget { void ApplyTransformation( TransformationContext context ); } public abstract class TransformationContext : IDisposable { private delegate void DelayedUpdate(); protected delegate object DynamicTransform( TransformationContext pThis, object obj, Type t ); // // State // private GrowOnlyHashTable< Type, System.Reflection.FieldInfo[] > m_fields; private List< DelayedUpdate > m_delayedUpdates; protected DynamicTransform m_dynamicTransform; // // Helper Methods // public virtual void Dispose() { } //--// protected abstract void ClearPending(); protected abstract bool ShouldTransform( object target ); protected virtual bool ShouldRefreshHashCodes() { return false; } public abstract void MarkAsVisited( object obj ); public abstract void Push ( object obj ); public abstract void Pop ( ); public abstract object TopContext ( ); public abstract object FindContext ( Type ctx ); public abstract object GetTransformInitiator(); public abstract TypeSystem GetTypeSystem(); //--// public abstract void Transform( ref ITransformationContextTarget itf ); public abstract void Transform( ref bool val ); public abstract void Transform( ref char val ); public abstract void Transform( ref sbyte val ); public abstract void Transform( ref byte val ); public abstract void Transform( ref short val ); public abstract void Transform( ref ushort val ); public abstract void Transform( ref int val ); public abstract void Transform( ref uint val ); public abstract void Transform( ref long val ); public abstract void Transform( ref ulong val ); public abstract void Transform( ref float val ); public abstract void Transform( ref double val ); public abstract void Transform( ref IntPtr val ); public abstract void Transform( ref UIntPtr val ); public abstract void Transform( ref string val ); public abstract void Transform( ref object val ); public abstract void Transform( ref Type val ); public abstract void Transform( ref bool[] valArray ); public abstract void Transform( ref char[] valArray ); public abstract void Transform( ref sbyte[] valArray ); public abstract void Transform( ref byte[] valArray ); public abstract void Transform( ref short[] valArray ); public abstract void Transform( ref ushort[] valArray ); public abstract void Transform( ref int[] valArray ); public abstract void Transform( ref uint[] valArray ); public abstract void Transform( ref long[] valArray ); public abstract void Transform( ref ulong[] valArray ); public abstract void Transform( ref float[] valArray ); public abstract void Transform( ref double[] valArray ); public abstract void Transform( ref IntPtr[] valArray ); public abstract void Transform( ref UIntPtr[] valArray ); public abstract void Transform( ref string[] valArray ); public abstract void Transform( ref object[] valArray ); public abstract void Transform( ref List< string > strLst ); public abstract void Transform( ref Debugging.DebugInfo debugInfo ); public abstract void Transform( ref WellKnownTypes wkt ); public abstract void Transform( ref WellKnownMethods wkm ); public abstract void Transform( ref WellKnownFields wkf ); public abstract void Transform( ref AssemblyRepresentation asml ); public abstract void Transform( ref List< AssemblyRepresentation > asmlLst ); public abstract void Transform( ref AssemblyRepresentation.VersionData ver ); public abstract void Transform( ref AssemblyRepresentation.VersionData.AssemblyFlags val ); public abstract void Transform( ref BaseRepresentation bd ); public abstract void Transform( ref TypeRepresentation td ); public abstract void Transform( ref ValueTypeRepresentation td ); public abstract void Transform( ref ArrayReferenceTypeRepresentation td ); public abstract void Transform( ref InterfaceTypeRepresentation itf ); public abstract void Transform( ref TypeRepresentation[] tdArray ); public abstract void Transform( ref InterfaceTypeRepresentation[] itfArray ); public abstract void Transform( ref List< TypeRepresentation > tdLst ); public abstract void Transform( ref FieldRepresentation fd ); public abstract void Transform( ref InstanceFieldRepresentation fd ); public abstract void Transform( ref StaticFieldRepresentation fd ); public abstract void Transform( ref FieldRepresentation[] fdArray ); public abstract void Transform( ref InstanceFieldRepresentation[] fdArray ); public abstract void Transform( ref MethodRepresentation md ); public abstract void Transform( ref MethodRepresentation[] mdArray ); public abstract void Transform( ref List mdList ); public abstract void Transform( ref MethodImplRepresentation mi ); public abstract void Transform( ref MethodImplRepresentation[] miArray ); public abstract void Transform( ref GenericParameterDefinition param ); public abstract void Transform( ref GenericParameterDefinition[] paramArray ); public abstract void Transform( ref CustomAttributeRepresentation ca ); public abstract void Transform( ref CustomAttributeRepresentation[] caArray ); public abstract void Transform( ref CustomAttributeAssociationRepresentation caa ); public abstract void Transform( ref CustomAttributeAssociationRepresentation[] caaArray ); public abstract void Transform( ref ResourceRepresentation res ); public abstract void Transform( ref List< ResourceRepresentation > resLst ); public abstract void Transform( ref ResourceRepresentation.Attributes val ); public abstract void Transform( ref ResourceRepresentation.Pair[] pairArray ); public abstract void Transform( ref VTable vTable ); public abstract void Transform( ref VTable.InterfaceMap iMap ); public abstract void Transform( ref GCInfo gi ); public abstract void Transform( ref GCInfo.Kind giKind ); public abstract void Transform( ref GCInfo.Pointer giPtr ); public abstract void Transform( ref GCInfo.Pointer[] giPtrArray ); public abstract void Transform( ref CodePointer cp ); public abstract void Transform( ref CodePointer[] cpArray ); public abstract void Transform( ref TypeRepresentation.BuiltInTypes val ); public abstract void Transform( ref TypeRepresentation.Attributes val ); public abstract void Transform( ref TypeRepresentation.BuildTimeAttributes val ); public abstract void Transform( ref TypeRepresentation.GenericContext gc ); public abstract void Transform( ref TypeRepresentation.InterfaceMap map ); public abstract void Transform( ref FieldRepresentation.Attributes val ); public abstract void Transform( ref GenericParameterDefinition.Attributes val ); public abstract void Transform( ref MethodRepresentation.Attributes val ); public abstract void Transform( ref MethodRepresentation.BuildTimeAttributes val ); public abstract void Transform( ref MethodRepresentation.GenericContext gc ); public abstract void Transform( ref MultiArrayReferenceTypeRepresentation.Dimension dim ); public abstract void Transform( ref MultiArrayReferenceTypeRepresentation.Dimension[] dimArray ); public abstract void Transform( ref ActivationRecordEvents val ); //--// public void Transform( ref BitVector vec ) { ClearPending(); if(vec != null && ShouldTransform( vec )) { this.Push( vec ); uint[] bitArray = vec.ToDirectArray(); Transform( ref bitArray ); this.Pop(); } } public void Transform( ref TypeSystem.Reachability reachability ) { ClearPending(); reachability.ApplyTransformation( this ); } public void Transform( ref GrowOnlySet< object > set ) { TransformContents( set ); } public void Transform( ref GrowOnlySet< FieldRepresentation > set ) { TransformContents( set ); } //--// public void Transform( ref GrowOnlyHashTable< FieldRepresentation, object > ht ) { TransformContents( ht ); } public void Transform( ref GrowOnlyHashTable< InstanceFieldRepresentation, object > ht ) { TransformContents( ht ); } public void Transform( ref GrowOnlyHashTable< string, TypeRepresentation > ht ) { TransformContents( ht ); } public void Transform( ref GrowOnlyHashTable< string, MethodRepresentation > ht ) { TransformContents( ht ); } public void Transform( ref GrowOnlyHashTable< string, FieldRepresentation > ht ) { TransformContents( ht ); } //--// public void TransformGeneric( ref T obj ) { object val = obj; Transform( ref val ); obj = (T)val; } public void TransformFields( T val ) { this.Push( val ); TransformFields( (object)val, typeof(T) ); this.Pop(); } //--// protected void TransformContents< K, V >( GrowOnlyHashTable< K, V > val ) where K : class where V : class { ClearPending(); if(val != null && ShouldTransform( val )) { this.Push( val ); K[] keys = val.KeysToArray(); V[] values = val.ValuesToArray(); K[] keysWork = val.KeysToArray(); V[] valuesWork = val.ValuesToArray(); object keysObj = keysWork ; Transform( ref keysObj ); object valuesObj = valuesWork; Transform( ref valuesObj ); keysWork = (K[])keysObj; valuesWork = (V[])valuesObj; if(ArrayUtility.ArrayReferenceEqualsNotNull( keys , keysWork , 0 ) == false || ArrayUtility.ArrayReferenceEqualsNotNull( values, valuesWork, 0 ) == false ) { AddDelayedUpdate( delegate() { val.Load( keysWork, valuesWork ); } ); } else if(ShouldRefreshHashCodes()) { val.RefreshHashCodes(); } this.Pop(); } } protected void TransformValueTypeContents< K, V >( GrowOnlyHashTable< K, V > val ) where K : class where V : struct { ClearPending(); if(val != null && ShouldTransform( val )) { this.Push( val ); K[] keys = val.KeysToArray(); V[] values = val.ValuesToArray(); K[] keysWork = val.KeysToArray(); V[] valuesWork = val.ValuesToArray(); object keysObj = keysWork ; Transform( ref keysObj ); object valuesObj = valuesWork; Transform( ref valuesObj ); keysWork = (K[])keysObj; valuesWork = (V[])valuesObj; if(ArrayUtility.ArrayReferenceEqualsNotNull( keys , keysWork , 0 ) == false || ArrayUtility.ArrayEqualsNotNull ( values, valuesWork, 0 ) == false ) { AddDelayedUpdate( delegate() { val.Load( keysWork, valuesWork ); } ); } else if(ShouldRefreshHashCodes()) { val.RefreshHashCodes(); } this.Pop(); } } protected void TransformContents< K >( GrowOnlySet< K > val ) where K : class { ClearPending(); if(val != null && ShouldTransform( val )) { this.Push( val ); K[] keys = val.ToArray(); K[] keysWork = val.ToArray(); object keysObj = keysWork; Transform( ref keysObj ); keysWork = (K[])keysObj; if(ArrayUtility.ArrayReferenceEqualsNotNull( keys, keysWork, 0 ) == false) { AddDelayedUpdate( delegate() { val.Load( keysWork ); } ); } else if(ShouldRefreshHashCodes()) { val.RefreshHashCodes(); } this.Pop(); } } //--// protected abstract void TransformArray( ref Array array ); #if !TRANSFORMATIONCONTEXT_SHOWALLMETHODSTODEBUGGER [System.Diagnostics.DebuggerHidden] #endif protected virtual object TransformGenericReference( object obj ) { if(obj == null) { return obj; } if(obj is ITransformationContextTarget) { ITransformationContextTarget target = (ITransformationContextTarget)obj; Transform( ref target ); return target; } DynamicTransform dlg = GetDynamicTransform(); Type t = obj.GetType(); #if TRANSFORMATIONCONTEXT__USE_EMIT if(this.IsReader && obj is MethodRepresentation) { if(ReflectionHelper.GetAttribute( t, false ) != null) { return TransformThroughReflection( obj ); } } #endif object obj2 = dlg( this, obj, t ); if(Object.ReferenceEquals( obj2, this ) == false) { return obj2; } if(obj is Array) { Array array = (Array)obj; TransformArray( ref array ); return array; } if(ReflectionHelper.GetAttribute< AllowCompileTimeIntrospectionAttribute >( t, false ) != null) { return TransformThroughReflection( obj ); } throw TypeConsistencyErrorException.Create( "Unexpected type {0}", t ); } protected abstract object TransformThroughReflection( object obj ); //--// protected void TransformFields( object obj , Type target ) { while(target != null) { if(m_fields == null) { m_fields = HashTableFactory.New< Type, System.Reflection.FieldInfo[] >(); } System.Reflection.FieldInfo[] fiArray; if(m_fields.TryGetValue( target, out fiArray ) == false) { fiArray = ReflectionHelper.GetAllInstanceFields( target ); m_fields[target] = fiArray; } foreach(System.Reflection.FieldInfo fi in fiArray) { object val = fi.GetValue( obj ); object valPost = val; Transform( ref valPost ); if(Object.ReferenceEquals( val, valPost ) == false) { fi.SetValue( obj, valPost ); } } target = target.BaseType; } } //--// #if !TRANSFORMATIONCONTEXT_SHOWALLMETHODSTODEBUGGER [System.Diagnostics.DebuggerHidden] #endif private void AddDelayedUpdate( DelayedUpdate dlg ) { if(m_delayedUpdates == null) { m_delayedUpdates = new List< DelayedUpdate >(); } m_delayedUpdates.Add( dlg ); } protected void RunDelayedUpdates() { while(true) { List< DelayedUpdate > lst = m_delayedUpdates; if(lst == null) { break; } m_delayedUpdates = null; foreach(DelayedUpdate dlg in lst) { dlg(); } } } //--// protected GrowOnlyHashTable< Type, System.Reflection.MethodInfo > BuildMethodInfoTable() { GrowOnlyHashTable< Type, System.Reflection.MethodInfo > handlers = HashTableFactory.NewWithReferenceEquality< Type, System.Reflection.MethodInfo >(); Type t = this.GetType(); while(t != null) { foreach(System.Reflection.MethodInfo mi in t.GetMethods( System.Reflection.BindingFlags.Public | System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.Instance )) { if(mi.Name == "Transform" && mi.IsAbstract == false) { System.Reflection.ParameterInfo[] parameters = mi.GetParameters(); if(parameters != null && parameters.Length == 1) { System.Reflection.ParameterInfo paramInfo = parameters[0]; Type paramType = paramInfo.ParameterType; if(paramType.IsByRef) { Type elementType = paramType.GetElementType(); if(elementType != typeof(object)) { handlers[elementType] = mi; } } } } } t = t.BaseType; } return handlers; } protected abstract GrowOnlyHashTable< Type, System.Reflection.MethodInfo > GetMethodInfoTable(); protected abstract DynamicTransform GetDynamicTransform(); protected abstract DynamicTransform BuildDynamicTransform(); #if TRANSFORMATIONCONTEXT__USE_EMIT public abstract bool IsReader { get; } #endif } } ================================================ FILE: Zelig/Zelig/RunTime/Zelig/TypeSystem/TypeSystem.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // //#define TYPESYSTEM_REPORT //#define TYPESYSTEM_REPORT_VERBOSE ////#define TYPESYSTEM_REDUCE_FOOTPRINT namespace Microsoft.Zelig.Runtime.TypeSystem { using System; using System.Collections.Generic; using System.IO; using System.Runtime.CompilerServices; using Microsoft.Zelig.MetaData.Normalized; public delegate void FieldEnumerationCallback( FieldRepresentation fd ); public delegate void MethodEnumerationCallback( MethodRepresentation md ); public class TypeSystem { public delegate void NotificationOfAttributeOnGeneric( ref bool fKeep, CustomAttributeRepresentation ca, BaseRepresentation owner ); public delegate void NotificationOfAttributeOnType ( ref bool fKeep, CustomAttributeRepresentation ca, TypeRepresentation owner ); public delegate void NotificationOfAttributeOnField ( ref bool fKeep, CustomAttributeRepresentation ca, FieldRepresentation owner ); public delegate void NotificationOfAttributeOnMethod ( ref bool fKeep, CustomAttributeRepresentation ca, MethodRepresentation owner ); public delegate void NotificationOfAttributeOnParam ( ref bool fKeep, CustomAttributeRepresentation ca, MethodRepresentation owner, int paramIndex ); public delegate void NotificationOfNewAssembly( AssemblyRepresentation asml ); public delegate void NotificationOfNewType ( TypeRepresentation td ); public delegate void NotificationOfNewField ( FieldRepresentation fd ); public delegate void NotificationOfNewMethod ( MethodRepresentation md ); public delegate bool TypeLayoutCallback( TypeRepresentation td, GrowOnlySet< TypeRepresentation > history ); //--// public class Reachability { // // State // GrowOnlySet< object > m_prohibited; GrowOnlySet< object > m_included; GrowOnlySet< object > m_pending; // // Constructor Methods // public Reachability() { m_prohibited = SetFactory.NewWithWeakEquality< object >(); m_included = SetFactory.NewWithWeakEquality< object >(); m_pending = SetFactory.NewWithWeakEquality< object >(); } private Reachability( GrowOnlySet< object > prohibited , GrowOnlySet< object > included , GrowOnlySet< object > pending ) { m_prohibited = prohibited; m_included = included; m_pending = pending; } // // Helper Methods // public void ApplyTransformation( TransformationContext context ) { context.Push( this ); context.Transform( ref m_prohibited ); context.Pop(); } public Reachability CloneForProhibitionEstimation() { GrowOnlySet< object > prohibited = m_prohibited.Clone(); GrowOnlySet< object > included = m_included; GrowOnlySet< object > pending = m_pending; return new Reachability( prohibited, included, pending ); } public Reachability CloneForIncrementalUpdate() { GrowOnlySet< object > prohibited = m_prohibited; GrowOnlySet< object > included = m_included; GrowOnlySet< object > pending = m_pending.Clone(); return new Reachability( prohibited, included, pending ); } public static Reachability CreateForUpdate( GrowOnlySet< object > set ) { GrowOnlySet< object > prohibited = null; GrowOnlySet< object > included = SetFactory.NewWithWeakEquality< object >(); GrowOnlySet< object > pending = set; return new Reachability( prohibited, included, pending ); } //--// public void RestartComputation() { m_included.Clear(); m_pending .Clear(); } public bool HasPendingItems() { return m_pending.Count > 0; } public object[] ApplyPendingSet( bool fUpdateIncluded ) { object[] res; lock(m_pending) { if(m_pending.Count == 0) { return null; } res = m_pending.ToArray(); m_pending.Clear(); } if(fUpdateIncluded) { lock(m_included) { foreach(object obj in res) { m_included.Insert( obj ); } } } return res; } //--// public bool Contains( object obj ) { CHECKS.ASSERT( obj != null, "Cannot use a null reference in Reachability.Contains calls" ); lock(m_included) { return m_included.Contains( obj ); } } public bool PendingContains( object obj ) { CHECKS.ASSERT( obj != null, "Cannot use a null reference in Reachability.PendingContains calls" ); lock(m_pending) { return m_pending.Contains( obj ); } } public bool IsProhibited( object obj ) { CHECKS.ASSERT( obj != null, "Cannot use a null reference in Reachability.IsProhibited calls" ); if(m_prohibited == null) { return false; } lock(m_prohibited) { return m_prohibited.Contains( obj ); } } //--// public bool ExpandProhibition( object obj ) { CHECKS.ASSERT( obj != null, "Cannot use a null reference in Reachability.ExpandProhibition calls" ); lock(m_prohibited) { return m_prohibited.Insert( obj ); } } public bool ExpandPending( object obj ) { CHECKS.ASSERT( obj != null, "Cannot use a null reference in Reachability.ExpandPending calls" ); if(m_included != null) { // is the lock needed? lock(m_included) { if(m_included.Contains( obj )) { return true; } } } lock(m_pending) { if(m_pending.Insert( obj )) { return true; } return false; } } // // Access Methods // public GrowOnlySet< object > ProhibitedSet { get { return m_prohibited; } } public GrowOnlySet< object > IncludedSet { get { return m_included; } } } //--// protected class PendingAnalysis { public delegate void Invoke( T target, ref ConversionContext context ); // // State // internal PendingAnalysis m_next; internal Invoke m_dlg; public T m_target; public ConversionContext m_context; //--// // // Debug Methods // public override string ToString() { System.Text.StringBuilder sb = new System.Text.StringBuilder(); sb.Append( m_target ); m_context.InnerToString( sb ); return sb.ToString(); } } protected class PendingAnalysisQueue { // // State // internal PendingAnalysis m_first; internal PendingAnalysis m_last; //--// public int Count { get { PendingAnalysis pa = m_first; if(pa == null) { return 0; } int count = 1; while(pa.m_next != null) { pa = pa.m_next; count++; } return count; } } public void Schedule( T target , ref ConversionContext context , PendingAnalysis.Invoke dlg ) { PendingAnalysis pa = new PendingAnalysis(); if(m_first == null) { m_first = pa; } if(m_last != null) { m_last.m_next = pa; } m_last = pa; pa.m_target = target; pa.m_context = context; pa.m_dlg = dlg; } public bool Dispatch() { PendingAnalysis pa = m_first; if(pa == null) { return false; } m_first = pa.m_next; if(m_last == pa) { m_last = null; } pa.m_dlg( pa.m_target, ref pa.m_context ); return true; } } internal struct Lookup : IEquatable< Lookup > where T : MetaDataObject { // // State // internal T m_metadata; internal ConversionContext m_context; // // MetaDataEquality Methods // public override bool Equals( object obj ) { if(obj is Lookup) { return Equals( (Lookup)obj ); } return false; } public bool Equals( Lookup other ) { if(m_metadata.Equals ( other.m_metadata ) && m_context .SameContents( ref other.m_context ) ) { return true; } return false; } public override int GetHashCode() { int result = m_metadata.GetHashCode(); foreach(TypeRepresentation td in m_context.m_typeContext) { result ^= td.GetHashCode(); } foreach(TypeRepresentation td in m_context.m_methodContext) { result ^= td.GetHashCode(); } return result; } //--// // // Debug Methods // public override string ToString() { System.Text.StringBuilder sb = new System.Text.StringBuilder(); if(m_metadata is MetaDataMethodBase) { MetaDataMethodBase md = (MetaDataMethodBase)(object)m_metadata; md.PrettyPrintSignature( sb ); } else { sb.Append( m_metadata ); } m_context.InnerToString( sb ); return sb.ToString(); } internal void Set( T metadata , ref ConversionContext context ) { m_metadata = metadata; m_context = context; if(metadata.UsesTypeParameters == false) { m_context.m_typeContextOwner = null; m_context.m_typeContext = TypeRepresentation.SharedEmptyArray; } if(metadata.UsesMethodParameters == false) { m_context.m_methodContextOwner = null; m_context.m_methodContext = TypeRepresentation.SharedEmptyArray; } } internal void Set( T metadata , TypeRepresentation owner ) { m_metadata = metadata; m_context.SetContextAsType( owner ); } } protected class CustomAttributeNotification { // // State // internal NotificationOfAttributeOnGeneric m_notificationOfAttributeOnGeneric; internal NotificationOfAttributeOnType m_notificationOfAttributeOnType; internal NotificationOfAttributeOnField m_notificationOfAttributeOnField; internal NotificationOfAttributeOnMethod m_notificationOfAttributeOnMethod; internal NotificationOfAttributeOnParam m_notificationOfAttributeOnParam; } // // State // private MethodRepresentation m_applicationEntryPoint; private List < AssemblyRepresentation > m_assemblies; private List < TypeRepresentation > m_types; private List < ResourceRepresentation > m_resources; private List < MethodRepresentation > m_exportedMethods; private GrowOnlyHashTable < FieldRepresentation, object > m_defaultValues; private InstantiationContext m_instantiationContext; private AssemblyRepresentation m_required_mscorlib; private WellKnownTypes m_wellKnownTypes; private WellKnownMethods m_wellKnownMethods; private WellKnownFields m_wellKnownFields; private GrowOnlyHashTable< string, TypeRepresentation > m_wellKnownTypesByName; private GrowOnlyHashTable< string, MethodRepresentation > m_wellKnownMethodsByName; private GrowOnlyHashTable< string, FieldRepresentation > m_wellKnownFieldsByName; // // These fields are used only during the MetaData import phase. // protected IEnvironmentProvider m_environmentProvider; private GrowOnlyHashTable < MetaDataAssembly , AssemblyRepresentation > m_lookupAssemblies; private GrowOnlyHashTable < Lookup< MetaDataTypeDefinitionAbstract >, TypeRepresentation > m_lookupTypes; private GrowOnlyHashTable < Lookup< MetaDataField >, FieldRepresentation > m_lookupFields; private GrowOnlyHashTable < Lookup< MetaDataMethodAbstract >, MethodRepresentation > m_lookupMethods; private GrowOnlyHashTable < Lookup< MetaDataCustomAttribute >, CustomAttributeRepresentation > m_lookupAttributes; private GrowOnlyHashTable < Lookup< MetaDataManifestResource >, ResourceRepresentation > m_lookupResources; private GrowOnlyHashTable < AssemblyRepresentation, MetaDataAssembly > m_reverseLookupAssemblies; private GrowOnlyHashTable < TypeRepresentation , Lookup< MetaDataTypeDefinitionAbstract > > m_reverseLookupTypes; private GrowOnlyHashTable < FieldRepresentation , Lookup< MetaDataField > > m_reverseLookupFields; private GrowOnlyHashTable < MethodRepresentation , Lookup< MetaDataMethodAbstract > > m_reverseLookupMethods; private NotificationOfNewAssembly m_notificationOfNewAssembly; private NotificationOfNewType m_notificationOfNewType; private NotificationOfNewField m_notificationOfNewField; private NotificationOfNewMethod m_notificationOfNewMethod; private GrowOnlyHashTable < TypeRepresentation , CustomAttributeNotification > m_customAttributeNotification; private GrowOnlyHashTable < TypeRepresentation , TypeLayoutCallback > m_layoutDelegation; private PendingAnalysisQueue< TypeRepresentation > m_pendingTypeAnalysis; private PendingAnalysisQueue< MethodRepresentation > m_pendingMethodAnalysis; private PendingAnalysisQueue< TypeRepresentation > m_pendingTypeCustomAttributeAnalysis; private PendingAnalysisQueue< MethodRepresentation > m_pendingMethodCustomAttributeAnalysis; private GenericInstantiationClosure m_genericRecursionCheck; // // Constructor Methods // protected TypeSystem( IEnvironmentProvider env ) { m_environmentProvider = env; m_assemblies = new List < AssemblyRepresentation >(); m_types = new List < TypeRepresentation >(); m_resources = new List < ResourceRepresentation >(); m_exportedMethods = new List < MethodRepresentation >(); m_defaultValues = HashTableFactory.New< FieldRepresentation, object >(); m_instantiationContext = new InstantiationContext(); m_wellKnownTypes = new WellKnownTypes (); m_wellKnownMethods = new WellKnownMethods(); m_wellKnownFields = new WellKnownFields (); m_wellKnownTypesByName = HashTableFactory.New< string, TypeRepresentation >(); m_wellKnownMethodsByName = HashTableFactory.New< string, MethodRepresentation >(); m_wellKnownFieldsByName = HashTableFactory.New< string, FieldRepresentation >(); } // // Helper Methods // public void InitializeForCompilation() { InitializeForMetaDataImport(); BootstrapMetaData(); RegisterMetaDataNotifications(); } protected virtual void InitializeForMetaDataImport() { m_lookupAssemblies = HashTableFactory.New< MetaDataAssembly , AssemblyRepresentation >(); m_lookupTypes = HashTableFactory.New< Lookup< MetaDataTypeDefinitionAbstract >, TypeRepresentation >(); m_lookupFields = HashTableFactory.New< Lookup< MetaDataField >, FieldRepresentation >(); m_lookupMethods = HashTableFactory.New< Lookup< MetaDataMethodAbstract >, MethodRepresentation >(); m_lookupAttributes = HashTableFactory.New< Lookup< MetaDataCustomAttribute >, CustomAttributeRepresentation >(); m_lookupResources = HashTableFactory.New< Lookup< MetaDataManifestResource >, ResourceRepresentation >(); //--// m_reverseLookupAssemblies = HashTableFactory.New< AssemblyRepresentation, MetaDataAssembly >(); m_reverseLookupTypes = HashTableFactory.New< TypeRepresentation , Lookup< MetaDataTypeDefinitionAbstract > >(); m_reverseLookupFields = HashTableFactory.New< FieldRepresentation , Lookup< MetaDataField > >(); m_reverseLookupMethods = HashTableFactory.New< MethodRepresentation , Lookup< MetaDataMethodAbstract > >(); //--// m_customAttributeNotification = HashTableFactory.New< TypeRepresentation, CustomAttributeNotification >(); m_layoutDelegation = HashTableFactory.New< TypeRepresentation, TypeLayoutCallback >(); m_pendingTypeAnalysis = new PendingAnalysisQueue< TypeRepresentation >(); m_pendingMethodAnalysis = new PendingAnalysisQueue< MethodRepresentation >(); m_pendingTypeCustomAttributeAnalysis = new PendingAnalysisQueue< TypeRepresentation >(); m_pendingMethodCustomAttributeAnalysis = new PendingAnalysisQueue< MethodRepresentation >(); m_genericRecursionCheck = new GenericInstantiationClosure(); } protected virtual void RegisterMetaDataNotifications() { } protected virtual void CleanupAfterMetaDataImport() { m_lookupAssemblies = null; m_lookupTypes = null; m_lookupFields = null; m_lookupMethods = null; m_lookupAttributes = null; m_lookupResources = null; //--// m_reverseLookupAssemblies = null; m_reverseLookupTypes = null; m_reverseLookupFields = null; m_reverseLookupMethods = null; //--// m_customAttributeNotification = null; m_pendingTypeAnalysis = null; m_pendingMethodAnalysis = null; m_pendingTypeCustomAttributeAnalysis = null; m_pendingMethodCustomAttributeAnalysis = null; m_genericRecursionCheck = null; } public virtual void RefreshHashCodesAfterTypeSystemRemapping() { // // We only need to refresh the hash codes for the collections that are not covered by ApplyTransformation. // m_layoutDelegation.RefreshHashCodes(); m_instantiationContext.RefreshHashCodes(); } //--// private void BootstrapMetaData() { IMetaDataBootstrap bootstrap = GetEnvironmentService< IMetaDataBootstrap >(); MetaDataAssembly mscorlib = bootstrap.GetAssembly( "mscorlib" ); m_required_mscorlib = ConvertToIR( mscorlib ); PopulateWellKnownTypes( bootstrap ); m_applicationEntryPoint = ConvertToIRWithoutContext( bootstrap.GetApplicationEntryPoint() ); if(m_applicationEntryPoint != null) { m_applicationEntryPoint.BuildTimeFlags |= MethodRepresentation.BuildTimeAttributes.NoInline; } } private void PopulateWellKnownTypes( IMetaDataBootstrap bootstrap ) { foreach(System.Reflection.FieldInfo fi in ReflectionHelper.GetAllPublicInstanceFields( typeof(WellKnownTypes) )) { foreach(WellKnownTypeLookupAttribute attrib in ReflectionHelper.GetAttributes< WellKnownTypeLookupAttribute >( fi, false )) { MetaDataAssembly assm = bootstrap.GetAssembly( attrib.AssemblyName ); if(assm != null) { MetaDataTypeDefinitionAbstract td = bootstrap.ResolveType( assm, attrib.Namespace, attrib.Name ); TypeRepresentation tdRes = ConvertToIRWithoutContext( td ); SetWellKnownType( fi.Name, tdRes ); } } } //--// IMetaDataBootstrap_FilterTypesByCustomAttributeCallback dlg = delegate( MetaDataTypeDefinitionAbstract td, MetaDataCustomAttribute ca ) { string name = (string)ca.FixedArgs[0]; TypeRepresentation tdRes = ConvertToIRWithoutContext( td ); TypeRepresentation tdResOld = GetWellKnownTypeNoThrow( name ); if(tdResOld != null && tdResOld != tdRes) { throw TypeConsistencyErrorException.Create( "Found the well-known type '{0}' defined more than once: {1} and {2}", name, tdResOld.FullNameWithAbbreviation, tdRes.FullNameWithAbbreviation ); } SetWellKnownType( name, tdRes ); }; bootstrap.FilterTypesByCustomAttribute( GetAssociatedMetaData( this.WellKnownTypes.Microsoft_Zelig_Internals_WellKnownTypeAttribute ), dlg ); bootstrap.FilterTypesByCustomAttribute( GetAssociatedMetaData( this.WellKnownTypes.Microsoft_Zelig_Runtime_TypeSystem_WellKnownTypeAttribute ), dlg ); } //--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--// public virtual void ResolveAll() { while(true) { if(m_pendingTypeAnalysis.Dispatch()) { continue; } if(m_pendingMethodAnalysis.Dispatch()) { continue; } if(m_pendingTypeCustomAttributeAnalysis.Dispatch()) { continue; } if(m_pendingMethodCustomAttributeAnalysis.Dispatch()) { continue; } break; } } //--// protected virtual void PerformDelayedTypeAnalysis( TypeRepresentation target , ref ConversionContext context ) { target.PerformDelayedTypeAnalysis( this, ref context ); } protected virtual void PerformDelayedMethodAnalysis( MethodRepresentation target , ref ConversionContext context ) { } protected virtual void PerformDelayedCustomAttributeAnalysis( TypeRepresentation target , ref ConversionContext context ) { target.PerformDelayedCustomAttributeAnalysis( this, ref context ); } protected virtual void PerformDelayedCustomAttributeAnalysis( MethodRepresentation target , ref ConversionContext context ) { target.PerformDelayedCustomAttributeAnalysis( this, ref context ); } //--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--// internal void NotifyNewAssemblyComplete( AssemblyRepresentation asml ) { var dlg = m_notificationOfNewAssembly; if(dlg != null) { dlg( asml ); } } internal void NotifyNewTypeComplete( TypeRepresentation td ) { var dlg = m_notificationOfNewType; if(dlg != null) { dlg( td ); } } internal void NotifyNewFieldComplete( FieldRepresentation fd ) { var dlg = m_notificationOfNewField; if(dlg != null) { dlg( fd ); } } internal void NotifyNewMethodComplete( MethodRepresentation md ) { var dlg = m_notificationOfNewMethod; if(dlg != null) { dlg( md ); } } internal bool NotifyNewCustomAttributeComplete( CustomAttributeAssociationRepresentation caa ) { CustomAttributeRepresentation ca = caa.CustomAttribute; BaseRepresentation owner = caa.Target; TypeRepresentation caTd = ca.Constructor.OwnerType; CustomAttributeNotification res; bool fKeep = true; if(m_customAttributeNotification.TryGetValue( caTd, out res )) { if(res.m_notificationOfAttributeOnGeneric != null) { res.m_notificationOfAttributeOnGeneric( ref fKeep, ca, owner ); } if(owner is TypeRepresentation) { if(res.m_notificationOfAttributeOnType != null) { res.m_notificationOfAttributeOnType( ref fKeep, ca, (TypeRepresentation)owner ); } } else if(owner is FieldRepresentation) { if(res.m_notificationOfAttributeOnField != null) { res.m_notificationOfAttributeOnField( ref fKeep, ca, (FieldRepresentation)owner ); } } else if(owner is MethodRepresentation) { if(caa.ParameterIndex == -1) { if(res.m_notificationOfAttributeOnMethod != null) { res.m_notificationOfAttributeOnMethod( ref fKeep, ca, (MethodRepresentation)owner ); } } else { if(res.m_notificationOfAttributeOnParam != null) { res.m_notificationOfAttributeOnParam( ref fKeep, ca, (MethodRepresentation)owner, caa.ParameterIndex ); } } } } return fKeep; } //--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--// public void InvalidateLayout() { foreach(TypeRepresentation td in this.Types) { td.InvalidateLayout(); } } public void LayoutTypes( uint memoryAlignment ) { GrowOnlySet< TypeRepresentation > history = SetFactory.NewWithReferenceEquality< TypeRepresentation >(); foreach(TypeRepresentation td in this.Types) { EnsureTypeLayout( td, history, memoryAlignment ); td.BuildGcInfo( this ); } } public void EnsureTypeLayout( TypeRepresentation td , GrowOnlySet history , uint memoryAlignment ) { if(td.ValidLayout) { return; } if(history.Insert( td ) == true) { throw TypeConsistencyErrorException.Create( "Found cyclic dependency for '{0}' while trying to compute its layout", td ); } TypeLayoutCallback callback; if(m_layoutDelegation.TryGetValue( td, out callback )) { if(callback( td, history )) { return; } } LayoutType( td, history, memoryAlignment ); } private void LayoutType( TypeRepresentation td , GrowOnlySet< TypeRepresentation > history , uint memoryAlignment ) { if(td.IsOpenType) return; if(td is ArrayReferenceTypeRepresentation) { TypeRepresentation tdElement = td.ContainedType; EnsureTypeLayout( tdElement, history, memoryAlignment ); FieldRepresentation fd = this.WellKnownFields.ArrayImpl_m_numElements; if(fd != null) { EnsureTypeLayout( fd.FieldType, history, memoryAlignment ); td.Size = fd.FieldType.Size; } else { td.Size = 0; } if(tdElement is ReferenceTypeRepresentation) { td.VirtualTable.ElementSize = sizeof(uint); } else if(tdElement is ScalarTypeRepresentation) { td.VirtualTable.ElementSize = tdElement.Size; } else { td.VirtualTable.ElementSize = AddressMath.AlignToBoundary( tdElement.Size, memoryAlignment ); } } if(td.ValidLayout == false) { if(td is BoxedValueTypeRepresentation) { BoxedValueTypeRepresentation boxed = (BoxedValueTypeRepresentation)td; TypeRepresentation boxee = boxed.UnderlyingType; EnsureTypeLayout( boxee, history, memoryAlignment ); td.Size = boxee.Size; } else { TypeRepresentation.Attributes layout = (td.Flags & TypeRepresentation.Attributes.LayoutMask); uint size; uint offset; TypeRepresentation tdSuper = td.Extends; if(tdSuper != null) { EnsureTypeLayout( tdSuper, history, memoryAlignment ); size = tdSuper.Size; } else { size = 0; } offset = size; foreach(FieldRepresentation fd in td.Fields) { if(fd is InstanceFieldRepresentation) { TypeRepresentation tdField = fd.FieldType; if(tdField is ValueTypeRepresentation) { EnsureTypeLayout( tdField, history, memoryAlignment ); } uint fdSize = tdField.SizeOfHoldingVariable; switch(layout) { case TypeRepresentation.Attributes.AutoLayout : case TypeRepresentation.Attributes.SequentialLayout: // // Adjust alignment of field. // switch(fdSize) { case 1: break; case 2: offset = (offset + 1u) & ~(2u-1u); break; case 4: case 8: offset = (offset + 3u) & ~(4u-1u); break; //// // Align on 64 bits. //// case 8: //// offset = (offset + 7u) & ~(8u-1u); //// break; default: offset = (offset + 3u) & ~(4u-1u); break; } fd.Offset = (int)offset; offset += fdSize; size = offset; break; case TypeRepresentation.Attributes.ExplicitLayout: CustomAttributeRepresentation ca = td.FindCustomAttribute( this.WellKnownTypes.System_Runtime_InteropServices_FieldOffsetAttribute ); if(ca != null) { fd.Offset = (int)ca.FixedArgsValues[0]; } size = Math.Max( (uint)(fd.Offset + fdSize), size ); break; } } } //fmegen: there is a problem with value types that have a "non-standard" size ValueTypeRepresentation vt = td as ValueTypeRepresentation; if ((null != vt) && ((vt.Flags & TypeRepresentation.Attributes.Abstract) == 0)) { // If this is a zero-sized struct, we need to arbitrarily assign it a size of one byte. This // matches the CLR spec and simplifies element offset validation if (size == 0) { size = 1; } //very special case: //a value type must not have a size of 3 bytes since we cannot guarantee //on the ARM platform that we're able to move this in an atomic way. //the arm does only support 1, 2, and 4 bytes store operators //...and, btw, the compiler will fail to generate an opcode for this size ;/ if (size == 3) { size = 4; } } td.Size = size; } } } //--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--// public MetaDataAssembly GetAssociatedMetaData( AssemblyRepresentation asml ) { MetaDataAssembly res; return m_reverseLookupAssemblies.TryGetValue( asml, out res ) ? res : null; } public MetaDataTypeDefinitionAbstract GetAssociatedMetaData( TypeRepresentation td ) { Lookup res; return m_reverseLookupTypes.TryGetValue( td, out res ) ? res.m_metadata : null; } public MetaDataField GetAssociatedMetaData( FieldRepresentation fd ) { Lookup res; return m_reverseLookupFields.TryGetValue( fd, out res ) ? res.m_metadata : null; } public MetaDataMethodBase GetAssociatedMetaData( MethodRepresentation md ) { Lookup res; return m_reverseLookupMethods.TryGetValue( md, out res ) ? (MetaDataMethodBase)res.m_metadata : null; } //--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--// public void ImportAssembly( MetaDataAssembly asml ) { foreach(MetaDataTypeDefinitionAbstract td in asml.Types) { // // This skips both System.Object (which is already included in the type system bootstrap) and (which is not supported). // if(td.Extends != null) { ConvertToIRWithoutContext( td ); } } foreach(MetaDataManifestResource res in asml.Resources) { ConvertToIRWithoutContext( res ); } } public AssemblyRepresentation ConvertToIR( MetaDataAssembly asml ) { AssemblyRepresentation asmlIR; if(m_lookupAssemblies.TryGetValue( asml, out asmlIR ) == false) { AssemblyRepresentation.VersionData dstVersion; MetaData.MetaDataVersion srcVersion = asml.Version; dstVersion.MajorVersion = srcVersion.MajorVersion; dstVersion.MinorVersion = srcVersion.MinorVersion; dstVersion.BuildNumber = srcVersion.BuildNumber; dstVersion.RevisionNumber = srcVersion.RevisionNumber; dstVersion.Flags = (AssemblyRepresentation.VersionData.AssemblyFlags)srcVersion.Flags; dstVersion.PublicKey = srcVersion.PublicKey; asmlIR = new AssemblyRepresentation( asml.Name, ref dstVersion ); m_lookupAssemblies[asml] = asmlIR; m_reverseLookupAssemblies[asmlIR] = asml; m_assemblies.Add( asmlIR ); NotifyNewAssemblyComplete( asmlIR ); } return asmlIR; } //--// public TypeRepresentation ConvertToIRWithoutContext( MetaDataTypeDefinitionAbstract td ) { ConversionContext context = new ConversionContext(); context.Initialize(); return ConvertToIR( td, context ); } public TypeRepresentation GetDefiningType( MetaDataField fd , ref ConversionContext context ) { bool fInstantiateGeneric = (context.m_typeContextOwner != null); return ConvertToIR( fd.Owner, context, fInstantiateGeneric ); } public TypeRepresentation GetDefiningType( MetaDataMethodBase md , ref ConversionContext context ) { bool fInstantiateGeneric = (context.m_typeContextOwner != null); return ConvertToIR( md.Owner, context, fInstantiateGeneric ); } public TypeRepresentation ConvertToIR( SignatureType td , ConversionContext context ) { return InnerConvertToIR( td.Type, ref context, false ); } public TypeRepresentation ConvertToIR( MetaDataTypeDefinitionAbstract td , ConversionContext context ) { return InnerConvertToIR( td, ref context, false ); } public TypeRepresentation ConvertToIR( MetaDataTypeDefinitionAbstract td , ConversionContext context , bool fInstantiateGeneric ) { return InnerConvertToIR( td, ref context, fInstantiateGeneric ); } private TypeRepresentation InnerConvertToIR( MetaDataTypeDefinitionAbstract td , ref ConversionContext context , bool fInstantiateGeneric ) { if(td == null) { return null; } //--// if(ComputeMaxGenericInstantiationDepth( ref context ) > 10) { throw TypeConsistencyErrorException.Create( "Found generic instantiation {0} levels deep. Is this an infinite generic recursion? {1}", ComputeMaxGenericInstantiationDepth( ref context ), context ); } td = FlattenTypeDefinition( td, ref context, fInstantiateGeneric ); //--// TypeRepresentation tdIR; bool fAllocateDelayedTypeParameter; bool fAllocateDelayedMethodParameter; tdIR = ResolveDelayedParameter( td, ref context, out fAllocateDelayedTypeParameter, out fAllocateDelayedMethodParameter ); if(tdIR != null) { return tdIR; } Lookup lookup = new Lookup(); lookup.Set( td, ref context ); if(m_lookupTypes.TryGetValue( lookup, out tdIR )) { if(tdIR == null) { throw TypeConsistencyErrorException.Create( "Detected recursive resolution attempt for {0}", td ); } ReportVerbose( "Resolved Type {0} => {1}", lookup, tdIR ); return tdIR; } //--// // // Create GenericContext, with a pointer to the template Generic and the parameter types. // TypeRepresentation.GenericContext genericContext; if(td is MetaDataTypeDefinitionGeneric) { TypeRepresentation[] genericParameters = context.m_typeContext; if(genericParameters.Length > 0) { TypeRepresentation tdIRTemplate = ConvertToIRWithoutContext( td ); genericContext = new TypeRepresentation.GenericContext( tdIRTemplate, genericParameters ); } else { genericContext = new TypeRepresentation.GenericContext( null, genericParameters ); } } else { genericContext = null; } Report( "Converting Type {0}", lookup ); AssemblyRepresentation asmlIR = ConvertToIR( td.Owner ); //--// if(fAllocateDelayedTypeParameter) { MetaDataTypeDefinitionDelayed td2 = (MetaDataTypeDefinitionDelayed)td; return RegisterAndAnalyze( ref lookup, new DelayedTypeParameterTypeRepresentation( asmlIR, context.m_typeContextOwner, td2.ParameterNumber ) ); } if(fAllocateDelayedMethodParameter) { MetaDataTypeDefinitionDelayed td2 = (MetaDataTypeDefinitionDelayed)td; return RegisterAndAnalyze( ref lookup, new DelayedMethodParameterTypeRepresentation( asmlIR, context.m_methodContextOwner, td2.ParameterNumber ) ); } if(td is MetaDataTypeDefinitionGeneric) { MetaDataTypeDefinitionGeneric td2 = (MetaDataTypeDefinitionGeneric)td; if(m_genericRecursionCheck.VerifyFiniteInstantiationOfGenericType( td2 ) == false) { throw TypeConsistencyErrorException.Create( "Detected recursive generic declaration starting from {0}", td ); } } m_lookupTypes[lookup] = null; //--// if(td is MetaDataTypeDefinitionBase) { MetaDataTypeDefinitionBase td2 = (MetaDataTypeDefinitionBase )td; MetaDataTypeDefinitionAbstract tdExtends = td.Extends; TypeRepresentation.BuiltInTypes builtinType = (TypeRepresentation.BuiltInTypes)td2.ElementType; TypeRepresentation.Attributes flags = (TypeRepresentation.Attributes )td2.Flags; if(tdExtends == null) { if((td2.Flags & MetaData.TypeAttributes.ClassSemanticsMask) == MetaData.TypeAttributes.Interface) { return RegisterAndAnalyze( ref lookup, new InterfaceTypeRepresentation( asmlIR, builtinType, flags, genericContext ) ); } else { if(IsObjectClass( td2 ) == false) { throw FeatureNotSupportedException.Create( "'{0}' doesn't inherit from System.Object, multiple type system roots not supported!", td2.FullName ); } return RegisterAndAnalyze( ref lookup, new ConcreteReferenceTypeRepresentation( asmlIR, builtinType, flags, genericContext ) ); } } else if(tdExtends is MetaDataTypeDefinitionBase && IsValueType( (MetaDataTypeDefinitionBase)tdExtends )) { if(td2.IsScalar) { return RegisterAndAnalyze( ref lookup, new ScalarTypeRepresentation( asmlIR, builtinType, flags, genericContext, td2.ScalarSize ) ); } else if(IsEnumType( td2 )) { // Special case: System.Enum extends System.ValueType, but is not itself a value type. return RegisterAndAnalyze( ref lookup, new ConcreteReferenceTypeRepresentation( asmlIR, builtinType, flags, genericContext ) ); } else { TypeRepresentation valueType = RegisterAndAnalyze( ref lookup, new ValueTypeRepresentation( asmlIR, builtinType, flags, genericContext ) ); // For value types, it's extremely likely we'll want to create a managed pointer to the type. // This is usually done when adding a method to the type. Rather than dirtying the type system // later, we create the managed pointer type in advance. CreateManagedPointerToType( valueType ); return valueType; } } else if(tdExtends is MetaDataTypeDefinitionBase && IsEnumType( (MetaDataTypeDefinitionBase)tdExtends )) { return RegisterAndAnalyze( ref lookup, new EnumerationTypeRepresentation( asmlIR, builtinType, flags, genericContext, td2.ScalarSize ) ); } else { if((td2.Flags & MetaData.TypeAttributes.RTSpecialName) != 0) { throw TypeConsistencyErrorException.Create( "Unexpected special name type '{0}'", td2 ); } else if((td2.Flags & MetaData.TypeAttributes.Abstract) != 0) { return RegisterAndAnalyze( ref lookup, new AbstractReferenceTypeRepresentation( asmlIR, builtinType, flags, genericContext ) ); } else { return RegisterAndAnalyze( ref lookup, new ConcreteReferenceTypeRepresentation( asmlIR, builtinType, flags, genericContext ) ); } } } else if(td is MetaDataTypeDefinitionDelayed) { throw TypeConsistencyErrorException.Create( "Invalid context [{0}] for delayed parameter {1}", context, td ); } else if(td is MetaDataTypeDefinitionArray) { MetaDataTypeDefinitionArray td2 = (MetaDataTypeDefinitionArray)td; TypeRepresentation elementType = ConvertToIR( td2.ObjectType, context ); // // Make sure there's a managed pointer to the elements of each array. // CreateManagedPointerToType( elementType ); if(td2 is MetaDataTypeDefinitionArraySz) { MetaDataTypeDefinitionArraySz td3 = (MetaDataTypeDefinitionArraySz)td2; return RegisterAndAnalyze( ref lookup, new SzArrayReferenceTypeRepresentation( asmlIR, elementType ) ); } else { MetaDataTypeDefinitionArrayMulti td3 = (MetaDataTypeDefinitionArrayMulti)td2; MetaDataTypeDefinitionArrayMulti .Dimension[] src = td3.Dimensions; MultiArrayReferenceTypeRepresentation.Dimension[] dst = new MultiArrayReferenceTypeRepresentation.Dimension[src.Length]; for(int i = 0; i < src.Length; i++) { dst[i].m_lowerBound = src[i].m_lowerBound; dst[i].m_upperBound = src[i].m_upperBound; } return RegisterAndAnalyze( ref lookup, new MultiArrayReferenceTypeRepresentation( asmlIR, elementType, td3.Rank, dst ) ); } } else if(td is MetaDataTypeDefinitionByRef) { MetaDataTypeDefinitionByRef td2 = (MetaDataTypeDefinitionByRef)td; TypeRepresentation pointerType = ConvertToIR( td2.BaseType, context ); switch(td2.ElementType) { case MetaData.ElementTypes.BYREF: return RegisterAndAnalyze( ref lookup, new ManagedPointerTypeRepresentation( asmlIR, pointerType ) ); case MetaData.ElementTypes.PTR: return RegisterAndAnalyze( ref lookup, new UnmanagedPointerTypeRepresentation( asmlIR, pointerType ) ); case MetaData.ElementTypes.PINNED: return RegisterAndAnalyze( ref lookup, new PinnedPointerTypeRepresentation( asmlIR, pointerType ) ); default: throw TypeConsistencyErrorException.Create( "Invalid byref specifier ('{0}') for type ('{1}')", td.ElementType, td ); } } else { throw FeatureNotSupportedException.Create( "Unknown type '{0}'", td ); } } //--// public MethodRepresentation ConvertToIRWithoutContext( MetaDataMethodAbstract md ) { ConversionContext context = new ConversionContext(); context.Initialize(); return ConvertToIR( md, context ); } public MethodRepresentation ConvertToIR( MetaDataMethodAbstract md , ConversionContext context ) { if(md == null) { return null; } //--// if(ComputeMaxGenericInstantiationDepth( ref context ) > 10) { throw TypeConsistencyErrorException.Create( "Found generic instantiation {0} levels deep. Is this an infinite generic recursion? {1}", ComputeMaxGenericInstantiationDepth( ref context ), context ); } md = FlattenMethodDefinition( md, ref context ); //--// MethodRepresentation mdIR; Lookup lookup = new Lookup(); lookup.Set( md, ref context ); if(m_lookupMethods.TryGetValue( lookup, out mdIR )) { if(mdIR == null) { throw TypeConsistencyErrorException.Create( "Detected recursive resolution attempt for {0}", md ); } ReportVerbose( "Resolved Method {0} => {1}", lookup, mdIR ); return mdIR; } m_lookupMethods[lookup] = null; //--// // // Create GenericContext, with a pointer to the template Generic and the parameter types. // MethodRepresentation.GenericContext genericContext; if(md is MetaDataMethodGeneric) { TypeRepresentation[] genericParameters = context.m_methodContext; if(genericParameters.Length > 0) { MethodRepresentation mdIRTemplate = ConvertToIRWithoutContext( md ); genericContext = new MethodRepresentation.GenericContext( mdIRTemplate, genericParameters ); } else { genericContext = new MethodRepresentation.GenericContext( null, genericParameters ); } } else { genericContext = null; } Report( "Converting Method {0}", lookup ); //--// if(md is MetaDataMethodBase) { MethodRepresentation retVal; MetaDataMethodBase md2 = (MetaDataMethodBase)md; TypeRepresentation tdIR = GetDefiningType( md2, ref context ); if(tdIR == null) { throw TypeConsistencyErrorException.Create( "Cannot define a new method '{0}' without its owner {0}", md ); } if((md2.Flags & MetaData.MethodAttributes.RTSpecialName) != 0) { switch(md2.Name) { case ".cctor": retVal = RegisterAndAnalyze( ref lookup, new StaticConstructorMethodRepresentation( tdIR, genericContext ) ); break; case ".ctor": retVal = RegisterAndAnalyze( ref lookup, new ConstructorMethodRepresentation( tdIR, genericContext ) ); break; // // Runtime-generated methods for multi-dimensional arrays. // case "Get": case "Set": case "Address": // // Methods on runtime-added interfaces for arrays: // // public interface IList : ICollection // { // // The Item property provides methods to read and edit entries in the List. // T this[int index] { // get; // set; // } // // // Returns the index of a particular item, if it is in the list. // // Returns -1 if the item isn't in the list. // int IndexOf(T item); // // // Inserts value into the list at position index. // // index must be non-negative and less than or equal to the // // number of elements in the list. If index equals the number // // of items in the list, then value is appended to the end. // void Insert(int index, T item); // // // Removes the item at position index. // void RemoveAt(int index); // } case "get_Item": case "set_Item": case "IndexOf": case "Insert": case "RemoveAt": // // Methods on runtime-added interfaces for arrays: // // public interface ICollection : IEnumerable // { // // Interfaces are not serialable // // Number of items in the collections. // int Count // { // get; // } // // bool IsReadOnly // { // get; // } // // void Add( T item ); // // void Clear(); // // bool Contains( T item ); // // // CopyTo copies a collection into an Array, starting at a particular // // index into the array. // // // void CopyTo( T[] array, int arrayIndex ); // // //void CopyTo(int sourceIndex, T[] destinationArray, int destinationIndex, int count); // // bool Remove( T item ); // } case "get_Count": case "get_ReadOnly": case "get_IsReadOnly": case "Add": case "Clear": case "Contains": case "CopyTo": case "Remove": // // Methods on runtime-added interfaces for arrays: // // public interface IEnumerable : IEnumerable // { // // Interfaces are not serializable // // Returns an IEnumerator for this enumerable Object. The enumerator provides // // a simple way to access all the contents of a collection. // /// // new IEnumerator GetEnumerator(); // } case "GetEnumerator": CHECKS.ASSERT( (md2.Flags & MetaData.MethodAttributes.Static) == 0, "Unexpected static context for runtime method" ); retVal = RegisterAndAnalyze( ref lookup, new RuntimeMethodRepresentation( tdIR, genericContext ) ); break; default: throw FeatureNotSupportedException.Create( "Unknown special name method '{0}'", md2 ); } } else if((md2.Flags & MetaData.MethodAttributes.Static) != 0) { retVal = RegisterAndAnalyze( ref lookup, new StaticMethodRepresentation( tdIR, genericContext ) ); } else if((md2.Flags & MetaData.MethodAttributes.Virtual) != 0) { if(md2.Name == "Finalize" ) { retVal = RegisterAndAnalyze( ref lookup, new FinalizerMethodRepresentation( tdIR, genericContext ) ); } else { if( ( md2.Flags & MetaData.MethodAttributes.Final ) != 0 ) { retVal = RegisterAndAnalyze( ref lookup, new FinalMethodRepresentation( tdIR, genericContext ) ); } else { retVal = RegisterAndAnalyze( ref lookup, new VirtualMethodRepresentation( tdIR, genericContext ) ); } } } else { retVal = RegisterAndAnalyze( ref lookup, new NonVirtualMethodRepresentation( tdIR, genericContext ) ); } // Either the PDB information doesn't capture the debug info for a method or the // Zelig metadata importer doesn't read/use it, either way there's no debug info // for the method definition itself. To get around that this scans the original // IL instructions to find the first one with debug info. if( md2.Instructions != null ) { foreach( var instruction in md2.Instructions ) { if( instruction.DebugInfo != null ) { retVal.DebugInfo = instruction.DebugInfo; break; } } // ensure that at least the scope information is valid if( retVal.DebugInfo == null ) { retVal.DebugInfo = new Debugging.DebugInfo(string.Empty, 0, 0, 0, 0) { Scope = md }; } } return retVal; } else { throw TypeConsistencyErrorException.Create( "You cannot convert method '{0}' to IR", md ); } } //--// public FieldRepresentation ConvertToIR( TypeRepresentation tdOwner , MetaDataFieldAbstract fdIn , ConversionContext context ) { if(fdIn == null) { return null; } //--// // // This part is a bit messy... // // Fields cannot be generic but their type can be. // As a consequence, context has to be adjusted to point to the actual type of the holding type. // So, we allow only the owner of a field to create it. // To make sure the context gets set appropriately, we build 'lookup' with the actual type, not the incoming context. // MetaDataField fd = FlattenFieldDefinition( fdIn, ref context ); TypeRepresentation tdIR = (tdOwner != null) ? tdOwner : GetDefiningType( fd, ref context ); if(tdIR == null) { throw TypeConsistencyErrorException.Create( "Cannot define a new field '{0}' without its owner {0}", fdIn ); } //--// FieldRepresentation fdIR; Lookup lookup = new Lookup(); lookup.Set( fd, tdIR ); if(m_lookupFields.TryGetValue( lookup, out fdIR )) { if(fdIR == null) { throw TypeConsistencyErrorException.Create( "Detected recursive resolution attempt for {0}", fd ); } ReportVerbose( "Resolved Field {0} => {1}", lookup, fdIR ); return fdIR; } m_lookupFields[lookup] = null; //--// Report( "Converting Field {0}", lookup ); if((fd.Flags & MetaData.FieldAttributes.Static) != 0) { fdIR = RegisterAndAnalyze( ref lookup, new StaticFieldRepresentation( tdIR, fd.Name ) ); } else { fdIR = RegisterAndAnalyze( ref lookup, new InstanceFieldRepresentation ( tdIR, fd.Name ) ); } if(lookup.m_metadata.Layout != null) { fdIR.Offset = lookup.m_metadata.Layout.Offset; } return fdIR; } //--// public void ConvertToIR( MetaDataCustomAttribute[] mdcaa , ConversionContext context , BaseRepresentation owner , int paramIndex ) { if(mdcaa != null) { int num = mdcaa.Length; for(int i = 0; i < num; i++) { CustomAttributeAssociationRepresentation caa = this.ConvertToIR( mdcaa[i], context, owner, paramIndex ); if(caa != null) { owner.AddCustomAttribute( caa ); } } } } public CustomAttributeAssociationRepresentation ConvertToIR( MetaDataCustomAttribute caIn , ConversionContext context , BaseRepresentation owner , int paramIndex ) { if(caIn == null) { return null; } //--// CustomAttributeRepresentation caIR; Lookup< MetaDataCustomAttribute > lookup = new Lookup< MetaDataCustomAttribute >(); lookup.Set( caIn, ref context ); if(m_lookupAttributes.TryGetValue( lookup, out caIR )) { if(caIR == null) { throw TypeConsistencyErrorException.Create( "Detected recursive resolution attempt for {0}", caIn ); } } else { m_lookupAttributes[lookup] = null; //--// Report( "Converting Custom Attribute {0}", lookup ); MetaDataCustomAttribute.NamedArg[] na = caIn.NamedArgs; MethodRepresentation constructor = this.ConvertToIR( caIn.Constructor, context ); object[] fixedArgsValues = ArrayUtility.CopyNotNullArray( caIn.FixedArgs ); string[] namedArgs = new string[na.Length]; object[] namedArgsValues = new object[na.Length]; for(int faIdx = 0; faIdx < fixedArgsValues.Length; faIdx++) { object obj = fixedArgsValues[faIdx]; if(obj is MetaDataTypeDefinitionAbstract) { fixedArgsValues[faIdx] = this.ConvertToIR( (MetaDataTypeDefinitionAbstract)obj, context ); } } for(int naIdx = 0; naIdx < na.Length; naIdx++) { object obj = na[naIdx].Value; if(obj is MetaDataTypeDefinitionAbstract) { obj = this.ConvertToIR( (MetaDataTypeDefinitionAbstract)obj, context ); } namedArgs [naIdx] = na[naIdx].Name; namedArgsValues[naIdx] = obj; } caIR = RegisterAndAnalyze( ref lookup, new CustomAttributeRepresentation( constructor, fixedArgsValues, namedArgs, namedArgsValues ) ); } CustomAttributeAssociationRepresentation caa = new CustomAttributeAssociationRepresentation( caIR, owner, paramIndex ); if(NotifyNewCustomAttributeComplete( caa ) == true) { return caa; } return null; } //--// public ResourceRepresentation ConvertToIRWithoutContext( MetaDataManifestResource res ) { ConversionContext context = new ConversionContext(); context.Initialize(); return ConvertToIR( res, context ); } public ResourceRepresentation ConvertToIR( MetaDataManifestResource resIn , ConversionContext context ) { if(resIn == null) { return null; } //--// ResourceRepresentation resIR; Lookup< MetaDataManifestResource > lookup = new Lookup< MetaDataManifestResource >(); lookup.Set( resIn, ref context ); if(m_lookupResources.TryGetValue( lookup, out resIR )) { if(resIR == null) { throw TypeConsistencyErrorException.Create( "Detected recursive resolution attempt for {0}", resIn ); } } else { m_lookupResources[lookup] = null; //--// Report( "Converting Resource {0}", lookup ); AssemblyRepresentation asmlIR = ConvertToIR( resIn.Owner ); resIR = RegisterAndAnalyze( ref lookup, new ResourceRepresentation( asmlIR ) ); } return resIR; } //--// public TypeRepresentation GetTypeOfValue( object value ) { if(value is int ) return m_wellKnownTypes.System_Int32; if(value is long ) return m_wellKnownTypes.System_Int64; if(value is float ) return m_wellKnownTypes.System_Single; if(value is double) return m_wellKnownTypes.System_Double; throw new Exception( "The method or operation is not implemented." ); } //--// public BoxedValueTypeRepresentation TryToGetBoxedValueType( ValueTypeRepresentation src ) { foreach(TypeRepresentation td in m_types) { BoxedValueTypeRepresentation boxed = td as BoxedValueTypeRepresentation; if(boxed != null && boxed.ContainedType == src) { return boxed; } } return null; } public BoxedValueTypeRepresentation GetBoxedValueType( ValueTypeRepresentation src ) { BoxedValueTypeRepresentation res = TryToGetBoxedValueType( src ); if(res == null) { throw TypeConsistencyErrorException.Create( "Cannot find boxed representation for {0}", src ); } return res; } public ManagedPointerTypeRepresentation TryToGetManagedPointerToType( TypeRepresentation src ) { foreach(TypeRepresentation td in m_types) { ManagedPointerTypeRepresentation ptr = td as ManagedPointerTypeRepresentation; if(ptr != null && ptr.ContainedType == src) { return ptr; } } return null; } public ManagedPointerTypeRepresentation GetManagedPointerToType( TypeRepresentation src ) { ManagedPointerTypeRepresentation res = TryToGetManagedPointerToType( src ); if(res == null) { throw TypeConsistencyErrorException.Create( "Cannot find representation for managed pointer to {0}", src ); } return res; } public SzArrayReferenceTypeRepresentation TryToGetArrayOfType( TypeRepresentation src ) { foreach(TypeRepresentation td in m_types) { SzArrayReferenceTypeRepresentation array = td as SzArrayReferenceTypeRepresentation; if(array != null && array.ContainedType == src) { return array; } } return null; } public SzArrayReferenceTypeRepresentation GetArrayOfType( TypeRepresentation src ) { SzArrayReferenceTypeRepresentation res = TryToGetArrayOfType( src ); if(res == null) { throw TypeConsistencyErrorException.Create( "Cannot find representation for array of {0}", src ); } return res; } //--// public bool IsNullable( TypeRepresentation td ) { TypeRepresentation.GenericContext gc = td.Generic; if(gc != null && gc.Template == this.WellKnownTypes.System_Nullable_of_T) { return true; } return false; } public TypeRepresentation GetNullableParameter( TypeRepresentation td ) { if(IsNullable( td )) { return td.GenericParameters[0]; } return null; } public TypeRepresentation CreateBoxedValueTypeIfNecessary( TypeRepresentation td ) { if(td is ReferenceTypeRepresentation || td is PointerTypeRepresentation ) { return td; } return CreateBoxedValueType( td ); } public TypeRepresentation CreateBoxedValueType( TypeRepresentation td ) { return RegisterAndAnalyze( new BoxedValueTypeRepresentation( td ) ); } public TypeRepresentation CreateManagedPointerToType( TypeRepresentation td ) { return RegisterAndAnalyze( new ManagedPointerTypeRepresentation( td.Owner, td ) ); } public TypeRepresentation CreateUnmanagedPointerToType( TypeRepresentation td ) { return RegisterAndAnalyze( new UnmanagedPointerTypeRepresentation( td.Owner, td ) ); } public TypeRepresentation CreateArrayOfType( TypeRepresentation td ) { return RegisterAndAnalyze( new SzArrayReferenceTypeRepresentation( td.Owner, td ) ); } public TypeRepresentation CreateDelayedVersionOfGenericTypeIfNecessary( TypeRepresentation td ) { TypeRepresentation.GenericContext gc = td.Generic; if(gc != null && gc.IsOpenType) { ConversionContext context = new ConversionContext(); context.Initialize(); context.SetContextAsType( td ); TypeRepresentation[] parameters = new TypeRepresentation[gc.ParametersDefinition.Length]; for(int i = 0; i < parameters.Length; i++) { parameters[i] = RegisterAndAnalyze( ref context, new DelayedTypeParameterTypeRepresentation( td.Owner, td, i ) ); } InstantiationContext ic = m_instantiationContext.SetParameters( parameters, null ); TypeRepresentation td2 = ic.Instantiate( td ); return td2; } else { return td; } } public TypeRepresentation CreateInstantiationOfGenericTemplate( TypeRepresentation tdTemplate , params TypeRepresentation[] parameters ) { var context = new ConversionContext(); context.SetContextAsTypeParameters( parameters ); return ConvertToIR( GetAssociatedMetaData( tdTemplate ), context, true ); } public MethodRepresentation CreateInstantiationOfGenericTemplate( MethodRepresentation mdTemplate , params TypeRepresentation[] parameters ) { var context = new ConversionContext(); context.SetContextAsType ( mdTemplate.OwnerType ); context.SetContextAsMethodParameters( parameters ); return ConvertToIR( GetAssociatedMetaData( mdTemplate ), context ); } //--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--// public MethodRepresentation InstantiateMethod( MethodRepresentation md , TypeRepresentation[] typeParameters , TypeRepresentation[] methodParameters , out InstantiationContext ic ) { ic = m_instantiationContext.SetParameters( typeParameters, methodParameters ); MethodRepresentation instantiatedMd = md.Instantiate( ic ); return instantiatedMd; } //--// private Lookup< MetaDataTypeDefinitionAbstract > ReverseLookup( TypeRepresentation td ) { Lookup< MetaDataTypeDefinitionAbstract > res; m_reverseLookupTypes.TryGetValue( td, out res ); return res; } private Lookup< MetaDataField > ReverseLookup( FieldRepresentation fd ) { Lookup< MetaDataField > res; m_reverseLookupFields.TryGetValue( fd, out res ); return res; } private Lookup< MetaDataMethodAbstract > ReverseLookup( MethodRepresentation md ) { Lookup< MetaDataMethodAbstract > res; m_reverseLookupMethods.TryGetValue( md, out res ); return res; } //--// private TypeRepresentation RegisterAndAnalyze( TypeRepresentation tdNew ) { TypeRepresentation tdRes = m_instantiationContext.Lookup( tdNew, true ); if(tdRes != null) { return tdRes; } m_types.Add( tdNew ); ConversionContext context = new ConversionContext(); context.Initialize(); tdNew.PerformDelayedTypeAnalysis( this, ref context ); return tdNew; } private TypeRepresentation RegisterAndAnalyze( ref ConversionContext context , TypeRepresentation tdNew ) { MetaData.Normalized.MetaDataTypeDefinitionAbstract metadata = this.GetAssociatedMetaData( tdNew ); tdNew.CompleteIdentity( this, ref context, metadata ); TypeRepresentation tdRes = m_instantiationContext.Lookup( tdNew, true ); if(tdRes != null) { return tdRes; } m_types.Add( tdNew ); tdNew.PerformTypeAnalysis( this, ref context ); return tdNew; } private TypeRepresentation RegisterAndAnalyze( ref Lookup< MetaDataTypeDefinitionAbstract > lookup , TypeRepresentation tdNew ) { m_lookupTypes[lookup] = tdNew; tdNew.CompleteIdentity( this, ref lookup.m_context, lookup.m_metadata ); //--// ReportVerbose( "Converted Type {0} [Context:{1}]", tdNew, lookup ); TypeRepresentation tdRes = m_instantiationContext.Lookup( tdNew, true ); if(tdRes != null) { ReportVerbose( "Found duplicate for {0} [Context:{1}]: {2} [Context:{3}]", tdNew, lookup, tdRes, ReverseLookup( tdRes ) ); m_lookupTypes[lookup] = tdRes; return tdRes; } else { m_lookupTypes[lookup] = tdNew; m_reverseLookupTypes[tdNew] = lookup; m_types.Add( tdNew ); tdNew.PerformTypeAnalysis( this, ref lookup.m_context ); return tdNew; } } private FieldRepresentation RegisterAndAnalyze( ref Lookup< MetaDataField > lookup , FieldRepresentation fdNew ) { FieldRepresentation fdRes = m_instantiationContext.Lookup( fdNew, true ); if(fdRes != null) { ReportVerbose( "Found duplicate for {0} [Context:{1}]: {2} [Context:{3}]", fdNew, lookup, fdRes, ReverseLookup( fdRes ) ); m_lookupFields[lookup] = fdRes; return fdRes; } else { m_lookupFields[lookup] = fdNew; m_reverseLookupFields[fdNew] = lookup; object defaultValue = lookup.m_metadata.DefaultValue; if(defaultValue != null) { m_defaultValues[fdNew] = defaultValue; } fdNew.OwnerType.AddField( fdNew ); fdNew.PerformFieldAnalysis( this, ref lookup.m_context ); return fdNew; } } private MethodRepresentation RegisterAndAnalyze( ref Lookup< MetaDataMethodAbstract > lookup , MethodRepresentation mdNew ) { m_lookupMethods[lookup] = mdNew; mdNew.CompleteIdentity( this, ref lookup.m_context, lookup.m_metadata ); //--// ReportVerbose( "Converted Method {0} [Context:{1}]", mdNew, lookup ); MethodRepresentation mdRes = m_instantiationContext.Lookup( mdNew, true ); if(mdRes != null) { ReportVerbose( "Found duplicate for {0} [Context:{1}]: {2} [Context:{3}]", mdNew, lookup, mdRes, ReverseLookup( mdRes ) ); m_lookupMethods[lookup] = mdRes; return mdRes; } else { m_lookupMethods[lookup] = mdNew; m_reverseLookupMethods[mdNew] = lookup; mdNew.OwnerType.AddMethod( mdNew ); mdNew.PerformMethodAnalysis( this, ref lookup.m_context ); return mdNew; } } private CustomAttributeRepresentation RegisterAndAnalyze( ref Lookup< MetaDataCustomAttribute > lookup , CustomAttributeRepresentation caNew ) { ReportVerbose( "Converted CA {0} [Context:{1}]", caNew, lookup ); CustomAttributeRepresentation caRes = m_instantiationContext.Lookup( caNew, true ); if(caRes != null) { ReportVerbose( "Found duplicate for {0} : {1} [Context:{2}]", caNew, caRes, lookup ); m_lookupAttributes[lookup] = caRes; return caRes; } else { m_lookupAttributes[lookup] = caNew; return caNew; } } private ResourceRepresentation RegisterAndAnalyze( ref Lookup< MetaDataManifestResource > lookup , ResourceRepresentation resNew ) { m_lookupResources[lookup] = resNew; resNew.CompleteIdentity( this, ref lookup.m_context, lookup.m_metadata ); ReportVerbose( "Converted Resource {0} [Context:{1}]", resNew, lookup ); ResourceRepresentation resRes = m_instantiationContext.Lookup( resNew, true ); if(resRes != null) { ReportVerbose( "Found duplicate for {0} : {1} [Context:{2}]", resNew, resRes, lookup ); m_lookupResources[lookup] = resRes; return resRes; } else { m_lookupResources[lookup] = resNew; m_resources.Add( resNew ); return resNew; } } //--//--//--// private int ComputeMaxGenericInstantiationDepth( ref ConversionContext context ) { if(context.m_typeContextOwner != null) { return ComputeMaxGenericInstantiationDepth( context.m_typeContextOwner ); } if(context.m_typeContext.Length > 0) { return ComputeMaxGenericInstantiationDepth( context.m_typeContext ); } return 0; } private int ComputeMaxGenericInstantiationDepth( TypeRepresentation td ) { return ComputeMaxGenericInstantiationDepth( td.GenericParameters ) + 1; } private int ComputeMaxGenericInstantiationDepth( TypeRepresentation[] genParams ) { int depth = 0; if(genParams != null) { for(int i = 0; i < genParams.Length; i++) { int depthParam = ComputeMaxGenericInstantiationDepth( genParams[i] ); if(depth < depthParam) depth = depthParam; } } return depth; } //--// private MetaDataTypeDefinitionAbstract FlattenTypeDefinition( MetaDataTypeDefinitionAbstract td , ref ConversionContext context , bool fInstantiateGeneric ) { if(td is MetaDataTypeDefinitionGenericInstantiation) { MetaDataTypeDefinitionGenericInstantiation td2 = (MetaDataTypeDefinitionGenericInstantiation)td; SignatureType[] instantiationParams = td2.InstantiationParams; TypeRepresentation[] genericParameters = new TypeRepresentation[instantiationParams.Length]; for(int i = 0; i < instantiationParams.Length; i++) { genericParameters[i] = ConvertToIR( instantiationParams[i], context ); } context.SetContextAsTypeParameters( genericParameters ); return td2.GenericType; } else if(td is MetaDataTypeDefinitionDelayed) { return td; } else if(td is MetaDataTypeDefinitionArray || td is MetaDataTypeDefinitionByRef ) { if(td.IsOpenType) { // // We need to keep the full context around during delayed array/byref expansion. // } else { context.SetContextAsTypeParameters( TypeRepresentation.SharedEmptyArray ); } return td; } else if(td is MetaDataTypeDefinitionGeneric && fInstantiateGeneric) { MetaDataTypeDefinitionGeneric td2 = (MetaDataTypeDefinitionGeneric)td; context.AdjustContextAsType( td2.GenericParams.Length ); return td; } else { context.SetContextAsTypeParameters( TypeRepresentation.SharedEmptyArray ); return td; } } private TypeRepresentation ResolveDelayedParameter( MetaDataTypeDefinitionAbstract td , ref ConversionContext context , out bool fAllocateDelayedTypeParameter , out bool fAllocateDelayedMethodParameter ) { fAllocateDelayedTypeParameter = false; fAllocateDelayedMethodParameter = false; if(context.m_typeContextOwner is ArrayReferenceTypeRepresentation) { // // Special case for runtime-generated methods on arrays, which normally cannot have generic parameters. // ArrayReferenceTypeRepresentation dstArray = (ArrayReferenceTypeRepresentation)context.m_typeContextOwner; TypeRepresentation elementType = dstArray.ContainedType; if(td is MetaDataTypeDefinitionDelayed) { return elementType; } if(td is MetaDataTypeDefinitionArray) { MetaDataTypeDefinitionArray tdArray = (MetaDataTypeDefinitionArray)td; MetaDataTypeDefinitionAbstract elementType2 = tdArray.ObjectType; if(elementType2 is MetaDataTypeDefinitionDelayed) { return dstArray; } if(elementType2 is MetaDataTypeDefinitionGenericInstantiation) { MetaDataTypeDefinitionGenericInstantiation elementTypeInst = (MetaDataTypeDefinitionGenericInstantiation)elementType2; if(elementTypeInst.GenericType == GetAssociatedMetaData( elementType )) { return dstArray; } } } } if(td is MetaDataTypeDefinitionDelayed) { MetaDataTypeDefinitionDelayed td2 = (MetaDataTypeDefinitionDelayed)td; if(td2.IsMethodParameter) { if(context.m_methodContext.Length > 0) { return context.m_methodContext[td2.ParameterNumber]; } if(context.m_methodContextOwner != null) { fAllocateDelayedMethodParameter = true; return null; } } else { if(context.m_typeContext.Length > 0) { return context.m_typeContext[td2.ParameterNumber]; } if(context.m_typeContextOwner != null) { fAllocateDelayedTypeParameter = true; return null; } } throw TypeConsistencyErrorException.Create( "Invalid context [{0}] for delayed parameter {1}", context, td ); } return null; } //--// private MetaDataMethodAbstract FlattenMethodDefinition( MetaDataMethodAbstract md , ref ConversionContext context ) { if(md is MetaDataMethodGenericInstantiation) { MetaDataMethodGenericInstantiation md2 = (MetaDataMethodGenericInstantiation)md; SignatureType[] instantiationParams = md2.InstantiationParams; TypeRepresentation[] genericParameters = new TypeRepresentation[instantiationParams.Length]; for(int i = 0; i < instantiationParams.Length; i++) { genericParameters[i] = ConvertToIR( instantiationParams[i], context ); } md = FlattenMethodDefinition( md2.BaseMethod, ref context ); context.SetContextAsMethodParameters( genericParameters ); return md; } else if(md is MetaDataMethodWithContext) { MetaDataMethodWithContext md2 = (MetaDataMethodWithContext)md; TypeRepresentation td = ConvertToIR( md2.ContextType, context ); ConversionContext contextOuter = context; context.SetContextAsType( td ); if(contextOuter.m_methodContext.Length > 0) { context.SetContextAsMethodParameters( contextOuter.m_methodContext ); } else if(contextOuter.m_methodContextOwner != null) { context.SetContextAsMethod( contextOuter.m_methodContextOwner ); } return FlattenMethodDefinition( md2.BaseMethod, ref context ); } else if(md is MetaDataMethodBase) { MetaDataMethodBase md2 = (MetaDataMethodBase)md; if(md2.IsOpenMethod == false) { MetaDataTypeDefinitionAbstract td = md2.Owner; if(td.IsOpenType == false) { context.SetContextAsTypeParameters( TypeRepresentation.SharedEmptyArray ); } else { if(td is MetaDataTypeDefinitionArray || td is MetaDataTypeDefinitionByRef ) { // // We need to keep the full context around during delayed array/byref expansion. // } else { context.SetContextAsMethodParameters( TypeRepresentation.SharedEmptyArray ); } } } return md2; } else { throw TypeConsistencyErrorException.Create( "Cannot flatten method {0}", md ); } } //--// private MetaDataField FlattenFieldDefinition( MetaDataFieldAbstract fdIn , ref ConversionContext context ) { MetaDataFieldAbstract fd = fdIn; while(true) { if(fd is MetaDataFieldWithContext) { MetaDataFieldWithContext fd2 = (MetaDataFieldWithContext)fd; TypeRepresentation td = ConvertToIR( fd2.ContextType, context ); context.SetContextAsType( td ); fd = fd2.BaseField; } else if(fd is MetaDataField) { MetaDataField fd2 = (MetaDataField)fd; if(fd2.IsOpenField == false && fd2.Owner.IsOpenType == false) { context.SetContextAsTypeParameters( TypeRepresentation.SharedEmptyArray ); } return fd2; } else { throw TypeConsistencyErrorException.Create( "Cannot flatten field {0}", fdIn ); } } } //--// [System.Diagnostics.Conditional( "TYPESYSTEM_REPORT" )] public void Report( string format , params object[] args ) { InnerReport( format, args ); } [System.Diagnostics.Conditional( "TYPESYSTEM_REPORT_VERBOSE" )] public void ReportVerbose( string format , params object[] args ) { InnerReport( format, args ); } protected virtual void InnerReport( string format , params object[] args ) { } //--// internal void QueueDelayedTypeAnalysis( TypeRepresentation td , ref ConversionContext context ) { m_pendingTypeAnalysis.Schedule( td, ref context, delegate( TypeRepresentation target, ref ConversionContext ctx ) { PerformDelayedTypeAnalysis( target, ref ctx ); } ); } internal void QueueDelayedMethodAnalysis( MethodRepresentation md , ref ConversionContext context ) { m_pendingMethodAnalysis.Schedule( md, ref context, delegate( MethodRepresentation target, ref ConversionContext ctx ) { PerformDelayedMethodAnalysis( target, ref ctx ); } ); } internal void QueueDelayedCustomAttributeAnalysis( TypeRepresentation td , ref ConversionContext context ) { m_pendingTypeCustomAttributeAnalysis.Schedule( td, ref context, delegate( TypeRepresentation target, ref ConversionContext ctx ) { PerformDelayedCustomAttributeAnalysis( target, ref ctx ); } ); } internal void QueueDelayedCustomAttributeAnalysis( MethodRepresentation md , ref ConversionContext context ) { m_pendingMethodCustomAttributeAnalysis.Schedule( md, ref context, delegate( MethodRepresentation target, ref ConversionContext ctx ) { PerformDelayedCustomAttributeAnalysis( target, ref ctx ); } ); } //--// private bool IsMSCORLIB( MetaDataTypeDefinitionAbstract td ) { AssemblyRepresentation asmlIR = ConvertToIR( td.Owner ); return m_required_mscorlib == asmlIR; } private bool IsObjectClass( MetaDataTypeDefinitionBase td ) { if(IsMSCORLIB( td ) && td.Namespace == "System" && td.Name == "Object" ) { return true; } return false; } private bool IsValueType( MetaDataTypeDefinitionBase td ) { if(IsMSCORLIB( td ) && td.Namespace == "System" && td.Name == "ValueType" ) { return true; } return false; } private bool IsEnumType( MetaDataTypeDefinitionBase td ) { if(IsMSCORLIB( td ) && td.Namespace == "System" && td.Name == "Enum" ) { return true; } return false; } //--// public virtual void ApplyTransformation( TransformationContext context ) { context.Push( this ); context.Transform( ref m_applicationEntryPoint ); context.Transform( ref m_assemblies ); context.Transform( ref m_types ); context.Transform( ref m_resources ); context.Transform( ref m_exportedMethods ); context.Transform( ref m_defaultValues ); context.Transform( ref m_required_mscorlib ); context.Transform( ref m_wellKnownTypes ); context.Transform( ref m_wellKnownMethods ); context.Transform( ref m_wellKnownFields ); context.Transform( ref m_wellKnownTypesByName ); context.Transform( ref m_wellKnownMethodsByName ); context.Transform( ref m_wellKnownFieldsByName ); context.Pop(); } //--// protected virtual void Reduce( TypeSystem.Reachability reachability , bool fApply ) { for(int i = m_types.Count; --i >= 0; ) { TypeRepresentation td = m_types[i]; if(reachability.Contains( td ) == false) { td.ProhibitUse( reachability, fApply ); if(fApply) { m_types.RemoveAt( i ); } } else { td.Reduce( reachability, fApply ); } } //--// for(int i = m_assemblies.Count; --i >= 0; ) { AssemblyRepresentation asml = m_assemblies[i]; if(reachability.Contains( asml ) == false) { reachability.ExpandProhibition( asml ); if(fApply) { m_assemblies.RemoveAt( i ); } } } //--// TypeSystem.ReduceHashTable( ref m_defaultValues , reachability, true , false, fApply ); TypeSystem.ReduceHashTable( ref m_wellKnownTypesByName , reachability, false, true , fApply ); TypeSystem.ReduceHashTable( ref m_wellKnownMethodsByName, reachability, false, true , fApply ); TypeSystem.ReduceHashTable( ref m_wellKnownFieldsByName , reachability, false, true , fApply ); if(fApply) { RefreshWellKnownEntities(); } //--// if(reachability.Contains( m_applicationEntryPoint ) == false) { if(fApply) { m_applicationEntryPoint = null; } } } public void RemoveDuplicateType( TypeRepresentation td ) { for(int i = m_types.Count; --i >= 0; ) { if(Object.ReferenceEquals( td, m_types[i] )) { m_types.RemoveAt( i ); } } } //--// public static void ReduceHashTable< TKey, TValue >( ref GrowOnlyHashTable< TKey, TValue > ht , Reachability reachability , bool fKeyMustBeReachable , bool fValueMustBeReachable , bool fApply ) { if(fApply) { GrowOnlyHashTable< TKey, TValue > copy = ht.CloneSettings(); foreach(TKey key in ht.Keys) { TValue val = ht[key]; if((fKeyMustBeReachable == false || (key != null && reachability.Contains( key ))) && (fValueMustBeReachable == false || (val != null && reachability.Contains( val ))) ) { copy[key] = val; } } ht = copy; } } public static void ReduceSet< TKey >( ref GrowOnlySet< TKey > set , Reachability reachability , bool fApply ) { if(fApply) { GrowOnlySet< TKey > copy = set.CloneSettings(); foreach(TKey key in set) { if(reachability.Contains( key )) { copy.Insert( key ); } } set = copy; } } //--// // // Access Methods // public MethodRepresentation ApplicationEntryPoint { get { return m_applicationEntryPoint; } } public List< AssemblyRepresentation > Assemblies { get { return m_assemblies; } } public List< TypeRepresentation > Types { get { return m_types; } } public List< ResourceRepresentation > Resources { get { return m_resources; } } public List< MethodRepresentation > ExportedMethods { get { return m_exportedMethods; } } public InstantiationContext InstantiationContext { get { return m_instantiationContext; } } public WellKnownTypes WellKnownTypes { get { return m_wellKnownTypes; } } public WellKnownMethods WellKnownMethods { get { return m_wellKnownMethods; } } public WellKnownFields WellKnownFields { get { return m_wellKnownFields; } } public void GetTypeSystemStatistics(ref int types, ref int fields, ref int methods ) { types = 0; fields = 0; methods = 0; foreach(var tr in this.Types) { if(ShouldIncludeInCodeGenStats( tr )) { types += 1; fields += tr.Fields.Length; methods += tr.Methods.Length; } } } public bool ShouldIncludeInCodeGenStats( TypeRepresentation tr ) { if( tr is SzArrayReferenceTypeRepresentation || tr is BoxedValueTypeRepresentation || tr is ManagedPointerTypeRepresentation || tr is UnmanagedPointerTypeRepresentation || tr is DelayedMethodParameterTypeRepresentation || tr is DelayedTypeParameterTypeRepresentation || tr is PinnedPointerTypeRepresentation ) { return false; } if(tr.IsOpenType) { return false; } if( tr is ArrayReferenceTypeRepresentation ) { TypeRepresentation contained = tr.ContainedType; if( contained is DelayedMethodParameterTypeRepresentation || contained is DelayedTypeParameterTypeRepresentation ) { return false; } } return true; } //--// public T GetEnvironmentService< T >() { return (T)m_environmentProvider.GetService( typeof(T) ); } public TypeRepresentation GetWellKnownType( string name ) { TypeRepresentation td = GetWellKnownTypeNoThrow( name ); if(td == null) { throw TypeConsistencyErrorException.Create( "Missing well-known type {0}", name ); } return td; } public MethodRepresentation GetWellKnownMethod( string name ) { MethodRepresentation md = GetWellKnownMethodNoThrow( name ); if(md == null) { throw TypeConsistencyErrorException.Create( "Missing well-known method {0}", name ); } return md; } public FieldRepresentation GetWellKnownField( string name ) { FieldRepresentation fd = GetWellKnownFieldNoThrow( name ); if(fd == null) { throw TypeConsistencyErrorException.Create( "Missing well-known field {0}", name ); } return fd; } public TypeRepresentation GetWellKnownTypeNoThrow( string name ) { return GetWellKnownEntity( m_wellKnownTypes, m_wellKnownTypesByName, name ); } public MethodRepresentation GetWellKnownMethodNoThrow( string name ) { return GetWellKnownEntity( m_wellKnownMethods, m_wellKnownMethodsByName, name ); } public FieldRepresentation GetWellKnownFieldNoThrow( string name ) { return GetWellKnownEntity( m_wellKnownFields, m_wellKnownFieldsByName, name ); } private T GetWellKnownEntity( object obj , GrowOnlyHashTable< string, T > lookup , string name ) where T : BaseRepresentation { T res; if(lookup.TryGetValue( name, out res )) { return res; } System.Reflection.FieldInfo fi = obj.GetType().GetField( name, System.Reflection.BindingFlags.Public | System.Reflection.BindingFlags.Instance ); if(fi != null) { return (T)fi.GetValue( obj ); } return null; } //--// public void SetWellKnownType( string name , TypeRepresentation td ) { SetWellKnownEntity( m_wellKnownTypes, m_wellKnownTypesByName, name, td ); } public void SetWellKnownMethod( string name , MethodRepresentation md ) { SetWellKnownEntity( m_wellKnownMethods, m_wellKnownMethodsByName, name, md ); } public void SetWellKnownField( string name , FieldRepresentation fd ) { SetWellKnownEntity( m_wellKnownFields, m_wellKnownFieldsByName, name, fd ); } private static void SetWellKnownEntity< T >( object obj , GrowOnlyHashTable< string, T > lookup , string name , T bd ) where T : BaseRepresentation { lookup[name] = bd; System.Reflection.FieldInfo fi = obj.GetType().GetField( name, System.Reflection.BindingFlags.Public | System.Reflection.BindingFlags.Instance ); if(fi != null) { fi.SetValue( obj, bd ); } } //--// public void RefreshWellKnownEntities() { RefreshWellKnownEntity( m_wellKnownTypes , m_wellKnownTypesByName ); RefreshWellKnownEntity( m_wellKnownMethods, m_wellKnownMethodsByName ); RefreshWellKnownEntity( m_wellKnownFields , m_wellKnownFieldsByName ); } private static void RefreshWellKnownEntity< T >( object obj , GrowOnlyHashTable< string, T > lookup ) where T : BaseRepresentation { foreach(System.Reflection.FieldInfo fi in ReflectionHelper.GetAllPublicInstanceFields( obj.GetType() )) { T bd; lookup.TryGetValue( fi.Name, out bd ); fi.SetValue( obj, bd ); } } //--// public void EnumerateFields( FieldEnumerationCallback callback ) { foreach(TypeRepresentation td in this.Types) { foreach(FieldRepresentation fd in td.Fields) { callback( fd ); } } } public void EnumerateMethods( MethodEnumerationCallback callback ) { foreach(TypeRepresentation td in this.Types) { foreach(MethodRepresentation md in td.Methods) { callback( md ); } } } public void EnumerateCustomAttributes( CustomAttributeAssociationEnumerationCallback callback ) { foreach(TypeRepresentation td in m_types) { td.EnumerateCustomAttributes( callback ); } } private CustomAttributeNotification EnsureCustomAttributeNotification( TypeRepresentation td ) { CustomAttributeNotification res; if(m_customAttributeNotification.TryGetValue( td, out res ) == false) { res = new CustomAttributeNotification(); m_customAttributeNotification[td] = res; } return res; } public void RegisterForNotificationOfAttributeOnGeneric( TypeRepresentation td , NotificationOfAttributeOnGeneric target ) { CustomAttributeNotification res = EnsureCustomAttributeNotification( td ); res.m_notificationOfAttributeOnGeneric += target; } public void RegisterForNotificationOfAttributeOnType( TypeRepresentation td , NotificationOfAttributeOnType target ) { CustomAttributeNotification res = EnsureCustomAttributeNotification( td ); res.m_notificationOfAttributeOnType += target; } public void RegisterForNotificationOfAttributeOnField( TypeRepresentation td , NotificationOfAttributeOnField target ) { CustomAttributeNotification res = EnsureCustomAttributeNotification( td ); res.m_notificationOfAttributeOnField += target; } public void RegisterForNotificationOfAttributeOnMethod( TypeRepresentation td , NotificationOfAttributeOnMethod target ) { CustomAttributeNotification res = EnsureCustomAttributeNotification( td ); res.m_notificationOfAttributeOnMethod += target; } public void RegisterForNotificationOfAttributeOnParam( TypeRepresentation td , NotificationOfAttributeOnParam target ) { CustomAttributeNotification res = EnsureCustomAttributeNotification( td ); res.m_notificationOfAttributeOnParam += target; } public void RegisterForNewAssembly( NotificationOfNewAssembly callback ) { m_notificationOfNewAssembly += callback; } public void RegisterForNewType( NotificationOfNewType callback ) { m_notificationOfNewType += callback; } public void RegisterForNewField( NotificationOfNewField callback ) { m_notificationOfNewField += callback; } public void RegisterForNewMethod( NotificationOfNewMethod callback ) { m_notificationOfNewMethod += callback; } public void RegisterForTypeLayoutDelegation( TypeRepresentation td , TypeLayoutCallback callback ) { m_layoutDelegation[td] = callback; } //--// public byte[] GetDefaultValue( FieldRepresentation fd ) { object res; if(m_defaultValues.TryGetValue( fd, out res )) { return (byte[])res; } return null; } public TypeRepresentation GetBuiltInType( TypeRepresentation.BuiltInTypes el ) { switch(el) { case TypeRepresentation.BuiltInTypes.VOID : return m_wellKnownTypes.System_Void ; case TypeRepresentation.BuiltInTypes.BOOLEAN : return m_wellKnownTypes.System_Boolean ; case TypeRepresentation.BuiltInTypes.CHAR : return m_wellKnownTypes.System_Char ; case TypeRepresentation.BuiltInTypes.I1 : return m_wellKnownTypes.System_SByte ; case TypeRepresentation.BuiltInTypes.U1 : return m_wellKnownTypes.System_Byte ; case TypeRepresentation.BuiltInTypes.I2 : return m_wellKnownTypes.System_Int16 ; case TypeRepresentation.BuiltInTypes.U2 : return m_wellKnownTypes.System_UInt16 ; case TypeRepresentation.BuiltInTypes.I4 : return m_wellKnownTypes.System_Int32 ; case TypeRepresentation.BuiltInTypes.U4 : return m_wellKnownTypes.System_UInt32 ; case TypeRepresentation.BuiltInTypes.I8 : return m_wellKnownTypes.System_Int64 ; case TypeRepresentation.BuiltInTypes.U8 : return m_wellKnownTypes.System_UInt64 ; case TypeRepresentation.BuiltInTypes.R4 : return m_wellKnownTypes.System_Single ; case TypeRepresentation.BuiltInTypes.R8 : return m_wellKnownTypes.System_Double ; case TypeRepresentation.BuiltInTypes.STRING : return m_wellKnownTypes.System_String ; case TypeRepresentation.BuiltInTypes.VALUETYPE : return m_wellKnownTypes.System_ValueType ; case TypeRepresentation.BuiltInTypes.CLASS : return m_wellKnownTypes.System_Object ; case TypeRepresentation.BuiltInTypes.TYPEDBYREF: return m_wellKnownTypes.System_TypedReference; case TypeRepresentation.BuiltInTypes.I : return m_wellKnownTypes.System_IntPtr ; case TypeRepresentation.BuiltInTypes.U : return m_wellKnownTypes.System_UIntPtr ; case TypeRepresentation.BuiltInTypes.OBJECT : return m_wellKnownTypes.System_Object ; case TypeRepresentation.BuiltInTypes.SZARRAY : return m_wellKnownTypes.System_Array ; } CHECKS.ASSERT( false, "Missing required type {0}", el ); return null; } private TypeRepresentation[] m_nativeTypes; public TypeRepresentation[] BuiltInTypes { get { if( m_nativeTypes == null ) { m_nativeTypes = new TypeRepresentation[ 21 ]; m_nativeTypes[ 0 ] = m_wellKnownTypes.System_Void; m_nativeTypes[ 1 ] = m_wellKnownTypes.System_Boolean; m_nativeTypes[ 2 ] = m_wellKnownTypes.System_Char; m_nativeTypes[ 3 ] = m_wellKnownTypes.System_SByte; m_nativeTypes[ 4 ] = m_wellKnownTypes.System_Byte; m_nativeTypes[ 5 ] = m_wellKnownTypes.System_Int16; m_nativeTypes[ 6 ] = m_wellKnownTypes.System_UInt16; m_nativeTypes[ 7 ] = m_wellKnownTypes.System_Int32; m_nativeTypes[ 8 ] = m_wellKnownTypes.System_UInt32; m_nativeTypes[ 9 ] = m_wellKnownTypes.System_Int64; m_nativeTypes[ 10 ] = m_wellKnownTypes.System_UInt64; m_nativeTypes[ 11 ] = m_wellKnownTypes.System_Single; m_nativeTypes[ 12 ] = m_wellKnownTypes.System_Double; m_nativeTypes[ 13 ] = m_wellKnownTypes.System_String; m_nativeTypes[ 14 ] = m_wellKnownTypes.System_ValueType; m_nativeTypes[ 15 ] = m_wellKnownTypes.System_Object; m_nativeTypes[ 16 ] = m_wellKnownTypes.System_TypedReference; m_nativeTypes[ 17 ] = m_wellKnownTypes.System_IntPtr; m_nativeTypes[ 18 ] = m_wellKnownTypes.System_UIntPtr; m_nativeTypes[ 19 ] = m_wellKnownTypes.System_Object; m_nativeTypes[ 20 ] = m_wellKnownTypes.System_Array; } return m_nativeTypes; } } //--// internal void Analyze_GenericParameterDefinition( MetaDataGenericParam src , ref GenericParameterDefinition dst , ref ConversionContext context ) { dst.Flags = (GenericParameterDefinition.Attributes)src.Flags; dst.Name = src.Name; MetaDataTypeDefinitionAbstract[] genericParamConstraints = src.GenericParamConstraints; if(genericParamConstraints != null) { dst.Constraints = new TypeRepresentation[genericParamConstraints.Length]; for(int j = 0; j < genericParamConstraints.Length; j++) { dst.Constraints[j] = ConvertToIR( genericParamConstraints[j], context ); } } else { dst.Constraints = TypeRepresentation.SharedEmptyArray; } } public virtual CodePointer CreateCodePointer( MethodRepresentation md ) { throw new NotImplementedException(); } public virtual bool IncludeInGCInfo( InstanceFieldRepresentation fd ) { throw new NotImplementedException(); } } //--// #if TYPESYSTEM_REDUCE_FOOTPRINT [ExtendClass(typeof(TypeRepresentation), NoConstructors=true)] public class TypeRepresentationImpl { public override bool Equals( object obj ) { return Object.ReferenceEquals( this, obj ); } public override int GetHashCode() { return 0; } internal virtual void PrettyToString( System.Text.StringBuilder sb , bool fPrefix , bool fWithAbbreviations ) { } public override string ToString() { return base.ToString(); } public TypeRepresentation[] GenericParameters { get { return TypeRepresentation.SharedEmptyArray; } } public GenericParameterDefinition[] GenericParameterDefinitions { get { return null; } } } [ExtendClass(typeof(DelayedMethodParameterTypeRepresentation), NoConstructors=true)] public sealed class DelayedMethodParameterTypeRepresentationImpl : TypeRepresentationImpl { internal override void PrettyToString( System.Text.StringBuilder sb , bool fPrefix , bool fWithAbbreviations ) { } } [ExtendClass(typeof(DelayedTypeParameterTypeRepresentation), NoConstructors=true)] public sealed class DelayedTypeParameterTypeRepresentationImpl : TypeRepresentationImpl { internal override void PrettyToString( System.Text.StringBuilder sb , bool fPrefix , bool fWithAbbreviations ) { } } [ExtendClass(typeof(MethodRepresentation), NoConstructors=true)] public class MethodRepresentationImpl { public override bool Equals( object obj ) { return Object.ReferenceEquals( this, obj ); } public override int GetHashCode() { return 0; } protected void PrettyToString( System.Text.StringBuilder sb , bool fPrefix ) { } public override string ToString() { return base.ToString(); } public TypeRepresentation[] GenericParameters { get { return TypeRepresentation.SharedEmptyArray; } } public GenericParameterDefinition[] GenericParametersDefinition { get { return null; } } } #endif } ================================================ FILE: Zelig/Zelig/RunTime/Zelig/TypeSystem/TypeSystem.csproj ================================================  Debug AnyCPU 9.0.21022 2.0 {186F31A3-EF89-4A25-B2D5-20060720AA01} Library Properties Microsoft.Zelig.Runtime.TypeSystem Microsoft.Zelig.Runtime.TypeSystem $(LlilumBuildRoot)\Host\obj\$(MSBuildProjectName)\ v4.5 true full false $(LlilumBuildRoot)\Host\bin\$(Configuration)\ DEBUG;TRACE prompt 4 true false AllRules.ruleset AnyCPU false pdbonly true $(LlilumBuildRoot)\Host\bin\$(Configuration)\ TRACE prompt 4 true false AllRules.ruleset AnyCPU false true full false $(LlilumBuildRoot)\Host\bin\$(Configuration)\ TRACE;DEBUG;TRANSFORMATIONCONTEXT_SHOWALLMETHODSTODEBUGGER; true AnyCPU false {186F31A3-EF89-4A25-B2D5-20060510AA01} Normalized False {186F31A3-EF89-4A25-B2D5-20061218AA01} Common False 3.5 ================================================ FILE: Zelig/Zelig/RunTime/Zelig/TypeSystem/Types/AbstractReferenceTypeRepresentation.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // namespace Microsoft.Zelig.Runtime.TypeSystem { using System; using System.Collections.Generic; public class AbstractReferenceTypeRepresentation : ReferenceTypeRepresentation { // // Constructor Methods // public AbstractReferenceTypeRepresentation( AssemblyRepresentation owner , BuiltInTypes builtinType , Attributes flags , GenericContext genericContext ) : base( owner, builtinType, flags, genericContext ) { } //--// // // Helper Methods // protected override TypeRepresentation AllocateInstantiation( InstantiationContext ic ) { AbstractReferenceTypeRepresentation tdRes = new AbstractReferenceTypeRepresentation( m_owner, m_builtinType, m_flags, new GenericContext( this, ic.TypeParameters ) ); tdRes.PopulateInstantiation( this, ic ); return tdRes; } //--// // // Access Methods // //--// // // Debug Methods // public override String ToString() { System.Text.StringBuilder sb = new System.Text.StringBuilder( "AbstractReferenceTypeRepresentation(" ); PrettyToString( sb, true, false ); sb.Append( ")" ); return sb.ToString(); } } } ================================================ FILE: Zelig/Zelig/RunTime/Zelig/TypeSystem/Types/ArrayReferenceTypeRepresentation.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // namespace Microsoft.Zelig.Runtime.TypeSystem { using System; using System.Collections.Generic; public abstract class ArrayReferenceTypeRepresentation : ReferenceTypeRepresentation { // // State // protected TypeRepresentation m_elementType; // // Constructor Methods // protected ArrayReferenceTypeRepresentation( AssemblyRepresentation owner , BuiltInTypes builtinType , Attributes flags , TypeRepresentation elementType ) : base( owner, builtinType, flags ) { m_elementType = elementType; } // // MetaDataEquality Methods // public override bool EqualsThroughEquivalence( object obj , EquivalenceSet set ) { if(obj is ArrayReferenceTypeRepresentation) { ArrayReferenceTypeRepresentation other = (ArrayReferenceTypeRepresentation)obj; return EqualsThroughEquivalence( m_elementType, other.m_elementType, set ); } return false; } public override bool Equals( object obj ) { return this.EqualsThroughEquivalence( obj, null ); } public override int GetHashCode() { return m_elementType.GetHashCode(); } //--// // // Helper Methods // protected override void PerformInnerDelayedTypeAnalysis( TypeSystem typeSystem , ref ConversionContext context ) { m_extends = (ReferenceTypeRepresentation)typeSystem.WellKnownTypes.System_Array; if(this.IsDelayedType == false) { MetaData.Normalized.MetaDataTypeDefinitionArray metadata = (MetaData.Normalized.MetaDataTypeDefinitionArray)typeSystem.GetAssociatedMetaData( this ); if(metadata != null) { AnalyzeEntries( typeSystem, ref context, metadata.Interfaces, null, metadata.Methods, null ); } } } public override void ApplyTransformation( TransformationContext context ) { context.Push( this ); // // Load before calling the base method, because we might get a call to GetHashCode(). // context.Transform( ref m_elementType ); base.ApplyTransformation( context ); context.Pop(); } //--// public abstract bool SameShape( ArrayReferenceTypeRepresentation other ); //--// // // Access Methods // public override TypeRepresentation ContainedType { get { return m_elementType; } } public override bool IsOpenType { get { return m_elementType.IsOpenType; } } public override bool IsDelayedType { get { return m_elementType.IsDelayedType; } } //--// public override bool CanBeAssignedFrom( TypeRepresentation rvalue , EquivalenceSet set ) { if(this.EqualsThroughEquivalence( rvalue, set )) { return true; } if(rvalue is ArrayReferenceTypeRepresentation) { ArrayReferenceTypeRepresentation rvalue2 = (ArrayReferenceTypeRepresentation)rvalue; TypeRepresentation thisElementType = this .ContainedType; TypeRepresentation rvalueElementType = rvalue2.ContainedType; if(thisElementType.EqualsThroughEquivalence( rvalueElementType, set )) { return true; } if(thisElementType is ReferenceTypeRepresentation) { return thisElementType.CanBeAssignedFrom( rvalueElementType, set ); } else if(thisElementType is EnumerationTypeRepresentation && rvalueElementType is EnumerationTypeRepresentation ) { if(thisElementType.BuiltInType == rvalueElementType.BuiltInType) { return true; } } } return false; } } } ================================================ FILE: Zelig/Zelig/RunTime/Zelig/TypeSystem/Types/BoxedValueTypeRepresentation.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // namespace Microsoft.Zelig.Runtime.TypeSystem { using System; using System.Collections.Generic; public sealed class BoxedValueTypeRepresentation : ReferenceTypeRepresentation { // // State // private TypeRepresentation m_valueType; // We need to use TypeRepresentation instead of ValueTypeRepresentation because we might need to box a delayed type. // // Constructor Methods // public BoxedValueTypeRepresentation( TypeRepresentation valueType ) : base( valueType.Owner, valueType.BuiltInType, valueType.Flags ) { m_valueType = valueType; var field = new InstanceFieldRepresentation(this, ".value", valueType); field.Offset = 0; AddField(field); } // // MetaDataEquality Methods // public override bool EqualsThroughEquivalence( object obj , EquivalenceSet set ) { if(obj is BoxedValueTypeRepresentation) { BoxedValueTypeRepresentation other = (BoxedValueTypeRepresentation)obj; return EqualsThroughEquivalence( m_valueType, other.m_valueType, set ); } return false; } public override bool Equals( object obj ) { return this.EqualsThroughEquivalence( obj, null ); } public override int GetHashCode() { return m_valueType.GetHashCode(); } //--// // // Helper Methods // protected override void PerformInnerDelayedTypeAnalysis( TypeSystem typeSystem , ref ConversionContext context ) { m_extends = m_valueType.Extends; } //--// public override void ApplyTransformation( TransformationContext context ) { context.Push( this ); // // Load before calling the base method, because we might get a call to GetHashCode(). // context.Transform( ref m_valueType ); base.ApplyTransformation( context ); context.Pop(); } //--// protected override TypeRepresentation AllocateInstantiation( InstantiationContext ic ) { TypeRepresentation valueType = ic.Instantiate( m_valueType ); // // When expanding box or unbox in the context of a generic method or type, we might need to box a delayed type. // At instantiation time, the delayed type might be resolved to a reference type. // if(valueType is ValueTypeRepresentation) { BoxedValueTypeRepresentation tdRes = new BoxedValueTypeRepresentation( valueType ); tdRes.PopulateInstantiation( this, ic ); return tdRes; } else { return valueType; } } //--// public override GCInfo.Kind ClassifyAsPointer() { return GCInfo.Kind.Internal; } // // Access Methods // public override TypeRepresentation ContainedType { get { return m_valueType; } } public override TypeRepresentation UnderlyingType { get { return m_valueType; } } public override bool IsOpenType { get { return m_valueType.IsOpenType; } } public override bool IsDelayedType { get { return m_valueType.IsDelayedType; } } public override StackEquivalentType StackEquivalentType { get { return StackEquivalentType.Object; } } //--// public override bool CanBeAssignedFrom( TypeRepresentation rvalue , EquivalenceSet set ) { if(this.EqualsThroughEquivalence( rvalue, set )) { return true; } if(rvalue is PointerTypeRepresentation) { // // Going from a byref to a boxed valuetype is OK. // return m_valueType.EqualsThroughEquivalence( rvalue.UnderlyingType, set ); } return m_valueType.CanBeAssignedFrom( rvalue, set ); } //--// // // Debug Methods // public override String ToString() { System.Text.StringBuilder sb = new System.Text.StringBuilder( "BoxedValueTypeRepresentation(" ); PrettyToString( sb, true, false ); sb.Append( ")" ); return sb.ToString(); } internal override void PrettyToString( System.Text.StringBuilder sb , bool fPrefix , bool fWithAbbreviations ) { sb.Append( "boxed " ); m_valueType.PrettyToString( sb, fPrefix, fWithAbbreviations ); } } } ================================================ FILE: Zelig/Zelig/RunTime/Zelig/TypeSystem/Types/ConcreteReferenceTypeRepresentation.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // namespace Microsoft.Zelig.Runtime.TypeSystem { using System; using System.Collections.Generic; public sealed class ConcreteReferenceTypeRepresentation : ReferenceTypeRepresentation { // // Constructor Methods // public ConcreteReferenceTypeRepresentation( AssemblyRepresentation owner , BuiltInTypes builtinType , Attributes flags , GenericContext genericContext ) : base( owner, builtinType, flags, genericContext ) { } //--// // // Helper Methods // protected override TypeRepresentation AllocateInstantiation( InstantiationContext ic ) { ConcreteReferenceTypeRepresentation tdRes = new ConcreteReferenceTypeRepresentation( m_owner, m_builtinType, m_flags, new GenericContext( this, ic.TypeParameters ) ); tdRes.PopulateInstantiation( this, ic ); return tdRes; } //--// // // Access Methods // //--// // // Debug Methods // public override String ToString() { System.Text.StringBuilder sb = new System.Text.StringBuilder( "ConcreteReferenceTypeRepresentation(" ); PrettyToString( sb, true, false ); sb.Append( ")" ); return sb.ToString(); } } } ================================================ FILE: Zelig/Zelig/RunTime/Zelig/TypeSystem/Types/DelayedMethodParameterTypeRepresentation.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // namespace Microsoft.Zelig.Runtime.TypeSystem { using System; using System.Collections.Generic; public sealed class DelayedMethodParameterTypeRepresentation : TypeRepresentation { // // State // private MethodRepresentation m_context; private int m_parameterNumber; // // Constructor Methods // public DelayedMethodParameterTypeRepresentation( AssemblyRepresentation owner , MethodRepresentation context , int parameterNumber ) : base( owner, BuiltInTypes.VAR, Attributes.None ) { m_context = context; m_parameterNumber = parameterNumber; } // // MetaDataEquality Methods // public override bool EqualsThroughEquivalence( object obj , EquivalenceSet set ) { if(obj is DelayedMethodParameterTypeRepresentation) { DelayedMethodParameterTypeRepresentation other = (DelayedMethodParameterTypeRepresentation)obj; if(m_parameterNumber == other.m_parameterNumber) { // // Don't compare the context with Equals, it would lead to an infinite recursion! // if(Object.ReferenceEquals( m_context, other.m_context )) { return true; } if(set != null) { if(set.AreEquivalent( this, this.m_context, other, other.m_context )) { return true; } } } } return false; } public override bool Equals( object obj ) { return this.EqualsThroughEquivalence( obj, null ); } public override int GetHashCode() { return (int)m_parameterNumber ^ m_context.GetHashCode(); } //--// // // Helper Methods // protected override void PerformInnerDelayedTypeAnalysis( TypeSystem typeSystem , ref ConversionContext context ) { m_extends = (ReferenceTypeRepresentation)typeSystem.WellKnownTypes.System_Object; foreach(TypeRepresentation td in m_context.GenericParametersDefinition[m_parameterNumber].Constraints) { if(td is InterfaceTypeRepresentation) { continue; } m_extends = td; break; } } //--// public override void ApplyTransformation( TransformationContext context ) { context.Push( this ); // // Load before calling the base method, because we might get a call to GetHashCode(). // context.Transform( ref m_context ); context.Transform( ref m_parameterNumber ); base.ApplyTransformation( context ); context.Pop(); } //--// protected override void SetShapeCategory( TypeSystem typeSystem ) { m_vTable.ShapeCategory = VTable.Shape.Invalid; } //--// protected override TypeRepresentation AllocateInstantiation( InstantiationContext ic ) { return ic.MethodParameters[m_parameterNumber]; } //--// public override GCInfo.Kind ClassifyAsPointer() { return GCInfo.Kind.Invalid; } //--// public override InstantiationFlavor GetInstantiationFlavor( TypeSystem typeSystem ) { if(m_extends.IsObject) { return InstantiationFlavor.Delayed; } if(m_extends == typeSystem.WellKnownTypes.System_ValueType) { return InstantiationFlavor.ValueType; } return m_extends.GetInstantiationFlavor( typeSystem ); } // // Access Methods // public override bool IsOpenType { get { return true; } } public override bool IsDelayedType { get { return true; } } public override uint SizeOfHoldingVariable { get { return 0; } } public override bool CanPointToMemory { get { return false; // We don't know at this stage. } } public MethodRepresentation Context { get { return m_context; } } public int ParameterNumber { get { return m_parameterNumber; } } //--// // // Debug Methods // public override String ToString() { System.Text.StringBuilder sb = new System.Text.StringBuilder( "DelayedMethodParameterTypeRepresentation(" ); PrettyToString( sb, true, false ); sb.Append( "," ); sb.Append( m_context ); sb.Append( ")" ); return sb.ToString(); } internal override void PrettyToString( System.Text.StringBuilder sb , bool fPrefix , bool fWithAbbreviations ) { if(m_context.GenericParameters != null && m_parameterNumber < m_context.GenericParameters.Length) { m_context.GenericParameters[m_parameterNumber].PrettyToString( sb, fPrefix, fWithAbbreviations ); } else if(m_context.GenericParametersDefinition != null && m_parameterNumber < m_context.GenericParametersDefinition.Length) { sb.Append( m_context.GenericParametersDefinition[m_parameterNumber].Name ); } else { sb.Append( "{MVAR," ); sb.Append( m_parameterNumber ); sb.Append( "}" ); } } } } ================================================ FILE: Zelig/Zelig/RunTime/Zelig/TypeSystem/Types/DelayedTypeParameterTypeRepresentation.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // namespace Microsoft.Zelig.Runtime.TypeSystem { using System; using System.Collections.Generic; public sealed class DelayedTypeParameterTypeRepresentation : TypeRepresentation { // // State // private TypeRepresentation m_context; private int m_parameterNumber; // // Constructor Methods // public DelayedTypeParameterTypeRepresentation( AssemblyRepresentation owner , TypeRepresentation context , int parameterNumber ) : base( owner, BuiltInTypes.VAR, Attributes.None ) { m_context = context; m_parameterNumber = parameterNumber; } // // MetaDataEquality Methods // public override bool EqualsThroughEquivalence( object obj , EquivalenceSet set ) { if(obj is DelayedTypeParameterTypeRepresentation) { DelayedTypeParameterTypeRepresentation other = (DelayedTypeParameterTypeRepresentation)obj; if(m_parameterNumber == other.m_parameterNumber) { // // Don't compare the context with Equals, it would lead to an infinite recursion! // if(Object.ReferenceEquals( m_context, other.m_context )) { return true; } if(set != null) { if(set.AreEquivalent( this, this.m_context, other, other.m_context )) { return true; } } } } return false; } public override bool Equals( object obj ) { return this.EqualsThroughEquivalence( obj, null ); } public override int GetHashCode() { return (int)m_parameterNumber ^ m_context.GetHashCode(); } //--// // // Helper Methods // protected override void PerformInnerDelayedTypeAnalysis( TypeSystem typeSystem , ref ConversionContext context ) { m_extends = (ReferenceTypeRepresentation)typeSystem.WellKnownTypes.System_Object; foreach(TypeRepresentation td in m_context.GenericParametersDefinition[m_parameterNumber].Constraints) { if(td is InterfaceTypeRepresentation) { continue; } m_extends = td; break; } } //--// public override void ApplyTransformation( TransformationContext context ) { context.Push( this ); // // Load before calling the base method, because we might get a call to GetHashCode(). // context.Transform( ref m_context ); context.Transform( ref m_parameterNumber ); base.ApplyTransformation( context ); context.Pop(); } //--// protected override void SetShapeCategory( TypeSystem typeSystem ) { m_vTable.ShapeCategory = VTable.Shape.Invalid; } //--// protected override TypeRepresentation AllocateInstantiation( InstantiationContext ic ) { return ic.TypeParameters[m_parameterNumber]; } //--// public override GCInfo.Kind ClassifyAsPointer() { return GCInfo.Kind.Invalid; } //--// public override InstantiationFlavor GetInstantiationFlavor( TypeSystem typeSystem ) { if(m_extends.IsObject) { return InstantiationFlavor.Delayed; } if(m_extends == typeSystem.WellKnownTypes.System_ValueType) { return InstantiationFlavor.ValueType; } return m_extends.GetInstantiationFlavor( typeSystem ); } //--// // // Access Methods // public override bool IsOpenType { get { return true; } } public override bool IsDelayedType { get { return true; } } public override uint SizeOfHoldingVariable { get { return 0; } } public override bool CanPointToMemory { get { return false; // We don't know at this stage. } } public TypeRepresentation Context { get { return m_context; } } public int ParameterNumber { get { return m_parameterNumber; } } //--// // // Debug Methods // public override String ToString() { System.Text.StringBuilder sb = new System.Text.StringBuilder( "DelayedTypeParameterTypeRepresentation(" ); PrettyToString( sb, true, false ); sb.Append( "," ); sb.Append( m_context ); sb.Append( ")" ); return sb.ToString(); } internal override void PrettyToString( System.Text.StringBuilder sb , bool fPrefix , bool fWithAbbreviations ) { GenericContext gc = m_context.Generic; if(gc != null) { TypeRepresentation[] parameters = gc.Parameters; if(m_parameterNumber < parameters.Length) { parameters[m_parameterNumber].PrettyToString( sb, fPrefix, fWithAbbreviations ); return; } GenericParameterDefinition[] defs = gc.ParametersDefinition; if(defs != null && m_parameterNumber < defs.Length) { sb.Append( defs[m_parameterNumber].Name ); return; } } sb.Append( "{VAR," ); sb.Append( m_parameterNumber ); sb.Append( "}" ); } } } ================================================ FILE: Zelig/Zelig/RunTime/Zelig/TypeSystem/Types/EnumerationTypeRepresentation.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // namespace Microsoft.Zelig.Runtime.TypeSystem { using System; using System.Collections.Generic; public sealed class EnumerationTypeRepresentation : ScalarTypeRepresentation { // // State // private TypeRepresentation m_underlyingType; private string[] m_literalsName; private ulong [] m_literalsValue; // // Constructor Methods // public EnumerationTypeRepresentation( AssemblyRepresentation owner , BuiltInTypes builtinType , Attributes flags , GenericContext genericContext , uint size ) : base( owner, builtinType, flags, genericContext, size ) { } //--// // // Helper Methods // protected override void PerformInnerDelayedTypeAnalysis( TypeSystem typeSystem , ref ConversionContext context ) { base.PerformInnerDelayedTypeAnalysis( typeSystem, ref context ); m_underlyingType = m_fields[0].FieldType; } public override void ApplyTransformation( TransformationContext context ) { context.Push( this ); base.ApplyTransformation( context ); context.Transform( ref m_underlyingType ); context.Transform( ref m_literalsName ); context.Transform( ref m_literalsValue ); context.Pop(); } //--// public void AddLiteral( string name , object value ) { ulong intVal; DataConversion.GetAsRawUlong( value, out intVal ); int len = m_literalsValue != null ? m_literalsValue.Length : 0; int pos = len; while(pos > 0) { if(m_literalsValue[pos-1] < intVal) { break; } pos--; } m_literalsName = ArrayUtility.InsertAtPositionOfArray( m_literalsName , pos, name ); m_literalsValue = ArrayUtility.InsertAtPositionOfArray( m_literalsValue, pos, intVal ); } public string FormatValue( object val ) { ulong intVal; if(DataConversion.GetAsRawUlong( val, out intVal )) { if(intVal != 0 && this.HasBuildTimeFlag( BuildTimeAttributes.FlagsAttribute )) { var sb = new System.Text.StringBuilder(); for(int i = m_literalsValue.Length; i-- > 0;) { ulong mask = m_literalsValue[i]; if((mask & intVal) == mask) { intVal &= ~mask; if(sb.Length != 0) { sb.Append( " | " ); } sb.Append( m_literalsName[i] ); } } if(intVal != 0) { if(sb.Length != 0) { sb.Append( " | " ); } sb.AppendFormat( "0x{0}", intVal ); } if(sb.Length != 0) { return sb.ToString(); } } for(int i = 0; i < m_literalsValue.Length; i++) { if(m_literalsValue[i] == intVal) { return m_literalsName[i]; } } } return val.ToString(); } // // Access Methods // public override StackEquivalentType StackEquivalentType { get { return m_underlyingType.StackEquivalentType; } } public override TypeRepresentation UnderlyingType { get { return m_underlyingType; } } //--// public override bool IsSigned { get { return m_underlyingType.IsSigned; } } public override bool IsInteger { get { return m_underlyingType.IsInteger; } } //--// public override bool CanBeAssignedFrom( TypeRepresentation rvalue , EquivalenceSet set ) { if(this.EqualsThroughEquivalence( rvalue, set )) { return true; } if(m_underlyingType.CanBeAssignedFrom( rvalue, set )) { return true; } return false; } //--// // // Debug Methods // public override String ToString() { System.Text.StringBuilder sb = new System.Text.StringBuilder( "EnumerationTypeRepresentation(" ); PrettyToString( sb, true, false ); sb.Append( ")" ); return sb.ToString(); } } } ================================================ FILE: Zelig/Zelig/RunTime/Zelig/TypeSystem/Types/InterfaceTypeRepresentation.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // namespace Microsoft.Zelig.Runtime.TypeSystem { using System; using System.Collections.Generic; public sealed class InterfaceTypeRepresentation : AbstractReferenceTypeRepresentation { public static new readonly InterfaceTypeRepresentation[] SharedEmptyArray = new InterfaceTypeRepresentation[0]; // // Constructor Methods // public InterfaceTypeRepresentation( AssemblyRepresentation owner , BuiltInTypes builtinType , Attributes flags , GenericContext genericContext ) : base( owner, builtinType, flags, genericContext ) { } //--// // // Helper Methods // protected override void SetShapeCategory( TypeSystem typeSystem ) { m_vTable.ShapeCategory = VTable.Shape.Interface; } //--// protected override TypeRepresentation AllocateInstantiation( InstantiationContext ic ) { InterfaceTypeRepresentation tdRes = new InterfaceTypeRepresentation( m_owner, m_builtinType, m_flags, new GenericContext( this, ic.TypeParameters ) ); tdRes.PopulateInstantiation( this, ic ); return tdRes; } //--// public override bool CanBeAssignedFrom( TypeRepresentation rvalue , EquivalenceSet set ) { rvalue = rvalue.UnderlyingType; while(rvalue != null) { if(this.EqualsThroughEquivalence( rvalue, set )) { return true; } foreach(InterfaceTypeRepresentation itf in rvalue.Interfaces) { if(this.CanBeAssignedFrom( itf, set )) { return true; } } rvalue = rvalue.Extends; } return false; } //--// // // Debug Methods // public override String ToString() { System.Text.StringBuilder sb = new System.Text.StringBuilder( "InterfaceTypeRepresentation(" ); PrettyToString( sb, true, false ); sb.Append( ")" ); return sb.ToString(); } } } ================================================ FILE: Zelig/Zelig/RunTime/Zelig/TypeSystem/Types/ManagedPointerTypeRepresentation.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // namespace Microsoft.Zelig.Runtime.TypeSystem { using System; using System.Collections.Generic; public sealed class ManagedPointerTypeRepresentation : PointerTypeRepresentation { // // Constructor Methods // public ManagedPointerTypeRepresentation( AssemblyRepresentation owner , TypeRepresentation pointerType ) : base( owner, BuiltInTypes.BYREF, pointerType ) { } //--// // // Helper Methods // protected override TypeRepresentation AllocateInstantiation( InstantiationContext ic ) { ManagedPointerTypeRepresentation tdRes = new ManagedPointerTypeRepresentation( m_owner, ic.Instantiate( m_pointerType ) ); tdRes.PopulateInstantiation( this, ic ); return tdRes; } //--// // // Access Methods // public override bool CanBeAssignedFrom( TypeRepresentation rvalue , EquivalenceSet set ) { if(rvalue is BoxedValueTypeRepresentation) { // // Going from a boxed valuetype to a byref is OK. // return m_pointerType.EqualsThroughEquivalence( rvalue.UnderlyingType, set ); } return base.CanBeAssignedFrom( rvalue, set ); } //--// // // Debug Methods // public override String ToString() { System.Text.StringBuilder sb = new System.Text.StringBuilder( "ManagedPointerTypeRepresentation(" ); PrettyToString( sb, true, false ); sb.Append( ")" ); return sb.ToString(); } internal override void PrettyToString( System.Text.StringBuilder sb , bool fPrefix , bool fWithAbbreviations ) { base.PrettyToString( sb, fPrefix, fWithAbbreviations ); sb.Append( "&" ); } } } ================================================ FILE: Zelig/Zelig/RunTime/Zelig/TypeSystem/Types/MultiArrayReferenceTypeRepresentation.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // namespace Microsoft.Zelig.Runtime.TypeSystem { using System; using System.Collections.Generic; public sealed class MultiArrayReferenceTypeRepresentation : ArrayReferenceTypeRepresentation { public struct Dimension { // // State // public uint m_lowerBound; public uint m_upperBound; } // // State // private uint m_rank; private Dimension[] m_dimensions; // // Constructor Methods // public MultiArrayReferenceTypeRepresentation( AssemblyRepresentation owner , TypeRepresentation elementType , uint rank , Dimension[] dimensions ) : base( owner, BuiltInTypes.ARRAY, Attributes.None, elementType ) { m_rank = rank; m_dimensions = dimensions; } // // MetaDataEquality Methods // public override bool EqualsThroughEquivalence( object obj , EquivalenceSet set ) { if(obj is MultiArrayReferenceTypeRepresentation) { MultiArrayReferenceTypeRepresentation other = (MultiArrayReferenceTypeRepresentation)obj; if(m_rank == other.m_rank) { if(ArrayUtility.ArrayEquals( m_dimensions, other.m_dimensions )) { return base.EqualsThroughEquivalence( obj, set ); } } } return false; } public override bool Equals( object obj ) { return this.EqualsThroughEquivalence( obj, null ); } public override int GetHashCode() { return base.GetHashCode(); } //--// // // Helper Methods // public override void ApplyTransformation( TransformationContext context ) { context.Push( this ); // // Load before calling the base method, because we might get a call to GetHashCode(). // context.Transform( ref m_rank ); context.Transform( ref m_dimensions ); base.ApplyTransformation( context ); context.Pop(); } //--// protected override void SetShapeCategory( TypeSystem typeSystem ) { m_vTable.ShapeCategory = VTable.Shape.MultiArray; } //--// protected override TypeRepresentation AllocateInstantiation( InstantiationContext ic ) { MultiArrayReferenceTypeRepresentation tdRes = new MultiArrayReferenceTypeRepresentation( m_owner, ic.Instantiate( m_elementType ), m_rank, m_dimensions ); tdRes.PopulateInstantiation( this, ic ); return tdRes; } //--// public override bool SameShape( ArrayReferenceTypeRepresentation other ) { MultiArrayReferenceTypeRepresentation other2 = other as MultiArrayReferenceTypeRepresentation; if(other2 != null) { if(m_rank == other2.m_rank) { if(ArrayUtility.ArrayEquals( m_dimensions, other2.m_dimensions )) { return true; } } } return false; } //--// // // Access Methods // public uint Rank { get { return m_rank; } } public Dimension[] Dimensions { get { return m_dimensions; } } //--// // // Debug Methods // public override String ToString() { System.Text.StringBuilder sb = new System.Text.StringBuilder( "MultiArrayReferenceTypeRepresentation(" ); PrettyToString( sb, true, false ); sb.Append( ")" ); return sb.ToString(); } internal override void PrettyToString( System.Text.StringBuilder sb , bool fPrefix , bool fWithAbbreviations ) { m_elementType.PrettyToString( sb, fPrefix, fWithAbbreviations ); sb.Append( "[" ); for(int i = 0; i < m_rank; i++) { if(i != 0) { sb.Append( "," ); } if(i < m_dimensions.Length) { Dimension dm = m_dimensions[i]; if(dm.m_lowerBound != 0 || dm.m_upperBound != 0) { sb.Append( dm.m_lowerBound ); sb.Append( ".." ); sb.Append( dm.m_upperBound ); } } } sb.Append( "]" ); } } } ================================================ FILE: Zelig/Zelig/RunTime/Zelig/TypeSystem/Types/PinnedPointerTypeRepresentation.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // namespace Microsoft.Zelig.Runtime.TypeSystem { using System; using System.Collections.Generic; public sealed class PinnedPointerTypeRepresentation : PointerTypeRepresentation { // // Constructor Methods // public PinnedPointerTypeRepresentation( AssemblyRepresentation owner , TypeRepresentation pointerType ) : base( owner, BuiltInTypes.PINNED, pointerType ) { } //--// // // Helper Methods // protected override TypeRepresentation AllocateInstantiation( InstantiationContext ic ) { PinnedPointerTypeRepresentation tdRes = new PinnedPointerTypeRepresentation( m_owner, ic.Instantiate( m_pointerType ) ); tdRes.PopulateInstantiation( this, ic ); return tdRes; } //--// // // Debug Methods // public override String ToString() { System.Text.StringBuilder sb = new System.Text.StringBuilder( "PinnedPointerTypeRepresentation(" ); PrettyToString( sb, true, false ); sb.Append( ")" ); return sb.ToString(); } } } ================================================ FILE: Zelig/Zelig/RunTime/Zelig/TypeSystem/Types/PointerTypeRepresentation.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // namespace Microsoft.Zelig.Runtime.TypeSystem { using System; using System.Collections.Generic; public abstract class PointerTypeRepresentation : TypeRepresentation { // // State // protected TypeRepresentation m_pointerType; // // Constructor Methods // protected PointerTypeRepresentation( AssemblyRepresentation owner , BuiltInTypes builtinType , TypeRepresentation pointerType ) : base( owner, builtinType, Attributes.None ) { m_pointerType = pointerType; this.Size = sizeof(uint); } // // MetaDataEquality Methods // public override bool EqualsThroughEquivalence( object obj , EquivalenceSet set ) { if(obj is PointerTypeRepresentation) { PointerTypeRepresentation other = (PointerTypeRepresentation)obj; if(EqualsThroughEquivalence( m_pointerType, other.m_pointerType, set )) { if(this.GetType() == other.GetType()) { return true; } } } return false; } public override bool Equals( object obj ) { return this.EqualsThroughEquivalence( obj, null ); } public override int GetHashCode() { return m_pointerType.GetHashCode(); } //--// // // Helper Methods // protected override void PerformInnerDelayedTypeAnalysis( TypeSystem typeSystem , ref ConversionContext context ) { //m_extends = (ReferenceTypeRepresentation)typeSystem.WellKnownTypes.System_Object; } //--// public override void ApplyTransformation( TransformationContext context ) { context.Push( this ); // // Load before calling the base method, because we might get a call to GetHashCode(). // context.Transform( ref m_pointerType ); base.ApplyTransformation( context ); context.Pop(); } //--// protected override void SetShapeCategory( TypeSystem typeSystem ) { m_vTable.ShapeCategory = VTable.Shape.Invalid; } //--// public override GCInfo.Kind ClassifyAsPointer() { return GCInfo.Kind.Internal; } //--// internal override void InvalidateLayout() { // A pointer has always a valid layout. } //--// // // Access Methods // public override TypeRepresentation ContainedType { get { return m_pointerType; } } public override TypeRepresentation UnderlyingType { get { return m_pointerType; } } public override bool IsOpenType { get { return m_pointerType.IsOpenType; } } public override bool IsDelayedType { get { return m_pointerType.IsDelayedType; } } //--// public override bool CanBeAssignedFrom( TypeRepresentation rvalue , EquivalenceSet set ) { if(this.EqualsThroughEquivalence( rvalue, set )) { return true; } if(rvalue is UnmanagedPointerTypeRepresentation) { // // Always allow an unmanaged pointer to be cast to another pointer. // return true; } StackEquivalentType seRValue = rvalue.StackEquivalentType; if(seRValue == StackEquivalentType.NativeInt) { return true; // Always allow a cast from a native int to a pointer. } return false; } public override StackEquivalentType StackEquivalentType { get { return StackEquivalentType.Pointer; } } public override uint SizeOfHoldingVariable { get { return sizeof(uint); } } public override bool CanPointToMemory { get { return true; } } //--// // // Debug Methods // internal override void PrettyToString( System.Text.StringBuilder sb , bool fPrefix , bool fWithAbbreviations ) { m_pointerType.PrettyToString( sb, fPrefix, fWithAbbreviations ); } } } ================================================ FILE: Zelig/Zelig/RunTime/Zelig/TypeSystem/Types/ReferenceTypeRepresentation.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // namespace Microsoft.Zelig.Runtime.TypeSystem { using System; using System.Collections.Generic; public abstract class ReferenceTypeRepresentation : TypeRepresentation { // // Constructor Methods // protected ReferenceTypeRepresentation( AssemblyRepresentation owner , BuiltInTypes builtinType , Attributes flags ) : base( owner, builtinType, flags ) { } protected ReferenceTypeRepresentation( AssemblyRepresentation owner , BuiltInTypes builtinType , Attributes flags , GenericContext genericContext ) : base( owner, builtinType, flags, genericContext ) { } //--// // // Helper Methods // protected override void PerformInnerDelayedTypeAnalysis( TypeSystem typeSystem , ref ConversionContext context ) { MetaData.Normalized.MetaDataTypeDefinitionBase metadata = (MetaData.Normalized.MetaDataTypeDefinitionBase)typeSystem.GetAssociatedMetaData( this ); ConversionContext localContext = context; localContext.SetContextAsType( this ); m_extends = typeSystem.ConvertToIR( metadata.Extends, localContext ); if(this.IsDelayedType == false) { AnalyzeEntries( typeSystem, ref localContext, metadata.Interfaces, metadata.Fields, metadata.Methods, metadata.MethodImpls ); } } //--// protected override void SetShapeCategory( TypeSystem typeSystem ) { m_vTable.ShapeCategory = (this == typeSystem.WellKnownTypes.System_Array) ? VTable.Shape.ArrayRoot : VTable.Shape.Class; } //--// public override GCInfo.Kind ClassifyAsPointer() { for(TypeRepresentation td = this; td != null; td = td.Extends) { if(td.HasBuildTimeFlag( BuildTimeAttributes.NoVTable )) { return GCInfo.Kind.Internal; } } return GCInfo.Kind.Heap; } //--// // // Access Methods // public override uint SizeOfHoldingVariable { get { return sizeof(uint); } } public override bool CanPointToMemory { get { return true; } } } } ================================================ FILE: Zelig/Zelig/RunTime/Zelig/TypeSystem/Types/ScalarTypeRepresentation.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // namespace Microsoft.Zelig.Runtime.TypeSystem { using System; using System.Collections.Generic; public class ScalarTypeRepresentation : ValueTypeRepresentation { // // Constructor Methods // public ScalarTypeRepresentation( AssemblyRepresentation owner , BuiltInTypes builtinType , Attributes flags , GenericContext genericContext , uint size ) : base( owner, builtinType, flags, genericContext ) { this.Size = size; } //--// // // Helper Methods // public Type ConvertToRuntimeType() { switch(m_builtinType) { case TypeRepresentation.BuiltInTypes.VOID : return typeof(void ); case TypeRepresentation.BuiltInTypes.BOOLEAN: return typeof(System.Boolean); case TypeRepresentation.BuiltInTypes.CHAR : return typeof(System.Char ); case TypeRepresentation.BuiltInTypes.I1 : return typeof(System.SByte ); case TypeRepresentation.BuiltInTypes.U1 : return typeof(System.Byte ); case TypeRepresentation.BuiltInTypes.I2 : return typeof(System.Int16 ); case TypeRepresentation.BuiltInTypes.U2 : return typeof(System.UInt16 ); case TypeRepresentation.BuiltInTypes.I4 : return typeof(System.Int32 ); case TypeRepresentation.BuiltInTypes.U4 : return typeof(System.UInt32 ); case TypeRepresentation.BuiltInTypes.I8 : return typeof(System.Int64 ); case TypeRepresentation.BuiltInTypes.U8 : return typeof(System.UInt64 ); case TypeRepresentation.BuiltInTypes.R4 : return typeof(System.Single ); case TypeRepresentation.BuiltInTypes.R8 : return typeof(System.Double ); case TypeRepresentation.BuiltInTypes.I : return typeof(System.IntPtr ); case TypeRepresentation.BuiltInTypes.U : return typeof(System.UIntPtr); } return null; } //--// public override GCInfo.Kind ClassifyAsPointer() { switch(m_builtinType) { case BuiltInTypes.I: case BuiltInTypes.U: return GCInfo.Kind.Potential; default: return GCInfo.Kind.NotAPointer; } } //--// protected override void SetShapeCategory( TypeSystem typeSystem ) { m_vTable.ShapeCategory = VTable.Shape.Scalar; } //--// protected override TypeRepresentation AllocateInstantiation( InstantiationContext ic ) { return this; } //--// internal override void InvalidateLayout() { // A scalar has always a valid layout. } //--// // // Access Methods // public override uint SizeOfHoldingVariable { get { return this.Size; } } public override bool CanPointToMemory { get { switch(m_builtinType) { case BuiltInTypes.I: case BuiltInTypes.U: return true; } return false; } } public override bool IsNumeric { get { return true; } } public override bool IsSigned { get { switch(m_builtinType) { case BuiltInTypes.I1: case BuiltInTypes.I2: case BuiltInTypes.I4: case BuiltInTypes.I8: case BuiltInTypes.R4: case BuiltInTypes.R8: case BuiltInTypes.I : return true; } return false; } } public override bool IsInteger { get { switch(m_builtinType) { case BuiltInTypes.BOOLEAN: case BuiltInTypes.CHAR : case BuiltInTypes.I1 : case BuiltInTypes.U1 : case BuiltInTypes.I2 : case BuiltInTypes.U2 : case BuiltInTypes.I4 : case BuiltInTypes.U4 : case BuiltInTypes.I8 : case BuiltInTypes.U8 : case BuiltInTypes.I : case BuiltInTypes.U : return true; } return false; } } public override bool IsFloatingPoint { get { switch(m_builtinType) { case BuiltInTypes.R4: case BuiltInTypes.R8: return true; } return false; } } //--// // // Debug Methods // public override String ToString() { System.Text.StringBuilder sb = new System.Text.StringBuilder( "ScalarTypeRepresentation(" ); PrettyToString( sb, true, false ); sb.Append( ")" ); return sb.ToString(); } } } ================================================ FILE: Zelig/Zelig/RunTime/Zelig/TypeSystem/Types/SzArrayReferenceTypeRepresentation.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // namespace Microsoft.Zelig.Runtime.TypeSystem { using System; using System.Collections.Generic; public sealed class SzArrayReferenceTypeRepresentation : ArrayReferenceTypeRepresentation { // // Constructor Methods // public SzArrayReferenceTypeRepresentation( AssemblyRepresentation owner , TypeRepresentation elementType ) : base( owner, BuiltInTypes.SZARRAY, Attributes.None, elementType ) { } //--// // // Helper Methods // protected override void SetShapeCategory( TypeSystem typeSystem ) { m_vTable.ShapeCategory = VTable.Shape.SzArray; } //--// protected override TypeRepresentation AllocateInstantiation( InstantiationContext ic ) { SzArrayReferenceTypeRepresentation tdRes = new SzArrayReferenceTypeRepresentation( m_owner, ic.Instantiate( m_elementType ) ); tdRes.PopulateInstantiation( this, ic ); return tdRes; } //--// public override bool SameShape( ArrayReferenceTypeRepresentation other ) { return other is SzArrayReferenceTypeRepresentation; } //--// // // Access Methods // //--// // // Debug Methods // public override String ToString() { System.Text.StringBuilder sb = new System.Text.StringBuilder( "SzArrayReferenceTypeRepresentation(" ); PrettyToString( sb, true, false ); sb.Append( ")" ); return sb.ToString(); } internal override void PrettyToString( System.Text.StringBuilder sb , bool fPrefix , bool fWithAbbreviations ) { m_elementType.PrettyToString( sb, fPrefix, fWithAbbreviations ); sb.Append( "[]" ); } } } ================================================ FILE: Zelig/Zelig/RunTime/Zelig/TypeSystem/Types/TypeRepresentation.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // namespace Microsoft.Zelig.Runtime.TypeSystem { using System; using System.Collections.Generic; public abstract class TypeRepresentation : BaseRepresentation { // // This is just a copy of Microsoft.Zelig.MetaData.TypeAttributes, needed to break the dependency of TypeSystem from MetaData. // [Flags] public enum Attributes { VisibilityMask = 0x00000007, NotPublic = 0x00000000, // Class is not public scope. Public = 0x00000001, // Class is public scope. NestedPublic = 0x00000002, // Class is nested with public visibility. NestedPrivate = 0x00000003, // Class is nested with private visibility. NestedFamily = 0x00000004, // Class is nested with family visibility. NestedAssembly = 0x00000005, // Class is nested with assembly visibility. NestedFamANDAssem = 0x00000006, // Class is nested with family and assembly visibility. NestedFamORAssem = 0x00000007, // Class is nested with family or assembly visibility. // Use this mask to retrieve class layout information // 0 is AutoLayout, 0x2 is SequentialLayout, 4 is ExplicitLayout LayoutMask = 0x00000018, AutoLayout = 0x00000000, // Class fields are auto-laid out SequentialLayout = 0x00000008, // Class fields are laid out sequentially ExplicitLayout = 0x00000010, // Layout is supplied explicitly // end layout mask // Use this mask to distinguish a type declaration as a Class, ValueType or Interface ClassSemanticsMask = 0x00000020, Class = 0x00000000, // Type is a class. Interface = 0x00000020, // Type is an interface. // Special semantics in addition to class semantics. Abstract = 0x00000080, // Class is abstract Sealed = 0x00000100, // Class is concrete and may not be extended SpecialName = 0x00000400, // Class name is special. Name describes how. // Implementation attributes. Import = 0x00001000, // Class / interface is imported Serializable = 0x00002000, // The class is Serializable. // Use tdStringFormatMask to retrieve string information for native interop StringFormatMask = 0x00030000, AnsiClass = 0x00000000, // LPTSTR is interpreted as ANSI in this class UnicodeClass = 0x00010000, // LPTSTR is interpreted as UNICODE AutoClass = 0x00020000, // LPTSTR is interpreted automatically CustomFormatClass = 0x00030000, // A non-standard encoding specified by CustomFormatMask CustomFormatMask = 0x00C00000, // Use this mask to retrieve non-standard encoding information for native interop. The meaning of the values of these 2 bits is unspecified. // end string format mask BeforeFieldInit = 0x00100000, // Initialize the class any time before first static field access. // Flags reserved for runtime use. ReservedMask = 0x00040800, RTSpecialName = 0x00000800, // Runtime should check name encoding. HasSecurity = 0x00040000, // Class has security associate with it. //--// None = 0x00000000, } // // This is just a copy of Microsoft.Zelig.MetaData.ElementTypes, needed to break the dependency of TypeSystem from MetaData. // public enum BuiltInTypes : byte { END = 0x00, VOID = 0x01, BOOLEAN = 0x02, CHAR = 0x03, I1 = 0x04, U1 = 0x05, I2 = 0x06, U2 = 0x07, I4 = 0x08, U4 = 0x09, I8 = 0x0A, U8 = 0x0B, R4 = 0x0C, R8 = 0x0D, STRING = 0x0E, ///////////////////////// every type above PTR will be simple type PTR = 0x0F, // PTR BYREF = 0x10, // BYREF ///////////////////////// Please use VALUETYPE. VALUECLASS is deprecated. VALUETYPE = 0x11, // VALUETYPE CLASS = 0x12, // CLASS VAR = 0x13, // a class type variable VAR ARRAY = 0x14, // MDARRAY ... ... GENERICINST = 0x15, // instantiated type TYPEDBYREF = 0x16, // This is a simple type. I = 0x18, // native integer size U = 0x19, // native unsigned integer size FNPTR = 0x1B, // FNPTR OBJECT = 0x1C, // Shortcut for System.Object SZARRAY = 0x1D, // Shortcut for single dimension zero lower bound array ///////////////////////// SZARRAY ///////////////////////// This is only for binding MVAR = 0x1E, // a method type variable MVAR CMOD_REQD = 0x1F, // required C modifier : E_T_CMOD_REQD CMOD_OPT = 0x20, // optional C modifier : E_T_CMOD_OPT ///////////////////////// This is for signatures generated internally (which will not be persisted in any way). INTERNAL = 0x21, // INTERNAL ///////////////////////// Note that this is the max of base type excluding modifiers MAX = 0x22, // first invalid element type MODIFIER = 0x40, SENTINEL = 0x01 | MODIFIER, // sentinel for varargs PINNED = 0x05 | MODIFIER } [Flags] public enum BuildTimeAttributes : uint { ForceDevirtualization = 0x00000001, ImplicitInstance = 0x00000002, NoVTable = 0x00000004, // The class does not have a vtable. FlagsAttribute = 0x00000010, } public enum InstantiationFlavor { Delayed , Class , ValueType, } public sealed class GenericContext { // // State // private TypeRepresentation m_template; private TypeRepresentation[] m_parameters; private GenericParameterDefinition[] m_parametersDefinition; // // Constructor Methods // public GenericContext( TypeRepresentation template , TypeRepresentation[] parameters ) { m_template = template; m_parameters = parameters; if(template != null && parameters != null) { CHECKS.ASSERT( template.GenericParametersDefinition.Length <= parameters.Length, "Mismatch" ); if(template.GenericParametersDefinition.Length < parameters.Length) { parameters = ArrayUtility.ExtractSliceFromNotNullArray( parameters, 0, template.GenericParametersDefinition.Length ); } } } //--// // // Helper Methods // public void ApplyTransformation( TransformationContext context ) { context.Push( this ); context.Transform( ref m_template ); context.Transform( ref m_parameters ); context.Transform( ref m_parametersDefinition ); context.Pop(); } //--// // // Helper Methods // internal void CompleteIdentity( TypeSystem typeSystem , MetaData.Normalized.MetaDataGenericTypeParam[] genericParams , ref ConversionContext localContext ) { if(m_template == null) { m_parametersDefinition = new GenericParameterDefinition[genericParams.Length]; for(int i = 0; i < genericParams.Length; i++) { CHECKS.ASSERT( genericParams[i].Number == i, "Found out of sync Generic Type Parameter definition" ); typeSystem.Analyze_GenericParameterDefinition( genericParams[i], ref m_parametersDefinition[i], ref localContext ); } } } //--// // // Access Methods // public TypeRepresentation Template { get { return m_template; } } public TypeRepresentation[] Parameters { get { return m_parameters; } } public GenericParameterDefinition[] ParametersDefinition { get { return m_parametersDefinition; } } public bool IsOpenType { get { if(m_parametersDefinition != null) { if(m_parameters.Length == 0) { return true; } foreach(TypeRepresentation td in m_parameters) { if(td.IsOpenType) { return true; } } } return false; } } public bool IsDelayedType { get { if(m_parameters.Length == 0) { return false; } foreach(TypeRepresentation td in m_parameters) { if(td.IsDelayedType) { return true; } } return false; } } } public struct InterfaceMap { public static readonly InterfaceMap[] SharedEmptyArray = new InterfaceMap[0]; // // State // public InterfaceTypeRepresentation Interface; public MethodRepresentation[] Methods; } public static readonly TypeRepresentation[] SharedEmptyArray = new TypeRepresentation[0]; // // State // protected AssemblyRepresentation m_owner; protected BuiltInTypes m_builtinType; protected Attributes m_flags; protected BuildTimeAttributes m_buildFlags; protected string m_name; protected string m_namespace; protected TypeRepresentation m_enclosingClass; protected GenericContext m_genericContext; protected TypeRepresentation m_extends; protected InterfaceTypeRepresentation[] m_interfaces; protected FieldRepresentation[] m_fields; protected MethodRepresentation[] m_methods; protected MethodImplRepresentation[] m_methodImpls; // // These fields are synthesized from the analysis of the type hierarchy and the type characteristics. // [WellKnownField( "TypeRepresentation_InterfaceMethodTables" )] protected InterfaceMap[] m_interfaceMethodTables; [WellKnownField( "TypeRepresentation_MethodTable" )] protected MethodRepresentation[] m_methodTable; [WellKnownField( "TypeRepresentation_VTable" )] protected VTable m_vTable; // // Constructor Methods // protected TypeRepresentation( AssemblyRepresentation owner , BuiltInTypes builtinType , Attributes flags ) : this( owner, builtinType, flags, null ) { } protected TypeRepresentation( AssemblyRepresentation owner , BuiltInTypes builtinType , Attributes flags , GenericContext genericContext ) { m_owner = owner; m_builtinType = builtinType; m_flags = flags; m_genericContext = genericContext; m_interfaces = InterfaceTypeRepresentation.SharedEmptyArray; m_fields = FieldRepresentation .SharedEmptyArray; m_methods = MethodRepresentation .SharedEmptyArray; m_methodImpls = MethodImplRepresentation .SharedEmptyArray; m_interfaceMethodTables = null; m_methodTable = null; m_vTable = new VTable( this ); m_vTable.BaseSize = uint.MaxValue; } // // MetaDataEquality Methods // public override bool EqualsThroughEquivalence( object obj , EquivalenceSet set ) { if(obj is TypeRepresentation) { TypeRepresentation other = (TypeRepresentation)obj; if( m_builtinType == other.m_builtinType && m_flags == other.m_flags && m_buildFlags == other.m_buildFlags && m_name == other.m_name && m_namespace == other.m_namespace && EqualsThroughEquivalence( m_enclosingClass , other.m_enclosingClass , set ) && ArrayEqualsThroughEquivalence( this.GenericParameters , other.GenericParameters, set ) ) { CHECKS.ASSERT( this.GetType() == other.GetType(), "Found two inconsistent TypeRepresentations" ); return true; } } return false; } public override bool Equals( object obj ) { return this.EqualsThroughEquivalence( obj, null ); } public override int GetHashCode() { return (int)m_builtinType ^ m_name.GetHashCode(); } [Inline] public static bool operator ==( TypeRepresentation left , TypeRepresentation right ) { return Object.Equals( left, right ); } [Inline] public static bool operator !=( TypeRepresentation left , TypeRepresentation right ) { return !(left == right); } //--// // // Helper Methods // protected void Done( TypeSystem typeSystem ) { typeSystem.NotifyNewTypeComplete( this ); } protected abstract void SetShapeCategory( TypeSystem typeSystem ); internal void CompleteIdentity( TypeSystem typeSystem , ref ConversionContext context , MetaData.Normalized.MetaDataTypeDefinitionAbstract td ) { SetShapeCategory( typeSystem ); //--// if(td is MetaData.Normalized.MetaDataTypeDefinitionBase) { MetaData.Normalized.MetaDataTypeDefinitionBase td2 = (MetaData.Normalized.MetaDataTypeDefinitionBase)td; m_name = td2.Name; m_namespace = td2.Namespace; m_enclosingClass = typeSystem.ConvertToIR( td2.EnclosingClass, context, true ); if(td is MetaData.Normalized.MetaDataTypeDefinitionGeneric) { MetaData.Normalized.MetaDataTypeDefinitionGeneric td3 = (MetaData.Normalized.MetaDataTypeDefinitionGeneric)td; ConversionContext localContext = context; localContext.SetContextAsType( this ); MetaData.Normalized.MetaDataGenericTypeParam[] genericParams = td3.GenericParams; if(genericParams != null) { CHECKS.ASSERT(m_genericContext != null, "Defining a generic type, but {0} doesn't have a generic context", this ); m_genericContext.CompleteIdentity( typeSystem, genericParams, ref localContext ); } } } } //--// internal void PerformTypeAnalysis( TypeSystem typeSystem , ref ConversionContext context ) { #if GENERICS typeSystem.QueueDelayedTypeAnalysis( this, ref context ); #else if(this.IsDelayedType == false) { typeSystem.QueueDelayedTypeAnalysis( this, ref context ); } else { Done( typeSystem ); } #endif } internal void PerformDelayedTypeAnalysis( TypeSystem typeSystem , ref ConversionContext context ) { PerformInnerDelayedTypeAnalysis( typeSystem, ref context ); Done( typeSystem ); } protected abstract void PerformInnerDelayedTypeAnalysis( TypeSystem typeSystem , ref ConversionContext context ); internal void PerformDelayedCustomAttributeAnalysis( TypeSystem typeSystem , ref ConversionContext context ) { MetaData.Normalized.MetaDataTypeDefinitionAbstract metadata = typeSystem.GetAssociatedMetaData( this ); typeSystem.ConvertToIR( metadata.CustomAttributes, context, this, -1 ); foreach(FieldRepresentation fd in m_fields) { fd.ProcessCustomAttributes( typeSystem, ref context ); } } //--// protected void AnalyzeEntries( TypeSystem typeSystem , ref ConversionContext context , MetaData.Normalized.MetaDataTypeDefinitionAbstract[] interfaces , MetaData.Normalized.MetaDataField[] fields , MetaData.Normalized.MetaDataMethodBase[] methods , MetaData.Normalized.MetaDataMethodImpl[] methodImpls ) { if(interfaces != null) { AnalyzeInterfaces( typeSystem, ref context, interfaces ); } if(fields != null) { AnalyzeFields( typeSystem, ref context, fields ); } if(methods != null) { AnalyzeMethods( typeSystem, ref context, methods ); } if(methodImpls != null) { AnalyzeMethodImpls( typeSystem, ref context, methodImpls ); } //--// if(this is InterfaceTypeRepresentation) { ; // Interfaces cannot have an interface map. } else if(this.IsOpenType) { ; // There's no point in building an interface map for a type that cannot be instantiated. } else { ; } typeSystem.QueueDelayedCustomAttributeAnalysis( this, ref context ); } private void AnalyzeInterfaces( TypeSystem typeSystem , ref ConversionContext context , MetaData.Normalized.MetaDataTypeDefinitionAbstract[] interfaces ) { foreach(MetaData.Normalized.MetaDataTypeDefinitionAbstract itf in interfaces) { TypeRepresentation itfRes = typeSystem.ConvertToIR( itf, context ); if(itfRes is InterfaceTypeRepresentation) { InterfaceTypeRepresentation itfNew = (InterfaceTypeRepresentation)itfRes; this.AddInterface( itfNew ); } else { throw TypeConsistencyErrorException.Create( "'{0}' is not an interface", itf ); } } } private void AnalyzeFields( TypeSystem typeSystem , ref ConversionContext context , MetaData.Normalized.MetaDataField[] fields ) { foreach(MetaData.Normalized.MetaDataField fd in fields) { if((fd.Flags & MetaData.FieldAttributes.Literal) == 0) { typeSystem.ConvertToIR( this, fd, context ); } else { var enu = this as EnumerationTypeRepresentation; if(enu != null) { var val = fd.DefaultValue; if(val != null) { enu.AddLiteral( fd.Name, val ); } } } } } private void AnalyzeMethods( TypeSystem typeSystem , ref ConversionContext context , MetaData.Normalized.MetaDataMethodBase[] methods ) { foreach(MetaData.Normalized.MetaDataMethodBase md in methods) { typeSystem.ConvertToIR( md, context ); } } private void AnalyzeMethodImpls( TypeSystem typeSystem , ref ConversionContext context , MetaData.Normalized.MetaDataMethodImpl[] methodImpls ) { foreach(MetaData.Normalized.MetaDataMethodImpl mi in methodImpls) { MethodRepresentation body = typeSystem.ConvertToIR( mi.Body , context ); MethodRepresentation declaration = typeSystem.ConvertToIR( mi.Declaration, context ); MethodImplRepresentation miRes = new MethodImplRepresentation( body, declaration ); this.AddMethodImpl( miRes ); } } //--// public override void ApplyTransformation( TransformationContext context ) { context.Push( this ); base.ApplyTransformation( context ); context.Transform( ref m_owner ); context.Transform( ref m_builtinType ); context.Transform( ref m_flags ); context.Transform( ref m_buildFlags ); context.Transform( ref m_name ); context.Transform( ref m_namespace ); context.Transform( ref m_enclosingClass ); context.Transform( ref m_genericContext ); context.Transform( ref m_extends ); context.Transform( ref m_interfaces ); context.Transform( ref m_fields ); context.Transform( ref m_methods ); context.Transform( ref m_methodImpls ); context.Transform( ref m_vTable ); context.Pop(); } //--// internal override void ProhibitUse( TypeSystem.Reachability reachability , bool fApply ) { base.ProhibitUse( reachability, fApply ); reachability.ExpandProhibition( m_vTable ); foreach(FieldRepresentation fd in m_fields) { fd.ProhibitUse( reachability, fApply ); } foreach(MethodRepresentation md in m_methods) { md.ProhibitUse( reachability, fApply ); } } internal override void Reduce( TypeSystem.Reachability reachability , bool fApply ) { base.Reduce( reachability, fApply ); for(int i = m_interfaces.Length; --i >= 0; ) { InterfaceTypeRepresentation itf = m_interfaces[i]; if(reachability.Contains( itf ) == false) { if(fApply) { RemoveInterface( itf ); } } } for(int i = m_fields.Length; --i >= 0; ) { FieldRepresentation fd = m_fields[i]; if(reachability.Contains( fd ) == false) { CHECKS.ASSERT( (fd is InstanceFieldRepresentation) == false || this.ValidLayout == false, "Cannot remove a field after the type has been laid out" ); fd.ProhibitUse( reachability, fApply ); if(fApply) { RemoveField( fd ); } } else { fd.Reduce( reachability, fApply ); } } for(int i = m_methods.Length; --i >= 0; ) { MethodRepresentation md = m_methods[i]; if(reachability.Contains( md ) == false) { md.ProhibitUse( reachability, fApply ); if(fApply) { RemoveMethod( md ); } } else { md.Reduce( reachability, fApply ); } } for(int i = m_methodImpls.Length; --i >= 0; ) { MethodImplRepresentation mid = m_methodImpls[i]; if(reachability.Contains( mid.Declaration ) == false || reachability.Contains( mid.Body ) == false ) { mid.ProhibitUse( reachability, fApply ); if(fApply) { RemoveMethodImpl( mid ); } } } } //--// public void ClearMethodTableAndInterfaceMaps( TypeSystem typeSystem ) { m_methodTable = null; m_interfaceMethodTables = null; m_vTable.MethodPointers = null; m_vTable.InterfaceMethodPointers = null; } public void BuildMethodTableAndInterfaceMaps( TypeSystem typeSystem ) { BuildMethodTable ( typeSystem ); BuildInterfaceMap( typeSystem ); } internal void BuildGcInfo( TypeSystem typeSystem ) { if(this.IsOpenType == false) { var lst = new List< GCInfo.Pointer >(); CollectPointerInfo( typeSystem, lst, this, 0 ); int num = lst.Count; if(num > 0) { var array = new GCInfo.Pointer[num]; m_vTable.GCInfo.Pointers = array; for(int i = 0; i < num; i++) { array[num - 1 - i] = lst[i]; } } else { m_vTable.GCInfo.Pointers = null; } } } private static void CollectPointerInfo( TypeSystem typeSystem , List< GCInfo.Pointer > lst , TypeRepresentation td , int offset ) { while(td != null) { FieldRepresentation[] fds = td.Fields; for(int i = fds.Length; --i >= 0; ) { var fd = fds[i] as InstanceFieldRepresentation; if(fd != null && typeSystem.IncludeInGCInfo( fd )) { TypeRepresentation fdType = fd.FieldType; int fdOffset = offset + fd.Offset; GCInfo.Kind fdKind = fdType.ClassifyAsPointer(); switch(fdKind) { case GCInfo.Kind.AggregateType: CollectPointerInfo( typeSystem, lst, fdType, fdOffset ); break; case GCInfo.Kind.Heap : case GCInfo.Kind.Internal : case GCInfo.Kind.Potential: { GCInfo.Pointer ptr = new GCInfo.Pointer(); ptr.Kind = fdKind; ptr.OffsetInWords = (short)(fdOffset / sizeof(uint)); lst.Add( ptr ); } break; } } } td = td.Extends; } } //--// private void BuildMethodTable( TypeSystem typeSystem ) { if(m_methodTable == null) { if(this.IsDelayedType) { m_methodTable = MethodRepresentation.SharedEmptyArray; } else { TypeRepresentation parent = this.Extends; if(parent != null) { parent.BuildMethodTable( typeSystem ); m_methodTable = ArrayUtility.CopyNotNullArray( parent.m_methodTable ); CHECKS.ASSERT( m_methodTable != null, "Parent class {0} for {1} has not been initialized properly", parent, this ); } else { m_methodTable = MethodRepresentation.SharedEmptyArray; } int methodTableLength = m_methodTable.Length; foreach(MethodRepresentation md in m_methods) { md.CreateCodePointer( typeSystem ); if(GetDeclarationOfMethodImpl( md ) != null) { continue; // Skip any method with an explicit MethodImpl. } if(md.IsOpenMethod == false && md is VirtualMethodRepresentation) { if(md.VTableLayoutFlags == MethodRepresentation.Attributes.ReuseSlot) { string name = md.Name; int i; // // Search from the bottom, to take care of "new" virtual methods. // for(i = methodTableLength - 1; i >= 0; i--) { MethodRepresentation md2 = m_methodTable[i]; if(md2.MatchNameAndSignature( name, md, null )) { if(md2 is FinalMethodRepresentation) { throw TypeConsistencyErrorException.Create( "{0} cannot override final method {1}", md, md2 ); } break; } } if(i >= 0) { m_methodTable[i] = md; continue; } } m_methodTable = ArrayUtility.AppendToNotNullArray( m_methodTable, md ); methodTableLength++; } } if((this is AbstractReferenceTypeRepresentation) == false) { for(int i = 0; i < methodTableLength; i++) { MethodRepresentation md = m_methodTable[i]; if((md.Flags & MethodRepresentation.Attributes.Abstract) != 0) { throw TypeConsistencyErrorException.Create( "Type {0} is missing a definition for abstract method {1}", this, md ); } } } } m_vTable.MethodPointers = ConvertToMethodPointers( m_methodTable ); } } //--// private void BuildInterfaceMap( TypeSystem typeSystem ) { if(m_interfaceMethodTables == null) { m_interfaceMethodTables = InterfaceMap.SharedEmptyArray; m_vTable.InterfaceMethodPointers = VTable.InterfaceMap.SharedEmptyArray; if(this is InterfaceTypeRepresentation) { // // The interface method table for an interface is its method table. // InterfaceMap im; im.Interface = (InterfaceTypeRepresentation)this; im.Methods = m_methodTable; m_interfaceMethodTables = ArrayUtility.AppendToNotNullArray( m_interfaceMethodTables, im ); //--// VTable.InterfaceMap im2; im2.Interface = this.VirtualTable; im2.MethodPointers = ConvertToMethodPointers( m_methodTable ); m_vTable.InterfaceMethodPointers = ArrayUtility.AppendToNotNullArray( m_vTable.InterfaceMethodPointers, im2 ); } else { TypeRepresentation td = this; while(td != null) { foreach(InterfaceTypeRepresentation itf in td.m_interfaces) { AddInterfaceImplementation( typeSystem, itf ); } td = td.Extends; } } } } private void AddInterfaceImplementation( TypeSystem typeSystem , InterfaceTypeRepresentation itf ) { foreach(InterfaceTypeRepresentation itfSub in itf.m_interfaces) { AddInterfaceImplementation( typeSystem, itfSub ); } int count = m_interfaceMethodTables.Length; for(int i = 0; i < count; i++) { if(m_interfaceMethodTables[i].Interface == itf) { return; } } InterfaceMap im; int len = itf.m_methods.Length; im.Interface = itf; if(len > 0) { im.Methods = new MethodRepresentation[len]; // // Section 12.2 of ECMA spec, Partition II // for(int i = 0; i < len; i++) { MethodRepresentation mdItf = itf.m_methods[i]; string mdItfName = mdItf.Name; for(TypeRepresentation td = this; ; td = td.Extends) { MethodRepresentation mdTarget; if(td == null) { //throw TypeConsistencyErrorException.Create( "Type {0} does not implement method {1} for interface {2}", this, mdItf, itf ); // // [ZachL] - Provide stub implemenation for interface methods that are never called. ComputeCallsClosure was changed so that // interface methods were not automatically included just because the interface and a type implementing that interface // were used. If the method was not called on a particular type then we don't need to drag its implementation and // everything it references in. // mdTarget = typeSystem.WellKnownMethods.ThreadImpl_ThrowNullException; } else { // // We have to do two passes: // // - The first one looks for explicit method implementation. // - The second one looks only for a simple name+signature match. // mdTarget = td.GetMethodImpl( mdItf ); if(mdTarget == null) { mdTarget = td.FindMatch( mdItfName, mdItf, null ); } } if(mdTarget != null) { im.Methods[i] = mdTarget; break; } } } } else { im.Methods = MethodRepresentation.SharedEmptyArray; } m_interfaceMethodTables = ArrayUtility.AppendToNotNullArray( m_interfaceMethodTables, im ); //--// VTable.InterfaceMap im2; im2.Interface = itf.VirtualTable; im2.MethodPointers = ConvertToMethodPointers( im.Methods ); m_vTable.InterfaceMethodPointers = ArrayUtility.AppendToNotNullArray( m_vTable.InterfaceMethodPointers, im2 ); } private static CodePointer[] ConvertToMethodPointers( MethodRepresentation[] mdArray ) { int len = mdArray.Length; CodePointer[] res = new CodePointer[len]; for(int i = 0; i < len; i++) { res[i] = mdArray[i].CodePointer; } return res; } //--// public TypeRepresentation Instantiate( InstantiationContext ic ) { TypeRepresentation instantiatedTd = AllocateInstantiation( ic ); TypeRepresentation instantiatedTdRes = ic.Lookup( instantiatedTd, true ); if(instantiatedTdRes != null) { return instantiatedTdRes; } else { //m_typeSystem.Types.Add( instantiatedTd ); return instantiatedTd; } } protected abstract TypeRepresentation AllocateInstantiation( InstantiationContext ic ); protected virtual void PopulateInstantiation( TypeRepresentation tdTemplate , InstantiationContext ic ) { m_builtinType = tdTemplate.m_builtinType; m_flags = tdTemplate.m_flags; m_buildFlags = tdTemplate.m_buildFlags; m_name = tdTemplate.m_name; m_namespace = tdTemplate.m_namespace; m_enclosingClass = ic.Instantiate( tdTemplate.m_enclosingClass ); m_extends = ic.Instantiate( tdTemplate.m_extends ); //// protected InterfaceTypeRepresentation[] m_interfaces; //// protected FieldRepresentation[] m_fields; //// protected MethodRepresentation[] m_methods; //// protected MethodImplRepresentation[] m_methodImpls; } //--// public void AddInterface( InterfaceTypeRepresentation itf ) { m_interfaces = ArrayUtility.AppendToNotNullArray( m_interfaces, itf ); } public void AddField( FieldRepresentation fd ) { m_fields = ArrayUtility.AppendToNotNullArray( m_fields, fd ); } public void AddMethod( MethodRepresentation md ) { m_methods = ArrayUtility.AppendToNotNullArray( m_methods, md ); } public void AddMethodImpl( MethodImplRepresentation mi ) { for(int i = 0; i < m_methodImpls.Length; i++) { MethodImplRepresentation miOld = m_methodImpls[i]; if(miOld.Declaration == mi.Declaration) { throw TypeConsistencyErrorException.Create( "Multiple methods are used to implement '{0}' on '{1}'", mi.Declaration, this ); } } m_methodImpls = ArrayUtility.AppendToNotNullArray( m_methodImpls, mi ); } //--// public void RemoveInterface( InterfaceTypeRepresentation itf ) { m_interfaces = ArrayUtility.RemoveUniqueFromNotNullArray( m_interfaces, itf ); } public void RemoveField( FieldRepresentation fd ) { m_fields = ArrayUtility.RemoveUniqueFromNotNullArray( m_fields, fd ); } public void RemoveMethod( MethodRepresentation md ) { m_methods = ArrayUtility.RemoveUniqueFromNotNullArray( m_methods, md ); for(int i = m_methodImpls.Length; --i >= 0; ) { if(m_methodImpls[i].Body == md) { m_methodImpls = ArrayUtility.RemoveAtPositionFromNotNullArray( m_methodImpls, i ); } } } public void RemoveMethodImpl( MethodImplRepresentation mid ) { for(int i = m_methodImpls.Length; --i >= 0; ) { if(m_methodImpls[i] == mid) { m_methodImpls = ArrayUtility.RemoveAtPositionFromNotNullArray( m_methodImpls, i ); } } } //--// public static TypeRepresentation FindCommonType( TypeRepresentation tdLeft , TypeRepresentation tdRight ) { while(tdLeft != null && tdRight != null) { if(tdLeft.CanBeAssignedFrom( tdRight, null )) { return tdLeft; } if(tdRight.CanBeAssignedFrom( tdLeft, null )) { return tdRight; } tdLeft = tdLeft .Extends; tdRight = tdRight.Extends; } return null; } //--// public FieldRepresentation FindField( string name ) { TypeRepresentation td = this; while(td != null) { foreach(FieldRepresentation fd in td.Fields) { if(fd.Name == name) { return fd; } } td = td.Extends; } return null; } public InstanceFieldRepresentation FindFieldAtOffset( int offset ) { TypeRepresentation td = this; while(td != null) { foreach(FieldRepresentation fd in td.Fields) { InstanceFieldRepresentation fdI = fd as InstanceFieldRepresentation; if(fdI != null && fdI.Offset == offset) { return fdI; } } td = td.Extends; } return null; } public MethodRepresentation FindMatch( string searchName ) { foreach(MethodRepresentation md in m_methods) { if(md.Name == searchName) { return md; } } return null; } public MethodRepresentation FindMatch( MethodRepresentation search , EquivalenceSet set ) { return FindMatch( search.Name, search, set ); } public MethodRepresentation FindMatch( string searchName , MethodRepresentation searchSignature , EquivalenceSet set ) { foreach(MethodRepresentation md in m_methods) { if(md.MatchNameAndSignature( searchName, searchSignature, set )) { return md; } } return null; } public FinalizerMethodRepresentation FindDestructor() { for(var td = this; td != null; td = td.Extends) { foreach(MethodRepresentation md in m_methods) { var res = md as FinalizerMethodRepresentation; if(res != null) { return res; } } } return null; } public ConstructorMethodRepresentation FindDefaultConstructor() { foreach(MethodRepresentation md in m_methods) { if(md is ConstructorMethodRepresentation && md.ThisPlusArguments.Length == 1) { return (ConstructorMethodRepresentation)md; } } return null; } public StaticConstructorMethodRepresentation FindDefaultStaticConstructor() { foreach(MethodRepresentation md in m_methods) { if(md is StaticConstructorMethodRepresentation) { return (StaticConstructorMethodRepresentation)md; } } return null; } public MethodRepresentation[] FindInterfaceTable( InterfaceTypeRepresentation itf ) { for(int i = 0; i < m_interfaceMethodTables.Length; i++) { if(m_interfaceMethodTables[i].Interface == itf) { return m_interfaceMethodTables[i].Methods; } } return null; } public InterfaceTypeRepresentation FindInstantiationOfGenericInterface( InterfaceTypeRepresentation itf , params TypeRepresentation[] parameters ) { var td = this; while(td != null) { foreach(var itf2 in td.m_interfaces) { if(itf2.GenericTemplate == itf && itf2.IsGenericInstantiation) { if(ArrayUtility.ArrayEqualsNotNull( itf2.GenericParameters, parameters, 0 )) { return itf2; } } } td = td.Extends; } return null; } //--// public void Substituite( FieldRepresentation oldFD , FieldRepresentation newFD ) { int pos = ArrayUtility.FindInNotNullArray( m_fields, oldFD ); m_fields = ArrayUtility.ReplaceAtPositionOfNotNullArray( m_fields, pos, newFD ); } public void Substituite( MethodRepresentation oldMD , MethodRepresentation newMD ) { newMD.PrepareToSubstitute( oldMD ); int pos = ArrayUtility.FindInNotNullArray( m_methods, oldMD ); m_methods = ArrayUtility.ReplaceAtPositionOfNotNullArray( m_methods, pos, newMD ); //--// // // Update the MethodImpl array, to point to the new method. // for(int i = 0; i < m_methodImpls.Length; i++) { MethodImplRepresentation mi = m_methodImpls[i]; if(mi.Body == oldMD) { mi = new MethodImplRepresentation( newMD, mi.Declaration ); m_methodImpls[i] = mi; } } } public VirtualMethodRepresentation CreateOverride( TypeSystem typeSystem , VirtualMethodRepresentation mdSource ) { if(mdSource.Generic != null) { throw TypeConsistencyErrorException.Create( "Overriding of generic method '{0}' is not supported", mdSource ); } else { VirtualMethodRepresentation md; if(this is ValueTypeRepresentation) { md = new FinalMethodRepresentation( this, null ); } else { md = new VirtualMethodRepresentation( this, null ); } AddMethod( md ); md.Override( typeSystem, mdSource ); return md; } } internal ConstructorMethodRepresentation CreateMatchingConstructor( TypeSystem typeSystem , ConstructorMethodRepresentation mdSource ) { if(mdSource.Generic != null) { throw TypeConsistencyErrorException.Create( "Overriding of generic method '{0}' is not supported", mdSource ); } else { ConstructorMethodRepresentation md = new ConstructorMethodRepresentation( this, null ); AddMethod( md ); md.Override( typeSystem, mdSource ); return md; } } //--// internal virtual void InvalidateLayout() { m_vTable.BaseSize = uint.MaxValue; } //--// public abstract GCInfo.Kind ClassifyAsPointer(); //--// public override void EnumerateCustomAttributes( CustomAttributeAssociationEnumerationCallback callback ) { base.EnumerateCustomAttributes( callback ); foreach(FieldRepresentation fd in m_fields) { fd.EnumerateCustomAttributes( callback ); } foreach(MethodRepresentation md in m_methods) { md.EnumerateCustomAttributes( callback ); } } public bool IsSubClassOf( TypeRepresentation rvalue , EquivalenceSet set ) { if(rvalue != null) { return rvalue.IsSuperClassOf( this, set ); } return false; } public bool IsSuperClassOf( TypeRepresentation rvalue , EquivalenceSet set ) { if(rvalue != null) { while(true) { rvalue = rvalue.Extends; if(rvalue == null) { break; } if(this.EqualsThroughEquivalence( rvalue, set )) { return true; } } } return false; } public virtual bool CanBeAssignedFrom( TypeRepresentation rvalue , EquivalenceSet set ) { if(this.EqualsThroughEquivalence( rvalue, set )) { return true; } // // Interfaces can always be cast to Object, but they don't actually inherit from Object, // so the loop below would fail. // if(rvalue is InterfaceTypeRepresentation && this.IsObject ) { return true; } if(rvalue is EnumerationTypeRepresentation) { EnumerationTypeRepresentation rvalue2 = (EnumerationTypeRepresentation)rvalue; return CanBeAssignedFrom( rvalue2.UnderlyingType, set ); } if(this.StackEquivalentType == StackEquivalentType.NativeInt && rvalue is PointerTypeRepresentation ) { return true; // Always allow a cast from a pointer to a native int. } if(rvalue is ArrayReferenceTypeRepresentation) { if(rvalue.Extends == this) { // // Any array can be cast to its base class, System.Array. // return true; } } return IsSuperClassOf( rvalue, set ); } //--// public MethodRepresentation GetDeclarationOfMethodImpl( MethodRepresentation body ) { foreach(MethodImplRepresentation mi in m_methodImpls) { if(mi.Body == body) { return mi.Declaration; } } return null; } public MethodRepresentation GetMethodImpl( MethodRepresentation declaration ) { foreach(MethodImplRepresentation mi in m_methodImpls) { if(mi.Declaration == declaration) { return mi.Body; } } return null; } public virtual InstantiationFlavor GetInstantiationFlavor( TypeSystem typeSystem ) { return InstantiationFlavor.Class; } //--// // // Access Methods // public AssemblyRepresentation Owner { get { return m_owner; } } public BuiltInTypes BuiltInType { get { return m_builtinType; } } public Attributes Flags { get { return m_flags; } } public BuildTimeAttributes BuildTimeFlags { get { return m_buildFlags; } set { m_buildFlags = value; } } public BuildTimeAttributes ExpandedBuildTimeFlags { get { var res = m_buildFlags; var tdTemplate = this.GenericTemplate; if(tdTemplate != null) { res |= tdTemplate.ExpandedBuildTimeFlags; } return res; } } public bool HasBuildTimeFlag( BuildTimeAttributes bta ) { return (this.ExpandedBuildTimeFlags & bta) != 0; } public string Name { get { return m_name; } } public string Namespace { get { return m_namespace; } } public TypeRepresentation EnclosingClass { get { return m_enclosingClass; } } public bool IsGenericInstantiation { get { return this.IsOpenType == false && this.GenericParameters.Length > 0; } } public GenericContext Generic { get { return m_genericContext; } } public TypeRepresentation GenericTemplate { get { if(m_genericContext != null) { return m_genericContext.Template; } return null; } } public TypeRepresentation[] GenericParameters { get { if(m_genericContext != null) { return m_genericContext.Parameters; } return TypeRepresentation.SharedEmptyArray; } } public GenericParameterDefinition[] GenericParametersDefinition { get { if(m_genericContext != null) { return m_genericContext.ParametersDefinition; } return null; } } public TypeRepresentation Extends { get { return m_extends; } } public InterfaceTypeRepresentation[] Interfaces { get { return m_interfaces; } } public FieldRepresentation[] Fields { get { return m_fields; } } public MethodRepresentation[] Methods { get { return m_methods; } } public MethodImplRepresentation[] MethodImpls { get { return m_methodImpls; } } public InterfaceMap[] InterfaceMaps { get { return m_interfaceMethodTables; } } public MethodRepresentation[] MethodTable { get { return m_methodTable; } } public VTable VirtualTable { get { return m_vTable; } } //--// public string FullName { get { System.Text.StringBuilder sb = new System.Text.StringBuilder(); PrettyToString( sb, false, false ); return sb.ToString(); } } public string FullNameWithAbbreviation { get { System.Text.StringBuilder sb = new System.Text.StringBuilder(); PrettyToString( sb, false, true ); return sb.ToString(); } } public virtual TypeRepresentation ContainedType { get { return null; } } public virtual TypeRepresentation UnderlyingType { get { return this; } } public bool IsObject { get { return (this is ConcreteReferenceTypeRepresentation && m_extends == null); } } public virtual bool IsOpenType { get { if(m_genericContext != null) { return m_genericContext.IsOpenType; } return false; } } public virtual bool IsDelayedType { get { if(m_genericContext != null) { return m_genericContext.IsDelayedType; } return false; } } public bool IsNestedType { get { return m_enclosingClass != null; } } public bool IsAbstract { get { return (m_flags & TypeRepresentation.Attributes.Abstract) != 0; } } //--// public virtual bool IsNumeric { get { return false; } } public virtual bool IsSigned { get { return false; } } public virtual bool IsInteger { get { return false; } } public virtual bool IsFloatingPoint { get { return false; } } public abstract bool CanPointToMemory { get; } //--// public virtual StackEquivalentType StackEquivalentType { get { switch(this.BuiltInType) { case BuiltInTypes.VOID : return StackEquivalentType.Void; case BuiltInTypes.BOOLEAN: return StackEquivalentType.Int32; case BuiltInTypes.CHAR : return StackEquivalentType.Int32; case BuiltInTypes.I1 : return StackEquivalentType.Int32; case BuiltInTypes.U1 : return StackEquivalentType.Int32; case BuiltInTypes.I2 : return StackEquivalentType.Int32; case BuiltInTypes.U2 : return StackEquivalentType.Int32; case BuiltInTypes.I4 : return StackEquivalentType.Int32; case BuiltInTypes.U4 : return StackEquivalentType.Int32; case BuiltInTypes.I8 : return StackEquivalentType.Int64; case BuiltInTypes.U8 : return StackEquivalentType.Int64; case BuiltInTypes.R4 : return StackEquivalentType.Float; case BuiltInTypes.R8 : return StackEquivalentType.Float; case BuiltInTypes.I : return StackEquivalentType.NativeInt; case BuiltInTypes.U : return StackEquivalentType.NativeInt; default : return StackEquivalentType.Object; } } } public bool ValidLayout { get { return m_vTable.BaseSize != uint.MaxValue; } } public uint Size { get { CHECKS.ASSERT( this.ValidLayout, "Cannot access the 'Size' property on type '{0}' before the type has been laid out", this ); return m_vTable.BaseSize; } set { m_vTable.BaseSize = value; } } public abstract uint SizeOfHoldingVariable { get; } public uint SizeOfHoldingVariableInWords { get { uint size = this.SizeOfHoldingVariable; // // Round to word size. // size = (size + (sizeof(uint)-1)) / sizeof(uint); return size; } } //--// // // Debug Methods // private string GetAbbreviation() { switch(m_builtinType) { case BuiltInTypes.VOID : return "void" ; case BuiltInTypes.BOOLEAN: return "bool" ; case BuiltInTypes.CHAR : return "char" ; case BuiltInTypes.I1 : return "sbyte" ; case BuiltInTypes.U1 : return "byte" ; case BuiltInTypes.I2 : return "short" ; case BuiltInTypes.U2 : return "ushort" ; case BuiltInTypes.I4 : return "int" ; case BuiltInTypes.U4 : return "uint" ; case BuiltInTypes.I8 : return "long" ; case BuiltInTypes.U8 : return "ulong" ; case BuiltInTypes.R4 : return "float" ; case BuiltInTypes.R8 : return "double" ; case BuiltInTypes.STRING : return "string" ; case BuiltInTypes.OBJECT : return "object" ; default : return null; } } internal virtual void PrettyToString( System.Text.StringBuilder sb , bool fPrefix , bool fWithAbbreviations ) { if(fPrefix) { if(this.IsDelayedType) { sb.Append( "delayed " ); } else if(this.IsOpenType) { sb.Append( "generic " ); } } string name = null; if(fWithAbbreviations) { name = GetAbbreviation(); } if(name != null) { sb.Append( name ); } else { if(this.IsNestedType) { this.EnclosingClass.PrettyToString( sb, false, fWithAbbreviations ); sb.Append( "." ); } if(this.Namespace != null && this.Namespace.Length != 0) { sb.Append( this.Namespace ); sb.Append( "." ); } sb.Append( this.Name ); } if(m_genericContext != null) { sb.Append( "<" ); TypeRepresentation[] parameters = m_genericContext.Parameters; if(parameters.Length > 0) { for(int i = 0; i < parameters.Length; i++) { if(i != 0) sb.Append( "," ); parameters[i].PrettyToString( sb, fPrefix, fWithAbbreviations ); } } else { GenericParameterDefinition[] defs = m_genericContext.ParametersDefinition; if(defs != null) { for(int i = 0; i < defs.Length; i++) { if(i != 0) sb.Append( "," ); sb.Append( defs[i].Name ); } } } sb.Append( ">" ); } } } } ================================================ FILE: Zelig/Zelig/RunTime/Zelig/TypeSystem/Types/UnmanagedPointerTypeRepresentation.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // namespace Microsoft.Zelig.Runtime.TypeSystem { using System; using System.Collections.Generic; public sealed class UnmanagedPointerTypeRepresentation : PointerTypeRepresentation { // // Constructor Methods // public UnmanagedPointerTypeRepresentation( AssemblyRepresentation owner , TypeRepresentation pointerType ) : base( owner, BuiltInTypes.PTR, pointerType ) { } //--// // // Helper Methods // protected override TypeRepresentation AllocateInstantiation( InstantiationContext ic ) { UnmanagedPointerTypeRepresentation tdRes = new UnmanagedPointerTypeRepresentation( m_owner, ic.Instantiate( m_pointerType ) ); tdRes.PopulateInstantiation( this, ic ); return tdRes; } //--// // // Access Methods // public override bool CanBeAssignedFrom( TypeRepresentation rvalue , EquivalenceSet set ) { if(this.EqualsThroughEquivalence( rvalue, set )) { return true; } StackEquivalentType seRValue = rvalue.StackEquivalentType; if(seRValue == StackEquivalentType.Pointer || seRValue == StackEquivalentType.NativeInt ) { // // Any pointer can be cast to an unmanaged pointer. // return true; } return false; } //--// // // Debug Methods // public override String ToString() { System.Text.StringBuilder sb = new System.Text.StringBuilder( "UnmanagedPointerTypeRepresentation(" ); PrettyToString( sb, true, false ); sb.Append( ")" ); return sb.ToString(); } internal override void PrettyToString( System.Text.StringBuilder sb , bool fPrefix , bool fWithAbbreviations ) { base.PrettyToString( sb, fPrefix, fWithAbbreviations ); sb.Append( "*" ); } } } ================================================ FILE: Zelig/Zelig/RunTime/Zelig/TypeSystem/Types/ValueTypeRepresentation.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // namespace Microsoft.Zelig.Runtime.TypeSystem { using System; using System.Collections.Generic; public class ValueTypeRepresentation : TypeRepresentation { // // Constructor Methods // public ValueTypeRepresentation( AssemblyRepresentation owner , BuiltInTypes builtinType , Attributes flags , GenericContext genericContext ) : base( owner, builtinType, flags, genericContext ) { } //--// // // Helper Methods // protected override void PerformInnerDelayedTypeAnalysis( TypeSystem typeSystem , ref ConversionContext context ) { MetaData.Normalized.MetaDataTypeDefinitionBase metadata = (MetaData.Normalized.MetaDataTypeDefinitionBase)typeSystem.GetAssociatedMetaData( this ); ConversionContext localContext = context; localContext.SetContextAsType( this ); m_extends = typeSystem.ConvertToIR( metadata.Extends, localContext ); if(this.IsDelayedType == false) { AnalyzeEntries( typeSystem, ref localContext, metadata.Interfaces, metadata.Fields, metadata.Methods, metadata.MethodImpls ); } } //--// protected override void SetShapeCategory( TypeSystem typeSystem ) { m_vTable.ShapeCategory = VTable.Shape.Struct; } //--// protected override TypeRepresentation AllocateInstantiation( InstantiationContext ic ) { ValueTypeRepresentation tdRes = new ValueTypeRepresentation( m_owner, m_builtinType, m_flags, new GenericContext( this, ic.TypeParameters ) ); tdRes.PopulateInstantiation( this, ic ); return tdRes; } //--// public override GCInfo.Kind ClassifyAsPointer() { return GCInfo.Kind.AggregateType; } //--// public override InstantiationFlavor GetInstantiationFlavor( TypeSystem typeSystem ) { return InstantiationFlavor.ValueType; } //--// // // Access Methods // public override bool CanBeAssignedFrom( TypeRepresentation rvalue , EquivalenceSet set ) { if(this.EqualsThroughEquivalence( rvalue, set )) { return true; } if(rvalue is BoxedValueTypeRepresentation) { if(this == rvalue.UnderlyingType) { // We can always assign a boxed value type to the same unboxed type. At most, this can cause a null // reference expception, but we should handle that later with injected null checks. return true; } } if(this .GetType() == typeof(ScalarTypeRepresentation) && rvalue.GetType() == typeof(ScalarTypeRepresentation) ) { ValueTypeRepresentation rvalue2 = (ValueTypeRepresentation)rvalue; uint thisSize = this .Size; uint rvalueSize = rvalue2.Size; // REVIEW: This check still allows the following operations; we should revisit each case: // - Assign float to int/uint/long/ulong (lossy). // - Assign double to long/ulong (lossy). // - Sign changes for same bit-width (can overflow). return ((thisSize >= rvalueSize) && (rvalueSize != 0)); // 'void' yields a zero size. } return base.CanBeAssignedFrom( rvalue, set ); } public override uint SizeOfHoldingVariable { get { return this.Size; } } public override bool CanPointToMemory { get { return false; } } //--// // // Debug Methods // public override String ToString() { System.Text.StringBuilder sb = new System.Text.StringBuilder( "ValueTypeRepresentation(" ); PrettyToString( sb, true, false ); sb.Append( ")" ); return sb.ToString(); } } } ================================================ FILE: Zelig/Zelig/RunTime/Zelig/TypeSystem/VTable.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // namespace Microsoft.Zelig.Runtime.TypeSystem { using System; using System.Collections.Generic; using System.Runtime.CompilerServices; [WellKnownType( "Microsoft_Zelig_Runtime_TypeSystem_VTable" )] [DisableReferenceCounting] public sealed class VTable { [AllowCompileTimeIntrospection] [Flags] public enum Shape : byte { Invalid = 0x00, Scalar = ValueType | 0x01, Struct = ValueType | 0x02, Interface = Reference | 0x03, Class = Reference | 0x04, ArrayRoot = Reference | Array | 0x05, SzArray = Reference | Array | 0x06, MultiArray = Reference | Array | 0x07, ValueType = 0x20, Reference = 0x40, Array = 0x80, } public struct InterfaceMap { public static readonly InterfaceMap[] SharedEmptyArray = new InterfaceMap[0]; // // State // public VTable Interface; public CodePointer[] MethodPointers; } // // State // // // The two size fields, BaseSize and ElementSize, are only copy of the corresponding values from TypeInfo. // They are here for performance reasons (copying the values here removes one indirection). // During heap walking, we need to compute the size of a block, to skip over it. // // This is done treating each object as if it were an array and computing the quantity: // // = Vt.BaseSize + Vt.ElementSize * // // This works because arrays have an extra uint field at the start, holding the number of elements in the array. // However, instances of non-array types will have random data at the offset of the Length field. // This is not a problem, as long as we ensure that ElementSize is set to zero. // Whatever the value of array length, the multiplication by zero will make it irrelevant. // [WellKnownField( "VTable_BaseSize" )] public uint BaseSize; [WellKnownField( "VTable_ElementSize" )] public uint ElementSize; [WellKnownField( "VTable_TypeInfo" )] public TypeRepresentation TypeInfo; [WellKnownField( "VTable_GCInfo" )] public GCInfo GCInfo; [WellKnownField( "VTable_Type" )] public Type Type; [WellKnownField( "VTable_ShapeCategory" )] public Shape ShapeCategory; // // TODO: We need to embed these pointers in the VTable object itself. // TODO: This way we can assume a fixed offset between MethodPointers and VTable and hardcode it in the method lookup code. // [WellKnownField( "VTable_MethodPointers" )] public CodePointer[] MethodPointers; [WellKnownField( "VTable_InterfaceMap" )] public InterfaceMap[] InterfaceMethodPointers; // // Constructor Methods // public VTable( TypeRepresentation owner ) { this.TypeInfo = owner; this.InterfaceMethodPointers = InterfaceMap.SharedEmptyArray; } //--// // // Helper Methods // public static bool SameType( object a , object b ) { return Get( a ) == Get( b ); } //--// public void ApplyTransformation( TransformationContext context ) { context.Push( this ); context.Transform( ref this.BaseSize ); context.Transform( ref this.ElementSize ); context.Transform( ref this.TypeInfo ); context.Transform( ref this.GCInfo ); context.Transform( ref this.MethodPointers ); context.Pop(); } //--// // // Access Methods // [WellKnownMethod( "VTable_Get" )] [MethodImpl( MethodImplOptions.InternalCall )] [DisableAutomaticReferenceCounting] public extern static VTable Get( object a ); [WellKnownMethod( "VTable_GetInterface" )] [DisableAutomaticReferenceCounting] public static CodePointer[] GetInterface( object a , VTable vtblInterface ) { VTable vtbl = Get( a ); InterfaceMap[] array = vtbl.InterfaceMethodPointers; for(int i = 0; i < array.Length; i++) { if(Object.ReferenceEquals( array[i].Interface, vtblInterface )) { return array[i].MethodPointers; } } return null; } [Inline] public static VTable GetFromType( Type t ) { return GetFromTypeHandle( t.TypeHandle ); } [MethodImpl( MethodImplOptions.InternalCall )] public extern static VTable GetFromTypeHandle( RuntimeTypeHandle hnd ); //--// [Inline] public bool CanBeAssignedFrom( VTable target ) { if(this == target) { return true; } return CanBeAssignedFrom_Slow( target ); } [NoInline] private bool CanBeAssignedFrom_Slow( VTable source ) { if(source.IsSubclassOf( this )) { return true; } if(this.IsArray && source.IsArray) { CHECKS.ASSERT( this.ShapeCategory == Shape.SzArray || this.ShapeCategory == Shape.MultiArray, "Found array that does not inherit from System.Array" ); if(this.ShapeCategory == source.ShapeCategory) { ArrayReferenceTypeRepresentation tdThis = (ArrayReferenceTypeRepresentation)this .TypeInfo; ArrayReferenceTypeRepresentation tdSource = (ArrayReferenceTypeRepresentation)source.TypeInfo; if(tdThis.SameShape( tdSource )) { TypeRepresentation subThis = tdThis .ContainedType.UnderlyingType; TypeRepresentation subSource = tdSource.ContainedType.UnderlyingType; VTable subVTableThis = subThis .VirtualTable; VTable subVTableSource = subSource.VirtualTable; if(subVTableThis == subVTableSource) { return true; } if(subVTableSource.IsValueType) { // // We require exact matching for value types. // return false; } if(subVTableThis.IsInterface) { return subVTableSource.ImplementsInterface( subVTableThis ); } return subVTableThis.CanBeAssignedFrom_Slow( subVTableSource ); } } } return false; } [NoInline] public bool IsSubclassOf( VTable target ) { TypeRepresentation td = this.TypeInfo; while(td != null) { if(target == td.VirtualTable) { return true; } td = td.Extends; } return false; } [NoInline] public bool ImplementsInterface( VTable expectedItf ) { VTable.InterfaceMap[] itfs = this.InterfaceMethodPointers; for(int i = itfs.Length; --i >= 0; ) { if(Object.ReferenceEquals( itfs[i].Interface, expectedItf )) { return true; } } return false; } // // Access Methods // public bool IsArray { [Inline] get { return (this.ShapeCategory & Shape.Array) != 0; } } public bool IsValueType { [Inline] get { return (this.ShapeCategory & Shape.ValueType) != 0; } } public bool IsInterface { [Inline] get { return this.ShapeCategory == Shape.Interface; } } // // Debug Methods // public override string ToString() { System.Text.StringBuilder sb = new System.Text.StringBuilder(); sb.AppendFormat( "VTable({0})", this.TypeInfo ); return sb.ToString(); } } } ================================================ FILE: Zelig/Zelig/RunTime/Zelig/TypeSystem/WellKnownFields.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // namespace Microsoft.Zelig.Runtime.TypeSystem { using System; using System.Collections.Generic; public class WellKnownFields { // // State // public readonly FieldRepresentation ArrayImpl_m_numElements; public readonly FieldRepresentation ThreadImpl_s_currentThread; public readonly FieldRepresentation ThreadImpl_m_currentException; public readonly FieldRepresentation DelegateImpl_m_target; public readonly FieldRepresentation DelegateImpl_m_codePtr; public readonly FieldRepresentation MulticastDelegateImpl_m_invocationList; public readonly FieldRepresentation StringImpl_ArrayLength; public readonly FieldRepresentation StringImpl_StringLength; public readonly FieldRepresentation StringImpl_FirstChar; //--// public readonly FieldRepresentation ObjectHeader_MultiUseWord; public readonly FieldRepresentation ObjectHeader_VirtualTable; public readonly FieldRepresentation CodePointer_Target; public readonly FieldRepresentation CodeMap_LookupAddress; public readonly FieldRepresentation CodeMap_Target; public readonly FieldRepresentation CodeMap_Ranges; public readonly FieldRepresentation CodeMap_ExceptionMap; public readonly FieldRepresentation ExceptionMap_Ranges; public readonly FieldRepresentation VTable_BaseSize; public readonly FieldRepresentation VTable_ElementSize; public readonly FieldRepresentation VTable_TypeInfo; public readonly FieldRepresentation VTable_GCInfo; public readonly FieldRepresentation VTable_Type; public readonly FieldRepresentation VTable_ShapeCategory; public readonly FieldRepresentation VTable_MethodPointers; public readonly FieldRepresentation VTable_InterfaceMap; public readonly FieldRepresentation RuntimeTypeImpl_m_handle; public readonly FieldRepresentation TypeRepresentation_InterfaceMethodTables; public readonly FieldRepresentation TypeRepresentation_MethodTable; public readonly FieldRepresentation RuntimeTypeHandleImpl_m_value; public readonly FieldRepresentation RuntimeFieldHandleImpl_m_value; public readonly FieldRepresentation RuntimeMethodHandleImpl_m_value; public readonly FieldRepresentation ResourceManagerImpl_s_resources; //--// public readonly FieldRepresentation Memory_m_availableMemory; public readonly FieldRepresentation Memory_m_relocationInfo; public readonly FieldRepresentation RelocationInfo_m_data; public readonly FieldRepresentation GarbageCollectionManager_m_extensionTargets; public readonly FieldRepresentation GarbageCollectionManager_m_extensionHandlers; // // Helper Methods // public void ApplyTransformation( TransformationContext context ) { context.Push( this ); context.TransformFields( this ); context.Pop(); } } } ================================================ FILE: Zelig/Zelig/RunTime/Zelig/TypeSystem/WellKnownMethods.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // namespace Microsoft.Zelig.Runtime.TypeSystem { using System; using System.Collections.Generic; public class WellKnownMethods { // // State // public readonly MethodRepresentation MemoryManager_Allocate; public readonly MethodRepresentation MemoryManager_Release; public readonly MethodRepresentation TypeSystemManager_InvokeStaticConstructors; public readonly MethodRepresentation TypeSystemManager_AllocateObject; public readonly MethodRepresentation TypeSystemManager_AllocateReferenceCountingObject; public readonly MethodRepresentation TypeSystemManager_AllocateObjectWithExtensions; public readonly MethodRepresentation TypeSystemManager_AllocateArray; public readonly MethodRepresentation TypeSystemManager_AllocateReferenceCountingArray; public readonly MethodRepresentation TypeSystemManager_AllocateArrayNoClear; public readonly MethodRepresentation TypeSystemManager_AllocateString; public readonly MethodRepresentation TypeSystemManager_CastToType; public readonly MethodRepresentation TypeSystemManager_CastToTypeNoThrow; public readonly MethodRepresentation TypeSystemManager_CastToSealedType; public readonly MethodRepresentation TypeSystemManager_CastToSealedTypeNoThrow; public readonly MethodRepresentation TypeSystemManager_CastToInterface; public readonly MethodRepresentation TypeSystemManager_CastToInterfaceNoThrow; public readonly MethodRepresentation TypeSystemManager_Throw; public readonly MethodRepresentation TypeSystemManager_Rethrow; public readonly MethodRepresentation TypeSystemManager_get_Instance; public readonly MethodRepresentation VTable_Get; public readonly MethodRepresentation VTable_GetInterface; public readonly MethodRepresentation ArrayImpl_get_Length; public readonly MethodRepresentation StringImpl_ctor_charArray_int_int; public readonly MethodRepresentation StringImpl_ctor_charArray; public readonly MethodRepresentation StringImpl_ctor_char_int; public readonly MethodRepresentation StringImpl_FastAllocateString; public readonly MethodRepresentation StringImpl_FastAllocateReferenceCountingString; public readonly MethodRepresentation MulticastDelegateImpl_MulticastDelegateImpl; public readonly MethodRepresentation ThreadImpl_ctor; public readonly MethodRepresentation ThreadImpl_get_CurrentThread; public readonly MethodRepresentation ThreadImpl_GetCurrentException; public readonly MethodRepresentation ThreadImpl_ThrowNullException; public readonly MethodRepresentation ThreadImpl_ThrowIndexOutOfRangeException; public readonly MethodRepresentation ThreadImpl_ThrowOverflowException; public readonly MethodRepresentation ThreadImpl_ThrowNotImplementedException; public readonly MethodRepresentation ThreadImpl_AllocateReleaseReferenceHelper; public readonly MethodRepresentation RuntimeHelpers_InitializeArray2; public readonly MethodRepresentation TypeImpl_GetTypeFromHandle; public readonly MethodRepresentation InterlockedImpl_InternalExchange_int; public readonly MethodRepresentation InterlockedImpl_InternalExchange_float; public readonly MethodRepresentation InterlockedImpl_InternalExchange_IntPtr; public readonly MethodRepresentation InterlockedImpl_InternalExchange_Template; public readonly MethodRepresentation InterlockedImpl_InternalCompareExchange_int; public readonly MethodRepresentation InterlockedImpl_InternalCompareExchange_float; public readonly MethodRepresentation InterlockedImpl_InternalCompareExchange_IntPtr; public readonly MethodRepresentation InterlockedImpl_InternalCompareExchange_Template; public readonly MethodRepresentation InterlockedImpl_InternalAdd_int; public readonly MethodRepresentation ReferenceCountingCollector_LoadAndAddReference; public readonly MethodRepresentation ReferenceCountingCollector_Swap; public readonly MethodRepresentation ReferenceCountingCollector_ReferenceCountingExchange; public readonly MethodRepresentation ReferenceCountingCollector_ReferenceCountingCompareExchange; public readonly MethodRepresentation Bootstrap_HeapInitialization; public readonly MethodRepresentation Bootstrap_ReferenceCountingInitialization; public readonly MethodRepresentation ThreadManager_CleanupBootstrapThread; public readonly MethodRepresentation ThreadManager_CleanupBootstrapThreadIfNeeded; //--// public readonly MethodRepresentation Object_Equals; public readonly MethodRepresentation Object_GetHashCode; public readonly MethodRepresentation ObjectHeader_AddReference; public readonly MethodRepresentation ObjectHeader_ReleaseReference; public readonly MethodRepresentation System_Buffer_InternalMemoryCopy; //public readonly MethodRepresentation System_Buffer_InternalBackwardMemoryCopy; public readonly MethodRepresentation Helpers_BinaryOperations_IntDiv; public readonly MethodRepresentation Helpers_BinaryOperations_IntRem; public readonly MethodRepresentation Helpers_BinaryOperations_UintDiv; public readonly MethodRepresentation Helpers_BinaryOperations_UintRem; public readonly MethodRepresentation Helpers_BinaryOperations_LongMul; public readonly MethodRepresentation Helpers_BinaryOperations_LongDiv; public readonly MethodRepresentation Helpers_BinaryOperations_LongRem; public readonly MethodRepresentation Helpers_BinaryOperations_LongShl; public readonly MethodRepresentation Helpers_BinaryOperations_LongShr; public readonly MethodRepresentation Helpers_BinaryOperations_UlongMul; public readonly MethodRepresentation Helpers_BinaryOperations_UlongDiv; public readonly MethodRepresentation Helpers_BinaryOperations_UlongRem; public readonly MethodRepresentation Helpers_BinaryOperations_UlongShl; public readonly MethodRepresentation Helpers_BinaryOperations_UlongShr; public readonly MethodRepresentation Finalizer_Allocate; //--// public readonly MethodRepresentation Microsoft_Zelig_Runtime_AbstractMethodWrapper_AddActivationRecordEvent; public readonly MethodRepresentation Microsoft_Zelig_Runtime_AbstractMethodWrapper_Prologue; public readonly MethodRepresentation Microsoft_Zelig_Runtime_AbstractMethodWrapper_Prologue2; public readonly MethodRepresentation Microsoft_Zelig_Runtime_AbstractMethodWrapper_Epilogue; public readonly MethodRepresentation Microsoft_Zelig_Runtime_AbstractMethodWrapper_Epilogue2; public readonly MethodRepresentation Microsoft_Zelig_Runtime_Memory_Fill; // // Helper Methods // public void ApplyTransformation( TransformationContext context ) { context.Push( this ); context.TransformFields( this ); context.Pop(); } } } ================================================ FILE: Zelig/Zelig/RunTime/Zelig/TypeSystem/WellKnownTypes.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // namespace Microsoft.Zelig.Runtime.TypeSystem { using System; using System.Collections.Generic; public class WellKnownTypes { // // State // // // We need to explictly know at least WellKnownTypeAttribute, the rest will be resolved based on WellKnownType attributes on the actual types. // [WellKnownTypeLookup( "mscorlib", "Microsoft.Zelig.Internals", "WellKnownTypeAttribute" )] public readonly TypeRepresentation Microsoft_Zelig_Internals_WellKnownTypeAttribute; [WellKnownTypeLookup( "Microsoft.Zelig.Runtime.Common", "Microsoft.Zelig.Runtime.TypeSystem", "WellKnownTypeAttribute" )] public readonly TypeRepresentation Microsoft_Zelig_Runtime_TypeSystem_WellKnownTypeAttribute; //--// [LinkToRuntimeType(typeof(System.Object ))] public readonly TypeRepresentation System_Object; [LinkToRuntimeType(typeof(System.Array ))] public readonly TypeRepresentation System_Array; [LinkToRuntimeType(typeof(System.ValueType ))] public readonly TypeRepresentation System_ValueType; [LinkToRuntimeType(typeof(System.Enum ))] public readonly TypeRepresentation System_Enum; [LinkToRuntimeType(typeof(void ))] public readonly TypeRepresentation System_Void; [LinkToRuntimeType(typeof(System.Boolean ))] public readonly TypeRepresentation System_Boolean; [LinkToRuntimeType(typeof(System.Char ))] public readonly TypeRepresentation System_Char; [LinkToRuntimeType(typeof(System.SByte ))] public readonly TypeRepresentation System_SByte; [LinkToRuntimeType(typeof(System.Byte ))] public readonly TypeRepresentation System_Byte; [LinkToRuntimeType(typeof(System.Int16 ))] public readonly TypeRepresentation System_Int16; [LinkToRuntimeType(typeof(System.UInt16 ))] public readonly TypeRepresentation System_UInt16; [LinkToRuntimeType(typeof(System.Int32 ))] public readonly TypeRepresentation System_Int32; [LinkToRuntimeType(typeof(System.UInt32 ))] public readonly TypeRepresentation System_UInt32; [LinkToRuntimeType(typeof(System.Int64 ))] public readonly TypeRepresentation System_Int64; [LinkToRuntimeType(typeof(System.UInt64 ))] public readonly TypeRepresentation System_UInt64; [LinkToRuntimeType(typeof(System.Single ))] public readonly TypeRepresentation System_Single; [LinkToRuntimeType(typeof(System.Double ))] public readonly TypeRepresentation System_Double; [LinkToRuntimeType(typeof(System.String ))] public readonly TypeRepresentation System_String; [LinkToRuntimeType(typeof(System.IntPtr ))] public readonly TypeRepresentation System_IntPtr; [LinkToRuntimeType(typeof(System.UIntPtr ))] public readonly TypeRepresentation System_UIntPtr; [LinkToRuntimeType(typeof(System.Nullable<> ))] public readonly TypeRepresentation System_Nullable_of_T; [LinkToRuntimeType(typeof(System.TypedReference ))] public readonly TypeRepresentation System_TypedReference; [LinkToRuntimeType(typeof(System.Delegate ))] public readonly TypeRepresentation System_Delegate; [LinkToRuntimeType(typeof(System.MulticastDelegate))] public readonly TypeRepresentation System_MulticastDelegate; public readonly TypeRepresentation System_WeakReference; public readonly TypeRepresentation System_Attribute; public readonly TypeRepresentation System_RuntimeTypeHandle; public readonly TypeRepresentation System_RuntimeFieldHandle; public readonly TypeRepresentation System_RuntimeMethodHandle; public readonly TypeRepresentation System_RuntimeArgumentHandle; public readonly TypeRepresentation System_RuntimeType; public readonly TypeRepresentation System_Threading_Thread; public readonly TypeRepresentation System_Runtime_CompilerServices_IsVolatile; public readonly TypeRepresentation System_FlagsAttribute; public readonly TypeRepresentation System_Runtime_InteropServices_FieldOffsetAttribute; public readonly TypeRepresentation System_IComparable_of_T; public readonly TypeRepresentation System_Collections_Generic_Comparer_of_T; public readonly TypeRepresentation System_Collections_Generic_GenericComparer_of_T; public readonly TypeRepresentation System_Collections_Generic_NullableComparer_of_T; public readonly TypeRepresentation System_Collections_Generic_ObjectComparer_of_T; public readonly TypeRepresentation System_IEquatable_of_T; public readonly TypeRepresentation System_Collections_Generic_EqualityComparer_of_Enum; public readonly TypeRepresentation System_Collections_Generic_EqualityComparer_of_Enum_sbyte; public readonly TypeRepresentation System_Collections_Generic_EqualityComparer_of_Enum_short; public readonly TypeRepresentation System_Collections_Generic_EqualityComparer_of_Enum_long; public readonly TypeRepresentation System_Collections_Generic_EqualityComparer_of_T; public readonly TypeRepresentation System_Collections_Generic_GenericEqualityComparer_of_T; public readonly TypeRepresentation System_Collections_Generic_NullableEqualityComparer_of_T; public readonly TypeRepresentation System_Collections_Generic_ObjectEqualityComparer_of_T; public readonly TypeRepresentation System_CurrentSystemTimeZone; public readonly TypeRepresentation System_Resources_ResourceManager; // TypeSystem attributes public readonly TypeRepresentation Microsoft_Zelig_Runtime_TypeSystem_AssumeReferencedAttribute; public readonly TypeRepresentation Microsoft_Zelig_Runtime_TypeSystem_DisableAutomaticReferenceCountingAttribute; public readonly TypeRepresentation Microsoft_Zelig_Runtime_TypeSystem_DisableReferenceCountingAttribute; // Runtime attributes public readonly TypeRepresentation Microsoft_Zelig_Runtime_AliasForBaseFieldAttribute; public readonly TypeRepresentation Microsoft_Zelig_Runtime_AliasForBaseMethodAttribute; public readonly TypeRepresentation Microsoft_Zelig_Runtime_AliasForSuperMethodAttribute; public readonly TypeRepresentation Microsoft_Zelig_Runtime_AliasForTargetMethodAttribute; public readonly TypeRepresentation Microsoft_Zelig_Runtime_AlignmentRequirementsAttribute; public readonly TypeRepresentation Microsoft_Zelig_Runtime_DiscardTargetImplementationAttribute; public readonly TypeRepresentation Microsoft_Zelig_Runtime_ExtendClassAttribute; public readonly TypeRepresentation Microsoft_Zelig_Runtime_InjectAtEntryPointAttribute; public readonly TypeRepresentation Microsoft_Zelig_Runtime_InjectAtExitPointAttribute; public readonly TypeRepresentation Microsoft_Zelig_Runtime_MergeWithTargetImplementationAttribute; public readonly TypeRepresentation Microsoft_Zelig_Runtime_SingletonFactoryPlatformFilterAttribute; public readonly TypeRepresentation Microsoft_Zelig_Runtime_ProductFilterAttribute; public readonly TypeRepresentation Microsoft_Zelig_Runtime_CapabilitiesFilterAttribute; // Helper types public readonly TypeRepresentation Microsoft_Zelig_Runtime_ObjectHeader; public readonly TypeRepresentation Microsoft_Zelig_Runtime_LandingPadResult; public readonly TypeRepresentation Microsoft_Zelig_Runtime_RuntimeTypeImpl; public readonly TypeRepresentation Microsoft_Zelig_Runtime_SZArrayHelper; public readonly TypeRepresentation Microsoft_Zelig_Runtime_TypeSystem_CodePointer; public readonly TypeRepresentation Microsoft_Zelig_Runtime_TypeSystem_VTable; public readonly TypeRepresentation Microsoft_Zelig_Runtime_TypeSystem_GlobalRoot; //--// public readonly TypeRepresentation Microsoft_Zelig_Runtime_ThreadManager; public readonly TypeRepresentation Microsoft_Zelig_Runtime_GarbageCollectionManager; public readonly TypeRepresentation Microsoft_Zelig_Runtime_ReferenceCountingCollector; public readonly TypeRepresentation Microsoft_Zelig_Runtime_StrictReferenceCountingCollector; //--// // // Helper Methods // public void ApplyTransformation( TransformationContext context ) { context.Push( this ); context.TransformFields( this ); context.Pop(); } } } ================================================ FILE: Zelig/Zelig/Test/Common/Assert.cs ================================================ using System; using Microsoft.Zelig.Runtime; namespace Microsoft.Zelig.Test { public static class Assert { public static TestResult CheckFailed(TestResult result) { if ((result & TestResult.Fail) != 0) { BugCheck.Assert(false, BugCheck.StopCode.InvalidOperation); } return result; } public static TestResult CheckFailed(TestResult result, string testName, int testNumber) { if ((result & TestResult.Fail) != 0) { TestConsole.WriteLine($"Failed: {testName}{testNumber}"); } else if ((result & TestResult.KnownFailure) != 0) { TestConsole.WriteLine($"Known failure: {testName}{testNumber}"); } return result; } public static void AreEqual(object expected, object actual) { AreEqual(expected, actual, null); } // TODO public static void AreEqual(object expected, object actual, string message) { if (!object.Equals(expected, actual)) { if(message == null) message = String.Empty; throw new ApplicationException(message + "\n\texpected:{" + ((expected == null) ? "(null)" : expected.ToString()) + "}\n\t but was:{" + ((actual == null) ? "(null)" : actual.ToString()) + "}"); } } // TODO public static void AreSame(object expected, object actual) { AreSame(expected, actual, null); } // TODO public static void AreSame(object expected, object actual, string message) { if (expected != actual) { if(message == null) message = String.Empty; throw new ApplicationException(message + "\n\texpected:{" + ((expected == null) ? "(null)" : expected.ToString()) + "}\n\t but was:{" + ((actual == null) ? "(null)" : actual.ToString()) + "}"); } } // TODO public static void IsTrue(bool condition) { IsTrue(condition, null); } // TODO public static void IsTrue(bool condition, string message) { if (!condition) { throw new ApplicationException(message); } } // TODO public static void IsFalse(bool condition) { IsFalse(condition, null); } // TODO public static void IsFalse(bool condition, string message) { if (condition) { throw new ApplicationException(message); } } // TODO public static void IsNull(object anObject) { IsNull(anObject, null); } // TODO public static void IsNull(object anObject, string message) { if (anObject != null) { throw new ApplicationException(message); } } // TODO public static void IsNotNull(object anObject) { IsNotNull(anObject, null); } // TODO public static void IsNotNull(object anObject, string message) { if (anObject == null) { throw new ApplicationException(message); } } } } ================================================ FILE: Zelig/Zelig/Test/Common/Console.cs ================================================  using Microsoft.Zelig.Runtime; namespace Microsoft.Zelig.Test { public static class TestConsole { public static void WriteLine(string message) { BugCheck.Log( message ); } } } ================================================ FILE: Zelig/Zelig/Test/Common/Properties/AssemblyInfo.cs ================================================ using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; // General Information about an assembly is controlled through the following // set of attributes. Change these attribute values to modify the information // associated with an assembly. [assembly: AssemblyTitle("Test_Common")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("simple")] [assembly: AssemblyCopyright("Copyright © 2015")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible(false)] // The following GUID is for the ID of the typelib if this project is exposed to COM [assembly: Guid("aa4773c3-713c-4612-a7fa-8ad068fd2011")] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Build and Revision Numbers // by using the '*' as shown below: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("1.0.0.0")] [assembly: AssemblyFileVersion("1.0.0.0")] ================================================ FILE: Zelig/Zelig/Test/Common/SpotTestLog.cs ================================================ using Microsoft.Zelig.Runtime; using System; namespace Microsoft.Zelig.Test { public abstract class Log { #region Member Variables private static int m_passCount = 0; private static int m_failCount = 0; private static int m_skipCount = 0; private static int m_knownFailureCount = 0; private enum CommentType { Comment, Exception } #endregion #region Public /// /// This method is used to log any test comments. /// /// A string containing the test comments. public static void Comment(string message) { BugCheck.Log( "\t" + message ); //LocalComment(message, CommentType.Comment); } /// /// This method is used to log any test comments. /// /// A string containing the test comments. public static void FilteredComment(string message) { //SpotTestLog.WriteRaw("\t" // + "" + FilterUnsafeXml(message) + "" // + "" + GetDate() + "" // + "" // + ""); } /// /// This method is used to log any exceptions that may arise during the test. /// /// A string containing the exception message. public static void Exception(string message) { //LocalComment(message, CommentType.Exception); } /// /// This method is used to log any exceptions that may arise during the test. /// /// A string containing the exception message. public static void Exception(string message, Exception ex) { //LocalComment(message, CommentType.Exception); //LocalComment("Message: " + ex.Message, CommentType.Exception); //LocalComment("Stack: " + ex.StackTrace, CommentType.Exception); //if (ex.InnerException != null) //{ // LocalComment("InnerException Message: " + ex.InnerException.Message, CommentType.Exception); // LocalComment("InnerException Stack: " + ex.InnerException.StackTrace, CommentType.Exception); //} } #endregion #region Internal internal static void ResetCounts() { m_passCount = 0; m_failCount = 0; m_skipCount = 0; m_knownFailureCount = 0; } internal static void Initialize(string test) { m_passCount = 0; m_failCount = 0; m_skipCount = 0; m_knownFailureCount = 0; //SpotTestLog.StartTestLog(test); //Log.StartMethod("Initialize"); } internal static void CleanUp(string test) { //Log.EndMethod("CleanUp"); //SpotTestLog.StartNode("Results"); //LogPassCount(); //LogFailCount(); //LogSkipCount(); //LogKnownFailureCount(); //SpotTestLog.EndNode("Results"); //SpotTestLog.EndTestLog(test); //System.Threading.Thread.Sleep(2000); } internal static void TestResult(string message, TestResult result) { //if (result == Zelig.Test.TestResult.Pass) //{ // SpotTestLog.StartResultNode("Pass"); // Pass( message ); //} //else if (result == Zelig.Test.TestResult.Fail) //{ // SpotTestLog.StartResultNode("Fail"); // Fail( message ); //} //else if (result == Zelig.Test.TestResult.Skip) //{ // SpotTestLog.StartResultNode("Skip"); // Skip( message ); //} //else if (result == Zelig.Test.TestResult.KnownFailure) //{ // SpotTestLog.StartResultNode("KnownFailure"); // KnownFailure( message ); //} //SpotTestLog.EndNode("TestMethodResult"); } internal static void Pass(string message) { m_passCount++; WriteMessage(message); } internal static void Fail(string message) { m_failCount++; WriteMessage(message); } internal static void Skip(string message) { m_skipCount++; WriteMessage(message); } internal static void KnownFailure(string message) { m_knownFailureCount++; WriteMessage(message); } internal static void WriteMessage(string message) { //SpotTestLog.WriteRaw("\t\t" + "" + // "" + GetDate() + "" + // ""); } internal static void StartTestMethod(string name) { //SpotTestLog.StartTestMethod(name); } internal static void EndTestMethod() { //SpotTestLog.EndTestMethod(); } internal static void StartMethod(string name) { //SpotTestLog.StartNode(name); } internal static void EndMethod(string name) { //SpotTestLog.EndNode(name); } #endregion #region Private private static void LocalComment(string message, CommentType ct) { //SpotTestLog.WriteRaw("\t" // + "" // + "" + GetDate() + "" // + "" // + ""); } private static string FilterUnsafeXml(string message) { // The filtering code is slow since it goes char by char and // can lead to time outs on very long strings. Hence do not // filter unsafe xml from strings longer than 200 chars. string filtered = ""; // Iterate through each char and replace as we go for (int i = 0; i < message.Length; i++) { switch (message[i]) { case '&': filtered += "&"; break; case '>': filtered += ">"; break; case '<': filtered += "<"; break; case '"': filtered += """; break; case '\'': filtered += "'"; break; default: int val = (int)message[i]; if ((val > 127) || (val < 32)) { filtered += "&#" + val + ";"; } else { filtered += message[i]; } break; } } return filtered; } private static void LogPassCount() { //SpotTestLog.WriteRaw("\t" + "" + m_passCount.ToString() + "" // + "" + GetDate() + "" + "" + ""); } private static void LogFailCount() { //SpotTestLog.WriteRaw("\t" + "" + m_failCount.ToString() + "" // + "" + GetDate() + "" + "" + ""); } private static void LogSkipCount() { //SpotTestLog.WriteRaw("\t" + "" + m_skipCount.ToString() + "" // + "" + GetDate() + "" + "" + ""); } private static void LogKnownFailureCount() { //SpotTestLog.WriteRaw("\t" + "" + m_knownFailureCount.ToString() + "" // + "" + GetDate() + "" + "" + ""); } private static string GetDate() { return DateTime.Today.Month + "/" + DateTime.Today.Day + "/" + DateTime.Today.Year; } #endregion } internal abstract class SpotTestLog { #region Internal internal static void Write(string node, string data) { //string value = "<" + RemoveInvalidCharacters(node) + ">" + // RemoveInvalidCharacters(data) + ""; //Log.WriteMessage(value); } internal static void StartTestLog(string test) { //string value = ""; //Log.WriteMessage(value); } internal static void EndTestLog(string test) { //string value = ""; //Log.WriteMessage(value); } internal static void StartResultNode(string result) { string value = "\t"; Log.WriteMessage(value); } internal static void EndResultNode(string test) { //string value = ""; //Log.WriteMessage(value); //Log.WriteMessage(string.Empty); } internal static void StartTestMethod(string name) { //string value = ""; //Log.WriteMessage(value); } internal static void EndTestMethod() { //string value = ""; //Log.WriteMessage(value); //Log.WriteMessage(string.Empty); } internal static void StartNode(string node) { //string value; //if (string.Equals(node.ToLower(), "initialize") || // string.Equals(node.ToLower(), "cleanup") || // string.Equals(node.ToLower(), "results")) //{ // if (string.Equals(node.ToLower(), "initialize") || // string.Equals(node.ToLower(), "results")) // { // Log.WriteMessage(string.Empty); // } // value = "<" + RemoveInvalidCharacters(node) + ">"; //} //else //{ // value = "\t<" + RemoveInvalidCharacters(node) + ">"; //} //Log.WriteMessage(value); } internal static void EndNode(string node) { //string value; //if (string.Equals(node.ToLower(), "initialize") || // string.Equals(node.ToLower(), "cleanup") || // string.Equals(node.ToLower(), "results")) //{ // value = ""; //} //else //{ // value = "\t"; //} //Log.WriteMessage(value); //if (string.Equals(node.ToLower(), "initialize") || // string.Equals(node.ToLower(), "results")) //{ // Log.WriteMessage(string.Empty); //} } internal static void WriteDate(string date) { //string value = "" + date + ""; //Log.WriteMessage("\t\t" + value); } internal static void WriteTime(string time) { //string value = ""; //Log.WriteMessage("\t\t" + value); } internal static void WriteText(string text) { //string value = ""; //Log.WriteMessage("\t\t" + value); } internal static void WriteRaw(string text) { //Log.WriteMessage(text); } #endregion #region Private internal static string RemoveInvalidCharacters(string input) { // Remove chars that will cause problems loading the xml file ('<', '>' etc). char[] invalidChars = { '<', '>', '&', '\'', '"' }; char[] array = input.ToCharArray(); foreach (char c in invalidChars) { for (int i = 0; i < array.Length; i++) { if (array[i] == c) { array[i] = ' '; } } } string returnVal = string.Empty; for (int i = 0; i < array.Length; i++) { if (array[i] != ' ') { returnVal += array[i]; } } return returnVal; } private static string StripInValidXmlChars(string s) { string validXML = string.Empty; char current; char[] charArray = s.ToCharArray(); if (s.Length == 0) return string.Empty; for (int i = 0; i < charArray.Length; i++) { current = charArray[i]; if ((current == 0x9) || (current == 0xA) || (current == 0xD) || ((current >= 0x20) && (current <= 0xD7FF)) || ((current >= 0xE000) && (current <= 0xFFFD))) { validXML += current; } } return validXML; } #endregion } } ================================================ FILE: Zelig/Zelig/Test/Common/TestAttributes.cs ================================================ using System; namespace Microsoft.Zelig.Test { [AttributeUsage(AttributeTargets.Method, AllowMultiple = false)] public sealed class SetUp : Attribute { public SetUp() : base() { // Only one SetUp attribute should be allowed per test class. // Any method attributed with [SetUp] should always be executed first. Log.WriteMessage(" "); } } [AttributeUsage(AttributeTargets.Method, AllowMultiple = false)] public sealed class TestMethod : Attribute { public TestMethod() : base() { // Allow for multiple methods with [TestMethod] attribute. } } [AttributeUsage(AttributeTargets.Method, AllowMultiple = false)] public sealed class TearDown : Attribute { public TearDown() : base() { // Only one TearDown attribute should be allowed per test class. // Any method attributed with [TearDown] should always be executed at the end. // This method needs to get executed irrespective of what the test results are. } } } ================================================ FILE: Zelig/Zelig/Test/Common/TestBase.cs ================================================ using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Microsoft.Zelig.Test { public class TestBase { private readonly string m_name; public TestBase() { this.m_name = this.GetType().Name; } public TestBase(String name) { this.m_name = name; } public String Name { get { return m_name; } } public virtual TestResult Run( string[] args ) { return TestResult.Pass; } } } ================================================ FILE: Zelig/Zelig/Test/Common/TestInterface.cs ================================================ using System; namespace Microsoft.Zelig.Test { public enum InitializeResult { ReadyToGo, Skip, } public interface ITestInterface { [SetUp] InitializeResult Initialize(); [TearDown] void CleanUp(); } } ================================================ FILE: Zelig/Zelig/Test/Common/TestResult.cs ================================================ using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Microsoft.Zelig.Test { [Flags] public enum TestResult { Pass = 0, Fail = 0x1, Skip = 0x2, KnownFailure = 0x4, } } ================================================ FILE: Zelig/Zelig/Test/Common/Test_Common.csproj ================================================  Debug AnyCPU {B649B569-516B-4C88-A7B1-EBD02E12DD99} Library Properties Microsoft.Zelig.Test Microsoft.Zelig.Test.Test_Common v4.5 512 true full true $(LlilumBuildRoot)\Target\bin\$(Configuration)\ DEBUG;TRACE prompt 4 full true $(LlilumBuildRoot)\Target\bin\$(Configuration)\ DEBUG;TRACE prompt 4 true {186f31a3-ef89-4a25-b2d5-20060509aa01} Kernel {186f31a3-ef89-4a25-b2d5-20070702aa01} system {186f31a3-ef89-4a25-b2d5-20080628aa01} system_core ================================================ FILE: Zelig/Zelig/Test/Common/Utilities.cs ================================================ using System; namespace Microsoft.Zelig.Test { /// /// A string utility class. /// public class Utilities { #region RandomString private static Random s_random = new Random(); /// /// Array of special characters that are allowed in File names /// public static readonly char[] SafeFileChars = new char[] { '!', '#', '$', '%', '\'', '(', ')', '+', '-', '.', '@', '[', ']', '_', '`', '{', '}', '~' }; /// /// Generates a random string. /// /// random string public static string GetRandomString() { return GetRandomString(-1, RandomType.None); } /// /// Generates a random string of the specified length. /// /// An integer specifying the length of the random string. /// random string public static string GetRandomString(int length) { return GetRandomString(length, RandomType.None); } /// /// Generates a safe random string. /// A safe string consists of only upper case and lower case english alphabets and numbers. /// /// random string public static string GetRandomSafeString() { return GetRandomString(-1, RandomType.String); } /// /// Generates a random safe string of the specified length. /// A safe string consists of only upper case and lower case english alphabets and numbers. /// /// An integer specifying the length of the random string. /// random string public static string GetRandomSafeString(int length) { return GetRandomString(length, RandomType.String); } /// /// Generates a random high byte string of random length. /// /// random string public static string GetRandomHighByteString() { return GetRandomString(-1, RandomType.HighByte); } /// /// Generates a random high byte string of the specified length. /// /// An integer specifying the length of the random string. /// random string public static string GetRandomHighByteString(int length) { return GetRandomString(length, RandomType.HighByte); } /// /// Generates a randome safe filename string. /// A safe string consists of only upper case, lower case, numbers, and SafeFileChars /// /// random string public static string GetRandomFileName() { return GetRandomString(-1, RandomType.File); } /// /// Generates a randome safe filename string of the specified length. /// A safe string consists of only upper case, lower case, numbers, and SafeFileChars /// /// An integer specifying the length of the random string /// random string public static string GetRandomFileName(int length) { return GetRandomString(length, RandomType.File); } /// /// Used to specified RandomString type /// private enum RandomType : int { String = 0, // only alpha numeric File = 1, // alpha/numeric/SafeFileChars None = 2, // ascii 32 -126 HighByte = 3 // Beyond ascii 128 (into the abyss) } /// /// Used to generate random string of specified length and type /// /// An integer specifying the length on the random string /// A RandomType enum specifying random string type /// random string private static string GetRandomString(int length, RandomType rnd) { // Negative numbers indicate a random string length of 10-20 is desired. if (length < 0) length = 10 + s_random.Next(11); char[] chars = new char[length]; for (int i = 0; i < length; i++) { switch (rnd) { case RandomType.String: switch (s_random.Next(3)) { case 0: // Get a random char between ascii 65 and 90 (upper case alphabets). chars[i] = (char)(65 + s_random.Next(26)); break; case 1: // Get a random char between ascii 97 and 122 (lower case alphabets). chars[i] = (char)(97 + s_random.Next(26)); break; case 2: // Get a random number 0 - 9 chars[i] = (char)('0' + s_random.Next(10)); break; } break; case RandomType.File: // 10% use SafeFileChars if (s_random.Next(10) == 0) { // Get a random char from SafeFileChars chars[i] = SafeFileChars[s_random.Next(SafeFileChars.Length)]; } else { goto case 0; // value - RandomType.String } break; case RandomType.None: // Get a random char from ascii 32 - 126 chars[i] = (char)(32 + s_random.Next(95)); break; case RandomType.HighByte: // Get a random char from ascii 128 - 65535 chars[i] = (char)(128 + s_random.Next(65407)); break; } } return new string(chars); } #endregion RandomString #region RandomByte /// /// A utility method to generate a random byte. /// /// public static byte GetRandomByte() { return (byte)s_random.Next(); } /// /// A utility to a generate random byte array of specified length. /// /// /// public static byte[] GetRandomBytes(int length) { byte[] byteArr = new byte[length]; s_random.NextBytes(byteArr); return byteArr; } #endregion RandomByte #region ConvertToHex /// /// A utility to Convert uint to Hex string /// /// public static string UintToHex(uint word) { string ret = new string("0x".ToCharArray()); for (int shift = 12; shift >= 0; shift -= 4) { ret += ByteToChar((byte)(word >> shift)); } return ret; } /// /// A utility to Convert byte to Hex string /// /// public static string ByteToHex(byte data) { string ret = new string("0x".ToCharArray()); for (int shift = 4; shift >= 0; shift -= 4) { ret += ByteToChar((byte)(data >> shift)); } return ret; } /// /// A utility to Convert byte to char /// /// private static char ByteToChar(byte nybble) { nybble &= 15; if (nybble < 10) { return (char)(nybble + (byte)'0'); } else { return (char)((nybble - 10) + (byte)'A'); } } #endregion ConvertToHex } } ================================================ FILE: Zelig/Zelig/Test/CompileTime/CompilerTests/CompilerTests.csproj ================================================  Debug AnyCPU {4D364D69-06AF-4277-8828-3B4313533A5B} Library Properties CompilerTests Microsoft.Zelig.Compiler.Tests v4.5.2 512 {3AC096D0-A1C2-E12C-1390-A8335801FDAB};{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC} 10.0 $(MSBuildExtensionsPath32)\Microsoft\VisualStudio\v$(VisualStudioVersion) $(ProgramFiles)\Common Files\microsoft shared\VSTT\$(VisualStudioVersion)\UITestExtensionPackages False UnitTest true full false $(LlilumBuildRoot)\Host\bin\$(Configuration)\ DEBUG;TRACE prompt 4 x64 pdbonly true $(LlilumBuildRoot)\Host\bin\$(Configuration)\ TRACE prompt 4 {186f31a3-ef89-4a25-b2d5-20070605aa02} FrontEnd False False False False ================================================ FILE: Zelig/Zelig/Test/CompileTime/CompilerTests/Properties/AssemblyInfo.cs ================================================ using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; // General Information about an assembly is controlled through the following // set of attributes. Change these attribute values to modify the information // associated with an assembly. [assembly: AssemblyTitle("CompilerTests")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("CompilerTests")] [assembly: AssemblyCopyright("Copyright © 2015")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible(false)] // The following GUID is for the ID of the typelib if this project is exposed to COM [assembly: Guid("4d364d69-06af-4277-8828-3b4313533a5b")] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Build and Revision Numbers // by using the '*' as shown below: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("1.0.0.0")] [assembly: AssemblyFileVersion("1.0.0.0")] ================================================ FILE: Zelig/Zelig/Test/CompileTime/CompilerTests/SimpleTests.cs ================================================ using System; using Microsoft.VisualStudio.TestTools.UnitTesting; using Microsoft.Zelig.FrontEnd; using System.IO; namespace CompilerTests { [TestClass] public class SimpleTests { private const string configPath = @"..\..\..\..\Zelig\CompileTime\CodeGenerator\FrontEnd\mbed_simple_LPC1768.FrontEndConfig"; private const string irPath = @"..\..\..\..\LLVM2IR_results\mbed\simple\Microsoft.Zelig.Test.mbed.Simple.ZeligIR"; private static bool compiled = false; [TestMethod] public void TestCompilation() { Compile(); } [TestMethod] public void TestZeligIR() { CompileIfNeeded(); Assert.IsTrue(File.Exists(irPath)); string str = File.ReadAllText(irPath); //Check for Program type Assert.IsTrue(str.Contains(@"Type: ConcreteReferenceTypeRepresentation(Microsoft.Zelig.Test.mbed.Simple.Program)")); //Check for Main method Assert.IsTrue(str.Contains(@"Method StaticMethodRepresentation(void Microsoft.Zelig.Test.mbed.Simple.Program::Main())")); } private void CompileIfNeeded() { if (!compiled) Compile(); } private void Compile() { Bench.RunBench(new string[] { "-cfg", configPath }); compiled = true; } } } ================================================ FILE: Zelig/Zelig/Test/CompileTime/GenericInstantiationClosure/Fail_Field/test.cs ================================================ // // Copyright (c) 2001 Microsoft Corporation. All rights reserved. // namespace GenericInstantiationClosure.Fail_Field { public class Fail_Field_A { public Fail_Field_B< Fail_Field_A< T > > value = new Fail_Field_B< Fail_Field_A< T > >(); } public class Fail_Field_B { public Fail_Field_A< Fail_Field_B< T > > value = new Fail_Field_A< Fail_Field_B< T > >(); } public class Bench { public static void Main() { Fail_Field_A t = new Fail_Field_A(); } } } ================================================ FILE: Zelig/Zelig/Test/CompileTime/GenericInstantiationClosure/Fail_GenericMethod1/test.cs ================================================ // // Copyright (c) 2001 Microsoft Corporation. All rights reserved. // namespace GenericInstantiationClosure.Fail_GenericMethod1 { public class Fail_GenericMethod_A { static public void Compute() { Fail_GenericMethod_B.Compute< Fail_GenericMethod_A >(); } } public class Fail_GenericMethod_B { static public void Compute() { Fail_GenericMethod_A.Compute< Fail_GenericMethod_B >(); } } public class Bench { public static void Main() { Fail_GenericMethod_A.Compute< int >(); } } } ================================================ FILE: Zelig/Zelig/Test/CompileTime/GenericInstantiationClosure/Fail_GenericMethod2/test.cs ================================================ // // Copyright (c) 2001 Microsoft Corporation. All rights reserved. // namespace GenericInstantiationClosure.Fail_GenericMethod2 { public class Fail_GenericMethod_C { public class Sub { } static public void Compute() { Compute< Sub >(); } } public class Bench { public static void Main() { Fail_GenericMethod_C.Compute< int >(); } } } ================================================ FILE: Zelig/Zelig/Test/CompileTime/GenericInstantiationClosure/Fail_Inheritance/test.cs ================================================ // // Copyright (c) 2001 Microsoft Corporation. All rights reserved. // namespace GenericInstantiationClosure.Fail_Inheritance { public class Fail_B { } public class Fail_A : Fail_B< Fail_A< Fail_A > > { } public class Bench { public static void Main() { Fail_A t = new Fail_A(); } } } ================================================ FILE: Zelig/Zelig/Test/CompileTime/GenericInstantiationClosure/Fail_Method/test.cs ================================================ // // Copyright (c) 2001 Microsoft Corporation. All rights reserved. // namespace GenericInstantiationClosure.Fail_Method { public class Fail_Method_A { static public void Compute() { Fail_Method_B< Fail_Method_A< T > >.Compute(); } } public class Fail_Method_B { static public void Compute() { Fail_Method_A< Fail_Method_B< T > >.Compute(); } } public class Bench { public static void Main() { Fail_Method_A< int >.Compute(); } } } ================================================ FILE: Zelig/Zelig/Test/CompileTime/GenericInstantiationClosure/Pass/test.cs ================================================ // // Copyright (c) 2001 Microsoft Corporation. All rights reserved. // namespace GenericInstantiationClosure.Pass { public class Pass_B { } public class Pass_A : Pass_B< Pass_A > { } //--// public class Pass_P { } public class Pass_C : Pass_P< Pass_D > { } public class Pass_D : Pass_P< Pass_C > { } public class Bench { public static void Main() { } } } ================================================ FILE: Zelig/Zelig/Test/CompileTime/GenericInstantiationClosure/rebuildDir.cmd ================================================ @echo off setlocal set DIR=%1 cd %DIR% sd edit * csc /out:%DIR%.exe /debug test.cs ================================================ FILE: Zelig/Zelig/Test/Desktop/Net/HttpTest/App.config ================================================  ================================================ FILE: Zelig/Zelig/Test/Desktop/Net/HttpTest/HttpTest.csproj ================================================  Debug AnyCPU {0F0DC8C5-349B-453D-94F2-123205E3EADD} Exe Properties HttpTest HttpTest v4.5.2 512 true AnyCPU true full false bin\Debug\ DEBUG;TRACE prompt 4 AnyCPU pdbonly true bin\Release\ TRACE prompt 4 ================================================ FILE: Zelig/Zelig/Test/Desktop/Net/HttpTest/Program.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // // // NOTICE: The firewall will generally block all incoming connections to a machine from external devices. // Please go to Windows Firewall -> Advanced Settings, and create an inbound rule that allows connections // to port 8080 // namespace HttpTest { using System; using System.Net; using System.Threading; using System.Linq; using System.Text; using System.Diagnostics; using System.Threading.Tasks; using System.Net.Sockets; using System.Collections.Generic; public class WebServer { private readonly HttpListener _listener = new HttpListener(); private readonly Func _responderMethod; public WebServer(Func method, params string[] prefixes) { if (!HttpListener.IsSupported) { throw new NotSupportedException("Needs Windows XP SP2, Server 2003 or later."); } // URI prefixes are required, for example // "http://localhost:8080/index/". if (prefixes == null || prefixes.Length == 0) { throw new ArgumentException("prefixes"); } // A responder method is required if (method == null) { throw new ArgumentException("method"); } foreach (string s in prefixes) { _listener.Prefixes.Add(s); } _responderMethod = method; _listener.Start(); } public void Run() { Task.Run(() => { Console.WriteLine("Webserver running..."); try { while (_listener.IsListening) { Task.Run(() => { var context = _listener.GetContext(); try { // Received a request Console.WriteLine("\n!!!Received Request!!!\n"); Console.WriteLine("Method: {0}\n", context.Request.HttpMethod); Console.WriteLine("Headers: {0}\n", context.Request.Headers); Console.WriteLine("Raw URL: {0}\n", context.Request.RawUrl); // See what data we received using (System.IO.Stream data = context.Request.InputStream) { using (System.IO.StreamReader reader = new System.IO.StreamReader(data, context.Request.ContentEncoding)) { Console.WriteLine("Data from request:\n"); Console.WriteLine(reader.ReadToEnd()); } } // Send back a response using our custom function based on request data string response = _responderMethod(context.Request); Console.WriteLine("Sending Response: {0}\n", response); byte[] buf = Encoding.ASCII.GetBytes(response); context.Response.ContentLength64 = buf.Length; context.Response.OutputStream.Write(buf, 0, buf.Length); } catch (Exception ex) { // suppress any exceptions and log Console.WriteLine("Server caught an exception: {0}", ex.StackTrace); } finally { // always close the stream Console.WriteLine("Closing the output stream"); context.Response.OutputStream.Close(); } }); } } catch (Exception ex) { Console.WriteLine("Server caught an exception: {0}", ex.Message); } }); } public void Stop() { _listener.Stop(); _listener.Close(); } } class Program { static void Main(string[] args) { WebServer server = null; // // Establish the local endpoint for the socket. // IPHostEntry ipHostInfo = Dns.GetHostEntry(Dns.GetHostName()); // // Pick 1st IPv4 address in the list. // List ipv4Locals = new List(); foreach (var addr in ipHostInfo.AddressList) { if (addr.AddressFamily == AddressFamily.InterNetwork) { ipv4Locals.Add(addr); } } try { Console.WriteLine("Starting the web server..."); server = new WebServer(SendResponse, "http://localhost:8080/", "http://*:8080/"); server.Run(); Console.WriteLine("Web server started."); Console.WriteLine("Your possible IPv4 addresses. Use in SimpleHTTP Test Program:"); foreach (var addr in ipv4Locals) { Console.WriteLine("http://{0}:8080", addr.ToString()); } Console.WriteLine("Press the Q key to quit."); while (Console.ReadKey().KeyChar != 'q' && Console.ReadKey().KeyChar != 'Q') { // Block until user wants to quit } server.Stop(); } catch(System.Net.HttpListenerException ex) { Console.WriteLine(string.Format("{0} - Need to restart as administrator. \nPress 'Enter' to continue...", ex.Message)); Console.Read(); RestartAsAdmin(); } } static void RestartAsAdmin() { var startInfo = new ProcessStartInfo("HttpTest.exe") { Verb = "runas" }; Process.Start(startInfo); Environment.Exit(0); } // Respond to the user with their query string in readable format public static string SendResponse(HttpListenerRequest request) { StringBuilder builder = new StringBuilder(); string color = string.Empty; foreach(var key in request.QueryString.AllKeys) { builder.Append(string.Format("
Key: {0} - Value: {1}", key, request.QueryString.Get(key))); } // Return a random color so the board will toggle the appropriate LED int random = new Random().Next(0, 2); if(random > 0) { color = "blue"; } else { color = "green"; } Console.WriteLine(string.Format("Web server is telling the board to turn on the {0} light.", color)); return string.Format("Query string:{0}
{1}", builder.ToString(), color); } } } ================================================ FILE: Zelig/Zelig/Test/Desktop/Net/HttpTest/Properties/AssemblyInfo.cs ================================================ using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; // General Information about an assembly is controlled through the following // set of attributes. Change these attribute values to modify the information // associated with an assembly. [assembly: AssemblyTitle("HttpTest")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("HttpTest")] [assembly: AssemblyCopyright("Copyright © 2016")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible(false)] // The following GUID is for the ID of the typelib if this project is exposed to COM [assembly: Guid("0f0dc8c5-349b-453d-94f2-123205e3eadd")] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Build and Revision Numbers // by using the '*' as shown below: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("1.0.0.0")] [assembly: AssemblyFileVersion("1.0.0.0")] ================================================ FILE: Zelig/Zelig/Test/Desktop/Net/NetworkTest/App.config ================================================  ================================================ FILE: Zelig/Zelig/Test/Desktop/Net/NetworkTest/NetworkTest.csproj ================================================  Debug AnyCPU {769F9326-B779-4F35-BC49-87E15CDF2A8C} Exe Properties NetworkTest NetworkTest v4.5.2 512 true AnyCPU true full false ..\..\..\..\..\ZeligBuild\Host\bin\Debug\ DEBUG;TRACE prompt 4 AnyCPU pdbonly true ..\..\..\..\..\ZeligBuild\Host\bin\Release\ TRACE prompt 4 ================================================ FILE: Zelig/Zelig/Test/Desktop/Net/NetworkTest/Program.cs ================================================  // // Copyright (c) Microsoft Corporation. All rights reserved. // namespace Microsoft.Zelig.Test { using System; using System.Collections.Generic; using System.Net; using System.Net.Sockets; using System.Text; using System.Threading; using System.Threading.Tasks; public class SynchronousSocketListener { internal class StringsBuffer { // Incoming data from the client. private List m_data; internal StringsBuffer( ) { m_data = new List( ); } internal void Add( string s ) { m_data.Add( s ); } internal List Data { get { return m_data; } } } //--// internal static int StartListening( StringsBuffer data ) { // // Establish the local endpoint for the socket. // IPHostEntry ipHostInfo = Dns.GetHostEntry(Dns.GetHostName()); // // Pick 1st IPv4 address in the list. // IPAddress ipv4Local = null; foreach(var addr in ipHostInfo.AddressList) { if(addr.AddressFamily == AddressFamily.InterNetwork) { ipv4Local = addr; break; } } // // Create a TCP/IP socket. // Socket listener = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); // Bind the socket to the local endpoint and // listen for incoming connections. int bytesReceived = 0; try { var localEndPoint = new IPEndPoint( ipv4Local, 11000); listener.Bind( localEndPoint ); listener.Listen( 10 ); Socket handler = null; StringBuilder builder = new StringBuilder(); // // Start listening for connections. // int connection = 1; while(true) { Console.BackgroundColor = ConsoleColor.Black; Console.ForegroundColor = NextColor; Console.Write( String.Format( "Waiting on {0} for connection #{1}... ", localEndPoint.ToString( ), connection++ ) ); handler = listener.Accept( ); Console.Write( String.Format( "Connected to {0}\r\n", handler.LocalEndPoint.ToString( ) ) ); //Task.Run( new Action( delegate //{ try { handler.ReceiveTimeout = 120 * 1 * 1000; // ten seconds timeout int count = 0; var buffer = new byte[ 1024 ]; // An incoming connection needs to be processed. while(true) { ++count; Console.Write( String.Format( "Performing read #{0:D4} from '{1}'. Bytes Received so far: {2:D8}\r", count, handler.RemoteEndPoint.ToString( ), bytesReceived ) ); int bytesRead = handler.Receive(buffer); bytesReceived += bytesRead; var moreData = Encoding.ASCII.GetString( buffer, 0, bytesRead ); builder.Append( moreData ); string finalString = builder.ToString(); // Ensure we got the return char terminated request if(finalString.IndexOf( "\n" ) != -1) { builder.Clear( ); data.Add( finalString ); } // // Echo data back // handler.Send( buffer, 0, bytesRead, SocketFlags.None ); if(finalString.IndexOf( "TEST_COMPLETED" ) != -1) { Console.Write( String.Format( "Performing read #{0:D4} from '{1}'. Bytes Received so far: {2:D8}\r\n", count, handler.RemoteEndPoint.ToString( ), bytesReceived ) ); break; } } } catch(Exception ex) { Console.WriteLine( "" ); Console.WriteLine( String.Format( "EXCEPTION CAUGHT on {0}", handler.RemoteEndPoint.ToString( ) ) ); Console.WriteLine( ex.StackTrace ); } finally { handler.Close( ); } //} ) //); } } catch(Exception e) { Console.WriteLine( e.ToString( ) ); } Console.WriteLine( "\nPress ENTER to continue..." ); Console.Read( ); return bytesReceived; } //--// static readonly ConsoleColor[] s_colors = new ConsoleColor[] { ConsoleColor.White, ConsoleColor.Green, ConsoleColor.Yellow, ConsoleColor.Cyan }; static int s_currentColorIndex = -1; public static ConsoleColor NextColor { get { return s_colors[ Interlocked.Increment( ref s_currentColorIndex ) % s_colors.Length ]; } } //--// public static int Main( String[] args ) { var allData = new StringsBuffer(); return StartListening( allData ); } } } ================================================ FILE: Zelig/Zelig/Test/Desktop/Net/NetworkTest/Properties/AssemblyInfo.cs ================================================ using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; // General Information about an assembly is controlled through the following // set of attributes. Change these attribute values to modify the information // associated with an assembly. [assembly: AssemblyTitle( "NetworkTest" )] [assembly: AssemblyDescription( "" )] [assembly: AssemblyConfiguration( "" )] [assembly: AssemblyCompany( "Microsoft IT" )] [assembly: AssemblyProduct( "NetworkTest" )] [assembly: AssemblyCopyright( "Copyright © Microsoft IT 2015" )] [assembly: AssemblyTrademark( "" )] [assembly: AssemblyCulture( "" )] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible( false )] // The following GUID is for the ID of the typelib if this project is exposed to COM [assembly: Guid( "769f9326-b779-4f35-bc49-87e15cdf2a8c" )] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Build and Revision Numbers // by using the '*' as shown below: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion( "1.0.0.0" )] [assembly: AssemblyFileVersion( "1.0.0.0" )] ================================================ FILE: Zelig/Zelig/Test/HardwareTests/Gpio/GpioTest.csproj ================================================  Debug AnyCPU {1AE58C3F-0319-4B7E-9E48-7A7BEBC2E3A5} Exe Properties Microsoft.Zelig.Test.GpioTest Microsoft.Zelig.Test.GpioTest v4.5 512 AnyCPU true full false $(LlilumBuildRoot)\Target\obj\$(MSBuildProjectName)\$(Configuration)\ $(LlilumBuildRoot)\Target\bin\$(Configuration)\ DEBUG;TRACE prompt 4 true AnyCPU pdbonly true $(LlilumBuildRoot)\Target\bin\$(Configuration)\ $(LlilumBuildRoot)\Target\obj\$(MSBuildProjectName)\$(Configuration)\ TRACE prompt 4 {1705887b-e636-4fa3-ae40-2d431af1511c} K64F {cee4d575-4b4b-42b0-b2f1-cc7198cb7306} LPC1768 {d7f2bc4e-1406-47aa-90e1-07bc4ce9410f} mbed {d68ee51b-a898-4a77-97d8-c61254cac122} Microsoft.Llilum.Devices {186f31a3-ef89-4a25-b2d5-20070702aa01} system {186f31a3-ef89-4a25-b2d5-20060509aa01} Kernel ================================================ FILE: Zelig/Zelig/Test/HardwareTests/Gpio/Program.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // #define LPC1768 //#define K64F namespace Microsoft.Zelig.Test.GpioTest { using System; using System.Threading; using Llilum.Devices.Gpio; #if (LPC1768) using LPC1768 = Llilum.LPC1768; #elif ( K64F ) using K64F = Llilum.K64F; #else #error No target board defined. #endif //--// class Program { internal class GpioInterruptTestData : IDisposable { private readonly AutoResetEvent m_evtComplete; private readonly GpioPin m_pinLED; private readonly GpioPin m_pinIn; private readonly GpioPin m_pinOut; private readonly GpioPin m_pinMon; private int m_pinVal; private bool m_disposed; public GpioInterruptTestData(int LedPinNumber, int InPinNumber, int OutPinNumber, int MonitorPin) { m_evtComplete = new AutoResetEvent(false); m_pinVal = 1; m_pinLED = GpioPin.TryCreateGpioPin(LedPinNumber); m_pinLED.Direction = PinDirection.Output; m_pinLED.Write(0); m_pinOut = GpioPin.TryCreateGpioPin(OutPinNumber); m_pinOut.Direction = PinDirection.Output; m_pinOut.Write(0); m_pinMon = GpioPin.TryCreateGpioPin(MonitorPin); m_pinMon.Direction = PinDirection.Output; m_pinMon.Write(0); m_pinIn = GpioPin.TryCreateGpioPin( InPinNumber ); m_pinIn.Direction = PinDirection.Input; } public GpioPin PinLED => m_pinLED; public GpioPin PinIn => m_pinIn; public GpioPin PinOut => m_pinOut; public GpioPin PinMon => m_pinMon; public void TogglePinValue() { m_pinLED.Write(m_pinVal); m_pinVal = m_pinVal == 1 ? 0 : 1; } public void SignalComplete() { m_evtComplete.Set(); } public void WaitComplete(int timeout) { m_evtComplete.WaitOne(timeout, false); } ~GpioInterruptTestData() { Dispose(false); } public void Dispose() { if (!m_disposed) { Dispose(true); GC.SuppressFinalize(this); m_disposed = true; } } protected void Dispose(bool disposing) { if (disposing) { s_GpioInterruptTestData = null; m_pinIn.Dispose(); m_pinLED.Dispose(); m_pinOut.Dispose(); m_pinMon.Dispose(); } } }; public static GpioInterruptTestData s_GpioInterruptTestData; static int[] TEST_GPIO_PINS = { #if (LPC1768) // // LPC1768 only supports interrupts on pins P0_* and P2_* (ports 0 and 2). // P0_0 == p9, p2_0 == p26 // // On the LPC1768, pins p9, p10, p11 and LED1 are used for this tests. Pins p9 // and p10 should be physically connected with a jumper. Pin p11 is used as a // monitor pin which indicates how much time was taken to service the interrupt. // (int)LPC1768.PinName.LED1, (int)LPC1768.PinName.p9, (int)LPC1768.PinName.p10, (int)LPC1768.PinName.p11, #elif (K64F) // // On the Freescale FRDM K64F board, this test requires you to jumper pins // PTC5 and PTC7 together to test GPIO interrupts. Pin PTC0 can be used as // a monitor pin with an oscilloscope to measure the time to service a GPIO // interrupt from creation to event handling. // (int)K64F.PinName.LED1, (int)K64F.PinName.PTC7, (int)K64F.PinName.PTC5, (int)K64F.PinName.PTC0, #else #error No target board defined. #endif }; static void Main( ) { while(true) { if (!TestGpioInterrupts()) { Console.WriteLine( "TestGpioInterrupts FAILED!" ); break; } // Sleep 1 second between test runs Thread.Sleep( 1000 ); } } static bool TestGpioInterrupts() { bool result = true; using(s_GpioInterruptTestData = new GpioInterruptTestData( TEST_GPIO_PINS[ 0 ], TEST_GPIO_PINS[ 1 ], TEST_GPIO_PINS[ 2 ], TEST_GPIO_PINS[ 3 ] )) { s_GpioInterruptTestData.PinIn.ValueChanged += HandlePinValueChanged; try { s_GpioInterruptTestData.PinMon.Write( 1 ); s_GpioInterruptTestData.PinOut.Write( 1 ); s_GpioInterruptTestData.WaitComplete( 1000 ); s_GpioInterruptTestData.PinOut.Write( 0 ); } catch(TimeoutException) { result = false; } s_GpioInterruptTestData.PinIn.ValueChanged -= HandlePinValueChanged; } return result; } private static void HandlePinValueChanged(object sender, PinEdge edge) { if (s_GpioInterruptTestData != null) { s_GpioInterruptTestData.PinMon.Write(0); s_GpioInterruptTestData.TogglePinValue(); s_GpioInterruptTestData.SignalComplete(); } } } } ================================================ FILE: Zelig/Zelig/Test/HardwareTests/Gpio/ReadMe.txt ================================================ The GpioTest project contains hardware tests related to GPIOs. GPIO tests: 1. GPIO Interrupt Handling Latency This test enables the user to measuring GPIO interrupt handling latency. The test uses 4 GPIO pins (including one LED). The pins are labeled in the test class GpioInterruptTestData as PinLED, PinIn, PinOut, PinMon. PinIn and PinOut must be physically connected with a jumper. PinOut will drive the interrupt for PinIn. PinMon is another output pin that is used to monitor the time between setting PinOut and receiving the interrupt for PinIn. An oscilloscope can be connected to PinMon to roughly determine the time it takes to service a GPIO interrupt. The PinLED pin is just used as a toggle for each iteration of the GPIO interrupt test. The following shows the pin map for both the LPC1768 and the FRDM K64F boards: a. LPC1768 PinLED = LPC1768.PinName.LED1 PinIn = LPC1768.PinName.p9 PinOut = LPC1768.PinName.p10 PinMon = LPC1768.PinName.p11 b. FRDM K64F PinLED = K64F.PinName.LED1 PinIn = K64F.PinName.PTC7 (J1 Pin15) PinOut = K64F.PinName.PTC5 (J1 Pin13) PinMon = K64F.PinName.PTC0 (J1 Pin11) ================================================ FILE: Zelig/Zelig/Test/HardwareTests/SerialPort/Program.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // #define LPC1768 //#define K64F namespace Microsoft.Zelig.Test.SerialPortTest { using System; using System.IO.Ports; using System.Threading; //--// class Program { private static byte[] s_txtBuffer = new byte[32]; private static byte s_curByte = 0; static void Main( ) { while(true) { if (!TestSerialPortLoopBack()) { Console.WriteLine( "TestSerialPortLoopBack failed!" ); break; } // Sleep 1 second between test runs Thread.Sleep( 1000 ); } } static bool TestSerialPortLoopBack() { string serialPortName; bool result = true; #if (LPC1768) serialPortName = "UART1"; #elif (K64F) serialPortName = "UART3"; #else throw new NotSupportedException(); #endif using (SerialPort port = new SerialPort(serialPortName, 115200, Parity.None, 8, StopBits.One)) { port.Open(); result = TestLoopback( port, ref s_txtBuffer ); } return result; } // // This test requires the RX/TX pins to be connected for hardware loop-back. // For LPC1768, connect pins p13 and p14. // For FRDM K64F, connect pins PTC17 and PTC16. // private static bool TestLoopback( SerialPort port, ref byte[] txtBuffer ) { byte b = s_curByte; bool result = true; int len = txtBuffer.Length; // // Fill TX buffer with incrementing pattern // for(int i = 0; i Debug AnyCPU {91FF2862-C6E5-45BB-B399-8E363E40361C} Exe Properties Microsoft.Zelig.Test.SerialPortTest Microsoft.Zelig.Test.SerialPortTest v4.5 512 AnyCPU true full false $(LlilumBuildRoot)\Target\obj\$(MSBuildProjectName)\$(Configuration)\ $(LlilumBuildRoot)\Target\bin\$(Configuration)\ DEBUG;TRACE prompt 4 true AnyCPU pdbonly true $(LlilumBuildRoot)\Target\bin\$(Configuration)\ $(LlilumBuildRoot)\Target\obj\$(MSBuildProjectName)\$(Configuration)\ TRACE prompt 4 {1705887b-e636-4fa3-ae40-2d431af1511c} K64F {cee4d575-4b4b-42b0-b2f1-cc7198cb7306} LPC1768 {d7f2bc4e-1406-47aa-90e1-07bc4ce9410f} mbed {d68ee51b-a898-4a77-97d8-c61254cac122} Microsoft.Llilum.Devices {186f31a3-ef89-4a25-b2d5-20070702aa01} system {186f31a3-ef89-4a25-b2d5-20060509aa01} Kernel ================================================ FILE: Zelig/Zelig/Test/LlilumTests.sln ================================================ Microsoft Visual Studio Solution File, Format Version 12.00 # Visual Studio 14 VisualStudioVersion = 14.0.23107.0 MinimumVisualStudioVersion = 10.0.40219.1 Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "MetaData", "MetaData", "{7F3A2DA3-7D2A-4F59-AEE2-3DBF75C80FFE}" EndProject Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "CodeGenerator", "CodeGenerator", "{6956D60A-260F-4B83-ABC6-EDABC5E17C84}" EndProject Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "AnalysisTools", "AnalysisTools", "{B005F882-B6AB-4CEA-9434-8BFF1876686B}" EndProject Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "DeviceModels", "DeviceModels", "{A1D7BA88-298C-440A-B626-E061EDCE4045}" EndProject Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "CompileTime", "CompileTime", "{AEF34496-481F-47EC-B246-92F7E87339C0}" EndProject Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "DebugTime", "DebugTime", "{B2AEC590-045A-4623-8DFD-357A5B54C424}" EndProject Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "RunTime", "RunTime", "{993EE84F-7CEA-40E0-BE5C-B1F38D1BA562}" EndProject Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "Framework", "Framework", "{AA94AD05-A42A-4190-8585-A82439976872}" EndProject Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "Zelig", "Zelig", "{5354D2AA-713A-4F47-BE76-2CCC57DE6EC4}" EndProject Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "TargetModels", "TargetModels", "{DC90A338-0E12-4668-8FFF-2A0BDEBC3597}" EndProject Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Importer", "..\CompileTime\MetaData\Importer\Importer.csproj", "{186F31A3-EF89-4A25-B2D5-20060404AA01}" EndProject Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "mscorlib", "..\RunTime\Framework\mscorlib\mscorlib.csproj", "{186F31A3-EF89-4A25-B2D5-20060501AA01}" EndProject Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "mscorlib_UnitTest", "..\RunTime\Framework\mscorlib_UnitTest\mscorlib_UnitTest.csproj", "{186F31A3-EF89-4A25-B2D5-20060509AA02}" EndProject Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Kernel", "..\RunTime\Zelig\Kernel\Kernel.csproj", "{186F31A3-EF89-4A25-B2D5-20060509AA01}" EndProject Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Normalized", "..\CompileTime\MetaData\Normalized\Normalized.csproj", "{186F31A3-EF89-4A25-B2D5-20060510AA01}" EndProject Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "IntermediateRepresentation", "..\CompileTime\CodeGenerator\IntermediateRepresentation\IntermediateRepresentation.csproj", "{186F31A3-EF89-4A25-B2D5-20060603AA01}" EndProject Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "CodeGenerator.UnitTest", "..\CompileTime\CodeGenerator\CodeGenerator.UnitTest\CodeGenerator.UnitTest.csproj", "{186F31A3-EF89-4A25-B2D5-20060606AA01}" EndProject Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "ArmProcessorEmulation", "..\DebugTime\ArmProcessorEmulation\ArmProcessorEmulation.csproj", "{186F31A3-EF89-4A25-B2D5-20060704AA01}" EndProject Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "TypeSystem", "..\RunTime\Zelig\TypeSystem\TypeSystem.csproj", "{186F31A3-EF89-4A25-B2D5-20060720AA01}" EndProject Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Common", "..\RunTime\Zelig\Common\Common.csproj", "{186F31A3-EF89-4A25-B2D5-20061218AA01}" EndProject Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "IRCompare", "..\CompileTime\AnalysisTools\IRCompare\IRCompare.csproj", "{186F31A3-EF89-4A25-B2D5-20070211AA01}" EndProject Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "CodeTransformation", "..\CompileTime\CodeGenerator\CodeTransformation\CodeTransformation.csproj", "{186F31A3-EF89-4A25-B2D5-20070222AA01}" EndProject Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Debugger", "..\DebugTime\Debugger\Debugger.csproj", "{186F31A3-EF89-4A25-B2D5-20070430AA01}" EndProject Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "ArmProcessor", "..\CompileTime\TargetModels\ArmProcessor\ArmProcessor.csproj", "{186F31A3-EF89-4A25-B2D5-20070519AA01}" EndProject Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "CommonPC", "..\RunTime\Zelig\CommonPC\CommonPC.csproj", "{186F31A3-EF89-4A25-B2D5-20070601AA01}" EndProject Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "FrontEnd", "..\CompileTime\CodeGenerator\FrontEnd\FrontEnd.csproj", "{186F31A3-EF89-4A25-B2D5-20070605AA02}" EndProject Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "ProductConfiguration", "..\CompileTime\TargetModels\ProductConfiguration\ProductConfiguration.csproj", "{186F31A3-EF89-4A25-B2D5-20070606AA01}" EndProject Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "system", "..\RunTime\Framework\system\system.csproj", "{186F31A3-EF89-4A25-B2D5-20070702AA01}" EndProject Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "InequalityGraphVisualization", "..\CompileTime\AnalysisTools\InequalityGraphVisualization\InequalityGraphVisualization.csproj", "{96BF0234-1D60-4401-A6B9-99839187234E}" EndProject Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "system_core", "..\RunTime\Framework\System_Core\system_core.csproj", "{186F31A3-EF89-4A25-B2D5-20080628AA01}" EndProject Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "TestMethodGen", "..\RunTime\DeviceModels\TestMethodGen\TestMethodGen.csproj", "{B7606EF5-A5EC-4A97-AB4A-35D00EFA2925}" EndProject Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "Test", "Test", "{3E953D4D-61BB-48CA-B996-90A5736BFA58}" EndProject Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "mbed", "mbed", "{79F07A26-A95A-45AB-B6B6-325A63AF1065}" EndProject Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "simple", "mbed\simple\simple.csproj", "{77D71AF4-11C3-409B-A211-51FA19E5C1AA}" EndProject Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "LibLLVM", "..\CompileTime\Llvm.NET\LibLLVM\LibLLVM.vcxproj", "{6C77A7DE-D464-430F-96A9-A64768763B5F}" EndProject Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Llvm.NET", "..\CompileTime\Llvm.NET\Llvm.NET\Llvm.NET.csproj", "{0162C8CE-6641-4922-8664-F8A44356FBF7}" EndProject Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "mbed", "..\RunTime\DeviceModels\mbed\mbed.csproj", "{D7F2BC4E-1406-47AA-90E1-07BC4CE9410F}" EndProject Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "CortexM", "CortexM", "{7FC1F0E6-A46C-4A0C-AA6F-233EEFEB33D3}" EndProject Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "Support", "Support", "{8988313A-FAC7-4CF9-B373-C4034FC01EFA}" EndProject Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "NativeHelpers", "mbed\NativeHelpers\NativeHelpers.vcxproj", "{6367CACE-0511-485D-9AE5-698F7E600839}" EndProject Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "Boards", "Boards", "{EE8431BB-2720-4F75-AD08-1E3307F68BE4}" EndProject Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "CompileTime", "CompileTime", "{DFC4F889-3803-4B12-B792-30504AD8C85A}" EndProject Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "System.Runtime.WindowsRuntime", "..\RunTime\Framework\System.Runtime.WindowsRuntime\System.Runtime.WindowsRuntime.csproj", "{016691CA-A31F-4273-A4D2-C5F6E4B3662D}" EndProject Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "SimpleTestProgram", "mbed\SimpleSDK\Managed\SimpleTestProgram.csproj", "{6C581F6A-34F8-4380-9BE0-279F709D13CB}" EndProject Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "Native", "mbed\SimpleSDK\Native\Native.vcxproj", "{D3FA04AF-4285-477D-A756-6C51E9A56E7A}" EndProject Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "SDK", "SDK", "{35A43865-50F4-423A-ACF6-B3AEC2511716}" EndProject Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "make", "make", "{F5824561-14E4-4E5E-83A4-CFE95F128829}" EndProject Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "M3", "M3", "{CF168235-325F-448A-B455-3382C2B9DA48}" EndProject Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "M4", "M4", "{CF4FC546-608D-4BE4-8A67-1E8C9F3526A3}" EndProject Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "CortexM3OnCMSIS-Core", "..\RunTime\DeviceModels\CortexM3OnCMSIS-Core\CortexM3OnCMSIS-Core.csproj", "{0B37E5BA-4839-4EC4-9E36-A96BCBEA2400}" EndProject Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "CortexM3OnMBED", "..\RunTime\DeviceModels\CortexM3OnMBED\CortexM3OnMBED.csproj", "{0C522C6A-0F77-4AF8-AD78-5B2415C98C51}" EndProject Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "ModelForCortexM3", "..\RunTime\DeviceModels\ModelForCortexM3\ModelForCortexM3.csproj", "{A30EB003-94F8-4A85-8DA1-006F6810A7A4}" EndProject Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "CortexM4OnCMSIS-Core", "..\RunTime\DeviceModels\CortexM4OnCMSIS-Core\CortexM4OnCMSIS-Core.csproj", "{7FB3F581-742D-4E12-A36A-BE172C574AB0}" EndProject Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "CortexM4OnMBED", "..\RunTime\DeviceModels\CortexM4OnMBED\CortexM4OnMBED.csproj", "{65C8EDA6-AC24-4E18-A5B5-216E0F2C3906}" EndProject Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "ModelForCortexM4", "..\RunTime\DeviceModels\ModelForCortexM4\ModelForCortexM4.csproj", "{CA8A6D38-528B-4FAA-89B6-8FA9178DE55D}" EndProject Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Microsoft.Llilum.Devices", "..\RunTime\Framework\Llilum\Devices\Microsoft.Llilum.Devices.csproj", "{D68EE51B-A898-4A77-97D8-C61254CAC122}" EndProject Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "Hardware", "Hardware", "{8323ECD0-B5EF-4885-9421-EB05DCB32884}" EndProject Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "GpioTest", "HardwareTests\Gpio\GpioTest.csproj", "{1AE58C3F-0319-4B7E-9E48-7A7BEBC2E3A5}" EndProject Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "SerialPortTest", "HardwareTests\SerialPort\SerialPortTest.csproj", "{91FF2862-C6E5-45BB-B399-8E363E40361C}" EndProject Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "K64F", "..\..\BoardConfigurations\K64F\Board\K64F.csproj", "{1705887B-E636-4FA3-AE40-2D431AF1511C}" EndProject Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "LPC1768", "..\..\BoardConfigurations\LPC1768\Board\LPC1768.csproj", "{CEE4D575-4B4B-42B0-B2F1-CC7198CB7306}" EndProject Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Windows", "..\RunTime\Framework\Windows\Windows.csproj", "{DC8C38D7-780B-4B13-8ACE-9050E39CC51C}" EndProject Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "K64FConfiguration", "..\..\BoardConfigurations\K64F\Configuration\K64FConfiguration.csproj", "{9863D039-AB21-4710-960E-7303919552C6}" EndProject Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "LPC1768Configuration", "..\..\BoardConfigurations\LPC1768\Configuration\LPC1768Configuration.csproj", "{C17E59D0-2D64-4012-8A98-D184D0CF8A49}" EndProject Global GlobalSection(SolutionConfigurationPlatforms) = preSolution Debug|Any CPU = Debug|Any CPU Debug|ARM = Debug|ARM Debug|Mixed Platforms = Debug|Mixed Platforms Debug|Win32 = Debug|Win32 Debug|x64 = Debug|x64 Instrumentation|Any CPU = Instrumentation|Any CPU Instrumentation|ARM = Instrumentation|ARM Instrumentation|Mixed Platforms = Instrumentation|Mixed Platforms Instrumentation|Win32 = Instrumentation|Win32 Instrumentation|x64 = Instrumentation|x64 Release|Any CPU = Release|Any CPU Release|ARM = Release|ARM Release|Mixed Platforms = Release|Mixed Platforms Release|Win32 = Release|Win32 Release|x64 = Release|x64 EndGlobalSection GlobalSection(ProjectConfigurationPlatforms) = postSolution {186F31A3-EF89-4A25-B2D5-20060404AA01}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {186F31A3-EF89-4A25-B2D5-20060404AA01}.Debug|Any CPU.Build.0 = Debug|Any CPU {186F31A3-EF89-4A25-B2D5-20060404AA01}.Debug|ARM.ActiveCfg = Debug|Any CPU {186F31A3-EF89-4A25-B2D5-20060404AA01}.Debug|ARM.Build.0 = Debug|Any CPU {186F31A3-EF89-4A25-B2D5-20060404AA01}.Debug|Mixed Platforms.ActiveCfg = Debug|Any CPU {186F31A3-EF89-4A25-B2D5-20060404AA01}.Debug|Mixed Platforms.Build.0 = Debug|Any CPU {186F31A3-EF89-4A25-B2D5-20060404AA01}.Debug|Win32.ActiveCfg = Debug|Any CPU {186F31A3-EF89-4A25-B2D5-20060404AA01}.Debug|Win32.Build.0 = Debug|Any CPU {186F31A3-EF89-4A25-B2D5-20060404AA01}.Debug|x64.ActiveCfg = Debug|Any CPU {186F31A3-EF89-4A25-B2D5-20060404AA01}.Debug|x64.Build.0 = Debug|Any CPU {186F31A3-EF89-4A25-B2D5-20060404AA01}.Instrumentation|Any CPU.ActiveCfg = Instrumentation|Any CPU {186F31A3-EF89-4A25-B2D5-20060404AA01}.Instrumentation|Any CPU.Build.0 = Instrumentation|Any CPU {186F31A3-EF89-4A25-B2D5-20060404AA01}.Instrumentation|ARM.ActiveCfg = Instrumentation|Any CPU {186F31A3-EF89-4A25-B2D5-20060404AA01}.Instrumentation|ARM.Build.0 = Instrumentation|Any CPU {186F31A3-EF89-4A25-B2D5-20060404AA01}.Instrumentation|Mixed Platforms.ActiveCfg = Instrumentation|Any CPU {186F31A3-EF89-4A25-B2D5-20060404AA01}.Instrumentation|Mixed Platforms.Build.0 = Instrumentation|Any CPU {186F31A3-EF89-4A25-B2D5-20060404AA01}.Instrumentation|Win32.ActiveCfg = Instrumentation|Any CPU {186F31A3-EF89-4A25-B2D5-20060404AA01}.Instrumentation|Win32.Build.0 = Instrumentation|Any CPU {186F31A3-EF89-4A25-B2D5-20060404AA01}.Instrumentation|x64.ActiveCfg = Instrumentation|Any CPU {186F31A3-EF89-4A25-B2D5-20060404AA01}.Instrumentation|x64.Build.0 = Instrumentation|Any CPU {186F31A3-EF89-4A25-B2D5-20060404AA01}.Release|Any CPU.ActiveCfg = Release|Any CPU {186F31A3-EF89-4A25-B2D5-20060404AA01}.Release|Any CPU.Build.0 = Release|Any CPU {186F31A3-EF89-4A25-B2D5-20060404AA01}.Release|ARM.ActiveCfg = Release|Any CPU {186F31A3-EF89-4A25-B2D5-20060404AA01}.Release|ARM.Build.0 = Release|Any CPU {186F31A3-EF89-4A25-B2D5-20060404AA01}.Release|Mixed Platforms.ActiveCfg = Release|Any CPU {186F31A3-EF89-4A25-B2D5-20060404AA01}.Release|Mixed Platforms.Build.0 = Release|Any CPU {186F31A3-EF89-4A25-B2D5-20060404AA01}.Release|Win32.ActiveCfg = Release|Any CPU {186F31A3-EF89-4A25-B2D5-20060404AA01}.Release|Win32.Build.0 = Release|Any CPU {186F31A3-EF89-4A25-B2D5-20060404AA01}.Release|x64.ActiveCfg = Release|Any CPU {186F31A3-EF89-4A25-B2D5-20060404AA01}.Release|x64.Build.0 = Release|Any CPU {186F31A3-EF89-4A25-B2D5-20060501AA01}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {186F31A3-EF89-4A25-B2D5-20060501AA01}.Debug|Any CPU.Build.0 = Debug|Any CPU {186F31A3-EF89-4A25-B2D5-20060501AA01}.Debug|ARM.ActiveCfg = Debug|Any CPU {186F31A3-EF89-4A25-B2D5-20060501AA01}.Debug|ARM.Build.0 = Debug|Any CPU {186F31A3-EF89-4A25-B2D5-20060501AA01}.Debug|Mixed Platforms.ActiveCfg = Debug|Any CPU {186F31A3-EF89-4A25-B2D5-20060501AA01}.Debug|Mixed Platforms.Build.0 = Debug|Any CPU {186F31A3-EF89-4A25-B2D5-20060501AA01}.Debug|Win32.ActiveCfg = Debug|Any CPU {186F31A3-EF89-4A25-B2D5-20060501AA01}.Debug|Win32.Build.0 = Debug|Any CPU {186F31A3-EF89-4A25-B2D5-20060501AA01}.Debug|x64.ActiveCfg = Debug|Any CPU {186F31A3-EF89-4A25-B2D5-20060501AA01}.Debug|x64.Build.0 = Debug|Any CPU {186F31A3-EF89-4A25-B2D5-20060501AA01}.Instrumentation|Any CPU.ActiveCfg = Instrumentation|Any CPU {186F31A3-EF89-4A25-B2D5-20060501AA01}.Instrumentation|Any CPU.Build.0 = Instrumentation|Any CPU {186F31A3-EF89-4A25-B2D5-20060501AA01}.Instrumentation|ARM.ActiveCfg = Instrumentation|Any CPU {186F31A3-EF89-4A25-B2D5-20060501AA01}.Instrumentation|ARM.Build.0 = Instrumentation|Any CPU {186F31A3-EF89-4A25-B2D5-20060501AA01}.Instrumentation|Mixed Platforms.ActiveCfg = Instrumentation|Any CPU {186F31A3-EF89-4A25-B2D5-20060501AA01}.Instrumentation|Mixed Platforms.Build.0 = Instrumentation|Any CPU {186F31A3-EF89-4A25-B2D5-20060501AA01}.Instrumentation|Win32.ActiveCfg = Instrumentation|Any CPU {186F31A3-EF89-4A25-B2D5-20060501AA01}.Instrumentation|Win32.Build.0 = Instrumentation|Any CPU {186F31A3-EF89-4A25-B2D5-20060501AA01}.Instrumentation|x64.ActiveCfg = Instrumentation|Any CPU {186F31A3-EF89-4A25-B2D5-20060501AA01}.Instrumentation|x64.Build.0 = Instrumentation|Any CPU {186F31A3-EF89-4A25-B2D5-20060501AA01}.Release|Any CPU.ActiveCfg = Release|Any CPU {186F31A3-EF89-4A25-B2D5-20060501AA01}.Release|Any CPU.Build.0 = Release|Any CPU {186F31A3-EF89-4A25-B2D5-20060501AA01}.Release|ARM.ActiveCfg = Release|Any CPU {186F31A3-EF89-4A25-B2D5-20060501AA01}.Release|ARM.Build.0 = Release|Any CPU {186F31A3-EF89-4A25-B2D5-20060501AA01}.Release|Mixed Platforms.ActiveCfg = Release|Any CPU {186F31A3-EF89-4A25-B2D5-20060501AA01}.Release|Mixed Platforms.Build.0 = Release|Any CPU {186F31A3-EF89-4A25-B2D5-20060501AA01}.Release|Win32.ActiveCfg = Release|Any CPU {186F31A3-EF89-4A25-B2D5-20060501AA01}.Release|Win32.Build.0 = Release|Any CPU {186F31A3-EF89-4A25-B2D5-20060501AA01}.Release|x64.ActiveCfg = Release|Any CPU {186F31A3-EF89-4A25-B2D5-20060501AA01}.Release|x64.Build.0 = Release|Any CPU {186F31A3-EF89-4A25-B2D5-20060509AA02}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {186F31A3-EF89-4A25-B2D5-20060509AA02}.Debug|Any CPU.Build.0 = Debug|Any CPU {186F31A3-EF89-4A25-B2D5-20060509AA02}.Debug|ARM.ActiveCfg = Debug|Any CPU {186F31A3-EF89-4A25-B2D5-20060509AA02}.Debug|ARM.Build.0 = Debug|Any CPU {186F31A3-EF89-4A25-B2D5-20060509AA02}.Debug|Mixed Platforms.ActiveCfg = Debug|Any CPU {186F31A3-EF89-4A25-B2D5-20060509AA02}.Debug|Mixed Platforms.Build.0 = Debug|Any CPU {186F31A3-EF89-4A25-B2D5-20060509AA02}.Debug|Win32.ActiveCfg = Debug|Any CPU {186F31A3-EF89-4A25-B2D5-20060509AA02}.Debug|Win32.Build.0 = Debug|Any CPU {186F31A3-EF89-4A25-B2D5-20060509AA02}.Debug|x64.ActiveCfg = Debug|Any CPU {186F31A3-EF89-4A25-B2D5-20060509AA02}.Debug|x64.Build.0 = Debug|Any CPU {186F31A3-EF89-4A25-B2D5-20060509AA02}.Instrumentation|Any CPU.ActiveCfg = Instrumentation|Any CPU {186F31A3-EF89-4A25-B2D5-20060509AA02}.Instrumentation|Any CPU.Build.0 = Instrumentation|Any CPU {186F31A3-EF89-4A25-B2D5-20060509AA02}.Instrumentation|ARM.ActiveCfg = Instrumentation|Any CPU {186F31A3-EF89-4A25-B2D5-20060509AA02}.Instrumentation|ARM.Build.0 = Instrumentation|Any CPU {186F31A3-EF89-4A25-B2D5-20060509AA02}.Instrumentation|Mixed Platforms.ActiveCfg = Instrumentation|Any CPU {186F31A3-EF89-4A25-B2D5-20060509AA02}.Instrumentation|Mixed Platforms.Build.0 = Instrumentation|Any CPU {186F31A3-EF89-4A25-B2D5-20060509AA02}.Instrumentation|Win32.ActiveCfg = Instrumentation|Any CPU {186F31A3-EF89-4A25-B2D5-20060509AA02}.Instrumentation|Win32.Build.0 = Instrumentation|Any CPU {186F31A3-EF89-4A25-B2D5-20060509AA02}.Instrumentation|x64.ActiveCfg = Instrumentation|Any CPU {186F31A3-EF89-4A25-B2D5-20060509AA02}.Instrumentation|x64.Build.0 = Instrumentation|Any CPU {186F31A3-EF89-4A25-B2D5-20060509AA02}.Release|Any CPU.ActiveCfg = Release|Any CPU {186F31A3-EF89-4A25-B2D5-20060509AA02}.Release|Any CPU.Build.0 = Release|Any CPU {186F31A3-EF89-4A25-B2D5-20060509AA02}.Release|ARM.ActiveCfg = Release|Any CPU {186F31A3-EF89-4A25-B2D5-20060509AA02}.Release|ARM.Build.0 = Release|Any CPU {186F31A3-EF89-4A25-B2D5-20060509AA02}.Release|Mixed Platforms.ActiveCfg = Release|Any CPU {186F31A3-EF89-4A25-B2D5-20060509AA02}.Release|Mixed Platforms.Build.0 = Release|Any CPU {186F31A3-EF89-4A25-B2D5-20060509AA02}.Release|Win32.ActiveCfg = Release|Any CPU {186F31A3-EF89-4A25-B2D5-20060509AA02}.Release|Win32.Build.0 = Release|Any CPU {186F31A3-EF89-4A25-B2D5-20060509AA02}.Release|x64.ActiveCfg = Release|Any CPU {186F31A3-EF89-4A25-B2D5-20060509AA02}.Release|x64.Build.0 = Release|Any CPU {186F31A3-EF89-4A25-B2D5-20060509AA01}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {186F31A3-EF89-4A25-B2D5-20060509AA01}.Debug|Any CPU.Build.0 = Debug|Any CPU {186F31A3-EF89-4A25-B2D5-20060509AA01}.Debug|ARM.ActiveCfg = Debug|Any CPU {186F31A3-EF89-4A25-B2D5-20060509AA01}.Debug|ARM.Build.0 = Debug|Any CPU {186F31A3-EF89-4A25-B2D5-20060509AA01}.Debug|Mixed Platforms.ActiveCfg = Debug|Any CPU {186F31A3-EF89-4A25-B2D5-20060509AA01}.Debug|Mixed Platforms.Build.0 = Debug|Any CPU {186F31A3-EF89-4A25-B2D5-20060509AA01}.Debug|Win32.ActiveCfg = Debug|Any CPU {186F31A3-EF89-4A25-B2D5-20060509AA01}.Debug|Win32.Build.0 = Debug|Any CPU {186F31A3-EF89-4A25-B2D5-20060509AA01}.Debug|x64.ActiveCfg = Debug|Any CPU {186F31A3-EF89-4A25-B2D5-20060509AA01}.Debug|x64.Build.0 = Debug|Any CPU {186F31A3-EF89-4A25-B2D5-20060509AA01}.Instrumentation|Any CPU.ActiveCfg = Instrumentation|Any CPU {186F31A3-EF89-4A25-B2D5-20060509AA01}.Instrumentation|Any CPU.Build.0 = Instrumentation|Any CPU {186F31A3-EF89-4A25-B2D5-20060509AA01}.Instrumentation|ARM.ActiveCfg = Instrumentation|Any CPU {186F31A3-EF89-4A25-B2D5-20060509AA01}.Instrumentation|ARM.Build.0 = Instrumentation|Any CPU {186F31A3-EF89-4A25-B2D5-20060509AA01}.Instrumentation|Mixed Platforms.ActiveCfg = Instrumentation|Any CPU {186F31A3-EF89-4A25-B2D5-20060509AA01}.Instrumentation|Mixed Platforms.Build.0 = Instrumentation|Any CPU {186F31A3-EF89-4A25-B2D5-20060509AA01}.Instrumentation|Win32.ActiveCfg = Instrumentation|Any CPU {186F31A3-EF89-4A25-B2D5-20060509AA01}.Instrumentation|Win32.Build.0 = Instrumentation|Any CPU {186F31A3-EF89-4A25-B2D5-20060509AA01}.Instrumentation|x64.ActiveCfg = Instrumentation|Any CPU {186F31A3-EF89-4A25-B2D5-20060509AA01}.Instrumentation|x64.Build.0 = Instrumentation|Any CPU {186F31A3-EF89-4A25-B2D5-20060509AA01}.Release|Any CPU.ActiveCfg = Release|Any CPU {186F31A3-EF89-4A25-B2D5-20060509AA01}.Release|Any CPU.Build.0 = Release|Any CPU {186F31A3-EF89-4A25-B2D5-20060509AA01}.Release|ARM.ActiveCfg = Release|Any CPU {186F31A3-EF89-4A25-B2D5-20060509AA01}.Release|ARM.Build.0 = Release|Any CPU {186F31A3-EF89-4A25-B2D5-20060509AA01}.Release|Mixed Platforms.ActiveCfg = Release|Any CPU {186F31A3-EF89-4A25-B2D5-20060509AA01}.Release|Mixed Platforms.Build.0 = Release|Any CPU {186F31A3-EF89-4A25-B2D5-20060509AA01}.Release|Win32.ActiveCfg = Release|Any CPU {186F31A3-EF89-4A25-B2D5-20060509AA01}.Release|Win32.Build.0 = Release|Any CPU {186F31A3-EF89-4A25-B2D5-20060509AA01}.Release|x64.ActiveCfg = Release|Any CPU {186F31A3-EF89-4A25-B2D5-20060509AA01}.Release|x64.Build.0 = Release|Any CPU {186F31A3-EF89-4A25-B2D5-20060510AA01}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {186F31A3-EF89-4A25-B2D5-20060510AA01}.Debug|Any CPU.Build.0 = Debug|Any CPU {186F31A3-EF89-4A25-B2D5-20060510AA01}.Debug|ARM.ActiveCfg = Debug|Any CPU {186F31A3-EF89-4A25-B2D5-20060510AA01}.Debug|ARM.Build.0 = Debug|Any CPU {186F31A3-EF89-4A25-B2D5-20060510AA01}.Debug|Mixed Platforms.ActiveCfg = Debug|Any CPU {186F31A3-EF89-4A25-B2D5-20060510AA01}.Debug|Mixed Platforms.Build.0 = Debug|Any CPU {186F31A3-EF89-4A25-B2D5-20060510AA01}.Debug|Win32.ActiveCfg = Debug|Any CPU {186F31A3-EF89-4A25-B2D5-20060510AA01}.Debug|Win32.Build.0 = Debug|Any CPU {186F31A3-EF89-4A25-B2D5-20060510AA01}.Debug|x64.ActiveCfg = Debug|Any CPU {186F31A3-EF89-4A25-B2D5-20060510AA01}.Debug|x64.Build.0 = Debug|Any CPU {186F31A3-EF89-4A25-B2D5-20060510AA01}.Instrumentation|Any CPU.ActiveCfg = Instrumentation|Any CPU {186F31A3-EF89-4A25-B2D5-20060510AA01}.Instrumentation|Any CPU.Build.0 = Instrumentation|Any CPU {186F31A3-EF89-4A25-B2D5-20060510AA01}.Instrumentation|ARM.ActiveCfg = Instrumentation|Any CPU {186F31A3-EF89-4A25-B2D5-20060510AA01}.Instrumentation|ARM.Build.0 = Instrumentation|Any CPU {186F31A3-EF89-4A25-B2D5-20060510AA01}.Instrumentation|Mixed Platforms.ActiveCfg = Instrumentation|Any CPU {186F31A3-EF89-4A25-B2D5-20060510AA01}.Instrumentation|Mixed Platforms.Build.0 = Instrumentation|Any CPU {186F31A3-EF89-4A25-B2D5-20060510AA01}.Instrumentation|Win32.ActiveCfg = Instrumentation|Any CPU {186F31A3-EF89-4A25-B2D5-20060510AA01}.Instrumentation|Win32.Build.0 = Instrumentation|Any CPU {186F31A3-EF89-4A25-B2D5-20060510AA01}.Instrumentation|x64.ActiveCfg = Instrumentation|Any CPU {186F31A3-EF89-4A25-B2D5-20060510AA01}.Instrumentation|x64.Build.0 = Instrumentation|Any CPU {186F31A3-EF89-4A25-B2D5-20060510AA01}.Release|Any CPU.ActiveCfg = Release|Any CPU {186F31A3-EF89-4A25-B2D5-20060510AA01}.Release|Any CPU.Build.0 = Release|Any CPU {186F31A3-EF89-4A25-B2D5-20060510AA01}.Release|ARM.ActiveCfg = Release|Any CPU {186F31A3-EF89-4A25-B2D5-20060510AA01}.Release|ARM.Build.0 = Release|Any CPU {186F31A3-EF89-4A25-B2D5-20060510AA01}.Release|Mixed Platforms.ActiveCfg = Release|Any CPU {186F31A3-EF89-4A25-B2D5-20060510AA01}.Release|Mixed Platforms.Build.0 = Release|Any CPU {186F31A3-EF89-4A25-B2D5-20060510AA01}.Release|Win32.ActiveCfg = Release|Any CPU {186F31A3-EF89-4A25-B2D5-20060510AA01}.Release|Win32.Build.0 = Release|Any CPU {186F31A3-EF89-4A25-B2D5-20060510AA01}.Release|x64.ActiveCfg = Release|Any CPU {186F31A3-EF89-4A25-B2D5-20060510AA01}.Release|x64.Build.0 = Release|Any CPU {186F31A3-EF89-4A25-B2D5-20060603AA01}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {186F31A3-EF89-4A25-B2D5-20060603AA01}.Debug|Any CPU.Build.0 = Debug|Any CPU {186F31A3-EF89-4A25-B2D5-20060603AA01}.Debug|ARM.ActiveCfg = Debug|Any CPU {186F31A3-EF89-4A25-B2D5-20060603AA01}.Debug|ARM.Build.0 = Debug|Any CPU {186F31A3-EF89-4A25-B2D5-20060603AA01}.Debug|Mixed Platforms.ActiveCfg = Debug|Any CPU {186F31A3-EF89-4A25-B2D5-20060603AA01}.Debug|Mixed Platforms.Build.0 = Debug|Any CPU {186F31A3-EF89-4A25-B2D5-20060603AA01}.Debug|Win32.ActiveCfg = Debug|Any CPU {186F31A3-EF89-4A25-B2D5-20060603AA01}.Debug|Win32.Build.0 = Debug|Any CPU {186F31A3-EF89-4A25-B2D5-20060603AA01}.Debug|x64.ActiveCfg = Debug|Any CPU {186F31A3-EF89-4A25-B2D5-20060603AA01}.Debug|x64.Build.0 = Debug|Any CPU {186F31A3-EF89-4A25-B2D5-20060603AA01}.Instrumentation|Any CPU.ActiveCfg = Instrumentation|Any CPU {186F31A3-EF89-4A25-B2D5-20060603AA01}.Instrumentation|Any CPU.Build.0 = Instrumentation|Any CPU {186F31A3-EF89-4A25-B2D5-20060603AA01}.Instrumentation|ARM.ActiveCfg = Instrumentation|Any CPU {186F31A3-EF89-4A25-B2D5-20060603AA01}.Instrumentation|ARM.Build.0 = Instrumentation|Any CPU {186F31A3-EF89-4A25-B2D5-20060603AA01}.Instrumentation|Mixed Platforms.ActiveCfg = Instrumentation|Any CPU {186F31A3-EF89-4A25-B2D5-20060603AA01}.Instrumentation|Mixed Platforms.Build.0 = Instrumentation|Any CPU {186F31A3-EF89-4A25-B2D5-20060603AA01}.Instrumentation|Win32.ActiveCfg = Instrumentation|Any CPU {186F31A3-EF89-4A25-B2D5-20060603AA01}.Instrumentation|Win32.Build.0 = Instrumentation|Any CPU {186F31A3-EF89-4A25-B2D5-20060603AA01}.Instrumentation|x64.ActiveCfg = Instrumentation|Any CPU {186F31A3-EF89-4A25-B2D5-20060603AA01}.Instrumentation|x64.Build.0 = Instrumentation|Any CPU {186F31A3-EF89-4A25-B2D5-20060603AA01}.Release|Any CPU.ActiveCfg = Release|Any CPU {186F31A3-EF89-4A25-B2D5-20060603AA01}.Release|Any CPU.Build.0 = Release|Any CPU {186F31A3-EF89-4A25-B2D5-20060603AA01}.Release|ARM.ActiveCfg = Release|Any CPU {186F31A3-EF89-4A25-B2D5-20060603AA01}.Release|ARM.Build.0 = Release|Any CPU {186F31A3-EF89-4A25-B2D5-20060603AA01}.Release|Mixed Platforms.ActiveCfg = Release|Any CPU {186F31A3-EF89-4A25-B2D5-20060603AA01}.Release|Mixed Platforms.Build.0 = Release|Any CPU {186F31A3-EF89-4A25-B2D5-20060603AA01}.Release|Win32.ActiveCfg = Release|Any CPU {186F31A3-EF89-4A25-B2D5-20060603AA01}.Release|Win32.Build.0 = Release|Any CPU {186F31A3-EF89-4A25-B2D5-20060603AA01}.Release|x64.ActiveCfg = Release|Any CPU {186F31A3-EF89-4A25-B2D5-20060603AA01}.Release|x64.Build.0 = Release|Any CPU {186F31A3-EF89-4A25-B2D5-20060606AA01}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {186F31A3-EF89-4A25-B2D5-20060606AA01}.Debug|Any CPU.Build.0 = Debug|Any CPU {186F31A3-EF89-4A25-B2D5-20060606AA01}.Debug|ARM.ActiveCfg = Debug|Any CPU {186F31A3-EF89-4A25-B2D5-20060606AA01}.Debug|ARM.Build.0 = Debug|Any CPU {186F31A3-EF89-4A25-B2D5-20060606AA01}.Debug|Mixed Platforms.ActiveCfg = Debug|Any CPU {186F31A3-EF89-4A25-B2D5-20060606AA01}.Debug|Mixed Platforms.Build.0 = Debug|Any CPU {186F31A3-EF89-4A25-B2D5-20060606AA01}.Debug|Win32.ActiveCfg = Debug|Any CPU {186F31A3-EF89-4A25-B2D5-20060606AA01}.Debug|Win32.Build.0 = Debug|Any CPU {186F31A3-EF89-4A25-B2D5-20060606AA01}.Debug|x64.ActiveCfg = Debug|Any CPU {186F31A3-EF89-4A25-B2D5-20060606AA01}.Debug|x64.Build.0 = Debug|Any CPU {186F31A3-EF89-4A25-B2D5-20060606AA01}.Instrumentation|Any CPU.ActiveCfg = Instrumentation|Any CPU {186F31A3-EF89-4A25-B2D5-20060606AA01}.Instrumentation|Any CPU.Build.0 = Instrumentation|Any CPU {186F31A3-EF89-4A25-B2D5-20060606AA01}.Instrumentation|ARM.ActiveCfg = Instrumentation|Any CPU {186F31A3-EF89-4A25-B2D5-20060606AA01}.Instrumentation|ARM.Build.0 = Instrumentation|Any CPU {186F31A3-EF89-4A25-B2D5-20060606AA01}.Instrumentation|Mixed Platforms.ActiveCfg = Instrumentation|Any CPU {186F31A3-EF89-4A25-B2D5-20060606AA01}.Instrumentation|Mixed Platforms.Build.0 = Instrumentation|Any CPU {186F31A3-EF89-4A25-B2D5-20060606AA01}.Instrumentation|Win32.ActiveCfg = Instrumentation|Any CPU {186F31A3-EF89-4A25-B2D5-20060606AA01}.Instrumentation|Win32.Build.0 = Instrumentation|Any CPU {186F31A3-EF89-4A25-B2D5-20060606AA01}.Instrumentation|x64.ActiveCfg = Instrumentation|Any CPU {186F31A3-EF89-4A25-B2D5-20060606AA01}.Instrumentation|x64.Build.0 = Instrumentation|Any CPU {186F31A3-EF89-4A25-B2D5-20060606AA01}.Release|Any CPU.ActiveCfg = Release|Any CPU {186F31A3-EF89-4A25-B2D5-20060606AA01}.Release|Any CPU.Build.0 = Release|Any CPU {186F31A3-EF89-4A25-B2D5-20060606AA01}.Release|ARM.ActiveCfg = Release|Any CPU {186F31A3-EF89-4A25-B2D5-20060606AA01}.Release|ARM.Build.0 = Release|Any CPU {186F31A3-EF89-4A25-B2D5-20060606AA01}.Release|Mixed Platforms.ActiveCfg = Release|Any CPU {186F31A3-EF89-4A25-B2D5-20060606AA01}.Release|Mixed Platforms.Build.0 = Release|Any CPU {186F31A3-EF89-4A25-B2D5-20060606AA01}.Release|Win32.ActiveCfg = Release|Any CPU {186F31A3-EF89-4A25-B2D5-20060606AA01}.Release|Win32.Build.0 = Release|Any CPU {186F31A3-EF89-4A25-B2D5-20060606AA01}.Release|x64.ActiveCfg = Release|Any CPU {186F31A3-EF89-4A25-B2D5-20060606AA01}.Release|x64.Build.0 = Release|Any CPU {186F31A3-EF89-4A25-B2D5-20060704AA01}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {186F31A3-EF89-4A25-B2D5-20060704AA01}.Debug|Any CPU.Build.0 = Debug|Any CPU {186F31A3-EF89-4A25-B2D5-20060704AA01}.Debug|ARM.ActiveCfg = Debug|Any CPU {186F31A3-EF89-4A25-B2D5-20060704AA01}.Debug|ARM.Build.0 = Debug|Any CPU {186F31A3-EF89-4A25-B2D5-20060704AA01}.Debug|Mixed Platforms.ActiveCfg = Debug|Any CPU {186F31A3-EF89-4A25-B2D5-20060704AA01}.Debug|Mixed Platforms.Build.0 = Debug|Any CPU {186F31A3-EF89-4A25-B2D5-20060704AA01}.Debug|Win32.ActiveCfg = Debug|Any CPU {186F31A3-EF89-4A25-B2D5-20060704AA01}.Debug|Win32.Build.0 = Debug|Any CPU {186F31A3-EF89-4A25-B2D5-20060704AA01}.Debug|x64.ActiveCfg = Debug|Any CPU {186F31A3-EF89-4A25-B2D5-20060704AA01}.Debug|x64.Build.0 = Debug|Any CPU {186F31A3-EF89-4A25-B2D5-20060704AA01}.Instrumentation|Any CPU.ActiveCfg = Instrumentation|Any CPU {186F31A3-EF89-4A25-B2D5-20060704AA01}.Instrumentation|Any CPU.Build.0 = Instrumentation|Any CPU {186F31A3-EF89-4A25-B2D5-20060704AA01}.Instrumentation|ARM.ActiveCfg = Instrumentation|Any CPU {186F31A3-EF89-4A25-B2D5-20060704AA01}.Instrumentation|ARM.Build.0 = Instrumentation|Any CPU {186F31A3-EF89-4A25-B2D5-20060704AA01}.Instrumentation|Mixed Platforms.ActiveCfg = Instrumentation|Any CPU {186F31A3-EF89-4A25-B2D5-20060704AA01}.Instrumentation|Mixed Platforms.Build.0 = Instrumentation|Any CPU {186F31A3-EF89-4A25-B2D5-20060704AA01}.Instrumentation|Win32.ActiveCfg = Instrumentation|Any CPU {186F31A3-EF89-4A25-B2D5-20060704AA01}.Instrumentation|Win32.Build.0 = Instrumentation|Any CPU {186F31A3-EF89-4A25-B2D5-20060704AA01}.Instrumentation|x64.ActiveCfg = Instrumentation|Any CPU {186F31A3-EF89-4A25-B2D5-20060704AA01}.Instrumentation|x64.Build.0 = Instrumentation|Any CPU {186F31A3-EF89-4A25-B2D5-20060704AA01}.Release|Any CPU.ActiveCfg = Release|Any CPU {186F31A3-EF89-4A25-B2D5-20060704AA01}.Release|Any CPU.Build.0 = Release|Any CPU {186F31A3-EF89-4A25-B2D5-20060704AA01}.Release|ARM.ActiveCfg = Release|Any CPU {186F31A3-EF89-4A25-B2D5-20060704AA01}.Release|ARM.Build.0 = Release|Any CPU {186F31A3-EF89-4A25-B2D5-20060704AA01}.Release|Mixed Platforms.ActiveCfg = Release|Any CPU {186F31A3-EF89-4A25-B2D5-20060704AA01}.Release|Mixed Platforms.Build.0 = Release|Any CPU {186F31A3-EF89-4A25-B2D5-20060704AA01}.Release|Win32.ActiveCfg = Release|Any CPU {186F31A3-EF89-4A25-B2D5-20060704AA01}.Release|Win32.Build.0 = Release|Any CPU {186F31A3-EF89-4A25-B2D5-20060704AA01}.Release|x64.ActiveCfg = Release|Any CPU {186F31A3-EF89-4A25-B2D5-20060704AA01}.Release|x64.Build.0 = Release|Any CPU {186F31A3-EF89-4A25-B2D5-20060720AA01}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {186F31A3-EF89-4A25-B2D5-20060720AA01}.Debug|Any CPU.Build.0 = Debug|Any CPU {186F31A3-EF89-4A25-B2D5-20060720AA01}.Debug|ARM.ActiveCfg = Debug|Any CPU {186F31A3-EF89-4A25-B2D5-20060720AA01}.Debug|ARM.Build.0 = Debug|Any CPU {186F31A3-EF89-4A25-B2D5-20060720AA01}.Debug|Mixed Platforms.ActiveCfg = Debug|Any CPU {186F31A3-EF89-4A25-B2D5-20060720AA01}.Debug|Mixed Platforms.Build.0 = Debug|Any CPU {186F31A3-EF89-4A25-B2D5-20060720AA01}.Debug|Win32.ActiveCfg = Debug|Any CPU {186F31A3-EF89-4A25-B2D5-20060720AA01}.Debug|Win32.Build.0 = Debug|Any CPU {186F31A3-EF89-4A25-B2D5-20060720AA01}.Debug|x64.ActiveCfg = Debug|Any CPU {186F31A3-EF89-4A25-B2D5-20060720AA01}.Debug|x64.Build.0 = Debug|Any CPU {186F31A3-EF89-4A25-B2D5-20060720AA01}.Instrumentation|Any CPU.ActiveCfg = Instrumentation|Any CPU {186F31A3-EF89-4A25-B2D5-20060720AA01}.Instrumentation|Any CPU.Build.0 = Instrumentation|Any CPU {186F31A3-EF89-4A25-B2D5-20060720AA01}.Instrumentation|ARM.ActiveCfg = Instrumentation|Any CPU {186F31A3-EF89-4A25-B2D5-20060720AA01}.Instrumentation|ARM.Build.0 = Instrumentation|Any CPU {186F31A3-EF89-4A25-B2D5-20060720AA01}.Instrumentation|Mixed Platforms.ActiveCfg = Instrumentation|Any CPU {186F31A3-EF89-4A25-B2D5-20060720AA01}.Instrumentation|Mixed Platforms.Build.0 = Instrumentation|Any CPU {186F31A3-EF89-4A25-B2D5-20060720AA01}.Instrumentation|Win32.ActiveCfg = Instrumentation|Any CPU {186F31A3-EF89-4A25-B2D5-20060720AA01}.Instrumentation|Win32.Build.0 = Instrumentation|Any CPU {186F31A3-EF89-4A25-B2D5-20060720AA01}.Instrumentation|x64.ActiveCfg = Instrumentation|Any CPU {186F31A3-EF89-4A25-B2D5-20060720AA01}.Instrumentation|x64.Build.0 = Instrumentation|Any CPU {186F31A3-EF89-4A25-B2D5-20060720AA01}.Release|Any CPU.ActiveCfg = Release|Any CPU {186F31A3-EF89-4A25-B2D5-20060720AA01}.Release|Any CPU.Build.0 = Release|Any CPU {186F31A3-EF89-4A25-B2D5-20060720AA01}.Release|ARM.ActiveCfg = Release|Any CPU {186F31A3-EF89-4A25-B2D5-20060720AA01}.Release|ARM.Build.0 = Release|Any CPU {186F31A3-EF89-4A25-B2D5-20060720AA01}.Release|Mixed Platforms.ActiveCfg = Release|Any CPU {186F31A3-EF89-4A25-B2D5-20060720AA01}.Release|Mixed Platforms.Build.0 = Release|Any CPU {186F31A3-EF89-4A25-B2D5-20060720AA01}.Release|Win32.ActiveCfg = Release|Any CPU {186F31A3-EF89-4A25-B2D5-20060720AA01}.Release|Win32.Build.0 = Release|Any CPU {186F31A3-EF89-4A25-B2D5-20060720AA01}.Release|x64.ActiveCfg = Release|Any CPU {186F31A3-EF89-4A25-B2D5-20060720AA01}.Release|x64.Build.0 = Release|Any CPU {186F31A3-EF89-4A25-B2D5-20061218AA01}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {186F31A3-EF89-4A25-B2D5-20061218AA01}.Debug|Any CPU.Build.0 = Debug|Any CPU {186F31A3-EF89-4A25-B2D5-20061218AA01}.Debug|ARM.ActiveCfg = Debug|Any CPU {186F31A3-EF89-4A25-B2D5-20061218AA01}.Debug|ARM.Build.0 = Debug|Any CPU {186F31A3-EF89-4A25-B2D5-20061218AA01}.Debug|Mixed Platforms.ActiveCfg = Debug|Any CPU {186F31A3-EF89-4A25-B2D5-20061218AA01}.Debug|Mixed Platforms.Build.0 = Debug|Any CPU {186F31A3-EF89-4A25-B2D5-20061218AA01}.Debug|Win32.ActiveCfg = Debug|Any CPU {186F31A3-EF89-4A25-B2D5-20061218AA01}.Debug|Win32.Build.0 = Debug|Any CPU {186F31A3-EF89-4A25-B2D5-20061218AA01}.Debug|x64.ActiveCfg = Debug|Any CPU {186F31A3-EF89-4A25-B2D5-20061218AA01}.Debug|x64.Build.0 = Debug|Any CPU {186F31A3-EF89-4A25-B2D5-20061218AA01}.Instrumentation|Any CPU.ActiveCfg = Instrumentation|Any CPU {186F31A3-EF89-4A25-B2D5-20061218AA01}.Instrumentation|Any CPU.Build.0 = Instrumentation|Any CPU {186F31A3-EF89-4A25-B2D5-20061218AA01}.Instrumentation|ARM.ActiveCfg = Instrumentation|Any CPU {186F31A3-EF89-4A25-B2D5-20061218AA01}.Instrumentation|ARM.Build.0 = Instrumentation|Any CPU {186F31A3-EF89-4A25-B2D5-20061218AA01}.Instrumentation|Mixed Platforms.ActiveCfg = Instrumentation|Any CPU {186F31A3-EF89-4A25-B2D5-20061218AA01}.Instrumentation|Mixed Platforms.Build.0 = Instrumentation|Any CPU {186F31A3-EF89-4A25-B2D5-20061218AA01}.Instrumentation|Win32.ActiveCfg = Instrumentation|Any CPU {186F31A3-EF89-4A25-B2D5-20061218AA01}.Instrumentation|Win32.Build.0 = Instrumentation|Any CPU {186F31A3-EF89-4A25-B2D5-20061218AA01}.Instrumentation|x64.ActiveCfg = Instrumentation|Any CPU {186F31A3-EF89-4A25-B2D5-20061218AA01}.Instrumentation|x64.Build.0 = Instrumentation|Any CPU {186F31A3-EF89-4A25-B2D5-20061218AA01}.Release|Any CPU.ActiveCfg = Release|Any CPU {186F31A3-EF89-4A25-B2D5-20061218AA01}.Release|Any CPU.Build.0 = Release|Any CPU {186F31A3-EF89-4A25-B2D5-20061218AA01}.Release|ARM.ActiveCfg = Release|Any CPU {186F31A3-EF89-4A25-B2D5-20061218AA01}.Release|ARM.Build.0 = Release|Any CPU {186F31A3-EF89-4A25-B2D5-20061218AA01}.Release|Mixed Platforms.ActiveCfg = Release|Any CPU {186F31A3-EF89-4A25-B2D5-20061218AA01}.Release|Mixed Platforms.Build.0 = Release|Any CPU {186F31A3-EF89-4A25-B2D5-20061218AA01}.Release|Win32.ActiveCfg = Release|Any CPU {186F31A3-EF89-4A25-B2D5-20061218AA01}.Release|Win32.Build.0 = Release|Any CPU {186F31A3-EF89-4A25-B2D5-20061218AA01}.Release|x64.ActiveCfg = Release|Any CPU {186F31A3-EF89-4A25-B2D5-20061218AA01}.Release|x64.Build.0 = Release|Any CPU {186F31A3-EF89-4A25-B2D5-20070211AA01}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {186F31A3-EF89-4A25-B2D5-20070211AA01}.Debug|Any CPU.Build.0 = Debug|Any CPU {186F31A3-EF89-4A25-B2D5-20070211AA01}.Debug|ARM.ActiveCfg = Debug|Any CPU {186F31A3-EF89-4A25-B2D5-20070211AA01}.Debug|ARM.Build.0 = Debug|Any CPU {186F31A3-EF89-4A25-B2D5-20070211AA01}.Debug|Mixed Platforms.ActiveCfg = Debug|Any CPU {186F31A3-EF89-4A25-B2D5-20070211AA01}.Debug|Mixed Platforms.Build.0 = Debug|Any CPU {186F31A3-EF89-4A25-B2D5-20070211AA01}.Debug|Win32.ActiveCfg = Debug|Any CPU {186F31A3-EF89-4A25-B2D5-20070211AA01}.Debug|Win32.Build.0 = Debug|Any CPU {186F31A3-EF89-4A25-B2D5-20070211AA01}.Debug|x64.ActiveCfg = Debug|Any CPU {186F31A3-EF89-4A25-B2D5-20070211AA01}.Debug|x64.Build.0 = Debug|Any CPU {186F31A3-EF89-4A25-B2D5-20070211AA01}.Instrumentation|Any CPU.ActiveCfg = Instrumentation|Any CPU {186F31A3-EF89-4A25-B2D5-20070211AA01}.Instrumentation|Any CPU.Build.0 = Instrumentation|Any CPU {186F31A3-EF89-4A25-B2D5-20070211AA01}.Instrumentation|ARM.ActiveCfg = Instrumentation|Any CPU {186F31A3-EF89-4A25-B2D5-20070211AA01}.Instrumentation|ARM.Build.0 = Instrumentation|Any CPU {186F31A3-EF89-4A25-B2D5-20070211AA01}.Instrumentation|Mixed Platforms.ActiveCfg = Instrumentation|Any CPU {186F31A3-EF89-4A25-B2D5-20070211AA01}.Instrumentation|Mixed Platforms.Build.0 = Instrumentation|Any CPU {186F31A3-EF89-4A25-B2D5-20070211AA01}.Instrumentation|Win32.ActiveCfg = Instrumentation|Any CPU {186F31A3-EF89-4A25-B2D5-20070211AA01}.Instrumentation|Win32.Build.0 = Instrumentation|Any CPU {186F31A3-EF89-4A25-B2D5-20070211AA01}.Instrumentation|x64.ActiveCfg = Instrumentation|Any CPU {186F31A3-EF89-4A25-B2D5-20070211AA01}.Instrumentation|x64.Build.0 = Instrumentation|Any CPU {186F31A3-EF89-4A25-B2D5-20070211AA01}.Release|Any CPU.ActiveCfg = Release|Any CPU {186F31A3-EF89-4A25-B2D5-20070211AA01}.Release|Any CPU.Build.0 = Release|Any CPU {186F31A3-EF89-4A25-B2D5-20070211AA01}.Release|ARM.ActiveCfg = Release|Any CPU {186F31A3-EF89-4A25-B2D5-20070211AA01}.Release|ARM.Build.0 = Release|Any CPU {186F31A3-EF89-4A25-B2D5-20070211AA01}.Release|Mixed Platforms.ActiveCfg = Release|Any CPU {186F31A3-EF89-4A25-B2D5-20070211AA01}.Release|Mixed Platforms.Build.0 = Release|Any CPU {186F31A3-EF89-4A25-B2D5-20070211AA01}.Release|Win32.ActiveCfg = Release|Any CPU {186F31A3-EF89-4A25-B2D5-20070211AA01}.Release|Win32.Build.0 = Release|Any CPU {186F31A3-EF89-4A25-B2D5-20070211AA01}.Release|x64.ActiveCfg = Release|Any CPU {186F31A3-EF89-4A25-B2D5-20070211AA01}.Release|x64.Build.0 = Release|Any CPU {186F31A3-EF89-4A25-B2D5-20070222AA01}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {186F31A3-EF89-4A25-B2D5-20070222AA01}.Debug|Any CPU.Build.0 = Debug|Any CPU {186F31A3-EF89-4A25-B2D5-20070222AA01}.Debug|ARM.ActiveCfg = Debug|Any CPU {186F31A3-EF89-4A25-B2D5-20070222AA01}.Debug|ARM.Build.0 = Debug|Any CPU {186F31A3-EF89-4A25-B2D5-20070222AA01}.Debug|Mixed Platforms.ActiveCfg = Debug|Any CPU {186F31A3-EF89-4A25-B2D5-20070222AA01}.Debug|Mixed Platforms.Build.0 = Debug|Any CPU {186F31A3-EF89-4A25-B2D5-20070222AA01}.Debug|Win32.ActiveCfg = Debug|Any CPU {186F31A3-EF89-4A25-B2D5-20070222AA01}.Debug|Win32.Build.0 = Debug|Any CPU {186F31A3-EF89-4A25-B2D5-20070222AA01}.Debug|x64.ActiveCfg = Debug|Any CPU {186F31A3-EF89-4A25-B2D5-20070222AA01}.Debug|x64.Build.0 = Debug|Any CPU {186F31A3-EF89-4A25-B2D5-20070222AA01}.Instrumentation|Any CPU.ActiveCfg = Instrumentation|Any CPU {186F31A3-EF89-4A25-B2D5-20070222AA01}.Instrumentation|Any CPU.Build.0 = Instrumentation|Any CPU {186F31A3-EF89-4A25-B2D5-20070222AA01}.Instrumentation|ARM.ActiveCfg = Instrumentation|Any CPU {186F31A3-EF89-4A25-B2D5-20070222AA01}.Instrumentation|ARM.Build.0 = Instrumentation|Any CPU {186F31A3-EF89-4A25-B2D5-20070222AA01}.Instrumentation|Mixed Platforms.ActiveCfg = Instrumentation|Any CPU {186F31A3-EF89-4A25-B2D5-20070222AA01}.Instrumentation|Mixed Platforms.Build.0 = Instrumentation|Any CPU {186F31A3-EF89-4A25-B2D5-20070222AA01}.Instrumentation|Win32.ActiveCfg = Instrumentation|Any CPU {186F31A3-EF89-4A25-B2D5-20070222AA01}.Instrumentation|Win32.Build.0 = Instrumentation|Any CPU {186F31A3-EF89-4A25-B2D5-20070222AA01}.Instrumentation|x64.ActiveCfg = Instrumentation|Any CPU {186F31A3-EF89-4A25-B2D5-20070222AA01}.Instrumentation|x64.Build.0 = Instrumentation|Any CPU {186F31A3-EF89-4A25-B2D5-20070222AA01}.Release|Any CPU.ActiveCfg = Release|Any CPU {186F31A3-EF89-4A25-B2D5-20070222AA01}.Release|Any CPU.Build.0 = Release|Any CPU {186F31A3-EF89-4A25-B2D5-20070222AA01}.Release|ARM.ActiveCfg = Release|Any CPU {186F31A3-EF89-4A25-B2D5-20070222AA01}.Release|ARM.Build.0 = Release|Any CPU {186F31A3-EF89-4A25-B2D5-20070222AA01}.Release|Mixed Platforms.ActiveCfg = Release|Any CPU {186F31A3-EF89-4A25-B2D5-20070222AA01}.Release|Mixed Platforms.Build.0 = Release|Any CPU {186F31A3-EF89-4A25-B2D5-20070222AA01}.Release|Win32.ActiveCfg = Release|Any CPU {186F31A3-EF89-4A25-B2D5-20070222AA01}.Release|Win32.Build.0 = Release|Any CPU {186F31A3-EF89-4A25-B2D5-20070222AA01}.Release|x64.ActiveCfg = Release|Any CPU {186F31A3-EF89-4A25-B2D5-20070222AA01}.Release|x64.Build.0 = Release|Any CPU {186F31A3-EF89-4A25-B2D5-20070430AA01}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {186F31A3-EF89-4A25-B2D5-20070430AA01}.Debug|Any CPU.Build.0 = Debug|Any CPU {186F31A3-EF89-4A25-B2D5-20070430AA01}.Debug|ARM.ActiveCfg = Debug|Any CPU {186F31A3-EF89-4A25-B2D5-20070430AA01}.Debug|ARM.Build.0 = Debug|Any CPU {186F31A3-EF89-4A25-B2D5-20070430AA01}.Debug|Mixed Platforms.ActiveCfg = Debug|Any CPU {186F31A3-EF89-4A25-B2D5-20070430AA01}.Debug|Mixed Platforms.Build.0 = Debug|Any CPU {186F31A3-EF89-4A25-B2D5-20070430AA01}.Debug|Win32.ActiveCfg = Debug|Any CPU {186F31A3-EF89-4A25-B2D5-20070430AA01}.Debug|Win32.Build.0 = Debug|Any CPU {186F31A3-EF89-4A25-B2D5-20070430AA01}.Debug|x64.ActiveCfg = Debug|Any CPU {186F31A3-EF89-4A25-B2D5-20070430AA01}.Debug|x64.Build.0 = Debug|Any CPU {186F31A3-EF89-4A25-B2D5-20070430AA01}.Instrumentation|Any CPU.ActiveCfg = Instrumentation|Any CPU {186F31A3-EF89-4A25-B2D5-20070430AA01}.Instrumentation|Any CPU.Build.0 = Instrumentation|Any CPU {186F31A3-EF89-4A25-B2D5-20070430AA01}.Instrumentation|ARM.ActiveCfg = Instrumentation|Any CPU {186F31A3-EF89-4A25-B2D5-20070430AA01}.Instrumentation|ARM.Build.0 = Instrumentation|Any CPU {186F31A3-EF89-4A25-B2D5-20070430AA01}.Instrumentation|Mixed Platforms.ActiveCfg = Instrumentation|Any CPU {186F31A3-EF89-4A25-B2D5-20070430AA01}.Instrumentation|Mixed Platforms.Build.0 = Instrumentation|Any CPU {186F31A3-EF89-4A25-B2D5-20070430AA01}.Instrumentation|Win32.ActiveCfg = Instrumentation|Any CPU {186F31A3-EF89-4A25-B2D5-20070430AA01}.Instrumentation|Win32.Build.0 = Instrumentation|Any CPU {186F31A3-EF89-4A25-B2D5-20070430AA01}.Instrumentation|x64.ActiveCfg = Instrumentation|Any CPU {186F31A3-EF89-4A25-B2D5-20070430AA01}.Instrumentation|x64.Build.0 = Instrumentation|Any CPU {186F31A3-EF89-4A25-B2D5-20070430AA01}.Release|Any CPU.ActiveCfg = Release|Any CPU {186F31A3-EF89-4A25-B2D5-20070430AA01}.Release|Any CPU.Build.0 = Release|Any CPU {186F31A3-EF89-4A25-B2D5-20070430AA01}.Release|ARM.ActiveCfg = Release|Any CPU {186F31A3-EF89-4A25-B2D5-20070430AA01}.Release|ARM.Build.0 = Release|Any CPU {186F31A3-EF89-4A25-B2D5-20070430AA01}.Release|Mixed Platforms.ActiveCfg = Release|Any CPU {186F31A3-EF89-4A25-B2D5-20070430AA01}.Release|Mixed Platforms.Build.0 = Release|Any CPU {186F31A3-EF89-4A25-B2D5-20070430AA01}.Release|Win32.ActiveCfg = Release|Any CPU {186F31A3-EF89-4A25-B2D5-20070430AA01}.Release|Win32.Build.0 = Release|Any CPU {186F31A3-EF89-4A25-B2D5-20070430AA01}.Release|x64.ActiveCfg = Release|Any CPU {186F31A3-EF89-4A25-B2D5-20070430AA01}.Release|x64.Build.0 = Release|Any CPU {186F31A3-EF89-4A25-B2D5-20070519AA01}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {186F31A3-EF89-4A25-B2D5-20070519AA01}.Debug|Any CPU.Build.0 = Debug|Any CPU {186F31A3-EF89-4A25-B2D5-20070519AA01}.Debug|ARM.ActiveCfg = Debug|Any CPU {186F31A3-EF89-4A25-B2D5-20070519AA01}.Debug|ARM.Build.0 = Debug|Any CPU {186F31A3-EF89-4A25-B2D5-20070519AA01}.Debug|Mixed Platforms.ActiveCfg = Debug|Any CPU {186F31A3-EF89-4A25-B2D5-20070519AA01}.Debug|Mixed Platforms.Build.0 = Debug|Any CPU {186F31A3-EF89-4A25-B2D5-20070519AA01}.Debug|Win32.ActiveCfg = Debug|Any CPU {186F31A3-EF89-4A25-B2D5-20070519AA01}.Debug|Win32.Build.0 = Debug|Any CPU {186F31A3-EF89-4A25-B2D5-20070519AA01}.Debug|x64.ActiveCfg = Debug|Any CPU {186F31A3-EF89-4A25-B2D5-20070519AA01}.Debug|x64.Build.0 = Debug|Any CPU {186F31A3-EF89-4A25-B2D5-20070519AA01}.Instrumentation|Any CPU.ActiveCfg = Instrumentation|Any CPU {186F31A3-EF89-4A25-B2D5-20070519AA01}.Instrumentation|Any CPU.Build.0 = Instrumentation|Any CPU {186F31A3-EF89-4A25-B2D5-20070519AA01}.Instrumentation|ARM.ActiveCfg = Instrumentation|Any CPU {186F31A3-EF89-4A25-B2D5-20070519AA01}.Instrumentation|ARM.Build.0 = Instrumentation|Any CPU {186F31A3-EF89-4A25-B2D5-20070519AA01}.Instrumentation|Mixed Platforms.ActiveCfg = Instrumentation|Any CPU {186F31A3-EF89-4A25-B2D5-20070519AA01}.Instrumentation|Mixed Platforms.Build.0 = Instrumentation|Any CPU {186F31A3-EF89-4A25-B2D5-20070519AA01}.Instrumentation|Win32.ActiveCfg = Instrumentation|Any CPU {186F31A3-EF89-4A25-B2D5-20070519AA01}.Instrumentation|Win32.Build.0 = Instrumentation|Any CPU {186F31A3-EF89-4A25-B2D5-20070519AA01}.Instrumentation|x64.ActiveCfg = Instrumentation|Any CPU {186F31A3-EF89-4A25-B2D5-20070519AA01}.Instrumentation|x64.Build.0 = Instrumentation|Any CPU {186F31A3-EF89-4A25-B2D5-20070519AA01}.Release|Any CPU.ActiveCfg = Release|Any CPU {186F31A3-EF89-4A25-B2D5-20070519AA01}.Release|Any CPU.Build.0 = Release|Any CPU {186F31A3-EF89-4A25-B2D5-20070519AA01}.Release|ARM.ActiveCfg = Release|Any CPU {186F31A3-EF89-4A25-B2D5-20070519AA01}.Release|ARM.Build.0 = Release|Any CPU {186F31A3-EF89-4A25-B2D5-20070519AA01}.Release|Mixed Platforms.ActiveCfg = Release|Any CPU {186F31A3-EF89-4A25-B2D5-20070519AA01}.Release|Mixed Platforms.Build.0 = Release|Any CPU {186F31A3-EF89-4A25-B2D5-20070519AA01}.Release|Win32.ActiveCfg = Release|Any CPU {186F31A3-EF89-4A25-B2D5-20070519AA01}.Release|Win32.Build.0 = Release|Any CPU {186F31A3-EF89-4A25-B2D5-20070519AA01}.Release|x64.ActiveCfg = Release|Any CPU {186F31A3-EF89-4A25-B2D5-20070519AA01}.Release|x64.Build.0 = Release|Any CPU {186F31A3-EF89-4A25-B2D5-20070601AA01}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {186F31A3-EF89-4A25-B2D5-20070601AA01}.Debug|Any CPU.Build.0 = Debug|Any CPU {186F31A3-EF89-4A25-B2D5-20070601AA01}.Debug|ARM.ActiveCfg = Debug|Any CPU {186F31A3-EF89-4A25-B2D5-20070601AA01}.Debug|ARM.Build.0 = Debug|Any CPU {186F31A3-EF89-4A25-B2D5-20070601AA01}.Debug|Mixed Platforms.ActiveCfg = Debug|Any CPU {186F31A3-EF89-4A25-B2D5-20070601AA01}.Debug|Mixed Platforms.Build.0 = Debug|Any CPU {186F31A3-EF89-4A25-B2D5-20070601AA01}.Debug|Win32.ActiveCfg = Debug|Any CPU {186F31A3-EF89-4A25-B2D5-20070601AA01}.Debug|Win32.Build.0 = Debug|Any CPU {186F31A3-EF89-4A25-B2D5-20070601AA01}.Debug|x64.ActiveCfg = Debug|Any CPU {186F31A3-EF89-4A25-B2D5-20070601AA01}.Debug|x64.Build.0 = Debug|Any CPU {186F31A3-EF89-4A25-B2D5-20070601AA01}.Instrumentation|Any CPU.ActiveCfg = Instrumentation|Any CPU {186F31A3-EF89-4A25-B2D5-20070601AA01}.Instrumentation|Any CPU.Build.0 = Instrumentation|Any CPU {186F31A3-EF89-4A25-B2D5-20070601AA01}.Instrumentation|ARM.ActiveCfg = Instrumentation|Any CPU {186F31A3-EF89-4A25-B2D5-20070601AA01}.Instrumentation|ARM.Build.0 = Instrumentation|Any CPU {186F31A3-EF89-4A25-B2D5-20070601AA01}.Instrumentation|Mixed Platforms.ActiveCfg = Instrumentation|Any CPU {186F31A3-EF89-4A25-B2D5-20070601AA01}.Instrumentation|Mixed Platforms.Build.0 = Instrumentation|Any CPU {186F31A3-EF89-4A25-B2D5-20070601AA01}.Instrumentation|Win32.ActiveCfg = Instrumentation|Any CPU {186F31A3-EF89-4A25-B2D5-20070601AA01}.Instrumentation|Win32.Build.0 = Instrumentation|Any CPU {186F31A3-EF89-4A25-B2D5-20070601AA01}.Instrumentation|x64.ActiveCfg = Instrumentation|Any CPU {186F31A3-EF89-4A25-B2D5-20070601AA01}.Instrumentation|x64.Build.0 = Instrumentation|Any CPU {186F31A3-EF89-4A25-B2D5-20070601AA01}.Release|Any CPU.ActiveCfg = Release|Any CPU {186F31A3-EF89-4A25-B2D5-20070601AA01}.Release|Any CPU.Build.0 = Release|Any CPU {186F31A3-EF89-4A25-B2D5-20070601AA01}.Release|ARM.ActiveCfg = Release|Any CPU {186F31A3-EF89-4A25-B2D5-20070601AA01}.Release|ARM.Build.0 = Release|Any CPU {186F31A3-EF89-4A25-B2D5-20070601AA01}.Release|Mixed Platforms.ActiveCfg = Release|Any CPU {186F31A3-EF89-4A25-B2D5-20070601AA01}.Release|Mixed Platforms.Build.0 = Release|Any CPU {186F31A3-EF89-4A25-B2D5-20070601AA01}.Release|Win32.ActiveCfg = Release|Any CPU {186F31A3-EF89-4A25-B2D5-20070601AA01}.Release|Win32.Build.0 = Release|Any CPU {186F31A3-EF89-4A25-B2D5-20070601AA01}.Release|x64.ActiveCfg = Release|Any CPU {186F31A3-EF89-4A25-B2D5-20070601AA01}.Release|x64.Build.0 = Release|Any CPU {186F31A3-EF89-4A25-B2D5-20070605AA02}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {186F31A3-EF89-4A25-B2D5-20070605AA02}.Debug|Any CPU.Build.0 = Debug|Any CPU {186F31A3-EF89-4A25-B2D5-20070605AA02}.Debug|ARM.ActiveCfg = Debug|Any CPU {186F31A3-EF89-4A25-B2D5-20070605AA02}.Debug|ARM.Build.0 = Debug|Any CPU {186F31A3-EF89-4A25-B2D5-20070605AA02}.Debug|Mixed Platforms.ActiveCfg = Debug|Any CPU {186F31A3-EF89-4A25-B2D5-20070605AA02}.Debug|Mixed Platforms.Build.0 = Debug|Any CPU {186F31A3-EF89-4A25-B2D5-20070605AA02}.Debug|Win32.ActiveCfg = Debug|Any CPU {186F31A3-EF89-4A25-B2D5-20070605AA02}.Debug|Win32.Build.0 = Debug|Any CPU {186F31A3-EF89-4A25-B2D5-20070605AA02}.Debug|x64.ActiveCfg = Debug|Any CPU {186F31A3-EF89-4A25-B2D5-20070605AA02}.Debug|x64.Build.0 = Debug|Any CPU {186F31A3-EF89-4A25-B2D5-20070605AA02}.Instrumentation|Any CPU.ActiveCfg = Instrumentation|Any CPU {186F31A3-EF89-4A25-B2D5-20070605AA02}.Instrumentation|Any CPU.Build.0 = Instrumentation|Any CPU {186F31A3-EF89-4A25-B2D5-20070605AA02}.Instrumentation|ARM.ActiveCfg = Instrumentation|Any CPU {186F31A3-EF89-4A25-B2D5-20070605AA02}.Instrumentation|ARM.Build.0 = Instrumentation|Any CPU {186F31A3-EF89-4A25-B2D5-20070605AA02}.Instrumentation|Mixed Platforms.ActiveCfg = Instrumentation|Any CPU {186F31A3-EF89-4A25-B2D5-20070605AA02}.Instrumentation|Mixed Platforms.Build.0 = Instrumentation|Any CPU {186F31A3-EF89-4A25-B2D5-20070605AA02}.Instrumentation|Win32.ActiveCfg = Instrumentation|Any CPU {186F31A3-EF89-4A25-B2D5-20070605AA02}.Instrumentation|Win32.Build.0 = Instrumentation|Any CPU {186F31A3-EF89-4A25-B2D5-20070605AA02}.Instrumentation|x64.ActiveCfg = Instrumentation|Any CPU {186F31A3-EF89-4A25-B2D5-20070605AA02}.Instrumentation|x64.Build.0 = Instrumentation|Any CPU {186F31A3-EF89-4A25-B2D5-20070605AA02}.Release|Any CPU.ActiveCfg = Release|Any CPU {186F31A3-EF89-4A25-B2D5-20070605AA02}.Release|Any CPU.Build.0 = Release|Any CPU {186F31A3-EF89-4A25-B2D5-20070605AA02}.Release|ARM.ActiveCfg = Release|Any CPU {186F31A3-EF89-4A25-B2D5-20070605AA02}.Release|ARM.Build.0 = Release|Any CPU {186F31A3-EF89-4A25-B2D5-20070605AA02}.Release|Mixed Platforms.ActiveCfg = Release|Any CPU {186F31A3-EF89-4A25-B2D5-20070605AA02}.Release|Mixed Platforms.Build.0 = Release|Any CPU {186F31A3-EF89-4A25-B2D5-20070605AA02}.Release|Win32.ActiveCfg = Release|Any CPU {186F31A3-EF89-4A25-B2D5-20070605AA02}.Release|Win32.Build.0 = Release|Any CPU {186F31A3-EF89-4A25-B2D5-20070605AA02}.Release|x64.ActiveCfg = Release|Any CPU {186F31A3-EF89-4A25-B2D5-20070605AA02}.Release|x64.Build.0 = Release|Any CPU {186F31A3-EF89-4A25-B2D5-20070606AA01}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {186F31A3-EF89-4A25-B2D5-20070606AA01}.Debug|Any CPU.Build.0 = Debug|Any CPU {186F31A3-EF89-4A25-B2D5-20070606AA01}.Debug|ARM.ActiveCfg = Debug|Any CPU {186F31A3-EF89-4A25-B2D5-20070606AA01}.Debug|ARM.Build.0 = Debug|Any CPU {186F31A3-EF89-4A25-B2D5-20070606AA01}.Debug|Mixed Platforms.ActiveCfg = Debug|Any CPU {186F31A3-EF89-4A25-B2D5-20070606AA01}.Debug|Mixed Platforms.Build.0 = Debug|Any CPU {186F31A3-EF89-4A25-B2D5-20070606AA01}.Debug|Win32.ActiveCfg = Debug|Any CPU {186F31A3-EF89-4A25-B2D5-20070606AA01}.Debug|Win32.Build.0 = Debug|Any CPU {186F31A3-EF89-4A25-B2D5-20070606AA01}.Debug|x64.ActiveCfg = Debug|Any CPU {186F31A3-EF89-4A25-B2D5-20070606AA01}.Debug|x64.Build.0 = Debug|Any CPU {186F31A3-EF89-4A25-B2D5-20070606AA01}.Instrumentation|Any CPU.ActiveCfg = Instrumentation|Any CPU {186F31A3-EF89-4A25-B2D5-20070606AA01}.Instrumentation|Any CPU.Build.0 = Instrumentation|Any CPU {186F31A3-EF89-4A25-B2D5-20070606AA01}.Instrumentation|ARM.ActiveCfg = Instrumentation|Any CPU {186F31A3-EF89-4A25-B2D5-20070606AA01}.Instrumentation|ARM.Build.0 = Instrumentation|Any CPU {186F31A3-EF89-4A25-B2D5-20070606AA01}.Instrumentation|Mixed Platforms.ActiveCfg = Instrumentation|Any CPU {186F31A3-EF89-4A25-B2D5-20070606AA01}.Instrumentation|Mixed Platforms.Build.0 = Instrumentation|Any CPU {186F31A3-EF89-4A25-B2D5-20070606AA01}.Instrumentation|Win32.ActiveCfg = Instrumentation|Any CPU {186F31A3-EF89-4A25-B2D5-20070606AA01}.Instrumentation|Win32.Build.0 = Instrumentation|Any CPU {186F31A3-EF89-4A25-B2D5-20070606AA01}.Instrumentation|x64.ActiveCfg = Instrumentation|Any CPU {186F31A3-EF89-4A25-B2D5-20070606AA01}.Instrumentation|x64.Build.0 = Instrumentation|Any CPU {186F31A3-EF89-4A25-B2D5-20070606AA01}.Release|Any CPU.ActiveCfg = Release|Any CPU {186F31A3-EF89-4A25-B2D5-20070606AA01}.Release|Any CPU.Build.0 = Release|Any CPU {186F31A3-EF89-4A25-B2D5-20070606AA01}.Release|ARM.ActiveCfg = Release|Any CPU {186F31A3-EF89-4A25-B2D5-20070606AA01}.Release|ARM.Build.0 = Release|Any CPU {186F31A3-EF89-4A25-B2D5-20070606AA01}.Release|Mixed Platforms.ActiveCfg = Release|Any CPU {186F31A3-EF89-4A25-B2D5-20070606AA01}.Release|Mixed Platforms.Build.0 = Release|Any CPU {186F31A3-EF89-4A25-B2D5-20070606AA01}.Release|Win32.ActiveCfg = Release|Any CPU {186F31A3-EF89-4A25-B2D5-20070606AA01}.Release|Win32.Build.0 = Release|Any CPU {186F31A3-EF89-4A25-B2D5-20070606AA01}.Release|x64.ActiveCfg = Release|Any CPU {186F31A3-EF89-4A25-B2D5-20070606AA01}.Release|x64.Build.0 = Release|Any CPU {186F31A3-EF89-4A25-B2D5-20070702AA01}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {186F31A3-EF89-4A25-B2D5-20070702AA01}.Debug|Any CPU.Build.0 = Debug|Any CPU {186F31A3-EF89-4A25-B2D5-20070702AA01}.Debug|ARM.ActiveCfg = Debug|Any CPU {186F31A3-EF89-4A25-B2D5-20070702AA01}.Debug|ARM.Build.0 = Debug|Any CPU {186F31A3-EF89-4A25-B2D5-20070702AA01}.Debug|Mixed Platforms.ActiveCfg = Debug|Any CPU {186F31A3-EF89-4A25-B2D5-20070702AA01}.Debug|Mixed Platforms.Build.0 = Debug|Any CPU {186F31A3-EF89-4A25-B2D5-20070702AA01}.Debug|Win32.ActiveCfg = Debug|Any CPU {186F31A3-EF89-4A25-B2D5-20070702AA01}.Debug|Win32.Build.0 = Debug|Any CPU {186F31A3-EF89-4A25-B2D5-20070702AA01}.Debug|x64.ActiveCfg = Debug|Any CPU {186F31A3-EF89-4A25-B2D5-20070702AA01}.Debug|x64.Build.0 = Debug|Any CPU {186F31A3-EF89-4A25-B2D5-20070702AA01}.Instrumentation|Any CPU.ActiveCfg = Instrumentation|Any CPU {186F31A3-EF89-4A25-B2D5-20070702AA01}.Instrumentation|Any CPU.Build.0 = Instrumentation|Any CPU {186F31A3-EF89-4A25-B2D5-20070702AA01}.Instrumentation|ARM.ActiveCfg = Instrumentation|Any CPU {186F31A3-EF89-4A25-B2D5-20070702AA01}.Instrumentation|ARM.Build.0 = Instrumentation|Any CPU {186F31A3-EF89-4A25-B2D5-20070702AA01}.Instrumentation|Mixed Platforms.ActiveCfg = Instrumentation|Any CPU {186F31A3-EF89-4A25-B2D5-20070702AA01}.Instrumentation|Mixed Platforms.Build.0 = Instrumentation|Any CPU {186F31A3-EF89-4A25-B2D5-20070702AA01}.Instrumentation|Win32.ActiveCfg = Instrumentation|Any CPU {186F31A3-EF89-4A25-B2D5-20070702AA01}.Instrumentation|Win32.Build.0 = Instrumentation|Any CPU {186F31A3-EF89-4A25-B2D5-20070702AA01}.Instrumentation|x64.ActiveCfg = Instrumentation|Any CPU {186F31A3-EF89-4A25-B2D5-20070702AA01}.Instrumentation|x64.Build.0 = Instrumentation|Any CPU {186F31A3-EF89-4A25-B2D5-20070702AA01}.Release|Any CPU.ActiveCfg = Release|Any CPU {186F31A3-EF89-4A25-B2D5-20070702AA01}.Release|Any CPU.Build.0 = Release|Any CPU {186F31A3-EF89-4A25-B2D5-20070702AA01}.Release|ARM.ActiveCfg = Release|Any CPU {186F31A3-EF89-4A25-B2D5-20070702AA01}.Release|ARM.Build.0 = Release|Any CPU {186F31A3-EF89-4A25-B2D5-20070702AA01}.Release|Mixed Platforms.ActiveCfg = Release|Any CPU {186F31A3-EF89-4A25-B2D5-20070702AA01}.Release|Mixed Platforms.Build.0 = Release|Any CPU {186F31A3-EF89-4A25-B2D5-20070702AA01}.Release|Win32.ActiveCfg = Release|Any CPU {186F31A3-EF89-4A25-B2D5-20070702AA01}.Release|Win32.Build.0 = Release|Any CPU {186F31A3-EF89-4A25-B2D5-20070702AA01}.Release|x64.ActiveCfg = Release|Any CPU {186F31A3-EF89-4A25-B2D5-20070702AA01}.Release|x64.Build.0 = Release|Any CPU {96BF0234-1D60-4401-A6B9-99839187234E}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {96BF0234-1D60-4401-A6B9-99839187234E}.Debug|Any CPU.Build.0 = Debug|Any CPU {96BF0234-1D60-4401-A6B9-99839187234E}.Debug|ARM.ActiveCfg = Debug|Any CPU {96BF0234-1D60-4401-A6B9-99839187234E}.Debug|ARM.Build.0 = Debug|Any CPU {96BF0234-1D60-4401-A6B9-99839187234E}.Debug|Mixed Platforms.ActiveCfg = Debug|Any CPU {96BF0234-1D60-4401-A6B9-99839187234E}.Debug|Mixed Platforms.Build.0 = Debug|Any CPU {96BF0234-1D60-4401-A6B9-99839187234E}.Debug|Win32.ActiveCfg = Debug|Any CPU {96BF0234-1D60-4401-A6B9-99839187234E}.Debug|Win32.Build.0 = Debug|Any CPU {96BF0234-1D60-4401-A6B9-99839187234E}.Debug|x64.ActiveCfg = Debug|Any CPU {96BF0234-1D60-4401-A6B9-99839187234E}.Debug|x64.Build.0 = Debug|Any CPU {96BF0234-1D60-4401-A6B9-99839187234E}.Instrumentation|Any CPU.ActiveCfg = Instrumentation|Any CPU {96BF0234-1D60-4401-A6B9-99839187234E}.Instrumentation|Any CPU.Build.0 = Instrumentation|Any CPU {96BF0234-1D60-4401-A6B9-99839187234E}.Instrumentation|ARM.ActiveCfg = Instrumentation|Any CPU {96BF0234-1D60-4401-A6B9-99839187234E}.Instrumentation|ARM.Build.0 = Instrumentation|Any CPU {96BF0234-1D60-4401-A6B9-99839187234E}.Instrumentation|Mixed Platforms.ActiveCfg = Instrumentation|Any CPU {96BF0234-1D60-4401-A6B9-99839187234E}.Instrumentation|Mixed Platforms.Build.0 = Instrumentation|Any CPU {96BF0234-1D60-4401-A6B9-99839187234E}.Instrumentation|Win32.ActiveCfg = Instrumentation|Any CPU {96BF0234-1D60-4401-A6B9-99839187234E}.Instrumentation|Win32.Build.0 = Instrumentation|Any CPU {96BF0234-1D60-4401-A6B9-99839187234E}.Instrumentation|x64.ActiveCfg = Instrumentation|Any CPU {96BF0234-1D60-4401-A6B9-99839187234E}.Instrumentation|x64.Build.0 = Instrumentation|Any CPU {96BF0234-1D60-4401-A6B9-99839187234E}.Release|Any CPU.ActiveCfg = Release|Any CPU {96BF0234-1D60-4401-A6B9-99839187234E}.Release|Any CPU.Build.0 = Release|Any CPU {96BF0234-1D60-4401-A6B9-99839187234E}.Release|ARM.ActiveCfg = Release|Any CPU {96BF0234-1D60-4401-A6B9-99839187234E}.Release|ARM.Build.0 = Release|Any CPU {96BF0234-1D60-4401-A6B9-99839187234E}.Release|Mixed Platforms.ActiveCfg = Release|Any CPU {96BF0234-1D60-4401-A6B9-99839187234E}.Release|Mixed Platforms.Build.0 = Release|Any CPU {96BF0234-1D60-4401-A6B9-99839187234E}.Release|Win32.ActiveCfg = Release|Any CPU {96BF0234-1D60-4401-A6B9-99839187234E}.Release|Win32.Build.0 = Release|Any CPU {96BF0234-1D60-4401-A6B9-99839187234E}.Release|x64.ActiveCfg = Release|Any CPU {96BF0234-1D60-4401-A6B9-99839187234E}.Release|x64.Build.0 = Release|Any CPU {186F31A3-EF89-4A25-B2D5-20080628AA01}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {186F31A3-EF89-4A25-B2D5-20080628AA01}.Debug|Any CPU.Build.0 = Debug|Any CPU {186F31A3-EF89-4A25-B2D5-20080628AA01}.Debug|ARM.ActiveCfg = Debug|Any CPU {186F31A3-EF89-4A25-B2D5-20080628AA01}.Debug|ARM.Build.0 = Debug|Any CPU {186F31A3-EF89-4A25-B2D5-20080628AA01}.Debug|Mixed Platforms.ActiveCfg = Debug|Any CPU {186F31A3-EF89-4A25-B2D5-20080628AA01}.Debug|Mixed Platforms.Build.0 = Debug|Any CPU {186F31A3-EF89-4A25-B2D5-20080628AA01}.Debug|Win32.ActiveCfg = Debug|Any CPU {186F31A3-EF89-4A25-B2D5-20080628AA01}.Debug|Win32.Build.0 = Debug|Any CPU {186F31A3-EF89-4A25-B2D5-20080628AA01}.Debug|x64.ActiveCfg = Debug|Any CPU {186F31A3-EF89-4A25-B2D5-20080628AA01}.Debug|x64.Build.0 = Debug|Any CPU {186F31A3-EF89-4A25-B2D5-20080628AA01}.Instrumentation|Any CPU.ActiveCfg = Instrumentation|Any CPU {186F31A3-EF89-4A25-B2D5-20080628AA01}.Instrumentation|Any CPU.Build.0 = Instrumentation|Any CPU {186F31A3-EF89-4A25-B2D5-20080628AA01}.Instrumentation|ARM.ActiveCfg = Instrumentation|Any CPU {186F31A3-EF89-4A25-B2D5-20080628AA01}.Instrumentation|ARM.Build.0 = Instrumentation|Any CPU {186F31A3-EF89-4A25-B2D5-20080628AA01}.Instrumentation|Mixed Platforms.ActiveCfg = Instrumentation|Any CPU {186F31A3-EF89-4A25-B2D5-20080628AA01}.Instrumentation|Mixed Platforms.Build.0 = Instrumentation|Any CPU {186F31A3-EF89-4A25-B2D5-20080628AA01}.Instrumentation|Win32.ActiveCfg = Instrumentation|Any CPU {186F31A3-EF89-4A25-B2D5-20080628AA01}.Instrumentation|Win32.Build.0 = Instrumentation|Any CPU {186F31A3-EF89-4A25-B2D5-20080628AA01}.Instrumentation|x64.ActiveCfg = Instrumentation|Any CPU {186F31A3-EF89-4A25-B2D5-20080628AA01}.Instrumentation|x64.Build.0 = Instrumentation|Any CPU {186F31A3-EF89-4A25-B2D5-20080628AA01}.Release|Any CPU.ActiveCfg = Release|Any CPU {186F31A3-EF89-4A25-B2D5-20080628AA01}.Release|Any CPU.Build.0 = Release|Any CPU {186F31A3-EF89-4A25-B2D5-20080628AA01}.Release|ARM.ActiveCfg = Release|Any CPU {186F31A3-EF89-4A25-B2D5-20080628AA01}.Release|ARM.Build.0 = Release|Any CPU {186F31A3-EF89-4A25-B2D5-20080628AA01}.Release|Mixed Platforms.ActiveCfg = Release|Any CPU {186F31A3-EF89-4A25-B2D5-20080628AA01}.Release|Mixed Platforms.Build.0 = Release|Any CPU {186F31A3-EF89-4A25-B2D5-20080628AA01}.Release|Win32.ActiveCfg = Release|Any CPU {186F31A3-EF89-4A25-B2D5-20080628AA01}.Release|Win32.Build.0 = Release|Any CPU {186F31A3-EF89-4A25-B2D5-20080628AA01}.Release|x64.ActiveCfg = Release|Any CPU {186F31A3-EF89-4A25-B2D5-20080628AA01}.Release|x64.Build.0 = Release|Any CPU {B7606EF5-A5EC-4A97-AB4A-35D00EFA2925}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {B7606EF5-A5EC-4A97-AB4A-35D00EFA2925}.Debug|Any CPU.Build.0 = Debug|Any CPU {B7606EF5-A5EC-4A97-AB4A-35D00EFA2925}.Debug|ARM.ActiveCfg = Debug|Any CPU {B7606EF5-A5EC-4A97-AB4A-35D00EFA2925}.Debug|ARM.Build.0 = Debug|Any CPU {B7606EF5-A5EC-4A97-AB4A-35D00EFA2925}.Debug|Mixed Platforms.ActiveCfg = Debug|Any CPU {B7606EF5-A5EC-4A97-AB4A-35D00EFA2925}.Debug|Mixed Platforms.Build.0 = Debug|Any CPU {B7606EF5-A5EC-4A97-AB4A-35D00EFA2925}.Debug|Win32.ActiveCfg = Debug|Any CPU {B7606EF5-A5EC-4A97-AB4A-35D00EFA2925}.Debug|Win32.Build.0 = Debug|Any CPU {B7606EF5-A5EC-4A97-AB4A-35D00EFA2925}.Debug|x64.ActiveCfg = Debug|Any CPU {B7606EF5-A5EC-4A97-AB4A-35D00EFA2925}.Debug|x64.Build.0 = Debug|Any CPU {B7606EF5-A5EC-4A97-AB4A-35D00EFA2925}.Instrumentation|Any CPU.ActiveCfg = Instrumentation|Any CPU {B7606EF5-A5EC-4A97-AB4A-35D00EFA2925}.Instrumentation|Any CPU.Build.0 = Instrumentation|Any CPU {B7606EF5-A5EC-4A97-AB4A-35D00EFA2925}.Instrumentation|ARM.ActiveCfg = Instrumentation|Any CPU {B7606EF5-A5EC-4A97-AB4A-35D00EFA2925}.Instrumentation|ARM.Build.0 = Instrumentation|Any CPU {B7606EF5-A5EC-4A97-AB4A-35D00EFA2925}.Instrumentation|Mixed Platforms.ActiveCfg = Instrumentation|Any CPU {B7606EF5-A5EC-4A97-AB4A-35D00EFA2925}.Instrumentation|Mixed Platforms.Build.0 = Instrumentation|Any CPU {B7606EF5-A5EC-4A97-AB4A-35D00EFA2925}.Instrumentation|Win32.ActiveCfg = Instrumentation|Any CPU {B7606EF5-A5EC-4A97-AB4A-35D00EFA2925}.Instrumentation|Win32.Build.0 = Instrumentation|Any CPU {B7606EF5-A5EC-4A97-AB4A-35D00EFA2925}.Instrumentation|x64.ActiveCfg = Instrumentation|Any CPU {B7606EF5-A5EC-4A97-AB4A-35D00EFA2925}.Instrumentation|x64.Build.0 = Instrumentation|Any CPU {B7606EF5-A5EC-4A97-AB4A-35D00EFA2925}.Release|Any CPU.ActiveCfg = Release|Any CPU {B7606EF5-A5EC-4A97-AB4A-35D00EFA2925}.Release|Any CPU.Build.0 = Release|Any CPU {B7606EF5-A5EC-4A97-AB4A-35D00EFA2925}.Release|ARM.ActiveCfg = Release|Any CPU {B7606EF5-A5EC-4A97-AB4A-35D00EFA2925}.Release|ARM.Build.0 = Release|Any CPU {B7606EF5-A5EC-4A97-AB4A-35D00EFA2925}.Release|Mixed Platforms.ActiveCfg = Release|Any CPU {B7606EF5-A5EC-4A97-AB4A-35D00EFA2925}.Release|Mixed Platforms.Build.0 = Release|Any CPU {B7606EF5-A5EC-4A97-AB4A-35D00EFA2925}.Release|Win32.ActiveCfg = Release|Any CPU {B7606EF5-A5EC-4A97-AB4A-35D00EFA2925}.Release|Win32.Build.0 = Release|Any CPU {B7606EF5-A5EC-4A97-AB4A-35D00EFA2925}.Release|x64.ActiveCfg = Release|Any CPU {B7606EF5-A5EC-4A97-AB4A-35D00EFA2925}.Release|x64.Build.0 = Release|Any CPU {77D71AF4-11C3-409B-A211-51FA19E5C1AA}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {77D71AF4-11C3-409B-A211-51FA19E5C1AA}.Debug|Any CPU.Build.0 = Debug|Any CPU {77D71AF4-11C3-409B-A211-51FA19E5C1AA}.Debug|ARM.ActiveCfg = Debug|Any CPU {77D71AF4-11C3-409B-A211-51FA19E5C1AA}.Debug|ARM.Build.0 = Debug|Any CPU {77D71AF4-11C3-409B-A211-51FA19E5C1AA}.Debug|Mixed Platforms.ActiveCfg = Debug|Any CPU {77D71AF4-11C3-409B-A211-51FA19E5C1AA}.Debug|Mixed Platforms.Build.0 = Debug|Any CPU {77D71AF4-11C3-409B-A211-51FA19E5C1AA}.Debug|Win32.ActiveCfg = Debug|Any CPU {77D71AF4-11C3-409B-A211-51FA19E5C1AA}.Debug|Win32.Build.0 = Debug|Any CPU {77D71AF4-11C3-409B-A211-51FA19E5C1AA}.Debug|x64.ActiveCfg = Debug|Any CPU {77D71AF4-11C3-409B-A211-51FA19E5C1AA}.Debug|x64.Build.0 = Debug|Any CPU {77D71AF4-11C3-409B-A211-51FA19E5C1AA}.Instrumentation|Any CPU.ActiveCfg = Release|Any CPU {77D71AF4-11C3-409B-A211-51FA19E5C1AA}.Instrumentation|Any CPU.Build.0 = Release|Any CPU {77D71AF4-11C3-409B-A211-51FA19E5C1AA}.Instrumentation|ARM.ActiveCfg = Release|Any CPU {77D71AF4-11C3-409B-A211-51FA19E5C1AA}.Instrumentation|ARM.Build.0 = Release|Any CPU {77D71AF4-11C3-409B-A211-51FA19E5C1AA}.Instrumentation|Mixed Platforms.ActiveCfg = Release|Any CPU {77D71AF4-11C3-409B-A211-51FA19E5C1AA}.Instrumentation|Mixed Platforms.Build.0 = Release|Any CPU {77D71AF4-11C3-409B-A211-51FA19E5C1AA}.Instrumentation|Win32.ActiveCfg = Release|Any CPU {77D71AF4-11C3-409B-A211-51FA19E5C1AA}.Instrumentation|Win32.Build.0 = Release|Any CPU {77D71AF4-11C3-409B-A211-51FA19E5C1AA}.Instrumentation|x64.ActiveCfg = Release|Any CPU {77D71AF4-11C3-409B-A211-51FA19E5C1AA}.Instrumentation|x64.Build.0 = Release|Any CPU {77D71AF4-11C3-409B-A211-51FA19E5C1AA}.Release|Any CPU.ActiveCfg = Release|Any CPU {77D71AF4-11C3-409B-A211-51FA19E5C1AA}.Release|Any CPU.Build.0 = Release|Any CPU {77D71AF4-11C3-409B-A211-51FA19E5C1AA}.Release|ARM.ActiveCfg = Release|Any CPU {77D71AF4-11C3-409B-A211-51FA19E5C1AA}.Release|ARM.Build.0 = Release|Any CPU {77D71AF4-11C3-409B-A211-51FA19E5C1AA}.Release|Mixed Platforms.ActiveCfg = Release|Any CPU {77D71AF4-11C3-409B-A211-51FA19E5C1AA}.Release|Mixed Platforms.Build.0 = Release|Any CPU {77D71AF4-11C3-409B-A211-51FA19E5C1AA}.Release|Win32.ActiveCfg = Release|Any CPU {77D71AF4-11C3-409B-A211-51FA19E5C1AA}.Release|Win32.Build.0 = Release|Any CPU {77D71AF4-11C3-409B-A211-51FA19E5C1AA}.Release|x64.ActiveCfg = Release|Any CPU {77D71AF4-11C3-409B-A211-51FA19E5C1AA}.Release|x64.Build.0 = Release|Any CPU {6C77A7DE-D464-430F-96A9-A64768763B5F}.Debug|Any CPU.ActiveCfg = Debug|x64 {6C77A7DE-D464-430F-96A9-A64768763B5F}.Debug|Any CPU.Build.0 = Debug|x64 {6C77A7DE-D464-430F-96A9-A64768763B5F}.Debug|ARM.ActiveCfg = Debug|x64 {6C77A7DE-D464-430F-96A9-A64768763B5F}.Debug|ARM.Build.0 = Debug|x64 {6C77A7DE-D464-430F-96A9-A64768763B5F}.Debug|Mixed Platforms.ActiveCfg = Debug|x64 {6C77A7DE-D464-430F-96A9-A64768763B5F}.Debug|Win32.ActiveCfg = Debug|Win32 {6C77A7DE-D464-430F-96A9-A64768763B5F}.Debug|Win32.Build.0 = Debug|Win32 {6C77A7DE-D464-430F-96A9-A64768763B5F}.Debug|x64.ActiveCfg = Debug|x64 {6C77A7DE-D464-430F-96A9-A64768763B5F}.Debug|x64.Build.0 = Debug|x64 {6C77A7DE-D464-430F-96A9-A64768763B5F}.Instrumentation|Any CPU.ActiveCfg = Release|x64 {6C77A7DE-D464-430F-96A9-A64768763B5F}.Instrumentation|Any CPU.Build.0 = Release|x64 {6C77A7DE-D464-430F-96A9-A64768763B5F}.Instrumentation|ARM.ActiveCfg = Release|x64 {6C77A7DE-D464-430F-96A9-A64768763B5F}.Instrumentation|ARM.Build.0 = Release|x64 {6C77A7DE-D464-430F-96A9-A64768763B5F}.Instrumentation|Mixed Platforms.ActiveCfg = Release|x64 {6C77A7DE-D464-430F-96A9-A64768763B5F}.Instrumentation|Win32.ActiveCfg = Release|Win32 {6C77A7DE-D464-430F-96A9-A64768763B5F}.Instrumentation|Win32.Build.0 = Release|Win32 {6C77A7DE-D464-430F-96A9-A64768763B5F}.Instrumentation|x64.ActiveCfg = Release|x64 {6C77A7DE-D464-430F-96A9-A64768763B5F}.Instrumentation|x64.Build.0 = Release|x64 {6C77A7DE-D464-430F-96A9-A64768763B5F}.Release|Any CPU.ActiveCfg = Release|x64 {6C77A7DE-D464-430F-96A9-A64768763B5F}.Release|Any CPU.Build.0 = Release|x64 {6C77A7DE-D464-430F-96A9-A64768763B5F}.Release|ARM.ActiveCfg = Release|x64 {6C77A7DE-D464-430F-96A9-A64768763B5F}.Release|ARM.Build.0 = Release|x64 {6C77A7DE-D464-430F-96A9-A64768763B5F}.Release|Mixed Platforms.ActiveCfg = Release|Win32 {6C77A7DE-D464-430F-96A9-A64768763B5F}.Release|Win32.ActiveCfg = Release|Win32 {6C77A7DE-D464-430F-96A9-A64768763B5F}.Release|Win32.Build.0 = Release|Win32 {6C77A7DE-D464-430F-96A9-A64768763B5F}.Release|x64.ActiveCfg = Release|x64 {6C77A7DE-D464-430F-96A9-A64768763B5F}.Release|x64.Build.0 = Release|x64 {0162C8CE-6641-4922-8664-F8A44356FBF7}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {0162C8CE-6641-4922-8664-F8A44356FBF7}.Debug|Any CPU.Build.0 = Debug|Any CPU {0162C8CE-6641-4922-8664-F8A44356FBF7}.Debug|ARM.ActiveCfg = Debug|Any CPU {0162C8CE-6641-4922-8664-F8A44356FBF7}.Debug|ARM.Build.0 = Debug|Any CPU {0162C8CE-6641-4922-8664-F8A44356FBF7}.Debug|Mixed Platforms.ActiveCfg = Debug|Any CPU {0162C8CE-6641-4922-8664-F8A44356FBF7}.Debug|Mixed Platforms.Build.0 = Debug|Any CPU {0162C8CE-6641-4922-8664-F8A44356FBF7}.Debug|Win32.ActiveCfg = Debug|Win32 {0162C8CE-6641-4922-8664-F8A44356FBF7}.Debug|Win32.Build.0 = Debug|Win32 {0162C8CE-6641-4922-8664-F8A44356FBF7}.Debug|x64.ActiveCfg = Debug|Any CPU {0162C8CE-6641-4922-8664-F8A44356FBF7}.Debug|x64.Build.0 = Debug|Any CPU {0162C8CE-6641-4922-8664-F8A44356FBF7}.Instrumentation|Any CPU.ActiveCfg = Release|Win32 {0162C8CE-6641-4922-8664-F8A44356FBF7}.Instrumentation|Any CPU.Build.0 = Release|Win32 {0162C8CE-6641-4922-8664-F8A44356FBF7}.Instrumentation|ARM.ActiveCfg = Release|x64 {0162C8CE-6641-4922-8664-F8A44356FBF7}.Instrumentation|ARM.Build.0 = Release|x64 {0162C8CE-6641-4922-8664-F8A44356FBF7}.Instrumentation|Mixed Platforms.ActiveCfg = Release|x64 {0162C8CE-6641-4922-8664-F8A44356FBF7}.Instrumentation|Mixed Platforms.Build.0 = Release|x64 {0162C8CE-6641-4922-8664-F8A44356FBF7}.Instrumentation|Win32.ActiveCfg = Release|Win32 {0162C8CE-6641-4922-8664-F8A44356FBF7}.Instrumentation|Win32.Build.0 = Release|Win32 {0162C8CE-6641-4922-8664-F8A44356FBF7}.Instrumentation|x64.ActiveCfg = Release|x64 {0162C8CE-6641-4922-8664-F8A44356FBF7}.Instrumentation|x64.Build.0 = Release|x64 {0162C8CE-6641-4922-8664-F8A44356FBF7}.Release|Any CPU.ActiveCfg = Release|x64 {0162C8CE-6641-4922-8664-F8A44356FBF7}.Release|Any CPU.Build.0 = Release|x64 {0162C8CE-6641-4922-8664-F8A44356FBF7}.Release|ARM.ActiveCfg = Release|x64 {0162C8CE-6641-4922-8664-F8A44356FBF7}.Release|ARM.Build.0 = Release|x64 {0162C8CE-6641-4922-8664-F8A44356FBF7}.Release|Mixed Platforms.ActiveCfg = Release|Win32 {0162C8CE-6641-4922-8664-F8A44356FBF7}.Release|Mixed Platforms.Build.0 = Release|Win32 {0162C8CE-6641-4922-8664-F8A44356FBF7}.Release|Win32.ActiveCfg = Release|Win32 {0162C8CE-6641-4922-8664-F8A44356FBF7}.Release|Win32.Build.0 = Release|Win32 {0162C8CE-6641-4922-8664-F8A44356FBF7}.Release|x64.ActiveCfg = Release|x64 {0162C8CE-6641-4922-8664-F8A44356FBF7}.Release|x64.Build.0 = Release|x64 {D7F2BC4E-1406-47AA-90E1-07BC4CE9410F}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {D7F2BC4E-1406-47AA-90E1-07BC4CE9410F}.Debug|Any CPU.Build.0 = Debug|Any CPU {D7F2BC4E-1406-47AA-90E1-07BC4CE9410F}.Debug|ARM.ActiveCfg = Debug|Any CPU {D7F2BC4E-1406-47AA-90E1-07BC4CE9410F}.Debug|ARM.Build.0 = Debug|Any CPU {D7F2BC4E-1406-47AA-90E1-07BC4CE9410F}.Debug|Mixed Platforms.ActiveCfg = Debug|Any CPU {D7F2BC4E-1406-47AA-90E1-07BC4CE9410F}.Debug|Mixed Platforms.Build.0 = Debug|Any CPU {D7F2BC4E-1406-47AA-90E1-07BC4CE9410F}.Debug|Win32.ActiveCfg = Debug|Any CPU {D7F2BC4E-1406-47AA-90E1-07BC4CE9410F}.Debug|Win32.Build.0 = Debug|Any CPU {D7F2BC4E-1406-47AA-90E1-07BC4CE9410F}.Debug|x64.ActiveCfg = Debug|Any CPU {D7F2BC4E-1406-47AA-90E1-07BC4CE9410F}.Debug|x64.Build.0 = Debug|Any CPU {D7F2BC4E-1406-47AA-90E1-07BC4CE9410F}.Instrumentation|Any CPU.ActiveCfg = Release|Any CPU {D7F2BC4E-1406-47AA-90E1-07BC4CE9410F}.Instrumentation|Any CPU.Build.0 = Release|Any CPU {D7F2BC4E-1406-47AA-90E1-07BC4CE9410F}.Instrumentation|ARM.ActiveCfg = Release|Any CPU {D7F2BC4E-1406-47AA-90E1-07BC4CE9410F}.Instrumentation|ARM.Build.0 = Release|Any CPU {D7F2BC4E-1406-47AA-90E1-07BC4CE9410F}.Instrumentation|Mixed Platforms.ActiveCfg = Release|Any CPU {D7F2BC4E-1406-47AA-90E1-07BC4CE9410F}.Instrumentation|Mixed Platforms.Build.0 = Release|Any CPU {D7F2BC4E-1406-47AA-90E1-07BC4CE9410F}.Instrumentation|Win32.ActiveCfg = Release|Any CPU {D7F2BC4E-1406-47AA-90E1-07BC4CE9410F}.Instrumentation|Win32.Build.0 = Release|Any CPU {D7F2BC4E-1406-47AA-90E1-07BC4CE9410F}.Instrumentation|x64.ActiveCfg = Release|Any CPU {D7F2BC4E-1406-47AA-90E1-07BC4CE9410F}.Instrumentation|x64.Build.0 = Release|Any CPU {D7F2BC4E-1406-47AA-90E1-07BC4CE9410F}.Release|Any CPU.ActiveCfg = Release|Any CPU {D7F2BC4E-1406-47AA-90E1-07BC4CE9410F}.Release|Any CPU.Build.0 = Release|Any CPU {D7F2BC4E-1406-47AA-90E1-07BC4CE9410F}.Release|ARM.ActiveCfg = Release|Any CPU {D7F2BC4E-1406-47AA-90E1-07BC4CE9410F}.Release|ARM.Build.0 = Release|Any CPU {D7F2BC4E-1406-47AA-90E1-07BC4CE9410F}.Release|Mixed Platforms.ActiveCfg = Release|Any CPU {D7F2BC4E-1406-47AA-90E1-07BC4CE9410F}.Release|Mixed Platforms.Build.0 = Release|Any CPU {D7F2BC4E-1406-47AA-90E1-07BC4CE9410F}.Release|Win32.ActiveCfg = Release|Any CPU {D7F2BC4E-1406-47AA-90E1-07BC4CE9410F}.Release|Win32.Build.0 = Release|Any CPU {D7F2BC4E-1406-47AA-90E1-07BC4CE9410F}.Release|x64.ActiveCfg = Release|Any CPU {D7F2BC4E-1406-47AA-90E1-07BC4CE9410F}.Release|x64.Build.0 = Release|Any CPU {6367CACE-0511-485D-9AE5-698F7E600839}.Debug|Any CPU.ActiveCfg = Debug|ARM {6367CACE-0511-485D-9AE5-698F7E600839}.Debug|ARM.ActiveCfg = Debug|ARM {6367CACE-0511-485D-9AE5-698F7E600839}.Debug|Mixed Platforms.ActiveCfg = Debug|ARM {6367CACE-0511-485D-9AE5-698F7E600839}.Debug|Win32.ActiveCfg = Debug|ARM {6367CACE-0511-485D-9AE5-698F7E600839}.Debug|x64.ActiveCfg = Debug|ARM {6367CACE-0511-485D-9AE5-698F7E600839}.Instrumentation|Any CPU.ActiveCfg = Release|ARM {6367CACE-0511-485D-9AE5-698F7E600839}.Instrumentation|ARM.ActiveCfg = Release|ARM {6367CACE-0511-485D-9AE5-698F7E600839}.Instrumentation|Mixed Platforms.ActiveCfg = Release|ARM {6367CACE-0511-485D-9AE5-698F7E600839}.Instrumentation|Win32.ActiveCfg = Release|ARM {6367CACE-0511-485D-9AE5-698F7E600839}.Instrumentation|x64.ActiveCfg = Release|ARM {6367CACE-0511-485D-9AE5-698F7E600839}.Release|Any CPU.ActiveCfg = Release|ARM {6367CACE-0511-485D-9AE5-698F7E600839}.Release|ARM.ActiveCfg = Release|ARM {6367CACE-0511-485D-9AE5-698F7E600839}.Release|Mixed Platforms.ActiveCfg = Release|ARM {6367CACE-0511-485D-9AE5-698F7E600839}.Release|Win32.ActiveCfg = Release|ARM {6367CACE-0511-485D-9AE5-698F7E600839}.Release|x64.ActiveCfg = Release|ARM {016691CA-A31F-4273-A4D2-C5F6E4B3662D}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {016691CA-A31F-4273-A4D2-C5F6E4B3662D}.Debug|Any CPU.Build.0 = Debug|Any CPU {016691CA-A31F-4273-A4D2-C5F6E4B3662D}.Debug|ARM.ActiveCfg = Debug|Any CPU {016691CA-A31F-4273-A4D2-C5F6E4B3662D}.Debug|ARM.Build.0 = Debug|Any CPU {016691CA-A31F-4273-A4D2-C5F6E4B3662D}.Debug|Mixed Platforms.ActiveCfg = Debug|Any CPU {016691CA-A31F-4273-A4D2-C5F6E4B3662D}.Debug|Mixed Platforms.Build.0 = Debug|Any CPU {016691CA-A31F-4273-A4D2-C5F6E4B3662D}.Debug|Win32.ActiveCfg = Debug|Any CPU {016691CA-A31F-4273-A4D2-C5F6E4B3662D}.Debug|Win32.Build.0 = Debug|Any CPU {016691CA-A31F-4273-A4D2-C5F6E4B3662D}.Debug|x64.ActiveCfg = Debug|Any CPU {016691CA-A31F-4273-A4D2-C5F6E4B3662D}.Debug|x64.Build.0 = Debug|Any CPU {016691CA-A31F-4273-A4D2-C5F6E4B3662D}.Instrumentation|Any CPU.ActiveCfg = Instrumentation|Any CPU {016691CA-A31F-4273-A4D2-C5F6E4B3662D}.Instrumentation|Any CPU.Build.0 = Instrumentation|Any CPU {016691CA-A31F-4273-A4D2-C5F6E4B3662D}.Instrumentation|ARM.ActiveCfg = Instrumentation|Any CPU {016691CA-A31F-4273-A4D2-C5F6E4B3662D}.Instrumentation|ARM.Build.0 = Instrumentation|Any CPU {016691CA-A31F-4273-A4D2-C5F6E4B3662D}.Instrumentation|Mixed Platforms.ActiveCfg = Instrumentation|Any CPU {016691CA-A31F-4273-A4D2-C5F6E4B3662D}.Instrumentation|Mixed Platforms.Build.0 = Instrumentation|Any CPU {016691CA-A31F-4273-A4D2-C5F6E4B3662D}.Instrumentation|Win32.ActiveCfg = Instrumentation|Any CPU {016691CA-A31F-4273-A4D2-C5F6E4B3662D}.Instrumentation|Win32.Build.0 = Instrumentation|Any CPU {016691CA-A31F-4273-A4D2-C5F6E4B3662D}.Instrumentation|x64.ActiveCfg = Instrumentation|Any CPU {016691CA-A31F-4273-A4D2-C5F6E4B3662D}.Instrumentation|x64.Build.0 = Instrumentation|Any CPU {016691CA-A31F-4273-A4D2-C5F6E4B3662D}.Release|Any CPU.ActiveCfg = Release|Any CPU {016691CA-A31F-4273-A4D2-C5F6E4B3662D}.Release|Any CPU.Build.0 = Release|Any CPU {016691CA-A31F-4273-A4D2-C5F6E4B3662D}.Release|ARM.ActiveCfg = Release|Any CPU {016691CA-A31F-4273-A4D2-C5F6E4B3662D}.Release|ARM.Build.0 = Release|Any CPU {016691CA-A31F-4273-A4D2-C5F6E4B3662D}.Release|Mixed Platforms.ActiveCfg = Release|Any CPU {016691CA-A31F-4273-A4D2-C5F6E4B3662D}.Release|Mixed Platforms.Build.0 = Release|Any CPU {016691CA-A31F-4273-A4D2-C5F6E4B3662D}.Release|Win32.ActiveCfg = Release|Any CPU {016691CA-A31F-4273-A4D2-C5F6E4B3662D}.Release|Win32.Build.0 = Release|Any CPU {016691CA-A31F-4273-A4D2-C5F6E4B3662D}.Release|x64.ActiveCfg = Release|Any CPU {016691CA-A31F-4273-A4D2-C5F6E4B3662D}.Release|x64.Build.0 = Release|Any CPU {6C581F6A-34F8-4380-9BE0-279F709D13CB}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {6C581F6A-34F8-4380-9BE0-279F709D13CB}.Debug|Any CPU.Build.0 = Debug|Any CPU {6C581F6A-34F8-4380-9BE0-279F709D13CB}.Debug|ARM.ActiveCfg = Debug|Any CPU {6C581F6A-34F8-4380-9BE0-279F709D13CB}.Debug|Mixed Platforms.ActiveCfg = Debug|Any CPU {6C581F6A-34F8-4380-9BE0-279F709D13CB}.Debug|Mixed Platforms.Build.0 = Debug|Any CPU {6C581F6A-34F8-4380-9BE0-279F709D13CB}.Debug|Win32.ActiveCfg = Debug|Any CPU {6C581F6A-34F8-4380-9BE0-279F709D13CB}.Debug|Win32.Build.0 = Debug|Any CPU {6C581F6A-34F8-4380-9BE0-279F709D13CB}.Debug|x64.ActiveCfg = Debug|Any CPU {6C581F6A-34F8-4380-9BE0-279F709D13CB}.Debug|x64.Build.0 = Debug|Any CPU {6C581F6A-34F8-4380-9BE0-279F709D13CB}.Instrumentation|Any CPU.ActiveCfg = Release|Any CPU {6C581F6A-34F8-4380-9BE0-279F709D13CB}.Instrumentation|Any CPU.Build.0 = Release|Any CPU {6C581F6A-34F8-4380-9BE0-279F709D13CB}.Instrumentation|ARM.ActiveCfg = Release|Any CPU {6C581F6A-34F8-4380-9BE0-279F709D13CB}.Instrumentation|ARM.Build.0 = Release|Any CPU {6C581F6A-34F8-4380-9BE0-279F709D13CB}.Instrumentation|Mixed Platforms.ActiveCfg = Release|Any CPU {6C581F6A-34F8-4380-9BE0-279F709D13CB}.Instrumentation|Mixed Platforms.Build.0 = Release|Any CPU {6C581F6A-34F8-4380-9BE0-279F709D13CB}.Instrumentation|Win32.ActiveCfg = Release|Any CPU {6C581F6A-34F8-4380-9BE0-279F709D13CB}.Instrumentation|Win32.Build.0 = Release|Any CPU {6C581F6A-34F8-4380-9BE0-279F709D13CB}.Instrumentation|x64.ActiveCfg = Release|Any CPU {6C581F6A-34F8-4380-9BE0-279F709D13CB}.Instrumentation|x64.Build.0 = Release|Any CPU {6C581F6A-34F8-4380-9BE0-279F709D13CB}.Release|Any CPU.ActiveCfg = Release|Any CPU {6C581F6A-34F8-4380-9BE0-279F709D13CB}.Release|Any CPU.Build.0 = Release|Any CPU {6C581F6A-34F8-4380-9BE0-279F709D13CB}.Release|ARM.ActiveCfg = Release|Any CPU {6C581F6A-34F8-4380-9BE0-279F709D13CB}.Release|ARM.Build.0 = Release|Any CPU {6C581F6A-34F8-4380-9BE0-279F709D13CB}.Release|Mixed Platforms.ActiveCfg = Release|Any CPU {6C581F6A-34F8-4380-9BE0-279F709D13CB}.Release|Mixed Platforms.Build.0 = Release|Any CPU {6C581F6A-34F8-4380-9BE0-279F709D13CB}.Release|Win32.ActiveCfg = Release|Any CPU {6C581F6A-34F8-4380-9BE0-279F709D13CB}.Release|Win32.Build.0 = Release|Any CPU {6C581F6A-34F8-4380-9BE0-279F709D13CB}.Release|x64.ActiveCfg = Release|Any CPU {6C581F6A-34F8-4380-9BE0-279F709D13CB}.Release|x64.Build.0 = Release|Any CPU {D3FA04AF-4285-477D-A756-6C51E9A56E7A}.Debug|Any CPU.ActiveCfg = Debug|ARM {D3FA04AF-4285-477D-A756-6C51E9A56E7A}.Debug|ARM.ActiveCfg = Debug|ARM {D3FA04AF-4285-477D-A756-6C51E9A56E7A}.Debug|ARM.Build.0 = Debug|ARM {D3FA04AF-4285-477D-A756-6C51E9A56E7A}.Debug|ARM.Deploy.0 = Debug|ARM {D3FA04AF-4285-477D-A756-6C51E9A56E7A}.Debug|Mixed Platforms.ActiveCfg = Debug|ARM {D3FA04AF-4285-477D-A756-6C51E9A56E7A}.Debug|Win32.ActiveCfg = Debug|ARM {D3FA04AF-4285-477D-A756-6C51E9A56E7A}.Debug|x64.ActiveCfg = Debug|ARM {D3FA04AF-4285-477D-A756-6C51E9A56E7A}.Instrumentation|Any CPU.ActiveCfg = Release|ARM {D3FA04AF-4285-477D-A756-6C51E9A56E7A}.Instrumentation|ARM.ActiveCfg = Release|ARM {D3FA04AF-4285-477D-A756-6C51E9A56E7A}.Instrumentation|ARM.Build.0 = Release|ARM {D3FA04AF-4285-477D-A756-6C51E9A56E7A}.Instrumentation|ARM.Deploy.0 = Release|ARM {D3FA04AF-4285-477D-A756-6C51E9A56E7A}.Instrumentation|Mixed Platforms.ActiveCfg = Release|ARM {D3FA04AF-4285-477D-A756-6C51E9A56E7A}.Instrumentation|Win32.ActiveCfg = Release|ARM {D3FA04AF-4285-477D-A756-6C51E9A56E7A}.Instrumentation|x64.ActiveCfg = Release|ARM {D3FA04AF-4285-477D-A756-6C51E9A56E7A}.Release|Any CPU.ActiveCfg = Release|ARM {D3FA04AF-4285-477D-A756-6C51E9A56E7A}.Release|ARM.ActiveCfg = Release|ARM {D3FA04AF-4285-477D-A756-6C51E9A56E7A}.Release|ARM.Build.0 = Release|ARM {D3FA04AF-4285-477D-A756-6C51E9A56E7A}.Release|ARM.Deploy.0 = Release|ARM {D3FA04AF-4285-477D-A756-6C51E9A56E7A}.Release|Mixed Platforms.ActiveCfg = Release|ARM {D3FA04AF-4285-477D-A756-6C51E9A56E7A}.Release|Win32.ActiveCfg = Release|ARM {D3FA04AF-4285-477D-A756-6C51E9A56E7A}.Release|x64.ActiveCfg = Release|ARM {0B37E5BA-4839-4EC4-9E36-A96BCBEA2400}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {0B37E5BA-4839-4EC4-9E36-A96BCBEA2400}.Debug|Any CPU.Build.0 = Debug|Any CPU {0B37E5BA-4839-4EC4-9E36-A96BCBEA2400}.Debug|ARM.ActiveCfg = Debug|Any CPU {0B37E5BA-4839-4EC4-9E36-A96BCBEA2400}.Debug|ARM.Build.0 = Debug|Any CPU {0B37E5BA-4839-4EC4-9E36-A96BCBEA2400}.Debug|Mixed Platforms.ActiveCfg = Debug|Any CPU {0B37E5BA-4839-4EC4-9E36-A96BCBEA2400}.Debug|Mixed Platforms.Build.0 = Debug|Any CPU {0B37E5BA-4839-4EC4-9E36-A96BCBEA2400}.Debug|Win32.ActiveCfg = Debug|Any CPU {0B37E5BA-4839-4EC4-9E36-A96BCBEA2400}.Debug|Win32.Build.0 = Debug|Any CPU {0B37E5BA-4839-4EC4-9E36-A96BCBEA2400}.Debug|x64.ActiveCfg = Debug|Any CPU {0B37E5BA-4839-4EC4-9E36-A96BCBEA2400}.Debug|x64.Build.0 = Debug|Any CPU {0B37E5BA-4839-4EC4-9E36-A96BCBEA2400}.Instrumentation|Any CPU.ActiveCfg = Release|Any CPU {0B37E5BA-4839-4EC4-9E36-A96BCBEA2400}.Instrumentation|Any CPU.Build.0 = Release|Any CPU {0B37E5BA-4839-4EC4-9E36-A96BCBEA2400}.Instrumentation|ARM.ActiveCfg = Release|Any CPU {0B37E5BA-4839-4EC4-9E36-A96BCBEA2400}.Instrumentation|ARM.Build.0 = Release|Any CPU {0B37E5BA-4839-4EC4-9E36-A96BCBEA2400}.Instrumentation|Mixed Platforms.ActiveCfg = Release|Any CPU {0B37E5BA-4839-4EC4-9E36-A96BCBEA2400}.Instrumentation|Mixed Platforms.Build.0 = Release|Any CPU {0B37E5BA-4839-4EC4-9E36-A96BCBEA2400}.Instrumentation|Win32.ActiveCfg = Release|Any CPU {0B37E5BA-4839-4EC4-9E36-A96BCBEA2400}.Instrumentation|Win32.Build.0 = Release|Any CPU {0B37E5BA-4839-4EC4-9E36-A96BCBEA2400}.Instrumentation|x64.ActiveCfg = Release|Any CPU {0B37E5BA-4839-4EC4-9E36-A96BCBEA2400}.Instrumentation|x64.Build.0 = Release|Any CPU {0B37E5BA-4839-4EC4-9E36-A96BCBEA2400}.Release|Any CPU.ActiveCfg = Release|Any CPU {0B37E5BA-4839-4EC4-9E36-A96BCBEA2400}.Release|Any CPU.Build.0 = Release|Any CPU {0B37E5BA-4839-4EC4-9E36-A96BCBEA2400}.Release|ARM.ActiveCfg = Release|Any CPU {0B37E5BA-4839-4EC4-9E36-A96BCBEA2400}.Release|ARM.Build.0 = Release|Any CPU {0B37E5BA-4839-4EC4-9E36-A96BCBEA2400}.Release|Mixed Platforms.ActiveCfg = Release|Any CPU {0B37E5BA-4839-4EC4-9E36-A96BCBEA2400}.Release|Mixed Platforms.Build.0 = Release|Any CPU {0B37E5BA-4839-4EC4-9E36-A96BCBEA2400}.Release|Win32.ActiveCfg = Release|Any CPU {0B37E5BA-4839-4EC4-9E36-A96BCBEA2400}.Release|Win32.Build.0 = Release|Any CPU {0B37E5BA-4839-4EC4-9E36-A96BCBEA2400}.Release|x64.ActiveCfg = Release|Any CPU {0B37E5BA-4839-4EC4-9E36-A96BCBEA2400}.Release|x64.Build.0 = Release|Any CPU {0C522C6A-0F77-4AF8-AD78-5B2415C98C51}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {0C522C6A-0F77-4AF8-AD78-5B2415C98C51}.Debug|Any CPU.Build.0 = Debug|Any CPU {0C522C6A-0F77-4AF8-AD78-5B2415C98C51}.Debug|ARM.ActiveCfg = Debug|Any CPU {0C522C6A-0F77-4AF8-AD78-5B2415C98C51}.Debug|ARM.Build.0 = Debug|Any CPU {0C522C6A-0F77-4AF8-AD78-5B2415C98C51}.Debug|Mixed Platforms.ActiveCfg = Debug|Any CPU {0C522C6A-0F77-4AF8-AD78-5B2415C98C51}.Debug|Mixed Platforms.Build.0 = Debug|Any CPU {0C522C6A-0F77-4AF8-AD78-5B2415C98C51}.Debug|Win32.ActiveCfg = Debug|Any CPU {0C522C6A-0F77-4AF8-AD78-5B2415C98C51}.Debug|Win32.Build.0 = Debug|Any CPU {0C522C6A-0F77-4AF8-AD78-5B2415C98C51}.Debug|x64.ActiveCfg = Debug|Any CPU {0C522C6A-0F77-4AF8-AD78-5B2415C98C51}.Debug|x64.Build.0 = Debug|Any CPU {0C522C6A-0F77-4AF8-AD78-5B2415C98C51}.Instrumentation|Any CPU.ActiveCfg = Release|Any CPU {0C522C6A-0F77-4AF8-AD78-5B2415C98C51}.Instrumentation|Any CPU.Build.0 = Release|Any CPU {0C522C6A-0F77-4AF8-AD78-5B2415C98C51}.Instrumentation|ARM.ActiveCfg = Release|Any CPU {0C522C6A-0F77-4AF8-AD78-5B2415C98C51}.Instrumentation|ARM.Build.0 = Release|Any CPU {0C522C6A-0F77-4AF8-AD78-5B2415C98C51}.Instrumentation|Mixed Platforms.ActiveCfg = Release|Any CPU {0C522C6A-0F77-4AF8-AD78-5B2415C98C51}.Instrumentation|Mixed Platforms.Build.0 = Release|Any CPU {0C522C6A-0F77-4AF8-AD78-5B2415C98C51}.Instrumentation|Win32.ActiveCfg = Release|Any CPU {0C522C6A-0F77-4AF8-AD78-5B2415C98C51}.Instrumentation|Win32.Build.0 = Release|Any CPU {0C522C6A-0F77-4AF8-AD78-5B2415C98C51}.Instrumentation|x64.ActiveCfg = Release|Any CPU {0C522C6A-0F77-4AF8-AD78-5B2415C98C51}.Instrumentation|x64.Build.0 = Release|Any CPU {0C522C6A-0F77-4AF8-AD78-5B2415C98C51}.Release|Any CPU.ActiveCfg = Release|Any CPU {0C522C6A-0F77-4AF8-AD78-5B2415C98C51}.Release|Any CPU.Build.0 = Release|Any CPU {0C522C6A-0F77-4AF8-AD78-5B2415C98C51}.Release|ARM.ActiveCfg = Release|Any CPU {0C522C6A-0F77-4AF8-AD78-5B2415C98C51}.Release|ARM.Build.0 = Release|Any CPU {0C522C6A-0F77-4AF8-AD78-5B2415C98C51}.Release|Mixed Platforms.ActiveCfg = Release|Any CPU {0C522C6A-0F77-4AF8-AD78-5B2415C98C51}.Release|Mixed Platforms.Build.0 = Release|Any CPU {0C522C6A-0F77-4AF8-AD78-5B2415C98C51}.Release|Win32.ActiveCfg = Release|Any CPU {0C522C6A-0F77-4AF8-AD78-5B2415C98C51}.Release|Win32.Build.0 = Release|Any CPU {0C522C6A-0F77-4AF8-AD78-5B2415C98C51}.Release|x64.ActiveCfg = Release|Any CPU {0C522C6A-0F77-4AF8-AD78-5B2415C98C51}.Release|x64.Build.0 = Release|Any CPU {A30EB003-94F8-4A85-8DA1-006F6810A7A4}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {A30EB003-94F8-4A85-8DA1-006F6810A7A4}.Debug|Any CPU.Build.0 = Debug|Any CPU {A30EB003-94F8-4A85-8DA1-006F6810A7A4}.Debug|ARM.ActiveCfg = Debug|Any CPU {A30EB003-94F8-4A85-8DA1-006F6810A7A4}.Debug|ARM.Build.0 = Debug|Any CPU {A30EB003-94F8-4A85-8DA1-006F6810A7A4}.Debug|Mixed Platforms.ActiveCfg = Debug|Any CPU {A30EB003-94F8-4A85-8DA1-006F6810A7A4}.Debug|Mixed Platforms.Build.0 = Debug|Any CPU {A30EB003-94F8-4A85-8DA1-006F6810A7A4}.Debug|Win32.ActiveCfg = Debug|Any CPU {A30EB003-94F8-4A85-8DA1-006F6810A7A4}.Debug|Win32.Build.0 = Debug|Any CPU {A30EB003-94F8-4A85-8DA1-006F6810A7A4}.Debug|x64.ActiveCfg = Debug|Any CPU {A30EB003-94F8-4A85-8DA1-006F6810A7A4}.Debug|x64.Build.0 = Debug|Any CPU {A30EB003-94F8-4A85-8DA1-006F6810A7A4}.Instrumentation|Any CPU.ActiveCfg = Instrumentation|Any CPU {A30EB003-94F8-4A85-8DA1-006F6810A7A4}.Instrumentation|Any CPU.Build.0 = Instrumentation|Any CPU {A30EB003-94F8-4A85-8DA1-006F6810A7A4}.Instrumentation|ARM.ActiveCfg = Instrumentation|Any CPU {A30EB003-94F8-4A85-8DA1-006F6810A7A4}.Instrumentation|ARM.Build.0 = Instrumentation|Any CPU {A30EB003-94F8-4A85-8DA1-006F6810A7A4}.Instrumentation|Mixed Platforms.ActiveCfg = Instrumentation|Any CPU {A30EB003-94F8-4A85-8DA1-006F6810A7A4}.Instrumentation|Mixed Platforms.Build.0 = Instrumentation|Any CPU {A30EB003-94F8-4A85-8DA1-006F6810A7A4}.Instrumentation|Win32.ActiveCfg = Instrumentation|Any CPU {A30EB003-94F8-4A85-8DA1-006F6810A7A4}.Instrumentation|Win32.Build.0 = Instrumentation|Any CPU {A30EB003-94F8-4A85-8DA1-006F6810A7A4}.Instrumentation|x64.ActiveCfg = Instrumentation|Any CPU {A30EB003-94F8-4A85-8DA1-006F6810A7A4}.Instrumentation|x64.Build.0 = Instrumentation|Any CPU {A30EB003-94F8-4A85-8DA1-006F6810A7A4}.Release|Any CPU.ActiveCfg = Release|Any CPU {A30EB003-94F8-4A85-8DA1-006F6810A7A4}.Release|Any CPU.Build.0 = Release|Any CPU {A30EB003-94F8-4A85-8DA1-006F6810A7A4}.Release|ARM.ActiveCfg = Release|Any CPU {A30EB003-94F8-4A85-8DA1-006F6810A7A4}.Release|ARM.Build.0 = Release|Any CPU {A30EB003-94F8-4A85-8DA1-006F6810A7A4}.Release|Mixed Platforms.ActiveCfg = Release|Any CPU {A30EB003-94F8-4A85-8DA1-006F6810A7A4}.Release|Mixed Platforms.Build.0 = Release|Any CPU {A30EB003-94F8-4A85-8DA1-006F6810A7A4}.Release|Win32.ActiveCfg = Release|Any CPU {A30EB003-94F8-4A85-8DA1-006F6810A7A4}.Release|Win32.Build.0 = Release|Any CPU {A30EB003-94F8-4A85-8DA1-006F6810A7A4}.Release|x64.ActiveCfg = Release|Any CPU {A30EB003-94F8-4A85-8DA1-006F6810A7A4}.Release|x64.Build.0 = Release|Any CPU {7FB3F581-742D-4E12-A36A-BE172C574AB0}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {7FB3F581-742D-4E12-A36A-BE172C574AB0}.Debug|Any CPU.Build.0 = Debug|Any CPU {7FB3F581-742D-4E12-A36A-BE172C574AB0}.Debug|ARM.ActiveCfg = Debug|Any CPU {7FB3F581-742D-4E12-A36A-BE172C574AB0}.Debug|ARM.Build.0 = Debug|Any CPU {7FB3F581-742D-4E12-A36A-BE172C574AB0}.Debug|Mixed Platforms.ActiveCfg = Debug|Any CPU {7FB3F581-742D-4E12-A36A-BE172C574AB0}.Debug|Mixed Platforms.Build.0 = Debug|Any CPU {7FB3F581-742D-4E12-A36A-BE172C574AB0}.Debug|Win32.ActiveCfg = Debug|Any CPU {7FB3F581-742D-4E12-A36A-BE172C574AB0}.Debug|Win32.Build.0 = Debug|Any CPU {7FB3F581-742D-4E12-A36A-BE172C574AB0}.Debug|x64.ActiveCfg = Debug|Any CPU {7FB3F581-742D-4E12-A36A-BE172C574AB0}.Debug|x64.Build.0 = Debug|Any CPU {7FB3F581-742D-4E12-A36A-BE172C574AB0}.Instrumentation|Any CPU.ActiveCfg = Release|Any CPU {7FB3F581-742D-4E12-A36A-BE172C574AB0}.Instrumentation|Any CPU.Build.0 = Release|Any CPU {7FB3F581-742D-4E12-A36A-BE172C574AB0}.Instrumentation|ARM.ActiveCfg = Release|Any CPU {7FB3F581-742D-4E12-A36A-BE172C574AB0}.Instrumentation|ARM.Build.0 = Release|Any CPU {7FB3F581-742D-4E12-A36A-BE172C574AB0}.Instrumentation|Mixed Platforms.ActiveCfg = Release|Any CPU {7FB3F581-742D-4E12-A36A-BE172C574AB0}.Instrumentation|Mixed Platforms.Build.0 = Release|Any CPU {7FB3F581-742D-4E12-A36A-BE172C574AB0}.Instrumentation|Win32.ActiveCfg = Release|Any CPU {7FB3F581-742D-4E12-A36A-BE172C574AB0}.Instrumentation|Win32.Build.0 = Release|Any CPU {7FB3F581-742D-4E12-A36A-BE172C574AB0}.Instrumentation|x64.ActiveCfg = Release|Any CPU {7FB3F581-742D-4E12-A36A-BE172C574AB0}.Instrumentation|x64.Build.0 = Release|Any CPU {7FB3F581-742D-4E12-A36A-BE172C574AB0}.Release|Any CPU.ActiveCfg = Release|Any CPU {7FB3F581-742D-4E12-A36A-BE172C574AB0}.Release|Any CPU.Build.0 = Release|Any CPU {7FB3F581-742D-4E12-A36A-BE172C574AB0}.Release|ARM.ActiveCfg = Release|Any CPU {7FB3F581-742D-4E12-A36A-BE172C574AB0}.Release|ARM.Build.0 = Release|Any CPU {7FB3F581-742D-4E12-A36A-BE172C574AB0}.Release|Mixed Platforms.ActiveCfg = Release|Any CPU {7FB3F581-742D-4E12-A36A-BE172C574AB0}.Release|Mixed Platforms.Build.0 = Release|Any CPU {7FB3F581-742D-4E12-A36A-BE172C574AB0}.Release|Win32.ActiveCfg = Release|Any CPU {7FB3F581-742D-4E12-A36A-BE172C574AB0}.Release|Win32.Build.0 = Release|Any CPU {7FB3F581-742D-4E12-A36A-BE172C574AB0}.Release|x64.ActiveCfg = Release|Any CPU {7FB3F581-742D-4E12-A36A-BE172C574AB0}.Release|x64.Build.0 = Release|Any CPU {65C8EDA6-AC24-4E18-A5B5-216E0F2C3906}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {65C8EDA6-AC24-4E18-A5B5-216E0F2C3906}.Debug|Any CPU.Build.0 = Debug|Any CPU {65C8EDA6-AC24-4E18-A5B5-216E0F2C3906}.Debug|ARM.ActiveCfg = Debug|Any CPU {65C8EDA6-AC24-4E18-A5B5-216E0F2C3906}.Debug|ARM.Build.0 = Debug|Any CPU {65C8EDA6-AC24-4E18-A5B5-216E0F2C3906}.Debug|Mixed Platforms.ActiveCfg = Debug|Any CPU {65C8EDA6-AC24-4E18-A5B5-216E0F2C3906}.Debug|Mixed Platforms.Build.0 = Debug|Any CPU {65C8EDA6-AC24-4E18-A5B5-216E0F2C3906}.Debug|Win32.ActiveCfg = Debug|Any CPU {65C8EDA6-AC24-4E18-A5B5-216E0F2C3906}.Debug|Win32.Build.0 = Debug|Any CPU {65C8EDA6-AC24-4E18-A5B5-216E0F2C3906}.Debug|x64.ActiveCfg = Debug|Any CPU {65C8EDA6-AC24-4E18-A5B5-216E0F2C3906}.Debug|x64.Build.0 = Debug|Any CPU {65C8EDA6-AC24-4E18-A5B5-216E0F2C3906}.Instrumentation|Any CPU.ActiveCfg = Release|Any CPU {65C8EDA6-AC24-4E18-A5B5-216E0F2C3906}.Instrumentation|Any CPU.Build.0 = Release|Any CPU {65C8EDA6-AC24-4E18-A5B5-216E0F2C3906}.Instrumentation|ARM.ActiveCfg = Release|Any CPU {65C8EDA6-AC24-4E18-A5B5-216E0F2C3906}.Instrumentation|ARM.Build.0 = Release|Any CPU {65C8EDA6-AC24-4E18-A5B5-216E0F2C3906}.Instrumentation|Mixed Platforms.ActiveCfg = Release|Any CPU {65C8EDA6-AC24-4E18-A5B5-216E0F2C3906}.Instrumentation|Mixed Platforms.Build.0 = Release|Any CPU {65C8EDA6-AC24-4E18-A5B5-216E0F2C3906}.Instrumentation|Win32.ActiveCfg = Release|Any CPU {65C8EDA6-AC24-4E18-A5B5-216E0F2C3906}.Instrumentation|Win32.Build.0 = Release|Any CPU {65C8EDA6-AC24-4E18-A5B5-216E0F2C3906}.Instrumentation|x64.ActiveCfg = Release|Any CPU {65C8EDA6-AC24-4E18-A5B5-216E0F2C3906}.Instrumentation|x64.Build.0 = Release|Any CPU {65C8EDA6-AC24-4E18-A5B5-216E0F2C3906}.Release|Any CPU.ActiveCfg = Release|Any CPU {65C8EDA6-AC24-4E18-A5B5-216E0F2C3906}.Release|Any CPU.Build.0 = Release|Any CPU {65C8EDA6-AC24-4E18-A5B5-216E0F2C3906}.Release|ARM.ActiveCfg = Release|Any CPU {65C8EDA6-AC24-4E18-A5B5-216E0F2C3906}.Release|ARM.Build.0 = Release|Any CPU {65C8EDA6-AC24-4E18-A5B5-216E0F2C3906}.Release|Mixed Platforms.ActiveCfg = Release|Any CPU {65C8EDA6-AC24-4E18-A5B5-216E0F2C3906}.Release|Mixed Platforms.Build.0 = Release|Any CPU {65C8EDA6-AC24-4E18-A5B5-216E0F2C3906}.Release|Win32.ActiveCfg = Release|Any CPU {65C8EDA6-AC24-4E18-A5B5-216E0F2C3906}.Release|Win32.Build.0 = Release|Any CPU {65C8EDA6-AC24-4E18-A5B5-216E0F2C3906}.Release|x64.ActiveCfg = Release|Any CPU {65C8EDA6-AC24-4E18-A5B5-216E0F2C3906}.Release|x64.Build.0 = Release|Any CPU {CA8A6D38-528B-4FAA-89B6-8FA9178DE55D}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {CA8A6D38-528B-4FAA-89B6-8FA9178DE55D}.Debug|Any CPU.Build.0 = Debug|Any CPU {CA8A6D38-528B-4FAA-89B6-8FA9178DE55D}.Debug|ARM.ActiveCfg = Debug|Any CPU {CA8A6D38-528B-4FAA-89B6-8FA9178DE55D}.Debug|ARM.Build.0 = Debug|Any CPU {CA8A6D38-528B-4FAA-89B6-8FA9178DE55D}.Debug|Mixed Platforms.ActiveCfg = Debug|Any CPU {CA8A6D38-528B-4FAA-89B6-8FA9178DE55D}.Debug|Mixed Platforms.Build.0 = Debug|Any CPU {CA8A6D38-528B-4FAA-89B6-8FA9178DE55D}.Debug|Win32.ActiveCfg = Debug|Any CPU {CA8A6D38-528B-4FAA-89B6-8FA9178DE55D}.Debug|Win32.Build.0 = Debug|Any CPU {CA8A6D38-528B-4FAA-89B6-8FA9178DE55D}.Debug|x64.ActiveCfg = Debug|Any CPU {CA8A6D38-528B-4FAA-89B6-8FA9178DE55D}.Debug|x64.Build.0 = Debug|Any CPU {CA8A6D38-528B-4FAA-89B6-8FA9178DE55D}.Instrumentation|Any CPU.ActiveCfg = Instrumentation|Any CPU {CA8A6D38-528B-4FAA-89B6-8FA9178DE55D}.Instrumentation|Any CPU.Build.0 = Instrumentation|Any CPU {CA8A6D38-528B-4FAA-89B6-8FA9178DE55D}.Instrumentation|ARM.ActiveCfg = Instrumentation|Any CPU {CA8A6D38-528B-4FAA-89B6-8FA9178DE55D}.Instrumentation|ARM.Build.0 = Instrumentation|Any CPU {CA8A6D38-528B-4FAA-89B6-8FA9178DE55D}.Instrumentation|Mixed Platforms.ActiveCfg = Instrumentation|Any CPU {CA8A6D38-528B-4FAA-89B6-8FA9178DE55D}.Instrumentation|Mixed Platforms.Build.0 = Instrumentation|Any CPU {CA8A6D38-528B-4FAA-89B6-8FA9178DE55D}.Instrumentation|Win32.ActiveCfg = Instrumentation|Any CPU {CA8A6D38-528B-4FAA-89B6-8FA9178DE55D}.Instrumentation|Win32.Build.0 = Instrumentation|Any CPU {CA8A6D38-528B-4FAA-89B6-8FA9178DE55D}.Instrumentation|x64.ActiveCfg = Instrumentation|Any CPU {CA8A6D38-528B-4FAA-89B6-8FA9178DE55D}.Instrumentation|x64.Build.0 = Instrumentation|Any CPU {CA8A6D38-528B-4FAA-89B6-8FA9178DE55D}.Release|Any CPU.ActiveCfg = Release|Any CPU {CA8A6D38-528B-4FAA-89B6-8FA9178DE55D}.Release|Any CPU.Build.0 = Release|Any CPU {CA8A6D38-528B-4FAA-89B6-8FA9178DE55D}.Release|ARM.ActiveCfg = Release|Any CPU {CA8A6D38-528B-4FAA-89B6-8FA9178DE55D}.Release|ARM.Build.0 = Release|Any CPU {CA8A6D38-528B-4FAA-89B6-8FA9178DE55D}.Release|Mixed Platforms.ActiveCfg = Release|Any CPU {CA8A6D38-528B-4FAA-89B6-8FA9178DE55D}.Release|Mixed Platforms.Build.0 = Release|Any CPU {CA8A6D38-528B-4FAA-89B6-8FA9178DE55D}.Release|Win32.ActiveCfg = Release|Any CPU {CA8A6D38-528B-4FAA-89B6-8FA9178DE55D}.Release|Win32.Build.0 = Release|Any CPU {CA8A6D38-528B-4FAA-89B6-8FA9178DE55D}.Release|x64.ActiveCfg = Release|Any CPU {CA8A6D38-528B-4FAA-89B6-8FA9178DE55D}.Release|x64.Build.0 = Release|Any CPU {D68EE51B-A898-4A77-97D8-C61254CAC122}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {D68EE51B-A898-4A77-97D8-C61254CAC122}.Debug|Any CPU.Build.0 = Debug|Any CPU {D68EE51B-A898-4A77-97D8-C61254CAC122}.Debug|ARM.ActiveCfg = Debug|Any CPU {D68EE51B-A898-4A77-97D8-C61254CAC122}.Debug|ARM.Build.0 = Debug|Any CPU {D68EE51B-A898-4A77-97D8-C61254CAC122}.Debug|Mixed Platforms.ActiveCfg = Debug|Any CPU {D68EE51B-A898-4A77-97D8-C61254CAC122}.Debug|Mixed Platforms.Build.0 = Debug|Any CPU {D68EE51B-A898-4A77-97D8-C61254CAC122}.Debug|Win32.ActiveCfg = Debug|Any CPU {D68EE51B-A898-4A77-97D8-C61254CAC122}.Debug|Win32.Build.0 = Debug|Any CPU {D68EE51B-A898-4A77-97D8-C61254CAC122}.Debug|x64.ActiveCfg = Debug|Any CPU {D68EE51B-A898-4A77-97D8-C61254CAC122}.Debug|x64.Build.0 = Debug|Any CPU {D68EE51B-A898-4A77-97D8-C61254CAC122}.Instrumentation|Any CPU.ActiveCfg = Release|Any CPU {D68EE51B-A898-4A77-97D8-C61254CAC122}.Instrumentation|Any CPU.Build.0 = Release|Any CPU {D68EE51B-A898-4A77-97D8-C61254CAC122}.Instrumentation|ARM.ActiveCfg = Release|Any CPU {D68EE51B-A898-4A77-97D8-C61254CAC122}.Instrumentation|ARM.Build.0 = Release|Any CPU {D68EE51B-A898-4A77-97D8-C61254CAC122}.Instrumentation|Mixed Platforms.ActiveCfg = Release|Any CPU {D68EE51B-A898-4A77-97D8-C61254CAC122}.Instrumentation|Mixed Platforms.Build.0 = Release|Any CPU {D68EE51B-A898-4A77-97D8-C61254CAC122}.Instrumentation|Win32.ActiveCfg = Release|Any CPU {D68EE51B-A898-4A77-97D8-C61254CAC122}.Instrumentation|Win32.Build.0 = Release|Any CPU {D68EE51B-A898-4A77-97D8-C61254CAC122}.Instrumentation|x64.ActiveCfg = Release|Any CPU {D68EE51B-A898-4A77-97D8-C61254CAC122}.Instrumentation|x64.Build.0 = Release|Any CPU {D68EE51B-A898-4A77-97D8-C61254CAC122}.Release|Any CPU.ActiveCfg = Release|Any CPU {D68EE51B-A898-4A77-97D8-C61254CAC122}.Release|Any CPU.Build.0 = Release|Any CPU {D68EE51B-A898-4A77-97D8-C61254CAC122}.Release|ARM.ActiveCfg = Release|Any CPU {D68EE51B-A898-4A77-97D8-C61254CAC122}.Release|ARM.Build.0 = Release|Any CPU {D68EE51B-A898-4A77-97D8-C61254CAC122}.Release|Mixed Platforms.ActiveCfg = Release|Any CPU {D68EE51B-A898-4A77-97D8-C61254CAC122}.Release|Mixed Platforms.Build.0 = Release|Any CPU {D68EE51B-A898-4A77-97D8-C61254CAC122}.Release|Win32.ActiveCfg = Release|Any CPU {D68EE51B-A898-4A77-97D8-C61254CAC122}.Release|Win32.Build.0 = Release|Any CPU {D68EE51B-A898-4A77-97D8-C61254CAC122}.Release|x64.ActiveCfg = Release|Any CPU {D68EE51B-A898-4A77-97D8-C61254CAC122}.Release|x64.Build.0 = Release|Any CPU {1AE58C3F-0319-4B7E-9E48-7A7BEBC2E3A5}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {1AE58C3F-0319-4B7E-9E48-7A7BEBC2E3A5}.Debug|Any CPU.Build.0 = Debug|Any CPU {1AE58C3F-0319-4B7E-9E48-7A7BEBC2E3A5}.Debug|ARM.ActiveCfg = Debug|Any CPU {1AE58C3F-0319-4B7E-9E48-7A7BEBC2E3A5}.Debug|ARM.Build.0 = Debug|Any CPU {1AE58C3F-0319-4B7E-9E48-7A7BEBC2E3A5}.Debug|Mixed Platforms.ActiveCfg = Debug|Any CPU {1AE58C3F-0319-4B7E-9E48-7A7BEBC2E3A5}.Debug|Mixed Platforms.Build.0 = Debug|Any CPU {1AE58C3F-0319-4B7E-9E48-7A7BEBC2E3A5}.Debug|Win32.ActiveCfg = Debug|Any CPU {1AE58C3F-0319-4B7E-9E48-7A7BEBC2E3A5}.Debug|Win32.Build.0 = Debug|Any CPU {1AE58C3F-0319-4B7E-9E48-7A7BEBC2E3A5}.Debug|x64.ActiveCfg = Debug|Any CPU {1AE58C3F-0319-4B7E-9E48-7A7BEBC2E3A5}.Debug|x64.Build.0 = Debug|Any CPU {1AE58C3F-0319-4B7E-9E48-7A7BEBC2E3A5}.Instrumentation|Any CPU.ActiveCfg = Release|Any CPU {1AE58C3F-0319-4B7E-9E48-7A7BEBC2E3A5}.Instrumentation|Any CPU.Build.0 = Release|Any CPU {1AE58C3F-0319-4B7E-9E48-7A7BEBC2E3A5}.Instrumentation|ARM.ActiveCfg = Release|Any CPU {1AE58C3F-0319-4B7E-9E48-7A7BEBC2E3A5}.Instrumentation|ARM.Build.0 = Release|Any CPU {1AE58C3F-0319-4B7E-9E48-7A7BEBC2E3A5}.Instrumentation|Mixed Platforms.ActiveCfg = Release|Any CPU {1AE58C3F-0319-4B7E-9E48-7A7BEBC2E3A5}.Instrumentation|Mixed Platforms.Build.0 = Release|Any CPU {1AE58C3F-0319-4B7E-9E48-7A7BEBC2E3A5}.Instrumentation|Win32.ActiveCfg = Release|Any CPU {1AE58C3F-0319-4B7E-9E48-7A7BEBC2E3A5}.Instrumentation|Win32.Build.0 = Release|Any CPU {1AE58C3F-0319-4B7E-9E48-7A7BEBC2E3A5}.Instrumentation|x64.ActiveCfg = Release|Any CPU {1AE58C3F-0319-4B7E-9E48-7A7BEBC2E3A5}.Instrumentation|x64.Build.0 = Release|Any CPU {1AE58C3F-0319-4B7E-9E48-7A7BEBC2E3A5}.Release|Any CPU.ActiveCfg = Release|Any CPU {1AE58C3F-0319-4B7E-9E48-7A7BEBC2E3A5}.Release|Any CPU.Build.0 = Release|Any CPU {1AE58C3F-0319-4B7E-9E48-7A7BEBC2E3A5}.Release|ARM.ActiveCfg = Release|Any CPU {1AE58C3F-0319-4B7E-9E48-7A7BEBC2E3A5}.Release|ARM.Build.0 = Release|Any CPU {1AE58C3F-0319-4B7E-9E48-7A7BEBC2E3A5}.Release|Mixed Platforms.ActiveCfg = Release|Any CPU {1AE58C3F-0319-4B7E-9E48-7A7BEBC2E3A5}.Release|Mixed Platforms.Build.0 = Release|Any CPU {1AE58C3F-0319-4B7E-9E48-7A7BEBC2E3A5}.Release|Win32.ActiveCfg = Release|Any CPU {1AE58C3F-0319-4B7E-9E48-7A7BEBC2E3A5}.Release|Win32.Build.0 = Release|Any CPU {1AE58C3F-0319-4B7E-9E48-7A7BEBC2E3A5}.Release|x64.ActiveCfg = Release|Any CPU {1AE58C3F-0319-4B7E-9E48-7A7BEBC2E3A5}.Release|x64.Build.0 = Release|Any CPU {91FF2862-C6E5-45BB-B399-8E363E40361C}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {91FF2862-C6E5-45BB-B399-8E363E40361C}.Debug|Any CPU.Build.0 = Debug|Any CPU {91FF2862-C6E5-45BB-B399-8E363E40361C}.Debug|ARM.ActiveCfg = Debug|Any CPU {91FF2862-C6E5-45BB-B399-8E363E40361C}.Debug|ARM.Build.0 = Debug|Any CPU {91FF2862-C6E5-45BB-B399-8E363E40361C}.Debug|Mixed Platforms.ActiveCfg = Debug|Any CPU {91FF2862-C6E5-45BB-B399-8E363E40361C}.Debug|Mixed Platforms.Build.0 = Debug|Any CPU {91FF2862-C6E5-45BB-B399-8E363E40361C}.Debug|Win32.ActiveCfg = Debug|Any CPU {91FF2862-C6E5-45BB-B399-8E363E40361C}.Debug|Win32.Build.0 = Debug|Any CPU {91FF2862-C6E5-45BB-B399-8E363E40361C}.Debug|x64.ActiveCfg = Debug|Any CPU {91FF2862-C6E5-45BB-B399-8E363E40361C}.Debug|x64.Build.0 = Debug|Any CPU {91FF2862-C6E5-45BB-B399-8E363E40361C}.Instrumentation|Any CPU.ActiveCfg = Release|Any CPU {91FF2862-C6E5-45BB-B399-8E363E40361C}.Instrumentation|Any CPU.Build.0 = Release|Any CPU {91FF2862-C6E5-45BB-B399-8E363E40361C}.Instrumentation|ARM.ActiveCfg = Release|Any CPU {91FF2862-C6E5-45BB-B399-8E363E40361C}.Instrumentation|ARM.Build.0 = Release|Any CPU {91FF2862-C6E5-45BB-B399-8E363E40361C}.Instrumentation|Mixed Platforms.ActiveCfg = Release|Any CPU {91FF2862-C6E5-45BB-B399-8E363E40361C}.Instrumentation|Mixed Platforms.Build.0 = Release|Any CPU {91FF2862-C6E5-45BB-B399-8E363E40361C}.Instrumentation|Win32.ActiveCfg = Release|Any CPU {91FF2862-C6E5-45BB-B399-8E363E40361C}.Instrumentation|Win32.Build.0 = Release|Any CPU {91FF2862-C6E5-45BB-B399-8E363E40361C}.Instrumentation|x64.ActiveCfg = Release|Any CPU {91FF2862-C6E5-45BB-B399-8E363E40361C}.Instrumentation|x64.Build.0 = Release|Any CPU {91FF2862-C6E5-45BB-B399-8E363E40361C}.Release|Any CPU.ActiveCfg = Release|Any CPU {91FF2862-C6E5-45BB-B399-8E363E40361C}.Release|Any CPU.Build.0 = Release|Any CPU {91FF2862-C6E5-45BB-B399-8E363E40361C}.Release|ARM.ActiveCfg = Release|Any CPU {91FF2862-C6E5-45BB-B399-8E363E40361C}.Release|ARM.Build.0 = Release|Any CPU {91FF2862-C6E5-45BB-B399-8E363E40361C}.Release|Mixed Platforms.ActiveCfg = Release|Any CPU {91FF2862-C6E5-45BB-B399-8E363E40361C}.Release|Mixed Platforms.Build.0 = Release|Any CPU {91FF2862-C6E5-45BB-B399-8E363E40361C}.Release|Win32.ActiveCfg = Release|Any CPU {91FF2862-C6E5-45BB-B399-8E363E40361C}.Release|Win32.Build.0 = Release|Any CPU {91FF2862-C6E5-45BB-B399-8E363E40361C}.Release|x64.ActiveCfg = Release|Any CPU {91FF2862-C6E5-45BB-B399-8E363E40361C}.Release|x64.Build.0 = Release|Any CPU {1705887B-E636-4FA3-AE40-2D431AF1511C}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {1705887B-E636-4FA3-AE40-2D431AF1511C}.Debug|Any CPU.Build.0 = Debug|Any CPU {1705887B-E636-4FA3-AE40-2D431AF1511C}.Debug|ARM.ActiveCfg = Debug|Any CPU {1705887B-E636-4FA3-AE40-2D431AF1511C}.Debug|ARM.Build.0 = Debug|Any CPU {1705887B-E636-4FA3-AE40-2D431AF1511C}.Debug|Mixed Platforms.ActiveCfg = Debug|Any CPU {1705887B-E636-4FA3-AE40-2D431AF1511C}.Debug|Mixed Platforms.Build.0 = Debug|Any CPU {1705887B-E636-4FA3-AE40-2D431AF1511C}.Debug|Win32.ActiveCfg = Debug|Any CPU {1705887B-E636-4FA3-AE40-2D431AF1511C}.Debug|Win32.Build.0 = Debug|Any CPU {1705887B-E636-4FA3-AE40-2D431AF1511C}.Debug|x64.ActiveCfg = Debug|Any CPU {1705887B-E636-4FA3-AE40-2D431AF1511C}.Debug|x64.Build.0 = Debug|Any CPU {1705887B-E636-4FA3-AE40-2D431AF1511C}.Instrumentation|Any CPU.ActiveCfg = Release|Any CPU {1705887B-E636-4FA3-AE40-2D431AF1511C}.Instrumentation|Any CPU.Build.0 = Release|Any CPU {1705887B-E636-4FA3-AE40-2D431AF1511C}.Instrumentation|ARM.ActiveCfg = Release|Any CPU {1705887B-E636-4FA3-AE40-2D431AF1511C}.Instrumentation|ARM.Build.0 = Release|Any CPU {1705887B-E636-4FA3-AE40-2D431AF1511C}.Instrumentation|Mixed Platforms.ActiveCfg = Release|Any CPU {1705887B-E636-4FA3-AE40-2D431AF1511C}.Instrumentation|Mixed Platforms.Build.0 = Release|Any CPU {1705887B-E636-4FA3-AE40-2D431AF1511C}.Instrumentation|Win32.ActiveCfg = Release|Any CPU {1705887B-E636-4FA3-AE40-2D431AF1511C}.Instrumentation|Win32.Build.0 = Release|Any CPU {1705887B-E636-4FA3-AE40-2D431AF1511C}.Instrumentation|x64.ActiveCfg = Release|Any CPU {1705887B-E636-4FA3-AE40-2D431AF1511C}.Instrumentation|x64.Build.0 = Release|Any CPU {1705887B-E636-4FA3-AE40-2D431AF1511C}.Release|Any CPU.ActiveCfg = Release|Any CPU {1705887B-E636-4FA3-AE40-2D431AF1511C}.Release|Any CPU.Build.0 = Release|Any CPU {1705887B-E636-4FA3-AE40-2D431AF1511C}.Release|ARM.ActiveCfg = Release|Any CPU {1705887B-E636-4FA3-AE40-2D431AF1511C}.Release|ARM.Build.0 = Release|Any CPU {1705887B-E636-4FA3-AE40-2D431AF1511C}.Release|Mixed Platforms.ActiveCfg = Release|Any CPU {1705887B-E636-4FA3-AE40-2D431AF1511C}.Release|Mixed Platforms.Build.0 = Release|Any CPU {1705887B-E636-4FA3-AE40-2D431AF1511C}.Release|Win32.ActiveCfg = Release|Any CPU {1705887B-E636-4FA3-AE40-2D431AF1511C}.Release|Win32.Build.0 = Release|Any CPU {1705887B-E636-4FA3-AE40-2D431AF1511C}.Release|x64.ActiveCfg = Release|Any CPU {1705887B-E636-4FA3-AE40-2D431AF1511C}.Release|x64.Build.0 = Release|Any CPU {CEE4D575-4B4B-42B0-B2F1-CC7198CB7306}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {CEE4D575-4B4B-42B0-B2F1-CC7198CB7306}.Debug|Any CPU.Build.0 = Debug|Any CPU {CEE4D575-4B4B-42B0-B2F1-CC7198CB7306}.Debug|ARM.ActiveCfg = Debug|Any CPU {CEE4D575-4B4B-42B0-B2F1-CC7198CB7306}.Debug|ARM.Build.0 = Debug|Any CPU {CEE4D575-4B4B-42B0-B2F1-CC7198CB7306}.Debug|Mixed Platforms.ActiveCfg = Debug|Any CPU {CEE4D575-4B4B-42B0-B2F1-CC7198CB7306}.Debug|Mixed Platforms.Build.0 = Debug|Any CPU {CEE4D575-4B4B-42B0-B2F1-CC7198CB7306}.Debug|Win32.ActiveCfg = Debug|Any CPU {CEE4D575-4B4B-42B0-B2F1-CC7198CB7306}.Debug|Win32.Build.0 = Debug|Any CPU {CEE4D575-4B4B-42B0-B2F1-CC7198CB7306}.Debug|x64.ActiveCfg = Debug|Any CPU {CEE4D575-4B4B-42B0-B2F1-CC7198CB7306}.Debug|x64.Build.0 = Debug|Any CPU {CEE4D575-4B4B-42B0-B2F1-CC7198CB7306}.Instrumentation|Any CPU.ActiveCfg = Release|Any CPU {CEE4D575-4B4B-42B0-B2F1-CC7198CB7306}.Instrumentation|Any CPU.Build.0 = Release|Any CPU {CEE4D575-4B4B-42B0-B2F1-CC7198CB7306}.Instrumentation|ARM.ActiveCfg = Release|Any CPU {CEE4D575-4B4B-42B0-B2F1-CC7198CB7306}.Instrumentation|ARM.Build.0 = Release|Any CPU {CEE4D575-4B4B-42B0-B2F1-CC7198CB7306}.Instrumentation|Mixed Platforms.ActiveCfg = Release|Any CPU {CEE4D575-4B4B-42B0-B2F1-CC7198CB7306}.Instrumentation|Mixed Platforms.Build.0 = Release|Any CPU {CEE4D575-4B4B-42B0-B2F1-CC7198CB7306}.Instrumentation|Win32.ActiveCfg = Release|Any CPU {CEE4D575-4B4B-42B0-B2F1-CC7198CB7306}.Instrumentation|Win32.Build.0 = Release|Any CPU {CEE4D575-4B4B-42B0-B2F1-CC7198CB7306}.Instrumentation|x64.ActiveCfg = Release|Any CPU {CEE4D575-4B4B-42B0-B2F1-CC7198CB7306}.Instrumentation|x64.Build.0 = Release|Any CPU {CEE4D575-4B4B-42B0-B2F1-CC7198CB7306}.Release|Any CPU.ActiveCfg = Release|Any CPU {CEE4D575-4B4B-42B0-B2F1-CC7198CB7306}.Release|Any CPU.Build.0 = Release|Any CPU {CEE4D575-4B4B-42B0-B2F1-CC7198CB7306}.Release|ARM.ActiveCfg = Release|Any CPU {CEE4D575-4B4B-42B0-B2F1-CC7198CB7306}.Release|ARM.Build.0 = Release|Any CPU {CEE4D575-4B4B-42B0-B2F1-CC7198CB7306}.Release|Mixed Platforms.ActiveCfg = Release|Any CPU {CEE4D575-4B4B-42B0-B2F1-CC7198CB7306}.Release|Mixed Platforms.Build.0 = Release|Any CPU {CEE4D575-4B4B-42B0-B2F1-CC7198CB7306}.Release|Win32.ActiveCfg = Release|Any CPU {CEE4D575-4B4B-42B0-B2F1-CC7198CB7306}.Release|Win32.Build.0 = Release|Any CPU {CEE4D575-4B4B-42B0-B2F1-CC7198CB7306}.Release|x64.ActiveCfg = Release|Any CPU {CEE4D575-4B4B-42B0-B2F1-CC7198CB7306}.Release|x64.Build.0 = Release|Any CPU {DC8C38D7-780B-4B13-8ACE-9050E39CC51C}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {DC8C38D7-780B-4B13-8ACE-9050E39CC51C}.Debug|Any CPU.Build.0 = Debug|Any CPU {DC8C38D7-780B-4B13-8ACE-9050E39CC51C}.Debug|ARM.ActiveCfg = Debug|Any CPU {DC8C38D7-780B-4B13-8ACE-9050E39CC51C}.Debug|ARM.Build.0 = Debug|Any CPU {DC8C38D7-780B-4B13-8ACE-9050E39CC51C}.Debug|Mixed Platforms.ActiveCfg = Debug|Any CPU {DC8C38D7-780B-4B13-8ACE-9050E39CC51C}.Debug|Mixed Platforms.Build.0 = Debug|Any CPU {DC8C38D7-780B-4B13-8ACE-9050E39CC51C}.Debug|Win32.ActiveCfg = Debug|Any CPU {DC8C38D7-780B-4B13-8ACE-9050E39CC51C}.Debug|Win32.Build.0 = Debug|Any CPU {DC8C38D7-780B-4B13-8ACE-9050E39CC51C}.Debug|x64.ActiveCfg = Debug|Any CPU {DC8C38D7-780B-4B13-8ACE-9050E39CC51C}.Debug|x64.Build.0 = Debug|Any CPU {DC8C38D7-780B-4B13-8ACE-9050E39CC51C}.Instrumentation|Any CPU.ActiveCfg = Instrumentation|Any CPU {DC8C38D7-780B-4B13-8ACE-9050E39CC51C}.Instrumentation|Any CPU.Build.0 = Instrumentation|Any CPU {DC8C38D7-780B-4B13-8ACE-9050E39CC51C}.Instrumentation|ARM.ActiveCfg = Instrumentation|Any CPU {DC8C38D7-780B-4B13-8ACE-9050E39CC51C}.Instrumentation|ARM.Build.0 = Instrumentation|Any CPU {DC8C38D7-780B-4B13-8ACE-9050E39CC51C}.Instrumentation|Mixed Platforms.ActiveCfg = Instrumentation|Any CPU {DC8C38D7-780B-4B13-8ACE-9050E39CC51C}.Instrumentation|Mixed Platforms.Build.0 = Instrumentation|Any CPU {DC8C38D7-780B-4B13-8ACE-9050E39CC51C}.Instrumentation|Win32.ActiveCfg = Instrumentation|Any CPU {DC8C38D7-780B-4B13-8ACE-9050E39CC51C}.Instrumentation|Win32.Build.0 = Instrumentation|Any CPU {DC8C38D7-780B-4B13-8ACE-9050E39CC51C}.Instrumentation|x64.ActiveCfg = Instrumentation|Any CPU {DC8C38D7-780B-4B13-8ACE-9050E39CC51C}.Instrumentation|x64.Build.0 = Instrumentation|Any CPU {DC8C38D7-780B-4B13-8ACE-9050E39CC51C}.Release|Any CPU.ActiveCfg = Release|Any CPU {DC8C38D7-780B-4B13-8ACE-9050E39CC51C}.Release|Any CPU.Build.0 = Release|Any CPU {DC8C38D7-780B-4B13-8ACE-9050E39CC51C}.Release|ARM.ActiveCfg = Release|Any CPU {DC8C38D7-780B-4B13-8ACE-9050E39CC51C}.Release|ARM.Build.0 = Release|Any CPU {DC8C38D7-780B-4B13-8ACE-9050E39CC51C}.Release|Mixed Platforms.ActiveCfg = Release|Any CPU {DC8C38D7-780B-4B13-8ACE-9050E39CC51C}.Release|Mixed Platforms.Build.0 = Release|Any CPU {DC8C38D7-780B-4B13-8ACE-9050E39CC51C}.Release|Win32.ActiveCfg = Release|Any CPU {DC8C38D7-780B-4B13-8ACE-9050E39CC51C}.Release|Win32.Build.0 = Release|Any CPU {DC8C38D7-780B-4B13-8ACE-9050E39CC51C}.Release|x64.ActiveCfg = Release|Any CPU {DC8C38D7-780B-4B13-8ACE-9050E39CC51C}.Release|x64.Build.0 = Release|Any CPU {9863D039-AB21-4710-960E-7303919552C6}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {9863D039-AB21-4710-960E-7303919552C6}.Debug|Any CPU.Build.0 = Debug|Any CPU {9863D039-AB21-4710-960E-7303919552C6}.Debug|ARM.ActiveCfg = Debug|Any CPU {9863D039-AB21-4710-960E-7303919552C6}.Debug|ARM.Build.0 = Debug|Any CPU {9863D039-AB21-4710-960E-7303919552C6}.Debug|Mixed Platforms.ActiveCfg = Debug|Any CPU {9863D039-AB21-4710-960E-7303919552C6}.Debug|Mixed Platforms.Build.0 = Debug|Any CPU {9863D039-AB21-4710-960E-7303919552C6}.Debug|Win32.ActiveCfg = Debug|Any CPU {9863D039-AB21-4710-960E-7303919552C6}.Debug|Win32.Build.0 = Debug|Any CPU {9863D039-AB21-4710-960E-7303919552C6}.Debug|x64.ActiveCfg = Debug|Any CPU {9863D039-AB21-4710-960E-7303919552C6}.Debug|x64.Build.0 = Debug|Any CPU {9863D039-AB21-4710-960E-7303919552C6}.Instrumentation|Any CPU.ActiveCfg = Release|Any CPU {9863D039-AB21-4710-960E-7303919552C6}.Instrumentation|Any CPU.Build.0 = Release|Any CPU {9863D039-AB21-4710-960E-7303919552C6}.Instrumentation|ARM.ActiveCfg = Release|Any CPU {9863D039-AB21-4710-960E-7303919552C6}.Instrumentation|ARM.Build.0 = Release|Any CPU {9863D039-AB21-4710-960E-7303919552C6}.Instrumentation|Mixed Platforms.ActiveCfg = Release|Any CPU {9863D039-AB21-4710-960E-7303919552C6}.Instrumentation|Mixed Platforms.Build.0 = Release|Any CPU {9863D039-AB21-4710-960E-7303919552C6}.Instrumentation|Win32.ActiveCfg = Release|Any CPU {9863D039-AB21-4710-960E-7303919552C6}.Instrumentation|Win32.Build.0 = Release|Any CPU {9863D039-AB21-4710-960E-7303919552C6}.Instrumentation|x64.ActiveCfg = Release|Any CPU {9863D039-AB21-4710-960E-7303919552C6}.Instrumentation|x64.Build.0 = Release|Any CPU {9863D039-AB21-4710-960E-7303919552C6}.Release|Any CPU.ActiveCfg = Release|Any CPU {9863D039-AB21-4710-960E-7303919552C6}.Release|Any CPU.Build.0 = Release|Any CPU {9863D039-AB21-4710-960E-7303919552C6}.Release|ARM.ActiveCfg = Release|Any CPU {9863D039-AB21-4710-960E-7303919552C6}.Release|ARM.Build.0 = Release|Any CPU {9863D039-AB21-4710-960E-7303919552C6}.Release|Mixed Platforms.ActiveCfg = Release|Any CPU {9863D039-AB21-4710-960E-7303919552C6}.Release|Mixed Platforms.Build.0 = Release|Any CPU {9863D039-AB21-4710-960E-7303919552C6}.Release|Win32.ActiveCfg = Release|Any CPU {9863D039-AB21-4710-960E-7303919552C6}.Release|Win32.Build.0 = Release|Any CPU {9863D039-AB21-4710-960E-7303919552C6}.Release|x64.ActiveCfg = Release|Any CPU {9863D039-AB21-4710-960E-7303919552C6}.Release|x64.Build.0 = Release|Any CPU {C17E59D0-2D64-4012-8A98-D184D0CF8A49}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {C17E59D0-2D64-4012-8A98-D184D0CF8A49}.Debug|Any CPU.Build.0 = Debug|Any CPU {C17E59D0-2D64-4012-8A98-D184D0CF8A49}.Debug|ARM.ActiveCfg = Debug|Any CPU {C17E59D0-2D64-4012-8A98-D184D0CF8A49}.Debug|ARM.Build.0 = Debug|Any CPU {C17E59D0-2D64-4012-8A98-D184D0CF8A49}.Debug|Mixed Platforms.ActiveCfg = Debug|Any CPU {C17E59D0-2D64-4012-8A98-D184D0CF8A49}.Debug|Mixed Platforms.Build.0 = Debug|Any CPU {C17E59D0-2D64-4012-8A98-D184D0CF8A49}.Debug|Win32.ActiveCfg = Debug|Any CPU {C17E59D0-2D64-4012-8A98-D184D0CF8A49}.Debug|Win32.Build.0 = Debug|Any CPU {C17E59D0-2D64-4012-8A98-D184D0CF8A49}.Debug|x64.ActiveCfg = Debug|Any CPU {C17E59D0-2D64-4012-8A98-D184D0CF8A49}.Debug|x64.Build.0 = Debug|Any CPU {C17E59D0-2D64-4012-8A98-D184D0CF8A49}.Instrumentation|Any CPU.ActiveCfg = Release|Any CPU {C17E59D0-2D64-4012-8A98-D184D0CF8A49}.Instrumentation|Any CPU.Build.0 = Release|Any CPU {C17E59D0-2D64-4012-8A98-D184D0CF8A49}.Instrumentation|ARM.ActiveCfg = Release|Any CPU {C17E59D0-2D64-4012-8A98-D184D0CF8A49}.Instrumentation|ARM.Build.0 = Release|Any CPU {C17E59D0-2D64-4012-8A98-D184D0CF8A49}.Instrumentation|Mixed Platforms.ActiveCfg = Release|Any CPU {C17E59D0-2D64-4012-8A98-D184D0CF8A49}.Instrumentation|Mixed Platforms.Build.0 = Release|Any CPU {C17E59D0-2D64-4012-8A98-D184D0CF8A49}.Instrumentation|Win32.ActiveCfg = Release|Any CPU {C17E59D0-2D64-4012-8A98-D184D0CF8A49}.Instrumentation|Win32.Build.0 = Release|Any CPU {C17E59D0-2D64-4012-8A98-D184D0CF8A49}.Instrumentation|x64.ActiveCfg = Release|Any CPU {C17E59D0-2D64-4012-8A98-D184D0CF8A49}.Instrumentation|x64.Build.0 = Release|Any CPU {C17E59D0-2D64-4012-8A98-D184D0CF8A49}.Release|Any CPU.ActiveCfg = Release|Any CPU {C17E59D0-2D64-4012-8A98-D184D0CF8A49}.Release|Any CPU.Build.0 = Release|Any CPU {C17E59D0-2D64-4012-8A98-D184D0CF8A49}.Release|ARM.ActiveCfg = Release|Any CPU {C17E59D0-2D64-4012-8A98-D184D0CF8A49}.Release|ARM.Build.0 = Release|Any CPU {C17E59D0-2D64-4012-8A98-D184D0CF8A49}.Release|Mixed Platforms.ActiveCfg = Release|Any CPU {C17E59D0-2D64-4012-8A98-D184D0CF8A49}.Release|Mixed Platforms.Build.0 = Release|Any CPU {C17E59D0-2D64-4012-8A98-D184D0CF8A49}.Release|Win32.ActiveCfg = Release|Any CPU {C17E59D0-2D64-4012-8A98-D184D0CF8A49}.Release|Win32.Build.0 = Release|Any CPU {C17E59D0-2D64-4012-8A98-D184D0CF8A49}.Release|x64.ActiveCfg = Release|Any CPU {C17E59D0-2D64-4012-8A98-D184D0CF8A49}.Release|x64.Build.0 = Release|Any CPU EndGlobalSection GlobalSection(SolutionProperties) = preSolution HideSolutionNode = FALSE EndGlobalSection GlobalSection(NestedProjects) = preSolution {7F3A2DA3-7D2A-4F59-AEE2-3DBF75C80FFE} = {AEF34496-481F-47EC-B246-92F7E87339C0} {6956D60A-260F-4B83-ABC6-EDABC5E17C84} = {AEF34496-481F-47EC-B246-92F7E87339C0} {B005F882-B6AB-4CEA-9434-8BFF1876686B} = {AEF34496-481F-47EC-B246-92F7E87339C0} {A1D7BA88-298C-440A-B626-E061EDCE4045} = {993EE84F-7CEA-40E0-BE5C-B1F38D1BA562} {AA94AD05-A42A-4190-8585-A82439976872} = {993EE84F-7CEA-40E0-BE5C-B1F38D1BA562} {5354D2AA-713A-4F47-BE76-2CCC57DE6EC4} = {993EE84F-7CEA-40E0-BE5C-B1F38D1BA562} {DC90A338-0E12-4668-8FFF-2A0BDEBC3597} = {AEF34496-481F-47EC-B246-92F7E87339C0} {186F31A3-EF89-4A25-B2D5-20060404AA01} = {7F3A2DA3-7D2A-4F59-AEE2-3DBF75C80FFE} {186F31A3-EF89-4A25-B2D5-20060501AA01} = {AA94AD05-A42A-4190-8585-A82439976872} {186F31A3-EF89-4A25-B2D5-20060509AA02} = {AA94AD05-A42A-4190-8585-A82439976872} {186F31A3-EF89-4A25-B2D5-20060509AA01} = {5354D2AA-713A-4F47-BE76-2CCC57DE6EC4} {186F31A3-EF89-4A25-B2D5-20060510AA01} = {7F3A2DA3-7D2A-4F59-AEE2-3DBF75C80FFE} {186F31A3-EF89-4A25-B2D5-20060603AA01} = {6956D60A-260F-4B83-ABC6-EDABC5E17C84} {186F31A3-EF89-4A25-B2D5-20060606AA01} = {6956D60A-260F-4B83-ABC6-EDABC5E17C84} {186F31A3-EF89-4A25-B2D5-20060704AA01} = {B2AEC590-045A-4623-8DFD-357A5B54C424} {186F31A3-EF89-4A25-B2D5-20060720AA01} = {5354D2AA-713A-4F47-BE76-2CCC57DE6EC4} {186F31A3-EF89-4A25-B2D5-20061218AA01} = {5354D2AA-713A-4F47-BE76-2CCC57DE6EC4} {186F31A3-EF89-4A25-B2D5-20070211AA01} = {B005F882-B6AB-4CEA-9434-8BFF1876686B} {186F31A3-EF89-4A25-B2D5-20070222AA01} = {6956D60A-260F-4B83-ABC6-EDABC5E17C84} {186F31A3-EF89-4A25-B2D5-20070430AA01} = {B2AEC590-045A-4623-8DFD-357A5B54C424} {186F31A3-EF89-4A25-B2D5-20070519AA01} = {DC90A338-0E12-4668-8FFF-2A0BDEBC3597} {186F31A3-EF89-4A25-B2D5-20070601AA01} = {5354D2AA-713A-4F47-BE76-2CCC57DE6EC4} {186F31A3-EF89-4A25-B2D5-20070605AA02} = {6956D60A-260F-4B83-ABC6-EDABC5E17C84} {186F31A3-EF89-4A25-B2D5-20070606AA01} = {DC90A338-0E12-4668-8FFF-2A0BDEBC3597} {186F31A3-EF89-4A25-B2D5-20070702AA01} = {AA94AD05-A42A-4190-8585-A82439976872} {96BF0234-1D60-4401-A6B9-99839187234E} = {B005F882-B6AB-4CEA-9434-8BFF1876686B} {186F31A3-EF89-4A25-B2D5-20080628AA01} = {AA94AD05-A42A-4190-8585-A82439976872} {79F07A26-A95A-45AB-B6B6-325A63AF1065} = {3E953D4D-61BB-48CA-B996-90A5736BFA58} {77D71AF4-11C3-409B-A211-51FA19E5C1AA} = {F5824561-14E4-4E5E-83A4-CFE95F128829} {6C77A7DE-D464-430F-96A9-A64768763B5F} = {6956D60A-260F-4B83-ABC6-EDABC5E17C84} {0162C8CE-6641-4922-8664-F8A44356FBF7} = {6956D60A-260F-4B83-ABC6-EDABC5E17C84} {D7F2BC4E-1406-47AA-90E1-07BC4CE9410F} = {8988313A-FAC7-4CF9-B373-C4034FC01EFA} {7FC1F0E6-A46C-4A0C-AA6F-233EEFEB33D3} = {A1D7BA88-298C-440A-B626-E061EDCE4045} {8988313A-FAC7-4CF9-B373-C4034FC01EFA} = {7FC1F0E6-A46C-4A0C-AA6F-233EEFEB33D3} {6367CACE-0511-485D-9AE5-698F7E600839} = {F5824561-14E4-4E5E-83A4-CFE95F128829} {EE8431BB-2720-4F75-AD08-1E3307F68BE4} = {7FC1F0E6-A46C-4A0C-AA6F-233EEFEB33D3} {DFC4F889-3803-4B12-B792-30504AD8C85A} = {3E953D4D-61BB-48CA-B996-90A5736BFA58} {016691CA-A31F-4273-A4D2-C5F6E4B3662D} = {AA94AD05-A42A-4190-8585-A82439976872} {6C581F6A-34F8-4380-9BE0-279F709D13CB} = {35A43865-50F4-423A-ACF6-B3AEC2511716} {D3FA04AF-4285-477D-A756-6C51E9A56E7A} = {35A43865-50F4-423A-ACF6-B3AEC2511716} {35A43865-50F4-423A-ACF6-B3AEC2511716} = {79F07A26-A95A-45AB-B6B6-325A63AF1065} {F5824561-14E4-4E5E-83A4-CFE95F128829} = {79F07A26-A95A-45AB-B6B6-325A63AF1065} {CF168235-325F-448A-B455-3382C2B9DA48} = {7FC1F0E6-A46C-4A0C-AA6F-233EEFEB33D3} {CF4FC546-608D-4BE4-8A67-1E8C9F3526A3} = {7FC1F0E6-A46C-4A0C-AA6F-233EEFEB33D3} {0B37E5BA-4839-4EC4-9E36-A96BCBEA2400} = {CF168235-325F-448A-B455-3382C2B9DA48} {0C522C6A-0F77-4AF8-AD78-5B2415C98C51} = {CF168235-325F-448A-B455-3382C2B9DA48} {A30EB003-94F8-4A85-8DA1-006F6810A7A4} = {CF168235-325F-448A-B455-3382C2B9DA48} {7FB3F581-742D-4E12-A36A-BE172C574AB0} = {CF4FC546-608D-4BE4-8A67-1E8C9F3526A3} {65C8EDA6-AC24-4E18-A5B5-216E0F2C3906} = {CF4FC546-608D-4BE4-8A67-1E8C9F3526A3} {CA8A6D38-528B-4FAA-89B6-8FA9178DE55D} = {CF4FC546-608D-4BE4-8A67-1E8C9F3526A3} {D68EE51B-A898-4A77-97D8-C61254CAC122} = {AA94AD05-A42A-4190-8585-A82439976872} {8323ECD0-B5EF-4885-9421-EB05DCB32884} = {3E953D4D-61BB-48CA-B996-90A5736BFA58} {1AE58C3F-0319-4B7E-9E48-7A7BEBC2E3A5} = {8323ECD0-B5EF-4885-9421-EB05DCB32884} {91FF2862-C6E5-45BB-B399-8E363E40361C} = {8323ECD0-B5EF-4885-9421-EB05DCB32884} {1705887B-E636-4FA3-AE40-2D431AF1511C} = {EE8431BB-2720-4F75-AD08-1E3307F68BE4} {CEE4D575-4B4B-42B0-B2F1-CC7198CB7306} = {EE8431BB-2720-4F75-AD08-1E3307F68BE4} {DC8C38D7-780B-4B13-8ACE-9050E39CC51C} = {AA94AD05-A42A-4190-8585-A82439976872} {9863D039-AB21-4710-960E-7303919552C6} = {DC90A338-0E12-4668-8FFF-2A0BDEBC3597} {C17E59D0-2D64-4012-8A98-D184D0CF8A49} = {DC90A338-0E12-4668-8FFF-2A0BDEBC3597} EndGlobalSection EndGlobal ================================================ FILE: Zelig/Zelig/Test/LlilumWin32/LlilumWin32.cpp ================================================ // LlilumWin32.cpp : Defines the entry point for the console application. // #include "stdafx.h" extern int LlosWin32_Main(void); int main() { return LlosWin32_Main(); } ================================================ FILE: Zelig/Zelig/Test/LlilumWin32/LlilumWin32.vcxproj ================================================  Debug Win32 Release Win32 {09CD4F6F-17D7-4A56-A8FD-797EBF2543DF} Win32Proj LlilumWin32 8.1 Application true v140 Unicode Application false v140 true Unicode true false Level3 Disabled WIN32;_DEBUG;_CONSOLE;%(PreprocessorDefinitions) $(LLILUM_ROOT)\Zelig\os_layer\inc;$(LLILUM_ROOT)\Zelig\os_layer\inc\api;$(LLILUM_ROOT)\Zelig\os_layer\inc\api\io;$(LLILUM_ROOT)\Zelig\os_layer\inc\debug;$(LLILUM_ROOT)\Zelig\os_layer\inc\hal Console true $(LLILUM_ROOT)Zelig\Zelig\$(Configuration)\Win32Abstraction.lib;$(LLILUM_ROOT)\Zelig\LLVM2IR_results\mbed\simple\Microsoft.Zelig.Test.mbed.Simple_opt.o;Synchronization.lib;%(AdditionalDependencies) Level3 MinSpace true true WIN32;NDEBUG;_CONSOLE;%(PreprocessorDefinitions) $(LLILUM_ROOT)Zelig\os_layer\inc;$(LLILUM_ROOT)\Zelig\os_layer\inc\api;$(LLILUM_ROOT)\Zelig\os_layer\inc\api\io;$(LLILUM_ROOT)\Zelig\os_layer\inc\debug;$(LLILUM_ROOT)\Zelig\os_layer\inc\hal Console true true true $(LLILUM_ROOT)Zelig\Zelig\$(Configuration)\Win32Abstraction.lib;$(LLILUM_ROOT)\Zelig\LLVM2IR_results\mbed\simple\Microsoft.Zelig.Test.mbed.Simple_opt.o;Synchronization.lib;%(AdditionalDependencies) {e18a0a2a-60af-4819-9f64-fd347e222144} ================================================ FILE: Zelig/Zelig/Test/LlilumWin32/LlilumWin32.vcxproj.filters ================================================  {4FC737F1-C7A5-4376-A066-2A32D752A2FF} cpp;c;cc;cxx;def;odl;idl;hpj;bat;asm;asmx {93995380-89BD-4b04-88EB-625FBE52EBFB} h;hh;hpp;hxx;hm;inl;inc;xsd {67DA6AB6-F800-4c08-8B7A-83BB121AAD01} rc;ico;cur;bmp;dlg;rc2;rct;bin;rgs;gif;jpg;jpeg;jpe;resx;tiff;tif;png;wav;mfcribbon-ms Header Files Header Files Source Files Source Files ================================================ FILE: Zelig/Zelig/Test/LlilumWin32/ReadMe.txt ================================================ ======================================================================== CONSOLE APPLICATION : LlilumWin32 Project Overview ======================================================================== AppWizard has created this LlilumWin32 application for you. This file contains a summary of what you will find in each of the files that make up your LlilumWin32 application. LlilumWin32.vcxproj This is the main project file for VC++ projects generated using an Application Wizard. It contains information about the version of Visual C++ that generated the file, and information about the platforms, configurations, and project features selected with the Application Wizard. LlilumWin32.vcxproj.filters This is the filters file for VC++ projects generated using an Application Wizard. It contains information about the association between the files in your project and the filters. This association is used in the IDE to show grouping of files with similar extensions under a specific node (for e.g. ".cpp" files are associated with the "Source Files" filter). LlilumWin32.cpp This is the main application source file. ///////////////////////////////////////////////////////////////////////////// Other standard files: StdAfx.h, StdAfx.cpp These files are used to build a precompiled header (PCH) file named LlilumWin32.pch and a precompiled types file named StdAfx.obj. ///////////////////////////////////////////////////////////////////////////// Other notes: AppWizard uses "TODO:" comments to indicate parts of the source code you should add to or customize. ///////////////////////////////////////////////////////////////////////////// ================================================ FILE: Zelig/Zelig/Test/LlilumWin32/stdafx.cpp ================================================ // stdafx.cpp : source file that includes just the standard includes // LlilumWin32.pch will be the pre-compiled header // stdafx.obj will contain the pre-compiled type information #include "stdafx.h" ================================================ FILE: Zelig/Zelig/Test/LlilumWin32/stdafx.h ================================================ // stdafx.h : include file for standard system include files, // or project specific include files that are used frequently, but // are changed infrequently // #pragma once #include "targetver.h" #include #include ================================================ FILE: Zelig/Zelig/Test/LlilumWin32/targetver.h ================================================ #pragma once // Including SDKDDKVer.h defines the highest available Windows platform. // If you wish to build your application for a previous Windows platform, include WinSDKVer.h and // set the _WIN32_WINNT macro to the platform you wish to support before including SDKDDKVer.h. #include ================================================ FILE: Zelig/Zelig/Test/LlilumWin32.sln ================================================  Microsoft Visual Studio Solution File, Format Version 12.00 # Visual Studio 14 VisualStudioVersion = 14.0.24720.0 MinimumVisualStudioVersion = 10.0.40219.1 Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "LlilumWin32", "LlilumWin32\LlilumWin32.vcxproj", "{09CD4F6F-17D7-4A56-A8FD-797EBF2543DF}" ProjectSection(ProjectDependencies) = postProject {E18A0A2A-60AF-4819-9F64-FD347E222144} = {E18A0A2A-60AF-4819-9F64-FD347E222144} EndProjectSection EndProject Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "Win32Abstraction", "..\..\os_layer\ports\win32\Win32Abstraction\Win32Abstraction.vcxproj", "{E18A0A2A-60AF-4819-9F64-FD347E222144}" EndProject Global GlobalSection(SolutionConfigurationPlatforms) = preSolution Debug|x64 = Debug|x64 Debug|x86 = Debug|x86 Release|x64 = Release|x64 Release|x86 = Release|x86 EndGlobalSection GlobalSection(ProjectConfigurationPlatforms) = postSolution {09CD4F6F-17D7-4A56-A8FD-797EBF2543DF}.Debug|x64.ActiveCfg = Debug|Win32 {09CD4F6F-17D7-4A56-A8FD-797EBF2543DF}.Debug|x64.Build.0 = Debug|Win32 {09CD4F6F-17D7-4A56-A8FD-797EBF2543DF}.Debug|x86.ActiveCfg = Debug|Win32 {09CD4F6F-17D7-4A56-A8FD-797EBF2543DF}.Debug|x86.Build.0 = Debug|Win32 {09CD4F6F-17D7-4A56-A8FD-797EBF2543DF}.Release|x64.ActiveCfg = Release|Win32 {09CD4F6F-17D7-4A56-A8FD-797EBF2543DF}.Release|x64.Build.0 = Release|Win32 {09CD4F6F-17D7-4A56-A8FD-797EBF2543DF}.Release|x86.ActiveCfg = Release|Win32 {09CD4F6F-17D7-4A56-A8FD-797EBF2543DF}.Release|x86.Build.0 = Release|Win32 {E18A0A2A-60AF-4819-9F64-FD347E222144}.Debug|x64.ActiveCfg = Debug|Win32 {E18A0A2A-60AF-4819-9F64-FD347E222144}.Debug|x86.ActiveCfg = Debug|Win32 {E18A0A2A-60AF-4819-9F64-FD347E222144}.Debug|x86.Build.0 = Debug|Win32 {E18A0A2A-60AF-4819-9F64-FD347E222144}.Release|x64.ActiveCfg = Release|Win32 {E18A0A2A-60AF-4819-9F64-FD347E222144}.Release|x86.ActiveCfg = Release|Win32 {E18A0A2A-60AF-4819-9F64-FD347E222144}.Release|x86.Build.0 = Release|Win32 EndGlobalSection GlobalSection(SolutionProperties) = preSolution HideSolutionNode = FALSE EndGlobalSection EndGlobal ================================================ FILE: Zelig/Zelig/Test/RunTime/NETMF/System/Http/AuthenticationTests.cs ================================================ //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // Copyright (c) Microsoft Corporation. All rights reserved. //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// using System; using System.Net; namespace Microsoft.Zelig.Test { public class AuthenticationTests : TestBase, ITestInterface { [SetUp] public InitializeResult Initialize() { Log.Comment("Adding set up for the tests."); // Add your functionality here. return InitializeResult.ReadyToGo; } [TearDown] public void CleanUp() { Log.Comment("Cleaning up after the tests."); // TODO: Add your clean up steps here. } public override TestResult Run( string[] args ) { return TestResult.Pass; } //--// //--// //--// #region Test [TestMethod] public TestResult TestHTTPStatusCodeHTTP1_1_WWWAuthenticate() { TestResult result = TestResult.Pass; string userName = "Igor"; string passWord = "MyPassword"; HttpWebRequest wr = (HttpWebRequest)WebRequest.Create("http://157.56.163.1/PasswordProtected"); //expect 401 - Unauthorized wr.UserAgent = ".Net Micro Framwork Device/4.0"; Log.Comment("Initial version: " + wr.ProtocolVersion); //Default version is 1.1 Log.Comment("Set Version 1.1"); wr.ProtocolVersion = new Version(1, 1); wr.Credentials = new NetworkCredential(userName, passWord); //wr.PreAuthenticate = true; //to send WWW-authenticate HTTP header with requests after authentication has taken place //wr.Headers.Set(HttpKnownHeaderNames.Authorization, "Basic QWxhZGRpbjpvcGVuIHNlc2FtZQ=="); try { HttpWebResponse response = (HttpWebResponse)wr.GetResponse(); Log.Comment("Expect StatusCode - Unauthorized "); if (HttpStatusCode.Unauthorized != response.StatusCode) { Log.Exception("Expect HttpStatusCode = Unauthorized but get " + response.StatusCode); result = TestResult.Fail; } string responseString = response.Headers.ToString(); Log.Comment("ResposeString = " + responseString); if (responseString.IndexOf("WWW-Authenticate: Basic realm=\".Net MF Example of Secure Area\"") > -1) { wr.Headers.Set(HttpKnownHeaderNames.Authorization, "Basic QWxhZGRpbjpvcGVuIHNlc2FtZQ=="); if ((HttpStatusCode.OK != response.StatusCode)) { Log.Exception("Expect HttpStatusCode = OK but get " + response.StatusCode); result = TestResult.Fail; } } response.Close(); } catch (Exception ex) { Log.Exception("[Client] Unexpected Exception", ex); result = TestResult.Fail; } return result; } #endregion Test } } ================================================ FILE: Zelig/Zelig/Test/RunTime/NETMF/System/Http/Base64Tests.cs ================================================ //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // Copyright (c) Microsoft Corporation. All rights reserved. //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// using System; using System.Text; namespace Microsoft.Zelig.Test { public class Base64Tests : TestBase, ITestInterface { [SetUp] public InitializeResult Initialize() { Log.Comment("Testing base64 encoding"); return InitializeResult.ReadyToGo; } [TearDown] public void CleanUp() { Log.Comment("No cleanup required after tests of base64 encoding."); } public override TestResult Run( string[] args ) { return TestResult.Pass; } //--// //--// //--// //////[TestMethod] //////public TestResult TestBase64Encoding() //////{ ////// try ////// { ////// string strOriginal = "Over the past few years, you've asked us to make some changes to Windows. We listened closely. Now it's time to share an early look at how we've used your feedback. Windows 7 is faster, more reliable, and makes it easier to do what you want. Both the everyday things and the killer \"is that really possible?\" things. Dig into this site to see what's coming..."; ////// byte [] dataToEncode = Encoding.UTF8.GetBytes(strOriginal); ////// string strEncoded = System.Convert.ToBase64String(dataToEncode); ////// string strEthalon = "T3ZlciB0aGUgcGFzdCBmZXcgeWVhcnMsIHlvdSd2ZSBhc2tlZCB1cyB0byBtYWtlIHNvbWUgY2hhbmdlcyB0byBXaW5kb3dzLiBXZSBsaXN0ZW5lZCBjbG9zZWx5LiBOb3cgaXQncyB0aW1lIHRvIHNoYXJlIGFuIGVhcmx5IGxvb2sgYXQgaG93IHdlJ3ZlIHVzZWQgeW91ciBmZWVkYmFjay4gV2luZG93cyA3IGlzIGZhc3RlciwgbW9yZSByZWxpYWJsZSwgYW5kIG1ha2VzIGl0IGVhc2llciB0byBkbyB3aGF0IHlvdSB3YW50LiBCb3RoIHRoZSBldmVyeWRheSB0aGluZ3MgYW5kIHRoZSBraWxsZXIgImlzIHRoYXQgcmVhbGx5IHBvc3NpYmxlPyIgdGhpbmdzLiBEaWcgaW50byB0aGlzIHNpdGUgdG8gc2VlIHdoYXQncyBjb21pbmcuLi4="; ////// if (strEncoded != strEthalon) ////// { ////// Log.Comment("Failed in encoding of the string." ); ////// Log.Comment("Expected result: " + strEthalon); ////// Log.Comment("Actual result: " + strEncoded); ////// return TestResult.Fail; ////// } ////// byte[] dataDecoded = System.Convert.FromBase64String(strEncoded); ////// string strDecoded = new string( Encoding.UTF8.GetChars(dataDecoded) ); ////// if (strOriginal != strDecoded) ////// { ////// Log.Comment("Failed in decoding of the string."); ////// Log.Comment("Expected result: " + strOriginal); ////// Log.Comment("Actual result: " + strDecoded); ////// return TestResult.Fail; ////// } ////// // change to RFC4548 encoding ////// byte[] dataToEncodeRFC4648 = new byte[256]; ////// for (int b = 0; b < 256; b++) ////// { ////// dataToEncodeRFC4648[b] = (byte)b; ////// } ////// strEncoded = System.Convert.ToBase64String(dataToEncodeRFC4648); ////// dataDecoded = System.Convert.FromBase64String(strEncoded); ////// System.Convert.UseRFC4648Encoding = true; ////// string strEncodedRFC4648 = System.Convert.ToBase64String(dataToEncodeRFC4648); ////// byte[] dataDecodedRFC4648 = System.Convert.FromBase64String(strEncodedRFC4648); ////// if(strEncoded.Length != strEncodedRFC4648.Length) ////// { ////// Log.Comment("RFC4648 encoding had a different length than default encoding."); ////// return TestResult.Fail; ////// } ////// for (int i = 0; i < strEncoded.Length; i++) ////// { ////// bool fOK = true; ////// switch (strEncoded[i]) ////// { ////// case '!': ////// fOK = strEncodedRFC4648[i] == '+'; ////// break; ////// case '*': ////// fOK = strEncodedRFC4648[i] == '/'; ////// break; ////// default: ////// fOK = strEncodedRFC4648[i] == strEncoded[i]; ////// break; ////// } ////// switch(strEncodedRFC4648[i]) ////// { ////// case '+': ////// fOK = strEncoded[i] == '!'; ////// break; ////// case '/': ////// fOK = strEncoded[i] == '*'; ////// break; ////// default: ////// fOK = strEncoded[i] == strEncodedRFC4648[i]; ////// break; ////// } ////// if (!fOK) ////// { ////// Log.Comment("The RFC4648 encoding does not match the default encoding at index: " + i); ////// Log.Comment("RF4648 result: " + strEncodedRFC4648[i]); ////// Log.Comment("default result: " + strEncoded[i]); ////// return TestResult.Fail; ////// } ////// } ////// for (int b = 0; b < 256; b++) ////// { ////// if ((dataDecodedRFC4648[b] != (byte)b) || ////// (dataDecoded[b] != (byte)b)) ////// { ////// Log.Comment("Failed in decoding of the string."); ////// Log.Comment("Expected result: " + (byte)b); ////// Log.Comment("Actual result: " + dataDecodedRFC4648[b]); ////// return TestResult.Fail; ////// } ////// } ////// } ////// catch (Exception ex) ////// { ////// Log.Exception("Unexpected Exception", ex); ////// return TestResult.Fail; ////// } ////// Log.Comment("Base64 decoding/encoding tests succeded"); ////// return TestResult.Pass; //////} [TestMethod] public TestResult TestBase64EncodingIndexed() { try { string strOriginal = "Over the past few years, you've asked us to make some changes to Windows. We listened closely. Now it's time to share an early look at how we've used your feedback. Windows 7 is faster, more reliable, and makes it easier to do what you want. Both the everyday things and the killer \"is that really possible?\" things. Dig into this site to see what's coming..."; byte[] dataToEncode = Encoding.UTF8.GetBytes(strOriginal); byte[] largeBuffer = new byte[dataToEncode.Length * 2]; Array.Copy(dataToEncode, 0, largeBuffer, dataToEncode.Length / 4, dataToEncode.Length); string strEncoded = System.Convert.ToBase64String(largeBuffer, dataToEncode.Length/4, dataToEncode.Length); string strEthalon = "T3ZlciB0aGUgcGFzdCBmZXcgeWVhcnMsIHlvdSd2ZSBhc2tlZCB1cyB0byBtYWtlIHNvbWUgY2hhbmdlcyB0byBXaW5kb3dzLiBXZSBsaXN0ZW5lZCBjbG9zZWx5LiBOb3cgaXQncyB0aW1lIHRvIHNoYXJlIGFuIGVhcmx5IGxvb2sgYXQgaG93IHdlJ3ZlIHVzZWQgeW91ciBmZWVkYmFjay4gV2luZG93cyA3IGlzIGZhc3RlciwgbW9yZSByZWxpYWJsZSwgYW5kIG1ha2VzIGl0IGVhc2llciB0byBkbyB3aGF0IHlvdSB3YW50LiBCb3RoIHRoZSBldmVyeWRheSB0aGluZ3MgYW5kIHRoZSBraWxsZXIgImlzIHRoYXQgcmVhbGx5IHBvc3NpYmxlPyIgdGhpbmdzLiBEaWcgaW50byB0aGlzIHNpdGUgdG8gc2VlIHdoYXQncyBjb21pbmcuLi4="; if (strEncoded != strEthalon) { Log.Comment("Failed in encoding of the string."); Log.Comment("Expected result: " + strEthalon); Log.Comment("Actual result: " + strEncoded); return TestResult.Fail; } char[] cabuf = strEncoded.ToCharArray(); char[] caBig = new char[cabuf.Length * 2]; Array.Copy(cabuf, 0, caBig, cabuf.Length / 4, cabuf.Length); byte[] dataDecoded = System.Convert.FromBase64CharArray(caBig, cabuf.Length / 4, cabuf.Length); string strDecoded = new string(Encoding.UTF8.GetChars(dataDecoded)); if (strOriginal != strDecoded) { Log.Comment("Failed in decoding of the string."); Log.Comment("Expected result: " + strOriginal); Log.Comment("Actual result: " + strDecoded); return TestResult.Fail; } } catch (Exception ex) { Log.Exception("Unexpected Exception", ex); return TestResult.Fail; } Log.Comment("Base64 decoding/encoding tests succeded"); return TestResult.Pass; } } } ================================================ FILE: Zelig/Zelig/Test/RunTime/NETMF/System/Http/FunctionalTests.cs ================================================ //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // Copyright (c) Microsoft Corporation. All rights reserved. //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// using System; using System.Net; using System.IO; using System.Text; namespace Microsoft.Zelig.Test { public class FunctionalTests : TestBase, ITestInterface { [SetUp] public InitializeResult Initialize() { Log.Comment("Adding set up for the tests."); try { // Check networking - we need to make sure we can reach our proxy server Dns.GetHostEntry(HttpTests.Proxy); } catch (Exception ex) { Log.Exception("Unable to get address for " + HttpTests.Proxy, ex); return InitializeResult.Skip; } return InitializeResult.ReadyToGo; } [TearDown] public void CleanUp() { Log.Comment("Cleaning up after the tests."); // TODO: Add your clean up steps here. } public override TestResult Run( string[] args ) { return TestResult.Pass; } //--// //--// //--// [TestMethod] public TestResult VisitMicrosoft() { try { Log.Comment("Small web page - redirect"); // Print for now, Parse later string data = new string(Encoding.UTF8.GetChars(GetRequested("http://www.microsoft.com", "IIS"))); } catch (Exception ex) { Log.Exception("Unexpected Exception", ex); return TestResult.Fail; } return TestResult.Pass; } [TestMethod] public TestResult VisitNYTimes() { try { Log.Comment("SUN web page"); // Print for now, Parse later string data = new string(Encoding.UTF8.GetChars(GetRequested("http://www.nytimes.com", "SUN", "APACHE"))); } catch (Exception ex) { Log.Exception("Unexpected Exception", ex); return TestResult.Fail; } return TestResult.Pass; } [TestMethod] public TestResult VisitApache() { try { Log.Comment("Apache Web server"); // Print for now, Parse later string data = new string(Encoding.UTF8.GetChars(GetRequested("http://www.apache.org", "Apache"))); } catch (Exception ex) { Log.Exception("Unexpected Exception", ex); return TestResult.Fail; } return TestResult.Pass; } [TestMethod] public TestResult VisitGoogle() { try { Log.Comment("Google Web server"); // Print for now, Parse later string data = new string(Encoding.UTF8.GetChars(GetRequested("http://www.google.com", "GWS"))); } catch (ArgumentException) { /* Don't care if google doesn't return wrong header, happens at major 'holidays' like april 1 */ } catch (Exception ex) { Log.Exception("Unexpected Exception", ex); return TestResult.Fail; } return TestResult.Pass; } [TestMethod] public TestResult VisitLighttpd() { try { Log.Comment("Lighttpd Web server"); // Print for now, Parse later string data = new string(Encoding.UTF8.GetChars(GetRequested("http://redmine.lighttpd.net", "Lighttpd"))); } catch (Exception ex) { Log.Exception("Unexpected Exception", ex); return TestResult.Fail; } return TestResult.Pass; } private byte[] GetRequested(string uri, params string[] servers) { byte[] page = null; // Create request. HttpWebRequest request = HttpWebRequest.Create(uri) as HttpWebRequest; // Set proxy information WebProxy itgProxy = new WebProxy(HttpTests.Proxy, true); request.Proxy = itgProxy; // Get response from server. WebResponse resp = null; try { resp = request.GetResponse(); } catch (Exception e) { Log.Exception("GetResponse Exception", e); throw e; } try { // Get Network response stream if (resp != null) { Log.Comment("Headers - "); foreach (string header in resp.Headers.AllKeys) { Log.Comment(" " + header + ": " + resp.Headers[header]); } using (Stream respStream = resp.GetResponseStream()) { // Get all data: if (resp.ContentLength != -1) { int respLength = (int)resp.ContentLength; page = new byte[respLength]; // Now need to read all data. We read in the loop until resp.ContentLength or zero bytes read. // Zero bytes read means there was error on server and it did not send all data. for (int totalBytesRead = 0; totalBytesRead < respLength; ) { int bytesRead = respStream.Read(page, totalBytesRead, respLength - totalBytesRead); // If nothing is read - means server closed connection or timeout. In this case no retry. if (bytesRead == 0) { break; } // Adds number of bytes read on this iteration. totalBytesRead += bytesRead; } } else { byte[] byteData = new byte[4096]; char[] charData = new char[4096]; string data = null; int bytesRead = 0; Decoder UTF8decoder = System.Text.Encoding.UTF8.GetDecoder(); int totalBytes = 0; while ((bytesRead = respStream.Read(byteData, 0, byteData.Length)) > 0) { int byteUsed, charUsed; bool completed = false; totalBytes += bytesRead; UTF8decoder.Convert(byteData, 0, bytesRead, charData, 0, bytesRead, true, out byteUsed, out charUsed, out completed); data = data + new String(charData, 0, charUsed); Log.Comment("Bytes Read Now: " + bytesRead + " Total: " + totalBytes); } Log.Comment("Total bytes downloaded in message body : " + totalBytes); page = Encoding.UTF8.GetBytes(data); } Log.Comment("Page downloaded"); respStream.Close(); } bool fFoundExpectedServer = false; string httpServer = resp.Headers["server"].ToLower(); foreach(string server in servers) { if (httpServer.IndexOf(server.ToLower()) >= 0) { fFoundExpectedServer = true; break; } } if(!fFoundExpectedServer) { Log.Exception("Expected server: " + servers[0] + ", but got server: " + resp.Headers["Server"]); throw new ArgumentException("Unexpected Server type"); } resp.Close(); } } catch (Exception ex) { Log.Exception("Unexpected exception processing response", ex); throw ex; } return page; } } } ================================================ FILE: Zelig/Zelig/Test/RunTime/NETMF/System/Http/HttpKnownHeaderNamesTests.cs ================================================ //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // Copyright (c) Microsoft Corporation. All rights reserved. //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// using System; using System.Net; namespace Microsoft.Zelig.Test { public class HttpKnownHeaderNamesTests : TestBase, ITestInterface { [SetUp] public InitializeResult Initialize() { Log.Comment("Adding set up for the tests."); // Add your functionality here. return InitializeResult.ReadyToGo; } [TearDown] public void CleanUp() { Log.Comment("Cleaning up after the tests."); // TODO: Add your clean up steps here. } public override TestResult Run( string[] args ) { return TestResult.Pass; } //--// //--// //--// #region Helper methods private bool VerifyHeaderIsIllegal( WebHeaderCollection wrc, string header, string content, Type exceptionType ) { bool res = true; try { Log.Comment("Set Headers Properties for header: '" + header + "', with value: '" + content + "'"); wrc.Set(header, content); Log.Comment("Illegal header was set: Failed."); res = false; } catch (Exception ex) { if (!HttpTests.ValidateException(ex, exceptionType)) { res = false; } } return res; } private bool VerifyHeaderIsLegal(WebHeaderCollection wrc, string header, string content, Type exceptionType) { bool res = true; try { Log.Comment("Set Headers Properties for header: '" + header + "', with value: '" + content + "'"); wrc.Set(header, content); } catch (Exception ex) { Log.Exception("Exception thrown for legal header: '" + header + "'", ex); res = false; } return res; } #endregion Helper methods #region Test [TestMethod] public TestResult TestSetHTTPRequestHeaderAfterCreateHTTP1_1() { TestResult result = TestResult.Pass; HttpWebRequest wr = (HttpWebRequest)WebRequest.Create("http://127.0.0.1:" + HttpServer.s_CurrentPort.ToString() + "/"); wr.UserAgent = ".Net Micro Framwork Device/4.0"; Log.Comment("Initial version: " + wr.ProtocolVersion); //Default version is 1.1 wr.ProtocolVersion = new Version(1, 1); try { // Setup server System.Net.WebHeaderCollection wrc = wr.Headers; if (!VerifyHeaderIsIllegal(wrc, HttpKnownHeaderNames.Accept, "text/plain; q=0.5, text/html, text/x-dvi; q=0.8, text/x-c", typeof(ArgumentException))) result = TestResult.Fail; if (!VerifyHeaderIsIllegal(wrc, HttpKnownHeaderNames.Connection, "close", typeof(ArgumentException))) result = TestResult.Fail; if (!VerifyHeaderIsIllegal(wrc, HttpKnownHeaderNames.ContentLength, "26012", typeof(ArgumentException))) result = TestResult.Fail; //if (!VerifyHeaderIsIllegal(wrc, HttpKnownHeaderNames.ContentType, "image/gif", typeof(ArgumentException))) result = TestResult.Fail; //if (!VerifyHeaderIsIllegal(wrc, HttpKnownHeaderNames.Date, System.DateTime.Today.ToString(), typeof(ArgumentException))) result = TestResult.Fail; if (!VerifyHeaderIsIllegal(wrc, HttpKnownHeaderNames.Expect, "100", typeof(ArgumentException))) result = TestResult.Fail; if (!VerifyHeaderIsIllegal(wrc, HttpKnownHeaderNames.Host, "www.w3.org", typeof(ArgumentException))) result = TestResult.Fail; if (!VerifyHeaderIsIllegal(wrc, HttpKnownHeaderNames.IfModifiedSince, "Sat, 23 May 2009 19:43:31 GMT", typeof(ArgumentException))) result = TestResult.Fail; if (!VerifyHeaderIsIllegal(wrc, HttpKnownHeaderNames.Range, "500-999", typeof(ArgumentException))) result = TestResult.Fail; if (!VerifyHeaderIsIllegal(wrc, HttpKnownHeaderNames.Referer, "http://www.w3.org/hypertext/DataSources/Overview.html", typeof(ArgumentException))) result = TestResult.Fail; if (!VerifyHeaderIsIllegal(wrc, HttpKnownHeaderNames.TransferEncoding, "chunked", typeof(ArgumentException))) result = TestResult.Fail; if (!VerifyHeaderIsIllegal(wrc, HttpKnownHeaderNames.UserAgent, ".NetMicroFramework", typeof(ArgumentException))) result = TestResult.Fail; } catch (Exception ex) { Log.Exception("[Client] Unexpected Exception", ex); result = TestResult.Fail; } return result; } public TestResult ValidateAbleToSetPropertiesValueHTTP1_1() { TestResult result = TestResult.Pass; HttpWebRequest wr = (HttpWebRequest)WebRequest.Create("http://127.0.0.1:" + HttpServer.s_CurrentPort.ToString() + "/"); wr.UserAgent = ".Net Micro Framwork Device/4.0"; Log.Comment("Initial version: " + wr.ProtocolVersion); //Default version is 1.1 Log.Comment("Set Version 1.0"); wr.ProtocolVersion = new Version(1, 1); try { System.Net.WebHeaderCollection wrc = wr.Headers; if (!VerifyHeaderIsLegal(wrc, HttpKnownHeaderNames.AcceptCharset, "iso-8859-5, unicode-1-1;q=0.8", typeof(ArgumentException))) result = TestResult.Fail; if (!VerifyHeaderIsLegal(wrc, HttpKnownHeaderNames.AcceptEncoding, "compress;q=0.5, gzip;q=1.0", typeof(ArgumentException))) result = TestResult.Fail; if (!VerifyHeaderIsLegal(wrc, HttpKnownHeaderNames.AcceptLanguage, "en-US", typeof(ArgumentException))) result = TestResult.Fail; if (!VerifyHeaderIsLegal(wrc, HttpKnownHeaderNames.Age, "2 days", typeof(ArgumentException))) result = TestResult.Fail; if (!VerifyHeaderIsLegal(wrc, HttpKnownHeaderNames.Allow, "GET, PUT", typeof(ArgumentException))) result = TestResult.Fail; if (!VerifyHeaderIsLegal(wrc, HttpKnownHeaderNames.CacheControl, "no-cache", typeof(ArgumentException))) result = TestResult.Fail; if (!VerifyHeaderIsLegal(wrc, HttpKnownHeaderNames.ContentEncoding, "gzip", typeof(ArgumentException))) result = TestResult.Fail; if (!VerifyHeaderIsLegal(wrc, HttpKnownHeaderNames.ContentLanguage, "mi, en", typeof(ArgumentException))) result = TestResult.Fail; if (!VerifyHeaderIsLegal(wrc, HttpKnownHeaderNames.ContentMD5, "60e985979f1d55ab7542440fbb9659e5", typeof(ArgumentException))) result = TestResult.Fail; if (!VerifyHeaderIsLegal(wrc, HttpKnownHeaderNames.ContentRange, "bytes 21010-47021/47022", typeof(ArgumentException))) result = TestResult.Fail; if (!VerifyHeaderIsLegal(wrc, HttpKnownHeaderNames.Cookie, "www.google.com", typeof(ArgumentException))) result = TestResult.Fail; if (!VerifyHeaderIsLegal(wrc, HttpKnownHeaderNames.Expires, "Thu, 01 Dec 1994 16:00:00 GMT", typeof(ArgumentException))) result = TestResult.Fail; if (!VerifyHeaderIsLegal(wrc, HttpKnownHeaderNames.From, "webmaster@w3.org", typeof(ArgumentException))) result = TestResult.Fail; if (!VerifyHeaderIsLegal(wrc, HttpKnownHeaderNames.IfMatch, "r2d2xxxx", typeof(ArgumentException))) result = TestResult.Fail; if (!VerifyHeaderIsLegal(wrc, HttpKnownHeaderNames.IfNoneMatch, "xyzzy", typeof(ArgumentException))) result = TestResult.Fail; if (!VerifyHeaderIsLegal(wrc, HttpKnownHeaderNames.IfRange, "TestIfRange: Need to have Range Header.", typeof(ArgumentException))) result = TestResult.Fail; if (!VerifyHeaderIsLegal(wrc, HttpKnownHeaderNames.IfUnmodifiedSince, "Fri, 22 May 2009 12:43:31 GMT", typeof(ArgumentException))) result = TestResult.Fail; if (!VerifyHeaderIsLegal(wrc, HttpKnownHeaderNames.KeepAlive, "true", typeof(ArgumentException))) result = TestResult.Fail; if (!VerifyHeaderIsLegal(wrc, HttpKnownHeaderNames.LastModified, "Fri, 22 May 2009 12:43:31 GMT", typeof(ArgumentException))) result = TestResult.Fail; if (!VerifyHeaderIsLegal(wrc, HttpKnownHeaderNames.MaxForwards, "10", typeof(ArgumentException))) result = TestResult.Fail; if (!VerifyHeaderIsLegal(wrc, HttpKnownHeaderNames.Pragma, "no-cache", typeof(ArgumentException))) result = TestResult.Fail; if (!VerifyHeaderIsLegal(wrc, HttpKnownHeaderNames.ProxyAuthenticate, "", typeof(ArgumentException))) result = TestResult.Fail; if (!VerifyHeaderIsLegal(wrc, HttpKnownHeaderNames.ProxyAuthorization, "", typeof(ArgumentException))) result = TestResult.Fail; if (!VerifyHeaderIsLegal(wrc, HttpKnownHeaderNames.RetryAfter, "100000", typeof(ArgumentException))) result = TestResult.Fail; if (!VerifyHeaderIsLegal(wrc, HttpKnownHeaderNames.Server, "", typeof(ArgumentException))) result = TestResult.Fail; if (!VerifyHeaderIsLegal(wrc, HttpKnownHeaderNames.SetCookie, "www.microsoft.com", typeof(ArgumentException))) result = TestResult.Fail; if (!VerifyHeaderIsLegal(wrc, HttpKnownHeaderNames.SetCookie2, "www.bing.com", typeof(ArgumentException))) result = TestResult.Fail; if (!VerifyHeaderIsLegal(wrc, HttpKnownHeaderNames.TE, "trailers, deflate;q=0.5", typeof(ArgumentException))) result = TestResult.Fail; if (!VerifyHeaderIsLegal(wrc, HttpKnownHeaderNames.Trailer, "Test Code", typeof(ArgumentException))) result = TestResult.Fail; if (!VerifyHeaderIsLegal(wrc, HttpKnownHeaderNames.Upgrade, "HTTP/2.0, SHTTP/1.3, IRC/6.9, RTA/x11", typeof(ArgumentException))) result = TestResult.Fail; if (!VerifyHeaderIsLegal(wrc, HttpKnownHeaderNames.Via, "1.0 fred, 1.1 nowhere.com (Apache/1.1)", typeof(ArgumentException))) result = TestResult.Fail; if (!VerifyHeaderIsLegal(wrc, HttpKnownHeaderNames.Vary, "*", typeof(ArgumentException))) result = TestResult.Fail; if (!VerifyHeaderIsLegal(wrc, HttpKnownHeaderNames.Warning, "TestWarning", typeof(ArgumentException))) result = TestResult.Fail; if (!VerifyHeaderIsLegal(wrc, HttpKnownHeaderNames.WWWAuthenticate, "WWW-Authenticate", typeof(ArgumentException))) result = TestResult.Fail; } catch (Exception ex) { Log.Exception("[Client] Unexpected Exception", ex); result = TestResult.Fail; } return result; } [TestMethod] public TestResult TestSetHTTPRequestHeaderAfterCreateHTTP1_0() { TestResult result = TestResult.Pass; HttpWebRequest wr = (HttpWebRequest)WebRequest.Create("http://127.0.0.1:" + HttpServer.s_CurrentPort.ToString() + "/"); wr.UserAgent = ".Net Micro Framwork Device/4.0"; Log.Comment("Initial version: " + wr.ProtocolVersion); //Default version is 1.1 wr.ProtocolVersion = new Version(1, 0); Log.Comment("Set Version 1.0"); try { // Setup server System.Net.WebHeaderCollection wrc = wr.Headers; if (!VerifyHeaderIsIllegal(wrc, HttpKnownHeaderNames.Accept, "text/plain; q=0.5, text/html, text/x-dvi; q=0.8, text/x-c", typeof(ArgumentException))) result = TestResult.Fail; if (!VerifyHeaderIsIllegal(wrc, HttpKnownHeaderNames.Connection, "close", typeof(ArgumentException))) result = TestResult.Fail; if (!VerifyHeaderIsIllegal(wrc, HttpKnownHeaderNames.ContentLength, "26012", typeof(ArgumentException))) result = TestResult.Fail; //if (!VerifyHeaderIsIllegal(wrc, HttpKnownHeaderNames.ContentType, "image/gif", typeof(ArgumentException))) result = TestResult.Fail; //if (!VerifyHeaderIsIllegal(wrc, HttpKnownHeaderNames.Date, System.DateTime.Today.ToString(), typeof(ArgumentException))) result = TestResult.Fail; if (!VerifyHeaderIsIllegal(wrc, HttpKnownHeaderNames.Expect, "100", typeof(ArgumentException))) result = TestResult.Fail; if (!VerifyHeaderIsIllegal(wrc, HttpKnownHeaderNames.Host, "www.w3.org", typeof(ArgumentException))) result = TestResult.Fail; if (!VerifyHeaderIsIllegal(wrc, HttpKnownHeaderNames.IfModifiedSince, "Sat, 23 May 2009 19:43:31 GMT", typeof(ArgumentException))) result = TestResult.Fail; if (!VerifyHeaderIsIllegal(wrc, HttpKnownHeaderNames.Range, "500-999", typeof(ArgumentException))) result = TestResult.Fail; if (!VerifyHeaderIsIllegal(wrc, HttpKnownHeaderNames.Referer, "http://www.w3.org/hypertext/DataSources/Overview.html", typeof(ArgumentException))) result = TestResult.Fail; if (!VerifyHeaderIsIllegal(wrc, HttpKnownHeaderNames.TransferEncoding, "chunked", typeof(ArgumentException))) result = TestResult.Fail; if (!VerifyHeaderIsIllegal(wrc, HttpKnownHeaderNames.UserAgent, ".NetMicroFramework", typeof(ArgumentException))) result = TestResult.Fail; } catch (Exception ex) { Log.Exception("[Client] Unexpected Exception", ex); result = TestResult.Fail; } return result; } public TestResult ValidateAbleToSetPropertiesValueHTTP1_0() { TestResult result = TestResult.Pass; HttpWebRequest wr = (HttpWebRequest)WebRequest.Create("http://127.0.0.1:" + HttpServer.s_CurrentPort.ToString() + "/"); wr.UserAgent = ".Net Micro Framwork Device/4.0"; Log.Comment("Initial version: " + wr.ProtocolVersion); //Default version is 1.1 wr.ProtocolVersion = new Version(1, 0); Log.Comment("Set Version 1.0"); try { System.Net.WebHeaderCollection wrc = wr.Headers; if (!VerifyHeaderIsLegal(wrc, HttpKnownHeaderNames.AcceptCharset, "iso-8859-5, unicode-1-1;q=0.8", typeof(ArgumentException))) result = TestResult.Fail; if (!VerifyHeaderIsLegal(wrc, HttpKnownHeaderNames.AcceptEncoding, "compress;q=0.5, gzip;q=1.0", typeof(ArgumentException))) result = TestResult.Fail; if (!VerifyHeaderIsLegal(wrc, HttpKnownHeaderNames.AcceptLanguage, "en-US", typeof(ArgumentException))) result = TestResult.Fail; if (!VerifyHeaderIsLegal(wrc, HttpKnownHeaderNames.Age, "2 days", typeof(ArgumentException))) result = TestResult.Fail; if (!VerifyHeaderIsLegal(wrc, HttpKnownHeaderNames.Allow, "GET, PUT", typeof(ArgumentException))) result = TestResult.Fail; if (!VerifyHeaderIsLegal(wrc, HttpKnownHeaderNames.CacheControl, "no-cache", typeof(ArgumentException))) result = TestResult.Fail; if (!VerifyHeaderIsLegal(wrc, HttpKnownHeaderNames.ContentEncoding, "gzip", typeof(ArgumentException))) result = TestResult.Fail; if (!VerifyHeaderIsLegal(wrc, HttpKnownHeaderNames.ContentLanguage, "mi, en", typeof(ArgumentException))) result = TestResult.Fail; if (!VerifyHeaderIsLegal(wrc, HttpKnownHeaderNames.ContentMD5, "60e985979f1d55ab7542440fbb9659e5", typeof(ArgumentException))) result = TestResult.Fail; if (!VerifyHeaderIsLegal(wrc, HttpKnownHeaderNames.ContentRange, "bytes 21010-47021/47022", typeof(ArgumentException))) result = TestResult.Fail; if (!VerifyHeaderIsLegal(wrc, HttpKnownHeaderNames.Cookie, "www.google.com", typeof(ArgumentException))) result = TestResult.Fail; if (!VerifyHeaderIsLegal(wrc, HttpKnownHeaderNames.Expires, "Thu, 01 Dec 1994 16:00:00 GMT", typeof(ArgumentException))) result = TestResult.Fail; if (!VerifyHeaderIsLegal(wrc, HttpKnownHeaderNames.From, "webmaster@w3.org", typeof(ArgumentException))) result = TestResult.Fail; if (!VerifyHeaderIsLegal(wrc, HttpKnownHeaderNames.IfMatch, "r2d2xxxx", typeof(ArgumentException))) result = TestResult.Fail; if (!VerifyHeaderIsLegal(wrc, HttpKnownHeaderNames.IfNoneMatch, "xyzzy", typeof(ArgumentException))) result = TestResult.Fail; if (!VerifyHeaderIsLegal(wrc, HttpKnownHeaderNames.IfRange, "TestIfRange: Need to have Range Header.", typeof(ArgumentException))) result = TestResult.Fail; if (!VerifyHeaderIsLegal(wrc, HttpKnownHeaderNames.IfUnmodifiedSince, "Fri, 22 May 2009 12:43:31 GMT", typeof(ArgumentException))) result = TestResult.Fail; if (!VerifyHeaderIsLegal(wrc, HttpKnownHeaderNames.KeepAlive, "true", typeof(ArgumentException))) result = TestResult.Fail; if (!VerifyHeaderIsLegal(wrc, HttpKnownHeaderNames.LastModified, "Fri, 22 May 2009 12:43:31 GMT", typeof(ArgumentException))) result = TestResult.Fail; if (!VerifyHeaderIsLegal(wrc, HttpKnownHeaderNames.MaxForwards, "10", typeof(ArgumentException))) result = TestResult.Fail; if (!VerifyHeaderIsLegal(wrc, HttpKnownHeaderNames.Pragma, "no-cache", typeof(ArgumentException))) result = TestResult.Fail; if (!VerifyHeaderIsLegal(wrc, HttpKnownHeaderNames.ProxyAuthenticate, "", typeof(ArgumentException))) result = TestResult.Fail; if (!VerifyHeaderIsLegal(wrc, HttpKnownHeaderNames.ProxyAuthorization, "", typeof(ArgumentException))) result = TestResult.Fail; if (!VerifyHeaderIsLegal(wrc, HttpKnownHeaderNames.RetryAfter, "100000", typeof(ArgumentException))) result = TestResult.Fail; if (!VerifyHeaderIsLegal(wrc, HttpKnownHeaderNames.Server, "", typeof(ArgumentException))) result = TestResult.Fail; if (!VerifyHeaderIsLegal(wrc, HttpKnownHeaderNames.SetCookie, "www.microsoft.com", typeof(ArgumentException))) result = TestResult.Fail; if (!VerifyHeaderIsLegal(wrc, HttpKnownHeaderNames.SetCookie2, "www.bing.com", typeof(ArgumentException))) result = TestResult.Fail; if (!VerifyHeaderIsLegal(wrc, HttpKnownHeaderNames.TE, "trailers, deflate;q=0.5", typeof(ArgumentException))) result = TestResult.Fail; if (!VerifyHeaderIsLegal(wrc, HttpKnownHeaderNames.Trailer, "Test Code", typeof(ArgumentException))) result = TestResult.Fail; if (!VerifyHeaderIsLegal(wrc, HttpKnownHeaderNames.Upgrade, "HTTP/2.0, SHTTP/1.3, IRC/6.9, RTA/x11", typeof(ArgumentException))) result = TestResult.Fail; if (!VerifyHeaderIsLegal(wrc, HttpKnownHeaderNames.Via, "1.0 fred, 1.1 nowhere.com (Apache/1.1)", typeof(ArgumentException))) result = TestResult.Fail; if (!VerifyHeaderIsLegal(wrc, HttpKnownHeaderNames.Vary, "*", typeof(ArgumentException))) result = TestResult.Fail; if (!VerifyHeaderIsLegal(wrc, HttpKnownHeaderNames.Warning, "TestWarning", typeof(ArgumentException))) result = TestResult.Fail; if (!VerifyHeaderIsLegal(wrc, HttpKnownHeaderNames.WWWAuthenticate, "WWW-Authenticate", typeof(ArgumentException))) result = TestResult.Fail; } catch (Exception ex) { Log.Exception("[Client] Unexpected Exception", ex); result = TestResult.Fail; } return result; } #endregion Test } } ================================================ FILE: Zelig/Zelig/Test/RunTime/NETMF/System/Http/HttpRequestHeaderTests.cs ================================================ //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // Copyright (c) Microsoft Corporation. All rights reserved. //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// using Microsoft.Llilum.Lwip; using System; using System.Net; namespace Microsoft.Zelig.Test { public class HttpRequestHeaderTests : TestBase, ITestInterface { [SetUp] public InitializeResult Initialize() { Log.Comment("Adding set up for the tests."); try { NetworkInterface[] nis = NetworkInterface.GetAllNetworkInterfaces(); } catch { return InitializeResult.Skip; } return InitializeResult.ReadyToGo; } [TearDown] public void CleanUp() { Log.Comment("Cleaning up after the tests."); // TODO: Add your clean up steps here. } public override TestResult Run( string[] args ) { return TestResult.Pass; } //--// //--// //--// #region Helper methods private TestResult Verify(System.Net.WebHeaderCollection wrc, System.Net.WebHeaderCollection RequestHeaders) { TestResult result = TestResult.Pass; try { Log.Comment("Get Headers - User-Agent"); if (wrc["User-Agent"] != RequestHeaders["User-Agent"]) { Log.Exception("User-Agent property value is incorrect."); result = TestResult.Fail; } Log.Comment("Get Headers - Connection"); if (wrc["Connection"] != RequestHeaders["Connection"]) { Log.Exception("Connection property value is incorrect."); result = TestResult.Fail; } Log.Comment("Get Headers - Host"); if (wrc["Host"] != RequestHeaders["Host"]) { Log.Exception("Host property value is incorrect."); result = TestResult.Fail; } } catch (Exception ex) { if (!HttpTests.ValidateException(ex, typeof(InvalidOperationException))) result = TestResult.Fail; } return result; } #endregion Helper methods #region Test [TestMethod] public TestResult ValidDefaultTestGetHTTPRequestHeaderAfterCreateHTTP1_1() { TestResult result = TestResult.Pass; HttpWebRequest wr = (HttpWebRequest)WebRequest.Create("http://127.0.0.1:" + HttpServer.s_CurrentPort.ToString() + "/"); wr.UserAgent = ".Net Micro Framwork Device/4.0"; Log.Comment("Initial version: " + wr.ProtocolVersion); //Default version is 1.1 Log.Comment("Set Version 1.1"); wr.ProtocolVersion = new Version(1, 1); HttpServer server = new HttpServer("http", ref result) { RequestUri = wr.RequestUri, RequestHeaders = wr.Headers, }; try { // Setup server server.StartServer(); System.Net.WebHeaderCollection wrc = wr.Headers; // Tests Verify(wrc, server.RequestHeaders); } catch (Exception ex) { Log.Exception("[Client] Unexpected Exception", ex); result = TestResult.Fail; } finally { //Stop server server.StopServer(); } return result; } [TestMethod] public TestResult ValidDefaultTestGetHTTPRequestHeaderAfterCreateHTTP1_1_Https() { TestResult result = TestResult.Pass; HttpWebRequest wr = (HttpWebRequest)WebRequest.Create("https://www.microsoft.com:443/"); wr.UserAgent = ".Net Micro Framwork Device/4.0"; Log.Comment("Initial version: " + wr.ProtocolVersion); //Default version is 1.1 Log.Comment("Set Version 1.1"); wr.ProtocolVersion = new Version(1, 1); HttpServer server = new HttpServer("https", 443, ref result) { RequestUri = wr.RequestUri, RequestHeaders = wr.Headers, }; try { // Setup server server.StartServer(); System.Net.WebHeaderCollection wrc = wr.Headers; // Tests Verify(wrc, server.RequestHeaders); } catch (Exception ex) { Log.Exception("[Client] Unexpected Exception", ex); result = TestResult.Fail; } finally { // Stop server server.StopServer(); } return result; } [TestMethod] public TestResult InValidDefaultTestGetHTTPRequestHeaderAfterCreateHTTP1_1_Https() { TestResult result = TestResult.Pass; HttpWebRequest wr = (HttpWebRequest)WebRequest.Create("https://127.0.0.1:443/"); wr.UserAgent = ".Net Micro Framwork Device/4.0"; Log.Comment("Negative Test case 1:"); Log.Comment("Initial version: " + wr.ProtocolVersion); //Default version is 1.1 Log.Comment("Set Version 1.1"); wr.ProtocolVersion = new Version(1, 1); HttpServer server = new HttpServer("http", ref result) { RequestUri = wr.RequestUri, RequestHeaders = wr.Headers, }; try { // Setup server server.StartServer(); System.Net.WebHeaderCollection wrc = wr.Headers; // Tests Verify(wrc, server.RequestHeaders); } catch (Exception ex) { Log.Exception("[Client] Unexpected Exception", ex); result = TestResult.Fail; } finally { // Stop server server.StopServer(); } return result; } [TestMethod] public TestResult InvalidDefaultTestGetHTTPRequestHeaderAfterCreateHTTP1_1_FTP() { TestResult result = TestResult.Pass; UriProperties props = new UriProperties("ftp", "//ftp.microsoft.com"); Uri uri = new Uri(props.OriginalUri); Log.Comment("Negative Test case 2:"); Log.Comment("Create WebRequest with FTP uri"); try { HttpWebRequest wrftp = (HttpWebRequest)WebRequest.Create(uri); } catch (System.NotSupportedException) { Log.Comment("Create WebRequest with FTP uri - Expected System.NotSupportedException"); } HttpWebRequest wr = (HttpWebRequest)WebRequest.Create("http://ftp.microsoft.com"); wr.UserAgent = ".Net Micro Framwork Device/4.0"; Log.Comment("Initial version: " + wr.ProtocolVersion); //Default version is 1.1 Log.Comment("Set Version 1.1"); wr.ProtocolVersion = new Version(1, 1); HttpServer server = new HttpServer("http", ref result) { RequestUri = wr.RequestUri, RequestHeaders = wr.Headers, }; try { // Setup server server.StartServer(); System.Net.WebHeaderCollection wrc = wr.Headers; // Tests Verify(wrc, server.RequestHeaders); } catch (Exception ex) { Log.Exception("[Client] Unexpected Exception", ex); result = TestResult.Fail; } finally { // Stop server server.StopServer(); } return result; } [TestMethod] public TestResult InvalidDefaultTestGetHTTPRequestHeaderAfterCreateHTTP1_1() { TestResult result = TestResult.Pass; HttpWebRequest wr = (HttpWebRequest)WebRequest.Create("http://ftp"); wr.UserAgent = ".Net Micro Framwork Device/4.0"; Log.Comment("Negative Test case 3:"); Log.Comment("Initial version: " + wr.ProtocolVersion); //Default version is 1.1 Log.Comment("Set Version 1.1"); wr.ProtocolVersion = new Version(1, 1); HttpServer server = new HttpServer("http", ref result) { RequestUri = wr.RequestUri, RequestHeaders = wr.Headers, }; try { // Setup server server.StartServer(); System.Net.WebHeaderCollection wrc = wr.Headers; // Tests Verify(wrc, server.RequestHeaders); } catch (Exception ex) { Log.Exception("[Client] Unexpected Exception", ex); result = TestResult.Fail; } finally { // Stop server server.StopServer(); } return result; } [TestMethod] public TestResult ValidDefaultTestGetHTTPRequestHeaderAfterCreateHTTP1_0() { TestResult result = TestResult.Pass; HttpWebRequest wr = (HttpWebRequest)WebRequest.Create("http://127.0.0.1:" + HttpServer.s_CurrentPort.ToString() + "/"); wr.UserAgent = ".Net Micro Framwork Device/4.0"; Log.Comment("Initial version: " + wr.ProtocolVersion); //Default version is 1.1 Log.Comment("Set Version 1.0"); wr.ProtocolVersion = new Version(1, 0); HttpServer server = new HttpServer("http", ref result) { RequestUri = wr.RequestUri, RequestHeaders = wr.Headers, }; try { // Setup server server.StartServer(); System.Net.WebHeaderCollection wrc = wr.Headers; // Tests Verify(wrc, server.RequestHeaders); } catch (Exception ex) { Log.Exception("[Client] Unexpected Exception", ex); result = TestResult.Fail; } finally { // Stop server server.StopServer(); } return result; } [TestMethod] public TestResult ValidDefaultTestGetHTTPRequestHeaderAfterCreateHTTP1_0_HTTPS() { TestResult result = TestResult.Pass; HttpWebRequest wr = (HttpWebRequest)WebRequest.Create("https://127.0.0.1:443/"); wr.UserAgent = ".Net Micro Framwork Device/4.0"; Log.Comment("Initial version: " + wr.ProtocolVersion); //Default version is 1.1 Log.Comment("Set Version 1.0"); wr.ProtocolVersion = new Version(1, 0); HttpServer server = new HttpServer("https", 443, ref result) { RequestUri = wr.RequestUri, RequestHeaders = wr.Headers, }; try { // Setup server server.StartServer(); System.Net.WebHeaderCollection wrc = wr.Headers; // Tests Verify(wrc, server.RequestHeaders); } catch (Exception ex) { Log.Exception("[Client] Unexpected Exception", ex); result = TestResult.Fail; } finally { // Stop server server.StopServer(); } return result; } [TestMethod] public TestResult InValidDefaultTestGetHTTPRequestHeaderAfterCreateHTTP1_0_HTTPS() { TestResult result = TestResult.Pass; HttpWebRequest wr = (HttpWebRequest)WebRequest.Create("https://127.0.0.1:443/"); wr.UserAgent = ".Net Micro Framwork Device/4.0"; Log.Comment("Negative Test case 4:"); Log.Comment("Initial version: " + wr.ProtocolVersion); //Default version is 1.1 Log.Comment("Set Version 1.0"); wr.ProtocolVersion = new Version(1, 0); HttpServer server = new HttpServer("http", ref result) { RequestUri = wr.RequestUri, RequestHeaders = wr.Headers, }; try { // Setup server server.StartServer(); System.Net.WebHeaderCollection wrc = wr.Headers; // Tests Verify(wrc, server.RequestHeaders); } catch (Exception ex) { Log.Exception("[Client] Unexpected Exception", ex); result = TestResult.Fail; } finally { // Stop server server.StopServer(); } return result; } [TestMethod] public TestResult InValidDefaultTestGetHTTPRequestHeaderAfterCreateHTTP1_0_FTP() { TestResult result = TestResult.Pass; HttpWebRequest wr = (HttpWebRequest)WebRequest.Create("http://ftp"); wr.UserAgent = ".Net Micro Framwork Device/4.0"; Log.Comment("Negative Test case 5:"); Log.Comment("Initial version: " + wr.ProtocolVersion); //Default version is 1.1 Log.Comment("Set Version 1.0"); wr.ProtocolVersion = new Version(1, 0); HttpServer server = new HttpServer("http", ref result) { RequestUri = wr.RequestUri, RequestHeaders = wr.Headers, }; try { // Setup server server.StartServer(); System.Net.WebHeaderCollection wrc = wr.Headers; // Tests Verify(wrc, server.RequestHeaders); } catch (Exception ex) { Log.Exception("[Client] Unexpected Exception", ex); result = TestResult.Fail; } finally { // Stop server server.StopServer(); } return result; } #endregion Test } } ================================================ FILE: Zelig/Zelig/Test/RunTime/NETMF/System/Http/HttpResponseHeaderTests.cs ================================================ //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // Copyright (c) Microsoft Corporation. All rights reserved. //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// using System; using System.Net; namespace Microsoft.Zelig.Test { public class HttpResponseHeaderTests : TestBase, ITestInterface { [SetUp] public InitializeResult Initialize() { Log.Comment("Adding set up for the tests."); // Add your functionality here. return InitializeResult.ReadyToGo; } [TearDown] public void CleanUp() { Log.Comment("Cleaning up after the tests."); // TODO: Add your clean up steps here. } public override TestResult Run( string[] args ) { return TestResult.Pass; } //--// //--// //--// #region Helper methods private TestResult StopServerListener(ref HttpServer server) { TestResult result = TestResult.Pass; HttpListener mylistener = server.Listener; try { mylistener.Stop(); } catch (Exception ex) { Log.Exception("Exception when stop listener: " + ex.Message.ToString()); result = TestResult.Fail; } return result; } private TestResult SetCommonHttpResponseHeaders(ref System.Net.WebHeaderCollection wrs) { TestResult result = TestResult.Pass; try { Log.Comment("Set Response Headers Properties"); wrs.Set(HttpKnownHeaderNames.AcceptRanges.ToString(), "bytes"); wrs.Set(HttpKnownHeaderNames.Age.ToString(), "0"); wrs.Set(HttpKnownHeaderNames.Allow.ToString(), "GET, PUT"); wrs.Set(HttpKnownHeaderNames.CacheControl.ToString(), "no-cache"); //Force intermediate caches to validate their copies directly with the origin server. wrs.Set(HttpKnownHeaderNames.Connection.ToString(), "close"); wrs.Set(HttpKnownHeaderNames.ContentEncoding.ToString(), "gzip"); wrs.Set(HttpKnownHeaderNames.ContentLanguage.ToString(), "mi, en"); wrs.Set(HttpKnownHeaderNames.ContentLength.ToString(), "26012"); wrs.Set(HttpKnownHeaderNames.ContentLocation.ToString(), ""); wrs.Set(HttpKnownHeaderNames.ContentMD5.ToString(), "60e985979f1d55ab7542440fbb9659e5"); wrs.Set(HttpKnownHeaderNames.ContentRange.ToString(), "bytes 21010-47021/47022"); wrs.Set(HttpKnownHeaderNames.ContentType.ToString(), "text/plain, image/gif"); wrs.Set(HttpKnownHeaderNames.Date.ToString(), System.DateTime.Today.ToString()); wrs.Set(HttpKnownHeaderNames.ETag.ToString(), "W/"); wrs.Set(HttpKnownHeaderNames.Expires.ToString(), "Thu, 01 Dec 1994 16:00:00 GMT"); //always force client cache validate on the request wrs.Set(HttpKnownHeaderNames.KeepAlive.ToString(), ""); wrs.Set(HttpKnownHeaderNames.LastModified.ToString(), "Fri, 22 May 2009 12:43:31 GMT"); wrs.Set(HttpKnownHeaderNames.Location.ToString(), "http://www.w3.org/pub/WWW/People.html"); wrs.Set(HttpKnownHeaderNames.Pragma.ToString(), "no-cache"); wrs.Set(HttpKnownHeaderNames.ProxyAuthenticate.ToString(), "NNNNNNNNNNNNNNNNN=="); wrs.Set(HttpKnownHeaderNames.RetryAfter.ToString(), "120"); wrs.Set(HttpKnownHeaderNames.SetCookie.ToString(), "http://www.w3.org/hypertext/DataSources/Overview.html"); wrs.Set(HttpKnownHeaderNames.Trailer.ToString(), "Test Code"); wrs.Set(HttpKnownHeaderNames.TransferEncoding.ToString(), "8BIT"); wrs.Set(HttpKnownHeaderNames.Upgrade.ToString(), "HTTP/2.0, SHTTP/1.3"); wrs.Set(HttpKnownHeaderNames.Vary.ToString(), "TestVary"); wrs.Set(HttpKnownHeaderNames.Via.ToString(), "1.0 fred, 1.1 nowhere.com (Apache/1.1)"); wrs.Set(HttpKnownHeaderNames.Warning.ToString(), "TestWarning"); wrs.Set(HttpKnownHeaderNames.WWWAuthenticate.ToString(), "BASIC realm=\"executives\""); } catch (Exception ex) { if (!HttpTests.ValidateException(ex, typeof(InvalidOperationException))) result = TestResult.Fail; } return result; } private TestResult SetCommonHttpResponseHeaders_1_0(ref System.Net.WebHeaderCollection wrs) { TestResult result = TestResult.Pass; try { Log.Comment("Set Response Headers Properties"); wrs.Set(HttpKnownHeaderNames.Allow.ToString(), "GET"); wrs.Set(HttpKnownHeaderNames.ContentEncoding.ToString(), "gzip"); wrs.Set(HttpKnownHeaderNames.ContentLength.ToString(), "26012"); wrs.Set(HttpKnownHeaderNames.ContentType.ToString(), "text/plain, image/gif"); wrs.Set(HttpKnownHeaderNames.Expires.ToString(), "Thu, 01 Dec 1994 16:00:00 GMT"); //always force client cache validate on the request wrs.Set(HttpKnownHeaderNames.KeepAlive.ToString(), ""); wrs.Set(HttpKnownHeaderNames.LastModified.ToString(), "Fri, 22 May 2009 12:43:31 GMT"); wrs.Set(HttpKnownHeaderNames.Location.ToString(), "http://www.w3.org/pub/WWW/People.html"); wrs.Set(HttpKnownHeaderNames.WWWAuthenticate.ToString(), "BASIC realm=\"executives\""); } catch (Exception ex) { if (!HttpTests.ValidateException(ex, typeof(InvalidOperationException))) result = TestResult.Fail; } return result; } private TestResult VerifyHttpResponseHeaders(System.Net.WebHeaderCollection wrc, System.Net.WebHeaderCollection wrs) { TestResult result = TestResult.Pass; try { string[] headers = wrc.AllKeys; string sValue = String.Empty; for (int i = 0; i < wrc.Count; i++) { sValue = wrc[headers[i]]; if (sValue != wrs[headers[i]]) { Log.Exception(headers[i] + "property value is incorrect."); result = TestResult.Fail; } } } catch (Exception ex) { if (!HttpTests.ValidateException(ex, typeof(InvalidOperationException))) result = TestResult.Fail; } return result; } #endregion helper methods #region Test [TestMethod] public TestResult ValidDefaultTestGetHTTPResponseHeaderAfterCreateHTTP1_1() { TestResult result = TestResult.Pass; HttpWebRequest wr = (HttpWebRequest)WebRequest.Create("http://127.0.0.1:8080/"); wr.UserAgent = ".Net Micro Framwork Device/4.0"; Log.Comment("Initial version: " + wr.ProtocolVersion); //Default version is 1.1 Log.Comment("Set Version 1.1"); wr.ProtocolVersion = new Version(1, 1); HttpServer server = new HttpServer("http", 8080, ref result) { RequestUri = wr.RequestUri, RequestHeaders = wr.Headers, ResponseString = "ValidDefaultTestGetHTTPResponseHeaderAfterCreateHTTP1_1" }; try { // Setup server server.StartServer(); System.Net.WebHeaderCollection wrs = server.RequestHeaders; SetCommonHttpResponseHeaders(ref wrs); HttpWebResponse response = (HttpWebResponse)wr.GetResponse(); WebHeaderCollection wrc = wr.Headers; VerifyHttpResponseHeaders(wrc, wrs); response.Close(); } catch (Exception ex) { Log.Exception("[Client] Unexpected Exception", ex); result = TestResult.Fail; } finally { StopServerListener(ref server); //Stop server server.StopServer(); } return result; } //This test case get System.NotSupportedException public TestResult ValidDefaultTestGetHTTPResponseHeaderAfterCreateHTTP1_1_https() { TestResult result = TestResult.Pass; HttpWebRequest wr = (HttpWebRequest)WebRequest.Create("https://127.0.0.1:443/"); wr.UserAgent = ".Net Micro Framwork Device/4.0"; Log.Comment("Initial version: " + wr.ProtocolVersion); //Default version is 1.1 Log.Comment("Set Version 1.1"); wr.ProtocolVersion = new Version(1, 1); HttpServer server = new HttpServer("https", 443, ref result) { RequestUri = wr.RequestUri, RequestHeaders = wr.Headers, }; try { // Setup server server.StartServer(); System.Net.WebHeaderCollection wrs = server.RequestHeaders; SetCommonHttpResponseHeaders(ref wrs); //Get System.NotSupportedException when retrive response -- Need further investigation HttpWebResponse response = (HttpWebResponse)wr.GetResponse(); WebHeaderCollection wrc = wr.Headers; VerifyHttpResponseHeaders(wrc, wrs); response.Close(); } catch (Exception ex) { Log.Exception("[Client] Unexpected Exception", ex); result = TestResult.Fail; } finally { StopServerListener(ref server); //Stop server server.StopServer(); } return result; } public TestResult InValidDefaultTestGetHTTPResponseHeaderAfterCreateHTTP1_1_ftp() { TestResult result = TestResult.Pass; HttpWebRequest wr = (HttpWebRequest)WebRequest.Create("http://ftp.microsoft.com"); wr.UserAgent = ".Net Micro Framwork Device/4.0"; Log.Comment("Initial version: " + wr.ProtocolVersion); //Default version is 1.1 Log.Comment("Set Version 1.0"); wr.ProtocolVersion = new Version(1, 1); HttpServer server = new HttpServer("http", 8080, ref result) { RequestUri = wr.RequestUri, RequestHeaders = wr.Headers, }; try { // Setup server server.StartServer(); System.Net.WebHeaderCollection wrs = server.RequestHeaders; SetCommonHttpResponseHeaders(ref wrs); HttpWebResponse response = (HttpWebResponse)wr.GetResponse(); WebHeaderCollection wrc = wr.Headers; VerifyHttpResponseHeaders(wrc, wrs); response.Close(); } catch (Exception ex) { Log.Exception("[Client] Unexpected Exception", ex); result = TestResult.Fail; } finally { StopServerListener(ref server); //Stop server server.StopServer(); } return result; } [TestMethod] public TestResult ValidDefaultTestGetHTTPResponseHeaderAfterCreateHTTP1_0() { TestResult result = TestResult.Pass; HttpWebRequest wr = (HttpWebRequest)WebRequest.Create("http://127.0.0.1:8080/"); wr.UserAgent = ".Net Micro Framwork Device/4.0"; Log.Comment("Initial version: " + wr.ProtocolVersion); //Default version is 1.0 Log.Comment("Set Version 1.0"); wr.ProtocolVersion = new Version(1, 0); HttpServer server = new HttpServer("http", 8080, ref result) { RequestUri = wr.RequestUri, RequestHeaders = wr.Headers, ResponseString = "ValidDefaultTestGetHTTPResponseHeaderAfterCreateHTTP1_0" }; try { // Setup server server.StartServer(); System.Net.WebHeaderCollection wrs = server.RequestHeaders; SetCommonHttpResponseHeaders_1_0(ref wrs); HttpWebResponse response = (HttpWebResponse)wr.GetResponse(); WebHeaderCollection wrc = wr.Headers; VerifyHttpResponseHeaders(wrc, wrs); response.Close(); } catch (Exception ex) { Log.Exception("[Client] Unexpected Exception", ex); result = TestResult.Fail; } finally { StopServerListener(ref server); //Stop server server.StopServer(); } return result; } //This test case get System.NotSupportedException public TestResult ValidDefaultTestGetHTTPResponseHeaderAfterCreateHTTP1_1_https1_0() { TestResult result = TestResult.Pass; HttpWebRequest wr = (HttpWebRequest)WebRequest.Create("https://127.0.0.1:443/"); wr.UserAgent = ".Net Micro Framwork Device/4.0"; Log.Comment("Initial version: " + wr.ProtocolVersion); //Default version is 1.1 Log.Comment("Set Version 1.0"); wr.ProtocolVersion = new Version(1, 0); HttpServer server = new HttpServer("https", 443, ref result) { RequestUri = wr.RequestUri, RequestHeaders = wr.Headers, }; try { // Setup server server.StartServer(); System.Net.WebHeaderCollection wrs = server.RequestHeaders; SetCommonHttpResponseHeaders_1_0(ref wrs); //Get System.NotSupportedException when retrive response -- Need further investigation HttpWebResponse response = (HttpWebResponse)wr.GetResponse(); WebHeaderCollection wrc = wr.Headers; VerifyHttpResponseHeaders(wrc, wrs); response.Close(); } catch (Exception ex) { Log.Exception("[Client] Unexpected Exception", ex); result = TestResult.Fail; } finally { StopServerListener(ref server); //Stop server server.StopServer(); } return result; } public TestResult InValidDefaultTestGetHTTPResponseHeaderAfterCreateHTTP1_1_ftp1_0() { TestResult result = TestResult.Pass; HttpWebRequest wr = (HttpWebRequest)WebRequest.Create("http://ftp.microsoft.com"); wr.UserAgent = ".Net Micro Framwork Device/4.0"; Log.Comment("Initial version: " + wr.ProtocolVersion); //Default version is 1.1 Log.Comment("Set Version 1.0"); wr.ProtocolVersion = new Version(1, 0); HttpServer server = new HttpServer("http", 8080, ref result) { RequestUri = wr.RequestUri, RequestHeaders = wr.Headers, }; try { // Setup server server.StartServer(); System.Net.WebHeaderCollection wrs = server.RequestHeaders; SetCommonHttpResponseHeaders_1_0(ref wrs); HttpWebResponse response = (HttpWebResponse)wr.GetResponse(); WebHeaderCollection wrc = wr.Headers; VerifyHttpResponseHeaders(wrc, wrs); response.Close(); } catch (Exception ex) { Log.Exception("[Client] Unexpected Exception", ex); result = TestResult.Fail; } finally { StopServerListener(ref server); //Stop server server.StopServer(); } return result; } #endregion Test } } ================================================ FILE: Zelig/Zelig/Test/RunTime/NETMF/System/Http/HttpServer.cs ================================================ //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // Copyright (c) Microsoft Corporation. All rights reserved. //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// using System; using System.Net; using System.Threading; using System.Security.Cryptography.X509Certificates; namespace Microsoft.Zelig.Test { public class HttpServer { private HttpListener listener; private TestResult result; private string serverPrefix = ""; private bool running = false; Thread server; AutoResetEvent evtStarted = new AutoResetEvent(false); public static int s_CurrentPort = 8080; public HttpServer(string prefix, ref TestResult Result) { serverPrefix = prefix; listener = new HttpListener(prefix, s_CurrentPort); result = Result; } public HttpServer(string prefix, int Port, ref TestResult Result) { serverPrefix = prefix; listener = new HttpListener(prefix, Port); result = Result; } public string ResponseString { get; set; } public HttpListener Listener { get { return listener; } set { this.listener = value; } } public Uri RequestUri { get; set; } public WebHeaderCollection RequestHeaders { get; set; } public void StartServer() { server = new Thread(new ThreadStart(RunServer)); server.Start(); if(!evtStarted.WaitOne(5000, false)) { s_CurrentPort++; throw new Exception("StartServer failed"); } } public void StopServer() { if (running) running = false; listener.Abort(); if (server.IsAlive && !server.Join(1000)) { server.Abort(); } } private void RunServer() { try { running = true; //////if (serverPrefix == "https") //////{ ////// if (Microsoft.SPOT.Hardware.SystemInfo.SystemID.SKU == 3) ////// { ////// listener.HttpsCert = new X509Certificate(m_emulatorCertData, "NetMF"); ////// } ////// else ////// { ////// //string serverCertAsString = HttpServer.Resource1.GetString(HttpServer.Resource1.StringResources.cert_device_microsoft_com); ////// //byte[] serverCertAsArray = System.Text.Encoding.UTF8.GetBytes(serverCertAsString); ////// //listener.HttpsCert = new X509Certificate(serverCertAsArray); ////// } //////} listener.Start(); Log.Comment("[Server] Starting listener..."); evtStarted.Set(); while (running) { HttpListenerContext context = listener.GetContext(); if (context == null) continue; HttpListenerRequest request = context.Request; HttpTests.PrintHeaders("Server Received request: ", request.Headers); HttpListenerResponse listenerResponse = context.Response; listenerResponse.KeepAlive = false; byte[] buffer = System.Text.Encoding.UTF8.GetBytes(this.ResponseString); switch (request.HttpMethod.ToUpper()) { case "GET": ProcessClientGetRequest(context); break; case "POST": ProcessClientPostRequest(context); break; case "HEAD": ProcessException(context, this); break; } listenerResponse.OutputStream.Write(buffer, 0, buffer.Length); listenerResponse.Close(); } } catch (ThreadAbortException) { } catch (WebException wex) { Log.Exception("Server throw exception: ", wex); return; } catch (Exception ex) { Log.Exception("[Server] Unexpected Server Exception", ex); } finally { if (running) { listener.Stop(); } } } private static void ProcessClientPostRequest(HttpListenerContext context) { } private static void ProcessException(HttpListenerContext context, HttpServer server) { HttpListenerRequest request = context.Request; HttpListenerResponse response = context.Response; string strFilePath = GetPathFromURL(request.RawUrl == null ? "" : request.RawUrl); // There is one particular URL that we process differently if (strFilePath == "\\webexception\\ConnClose.html") { // Throw the 'WebException' object with a message string, message status server.ResponseString = (new WebException("ConnectionClosed", WebExceptionStatus.ConnectionClosed)).ToString(); } if (strFilePath == "\\webexception\\KeepAliveFailure.html") { // Throw the 'WebException' object with a message string, message status server.ResponseString = (new WebException("KeepAliveFailure", WebExceptionStatus.KeepAliveFailure)).ToString(); } if (strFilePath == "\\webexception\\Pending.html") { // Throw the 'WebException' object with a message string, message status server.ResponseString = (new WebException("Pending", WebExceptionStatus.Pending)).ToString(); } if (strFilePath == "\\webexception\\PipelineFailure.html") { // Throw the 'WebException' object with a message string, message status server.ResponseString = (new WebException("PipelineFailure", WebExceptionStatus.PipelineFailure)).ToString(); } if (strFilePath == "\\webexception\\ProxyNameResolutionFailure.html") { // Throw the 'WebException' object with a message string, message status server.ResponseString = (new WebException("ProxyNameResolutionFailure", WebExceptionStatus.ProxyNameResolutionFailure)).ToString(); } if (strFilePath == "\\webexception\\ReceiveFailure.html") { // Throw the 'WebException' object with a message string, message status server.ResponseString = (new WebException("ReceiveFailure", WebExceptionStatus.ReceiveFailure)).ToString(); } if (strFilePath == "\\webexception\\RequestCanceled.html") { // Throw the 'WebException' object with a message string, message status server.ResponseString = (new WebException("RequestCanceled", WebExceptionStatus.RequestCanceled)).ToString(); } if (strFilePath == "\\webexception\\SecureChannelFailure.html") { // Throw the 'WebException' object with a message string, message status server.ResponseString = (new WebException("SecureChannelFailure", WebExceptionStatus.SecureChannelFailure)).ToString(); } if (strFilePath == "\\webexception\\SendFailure.html") { // Throw the 'WebException' object with a message string, message status server.ResponseString = (new WebException("SendFailure", WebExceptionStatus.SendFailure)).ToString(); } if (strFilePath == "\\webexception\\Success.html") { // Throw the 'WebException' object with a message string, message status server.ResponseString = (new WebException("Success", WebExceptionStatus.Success)).ToString(); } if (strFilePath == "\\webexception\\Timeout.html") { // Throw the 'WebException' object with a message string, message status server.ResponseString = (new WebException("Timeout", WebExceptionStatus.Timeout)).ToString(); } if (strFilePath == "\\webexception\\TrustFailure.html") { // Throw the 'WebException' object with a message string, message status server.ResponseString = (new WebException("TrustFailure", WebExceptionStatus.TrustFailure)).ToString(); } if (strFilePath == "\\webexception\\ConnectFailure.html") { // Throw the 'WebException' object with a message string, message status server.ResponseString = (new WebException("ConnectFailure", WebExceptionStatus.ConnectFailure)).ToString(); } if (strFilePath == "\\webexception\\NameResolutionFailure.html") { // Throw the 'WebException' object with a message string, message status server.ResponseString = (new WebException("NameResolutionFailure", WebExceptionStatus.NameResolutionFailure)).ToString(); } if (strFilePath == "\\webexception\\ProtocolError.html") { // Throw the 'WebException' object with a message string, message status server.ResponseString = (new WebException("ProtocolError", WebExceptionStatus.ProtocolError)).ToString(); } if (strFilePath == "\\webexception\\ServerProtocolViolation.html") { // Throw the 'WebException' object with a message string, message status server.ResponseString = (new WebException("ServerProtocolViolation", WebExceptionStatus.ServerProtocolViolation)).ToString(); } byte[] buffer = System.Text.Encoding.UTF8.GetBytes(server.ResponseString); response.OutputStream.Write(buffer, 0, buffer.Length); return; } private static void ProcessClientGetRequest(HttpListenerContext context) { HttpListenerRequest request = context.Request; HttpListenerResponse response = context.Response; string strFilePath = GetPathFromURL(request.RawUrl == null ? "" : request.RawUrl); if (strFilePath == null || strFilePath.Length == 0) { return; } // There is one particular URL that we process differently else if (strFilePath == "\\PasswordProtected") { ProcessPasswordProtectedArea(request, response); return; } else if (strFilePath == "\\webpages\\index.html") //return Ambiguous { response.StatusCode = (int)HttpStatusCode.Ambiguous; } else if (strFilePath == "\\webpages\\accepted.html") //return Accepted { response.StatusCode = (int)HttpStatusCode.Accepted; } else if (strFilePath == "\\webpages\\Gateway.html") //return BadGateway { response.StatusCode = (int)HttpStatusCode.BadGateway; } else if (strFilePath == "\\webpages\\badRequest.html") //return BadRequest { response.StatusCode = (int)HttpStatusCode.BadRequest; } else if (strFilePath == "\\webpages\\conflict.html") //return Conflict { response.StatusCode = (int)HttpStatusCode.Conflict; } else if (strFilePath == "\\webpages\\continue.html") //return Continue { response.StatusCode = (int)HttpStatusCode.Continue; } else if (strFilePath == "\\webpages\\created.html") //return Created { response.StatusCode = (int)HttpStatusCode.Created; } else if (strFilePath == "\\webpages\\expfailed.html") //return ExpectationFailed { response.StatusCode = (int)HttpStatusCode.ExpectationFailed; } else if (strFilePath == "\\webpages\\forbidden.html") //return Forbidden { response.StatusCode = (int)HttpStatusCode.Forbidden; } else if (strFilePath == "\\webpages\\found.html") //return Found { response.StatusCode = (int)HttpStatusCode.Found; } else if (strFilePath == "\\webpages\\gateway.html") //return GatewayTimeout { response.StatusCode = (int)HttpStatusCode.GatewayTimeout; } else if (strFilePath == "\\webpages\\gone.html") //return Gone { response.StatusCode = (int)HttpStatusCode.Gone; } else if (strFilePath == "\\webpages\\httpversion.html") //return HttpVersionNotSupported { response.StatusCode = (int)HttpStatusCode.HttpVersionNotSupported; } else if (strFilePath == "\\webpages\\iserror.html") //return InternalServerError { response.StatusCode = (int)HttpStatusCode.InternalServerError; } else if (strFilePath == "\\webpages\\lrequired.html") //return LengthRequired { response.StatusCode = (int)HttpStatusCode.LengthRequired; } else if (strFilePath == "\\webpages\\method.html") //return MethodNotAllowed { response.StatusCode = (int)HttpStatusCode.MethodNotAllowed; } else if (strFilePath == "\\webpages\\moved.html") //return Moved { response.StatusCode = (int)HttpStatusCode.Moved; } else if (strFilePath == "\\webpages\\NoContent.html") //return NoContent { response.StatusCode = (int)HttpStatusCode.NoContent; } else if (strFilePath == "\\webpages\\nonauthInfo.html") //return NonAuthoritativeInformation { response.StatusCode = (int)HttpStatusCode.NonAuthoritativeInformation; } else if (strFilePath == "\\webpages\\NotAccept.html") //return NotAcceptable { response.StatusCode = (int)HttpStatusCode.NotAcceptable; } else if (strFilePath == "\\webpages\\NotImplement.html") //return NotImplemented { response.StatusCode = (int)HttpStatusCode.NotImplemented; } else if (strFilePath == "\\webpages\\NotModified.html") //return NotModified { response.StatusCode = (int)HttpStatusCode.NotModified; } else if (strFilePath == "\\webpages\\PContent.html") //return PartialContent { response.StatusCode = (int)HttpStatusCode.PartialContent; } else if (strFilePath == "\\webpages\\Precond.html") //return PreconditionFailed { response.StatusCode = (int)HttpStatusCode.PreconditionFailed; } else if (strFilePath == "\\webpages\\ProxyAuth.html") //return ProxyAuthenticationRequired { response.StatusCode = (int)HttpStatusCode.ProxyAuthenticationRequired; } else if (strFilePath == "\\webpages\\redirect.html") //return Redirect { response.StatusCode = (int)HttpStatusCode.Redirect; } else if (strFilePath == "\\webpages\\RMethod.html") //return RedirectMethod { response.StatusCode = (int)HttpStatusCode.RedirectMethod; } else if (strFilePath == "\\webpages\\reqRange.html") //return RequestedRangeNotSatisfiable { response.StatusCode = (int)HttpStatusCode.RequestedRangeNotSatisfiable; } else if (strFilePath == "\\webpages\\payment.html") //return PaymentRequired { response.StatusCode = (int)HttpStatusCode.PaymentRequired; } else if (strFilePath == "\\webpages\\reqEntity.html") //return RequestEntityTooLarge { response.StatusCode = (int)HttpStatusCode.RequestEntityTooLarge; } else if (strFilePath == "\\webpages\\testTimeOut.html") //return RequestTimeout { response.StatusCode = (int)HttpStatusCode.RequestTimeout; } else if (strFilePath == "\\webpages\\ResetContent.html") //return ResetContent { response.StatusCode = (int)HttpStatusCode.ResetContent; } else if (strFilePath == "\\webpages\\SeeOther.html") //return SeeOther { response.StatusCode = (int)HttpStatusCode.SeeOther; } else if (strFilePath == "\\webpages\\SwitchProt.html") //return SwitchingProtocols { response.StatusCode = (int)HttpStatusCode.SwitchingProtocols; } else if (strFilePath == "\\webpages\\Unauth.html") //return Unauthorized { response.StatusCode = (int)HttpStatusCode.Unauthorized; } else if (strFilePath == "\\webpages\\Unused.html") //return Unused { response.StatusCode = (int)HttpStatusCode.Unused; } else if (strFilePath == "\\webpages\\UseProxy.html") //return UseProxy { response.StatusCode = (int)HttpStatusCode.UseProxy; } else if (strFilePath == "\\webpages\\service.html") //return ServiceUnavailable { response.StatusCode = (int)HttpStatusCode.ServiceUnavailable; } else if (strFilePath == "\\webpages\\tempRedir.html") //return TemporaryRedirect { response.StatusCode = (int)HttpStatusCode.TemporaryRedirect; } else if (strFilePath == "\\local\\webpages\\mysubdir\\index.html" || strFilePath.Length > 30) //return RequestUriTooLong { response.StatusCode = (int)HttpStatusCode.RequestUriTooLong; } else if (strFilePath == "\\webpages\\NotFound.html") { response.StatusCode = (int)HttpStatusCode.NotFound; } else if (strFilePath == "\\webpages\\NotExistUriPath.html") { response.StatusCode = (int)HttpStatusCode.NotFound; } return; } private static void ProcessPasswordProtectedArea(HttpListenerRequest request, HttpListenerResponse response) { } static private string GetPathFromURL(string URL) { char[] szFilePath = URL.ToCharArray(); for (int i = 0, length = szFilePath.Length; i < length; i++) { if (szFilePath[i] == '/') { szFilePath[i] = '\\'; } } // Return updated string with \SD in front return new string(szFilePath); } #region EmulatorCertificate // // The following data is a self-signed certificate in .PFX format that is used by this sample when deployed to the emulator. // private static byte[] m_emulatorCertData = new byte[] { 0x30, 0x82, 0x0a, 0x73, 0x02, 0x01, 0x03, 0x30, 0x82, 0x0a, 0x33, 0x06, 0x09, 0x2a, 0x86, 0x48, 0x86, 0xf7, 0x0d, 0x01, 0x07, 0x01, 0xa0, 0x82, 0x0a, 0x24, 0x04, 0x82, 0x0a, 0x20, 0x30, 0x82, 0x0a, 0x1c, 0x30, 0x82, 0x06, 0x15, 0x06, 0x09, 0x2a, 0x86, 0x48, 0x86, 0xf7, 0x0d, 0x01, 0x07, 0x01, 0xa0, 0x82, 0x06, 0x06, 0x04, 0x82, 0x06, 0x02, 0x30, 0x82, 0x05, 0xfe, 0x30, 0x82, 0x05, 0xfa, 0x06, 0x0b, 0x2a, 0x86, 0x48, 0x86, 0xf7, 0x0d, 0x01, 0x0c, 0x0a, 0x01, 0x02, 0xa0, 0x82, 0x04, 0xfe, 0x30, 0x82, 0x04, 0xfa, 0x30, 0x1c, 0x06, 0x0a, 0x2a, 0x86, 0x48, 0x86, 0xf7, 0x0d, 0x01, 0x0c, 0x01, 0x03, 0x30, 0x0e, 0x04, 0x08, 0x10, 0x8f, 0xb2, 0x4b, 0x95, 0x7e, 0x94, 0x37, 0x02, 0x02, 0x07, 0xd0, 0x04, 0x82, 0x04, 0xd8, 0xfc, 0xc9, 0xde, 0x58, 0x78, 0x73, 0x14, 0xa8, 0xf8, 0xd6, 0xed, 0x28, 0x53, 0x9e, 0x7a, 0xd3, 0x31, 0x33, 0x7c, 0xea, 0xe9, 0x1a, 0xdd, 0x46, 0x62, 0x66, 0x65, 0xf7, 0xbb, 0x8f, 0xfd, 0xb2, 0xd0, 0x81, 0x68, 0xfe, 0x24, 0x51, 0x30, 0xa7, 0xf3, 0x45, 0x90, 0x82, 0x21, 0xfe, 0x49, 0x32, 0xdc, 0xe2, 0x51, 0xf0, 0x5a, 0xec, 0x05, 0xee, 0x48, 0x36, 0x94, 0x6b, 0xc5, 0xa2, 0x07, 0x24, 0xaf, 0xec, 0x6f, 0x4b, 0xb5, 0x7e, 0x9d, 0x15, 0x54, 0xbc, 0x2d, 0x1f, 0xe1, 0x63, 0x87, 0x11, 0x7e, 0xa7, 0x45, 0x61, 0x52, 0x67, 0xbc, 0xb1, 0x64, 0x1b, 0xa2, 0x18, 0xb5, 0x1d, 0xf5, 0xca, 0x48, 0x7a, 0xf7, 0x95, 0xce, 0x78, 0x00, 0x2b, 0x78, 0x61, 0x98, 0x07, 0xff, 0xab, 0x29, 0xc6, 0xc7, 0x05, 0x69, 0x33, 0x68, 0xad, 0x9b, 0xc7, 0x64, 0x38, 0x56, 0x6c, 0x43, 0xd9, 0x24, 0xfd, 0x6c, 0x9e, 0xbd, 0xd3, 0xe3, 0x77, 0x7b, 0xe6, 0x33, 0x9b, 0xa9, 0x49, 0x14, 0xab, 0xa2, 0x62, 0x75, 0xe8, 0xe8, 0xd7, 0xe4, 0x59, 0x66, 0x8d, 0xcc, 0x67, 0xcc, 0x57, 0x90, 0x4c, 0x52, 0x5a, 0x56, 0x8d, 0xea, 0x79, 0xc8, 0x5a, 0x2d, 0xc1, 0xdb, 0xd4, 0x68, 0x34, 0x8d, 0x6c, 0xbf, 0x4c, 0x5f, 0xa9, 0x0c, 0x58, 0x3e, 0xc2, 0x68, 0x89, 0x91, 0xee, 0xc5, 0xcb, 0x13, 0x38, 0x5f, 0x9c, 0x90, 0x3f, 0x0a, 0x28, 0x03, 0xca, 0xa1, 0x60, 0xa8, 0xfd, 0x96, 0xa3, 0x02, 0xf1, 0xd8, 0x51, 0x46, 0x9d, 0xec, 0xb9, 0xbb, 0x9e, 0x35, 0x02, 0x8a, 0x63, 0x15, 0xfb, 0xe5, 0xdc, 0x25, 0xeb, 0xc6, 0xe7, 0x71, 0xeb, 0xcf, 0x4e, 0xc3, 0x30, 0xf8, 0xc9, 0x77, 0xc8, 0xb2, 0x74, 0x68, 0x37, 0xa9, 0x13, 0x30, 0x86, 0x20, 0x0c, 0xb6, 0x30, 0x96, 0x78, 0x25, 0xb5, 0xc0, 0x49, 0x1e, 0xda, 0xa2, 0x4b, 0xb2, 0xbb, 0xae, 0x77, 0x95, 0x1f, 0x97, 0x45, 0x08, 0x24, 0x1c, 0xf7, 0xfc, 0x36, 0xee, 0x4a, 0xbf, 0xc0, 0x60, 0x16, 0x13, 0x1b, 0x25, 0xe8, 0x7f, 0x97, 0x46, 0x70, 0xf6, 0x75, 0xd8, 0x6c, 0xbc, 0xf6, 0xe1, 0x7e, 0xe5, 0xb3, 0x83, 0x69, 0xa4, 0xd3, 0x4a, 0xe5, 0xef, 0x19, 0x1c, 0x71, 0xc3, 0xd2, 0x09, 0x12, 0xb0, 0xed, 0xe8, 0x0f, 0xb9, 0x38, 0x1e, 0x23, 0x8c, 0xce, 0x68, 0x62, 0x7c, 0x42, 0xce, 0xec, 0xd4, 0x38, 0x05, 0x9f, 0x1c, 0x2c, 0xb1, 0x7c, 0x3e, 0xfb, 0xc4, 0x00, 0xc8, 0xca, 0xa9, 0xbc, 0xbd, 0xee, 0xc6, 0xe4, 0xec, 0xff, 0x82, 0xb1, 0x89, 0xe6, 0x5b, 0xab, 0x57, 0x9e, 0x19, 0x51, 0x90, 0x21, 0x76, 0xcb, 0x57, 0xa9, 0x38, 0x26, 0x38, 0x55, 0xa8, 0x63, 0x8c, 0xa3, 0x54, 0x32, 0x1f, 0xa0, 0x23, 0x0e, 0x58, 0x32, 0x84, 0xc6, 0x54, 0xf5, 0x7b, 0x70, 0xd6, 0xbc, 0xc3, 0x63, 0x9b, 0x43, 0x49, 0x44, 0x9f, 0x26, 0x90, 0x9c, 0x6a, 0x93, 0x99, 0x20, 0xc2, 0x60, 0x51, 0x8a, 0x0d, 0x0c, 0x29, 0xe1, 0x37, 0x6d, 0xab, 0x77, 0x8d, 0xd3, 0x9d, 0xac, 0xc9, 0xa2, 0xc0, 0x41, 0x9d, 0x07, 0xaf, 0xda, 0x84, 0x5d, 0xc4, 0x18, 0x43, 0x10, 0xce, 0x48, 0xb7, 0xf7, 0x6c, 0x77, 0x5d, 0x2c, 0xd3, 0x88, 0x72, 0xf1, 0xe3, 0x10, 0x80, 0xbc, 0x5d, 0xf5, 0x02, 0xc9, 0x0e, 0xfb, 0xfb, 0xf8, 0xfb, 0x83, 0xe1, 0xa6, 0x4a, 0xb5, 0xae, 0xb7, 0x4e, 0xe3, 0xbe, 0xe9, 0xd4, 0xf4, 0xd3, 0x0c, 0x41, 0x80, 0x99, 0xce, 0x55, 0x3c, 0x4f, 0x35, 0x41, 0x7e, 0x4c, 0x1d, 0x97, 0x9c, 0x48, 0xde, 0xb5, 0xe5, 0x23, 0x34, 0xb2, 0x7c, 0xfa, 0xe1, 0x29, 0x75, 0xb6, 0x3b, 0x34, 0x51, 0x0f, 0xe9, 0xc9, 0x55, 0xe3, 0x1d, 0xb5, 0xf4, 0x1f, 0xed, 0xf6, 0xf0, 0x2b, 0xa2, 0x03, 0x95, 0x6e, 0xe9, 0xc6, 0xbe, 0x1a, 0x81, 0x39, 0x33, 0x74, 0xd8, 0xf2, 0x72, 0xc1, 0x36, 0x4b, 0x1d, 0x3c, 0x09, 0xd2, 0x43, 0x0c, 0x88, 0x5b, 0x95, 0xca, 0xa0, 0x20, 0x0f, 0x52, 0x8d, 0x98, 0x6a, 0x87, 0xe7, 0x87, 0x6d, 0xed, 0x95, 0x14, 0xab, 0xa2, 0xf1, 0x9b, 0x45, 0xe7, 0x78, 0x4f, 0x8b, 0x27, 0x1d, 0xa9, 0x17, 0x42, 0x30, 0x85, 0x77, 0x2e, 0xd6, 0x02, 0x7e, 0x95, 0xda, 0xcf, 0x42, 0xbd, 0xec, 0x96, 0x25, 0xdb, 0xc8, 0x9b, 0x2a, 0x7c, 0xe4, 0x00, 0x03, 0x70, 0xf4, 0x93, 0x1d, 0x8b, 0x45, 0x19, 0x5b, 0xf5, 0xbc, 0x6a, 0x1f, 0xaf, 0xe1, 0x8d, 0x4e, 0x6d, 0x0e, 0xef, 0x78, 0x34, 0xf4, 0x24, 0xcb, 0x9b, 0x05, 0xf0, 0xcc, 0x9e, 0x5e, 0x53, 0x8a, 0xba, 0xc4, 0xf7, 0xbf, 0xf5, 0x13, 0xe0, 0x00, 0x51, 0xea, 0x22, 0xa4, 0xec, 0x24, 0x83, 0x88, 0x74, 0xc7, 0x39, 0xe0, 0xb2, 0xa6, 0x13, 0xc8, 0xdb, 0xad, 0xe6, 0x09, 0x01, 0x1b, 0x0a, 0x79, 0xb1, 0xc3, 0xbc, 0x8c, 0x45, 0xd7, 0x8a, 0x66, 0x04, 0x90, 0xb3, 0x7b, 0x75, 0x24, 0xbe, 0xa4, 0x61, 0xdc, 0x0a, 0x46, 0xd9, 0x28, 0x47, 0x26, 0x0e, 0xad, 0xb8, 0xf9, 0xae, 0xf9, 0x16, 0xc2, 0x88, 0x9c, 0x8d, 0xfb, 0xec, 0xee, 0x16, 0xcd, 0x1d, 0xe5, 0x9d, 0x9d, 0x48, 0xaa, 0xd8, 0x88, 0x2c, 0x10, 0x62, 0x61, 0x57, 0x79, 0xe3, 0x31, 0x8a, 0x1f, 0x2b, 0x9f, 0xa8, 0x31, 0x9c, 0xeb, 0x36, 0x2c, 0xb7, 0x48, 0x50, 0x73, 0xc0, 0x90, 0xc9, 0x2c, 0xd7, 0xbe, 0x90, 0xa0, 0x57, 0xde, 0x6f, 0x54, 0xc3, 0x88, 0xe3, 0x87, 0x22, 0xf5, 0x16, 0x1a, 0x30, 0x42, 0x3c, 0xd1, 0x19, 0xbd, 0xb1, 0xaf, 0x7c, 0x63, 0xfc, 0xdf, 0x7a, 0x4b, 0xe6, 0x54, 0x22, 0x77, 0x4a, 0x1e, 0x3b, 0x09, 0x8e, 0x13, 0xb0, 0x1f, 0x16, 0xb9, 0xab, 0x27, 0x27, 0x4f, 0xa3, 0x6a, 0xe0, 0xb9, 0x5f, 0x5d, 0x3d, 0x07, 0x30, 0x0f, 0xc6, 0xb7, 0xe8, 0x62, 0xdd, 0x02, 0x43, 0x9c, 0x99, 0xc8, 0xc0, 0xff, 0xb0, 0xe5, 0x77, 0xe2, 0x81, 0xd4, 0x1e, 0xcc, 0xe6, 0x54, 0x83, 0xbb, 0x60, 0xfc, 0xa0, 0xc2, 0x51, 0x66, 0xa7, 0xf6, 0x43, 0x72, 0x6b, 0x13, 0xd1, 0x39, 0xb7, 0xf5, 0x0e, 0x68, 0x50, 0xa1, 0xe8, 0x44, 0xb3, 0x76, 0x45, 0xe6, 0x46, 0x13, 0xda, 0xd8, 0xd0, 0x27, 0x7e, 0x2d, 0xaf, 0xec, 0x61, 0xe0, 0xe3, 0xeb, 0x0b, 0xcf, 0x59, 0x77, 0x18, 0x65, 0xd2, 0x4d, 0x9b, 0x70, 0xb0, 0x26, 0xb7, 0x3c, 0xfd, 0x22, 0xb9, 0xb6, 0xc9, 0x5c, 0xe3, 0xfd, 0xae, 0xf8, 0xbe, 0x70, 0x7b, 0xdc, 0x24, 0x7e, 0x92, 0xf7, 0x33, 0xbd, 0xd9, 0x7c, 0xf4, 0x26, 0x12, 0xd3, 0x0f, 0xc3, 0x65, 0x60, 0x0a, 0x07, 0xa8, 0x39, 0xf7, 0x0e, 0x23, 0x68, 0xca, 0x73, 0x0e, 0xf3, 0xb3, 0x20, 0x3c, 0x63, 0xf3, 0x60, 0x91, 0xae, 0x16, 0xdc, 0x1e, 0x92, 0x8d, 0xe6, 0xff, 0x7f, 0x4b, 0xe6, 0xa6, 0xfa, 0x75, 0x50, 0x7b, 0x05, 0x4e, 0xc0, 0x76, 0xe8, 0x72, 0x75, 0x58, 0xd4, 0xf3, 0x58, 0x02, 0xa9, 0x1b, 0xc8, 0xb3, 0x33, 0x49, 0x79, 0xb3, 0x1d, 0x22, 0x49, 0x28, 0x9e, 0x84, 0x15, 0xb3, 0x82, 0x09, 0x67, 0x30, 0xd4, 0x9f, 0x70, 0x9c, 0x8f, 0x86, 0xad, 0xdc, 0x40, 0x1f, 0x29, 0x7b, 0x3c, 0x2f, 0x58, 0xfd, 0xc2, 0xfa, 0xfe, 0x32, 0x28, 0xfb, 0x67, 0x01, 0x21, 0x5c, 0x4b, 0x8f, 0x19, 0xcd, 0xbc, 0xfe, 0x74, 0xd2, 0xb1, 0x36, 0x56, 0x5e, 0x9f, 0xd0, 0x1b, 0x36, 0xc7, 0xaf, 0xc3, 0xa0, 0x88, 0xf1, 0x68, 0xed, 0x22, 0xe5, 0x88, 0x78, 0x88, 0x8f, 0x72, 0xfd, 0x90, 0x44, 0xb0, 0xd6, 0x77, 0xab, 0x98, 0x55, 0xcb, 0xe8, 0x6a, 0xb5, 0x66, 0x28, 0x18, 0xf1, 0xaf, 0xde, 0x24, 0x82, 0xe1, 0x5a, 0x0a, 0x20, 0x36, 0x1e, 0x07, 0xa9, 0x79, 0x36, 0x48, 0xab, 0xee, 0xbe, 0x99, 0x7f, 0xc6, 0xdc, 0xa6, 0x83, 0x60, 0x9b, 0x75, 0x4b, 0xfb, 0x90, 0x8d, 0x04, 0x11, 0x7e, 0xa8, 0x94, 0x43, 0x2a, 0xec, 0x1b, 0x9c, 0xa9, 0x0b, 0x7a, 0x43, 0x8f, 0x1e, 0xb1, 0x7b, 0x67, 0x72, 0xd5, 0x48, 0x93, 0xdc, 0xe0, 0x49, 0xca, 0x39, 0xe0, 0x2d, 0xaa, 0x44, 0x67, 0xd1, 0x28, 0x49, 0x62, 0x8b, 0x40, 0x41, 0x72, 0x49, 0xce, 0x59, 0x32, 0x44, 0x69, 0x22, 0xde, 0xd7, 0xe7, 0x9c, 0xab, 0x66, 0xb3, 0x71, 0xe2, 0xc1, 0xee, 0x43, 0x0f, 0x3d, 0x2a, 0xe6, 0xae, 0xbc, 0x37, 0x64, 0x5a, 0xf3, 0x99, 0x5d, 0xab, 0x3a, 0x2c, 0xd4, 0x6d, 0x2e, 0xb8, 0x5e, 0xd8, 0x94, 0x86, 0x64, 0xad, 0x82, 0xb0, 0xe5, 0x76, 0xf2, 0xbc, 0x78, 0x45, 0xb1, 0x63, 0x0e, 0x25, 0x1c, 0xd8, 0xd3, 0x14, 0xc6, 0x18, 0x07, 0x7e, 0x0b, 0xc7, 0x06, 0x76, 0xbb, 0x89, 0x44, 0xeb, 0x84, 0x1c, 0xf8, 0x9c, 0xfe, 0x9e, 0x0f, 0xac, 0x4f, 0xd8, 0xe6, 0xbd, 0x29, 0x90, 0xeb, 0xe9, 0x54, 0xb8, 0xb6, 0x15, 0x9a, 0x44, 0x0d, 0x52, 0xda, 0xc9, 0x67, 0xd3, 0x83, 0xd7, 0x52, 0x3f, 0xbd, 0x2a, 0x6c, 0x55, 0x6c, 0x08, 0x63, 0xb4, 0x61, 0xac, 0xe8, 0x34, 0x4e, 0x06, 0xa1, 0xb8, 0x89, 0xb5, 0x13, 0xe4, 0x93, 0xad, 0xc6, 0xa8, 0xf5, 0x31, 0x81, 0xe8, 0x30, 0x0d, 0x06, 0x09, 0x2b, 0x06, 0x01, 0x04, 0x01, 0x82, 0x37, 0x11, 0x02, 0x31, 0x00, 0x30, 0x13, 0x06, 0x09, 0x2a, 0x86, 0x48, 0x86, 0xf7, 0x0d, 0x01, 0x09, 0x15, 0x31, 0x06, 0x04, 0x04, 0x01, 0x00, 0x00, 0x00, 0x30, 0x57, 0x06, 0x09, 0x2a, 0x86, 0x48, 0x86, 0xf7, 0x0d, 0x01, 0x09, 0x14, 0x31, 0x4a, 0x1e, 0x48, 0x00, 0x65, 0x00, 0x35, 0x00, 0x62, 0x00, 0x61, 0x00, 0x34, 0x00, 0x35, 0x00, 0x63, 0x00, 0x36, 0x00, 0x2d, 0x00, 0x33, 0x00, 0x61, 0x00, 0x31, 0x00, 0x61, 0x00, 0x2d, 0x00, 0x34, 0x00, 0x39, 0x00, 0x62, 0x00, 0x35, 0x00, 0x2d, 0x00, 0x62, 0x00, 0x33, 0x00, 0x32, 0x00, 0x35, 0x00, 0x2d, 0x00, 0x35, 0x00, 0x36, 0x00, 0x37, 0x00, 0x65, 0x00, 0x39, 0x00, 0x61, 0x00, 0x36, 0x00, 0x37, 0x00, 0x62, 0x00, 0x30, 0x00, 0x65, 0x00, 0x39, 0x30, 0x69, 0x06, 0x09, 0x2b, 0x06, 0x01, 0x04, 0x01, 0x82, 0x37, 0x11, 0x01, 0x31, 0x5c, 0x1e, 0x5a, 0x00, 0x4d, 0x00, 0x69, 0x00, 0x63, 0x00, 0x72, 0x00, 0x6f, 0x00, 0x73, 0x00, 0x6f, 0x00, 0x66, 0x00, 0x74, 0x00, 0x20, 0x00, 0x52, 0x00, 0x53, 0x00, 0x41, 0x00, 0x20, 0x00, 0x53, 0x00, 0x43, 0x00, 0x68, 0x00, 0x61, 0x00, 0x6e, 0x00, 0x6e, 0x00, 0x65, 0x00, 0x6c, 0x00, 0x20, 0x00, 0x43, 0x00, 0x72, 0x00, 0x79, 0x00, 0x70, 0x00, 0x74, 0x00, 0x6f, 0x00, 0x67, 0x00, 0x72, 0x00, 0x61, 0x00, 0x70, 0x00, 0x68, 0x00, 0x69, 0x00, 0x63, 0x00, 0x20, 0x00, 0x50, 0x00, 0x72, 0x00, 0x6f, 0x00, 0x76, 0x00, 0x69, 0x00, 0x64, 0x00, 0x65, 0x00, 0x72, 0x30, 0x82, 0x03, 0xff, 0x06, 0x09, 0x2a, 0x86, 0x48, 0x86, 0xf7, 0x0d, 0x01, 0x07, 0x06, 0xa0, 0x82, 0x03, 0xf0, 0x30, 0x82, 0x03, 0xec, 0x02, 0x01, 0x00, 0x30, 0x82, 0x03, 0xe5, 0x06, 0x09, 0x2a, 0x86, 0x48, 0x86, 0xf7, 0x0d, 0x01, 0x07, 0x01, 0x30, 0x1c, 0x06, 0x0a, 0x2a, 0x86, 0x48, 0x86, 0xf7, 0x0d, 0x01, 0x0c, 0x01, 0x06, 0x30, 0x0e, 0x04, 0x08, 0x61, 0xa4, 0xc1, 0x1b, 0x25, 0xf3, 0x59, 0xa7, 0x02, 0x02, 0x07, 0xd0, 0x80, 0x82, 0x03, 0xb8, 0xba, 0x27, 0x3f, 0x33, 0x49, 0x3e, 0x7a, 0xa4, 0xc8, 0x15, 0x83, 0x12, 0x97, 0x7c, 0xc2, 0x18, 0xad, 0x15, 0x60, 0x74, 0xd8, 0xb7, 0x64, 0x79, 0x50, 0x4e, 0xa2, 0xb5, 0x4f, 0xc7, 0x8b, 0xd7, 0x67, 0x11, 0xbf, 0xa9, 0xef, 0xea, 0x4c, 0xef, 0x31, 0xb4, 0x54, 0xe7, 0xf8, 0xcb, 0xc8, 0xca, 0x17, 0x59, 0xe9, 0x15, 0xaf, 0x1b, 0xe8, 0xfe, 0xd0, 0xc5, 0x4a, 0xa9, 0xf7, 0x5b, 0x0c, 0x77, 0xea, 0xae, 0x25, 0x99, 0x5a, 0xdc, 0x2b, 0x30, 0x25, 0x8c, 0x53, 0xa3, 0x39, 0x53, 0x5b, 0xf3, 0x25, 0xe7, 0xc2, 0xe2, 0x13, 0x2e, 0x9f, 0x47, 0xea, 0xf7, 0x86, 0xad, 0x45, 0x8b, 0x75, 0x73, 0x2a, 0xef, 0xf8, 0x43, 0x45, 0xb6, 0x2d, 0xb5, 0x8d, 0xb0, 0x0e, 0xfa, 0x93, 0x5e, 0xb5, 0xe8, 0xb7, 0xaf, 0x8a, 0xfd, 0xbc, 0x7a, 0xcd, 0xc9, 0xa7, 0x5c, 0x3c, 0x35, 0xd9, 0xec, 0x39, 0x39, 0x80, 0x4a, 0xe4, 0x34, 0xe1, 0x8f, 0x17, 0xa0, 0x97, 0xa5, 0xcf, 0x7c, 0xe4, 0x2e, 0x9a, 0xc6, 0x16, 0xa5, 0x85, 0x6d, 0x1c, 0xd7, 0x44, 0xbe, 0xf3, 0xea, 0xd5, 0xfd, 0xd1, 0x35, 0x38, 0x94, 0x40, 0xa6, 0xd2, 0x0e, 0xae, 0xd7, 0x5f, 0xef, 0xcb, 0x9b, 0xf6, 0x10, 0x8c, 0xe1, 0xd5, 0x9d, 0xf1, 0xf3, 0x75, 0x4d, 0x3f, 0x32, 0x15, 0xc7, 0xcf, 0xe8, 0x07, 0xfa, 0xcd, 0x48, 0x56, 0x7e, 0xf9, 0xd2, 0xb2, 0x60, 0x6f, 0x8d, 0x70, 0x6e, 0xc0, 0xb4, 0x87, 0xb8, 0x43, 0xdc, 0x35, 0x22, 0x2f, 0xc0, 0x61, 0xbd, 0x6b, 0x9c, 0xfe, 0xe1, 0xeb, 0xaa, 0x6a, 0xbc, 0x30, 0x88, 0x5a, 0x6d, 0xfb, 0xd3, 0x87, 0x22, 0xca, 0xbd, 0x3f, 0x1a, 0xf7, 0x0e, 0xf4, 0xf9, 0x6e, 0xd0, 0xf7, 0x01, 0xea, 0x78, 0x2d, 0x7c, 0x50, 0x26, 0xd9, 0xca, 0xfa, 0x7c, 0xe1, 0x16, 0x22, 0xb8, 0xb7, 0x9c, 0x94, 0x18, 0xb8, 0xd8, 0x4e, 0xac, 0xbd, 0xe8, 0x80, 0xe7, 0x4f, 0x9a, 0x9b, 0xb7, 0x06, 0x96, 0x32, 0xd6, 0xde, 0xd5, 0xe6, 0x8f, 0x45, 0x5d, 0x7e, 0xc2, 0xe6, 0xff, 0x71, 0x9b, 0x66, 0x67, 0x89, 0xbf, 0x85, 0x11, 0xf1, 0xeb, 0x13, 0x42, 0xa9, 0x66, 0x09, 0x43, 0x01, 0x66, 0x9b, 0x94, 0xb5, 0x16, 0x64, 0xcd, 0xf1, 0x32, 0x3f, 0x46, 0x6d, 0x39, 0x29, 0x9c, 0xd4, 0xcf, 0xff, 0x1b, 0x1c, 0xe9, 0x5a, 0xe0, 0xd2, 0xca, 0x26, 0x73, 0xa0, 0x9e, 0xbe, 0x76, 0xdf, 0x12, 0x20, 0x4e, 0x65, 0xcc, 0xd3, 0x22, 0x28, 0xe4, 0x20, 0x87, 0xab, 0xf3, 0xfb, 0x1e, 0x3d, 0x14, 0x1f, 0x84, 0x7d, 0x3f, 0x5e, 0xf6, 0xce, 0x95, 0xfe, 0xe1, 0xe4, 0x55, 0xb6, 0xa7, 0xf8, 0xa4, 0x28, 0x38, 0x7a, 0x78, 0xd3, 0xd6, 0x51, 0xfc, 0x62, 0x5b, 0x49, 0x53, 0xec, 0x53, 0x06, 0x9f, 0xa1, 0x71, 0x45, 0x60, 0x0f, 0x2a, 0x13, 0x6f, 0xc4, 0x64, 0x58, 0x43, 0x6f, 0x56, 0x0c, 0xb5, 0x73, 0x4d, 0x6f, 0x45, 0x9a, 0x3a, 0x19, 0xd7, 0x5c, 0xa1, 0xf7, 0x8e, 0x94, 0x02, 0x14, 0x4e, 0x7d, 0x01, 0x70, 0x34, 0x98, 0xeb, 0x1d, 0x30, 0x47, 0x58, 0x81, 0xfb, 0x20, 0xb2, 0x3c, 0xaf, 0x5e, 0x50, 0x41, 0xca, 0x20, 0xf1, 0xbd, 0x6d, 0x29, 0xd6, 0x92, 0x33, 0x27, 0xc0, 0x34, 0x6b, 0x5a, 0x6c, 0x55, 0xe3, 0x4f, 0x22, 0x14, 0x6b, 0x37, 0x53, 0xca, 0xa8, 0x6c, 0xf7, 0xf5, 0xaa, 0xdb, 0x42, 0xa7, 0x56, 0x81, 0x8b, 0x72, 0xc5, 0xf9, 0x07, 0x70, 0x97, 0x18, 0x04, 0xea, 0x6b, 0x33, 0x5a, 0xdf, 0xc7, 0xfa, 0xf8, 0x01, 0x0f, 0x9b, 0xfc, 0xb6, 0x06, 0xc1, 0x95, 0xb8, 0x32, 0xa1, 0xd0, 0x6f, 0xd8, 0xd5, 0xe8, 0xba, 0x95, 0xf5, 0x6d, 0x2c, 0x5a, 0x20, 0x0a, 0xe2, 0xfe, 0x4e, 0xa7, 0x5c, 0xf2, 0x6d, 0xc5, 0x09, 0x0d, 0xe7, 0x5f, 0x90, 0xa9, 0x54, 0x7c, 0x91, 0x60, 0x50, 0x45, 0xf9, 0x48, 0x7b, 0x90, 0xf8, 0xba, 0x99, 0x86, 0xbe, 0x05, 0xda, 0x2d, 0xa9, 0xae, 0xfd, 0xba, 0x71, 0x5d, 0xf6, 0xa1, 0x1f, 0x01, 0x70, 0xd0, 0x3e, 0xfd, 0x11, 0x8d, 0x82, 0xfa, 0x23, 0x5e, 0xf8, 0x3f, 0x57, 0x44, 0x0a, 0xbf, 0xd4, 0x59, 0x4b, 0xe8, 0x61, 0x82, 0x96, 0x59, 0xe7, 0xd8, 0xae, 0x53, 0x9b, 0x57, 0x69, 0x70, 0xf8, 0xde, 0xa0, 0x55, 0x8b, 0xc5, 0x48, 0x21, 0x60, 0x35, 0xdc, 0xb6, 0x1b, 0xeb, 0x42, 0x89, 0x25, 0x8f, 0xa6, 0xab, 0xe0, 0x97, 0x1b, 0x37, 0x3e, 0x34, 0xc5, 0xc5, 0x86, 0xf4, 0x74, 0xa1, 0x53, 0x67, 0xef, 0x5b, 0x41, 0x11, 0xb8, 0xfd, 0xed, 0xf6, 0x59, 0x5c, 0x7e, 0xf3, 0xbd, 0x43, 0x76, 0x9a, 0x1d, 0x62, 0x01, 0xda, 0x9c, 0x6c, 0xb9, 0x96, 0xa9, 0x0e, 0xcb, 0xf0, 0xe1, 0x65, 0x23, 0x5b, 0x31, 0x9e, 0x27, 0x16, 0x79, 0x1b, 0x78, 0xeb, 0x09, 0x47, 0xdb, 0x0e, 0xba, 0x9f, 0x6b, 0x5d, 0x0f, 0xf5, 0x1b, 0xbb, 0x84, 0x2b, 0x46, 0x9f, 0x6b, 0xcb, 0x65, 0x2d, 0xeb, 0x61, 0xa6, 0xe9, 0x55, 0xb7, 0x59, 0xf0, 0x5d, 0x02, 0xc5, 0x56, 0xbf, 0x5b, 0x6e, 0xa7, 0x88, 0x4f, 0x9f, 0x3b, 0x9d, 0x64, 0x58, 0x79, 0x99, 0x04, 0x43, 0xba, 0xe4, 0xc3, 0x63, 0x22, 0x77, 0xad, 0xc8, 0xef, 0x1a, 0x4e, 0xc4, 0x0b, 0xaa, 0xd1, 0x76, 0xaf, 0x63, 0x48, 0x42, 0xf6, 0x68, 0x5f, 0x34, 0xd7, 0xbf, 0x41, 0x58, 0xce, 0x50, 0xb9, 0x9e, 0x60, 0x5d, 0x4d, 0xb3, 0x42, 0xa0, 0x31, 0xbd, 0xf6, 0x95, 0x7e, 0x8d, 0xd4, 0x10, 0xb8, 0x48, 0xee, 0x7e, 0x53, 0x7d, 0x18, 0xc8, 0x20, 0x77, 0xfd, 0xa1, 0xce, 0x3c, 0x99, 0xd8, 0xcc, 0x2e, 0x58, 0xc8, 0xa4, 0x47, 0x4c, 0x2b, 0xab, 0xb5, 0x80, 0x54, 0x57, 0x95, 0xd4, 0x96, 0x7d, 0xd1, 0x0c, 0xe0, 0x14, 0x97, 0x98, 0xcb, 0x48, 0x3f, 0x52, 0x08, 0x9c, 0xc6, 0x0e, 0xa9, 0xa5, 0xa5, 0x3d, 0x4f, 0xa8, 0xb4, 0xf6, 0x7b, 0x6c, 0xf3, 0x69, 0x9c, 0x7d, 0x28, 0xf8, 0xf8, 0x99, 0x6a, 0xad, 0x35, 0xdb, 0x14, 0xe4, 0x3c, 0xfc, 0x92, 0xb0, 0xb6, 0x68, 0x7c, 0xa1, 0xe9, 0x55, 0x41, 0x91, 0x05, 0xf2, 0xb4, 0xd7, 0x7c, 0x33, 0xc4, 0x72, 0xfb, 0xde, 0xd7, 0x2d, 0x4f, 0xfb, 0xa1, 0x46, 0xe6, 0x30, 0xd8, 0x73, 0xf3, 0x19, 0x9e, 0x0b, 0x82, 0xef, 0x62, 0xac, 0xd5, 0x1e, 0x7d, 0x25, 0xb7, 0xd9, 0xd8, 0x04, 0xe3, 0x3d, 0x90, 0x50, 0x3b, 0x91, 0xfe, 0x34, 0x89, 0x04, 0x9e, 0x5b, 0xac, 0x26, 0x1e, 0xa0, 0xb8, 0x02, 0xf0, 0x91, 0x06, 0xe2, 0xc3, 0xf9, 0x49, 0x7d, 0xe8, 0xe5, 0xd4, 0x9e, 0xad, 0x03, 0x78, 0xf2, 0xba, 0x06, 0xcd, 0x70, 0xf9, 0xa9, 0xf1, 0xba, 0x62, 0xcc, 0xfb, 0x7a, 0xaf, 0xde, 0xbf, 0xbf, 0x92, 0x38, 0x76, 0x16, 0x3c, 0x5d, 0xbe, 0xc6, 0x6a, 0x55, 0xa4, 0x8b, 0x71, 0x00, 0xd4, 0x9e, 0xac, 0x0c, 0x16, 0x5a, 0x0f, 0x1d, 0x5d, 0xa0, 0x18, 0x9a, 0x9c, 0x33, 0x7d, 0xf3, 0x61, 0xb4, 0x4d, 0x4c, 0x30, 0x37, 0x30, 0x1f, 0x30, 0x07, 0x06, 0x05, 0x2b, 0x0e, 0x03, 0x02, 0x1a, 0x04, 0x14, 0xc5, 0xf9, 0x1d, 0xbf, 0x65, 0xa1, 0x0e, 0xe0, 0x50, 0x17, 0x1c, 0x78, 0x47, 0x1a, 0x91, 0xd4, 0xe9, 0x58, 0x28, 0x92, 0x04, 0x14, 0x97, 0x1e, 0xb6, 0x49, 0xb8, 0x3e, 0x03, 0x6d, 0xef, 0xbf, 0xe4, 0x41, 0x34, 0x44, 0x24, 0xa9, 0xc7, 0xcd, 0x35, 0xc9, }; #endregion //EmulatorCertificate } } ================================================ FILE: Zelig/Zelig/Test/RunTime/NETMF/System/Http/HttpStatusCodeTests.cs ================================================ //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // Copyright (c) Microsoft Corporation. All rights reserved. //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// using Microsoft.Llilum.Lwip; using System; using System.IO; using System.Net; namespace Microsoft.Zelig.Test { public class HttpStatusCodeTests : TestBase, ITestInterface { [SetUp] public InitializeResult Initialize() { Log.Comment("Adding set up for the tests."); try { NetworkInterface[] nis = NetworkInterface.GetAllNetworkInterfaces(); } catch { return InitializeResult.Skip; } return InitializeResult.ReadyToGo; } [TearDown] public void CleanUp() { Log.Comment("Cleaning up after the tests."); // TODO: Add your clean up steps here. } public override TestResult Run( string[] args ) { return TestResult.Pass; } //--// //--// //--// #region Test [TestMethod] public TestResult ValidDefaultTestHTTPStatusCodeHTTP1_1() { TestResult result = TestResult.Pass; HttpWebRequest wr = (HttpWebRequest)WebRequest.Create("http://127.0.0.1:" + HttpServer.s_CurrentPort.ToString() + "/"); wr.UserAgent = ".Net Micro Framwork Device/4.0"; Log.Comment("Initial version: " + wr.ProtocolVersion); //Default version is 1.1 Log.Comment("Set Version 1.1"); wr.ProtocolVersion = new Version(1, 1); HttpServer server = new HttpServer("http", ref result) { RequestUri = wr.RequestUri, RequestHeaders = wr.Headers, ResponseString = "ValidDefaultTestHTTPStatusCodeHTTP1_1" }; try { // Setup server server.StartServer(); HttpWebResponse response = (HttpWebResponse)wr.GetResponse(); Log.Comment("Expect StatusCode - OK"); if (HttpStatusCode.OK != response.StatusCode) { Log.Exception("Expect HttpStatusCode = OK but get " + response.StatusCode); result = TestResult.Fail; } Log.Comment("Receive " + response.StatusDescription); response.Close(); } catch (Exception ex) { Log.Exception("[Client] Unexpected Exception", ex); result = TestResult.Fail; } finally { //Stop server server.StopServer(); } return result; } [TestMethod] public TestResult DefaultTestHTTPStatusCodeHTTP1_1_Unauthorized() { TestResult result = TestResult.Pass; HttpWebRequest wr = (HttpWebRequest)WebRequest.Create("http://127.0.0.1:" + HttpServer.s_CurrentPort.ToString() + "/webpages/Unauth.html"); //expect 401 - Unauthorized wr.UserAgent = ".Net Micro Framwork Device/4.0"; Log.Comment("Initial version: " + wr.ProtocolVersion); //Default version is 1.1 Log.Comment("Set Version 1.1"); wr.ProtocolVersion = new Version(1, 1); HttpServer server = new HttpServer("http", ref result) { RequestUri = wr.RequestUri, RequestHeaders = wr.Headers, ResponseString = "DefaultTestHTTPStatusCodeHTTP1_1_Unauthorized" }; try { // Setup server server.StartServer(); HttpWebResponse response = (HttpWebResponse)wr.GetResponse(); Log.Comment("Expect StatusCode - Unauthorized "); if (HttpStatusCode.Unauthorized != response.StatusCode) { Log.Exception("Expect HttpStatusCode = Unauthorized but get " + response.StatusCode); result = TestResult.Fail; } response.Close(); } catch (Exception ex) { Log.Exception("[Client] Unexpected Exception", ex); result = TestResult.Fail; } finally { //Stop server server.StopServer(); } return result; } [TestMethod] public TestResult DefaultTestHTTPStatusCodeHTTP1_1_NotFound() { TestResult result = TestResult.Pass; HttpWebRequest wr = (HttpWebRequest)WebRequest.Create("http://127.0.0.1:" + HttpServer.s_CurrentPort.ToString() + "/webpages/NotFound.html"); //expect 404 - NotFound wr.UserAgent = ".Net Micro Framwork Device/4.0"; Log.Comment("Initial version: " + wr.ProtocolVersion); //Default version is 1.1 Log.Comment("Set Version 1.1"); wr.ProtocolVersion = new Version(1, 1); HttpServer server = new HttpServer("http", ref result) { RequestUri = wr.RequestUri, RequestHeaders = wr.Headers, ResponseString = "DefaultTestHTTPStatusCodeHTTP1_1_NotFound" }; try { // Setup server server.StartServer(); HttpWebResponse response = (HttpWebResponse)wr.GetResponse(); Log.Comment("Expect StatusCode - NotFound "); if (HttpStatusCode.NotFound != response.StatusCode) { Log.Exception("Expect HttpStatusCode = NotFound but get " + response.StatusCode); result = TestResult.Fail; } Log.Comment("Receive " + response.StatusDescription); response.Close(); } catch (Exception ex) { Log.Exception("[Client] Unexpected Exception", ex); result = TestResult.Fail; } finally { //Stop server server.StopServer(); } return result; } //Bug 68085... [TestMethod] public TestResult DefaultTestHTTPStatusCodeHTTP1_1_NotExistUriPath() { TestResult result = TestResult.Pass; HttpWebRequest wr = (HttpWebRequest)WebRequest.Create("http://127.0.0.1:" + HttpServer.s_CurrentPort.ToString() + "/webpages/NotExistUriPath.html"); wr.UserAgent = ".Net Micro Framwork Device/4.0"; Log.Comment("Initial version: " + wr.ProtocolVersion); //Default version is 1.1 Log.Comment("Set Version 1.1"); wr.ProtocolVersion = new Version(1, 1); HttpServer server = new HttpServer("http", ref result) { RequestUri = wr.RequestUri, RequestHeaders = wr.Headers, ResponseString = "DefaultTestHTTPStatusCodeHTTP1_1_NotExistUriPath" }; try { // Setup server server.StartServer(); HttpWebResponse response = (HttpWebResponse)wr.GetResponse(); Log.Comment("Expect StatusCode - NotFound "); if (HttpStatusCode.NotFound != response.StatusCode) { if ("0" == response.StatusCode.ToString()) Log.Exception("Known Issue::Bug 68085 - HttpStatusCode = 0 was returned"); else Log.Exception("Expect HttpStatusCode = NotFound but get " + response.StatusCode); result = TestResult.Fail; } response.Close(); } catch (Exception ex) { Log.Exception("[Client] Unexpected Exception", ex); result = TestResult.Fail; } finally { //Stop server server.StopServer(); } return result; } [TestMethod] public TestResult TestHTTPStatusCodeHTTP1_1_SetChunked() { TestResult result = TestResult.Pass; HttpWebRequest wr = (HttpWebRequest)WebRequest.Create("http://127.0.0.1:" + HttpServer.s_CurrentPort.ToString() + "/"); //expect 200 - OK wr.UserAgent = ".Net Micro Framwork Device/4.0"; Log.Comment("Initial version: " + wr.ProtocolVersion); //Default version is 1.1 Log.Comment("Set Version 1.1"); wr.ProtocolVersion = new Version(1, 1); wr.SendChunked = true; try { wr.Headers.Set(HttpKnownHeaderNames.TransferEncoding, "chunked"); result = TestResult.Fail; } catch (ArgumentException ex) { Log.Exception("Expected ArgumentException: ", ex); } return result; } [TestMethod] public TestResult TestHTTPStatusCodeHTTP1_1_SendChunked_WithTransferEncoding() { TestResult result = TestResult.Pass; HttpWebRequest wr = (HttpWebRequest)WebRequest.Create("http://127.0.0.1:" + HttpServer.s_CurrentPort.ToString() + "/"); wr.UserAgent = ".Net Micro Framwork Device/4.0"; Log.Comment("Initial version: " + wr.ProtocolVersion); //Default version is 1.1 Log.Comment("Set Version 1.1"); wr.ProtocolVersion = new Version(1, 1); wr.SendChunked = true; wr.TransferEncoding = "Quoted-printable"; string requestString = "ContentLength: " + wr.ContentLength + " ContentType:" + wr.ContentType + " KeepAlive:" + wr.KeepAlive + " ProtocolVersion:" + wr.ProtocolVersion + " TransferEncoding:" + wr.TransferEncoding + " SendChunked:" + wr.SendChunked + " Expect:" + wr.Expect + " Timeout:" + wr.Timeout; Log.Comment(requestString); HttpServer server = new HttpServer("http", ref result) { RequestUri = wr.RequestUri, RequestHeaders = wr.Headers, ResponseString = "TestHTTPStatusCodeHTTP1_1_SendChunked_WithTransferEncoding" }; try { // Setup server server.StartServer(); HttpWebResponse response = (HttpWebResponse)wr.GetResponse(); string ResponseString = "Server response: ContentEncoding:" + response.ContentEncoding + " ContentLength: " + response.ContentLength + " ContentType:" + response.ContentType + " ProtocolVersion:" + response.ProtocolVersion + " StatusCode:" + response.StatusCode + " StatusDescription:" + response.StatusDescription; Log.Comment(ResponseString); Log.Comment("Expect StatusCode - OK"); if (HttpStatusCode.OK != response.StatusCode) { Log.Exception("Expect HttpStatusCode = OK but get " + response.StatusCode); result = TestResult.Fail; } Log.Comment("Receive " + response.StatusDescription); response.Close(); } catch (Exception ex) { Log.Exception("[Client] Unexpected Exception", ex); result = TestResult.Fail; } finally { //Stop server server.StopServer(); } return result; } [TestMethod] public TestResult TestHTTPStatusCodeHTTP1_1_Ambiguous() { TestResult result = TestResult.Pass; HttpWebRequest wr = (HttpWebRequest)WebRequest.Create("http://127.0.0.1:" + HttpServer.s_CurrentPort.ToString() + "/webpages/index.html"); //expect 300 - Ambiguous wr.UserAgent = ".Net Micro Framwork Device/4.0"; wr.Method = "GET"; Log.Comment("Initial version: " + wr.ProtocolVersion); //Default version is 1.1 Log.Comment("Set Version 1.1"); wr.ProtocolVersion = new Version(1, 1); HttpServer server = new HttpServer("http", ref result) { RequestUri = wr.RequestUri, RequestHeaders = wr.Headers, ResponseString = "TestHTTPStatusCodeHTTP1_1_Ambiguous" }; try { // Setup server server.StartServer(); HttpWebResponse response = (HttpWebResponse)wr.GetResponse(); Log.Comment("Expect StatusCode - Ambiguous"); if ((int)HttpStatusCode.Ambiguous != (int)response.StatusCode) { Log.Exception("Expect HttpStatusCode = Ambiguous but get " + response.StatusCode); result = TestResult.Fail; } Log.Comment("Receive " + response.StatusDescription); response.Close(); } catch (Exception ex) { Log.Exception("[Client] Unexpected Exception", ex); result = TestResult.Fail; } finally { //Stop server server.StopServer(); } return result; } [TestMethod] public TestResult TestHTTPStatusCodeHTTP1_1_BadGateway() { TestResult result = TestResult.Pass; HttpWebRequest wr = (HttpWebRequest)WebRequest.Create("http://127.0.0.1:" + HttpServer.s_CurrentPort.ToString() + "/webpages/Gateway.html"); //expect 502 - BadGateway wr.UserAgent = ".Net Micro Framwork Device/4.0"; wr.Method = "GET"; Log.Comment("Initial version: " + wr.ProtocolVersion); //Default version is 1.1 Log.Comment("Set Version 1.1"); wr.ProtocolVersion = new Version(1, 1); HttpServer server = new HttpServer("http", ref result) { RequestUri = wr.RequestUri, RequestHeaders = wr.Headers, ResponseString = "TestHTTPStatusCodeHTTP1_1_BadGateway" }; try { // Setup server server.StartServer(); HttpWebResponse response = (HttpWebResponse)wr.GetResponse(); Log.Comment("Expect StatusCode - BadGateway"); if ((int)HttpStatusCode.BadGateway != (int)response.StatusCode) { Log.Exception("Expect HttpStatusCode = BadGateway but get " + response.StatusCode); result = TestResult.Fail; } Log.Comment("Receive " + response.StatusDescription); response.Close(); } catch (Exception ex) { Log.Exception("[Client] Unexpected Exception", ex); result = TestResult.Fail; } finally { //Stop server server.StopServer(); } return result; } [TestMethod] public TestResult TestHTTPStatusCodeHTTP1_1_Conflict() { TestResult result = TestResult.Pass; HttpWebRequest wr = (HttpWebRequest)WebRequest.Create("http://127.0.0.1:" + HttpServer.s_CurrentPort.ToString() + "/webpages/conflict.html"); //expect 409 - Conflict wr.UserAgent = ".Net Micro Framwork Device/4.0"; wr.Method = "GET"; Log.Comment("Initial version: " + wr.ProtocolVersion); //Default version is 1.1 Log.Comment("Set Version 1.1"); wr.ProtocolVersion = new Version(1, 1); HttpServer server = new HttpServer("http", ref result) { RequestUri = wr.RequestUri, RequestHeaders = wr.Headers, ResponseString = "TestHTTPStatusCodeHTTP1_1_Conflict" }; try { // Setup server server.StartServer(); HttpWebResponse response = (HttpWebResponse)wr.GetResponse(); Log.Comment("Expect StatusCode - Conflict"); if ((int)HttpStatusCode.Conflict != (int)response.StatusCode) { Log.Exception("Expect HttpStatusCode = Conflict but get " + response.StatusCode); result = TestResult.Fail; } Log.Comment("Receive " + response.StatusDescription); response.Close(); } catch (Exception ex) { Log.Exception("[Client] Unexpected Exception", ex); result = TestResult.Fail; } finally { //Stop server server.StopServer(); } return result; } [TestMethod] public TestResult TestHTTPStatusCodeHTTP1_1_Moved() { TestResult result = TestResult.Pass; HttpWebRequest wr = (HttpWebRequest)WebRequest.Create("http://127.0.0.1:" + HttpServer.s_CurrentPort.ToString() + "/webpages/moved.html"); //expect 301 - Moved wr.UserAgent = ".Net Micro Framwork Device/4.0"; wr.Method = "GET"; Log.Comment("Initial version: " + wr.ProtocolVersion); //Default version is 1.1 Log.Comment("Set Version 1.1"); wr.ProtocolVersion = new Version(1, 1); HttpServer server = new HttpServer("http", ref result) { RequestUri = wr.RequestUri, RequestHeaders = wr.Headers, ResponseString = "TestHTTPStatusCodeHTTP1_1_Moved" }; try { // Setup server server.StartServer(); HttpWebResponse response = (HttpWebResponse)wr.GetResponse(); Log.Comment("Expect StatusCode - Moved"); if ((int)HttpStatusCode.Moved != (int)response.StatusCode) { Log.Exception("Expect HttpStatusCode = Moved but get " + response.StatusCode); result = TestResult.Fail; } Log.Comment("Receive " + response.StatusDescription); response.Close(); } catch (Exception ex) { Log.Exception("[Client] Unexpected Exception", ex); result = TestResult.Fail; } finally { //Stop server server.StopServer(); } return result; } [TestMethod] public TestResult TestHTTPStatusCodeHTTP1_1_Redirect() { TestResult result = TestResult.Pass; HttpWebRequest wr = (HttpWebRequest)WebRequest.Create("http://127.0.0.1:" + HttpServer.s_CurrentPort.ToString() + "/webpages/redirect.html"); //expect 302 - Redirect wr.UserAgent = ".Net Micro Framwork Device/4.0"; wr.Method = "GET"; Log.Comment("Initial version: " + wr.ProtocolVersion); //Default version is 1.1 Log.Comment("Set Version 1.1"); wr.ProtocolVersion = new Version(1, 1); HttpServer server = new HttpServer("http", ref result) { RequestUri = wr.RequestUri, RequestHeaders = wr.Headers, ResponseString = "TestHTTPStatusCodeHTTP1_1_Redirect" }; try { // Setup server server.StartServer(); HttpWebResponse response = (HttpWebResponse)wr.GetResponse(); Log.Comment("Expect StatusCode - Redirect"); if ((int)HttpStatusCode.Redirect != (int)response.StatusCode) { Log.Exception("Expect HttpStatusCode = Redirect but get " + response.StatusCode); result = TestResult.Fail; } Log.Comment("Receive " + response.StatusDescription); response.Close(); } catch (Exception ex) { Log.Exception("[Client] Unexpected Exception", ex); result = TestResult.Fail; } finally { //Stop server server.StopServer(); } return result; } [TestMethod] public TestResult TestHTTPStatusCodeHTTP1_1_PaymentRequired() { TestResult result = TestResult.Pass; HttpWebRequest wr = (HttpWebRequest)WebRequest.Create("http://127.0.0.1:" + HttpServer.s_CurrentPort.ToString() + "/webpages/payment.html"); //expect 402 - PaymentRequired wr.UserAgent = ".Net Micro Framwork Device/4.0"; wr.Method = "GET"; Log.Comment("Initial version: " + wr.ProtocolVersion); //Default version is 1.1 Log.Comment("Set Version 1.1"); wr.ProtocolVersion = new Version(1, 1); HttpServer server = new HttpServer("http", ref result) { RequestUri = wr.RequestUri, RequestHeaders = wr.Headers, ResponseString = "TestHTTPStatusCodeHTTP1_1_PaymentRequired" }; try { // Setup server server.StartServer(); HttpWebResponse response = (HttpWebResponse)wr.GetResponse(); Log.Comment("Expect StatusCode - PaymentRequired"); if ((int)HttpStatusCode.PaymentRequired != (int)response.StatusCode) { Log.Exception("Expect HttpStatusCode = PaymentRequired but get " + response.StatusCode); result = TestResult.Fail; } Log.Comment("Receive " + response.StatusDescription); response.Close(); } catch (Exception ex) { Log.Exception("[Client] Unexpected Exception", ex); result = TestResult.Fail; } finally { //Stop server server.StopServer(); } return result; } [TestMethod] public TestResult TestHTTPStatusCodeHTTP1_1_RequestTimeout() { TestResult result = TestResult.Pass; HttpWebRequest wr = (HttpWebRequest)WebRequest.Create("http://127.0.0.1:" + HttpServer.s_CurrentPort.ToString() + "/webpages/testTimeOut.html"); //expect 408 - RequestTimeout wr.UserAgent = ".Net Micro Framwork Device/4.0"; wr.Method = "GET"; Log.Comment("Initial version: " + wr.ProtocolVersion); //Default version is 1.1 Log.Comment("Set Version 1.1"); wr.ProtocolVersion = new Version(1, 1); HttpServer server = new HttpServer("http", ref result) { RequestUri = wr.RequestUri, RequestHeaders = wr.Headers, ResponseString = "TestHTTPStatusCodeHTTP1_1_RequestTimeout" }; try { // Setup server server.StartServer(); HttpWebResponse response = (HttpWebResponse)wr.GetResponse(); Log.Comment("Expect StatusCode - RequestTimeout"); if ((int)HttpStatusCode.RequestTimeout != (int)response.StatusCode) { Log.Exception("Expect HttpStatusCode = RequestTimeout but get " + response.StatusCode); result = TestResult.Fail; } Log.Comment("Receive " + response.StatusDescription); response.Close(); } catch (Exception ex) { Log.Exception("[Client] Unexpected Exception", ex); result = TestResult.Fail; } finally { //Stop server server.StopServer(); } return result; } [TestMethod] public TestResult TestHTTPStatusCodeHTTP1_1_RequestUriTooLong() { TestResult result = TestResult.Pass; HttpWebRequest wr = (HttpWebRequest)WebRequest.Create("http://127.0.0.1:" + HttpServer.s_CurrentPort.ToString() + "/local/webpages/mysubdir/index.html"); //expect 414 - RequestUriTooLong wr.UserAgent = ".Net Micro Framwork Device/4.0"; wr.Method = "GET"; Log.Comment("Initial version: " + wr.ProtocolVersion); //Default version is 1.1 Log.Comment("Set Version 1.1"); wr.ProtocolVersion = new Version(1, 1); HttpServer server = new HttpServer("http", ref result) { RequestUri = wr.RequestUri, RequestHeaders = wr.Headers, ResponseString = "TestHTTPStatusCodeHTTP1_1_RequestUriTooLong" }; try { // Setup server server.StartServer(); HttpWebResponse response = (HttpWebResponse)wr.GetResponse(); Log.Comment("Expect StatusCode - RequestUriTooLong"); if ((int)HttpStatusCode.RequestUriTooLong != (int)response.StatusCode) { Log.Exception("Expect HttpStatusCode = RequestUriTooLong but get " + response.StatusCode); result = TestResult.Fail; } Log.Comment("Receive " + response.StatusDescription); response.Close(); } catch (Exception ex) { Log.Exception("[Client] Unexpected Exception", ex); result = TestResult.Fail; } finally { //Stop server server.StopServer(); } return result; } [TestMethod] public TestResult TestHTTPStatusCodeHTTP1_1_ServiceUnavailable() { TestResult result = TestResult.Pass; HttpWebRequest wr = (HttpWebRequest)WebRequest.Create("http://127.0.0.1:" + HttpServer.s_CurrentPort.ToString() + "/webpages/service.html"); //expect 503 - ServiceUnavailable wr.UserAgent = ".Net Micro Framwork Device/4.0"; wr.Method = "GET"; Log.Comment("Initial version: " + wr.ProtocolVersion); //Default version is 1.1 Log.Comment("Set Version 1.1"); wr.ProtocolVersion = new Version(1, 1); HttpServer server = new HttpServer("http", ref result) { RequestUri = wr.RequestUri, RequestHeaders = wr.Headers, ResponseString = "TestHTTPStatusCodeHTTP1_1_ServiceUnavailable" }; try { // Setup server server.StartServer(); HttpWebResponse response = (HttpWebResponse)wr.GetResponse(); Log.Comment("Expect StatusCode - ServiceUnavailable"); if ((int)HttpStatusCode.ServiceUnavailable != (int)response.StatusCode) { Log.Exception("Expect HttpStatusCode = ServiceUnavailable but get " + response.StatusCode); result = TestResult.Fail; } Log.Comment("Receive " + response.StatusDescription); response.Close(); } catch (Exception ex) { Log.Exception("[Client] Unexpected Exception", ex); result = TestResult.Fail; } finally { //Stop server server.StopServer(); } return result; } [TestMethod] public TestResult TestHTTPStatusCodeHTTP1_1_TemporaryRedirect() { TestResult result = TestResult.Pass; HttpWebRequest wr = (HttpWebRequest)WebRequest.Create("http://127.0.0.1:" + HttpServer.s_CurrentPort.ToString() + "/webpages/tempRedir.html"); //expect 307 - TemporaryRedirect wr.UserAgent = ".Net Micro Framwork Device/4.0"; wr.Method = "GET"; Log.Comment("Initial version: " + wr.ProtocolVersion); //Default version is 1.1 Log.Comment("Set Version 1.1"); wr.ProtocolVersion = new Version(1, 1); HttpServer server = new HttpServer("http", ref result) { RequestUri = wr.RequestUri, RequestHeaders = wr.Headers, ResponseString = "TestHTTPStatusCodeHTTP1_1_TemporaryRedirect" }; try { // Setup server server.StartServer(); HttpWebResponse response = (HttpWebResponse)wr.GetResponse(); Log.Comment("Expect StatusCode - TemporaryRedirect"); if ((int)HttpStatusCode.TemporaryRedirect != (int)response.StatusCode) { Log.Exception("Expect HttpStatusCode = TemporaryRedirect but get " + response.StatusCode); result = TestResult.Fail; } Log.Comment("Receive " + response.StatusDescription); response.Close(); } catch (Exception ex) { Log.Exception("[Client] Unexpected Exception", ex); result = TestResult.Fail; } finally { //Stop server server.StopServer(); } return result; } [TestMethod] public TestResult TestHTTPStatusCodeHTTP1_1_Accepted() { TestResult result = TestResult.Pass; HttpWebRequest wr = (HttpWebRequest)WebRequest.Create("http://127.0.0.1:" + HttpServer.s_CurrentPort.ToString() + "/webpages/accepted.html"); //expect 202 - Accepted wr.UserAgent = ".Net Micro Framwork Device/4.0"; wr.Method = "GET"; Log.Comment("Initial version: " + wr.ProtocolVersion); //Default version is 1.1 Log.Comment("Set Version 1.1"); wr.ProtocolVersion = new Version(1, 1); HttpServer server = new HttpServer("http", ref result) { RequestUri = wr.RequestUri, RequestHeaders = wr.Headers, ResponseString = "TestHTTPStatusCodeHTTP1_1_Accepted" }; try { // Setup server server.StartServer(); HttpWebResponse response = (HttpWebResponse)wr.GetResponse(); Log.Comment("Expect StatusCode - Accepted"); if ((int)HttpStatusCode.Accepted != (int)response.StatusCode) { Log.Exception("Expect HttpStatusCode = Accepted but get " + response.StatusCode); result = TestResult.Fail; } Log.Comment("Receive " + response.StatusDescription); response.Close(); } catch (Exception ex) { Log.Exception("[Client] Unexpected Exception", ex); result = TestResult.Fail; } finally { //Stop server server.StopServer(); } return result; } [TestMethod] public TestResult TestHTTPStatusCodeHTTP1_1_BadRequest() { TestResult result = TestResult.Pass; HttpWebRequest wr = (HttpWebRequest)WebRequest.Create("http://127.0.0.1:" + HttpServer.s_CurrentPort.ToString() + "/webpages/badRequest.html"); //expect 400 - BadRequest wr.UserAgent = ".Net Micro Framwork Device/4.0"; wr.Method = "GET"; Log.Comment("Initial version: " + wr.ProtocolVersion); //Default version is 1.1 Log.Comment("Set Version 1.1"); wr.ProtocolVersion = new Version(1, 1); HttpServer server = new HttpServer("http", ref result) { RequestUri = wr.RequestUri, RequestHeaders = wr.Headers, ResponseString = "TestHTTPStatusCodeHTTP1_1_BadRequest" }; try { // Setup server server.StartServer(); HttpWebResponse response = (HttpWebResponse)wr.GetResponse(); Log.Comment("Expect StatusCode - BadRequest"); if ((int)HttpStatusCode.BadRequest != (int)response.StatusCode) { Log.Exception("Expect HttpStatusCode = BadRequest but get " + response.StatusCode); result = TestResult.Fail; } Log.Comment("Receive " + response.StatusDescription); response.Close(); } catch (Exception ex) { Log.Exception("[Client] Unexpected Exception", ex); result = TestResult.Fail; } finally { //Stop server server.StopServer(); } return result; } [TestMethod] public TestResult TestHTTPStatusCodeHTTP1_1_Continue() { TestResult result = TestResult.Pass; HttpWebRequest wr = (HttpWebRequest)WebRequest.Create("http://127.0.0.1:" + HttpServer.s_CurrentPort.ToString() + "/webpages/continue.html"); //expect 100 - Continue wr.UserAgent = ".Net Micro Framwork Device/4.0"; wr.Method = "GET"; Log.Comment("Initial version: " + wr.ProtocolVersion); //Default version is 1.1 Log.Comment("Set Version 1.1"); wr.ProtocolVersion = new Version(1, 1); HttpServer server = new HttpServer("http", ref result) { RequestUri = wr.RequestUri, RequestHeaders = wr.Headers, ResponseString = "TestHTTPStatusCodeHTTP1_1_Continue" }; try { // Setup server server.StartServer(); wr.ContinueDelegate = delegate(int StatusCode, WebHeaderCollection httpHeaders){ }; HttpWebResponse response = (HttpWebResponse)wr.GetResponse(); Log.Comment("Expect StatusCode - Continue"); if ((int)HttpStatusCode.Continue != (int)response.StatusCode) { Log.Exception("Expect HttpStatusCode = Continue but get " + response.StatusCode); result = TestResult.Fail; } Log.Comment("Receive " + response.StatusDescription); response.Close(); } catch (Exception ex) { Log.Exception("[Client] Unexpected Exception", ex); result = TestResult.Fail; } finally { //Stop server server.StopServer(); } return result; } [TestMethod] public TestResult TestHTTPStatusCodeHTTP1_1_Created() { TestResult result = TestResult.Pass; HttpWebRequest wr = (HttpWebRequest)WebRequest.Create("http://127.0.0.1:" + HttpServer.s_CurrentPort.ToString() + "/webpages/created.html"); //expect 201 - Created wr.UserAgent = ".Net Micro Framwork Device/4.0"; wr.Method = "GET"; Log.Comment("Initial version: " + wr.ProtocolVersion); //Default version is 1.1 Log.Comment("Set Version 1.1"); wr.ProtocolVersion = new Version(1, 1); HttpServer server = new HttpServer("http", ref result) { RequestUri = wr.RequestUri, RequestHeaders = wr.Headers, ResponseString = "TestHTTPStatusCodeHTTP1_1_Created" }; try { // Setup server server.StartServer(); HttpWebResponse response = (HttpWebResponse)wr.GetResponse(); Log.Comment("Expect StatusCode - Created"); if ((int)HttpStatusCode.Created != (int)response.StatusCode) { Log.Exception("Expect HttpStatusCode = Created but get " + response.StatusCode); result = TestResult.Fail; } Log.Comment("Receive " + response.StatusDescription); response.Close(); } catch (Exception ex) { Log.Exception("[Client] Unexpected Exception", ex); result = TestResult.Fail; } finally { //Stop server server.StopServer(); } return result; } [TestMethod] public TestResult TestHTTPStatusCodeHTTP1_1_ExpectationFailed() { TestResult result = TestResult.Pass; HttpWebRequest wr = (HttpWebRequest)WebRequest.Create("http://127.0.0.1:" + HttpServer.s_CurrentPort.ToString() + "/webpages/expfailed.html"); //expect 417 - ExpectationFailed wr.UserAgent = ".Net Micro Framwork Device/4.0"; wr.Method = "GET"; Log.Comment("Initial version: " + wr.ProtocolVersion); //Default version is 1.1 Log.Comment("Set Version 1.1"); wr.ProtocolVersion = new Version(1, 1); HttpServer server = new HttpServer("http", ref result) { RequestUri = wr.RequestUri, RequestHeaders = wr.Headers, ResponseString = "TestHTTPStatusCodeHTTP1_1_ExpectationFailed" }; try { // Setup server server.StartServer(); HttpWebResponse response = (HttpWebResponse)wr.GetResponse(); Log.Comment("Expect StatusCode - ExpectationFailed"); if ((int)HttpStatusCode.ExpectationFailed != (int)response.StatusCode) { Log.Exception("Expect HttpStatusCode = ExpectationFailed but get " + response.StatusCode); result = TestResult.Fail; } Log.Comment("Receive " + response.StatusDescription); response.Close(); } catch (Exception ex) { Log.Exception("[Client] Unexpected Exception", ex); result = TestResult.Fail; } finally { //Stop server server.StopServer(); } return result; } [TestMethod] public TestResult TestHTTPStatusCodeHTTP1_1_Forbidden() { TestResult result = TestResult.Pass; HttpWebRequest wr = (HttpWebRequest)WebRequest.Create("http://127.0.0.1:" + HttpServer.s_CurrentPort.ToString() + "/webpages/forbidden.html"); //expect 403 - Forbidden wr.UserAgent = ".Net Micro Framwork Device/4.0"; wr.Method = "GET"; Log.Comment("Initial version: " + wr.ProtocolVersion); //Default version is 1.1 Log.Comment("Set Version 1.1"); wr.ProtocolVersion = new Version(1, 1); HttpServer server = new HttpServer("http", ref result) { RequestUri = wr.RequestUri, RequestHeaders = wr.Headers, ResponseString = "TestHTTPStatusCodeHTTP1_1_Forbidden" }; try { // Setup server server.StartServer(); HttpWebResponse response = (HttpWebResponse)wr.GetResponse(); Log.Comment("Expect StatusCode - Forbidden"); if ((int)HttpStatusCode.Forbidden != (int)response.StatusCode) { Log.Exception("Expect HttpStatusCode = Forbidden but get " + response.StatusCode); result = TestResult.Fail; } Log.Comment("Receive " + response.StatusDescription); response.Close(); } catch (Exception ex) { Log.Exception("[Client] Unexpected Exception", ex); result = TestResult.Fail; } finally { //Stop server server.StopServer(); } return result; } [TestMethod] public TestResult TestHTTPStatusCodeHTTP1_1_Found() { TestResult result = TestResult.Pass; HttpWebRequest wr = (HttpWebRequest)WebRequest.Create("http://127.0.0.1:" + HttpServer.s_CurrentPort.ToString() + "/webpages/found.html"); //expect 302 - Found wr.UserAgent = ".Net Micro Framwork Device/4.0"; wr.Method = "GET"; Log.Comment("Initial version: " + wr.ProtocolVersion); //Default version is 1.1 Log.Comment("Set Version 1.1"); wr.ProtocolVersion = new Version(1, 1); HttpServer server = new HttpServer("http", ref result) { RequestUri = wr.RequestUri, RequestHeaders = wr.Headers, ResponseString = "TestHTTPStatusCodeHTTP1_1_Found" }; try { // Setup server server.StartServer(); HttpWebResponse response = (HttpWebResponse)wr.GetResponse(); Log.Comment("Expect StatusCode - Found"); if ((int)HttpStatusCode.Found != (int)response.StatusCode) { Log.Exception("Expect HttpStatusCode = Found but get " + response.StatusCode); result = TestResult.Fail; } Log.Comment("Receive " + response.StatusDescription); response.Close(); } catch (Exception ex) { Log.Exception("[Client] Unexpected Exception", ex); result = TestResult.Fail; } finally { //Stop server server.StopServer(); } return result; } [TestMethod] public TestResult TestHTTPStatusCodeHTTP1_1_GatewayTimeout() { TestResult result = TestResult.Pass; HttpWebRequest wr = (HttpWebRequest)WebRequest.Create("http://127.0.0.1:" + HttpServer.s_CurrentPort.ToString() + "/webpages/gateway.html"); //expect - GatewayTimeout wr.UserAgent = ".Net Micro Framwork Device/4.0"; wr.Method = "GET"; Log.Comment("Initial version: " + wr.ProtocolVersion); //Default version is 1.1 Log.Comment("Set Version 1.1"); wr.ProtocolVersion = new Version(1, 1); HttpServer server = new HttpServer("http", ref result) { RequestUri = wr.RequestUri, RequestHeaders = wr.Headers, ResponseString = "TestHTTPStatusCodeHTTP1_1_GatewayTimeout" }; try { // Setup server server.StartServer(); HttpWebResponse response = (HttpWebResponse)wr.GetResponse(); Log.Comment("Expect StatusCode - GatewayTimeout"); if ((int)HttpStatusCode.GatewayTimeout != (int)response.StatusCode) { Log.Exception("Expect HttpStatusCode = GatewayTimeout but get " + response.StatusCode); result = TestResult.Fail; } Log.Comment("Receive " + response.StatusDescription); response.Close(); } catch (Exception ex) { Log.Exception("[Client] Unexpected Exception", ex); result = TestResult.Fail; } finally { //Stop server server.StopServer(); } return result; } [TestMethod] public TestResult TestHTTPStatusCodeHTTP1_1_Gone() { TestResult result = TestResult.Pass; HttpWebRequest wr = (HttpWebRequest)WebRequest.Create("http://127.0.0.1:" + HttpServer.s_CurrentPort.ToString() + "/webpages/gone.html"); //expect 410 - Gone wr.UserAgent = ".Net Micro Framwork Device/4.0"; wr.Method = "GET"; Log.Comment("Initial version: " + wr.ProtocolVersion); //Default version is 1.1 Log.Comment("Set Version 1.1"); wr.ProtocolVersion = new Version(1, 1); HttpServer server = new HttpServer("http", ref result) { RequestUri = wr.RequestUri, RequestHeaders = wr.Headers, ResponseString = "TestHTTPStatusCodeHTTP1_1_Gone" }; try { // Setup server server.StartServer(); HttpWebResponse response = (HttpWebResponse)wr.GetResponse(); Log.Comment("Expect StatusCode - Gone"); if ((int)HttpStatusCode.Gone != (int)response.StatusCode) { Log.Exception("Expect HttpStatusCode = Gone but get " + response.StatusCode); result = TestResult.Fail; } Log.Comment("Receive " + response.StatusDescription); response.Close(); } catch (Exception ex) { Log.Exception("[Client] Unexpected Exception", ex); result = TestResult.Fail; } finally { //Stop server server.StopServer(); } return result; } [TestMethod] public TestResult TestHTTPStatusCodeHTTP1_1_HttpVersionNotSupported() { TestResult result = TestResult.Pass; HttpWebRequest wr = (HttpWebRequest)WebRequest.Create("http://127.0.0.1:" + HttpServer.s_CurrentPort.ToString() + "/webpages/httpversion.html"); //expect 505 - HttpVersionNotSupported wr.UserAgent = ".Net Micro Framwork Device/4.0"; wr.Method = "GET"; Log.Comment("Initial version: " + wr.ProtocolVersion); //Default version is 1.1 Log.Comment("Set Version 1.1"); wr.ProtocolVersion = new Version(1, 1); HttpServer server = new HttpServer("http", ref result) { RequestUri = wr.RequestUri, RequestHeaders = wr.Headers, ResponseString = "TestHTTPStatusCodeHTTP1_1_HttpVersionNotSupported" }; try { // Setup server server.StartServer(); HttpWebResponse response = (HttpWebResponse)wr.GetResponse(); Log.Comment("Expect StatusCode - HttpVersionNotSupported"); if ((int)HttpStatusCode.HttpVersionNotSupported != (int)response.StatusCode) { Log.Exception("Expect HttpStatusCode = HttpVersionNotSupported but get " + response.StatusCode); result = TestResult.Fail; } Log.Comment("Receive " + response.StatusDescription); response.Close(); } catch (Exception ex) { Log.Exception("[Client] Unexpected Exception", ex); result = TestResult.Fail; } finally { //Stop server server.StopServer(); } return result; } [TestMethod] public TestResult TestHTTPStatusCodeHTTP1_1_InternalServerError() { TestResult result = TestResult.Pass; HttpWebRequest wr = (HttpWebRequest)WebRequest.Create("http://127.0.0.1:" + HttpServer.s_CurrentPort.ToString() + "/webpages/iserror.html"); //expect 500 - InternalServerError wr.UserAgent = ".Net Micro Framwork Device/4.0"; wr.Method = "GET"; Log.Comment("Initial version: " + wr.ProtocolVersion); //Default version is 1.1 Log.Comment("Set Version 1.1"); wr.ProtocolVersion = new Version(1, 1); HttpServer server = new HttpServer("http", ref result) { RequestUri = wr.RequestUri, RequestHeaders = wr.Headers, ResponseString = "TestHTTPStatusCodeHTTP1_1_InternalServerError" }; try { // Setup server server.StartServer(); HttpWebResponse response = (HttpWebResponse)wr.GetResponse(); Log.Comment("Expect StatusCode - InternalServerError"); if ((int)HttpStatusCode.InternalServerError != (int)response.StatusCode) { Log.Exception("Expect HttpStatusCode = InternalServerError but get " + response.StatusCode); result = TestResult.Fail; } Log.Comment("Receive " + response.StatusDescription); response.Close(); } catch (Exception ex) { Log.Exception("[Client] Unexpected Exception", ex); result = TestResult.Fail; } finally { //Stop server server.StopServer(); } return result; } [TestMethod] public TestResult TestHTTPStatusCodeHTTP1_1_LengthRequired() { TestResult result = TestResult.Pass; HttpWebRequest wr = (HttpWebRequest)WebRequest.Create("http://127.0.0.1:" + HttpServer.s_CurrentPort.ToString() + "/webpages/lrequired.html"); //expect 411 - LengthRequired wr.UserAgent = ".Net Micro Framwork Device/4.0"; wr.Method = "GET"; Log.Comment("Initial version: " + wr.ProtocolVersion); //Default version is 1.1 Log.Comment("Set Version 1.1"); wr.ProtocolVersion = new Version(1, 1); HttpServer server = new HttpServer("http", ref result) { RequestUri = wr.RequestUri, RequestHeaders = wr.Headers, ResponseString = "TestHTTPStatusCodeHTTP1_1_LengthRequired" }; try { // Setup server server.StartServer(); HttpWebResponse response = (HttpWebResponse)wr.GetResponse(); Log.Comment("Expect StatusCode - LengthRequired"); if ((int)HttpStatusCode.LengthRequired != (int)response.StatusCode) { Log.Exception("Expect HttpStatusCode = LengthRequired but get " + response.StatusCode); result = TestResult.Fail; } Log.Comment("Receive " + response.StatusDescription); response.Close(); } catch (Exception ex) { Log.Exception("[Client] Unexpected Exception", ex); result = TestResult.Fail; } finally { //Stop server server.StopServer(); } return result; } [TestMethod] public TestResult TestHTTPStatusCodeHTTP1_1_MethodNotAllowed() { TestResult result = TestResult.Pass; HttpWebRequest wr = (HttpWebRequest)WebRequest.Create("http://127.0.0.1:" + HttpServer.s_CurrentPort.ToString() + "/webpages/method.html"); //expect 405 - MethodNotAllowed wr.UserAgent = ".Net Micro Framwork Device/4.0"; wr.Method = "GET"; Log.Comment("Initial version: " + wr.ProtocolVersion); //Default version is 1.1 Log.Comment("Set Version 1.1"); wr.ProtocolVersion = new Version(1, 1); HttpServer server = new HttpServer("http", ref result) { RequestUri = wr.RequestUri, RequestHeaders = wr.Headers, ResponseString = "TestHTTPStatusCodeHTTP1_1_MethodNotAllowed" }; try { // Setup server server.StartServer(); HttpWebResponse response = (HttpWebResponse)wr.GetResponse(); Log.Comment("Expect StatusCode - MethodNotAllowed"); if ((int)HttpStatusCode.MethodNotAllowed != (int)response.StatusCode) { Log.Exception("Expect HttpStatusCode = MethodNotAllowed but get " + response.StatusCode); result = TestResult.Fail; } Log.Comment("Receive " + response.StatusDescription); response.Close(); } catch (Exception ex) { Log.Exception("[Client] Unexpected Exception", ex); result = TestResult.Fail; } finally { //Stop server server.StopServer(); } return result; } [TestMethod] public TestResult TestHTTPStatusCodeHTTP1_1_NoContent() { TestResult result = TestResult.Pass; HttpWebRequest wr = (HttpWebRequest)WebRequest.Create("http://127.0.0.1:" + HttpServer.s_CurrentPort.ToString() + "/webpages/NoContent.html"); //expect 204 - NoContent wr.UserAgent = ".Net Micro Framwork Device/4.0"; wr.Method = "GET"; Log.Comment("Initial version: " + wr.ProtocolVersion); //Default version is 1.1 Log.Comment("Set Version 1.1"); wr.ProtocolVersion = new Version(1, 1); HttpServer server = new HttpServer("http", ref result) { RequestUri = wr.RequestUri, RequestHeaders = wr.Headers, ResponseString = "TestHTTPStatusCodeHTTP1_1_NoContent" }; try { // Setup server server.StartServer(); HttpWebResponse response = (HttpWebResponse)wr.GetResponse(); Log.Comment("Expect StatusCode - NoContent"); if ((int)HttpStatusCode.NoContent != (int)response.StatusCode) { Log.Exception("Expect HttpStatusCode = NoContent but get " + response.StatusCode); result = TestResult.Fail; } Log.Comment("Receive " + response.StatusDescription); response.Close(); } catch (Exception ex) { Log.Exception("[Client] Unexpected Exception", ex); result = TestResult.Fail; } finally { //Stop server server.StopServer(); } return result; } [TestMethod] public TestResult TestHTTPStatusCodeHTTP1_1_NonAuthoritativeInformation() { TestResult result = TestResult.Pass; HttpWebRequest wr = (HttpWebRequest)WebRequest.Create("http://127.0.0.1:" + HttpServer.s_CurrentPort.ToString() + "/webpages/nonauthInfo.html"); //expect 203 - NonAuthoritativeInformation wr.UserAgent = ".Net Micro Framwork Device/4.0"; wr.Method = "GET"; Log.Comment("Initial version: " + wr.ProtocolVersion); //Default version is 1.1 Log.Comment("Set Version 1.1"); wr.ProtocolVersion = new Version(1, 1); HttpServer server = new HttpServer("http", ref result) { RequestUri = wr.RequestUri, RequestHeaders = wr.Headers, ResponseString = "TestHTTPStatusCodeHTTP1_1_NonAuthoritativeInformation" }; try { // Setup server server.StartServer(); HttpWebResponse response = (HttpWebResponse)wr.GetResponse(); Log.Comment("Expect StatusCode - NonAuthoritativeInformation"); if ((int)HttpStatusCode.NonAuthoritativeInformation != (int)response.StatusCode) { Log.Exception("Expect HttpStatusCode = NonAuthoritativeInformation but get " + response.StatusCode); result = TestResult.Fail; } Log.Comment("Receive " + response.StatusDescription); response.Close(); } catch (Exception ex) { Log.Exception("[Client] Unexpected Exception", ex); result = TestResult.Fail; } finally { //Stop server server.StopServer(); } return result; } [TestMethod] public TestResult TestHTTPStatusCodeHTTP1_1_NotAcceptable() { TestResult result = TestResult.Pass; HttpWebRequest wr = (HttpWebRequest)WebRequest.Create("http://127.0.0.1:" + HttpServer.s_CurrentPort.ToString() + "/webpages/NotAccept.html"); //expect - NotAcceptable wr.UserAgent = ".Net Micro Framwork Device/4.0"; wr.Method = "GET"; Log.Comment("Initial version: " + wr.ProtocolVersion); //Default version is 1.1 Log.Comment("Set Version 1.1"); wr.ProtocolVersion = new Version(1, 1); HttpServer server = new HttpServer("http", ref result) { RequestUri = wr.RequestUri, RequestHeaders = wr.Headers, ResponseString = "TestHTTPStatusCodeHTTP1_1_NotAcceptable" }; try { // Setup server server.StartServer(); HttpWebResponse response = (HttpWebResponse)wr.GetResponse(); Log.Comment("Expect StatusCode - NotAcceptable"); if ((int)HttpStatusCode.NotAcceptable != (int)response.StatusCode) { Log.Exception("Expect HttpStatusCode = NotAcceptable but get " + response.StatusCode); result = TestResult.Fail; } Log.Comment("Receive " + response.StatusDescription); response.Close(); } catch (Exception ex) { Log.Exception("[Client] Unexpected Exception", ex); result = TestResult.Fail; } finally { //Stop server server.StopServer(); } return result; } [TestMethod] public TestResult TestHTTPStatusCodeHTTP1_1_NotImplemented() { TestResult result = TestResult.Pass; HttpWebRequest wr = (HttpWebRequest)WebRequest.Create("http://127.0.0.1:" + HttpServer.s_CurrentPort.ToString() + "/webpages/NotImplement.html"); //expect 501 - NotImplemented wr.UserAgent = ".Net Micro Framwork Device/4.0"; wr.Method = "GET"; Log.Comment("Initial version: " + wr.ProtocolVersion); //Default version is 1.1 Log.Comment("Set Version 1.1"); wr.ProtocolVersion = new Version(1, 1); HttpServer server = new HttpServer("http", ref result) { RequestUri = wr.RequestUri, RequestHeaders = wr.Headers, ResponseString = "TestHTTPStatusCodeHTTP1_1_NotImplemented" }; try { // Setup server server.StartServer(); HttpWebResponse response = (HttpWebResponse)wr.GetResponse(); Log.Comment("Expect StatusCode - NotImplemented"); if ((int)HttpStatusCode.NotImplemented != (int)response.StatusCode) { Log.Exception("Expect HttpStatusCode = NotImplemented but get " + response.StatusCode); result = TestResult.Fail; } Log.Comment("Receive " + response.StatusDescription); response.Close(); } catch (Exception ex) { Log.Exception("[Client] Unexpected Exception", ex); result = TestResult.Fail; } finally { //Stop server server.StopServer(); } return result; } [TestMethod] public TestResult TestHTTPStatusCodeHTTP1_1_NotModified() { TestResult result = TestResult.Pass; HttpWebRequest wr = (HttpWebRequest)WebRequest.Create("http://127.0.0.1:" + HttpServer.s_CurrentPort.ToString() + "/webpages/NotModified.html"); //expect - NotModified wr.UserAgent = ".Net Micro Framwork Device/4.0"; wr.Method = "GET"; Log.Comment("Initial version: " + wr.ProtocolVersion); //Default version is 1.1 Log.Comment("Set Version 1.1"); wr.ProtocolVersion = new Version(1, 1); HttpServer server = new HttpServer("http", ref result) { RequestUri = wr.RequestUri, RequestHeaders = wr.Headers, ResponseString = "TestHTTPStatusCodeHTTP1_1_NotModified" }; try { // Setup server server.StartServer(); HttpWebResponse response = (HttpWebResponse)wr.GetResponse(); Log.Comment("Expect StatusCode - NotModified"); if ((int)HttpStatusCode.NotModified != (int)response.StatusCode) { Log.Exception("Expect HttpStatusCode = NotModified but get " + response.StatusCode); result = TestResult.Fail; } Log.Comment("Receive " + response.StatusDescription); response.Close(); } catch (Exception ex) { Log.Exception("[Client] Unexpected Exception", ex); result = TestResult.Fail; } finally { //Stop server server.StopServer(); } return result; } [TestMethod] public TestResult TestHTTPStatusCodeHTTP1_1_PartialContent() { TestResult result = TestResult.Pass; HttpWebRequest wr = (HttpWebRequest)WebRequest.Create("http://127.0.0.1:" + HttpServer.s_CurrentPort.ToString() + "/webpages/PContent.html"); //expect 206 - PartialContent wr.UserAgent = ".Net Micro Framwork Device/4.0"; wr.Method = "GET"; Log.Comment("Initial version: " + wr.ProtocolVersion); //Default version is 1.1 Log.Comment("Set Version 1.1"); wr.ProtocolVersion = new Version(1, 1); HttpServer server = new HttpServer("http", ref result) { RequestUri = wr.RequestUri, RequestHeaders = wr.Headers, ResponseString = "TestHTTPStatusCodeHTTP1_1_PartialContent" }; try { // Setup server server.StartServer(); HttpWebResponse response = (HttpWebResponse)wr.GetResponse(); Log.Comment("Expect StatusCode - PartialContent"); if ((int)HttpStatusCode.PartialContent != (int)response.StatusCode) { Log.Exception("Expect HttpStatusCode = PartialContent but get " + response.StatusCode); result = TestResult.Fail; } Log.Comment("Receive " + response.StatusDescription); response.Close(); } catch (Exception ex) { Log.Exception("[Client] Unexpected Exception", ex); result = TestResult.Fail; } finally { //Stop server server.StopServer(); } return result; } [TestMethod] public TestResult TestHTTPStatusCodeHTTP1_1_PreconditionFailed() { TestResult result = TestResult.Pass; HttpWebRequest wr = (HttpWebRequest)WebRequest.Create("http://127.0.0.1:" + HttpServer.s_CurrentPort.ToString() + "/webpages/Precond.html"); //expect 412 - PreconditionFailed wr.UserAgent = ".Net Micro Framwork Device/4.0"; wr.Method = "GET"; Log.Comment("Initial version: " + wr.ProtocolVersion); //Default version is 1.1 Log.Comment("Set Version 1.1"); wr.ProtocolVersion = new Version(1, 1); HttpServer server = new HttpServer("http", ref result) { RequestUri = wr.RequestUri, RequestHeaders = wr.Headers, ResponseString = "TestHTTPStatusCodeHTTP1_1_PreconditionFailed" }; try { // Setup server server.StartServer(); HttpWebResponse response = (HttpWebResponse)wr.GetResponse(); Log.Comment("Expect StatusCode - PreconditionFailed"); if ((int)HttpStatusCode.PreconditionFailed != (int)response.StatusCode) { Log.Exception("Expect HttpStatusCode = PreconditionFailed but get " + response.StatusCode); result = TestResult.Fail; } Log.Comment("Receive " + response.StatusDescription); response.Close(); } catch (Exception ex) { Log.Exception("[Client] Unexpected Exception", ex); result = TestResult.Fail; } finally { //Stop server server.StopServer(); } return result; } [TestMethod] public TestResult TestHTTPStatusCodeHTTP1_1_ProxyAuthenticationRequired() { TestResult result = TestResult.Pass; HttpWebRequest wr = (HttpWebRequest)WebRequest.Create("http://127.0.0.1:" + HttpServer.s_CurrentPort.ToString() + "/webpages/ProxyAuth.html"); //expect - ProxyAuthenticationRequired wr.UserAgent = ".Net Micro Framwork Device/4.0"; wr.Method = "GET"; Log.Comment("Initial version: " + wr.ProtocolVersion); //Default version is 1.1 Log.Comment("Set Version 1.1"); wr.ProtocolVersion = new Version(1, 1); HttpServer server = new HttpServer("http", ref result) { RequestUri = wr.RequestUri, RequestHeaders = wr.Headers, ResponseString = "TestHTTPStatusCodeHTTP1_1_ProxyAuthenticationRequired" }; try { // Setup server server.StartServer(); HttpWebResponse response = (HttpWebResponse)wr.GetResponse(); Log.Comment("Expect StatusCode - ProxyAuthenticationRequired"); if ((int)HttpStatusCode.ProxyAuthenticationRequired != (int)response.StatusCode) { Log.Exception("Expect HttpStatusCode = ProxyAuthenticationRequired but get " + response.StatusCode); result = TestResult.Fail; } Log.Comment("Receive " + response.StatusDescription); response.Close(); } catch (Exception ex) { Log.Exception("[Client] Unexpected Exception", ex); result = TestResult.Fail; } finally { //Stop server server.StopServer(); } return result; } [TestMethod] public TestResult TestHTTPStatusCodeHTTP1_1_RedirectMethod() { TestResult result = TestResult.Pass; HttpWebRequest wr = (HttpWebRequest)WebRequest.Create("http://127.0.0.1:" + HttpServer.s_CurrentPort.ToString() + "/webpages/RMethod.html"); //expect - RedirectMethod wr.UserAgent = ".Net Micro Framwork Device/4.0"; wr.Method = "GET"; Log.Comment("Initial version: " + wr.ProtocolVersion); //Default version is 1.1 Log.Comment("Set Version 1.1"); wr.ProtocolVersion = new Version(1, 1); HttpServer server = new HttpServer("http", ref result) { RequestUri = wr.RequestUri, RequestHeaders = wr.Headers, ResponseString = "TestHTTPStatusCodeHTTP1_1_RedirectMethod" }; try { // Setup server server.StartServer(); HttpWebResponse response = (HttpWebResponse)wr.GetResponse(); Log.Comment("Expect StatusCode - RedirectMethod"); if ((int)HttpStatusCode.RedirectMethod != (int)response.StatusCode) { Log.Exception("Expect HttpStatusCode = RedirectMethod but get " + response.StatusCode); result = TestResult.Fail; } Log.Comment("Receive " + response.StatusDescription); response.Close(); } catch (Exception ex) { Log.Exception("[Client] Unexpected Exception", ex); result = TestResult.Fail; } finally { //Stop server server.StopServer(); } return result; } [TestMethod] public TestResult TestHTTPStatusCodeHTTP1_1_RequestedRangeNotSatisfiable() { TestResult result = TestResult.Pass; HttpWebRequest wr = (HttpWebRequest)WebRequest.Create("http://127.0.0.1:" + HttpServer.s_CurrentPort.ToString() + "/webpages/reqRange.html"); //expect 416 - RequestedRangeNotSatisfiable wr.UserAgent = ".Net Micro Framwork Device/4.0"; wr.Method = "GET"; Log.Comment("Initial version: " + wr.ProtocolVersion); //Default version is 1.1 Log.Comment("Set Version 1.1"); wr.ProtocolVersion = new Version(1, 1); HttpServer server = new HttpServer("http", ref result) { RequestUri = wr.RequestUri, RequestHeaders = wr.Headers, ResponseString = "TestHTTPStatusCodeHTTP1_1_RequestedRangeNotSatisfiable" }; try { // Setup server server.StartServer(); HttpWebResponse response = (HttpWebResponse)wr.GetResponse(); Log.Comment("Expect StatusCode - RequestedRangeNotSatisfiable"); if ((int)HttpStatusCode.RequestedRangeNotSatisfiable != (int)response.StatusCode) { Log.Exception("Expect HttpStatusCode = RequestedRangeNotSatisfiable but get " + response.StatusCode); result = TestResult.Fail; } Log.Comment("Receive " + response.StatusDescription); response.Close(); } catch (Exception ex) { Log.Exception("[Client] Unexpected Exception", ex); result = TestResult.Fail; } finally { //Stop server server.StopServer(); } return result; } [TestMethod] public TestResult TestHTTPStatusCodeHTTP1_1_RequestEntityTooLarge() { TestResult result = TestResult.Pass; HttpWebRequest wr = (HttpWebRequest)WebRequest.Create("http://127.0.0.1:" + HttpServer.s_CurrentPort.ToString() + "/webpages/reqEntity.html"); //expect 413 - RequestEntityTooLarge wr.UserAgent = ".Net Micro Framwork Device/4.0"; wr.Method = "GET"; Log.Comment("Initial version: " + wr.ProtocolVersion); //Default version is 1.1 Log.Comment("Set Version 1.1"); wr.ProtocolVersion = new Version(1, 1); HttpServer server = new HttpServer("http", ref result) { RequestUri = wr.RequestUri, RequestHeaders = wr.Headers, ResponseString = "TestHTTPStatusCodeHTTP1_1_RequestEntityTooLarge" }; try { // Setup server server.StartServer(); HttpWebResponse response = (HttpWebResponse)wr.GetResponse(); Log.Comment("Expect StatusCode - RequestEntityTooLarge"); if ((int)HttpStatusCode.RequestEntityTooLarge != (int)response.StatusCode) { Log.Exception("Expect HttpStatusCode = RequestEntityTooLarge but get " + response.StatusCode); result = TestResult.Fail; } Log.Comment("Receive " + response.StatusDescription); response.Close(); } catch (Exception ex) { Log.Exception("[Client] Unexpected Exception", ex); result = TestResult.Fail; } finally { //Stop server server.StopServer(); } return result; } [TestMethod] public TestResult TestHTTPStatusCodeHTTP1_1_ResetContent() { TestResult result = TestResult.Pass; HttpWebRequest wr = (HttpWebRequest)WebRequest.Create("http://127.0.0.1:" + HttpServer.s_CurrentPort.ToString() + "/webpages/ResetContent.html"); //expect - ResetContent wr.UserAgent = ".Net Micro Framwork Device/4.0"; wr.Method = "GET"; Log.Comment("Initial version: " + wr.ProtocolVersion); //Default version is 1.1 Log.Comment("Set Version 1.1"); wr.ProtocolVersion = new Version(1, 1); HttpServer server = new HttpServer("http", ref result) { RequestUri = wr.RequestUri, RequestHeaders = wr.Headers, ResponseString = "TestHTTPStatusCodeHTTP1_1_ResetContent" }; try { // Setup server server.StartServer(); HttpWebResponse response = (HttpWebResponse)wr.GetResponse(); Log.Comment("Expect StatusCode - ResetContent"); if ((int)HttpStatusCode.ResetContent != (int)response.StatusCode) { Log.Exception("Expect HttpStatusCode = ResetContent but get " + response.StatusCode); result = TestResult.Fail; } Log.Comment("Receive " + response.StatusDescription); response.Close(); } catch (Exception ex) { Log.Exception("[Client] Unexpected Exception", ex); result = TestResult.Fail; } finally { //Stop server server.StopServer(); } return result; } [TestMethod] public TestResult TestHTTPStatusCodeHTTP1_1_SeeOther() { TestResult result = TestResult.Pass; HttpWebRequest wr = (HttpWebRequest)WebRequest.Create("http://127.0.0.1:" + HttpServer.s_CurrentPort.ToString() + "/webpages/SeeOther.html"); //expect - SeeOther wr.UserAgent = ".Net Micro Framwork Device/4.0"; wr.Method = "GET"; Log.Comment("Initial version: " + wr.ProtocolVersion); //Default version is 1.1 Log.Comment("Set Version 1.1"); wr.ProtocolVersion = new Version(1, 1); HttpServer server = new HttpServer("http", ref result) { RequestUri = wr.RequestUri, RequestHeaders = wr.Headers, ResponseString = "TestHTTPStatusCodeHTTP1_1_SeeOther" }; try { // Setup server server.StartServer(); HttpWebResponse response = (HttpWebResponse)wr.GetResponse(); Log.Comment("Expect StatusCode - SeeOther"); if ((int)HttpStatusCode.SeeOther != (int)response.StatusCode) { Log.Exception("Expect HttpStatusCode = SeeOther but get " + response.StatusCode); result = TestResult.Fail; } Log.Comment("Receive " + response.StatusDescription); response.Close(); } catch (Exception ex) { Log.Exception("[Client] Unexpected Exception", ex); result = TestResult.Fail; } finally { //Stop server server.StopServer(); } return result; } [TestMethod] public TestResult TestHTTPStatusCodeHTTP1_1_SwitchingProtocols() { TestResult result = TestResult.Pass; HttpWebRequest wr = (HttpWebRequest)WebRequest.Create("http://127.0.0.1:" + HttpServer.s_CurrentPort.ToString() + "/webpages/SwitchProt.html"); //expect - SwitchingProtocols wr.UserAgent = ".Net Micro Framwork Device/4.0"; wr.Method = "GET"; Log.Comment("Initial version: " + wr.ProtocolVersion); //Default version is 1.1 Log.Comment("Set Version 1.1"); wr.ProtocolVersion = new Version(1, 1); HttpServer server = new HttpServer("http", ref result) { RequestUri = wr.RequestUri, RequestHeaders = wr.Headers, ResponseString = "TestHTTPStatusCodeHTTP1_1_SwitchingProtocols" }; try { // Setup server server.StartServer(); HttpWebResponse response = (HttpWebResponse)wr.GetResponse(); Log.Comment("Expect StatusCode - SwitchingProtocols"); if ((int)HttpStatusCode.SwitchingProtocols != (int)response.StatusCode) { Log.Exception("Expect HttpStatusCode = SwitchingProtocols but get " + response.StatusCode); result = TestResult.Fail; } Log.Comment("Receive " + response.StatusDescription); response.Close(); } catch (Exception ex) { Log.Exception("[Client] Unexpected Exception", ex); result = TestResult.Fail; } finally { //Stop server server.StopServer(); } return result; } [TestMethod] public TestResult TestHTTPStatusCodeHTTP1_1_Unauthorized() { TestResult result = TestResult.Pass; HttpWebRequest wr = (HttpWebRequest)WebRequest.Create("http://127.0.0.1:" + HttpServer.s_CurrentPort.ToString() + "/webpages/Unauth.html"); //expect - Unauthorized wr.UserAgent = ".Net Micro Framwork Device/4.0"; wr.Method = "GET"; Log.Comment("Initial version: " + wr.ProtocolVersion); //Default version is 1.1 Log.Comment("Set Version 1.1"); wr.ProtocolVersion = new Version(1, 1); HttpServer server = new HttpServer("http", ref result) { RequestUri = wr.RequestUri, RequestHeaders = wr.Headers, ResponseString = "TestHTTPStatusCodeHTTP1_1_Unauthorized" }; try { // Setup server server.StartServer(); HttpWebResponse response = (HttpWebResponse)wr.GetResponse(); Log.Comment("Expect StatusCode - Unauthorized"); if ((int)HttpStatusCode.Unauthorized != (int)response.StatusCode) { Log.Exception("Expect HttpStatusCode = Unauthorized but get " + response.StatusCode); result = TestResult.Fail; } Log.Comment("Receive " + response.StatusDescription); response.Close(); } catch (Exception ex) { Log.Exception("[Client] Unexpected Exception", ex); result = TestResult.Fail; } finally { //Stop server server.StopServer(); } return result; } [TestMethod] public TestResult TestHTTPStatusCodeHTTP1_1_Unused() { TestResult result = TestResult.Pass; HttpWebRequest wr = (HttpWebRequest)WebRequest.Create("http://127.0.0.1:" + HttpServer.s_CurrentPort.ToString() + "/webpages/Unused.html"); //expect - Unused wr.UserAgent = ".Net Micro Framwork Device/4.0"; wr.Method = "GET"; Log.Comment("Initial version: " + wr.ProtocolVersion); //Default version is 1.1 Log.Comment("Set Version 1.1"); wr.ProtocolVersion = new Version(1, 1); HttpServer server = new HttpServer("http", ref result) { RequestUri = wr.RequestUri, RequestHeaders = wr.Headers, ResponseString = "TestHTTPStatusCodeHTTP1_1_Unused" }; try { // Setup server server.StartServer(); HttpWebResponse response = (HttpWebResponse)wr.GetResponse(); Log.Comment("Expect StatusCode - Unused"); if ((int)HttpStatusCode.Unused != (int)response.StatusCode) { Log.Exception("Expect HttpStatusCode = Unused but get " + response.StatusCode); result = TestResult.Fail; } Log.Comment("Receive " + response.StatusDescription); response.Close(); } catch (Exception ex) { Log.Exception("[Client] Unexpected Exception", ex); result = TestResult.Fail; } finally { //Stop server server.StopServer(); } return result; } [TestMethod] public TestResult TestHTTPStatusCodeHTTP1_1_UseProxy() { TestResult result = TestResult.Pass; HttpWebRequest wr = (HttpWebRequest)WebRequest.Create("http://127.0.0.1:" + HttpServer.s_CurrentPort.ToString() + "/webpages/UseProxy.html"); //expect - UseProxy wr.UserAgent = ".Net Micro Framwork Device/4.0"; wr.Method = "GET"; Log.Comment("Initial version: " + wr.ProtocolVersion); //Default version is 1.1 Log.Comment("Set Version 1.1"); wr.ProtocolVersion = new Version(1, 1); HttpServer server = new HttpServer("http", ref result) { RequestUri = wr.RequestUri, RequestHeaders = wr.Headers, ResponseString = "TestHTTPStatusCodeHTTP1_1_UseProxy" }; try { // Setup server server.StartServer(); HttpWebResponse response = (HttpWebResponse)wr.GetResponse(); Log.Comment("Expect StatusCode - UseProxy"); if ((int)HttpStatusCode.UseProxy != (int)response.StatusCode) { Log.Exception("Expect HttpStatusCode = UseProxy but get " + response.StatusCode); result = TestResult.Fail; } Log.Comment("Receive " + response.StatusDescription); response.Close(); } catch (Exception ex) { Log.Exception("[Client] Unexpected Exception", ex); result = TestResult.Fail; } finally { //Stop server server.StopServer(); } return result; } [TestMethod] public TestResult TestHTTPStatusCodeHTTP1_0_SendChunked_WithTransferEncoding() { TestResult result = TestResult.Pass; HttpWebRequest wr = (HttpWebRequest)WebRequest.Create("http://127.0.0.1:" + HttpServer.s_CurrentPort.ToString() + "/"); //expect 200 - OK wr.UserAgent = ".Net Micro Framwork Device/4.0"; Log.Comment("Initial version: " + wr.ProtocolVersion); //Default version is 1.1 Log.Comment("Set Version 1.0"); wr.ProtocolVersion = new Version(1, 0); wr.SendChunked = true; wr.TransferEncoding = "binary"; string requestString = "ContentLength: " + wr.ContentLength + " ContentType:" + wr.ContentType + " KeepAlive:" + wr.KeepAlive + " ProtocolVersion:" + wr.ProtocolVersion + " TransferEncoding:" + wr.TransferEncoding + " SendChunked:" + wr.SendChunked + " Expect:" + wr.Expect + " Timeout:" + wr.Timeout; Log.Comment(requestString); HttpServer server = new HttpServer("http", ref result) { RequestUri = wr.RequestUri, RequestHeaders = wr.Headers, ResponseString = "TestHTTPStatusCodeHTTP1_0_SendChunked_WithTransferEncoding" }; try { // Setup server server.StartServer(); HttpWebResponse response = (HttpWebResponse)wr.GetResponse(); string ResponseString = "Server response: ContentEncoding:" + response.ContentEncoding + " ContentLength: " + response.ContentLength + " ContentType:" + response.ContentType + " ProtocolVersion:" + response.ProtocolVersion + " Server:" + response.Server + " StatusCode:" + response.StatusCode + " StatusDescription:" + response.StatusDescription; Log.Comment(ResponseString); Log.Comment("Expect StatusCode - OK"); if (HttpStatusCode.OK != response.StatusCode) { Log.Exception("Expect HttpStatusCode = OK but get " + response.StatusCode); result = TestResult.Fail; } Log.Comment("Receive " + response.StatusDescription); response.Close(); } catch (Exception ex) { Log.Exception("[Client] Unexpected Exception", ex); result = TestResult.Fail; } finally { //Stop server server.StopServer(); } return result; } #endregion Test } } ================================================ FILE: Zelig/Zelig/Test/RunTime/NETMF/System/Http/HttpVersionTests.cs ================================================ //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // Copyright (c) Microsoft Corporation. All rights reserved. //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// using System; using System.Net; namespace Microsoft.Zelig.Test { public class HttpVersionTests : TestBase, ITestInterface { [SetUp] public InitializeResult Initialize() { Log.Comment("Adding set up for the tests."); try { // Check networking - we need to make sure we can reach our proxy server Dns.GetHostEntry(HttpTests.Proxy); } catch (Exception ex) { Log.Exception("Unable to get address for " + HttpTests.Proxy, ex); return InitializeResult.Skip; } return InitializeResult.ReadyToGo; } [TearDown] public void CleanUp() { Log.Comment("Cleaning up after the tests."); // TODO: Add your clean up steps here. } public override TestResult Run( string[] args ) { return TestResult.Pass; } //--// //--// //--// #region Helper methods private TestResult Verify(HttpWebRequest Request, Version ExpectedVersion) { TestResult result = TestResult.Pass; // Assign Proxy Request.Proxy = new WebProxy(HttpTests.Proxy, true); HttpWebResponse myResponse = (HttpWebResponse)Request.GetResponse(); Log.Comment("Version after assignment:" + Request.ProtocolVersion); Log.Comment("Response version:" + myResponse.ProtocolVersion); if (Request.ProtocolVersion.Major != ExpectedVersion.Major && Request.ProtocolVersion.Minor != ExpectedVersion.Major) { Log.Exception("Expected Request Version " + ExpectedVersion); result = TestResult.Fail; } if (myResponse.ProtocolVersion != HttpVersion.Version11) { Log.Exception("Expected Response Version 1.1"); result = TestResult.Fail; } return result; } #endregion Helper methods #region Test Cases [TestMethod] public TestResult VerifyDefault() { TestResult result = TestResult.Pass; try { HttpWebRequest myRequest = (HttpWebRequest)WebRequest.Create("http://www.microsoft.com"); if (myRequest.ProtocolVersion != HttpVersion.Version11) { Log.Exception("Expected Version 1.1, but got " + myRequest.ProtocolVersion); return TestResult.Fail; } result = Verify(myRequest, HttpVersion.Version11); } catch (Exception ex) { Log.Exception("Unexpected exception", ex); result = TestResult.Fail; } return result; } [TestMethod] public TestResult VerifyChange10() { TestResult result = TestResult.Pass; try { HttpWebRequest myRequest = (HttpWebRequest)WebRequest.Create("http://www.microsoft.com"); myRequest.ProtocolVersion = HttpVersion.Version10; result = Verify(myRequest, HttpVersion.Version10); } catch (Exception ex) { Log.Exception("Unexpected exception", ex); result = TestResult.Fail; } return result; } [TestMethod] public TestResult VerifyChange11() { TestResult result = TestResult.Pass; try { HttpWebRequest myRequest = (HttpWebRequest)WebRequest.Create("http://www.microsoft.com"); myRequest.ProtocolVersion = HttpVersion.Version11; result = Verify(myRequest, HttpVersion.Version11); } catch (Exception ex) { Log.Exception("Unexpected exception", ex); result = TestResult.Fail; } return result; } #endregion Test Cases } } ================================================ FILE: Zelig/Zelig/Test/RunTime/NETMF/System/Http/HttpWebRequestTests.cs ================================================ //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // Copyright (c) Microsoft Corporation. All rights reserved. //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// using Microsoft.Llilum.Lwip; using System; using System.IO; using System.Net; namespace Microsoft.Zelig.Test { public class HttpWebRequestTests : TestBase, ITestInterface { [SetUp] public InitializeResult Initialize() { Log.Comment("Adding set up for the tests."); try { NetworkInterface[] nis = NetworkInterface.GetAllNetworkInterfaces(); } catch { return InitializeResult.Skip; } return InitializeResult.ReadyToGo; } [TearDown] public void CleanUp() { Log.Comment("Cleaning up after the tests."); // TODO: Add your clean up steps here. } public override TestResult Run( string[] args ) { return TestResult.Pass; } //--// //--// //--// #region Test Cases [TestMethod] public TestResult ConstructorTestsValid() { TestResult result = TestResult.Pass; try { Log.Comment("Create string request"); HttpWebRequest strRequest = (HttpWebRequest)HttpWebRequest.Create(HttpTests.MSUrl); Log.Comment("Create URI request"); Uri uri = new Uri(HttpTests.MSUrl); HttpWebRequest uriRequest = (HttpWebRequest)HttpWebRequest.Create(uri); } catch (Exception ex) { Log.Exception("Unexpected Exception", ex); result = TestResult.Fail; } return result; } [TestMethod] public TestResult ConstructorTestsNullArgs() { TestResult result = TestResult.Pass; try { Log.Comment("Create string request"); string URL = null; try { HttpWebRequest strRequest = (HttpWebRequest)HttpWebRequest.Create(URL); Log.Exception("Expected ArgumentNullException"); result = TestResult.Fail; } catch (Exception ex) { /* pass case */ if (!HttpTests.ValidateException(ex, typeof(ArgumentNullException))) result = TestResult.Fail; } Log.Comment("Create URI request"); Uri uri = null; try { HttpWebRequest uriRequest = (HttpWebRequest)HttpWebRequest.Create(uri); Log.Exception("Expected ArgumentNullException"); result = TestResult.Fail; } catch (Exception ex) { /* pass case */ if (!HttpTests.ValidateException(ex, typeof(ArgumentNullException))) result = TestResult.Fail; } } catch (Exception ex) { Log.Exception("Unexpected Exception", ex); result = TestResult.Fail; } return result; } [TestMethod] public TestResult ConstructorTestsEmptyArgs() { TestResult result = TestResult.Pass; try { Log.Comment("Create string request"); string URL = ""; try { HttpWebRequest strRequest = (HttpWebRequest)HttpWebRequest.Create(URL); Log.Exception("Expected ArgumentException"); result = TestResult.Fail; } catch (Exception ex) { /* pass case */ if (!HttpTests.ValidateException(ex, typeof(ArgumentNullException))) result = TestResult.Fail; } } catch (Exception ex) { Log.Exception("Unexpected Exception", ex); result = TestResult.KnownFailure; } return result; } [TestMethod] public TestResult AddRangeValidTests() { TestResult result = TestResult.Pass; HttpWebRequest wr; try { Log.Comment("AddRange(1)"); wr = (HttpWebRequest)WebRequest.Create(HttpTests.MSUrl); wr.AddRange(1); if (wr.Headers["Range"] != "bytes=1-") { Log.Exception("Expected bytes=1-, but got " + wr.Headers["Range"]); result = TestResult.Fail; } Log.Comment("AddRange(-1)"); wr = (HttpWebRequest)WebRequest.Create(HttpTests.MSUrl); wr.AddRange(-1); if (wr.Headers["Range"] != "bytes=-1") { Log.Exception("Expected bytes=-1, but got " + wr.Headers["Range"]); result = TestResult.Fail; } Log.Comment("AddRange(100, 500)"); wr = (HttpWebRequest)WebRequest.Create(HttpTests.MSUrl); wr.AddRange(100, 500); if (wr.Headers["Range"] != "bytes=100-500") { Log.Exception("Expected bytes=100-500, but got " + wr.Headers["Range"]); result = TestResult.Fail; } Log.Comment("MultiRange - AddRange(1, 5) + AddRange(100, 500)"); wr = (HttpWebRequest)WebRequest.Create(HttpTests.MSUrl); wr.AddRange(1, 5); wr.AddRange(100, 500); if (wr.Headers["Range"] != "bytes=1-5,100-500") { Log.Exception("Expected bytes=1-5,100-500, but got " + wr.Headers["Range"]); result = TestResult.Fail; } Log.Comment("AddRange(chars, 5000)"); wr = (HttpWebRequest)WebRequest.Create(HttpTests.MSUrl); wr.AddRange("chars", 5000); if (wr.Headers["Range"] != "chars=5000-") { Log.Exception("Expected chars=5000-, but got " + wr.Headers["Range"]); result = TestResult.Fail; } Log.Comment("AddRange(strings, 800, 900)"); wr = (HttpWebRequest)WebRequest.Create(HttpTests.MSUrl); wr.AddRange("strings", 800, 900); if (wr.Headers["Range"] != "strings=800-900") { Log.Exception("Expected strings=800-900, but got " + wr.Headers["Range"]); result = TestResult.Fail; } } catch (Exception ex) { Log.Exception("Unexpected Exception", ex); result = TestResult.Fail; } return result; } [TestMethod] public TestResult AddRangeInvalidTests() { TestResult result = TestResult.Pass; HttpWebRequest wr; try { Log.Comment("invalid from - AddRange(-1, 500)"); wr = (HttpWebRequest)WebRequest.Create(HttpTests.MSUrl); try { wr.AddRange(-1, 500); Log.Exception("Expected ArgumentOutOfRangeException"); result = TestResult.Fail; } catch (Exception ex) { /* pass case */ if (!HttpTests.ValidateException(ex, typeof(ArgumentOutOfRangeException))) result = TestResult.Fail; } Log.Comment("invalid from - AddRange(1, -500)"); wr = (HttpWebRequest)WebRequest.Create(HttpTests.MSUrl); try { wr.AddRange(1, -500); Log.Exception("Expected ArgumentOutOfRangeException"); result = TestResult.Fail; } catch (Exception ex) { /* pass case */ if (!HttpTests.ValidateException(ex, typeof(ArgumentOutOfRangeException))) result = TestResult.Fail; } Log.Comment("invalid specifier - AddRange(null, 500)"); wr = (HttpWebRequest)WebRequest.Create(HttpTests.MSUrl); try { wr.AddRange(null, 500); Log.Exception("Expected ArgumentNullException"); result = TestResult.Fail; } catch (Exception ex) { /* pass case */ if (!HttpTests.ValidateException(ex, typeof(ArgumentNullException))) result = TestResult.Fail; } Log.Comment("invalid specifier - AddRange(null, 1, 500)"); wr = (HttpWebRequest)WebRequest.Create(HttpTests.MSUrl); try { wr.AddRange(null, 1, 500); Log.Exception("Expected ArgumentNullException"); result = TestResult.Fail; } catch (Exception ex) { /* pass case */ if (!HttpTests.ValidateException(ex, typeof(ArgumentNullException))) result = TestResult.Fail; } } catch (Exception ex) { Log.Exception("Unexpected Exception", ex); result = TestResult.Fail; } return result; } [TestMethod] public TestResult CheckBadHeaders() { TestResult result = TestResult.Pass; try { Log.Comment("low byte"); if (!TestCheckBadHeaders("low byte \u0031 embedded string")) result = TestResult.Fail; Log.Comment("high byte"); if (!TestCheckBadHeaders("high byte \u0128 embedded string")) result = TestResult.Fail; Log.Comment("bad nl wrap"); if (!TestCheckBadHeaders("bad\nwrap")) result = TestResult.Fail; Log.Comment("bad crlf wrap"); if (!TestCheckBadHeaders("bad\r\nwrap")) result = TestResult.Fail; Log.Comment("embedded tab"); if (!TestCheckBadHeaders("embedded\ttab")) result = TestResult.Fail; } catch (Exception ex) { Log.Exception("Unexpected Exception", ex); result = TestResult.Fail; } return result; } private bool TestCheckBadHeaders(string value) { HttpWebRequest wr = (HttpWebRequest)WebRequest.Create(HttpTests.MSUrl); ; try { wr.Headers.Add("Test", value); } catch (Exception ex) { if (!HttpTests.ValidateException(ex, typeof(ArgumentException))) return false; } return true; } [TestMethod] public TestResult AcceptHeaderTest() { TestResult result = TestResult.Pass; HttpWebRequest wr = (HttpWebRequest)WebRequest.Create(HttpTests.MSUrl);; try { Log.Comment("Initial value should be null"); if (wr.Accept != null) { Log.Exception("Unexpected initial value: " + wr.Accept); result = TestResult.Fail; } if (!ValidateAccept(wr, "text/plain")) result = TestResult.Fail; if (!ValidateAccept(wr, "text/plain; q=0.5, text/html,\r\n\ttext/x-dvi; q=0.8, text/x-c")) result = TestResult.Fail; if (!ValidateAccept(wr, "text/*;q=0.3, text/html;q=0.7, text/html;level=1,\r\n\ttext/html;level=2;q=0.4, */*;q=0.5")) result = TestResult.Fail; Log.Comment("Clear w/null header"); if (!ValidateAccept(wr, null)) result = TestResult.Fail; } catch (Exception ex) { Log.Exception("Unexpected Exception", ex); result = TestResult.Fail; } return result; } private bool ValidateAccept(HttpWebRequest wr, string mediaRange) { Log.Comment("Media-Range: " + mediaRange); wr.Accept = mediaRange; if (wr.Accept != mediaRange) { Log.Exception("Expected: " + mediaRange + ", but got: " + wr.Accept); return false; } return true; } [TestMethod] public TestResult ContentLengthHeader() { TestResult result = TestResult.Pass; HttpWebRequest wr = (HttpWebRequest)WebRequest.Create(HttpTests.MSUrl); ; try { Log.Comment("negative value should throw"); try { wr.ContentLength = -1; } catch (Exception ex) { /* pass case */ if (!HttpTests.ValidateException(ex, typeof(ArgumentOutOfRangeException))) result = TestResult.Fail; } wr.ContentLength = 1234567; if (wr.ContentLength != 1234567) { Log.Exception("Expected ContentLength 1234567, but got " + wr.ContentLength); result = TestResult.Fail; } } catch (Exception ex) { Log.Exception("Unexpected Exception", ex); result = TestResult.Fail; } return result; } [TestMethod] public TestResult ProtocolVersion() { TestResult result = TestResult.Pass; HttpWebRequest wr = (HttpWebRequest)WebRequest.Create(HttpTests.MSUrl); try { Log.Comment("Initial version: " + wr.ProtocolVersion); Log.Comment("Set Version 1.0"); wr.ProtocolVersion = new Version(1, 0); if (wr.ProtocolVersion.Major != 1 && wr.ProtocolVersion.Minor != 0) { Log.Exception("Expected version 1.0, but got " + wr.ProtocolVersion.ToString()); result = TestResult.Fail; } Log.Comment("Set Version 1.1"); wr.ProtocolVersion = new Version(1, 1); if (wr.ProtocolVersion.Major != 1 && wr.ProtocolVersion.Minor != 1) { Log.Exception("Expected version 1.0, but got " + wr.ProtocolVersion.ToString()); result = TestResult.Fail; } Log.Comment("Set Invalid Version 3.7"); try { wr.ProtocolVersion = new Version(3, 7); Log.Exception("Expected Argument Exception"); result = TestResult.Fail; } catch (Exception ex) { if (!HttpTests.ValidateException(ex, typeof(ArgumentException))) result = TestResult.Fail; } } catch (Exception ex) { Log.Exception("Unexpected Exception", ex); result = TestResult.Fail; } return result; } [TestMethod] public TestResult SetHeadersAfterRequest() { TestResult result = TestResult.Pass; HttpWebRequest wr = (HttpWebRequest)WebRequest.Create("http://127.0.0.1:" + HttpTestServer.s_CurrentPort.ToString() + "/"); wr.UserAgent = ".Net Micro Framwork Device/4.0"; HttpTestServer server = new HttpTestServer("http", ref result) { RequestUri = wr.RequestUri, RequestHeaders = wr.Headers, ResponseString = "SetHeadersAfterRequest" }; try { // Setup server server.StartServer(); HttpWebResponse response = (HttpWebResponse)wr.GetResponse(); // Tests try { Log.Comment("ReadWriteTimeout"); wr.ReadWriteTimeout = 10; Log.Exception("[Client] Expected InvalidOperationException"); result = TestResult.Fail; } catch (Exception ex) { if (!HttpTests.ValidateException(ex, typeof(InvalidOperationException))) result = TestResult.Fail; } try { Log.Comment("ContentLength"); wr.ContentLength = 10; Log.Exception("[Client] Expected InvalidOperationException"); result = TestResult.Fail; } catch (Exception ex) { if (!HttpTests.ValidateException(ex, typeof(InvalidOperationException))) result = TestResult.Fail; } try { Log.Comment("Headers"); wr.Headers = new WebHeaderCollection(); Log.Exception("[Client] Expected InvalidOperationException"); result = TestResult.Fail; } catch (Exception ex) { if (!HttpTests.ValidateException(ex, typeof(InvalidOperationException))) result = TestResult.Fail; } try { Log.Comment("Proxy"); wr.Proxy = null; Log.Exception("[Client] Expected InvalidOperationException"); result = TestResult.Fail; } catch (Exception ex) { if (!HttpTests.ValidateException(ex, typeof(InvalidOperationException))) result = TestResult.Fail; } try { Log.Comment("SendChunked"); wr.SendChunked = true; Log.Exception("[Client] Expected InvalidOperationException"); result = TestResult.Fail; } catch (Exception ex) { if (!HttpTests.ValidateException(ex, typeof(InvalidOperationException))) result = TestResult.Fail; } } catch (Exception ex) { Log.Exception("[Client] Unexpected Exception", ex); result = TestResult.Fail; } finally { // Stop server server.StopServer(); } return result; } [TestMethod] public TestResult FunctionalChunkTests() { TestResult result = TestResult.Pass; HttpWebRequest wr = (HttpWebRequest)WebRequest.Create("http://127.0.0.1:" + HttpTestServer.s_CurrentPort.ToString() + "/"); wr.UserAgent = ".Net Micro Framwork Device/4.0"; wr.KeepAlive = true; HttpTestServer server = new HttpTestServer("http", ref result) { RequestUri = wr.RequestUri, RequestHeaders = wr.Headers, ResponseString = Utilities.GetRandomSafeString(5000), }; try { // Setup server server.StartServer(); Log.Comment("Send UnChunked"); wr.SendChunked = false; HttpWebResponse response = (HttpWebResponse)wr.GetResponse(); HttpTests.PrintHeaders("Client", response.Headers); using (Stream responseStream = response.GetResponseStream()) { if (responseStream != null) { string page = HttpTests.ReadStream("Client", responseStream); if (page != server.ResponseString) { result = TestResult.Fail; Log.Exception("[Client] Send UnChunked - Corrupt Page!"); Log.Exception("[Client] Expected: " + server.ResponseString); Log.Exception("[Client] Received: " + page); } } else { result = TestResult.Fail; Log.Exception("[Client] Expected stream, but got null"); } } Log.Comment("Send Chunked"); wr = (HttpWebRequest)WebRequest.Create("http://127.0.0.1:" + HttpTestServer.s_CurrentPort.ToString() + "/"); wr.UserAgent = ".Net Micro Framwork Device/4.0"; wr.SendChunked = true; server.SendChunked = true; server.RequestHeaders = wr.Headers; response = (HttpWebResponse)wr.GetResponse(); HttpTests.PrintHeaders("Client", response.Headers); using (Stream responseStream = response.GetResponseStream()) { if (responseStream != null) { string page = HttpTests.ReadStream("Client", responseStream); if (page != server.ResponseString) { result = TestResult.Fail; Log.Exception("[Client] Send Chunked - Corrupt Page!"); Log.Exception("[Client] Expected: " + server.ResponseString); Log.Exception("[Client] Received: " + page); } } else { result = TestResult.Fail; Log.Exception("[Client] Expected stream, but got null"); } } } catch (Exception ex) { Log.Exception("[Client] Unexpected Exception", ex); result = TestResult.Fail; } finally { // Stop server server.StopServer(); } return result; } [TestMethod] public TestResult Skeleton() { TestResult result = TestResult.Pass; try { } catch (Exception ex) { Log.Exception("Unexpected Exception", ex); result = TestResult.Fail; } return result; } #endregion Test Cases } } ================================================ FILE: Zelig/Zelig/Test/RunTime/NETMF/System/Http/HttpWebResponseTests.cs ================================================ //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // Copyright (c) Microsoft Corporation. All rights reserved. //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// using System; using System.Net; namespace Microsoft.Zelig.Test { public class HttpWebResponseTests : TestBase, ITestInterface { [SetUp] public InitializeResult Initialize() { Log.Comment("Adding set up for the tests."); // Add your functionality here. return InitializeResult.ReadyToGo; } [TearDown] public void CleanUp() { Log.Comment("Cleaning up after the tests."); // TODO: Add your clean up steps here. } public override TestResult Run( string[] args ) { return TestResult.Pass; } //--// //--// //--// [TestMethod] public TestResult NotImplemented() { // TODO: Add your tests here. return TestResult.Skip; } } } ================================================ FILE: Zelig/Zelig/Test/RunTime/NETMF/System/Http/Master.cs ================================================ /*--------------------------------------------------------------------- * Master.cs - file description * Main class, responsible for running all of the other *Tests.cs files * Version: 1.0 * Author: REDMOND\jamesweb * Created: 2/27/2009 10:20:51 AM * ---------------------------------------------------------------------*/ using System; using System.Net; using System.IO; using System.Text; namespace Microsoft.Zelig.Test { public class HttpTests { // manually set proxy server here - In future should get from config public static string Proxy = "itgproxy.redmond.corp.microsoft.com"; public static string MSUrl = "http://www.microsoft.com"; private static Decoder UTF8decoder = System.Text.Encoding.UTF8.GetDecoder(); //--// public static bool ValidateException(Exception ex, Type ExpectedException) { bool result = (ex.GetType() == ExpectedException); if (!result) Log.Exception("Expected exception type: " + ExpectedException.Name, ex); return result; } public static string ReadStream(string source, Stream Reader) { Reader.ReadTimeout = 1000; byte[] byteData = new byte[4096]; char[] charData = new char[4096]; string data = null; int bytesRead = 0; int totalBytes = 0; try { while ((bytesRead = Reader.Read(byteData, 0, byteData.Length)) > 0) { int byteUsed, charUsed; bool completed = false; totalBytes += bytesRead; UTF8decoder.Convert(byteData, 0, bytesRead, charData, 0, bytesRead, true, out byteUsed, out charUsed, out completed); data = data + new String(charData, 0, charUsed); Log.Comment("[" + source + "] Bytes Read Now: " + bytesRead + " Total: " + totalBytes); } } catch(System.Net.Sockets.SocketException se) { if (se.ErrorCode != (int)System.Net.Sockets.SocketError.TimedOut) { throw se; } } Log.Comment("[" + source + "] Total bytes in message body : " + totalBytes); Log.Comment("[" + source + "] Received: " + data); return data; } public static void PrintHeaders(string source, WebHeaderCollection headers) { Log.Comment("[" + source + "] Rcvd Headers:"); foreach (string header in headers.AllKeys) { Log.Comment("[" + source + "] " + header + ": " + headers[header]); } } } } ================================================ FILE: Zelig/Zelig/Test/RunTime/NETMF/System/Http/ProtocolViolationExceptionTests.cs ================================================ //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // Copyright (c) Microsoft Corporation. All rights reserved. //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// using System; using System.Net; namespace Microsoft.Zelig.Test { public class ProtocolViolationExceptionTests : TestBase, ITestInterface { [SetUp] public InitializeResult Initialize() { Log.Comment("Adding set up for the tests."); // Add your functionality here. return InitializeResult.ReadyToGo; } [TearDown] public void CleanUp() { Log.Comment("Cleaning up after the tests."); // TODO: Add your clean up steps here. } public override TestResult Run( string[] args ) { return TestResult.Pass; } //--// //--// //--// [TestMethod] public TestResult NotImplemented() { // TODO: Add your tests here. return TestResult.Skip; } } } ================================================ FILE: Zelig/Zelig/Test/RunTime/NETMF/System/Http/TestServer.cs ================================================ using System; using System.Net; using System.Threading; namespace Microsoft.Zelig.Test { public class HttpTestServer { private HttpListener listener; private TestResult result; private bool running = false; AutoResetEvent evtStarted = new AutoResetEvent(false); Thread server; public static int s_CurrentPort = 8080; public HttpTestServer(string prefix, ref TestResult Result) { listener = new HttpListener(prefix, s_CurrentPort); result = Result; } public HttpTestServer(string prefix, int Port, ref TestResult Result) { listener = new HttpListener(prefix, Port); result = Result; } public string ResponseString { get; set; } public bool SendChunked { get; set; } public Uri RequestUri { get; set; } public WebHeaderCollection RequestHeaders { get; set; } public void StartServer() { server = new Thread(new ThreadStart(RunServer)); server.Start(); if (!evtStarted.WaitOne(5000, false)) { s_CurrentPort++; throw new Exception("Unable to start server"); } } public void StopServer() { if (running) { running = false; listener.Abort(); server.Join(); } } private void RunServer() { try { running = true; listener.Start(); Log.Comment("[Server] Starting listener..."); evtStarted.Set(); while (running) { HttpListenerContext context = listener.GetContext(); if (context == null) continue; HttpListenerRequest request = context.Request; // request header validation if (this.RequestHeaders != null) { foreach (string header in this.RequestHeaders.AllKeys) { if (this.RequestHeaders[header] != request.Headers[header]) { this.result = TestResult.Fail; Log.Exception("[Server] Expected " + header + ":" + this.RequestHeaders[header] + ", but got " + header + ":" + request.Headers[header]); } } } HttpTests.PrintHeaders("Server", request.Headers); // BUGBUG: Check inbound stream once 54503 & 54507 are fixed //HttpTests.ReadStream("Client", request.InputStream); HttpListenerResponse response = context.Response; byte[] buffer = System.Text.Encoding.UTF8.GetBytes(this.ResponseString); response.Headers.Add("Server", ".Net Micro Framework Device/4.0"); response.SendChunked = this.SendChunked; if (!this.SendChunked) response.ContentLength64 = buffer.Length; response.OutputStream.Write(buffer, 0, buffer.Length); response.Close(); } listener.Stop(); } catch (Exception ex) { Log.Exception("[Server] Unexpected Server Exception", ex); } finally { if (listener.IsListening) listener.Abort(); running = false; } } } } ================================================ FILE: Zelig/Zelig/Test/RunTime/NETMF/System/Http/UriTests.cs ================================================ //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // Copyright (c) Microsoft Corporation. All rights reserved. //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// using System; namespace Microsoft.Zelig.Test { public class UriTests : TestBase, ITestInterface { Uri uri; UriProperties props; ParsedUri parsed; [SetUp] public InitializeResult Initialize() { Log.Comment("Adding set up for the tests."); // Add your functionality here. return InitializeResult.ReadyToGo; } [TearDown] public void CleanUp() { Log.Comment("Cleaning up after the tests."); // TODO: Add your clean up steps here. } public override TestResult Run( string[] args ) { return TestResult.Pass; } //--// //--// //--// #region helper functions private bool ValidUri(Uri uri, UriProperties props) { bool result = true; // AbsolutePath if (props.Path != null && uri.AbsolutePath != props.Path) { Log.Exception("Expected AbsolutePath: " + props.Path + ", but got: " + uri.AbsolutePath); result = false; } // AbsoluteUri if (uri.AbsoluteUri != props.AbsoluteUri) { Log.Exception("Expected AbsoluteUri: " + props.AbsoluteUri + ", but got: " + uri.AbsoluteUri); result = false; } // HostNameType if (uri.HostNameType != props.Type) { Log.Exception("Expected HostNameType: " + props.Type + ", but got: " + uri.HostNameType); result = false; } switch (uri.Scheme.ToLower()) { case "http": case "https": if (uri.Port != props.Port) { Log.Exception("Expected Port: " + props.Port + ", but got: " + uri.Port); result = false; } // Host if (uri.Host != props.Host) { Log.Exception("Expected Host: " + props.Host + ", but got: " + uri.Host); result = false; } break; default: // no validation break; } // Scheme if (uri.Scheme != props.Scheme) { Log.Exception("Expected Scheme: " + props.Scheme + ", but got: " + uri.Scheme); result = false; } return result; } #endregion Helper functions #region Test Cases [TestMethod] public TestResult InvalidConstructorTests() { TestResult result = TestResult.Pass; try { Log.Comment("null string constructor"); try { uri = new Uri(null); } catch (ArgumentNullException ex) { if (!HttpTests.ValidateException(ex, typeof(ArgumentNullException))) result = TestResult.Fail; } Log.Comment("no uri string"); try { uri = new Uri("foo"); } catch (ArgumentException ex) { if (!HttpTests.ValidateException(ex, typeof(ArgumentException))) result = TestResult.Fail; } Log.Comment("uri, no address"); try { uri = new Uri("http:"); } catch (ArgumentException ex) { if (!HttpTests.ValidateException(ex, typeof(ArgumentException))) result = TestResult.Fail; } Log.Comment("uri, starts with non-alpha"); try { uri = new Uri("1ttp://foo.com"); } catch (ArgumentException ex) { if (!HttpTests.ValidateException(ex, typeof(ArgumentException))) result = TestResult.Fail; } Log.Comment("uri, includes numeric"); try { uri = new Uri("h1tp://foo.com"); } catch (ArgumentException ex) { if (!HttpTests.ValidateException(ex, typeof(ArgumentException))) result = TestResult.Fail; } Log.Comment("uri, includes non-alpha"); try { uri = new Uri("h@tp://foo.com"); } catch (ArgumentException ex) { if (!HttpTests.ValidateException(ex, typeof(ArgumentException))) result = TestResult.Fail; } Log.Comment("No ABSPath port URI"); try { uri = new Uri(HttpTests.MSUrl + ":80"); } catch (ArgumentException ex) { if (!HttpTests.ValidateException(ex, typeof(ArgumentException))) result = TestResult.Fail; } Log.Comment("Empty string constructor"); try { uri = new Uri(""); } catch (ArgumentException ex) { if (!HttpTests.ValidateException(ex, typeof(ArgumentNullException))) result = TestResult.Fail; } } catch (Exception ex) { Log.Exception("Unexpected Exception", ex); result = TestResult.Fail; } return result; } [TestMethod] public TestResult ValidUri() { TestResult result = TestResult.Pass; try { Log.Comment("Microsoft URL"); props = new UriProperties("http", "www.microsoft.com"); uri = new Uri(props.OriginalUri); if (!ValidUri(uri, props)) result = TestResult.Fail; Log.Comment("Alternate http port URL"); props = new UriProperties("http", "www.microsoft.com") { Port = 1080, Path = "/" //Need to remove later. This seems like a bug to require it. }; uri = new Uri(props.OriginalUri); if (!ValidUri(uri, props)) result = TestResult.Fail; Log.Comment("URL with content"); props = new UriProperties("http", "www.microsoft.com") { Path = "/en/us/default.aspx" }; uri = new Uri(props.OriginalUri); if (!ValidUri(uri, props)) result = TestResult.Fail; } catch (Exception ex) { Log.Exception("Unexpected Exception", ex); result = TestResult.Fail; } return result; } [TestMethod] public TestResult ValidURN() { TestResult result = TestResult.Pass; try { Log.Comment("isbn"); props = new UriProperties("urn", "isbn:0451450523"); uri = new Uri(props.OriginalUri); if (!ValidUri(uri, props)) result = TestResult.Fail; Log.Comment("isan"); props = new UriProperties("urn", "isan:0000-0000-9E59-0000-O-0000-0000-2"); uri = new Uri(props.OriginalUri); if (!ValidUri(uri, props)) result = TestResult.Fail; Log.Comment("issn"); props = new UriProperties("urn", "issn:0167-6423"); uri = new Uri(props.OriginalUri); if (!ValidUri(uri, props)) result = TestResult.Fail; Log.Comment("ietf"); props = new UriProperties("urn", "ietf:rfc:2648"); uri = new Uri(props.OriginalUri); if (!ValidUri(uri, props)) result = TestResult.Fail; Log.Comment("mpeg"); props = new UriProperties("urn", "mpeg:mpeg7:schema:2001"); uri = new Uri(props.OriginalUri); if (!ValidUri(uri, props)) result = TestResult.Fail; Log.Comment("oid"); props = new UriProperties("urn", "oid:2.216.840"); uri = new Uri(props.OriginalUri); if (!ValidUri(uri, props)) result = TestResult.Fail; Log.Comment("urn:uuid"); props = new UriProperties("urn", "uuid:6e8bc430-9c3a-11d9-9669-0800200c9a66"); uri = new Uri(props.OriginalUri); if (!ValidUri(uri, props)) result = TestResult.Fail; Log.Comment("uuid"); props = new UriProperties("uuid", "6e8bc430-9c3a-11d9-9669-0800200c9a66"); uri = new Uri(props.OriginalUri); if (!ValidUri(uri, props)) result = TestResult.Fail; Log.Comment("uci"); props = new UriProperties("urn", "uci:I001+SBSi-B10000083052"); uri = new Uri(props.OriginalUri); if (!ValidUri(uri, props)) result = TestResult.Fail; } catch (Exception ex) { Log.Exception("Unexpected Exception", ex); result = TestResult.Fail; } return result; } [TestMethod] public TestResult AdditionalValidUri() { TestResult result = TestResult.Pass; try { Log.Comment("iris.beep"); props = new UriProperties("iris.beep", "bop") { Type = UriHostNameType.Unknown }; uri = new Uri(props.OriginalUri); if (!ValidUri(uri, props)) result = TestResult.Fail; Log.Comment("Microsoft Secure URL"); props = new UriProperties("https", "www.microsoft.com"); uri = new Uri(props.OriginalUri); if (!ValidUri(uri, props)) result = TestResult.Fail; Log.Comment("Alternate https port URL"); props = new UriProperties("https", "www.microsoft.com") { Port = 1443 }; uri = new Uri(props.OriginalUri); if (!ValidUri(uri, props)) result = TestResult.Fail; Log.Comment("H323 uri"); props = new UriProperties("h323", "user@host:54"); uri = new Uri(props.OriginalUri); if (!ValidUri(uri, props)) result = TestResult.Fail; Log.Comment("FTP URI"); uri = new Uri("ftp://ftp.microsoft.com/file.txt"); parsed = new ParsedUri("ftp", "ftp.microsoft.com", UriHostNameType.Dns, 21, "/file.txt", "ftp://ftp.microsoft.com/file.txt"); if (!parsed.ValidUri(uri)) result = TestResult.Fail; Log.Comment("Unix style file"); uri = new Uri("file:///etc/hosts"); parsed = new ParsedUri("file", string.Empty, UriHostNameType.Basic, -1, "/etc/hosts", "file:///etc/hosts"); if (!parsed.ValidUri(uri)) result = TestResult.Fail; Log.Comment("Windows share style file"); uri = new Uri("file:///\\\\server\\folder\\file.txt"); parsed = new ParsedUri("file", "server", UriHostNameType.Dns, -1, "/folder/file.txt", "file://server/folder/file.txt"); if (!parsed.ValidUri(uri)) result = TestResult.Fail; Log.Comment("Windows drive style file"); uri = new Uri("file:///c:\\rbllog"); parsed = new ParsedUri("file", string.Empty, UriHostNameType.Basic, -1, "c:/rbllog", "file:///c:/rbllog"); if (!parsed.ValidUri(uri)) result = TestResult.Fail; } catch (Exception ex) { Log.Exception("Unexpected Exception - these cases currently all fail", ex); result = TestResult.Fail; } return result; } [TestMethod] public TestResult RelativeURI() { TestResult result = TestResult.Pass; try { Log.Comment("relative url"); uri = new Uri("/doc/text.html", UriKind.Relative); Log.Comment("absolute url"); props = new UriProperties("https", "www.microsoft.com") { Path = "/doc/text.html", Port = 1443 }; uri = new Uri(props.OriginalUri, UriKind.Absolute); if (!ValidUri(uri, props)) result = TestResult.Fail; Log.Comment("RelativeOrAbsolute"); try { uri = new Uri("/doc/text.html", UriKind.RelativeOrAbsolute); } catch (ArgumentException ex) { if (!HttpTests.ValidateException(ex, typeof(ArgumentException))) result = TestResult.Fail; } } catch (Exception ex) { Log.Exception("Unexpected Exception", ex); result = TestResult.Fail; } return result; } [TestMethod] public TestResult MoreSchemes() { TestResult result = TestResult.Pass; var sUris = new string[] { "ws://ws.pusherapp.com:80/app/?client=js&version=1.9.3&protocol=5", "\tftp://abc.com ", "ldap://[2001:db8::7]/c=GB?objectClass?one", "mailto:John.Doe@example.com", "mailto://abc/d", "news:comp.infosystems.www.servers.unix", "tel:+1-816-555-1212", "telnet://192.0.2.16:80/", "h323:abc", "h323://abc/d" }; var parseds = new ParsedUri[] { new ParsedUri("ws", "ws.pusherapp.com", UriHostNameType.Dns, 80, "/app/?client=js&version=1.9.3&protocol=5", "ws://ws.pusherapp.com/app/?client=js&version=1.9.3&protocol=5"), new ParsedUri("ftp", "abc.com", UriHostNameType.Dns, 21, "/", "ftp://abc.com/"), new ParsedUri("ldap", "[2001:db8::7]", UriHostNameType.IPv6, 389, "/c=GB?objectClass?one", "ldap://[2001:db8::7]/c=GB?objectClass?one"), new ParsedUri("mailto", "John.Doe@example.com", UriHostNameType.Dns, 25, string.Empty, "mailto:John.Doe@example.com"), new ParsedUri("mailto", string.Empty, UriHostNameType.Basic, 25, "//abc/d", "mailto://abc/d"), new ParsedUri("news", string.Empty, UriHostNameType.Unknown, -1, "comp.infosystems.www.servers.unix", "news:comp.infosystems.www.servers.unix"), new ParsedUri("tel", string.Empty, UriHostNameType.Unknown, -1, "+1-816-555-1212", "tel:+1-816-555-1212"), new ParsedUri("telnet", "192.0.2.16", UriHostNameType.IPv4, 80, "/", "telnet://192.0.2.16:80/"), new ParsedUri("h323", string.Empty, UriHostNameType.Unknown, -1, "abc", "h323:abc"), new ParsedUri("h323", "abc", UriHostNameType.Dns, -1, "/d", "h323://abc/d") }; for (int i = 0; i < sUris.Length; i++) { uri = new Uri(sUris[i]); if (!parseds[i].ValidUri(uri)) { result = TestResult.Fail; } } return result; } [TestMethod] public TestResult FileScheme() { TestResult result = TestResult.Pass; var sUris = new string[] { "file://", "file:///", "file:////", "file://c", "file:///c", "file:////c", }; var parseds = new ParsedUri[] { new ParsedUri("file", string.Empty, UriHostNameType.Basic, -1, "/", "file:///"), new ParsedUri("file", string.Empty, UriHostNameType.Basic, -1, "/", "file:///"), new ParsedUri("file", string.Empty, UriHostNameType.Basic, -1, "//", "file:////"), new ParsedUri("file", "c", UriHostNameType.Dns, -1, "/", "file://c/"), new ParsedUri("file", string.Empty, UriHostNameType.Basic, -1, "/c", "file:///c"), new ParsedUri("file", "c", UriHostNameType.Dns, -1, "/", "file://c/"), }; for (int i = 0; i < sUris.Length; i++) { uri = new Uri(sUris[i]); if (!parseds[i].ValidUri(uri)) { result = TestResult.Fail; } } return result; } [TestMethod] public TestResult Exceptions() { TestResult result = TestResult.Pass; var sUris = new string[] { "file:///c:", "http:abc/d/", "file:/server" }; for (int i = 0; i < sUris.Length; i++) { try { uri = new Uri(sUris[i]); result = TestResult.Fail; } catch (ArgumentException) { } } return result; } #endregion Test Cases } #region helper class public class UriProperties { private string _scheme; private string _host; private bool _portSet = false; private int _port; private UriHostNameType _type = UriHostNameType.Unknown; public UriProperties(string Scheme, string Host) { // Minimal required properties _scheme = Scheme; _host = Host; } public string Scheme { get { return _scheme; } } public string Host { set { _host = value; } get { return _host; } } public int Port { get { return _port; } set { _portSet = true; _port = value; } } public bool PortSet { get { return _portSet; } } public string Path { get; set; } public UriHostNameType Type { get { return _type; } set { _type = value; } } public string AbsoluteUri { get { string uri = OriginalUri; // for http[s] add trailing / if no path if (Path == null && _scheme.ToLower().IndexOf("http") == 0 && uri[uri.Length - 1] != '/') { uri += "/"; } return uri; } } public string OriginalUri { get { string uri = _scheme; int defaultPort = 0; switch (_scheme.ToLower()) { case "http": _type = UriHostNameType.Dns; defaultPort = 80; uri += "://" + _host; break; case "https": _type = UriHostNameType.Dns; defaultPort = 443; uri += "://" + _host; break; default: // No hosts, so move _host to Path if (_host != "") { Path = _host; _host = ""; } uri += ":" + _host; break; } if (_portSet) uri += ":" + Port; else _port = defaultPort; if (Path != null) uri += Path; return uri; } } } class ParsedUri { public string Scheme { get; set; } public string Host { get; set; } public UriHostNameType HostNameType { get; set; } public int Port { get; set; } public string AbsolutePath { get; set; } public string AbsoluteUri { get; set; } public ParsedUri(string _scheme, string _host, UriHostNameType _hostNameType, int _port, string _absolutePath, string _absoluteUri) { Scheme = _scheme; Host = _host; HostNameType = _hostNameType; Port = _port; AbsolutePath = _absolutePath; AbsoluteUri = _absoluteUri; } public bool ValidUri(Uri uri) { bool result = true; // Scheme if (uri.Scheme != Scheme) { Log.Exception("Expected Scheme: " + Scheme + ", but got: " + uri.Scheme); result = false; } // Host if (uri.Host != Host) { Log.Exception("Expected Host: " + Host + ", but got: " + uri.Host); result = false; } // Port if (uri.Port != Port) { Log.Exception("Expected Port: " + Port.ToString() + ", but got: " + uri.Port.ToString()); result = false; } // AbsolutePath if (uri.AbsolutePath != AbsolutePath) { Log.Exception("Expected AbsolutePath: " + AbsolutePath + ", but got: " + uri.AbsolutePath); result = false; } // AbsoluteUri if (uri.AbsoluteUri != AbsoluteUri) { Log.Exception("Expected AbsoluteUri: " + AbsoluteUri + ", but got: " + uri.AbsoluteUri); result = false; } // HostNameType if (uri.HostNameType != HostNameType) { Log.Exception("Expected HostNameType: " + HostNameType + ", but got: " + uri.HostNameType); result = false; } return result; } } #endregion helper class } ================================================ FILE: Zelig/Zelig/Test/RunTime/NETMF/System/Http/WebExceptionTests.cs ================================================ //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // Copyright (c) Microsoft Corporation. All rights reserved. //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// using Microsoft.Llilum.Lwip; using System; using System.Net; namespace Microsoft.Zelig.Test { public class WebExceptionTests : TestBase, ITestInterface { [SetUp] public InitializeResult Initialize() { Log.Comment("Adding set up for the tests."); try { NetworkInterface[] nis = NetworkInterface.GetAllNetworkInterfaces(); } catch { return InitializeResult.Skip; } return InitializeResult.ReadyToGo; } [TearDown] public void CleanUp() { Log.Comment("Cleaning up after the tests."); // TODO: Add your clean up steps here. } public override TestResult Run( string[] args ) { return TestResult.Pass; } //--// //--// //--// #region Helper methods private TestResult VerifyStream(HttpWebResponse response, HttpServer server) { TestResult result = TestResult.Pass; using (System.IO.Stream responseStream = response.GetResponseStream()) { if (responseStream != null) { string page = HttpTests.ReadStream("Client", responseStream); if (page != server.ResponseString) { Log.Exception("Expect " + server.ResponseString + " but get " + responseStream.ToString()); result = TestResult.Fail; } } else { result = TestResult.Fail; Log.Exception("[Client] Expected stream, but got null"); } } return result; } #endregion Helper methods #region Test [TestMethod] public TestResult TestWebExceptionHTTP1_1_ConnectionClosed() { TestResult result = TestResult.Pass; HttpWebRequest wr = (HttpWebRequest)WebRequest.Create("http://127.0.0.1:" + HttpServer.s_CurrentPort.ToString() + "/webexception/ConnClose.html"); //expect ConnectionClosed wr.UserAgent = ".Net Micro Framwork Device/4.0"; wr.Method = "HEAD"; Log.Comment("Initial version: " + wr.ProtocolVersion); //Default version is 1.1 Log.Comment("Set Version 1.1"); wr.ProtocolVersion = new Version(1, 1); HttpServer server = new HttpServer("http", ref result) { RequestUri = wr.RequestUri, RequestHeaders = wr.Headers, ResponseString = "" }; try { // Setup server server.StartServer(); HttpWebResponse response = (HttpWebResponse)wr.GetResponse(); Log.Comment("Expect ConnectionClosed"); VerifyStream(response, server); response.Close(); } catch (Exception ex) { Log.Exception("Exception caught: ", ex); } finally { //Stop server server.StopServer(); } return result; } [TestMethod] public TestResult TestWebExceptionHTTP1_1_KeepAliveFailure() { TestResult result = TestResult.Pass; HttpWebRequest wr = (HttpWebRequest)WebRequest.Create("http://127.0.0.1:" + HttpServer.s_CurrentPort.ToString() + "/webexception/KeepAliveFailure.html"); //expect KeepAliveFailure wr.UserAgent = ".Net Micro Framwork Device/4.0"; wr.Method = "HEAD"; Log.Comment("Initial version: " + wr.ProtocolVersion); //Default version is 1.1 Log.Comment("Set Version 1.1"); wr.ProtocolVersion = new Version(1, 1); HttpServer server = new HttpServer("http", ref result) { RequestUri = wr.RequestUri, RequestHeaders = wr.Headers, ResponseString = "" }; try { // Setup server server.StartServer(); HttpWebResponse response = (HttpWebResponse)wr.GetResponse(); Log.Comment("Expect KeepAliveFailure"); VerifyStream(response, server); response.Close(); } catch (Exception ex) { Log.Exception("Exception caught: ", ex); } finally { //Stop server server.StopServer(); } return result; } [TestMethod] public TestResult TestWebExceptionHTTP1_1_Pending() { TestResult result = TestResult.Pass; HttpWebRequest wr = (HttpWebRequest)WebRequest.Create("http://127.0.0.1:" + HttpServer.s_CurrentPort.ToString() + "/webexception/Pending.html"); //expect Pending wr.UserAgent = ".Net Micro Framwork Device/4.0"; wr.Method = "HEAD"; Log.Comment("Initial version: " + wr.ProtocolVersion); //Default version is 1.1 Log.Comment("Set Version 1.1"); wr.ProtocolVersion = new Version(1, 1); HttpServer server = new HttpServer("http", ref result) { RequestUri = wr.RequestUri, RequestHeaders = wr.Headers, ResponseString = "" }; try { // Setup server server.StartServer(); HttpWebResponse response = (HttpWebResponse)wr.GetResponse(); Log.Comment("Expect Pending"); VerifyStream(response, server); response.Close(); } catch (Exception ex) { Log.Exception("Exception caught: ", ex); } finally { //Stop server server.StopServer(); } return result; } [TestMethod] public TestResult TestWebExceptionHTTP1_1_PipelineFailure() { TestResult result = TestResult.Pass; HttpWebRequest wr = (HttpWebRequest)WebRequest.Create("http://127.0.0.1:" + HttpServer.s_CurrentPort.ToString() + "/webexception/PipelineFailure.html"); //expect PipelineFailure wr.UserAgent = ".Net Micro Framwork Device/4.0"; wr.Method = "HEAD"; Log.Comment("Initial version: " + wr.ProtocolVersion); //Default version is 1.1 Log.Comment("Set Version 1.1"); wr.ProtocolVersion = new Version(1, 1); HttpServer server = new HttpServer("http", ref result) { RequestUri = wr.RequestUri, RequestHeaders = wr.Headers, ResponseString = "" }; try { // Setup server server.StartServer(); HttpWebResponse response = (HttpWebResponse)wr.GetResponse(); Log.Comment("Expect PipelineFailure"); VerifyStream(response, server); response.Close(); } catch (Exception ex) { Log.Exception("Exception caught: ", ex); } finally { //Stop server server.StopServer(); } return result; } [TestMethod] public TestResult TestWebExceptionHTTP1_1_ProxyNameResolutionFailure() { TestResult result = TestResult.Pass; HttpWebRequest wr = (HttpWebRequest)WebRequest.Create("http://127.0.0.1:" + HttpServer.s_CurrentPort.ToString() + "/webexception/ProxyNameResolutionFailure.html"); //expect ProxyNameResolutionFailure wr.UserAgent = ".Net Micro Framwork Device/4.0"; wr.Method = "HEAD"; Log.Comment("Initial version: " + wr.ProtocolVersion); //Default version is 1.1 Log.Comment("Set Version 1.1"); wr.ProtocolVersion = new Version(1, 1); HttpServer server = new HttpServer("http", ref result) { RequestUri = wr.RequestUri, RequestHeaders = wr.Headers, ResponseString = "" }; try { // Setup server server.StartServer(); HttpWebResponse response = (HttpWebResponse)wr.GetResponse(); Log.Comment("Expect ProxyNameResolutionFailure"); VerifyStream(response, server); response.Close(); } catch (Exception ex) { Log.Exception("Exception caught: ", ex); } finally { //Stop server server.StopServer(); } return result; } [TestMethod] public TestResult TestWebExceptionHTTP1_1_ReceiveFailure() { TestResult result = TestResult.Pass; HttpWebRequest wr = (HttpWebRequest)WebRequest.Create("http://127.0.0.1:" + HttpServer.s_CurrentPort.ToString() + "/webexception/ReceiveFailure.html"); //expect ReceiveFailure wr.UserAgent = ".Net Micro Framwork Device/4.0"; wr.Method = "HEAD"; Log.Comment("Initial version: " + wr.ProtocolVersion); //Default version is 1.1 Log.Comment("Set Version 1.1"); wr.ProtocolVersion = new Version(1, 1); HttpServer server = new HttpServer("http", ref result) { RequestUri = wr.RequestUri, RequestHeaders = wr.Headers, ResponseString = "" }; try { // Setup server server.StartServer(); HttpWebResponse response = (HttpWebResponse)wr.GetResponse(); Log.Comment("Expect ReceiveFailure"); VerifyStream(response, server); response.Close(); } catch (Exception ex) { Log.Exception("Exception caught: ", ex); } finally { //Stop server server.StopServer(); } return result; } [TestMethod] public TestResult TestWebExceptionHTTP1_1_RequestCanceled() { TestResult result = TestResult.Pass; HttpWebRequest wr = (HttpWebRequest)WebRequest.Create("http://127.0.0.1:" + HttpServer.s_CurrentPort.ToString() + "/webexception/RequestCanceled.html"); //expect RequestCanceled wr.UserAgent = ".Net Micro Framwork Device/4.0"; wr.Method = "HEAD"; Log.Comment("Initial version: " + wr.ProtocolVersion); //Default version is 1.1 Log.Comment("Set Version 1.1"); wr.ProtocolVersion = new Version(1, 1); HttpServer server = new HttpServer("http", ref result) { RequestUri = wr.RequestUri, RequestHeaders = wr.Headers, ResponseString = "" }; try { // Setup server server.StartServer(); HttpWebResponse response = (HttpWebResponse)wr.GetResponse(); Log.Comment("Expect RequestCanceled"); VerifyStream(response, server); response.Close(); } catch (Exception ex) { Log.Exception("Exception caught: ", ex); } finally { //Stop server server.StopServer(); } return result; } [TestMethod] public TestResult TestWebExceptionHTTP1_1_SecureChannelFailure() { TestResult result = TestResult.Pass; HttpWebRequest wr = (HttpWebRequest)WebRequest.Create("http://127.0.0.1:" + HttpServer.s_CurrentPort.ToString() + "/webexception/SecureChannelFailure.html"); //expect SecureChannelFailure wr.UserAgent = ".Net Micro Framwork Device/4.0"; wr.Method = "HEAD"; Log.Comment("Initial version: " + wr.ProtocolVersion); //Default version is 1.1 Log.Comment("Set Version 1.1"); wr.ProtocolVersion = new Version(1, 1); HttpServer server = new HttpServer("http", ref result) { RequestUri = wr.RequestUri, RequestHeaders = wr.Headers, ResponseString = "" }; try { // Setup server server.StartServer(); HttpWebResponse response = (HttpWebResponse)wr.GetResponse(); Log.Comment("Expect SecureChannelFailure"); VerifyStream(response, server); response.Close(); } catch (Exception ex) { Log.Exception("Exception caught: ", ex); } finally { //Stop server server.StopServer(); } return result; } [TestMethod] public TestResult TestWebExceptionHTTP1_1_SendFailure() { TestResult result = TestResult.Pass; HttpWebRequest wr = (HttpWebRequest)WebRequest.Create("http://127.0.0.1:" + HttpServer.s_CurrentPort.ToString() + "/webexception/SendFailure.html"); //expect SendFailure wr.UserAgent = ".Net Micro Framwork Device/4.0"; wr.Method = "HEAD"; Log.Comment("Initial version: " + wr.ProtocolVersion); //Default version is 1.1 Log.Comment("Set Version 1.1"); wr.ProtocolVersion = new Version(1, 1); HttpServer server = new HttpServer("http", ref result) { RequestUri = wr.RequestUri, RequestHeaders = wr.Headers, ResponseString = "" }; try { // Setup server server.StartServer(); HttpWebResponse response = (HttpWebResponse)wr.GetResponse(); Log.Comment("Expect SendFailure"); VerifyStream(response, server); response.Close(); } catch (Exception ex) { Log.Exception("Exception caught: ", ex); } finally { //Stop server server.StopServer(); } return result; } [TestMethod] public TestResult TestWebExceptionHTTP1_1_Success() { TestResult result = TestResult.Pass; HttpWebRequest wr = (HttpWebRequest)WebRequest.Create("http://127.0.0.1:" + HttpServer.s_CurrentPort.ToString() + "/webexception/Success.html"); //expect Success wr.UserAgent = ".Net Micro Framwork Device/4.0"; wr.Method = "HEAD"; Log.Comment("Initial version: " + wr.ProtocolVersion); //Default version is 1.1 Log.Comment("Set Version 1.1"); wr.ProtocolVersion = new Version(1, 1); HttpServer server = new HttpServer("http", ref result) { RequestUri = wr.RequestUri, RequestHeaders = wr.Headers, ResponseString = "" }; try { // Setup server server.StartServer(); HttpWebResponse response = (HttpWebResponse)wr.GetResponse(); Log.Comment("Expect Success"); VerifyStream(response, server); response.Close(); } catch (Exception ex) { Log.Exception("Exception caught: ", ex); } finally { //Stop server server.StopServer(); } return result; } [TestMethod] public TestResult TestWebExceptionHTTP1_1_Timeout() { TestResult result = TestResult.Pass; HttpWebRequest wr = (HttpWebRequest)WebRequest.Create("http://127.0.0.1:" + HttpServer.s_CurrentPort.ToString() + "/webexception/Timeout.html"); //expect Timeout wr.UserAgent = ".Net Micro Framwork Device/4.0"; wr.Method = "HEAD"; Log.Comment("Initial version: " + wr.ProtocolVersion); //Default version is 1.1 Log.Comment("Set Version 1.1"); wr.ProtocolVersion = new Version(1, 1); HttpServer server = new HttpServer("http", ref result) { RequestUri = wr.RequestUri, RequestHeaders = wr.Headers, ResponseString = "" }; try { // Setup server server.StartServer(); HttpWebResponse response = (HttpWebResponse)wr.GetResponse(); Log.Comment("Expect Timeout"); VerifyStream(response, server); response.Close(); } catch (Exception ex) { Log.Exception("Exception caught: ", ex); } finally { //Stop server server.StopServer(); } return result; } [TestMethod] public TestResult TestWebExceptionHTTP1_1_TrustFailure() { TestResult result = TestResult.Pass; HttpWebRequest wr = (HttpWebRequest)WebRequest.Create("http://127.0.0.1:" + HttpServer.s_CurrentPort.ToString() + "/webexception/TrustFailure.html"); //expect TrustFailure wr.UserAgent = ".Net Micro Framwork Device/4.0"; wr.Method = "HEAD"; Log.Comment("Initial version: " + wr.ProtocolVersion); //Default version is 1.1 Log.Comment("Set Version 1.1"); wr.ProtocolVersion = new Version(1, 1); HttpServer server = new HttpServer("http", ref result) { RequestUri = wr.RequestUri, RequestHeaders = wr.Headers, ResponseString = "" }; try { // Setup server server.StartServer(); HttpWebResponse response = (HttpWebResponse)wr.GetResponse(); Log.Comment("Expect TrustFailure"); VerifyStream(response, server); response.Close(); } catch (Exception ex) { Log.Exception("Exception caught: ", ex); } finally { //Stop server server.StopServer(); } return result; } [TestMethod] public TestResult TestWebExceptionHTTP1_1_ConnectFailure() { TestResult result = TestResult.Pass; HttpWebRequest wr = (HttpWebRequest)WebRequest.Create("http://127.0.0.1:" + HttpServer.s_CurrentPort.ToString() + "/webexception/ConnectFailure.html"); //expect ConnectFailure wr.UserAgent = ".Net Micro Framwork Device/4.0"; wr.Method = "HEAD"; Log.Comment("Initial version: " + wr.ProtocolVersion); //Default version is 1.1 Log.Comment("Set Version 1.1"); wr.ProtocolVersion = new Version(1, 1); HttpServer server = new HttpServer("http", ref result) { RequestUri = wr.RequestUri, RequestHeaders = wr.Headers, ResponseString = "" }; try { // Setup server server.StartServer(); HttpWebResponse response = (HttpWebResponse)wr.GetResponse(); Log.Comment("Expect ConnectFailure"); VerifyStream(response, server); response.Close(); } catch (Exception ex) { Log.Exception("Exception caught: ", ex); } finally { //Stop server server.StopServer(); } return result; } [TestMethod] public TestResult TestWebExceptionHTTP1_1_NameResolutionFailure() { TestResult result = TestResult.Pass; HttpWebRequest wr = (HttpWebRequest)WebRequest.Create("http://127.0.0.1:" + HttpServer.s_CurrentPort.ToString() + "/webexception/NameResolutionFailure.html"); //expect NameResolutionFailure wr.UserAgent = ".Net Micro Framwork Device/4.0"; wr.Method = "HEAD"; Log.Comment("Initial version: " + wr.ProtocolVersion); //Default version is 1.1 Log.Comment("Set Version 1.1"); wr.ProtocolVersion = new Version(1, 1); HttpServer server = new HttpServer("http", ref result) { RequestUri = wr.RequestUri, RequestHeaders = wr.Headers, ResponseString = "" }; try { // Setup server server.StartServer(); HttpWebResponse response = (HttpWebResponse)wr.GetResponse(); Log.Comment("Expect NameResolutionFailure"); VerifyStream(response, server); response.Close(); } catch (Exception ex) { Log.Exception("Exception caught: ", ex); } finally { //Stop server server.StopServer(); } return result; } [TestMethod] public TestResult TestWebExceptionHTTP1_1_ProtocolError() { TestResult result = TestResult.Pass; HttpWebRequest wr = (HttpWebRequest)WebRequest.Create("http://127.0.0.1:" + HttpServer.s_CurrentPort.ToString() + "/webexception/ProtocolError.html"); //expect ProtocolError wr.UserAgent = ".Net Micro Framwork Device/4.0"; wr.Method = "HEAD"; Log.Comment("Initial version: " + wr.ProtocolVersion); //Default version is 1.1 Log.Comment("Set Version 1.1"); wr.ProtocolVersion = new Version(1, 1); HttpServer server = new HttpServer("http", ref result) { RequestUri = wr.RequestUri, RequestHeaders = wr.Headers, ResponseString = "" }; try { // Setup server server.StartServer(); HttpWebResponse response = (HttpWebResponse)wr.GetResponse(); Log.Comment("Expect ProtocolError"); VerifyStream(response, server); response.Close(); } catch (Exception ex) { Log.Exception("Exception caught: ", ex); } finally { //Stop server server.StopServer(); } return result; } [TestMethod] public TestResult TestWebExceptionHTTP1_1_ServerProtocolViolation() { TestResult result = TestResult.Pass; HttpWebRequest wr = (HttpWebRequest)WebRequest.Create("http://127.0.0.1:" + HttpServer.s_CurrentPort.ToString() + "/webexception/ServerProtocolViolation.html"); //expect ServerProtocolViolation wr.UserAgent = ".Net Micro Framwork Device/4.0"; wr.Method = "HEAD"; Log.Comment("Initial version: " + wr.ProtocolVersion); //Default version is 1.1 Log.Comment("Set Version 1.1"); wr.ProtocolVersion = new Version(1, 1); HttpServer server = new HttpServer("http", ref result) { RequestUri = wr.RequestUri, RequestHeaders = wr.Headers, ResponseString = "" }; try { // Setup server server.StartServer(); HttpWebResponse response = (HttpWebResponse)wr.GetResponse(); Log.Comment("Expect ServerProtocolViolation"); VerifyStream(response, server); response.Close(); } catch (Exception ex) { Log.Exception("Exception caught: ", ex); } finally { //Stop server server.StopServer(); } return result; } #endregion Test } } ================================================ FILE: Zelig/Zelig/Test/RunTime/NETMF/System/Http/WebHeaderCollectionTests.cs ================================================ //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // Copyright (c) Microsoft Corporation. All rights reserved. //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// using System; using System.Net; namespace Microsoft.Zelig.Test { public class WebHeaderCollectionTests : TestBase, ITestInterface { [SetUp] public InitializeResult Initialize() { Log.Comment("Adding set up for the tests."); // Add your functionality here. return InitializeResult.ReadyToGo; } [TearDown] public void CleanUp() { Log.Comment("Cleaning up after the tests."); // TODO: Add your clean up steps here. } public override TestResult Run( string[] args ) { return TestResult.Pass; } //--// //--// //--// #region Helper methods private TestResult VerifyHttpHeaders(System.Net.WebHeaderCollection wrc, System.Net.WebHeaderCollection wrs) { TestResult result = TestResult.Pass; try { string[] headers = wrc.AllKeys; string sValue = String.Empty; for (int i = 0; i < wrc.Count; i++) { sValue = wrc[headers[i]]; if (sValue != wrs[headers[i]]) { Log.Exception(headers[i] + "property value is incorrect."); result = TestResult.Fail; } } } catch (Exception ex) { if (!HttpTests.ValidateException(ex, typeof(InvalidOperationException))) result = TestResult.Fail; } return result; } private bool VerifyAddHeaderIsIllegal(WebHeaderCollection wrc, string header, string content, Type exceptionType) { bool res = true; try { Log.Comment("Set Headers Properties for header: '" + header + "', with value: '" + content + "'"); if (null == content) wrc.Add(header); else wrc.Add(header, content); Log.Comment("Illegal header was set: Failed."); res = false; } catch (Exception ex) { if (!HttpTests.ValidateException(ex, exceptionType)) { res = false; } } return res; } private bool VerifyHeaderIsLegal(WebHeaderCollection wrc, string header, string content, Type exceptionType) { bool res = true; try { Log.Comment("Set Headers Properties for header: '" + header + "', with value: '" + content + "'"); if(null == content) wrc.Add(header); else wrc.Add(header, content); } catch (Exception ex) { Log.Exception("Exception thrown for legal header: '" + header + "'", ex); res = false; } return res; } #endregion Helper methods #region Test [TestMethod] public TestResult TestWebHeaderCollectionAddIllegal() { TestResult result = TestResult.Pass; HttpWebRequest wr = (HttpWebRequest)WebRequest.Create("http://127.0.0.1:" + HttpServer.s_CurrentPort.ToString() + "/"); //expect 200 - OK wr.UserAgent = ".Net Micro Framwork Device/4.0"; Log.Comment("Initial version: " + wr.ProtocolVersion); //Default version is 1.1 Log.Comment("Set Version 1.1"); wr.ProtocolVersion = new Version(1, 1); try { WebHeaderCollection wrc = wr.Headers; //Attempt to add Restricted header if (!VerifyAddHeaderIsIllegal(wrc, HttpKnownHeaderNames.Accept, null, typeof(ArgumentException))) result = TestResult.Fail; if (!VerifyAddHeaderIsIllegal(wrc, HttpKnownHeaderNames.Connection, null, typeof(ArgumentException))) result = TestResult.Fail; if (!VerifyAddHeaderIsIllegal(wrc, HttpKnownHeaderNames.ContentLength, null, typeof(ArgumentException))) result = TestResult.Fail; if (!VerifyAddHeaderIsIllegal(wrc, HttpKnownHeaderNames.ContentType, null, typeof(ArgumentException))) result = TestResult.Fail; if (!VerifyAddHeaderIsIllegal(wrc, HttpKnownHeaderNames.Date, null, typeof(ArgumentException))) result = TestResult.Fail; if (!VerifyAddHeaderIsIllegal(wrc, HttpKnownHeaderNames.Expect, null, typeof(ArgumentException))) result = TestResult.Fail; if (!VerifyAddHeaderIsIllegal(wrc, HttpKnownHeaderNames.Host, null, typeof(ArgumentException))) result = TestResult.Fail; if (!VerifyAddHeaderIsIllegal(wrc, HttpKnownHeaderNames.IfModifiedSince, null, typeof(ArgumentException))) result = TestResult.Fail; if (!VerifyAddHeaderIsIllegal(wrc, HttpKnownHeaderNames.Range, null, typeof(ArgumentException))) result = TestResult.Fail; if (!VerifyAddHeaderIsIllegal(wrc, HttpKnownHeaderNames.Referer, null, typeof(ArgumentException))) result = TestResult.Fail; if (!VerifyAddHeaderIsIllegal(wrc, HttpKnownHeaderNames.TransferEncoding, null, typeof(ArgumentException))) result = TestResult.Fail; if (!VerifyAddHeaderIsIllegal(wrc, HttpKnownHeaderNames.UserAgent, null, typeof(ArgumentException))) result = TestResult.Fail; if (!VerifyAddHeaderIsIllegal(wrc, HttpKnownHeaderNames.ProxyConnection, null, typeof(ArgumentException))) result = TestResult.Fail; } catch (Exception ex) { Log.Exception("[Client] Unexpected Exception", ex); result = TestResult.Fail; } return result; } [TestMethod] public TestResult TestWebHeaderCollectionAddIllegal2() { TestResult result = TestResult.Pass; HttpWebRequest wr = (HttpWebRequest)WebRequest.Create("http://127.0.0.1:" + HttpServer.s_CurrentPort.ToString() + "/"); //expect 200 - OK wr.UserAgent = ".Net Micro Framwork Device/4.0"; Log.Comment("Initial version: " + wr.ProtocolVersion); //Default version is 1.1 Log.Comment("Set Version 1.1"); wr.ProtocolVersion = new Version(1, 1); try { WebHeaderCollection wrc = wr.Headers; //Attempt to add Restricted header if (!VerifyAddHeaderIsIllegal(wrc, HttpKnownHeaderNames.Accept, "text/plain; q=0.5, text/html, text/x-dvi; q=0.8, text/x-c", typeof(ArgumentException))) result = TestResult.Fail; if (!VerifyAddHeaderIsIllegal(wrc, HttpKnownHeaderNames.Connection, "close", typeof(ArgumentException))) result = TestResult.Fail; if (!VerifyAddHeaderIsIllegal(wrc, HttpKnownHeaderNames.ContentLength, "26012", typeof(ArgumentException))) result = TestResult.Fail; if (!VerifyAddHeaderIsIllegal(wrc, HttpKnownHeaderNames.ContentType, "image/gif", typeof(ArgumentException))) result = TestResult.Fail; if (!VerifyAddHeaderIsIllegal(wrc, HttpKnownHeaderNames.Date, System.DateTime.Today.ToString(), typeof(ArgumentException))) result = TestResult.Fail; if (!VerifyAddHeaderIsIllegal(wrc, HttpKnownHeaderNames.Expect, "100", typeof(ArgumentException))) result = TestResult.Fail; if (!VerifyAddHeaderIsIllegal(wrc, HttpKnownHeaderNames.Host, "www.w3.org", typeof(ArgumentException))) result = TestResult.Fail; if (!VerifyAddHeaderIsIllegal(wrc, HttpKnownHeaderNames.IfModifiedSince, "Sat, 23 May 2009 19:43:31 GMT", typeof(ArgumentException))) result = TestResult.Fail; if (!VerifyAddHeaderIsIllegal(wrc, HttpKnownHeaderNames.Range, "500-999", typeof(ArgumentException))) result = TestResult.Fail; if (!VerifyAddHeaderIsIllegal(wrc, HttpKnownHeaderNames.Referer, "http://www.w3.org/hypertext/DataSources/Overview.html", typeof(ArgumentException))) result = TestResult.Fail; if (!VerifyAddHeaderIsIllegal(wrc, HttpKnownHeaderNames.TransferEncoding, "chunked", typeof(ArgumentException))) result = TestResult.Fail; if (!VerifyAddHeaderIsIllegal(wrc, HttpKnownHeaderNames.UserAgent, ".NetMicroFramework", typeof(ArgumentException))) result = TestResult.Fail; if (!VerifyAddHeaderIsIllegal(wrc, HttpKnownHeaderNames.ProxyConnection, "www.microsoft.com", typeof(ArgumentException))) result = TestResult.Fail; } catch (Exception ex) { Log.Exception("[Client] Unexpected Exception", ex); result = TestResult.Fail; } return result; } [TestMethod] public TestResult TestWebHeaderCollectionAddLegal2() { TestResult result = TestResult.Pass; HttpWebRequest wr = (HttpWebRequest)WebRequest.Create("http://127.0.0.1:" + HttpServer.s_CurrentPort.ToString() + "/"); wr.UserAgent = ".Net Micro Framwork Device/4.0"; Log.Comment("Initial version: " + wr.ProtocolVersion); //Default version is 1.1 Log.Comment("Set Version 1.0"); wr.ProtocolVersion = new Version(1, 1); try { System.Net.WebHeaderCollection wrc = wr.Headers; if (!VerifyHeaderIsLegal(wrc, HttpKnownHeaderNames.AcceptCharset, "iso-8859-5, unicode-1-1;q=0.8", typeof(ArgumentException))) result = TestResult.Fail; if (!VerifyHeaderIsLegal(wrc, HttpKnownHeaderNames.AcceptEncoding, "compress;q=0.5, gzip;q=1.0", typeof(ArgumentException))) result = TestResult.Fail; if (!VerifyHeaderIsLegal(wrc, HttpKnownHeaderNames.AcceptLanguage, "en-US", typeof(ArgumentException))) result = TestResult.Fail; if (!VerifyHeaderIsLegal(wrc, HttpKnownHeaderNames.Age, "2 days", typeof(ArgumentException))) result = TestResult.Fail; if (!VerifyHeaderIsLegal(wrc, HttpKnownHeaderNames.Allow, "GET, PUT", typeof(ArgumentException))) result = TestResult.Fail; if (!VerifyHeaderIsLegal(wrc, HttpKnownHeaderNames.CacheControl, "no-cache", typeof(ArgumentException))) result = TestResult.Fail; if (!VerifyHeaderIsLegal(wrc, HttpKnownHeaderNames.ContentEncoding, "gzip", typeof(ArgumentException))) result = TestResult.Fail; if (!VerifyHeaderIsLegal(wrc, HttpKnownHeaderNames.ContentLanguage, "mi, en", typeof(ArgumentException))) result = TestResult.Fail; if (!VerifyHeaderIsLegal(wrc, HttpKnownHeaderNames.ContentMD5, "60e985979f1d55ab7542440fbb9659e5", typeof(ArgumentException))) result = TestResult.Fail; if (!VerifyHeaderIsLegal(wrc, HttpKnownHeaderNames.ContentRange, "bytes 21010-47021/47022", typeof(ArgumentException))) result = TestResult.Fail; if (!VerifyHeaderIsLegal(wrc, HttpKnownHeaderNames.Cookie, "www.google.com", typeof(ArgumentException))) result = TestResult.Fail; if (!VerifyHeaderIsLegal(wrc, HttpKnownHeaderNames.Expires, "Thu, 01 Dec 1994 16:00:00 GMT", typeof(ArgumentException))) result = TestResult.Fail; if (!VerifyHeaderIsLegal(wrc, HttpKnownHeaderNames.From, "webmaster@w3.org", typeof(ArgumentException))) result = TestResult.Fail; if (!VerifyHeaderIsLegal(wrc, HttpKnownHeaderNames.IfMatch, "r2d2xxxx", typeof(ArgumentException))) result = TestResult.Fail; if (!VerifyHeaderIsLegal(wrc, HttpKnownHeaderNames.IfNoneMatch, "xyzzy", typeof(ArgumentException))) result = TestResult.Fail; if (!VerifyHeaderIsLegal(wrc, HttpKnownHeaderNames.IfRange, "TestIfRange: Need to have Range Header.", typeof(ArgumentException))) result = TestResult.Fail; if (!VerifyHeaderIsLegal(wrc, HttpKnownHeaderNames.IfUnmodifiedSince, "Fri, 22 May 2009 12:43:31 GMT", typeof(ArgumentException))) result = TestResult.Fail; if (!VerifyHeaderIsLegal(wrc, HttpKnownHeaderNames.KeepAlive, "true", typeof(ArgumentException))) result = TestResult.Fail; if (!VerifyHeaderIsLegal(wrc, HttpKnownHeaderNames.LastModified, "Fri, 22 May 2009 12:43:31 GMT", typeof(ArgumentException))) result = TestResult.Fail; if (!VerifyHeaderIsLegal(wrc, HttpKnownHeaderNames.MaxForwards, "10", typeof(ArgumentException))) result = TestResult.Fail; if (!VerifyHeaderIsLegal(wrc, HttpKnownHeaderNames.Pragma, "no-cache", typeof(ArgumentException))) result = TestResult.Fail; if (!VerifyHeaderIsLegal(wrc, HttpKnownHeaderNames.ProxyAuthenticate, "", typeof(ArgumentException))) result = TestResult.Fail; if (!VerifyHeaderIsLegal(wrc, HttpKnownHeaderNames.ProxyAuthorization, "", typeof(ArgumentException))) result = TestResult.Fail; if (!VerifyHeaderIsLegal(wrc, HttpKnownHeaderNames.RetryAfter, "100000", typeof(ArgumentException))) result = TestResult.Fail; if (!VerifyHeaderIsLegal(wrc, HttpKnownHeaderNames.Server, "", typeof(ArgumentException))) result = TestResult.Fail; if (!VerifyHeaderIsLegal(wrc, HttpKnownHeaderNames.SetCookie, "www.microsoft.com", typeof(ArgumentException))) result = TestResult.Fail; if (!VerifyHeaderIsLegal(wrc, HttpKnownHeaderNames.SetCookie2, "www.bing.com", typeof(ArgumentException))) result = TestResult.Fail; if (!VerifyHeaderIsLegal(wrc, HttpKnownHeaderNames.TE, "trailers, deflate;q=0.5", typeof(ArgumentException))) result = TestResult.Fail; if (!VerifyHeaderIsLegal(wrc, HttpKnownHeaderNames.Trailer, "Test Code", typeof(ArgumentException))) result = TestResult.Fail; if (!VerifyHeaderIsLegal(wrc, HttpKnownHeaderNames.Upgrade, "HTTP/2.0, SHTTP/1.3, IRC/6.9, RTA/x11", typeof(ArgumentException))) result = TestResult.Fail; if (!VerifyHeaderIsLegal(wrc, HttpKnownHeaderNames.Via, "1.0 fred, 1.1 nowhere.com (Apache/1.1)", typeof(ArgumentException))) result = TestResult.Fail; if (!VerifyHeaderIsLegal(wrc, HttpKnownHeaderNames.Vary, "*", typeof(ArgumentException))) result = TestResult.Fail; if (!VerifyHeaderIsLegal(wrc, HttpKnownHeaderNames.Warning, "TestWarning", typeof(ArgumentException))) result = TestResult.Fail; if (!VerifyHeaderIsLegal(wrc, HttpKnownHeaderNames.WWWAuthenticate, "WWW-Authenticate", typeof(ArgumentException))) result = TestResult.Fail; } catch (Exception ex) { Log.Exception("[Client] Unexpected Exception", ex); result = TestResult.Fail; } return result; } [TestMethod] public TestResult TestWebHeaderCollectionIsRestricted() { TestResult result = TestResult.Pass; HttpWebRequest wr = (HttpWebRequest)WebRequest.Create("http://127.0.0.1:" + HttpServer.s_CurrentPort.ToString() + "/"); //expect 200 - OK wr.UserAgent = ".Net Micro Framwork Device/4.0"; Log.Comment("Initial version: " + wr.ProtocolVersion); //Default version is 1.1 Log.Comment("Set Version 1.1"); wr.ProtocolVersion = new Version(1, 1); try { WebHeaderCollection wrc = wr.Headers; //Attempt to add Restricted header if (!WebHeaderCollection.IsRestricted(HttpKnownHeaderNames.Accept)) result = TestResult.Fail; if (!WebHeaderCollection.IsRestricted(HttpKnownHeaderNames.Connection)) result = TestResult.Fail; if (!WebHeaderCollection.IsRestricted(HttpKnownHeaderNames.ContentLength)) result = TestResult.Fail; if (!WebHeaderCollection.IsRestricted(HttpKnownHeaderNames.ContentType)) result = TestResult.Fail; if (!WebHeaderCollection.IsRestricted(HttpKnownHeaderNames.Date)) result = TestResult.Fail; if (!WebHeaderCollection.IsRestricted(HttpKnownHeaderNames.Expect)) result = TestResult.Fail; if (!WebHeaderCollection.IsRestricted(HttpKnownHeaderNames.Host)) result = TestResult.Fail; if (!WebHeaderCollection.IsRestricted(HttpKnownHeaderNames.IfModifiedSince)) result = TestResult.Fail; if (!WebHeaderCollection.IsRestricted(HttpKnownHeaderNames.Range)) result = TestResult.Fail; if (!WebHeaderCollection.IsRestricted(HttpKnownHeaderNames.Referer)) result = TestResult.Fail; if (!WebHeaderCollection.IsRestricted(HttpKnownHeaderNames.TransferEncoding)) result = TestResult.Fail; if (!WebHeaderCollection.IsRestricted(HttpKnownHeaderNames.UserAgent)) result = TestResult.Fail; if (!WebHeaderCollection.IsRestricted(HttpKnownHeaderNames.ProxyConnection)) result = TestResult.Fail; } catch (Exception ex) { Log.Exception("[Client] Unexpected Exception", ex); result = TestResult.Fail; } return result; } [TestMethod] public TestResult TestWebHeaderCollectionRemove() { TestResult result = TestResult.Pass; HttpWebRequest wr = (HttpWebRequest)WebRequest.Create("http://127.0.0.1:" + HttpServer.s_CurrentPort.ToString() + "/"); wr.UserAgent = ".Net Micro Framwork Device/4.0"; Log.Comment("Initial version: " + wr.ProtocolVersion); //Default version is 1.1 Log.Comment("Set Version 1.0"); wr.ProtocolVersion = new Version(1, 1); try { System.Net.WebHeaderCollection wrc = wr.Headers; int initialCount = wrc.Count; //set and remove individual header Log.Comment("Set and Remove HttpKnownHeaderNames.AcceptCharset"); wrc.Set(HttpKnownHeaderNames.AcceptCharset, "iso-8859-5, unicode-1-1;q=0.8"); wrc.Remove(HttpKnownHeaderNames.AcceptCharset); if (wrc.Count != initialCount) { result = TestResult.Fail; } Log.Comment("Set and Remove HttpKnownHeaderNames.AcceptEncoding"); wrc.Set(HttpKnownHeaderNames.AcceptEncoding, "compress;q=0.5, gzip;q=1.0"); wrc.Remove(HttpKnownHeaderNames.AcceptEncoding); if (wrc.Count != initialCount) { result = TestResult.Fail; } Log.Comment("Set and Remove HttpKnownHeaderNames.AcceptLanguage"); wrc.Set(HttpKnownHeaderNames.AcceptLanguage, "en-US"); wrc.Remove(HttpKnownHeaderNames.AcceptLanguage); if (wrc.Count != initialCount) { result = TestResult.Fail; } //Set and remove group of headers Log.Comment("Set group of headers..."); wrc.Set(HttpKnownHeaderNames.Age, "2 days"); wrc.Set(HttpKnownHeaderNames.Allow, "GET, PUT"); wrc.Set(HttpKnownHeaderNames.CacheControl, "no-cache"); wrc.Set(HttpKnownHeaderNames.ContentEncoding, "gzip"); wrc.Set(HttpKnownHeaderNames.ContentLanguage, "mi, en"); wrc.Set(HttpKnownHeaderNames.ContentMD5, "60e985979f1d55ab7542440fbb9659e5"); wrc.Set(HttpKnownHeaderNames.ContentRange, "bytes 21010-47021/47022"); wrc.Set(HttpKnownHeaderNames.Cookie, "www.google.com"); wrc.Set(HttpKnownHeaderNames.Expires, "Thu, 01 Dec 1994 16:00:00 GMT"); wrc.Set(HttpKnownHeaderNames.From, "webmaster@w3.org"); wrc.Set(HttpKnownHeaderNames.IfMatch, "r2d2xxxx"); wrc.Set(HttpKnownHeaderNames.IfNoneMatch, "xyzzy"); wrc.Set(HttpKnownHeaderNames.IfRange, "TestIfRange: Need to have Range Header."); wrc.Set(HttpKnownHeaderNames.IfUnmodifiedSince, "Fri, 22 May 2009 12:43:31 GMT"); wrc.Set(HttpKnownHeaderNames.KeepAlive, "true"); wrc.Set(HttpKnownHeaderNames.LastModified, "Fri, 22 May 2009 12:43:31 GMT"); wrc.Set(HttpKnownHeaderNames.MaxForwards, "10"); wrc.Set(HttpKnownHeaderNames.Pragma, "no-cache"); wrc.Set(HttpKnownHeaderNames.ProxyAuthenticate, ""); wrc.Set(HttpKnownHeaderNames.ProxyAuthorization, ""); wrc.Set(HttpKnownHeaderNames.RetryAfter, "100000"); wrc.Set(HttpKnownHeaderNames.Server, ""); wrc.Set(HttpKnownHeaderNames.SetCookie, "www.microsoft.com"); wrc.Set(HttpKnownHeaderNames.SetCookie2, "www.bing.com"); wrc.Set(HttpKnownHeaderNames.TE, "trailers, deflate;q=0.5"); wrc.Set(HttpKnownHeaderNames.Trailer, "Test Code"); wrc.Set(HttpKnownHeaderNames.Upgrade, "HTTP/2.0, SHTTP/1.3, IRC/6.9, RTA/x11"); wrc.Set(HttpKnownHeaderNames.Via, "1.0 fred, 1.1 nowhere.com (Apache/1.1)"); wrc.Set(HttpKnownHeaderNames.Vary, "*"); wrc.Set(HttpKnownHeaderNames.Warning, "TestWarning"); wrc.Set(HttpKnownHeaderNames.WWWAuthenticate, "WWW-Authenticate"); //remove headers Log.Comment("Remove group of headers..."); wrc.Remove(HttpKnownHeaderNames.Age); wrc.Remove(HttpKnownHeaderNames.Allow); wrc.Remove(HttpKnownHeaderNames.CacheControl); wrc.Remove(HttpKnownHeaderNames.ContentEncoding); wrc.Remove(HttpKnownHeaderNames.ContentLanguage); wrc.Remove(HttpKnownHeaderNames.ContentMD5); wrc.Remove(HttpKnownHeaderNames.ContentRange); wrc.Remove(HttpKnownHeaderNames.Cookie); wrc.Remove(HttpKnownHeaderNames.Expires); wrc.Remove(HttpKnownHeaderNames.From); wrc.Remove(HttpKnownHeaderNames.IfMatch); wrc.Remove(HttpKnownHeaderNames.IfNoneMatch); wrc.Remove(HttpKnownHeaderNames.IfRange); wrc.Remove(HttpKnownHeaderNames.IfUnmodifiedSince); wrc.Remove(HttpKnownHeaderNames.KeepAlive); wrc.Remove(HttpKnownHeaderNames.LastModified); wrc.Remove(HttpKnownHeaderNames.MaxForwards); wrc.Remove(HttpKnownHeaderNames.Pragma); wrc.Remove(HttpKnownHeaderNames.ProxyAuthenticate); wrc.Remove(HttpKnownHeaderNames.ProxyAuthorization); wrc.Remove(HttpKnownHeaderNames.RetryAfter); wrc.Remove(HttpKnownHeaderNames.Server); wrc.Remove(HttpKnownHeaderNames.SetCookie); wrc.Remove(HttpKnownHeaderNames.SetCookie2); wrc.Remove(HttpKnownHeaderNames.TE); wrc.Remove(HttpKnownHeaderNames.Trailer); wrc.Remove(HttpKnownHeaderNames.Upgrade); wrc.Remove(HttpKnownHeaderNames.Via); wrc.Remove(HttpKnownHeaderNames.Vary); wrc.Remove(HttpKnownHeaderNames.Warning); wrc.Remove(HttpKnownHeaderNames.WWWAuthenticate); if (wrc.Count != initialCount) { result = TestResult.Fail; } } catch (Exception ex) { Log.Exception("[Client] Unexpected Exception", ex); result = TestResult.Fail; } return result; } #endregion Test } } ================================================ FILE: Zelig/Zelig/Test/RunTime/NETMF/System/Http/WebProxyTests.cs ================================================ //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // Copyright (c) Microsoft Corporation. All rights reserved. //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// using System; using System.Net; namespace Microsoft.Zelig.Test { public class WebProxyTests : TestBase, ITestInterface { [SetUp] public InitializeResult Initialize() { Log.Comment("Adding set up for the tests."); // Add your functionality here. return InitializeResult.ReadyToGo; } [TearDown] public void CleanUp() { Log.Comment("Cleaning up after the tests."); // TODO: Add your clean up steps here. } public override TestResult Run( string[] args ) { return TestResult.Pass; } //--// //--// //--// [TestMethod] public TestResult TestDefaultWebProxy() { TestResult result = TestResult.Pass; Log.Comment("Set proxy using WebProxy()"); UriProperties props = new UriProperties("http", "www.microsoft.com"); Uri uri = new Uri(props.OriginalUri); WebProxy proxyObject = new WebProxy(); WebRequest wr = WebRequest.Create(uri); wr.Proxy = proxyObject; Uri wrUri = wr.Proxy.GetProxy(uri); if (wrUri != uri) { result = TestResult.Fail; } return result; } [TestMethod] public TestResult TestWebProxyConstructor1() { TestResult result = TestResult.Pass; Log.Comment("Set proxy using WebProxy(string)"); UriProperties props = new UriProperties("http", "www.microsoft.com"); Uri uri = new Uri(props.OriginalUri); string proxy = "itgproxy.redmond.corp.microsoft.com"; WebProxy proxyObject = new WebProxy(proxy); WebRequest wr = WebRequest.Create(uri); wr.Proxy = proxyObject; Uri wrUri = wr.Proxy.GetProxy(uri); if (wrUri.Host != proxy) { result = TestResult.Fail; } return result; } [TestMethod] public TestResult TestWebProxyConstructor2() { TestResult result = TestResult.Pass; Log.Comment("Set proxy using WebProxy(string, bool)"); UriProperties props = new UriProperties("http", "www.microsoft.com"); Uri uri = new Uri(props.OriginalUri); string proxy = "itgproxy.redmond.corp.microsoft.com"; WebProxy proxyObject = new WebProxy(proxy, true); WebRequest wr = WebRequest.Create(uri); wr.Proxy = proxyObject; Uri wrUri = wr.Proxy.GetProxy(uri); if (wrUri.Host != proxy) { result = TestResult.Fail; } return result; } [TestMethod] public TestResult TestWebProxyConstructor3() { TestResult result = TestResult.Pass; Log.Comment("Set proxy using WebProxy(string, int)"); UriProperties props = new UriProperties("http", "www.microsoft.com"); Uri uri = new Uri(props.OriginalUri); string proxy = "itgproxy.redmond.corp.microsoft.com"; WebProxy proxyObject = new WebProxy(proxy, 80); WebRequest wr = WebRequest.Create(uri); wr.Proxy = proxyObject; Uri wrUri = wr.Proxy.GetProxy(uri); if (wrUri.Host != proxy) { result = TestResult.Fail; } return result; } [TestMethod] public TestResult TestWebProxyConstructor4() { TestResult result = TestResult.Pass; Log.Comment("Set proxy using WebProxy(System.Uri, bool)"); UriProperties props = new UriProperties("http", "www.microsoft.com"); Uri uri = new Uri(props.OriginalUri); WebProxy proxyObject = new WebProxy(uri, true); WebRequest wr = WebRequest.Create(uri); wr.Proxy = proxyObject; Uri wrUri = wr.Proxy.GetProxy(uri); if (wrUri != uri) { result = TestResult.Fail; } return result; } [TestMethod] public TestResult TestWebProxyConstructor5() { TestResult result = TestResult.Pass; Log.Comment("Set proxy using WebProxy(System.Uri)"); UriProperties props = new UriProperties("http", "www.microsoft.com"); Uri uri = new Uri(props.OriginalUri); WebProxy proxyObject = new WebProxy(uri); if (proxyObject.BypassProxyOnLocal) { result = TestResult.Fail; } WebRequest wr = WebRequest.Create(uri); wr.Proxy = proxyObject; Uri wrUri = wr.Proxy.GetProxy(uri); if (wrUri != uri) { result = TestResult.Fail; } return result; } [TestMethod] public TestResult TestWebProxyInvalidserverAddress() { TestResult result = TestResult.Pass; Log.Comment("Set proxy using WebProxy(string, bool)"); UriProperties props = new UriProperties("http", "www.microsoft.com"); Uri uri = new Uri(props.OriginalUri); try { WebProxy proxyObject = new WebProxy("ht1p:itgproxy", true); result = TestResult.Fail; } catch (ArgumentException ex) { Log.Exception("Expect ArgumentException: ", ex); } try { WebProxy proxyObject = new WebProxy(string.Empty, true); result = TestResult.Fail; } catch (ArgumentOutOfRangeException ex) { Log.Exception("Expect ArgumentOutOfRangeException: ", ex); } return result; } } } ================================================ FILE: Zelig/Zelig/Test/RunTime/NETMF/System/Http/WebRequestTests.cs ================================================ //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // Copyright (c) Microsoft Corporation. All rights reserved. //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// using System; using System.Net; namespace Microsoft.Zelig.Test { public class WebRequestTests : TestBase, ITestInterface { [SetUp] public InitializeResult Initialize() { Log.Comment("Adding set up for the tests."); // Add your functionality here. return InitializeResult.ReadyToGo; } [TearDown] public void CleanUp() { Log.Comment("Cleaning up after the tests."); // TODO: Add your clean up steps here. } public override TestResult Run( string[] args ) { return TestResult.Pass; } //--// //--// //--// #region Test Cases [TestMethod] public TestResult ValidConstructorTests() { TestResult result = TestResult.Pass; try { Log.Comment("string constructor"); WebRequest wrStr = WebRequest.Create(HttpTests.MSUrl); if (wrStr.RequestUri.AbsoluteUri != HttpTests.MSUrl + "/") { Log.Exception("Expected " + HttpTests.MSUrl + ", but got " + wrStr.RequestUri.AbsoluteUri); result = TestResult.Fail; } Log.Comment("uri constructor"); Uri uri = new Uri(HttpTests.MSUrl); WebRequest wrUri = WebRequest.Create(uri); if (wrUri.RequestUri.AbsoluteUri != HttpTests.MSUrl + "/") { Log.Exception("Expected " + HttpTests.MSUrl + ", but got " + wrUri.RequestUri.AbsoluteUri); result = TestResult.Fail; } } catch (Exception ex) { Log.Exception("Unexpected Exception", ex); result = TestResult.Fail; } return result; } [TestMethod] public TestResult InvalidConstructorTests() { TestResult result = TestResult.Pass; try { Log.Comment("null string"); string nullString = null; try { WebRequest nsWR = WebRequest.Create(nullString); } catch (Exception ex) { if (!HttpTests.ValidateException(ex, typeof(ArgumentNullException))) result = TestResult.Fail; } Log.Comment("null uri"); Uri nullUri = null; try { WebRequest nuWr = WebRequest.Create(nullUri); } catch (Exception ex) { if (!HttpTests.ValidateException(ex, typeof(ArgumentNullException))) result = TestResult.Fail; } Log.Comment("invalud URI type"); try { WebRequest inWr = WebRequest.Create("ftp://ftp.microsoft.com"); } catch (Exception ex) { if (!HttpTests.ValidateException(ex, typeof(NotSupportedException))) result = TestResult.Fail; } } catch (Exception ex) { Log.Exception("Unexpected Exception", ex); result = TestResult.Fail; } return result; } [TestMethod] public TestResult ValidPropertiesTests() { TestResult result = TestResult.Pass; try { Log.Comment("WebRequest Properties"); WebRequest wrStr = WebRequest.Create(HttpTests.MSUrl); Log.Comment("Get ContentType property"); if (null != wrStr.ContentType) { Log.Exception("Expected null but got an object"); result = TestResult.Fail; } Log.Comment("Get Method property"); if (wrStr.Method == System.String.Empty || wrStr.Method.CompareTo("GET") != 0) { Log.Exception("Expected Method string but get empty string"); result = TestResult.Fail; } Log.Comment("Get Proxy property - Expect null"); if (wrStr.Proxy != null) { Log.Exception("Expected Proxy property to be null but "); result = TestResult.Fail; } Log.Comment("Set and Get Timeout property"); wrStr.Timeout = 90000; if (wrStr.Timeout != 90000) { Log.Exception("Failed to set TimeOut property"); result = TestResult.Fail; } wrStr.Timeout = 100000; if (wrStr.Timeout != 100000) { Log.Exception("Failed to set TimeOut property"); result = TestResult.Fail; } Log.Comment("Set ConnectionGroupName property - should get System.NotSupportedException"); try { wrStr.ConnectionGroupName = "test"; } catch (System.NotSupportedException e) { Log.Exception("Get exception when set the value of ConnectionGroupName property. " + e.Message.ToString()); } Log.Comment("Set PreAuthenticate property"); try { // BUILD BREAK - PreAuthenticate is not defined for HttpWebRequest //wrStr.PreAuthenticate = true; } catch (Exception e) { Log.Exception("Bug #61228: Get exception when set the value of PreAuthenticate property. " + e.Message.ToString()); } } catch (Exception ex) { Log.Exception("Unexpected Exception", ex); result = TestResult.Fail; } return result; } #endregion Test Cases } } ================================================ FILE: Zelig/Zelig/Test/RunTime/NETMF/System/Http/WebResponseTests.cs ================================================ //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // Copyright (c) Microsoft Corporation. All rights reserved. //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// using Microsoft.Llilum.Lwip; using System; using System.Net; namespace Microsoft.Zelig.Test { public class WebResponseTests : TestBase, ITestInterface { [SetUp] public InitializeResult Initialize() { Log.Comment("Adding set up for the tests."); try { NetworkInterface[] nis = NetworkInterface.GetAllNetworkInterfaces(); } catch { return InitializeResult.Skip; } return InitializeResult.ReadyToGo; } [TearDown] public void CleanUp() { Log.Comment("Cleaning up after the tests."); // TODO: Add your clean up steps here. } public override TestResult Run( string[] args ) { return TestResult.Pass; } //--// //--// //--// [TestMethod] public TestResult NotSupportExceptionTest() { TestResult result = TestResult.Pass; try { Log.Comment("WebResponse Test"); HttpWebRequest wrStr = (HttpWebRequest)WebRequest.Create("http://127.0.0.1:" + HttpServer.s_CurrentPort.ToString() + "/"); HttpServer server = new HttpServer("http", ref result) { RequestUri = wrStr.RequestUri, RequestHeaders = wrStr.Headers, ResponseString = "WebResponse Test" }; server.StartServer(); WebRequest wr = wrStr; WebResponse wresp = wr.GetResponse(); Log.Comment("Check ResponseUri property"); if (wresp.ResponseUri.AbsoluteUri != wr.RequestUri.AbsoluteUri) { Log.Exception("Expected " + HttpTests.MSUrl + ", but got " + wresp.ResponseUri.AbsoluteUri); result = TestResult.Fail; } Log.Comment("Check ContentType property"); if (wresp.ContentType != "") { Log.Exception("Expected: " + wr.ContentType); result = TestResult.Fail; } Log.Comment("Invoke WebResponse.Close()"); try { wresp.Close(); } catch (System.NotSupportedException e) { Log.Exception("Get exception when invoke WebResponse.Close(). " + e.Message.ToString()); result = TestResult.Fail; } finally { //Stop server server.StopServer(); } } catch (Exception ex) { Log.Exception("Unexpected Exception", ex); result = TestResult.Fail; } return result; } } } ================================================ FILE: Zelig/Zelig/Test/RunTime/NETMF/System/IO/MemoryStream/CanRead.cs ================================================ //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // Copyright (c) Microsoft Corporation. All rights reserved. //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// using System; using System.IO; namespace Microsoft.Zelig.Test { public class CanRead : TestBase, ITestInterface { [SetUp] public InitializeResult Initialize() { return InitializeResult.ReadyToGo; } [TearDown] public void CleanUp() { } public override TestResult Run( string[] args ) { TestResult result = TestResult.Pass; result |= Assert.CheckFailed( CanRead_Default_Ctor( ) ); result |= Assert.CheckFailed( CanRead_Byte_Ctor( ) ); return result; } [TestMethod] public TestResult CanRead_Default_Ctor() { TestResult result = TestResult.Pass; try { Log.Comment("Verify CanRead is true for default Ctor"); using (MemoryStream fs = new MemoryStream()) { if (!fs.CanRead) { result = TestResult.Fail; Log.Exception("Expected CanRead == true, but got CanRead == false"); } } } catch (Exception ex) { result = TestResult.Fail; Log.Exception("Unexpected exception", ex); } return result; } [TestMethod] public TestResult CanRead_Byte_Ctor() { TestResult result = TestResult.Pass; try { Log.Comment("Verify CanRead is true for Byte[] Ctor"); byte[] buffer = new byte[1024]; using (MemoryStream fs = new MemoryStream(buffer)) { if (!fs.CanRead) { result = TestResult.Fail; Log.Exception("Expected CanRead == true, but got CanRead == false"); } } } catch (Exception ex) { result = TestResult.Fail; Log.Exception("Unexpected exception", ex); } return result; } } } ================================================ FILE: Zelig/Zelig/Test/RunTime/NETMF/System/IO/MemoryStream/CanSeek.cs ================================================ //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // Copyright (c) Microsoft Corporation. All rights reserved. //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// using System; using System.IO; namespace Microsoft.Zelig.Test { public class CanSeek : TestBase, ITestInterface { [SetUp] public InitializeResult Initialize() { return InitializeResult.ReadyToGo; } [TearDown] public void CleanUp() { } public override TestResult Run( string[] args ) { TestResult result = TestResult.Pass; result |= Assert.CheckFailed( CanSeek_Default_Ctor( ) ); result |= Assert.CheckFailed( CanSeek_Byte_Ctor( ) ); return result; } [TestMethod] public TestResult CanSeek_Default_Ctor() { TestResult result = TestResult.Pass; try { Log.Comment("Verify CanSeek is true for default Ctor"); using (MemoryStream fs = new MemoryStream()) { if (!fs.CanSeek) { result = TestResult.Fail; Log.Exception("Expected CanSeek == true, but got CanSeek == false"); } } } catch (Exception ex) { result = TestResult.Fail; Log.Exception("Unexpected exception", ex); } return result; } [TestMethod] public TestResult CanSeek_Byte_Ctor() { TestResult result = TestResult.Pass; try { Log.Comment("Verify CanSeek is true for Byte[] Ctor"); byte[] buffer = new byte[1024]; using (MemoryStream fs = new MemoryStream(buffer)) { if (!fs.CanSeek) { result = TestResult.Fail; Log.Exception("Expected CanSeek == true, but got CanSeek == false"); } } } catch (Exception ex) { result = TestResult.Fail; Log.Exception("Unexpected exception", ex); } return result; } } } ================================================ FILE: Zelig/Zelig/Test/RunTime/NETMF/System/IO/MemoryStream/CanWrite.cs ================================================ //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // Copyright (c) Microsoft Corporation. All rights reserved. //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// using System; using System.IO; namespace Microsoft.Zelig.Test { public class CanWrite : TestBase, ITestInterface { [SetUp] public InitializeResult Initialize() { return InitializeResult.ReadyToGo; } [TearDown] public void CleanUp() { } public override TestResult Run( string[] args ) { TestResult result = TestResult.Pass; result |= Assert.CheckFailed( CanWrite_Default_Ctor( ) ); result |= Assert.CheckFailed( CanWrite_Byte_Ctor( ) ); return result; } [TestMethod] public TestResult CanWrite_Default_Ctor() { TestResult result = TestResult.Pass; try { Log.Comment("Verify CanWrite is true for default Ctor"); using (MemoryStream fs = new MemoryStream()) { if (!fs.CanWrite) { result = TestResult.Fail; Log.Exception("Expected CanWrite == true, but got CanWrite == false"); } } } catch (Exception ex) { result = TestResult.Fail; Log.Exception("Unexpected exception", ex); } return result; } [TestMethod] public TestResult CanWrite_Byte_Ctor() { TestResult result = TestResult.Pass; try { Log.Comment("Verify CanWrite is true for Byte[] Ctor"); byte[] buffer = new byte[1024]; using (MemoryStream fs = new MemoryStream(buffer)) { if (!fs.CanWrite) { result = TestResult.Fail; Log.Exception("Expected CanWrite == true, but got CanWrite == false"); } } } catch (Exception ex) { result = TestResult.Fail; Log.Exception("Unexpected exception", ex); } return result; } } } ================================================ FILE: Zelig/Zelig/Test/RunTime/NETMF/System/IO/MemoryStream/Close.cs ================================================ //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // Copyright (c) Microsoft Corporation. All rights reserved. //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// using System; using System.IO; namespace Microsoft.Zelig.Test { public class Close : TestBase, ITestInterface { [SetUp] public InitializeResult Initialize() { return InitializeResult.ReadyToGo; } [TearDown] public void CleanUp() { } public override TestResult Run( string[] args ) { TestResult result = TestResult.Pass; //result |= Assert.CheckFailed( VerifyClose( ) ); return result; } [TestMethod] public TestResult VerifyClose() { TestResult result = TestResult.Pass; try { MemoryStream ms = new MemoryStream(); ms.WriteByte(0); Log.Comment("Close stream"); ms.Close(); try { Log.Comment("Verify actually closed by writing to it"); ms.WriteByte(0); result = TestResult.Fail; Log.Exception("Expected ObjectDisposedException"); } catch (ObjectDisposedException) { /* pass case */ } } catch (Exception ex) { result = TestResult.Fail; Log.Exception("Unexpected exception", ex); } return result; } } } ================================================ FILE: Zelig/Zelig/Test/RunTime/NETMF/System/IO/MemoryStream/Flush.cs ================================================ //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // Copyright (c) Microsoft Corporation. All rights reserved. //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// using System; using System.IO; namespace Microsoft.Zelig.Test { public class Flush : TestBase, ITestInterface { [SetUp] public InitializeResult Initialize() { return InitializeResult.ReadyToGo; } [TearDown] public void CleanUp() { } public override TestResult Run( string[] args ) { TestResult result = TestResult.Pass; result |= Assert.CheckFailed( VerifyFlush( ) ); return result; } [TestMethod] public TestResult VerifyFlush() { TestResult result = TestResult.Pass; try { using (MemoryStream ms = new MemoryStream()) { byte[] data = Utilities.GetRandomBytes(5000); ms.Write(data, 0, data.Length); ms.Flush(); if (ms.Length != 5000) { result = TestResult.Fail; Log.Exception("Expected 5000 bytes, but got " + ms.Length); } } } catch (Exception ex) { result = TestResult.Fail; Log.Exception("Unexpected exception", ex); } return result; } } } ================================================ FILE: Zelig/Zelig/Test/RunTime/NETMF/System/IO/MemoryStream/Length.cs ================================================ //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // Copyright (c) Microsoft Corporation. All rights reserved. //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// using System; using System.IO; namespace Microsoft.Zelig.Test { public class Length : TestBase, ITestInterface { [SetUp] public InitializeResult Initialize() { Log.Comment("Adding set up for the tests."); // TODO: Add your set up steps here. return InitializeResult.ReadyToGo; } [TearDown] public void CleanUp() { Log.Comment("Cleaning up after the tests."); // TODO: Add your clean up steps here. } public override TestResult Run( string[] args ) { TestResult result = TestResult.Pass; //result |= Assert.CheckFailed( ObjectDisposed( ) ); result |= Assert.CheckFailed( LengthTests( ) ); return result; } #region Helper methods private bool TestLength(MemoryStream ms, long expectedLength) { if (ms.Length != expectedLength) { Log.Exception("Expected length " + expectedLength + " but got, " + ms.Length); return false; } return true; } private bool TestPosition(MemoryStream ms, long expectedPosition) { if (ms.Position != expectedPosition) { Log.Exception("Expected position " + expectedPosition + " but got, " + ms.Position); return false; } return true; } #endregion Helper methods #region Test Cases [TestMethod] public TestResult ObjectDisposed() { TestResult result = TestResult.Pass; try { MemoryStream ms = new MemoryStream(); ms.Close(); try { long length = ms.Length; result = TestResult.Fail; Log.Exception("Expected ObjectDisposedException, but got length " + length); } catch (ObjectDisposedException) { /*Pass Case */ } } catch (Exception ex) { Log.Exception("Unexpected exception", ex); result = TestResult.Fail; } return result; } [TestMethod] public TestResult LengthTests() { TestResult result = TestResult.Pass; try { using (MemoryStream ms = new MemoryStream()) { Log.Comment("Set initial length to 50, and position to 50"); ms.SetLength(50); ms.Position = 50; if (!TestLength(ms, 50)) result = TestResult.Fail; Log.Comment("Write 'foo bar'"); StreamWriter sw = new StreamWriter(ms); sw.Write("foo bar"); sw.Flush(); if (!TestLength(ms, 57)) result = TestResult.Fail; Log.Comment("Shorten Length to 30"); ms.SetLength(30); if (!TestLength(ms, 30)) result = TestResult.Fail; Log.Comment("Verify position was adjusted"); if (!TestPosition(ms, 30)) result = TestResult.Fail; Log.Comment("Extend length to 100"); ms.SetLength(100); if (!TestLength(ms, 100)) result = TestResult.Fail; } Log.Comment("Verify memorystream is 0 bytes after close"); using (MemoryStream ms = new MemoryStream()) { if (!TestLength(ms, 0)) result = TestResult.Fail; } } catch (Exception ex) { Log.Exception("Unexpected exception", ex); result = TestResult.Fail; } return result; } #endregion Test Cases } } ================================================ FILE: Zelig/Zelig/Test/RunTime/NETMF/System/IO/MemoryStream/MemoryStreamHelper.cs ================================================ //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // Copyright (c) Microsoft Corporation. All rights reserved. //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// using System; using System.IO; namespace Microsoft.Zelig.Test { public class MemoryStreamHelper { public static bool WriteReadEmpty(Stream ms) { bool result = true; if (ms.Position != 0) { result = false; Log.Exception("Expected postion 0, but got " + ms.Position); } if (ms.Length != 0) { result = false; Log.Exception("Expected length 0, but got " + ms.Length); } return WriteReadVerify(ms) & result; } public static bool WriteReadVerify(Stream ms) { bool result = Write(ms, 300); // Flush writes ms.Flush(); Log.Comment("Seek to start and Read"); ms.Seek(0, SeekOrigin.Begin); result &= VerifyRead(ms); return result; } public static bool Write(Stream ms, int length) { bool result = true; long startLength = ms.Length; // we can only write 0-255, so mod the // length to figure out next data value long data = startLength % 256; Log.Comment("Seek to end"); ms.Seek(0, SeekOrigin.End); Log.Comment("Write to file"); for (long i = startLength; i < startLength + length; i++) { ms.WriteByte((byte)data++); // if we hit max byte, reset if (data > 255) data = 0; } return result; } public static bool VerifyRead(Stream ms) { bool result = true; Log.Comment("Verify " + ms.Length + " bytes of data in file"); // we can only read 0-255, so mod the // position to figure out next data value int nextbyte = (int)ms.Position % 256; for (int i = 0; i < ms.Length; i++) { int readByte = ms.ReadByte(); if (readByte != nextbyte) { result = false; Log.Exception("Byte in position " + i + " has wrong value: " + readByte); } // Reset if wraps past 255 if (++nextbyte > 255) nextbyte = 0; } return result; } } } ================================================ FILE: Zelig/Zelig/Test/RunTime/NETMF/System/IO/MemoryStream/MemoryStream_Ctor.cs ================================================ //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // Copyright (c) Microsoft Corporation. All rights reserved. //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// using System; using System.IO; namespace Microsoft.Zelig.Test { public class MemoryStream_Ctor : TestBase, ITestInterface { [SetUp] public InitializeResult Initialize() { return InitializeResult.ReadyToGo; } [TearDown] public void CleanUp() { } public override TestResult Run( string[] args ) { TestResult result = TestResult.Pass; //result |= Assert.CheckFailed( InvalidArguments( ) ); result |= Assert.CheckFailed( Valid_Default_Ctor( ) ); //result |= Assert.CheckFailed( Variable_Buffer_Ctor( ) ); return result; } #region Helper methods private bool ValidateMemoryStream(MemoryStream ms, int ExpectedLength) { bool success = true; Log.Comment("Check Length"); if (ms.Length != ExpectedLength) { success = false; Log.Exception("Expected Length 0, but got Length " + ms.Length); } Log.Comment("Check CanSeek"); if (!ms.CanSeek) { success = false; Log.Exception("Expected CanSeek to be true, but was false"); } Log.Comment("Check CanRead"); if (!ms.CanRead) { success = false; Log.Exception("Expected CanRead to be true, but was false"); } Log.Comment("Check CanWrite"); if (!ms.CanWrite) { success = false; Log.Exception("Expected CanWrite to be true, but was false"); } if (ms.Position != 0) { success = false; Log.Exception("Expected Position to be 0, but was " + ms.Position); } return success; } #endregion Helper methods #region Test Cases [TestMethod] public TestResult InvalidArguments() { TestResult result = TestResult.Pass; try { try { Log.Comment("null buffer"); using (MemoryStream fs = new MemoryStream(null)) { } result = TestResult.Fail; Log.Exception("Expected ArgumentException"); } catch (ArgumentException) { /* pass case */ } } catch (Exception ex) { Log.Exception("Unexpected exception", ex); result = TestResult.Fail; } return result; } [TestMethod] public TestResult Valid_Default_Ctor() { TestResult result = TestResult.Pass; try { using (MemoryStream ms = new MemoryStream()) { if (!ValidateMemoryStream(ms, 0)) result = TestResult.Fail; } } catch (Exception ex) { Log.Exception("Unexpected exception", ex); result = TestResult.Fail; } return result; } [TestMethod] public TestResult Variable_Buffer_Ctor() { TestResult result = TestResult.Pass; try { Log.Comment("Verify buffer constructors length 0-100"); for (int i = 0; i < 100; i++) { byte[] buffer = new byte[i]; using (MemoryStream ms = new MemoryStream(buffer)) { if (!ValidateMemoryStream(ms, i)) result = TestResult.Fail; Log.Comment("Try to extend beyond buffer length"); try { ms.SetLength(i + 1); result = TestResult.Fail; Log.Exception("Expected NotSupportedException"); } catch (NotSupportedException) { /* pass case */ } Log.Comment("Truncate to 0"); for (int j = buffer.Length; j >= 0; j--) { ms.SetLength(j); } } } Log.Comment("Verify 10k buffer constructor"); byte[] largeBuffer = new byte[10000]; using (MemoryStream ms = new MemoryStream(largeBuffer)) { if (!ValidateMemoryStream(ms, largeBuffer.Length)) result = TestResult.Fail; } } catch (Exception ex) { Log.Exception("Unexpected exception", ex); result = TestResult.Fail; } return result; } #endregion Test Cases } } ================================================ FILE: Zelig/Zelig/Test/RunTime/NETMF/System/IO/MemoryStream/Position.cs ================================================ //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // Copyright (c) Microsoft Corporation. All rights reserved. //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// using System; using System.IO; namespace Microsoft.Zelig.Test { public class Position : TestBase, ITestInterface { [SetUp] public InitializeResult Initialize() { Log.Comment("Adding set up for the tests."); // TODO: Add your set up steps here. // if (Setup Fails) // return InitializeResult.Skip; return InitializeResult.ReadyToGo; } [TearDown] public void CleanUp() { Log.Comment("Cleaning up after the tests."); // TODO: Add your clean up steps here. } public override TestResult Run(string[] args) { TestResult result = TestResult.Pass; //result |= Assert.CheckFailed(ObjectDisposed(), "ObjectDisposed", 0); //result |= Assert.CheckFailed(InvalidRange(), "InvalidRange", 0); //result |= Assert.CheckFailed(GetSetStaticBuffer(), "GetSetStaticBuffer", 0); //result |= Assert.CheckFailed(GetSetDynamicBuffer(), "GetSetDynamicBuffer", 0); return result; } #region Helper methods private bool GetSetPosition(MemoryStream ms, int TestLength) { bool success = true; Log.Comment("Move forwards"); for (int i = 0; i < TestLength; i++) { ms.Position = i; if (ms.Position != i) { success = false; Log.Exception("Expected position " + i + " but got position " + ms.Position); } } Log.Comment("Move backwards"); for (int i = TestLength - 1; i >= 0; i--) { ms.Position = i; if (ms.Position != i) { success = false; Log.Exception("Expected position " + i + " but got position " + ms.Position); } } return success; } #endregion Helper methods #region Test Cases [TestMethod] public TestResult ObjectDisposed() { MemoryStream ms = new MemoryStream(); ms.Close(); TestResult result = TestResult.Pass; try { try { long position = ms.Position; result = TestResult.Fail; Log.Exception("Expected ObjectDisposedException, but got position " + position); } catch (ObjectDisposedException) { /*Pass Case */ } try { ms.Position = 0; result = TestResult.Fail; Log.Exception("Expected ObjectDisposedException, but set position"); } catch (ObjectDisposedException) { /*Pass Case */ } } catch (Exception ex) { Log.Exception("Unexpected exception: " + ex.Message); result = TestResult.Fail; } return result; } [TestMethod] public TestResult InvalidRange() { TestResult result = TestResult.Pass; try { byte[] buffer = new byte[100]; using (MemoryStream ms = new MemoryStream(buffer)) { Log.Comment("Try -1 postion"); try { ms.Position = -1; result = TestResult.Fail; Log.Exception("Expected ArgumentOutOfRangeException"); } catch (ArgumentOutOfRangeException) { /* pass case */ } Log.Comment("Try Long.MinValue postion"); try { ms.Position = long.MinValue; result = TestResult.Fail; Log.Exception("Expected ArgumentOutOfRangeException"); } catch (ArgumentOutOfRangeException) { /* pass case */ } } } catch (Exception ex) { Log.Exception("Unexpected exception", ex); result = TestResult.Fail; } return result; } [TestMethod] public TestResult GetSetStaticBuffer() { TestResult result = TestResult.Pass; try { byte[] buffer = new byte[1000]; Log.Comment("Get/Set Position with static buffer"); using (MemoryStream ms = new MemoryStream(buffer)) { if (!GetSetPosition(ms, buffer.Length)) result = TestResult.Fail; } } catch (Exception ex) { Log.Exception("Unexpected exception", ex); result = TestResult.Fail; } return result; } [TestMethod] public TestResult GetSetDynamicBuffer() { TestResult result = TestResult.Pass; try { Log.Comment("Get/Set Position with dynamic buffer"); using (MemoryStream ms = new MemoryStream()) { if (!GetSetPosition(ms, 1000)) result = TestResult.Fail; } } catch (Exception ex) { Log.Exception("Unexpected exception", ex); result = TestResult.Fail; } return result; } #endregion Test Cases } } ================================================ FILE: Zelig/Zelig/Test/RunTime/NETMF/System/IO/MemoryStream/Read.cs ================================================ //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // Copyright (c) Microsoft Corporation. All rights reserved. //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// using System; using System.IO; using System.Text; namespace Microsoft.Zelig.Test { public class Read : TestBase, ITestInterface { [SetUp] public InitializeResult Initialize() { Log.Comment("Adding set up for the tests."); // TODO: Add your set up steps here. return InitializeResult.ReadyToGo; } [TearDown] public void CleanUp() { Log.Comment("Cleaning up after the tests."); // TODO: Add your clean up steps here. } public override TestResult Run( string[] args ) { TestResult result = TestResult.Pass; //result |= Assert.CheckFailed( InvalidCases( ) ); result |= Assert.CheckFailed( VanillaRead( ) ); return result; } #region Local Helper methods private bool TestRead(MemoryStream ms, int length) { return TestRead(ms, length, length, length); } private bool TestRead(MemoryStream ms, int BufferLength, int BytesToRead, int BytesExpected) { bool result = true; int nextbyte = (int)ms.Position % 256; byte[] byteBuffer = new byte[BufferLength]; int bytesRead = ms.Read(byteBuffer, 0, BytesToRead); if (bytesRead != BytesExpected) { result = false; Log.Exception("Expected " + BytesToRead + " bytes, but got " + bytesRead + " bytes"); } for (int i = 0; i < bytesRead; i++) { if (byteBuffer[i] != nextbyte) { result = false; Log.Exception("Byte in position " + i + " has wrong value: " + byteBuffer[i]); } // Reset if wraps past 255 if (++nextbyte > 255) nextbyte = 0; } return result; } #endregion Local Helper methods #region Test Cases [TestMethod] public TestResult InvalidCases() { TestResult result = TestResult.Pass; try { using (MemoryStream ms = new MemoryStream()) { Log.Comment("null Buffer"); try { int read = ms.Read(null, 0, 0); result = TestResult.Fail; Log.Exception("Expected ArgumentNullException, but read " + read + " bytes"); } catch (ArgumentNullException) { /* pass case */ } Log.Comment("negative offset"); try { int read = ms.Read(new byte[]{1}, -1, 0); result = TestResult.Fail; Log.Exception("Expected ArgumentOutOfRangeException, but read " + read + " bytes"); } catch (ArgumentOutOfRangeException) { /* pass case */ } Log.Comment("negative count"); try { int read = ms.Read(new byte[] { 1 }, 0, -1); result = TestResult.Fail; Log.Exception("Expected ArgumentOutOfRangeException, but read " + read + " bytes"); } catch (ArgumentOutOfRangeException) { /* pass case */ } Log.Comment("offset exceeds buffer size"); try { int read = ms.Read(new byte[] { 1 }, 2, 0); result = TestResult.Fail; Log.Exception("Expected ArgumentException, but read " + read + " bytes"); } catch (ArgumentException) { /* pass case */ } Log.Comment("count exceeds buffer size"); try { int read = ms.Read(new byte[] { 1 }, 0, 2); result = TestResult.Fail; Log.Exception("Expected ArgumentException, but read " + read + " bytes"); } catch (ArgumentException) { /* pass case */ } } MemoryStream ms2 = new MemoryStream(); MemoryStreamHelper.Write(ms2, 100); ms2.Seek(0, SeekOrigin.Begin); ms2.Close(); Log.Comment("Read from closed stream"); try { int readBytes = ms2.Read(new byte[] { 50 }, 0, 50); result = TestResult.Fail; Log.Exception("Expected ObjectDisposedException, but read " + readBytes + " bytes"); } catch (ObjectDisposedException) { /* pass case */ } } catch (Exception ex) { Log.Exception("Unexpected exception", ex); result = TestResult.Fail; } return result; } [TestMethod] public TestResult VanillaRead() { TestResult result = TestResult.Pass; try { using (MemoryStream ms = new MemoryStream()) { // Write to stream then reset to beginning MemoryStreamHelper.Write(ms, 1000); ms.Seek(0, SeekOrigin.Begin); Log.Comment("Read 256 bytes of data"); if (!TestRead(ms, 256)) result = TestResult.Fail; Log.Comment("Request less bytes then buffer"); if (!TestRead(ms, 256, 100, 100)) result = TestResult.Fail; // 1000 - 256 - 100 = 644 Log.Comment("Request more bytes then file"); if (!TestRead(ms, 1000, 1000, 644)) result = TestResult.Fail; Log.Comment("Request bytes after EOF"); if (!TestRead(ms, 100, 100, 0)) result = TestResult.Fail; Log.Comment("Rewind and read entire file in one buffer larger then file"); ms.Seek(0, SeekOrigin.Begin); if (!TestRead(ms, 1001, 1001, 1000)) result = TestResult.Fail; Log.Comment("Rewind and read from middle"); ms.Position = 500; if (!TestRead(ms, 256)) result = TestResult.Fail; Log.Comment("Read position after EOS"); ms.Position = ms.Length + 10; if (!TestRead(ms, 100, 100, 0)) result = TestResult.Fail; Log.Comment("Verify Read validation with UTF8 string"); ms.SetLength(0); string test = "MFFramework Test"; ms.Write(UTF8Encoding.UTF8.GetBytes(test), 0, test.Length); ms.Flush(); ms.Seek(0, SeekOrigin.Begin); byte[] readbuff = new byte[20]; int read = ms.Read(readbuff, 0, readbuff.Length); string testResult = new string(Encoding.UTF8.GetChars(readbuff, 0, read)); if (test != testResult) { result = TestResult.Fail; Log.Comment("Expected: " + test + ", but got: " + testResult); } } } catch (Exception ex) { Log.Exception("Unexpected exception", ex); result = TestResult.Fail; } return result; } #endregion Test Cases } } ================================================ FILE: Zelig/Zelig/Test/RunTime/NETMF/System/IO/MemoryStream/ReadByte.cs ================================================ //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // Copyright (c) Microsoft Corporation. All rights reserved. //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// using System; using System.IO; namespace Microsoft.Zelig.Test { public class ReadByte : TestBase, ITestInterface { [SetUp] public InitializeResult Initialize() { Log.Comment("Adding set up for the tests."); // TODO: Add your set up steps here. return InitializeResult.ReadyToGo; } [TearDown] public void CleanUp() { Log.Comment("Cleaning up after the tests."); // TODO: Add your clean up steps here. } public override TestResult Run( string[] args ) { TestResult result = TestResult.Pass; //result |= Assert.CheckFailed( InvalidCases( ) ); result |= Assert.CheckFailed( VanillaCases( ) ); return result; } #region Test Cases [TestMethod] public TestResult InvalidCases() { TestResult result = TestResult.Pass; try { MemoryStream ms2 = new MemoryStream(); MemoryStreamHelper.Write(ms2, 100); ms2.Seek(0, SeekOrigin.Begin); ms2.Close(); Log.Comment("Read from closed stream"); try { int readBytes = ms2.ReadByte(); result = TestResult.Fail; Log.Exception("Expected ObjectDisposedException, but read " + readBytes + " bytes"); } catch (ObjectDisposedException) { /* pass case */ } } catch (Exception ex) { Log.Exception("Unexpected exception", ex); result = TestResult.Fail; } return result; } [TestMethod] public TestResult VanillaCases() { TestResult result = TestResult.Pass; try { using (MemoryStream ms = new MemoryStream()) { MemoryStreamHelper.Write(ms, 256); ms.Position = 0; Log.Comment("ReadBytes and verify"); for (int i = 0; i < 256; i++) { int b = ms.ReadByte(); if (b != i) { result = TestResult.Fail; Log.Exception("Expected " + i + " but got " + b); } } Log.Comment("Bytes past EOS should return -1"); int rb = ms.ReadByte(); if (rb != -1) { result = TestResult.Fail; Log.Exception("Expected -1 but got " + rb); } } } catch (Exception ex) { Log.Exception("Unexpected exception", ex); result = TestResult.Fail; } return result; } #endregion Test Cases } } ================================================ FILE: Zelig/Zelig/Test/RunTime/NETMF/System/IO/MemoryStream/Seek.cs ================================================ //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // Copyright (c) Microsoft Corporation. All rights reserved. //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// using System; using System.IO; namespace Microsoft.Zelig.Test { public class Seek : TestBase, ITestInterface { [SetUp] public InitializeResult Initialize() { Log.Comment("Adding set up for the tests."); // TODO: Add your set up steps here. return InitializeResult.ReadyToGo; } [TearDown] public void CleanUp() { Log.Comment("Cleaning up after the tests."); // TODO: Add your clean up steps here. } public override TestResult Run( string[] args ) { TestResult result = TestResult.Pass; //result |= Assert.CheckFailed( InvalidCases( ) ); result |= Assert.CheckFailed( ValidCases( ) ); return result; } #region Helper methods private bool TestSeek(MemoryStream ms, long offset, SeekOrigin origin, long expectedPosition) { bool result = true; long seek = ms.Seek(offset, origin); if (seek != ms.Position && seek != expectedPosition) { result = false; Log.Exception("Unexpected seek results!"); Log.Exception("Expected position: " + expectedPosition); Log.Exception("Seek result: " + seek); Log.Exception("fs.Position: " + ms.Position); } return result; } private bool TestExtend(MemoryStream ms, long offset, SeekOrigin origin, long expectedPosition, long expectedLength) { bool result = TestSeek(ms, offset, origin, expectedLength); ms.WriteByte(1); if (ms.Length != expectedLength) { result = false; Log.Exception("Expected seek past end to change length to " + expectedLength + ", but its " + ms.Length); } return result; } #endregion Helper methods #region Test Cases [TestMethod] public TestResult InvalidCases() { MemoryStream fs = new MemoryStream(); MemoryStreamHelper.Write(fs, 1000); long seek; TestResult result = TestResult.Pass; try { try { Log.Comment("Seek -1 from Begin"); seek = fs.Seek(-1, SeekOrigin.Begin); result = TestResult.Fail; Log.Exception("Expected IOException, but got position " + seek); } catch (IOException) { /* pass case */ } try { Log.Comment("Seek -1001 from Current - at end from write"); seek = fs.Seek(-1001, SeekOrigin.Current); result = TestResult.Fail; Log.Exception("Expected IOException, but got position " + seek); } catch (IOException) { /* pass case */ } try { Log.Comment("Seek -1001 from End"); seek = fs.Seek(-1001, SeekOrigin.End); result = TestResult.Fail; Log.Exception("Expected IOException, but got position " + seek); } catch (IOException) { /* pass case */ } try { Log.Comment("Seek invalid -1 origin"); seek = fs.Seek(1, (SeekOrigin)(-1)); result = TestResult.Fail; Log.Exception("Expected ArgumentException, but got position " + seek); } catch (ArgumentException) { /* pass case */ } try { Log.Comment("Seek invalid 10 origin"); seek = fs.Seek(1, (SeekOrigin)10); result = TestResult.Fail; Log.Exception("Expected ArgumentException, but got position " + seek); } catch (ArgumentException) { /* pass case */ } try { Log.Comment("Seek with closed stream"); fs.Close(); seek = fs.Seek(0, SeekOrigin.Begin); result = TestResult.Fail; Log.Exception("Expected ObjectDisposedException, but got position " + seek); } catch (ObjectDisposedException) { /* pass case */ } try { Log.Comment("Seek with disposed stream"); fs.Dispose(); seek = fs.Seek(0, SeekOrigin.End); result = TestResult.Fail; Log.Exception("Expected ObjectDisposedException, but got position " + seek); } catch (ObjectDisposedException) { /* pass case */ } } catch (Exception ex) { Log.Exception("Unexpected exception: " + ex.Message); result = TestResult.Fail; } finally { if (fs != null) fs.Dispose(); } return result; } [TestMethod] public TestResult ValidCases() { TestResult result = TestResult.Pass; try { using (MemoryStream fs = new MemoryStream()) { MemoryStreamHelper.Write(fs, 1000); Log.Comment("Seek to beginning"); if (!TestSeek(fs, 0, SeekOrigin.Begin, 0)) result = TestResult.Fail; Log.Comment("Seek forward offset from begging"); if (!TestSeek(fs, 10, SeekOrigin.Begin, 0)) result = TestResult.Fail; Log.Comment("Seek backwards offset from current"); if (!TestSeek(fs, -5, SeekOrigin.Current, 5)) result = TestResult.Fail; Log.Comment("Seek forwards offset from current"); if (!TestSeek(fs, 20, SeekOrigin.Current, 25)) result = TestResult.Fail; Log.Comment("Seek to end"); if (!TestSeek(fs, 0, SeekOrigin.End, 1000)) result = TestResult.Fail; Log.Comment("Seek backwards offset from end"); if (!TestSeek(fs, -35, SeekOrigin.End, 965)) result = TestResult.Fail; Log.Comment("Seek past end relative to End"); if (!TestExtend(fs, 1, SeekOrigin.End, 1001, 1002)) result = TestResult.Fail; Log.Comment("Seek past end relative to Begin"); if (!TestExtend(fs, 1002, SeekOrigin.Begin, 1002, 1003)) result = TestResult.Fail; Log.Comment("Seek past end relative to Current"); if (!TestSeek(fs, 995, SeekOrigin.Begin, 995)) result = TestResult.Fail; if (!TestExtend(fs, 10, SeekOrigin.Current, 1005, 1006)) result = TestResult.Fail; // 1000 --123456 // verify 011001 Log.Comment("Verify proper bytes written at end (zero'd bytes from seek beyond end)"); byte[] buff = new byte[6]; byte[] verify = new byte[] { 0, 1, 1, 0, 0, 1 }; fs.Seek(-6, SeekOrigin.End); fs.Read(buff, 0, buff.Length); for (int i = 0; i < buff.Length; i++) { if (buff[i] != verify[i]) { result = TestResult.Fail; Log.Comment("Position " + i + ":" + buff[i] + " != " + verify[i]); } } } } catch (Exception ex) { Log.Exception("Unexpected exception: " + ex.Message); result = TestResult.Fail; } return result; } #endregion Test Cases } } ================================================ FILE: Zelig/Zelig/Test/RunTime/NETMF/System/IO/MemoryStream/SetLength.cs ================================================ //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // Copyright (c) Microsoft Corporation. All rights reserved. //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// using System; using System.IO; namespace Microsoft.Zelig.Test { public class SetLength : TestBase, ITestInterface { [SetUp] public InitializeResult Initialize() { Log.Comment("Adding set up for the tests."); // TODO: Add your set up steps here. return InitializeResult.ReadyToGo; } [TearDown] public void CleanUp() { Log.Comment("Cleaning up after the tests."); // TODO: Add your clean up steps here. } public override TestResult Run( string[] args ) { TestResult result = TestResult.Pass; //result |= Assert.CheckFailed( ObjectDisposed( ) ); result |= Assert.CheckFailed( LengthTests( ) ); //result |= Assert.CheckFailed( InvalidSetLength( ) ); return result; } #region Helper methods private bool TestLength(MemoryStream ms, long expectedLength) { if (ms.Length != expectedLength) { Log.Exception("Expected length " + expectedLength + " but got, " + ms.Length); return false; } return true; } private bool TestPosition(MemoryStream ms, long expectedPosition) { if (ms.Position != expectedPosition) { Log.Exception("Expected position " + expectedPosition + " but got, " + ms.Position); return false; } return true; } #endregion Helper methods #region Test Cases [TestMethod] public TestResult ObjectDisposed() { MemoryStream ms = new MemoryStream(); ms.Close(); TestResult result = TestResult.Pass; try { try { long length = ms.Length; result = TestResult.Fail; Log.Exception("Expected ObjectDisposedException, but got length " + length); } catch (ObjectDisposedException) { /*Pass Case */ } } catch (Exception ex) { Log.Exception("Unexpected exception: " + ex.Message); result = TestResult.Fail; } return result; } [TestMethod] public TestResult LengthTests() { TestResult result = TestResult.Pass; try { using (MemoryStream ms = new MemoryStream()) { Log.Comment("Set initial length to 50, and position to 50"); ms.SetLength(50); ms.Position = 50; if (!TestLength(ms, 50)) result = TestResult.Fail; Log.Comment("Write 'foo bar'"); StreamWriter sw = new StreamWriter(ms); sw.Write("foo bar"); sw.Flush(); if (!TestLength(ms, 57)) result = TestResult.Fail; Log.Comment("Shorten Length to 30"); ms.SetLength(30); if (!TestLength(ms, 30)) result = TestResult.Fail; Log.Comment("Verify position was adjusted"); if (!TestPosition(ms, 30)) result = TestResult.Fail; Log.Comment("Extend length to 100"); ms.SetLength(100); if (!TestLength(ms, 100)) result = TestResult.Fail; } } catch (Exception ex) { Log.Exception("Unexpected exception: " + ex.Message); result = TestResult.Fail; } return result; } [TestMethod] public TestResult InvalidSetLength() { TestResult result = TestResult.Pass; try { using (MemoryStream ms = new MemoryStream()) { try { Log.Comment("-1"); ms.SetLength(-1); result = TestResult.Fail; Log.Exception("Expected ArgumentOutOfRangeException, but set length"); } catch (ArgumentOutOfRangeException) { /* Pass Case */ } try { Log.Comment("-10000"); ms.SetLength(-10000); result = TestResult.Fail; Log.Exception("Expected ArgumentOutOfRangeException, but set length"); } catch (ArgumentOutOfRangeException) { /* Pass Case */ } try { Log.Comment("long.MinValue"); ms.SetLength(long.MinValue); result = TestResult.Fail; Log.Exception("Expected ArgumentOutOfRangeException, but set length"); } catch (ArgumentOutOfRangeException) { /* Pass Case */ } try { Log.Comment("long.MaxValue"); ms.SetLength(long.MaxValue); result = TestResult.Fail; Log.Exception("Expected IOException, but set length"); } catch (ArgumentOutOfRangeException) { /* Pass Case */ } } } catch (Exception ex) { Log.Exception("Unexpected exception: " + ex.Message); result = TestResult.Fail; } return result; } #endregion Test Cases } } ================================================ FILE: Zelig/Zelig/Test/RunTime/NETMF/System/IO/MemoryStream/ToArray.cs ================================================ //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // Copyright (c) Microsoft Corporation. All rights reserved. //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// using System; using System.IO; namespace Microsoft.Zelig.Test { public class ToArray : TestBase, ITestInterface { [SetUp] public InitializeResult Initialize() { Log.Comment("Adding set up for the tests."); // TODO: Add your set up steps here. return InitializeResult.ReadyToGo; } [TearDown] public void CleanUp() { Log.Comment("Cleaning up after the tests."); // TODO: Add your clean up steps here. } public override TestResult Run( string[] args ) { TestResult result = TestResult.Pass; result |= Assert.CheckFailed( Ctor_ToArray( ) ); result |= Assert.CheckFailed( VerifyValues( ) ); result |= Assert.CheckFailed( ChangeLengths( ) ); return result; } #region Helper methods private bool VerifyArray(byte[] data, int expected) { bool result = true; Log.Comment("Verify Length"); if (data.Length != expected) { result = false; Log.Exception("Expected " + expected + " bytes, but got " + data.Length); } Log.Comment("Verify pattern in array"); int nextbyte = 0; for (int i = 0; i < data.Length; i++) { if (data[i] != nextbyte) { result = false; Log.Exception("Byte in position " + i + " has wrong value: " + data[i]); } // Reset if wraps past 255 if (++nextbyte > 255) nextbyte = 0; } return result; } #endregion Helper methods #region Test Cases [TestMethod] public TestResult Ctor_ToArray() { TestResult result = TestResult.Pass; try { Log.Comment("Dynamic Stream"); using (MemoryStream ms = new MemoryStream()) { byte[] stream = ms.ToArray(); if (stream.Length != 0) { result = TestResult.Fail; Log.Exception("Expected length 0, but got length " + stream.Length); } } Log.Comment("Static Stream"); using (MemoryStream ms = new MemoryStream(new byte[512])) { byte[] stream = ms.ToArray(); if (stream.Length != 512) { result = TestResult.Fail; Log.Exception("Expected length 512, but got length " + stream.Length); } } } catch (Exception ex) { Log.Exception("Unexpected exception", ex); result = TestResult.Fail; } return result; } [TestMethod] public TestResult VerifyValues() { TestResult result = TestResult.Pass; try { Log.Comment("Verify Data"); using (MemoryStream ms = new MemoryStream()) { Log.Comment("Write 1000 bytes in specific pattern"); MemoryStreamHelper.Write(ms, 1000); byte[] stream = ms.ToArray(); if (!VerifyArray(stream, 1000)) result = TestResult.Fail; } } catch (Exception ex) { Log.Exception("Unexpected exception", ex); result = TestResult.Fail; } return result; } [TestMethod] public TestResult ChangeLengths() { TestResult result = TestResult.Pass; try { Log.Comment("Verify array is still valid after truncation (copy array)"); using (MemoryStream ms = new MemoryStream()) { MemoryStreamHelper.Write(ms, 1000); ms.SetLength(200); ms.Flush(); byte[] stream = ms.ToArray(); if (!VerifyArray(stream, 200)) result = TestResult.Fail; } } catch (Exception ex) { Log.Exception("Unexpected exception", ex); result = TestResult.Fail; } return result; } #endregion Test Cases } } ================================================ FILE: Zelig/Zelig/Test/RunTime/NETMF/System/IO/MemoryStream/Write.cs ================================================ //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // Copyright (c) Microsoft Corporation. All rights reserved. //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// #define TEST_EXCEPTIONS using System; using System.IO; using System.Text; namespace Microsoft.Zelig.Test { public class Write : TestBase, ITestInterface { [SetUp] public InitializeResult Initialize() { Log.Comment("Adding set up for the tests."); // TODO: Add your set up steps here. return InitializeResult.ReadyToGo; } [TearDown] public void CleanUp() { Log.Comment("Cleaning up after the tests."); // TODO: Add your clean up steps here. } //TODO Test with position longer then length public override TestResult Run( string[] args ) { TestResult result = TestResult.Pass; result |= Assert.CheckFailed( InvalidCases( ) ); result |= Assert.CheckFailed( VanillaWrite_Dynamic_Ctor( ) ); result |= Assert.CheckFailed( VanillaWrite_Static_Ctor( ) ); result |= Assert.CheckFailed( ShiftBuffer( ) ); result |= Assert.CheckFailed( BoundaryCheck( ) ); return result; } #region Local Helper methods private bool TestWrite(MemoryStream ms, int length) { return TestWrite(ms, length, length, 0); } private bool TestWrite(MemoryStream ms, int length, long ExpectedLength) { return TestWrite(ms, length, length, 0, ExpectedLength); } private bool TestWrite(MemoryStream ms, int BufferLength, int BytesToWrite, int Offset) { return TestWrite(ms, BufferLength, BytesToWrite, Offset, ms.Position + BytesToWrite); } private bool TestWrite(MemoryStream ms, int BufferLength, int BytesToWrite, int Offset, long ExpectedLength) { bool result = true; long startLength = ms.Position; long nextbyte = startLength % 256; byte[] byteBuffer = new byte[BufferLength]; for (int i = Offset; i < (Offset + BytesToWrite); i++) { byteBuffer[i] = (byte)nextbyte; // Reset if wraps past 255 if (++nextbyte > 255) nextbyte = 0; } ms.Write(byteBuffer, Offset, BytesToWrite); ms.Flush(); if (ExpectedLength < ms.Length) { result = false; Log.Exception("Expected final length of " + ExpectedLength + " bytes, but got " + ms.Length + " bytes"); } return result; } #endregion Local Helper methods #region Test Cases [TestMethod] public TestResult InvalidCases() { MemoryStream fs = new MemoryStream(); byte[] writebuff = new byte[1024]; TestResult result = TestResult.Pass; try { try { Log.Comment("Write to null buffer"); fs.Write(null, 0, writebuff.Length); result = TestResult.Fail; Log.Exception("Expected ArgumentNullException"); } catch (ArgumentNullException) { /* pass case */ } try { Log.Comment("Write to negative offset"); fs.Write(writebuff, -1, writebuff.Length); result = TestResult.Fail; Log.Exception("Expected ArgumentOutOfRangeException"); } catch (ArgumentOutOfRangeException) { /* pass case */ } try { Log.Comment("Write to out of range offset"); fs.Write(writebuff, writebuff.Length + 1, writebuff.Length); result = TestResult.Fail; Log.Exception("Expected ArgumentException"); } catch (ArgumentException) { /* pass case */ } try { Log.Comment("Write negative count"); fs.Write(writebuff, 0, -1); result = TestResult.Fail; // previous Bug # 21669 Log.Exception("Expected ArgumentOutOfRangeException"); } catch (ArgumentOutOfRangeException) { /* pass case */ } try { Log.Comment("Write count larger then buffer"); fs.Write(writebuff, 0, writebuff.Length + 1); result = TestResult.Fail; Log.Exception("Expected ArgumentException"); } catch (ArgumentException) { /* pass case */ } try { Log.Comment("Write closed stream"); fs.Close(); fs.Write(writebuff, 0, writebuff.Length); result = TestResult.Fail; Log.Exception("Expected ObjectDisposedException"); } catch (ObjectDisposedException) { /* pass case */ } try { Log.Comment("Write disposed stream"); fs = new MemoryStream(); fs.Dispose(); fs.Write(writebuff, 0, writebuff.Length); result = TestResult.Fail; Log.Exception("Expected ObjectDisposedException"); } catch (ObjectDisposedException) { /* pass case */ } } catch (Exception ex) { Log.Exception("Unexpected exception: " + ex.Message); result = TestResult.Fail; } finally { if (fs != null) fs.Dispose(); } return result; } [TestMethod] public TestResult VanillaWrite_Dynamic_Ctor() { TestResult result = TestResult.Pass; try { using (MemoryStream ms = new MemoryStream()) { Log.Comment("Write 256 bytes of data"); if (!TestWrite(ms, 256)) result = TestResult.Fail; Log.Comment("Write middle of buffer"); if (!TestWrite(ms, 256, 100, 100)) result = TestResult.Fail; // 1000 - 256 - 100 = 644 Log.Comment("Write start of buffer"); if (!TestWrite(ms, 1000, 644, 0)) result = TestResult.Fail; Log.Comment("Write end of buffer"); if (!TestWrite(ms, 1000, 900, 100)) result = TestResult.Fail; Log.Comment("Rewind and verify all bytes written"); ms.Seek(0, SeekOrigin.Begin); if (!MemoryStreamHelper.VerifyRead(ms)) result = TestResult.Fail; Log.Comment("Verify Read validation with UTF8 string"); ms.SetLength(0); string test = "MFFramework Test"; ms.Write(UTF8Encoding.UTF8.GetBytes(test), 0, test.Length); ms.Flush(); ms.Seek(0, SeekOrigin.Begin); byte[] readbuff = new byte[20]; int read = ms.Read(readbuff, 0, readbuff.Length); string testResult = new string(Encoding.UTF8.GetChars(readbuff, 0, read)); if (test != testResult) { result = TestResult.Fail; Log.Comment("Expected: " + test + ", but got: " + testResult); } } } catch (Exception ex) { Log.Exception("Unexpected exception: " + ex.Message); result = TestResult.Fail; } return result; } [TestMethod] public TestResult VanillaWrite_Static_Ctor() { TestResult result = TestResult.Pass; try { byte[] buffer = new byte[1024]; using (MemoryStream ms = new MemoryStream(buffer)) { Log.Comment("Write 256 bytes of data"); if (!TestWrite(ms, 256, 1024)) result = TestResult.Fail; Log.Comment("Write middle of buffer"); if (!TestWrite(ms, 256, 100, 100, 1024)) result = TestResult.Fail; // 1000 - 256 - 100 = 644 Log.Comment("Write start of buffer"); if (!TestWrite(ms, 1000, 644, 0, 1024)) result = TestResult.Fail; #if TEST_EXCEPTIONS Log.Comment("Write past end of buffer"); try { TestWrite(ms, 50, 1024); result = TestResult.Fail; Log.Exception("Expected NotSupportedException"); } catch (NotSupportedException) { /* pass case */ } #endif Log.Comment("Verify failed Write did not move position"); if (ms.Position != 1000) { result = TestResult.Fail; Log.Comment("Expected position to be 1000, but it is " + ms.Position); } Log.Comment("Write final 24 bytes of static buffer"); if (!TestWrite(ms, 24)) result = TestResult.Fail; Log.Comment("Rewind and verify all bytes written"); ms.Seek(0, SeekOrigin.Begin); if (!MemoryStreamHelper.VerifyRead(ms)) result = TestResult.Fail; Log.Comment("Verify Read validation with UTF8 string"); ms.SetLength(0); string test = "MFFramework Test"; ms.Write(UTF8Encoding.UTF8.GetBytes(test), 0, test.Length); ms.Flush(); ms.Seek(0, SeekOrigin.Begin); byte[] readbuff = new byte[20]; int read = ms.Read(readbuff, 0, readbuff.Length); string testResult = new string(Encoding.UTF8.GetChars(readbuff, 0, read)); if (test != testResult) { result = TestResult.Fail; Log.Comment("Expected: " + test + ", but got: " + testResult); } } } catch (Exception ex) { Log.Exception("Unexpected exception: " + ex.Message); result = TestResult.Fail; } return result; } [TestMethod] public TestResult ShiftBuffer() { TestResult result = TestResult.Pass; try { int bufSize; int iCountErrors = 0; for (int i = 1; i < 10; i++) { bufSize = i; MemoryStream ms = new MemoryStream(); for (int j = 0; j < bufSize; ++j) ms.WriteByte((byte)j); // Move everything forward by 1 byte ms.Seek(0, SeekOrigin.Begin); byte[] buf = ms.ToArray(); ms.Write(buf, 1, bufSize - 1); ms.Seek(0, SeekOrigin.Begin); //we'll read till one before the last since these should be shifted by 1 for (int j = 0; j < ms.Length - 1; ++j) { int bit = ms.ReadByte(); if (bit != j + 1) { ++iCountErrors; Log.Exception("Err_8324t! Check VSWhdibey #458551, Returned: " + bit + ", Expected: " + (j + 1)); } } //last bit should be the same if (ms.ReadByte() != i - 1) { ++iCountErrors; Log.Exception("Err_32947gs! Last bit is not correct Check VSWhdibey #458551"); } } //Buffer sizes of 9 (10 here since we shift by 1) and above doesn't have the above 'optimization' problem for (int i = 10; i < 64; i++) { bufSize = i; MemoryStream ms = new MemoryStream(); for (int j = 0; j < bufSize; ++j) ms.WriteByte((byte)j); // Move everything forward by 1 byte ms.Seek(0, SeekOrigin.Begin); byte[] buf = ms.ToArray(); ms.Write(buf, 1, bufSize - 1); ms.Seek(0, SeekOrigin.Begin); for (int j = 0; j < ms.Length; ++j) { int bit = ms.ReadByte(); if (j != ms.Length - 1) { if (bit != (j + 1)) { ++iCountErrors; Log.Exception("Err_235radg_" + i + "! Check VSWhdibey #458551, Returned: " + bit + ", Expected: " + (j + 1)); } } else if (bit != j) { ++iCountErrors; Log.Exception("Err_235radg_" + i + "! Check VSWhdibey #458551, Returned: " + bit + ", Expected:" + (j + 1)); } } } if (iCountErrors > 0) result = TestResult.Fail; } catch (Exception ex) { Log.Exception("Unexpected exception: " + ex.Message); result = TestResult.Fail; } return result; } [TestMethod] public TestResult BoundaryCheck() { TestResult result = TestResult.Pass; try { for (int i = 250; i < 260; i++) { using (MemoryStream ms = new MemoryStream()) { TestWrite(ms, i); ms.Position = 0; if (!MemoryStreamHelper.VerifyRead(ms)) result = TestResult.Fail; Log.Comment("Position: " + ms.Position); Log.Comment("Length: " + ms.Length); if (i != ms.Position | i != ms.Length) { result = TestResult.Fail; Log.Exception("Expected Position and Length to be " + i); } } } } catch (Exception ex) { Log.Exception("Unexpected exception: " + ex.Message); result = TestResult.Fail; } return result; } #endregion Test Cases } } ================================================ FILE: Zelig/Zelig/Test/RunTime/NETMF/System/IO/MemoryStream/WriteByte.cs ================================================ //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // Copyright (c) Microsoft Corporation. All rights reserved. //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// #define TEST_EXCEPTIONS using System; using System.IO; namespace Microsoft.Zelig.Test { public class WriteByte : TestBase, ITestInterface { [SetUp] public InitializeResult Initialize() { Log.Comment("Adding set up for the tests."); // TODO: Add your set up steps here. return InitializeResult.ReadyToGo; } [TearDown] public void CleanUp() { Log.Comment("Cleaning up after the tests."); // TODO: Add your clean up steps here. } public override TestResult Run( string[] args ) { TestResult result = TestResult.Pass; result |= Assert.CheckFailed( ExtendBuffer( ) ); result |= Assert.CheckFailed( InvalidRange( ) ); result |= Assert.CheckFailed( VanillaWrite( ) ); result |= Assert.CheckFailed( BoundaryCheck( ) ); return result; } #region Helper methods private bool TestWrite(MemoryStream ms, int BytesToWrite) { return TestWrite(ms, BytesToWrite, ms.Position + BytesToWrite); } private bool TestWrite(MemoryStream ms, int BytesToWrite, long ExpectedLength) { bool result = true; long startLength = ms.Position; long nextbyte = startLength % 256; for (int i = 0; i < BytesToWrite; i++) { ms.WriteByte((byte)nextbyte); // Reset if wraps past 255 if (++nextbyte > 255) nextbyte = 0; } ms.Flush(); if (ExpectedLength < ms.Length) { result = false; Log.Exception("Expeceted final length of " + ExpectedLength + " bytes, but got " + ms.Length + " bytes"); } return result; } #endregion Helper methods #region Test Cases [TestMethod] public TestResult ExtendBuffer() { TestResult result = TestResult.Pass; try { using (MemoryStream ms = new MemoryStream()) { Log.Comment("Set Position past end of stream"); // Internal buffer is initialized to 256, if this changes, this test is no longer valid. // Exposing capcity would have made this test easier/dynamic. ms.Position = 300; ms.WriteByte(123); if (ms.Length != 301) { result = TestResult.Fail; Log.Exception("Expected length 301, got length " + ms.Length); } ms.Position = 300; int read = ms.ReadByte(); if (read != 123) { result = TestResult.Fail; Log.Exception("Expected value 123, but got value " + result); } } } catch (Exception ex) { Log.Exception("Unexpected exception", ex); result = TestResult.Fail; } return result; } [TestMethod] public TestResult InvalidRange() { TestResult result = TestResult.Pass; try { byte[] buffer = new byte[100]; using (MemoryStream ms = new MemoryStream(buffer)) { Log.Comment("Set Position past end of static stream"); ms.Position = buffer.Length + 1; try { ms.WriteByte(1); result = TestResult.Fail; Log.Exception("Expected NotSupportedException"); } catch (NotSupportedException) { /* pass case */ } } } catch (Exception ex) { Log.Exception("Unexpected exception", ex); result = TestResult.Fail; } return result; } [TestMethod] public TestResult VanillaWrite() { TestResult result = TestResult.Pass; try { Log.Comment("Static Buffer"); byte[] buffer = new byte[100]; using (MemoryStream ms = new MemoryStream(buffer)) { Log.Comment("Write 50 bytes of data"); if (!TestWrite(ms, 50, 100)) result = TestResult.Fail; Log.Comment("Write final 50 bytes of data"); if (!TestWrite(ms, 50, 100)) result = TestResult.Fail; #if TEST_EXCEPTIONS Log.Comment("Any more bytes written should throw"); try { ms.WriteByte(50); result = TestResult.Fail; Log.Exception("Expected NotSupportedException"); } catch (NotSupportedException) { /* pass case */ } #endif Log.Comment("Rewind and verify all bytes written"); ms.Seek(0, SeekOrigin.Begin); if (!MemoryStreamHelper.VerifyRead(ms)) result = TestResult.Fail; } Log.Comment("Dynamic Buffer"); using (MemoryStream ms = new MemoryStream()) { Log.Comment("Write 100 bytes of data"); if (!TestWrite(ms, 100)) result = TestResult.Fail; Log.Comment("Extend internal buffer, write 160"); if (!TestWrite(ms, 160)) result = TestResult.Fail; Log.Comment("Double extend internal buffer, write 644"); if (!TestWrite(ms, 644)) result = TestResult.Fail; Log.Comment("write another 1100"); if (!TestWrite(ms, 1100)) result = TestResult.Fail; Log.Comment("Rewind and verify all bytes written"); ms.Seek(0, SeekOrigin.Begin); if (!MemoryStreamHelper.VerifyRead(ms)) result = TestResult.Fail; } } catch (Exception ex) { Log.Exception("Unexpected exception", ex); result = TestResult.Fail; } return result; } [TestMethod] public TestResult BoundaryCheck() { TestResult result = TestResult.Pass; try { for (int i = 250; i < 260; i++) { using (MemoryStream ms = new MemoryStream()) { MemoryStreamHelper.Write(ms, i); ms.Position = 0; if (!MemoryStreamHelper.VerifyRead(ms)) result = TestResult.Fail; Log.Comment("Position: " + ms.Position); Log.Comment("Length: " + ms.Length); if (i != ms.Position | i != ms.Length) { result = TestResult.Fail; Log.Exception("Expected Position and Length to be " + i); } } } } catch (Exception ex) { Log.Exception("Unexpected exception: " + ex.Message); result = TestResult.Fail; } return result; } #endregion Test Cases } } ================================================ FILE: Zelig/Zelig/Test/RunTime/NETMF/System/IO/MemoryStream/WriteTo.cs ================================================ //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // Copyright (c) Microsoft Corporation. All rights reserved. //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// using System; using System.IO; namespace Microsoft.Zelig.Test { public class WriteTo : TestBase, ITestInterface { private bool _fileSystemInit; [SetUp] public InitializeResult Initialize() { // These tests rely on underlying file system so we need to make // sure we can format it before we start the tests. If we can't // format it, then we assume there is no FS to test on this platform. //////// delete the directory DOTNETMF_FS_EMULATION //////try //////{ ////// IOTests.IntializeVolume(); ////// _fileSystemInit = true; //////} //////catch (Exception ex) //////{ ////// Log.Exception("Skipping: Unable to initialize file system", ex); ////// _fileSystemInit = false; //////} return InitializeResult.ReadyToGo; } [TearDown] public void CleanUp() { Log.Comment("Cleaning up after the tests."); // TODO: Add your clean up steps here. } public override TestResult Run( string[] args ) { TestResult result = TestResult.Pass; //result |= Assert.CheckFailed( InvalidArgs( ) ); //result |= Assert.CheckFailed( WriteTo_FileStream( ) ); result |= Assert.CheckFailed( WriteTo_MemoryStream( ) ); return result; } #region Test Cases [TestMethod] public TestResult InvalidArgs() { TestResult result = TestResult.Pass; try { using (MemoryStream ms = new MemoryStream()) { Log.Comment("Initialize stream"); MemoryStreamHelper.Write(ms, 1000); try { Log.Comment("null stream"); ms.WriteTo(null); result = TestResult.Fail; Log.Exception("Expected ArgumentNullException"); } catch (ArgumentNullException) { /* pass case */ } if (_fileSystemInit) { try { Log.Comment("pass in read-only stream"); using (FileStream fs = new FileStream("readonly", FileMode.OpenOrCreate, FileAccess.Read)) { ms.WriteTo(fs); } } catch (NotSupportedException) { /* pass case */ } } try { Log.Comment("Target Stream closed"); MemoryStream mst = new MemoryStream(); mst.Close(); ms.WriteTo(mst); result = TestResult.Fail; Log.Exception("Expected ObjectDisposedException"); } catch (ObjectDisposedException) { /* pass case */ } try { Log.Comment("Current Stream closed"); ms.Close(); using (MemoryStream mst = new MemoryStream()) { ms.WriteTo(mst); result = TestResult.Fail; Log.Exception("Expected ObjectDisposedException"); } } catch (ObjectDisposedException) { /* pass case */ } } } catch (Exception ex) { Log.Exception("Unexpected exception", ex); result = TestResult.Fail; } return result; } [TestMethod] public TestResult WriteTo_FileStream() { // Don't run test if no FileSystem if (!_fileSystemInit) return TestResult.Skip; TestResult result = TestResult.Pass; string fileName = "WriteTo_FileStream.txt"; try { using (MemoryStream ms = new MemoryStream()) { Log.Comment("Initialize stream with 1234 bytes"); MemoryStreamHelper.Write(ms, 1234); using (FileStream fs = new FileStream(fileName, FileMode.Create)) { Log.Comment("WriteTo FileStream"); ms.WriteTo(fs); } Log.Comment("Verify closed file"); using (FileStream fs = new FileStream(fileName, FileMode.Open)) { if (fs.Length != 1234) { result = TestResult.Fail; Log.Exception("Expected 1234 bytes, but got " + fs.Length); } if (!MemoryStreamHelper.VerifyRead(fs)) result = TestResult.Fail; } } } catch (Exception ex) { Log.Exception("Unexpected exception", ex); result = TestResult.Fail; } return result; } [TestMethod] public TestResult WriteTo_MemoryStream() { TestResult result = TestResult.Pass; try { using (MemoryStream ms = new MemoryStream()) { Log.Comment("Initialize stream with 1234 bytes"); MemoryStreamHelper.Write(ms, 1234); using (MemoryStream ms2 = new MemoryStream()) { Log.Comment("WriteTo MemoryStream"); ms.WriteTo(ms2); Log.Comment("Verify 2nd MemoryStream"); if (ms2.Length != 1234) { result = TestResult.Fail; Log.Exception("Expected 1234 bytes, but got " + ms2.Length); } ms2.Position = 0; if (!MemoryStreamHelper.VerifyRead(ms2)) result = TestResult.Fail; } } } catch (Exception ex) { Log.Exception("Unexpected exception", ex); result = TestResult.Fail; } return result; } #endregion Test Cases } } ================================================ FILE: Zelig/Zelig/Test/RunTime/NETMF/System/Test_System.csproj ================================================  Debug AnyCPU {54125FC8-5C6D-4F4B-92B8-3377FE1D92E1} Library Properties Microsoft.Zelig.Test Test_mscorlib Microsoft.Zelig.Test.Runtime.Test_System v4.5 512 true full true ..\..\..\..\..\ZeligBuild\Target\bin\Debug\ DEBUG;TRACE prompt 4 CS0108; CS0162; CS0219; ; CS0164; CS0219; CS0649; CS0414; CS0169; CS0114; CS0251 full true ..\..\..\..\..\ZeligBuild\Target\bin\Release\ DEBUG;TRACE prompt 4 true CS0108; CS0162; CS0219; ; CS0164; CS0219; CS0649; CS0414; CS0169; CS0114; CS0251 {e77ac86e-58ab-47b6-bc6d-3c1b4545cdfd} Microsoft.Llilum.Lwip {186f31a3-ef89-4a25-b2d5-20070702aa01} system {186f31a3-ef89-4a25-b2d5-20080628aa01} system_core {b649b569-516b-4c88-a7b1-ebd02e12dd99} Test_Common ================================================ FILE: Zelig/Zelig/Test/RunTime/NETMF/System/Text/StringBuilder/StringBuilderTests.cs ================================================ //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // Copyright (c) Microsoft Corporation. All rights reserved. //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// using System; namespace Microsoft.Zelig.Test { public class StringBuilderTests : TestBase, ITestInterface { [SetUp] public InitializeResult Initialize() { return InitializeResult.ReadyToGo; } [TearDown] public void CleanUp() { } #region Fields System.Text.StringBuilder stringBuilder = new System.Text.StringBuilder(); #endregion public override TestResult Run( string[] args ) { TestResult result = TestResult.Pass; string testName = "Test_0_AppendTest_"; result |= Assert.CheckFailed(Test_0_AppendTest_0(), testName, 0); testName = "Test_1_RemoveTest_"; result |= Assert.CheckFailed(Test_1_RemoveTest_0(), testName, 0); testName = "Test_2_InsertTest_"; //result |= Assert.CheckFailed(Test_2_InsertTest_0(), testName, 0); // https://github.com/NETMF/llilum/issues/109, https://github.com/NETMF/llilum/issues/108 testName = "Test_3_ReplaceTest_"; result |= Assert.CheckFailed(Test_3_ReplaceTest_0(), testName, 0); result |= Assert.CheckFailed(Test_3_ReplaceTest_1(), testName, 1); result |= Assert.CheckFailed(Test_3_ReplaceTest_2(), testName, 2); result |= Assert.CheckFailed(Test_3_ReplaceTest_3(), testName, 3); result |= Assert.CheckFailed(Test_3_ReplaceTest_4(), testName, 4); result |= Assert.CheckFailed(Test_3_ReplaceTest_5(), testName, 5); result |= Assert.CheckFailed(Test_3_ReplaceTest_6(), testName, 6); //result |= Assert.CheckFailed(Test_3_ReplaceTest_7(), testName, 7); testName = "Test_4_CapacityTest_"; result |= Assert.CheckFailed(Test_4_CapacityTest_0(), testName, 0); return result; } #region Append Tests [TestMethod] public TestResult Test_0_AppendTest_0() { bool result = false; stringBuilder.Append(true); result = stringBuilder.ToString() == Boolean.TrueString; if (!result) { return TestResult.Fail; } stringBuilder.Append(false); result = stringBuilder.ToString() == string.Concat(Boolean.TrueString, Boolean.FalseString); if (!result) { return TestResult.Fail; } stringBuilder.Append(byte.MinValue); result = stringBuilder.ToString() == string.Concat(Boolean.TrueString, Boolean.FalseString, byte.MinValue); if (!result) { return TestResult.Fail; } stringBuilder.Append(new char[] { 'x', 'a' }); result = stringBuilder.ToString() == string.Concat(Boolean.TrueString, Boolean.FalseString, byte.MinValue, "xa"); if (!result) { return TestResult.Fail; } stringBuilder.Append(double.Epsilon); result = stringBuilder.ToString() == string.Concat(Boolean.TrueString, Boolean.FalseString, byte.MinValue, "xa", double.Epsilon.ToString()); if (!result) { return TestResult.Fail; } stringBuilder.Append(float.Epsilon); result = stringBuilder.ToString() == string.Concat(Boolean.TrueString, Boolean.FalseString, byte.MinValue, "xa", double.Epsilon.ToString(), float.Epsilon.ToString()); if (!result) { return TestResult.Fail; } stringBuilder.Append(int.MaxValue); result = stringBuilder.ToString() == string.Concat(Boolean.TrueString, Boolean.FalseString, byte.MinValue, "xa", double.Epsilon.ToString(), float.Epsilon.ToString(), int.MaxValue); if (!result) { return TestResult.Fail; } stringBuilder.Append(long.MaxValue); result = stringBuilder.ToString() == string.Concat(Boolean.TrueString, Boolean.FalseString, byte.MinValue, "xa", double.Epsilon.ToString(), float.Epsilon.ToString(), int.MaxValue, long.MaxValue); if (!result) { return TestResult.Fail; } stringBuilder.Append((object)"string"); result = stringBuilder.ToString() == string.Concat(Boolean.TrueString, Boolean.FalseString, byte.MinValue, "xa", double.Epsilon.ToString(), float.Epsilon.ToString(), int.MaxValue, long.MaxValue, "string"); if (!result) { return TestResult.Fail; } return (result == true) ? TestResult.Pass : TestResult.Fail; } #endregion #region Remove Tests [TestMethod] public TestResult Test_1_RemoveTest_0() { bool result = false; result = stringBuilder.Clear().ToString() == string.Empty; if (!result) { return TestResult.Fail; } string testString = "0123456789"; stringBuilder.Append(testString); stringBuilder.Remove(0, 1); result = stringBuilder.ToString() == "123456789"; if (!result) { return TestResult.Fail; } stringBuilder.Remove(stringBuilder.Length - 1, 1); result = stringBuilder.ToString() == "12345678"; if (!result) { return TestResult.Fail; } return (result == true) ? TestResult.Pass : TestResult.Fail; } #endregion #region Insert Tests [TestMethod] public TestResult Test_2_InsertTest_0() { stringBuilder.Clear(); bool result = false; string testString = "0000"; stringBuilder.Append(testString); stringBuilder.Insert(0, "x", 2); result = stringBuilder.ToString() == "xx0000"; if (!result) return TestResult.Fail; stringBuilder.Insert(stringBuilder.Length, "x", 2); result = stringBuilder.ToString() == "xx0000xx"; return (result == false) ? TestResult.Fail : TestResult.Pass; } #endregion #region Replace Tests [TestMethod] public TestResult Test_3_ReplaceTest_0() { stringBuilder.Clear(); bool result = false; string testString = "0000"; stringBuilder.Append(testString); stringBuilder.Append("_"); stringBuilder.Append(testString); stringBuilder.Replace(testString, "xx"); result = stringBuilder.ToString() == "xx_xx"; return (result == false) ? TestResult.Fail : TestResult.Pass; } [TestMethod] public TestResult Test_3_ReplaceTest_1() { stringBuilder.Clear(); bool result = false; string testString = "BEGIN"; //stringBuilder.Append("BEGIN_MID_END"); stringBuilder.Append('B'); stringBuilder.Append('E'); stringBuilder.Append('G'); stringBuilder.Append('I'); stringBuilder.Append('N'); stringBuilder.Append('_'); stringBuilder.Append('M'); stringBuilder.Append('I'); stringBuilder.Append('D'); stringBuilder.Append('_'); stringBuilder.Append('E'); stringBuilder.Append('N'); stringBuilder.Append('D'); stringBuilder.Replace(testString, "xx"); result = stringBuilder.ToString() == "xx_MID_END"; return (result == false) ? TestResult.Fail : TestResult.Pass; } [TestMethod] public TestResult Test_3_ReplaceTest_2() { bool result = false; string testString = "MID"; stringBuilder.Replace(testString, "xx"); result = stringBuilder.ToString() == "xx_xx_END"; return (result == false) ? TestResult.Fail : TestResult.Pass; } [TestMethod] public TestResult Test_3_ReplaceTest_3() { bool result = false; string testString = "END"; stringBuilder.Replace(testString, "xx"); result = stringBuilder.ToString() == "xx_xx_xx"; return (result == false) ? TestResult.Fail : TestResult.Pass; } [TestMethod] public TestResult Test_3_ReplaceTest_4() { string testString = "The quick br!wn d#g jumps #ver the lazy cat."; bool result = false; stringBuilder = new System.Text.StringBuilder(testString); stringBuilder.Replace('#', '!', 15, 29); // Some '#' -> '!' result = stringBuilder.ToString() == "The quick br!wn d!g jumps !ver the lazy cat."; if (!result) return TestResult.Fail; stringBuilder.Replace('!', 'o'); // All '!' -> 'o' result = stringBuilder.ToString() == "The quick brown dog jumps over the lazy cat."; if (!result) return TestResult.Fail; stringBuilder.Replace("cat", "dog"); // All "cat" -> "dog" result = stringBuilder.ToString() == "The quick brown dog jumps over the lazy dog."; if (!result) return TestResult.Fail; stringBuilder.Replace("dog", "fox", 15, 20); // Some "dog" -> "fox" result = stringBuilder.ToString() == "The quick brown fox jumps over the lazy dog."; if (!result) return TestResult.Fail; return TestResult.Pass; } [TestMethod] public TestResult Test_3_ReplaceTest_5() { stringBuilder.Clear(); stringBuilder.Append("12345"); stringBuilder.Replace("45", "def"); return stringBuilder.ToString() == "123def" ? TestResult.Pass : TestResult.Fail; } [TestMethod] public TestResult Test_3_ReplaceTest_6() { stringBuilder.Clear(); stringBuilder.Append("[{1234}]Test}]"); stringBuilder.Replace("}]", "}]example"); return stringBuilder.ToString() == "[{1234}]exampleTest}]example" ? TestResult.Pass : TestResult.Fail; } [TestMethod] public TestResult Test_3_ReplaceTest_7() { var random = new Random(); for (int i = 0; i < 1000; i++) { string sRaw, sFind, sReplace; GenerateFuzzyParameters(out sRaw, out sFind, out sReplace, random); stringBuilder.Clear(); stringBuilder.Append(sRaw); stringBuilder.Replace(sFind, sReplace); string sMFOutput = stringBuilder.ToString(); string sNativeOutput = NativeReplace(sRaw, sFind, sReplace); if (sMFOutput != sNativeOutput) { Log.Comment("StringBuilder(\"" + sRaw + "\").Replace(\"" + sFind + "\", \"" + sReplace + "\") returns \"" + sMFOutput + "\""); return TestResult.Fail; } } return TestResult.Pass; } void GenerateFuzzyParameters(out string sRaw, out string sFind, out string sReplace, Random random) { int cFind = random.Next(1, 4); sFind = RandomString(random, 2, 6); sReplace = RandomString(random, 4, 10); sRaw = string.Empty; for (int i = 0; i < cFind; i++) { if (i > 0 || random.Next() % 5 > 0) { sRaw += RandomString(random, 2, 6); } sRaw += sFind; } if (random.Next() % 5 > 0) { sRaw += RandomString(random, 2, 6); } } string RandomString(Random random, int iLenMin, int iLenMax) { string sChars = "abcdefghijklmnopqrstuvwxyz0123456789{}[]-=+()"; int length = random.Next(iLenMin, iLenMax); string sOutput = string.Empty; for (int i = 0; i < length; i++) { sOutput += sChars[random.Next(0, sChars.Length - 1)]; } return sOutput; } string NativeReplace(string sRaw, string sFind, string sReplace) { string sOutput = sRaw; int i = 0; while (i < sOutput.Length) { int p = sOutput.IndexOf(sFind, i); if (p < 0) { break; } sOutput = sOutput.Substring(0, p) + sReplace + sOutput.Substring(p + sFind.Length); i = p + sReplace.Length; } return sOutput; } #endregion #region Capacity Tests [TestMethod] public TestResult Test_4_CapacityTest_0() { stringBuilder.Length = 0; stringBuilder.Capacity = 5; bool result = false; result = stringBuilder.ToString() == string.Empty; if (!result) { return TestResult.Fail; } string testString = "0000"; stringBuilder.Append(string.Empty); stringBuilder.Append(testString); stringBuilder.Append(string.Empty); //should allocate here stringBuilder.Append("_"); stringBuilder.Append("_"); //result is true if capacity is > 5 result = stringBuilder.Capacity > 5; if (!result) { return TestResult.Fail; } return (result == false) ? TestResult.Fail : TestResult.Pass; } #endregion } static class RandomExtension { static public int Next(this Random random, int iMin, int iMax) { return random.Next(iMax - iMin) + iMin; } } } ================================================ FILE: Zelig/Zelig/Test/RunTime/NETMF/System/netTests/NetTests.cs ================================================ //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // Copyright (c) Microsoft Corporation. All rights reserved. //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// using System; using System.Net; using System.Net.Sockets; namespace Microsoft.Zelig.Test { public class NetTests : TestBase, ITestInterface { [SetUp] public InitializeResult Initialize() { Log.Comment("Adding set up for the tests"); try { // Check networking - we need to make sure we can reach our proxy server System.Net.Dns.GetHostEntry("itgproxy.dns.microsoft.com"); } catch (Exception ex) { Log.Exception("Unable to get address for itgproxy.dns.microsoft.com", ex); return InitializeResult.Skip; } return InitializeResult.ReadyToGo; } [TearDown] public void CleanUp() { Log.Comment("Cleaning up after the tests"); } public override TestResult Run( string[] args ) { return TestResult.Pass; } //--// //--// //--// [TestMethod] public TestResult NetTest1_DNS() { /// /// 1. Creates an IPHostEntry for localhost /// 2. Verifies that it exists and contains the right data /// /// bool testResult = true; try { IPHostEntry ipHostEntry = Dns.GetHostEntry("192.168.1.1"); if (ipHostEntry.AddressList.Length != 1) throw new Exception("GetHostEntry resturned wrong number of addresses"); IPAddress address = ipHostEntry.AddressList[0]; if (address == null) throw new Exception("Address is null"); if (address.ToString() != "192.168.1.1") throw new Exception("Address is incorrect"); } catch (Exception e) { Log.Comment("Caught exception: " + e.Message); testResult = false; } return (testResult ? TestResult.Pass : TestResult.Fail); } [TestMethod] public TestResult NetTest2_IPAddressBasic() { /// /// 1. Creates 30 Random IPs between 0.0.0.0 and 255.255.255.127 /// 2. Verifies that they can be constructed /// 3. Verifies that they have the correct data (GetAddressBytes) /// 4. Verifies ToString and GetHashcode /// /// bool testResult = true; try { Random random = new Random(); for (int i = 0; i <= 30; i++) { int[] IPInts = { random.Next(256), random.Next(256), random.Next(256), random.Next(128) }; Log.Comment("Random IP " + IPInts[0] + "." + IPInts[1] + "." + IPInts[2] + "." + IPInts[3]); IPAddress address = new IPAddress((long)( IPInts[0] + IPInts[1] * 256 + IPInts[2] * 256 * 256 + IPInts[3] * 256 * 256 * 256)); if (address == null) throw new Exception("Address is null"); //////Type typeOfAddress = address.GetType(); //////if (typeOfAddress != Type.GetType("System.Net.IPAddress")) ////// throw new Exception("Type is incorrect"); byte[] targetBytes = { (byte)IPInts[0], (byte)IPInts[1], (byte)IPInts[2], (byte)IPInts[3] }; byte[] addressBytes = address.GetAddressBytes(); if (addressBytes.Length != 4) throw new Exception("GetAddressBytes returns wrong size"); for (int j = 0; j < 4; j++) if (addressBytes[j] != targetBytes[j]) throw new Exception("GetAddressBytes returns wrong bytes"); IPAddress address2 = new IPAddress((long)( IPInts[0] + IPInts[1] * 256 + IPInts[2] * 256 * 256 + IPInts[3] * 256 * 256 * 256)); if (address.ToString() != address2.ToString()) throw new Exception("ToString returns differently for same data"); if (address.GetHashCode() != address2.GetHashCode()) throw new Exception("GetHasCode returns differently for same data"); address2 = new IPAddress((long)( (IPInts[0] % 2 + 1) + (IPInts[1] % 2 + 1 )* 256 + (IPInts[2] % 2 + 1 )* 256 * 256 + (IPInts[3] % 2 + 1 )* 256 * 256 * 256)); if (address.GetHashCode() == address2.GetHashCode()) throw new Exception("GetHasCode returns same for " + address.ToString() + " as " + address2.ToString()); } } catch (Exception e) { Log.Comment("Caught exception: " + e.Message); testResult = false; } return (testResult ? TestResult.Pass : TestResult.Fail); } [TestMethod] public TestResult NetTest3_IPAddressLoopback() { /// /// 1. Creates an IPHostEntry for localhost /// 2. Verifies that it exists and contains the right data /// /// bool testResult = true; try { IPAddress address = IPAddress.Loopback; if (address == null) throw new Exception("Address is null"); if (address.ToString() != "127.0.0.1") throw new Exception("Address is incorrect"); //////Type typeOfAddress = address.GetType(); //////if (typeOfAddress != Type.GetType("System.Net.IPAddress")) ////// throw new Exception("Type is incorrect"); byte[] localhostBytes = {(byte)127,(byte)0,(byte)0,(byte)1}; byte[] addressBytes = address.GetAddressBytes(); if (addressBytes.Length != 4) throw new Exception("GetAddressBytes returns wrong size"); for (int i = 0; i < 4; i++) if (addressBytes[i] != localhostBytes[i]) throw new Exception("GetAddressBytes returns wrong bytes"); } catch (Exception e) { Log.Comment("Caught exception: " + e.Message); testResult = false; } return (testResult ? TestResult.Pass : TestResult.Fail); } [TestMethod] public TestResult NetTest4_IPAddressAny() { /// /// 1. Creates an IPHostEntry for Any /// 2. Verifies that it exists and contains the right data /// /// bool testResult = true; try { IPAddress address = IPAddress.Any; if (address == null) throw new Exception("Address is null"); if (address.ToString() != "0.0.0.0") throw new Exception("Address is incorrect"); //////Type typeOfAddress = address.GetType(); //////if (typeOfAddress != Type.GetType("System.Net.IPAddress")) ////// throw new Exception("Type is incorrect"); byte[] localhostBytes = {(byte)0,(byte)0,(byte)0,(byte)0}; byte[] addressBytes = address.GetAddressBytes(); if (addressBytes.Length != 4) throw new Exception("GetAddressBytes returns wrong size"); for (int i = 0; i < 4; i++) if (addressBytes[i] != localhostBytes[i]) throw new Exception("GetAddressBytes returns wrong bytes"); } catch (Exception e) { Log.Comment("Caught exception: " + e.Message); testResult = false; } return (testResult ? TestResult.Pass : TestResult.Fail); } [TestMethod] public TestResult NetTest5_IPEndPointBasic() { /// /// 1. Creates 30 Random IPs between 0.0.0.0 and 255.255.255.127 /// 2. Verifies that they can be constructed as IPEndPoints with both ctors /// 3. Verifies that their data, ToString and GetHashCode funcs return normally /// 4. Clones one with Create and verifies the above funcs again /// /// bool testResult = true; try { Random random = new Random(); for (int i = 0; i <= 30; i++) { int[] IPInts = { random.Next(256), random.Next(256), random.Next(256), random.Next(128) }; int portInt = random.Next(65535) + 1; long addressLong = (long)( IPInts[0] + IPInts[1] * 256 + IPInts[2] * 256 * 256 + IPInts[3] * 256 * 256 * 256); Log.Comment("Random IP " + IPInts[0] + "." + IPInts[1] + "." + IPInts[2] + "." + IPInts[3] + ":" + portInt); IPAddress address = new IPAddress(addressLong); Log.Comment("EndPoint1 created with IPAddress and int"); IPEndPoint endPoint1 = new IPEndPoint(address,portInt); Log.Comment("EndPoint2 created with long and int"); IPEndPoint endPoint2 = new IPEndPoint(addressLong, portInt); if (endPoint1 == null) throw new Exception("EndPoint1 is null"); if (endPoint2 == null) throw new Exception("EndPoint2 is null"); Type typeOfEndPoint = endPoint1.GetType(); //////if (typeOfEndPoint != Type.GetType("System.Net.IPEndPoint")) ////// throw new Exception("EndPoint1 Type is incorrect"); //////typeOfEndPoint = endPoint2.GetType(); //////if (typeOfEndPoint != Type.GetType("System.Net.IPEndPoint")) ////// throw new Exception("EndPoint2 Type is incorrect"); if (endPoint1.ToString() != endPoint2.ToString()) throw new Exception("ToString returns differently for same data"); if (!endPoint1.Equals(endPoint2)) { throw new Exception("Equals returns false for same data"); } int hashCode1 = endPoint1.GetHashCode(); int hashCode2 = endPoint2.GetHashCode(); if (hashCode1 != hashCode2) throw new Exception("GetHasCode returns differently for same data"); if (endPoint1.Address.ToString() != endPoint2.Address.ToString() || endPoint1.Address.ToString() != address.ToString() || endPoint2.Address.ToString() != address.ToString()) throw new Exception("Address returns wrong data"); if (endPoint1.Port != endPoint2.Port || endPoint1.Port != portInt || endPoint2.Port != portInt) throw new Exception("Port returns wrong data"); Log.Comment("Cloning Enpoint1 into EndPoint2"); endPoint2 = (IPEndPoint)endPoint2.Create(endPoint1.Serialize()); typeOfEndPoint = endPoint2.GetType(); //////if (typeOfEndPoint != Type.GetType("System.Net.IPEndPoint")) ////// throw new Exception("EndPoint2 Type is incorrect after clone"); if (endPoint1.ToString() != endPoint2.ToString()) throw new Exception("ToString returns differently for cloned data"); //21295 GetHashCode returns differently for cloned data if (endPoint1.GetHashCode() != endPoint2.GetHashCode()) throw new Exception("GetHashCode returns differently for cloned data"); if (endPoint1.Address.ToString() != endPoint2.Address.ToString() || endPoint1.Address.ToString() != address.ToString() || endPoint2.Address.ToString() != address.ToString()) throw new Exception("Address returns wrong data after clone"); if (endPoint1.Port != endPoint2.Port || endPoint1.Port != portInt || endPoint2.Port != portInt) throw new Exception("Port returns wrong data after clone"); Log.Comment("Recreating EndPoint2 with new data"); int portInt2 = portInt % 2 + 1; long addressLong2 = (long)( (IPInts[0] % 2 + 1) + (IPInts[1] % 2 + 1 )* 256 + (IPInts[2] % 2 + 1 )* 256 * 256 + (IPInts[3] % 2 + 1 )* 256 * 256 * 256); endPoint2 = new IPEndPoint(addressLong2, portInt2); if (endPoint1.GetHashCode() == endPoint2.GetHashCode()) throw new Exception("GetHashCode returns same for " + endPoint1.ToString() + " as " + endPoint2.ToString()); if (endPoint1.Address == endPoint2.Address || endPoint2.Address == address) throw new Exception("Address returns wrong data after change"); if (endPoint1.Port == endPoint2.Port || endPoint2.Port == portInt) throw new Exception("Port returns wrong data after change"); } } catch (Exception e) { Log.Comment("Caught exception: " + e.Message); testResult = false; } return (testResult ? TestResult.Pass : TestResult.Fail); } [TestMethod] public TestResult NetTest5_IPHostEntryBasic() { /// /// 1. Creates an IPHostEntry for localhost /// 2. Verifies that it exists and contains the right data /// /// bool testResult = true; try { IPHostEntry ipHostEntry = Dns.GetHostEntry("192.168.1.1"); if (ipHostEntry == null) throw new Exception("IPHostEntry is null"); Type typeOfIPHostEntry = ipHostEntry.GetType(); //////if (typeOfIPHostEntry != Type.GetType("System.Net.IPHostEntry")) ////// throw new Exception("IPHostEntry Type is incorrect"); if (ipHostEntry.AddressList[0].ToString() != "192.168.1.1") throw new Exception("AddressList[0] is incorrect"); try { ipHostEntry.AddressList[1].ToString(); throw new Exception("AddressList[1] is not null"); } catch (System.IndexOutOfRangeException) { } } catch (Exception e) { Log.Comment("Caught exception: " + e.Message); testResult = false; } return (testResult ? TestResult.Pass : TestResult.Fail); } [TestMethod] public TestResult NetTest6_SocketAddressBasic() { /// /// 1. Creates 30 Random IPs between 0.0.0.0 and 255.255.255.127 /// 2. Verifies that they can be constructed as SocketAddress /// 3. Verifies that they have the correct data (GetAddressBytes) /// 4. Verifies ToString and GetHashcode /// /// bool testResult = true; try { Random random = new Random(); for (int i = 0; i <= 30; i++) { int[] IPInts = { random.Next(256), random.Next(256), random.Next(256), random.Next(128) }; Log.Comment("Random IP " + IPInts[0] + "." + IPInts[1] + "." + IPInts[2] + "." + IPInts[3]); IPAddress address = new IPAddress((long)( IPInts[0] + IPInts[1] * 256 + IPInts[2] * 256 * 256 + IPInts[3] * 256 * 256 * 256)); int portInt = random.Next(65536); IPEndPoint ipEndpoint1 = new IPEndPoint(address, portInt); SocketAddress socketAddress1 = ipEndpoint1.Serialize(); SocketAddress socketAddress2 = ipEndpoint1.Serialize(); if (socketAddress1 == null) throw new Exception("socketAddress1 is null"); if (socketAddress2 == null) throw new Exception("socketAddress2 is null"); Type typeOfSocketAddress = socketAddress1.GetType(); //////if (typeOfSocketAddress != Type.GetType("System.Net.SocketAddress")) ////// throw new Exception("socketAddress1 Type is incorrect"); typeOfSocketAddress = socketAddress2.GetType(); //////if (typeOfSocketAddress != Type.GetType("System.Net.SocketAddress")) ////// throw new Exception("socketAddress2 Type is incorrect"); if (socketAddress1.ToString() != socketAddress2.ToString()) throw new Exception("ToString returns differently for same data"); //21295 GetHashCode returns differently for cloned data if (socketAddress1.GetHashCode() != socketAddress2.GetHashCode()) throw new Exception("GetHashCode returns differently for same data"); if (socketAddress1.Family != AddressFamily.InterNetwork) throw new Exception("socketAddress1 Family is incorrect"); if (socketAddress2.Family != AddressFamily.InterNetwork) throw new Exception("socketAddress2 Family is incorrect"); /* * Pending Resolution of 17428 * Log.Comment("Recreating socketAddress2 with new data"); int portInt2 = portInt % 2 + 1; long addressLong2 = (long)( (IPInts[0] % 2 + 1) + (IPInts[1] % 2 + 1) * 256 + (IPInts[2] % 2 + 1) * 256 * 256 + (IPInts[3] % 2 + 1) * 256 * 256 * 256); IPEndPoint ipEndpoint2 = new IPEndPoint(addressLong2, portInt2); socketAddress2 = ipEndpoint2.Serialize(); socketAddress2.Family = AddressFamily.Chaos; */ socketAddress2 = new SocketAddress(AddressFamily.Chaos, 8); if (socketAddress1.GetHashCode() == socketAddress2.GetHashCode()) throw new Exception("GetHashCode returns same for " + socketAddress1.ToString() + " as " + socketAddress2.ToString()); if (socketAddress1.ToString() == socketAddress2.ToString()) throw new Exception("ToString returns same for different data"); } } catch (Exception e) { Log.Comment("Caught exception: " + e.Message); testResult = false; } return (testResult ? TestResult.Pass : TestResult.KnownFailure); } } } ================================================ FILE: Zelig/Zelig/Test/RunTime/NETMF/System/socketTests/SocketExceptionTests.cs ================================================ /*--------------------------------------------------------------------- * SocketExceptionsTests.cs - file description * Version: 1.0 * Author: REDMOND\a-grchat * Created: 9/12/2007 4:51:10 PM * ---------------------------------------------------------------------*/ using System.Net; using System.Net.Sockets; using System.Threading; using System; namespace Microsoft.Zelig.Test { public class SocketExceptionTests : TestBase, ITestInterface { [SetUp] public InitializeResult Initialize() { /// /// This file tests all of the SocketExceptions except: /// /// The following ErrorCodes are not supported by the MF due to /// the lack of non-blocking (Begin-End)Send and (Begin-End)Receive methods: /// AlreadyInProgress, ConnectionAborted, Disconnecting /// /// The following ErrorCodes are not tested because they represent occurances /// that the TestHarness cannot duplicate: /// NetworkDown, NetworkUnreachable, NetworkReset, ConnectionReset , HostDown /// ProcessLimit, SystemNotReady, VersionNotSupported, TryAgain, NoRecovery, NoData /// /// The following ErrorCodes are not supported by the MF for other reasons: /// NotSocket, TypeNotFound -- VS returns typing errors instead /// DestinationAddressRequired -- VS throws AddressNotAvailable instead /// Shutdown -- MF does not implement Shutdown() /// NotInitialized -- C# doesn't use WSAStartup /// //Wait for GC try { // Check networking - we need to make sure we can reach our proxy server System.Net.Dns.GetHostEntry("itgproxy.dns.microsoft.com"); } catch (Exception ex) { Log.Exception("Unable to get address for itgproxy.dns.microsoft.com", ex); return InitializeResult.Skip; } Log.Comment("The following tests are located in SocketExceptionTests.cs"); return InitializeResult.ReadyToGo; } [TearDown] public void CleanUp() { Log.Comment("Cleaning up after the tests."); } public override TestResult Run( string[] args ) { return TestResult.Pass; } //--// //--// //--// [TestMethod] public TestResult SocketExceptionTest2_AddressAlreadyInUse() { /// /// 1. Causes an AddressAlreadyInUse error /// /// bool isCorrectCatch = false; bool isAnyCatch = false; try { Socket socketClient = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); Socket socketServer = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); try { socketClient.Bind(new IPEndPoint(IPAddress.Loopback, 10)); socketServer.Bind(new IPEndPoint(IPAddress.Loopback, 10)); } catch (SocketException e) { if (e.ErrorCode.ToString() != SocketError.AddressAlreadyInUse.ToString()) throw new System.Exception("Incorrect ErrorCode in SocketException " + e.ErrorCode, e); isCorrectCatch = true; isAnyCatch = true; } finally { socketClient.Close(); socketServer.Close(); } } catch (System.Exception e) { isAnyCatch = true; Log.Comment("Incorrect exception caught: " + e.Message); } if (!isAnyCatch) { Log.Comment("No exception caught"); } return (isCorrectCatch ? TestResult.Pass : TestResult.Fail); } [TestMethod] public TestResult SocketExceptionTest3_Protocol_Address_FamilyNotSupported() { /// /// 1. Causes an Address or ProtocolFamilyNotSupported error /// According to MSDN these Exceptions are "interchangeable in most cases" /// /// bool isAnyCatch = false; try { try { Socket socketTest = new Socket(AddressFamily.AppleTalk, SocketType.Stream, ProtocolType.Udp); } catch (SocketException e) { if (e.ErrorCode != (int)SocketError.ProtocolFamilyNotSupported && e.ErrorCode != (int)SocketError.AddressFamilyNotSupported) throw new System.Exception("Incorrect ErrorCode in SocketException " + e.ErrorCode, e); isAnyCatch = true; } } catch (System.Exception e) { isAnyCatch = true; Log.Comment("Incorrect exception caught: " + e.Message); } if (!isAnyCatch) { Log.Comment("No exception caught"); } return (isAnyCatch ? TestResult.Pass : TestResult.Fail); } [TestMethod] public TestResult SocketExceptionTest4_ProtocolNotSupported() { /// /// 1. Causes a ProtocolNotSupported error /// This test currently fails see 17577 /// /// bool isAnyCatch = false; try { try { Socket socketTest = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Udp); } catch (SocketException e) { if (e.ErrorCode != (int)SocketError.ProtocolNotSupported) throw new System.Exception("Incorrect ErrorCode in SocketException " + e.ErrorCode, e); isAnyCatch = true; } } catch (System.Exception e) { isAnyCatch = true; Log.Comment("Incorrect exception caught: " + e.Message); } if (!isAnyCatch) { Log.Comment("No exception caught"); } return (isAnyCatch ? TestResult.Pass : TestResult.Fail); } [TestMethod] public TestResult SocketExceptionTest6_IsConnected() { /// /// 1. Causes a IsConnected error /// /// bool isCorrectCatch = false; bool isAnyCatch = false; SocketPair testSockets = new SocketPair(ProtocolType.Tcp, SocketType.Stream); try { try { testSockets.Startup(0, 0); testSockets.socketServer.Listen(1); testSockets.socketClient.Connect(testSockets.epServer); testSockets.socketClient.Connect(testSockets.epServer); } catch (SocketException) { isCorrectCatch = true; isAnyCatch = true; } } catch (System.Exception e) { isAnyCatch = true; Log.Comment("Incorrect exception caught: " + e.Message); } finally { testSockets.TearDown(); } if (!isAnyCatch) { Log.Comment("No exception caught"); } return (isCorrectCatch ? TestResult.Pass : TestResult.Fail); } [TestMethod] public TestResult SocketExceptionTest11_AccessDenied() { /// /// 1. Causes a AccessDenied error /// /// bool isCorrectCatch = false; bool isAnyCatch = false; SocketPair testSockets = new SocketPair(ProtocolType.Udp, SocketType.Dgram); try { try { int clientPort = SocketTools.nextPort; int serverPort = SocketTools.nextPort; int tempPort = serverPort; testSockets.socketClient.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.Broadcast, false); testSockets.Startup(clientPort, serverPort); IPEndPoint epBroadcast = new IPEndPoint(SocketTools.DottedDecimalToIp((byte)255, (byte)255, (byte)255, (byte)255), tempPort); EndPoint serverEndPoint = epBroadcast.Create(epBroadcast.Serialize()); testSockets.socketClient.SendTo(testSockets.bufSend, serverEndPoint); } catch (SocketException) { isCorrectCatch = true; isAnyCatch = true; } } catch (System.Exception e) { isAnyCatch = true; Log.Comment("Incorrect exception caught: " + e.Message); } finally { testSockets.TearDown(); } if (!isAnyCatch) { Log.Comment("No exception caught"); } return (isCorrectCatch ? TestResult.Pass : TestResult.Fail); } [TestMethod] public TestResult SocketExceptionTest12_NotConnected() { /// /// 1. Causes a NotConnected error /// /// bool isCorrectCatch = false; bool isAnyCatch = false; SocketPair testSockets = new SocketPair(ProtocolType.Tcp, SocketType.Stream); try { try { testSockets.Startup(0, 0); Socket socketTemp = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); socketTemp.Bind(testSockets.socketServer.RemoteEndPoint); socketTemp.Send(new byte[2]); } catch (SocketException) { isCorrectCatch = true; isAnyCatch = true; } } catch (System.Exception e) { isAnyCatch = true; Log.Comment("Incorrect exception caught: " + e.Message); } finally { testSockets.TearDown(); } if (!isAnyCatch) { Log.Comment("No exception caught"); } return (isCorrectCatch ? TestResult.Pass : TestResult.Fail); } [TestMethod] public TestResult SocketExceptionTest13_InvalidArgument() { /// /// 1. Causes a InvalidArgument error /// /// bool isCorrectCatch = false; bool isAnyCatch = false; SocketPair testSockets = new SocketPair(ProtocolType.Tcp, SocketType.Stream); try { try { int clientPort = SocketTools.nextPort; int serverPort = SocketTools.nextPort; int tempPort = clientPort; testSockets.Startup(clientPort, serverPort); testSockets.socketServer.SetSocketOption(SocketOptionLevel.IPv6, SocketOptionName.Broadcast, true); } catch (SocketException) { isCorrectCatch = true; isAnyCatch = true; } } catch (System.Exception e) { isAnyCatch = true; Log.Comment("Incorrect exception caught: " + e.Message); } finally { testSockets.TearDown(); } if (!isAnyCatch) { Log.Comment("No exception caught"); } return (isCorrectCatch ? TestResult.Pass : TestResult.Fail); } [TestMethod] public TestResult SocketExceptionTest14_AddressNotAvailable() { /// /// 1. Causes a AddressNotAvailable error /// Due to loopback this method causes an InvalidArgument /// SocketException erroneously /// /// bool isCorrectCatch = false; bool isAnyCatch = false; SocketPair testSockets = new SocketPair(ProtocolType.Tcp, SocketType.Stream); try { try { int clientPort = SocketTools.nextPort; int serverPort = SocketTools.nextPort; int tempPort = clientPort; testSockets.Startup(clientPort, serverPort); testSockets.socketClient.Bind(new IPEndPoint(new IPAddress(SocketTools.DottedDecimalToIp((byte)192, (byte)168, (byte)192, (byte)168)), tempPort)); } catch (SocketException) { isCorrectCatch = true; isAnyCatch = true; } } catch (System.Exception e) { isAnyCatch = true; Log.Comment("Incorrect exception caught: " + e.Message); } finally { testSockets.TearDown(); } if (!isAnyCatch) { Log.Comment("No exception caught"); } return (isCorrectCatch ? TestResult.Pass : TestResult.Fail); } [TestMethod] public TestResult SocketExceptionTest16_HostNotFound() { /// /// 1. Causes a HostNotFound error /// /// bool isCorrectCatch = false; bool isAnyCatch = false; try { try { IPHostEntry ipHostEntry = Dns.GetHostEntry("fakeHostName"); } catch (SocketException) { isCorrectCatch = true; isAnyCatch = true; } } catch (System.Exception e) { isAnyCatch = true; Log.Comment("Incorrect exception caught: " + e.Message); } if (!isAnyCatch) { Log.Comment("No exception caught"); } return (isCorrectCatch ? TestResult.Pass : TestResult.Fail); } [TestMethod] public TestResult SocketExceptionTest17_SocketError() { /// /// 1. Causes a SocketError error /// This currently succeeds but will need re-writing if 17577 is addressed /// /// bool isCorrectCatch = false; try { SocketPair testSockets = new SocketPair(ProtocolType.Udp, SocketType.Stream); } catch (SocketException) { isCorrectCatch = true; } return (isCorrectCatch ? TestResult.Pass : TestResult.Fail); } [TestMethod] public TestResult SocketExceptionTest18_Fault() { /// /// 1. Causes a Fault error /// /// bool isCorrectCatch = false; bool isAnyCatch = false; SocketPair testSockets = new SocketPair(ProtocolType.Tcp, SocketType.Stream); try { try { testSockets.socketClient.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.Linger, new byte[] { (byte)0 }); testSockets.Startup(0, 0); } catch (SocketException) { isCorrectCatch = true; isAnyCatch = true; } } catch (System.Exception e) { isAnyCatch = true; Log.Comment("Incorrect exception caught: " + e.Message); } finally { testSockets.TearDown(); } if (!isAnyCatch) { Log.Comment("No exception caught"); } return (isCorrectCatch ? TestResult.Pass : TestResult.Fail); } [TestMethod] public TestResult SocketExceptionTest19_ProtocolOption() { /// /// 1. Causes a ProtocolOption error /// /// bool isCorrectCatch = false; bool isAnyCatch = false; SocketPair testSockets = new SocketPair(ProtocolType.Tcp, SocketType.Stream); try { try { testSockets.Startup(0, 0); testSockets.socketClient.GetSocketOption(SocketOptionLevel.IP, SocketOptionName.Linger); } catch (SocketException) { isCorrectCatch = true; isAnyCatch = true; } } catch (System.Exception e) { isAnyCatch = true; Log.Comment("Incorrect exception caught: " + e.Message); } if (!isAnyCatch) { Log.Comment("No exception caught"); } testSockets.TearDown(); testSockets = null; return (isCorrectCatch ? TestResult.Pass : TestResult.Fail); } [TestMethod] public TestResult SocketExceptionTest20_OperationNotSupported() { /// /// 1. Causes a OperationNotSupported error /// /// bool isCorrectCatch = false; bool isAnyCatch = false; SocketPair testSockets = new SocketPair(ProtocolType.Tcp, SocketType.Stream); try { try { testSockets.Startup(0, 0); testSockets.socketServer.Listen(1); testSockets.socketClient.Connect(testSockets.epServer); testSockets.socketClient.Send(testSockets.bufSend); using (Socket sock = testSockets.socketServer.Accept()) { sock.Receive(testSockets.bufReceive, SocketFlags.DontRoute); } isCorrectCatch = true; } catch (SocketException) { isCorrectCatch = true; isAnyCatch = true; } } catch (System.Exception e) { isAnyCatch = true; Log.Comment("Incorrect exception caught: " + e.Message); } if (!isAnyCatch) { Log.Comment("No exception caught"); } testSockets.TearDown(); testSockets = null; return (isCorrectCatch ? TestResult.Pass : TestResult.Fail); } } } ================================================ FILE: Zelig/Zelig/Test/RunTime/NETMF/System/socketTests/SocketPair.cs ================================================ /*--------------------------------------------------------------------- * SocketPair.cs - file description * Version: 1.0 * Author: REDMOND\a-grchat * Created: 9/12/2007 4:51:10 PM * * Defines an object that is a pair of Sockets of the same protocol * 1 client 1 server, and verification methods * ---------------------------------------------------------------------*/ using System; using System.Reflection; using System.Threading; using System.Net; using System.Net.Sockets; namespace Microsoft.Zelig.Test { public class SocketPair { private const int STANDARD_SIZE = 3; public Socket socketClient; public Socket socketServer; public byte[] bufSend; public byte[] bufReceive; public IPEndPoint epClient; public IPEndPoint epServer; public SocketPair( ProtocolType protocolType, SocketType socketType ) { socketClient = new Socket( AddressFamily.InterNetwork, socketType, protocolType ); socketServer = new Socket( AddressFamily.InterNetwork, socketType, protocolType ); if(protocolType == ProtocolType.Tcp) { socketClient.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.Linger, false); socketServer.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.Linger, false); } bufSend = null; bufReceive = null; epClient = null; epServer = null; } ~SocketPair() { TearDown(); } public void Startup( int portClient, int portServer ) { socketClient.Bind(new IPEndPoint(IPAddress.Loopback, portClient)); socketServer.Bind(new IPEndPoint(IPAddress.Loopback, portServer)); epClient = (IPEndPoint)socketClient.LocalEndPoint; epServer = (IPEndPoint)socketServer.LocalEndPoint; Log.Comment("Server Port#: "+epServer + " Client Port#: "+epClient); bufSend = new byte[STANDARD_SIZE]; new Random().NextBytes(bufSend); bufReceive = new byte[bufSend.Length]; } public void TearDown() { CloseSocket(ref socketClient); CloseSocket(ref socketServer); } private void CloseSocket(ref Socket socket) { if (socket != null) { socket.Close(); socket = null; } } public void AssertDataReceived(int cBytes) { if (cBytes != bufSend.Length) throw new Exception("Recieve failed, wrong size " + cBytes + " " + bufSend.Length); for (int i = 0; i < bufReceive.Length; i++) { if (bufSend[i] != bufReceive[i]) throw new Exception("Receive failed, wrong data"); } } } } ================================================ FILE: Zelig/Zelig/Test/RunTime/NETMF/System/socketTests/SocketServer.cs ================================================ using System; using System.Net; using System.Net.Sockets; using System.Text; using System.Threading; namespace Microsoft.Zelig.Test { public enum TestType { Linger = 0, ReceiveTimeout, SendTimeout, SendReceiveBufferSize, NoDelay, None } public class SocketServer : Socket { private const Int32 c_microsecondsPerSecond = 1000000; private bool _running = false; private Thread _serverThread; public TestType testId = TestType.None; public TestResult testResult; private bool m_linger; public SocketServer(TestType testType, AddressFamily addressFamily, SocketType socketType, ProtocolType protocolType) : base (addressFamily, socketType, protocolType) { testId = testType; m_linger = false; } /// /// Start processing connections /// public void Start() { this.Stop(); _running = true; _serverThread = new Thread(new ThreadStart(StartServer)); _serverThread.Start(); } /// /// Stop processing new connections /// public void Stop() { // If server is running, stop it first if (_running) { _running = false; _serverThread.Abort(); _serverThread.Join(); } } /// /// Internal thread that handles all communications. /// private void StartServer() { Socket lingerSock = null; try { while (_running) { // Wait for a client to connect Socket clientSocket = this.Accept(); { Log.Comment("Starting server with the tests type " + testId.ToString()); switch (testId) { case TestType.Linger: lingerSock = clientSocket; Linger(lingerSock); break; case TestType.NoDelay: case TestType.ReceiveTimeout: case TestType.SendReceiveBufferSize: case TestType.SendTimeout: clientSocket.Close(); break; } } } } catch (ThreadAbortException) { } finally { if (lingerSock != null) { lingerSock.Close(); } _running = false; } } public bool LingerValue { set { m_linger = value; } } public void Linger(Socket sock) { try { byte[] bytesReceived = new byte[400]; sock.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.Linger, m_linger ? 3000: 0 ); int cnt = sock.Receive(bytesReceived); sock.Send(bytesReceived, cnt, SocketFlags.None); testResult = TestResult.Pass; sock.Close(); } catch { } } } } ================================================ FILE: Zelig/Zelig/Test/RunTime/NETMF/System/socketTests/SocketTests.cs ================================================ /*--------------------------------------------------------------------- * SocketTests.cs - file description * Version: 1.0 * Author: REDMOND\a-grchat * Created: 9/12/2007 4:51:10 PM * * Tests the basic functionality of Socket objects * ---------------------------------------------------------------------*/ using System; using System.Reflection; using System.Threading; using System.Net; using System.Net.Sockets; using Microsoft.Llilum.Lwip; namespace Microsoft.Zelig.Test { public class SocketTests : TestBase, ITestInterface { [SetUp] public InitializeResult Initialize() { Log.Comment("Adding set up for the tests"); try { // Check networking - we need to make sure we can reach our proxy server System.Net.Dns.GetHostEntry("itgproxy.dns.microsoft.com"); } catch (Exception ex) { Log.Exception("Unable to get address for itgproxy.dns.microsoft.com", ex); return InitializeResult.Skip; } return InitializeResult.ReadyToGo; } [TearDown] public void CleanUp() { Log.Comment("Cleaning up after the tests"); } public override TestResult Run( string[] args ) { return TestResult.Pass; } //--// //--// //--// //[TestMethod] //public TestResult NetworkStream_Read() //{ // TestResult testResult = TestResult.Pass; // IPHostEntry hostEntry = Dns.GetHostEntry(""); // IPAddress ipAddress = null; // for (int i = 0; i < hostEntry.AddressList.Length; ++i) // { // try // { // Log.Comment(hostEntry.AddressList[i].ToString()); // ipAddress = hostEntry.AddressList[i]; // } // catch { } // } // IPEndPoint ipEndPoint = new IPEndPoint(ipAddress, 80); // Socket s = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); // s.Bind(ipEndPoint); // s.Listen(1); // NetworkStream ns = new NetworkStream(s.Accept(),false); // byte[] msg = new Byte[25]; // int bytesRead= 0; // bytesRead = ns.Read(msg, 0, msg.Length); // s.Close(); // return testResult; //} //[TestMethod] //public TestResult SocketTest14_DPWSOptions() //{ // TestResult testResult = TestResult.Pass; // IPHostEntry hostEntry = Dns.GetHostEntry(""); // IPAddress ipAddress = null; // for (int i = 0; i < hostEntry.AddressList.Length; ++i) // { // try // { // Log.Comment(hostEntry.AddressList[i].ToString()); // ipAddress = hostEntry.AddressList[i]; // } // catch { } // } // IPEndPoint endPoint = new IPEndPoint(ipAddress, 11000); // Socket s = new Socket(AddressFamily.InterNetwork, // SocketType.Dgram, // ProtocolType.Udp); // // Creates an IPEndPoint to capture the identity of the sending host. // IPEndPoint sender = new IPEndPoint(IPAddress.Any, 0); // EndPoint senderRemote = (EndPoint)sender; // // Binding is required with ReceiveFrom calls. // s.Bind(endPoint); // byte[] msg = new Byte[256]; // Log.Comment("Waiting to receive datagrams from client..."); // // This call blocks. // s.ReceiveFrom(msg, msg.Length, SocketFlags.None, ref senderRemote); // s.Close(); // return testResult; //} [TestMethod] public TestResult SocketTest0_MaxSockets() { /// ///1. Starts Numerous sockets with linger option to false. ///2. Should not fail because we should be able to reclaim those sockets if linger is true /// bool testResult = true; int i = 1; try { for (; i < 300; ++i) { using (Socket socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp)) { socket.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.Linger, false); } } i = 1; for (; i < 300; ++i) { Socket socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); socket.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.Linger, false); socket.Close(); } } //catch (Exception e) catch { Log.Comment("Incorrectly threw an exception trying to create " + i.ToString() + " sockets."); //////if (e.GetType() == Type.GetType("System.Net.Sockets.SocketException")) //////Log.Comment("ErrorCode: " + ((SocketException)e).ErrorCode); testResult = false; } return (testResult ? TestResult.Pass : TestResult.Fail); } [TestMethod] public TestResult SocketTest1_BasicTCP() { /// ///1. Starts a server socket listening for TCP ///2. Starts a client socket connected to the server ///3. Verifies that data can be correctly sent and recieved /// bool testResult = true; SocketPair testSockets = null; try { testSockets = new SocketPair(ProtocolType.Tcp, SocketType.Stream); Log.Comment("Testing with port 0"); testSockets.Startup(0, 0); testSockets.socketServer.Listen(1); testSockets.socketClient.Connect(testSockets.epServer); int cBytes = testSockets.socketClient.Send(testSockets.bufSend); if (cBytes != testSockets.bufSend.Length) throw new Exception("Send failed, wrong length"); using (Socket sock = testSockets.socketServer.Accept()) { if (sock.LocalEndPoint == null) throw new Exception("LocalEndPoint is null"); //Fix? if (testSockets.socketServer.LocalEndPoint.ToString() != sock.LocalEndPoint.ToString()) throw new Exception("LocalEndPoint is incorrect"); if (sock.RemoteEndPoint == null) throw new Exception("RemoteEndPoint is null"); if (testSockets.socketClient.LocalEndPoint.ToString() != sock.RemoteEndPoint.ToString()) throw new Exception("RemoteEndPoint is incorrect"); cBytes = sock.Available; if (cBytes != testSockets.bufSend.Length) throw new Exception("Send failed, wrong length"); cBytes = sock.Receive(testSockets.bufReceive); } testSockets.AssertDataReceived(cBytes); } catch (Exception e) { Log.Comment("Caught exception: " + e.Message); //////if (e.GetType() == Type.GetType("System.Net.Sockets.SocketException")) ////// Log.Comment("ErrorCode: " + ((SocketException)e).ErrorCode); testResult = false; } finally { if (testSockets != null) { testSockets.TearDown(); testSockets = null; } } return (testResult ? TestResult.Pass : TestResult.Fail); } [TestMethod] public TestResult SocketTest1_TCP_LingerFalse() { /// ///1. Starts a server socket listening for TCP ///2. Starts a client socket connected to the server ///3. Verifies that data can be correctly sent and recieved ///4. Verifies linger is functional /// /////////skip this test for the emulator since setting socket options is not supported. //////if (Microsoft.SPOT.Hardware.SystemInfo.SystemID.SKU == 3) ////// return TestResult.Skip; TestResult testResult = TestResult.Pass; IPEndPoint serverEndPoint = new IPEndPoint(IPAddress.Loopback, 3053); IPEndPoint clientEndPoint = new IPEndPoint(IPAddress.Loopback, 3054); SocketServer server = null; try { server = new SocketServer(TestType.Linger, AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); server.LingerValue = false; server.Bind(serverEndPoint); server.Listen(1); server.Start(); for (int i = 0; i < 2; ++i) { Socket client = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); try { client.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.Linger, false); Log.Comment("Testing with port 0"); Log.Comment("For linger verify that we can reuse the ipEndPoint multiple times"); client.Bind(clientEndPoint); client.Connect(server.LocalEndPoint); int bytesSent = client.Send(new byte[200]); Log.Comment("Create another client to connect to the server endpoint directly after this client closes."); } catch (SocketException e) { Log.Comment("Exception " + e); Log.Comment("ErrorCode: " + e.ErrorCode); testResult = TestResult.Fail; break; } catch (Exception e) { Log.Comment("Exception " + e); testResult = TestResult.Fail; break; } finally { client.Close(); } } } catch (SocketException e) { Log.Comment("Caught exception: " + e.Message); Log.Comment("ErrorCode: " + e.ErrorCode.ToString()); testResult = TestResult.Fail; } catch (Exception e) { Log.Comment("Caught exception: " + e.Message); testResult = TestResult.Fail; } finally { if (server != null) { server.Stop(); server.Close(); } } return testResult; } [TestMethod] public TestResult SocketTest1_TCP_LingerTrue() { /// ///1. Starts a server socket listening for TCP ///2. Starts a client socket connected to the server ///3. Verifies that data can be correctly sent and recieved ///4. Verifies linger is functional /// /////////skip this test for the emulator since setting socket options is not supported. //////if (Microsoft.SPOT.Hardware.SystemInfo.SystemID.SKU == 3) ////// return TestResult.Skip; TestResult testResult = TestResult.Fail; IPEndPoint serverEndPoint = new IPEndPoint(IPAddress.Loopback, 3055); IPEndPoint clientEndPoint = new IPEndPoint(IPAddress.Loopback, 3056); SocketServer server = null; try { server = new SocketServer(TestType.Linger, AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); server.LingerValue = true; server.Bind(serverEndPoint); server.Listen(1); server.Start(); for (int i = 0; i < 2; ++i) { Socket client = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); try { Log.Comment("Testing with port 0"); client.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.Linger, 3000); Log.Comment("For linger verify that we can reuse the ipEndPoint multiple times"); client.Bind(clientEndPoint); client.Connect(server.LocalEndPoint); int bytesSent = client.Send(new byte[200]); Log.Comment("Create another client to connect to the server endpoint directly after this client closes."); } catch (SocketException e) { Log.Comment("Exception " + e); Log.Comment("ErrorCode: " + e.ErrorCode); testResult = TestResult.Pass; } catch (Exception e) { Log.Comment("Exception " + e); testResult = TestResult.Fail; break; } finally { client.Close(); } } } catch (SocketException e) { Log.Comment("Caught exception: " + e.Message); Log.Comment("ErrorCode: " + e.ErrorCode.ToString()); testResult = TestResult.Fail; } catch (Exception e) { Log.Comment("Caught exception: " + e.Message); testResult = TestResult.Fail; } finally { if (server != null) { server.Stop(); server.Close(); } } return testResult; } [TestMethod] public TestResult SocketTest1_TCP_NoDelay() { /// ///1. Starts a server socket listening for TCP ///2. Starts a client socket connected to the server ///3. Verifies that data can be correctly sent and recieved ///4. Verifies NoDelay is functional /// /////////skip this test for the emulator since setting socket options is not supported. //////if (Microsoft.SPOT.Hardware.SystemInfo.SystemID.SKU == 3) ////// return TestResult.Skip; TestResult testResult = TestResult.Pass; bool noDelay = false; int bytesReceivedNoDelay = 0; int bytesReceivedDelay = 0; do { SocketPair testSockets = new SocketPair(ProtocolType.Tcp, SocketType.Stream); try { testSockets.socketClient.SetSocketOption(SocketOptionLevel.Tcp, SocketOptionName.NoDelay, noDelay); Log.Comment("Testing with port 0"); testSockets.Startup(0, 0); testSockets.socketServer.Listen(1); testSockets.socketClient.Connect(testSockets.epServer); Log.Comment("send lots of small packets."); int bytesSent = 0; for (int i = 0; i < 140; ++i) { bytesSent += testSockets.socketClient.Send(testSockets.bufSend); } using (Socket sock = testSockets.socketServer.Accept()) { byte[] recBytes = new byte[486*testSockets.bufSend.Length]; int bytesReceived = sock.Available; bytesReceived = sock.Receive(recBytes); if (noDelay) bytesReceivedNoDelay = bytesReceived; else bytesReceivedDelay = bytesReceived; Log.Comment("BytesSent: " + bytesSent + " BytesReceived: " + bytesReceived); } } catch (SocketException e) { Log.Comment("Caught exception: " + e.Message); Log.Comment("ErrorCode: " + e.ErrorCode.ToString()); testResult = TestResult.Fail; } catch (Exception e) { Log.Comment("Caught exception: " + e.Message); testResult = TestResult.Fail; } finally { testSockets.TearDown(); } noDelay = !noDelay; } while (noDelay); if (bytesReceivedNoDelay < bytesReceivedDelay) { testResult = TestResult.Fail; Log.Comment("We've received more bytes with nodelay enabled."); } return testResult; } [TestMethod] public TestResult SocketTest1_TCP_ReceiveTimeout() { /// ///1. Starts a server socket listening for TCP ///2. Starts a client socket connected to the server ///3. Verifies that data can be correctly sent and recieved ///4. Verifies Receive timeout is functional /// /////////skip this test for the emulator since setting socket options is not supported. //////if (Microsoft.SPOT.Hardware.SystemInfo.SystemID.SKU == 3) ////// return TestResult.Skip; TestResult testResult = TestResult.Fail; Socket server = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); Socket client = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); try { int receiveTimeout = (int)server.GetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReceiveTimeout); Log.Comment("Get the receiveTimeout size on the server = " + receiveTimeout); int newTimeout = 1000; Log.Comment("Set the receiveTimeout size on the server = " + newTimeout); server.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReceiveTimeout, newTimeout); int receiveTimeout2 = (int)server.GetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReceiveTimeout); Log.Comment("The new receiveTimeout size on the server=" + receiveTimeout2); Log.Comment("Testing with port 0"); client.Bind(new IPEndPoint(IPAddress.Loopback, 0)); server.Bind(new IPEndPoint(IPAddress.Loopback, 0)); IPEndPoint epClient = (IPEndPoint)client.LocalEndPoint; IPEndPoint epServer = (IPEndPoint)server.LocalEndPoint; server.Listen(1); client.Connect(epServer); using (Socket sock = server.Accept()) { byte[] recBytes = new byte[12000]; Log.Comment("Dont send any data. This will cause receive to timeout."); //int bytesSent = client.Send(new byte[1]); try { Log.Comment("Receiving bytes."); server.Receive(recBytes); Log.Comment("Receive returned unexpectedly"); } catch (SocketException e) { Log.Comment("correctly threw exception after Receive Timeout on server: " + e); testResult = TestResult.Pass; } catch (Exception e) { Log.Comment("incorrectly threw exception: " + e); testResult = TestResult.Fail; } } } catch (SocketException e) { if (e.ErrorCode == (int)SocketError.ProtocolOption) { testResult = TestResult.Skip; } else { Log.Comment("Caught exception: " + e.Message); Log.Comment("ErrorCode: " + e.ErrorCode.ToString()); testResult = TestResult.Fail; } } catch (Exception e) { Log.Comment("Caught exception: " + e.Message); testResult = TestResult.Fail; } finally { server.Close(); client.Close(); } return testResult; } [TestMethod] public TestResult SocketTest1_TCP_SendTimeout() { /// ///1. Starts a server socket listening for TCP ///2. Starts a client socket connected to the server ///3. Verifies that data can be correctly sent and recieved ///4. Verifies Send timeout is functional /// /////////skip this test for the emulator since setting socket options is not supported. //////if (Microsoft.SPOT.Hardware.SystemInfo.SystemID.SKU == 3) ////// return TestResult.Skip; TestResult testResult = TestResult.Fail; Socket server = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); Socket client = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); try { int sendTimeout = (int)client.GetSocketOption(SocketOptionLevel.Socket, SocketOptionName.SendTimeout); Log.Comment("Get the SendTimeout size on the server = " + sendTimeout); int newTimeout = 1000; Log.Comment("Set the receiveTimeout size on the server = " + newTimeout); client.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.SendTimeout, newTimeout); int sendTimeout2 = (int)client.GetSocketOption(SocketOptionLevel.Socket, SocketOptionName.SendTimeout); Log.Comment("The new SendTimeout size on the server=" + sendTimeout2); Log.Comment("Testing with port 0"); client.Bind(new IPEndPoint(IPAddress.Loopback, 0)); server.Bind(new IPEndPoint(IPAddress.Loopback, 0)); IPEndPoint epClient = (IPEndPoint)client.LocalEndPoint; IPEndPoint epServer = (IPEndPoint)server.LocalEndPoint; server.Listen(1); client.Connect(epServer); using (Socket sock = server.Accept()) { byte[] recBytes = new byte[12000]; Log.Comment("Send to a closed server to cause a timeout."); try { for( int i=0; i<1000; ++i) { int bytesSent = client.Send(recBytes); } Log.Comment("Receiving bytes."); testResult = TestResult.Fail; } catch (SocketException e) { Log.Comment("correctly threw exception after Send Timeout on server: " + e); testResult = TestResult.Pass; } catch (Exception e) { Log.Comment("incorrectly threw exception: " + e); testResult = TestResult.Fail; } } } catch (SocketException e) { if (e.ErrorCode == (int)SocketError.ProtocolOption) { testResult = TestResult.Skip; } else { Log.Comment("Caught exception: " + e.Message); Log.Comment("ErrorCode: " + e.ErrorCode.ToString()); testResult = TestResult.Fail; } } catch (Exception e) { Log.Comment("Caught exception: " + e.Message); testResult = TestResult.Fail; } finally { server.Close(); client.Close(); } return testResult; } [TestMethod] public TestResult SocketTest2_BasicUDP() { /// /// 1. Starts a server socket listening for UDP /// 2. Starts a client socket sending UDP packets /// 3. Verifies that data can be correctly sent and recieved /// /// bool testResult = true; SocketPair testSockets = null; try { testSockets = new SocketPair(ProtocolType.Udp, SocketType.Dgram); Log.Comment("Testing with port 0"); testSockets.Startup(0, 0); int cBytes = testSockets.socketClient.SendTo( testSockets.bufSend, testSockets.epServer); if (cBytes != testSockets.bufSend.Length) throw new Exception("Send failed, wrong length"); EndPoint epFrom = new IPEndPoint(IPAddress.Any, 0); cBytes = testSockets.socketServer.ReceiveFrom(testSockets.bufReceive, ref epFrom); if (testSockets.epClient.Address.ToString() != ((IPEndPoint)epFrom).Address.ToString()) throw new Exception("Bad address"); } catch (SocketException e) { if (e.ErrorCode == 10047) { Log.Comment("Address family not supported by protocol family."); Log.Comment("This exception is thrown by the device driver that doesnt' implement Loopback for UDP"); } else { testResult = false; Log.Comment("Fail for any other error codes that we don't know about"); } } catch (Exception e) { Log.Comment("Caught exception: " + e.Message); //////if (e.GetType() == Type.GetType("System.Net.Sockets.SocketException")) ////// Log.Comment("ErrorCode: " + ((SocketException)e).ErrorCode); testResult = false; } finally { if (testSockets != null) { testSockets.TearDown(); testSockets = null; } } return (testResult ? TestResult.Pass : TestResult.Fail); } [TestMethod] public TestResult SocketTest3_SocketOption() { /// /// 1. Creates a pair of UDP sockets /// 3. Verifies that SocketOptions can be correctly set and got /// /// bool testResult = true; SocketPair testSockets = null; try { testSockets = new SocketPair(ProtocolType.Udp, SocketType.Dgram); Log.Comment("Testing with port 0"); testSockets.Startup(0, 0); int iSet = 0x1024; int iGet; testSockets.socketClient.SetSocketOption( SocketOptionLevel.Socket, SocketOptionName.ReceiveBuffer, iSet); iGet = (int)testSockets.socketClient.GetSocketOption( SocketOptionLevel.Socket, SocketOptionName.ReceiveBuffer); if (iSet != iGet) throw new Exception("Socket option flag ints differ"); testSockets.socketClient.SetSocketOption( SocketOptionLevel.Socket, SocketOptionName.SendBuffer, iSet); iGet = (int)testSockets.socketClient.GetSocketOption( SocketOptionLevel.Socket, SocketOptionName.SendBuffer); if (iSet != iGet) throw new Exception("Socket option flag ints differ"); bool fSet = true; bool fGet; try { testSockets.socketClient.SetSocketOption( SocketOptionLevel.Socket, SocketOptionName.ReuseAddress, fSet); fGet = ((int)testSockets.socketClient.GetSocketOption( SocketOptionLevel.Socket, SocketOptionName.ReuseAddress) == 0x1); if (fSet != fGet) throw new Exception("Socket option flag bools differ"); } catch (SocketException se) { if (se.ErrorCode != (int)SocketError.ProtocolOption) throw; } } catch (Exception e) { Log.Comment("Caught exception: " + e.Message); //////if (e.GetType() == Type.GetType("System.Net.Sockets.SocketException")) ////// Log.Comment("ErrorCode: " + ((SocketException)e).ErrorCode); testResult = false; } finally { if (testSockets != null) { testSockets.TearDown(); testSockets = null; } } return (testResult ? TestResult.Pass : TestResult.Fail); } [TestMethod] public TestResult SocketTest5_BasicRAW() { /// /// 1. Starts a server socket listening for Raw /// 2. Starts a client socket connected to the server /// 3. Verifies that data can be correctly sent and recieved /// /// bool testResult = true; SocketPair testSockets = null; try { testSockets = new SocketPair(ProtocolType.Raw, SocketType.Raw); testSockets.Startup(0, 0); testSockets.socketServer.Listen(1); testSockets.socketClient.Connect(testSockets.epServer); int cBytes = testSockets.socketClient.Send(testSockets.bufSend); if (cBytes != testSockets.bufSend.Length) throw new Exception("Send failed, wrong length"); using (Socket sock = testSockets.socketServer.Accept()) { if (sock.LocalEndPoint == null) throw new Exception("LocalEndPoint is null"); //Fix? if (testSockets.socketServer.LocalEndPoint.ToString() != sock.LocalEndPoint.ToString()) throw new Exception("LocalEndPoint is incorrect"); if (sock.RemoteEndPoint == null) throw new Exception("RemoteEndPoint is null"); if (testSockets.socketClient.LocalEndPoint.ToString() != sock.RemoteEndPoint.ToString()) throw new Exception("RemoteEndPoint is incorrect"); cBytes = sock.Available; if (cBytes != testSockets.bufSend.Length) throw new Exception("Send failed, wrong length"); cBytes = sock.Receive(testSockets.bufReceive); } testSockets.AssertDataReceived(cBytes); } catch (SocketException e) { Log.Comment("Caught exception: " + e.Message); Log.Comment("ErrorCode: " + ((SocketException)e).ErrorCode); } catch (Exception e) { Log.Comment("Caught exception: " + e.Message); //////if (e.GetType() == Type.GetType("System.Net.Sockets.SocketException")) ////// Log.Comment("ErrorCode: " + ((SocketException)e).ErrorCode); testResult = false; } finally { if (testSockets != null) { testSockets.TearDown(); testSockets = null; } } return (testResult ? TestResult.Pass : TestResult.Fail); } [TestMethod] public TestResult SocketTest6_TCPRecieve() { /// /// 1. Starts a server socket listening for TCP /// 2. Starts a client socket connected to the server /// 3. Verifies that data can be correctly sent and recieved using /// each prototype of Recieve method /// 4. Verifies that exceptions are correctly thrown for Recieve calls that have /// bad Offset or Size parameters /// /// bool testResult = true; SocketPair testSockets = null; try { testSockets = new SocketPair(ProtocolType.Tcp, SocketType.Stream); Log.Comment("Testing with port 0"); testSockets.Startup(0, 0); testSockets.socketServer.Listen(1); testSockets.socketClient.Connect(testSockets.epServer); int cBytes = testSockets.socketClient.Send(testSockets.bufSend); using (Socket sock = testSockets.socketServer.Accept()) { cBytes = sock.Available; cBytes = sock.Receive(testSockets.bufReceive, SocketFlags.None); } testSockets.AssertDataReceived(cBytes); } catch (Exception e) { Log.Comment("Caught exception in Recieve with Byte Array, SocketFlags: " + e.Message); //////if (e.GetType() == Type.GetType("System.Net.Sockets.SocketException")) ////// Log.Comment("ErrorCode: " + ((SocketException)e).ErrorCode); testResult = false; } finally { if (testSockets != null) { testSockets.TearDown(); testSockets = null; } } try { testSockets = new SocketPair(ProtocolType.Tcp, SocketType.Stream); Log.Comment("Testing with port 0"); testSockets.Startup(0, 0); testSockets.socketServer.Listen(1); testSockets.socketClient.Connect(testSockets.epServer); int cBytes = testSockets.socketClient.Send(testSockets.bufSend); using (Socket sock = testSockets.socketServer.Accept()) { cBytes = sock.Available; cBytes = sock.Receive(testSockets.bufReceive, testSockets.bufSend.Length, SocketFlags.None); } testSockets.AssertDataReceived(cBytes); } catch (Exception e) { Log.Comment("Caught exception in Recieve with Byte Array, Int, SocketFlags: " + e.Message); //////if (e.GetType() == Type.GetType("System.Net.Sockets.SocketException")) ////// Log.Comment("ErrorCode: " + ((SocketException)e).ErrorCode); testResult = false; } finally { if (testSockets != null) { testSockets.TearDown(); testSockets = null; } } bool subResult = false; try { testSockets = new SocketPair(ProtocolType.Tcp, SocketType.Stream); Log.Comment("Testing with port 0"); testSockets.Startup(0, 0); testSockets.socketServer.Listen(1); testSockets.socketClient.Connect(testSockets.epServer); int cBytes = testSockets.socketClient.Send(testSockets.bufSend); using (Socket sock = testSockets.socketServer.Accept()) { cBytes = sock.Available; cBytes = sock.Receive(testSockets.bufReceive, testSockets.bufSend.Length + 2, SocketFlags.None); } testSockets.AssertDataReceived(cBytes); } catch (System.IndexOutOfRangeException) { Log.Comment("IndexOutOfRangeException Successfully Caught"); subResult = true; } catch (Exception e) { Log.Comment("Caught exception in Recieve with Byte Array, Int, SocketFlags: " + e.Message); //////if (e.GetType() == Type.GetType("System.Net.Sockets.SocketException")) ////// Log.Comment("ErrorCode: " + ((SocketException)e).ErrorCode); testResult = false; subResult = true; } finally { if (testSockets != null) { testSockets.TearDown(); testSockets = null; } if (!subResult) Log.Comment("Erroneously succeeded with bad Int-Size parameter"); testResult &= subResult; } try { testSockets = new SocketPair(ProtocolType.Tcp, SocketType.Stream); Log.Comment("Testing with port 0"); testSockets.Startup(0, 0); testSockets.socketServer.Listen(1); testSockets.socketClient.Connect(testSockets.epServer); int cBytes = testSockets.socketClient.Send(testSockets.bufSend); using (Socket sock = testSockets.socketServer.Accept()) { cBytes = sock.Available; cBytes = sock.Receive(testSockets.bufReceive, 0, testSockets.bufSend.Length, SocketFlags.None); } testSockets.AssertDataReceived(cBytes); } catch (Exception e) { Log.Comment("Caught exception in Recieve with Byte Array, Int-Offset," + "Int-Size, SocketFlags: " + e.Message); //////if (e.GetType() == Type.GetType("System.Net.Sockets.SocketException")) ////// Log.Comment("ErrorCode: " + ((SocketException)e).ErrorCode); testResult = false; } finally { if (testSockets != null) { testSockets.TearDown(); testSockets = null; } } subResult = false; try { testSockets = new SocketPair(ProtocolType.Tcp, SocketType.Stream); Log.Comment("Testing with port 0"); testSockets.Startup(0, 0); testSockets.socketServer.Listen(1); testSockets.socketClient.Connect(testSockets.epServer); int cBytes = testSockets.socketClient.Send(testSockets.bufSend); using (Socket sock = testSockets.socketServer.Accept()) { cBytes = sock.Available; cBytes = sock.Receive(testSockets.bufReceive, 2, testSockets.bufSend.Length, SocketFlags.None); } testSockets.AssertDataReceived(cBytes); } catch (System.IndexOutOfRangeException) { Log.Comment("IndexOutOfRangeException Successfully Caught"); subResult = true; } catch (Exception e) { Log.Comment("Caught exception in Recieve with Byte Array," + " Int-Offset, Int-Size, SocketFlags: " + e.Message); //////if (e.GetType() == Type.GetType("System.Net.Sockets.SocketException")) ////// Log.Comment("ErrorCode: " + ((SocketException)e).ErrorCode); testResult = false; subResult = true; } finally { if (testSockets != null) { testSockets.TearDown(); testSockets = null; } if (!subResult) Log.Comment("Erroneously succeeded with bad Int-Offset parameter"); testResult &= subResult; } try { testSockets = new SocketPair(ProtocolType.Tcp, SocketType.Stream); Log.Comment("Testing with port 0"); testSockets.Startup(0, 0); testSockets.socketServer.Listen(1); testSockets.socketClient.Connect(testSockets.epServer); int cBytes = testSockets.socketClient.Send(testSockets.bufSend, 1, testSockets.bufSend.Length - 1, SocketFlags.None); int throwAway; using (Socket sock = testSockets.socketServer.Accept()) { throwAway = sock.Available; cBytes = sock.Receive(testSockets.bufReceive, 1, 2, SocketFlags.None); throwAway = testSockets.socketClient.Send(testSockets.bufSend, 0, 1, SocketFlags.None); throwAway = sock.Available; cBytes += sock.Receive(testSockets.bufReceive, 0, 1, SocketFlags.None); } testSockets.AssertDataReceived(cBytes); } catch (Exception e) { Log.Comment("Caught exception in Recieve with Byte Array, " + "Int-Offset, Int-Size, SocketFlags: " + e.Message); //////if (e.GetType() == Type.GetType("System.Net.Sockets.SocketException")) ////// Log.Comment("ErrorCode: " + ((SocketException)e).ErrorCode); testResult = false; } finally { if (testSockets != null) { testSockets.TearDown(); testSockets = null; } } return (testResult ? TestResult.Pass : TestResult.Fail); } [TestMethod] public TestResult SocketTest7_TCPSend() { /// /// 1. Starts a server socket listening for TCP /// 2. Starts a client socket connected to the server /// 3. Verifies that data can be correctly sent and recieved using /// each prototype of Send method /// 4. Verifies that exceptions are correctly thrown for Send calls that have /// bad Offset or Size parameters /// /// bool testResult = true; SocketPair testSockets = null; try { testSockets = new SocketPair(ProtocolType.Tcp, SocketType.Stream); Log.Comment("Testing with port 0"); testSockets.Startup(0, 0); testSockets.socketServer.Listen(1); testSockets.socketClient.Connect(testSockets.epServer); int cBytes = testSockets.socketClient.Send(testSockets.bufSend, SocketFlags.None); using (Socket sock = testSockets.socketServer.Accept()) { cBytes = sock.Available; cBytes = sock.Receive(testSockets.bufReceive); } testSockets.AssertDataReceived(cBytes); } catch (Exception e) { Log.Comment("Caught exception in Send with Byte Array, SocketFlags: " + e.Message); //////if (e.GetType() == Type.GetType("System.Net.Sockets.SocketException")) ////// Log.Comment("ErrorCode: " + ((SocketException)e).ErrorCode); testResult = false; } finally { if (testSockets != null) { testSockets.TearDown(); testSockets = null; } } try { testSockets = new SocketPair(ProtocolType.Tcp, SocketType.Stream); Log.Comment("Testing with port 0"); testSockets.Startup(0, 0); testSockets.socketServer.Listen(1); testSockets.socketClient.Connect(testSockets.epServer); int cBytes = testSockets.socketClient.Send(testSockets.bufSend, testSockets.bufSend.Length, SocketFlags.None); using (Socket sock = testSockets.socketServer.Accept()) { cBytes = sock.Available; cBytes = sock.Receive(testSockets.bufReceive); } testSockets.AssertDataReceived(cBytes); } catch (Exception e) { Log.Comment("Caught exception in Send with Byte Array, Int, SocketFlags: " + e.Message); //////if (e.GetType() == Type.GetType("System.Net.Sockets.SocketException")) ////// Log.Comment("ErrorCode: " + ((SocketException)e).ErrorCode); testResult = false; } finally { if (testSockets != null) { testSockets.TearDown(); testSockets = null; } } bool subResult = false; try { testSockets = new SocketPair(ProtocolType.Tcp, SocketType.Stream); Log.Comment("Testing with port 0"); testSockets.Startup(0, 0); testSockets.socketServer.Listen(1); testSockets.socketClient.Connect(testSockets.epServer); int cBytes = testSockets.socketClient.Send(testSockets.bufSend, testSockets.bufSend.Length + 2, SocketFlags.None); using (Socket sock = testSockets.socketServer.Accept()) { cBytes = sock.Available; cBytes = sock.Receive(testSockets.bufReceive); } testSockets.AssertDataReceived(cBytes); } catch (System.IndexOutOfRangeException) { Log.Comment("IndexOutOfRangeException Successfully Caught"); subResult = true; } catch (Exception e) { Log.Comment("Caught exception in Send with Byte Array, Int, SocketFlags: " + e.Message); //////if (e.GetType() == Type.GetType("System.Net.Sockets.SocketException")) ////// Log.Comment("ErrorCode: " + ((SocketException)e).ErrorCode); testResult = false; subResult = true; } finally { if (testSockets != null) { testSockets.TearDown(); testSockets = null; } if (!subResult) Log.Comment("Erroneously succeeded with bad Int-Size parameter"); testResult &= subResult; } try { testSockets = new SocketPair(ProtocolType.Tcp, SocketType.Stream); Log.Comment("Testing with port 0"); testSockets.Startup(0, 0); testSockets.socketServer.Listen(1); testSockets.socketClient.Connect(testSockets.epServer); int cBytes = testSockets.socketClient.Send(testSockets.bufSend, 0, testSockets.bufSend.Length, SocketFlags.None); using (Socket sock = testSockets.socketServer.Accept()) { cBytes = sock.Available; cBytes = sock.Receive(testSockets.bufReceive); } testSockets.AssertDataReceived(cBytes); } catch (Exception e) { Log.Comment("Caught exception in Send with Byte Array, Int-Offset, " + "Int-Size, SocketFlags: " + e.Message); //////if (e.GetType() == Type.GetType("System.Net.Sockets.SocketException")) ////// Log.Comment("ErrorCode: " + ((SocketException)e).ErrorCode); testResult = false; } finally { if (testSockets != null) { testSockets.TearDown(); testSockets = null; } } subResult = false; try { testSockets = new SocketPair(ProtocolType.Tcp, SocketType.Stream); Log.Comment("Testing with port 0"); testSockets.Startup(0, 0); testSockets.socketServer.Listen(1); testSockets.socketClient.Connect(testSockets.epServer); int cBytes = testSockets.socketClient.Send(testSockets.bufSend, 2, testSockets.bufSend.Length, SocketFlags.None); using (Socket sock = testSockets.socketServer.Accept()) { cBytes = sock.Available; cBytes = sock.Receive(testSockets.bufReceive); } testSockets.AssertDataReceived(cBytes); } catch (System.IndexOutOfRangeException) { Log.Comment("IndexOutOfRangeException Successfully Caught"); subResult = true; } catch (Exception e) { Log.Comment("Caught exception in Send with Byte Array, Int-Offset, " + "Int-Size, SocketFlags: " + e.Message); //////if (e.GetType() == Type.GetType("System.Net.Sockets.SocketException")) ////// Log.Comment("ErrorCode: " + ((SocketException)e).ErrorCode); testResult = false; subResult = true; } finally { if (testSockets != null) { testSockets.TearDown(); testSockets = null; } if (!subResult) Log.Comment("Erroneously succeeded with bad Int-Offset parameter"); testResult &= subResult; } return (testResult ? TestResult.Pass : TestResult.Fail); } [TestMethod] public TestResult SocketTest8_TCPRecieveFrom() { /// /// 1. Starts a server socket listening for TCP /// 2. Starts a client socket connected to the server /// 3. Verifies that data can be correctly sent and Recieved using /// each prototype of RecieveFrom method /// 4. Verifies that exceptions are correctly thrown for RecieveFrom calls that have /// bad Offset or Size parameters /// /// TestResult testResult = TestResult.Pass; SocketPair testSockets = null; try { testSockets = new SocketPair(ProtocolType.Tcp, SocketType.Stream); Log.Comment("Testing with port 0"); testSockets.Startup(0, 0); EndPoint remoteEndPoint = testSockets.epClient.Create(testSockets.epClient.Serialize()); testSockets.socketServer.Listen(1); testSockets.socketClient.Connect(testSockets.epServer); int cBytes = testSockets.socketClient.Send(testSockets.bufSend); using (Socket sock = testSockets.socketServer.Accept()) { cBytes = sock.ReceiveFrom(testSockets.bufReceive, 0, testSockets.bufSend.Length, SocketFlags.None, ref remoteEndPoint); } testSockets.AssertDataReceived(cBytes); testSockets.TearDown(); } catch (Exception e) { Log.Comment("Caught exception in RecieveFrom with Byte Array," + " Int, SocketFlags: " + e.Message); testResult = TestResult.Fail; } finally { if (testSockets != null) { testSockets.TearDown(); testSockets = null; } } return testResult; } [TestMethod] public TestResult SocketTest9_TCPSendTo() { /// /// 1. Starts a server socket listening for TCP /// 2. Starts a client socket connected to the server /// 3. Verifies that data can be correctly sent and recieved using /// each prototype of SendTo method /// 4. Verifies that exceptions are correctly thrown for SendTo calls that have /// bad Offset or Size parameters /// /// SocketPair testSockets = null; bool testResult = true; try { testSockets = new SocketPair(ProtocolType.Tcp, SocketType.Stream); Log.Comment("Testing with port 0"); testSockets.Startup(0, 0); EndPoint serverEndPoint = testSockets.epServer.Create( testSockets.epServer.Serialize()); testSockets.socketServer.Listen(1); testSockets.socketClient.Connect(testSockets.epServer); int cBytes = testSockets.socketClient.SendTo(testSockets.bufSend, SocketFlags.None, serverEndPoint); using (Socket sock = testSockets.socketServer.Accept()) { cBytes = sock.Available; cBytes = sock.Receive(testSockets.bufReceive); } testSockets.AssertDataReceived(cBytes); } catch (Exception e) { Log.Comment("Caught exception in SendTo with Byte Array, SocketFlags: " + e.Message); //////if (e.GetType() == Type.GetType("System.Net.Sockets.SocketException")) ////// Log.Comment("ErrorCode: " + ((SocketException)e).ErrorCode); testResult = false; } finally { if (testSockets != null) { testSockets.TearDown(); testSockets = null; } } try { testSockets = new SocketPair(ProtocolType.Tcp, SocketType.Stream); Log.Comment("Testing with port 0"); testSockets.Startup(0, 0); EndPoint serverEndPoint = testSockets.epServer.Create( testSockets.epServer.Serialize()); testSockets.socketServer.Listen(1); testSockets.socketClient.Connect(testSockets.epServer); int cBytes = testSockets.socketClient.SendTo( testSockets.bufSend, testSockets.bufSend.Length, SocketFlags.None, serverEndPoint); using (Socket sock = testSockets.socketServer.Accept()) { cBytes = sock.Available; cBytes = sock.Receive(testSockets.bufReceive); } testSockets.AssertDataReceived(cBytes); } catch (Exception e) { Log.Comment("Caught exception in SendTo with Byte Array, Int, SocketFlags: " + e.Message); //////if (e.GetType() == Type.GetType("System.Net.Sockets.SocketException")) ////// Log.Comment("ErrorCode: " + ((SocketException)e).ErrorCode); testResult = false; } finally { if (testSockets != null) { testSockets.TearDown(); testSockets = null; } } bool subResult = false; try { testSockets = new SocketPair(ProtocolType.Tcp, SocketType.Stream); Log.Comment("Testing with port 0"); testSockets.Startup(0, 0); EndPoint serverEndPoint = testSockets.epServer.Create( testSockets.epServer.Serialize()); testSockets.socketServer.Listen(1); testSockets.socketClient.Connect(testSockets.epServer); int cBytes = testSockets.socketClient.SendTo(testSockets.bufSend, testSockets.bufSend.Length + 2, SocketFlags.None, serverEndPoint); using (Socket sock = testSockets.socketServer.Accept()) { cBytes = sock.Available; cBytes = sock.Receive(testSockets.bufReceive); } testSockets.AssertDataReceived(cBytes); } catch (System.IndexOutOfRangeException) { Log.Comment("IndexOutOfRangeException Successfully Caught"); subResult = true; } catch (Exception e) { Log.Comment("Caught exception in SendTo with Byte Array, Int, SocketFlags: " + e.Message); //////if (e.GetType() == Type.GetType("System.Net.Sockets.SocketException")) ////// Log.Comment("ErrorCode: " + ((SocketException)e).ErrorCode); testResult = false; subResult = true; } finally { if (testSockets != null) { testSockets.TearDown(); testSockets = null; } if (!subResult) Log.Comment("Erroneously succeeded with bad Int-Size parameter"); testResult &= subResult; } try { testSockets = new SocketPair(ProtocolType.Tcp, SocketType.Stream); Log.Comment("Testing with port 0"); testSockets.Startup(0, 0); EndPoint serverEndPoint = testSockets.epServer.Create( testSockets.epServer.Serialize()); testSockets.socketServer.Listen(1); testSockets.socketClient.Connect(testSockets.epServer); int cBytes = testSockets.socketClient.SendTo( testSockets.bufSend, 0, testSockets.bufSend.Length, SocketFlags.None, serverEndPoint); using (Socket sock = testSockets.socketServer.Accept()) { cBytes = sock.Available; cBytes = sock.Receive(testSockets.bufReceive); } testSockets.AssertDataReceived(cBytes); } catch (Exception e) { Log.Comment("Caught exception in SendTo with Byte Array," + " Int-Offset, Int-Size, SocketFlags: " + e.Message); //////if (e.GetType() == Type.GetType("System.Net.Sockets.SocketException")) ////// Log.Comment("ErrorCode: " + ((SocketException)e).ErrorCode); testResult = false; } finally { if (testSockets != null) { testSockets.TearDown(); testSockets = null; } } subResult = false; try { testSockets = new SocketPair(ProtocolType.Tcp, SocketType.Stream); Log.Comment("Testing with port 0"); testSockets.Startup(0, 0); EndPoint serverEndPoint = testSockets.epServer.Create( testSockets.epServer.Serialize()); testSockets.socketServer.Listen(1); testSockets.socketClient.Connect(testSockets.epServer); int cBytes = testSockets.socketClient.SendTo( testSockets.bufSend, 2, testSockets.bufSend.Length, SocketFlags.None, serverEndPoint); using (Socket sock = testSockets.socketServer.Accept()) { cBytes = sock.Available; cBytes = sock.Receive(testSockets.bufReceive); } testSockets.AssertDataReceived(cBytes); testSockets.TearDown(); testSockets = null; } catch (System.IndexOutOfRangeException) { Log.Comment("IndexOutOfRangeException Successfully Caught"); subResult = true; } catch (Exception e) { Log.Comment("Caught exception in SendTo with Byte Array," + " Int-Offset, Int-Size, SocketFlags: " + e.Message); //////if (e.GetType() == Type.GetType("System.Net.Sockets.SocketException")) ////// Log.Comment("ErrorCode: " + ((SocketException)e).ErrorCode); testResult = false; subResult = true; } finally { if (!subResult) Log.Comment("Erroneously succeeded with bad Int-Offset parameter"); testResult &= subResult; } return (testResult ? TestResult.Pass : TestResult.Fail); } [TestMethod] public TestResult SocketTest10_TCPPoll() { /// /// 1. Starts a server socket listening for TCP /// 2. Starts a client socket connected to the server /// 3. Transfers some data /// 4. Verifies that Poll returns correct results after each individual /// function is called. /// /// bool testResult = true; try { SocketPair testSockets = new SocketPair(ProtocolType.Tcp, SocketType.Stream); Log.Comment("Testing with port 0"); testSockets.Startup(0, 0); testSockets.socketServer.Listen(1); Log.Comment("Listen called"); testSockets.socketClient.Connect(testSockets.epServer); Log.Comment("Connect called"); int cBytes = testSockets.socketClient.Send(testSockets.bufSend); Log.Comment("Send called"); testResult = (testSockets.socketClient.Poll(1000, SelectMode.SelectWrite) == true); testResult = (testSockets.socketServer.Poll(1000, SelectMode.SelectRead) == true); using (Socket sock = testSockets.socketServer.Accept()) { Log.Comment("Accept called"); testResult = (testSockets.socketClient.Poll(1000, SelectMode.SelectWrite) == true); cBytes = sock.Available; Log.Comment("Available bytes assigned"); testResult = (testSockets.socketClient.Poll(1000, SelectMode.SelectWrite) == true); cBytes = sock.Receive(testSockets.bufReceive); Log.Comment("Recieve called"); testResult = (testSockets.socketClient.Poll(1000, SelectMode.SelectWrite) == true); } testSockets.AssertDataReceived(cBytes); testSockets.TearDown(); testSockets = null; } catch (Exception e) { Log.Comment("Caught exception: " + e.Message); //////if (e.GetType() == Type.GetType("System.Net.Sockets.SocketException")) ////// Log.Comment("ErrorCode: " + ////// ((SocketException)e).ErrorCode); testResult = false; } return (testResult ? TestResult.Pass : TestResult.Fail); } [TestMethod] public TestResult SocketTest11_SetSocketOptionBasic() { /// /// 1. Call SetSocketOption with each of its signatures /// /// bool isAnyCatch = false; try { SocketPair testSockets = new SocketPair(ProtocolType.Tcp, SocketType.Stream); // check the bool testSockets.socketClient.SetSocketOption( SocketOptionLevel.Socket, SocketOptionName.Linger, true); bool linger = (0 != (int)testSockets.socketClient.GetSocketOption( SocketOptionLevel.Socket, SocketOptionName.Linger)); if (!linger) throw new Exception("Linger was not enabled"); int lingerTime = 20; testSockets.socketClient.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.Linger, lingerTime); int lingerResult = (int)testSockets.socketClient.GetSocketOption( SocketOptionLevel.Socket, SocketOptionName.Linger); if (lingerResult != lingerTime) throw new Exception("Linger time was not set correctly"); // check the bool again for false testSockets.socketClient.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.Linger, false); bool notLinger = (0 == (int)testSockets.socketClient.GetSocketOption( SocketOptionLevel.Socket, SocketOptionName.Linger)); if (!notLinger) throw new Exception("Linger was not disabled"); // proceed to bind Log.Comment("Testing with port 0"); testSockets.Startup(0, 0); testSockets.socketServer.Listen(1); testSockets.socketClient.Connect(testSockets.epServer); int cBytes = testSockets.socketClient.Send(testSockets.bufSend); using (Socket sock = testSockets.socketServer.Accept()) { cBytes = sock.Receive(testSockets.bufReceive); testSockets.AssertDataReceived(cBytes); } testSockets.TearDown(); testSockets = null; } catch (Exception e) { isAnyCatch = true; Log.Comment("Exception caught: " + e.Message); //////if (e.GetType() == Type.GetType("System.Net.Sockets.SocketException")) ////// Log.Comment("ErrorCode: " + ((SocketException)e).ErrorCode); } return (!isAnyCatch ? TestResult.Pass : TestResult.Fail); } [TestMethod] public TestResult SocketTest13_DPWSOptions() { /// /// 1. Starts a server socket listening for UDP /// 2. Starts a client socket sending UDP packets /// 3. Verifies that data can be correctly sent and recieved /// /// ////////don't run on the emulator since this isn't supported //////if (Microsoft.SPOT.Hardware.SystemInfo.SystemID.SKU == 3) ////// return TestResult.Skip; bool testResult = true; try { SocketPair testSockets = new SocketPair(ProtocolType.Udp, SocketType.Dgram); NetworkInterface[] inter = NetworkInterface.GetAllNetworkInterfaces(); IPAddress localAddress = SocketTools.ParseAddress(inter[0].IPAddress); try { byte[] local = localAddress.GetAddressBytes(); byte[] multicastOpt = new byte[] { 224, 100, 1, 1, local[0], local[1], local[2], local[3]}; testSockets.socketClient.SetSocketOption(SocketOptionLevel.IP, SocketOptionName.AddMembership, multicastOpt); } catch (SocketException se) { if (se.ErrorCode != (int)SocketError.ProtocolOption) { Log.Comment("Caught exception: " + se.Message); //////if (se.GetType() == Type.GetType("System.Net.Sockets.SocketException")) ////// Log.Comment("ErrorCode: " + se.ErrorCode); testResult = false; } } catch (Exception e) { Log.Comment("Caught exception: " + e.Message); //////if (e.GetType() == Type.GetType("System.Net.Sockets.SocketException")) ////// Log.Comment("ErrorCode: " + ((SocketException)e).ErrorCode); testResult = false; } try { testSockets.socketClient.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReuseAddress, true); } catch (SocketException se) { if (se.ErrorCode != (int)SocketError.ProtocolOption) { Log.Comment("Caught exception: " + se.Message); //////if (se.GetType() == Type.GetType("System.Net.Sockets.SocketException")) ////// Log.Comment("ErrorCode: " + se.ErrorCode); testResult = false; } } catch (Exception e) { Log.Comment("Caught exception: " + e.Message); //////if (e.GetType() == Type.GetType("System.Net.Sockets.SocketException")) ////// Log.Comment("ErrorCode: " + ((SocketException)e).ErrorCode); testResult = false; } try { byte [] bytes = localAddress.GetAddressBytes(); // given the address change it to what SetSocketOption needs testSockets.socketClient.SetSocketOption( SocketOptionLevel.IP, SocketOptionName.MulticastInterface, bytes); } catch (SocketException se) { if (se.ErrorCode != (int)SocketError.ProtocolOption) { Log.Comment("Caught exception: " + se.Message); //////if (se.GetType() == Type.GetType("System.Net.Sockets.SocketException")) ////// Log.Comment("ErrorCode: " + se.ErrorCode); testResult = false; } } catch (Exception e) { Log.Comment("Caught exception: " + e.Message); //////if (e.GetType() == Type.GetType("System.Net.Sockets.SocketException")) ////// Log.Comment("ErrorCode: " + ((SocketException)e).ErrorCode); testResult = false; } try { testSockets.socketClient.SetSocketOption(SocketOptionLevel.IP, SocketOptionName.DontFragment, true); } catch (SocketException se) { if (se.ErrorCode != (int)SocketError.ProtocolOption) { Log.Comment("Caught exception: " + se.Message); //////if (se.GetType() == Type.GetType("System.Net.Sockets.SocketException")) ////// Log.Comment("ErrorCode: " + se.ErrorCode); testResult = false; } } catch (Exception e) { Log.Comment("Caught exception: " + e.Message); //////if (e.GetType() == Type.GetType("System.Net.Sockets.SocketException")) ////// Log.Comment("ErrorCode: " + ((SocketException)e).ErrorCode); testResult = false; } try { testSockets.socketClient.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.Broadcast, false); } catch (SocketException se) { if (se.ErrorCode != (int)SocketError.ProtocolOption) { Log.Comment("Caught exception: " + se.Message); //////if (se.GetType() == Type.GetType("System.Net.Sockets.SocketException")) ////// Log.Comment("ErrorCode: " + se.ErrorCode); testResult = false; } } catch (Exception e) { Log.Comment("Caught exception: " + e.Message); //////if (e.GetType() == Type.GetType("System.Net.Sockets.SocketException")) ////// Log.Comment("ErrorCode: " + ((SocketException)e).ErrorCode); testResult = false; } try { testSockets.socketClient.SetSocketOption(SocketOptionLevel.Udp, SocketOptionName.ExclusiveAddressUse, true); } catch (SocketException se) { if (se.ErrorCode != (int)SocketError.ProtocolOption) { Log.Comment("Caught exception: " + se.Message); //////if (se.GetType() == Type.GetType("System.Net.Sockets.SocketException")) ////// Log.Comment("ErrorCode: " + se.ErrorCode); testResult = false; } } catch (Exception e) { Log.Comment("Caught exception: " + e.Message); //////if (e.GetType() == Type.GetType("System.Net.Sockets.SocketException")) ////// Log.Comment("ErrorCode: " + ((SocketException)e).ErrorCode); testResult = false; } try { int error = (int)testSockets.socketClient.GetSocketOption( SocketOptionLevel.Socket, SocketOptionName.Error); Log.Comment("Current error: " + error.ToString()); } catch (SocketException se) { if (se.ErrorCode != (int)SocketError.ProtocolOption) { Log.Comment("Caught exception: " + se.Message); //////if (se.GetType() == Type.GetType("System.Net.Sockets.SocketException")) ////// Log.Comment("ErrorCode: " + se.ErrorCode); testResult = false; } } catch (Exception e) { Log.Comment("Caught exception: " + e.Message); //////if (e.GetType() == Type.GetType("System.Net.Sockets.SocketException")) ////// Log.Comment("ErrorCode: " + ((SocketException)e).ErrorCode); testResult = false; } try { SocketType type = (SocketType)( (int)testSockets.socketClient.GetSocketOption(SocketOptionLevel.Socket, SocketOptionName.Type)); Log.Comment("Current error: " + type.ToString()); } catch (SocketException se) { if (se.ErrorCode != (int)SocketError.ProtocolOption) { Log.Comment("Caught exception: " + se.Message); //////if (se.GetType() == Type.GetType("System.Net.Sockets.SocketException")) ////// Log.Comment("ErrorCode: " + se.ErrorCode); testResult = false; } } catch (Exception e) { Log.Comment("Caught exception: " + e.Message); //////if (e.GetType() == Type.GetType("System.Net.Sockets.SocketException")) ////// Log.Comment("ErrorCode: " + ((SocketException)e).ErrorCode); testResult = false; } try { int error = (int)testSockets.socketClient.GetSocketOption(SocketOptionLevel.Socket, SocketOptionName.Error); Log.Comment("Current error: " + error.ToString()); } catch (SocketException se) { if (se.ErrorCode != (int)SocketError.ProtocolOption) { Log.Comment("Caught exception: " + se.Message); //////if (se.GetType() == Type.GetType("System.Net.Sockets.SocketException")) ////// Log.Comment("ErrorCode: " + se.ErrorCode); testResult = false; } } catch (Exception e) { Log.Comment("Caught exception: " + e.Message); //////if (e.GetType() == Type.GetType("System.Net.Sockets.SocketException")) ////// Log.Comment("ErrorCode: " + ((SocketException)e).ErrorCode); testResult = false; } try { SocketType type = (SocketType)( (int)testSockets.socketClient.GetSocketOption(SocketOptionLevel.Socket, SocketOptionName.Type)); Log.Comment("Current error: " + type.ToString()); } catch (SocketException se) { if (se.ErrorCode != (int)SocketError.ProtocolOption) { Log.Comment("Caught exception: " + se.Message); //////if (se.GetType() == Type.GetType("System.Net.Sockets.SocketException")) ////// Log.Comment("ErrorCode: " + se.ErrorCode); testResult = false; } } catch (Exception e) { Log.Comment("Caught exception: " + e.Message); //////if (e.GetType() == Type.GetType("System.Net.Sockets.SocketException")) ////// Log.Comment("ErrorCode: " + ((SocketException)e).ErrorCode); testResult = false; } try { byte[] local = localAddress.GetAddressBytes(); byte[] multicastOpt = new byte[] { 224, 100, 1, 1, local[0], local[1], local[2], local[3]}; testSockets.socketClient.SetSocketOption(SocketOptionLevel.IP, SocketOptionName.DropMembership, multicastOpt); } catch (SocketException se) { if (se.ErrorCode != (int)SocketError.ProtocolOption) { Log.Comment("Caught exception: " + se.Message); //////if (se.GetType() == Type.GetType("System.Net.Sockets.SocketException")) ////// Log.Comment("ErrorCode: " + se.ErrorCode); testResult = false; } } catch (Exception e) { Log.Comment("Caught exception: " + e.Message); //////if (e.GetType() == Type.GetType("System.Net.Sockets.SocketException")) ////// Log.Comment("ErrorCode: " + ((SocketException)e).ErrorCode); testResult = false; } try { testSockets.socketClient.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReuseAddress, true); } catch (SocketException se) { if (se.ErrorCode != (int)SocketError.ProtocolOption) { Log.Comment("Caught exception: " + se.Message); //////if (se.GetType() == Type.GetType("System.Net.Sockets.SocketException")) ////// Log.Comment("ErrorCode: " + se.ErrorCode); testResult = false; } } catch (Exception e) { Log.Comment("Caught exception: " + e.Message); //////if (e.GetType() == Type.GetType("System.Net.Sockets.SocketException")) ////// Log.Comment("ErrorCode: " + ((SocketException)e).ErrorCode); testResult = false; } try { testSockets.socketClient.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReceiveBuffer, 0x1024); } catch (SocketException se) { if (se.ErrorCode != (int)SocketError.ProtocolOption) { Log.Comment("Caught exception: " + se.Message); //////if (se.GetType() == Type.GetType("System.Net.Sockets.SocketException")) ////// Log.Comment("ErrorCode: " + se.ErrorCode); testResult = false; } } catch (Exception e) { Log.Comment("Caught exception: " + e.Message); //////if (e.GetType() == Type.GetType("System.Net.Sockets.SocketException")) ////// Log.Comment("ErrorCode: " + ((SocketException)e).ErrorCode); testResult = false; } Log.Comment("Testing with port 0"); testSockets.Startup(0, 0); int cBytes = testSockets.socketClient.SendTo(testSockets.bufSend, testSockets.epServer); if (cBytes != testSockets.bufSend.Length) throw new Exception("Send failed, wrong length"); EndPoint epFrom = new IPEndPoint(IPAddress.Any, 0); cBytes = testSockets.socketServer.ReceiveFrom( testSockets.bufReceive, ref epFrom); if (testSockets.epClient.Address.ToString() != ((IPEndPoint)epFrom).Address.ToString()) throw new Exception("Bad address"); testSockets.TearDown(); testSockets = null; } catch (Exception e) { Log.Comment("Caught exception: " + e.Message); //////if (e.GetType() == Type.GetType("System.Net.Sockets.SocketException")) ////// Log.Comment("ErrorCode: " + ((SocketException)e).ErrorCode); testResult = false; } return (testResult ? TestResult.Pass : TestResult.Fail); } } } ================================================ FILE: Zelig/Zelig/Test/RunTime/NETMF/System/socketTests/SocketTools.cs ================================================ using System; using System.Net; using System.Net.Sockets; namespace Microsoft.Zelig.Test { public class SocketTools { static private int m_portCounter = 0; static public int nextPort { get { int rangeOfPorts = 65000; int startPort = 1024; int retPort = m_portCounter % rangeOfPorts + startPort; m_portCounter++; return retPort; } } static public long DottedDecimalToIp(byte a1, byte a2, byte a3, byte a4) { return (long)((ulong)a4 << 24 | (ulong)a3 << 16 | (ulong)a2 << 8 | (ulong)a1); } static public IPAddress ParseAddress(string ipString) { if (ipString == null) throw new ArgumentNullException("WsdIPAddress.ipString must not be null."); ulong ipAddress = 0L; int lastIndex = 0; int shiftIndex = 0; ulong mask = 0x00000000000000FF; ulong octet = 0L; int length = ipString.Length; for (int i = 0; i < length; ++i) { // Parse to '.' or end of IP address if (ipString[i] == '.' || i == length - 1) // If the IP starts with a '.' // or a segment is longer than 3 characters or shiftIndex > // last bit position throw. if (i == 0 || i - lastIndex > 3 || shiftIndex > 24) throw new Exception("invalid address format (###.###.###.###) " + ipString); else { i = i == length - 1 ? ++i : i; octet = (ulong)(ToInt32(ipString.Substring(lastIndex, i - lastIndex)) & 0x00000000000000FF); ipAddress = ipAddress + (ulong)((octet << shiftIndex) & mask); lastIndex = i + 1; shiftIndex += 8; mask <<= 8; } } return new IPAddress((long)ipAddress); } static public bool ArrayEquals(bool[] array1, bool[] array2) { if (array1.Length != array2.Length) return false; for (int i = 0; i < array1.Length; i++) { if (array1[i] != array2[i]) return false; } return true; } static public bool ArrayEquals(byte[] array1, byte[] array2) { if (array1.Length != array2.Length) return false; for (int i = 0; i < array1.Length; i++) { if (array1[i] != array2[i]) return false; } return true; } //--// static private int ToInt32(string number) { if (number == null) throw new ArgumentNullException("number", "Must not be null."); int result = 0; int digit = 0; int exp = 1; int length = number.Length; char[] num = number.ToCharArray(); switch(length) { case 1 : exp = 1; break; case 2 : exp = 10; break; case 3 : exp = 100; break; default: throw new ArgumentException( "any octet in an IP address can be up to 3 digits long" ); } for (int i = 0; i < length; ++i) { digit = (int)(num[i] - '0'); // Make sure argument number is valid. If not this is not a format specifier if (digit < 0 || digit > 9) throw new ArgumentOutOfRangeException("Format_Argument", number); result = result + (digit * exp); exp /= 10; } return result; } } } ================================================ FILE: Zelig/Zelig/Test/RunTime/NETMF/System/socketTests/SocketsEnumsTests.cs ================================================ /*--------------------------------------------------------------------- * SocketsEnumsTests.cs - file description * Version: 1.0 * Author: REDMOND\a-grchat * Created: 9/13/2007 10:06:40 AM * * Tests the Socket library's enumerations by utilizing each element of each of them * ---------------------------------------------------------------------*/ using System; using System.Reflection; using System.Threading; using System.Net; using System.Net.Sockets; using Microsoft.Llilum.Lwip; namespace Microsoft.Zelig.Test { public class SocketsEnumsTests : TestBase, ITestInterface { [SetUp] public InitializeResult Initialize() { Log.Comment("Adding set up for the tests"); try { // Check networking - we need to make sure we can reach our proxy server System.Net.Dns.GetHostEntry("itgproxy.dns.microsoft.com"); } catch (Exception ex) { Log.Exception("Unable to get address for itgproxy.dns.microsoft.com", ex); return InitializeResult.Skip; } return InitializeResult.ReadyToGo; } [TearDown] public void CleanUp() { Log.Comment("Cleaning up after the tests."); } public override TestResult Run( string[] args ) { return TestResult.Pass; } //--// //--// //--// [TestMethod] public TestResult SocketsEnums8_SocketFlags_Peek() { /// /// 1. Sends TCP data using the Peek flag /// 2. Verifies that the correct exception is thrown /// Further testing would require harness alteration /// /// bool isAnyCatch = false; try { try { SocketPair testSockets = new SocketPair(ProtocolType.Tcp, SocketType.Stream); testSockets.Startup(0, 0); testSockets.socketServer.Listen(1); testSockets.socketClient.Connect(testSockets.epServer); int cBytes = testSockets.socketClient.Send(testSockets.bufSend); using (Socket sock = testSockets.socketServer.Accept()) { cBytes = sock.Receive(testSockets.bufReceive, SocketFlags.Peek); Log.Comment("Checking Peek data"); testSockets.AssertDataReceived(cBytes); int cBytesAgain = sock.Receive(testSockets.bufReceive); if(cBytesAgain < cBytes) throw new Exception( "Peek returns more bytes than the successive read" ); } testSockets.AssertDataReceived(cBytes); testSockets.TearDown(); testSockets = null; } catch (SocketException) { isAnyCatch = true; } } catch (System.Exception e) { isAnyCatch = true; Log.Comment("Incorrect exception caught: " + e.Message); } if (!isAnyCatch) { Log.Comment("No exception caught"); } return (isAnyCatch ? TestResult.Fail : TestResult.Pass); } [TestMethod] public TestResult SocketsEnums9_SocketOptionLevel() { /// /// 1. Tests that Set and GetSocketOption can be called using each member of /// SocketOptionLevel /// /// TODO: Fix Docs for (...Byte[]) /// /// bool isAnyCatch = false; try { SocketPair testSockets = new SocketPair(ProtocolType.Tcp, SocketType.Stream); try { testSockets.socketClient.SetSocketOption(SocketOptionLevel.Tcp, SocketOptionName.NoDelay, false); if (0 != (int)testSockets.socketClient.GetSocketOption( SocketOptionLevel.Tcp, SocketOptionName.NoDelay)) throw new System.Exception("SocketOptionLevel.Tcp failed"); testSockets.socketClient.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.Linger, true); if (0 == (int)testSockets.socketClient.GetSocketOption( SocketOptionLevel.Socket, SocketOptionName.Linger)) throw new System.Exception("SocketOptionLevel.Socket failed"); //testSockets.socketClient.SetSocketOption(SocketOptionLevel.IP, // SocketOptionName.DontFragment, true); //if (0 == (int)testSockets.socketClient.GetSocketOption( // SocketOptionLevel.IP, SocketOptionName.DontFragment)) // throw new System.Exception("SocketOptionLevel.IP failed"); if ((int)testSockets.socketClient.GetSocketOption( SocketOptionLevel.Socket, SocketOptionName.Linger) != 1) throw new System.Exception( "GetSocketOption with Level and Name got wrong data"); byte[] lingerBytes = new byte[] { 0, 0, 0, 0 }; testSockets.socketClient.GetSocketOption( SocketOptionLevel.Socket, SocketOptionName.Linger, lingerBytes); if (!SocketTools.ArrayEquals(lingerBytes, new byte[] { 1, 0, 0, 0 })) throw new System.Exception("GetSocketOption with Level," + " Name and ByteArray got wrong data"); testSockets.Startup(0, 0); testSockets.socketServer.Listen(1); testSockets.socketClient.Connect(testSockets.epServer); testSockets.socketClient.Send(testSockets.bufSend); int cBytes = 0; using (Socket sock = testSockets.socketServer.Accept()) { Thread.Sleep(500); cBytes = sock.Available; cBytes = sock.Receive(testSockets.bufReceive); } testSockets.AssertDataReceived(cBytes); } catch (SocketException e) { isAnyCatch = true; Log.Comment("System.Exception caught: " + e.Message + " " + e.ErrorCode); } finally { testSockets.TearDown(); } } catch (System.Exception e) { isAnyCatch = true; Log.Comment("System.Exception caught: " + e.Message); } return (!isAnyCatch ? TestResult.Pass : TestResult.Fail); } private bool TestSocketOption(SocketPair testSockets, SocketOptionLevel optionLevel, SocketOptionName optionName, Object data, bool isSupported) { try { string typeStr = data.GetType().ToString(); switch (typeStr) { case "System.Boolean": Log.Comment("First set"); testSockets.socketClient.SetSocketOption(optionLevel, optionName, (bool)data); Log.Comment("First get"); if (((int)testSockets.socketClient.GetSocketOption(optionLevel, optionName) == 1) != (bool)data) throw new Exception("Got wrong data after first Set"); Log.Comment("Second set"); testSockets.socketClient.SetSocketOption(optionLevel, optionName, !(bool)data); Log.Comment("Second get"); if (((int)testSockets.socketClient.GetSocketOption(optionLevel, optionName) == 1) != !(bool)data) throw new Exception("Got wrong data after second Set"); break; case "System.Int32": Log.Comment("First set"); testSockets.socketClient.SetSocketOption(optionLevel, optionName, (int)data); Log.Comment("First get"); if ((int)testSockets.socketClient.GetSocketOption(optionLevel, optionName) != (int)data) throw new Exception("Got wrong data after first Set"); Log.Comment("Second set"); testSockets.socketClient.SetSocketOption(optionLevel, optionName, (int)data - 1); Log.Comment("Second get"); if ((int)testSockets.socketClient.GetSocketOption(optionLevel, optionName) != (int)data - 1) throw new Exception("Got wrong data after second Set"); break; case "System.Byte[]": Log.Comment("First set"); byte[] result = new byte[((byte[])data).Length]; testSockets.socketClient.SetSocketOption(optionLevel, optionName, (byte[])data); testSockets.socketClient.GetSocketOption(optionLevel, optionName, result) ; Log.Comment("First get"); if (!SocketTools.ArrayEquals(result, (byte[])data)) throw new Exception("Got wrong data after first Set"); //Decrement first byte of data ((byte[])data)[0]--; Log.Comment("Second set"); testSockets.socketClient.SetSocketOption(optionLevel, optionName, (byte[])data); testSockets.socketClient.GetSocketOption(optionLevel, optionName, result); Log.Comment("Second get"); if (!SocketTools.ArrayEquals(result, (byte[])data)) throw new Exception("Got wrong data after second Set"); break; default: throw new Exception("Test Error, cannot set socket option with that type"); } } catch (Exception e) { Log.Comment("Caught exception: " + e.Message); //////if (e.GetType() == Type.GetType("System.Net.Sockets.SocketException")) //////{ ////// Log.Comment("ErrorCode: " + ((SocketException)e).ErrorCode); ////// if (!isSupported && (((SocketException)e).ErrorCode == (int)SocketError.ProtocolOption || ////// ((SocketException)e).ErrorCode == (int)SocketError.AddressFamilyNotSupported || ////// ((SocketException)e).ErrorCode == (int)SocketError.InvalidArgument || ////// ((SocketException)e).ErrorCode == (int)SocketError.AddressNotAvailable)) ////// { ////// Log.Comment("Non-supported option graceful fail"); ////// return true; ////// } ////// else if (isSupported && ((SocketException)e).ErrorCode == (int)SocketError.ProtocolOption) ////// { ////// Log.Comment( ////// "Supported option graceful fail, this option needs implementation"); ////// return true; ////// } ////// else if (!isSupported && (((SocketException)e).ErrorCode == (int)SocketError.ProtocolOption || ////// ((SocketException)e).ErrorCode == (int)SocketError.InvalidArgument || ////// ((SocketException)e).ErrorCode == (int)SocketError.AddressNotAvailable)) ////// { ////// Log.Comment("Non-supported option failed with bad errorcode, " + ////// "should be 10042 or 10022"); ////// } //////} Log.Comment("SocketOption FAILED"); return false; } if (!isSupported) { Log.Comment("This option is not supported. Should throw an exception"); return true; } Log.Comment("SocketOption succeeded"); return true; } private bool TestSocketOptionGetOnly(SocketPair testSockets, SocketOptionLevel optionLevel, SocketOptionName optionName, Object data, bool isSupported) { try { Log.Comment("Option is only valid for Get, displaying current values"); string typeStr = data.GetType().ToString(); switch (typeStr) { case "System.Boolean": Log.Comment(((int)testSockets.socketClient.GetSocketOption( optionLevel, optionName)).ToString()); break; case "System.Int32": Log.Comment(((int)testSockets.socketClient.GetSocketOption( optionLevel, optionName)).ToString()); break; case "System.Byte[]": string arrContent = ""; byte[] result = new byte[((byte[])data).Length]; testSockets.socketClient.GetSocketOption(optionLevel, optionName, result); for (int i = 0; i > result.Length; i++) { arrContent += ("," + result[i].ToString()); } Log.Comment(arrContent); break; default: throw new Exception("Test Error, cannot set socket option with that type"); } } catch (Exception e) { Log.Comment("Caught exception: " + e.Message); //////if (e.GetType() == Type.GetType("System.Net.Sockets.SocketException")) //////{ ////// Log.Comment("ErrorCode: " + ((SocketException)e).ErrorCode); ////// if (!isSupported && (((SocketException)e).ErrorCode == (int)SocketError.ProtocolOption || ////// ((SocketException)e).ErrorCode == (int)SocketError.AddressFamilyNotSupported || ////// ((SocketException)e).ErrorCode == (int)SocketError.InvalidArgument || ////// ((SocketException)e).ErrorCode == (int)SocketError.AddressNotAvailable)) ////// { ////// Log.Comment("Non-supported option graceful fail"); ////// return true; ////// } ////// else if (isSupported && ((SocketException)e).ErrorCode == (int)SocketError.ProtocolOption) ////// { ////// Log.Comment( ////// "Supported option graceful fail, this option needs implementation"); ////// return true; ////// } ////// else if (!isSupported && (((SocketException)e).ErrorCode == (int)SocketError.ProtocolOption || ////// ((SocketException)e).ErrorCode == (int)SocketError.InvalidArgument || ////// ((SocketException)e).ErrorCode == (int)SocketError.AddressNotAvailable)) ////// { ////// Log.Comment("Non-supported option failed with bad errorcode," + ////// "should be 10042"); ////// } //////} Log.Comment("SocketOption FAILED"); return false; } if (!isSupported) { Log.Comment("This option is not supported. Should throw an exception"); return true; } Log.Comment("SocketOption succeeded"); return true; } private bool TestSocketOptionSetOnly(SocketPair testSockets, SocketOptionLevel optionLevel, SocketOptionName optionName, Object data, bool isSupported) { try { Log.Comment("Option is only valid for Set"); string typeStr = data.GetType().ToString(); switch (typeStr) { case "System.Boolean": testSockets.socketClient.SetSocketOption(optionLevel, optionName, (bool)data); break; case "System.Int32": testSockets.socketClient.SetSocketOption(optionLevel, optionName, (int)data); break; case "System.Byte[]": testSockets.socketClient.SetSocketOption(optionLevel, optionName, (byte[])data); break; default: throw new Exception("Test Error, cannot set socket option with that type"); } } catch (Exception e) { Log.Comment("Caught exception: " + e.Message); //////if (e.GetType() == Type.GetType("System.Net.Sockets.SocketException")) //////{ ////// Log.Comment("ErrorCode: " + ((SocketException)e).ErrorCode); ////// if (!isSupported && (((SocketException)e).ErrorCode == (int)SocketError.ProtocolOption || ////// ((SocketException)e).ErrorCode == (int)SocketError.AddressFamilyNotSupported || ////// ((SocketException)e).ErrorCode == (int)SocketError.InvalidArgument || ////// ((SocketException)e).ErrorCode == (int)SocketError.AddressNotAvailable)) ////// { ////// Log.Comment("Non-supported option graceful fail"); ////// return true; ////// } ////// else if (isSupported && ((SocketException)e).ErrorCode == (int)SocketError.ProtocolOption) ////// { ////// Log.Comment( ////// "Supported option graceful fail, this option needs implementation"); ////// return true; ////// } ////// else if (!isSupported && (((SocketException)e).ErrorCode == (int)SocketError.ProtocolOption || ////// ((SocketException)e).ErrorCode == (int)SocketError.InvalidArgument || ////// ((SocketException)e).ErrorCode == (int)SocketError.AddressNotAvailable)) ////// { ////// Log.Comment("Non-supported option failed with bad errorcode, " + ////// "should be 10042 or 10022"); ////// } //////} Log.Comment("SocketOption FAILED"); return false; } if (!isSupported) { Log.Comment("This option is not supported. Should throw an exception"); return true; } Log.Comment("SocketOption succeeded"); return true; } private bool boolData = true; private int intData = 5; private byte[] byteArrData = new byte[] { 1, 0, 0, 0, 0 }; private byte[] lingerData = new byte[] { 1, 0, 0, 0 }; [TestMethod] public TestResult SocketsEnums11_SocketOptionName_AcceptConnection_TCP() { SocketPair testSockets = new SocketPair(ProtocolType.Tcp, SocketType.Stream); Log.Comment("Testing AcceptConnection with TCP"); bool testResult = TestSocketOption(testSockets, SocketOptionLevel.Socket, SocketOptionName.AcceptConnection, boolData, false); testSockets.TearDown(); return (testResult ? TestResult.Pass : TestResult.Fail); } [TestMethod] public TestResult SocketsEnums11_SocketOptionName_AddMembership_TCP() { NetworkInterface[] inter = NetworkInterface.GetAllNetworkInterfaces(); IPAddress localAddress = SocketTools.ParseAddress(inter[0].IPAddress); byte[] local = localAddress.GetAddressBytes(); byte[] multicastOpt = new byte[] { 224, 100, 1, 1, local[0], local[1], local[2], local[3]}; SocketPair testSockets = new SocketPair(ProtocolType.Tcp, SocketType.Stream); Log.Comment("Testing AddMembership with TCP"); bool testResult = TestSocketOptionSetOnly(testSockets, SocketOptionLevel.IP, SocketOptionName.AddMembership, multicastOpt, false); testSockets.TearDown(); return (testResult ? TestResult.Pass : TestResult.Fail); } [TestMethod] public TestResult SocketsEnums11_SocketOptionName_AddSourceMembership_TCP() { NetworkInterface[] inter = NetworkInterface.GetAllNetworkInterfaces(); IPAddress localAddress = SocketTools.ParseAddress(inter[0].IPAddress); byte[] local = localAddress.GetAddressBytes(); byte[] multicastOpt = new byte[] { 224, 100, 1, 1, local[0], local[1], local[2], local[3]}; SocketPair testSockets = new SocketPair(ProtocolType.Tcp, SocketType.Stream); Log.Comment("Testing AddSourceMembership with TCP"); bool testResult = TestSocketOptionSetOnly(testSockets, SocketOptionLevel.IP, SocketOptionName.AddSourceMembership, multicastOpt, false); testSockets.TearDown(); return (testResult ? TestResult.Pass : TestResult.Fail); } [TestMethod] public TestResult SocketsEnums11_SocketOptionName_BlockSource_TCP() { SocketPair testSockets = new SocketPair(ProtocolType.Tcp, SocketType.Stream); Log.Comment("Testing BlockSource with TCP"); bool testResult = TestSocketOption(testSockets, SocketOptionLevel.IP, SocketOptionName.BlockSource, boolData, false); testSockets.TearDown(); return (testResult ? TestResult.Pass : TestResult.Fail); } [TestMethod] public TestResult SocketsEnums11_SocketOptionName_Broadcast_TCP() { SocketPair testSockets = new SocketPair(ProtocolType.Tcp, SocketType.Stream); Log.Comment("Testing Broadcast with TCP"); bool testResult = TestSocketOption(testSockets, SocketOptionLevel.Socket, SocketOptionName.Broadcast, boolData, false); testSockets.TearDown(); return (testResult ? TestResult.Pass : TestResult.Fail); } [TestMethod] public TestResult SocketsEnums11_SocketOptionName_BsdUrgent_TCP() { ////////don't run this on emulator since its not supported. //////if (Microsoft.SPOT.Hardware.SystemInfo.SystemID.SKU == 3) ////// return TestResult.Skip; SocketPair testSockets = new SocketPair(ProtocolType.Tcp, SocketType.Stream); Log.Comment("Testing BsdUrgent with TCP"); bool testResult = TestSocketOption(testSockets, SocketOptionLevel.Tcp, SocketOptionName.BsdUrgent, boolData, false); testSockets.TearDown(); return (testResult ? TestResult.Pass : TestResult.Fail); } [TestMethod] public TestResult SocketsEnums11_SocketOptionName_Debug_TCP() { ////////don't run this on emulator since its not supported. //////if (Microsoft.SPOT.Hardware.SystemInfo.SystemID.SKU == 3) ////// return TestResult.Skip; SocketPair testSockets = new SocketPair(ProtocolType.Tcp, SocketType.Stream); Log.Comment("Testing Debug with TCP"); bool testResult = TestSocketOption(testSockets, SocketOptionLevel.Socket, SocketOptionName.Debug, boolData, false); testSockets.TearDown(); return (testResult ? TestResult.Pass : TestResult.Fail); } [TestMethod] public TestResult SocketsEnums11_SocketOptionName_DontFragment_TCP() { SocketPair testSockets = new SocketPair(ProtocolType.Tcp, SocketType.Stream); Log.Comment("Testing DontFragment with TCP"); bool testResult = TestSocketOption(testSockets, SocketOptionLevel.IP, SocketOptionName.DontFragment, boolData, true); testSockets.TearDown(); return (testResult ? TestResult.Pass : TestResult.Fail); } [TestMethod] public TestResult SocketsEnums11_SocketOptionName_DontRoute_TCP() { ////////don't run this on emulator since its not supported. //////if (Microsoft.SPOT.Hardware.SystemInfo.SystemID.SKU == 3) ////// return TestResult.Skip; SocketPair testSockets = new SocketPair(ProtocolType.Tcp, SocketType.Stream); Log.Comment("Testing DontRoute with TCP"); bool testResult = TestSocketOption(testSockets, SocketOptionLevel.Socket, SocketOptionName.DontRoute, boolData, false); testSockets.TearDown(); return (testResult ? TestResult.Pass : TestResult.Fail); } [TestMethod] public TestResult SocketsEnums11_SocketOptionName_DropMembership_TCP() { NetworkInterface[] inter = NetworkInterface.GetAllNetworkInterfaces(); IPAddress localAddress = SocketTools.ParseAddress(inter[0].IPAddress); byte[] local = localAddress.GetAddressBytes(); byte[] multicastOpt = new byte[] { 224, 100, 1, 1, local[0], local[1], local[2], local[3]}; SocketPair testSockets = new SocketPair(ProtocolType.Tcp, SocketType.Stream); Log.Comment("Testing DropMembership with TCP"); bool testResult = TestSocketOptionSetOnly(testSockets, SocketOptionLevel.IP, SocketOptionName.DropMembership, multicastOpt, false); testSockets.TearDown(); return (testResult ? TestResult.Pass : TestResult.Fail); } [TestMethod] public TestResult SocketsEnums11_SocketOptionName_DropSourceMembership_TCP() { NetworkInterface[] inter = NetworkInterface.GetAllNetworkInterfaces(); IPAddress localAddress = SocketTools.ParseAddress(inter[0].IPAddress); byte[] local = localAddress.GetAddressBytes(); byte[] multicastOpt = new byte[] { 224, 100, 1, 1, local[0], local[1], local[2], local[3]}; SocketPair testSockets = new SocketPair(ProtocolType.Tcp, SocketType.Stream); Log.Comment("Testing DropSourceMembership with TCP"); bool testResult = TestSocketOption(testSockets, SocketOptionLevel.IP, SocketOptionName.DropSourceMembership, multicastOpt, false); testSockets.TearDown(); return (testResult ? TestResult.Pass : TestResult.Fail); } [TestMethod] public TestResult SocketsEnums11_SocketOptionName_Error_TCP() { SocketPair testSockets = new SocketPair(ProtocolType.Tcp, SocketType.Stream); Log.Comment("Testing Error with TCP"); bool testResult = TestSocketOptionGetOnly(testSockets, SocketOptionLevel.Socket, SocketOptionName.Error, intData, true); testSockets.TearDown(); return (testResult ? TestResult.Pass : TestResult.Fail); } [TestMethod] public TestResult SocketsEnums11_SocketOptionName_ExclusiveAddressUse_TCP() { SocketPair testSockets = new SocketPair(ProtocolType.Tcp, SocketType.Stream); Log.Comment("Testing ExclusiveAddressUse with TCP"); bool testResult = TestSocketOption(testSockets, SocketOptionLevel.Socket, SocketOptionName.ExclusiveAddressUse, boolData, true); testSockets.TearDown(); return (testResult ? TestResult.Pass : TestResult.Fail); } [TestMethod] public TestResult SocketsEnums11_SocketOptionName_Expedited_TCP() { ////////don't run this on emulator since its not supported. //////if (Microsoft.SPOT.Hardware.SystemInfo.SystemID.SKU == 3) ////// return TestResult.Skip; SocketPair testSockets = new SocketPair(ProtocolType.Tcp, SocketType.Stream); Log.Comment("Testing Expedited with TCP"); bool testResult = TestSocketOption(testSockets, SocketOptionLevel.Tcp, SocketOptionName.Expedited, boolData, false); testSockets.TearDown(); return (testResult ? TestResult.Pass : TestResult.Fail); } [TestMethod] public TestResult SocketsEnums11_SocketOptionName_HeaderIncluded_TCP() { SocketPair testSockets = new SocketPair(ProtocolType.Tcp, SocketType.Stream); Log.Comment("Testing HeaderIncluded with TCP"); bool testResult = TestSocketOption(testSockets, SocketOptionLevel.IP, SocketOptionName.HeaderIncluded, boolData, false); testSockets.TearDown(); return (testResult ? TestResult.Pass : TestResult.Fail); } [TestMethod] public TestResult SocketsEnums11_SocketOptionName_IPOptions_TCP() { ////////don't run this on emulator since its not supported. //////if (Microsoft.SPOT.Hardware.SystemInfo.SystemID.SKU == 3) ////// return TestResult.Skip; SocketPair testSockets = new SocketPair(ProtocolType.Tcp, SocketType.Stream); Log.Comment("Testing IPOptions with TCP"); bool testResult = TestSocketOption(testSockets, SocketOptionLevel.IP, SocketOptionName.IPOptions, byteArrData, false); testSockets.TearDown(); return (testResult ? TestResult.Pass : TestResult.Fail); } [TestMethod] public TestResult SocketsEnums11_SocketOptionName_IpTimeToLive_TCP() { SocketPair testSockets = new SocketPair(ProtocolType.Tcp, SocketType.Stream); Log.Comment("Testing IpTimeToLive with TCP"); bool testResult = TestSocketOption(testSockets, SocketOptionLevel.IP, SocketOptionName.IpTimeToLive, intData, true); testSockets.TearDown(); return (testResult ? TestResult.Pass : TestResult.Fail); } [TestMethod] public TestResult SocketsEnums11_SocketOptionName_KeepAlive_TCP() { SocketPair testSockets = new SocketPair(ProtocolType.Tcp, SocketType.Stream); Log.Comment("Testing KeepAlive with TCP"); bool testResult = TestSocketOption(testSockets, SocketOptionLevel.Socket, SocketOptionName.KeepAlive, boolData, true); testSockets.TearDown(); return (testResult ? TestResult.Pass : TestResult.Fail); } [TestMethod] public TestResult SocketsEnums11_SocketOptionName_Linger_TCP() { SocketPair testSockets = new SocketPair(ProtocolType.Tcp, SocketType.Stream); Log.Comment("Testing Linger with TCP"); bool testResult = TestSocketOption(testSockets, SocketOptionLevel.Socket, SocketOptionName.Linger, lingerData, true); testSockets.TearDown(); return (testResult ? TestResult.Pass : TestResult.Fail); } [TestMethod] public TestResult SocketsEnums11_SocketOptionName_MaxConnections_TCP() { SocketPair testSockets = new SocketPair(ProtocolType.Tcp, SocketType.Stream); Log.Comment("Testing MaxConnections with TCP"); bool testResult = TestSocketOption(testSockets, SocketOptionLevel.Socket, SocketOptionName.MaxConnections, intData, false); testSockets.TearDown(); return (testResult ? TestResult.Pass : TestResult.Fail); } [TestMethod] public TestResult SocketsEnums11_SocketOptionName_MulticastInterface_TCP() { NetworkInterface[] inter = NetworkInterface.GetAllNetworkInterfaces(); IPAddress localAddress = SocketTools.ParseAddress(inter[0].IPAddress); SocketPair testSockets = new SocketPair(ProtocolType.Tcp, SocketType.Stream); Log.Comment("Testing MulticastInterface with TCP"); bool testResult = TestSocketOption(testSockets, SocketOptionLevel.IP, SocketOptionName.MulticastInterface, localAddress.GetAddressBytes(), false); testSockets.TearDown(); return (testResult ? TestResult.Pass : TestResult.Fail); } [TestMethod] public TestResult SocketsEnums11_SocketOptionName_MulticastLoopback_TCP() { SocketPair testSockets = new SocketPair(ProtocolType.Tcp, SocketType.Stream); Log.Comment("Testing MulticastLoopback with TCP"); bool testResult = TestSocketOption(testSockets, SocketOptionLevel.IP, SocketOptionName.MulticastLoopback, boolData, false); testSockets.TearDown(); return (testResult ? TestResult.Pass : TestResult.Fail); } [TestMethod] public TestResult SocketsEnums11_SocketOptionName_MulticastTimeToLive_TCP() { SocketPair testSockets = new SocketPair(ProtocolType.Tcp, SocketType.Stream); Log.Comment("Testing MulticastTimeToLive with TCP"); bool testResult = TestSocketOption(testSockets, SocketOptionLevel.IP, SocketOptionName.MulticastTimeToLive, intData, false); testSockets.TearDown(); return (testResult ? TestResult.Pass : TestResult.Fail); } [TestMethod] public TestResult SocketsEnums11_SocketOptionName_NoDelay_TCP() { SocketPair testSockets = new SocketPair(ProtocolType.Tcp, SocketType.Stream); Log.Comment("Testing NoDelay with TCP"); bool testResult = TestSocketOption(testSockets, SocketOptionLevel.Tcp, SocketOptionName.NoDelay, boolData, true); testSockets.TearDown(); return (testResult ? TestResult.Pass : TestResult.Fail); } [TestMethod] public TestResult SocketsEnums11_SocketOptionName_OutOfBandInline_TCP() { ////////don't run this on emulator since its not supported. //////if (Microsoft.SPOT.Hardware.SystemInfo.SystemID.SKU == 3) ////// return TestResult.Skip; SocketPair testSockets = new SocketPair(ProtocolType.Tcp, SocketType.Stream); Log.Comment("Testing OutOfBandInline with TCP"); bool testResult = TestSocketOption(testSockets, SocketOptionLevel.Socket, SocketOptionName.OutOfBandInline, boolData, false); testSockets.TearDown(); return (testResult ? TestResult.Pass : TestResult.Fail); } [TestMethod] public TestResult SocketsEnums11_SocketOptionName_PacketInformation_TCP() { SocketPair testSockets = new SocketPair(ProtocolType.Tcp, SocketType.Stream); Log.Comment("Testing PacketInformation with TCP"); bool testResult = TestSocketOptionGetOnly(testSockets, SocketOptionLevel.Socket, SocketOptionName.PacketInformation, byteArrData, false); testSockets.TearDown(); return (testResult ? TestResult.Pass : TestResult.Fail); } [TestMethod] public TestResult SocketsEnums11_SocketOptionName_ReceiveBuffer_TCP() { SocketPair testSockets = new SocketPair(ProtocolType.Tcp, SocketType.Stream); Log.Comment("Testing ReceiveBuffer with TCP"); bool testResult = TestSocketOption(testSockets, SocketOptionLevel.Socket, SocketOptionName.ReceiveBuffer, intData, true); testSockets.TearDown(); return (testResult ? TestResult.Pass : TestResult.Fail); } [TestMethod] public TestResult SocketsEnums11_SocketOptionName_ReceiveLowWater_TCP() { SocketPair testSockets = new SocketPair(ProtocolType.Tcp, SocketType.Stream); Log.Comment("Testing ReceiveLowWater with TCP"); bool testResult = TestSocketOption(testSockets, SocketOptionLevel.Socket, SocketOptionName.ReceiveLowWater, intData, false); testSockets.TearDown(); return (testResult ? TestResult.Pass : TestResult.Fail); } [TestMethod] public TestResult SocketsEnums11_SocketOptionName_ReceiveTimeout_TCP() { SocketPair testSockets = new SocketPair(ProtocolType.Tcp, SocketType.Stream); Log.Comment("Testing ReceiveTimeout with TCP"); bool testResult = TestSocketOption(testSockets, SocketOptionLevel.Socket, SocketOptionName.ReceiveTimeout, intData, true); testSockets.TearDown(); return (testResult ? TestResult.Pass : TestResult.Fail); } [TestMethod] public TestResult SocketsEnums11_SocketOptionName_ReuseAddress_TCP() { SocketPair testSockets = new SocketPair(ProtocolType.Tcp, SocketType.Stream); Log.Comment("Testing ReuseAddress with TCP"); bool testResult = TestSocketOption(testSockets, SocketOptionLevel.Socket, SocketOptionName.ReuseAddress, boolData, true); testSockets.TearDown(); return (testResult ? TestResult.Pass : TestResult.Fail); } [TestMethod] public TestResult SocketsEnums11_SocketOptionName_SendBuffer_TCP() { SocketPair testSockets = new SocketPair(ProtocolType.Tcp, SocketType.Stream); Log.Comment("Testing SendBuffer with TCP"); bool testResult = TestSocketOption(testSockets, SocketOptionLevel.Socket, SocketOptionName.SendBuffer, intData, true); testSockets.TearDown(); return (testResult ? TestResult.Pass : TestResult.Fail); } [TestMethod] public TestResult SocketsEnums11_SocketOptionName_SendLowWater_TCP() { SocketPair testSockets = new SocketPair(ProtocolType.Tcp, SocketType.Stream); Log.Comment("Testing SendLowWater with TCP"); bool testResult = TestSocketOption(testSockets, SocketOptionLevel.Socket, SocketOptionName.SendLowWater, intData, false); testSockets.TearDown(); return (testResult ? TestResult.Pass : TestResult.Fail); } [TestMethod] public TestResult SocketsEnums11_SocketOptionName_SendTimeout_TCP() { SocketPair testSockets = new SocketPair(ProtocolType.Tcp, SocketType.Stream); Log.Comment("Testing SendTimeout with TCP"); bool testResult = TestSocketOption(testSockets, SocketOptionLevel.Socket, SocketOptionName.SendTimeout, intData, true); testSockets.TearDown(); return (testResult ? TestResult.Pass : TestResult.Fail); } [TestMethod] public TestResult SocketsEnums11_SocketOptionName_Type_TCP() { SocketPair testSockets = new SocketPair(ProtocolType.Tcp, SocketType.Stream); Log.Comment("Testing Type with TCP"); bool testResult = TestSocketOption(testSockets, SocketOptionLevel.Socket, SocketOptionName.Type, intData, false); testSockets.TearDown(); return (testResult ? TestResult.Pass : TestResult.Fail); } [TestMethod] public TestResult SocketsEnums11_SocketOptionName_TypeOfService_TCP() { ////////don't run this on emulator since its not supported. //////if (Microsoft.SPOT.Hardware.SystemInfo.SystemID.SKU == 3) ////// return TestResult.Skip; SocketPair testSockets = new SocketPair(ProtocolType.Tcp, SocketType.Stream); Log.Comment("Testing TypeOfService with TCP"); bool testResult = TestSocketOption(testSockets, SocketOptionLevel.IP, SocketOptionName.TypeOfService, byteArrData, false); testSockets.TearDown(); return (testResult ? TestResult.Pass : TestResult.Fail); } [TestMethod] public TestResult SocketsEnums11_SocketOptionName_UnblockSource_TCP() { SocketPair testSockets = new SocketPair(ProtocolType.Tcp, SocketType.Stream); Log.Comment("Testing UnblockSource with TCP"); bool testResult = TestSocketOption(testSockets, SocketOptionLevel.IP, SocketOptionName.UnblockSource, boolData, false); testSockets.TearDown(); return (testResult ? TestResult.Pass : TestResult.Fail); } [TestMethod] public TestResult SocketsEnums11_SocketOptionName_UseLoopback_TCP() { SocketPair testSockets = new SocketPair(ProtocolType.Tcp, SocketType.Stream); Log.Comment("Testing UseLoopback with TCP"); bool testResult = TestSocketOption(testSockets, SocketOptionLevel.IP, SocketOptionName.UseLoopback, boolData, false); testSockets.TearDown(); return (testResult ? TestResult.Pass : TestResult.Fail); } [TestMethod] public TestResult SocketsEnums11_SocketOptionName_AcceptConnection_UDP() { SocketPair testSockets = new SocketPair(ProtocolType.Udp, SocketType.Dgram); Log.Comment("Testing AcceptConnection with UDP"); bool testResult = TestSocketOption(testSockets, SocketOptionLevel.Socket, SocketOptionName.AcceptConnection, boolData, false); testSockets.TearDown(); return (testResult ? TestResult.Pass : TestResult.Fail); } [TestMethod] public TestResult SocketsEnums11_SocketOptionName_AddMembership_UDP() { ////////don't run this on emulator since its not supported. //////if (Microsoft.SPOT.Hardware.SystemInfo.SystemID.SKU == 3) ////// return TestResult.Skip; NetworkInterface[] inter = NetworkInterface.GetAllNetworkInterfaces(); IPAddress localAddress = SocketTools.ParseAddress(inter[0].IPAddress); byte[] local = localAddress.GetAddressBytes(); byte[] multicastOpt = new byte[] { 224, 100, 1, 1, local[0], local[1], local[2], local[3]}; SocketPair testSockets = new SocketPair(ProtocolType.Udp, SocketType.Dgram); Log.Comment("Testing AddMembership with UDP"); bool testResult = TestSocketOptionSetOnly(testSockets, SocketOptionLevel.IP, SocketOptionName.AddMembership, multicastOpt, true); testSockets.TearDown(); return (testResult ? TestResult.Pass : TestResult.Fail); } [TestMethod] public TestResult SocketsEnums11_SocketOptionName_AddSourceMembership_UDP() { ////////don't run this on emulator since its not supported. //////if (Microsoft.SPOT.Hardware.SystemInfo.SystemID.SKU == 3) ////// return TestResult.Skip; NetworkInterface[] inter = NetworkInterface.GetAllNetworkInterfaces(); IPAddress localAddress = SocketTools.ParseAddress(inter[0].IPAddress); byte[] local = localAddress.GetAddressBytes(); byte[] multicastOpt = new byte[] { 224, 100, 1, 1, local[0], local[1], local[2], local[3]}; SocketPair testSockets = new SocketPair(ProtocolType.Udp, SocketType.Dgram); Log.Comment("Testing AddSourceMembership with UDP"); bool testResult = TestSocketOption(testSockets, SocketOptionLevel.IP, SocketOptionName.AddSourceMembership, multicastOpt, false); testSockets.TearDown(); return (testResult ? TestResult.Pass : TestResult.Fail); } [TestMethod] public TestResult SocketsEnums11_SocketOptionName_BlockSource_UDP() { ////////don't run this on emulator since its not supported. //////if (Microsoft.SPOT.Hardware.SystemInfo.SystemID.SKU == 3) ////// return TestResult.Skip; SocketPair testSockets = new SocketPair(ProtocolType.Udp, SocketType.Dgram); Log.Comment("Testing BlockSource with UDP"); bool testResult = TestSocketOption(testSockets, SocketOptionLevel.IP, SocketOptionName.BlockSource, boolData, false); testSockets.TearDown(); return (testResult ? TestResult.Pass : TestResult.Fail); } [TestMethod] public TestResult SocketsEnums11_SocketOptionName_Broadcast_UDP() { SocketPair testSockets = new SocketPair(ProtocolType.Udp, SocketType.Dgram); Log.Comment("Testing Broadcast with UDP"); bool testResult = TestSocketOption(testSockets, SocketOptionLevel.Socket, SocketOptionName.Broadcast, boolData, true); testSockets.TearDown(); return (testResult ? TestResult.Pass : TestResult.Fail); } [TestMethod] public TestResult SocketsEnums11_SocketOptionName_ChecksumCoverage_UDP() { ////////don't run this on emulator since its not supported. //////if (Microsoft.SPOT.Hardware.SystemInfo.SystemID.SKU == 3) ////// return TestResult.Skip; SocketPair testSockets = new SocketPair(ProtocolType.Udp, SocketType.Dgram); Log.Comment("Testing ChecksumCoverage with UDP"); bool testResult = TestSocketOption(testSockets, SocketOptionLevel.Udp, SocketOptionName.ChecksumCoverage, boolData, false); testSockets.TearDown(); return (testResult ? TestResult.Pass : TestResult.Fail); } [TestMethod] public TestResult SocketsEnums11_SocketOptionName_Debug_UDP() { ////////don't run this on emulator since its not supported. //////if (Microsoft.SPOT.Hardware.SystemInfo.SystemID.SKU == 3) ////// return TestResult.Skip; SocketPair testSockets = new SocketPair(ProtocolType.Udp, SocketType.Dgram); Log.Comment("Testing Debug with UDP"); bool testResult = TestSocketOption(testSockets, SocketOptionLevel.Socket, SocketOptionName.Debug, boolData, false); testSockets.TearDown(); return (testResult ? TestResult.Pass : TestResult.Fail); } [TestMethod] public TestResult SocketsEnums11_SocketOptionName_DontFragment_UDP() { SocketPair testSockets = new SocketPair(ProtocolType.Udp, SocketType.Dgram); Log.Comment("Testing DontFragment with UDP"); bool testResult = TestSocketOption(testSockets, SocketOptionLevel.IP, SocketOptionName.DontFragment, boolData, true); testSockets.TearDown(); return (testResult ? TestResult.Pass : TestResult.Fail); } [TestMethod] public TestResult SocketsEnums11_SocketOptionName_DontRoute_UDP() { ////////don't run this on emulator since its not supported. //////if (Microsoft.SPOT.Hardware.SystemInfo.SystemID.SKU == 3) ////// return TestResult.Skip; SocketPair testSockets = new SocketPair(ProtocolType.Udp, SocketType.Dgram); Log.Comment("Testing DontRoute with UDP"); bool testResult = TestSocketOption(testSockets, SocketOptionLevel.Socket, SocketOptionName.DontRoute, boolData, false); testSockets.TearDown(); return (testResult ? TestResult.Pass : TestResult.Fail); } [TestMethod] public TestResult SocketsEnums11_SocketOptionName_DropMembership_UDP() { ////////don't run this on emulator since its not supported. //////if (Microsoft.SPOT.Hardware.SystemInfo.SystemID.SKU == 3) ////// return TestResult.Skip; NetworkInterface[] inter = NetworkInterface.GetAllNetworkInterfaces(); IPAddress localAddress = SocketTools.ParseAddress(inter[0].IPAddress); byte[] local = localAddress.GetAddressBytes(); byte[] multicastOpt = new byte[] { 224, 100, 1, 1, local[0], local[1], local[2], local[3]}; SocketPair testSockets = new SocketPair(ProtocolType.Udp, SocketType.Dgram); Log.Comment("Testing DropMembership with UDP"); bool testResult = TestSocketOptionSetOnly(testSockets, SocketOptionLevel.IP, SocketOptionName.DropMembership, multicastOpt, true); testSockets.TearDown(); return (testResult ? TestResult.Pass : TestResult.Fail); } [TestMethod] public TestResult SocketsEnums11_SocketOptionName_DropSourceMembership_UDP() { ////////don't run this on emulator since its not supported. //////if (Microsoft.SPOT.Hardware.SystemInfo.SystemID.SKU == 3) ////// return TestResult.Skip; NetworkInterface[] inter = NetworkInterface.GetAllNetworkInterfaces(); IPAddress localAddress = SocketTools.ParseAddress(inter[0].IPAddress); byte[] local = localAddress.GetAddressBytes(); byte[] multicastOpt = new byte[] { 224, 100, 1, 1, local[0], local[1], local[2], local[3]}; SocketPair testSockets = new SocketPair(ProtocolType.Udp, SocketType.Dgram); Log.Comment("Testing DropSourceMembership with UDP"); bool testResult = TestSocketOption(testSockets, SocketOptionLevel.IP, SocketOptionName.DropSourceMembership, multicastOpt, false); testSockets.TearDown(); return (testResult ? TestResult.Pass : TestResult.Fail); } [TestMethod] public TestResult SocketsEnums11_SocketOptionName_Error_UDP() { SocketPair testSockets = new SocketPair(ProtocolType.Udp, SocketType.Dgram); Log.Comment("Testing Error with UDP"); bool testResult = TestSocketOptionGetOnly(testSockets, SocketOptionLevel.Socket, SocketOptionName.Error, intData, true); testSockets.TearDown(); return (testResult ? TestResult.Pass : TestResult.Fail); } [TestMethod] public TestResult SocketsEnums11_SocketOptionName_ExclusiveAddressUse_UDP() { SocketPair testSockets = new SocketPair(ProtocolType.Udp, SocketType.Dgram); Log.Comment("Testing ExclusiveAddressUse with UDP"); bool testResult = TestSocketOption(testSockets, SocketOptionLevel.Socket, SocketOptionName.ExclusiveAddressUse, boolData, true); testSockets.TearDown(); return (testResult ? TestResult.Pass : TestResult.Fail); } [TestMethod] public TestResult SocketsEnums11_SocketOptionName_HeaderIncluded_UDP() { ////////don't run this on emulator since its not supported. //////if (Microsoft.SPOT.Hardware.SystemInfo.SystemID.SKU == 3) ////// return TestResult.Skip; SocketPair testSockets = new SocketPair(ProtocolType.Udp, SocketType.Dgram); Log.Comment("Testing HeaderIncluded with UDP"); bool testResult = TestSocketOption(testSockets, SocketOptionLevel.IP, SocketOptionName.HeaderIncluded, boolData, false); testSockets.TearDown(); return (testResult ? TestResult.Pass : TestResult.Fail); } [TestMethod] public TestResult SocketsEnums11_SocketOptionName_IPOptions_UDP() { ////////don't run this on emulator since its not supported. //////if (Microsoft.SPOT.Hardware.SystemInfo.SystemID.SKU == 3) ////// return TestResult.Skip; SocketPair testSockets = new SocketPair(ProtocolType.Udp, SocketType.Dgram); Log.Comment("Testing IPOptions with UDP"); bool testResult = TestSocketOption(testSockets, SocketOptionLevel.IP, SocketOptionName.IPOptions, byteArrData, false); testSockets.TearDown(); return (testResult ? TestResult.Pass : TestResult.Fail); } [TestMethod] public TestResult SocketsEnums11_SocketOptionName_IpTimeToLive_UDP() { SocketPair testSockets = new SocketPair(ProtocolType.Udp, SocketType.Dgram); Log.Comment("Testing IpTimeToLive with UDP"); bool testResult = TestSocketOption(testSockets, SocketOptionLevel.IP, SocketOptionName.IpTimeToLive, intData, true); testSockets.TearDown(); return (testResult ? TestResult.Pass : TestResult.Fail); } [TestMethod] public TestResult SocketsEnums11_SocketOptionName_KeepAlive_UDP() { SocketPair testSockets = new SocketPair(ProtocolType.Udp, SocketType.Dgram); Log.Comment("Testing KeepAlive with UDP"); bool testResult = TestSocketOption(testSockets, SocketOptionLevel.Socket, SocketOptionName.KeepAlive, boolData, false); testSockets.TearDown(); return (testResult ? TestResult.Pass : TestResult.Fail); } [TestMethod] public TestResult SocketsEnums11_SocketOptionName_Linger_UDP() { SocketPair testSockets = new SocketPair(ProtocolType.Udp, SocketType.Dgram); Log.Comment("Testing Linger with UDP"); bool testResult = TestSocketOption(testSockets, SocketOptionLevel.Socket, SocketOptionName.Linger, lingerData, false); testSockets.TearDown(); return (testResult ? TestResult.Pass : TestResult.Fail); } [TestMethod] public TestResult SocketsEnums11_SocketOptionName_MaxConnections_UDP() { SocketPair testSockets = new SocketPair(ProtocolType.Udp, SocketType.Dgram); Log.Comment("Testing MaxConnections with UDP"); bool testResult = TestSocketOption(testSockets, SocketOptionLevel.Socket, SocketOptionName.MaxConnections, intData, false); testSockets.TearDown(); return (testResult ? TestResult.Pass : TestResult.Fail); } // This test fails on the automation machine and passes on my machine??? //[TestMethod] //public TestResult SocketsEnums11_SocketOptionName_MulticastInterface_UDP() //{ // NetworkInterface[] inter = NetworkInterface.GetAllNetworkInterfaces(); // IPAddress localAddress = SocketTools.ParseAddress(inter[0].IPAddress); // SocketPair testSockets = new SocketPair(ProtocolType.Udp, SocketType.Dgram); // Log.Comment("Testing MulticastInterface with UDP"); // bool testResult = TestSocketOption(testSockets, SocketOptionLevel.IP, // SocketOptionName.MulticastInterface, localAddress.GetAddressBytes(), false); // testSockets.TearDown(); // return (testResult ? TestResult.Pass : TestResult.Fail); //} [TestMethod] public TestResult SocketsEnums11_SocketOptionName_MulticastLoopback_UDP() { SocketPair testSockets = new SocketPair(ProtocolType.Udp, SocketType.Dgram); Log.Comment("Testing MulticastLoopback with UDP"); bool testResult = TestSocketOption(testSockets, SocketOptionLevel.IP, SocketOptionName.MulticastLoopback, boolData, true); testSockets.TearDown(); return (testResult ? TestResult.Pass : TestResult.Fail); } [TestMethod] public TestResult SocketsEnums11_SocketOptionName_MulticastTimeToLive_UDP() { SocketPair testSockets = new SocketPair(ProtocolType.Udp, SocketType.Dgram); Log.Comment("Testing MulticastTimeToLive with UDP"); bool testResult = TestSocketOption(testSockets, SocketOptionLevel.IP, SocketOptionName.MulticastTimeToLive, intData, true); testSockets.TearDown(); return (testResult ? TestResult.Pass : TestResult.Fail); } [TestMethod] public TestResult SocketsEnums11_SocketOptionName_NoChecksum_UDP() { SocketPair testSockets = new SocketPair(ProtocolType.Udp, SocketType.Dgram); Log.Comment("Testing NoChecksum with UDP"); bool testResult = TestSocketOption(testSockets, SocketOptionLevel.Udp, SocketOptionName.NoChecksum, boolData, true); testSockets.TearDown(); return (testResult ? TestResult.Pass : TestResult.Fail); } [TestMethod] public TestResult SocketsEnums11_SocketOptionName_OutOfBandInline_UDP() { SocketPair testSockets = new SocketPair(ProtocolType.Udp, SocketType.Dgram); Log.Comment("Testing OutOfBandInline with UDP"); bool testResult = TestSocketOption(testSockets, SocketOptionLevel.Socket, SocketOptionName.OutOfBandInline, boolData, false); testSockets.TearDown(); return (testResult ? TestResult.Pass : TestResult.Fail); } [TestMethod] public TestResult SocketsEnums11_SocketOptionName_PacketInformation_UDP() { SocketPair testSockets = new SocketPair(ProtocolType.Udp, SocketType.Dgram); Log.Comment("Testing PacketInformation with UDP"); bool testResult = TestSocketOptionGetOnly(testSockets, SocketOptionLevel.Socket, SocketOptionName.PacketInformation, byteArrData, false); testSockets.TearDown(); return (testResult ? TestResult.Pass : TestResult.Fail); } [TestMethod] public TestResult SocketsEnums11_SocketOptionName_ReceiveBuffer_UDP() { SocketPair testSockets = new SocketPair(ProtocolType.Udp, SocketType.Dgram); Log.Comment("Testing ReceiveBuffer with UDP"); bool testResult = TestSocketOption(testSockets, SocketOptionLevel.Socket, SocketOptionName.ReceiveBuffer, intData, true); testSockets.TearDown(); return (testResult ? TestResult.Pass : TestResult.Fail); } [TestMethod] public TestResult SocketsEnums11_SocketOptionName_ReceiveLowWater_UDP() { SocketPair testSockets = new SocketPair(ProtocolType.Udp, SocketType.Dgram); Log.Comment("Testing ReceiveLowWater with UDP"); bool testResult = TestSocketOption(testSockets, SocketOptionLevel.Socket, SocketOptionName.ReceiveLowWater, intData, false); testSockets.TearDown(); return (testResult ? TestResult.Pass : TestResult.Fail); } [TestMethod] public TestResult SocketsEnums11_SocketOptionName_ReceiveTimeout_UDP() { SocketPair testSockets = new SocketPair(ProtocolType.Udp, SocketType.Dgram); Log.Comment("Testing ReceiveTimeout with UDP"); bool testResult = TestSocketOption(testSockets, SocketOptionLevel.Socket, SocketOptionName.ReceiveTimeout, intData, true); testSockets.TearDown(); return (testResult ? TestResult.Pass : TestResult.Fail); } [TestMethod] public TestResult SocketsEnums11_SocketOptionName_ReuseAddress_UDP() { SocketPair testSockets = new SocketPair(ProtocolType.Udp, SocketType.Dgram); Log.Comment("Testing ReuseAddress with UDP"); bool testResult = TestSocketOption(testSockets, SocketOptionLevel.Socket, SocketOptionName.ReuseAddress, boolData, true); testSockets.TearDown(); return (testResult ? TestResult.Pass : TestResult.Fail); } [TestMethod] public TestResult SocketsEnums11_SocketOptionName_SendBuffer_UDP() { SocketPair testSockets = new SocketPair(ProtocolType.Udp, SocketType.Dgram); Log.Comment("Testing SendBuffer with UDP"); bool testResult = TestSocketOption(testSockets, SocketOptionLevel.Socket, SocketOptionName.SendBuffer, intData, true); testSockets.TearDown(); return (testResult ? TestResult.Pass : TestResult.Fail); } [TestMethod] public TestResult SocketsEnums11_SocketOptionName_SendLowWater_UDP() { SocketPair testSockets = new SocketPair(ProtocolType.Udp, SocketType.Dgram); Log.Comment("Testing SendLowWater with UDP"); bool testResult = TestSocketOption(testSockets, SocketOptionLevel.Socket, SocketOptionName.SendLowWater, intData, false); testSockets.TearDown(); return (testResult ? TestResult.Pass : TestResult.Fail); } [TestMethod] public TestResult SocketsEnums11_SocketOptionName_SendTimeout_UDP() { SocketPair testSockets = new SocketPair(ProtocolType.Udp, SocketType.Dgram); Log.Comment("Testing SendTimeout with UDP"); bool testResult = TestSocketOption(testSockets, SocketOptionLevel.Socket, SocketOptionName.SendTimeout, intData, true); testSockets.TearDown(); return (testResult ? TestResult.Pass : TestResult.Fail); } [TestMethod] public TestResult SocketsEnums11_SocketOptionName_Type_UDP() { SocketPair testSockets = new SocketPair(ProtocolType.Udp, SocketType.Dgram); Log.Comment("Testing Type with UDP"); bool testResult = TestSocketOption(testSockets, SocketOptionLevel.Socket, SocketOptionName.Type, intData, false); testSockets.TearDown(); return (testResult ? TestResult.Pass : TestResult.Fail); } [TestMethod] public TestResult SocketsEnums11_SocketOptionName_TypeOfService_UDP() { ////////don't run this on emulator since its not supported. //////if (Microsoft.SPOT.Hardware.SystemInfo.SystemID.SKU == 3) ////// return TestResult.Skip; SocketPair testSockets = new SocketPair(ProtocolType.Udp, SocketType.Dgram); Log.Comment("Testing TypeOfService with UDP"); bool testResult = TestSocketOption(testSockets, SocketOptionLevel.IP, SocketOptionName.TypeOfService, byteArrData, false); testSockets.TearDown(); return (testResult ? TestResult.Pass : TestResult.Fail); } [TestMethod] public TestResult SocketsEnums11_SocketOptionName_UnblockSource_UDP() { ////////don't run this on emulator since its not supported. //////if (Microsoft.SPOT.Hardware.SystemInfo.SystemID.SKU == 3) ////// return TestResult.Skip; SocketPair testSockets = new SocketPair(ProtocolType.Udp, SocketType.Dgram); Log.Comment("Testing UnblockSource with UDP"); bool testResult = TestSocketOption(testSockets, SocketOptionLevel.IP, SocketOptionName.UnblockSource, boolData, false); testSockets.TearDown(); return (testResult ? TestResult.Pass : TestResult.Fail); } [TestMethod] public TestResult SocketsEnums11_SocketOptionName_UseLoopback_UDP() { SocketPair testSockets = new SocketPair(ProtocolType.Udp, SocketType.Dgram); Log.Comment("Testing UseLoopback with UDP"); bool testResult = TestSocketOption(testSockets, SocketOptionLevel.IP, SocketOptionName.UseLoopback, boolData, false); testSockets.TearDown(); return (testResult ? TestResult.Pass : TestResult.Fail); } [TestMethod] public TestResult SocketsEnums12_SON_AcceptConnection() { /// /// 1. Starts a server socket listening for TCP /// 2. Verifies that AcceptConnection is correct before and after /// /// bool testResult = true; try { byte[] buf = new byte[4]; int number; SocketPair testSockets = new SocketPair(ProtocolType.Tcp, SocketType.Stream); testSockets.Startup(0, 0); testSockets.socketServer.GetSocketOption( SocketOptionLevel.Socket, SocketOptionName.AcceptConnection, buf ); number = (int)buf[0] + (int)(buf[1]<<8) + (int)(buf[2]<<16) + (int)(buf[3]<<24); testResult &= (number == 0); testSockets.socketServer.Listen(1); testSockets.socketServer.GetSocketOption( SocketOptionLevel.Socket, SocketOptionName.AcceptConnection, buf ); number = (int)buf[0] + (int)(buf[1]<<8) + (int)(buf[2]<<16) + (int)(buf[3]<<24); testResult &= (number != 0); testSockets.TearDown(); testSockets = null; } catch (System.Exception e) { Log.Comment("Caught exception: " + e.Message); //////if (e.GetType() == Type.GetType("System.Net.Sockets.SocketException")) ////// Log.Comment("ErrorCode: " + ((SocketException)e).ErrorCode); testResult = false; } return (testResult ? TestResult.Pass : TestResult.Fail); } [TestMethod] public TestResult SocketsEnums13_SON_Broadcast() { /// /// 1. Starts a UDP client broadcasting /// 2. Verifies that Broadcast is correct before and after /// /// bool testResult = false; try { SocketPair testSockets1 = new SocketPair(ProtocolType.Udp, SocketType.Dgram); int clientPort1 = SocketTools.nextPort; int serverPort1 = SocketTools.nextPort; int tempPort1 = SocketTools.nextPort; IPEndPoint epBroadcast1 = new IPEndPoint( SocketTools.DottedDecimalToIp( (byte)255, (byte)255, (byte)255, (byte)255), tempPort1); Log.Comment("SetSocketOption socket, broadcast, false"); testSockets1.socketClient.SetSocketOption( SocketOptionLevel.Socket, SocketOptionName.Broadcast, false); try { Log.Comment("SendTo epBroadcast1"); testSockets1.socketClient.SendTo( new byte[] { 0x01, 0x02, 0x03 }, epBroadcast1); Log.Comment("Error, this should never get displayed. An exception should have been thrown."); } catch (SocketException e) { Log.Comment("Error code: " + e.ErrorCode); Log.Comment("Correctly threw exception trying to broadcast from socket that has had broadcast turned off."); testResult = true; } catch (Exception e) { Log.Comment("Incorrect exception thrown: " + e.Message); } finally { Log.Comment("Tear down the socket"); testSockets1.TearDown(); } //--// SocketPair testSockets2 = new SocketPair(ProtocolType.Udp, SocketType.Dgram); int clientPort2 = SocketTools.nextPort; int serverPort2 = SocketTools.nextPort; int tempPort2 = SocketTools.nextPort; IPEndPoint epBroadcast2 = new IPEndPoint( SocketTools.DottedDecimalToIp( (byte)255, (byte)255, (byte)255, (byte)255), tempPort2); Log.Comment("SetSocketOption socket, broadcast, true"); testSockets2.socketClient.SetSocketOption( SocketOptionLevel.Socket,SocketOptionName.Broadcast, true); try { Log.Comment("SendTo epBroadcast1"); testSockets2.socketClient.SendTo( new byte[] { 0x01, 0x02, 0x03 }, epBroadcast2); } catch (SocketException e) { Log.Comment("Error code: " + e.ErrorCode); if (e.ErrorCode == 10047) { Log.Comment("Some drivers do not like this option being set. Allow them to throw this exception"); testResult &= true; } else { Log.Comment("Incorrectly threw exception trying to broadcast from socket that has had broadcast turned on."); testResult = false; } } catch (Exception e) { Log.Comment("Incorrect exception thrown: " + e.Message); } finally { Log.Comment("Tear down the socket"); testSockets2.TearDown(); } } catch (SocketException e) { Log.Comment("SocketException ErrorCode: " + e.ErrorCode); if (e.ErrorCode == 10047) { Log.Comment("Address family not supported by protocol family."); Log.Comment("This exception is thrown by the device driver that doesnt' implement Loopback for UDP"); } else { Log.Comment("Fail for any other error codes that we don't know about"); testResult = false; } } catch (Exception e) { Log.Comment("Caught exception: " + e.Message); testResult = false; } return (testResult ? TestResult.Pass : TestResult.Fail); } [TestMethod] public TestResult SocketsEnums14_SON_ReceiveBuffer() { /// /// 1. Sends a message of size RecieveBuffer /// 2. Verifies that it transferred correctly /// 1. Sends a message of size RecieveBuffer+1 /// 2. Verifies that the correct exception is thrown /// /// bool testResult = true; byte[] buf = new byte[4]; int number; try { int receiveBufferValue1 = 1024; int receiveBufferValue2 = 512; SocketPair testSockets = new SocketPair(ProtocolType.Tcp, SocketType.Stream); testSockets.socketClient.SetSocketOption( SocketOptionLevel.Socket, SocketOptionName.ReceiveBuffer, receiveBufferValue1); testSockets.socketClient.GetSocketOption( SocketOptionLevel.Socket, SocketOptionName.ReceiveBuffer, buf); number = (int)buf[0] + (int)(buf[1]<<8) + (int)(buf[2]<<16) + (int)(buf[3]<<24); if(number != receiveBufferValue1) throw new System.Exception("ReceiveBuffer option was not set correctly"); testSockets.socketClient.SetSocketOption( SocketOptionLevel.Socket, SocketOptionName.ReceiveBuffer, receiveBufferValue2); testSockets.socketClient.GetSocketOption( SocketOptionLevel.Socket, SocketOptionName.ReceiveBuffer, buf); number = (int)buf[0] + (int)(buf[1]<<8) + (int)(buf[2]<<16) + (int)(buf[3]<<24); if(number != receiveBufferValue2) throw new System.Exception("ReceiveBuffer option was not set correctly"); testSockets.Startup(0, 0); Log.Comment("ReceiveBuffer " + number.ToString() ); testSockets.bufSend = new byte[number]; testSockets.bufReceive = new byte[number]; testSockets.socketServer.Listen(1); testSockets.socketClient.Connect(testSockets.epServer); int cBytes = testSockets.socketClient.Send(testSockets.bufSend); if (cBytes != testSockets.bufSend.Length) throw new System.Exception("Send failed, wrong length"); using (Socket sock = testSockets.socketServer.Accept()) { if (sock.LocalEndPoint == null) throw new System.Exception("LocalEndPoint is null"); if (testSockets.socketServer.LocalEndPoint.ToString() != sock.LocalEndPoint.ToString()) throw new System.Exception("LocalEndPoint is incorrect"); if (sock.RemoteEndPoint == null) throw new System.Exception("RemoteEndPoint is null"); if (testSockets.socketClient.LocalEndPoint.ToString() != sock.RemoteEndPoint.ToString()) throw new System.Exception("RemoteEndPoint is incorrect"); //wait a second to ensure the socket is available System.Threading.Thread.Sleep(1000); cBytes = sock.Available; if (cBytes != testSockets.bufSend.Length) throw new System.Exception("Send failed, wrong length"); cBytes = sock.Receive(testSockets.bufReceive); } testSockets.AssertDataReceived(cBytes); testSockets.TearDown(); testSockets = null; } catch (System.Exception e) { Log.Comment("Caught exception: " + e.Message); //////if (e.GetType() == Type.GetType("System.Net.Sockets.SocketException")) ////// Log.Comment("ErrorCode: " + ((SocketException)e).ErrorCode); testResult = false; } return (testResult ? TestResult.Pass : TestResult.Fail); } [TestMethod] public TestResult SocketsEnums15_SON_SendBuffer() { /// /// 1. Sends a message of size SendBuffer /// 2. Verifies that it transferred correctly /// 1. Sends a message of size SendBuffer+1 /// 2. Verifies that the correct exception is thrown /// /// bool testResult = true; byte[] buf = new byte[4]; int number; try { int sendBufferValue1 = 1024; int sendBufferValue2 = 512; SocketPair testSockets = new SocketPair(ProtocolType.Tcp, SocketType.Stream); testSockets.socketClient.SetSocketOption( SocketOptionLevel.Socket, SocketOptionName.SendBuffer, sendBufferValue1); testSockets.socketClient.GetSocketOption( SocketOptionLevel.Socket, SocketOptionName.SendBuffer, buf); number = (int)buf[0] + (int)(buf[1]<<8) + (int)(buf[2]<<16) + (int)(buf[3]<<24); if(number != sendBufferValue1) throw new System.Exception("ReceiveBuffer option was not set correctly"); testSockets.socketClient.SetSocketOption( SocketOptionLevel.Socket, SocketOptionName.SendBuffer, sendBufferValue2); testSockets.socketClient.GetSocketOption( SocketOptionLevel.Socket, SocketOptionName.SendBuffer, buf); number = (int)buf[0] + (int)(buf[1]<<8) + (int)(buf[2]<<16) + (int)(buf[3]<<24); if(number != sendBufferValue2) throw new System.Exception("ReceiveBuffer option was not set correctly"); Log.Comment("ReceiveBuffer " + number.ToString() ); testSockets.Startup(0, 0); testSockets.bufSend = new byte[number]; testSockets.bufReceive = new byte[number]; testSockets.socketServer.Listen(1); testSockets.socketClient.Connect(testSockets.epServer); int cBytes = testSockets.socketClient.Send(testSockets.bufSend); if (cBytes != testSockets.bufSend.Length) throw new System.Exception("Send failed, wrong length"); using (Socket sock = testSockets.socketServer.Accept()) { if (sock.LocalEndPoint == null) throw new System.Exception("LocalEndPoint is null"); if (testSockets.socketServer.LocalEndPoint.ToString() != sock.LocalEndPoint.ToString()) throw new System.Exception("LocalEndPoint is incorrect"); if (sock.RemoteEndPoint == null) throw new System.Exception("RemoteEndPoint is null"); if (testSockets.socketClient.LocalEndPoint.ToString() != sock.RemoteEndPoint.ToString()) throw new System.Exception("RemoteEndPoint is incorrect"); //wait a second to ensure the socket is available System.Threading.Thread.Sleep(1000); cBytes = sock.Available; if (cBytes != testSockets.bufSend.Length) throw new System.Exception("Send failed, wrong length"); cBytes = sock.Receive(testSockets.bufReceive); } testSockets.AssertDataReceived(cBytes); testSockets.TearDown(); testSockets = null; } catch (System.Exception e) { Log.Comment("Caught exception: " + e.Message); //////if (e.GetType() == Type.GetType("System.Net.Sockets.SocketException")) ////// Log.Comment("ErrorCode: " + ((SocketException)e).ErrorCode); testResult = false; } return (testResult ? TestResult.Pass : TestResult.Fail); } } } ================================================ FILE: Zelig/Zelig/Test/RunTime/NETMF/System/socketTests/StressTests.cs ================================================ /*---------------------------------------------------------------------- * StressTests.cs - file description * Version: 1.0 * Author: REDMOND\a-grchat * Created: 1/7/2008 11:08:59 AM * * This tests sending large packets and large amounts of large packets * ---------------------------------------------------------------------*/ using System; using System.Reflection; using System.Threading; using System.Net; using System.Net.Sockets; namespace Microsoft.Zelig.Test { public class StressTests : TestBase, ITestInterface { [SetUp] public InitializeResult Initialize() { Log.Comment("Adding set up for the tests"); try { // Check networking - we need to make sure we can reach our proxy server System.Net.Dns.GetHostEntry("itgproxy.dns.microsoft.com"); } catch (Exception ex) { Log.Exception("Unable to get address for itgproxy.dns.microsoft.com", ex); return InitializeResult.Skip; } return InitializeResult.ReadyToGo; } [TearDown] public void CleanUp() { Log.Comment("Cleaning up after the tests."); } public override TestResult Run( string[] args ) { return TestResult.Pass; } //--// //--// //--// //This is a large number greater than the max buffer size private const int LARGE_NUM = 5000; private class StressSocketPair : SocketPair { private AutoResetEvent evt; //--// public StressSocketPair(ProtocolType prot, SocketType st) : base(prot, st) { if (prot == ProtocolType.Tcp) { socketClient.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.Linger, false); socketServer.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.Linger, false); } evt = new AutoResetEvent( false ); } public new void Startup(int portClient, int portServer) { socketClient.Bind(new IPEndPoint(IPAddress.Loopback, portClient)); socketServer.Bind(new IPEndPoint(IPAddress.Loopback, portServer)); epClient = (IPEndPoint)socketClient.LocalEndPoint; epServer = (IPEndPoint)socketServer.LocalEndPoint; NewData(); } public void NewData() { NewData( LARGE_NUM ); } public void NewData( int size ) { bufSend = new byte[size]; bufReceive = new byte[size]; new Random().NextBytes(bufSend); } public void StressTestAsyncThreadProc() { using(Socket sock = socketServer.Accept()) { int cToReceive = bufReceive.Length; do { cToReceive -= sock.Receive( bufReceive, bufReceive.Length - cToReceive, cToReceive, SocketFlags.None ); } while(cToReceive > 0); } evt.Set(); } public AutoResetEvent SyncPoint { get { return evt; } } } [TestMethod] public TestResult StressTest1_LargePacketUDP() { /// ///1. Starts a server socket listening for TCP ///2. Starts a client socket connected to the server ///3. Verifies that a large amount of data can be sent /// const int c_StartSize = 0x100; const int c_EndSize = 0x176F; bool testResult = true; int size = c_StartSize; int increment = 2; try { do { StressSocketPair testSockets = new StressSocketPair( ProtocolType.Udp, SocketType.Dgram ); testSockets.Startup(0, 0); testSockets.NewData( size ); int cBytes = testSockets.socketClient.SendTo(testSockets.bufSend, testSockets.epServer); if (cBytes != testSockets.bufSend.Length) throw new Exception("Send failed, wrong length"); int cToReceive = cBytes; int spin = 0; do { int avail = testSockets.socketServer.Available; if(avail > 0) { EndPoint epClient = (EndPoint)testSockets.epClient; cToReceive -= testSockets.socketServer.ReceiveFrom( testSockets.bufReceive, cBytes - cToReceive, cToReceive, SocketFlags.None, ref epClient ); } else { Thread.Sleep( 100 ); ++spin; } } while (cToReceive > 0 && spin < 20 ); if(spin == 20) testResult = false; testSockets.AssertDataReceived(cBytes); testSockets.TearDown(); testSockets = null; // clean up allocations System.GC.Collect(); size *= increment; } while (size <= c_EndSize); } catch (Exception e) { Log.Exception("Unexpected Exception", e); //////if (e.GetType() == Type.GetType("System.Net.Sockets.SocketException")) ////// Log.Comment("ErrorCode: " + ((SocketException)e).ErrorCode); testResult = false; } Log.Comment( "Max buffer size successfully sent and received was: " + (size / increment).ToString() ); return (testResult ? TestResult.Pass : TestResult.Pass); } [TestMethod] public TestResult StressTest2_LargePacketTCP() { /// ///1. Starts a server socket listening for TCP ///2. Starts a client socket connected to the server ///3. Verifies that a large amount of data can be sent /// const int c_StartSize = 0x100; const int c_EndSize = 0x10000; TestResult testResult = TestResult .Pass; int size = c_StartSize; int increment = 2; Thread server = null; try { do { StressSocketPair testSockets = new StressSocketPair( ProtocolType.Tcp, SocketType.Stream); server = new Thread(new ThreadStart( testSockets.StressTestAsyncThreadProc)); testSockets.Startup(0, 0); testSockets.NewData(size); testSockets.socketServer.Listen(1); testSockets.socketClient.Connect(testSockets.epServer); server.Start(); DateTime start = DateTime.Now; int cBytes = testSockets.socketClient.Send(testSockets.bufSend); if (cBytes != testSockets.bufSend.Length) throw new Exception("Send failed, wrong length"); testSockets.SyncPoint.WaitOne(); DateTime end = DateTime.Now; Log.Comment("Successfully received buffer of size " + testSockets.bufReceive.Length); int duration = (end - start).Milliseconds + 1; Log.Comment("Approximate " + testSockets.bufReceive.Length / duration + " Kb/sec rate to send "); testSockets.AssertDataReceived(cBytes); testSockets.TearDown(); testSockets = null; size *= increment; // clean up allocations System.GC.Collect(); server.Join(); server = null; } while (size <= c_EndSize); } catch (System.Net.Sockets.SocketException e) { Log.Exception("Unexpected SocketException - ErrorCode: " + ((SocketException)e).ErrorCode, e); if (e.ErrorCode == (int)SocketError.MessageSize) { testResult = TestResult.Pass; } else { testResult = TestResult.Fail; } } catch (System.OutOfMemoryException e) { Log.Exception("System.OutOfMemoryException", e); testResult = TestResult.Pass; } catch (Exception e) { Log.Exception("Unexpected Exception", e); testResult = TestResult.Fail; } finally { if (server != null && server.IsAlive) { server.Abort(); } } return testResult; } [TestMethod] public TestResult StressTest3_LargePacketUDP() { /// /// 1. Starts a server socket listening for UDP /// 2. Starts a client socket sending UDP packets /// 3. Verifies that a large amount of data can be sent /// /// TestResult testResult = TestResult.Pass; StressSocketPair testSockets = new StressSocketPair(ProtocolType.Udp, SocketType.Dgram); try { Log.Comment("Testing with port 0"); testSockets.Startup(0, 0); int cBytes = testSockets.socketClient.SendTo(testSockets.bufSend, testSockets.epServer); if (cBytes != testSockets.bufSend.Length) throw new Exception("Send failed, wrong length"); EndPoint epFrom = new IPEndPoint(IPAddress.Any, 0); cBytes = testSockets.socketServer.ReceiveFrom(testSockets.bufReceive, ref epFrom); if (testSockets.epClient.Address.ToString() != ((IPEndPoint)epFrom).Address.ToString()) throw new Exception("Bad address"); } catch (SocketException e) { Log.Exception("Unexpected Socket Excption - ErrorCode: " + e.ErrorCode.ToString(), e); if (e.ErrorCode == 10047) { Log.Comment("Address family not supported by protocol family."); Log.Comment("This exception is thrown by the device driver that doesnt' implement Loopback for UDP"); } else { testResult = TestResult.Fail; Log.Comment("Fail for any other error codes that we don't know about"); } } catch (Exception e) { Log.Exception("Unexpected Exception", e); testResult = TestResult.Fail; } finally { testSockets.TearDown(); } return testResult; } [TestMethod] public TestResult StressTest4_MarathonSend() { /// ///1. Starts a server socket listening for TCP ///2. Starts a client socket connected to the server ///3. Verifies that a large amount of data can be sent /// many consecutive times. /// TestResult testResult = TestResult.Pass; StressSocketPair testSockets = new StressSocketPair(ProtocolType.Tcp, SocketType.Stream); try { Log.Comment("Testing with port 0"); testSockets.Startup(0, 0); testSockets.socketClient.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.SendBuffer, 5 * 1024); testSockets.socketServer.Listen(1); testSockets.socketClient.Connect(testSockets.epServer); int cBytes = 0; using (Socket sock = testSockets.socketServer.Accept()) { sock.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReceiveBuffer, 5 * 1024); for (int i = 0; i < 100; i++) { cBytes = testSockets.socketClient.Send(testSockets.bufSend); if (cBytes != testSockets.bufSend.Length) throw new Exception("Send failed, wrong length"); if (sock.LocalEndPoint == null) throw new Exception("LocalEndPoint is null"); //Fix? if (testSockets.socketServer.LocalEndPoint.ToString() != sock.LocalEndPoint.ToString()) throw new Exception("LocalEndPoint is incorrect"); if (sock.RemoteEndPoint == null) throw new Exception("RemoteEndPoint is null"); if (testSockets.socketClient.LocalEndPoint.ToString() != sock.RemoteEndPoint.ToString()) throw new Exception("RemoteEndPoint is incorrect"); int cToReceive = cBytes; do { cToReceive -= sock.Receive(testSockets.bufReceive, cBytes - cToReceive, cToReceive, SocketFlags.None); } while (cToReceive > 0); } testSockets.AssertDataReceived(cBytes); testSockets.NewData(); } } catch (System.OutOfMemoryException e) { Log.Exception("Out of Memory Exception is ok on devices with limited memory constraints.", e); } catch (System.Net.Sockets.SocketException e) { Log.Exception("ErrorCode: " + ((SocketException)e).ErrorCode, e); testResult = TestResult.Fail; } catch (Exception e) { Log.Exception("Unexpected Exception", e); testResult = TestResult.Fail; } finally { testSockets.TearDown(); } return testResult; } } } ================================================ FILE: Zelig/Zelig/Test/RunTime/NETMF/mscorlib/Properties/AssemblyInfo.cs ================================================ using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; // General Information about an assembly is controlled through the following // set of attributes. Change these attribute values to modify the information // associated with an assembly. [assembly: AssemblyTitle("simple")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("Test_mscorlib")] [assembly: AssemblyCopyright("Copyright © 2015")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible(false)] // The following GUID is for the ID of the typelib if this project is exposed to COM [assembly: Guid("aa4773c3-713c-4612-a7fa-8ad068fd2011")] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Build and Revision Numbers // by using the '*' as shown below: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("1.0.0.0")] [assembly: AssemblyFileVersion("1.0.0.0")] ================================================ FILE: Zelig/Zelig/Test/RunTime/NETMF/mscorlib/Test_mscorlib.csproj ================================================  Debug AnyCPU {E149B569-516B-4C88-A7B1-EBD02E12DD1E} Library Properties Microsoft.Zelig.Test Test_mscorlib Microsoft.Zelig.Test.Runtime.Test_mscorlib v4.5 512 true full true ..\..\..\..\..\ZeligBuild\Target\bin\Debug\ DEBUG;TRACE prompt 4 CS0618; CS0661; CS0660; CS0628; CS1058; CS0067; CS0108; CS0168; CS0109; CS0414; CS0626; CS1718; CS0675; 0CS0108; CS0162; CS0219; ; CS0164; CS0219; CS0649; CS0414; CS0169; CS0114; CS0251 full true ..\..\..\..\..\ZeligBuild\Target\bin\Release\ DEBUG;TRACE prompt 4 true CS0108; CS0162; CS0219; ; CS0164; CS0219; CS0649; CS0414; CS0169; CS0114; CS0251 {186f31a3-ef89-4a25-b2d5-20070702aa01} system {186f31a3-ef89-4a25-b2d5-20080628aa01} system_core {b649b569-516b-4c88-a7b1-ebd02e12dd99} Test_Common ================================================ FILE: Zelig/Zelig/Test/RunTime/NETMF/mscorlib/arrays/ArraysOtherTests.cs ================================================ //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // Copyright (c) Microsoft Corporation. All rights reserved. //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// using System; namespace Microsoft.Zelig.Test { public class ArraysOtherTests : TestBase, ITestInterface { [SetUp] public InitializeResult Initialize( ) { return InitializeResult.ReadyToGo; } [TearDown] public void CleanUp() { } public override TestResult Run( string[] args ) { TestResult result = TestResult.Pass; result |= Assert.CheckFailed( Othersystemarrays_conversion_01_Test( ) ); result |= Assert.CheckFailed( Othersystemarrays_conversion_02_Test( ) ); result |= Assert.CheckFailed( Othersystemarrays_nullvalue_01_Test( ) ); result |= Assert.CheckFailed( Othercovariance_exception_01_Test( ) ); result |= Assert.CheckFailed( Othercovariance_exception_02_Test( ) ); result |= Assert.CheckFailed( Othercovariance_explicit_01_Test( ) ); result |= Assert.CheckFailed( Othercovariance_explicit_02_Test( ) ); result |= Assert.CheckFailed( Othercovariance_explicit_03_Test( ) ); result |= Assert.CheckFailed( Othercovariance_explicit_04_Test( ) ); result |= Assert.CheckFailed( Othercovariance_implicit_01_Test( ) ); result |= Assert.CheckFailed( Othercovariance_implicit_02_Test( ) ); result |= Assert.CheckFailed( Othercovariance_implicit_03_Test( ) ); result |= Assert.CheckFailed( Othercovariance_implicit_04_Test( ) ); result |= Assert.CheckFailed( Othercovariance_implicit_05_Test( ) ); return result; } //Other Test methods //The following tests were ported from folder current\test\cases\client\CLR\Conformance\10_classes\Other //systemarrays_conversion_01,systemarrays_conversion_02,systemarrays_nullvalue_01,covariance_exception_01,covariance_exception_02,covariance_explicit_01,covariance_explicit_02,covariance_explicit_03,covariance_explicit_04,covariance_implicit_01,covariance_implicit_02,covariance_implicit_03,covariance_implicit_04,covariance_implicit_05 //Test Case Calls [TestMethod] public TestResult Othersystemarrays_conversion_01_Test() { Log.Comment("System.Array Type - Conversions "); Log.Comment("Verify that an implicit reference conversion from T[D] to System.Array exists"); if (Other_TestClass_systemarrays_conversion_01.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Othersystemarrays_conversion_02_Test() { Log.Comment("System.Array Type - Conversions "); Log.Comment("Verify that an explicit reference conversion from System.Array to T[D] exists"); if (Other_TestClass_systemarrays_conversion_02.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Othersystemarrays_nullvalue_01_Test() { Log.Comment("System.Array Type - Null Values"); Log.Comment("Verify that a System.Array array can be set to null"); if (Other_TestClass_systemarrays_nullvalue_01.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Othercovariance_exception_01_Test() { if (Other_TestClass_covariance_exception_01.testMethod()) { return TestResult.Pass; } return TestResult.KnownFailure; } [TestMethod] public TestResult Othercovariance_exception_02_Test() { Log.Comment("Array Covariance"); Log.Comment("Verify an System.Exception is thrown when incompatible types are assigned to array elements"); if (Other_TestClass_covariance_exception_02.testMethod()) { return TestResult.Pass; } return TestResult.KnownFailure; } [TestMethod] public TestResult Othercovariance_explicit_01_Test() { Log.Comment("Array Covariance"); Log.Comment("Verify covariance from object to any reference-type (class)"); if (Other_TestClass_covariance_explicit_01.testMethod()) { return TestResult.Pass; } return TestResult.KnownFailure; } [TestMethod] public TestResult Othercovariance_explicit_02_Test() { Log.Comment("Array Covariance"); Log.Comment("Verify covariance from any reference-type (interface) to object"); if (Other_TestClass_covariance_explicit_02.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Othercovariance_explicit_03_Test() { Log.Comment("Array Covariance"); Log.Comment("Verify covariance from any class-type S to any class-type T, provided S is base class of T"); if (Other_TestClass_covariance_explicit_03.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Othercovariance_explicit_04_Test() { Log.Comment("Array Covariance"); Log.Comment("Verify covariance from any interface-type S to any interface-type T, provided S is not derived from T"); if (Other_TestClass_covariance_explicit_04.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Othercovariance_implicit_01_Test() { Log.Comment("Array Covariance"); Log.Comment("Verify covariance from any reference-type (class) to object"); if (Other_TestClass_covariance_implicit_01.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Othercovariance_implicit_02_Test() { Log.Comment("Array Covariance"); Log.Comment("Verify covariance from any reference-type (interface) to object"); if (Other_TestClass_covariance_implicit_02.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Othercovariance_implicit_03_Test() { Log.Comment("Array Covariance"); Log.Comment("Verify covariance from any class-type S to any class-type T, provided S is derived from T"); if (Other_TestClass_covariance_implicit_03.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Othercovariance_implicit_04_Test() { Log.Comment("Array Covariance"); Log.Comment("Verify covariance from any class-type S to any interface-type T, provided S implements T"); if (Other_TestClass_covariance_implicit_04.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Othercovariance_implicit_05_Test() { Log.Comment("Array Covariance"); Log.Comment("Verify covariance from any interface-type S to any interface-type T, provided S is derived from T"); if (Other_TestClass_covariance_implicit_05.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult BinarySearch_Test() { Log.Comment("Array.BinarySearch"); var objects = new MyClass[6]; for (int i = 0; i < 6; i++) { objects[i] = new MyClass(i + 1); } int y = Array.BinarySearch(objects, new MyClass(5), null); if (y == 4) { return TestResult.Pass; } else { Log.Comment("BinarySearch returns " + y.ToString()); return TestResult.Fail; } } class MyClass : IComparable { int m_int; public MyClass(int i) { m_int = i; } public int Value { get { return m_int; } } public int CompareTo(object obj) { var target = obj as MyClass; if (target == null) { throw new ArgumentException( ); } return m_int - target.m_int; } } //Compiled Test Cases class Other_TestClass_systemarrays_conversion_01 { public static int Main_old() { int result = 32; MyClass[] a = new MyClass[] { new MyClass(5), new MyClass(6), new MyClass(7) }; System.Array SystemArray; int[] StaticArray = new int[] { 10, 20, 30, 40 }; // There exists an implicit reference conversion for this SystemArray = StaticArray; if (result == a[2].Value) { return 1; } return 0; } public static bool testMethod() { return (Main_old() == 0); } } class Other_TestClass_systemarrays_conversion_02 { public static int Main_old() { System.Array SystemArray; int[] StaticArray = new int[] { 10, 20, 30, 40 }; int[] StaticArray2 = new int[] { 1, 2, 3, 4 }; SystemArray = StaticArray; StaticArray2 = (int[])SystemArray; int result = 0; for (int x = 0; x < 4; x++) { if (StaticArray[x] != (x + 1) * 10) { result = 1; } } return result; } public static bool testMethod() { return (Main_old() == 0); } } class Other_TestClass_systemarrays_nullvalue_01 { public static int Main_old() { System.Array SystemArray; SystemArray = null; return 0; } public static bool testMethod() { return (Main_old() == 0); } } class Other_TestClass_covariance_exception_01 { static void Fill(object[] array, int index, int count, object value) { for (int i = index; i < index + count; i++) array[i] = value; } public static int Main_old( ) { string[] strings = new string[100]; Fill( strings, 0, 100, "Undefined" ); Fill( strings, 0, 10, null ); try { Fill( strings, 90, 10, 0 ); } catch(System.Exception) { return 0; } return 1; } public static bool testMethod() { return (Main_old() == 0); } } class Queue { int next; int prev; } class Other_TestClass_covariance_exception_02 { public static int Main_old() { string[] stringArr = new string[10]; object[] objectArr = stringArr; objectArr[0] = "hello"; try { objectArr[1] = new Queue(); } catch (System.Exception) { return 0; } return 1; } public static bool testMethod() { return (Main_old() == 0); } } class Other_TestClass_covariance_explicit_01_Imp { public int x; } class Other_TestClass_covariance_explicit_01 { public static int Main_old() { Other_TestClass_covariance_explicit_01_Imp[] mc = new Other_TestClass_covariance_explicit_01_Imp[10]; for (int x=0; x < 10; x++) { mc[x] = new Other_TestClass_covariance_explicit_01_Imp( ); mc[x].x = x; } object[] o = new Other_TestClass_covariance_explicit_01_Imp[10]; mc = (Other_TestClass_covariance_explicit_01_Imp[])o; return 0; } public static bool testMethod() { return (Main_old() == 0); } } interface Other_TestClass_covariance_explicit_02_Inter { int testmethod( ); } class Other_TestClass_covariance_explicit_02_Imp : Other_TestClass_covariance_explicit_02_Inter { public int testmethod() { Log.Comment("Other_TestClass_covariance_explicit_02_Imp::testmethod()"); return 0; } } class Other_TestClass_covariance_explicit_02 { public static int Main_old() { Other_TestClass_covariance_explicit_02_Inter[] inst = new Other_TestClass_covariance_explicit_02_Inter[10]; for (int x = 0; x < 10; x++) { inst[x] = new Other_TestClass_covariance_explicit_02_Imp( ); } object[] o = new Other_TestClass_covariance_explicit_02_Imp[10]; inst = (Other_TestClass_covariance_explicit_02_Imp[])o; return 0; } public static bool testMethod() { return (Main_old() == 0); } } class ClassS { public int x; } class ClassT : ClassS { public int y; } class Other_TestClass_covariance_explicit_03 { public static int Main_old() { ClassS[] cs = new ClassT[10]; ClassT[] ct = new ClassT[10]; for (int x = 0; x < 10; x++) { cs[x] = new ClassT( ); ct[x] = new ClassT( ); } ct = (ClassT[])cs; return 0; } public static bool testMethod() { return (Main_old() == 0); } } interface InterfaceS { int Other_TestClass_covariance_explicit_04MethodS( ); } interface InterfaceT : InterfaceS { int Other_TestClass_covariance_explicit_04MethodT( ); } class Other_TestClass_covariance_explicit_04_Imp : InterfaceS, InterfaceT { public int x; public int Other_TestClass_covariance_explicit_04MethodS() { return 0; } public int Other_TestClass_covariance_explicit_04MethodT() { return 0; } } class Other_TestClass_covariance_explicit_04 { public static int Main_old() { InterfaceS[] ifs = new InterfaceT[10]; InterfaceT[] ift = new InterfaceT[10]; Other_TestClass_covariance_explicit_04_Imp mc = new Other_TestClass_covariance_explicit_04_Imp( ); for (int x = 0; x < 10; x++) { ifs[x] = new Other_TestClass_covariance_explicit_04_Imp( ); ift[x] = new Other_TestClass_covariance_explicit_04_Imp( ); } ift = (InterfaceT[])ifs; return 0; } public static bool testMethod() { return (Main_old() == 0); } } class Other_TestClass_covariance_implicit_01_Imp { public int x; } class Other_TestClass_covariance_implicit_01 { public static int Main_old() { Other_TestClass_covariance_implicit_01_Imp[] mc = new Other_TestClass_covariance_implicit_01_Imp[10]; for (int x = 0; x < 10; x++) { mc[x] = new Other_TestClass_covariance_implicit_01_Imp( ); Log.Comment(x.ToString()); mc[x].x = x; } object[] o = new object[10]; o = mc; for (int x = 0; x < 10; x++) { Log.Comment(((Other_TestClass_covariance_implicit_01_Imp)o[x]).x.ToString()); } return 0; } public static bool testMethod() { return (Main_old() == 0); } } interface Other_TestClass_covariance_implicit_02_Inter { int testmethod( ); } class Other_TestClass_covariance_implicit_02_Imp : Other_TestClass_covariance_implicit_02_Inter { public int testmethod() { Log.Comment("Other_TestClass_covariance_implicit_02_Imp::testmethod()"); return 0; } } class Other_TestClass_covariance_implicit_02 { public static int Main_old() { Other_TestClass_covariance_implicit_02_Inter[] inst = new Other_TestClass_covariance_implicit_02_Inter[10]; for (int x = 0; x < 10; x++) { inst[x] = new Other_TestClass_covariance_implicit_02_Imp( ); } object[] o = new object[10]; o = inst; return 0; } public static bool testMethod() { return (Main_old() == 0); } } class Other_TestClass_covariance_implicit_03_T { public int x; } class Other_TestClass_covariance_implicit_03_S : Other_TestClass_covariance_implicit_03_T { public int y; } class Other_TestClass_covariance_implicit_03 { public static int Main_old() { Other_TestClass_covariance_implicit_03_S[] cs = new Other_TestClass_covariance_implicit_03_S[10]; Other_TestClass_covariance_implicit_03_T[] ct = new Other_TestClass_covariance_implicit_03_T[10]; for (int x = 0; x < 10; x++) { cs[x] = new Other_TestClass_covariance_implicit_03_S( ); ct[x] = new Other_TestClass_covariance_implicit_03_T( ); } ct = cs; return 0; } public static bool testMethod() { return (Main_old() == 0); } } interface Other_TestClass_covariance_implicit_04_IT { int Other_TestClass_covariance_implicit_04Method( ); } class Other_TestClass_covariance_implicit_04_ImpS : Other_TestClass_covariance_implicit_04_IT { public int x; public int Other_TestClass_covariance_implicit_04Method() { return 0; } } class Other_TestClass_covariance_implicit_04 { public static int Main_old() { Other_TestClass_covariance_implicit_04_IT[] it = new Other_TestClass_covariance_implicit_04_IT[10]; Other_TestClass_covariance_implicit_04_ImpS[] cs = new Other_TestClass_covariance_implicit_04_ImpS[10]; for (int x = 0; x < 10; x++) { it[x] = new Other_TestClass_covariance_implicit_04_ImpS( ); cs[x] = new Other_TestClass_covariance_implicit_04_ImpS( ); } it = cs; return 0; } public static bool testMethod() { return (Main_old() == 0); } } interface Other_TestClass_covariance_implicit_05_IT { int Other_TestClass_covariance_implicit_05MethodT( ); } interface Other_TestClass_covariance_implicit_05_IS : Other_TestClass_covariance_implicit_05_IT { int Other_TestClass_covariance_implicit_05MethodS( ); } class Other_TestClass_covariance_implicit_05_ImpT : Other_TestClass_covariance_implicit_05_IT { public int x; public int Other_TestClass_covariance_implicit_05MethodT() { return 0; } } class Other_TestClass_covariance_implicit_05_ImpS : Other_TestClass_covariance_implicit_05_IS { public int x; public int Other_TestClass_covariance_implicit_05MethodS() { return 0; } public int Other_TestClass_covariance_implicit_05MethodT() { return 0; } } class Other_TestClass_covariance_implicit_05 { public static int Main_old() { Other_TestClass_covariance_implicit_05_IS[] ifs = new Other_TestClass_covariance_implicit_05_IS[10]; Other_TestClass_covariance_implicit_05_IT[] ift = new Other_TestClass_covariance_implicit_05_IT[10]; Other_TestClass_covariance_implicit_05_ImpS cs = new Other_TestClass_covariance_implicit_05_ImpS( ); Other_TestClass_covariance_implicit_05_ImpT ct = new Other_TestClass_covariance_implicit_05_ImpT( ); for (int x = 0; x < 10; x++) { ifs[x] = new Other_TestClass_covariance_implicit_05_ImpS( ); ift[x] = new Other_TestClass_covariance_implicit_05_ImpT( ); } ift = ifs; return 0; } public static bool testMethod() { return (Main_old() == 0); } } } } ================================================ FILE: Zelig/Zelig/Test/RunTime/NETMF/mscorlib/arrays/ArraysSimpleTests.cs ================================================ //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // Copyright (c) Microsoft Corporation. All rights reserved. //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// #define TEST_EXCEPTIONS using System; namespace Microsoft.Zelig.Test { public class ArraysSimpleTests : TestBase, ITestInterface { [SetUp] public InitializeResult Initialize( ) { return InitializeResult.ReadyToGo; } [TearDown] public void CleanUp() { } public override TestResult Run(string[] args) { TestResult result = TestResult.Pass; string testName = "Simple_decl_decl_"; result |= Assert.CheckFailed(Simple_decl_decl_01_Test(), testName, 1); result |= Assert.CheckFailed(Simple_decl_decl_02_Test(), testName, 2); result |= Assert.CheckFailed(Simple_decl_decl_03_Test(), testName, 3); result |= Assert.CheckFailed(Simple_decl_decl_04_Test(), testName, 4); result |= Assert.CheckFailed(Simple_decl_decl_05_Test(), testName, 5); result |= Assert.CheckFailed(Simple_decl_decl_06_Test(), testName, 6); result |= Assert.CheckFailed(Simple_decl_decl_07_Test(), testName, 7); result |= Assert.CheckFailed(Simple_decl_decl_08_Test(), testName, 8); result |= Assert.CheckFailed(Simple_decl_decl_09_Test(), testName, 9); result |= Assert.CheckFailed(Simple_decl_decl_10_Test(), testName, 10); result |= Assert.CheckFailed(Simple_decl_decl_11_Test(), testName, 11); result |= Assert.CheckFailed(Simple_decl_decl_12_Test(), testName, 12); result |= Assert.CheckFailed(Simple_decl_decl_13_Test(), testName, 13); result |= Assert.CheckFailed(Simple_decl_decl_14_Test(), testName, 14); result |= Assert.CheckFailed(Simple_decl_decl_15_Test(), testName, 15); testName = "Simple_decl_bounds_"; result |= Assert.CheckFailed(Simple_decl_bounds_01_Test(), testName, 1); testName = "Simple_decl_index_"; result |= Assert.CheckFailed(Simple_decl_index_01_Test(), testName, 1); result |= Assert.CheckFailed(Simple_decl_index_02_Test(), testName, 2); result |= Assert.CheckFailed(Simple_decl_index_03_Test(), testName, 3); result |= Assert.CheckFailed(Simple_decl_index_04_Test(), testName, 4); result |= Assert.CheckFailed(Simple_decl_index_05_Test(), testName, 5); result |= Assert.CheckFailed(Simple_decl_index_06_Test(), testName, 6); result |= Assert.CheckFailed(Simple_decl_index_07_Test(), testName, 7); result |= Assert.CheckFailed(Simple_decl_index_08_Test(), testName, 8); result |= Assert.CheckFailed(Simple_decl_index_09_Test(), testName, 9); result |= Assert.CheckFailed(Simple_decl_index_10_Test(), testName, 10); result |= Assert.CheckFailed(Simple_decl_index_11_Test(), testName, 11); result |= Assert.CheckFailed(Simple_decl_index_12_Test(), testName, 12); testName = "Simple_decl_syntax_"; result |= Assert.CheckFailed(Simple_decl_syntax_03_Test(), testName, 3); testName = "Simple_init_init_a_"; result |= Assert.CheckFailed(Simple_init_init_a_01_Test(), testName, 1); result |= Assert.CheckFailed(Simple_init_init_a_02_Test(), testName, 2); result |= Assert.CheckFailed(Simple_init_init_a_03_Test(), testName, 3); result |= Assert.CheckFailed(Simple_init_init_a_04_Test(), testName, 4); result |= Assert.CheckFailed(Simple_init_init_a_05_Test(), testName, 5); result |= Assert.CheckFailed(Simple_init_init_a_06_Test(), testName, 6); testName = "Simple_init_init_a_"; result |= Assert.CheckFailed(Simple_init_init_b_02_Test(), testName, 2); result |= Assert.CheckFailed(Simple_init_init_b_03_Test(), testName, 3); result |= Assert.CheckFailed(Simple_init_init_b_04_Test(), testName, 4); result |= Assert.CheckFailed(Simple_init_init_b_05_Test(), testName, 5); result |= Assert.CheckFailed(Simple_init_init_b_06_Test(), testName, 6); result |= Assert.CheckFailed(Simple_init_init_b_08_Test(), testName, 8); result |= Assert.CheckFailed(Simple_init_init_b_09_Test(), testName, 9); result |= Assert.CheckFailed(Simple_init_init_b_10_Test(), testName, 10); testName = "Simple_init_init_a_"; result |= Assert.CheckFailed(Simple_init_init_c_01_Test(), testName, 1); result |= Assert.CheckFailed(Simple_init_init_c_02_Test(), testName, 2); result |= Assert.CheckFailed(Simple_init_init_c_03_Test(), testName, 3); result |= Assert.CheckFailed(Simple_init_init_c_04_Test(), testName, 4); result |= Assert.CheckFailed(Simple_init_init_c_05_Test(), testName, 5); result |= Assert.CheckFailed(Simple_init_init_c_06_Test(), testName, 6); result |= Assert.CheckFailed(Simple_init_init_c_08_Test(), testName, 8); result |= Assert.CheckFailed(Simple_init_init_c_09_Test(), testName, 9); result |= Assert.CheckFailed(Simple_init_init_c_10_Test(), testName, 10); testName = "Simple_init_init_a_"; result |= Assert.CheckFailed(Simple_init_init_d_01_Test(), testName, 1); result |= Assert.CheckFailed(Simple_init_init_d_02_Test(), testName, 2); result |= Assert.CheckFailed(Simple_init_init_d_03_Test(), testName, 3); result |= Assert.CheckFailed(Simple_init_init_d_04_Test(), testName, 4); result |= Assert.CheckFailed(Simple_init_init_d_05_Test(), testName, 5); result |= Assert.CheckFailed(Simple_init_init_d_06_Test(), testName, 6); result |= Assert.CheckFailed(Simple_init_init_d_08_Test(), testName, 8); result |= Assert.CheckFailed(Simple_init_init_d_09_Test(), testName, 9); result |= Assert.CheckFailed(Simple_init_init_d_10_Test(), testName, 10); testName = "Simple_init_init_a_"; result |= Assert.CheckFailed(Simple_init_init_e_01_Test(), testName, 1); result |= Assert.CheckFailed(Simple_init_init_e_02_Test(), testName, 2); result |= Assert.CheckFailed(Simple_init_init_e_03_Test(), testName, 3); result |= Assert.CheckFailed(Simple_init_init_e_04_Test(), testName, 4); result |= Assert.CheckFailed(Simple_init_init_e_05_Test(), testName, 5); result |= Assert.CheckFailed(Simple_init_init_e_06_Test(), testName, 6); result |= Assert.CheckFailed(Simple_init_init_e_08_Test(), testName, 8); result |= Assert.CheckFailed(Simple_init_init_e_09_Test(), testName, 9); result |= Assert.CheckFailed(Simple_init_init_e_10_Test(), testName, 10); testName = "Simple_init_syntax_"; result |= Assert.CheckFailed(Simple_init_syntax_09_Test(), testName, 9); result |= Assert.CheckFailed(Simple_init_syntax_11_Test(), testName, 11); result |= Assert.CheckFailed(Simple_init_syntax_12_Test(), testName, 12); testName = "Simple_init_decl_"; result |= Assert.CheckFailed(Simple_init_decl_02_Test(), testName, 2); result |= Assert.CheckFailed(Simple_init_decl_03_Test(), testName, 3); result |= Assert.CheckFailed(Simple_init_decl_04_Test(), testName, 4); result |= Assert.CheckFailed(Simple_init_decl_05_Test(), testName, 5); testName = "Simple_init_shorthand_"; result |= Assert.CheckFailed(Simple_init_shorthand_01_Test(), testName, 1); testName = "Simple_init_constinit_"; result |= Assert.CheckFailed(Simple_init_constinit_01_Test(), testName, 1); result |= Assert.CheckFailed(Simple_init_constinit_02_Test(), testName, 2); result |= Assert.CheckFailed(Simple_init_constinit_03_Test(), testName, 3); testName = "Simple_acc_iter_length_"; result |= Assert.CheckFailed(Simple_acc_iter_length_01_Test(), testName, 1); testName = "Simple_acc_iter_bounds_"; result |= Assert.CheckFailed(Simple_acc_iter_bounds_01_Test(), testName, 1); result |= Assert.CheckFailed(Simple_acc_iter_bounds_02_Test(), testName, 2); result |= Assert.CheckFailed(Simple_acc_iter_bounds_03_Test(), testName, 3); result |= Assert.CheckFailed(Simple_acc_iter_bounds_04_Test(), testName, 4); testName = "Simple_acc_iter_idxtype_a_"; result |= Assert.CheckFailed(Simple_acc_iter_idxtype_a_01_Test(), testName, 1); result |= Assert.CheckFailed(Simple_acc_iter_idxtype_a_02_Test(), testName, 2); result |= Assert.CheckFailed(Simple_acc_iter_idxtype_a_03_Test(), testName, 3); result |= Assert.CheckFailed(Simple_acc_iter_idxtype_a_04_Test(), testName, 4); result |= Assert.CheckFailed(Simple_acc_iter_idxtype_a_06_Test(), testName, 6); testName = "Simple_acc_iter_idxtype_b_"; result |= Assert.CheckFailed(Simple_acc_iter_idxtype_b_01_Test(), testName, 1); result |= Assert.CheckFailed(Simple_acc_iter_idxtype_b_02_Test(), testName, 2); result |= Assert.CheckFailed(Simple_acc_iter_idxtype_b_03_Test(), testName, 3); result |= Assert.CheckFailed(Simple_acc_iter_idxtype_b_04_Test(), testName, 4); result |= Assert.CheckFailed(Simple_acc_iter_idxtype_b_06_Test(), testName, 6); testName = "Simple_acc_iter_iter_"; result |= Assert.CheckFailed(Simple_acc_iter_iter_01_Test(), testName, 1); result |= Assert.CheckFailed(Simple_acc_iter_iter_02_Test(), testName, 2); testName = "Simple_assign_smpass_a_"; result |= Assert.CheckFailed(Simple_assign_smpass_a_01_Test(), testName, 1); result |= Assert.CheckFailed(Simple_assign_smpass_a_02_Test(), testName, 2); result |= Assert.CheckFailed(Simple_assign_smpass_a_03_Test(), testName, 3); result |= Assert.CheckFailed(Simple_assign_smpass_a_04_Test(), testName, 4); result |= Assert.CheckFailed(Simple_assign_smpass_a_05_Test(), testName, 5); result |= Assert.CheckFailed(Simple_assign_smpass_a_06_Test(), testName, 6); result |= Assert.CheckFailed(Simple_assign_smpass_a_07_Test(), testName, 7); result |= Assert.CheckFailed(Simple_assign_smpass_a_08_Test(), testName, 8); result |= Assert.CheckFailed(Simple_assign_smpass_a_09_Test(), testName, 9); testName = "Simple_assign_smpass_b_"; result |= Assert.CheckFailed(Simple_assign_smpass_b_01_Test(), testName, 1); result |= Assert.CheckFailed(Simple_assign_smpass_b_02_Test(), testName, 2); result |= Assert.CheckFailed(Simple_assign_smpass_b_03_Test(), testName, 3); result |= Assert.CheckFailed(Simple_assign_smpass_b_04_Test(), testName, 4); result |= Assert.CheckFailed(Simple_assign_smpass_b_05_Test(), testName, 5); result |= Assert.CheckFailed(Simple_assign_smpass_b_06_Test(), testName, 6); result |= Assert.CheckFailed(Simple_assign_smpass_b_07_Test(), testName, 7); result |= Assert.CheckFailed(Simple_assign_smpass_b_08_Test(), testName, 8); result |= Assert.CheckFailed(Simple_assign_smpass_b_09_Test(), testName, 9); testName = "Simple_assign_badcode_"; result |= Assert.CheckFailed(Simple_assign_badcode_01_Test(), testName, 1); result |= Assert.CheckFailed(Simple_assign_badcode_03_Test(), testName, 3); result |= Assert.CheckFailed(Simple_assign_badcode_04_Test(), testName, 4); testName = "Simple_assign_element_"; result |= Assert.CheckFailed(Simple_assign_element_01_Test(), testName, 1); result |= Assert.CheckFailed(Simple_assign_element_02_Test(), testName, 2); testName = "Simple_assign_argpass_"; result |= Assert.CheckFailed(Simple_assign_argpass_01_Test(), testName, 1); result |= Assert.CheckFailed(Simple_assign_argpass_02_Test(), testName, 2); result |= Assert.CheckFailed(Simple_assign_argpass_03_Test(), testName, 3); testName = "Simple_object_sysarr_"; result |= Assert.CheckFailed(Simple_object_sysarr_01_Test(), testName, 1); result |= Assert.CheckFailed(Simple_object_sysarr_02_Test(), testName, 2); return result; } //Simple Test methods //The following tests were ported from folder current\test\cases\client\CLR\Conformance\10_classes\Simple //decl_decl_01,decl_decl_02,decl_decl_03,decl_decl_04,decl_decl_05,decl_decl_06,decl_decl_07,decl_decl_08,decl_decl_09,decl_decl_10,decl_decl_11,decl_decl_12,decl_decl_13,decl_decl_14,decl_decl_15,decl_bounds_01,decl_bounds_02,decl_bounds_03,decl_index_01,decl_index_02,decl_index_03,decl_index_04,decl_index_05,decl_index_06,decl_index_07,decl_index_08,decl_index_09,decl_index_10,decl_index_11,decl_index_12,decl_syntax_03,init_init_a_01,init_init_a_02,init_init_a_03,init_init_a_04,init_init_a_05,ini /* JHS t_init_a_06,init_init_a_08,init_init_a_09,init_init_a_10,init_init_b_01,init_init_b_02,init_init_b_03,init_init_b_04,init_init_b_05,init_init_b_06,init_init_b_08,init_init_b_09,init_init_b_10,init_init_c_01,init_init_c_02,init_init_c_03,init_init_c_04,init_init_c_05,init_init_c_06,init_init_c_08,init_init_c_09,init_init_c_10,init_init_d_01,init_init_d_02,init_init_d_03,init_init_d_04,init_init_d_05,init_init_d_06,init_init_d_08,init_init_d_09,init_init_d_10,init_init_e_01,init_init_e_02,init_init_e_03,init _init_e_04,init_init_e_05,init_init_e_06,init_init_e_08,init_init_e_09,init_init_e_10,init_syntax_09,init_syntax_11,init_syntax_12,init_decl_02,init_decl_03,init_decl_04,init_decl_05,init_shorthand_01,init_constinit_01,init_constinit_02,init_constinit_03,acc_iter_length_01,acc_iter_bounds_01,acc_iter_bounds_02,acc_iter_bounds_03,acc_iter_bounds_04,acc_iter_idxtype_a_01,acc_iter_idxtype_a_02,acc_iter_idxtype_a_03,acc_iter_idxtype_a_04,acc_iter_idxtype_a_06,acc_iter_idxtype_b_01,acc_iter_idxtype_b_02,acc_ite r_idxtype_b_03,acc_iter_idxtype_b_04,acc_iter_idxtype_b_06,acc_iter_iter_01,acc_iter_iter_02,assign_smpass_a_01,assign_smpass_a_02,assign_smpass_a_03,assign_smpass_a_04,assign_smpass_a_05,assign_smpass_a_06,assign_smpass_a_07,assign_smpass_a_08,assign_smpass_a_09,assign_smpass_b_01,assign_smpass_b_02,assign_smpass_b_03,assign_smpass_b_04,assign_smpass_b_05,assign_smpass_b_06,assign_smpass_b_07,assign_smpass_b_08,assign_smpass_b_09,assign_badcode_01,assign_badcode_03,assign_badcode_04,assign_element_01,assign_ element_02,assign_argpass_01,assign_argpass_02,assign_argpass_03,object_sysarr_01,object_sysarr_02,object_sysarr_03,nonzerolb_decl_01,nonzerolb_decl_02,nonzerolb_error_04,nonzerolb_usage_01,nonzerolb_usage_02,nonzerolb_usage_03,nonzerolb_usage_04.cs) -- skipped */ //Test Case Calls [TestMethod] public TestResult Simple_decl_decl_01_Test() { Log.Comment(" Arrays - Declarations"); Log.Comment(" Declare a simple array of type int"); if (Simple_TestClass_decl_decl_01.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Simple_decl_decl_02_Test() { Log.Comment(" Arrays - Declarations"); Log.Comment(" Declare a simple array of type byte"); if (Simple_TestClass_decl_decl_02.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Simple_decl_decl_03_Test() { Log.Comment(" Arrays - Declarations"); Log.Comment(" Declare a simple array of type short"); if (Simple_TestClass_decl_decl_03.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Simple_decl_decl_04_Test() { Log.Comment(" Arrays - Declarations"); Log.Comment(" Declare a simple array of type long"); if (Simple_TestClass_decl_decl_04.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Simple_decl_decl_05_Test() { Log.Comment(" Arrays - Declarations"); Log.Comment(" Declare a simple array of type char"); if (Simple_TestClass_decl_decl_05.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Simple_decl_decl_06_Test() { Log.Comment(" Arrays - Declarations"); Log.Comment(" Declare a simple array of type double"); if (Simple_TestClass_decl_decl_06.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Simple_decl_decl_07_Test() { Log.Comment(" Arrays - Declarations"); Log.Comment(" Declare a simple array of type float"); if (Simple_TestClass_decl_decl_07.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Simple_decl_decl_08_Test() { Log.Comment(" Arrays - Declarations"); Log.Comment(" Declare a simple array of type double"); if (Simple_TestClass_decl_decl_08.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Simple_decl_decl_09_Test() { Log.Comment(" Arrays - Declarations"); Log.Comment(" Declare a simple array of type bool"); if (Simple_TestClass_decl_decl_09.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Simple_decl_decl_10_Test() { Log.Comment(" Arrays - Declarations"); Log.Comment(" Declare a simple array of a user-defined struct"); if (Simple_TestClass_decl_decl_10.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Simple_decl_decl_11_Test() { Log.Comment(" Arrays - Declarations"); Log.Comment(" Declare a simple array of a user-defined class"); if (Simple_TestClass_decl_decl_11.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Simple_decl_decl_12_Test() { Log.Comment(" Arrays - Declarations"); Log.Comment(" Declare a simple array of a user-defined interface"); if (Simple_TestClass_decl_decl_12.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Simple_decl_decl_13_Test() { Log.Comment(" Arrays - Declarations"); Log.Comment(" Declare a simple array of type object"); if (Simple_TestClass_decl_decl_13.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Simple_decl_decl_14_Test() { Log.Comment(" Arrays - Declarations"); Log.Comment(" Declare a simple array of delegates"); if (Simple_TestClass_decl_decl_14.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Simple_decl_decl_15_Test() { Log.Comment(" Arrays - Declarations"); Log.Comment(" Declare a simple array of type System.Array"); if (Simple_TestClass_decl_decl_15.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Simple_decl_bounds_01_Test() { Log.Comment(" Arrays - Declarations"); Log.Comment(" An array created as array[0] compiles successfully"); if (Simple_TestClass_decl_bounds_01.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Simple_decl_index_01_Test() { Log.Comment(" decl_index_01 "); Log.Comment(" Arrays - Declarations"); Log.Comment(" A char variable as an array index should work"); if (Simple_TestClass_decl_index_01.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Simple_decl_index_02_Test() { Log.Comment(" Arrays - Declarations"); Log.Comment(" A byte variable as an array index should work"); if (Simple_TestClass_decl_index_02.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Simple_decl_index_03_Test() { Log.Comment(" Arrays - Declarations"); Log.Comment(" A short variable as an array index should work"); if (Simple_TestClass_decl_index_03.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Simple_decl_index_04_Test() { Log.Comment(" Arrays - Declarations"); Log.Comment(" A short literal as an array index should work"); if (Simple_TestClass_decl_index_04.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Simple_decl_index_05_Test() { Log.Comment(" Arrays - Declarations"); Log.Comment(" A byte literal as an array index should work"); if (Simple_TestClass_decl_index_05.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Simple_decl_index_06_Test() { Log.Comment(" Arrays - Declarations"); Log.Comment(" A char literal as an array index should work"); if (Simple_TestClass_decl_index_06.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Simple_decl_index_07_Test() { Log.Comment(" Arrays - Declarations"); Log.Comment(" A uint variable as an array index should work"); if (Simple_TestClass_decl_index_07.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Simple_decl_index_08_Test() { Log.Comment(" Arrays - Declarations"); Log.Comment(" A long variable as an array index should work"); if (Simple_TestClass_decl_index_08.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Simple_decl_index_09_Test() { Log.Comment(" Arrays - Declarations"); Log.Comment(" A ulong variable as an array index should work"); if (Simple_TestClass_decl_index_09.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Simple_decl_index_10_Test() { Log.Comment(" Arrays - Declarations"); Log.Comment(" A uint literal as an array index should work"); if (Simple_TestClass_decl_index_10.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Simple_decl_index_11_Test() { Log.Comment(" Arrays - Declarations"); Log.Comment(" A long literal as an array index should work"); if (Simple_TestClass_decl_index_11.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Simple_decl_index_12_Test() { Log.Comment(" Arrays - Declarations"); Log.Comment(" A ulong literal as an array index should work"); if (Simple_TestClass_decl_index_12.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Simple_decl_syntax_03_Test() { Log.Comment(" Arrays - Declarations"); Log.Comment(" Spaces after type and between brackets and comments do not affect arrays"); if (Simple_TestClass_decl_syntax_03.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Simple_init_init_a_01_Test() { Log.Comment(" Arrays - Initialization"); Log.Comment(" Initialization of arrays of type int using new (longhand)"); if (Simple_TestClass_init_init_a_01.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Simple_init_init_a_02_Test() { Log.Comment(" Arrays - Initialization"); Log.Comment(" Initialization of arrays of type short using new (longhand)"); if (Simple_TestClass_init_init_a_02.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Simple_init_init_a_03_Test() { Log.Comment(" Arrays - Initialization"); Log.Comment(" Initialization of arrays of type byte using new (longhand)"); if (Simple_TestClass_init_init_a_03.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Simple_init_init_a_04_Test() { Log.Comment(" Arrays - Initialization"); Log.Comment(" Initialization of arrays of type long using new (longhand)"); if (Simple_TestClass_init_init_a_04.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Simple_init_init_a_05_Test() { Log.Comment(" Arrays - Initialization"); Log.Comment(" Initialization of arrays of type double using new (longhand)"); if (Simple_TestClass_init_init_a_05.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Simple_init_init_a_06_Test() { Log.Comment(" Arrays - Initialization"); Log.Comment(" Initialization of arrays of type float using new (longhand)"); if (Simple_TestClass_init_init_a_06.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Simple_init_init_a_08_Test() { Log.Comment(" Arrays - Initialization"); Log.Comment(" Initialization of arrays of type String using new (longhand)"); if (Simple_TestClass_init_init_a_08.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Simple_init_init_a_09_Test() { Log.Comment(" Arrays - Initialization"); Log.Comment(" Initialization of arrays of type char using new (longhand)"); if (Simple_TestClass_init_init_a_09.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Simple_init_init_a_10_Test() { Log.Comment(" Arrays - Initialization"); Log.Comment(" Initialization of arrays of type bool using new (longhand)"); if (Simple_TestClass_init_init_a_10.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Simple_init_init_b_01_Test() { Log.Comment(" Arrays - Initialization"); Log.Comment(" Initialization of arrays of type int using new (shorthand)"); if (Simple_TestClass_init_init_b_01.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Simple_init_init_b_02_Test() { Log.Comment(" Arrays - Initialization"); Log.Comment(" Initialization of arrays of type short using new (shorthand)"); if (Simple_TestClass_init_init_b_02.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Simple_init_init_b_03_Test() { Log.Comment(" Arrays - Initialization"); Log.Comment(" Initialization of arrays of type byte using new (shorthand)"); if (Simple_TestClass_init_init_b_03.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Simple_init_init_b_04_Test() { Log.Comment(" Arrays - Initialization"); Log.Comment(" Initialization of arrays of type long using new (shorthand)"); if (Simple_TestClass_init_init_b_04.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Simple_init_init_b_05_Test() { Log.Comment(" Arrays - Initialization"); Log.Comment(" Initialization of arrays of type double using new (shorthand)"); if (Simple_TestClass_init_init_b_05.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Simple_init_init_b_06_Test() { Log.Comment(" Arrays - Initialization"); Log.Comment(" Initialization of arrays of type float using new (shorthand)"); if (Simple_TestClass_init_init_b_06.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Simple_init_init_b_08_Test() { Log.Comment(" Arrays - Initialization"); Log.Comment(" Initialization of arrays of type String using new (shorthand)"); if (Simple_TestClass_init_init_b_08.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Simple_init_init_b_09_Test() { Log.Comment(" Arrays - Initialization"); Log.Comment(" Initialization of arrays of type char using new (shorthand)"); if (Simple_TestClass_init_init_b_09.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Simple_init_init_b_10_Test() { Log.Comment(" Arrays - Initialization"); Log.Comment(" Initialization of arrays of type bool using new (shorthand)"); if (Simple_TestClass_init_init_b_10.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Simple_init_init_c_01_Test() { Log.Comment(" Arrays - Initialization"); Log.Comment(" Initialization of arrays of type int using new (# init values sets array size)"); if (Simple_TestClass_init_init_c_01.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Simple_init_init_c_02_Test() { Log.Comment(" Arrays - Initialization"); Log.Comment(" Initialization of arrays of type short using new (# init values sets array size)"); if (Simple_TestClass_init_init_c_02.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Simple_init_init_c_03_Test() { Log.Comment(" Arrays - Initialization"); Log.Comment(" Initialization of arrays of type byte using new (# init values sets array size)"); if (Simple_TestClass_init_init_c_03.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Simple_init_init_c_04_Test() { Log.Comment(" Arrays - Initialization"); Log.Comment(" Initialization of arrays of type long using new (# init values sets array size)"); if (Simple_TestClass_init_init_c_04.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Simple_init_init_c_05_Test() { Log.Comment(" Arrays - Initialization"); Log.Comment(" Initialization of arrays of type double using new (# init values sets array size)"); if (Simple_TestClass_init_init_c_05.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Simple_init_init_c_06_Test() { Log.Comment(" Arrays - Initialization"); Log.Comment(" Initialization of arrays of type float using new (# init values sets array size)"); if (Simple_TestClass_init_init_c_06.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Simple_init_init_c_08_Test() { Log.Comment(" Arrays - Initialization"); Log.Comment(" Initialization of arrays of type String using new (# init values sets array size)"); if (Simple_TestClass_init_init_c_08.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Simple_init_init_c_09_Test() { Log.Comment(" Arrays - Initialization"); Log.Comment(" Initialization of arrays of type char using new (# init values sets array size)"); if (Simple_TestClass_init_init_c_09.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Simple_init_init_c_10_Test() { Log.Comment(" Arrays - Initialization"); Log.Comment(" Initialization of arrays of type bool using new (# init values sets array size)"); if (Simple_TestClass_init_init_c_10.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Simple_init_init_d_01_Test() { Log.Comment(" Arrays - Initialization"); Log.Comment(" Initialization of arrays of type int using new (longhand) separate from decl statement"); if (Simple_TestClass_init_init_d_01.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Simple_init_init_d_02_Test() { Log.Comment(" Arrays - Initialization"); Log.Comment(" Initialization of arrays of type short using new (longhand) separate from decl statement"); if (Simple_TestClass_init_init_d_02.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Simple_init_init_d_03_Test() { Log.Comment(" Arrays - Initialization"); Log.Comment(" Initialization of arrays of type byte using new (longhand) separate from decl statement"); if (Simple_TestClass_init_init_d_03.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Simple_init_init_d_04_Test() { Log.Comment(" Arrays - Initialization"); Log.Comment(" Initialization of arrays of type long using new (longhand) separate from decl statement"); if (Simple_TestClass_init_init_d_04.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Simple_init_init_d_05_Test() { Log.Comment(" Arrays - Initialization"); Log.Comment(" Initialization of arrays of type double using new (longhand) separate from decl statement"); if (Simple_TestClass_init_init_d_05.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Simple_init_init_d_06_Test() { Log.Comment(" Arrays - Initialization"); Log.Comment(" Initialization of arrays of type float using new (longhand) separate from decl statement"); if (Simple_TestClass_init_init_d_06.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Simple_init_init_d_08_Test() { Log.Comment(" Arrays - Initialization"); Log.Comment(" Initialization of arrays of type String using new (longhand) separate from decl statement"); if (Simple_TestClass_init_init_d_08.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Simple_init_init_d_09_Test() { Log.Comment(" Arrays - Initialization"); Log.Comment(" Initialization of arrays of type char using new (longhand) separate from decl statement"); if (Simple_TestClass_init_init_d_09.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Simple_init_init_d_10_Test() { Log.Comment(" Arrays - Initialization"); Log.Comment(" Initialization of arrays of type bool using new (longhand) separate from decl statement"); if (Simple_TestClass_init_init_d_10.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Simple_init_init_e_01_Test() { Log.Comment(" Arrays - Initialization"); Log.Comment(" Initialization of arrays of type int using new (# init values sets array size) separate from decl statement"); if (Simple_TestClass_init_init_e_01.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Simple_init_init_e_02_Test() { Log.Comment(" Arrays - Initialization"); Log.Comment(" Initialization of arrays of type short using new (# init values sets array size) separate from decl statement"); if (Simple_TestClass_init_init_e_02.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Simple_init_init_e_03_Test() { Log.Comment(" Arrays - Initialization"); Log.Comment(" Initialization of arrays of type byte using new (# init values sets array size) separate from decl statement"); if (Simple_TestClass_init_init_e_03.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Simple_init_init_e_04_Test() { Log.Comment(" Arrays - Initialization"); Log.Comment(" Initialization of arrays of type long using new (# init values sets array size) separate from decl statement"); if (Simple_TestClass_init_init_e_04.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Simple_init_init_e_05_Test() { Log.Comment(" Arrays - Initialization"); Log.Comment(" Initialization of arrays of type double using new (# init values sets array size) separate from decl statement"); if (Simple_TestClass_init_init_e_05.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Simple_init_init_e_06_Test() { Log.Comment(" Arrays - Initialization"); Log.Comment(" Initialization of arrays of type float using new (# init values sets array size) separate from decl statement"); if (Simple_TestClass_init_init_e_06.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Simple_init_init_e_08_Test() { Log.Comment(" Arrays - Initialization"); Log.Comment(" Initialization of arrays of type String using new (# init values sets array size) separate from decl statement"); if (Simple_TestClass_init_init_e_08.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Simple_init_init_e_09_Test() { Log.Comment(" Arrays - Initialization"); Log.Comment(" Initialization of arrays of type char using new (# init values sets array size) separate from decl statement"); if (Simple_TestClass_init_init_e_09.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Simple_init_init_e_10_Test() { Log.Comment(" Arrays - Initialization"); Log.Comment(" Initialization of arrays of type bool using new (# init values sets array size) separate from decl statement"); if (Simple_TestClass_init_init_e_10.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Simple_init_syntax_09_Test() { Log.Comment(" Arrays - Initialization"); Log.Comment(" Syntax - Whitespace and comments in braces should not affect anything"); if (Simple_TestClass_init_syntax_09.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Simple_init_syntax_11_Test() { Log.Comment(" Arrays - Initialization"); Log.Comment(" Syntax - zero elements in initializer should create zero length array"); if (Simple_TestClass_init_syntax_11.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Simple_init_syntax_12_Test() { Log.Comment(" Arrays - Initialization"); Log.Comment(" Syntax - zero elements in initializer should be allowed for 0-length array"); if (Simple_TestClass_init_syntax_12.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Simple_init_decl_02_Test() { Log.Comment(" Arrays - Initialization"); Log.Comment(" Declaration - if initializer is used, a provided index can be a const"); if (Simple_TestClass_init_decl_02.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Simple_init_decl_03_Test() { Log.Comment(" Arrays - Initialization"); Log.Comment(" Declaration - if initializer is used, a provided index can be a const short"); if (Simple_TestClass_init_decl_03.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Simple_init_decl_04_Test() { Log.Comment(" Arrays - Initialization"); Log.Comment(" Declaration - if initializer is used, a provided index can be a const byte"); if (Simple_TestClass_init_decl_04.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Simple_init_decl_05_Test() { Log.Comment(" Arrays - Initialization"); Log.Comment(" Declaration - if initializer is used, a provided index can be a const long casted to an int"); if (Simple_TestClass_init_decl_05.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Simple_init_shorthand_01_Test() { Log.Comment(" Arrays - Initialization"); Log.Comment(" Initialization of arrays of type int using new (shorthand)"); Log.Comment(" This is to verify bug #52958 doesn't regress"); if (Simple_TestClass_init_shorthand_01.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Simple_init_constinit_01_Test() { Log.Comment(" Arrays - Initialization"); Log.Comment(" Ensure all constant init optimization code paths are covered: all constants (VS7:124565 for more info)"); if (Simple_TestClass_init_constinit_01.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Simple_init_constinit_02_Test() { Log.Comment(" Arrays - Initialization"); Log.Comment(" Ensure all constant init optimization code paths are covered: all variables (VS7:124565 for more info)"); if (Simple_TestClass_init_constinit_02.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Simple_init_constinit_03_Test() { Log.Comment(" Arrays - Initialization"); Log.Comment(" Ensure all constant init optimization code paths are covered: half variables and half constants (VS7:124565 for more info)"); if (Simple_TestClass_init_constinit_03.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Simple_acc_iter_length_01_Test() { Log.Comment(" acc_iter_length_01 "); Log.Comment(" Arrays - Access and Iteration"); Log.Comment(" Declare simple arrays of various lengths and verify that array.Length is correct"); if (Simple_TestClass_acc_iter_length_01.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Simple_acc_iter_bounds_01_Test() { Log.Comment(" Arrays - Access and Iteration"); Log.Comment(" Accessing an array's 0th element should work fine"); if (Simple_TestClass_acc_iter_bounds_01.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Simple_acc_iter_bounds_02_Test() { Log.Comment(" Arrays - Access and Iteration"); Log.Comment(" Accessing an array's maxlength element should work fine"); if (Simple_TestClass_acc_iter_bounds_02.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Simple_acc_iter_bounds_03_Test() { Log.Comment(" Arrays - Access and Iteration"); Log.Comment(" Accessing an array's -1 element should throw an System.Exception"); #if TEST_EXCEPTIONS if (Simple_TestClass_acc_iter_bounds_03.testMethod()) { return TestResult.Pass; } return TestResult.Fail; #else return TestResult.Skip; #endif } [TestMethod] public TestResult Simple_acc_iter_bounds_04_Test() { Log.Comment(" Arrays - Access and Iteration"); Log.Comment(" Accessing an array's maxlength+1 element should throw an System.Exception"); #if TEST_EXCEPTIONS if (Simple_TestClass_acc_iter_bounds_04.testMethod()) { return TestResult.Pass; } return TestResult.Fail; #else return TestResult.Skip; #endif } [TestMethod] public TestResult Simple_acc_iter_idxtype_a_01_Test() { Log.Comment(" Arrays - Access and Iteration"); Log.Comment(" Accessing an array's index with a variable of type int should work"); if (Simple_TestClass_acc_iter_idxtype_a_01.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Simple_acc_iter_idxtype_a_02_Test() { Log.Comment(" Arrays - Access and Iteration"); Log.Comment(" Accessing an array's index with a variable of type short should work"); if (Simple_TestClass_acc_iter_idxtype_a_02.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Simple_acc_iter_idxtype_a_03_Test() { Log.Comment(" Arrays - Access and Iteration"); Log.Comment(" Accessing an array's index with a variable of type byte should work"); if (Simple_TestClass_acc_iter_idxtype_a_03.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Simple_acc_iter_idxtype_a_04_Test() { Log.Comment(" Arrays - Access and Iteration"); Log.Comment(" Accessing an array's index with a variable of type char should work"); if (Simple_TestClass_acc_iter_idxtype_a_04.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Simple_acc_iter_idxtype_a_06_Test() { Log.Comment(" Arrays - Access and Iteration"); Log.Comment(" Accessing an array's index with a variable of type long should work"); if (Simple_TestClass_acc_iter_idxtype_a_06.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Simple_acc_iter_idxtype_b_01_Test() { Log.Comment(" Arrays - Access and Iteration"); Log.Comment(" Accessing an array's index with an int literal should work"); if (Simple_TestClass_acc_iter_idxtype_b_01.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Simple_acc_iter_idxtype_b_02_Test() { Log.Comment(" Arrays - Access and Iteration"); Log.Comment(" Accessing an array's index with a short literal should work"); if (Simple_TestClass_acc_iter_idxtype_b_02.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Simple_acc_iter_idxtype_b_03_Test() { Log.Comment(" Arrays - Access and Iteration"); Log.Comment(" Accessing an array's index with a byte literal should work"); if (Simple_TestClass_acc_iter_idxtype_b_03.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Simple_acc_iter_idxtype_b_04_Test() { Log.Comment(" Arrays - Access and Iteration"); Log.Comment(" Accessing an array's index with a char literal should work"); if (Simple_TestClass_acc_iter_idxtype_b_04.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Simple_acc_iter_idxtype_b_06_Test() { Log.Comment(" Arrays - Access and Iteration"); Log.Comment(" Accessing an array's index with a variable of type long should work"); if (Simple_TestClass_acc_iter_idxtype_b_06.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Simple_acc_iter_iter_01_Test() { Log.Comment(" Arrays - Access and Iteration"); Log.Comment(" Declare simple array of int, init it through iteration, verify values are correct"); if (Simple_TestClass_acc_iter_iter_01.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Simple_acc_iter_iter_02_Test() { Log.Comment(" Arrays - Access and Iteration"); Log.Comment(" Declare simple array of char, init it through individual element assignments, verify correctness"); if (Simple_TestClass_acc_iter_iter_02.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Simple_assign_smpass_a_01_Test() { Log.Comment(" Arrays - Assignments"); Log.Comment(" Assigning int type literals into array elements should work"); if (Simple_TestClass_assign_smpass_a_01.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Simple_assign_smpass_a_02_Test() { Log.Comment(" Arrays - Assignments"); Log.Comment(" Assigning byte type literals into array elements should work"); if (Simple_TestClass_assign_smpass_a_02.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Simple_assign_smpass_a_03_Test() { Log.Comment(" Arrays - Assignments"); Log.Comment(" Assigning short type literals into array elements should work"); if (Simple_TestClass_assign_smpass_a_03.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Simple_assign_smpass_a_04_Test() { Log.Comment(" Arrays - Assignments"); Log.Comment(" Assigning long type literals into array elements should work"); if (Simple_TestClass_assign_smpass_a_04.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Simple_assign_smpass_a_05_Test() { Log.Comment(" Arrays - Assignments"); Log.Comment(" Assigning char type literals into array elements should work"); if (Simple_TestClass_assign_smpass_a_05.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Simple_assign_smpass_a_06_Test() { Log.Comment(" Arrays - Assignments"); Log.Comment(" Assigning double type literals into array elements should work"); if (Simple_TestClass_assign_smpass_a_06.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Simple_assign_smpass_a_07_Test() { Log.Comment(" Arrays - Assignments"); Log.Comment(" Assigning float type literals into array elements should work"); if (Simple_TestClass_assign_smpass_a_07.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Simple_assign_smpass_a_08_Test() { Log.Comment(" Arrays - Assignments"); Log.Comment(" Assigning double type literals into array elements should work"); if (Simple_TestClass_assign_smpass_a_08.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Simple_assign_smpass_a_09_Test() { Log.Comment(" Arrays - Assignments"); Log.Comment(" Assigning bool type literals into array elements should work"); if (Simple_TestClass_assign_smpass_a_09.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Simple_assign_smpass_b_01_Test() { Log.Comment(" Arrays - Assignments"); Log.Comment(" Assigning int type variables into array elements should work"); if (Simple_TestClass_assign_smpass_b_01.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Simple_assign_smpass_b_02_Test() { Log.Comment(" Arrays - Assignments"); Log.Comment(" Assigning byte type variables into array elements should work"); if (Simple_TestClass_assign_smpass_b_02.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Simple_assign_smpass_b_03_Test() { Log.Comment(" Arrays - Assignments"); Log.Comment(" Assigning short type variables into array elements should work"); if (Simple_TestClass_assign_smpass_b_03.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Simple_assign_smpass_b_04_Test() { Log.Comment(" Arrays - Assignments"); Log.Comment(" Assigning long type variables into array elements should work"); if (Simple_TestClass_assign_smpass_b_04.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Simple_assign_smpass_b_05_Test() { Log.Comment(" Arrays - Assignments"); Log.Comment(" Assigning char type variables into array elements should work"); if (Simple_TestClass_assign_smpass_b_05.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Simple_assign_smpass_b_06_Test() { Log.Comment(" Arrays - Assignments"); Log.Comment(" Assigning double type variables into array elements should work"); if (Simple_TestClass_assign_smpass_b_06.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Simple_assign_smpass_b_07_Test() { Log.Comment(" Arrays - Assignments"); Log.Comment(" Assigning float type variables into array elements should work"); if (Simple_TestClass_assign_smpass_b_07.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Simple_assign_smpass_b_08_Test() { Log.Comment(" Arrays - Assignments"); Log.Comment(" Assigning double type variables into array elements should work"); if (Simple_TestClass_assign_smpass_b_08.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Simple_assign_smpass_b_09_Test() { Log.Comment(" Arrays - Assignments"); Log.Comment(" Assigning bool type variables into array elements should work"); if (Simple_TestClass_assign_smpass_b_09.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Simple_assign_badcode_01_Test() { Log.Comment(" Arrays - Assignments"); Log.Comment(" Assigning null to an array variable should work"); if (Simple_TestClass_assign_badcode_01.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Simple_assign_badcode_03_Test() { Log.Comment(" Arrays - Assignments"); Log.Comment(" Assigning a smaller array to a bigger array should work"); if (Simple_TestClass_assign_badcode_03.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Simple_assign_badcode_04_Test() { Log.Comment(" Arrays - Assignments"); Log.Comment(" Assigning a bigger array to a smaller array should work"); if (Simple_TestClass_assign_badcode_04.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Simple_assign_element_01_Test() { Log.Comment(" Arrays - Assignments"); Log.Comment(" Assigning one element to another element of the same array should work"); if (Simple_TestClass_assign_element_01.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Simple_assign_element_02_Test() { Log.Comment(" Arrays - Assignments"); Log.Comment(" Assigning one element to another element of a different array should work"); if (Simple_TestClass_assign_element_02.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Simple_assign_argpass_01_Test() { Log.Comment(" Arrays - Assignments - Passing elements to methods"); Log.Comment(" Passing an element to a function should work"); if (Simple_TestClass_assign_argpass_01.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Simple_assign_argpass_02_Test() { Log.Comment(" Arrays - Assignments - Passing elements to methods"); Log.Comment(" Passing an element to a function as a ref parameter should work"); if (Simple_TestClass_assign_argpass_02.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Simple_assign_argpass_03_Test() { Log.Comment(" Arrays - Assignments - Passing elements to methods"); Log.Comment(" Passing an element to a function as an out parameter should work"); if (Simple_TestClass_assign_argpass_03.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Simple_object_sysarr_01_Test() { Log.Comment(" Arrays - As Object and System.Array"); Log.Comment(" Testing the System.Array methods and Properties: System.Array.Clear()"); if (Simple_TestClass_object_sysarr_01.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Simple_object_sysarr_02_Test() { Log.Comment(" Arrays - As Object and System.Array"); Log.Comment(" Testing the System.Array methods and Properties: Length property"); if (Simple_TestClass_object_sysarr_02.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } //Compiled Test Cases class Simple_TestClass_decl_decl_01 { public static int Main_old() { int[] arr = new int[10]; return 0; } public static bool testMethod() { return (Main_old() == 0); } } class Simple_TestClass_decl_decl_02 { public static int Main_old() { byte[] arr = new byte[10]; return 0; } public static bool testMethod() { return (Main_old() == 0); } } class Simple_TestClass_decl_decl_03 { public static int Main_old() { short[] arr = new short[10]; return 0; } public static bool testMethod() { return (Main_old() == 0); } } class Simple_TestClass_decl_decl_04 { public static int Main_old() { long[] arr = new long[10]; return 0; } public static bool testMethod() { return (Main_old() == 0); } } class Simple_TestClass_decl_decl_05 { public static int Main_old() { char[] arr = new char[10]; return 0; } public static bool testMethod() { return (Main_old() == 0); } } class Simple_TestClass_decl_decl_06 { public static int Main_old() { double[] arr = new double[10]; return 0; } public static bool testMethod() { return (Main_old() == 0); } } class Simple_TestClass_decl_decl_07 { public static int Main_old() { float[] arr = new float[10]; return 0; } public static bool testMethod() { return (Main_old() == 0); } } class Simple_TestClass_decl_decl_08 { public static int Main_old() { double[] arr = new double[10]; return 0; } public static bool testMethod() { return (Main_old() == 0); } } class Simple_TestClass_decl_decl_09 { public static int Main_old() { bool[] arr = new bool[10]; return 0; } public static bool testMethod() { return (Main_old() == 0); } } struct myStruct { public int x ; } class Simple_TestClass_decl_decl_10 { public static int Main_old() { myStruct[] arr = new myStruct[10]; return 0; } public static bool testMethod() { return (Main_old() == 0); } } class myClass { public int x = 0; void meth() { } } class Simple_TestClass_decl_decl_11 { public static int Main_old() { myClass[] arr = new myClass[10]; return 0; } public static bool testMethod() { return (Main_old() == 0); } } interface myInterface { } class Simple_TestClass_decl_decl_12 { public static int Main_old() { myInterface[] arr = new myInterface[10]; return 0; } public static bool testMethod() { return (Main_old() == 0); } } class Simple_TestClass_decl_decl_13 { public static int Main_old() { object[] arr = new object[10]; return 0; } public static bool testMethod() { return (Main_old() == 0); } } delegate void myDelegate(String myString); class Simple_TestClass_decl_decl_14 { public static int Main_old() { myDelegate[] myDel = new myDelegate[10]; return 0; } public static bool testMethod() { return (Main_old() == 0); } } class Simple_TestClass_decl_decl_15 { public static int Main_old() { Array[] arr = new Array[10]; return 0; } public static bool testMethod() { return (Main_old() == 0); } } class Simple_TestClass_decl_bounds_01 { public static int Main_old() { int[] arr = new int[0]; return 0; } public static bool testMethod() { return (Main_old() == 0); } } class Simple_TestClass_decl_index_01 { public static int Main_old() { char x = 'a'; int[] arr1 = new int[x]; char y = 'b'; int[] arr2 = new int[y]; if (arr1.Length == (arr2.Length - 1)) return 0; else return 1; } public static bool testMethod() { return (Main_old() == 0); } } class Simple_TestClass_decl_index_02 { public static int Main_old() { byte x = 5; int[] arr1 = new int[x]; return 0; } public static bool testMethod() { return (Main_old() == 0); } } class Simple_TestClass_decl_index_03 { public static int Main_old() { short x = 5; int[] arr1 = new int[x]; return 0; } public static bool testMethod() { return (Main_old() == 0); } } class Simple_TestClass_decl_index_04 { public static int Main_old() { int[] arr1 = new int[(short)5]; return 0; } public static bool testMethod() { return (Main_old() == 0); } } class Simple_TestClass_decl_index_05 { public static int Main_old() { int[] arr1 = new int[(byte)5]; return 0; } public static bool testMethod() { return (Main_old() == 0); } } class Simple_TestClass_decl_index_06 { public static int Main_old() { int[] arr1 = new int['a']; int[] arr2 = new int['b']; Log.Comment(arr1.Length.ToString()); Log.Comment(arr2.Length.ToString()); if (arr1.Length == (arr2.Length - 1)) return 0; else return 1; } public static bool testMethod() { return (Main_old() == 0); } } class Simple_TestClass_decl_index_07 { public static int Main_old() { uint x = 5; int[] arr1 = new int[x]; return 0; } public static bool testMethod() { return (Main_old() == 0); } } class Simple_TestClass_decl_index_08 { public static int Main_old() { long x = 5; int[] arr1 = new int[x]; return 0; } public static bool testMethod() { return (Main_old() == 0); } } class Simple_TestClass_decl_index_09 { public static int Main_old() { ulong x = 5; int[] arr1 = new int[x]; return 0; } public static bool testMethod() { return (Main_old() == 0); } } class Simple_TestClass_decl_index_10 { public static int Main_old() { int[] arr1 = new int[5U]; return 0; } public static bool testMethod() { return (Main_old() == 0); } } class Simple_TestClass_decl_index_11 { public static int Main_old() { int[] arr1 = new int[5L]; return 0; } public static bool testMethod() { return (Main_old() == 0); } } class Simple_TestClass_decl_index_12 { public static int Main_old() { int[] arr1 = new int[5UL]; return 0; } public static bool testMethod() { return (Main_old() == 0); } } class Simple_TestClass_decl_syntax_03 { public static int Main_old() { int[] arr = new int[10]; int[ /* test comment */ ] arr2 = new int[5]; return 0; } public static bool testMethod() { return (Main_old() == 0); } } class Simple_TestClass_init_init_a_01 { public static int Main_old() { int[] arr = new int[5] { 1, 2, 3, 4, 5 }; int x = 0; if (arr[0] != 1) x = 1; if (arr[1] != 2) x = 1; if (arr[2] != 3) x = 1; if (arr[3] != 4) x = 1; if (arr[4] != 5) x = 1; return x; } public static bool testMethod() { return (Main_old() == 0); } } class Simple_TestClass_init_init_a_02 { public static int Main_old() { short[] arr = new short[5] { 1, 2, 3, 4, 5 }; int x = 0; if (arr[0] != 1) x = 1; if (arr[1] != 2) x = 1; if (arr[2] != 3) x = 1; if (arr[3] != 4) x = 1; if (arr[4] != 5) x = 1; return x; } public static bool testMethod() { return (Main_old() == 0); } } class Simple_TestClass_init_init_a_03 { public static int Main_old() { byte[] arr = new byte[5] { 1, 2, 3, 4, 5 }; int x = 0; if (arr[0] != 1) x = 1; if (arr[1] != 2) x = 1; if (arr[2] != 3) x = 1; if (arr[3] != 4) x = 1; if (arr[4] != 5) x = 1; return x; } public static bool testMethod() { return (Main_old() == 0); } } class Simple_TestClass_init_init_a_04 { public static int Main_old() { long[] arr = new long[5] { 1, 2, 3, 4, 5 }; int x = 0; if (arr[0] != 1) x = 1; if (arr[1] != 2) x = 1; if (arr[2] != 3) x = 1; if (arr[3] != 4) x = 1; if (arr[4] != 5) x = 1; return x; } public static bool testMethod() { return (Main_old() == 0); } } class Simple_TestClass_init_init_a_05 { public static int Main_old() { double[] arr = new double[5] { 1.0, 2.0, 3.0, 4.0, 5.0 }; int x = 0; if (arr[0] != 1.0) x = 1; if (arr[1] != 2.0) x = 1; if (arr[2] != 3.0) x = 1; if (arr[3] != 4.0) x = 1; if (arr[4] != 5.0) x = 1; return x; } public static bool testMethod() { return (Main_old() == 0); } } class Simple_TestClass_init_init_a_06 { public static int Main_old() { float[] arr = new float[5] { 1.0f, 2.0f, 3.0f, 4.0f, 5.0f }; int x = 0; if (arr[0] != 1.0) x = 1; if (arr[1] != 2.0) x = 1; if (arr[2] != 3.0) x = 1; if (arr[3] != 4.0) x = 1; if (arr[4] != 5.0) x = 1; return x; } public static bool testMethod() { return (Main_old() == 0); } } class Simple_TestClass_init_init_a_08 { public static int Main_old() { String[] arr = new String[5] { "one", "two", "three", "four", "five" }; int x = 0; if (!arr[0].Equals("one")) x = 1; if (!arr[1].Equals("two")) x = 1; if (!arr[2].Equals("three")) x = 1; if (!arr[3].Equals("four")) x = 1; if (!arr[4].Equals("five")) x = 1; return x; } public static bool testMethod() { return (Main_old() == 0); } } class Simple_TestClass_init_init_a_09 { public static int Main_old() { char[] arr = new char[5] { '1', '2', '3', '4', '5' }; int x = 0; if (arr[0] != '1') x = 1; if (arr[1] != '2') x = 1; if (arr[2] != '3') x = 1; if (arr[3] != '4') x = 1; if (arr[4] != '5') x = 1; return x; } public static bool testMethod() { return (Main_old() == 0); } } class Simple_TestClass_init_init_a_10 { public static int Main_old() { bool[] arr = new bool[5] { true, false, true, false, true }; int x = 0; if (!arr[0]) x = 1; if (arr[1]) x = 1; if (!arr[2]) x = 1; if (arr[3]) x = 1; if (!arr[4]) x = 1; return x; } public static bool testMethod() { return (Main_old() == 0); } } class Simple_TestClass_init_init_b_01 { public static int Main_old() { int[] arr = { 1, 2, 3, 4, 5 }; int x = 0; if (arr[0] != 1) x = 1; if (arr[1] != 2) x = 1; if (arr[2] != 3) x = 1; if (arr[3] != 4) x = 1; if (arr[4] != 5) x = 1; return x; } public static bool testMethod() { return (Main_old() == 0); } } class Simple_TestClass_init_init_b_02 { public static int Main_old() { short[] arr = { 1, 2, 3, 4, 5 }; int x = 0; if (arr[0] != 1) x = 1; if (arr[1] != 2) x = 1; if (arr[2] != 3) x = 1; if (arr[3] != 4) x = 1; if (arr[4] != 5) x = 1; return x; } public static bool testMethod() { return (Main_old() == 0); } } class Simple_TestClass_init_init_b_03 { public static int Main_old() { byte[] arr = { 1, 2, 3, 4, 5 }; int x = 0; if (arr[0] != 1) x = 1; if (arr[1] != 2) x = 1; if (arr[2] != 3) x = 1; if (arr[3] != 4) x = 1; if (arr[4] != 5) x = 1; return x; } public static bool testMethod() { return (Main_old() == 0); } } class Simple_TestClass_init_init_b_04 { public static int Main_old() { long[] arr = { 1, 2, 3, 4, 5 }; int x = 0; if (arr[0] != 1) x = 1; if (arr[1] != 2) x = 1; if (arr[2] != 3) x = 1; if (arr[3] != 4) x = 1; if (arr[4] != 5) x = 1; return x; } public static bool testMethod() { return (Main_old() == 0); } } class Simple_TestClass_init_init_b_05 { public static int Main_old() { double[] arr = { 1.0, 2.0, 3.0, 4.0, 5.0 }; int x = 0; if (arr[0] != 1.0) x = 1; if (arr[1] != 2.0) x = 1; if (arr[2] != 3.0) x = 1; if (arr[3] != 4.0) x = 1; if (arr[4] != 5.0) x = 1; return x; } public static bool testMethod() { return (Main_old() == 0); } } class Simple_TestClass_init_init_b_06 { public static int Main_old() { float[] arr = { 1.0f, 2.0f, 3.0f, 4.0f, 5.0f }; int x = 0; if (arr[0] != 1.0) x = 1; if (arr[1] != 2.0) x = 1; if (arr[2] != 3.0) x = 1; if (arr[3] != 4.0) x = 1; if (arr[4] != 5.0) x = 1; return x; } public static bool testMethod() { return (Main_old() == 0); } } class Simple_TestClass_init_init_b_08 { public static int Main_old() { String[] arr = { "one", "two", "three", "four", "five" }; int x = 0; if (!arr[0].Equals("one")) x = 1; if (!arr[1].Equals("two")) x = 1; if (!arr[2].Equals("three")) x = 1; if (!arr[3].Equals("four")) x = 1; if (!arr[4].Equals("five")) x = 1; return x; } public static bool testMethod() { return (Main_old() == 0); } } class Simple_TestClass_init_init_b_09 { public static int Main_old() { char[] arr = { '1', '2', '3', '4', '5' }; int x = 0; if (arr[0] != '1') x = 1; if (arr[1] != '2') x = 1; if (arr[2] != '3') x = 1; if (arr[3] != '4') x = 1; if (arr[4] != '5') x = 1; return x; } public static bool testMethod() { return (Main_old() == 0); } } class Simple_TestClass_init_init_b_10 { public static int Main_old() { bool[] arr = { true, false, true, false, true }; int x = 0; if (!arr[0]) x = 1; if (arr[1]) x = 1; if (!arr[2]) x = 1; if (arr[3]) x = 1; if (!arr[4]) x = 1; return x; } public static bool testMethod() { return (Main_old() == 0); } } class Simple_TestClass_init_init_c_01 { public static int Main_old() { int[] arr = new int[] { 1, 2, 3, 4, 5 }; int x = 0; if (arr[0] != 1) x = 1; if (arr[1] != 2) x = 1; if (arr[2] != 3) x = 1; if (arr[3] != 4) x = 1; if (arr[4] != 5) x = 1; if (arr.Length != 5) x = 1; return x; } public static bool testMethod() { return (Main_old() == 0); } } class Simple_TestClass_init_init_c_02 { public static int Main_old() { short[] arr = new short[] { 1, 2, 3, 4, 5 }; int x = 0; if (arr[0] != 1) x = 1; if (arr[1] != 2) x = 1; if (arr[2] != 3) x = 1; if (arr[3] != 4) x = 1; if (arr[4] != 5) x = 1; if (arr.Length != 5) x = 1; return x; } public static bool testMethod() { return (Main_old() == 0); } } class Simple_TestClass_init_init_c_03 { public static int Main_old() { byte[] arr = new byte[] { 1, 2, 3, 4, 5 }; int x = 0; if (arr[0] != 1) x = 1; if (arr[1] != 2) x = 1; if (arr[2] != 3) x = 1; if (arr[3] != 4) x = 1; if (arr[4] != 5) x = 1; if (arr.Length != 5) x = 1; return x; } public static bool testMethod() { return (Main_old() == 0); } } class Simple_TestClass_init_init_c_04 { public static int Main_old() { long[] arr = new long[] { 1, 2, 3, 4, 5 }; int x = 0; if (arr[0] != 1) x = 1; if (arr[1] != 2) x = 1; if (arr[2] != 3) x = 1; if (arr[3] != 4) x = 1; if (arr[4] != 5) x = 1; if (arr.Length != 5) x = 1; return x; } public static bool testMethod() { return (Main_old() == 0); } } class Simple_TestClass_init_init_c_05 { public static int Main_old() { double[] arr = new double[] { 1.0, 2.0, 3.0, 4.0, 5.0 }; int x = 0; if (arr[0] != 1.0) x = 1; if (arr[1] != 2.0) x = 1; if (arr[2] != 3.0) x = 1; if (arr[3] != 4.0) x = 1; if (arr[4] != 5.0) x = 1; if (arr.Length != 5) x = 1; return x; } public static bool testMethod() { return (Main_old() == 0); } } class Simple_TestClass_init_init_c_06 { public static int Main_old() { float[] arr = new float[] { 1.0f, 2.0f, 3.0f, 4.0f, 5.0f }; int x = 0; if (arr[0] != 1.0) x = 1; if (arr[1] != 2.0) x = 1; if (arr[2] != 3.0) x = 1; if (arr[3] != 4.0) x = 1; if (arr[4] != 5.0) x = 1; if (arr.Length != 5) x = 1; return x; } public static bool testMethod() { return (Main_old() == 0); } } class Simple_TestClass_init_init_c_08 { public static int Main_old() { String[] arr = new String[] { "one", "two", "three", "four", "five" }; int x = 0; if (!arr[0].Equals("one")) x = 1; if (!arr[1].Equals("two")) x = 1; if (!arr[2].Equals("three")) x = 1; if (!arr[3].Equals("four")) x = 1; if (!arr[4].Equals("five")) x = 1; if (arr.Length != 5) x = 1; return x; } public static bool testMethod() { return (Main_old() == 0); } } class Simple_TestClass_init_init_c_09 { public static int Main_old() { char[] arr = new char[] { '1', '2', '3', '4', '5' }; int x = 0; if (arr[0] != '1') x = 1; if (arr[1] != '2') x = 1; if (arr[2] != '3') x = 1; if (arr[3] != '4') x = 1; if (arr[4] != '5') x = 1; if (arr.Length != 5) x = 1; return x; } public static bool testMethod() { return (Main_old() == 0); } } class Simple_TestClass_init_init_c_10 { public static int Main_old() { bool[] arr = new bool[] { true, false, true, false, true }; int x = 0; if (!arr[0]) x = 1; if (arr[1]) x = 1; if (!arr[2]) x = 1; if (arr[3]) x = 1; if (!arr[4]) x = 1; if (arr.Length != 5) x = 1; return x; } public static bool testMethod() { return (Main_old() == 0); } } class Simple_TestClass_init_init_d_01 { public static int Main_old() { int[] arr; arr = new int[5] { 1, 2, 3, 4, 5 }; int x = 0; if (arr[0] != 1) x = 1; if (arr[1] != 2) x = 1; if (arr[2] != 3) x = 1; if (arr[3] != 4) x = 1; if (arr[4] != 5) x = 1; return x; } public static bool testMethod() { return (Main_old() == 0); } } class Simple_TestClass_init_init_d_02 { public static int Main_old() { short[] arr; arr = new short[5] { 1, 2, 3, 4, 5 }; int x = 0; if (arr[0] != 1) x = 1; if (arr[1] != 2) x = 1; if (arr[2] != 3) x = 1; if (arr[3] != 4) x = 1; if (arr[4] != 5) x = 1; return x; } public static bool testMethod() { return (Main_old() == 0); } } class Simple_TestClass_init_init_d_03 { public static int Main_old() { byte[] arr; arr = new byte[5] { 1, 2, 3, 4, 5 }; int x = 0; if (arr[0] != 1) x = 1; if (arr[1] != 2) x = 1; if (arr[2] != 3) x = 1; if (arr[3] != 4) x = 1; if (arr[4] != 5) x = 1; return x; } public static bool testMethod() { return (Main_old() == 0); } } class Simple_TestClass_init_init_d_04 { public static int Main_old() { long[] arr; arr = new long[5] { 1, 2, 3, 4, 5 }; int x = 0; if (arr[0] != 1) x = 1; if (arr[1] != 2) x = 1; if (arr[2] != 3) x = 1; if (arr[3] != 4) x = 1; if (arr[4] != 5) x = 1; return x; } public static bool testMethod() { return (Main_old() == 0); } } class Simple_TestClass_init_init_d_05 { public static int Main_old() { double[] arr; arr = new double[5] { 1.0, 2.0, 3.0, 4.0, 5.0 }; int x = 0; if (arr[0] != 1.0) x = 1; if (arr[1] != 2.0) x = 1; if (arr[2] != 3.0) x = 1; if (arr[3] != 4.0) x = 1; if (arr[4] != 5.0) x = 1; return x; } public static bool testMethod() { return (Main_old() == 0); } } class Simple_TestClass_init_init_d_06 { public static int Main_old() { float[] arr; arr = new float[5] { 1.0f, 2.0f, 3.0f, 4.0f, 5.0f }; int x = 0; if (arr[0] != 1.0) x = 1; if (arr[1] != 2.0) x = 1; if (arr[2] != 3.0) x = 1; if (arr[3] != 4.0) x = 1; if (arr[4] != 5.0) x = 1; return x; } public static bool testMethod() { return (Main_old() == 0); } } class Simple_TestClass_init_init_d_08 { public static int Main_old() { String[] arr; arr = new String[5] { "one", "two", "three", "four", "five" }; int x = 0; if (!arr[0].Equals("one")) x = 1; if (!arr[1].Equals("two")) x = 1; if (!arr[2].Equals("three")) x = 1; if (!arr[3].Equals("four")) x = 1; if (!arr[4].Equals("five")) x = 1; return x; } public static bool testMethod() { return (Main_old() == 0); } } class Simple_TestClass_init_init_d_09 { public static int Main_old() { char[] arr; arr = new char[5] { '1', '2', '3', '4', '5' }; int x = 0; if (arr[0] != '1') x = 1; if (arr[1] != '2') x = 1; if (arr[2] != '3') x = 1; if (arr[3] != '4') x = 1; if (arr[4] != '5') x = 1; return x; } public static bool testMethod() { return (Main_old() == 0); } } class Simple_TestClass_init_init_d_10 { public static int Main_old() { bool[] arr; arr = new bool[5] { true, false, true, false, true }; int x = 0; if (!arr[0]) x = 1; if (arr[1]) x = 1; if (!arr[2]) x = 1; if (arr[3]) x = 1; if (!arr[4]) x = 1; return x; } public static bool testMethod() { return (Main_old() == 0); } } class Simple_TestClass_init_init_e_01 { public static int Main_old() { int[] arr; arr = new int[] { 1, 2, 3, 4, 5 }; int x = 0; if (arr[0] != 1) x = 1; if (arr[1] != 2) x = 1; if (arr[2] != 3) x = 1; if (arr[3] != 4) x = 1; if (arr[4] != 5) x = 1; if (arr.Length != 5) x = 1; return x; } public static bool testMethod() { return (Main_old() == 0); } } class Simple_TestClass_init_init_e_02 { public static int Main_old() { short[] arr; arr = new short[] { 1, 2, 3, 4, 5 }; int x = 0; if (arr[0] != 1) x = 1; if (arr[1] != 2) x = 1; if (arr[2] != 3) x = 1; if (arr[3] != 4) x = 1; if (arr[4] != 5) x = 1; if (arr.Length != 5) x = 1; return x; } public static bool testMethod() { return (Main_old() == 0); } } class Simple_TestClass_init_init_e_03 { public static int Main_old() { byte[] arr; arr = new byte[] { 1, 2, 3, 4, 5 }; int x = 0; if (arr[0] != 1) x = 1; if (arr[1] != 2) x = 1; if (arr[2] != 3) x = 1; if (arr[3] != 4) x = 1; if (arr[4] != 5) x = 1; if (arr.Length != 5) x = 1; return x; } public static bool testMethod() { return (Main_old() == 0); } } class Simple_TestClass_init_init_e_04 { public static int Main_old() { long[] arr; arr = new long[] { 1, 2, 3, 4, 5 }; int x = 0; if (arr[0] != 1) x = 1; if (arr[1] != 2) x = 1; if (arr[2] != 3) x = 1; if (arr[3] != 4) x = 1; if (arr[4] != 5) x = 1; if (arr.Length != 5) x = 1; return x; } public static bool testMethod() { return (Main_old() == 0); } } class Simple_TestClass_init_init_e_05 { public static int Main_old() { double[] arr; arr = new double[] { 1.0, 2.0, 3.0, 4.0, 5.0 }; int x = 0; if (arr[0] != 1.0) x = 1; if (arr[1] != 2.0) x = 1; if (arr[2] != 3.0) x = 1; if (arr[3] != 4.0) x = 1; if (arr[4] != 5.0) x = 1; if (arr.Length != 5) x = 1; return x; } public static bool testMethod() { return (Main_old() == 0); } } class Simple_TestClass_init_init_e_06 { public static int Main_old() { float[] arr; arr = new float[] { 1.0f, 2.0f, 3.0f, 4.0f, 5.0f }; int x = 0; if (arr[0] != 1.0) x = 1; if (arr[1] != 2.0) x = 1; if (arr[2] != 3.0) x = 1; if (arr[3] != 4.0) x = 1; if (arr[4] != 5.0) x = 1; if (arr.Length != 5) x = 1; return x; } public static bool testMethod() { return (Main_old() == 0); } } class Simple_TestClass_init_init_e_08 { public static int Main_old() { String[] arr; arr = new String[] { "one", "two", "three", "four", "five" }; int x = 0; if (!arr[0].Equals("one")) x = 1; if (!arr[1].Equals("two")) x = 1; if (!arr[2].Equals("three")) x = 1; if (!arr[3].Equals("four")) x = 1; if (!arr[4].Equals("five")) x = 1; if (arr.Length != 5) x = 1; return x; } public static bool testMethod() { return (Main_old() == 0); } } class Simple_TestClass_init_init_e_09 { public static int Main_old() { char[] arr; arr = new char[] { '1', '2', '3', '4', '5' }; int x = 0; if (arr[0] != '1') x = 1; if (arr[1] != '2') x = 1; if (arr[2] != '3') x = 1; if (arr[3] != '4') x = 1; if (arr[4] != '5') x = 1; if (arr.Length != 5) x = 1; return x; } public static bool testMethod() { return (Main_old() == 0); } } class Simple_TestClass_init_init_e_10 { public static int Main_old() { bool[] arr; arr = new bool[] { true, false, true, false, true }; int x = 0; if (!arr[0]) x = 1; if (arr[1]) x = 1; if (!arr[2]) x = 1; if (arr[3]) x = 1; if (!arr[4]) x = 1; if (arr.Length != 5) x = 1; return x; } public static bool testMethod() { return (Main_old() == 0); } } class Simple_TestClass_init_syntax_09 { public static int Main_old() { int[] arr = new int[5] { 1, 2, 3, 4, 5 }; int[] arr2 = new int[5] { 1, /* test comment */ 2, 3, 4, 5 }; return 0; } public static bool testMethod() { return (Main_old() == 0); } } class Simple_TestClass_init_syntax_11 { public static int Main_old() { int[] arr = new int[] { }; if (arr.Length == 0) return 0; else return 1; } public static bool testMethod() { return (Main_old() == 0); } } class Simple_TestClass_init_syntax_12 { public static int Main_old() { int[] arr = new int[0] { }; if (arr.Length == 0) return 0; else return 1; } public static bool testMethod() { return (Main_old() == 0); } } class Simple_TestClass_init_decl_02 { const int myLength = 5; public static int Main_old() { int[] arr = new int[myLength] { 1, 2, 3, 4, 5 }; int x = 0; if (arr[0] != 1) x = 1; if (arr[1] != 2) x = 1; if (arr[2] != 3) x = 1; if (arr[3] != 4) x = 1; if (arr[4] != 5) x = 1; return x; } public static bool testMethod() { return (Main_old() == 0); } } class Simple_TestClass_init_decl_03 { const short myLength = 5; public static int Main_old() { int[] arr = new int[myLength] { 1, 2, 3, 4, 5 }; int x = 0; if (arr[0] != 1) x = 1; if (arr[1] != 2) x = 1; if (arr[2] != 3) x = 1; if (arr[3] != 4) x = 1; if (arr[4] != 5) x = 1; return x; } public static bool testMethod() { return (Main_old() == 0); } } class Simple_TestClass_init_decl_04 { const byte myLength = 5; public static int Main_old() { int[] arr = new int[myLength] { 1, 2, 3, 4, 5 }; int x = 0; if (arr[0] != 1) x = 1; if (arr[1] != 2) x = 1; if (arr[2] != 3) x = 1; if (arr[3] != 4) x = 1; if (arr[4] != 5) x = 1; return x; } public static bool testMethod() { return (Main_old() == 0); } } class Simple_TestClass_init_decl_05 { const long myLength = 5; public static int Main_old() { int[] arr = new int[(int)myLength] { 1, 2, 3, 4, 5 }; int x = 0; if (arr[0] != 1) x = 1; if (arr[1] != 2) x = 1; if (arr[2] != 3) x = 1; if (arr[3] != 4) x = 1; if (arr[4] != 5) x = 1; return x; } public static bool testMethod() { return (Main_old() == 0); } } class Simple_TestClass_init_shorthand_01 { static int[] a = { 1, 2, 3, 4 }; public static int Main_old() { for (int i = 0; i < 4; i++) { int[] b = { 1, 2, 3, 4 }; Log.Comment(a[i].ToString()); Log.Comment(b[i].ToString()); } return 0; } public static bool testMethod() { return (Main_old() == 0); } } class Simple_TestClass_init_constinit_01 { int[] TestArray1 = new int[] { 1, 2, 3, 4 }; static int Main_old() { int[] TestArray2 = new int[] { 1, 2, 3, 4 }; return 0; } public static bool testMethod() { return (Main_old() == 0); } } class Simple_TestClass_init_constinit_02 { int a = 1; int b = 2; int c = 3; int d = 4; void MyMethod() { int[] TestArray = new int[] { a, b, c, d }; } static int Main_old() { Simple_TestClass_init_constinit_02 a = new Simple_TestClass_init_constinit_02(); a.MyMethod(); return 0; } public static bool testMethod() { return (Main_old() == 0); } } class Simple_TestClass_init_constinit_03 { int a = 1; int b = 2; void MyMethod() { int[] TestArray = new int[] { 1, a, 2, b }; } static int Main_old() { Simple_TestClass_init_constinit_03 a = new Simple_TestClass_init_constinit_03(); a.MyMethod(); return 0; } public static bool testMethod() { return (Main_old() == 0); } } class Simple_TestClass_acc_iter_length_01 { public static int Main_old() { int[] arr1 = new int[10]; double[] arr2 = new double[15]; float[] arr3; arr3 = new float[1]; char[] arr4; arr4 = new char[0]; int x = 0; if (arr1.Length != 10) x = 1; if (arr2.Length != 15) x = 1; if (arr3.Length != 1) x = 1; if (arr4.Length != 0) x = 1; return x; } public static bool testMethod() { return (Main_old() == 0); } } class Simple_TestClass_acc_iter_bounds_01 { public static int Main_old() { int[] arr = new int[10]; arr[0] = 5; if (arr[0] == 5) return 0; else return 1; } public static bool testMethod() { return (Main_old() == 0); } } class Simple_TestClass_acc_iter_bounds_02 { public static int Main_old() { int[] arr = new int[10]; arr[9] = 5; if (arr[9] == 5) return 0; else return 1; } public static bool testMethod() { return (Main_old() == 0); } } class Simple_TestClass_acc_iter_bounds_03 { public static int Main_old() { int[] arr = new int[10]; try { arr[-1] = 5; } catch (System.Exception) { return 0; } return 1; } public static bool testMethod() { return (Main_old() == 0); } } class Simple_TestClass_acc_iter_bounds_04 { public static int Main_old() { int[] arr = new int[10]; try { arr[10] = 5; } catch (System.Exception) { return 0; } return 1; } public static bool testMethod() { return (Main_old() == 0); } } class Simple_TestClass_acc_iter_idxtype_a_01 { public static int Main_old() { int[] arr = new int[10]; arr[5] = 100; int idx = 5; if (arr[idx] == 100) return 0; else return 1; } public static bool testMethod() { return (Main_old() == 0); } } class Simple_TestClass_acc_iter_idxtype_a_02 { public static int Main_old() { int[] arr = new int[10]; arr[5] = 100; short idx = 5; if (arr[idx] == 100) return 0; else return 1; } public static bool testMethod() { return (Main_old() == 0); } } class Simple_TestClass_acc_iter_idxtype_a_03 { public static int Main_old() { int[] arr = new int[10]; arr[5] = 100; byte idx = 5; if (arr[idx] == 100) return 0; else return 1; } public static bool testMethod() { return (Main_old() == 0); } } class Simple_TestClass_acc_iter_idxtype_a_04 { public static int Main_old() { int[] arr = new int[10]; arr[5] = 100; char idx = (char)5; if (arr[idx] == 100) return 0; else return 1; } public static bool testMethod() { return (Main_old() == 0); } } class Simple_TestClass_acc_iter_idxtype_a_06 { public static int Main_old() { int[] arr = new int[10]; arr[5] = 100; long idx = 5L; if (arr[idx] == 100) return 0; else return 1; } public static bool testMethod() { return (Main_old() == 0); } } class Simple_TestClass_acc_iter_idxtype_b_01 { public static int Main_old() { int[] arr = new int[10]; arr[5] = 100; if (arr[5] == 100) return 0; else return 1; } public static bool testMethod() { return (Main_old() == 0); } } class Simple_TestClass_acc_iter_idxtype_b_02 { public static int Main_old() { int[] arr = new int[10]; arr[5] = 100; if (arr[(short)5] == 100) return 0; else return 1; } public static bool testMethod() { return (Main_old() == 0); } } class Simple_TestClass_acc_iter_idxtype_b_03 { public static int Main_old() { int[] arr = new int[10]; arr[5] = 100; if (arr[(byte)5] == 100) return 0; else return 1; } public static bool testMethod() { return (Main_old() == 0); } } class Simple_TestClass_acc_iter_idxtype_b_04 { public static int Main_old() { int[] arr = new int[35]; arr[32] = 100; if (arr[' '] == 100) return 0; else return 1; } public static bool testMethod() { return (Main_old() == 0); } } class Simple_TestClass_acc_iter_idxtype_b_06 { public static int Main_old() { int[] arr = new int[10]; arr[5] = 100; if (arr[5L] == 100) return 0; else return 1; } public static bool testMethod() { return (Main_old() == 0); } } class Simple_TestClass_acc_iter_iter_01 { public static int Main_old() { int[] arr = new int[10]; for (int x = 0; x < arr.Length; x++) { arr[x] = x; } int result = 0; for (int y = 0; y < arr.Length; y++) { if (arr[y] != y) result = 1; } return result; } public static bool testMethod() { return (Main_old() == 0); } } class Simple_TestClass_acc_iter_iter_02 { public static int Main_old() { char[] arr = new char[10]; arr[0] = 'L'; arr[1] = 'a'; arr[2] = 'n'; arr[3] = 'g'; arr[4] = 'u'; arr[5] = 'a'; arr[6] = 'g'; arr[7] = 'e'; int result = 0; if (arr[0] != 'L') result = 1; if (arr[1] != 'a') result = 1; if (arr[2] != 'n') result = 1; if (arr[3] != 'g') result = 1; if (arr[4] != 'u') result = 1; if (arr[5] != 'a') result = 1; if (arr[6] != 'g') result = 1; if (arr[7] != 'e') result = 1; return result; } public static bool testMethod() { return (Main_old() == 0); } } class Simple_TestClass_assign_smpass_a_01 { public static int Main_old() { int[] arr = new int[5]; arr[3] = 5; return 0; } public static bool testMethod() { return (Main_old() == 0); } } class Simple_TestClass_assign_smpass_a_02 { public static int Main_old() { byte[] arr = new byte[5]; arr[3] = (byte)5; return 0; } public static bool testMethod() { return (Main_old() == 0); } } class Simple_TestClass_assign_smpass_a_03 { public static int Main_old() { short[] arr = new short[5]; arr[3] = (short)5; return 0; } public static bool testMethod() { return (Main_old() == 0); } } class Simple_TestClass_assign_smpass_a_04 { public static int Main_old() { long[] arr = new long[5]; arr[3] = (long)5; return 0; } public static bool testMethod() { return (Main_old() == 0); } } class Simple_TestClass_assign_smpass_a_05 { public static int Main_old() { char[] arr = new char[5]; arr[3] = 'c'; return 0; } public static bool testMethod() { return (Main_old() == 0); } } class Simple_TestClass_assign_smpass_a_06 { public static int Main_old() { double[] arr = new double[5]; arr[3] = 5.42; return 0; } public static bool testMethod() { return (Main_old() == 0); } } class Simple_TestClass_assign_smpass_a_07 { public static int Main_old() { float[] arr = new float[5]; arr[3] = (float)1.00; return 0; } public static bool testMethod() { return (Main_old() == 0); } } class Simple_TestClass_assign_smpass_a_08 { public static int Main_old() { double[] arr = new double[5]; arr[3] = (double)1.00; return 0; } public static bool testMethod() { return (Main_old() == 0); } } class Simple_TestClass_assign_smpass_a_09 { public static int Main_old() { bool[] arr = new bool[5]; arr[3] = true; return 0; } public static bool testMethod() { return (Main_old() == 0); } } class Simple_TestClass_assign_smpass_b_01 { public static int Main_old() { int[] arr = new int[5]; int x = 5; arr[3] = x; return 0; } public static bool testMethod() { return (Main_old() == 0); } } class Simple_TestClass_assign_smpass_b_02 { public static int Main_old() { byte[] arr = new byte[5]; byte x = 5; arr[3] = x; return 0; } public static bool testMethod() { return (Main_old() == 0); } } class Simple_TestClass_assign_smpass_b_03 { public static int Main_old() { short[] arr = new short[5]; short x = 5; arr[3] = x; return 0; } public static bool testMethod() { return (Main_old() == 0); } } class Simple_TestClass_assign_smpass_b_04 { public static int Main_old() { long[] arr = new long[5]; long x = 5; arr[3] = x; return 0; } public static bool testMethod() { return (Main_old() == 0); } } class Simple_TestClass_assign_smpass_b_05 { public static int Main_old() { char[] arr = new char[5]; char x = 'c'; arr[3] = x; return 0; } public static bool testMethod() { return (Main_old() == 0); } } class Simple_TestClass_assign_smpass_b_06 { public static int Main_old() { double[] arr = new double[5]; double x = 5.42; arr[3] = x; return 0; } public static bool testMethod() { return (Main_old() == 0); } } class Simple_TestClass_assign_smpass_b_07 { public static int Main_old() { float[] arr = new float[5]; float x = (float)1.00; arr[3] = x; return 0; } public static bool testMethod() { return (Main_old() == 0); } } class Simple_TestClass_assign_smpass_b_08 { public static int Main_old() { double[] arr = new double[5]; double x = (double)1.00; arr[3] = x; return 0; } public static bool testMethod() { return (Main_old() == 0); } } class Simple_TestClass_assign_smpass_b_09 { public static int Main_old() { bool[] arr = new bool[5]; bool x = true; arr[3] = x; return 0; } public static bool testMethod() { return (Main_old() == 0); } } class Simple_TestClass_assign_badcode_01 { public static int Main_old() { int[] arr = new int[5] { 1, 2, 3, 4, 5 }; if (arr[2] != 3) return 1; arr = null; try { if (arr[2] == 3) return 1; } catch (System.Exception) { return 0; } return 1; } public static bool testMethod() { return (Main_old() == 0); } } class Simple_TestClass_assign_badcode_03 { public static int Main_old() { int[] arr1 = new int[5] { 1, 2, 3, 4, 5 }; int[] arr2 = new int[3] { 6, 7, 8 }; int result = 0; // Verify lengths are different if (arr1.Length == arr2.Length) result = 1; // assign the small array to the larger array // This is actually just making arr1 point to arr2, NOT copying arr1 = arr2; // verify the values are correct if (arr1[0] != 6) result = 1; if (arr1[1] != 7) result = 1; if (arr1[2] != 8) result = 1; if (arr1.Length != arr2.Length) result = 1; return result; } public static bool testMethod() { return (Main_old() == 0); } } class Simple_TestClass_assign_badcode_04 { public static int Main_old() { int[] arr1 = new int[3] { 6, 7, 8 }; int[] arr2 = new int[5] { 1, 2, 3, 4, 5 }; int result = 0; // Verify lengths are different if (arr1.Length == arr2.Length) result = 1; // assign the larger array to the smaller array // This is actually just making arr1 point to arr2, NOT copying arr1 = arr2; // verify the values are correct if (arr1[0] != 1) result = 1; if (arr1[1] != 2) result = 1; if (arr1[2] != 3) result = 1; if (arr1.Length != arr2.Length) result = 1; return result; } public static bool testMethod() { return (Main_old() == 0); } } class Simple_TestClass_assign_element_01 { public static int Main_old() { int[] arr = new int[5] { 1, 2, 3, 4, 5 }; arr[2] = arr[4]; if (arr[2] == 5) return 0; return 1; } public static bool testMethod() { return (Main_old() == 0); } } class Simple_TestClass_assign_element_02 { public static int Main_old() { int[] arr1 = new int[5] { 1, 2, 3, 4, 5 }; int[] arr2 = new int[5] { 6, 7, 8, 9, 10 }; arr1[2] = arr2[4]; if (arr1[2] == 10) return 0; return 1; } public static bool testMethod() { return (Main_old() == 0); } } class Simple_TestClass_assign_argpass_01 { public static int ElementTaker(int val) { return val; } public static int Main_old() { int[] arr = new int[5] { 1, 2, 3, 4, 5 }; Log.Comment(ElementTaker(arr[2]).ToString()); return 0; } public static bool testMethod() { return (Main_old() == 0); } } class Simple_TestClass_assign_argpass_02 { public static int ElementTaker(ref int val) { val += 5; return val; } public static int Main_old() { int[] arr = new int[5] { 1, 2, 3, 4, 5 }; Log.Comment(ElementTaker(ref arr[2]).ToString()); if (arr[2] != 8) return 1; return 0; } public static bool testMethod() { return (Main_old() == 0); } } class Simple_TestClass_assign_argpass_03 { public static int ElementTaker(out int val) { val = 5; return val; } public static int Main_old() { int[] arr = new int[5] { 1, 2, 3, 4, 5 }; Log.Comment(ElementTaker(out arr[2]).ToString()); if (arr[2] != 5) return 1; return 0; } public static bool testMethod() { return (Main_old() == 0); } } class Simple_TestClass_object_sysarr_01 { public static int Main_old() { int[] arr = new int[5] { 1, 2, 3, 4, 5 }; int result = 0; for (int x = 0; x < arr.Length; x++) if (arr[x] != x + 1) result = 1; Array.Clear(arr, 0, 5); for (int x = 0; x < arr.Length; x++) if (arr[x] != 0) result = 1; return result; } public static bool testMethod() { return (Main_old() == 0); } } class Simple_TestClass_object_sysarr_02 { public static int Main_old() { int result = 0; int[] arr1 = new int[5] { 1, 2, 3, 4, 5 }; if (arr1.Length != 5) result = 1; int[] arr2 = new int[] { 1, 2, 3, 4, 5 }; if (arr2.Length != 5) result = 1; int[] arr3 = new int[] { }; if (arr3.Length != 0) result = 1; int[] arr4 = new int[0]; if (arr4.Length != 0) result = 1; return result; } public static bool testMethod() { return (Main_old() == 0); } } } } ================================================ FILE: Zelig/Zelig/Test/RunTime/NETMF/mscorlib/attributes/AttributesTests1.cs ================================================ //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // Copyright (c) Microsoft Corporation. All rights reserved. ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////#undef DEBUG #undef DEBUG using System; using System.Reflection; using Microsoft.SPOT.Platform.Test; using System.Diagnostics; using System.Runtime.InteropServices; namespace Microsoft.SPOT.Platform.Tests { public class AttributesTests1 : IMFTestInterface { [SetUp] public InitializeResult Initialize() { Log.Comment("Adding set up for the tests"); Log.Comment("This tests the syntax and use of user created and included Attributes"); // Add your functionality here. return InitializeResult.ReadyToGo; } [TearDown] public void CleanUp() { Log.Comment("Cleaning up after the tests"); } //Attributes Test methods //The following tests were ported from folder current\test\cases\client\CLR\Conformance\17_Attributes //attrib000,attrib000_2,attrib001,attrib002,attrib017_7,attrib017_7a,attrib017_8c,attrib017_9b,attrib021_2,attrib021_4,attrib029_8,attrib029_9,attrib029_a,attrib029_b,attrib031_4,attrib032_2,attrib033_2,attrib035_12,attrib035_22,attrib036_1,attrib038_1,attrib047_4,attrib047_5,attrib049_4,attrib054,attrib062 //Test Case Calls [TestMethod] public MFTestResults Attrib_attrib000_Test() { Log.Comment("Declare a basic attribute class, example from C# Language reference, 1.1"); if (Attrib_TestClass_attrib000.testMethod()) { return MFTestResults.Pass; } return MFTestResults.Fail; } [TestMethod] public MFTestResults Attrib_attrib000_2_Test() { Log.Comment("17.1 - A non-abstract attribute class must have public accessibility."); if (Attrib_TestClass_attrib000_2.testMethod()) { return MFTestResults.Pass; } return MFTestResults.Fail; } [TestMethod] public MFTestResults Attrib_attrib001_Test() { Log.Comment("Declare a basic attribute class, example from C# Language reference, 1.1"); if (Attrib_TestClass_attrib001.testMethod()) { return MFTestResults.Pass; } return MFTestResults.Fail; } [TestMethod] public MFTestResults Attrib_attrib002_Test() { Log.Comment("Declare a basic attribute class, example from C# Language reference, 1.1"); if (Attrib_TestClass_attrib002.testMethod()) { return MFTestResults.Pass; } return MFTestResults.Fail; } [TestMethod] public MFTestResults Attrib_attrib017_7a_Test() { Log.Comment("17.4.5 test of conditional when DEBUG is undefined"); if (Attrib_TestClass_attrib017_7a.testMethod()) { return MFTestResults.Pass; } return MFTestResults.Fail; } [TestMethod] public MFTestResults Attrib_attrib017_8c_Test() { Log.Comment("17.4.5 - Example from CLR"); if (Attrib_TestClass_attrib017_8c.testMethod()) { return MFTestResults.Pass; } return MFTestResults.Fail; } [TestMethod] public MFTestResults Attrib_attrib021_2_Test() { Log.Comment("CLR 17.4.9 - guid Attribute"); if (Attrib_TestClass_attrib021_2.testMethod()) { return MFTestResults.Pass; } return MFTestResults.Fail; } [TestMethod] public MFTestResults Attrib_attrib021_4_Test() { Log.Comment("CLR 17.4.9 - guid Attribute"); if (Attrib_TestClass_attrib021_4.testMethod()) { return MFTestResults.Pass; } return MFTestResults.Fail; } [TestMethod] public MFTestResults Attrib_attrib029_8_Test() { Log.Comment("CLR 17.4.19 - obsolete"); Log.Comment("obsolete can be used on any declaration, but should be able to call"); Log.Comment("obsolete methods"); if (Attrib_TestClass_attrib029_8.testMethod()) { return MFTestResults.Pass; } return MFTestResults.Fail; } [TestMethod] public MFTestResults Attrib_attrib029_9_Test() { Log.Comment("CLR 17.4.19 - obsolete"); Log.Comment("obsolete can be used on any declaration, but should be able to call"); Log.Comment("obsolete methods"); if (Attrib_TestClass_attrib029_9.testMethod()) { return MFTestResults.Pass; } return MFTestResults.Fail; } [TestMethod] public MFTestResults Attrib_attrib029_a_Test() { Log.Comment("CLR 17.4.19 - obsolete"); Log.Comment("obsolete can be used on any declaration, but should be able to call"); Log.Comment("obsolete methods"); if (Attrib_TestClass_attrib029_a.testMethod()) { return MFTestResults.Pass; } return MFTestResults.Fail; } [TestMethod] public MFTestResults Attrib_attrib029_b_Test() { Log.Comment("CLR 17.4.19 - obsolete"); Log.Comment("obsolete can be used on any declaration, but overrides should generate warning"); if (Attrib_TestClass_attrib029_b.testMethod()) { return MFTestResults.Pass; } return MFTestResults.Fail; } [TestMethod] public MFTestResults Attrib_attrib031_4_Test() { Log.Comment("CLR 17.4.22 - serializable Attribute"); if (Attrib_TestClass_attrib031_4.testMethod()) { return MFTestResults.Pass; } return MFTestResults.Fail; } [TestMethod] public MFTestResults Attrib_attrib032_2_Test() { Log.Comment("CLR 17.4.23 - structlayout Attribute"); if (Attrib_TestClass_attrib032_2.testMethod()) { return MFTestResults.Pass; } return MFTestResults.Fail; } [TestMethod] public MFTestResults Attrib_attrib033_2_Test() { Log.Comment("Attribute usage is inherited."); if (Attrib_TestClass_attrib033_2.testMethod()) { return MFTestResults.Pass; } return MFTestResults.Fail; } /* * These tests are excluded because they require parts of System.Reflection that are not supported in the MF * [TestMethod] public MFTestResults Attrib_attrib035_12_Test() { Log.Comment("Make sure that assembly level GuidAttribute appears in assembly"); if (Attrib_TestClass_attrib035_12.testMethod()) { return MFTestResults.Pass; } return MFTestResults.Fail; } [TestMethod] public MFTestResults Attrib_attrib035_22_Test() { Log.Comment("Make sure that assembly level GuidAttribute appears in assembly"); if (Attrib_TestClass_attrib035_22.testMethod()) { return MFTestResults.Pass; } return MFTestResults.Fail; } */ [TestMethod] public MFTestResults Attrib_attrib036_1_Test() { Log.Comment("17.1 - A top-level, non-abstract attribute class must have public or"); Log.Comment("internal accessibility. Nested attribute classes may also be private,"); Log.Comment("protected, or protected internal."); if (Attrib_TestClass_attrib036_1.testMethod()) { return MFTestResults.Pass; } return MFTestResults.Fail; } [TestMethod] public MFTestResults Attrib_attrib038_1_Test() { Log.Comment("Verify params keyword"); if (Attrib_TestClass_attrib038_1.testMethod()) { return MFTestResults.Pass; } return MFTestResults.Fail; } [TestMethod] public MFTestResults Attrib_attrib047_4_Test() { Log.Comment(" Make sure that ObsoleteAttribute works with following targets"); Log.Comment("[AttributeUsage(AttributeTargets.Class | AttributeTargets.Struct |"); Log.Comment(" AttributeTargets.Enum | AttributeTargets.Constructor |"); Log.Comment(" AttributeTargets.Method | AttributeTargets.Property |"); Log.Comment(" AttributeTargets.Field | AttributeTargets.Event |"); Log.Comment(" AttributeTargets.Interface | AttributeTargets.Delegate)]"); if (Attrib_TestClass_attrib047_4.testMethod()) { return MFTestResults.Pass; } return MFTestResults.Fail; } [TestMethod] public MFTestResults Attrib_attrib047_5_Test() { Log.Comment(" Make sure that ObsoleteAttribute works with following targets"); Log.Comment("[AttributeUsage(AttributeTargets.Class | AttributeTargets.Struct |"); Log.Comment(" AttributeTargets.Enum | AttributeTargets.Constructor |"); Log.Comment(" AttributeTargets.Method | AttributeTargets.Property |"); Log.Comment(" AttributeTargets.Field | AttributeTargets.Event |"); Log.Comment(" AttributeTargets.Interface | AttributeTargets.Delegate)]"); if (Attrib_TestClass_attrib047_5.testMethod()) { return MFTestResults.Pass; } return MFTestResults.Fail; } [TestMethod] public MFTestResults Attrib_attrib049_4_Test() { Log.Comment("Bad named attribute argumements should be an error"); if (Attrib_TestClass_attrib049_4.testMethod()) { return MFTestResults.Pass; } return MFTestResults.Fail; } [TestMethod] public MFTestResults Attrib_attrib054_Test() { Log.Comment("ECMA complaince: support special attribute name binding rules with @ identifier"); Log.Comment("explictly specify attribute location with @"); if (Attrib_TestClass_attrib054.testMethod()) { return MFTestResults.Pass; } return MFTestResults.Fail; } [TestMethod] public MFTestResults Attrib_attrib062_Test() { Log.Comment("Declare a derived attribute after declaring its base."); Log.Comment("Attributes can inherit from other attirubtes that have not yet been declared as long as there are no"); Log.Comment("circular dependencies."); if (Attrib_TestClass_attrib062.testMethod()) { return MFTestResults.Pass; } return MFTestResults.Fail; } //Compiled Test Cases [AttributeUsage(AttributeTargets.Class)] public class Attrib_TestClass_attrib000_A : Attribute { } public class Attrib_TestClass_attrib000 { public static int Main_old() { return 0; } public static bool testMethod() { return (Main_old() == 0); } } [AttributeUsage(AttributeTargets.Class)] abstract class Attrib_TestClass_attrib000_2_C1 : Attribute { public abstract void mf(); } public class Attrib_TestClass_attrib000_2 { public static int Main_old() { return 0; } public static bool testMethod() { return (Main_old() == 0); } } [AttributeUsage(AttributeTargets.Struct | AttributeTargets.Class | AttributeTargets.Interface)] public class Attrib_TestClass_attrib001_C : Attribute { public int Name; public Attrib_TestClass_attrib001_C(int sName) { Name = sName; } [Attrib_TestClass_attrib001_C(5)] class Attrib_TestClass_attrib001_C1 { } [Attrib_TestClass_attrib001_C(6)] interface Attrib_TestClass_attrib001_I1 { } [Attrib_TestClass_attrib001_C(7)] struct Attrib_TestClass_attrib001_S1 { } } public class Attrib_TestClass_attrib001 { public static int Main_old() { return 0; } public static bool testMethod() { return (Main_old() == 0); } } [AttributeUsage(AttributeTargets.Class)] public class Attrib_TestClass_attrib002 : Attribute { public static int Main_old() { return 0; } public static bool testMethod() { return (Main_old() == 0); } } public class Attrib_TestClass_attrib017_7a_C1 { [Conditional("DEBUG")] public static void M() { Attrib_TestClass_attrib017_7a.retval++; Log.Comment("Executed Attrib_TestClass_attrib017_7a_C1.M"); } } public class Attrib_TestClass_attrib017_7a_C2 { public static void Test() { Attrib_TestClass_attrib017_7a_C1.M(); } } public class Attrib_TestClass_attrib017_7a { public static int retval = 0; public static int Main_old() { Attrib_TestClass_attrib017_7a_C2.Test(); if (retval == 0) Log.Comment("PASS"); else Log.Comment("FAIL"); return retval; } public static bool testMethod() { return (Main_old() == 0); } } class Attrib_TestClass_attrib017_8c_C1 { [Conditional("DEBUG")] public static void C1() { Log.Comment("Executed Class1.C1()"); } } class Attrib_TestClass_attrib017_8c_C2 { public static void C2() { Log.Comment("Executed Class2.C2()"); Attrib_TestClass_attrib017_8c_C1.C1(); // C1 is called } } class Attrib_TestClass_attrib017_8c_C3 { public static void C4() { Log.Comment("Executed Attrib_TestClass_attrib017_8c_C3.C4()"); Attrib_TestClass_attrib017_8c_C1.C1(); } } public class Attrib_TestClass_attrib017_8c { public static int Main_old() { Attrib_TestClass_attrib017_8c_C3.C4(); Attrib_TestClass_attrib017_8c_C2.C2(); return 0; } public static bool testMethod() { return (Main_old() == 0); } } [Guid("00020810-0000-0000-C000-000000000046")] class Attrib_TestClass_attrib021_2_C1 { } public class Attrib_TestClass_attrib021_2 { public static int Main_old() { Attrib_TestClass_attrib021_2_C1 w = new Attrib_TestClass_attrib021_2_C1(); // Creates an Excel worksheet return 0; } public static bool testMethod() { return (Main_old() == 0); } } [GuidAttribute("00020810-0000-0000-C000-000000000046")] struct Attrib_TestClass_attrib021_4_C1 { } public class Attrib_TestClass_attrib021_4 { public static int Main_old() { Attrib_TestClass_attrib021_4_C1 w = new Attrib_TestClass_attrib021_4_C1(); // Creates an Excel worksheet return 0; } public static bool testMethod() { return (Main_old() == 0); } } public class Attrib_TestClass_attrib029_8_C1 { public Attrib_TestClass_attrib029_8_C1() { _i = -1; } private int _i; [Obsolete] public int i { get { return _i; } set { _i = value; Attrib_TestClass_attrib029_8_S1 s1 = new Attrib_TestClass_attrib029_8_S1(-1); s1.j = 3; if (s1.j == 3) Attrib_TestClass_attrib029_8.retval -= 1; } } } public struct Attrib_TestClass_attrib029_8_S1 { public Attrib_TestClass_attrib029_8_S1(int i) { _j = i; } private int _j; [Obsolete("Attrib_TestClass_attrib029_8_S1 is an obsolete struct")] public int j { get { return _j; } set { _j = value; } } } public class Attrib_TestClass_attrib029_8 { public static int retval = 7; public static int Main_old() { Attrib_TestClass_attrib029_8_C1 c1 = new Attrib_TestClass_attrib029_8_C1(); c1.i = 5; int anInt = c1.i; if (anInt == 5) retval -= 2; Attrib_TestClass_attrib029_8_S1 s1 = new Attrib_TestClass_attrib029_8_S1(); s1.j = 10; if (10 == s1.j) retval -= 4; if (0 == retval) Log.Comment("PASS"); else Log.Comment("FAIL, retval==" + retval.ToString()); return retval; } public static bool testMethod() { return (Main_old() == 0); } } public class Attrib_TestClass_attrib029_9_C1 { [Obsolete] public int C1Method(int value) { Attrib_TestClass_attrib029_9_S1 s1 = new Attrib_TestClass_attrib029_9_S1(-1); if (s1.S1Method(3) == 3) Attrib_TestClass_attrib029_9.retval -= 1; return value; } } public struct Attrib_TestClass_attrib029_9_S1 { public Attrib_TestClass_attrib029_9_S1(int i) { } [Obsolete("Attrib_TestClass_attrib029_9_S1 is an obsolete struct")] public int S1Method(int value) { return value; } } public class Attrib_TestClass_attrib029_9 { public static int retval = 7; public static int Main_old() { Attrib_TestClass_attrib029_9_C1 c1 = new Attrib_TestClass_attrib029_9_C1(); int anInt = c1.C1Method(5); if (anInt == 5) retval -= 2; Attrib_TestClass_attrib029_9_S1 s1 = new Attrib_TestClass_attrib029_9_S1(); if (10 == s1.S1Method(10)) retval -= 4; if (0 == retval) Log.Comment("PASS"); else Log.Comment("FAIL, retval==" + retval.ToString()); return retval; } public static bool testMethod() { return (Main_old() == 0); } } public class Attrib_TestClass_attrib029_a_C1 { public Attrib_TestClass_attrib029_a_C1() { i = -1; } [Obsolete] public int i; } public struct Attrib_TestClass_attrib029_a_S1 { public Attrib_TestClass_attrib029_a_S1(int i) { j = i; } [Obsolete("Attrib_TestClass_attrib029_a_S1 is an obsolete struct")] public int j; } public class Attrib_TestClass_attrib029_a { public static int retval = 3; public static int Main_old() { Attrib_TestClass_attrib029_a_C1 c1 = new Attrib_TestClass_attrib029_a_C1(); c1.i = 5; int anInt = c1.i; if (anInt == 5) retval -= 1; Attrib_TestClass_attrib029_a_S1 s1 = new Attrib_TestClass_attrib029_a_S1(); s1.j = 10; if (10 == s1.j) retval -= 2; if (0 == retval) Log.Comment("PASS"); else Log.Comment("FAIL, retval==" + retval.ToString()); return retval; } public static bool testMethod() { return (Main_old() == 0); } } public class Attrib_TestClass_attrib029_b_C1 { [Obsolete] public virtual int C1Method(int value) { Attrib_TestClass_attrib029_b.retval -= 1; return value; } } public class Attrib_TestClass_attrib029_b_C2 : Attrib_TestClass_attrib029_b_C1 { public override int C1Method(int value) { base.C1Method(value); return value; } } public class Attrib_TestClass_attrib029_b { public static int retval = 3; public static int Main_old() { Attrib_TestClass_attrib029_b_C1 c1 = new Attrib_TestClass_attrib029_b_C1(); int anInt = c1.C1Method(5); if (anInt == 5) retval -= 2; if (0 == retval) Log.Comment("PASS"); else Log.Comment("FAIL, retval==" + retval.ToString()); return retval; } public static bool testMethod() { return (Main_old() == 0); } } [type: Serializable] struct Attrib_TestClass_attrib031_4_C1 { public int i;} [type: Serializable] public class Attrib_TestClass_attrib031_4 { public static int Main_old() { if (typeof(Attrib_TestClass_attrib031_4_C1).IsSerializable) { Log.Comment("PASS"); return 0; } Log.Comment("FAIL"); return 1; } public static bool testMethod() { return (Main_old() == 0); } } [StructLayout(LayoutKind.Sequential)] class Attrib_TestClass_attrib032_2_C1 { int i; double d; char c; byte b1, b2, b3; } public class Attrib_TestClass_attrib032_2 { public static int Main_old() { return 0; } public static bool testMethod() { return (Main_old() == 0); } } [AttributeUsage(AttributeTargets.Method)] public class Attrib_TestClass_attrib033_2_A1 : Attribute { public Attrib_TestClass_attrib033_2_A1(int i) { } } public class Attrib_TestClass_attrib033_2_A2 : Attrib_TestClass_attrib033_2_A1 { public Attrib_TestClass_attrib033_2_A2(int i) : base(i) { } } class Attrib_TestClass_attrib033_2 { [Attrib_TestClass_attrib033_2_A2(4)] // Should be legal. public static int Main_old() { return 0; } public static bool testMethod() { return (Main_old() == 0); } } /* public class Attrib_TestClass_attrib035_12 { public static int Main_old() { int retval = 3; object[] gaa = Assembly.GetExecutingAssembly().GetCustomAttributes(typeof(GuidAttribute), false); GuidAttribute ga = null; if (gaa.Length == 1) retval -= 1; try { ga = (GuidAttribute)gaa[0]; if (ga.Value == Attrib_TestClass_attrib035_12_C5.GuidString) retval -= 2; } catch { } //Just keep the program from dying if (retval == 0) Log.Comment("PASS"); else Log.Comment("FAIL, retval == {0}", retval); return retval; } public static bool testMethod() { return (Main_old() == 0); } } public class Attrib_TestClass_attrib035_22 { public static int Main_old() { Attrib_TestClass_attrib035_22_C5 x = new Attrib_TestClass_attrib035_22_C5(); int retval = x.MyMethod(); if (retval == 0) Log.Comment("PASS"); else Log.Comment("FAIL, retval == {0}", retval); return retval; } public static bool testMethod() { return (Main_old() == 0); } } */ [AttributeUsage(AttributeTargets.Class)] internal class Attrib_TestClass_attrib036_1_A1 : Attribute { Attrib_TestClass_attrib036_1_A1() { } //Default ctor necessary because compiler generates public ctor otherwise internal Attrib_TestClass_attrib036_1_A1(int i) { } [AttributeUsage(AttributeTargets.Class)] protected class Attrib2 : Attribute { Attrib2() { } //Default ctor necessary because compiler generates public ctor otherwise protected Attrib2(int i) { } [AttributeUsage(AttributeTargets.Class)] internal protected class Attrib3 : Attribute { Attrib3() { } //Default ctor necessary because compiler generates public ctor otherwise protected internal Attrib3(int i) { } } [AttributeUsage(AttributeTargets.Class)] private class Attrib4 : Attribute { Attrib4() { } //Default ctor necessary because compiler generates public ctor otherwise private Attrib4(int i) { } } } } public class Attrib_TestClass_attrib036_1 { public static int Main_old() { return 0; } public static bool testMethod() { return (Main_old() == 0); } } public delegate void Attrib_TestClass_attrib038_1_F1(params int[] numbers); public class Attrib_TestClass_attrib038_1_C1 { public void Attrib_TestClass_attrib038_1(params int[] numbers) { Log.Comment("Called with " + numbers.Length.ToString() + " args"); } } public class Attrib_TestClass_attrib038_1 { public static void Main_old() { Attrib_TestClass_attrib038_1_C1 cls = new Attrib_TestClass_attrib038_1_C1(); Attrib_TestClass_attrib038_1_F1 f1 = new Attrib_TestClass_attrib038_1_F1(cls.Attrib_TestClass_attrib038_1); f1(); f1(1); f1(1, 2); f1(1, 2, 3); } public static bool testMethod() { Main_old(); return true; } } [AttributeUsage(AttributeTargets.All, AllowMultiple = true)] public class Attrib_TestClass_attrib047_4_A1 : Attribute { [Obsolete("Constructor", false)] public Attrib_TestClass_attrib047_4_A1() { } [Obsolete("Property", false)] public int Prop { get { return 1; } set { } } [Obsolete("Field", false)] public int Field; } [Attrib_TestClass_attrib047_4_A1] [Attrib_TestClass_attrib047_4_A1()] [Attrib_TestClass_attrib047_4_A1(Field = 1)] [Attrib_TestClass_attrib047_4_A1(Prop = 1)] public class Attrib_TestClass_attrib047_4 { [method: Attrib_TestClass_attrib047_4_A1] [method: Attrib_TestClass_attrib047_4_A1()] [return: Attrib_TestClass_attrib047_4_A1(Field = 1)] [return: Attrib_TestClass_attrib047_4_A1(Prop = 1)] public static int Main_old() { return 0; } public static bool testMethod() { return (Main_old() == 0); } } [Obsolete("Class", false)] public class Attrib_TestClass_attrib047_5_A { [Obsolete("Constructor", false)] public Attrib_TestClass_attrib047_5_A() { } [Obsolete("Struct", false)] public struct S { } [Obsolete("Enum", false)] public enum E { } [Obsolete("Method", false)] public void foo() { } [Obsolete("Property", false)] public int Prop { get { return 1; } set { } } [Obsolete("Delegate", false)] public delegate void Del(); [Obsolete("Event", false)] public event Del Eve; [Obsolete("Field", false)] public readonly int Field; [Obsolete("Interface", false)] public interface I { } } public class Attrib_TestClass_attrib047_5 { public void foo() { } public static int Main_old() { Attrib_TestClass_attrib047_5 t = new Attrib_TestClass_attrib047_5(); Attrib_TestClass_attrib047_5_A a = new Attrib_TestClass_attrib047_5_A(); Attrib_TestClass_attrib047_5_A.S s = new Attrib_TestClass_attrib047_5_A.S(); a.Eve += new Attrib_TestClass_attrib047_5_A.Del(t.foo); a.foo(); int i = a.Prop; a.Prop = i; i = a.Field; Attrib_TestClass_attrib047_5_A.E e; return 0; } public static bool testMethod() { return (Main_old() == 0); } } public class Attrib_TestClass_attrib049_4_B : Attribute { public readonly int Attrib_TestClass_attrib049_4_C5; } public class Attrib_TestClass_attrib049_4_C : Attrib_TestClass_attrib049_4_B { new public int Attrib_TestClass_attrib049_4_C5; } [Attrib_TestClass_attrib049_4_C(Attrib_TestClass_attrib049_4_C5 = 5)] // should not be an error public class Attrib_TestClass_attrib049_4 { public static int Main_old() { return 0; } public static bool testMethod() { return (Main_old() == 0); } } [AttributeUsage(AttributeTargets.All)] public class Attrib_TestClass_attrib054_C5 : Attribute { } [AttributeUsage(AttributeTargets.All)] public class Attrib_TestClass_attrib054_A1 : Attribute { } [Attrib_TestClass_attrib054_A1] // Refers to Attrib_TestClass_attrib054_A1 class Attrib_TestClass_attrib054_C2 { } [@Attrib_TestClass_attrib054_C5] // Refers to Attrib_TestClass_attrib054_C5 class Attrib_TestClass_attrib054_C3 { [method: @Attrib_TestClass_attrib054_C5] [method: Attrib_TestClass_attrib054_A1] void foo() { } [method: @Attrib_TestClass_attrib054_C5] [method: @Attrib_TestClass_attrib054_A1] void foo(int i) { } [method: @Attrib_TestClass_attrib054_C5] [method: Attrib_TestClass_attrib054_A1] void foo(int i, int ii) { } } [@Attrib_TestClass_attrib054_A1] // Refers to Attrib_TestClass_attrib054_A1 class Attrib_TestClass_attrib054_C4 { } public class Attrib_TestClass_attrib054 { public static int Main_old() { return 0; } public static bool testMethod() { return (Main_old() == 0); } } public class Attrib_TestClass_attrib062_A2 : Attrib_TestClass_attrib062_A1 { } public class Attrib_TestClass_attrib062_A1 : Attribute { } [Attrib_TestClass_attrib062_A1] [Attrib_TestClass_attrib062_A2] public class Attrib_TestClass_attrib062 { public static int Main_old() { return 0; } public static bool testMethod() { return (Main_old() == 0); } } } } ================================================ FILE: Zelig/Zelig/Test/RunTime/NETMF/mscorlib/attributes/AttributesTests2.cs ================================================ //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // Copyright (c) Microsoft Corporation. All rights reserved. ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////#define DEBUG #define DEBUG using System; using System.Reflection; using Microsoft.SPOT.Platform.Test; using System.Diagnostics; using System.Runtime.InteropServices; namespace Microsoft.SPOT.Platform.Tests { public class AttributesTests2 : IMFTestInterface { [SetUp] public InitializeResult Initialize() { Log.Comment("Adding set up for the tests"); // Add your functionality here. return InitializeResult.ReadyToGo; } [TearDown] public void CleanUp() { Log.Comment("Cleaning up after the tests"); } //Attributes Test methods //The following tests were ported from folder current\test\cases\client\CLR\Conformance\10_classes\Attributes //attrib000,attrib000_2,attrib001,attrib002,attrib017_7,attrib017_7a,attrib017_8c,attrib017_9b,attrib021_2,attrib021_4,attrib029_8,attrib029_9,attrib029_a,attrib029_b,attrib031_4,attrib032_2,attrib033_2,attrib035_12,attrib035_22,attrib036_1,attrib038_1,attrib047_4,attrib047_5,attrib049_4,attrib054,attrib062 //Test Case Calls [TestMethod] public MFTestResults Attrib_attrib017_7_Test() { Log.Comment("17.4.5 Testing Conditional with DEBUG defined."); if (Attrib_TestClass_attrib017_7.testMethod()) { return MFTestResults.Pass; } return MFTestResults.Fail; } [TestMethod] public MFTestResults Attrib_attrib017_9b_Test() { Log.Comment("17.4.5 - Conditional not valid on delegate creation."); if (Attrib_TestClass_attrib017_9b.testMethod()) { return MFTestResults.Pass; } return MFTestResults.Fail; } public class Attrib_TestClass_attrib017_7_C1 { [Conditional("DEBUG")] public static void M() { Attrib_TestClass_attrib017_7.retval++; Log.Comment("Executed Attrib_TestClass_attrib017_7_C1.M"); } } public class Attrib_TestClass_attrib017_7_C2 { public static void Attrib_TestClass_attrib017_7() { Attrib_TestClass_attrib017_7_C1.M(); } } public class Attrib_TestClass_attrib017_7 { public static int retval = 0; public static int Main_old() { Attrib_TestClass_attrib017_7_C2.Attrib_TestClass_attrib017_7(); if (retval != 0) { Log.Comment("PASS"); return 0; } Log.Comment("FAIL"); return 1; } public static bool testMethod() { return (Main_old() == 0); } } class Attrib_TestClass_attrib017_9b_C1 { [Conditional("DEBUG")] public virtual void M() { Log.Comment("Class1.M executed"); } } class Attrib_TestClass_attrib017_9b_C2 : Attrib_TestClass_attrib017_9b_C1 { public override void M() { Log.Comment("Class2.M executed"); base.M(); // base.M is not called! } } class Attrib_TestClass_attrib017_9b_C3 { public static void Attrib_TestClass_attrib017_9b() { Attrib_TestClass_attrib017_9b_C2 c = new Attrib_TestClass_attrib017_9b_C2(); c.M(); // Attrib_TestClass_attrib017_9b_C2.M() is called, but Attrib_TestClass_attrib017_9b_C1.M() is not! Attrib_TestClass_attrib017_9b_C1 c1 = new Attrib_TestClass_attrib017_9b_C1(); c1.M(); // But this time Attrib_TestClass_attrib017_9b_C1.M() is called. } } public class Attrib_TestClass_attrib017_9b { public static int Main_old() { Attrib_TestClass_attrib017_9b_C3.Attrib_TestClass_attrib017_9b(); return 0; } public static bool testMethod() { return (Main_old() == 0); } } } } ================================================ FILE: Zelig/Zelig/Test/RunTime/NETMF/mscorlib/basicconcepts/BasicConceptTests.cs ================================================ //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // Copyright (c) Microsoft Corporation. All rights reserved. //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// using System; using Microsoft.Zelig.Test; namespace Microsoft.Zelig.Test { public class BasicConceptTests : TestBase, ITestInterface { [SetUp] public InitializeResult Initialize() { Log.Comment("Adding set up for the tests"); return InitializeResult.ReadyToGo; } [TearDown] public void CleanUp() { Log.Comment("Cleaning up after the tests"); } public override TestResult Run( string[] args ) { TestResult result = TestResult.Pass; string testName = "Basic_scope"; result |= Assert.CheckFailed(Basic_scope001_Test(), testName, 1); result |= Assert.CheckFailed(Basic_scope002_Test(), testName, 2); result |= Assert.CheckFailed(Basic_scope003_Test(), testName, 3); result |= Assert.CheckFailed(Basic_scope004_Test(), testName, 4); result |= Assert.CheckFailed(Basic_scope005_Test(), testName, 5); result |= Assert.CheckFailed(Basic_scope006_Test(), testName, 6); result |= Assert.CheckFailed(Basic_scope012_Test(), testName, 12); result |= Assert.CheckFailed(Basic_scope019_Test(), testName, 19); result |= Assert.CheckFailed(Basic_scope022_Test(), testName, 22); result |= Assert.CheckFailed(Basic_scope023_Test(), testName, 23); result |= Assert.CheckFailed(Basic_scope024_Test(), testName, 24); result |= Assert.CheckFailed(Basic_scope025_Test(), testName, 25); result |= Assert.CheckFailed(Basic_scope027_Test(), testName, 27); result |= Assert.CheckFailed(Basic_scope029_Test(), testName, 29); result |= Assert.CheckFailed(Basic_scope033_Test(), testName, 33); result |= Assert.CheckFailed(Basic_scope037_Test(), testName, 37); result |= Assert.CheckFailed(Basic_scope041_Test(), testName, 41); result |= Assert.CheckFailed(Basic_scope044_Test(), testName, 44); result |= Assert.CheckFailed(Basic_scope051_Test(), testName, 51); result |= Assert.CheckFailed(Basic_scope053_Test(), testName, 53); result |= Assert.CheckFailed(Basic_scope055_Test(), testName, 55); result |= Assert.CheckFailed(Basic_scope056_Test(), testName, 56); result |= Assert.CheckFailed(Basic_scope057_Test(), testName, 57); result |= Assert.CheckFailed(Basic_scope058_Test(), testName, 58); result |= Assert.CheckFailed(Basic_scope059_Test(), testName, 59); result |= Assert.CheckFailed(Basic_scope061_Test(), testName, 61); result |= Assert.CheckFailed(Basic_scope062_Test(), testName, 62); result |= Assert.CheckFailed(Basic_scope063_Test(), testName, 63); result |= Assert.CheckFailed(Basic_scope064_Test(), testName, 64); result |= Assert.CheckFailed(Basic_scope067_Test(), testName, 67); result |= Assert.CheckFailed(Basic_scope068_Test(), testName, 68); result |= Assert.CheckFailed(Basic_scope069_Test(), testName, 69); result |= Assert.CheckFailed(Basic_scope070_Test(), testName, 70); result |= Assert.CheckFailed(Basic_scope071_Test(), testName, 71); result |= Assert.CheckFailed(Basic_scope074_Test(), testName, 74); testName = "Basic_nhide"; result |= Assert.CheckFailed(Basic_nhide001_Test(), testName, 1); result |= Assert.CheckFailed(Basic_nhide002_Test(), testName, 2); result |= Assert.CheckFailed(Basic_nhide003_Test(), testName, 3); result |= Assert.CheckFailed(Basic_nhide004_Test(), testName, 4); result |= Assert.CheckFailed(Basic_nhide005_Test(), testName, 5); result |= Assert.CheckFailed(Basic_nhide006_Test(), testName, 6); result |= Assert.CheckFailed(Basic_nhide007_Test(), testName, 7); result |= Assert.CheckFailed(Basic_nhide008_Test(), testName, 8); result |= Assert.CheckFailed(Basic_nhide009_Test(), testName, 9); result |= Assert.CheckFailed(Basic_nhide010_Test(), testName, 10); result |= Assert.CheckFailed(Basic_nhide011_Test(), testName, 11); result |= Assert.CheckFailed(Basic_nhide012_Test(), testName, 12); result |= Assert.CheckFailed(Basic_nhide013_Test(), testName, 13); result |= Assert.CheckFailed(Basic_nhide014_Test(), testName, 14); result |= Assert.CheckFailed(Basic_nhide015_Test(), testName, 15); result |= Assert.CheckFailed(Basic_nhide016_Test(), testName, 16); result |= Assert.CheckFailed(Basic_nhide017_Test(), testName, 17); result |= Assert.CheckFailed(Basic_nhide018_Test(), testName, 18); result |= Assert.CheckFailed(Basic_nhide019_Test(), testName, 19); result |= Assert.CheckFailed(Basic_nhide020_Test(), testName, 20); result |= Assert.CheckFailed(Basic_nhide021_Test(), testName, 21); result |= Assert.CheckFailed(Basic_nhide022_Test(), testName, 22); result |= Assert.CheckFailed(Basic_nhide023_Test(), testName, 23); result |= Assert.CheckFailed(Basic_nhide024_Test(), testName, 24); result |= Assert.CheckFailed(Basic_nhide025_Test(), testName, 25); result |= Assert.CheckFailed(Basic_nhide026_Test(), testName, 26); result |= Assert.CheckFailed(Basic_nhide027_Test(), testName, 27); result |= Assert.CheckFailed(Basic_nhide028_Test(), testName, 28); result |= Assert.CheckFailed(Basic_nhide029_Test(), testName, 29); result |= Assert.CheckFailed(Basic_nhide030_Test(), testName, 30); result |= Assert.CheckFailed(Basic_nhide031_Test(), testName, 31); result |= Assert.CheckFailed(Basic_nhide032_Test(), testName, 32); result |= Assert.CheckFailed(Basic_nhide033_Test(), testName, 33); result |= Assert.CheckFailed(Basic_nhide034_Test(), testName, 34); result |= Assert.CheckFailed(Basic_nhide035_Test(), testName, 35); result |= Assert.CheckFailed(Basic_nhide036_Test(), testName, 36); result |= Assert.CheckFailed(Basic_nhide037_Test(), testName, 37); result |= Assert.CheckFailed(Basic_nhide038_Test(), testName, 38); result |= Assert.CheckFailed(Basic_nhide039_Test(), testName, 39); result |= Assert.CheckFailed(Basic_nhide040_Test(), testName, 40); result |= Assert.CheckFailed(Basic_nhide041_Test(), testName, 41); result |= Assert.CheckFailed(Basic_nhide042_Test(), testName, 42); result |= Assert.CheckFailed(Basic_nhide043_Test(), testName, 43); result |= Assert.CheckFailed(Basic_nhide044_Test(), testName, 44); result |= Assert.CheckFailed(Basic_nhide045_Test(), testName, 45); result |= Assert.CheckFailed(Basic_nhide047_Test(), testName, 47); result |= Assert.CheckFailed(Basic_nhide049_Test(), testName, 49); result |= Assert.CheckFailed(Basic_nhide050_Test(), testName, 50); result |= Assert.CheckFailed(Basic_nhide051_Test(), testName, 51); result |= Assert.CheckFailed(Basic_nhide053_Test(), testName, 53); result |= Assert.CheckFailed(Basic_nhide055_Test(), testName, 55); result |= Assert.CheckFailed(Basic_nhide056_Test(), testName, 56); result |= Assert.CheckFailed(Basic_nhide057_Test(), testName, 57); result |= Assert.CheckFailed(Basic_nhide059_Test(), testName, 59); result |= Assert.CheckFailed(Basic_nhide061_Test(), testName, 61); result |= Assert.CheckFailed(Basic_nhide062_Test(), testName, 62); result |= Assert.CheckFailed(Basic_nhide063_Test(), testName, 63); result |= Assert.CheckFailed(Basic_nhide064_Test(), testName, 64); result |= Assert.CheckFailed(Basic_nhide067_Test(), testName, 67); result |= Assert.CheckFailed(Basic_nhide068_Test(), testName, 68); result |= Assert.CheckFailed(Basic_nhide071_Test(), testName, 71); result |= Assert.CheckFailed(Basic_nhide072_Test(), testName, 72); result |= Assert.CheckFailed(Basic_nhide075_Test(), testName, 75); result |= Assert.CheckFailed(Basic_nhide076_Test(), testName, 76); result |= Assert.CheckFailed(Basic_nhide077_Test(), testName, 77); result |= Assert.CheckFailed(Basic_nhide079_Test(), testName, 79); result |= Assert.CheckFailed(Basic_nhide081_Test(), testName, 81); result |= Assert.CheckFailed(Basic_nhide082_Test(), testName, 82); result |= Assert.CheckFailed(Basic_nhide085_Test(), testName, 85); result |= Assert.CheckFailed(Basic_nhide086_Test(), testName, 86); result |= Assert.CheckFailed(Basic_nhide087_Test(), testName, 87); result |= Assert.CheckFailed(Basic_nhide088_Test(), testName, 88); result |= Assert.CheckFailed(Basic_nhide089_Test(), testName, 89); result |= Assert.CheckFailed(Basic_nhide090_Test(), testName, 90); result |= Assert.CheckFailed(Basic_nhide091_Test(), testName, 91); result |= Assert.CheckFailed(Basic_nhide092_Test(), testName, 92); testName = "Basic_memac"; result |= Assert.CheckFailed(Basic_memac009_Test(), testName, 9); result |= Assert.CheckFailed(Basic_memac010_Test(), testName, 10); result |= Assert.CheckFailed(Basic_memac011_Test(), testName, 11); result |= Assert.CheckFailed(Basic_memac012_Test(), testName, 12); //result |= Assert.CheckFailed(Basic_memac013_Test(), testName, 13); //result |= Assert.CheckFailed(Basic_memac014_Test(), testName, 14); result |= Assert.CheckFailed(Basic_memac019_Test(), testName, 19); result |= Assert.CheckFailed(Basic_memac020_Test(), testName, 20); result |= Assert.CheckFailed(Basic_memac021_Test(), testName, 21); result |= Assert.CheckFailed(Basic_memac022_Test(), testName, 22); result |= Assert.CheckFailed(Basic_memac025_Test(), testName, 25); result |= Assert.CheckFailed(Basic_memac027_Test(), testName, 27); result |= Assert.CheckFailed(Basic_memac029_Test(), testName, 29); result |= Assert.CheckFailed(Basic_memac030_Test(), testName, 30); result |= Assert.CheckFailed(Basic_memac033_Test(), testName, 33); result |= Assert.CheckFailed(Basic_memac034_Test(), testName, 34); //result |= Assert.CheckFailed(Basic_memac039_Test(), testName, 39); //result |= Assert.CheckFailed(Basic_memac041_Test(), testName, 41); result |= Assert.CheckFailed(Basic_memac042_Test(), testName, 42); result |= Assert.CheckFailed(Basic_memac043_Test(), testName, 43); result |= Assert.CheckFailed(Basic_memac044_Test(), testName, 44); result |= Assert.CheckFailed(Basic_memac045_Test(), testName, 45); result |= Assert.CheckFailed(Basic_memac046_Test(), testName, 46); result |= Assert.CheckFailed(Basic_memac047_Test(), testName, 47); testName = "Basic_accon"; result |= Assert.CheckFailed(Basic_accon001_Test(), testName, 1); result |= Assert.CheckFailed(Basic_accon003_Test(), testName, 3); result |= Assert.CheckFailed(Basic_accon005_Test(), testName, 5); result |= Assert.CheckFailed(Basic_accon007_Test(), testName, 7); result |= Assert.CheckFailed(Basic_accon009_Test(), testName, 9); result |= Assert.CheckFailed(Basic_accon011_Test(), testName, 11); result |= Assert.CheckFailed(Basic_accon013_Test(), testName, 13); result |= Assert.CheckFailed(Basic_accon015_Test(), testName, 15); result |= Assert.CheckFailed(Basic_accon019_Test(), testName, 19); result |= Assert.CheckFailed(Basic_accon021_Test(), testName, 21); result |= Assert.CheckFailed(Basic_accon023_Test(), testName, 23); result |= Assert.CheckFailed(Basic_accon025_Test(), testName, 25); result |= Assert.CheckFailed(Basic_accon027_Test(), testName, 27); result |= Assert.CheckFailed(Basic_accon029_Test(), testName, 29); result |= Assert.CheckFailed(Basic_accon031_Test(), testName, 31); result |= Assert.CheckFailed(Basic_accon033_Test(), testName, 33); result |= Assert.CheckFailed(Basic_accon035_Test(), testName, 35); result |= Assert.CheckFailed(Basic_accon037_Test(), testName, 37); result |= Assert.CheckFailed(Basic_accon039_Test(), testName, 39); result |= Assert.CheckFailed(Basic_accon041_Test(), testName, 41); result |= Assert.CheckFailed(Basic_accon043_Test(), testName, 43); result |= Assert.CheckFailed(Basic_accon045_Test(), testName, 45); result |= Assert.CheckFailed(Basic_accon047_Test(), testName, 47); result |= Assert.CheckFailed(Basic_accon049_Test(), testName, 49); result |= Assert.CheckFailed(Basic_accon051_Test(), testName, 51); result |= Assert.CheckFailed(Basic_accon053_Test(), testName, 53); result |= Assert.CheckFailed(Basic_accon055_Test(), testName, 55); return result; } //--// //--// //--// //BasicConcept Test methods //The following tests were ported from folder current\test\cases\client\CLR\Conformance\10_classes\BasicConcept //scope001,scope002,scope003,scope004,scope005,scope006,scope012,scope019,scope022,scope023,scope024,scope025,scope027,scope029,scope033,scope037,scope041,scope044,scope051,scope053,scope055,scope056,scope057,scope058,scope059,scope061,scope062,scope063,scope064,scope067,scope068,scope069,scope070,scope071,scope074,nhide001,nhide002,nhide003,nhide004,nhide005,nhide006,nhide007,nhide008,nhide009,nhide010,nhide011,nhide012,nhide013,nhide014,nhide015,nhide016,nhide017,nhide018,nhide019,nhide020,nhide021,nhide022,nhide023,nhide024,nhide025,nhide026,nhide027,nhide028,nhide029,nhide030,nhide031,nhide032,nhide033,nhide034,nhide035,nhide036,nhide037,nhide038,nhide039,nhide040,nhide041,nhide042,nhide043,nhide044,nhide045,nhide047,nhide049,nhide050,nhide051,nhide053,nhide055,nhide056,nhide057,nhide059,nhide061,nhide062,nhide063,nhide064,nhide067,nhide068,nhide071,nhide072,nhide075,nhide076,nhide077,nhide079,nhide081,nhide082,nhide085,nhide086,nhide087,nhide088,nhide089,nhide090,nhide091,nhide092,memac009,memac010,memac011,memac012,memac013,memac014,memac019,memac020,memac021,memac022,memac025,memac027,memac029,memac030,memac033,memac034,memac039,memac041,memac042,memac043,memac044,memac045,memac046,memac047,accon001,accon003,accon005,accon007,accon009,accon011,accon013,accon015,accon019,accon021,accon023,accon025,accon027,accon029,accon031,accon033,accon035,accon037,accon039,accon041,accon043,accon045,accon047,accon049,accon051,accon053,accon055 //Test Case Calls [TestMethod] public TestResult Basic_scope001_Test() { Log.Comment("Section 3.5"); Log.Comment("The scope of a namespace member declared by"); Log.Comment("a namespace-member-declaration with no enclosing"); Log.Comment("namespace-declaration is the entire program text"); Log.Comment("of each compilation unit."); if (Basic_TestClass_scope001.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Basic_scope002_Test() { Log.Comment("Section 3.5"); Log.Comment("The scope of a namespace member declared by a "); Log.Comment("namespace-member-declaration within a "); Log.Comment("namespace-declaration whose fully qualified name"); Log.Comment("is N is the namespace-body of every namespace-declaration"); Log.Comment("whose fully qualified name is N or starts with the same "); Log.Comment("sequence of indentifiers as N."); if (NS_Basic_TestClass_scope002.Basic_TestClass_scope002.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Basic_scope003_Test() { Log.Comment("Section 3.5"); Log.Comment("The scope of a namespace member declared by a "); Log.Comment("namespace-member-declaration within a "); Log.Comment("namespace-declaration whose fully qualified name"); Log.Comment("is N is the namespace-body of every namespace-declaration"); Log.Comment("whose fully qualified name is N or starts with the same "); Log.Comment("sequence of indentifiers as N."); if (NS_Basic_TestClass_scope003.Basic_TestClass_scope003.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Basic_scope004_Test() { Log.Comment("Section 3.5"); Log.Comment("The scope of a namespace member declared by a "); Log.Comment("namespace-member-declaration within a "); Log.Comment("namespace-declaration whose fully qualified name"); Log.Comment("is N is the namespace-body of every namespace-declaration"); Log.Comment("whose fully qualified name is N or starts with the same "); Log.Comment("sequence of indentifiers as N."); if (NS_Basic_TestClass_scope004.NS_Basic_TestClass_scope004_2.Basic_TestClass_scope004.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Basic_scope005_Test() { Log.Comment("Section 3.5"); Log.Comment("The scope of a namespace member declared by a "); Log.Comment("namespace-member-declaration within a "); Log.Comment("namespace-declaration whose fully qualified name"); Log.Comment("is N is the namespace-body of every namespace-declaration"); Log.Comment("whose fully qualified name is N or starts with the same "); Log.Comment("sequence of indentifiers as N."); if (NS_Basic_TestClass_scope005.NS_Basic_TestClass_scope005_2.Basic_TestClass_scope005.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Basic_scope006_Test() { Log.Comment("Section 3.5"); Log.Comment("The scope of a namespace member declared by a "); Log.Comment("namespace-member-declaration within a "); Log.Comment("namespace-declaration whose fully qualified name"); Log.Comment("is N is the namespace-body of every namespace-declaration"); Log.Comment("whose fully qualified name is N or starts with the same "); Log.Comment("sequence of indentifiers as N."); if (NS_Basic_TestClass_scope006.NS_Basic_TestClass_scope006_2.Basic_TestClass_scope006.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Basic_scope012_Test() { Log.Comment("Section 3.5"); Log.Comment("The scope of a name defined or imported by a using-directive"); Log.Comment("extends over the namespace-member-declarations of the"); Log.Comment("compilation-unit or namespace-body in which the using-directive"); Log.Comment("occurs."); if (NS_Basic_TestClass_scope012.Basic_TestClass_scope012.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Basic_scope019_Test() { Log.Comment("Section 3.5"); Log.Comment("The scope of a member declared by a class-member-declaration"); Log.Comment("is the class body in which the declaration occurs."); if (Basic_TestClass_scope019.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Basic_scope022_Test() { Log.Comment("Section 3.5"); Log.Comment("The scope of a member declared by a class-member-declaration"); Log.Comment("is the class body in which the declaration occurs. In addition,"); Log.Comment("the scope of a class member extends to the class-body of those"); Log.Comment("derived classes that are included in the accessibility domain"); Log.Comment("of the member."); if (Basic_TestClass_scope022.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Basic_scope023_Test() { Log.Comment("Section 3.5"); Log.Comment("The scope of a member declared by a class-member-declaration"); Log.Comment("is the class body in which the declaration occurs. In addition,"); Log.Comment("the scope of a class member extends to the class-body of those"); Log.Comment("derived classes that are included in the accessibility domain"); Log.Comment("of the member."); if (Basic_TestClass_scope023.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Basic_scope024_Test() { Log.Comment("Section 3.5"); Log.Comment("The scope of a member declared by a class-member-declaration"); Log.Comment("is the class body in which the declaration occurs. In addition,"); Log.Comment("the scope of a class member extends to the class-body of those"); Log.Comment("derived classes that are included in the accessibility domain"); Log.Comment("of the member."); if (Basic_TestClass_scope024.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Basic_scope025_Test() { Log.Comment("Section 3.5"); Log.Comment("The scope of a member declared by a struct-member-declaration"); Log.Comment("is the struct-body in which the declaration occurs."); if (Basic_TestClass_scope025.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Basic_scope027_Test() { Log.Comment("Section 3.5"); Log.Comment("The scope of a member declared by an enum-member-declaration"); Log.Comment("is the enum-body in which the declaration occurs."); if (Basic_TestClass_scope027.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Basic_scope029_Test() { Log.Comment("Section 3.5"); Log.Comment("The scope of a parameter declared in a constructor-declaration"); Log.Comment("is the constructor-initializer and the block of that "); Log.Comment("constructor-declaration."); if (Basic_TestClass_scope029.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Basic_scope033_Test() { Log.Comment("Section 3.5"); Log.Comment("The scope of a parameter declared in a method-declaration"); Log.Comment("is the method-body of that method-declaration."); if (Basic_TestClass_scope033.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Basic_scope037_Test() { Log.Comment("Section 3.5"); Log.Comment("The scope of a parameter declared in an indexer-declaration"); Log.Comment("is the accessor-declarations of that indexer-declaration."); if (Basic_TestClass_scope037.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Basic_scope041_Test() { Log.Comment("Section 3.5"); Log.Comment("The scope of a parameter declared in an operator-declaration"); Log.Comment("is the block of that operator-declaration."); if (Basic_TestClass_scope041.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Basic_scope044_Test() { Log.Comment("Section 3.5"); Log.Comment("The scope of a local variable declared in a local-variable-declaration"); Log.Comment("is the block in which the declaration occurs. It is an error to refer to"); Log.Comment("a lcaol variable in a textual position that precedes the variable-declaratior"); Log.Comment("of the local variable."); if (Basic_TestClass_scope044.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Basic_scope051_Test() { Log.Comment("Section 3.5"); Log.Comment("The scope of a local variable in a for-initializer of a "); Log.Comment("for statement is the for-initializer, the for-condition,"); Log.Comment("the for-iterator, and the contained statement of the for"); Log.Comment("statement."); if (Basic_TestClass_scope051.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Basic_scope053_Test() { Log.Comment("Section 3.5"); Log.Comment("The scope of a label declared in a label-statement"); Log.Comment("is the block in which the declaration occurs."); if (Basic_TestClass_scope053.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Basic_scope055_Test() { Log.Comment("Section 3.5"); Log.Comment("The scope of a label declared in a label-statement"); Log.Comment("is the block in which the declaration occurs."); if (Basic_TestClass_scope055.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Basic_scope056_Test() { Log.Comment("Section 3.5"); Log.Comment("Within the scope of a namespace, class,"); Log.Comment("struct, interface, or enumeration member "); Log.Comment("it is possible to refer to the member in "); Log.Comment("a textual position that precedes the "); Log.Comment("declaration of the member."); if (NS_Basic_TestClass_scope056.Basic_TestClass_scope056.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Basic_scope057_Test() { Log.Comment("Section 3.5"); Log.Comment("Within the scope of a namespace, class,"); Log.Comment("struct, interface, or enumeration member "); Log.Comment("it is possible to refer to the member in "); Log.Comment("a textual position that precedes the "); Log.Comment("declaration of the member."); if (Basic_TestClass_scope057.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Basic_scope058_Test() { Log.Comment("Section 3.5"); Log.Comment("Within the scope of a namespace, class,"); Log.Comment("struct, interface, or enumeration member "); Log.Comment("it is possible to refer to the member in "); Log.Comment("a textual position that precedes the "); Log.Comment("declaration of the member."); if (Basic_TestClass_scope058.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Basic_scope059_Test() { Log.Comment("Section 3.5"); Log.Comment("Within the scope of a namespace, class,"); Log.Comment("struct, interface, or enumeration member "); Log.Comment("it is possible to refer to the member in "); Log.Comment("a textual position that precedes the "); Log.Comment("declaration of the member."); if (Basic_TestClass_scope059.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Basic_scope061_Test() { Log.Comment("Section 3.5"); Log.Comment("Witin the scope of a local variable, it is an"); Log.Comment("error to refer to the local variable in a "); Log.Comment("textual position that precedes the"); Log.Comment("variable-declarator of the local variable."); if (Basic_TestClass_scope061.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Basic_scope062_Test() { Log.Comment("Section 3.5"); Log.Comment("The meaning of a name within a block may differ"); Log.Comment("based on the context in which the name is used."); if (Basic_TestClass_scope062.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Basic_scope063_Test() { Log.Comment("Section 3.5"); if (Basic_TestClass_scope063.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Basic_scope064_Test() { Log.Comment("Section 3.5"); if (Basic_TestClass_scope064.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Basic_scope067_Test() { Log.Comment("Section 3.5"); if (Basic_TestClass_scope067.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Basic_scope068_Test() { Log.Comment("Section 3.5"); if (Basic_TestClass_scope068.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Basic_scope069_Test() { Log.Comment("Section 3"); if (Basic_TestClass_scope069.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Basic_scope070_Test() { Log.Comment("Section 3"); if (Basic_TestClass_scope070.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Basic_scope071_Test() { Log.Comment("Section 3"); if (Basic_TestClass_scope071.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Basic_scope074_Test() { Log.Comment("Section 3.5"); Log.Comment("The scope of a label declared in a label-statement"); Log.Comment("is the block in which the declaration occurs."); if (Basic_TestClass_scope074.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Basic_nhide001_Test() { Log.Comment("Section 3.5.1"); Log.Comment("Name hiding through nesting can occur as a result of"); Log.Comment("nesting namespaces or types within namespaces, as a "); Log.Comment("result of nesting types within classes or structs,"); Log.Comment("and as a result of parameter and local variable"); Log.Comment("declarations. Name hiding through nesting of scopes"); Log.Comment("always occurs silently, i.e. no errors or warnings"); Log.Comment("are reported when outer names are hidden by inner names."); if (NS_Basic_TestClass_nhide001.Basic_TestClass_nhide001.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Basic_nhide002_Test() { Log.Comment("Section 3.5.1"); Log.Comment("Name hiding through nesting can occur as a result of"); Log.Comment("nesting namespaces or types within namespaces, as a "); Log.Comment("result of nesting types within classes or structs,"); Log.Comment("and as a result of parameter and local variable"); Log.Comment("declarations. Name hiding through nesting of scopes"); Log.Comment("always occurs silently, i.e. no errors or warnings"); Log.Comment("are reported when outer names are hidden by inner names."); if (NS_Basic_TestClass_nhide002.Basic_TestClass_nhide002.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Basic_nhide003_Test() { Log.Comment("Section 3.5.1"); Log.Comment("Name hiding through nesting can occur as a result of"); Log.Comment("nesting namespaces or types within namespaces, as a "); Log.Comment("result of nesting types within classes or structs,"); Log.Comment("and as a result of parameter and local variable"); Log.Comment("declarations. Name hiding through nesting of scopes"); Log.Comment("always occurs silently, i.e. no errors or warnings"); Log.Comment("are reported when outer names are hidden by inner names."); if (NS_Basic_TestClass_nhide003.Basic_TestClass_nhide003.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Basic_nhide004_Test() { Log.Comment("Section 3.5.1"); Log.Comment("Name hiding through nesting can occur as a result of"); Log.Comment("nesting namespaces or types within namespaces, as a "); Log.Comment("result of nesting types within classes or structs,"); Log.Comment("and as a result of parameter and local variable"); Log.Comment("declarations. Name hiding through nesting of scopes"); Log.Comment("always occurs silently, i.e. no errors or warnings"); Log.Comment("are reported when outer names are hidden by inner names."); if (NS_Basic_TestClass_nhide004.Basic_TestClass_nhide004.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Basic_nhide005_Test() { Log.Comment("Section 3.5.1"); Log.Comment("Name hiding through nesting can occur as a result of"); Log.Comment("nesting namespaces or types within namespaces, as a "); Log.Comment("result of nesting types within classes or structs,"); Log.Comment("and as a result of parameter and local variable"); Log.Comment("declarations. Name hiding through nesting of scopes"); Log.Comment("always occurs silently, i.e. no errors or warnings"); Log.Comment("are reported when outer names are hidden by inner names."); if (NS_Basic_TestClass_nhide005.Basic_TestClass_nhide005.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Basic_nhide006_Test() { Log.Comment("Section 3.5.1"); Log.Comment("Name hiding through nesting can occur as a result of"); Log.Comment("nesting namespaces or types within namespaces, as a "); Log.Comment("result of nesting types within classes or structs,"); Log.Comment("and as a result of parameter and local variable"); Log.Comment("declarations. Name hiding through nesting of scopes"); Log.Comment("always occurs silently, i.e. no errors or warnings"); Log.Comment("are reported when outer names are hidden by inner names."); if (NS_Basic_TestClass_nhide006.Basic_TestClass_nhide006.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Basic_nhide007_Test() { Log.Comment("Section 3.5.1"); Log.Comment("Name hiding through nesting can occur as a result of"); Log.Comment("nesting namespaces or types within namespaces, as a "); Log.Comment("result of nesting types within classes or structs,"); Log.Comment("and as a result of parameter and local variable"); Log.Comment("declarations. Name hiding through nesting of scopes"); Log.Comment("always occurs silently, i.e. no errors or warnings"); Log.Comment("are reported when outer names are hidden by inner names."); if (Basic_TestClass_nhide007.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Basic_nhide008_Test() { Log.Comment("Section 3.5.1"); Log.Comment("Name hiding through nesting can occur as a result of"); Log.Comment("nesting namespaces or types within namespaces, as a "); Log.Comment("result of nesting types within classes or structs,"); Log.Comment("and as a result of parameter and local variable"); Log.Comment("declarations. Name hiding through nesting of scopes"); Log.Comment("always occurs silently, i.e. no errors or warnings"); Log.Comment("are reported when outer names are hidden by inner names."); if (NS_Basic_TestClass_nhide008.Basic_TestClass_nhide008.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Basic_nhide009_Test() { Log.Comment("Section 3.5.1"); Log.Comment("Name hiding through nesting can occur as a result of"); Log.Comment("nesting namespaces or types within namespaces, as a "); Log.Comment("result of nesting types within classes or structs,"); Log.Comment("and as a result of parameter and local variable"); Log.Comment("declarations. Name hiding through nesting of scopes"); Log.Comment("always occurs silently, i.e. no errors or warnings"); Log.Comment("are reported when outer names are hidden by inner names."); if (NS_Basic_TestClass_nhide009.Basic_TestClass_nhide009.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Basic_nhide010_Test() { Log.Comment("Section 3.5.1"); Log.Comment("Name hiding through nesting can occur as a result of"); Log.Comment("nesting namespaces or types within namespaces, as a "); Log.Comment("result of nesting types within classes or structs,"); Log.Comment("and as a result of parameter and local variable"); Log.Comment("declarations. Name hiding through nesting of scopes"); Log.Comment("always occurs silently, i.e. no errors or warnings"); Log.Comment("are reported when outer names are hidden by inner names."); if (NS_Basic_TestClass_nhide010.Basic_TestClass_nhide010.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Basic_nhide011_Test() { Log.Comment("Section 3.5.1"); Log.Comment("Name hiding through nesting can occur as a result of"); Log.Comment("nesting namespaces or types within namespaces, as a "); Log.Comment("result of nesting types within classes or structs,"); Log.Comment("and as a result of parameter and local variable"); Log.Comment("declarations. Name hiding through nesting of scopes"); Log.Comment("always occurs silently, i.e. no errors or warnings"); Log.Comment("are reported when outer names are hidden by inner names."); if (NS_Basic_TestClass_nhide011.Basic_TestClass_nhide011.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Basic_nhide012_Test() { Log.Comment("Section 3.5.1"); Log.Comment("Name hiding through nesting can occur as a result of"); Log.Comment("nesting namespaces or types within namespaces, as a "); Log.Comment("result of nesting types within classes or structs,"); Log.Comment("and as a result of parameter and local variable"); Log.Comment("declarations. Name hiding through nesting of scopes"); Log.Comment("always occurs silently, i.e. no errors or warnings"); Log.Comment("are reported when outer names are hidden by inner names."); if (NS_Basic_TestClass_nhide012.Basic_TestClass_nhide012.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Basic_nhide013_Test() { Log.Comment("Section 3.5.1"); Log.Comment("Name hiding through nesting can occur as a result of"); Log.Comment("nesting namespaces or types within namespaces, as a "); Log.Comment("result of nesting types within classes or structs,"); Log.Comment("and as a result of parameter and local variable"); Log.Comment("declarations. Name hiding through nesting of scopes"); Log.Comment("always occurs silently, i.e. no errors or warnings"); Log.Comment("are reported when outer names are hidden by inner names."); if (NS_Basic_TestClass_nhide013.Basic_TestClass_nhide013.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Basic_nhide014_Test() { Log.Comment("Section 3.5.1"); Log.Comment("Name hiding through nesting can occur as a result of"); Log.Comment("nesting namespaces or types within namespaces, as a "); Log.Comment("result of nesting types within classes or structs,"); Log.Comment("and as a result of parameter and local variable"); Log.Comment("declarations. Name hiding through nesting of scopes"); Log.Comment("always occurs silently, i.e. no errors or warnings"); Log.Comment("are reported when outer names are hidden by inner names."); if (Basic_TestClass_nhide014.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Basic_nhide015_Test() { Log.Comment("Section 3.5.1"); Log.Comment("Name hiding through nesting can occur as a result of"); Log.Comment("nesting namespaces or types within namespaces, as a "); Log.Comment("result of nesting types within classes or structs,"); Log.Comment("and as a result of parameter and local variable"); Log.Comment("declarations. Name hiding through nesting of scopes"); Log.Comment("always occurs silently, i.e. no errors or warnings"); Log.Comment("are reported when outer names are hidden by inner names."); if (Basic_TestClass_nhide015.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Basic_nhide016_Test() { Log.Comment("Section 3.5.1"); Log.Comment("Name hiding through nesting can occur as a result of"); Log.Comment("nesting namespaces or types within namespaces, as a "); Log.Comment("result of nesting types within classes or structs,"); Log.Comment("and as a result of parameter and local variable"); Log.Comment("declarations. Name hiding through nesting of scopes"); Log.Comment("always occurs silently, i.e. no errors or warnings"); Log.Comment("are reported when outer names are hidden by inner names."); if (Basic_TestClass_nhide016.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Basic_nhide017_Test() { Log.Comment("Section 3.5.1"); Log.Comment("Name hiding through nesting can occur as a result of"); Log.Comment("nesting namespaces or types within namespaces, as a "); Log.Comment("result of nesting types within classes or structs,"); Log.Comment("and as a result of parameter and local variable"); Log.Comment("declarations. Name hiding through nesting of scopes"); Log.Comment("always occurs silently, i.e. no errors or warnings"); Log.Comment("are reported when outer names are hidden by inner names."); if (Basic_TestClass_nhide017.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Basic_nhide018_Test() { Log.Comment("Section 3.5.1"); Log.Comment("Name hiding through nesting can occur as a result of"); Log.Comment("nesting namespaces or types within namespaces, as a "); Log.Comment("result of nesting types within classes or structs,"); Log.Comment("and as a result of parameter and local variable"); Log.Comment("declarations. Name hiding through nesting of scopes"); Log.Comment("always occurs silently, i.e. no errors or warnings"); Log.Comment("are reported when outer names are hidden by inner names."); if (Basic_TestClass_nhide018.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Basic_nhide019_Test() { Log.Comment("Section 3.5.1"); Log.Comment("Name hiding through nesting can occur as a result of"); Log.Comment("nesting namespaces or types within namespaces, as a "); Log.Comment("result of nesting types within classes or structs,"); Log.Comment("and as a result of parameter and local variable"); Log.Comment("declarations. Name hiding through nesting of scopes"); Log.Comment("always occurs silently, i.e. no errors or warnings"); Log.Comment("are reported when outer names are hidden by inner names."); if (Basic_TestClass_nhide019.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Basic_nhide020_Test() { Log.Comment("Section 3.5.1"); Log.Comment("Name hiding through nesting can occur as a result of"); Log.Comment("nesting namespaces or types within namespaces, as a "); Log.Comment("result of nesting types within classes or structs,"); Log.Comment("and as a result of parameter and local variable"); Log.Comment("declarations. Name hiding through nesting of scopes"); Log.Comment("always occurs silently, i.e. no errors or warnings"); Log.Comment("are reported when outer names are hidden by inner names."); if (Basic_TestClass_nhide020.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Basic_nhide021_Test() { Log.Comment("Section 3.5.1"); Log.Comment("Name hiding through nesting can occur as a result of"); Log.Comment("nesting namespaces or types within namespaces, as a "); Log.Comment("result of nesting types within classes or structs,"); Log.Comment("and as a result of parameter and local variable"); Log.Comment("declarations. Name hiding through nesting of scopes"); Log.Comment("always occurs silently, i.e. no errors or warnings"); Log.Comment("are reported when outer names are hidden by inner names."); if (Basic_TestClass_nhide021.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Basic_nhide022_Test() { Log.Comment("Section 3.5.1"); Log.Comment("Name hiding through nesting can occur as a result of"); Log.Comment("nesting namespaces or types within namespaces, as a "); Log.Comment("result of nesting types within classes or structs,"); Log.Comment("and as a result of parameter and local variable"); Log.Comment("declarations. Name hiding through nesting of scopes"); Log.Comment("always occurs silently, i.e. no errors or warnings"); Log.Comment("are reported when outer names are hidden by inner names."); if (Basic_TestClass_nhide022.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Basic_nhide023_Test() { Log.Comment("Section 3.5.1"); Log.Comment("Name hiding through nesting can occur as a result of"); Log.Comment("nesting namespaces or types within namespaces, as a "); Log.Comment("result of nesting types within classes or structs,"); Log.Comment("and as a result of parameter and local variable"); Log.Comment("declarations. Name hiding through nesting of scopes"); Log.Comment("always occurs silently, i.e. no errors or warnings"); Log.Comment("are reported when outer names are hidden by inner names."); if (Basic_TestClass_nhide023.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Basic_nhide024_Test() { Log.Comment("Section 3.5.1"); Log.Comment("Name hiding through nesting can occur as a result of"); Log.Comment("nesting namespaces or types within namespaces, as a "); Log.Comment("result of nesting types within classes or structs,"); Log.Comment("and as a result of parameter and local variable"); Log.Comment("declarations. Name hiding through nesting of scopes"); Log.Comment("always occurs silently, i.e. no errors or warnings"); Log.Comment("are reported when outer names are hidden by inner names."); if (Basic_TestClass_nhide024.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Basic_nhide025_Test() { Log.Comment("Section 3.5.1"); Log.Comment("Name hiding through nesting can occur as a result of"); Log.Comment("nesting namespaces or types within namespaces, as a "); Log.Comment("result of nesting types within classes or structs,"); Log.Comment("and as a result of parameter and local variable"); Log.Comment("declarations. Name hiding through nesting of scopes"); Log.Comment("always occurs silently, i.e. no errors or warnings"); Log.Comment("are reported when outer names are hidden by inner names."); if (Basic_TestClass_nhide025.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Basic_nhide026_Test() { Log.Comment("Section 3.5.1"); Log.Comment("Name hiding through nesting can occur as a result of"); Log.Comment("nesting namespaces or types within namespaces, as a "); Log.Comment("result of nesting types within classes or structs,"); Log.Comment("and as a result of parameter and local variable"); Log.Comment("declarations. Name hiding through nesting of scopes"); Log.Comment("always occurs silently, i.e. no errors or warnings"); Log.Comment("are reported when outer names are hidden by inner names."); if (Basic_TestClass_nhide026.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Basic_nhide027_Test() { Log.Comment("Section 3.5.1"); Log.Comment("Name hiding through nesting can occur as a result of"); Log.Comment("nesting namespaces or types within namespaces, as a "); Log.Comment("result of nesting types within classes or structs,"); Log.Comment("and as a result of parameter and local variable"); Log.Comment("declarations. Name hiding through nesting of scopes"); Log.Comment("always occurs silently, i.e. no errors or warnings"); Log.Comment("are reported when outer names are hidden by inner names."); if (Basic_TestClass_nhide027.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Basic_nhide028_Test() { Log.Comment("Section 3.5.1"); Log.Comment("Name hiding through nesting can occur as a result of"); Log.Comment("nesting namespaces or types within namespaces, as a "); Log.Comment("result of nesting types within classes or structs,"); Log.Comment("and as a result of parameter and local variable"); Log.Comment("declarations. Name hiding through nesting of scopes"); Log.Comment("always occurs silently, i.e. no errors or warnings"); Log.Comment("are reported when outer names are hidden by inner names."); if (Basic_TestClass_nhide028.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Basic_nhide029_Test() { Log.Comment("Section 3.5.1"); Log.Comment("Name hiding through nesting can occur as a result of"); Log.Comment("nesting namespaces or types within namespaces, as a "); Log.Comment("result of nesting types within classes or structs,"); Log.Comment("and as a result of parameter and local variable"); Log.Comment("declarations. Name hiding through nesting of scopes"); Log.Comment("always occurs silently, i.e. no errors or warnings"); Log.Comment("are reported when outer names are hidden by inner names."); if (Basic_TestClass_nhide029.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Basic_nhide030_Test() { Log.Comment("Section 3.5.1"); Log.Comment("Name hiding through nesting can occur as a result of"); Log.Comment("nesting namespaces or types within namespaces, as a "); Log.Comment("result of nesting types within classes or structs,"); Log.Comment("and as a result of parameter and local variable"); Log.Comment("declarations. Name hiding through nesting of scopes"); Log.Comment("always occurs silently, i.e. no errors or warnings"); Log.Comment("are reported when outer names are hidden by inner names."); if (Basic_TestClass_nhide030.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Basic_nhide031_Test() { Log.Comment("Section 3.5.1"); Log.Comment("Name hiding through nesting can occur as a result of"); Log.Comment("nesting namespaces or types within namespaces, as a "); Log.Comment("result of nesting types within classes or structs,"); Log.Comment("and as a result of parameter and local variable"); Log.Comment("declarations. Name hiding through nesting of scopes"); Log.Comment("always occurs silently, i.e. no errors or warnings"); Log.Comment("are reported when outer names are hidden by inner names."); if (Basic_TestClass_nhide031.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Basic_nhide032_Test() { Log.Comment("Section 3.5.1"); Log.Comment("Name hiding through nesting can occur as a result of"); Log.Comment("nesting namespaces or types within namespaces, as a "); Log.Comment("result of nesting types within classes or structs,"); Log.Comment("and as a result of parameter and local variable"); Log.Comment("declarations. Name hiding through nesting of scopes"); Log.Comment("always occurs silently, i.e. no errors or warnings"); Log.Comment("are reported when outer names are hidden by inner names."); if (Basic_TestClass_nhide032.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Basic_nhide033_Test() { Log.Comment("Section 3.5.1"); Log.Comment("Name hiding through nesting can occur as a result of"); Log.Comment("nesting namespaces or types within namespaces, as a "); Log.Comment("result of nesting types within classes or structs,"); Log.Comment("and as a result of parameter and local variable"); Log.Comment("declarations. Name hiding through nesting of scopes"); Log.Comment("always occurs silently, i.e. no errors or warnings"); Log.Comment("are reported when outer names are hidden by inner names."); if (Basic_TestClass_nhide033.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Basic_nhide034_Test() { Log.Comment("Section 3.5.1"); Log.Comment("Name hiding through nesting can occur as a result of"); Log.Comment("nesting namespaces or types within namespaces, as a "); Log.Comment("result of nesting types within classes or structs,"); Log.Comment("and as a result of parameter and local variable"); Log.Comment("declarations. Name hiding through nesting of scopes"); Log.Comment("always occurs silently, i.e. no errors or warnings"); Log.Comment("are reported when outer names are hidden by inner names."); if (Basic_TestClass_nhide034.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Basic_nhide035_Test() { Log.Comment("Section 3.5.1"); Log.Comment("Name hiding through nesting can occur as a result of"); Log.Comment("nesting namespaces or types within namespaces, as a "); Log.Comment("result of nesting types within classes or structs,"); Log.Comment("and as a result of parameter and local variable"); Log.Comment("declarations. Name hiding through nesting of scopes"); Log.Comment("always occurs silently, i.e. no errors or warnings"); Log.Comment("are reported when outer names are hidden by inner names."); if (Basic_TestClass_nhide035.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Basic_nhide036_Test() { Log.Comment("Section 3.5.1"); Log.Comment("Name hiding through nesting can occur as a result of"); Log.Comment("nesting namespaces or types within namespaces, as a "); Log.Comment("result of nesting types within classes or structs,"); Log.Comment("and as a result of parameter and local variable"); Log.Comment("declarations. Name hiding through nesting of scopes"); Log.Comment("always occurs silently, i.e. no errors or warnings"); Log.Comment("are reported when outer names are hidden by inner names."); if (Basic_TestClass_nhide036.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Basic_nhide037_Test() { Log.Comment("Section 3.5.1"); Log.Comment("Name hiding through nesting can occur as a result of"); Log.Comment("nesting namespaces or types within namespaces, as a "); Log.Comment("result of nesting types within classes or structs,"); Log.Comment("and as a result of parameter and local variable"); Log.Comment("declarations. Name hiding through nesting of scopes"); Log.Comment("always occurs silently, i.e. no errors or warnings"); Log.Comment("are reported when outer names are hidden by inner names."); if (Basic_TestClass_nhide037.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Basic_nhide038_Test() { Log.Comment("Section 3.5.1"); Log.Comment("Name hiding through nesting can occur as a result of"); Log.Comment("nesting namespaces or types within namespaces, as a "); Log.Comment("result of nesting types within classes or structs,"); Log.Comment("and as a result of parameter and local variable"); Log.Comment("declarations. Name hiding through nesting of scopes"); Log.Comment("always occurs silently, i.e. no errors or warnings"); Log.Comment("are reported when outer names are hidden by inner names."); if (Basic_TestClass_nhide038.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Basic_nhide039_Test() { Log.Comment("Section 3.5.1"); Log.Comment("Name hiding through nesting can occur as a result of"); Log.Comment("nesting namespaces or types within namespaces, as a "); Log.Comment("result of nesting types within classes or structs,"); Log.Comment("and as a result of parameter and local variable"); Log.Comment("declarations. Name hiding through nesting of scopes"); Log.Comment("always occurs silently, i.e. no errors or warnings"); Log.Comment("are reported when outer names are hidden by inner names."); if (Basic_TestClass_nhide039.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Basic_nhide040_Test() { Log.Comment("Section 3.5.1"); Log.Comment("Name hiding through nesting can occur as a result of"); Log.Comment("nesting namespaces or types within namespaces, as a "); Log.Comment("result of nesting types within classes or structs,"); Log.Comment("and as a result of parameter and local variable"); Log.Comment("declarations. Name hiding through nesting of scopes"); Log.Comment("always occurs silently, i.e. no errors or warnings"); Log.Comment("are reported when outer names are hidden by inner names."); if (Basic_TestClass_nhide040.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Basic_nhide041_Test() { Log.Comment("Section 3.5.1"); Log.Comment("Name hiding through nesting can occur as a result of"); Log.Comment("nesting namespaces or types within namespaces, as a "); Log.Comment("result of nesting types within classes or structs,"); Log.Comment("and as a result of parameter and local variable"); Log.Comment("declarations. Name hiding through nesting of scopes"); Log.Comment("always occurs silently, i.e. no errors or warnings"); Log.Comment("are reported when outer names are hidden by inner names."); if (Basic_TestClass_nhide041.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Basic_nhide042_Test() { Log.Comment("Section 3.5.1"); Log.Comment("Name hiding through nesting can occur as a result of"); Log.Comment("nesting namespaces or types within namespaces, as a "); Log.Comment("result of nesting types within classes or structs,"); Log.Comment("and as a result of parameter and local variable"); Log.Comment("declarations. Name hiding through nesting of scopes"); Log.Comment("always occurs silently, i.e. no errors or warnings"); Log.Comment("are reported when outer names are hidden by inner names."); if (Basic_TestClass_nhide042.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Basic_nhide043_Test() { Log.Comment("Section 3.5.1"); Log.Comment("Name hiding through nesting can occur as a result of"); Log.Comment("nesting namespaces or types within namespaces, as a "); Log.Comment("result of nesting types within classes or structs,"); Log.Comment("and as a result of parameter and local variable"); Log.Comment("declarations. Name hiding through nesting of scopes"); Log.Comment("always occurs silently, i.e. no errors or warnings"); Log.Comment("are reported when outer names are hidden by inner names."); if (Basic_TestClass_nhide043.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Basic_nhide044_Test() { Log.Comment("Section 3.5.1"); Log.Comment("Name hiding through nesting can occur as a result of"); Log.Comment("nesting namespaces or types within namespaces, as a "); Log.Comment("result of nesting types within classes or structs,"); Log.Comment("and as a result of parameter and local variable"); Log.Comment("declarations. Name hiding through nesting of scopes"); Log.Comment("always occurs silently, i.e. no errors or warnings"); Log.Comment("are reported when outer names are hidden by inner names."); if (Basic_TestClass_nhide044.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Basic_nhide045_Test() { Log.Comment("Section 3.5.1"); Log.Comment("When a name in an inner scope hides a name"); Log.Comment("in an outer scope, it hides all overloaded "); Log.Comment("occurrences of that name."); if (Basic_TestClass_nhide045.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Basic_nhide047_Test() { Log.Comment("Section 3.5.1"); Log.Comment("When a name in an inner scope hides a name"); Log.Comment("in an outer scope, it hides all overloaded "); Log.Comment("occurrences of that name."); if (Basic_TestClass_nhide047.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Basic_nhide049_Test() { Log.Comment("Section 3.5.1"); Log.Comment("When a name in an inner scope hides a name"); Log.Comment("in an outer scope, it hides all overloaded "); Log.Comment("occurrences of that name."); if (Basic_TestClass_nhide049.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Basic_nhide050_Test() { Log.Comment("Section 3.5.1"); Log.Comment("When a name in an inner scope hides a name"); Log.Comment("in an outer scope, it hides all overloaded "); Log.Comment("occurrences of that name."); if (Basic_TestClass_nhide050.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Basic_nhide051_Test() { Log.Comment("Section 3.5.1"); Log.Comment("When a name in an inner scope hides a name"); Log.Comment("in an outer scope, it hides all overloaded "); Log.Comment("occurrences of that name."); if (Basic_TestClass_nhide051.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Basic_nhide053_Test() { Log.Comment("Section 3.5.1"); Log.Comment("When a name in an inner scope hides a name"); Log.Comment("in an outer scope, it hides all overloaded "); Log.Comment("occurrences of that name."); if (Basic_TestClass_nhide053.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Basic_nhide055_Test() { Log.Comment("Section 3.5.1"); Log.Comment("When a name in an inner scope hides a name"); Log.Comment("in an outer scope, it hides all overloaded "); Log.Comment("occurrences of that name."); if (Basic_TestClass_nhide055.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Basic_nhide056_Test() { Log.Comment("Section 3.5.1"); Log.Comment("When a name in an inner scope hides a name"); Log.Comment("in an outer scope, it hides all overloaded "); Log.Comment("occurrences of that name."); if (Basic_TestClass_nhide056.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Basic_nhide057_Test() { Log.Comment("Section 3.5.1"); Log.Comment("When a name in an inner scope hides a name"); Log.Comment("in an outer scope, it hides all overloaded "); Log.Comment("occurrences of that name."); if (Basic_TestClass_nhide057.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Basic_nhide059_Test() { Log.Comment("Section 3.5.1"); Log.Comment("When a name in an inner scope hides a name"); Log.Comment("in an outer scope, it hides all overloaded "); Log.Comment("occurrences of that name."); if (Basic_TestClass_nhide059.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Basic_nhide061_Test() { Log.Comment("Section 3.5.1"); Log.Comment("A constant, field, property, event or type introduced"); Log.Comment("in a class or struct hides all base class members with the "); Log.Comment("same name."); if (Basic_TestClass_nhide061.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Basic_nhide062_Test() { Log.Comment("Section 3.5.1"); Log.Comment("A constant, field, property, event or type introduced"); Log.Comment("in a class or struct hides all base class members with the "); Log.Comment("same name."); if (Basic_TestClass_nhide062.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Basic_nhide063_Test() { Log.Comment("Section 3.5.1"); Log.Comment("A constant, field, property, event or type introduced"); Log.Comment("in a class or struct hides all base class members with the "); Log.Comment("same name."); if (Basic_TestClass_nhide063.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Basic_nhide064_Test() { Log.Comment("Section 3.5.1"); Log.Comment("A constant, field, property, event or type introduced"); Log.Comment("in a class or struct hides all base class members with the "); Log.Comment("same name."); if (Basic_TestClass_nhide064.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Basic_nhide067_Test() { Log.Comment("Section 3.5.1"); Log.Comment("A constant, field, property, event or type introduced"); Log.Comment("in a class or struct hides all base class members with the "); Log.Comment("same name."); if (Basic_TestClass_nhide067.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Basic_nhide068_Test() { Log.Comment("Section 3.5.1"); Log.Comment("A constant, field, property, event or type introduced"); Log.Comment("in a class or struct hides all base class members with the "); Log.Comment("same name."); if (Basic_TestClass_nhide068.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Basic_nhide071_Test() { Log.Comment("Section 3.5.1"); Log.Comment("A method introduced in a class or a struct"); Log.Comment("hides all non-method base class members with"); Log.Comment("the same name, and all base class methods"); Log.Comment("with the same signature (method name and"); Log.Comment("parameter count, modifiers, and types)."); if (Basic_TestClass_nhide071.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Basic_nhide072_Test() { Log.Comment("Section 3.5.1"); Log.Comment("A method introduced in a class or a struct"); Log.Comment("hides all non-method base class members with"); Log.Comment("the same name, and all base class methods"); Log.Comment("with the same signature (method name and"); Log.Comment("parameter count, modifiers, and types)."); if (Basic_TestClass_nhide072.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Basic_nhide075_Test() { Log.Comment("Section 3.5.1"); Log.Comment("A method introduced in a class or a struct"); Log.Comment("hides all non-method base class members with"); Log.Comment("the same name, and all base class methods"); Log.Comment("with the same signature (method name and"); Log.Comment("parameter count, modifiers, and types)."); if (Basic_TestClass_nhide075.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Basic_nhide076_Test() { Log.Comment("Section 3.5.1"); Log.Comment("A method introduced in a class or a struct"); Log.Comment("hides all non-method base class members with"); Log.Comment("the same name, and all base class methods"); Log.Comment("with the same signature (method name and"); Log.Comment("parameter count, modifiers, and types)."); if (Basic_TestClass_nhide076.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Basic_nhide077_Test() { Log.Comment("Section 3.5.1"); Log.Comment("A method introduced in a class or a struct"); Log.Comment("hides all non-method base class members with"); Log.Comment("the same name, and all base class methods"); Log.Comment("with the same signature (method name and"); Log.Comment("parameter count, modifiers, and types)."); if (Basic_TestClass_nhide077.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Basic_nhide079_Test() { Log.Comment("Section 3.5.1"); Log.Comment("A method introduced in a class or a struct"); Log.Comment("hides all non-method base class members with"); Log.Comment("the same name, and all base class methods"); Log.Comment("with the same signature (method name and"); Log.Comment("parameter count, modifiers, and types)."); if (Basic_TestClass_nhide079.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Basic_nhide081_Test() { Log.Comment("Section 3.5.1"); Log.Comment("A method introduced in a class or a struct"); Log.Comment("hides all non-method base class members with"); Log.Comment("the same name, and all base class methods"); Log.Comment("with the same signature (method name and"); Log.Comment("parameter count, modifiers, and types)."); if (Basic_TestClass_nhide081.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Basic_nhide082_Test() { Log.Comment("Section 3.5.1"); Log.Comment("A method introduced in a class or a struct"); Log.Comment("hides all non-method base class members with"); Log.Comment("the same name, and all base class methods"); Log.Comment("with the same signature (method name and"); Log.Comment("parameter count, modifiers, and types)."); if (Basic_TestClass_nhide082.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Basic_nhide085_Test() { Log.Comment("Section 3.5.1"); Log.Comment("A method introduced in a class or a struct"); Log.Comment("hides all non-method base class members with"); Log.Comment("the same name, and all base class methods"); Log.Comment("with the same signature (method name and"); Log.Comment("parameter count, modifiers, and types)."); if (Basic_TestClass_nhide085.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Basic_nhide086_Test() { Log.Comment("Section 3.5.1"); Log.Comment("A method introduced in a class or a struct"); Log.Comment("hides all non-method base class members with"); Log.Comment("the same name, and all base class methods"); Log.Comment("with the same signature (method name and"); Log.Comment("parameter count, modifiers, and types)."); if (Basic_TestClass_nhide086.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Basic_nhide087_Test() { Log.Comment("Section 3.5.1"); Log.Comment("A method introduced in a class or a struct"); Log.Comment("hides all non-method base class members with"); Log.Comment("the same name, and all base class methods"); Log.Comment("with the same signature (method name and"); Log.Comment("parameter count, modifiers, and types)."); if (Basic_TestClass_nhide087.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Basic_nhide088_Test() { Log.Comment("Section 3.5.1"); Log.Comment("A method introduced in a class or a struct"); Log.Comment("hides all non-method base class members with"); Log.Comment("the same name, and all base class methods"); Log.Comment("with the same signature (method name and"); Log.Comment("parameter count, modifiers, and types)."); if (Basic_TestClass_nhide088.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Basic_nhide089_Test() { Log.Comment("Section 3.5.1"); Log.Comment("An indexer introduced in a class or a struct"); Log.Comment("hides all base class indexers with the same"); Log.Comment("signature (parameter count and types)."); if (Basic_TestClass_nhide089.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Basic_nhide090_Test() { Log.Comment("Section 3.5.1"); Log.Comment("An indexer introduced in a class or a struct"); Log.Comment("hides all base class indexers with the same"); Log.Comment("signature (parameter count and types)."); if (Basic_TestClass_nhide090.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Basic_nhide091_Test() { Log.Comment("Section 3.5.1"); Log.Comment("Contrary to hiding a name from an outer scope,"); Log.Comment("hding an accessible name from an inherited scope"); Log.Comment("causes a warning to be reported."); if (Basic_TestClass_nhide091.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Basic_nhide092_Test() { Log.Comment("Section 3.5.1"); Log.Comment("A declaration of a new member hides an inherited"); Log.Comment("member only within the scope of the new member."); if (Basic_TestClass_nhide092.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Basic_memac009_Test() { Log.Comment("Section 3.3"); Log.Comment("Then, if M is public, the access is permitted."); if (Basic_TestClass_memac009.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Basic_memac010_Test() { Log.Comment("Section 3.3"); Log.Comment("Then, if M is public, the access is permitted."); if (Basic_TestClass_memac010.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Basic_memac011_Test() { Log.Comment("Section 3.3"); Log.Comment("Otherwise, if M is protected internal, the access"); Log.Comment("is permitted if it occurs within the project in which"); Log.Comment("M is declared, or if it occurs within a class derived "); Log.Comment("from the class in which M is declared and takes place "); Log.Comment("through the derived class type."); if (Basic_TestClass_memac011.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Basic_memac012_Test() { Log.Comment("Section 3.3"); Log.Comment("Otherwise, if M is protected internal, the access"); Log.Comment("is permitted if it occurs within the project in which"); Log.Comment("M is declared, or if it occurs within a class derived "); Log.Comment("from the class in which M is declared and takes place "); Log.Comment("through the derived class type."); if (Basic_TestClass_memac012.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } /* * These tests were removed because they required additional files, they fail in the baseline * [TestMethod] public TestResult Basic_memac013_Test() { Log.Comment("Section 3.3"); Log.Comment("Otherwise, if M is protected internal, the access"); Log.Comment("is permitted if it occurs within the project in which"); Log.Comment("M is declared, or if it occurs within a class derived "); Log.Comment("from the class in which M is declared and takes place "); Log.Comment("through the derived class type."); if (Basic_TestClass_memac013.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Basic_memac014_Test() { Log.Comment("Section 3.3"); Log.Comment("Otherwise, if M is protected internal, the access"); Log.Comment("is permitted if it occurs within the project in which"); Log.Comment("M is declared, or if it occurs within a class derived "); Log.Comment("from the class in which M is declared and takes place "); Log.Comment("through the derived class type."); if (Basic_TestClass_memac014.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } * */ [TestMethod] public TestResult Basic_memac019_Test() { Log.Comment("Section 3.3"); Log.Comment("Otherwise, if M is protected, the access is permitted"); Log.Comment("if it occurs within the class in which M is declared, or"); Log.Comment("if it occurs within a class derived from the class in"); Log.Comment("which M is delared and takes place through the derived class "); Log.Comment("type."); if (Basic_TestClass_memac019.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Basic_memac020_Test() { Log.Comment("Section 3.3"); Log.Comment("Otherwise, if M is protected, the access is permitted"); Log.Comment("if it occurs within the class in which M is declared, or"); Log.Comment("if it occurs within a class derived from the class in"); Log.Comment("which M is delared and takes place through the derived class "); Log.Comment("type."); if (Basic_TestClass_memac020.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Basic_memac021_Test() { Log.Comment("Section 3.3"); Log.Comment("Otherwise, if M is protected, the access is permitted"); Log.Comment("if it occurs within the class in which M is declared, or"); Log.Comment("if it occurs within a class derived from the class in"); Log.Comment("which M is delared and takes place through the derived class "); Log.Comment("type."); if (Basic_TestClass_memac021.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Basic_memac022_Test() { Log.Comment("Section 3.3"); Log.Comment("Otherwise, if M is protected, the access is permitted"); Log.Comment("if it occurs within the class in which M is declared, or"); Log.Comment("if it occurs within a class derived from the class in"); Log.Comment("which M is delared and takes place through the derived class "); Log.Comment("type."); if (Basic_TestClass_memac022.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Basic_memac025_Test() { Log.Comment("Section 3.3"); Log.Comment("Otherwise, if M is protected, the access is permitted"); Log.Comment("if it occurs within the class in which M is declared, or"); Log.Comment("if it occurs within a class derived from the class in"); Log.Comment("which M is delared and takes place through the derived class "); Log.Comment("type."); if (Basic_TestClass_memac025.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Basic_memac027_Test() { Log.Comment("Section 3.3"); Log.Comment("Otherwise, if M is internal, the access is permitted"); Log.Comment("if it occurs within the project in which M is declared."); if (Basic_TestClass_memac027.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Basic_memac029_Test() { Log.Comment("Section 3.3"); Log.Comment("Otherwise, if M is internal, the access is permitted"); Log.Comment("if it occurs within the project in which M is declared."); if (Basic_TestClass_memac029.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Basic_memac030_Test() { Log.Comment("Section 3.3"); Log.Comment("Otherwise, if M is internal, the access is permitted"); Log.Comment("if it occurs within the project in which M is declared."); if (Basic_TestClass_memac030.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Basic_memac033_Test() { Log.Comment("Section 3.3"); Log.Comment("Otherwise, if M is private, the access is permitted"); Log.Comment("if it occurs within the type in which M is declared."); if (Basic_TestClass_memac033.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Basic_memac034_Test() { Log.Comment("Section 3.3"); Log.Comment("Otherwise, if M is private, the access is permitted"); Log.Comment("if it occurs within the type in which M is declared."); if (Basic_TestClass_memac034.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } /* * These tests were skipped because they require extra files, they fail in the baseline. * [TestMethod] public TestResult Basic_memac039_Test() { Log.Comment("VS Bug 75548"); if (Basic_TestClass_memac039.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Basic_memac041_Test() { if (Basic_TestClass_memac041.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } * */ [TestMethod] public TestResult Basic_memac042_Test() { Log.Comment("Section 3.5"); if (Basic_TestClass_memac042.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Basic_memac043_Test() { Log.Comment("Section 3.5"); if (Basic_TestClass_memac043.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Basic_memac044_Test() { Log.Comment("Section 3.5"); if (Basic_TestClass_memac044.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Basic_memac045_Test() { Log.Comment("Section 3.5"); if (Basic_TestClass_memac045.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Basic_memac046_Test() { Log.Comment("Section 3.5"); if (Basic_TestClass_memac046.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Basic_memac047_Test() { Log.Comment("Section 3.5"); if (Basic_TestClass_memac047.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Basic_accon001_Test() { Log.Comment("Section 3.3"); Log.Comment("The direct base class of a class type must be"); Log.Comment("at least as accessible as the class type itself."); if (Basic_TestClass_accon001.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Basic_accon003_Test() { Log.Comment("Section 3.3"); Log.Comment("The direct base class of a class type must be"); Log.Comment("at least as accessible as the class type itself."); if (Basic_TestClass_accon003.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Basic_accon005_Test() { Log.Comment("Section 3.3"); Log.Comment("The direct base class of a class type must be"); Log.Comment("at least as accessible as the class type itself."); if (Basic_TestClass_accon005.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Basic_accon007_Test() { Log.Comment("Section 3.3"); Log.Comment("The direct base class of a class type must be"); Log.Comment("at least as accessible as the class type itself."); if (Basic_TestClass_accon007.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Basic_accon009_Test() { Log.Comment("Section 3.3"); Log.Comment("The direct base class of a class type must be"); Log.Comment("at least as accessible as the class type itself."); if (Basic_TestClass_accon009.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Basic_accon011_Test() { Log.Comment("Section 3.3"); Log.Comment("The direct base class of a class type must be"); Log.Comment("at least as accessible as the class type itself."); if (Basic_TestClass_accon011.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Basic_accon013_Test() { Log.Comment("Section 3.3"); Log.Comment("The direct base class of a class type must be"); Log.Comment("at least as accessible as the class type itself."); if (Basic_TestClass_accon013.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Basic_accon015_Test() { Log.Comment("Section 3.3"); Log.Comment("The direct base class of a class type must be"); Log.Comment("at least as accessible as the class type itself."); if (Basic_TestClass_accon015.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Basic_accon019_Test() { Log.Comment("Section 3.3"); Log.Comment("The direct base class of a class type must be"); Log.Comment("at least as accessible as the class type itself."); if (Basic_TestClass_accon019.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Basic_accon021_Test() { Log.Comment("Section 3.3"); Log.Comment("The direct base class of a class type must be"); Log.Comment("at least as accessible as the class type itself."); if (Basic_TestClass_accon021.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Basic_accon023_Test() { Log.Comment("Section 3.3"); Log.Comment("The explicit base interfaces of an interface "); Log.Comment("type must be at least as accessible as the interface"); Log.Comment("type itself."); if (Basic_TestClass_accon023.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Basic_accon025_Test() { Log.Comment("Section 3.3"); Log.Comment("The explicit base interfaces of an interface "); Log.Comment("type must be at least as accessible as the interface"); Log.Comment("type itself."); if (Basic_TestClass_accon025.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Basic_accon027_Test() { Log.Comment("Section 3.3"); Log.Comment("The explicit base interfaces of an interface "); Log.Comment("type must be at least as accessible as the interface"); Log.Comment("type itself."); if (Basic_TestClass_accon027.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Basic_accon029_Test() { Log.Comment("Section 3.3"); Log.Comment("The explicit base interfaces of an interface "); Log.Comment("type must be at least as accessible as the interface"); Log.Comment("type itself."); if (Basic_TestClass_accon029.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Basic_accon031_Test() { Log.Comment("Section 3.3"); Log.Comment("The explicit base interfaces of an interface "); Log.Comment("type must be at least as accessible as the interface"); Log.Comment("type itself."); if (Basic_TestClass_accon031.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Basic_accon033_Test() { Log.Comment("Section 3.3"); Log.Comment("The return type and parameter types of a delegate"); Log.Comment("type must be at least as accessible as the delegate"); Log.Comment("ytpe itself."); if (Basic_TestClass_accon033.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Basic_accon035_Test() { Log.Comment("Section 3.3"); Log.Comment("The return type and parameter types of a delegate"); Log.Comment("type must be at least as accessible as the delegate"); Log.Comment("ytpe itself."); if (Basic_TestClass_accon035.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Basic_accon037_Test() { Log.Comment("Section 3.3"); Log.Comment("The type of a constant must be at least as"); Log.Comment("accessible as the constant itself."); if (Basic_TestClass_accon037.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Basic_accon039_Test() { Log.Comment("Section 3.3"); Log.Comment("The type of a field must be at least as accessible"); Log.Comment("as the field itself."); if (Basic_TestClass_accon039.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Basic_accon041_Test() { Log.Comment("Section 3.3"); Log.Comment("The return type and parameter types of a method"); Log.Comment("must be at least asaccessible as the method itself."); if (Basic_TestClass_accon041.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Basic_accon043_Test() { Log.Comment("Section 3.3"); Log.Comment("The return type and parameter types of a method"); Log.Comment("must be at least asaccessible as the method itself."); if (Basic_TestClass_accon043.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Basic_accon045_Test() { Log.Comment("Section 3.3"); Log.Comment("The type of a property must be at least as"); Log.Comment("accessible as the property itself."); if (Basic_TestClass_accon045.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Basic_accon047_Test() { Log.Comment("Section 3.3"); Log.Comment("The return type and parameter types of an"); Log.Comment("indexer must be at least as accessible as the"); Log.Comment("indexer itself."); if (Basic_TestClass_accon047.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Basic_accon049_Test() { Log.Comment("Section 3.3"); Log.Comment("The return type and parameter types of an"); Log.Comment("indexer must be at least as accessible as the"); Log.Comment("indexer itself."); if (Basic_TestClass_accon049.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Basic_accon051_Test() { Log.Comment("Section 3.3"); Log.Comment("The return type and parameter types of an"); Log.Comment("operator must be at least as accessible as"); Log.Comment("the operator itself."); if (Basic_TestClass_accon051.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Basic_accon053_Test() { Log.Comment("Section 3.3"); Log.Comment("The return type and parameter types of an"); Log.Comment("operator must be at least as accessible as"); Log.Comment("the operator itself."); if (Basic_TestClass_accon053.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Basic_accon055_Test() { Log.Comment("Section 3.3"); Log.Comment("The parameter types of a constructor must be at least"); Log.Comment("as accessible as the constructor itself."); if (Basic_TestClass_accon055.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } class Basic_TestClass_scope001 { public static int Main_old() { if ((Basic_TestClass_scope001_C1.intI == 1) && (NS_Basic_TestClass_scope001.MyClass2.intI == 2)) { return 0; } else { return 1; } } public static bool testMethod() { return (Main_old() == 0); } } class Basic_TestClass_scope001_C1 { public static int intI = 1; } class Basic_TestClass_scope019 { int intTest = 1; static int intTest2 = 2; string strTest = "test"; static string strTest2 = "test2"; class Basic_TestClass_scope019_C1 { } public Basic_TestClass_scope019() { int intI = intTest; string strS = strTest; Basic_TestClass_scope019_C1 tc = new Basic_TestClass_scope019_C1(); } ~Basic_TestClass_scope019() { int intI = intTest; string strS = strTest; Basic_TestClass_scope019_C1 tc = new Basic_TestClass_scope019_C1(); } public void TestMeth() { int intI = intTest; string strS = strTest; Basic_TestClass_scope019_C1 tc = new Basic_TestClass_scope019_C1(); } public static int Main_old() { int intI = intTest2; string strS = strTest2; Basic_TestClass_scope019_C1 tc = new Basic_TestClass_scope019_C1(); return 0; } public static bool testMethod() { return (Main_old() == 0); } } class Basic_TestClass_scope022_C2 { protected int intTest = 1; public static int intTest2 = 2; internal string strTest = "test"; public static string strTest2 = "test2"; public class Basic_TestClass_scope022 { } } class Basic_TestClass_scope022 : Basic_TestClass_scope022_C2 { public Basic_TestClass_scope022() { int intI = intTest; string strS = strTest; Basic_TestClass_scope022 tc = new Basic_TestClass_scope022(); } ~Basic_TestClass_scope022() { int intI = intTest; string strS = strTest; Basic_TestClass_scope022 tc = new Basic_TestClass_scope022(); } public void TestMeth() { int intI = intTest; string strS = strTest; Basic_TestClass_scope022 tc = new Basic_TestClass_scope022(); } public static int Main_old() { int intI = intTest2; string strS = strTest2; Basic_TestClass_scope022 tc = new Basic_TestClass_scope022(); return 0; } public static bool testMethod() { return (Main_old() == 0); } } class Basic_TestClass_scope023 { public int intTest = 1; class Basic_TestClass_scope023_C1 : Basic_TestClass_scope023 { public int RetInt() { return intTest; } public static int Main_old() { Basic_TestClass_scope023_C1 tc = new Basic_TestClass_scope023_C1(); if (tc.RetInt() == 1) { return 0; } else { return 1; } } } public static bool testMethod() { return (Basic_TestClass_scope023_C1.Main_old() == 0); } } class Basic_TestClass_scope024 { static int intTest = 1; class Basic_TestClass_scope024_C1 { public int RetInt() { return intTest; } public static int Main_old() { Basic_TestClass_scope024_C1 tc = new Basic_TestClass_scope024_C1(); if (tc.RetInt() == 1) { return 0; } else { return 1; } } } public static bool testMethod() { return (Basic_TestClass_scope024_C1.Main_old() == 0); } } struct Basic_TestClass_scope025 { int intTest; static int intTest2; string strTest; static string strTest2; struct Basic_TestClass_scope025_C1 { } public void TestMeth() { int intI = intTest; string strS = strTest; Basic_TestClass_scope025_C1 tc = new Basic_TestClass_scope025_C1(); } public static int Main_old() { int intI = intTest2; string strS = strTest2; Basic_TestClass_scope025_C1 tc = new Basic_TestClass_scope025_C1(); return 0; } public static bool testMethod() { return (Main_old() == 0); } } enum Basic_TestClass_scope027_Enum { aa = 2, bb = aa } public class Basic_TestClass_scope027 { public static int Main_old() { if ((int)Basic_TestClass_scope027_Enum.bb == 2) { return 0; } else { return 1; } } public static bool testMethod() { return (Main_old() == 0); } } public class Basic_TestClass_scope029_C2 { protected int intI; protected string strS; protected Basic_TestClass_scope029_C2(int i, string s) { intI = i; strS = s; } } public class Basic_TestClass_scope029 : Basic_TestClass_scope029_C2 { int intI2; string strS2; public Basic_TestClass_scope029(int i, string s) : base(i, s) { intI2 = i + 1; strS2 = s + "!"; } public static int Main_old() { Basic_TestClass_scope029 test = new Basic_TestClass_scope029(2, "test"); if ((test.intI == 2) && (test.strS == "test") && (test.intI2 == 3) && (test.strS2 == "test!")) { return 0; } else { return 1; } } public static bool testMethod() { return (Main_old() == 0); } } public class Basic_TestClass_scope033 { int intI; string strS; public void Basic_TestClass_scope033_C1(int i, string s) { intI = i; strS = s; } public static int Main_old() { Basic_TestClass_scope033 TC = new Basic_TestClass_scope033(); TC.Basic_TestClass_scope033_C1(2, "test"); if ((TC.intI == 2) && (TC.strS == "test")) { return 0; } else { return 1; } } public static bool testMethod() { return (Main_old() == 0); } } public class Basic_TestClass_scope037 { int intI; string strS; public string this[int i, string s] { get { return s + i; } set { intI = i; strS = s; } } public static int Main_old() { Basic_TestClass_scope037 test = new Basic_TestClass_scope037(); test[2, "test"] = "QQQ"; if ((test[2, "test"] == "test2") && (test.intI == 2) && (test.strS == "test")) { return 0; } else { return 1; } } public static bool testMethod() { return (Main_old() == 0); } } class Basic_TestClass_scope041 { public int intI = 2; public static Basic_TestClass_scope041 operator +(Basic_TestClass_scope041 MyInt) { MyInt.intI = 3; return new Basic_TestClass_scope041(); } public static int Main_old() { Basic_TestClass_scope041 Basic_TestClass_scope041_C1 = new Basic_TestClass_scope041(); Basic_TestClass_scope041 temp = +Basic_TestClass_scope041_C1; if (Basic_TestClass_scope041_C1.intI == 3) { return 0; } else { return 1; } } public static bool testMethod() { return (Main_old() == 0); } } class Basic_TestClass_scope044 { public bool Basic_TestClass_scope044_C1() { int intI = 1; string strS = "test"; if ((intI == 1) && (strS == "test")) { return true; } else { return false; } } public static int Main_old() { int intI = 2; string strS = "test2"; if ((intI != 2) || (strS != "test2")) { return 1; } for (intI = 1; intI < 3; intI++) { int intI2 = 3; string strS2 = "test3"; if ((intI2 != 3) || (strS2 != "test3")) { return 1; } } { int intI3 = 4; string strS3 = "test4"; if ((intI3 != 4) || (strS3 != "test4")) { return 1; } } Basic_TestClass_scope044 TC = new Basic_TestClass_scope044(); if (TC.Basic_TestClass_scope044_C1() == true) { return 0; } else { return 1; } } public static bool testMethod() { return (Main_old() == 0); } } class Basic_TestClass_scope051 { public static int Main_old() { int i = 0; for (int intI = 0; intI < 3; intI++) { int intJ = intI; i++; } if (i == 3) { return 0; } else { return 1; } } public static bool testMethod() { return (Main_old() == 0); } } class Basic_TestClass_scope053 { public static int Main_old() { int Basic_TestClass_scope053_A = 2; goto Basic_TestClass_scope053_A; Basic_TestClass_scope053_A++; Basic_TestClass_scope053_A: Basic_TestClass_scope053_A++; if (Basic_TestClass_scope053_A == 3) { return 0; } else { return 1; } } public static bool testMethod() { return (Main_old() == 0); } } class Basic_TestClass_scope055 { public static int Main_old() { int Basic_TestClass_scope055_A = 2; { goto Basic_TestClass_scope055_A; Basic_TestClass_scope055_A++; } Basic_TestClass_scope055_A: Basic_TestClass_scope055_A++; if (Basic_TestClass_scope055_A == 3) { return 0; } else { return 1; } } public static bool testMethod() { return (Main_old() == 0); } } class Basic_TestClass_scope057 { public static int Main_old() { Basic_TestClass_scope057 TC = new Basic_TestClass_scope057(); if (TC.test()) { return 0; } else { return 1; } } public bool test() { if (intI == 1) { return true; } return false; } int intI = 1; public static bool testMethod() { return (Main_old() == 0); } } struct Basic_TestClass_scope058 { public static int Main_old() { Basic_TestClass_scope058 TS = new Basic_TestClass_scope058(1); if (TS.test()) { return 0; } else { return 1; } } public bool test() { if (intI == 1) { return true; } return false; } public Basic_TestClass_scope058(int i) { intI = i; } int intI; public static bool testMethod() { return (Main_old() == 0); } } enum Basic_TestClass_scope059_Enum { AA = BB, BB = 1 } public class Basic_TestClass_scope059 { public static int Main_old() { if ((int)Basic_TestClass_scope059_Enum.AA == 1) { return 0; } else { return 1; } } public static bool testMethod() { return (Main_old() == 0); } } public class Basic_TestClass_scope061 { void G() { int j = (j = 1); } void H() { int a = 1, b = ++a; } public static int Main_old() { return 0; } public static bool testMethod() { return (Main_old() == 0); } } class Basic_TestClass_scope062_A { } public class Basic_TestClass_scope062 { public static int Main_old() { string Basic_TestClass_scope062_A = "test"; string S = Basic_TestClass_scope062_A; Type t = typeof(Basic_TestClass_scope062_A); if (t != typeof(string)) { return 0; } else { return 1; } } public static bool testMethod() { return (Main_old() == 0); } } public class Basic_TestClass_scope063_C1 { } public class Basic_TestClass_scope063 { static int Basic_TestClass_scope063_C1 = 2; public static int Main_old() { if (Basic_TestClass_scope063_C1 == 2) { return 0; } else { return 1; } } public static bool testMethod() { return (Main_old() == 0); } } public class Basic_TestClass_scope064_C1 { public int intI = 3; } public class Basic_TestClass_scope064 { static int Basic_TestClass_scope064_C1 = 2; public static int Main_old() { Basic_TestClass_scope064_C1 tc = new Basic_TestClass_scope064_C1(); if (tc.intI == 3) { return 0; } else { return 1; } } public static bool testMethod() { return (Main_old() == 0); } } public class Basic_TestClass_scope067_C1 { } public class Basic_TestClass_scope067 { int Basic_TestClass_scope067_C1 = 2; public int TestMeth() { if (Basic_TestClass_scope067_C1 == 2) { return 0; } else { return 1; } } public static int Main_old() { Basic_TestClass_scope067 MC = new Basic_TestClass_scope067(); return MC.TestMeth(); } public static bool testMethod() { return (Main_old() == 0); } } public class Basic_TestClass_scope068_C1 { public int intI = 3; } public class Basic_TestClass_scope068 { int Basic_TestClass_scope068_C1 = 2; public int TestMeth() { Basic_TestClass_scope068_C1 tc = new Basic_TestClass_scope068_C1(); if (tc.intI == 3) { return 0; } else { return 1; } } public static int Main_old() { Basic_TestClass_scope068 MC = new Basic_TestClass_scope068(); return MC.TestMeth(); } public static bool testMethod() { return (Main_old() == 0); } } class Basic_TestClass_scope069 { private class MyInner { public int MyMeth(MyInner2 arg) { return arg.intI; } } protected class MyInner2 { public int intI = 2; } public static int Main_old() { MyInner MI = new MyInner(); if (MI.MyMeth(new MyInner2()) == 2) { return 0; } else { return 1; } } public static bool testMethod() { return (Main_old() == 0); } } class Basic_TestClass_scope070 { protected class MyInner { public int MyMeth(MyInner2 arg) { return arg.intI; } } protected class MyInner2 { public int intI = 2; } public static int Main_old() { MyInner MI = new MyInner(); if (MI.MyMeth(new MyInner2()) == 2) { return 0; } else { return 1; } } public static bool testMethod() { return (Main_old() == 0); } } class Basic_TestClass_scope071 { internal protected class MyInner { public int MyMeth(MyInner2 arg) { return arg.intI; } } internal protected class MyInner2 { public int intI = 2; } public static int Main_old() { MyInner MI = new MyInner(); if (MI.MyMeth(new MyInner2()) == 2) { return 0; } else { return 1; } } public static bool testMethod() { return (Main_old() == 0); } } class Basic_TestClass_scope074 { public static int Main_old() { { L1: int i = 0; } { L1: int i = 0; } { L1: int i = 0; } { L1: int i = 0; } return 0; } public static bool testMethod() { return (Main_old() == 0); } } class Basic_TestClass_nhide007 { public static int Main_old() { if (Basic_TestClass_nhide007_C1.Basic_TestClass_nhide007_C1.intI == 1) { return 0; } else { return 1; } } public static bool testMethod() { return (Main_old() == 0); } } class Basic_TestClass_nhide015 { class Basic_TestClass_nhide015_C1 { public class Basic_TestClass_nhide015_I { public static int intI = 2; } } class Basic_TestClass_nhide015_C2 { public static int Main_old() { if (Basic_TestClass_nhide015_C1.Basic_TestClass_nhide015_I.intI == 2) { Log.Comment("foo"); return 0; } else { return 1; } } } public static bool testMethod() { return (Basic_TestClass_nhide015_C2.Main_old() == 0); } } class Basic_TestClass_nhide016_C1 { public class Basic_TestClass_nhide016_I { public static int intI = 1; } } class Basic_TestClass_nhide016 { class Basic_TestClass_nhide016_C1 { public class Basic_TestClass_nhide016_I { public static int intI = 2; } } class Basic_TestClass_nhide016_C2 { public static int Main_old() { if (Basic_TestClass_nhide016_C1.Basic_TestClass_nhide016_I.intI == 2) { return 0; } else { return 1; } } } public static bool testMethod() { return (Basic_TestClass_nhide016_C2.Main_old() == 0); } } struct Basic_TestClass_nhide017_St1 { public class Basic_TestClass_nhide017_I { public static int intI = 1; } } class Basic_TestClass_nhide017 { struct Basic_TestClass_nhide017_St1 { public class Basic_TestClass_nhide017_I { public static int intI = 2; } } class Basic_TestClass_nhide017_C2 { public static int Main_old() { if (Basic_TestClass_nhide017_St1.Basic_TestClass_nhide017_I.intI == 2) { return 0; } else { return 1; } } } public static bool testMethod() { return (Basic_TestClass_nhide017_C2.Main_old() == 0); } } interface Basic_TestClass_nhide018_Inter { void bogus(); } class Basic_TestClass_nhide018 { interface Basic_TestClass_nhide018_Inter { void test(); } class Basic_TestClass_nhide018_C2 : Basic_TestClass_nhide018_Inter { public void test() { } public static int Main_old() { return 0; } } public static bool testMethod() { return (Basic_TestClass_nhide018_C2.Main_old() == 0); } } enum Basic_TestClass_nhide019_Enum { test = 1 } class Basic_TestClass_nhide019 { enum Basic_TestClass_nhide019_Enum { test = 2 } class Basic_TestClass_nhide019_C2 { public static int Main_old() { if ((int)Basic_TestClass_nhide019_Enum.test == 2) { return 0; } else { return 1; } } } public static bool testMethod() { return (Basic_TestClass_nhide019_C2.Main_old() == 0); } } delegate void Basic_TestClass_nhide020_Del(); class Basic_TestClass_nhide020 { delegate int Basic_TestClass_nhide020_Del(int intI); class Basic_TestClass_nhide020_C2 { int TestMeth(int intI) { return 1; } public static int Main_old() { Basic_TestClass_nhide020_C2 test = new Basic_TestClass_nhide020_C2(); Basic_TestClass_nhide020_Del td = new Basic_TestClass_nhide020_Del(test.TestMeth); return 0; } } public static bool testMethod() { return (Basic_TestClass_nhide020_C2.Main_old() == 0); } } class Basic_TestClass_nhide021_C1 { public class Basic_TestClass_nhide021_I { public static int intI = 1; } } class T_Basic_TestClass_nhide021 { class Basic_TestClass_nhide021_C1 { public class Basic_TestClass_nhide021_I { public static int intI = 2; } } } class Basic_TestClass_nhide021 { public static int Main_old() { if (Basic_TestClass_nhide021_C1.Basic_TestClass_nhide021_I.intI == 1) { return 0; } else { return 1; } } public static bool testMethod() { return (Main_old() == 0); } } struct Basic_TestClass_nhide022 { class Basic_TestClass_nhide022_C1 { public class Basic_TestClass_nhide022_I { public static int intI = 2; } } class Basic_TestClass_nhide022_C2 { public static int Main_old() { if (Basic_TestClass_nhide022_C1.Basic_TestClass_nhide022_I.intI == 2) { Log.Comment("foo"); return 0; } else { return 1; } } } public static bool testMethod() { return (Basic_TestClass_nhide022_C2.Main_old() == 0); } } //Compiled Test Cases class Basic_TestClass_nhide023_C1 { public class Basic_TestClass_nhide023_I { public static int intI = 1; } } struct Basic_TestClass_nhide023 { class Basic_TestClass_nhide023_C1 { public class Basic_TestClass_nhide023_I { public static int intI = 2; } } class Basic_TestClass_nhide023_C2 { public static int Main_old() { if (Basic_TestClass_nhide023_C1.Basic_TestClass_nhide023_I.intI == 2) { return 0; } else { return 1; } } } public static bool testMethod() { return (Basic_TestClass_nhide023_C2.Main_old() == 0); } } struct Basic_TestClass_nhide024_St1 { public class Basic_TestClass_nhide024_I { public static int intI = 1; } } struct Basic_TestClass_nhide024 { struct Basic_TestClass_nhide024_St1 { public class Basic_TestClass_nhide024_I { public static int intI = 2; } } class Basic_TestClass_nhide024_C1 { public static int Main_old() { if (Basic_TestClass_nhide024_St1.Basic_TestClass_nhide024_I.intI == 2) { Log.Comment("foo"); return 0; } else { return 1; } } } public static bool testMethod() { return (Basic_TestClass_nhide024_C1.Main_old() == 0); } } interface Basic_TestClass_nhide025_Inter { void bogus(); } struct Basic_TestClass_nhide025 { interface Basic_TestClass_nhide025_Inter { void test(); } class Basic_TestClass_nhide025_C1 : Basic_TestClass_nhide025_Inter { public void test() { } public static int Main_old() { return 0; } } public static bool testMethod() { return (Basic_TestClass_nhide025_C1.Main_old() == 0); } } enum Basic_TestClass_nhide026_Enum { test = 1 } struct Basic_TestClass_nhide026 { enum Basic_TestClass_nhide026_Enum { test = 2 } class Basic_TestClass_nhide026_C1 { public static int Main_old() { if ((int)Basic_TestClass_nhide026_Enum.test == 2) { return 0; } else { return 1; } } } public static bool testMethod() { return (Basic_TestClass_nhide026_C1.Main_old() == 0); } } delegate void Basic_TestClass_nhide027_Del(); struct Basic_TestClass_nhide027 { delegate int Basic_TestClass_nhide027_Del(int intI); class Basic_TestClass_nhide027_C1 { int TestMeth(int intI) { return 1; } public static int Main_old() { Basic_TestClass_nhide027_C1 test = new Basic_TestClass_nhide027_C1(); Basic_TestClass_nhide027_Del td = new Basic_TestClass_nhide027_Del(test.TestMeth); return 0; } } public static bool testMethod() { return (Basic_TestClass_nhide027_C1.Main_old() == 0); } } class Basic_TestClass_nhide028_C1 { public class Basic_TestClass_nhide028_I { public static int intI = 1; } } struct Basic_TestClass_nhide028_St2 { class Basic_TestClass_nhide028_C1 { public class Basic_TestClass_nhide028_I { public static int intI = 2; } } } class Basic_TestClass_nhide028 { public static int Main_old() { if (Basic_TestClass_nhide028_C1.Basic_TestClass_nhide028_I.intI == 1) { return 0; } else { return 1; } } public static bool testMethod() { return (Main_old() == 0); } } class Basic_TestClass_nhide029 { public int intI = 1; public bool Basic_TestClass_nhide029_C1(int intI) { if (intI == 2) { return true; } return false; } public static int Main_old() { Basic_TestClass_nhide029 test = new Basic_TestClass_nhide029(); if (test.Basic_TestClass_nhide029_C1(2)) { return 0; } else { return 1; } } public static bool testMethod() { return (Main_old() == 0); } } class Basic_TestClass_nhide030 { public string strS = "test1"; public bool Basic_TestClass_nhide030_C1(string strS) { if (strS == "test2") { return true; } return false; } public static int Main_old() { Basic_TestClass_nhide030 test = new Basic_TestClass_nhide030(); if (test.Basic_TestClass_nhide030_C1("test2")) { return 0; } else { return 1; } } public static bool testMethod() { return (Main_old() == 0); } } class Basic_TestClass_nhide031 { public static int intI = 1; public static bool Basic_TestClass_nhide031_C1(int intI) { if (intI == 2) { return true; } return false; } public static int Main_old() { if (Basic_TestClass_nhide031.Basic_TestClass_nhide031_C1(2)) { return 0; } else { return 1; } } public static bool testMethod() { return (Main_old() == 0); } } class Basic_TestClass_nhide032 { public static string strS = "test1"; public static bool Basic_TestClass_nhide032_C1(string strS) { if (strS == "test2") { return true; } return false; } public static int Main_old() { if (Basic_TestClass_nhide032.Basic_TestClass_nhide032_C1("test2")) { return 0; } else { return 1; } } public static bool testMethod() { return (Main_old() == 0); } } class Basic_TestClass_nhide033 { public int intI = 1; public int intJ = 2; public bool Basic_TestClass_nhide033_C1(int intI, int intJ) { if ((intI == 2) && (intJ == 3)) { return true; } return false; } public static int Main_old() { Basic_TestClass_nhide033 test = new Basic_TestClass_nhide033(); if (test.Basic_TestClass_nhide033_C1(2, 3)) { return 0; } else { return 1; } } public static bool testMethod() { return (Main_old() == 0); } } class Basic_TestClass_nhide034 { public string strS = "test1"; public string strS2 = "test2"; public bool Basic_TestClass_nhide034_C1(string strS, string strS2) { if ((strS == "test2") && (strS2 == "test3")) { return true; } return false; } public static int Main_old() { Basic_TestClass_nhide034 test = new Basic_TestClass_nhide034(); if (test.Basic_TestClass_nhide034_C1("test2", "test3")) { return 0; } else { return 1; } } public static bool testMethod() { return (Main_old() == 0); } } class Basic_TestClass_nhide035 { public int intI = 1; public bool Basic_TestClass_nhide035_C1(ref int intI) { if (intI == 2) { return true; } return false; } public static int Main_old() { int intJ = 2; Basic_TestClass_nhide035 test = new Basic_TestClass_nhide035(); if (test.Basic_TestClass_nhide035_C1(ref intJ)) { return 0; } else { return 1; } } public static bool testMethod() { return (Main_old() == 0); } } class Basic_TestClass_nhide036 { public string strS = "test1"; public bool Basic_TestClass_nhide036_C1(ref string strS) { if (strS == "test2") { return true; } return false; } public static int Main_old() { string strTest = "test2"; Basic_TestClass_nhide036 test = new Basic_TestClass_nhide036(); if (test.Basic_TestClass_nhide036_C1(ref strTest)) { return 0; } else { return 1; } } public static bool testMethod() { return (Main_old() == 0); } } class Basic_TestClass_nhide037 { public int intI = 1; public void Basic_TestClass_nhide037_C1(out int intI) { intI = 2; } public static int Main_old() { int intJ; Basic_TestClass_nhide037 test = new Basic_TestClass_nhide037(); test.Basic_TestClass_nhide037_C1(out intJ); if ((test.intI == 1) && (intJ == 2)) { return 0; } else { return 1; } } public static bool testMethod() { return (Main_old() == 0); } } class Basic_TestClass_nhide038 { public string strS = "test1"; public void Basic_TestClass_nhide038_C1(out string strS) { strS = "test2"; } public static int Main_old() { string strTest; Basic_TestClass_nhide038 test = new Basic_TestClass_nhide038(); test.Basic_TestClass_nhide038_C1(out strTest); if ((test.strS == "test1") && (strTest == "test2")) { return 0; } else { return 1; } } public static bool testMethod() { return (Main_old() == 0); } } class Basic_TestClass_nhide039 { public static int intI = 1; public static int Main_old() { int intI = 2; if (intI == 2) { return 0; } else { return 1; } } public static bool testMethod() { return (Main_old() == 0); } } class Basic_TestClass_nhide040 { public static string strS = "test"; public static int Main_old() { string strS = "test2"; if (strS == "test2") { return 0; } else { return 1; } } public static bool testMethod() { return (Main_old() == 0); } } class Basic_TestClass_nhide041 { int intI = 1; bool Test1() { int intI = 2; if (intI == 2) { return true; } return false; } bool Test2() { if (intI == 1) { return true; } else { return false; } } public static int Main_old() { Basic_TestClass_nhide041 test = new Basic_TestClass_nhide041(); if (test.Test1() && test.Test2()) { return 0; } else { return 1; } } public static bool testMethod() { return (Main_old() == 0); } } class Basic_TestClass_nhide042 { string strS = "test2"; bool Test1() { string strS = "test1"; if (strS == "test1") { return true; } return false; } bool Test2() { if (strS == "test2") { return true; } else { return false; } } public static int Main_old() { Basic_TestClass_nhide042 test = new Basic_TestClass_nhide042(); if (test.Test1() && test.Test2()) { return 0; } else { return 1; } } public static bool testMethod() { return (Main_old() == 0); } } class Basic_TestClass_nhide043 { int intI = 1; bool Test1() { int intI = 2; if (intI == 2) { return true; } return false; } bool Test2() { int intI = 3; if (intI == 3) { return true; } return false; } public static int Main_old() { Basic_TestClass_nhide043 test = new Basic_TestClass_nhide043(); if (test.Test1() && test.Test2()) { return 0; } else { return 1; } } public static bool testMethod() { return (Main_old() == 0); } } class Basic_TestClass_nhide044 { string strS = "test2"; bool Test1() { string strS = "test1"; if (strS == "test1") { return true; } return false; } bool Test2() { string strS = "test2"; if (strS == "test2") { return true; } return false; } public static int Main_old() { Basic_TestClass_nhide044 test = new Basic_TestClass_nhide044(); if (test.Test1() && test.Test2()) { return 0; } else { return 1; } } public static bool testMethod() { return (Main_old() == 0); } } class Basic_TestClass_nhide045 { static int Basic_TestClass_nhide045_C1(int intI) { return -1; } static int Basic_TestClass_nhide045_C1(string s) { return -1; } class Basic_TestClass_nhide045_I { static int Basic_TestClass_nhide045_C1(int intI) { return intI; } public static int Main_old() { if (Basic_TestClass_nhide045_C1(2) == 2) { return 0; } else { return 1; } } } public static bool testMethod() { return (Basic_TestClass_nhide045_I.Main_old() == 0); } } class Basic_TestClass_nhide047 { static int Basic_TestClass_nhide047_C1() { return 1; } class Basic_TestClass_nhide047_I { static int Basic_TestClass_nhide047_C1 = 2; public static int Main_old() { if (Basic_TestClass_nhide047_C1 == 2) { return 0; } else { return 1; } } } public static bool testMethod() { return (Basic_TestClass_nhide047_I.Main_old() == 0); } } class Basic_TestClass_nhide049 { class Basic_TestClass_nhide049_C1 { } class Basic_TestClass_nhide049_I { static int Basic_TestClass_nhide049_C1 = 2; public static int Main_old() { if (Basic_TestClass_nhide049_C1 == 2) { return 0; } else { return 1; } } } public static bool testMethod() { return (Basic_TestClass_nhide049_I.Main_old() == 0); } } class Basic_TestClass_nhide050 { class Basic_TestClass_nhide050_C1 { public int intI = 3; } class Basic_TestClass_nhide050_I { public static int Basic_TestClass_nhide050_C1 = 2; public static int Main_old() { Basic_TestClass_nhide050_C1 t = new Basic_TestClass_nhide050_C1(); if (t.intI == 3) { return 0; } else { return 1; } } } public static bool testMethod() { return (Basic_TestClass_nhide050_I.Main_old() == 0); } } class Basic_TestClass_nhide051 { static int Basic_TestClass_nhide051_C1(int intI) { return -1; } static int Basic_TestClass_nhide051_C1(string s) { return -1; } class Basic_TestClass_nhide051_I { int Basic_TestClass_nhide051_C1(int intI) { return intI; } public int RetVal() { if (Basic_TestClass_nhide051_C1(2) == 2) { return 0; } else { return 1; } } public static int Main_old() { Basic_TestClass_nhide051_I MC = new Basic_TestClass_nhide051_I(); return MC.RetVal(); } } public static bool testMethod() { return (Basic_TestClass_nhide051_I.Main_old() == 0); } } class Basic_TestClass_nhide053 { static int Basic_TestClass_nhide053_C1() { return 1; } class Basic_TestClass_nhide053_I { int Basic_TestClass_nhide053_C1 = 2; public int RetVal() { if (Basic_TestClass_nhide053_C1 == 2) { return 0; } else { return 1; } } public static int Main_old() { Basic_TestClass_nhide053_I MC = new Basic_TestClass_nhide053_I(); return MC.RetVal(); } } public static bool testMethod() { return (Basic_TestClass_nhide053_I.Main_old() == 0); } } class Basic_TestClass_nhide055 { class Basic_TestClass_nhide055_C1 { } class Basic_TestClass_nhide055_I { int Basic_TestClass_nhide055_C1 = 2; public int RetVal() { if (Basic_TestClass_nhide055_C1 == 2) { return 0; } else { return 1; } } public static int Main_old() { Basic_TestClass_nhide055_I MC = new Basic_TestClass_nhide055_I(); return MC.RetVal(); } } public static bool testMethod() { return (Basic_TestClass_nhide055_I.Main_old() == 0); } } class Basic_TestClass_nhide056 { class Basic_TestClass_nhide056_C1 { } class Basic_TestClass_nhide056_I { int Basic_TestClass_nhide056_C1 = 2; public void RetVal() { Basic_TestClass_nhide056_C1 tc = new Basic_TestClass_nhide056_C1(); } public static int Main_old() { return 0; } } public static bool testMethod() { return (Basic_TestClass_nhide056_I.Main_old() == 0); } } class Basic_TestClass_nhide057_C4 { public int intRet() { return 2; } } class Basic_TestClass_nhide057 { class Basic_TestClass_nhide057_C1 { public static int intRet() { return 1; } } class Basic_TestClass_nhide057_I { static Basic_TestClass_nhide057_C4 Basic_TestClass_nhide057_C1 = new Basic_TestClass_nhide057_C4(); public static int Main_old() { if (Basic_TestClass_nhide057_C1.intRet() == 2) { return 0; } else { return 1; } } } public static bool testMethod() { return (Basic_TestClass_nhide057_I.Main_old() == 0); } } class Basic_TestClass_nhide059_C4 { public int intRet() { return 2; } } class Basic_TestClass_nhide059 { class Basic_TestClass_nhide059_C1 { public static int intRet() { return 1; } } class Basic_TestClass_nhide059_I { public int TestMeth() { Basic_TestClass_nhide059_C4 Basic_TestClass_nhide059_C1 = new Basic_TestClass_nhide059_C4(); return Basic_TestClass_nhide059_C1.intRet(); } public static int Main_old() { Basic_TestClass_nhide059_I TC = new Basic_TestClass_nhide059_I(); if (TC.TestMeth() == 2) { return 0; } else { return 1; } } } public static bool testMethod() { return (Basic_TestClass_nhide059_I.Main_old() == 0); } } class Basic_TestClass_nhide061_C5 { public const int intI = 1; } class Basic_TestClass_nhide061 : Basic_TestClass_nhide061_C5 { public const int intI = 2; public static int Main_old() { if (intI == 2) { return 0; } else { return 1; } } public static bool testMethod() { return (Main_old() == 0); } } class Basic_TestClass_nhide062_C5 { public int intI = 1; } class Basic_TestClass_nhide062 : Basic_TestClass_nhide062_C5 { public int intI = 2; public static int Main_old() { Basic_TestClass_nhide062 test = new Basic_TestClass_nhide062(); if (test.intI == 2) { return 0; } else { return 1; } } public static bool testMethod() { return (Main_old() == 0); } } class Basic_TestClass_nhide063_C5 { public int intI { get { return 1; } } } class Basic_TestClass_nhide063 : Basic_TestClass_nhide063_C5 { public int intI { get { return 2; } } public static int Main_old() { Basic_TestClass_nhide063 test = new Basic_TestClass_nhide063(); if (test.intI == 2) { return 0; } else { return 1; } } public static bool testMethod() { return (Main_old() == 0); } } class Basic_TestClass_nhide064_C5 { public class Basic_TestClass_nhide064_C1 { public int intI = 1; } } class Basic_TestClass_nhide064 : Basic_TestClass_nhide064_C5 { public class Basic_TestClass_nhide064_C1 { public int intI = 2; } public static int Main_old() { Basic_TestClass_nhide064_C1 test = new Basic_TestClass_nhide064_C1(); if (test.intI == 2) { return 0; } else { return 1; } } public static bool testMethod() { return (Main_old() == 0); } } class Basic_TestClass_nhide067_C5 { public int intI { get { return 1; } } } class Basic_TestClass_nhide067 : Basic_TestClass_nhide067_C5 { public class intI { public int i = 2; } public static int Main_old() { intI test = new intI(); if (test.i == 2) { return 0; } else { return 1; } } public static bool testMethod() { return (Main_old() == 0); } } class Basic_TestClass_nhide068_C5 { public class intI { public int i = 2; } } class Basic_TestClass_nhide068 : Basic_TestClass_nhide068_C5 { const int intI = 3; public static int Main_old() { intI test = new intI(); if ((test.i == 2) && (intI == 3)) { return 0; } else { return 1; } } public static bool testMethod() { return (Main_old() == 0); } } class Basic_TestClass_nhide071_C5 { public int MyMeth = 1; } class Basic_TestClass_nhide071 : Basic_TestClass_nhide071_C5 { public int MyMeth() { return 2; } public static int Main_old() { Basic_TestClass_nhide071 test = new Basic_TestClass_nhide071(); if (test.MyMeth() == 2) { return 0; } else { return 1; } } public static bool testMethod() { return (Main_old() == 0); } } class Basic_TestClass_nhide072_C5 { public static int MyMeth = 1; } class Basic_TestClass_nhide072 : Basic_TestClass_nhide072_C5 { public static int MyMeth() { return 2; } public static int Main_old() { if (MyMeth() == 2) { return 0; } else { return 1; } } public static bool testMethod() { return (Main_old() == 0); } } class Basic_TestClass_nhide075_C5 { public int MyMeth(int intI) { return intI; } } class Basic_TestClass_nhide075 : Basic_TestClass_nhide075_C5 { public int MyMeth(int intI) { return intI + 1; } public static int Main_old() { Basic_TestClass_nhide075 test = new Basic_TestClass_nhide075(); if (test.MyMeth(2) == 3) { return 0; } else { return 1; } } public static bool testMethod() { return (Main_old() == 0); } } class Basic_TestClass_nhide076_C5 { public static int MyMeth(int intI) { return intI; } } class Basic_TestClass_nhide076 : Basic_TestClass_nhide076_C5 { public static int MyMeth(int intI) { return intI + 1; } public static int Main_old() { if (MyMeth(2) == 3) { return 0; } else { return 1; } } public static bool testMethod() { return (Main_old() == 0); } } class Basic_TestClass_nhide077_C5 { public static int MyMeth(int intI) { return intI; } } class Basic_TestClass_nhide077 : Basic_TestClass_nhide077_C5 { public int MyMeth(int intI) { return intI + 1; } public static int Main_old() { Basic_TestClass_nhide077 test = new Basic_TestClass_nhide077(); if (test.MyMeth(2) == 3) { return 0; } else { return 1; } } public static bool testMethod() { return (Main_old() == 0); } } class Basic_TestClass_nhide079_C5 { public int MyMeth(int intI) { return intI; } } class Basic_TestClass_nhide079 : Basic_TestClass_nhide079_C5 { public static int MyMeth(int intI) { return intI + 1; } public static int Main_old() { if (MyMeth(2) == 3) { return 0; } else { return 1; } } public static bool testMethod() { return (Main_old() == 0); } } class Basic_TestClass_nhide081_C5 { public int MyMeth() { return 1; } public int MyMeth(int intI) { return intI; } } class Basic_TestClass_nhide081 : Basic_TestClass_nhide081_C5 { public int MyMeth(int intI) { return intI + 1; } public static int Main_old() { Basic_TestClass_nhide081 test = new Basic_TestClass_nhide081(); if (test.MyMeth() == 1) { return 0; } else { return 1; } } public static bool testMethod() { return (Main_old() == 0); } } class Basic_TestClass_nhide082_C5 { public static int MyMeth() { return 1; } public static int MyMeth(int intI) { return intI; } } class Basic_TestClass_nhide082 : Basic_TestClass_nhide082_C5 { public static int MyMeth(int intI) { return intI + 1; } public static int Main_old() { if (MyMeth() == 1) { return 0; } else { return 1; } } public static bool testMethod() { return (Main_old() == 0); } } class Basic_TestClass_nhide085_C5 { public int MyMeth(int intI) { return intI; } } class Basic_TestClass_nhide085 : Basic_TestClass_nhide085_C5 { public int MyMeth(string strS) { return 1; } public static int Main_old() { Basic_TestClass_nhide085 test = new Basic_TestClass_nhide085(); if ((test.MyMeth(2) == 2) && (test.MyMeth("bogus") == 1)) { return 0; } else { return 1; } } public static bool testMethod() { return (Main_old() == 0); } } class Basic_TestClass_nhide086_C5 { public static int MyMeth(int intI) { return intI; } } class Basic_TestClass_nhide086 : Basic_TestClass_nhide086_C5 { public static int MyMeth(string strS) { return 1; } public static int Main_old() { if ((MyMeth(2) == 2) && (MyMeth("bogus") == 1)) { return 0; } else { return 1; } } public static bool testMethod() { return (Main_old() == 0); } } struct Basic_TestClass_nhide087 { public string ToString() { return "MyTestStruct"; } public static int Main_old() { Basic_TestClass_nhide087 test = new Basic_TestClass_nhide087(); if (test.ToString() == "MyTestStruct") { return 0; } else { return 1; } } public static bool testMethod() { return (Main_old() == 0); } } struct Basic_TestClass_nhide088 { public string ToString(string strS) { return strS; } public static int Main_old() { Basic_TestClass_nhide088 test = new Basic_TestClass_nhide088(); string s1 = test.ToString(); string s2 = test.ToString("Basic_TestClass_nhide088"); if ((s1 == "Microsoft.Zelig.Test.BasicConceptTests.Basic_TestClass_nhide088") && (s2 == "Basic_TestClass_nhide088")) { return 0; } else { return 1; } } public static bool testMethod() { return (Main_old() == 0); } } public class Basic_TestClass_nhide089_C2 { public int this[int intI] { get { return intI; } } } public class Basic_TestClass_nhide089 : Basic_TestClass_nhide089_C2 { public int this[int intI] { get { return intI + 1; } } public static int Main_old() { Basic_TestClass_nhide089 test = new Basic_TestClass_nhide089(); if (test[3] == 4) { return 0; } else { return 1; } } public static bool testMethod() { return (Main_old() == 0); } } public class Basic_TestClass_nhide090_C2 { public int this[long lngL] { get { return (int)lngL; } } } public class Basic_TestClass_nhide090 : Basic_TestClass_nhide090_C2 { public int this[int intI] { get { return intI + 1; } } public static int Main_old() { Basic_TestClass_nhide090 test = new Basic_TestClass_nhide090(); if ((test[(long)3] == 3) && (test[(int)3] == 4)) { return 0; } else { return 1; } } public static bool testMethod() { return (Main_old() == 0); } } public class Basic_TestClass_nhide091_C2 { public void F() { } } public class Basic_TestClass_nhide091 : Basic_TestClass_nhide091_C2 { public void F() { } public static int Main_old() { return 0; } public static bool testMethod() { return (Main_old() == 0); } } public class Basic_TestClass_nhide092_C2 { public static int F() { return 2; } } public class Basic_TestClass_nhide092_C6 : Basic_TestClass_nhide092_C2 { new private static int F() { return 3; } } public class Basic_TestClass_nhide092 : Basic_TestClass_nhide092_C6 { public static int Main_old() { if (F() == 2) { return 0; } else { return 1; } } public static bool testMethod() { return (Main_old() == 0); } } public class Basic_TestClass_memac009_O { public class Basic_TestClass_memac009_C1 { public int intI = 2; } } public class Basic_TestClass_memac009 { public static int Main_old() { Basic_TestClass_memac009_O.Basic_TestClass_memac009_C1 tc = new Basic_TestClass_memac009_O.Basic_TestClass_memac009_C1(); if (tc.intI == 2) { return 0; } else { return 1; } } public static bool testMethod() { return (Main_old() == 0); } } public class Basic_TestClass_memac010_C1 { public static int intI = 2; } public class Basic_TestClass_memac010 { public static int Main_old() { if (Basic_TestClass_memac010_C1.intI == 2) { return 0; } else { return 1; } } public static bool testMethod() { return (Main_old() == 0); } } public class Basic_TestClass_memac011_O { protected internal class Basic_TestClass_memac011_C1 { public int intI = 2; } } public class Basic_TestClass_memac011 { public static int Main_old() { Basic_TestClass_memac011_O.Basic_TestClass_memac011_C1 tc = new Basic_TestClass_memac011_O.Basic_TestClass_memac011_C1(); if (tc.intI == 2) { return 0; } else { return 1; } } public static bool testMethod() { return (Main_old() == 0); } } public class Basic_TestClass_memac012_O { protected static internal int intI = 2; } public class Basic_TestClass_memac012 { public static int Main_old() { if (Basic_TestClass_memac012_O.intI == 2) { return 0; } else { return 1; } } public static bool testMethod() { return (Main_old() == 0); } } /* public class Basic_TestClass_memac013 : Basic_TestClass_memac013_O { public static int Main_old() { Basic_TestClass_memac013_C1 tc = new Basic_TestClass_memac013_C1(); if (tc.intI == 2) { return 0; } else { return 1; } } public static bool testMethod() { return (Main_old() == 0); } } public class Basic_TestClass_memac014 : Basic_TestClass_memac014_O { public static int Main_old() { if (intI == 2) { return 0; } else { return 1; } } public static bool testMethod() { return (Main_old() == 0); } } * */ public class Basic_TestClass_memac019 { protected class Basic_TestClass_memac019_C1 { public int intI = 2; public static int Main_old() { Basic_TestClass_memac019_C1 tc = new Basic_TestClass_memac019_C1(); if (tc.intI == 2) { return 0; } else { return 1; } } } public static bool testMethod() { return (Basic_TestClass_memac019_C1.Main_old() == 0); } } public class Basic_TestClass_memac020 { protected static int intI = 2; public static int Main_old() { if (intI == 2) { return 0; } else { return 1; } } public static bool testMethod() { return (Main_old() == 0); } } public class Basic_TestClass_memac021_O { protected class Basic_TestClass_memac021_C1 { public int intI = 2; } } public class Basic_TestClass_memac021 : Basic_TestClass_memac021_O { public static int Main_old() { Basic_TestClass_memac021_C1 tc = new Basic_TestClass_memac021_C1(); if (tc.intI == 2) { return 0; } else { return 1; } } public static bool testMethod() { return (Main_old() == 0); } } public class Basic_TestClass_memac022_O { protected static int intI = 2; } public class Basic_TestClass_memac022 : Basic_TestClass_memac022_O { public static int Main_old() { if (intI == 2) { return 0; } else { return 1; } } public static bool testMethod() { return (Main_old() == 0); } } public class Basic_TestClass_memac025_O { protected class Basic_TestClass_memac025_C1 { public int intI = 2; } } public class Basic_TestClass_memac025 : Basic_TestClass_memac025_O { public static int Main_old() { Basic_TestClass_memac025_O.Basic_TestClass_memac025_C1 tc = new Basic_TestClass_memac025_O.Basic_TestClass_memac025_C1(); if (tc.intI == 2) { return 0; } else { return 1; } } public static bool testMethod() { return (Main_old() == 0); } } internal class Basic_TestClass_memac027_C1 { public int intI = 2; } public class Basic_TestClass_memac027 { public static int Main_old() { Basic_TestClass_memac027_C1 TC = new Basic_TestClass_memac027_C1(); if (TC.intI == 2) { return 0; } else { return 1; } } public static bool testMethod() { return (Main_old() == 0); } } public class Basic_TestClass_memac029_O { internal class Basic_TestClass_memac029_C1 { public int intI = 2; } } public class Basic_TestClass_memac029 { public static int Main_old() { Basic_TestClass_memac029_O.Basic_TestClass_memac029_C1 TC = new Basic_TestClass_memac029_O.Basic_TestClass_memac029_C1(); if (TC.intI == 2) { return 0; } else { return 1; } } public static bool testMethod() { return (Main_old() == 0); } } public class Basic_TestClass_memac030_O { static internal int intI = 2; } public class Basic_TestClass_memac030 { public static int Main_old() { if (Basic_TestClass_memac030_O.intI == 2) { return 0; } else { return 1; } } public static bool testMethod() { return (Main_old() == 0); } } public class Basic_TestClass_memac033 { private class Basic_TestClass_memac033_C1 { public int intI = 2; public static int Main_old() { Basic_TestClass_memac033_C1 tc = new Basic_TestClass_memac033_C1(); if (tc.intI == 2) { return 0; } else { return 1; } } } public static bool testMethod() { return (Basic_TestClass_memac033_C1.Main_old() == 0); } } public class Basic_TestClass_memac034 { private static int intI = 2; public static int Main_old() { if (intI == 2) { return 0; } else { return 1; } } public static bool testMethod() { return (Main_old() == 0); } } /* public class Basic_TestClass_memac039 : Basic_TestClass_memac039_C2 { protected override void OnSetComponentDefaults() { } public static int Main_old() { return 0; } public static bool testMethod() { return (Main_old() == 0); } } public class Basic_TestClass_memac041_B : Basic_TestClass_memac041_A { protected override void f() { Log.Comment("Basic_TestClass_memac041_B.f()"); } static void Main_old() { Basic_TestClass_memac041_B b = new Basic_TestClass_memac041_B(); b.f(); } public static bool testMethod() { Main_old(); Microsoft.SPOT.Debug.Print(""); } } */ class Basic_TestClass_memac042_B { protected static int F() { return 2; } } class Basic_TestClass_memac042_D : Basic_TestClass_memac042_B { public static int F() { return Basic_TestClass_memac042_B.F(); } } class Basic_TestClass_memac042 { static int Main_old() { if (Basic_TestClass_memac042_D.F() == 2) { return 0; } else { return 1; } } public static bool testMethod() { return (Main_old() == 0); } } class Basic_TestClass_memac043_B { protected internal static int F() { return 2; } } class Basic_TestClass_memac043_D : Basic_TestClass_memac043_B { public static int F() { return Basic_TestClass_memac043_B.F(); } } class Basic_TestClass_memac043 { static int Main_old() { if (Basic_TestClass_memac043_D.F() == 2) { return 0; } else { return 1; } } public static bool testMethod() { return (Main_old() == 0); } } class Basic_TestClass_memac044_B { protected static int intI = 2; } class Basic_TestClass_memac044_D : Basic_TestClass_memac044_B { public static int F() { return Basic_TestClass_memac044_B.intI; } } class Basic_TestClass_memac044 { static int Main_old() { if (Basic_TestClass_memac044_D.F() == 2) { return 0; } else { return 1; } } public static bool testMethod() { return (Main_old() == 0); } } class Basic_TestClass_memac045_B { protected internal static int intI = 2; } class Basic_TestClass_memac045_D : Basic_TestClass_memac045_B { public static int F() { return Basic_TestClass_memac045_B.intI; } } class Basic_TestClass_memac045 { static int Main_old() { if (Basic_TestClass_memac045_D.F() == 2) { return 0; } else { return 1; } } public static bool testMethod() { return (Main_old() == 0); } } class Basic_TestClass_memac046_B { protected static int intI { get { return 2; } } } class Basic_TestClass_memac046_D : Basic_TestClass_memac046_B { public static int F() { return Basic_TestClass_memac046_B.intI; } } class Basic_TestClass_memac046 { static int Main_old() { if (Basic_TestClass_memac046_D.F() == 2) { return 0; } else { return 1; } } public static bool testMethod() { return (Main_old() == 0); } } class Basic_TestClass_memac047_B { protected internal static int intI { get { return 2; } } } class Basic_TestClass_memac047_D : Basic_TestClass_memac047_B { public static int F() { return Basic_TestClass_memac047_B.intI; } } class Basic_TestClass_memac047 { static int Main_old() { if (Basic_TestClass_memac047_D.F() == 2) { return 0; } else { return 1; } } public static bool testMethod() { return (Main_old() == 0); } } public class Basic_TestClass_accon001_C2 { } internal class Basic_TestClass_accon001 : Basic_TestClass_accon001_C2 { public static int Main_old() { return 0; } public static bool testMethod() { return (Main_old() == 0); } } public class Basic_TestClass_accon003 { public class Basic_TestClass_accon003_C2 { } private class Basic_TestClass_accon003_C3 : Basic_TestClass_accon003_C2 { public static int Main_old() { return 0; } } public static bool testMethod() { return (Basic_TestClass_accon003_C3.Main_old() == 0); } } public class Basic_TestClass_accon005 { public class Basic_TestClass_accon005_C2 { } protected class Basic_TestClass_accon005_C3 : Basic_TestClass_accon005_C2 { public static int Main_old() { return 0; } } public static bool testMethod() { return (Basic_TestClass_accon005_C3.Main_old() == 0); } } public class Basic_TestClass_accon007 { public class Basic_TestClass_accon007_C2 { } internal class Basic_TestClass_accon007_C3 : Basic_TestClass_accon007_C2 { public static int Main_old() { return 0; } } public static bool testMethod() { return (Basic_TestClass_accon007_C3.Main_old() == 0); } } public class Basic_TestClass_accon009 { public class Basic_TestClass_accon009_C2 { } protected internal class Basic_TestClass_accon009_C3 : Basic_TestClass_accon009_C2 { public static int Main_old() { return 0; } } public static bool testMethod() { return (Basic_TestClass_accon009_C3.Main_old() == 0); } } public class Basic_TestClass_accon011 { protected internal class Basic_TestClass_accon011_C2 { } protected class Basic_TestClass_accon011_C3 : Basic_TestClass_accon011_C2 { public static int Main_old() { return 0; } } public static bool testMethod() { return (Basic_TestClass_accon011_C3.Main_old() == 0); } } public class Basic_TestClass_accon013 { protected internal class Basic_TestClass_accon013_C2 { } internal class Basic_TestClass_accon013_C3 : Basic_TestClass_accon013_C2 { public static int Main_old() { return 0; } } public static bool testMethod() { return (Basic_TestClass_accon013_C3.Main_old() == 0); } } public class Basic_TestClass_accon015 { protected internal class Basic_TestClass_accon015_C2 { } private class Basic_TestClass_accon015_C3 : Basic_TestClass_accon015_C2 { public static int Main_old() { return 0; } } public static bool testMethod() { return (Basic_TestClass_accon015_C3.Main_old() == 0); } } public class Basic_TestClass_accon019 { protected class Basic_TestClass_accon019_C2 { } private class Basic_TestClass_accon019_C3 : Basic_TestClass_accon019_C2 { public static int Main_old() { return 0; } } public static bool testMethod() { return (Basic_TestClass_accon019_C3.Main_old() == 0); } } public class Basic_TestClass_accon021 { internal class Basic_TestClass_accon021_C2 { } private class Basic_TestClass_accon021_C3 : Basic_TestClass_accon021_C2 { public static int Main_old() { return 0; } } public static bool testMethod() { return (Basic_TestClass_accon021_C3.Main_old() == 0); } } public interface Basic_TestClass_accon023_C2 { } internal interface Basic_TestClass_accon023_Inter : Basic_TestClass_accon023_C2 { } public class Basic_TestClass_accon023 { public static int Main_old() { return 0; } public static bool testMethod() { return (Main_old() == 0); } } public class Basic_TestClass_accon025 { public interface Basic_TestClass_accon025_C2 { } protected internal interface Basic_TestClass_accon025_Inter : Basic_TestClass_accon025_C2 { } public class Basic_TestClass_accon025_C3 { public static int Main_old() { return 0; } } public static bool testMethod() { return (Basic_TestClass_accon025_C3.Main_old() == 0); } } public class Basic_TestClass_accon027 { protected internal interface Basic_TestClass_accon027_C2 { } protected interface Basic_TestClass_accon027_Inter : Basic_TestClass_accon027_C2 { } public class Basic_TestClass_accon027_C3 { public static int Main_old() { return 0; } } public static bool testMethod() { return (Basic_TestClass_accon027_C3.Main_old() == 0); } } public class Basic_TestClass_accon029 { protected internal interface Basic_TestClass_accon029_C2 { } internal interface Basic_TestClass_accon029_Inter : Basic_TestClass_accon029_C2 { } public class Basic_TestClass_accon029_C3 { public static int Main_old() { return 0; } } public static bool testMethod() { return (Basic_TestClass_accon029_C3.Main_old() == 0); } } public class Basic_TestClass_accon031 { protected interface Basic_TestClass_accon031_C2 { } private interface Basic_TestClass_accon031_Inter : Basic_TestClass_accon031_C2 { } public class Basic_TestClass_accon031_C3 { public static int Main_old() { return 0; } } public static bool testMethod() { return (Basic_TestClass_accon031_C3.Main_old() == 0); } } public class Basic_TestClass_accon033 { public class Basic_TestClass_accon033_C1 { } protected delegate Basic_TestClass_accon033_C1 MyDelegate(); public class Basic_TestClass_accon033_C3 { public static int Main_old() { return 0; } } public static bool testMethod() { return (Basic_TestClass_accon033_C3.Main_old() == 0); } } public class Basic_TestClass_accon035 { public class Basic_TestClass_accon035_C1 { } internal delegate void MyDelegate(Basic_TestClass_accon035_C1 T); public class Basic_TestClass_accon035_C3 { public static int Main_old() { return 0; } } public static bool testMethod() { return (Basic_TestClass_accon035_C3.Main_old() == 0); } } public class Basic_TestClass_accon037 { public enum Basic_TestClass_accon037_C1 { aa = 1 } internal const Basic_TestClass_accon037_C1 e1 = Basic_TestClass_accon037_C1.aa; public class Basic_TestClass_accon037_C3 { public static int Main_old() { return 0; } } public static bool testMethod() { return (Basic_TestClass_accon037_C3.Main_old() == 0); } } public class Basic_TestClass_accon039 { public enum Basic_TestClass_accon039_C1 { aa = 1 } protected internal Basic_TestClass_accon039_C1 e1 = Basic_TestClass_accon039_C1.aa; public class Basic_TestClass_accon039_C3 { public static int Main_old() { return 0; } } public static bool testMethod() { return (Basic_TestClass_accon039_C3.Main_old() == 0); } } public class Basic_TestClass_accon041 { public class Basic_TestClass_accon041_C1 { } private Basic_TestClass_accon041_C1 MyMeth() { return new Basic_TestClass_accon041_C1(); } public class Basic_TestClass_accon041_C3 { public static int Main_old() { return 0; } } public static bool testMethod() { return (Basic_TestClass_accon041_C3.Main_old() == 0); } } public class Basic_TestClass_accon043 { public class Basic_TestClass_accon043_C1 { } private void MyMeth(Basic_TestClass_accon043_C1 T) { } public class Basic_TestClass_accon043_C3 { public static int Main_old() { return 0; } } public static bool testMethod() { return (Basic_TestClass_accon043_C3.Main_old() == 0); } } public class Basic_TestClass_accon045 { public class Basic_TestClass_accon045_C1 { } protected Basic_TestClass_accon045_C1 c1 { get { return new Basic_TestClass_accon045_C1(); } } public class Basic_TestClass_accon045_C3 { public static int Main_old() { return 0; } } public static bool testMethod() { return (Basic_TestClass_accon045_C3.Main_old() == 0); } } public class Basic_TestClass_accon047 { public class Basic_TestClass_accon047_C1 { } internal Basic_TestClass_accon047_C1 this[int intI] { get { return new Basic_TestClass_accon047_C1(); } } public class Basic_TestClass_accon047_C3 { public static int Main_old() { return 0; } } public static bool testMethod() { return (Basic_TestClass_accon047_C3.Main_old() == 0); } } public class Basic_TestClass_accon049 { public class Basic_TestClass_accon049_C1 { } internal int this[Basic_TestClass_accon049_C1 T] { get { return 1; } } public class Basic_TestClass_accon049_C3 { public static int Main_old() { return 0; } } public static bool testMethod() { return (Basic_TestClass_accon049_C3.Main_old() == 0); } } public class Basic_TestClass_accon051_C1 { } public class Basic_TestClass_accon051 { public static Basic_TestClass_accon051_C1 operator +(Basic_TestClass_accon051 MyInt, Basic_TestClass_accon051 MyInt2) { return new Basic_TestClass_accon051_C1(); } public static int Main_old() { return 0; } public static bool testMethod() { return (Main_old() == 0); } } public class Basic_TestClass_accon053_C1 { } public class Basic_TestClass_accon053 { public static int operator +(Basic_TestClass_accon053 MyInt, Basic_TestClass_accon053_C1 MyInt2) { return 1; } public static int Main_old() { return 0; } public static bool testMethod() { return (Main_old() == 0); } } public class Basic_TestClass_accon055_C1 { } public class Basic_TestClass_accon055 { internal Basic_TestClass_accon055(Basic_TestClass_accon055_C1 T) { } public static int Main_old() { return 0; } public static bool testMethod() { return (Main_old() == 0); } } } } //Other Namespaces namespace NS_Basic_TestClass_scope001 { class MyClass2 { public static int intI = 2; } } namespace NS_Basic_TestClass_scope002 { class Basic_TestClass_scope002 { public static int Main_old() { if ((Basic_TestClass_scope002_C1.intI == 1) && (TestNS.MyClass2.intI == 2)) { return 0; } else { return 1; } } public static bool testMethod() { return (Main_old() == 0); } } class Basic_TestClass_scope002_C1 { public static int intI = 1; } namespace TestNS { class MyClass2 { public static int intI = 2; } } } namespace NS_Basic_TestClass_scope003 { class Basic_TestClass_scope003 { public static int Main_old() { if ((Basic_TestClass_scope003_C1.intI == 1) && (TestNS.MyClass2.intI == 2)) { return 0; } else { return 1; } } public static bool testMethod() { return (Main_old() == 0); } } } namespace NS_Basic_TestClass_scope003 { class Basic_TestClass_scope003_C1 { public static int intI = 1; } namespace TestNS { class MyClass2 { public static int intI = 2; } } } namespace NS_Basic_TestClass_scope004 { namespace NS_Basic_TestClass_scope004_2 { class Basic_TestClass_scope004 { public static int Main_old() { if ((Basic_TestClass_scope004_C1.intI == 1) && (TestNS.MyClass2.intI == 2)) { return 0; } else { return 1; } } public static bool testMethod() { return (Main_old() == 0); } } } } namespace NS_Basic_TestClass_scope004.NS_Basic_TestClass_scope004_2 { class Basic_TestClass_scope004_C1 { public static int intI = 1; } namespace TestNS { class MyClass2 { public static int intI = 2; } } } namespace NS_Basic_TestClass_scope005 { class Basic_TestClass_scope005_C1 { public static int intI = 1; } namespace TestNS { class MyClass2 { public static int intI = 2; } } namespace NS_Basic_TestClass_scope005_2 { class Basic_TestClass_scope005 { public static int Main_old() { if ((Basic_TestClass_scope005_C1.intI == 1) && (TestNS.MyClass2.intI == 2)) { return 0; } else { return 1; } } public static bool testMethod() { return (Main_old() == 0); } } } } namespace NS_Basic_TestClass_scope006 { namespace NS_Basic_TestClass_scope006_2 { class Basic_TestClass_scope006 { public static int Main_old() { if ((Basic_TestClass_scope006_C1.intI == 1) && (TestNS.MyClass2.intI == 2)) { return 0; } else { return 1; } } public static bool testMethod() { return (Main_old() == 0); } } } } namespace NS_Basic_TestClass_scope006 { class Basic_TestClass_scope006_C1 { public static int intI = 1; } namespace TestNS { class MyClass2 { public static int intI = 2; } } } namespace NS_Basic_TestClass_scope012 { class Basic_TestClass_scope012 { public static int Main_old() { if (Math.Max(2, 3) == 3) { return 0; } else { return 1; } } public static bool testMethod() { return (Main_old() == 0); } } } namespace NS_Basic_TestClass_scope056 { class Basic_TestClass_scope056 { public Basic_TestClass_scope056_C2 MC; public static int Main_old() { return 0; } public static bool testMethod() { return (Main_old() == 0); } } class Basic_TestClass_scope056_C2 { } } namespace Basic_TestClass_nhide001_C1 { class Basic_TestClass_nhide001_C1 { public static int intI = 1; } } namespace NS_Basic_TestClass_nhide001 { namespace Basic_TestClass_nhide001_C1 { class Basic_TestClass_nhide001_C1 { public static int intI = 2; } } class Basic_TestClass_nhide001 { public static int Main_old() { if (Basic_TestClass_nhide001_C1.Basic_TestClass_nhide001_C1.intI == 2) { return 0; } else { return 1; } } public static bool testMethod() { return (Main_old() == 0); } } } class Basic_TestClass_nhide002_C1 { public class Basic_TestClass_nhide002_C2 { public static int intI = 1; } } namespace NS_Basic_TestClass_nhide002 { namespace Basic_TestClass_nhide002_C1 { class Basic_TestClass_nhide002_C2 { public static int intI = 2; } } class Basic_TestClass_nhide002 { public static int Main_old() { if (Basic_TestClass_nhide002_C1.Basic_TestClass_nhide002_C2.intI == 2) { return 0; } else { return 1; } } public static bool testMethod() { return (Main_old() == 0); } } } struct Basic_TestClass_nhide003_C1 { public class Basic_TestClass_nhide003_C2 { public static int intI = 1; } } namespace NS_Basic_TestClass_nhide003 { namespace Basic_TestClass_nhide003_C1 { class Basic_TestClass_nhide003_C2 { public static int intI = 2; } } class Basic_TestClass_nhide003 { public static int Main_old() { if (Basic_TestClass_nhide003_C1.Basic_TestClass_nhide003_C2.intI == 2) { return 0; } else { return 1; } } public static bool testMethod() { return (Main_old() == 0); } } } interface Basic_TestClass_nhide004_C1 { } namespace NS_Basic_TestClass_nhide004 { namespace Basic_TestClass_nhide004_C1 { class Basic_TestClass_nhide004_C2 { public static int intI = 2; } } class Basic_TestClass_nhide004 { public static int Main_old() { if (Basic_TestClass_nhide004_C1.Basic_TestClass_nhide004_C2.intI == 2) { return 0; } else { return 1; } } public static bool testMethod() { return (Main_old() == 0); } } } enum Basic_TestClass_nhide005_C1 { Basic_TestClass_nhide005_C1 = 1 } namespace NS_Basic_TestClass_nhide005 { namespace Basic_TestClass_nhide005_C1 { class Basic_TestClass_nhide005_C1 { public static int intI = 2; } } class Basic_TestClass_nhide005 { public static int Main_old() { if (Basic_TestClass_nhide005_C1.Basic_TestClass_nhide005_C1.intI == 2) { return 0; } else { return 1; } } public static bool testMethod() { return (Main_old() == 0); } } } delegate void Basic_TestClass_nhide006_C1(); namespace NS_Basic_TestClass_nhide006 { namespace Basic_TestClass_nhide006_C1 { class Basic_TestClass_nhide006_C1 { public static int intI = 2; } } class Basic_TestClass_nhide006 { public static int Main_old() { if (Basic_TestClass_nhide006_C1.Basic_TestClass_nhide006_C1.intI == 2) { return 0; } else { return 1; } } public static bool testMethod() { return (Main_old() == 0); } } } namespace Basic_TestClass_nhide007_C1 { class Basic_TestClass_nhide007_C1 { public static int intI = 1; } } namespace NS_Basic_TestClass_nhide007 { namespace Basic_TestClass_nhide007_C1 { class Basic_TestClass_nhide007_C1 { public static int intI = 2; } } } namespace Basic_TestClass_nhide008_C1 { class Basic_TestClass_nhide008_I { public static int intI = 1; } } namespace NS_Basic_TestClass_nhide008 { class Basic_TestClass_nhide008_C1 { public class Basic_TestClass_nhide008_I { public static int intI = 2; } } class Basic_TestClass_nhide008 { public static int Main_old() { if (Basic_TestClass_nhide008_C1.Basic_TestClass_nhide008_I.intI == 2) { Log.Comment("foo"); return 0; } else { return 1; } } public static bool testMethod() { return (Main_old() == 0); } } } class Basic_TestClass_nhide009_C1 { public class Basic_TestClass_nhide009_I { public static int intI = 1; } } namespace NS_Basic_TestClass_nhide009 { class Basic_TestClass_nhide009_C1 { public class Basic_TestClass_nhide009_I { public static int intI = 2; } } class Basic_TestClass_nhide009 { public static int Main_old() { if (Basic_TestClass_nhide009_C1.Basic_TestClass_nhide009_I.intI == 2) { return 0; } else { return 1; } } public static bool testMethod() { return (Main_old() == 0); } } } struct Basic_TestClass_nhide010_St1 { public class Basic_TestClass_nhide010_I { public static int intI = 1; } } namespace NS_Basic_TestClass_nhide010 { struct Basic_TestClass_nhide010_St1 { public class Basic_TestClass_nhide010_I { public static int intI = 2; } } class Basic_TestClass_nhide010 { public static int Main_old() { if (Basic_TestClass_nhide010_St1.Basic_TestClass_nhide010_I.intI == 2) { Log.Comment("foo"); return 0; } else { return 1; } } public static bool testMethod() { return (Main_old() == 0); } } } interface Basic_TestClass_nhide011_Inter { void bogus(); } namespace NS_Basic_TestClass_nhide011 { interface Basic_TestClass_nhide011_Inter { void test(); } class Basic_TestClass_nhide011 : Basic_TestClass_nhide011_Inter { public void test() { } public static int Main_old() { return 0; } public static bool testMethod() { return (Main_old() == 0); } } } enum Basic_TestClass_nhide012_Enum { test = 1 } namespace NS_Basic_TestClass_nhide012 { enum Basic_TestClass_nhide012_Enum { test = 2 } class Basic_TestClass_nhide012 { public static int Main_old() { if ((int)Basic_TestClass_nhide012_Enum.test == 2) { return 0; } else { return 1; } } public static bool testMethod() { return (Main_old() == 0); } } } delegate void Basic_TestClass_nhide013_Del(); namespace NS_Basic_TestClass_nhide013 { delegate int Basic_TestClass_nhide013_Del(int intI); class Basic_TestClass_nhide013 { int TestMeth(int intI) { return 1; } public static int Main_old() { Basic_TestClass_nhide013 test = new Basic_TestClass_nhide013(); Basic_TestClass_nhide013_Del td = new Basic_TestClass_nhide013_Del(test.TestMeth); return 0; } public static bool testMethod() { return (Main_old() == 0); } } } class Basic_TestClass_nhide014_C1 { public class Basic_TestClass_nhide014_I { public static int intI = 1; } } namespace NS_Basic_TestClass_nhide014 { class Basic_TestClass_nhide014_C1 { public class Basic_TestClass_nhide014_I { public static int intI = 2; } } } class Basic_TestClass_nhide014 { public static int Main_old() { if (Basic_TestClass_nhide014_C1.Basic_TestClass_nhide014_I.intI == 1) { return 0; } else { return 1; } } public static bool testMethod() { return (Main_old() == 0); } } namespace Basic_TestClass_nhide015_C1 { class Basic_TestClass_nhide015_I { public static int intI = 1; } } namespace Basic_TestClass_nhide022_C1 { class Basic_TestClass_nhide022_I { public static int intI = 1; } } ================================================ FILE: Zelig/Zelig/Test/RunTime/NETMF/mscorlib/bitconverter/BitConverterTests.cs ================================================ //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // Copyright (c) Microsoft Corporation. All rights reserved. //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// using System; using System.Reflection; using Microsoft.SPOT.Platform.Test; namespace Microsoft.SPOT.Platform.Tests { public class BitConverterTests : IMFTestInterface { [SetUp] public InitializeResult Initialize() { Log.Comment("BitConverter tests initialized."); return InitializeResult.ReadyToGo; } [TearDown] public void CleanUp() { Log.Comment("Cleaning up after BitConverter tests."); } //Test Case Calls [TestMethod] public MFTestResults BitConverterTest_DoubleToInt64Bits() { try { Helper.DoubleToLongBits(1.0, 0x3FF0000000000000); Helper.DoubleToLongBits(15.0, 0x402E000000000000); Helper.DoubleToLongBits(255.0, 0x406FE00000000000); Helper.DoubleToLongBits(4294967295.0, 0x41EFFFFFFFE00000); Helper.DoubleToLongBits(0.00390625, 0x3F70000000000000); Helper.DoubleToLongBits(0.00000000023283064365386962890625, 0x3DF0000000000000); Helper.DoubleToLongBits(1.234567890123E-300, 0x01AA74FE1C1E7E45); Helper.DoubleToLongBits(1.23456789012345E-150, 0x20D02A36586DB4BB); Helper.DoubleToLongBits(1.2345678901234565, 0x3FF3C0CA428C59FA); Helper.DoubleToLongBits(1.2345678901234567, 0x3FF3C0CA428C59FB); Helper.DoubleToLongBits(1.2345678901234569, 0x3FF3C0CA428C59FC); Helper.DoubleToLongBits(1.23456789012345678E+150, 0x5F182344CD3CDF9F); Helper.DoubleToLongBits(1.234567890123456789E+300, 0x7E3D7EE8BCBBD352); Helper.DoubleToLongBits(double.MinValue, unchecked((long)0xFFEFFFFFFFFFFFFF)); Helper.DoubleToLongBits(double.MaxValue, 0x7FEFFFFFFFFFFFFF); Helper.DoubleToLongBits(double.Epsilon, 0x0000000000000001); Helper.DoubleToLongBits(double.NaN, unchecked((long)0xFFF8000000000000)); Helper.DoubleToLongBits(double.NegativeInfinity, unchecked((long)0xFFF0000000000000)); Helper.DoubleToLongBits(double.PositiveInfinity, 0x7FF0000000000000); } catch (TestFailException e) { Log.Comment(e.Message); return MFTestResults.Fail; } return MFTestResults.Pass; } [TestMethod] public MFTestResults BitConverterTest_GetBytesBool() { try { Helper.GetBytesBool(true, new byte[] { 1 }); Helper.GetBytesBool(false, new byte[] { 0 }); } catch (TestFailException e) { Log.Comment(e.Message); return MFTestResults.Fail; } return MFTestResults.Pass; } [TestMethod] public MFTestResults BitConverterTest_GetBytesChar() { try { Helper.GetBytesChar('\0', new byte[] { 0x00, 0x00 }); Helper.GetBytesChar(' ', new byte[] { 0x20, 0x00 }); Helper.GetBytesChar('*', new byte[] { 0x2A, 0x00 }); Helper.GetBytesChar('3', new byte[] { 0x33, 0x00 }); Helper.GetBytesChar('A', new byte[] { 0x41, 0x00 }); Helper.GetBytesChar('[', new byte[] { 0x5B, 0x00 }); Helper.GetBytesChar('a', new byte[] { 0x61, 0x00 }); Helper.GetBytesChar('{', new byte[] { 0x7B, 0x00 }); Helper.GetBytesChar('测', new byte[] { 0x4B, 0x6D }); } catch (TestFailException e) { Log.Comment(e.Message); return MFTestResults.Fail; } return MFTestResults.Pass; } [TestMethod] public MFTestResults BitConverterTest_GetBytesDouble() { try { Helper.GetBytesDouble(0.0, new byte[] { 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 }); Helper.GetBytesDouble(1.0, new byte[] { 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xF0, 0x3F }); Helper.GetBytesDouble(255.0, new byte[] { 0x00, 0x00, 0x00, 0x00, 0x00, 0xE0, 0x6F, 0x40 }); Helper.GetBytesDouble(4294967295.0, new byte[] { 0x00, 0x00, 0xE0, 0xFF, 0xFF, 0xFF, 0xEF, 0x41 }); Helper.GetBytesDouble(0.00390625, new byte[] { 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x70, 0x3F }); Helper.GetBytesDouble(0.00000000023283064365386962890625, new byte[] { 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xF0, 0x3D }); Helper.GetBytesDouble(1.23456789012345E-300, new byte[] { 0xDF, 0x88, 0x1E, 0x1C, 0xFE, 0x74, 0xAA, 0x01 }); Helper.GetBytesDouble(1.2345678901234565, new byte[] { 0xFA, 0x59, 0x8C, 0x42, 0xCA, 0xC0, 0xF3, 0x3F }); Helper.GetBytesDouble(1.2345678901234567, new byte[] { 0xFB, 0x59, 0x8C, 0x42, 0xCA, 0xC0, 0xF3, 0x3F }); Helper.GetBytesDouble(1.2345678901234569, new byte[] { 0xFC, 0x59, 0x8C, 0x42, 0xCA, 0xC0, 0xF3, 0x3F }); Helper.GetBytesDouble(1.23456789012345678E+300, new byte[] { 0x52, 0xD3, 0xBB, 0xBC, 0xE8, 0x7E, 0x3D, 0x7E }); Helper.GetBytesDouble(double.MinValue, new byte[] { 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xEF, 0xFF }); Helper.GetBytesDouble(double.MaxValue, new byte[] { 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xEF, 0x7F }); Helper.GetBytesDouble(double.Epsilon, new byte[] { 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 }); Helper.GetBytesDouble(double.NaN, new byte[] { 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xF8, 0xFF }); Helper.GetBytesDouble(double.NegativeInfinity, new byte[] { 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xF0, 0xFF }); Helper.GetBytesDouble(double.PositiveInfinity, new byte[] { 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xF0, 0x7F }); } catch (TestFailException e) { Log.Comment(e.Message); return MFTestResults.Fail; } return MFTestResults.Pass; } [TestMethod] public MFTestResults BitConverterTest_GetBytesInt16() { try { Helper.GetBytesInt16(0, new byte[] { 0x00, 0x00 }); Helper.GetBytesInt16(15, new byte[] { 0x0F, 0x00 }); Helper.GetBytesInt16(-15, new byte[] { 0xF1, 0xFF }); Helper.GetBytesInt16(10000, new byte[] { 0x10, 0x27 }); Helper.GetBytesInt16(-10000, new byte[] { 0xF0, 0xD8 }); Helper.GetBytesInt16(short.MinValue, new byte[] { 0x00, 0x80 }); Helper.GetBytesInt16(short.MaxValue, new byte[] { 0xFF, 0x7F }); } catch (TestFailException e) { Log.Comment(e.Message); return MFTestResults.Fail; } return MFTestResults.Pass; } [TestMethod] public MFTestResults BitConverterTest_GetBytesInt32() { try { Helper.GetBytesInt32(0, new byte[] { 0x00, 0x00, 0x00, 0x00 }); Helper.GetBytesInt32(15, new byte[] { 0x0F, 0x00, 0x00, 0x00 }); Helper.GetBytesInt32(-15, new byte[] { 0xF1, 0xFF, 0xFF, 0xFF }); Helper.GetBytesInt32(1048576, new byte[] { 0x00, 0x00, 0x10, 0x00 }); Helper.GetBytesInt32(-1048576, new byte[] { 0x00, 0x00, 0xF0, 0xFF }); Helper.GetBytesInt32(1000000000, new byte[] { 0x00, 0xCA, 0x9A, 0x3B }); Helper.GetBytesInt32(-1000000000, new byte[] { 0x00, 0x36, 0x65, 0xC4 }); Helper.GetBytesInt32(int.MinValue, new byte[] { 0x00, 0x00, 0x00, 0x80 }); Helper.GetBytesInt32(int.MaxValue, new byte[] { 0xFF, 0xFF, 0xFF, 0x7F }); } catch (TestFailException e) { Log.Comment(e.Message); return MFTestResults.Fail; } return MFTestResults.Pass; } [TestMethod] public MFTestResults BitConverterTest_GetBytesInt64() { try { Helper.GetBytesInt64(0, new byte[] { 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 }); Helper.GetBytesInt64(16777215, new byte[] { 0xFF, 0xFF, 0xFF, 0x00, 0x00, 0x00, 0x00, 0x00 }); Helper.GetBytesInt64(-16777215, new byte[] { 0x01, 0x00, 0x00, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF }); Helper.GetBytesInt64(1000000000, new byte[] { 0x00, 0xCA, 0x9A, 0x3B, 0x00, 0x00, 0x00, 0x00 }); Helper.GetBytesInt64(-1000000000, new byte[] { 0x00, 0x36, 0x65, 0xC4, 0xFF, 0xFF, 0xFF, 0xFF }); Helper.GetBytesInt64(4294967296, new byte[] { 0x00, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00 }); Helper.GetBytesInt64(-4294967296, new byte[] { 0x00, 0x00, 0x00, 0x00, 0xFF, 0xFF, 0xFF, 0xFF }); Helper.GetBytesInt64(187649984473770, new byte[] { 0xAA, 0xAA, 0xAA, 0xAA, 0xAA, 0xAA, 0x00, 0x00 }); Helper.GetBytesInt64(-187649984473770, new byte[] { 0x56, 0x55, 0x55, 0x55, 0x55, 0x55, 0xFF, 0xFF }); Helper.GetBytesInt64(1000000000000000000, new byte[] { 0x00, 0x00, 0x64, 0xA7, 0xB3, 0xB6, 0xE0, 0x0D }); Helper.GetBytesInt64(-1000000000000000000, new byte[] { 0x00, 0x00, 0x9C, 0x58, 0x4C, 0x49, 0x1F, 0xF2 }); Helper.GetBytesInt64(long.MinValue, new byte[] { 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x80 }); Helper.GetBytesInt64(long.MaxValue, new byte[] { 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0x7F }); } catch (TestFailException e) { Log.Comment(e.Message); return MFTestResults.Fail; } return MFTestResults.Pass; } [TestMethod] public MFTestResults BitConverterTest_GetBytesSingle() { try { Helper.GetBytesSingle(0.0F, new byte[] { 0x00, 0x00, 0x00, 0x00 }); Helper.GetBytesSingle(1.0F, new byte[] { 0x00, 0x00, 0x80, 0x3F }); Helper.GetBytesSingle(15.0F, new byte[] { 0x00, 0x00, 0x70, 0x41 }); Helper.GetBytesSingle(65535.0F, new byte[] { 0x00, 0xFF, 0x7F, 0x47 }); Helper.GetBytesSingle(0.00390625F, new byte[] { 0x00, 0x00, 0x80, 0x3B }); Helper.GetBytesSingle(0.00000000023283064365386962890625F, new byte[] { 0x00, 0x00, 0x80, 0x2F }); Helper.GetBytesSingle(1.2345E-35F, new byte[] { 0x49, 0x46, 0x83, 0x05 }); Helper.GetBytesSingle(1.2345671F, new byte[] { 0x4B, 0x06, 0x9E, 0x3F }); Helper.GetBytesSingle(1.2345673F, new byte[] { 0x4D, 0x06, 0x9E, 0x3F }); Helper.GetBytesSingle(1.2345677F, new byte[] { 0x50, 0x06, 0x9E, 0x3F }); Helper.GetBytesSingle(1.23456789E+35F, new byte[] { 0x1E, 0x37, 0xBE, 0x79 }); Helper.GetBytesSingle(float.MinValue, new byte[] { 0xFF, 0xFF, 0x7F, 0xFF }); Helper.GetBytesSingle(float.MaxValue, new byte[] { 0xFF, 0xFF, 0x7F, 0x7F }); Helper.GetBytesSingle(float.Epsilon, new byte[] { 0x01, 0x00, 0x00, 0x00 }); Helper.GetBytesSingle(0.0F / 0.0F, new byte[] { 0x00, 0x00, 0xC0, 0xFF }); Helper.GetBytesSingle(-1.0F / 0.0F, new byte[] { 0x00, 0x00, 0x80, 0xFF }); Helper.GetBytesSingle(1.0F / 0.0F, new byte[] { 0x00, 0x00, 0x80, 0x7F }); } catch (TestFailException e) { Log.Comment(e.Message); return MFTestResults.Fail; } return MFTestResults.Pass; } [TestMethod] public MFTestResults BitConverterTest_GetBytesUInt16() { try { Helper.GetBytesUInt16(15, new byte[] { 0x0F, 0x00 }); Helper.GetBytesUInt16(1023, new byte[] { 0xFF, 0x03 }); Helper.GetBytesUInt16(10000, new byte[] { 0x10, 0x27 }); Helper.GetBytesUInt16(ushort.MinValue, new byte[] { 0x00, 0x00 }); Helper.GetBytesUInt16((ushort)short.MaxValue, new byte[] { 0xFF, 0x7F }); Helper.GetBytesUInt16(ushort.MaxValue, new byte[] { 0xFF, 0xFF }); } catch (TestFailException e) { Log.Comment(e.Message); return MFTestResults.Fail; } return MFTestResults.Pass; } [TestMethod] public MFTestResults BitConverterTest_GetBytesUInt32() { try { Helper.GetBytesUInt32(15, new byte[] { 0x0F, 0x00, 0x00, 0x00 }); Helper.GetBytesUInt32(1023, new byte[] { 0xFF, 0x03, 0x00, 0x00 }); Helper.GetBytesUInt32(1048576, new byte[] { 0x00, 0x00, 0x10, 0x00 }); Helper.GetBytesUInt32(1000000000, new byte[] { 0x00, 0xCA, 0x9A, 0x3B }); Helper.GetBytesUInt32(uint.MinValue, new byte[] { 0x00, 0x00, 0x00, 0x00 }); Helper.GetBytesUInt32(int.MaxValue, new byte[] { 0xFF, 0xFF, 0xFF, 0x7F }); Helper.GetBytesUInt32(uint.MaxValue, new byte[] { 0xFF, 0xFF, 0xFF, 0xFF }); } catch (TestFailException e) { Log.Comment(e.Message); return MFTestResults.Fail; } return MFTestResults.Pass; } [TestMethod] public MFTestResults BitConverterTest_GetBytesUInt64() { try { Helper.GetBytesUInt64(16777215, new byte[] { 0xFF, 0xFF, 0xFF, 0x00, 0x00, 0x00, 0x00, 0x00 }); Helper.GetBytesUInt64(1000000000, new byte[] { 0x00, 0xCA, 0x9A, 0x3B, 0x00, 0x00, 0x00, 0x00 }); Helper.GetBytesUInt64(4294967296, new byte[] { 0x00, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00 }); Helper.GetBytesUInt64(187649984473770, new byte[] { 0xAA, 0xAA, 0xAA, 0xAA, 0xAA, 0xAA, 0x00, 0x00 }); Helper.GetBytesUInt64(1000000000000000000, new byte[] { 0x00, 0x00, 0x64, 0xA7, 0xB3, 0xB6, 0xE0, 0x0D }); Helper.GetBytesUInt64(10000000000000000000, new byte[] { 0x00, 0x00, 0xE8, 0x89, 0x04, 0x23, 0xC7, 0x8A }); Helper.GetBytesUInt64(ulong.MinValue, new byte[] { 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 }); Helper.GetBytesUInt64(long.MaxValue, new byte[] { 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0x7F }); Helper.GetBytesUInt64(ulong.MaxValue, new byte[] { 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF }); } catch (TestFailException e) { Log.Comment(e.Message); return MFTestResults.Fail; } return MFTestResults.Pass; } [TestMethod] public MFTestResults BitConverterTest_LongBitsToDouble() { try { Helper.LongBitsToDouble(0x0000000000000000, 0.0000000000000000E+000); Helper.LongBitsToDouble(0x3FF0000000000000, 1.0000000000000000E+000); Helper.LongBitsToDouble(0x402E000000000000, 1.5000000000000000E+001); Helper.LongBitsToDouble(0x406FE00000000000, 2.5500000000000000E+002); Helper.LongBitsToDouble(0x41EFFFFFFFE00000, 4.2949672950000000E+009); Helper.LongBitsToDouble(0x3F70000000000000, 3.9062500000000000E-003); Helper.LongBitsToDouble(0x3DF0000000000000, 2.3283064365386963E-010); Helper.LongBitsToDouble(0x0000000000000001, 4.9406564584124654E-324); Helper.LongBitsToDouble(0x000000000000FFFF, 3.2378592100206092E-319); Helper.LongBitsToDouble(0x0000FFFFFFFFFFFF, 1.3906711615669959E-309); Helper.LongBitsToDouble(unchecked((long)0xFFFFFFFFFFFFFFFF), double.NaN); Helper.LongBitsToDouble(unchecked((long)0xFFF0000000000000), double.NegativeInfinity); Helper.LongBitsToDouble(0x7FF0000000000000, double.PositiveInfinity); Helper.LongBitsToDouble(unchecked((long)0xFFEFFFFFFFFFFFFF), double.MinValue); Helper.LongBitsToDouble(0x7FEFFFFFFFFFFFFF, double.MaxValue); Helper.LongBitsToDouble(long.MinValue, 0.0000000000000000E+000); Helper.LongBitsToDouble(long.MaxValue, double.NaN); } catch (TestFailException e) { Log.Comment(e.Message); return MFTestResults.Fail; } return MFTestResults.Pass; } [TestMethod] public MFTestResults BitConverterTest_ToBoolean() { try { var byteArray = new byte[] { 0, 1, 2, 4, 8, 16, 32, 64, 128, 255 }; Helper.BAToBool(byteArray, 0, false); Helper.BAToBool(byteArray, 1, true); Helper.BAToBool(byteArray, 3, true); Helper.BAToBool(byteArray, 5, true); Helper.BAToBool(byteArray, 8, true); Helper.BAToBool(byteArray, 9, true); Helper.BAToBoolThrow(byteArray, int.MinValue, typeof(ArgumentOutOfRangeException)); Helper.BAToBoolThrow(byteArray, -1, typeof(ArgumentOutOfRangeException)); Helper.BAToBoolThrow(byteArray, byteArray.Length, typeof(ArgumentOutOfRangeException)); Helper.BAToBoolThrow(byteArray, int.MaxValue, typeof(ArgumentOutOfRangeException)); Helper.BAToBoolThrow(new byte[] { }, 1, typeof(ArgumentOutOfRangeException)); Helper.BAToBoolThrow(null, 1, typeof(ArgumentNullException)); } catch (TestFailException e) { Log.Comment(e.Message); return MFTestResults.Fail; } return MFTestResults.Pass; } [TestMethod] public MFTestResults BitConverterTest_ToChar() { try { var byteArray = new byte[] { 32, 0, 0, 42, 0, 65, 0, 125, 0, 197, 0, 168, 3, 41, 4, 172, 32 }; Helper.BAToChar(byteArray, 0, ' '); Helper.BAToChar(byteArray, 1, '\0'); Helper.BAToChar(byteArray, 3, '*'); Helper.BAToChar(byteArray, 5, 'A'); Helper.BAToChar(byteArray, 7, '}'); Helper.BAToChar(byteArray, 9, 'Å'); Helper.BAToChar(byteArray, 11, 'Ψ'); Helper.BAToChar(byteArray, 13, 'Щ'); Helper.BAToChar(byteArray, 15, '€'); Helper.BAToCharThrow(byteArray, int.MinValue, typeof(ArgumentOutOfRangeException)); Helper.BAToCharThrow(byteArray, -1, typeof(ArgumentOutOfRangeException)); Helper.BAToCharThrow(byteArray, byteArray.Length - 1, typeof(ArgumentException)); Helper.BAToCharThrow(byteArray, byteArray.Length, typeof(ArgumentOutOfRangeException)); Helper.BAToCharThrow(byteArray, int.MaxValue, typeof(ArgumentOutOfRangeException)); Helper.BAToCharThrow(new byte[] { }, 1, typeof(ArgumentOutOfRangeException)); Helper.BAToCharThrow(null, 1, typeof(ArgumentNullException)); } catch (TestFailException e) { Log.Comment(e.Message); return MFTestResults.Fail; } return MFTestResults.Pass; } [TestMethod] public MFTestResults BitConverterTest_ToDouble() { try { var byteArray = new byte[]{ 0, 0, 0, 0, 0, 0, 0, 0, 240, 63, 0, 0, 0, 0, 0, 224, 111, 64, 0, 0, 224, 255, 255, 255, 239, 65, 0, 0, 0, 0, 0, 0, 112, 63, 0, 0, 0, 0, 0, 0, 240, 61, 223, 136, 30, 28, 254, 116, 170, 1, 250, 89, 140, 66, 202, 192, 243, 63, 251, 89, 140, 66, 202, 192, 243, 63, 252, 89, 140, 66, 202, 192, 243, 63, 82, 211, 187, 188, 232, 126, 61, 126, 255, 255, 255, 255, 255, 255, 239, 255, 255, 255, 255, 255, 255, 239, 127, 1, 0, 0, 0, 0, 0, 0, 0, 248, 255, 0, 0, 0, 0, 0, 0, 240, 255, 0, 0, 0, 0, 0, 0, 240, 127 }; Helper.BAToDouble(byteArray, 0, 0.0000000000000000E+000); Helper.BAToDouble(byteArray, 2, 1.0000000000000000E+000); Helper.BAToDouble(byteArray, 10, 2.5500000000000000E+002); Helper.BAToDouble(byteArray, 18, 4.2949672950000000E+009); Helper.BAToDouble(byteArray, 26, 3.9062500000000000E-003); Helper.BAToDouble(byteArray, 34, 2.3283064365386963E-010); Helper.BAToDouble(byteArray, 42, 1.2345678901234500E-300); Helper.BAToDouble(byteArray, 50, 1.2345678901234565E+000); Helper.BAToDouble(byteArray, 58, 1.2345678901234567E+000); Helper.BAToDouble(byteArray, 66, 1.2345678901234569E+000); Helper.BAToDouble(byteArray, 74, 1.2345678901234569E+300); Helper.BAToDouble(byteArray, 82, double.MinValue); Helper.BAToDouble(byteArray, 89, double.MaxValue); Helper.BAToDouble(byteArray, 97, double.Epsilon); Helper.BAToDouble(byteArray, 99, double.NaN); Helper.BAToDouble(byteArray, 107, double.NegativeInfinity); Helper.BAToDouble(byteArray, 115, double.PositiveInfinity); Helper.BAToDoubleThrow(byteArray, int.MinValue, typeof(ArgumentOutOfRangeException)); Helper.BAToDoubleThrow(byteArray, -1, typeof(ArgumentOutOfRangeException)); Helper.BAToDoubleThrow(byteArray, byteArray.Length - 7, typeof(ArgumentException)); Helper.BAToDoubleThrow(byteArray, byteArray.Length - 1, typeof(ArgumentException)); Helper.BAToDoubleThrow(byteArray, byteArray.Length, typeof(ArgumentOutOfRangeException)); Helper.BAToDoubleThrow(byteArray, int.MaxValue, typeof(ArgumentOutOfRangeException)); Helper.BAToDoubleThrow(new byte[] { }, 1, typeof(ArgumentOutOfRangeException)); Helper.BAToDoubleThrow(null, 1, typeof(ArgumentNullException)); } catch (TestFailException e) { Log.Comment(e.Message); return MFTestResults.Fail; } return MFTestResults.Pass; } [TestMethod] public MFTestResults BitConverterTest_ToInt16() { try { var byteArray = new byte[] { 15, 0, 0, 128, 16, 39, 240, 216, 241, 255, 127 }; Helper.BAToInt16(byteArray, 1, 0); Helper.BAToInt16(byteArray, 0, 15); Helper.BAToInt16(byteArray, 8, -15); Helper.BAToInt16(byteArray, 4, 10000); Helper.BAToInt16(byteArray, 6, -10000); Helper.BAToInt16(byteArray, 9, short.MaxValue); Helper.BAToInt16(byteArray, 2, short.MinValue); Helper.BAToInt16Throw(byteArray, int.MinValue, typeof(ArgumentOutOfRangeException)); Helper.BAToInt16Throw(byteArray, -1, typeof(ArgumentOutOfRangeException)); Helper.BAToInt16Throw(byteArray, byteArray.Length - 1, typeof(ArgumentException)); Helper.BAToInt16Throw(byteArray, byteArray.Length, typeof(ArgumentOutOfRangeException)); Helper.BAToInt16Throw(byteArray, int.MaxValue, typeof(ArgumentOutOfRangeException)); Helper.BAToInt16Throw(new byte[] { }, 1, typeof(ArgumentOutOfRangeException)); Helper.BAToInt16Throw(null, 1, typeof(ArgumentNullException)); } catch (TestFailException e) { Log.Comment(e.Message); return MFTestResults.Fail; } return MFTestResults.Pass; } [TestMethod] public MFTestResults BitConverterTest_Int32() { try { var byteArray = new byte[]{ 15, 0, 0, 0, 0, 128, 0, 0, 16, 0, 0, 240, 255, 0, 202, 154, 59, 0, 54, 101, 196, 241, 255, 255, 255, 127 }; Helper.BAToInt32(byteArray, 1, 0); Helper.BAToInt32(byteArray, 0, 15); Helper.BAToInt32(byteArray, 21, -15); Helper.BAToInt32(byteArray, 6, 1048576); Helper.BAToInt32(byteArray, 9, -1048576); Helper.BAToInt32(byteArray, 13, 1000000000); Helper.BAToInt32(byteArray, 17, -1000000000); Helper.BAToInt32(byteArray, 22, int.MaxValue); Helper.BAToInt32(byteArray, 2, int.MinValue); Helper.BAToInt32Throw(byteArray, int.MinValue, typeof(ArgumentOutOfRangeException)); Helper.BAToInt32Throw(byteArray, -1, typeof(ArgumentOutOfRangeException)); Helper.BAToInt32Throw(byteArray, byteArray.Length - 3, typeof(ArgumentException)); Helper.BAToInt32Throw(byteArray, byteArray.Length - 1, typeof(ArgumentException)); Helper.BAToInt32Throw(byteArray, byteArray.Length, typeof(ArgumentOutOfRangeException)); Helper.BAToInt32Throw(byteArray, int.MaxValue, typeof(ArgumentOutOfRangeException)); Helper.BAToInt32Throw(new byte[] { }, 1, typeof(ArgumentOutOfRangeException)); Helper.BAToInt32Throw(null, 1, typeof(ArgumentNullException)); } catch (TestFailException e) { Log.Comment(e.Message); return MFTestResults.Fail; } return MFTestResults.Pass; } [TestMethod] public MFTestResults BitConverterTest_Int64() { try { var byteArray = new byte[]{ 0, 54, 101, 196, 255, 255, 255, 255, 0, 0, 0, 0, 0, 0, 0, 0, 128, 0, 202, 154, 59, 0, 0, 0, 0, 1, 0, 0, 0, 0, 255, 255, 255, 255, 1, 0, 0, 255, 255, 255, 255, 255, 255, 255, 127, 86, 85, 85, 85, 85, 85, 255, 255, 170, 170, 170, 170, 170, 170, 0, 0, 100, 167, 179, 182, 224, 13, 0, 0, 156, 88, 76, 73, 31, 242 }; Helper.BAToInt64(byteArray, 8, 0); Helper.BAToInt64(byteArray, 5, 16777215); Helper.BAToInt64(byteArray, 34, -16777215); Helper.BAToInt64(byteArray, 17, 1000000000); Helper.BAToInt64(byteArray, 0, -1000000000); Helper.BAToInt64(byteArray, 21, 4294967296); Helper.BAToInt64(byteArray, 26, -4294967296); Helper.BAToInt64(byteArray, 53, 187649984473770); Helper.BAToInt64(byteArray, 45, -187649984473770); Helper.BAToInt64(byteArray, 59, 1000000000000000000); Helper.BAToInt64(byteArray, 67, -1000000000000000000); Helper.BAToInt64(byteArray, 37, long.MaxValue); Helper.BAToInt64(byteArray, 9, long.MinValue); Helper.BAToInt64Throw(byteArray, int.MinValue, typeof(ArgumentOutOfRangeException)); Helper.BAToInt64Throw(byteArray, -1, typeof(ArgumentOutOfRangeException)); Helper.BAToInt64Throw(byteArray, byteArray.Length - 7, typeof(ArgumentException)); Helper.BAToInt64Throw(byteArray, byteArray.Length - 1, typeof(ArgumentException)); Helper.BAToInt64Throw(byteArray, byteArray.Length, typeof(ArgumentOutOfRangeException)); Helper.BAToInt64Throw(byteArray, int.MaxValue, typeof(ArgumentOutOfRangeException)); Helper.BAToInt64Throw(new byte[] { }, 1, typeof(ArgumentOutOfRangeException)); Helper.BAToInt64Throw(null, 1, typeof(ArgumentNullException)); } catch (TestFailException e) { Log.Comment(e.Message); return MFTestResults.Fail; } return MFTestResults.Pass; } [TestMethod] public MFTestResults BitConverterTest_ToSingle() { try { var byteArray = new byte[]{ 0, 0, 0, 0, 128, 63, 0, 0, 112, 65, 0, 255, 127, 71, 0, 0, 128, 59, 0, 0, 128, 47, 73, 70, 131, 5, 75, 6, 158, 63, 77, 6, 158, 63, 80, 6, 158, 63, 30, 55, 190, 121, 255, 255, 127, 255, 255, 127, 127, 1, 0, 0, 0, 192, 255, 0, 0, 128, 255, 0, 0, 128, 127 }; Helper.BAToSingle(byteArray, 0, 0.0000000E+000F); Helper.BAToSingle(byteArray, 2, 1.0000000E+000F); Helper.BAToSingle(byteArray, 6, 1.5000000E+001F); Helper.BAToSingle(byteArray, 10, 6.5535000E+004F); Helper.BAToSingle(byteArray, 14, 3.9062500E-003F); Helper.BAToSingle(byteArray, 18, 2.3283064E-010F); Helper.BAToSingle(byteArray, 22, 1.2345000E-035F); Helper.BAToSingle(byteArray, 26, 1.2345671E+000F); Helper.BAToSingle(byteArray, 30, 1.2345673E+000F); Helper.BAToSingle(byteArray, 34, 1.2345676E+000F); Helper.BAToSingle(byteArray, 38, 1.2345679E+035F); Helper.BAToSingle(byteArray, 42, float.MinValue); Helper.BAToSingle(byteArray, 45, float.MaxValue); Helper.BAToSingle(byteArray, 49, float.Epsilon); Helper.BAToSingle(byteArray, 51, 0.0F / 0.0F); Helper.BAToSingle(byteArray, 55, -1.0F / 0.0F); Helper.BAToSingle(byteArray, 59, 1.0F / 0.0F); Helper.BAToSingleThrow(byteArray, int.MinValue, typeof(ArgumentOutOfRangeException)); Helper.BAToSingleThrow(byteArray, -1, typeof(ArgumentOutOfRangeException)); Helper.BAToSingleThrow(byteArray, byteArray.Length - 3, typeof(ArgumentException)); Helper.BAToSingleThrow(byteArray, byteArray.Length - 1, typeof(ArgumentException)); Helper.BAToSingleThrow(byteArray, byteArray.Length, typeof(ArgumentOutOfRangeException)); Helper.BAToSingleThrow(byteArray, int.MaxValue, typeof(ArgumentOutOfRangeException)); Helper.BAToSingleThrow(new byte[] { }, 1, typeof(ArgumentOutOfRangeException)); Helper.BAToSingleThrow(null, 1, typeof(ArgumentNullException)); } catch (TestFailException e) { Log.Comment(e.Message); return MFTestResults.Fail; } return MFTestResults.Pass; } [TestMethod] public MFTestResults BitConverterTest_ToUInt16() { try { var byteArray = new byte[] { 15, 0, 0, 255, 3, 16, 39, 255, 255, 127 }; Helper.BAToUInt16(byteArray, 1, 0); Helper.BAToUInt16(byteArray, 0, 15); Helper.BAToUInt16(byteArray, 3, 1023); Helper.BAToUInt16(byteArray, 5, 10000); Helper.BAToUInt16(byteArray, 8, (ushort)short.MaxValue); Helper.BAToUInt16(byteArray, 7, ushort.MaxValue); Helper.BAToUInt16Throw(byteArray, int.MinValue, typeof(ArgumentOutOfRangeException)); Helper.BAToUInt16Throw(byteArray, -1, typeof(ArgumentOutOfRangeException)); Helper.BAToUInt16Throw(byteArray, byteArray.Length - 1, typeof(ArgumentException)); Helper.BAToUInt16Throw(byteArray, byteArray.Length, typeof(ArgumentOutOfRangeException)); Helper.BAToUInt16Throw(byteArray, int.MaxValue, typeof(ArgumentOutOfRangeException)); Helper.BAToUInt16Throw(new byte[] { }, 1, typeof(ArgumentOutOfRangeException)); Helper.BAToUInt16Throw(null, 1, typeof(ArgumentNullException)); } catch (TestFailException e) { Log.Comment(e.Message); return MFTestResults.Fail; } return MFTestResults.Pass; } [TestMethod] public MFTestResults BitConverterTest_ToUInt32() { try { var byteArray = new byte[]{ 15, 0, 0, 0, 0, 16, 0, 255, 3, 0, 0, 202, 154, 59, 255, 255, 255, 255, 127 }; Helper.BAToUInt32(byteArray, 1, 0); Helper.BAToUInt32(byteArray, 0, 15); Helper.BAToUInt32(byteArray, 7, 1023); Helper.BAToUInt32(byteArray, 3, 1048576); Helper.BAToUInt32(byteArray, 10, 1000000000); Helper.BAToUInt32(byteArray, 15, int.MaxValue); Helper.BAToUInt32(byteArray, 14, uint.MaxValue); Helper.BAToUInt32Throw(byteArray, int.MinValue, typeof(ArgumentOutOfRangeException)); Helper.BAToUInt32Throw(byteArray, -1, typeof(ArgumentOutOfRangeException)); Helper.BAToUInt32Throw(byteArray, byteArray.Length - 3, typeof(ArgumentException)); Helper.BAToUInt32Throw(byteArray, byteArray.Length - 1, typeof(ArgumentException)); Helper.BAToUInt32Throw(byteArray, byteArray.Length, typeof(ArgumentOutOfRangeException)); Helper.BAToUInt32Throw(byteArray, int.MaxValue, typeof(ArgumentOutOfRangeException)); Helper.BAToUInt32Throw(new byte[] { }, 1, typeof(ArgumentOutOfRangeException)); Helper.BAToUInt32Throw(null, 1, typeof(ArgumentNullException)); } catch (TestFailException e) { Log.Comment(e.Message); return MFTestResults.Fail; } return MFTestResults.Pass; } [TestMethod] public MFTestResults BitConverterTest_ToUInt64() { try { var byteArray = new byte[]{ 255, 255, 255, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 100, 167, 179, 182, 224, 13, 0, 202, 154, 59, 0, 0, 0, 0, 170, 170, 170, 170, 170, 170, 0, 0, 232, 137, 4, 35, 199, 138, 255, 255, 255, 255, 255, 255, 255, 255, 127 }; Helper.BAToUInt64(byteArray, 3, 0); Helper.BAToUInt64(byteArray, 0, 16777215); Helper.BAToUInt64(byteArray, 21, 1000000000); Helper.BAToUInt64(byteArray, 7, 4294967296); Helper.BAToUInt64(byteArray, 29, 187649984473770); Helper.BAToUInt64(byteArray, 13, 1000000000000000000); Helper.BAToUInt64(byteArray, 35, 10000000000000000000); Helper.BAToUInt64(byteArray, 44, long.MaxValue); Helper.BAToUInt64(byteArray, 43, ulong.MaxValue); Helper.BAToUInt64Throw(byteArray, int.MinValue, typeof(ArgumentOutOfRangeException)); Helper.BAToUInt64Throw(byteArray, -1, typeof(ArgumentOutOfRangeException)); Helper.BAToUInt64Throw(byteArray, byteArray.Length - 7, typeof(ArgumentException)); Helper.BAToUInt64Throw(byteArray, byteArray.Length - 1, typeof(ArgumentException)); Helper.BAToUInt64Throw(byteArray, byteArray.Length, typeof(ArgumentOutOfRangeException)); Helper.BAToUInt64Throw(byteArray, int.MaxValue, typeof(ArgumentOutOfRangeException)); Helper.BAToUInt64Throw(new byte[] { }, 1, typeof(ArgumentOutOfRangeException)); Helper.BAToUInt64Throw(null, 1, typeof(ArgumentNullException)); } catch (TestFailException e) { Log.Comment(e.Message); return MFTestResults.Fail; } return MFTestResults.Pass; } [TestMethod] public MFTestResults BitConverterTest_ToString() { try { Helper.WriteByteArray(new byte[] { 0, 1, 2, 4, 8, 16, 32, 64, 128, 255 }, "00-01-02-04-08-10-20-40-80-FF"); Helper.WriteByteArray(new byte[] { 32, 0, 0, 42, 0, 65, 0, 125, 0, 197, 0, 168, 3, 41, 4, 172, 32 }, "20-00-00-2A-00-41-00-7D-00-C5-00-A8-03-29-04-AC-20"); Helper.WriteByteArray(new byte[] { 15, 0, 0, 128, 16, 39, 240, 216, 241, 255, 127 }, "0F-00-00-80-10-27-F0-D8-F1-FF-7F"); Helper.WriteByteArray(new byte[] { 15, 0, 0, 0, 0, 16, 0, 255, 3, 0, 0, 202, 154, 59, 255, 255, 255, 255, 127 }, "0F-00-00-00-00-10-00-FF-03-00-00-CA-9A-3B-FF-FF-FF-FF-7F"); Helper.WriteMultiLineByteArray(new byte[]{ 0, 0, 0, 0, 128, 63, 0, 0, 112, 65, 0, 255, 127, 71, 0, 0, 128, 59, 0, 0, 128, 47, 73, 70, 131, 5, 75, 6, 158, 63, 77, 6, 158, 63, 80, 6, 158, 63, 30, 55, 190, 121, 255, 255, 127, 255, 255, 127, 127, 1, 0, 0, 0, 192, 255, 0, 0, 128, 255, 0, 0, 128, 127 }, @"00-00-00-00-80-3F-00-00-70-41-00-FF-7F-47-00-00-80-3B-00-00 80-2F-49-46-83-05-4B-06-9E-3F-4D-06-9E-3F-50-06-9E-3F-1E-37 BE-79-FF-FF-7F-FF-FF-7F-7F-01-00-00-00-C0-FF-00-00-80-FF-00 00-80-7F"); Helper.WriteMultiLineByteArray(new byte[]{ 255, 255, 255, 0, 0, 20, 0, 33, 0, 0, 0, 1, 0, 0, 0, 100, 167, 179, 182, 224, 13, 0, 202, 154, 59, 0, 143, 91, 0, 170, 170, 170, 170, 170, 170, 0, 0, 232, 137, 4, 35, 199, 138, 255, 232, 244, 255, 252, 205, 255, 255, 129 }, @"FF-FF-FF-00-00-14-00-21-00-00-00-01-00-00-00-64-A7-B3-B6-E0 0D-00-CA-9A-3B-00-8F-5B-00-AA-AA-AA-AA-AA-AA-00-00-E8-89-04 23-C7-8A-FF-E8-F4-FF-FC-CD-FF-FF-81"); Helper.WriteMultiLineByteArray(new byte[]{ 0, 222, 0, 0, 0, 224, 111, 64, 0, 0, 224, 255, 255, 255, 239, 65, 0, 0, 131, 0, 0, 0, 112, 63, 0, 143, 0, 100, 0, 0, 240, 61, 223, 136, 30, 28, 254, 116, 170, 1, 250, 89, 140, 66, 202, 192, 243, 63, 251, 89, 140, 66, 202, 192, 243, 63, 252, 89, 140, 66, 202, 192, 243, 63, 82, 211, 187, 188, 232, 126, 255, 255, 255, 244, 255, 239, 127, 1, 0, 0, 0, 10, 17, 0, 0, 248, 255, 0, 88, 0, 91, 0, 0, 240, 255, 0, 0, 240, 157 }, @"00-DE-00-00-00-E0-6F-40-00-00-E0-FF-FF-FF-EF-41-00-00-83-00 00-00-70-3F-00-8F-00-64-00-00-F0-3D-DF-88-1E-1C-FE-74-AA-01 FA-59-8C-42-CA-C0-F3-3F-FB-59-8C-42-CA-C0-F3-3F-FC-59-8C-42 CA-C0-F3-3F-52-D3-BB-BC-E8-7E-FF-FF-FF-F4-FF-EF-7F-01-00-00 00-0A-11-00-00-F8-FF-00-58-00-5B-00-00-F0-FF-00-00-F0-9D"); } catch (TestFailException e) { Log.Comment(e.Message); return MFTestResults.Fail; } return MFTestResults.Pass; } [TestMethod] public MFTestResults BitConverterTest_ToStringEmpty() { var empty = new byte[] { }; if (BitConverter.ToString(empty) != string.Empty) { Log.Comment("BitConverter.ToString({}) doesn't return empty string"); return MFTestResults.Fail; } if (BitConverter.ToString(empty, 0) != string.Empty) { Log.Comment("BitConverter.ToString({}, 0) doesn't return empty string"); return MFTestResults.Fail; } if (BitConverter.ToString(empty, 0, 0) != string.Empty) { Log.Comment("BitConverter.ToString({}, 0, 0) doesn't return empty string"); return MFTestResults.Fail; } return MFTestResults.Pass; } [TestMethod] public MFTestResults BitConverterTest_ToStringThrow() { try { var bytes = new byte[] { 0, 1, 2, 4, 8, 16, 32, 64, 128, 255 }; Helper.ToStringThrow(null, typeof(ArgumentNullException)); Helper.ToStringThrow(null, 0, typeof(ArgumentNullException)); Helper.ToStringThrow(null, 0, 0, typeof(ArgumentNullException)); Helper.ToStringThrow(bytes, int.MinValue, typeof(ArgumentOutOfRangeException)); Helper.ToStringThrow(bytes, -1, typeof(ArgumentOutOfRangeException)); Helper.ToStringThrow(bytes, bytes.Length, typeof(ArgumentOutOfRangeException)); Helper.ToStringThrow(bytes, int.MaxValue, typeof(ArgumentOutOfRangeException)); Helper.ToStringThrow(bytes, int.MinValue, 1, typeof(ArgumentOutOfRangeException)); Helper.ToStringThrow(bytes, -1, 1, typeof(ArgumentOutOfRangeException)); Helper.ToStringThrow(bytes, bytes.Length, 1, typeof(ArgumentOutOfRangeException)); Helper.ToStringThrow(bytes, int.MaxValue, 1, typeof(ArgumentOutOfRangeException)); Helper.ToStringThrow(bytes, 0, -1, typeof(ArgumentOutOfRangeException)); Helper.ToStringThrow(bytes, 0, int.MinValue, typeof(ArgumentOutOfRangeException)); Helper.ToStringThrow(bytes, 0, bytes.Length + 1, typeof(ArgumentException)); Helper.ToStringThrow(bytes, 0, int.MaxValue, typeof(ArgumentException)); Helper.ToStringThrow(bytes, 1, bytes.Length, typeof(ArgumentException)); Helper.ToStringThrow(bytes, 1, int.MaxValue, typeof(ArgumentException)); Helper.ToStringThrow(bytes, bytes.Length - 1, 2, typeof(ArgumentException)); Helper.ToStringThrow(bytes, bytes.Length - 1, int.MaxValue, typeof(ArgumentException)); var empty = new byte[] { }; Helper.ToStringThrow(empty, 1, typeof(ArgumentOutOfRangeException)); Helper.ToStringThrow(empty, 1, 0, typeof(ArgumentOutOfRangeException)); Helper.ToStringThrow(empty, 0, 1, typeof(ArgumentOutOfRangeException)); } catch (TestFailException e) { Log.Comment(e.Message); return MFTestResults.Fail; } return MFTestResults.Pass; } } } ================================================ FILE: Zelig/Zelig/Test/RunTime/NETMF/mscorlib/bitconverter/Helper.cs ================================================ using System; using Microsoft.SPOT; namespace Microsoft.SPOT.Platform.Tests { class Helper { static string DigitialToHex(int x) { switch (x) { case 0: return "0"; case 1: return "1"; case 2: return "2"; case 3: return "3"; case 4: return "4"; case 5: return "5"; case 6: return "6"; case 7: return "7"; case 8: return "8"; case 9: return "9"; case 10: return "A"; case 11: return "B"; case 12: return "C"; case 13: return "D"; case 14: return "E"; case 15: return "F"; default: throw new Exception(); } } static string ByteToHex(byte b) { return DigitialToHex(b / 16) + DigitialToHex(b % 16); } static string LongToHex(long l) { string sHex = string.Empty; for (int i = 0; i < 8; i++) { sHex = ByteToHex((byte)(l & 0xff)) + sHex; l >>= 8; } return sHex; } static bool CompareByteArray(byte[] left, byte[] right) { if (left.Length != right.Length) { return false; } for (int i = 0; i < left.Length; i++) { if (left[i] != right[i]) { return false; } } return true; } static string ByteArrayToHex(byte[] bs) { string sHex = string.Empty; foreach (byte b in bs) { if (sHex.Length > 0) { sHex += "-"; } sHex += ByteToHex(b); } return sHex; } static public void DoubleToLongBits(double input, long expected) { long ret = BitConverter.DoubleToInt64Bits(input); if (ret != expected) { throw new TestFailException( "BitConverter.DoubleToInt64Bits", LongToHex(ret), LongToHex(expected), input); } } static public void GetBytesBool(bool input, byte[] expected) { byte[] ret = BitConverter.GetBytes(input); if (!CompareByteArray(ret, expected)) { throw new TestFailException( "BitConverter.GetBytes", ByteArrayToHex(ret), ByteArrayToHex(expected), input); } } static public void GetBytesChar(char input, byte[] expected) { byte[] ret = BitConverter.GetBytes(input); if (!CompareByteArray(ret, expected)) { throw new TestFailException( "BitConverter.GetBytes", ByteArrayToHex(ret), ByteArrayToHex(expected), input); } } static public void GetBytesDouble(double input, byte[] expected) { byte[] ret = BitConverter.GetBytes(input); if (!CompareByteArray(ret, expected)) { throw new TestFailException( "BitConverter.GetBytes", ByteArrayToHex(ret), ByteArrayToHex(expected), input); } } static public void GetBytesSingle(float input, byte[] expected) { byte[] ret = BitConverter.GetBytes(input); if (!CompareByteArray(ret, expected)) { throw new TestFailException( "BitConverter.GetBytes", ByteArrayToHex(ret), ByteArrayToHex(expected), input); } } static public void GetBytesInt64(long input, byte[] expected) { byte[] ret = BitConverter.GetBytes(input); if (!CompareByteArray(ret, expected)) { throw new TestFailException( "BitConverter.GetBytes", ByteArrayToHex(ret), ByteArrayToHex(expected), input); } } static public void GetBytesInt32(int input, byte[] expected) { byte[] ret = BitConverter.GetBytes(input); if (!CompareByteArray(ret, expected)) { throw new TestFailException( "BitConverter.GetBytes", ByteArrayToHex(ret), ByteArrayToHex(expected), input); } } static public void GetBytesInt16(short input, byte[] expected) { byte[] ret = BitConverter.GetBytes(input); if (!CompareByteArray(ret, expected)) { throw new TestFailException( "BitConverter.GetBytes", ByteArrayToHex(ret), ByteArrayToHex(expected), input); } } static public void GetBytesUInt64(ulong input, byte[] expected) { byte[] ret = BitConverter.GetBytes(input); if (!CompareByteArray(ret, expected)) { throw new TestFailException( "BitConverter.GetBytes", ByteArrayToHex(ret), ByteArrayToHex(expected), input); } } static public void GetBytesUInt32(uint input, byte[] expected) { byte[] ret = BitConverter.GetBytes(input); if (!CompareByteArray(ret, expected)) { throw new TestFailException( "BitConverter.GetBytes", ByteArrayToHex(ret), ByteArrayToHex(expected), input); } } static public void GetBytesUInt16(ushort input, byte[] expected) { byte[] ret = BitConverter.GetBytes(input); if (!CompareByteArray(ret, expected)) { throw new TestFailException( "BitConverter.GetBytes", ByteArrayToHex(ret), ByteArrayToHex(expected), input); } } static public void LongBitsToDouble(long input, double expected) { double ret = BitConverter.Int64BitsToDouble(input); if (ret != expected) { throw new TestFailException( "BitConverter.Int64BitsToDouble", ret, expected, LongToHex(input)); } } static public void BAToBool(byte[] bytes, int index, bool expected) { bool ret = BitConverter.ToBoolean(bytes, index); if (ret != expected) { throw new TestFailException( "BitConverter.ToBoolean", ret, expected, ByteArrayToHex(bytes), index); } } static public void BAToBoolThrow(byte[] bytes, int index, Type expectedExceptionType) { Exception exception = null; try { BitConverter.ToBoolean(bytes, index); } catch (Exception e) { exception = e; } if (exception == null || exception.GetType() != expectedExceptionType) { throw new TestFailException( "BitConverter.ToBoolean", exception, expectedExceptionType, ByteArrayToHex(bytes), index); } } static public void BAToChar(byte[] bytes, int index, char expected) { char ret = BitConverter.ToChar(bytes, index); if (ret != expected) { throw new TestFailException( "BitConverter.ToChar", ret, expected, ByteArrayToHex(bytes), index); } } static public void BAToCharThrow(byte[] bytes, int index, Type expectedExceptionType) { Exception exception = null; try { BitConverter.ToChar(bytes, index); } catch (Exception e) { exception = e; } if (exception == null || exception.GetType() != expectedExceptionType) { throw new TestFailException( "BitConverter.ToChar", exception, expectedExceptionType, ByteArrayToHex(bytes), index); } } static public void BAToDouble(byte[] bytes, int index, double expected) { double ret = BitConverter.ToDouble(bytes, index); if (ret != expected) { throw new TestFailException( "BitConverter.ToDouble", ret, expected, ByteArrayToHex(bytes), index); } } static public void BAToDoubleThrow(byte[] bytes, int index, Type expectedExceptionType) { Exception exception = null; try { BitConverter.ToDouble(bytes, index); } catch (Exception e) { exception = e; } if (exception == null || exception.GetType() != expectedExceptionType) { throw new TestFailException( "BitConverter.ToDouble", exception, expectedExceptionType, ByteArrayToHex(bytes), index); } } static public void BAToInt16(byte[] bytes, int index, short expected) { short ret = BitConverter.ToInt16(bytes, index); if (ret != expected) { throw new TestFailException( "BitConverter.ToInt16", ret, expected, ByteArrayToHex(bytes), index, index); } } static public void BAToInt16Throw(byte[] bytes, int index, Type expectedExceptionType) { Exception exception = null; try { BitConverter.ToInt16(bytes, index); } catch (Exception e) { exception = e; } if (exception == null || exception.GetType() != expectedExceptionType) { throw new TestFailException( "BitConverter.ToInt16", exception, expectedExceptionType, ByteArrayToHex(bytes), index); } } static public void BAToInt32(byte[] bytes, int index, int expected) { int ret = BitConverter.ToInt32(bytes, index); if (ret != expected) { throw new TestFailException( "BitConverter.ToInt32", ret, expected, ByteArrayToHex(bytes), index); } } static public void BAToInt32Throw(byte[] bytes, int index, Type expectedExceptionType) { Exception exception = null; try { BitConverter.ToInt32(bytes, index); } catch (Exception e) { exception = e; } if (exception == null || exception.GetType() != expectedExceptionType) { throw new TestFailException( "BitConverter.ToInt32", exception, expectedExceptionType, ByteArrayToHex(bytes), index); } } static public void BAToInt64(byte[] bytes, int index, long expected) { long ret = BitConverter.ToInt64(bytes, index); if (ret != expected) { throw new TestFailException( "BitConverter.ToInt64", ret, expected, ByteArrayToHex(bytes), index); } } static public void BAToInt64Throw(byte[] bytes, int index, Type expectedExceptionType) { Exception exception = null; try { BitConverter.ToInt64(bytes, index); } catch (Exception e) { exception = e; } if (exception == null || exception.GetType() != expectedExceptionType) { throw new TestFailException( "BitConverter.ToInt64", exception, expectedExceptionType, ByteArrayToHex(bytes), index); } } static public void BAToSingle(byte[] bytes, int index, float expected) { float ret = BitConverter.ToSingle(bytes, index); if (ret != expected) { throw new TestFailException( "BitConverter.ToSingle", ret, expected, ByteArrayToHex(bytes), index); } } static public void BAToSingleThrow(byte[] bytes, int index, Type expectedExceptionType) { Exception exception = null; try { BitConverter.ToSingle(bytes, index); } catch (Exception e) { exception = e; } if (exception == null || exception.GetType() != expectedExceptionType) { throw new TestFailException( "BitConverter.ToSingle", exception, expectedExceptionType, ByteArrayToHex(bytes), index); } } static public void BAToUInt16(byte[] bytes, int index, ushort expected) { ushort ret = BitConverter.ToUInt16(bytes, index); if (ret != expected) { throw new TestFailException( "BitConverter.ToUInt16", ret, expected, ByteArrayToHex(bytes), index); } } static public void BAToUInt16Throw(byte[] bytes, int index, Type expectedExceptionType) { Exception exception = null; try { BitConverter.ToUInt16(bytes, index); } catch (Exception e) { exception = e; } if (exception == null || exception.GetType() != expectedExceptionType) { throw new TestFailException( "BitConverter.ToUInt16", exception, expectedExceptionType, ByteArrayToHex(bytes), index); } } static public void BAToUInt32(byte[] bytes, int index, uint expected) { uint ret = BitConverter.ToUInt32(bytes, index); if (ret != expected) { throw new TestFailException( "BitConverter.ToUInt32", ret, expected, ByteArrayToHex(bytes), index); } } static public void BAToUInt32Throw(byte[] bytes, int index, Type expectedExceptionType) { Exception exception = null; try { BitConverter.ToUInt32(bytes, index); } catch (Exception e) { exception = e; } if (exception == null || exception.GetType() != expectedExceptionType) { throw new TestFailException( "BitConverter.ToUInt32", exception, expectedExceptionType, ByteArrayToHex(bytes), index); } } static public void BAToUInt64(byte[] bytes, int index, ulong expected) { ulong ret = BitConverter.ToUInt64(bytes, index); if (ret != expected) { throw new TestFailException( "BitConverter.ToUInt64", ret, expected, ByteArrayToHex(bytes), index); } } static public void BAToUInt64Throw(byte[] bytes, int index, Type expectedExceptionType) { Exception exception = null; try { BitConverter.ToUInt64(bytes, index); } catch (Exception e) { exception = e; } if (exception == null || exception.GetType() != expectedExceptionType) { throw new TestFailException( "BitConverter.ToUInt64", exception, expectedExceptionType, ByteArrayToHex(bytes), index); } } static public void WriteByteArray(byte[] bytes, string expected) { string ret = BitConverter.ToString(bytes); if (ret != expected) { throw new TestFailException( "BitConverter.ToString", ret, expected, ByteArrayToHex(bytes)); } } static public void WriteMultiLineByteArray(byte[] bytes, string expected) { string ret = string.Empty; const int rowSize = 20; int i; for (i = 0; i < bytes.Length - rowSize; i += rowSize) { if (ret.Length > 0) { ret += "\r\n"; } ret += BitConverter.ToString(bytes, i, rowSize); } if (ret.Length > 0) { ret += "\r\n"; } ret += BitConverter.ToString(bytes, i); if (ret != expected) { throw new TestFailException( "BitConverter.ToString(2)", ret, expected, ByteArrayToHex(bytes)); } } static public void ToStringThrow(byte[] bytes, Type expectedExceptionType) { Exception exception = null; try { BitConverter.ToString(bytes); } catch (Exception e) { exception = e; } if (exception == null || exception.GetType() != expectedExceptionType) { throw new TestFailException( "BitConverter.ToString", exception, expectedExceptionType, ByteArrayToHex(bytes)); } } static public void ToStringThrow(byte[] bytes, int index, Type expectedExceptionType) { Exception exception = null; try { BitConverter.ToString(bytes, index); } catch (Exception e) { exception = e; } if (exception == null || exception.GetType() != expectedExceptionType) { throw new TestFailException( "BitConverter.ToString", exception, expectedExceptionType, ByteArrayToHex(bytes), index); } } static public void ToStringThrow(byte[] bytes, int index, int length, Type expectedExceptionType) { Exception exception = null; try { BitConverter.ToString(bytes, index, length); } catch (Exception e) { exception = e; } if (exception == null || exception.GetType() != expectedExceptionType) { throw new TestFailException( "BitConverter.ToString", exception, expectedExceptionType, ByteArrayToHex(bytes), index, length); } } } } ================================================ FILE: Zelig/Zelig/Test/RunTime/NETMF/mscorlib/bitconverter/TestFailException.cs ================================================ using System; using System.Text; using Microsoft.SPOT; namespace Microsoft.SPOT.Platform.Tests { class TestFailException : Exception { static string GenerateArgList(object[] args) { StringBuilder builder = new StringBuilder(); foreach (object arg in args) { if (builder.Length > 0) { builder.Append(", "); } builder.Append(arg.ToString()); } return builder.ToString(); } static string GenerateMessage(string sMethod, object ret, object expected, object[] args) { return sMethod + "(" + GenerateArgList(args) + ") returns " + ret.ToString() + " rather than " + expected.ToString(); } static string GenerateMessage(string sMethod, Exception exception, Type expectedExceptionType, object[] args) { if (exception == null) { return sMethod + "(" + GenerateArgList(args) + ") throw no exception rather than " + expectedExceptionType.Name; } else { return sMethod + "(" + GenerateArgList(args) + ") throw exception " + exception.GetType().Name + " rather than " + expectedExceptionType.Name; } } public TestFailException(string sMethod, object ret, object expected, params object[] args) : base(GenerateMessage(sMethod, ret, expected, args)) { } public TestFailException(string sMethod, Exception exception, Type expectedExceptionType, params object[] args) : base(GenerateMessage(sMethod, exception, expectedExceptionType, args)) { } } } ================================================ FILE: Zelig/Zelig/Test/RunTime/NETMF/mscorlib/classes/classes1/ConstTests.cs ================================================ //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // Copyright (c) Microsoft Corporation. All rights reserved. //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// //#define GET_FIELD_WITH_BINDING_FLAGS_IMPLEMENTED using System; using System.Reflection; using Microsoft.Zelig.Test; namespace Microsoft.Zelig.Test { public class ConstTests : TestBase, ITestInterface { [SetUp] public InitializeResult Initialize() { Log.Comment("Adding set up for the tests."); // Add your functionality here. return InitializeResult.ReadyToGo; } [TearDown] public void CleanUp() { Log.Comment("Cleaning up after the tests"); } public override TestResult Run(string[] args) { TestResult result = TestResult.Pass; string testName = "Const"; result |= Assert.CheckFailed(Const1_Test(), testName, 1); result |= Assert.CheckFailed(Const2_Test(), testName, 2); result |= Assert.CheckFailed(Const3_Test(), testName, 3); result |= Assert.CheckFailed(Const4_Test(), testName, 4); result |= Assert.CheckFailed(Const5_Test(), testName, 5); result |= Assert.CheckFailed(Const6_Test(), testName, 6); result |= Assert.CheckFailed(Const9_Test(), testName, 9); result |= Assert.CheckFailed(Const11_Test(), testName, 11); result |= Assert.CheckFailed(Const12_Test(), testName, 12); result |= Assert.CheckFailed(Const13_Test(), testName, 13); result |= Assert.CheckFailed(Const14_Test(), testName, 14); result |= Assert.CheckFailed(Const15_Test(), testName, 15); result |= Assert.CheckFailed(Const16_Test(), testName, 16); result |= Assert.CheckFailed(Const17_Test(), testName, 17); result |= Assert.CheckFailed(Const18_Test(), testName, 18); result |= Assert.CheckFailed(Const19_Test(), testName, 19); result |= Assert.CheckFailed(Const20_Test(), testName, 20); result |= Assert.CheckFailed(Const21_Test(), testName, 21); result |= Assert.CheckFailed(Const24_Test(), testName, 24); result |= Assert.CheckFailed(Const25_Test(), testName, 25); result |= Assert.CheckFailed(Const26_Test(), testName, 26); result |= Assert.CheckFailed(Const27_Test(), testName, 27); result |= Assert.CheckFailed(Const28_Test(), testName, 28); result |= Assert.CheckFailed(Const30_Test(), testName, 30); result |= Assert.CheckFailed(Const32_Test(), testName, 32); result |= Assert.CheckFailed(Const33_Test(), testName, 33); result |= Assert.CheckFailed(Const34_Test(), testName, 34); result |= Assert.CheckFailed(Const35_Test(), testName, 35); #if GET_FIELD_WITH_BINDING_FLAGS_IMPLEMENTED result |= Assert.CheckFailed(Const42_Test(), testName, 42); result |= Assert.CheckFailed(Const43_Test(), testName, 43); #endif result |= Assert.CheckFailed(Const44_Test(), testName, 44); result |= Assert.CheckFailed(Const56_Test(), testName, 56); result |= Assert.CheckFailed(Const57_Test(), testName, 57); return result; } //--// //--// //--// //Const test methods //All test methods ported from folder current\test\cases\client\CLR\Conformance\10_classes\const //The following tests were removed because they were build failure tests: //7,8,10,23,29,31,36-41,45-52,55 //The following tests were removed because they caused the .Net Metadata Processor to crash //22,54, these tests failed in the Baseline document //Test 53 was removed because of an Attributes error this test was skipped in the Baseline document //20,42,43 [TestMethod] public TestResult Const1_Test() { //Ported from const1.cs Log.Comment("Section 10.3"); Log.Comment("A constant-declaration may include a set of attributes,"); Log.Comment("a new modifier, and one of four access modifiers. The"); Log.Comment("attributes and modifiers apply to all of the members "); Log.Comment("declared by the constant declaration."); if (ConstTestClass1.test()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Const2_Test() { //Ported from const2.cs Log.Comment("Section 10.3"); Log.Comment("A constant-declaration may include a set of attributes,"); Log.Comment("a new modifier, and one of four access modifiers. The"); Log.Comment("attributes and modifiers apply to all of the members "); Log.Comment("declared by the constant declaration."); if (ConstTestClass2.test()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Const3_Test() { //Ported from const3.cs Log.Comment("Section 10.3"); Log.Comment("A constant-declaration may include a set of attributes,"); Log.Comment("a new modifier, and one of four access modifiers. The"); Log.Comment("attributes and modifiers apply to all of the members "); Log.Comment("declared by the constant declaration."); if (ConstTestClass3.test()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Const4_Test() { //Ported from const4.cs Log.Comment("Section 10.3"); Log.Comment("A constant-declaration may include a set of attributes,"); Log.Comment("a new modifier, and one of four access modifiers. The"); Log.Comment("attributes and modifiers apply to all of the members "); Log.Comment("declared by the constant declaration."); if (ConstTestClass4.test()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Const5_Test() { //Ported from const5.cs Log.Comment("Section 10.3"); Log.Comment("A constant-declaration may include a set of attributes,"); Log.Comment("a new modifier, and one of four access modifiers. The"); Log.Comment("attributes and modifiers apply to all of the members "); Log.Comment("declared by the constant declaration."); if (ConstTestClass5.test()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Const6_Test() { //Ported from const6.cs Log.Comment("Section 10.3"); Log.Comment("A constant-declaration may include a set of attributes,"); Log.Comment("a new modifier, and one of four access modifiers. The"); Log.Comment("attributes and modifiers apply to all of the members "); Log.Comment("declared by the constant declaration."); if (ConstTestClass6.test()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Const9_Test() { //Ported from const9.cs Log.Comment("Section 10.3"); Log.Comment("A constant-declaration may include a set of attributes,"); Log.Comment("a new modifier, and one of four access modifiers. The"); Log.Comment("attributes and modifiers apply to all of the members "); Log.Comment("declared by the constant declaration."); if (ConstTestClass9.test()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Const11_Test() { Log.Comment("Section 10.3"); Log.Comment("The type specified in a constant declaration"); Log.Comment("must be byte, char, short, int, long, float,"); Log.Comment("double, double, bool, string, an enum-type,"); Log.Comment("or a reference type. Each constant-expression"); Log.Comment("must yield a value of the target type or of a "); Log.Comment("type that can be converted to the target type"); Log.Comment("by implicit conversion."); //Ported from const11.cs if (ConstTestClass11.test()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Const12_Test() { //Ported from const12.cs Log.Comment("Section 10.3"); Log.Comment("The type specified in a constant declaration"); Log.Comment("must be byte, char, short, int, long, float,"); Log.Comment("double, double, bool, string, an enum-type,"); Log.Comment("or a reference type. Each constant-expression"); Log.Comment("must yield a value of the target type or of a "); Log.Comment("type that can be converted to the target type"); Log.Comment("by implicit conversion."); if (ConstTestClass12.test()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Const13_Test() { //Ported from const13.cs Log.Comment("Section 10.3"); Log.Comment("The type specified in a constant declaration"); Log.Comment("must be byte, char, short, int, long, float,"); Log.Comment("double, double, bool, string, an enum-type,"); Log.Comment("or a reference type. Each constant-expression"); Log.Comment("must yield a value of the target type or of a "); Log.Comment("type that can be converted to the target type"); Log.Comment("by implicit conversion."); if (ConstTestClass13.test()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Const14_Test() { //Ported from const14.cs Log.Comment("Section 10.3"); Log.Comment("The type specified in a constant declaration"); Log.Comment("must be byte, char, short, int, long, float,"); Log.Comment("double, double, bool, string, an enum-type,"); Log.Comment("or a reference type. Each constant-expression"); Log.Comment("must yield a value of the target type or of a "); Log.Comment("type that can be converted to the target type"); Log.Comment("by implicit conversion."); if (ConstTestClass14.test()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Const15_Test() { //Ported from const15.cs Log.Comment("Section 10.3"); Log.Comment("The type specified in a constant declaration"); Log.Comment("must be byte, char, short, int, long, float,"); Log.Comment("double, double, bool, string, an enum-type,"); Log.Comment("or a reference type. Each constant-expression"); Log.Comment("must yield a value of the target type or of a "); Log.Comment("type that can be converted to the target type"); Log.Comment("by implicit conversion."); if (ConstTestClass15.test()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Const16_Test() { //Ported from const16.cs Log.Comment("Section 10.3"); Log.Comment("The type specified in a constant declaration"); Log.Comment("must be byte, char, short, int, long, float,"); Log.Comment("double, double, bool, string, an enum-type,"); Log.Comment("or a reference type. Each constant-expression"); Log.Comment("must yield a value of the target type or of a "); Log.Comment("type that can be converted to the target type"); Log.Comment("by implicit conversion."); if (ConstTestClass16.test()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Const17_Test() { //Ported from const17.cs Log.Comment("Section 10.3"); Log.Comment("The type specified in a constant declaration"); Log.Comment("must be byte, char, short, int, long, float,"); Log.Comment("double, double, bool, string, an enum-type,"); Log.Comment("or a reference type. Each constant-expression"); Log.Comment("must yield a value of the target type or of a "); Log.Comment("type that can be converted to the target type"); Log.Comment("by implicit conversion."); if (ConstTestClass17.test()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Const18_Test() { //Ported from const18.cs Log.Comment("Section 10.3"); Log.Comment("The type specified in a constant declaration"); Log.Comment("must be byte, char, short, int, long, float,"); Log.Comment("double, double, bool, string, an enum-type,"); Log.Comment("or a reference type. Each constant-expression"); Log.Comment("must yield a value of the target type or of a "); Log.Comment("type that can be converted to the target type"); Log.Comment("by implicit conversion."); if (ConstTestClass18.test()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Const19_Test() { //Ported from const19.cs Log.Comment("Section 10.3"); Log.Comment("The type specified in a constant declaration"); Log.Comment("must be byte, char, short, int, long, float,"); Log.Comment("double, double, bool, string, an enum-type,"); Log.Comment("or a reference type. Each constant-expression"); Log.Comment("must yield a value of the target type or of a "); Log.Comment("type that can be converted to the target type"); Log.Comment("by implicit conversion."); if (ConstTestClass19.test()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Const20_Test() { //Ported from const20.cs Log.Comment("Section 10.3"); Log.Comment("The type specified in a constant declaration"); Log.Comment("must be byte, char, short, int, long, float,"); Log.Comment("double, double, bool, string, an enum-type,"); Log.Comment("or a reference type. Each constant-expression"); Log.Comment("must yield a value of the target type or of a "); Log.Comment("type that can be converted to the target type"); Log.Comment("by implicit conversion."); if (ConstTestClass20.test()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Const21_Test() { //Ported from const21.cs Log.Comment("Section 10.3"); Log.Comment("The type specified in a constant declaration"); Log.Comment("must be byte, char, short, int, long, float,"); Log.Comment("double, double, bool, string, an enum-type,"); Log.Comment("or a reference type. Each constant-expression"); Log.Comment("must yield a value of the target type or of a "); Log.Comment("type that can be converted to the target type"); Log.Comment("by implicit conversion."); if (ConstTestClass21.test()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Const24_Test() { //Ported from const24.cs Log.Comment("Section 10.3"); Log.Comment("The type specified in a constant declaration"); Log.Comment("must be byte, char, short, int, long, float,"); Log.Comment("double, double, bool, string, an enum-type,"); Log.Comment("or a reference type. Each constant-expression"); Log.Comment("must yield a value of the target type or of a "); Log.Comment("type that can be converted to the target type"); Log.Comment("by implicit conversion."); if (ConstTestClass24.test()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Const25_Test() { //Ported from const25.cs Log.Comment("Section 10.3"); Log.Comment("A constant itself can participate in a constant-expression."); Log.Comment("Thus, a constant may be used in any construct that requires"); Log.Comment("a constant-expression. Examples of such constructs include"); Log.Comment("case labels, goto case statements, enum member declarations,"); Log.Comment("attributes, and other constant declarations."); if (ConstTestClass25.test()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Const26_Test() { //Ported from const26.cs Log.Comment("Section 10.3"); Log.Comment("A constant itself can participate in a constant-expression."); Log.Comment("Thus, a constant may be used in any construct that requires"); Log.Comment("a constant-expression. Examples of such constructs include"); Log.Comment("case labels, goto case statements, enum member declarations,"); Log.Comment("attributes, and other constant declarations."); if (ConstTestClass26.test()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Const27_Test() { //Ported from const27.cs Log.Comment("Section 10.3"); Log.Comment("A constant itself can participate in a constant-expression."); Log.Comment("Thus, a constant may be used in any construct that requires"); Log.Comment("a constant-expression. Examples of such constructs include"); Log.Comment("case labels, goto case statements, enum member declarations,"); Log.Comment("attributes, and other constant declarations."); if (ConstTestClass27.test()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Const28_Test() { //Ported from const28.cs Log.Comment("Section 10.3"); Log.Comment("A constant itself can participate in a constant-expression."); Log.Comment("Thus, a constant may be used in any construct that requires"); Log.Comment("a constant-expression. Examples of such constructs include"); Log.Comment("case labels, goto case statements, enum member declarations,"); Log.Comment("attributes, and other constant declarations."); if (ConstTestClass28.test()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Const30_Test() { //Ported from const30.cs Log.Comment("Section 10.3"); Log.Comment("Constants are permitted to depend on other constants"); Log.Comment("within the same project as long as the dependencies"); Log.Comment("are not of a circular nature. The compiler automatically"); Log.Comment("arranges to evaluate the constant declarations in the"); Log.Comment("appropriate order."); if (ConstTestClass30.test()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Const32_Test() { //Ported from const32.cs Log.Comment("Section 10.3"); Log.Comment("The type specified in a constant declaration"); Log.Comment("must be byte, char, short, int, long, float,"); Log.Comment("double, double, bool, string, an enum-type,"); Log.Comment("or a reference type. Each constant-expression"); Log.Comment("must yield a value of the target type or of a "); Log.Comment("type that can be converted to the target type"); Log.Comment("by implicit conversion."); if (ConstTestClass32.test()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Const33_Test() { //Ported from const33.cs Log.Comment("Section 10.3"); Log.Comment("The type specified in a constant declaration"); Log.Comment("must be byte, char, short, int, long, float,"); Log.Comment("double, double, bool, string, an enum-type,"); Log.Comment("or a reference type. Each constant-expression"); Log.Comment("must yield a value of the target type or of a "); Log.Comment("type that can be converted to the target type"); Log.Comment("by implicit conversion."); if (ConstTestClass33.test()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Const34_Test() { //Ported from const34.cs Log.Comment("Section 10.3"); Log.Comment("The type specified in a constant declaration"); Log.Comment("must be byte, char, short, int, long, float,"); Log.Comment("double, double, bool, string, an enum-type,"); Log.Comment("or a reference type. Each constant-expression"); Log.Comment("must yield a value of the target type or of a "); Log.Comment("type that can be converted to the target type"); Log.Comment("by implicit conversion."); if (ConstTestClass34.test()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Const35_Test() { //Ported from const35.cs Log.Comment("Section 10.3"); Log.Comment("The type specified in a constant declaration"); Log.Comment("must be byte, char, short, int, long, float,"); Log.Comment("double, double, bool, string, an enum-type,"); Log.Comment("or a reference type. Each constant-expression"); Log.Comment("must yield a value of the target type or of a "); Log.Comment("type that can be converted to the target type"); Log.Comment("by implicit conversion."); if (ConstTestClass35.test()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Const42_Test() { //Ported from const42.cs Log.Comment("Section 10.3"); Log.Comment("A constant declarator introduces a new member"); Log.Comment("This test is expected to fail"); if (ConstTestClass42.test()) { Log.Comment("This failure indicates a test is now passing that previously failed by design."); Log.Comment("It previously marked as known failure because of bug # 17246"); Log.Comment("The Test owner needs to verify that the change was intentional and remove the known failure."); return TestResult.Fail; } return TestResult.Pass; } [TestMethod] public TestResult Const43_Test() { //Ported from const43.cs Log.Comment("Section 10.3"); Log.Comment("A constant declarator introduces a new member"); Log.Comment("This test is expected to fail"); if (ConstTestClass43.test()) { Log.Comment("This failure indicates a test is now passing that previously failed by design."); Log.Comment("It previously marked as known failure because of bug # 17246"); Log.Comment("The Test owner needs to verify that the change was intentional and remove the known failure."); return TestResult.Fail; } return TestResult.Pass; } [TestMethod] public TestResult Const44_Test() { //Ported from const44.cs Log.Comment("Section 10.3"); Log.Comment("The type of a constant must be at least as acccessible as the constant itself."); if (ConstTestClass44.test()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Const56_Test() { //Ported from const56.cs Log.Comment("Section 10.3"); Log.Comment("...the only possible value for constants of reference-types other than "); Log.Comment("string is null"); if (ConstTestClass56.test()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Const57_Test() { //Ported from const57.cs Log.Comment("Section 10.3"); Log.Comment("A constant declaration that declares multiple constants is equivalent to "); Log.Comment("multiple declarations of single constants with the same attributes, "); Log.Comment("modifiers, and type. "); if (ConstTestClass57.test()) { return TestResult.Pass; } return TestResult.Fail; } //Const test classes class ConstTestClass1 { const int intI = 2; public static bool test() { if (intI == 2) { return true; } else { return false; } } } class ConstTestClass2_base { public const int intI = 1; } class ConstTestClass2 : ConstTestClass2_base { new const int intI = 2; public static bool test() { if (intI == 2) { return true; } else { return false; } } } class ConstTestClass3 { public const int intI = 2; public static bool test() { if (intI == 2) { return true; } else { return false; } } } class ConstTestClass4 { protected const int intI = 2; public static bool test() { if (intI == 2) { return true; } else { return false; } } } class ConstTestClass5 { internal const int intI = 2; public static bool test() { if (intI == 2) { return true; } else { return false; } } } class ConstTestClass6 { private const int intI = 2; public static bool test() { if (intI == 2) { return true; } else { return false; } } } class ConstTestClass7_sub { protected const int intI = 2; } class ConstTestClass9_sub { public const int intI = 2, intJ = 3; } class ConstTestClass9 { public static bool test() { if ((ConstTestClass9_sub.intI == 2) && (ConstTestClass9_sub.intJ == 3)) { return true; } else { return false; } } } class ConstTestClass11 { const byte byteB = 2; public static bool test() { if (byteB == 2) { return true; } else { return false; } } } class ConstTestClass12 { const char charC = 'b'; public static bool test() { if (charC == 'b') { return true; } else { return false; } } } class ConstTestClass13 { const short shortS = 2; public static bool test() { if (shortS == 2) { return true; } else { return false; } } } class ConstTestClass14 { //This appears to be a duplicate of Test 1 const int IntI = 2; public static bool test() { if (IntI == 2) { return true; } else { return false; } } } class ConstTestClass15 { const long longL = 2L; public static bool test() { if (longL == 2L) { return true; } else { return false; } } } class ConstTestClass16 { const float floatF = 2.0F; public static bool test() { if (floatF == 2.0F) { return true; } else { return false; } } } class ConstTestClass17 { const double doubleD = 2.0D; public static bool test() { if (doubleD == 2.0D) { return true; } else { return false; } } } class ConstTestClass18 { //Is this OK to cast? const double doubleD = (double)2.0M; public static bool test() { if (doubleD == (double)2.0M) { return true; } else { return false; } } } class ConstTestClass19 { const bool boolB = true; public static bool test() { if (boolB) { return true; } else { return false; } } } class ConstTestClass20 { const string stringS = "mytest"; public static bool test() { if (stringS.Equals("mytest")) { return true; } else { return false; } } } enum ConstTestClass21Enum { a = 1, b = 2 } class ConstTestClass21 { const ConstTestClass21Enum enumE = ConstTestClass21Enum.a; public static bool test() { if (enumE == ConstTestClass21Enum.a) { return true; } else { return false; } } } class ConstTestClass24 { const double doubleD = 2.0F; public static bool test() { if (doubleD == 2.0D) { return true; } else { return false; } } } class ConstTestClass25 { const int MyInt = 1; public static bool test() { int intI = 1; switch (intI) { case MyInt: return true; default: return false; } } } class ConstTestClass26 { const int MyInt = 1; public static bool test() { int intI = 2; switch (intI) { case 1: return true; case 2: goto case MyInt; default: return false; } } } class ConstTestClass27 { const int MyInt = 2; enum MyEnum { a = 1, b = MyInt } public static bool test() { if (MyEnum.b == (MyEnum)2) { return true; } else { return false; } } } class ConstTestClass28 { const int MyInt = 2; const int MyTest = MyInt; public static bool test() { if (MyTest == 2) { return true; } else { return false; } } } class ConstTestClass30_sub { public const int X = ConstTestClass30.Z + 1; public const int Y = 10; } class ConstTestClass30 { public const int Z = ConstTestClass30_sub.Y + 1; public static bool test() { if ((ConstTestClass30_sub.Y == 10) && (ConstTestClass30.Z == 11) && (ConstTestClass30_sub.X == 12)) { return true; } else { return false; } } } class ConstTestClass32 { const sbyte sbyteS = 2; public static bool test() { if (sbyteS == 2) { return true; } else { return false; } } } class ConstTestClass33 { const ushort ushortU = 2; public static bool test() { if (ushortU == 2) { return true; } else { return false; } } } class ConstTestClass34 { const uint uintU = 2; public static bool test() { if (uintU == 2) { return true; } else { return false; } } } class ConstTestClass35 { const ulong ulongU = 2; public static bool test() { if (ulongU == 2) { return true; } else { return false; } } } class ConstTestClass42 { const int intI = 10; public static bool test() { bool retval = false; FieldInfo fi = typeof(ConstTestClass42).GetField("intI", BindingFlags.NonPublic | BindingFlags.Static); if (null != fi) retval = true; return retval; } } class ConstTestClass43 { const int intI = 10; public static bool test() { bool retval = false; FieldInfo fi = typeof(ConstTestClass43).GetField("intI", BindingFlags.NonPublic | BindingFlags.Static); if (null != fi) if ((int)fi.GetValue(ConstTestClass43.intI) == 10) retval = true; return retval; } } class ConstTestClass44 { enum E { zero, one, two, three }; const E enumE = E.two; public static bool test() { bool retval = false; if (enumE == E.two) retval = true; return retval; } } class ConstTestClass55_sub { int _i; public ConstTestClass55_sub(int i) { _i = i; } public int GetI() { return _i; } } class ConstTestClass56_sub { int _i; public ConstTestClass56_sub(int i) { _i = i; } public int GetI() { return _i; } } class ConstTestClass56 { public readonly ConstTestClass56_sub mc = new ConstTestClass56_sub(10); public static bool test() { bool retval = false; ConstTestClass56 mmc = new ConstTestClass56(); if (mmc.mc.GetI() == 10) retval = true; return retval; } } class ConstTestClass57_sub_A { public const double X = 1.0, Y = 2.0, Z = 3.0; } class ConstTestClass57_sub_B { public const double X = 1.0; public const double Y = 2.0; public const double Z = 3.0; } class ConstTestClass57 { public static bool test() { bool retval = false; ConstTestClass57 mmc = new ConstTestClass57(); if ((ConstTestClass57_sub_A.X == ConstTestClass57_sub_B.X) && (ConstTestClass57_sub_A.Y == ConstTestClass57_sub_B.Y) && (ConstTestClass57_sub_A.Z == ConstTestClass57_sub_B.Z)) retval = true; return retval; } } } } ================================================ FILE: Zelig/Zelig/Test/RunTime/NETMF/mscorlib/classes/classes1/ConstructorsTests.cs ================================================ //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // Copyright (c) Microsoft Corporation. All rights reserved. //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// using System; using System.Reflection; using Microsoft.Zelig.Test; namespace Microsoft.Zelig.Test { public class ConstructorsTests : TestBase, ITestInterface { [SetUp] public InitializeResult Initialize() { Log.Comment("Adding set up for the tests."); // Add your functionality here. return InitializeResult.ReadyToGo; } [TearDown] public void CleanUp() { Log.Comment("Cleaning up after the tests"); } public override TestResult Run(string[] args) { TestResult result = TestResult.Pass; string testName = "Constructors"; result |= Assert.CheckFailed(Constructors1_Test(), testName, 1); result |= Assert.CheckFailed(Constructors2_Test(), testName, 2); result |= Assert.CheckFailed(Constructors3_Test(), testName, 3); result |= Assert.CheckFailed(Constructors5_Test(), testName, 5); result |= Assert.CheckFailed(Constructors6_Test(), testName, 6); result |= Assert.CheckFailed(Constructors8_Test(), testName, 8); result |= Assert.CheckFailed(Constructors10_Test(), testName, 10); result |= Assert.CheckFailed(Constructors11_Test(), testName, 11); result |= Assert.CheckFailed(Constructors13_Test(), testName, 13); result |= Assert.CheckFailed(Constructors16_Test(), testName, 16); result |= Assert.CheckFailed(Constructors17_Test(), testName, 17); result |= Assert.CheckFailed(Constructors20_Test(), testName, 20); result |= Assert.CheckFailed(Constructors21_Test(), testName, 21); result |= Assert.CheckFailed(Constructors22_Test(), testName, 22); result |= Assert.CheckFailed(Constructors23_Test(), testName, 23); result |= Assert.CheckFailed(Constructors24_Test(), testName, 24); result |= Assert.CheckFailed(Constructors25_Test(), testName, 25); result |= Assert.CheckFailed(Constructors26_Test(), testName, 26); result |= Assert.CheckFailed(Constructors27_Test(), testName, 27); result |= Assert.CheckFailed(Constructors28_Test(), testName, 28); result |= Assert.CheckFailed(Constructors31_Test(), testName, 31); result |= Assert.CheckFailed(Constructors32_Test(), testName, 32); result |= Assert.CheckFailed(Constructors33_Test(), testName, 33); result |= Assert.CheckFailed(Constructors34_Test(), testName, 34); result |= Assert.CheckFailed(Constructors35_Test(), testName, 35); result |= Assert.CheckFailed(Constructors44_Test(), testName, 44); result |= Assert.CheckFailed(Constructors45_Test(), testName, 45); result |= Assert.CheckFailed(Constructors46_Test(), testName, 46); result |= Assert.CheckFailed(Constructors47_Test(), testName, 47); result |= Assert.CheckFailed(Constructors50_Test(), testName, 50); result |= Assert.CheckFailed(Constructors51_Test(), testName, 51); result |= Assert.CheckFailed(Constructors52_Test(), testName, 52); result |= Assert.CheckFailed(Constructors54_Test(), testName, 54); result |= Assert.CheckFailed(Constructors55_Test(), testName, 55); result |= Assert.CheckFailed(Constructors56_Test(), testName, 56); result |= Assert.CheckFailed(Constructors57_Test(), testName, 57); result |= Assert.CheckFailed(Constructors64_Test(), testName, 64); return result; } //Constructors Tests //All test methods ported from folder current\test\cases\client\CLR\Conformance\10_classes\constructors //The following tests were removed because they were build failure tests: //12,14,15,18,29,30,35-43,48,49,59,60-62,65,67,69-74 //The following tests were removed because they require additional files to run //58,66,68. 58 Failed in the Baseline document, 66 and 68 were not included //Test 63 would not compile because it referenced System.Type.GetConstructors() which doesn't exist, //it was skipped in the baseline document //Test 63a was removed because it caused Null reference exceptions, it failed in the Baseline doc //47,58,63a Failed [TestMethod] public TestResult Constructors1_Test() { //Ported from Const1.cs Log.Comment("Tests if assignments in a constructor function."); if (ConstructorsTestClass1.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Constructors2_Test() { //Ported from Const2.cs Log.Comment("Tests if assignments in a constructor function, when constructor is public."); if (ConstructorsTestClass2.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Constructors3_Test() { //Ported from Const3.cs Log.Comment("Tests if assignments in a constructor function, when constructor is protected."); if (ConstructorsTestClass3.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Constructors5_Test() { //Ported from Const5.cs Log.Comment("Tests if assignments in a constructor function, when constructor is internal."); if (ConstructorsTestClass5.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Constructors6_Test() { //Ported from Const6.cs Log.Comment("Tests if assignments in a constructor function, when constructor is private."); if (ConstructorsTestClass6.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Constructors8_Test() { //Ported from Const8.cs Log.Comment("Tests if assignments in a constructor function, when constructor has one parameter."); if (ConstructorsTestClass8.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Constructors10_Test() { //Ported from Const10.cs Log.Comment("Tests if assignments in a constructor function, when constructor is called with one parameter"); Log.Comment("and is overloaded with an un-called zero parameter version"); if (ConstructorsTestClass10.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Constructors11_Test() { //Ported from Const11.cs Log.Comment("Tests if assignments in a constructor function, when constructor has two parameters."); if (ConstructorsTestClass11.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Constructors13_Test() { //Ported from Const13.cs Log.Comment("Tests if assignments in a constructor function, when constructor has ten parameters."); if (ConstructorsTestClass13.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Constructors16_Test() { //Ported from Const16.cs Log.Comment("Tests if assignments in a constructor function, when test class inherits constructor"); Log.Comment("and extends it with base"); if (ConstructorsTestClass16.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Constructors17_Test() { //Ported from Const17.cs Log.Comment("Tests if assignments in a constructor function, when test class inherits 2 constructors"); Log.Comment("and extends one of them with base"); if (ConstructorsTestClass17.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Constructors20_Test() { //Ported from Const20.cs Log.Comment("Tests if assignments in a constructor and its base are both functional"); if (ConstructorsTestClass20.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Constructors21_Test() { //Ported from Const21.cs Log.Comment("Tests if assignments in a constructor and its base, and its base's base are all functional"); if (ConstructorsTestClass21.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Constructors22_Test() { //Ported from Const22.cs Log.Comment("Tests if assignments in both a class' constructors are functional when a parametered constructor extends"); Log.Comment("a not-parametered one with 'this'"); if (ConstructorsTestClass22.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Constructors23_Test() { //Ported from Const23.cs Log.Comment("Tests if assignments in both a class' constructors are functional when a not-parametered constructor extends"); Log.Comment("a parametered one with 'this'"); if (ConstructorsTestClass23.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Constructors24_Test() { //Ported from Const24.cs Log.Comment("Tests if assignments in all a class' constructors are functional in a chain of extension using 'this'"); if (ConstructorsTestClass24.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Constructors25_Test() { //Ported from Const25.cs Log.Comment("Tests if assignments in all a class' constructors are functional when a parametered one extends a"); Log.Comment("not-parametered one, which in turn extends the class' base class constructor"); if (ConstructorsTestClass25.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Constructors26_Test() { //Ported from Const26.cs Log.Comment("Tests if assignments in all a class' constructors are functional when a not-parametered one extends a"); Log.Comment("not-parametered one in its base class, which in turn extends a parametered one in the base class"); if (ConstructorsTestClass26.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Constructors27_Test() { //Ported from Const27.cs Log.Comment("Tests if assignments in both a class' constructors are functional when a two-parametered constructor extends"); Log.Comment("a one-parametered one with 'this'"); if (ConstructorsTestClass27.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Constructors28_Test() { //Ported from Const28.cs Log.Comment("Tests if assignments in both a class' constructors are functional when a two-parametered constructor extends"); Log.Comment("a one-parametered one with 'this' and calls that constructor with a static arg"); if (ConstructorsTestClass28.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Constructors31_Test() { //Ported from Const31.cs Log.Comment("Tests if assignments in both a class' constructors are functional when a not-parametered constructor extends"); Log.Comment("a two-parametered one with 'this'"); if (ConstructorsTestClass31.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Constructors32_Test() { //Ported from Const32.cs Log.Comment("Tests if assignments in both a class' constructors are functional when a parametered constructor extends"); Log.Comment("a not-parametered one that is private with 'this'"); if (ConstructorsTestClass32.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Constructors33_Test() { //Ported from Const33.cs Log.Comment("Tests if assignments in a class' constructor are functional when the constructor is static"); if (ConstructorsTestClass33.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Constructors34_Test() { //Ported from Const34.cs Log.Comment("Tests if assignments in a class' constructor are functional when one constructor is static"); Log.Comment("and the other isn't"); if (ConstructorsTestClass34.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Constructors35_Test() { //From Bug# 16354/16719 Log.Comment("Tests if handled exceptions in constructors continues execution"); if (ConstructorsTestClass35.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Constructors44_Test() { //Ported from Const44.cs Log.Comment("Section 10.9.5"); Log.Comment("When a class declares only private constructors it "); Log.Comment("is not possible for other classes to derive from"); Log.Comment("the class or create instances of the class (an System.Exception"); Log.Comment("being classes nested within the class)."); if (ConstructorsTestClass44.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Constructors45_Test() { //Ported from Const45.cs Log.Comment("Section 10.11."); Log.Comment("It is possible to construct circular dependencies that"); Log.Comment("allow static fields with variable initializers to be"); Log.Comment("observed in their default value state."); if (ConstructorsTestClass45.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } //We initialize static constructors on load rather when enumerated, so order is not guaranteed (unlike desktop) [TestMethod] public TestResult Constructors46_Test() { //Ported from Const46.cs Log.Comment("Section 10.11."); Log.Comment("It is possible to construct circular dependencies that"); Log.Comment("allow static fields with variable initializers to be"); Log.Comment("observed in their default value state."); return TestResult.Skip; //if (ConstructorsTestClass46.testMethod()) //{ // return TestResult.Pass; //} //return TestResult.Fail; } [TestMethod] public TestResult Constructors47_Test() { //Ported from Const47.cs Log.Comment("Section 10.11."); Log.Comment("It is possible to construct circular dependencies that"); Log.Comment("allow static fields with variable initializers to be"); Log.Comment("observed in their default value state."); Log.Comment("This test is expected to fail."); return TestResult.Skip; //if (ConstructorsTestClass47.testMethod()) //{ // return TestResult.Fail; //} //return TestResult.Pass; } [TestMethod] public TestResult Constructors50_Test() { //Ported from Const50.cs Log.Comment("The scope of the parameters given by the formal"); Log.Comment("parameter list of a constructor includes the"); Log.Comment("constructor initializer of that declaration."); Log.Comment("Thus, a constructor initializer is permitted to"); Log.Comment("access the parameters of the constructor."); if (ConstructorsTestClass50.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Constructors51_Test() { //Ported from Const51.cs Log.Comment("Section 10.9"); Log.Comment("The scope of the parameters given by the formal"); Log.Comment("parameter list of a constructor includes the"); Log.Comment("constructor initializer of that declaration."); Log.Comment("Thus, a constructor initializer is permitted to"); Log.Comment("access the parameters of the constructor."); if (ConstructorsTestClass51.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Constructors52_Test() { Log.Comment("Testing a constructor with a '(params int[] values)' prototype, called with 3 ints"); //Ported from Const52.cs if (ConstructorsTestClass52.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Constructors54_Test() { //Ported from Const54.cs Log.Comment("Testing a constructor with a '(params int[] values)' prototype, called with 3 ints from its derived class"); if (ConstructorsTestClass54.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Constructors55_Test() { //Ported from Const55.cs Log.Comment("Testing a constructor with a '(params int[] values)' prototype, called with 3 ints"); Log.Comment(" from its derived class, and both constructors are 'protected internal'"); if (ConstructorsTestClass55.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Constructors56_Test() { Log.Comment("Testing a constructor with a '(params int[] values)' prototype, called with 3 ints"); Log.Comment(" from its derived class implicitly, and both constructors are 'internal'"); //Ported from Const56.cs if (ConstructorsTestClass56.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Constructors57_Test() { //Ported from Const57.cs Log.Comment("Testing a 'private' constructor with a '(params int[] values)' prototype, called with 3 ints"); if (ConstructorsTestClass57.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Constructors64_Test() { //Ported from Const64.cs //////Log.Comment("Instance constructors, destructors, and static constructors are not inherited"); //////if (ConstructorsTestClass64.testMethod()) //////{ ////// return TestResult.Pass; //////} //////return TestResult.Fail; return TestResult.Pass; } //Constructors Test Classes class ConstructorsTestClass1 { //no modifier ConstructorsTestClass1() { intI = 2; } int intI; public static bool testMethod() { ConstructorsTestClass1 test = new ConstructorsTestClass1(); if (test.intI == 2) { return true; } else { return false; } } } class ConstructorsTestClass2 { //public public ConstructorsTestClass2() { intI = 2; } int intI; public static bool testMethod() { ConstructorsTestClass2 test = new ConstructorsTestClass2(); if (test.intI == 2) { return true; } else { return false; } } } class ConstructorsTestClass3 { //protected protected ConstructorsTestClass3() { intI = 2; } int intI; public static bool testMethod() { ConstructorsTestClass3 test = new ConstructorsTestClass3(); if (test.intI == 2) { return true; } else { return false; } } } class ConstructorsTestClass5 { //internal internal ConstructorsTestClass5() { intI = 2; } int intI; public static bool testMethod() { ConstructorsTestClass5 test = new ConstructorsTestClass5(); if (test.intI == 2) { return true; } else { return false; } } } class ConstructorsTestClass6 { //private private ConstructorsTestClass6() { intI = 2; } int intI; public static bool testMethod() { ConstructorsTestClass6 test = new ConstructorsTestClass6(); if (test.intI == 2) { return true; } else { return false; } } } class ConstructorsTestClass8 { //one parameter ConstructorsTestClass8(int intX) { intI = intX; } int intI; public static bool testMethod() { ConstructorsTestClass8 test = new ConstructorsTestClass8(3); if (test.intI == 3) { return true; } else { return false; } } } class ConstructorsTestClass10 { ConstructorsTestClass10() { intI = 2; } ConstructorsTestClass10(int intX) { intI = intX; } int intI; public static bool testMethod() { ConstructorsTestClass10 test = new ConstructorsTestClass10(3); //calling constructor with parameter if (test.intI == 3) { return true; } else { return false; } } } class ConstructorsTestClass11 { //multiple parameters ConstructorsTestClass11(int intX, int intY) { intI = intX + intY; } int intI; public static bool testMethod() { ConstructorsTestClass11 test = new ConstructorsTestClass11(3, 4); if (test.intI == 7) { return true; } else { return false; } } } class ConstructorsTestClass13 { //multiple parameters ConstructorsTestClass13(int int1, int int2, int int3, int int4, int int5, int int6, int int7, int int8, int int9, int int10) { intI = int1 + int2 + int3 + int4 + int5 + int6 + int7 + int8 + int9 + int10; } int intI; public static bool testMethod() { ConstructorsTestClass13 test = new ConstructorsTestClass13(1,2,3,4,5,6,7,8,9,10); if (test.intI == 55) { return true; } else { return false; } } } class ConstructorsTestClass16_Base { public int intI = 1; protected ConstructorsTestClass16_Base() { intI = 2; } } class ConstructorsTestClass16 : ConstructorsTestClass16_Base { //base constructor initializer ConstructorsTestClass16() : base() { intI = intI * 2; } public static bool testMethod() { ConstructorsTestClass16 Test = new ConstructorsTestClass16(); if (Test.intI == 4) { return true; } else { return false; } } } class ConstructorsTestClass17_Base { public int intI = 1; protected ConstructorsTestClass17_Base() { intI = 2; } protected ConstructorsTestClass17_Base(int intJ) { intI = intJ; } } class ConstructorsTestClass17 : ConstructorsTestClass17_Base { //base constructor initializer ConstructorsTestClass17() : base(3) { intI = intI * 2; } public static bool testMethod() { ConstructorsTestClass17 Test = new ConstructorsTestClass17(); if (Test.intI == 6) { return true; } else { return false; } } } class ConstructorsTestClass20_Base { public int intI = 1; protected ConstructorsTestClass20_Base(int intJ, int intK) { intI = intJ + intK; } } class ConstructorsTestClass20 : ConstructorsTestClass20_Base { //base constructor initializer ConstructorsTestClass20() : base(3, 4) { intI = intI * 2; } public static bool testMethod() { ConstructorsTestClass20 Test = new ConstructorsTestClass20(); if (Test.intI == 14) { return true; } else { return false; } } } class ConstructorsTestClass21_Base1 { public int intI = 1; protected ConstructorsTestClass21_Base1() { intI = 2; } } class ConstructorsTestClass21_Base2 : ConstructorsTestClass21_Base1 { protected ConstructorsTestClass21_Base2() : base() { intI = intI * 2; } } class ConstructorsTestClass21 : ConstructorsTestClass21_Base2 { //base constructor initializer ConstructorsTestClass21() : base() { intI = intI * 2; } public static bool testMethod() { ConstructorsTestClass21 test = new ConstructorsTestClass21(); if (test.intI == 8) { return true; } else { return false; } } } class ConstructorsTestClass22 { int intI = 1; ConstructorsTestClass22() { intI = 2; } //this constructor initializer ConstructorsTestClass22(int intJ) : this() { intI = intI * intJ; } public static bool testMethod() { ConstructorsTestClass22 Test = new ConstructorsTestClass22(2); if (Test.intI == 4) { return true; } else { return false; } } } class ConstructorsTestClass23 { int intI = 1; ConstructorsTestClass23() : this(3) { intI = intI * 2; } //this constructor initializer ConstructorsTestClass23(int intJ) { intI = intJ; } public static bool testMethod() { ConstructorsTestClass23 Test = new ConstructorsTestClass23(); if (Test.intI == 6) { return true; } else { return false; } } } class ConstructorsTestClass24 { int intI = 1; ConstructorsTestClass24() { intI = 2; } //this constructor initializer ConstructorsTestClass24(int intJ) : this() { intI = intI * intJ; } //this constructor initializer ConstructorsTestClass24(int intK, int intL) : this(3) { intI = (intI + intK) * intL; } public static bool testMethod() { ConstructorsTestClass24 Test = new ConstructorsTestClass24(3, 4); if (Test.intI == 36) { return true; } else { return false; } } } class ConstructorsTestClass25_Base { public int intI = 1; protected ConstructorsTestClass25_Base() { intI = 2; } } class ConstructorsTestClass25 : ConstructorsTestClass25_Base { //base constructor initializer ConstructorsTestClass25() : base() { intI = intI * 2; } //this constructor initializer ConstructorsTestClass25(int intJ) : this() { intI = intI + intJ; } public static bool testMethod() { ConstructorsTestClass25 Test = new ConstructorsTestClass25(3); if (Test.intI == 7) { return true; } else { return false; } } } class ConstructorsTestClass26_Base { public int intI = 1; //this constructor initializer protected ConstructorsTestClass26_Base() : this(3) { intI = intI * 2; } protected ConstructorsTestClass26_Base(int intJ) { intI = intJ; } } class ConstructorsTestClass26 : ConstructorsTestClass26_Base { //base constructor initializer ConstructorsTestClass26() : base() { intI = intI * 2; } public static bool testMethod() { ConstructorsTestClass26 Test = new ConstructorsTestClass26(); if (Test.intI == 12) { return true; } else { return false; } } } class ConstructorsTestClass27 { int intI = 1; ConstructorsTestClass27(int intJ) { intI = intJ; } //this constructor initializer ConstructorsTestClass27(int intK, int intL) : this(intL) { intI = intI + intK; } public static bool testMethod() { ConstructorsTestClass27 Test = new ConstructorsTestClass27(3, 4); if (Test.intI == 7) { return true; } else { return false; } } } class ConstructorsTestClass28 { static int int3 = 3; int intI = 1; ConstructorsTestClass28(int intJ) { intI = intJ; } //this constructor initializer ConstructorsTestClass28(int intK, int intL) : this(ConstructorsTestClass28.int3) { intI = (intI + intK) * intL; } public static bool testMethod() { ConstructorsTestClass28 Test = new ConstructorsTestClass28(3, 4); if (Test.intI == 24) { return true; } else { return false; } } } class ConstructorsTestClass31 { int intI = 1; ConstructorsTestClass31() : this(3, 4) { intI = intI * 2; } //this constructor initializer ConstructorsTestClass31(int intK, int intL) { intI = intK + intL; } public static bool testMethod() { ConstructorsTestClass31 Test = new ConstructorsTestClass31(); if (Test.intI == 14) { return true; } else { return false; } } } class ConstructorsTestClass32 { int intI = 1; private ConstructorsTestClass32() { intI = 2; } //this constructor initializer ConstructorsTestClass32(int intJ) : this() { intI = intI * intJ; } public static bool testMethod() { ConstructorsTestClass32 Test = new ConstructorsTestClass32(2); if (Test.intI == 4) { return true; } else { return false; } } } class ConstructorsTestClass33 { //static constructor static ConstructorsTestClass33() { intI = 2; } static int intI = 1; public static bool testMethod() { if (intI == 2) { return true; } else { return false; } } } class ConstructorsTestClass34 { //static constructor static ConstructorsTestClass34() { intI = 2; } ConstructorsTestClass34() { intI = 3; } static int intI = 1; public static bool testMethod() { bool RetVal = true; if (intI != 2) { RetVal = false; } ConstructorsTestClass34 Test = new ConstructorsTestClass34(); if (intI != 3) { RetVal = false; } return RetVal; } } class ConstructorsTestClass35 { // static constructor - with Exception static ConstructorsTestClass35() { try { throw new Exception(); } catch { } intI = 5; } static int intI = 1; public static bool testMethod() { return (intI == 5); } } class ConstructorsTestClass44_Base { protected int MyInt = 2; private ConstructorsTestClass44_Base() { } public ConstructorsTestClass44_Base(int intI) { MyInt = intI; } } class ConstructorsTestClass44 : ConstructorsTestClass44_Base { public ConstructorsTestClass44() : base(1) { } public static bool testMethod() { ConstructorsTestClass44 test = new ConstructorsTestClass44(); if (test.MyInt == 1) { return true; } else { return false; } } } class ConstructorsTestClass45 { int intI; private ConstructorsTestClass45() { intI = 1; } public static bool testMethod() { return InnerClass.testMethod(); } class InnerClass { public static bool testMethod() { ConstructorsTestClass45 test = new ConstructorsTestClass45(); if (test.intI == 1) { return true; } else { return false; } } } } class ConstructorsTestClass46_sub { public static int X = ConstructorsTestClass46.Y + 1; } class ConstructorsTestClass46 { public static int Y = ConstructorsTestClass46_sub.X + 1; public static bool testMethod() { if ((ConstructorsTestClass46_sub.X == 1) && (ConstructorsTestClass46.Y == 2)) { return true; } else { Log.Exception("Expected X==1, got X=" + ConstructorsTestClass46_sub.X); Log.Exception("Expected Y==2, got Y=" + ConstructorsTestClass46.Y); return false; } } } class ConstructorsTestClass47 { public static int X = ConstructorsTestClass47_sub.Y + 1; public static bool testMethod() { if ((ConstructorsTestClass47.X == 2) && (ConstructorsTestClass47_sub.Y == 1)) { return true; } else { return false; } } } class ConstructorsTestClass47_sub { public static int Y = ConstructorsTestClass47.X + 1; } class ConstructorsTestClass50_Base { public int intI; public ConstructorsTestClass50_Base(int x, int y) { intI = x * 2 + y * 3; } } class ConstructorsTestClass50 : ConstructorsTestClass50_Base { public ConstructorsTestClass50(int x, int y) : base(x + y, x - y) { } public static bool testMethod() { ConstructorsTestClass50 test = new ConstructorsTestClass50(5, 3); if (test.intI == 22) { return true; } else { return false; } } } class ConstructorsTestClass51 { int intI; public ConstructorsTestClass51(int x, int y, int z) { intI = x * 2 + y * 3; } public ConstructorsTestClass51(int x, int y) : this(x + y, x - y, 0) { } public static bool testMethod() { ConstructorsTestClass51 test = new ConstructorsTestClass51(5, 3); if (test.intI == 22) { return true; } else { return false; } } } class ConstructorsTestClass52 { int intTest; public ConstructorsTestClass52(params int[] values) { intTest = values[0] + values[1] + values[2]; } public static bool testMethod() { int intI = 1; int intJ = 2; int intK = 3; ConstructorsTestClass52 mc = new ConstructorsTestClass52(intI, intJ, intK); if (mc.intTest == 6) { return true; } else { return false; } } } class ConstructorsTestClass53 { int intTest; public ConstructorsTestClass53(params int[] values) { intTest = values[0] + values[1] + values[2]; } public static bool testMethod() { int intI = 1; int intJ = 2; int intK = 3; ConstructorsTestClass53 mc = new ConstructorsTestClass53(intI, intJ, intK); if (mc.intTest == 6) { return true; } else { return false; } } } class ConstructorsTestClass54_base { public int intTest; protected ConstructorsTestClass54_base(params int[] values) { intTest = values[0] + values[1] + values[2]; } } class ConstructorsTestClass54 : ConstructorsTestClass54_base { protected ConstructorsTestClass54(params int[] values) : base(values) { } public static bool testMethod() { int intI = 1; int intJ = 2; int intK = 3; ConstructorsTestClass54 mc = new ConstructorsTestClass54(intI, intJ, intK); if (mc.intTest == 6) { return true; } else { return false; } } } class ConstructorsTestClass55_Base { public int intTest; protected internal ConstructorsTestClass55_Base(params int[] values) { intTest = values[0] + values[1] + values[2]; } } class ConstructorsTestClass55 : ConstructorsTestClass55_Base { protected internal ConstructorsTestClass55(params int[] values) : base(values) { } public static bool testMethod() { int intI = 1; int intJ = 2; int intK = 3; ConstructorsTestClass55 mc = new ConstructorsTestClass55(intI, intJ, intK); if (mc.intTest == 6) { return true; } else { return false; } } } class ConstructorsTestClass56_Sub { public int intTest; internal ConstructorsTestClass56_Sub(params int[] values) { intTest = values[0] + values[1] + values[2]; } } class ConstructorsTestClass56 { public static bool testMethod() { int intI = 1; int intJ = 2; int intK = 3; ConstructorsTestClass56_Sub mc = new ConstructorsTestClass56_Sub(intI, intJ, intK); if (mc.intTest == 6) { return true; } else { return false; } } } class ConstructorsTestClass57 { int intTest; private ConstructorsTestClass57(params int[] values) { intTest = values[0] + values[1] + values[2]; } public static bool testMethod() { int intI = 1; int intJ = 2; int intK = 3; ConstructorsTestClass57 mc = new ConstructorsTestClass57(intI, intJ, intK); if (mc.intTest == 6) { return true; } else { return false; } } } public class ConstructorsTestClass64_Base { public ConstructorsTestClass64_Base() { } ~ConstructorsTestClass64_Base() { } } class ConstructorsTestClass64_Derived : ConstructorsTestClass64_Base { } //////class ConstructorsTestClass64 //////{ ////// public static bool testMethod() ////// { ////// ConstructorsTestClass64_Derived d = new ConstructorsTestClass64_Derived(); ////// MethodInfo mi = d.GetType().GetMethod("Finalize", BindingFlags.Public | BindingFlags.Instance | BindingFlags.Static); ////// if (null != mi) ////// { ////// return false; ////// } ////// return true; ////// } //////} } } ================================================ FILE: Zelig/Zelig/Test/RunTime/NETMF/mscorlib/classes/classes1/DeclarationsTests.cs ================================================ //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // Copyright (c) Microsoft Corporation. All rights reserved. //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// using System; using System.Reflection; using Microsoft.Zelig.Test; namespace Microsoft.Zelig.Test { public class DeclarationsTests : TestBase, ITestInterface { [SetUp] public InitializeResult Initialize() { Log.Comment("Adding set up for the tests"); // Add your functionality here. return InitializeResult.ReadyToGo; } [TearDown] public void CleanUp() { Log.Comment("Cleaning up after the tests"); } public override TestResult Run(string[] args) { TestResult result = TestResult.Pass; result |= Assert.CheckFailed(Meta_Test(), "Meta", 0); string testName = "BaseClass"; result |= Assert.CheckFailed(BaseClass1_Test(), testName, 1); result |= Assert.CheckFailed(BaseClass2_Test(), testName, 2); result |= Assert.CheckFailed(BaseClass3_Test(), testName, 3); result |= Assert.CheckFailed(BaseClass4_Test(), testName, 4); result |= Assert.CheckFailed(BaseClass10_Test(), testName, 10); result |= Assert.CheckFailed(BaseClass13_Test(), testName, 13); result |= Assert.CheckFailed(BaseClass25_Test(), testName, 25); result |= Assert.CheckFailed(BaseClass29_Test(), testName, 29); testName = "Modifiers"; result |= Assert.CheckFailed(Modifiers2_Test(), testName, 2); result |= Assert.CheckFailed(Modifiers3_Test(), testName, 3); result |= Assert.CheckFailed(Modifiers4_Test(), testName, 4); result |= Assert.CheckFailed(Modifiers6_Test(), testName, 6); result |= Assert.CheckFailed(Modifiers7_Test(), testName, 7); result |= Assert.CheckFailed(Modifiers8_Test(), testName, 8); result |= Assert.CheckFailed(Modifiers10_Test(), testName, 10); result |= Assert.CheckFailed(Modifiers11_Test(), testName, 11); result |= Assert.CheckFailed(Modifiers12_Test(), testName, 12); result |= Assert.CheckFailed(Modifiers13_Test(), testName, 13); result |= Assert.CheckFailed(Modifiers14_Test(), testName, 14); result |= Assert.CheckFailed(Modifiers23_Test(), testName, 23); result |= Assert.CheckFailed(Modifiers24_Test(), testName, 24); result |= Assert.CheckFailed(Modifiers25_Test(), testName, 25); result |= Assert.CheckFailed(Modifiers26_Test(), testName, 26); result |= Assert.CheckFailed(Modifiers31_Test(), testName, 31); return result; } //--// //--// //--// [TestMethod] public TestResult Meta_Test() { return TestResult.Pass; } //Delcarations Tests //All test methods ported from folder current\test\cases\client\CLR\Conformance\10_classes\Declartations //The BaseClass*_Test() functions are ported from Declarations\basclass\basec*.cs files //The Modifiers*_Test() functions are ported from Declarations\basclass\mod*.cs files //The following tests were removed because they were build failure tests: //BaseClass: 5-9,11,12,14-24,26-28 //Modifiers: 1,5,9,15-22,27-30,32 [TestMethod] public TestResult BaseClass1_Test() { Log.Comment("Tests an int declaration with assignment in a base class"); if (BaseClassTestClass1.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult BaseClass2_Test() { Log.Comment("Tests a function declaration in a implementing class still"); Log.Comment("works after child is cast as an implemented interface"); if (BaseClassTestClass2.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult BaseClass3_Test() { Log.Comment("Tests a function declaration in an implementing class still works after child is cast as"); Log.Comment("each of two implemented interfaces"); if (BaseClassTestClass3.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult BaseClass4_Test() { Log.Comment("Tests a function declaration in a child class still works after child is cast as"); Log.Comment("its parent class and an interface it implements"); if (BaseClassTestClass4.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult BaseClass10_Test() { Log.Comment("Section 10.1"); Log.Comment("The base classes of a class are the direct base"); Log.Comment("class and its base classes. In other words, the"); Log.Comment("set of base classes is the transitive closure of the "); Log.Comment("direct base class relatationship."); if (BaseClassTestClass10.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult BaseClass13_Test() { Log.Comment("Section 10.1"); Log.Comment("Note that a class does not depend on the"); Log.Comment("classes that are nested within it. "); if (BaseClassTestClass13.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult BaseClass25_Test() { Log.Comment("10.1.2.1 "); Log.Comment("inheriting from nested types"); if (BaseClassTestClass25.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult BaseClass29_Test() { Log.Comment("10.1.2.1 "); Log.Comment("inheriting from nested types"); if (BaseClassTestClass29.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Modifiers2_Test() { Log.Comment("Testing a public int inside an inner class with modifier 'new' "); if (ModifiersTestClass2.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Modifiers3_Test() { Log.Comment("Testing a public int directly inside a public class"); if (ModifiersTestClass3.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Modifiers4_Test() { Log.Comment("Testing a public int inside an inner class with modifier 'public' "); if (ModifiersTestClass4.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Modifiers6_Test() { Log.Comment("Testing a public int inside an inner class with modifier 'protected' "); if (ModifiersTestClass6.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Modifiers7_Test() { Log.Comment("Testing a public int directly inside an internal class"); if (ModifiersTestClass7.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Modifiers8_Test() { Log.Comment("Testing a public int inside an inner class with modifier 'internal' "); if (ModifiersTestClass8.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Modifiers10_Test() { Log.Comment("Testing a public int inside an inner class with modifier 'private' "); if (ModifiersTestClass10.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Modifiers11_Test() { Log.Comment("Testing a public int inside an abstract class that is implemented"); if (ModifiersTestClass11.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Modifiers12_Test() { Log.Comment("Testing a public int inside an inner abstract class that is implemented"); if (ModifiersTestClass12.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Modifiers13_Test() { Log.Comment("Testing a public int directly inside a sealed class"); if (ModifiersTestClass13.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Modifiers14_Test() { Log.Comment("Testing a public int inside an inner sealed class"); if (ModifiersTestClass14.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Modifiers23_Test() { Log.Comment("An abstract class cannot be instantiated, and it is"); Log.Comment("an error to use the new operator on an abstract class."); Log.Comment("While it is possible to have variables and values whose"); Log.Comment("compile-time types are abstract, such variables and values"); Log.Comment("will necessarily either be null or contain references"); Log.Comment("to instances of non-abstract classes derived from the "); Log.Comment("abstract types."); if (ModifiersTestClass23.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Modifiers24_Test() { Log.Comment("An abstract class cannot be instantiated, and it is"); Log.Comment("an error to use the new operator on an abstract class."); Log.Comment("While it is possible to have variables and values whose"); Log.Comment("compile-time types are abstract, such variables and values"); Log.Comment("will necessarily either be null or contain references"); Log.Comment("to instances of non-abstract classes derived from the "); Log.Comment("abstract types."); if (ModifiersTestClass24.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Modifiers25_Test() { Log.Comment("Section 10.1"); Log.Comment("An abstract class is permitted (but not required)"); Log.Comment("to contain abstract methods and accessors."); if (ModifiersTestClass25.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Modifiers26_Test() { Log.Comment("Section 10.1"); Log.Comment("An abstract class is permitted (but not required)"); Log.Comment("to contain abstract methods and accessors."); if (ModifiersTestClass26.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Modifiers31_Test() { Log.Comment("Section 10.1"); Log.Comment("When a non-abstract class is derived from"); Log.Comment("an abstract class, the non-abstract class must"); Log.Comment("be include actual implementations of all inherited "); Log.Comment("abstract methods and accessors. Such implementations"); Log.Comment("are provided by overriding the abstract methods"); Log.Comment("and accessors."); if (ModifiersTestClass31.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } class BaseClassTestClass1_Base { public int intI = 2; } class BaseClassTestClass1 : BaseClassTestClass1_Base { public static bool testMethod() { BaseClassTestClass1 MC = new BaseClassTestClass1(); if (MC.intI == 2) { return true; } else { return false; } } } interface BaseClassTestClass2_Base { int RetInt(); } class BaseClassTestClass2 : BaseClassTestClass2_Base { public int RetInt() { return 2; } public static bool testMethod() { BaseClassTestClass2 MC = new BaseClassTestClass2(); BaseClassTestClass2_Base Test = (BaseClassTestClass2_Base)MC; if (Test.RetInt() == 2) { return true; } else { return false; } } } interface BaseClassTestClass3_Base1 { int RetInt(); } interface BaseClassTestClass3_Base2 { int RetInt2(); } class BaseClassTestClass3 : BaseClassTestClass3_Base1, BaseClassTestClass3_Base2 { public int RetInt() { return 2; } public int RetInt2() { return 3; } public static bool testMethod() { BaseClassTestClass3 MC = new BaseClassTestClass3(); BaseClassTestClass3_Base1 Test1 = (BaseClassTestClass3_Base1)MC; BaseClassTestClass3_Base2 Test2 = (BaseClassTestClass3_Base2)MC; if ((Test1.RetInt() == 2) && (Test2.RetInt2() == 3)) { return true; } else { return false; } } } class BaseClassTestClass4_Base1 { public int RetInt() { return 2; } } interface BaseClassTestClass4_Base2 { int RetInt2(); } class BaseClassTestClass4 : BaseClassTestClass4_Base1, BaseClassTestClass4_Base2 { public int RetInt2() { return 3; } public static bool testMethod() { BaseClassTestClass4 MC = new BaseClassTestClass4(); BaseClassTestClass4_Base1 Test1 = (BaseClassTestClass4_Base1)MC; BaseClassTestClass4_Base2 Test2 = (BaseClassTestClass4_Base2)MC; if ((Test1.RetInt() == 2) && (Test2.RetInt2() == 3)) { return true; } else { return false; } } } class BaseClassTestClass10_Base1 { public int intI = 2; } class BaseClassTestClass10_Base2 : BaseClassTestClass10_Base1 { public int intJ = 3; } class BaseClassTestClass10 : BaseClassTestClass10_Base2 { public static bool testMethod() { BaseClassTestClass10 MC = new BaseClassTestClass10(); if ((MC.intI == 2) && (MC.intJ == 3)) { return true; } else { return false; } } } class BaseClassTestClass13 { class BaseClassTestClass13_Sub : BaseClassTestClass13 { public int intI = 2; } public static bool testMethod() { BaseClassTestClass13_Sub test = new BaseClassTestClass13_Sub(); if (test.intI == 2) { return true; } else { return false; } } } class BaseClassTestClass25_Base1 { public class BaseClassTestClass25_Sub1 : BaseClassTestClass25_Base1 { } public interface BaseClassTestClass25_Interface1 { } public class BaseClassTestClass25_Sub2 : BaseClassTestClass25_Sub1, BaseClassTestClass25_Interface1 { } } class BaseClassTestClass25 : BaseClassTestClass25_Base1.BaseClassTestClass25_Sub2, BaseClassTestClass25_Base1.BaseClassTestClass25_Interface1 { public static bool testMethod() { BaseClassTestClass25 m = new BaseClassTestClass25(); if ((BaseClassTestClass25_Base1.BaseClassTestClass25_Sub2)m == null) return false; if ((BaseClassTestClass25_Base1.BaseClassTestClass25_Interface1)m == null) return false; return true; } } public class BaseClassTestClass29_SubC : BaseClassTestClass29_SubA.BaseClassTestClass29_SubB{} class BaseClassTestClass29_SubG : BaseClassTestClass29_SubC{} class BaseClassTestClass29_SubGG : BaseClassTestClass29_SubA.D{} class BaseClassTestClass29_SubGGG : BaseClassTestClass29_SubD, BaseClassTestClass29_SubA.BaseClassTestClass29_SubC.II, BaseClassTestClass29_SubA.BaseClassTestClass29_SubB.I { } public class BaseClassTestClass29_SubA { public class BaseClassTestClass29_SubB : BaseClassTestClass29_SubC.I { public interface I{} } public class BaseClassTestClass29_SubC { public interface I{} public interface II : I {} } public class D : BaseClassTestClass29_SubC.II { public class DD : D, BaseClassTestClass29_SubC.I, BaseClassTestClass29_SubC.II { public interface I : BaseClassTestClass29_SubC.II{} } } } class BaseClassTestClass29_SubD : BaseClassTestClass29_SubC{} class BaseClassTestClass29_SubDD : BaseClassTestClass29_SubA.D{} class BaseClassTestClass29_SubDDD : BaseClassTestClass29_SubD, BaseClassTestClass29_SubA.BaseClassTestClass29_SubC.II, BaseClassTestClass29_SubA.BaseClassTestClass29_SubB.I{} class BaseClassTestClass29 { public static bool testMethod() { return true; } } class ModifiersTestClass2_Base1 { public class Inner { public int IntI = 1; } } class ModifiersTestClass2 : ModifiersTestClass2_Base1 { // new new class Inner { public int IntI = 2; } public static bool testMethod() { Inner Test = new Inner(); if (Test.IntI == 2) { return true; } else { return false; } } } public class ModifiersTestClass3 { public int IntI = 2; public static bool testMethod() { ModifiersTestClass3 Test = new ModifiersTestClass3(); if (Test.IntI == 2) { return true; } else { return false; } } } class ModifiersTestClass4 { //public public class Inner { public int IntI = 2; } public static bool testMethod() { Inner Test = new Inner(); if (Test.IntI == 2) { return true; } else { return false; } } } class ModifiersTestClass6 { protected class Inner { public int IntI = 2; } public static bool testMethod() { Inner Test = new Inner(); if (Test.IntI == 2) { return true; } else { return false; } } } internal class ModifiersTestClass7 { public int IntI = 2; public static bool testMethod() { ModifiersTestClass7 Test = new ModifiersTestClass7(); if (Test.IntI == 2) { return true; } else { return false; } } } class ModifiersTestClass8 { // internal internal class Inner { public int IntI = 2; } public static bool testMethod() { Inner Test = new Inner(); if (Test.IntI == 2) { return true; } else { return false; } } } class ModifiersTestClass10 { // private private class Inner { public int IntI = 2; } public static bool testMethod() { Inner Test = new Inner(); if (Test.IntI == 2) { return true; } else { return false; } } } public abstract class ModifiersTestClass11_Base { public int IntI = 2; } public class ModifiersTestClass11 : ModifiersTestClass11_Base { public static bool testMethod() { ModifiersTestClass11 Test = new ModifiersTestClass11(); if (Test.IntI == 2) { return true; } else { return false; } } } public class ModifiersTestClass12 { // abstract abstract class BaseClass { public int IntI = 2; } class Inner : BaseClass { } public static bool testMethod() { Inner Test = new Inner(); if (Test.IntI == 2) { return true; } else { return false; } } } sealed class ModifiersTestClass13 { public int IntI = 2; public static bool testMethod() { ModifiersTestClass13 Test = new ModifiersTestClass13(); if (Test.IntI == 2) { return true; } else { return false; } } } class ModifiersTestClass14 { //sealed sealed class Inner { public int IntI = 2; } public static bool testMethod() { Inner Test = new Inner(); if (Test.IntI == 2) { return true; } else { return false; } } } abstract class ModifiersTestClass23_Sub1 { } class ModifiersTestClass23 { ModifiersTestClass23_Sub1 A; public static bool testMethod() { ModifiersTestClass23 test = new ModifiersTestClass23(); if (test.A == null) { return true; } else { return false; } } } abstract class ModifiersTestClass24_Abstract1 { public abstract int retInt(); } class ModifiersTestClass24_Derived1 : ModifiersTestClass24_Abstract1 { override public int retInt() { return 2; } } class ModifiersTestClass24 { ModifiersTestClass24_Abstract1 A = new ModifiersTestClass24_Derived1(); public static bool testMethod() { ModifiersTestClass24 test = new ModifiersTestClass24(); if (test.A.retInt() == 2) { return true; } else { return false; } } } abstract class ModifiersTestClass25_Abstract1 { } class ModifiersTestClass25 : ModifiersTestClass25_Abstract1 { public static bool testMethod() { return true; } } abstract class ModifiersTestClass26_Abstract1 { public abstract void foo(); public abstract int intI { get; set; } } class ModifiersTestClass26 { public static bool testMethod() { return true; } } abstract class ModifiersTestClass31_SubA { public abstract void F(); } abstract class ModifiersTestClass31_SubB : ModifiersTestClass31_SubA { public void G() { } } class ModifiersTestClass31 : ModifiersTestClass31_SubB { int MyInt = 0; public override void F() { MyInt = 1; } public static bool testMethod() { ModifiersTestClass31 test = new ModifiersTestClass31(); ModifiersTestClass31_SubA abstest = test; abstest.F(); if (test.MyInt == 1) { return true; } else { return false; } } } } } ================================================ FILE: Zelig/Zelig/Test/RunTime/NETMF/mscorlib/classes/classes1/DestructorsTests.cs ================================================ //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // Copyright (c) Microsoft Corporation. All rights reserved. //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// using System; using System.Reflection; using Microsoft.Zelig.Test; namespace Microsoft.Zelig.Test { public class DestructorsTests : TestBase, ITestInterface { [SetUp] public InitializeResult Initialize() { Log.Comment("Adding set up for the tests."); // Add your functionality here. return InitializeResult.ReadyToGo; } [TearDown] public void CleanUp() { Log.Comment("Cleaning up after the tests"); } public override TestResult Run( string[] args ) { TestResult result = TestResult.Pass; if(GC.GetTotalMemory(false) != 0) { string testName = "Destructors"; result |= Assert.CheckFailed(Destructors3_Test(), testName, 3); result |= Assert.CheckFailed(Destructors4_Test(), testName, 4); result |= Assert.CheckFailed(Destructors7_Test(), testName, 7); } else { result = TestResult.Skip; } return result; } //--// //--// //--// //Destructors Test methods //All test methods ported from folder current\test\cases\client\CLR\Conformance\10_classes\Destructors //The following tests were removed because they were build failure tests: //1,2,5,6,8-10 [TestMethod] public TestResult Destructors3_Test() { //Ported from Destructors3.cs Log.Comment(" Section 10.11"); Log.Comment(" Destructors implement the actions required to "); Log.Comment(" destruct the instances of a class."); Log.Comment(""); Log.Comment("Note: This test may fail due to lengthy garbage collection, look for Destructor messages in later logs"); if (DestructorsTestClass3.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Destructors4_Test() { //Ported from Destructors4.cs Log.Comment(" Section 10.11"); Log.Comment(" Destructors implement the actions required to "); Log.Comment(" destruct the instances of a class."); Log.Comment(""); Log.Comment("Note: This test may fail due to lengthy garbage collection, look for Destructor messages in later logs"); if (DestructorsTestClass4.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Destructors7_Test() { //Ported from Destructors7.cs Log.Comment(" Section 10.12"); Log.Comment(" Destructors are not inherited. Thus, a class"); Log.Comment(" has no other destructors than those that are "); Log.Comment(" actually declared in the class."); Log.Comment(""); Log.Comment("Note: This test may fail due to lengthy garbage collection, look for Destructor messages in later logs"); if (DestructorsTestClass7.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } class DestructorsTestClass3 { static int intI = 1; ~DestructorsTestClass3() { //Log.Comment("Calling Destructor for Test Class 3"); intI = 2; } public static bool testMethod() { DestructorsTestClass3 mc = new DestructorsTestClass3(); mc = null; System.GC.Collect( ); int sleepTime = 5000; int slept = 0; while (intI != 2 && slept < sleepTime) { System.Threading.Thread.Sleep(10); slept += 10; } Log.Comment("Thread has slept for"); Log.Comment(slept.ToString()); if (intI == 2) { return true; } else { return false; } } } class DestructorsTestClass4_Base { public static int intI = 2; ~DestructorsTestClass4_Base() { intI = intI * 2; //Log.Comment("Calling Destructor for Test Class 4 Base"); } } class DestructorsTestClass4 : DestructorsTestClass4_Base { ~DestructorsTestClass4() { intI = intI + 2; //Log.Comment("Calling Destructor for Test Class 4"); } public static bool testMethod() { DestructorsTestClass4 mc = new DestructorsTestClass4(); mc = null; System.GC.Collect( ); int sleepTime = 5000; int slept = 0; while (intI != 8 && slept < sleepTime) { System.Threading.Thread.Sleep(10); slept += 10; } Log.Comment("Thread has slept for"); Log.Comment(slept.ToString()); if (intI == 8) { return true; } else { return false; } } } class DestructorsTestClass7_Base { public static int intI = 2; } class DestructorsTestClass7 : DestructorsTestClass7_Base { ~DestructorsTestClass7() { intI = 3; //Log.Comment("Calling Destructor for Test Class 7"); } public static bool testMethod() { DestructorsTestClass7 mc = new DestructorsTestClass7(); mc = null; System.GC.Collect( ); int sleepTime = 5000; int slept = 0; while (intI != 3 && slept < sleepTime) { System.Threading.Thread.Sleep(10); slept += 10; } Log.Comment("Thread has slept for"); Log.Comment(slept.ToString()); if (intI == 3) { return true; } else { return false; } } } } } ================================================ FILE: Zelig/Zelig/Test/RunTime/NETMF/mscorlib/classes/classes1/EventsTests.cs ================================================ //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // Copyright (c) Microsoft Corporation. All rights reserved. //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// using System; using System.Reflection; using Microsoft.Zelig.Test; namespace Microsoft.Zelig.Test { public class EventsTests : TestBase, ITestInterface { [SetUp] public InitializeResult Initialize() { Log.Comment("Adding set up for the tests."); // Add your functionality here. return InitializeResult.ReadyToGo; } [TearDown] public void CleanUp() { Log.Comment("Cleaning up after the tests"); } public override TestResult Run(string[] args) { TestResult result = TestResult.Pass; result |= Assert.CheckFailed(Events1_Test(), "Events", 1); return result; } //--// //--// //--// //Events Test methods //All test methods ported from folder current\test\cases\client\CLR\Conformance\10_classes\Events //The following tests were removed because they were build failure tests: //2-9,12-41 [TestMethod] public TestResult Events1_Test() { Log.Comment("This is testing an obsolete event structure, but should pass."); if (EventsTestClass1.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } public delegate void EventsTestClass1_EventHandler1(); public class EventsTestClass1_Event1 { [Obsolete("This is Obsolete")] public event EventsTestClass1_EventHandler1 CMyEvent; public void Fire() { if (CMyEvent != null) CMyEvent(); } } public class EventsTestClass1_Sub1 { public static void MyMeth(){} public static void Main_old() { EventsTestClass1_Event1 mc = new EventsTestClass1_Event1(); mc.CMyEvent += new EventsTestClass1_EventHandler1(MyMeth); mc.Fire(); } } class EventsTestClass1 { public static bool testMethod() { try { EventsTestClass1_Sub1.Main_old(); } catch { return false; } return true; } } } } ================================================ FILE: Zelig/Zelig/Test/RunTime/NETMF/mscorlib/classes/classes1/FieldsTests.cs ================================================ //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // Copyright (c) Microsoft Corporation. All rights reserved. //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// #define TEST_EXCEPTIONS using System; using System.Reflection; using System.Runtime.CompilerServices; using Microsoft.Zelig.Test; namespace Microsoft.Zelig.Test { public class FieldsTests : TestBase, ITestInterface { [SetUp] public InitializeResult Initialize() { Log.Comment("Adding set up for the tests."); // Add your functionality here. return InitializeResult.ReadyToGo; } [TearDown] public void CleanUp() { Log.Comment("Cleaning up after the tests"); } public override TestResult Run(string[] args) { TestResult result = TestResult.Pass; string testName = "Fields"; result |= Assert.CheckFailed(Fields1_testMethod(), testName, 1); result |= Assert.CheckFailed(Fields2_testMethod(), testName, 2); result |= Assert.CheckFailed(Fields3_testMethod(), testName, 3); result |= Assert.CheckFailed(Fields4_testMethod(), testName, 4); result |= Assert.CheckFailed(Fields5_testMethod(), testName, 5); result |= Assert.CheckFailed(Fields6_testMethod(), testName, 6); result |= Assert.CheckFailed(Fields7_testMethod(), testName, 7); result |= Assert.CheckFailed(Fields8_testMethod(), testName, 8); result |= Assert.CheckFailed(Fields13_testMethod(), testName, 13); result |= Assert.CheckFailed(Fields14_testMethod(), testName, 14); result |= Assert.CheckFailed(Fields15_testMethod(), testName, 15); result |= Assert.CheckFailed(Fields16_testMethod(), testName, 16); result |= Assert.CheckFailed(Fields17_testMethod(), testName, 17); result |= Assert.CheckFailed(Fields18_testMethod(), testName, 18); result |= Assert.CheckFailed(Fields20_testMethod(), testName, 20); result |= Assert.CheckFailed(Fields22_testMethod(), testName, 22); result |= Assert.CheckFailed(Fields23_testMethod(), testName, 23); result |= Assert.CheckFailed(Fields24_testMethod(), testName, 24); result |= Assert.CheckFailed(Fields41_testMethod(), testName, 41); //result |= Assert.CheckFailed(Fields42_testMethod(), testName, 42); https://github.com/NETMF/llilum/issues/127 result |= Assert.CheckFailed(Fields43_testMethod(), testName, 43); result |= Assert.CheckFailed(Fields44_testMethod(), testName, 44); result |= Assert.CheckFailed(Fields45_testMethod(), testName, 45); result |= Assert.CheckFailed(Fields46_testMethod(), testName, 46); result |= Assert.CheckFailed(Fields49_testMethod(), testName, 49); result |= Assert.CheckFailed(Fields51_testMethod(), testName, 51); result |= Assert.CheckFailed(Fields52_testMethod(), testName, 52); result |= Assert.CheckFailed(Fields53_testMethod(), testName, 53); result |= Assert.CheckFailed(Fields54_testMethod(), testName, 54); result |= Assert.CheckFailed(Fields55_testMethod(), testName, 55); result |= Assert.CheckFailed(Fields56_testMethod(), testName, 56); result |= Assert.CheckFailed(Fields57_testMethod(), testName, 57); result |= Assert.CheckFailed(Fields58_testMethod(), testName, 58); return result; } //--// //--// //--// //Fields Test methods //The Fields*_testMethod() functions are ported from Fields\field*.cs files //The following Fields tests were removed because they were build failure tests: //9-12,,19,21,25-40,47,48,50,59-62,64 //Fields Test 42 was removed because Microsoft.SPOT.Math does not contain the abs() function which it uses //It fails in the Baseline document //Fields Test 63 was removed because the function isVolatile() is not defined //It was not included in the Baseline document //The FieldsVolatile*_testMethod() functions would be ported from Fields\Volatile\volatile*.cs files //but none of them would build because they require //System.Runtime.CompilerServices.isVolatile() which is not included in the Micro Framework //Also current Visual Studios docs indicate that all variables are considered volatile //They are not included in the Baseline document //22,23,24,42 [TestMethod] public TestResult Fields1_testMethod() { Log.Comment(" Section 10.4"); Log.Comment(" A field-declaration may include set of attributes,"); Log.Comment(" a new modifier, one of four access modifiers, a"); Log.Comment(" static modifier, and a readonly modifier. The "); Log.Comment(" attributes and modifiers apply to all of the "); Log.Comment(" members declared by the field-declaration."); if (FieldsTestClass1.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Fields2_testMethod() { Log.Comment(" Section 10.4"); Log.Comment(" A field-declaration may include set of attributes,"); Log.Comment(" a new modifier, one of four access modifiers, a"); Log.Comment(" static modifier, and a readonly modifier. The "); Log.Comment(" attributes and modifiers apply to all of the "); Log.Comment(" members declared by the field-declaration."); if (FieldsTestClass2.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Fields3_testMethod() { Log.Comment(" Section 10.4"); Log.Comment(" A field-declaration may include set of attributes,"); Log.Comment(" a new modifier, one of four access modifiers, a"); Log.Comment(" static modifier, and a readonly modifier. The "); Log.Comment(" attributes and modifiers apply to all of the "); Log.Comment(" members declared by the field-declaration."); if (FieldsTestClass3.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Fields4_testMethod() { Log.Comment(" Section 10.4"); Log.Comment(" A field-declaration may include set of attributes,"); Log.Comment(" a new modifier, one of four access modifiers, a"); Log.Comment(" static modifier, and a readonly modifier. The "); Log.Comment(" attributes and modifiers apply to all of the "); Log.Comment(" members declared by the field-declaration."); if (FieldsTestClass4.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Fields5_testMethod() { Log.Comment(" Section 10.4"); Log.Comment(" A field-declaration may include set of attributes,"); Log.Comment(" a new modifier, one of four access modifiers, a"); Log.Comment(" static modifier, and a readonly modifier. The "); Log.Comment(" attributes and modifiers apply to all of the "); Log.Comment(" members declared by the field-declaration."); if (FieldsTestClass5.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Fields6_testMethod() { Log.Comment(" Section 10.4"); Log.Comment(" A field-declaration may include set of attributes,"); Log.Comment(" a new modifier, one of four access modifiers, a"); Log.Comment(" static modifier, and a readonly modifier. The "); Log.Comment(" attributes and modifiers apply to all of the "); Log.Comment(" members declared by the field-declaration."); if (FieldsTestClass6.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Fields7_testMethod() { Log.Comment(" Section 10.4"); Log.Comment(" A field-declaration may include set of attributes,"); Log.Comment(" a new modifier, one of four access modifiers, a"); Log.Comment(" static modifier, and a readonly modifier. The "); Log.Comment(" attributes and modifiers apply to all of the "); Log.Comment(" members declared by the field-declaration."); if (FieldsTestClass7.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Fields8_testMethod() { Log.Comment(" Section 10.4"); Log.Comment(" A field-declaration may include set of attributes,"); Log.Comment(" a new modifier, one of four access modifiers, a"); Log.Comment(" static modifier, and a readonly modifier. The "); Log.Comment(" attributes and modifiers apply to all of the "); Log.Comment(" members declared by the field-declaration."); if (FieldsTestClass8.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Fields13_testMethod() { Log.Comment(" Section 10.4"); Log.Comment(" A field-declaration may include set of attributes,"); Log.Comment(" a new modifier, one of four access modifiers, a"); Log.Comment(" static modifier, and a readonly modifier. The "); Log.Comment(" attributes and modifiers apply to all of the "); Log.Comment(" members declared by the field-declaration."); Log.Comment(""); Log.Comment(" A field declaration that declares multiple fields"); Log.Comment(" is equivalent to multiple declarations of single "); Log.Comment(" fields with the same attributes, modifiers, and type."); if (FieldsTestClass13.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Fields14_testMethod() { Log.Comment(" Section 10.4"); Log.Comment(" A static field identifies exactly on storage location."); Log.Comment(" No matter how many instances of a class are created,"); Log.Comment(" there is only ever one copy of a static field."); if (FieldsTestClass14.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Fields15_testMethod() { Log.Comment(" Section 10.4"); Log.Comment(" A static field comes into existence when the "); Log.Comment(" type in which it is declared is loaded, and "); Log.Comment(" ceases to exist when the type in which it "); Log.Comment(" is declared in unloaded."); if (FieldsTestClass15.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Fields16_testMethod() { Log.Comment(" Section 10.4"); Log.Comment(" Every instance of a class contains a separate copy"); Log.Comment(" of all instance fields of the class. An instance "); Log.Comment(" field comes into existence when a new instance of "); Log.Comment(" its class is created, and ceases to exist when there "); Log.Comment(" are no references to that instance and the destructor"); Log.Comment(" of the instance has executed."); if (FieldsTestClass16.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Fields17_testMethod() { Log.Comment(" Section 10.4"); Log.Comment(" Every instance of a class contains a separate copy"); Log.Comment(" of all instance fields of the class. An instance "); Log.Comment(" field comes into existence when a new instance of "); Log.Comment(" its class is created, and ceases to exist when there "); Log.Comment(" are no references to that instance and the destructor"); Log.Comment(" of the instance has executed."); #if TEST_EXCEPTIONS if (FieldsTestClass17.testMethod()) { return TestResult.Pass; } return TestResult.Fail; #else return TestResult.Skip; #endif } [TestMethod] public TestResult Fields18_testMethod() { Log.Comment(" Section 10.4"); Log.Comment(" When a field is referenced in a member-access of"); Log.Comment(" the form E.M, if M is a static field, E must denote"); Log.Comment(" a type, and if M is an instance field, E must "); Log.Comment(" denote an instance."); if (FieldsTestClass18.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Fields20_testMethod() { Log.Comment(" Section 10.4"); Log.Comment(" When a field is referenced in a member-access of"); Log.Comment(" the form E.M, if M is a static field, E must denote"); Log.Comment(" a type, and if M is an instance field, E must "); Log.Comment(" denote an instance."); if (FieldsTestClass20.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Fields22_testMethod() { Log.Comment(" Section 10.4"); Log.Comment(" When a field-declaration includes a readonly"); Log.Comment(" modifier, assignments to the fields introduced"); Log.Comment(" by the declaration can only occur as part of"); Log.Comment(" the declaration or in a constructor in the"); Log.Comment(" same class."); if (FieldsTestClass22.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Fields23_testMethod() { Log.Comment(" Section 10.4"); Log.Comment(" When a field-declaration includes a readonly"); Log.Comment(" modifier, assignments to the fields introduced"); Log.Comment(" by the declaration can only occur as part of"); Log.Comment(" the declaration or in a constructor in the"); Log.Comment(" same class."); if (FieldsTestClass23.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Fields24_testMethod() { Log.Comment(" Section 10.4"); Log.Comment(" When a field-declaration includes a readonly"); Log.Comment(" modifier, assignments to the fields introduced"); Log.Comment(" by the declaration can only occur as part of"); Log.Comment(" the declaration or in a constructor in the"); Log.Comment(" same class."); if (FieldsTestClass24.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Fields41_testMethod() { Log.Comment(" Section 10.4"); Log.Comment(" A static readonly field is useful when a symbolic"); Log.Comment(" name for a constant value is desired, but when the "); Log.Comment(" type of the value is not permitted in a const declaration"); Log.Comment(" or when the value cannot be computed at compile-time"); Log.Comment(" by a constant expression."); if (FieldsTestClass41.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Fields42_testMethod() { Log.Comment(" Section 10.4"); Log.Comment(" Field declarations may include variable-initializers."); Log.Comment(" For static fields, varaible initializers correspond to"); Log.Comment(" assignment statements that are executed when the class"); Log.Comment(" is loaded. For instance fields, variable initializers"); Log.Comment(" correspond to assignment statements that are executed"); Log.Comment(" when an instance of the class is created."); Log.Comment("This test has been rewritten to avoid use of the Math.Abs function which the MF does not support"); if (FieldsTestClass42.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Fields43_testMethod() { Log.Comment(" Section 10.4"); Log.Comment(" The static field variable initializers of a class"); Log.Comment(" correspond to a sequence of assignments that are "); Log.Comment(" executed immediately upon entry to the static"); Log.Comment(" constructor of a class. The variable initializers"); Log.Comment(" are executed in the textual order they appear"); Log.Comment(" in the class declaration."); if (FieldsTestClass43.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Fields44_testMethod() { Log.Comment(" Section 10.4"); Log.Comment(" The static field variable initializers of a class"); Log.Comment(" correspond to a sequence of assignments that are "); Log.Comment(" executed immediately upon entry to the static"); Log.Comment(" constructor of a class. The variable initializers"); Log.Comment(" are executed in the textual order they appear"); Log.Comment(" in the class declaration."); if (FieldsTestClass44.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Fields45_testMethod() { Log.Comment(" Section 10.4"); Log.Comment(" The static field variable initializers of a class"); Log.Comment(" correspond to a sequence of assignments that are "); Log.Comment(" executed immediately upon entry to the static"); Log.Comment(" constructor of a class. The variable initializers"); Log.Comment(" are executed in the textual order they appear"); Log.Comment(" in the class declaration."); if (FieldsTestClass45.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Fields46_testMethod() { Log.Comment(" Section 10.4"); Log.Comment(" The instance field variable initializers of a class"); Log.Comment(" correspond to a sequence of assignments that are "); Log.Comment(" executed immediately upon entry to one of the instance"); Log.Comment(" constructors of the class."); if (FieldsTestClass46.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Fields49_testMethod() { Log.Comment(" A variable initializer for an instance field"); Log.Comment(" cannot reference the instance being created."); Log.Comment(" Thus, it is an error to reference this in a "); Log.Comment(" variable initializer, as it is an error for"); Log.Comment(" a variable initialzer to reference any instance"); Log.Comment(" member through a simple-name."); if (FieldsTestClass49.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Fields51_testMethod() { Log.Comment(" Section 10.4"); Log.Comment(" Specifically, assignments to a readonly field"); Log.Comment(" are permitted only in the following context."); Log.Comment(" ..."); Log.Comment(" For an instance field, in the instance constructors"); Log.Comment(" of the class that contains the field declaration, or"); Log.Comment(" for a static field, in the static constructor of the"); Log.Comment(" class the contains the field declaration. These are also"); Log.Comment(" contexts in which it is valid to pass a readonly field"); Log.Comment(" as an out or ref parameter."); if (FieldsTestClass51.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Fields52_testMethod() { Log.Comment(" Section 10.4"); Log.Comment(" Specifically, assignments to a readonly field"); Log.Comment(" are permitted only in the following context."); Log.Comment(" ..."); Log.Comment(" For an instance field, in the instance constructors"); Log.Comment(" of the class that contains the field declaration, or"); Log.Comment(" for a static field, in the static constructor of the"); Log.Comment(" class the contains the field declaration. These are also"); Log.Comment(" contexts in which it is valid to pass a readonly field"); Log.Comment(" as an out or ref parameter."); if (FieldsTestClass52.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Fields53_testMethod() { Log.Comment("Testing bools assigned with (x == y)"); if (FieldsTestClass53.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Fields54_testMethod() { Log.Comment("Testing bools assigned with function calls"); if (FieldsTestClass54.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Fields55_testMethod() { Log.Comment("Testing bools assigned with conditionals"); if (FieldsTestClass55.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Fields56_testMethod() { Log.Comment("Testing ints assigned with function calls"); if (FieldsTestClass56.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Fields57_testMethod() { Log.Comment("Testing strings assigned with \"x\" + \"y\""); if (FieldsTestClass57.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Fields58_testMethod() { Log.Comment("Testing strings assigned with function calls"); if (FieldsTestClass58.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } class FieldsTestClass1 { int intI = 2; public static bool testMethod() { FieldsTestClass1 test = new FieldsTestClass1(); if (test.intI == 2) { return true; } else { return false; } } } class FieldsTestClass2_Base { public int intI = 1; } class FieldsTestClass2 : FieldsTestClass2_Base { new int intI = 2; public static bool testMethod() { FieldsTestClass2 test = new FieldsTestClass2(); if (test.intI == 2) { return true; } else { return false; } } } class FieldsTestClass3 { public int intI = 2; public static bool testMethod() { FieldsTestClass3 test = new FieldsTestClass3(); if (test.intI == 2) { return true; } else { return false; } } } class FieldsTestClass4 { protected int intI = 2; public static bool testMethod() { FieldsTestClass4 test = new FieldsTestClass4(); if (test.intI == 2) { return true; } else { return false; } } } class FieldsTestClass5 { internal int intI = 2; public static bool testMethod() { FieldsTestClass5 test = new FieldsTestClass5(); if (test.intI == 2) { return true; } else { return false; } } } class FieldsTestClass6 { private int intI = 2; public static bool testMethod() { FieldsTestClass6 test = new FieldsTestClass6(); if (test.intI == 2) { return true; } else { return false; } } } class FieldsTestClass7 { static int intI = 2; public static bool testMethod() { if (intI == 2) { return true; } else { return false; } } } class FieldsTestClass8 { readonly int intI = 2; public static bool testMethod() { FieldsTestClass8 test = new FieldsTestClass8(); if (test.intI == 2) { return true; } else { return false; } } } class FieldsTestClass13_Base { public int intI = 2, intJ = 3; } class FieldsTestClass13 { public static bool testMethod() { FieldsTestClass13_Base test = new FieldsTestClass13_Base(); if ((test.intI == 2) && (test.intJ == 3)) { return true; } else { return false; } } } class FieldsTestClass14 { static int intI = 1; public void ChangeInt(int intJ) { intI = intJ; } public static bool testMethod() { FieldsTestClass14 c1 = new FieldsTestClass14(); c1.ChangeInt(2); FieldsTestClass14 c2 = new FieldsTestClass14(); c1.ChangeInt(3); FieldsTestClass14 c3 = new FieldsTestClass14(); c1.ChangeInt(4); if (intI == 4) { return true; } else { return false; } } } class FieldsTestClass15_Base { public static int intI = 1; } class FieldsTestClass15 { public static bool testMethod() { if (FieldsTestClass15_Base.intI == 1) { return true; } else { return false; } } } class FieldsTestClass16 { int intI = 1; public void ChangeInt(int intJ) { intI = intJ; } public static bool testMethod() { FieldsTestClass16 c1 = new FieldsTestClass16(); c1.ChangeInt(2); FieldsTestClass16 c2 = new FieldsTestClass16(); c2.ChangeInt(3); FieldsTestClass16 c3 = new FieldsTestClass16(); c3.ChangeInt(4); if ((c1.intI == 2) && (c2.intI == 3) && (c3.intI == 4)) { return true; } else { return false; } } } class FieldsTestClass17_Base { public int intI = 1; } class FieldsTestClass17 { FieldsTestClass17_Base tc; public static bool testMethod() { try { bool RetVal = false; FieldsTestClass17 test = new FieldsTestClass17(); try { int intJ = test.tc.intI; //MyTest hasn't been instantiated } catch (System.Exception) { RetVal = true; } return RetVal; } catch { return false; } } } class FieldsTestClass18 { static int intI = 2; public static bool testMethod() { if (FieldsTestClass18.intI == 2) { return true; } else { return false; } } } class FieldsTestClass20 { int intI = 2; public static bool testMethod() { FieldsTestClass20 test = new FieldsTestClass20(); if (test.intI == 2) { return true; } else { return false; } } } enum FieldsTestClass22_Enum { a = 1, b = 2 } struct FieldsTestClass22_Struct { public FieldsTestClass22_Struct(int intI) { Test = intI; } public int Test; } struct FieldsTestClass22_Sub { public FieldsTestClass22_Sub(int intI) { Test = intI; } public int Test; } class FieldsTestClass22 { readonly int intI = 2; readonly string strS = "MyString"; readonly FieldsTestClass22_Enum enuE = FieldsTestClass22_Enum.a; readonly FieldsTestClass22_Struct sctS = new FieldsTestClass22_Struct(3); readonly FieldsTestClass22_Sub clsC = new FieldsTestClass22_Sub(4); public static bool testMethod() { FieldsTestClass22 MC = new FieldsTestClass22(); if ((MC.intI == 2) && (MC.strS.Equals("MyString")) && (MC.enuE == FieldsTestClass22_Enum.a) && (MC.sctS.Test == 3) && (MC.clsC.Test == 4)) { return true; } else { return false; } } } enum FieldsTestClass23_Enum { a = 1, b = 2 } struct FieldsTestClass23_Struct { public FieldsTestClass23_Struct(int intI) { Test = intI; } public int Test; } struct FieldsTestClass23_Sub { public FieldsTestClass23_Sub(int intI) { Test = intI; } public int Test; } class FieldsTestClass23 { public FieldsTestClass23() { intI = 2; strS = "MyString"; enuE = FieldsTestClass23_Enum.a; sctS = new FieldsTestClass23_Struct(3); clsC = new FieldsTestClass23_Sub(4); } readonly int intI; readonly string strS; readonly FieldsTestClass23_Enum enuE; readonly FieldsTestClass23_Struct sctS; readonly FieldsTestClass23_Sub clsC; public static bool testMethod() { FieldsTestClass23 MC = new FieldsTestClass23(); if ((MC.intI == 2) && (MC.strS.Equals("MyString")) && (MC.enuE == FieldsTestClass23_Enum.a) && (MC.sctS.Test == 3) && (MC.clsC.Test == 4)) { return true; } else { return false; } } } enum FieldsTestClass24_Enum { a = 1, b = 2 } struct FieldsTestClass24_Struct { public FieldsTestClass24_Struct(int intI) { Test = intI; } public int Test; } struct FieldsTestClass24_Sub { public FieldsTestClass24_Sub(int intI) { Test = intI; } public int Test; } class FieldsTestClass24 { public FieldsTestClass24() { intI = 2; strS = "MyString"; enuE = FieldsTestClass24_Enum.a; sctS = new FieldsTestClass24_Struct(3); clsC = new FieldsTestClass24_Sub(4); } readonly int intI = 3; readonly string strS = "FooBar"; readonly FieldsTestClass24_Enum enuE = FieldsTestClass24_Enum.b; readonly FieldsTestClass24_Struct sctS = new FieldsTestClass24_Struct(2); readonly FieldsTestClass24_Sub clsC = new FieldsTestClass24_Sub(5); public static bool testMethod() { FieldsTestClass24 MC = new FieldsTestClass24(); if ((MC.intI == 2) && (MC.strS.Equals("MyString")) && (MC.enuE == FieldsTestClass24_Enum.a) && (MC.sctS.Test == 3) && (MC.clsC.Test == 4)) { return true; } else { return false; } } } public class FieldsTestClass41 { public static readonly FieldsTestClass41 Black = new FieldsTestClass41(0, 0, 0); public static readonly FieldsTestClass41 White = new FieldsTestClass41(255, 255, 255); public static readonly FieldsTestClass41 Red = new FieldsTestClass41(255, 0, 0); public static readonly FieldsTestClass41 Green = new FieldsTestClass41(0, 255, 0); public static readonly FieldsTestClass41 Blue = new FieldsTestClass41(0, 0, 255); private byte red, green, blue; public FieldsTestClass41(byte r, byte g, byte b) { red = r; green = g; blue = b; } public void getRGB(out byte r1, out byte g1, out byte b1) { r1 = red; g1 = green; b1 = blue; } public static bool testMethod() { FieldsTestClass41 wht = FieldsTestClass41.White; byte r2, g2, b2; wht.getRGB(out r2, out g2, out b2); if ((r2 == 255) && (g2 == 255) && (b2 == 255)) { return true; } else { return false; } } } public class FieldsTestClass42 { static int x = (int)Math.Cos(4 - 2) * 100; int i = 100; string s = "Hello"; public static bool testMethod() { try { FieldsTestClass42 t = new FieldsTestClass42(); if ((x == Math.Cos(2)) && (t.i == 100) && (t.s.Equals("Hello"))) { return true; } else { return false; } } catch { return false; } } } public class FieldsTestClass43 { static int intI; static int intJ = 2; //intJ should be initialized before we enter the static constructor static FieldsTestClass43() { intI = intJ; } public static bool testMethod() { if (intI == 2) { return true; } else { return false; } } } public class FieldsTestClass44 { static int intI = 2; //intI is initialized before intJ static int intJ = intI + 3; public static bool testMethod() { if (intJ == 5) { return true; } else { return false; } } } public class FieldsTestClass45 { //intI is initialized after intJ static int intJ = intI + 3; static int intI = 2; public static bool testMethod() { if (intJ == 3) { return true; } else { return false; } } } public class FieldsTestClass46 { int intI = 2; int intJ; int intK; public FieldsTestClass46() { //int I should already be initialized intJ = intI; } public FieldsTestClass46(int DummyInt) { //int I should already be initialized intK = intI; } public static bool testMethod() { FieldsTestClass46 test1 = new FieldsTestClass46(); FieldsTestClass46 test2 = new FieldsTestClass46(0); if ((test1.intJ == 2) && (test2.intK == 2)) { return true; } else { return false; } } } public class FieldsTestClass49 { public static int intI = 2; public int intK = intI; public static bool testMethod() { FieldsTestClass49 test = new FieldsTestClass49(); if (test.intK == 2) { return true; } else { return false; } } } class FieldsTestClass51 { FieldsTestClass51() { MyMeth1(ref intI); MyMeth2(out intJ); } public static void MyMeth1(ref int i) { i = 2; } public static void MyMeth2(out int j) { j = 3; } public readonly int intI; public readonly int intJ; public static bool testMethod() { FieldsTestClass51 mc = new FieldsTestClass51(); if ((mc.intI == 2) && (mc.intJ == 3)) { return true; } else { return false; } } } class FieldsTestClass52 { static FieldsTestClass52() { MyMeth1(ref intI); MyMeth2(out intJ); } public static void MyMeth1(ref int i) { i = 2; } public static void MyMeth2(out int j) { j = 3; } public static readonly int intI; public static readonly int intJ; public static bool testMethod() { if ((FieldsTestClass52.intI == 2) && (FieldsTestClass52.intJ == 3)) { return true; } else { return false; } } } class FieldsTestClass53 { public static bool b1 = (3 == 3); public static bool b2 = (3 == 4); public bool b3 = (3 == 3); public bool b4 = (3 == 4); public static bool testMethod() { FieldsTestClass53 mc = new FieldsTestClass53(); if ((b1 == true) && (b2 == false) && (mc.b3 == true) && (mc.b4 == false)) { return true; } else { return false; } } } class FieldsTestClass54 { public static bool b1 = RetTrue(); public static bool b2 = RetFalse(); public bool b3 = RetTrue(); public bool b4 = RetFalse(); public static bool RetTrue() { return true; } public static bool RetFalse() { return false; } public static bool testMethod() { FieldsTestClass54 mc = new FieldsTestClass54(); if ((b1 == true) && (b2 == false) && (mc.b3 == true) && (mc.b4 == false)) { return true; } else { return false; } } } class FieldsTestClass55 { public static int i1 = (3 & 6); public static int i2 = (3 | 6); public int i3 = (3 & 6); public int i4 = (3 | 6); public static bool testMethod() { FieldsTestClass55 mc = new FieldsTestClass55(); if ((i1 == 2) && (i2 == 7) && (mc.i3 == 2) && (mc.i4 == 7)) { return true; } else { return false; } } } class FieldsTestClass56 { public static int i1 = Ret2(); public static int i2 = Ret7(); public int i3 = Ret2(); public int i4 = Ret7(); public static int Ret2() { return 2; } public static int Ret7() { return 7; } public static bool testMethod() { FieldsTestClass56 mc = new FieldsTestClass56(); if ((i1 == 2) && (i2 == 7) && (mc.i3 == 2) && (mc.i4 == 7)) { return true; } else { return false; } } } class FieldsTestClass57 { public static string s1 = "foo" + "bar"; public static string s2 = "bar" + "foo"; public string s3 = "foo" + "bar"; public string s4 = "bar" + "foo"; public static bool testMethod() { FieldsTestClass57 mc = new FieldsTestClass57(); if ((s1 == "foobar") && (s2 == "barfoo") && (mc.s3 == "foobar") && (mc.s4 == "barfoo")) { return true; } else { return false; } } } class FieldsTestClass58 { public static string s1 = Ret1(); public static string s2 = Ret2(); public string s3 = Ret1(); public string s4 = Ret2(); public static string Ret1() { return "foobar"; } public static string Ret2() { return "barfoo"; } public static bool testMethod() { try { FieldsTestClass58 mc = new FieldsTestClass58(); if ((s1 == "foobar") && (s2 == "barfoo") && (mc.s3 == "foobar") && (mc.s4 == "barfoo")) { return true; } else { return false; } } catch { return false; } } } } } ================================================ FILE: Zelig/Zelig/Test/RunTime/NETMF/mscorlib/classes/classes2/IndexersTests.cs ================================================ //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // Copyright (c) Microsoft Corporation. All rights reserved. //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// using System; using System.Reflection; using Microsoft.Zelig.Test; namespace Microsoft.Zelig.Test { public class IndexersTests : TestBase, ITestInterface { [SetUp] public InitializeResult Initialize() { Log.Comment("Adding set up for the tests"); return InitializeResult.ReadyToGo; } [TearDown] public void CleanUp() { Log.Comment("Cleaning up after the tests"); } public override TestResult Run(string[] args) { TestResult result = TestResult.Pass; string testName = "Indexers"; result |= Assert.CheckFailed(Indexers1_Test(), testName, 1); result |= Assert.CheckFailed(Indexers2_Test(), testName, 2); result |= Assert.CheckFailed(Indexers3_Test(), testName, 3); result |= Assert.CheckFailed(Indexers4_Test(), testName, 4); result |= Assert.CheckFailed(Indexers5_Test(), testName, 5); result |= Assert.CheckFailed(Indexers6_Test(), testName, 6); result |= Assert.CheckFailed(Indexers10_Test(), testName, 10); result |= Assert.CheckFailed(Indexers11_Test(), testName, 11); result |= Assert.CheckFailed(Indexers12_Test(), testName, 12); result |= Assert.CheckFailed(Indexers14_Test(), testName, 14); result |= Assert.CheckFailed(Indexers18_Test(), testName, 18); result |= Assert.CheckFailed(Indexers23_Test(), testName, 23); result |= Assert.CheckFailed(Indexers29_Test(), testName, 29); result |= Assert.CheckFailed(Indexers32_Test(), testName, 32); result |= Assert.CheckFailed(Indexers33_Test(), testName, 33); result |= Assert.CheckFailed(Indexers37_Test(), testName, 37); result |= Assert.CheckFailed(Indexers38_Test(), testName, 38); result |= Assert.CheckFailed(Indexers39_Test(), testName, 39); result |= Assert.CheckFailed(Indexers42_Test(), testName, 42); result |= Assert.CheckFailed(Indexers43_Test(), testName, 43); result |= Assert.CheckFailed(Indexers46_Test(), testName, 46); result |= Assert.CheckFailed(Indexers47_Test(), testName, 47); result |= Assert.CheckFailed(Indexers48_Test(), testName, 48); result |= Assert.CheckFailed(Indexers49_Test(), testName, 49); result |= Assert.CheckFailed(Indexers50_Test(), testName, 50); result |= Assert.CheckFailed(Indexers51_Test(), testName, 51); result |= Assert.CheckFailed(Indexers52_Test(), testName, 52); result |= Assert.CheckFailed(Indexers53_Test(), testName, 53); result |= Assert.CheckFailed(Indexers55_Test(), testName, 55); result |= Assert.CheckFailed(Indexers56_Test(), testName, 56); return result; } //Indexers Test methods //All test methods ported from folder current\test\cases\client\CLR\Conformance\10_classes\Indexers //The following tests were included in the Baseline document: //01,02,03,04,05,06,10,11,12,14,18,23,29,32,33,37,38,39,42,43,46,47,48,49,50,51,52,53,54,55,56 //52,54 Failed in the Baseline Document, test 54 has been removed because it would not compile. [TestMethod] public TestResult Indexers1_Test() { Log.Comment(" Section 10.8"); Log.Comment(" An indexer-declaration may include set of"); Log.Comment(" attributes, a new modifier, and a valid combination"); Log.Comment(" of the four access modifiers."); if (IndexersTestClass1.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Indexers2_Test() { Log.Comment(" Section 10.8"); Log.Comment(" An indexer-declaration may include set of"); Log.Comment(" attributes, a new modifier, and a valid combination"); Log.Comment(" of the four access modifiers."); if (IndexersTestClass2.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Indexers3_Test() { Log.Comment(" Section 10.8"); Log.Comment(" An indexer-declaration may include set of"); Log.Comment(" attributes, a new modifier, and a valid combination"); Log.Comment(" of the four access modifiers."); if (IndexersTestClass3.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Indexers4_Test() { Log.Comment(" Section 10.8"); Log.Comment(" An indexer-declaration may include set of"); Log.Comment(" attributes, a new modifier, and a valid combination"); Log.Comment(" of the four access modifiers."); if (IndexersTestClass4.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Indexers5_Test() { Log.Comment(" Section 10.8"); Log.Comment(" An indexer-declaration may include set of"); Log.Comment(" attributes, a new modifier, and a valid combination"); Log.Comment(" of the four access modifiers."); if (IndexersTestClass5.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Indexers6_Test() { Log.Comment(" Section 10.8"); Log.Comment(" An indexer-declaration may include set of"); Log.Comment(" attributes, a new modifier, and a valid combination"); Log.Comment(" of the four access modifiers."); if (IndexersTestClass6.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Indexers10_Test() { Log.Comment(" Section 10.8"); Log.Comment(" An indexer-declaration may include set of"); Log.Comment(" attributes, a new modifier, and a valid combination"); Log.Comment(" of the four access modifiers."); if (IndexersTestClass10.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Indexers11_Test() { Log.Comment(" Section 10.8"); Log.Comment(" An indexer-declaration may include set of"); Log.Comment(" attributes, a new modifier, and a valid combination"); Log.Comment(" of the four access modifiers."); if (IndexersTestClass11.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Indexers12_Test() { Log.Comment(" Section 10.8"); Log.Comment(" The type on an indexer declaration specifies"); Log.Comment(" the element type of the indexer introduced"); Log.Comment(" by the declaration"); if (IndexersTestClass12.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Indexers14_Test() { Log.Comment(" Unless the indexer is an explicit interface"); Log.Comment(" member implementation, the type is followed"); Log.Comment(" by the keyword this. For an explicit "); Log.Comment(" interface member implementation, the type is "); Log.Comment(" followed by an interface-type, a . and the "); Log.Comment(" keyword this."); Log.Comment("This is currently an expected fail, but is resolved in 3.0 see Bug 16341 for details"); if (IndexersTestClass14.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Indexers18_Test() { Log.Comment(" Section 10.8"); Log.Comment(" The formal-index-parameter-list specifies"); Log.Comment(" the parameters of the indexer. The formal"); Log.Comment(" parameter list of an indexer corresponds"); Log.Comment(" to that of a method, except that at least"); Log.Comment(" one parameter must be specified, and that the"); Log.Comment(" ref and out parameter modifiers are not"); Log.Comment(" permitted."); if (IndexersTestClass18.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Indexers23_Test() { Log.Comment(" Section 10.8"); Log.Comment(" The type of an indexer declaration and each "); Log.Comment(" of the types referenced in the formal-index"); Log.Comment(" parameter list must be at least as accessible"); Log.Comment(" as the indexer itself."); if (IndexersTestClass23.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Indexers29_Test() { Log.Comment(" Section 10.8"); Log.Comment(" The formal parameter list of an indexer defines"); Log.Comment(" the signature of the indexer. Specifically, the"); Log.Comment(" signature of an indexer consists of the number and"); Log.Comment(" types of its formal parameters. The element type"); Log.Comment(" is not a part of an index signature, nor are the"); Log.Comment(" names of the formal parameters."); if (IndexersTestClass29.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Indexers32_Test() { Log.Comment(" Section 10.8"); Log.Comment(" The formal parameter list of an indexer defines"); Log.Comment(" the signature of the indexer. Specifically, the"); Log.Comment(" signature of an indexer consists of the number and"); Log.Comment(" types of its formal parameters. The element type"); Log.Comment(" is not a part of an index signature, nor are the"); Log.Comment(" names of the formal parameters."); if (IndexersTestClass32.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Indexers33_Test() { Log.Comment(" Section 10.8"); Log.Comment(" The formal parameter list of an indexer defines"); Log.Comment(" the signature of the indexer. Specifically, the"); Log.Comment(" signature of an indexer consists of the number and"); Log.Comment(" types of its formal parameters. The element type"); Log.Comment(" is not a part of an index signature, nor are the"); Log.Comment(" names of the formal parameters."); if (IndexersTestClass33.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Indexers37_Test() { Log.Comment(" Section 10.8"); Log.Comment(" With these differences in mind, all rules"); Log.Comment(" defined in 10.6.2 and 10.6.3 apply to indexer"); Log.Comment(" accessors as well as property accessors."); if (IndexersTestClass37.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Indexers38_Test() { Log.Comment(" Section 10.8"); Log.Comment(" With these differences in mind, all rules"); Log.Comment(" defined in 10.6.2 and 10.6.3 apply to indexer"); Log.Comment(" accessors as well as property accessors."); if (IndexersTestClass38.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Indexers39_Test() { Log.Comment(" Section 10.8"); Log.Comment(" With these differences in mind, all rules"); Log.Comment(" defined in 10.6.2 and 10.6.3 apply to indexer"); Log.Comment(" accessors as well as property accessors."); if (IndexersTestClass39.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Indexers42_Test() { Log.Comment(" Section 10.8"); Log.Comment(" With these differences in mind, all rules"); Log.Comment(" defined in 10.6.2 and 10.6.3 apply to indexer"); Log.Comment(" accessors as well as property accessors."); if (IndexersTestClass42.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Indexers43_Test() { Log.Comment(" Section 10.8"); Log.Comment(" With these differences in mind, all rules"); Log.Comment(" defined in 10.6.2 and 10.6.3 apply to indexer"); Log.Comment(" accessors as well as property accessors."); if (IndexersTestClass43.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Indexers46_Test() { Log.Comment("Testing multiple comma separated indexers"); if (IndexersTestClass46.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Indexers47_Test() { Log.Comment("Testing multiple comma separated indexers to a public variable"); if (IndexersTestClass47.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Indexers48_Test() { Log.Comment("Testing multiple comma separated indexers with a protected internal get and set"); if (IndexersTestClass48.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Indexers49_Test() { Log.Comment("Testing multiple comma separated indexers with an internal get and set"); if (IndexersTestClass49.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Indexers50_Test() { Log.Comment("Testing multiple comma separated indexers with a private get and set"); if (IndexersTestClass50.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Indexers51_Test() { Log.Comment("Testing multiple comma separated indexers with a public virtual get and set"); if (IndexersTestClass51.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Indexers52_Test() { Log.Comment("Testing multiple comma separated indexers with an overridden public virtual get and set"); if (IndexersTestClass52.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Indexers53_Test() { Log.Comment("Testing multiple comma separated indexers with an overridden public abstract get and set"); if (IndexersTestClass53.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Indexers55_Test() { Log.Comment("Testing 10 explicitly specified indexers"); if (IndexersTestClass55.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Indexers56_Test() { Log.Comment("Testing a single indexers with an overridden public abstract get"); if (IndexersTestClass56.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } public class IndexersTestClass1 { int intJ; int this[int intI] { get { return intI + intJ; } set { intJ = intI + 1; } } public static bool testMethod() { try { IndexersTestClass1 test = new IndexersTestClass1(); test[1] = 1; if (test[2] == 4) { return true; } else { return false; } } catch { return false; } } } public class IndexersTestClass2 { int intJ; public int this[int intI] { get { return intI + intJ; } set { intJ = intI + 1; } } public static bool testMethod() { IndexersTestClass2 test = new IndexersTestClass2(); test[1] = 1; if (test[2] == 4) { return true; } else { return false; } } } public class IndexersTestClass3 { int intJ; protected int this[int intI] { get { return intI + intJ; } set { intJ = intI + 1; } } public static bool testMethod() { try { IndexersTestClass3 test = new IndexersTestClass3(); test[1] = 1; if (test[2] == 4) { return true; } else { return false; } } catch { return false; } } } public class IndexersTestClass4 { int intJ; internal int this[int intI] { get { return intI + intJ; } set { intJ = intI + 1; } } public static bool testMethod() { IndexersTestClass4 test = new IndexersTestClass4(); test[1] = 1; if (test[2] == 4) { return true; } else { return false; } } } public class IndexersTestClass5 { int intJ; private int this[int intI] { get { return intI + intJ; } set { intJ = intI + 1; } } public static bool testMethod() { IndexersTestClass5 test = new IndexersTestClass5(); test[1] = 1; if (test[2] == 4) { return true; } else { return false; } } } public class IndexersTestClass6 { int intJ; protected internal int this[int intI] { get { return intI + intJ; } set { intJ = intI + 1; } } public static bool testMethod() { IndexersTestClass6 test = new IndexersTestClass6(); test[1] = 1; if (test[2] == 4) { return true; } else { return false; } } } public class IndexersTestClass7_Sub { int intJ; protected int this[int intI] { get { return intI + intJ; } set { intJ = intI + 1; } } } public class IndexersTestClass10_Base { int intJ; protected int this[int intI] { get { return intI + intJ; } set { intJ = intI + 1; } } } public class IndexersTestClass10 : IndexersTestClass10_Base { public static bool testMethod() { IndexersTestClass10 test = new IndexersTestClass10(); test[1] = 1; if (test[1] == 3) { return true; } else { return false; } } } public class IndexersTestClass11_Base { protected int intJ; protected int this[int intI] { get { return -1; } set { intJ = -1; } } } public class IndexersTestClass11 : IndexersTestClass11_Base { new protected int this[int intI] { get { return intI + intJ; } set { intJ = intI + 1; } } public static bool testMethod() { IndexersTestClass11 test = new IndexersTestClass11(); test[1] = 1; if (test[2] == 4) { return true; } else { return false; } } } public class IndexersTestClass12_Sub { public int intI = 2; } public class IndexersTestClass12 { IndexersTestClass12_Sub TC; IndexersTestClass12_Sub this[int i] { get { return TC; } set { TC = value; TC.intI = TC.intI + i; } } public static bool testMethod() { IndexersTestClass12 test = new IndexersTestClass12(); test[1] = new IndexersTestClass12_Sub(); if (test[2].intI == 3) { return true; } else { return false; } } } public interface IndexersTestClass14_Base { int this[int i] { get; set; } } public class IndexersTestClass14 : IndexersTestClass14_Base { int intI; int this[int i] { get { return intI; } set { intI = value; } } int IndexersTestClass14_Base.this[int i] { get { return intI + 1; } set { intI = value + 1; } } public static bool testMethod() { IndexersTestClass14 test1 = new IndexersTestClass14(); IndexersTestClass14_Base test2 = new IndexersTestClass14(); test1[1] = 2; test2[2] = 2; if ((test1[1] == 2) && (test2[2] == 4)) { return true; } else { return false; } } } public class IndexersTestClass18 { int this[int int1, int int2, int int3, int int4, int int5, int int6, int int7, int int8, int int9, int int10] { get { return int1 + int2 + int3 + int4 + int5 + int6 + int7 + int8 + int9 + int10; } } public static bool testMethod() { IndexersTestClass18 test = new IndexersTestClass18(); if (test[1, 2, 3, 4, 5, 6, 7, 8, 9, 10] == 55) { return true; } else { return false; } } } public class IndexersTestClass23 { private class TestClass { public int intI = 1; } private TestClass this[TestClass t] { get { return t; } } public static bool testMethod() { IndexersTestClass23 test = new IndexersTestClass23(); TestClass TC = new TestClass(); if (test[TC] == TC) { return true; } else { return false; } } } public class IndexersTestClass29 { public int this[int intI] { get { return intI; } } public int this[long lngL] { get { return (int)lngL + 1; } } public static bool testMethod() { IndexersTestClass29 test = new IndexersTestClass29(); int i = 1; long j = 2; if ((test[i] == 1) && (test[j] == 3)) { return true; } else { return false; } } } public class IndexersTestClass32 { public int this[int intI] { get { return intI; } } public int this[int intI, int intJ] { get { return intI + intJ; } } public static bool testMethod() { IndexersTestClass32 test = new IndexersTestClass32(); int i = 1; int j = 2; if ((test[i] == 1) && (test[i, j] == 3)) { return true; } else { return false; } } } public class IndexersTestClass33_Base { public int this[int intI] { get { return intI; } } } public class IndexersTestClass33 : IndexersTestClass33_Base { public int this[int intI, int intJ] { get { return intI + intJ; } } public static bool testMethod() { IndexersTestClass33 test = new IndexersTestClass33(); int i = 1; int j = 2; if ((test[i] == 1) && (test[i, j] == 3)) { return true; } else { return false; } } } public class IndexersTestClass37 { public int TestInt; public virtual int this[int intI] { set { TestInt = intI + value; } get { return TestInt + intI; } } public static bool testMethod() { IndexersTestClass37 test = new IndexersTestClass37(); test[2] = 2; if (test[2] == 6) { return true; } else { return false; } } } public class IndexersTestClass38_Base { public int TestInt; public virtual int this[int intI] { set { TestInt = -1; } get { return -1; } } } public class IndexersTestClass38 : IndexersTestClass38_Base { public override int this[int intI] { set { TestInt = intI + value; } get { return TestInt + intI; } } public static bool testMethod() { IndexersTestClass38_Base test = new IndexersTestClass38(); test[2] = 2; if (test[2] == 6) { return true; } else { return false; } } } public abstract class IndexersTestClass39_Base { public int TestInt; public abstract int this[int intI] { set; get; } } public class IndexersTestClass39 : IndexersTestClass39_Base { public override int this[int intI] { set { TestInt = intI + value; } get { return TestInt + intI; } } public static bool testMethod() { IndexersTestClass39_Base test = new IndexersTestClass39(); test[2] = 2; if (test[2] == 6) { return true; } else { return false; } } } public class IndexersTestClass42_Base { public int TestInt; public virtual int this[int intI] { set { TestInt = intI + value; } get { return -1; } } } public class IndexersTestClass42 : IndexersTestClass42_Base { public override int this[int intI] { get { return TestInt + intI; } } public static bool testMethod() { IndexersTestClass42_Base test = new IndexersTestClass42(); test[2] = 2; if (test[2] == 6) { return true; } else { return false; } } } public class IndexersTestClass43_Base { public int TestInt; public virtual int this[int intI] { set { TestInt = -1; } get { return TestInt + intI; } } } public class IndexersTestClass43 : IndexersTestClass43_Base { public override int this[int intI] { set { TestInt = intI + value; } } public static bool testMethod() { IndexersTestClass43_Base test = new IndexersTestClass43(); test[2] = 2; if (test[2] == 6) { return true; } else { return false; } } } public class IndexersTestClass46 { int intTest; public int this[params int[] values] { get { return intTest; } set { intTest = values[0] + values[1] + values[2]; } } public static bool testMethod() { IndexersTestClass46 mc = new IndexersTestClass46(); mc[1, 2, 3] = 0; if (mc[1, 2, 3] == 6) { return true; } else { return false; } } } public class IndexersTestClass47_Base { public int intTest; protected int this[params int[] values] { get { return intTest; } set { intTest = values[0] + values[1] + values[2]; } } } public class IndexersTestClass47 : IndexersTestClass47_Base { public static bool testMethod() { IndexersTestClass47 mc = new IndexersTestClass47(); mc[1, 2, 3] = 0; if (mc[1, 2, 3] == 6) { return true; } else { return false; } } } public class IndexersTestClass48_Base { public int intTest; protected internal int this[params int[] values] { get { return intTest; } set { intTest = values[0] + values[1] + values[2]; } } } public class IndexersTestClass48 : IndexersTestClass48_Base { public static bool testMethod() { IndexersTestClass48 mc = new IndexersTestClass48(); mc[1, 2, 3] = 0; if (mc[1, 2, 3] == 6) { return true; } else { return false; } } } public class IndexersTestClass49_Sub { public int intTest; internal int this[params int[] values] { get { return intTest; } set { intTest = values[0] + values[1] + values[2]; } } } public class IndexersTestClass49 { public static bool testMethod() { IndexersTestClass49_Sub mc = new IndexersTestClass49_Sub(); mc[1, 2, 3] = 0; if (mc[1, 2, 3] == 6) { return true; } else { return false; } } } public class IndexersTestClass50 { int intTest; private int this[params int[] values] { get { return intTest; } set { intTest = values[0] + values[1] + values[2]; } } public static bool testMethod() { IndexersTestClass50 mc = new IndexersTestClass50(); mc[1, 2, 3] = 0; if (mc[1, 2, 3] == 6) { return true; } else { return false; } } } public class IndexersTestClass51_Base { public int intTest; public virtual int this[params int[] values] { get { return intTest + 1; } set { intTest = 0; } } } public class IndexersTestClass51 : IndexersTestClass51_Base { public override int this[params int[] values] { get { return intTest; } set { intTest = values[0] + values[1] + values[2]; } } public static bool testMethod() { IndexersTestClass51_Base mc = new IndexersTestClass51(); mc[1, 2, 3] = 0; if (mc[1, 2, 3] == 6) { return true; } else { return false; } } } public class IndexersTestClass52_Base { public int intTest; public virtual int this[params int[] values] { get { return intTest; } set { intTest = values[0] + values[1] + values[2]; } } } public class IndexersTestClass52 : IndexersTestClass52_Base { public new int this[params int[] values] { get { return intTest + 1; } set { intTest = 0; } } public static bool testMethod() { IndexersTestClass52_Base mc = new IndexersTestClass52(); mc[1, 2, 3] = 0; if (mc[1, 2, 3] == 6) { return true; } else { return false; } } } public abstract class IndexersTestClass53_Base { public int intTest; public abstract int this[params int[] values] { get; set; } } public class IndexersTestClass53 : IndexersTestClass53_Base { public override int this[params int[] values] { get { return intTest; } set { intTest = values[0] + values[1] + values[2]; } } public static bool testMethod() { IndexersTestClass53_Base mc = new IndexersTestClass53(); mc[1, 2, 3] = 0; if (mc[1, 2, 3] == 6) { return true; } else { return false; } } } public class IndexersTestClass55 { public int this[int i1, int i2, int i3, int i4, int i5, int i6, int i7, int i8, int i9, int i10] { get { return (i1 + i2 + i3 + i4 + i5 + i6 + i7 + i8 + i9 + i10); } } public static bool testMethod() { IndexersTestClass55 MC = new IndexersTestClass55(); if (MC[1, 2, 3, 4, 5, 6, 7, 8, 9, 10] == 55) { return true; } else { return false; } } } public abstract class IndexersTestClass56_Base { protected int this[int intI] { get { return (intI + 1); } } } public class IndexersTestClass56 : IndexersTestClass56_Base { public int RetInt(int j) { return base[j]; } public static bool testMethod() { IndexersTestClass56 MC = new IndexersTestClass56(); if (MC.RetInt(2) == 3) { return true; } else { return false; } } } } } ================================================ FILE: Zelig/Zelig/Test/RunTime/NETMF/mscorlib/classes/classes2/OperatorsTests.cs ================================================ //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // Copyright (c) Microsoft Corporation. All rights reserved. //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// using System; using System.Reflection; using Microsoft.Zelig.Test; namespace Microsoft.Zelig.Test { public class OperatorsTests : TestBase, ITestInterface { [SetUp] public InitializeResult Initialize() { Log.Comment("Adding set up for the tests"); return InitializeResult.ReadyToGo; } [TearDown] public void CleanUp() { Log.Comment("Cleaning up after the tests"); } public override TestResult Run(string[] args) { TestResult result = TestResult.Pass; string testName = "Operators"; result |= Assert.CheckFailed(Operators1_Test(), testName, 1); result |= Assert.CheckFailed(Operators2_Test(), testName, 2); result |= Assert.CheckFailed(Operators3_Test(), testName, 3); result |= Assert.CheckFailed(Operators4_Test(), testName, 4); result |= Assert.CheckFailed(Operators5_Test(), testName, 5); result |= Assert.CheckFailed(Operators6_Test(), testName, 6); result |= Assert.CheckFailed(Operators7_Test(), testName, 7); result |= Assert.CheckFailed(Operators13_Test(), testName, 13); result |= Assert.CheckFailed(Operators14_Test(), testName, 14); result |= Assert.CheckFailed(Operators15_Test(), testName, 15); result |= Assert.CheckFailed(Operators16_Test(), testName, 16); result |= Assert.CheckFailed(Operators17_Test(), testName, 17); result |= Assert.CheckFailed(Operators18_Test(), testName, 18); result |= Assert.CheckFailed(Operators19_Test(), testName, 19); result |= Assert.CheckFailed(Operators20_Test(), testName, 20); result |= Assert.CheckFailed(Operators21_Test(), testName, 21); result |= Assert.CheckFailed(Operators22_Test(), testName, 22); result |= Assert.CheckFailed(Operators23_Test(), testName, 23); result |= Assert.CheckFailed(Operators24_Test(), testName, 24); result |= Assert.CheckFailed(Operators38_Test(), testName, 38); result |= Assert.CheckFailed(Operators39_Test(), testName, 39); result |= Assert.CheckFailed(Operators40_Test(), testName, 40); result |= Assert.CheckFailed(Operators41_Test(), testName, 41); result |= Assert.CheckFailed(Operators42_Test(), testName, 42); result |= Assert.CheckFailed(Operators43_Test(), testName, 43); result |= Assert.CheckFailed(Operators44_Test(), testName, 44); result |= Assert.CheckFailed(Operators45_Test(), testName, 45); result |= Assert.CheckFailed(Operators46_Test(), testName, 46); result |= Assert.CheckFailed(Operators67_Test(), testName, 67); result |= Assert.CheckFailed(Operators68_Test(), testName, 68); result |= Assert.CheckFailed(Operators69_Test(), testName, 69); result |= Assert.CheckFailed(Operators88_Test(), testName, 88); result |= Assert.CheckFailed(Operators89_Test(), testName, 89); result |= Assert.CheckFailed(Operators90_Test(), testName, 90); result |= Assert.CheckFailed(Operators91_Test(), testName, 91); result |= Assert.CheckFailed(Operators92_Test(), testName, 92); result |= Assert.CheckFailed(Operators93_Test(), testName, 93); result |= Assert.CheckFailed(Operators94_Test(), testName, 94); result |= Assert.CheckFailed(Operators95_Test(), testName, 95); result |= Assert.CheckFailed(Operators96_Test(), testName, 96); return result; } //Operators Test methods //All test methods ported from folder current\test\cases\client\CLR\Conformance\10_classes\Operators //The following tests were removed because they were build failure tests: //8-12,26-37,47-66,70-87 [TestMethod] public TestResult Operators1_Test() { Log.Comment("Tests overriding unary plus"); if (OperatorsTestClass1.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Operators2_Test() { Log.Comment("Tests overriding unary minus"); if (OperatorsTestClass2.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Operators3_Test() { Log.Comment("Tests overriding tilde"); if (OperatorsTestClass3.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Operators4_Test() { Log.Comment("Tests overriding increment prefix"); if (OperatorsTestClass4.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Operators5_Test() { Log.Comment("Tests overriding increment suffix"); if (OperatorsTestClass5.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Operators6_Test() { Log.Comment("Tests overriding decrement prefix"); if (OperatorsTestClass6.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Operators7_Test() { Log.Comment("Tests overriding decrement suffix"); if (OperatorsTestClass7.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Operators13_Test() { Log.Comment("Tests overriding binary plus"); if (OperatorsTestClass13.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Operators14_Test() { Log.Comment("Tests overriding binary minus"); if (OperatorsTestClass14.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Operators15_Test() { Log.Comment("Tests overriding asterisk (multiply)"); if (OperatorsTestClass15.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Operators16_Test() { Log.Comment("Tests overriding slash (division)"); if (OperatorsTestClass16.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Operators17_Test() { Log.Comment("Tests overriding percent (modulus)"); if (OperatorsTestClass17.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Operators18_Test() { Log.Comment("Tests overriding caret (xor)"); if (OperatorsTestClass18.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Operators19_Test() { Log.Comment("Tests overriding ampersand"); if (OperatorsTestClass19.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Operators20_Test() { Log.Comment("Tests overriding pipe (or)"); if (OperatorsTestClass20.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Operators21_Test() { Log.Comment("Tests overriding double less-than (left shift)"); if (OperatorsTestClass21.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Operators22_Test() { Log.Comment("Tests overriding double greater-than (right shift)"); if (OperatorsTestClass22.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Operators23_Test() { Log.Comment("Tests overriding binary plus with 1 int parameter"); if (OperatorsTestClass23.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Operators24_Test() { Log.Comment("Tests overriding double equals (equality comparison) and exclamation-equals (non-equality comparison)"); if (OperatorsTestClass24.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Operators38_Test() { Log.Comment("Tests overriding binary plus with 1 int parameter"); if (OperatorsTestClass38.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Operators39_Test() { Log.Comment("Tests overriding binary minus with 1 int parameter"); if (OperatorsTestClass39.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Operators40_Test() { Log.Comment("Tests overriding asterisk (multiply) with 1 int parameter"); if (OperatorsTestClass40.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Operators41_Test() { Log.Comment("Tests overriding slash (divide) with 1 int parameter"); if (OperatorsTestClass41.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Operators42_Test() { Log.Comment("Tests overriding percent (modulus) with 1 int parameter"); if (OperatorsTestClass42.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Operators43_Test() { Log.Comment("Tests overriding caret (xor) with 1 int parameter"); if (OperatorsTestClass43.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Operators44_Test() { Log.Comment("Tests overriding ampersand with 1 int parameter"); if (OperatorsTestClass44.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Operators45_Test() { Log.Comment("Tests overriding pipe (or) with 1 int parameter"); if (OperatorsTestClass45.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Operators46_Test() { Log.Comment("Tests overriding double equals (equality comparison) and exclamation-equals "); Log.Comment("(non-equality comparison) with 1 int"); if (OperatorsTestClass46.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Operators67_Test() { Log.Comment("Tests overriding unary exclamation (not)"); if (OperatorsTestClass67.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Operators68_Test() { Log.Comment("Tests overriding true and false"); if (OperatorsTestClass68.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Operators69_Test() { Log.Comment("Tests overriding true and false and ampersand"); if (OperatorsTestClass69.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Operators88_Test() { Log.Comment("Tests true and false with ampersand"); if (OperatorsTestClass88.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Operators89_Test() { Log.Comment("Tests true and false with double ampersand"); if (OperatorsTestClass89.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Operators90_Test() { Log.Comment("Tests true and false with pipe (or)"); if (OperatorsTestClass90.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Operators91_Test() { Log.Comment("Tests true and false with double pipe (or)"); if (OperatorsTestClass91.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Operators92_Test() { Log.Comment("Tests true and false with caret (xor)"); if (OperatorsTestClass92.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Operators93_Test() { Log.Comment("Tests numerical types with plus"); if (OperatorsTestClass93.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Operators94_Test() { Log.Comment("Tests numerical types with minus"); if (OperatorsTestClass94.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Operators95_Test() { Log.Comment("Tests numerical types with asterisk (multiply)"); if (OperatorsTestClass95.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Operators96_Test() { Log.Comment("Tests numerical types with slash (divide)"); if (OperatorsTestClass96.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } class OperatorsTestClass1 { public int intI = 2; public static OperatorsTestClass1 operator +(OperatorsTestClass1 MyInt) { MyInt.intI = 3; return MyInt; } public static bool testMethod() { OperatorsTestClass1 Test = new OperatorsTestClass1(); OperatorsTestClass1 temp = +Test; if (Test.intI == 3) { return true; } else { return false; } } } class OperatorsTestClass2 { public int intI = 2; public static OperatorsTestClass2 operator -(OperatorsTestClass2 MyInt) { MyInt.intI = 3; return MyInt; } public static bool testMethod() { OperatorsTestClass2 Test = new OperatorsTestClass2(); OperatorsTestClass2 temp = -Test; if (Test.intI == 3) { return true; } else { return false; } } } class OperatorsTestClass3 { public int intI = 2; public static OperatorsTestClass3 operator ~(OperatorsTestClass3 MyInt) { MyInt.intI = 3; return MyInt; } public static bool testMethod() { OperatorsTestClass3 Test = new OperatorsTestClass3(); OperatorsTestClass3 temp = ~Test; if (Test.intI == 3) { return true; } else { return false; } } } class OperatorsTestClass4 { public int intI = 2; public static OperatorsTestClass4 operator ++(OperatorsTestClass4 MyInt) { OperatorsTestClass4 MC = new OperatorsTestClass4(); MC.intI = 3; return MC; } public static bool testMethod() { OperatorsTestClass4 Test = new OperatorsTestClass4(); OperatorsTestClass4 Test2 = ++Test; if ((Test.intI == 3) && (Test2.intI == 3)) { return true; } else { return false; } } } class OperatorsTestClass5 { public int intI = 2; public static OperatorsTestClass5 operator ++(OperatorsTestClass5 MyInt) { OperatorsTestClass5 MC = new OperatorsTestClass5(); MC.intI = 3; return MC; } public static bool testMethod() { OperatorsTestClass5 Test = new OperatorsTestClass5(); OperatorsTestClass5 Test2 = Test++; if ((Test.intI == 3) && (Test2.intI == 2)) { return true; } else { return false; } } } class OperatorsTestClass6 { public int intI = 2; public static OperatorsTestClass6 operator --(OperatorsTestClass6 MyInt) { OperatorsTestClass6 MC = new OperatorsTestClass6(); MC.intI = 3; return MC; } public static bool testMethod() { OperatorsTestClass6 Test = new OperatorsTestClass6(); OperatorsTestClass6 Test2 = --Test; if ((Test.intI == 3) && (Test2.intI == 3)) { return true; } else { return false; } } } class OperatorsTestClass7 { public int intI = 2; public static OperatorsTestClass7 operator --(OperatorsTestClass7 MyInt) { OperatorsTestClass7 MC = new OperatorsTestClass7(); MC.intI = 3; return MC; } public static bool testMethod() { OperatorsTestClass7 Test = new OperatorsTestClass7(); OperatorsTestClass7 Test2 = Test--; if ((Test.intI == 3) && (Test2.intI == 2)) { return true; } else { return false; } } } class OperatorsTestClass13 { public int intI = 2; public static OperatorsTestClass13 operator +(OperatorsTestClass13 MyInt, OperatorsTestClass13 MyInt2) { OperatorsTestClass13 MC = new OperatorsTestClass13(); MC.intI = MyInt.intI + MyInt2.intI; return MC; } public static bool testMethod() { OperatorsTestClass13 Test1 = new OperatorsTestClass13(); OperatorsTestClass13 Test2 = new OperatorsTestClass13(); Test2.intI = 3; OperatorsTestClass13 Test = Test1 + Test2; if (Test.intI == 5) { return true; } else { return false; } } } class OperatorsTestClass14 { public int intI = 2; public static OperatorsTestClass14 operator -(OperatorsTestClass14 MyInt, OperatorsTestClass14 MyInt2) { OperatorsTestClass14 MC = new OperatorsTestClass14(); MC.intI = MyInt.intI + MyInt2.intI; return MC; } public static bool testMethod() { OperatorsTestClass14 Test1 = new OperatorsTestClass14(); OperatorsTestClass14 Test2 = new OperatorsTestClass14(); Test2.intI = 3; OperatorsTestClass14 Test = Test1 - Test2; if (Test.intI == 5) { return true; } else { return false; } } } class OperatorsTestClass15 { public int intI = 2; public static OperatorsTestClass15 operator *(OperatorsTestClass15 MyInt, OperatorsTestClass15 MyInt2) { OperatorsTestClass15 MC = new OperatorsTestClass15(); MC.intI = MyInt.intI + MyInt2.intI; return MC; } public static bool testMethod() { OperatorsTestClass15 Test1 = new OperatorsTestClass15(); OperatorsTestClass15 Test2 = new OperatorsTestClass15(); Test2.intI = 3; OperatorsTestClass15 Test = Test1 * Test2; if (Test.intI == 5) { return true; } else { return false; } } } class OperatorsTestClass16 { public int intI = 2; public static OperatorsTestClass16 operator /(OperatorsTestClass16 MyInt, OperatorsTestClass16 MyInt2) { OperatorsTestClass16 MC = new OperatorsTestClass16(); MC.intI = MyInt.intI + MyInt2.intI; return MC; } public static bool testMethod() { OperatorsTestClass16 Test1 = new OperatorsTestClass16(); OperatorsTestClass16 Test2 = new OperatorsTestClass16(); Test2.intI = 3; OperatorsTestClass16 Test = Test1 / Test2; if (Test.intI == 5) { return true; } else { return false; } } } class OperatorsTestClass17 { public int intI = 2; public static OperatorsTestClass17 operator %(OperatorsTestClass17 MyInt, OperatorsTestClass17 MyInt2) { OperatorsTestClass17 MC = new OperatorsTestClass17(); MC.intI = MyInt.intI + MyInt2.intI; return MC; } public static bool testMethod() { OperatorsTestClass17 Test1 = new OperatorsTestClass17(); OperatorsTestClass17 Test2 = new OperatorsTestClass17(); Test2.intI = 3; OperatorsTestClass17 Test = Test1 % Test2; if (Test.intI == 5) { return true; } else { return false; } } } class OperatorsTestClass18 { public int intI = 2; public static OperatorsTestClass18 operator ^(OperatorsTestClass18 MyInt, OperatorsTestClass18 MyInt2) { OperatorsTestClass18 MC = new OperatorsTestClass18(); MC.intI = MyInt.intI + MyInt2.intI; return MC; } public static bool testMethod() { OperatorsTestClass18 Test1 = new OperatorsTestClass18(); OperatorsTestClass18 Test2 = new OperatorsTestClass18(); Test2.intI = 3; OperatorsTestClass18 Test = Test1 ^ Test2; if (Test.intI == 5) { return true; } else { return false; } } } class OperatorsTestClass19 { public int intI = 2; public static OperatorsTestClass19 operator &(OperatorsTestClass19 MyInt, OperatorsTestClass19 MyInt2) { OperatorsTestClass19 MC = new OperatorsTestClass19(); MC.intI = MyInt.intI + MyInt2.intI; return MC; } public static bool testMethod() { OperatorsTestClass19 Test1 = new OperatorsTestClass19(); OperatorsTestClass19 Test2 = new OperatorsTestClass19(); Test2.intI = 3; OperatorsTestClass19 Test = Test1 & Test2; if (Test.intI == 5) { return true; } else { return false; } } } class OperatorsTestClass20 { public int intI = 2; public static OperatorsTestClass20 operator |(OperatorsTestClass20 MyInt, OperatorsTestClass20 MyInt2) { OperatorsTestClass20 MC = new OperatorsTestClass20(); MC.intI = MyInt.intI + MyInt2.intI; return MC; } public static bool testMethod() { OperatorsTestClass20 Test1 = new OperatorsTestClass20(); OperatorsTestClass20 Test2 = new OperatorsTestClass20(); Test2.intI = 3; OperatorsTestClass20 Test = Test1 | Test2; if (Test.intI == 5) { return true; } else { return false; } } } class OperatorsTestClass21 { public int intI = 2; public static OperatorsTestClass21 operator <<(OperatorsTestClass21 MyInt, int MyInt2) { OperatorsTestClass21 MC = new OperatorsTestClass21(); MC.intI = MyInt.intI + MyInt2; return MC; } public static bool testMethod() { OperatorsTestClass21 Test1 = new OperatorsTestClass21(); OperatorsTestClass21 Test = Test1 << 3; if (Test.intI == 5) { return true; } else { return false; } } } class OperatorsTestClass22 { public int intI = 2; public static OperatorsTestClass22 operator >>(OperatorsTestClass22 MyInt, int MyInt2) { OperatorsTestClass22 MC = new OperatorsTestClass22(); MC.intI = MyInt.intI + MyInt2; return MC; } public static bool testMethod() { OperatorsTestClass22 Test1 = new OperatorsTestClass22(); OperatorsTestClass22 Test = Test1 >> 3; if (Test.intI == 5) { return true; } else { return false; } } } class OperatorsTestClass23 { public int intI = 2; public static OperatorsTestClass23 operator +(OperatorsTestClass23 MyInt, int MyInt2) { OperatorsTestClass23 MC = new OperatorsTestClass23(); MC.intI = MyInt.intI + MyInt2; return MC; } public static bool testMethod() { OperatorsTestClass23 Test1 = new OperatorsTestClass23(); OperatorsTestClass23 Test = Test1 + 3; if (Test.intI == 5) { return true; } else { return false; } } } class OperatorsTestClass24 { public int intI = 2; public static bool operator ==(OperatorsTestClass24 MyInt, OperatorsTestClass24 MyInt2) { if (MyInt.intI == MyInt2.intI) { return true; } else { return false; } } public static bool operator !=(OperatorsTestClass24 MyInt, OperatorsTestClass24 MyInt2) { return false; } public static bool testMethod() { OperatorsTestClass24 Test1 = new OperatorsTestClass24(); OperatorsTestClass24 Test2 = new OperatorsTestClass24(); OperatorsTestClass24 Test3 = new OperatorsTestClass24(); Test2.intI = 3; if ((Test1 == Test3) && (!(Test1 == Test2))) { return true; } else { return false; } } } class OperatorsTestClass38 { public int intI = 2; public static OperatorsTestClass38 operator +(OperatorsTestClass38 MyInt, int MyInt2) { OperatorsTestClass38 MC = new OperatorsTestClass38(); MC.intI = MyInt.intI + MyInt2; return MC; } public static OperatorsTestClass38 operator +(int MyInt, OperatorsTestClass38 MyInt2) { OperatorsTestClass38 MC = new OperatorsTestClass38(); MC.intI = MyInt + MyInt2.intI + 1; return MC; } public static bool testMethod() { OperatorsTestClass38 Test1 = new OperatorsTestClass38(); OperatorsTestClass38 TestClass1 = Test1 + 1; OperatorsTestClass38 TestClass2 = 1 + Test1; if ((TestClass1.intI == 3) && (TestClass2.intI == 4)) { return true; } else { return false; } } } class OperatorsTestClass39 { public int intI = 2; public static OperatorsTestClass39 operator -(OperatorsTestClass39 MyInt, int MyInt2) { OperatorsTestClass39 MC = new OperatorsTestClass39(); MC.intI = MyInt.intI + MyInt2; return MC; } public static OperatorsTestClass39 operator -(int MyInt, OperatorsTestClass39 MyInt2) { OperatorsTestClass39 MC = new OperatorsTestClass39(); MC.intI = MyInt + MyInt2.intI + 1; return MC; } public static bool testMethod() { OperatorsTestClass39 Test1 = new OperatorsTestClass39(); OperatorsTestClass39 TestClass1 = Test1 - 1; OperatorsTestClass39 TestClass2 = 1 - Test1; if ((TestClass1.intI == 3) && (TestClass2.intI == 4)) { return true; } else { return false; } } } class OperatorsTestClass40 { public int intI = 2; public static OperatorsTestClass40 operator *(OperatorsTestClass40 MyInt, int MyInt2) { OperatorsTestClass40 MC = new OperatorsTestClass40(); MC.intI = MyInt.intI + MyInt2; return MC; } public static OperatorsTestClass40 operator *(int MyInt, OperatorsTestClass40 MyInt2) { OperatorsTestClass40 MC = new OperatorsTestClass40(); MC.intI = MyInt + MyInt2.intI + 1; return MC; } public static bool testMethod() { OperatorsTestClass40 Test1 = new OperatorsTestClass40(); OperatorsTestClass40 TestClass1 = Test1 * 1; OperatorsTestClass40 TestClass2 = 1 * Test1; if ((TestClass1.intI == 3) && (TestClass2.intI == 4)) { return true; } else { return false; } } } class OperatorsTestClass41 { public int intI = 2; public static OperatorsTestClass41 operator /(OperatorsTestClass41 MyInt, int MyInt2) { OperatorsTestClass41 MC = new OperatorsTestClass41(); MC.intI = MyInt.intI + MyInt2; return MC; } public static OperatorsTestClass41 operator /(int MyInt, OperatorsTestClass41 MyInt2) { OperatorsTestClass41 MC = new OperatorsTestClass41(); MC.intI = MyInt + MyInt2.intI + 1; return MC; } public static bool testMethod() { OperatorsTestClass41 Test1 = new OperatorsTestClass41(); OperatorsTestClass41 TestClass1 = Test1 / 1; OperatorsTestClass41 TestClass2 = 1 / Test1; if ((TestClass1.intI == 3) && (TestClass2.intI == 4)) { return true; } else { return false; } } } class OperatorsTestClass42 { public int intI = 2; public static OperatorsTestClass42 operator %(OperatorsTestClass42 MyInt, int MyInt2) { OperatorsTestClass42 MC = new OperatorsTestClass42(); MC.intI = MyInt.intI + MyInt2; return MC; } public static OperatorsTestClass42 operator %(int MyInt, OperatorsTestClass42 MyInt2) { OperatorsTestClass42 MC = new OperatorsTestClass42(); MC.intI = MyInt + MyInt2.intI + 1; return MC; } public static bool testMethod() { OperatorsTestClass42 Test1 = new OperatorsTestClass42(); OperatorsTestClass42 TestClass1 = Test1 % 1; OperatorsTestClass42 TestClass2 = 1 % Test1; if ((TestClass1.intI == 3) && (TestClass2.intI == 4)) { return true; } else { return false; } } } class OperatorsTestClass43 { public int intI = 2; public static OperatorsTestClass43 operator ^(OperatorsTestClass43 MyInt, int MyInt2) { OperatorsTestClass43 MC = new OperatorsTestClass43(); MC.intI = MyInt.intI + MyInt2; return MC; } public static OperatorsTestClass43 operator ^(int MyInt, OperatorsTestClass43 MyInt2) { OperatorsTestClass43 MC = new OperatorsTestClass43(); MC.intI = MyInt + MyInt2.intI + 1; return MC; } public static bool testMethod() { OperatorsTestClass43 Test1 = new OperatorsTestClass43(); OperatorsTestClass43 TestClass1 = Test1 ^ 1; OperatorsTestClass43 TestClass2 = 1 ^ Test1; if ((TestClass1.intI == 3) && (TestClass2.intI == 4)) { return true; } else { return false; } } } class OperatorsTestClass44 { public int intI = 2; public static OperatorsTestClass44 operator &(OperatorsTestClass44 MyInt, int MyInt2) { OperatorsTestClass44 MC = new OperatorsTestClass44(); MC.intI = MyInt.intI + MyInt2; return MC; } public static OperatorsTestClass44 operator &(int MyInt, OperatorsTestClass44 MyInt2) { OperatorsTestClass44 MC = new OperatorsTestClass44(); MC.intI = MyInt + MyInt2.intI + 1; return MC; } public static bool testMethod() { OperatorsTestClass44 Test1 = new OperatorsTestClass44(); OperatorsTestClass44 TestClass1 = Test1 & 1; OperatorsTestClass44 TestClass2 = 1 & Test1; if ((TestClass1.intI == 3) && (TestClass2.intI == 4)) { return true; } else { return false; } } } class OperatorsTestClass45 { public int intI = 2; public static OperatorsTestClass45 operator |(OperatorsTestClass45 MyInt, int MyInt2) { OperatorsTestClass45 MC = new OperatorsTestClass45(); MC.intI = MyInt.intI + MyInt2; return MC; } public static OperatorsTestClass45 operator |(int MyInt, OperatorsTestClass45 MyInt2) { OperatorsTestClass45 MC = new OperatorsTestClass45(); MC.intI = MyInt + MyInt2.intI + 1; return MC; } public static bool testMethod() { OperatorsTestClass45 Test1 = new OperatorsTestClass45(); OperatorsTestClass45 TestClass1 = Test1 | 1; OperatorsTestClass45 TestClass2 = 1 | Test1; if ((TestClass1.intI == 3) || (TestClass2.intI == 4)) { return true; } else { return false; } } } class OperatorsTestClass46 { public int intI = 2; public static bool operator ==(OperatorsTestClass46 MyInt, int MyInt2) { return (MyInt.intI != MyInt2); } public static bool operator !=(OperatorsTestClass46 MyInt, int MyInt2) { return false; } public static bool testMethod() { OperatorsTestClass46 Test1 = new OperatorsTestClass46(); if (((Test1 == 2) == false) && ((Test1 == 4) == true)) { return true; } else { return false; } } } class OperatorsTestClass67 { public int intI = 2; public static bool operator !(OperatorsTestClass67 MyInt) { MyInt.intI = 3; return true; } public static bool testMethod() { OperatorsTestClass67 Test = new OperatorsTestClass67(); if ((!Test) && (Test.intI == 3)) { return true; } else { return false; } } } class OperatorsTestClass68 { public int intI = 2; public static bool operator true(OperatorsTestClass68 MyInt) { MyInt.intI = 3; return true; } public static bool operator false(OperatorsTestClass68 MyInt) { MyInt.intI = 4; return false; } public static bool testMethod() { OperatorsTestClass68 Test = new OperatorsTestClass68(); if (Test) { if (Test.intI == 3) { return true; } return false; } else { return false; } } } class OperatorsTestClass69 { public int intI = 2; public static bool operator true(OperatorsTestClass69 MyInt) { MyInt.intI = 3; return true; } public static bool operator false(OperatorsTestClass69 MyInt) { MyInt.intI = 4; return false; } public static OperatorsTestClass69 operator &(OperatorsTestClass69 mc1, OperatorsTestClass69 mc2) { return new OperatorsTestClass69(); } public static bool testMethod() { OperatorsTestClass69 Test1 = new OperatorsTestClass69(); OperatorsTestClass69 Test2 = new OperatorsTestClass69(); if (Test1 && Test2) { if ((Test1.intI == 4) && (Test2.intI == 2)) { return true; } else { return false; } } return false; } } class OperatorsTestClass88 { public static bool retTrue() { return true; } public static bool retFalse() { return false; } public static bool testMethod() { bool retVal = true; if ((true & true) != true) retVal = false; if ((true & retTrue()) != true) retVal = false; if ((retTrue() & true) != true) retVal = false; if ((true & false) != false) retVal = false; if ((retTrue() & false) != false) retVal = false; if ((true & retFalse()) != false) retVal = false; if ((false & true) != false) retVal = false; if ((retFalse() & true) != false) retVal = false; if ((false & retTrue()) != false) retVal = false; if ((false & false) != false) retVal = false; if ((retFalse() & false) != false) retVal = false; if ((false & retFalse()) != false) retVal = false; return retVal; } } class OperatorsTestClass89 { public static bool retTrue() { return true; } public static bool retFalse() { return false; } public static bool testMethod() { bool retVal = true; if ((true && true) != true) retVal = false; if ((true && retTrue()) != true) retVal = false; if ((retTrue() && true) != true) retVal = false; if ((true && false) != false) retVal = false; if ((retTrue() && false) != false) retVal = false; if ((true && retFalse()) != false) retVal = false; if ((false && true) != false) retVal = false; if ((retFalse() && true) != false) retVal = false; if ((false && retTrue()) != false) retVal = false; if ((false && false) != false) retVal = false; if ((retFalse() && false) != false) retVal = false; if ((false && retFalse()) != false) retVal = false; return retVal; } } class OperatorsTestClass90 { public static bool retTrue() { return true; } public static bool retFalse() { return false; } public static bool testMethod() { bool retVal = true; if ((true | true) != true) retVal = false; if ((true | retTrue()) != true) retVal = false; if ((retTrue() | true) != true) retVal = false; if ((true | false) != true) retVal = false; if ((retTrue() | false) != true) retVal = false; if ((true | retFalse()) != true) retVal = false; if ((false | true) != true) retVal = false; if ((retFalse() | true) != true) retVal = false; if ((false | retTrue()) != true) retVal = false; if ((false | false) != false) retVal = false; if ((retFalse() | false) != false) retVal = false; if ((false | retFalse()) != false) retVal = false; return retVal; } } class OperatorsTestClass91 { public static bool retTrue() { return true; } public static bool retFalse() { return false; } public static bool testMethod() { bool retVal = true; if ((true || true) != true) retVal = false; if ((true || retTrue()) != true) retVal = false; if ((retTrue() || true) != true) retVal = false; if ((true || false) != true) retVal = false; if ((retTrue() || false) != true) retVal = false; if ((true || retFalse()) != true) retVal = false; if ((false || true) != true) retVal = false; if ((retFalse() || true) != true) retVal = false; if ((false || retTrue()) != true) retVal = false; if ((false || false) != false) retVal = false; if ((retFalse() || false) != false) retVal = false; if ((false || retFalse()) != false) retVal = false; return retVal; } } class OperatorsTestClass92 { public static bool retTrue() { return true; } public static bool retFalse() { return false; } public static bool testMethod() { bool retVal = true; if ((true ^ true) != false) retVal = false; if ((true ^ retTrue()) != false) retVal = false; if ((retTrue() ^ true) != false) retVal = false; if ((true ^ false) != true) retVal = false; if ((retTrue() ^ false) != true) retVal = false; if ((true ^ retFalse()) != true) retVal = false; if ((false ^ true) != true) retVal = false; if ((retFalse() ^ true) != true) retVal = false; if ((false ^ retTrue()) != true) retVal = false; if ((false ^ false) != false) retVal = false; if ((retFalse() ^ false) != false) retVal = false; if ((false ^ retFalse()) != false) retVal = false; return retVal; } } class OperatorsTestClass93 { public static bool testMethod() { bool retVal = true; sbyte sb = 2; byte b = 2; short s = 2; ushort us = 2; int i = 2; uint ui = 2; long l = 2; ulong ul = 2; if ((sb + 0) != sb) retVal = false; if ((0 + sb) != sb) retVal = false; if ((b + 0) != b) retVal = false; if ((0 + b) != b) retVal = false; if ((s + 0) != s) retVal = false; if ((0 + s) != s) retVal = false; if ((us + 0) != us) retVal = false; if ((0 + us) != us) retVal = false; if ((i + 0) != i) retVal = false; if ((0 + i) != i) retVal = false; if ((ui + 0) != ui) retVal = false; if ((0 + ui) != ui) retVal = false; if ((l + 0) != l) retVal = false; if ((0 + l) != l) retVal = false; if ((ul + 0) != ul) retVal = false; if ((0 + ul) != ul) retVal = false; return retVal; } } class OperatorsTestClass94 { public static bool testMethod() { bool retVal = true; sbyte sb = 2; byte b = 2; short s = 2; ushort us = 2; int i = 2; uint ui = 2; long l = 2; ulong ul = 2; if ((sb - 0) != sb) retVal = false; if ((b - 0) != b) retVal = false; if ((0 - b) != -b) retVal = false; if ((s - 0) != s) retVal = false; if ((0 - s) != -s) retVal = false; if ((us - 0) != us) retVal = false; if ((i - 0) != i) retVal = false; if ((0 - i) != -i) retVal = false; if ((ui - 0) != ui) retVal = false; if ((l - 0) != l) retVal = false; if ((0 - l) != -l) retVal = false; if ((ul - 0) != ul) retVal = false; return retVal; } } class OperatorsTestClass95 { public static bool testMethod() { bool retVal = true; sbyte sb = 2; byte b = 2; short s = 2; ushort us = 2; int i = 2; uint ui = 2; long l = 2; ulong ul = 2; if ((sb * 0) != 0) retVal = false; if ((0 * sb) != 0) retVal = false; if ((b * 0) != 0) retVal = false; if ((0 * b) != 0) retVal = false; if ((s * 0) != 0) retVal = false; if ((0 * s) != 0) retVal = false; if ((us * 0) != 0) retVal = false; if ((0 * us) != 0) retVal = false; if ((i * 0) != 0) retVal = false; if ((0 * i) != 0) retVal = false; if ((ui * 0) != 0) retVal = false; if ((0 * ui) != 0) retVal = false; if ((l * 0) != 0) retVal = false; if ((0 * l) != 0) retVal = false; if ((ul * 0) != 0) retVal = false; if ((0 * ul) != 0) retVal = false; return retVal; } } class OperatorsTestClass96 { public static bool testMethod() { bool retVal = true; sbyte sb = 2; byte b = 2; short s = 2; ushort us = 2; int i = 2; uint ui = 2; long l = 2; ulong ul = 2; if ((0 / sb) != 0) retVal = false; if ((0 / b) != 0) retVal = false; if ((0 / s) != 0) retVal = false; if ((0 / us) != 0) retVal = false; if ((0 / i) != 0) retVal = false; if ((0 / ui) != 0) retVal = false; if ((0 / l) != 0) retVal = false; if ((0 / ul) != 0) retVal = false; return retVal; } } } } ================================================ FILE: Zelig/Zelig/Test/RunTime/NETMF/mscorlib/classes/classes2/PropertiesTests.cs ================================================ //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // Copyright (c) Microsoft Corporation. All rights reserved. //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// #define TEST_EXCEPTIONS using System; using System.Reflection; using Microsoft.Zelig.Test; namespace Microsoft.Zelig.Test { public class PropertiesTests : TestBase, ITestInterface { [SetUp] public InitializeResult Initialize() { Log.Comment("Adding set up for the tests"); return InitializeResult.ReadyToGo; } [TearDown] public void CleanUp() { Log.Comment("Cleaning up after the tests"); } public override TestResult Run(string[] args) { TestResult result = TestResult.Pass; string testName = "Properties"; result |= Assert.CheckFailed(Properties003_Test(), testName, 3); result |= Assert.CheckFailed(Properties004_Test(), testName, 4); result |= Assert.CheckFailed(Properties005_Test(), testName, 5); result |= Assert.CheckFailed(Properties006_Test(), testName, 6); result |= Assert.CheckFailed(Properties007_Test(), testName, 7); result |= Assert.CheckFailed(Properties008_Test(), testName, 8); result |= Assert.CheckFailed(Properties009_Test(), testName, 9); result |= Assert.CheckFailed(Properties010_Test(), testName, 10); result |= Assert.CheckFailed(Properties011_Test(), testName, 11); result |= Assert.CheckFailed(Properties024_Test(), testName, 24); result |= Assert.CheckFailed(Properties025_Test(), testName, 25); result |= Assert.CheckFailed(Properties026_Test(), testName, 26); result |= Assert.CheckFailed(Properties027_Test(), testName, 27); result |= Assert.CheckFailed(Properties033_Test(), testName, 33); result |= Assert.CheckFailed(Properties034_Test(), testName, 34); result |= Assert.CheckFailed(Properties035_Test(), testName, 35); result |= Assert.CheckFailed(Properties036_Test(), testName, 36); result |= Assert.CheckFailed(Properties037_Test(), testName, 37); result |= Assert.CheckFailed(Properties038_Test(), testName, 38); result |= Assert.CheckFailed(Properties043_Test(), testName, 43); result |= Assert.CheckFailed(Properties046_Test(), testName, 46); result |= Assert.CheckFailed(Properties048_Test(), testName, 48); result |= Assert.CheckFailed(Properties050_Test(), testName, 50); result |= Assert.CheckFailed(Properties053_Test(), testName, 53); result |= Assert.CheckFailed(Properties054_Test(), testName, 54); result |= Assert.CheckFailed(Properties056_Test(), testName, 56); result |= Assert.CheckFailed(Properties058_Test(), testName, 58); result |= Assert.CheckFailed(Properties059_Test(), testName, 59); result |= Assert.CheckFailed(Properties060_Test(), testName, 60); result |= Assert.CheckFailed(Properties062_Test(), testName, 62); result |= Assert.CheckFailed(Properties068_Test(), testName, 68); result |= Assert.CheckFailed(Properties071_Test(), testName, 71); result |= Assert.CheckFailed(Properties072_Test(), testName, 72); result |= Assert.CheckFailed(Properties073_Test(), testName, 73); result |= Assert.CheckFailed(Properties074_Test(), testName, 74); result |= Assert.CheckFailed(Properties075_Test(), testName, 75); result |= Assert.CheckFailed(Properties078_Test(), testName, 78); result |= Assert.CheckFailed(Properties089_Test(), testName, 89); result |= Assert.CheckFailed(Properties090_Test(), testName, 90); result |= Assert.CheckFailed(Properties097_Test(), testName, 97); result |= Assert.CheckFailed(Properties109_Test(), testName, 109); result |= Assert.CheckFailed(Properties110_Test(), testName, 110); result |= Assert.CheckFailed(Properties121_Test(), testName, 121); result |= Assert.CheckFailed(Properties122_Test(), testName, 122); result |= Assert.CheckFailed(Properties123_Test(), testName, 123); result |= Assert.CheckFailed(Properties124_Test(), testName, 124); result |= Assert.CheckFailed(Properties125_Test(), testName, 125); result |= Assert.CheckFailed(Properties126_Test(), testName, 126); return result; } //Properties Test methods //The following test methods were ported from the folder //current\test\cases\client\CLR\Conformance\10_classes\Properties //003,004,005,006,007,008,009,010,011,024,025,026,027,033,034,035,036,037,038, //043,046,048,050,053,054,056,058,059,060,062,068,071,072,073,074,075,078,089, //090,097,109,110,121,122,123,124,125,126 //Tests 134-125 failed in the Baseline Doc, all others passed //All tests that were not ported were not present in the Baseline Doc //Test Case Calls [TestMethod] public TestResult Properties003_Test() { Log.Comment("Section 10.6"); Log.Comment("A property declaration may include set of"); Log.Comment("attributes, a new modifier, a valid combination"); Log.Comment("nof the four access modifiers, and a static modifier."); if (PropertiesTestClass003.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Properties004_Test() { Log.Comment("Section 10.6"); Log.Comment("A property declaration may include set of"); Log.Comment("attributes, a new modifier, a valid combination"); Log.Comment("nof the four access modifiers, and a static modifier."); if (PropertiesTestClass004.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Properties005_Test() { Log.Comment("Section 10.6"); Log.Comment("A property declaration may include set of"); Log.Comment("attributes, a new modifier, a valid combination"); Log.Comment("nof the four access modifiers, and a static modifier."); if (PropertiesTestClass005.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Properties006_Test() { Log.Comment("Section 10.6"); Log.Comment("A property declaration may include set of"); Log.Comment("attributes, a new modifier, a valid combination"); Log.Comment("nof the four access modifiers, and a static modifier."); if (PropertiesTestClass006.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Properties007_Test() { Log.Comment("Section 10.6"); Log.Comment("A property declaration may include set of"); Log.Comment("attributes, a new modifier, a valid combination"); Log.Comment("nof the four access modifiers, and a static modifier."); if (PropertiesTestClass007.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Properties008_Test() { Log.Comment("Section 10.6"); Log.Comment("A property declaration may include set of"); Log.Comment("attributes, a new modifier, a valid combination"); Log.Comment("nof the four access modifiers, and a static modifier."); if (PropertiesTestClass008.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Properties009_Test() { Log.Comment("Section 10.6"); Log.Comment("A property declaration may include set of"); Log.Comment("attributes, a new modifier, a valid combination"); Log.Comment("nof the four access modifiers, and a static modifier."); if (PropertiesTestClass009.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Properties010_Test() { Log.Comment("Section 10.6"); Log.Comment("A property declaration may include set of"); Log.Comment("attributes, a new modifier, a valid combination"); Log.Comment("nof the four access modifiers, and a static modifier."); if (PropertiesTestClass010.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Properties011_Test() { Log.Comment("Section 10.6 "); Log.Comment("The type of a property declaration specifies"); Log.Comment("the type of the property introduced by the"); Log.Comment("declaration, and the member-name specifies"); Log.Comment("the name of the property. Unless the property"); Log.Comment("is an explicit interface member implementation,"); Log.Comment("the member name is simply an identifier. For an"); Log.Comment("explicit interface member implementation, the"); Log.Comment("member name consists of an interface-type followed"); Log.Comment("by a . and an identifier."); Log.Comment("This is currently an expected fail, but is resolved in 3.0 see Bug 16341 for details"); if (PropertiesTestClass011.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Properties024_Test() { Log.Comment("Section 10.6 "); Log.Comment("An instance property is associated with"); Log.Comment("a given instance of a class, and this instance"); Log.Comment("can be accessed as this in the accessors of"); Log.Comment("the property."); if (PropertiesTestClass024.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Properties025_Test() { Log.Comment("Section 10.6 "); Log.Comment("An instance property is associated with"); Log.Comment("a given instance of a class, and this instance"); Log.Comment("can be accessed as this in the accessors of"); Log.Comment("the property."); if (PropertiesTestClass025.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Properties026_Test() { Log.Comment("Section 10.6 "); Log.Comment("When a property is referenced in a member-access"); Log.Comment("of the form E.M, if M is a static property, E must"); Log.Comment("denote a type, and if M is an instance property,"); Log.Comment("E must denote an instance."); if (PropertiesTestClass026.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Properties027_Test() { Log.Comment("Section 10.6 "); Log.Comment("When a property is referenced in a member-access"); Log.Comment("of the form E.M, if M is a static property, E must"); Log.Comment("denote a type, and if M is an instance property,"); Log.Comment("E must denote an instance."); if (PropertiesTestClass027.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Properties033_Test() { Log.Comment("Section 10.6 "); Log.Comment("The accessor declarations consist of a "); Log.Comment("get-accessor-declaration, a set-accessor"); Log.Comment("declaration, or both."); if (PropertiesTestClass033.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Properties034_Test() { Log.Comment("Section 10.6 "); Log.Comment("The accessor declarations consist of a "); Log.Comment("get-accessor-declaration, a set-accessor"); Log.Comment("declaration, or both."); if (PropertiesTestClass034.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Properties035_Test() { Log.Comment("Section 10.6 "); Log.Comment("The accessor declarations consist of a "); Log.Comment("get-accessor-declaration, a set-accessor"); Log.Comment("declaration, or both."); if (PropertiesTestClass035.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Properties036_Test() { Log.Comment("Section 10.6 "); Log.Comment("Each accessor declaration consists of an"); Log.Comment("optional accessor-modifier, followed by the"); Log.Comment("keyword get or set, followed by an accessor"); if (PropertiesTestClass036.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Properties037_Test() { Log.Comment("Section 10.6 "); Log.Comment("Each accessor declaration consists of an"); Log.Comment("optional accessor-modifier, followed by the"); Log.Comment("keyword get or set, followed by an accessor"); if (PropertiesTestClass037.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Properties038_Test() { Log.Comment("Section 10.6 "); Log.Comment("Each accessor declaration consists of an"); Log.Comment("optional accessor-modifier, followed by the"); Log.Comment("keyword get or set, followed by an accessor"); if (PropertiesTestClass038.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Properties043_Test() { Log.Comment("Section 10.6 "); Log.Comment("Each accessor declaration consists of an"); Log.Comment("optional accessor-modifier, followed by the"); Log.Comment("keyword get or set, followed by an accessor"); if (PropertiesTestClass043.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Properties046_Test() { Log.Comment("Section 10.6 "); Log.Comment("Each accessor declaration consists of an"); Log.Comment("optional accessor-modifier, followed by the"); Log.Comment("keyword get or set, followed by an accessor"); if (PropertiesTestClass046.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Properties048_Test() { Log.Comment("Section 10.6 "); Log.Comment("Each accessor declaration consists of an"); Log.Comment("optional accessor-modifier, followed by the"); Log.Comment("keyword get or set, followed by an accessor"); if (PropertiesTestClass048.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Properties050_Test() { Log.Comment("Section 10.6 "); Log.Comment("Each accessor declaration consists of an"); Log.Comment("optional accessor-modifier, followed by the"); Log.Comment("keyword get or set, followed by an accessor"); if (PropertiesTestClass050.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Properties053_Test() { Log.Comment("Section 10.6 "); Log.Comment("Each accessor declaration consists of an"); Log.Comment("optional accessor-modifier, followed by the"); Log.Comment("keyword get or set, followed by an accessor"); #if TEST_EXCEPTIONS if (PropertiesTestClass053.testMethod()) { return TestResult.Pass; } return TestResult.Fail; #else return TestResult.Skip; #endif } [TestMethod] public TestResult Properties054_Test() { Log.Comment("Section 10.6 "); Log.Comment("Each accessor declaration consists of an"); Log.Comment("optional accessor-modifier, followed by the"); Log.Comment("keyword get or set, followed by an accessor"); #if TEST_EXCEPTIONS if (PropertiesTestClass054.testMethod()) { return TestResult.Pass; } return TestResult.Fail; #else return TestResult.Skip; #endif } [TestMethod] public TestResult Properties056_Test() { Log.Comment("Section 10.6 "); Log.Comment("Each accessor declaration consists of an"); Log.Comment("optional accessor-modifier, followed by the"); Log.Comment("keyword get or set, followed by an accessor"); if (PropertiesTestClass056.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Properties058_Test() { Log.Comment("Section 10.6 "); Log.Comment("Each accessor declaration consists of an"); Log.Comment("optional accessor-modifier, followed by the"); Log.Comment("keyword get or set, followed by an accessor"); if (PropertiesTestClass058.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Properties059_Test() { Log.Comment("Section 10.6 "); Log.Comment("Each accessor declaration consists of an"); Log.Comment("optional accessor-modifier, followed by the"); Log.Comment("keyword get or set, followed by an accessor"); if (PropertiesTestClass059.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Properties060_Test() { Log.Comment("Section 10.6 "); Log.Comment("Each accessor declaration consists of an"); Log.Comment("optional accessor-modifier, followed by the"); Log.Comment("keyword get or set, followed by an accessor"); if (PropertiesTestClass060.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Properties062_Test() { Log.Comment("Section 10.6 "); Log.Comment("Each accessor declaration consists of an"); Log.Comment("optional accessor-modifier, followed by the"); Log.Comment("keyword get or set, followed by an accessor"); if (PropertiesTestClass062.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Properties068_Test() { Log.Comment("Section 10.6 "); Log.Comment("Each accessor declaration consists of an"); Log.Comment("optional accessor-modifier, followed by the"); Log.Comment("keyword get or set, followed by an accessor"); if (PropertiesTestClass068.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Properties071_Test() { Log.Comment("Section 10.6 "); Log.Comment("Each accessor declaration consists of an"); Log.Comment("optional accessor-modifier, followed by the"); Log.Comment("keyword get or set, followed by an accessor"); if (PropertiesTestClass071.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Properties072_Test() { Log.Comment("Section 10.6 "); Log.Comment("Each accessor declaration consists of an"); Log.Comment("optional accessor-modifier, followed by the"); Log.Comment("keyword get or set, followed by an accessor"); if (PropertiesTestClass072.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Properties073_Test() { Log.Comment("Section 10.6 "); Log.Comment("Each accessor declaration consists of an"); Log.Comment("optional accessor-modifier, followed by the"); Log.Comment("keyword get or set, followed by an accessor"); if (PropertiesTestClass073.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Properties074_Test() { Log.Comment("Section 10.6 "); Log.Comment("Each accessor declaration consists of an"); Log.Comment("optional accessor-modifier, followed by the"); Log.Comment("keyword get or set, followed by an accessor"); if (PropertiesTestClass074.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Properties075_Test() { Log.Comment("Section 10.6 "); Log.Comment("Each accessor declaration consists of an"); Log.Comment("optional accessor-modifier, followed by the"); Log.Comment("keyword get or set, followed by an accessor"); if (PropertiesTestClass075.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Properties078_Test() { Log.Comment("Section 10.6 "); Log.Comment("Each accessor declaration consists of an"); Log.Comment("optional accessor-modifier, followed by the"); Log.Comment("keyword get or set, followed by an accessor"); if (PropertiesTestClass078.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Properties089_Test() { Log.Comment("Section 10.6 "); Log.Comment("Each accessor declaration consists of an"); Log.Comment("optional accessor-modifier, followed by the"); Log.Comment("keyword get or set, followed by an accessor"); if (PropertiesTestClass089.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Properties090_Test() { Log.Comment("Section 10.6 "); Log.Comment("Each accessor declaration consists of an"); Log.Comment("optional accessor-modifier, followed by the"); Log.Comment("keyword get or set, followed by an accessor"); if (PropertiesTestClass090.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Properties097_Test() { Log.Comment("Section 10.6 "); Log.Comment("Each accessor declaration consists of an"); Log.Comment("optional accessor-modifier, followed by the"); Log.Comment("keyword get or set, followed by an accessor"); if (PropertiesTestClass097.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Properties109_Test() { Log.Comment("Section 10.6 "); Log.Comment("Each accessor declaration consists of an"); Log.Comment("optional accessor-modifier, followed by the"); Log.Comment("keyword get or set, followed by an accessor"); if (PropertiesTestClass109.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Properties110_Test() { Log.Comment("Section 10.6 "); Log.Comment("Each accessor declaration consists of an"); Log.Comment("optional accessor-modifier, followed by the"); Log.Comment("keyword get or set, followed by an accessor"); if (PropertiesTestClass110.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Properties121_Test() { Log.Comment("Section 10.6 "); Log.Comment("Each accessor declaration consists of an"); Log.Comment("optional accessor-modifier, followed by the"); Log.Comment("keyword get or set, followed by an accessor"); if (PropertiesTestClass121.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Properties122_Test() { Log.Comment("Section 10.6 "); Log.Comment("Each accessor declaration consists of an"); Log.Comment("optional accessor-modifier, followed by the"); Log.Comment("keyword get or set, followed by an accessor"); if (PropertiesTestClass122.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Properties123_Test() { Log.Comment("Section 10.6 "); Log.Comment("Each accessor declaration consists of an"); Log.Comment("optional accessor-modifier, followed by the"); Log.Comment("keyword get or set, followed by an accessor"); //Log.Comment("This test is an expected fail"); if (PropertiesTestClass123.testMethod()) { //return TestResult.Fail; return TestResult.Pass; } //return TestResult.Pass; return TestResult.Fail; } [TestMethod] public TestResult Properties124_Test() { Log.Comment("Section 10.6 "); Log.Comment("Each accessor declaration consists of an"); Log.Comment("optional accessor-modifier, followed by the"); Log.Comment("keyword get or set, followed by an accessor"); //Log.Comment("This test is an expected fail"); if (PropertiesTestClass124.testMethod()) { //return TestResult.Fail; return TestResult.Pass; } //return TestResult.Pass; return TestResult.Fail; } [TestMethod] public TestResult Properties125_Test() { Log.Comment("Section 10.6 "); Log.Comment("Each accessor declaration consists of an"); Log.Comment("optional accessor-modifier, followed by the"); Log.Comment("keyword get or set, followed by an accessor"); if (PropertiesTestClass125.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Properties126_Test() { Log.Comment("Section 10.6 "); Log.Comment("Each accessor declaration consists of an"); Log.Comment("optional accessor-modifier, followed by the"); Log.Comment("keyword get or set, followed by an accessor"); if (PropertiesTestClass126.testMethod()) { return TestResult.Fail; } return TestResult.Pass; } //Compiled Test Cases class PropertiesTestClass003 { int intI = 0; int MyProp { get { return intI; } set { intI = value; } } public static bool testMethod() { PropertiesTestClass003 test = new PropertiesTestClass003(); test.MyProp = 2; if (test.MyProp == 2) { return true; } else { return false; } } } class PropertiesTestClass004_Base { public int MyProp { get { return 1; } } } class PropertiesTestClass004 : PropertiesTestClass004_Base { int intI = 0; new int MyProp { get { return intI; } set { intI = value; } } public static bool testMethod() { PropertiesTestClass004 test = new PropertiesTestClass004(); test.MyProp = 2; if (test.MyProp == 2) { return true; } else { return false; } } } class PropertiesTestClass005 { int intI = 0; public int MyProp { get { return intI; } set { intI = value; } } public static bool testMethod() { PropertiesTestClass005 test = new PropertiesTestClass005(); test.MyProp = 2; if (test.MyProp == 2) { return true; } else { return false; } } } class PropertiesTestClass006 { int intI = 0; protected int MyProp { get { return intI; } set { intI = value; } } public static bool testMethod() { PropertiesTestClass006 test = new PropertiesTestClass006(); test.MyProp = 2; if (test.MyProp == 2) { return true; } else { return false; } } } class PropertiesTestClass007 { int intI = 0; internal int MyProp { get { return intI; } set { intI = value; } } public static bool testMethod() { PropertiesTestClass007 test = new PropertiesTestClass007(); test.MyProp = 2; if (test.MyProp == 2) { return true; } else { return false; } } } class PropertiesTestClass008 { int intI = 0; private int MyProp { get { return intI; } set { intI = value; } } public static bool testMethod() { PropertiesTestClass008 test = new PropertiesTestClass008(); test.MyProp = 2; if (test.MyProp == 2) { return true; } else { return false; } } } class PropertiesTestClass009 { int intI = 0; protected internal int MyProp { get { return intI; } set { intI = value; } } public static bool testMethod() { PropertiesTestClass009 test = new PropertiesTestClass009(); test.MyProp = 2; if (test.MyProp == 2) { return true; } else { return false; } } } class PropertiesTestClass010 { static int intI = 0; static int MyProp { get { return intI; } set { intI = value; } } public static bool testMethod() { PropertiesTestClass010.MyProp = 2; if (PropertiesTestClass010.MyProp == 2) { return true; } else { return false; } } } interface PropertiesTestClass011_Interface { int MyProp { get; set; } } class PropertiesTestClass011 : PropertiesTestClass011_Interface { static int intI = 0; int PropertiesTestClass011_Interface.MyProp { get { return intI; } set { intI = value; } } public static bool testMethod() { try { PropertiesTestClass011 MC = new PropertiesTestClass011(); ((PropertiesTestClass011_Interface)MC).MyProp = 2; if (((PropertiesTestClass011_Interface)MC).MyProp == 2) { return true; } else { return false; } } catch { return false; } } } public class PropertiesTestClass024 { public int intI = 2; public int MyProp { get { return this.intI; } } public static bool testMethod() { PropertiesTestClass024 test = new PropertiesTestClass024(); if (test.MyProp == 2) { return true; } else { return false; } } } public class PropertiesTestClass025 { public int intI = 1; public int MyProp { set { this.intI = value; } } public static bool testMethod() { PropertiesTestClass025 test = new PropertiesTestClass025(); test.MyProp = 2; if (test.intI == 2) { return true; } else { return false; } } } public class PropertiesTestClass026 { public int intI = 1; public int MyProp { set { this.intI = value; } get { return intI; } } public int GetProp() { return MyProp; } public void SetProp(int intJ) { MyProp = intJ; } public static bool testMethod() { PropertiesTestClass026 test = new PropertiesTestClass026(); test.SetProp(3); if (test.GetProp() == 3) { return true; } else { return false; } } } public class PropertiesTestClass027 { public static int intI = 1; public static int MyProp { set { intI = value; } get { return intI; } } public static int GetProp() { return MyProp; } public static void SetProp(int intJ) { MyProp = intJ; } public static bool testMethod() { PropertiesTestClass027.SetProp(3); if (PropertiesTestClass027.GetProp() == 3) { return true; } else { return false; } } } public class PropertiesTestClass033 { public int MyProp { get { return 2; } } public static bool testMethod() { PropertiesTestClass033 test = new PropertiesTestClass033(); if (test.MyProp == 2) { return true; } else { return false; } } } public class PropertiesTestClass034 { public int intI = 0; public int MyProp { set { intI = value; } } public static bool testMethod() { PropertiesTestClass034 test = new PropertiesTestClass034(); test.MyProp = 2; if (test.intI == 2) { return true; } else { return false; } } } public class PropertiesTestClass035 { public int intI = 0; public int MyProp { set { intI = value; } get { return intI; } } public static bool testMethod() { PropertiesTestClass035 test = new PropertiesTestClass035(); test.MyProp = 2; if (test.MyProp == 2) { return true; } else { return false; } } } public class PropertiesTestClass036 { int intI = 0; public virtual int MyProp { set { intI = value; } get { return intI; } } public static bool testMethod() { PropertiesTestClass036 test = new PropertiesTestClass036(); test.MyProp = 2; if (test.MyProp == 2) { return true; } else { return false; } } } public class PropertiesTestClass037_Base { public virtual int MyProp { set { } get { return -1; } } } public class PropertiesTestClass037 : PropertiesTestClass037_Base { int intI = 0; public override int MyProp { set { intI = value; } get { return intI; } } public static bool testMethod() { PropertiesTestClass037_Base test = new PropertiesTestClass037(); test.MyProp = 2; if (test.MyProp == 2) { return true; } else { return false; } } } public abstract class PropertiesTestClass038_Base { public abstract int MyProp { set; get; } } public class PropertiesTestClass038 : PropertiesTestClass038_Base { int intI = 0; public override int MyProp { set { intI = value; } get { return intI; } } public static bool testMethod() { PropertiesTestClass038_Base test = new PropertiesTestClass038(); test.MyProp = 2; if (test.MyProp == 2) { return true; } else { return false; } } } public class PropertiesTestClass043 { public int TestInt = 1; public int MyProp { get { TestInt = 2; return -1; } set { } } public static bool testMethod() { PropertiesTestClass043 test = new PropertiesTestClass043(); test.MyProp = 2; if (test.TestInt == 1) { return true; } else { return false; } } } public class PropertiesTestClass046 { public int MyProp { get { short s = 3; return s; } } public static bool testMethod() { PropertiesTestClass046 test = new PropertiesTestClass046(); if (test.MyProp == 3) { return true; } else { return false; } } } public class PropertiesTestClass048_Sub { public int intI = 2; public static implicit operator int(PropertiesTestClass048_Sub t) { return t.intI; } } public class PropertiesTestClass048 { public int MyProp { get { PropertiesTestClass048_Sub test = new PropertiesTestClass048_Sub(); return test; } } public static bool testMethod() { PropertiesTestClass048 MC = new PropertiesTestClass048(); if (MC.MyProp == 2) { return true; } else { return false; } } } public class PropertiesTestClass050_Sub { public int intI = 2; public static implicit operator int(PropertiesTestClass050_Sub t) { return t.intI; } } public class PropertiesTestClass050 { public bool b = true; public int MyProp { get { if (b == true) { PropertiesTestClass050_Sub test = new PropertiesTestClass050_Sub(); return test; } else { return 3; } } } public static bool testMethod() { PropertiesTestClass050 MC = new PropertiesTestClass050(); PropertiesTestClass050 MC2 = new PropertiesTestClass050(); MC.b = true; MC2.b = false; if ((MC.MyProp == 2) && (MC2.MyProp == 3)) { return true; } else { return false; } } } public class PropertiesTestClass053 { public int MyProp { get { throw new System.Exception(); } } public static bool testMethod() { PropertiesTestClass053 test = new PropertiesTestClass053(); try { int intJ = test.MyProp; } catch (System.Exception) { return true; } return false; } } public class PropertiesTestClass054 { public bool b = true; public int MyProp { get { if (b == true) { return 1; } else { throw new System.Exception(); } } } public static bool testMethod() { PropertiesTestClass054 MC = new PropertiesTestClass054(); PropertiesTestClass054 MC2 = new PropertiesTestClass054(); MC.b = true; MC2.b = false; if (MC.MyProp != 1) { return false; } try { int intJ = MC2.MyProp; } catch (System.Exception) { return true; } return false; } } public class PropertiesTestClass056 { public int intI = 2; public int MyProp { set {} get { intI = 3; return 1; } } public static bool testMethod() { PropertiesTestClass056 test = new PropertiesTestClass056(); test.MyProp = 4; if (test.intI == 2) { return true; } else { return false; } } } public class PropertiesTestClass058 { public int intI = 2; public int MyProp { set { return; intI = 3; } } public static bool testMethod() { PropertiesTestClass058 test = new PropertiesTestClass058(); test.MyProp = 4; if (test.intI == 2) { return true; } else { return false; } } } public class PropertiesTestClass059 { public int intI = 2; public int MyProp { set { intI = value; return; } } public static bool testMethod() { PropertiesTestClass059 test = new PropertiesTestClass059(); test.MyProp = 4; if (test.intI == 4) { return true; } else { return false; } } } public class PropertiesTestClass060 { bool b = true; public int intI = 2; public int MyProp { set { if (b == true) { intI = value; return; } else { intI = value + 1; return; } } } public static bool testMethod() { PropertiesTestClass060 test = new PropertiesTestClass060(); PropertiesTestClass060 test2 = new PropertiesTestClass060(); test.b = true; test2.b = false; test.MyProp = 4; test2.MyProp = 4; if ((test.intI == 4) && (test2.intI == 5)) { return true; } else { return false; } } } public class PropertiesTestClass062 { int value; public int MyProp { set { this.value = 2; value = 3; } } public static bool testMethod() { PropertiesTestClass062 test = new PropertiesTestClass062(); test.MyProp = 1; if (test.value == 2) { return true; } else { return false; } } } public class PropertiesTestClass068_Base { public int intTest; public int MyProp { get { return intTest; } set { intTest = value; } } } public class PropertiesTestClass068 : PropertiesTestClass068_Base { new public int MyProp { get { return intTest + 1; } set { intTest = value + 1; } } public static bool testMethod() { PropertiesTestClass068 test = new PropertiesTestClass068(); test.MyProp = 2; if (test.MyProp == 4) { return true; } else { return false; } } } public class PropertiesTestClass071_Base { public int MyProp { get { return 1; } } } public class PropertiesTestClass071 : PropertiesTestClass071_Base { public int MyProp { set {} } public static bool testMethod() { PropertiesTestClass071 test = new PropertiesTestClass071(); int intJ = ((PropertiesTestClass071_Base)test).MyProp; if (intJ == 1) { return true; } else { return false; } } } public class PropertiesTestClass072_Base { public int intI; public int MyProp { set{intI = value;} } } public class PropertiesTestClass072 : PropertiesTestClass072_Base { new public int MyProp { get {return 1;} } public static bool testMethod() { PropertiesTestClass072 test = new PropertiesTestClass072(); ((PropertiesTestClass072_Base)test).MyProp = 2; if (test.intI == 2) { return true; } else { return false; } } } public class PropertiesTestClass073_Base { public int MyProp { get { return 1; } } } public class PropertiesTestClass073 : PropertiesTestClass073_Base { new public int MyProp { get {return 2;} } public static bool testMethod() { PropertiesTestClass073 test = new PropertiesTestClass073(); int intJ = ((PropertiesTestClass073_Base)test).MyProp; if (intJ == 1) { return true; } else { return false; } } } public class PropertiesTestClass074_Base { public int intI; public int MyProp { set{intI = value;} } } public class PropertiesTestClass074 : PropertiesTestClass074_Base { new public int MyProp { set{intI = value + 1;} } public static bool testMethod() { PropertiesTestClass074 test = new PropertiesTestClass074(); ((PropertiesTestClass074_Base)test).MyProp = 2; if (test.intI == 2) { return true; } else { return false; } } } public class PropertiesTestClass075 { int intI = 0; public virtual int MyProp { get {return intI;} set {intI = value;} } public static bool testMethod() { PropertiesTestClass075 test = new PropertiesTestClass075(); test.MyProp = 2; if (test.MyProp == 2) { return true; } else { return false; } } } public abstract class PropertiesTestClass078_Sub { public int intI = 0; public abstract int MyProp { get; set; } } public class PropertiesTestClass078 : PropertiesTestClass078_Sub { public override int MyProp { get {return intI;} set {intI = value;} } public static bool testMethod() { PropertiesTestClass078_Sub test = new PropertiesTestClass078(); test.MyProp = 2; if (test.MyProp == 2) { return true; } else { return false; } } } public class PropertiesTestClass089_Base { public int intI; public virtual int MyProp { set {intI = value;} get {return intI;} } } public class PropertiesTestClass089 : PropertiesTestClass089_Base { public override int MyProp { get {return intI + 1;} } public static bool testMethod() { PropertiesTestClass089_Base test = new PropertiesTestClass089(); test.MyProp = 2; if (test.MyProp == 3) { return true; } else { return false; } } } public class PropertiesTestClass090_Base { public int intI; public virtual int MyProp { set {intI = value;} get {return intI;} } } public class PropertiesTestClass090 : PropertiesTestClass090_Base { public override int MyProp { set {intI = value - 1;} } public static bool testMethod() { PropertiesTestClass090_Base test = new PropertiesTestClass090(); test.MyProp = 2; if (test.MyProp == 1) { return true; } else { return false; } } } class PropertiesTestClass097 { int intI = 0; int MyProp { set { intI = value; } get { return intI; } } public static bool testMethod() { PropertiesTestClass097 test = new PropertiesTestClass097(); test.MyProp = 2; if (test.MyProp == 2) { return true; } else { return false; } } } class PropertiesTestClass109_Base { public virtual int foo { get { return 1; } } } class PropertiesTestClass109_Derived : PropertiesTestClass109_Base { private int get_foo() { return 1; } } class PropertiesTestClass109 : PropertiesTestClass109_Derived { public override int foo { get { return 2; } } public static bool testMethod() { PropertiesTestClass109_Base MB = new PropertiesTestClass109(); if (MB.foo == 2) { return true; } else { return false; } } } class PropertiesTestClass110_Base { public int intI; public virtual int foo { set { intI = 1; } } } class PropertiesTestClass110_Derived : PropertiesTestClass110_Base { private void set_foo(int value) { intI = 2; } } class PropertiesTestClass110 : PropertiesTestClass110_Derived { public override int foo { set { intI = 3; } } public static bool testMethod() { PropertiesTestClass110_Base MB = new PropertiesTestClass110(); MB.foo = 3; if (MB.intI == 3) { return true; } else { return false; } } } class PropertiesTestClass121_Base { public virtual int MyProp { get { return 1; } } } class PropertiesTestClass121 : PropertiesTestClass121_Base { public override int MyProp { get { return 2; } } public static bool testMethod() { PropertiesTestClass121_Base MC = new PropertiesTestClass121(); if (MC.MyProp == 2) { return true; } else { return false; } } } class PropertiesTestClass122_Base { public int myInt; public virtual int MyProp { set { myInt = 1; } } } class PropertiesTestClass122 : PropertiesTestClass122_Base { public override int MyProp { set { myInt = 2; } } public static bool testMethod() { PropertiesTestClass122_Base MC = new PropertiesTestClass122(); MC.MyProp = 0; if (MC.myInt == 2) { return true; } else { return false; } } } class PropertiesTestClass123_Base { public virtual int MyProp { get { return 1; } } } class PropertiesTestClass123 : PropertiesTestClass123_Base { public new int MyProp { get { return 2; } } public static bool testMethod() { PropertiesTestClass123_Base MC = new PropertiesTestClass123(); if (MC.MyProp == 1) { return true; } else { return false; } } } class PropertiesTestClass124_Base { public int myInt; public virtual int MyProp { set { myInt = 1; } } } class PropertiesTestClass124 : PropertiesTestClass124_Base { public new int MyProp { set { myInt = 2; } } public static bool testMethod() { PropertiesTestClass124_Base MC = new PropertiesTestClass124(); MC.MyProp = 0; if (MC.myInt == 1) { return true; } else { return false; } } } class PropertiesTestClass125_Base { public int intI = 0; public virtual int MyProp { get { return -1; } set { intI = -1; } } } class PropertiesTestClass125 : PropertiesTestClass125_Base { public override int MyProp { get { return intI; } set { intI = value; } } public static bool testMethod() { PropertiesTestClass125_Base MC = new PropertiesTestClass125(); MC.MyProp = 4; if (MC.MyProp == 4) { return true; } else { return false; } } } class PropertiesTestClass126_Base { public int intI = 0; public virtual int MyProp { get { return intI; } set { intI = value; } } } class PropertiesTestClass126 : PropertiesTestClass126_Base { public new int MyProp { get { return -1; } set { intI = -1; } } public static bool testMethod() { PropertiesTestClass126_Base MC = new PropertiesTestClass126(); MC.MyProp = 4; if (MC.MyProp == -1) { return true; } else { return false; } } } } } ================================================ FILE: Zelig/Zelig/Test/RunTime/NETMF/mscorlib/classes/classes2/Static_InstTests.cs ================================================ //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // Copyright (c) Microsoft Corporation. All rights reserved. //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// using System; using System.Reflection; namespace Microsoft.Zelig.Test { public class Static_InstTests : TestBase, ITestInterface { [SetUp] public InitializeResult Initialize() { Log.Comment("Adding set up for the tests"); return InitializeResult.ReadyToGo; } [TearDown] public void CleanUp() { Log.Comment("Cleaning up after the tests"); } public override TestResult Run( string[] args ) { TestResult result = TestResult.Pass; string testName = "Static_Inst"; result |= Assert.CheckFailed(Static_Inst01_Test(), testName, 1); result |= Assert.CheckFailed(Static_Inst07_Test(), testName, 7); result |= Assert.CheckFailed(Static_Inst14_Test(), testName, 14); result |= Assert.CheckFailed(Static_Inst18_Test(), testName, 18); result |= Assert.CheckFailed(Static_Inst19_Test(), testName, 19); result |= Assert.CheckFailed(Static_Inst20_Test(), testName, 20); result |= Assert.CheckFailed(Static_Inst21_Test(), testName, 21); result |= Assert.CheckFailed(Static_Inst22_Test(), testName, 22); result |= Assert.CheckFailed(Static_Inst23_Test(), testName, 23); return result; } //Static_Inst Test methods //The following tests were ported from folder current\test\cases\client\CLR\Conformance\10_classes\Static_Inst //Test Case Calls [TestMethod] public TestResult Static_Inst01_Test() { Log.Comment(" Section 10.2 "); Log.Comment(" When a static member is referenced in a member-access"); Log.Comment(" of the form E.M, E must denote a type. It is an error for"); Log.Comment(" E to denote an instance."); if (Static_InstTestClass01.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Static_Inst07_Test() { Log.Comment(" Section 10.2 "); Log.Comment(" A static field identifies exactly one storage location."); Log.Comment(" No matter how many instances of a class are created,"); Log.Comment(" there is only ever one copy of a static field."); if (Static_InstTestClass07.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Static_Inst14_Test() { Log.Comment(" Section 10.2 "); Log.Comment(" When an instance member is referenced in a member-access"); Log.Comment(" of the form E.M, E must denote an instance. It is an error "); Log.Comment(" for E to denote a type."); if (Static_InstTestClass14.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Static_Inst18_Test() { Log.Comment(" Section 10.2 "); Log.Comment(" Every instance of a class contains a separate copy "); Log.Comment(" of all instance fields of the class."); if (Static_InstTestClass18.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Static_Inst19_Test() { Log.Comment(" Section 10.2 "); Log.Comment(" An instance function member (method, property "); Log.Comment(" accessor, indexer accessor, constructor, or "); Log.Comment(" destructor) operates on a given instance of "); Log.Comment(" the class, and this instance can be accessed as"); Log.Comment(" this."); if (Static_InstTestClass19.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Static_Inst20_Test() { Log.Comment(" Section 10.2 "); Log.Comment(" An instance function member (method, property "); Log.Comment(" accessor, indexer accessor, constructor, or "); Log.Comment(" destructor) operates on a given instance of "); Log.Comment(" the class, and this instance can be accessed as"); Log.Comment(" this."); if (Static_InstTestClass20.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Static_Inst21_Test() { Log.Comment(" Section 10.2 "); Log.Comment(" An instance function member (method, property "); Log.Comment(" accessor, indexer accessor, constructor, or "); Log.Comment(" destructor) operates on a given instance of "); Log.Comment(" the class, and this instance can be accessed as"); Log.Comment(" this."); if (Static_InstTestClass21.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Static_Inst22_Test() { Log.Comment(" Section 10.2 "); Log.Comment(" An instance function member (method, property "); Log.Comment(" accessor, indexer accessor, constructor, or "); Log.Comment(" destructor) operates on a given instance of "); Log.Comment(" the class, and this instance can be accessed as"); Log.Comment(" this."); if (Static_InstTestClass22.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Static_Inst23_Test() { Log.Comment(" Section 10.2 "); Log.Comment(" An instance function member (method, property "); Log.Comment(" accessor, indexer accessor, constructor, or "); Log.Comment(" destructor) operates on a given instance of "); Log.Comment(" the class, and this instance can be accessed as"); Log.Comment(" this."); if (Static_InstTestClass23.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } //Compiled Test Cases class Static_InstTestClass01 { public static int intI = 1; public static int intJ() { return 2; } public static int intK { get { return 3; } } public const int intL = 4; public class MyInner { public int intM = 5; } public static bool testMethod() { if (Static_InstTestClass01.intI != 1) return false; if (Static_InstTestClass01.intJ() != 2) return false; if (Static_InstTestClass01.intK != 3) return false; if (Static_InstTestClass01.intL != 4) return false; if (new Static_InstTestClass01.MyInner().intM != 5) return false; return true; } } class Static_InstTestClass07 { public static int intI = 1; public void increment() { Static_InstTestClass07.intI++; } public static bool testMethod() { if (Static_InstTestClass07.intI != 1) return false; Static_InstTestClass07 test1 = new Static_InstTestClass07(); test1.increment(); if (Static_InstTestClass07.intI != 2) return false; Static_InstTestClass07 test2 = new Static_InstTestClass07(); test2.increment(); if (Static_InstTestClass07.intI != 3) return false; Static_InstTestClass07 test3 = new Static_InstTestClass07(); test3.increment(); if (Static_InstTestClass07.intI != 4) return false; return true; } } class Static_InstTestClass14 { public int intI = 1; public int intJ() { return 2; } public int intK { get { return 3; } } public static bool testMethod() { Static_InstTestClass14 test = new Static_InstTestClass14(); if (test.intI != 1) return false; if (test.intJ() != 2) return false; if (test.intK != 3) return false; return true; } } class Static_InstTestClass18 { public int intI = 1; public void setInt(int intJ) { intI = intJ; } public static bool testMethod() { Static_InstTestClass18 test1 = new Static_InstTestClass18(); Static_InstTestClass18 test2 = new Static_InstTestClass18(); Static_InstTestClass18 test3 = new Static_InstTestClass18(); test1.setInt(2); test2.setInt(3); test3.setInt(4); if (test1.intI != 2) return false; if (test2.intI != 3) return false; if (test3.intI != 4) return false; return true; } } class Static_InstTestClass19 { int intI; public void foo() { intI = 2; } public static bool testMethod() { Static_InstTestClass19 test = new Static_InstTestClass19(); test.foo(); if (test.intI == 2) { return true; } else { return false; } } } class Static_InstTestClass20 { int intI; public int intJ { get { intI = 2; return 3; } } public static bool testMethod() { Static_InstTestClass20 test = new Static_InstTestClass20(); int intK = test.intJ; if (test.intI == 2) { return true; } else { return false; } } } class Static_InstTestClass21 { int intI; public int this[int intJ] { get { intI = 2; return 3; } } public static bool testMethod() { Static_InstTestClass21 test = new Static_InstTestClass21(); int intK = test[1]; if (test.intI == 2) { return true; } else { return false; } } } class Static_InstTestClass22 { int intI; public Static_InstTestClass22() { intI = 2; } public static bool testMethod() { Static_InstTestClass22 test = new Static_InstTestClass22(); if (test.intI == 2) { return true; } else { return false; } } } class Static_InstTestClass23 { int intI; public void foo() { this.intI = 2; } public static bool testMethod() { Static_InstTestClass23 test = new Static_InstTestClass23(); test.foo(); if (test.intI == 2) { return true; } else { return false; } } } } } ================================================ FILE: Zelig/Zelig/Test/RunTime/NETMF/mscorlib/classes/classes3/MembersTests.cs ================================================ //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // Copyright (c) Microsoft Corporation. All rights reserved. //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// using System; using System.Reflection; using Microsoft.Zelig.Test; namespace Microsoft.Zelig.Test { public class MembersTests : TestBase, ITestInterface { [SetUp] public InitializeResult Initialize() { Log.Comment("Adding set up for the tests"); // Add your functionality here. return InitializeResult.ReadyToGo; } [TearDown] public void CleanUp() { Log.Comment("Cleaning up after the tests"); } public override TestResult Run( string[] args ) { TestResult result = TestResult.Pass; string testName = "Members"; result |= Assert.CheckFailed(Members23_Test(), testName, 23); result |= Assert.CheckFailed(Members24_Test(), testName, 24); result |= Assert.CheckFailed(Members25_Test(), testName, 25); result |= Assert.CheckFailed(Members26_Test(), testName, 26); result |= Assert.CheckFailed(Members27_Test(), testName, 27); result |= Assert.CheckFailed(Members28_Test(), testName, 28); testName = "MembersInheritance"; result |= Assert.CheckFailed(MembersInheritance001_Test(), testName, 1); result |= Assert.CheckFailed(MembersInheritance002_Test(), testName, 2); result |= Assert.CheckFailed(MembersInheritance003_Test(), testName, 3); result |= Assert.CheckFailed(MembersInheritance004_Test(), testName, 4); result |= Assert.CheckFailed(MembersInheritance005_Test(), testName, 5); result |= Assert.CheckFailed(MembersInheritance006_Test(), testName, 6); result |= Assert.CheckFailed(MembersInheritance007_Test(), testName, 7); result |= Assert.CheckFailed(MembersInheritance008_Test(), testName, 8); result |= Assert.CheckFailed(MembersInheritance018_Test(), testName, 18); result |= Assert.CheckFailed(MembersInheritance019_Test(), testName, 19); result |= Assert.CheckFailed(MembersInheritance020_Test(), testName, 20); result |= Assert.CheckFailed(MembersInheritance021_Test(), testName, 21); result |= Assert.CheckFailed(MembersInheritance022_Test(), testName, 22); result |= Assert.CheckFailed(MembersInheritance023_Test(), testName, 23); result |= Assert.CheckFailed(MembersInheritance024_Test(), testName, 24); result |= Assert.CheckFailed(MembersInheritance025_Test(), testName, 25); result |= Assert.CheckFailed(MembersInheritance026_Test(), testName, 26); result |= Assert.CheckFailed(MembersInheritance027_Test(), testName, 27); result |= Assert.CheckFailed(MembersInheritance028_Test(), testName, 28); result |= Assert.CheckFailed(MembersInheritance029_Test(), testName, 29); result |= Assert.CheckFailed(MembersInheritance030_Test(), testName, 30); result |= Assert.CheckFailed(MembersInheritance031_Test(), testName, 31); result |= Assert.CheckFailed(MembersInheritance032_Test(), testName, 32); result |= Assert.CheckFailed(MembersInheritance033_Test(), testName, 33); result |= Assert.CheckFailed(MembersInheritance034_Test(), testName, 34); result |= Assert.CheckFailed(MembersInheritance035_Test(), testName, 35); result |= Assert.CheckFailed(MembersInheritance036_Test(), testName, 36); result |= Assert.CheckFailed(MembersInheritance037_Test(), testName, 37); result |= Assert.CheckFailed(MembersInheritance038_Test(), testName, 38); result |= Assert.CheckFailed(MembersInheritance039_Test(), testName, 39); result |= Assert.CheckFailed(MembersInheritance040_Test(), testName, 40); result |= Assert.CheckFailed(MembersInheritance041_Test(), testName, 41); result |= Assert.CheckFailed(MembersInheritance042_Test(), testName, 42); result |= Assert.CheckFailed(MembersInheritance043_Test(), testName, 43); result |= Assert.CheckFailed(MembersInheritance044_Test(), testName, 44); result |= Assert.CheckFailed(MembersInheritance045_Test(), testName, 45); result |= Assert.CheckFailed(MembersInheritance046_Test(), testName, 46); result |= Assert.CheckFailed(MembersInheritance047_Test(), testName, 47); result |= Assert.CheckFailed(MembersInheritance053_Test(), testName, 53); result |= Assert.CheckFailed(MembersInheritance054_Test(), testName, 54); result |= Assert.CheckFailed(MembersInheritance057_Test(), testName, 57); result |= Assert.CheckFailed(MembersInheritance058_Test(), testName, 58); result |= Assert.CheckFailed(MembersInheritance059_Test(), testName, 59); testName = "MembersModifiers"; result |= Assert.CheckFailed(MembersModifiers01_Test(), testName, 1); result |= Assert.CheckFailed(MembersModifiers02_Test(), testName, 2); result |= Assert.CheckFailed(MembersModifiers03_Test(), testName, 3); result |= Assert.CheckFailed(MembersModifiers04_Test(), testName, 4); result |= Assert.CheckFailed(MembersModifiers05_Test(), testName, 5); result |= Assert.CheckFailed(MembersModifiers06_Test(), testName, 6); result |= Assert.CheckFailed(MembersModifiers07_Test(), testName, 7); result |= Assert.CheckFailed(MembersModifiers08_Test(), testName, 8); result |= Assert.CheckFailed(MembersModifiers12_Test(), testName, 12); result |= Assert.CheckFailed(MembersModifiers23_Test(), testName, 23); result |= Assert.CheckFailed(MembersModifiers24_Test(), testName, 24); result |= Assert.CheckFailed(MembersModifiers25_Test(), testName, 25); result |= Assert.CheckFailed(MembersModifiers26_Test(), testName, 26); result |= Assert.CheckFailed(MembersModifiers27_Test(), testName, 27); return result; } //Members Tests //The following tests ported from folder current\test\cases\client\CLR\Conformance\10_classes\Members //023,024,025,026,027,028 //The following tests ported from folder current\test\cases\client\CLR\Conformance\10_classes\Members\Inheritance //001,002,003,004,005,006,007,008,018,019,020,021,022,023,024,025,026,027,028,029,030,031,032,033,034,035,036,037,038,039,040,041,042,043,044,045,046,047,053,054,057,058,059 //The following tests ported from folder current\test\cases\client\CLR\Conformance\10_classes\Members\Modifiers //01,02,03,04,05,06,07,08,12,23,24,25,26,27 //All tests that were not ported did not appear in the Baseline Document [TestMethod] public TestResult Members23_Test() { Log.Comment(" Section 10.2"); Log.Comment(" The inherited members of a class are specifically"); Log.Comment(" not part of the declaration space of a class. Thus, a "); Log.Comment(" derived class is allowed to declare a member with the same "); Log.Comment(" name or signature as an inherited member (which in effect"); Log.Comment(" hides the inherited member)."); if (MembersTestClass023.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Members24_Test() { Log.Comment(" Section 10.2"); Log.Comment(" The inherited members of a class are specifically"); Log.Comment(" not part of the declaration space of a class. Thus, a "); Log.Comment(" derived class is allowed to declare a member with the same "); Log.Comment(" name or signature as an inherited member (which in effect"); Log.Comment(" hides the inherited member)."); if (MembersTestClass024.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Members25_Test() { Log.Comment(" Section 10.2"); Log.Comment(" The inherited members of a class are specifically"); Log.Comment(" not part of the declaration space of a class. Thus, a "); Log.Comment(" derived class is allowed to declare a member with the same "); Log.Comment(" name or signature as an inherited member (which in effect"); Log.Comment(" hides the inherited member)."); if (MembersTestClass025.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Members26_Test() { Log.Comment(" Section 10.2"); Log.Comment(" The inherited members of a class are specifically"); Log.Comment(" not part of the declaration space of a class. Thus, a "); Log.Comment(" derived class is allowed to declare a member with the same "); Log.Comment(" name or signature as an inherited member (which in effect"); Log.Comment(" hides the inherited member)."); if (MembersTestClass026.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Members27_Test() { Log.Comment(" Section 10.2"); Log.Comment(" The inherited members of a class are specifically"); Log.Comment(" not part of the declaration space of a class. Thus, a "); Log.Comment(" derived class is allowed to declare a member with the same "); Log.Comment(" name or signature as an inherited member (which in effect"); Log.Comment(" hides the inherited member)."); if (MembersTestClass027.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Members28_Test() { Log.Comment(" Section 10.2"); Log.Comment(" The inherited members of a class are specifically"); Log.Comment(" not part of the declaration space of a class. Thus, a "); Log.Comment(" derived class is allowed to declare a member with the same "); Log.Comment(" name or signature as an inherited member (which in effect"); Log.Comment(" hides the inherited member)."); if (MembersTestClass028.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } //Test Case Calls [TestMethod] public TestResult MembersInheritance001_Test() { Log.Comment(" Section 10.2"); Log.Comment(" Inheritance is transitive. If C is derived from"); Log.Comment(" B, and B is derived from A, then C inherits the"); Log.Comment(" members declared in B as well as the members"); if (MembersInheritanceTestClass001.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult MembersInheritance002_Test() { Log.Comment(" Section 10.2"); Log.Comment(" Inheritance is transitive. If C is derived from"); Log.Comment(" B, and B is derived from A, then C inherits the"); Log.Comment(" members declared in B as well as the members"); if (MembersInheritanceTestClass002.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult MembersInheritance003_Test() { Log.Comment(" Section 10.2"); Log.Comment(" Inheritance is transitive. If C is derived from"); Log.Comment(" B, and B is derived from A, then C inherits the"); Log.Comment(" members declared in B as well as the members"); if (MembersInheritanceTestClass003.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult MembersInheritance004_Test() { Log.Comment(" Section 10.2"); Log.Comment(" Inheritance is transitive. If C is derived from"); Log.Comment(" B, and B is derived from A, then C inherits the"); Log.Comment(" members declared in B as well as the members"); if (MembersInheritanceTestClass004.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult MembersInheritance005_Test() { Log.Comment(" Section 10.2"); Log.Comment(" Inheritance is transitive. If C is derived from"); Log.Comment(" B, and B is derived from A, then C inherits the"); Log.Comment(" members declared in B as well as the members"); if (MembersInheritanceTestClass005.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult MembersInheritance006_Test() { Log.Comment(" Section 10.2"); Log.Comment(" Inheritance is transitive. If C is derived from"); Log.Comment(" B, and B is derived from A, then C inherits the"); Log.Comment(" members declared in B as well as the members"); if (MembersInheritanceTestClass006.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult MembersInheritance007_Test() { Log.Comment(" Section 10.2"); Log.Comment(" Inheritance is transitive. If C is derived from"); Log.Comment(" B, and B is derived from A, then C inherits the"); Log.Comment(" members declared in B as well as the members"); if (MembersInheritanceTestClass007.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult MembersInheritance008_Test() { Log.Comment(" Section 10.2"); Log.Comment(" Inheritance is transitive. If C is derived from"); Log.Comment(" B, and B is derived from A, then C inherits the"); Log.Comment(" members declared in B as well as the members"); if (MembersInheritanceTestClass008.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult MembersInheritance018_Test() { Log.Comment(" Section 10.2"); Log.Comment(" Constructors and destructors are not inherited, but all"); Log.Comment(" other members are, regardless of their declared accessibility."); Log.Comment(" However, depending on their declared accessibility, inherited"); Log.Comment(" members may not be accessible in the derived class."); if (MembersInheritanceTestClass018.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult MembersInheritance019_Test() { Log.Comment(" Section 10.2"); Log.Comment(" Constructors and destructors are not inherited, but all"); Log.Comment(" other members are, regardless of their declared accessibility."); Log.Comment(" However, depending on their declared accessibility, inherited"); Log.Comment(" members may not be accessible in the derived class."); if (MembersInheritanceTestClass019.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult MembersInheritance020_Test() { Log.Comment(" Section 10.2"); Log.Comment(" Constructors and destructors are not inherited, but all"); Log.Comment(" other members are, regardless of their declared accessibility."); Log.Comment(" However, depending on their declared accessibility, inherited"); Log.Comment(" members may not be accessible in the derived class."); if (MembersInheritanceTestClass020.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult MembersInheritance021_Test() { Log.Comment(" Section 10.2"); Log.Comment(" Constructors and destructors are not inherited, but all"); Log.Comment(" other members are, regardless of their declared accessibility."); Log.Comment(" However, depending on their declared accessibility, inherited"); Log.Comment(" members may not be accessible in the derived class."); if (MembersInheritanceTestClass021.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult MembersInheritance022_Test() { Log.Comment(" Section 10.2"); Log.Comment(" Constructors and destructors are not inherited, but all"); Log.Comment(" other members are, regardless of their declared accessibility."); Log.Comment(" However, depending on their declared accessibility, inherited"); Log.Comment(" members may not be accessible in the derived class."); if (MembersInheritanceTestClass022.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult MembersInheritance023_Test() { Log.Comment(" Section 10.2"); Log.Comment(" Constructors and destructors are not inherited, but all"); Log.Comment(" other members are, regardless of their declared accessibility."); Log.Comment(" However, depending on their declared accessibility, inherited"); Log.Comment(" members may not be accessible in the derived class."); if (MembersInheritanceTestClass023.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult MembersInheritance024_Test() { Log.Comment(" Section 10.2"); Log.Comment(" Constructors and destructors are not inherited, but all"); Log.Comment(" other members are, regardless of their declared accessibility."); Log.Comment(" However, depending on their declared accessibility, inherited"); Log.Comment(" members may not be accessible in the derived class."); if (MembersInheritanceTestClass024.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult MembersInheritance025_Test() { Log.Comment(" Section 10.2"); Log.Comment(" Constructors and destructors are not inherited, but all"); Log.Comment(" other members are, regardless of their declared accessibility."); Log.Comment(" However, depending on their declared accessibility, inherited"); Log.Comment(" members may not be accessible in the derived class."); if (MembersInheritanceTestClass025.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult MembersInheritance026_Test() { Log.Comment(" Section 10.2"); Log.Comment(" An instance of a class contains a copy of all instance fields"); Log.Comment(" declared in the class and its base classes, and an implicit"); Log.Comment(" conversion exists from a derived class type to any of its base "); Log.Comment(" class types. Thus, a reference to a derived class instance"); Log.Comment(" can be treated as a reference to a base class instance."); if (MembersInheritanceTestClass026.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult MembersInheritance027_Test() { Log.Comment(" Section 10.2"); Log.Comment(" An instance of a class contains a copy of all instance fields"); Log.Comment(" declared in the class and its base classes, and an implicit"); Log.Comment(" conversion exists from a derived class type to any of its base "); Log.Comment(" class types. Thus, a reference to a derived class instance"); Log.Comment(" can be treated as a reference to a base class instance."); if (MembersInheritanceTestClass027.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult MembersInheritance028_Test() { Log.Comment(" Section 10.2"); Log.Comment(" A class can declare virtual methods, properties,"); Log.Comment(" and indexers, and derived classes can override the "); Log.Comment(" implementation of these function members. This enables"); Log.Comment(" classes to exhibit polymorphic behavior wherein the "); Log.Comment(" actions performed by a function member invocation"); Log.Comment(" varies depending on the run-time type of the instance"); Log.Comment(" through which the member is invoked."); if (MembersInheritanceTestClass028.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult MembersInheritance029_Test() { Log.Comment(" Section 10.2"); Log.Comment(" A class can declare virtual methods, properties,"); Log.Comment(" and indexers, and derived classes can override the "); Log.Comment(" implementation of these function members. This enables"); Log.Comment(" classes to exhibit polymorphic behavior wherein the "); Log.Comment(" actions performed by a function member invocation"); Log.Comment(" varies depending on the run-time type of the instance"); Log.Comment(" through which the member is invoked."); if (MembersInheritanceTestClass029.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult MembersInheritance030_Test() { Log.Comment(" Section 10.2"); Log.Comment(" A class can declare virtual methods, properties,"); Log.Comment(" and indexers, and derived classes can override the "); Log.Comment(" implementation of these function members. This enables"); Log.Comment(" classes to exhibit polymorphic behavior wherein the "); Log.Comment(" actions performed by a function member invocation"); Log.Comment(" varies depending on the run-time type of the instance"); Log.Comment(" through which the member is invoked."); if (MembersInheritanceTestClass030.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult MembersInheritance031_Test() { Log.Comment(" Section 10.2"); Log.Comment(" A class can declare virtual methods, properties,"); Log.Comment(" and indexers, and derived classes can override the "); Log.Comment(" implementation of these function members. This enables"); Log.Comment(" classes to exhibit polymorphic behavior wherein the "); Log.Comment(" actions performed by a function member invocation"); Log.Comment(" varies depending on the run-time type of the instance"); Log.Comment(" through which the member is invoked."); if (MembersInheritanceTestClass031.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult MembersInheritance032_Test() { Log.Comment(" Section 10.2"); Log.Comment(" A class can declare virtual methods, properties,"); Log.Comment(" and indexers, and derived classes can override the "); Log.Comment(" implementation of these function members. This enables"); Log.Comment(" classes to exhibit polymorphic behavior wherein the "); Log.Comment(" actions performed by a function member invocation"); Log.Comment(" varies depending on the run-time type of the instance"); Log.Comment(" through which the member is invoked."); if (MembersInheritanceTestClass032.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult MembersInheritance033_Test() { Log.Comment(" Section 10.2"); Log.Comment(" A class can declare virtual methods, properties,"); Log.Comment(" and indexers, and derived classes can override the "); Log.Comment(" implementation of these function members. This enables"); Log.Comment(" classes to exhibit polymorphic behavior wherein the "); Log.Comment(" actions performed by a function member invocation"); Log.Comment(" varies depending on the run-time type of the instance"); Log.Comment(" through which the member is invoked."); if (MembersInheritanceTestClass033.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult MembersInheritance034_Test() { Log.Comment(" Section 10.2"); Log.Comment(" A class can declare virtual methods, properties,"); Log.Comment(" and indexers, and derived classes can override the "); Log.Comment(" implementation of these function members. This enables"); Log.Comment(" classes to exhibit polymorphic behavior wherein the "); Log.Comment(" actions performed by a function member invocation"); Log.Comment(" varies depending on the run-time type of the instance"); Log.Comment(" through which the member is invoked."); if (MembersInheritanceTestClass034.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult MembersInheritance035_Test() { Log.Comment(" Section 10.2"); Log.Comment(" A class can declare virtual methods, properties,"); Log.Comment(" and indexers, and derived classes can override the "); Log.Comment(" implementation of these function members. This enables"); Log.Comment(" classes to exhibit polymorphic behavior wherein the "); Log.Comment(" actions performed by a function member invocation"); Log.Comment(" varies depending on the run-time type of the instance"); Log.Comment(" through which the member is invoked."); if (MembersInheritanceTestClass035.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult MembersInheritance036_Test() { Log.Comment(" Section 10.2"); Log.Comment(" A class can declare virtual methods, properties,"); Log.Comment(" and indexers, and derived classes can override the "); Log.Comment(" implementation of these function members. This enables"); Log.Comment(" classes to exhibit polymorphic behavior wherein the "); Log.Comment(" actions performed by a function member invocation"); Log.Comment(" varies depending on the run-time type of the instance"); Log.Comment(" through which the member is invoked."); if (MembersInheritanceTestClass036.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult MembersInheritance037_Test() { Log.Comment(" Section 10.2"); Log.Comment(" A class-member-declaration is permitted to declare"); Log.Comment(" a member with the same name or signature as an "); Log.Comment(" inherited member. When this occurs, the derived"); Log.Comment(" class member is said to hide the base class member."); if (MembersInheritanceTestClass037.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult MembersInheritance038_Test() { Log.Comment(" Section 10.2"); Log.Comment(" A class-member-declaration is permitted to declare"); Log.Comment(" a member with the same name or signature as an "); Log.Comment(" inherited member. When this occurs, the derived"); Log.Comment(" class member is said to hide the base class member."); if (MembersInheritanceTestClass038.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult MembersInheritance039_Test() { Log.Comment(" Section 10.2"); Log.Comment(" A class-member-declaration is permitted to declare"); Log.Comment(" a member with the same name or signature as an "); Log.Comment(" inherited member. When this occurs, the derived"); Log.Comment(" class member is said to hide the base class member."); if (MembersInheritanceTestClass039.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult MembersInheritance040_Test() { Log.Comment(" Section 10.2"); Log.Comment(" A class-member-declaration is permitted to declare"); Log.Comment(" a member with the same name or signature as an "); Log.Comment(" inherited member. When this occurs, the derived"); Log.Comment(" class member is said to hide the base class member."); if (MembersInheritanceTestClass040.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult MembersInheritance041_Test() { Log.Comment(" Section 10.2"); Log.Comment(" If a new modifier is included in a declaration"); Log.Comment(" that doesn't hide an inherited member, a warning "); Log.Comment(" is issued to that effect."); if (MembersInheritanceTestClass041.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult MembersInheritance042_Test() { Log.Comment(" Section 10.2"); Log.Comment(" If a new modifier is included in a declaration"); Log.Comment(" that doesn't hide an inherited member, a warning "); Log.Comment(" is issued to that effect."); if (MembersInheritanceTestClass042.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult MembersInheritance043_Test() { Log.Comment(" Section 10.2"); Log.Comment(" If a new modifier is included in a declaration"); Log.Comment(" that doesn't hide an inherited member, a warning "); Log.Comment(" is issued to that effect."); if (MembersInheritanceTestClass043.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult MembersInheritance044_Test() { Log.Comment(" Section 10.2"); Log.Comment(" If a new modifier is included in a declaration"); Log.Comment(" that doesn't hide an inherited member, a warning "); Log.Comment(" is issued to that effect."); if (MembersInheritanceTestClass044.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult MembersInheritance045_Test() { Log.Comment(" Section 10.2"); Log.Comment(" If a new modifier is included in a declaration"); Log.Comment(" that doesn't hide an inherited member, a warning "); Log.Comment(" is issued to that effect."); if (MembersInheritanceTestClass045.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult MembersInheritance046_Test() { Log.Comment(" Section 10.2"); Log.Comment(" If a new modifier is included in a declaration"); Log.Comment(" that doesn't hide an inherited member, a warning "); Log.Comment(" is issued to that effect."); if (MembersInheritanceTestClass046.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult MembersInheritance047_Test() { Log.Comment(" Section 10.2"); Log.Comment(" If a new modifier is included in a declaration"); Log.Comment(" that doesn't hide an inherited member, a warning "); Log.Comment(" is issued to that effect."); if (MembersInheritanceTestClass047.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult MembersInheritance053_Test() { Log.Comment(" Section 10.2"); Log.Comment(" If a new modifier is included in a declaration"); Log.Comment(" that doesn't hide an inherited member, a warning "); Log.Comment(" is issued to that effect."); if (MembersInheritanceTestClass053.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult MembersInheritance054_Test() { Log.Comment("Testing that protected members can be passed to a grandchild class"); if (MembersInheritanceTestClass054.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult MembersInheritance057_Test() { Log.Comment("Testing that you can inherit from a member class"); if (MembersInheritanceTestClass057.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult MembersInheritance058_Test() { Log.Comment("Testing that you can inherit from a class declared later in the file"); if (MembersInheritanceTestClass058.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult MembersInheritance059_Test() { Log.Comment("Testing that an inner class inherit from another class"); if (MembersInheritanceTestClass059.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } //Test Case Calls [TestMethod] public TestResult MembersModifiers01_Test() { Log.Comment(" Section 10.2"); Log.Comment(" A class-member-declaration may include one of the "); Log.Comment(" four access modifiers: public, protected, internal,"); Log.Comment(" or private. It is an error to specify more than one"); Log.Comment(" access modifier. When a class-member-declaration "); Log.Comment(" does not include an access modifier, the declaration"); Log.Comment(" defaults to private."); if (MembersModifiersTestClass01.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult MembersModifiers02_Test() { Log.Comment(" Section 10.2"); Log.Comment(" A class-member-declaration may include one of the "); Log.Comment(" four access modifiers: public, protected, internal,"); Log.Comment(" or private. It is an error to specify more than one"); Log.Comment(" access modifier. When a class-member-declaration "); Log.Comment(" does not include an access modifier, the declaration"); Log.Comment(" defaults to private."); if (MembersModifiersTestClass02.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult MembersModifiers03_Test() { Log.Comment(" Section 10.2"); Log.Comment(" A class-member-declaration may include one of the "); Log.Comment(" four access modifiers: public, protected, internal,"); Log.Comment(" or private. It is an error to specify more than one"); Log.Comment(" access modifier. When a class-member-declaration "); Log.Comment(" does not include an access modifier, the declaration"); Log.Comment(" defaults to private."); if (MembersModifiersTestClass03.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult MembersModifiers04_Test() { Log.Comment(" Section 10.2"); Log.Comment(" A class-member-declaration may include one of the "); Log.Comment(" four access modifiers: public, protected, internal,"); Log.Comment(" or private. It is an error to specify more than one"); Log.Comment(" access modifier. When a class-member-declaration "); Log.Comment(" does not include an access modifier, the declaration"); Log.Comment(" defaults to private."); if (MembersModifiersTestClass04.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult MembersModifiers05_Test() { Log.Comment(" Section 10.2"); Log.Comment(" A class-member-declaration may include one of the "); Log.Comment(" four access modifiers: public, protected, internal,"); Log.Comment(" or private. It is an error to specify more than one"); Log.Comment(" access modifier. When a class-member-declaration "); Log.Comment(" does not include an access modifier, the declaration"); Log.Comment(" defaults to private."); if (MembersModifiersTestClass05.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult MembersModifiers06_Test() { Log.Comment(" Section 10.2"); Log.Comment(" A class-member-declaration may include one of the "); Log.Comment(" four access modifiers: public, protected, internal,"); Log.Comment(" or private. It is an error to specify more than one"); Log.Comment(" access modifier. When a class-member-declaration "); Log.Comment(" does not include an access modifier, the declaration"); Log.Comment(" defaults to private."); if (MembersModifiersTestClass06.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult MembersModifiers07_Test() { Log.Comment(" Section 10.2"); Log.Comment(" A class-member-declaration may include one of the "); Log.Comment(" four access modifiers: public, protected, internal,"); Log.Comment(" or private. It is an error to specify more than one"); Log.Comment(" access modifier. When a class-member-declaration "); Log.Comment(" does not include an access modifier, the declaration"); Log.Comment(" defaults to private."); if (MembersModifiersTestClass07.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult MembersModifiers08_Test() { Log.Comment(" Section 10.2"); Log.Comment(" A class-member-declaration may include one of the "); Log.Comment(" four access modifiers: public, protected, internal,"); Log.Comment(" or private. It is an error to specify more than one"); Log.Comment(" access modifier. When a class-member-declaration "); Log.Comment(" does not include an access modifier, the declaration"); Log.Comment(" defaults to private."); if (MembersModifiersTestClass08.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult MembersModifiers12_Test() { Log.Comment(" Section 10.2"); Log.Comment(" A class-member-declaration may include one of the "); Log.Comment(" four access modifiers: public, protected, internal,"); Log.Comment(" or private. It is an error to specify more than one"); Log.Comment(" access modifier. When a class-member-declaration "); Log.Comment(" does not include an access modifier, the declaration"); Log.Comment(" defaults to private."); if (MembersModifiersTestClass12.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult MembersModifiers23_Test() { if (MembersModifiersTestClass23.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult MembersModifiers24_Test() { if (MembersModifiersTestClass24.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult MembersModifiers25_Test() { if (MembersModifiersTestClass25.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult MembersModifiers26_Test() { if (MembersModifiersTestClass26.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult MembersModifiers27_Test() { if (MembersModifiersTestClass27.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } //Compiled Test Cases class MembersTestClass_Base023 { public const int intI = 1; } class MembersTestClass023 : MembersTestClass_Base023 { public const int intI = 2; public static bool testMethod() { if (intI == 2) { return true; } else { return false; } } } class MembersTestClass_Base024 { public int intI = 1; } class MembersTestClass024 : MembersTestClass_Base024 { public int intI = 2; public static bool testMethod() { MembersTestClass024 test = new MembersTestClass024(); if (test.intI == 2) { return true; } else { return false; } } } class MembersTestClass_Base025 { public int intI { get { return 1; } } } class MembersTestClass025 : MembersTestClass_Base025 { public int intI { get { return 2; } } public static bool testMethod() { MembersTestClass025 test = new MembersTestClass025(); if (test.intI == 2) { return true; } else { return false; } } } class MembersTestClass_Base026 { public class MyInner { public static int intI = 1; } } class MembersTestClass026 : MembersTestClass_Base026 { public class MyInner { public static int intI = 2; } public static bool testMethod() { if (MyInner.intI == 2) { return true; } else { return false; } } } class MembersTestClass_Base027 { public int intI() { return 1; } } class MembersTestClass027 : MembersTestClass_Base027 { public int intI() { return 2; } public static bool testMethod() { MembersTestClass027 test = new MembersTestClass027(); if (test.intI() == 2) { return true; } else { return false; } } } class MembersTestClass_Base028 { public int this[int I] { get { return 1; } } } class MembersTestClass028 : MembersTestClass_Base028 { public int this[int I] { get { return 2; } } public static bool testMethod() { MembersTestClass028 test = new MembersTestClass028(); if (test[9] == 2) { return true; } else { return false; } } } //Compiled Test Cases class MembersInheritanceTestClass001_SubA { } class MembersInheritanceTestClass001_SubB : MembersInheritanceTestClass001_SubA { public int intI = 1; protected String strS = "Class B"; protected int intJ() {return 2;} public static int intK = 3; } class MembersInheritanceTestClass001 : MembersInheritanceTestClass001_SubB { public static bool testMethod() { MembersInheritanceTestClass001 test = new MembersInheritanceTestClass001(); if ((test.intI ==1) && (test.intJ() == 2) && (intK == 3) && (test.strS.Equals("Class B"))) { return true; } else { return false; } } } class MembersInheritanceTestClass002_SubA { public int intI = 1; protected int intJ() {return 2;} public static int intK = 3; protected String strS = "Class A"; } class MembersInheritanceTestClass002_SubB : MembersInheritanceTestClass002_SubA { } class MembersInheritanceTestClass002 : MembersInheritanceTestClass002_SubB { public static bool testMethod() { MembersInheritanceTestClass002 test = new MembersInheritanceTestClass002(); if ((test.intI ==1) && (test.intJ() == 2) && (intK == 3) && (test.strS.Equals("Class A"))) { return true; } else { return false; } } } class MembersInheritanceTestClass003_SubA { } class MembersInheritanceTestClass003_SubB : MembersInheritanceTestClass003_SubA { protected struct MyStruct { public int intI; public MyStruct(int intJ) { intI = intJ; } } } class MembersInheritanceTestClass003 : MembersInheritanceTestClass003_SubB { public static bool testMethod() { MyStruct test = new MyStruct(3); if (test.intI == 3) { return true; } else { return false; } } } class MembersInheritanceTestClass004_SubA { protected struct MyStruct { public int intI; public MyStruct(int intJ) { intI = intJ; } } } class MembersInheritanceTestClass004_SubB : MembersInheritanceTestClass004_SubA { } class MembersInheritanceTestClass004 : MembersInheritanceTestClass004_SubB { public static bool testMethod() { MyStruct test = new MyStruct(3); if (test.intI == 3) { return true; } else { return false; } } } class MembersInheritanceTestClass005_SubA { } class MembersInheritanceTestClass005_SubB : MembersInheritanceTestClass005_SubA { protected enum AA {zero, one} } class MembersInheritanceTestClass005 : MembersInheritanceTestClass005_SubB { public static bool testMethod() { AA MyEnum = AA.one; if ((int)MyEnum == 1) { return true; } else { return false; } } } class MembersInheritanceTestClass006_SubA { protected enum AA {zero, one} } class MembersInheritanceTestClass006_SubB : MembersInheritanceTestClass006_SubA { } class MembersInheritanceTestClass006 : MembersInheritanceTestClass006_SubB { public static bool testMethod() { AA MyEnum = AA.one; if ((int)MyEnum == 1) { return true; } else { return false; } } } class MembersInheritanceTestClass007_SubA { } class MembersInheritanceTestClass007_SubB : MembersInheritanceTestClass007_SubA { protected class MembersInheritanceTestClass007 { public int intI; public MembersInheritanceTestClass007(int intJ) { intI = intJ; } } } class MembersInheritanceTestClass007 : MembersInheritanceTestClass007_SubB { public static bool testMethod() { MembersInheritanceTestClass007 test = new MembersInheritanceTestClass007(3); if (test.intI == 3) { return true; } else { return false; } } } class MembersInheritanceTestClass008_SubA { protected class MembersInheritanceTestClass008 { public int intI; public MembersInheritanceTestClass008(int intJ) { intI = intJ; } } } class MembersInheritanceTestClass008_SubB : MembersInheritanceTestClass008_SubA { } class MembersInheritanceTestClass008 : MembersInheritanceTestClass008_SubB { public static bool testMethod() { MembersInheritanceTestClass008 test = new MembersInheritanceTestClass008(3); if (test.intI == 3) { return true; } else { return false; } } } class MembersInheritanceTestClass018_Base { public int intI = 1; protected String strS = "MembersInheritanceTestClass018_Base"; protected int intJ() {return 2;} public static int intK = 3; } class MembersInheritanceTestClass018 : MembersInheritanceTestClass018_Base { public static bool testMethod() { MembersInheritanceTestClass018 test = new MembersInheritanceTestClass018(); if ((test.intI ==1) && (test.intJ() == 2) && (intK == 3) && (test.strS.Equals("MembersInheritanceTestClass018_Base"))) { return true; } else { return false; } } } class MembersInheritanceTestClass019_Base { public int intI = 1; } class MembersInheritanceTestClass019 : MembersInheritanceTestClass019_Base { public int intI = 2; public static bool testMethod() { MembersInheritanceTestClass019 test = new MembersInheritanceTestClass019(); if (test.intI == 2) { return true; } else { return false; } } } class MembersInheritanceTestClass020_Base { protected int intI() {return 2;} } class MembersInheritanceTestClass020 : MembersInheritanceTestClass020_Base { new protected int intI() {return 3;} public static bool testMethod() { MembersInheritanceTestClass020 test = new MembersInheritanceTestClass020(); if (test.intI() == 3) { return true; } else { return false; } } } class MembersInheritanceTestClass021_Base { public static int intI = 1; } class MembersInheritanceTestClass021 : MembersInheritanceTestClass021_Base { public static int intI = 2; public static bool testMethod() { MembersInheritanceTestClass021 test = new MembersInheritanceTestClass021(); if (intI == 2) { return true; } else { return false; } } } class MembersInheritanceTestClass022_Base { public String strS = "MembersInheritanceTestClass022_Base"; } class MembersInheritanceTestClass022 : MembersInheritanceTestClass022_Base { public static String strS = "MembersInheritanceTestClass022"; public static bool testMethod() { MembersInheritanceTestClass022 test = new MembersInheritanceTestClass022(); if (strS.Equals("MembersInheritanceTestClass022")) { return true; } else { return false; } } } class MembersInheritanceTestClass023_Base { public struct MyStruct { public static int intI = 1; } } class MembersInheritanceTestClass023 : MembersInheritanceTestClass023_Base { new struct MyStruct { public static int intI = 2; } public static bool testMethod() { if (MyStruct.intI == 2) { return true; } else { return false; } } } class MembersInheritanceTestClass024_Base { public enum AA {one, two} } class MembersInheritanceTestClass024 : MembersInheritanceTestClass024_Base { public enum AA {zero, one} public static bool testMethod() { AA MyEnum = AA.one; if ((int)MyEnum == 1) { return true; } else { return false; } } } class MembersInheritanceTestClass025_Base { public class MyInner { public static int intI = 1; } } class MembersInheritanceTestClass025 : MembersInheritanceTestClass025_Base { new class MyInner { public static int intI = 2; } public static bool testMethod() { if (MyInner.intI == 2) { return true; } else { return false; } } } class MembersInheritanceTestClass026_Base { public int intI = 1; } class MembersInheritanceTestClass026 : MembersInheritanceTestClass026_Base { public static bool testMethod() { MembersInheritanceTestClass026_Base test = new MembersInheritanceTestClass026(); if (test.intI == 1) { return true; } else { return false; } } } class MembersInheritanceTestClass027_Base1 { public int intI = 1; } class MembersInheritanceTestClass027_Base2 : MembersInheritanceTestClass027_Base1 { } class MembersInheritanceTestClass027 : MembersInheritanceTestClass027_Base2 { public static bool testMethod() { MembersInheritanceTestClass027_Base1 test = new MembersInheritanceTestClass027(); if (test.intI == 1) { return true; } else { return false; } } } class MembersInheritanceTestClass028_Base { public virtual int retInt() { return 1; } } class MembersInheritanceTestClass028 : MembersInheritanceTestClass028_Base { public override int retInt() { return 2; } public static bool testMethod() { MembersInheritanceTestClass028_Base test = new MembersInheritanceTestClass028(); if (test.retInt() == 2) { return true; } else { return false; } } } class MembersInheritanceTestClass029_Base { public int intI = 0; public virtual int retInt { get { return -2; } set { intI = -1; } } } class MembersInheritanceTestClass029 : MembersInheritanceTestClass029_Base { public override int retInt { get { return intI; } set { intI = value; } } public static bool testMethod() { MembersInheritanceTestClass029_Base test = new MembersInheritanceTestClass029(); test.retInt = 2; if (test.retInt == 2) { return true; } else { return false; } } } class MembersInheritanceTestClass030_Base { public int intI = 0; public virtual int retInt { get { return -2; } set { intI = -1; } } } class MembersInheritanceTestClass030 : MembersInheritanceTestClass030_Base { public override int retInt { set { intI = value; } } public static bool testMethod() { MembersInheritanceTestClass030_Base test = new MembersInheritanceTestClass030(); test.retInt = 2; if ((test.intI == 2) && (test.retInt == -2)) { return true; } else { return false; } } } class MembersInheritanceTestClass031_Base { public int intI = 0; public virtual int retInt { get { return -2; } set { intI = -1; } } } class MembersInheritanceTestClass031 : MembersInheritanceTestClass031_Base { public override int retInt { get { return intI; } } public static bool testMethod() { MembersInheritanceTestClass031_Base test = new MembersInheritanceTestClass031(); test.retInt = 2; if ((test.intI == -1) && (test.retInt == -1)) { return true; } else { return false; } } } class MembersInheritanceTestClass032_Base { public int intI = 0; public virtual int retInt { get { return -2; } set { intI = -1; } } } class MembersInheritanceTestClass032 : MembersInheritanceTestClass032_Base { public new int retInt { get { return intI; } set { intI = value; } } public static bool testMethod() { MembersInheritanceTestClass032_Base test = new MembersInheritanceTestClass032(); test.retInt = 2; if ((test.intI == -1) && (test.retInt == -2)) { return true; } else { return false; } } } class MembersInheritanceTestClass033_Base { public int intI = 0; public virtual int this[int i] { get { return -2; } set { intI = -1; } } } class MembersInheritanceTestClass033 : MembersInheritanceTestClass033_Base { public override int this[int i] { get { return intI; } set { intI = i + value; } } public static bool testMethod() { MembersInheritanceTestClass033_Base test = new MembersInheritanceTestClass033(); test[2] = 2; if (test[2] == 4) { return true; } else { return false; } } } class MembersInheritanceTestClass034_Base { public int intI = 0; public virtual int this[int i] { get { return -2; } set { intI = -1; } } } class MembersInheritanceTestClass034 : MembersInheritanceTestClass034_Base { public override int this[int i] { set { intI = i + value; } } public static bool testMethod() { MembersInheritanceTestClass034_Base test = new MembersInheritanceTestClass034(); test[2] = 2; if ((test[2] == -2)&&(test.intI == 4)) { return true; } else { return false; } } } class MembersInheritanceTestClass035_Base { public int intI = 0; public virtual int this[int i] { get { return -2; } set { intI = -1; } } } class MembersInheritanceTestClass035 : MembersInheritanceTestClass035_Base { public override int this[int i] { get { return intI; } } public static bool testMethod() { MembersInheritanceTestClass035_Base test = new MembersInheritanceTestClass035(); test[2] = 2; if ((test[2] == -1)&&(test.intI == -1)) { return true; } else { return false; } } } class MembersInheritanceTestClass036_Base { public int intI = 0; public virtual int this[int i] { get { return -2; } set { intI = -1; } } } class MembersInheritanceTestClass036 : MembersInheritanceTestClass036_Base { public new int this[int i] { get { return intI; } set { intI = i + value; } } public static bool testMethod() { MembersInheritanceTestClass036_Base test = new MembersInheritanceTestClass036(); test[2] = 2; if ((test[2] == -2)&&(test.intI == -1)) { return true; } else { return false; } } } class MembersInheritanceTestClass037_Base { public int intI = 1; public String strS = "MembersInheritanceTestClass037_Base"; public int intJ() {return 2;} public static int intK = 3; } class MembersInheritanceTestClass037 : MembersInheritanceTestClass037_Base { public int intI = 4; public String strS = "MembersInheritanceTestClass037"; public int intJ() {return 5;} public static int intK = 6; public static bool testMethod() { MembersInheritanceTestClass037 testc = new MembersInheritanceTestClass037(); MembersInheritanceTestClass037_Base testb = (MembersInheritanceTestClass037_Base) testc; if (testb.intI != 1) return false; if (testb.strS.Equals("MembersInheritanceTestClass037_Base") != true) return false; if (testb.intJ() != 2) return false; if (MembersInheritanceTestClass037_Base.intK != 3) return false; if (testc.intI != 4) return false; if (testc.strS.Equals("MembersInheritanceTestClass037") != true) return false; if (testc.intJ() != 5) return false; if (MembersInheritanceTestClass037.intK != 6) return false; return true; } } class MembersInheritanceTestClass038_Base { public struct MyStruct { public int retInt() { return 1; } } } class MembersInheritanceTestClass038 : MembersInheritanceTestClass038_Base { public struct MyStruct { public int retInt() { return 2; } } public static bool testMethod() { MyStruct test = new MyStruct(); if (test.retInt() == 2) { return true; } else { return false; } } } class MembersInheritanceTestClass039_Base { public enum MyEnum {zero, one} } class MembersInheritanceTestClass039 : MembersInheritanceTestClass039_Base { public enum MyEnum {one, two} public static bool testMethod() { MyEnum test = MyEnum.one; if ((int)test == 0) { return true; } else { return false; } } } class MembersInheritanceTestClass040_Base { public class MyInner { public int retInt() { return 1; } } } class MembersInheritanceTestClass040 : MembersInheritanceTestClass040_Base { public class MyInner { public int retInt() { return 2; } } public static bool testMethod() { MyInner test = new MyInner(); if (test.retInt() == 2) { return true; } else { return false; } } } class MembersInheritanceTestClass041_Base {} class MembersInheritanceTestClass041 : MembersInheritanceTestClass041_Base { public int intI = 1; public static bool testMethod() { MembersInheritanceTestClass041 test = new MembersInheritanceTestClass041(); if (test.intI == 1) { return true; } else { return false; } } } class MembersInheritanceTestClass042_Base {} class MembersInheritanceTestClass042 : MembersInheritanceTestClass042_Base { public String strS = "MembersInheritanceTestClass042"; public static bool testMethod() { MembersInheritanceTestClass042 test = new MembersInheritanceTestClass042(); if (test.strS.Equals("MembersInheritanceTestClass042")) { return true; } else { return false; } } } class MembersInheritanceTestClass043_Base {} class MembersInheritanceTestClass043 : MembersInheritanceTestClass043_Base { public int intJ() {return 2;} public static bool testMethod() { MembersInheritanceTestClass043 test = new MembersInheritanceTestClass043(); if (test.intJ() == 2) { return true; } else { return false; } } } class MembersInheritanceTestClass044_Base {} class MembersInheritanceTestClass044 : MembersInheritanceTestClass044_Base { public static int intK = 3; public static bool testMethod() { if (MembersInheritanceTestClass044.intK == 3) { return true; } else { return false; } } } class MembersInheritanceTestClass045_Base {} class MembersInheritanceTestClass045 : MembersInheritanceTestClass045_Base { public struct MyStruct { public int intRet() {return 1;} } public static bool testMethod() { MyStruct test = new MyStruct(); if (test.intRet() == 1) { return true; } else { return false; } } } class MembersInheritanceTestClass046_Base {} class MembersInheritanceTestClass046 : MembersInheritanceTestClass046_Base { enum MyEnum {one, two} public static bool testMethod() { MyEnum test = MyEnum.one; if ((int)test == 0) { return true; } else { return false; } } } class MembersInheritanceTestClass047_Base {} class MembersInheritanceTestClass047 : MembersInheritanceTestClass047_Base { public class MyInner { public int intRet() {return 1;} } public static bool testMethod() { MyInner test = new MyInner(); if (test.intRet() == 1) { return true; } else { return false; } } } public class MembersInheritanceTestClass053_Base { protected int intI = 2; protected int MyMeth() { return 4; } int intJ; protected int PropInt { get { return intJ; } set { intJ = value; } } } public class MembersInheritanceTestClass053_Derived : MembersInheritanceTestClass053_Base { } class MembersInheritanceTestClass053 : MembersInheritanceTestClass053_Derived { public int Test() { PropInt = 3; if ((intI == 2) && (PropInt == 3) && (MyMeth() == 4)) { return 0; } else { return 1; } } public static bool testMethod() { MembersInheritanceTestClass053 mc = new MembersInheritanceTestClass053(); return (mc.Test() == 0); } } public class MembersInheritanceTestClass054_Base { protected int intI = 2; protected int MyMeth() { return 4; } int intJ; protected int PropInt { get { return intJ; } set { intJ = value; } } } public class MembersInheritanceTestClass054_Derived : MembersInheritanceTestClass054_Base { } class MembersInheritanceTestClass054 : MembersInheritanceTestClass054_Derived { public static bool testMethod() { MembersInheritanceTestClass054 mc = new MembersInheritanceTestClass054(); mc.PropInt = 3; if ((mc.intI == 2) && (mc.PropInt == 3) && (mc.MyMeth() == 4)) { return true; } else { return false; } } } class MembersInheritanceTestClass057 : MembersInheritanceTestClass057_SubB.N { public static bool testMethod() { MembersInheritanceTestClass057 MC = new MembersInheritanceTestClass057(); if (MC.intI == 2) { return true; } else { return false; } } } class MembersInheritanceTestClass057_SubB { internal class N { internal int intI = 2; } } class MembersInheritanceTestClass058 : MembersInheritanceTestClass058_SubB { public static bool testMethod() { MembersInheritanceTestClass058 MC = new MembersInheritanceTestClass058(); if (MC.intI == 2) { return true; } else { return false; } } } class MembersInheritanceTestClass058_SubB { public int intI = 2; } public class MembersInheritanceTestClass059 { public int intI = 2; public class MyInner : MembersInheritanceTestClass059 {} public static bool testMethod() { MyInner MI = new MyInner(); if (MI.intI == 2) { return true; } else { return false; } } } class MembersModifiersTestClass01 { //public public int intI = 1; public String strS = "MembersModifiersTestClass01"; public int intJ() { return 2; } public static int intK = 3; public static bool testMethod() { MembersModifiersTestClass01 test = new MembersModifiersTestClass01(); if ((test.intI == 1) && (test.intJ() == 2) && (intK == 3) && (test.strS.Equals("MembersModifiersTestClass01"))) { return true; } else { return false; } } } class MembersModifiersTestClass02 { //protected protected int intI = 1; protected String strS = "MembersModifiersTestClass02"; protected int intJ() {return 2;} protected static int intK = 3; public static bool testMethod() { MembersModifiersTestClass02 test = new MembersModifiersTestClass02(); if ((test.intI ==1) && (test.intJ() == 2) && (intK == 3) && (test.strS.Equals("MembersModifiersTestClass02"))) { return true; } else { return false; } } } class MembersModifiersTestClass03 { //internal internal int intI = 1; internal String strS = "MembersModifiersTestClass03"; internal int intJ() {return 2;} internal static int intK = 3; public static bool testMethod() { MembersModifiersTestClass03 test = new MembersModifiersTestClass03(); if ((test.intI ==1) && (test.intJ() == 2) && (intK == 3) && (test.strS.Equals("MembersModifiersTestClass03"))) { return true; } else { return false; } } } class MembersModifiersTestClass04 { //private private int intI = 1; private String strS = "MembersModifiersTestClass04"; private int intJ() {return 2;} private static int intK = 3; public static bool testMethod() { MembersModifiersTestClass04 test = new MembersModifiersTestClass04(); if ((test.intI ==1) && (test.intJ() == 2) && (intK == 3) && (test.strS.Equals("MembersModifiersTestClass04"))) { return true; } else { return false; } } } class MembersModifiersTestClass05 { //public public struct MyStruct { public static int intI = 1; } public enum AA {zero, one} public class MyInner { public static int intI = 2; } public static bool testMethod() { AA MyEnum = AA.zero; if ((MyStruct.intI == 1) && (MyEnum == AA.zero) && (MyInner.intI ==2)) { return true; } else { return false; } } } class MembersModifiersTestClass06 { //protected protected struct MyStruct { public static int intI = 1; } protected enum AA {zero, one} protected class MyInner { public static int intI = 2; } public static bool testMethod() { AA MyEnum = AA.zero; if ((MyStruct.intI == 1) && (MyEnum == AA.zero) && (MyInner.intI ==2)) { return true; } else { return false; } } } class MembersModifiersTestClass07 { //internal internal struct MyStruct { public static int intI = 1; } internal enum AA {zero, one} internal class MyInner { public static int intI = 2; } public static bool testMethod() { AA MyEnum = AA.zero; if ((MyStruct.intI == 1) && (MyEnum == AA.zero) && (MyInner.intI ==2)) { return true; } else { return false; } } } class MembersModifiersTestClass08 { //private private struct MyStruct { public static int intI = 1; } private enum AA {zero, one} private class MyInner { public static int intI = 2; } public static bool testMethod() { AA MyEnum = AA.zero; if ((MyStruct.intI == 1) && (MyEnum == AA.zero) && (MyInner.intI ==2)) { return true; } else { return false; } } } class MembersModifiersTestClass12 { protected internal int intI = 1; public static bool testMethod() { MembersModifiersTestClass12 test = new MembersModifiersTestClass12(); if (test.intI == 1) { return true; } else { return false; } } } sealed class MembersModifiersTestClass23 { protected int intI = 0; public static bool testMethod() { return true; } } sealed class MembersModifiersTestClass24 { protected int intI { get {return 1;} set {} } public static bool testMethod() { return true; } } sealed class MembersModifiersTestClass25 { protected void MyMeth() {} public static bool testMethod() { return true; } } sealed class MembersModifiersTestClass26 { protected int this[int intI] { get { return 1; } set {} } public static bool testMethod() { return true; } } sealed class MembersModifiersTestClass27 { protected class MyNested {} public static bool testMethod() { return true; } } } } ================================================ FILE: Zelig/Zelig/Test/RunTime/NETMF/mscorlib/classes/classes3/MethodsTests.cs ================================================ //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // Copyright (c) Microsoft Corporation. All rights reserved. //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// using System; using System.Reflection; using Microsoft.Zelig.Test; namespace Microsoft.Zelig.Test { public class MethodsTests : TestBase, ITestInterface { [SetUp] public InitializeResult Initialize() { Log.Comment("Adding set up for the tests"); return InitializeResult.ReadyToGo; } [TearDown] public void CleanUp() { Log.Comment("Cleaning up after the tests"); } public override TestResult Run( string[] args ) { TestResult result = TestResult.Pass; string testName = "Methods"; result |= Assert.CheckFailed(Methods1_Test(), testName, 1); result |= Assert.CheckFailed(Methods2_Test(), testName, 2); result |= Assert.CheckFailed(Methods3_Test(), testName, 3); result |= Assert.CheckFailed(Methods4_Test(), testName, 4); result |= Assert.CheckFailed(Methods6_Test(), testName, 6); result |= Assert.CheckFailed(Methods7_Test(), testName, 7); result |= Assert.CheckFailed(Methods9_Test(), testName, 9); result |= Assert.CheckFailed(Methods10_Test(), testName, 10); result |= Assert.CheckFailed(Methods11_Test(), testName, 11); result |= Assert.CheckFailed(Methods13_Test(), testName, 13); result |= Assert.CheckFailed(Methods17_Test(), testName, 17); result |= Assert.CheckFailed(Methods19_Test(), testName, 19); result |= Assert.CheckFailed(Methods20_Test(), testName, 20); result |= Assert.CheckFailed(Methods22_Test(), testName, 22); result |= Assert.CheckFailed(Methods23_Test(), testName, 23); result |= Assert.CheckFailed(Methods24_Test(), testName, 24); result |= Assert.CheckFailed(Methods25_Test(), testName, 25); result |= Assert.CheckFailed(Methods26_Test(), testName, 26); result |= Assert.CheckFailed(Methods29_Test(), testName, 29); result |= Assert.CheckFailed(Methods30_Test(), testName, 30); result |= Assert.CheckFailed(Methods33_Test(), testName, 33); result |= Assert.CheckFailed(Methods34_Test(), testName, 34); result |= Assert.CheckFailed(Methods35_Test(), testName, 35); result |= Assert.CheckFailed(Methods56_Test(), testName, 56); result |= Assert.CheckFailed(Methods57_Test(), testName, 57); result |= Assert.CheckFailed(Methods58_Test(), testName, 58); result |= Assert.CheckFailed(Methods59_Test(), testName, 59); result |= Assert.CheckFailed(Methods60_Test(), testName, 60); result |= Assert.CheckFailed(Methods61_Test(), testName, 61); result |= Assert.CheckFailed(Methods66_Test(), testName, 66); result |= Assert.CheckFailed(Methods67_Test(), testName, 67); result |= Assert.CheckFailed(Methods68_Test(), testName, 68); result |= Assert.CheckFailed(Methods69_Test(), testName, 69); result |= Assert.CheckFailed(Methods70_Test(), testName, 70); result |= Assert.CheckFailed(Methods71_Test(), testName, 71); result |= Assert.CheckFailed(Methods75_Test(), testName, 75); result |= Assert.CheckFailed(Methods78_Test(), testName, 78); result |= Assert.CheckFailed(Methods79_Test(), testName, 79); result |= Assert.CheckFailed(Methods80_Test(), testName, 80); result |= Assert.CheckFailed(Methods84_Test(), testName, 84); result |= Assert.CheckFailed(Methods85_Test(), testName, 85); result |= Assert.CheckFailed(Methods92_Test(), testName, 92); result |= Assert.CheckFailed(Methods93_Test(), testName, 93); result |= Assert.CheckFailed(Methods94_Test(), testName, 94); result |= Assert.CheckFailed(Methods95_Test(), testName, 95); result |= Assert.CheckFailed(Methods103_Test(), testName, 103); result |= Assert.CheckFailed(Methods104_Test(), testName, 104); result |= Assert.CheckFailed(Methods105_Test(), testName, 105); result |= Assert.CheckFailed(Methods106_Test(), testName, 106); result |= Assert.CheckFailed(Methods107_Test(), testName, 107); result |= Assert.CheckFailed(Methods108_Test(), testName, 108); result |= Assert.CheckFailed(Methods109_Test(), testName, 109); result |= Assert.CheckFailed(Methods110_Test(), testName, 110); result |= Assert.CheckFailed(Methods111_Test(), testName, 111); result |= Assert.CheckFailed(Methods112_Test(), testName, 112); result |= Assert.CheckFailed(Methods116_Test(), testName, 116); result |= Assert.CheckFailed(Methods117_Test(), testName, 117); result |= Assert.CheckFailed(Methods119_Test(), testName, 119); result |= Assert.CheckFailed(Methods120_Test(), testName, 120); result |= Assert.CheckFailed(Methods121_Test(), testName, 121); result |= Assert.CheckFailed(Methods124_Test(), testName, 124); result |= Assert.CheckFailed(Methods125_Test(), testName, 125); result |= Assert.CheckFailed(Methods132_Test(), testName, 132); result |= Assert.CheckFailed(Methods133_Test(), testName, 133); result |= Assert.CheckFailed(Methods134_Test(), testName, 134); result |= Assert.CheckFailed(Methods142_Test(), testName, 142); result |= Assert.CheckFailed(Methods148_Test(), testName, 148); result |= Assert.CheckFailed(Methods149_Test(), testName, 149); result |= Assert.CheckFailed(Methods150_Test(), testName, 150); result |= Assert.CheckFailed(Methods154_Test(), testName, 154); result |= Assert.CheckFailed(Methods159_Test(), testName, 159); result |= Assert.CheckFailed(Methods160_Test(), testName, 160); result |= Assert.CheckFailed(Methods161_Test(), testName, 161); result |= Assert.CheckFailed(Methods163_Test(), testName, 163); result |= Assert.CheckFailed(Methods164_Test(), testName, 164); result |= Assert.CheckFailed(Methods169_Test(), testName, 169); result |= Assert.CheckFailed(Methods172_Test(), testName, 172); result |= Assert.CheckFailed(Methods173_Test(), testName, 173); result |= Assert.CheckFailed(Methods174_Test(), testName, 174); result |= Assert.CheckFailed(Methods175_Test(), testName, 175); result |= Assert.CheckFailed(Methods179_Test(), testName, 179); result |= Assert.CheckFailed(Methods180_Test(), testName, 180); result |= Assert.CheckFailed(Methods181_Test(), testName, 181); result |= Assert.CheckFailed(Methods182_Test(), testName, 182); result |= Assert.CheckFailed(Methods183_Test(), testName, 183); result |= Assert.CheckFailed(Methods184_Test(), testName, 184); result |= Assert.CheckFailed(Methods185_Test(), testName, 185); result |= Assert.CheckFailed(Methods186_Test(), testName, 186); result |= Assert.CheckFailed(Methods187_Test(), testName, 187); result |= Assert.CheckFailed(Methods188_Test(), testName, 188); result |= Assert.CheckFailed(Methods190_Test(), testName, 190); result |= Assert.CheckFailed(Methods191_Test(), testName, 191); result |= Assert.CheckFailed(Methods192_Test(), testName, 192); result |= Assert.CheckFailed(Methods193_Test(), testName, 193); result |= Assert.CheckFailed(Methods194_Test(), testName, 194); result |= Assert.CheckFailed(Methods195_Test(), testName, 195); result |= Assert.CheckFailed(Methods196_Test(), testName, 196); result |= Assert.CheckFailed(Methods197_Test(), testName, 197); result |= Assert.CheckFailed(Methods199_Test(), testName, 199); result |= Assert.CheckFailed(Methods200_Test(), testName, 200); result |= Assert.CheckFailed(Methods201_Test(), testName, 201); result |= Assert.CheckFailed(Methods204_Test(), testName, 204); result |= Assert.CheckFailed(Methods205_Test(), testName, 205); result |= Assert.CheckFailed(Methods206_Test(), testName, 206); result |= Assert.CheckFailed(Methods207_Test(), testName, 207); result |= Assert.CheckFailed(Methods210_Test(), testName, 210); result |= Assert.CheckFailed(Methods223_Test(), testName, 223); result |= Assert.CheckFailed(Methods224_Test(), testName, 224); result |= Assert.CheckFailed(Methods229_Test(), testName, 229); result |= Assert.CheckFailed(Methods230_Test(), testName, 230); result |= Assert.CheckFailed(Methods231_Test(), testName, 231); result |= Assert.CheckFailed(Methods232_Test(), testName, 232); result |= Assert.CheckFailed(Methods233_Test(), testName, 233); return result; } //Methods Test methods //All test methods ported from folder current\test\cases\client\CLR\Conformance\10_classes\Methods //The following tests were removed because they were build failure tests: //5,8,12,14-16,18,21,27,28,31,32,62-65,72-74,76,77,81-83,86-91,96-102,113-115, //122,123,126-131,135-141,143-147,151-153,208,209,211-22,225-228,234-239 //189 was removed because it required external files, it failed in the Baseline document //11,23,67,70,79,104,107,110,112,134,189,195, //Skip 17 [TestMethod] public TestResult Methods1_Test() { Log.Comment(" Section 10.5"); Log.Comment(" A method-declaration may include set of attributes,"); Log.Comment(" a new modifier, one of four access modifiers,"); Log.Comment(" one of the static, virtual, override, or abstract "); Log.Comment(" modifiers, and an extern modifier."); if (MethodsTestClass1.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Methods2_Test() { Log.Comment(" Section 10.5"); Log.Comment(" A method-declaration may include set of attributes,"); Log.Comment(" a new modifier, one of four access modifiers,"); Log.Comment(" one of the static, virtual, override, or abstract "); Log.Comment(" modifiers, and an extern modifier."); if (MethodsTestClass2.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Methods3_Test() { Log.Comment(" Section 10.5"); Log.Comment(" A method-declaration may include set of attributes,"); Log.Comment(" a new modifier, one of four access modifiers,"); Log.Comment(" one of the static, virtual, override, or abstract "); Log.Comment(" modifiers, and an extern modifier."); if (MethodsTestClass3.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Methods4_Test() { Log.Comment(" Section 10.5"); Log.Comment(" A method-declaration may include set of attributes,"); Log.Comment(" a new modifier, one of four access modifiers,"); Log.Comment(" one of the static, virtual, override, or abstract "); Log.Comment(" modifiers, and an extern modifier."); if (MethodsTestClass4.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Methods6_Test() { Log.Comment(" Section 10.5"); Log.Comment(" A method-declaration may include set of attributes,"); Log.Comment(" a new modifier, one of four access modifiers,"); Log.Comment(" one of the static, virtual, override, or abstract "); Log.Comment(" modifiers, and an extern modifier."); if (MethodsTestClass6.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Methods7_Test() { Log.Comment(" Section 10.5"); Log.Comment(" A method-declaration may include set of attributes,"); Log.Comment(" a new modifier, one of four access modifiers,"); Log.Comment(" one of the static, virtual, override, or abstract "); Log.Comment(" modifiers, and an extern modifier."); if (MethodsTestClass7.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Methods9_Test() { Log.Comment(" Section 10.5"); Log.Comment(" A method-declaration may include set of attributes,"); Log.Comment(" a new modifier, one of four access modifiers,"); Log.Comment(" one of the static, virtual, override, or abstract "); Log.Comment(" modifiers, and an extern modifier."); if (MethodsTestClass9.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Methods10_Test() { Log.Comment(" Section 10.5"); Log.Comment(" A method-declaration may include set of attributes,"); Log.Comment(" a new modifier, one of four access modifiers,"); Log.Comment(" one of the static, virtual, override, or abstract "); Log.Comment(" modifiers, and an extern modifier."); if (MethodsTestClass10.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Methods11_Test() { Log.Comment(" Section 10.5"); Log.Comment(" A method-declaration may include set of attributes,"); Log.Comment(" a new modifier, one of four access modifiers,"); Log.Comment(" one of the static, virtual, override, or abstract "); Log.Comment(" modifiers, and an extern modifier."); if (MethodsTestClass11.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Methods13_Test() { Log.Comment(" Section 10.5"); Log.Comment(" A method-declaration may include set of attributes,"); Log.Comment(" a new modifier, one of four access modifiers,"); Log.Comment(" one of the static, virtual, override, or abstract "); Log.Comment(" modifiers, and an extern modifier."); if (MethodsTestClass13.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Methods17_Test() { Log.Comment(" Section 10.5"); Log.Comment(" A method-declaration may include set of attributes,"); Log.Comment(" a new modifier, one of four access modifiers,"); Log.Comment(" one of the static, virtual, override, or abstract "); Log.Comment(" modifiers, and an extern modifier."); if (MethodsTestClass17.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Methods19_Test() { Log.Comment(" The return-type of a method declaration specifies"); Log.Comment(" the type of the value computed and returned by the"); Log.Comment(" method. The return type is void if the method does"); Log.Comment(" not return a value."); if (MethodsTestClass19.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Methods20_Test() { Log.Comment(" The return-type of a method declaration specifies"); Log.Comment(" the type of the value computed and returned by the"); Log.Comment(" method. The return type is void if the method does"); Log.Comment(" not return a value."); if (MethodsTestClass20.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Methods22_Test() { Log.Comment(" The return-type of a method declaration specifies"); Log.Comment(" the type of the value computed and returned by the"); Log.Comment(" method. The return type is void if the method does"); Log.Comment(" not return a value."); if (MethodsTestClass22.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Methods23_Test() { Log.Comment(" The return-type of a method declaration specifies"); Log.Comment(" the type of the value computed and returned by the"); Log.Comment(" method. The return type is void if the method does"); Log.Comment(" not return a value."); if (MethodsTestClass23.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Methods24_Test() { Log.Comment(" The return-type of a method declaration specifies"); Log.Comment(" the type of the value computed and returned by the"); Log.Comment(" method. The return type is void if the method does"); Log.Comment(" not return a value."); if (MethodsTestClass24.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Methods25_Test() { Log.Comment(" The return-type of a method declaration specifies"); Log.Comment(" the type of the value computed and returned by the"); Log.Comment(" method. The return type is void if the method does"); Log.Comment(" not return a value."); if (MethodsTestClass25.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Methods26_Test() { Log.Comment(" The return-type of a method declaration specifies"); Log.Comment(" the type of the value computed and returned by the"); Log.Comment(" method. The return type is void if the method does"); Log.Comment(" not return a value."); if (MethodsTestClass26.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Methods29_Test() { Log.Comment(" Section 10.5"); Log.Comment(" The member-name specifies the name of the method."); Log.Comment(" Unless the method is an explicit interface member"); Log.Comment(" implementation, the member-name is simply an "); Log.Comment(" identifier. For an explicit interface member "); Log.Comment(" implementation, the member-name consists of an"); Log.Comment(" interface-type followed by a . and an identifier."); if (MethodsTestClass29.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Methods30_Test() { Log.Comment(" Section 10.5"); Log.Comment(" The member-name specifies the name of the method."); Log.Comment(" Unless the method is an explicit interface member"); Log.Comment(" implementation, the member-name is simply an "); Log.Comment(" identifier. For an explicit interface member "); Log.Comment(" implementation, the member-name consists of an"); Log.Comment(" interface-type followed by a . and an identifier."); if (MethodsTestClass30.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Methods33_Test() { Log.Comment(" Section 10.5"); Log.Comment(" The optional formal-parameter-list specifies"); Log.Comment(" the parameters of the method."); if (MethodsTestClass33.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Methods34_Test() { Log.Comment(" Section 10.5"); Log.Comment(" The optional formal-parameter-list specifies"); Log.Comment(" the parameters of the method."); if (MethodsTestClass34.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Methods35_Test() { Log.Comment("Testing method call with 10 parameters"); if (MethodsTestClass35.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Methods56_Test() { Log.Comment(" Section 10.5"); Log.Comment(" A method declaration creates a separate space"); Log.Comment(" for parameters and local variables. Names are introduced"); Log.Comment(" into this declaration space by the formal parameter"); Log.Comment(" list of the method and by the local variable declarations"); Log.Comment(" in the block of the method. All names in the declaration"); Log.Comment(" space of a method must be unique. Thus it is an error"); Log.Comment(" for a parameter or local variable to have the same name"); Log.Comment(" as another parameter or local variable."); if (MethodsTestClass56.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Methods57_Test() { Log.Comment(" Section 10.5"); Log.Comment(" A method declaration creates a separate space"); Log.Comment(" for parameters and local variables. Names are introduced"); Log.Comment(" into this declaration space by the formal parameter"); Log.Comment(" list of the method and by the local variable declarations"); Log.Comment(" in the block of the method. All names in the declaration"); Log.Comment(" space of a method must be unique. Thus it is an error"); Log.Comment(" for a parameter or local variable to have the same name"); Log.Comment(" as another parameter or local variable."); if (MethodsTestClass57.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Methods58_Test() { Log.Comment(" Section 10.5"); Log.Comment(" When a formal parameter is a value parameter,"); Log.Comment(" the corresponding argument in the method invocation"); Log.Comment(" must be an expression of a type that is implicitly"); Log.Comment(" convertible to the formal parameter type."); if (MethodsTestClass58.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Methods59_Test() { Log.Comment(" Section 10.5"); Log.Comment(" When a formal parameter is a value parameter,"); Log.Comment(" the corresponding argument in the method invocation"); Log.Comment(" must be an expression of a type that is implicitly"); Log.Comment(" convertible to the formal parameter type."); if (MethodsTestClass59.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Methods60_Test() { Log.Comment(" Section 10.5"); Log.Comment(" When a formal parameter is a value parameter,"); Log.Comment(" the corresponding argument in the method invocation"); Log.Comment(" must be an expression of a type that is implicitly"); Log.Comment(" convertible to the formal parameter type."); if (MethodsTestClass60.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Methods61_Test() { Log.Comment(" Section 10.5"); Log.Comment(" When a formal parameter is a value parameter,"); Log.Comment(" the corresponding argument in the method invocation"); Log.Comment(" must be an expression of a type that is implicitly"); Log.Comment(" convertible to the formal parameter type."); if (MethodsTestClass61.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Methods66_Test() { Log.Comment(" Section 10.5"); Log.Comment(" A method is permitted to assign new values to "); Log.Comment(" a value parameter. Such assignments only affect"); Log.Comment(" the local storage location represented by the "); Log.Comment(" value parameter--they have no effect on the actual "); Log.Comment(" argument given in the method invocation."); if (MethodsTestClass66.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Methods67_Test() { Log.Comment(" Section 10.5"); Log.Comment(" A method is permitted to assign new values to "); Log.Comment(" a value parameter. Such assignments only affect"); Log.Comment(" the local storage location represented by the "); Log.Comment(" value parameter--they have no effect on the actual "); Log.Comment(" argument given in the method invocation."); if (MethodsTestClass67.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Methods68_Test() { Log.Comment(" Section 10.5"); Log.Comment(" A method is permitted to assign new values to "); Log.Comment(" a value parameter. Such assignments only affect"); Log.Comment(" the local storage location represented by the "); Log.Comment(" value parameter--they have no effect on the actual "); Log.Comment(" argument given in the method invocation."); if (MethodsTestClass68.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Methods69_Test() { Log.Comment(" Section 10.5"); Log.Comment(" A parameter declared with a ref modifier is a "); Log.Comment(" reference parameter. Unlike a value parameter,"); Log.Comment(" a reference parameter does not create a new "); Log.Comment(" storage location. Instead, a reference parameter"); Log.Comment(" represents the same storage location as the"); Log.Comment(" variable given as the argument in the method"); Log.Comment(" invocation."); if (MethodsTestClass69.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Methods70_Test() { Log.Comment(" Section 10.5"); Log.Comment(" A parameter declared with a ref modifier is a "); Log.Comment(" reference parameter. Unlike a value parameter,"); Log.Comment(" a reference parameter does not create a new "); Log.Comment(" storage location. Instead, a reference parameter"); Log.Comment(" represents the same storage location as the"); Log.Comment(" variable given as the argument in the method"); Log.Comment(" invocation."); if (MethodsTestClass70.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Methods71_Test() { Log.Comment(" Section 10.5"); Log.Comment(" A parameter declared with a ref modifier is a "); Log.Comment(" reference parameter. Unlike a value parameter,"); Log.Comment(" a reference parameter does not create a new "); Log.Comment(" storage location. Instead, a reference parameter"); Log.Comment(" represents the same storage location as the"); Log.Comment(" variable given as the argument in the method"); Log.Comment(" invocation."); if (MethodsTestClass71.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Methods75_Test() { Log.Comment(" Section 10.5"); Log.Comment(" When a formal parameter is a reference parameter,"); Log.Comment(" the corresponding argument in a method invocation"); Log.Comment(" must consist of the keyword ref followed by a "); Log.Comment(" variable-reference of the same type as the formal"); Log.Comment(" parameter. A variable must be definitely assigned"); Log.Comment(" before it can be passed as a reference parameter."); if (MethodsTestClass75.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Methods78_Test() { Log.Comment(" Section 10.5"); Log.Comment(" A parameter declared with an out modifier is an output"); Log.Comment(" parameter. Similar to a reference parameter, an output"); Log.Comment(" parameter does not create a new storage location. Instead,"); Log.Comment(" an output parameter represents the same storage location"); Log.Comment(" as the variable given as the argument in the method invocation."); if (MethodsTestClass78.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Methods79_Test() { Log.Comment(" Section 10.5"); Log.Comment(" A parameter declared with an out modifier is an output"); Log.Comment(" parameter. Similar to a reference parameter, an output"); Log.Comment(" parameter does not create a new storage location. Instead,"); Log.Comment(" an output parameter represents the same storage location"); Log.Comment(" as the variable given as the argument in the method invocation."); if (MethodsTestClass79.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Methods80_Test() { Log.Comment(" Section 10.5"); Log.Comment(" A parameter declared with an out modifier is an output"); Log.Comment(" parameter. Similar to a reference parameter, an output"); Log.Comment(" parameter does not create a new storage location. Instead,"); Log.Comment(" an output parameter represents the same storage location"); Log.Comment(" as the variable given as the argument in the method invocation."); if (MethodsTestClass80.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Methods84_Test() { Log.Comment(" Section 10.5"); Log.Comment(" When a formal parameter is an output parameter,"); Log.Comment(" the corresponding argument in a method invocation"); Log.Comment(" must consist of the keyword out followed by a "); Log.Comment(" variable-reference of the same type as the formal "); Log.Comment(" parameter. A variable need not be definitely"); Log.Comment(" assigned before it can be passed as an output"); Log.Comment(" parameter, but following an invocation where a "); Log.Comment(" variable was passed as an output parameter, the"); Log.Comment(" variable is considered definitely assigned."); if (MethodsTestClass84.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Methods85_Test() { Log.Comment(" Section 10.5"); Log.Comment(" When a formal parameter is an output parameter,"); Log.Comment(" the corresponding argument in a method invocation"); Log.Comment(" must consist of the keyword out followed by a "); Log.Comment(" variable-reference of the same type as the formal "); Log.Comment(" parameter. A variable need not be definitely"); Log.Comment(" assigned before it can be passed as an output"); Log.Comment(" parameter, but following an invocation where a "); Log.Comment(" variable was passed as an output parameter, the"); Log.Comment(" variable is considered definitely assigned."); if (MethodsTestClass85.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Methods92_Test() { Log.Comment(" Section 10.5"); Log.Comment(" Every output parameter of a method must be"); Log.Comment(" definitely assigned before the method returns."); if (MethodsTestClass92.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Methods93_Test() { Log.Comment(" Section 10.5"); Log.Comment(" Every output parameter of a method must be"); Log.Comment(" definitely assigned before the method returns."); if (MethodsTestClass93.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Methods94_Test() { Log.Comment(" Section 10.5"); Log.Comment(" Every output parameter of a method must be"); Log.Comment(" definitely assigned before the method returns."); if (MethodsTestClass94.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Methods95_Test() { Log.Comment(" Section 10.5"); Log.Comment(" Every output parameter of a method must be"); Log.Comment(" definitely assigned before the method returns."); if (MethodsTestClass95.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Methods103_Test() { Log.Comment(" Section 10.5"); Log.Comment(" The implementation of a non-virtual method"); Log.Comment(" is invariant: The implementation is the same "); Log.Comment(" whether the method is invoked on an instance"); Log.Comment(" of the class in which it is declared or an "); Log.Comment(" instance of the derived class."); if (MethodsTestClass103.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Methods104_Test() { Log.Comment(" Section 10.5"); Log.Comment(" The implementation of a non-virtual method"); Log.Comment(" is invariant: The implementation is the same "); Log.Comment(" whether the method is invoked on an instance"); Log.Comment(" of the class in which it is declared or an "); Log.Comment(" instance of the derived class."); if (MethodsTestClass104.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Methods105_Test() { Log.Comment(" Section 10.5"); Log.Comment(" The implementation of a non-virtual method"); Log.Comment(" is invariant: The implementation is the same "); Log.Comment(" whether the method is invoked on an instance"); Log.Comment(" of the class in which it is declared or an "); Log.Comment(" instance of the derived class."); if (MethodsTestClass105.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Methods106_Test() { Log.Comment(" Section 10.5"); Log.Comment(" For every virtual method declaration of M,"); Log.Comment(" there exists a most derived implementation"); Log.Comment(" of the method with respect to the class."); Log.Comment(" The most derived implementation of a "); Log.Comment(" virtual method M with respectto a class"); Log.Comment(" R is determined as follows:"); Log.Comment(""); Log.Comment(" If R contains the introducing virtual"); Log.Comment(" declaration of M, then this is the most"); Log.Comment(" derived implementation of M."); if (MethodsTestClass106.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Methods107_Test() { Log.Comment(" Section 10.5"); Log.Comment(" For every virtual method declaration of M,"); Log.Comment(" there exists a most derived implementation"); Log.Comment(" of the method with respect to the class."); Log.Comment(" The most derived implementation of a "); Log.Comment(" virtual method M with respectto a class"); Log.Comment(" R is determined as follows:"); Log.Comment(""); Log.Comment(" If R contains the introducing virtual"); Log.Comment(" declaration of M, then this is the most"); Log.Comment(" derived implementation of M."); if (MethodsTestClass107.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Methods108_Test() { Log.Comment(" Section 10.5"); Log.Comment(" For every virtual method declaration of M,"); Log.Comment(" there exists a most derived implementation"); Log.Comment(" of the method with respect to the class."); Log.Comment(" The most derived implementation of a "); Log.Comment(" virtual method M with respectto a class"); Log.Comment(" R is determined as follows:"); Log.Comment(""); Log.Comment(" If R contains the introducing virtual"); Log.Comment(" declaration of M, then this is the most"); Log.Comment(" derived implementation of M."); Log.Comment(""); Log.Comment(" Otherwise, if R contains an override of M,"); Log.Comment(" then this is the most derived implementation"); Log.Comment(" of M."); if (MethodsTestClass108.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Methods109_Test() { Log.Comment(" Section 10.5"); Log.Comment(" For every virtual method declaration of M,"); Log.Comment(" there exists a most derived implementation"); Log.Comment(" of the method with respect to the class."); Log.Comment(" The most derived implementation of a "); Log.Comment(" virtual method M with respectto a class"); Log.Comment(" R is determined as follows:"); Log.Comment(""); Log.Comment(" If R contains the introducing virtual"); Log.Comment(" declaration of M, then this is the most"); Log.Comment(" derived implementation of M."); Log.Comment(""); Log.Comment(" Otherwise, if R contains an override of M,"); Log.Comment(" then this is the most derived implementation"); Log.Comment(" of M."); if (MethodsTestClass109.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Methods110_Test() { Log.Comment(" Section 10.5"); Log.Comment(" For every virtual method declaration of M,"); Log.Comment(" there exists a most derived implementation"); Log.Comment(" of the method with respect to the class."); Log.Comment(" The most derived implementation of a "); Log.Comment(" virtual method M with respectto a class"); Log.Comment(" R is determined as follows:"); Log.Comment(""); Log.Comment(" If R contains the introducing virtual"); Log.Comment(" declaration of M, then this is the most"); Log.Comment(" derived implementation of M."); Log.Comment(""); Log.Comment(" Otherwise, if R contains an override of M,"); Log.Comment(" then this is the most derived implementation"); Log.Comment(" of M."); if (MethodsTestClass110.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Methods111_Test() { Log.Comment(" Section 10.5"); Log.Comment(" For every virtual method declaration of M,"); Log.Comment(" there exists a most derived implementation"); Log.Comment(" of the method with respect to the class."); Log.Comment(" The most derived implementation of a "); Log.Comment(" virtual method M with respectto a class"); Log.Comment(" R is determined as follows:"); Log.Comment(""); Log.Comment(" If R contains the introducing virtual"); Log.Comment(" declaration of M, then this is the most"); Log.Comment(" derived implementation of M."); Log.Comment(""); Log.Comment(" Otherwise, if R contains an override of M,"); Log.Comment(" then this is the most derived implementation"); Log.Comment(" of M."); if (MethodsTestClass111.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Methods112_Test() { Log.Comment(" Section 10.5"); Log.Comment(" Because methods are allowed to hide inherited"); Log.Comment(" methods, it is possible for a class to contain"); Log.Comment(" several virtual methods with the same signature."); Log.Comment(" This does not provide an ambiguity problem, since"); Log.Comment(" all but the most derived method are hidden."); if (MethodsTestClass112.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Methods116_Test() { Log.Comment(" Section 10.5"); Log.Comment(" It is an error for an override method declaration"); Log.Comment(" to include any one of the new, static, virtual, or "); Log.Comment(" abstract modifiers."); if (MethodsTestClass116.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Methods117_Test() { Log.Comment(" Section 10.5"); Log.Comment(" For purposes of locating the overridden base"); Log.Comment(" method, a method is considered accessible if "); Log.Comment(" it is public, if it is protected, if it is "); Log.Comment(" internal and declared in the same project as "); Log.Comment(" C, or if it is private and declared in a class"); Log.Comment(" containing the declaration of C."); if (MethodsTestClass117.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Methods119_Test() { Log.Comment(" Section 10.5"); Log.Comment(" For purposes of locating the overridden base"); Log.Comment(" method, a method is considered accessible if "); Log.Comment(" it is public, if it is protected, if it is "); Log.Comment(" internal and declared in the same project as "); Log.Comment(" C, or if it is private and declared in a class"); Log.Comment(" containing the declaration of C."); if (MethodsTestClass119.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Methods120_Test() { Log.Comment(" Section 10.5"); Log.Comment(" For purposes of locating the overridden base"); Log.Comment(" method, a method is considered accessible if "); Log.Comment(" it is public, if it is protected, if it is "); Log.Comment(" internal and declared in the same project as "); Log.Comment(" C, or if it is private and declared in a class"); Log.Comment(" containing the declaration of C."); if (MethodsTestClass120.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Methods121_Test() { Log.Comment(" Section 10.5"); Log.Comment(" For purposes of locating the overridden base"); Log.Comment(" method, a method is considered accessible if "); Log.Comment(" it is public, if it is protected, if it is "); Log.Comment(" internal and declared in the same project as "); Log.Comment(" C, or if it is private and declared in a class"); Log.Comment(" containing the declaration of C."); if (MethodsTestClass121.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Methods124_Test() { Log.Comment(" Section 10.5"); Log.Comment(" A compile time-error occurs unless all"); Log.Comment(" of the following are true for an override"); Log.Comment(" declaration:"); Log.Comment(""); Log.Comment(" An overriddden base method can be located"); Log.Comment(" as described above."); Log.Comment(""); Log.Comment(" The overridden base method is virtual,"); Log.Comment(" abstract, or override method. In other"); Log.Comment(" words, the overridden base method cannot"); Log.Comment(" be static or non-virtual."); if (MethodsTestClass124.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Methods125_Test() { Log.Comment(" Section 10.5"); Log.Comment(" A compile time-error occurs unless all"); Log.Comment(" of the following are true for an override"); Log.Comment(" declaration:"); Log.Comment(""); Log.Comment(" An overriddden base method can be located"); Log.Comment(" as described above."); Log.Comment(""); Log.Comment(" The overridden base method is virtual,"); Log.Comment(" abstract, or override method. In other"); Log.Comment(" words, the overridden base method cannot"); Log.Comment(" be static or non-virtual."); if (MethodsTestClass125.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Methods132_Test() { Log.Comment(" Section 10.5"); Log.Comment(" An override declaration can access the overridden "); Log.Comment(" base method using a base-access."); if (MethodsTestClass132.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Methods133_Test() { Log.Comment(" Section 10.5"); Log.Comment(" An override declaration can access the overridden "); Log.Comment(" base method using a base-access."); if (MethodsTestClass133.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Methods134_Test() { Log.Comment(" Section 10.5"); Log.Comment(" Only by including an override modifier can"); Log.Comment(" a method override another method. In all other"); Log.Comment(" cases, a method with the same signature as an"); Log.Comment(" inherited method simply hides the inherited "); Log.Comment(" member."); if (MethodsTestClass134.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Methods142_Test() { if (MethodsTestClass142.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Methods148_Test() { Log.Comment(" Section 10.5"); Log.Comment(" If execution of the method body of a void"); Log.Comment(" method completes normally (that is, if control"); Log.Comment(" flows off the end of the method body), the "); Log.Comment(" method simply returns to the caller."); if (MethodsTestClass148.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Methods149_Test() { Log.Comment(" Section 10.5"); Log.Comment(" When the return type of a method is not void,"); Log.Comment(" each return statement in the method body must"); Log.Comment(" specify an expression of a type that is implicitly"); Log.Comment(" covertable to the return type."); if (MethodsTestClass149.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Methods150_Test() { Log.Comment(" Section 10.5"); Log.Comment(" When the return type of a method is not void,"); Log.Comment(" each return statement in the method body must"); Log.Comment(" specify an expression of a type that is implicitly"); Log.Comment(" covertable to the return type."); if (MethodsTestClass150.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Methods154_Test() { Log.Comment(" Section 10.5"); Log.Comment(" When the return type of a method is not void,"); Log.Comment(" each return statement in the method body must"); Log.Comment(" specify an expression of a type that is implicitly"); Log.Comment(" covertable to the return type."); if (MethodsTestClass154.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Methods159_Test() { Log.Comment(" Section 10.5"); Log.Comment(" When the return type of a method is not void,"); Log.Comment(" each return statement in the method body must"); Log.Comment(" specify an expression of a type that is implicitly"); Log.Comment(" covertable to the return type. Execution of the "); Log.Comment(" method body of a value returning method is required"); Log.Comment(" to terminate in a return statement that specifies"); Log.Comment(" an expression or in a throw statement that throws"); Log.Comment(" an System.Exception."); if (MethodsTestClass159.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Methods160_Test() { Log.Comment(" Section 10.5"); Log.Comment(" When the return type of a method is not void,"); Log.Comment(" each return statement in the method body must"); Log.Comment(" specify an expression of a type that is implicitly"); Log.Comment(" covertable to the return type. Execution of the "); Log.Comment(" method body of a value returning method is required"); Log.Comment(" to terminate in a return statement that specifies"); Log.Comment(" an expression or in a throw statement that throws"); Log.Comment(" an System.Exception."); if (MethodsTestClass160.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Methods161_Test() { Log.Comment(" Section 10.5"); Log.Comment(" When the return type of a method is not void,"); Log.Comment(" each return statement in the method body must"); Log.Comment(" specify an expression of a type that is implicitly"); Log.Comment(" covertable to the return type. Execution of the "); Log.Comment(" method body of a value returning method is required"); Log.Comment(" to terminate in a return statement that specifies"); Log.Comment(" an expression or in a throw statement that throws"); Log.Comment(" an System.Exception."); if (MethodsTestClass161.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Methods163_Test() { Log.Comment(" Section 10.5"); Log.Comment(" A parameter declared with a params modifier is"); Log.Comment(" a params parameter. A params parameter must be"); Log.Comment(" the last parameter in the formal parameter list,"); Log.Comment(" and the type of a params parameter must be a "); Log.Comment(" single-dimension array type. For example, the"); Log.Comment(" types int[] and int[][] can be used as the type of"); Log.Comment(" a params parameter, but the type int[,] cannot be"); Log.Comment(" used in this way."); if (MethodsTestClass163.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Methods164_Test() { Log.Comment(" Section 10.5"); Log.Comment(" A parameter declared with a params modifier is"); Log.Comment(" a params parameter. A params parameter must be"); Log.Comment(" the last parameter in the formal parameter list,"); Log.Comment(" and the type of a params parameter must be a "); Log.Comment(" single-dimension array type. For example, the"); Log.Comment(" types int[] and int[][] can be used as the type of"); Log.Comment(" a params parameter, but the type int[,] cannot be"); Log.Comment(" used in this way."); if (MethodsTestClass164.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Methods169_Test() { Log.Comment(" Section 10.5"); Log.Comment(" A params parameter enables a caller to supply values"); Log.Comment(" in one of two ways."); Log.Comment(" The caller may specify an expression of a type that"); Log.Comment(" is implicitly convertible to the formal parameter type."); Log.Comment(" In this case, the params parameter acts precisely like"); Log.Comment(" a value parameter."); if (MethodsTestClass169.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Methods172_Test() { Log.Comment(" Section 10.5"); Log.Comment(" A params parameter enables a caller to supply values"); Log.Comment(" in one of two ways."); Log.Comment(" Alternately, the caller may specify zero or more expressions,"); Log.Comment(" where the type of each expression is implicitly convertible"); Log.Comment(" to the element type of the formal parameter type. In this case,"); Log.Comment(" params parameter is initialized with an array fo the formal"); Log.Comment(" parameter type that contains the value or values provided by"); Log.Comment(" the caller."); if (MethodsTestClass172.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Methods173_Test() { Log.Comment(" Section 10.5"); Log.Comment(" A params parameter enables a caller to supply values"); Log.Comment(" in one of two ways."); Log.Comment(" Alternately, the caller may specify zero or more expressions,"); Log.Comment(" where the type of each expression is implicitly convertible"); Log.Comment(" to the element type of the formal parameter type. In this case,"); Log.Comment(" params parameter is initialized with an array fo the formal"); Log.Comment(" parameter type that contains the value or values provided by"); Log.Comment(" the caller."); if (MethodsTestClass173.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Methods174_Test() { Log.Comment(" Section 10.5"); Log.Comment(" A params parameter enables a caller to supply values"); Log.Comment(" in one of two ways."); Log.Comment(" Alternately, the caller may specify zero or more expressions,"); Log.Comment(" where the type of each expression is implicitly convertible"); Log.Comment(" to the element type of the formal parameter type. In this case,"); Log.Comment(" params parameter is initialized with an array fo the formal"); Log.Comment(" parameter type that contains the value or values provided by"); Log.Comment(" the caller."); if (MethodsTestClass174.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Methods175_Test() { Log.Comment(" Section 10.5"); Log.Comment(" A params parameter enables a caller to supply values"); Log.Comment(" in one of two ways."); Log.Comment(" Alternately, the caller may specify zero or more expressions,"); Log.Comment(" where the type of each expression is implicitly convertible"); Log.Comment(" to the element type of the formal parameter type. In this case,"); Log.Comment(" params parameter is initialized with an array fo the formal"); Log.Comment(" parameter type that contains the value or values provided by"); Log.Comment(" the caller."); if (MethodsTestClass175.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Methods179_Test() { Log.Comment(" Section 10.5"); Log.Comment(" A params parameter enables a caller to supply values"); Log.Comment(" in one of two ways."); Log.Comment(" Alternately, the caller may specify zero or more expressions,"); Log.Comment(" where the type of each expression is implicitly convertible"); Log.Comment(" to the element type of the formal parameter type. In this case,"); Log.Comment(" params parameter is initialized with an array fo the formal"); Log.Comment(" parameter type that contains the value or values provided by"); Log.Comment(" the caller."); if (MethodsTestClass179.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Methods180_Test() { Log.Comment(" Section 10.5"); Log.Comment(" A params parameter enables a caller to supply values"); Log.Comment(" in one of two ways."); Log.Comment(" Alternately, the caller may specify zero or more expressions,"); Log.Comment(" where the type of each expression is implicitly convertible"); Log.Comment(" to the element type of the formal parameter type. In this case,"); Log.Comment(" params parameter is initialized with an array fo the formal"); Log.Comment(" parameter type that contains the value or values provided by"); Log.Comment(" the caller."); if (MethodsTestClass180.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Methods181_Test() { Log.Comment(" Section 10.5"); Log.Comment(" A params parameter enables a caller to supply values"); Log.Comment(" in one of two ways."); Log.Comment(" Alternately, the caller may specify zero or more expressions,"); Log.Comment(" where the type of each expression is implicitly convertible"); Log.Comment(" to the element type of the formal parameter type. In this case,"); Log.Comment(" params parameter is initialized with an array fo the formal"); Log.Comment(" parameter type that contains the value or values provided by"); Log.Comment(" the caller."); if (MethodsTestClass181.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Methods182_Test() { Log.Comment(" Section 10.5"); Log.Comment(" A params parameter enables a caller to supply values"); Log.Comment(" in one of two ways."); Log.Comment(" Alternately, the caller may specify zero or more expressions,"); Log.Comment(" where the type of each expression is implicitly convertible"); Log.Comment(" to the element type of the formal parameter type. In this case,"); Log.Comment(" params parameter is initialized with an array fo the formal"); Log.Comment(" parameter type that contains the value or values provided by"); Log.Comment(" the caller."); if (MethodsTestClass182.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Methods183_Test() { Log.Comment(" Section 10.5"); Log.Comment(" A params parameter enables a caller to supply values"); Log.Comment(" in one of two ways."); Log.Comment(" Alternately, the caller may specify zero or more expressions,"); Log.Comment(" where the type of each expression is implicitly convertible"); Log.Comment(" to the element type of the formal parameter type. In this case,"); Log.Comment(" params parameter is initialized with an array fo the formal"); Log.Comment(" parameter type that contains the value or values provided by"); Log.Comment(" the caller."); if (MethodsTestClass183.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Methods184_Test() { Log.Comment(" Section 10.5"); Log.Comment(" A params parameter enables a caller to supply values"); Log.Comment(" in one of two ways."); Log.Comment(" Alternately, the caller may specify zero or more expressions,"); Log.Comment(" where the type of each expression is implicitly convertible"); Log.Comment(" to the element type of the formal parameter type. In this case,"); Log.Comment(" params parameter is initialized with an array fo the formal"); Log.Comment(" parameter type that contains the value or values provided by"); Log.Comment(" the caller."); if (MethodsTestClass184.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Methods185_Test() { Log.Comment(" Section 10.5"); Log.Comment(" A method is permitted to assign new values"); Log.Comment(" to a params parameter. Such assignments only"); Log.Comment(" affect the local storage location represented"); Log.Comment(" by the params parameter."); if (MethodsTestClass185.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Methods186_Test() { Log.Comment(" Section 10.5"); Log.Comment(" A params parameter can be passed along to another"); Log.Comment(" params parameter."); if (MethodsTestClass186.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Methods187_Test() { Log.Comment(" Section 10.5"); Log.Comment(" A params parameter can be passed along to another"); Log.Comment(" params parameter."); if (MethodsTestClass187.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Methods188_Test() { Log.Comment("Testing explicit base method call to a child class whose parent implements"); if (MethodsTestClass188.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Methods190_Test() { Log.Comment("Testing implicit base method calls to protected methods in parent class"); if (MethodsTestClass190.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Methods191_Test() { Log.Comment("Testing implicit base method calls to internal methods in parent class"); if (MethodsTestClass191.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Methods192_Test() { Log.Comment("Testing implicit base method calls to protected internal methods in parent class"); if (MethodsTestClass192.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Methods193_Test() { Log.Comment("Testing implicit base method calls to private methods in parent class"); if (MethodsTestClass193.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Methods194_Test() { Log.Comment("Testing implicit base method calls to public virtual methods in parent class"); if (MethodsTestClass194.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Methods195_Test() { Log.Comment("Tests if a new method does not overwrite a virtual method in a base class"); if (MethodsTestClass195.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Methods196_Test() { Log.Comment("Tests if a new method does overwrite an abstract method in a base class"); if (MethodsTestClass196.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Methods197_Test() { Log.Comment("Tests the calling of an empty delegate"); if (MethodsTestClass197.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Methods199_Test() { Log.Comment("Tests if a sealed method overwrites a virtual method in a base class"); if (MethodsTestClass199.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Methods200_Test() { Log.Comment("Tests large number of assignments inside a public method"); if (MethodsTestClass200.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Methods201_Test() { Log.Comment("Tests large number of assignments inside a public static method"); if (MethodsTestClass201.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Methods204_Test() { Log.Comment("Tests a method with explicit, params signature"); if (MethodsTestClass204.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Methods205_Test() { Log.Comment("Tests a method with a mixed explicit and params signature"); if (MethodsTestClass205.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Methods206_Test() { Log.Comment("Tests method overloading between params and explicit signatures (static)"); if (MethodsTestClass206.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Methods207_Test() { Log.Comment("Tests method overloading between params and explicit signatures"); if (MethodsTestClass207.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Methods210_Test() { Log.Comment(" Section 10.5 If the declaration includes the sealed modifier, then the "); Log.Comment(" declaration must also include the override modifier."); if (MethodsTestClass210.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Methods223_Test() { Log.Comment(" Section 10.5 The ref and out parameters are part of a method's signature, but the params modifier is not."); if (MethodsTestClass223.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Methods224_Test() { Log.Comment(" Section 10.5 The ref and out parameters are part of a method's signature, but the params modifier is not."); if (MethodsTestClass224.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Methods229_Test() { Log.Comment(" error CS0114: 'function1' hides inherited member 'function2'."); Log.Comment(" To make the current method override that implementation, add "); Log.Comment(" the override keyword. Otherwise add the new keyword."); if (MethodsTestClass229.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Methods230_Test() { Log.Comment(" error CS0114: 'function1' hides inherited member 'function2'."); Log.Comment(" To make the current method override that implementation, add "); Log.Comment(" the override keyword. Otherwise add the new keyword."); if (MethodsTestClass230.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Methods231_Test() { Log.Comment(" error CS0114: 'function1' hides inherited member 'function2'."); Log.Comment(" To make the current method override that implementation, add "); Log.Comment(" the override keyword. Otherwise add the new keyword."); if (MethodsTestClass231.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Methods232_Test() { Log.Comment(" error CS0114: 'function1' hides inherited member 'function2'."); Log.Comment(" To make the current method override that implementation, add "); Log.Comment(" the override keyword. Otherwise add the new keyword."); if (MethodsTestClass232.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Methods233_Test() { Log.Comment(" Section 10.5"); Log.Comment(" A method-declaration may include set of attributes,"); Log.Comment(" a new modifier, one of four access modifiers,"); Log.Comment(" one of the static, virtual, override, or abstract "); Log.Comment(" modifiers, and an extern modifier."); if (MethodsTestClass233.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } public class MethodsTestClass_Base1 { public static bool testMethod() { return false; } } public class MethodsTestClass1 : MethodsTestClass_Base1 { //new modifier public int MyMeth() { return 2; } public static bool testMethod() { MethodsTestClass1 test = new MethodsTestClass1(); if (test.MyMeth() == 2) { return true; } else { return false; } } } public class MethodsTestClass2 { //new modifier public int MyMeth() { return 2; } public static bool testMethod() { MethodsTestClass2 test = new MethodsTestClass2(); if (test.MyMeth() == 2) { return true; } else { return false; } } } public class MethodsTestClass3 { //public modifier public int MyMeth() { return 2; } public static bool testMethod() { MethodsTestClass3 test = new MethodsTestClass3(); if (test.MyMeth() == 2) { return true; } else { return false; } } } public class MethodsTestClass_Base4 { //protected modifier protected int MyMeth() { return 2; } } public class MethodsTestClass4 : MethodsTestClass_Base4 { public static bool testMethod() { MethodsTestClass4 test = new MethodsTestClass4(); if (test.MyMeth() == 2) { return true; } else { return false; } } } public class MethodsTestClass6 { //internal modifier internal int MyMeth() { return 2; } public static bool testMethod() { MethodsTestClass6 test = new MethodsTestClass6(); if (test.MyMeth() == 2) { return true; } else { return false; } } } public class MethodsTestClass7 { //private modifier private int MyMeth() { return 2; } public static bool testMethod() { MethodsTestClass7 test = new MethodsTestClass7(); if (test.MyMeth() == 2) { return true; } else { return false; } } } public class MethodsTestClass9 { //static modifier static int MyMeth() { return 2; } public static bool testMethod() { if (MyMeth() == 2) { return true; } else { return false; } } } public class MethodsTestClass_Base10 { //virtual modifier public virtual int MyMeth(){ return 1; } } public class MethodsTestClass10 : MethodsTestClass_Base10 { //override modifier public override int MyMeth(){ return 2; } public static bool testMethod() { MethodsTestClass_Base10 test = new MethodsTestClass10(); if (test.MyMeth() == 2) { return true; } else { return false; } } } public class MethodsTestClass_Base11 { //virtual modifier public virtual int MyMeth(){ return 1; } } public class MethodsTestClass11 : MethodsTestClass_Base11 { //new modifier new int MyMeth(){ return 2; } public static bool testMethod() { MethodsTestClass_Base11 test = new MethodsTestClass11(); if (test.MyMeth() == 1) { return true; } else { return false; } } } abstract class MethodsTestClass_Base13 { //abstract modifier public abstract int MyMeth(); } class MethodsTestClass13 : MethodsTestClass_Base13 { public override int MyMeth() { return 2; } public static bool testMethod() { MethodsTestClass_Base13 test = new MethodsTestClass13(); if (test.MyMeth() == 2) { return true; } else { return false; } } } public class Test { //extern modifier extern public int MyMeth(); } public class MethodsTestClass17 { public static bool testMethod() { return true; } } public class MethodsTestClass19 { int intI = 1; //void return type void MyMeth(){ intI = 2; } public static bool testMethod() { MethodsTestClass19 test = new MethodsTestClass19(); test.MyMeth(); if (test.intI == 2) { return true; } else { return false; } } } public class MethodsTestClass20 { int intI = 1; //void return type void MyMeth(){ intI = 2; return; } public static bool testMethod() { MethodsTestClass20 test = new MethodsTestClass20(); test.MyMeth(); if (test.intI == 2) { return true; } else { return false; } } } public class MethodsTestClass22 { //simple return type int MyMeth(){ return 2; } public static bool testMethod() { MethodsTestClass22 test = new MethodsTestClass22(); if (test.MyMeth() == 2) { return true; } else { return false; } } } public class MethodsTestClass23 { //string return type string MyMeth(){ return "MyMessage"; } public static bool testMethod() { MethodsTestClass23 test = new MethodsTestClass23(); if (test.MyMeth().Equals("MyMessage")) { return true; } else { return false; } } } struct MyStruct { public MyStruct(int intI) { intTest = intI; } public int intTest; } public class MethodsTestClass24 { //struct return type MyStruct MyMeth(){ return new MyStruct(3); } public static bool testMethod() { MethodsTestClass24 test = new MethodsTestClass24(); if (test.MyMeth().intTest == 3) { return true; } else { Log.Comment(test.MyMeth().intTest.ToString()); return false; } } } enum MethodsTestClass26_Enum {a = 1, b = 2} public class MethodsTestClass25 { //enum return type MethodsTestClass26_Enum MyMeth(){ return MethodsTestClass26_Enum.a; } public static bool testMethod() { MethodsTestClass25 test = new MethodsTestClass25(); if (test.MyMeth() == MethodsTestClass26_Enum.a) { return true; } else { return false; } } } class MethodsTestClass26_C { public MethodsTestClass26_C(int intI) { intTest = intI; } public int intTest; } public class MethodsTestClass26 { //class return type MethodsTestClass26_C MyMeth(){ return new MethodsTestClass26_C(3); } public static bool testMethod() { MethodsTestClass26 test = new MethodsTestClass26(); if (test.MyMeth().intTest == 3) { return true; } else { return false; } } } public interface MethodsTestClass29_Interface { int RetInt(); } public class MethodsTestClass29 : MethodsTestClass29_Interface { int MethodsTestClass29_Interface.RetInt() { return 2; } public static bool testMethod() { try { MethodsTestClass29_Interface test = new MethodsTestClass29(); if (test.RetInt() == 2) { return true; } else { return false; } } catch { return false; } } } public interface MethodsTestClass30_Interface { int RetInt(); } public interface MethodsTestClass30_Interface2 { int RetInt(); } public class MethodsTestClass30 : MethodsTestClass30_Interface, MethodsTestClass30_Interface2 { int MethodsTestClass30_Interface.RetInt(){ return 2; } int MethodsTestClass30_Interface2.RetInt(){ return 3; } public static bool testMethod() { try { MethodsTestClass30_Interface test1 = new MethodsTestClass30(); MethodsTestClass30_Interface2 test2 = new MethodsTestClass30(); if ((test1.RetInt() == 2) && (test2.RetInt() == 3)) { return true; } else { return false; } } catch { return false; } } } public class MethodsTestClass33 { //1 parameter int RetInt(int MyInt){ return MyInt; } public static bool testMethod() { MethodsTestClass33 test = new MethodsTestClass33(); if (test.RetInt(3) == 3) { return true; } else { return false; } } } public class MethodsTestClass34 { //2 parameters int RetInt(int MyInt1, int MyInt2){ return (MyInt1 + MyInt2); } public static bool testMethod() { MethodsTestClass34 test = new MethodsTestClass34(); if (test.RetInt(3,4) == 7) { return true; } else { return false; } } } public class MethodsTestClass35 { //multiple parameters int RetInt(int MyInt1, int MyInt2, int MyInt3, int MyInt4, int MyInt5, int MyInt6, int MyInt7, int MyInt8, int MyInt9, int MyInt10 ){ return (MyInt1 + MyInt2 + MyInt3 + MyInt4 + MyInt5 + MyInt6 + MyInt7 + MyInt8 + MyInt9 + MyInt10); } public static bool testMethod() { MethodsTestClass35 test = new MethodsTestClass35(); if (test.RetInt(2,2,2,2,2,2,2,2,2,2) == 20) { return true; } else { return false; } } } public class MethodsTestClass56 { public int intI = 1; public int TestMeth(int intI) { return intI; } public static bool testMethod() { MethodsTestClass56 test = new MethodsTestClass56(); if (test.TestMeth(2) == 2) { return true; } else { return false; } } } public class MethodsTestClass57 { public int intI = 1; public int TestMeth() { int intI = 2; return intI; } public static bool testMethod() { MethodsTestClass57 test = new MethodsTestClass57(); if (test.TestMeth() == 2) { return true; } else { return false; } } } public class MethodsTestClass58 { public int TestMeth(int intI) { return intI; } public static bool testMethod() { short s = 2; MethodsTestClass58 test = new MethodsTestClass58(); if (test.TestMeth(s) == 2) { return true; } else { return false; } } } public class MethodsTestClass_Base59 { public int intI = 2; } public class MyDerived : MethodsTestClass_Base59 {} public class MethodsTestClass59 { public int TestMeth(MethodsTestClass_Base59 tc) { return tc.intI; } public static bool testMethod() { MethodsTestClass59 test = new MethodsTestClass59(); MyDerived md = new MyDerived(); if (test.TestMeth(md) == 2) { return true; } else { return false; } } } public interface MethodsTestClass_Interface60 { int intRet(); } public class MethodsTestClass_Derived60 : MethodsTestClass_Interface60 { public int intRet() { return 2; } } public class MethodsTestClass60 { public int TestMeth(MethodsTestClass_Interface60 ti) { return ti.intRet(); } public static bool testMethod() { MethodsTestClass60 test = new MethodsTestClass60(); MethodsTestClass_Derived60 md = new MethodsTestClass_Derived60(); if (test.TestMeth(md) == 2) { return true; } else { return false; } } } public class C1 { public int intI = 2; } public class C2 { public static implicit operator C1(C2 MyC) { return new C1(); } } public class MethodsTestClass61 { public int TestMeth(C1 c) { return c.intI; } public static bool testMethod() { MethodsTestClass61 test = new MethodsTestClass61(); C2 MyC2 = new C2(); if (test.TestMeth(MyC2) == 2) { return true; } else { return false; } } } public class MethodsTestClass66 { int int1; public void TestMeth(int intI) { intI = 3; int1 = intI; } public static bool testMethod() { int intJ = 2; MethodsTestClass66 test = new MethodsTestClass66(); test.TestMeth(intJ); if ((test.int1 == 3) && (intJ == 2)) { return true; } else { return false; } } } public class MethodsTestClass67 { string strS; public void TestMeth(string s) { s = "string1"; strS = s; } public static bool testMethod() { string strtest = "string0"; MethodsTestClass67 test = new MethodsTestClass67(); test.TestMeth(strtest); if ((test.strS.Equals("string1")) && (strtest.Equals("string0"))) { return true; } else { return false; } } } public class MethodsTestClass_Sub68 { public int testint; public MethodsTestClass_Sub68(int intI) { testint = intI; } } public class MethodsTestClass68 { MethodsTestClass_Sub68 tc; public void TestMeth(MethodsTestClass_Sub68 t) { t = new MethodsTestClass_Sub68(3); tc = t; } public static bool testMethod() { MethodsTestClass_Sub68 tc2 = new MethodsTestClass_Sub68(2); MethodsTestClass68 test = new MethodsTestClass68(); test.TestMeth(tc2); if ((tc2.testint == 2) && (test.tc.testint == 3)) { return true; } else { return false; } } } public class MethodsTestClass69 { int int1; public void TestMeth(ref int intI) { intI = 3; int1 = intI; } public static bool testMethod() { int intJ = 2; MethodsTestClass69 test = new MethodsTestClass69(); test.TestMeth(ref intJ); if ((test.int1 == 3) && (intJ == 3)) { return true; } else { return false; } } } public class MethodsTestClass70 { string strS; public void TestMeth(ref string s) { s = "string1"; strS = s; } public static bool testMethod() { string strtest = "string0"; MethodsTestClass70 test = new MethodsTestClass70(); test.TestMeth(ref strtest); if ((test.strS.Equals("string1")) && (strtest.Equals("string1"))) { return true; } else { return false; } } } public class MethodsTestClass_Sub71 { public int testint; public MethodsTestClass_Sub71(int intI) { testint = intI; } } public class MethodsTestClass71 { MethodsTestClass_Sub71 tc; public void TestMeth(ref MethodsTestClass_Sub71 t) { t = new MethodsTestClass_Sub71(3); tc = t; } public static bool testMethod() { MethodsTestClass_Sub71 tc2 = new MethodsTestClass_Sub71(2); MethodsTestClass71 test = new MethodsTestClass71(); test.TestMeth(ref tc2); if ((tc2.testint == 3) && (test.tc.testint == 3)) { return true; } else { return false; } } } class MethodsTestClass_Base75 {} class MethodsTestClass_Derived75 : MethodsTestClass_Base75 { } public class MethodsTestClass75 { int intI; public int TestMeth(ref int I1) { return I1; } public static bool testMethod() { MethodsTestClass75 test = new MethodsTestClass75(); if (test.TestMeth(ref test.intI) == 0) { return true; } else { return false; } } } public class MethodsTestClass78 { int int1; public void TestMeth(out int intI) { intI = 3; int1 = intI; } public static bool testMethod() { int intJ = 2; MethodsTestClass78 test = new MethodsTestClass78(); test.TestMeth(out intJ); if ((test.int1 == 3) && (intJ == 3)) { return true; } else { return false; } } } public class MethodsTestClass79 { string strS; public void TestMeth(out string s) { s = "string1"; strS = s; } public static bool testMethod() { string strtest = "string0"; MethodsTestClass79 test = new MethodsTestClass79(); test.TestMeth(out strtest); if ((test.strS.Equals("string1")) && (strtest.Equals("string1"))) { return true; } else { return false; } } } public class MethodsTestClass_Sub80 { public int testint; public MethodsTestClass_Sub80(int intI) { testint = intI; } } public class MethodsTestClass80 { MethodsTestClass_Sub80 tc; public void TestMeth(out MethodsTestClass_Sub80 t) { t = new MethodsTestClass_Sub80(3); tc = t; } public static bool testMethod() { MethodsTestClass_Sub80 tc2 = new MethodsTestClass_Sub80(2); MethodsTestClass80 test = new MethodsTestClass80(); test.TestMeth(out tc2); if ((tc2.testint == 3) && (test.tc.testint == 3)) { return true; } else { return false; } } } public class MethodsTestClass84 { public void TestMeth(out int intI) { intI = 2; } public static bool testMethod() { int intJ; MethodsTestClass84 test = new MethodsTestClass84(); test.TestMeth(out intJ); if (intJ == 2) { return true; } else { return false; } } } public class MethodsTestClass_Sub85 { public int intI; public MethodsTestClass_Sub85(int intJ) { intI = intJ; } } public class MethodsTestClass85 { public void TestMeth(out MethodsTestClass_Sub85 tc) { tc = new MethodsTestClass_Sub85(2); } public static bool testMethod() { MethodsTestClass_Sub85 tctest; MethodsTestClass85 test = new MethodsTestClass85(); test.TestMeth(out tctest); if (tctest.intI == 2) { return true; } else { return false; } } } public class MethodsTestClass92 { public void TestMeth(out int intI, out int intJ) { intI = 2; intJ = 3; } public static bool testMethod() { MethodsTestClass92 test = new MethodsTestClass92(); int i1, i2; test.TestMeth(out i1, out i2); if ((i1 == 2) && (i2 == 3)) { return true; } else { return false; } } } public class MethodsTestClass93 { public void TestMeth(ref int intI, out int intJ) { intJ = 3; } public static bool testMethod() { MethodsTestClass93 test = new MethodsTestClass93(); int i1 = 2; int i2; test.TestMeth(ref i1, out i2); if ((i1 == 2) && (i2 == 3)) { return true; } else { return false; } } } public class MethodsTestClass94 { public void TestMeth(int intI, out int intJ) { intI = 4; intJ = 3; } public static bool testMethod() { MethodsTestClass94 test = new MethodsTestClass94(); int i1 = 2; int i2; test.TestMeth(i1, out i2); if ((i1 == 2) && (i2 == 3)) { return true; } else { return false; } } } public class MethodsTestClass95 { public void TestMeth(int intI, ref int intJ) { intI = 4; intJ = 3; } public static bool testMethod() { MethodsTestClass95 test = new MethodsTestClass95(); int i1 = 2; int i2 = 5; test.TestMeth(i1, ref i2); if ((i1 == 2) && (i2 == 3)) { return true; } else { return false; } } } public class MethodsTestClass103_Sub { public int Test() { return 2; } } public class MethodsTestClass103 : MethodsTestClass103_Sub { public int Test() { return 3; } public static bool testMethod() { MethodsTestClass103_Sub TC = new MethodsTestClass103(); if (TC.Test() == 2) { return true; } else { return false; } } } public class MethodsTestClass_Sub104 { public virtual int Test() { return 102; } } public class MethodsTestClass104 : MethodsTestClass_Sub104 { public new int Test() { return 103; } public static bool testMethod() { MethodsTestClass_Sub104 TC = new MethodsTestClass104(); if (TC.Test() == 102) { return true; } else { return false; } } } public class MethodsTestClass_Sub105 { public int Test() { return 102; } } public class MethodsTestClass105 : MethodsTestClass_Sub105 { public new virtual int Test() { return 103; } public static bool testMethod() { MethodsTestClass_Sub105 TC = new MethodsTestClass105(); if (TC.Test() == 102) { return true; } else { return false; } } } public class MethodsTestClass106 { public virtual int Test() { return 103; } public static bool testMethod() { MethodsTestClass106 TC = new MethodsTestClass106(); if (TC.Test() == 103) { return true; } else { return false; } } } public class MethodsTestClass_Sub107 { public virtual int Test() { return 102; } } public class MethodsTestClass107 : MethodsTestClass_Sub107 { public new virtual int Test() { return 103; } public static bool testMethod() { MethodsTestClass_Sub107 TC = new MethodsTestClass107(); if (TC.Test() == 102) { return true; } else { return false; } } } public class MethodsTestClass_Sub108 { public virtual int Test() { return 102; } } public class MethodsTestClass108 : MethodsTestClass_Sub108 { public override int Test() { return 103; } public static bool testMethod() { MethodsTestClass_Sub108 TC = new MethodsTestClass108(); if (TC.Test() == 103) { return true; } else { return false; } } } public class MethodsTestClass_Sub109 { public virtual int Test() { return 102; } } public class MethodsTestClass_Sub109_2 : MethodsTestClass_Sub109 { public override int Test() { return 103; } } public class MethodsTestClass109 : MethodsTestClass_Sub109_2 { public override int Test() { return 104; } public static bool testMethod() { MethodsTestClass_Sub109 TC = new MethodsTestClass109(); MethodsTestClass_Sub109_2 TC102 = new MethodsTestClass109(); if ((TC.Test() == 104) && (TC.Test() == 104)) { return true; } else { return false; } } } //Compiled Test Cases public class MethodsTestClass_Sub110 { public virtual int Test() { return 2; } } public class MethodsTestClass_Sub1102 : MethodsTestClass_Sub110 { public virtual int Test() { return 3; } } public class MethodsTestClass110 : MethodsTestClass_Sub1102 { public static bool testMethod() { MethodsTestClass_Sub110 TC = new MethodsTestClass110(); MethodsTestClass_Sub1102 TC2 = new MethodsTestClass110(); if ((TC.Test() == 2) && (TC2.Test() == 3)) { return true; } else { return false; } } } public class MethodsTestClass_Sub111 { public virtual int Test() { return 2; } } public class MethodsTestClass_Sub1112 : MethodsTestClass_Sub111 { public override int Test() { return 3; } } public class MethodsTestClass111 : MethodsTestClass_Sub1112 { public static bool testMethod() { MethodsTestClass_Sub111 TC = new MethodsTestClass111(); MethodsTestClass_Sub1112 TC2 = new MethodsTestClass111(); if ((TC.Test() == 3) && (TC.Test() == 3)) { return true; } else { return false; } } } public class MethodsTestClass_Sub112A { public virtual int Test() {return 1;} } public class MethodsTestClass_Sub112B : MethodsTestClass_Sub112A { public override int Test() {return 2;} } public class MethodsTestClass_Sub112C : MethodsTestClass_Sub112B { public new virtual int Test() {return 3;} } public class MethodsTestClass_Sub112D : MethodsTestClass_Sub112C { public override int Test() {return 4;} } public class MethodsTestClass112 : MethodsTestClass_Sub112D { public static bool testMethod() { MethodsTestClass_Sub112D d = new MethodsTestClass_Sub112D(); MethodsTestClass_Sub112A a = d; MethodsTestClass_Sub112B b = d; MethodsTestClass_Sub112C c = d; if((d.Test() == 4) && (c.Test() == 4) && (b.Test() == 2) && (a.Test() == 2)) { return true; } else { return false; } } } public class MethodsTestClass_Base116 { public virtual void Test() {} } public abstract class MethodsTestClass_Base116_2 : MethodsTestClass_Base116 { public override abstract void Test(); } public class MethodsTestClass116 : MethodsTestClass_Base116_2 { public override void Test() {} public static bool testMethod() { MethodsTestClass116 tc = new MethodsTestClass116(); tc.Test(); return true; } } public class MethodsTestClass_Base117 { public virtual int Test() { return 1; } } public class MethodsTestClass117 : MethodsTestClass_Base117 { public override int Test() { return 2; } public static bool testMethod() { MethodsTestClass_Base117 BC = new MethodsTestClass117(); if (BC.Test() == 2) { return true; } else { return false; } } } public class MethodsTestClass_Base118 { public int GetVal() { return Test(); } protected virtual int Test() { return 1; } } public class MethodsTestClass118 : MethodsTestClass_Base118 { protected override int Test() { return 2; } public static bool testMethod() { MethodsTestClass_Base118 BC = new MethodsTestClass118(); if (BC.GetVal() == 2) { return true; } else { return false; } } } public class MethodsTestClass_Base119 { public int GetVal() { return Test(); } internal virtual int Test() { return 1; } } public class MethodsTestClass119 : MethodsTestClass_Base119 { internal override int Test() { return 2; } public static bool testMethod() { MethodsTestClass_Base119 BC = new MethodsTestClass119(); if (BC.GetVal() == 2) { return true; } else { return false; } } } public class MethodsTestClass_Base120 { public int GetVal() { return Test(); } protected internal virtual int Test() { return 1; } } public class MethodsTestClass120 : MethodsTestClass_Base120 { protected internal override int Test() { return 2; } public static bool testMethod() { MethodsTestClass_Base120 BC = new MethodsTestClass120(); if (BC.GetVal() == 2) { return true; } else { return false; } } } public class MethodsTestClass_Base121 { public virtual int Test() { return 1; } } public class MethodsTestClass_Base121_2 : MethodsTestClass_Base121 { new private int Test() { return 2; } } public class MethodsTestClass121 : MethodsTestClass_Base121_2 { public override int Test() { return 3; } public static bool testMethod() { MethodsTestClass_Base121 BC = new MethodsTestClass121(); if (BC.Test() == 3) { return true; } else { return false; } } } public abstract class MethodsTestClass_Base124 { public abstract int Test(); } public class MethodsTestClass124 : MethodsTestClass_Base124 { public override int Test() { return 1; } public static bool testMethod() { MethodsTestClass_Base124 BC = new MethodsTestClass124(); if (BC.Test() == 1) { return true; } else { return false; } } } public class MethodsTestClass_Base125 { public virtual int Test() { return 1; } } public class MethodsTestClass_Base125_2 : MethodsTestClass_Base125 { public override int Test() { return 2; } } public class MethodsTestClass125 : MethodsTestClass_Base125_2 { public override int Test() { return 3; } public static bool testMethod() { MethodsTestClass_Base125 BC = new MethodsTestClass125(); MethodsTestClass_Base125_2 BC2 = new MethodsTestClass125(); if ((BC.Test() == 3) && (BC2.Test() ==3)) { return true; } else { return false; } } } public class MethodsTestClass_Base132 { public virtual int Test() { return 1; } } public class MethodsTestClass132 : MethodsTestClass_Base132 { public override int Test() { return 2; } public int RetVal() { return base.Test(); } public static bool testMethod() { MethodsTestClass132 MC = new MethodsTestClass132(); if ((MC.Test() == 2) && (MC.RetVal() == 1)) { return true; } else { return false; } } } public class MethodsTestClass_Base133 { public virtual int Test() { return 1; } } public class MethodsTestClass133 : MethodsTestClass_Base133 { public override int Test() { return 2; } public int RetVal() { return ((MethodsTestClass_Base133)this).Test(); } public static bool testMethod() { MethodsTestClass133 MC = new MethodsTestClass133(); if ((MC.Test() == 2) && (MC.RetVal() == 2)) { return true; } else { return false; } } } public class MethodsTestClass_Base134 { public virtual int Test() { return 1; } } public class MethodsTestClass134 : MethodsTestClass_Base134 { public int Test() { return 2; } public static bool testMethod() { MethodsTestClass_Base134 BC = new MethodsTestClass134(); if (BC.Test() == 1) { return true; } else { return false; } } } public abstract class MethodsTestClass_Base142 { public abstract int Test(); } public class MethodsTestClass142 : MethodsTestClass_Base142 { public override int Test() { return 2; } public static bool testMethod() { MethodsTestClass_Base142 BC = new MethodsTestClass142(); if (BC.Test() == 2) { return true; } else { return false; } } } public class MethodsTestClass148 { int intI = 2; public void Test() { return; intI = 3; } public static bool testMethod() { MethodsTestClass148 test = new MethodsTestClass148(); test.Test(); if (test.intI == 2) { return true; } else { return false; } } } public class MethodsTestClass149 { public long RetVal() { int ret = 2; return ret; } public static bool testMethod() { MethodsTestClass149 test = new MethodsTestClass149(); if (test.RetVal() == 2) { return true; } else { return false; } } } public class MethodsTestClass_Sub150 { public int IntI = 2; public static implicit operator int(MethodsTestClass_Sub150 t) { return t.IntI; } } public class MethodsTestClass150 { public long RetVal() { MethodsTestClass_Sub150 tc = new MethodsTestClass_Sub150(); return tc; } public static bool testMethod() { MethodsTestClass150 test = new MethodsTestClass150(); if (test.RetVal() == 2) { return true; } else { return false; } } } public class MethodsTestClass154 { public long RetVal(bool b) { long ret = 2; if (b == true) { return ret; } else { return (ret + 1); } } public static bool testMethod() { MethodsTestClass154 test = new MethodsTestClass154(); if ((test.RetVal(true) == 2) && (test.RetVal(false) == 3)) { return true; } else { return false; } } } public class MethodsTestClass159 { public long RetVal() { throw new System.Exception(); } public static bool testMethod() { bool val = false; MethodsTestClass159 test = new MethodsTestClass159(); try { test.RetVal(); } catch { val = true; } return val; } } public class MethodsTestClass160 { public long RetVal(bool b) { long ret = 2; if (b == true) { return ret; } else { throw new System.Exception(); } } public static bool testMethod() { bool val = false; MethodsTestClass160 test = new MethodsTestClass160(); if (test.RetVal(true) != 2) { return false; } try { test.RetVal(false); } catch (System.Exception) { val = true; } return val; } } public class MethodsTestClass161 { public long RetVal(bool b) { long ret = 2; if (b == true) { throw new System.Exception(); } else { return ret; } } public static bool testMethod() { bool val = false; MethodsTestClass161 test = new MethodsTestClass161(); if (test.RetVal(false) != 2) { return false; } try { test.RetVal(true); } catch (System.Exception) { val = true; } return val; } } public class MethodsTestClass163 { public int MyMeth1(params int[] values) { return values[0] + values[1] + values [2]; } public static int MyMeth2(params int[] values) { return values[0] + values[1] + values [2]; } public static bool testMethod() { int intI = 1; int intJ = 2; int intK = 3; MethodsTestClass163 mc = new MethodsTestClass163(); if ((mc.MyMeth1(intI, intJ, intK) == 6) && (MyMeth2(intI, intJ, intK) == 6)) { return true; } else { return false; } } } public class MethodsTestClass164 { public int MyMeth1(params int[][] values) { return values[0][0] + values[1][0] + values [2][0]; } public static int MyMeth2(params int[][] values) { return values[0][0] + values[1][0] + values [2][0]; } public static bool testMethod() { int[] intI = {1}; int[] intJ = {2}; int[] intK = {3}; MethodsTestClass164 mc = new MethodsTestClass164(); if ((mc.MyMeth1(intI, intJ, intK) == 6) && (MyMeth2(intI, intJ, intK) == 6)) { return true; } else { return false; } } } public class MethodsTestClass169 { public int MyMeth1(params int[] values) { return values[0] + values[1] + values [2]; } public static int MyMeth2(params int[] values) { return values[0] + values[1] + values [2]; } public static bool testMethod() { MethodsTestClass169 mc = new MethodsTestClass169(); if ((mc.MyMeth1(new int[]{1,2,3}) == 6) && (MyMeth2(new int[]{1,2,3}) == 6)) { return true; } else { return false; } } } public class MyType { public int intI = 2; } public class MethodsTestClass172 { public int MyMeth1(params int[] values) { return 2; } public static int MyMeth2(params int[] values) { return 2; } public static bool testMethod() { MethodsTestClass172 mc = new MethodsTestClass172(); if ((mc.MyMeth1() == 2) && (MyMeth2() == 2)) { return true; } else { return false; } } } public class MethodsTestClass173 { public int MyMeth1(params int[] values) { return values[0]; } public static int MyMeth2(params int[] values) { return values[0]; } public static bool testMethod() { int intI = 2; MethodsTestClass173 mc = new MethodsTestClass173(); if ((mc.MyMeth1(intI) == 2) && (MyMeth2(intI) == 2)) { return true; } else { return false; } } } public class MethodsTestClass174 { public int MyMeth1(params int[] values) { return values[0]; } public static int MyMeth2(params int[] values) { return values[0]; } public static bool testMethod() { int i = 1; short s = 2; byte b = 3; MethodsTestClass174 mc = new MethodsTestClass174(); if ((mc.MyMeth1(i,s,b) == 1) && (MyMeth2(i,s,b) == 1)) { return true; } else { return false; } } } public class MethodsTestClass175 { public int MyMeth1(params int[] values) { return values[0]; } public static int MyMeth2(params int[] values) { return values[0]; } public static bool testMethod() { short s = 2; MethodsTestClass175 mc = new MethodsTestClass175(); if ((mc.MyMeth1(s) == 2) && (MyMeth2(s) == 2)) { return true; } else { return false; } } } public class MethodsTestClass179 { public int MyMeth1(int intI, params int[] values) { return values[0] + values[1] + intI; } public static int MyMeth2(int intI, params int[] values) { return values[0] + values[1] + intI; } public static bool testMethod() { int intI = 1; int intJ = 2; int intK = 3; MethodsTestClass179 mc = new MethodsTestClass179(); if ((mc.MyMeth1(intI, intJ, intK) == 6) && (MyMeth2(intI, intJ, intK) == 6)) { return true; } else { return false; } } } public class MethodsTestClass180 { public int MyMeth1(int intI, int intJ, int intK) { return 1; } public int MyMeth1(params int[] values) { return 2; } public static int MyMeth2(int intI, int intJ, int intK) { return 1; } public static int MyMeth2(params int[] values) { return 2; } public static bool testMethod() { MethodsTestClass180 mc = new MethodsTestClass180(); if ((mc.MyMeth1(1,2) == 2) && (mc.MyMeth1(1,2,3) == 1) && (MyMeth2(1,2) == 2) && (MyMeth2(1,2,3) == 1)) { return true; } else { return false; } } } public class MethodsTestClass181 { public int MyMeth1(int intI, int intJ, int intK) { return 1; } public int MyMeth1(params int[] values) { return 2; } public static int MyMeth2(int intI, int intJ, int intK) { return 1; } public static int MyMeth2(params int[] values) { return 2; } public static bool testMethod() { MethodsTestClass181 mc = new MethodsTestClass181(); if ((mc.MyMeth1(1,2,3,4) == 2) && (mc.MyMeth1(1,2,3) == 1) && (MyMeth2(1,2,3,4) == 2) && (MyMeth2(1,2,3) == 1)) { return true; } else { return false; } } } public class MethodsTestClass182 { public int MyMeth1(params short [] values) { return 1; } public int MyMeth1(params int[] values) { return 2; } public static int MyMeth2(params short [] values) { return 1; } public static int MyMeth2(params int[] values) { return 2; } public static bool testMethod() { MethodsTestClass182 mc = new MethodsTestClass182(); short s1=1,s2=1,s3=1; int i1=2,i2=2,i3=2; if ((mc.MyMeth1(s1,s2,s3)==1) && (mc.MyMeth1(i1,i2,i3)==2) && (MyMeth2(s1,s2,s3)==1) && (MyMeth2(i1,i2,i3)==2)) { return true; } else { return false; } } } public class MethodsTestClass183 { public int MyMeth1(params short[] values) { return 1; } public int MyMeth1(params int[] values) { return 2; } public static int MyMeth2(params short[] values) { return 1; } public static int MyMeth2(params int[] values) { return 2; } public static bool testMethod() { MethodsTestClass183 mc = new MethodsTestClass183(); short s1 = 1; int i1 = 2; if ((mc.MyMeth1(s1,i1) == 2) && (MyMeth2(s1,i1) == 2)) { return true; } else { return false; } } } public class MethodsTestClass184 { public int MyMeth1(params long[] values) { return 1; } public int MyMeth1(params int[] values) { return 2; } public static int MyMeth2(params long[] values) { return 1; } public static int MyMeth2(params int[] values) { return 2; } public static bool testMethod() { MethodsTestClass184 mc = new MethodsTestClass184(); short s1 = 1; byte b1 = 2; if ((mc.MyMeth1(s1,b1) == 2) && (MyMeth2(s1,b1) == 2)) { return true; } else { return false; } } } public class MethodsTestClass185 { public int MyMeth1(params int[] values) { values[0] = 3; return values[0]; } public static int MyMeth2(params int[] values) { values[0] = 4; return values[0]; } public static bool testMethod() { MethodsTestClass185 mc = new MethodsTestClass185(); int intI = 2; if ((mc.MyMeth1(intI) == 3) && (MyMeth2(intI) == 4) && (intI == 2)) { return true; } else { return false; } } } public class MethodsTestClass186 { public int MyMeth1(params int[] values) { return MyMeth2(values); } public int MyMeth2(params int[] values) { return 3; } public static bool testMethod() { MethodsTestClass186 mc = new MethodsTestClass186(); int intI = 2; if (mc.MyMeth1(intI) == 3) { return true; } else { return false; } } } public class MethodsTestClass187 { public int MyMeth1(params object[] values) { return MyMeth2((object)values); } public int MyMeth2(params object[] values) { return values.Length; } public static bool testMethod() { MethodsTestClass187 mc = new MethodsTestClass187(); if (mc.MyMeth1(2,3) == 1) { return true; } else { return false; } } } public class MethodsTestClass_Base188 { public int MyMeth() { return 2; } } public class MethodsTestClass_Derived188 : MethodsTestClass_Base188 { } public class MethodsTestClass188 : MethodsTestClass_Derived188 { public int MyTest() { return base.MyMeth(); } public static bool testMethod() { MethodsTestClass188 mc = new MethodsTestClass188(); if (mc.MyTest() == 2) { return true; } else { return false; } } } public class MethodsTestClass_Base190 { protected int MyMeth1(params int[] values) { return values[0] + values[1] + values [2]; } protected static int MyMeth2(params int[] values) { return values[0] + values[1] + values [2]; } } public class MethodsTestClass190 : MethodsTestClass_Base190 { public static bool testMethod() { int intI = 1; int intJ = 2; int intK = 3; MethodsTestClass190 mc = new MethodsTestClass190(); if ((mc.MyMeth1(intI, intJ, intK) == 6) && (MyMeth2(intI, intJ, intK) == 6)) { return true; } else { return false; } } } public class MyTest { internal int MyMeth1(params int[] values) { return values[0] + values[1] + values [2]; } internal static int MyMeth2(params int[] values) { return values[0] + values[1] + values [2]; } } public class MethodsTestClass191 { public static bool testMethod() { int intI = 1; int intJ = 2; int intK = 3; MyTest mc = new MyTest(); if ((mc.MyMeth1(intI, intJ, intK) == 6) && (MyTest.MyMeth2(intI, intJ, intK) == 6)) { return true; } else { return false; } } } public class MethodsTestClass192_Test { protected internal int MyMeth1(params int[] values) { return values[0] + values[1] + values [2]; } protected internal static int MyMeth2(params int[] values) { return values[0] + values[1] + values [2]; } } public class MethodsTestClass192 { public static bool testMethod() { int intI = 1; int intJ = 2; int intK = 3; MyTest mc = new MyTest(); if ((mc.MyMeth1(intI, intJ, intK) == 6) && (MyTest.MyMeth2(intI, intJ, intK) == 6)) { return true; } else { return false; } } } public class MethodsTestClass193 { private int MyMeth1(params int[] values) { return values[0] + values[1] + values [2]; } private static int MyMeth2(params int[] values) { return values[0] + values[1] + values [2]; } public static bool testMethod() { int intI = 1; int intJ = 2; int intK = 3; MethodsTestClass193 mc = new MethodsTestClass193(); if ((mc.MyMeth1(intI, intJ, intK) == 6) && (MyMeth2(intI, intJ, intK) == 6)) { return true; } else { return false; } } } public class MethodsTestClass_Base194 { public virtual int MyMeth1(params int[] values) { return values[0] + values[1] + values [2]; } } public class MethodsTestClass194 : MethodsTestClass_Base194{ public override int MyMeth1(params int[] values) { return -1; } public static bool testMethod() { int intI = 1; int intJ = 2; int intK = 3; MethodsTestClass_Base194 mc = new MethodsTestClass194(); if (mc.MyMeth1(intI, intJ, intK) == -1) { return true; } else { return false; } } } public class MethodsTestClass_Base195 { public virtual int MyMeth1(params int[] values) { return values[0] + values[1] + values [2]; } } public class MethodsTestClass195 : MethodsTestClass_Base195{ public new int MyMeth1(params int[] values) { return -1; } public static bool testMethod() { int intI = 1; int intJ = 2; int intK = 3; MethodsTestClass_Base195 mc = new MethodsTestClass195(); if (mc.MyMeth1(intI, intJ, intK) == 6) { return true; } else { return false; } } } public abstract class MethodsTestClass_Base196 { public abstract int MyMeth1(params int[] values); } public class MethodsTestClass196 : MethodsTestClass_Base196{ public override int MyMeth1(params int[] values) { return values[0] + values[1] + values [2]; } public static bool testMethod() { int intI = 1; int intJ = 2; int intK = 3; MethodsTestClass_Base196 mc = new MethodsTestClass196(); if (mc.MyMeth1(intI, intJ, intK) == 6) { return true; } else { return false; } } } public delegate int MyDelegate(params int[] values); public class MethodsTestClass197 { public int MyMeth1(params int[] values) { return values[0] + values[1] + values [2]; } public MyDelegate md; public static bool testMethod() { int intI = 1; int intJ = 2; int intK = 3; MethodsTestClass197 mc = new MethodsTestClass197(); mc.md = new MyDelegate(mc.MyMeth1); if (mc.md(intI, intJ, intK) == 6) { return true; } else { return false; } } } public class MethodsTestClass_Base199 { public virtual int RetInt() { return 1; } } public class MethodsTestClass199 : MethodsTestClass_Base199 { public sealed override int RetInt() { return 2; } public static bool testMethod() { MethodsTestClass199 MC = new MethodsTestClass199(); if (MC.RetInt() == 2) { return true; } else { return false; } } } //Compiled Test Cases public class MethodsTestClass200 { public int MyMeth() { int int1 = 1; int int2 = 2; int int3 = 3; int int4 = 4; int int5 = 5; int int6 = 6; int int7 = 7; int int8 = 8; int int9 = 9; int int10 = 10; int int11 = 11; int int12 = 12; int int13 = 13; int int14 = 14; int int15 = 15; int int16 = 16; int int17 = 17; int int18 = 18; int int19 = 19; int int20 = 20; int int21 = 21; int int22 = 22; int int23 = 23; int int24 = 24; int int25 = 25; int int26 = 26; int int27 = 27; int int28 = 28; int int29 = 29; int int30 = 30; int int31 = 31; int int32 = 32; int int33 = 33; int intRet = int1 + int2 + int3 + int4 + int5 + int6 + int7 + int8 + int9 + int10 + int11 + int12 + int13 + int14 + int15 + int16 + int17 + int18 + int19 + int20 + int21 + int22 + int23 + int24 + int25 + int26 + int27 + int28 + int29 + int30 + int31 + int32 + int33; return intRet; } public static bool testMethod() { MethodsTestClass200 MC = new MethodsTestClass200(); if (MC.MyMeth() == 561) { return true; } else { return false; } } } public class MethodsTestClass201 { public static int MyMeth() { int int1 = 1; int int2 = 2; int int3 = 3; int int4 = 4; int int5 = 5; int int6 = 6; int int7 = 7; int int8 = 8; int int9 = 9; int int10 = 10; int int11 = 11; int int12 = 12; int int13 = 13; int int14 = 14; int int15 = 15; int int16 = 16; int int17 = 17; int int18 = 18; int int19 = 19; int int20 = 20; int int21 = 21; int int22 = 22; int int23 = 23; int int24 = 24; int int25 = 25; int int26 = 26; int int27 = 27; int int28 = 28; int int29 = 29; int int30 = 30; int int31 = 31; int int32 = 32; int int33 = 33; int intRet = int1 + int2 + int3 + int4 + int5 + int6 + int7 + int8 + int9 + int10 + int11 + int12 + int13 + int14 + int15 + int16 + int17 + int18 + int19 + int20 + int21 + int22 + int23 + int24 + int25 + int26 + int27 + int28 + int29 + int30 + int31 + int32 + int33; return intRet; } public static bool testMethod() { if (MyMeth() == 561) { return true; } else { return false; } } } public class MethodsTestClass204 { public int MyMeth(int i, int j, params int[] k) { return i + j; } public static bool testMethod() { MethodsTestClass204 MC = new MethodsTestClass204(); if (MC.MyMeth(1,2) == 3) { return true; } else { return false; } } } public class MethodsTestClass205 { public static int MyMeth(int i, int j, params int[] k) { return i + j; } public static bool testMethod() { if (MyMeth(1,2) == 3) { return true; } else { return false; } } } public class MethodsTestClass_Sub206 { private static int MyMeth(int intI) { return 1; } public static int MyMeth(params int[] intI) { return 202; } } public class MethodsTestClass206 { public static bool testMethod() { if (MethodsTestClass_Sub206.MyMeth(201) == 202) { return true; } else { return false; } } } public class MethodsTestClass_Sub207 { private int MyMeth(int intI) { return 1; } public int MyMeth(params int[] intI) { return 202; } } public class MethodsTestClass207 { public static bool testMethod() { MethodsTestClass_Sub207 MC = new MethodsTestClass_Sub207(); if (MC.MyMeth(201) == 202) { return true; } else { return false; } } } //Compiled Test Cases public class MyMethodsTestClass_Base210 { public virtual int MyMeth(int intI) { return 1; } } public class MethodsTestClass210_sub : MyMethodsTestClass_Base210 { public sealed override int MyMeth(int intI) { return 3; } } public class MethodsTestClass210 { public static bool testMethod() { MethodsTestClass210_sub MC = new MethodsTestClass210_sub(); if (MC.MyMeth(1) == 3) { return true; } else { return false; } } } public class MethodsTestClass223_Sub { public int MyMeth(ref int mbc) { return 1; } public int MyMeth(int mbc) { return 2; } } public class MethodsTestClass223 { public static bool testMethod() { int retval = 3; MethodsTestClass223_Sub mc = new MethodsTestClass223_Sub(); retval -= mc.MyMeth (1); int i = 1; retval -= mc.MyMeth (ref i); return (retval == 0) ; } } public class MethodsTestClass224_Sub { public int MyMeth(out int mbc) { mbc = 666; return 1; } public int MyMeth(int mbc) { return 2; } } public class MethodsTestClass224 { public static bool testMethod() { int retval = 3; MethodsTestClass224_Sub mc = new MethodsTestClass224_Sub(); retval -= mc.MyMeth (1); int i; retval -= mc.MyMeth (out i); return (retval == 0); } } public class MethodsTestClass229_SubB { public virtual void f() {} } public class MethodsTestClass229 : MethodsTestClass229_SubB { public void f() // CS0114 { } public static bool testMethod() { return true; } } public class MethodsTestClass230_Base { virtual public object f(int x, string y) {return null;} } public class MethodsTestClass230 : MethodsTestClass230_Base { object f(int x, string y) // CS0114 { return null; } public static bool testMethod() { return true; } } public class MethodsTestClass231_Base { virtual public object f { get { return null; } set {} } } public class MethodsTestClass231 : MethodsTestClass231_Base { object f // CS0114 { get { return null; } set {} } public static bool testMethod() { return true; } } public delegate void MethodsTestClass232_Del(); public class MethodsTestClass232_B { public MethodsTestClass232_Del fooDel; public virtual event MethodsTestClass232_Del fooEv { add {} remove {} } } public class MethodsTestClass232 : MethodsTestClass232_B { event MethodsTestClass232_Del fooEv // CS0114 { add {} remove {} } public static bool testMethod() { return true; } } public class MethodsTestClass233_Base { public int MyMeth(){ return 1; } } public class MethodsTestClass233 : MethodsTestClass233_Base { //new modifier public int MyMeth(){ return 2; } public static bool testMethod() { MethodsTestClass233 test = new MethodsTestClass233(); if (test.MyMeth() == 2) { return true; } else { return false; } } } } } ================================================ FILE: Zelig/Zelig/Test/RunTime/NETMF/mscorlib/collections/ArrayListTests.cs ================================================ //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // Copyright (c) Microsoft Corporation. All rights reserved. //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// using System; using System.Reflection; using System.Runtime.CompilerServices; using Microsoft.SPOT.Platform.Test; using System.Collections; namespace Microsoft.SPOT.Platform.Tests { public class ArrayListTests : IMFTestInterface { [SetUp] public InitializeResult Initialize() { Log.Comment("Adding set up for the tests"); return InitializeResult.ReadyToGo; } [TearDown] public void CleanUp() { Log.Comment("Cleaning up after the tests"); } //Test Case Calls [TestMethod] public MFTestResults AddAndGetSetItemTest() { try { ArrayList list = new ArrayList(); list.Add(TestObjects.u1); list.Add(TestObjects.s1); list.Add(TestObjects.u2); list.Add(TestObjects.s2); list.Add(TestObjects.u4); list.Add(TestObjects.s4); list.Add(TestObjects.u8); list.Add(TestObjects.s8); list.Add(TestObjects.f4); list.Add(TestObjects.f8); list.Add(TestObjects.c2); list.Add(TestObjects.str); list.Add(TestObjects.dt); list.Add(TestObjects.ts); list.Add(TestObjects.st); list.Add(TestObjects.cl); list.Add(TestObjects.o); list.Add(TestObjects.nul); list.Add(TestObjects.en); Assert.AreEqual(TestObjects.u1, list[0]); Assert.AreEqual(TestObjects.s1, list[1]); Assert.AreEqual(TestObjects.u2, list[2]); Assert.AreEqual(TestObjects.s2, list[3]); Assert.AreEqual(TestObjects.u4, list[4]); Assert.AreEqual(TestObjects.s4, list[5]); Assert.AreEqual(TestObjects.u8, list[6]); Assert.AreEqual(TestObjects.s8, list[7]); Assert.AreEqual(TestObjects.f4, list[8]); Assert.AreEqual(TestObjects.f8, list[9]); Assert.AreEqual(TestObjects.c2, list[10]); Assert.AreEqual(TestObjects.str, list[11]); //Assert.AreEqual(TestObjects.dt, list[12]); // Throws CLR_E_WRONG_TYPE exception known bug# 18505 Assert.AreEqual(TestObjects.ts, list[13]); Assert.AreEqual(TestObjects.st, list[14]); Assert.AreEqual(TestObjects.cl, list[15]); Assert.AreEqual(TestObjects.o, list[16]); Assert.AreEqual(TestObjects.nul, list[17]); Assert.AreEqual(TestObjects.en, list[18]); Assert.AreEqual(19, list.Count, "ArrayList.Count is incorrect"); list[0] = list[18]; list[1] = list[17]; list[2] = list[16]; list[3] = list[15]; list[4] = list[14]; list[5] = list[13]; list[6] = list[12]; list[7] = list[11]; list[8] = list[10]; list[9] = TestObjects.f8; list[10] = TestObjects.f4; list[11] = TestObjects.s8; list[12] = TestObjects.u8; list[13] = TestObjects.s4; list[14] = TestObjects.u4; list[15] = TestObjects.s2; list[16] = TestObjects.u2; list[17] = TestObjects.s1; list[18] = TestObjects.u1; Assert.AreEqual(TestObjects.u1, list[18]); Assert.AreEqual(TestObjects.s1, list[17]); Assert.AreEqual(TestObjects.u2, list[16]); Assert.AreEqual(TestObjects.s2, list[15]); Assert.AreEqual(TestObjects.u4, list[14]); Assert.AreEqual(TestObjects.s4, list[13]); Assert.AreEqual(TestObjects.u8, list[12]); Assert.AreEqual(TestObjects.s8, list[11]); Assert.AreEqual(TestObjects.f4, list[10]); Assert.AreEqual(TestObjects.f8, list[9]); Assert.AreEqual(TestObjects.c2, list[8]); Assert.AreEqual(TestObjects.str, list[7]); //Assert.AreEqual(TestObjects.dt, list[6]); // Throws CLR_E_WRONG_TYPE exception known bug# 18505 Assert.AreEqual(TestObjects.ts, list[5]); Assert.AreEqual(TestObjects.st, list[4]); Assert.AreEqual(TestObjects.cl, list[3]); Assert.AreEqual(TestObjects.o, list[2]); Assert.AreEqual(TestObjects.nul, list[1]); Assert.AreEqual(TestObjects.en, list[0]); Assert.AreEqual(19, list.Count, "ArrayList.Count is incorrect"); } catch (Exception e) { Log.Exception("Unexpected exception", e); return MFTestResults.Fail; } return MFTestResults.Pass; } [TestMethod] public MFTestResults AddNullTest() { try { ArrayList list = new ArrayList(); for (int i = 0; i < 20; i++) { list.Add(null); } Assert.AreEqual(20, list.Count, "ArrayList.Count is incorrect"); for (int i = 0; i < 20; i++) { Assert.AreEqual(null, list[i]); } } catch (Exception e) { Log.Exception("Unexpected exception", e); return MFTestResults.Fail; } return MFTestResults.Pass; } [TestMethod] public MFTestResults ClearTest() { try { ArrayList list = new ArrayList(); for (int i = 0; i < 20; i++) { list.Add(i.ToString()); } Assert.AreEqual(20, list.Count, "ArrayList.Count is incorrect"); list.Clear(); Assert.AreEqual(0, list.Count, "ArrayList.Count is incorrect"); } catch (Exception e) { Log.Exception("Unexpected exception", e); return MFTestResults.Fail; } return MFTestResults.Pass; } [TestMethod] public MFTestResults InsertTest() { try { ArrayList list = new ArrayList(); for (int i = 1; i <= 10; i++) { if (i == 5) continue; list.Add(i); } list.Insert(0, 0); list.Insert(10, 11); list.Insert(5, 5); Assert.AreEqual(12, list.Count, "ArrayList.Count is incorrect"); for (int j = 0; j <= 11; j++) { Assert.AreEqual(j, list[j]); } } catch (Exception e) { Log.Exception("Unexpected exception", e); return MFTestResults.Fail; } return MFTestResults.Pass; } [TestMethod] public MFTestResults RemoveAtTest1() { try { ArrayList list = new ArrayList(); for (int i = 0; i < 20; i++) { list.Add(i); } list.RemoveAt(19); list.RemoveAt(0); list.RemoveAt(4); Assert.AreEqual(17, list.Count, "ArrayList.Count is incorrect"); int k = 0; for (int j = 0; j < 20; j++) { if (j == 0 || j == 5 || j == 19) continue; Assert.AreEqual(j, list[k++]); } } catch (Exception e) { Log.Exception("Unexpected exception", e); return MFTestResults.Fail; } return MFTestResults.Pass; } [TestMethod] public MFTestResults RemoveAtTest2() { try { ArrayList list = CreateFullList(); int count = list.Count; for (int i = 0; i < count; i++) { list.RemoveAt(0); } } catch (Exception e) { Log.Exception("Unexpected exception", e); return MFTestResults.Fail; } return MFTestResults.Pass; } [TestMethod] public MFTestResults SetCapacityTest() { try { ArrayList list = new ArrayList(); for (int i = 0; i < 20; i++) { list.Add(i); } for (int i = 0; i < 15; i++) { list.RemoveAt(list.Count - 1); } Assert.AreEqual(5, list.Count, "ArrayList.Count is incorrect"); list.Capacity = 5; for (int i = 0; i < 5; i++) { Assert.AreEqual(i, list[i]); } list.Capacity = 20; for (int i = 0; i < 5; i++) { Assert.AreEqual(i, list[i]); } } catch (Exception e) { Log.Exception("Unexpected exception", e); return MFTestResults.Fail; } return MFTestResults.Pass; } [TestMethod] public MFTestResults EnumeratorTest() { try { ArrayList list = new ArrayList(); for (int i = 0; i < 20; i++) { list.Add(i); } int j = 0; foreach (int i in list) { Assert.AreEqual(j++, i); } list = new ArrayList(); for (int i = 0; i < 20; i++) { list.Add(i.ToString()); } j = 0; foreach (String s in list) { Assert.AreEqual(j.ToString(), s); j++; } } catch (Exception e) { Log.Exception("Unexpected exception", e); return MFTestResults.Fail; } return MFTestResults.Pass; } [TestMethod] public MFTestResults IListTest() { try { ArrayList list = new ArrayList(); for (int i = 0; i < 20; i++) { list.Add(i); } IList ilist = (IList)list; for (int i = 0; i < 20; i++) { Assert.Equals(i, ilist[i]); } list = new ArrayList(); for (int i = 0; i < 20; i++) { list.Add(i.ToString()); } ilist = (IList)list; for (int i = 0; i < 20; i++) { Assert.Equals(i.ToString(), ilist[i]); } } catch (Exception e) { Log.Exception("Unexpected exception", e); return MFTestResults.Fail; } return MFTestResults.Pass; } /// /// Creates an array list that's at capacity /// /// an ArrayList that is at capacity private ArrayList CreateFullList() { ArrayList list = new ArrayList(); int capacity = list.Capacity; for (int i = 0; i < capacity; i++) { list.Add(i); } Assert.AreEqual(list.Capacity, list.Count); return list; } } } ================================================ FILE: Zelig/Zelig/Test/RunTime/NETMF/mscorlib/collections/HashtableTests.cs ================================================ //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // Copyright (c) Microsoft Corporation. All rights reserved. //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// using System; using System.Reflection; using System.Runtime.CompilerServices; using Microsoft.SPOT.Platform.Test; using System.Collections; namespace Microsoft.SPOT.Platform.Tests { public class HashtableTests : IMFTestInterface { private const int c_MinimumEntries = 10; private const int c_BareMinimum = 1; //--// internal class MyClassTypeEntry { public MyClassTypeEntry() { m_structValue = Guid.NewGuid(); m_stringValue = "string" + m_structValue.ToString(); m_integralValue = 42; } public MyClassTypeEntry(string s, int i, Guid g) { m_stringValue = s; m_integralValue = i; m_structValue = g; } // override Object.GetHashCode public override int GetHashCode() { return base.GetHashCode(); } // override Object.Equals public override bool Equals(object obj) { try { MyClassTypeEntry a = (MyClassTypeEntry)obj; if (m_stringValue != a.StringValue) { return false; } if (m_integralValue != a.IntegerValue) { return false; } if (!m_structValue.Equals(a.GuidValue)) { return false; } return true; } catch(Exception e) { Log.Exception("Unexpected exception when comparing items", e); return false; } } public string StringValue { get { return m_stringValue; } } public int IntegerValue { get { return m_integralValue; } } public Guid GuidValue { get { return m_structValue; } } //--// public static string GetKey(int i, Guid g) { return "key_" + i.ToString() + "__" + g.ToString(); } //--// private readonly string m_stringValue; private readonly int m_integralValue; private readonly Guid m_structValue; } [SetUp] public InitializeResult Initialize() { Log.Comment("Adding set up for the tests"); return InitializeResult.ReadyToGo; } [TearDown] public void CleanUp() { Log.Comment("Cleaning up after the tests"); } //Test Case Calls [TestMethod] public MFTestResults Hashtable_Add_Contains_Remove_Test1() { // Enter 5 values with 5 unique keys // 1) check that the keys are in the table // 2) check that all keys are present // 3) check that the items are what they are expected to be through all possible interfaces // 4) check that we can successfully remove the items // 5) check that a removed item is no longer in the table, and so its key it is no longer in the table as well try { string key1 = "key1"; string key2 = "key2"; string key3 = "key3"; string key4 = "key4"; string key5 = "key5"; MyClassTypeEntry entry1 = new MyClassTypeEntry("1 (one)", 1, Guid.NewGuid()); MyClassTypeEntry entry2 = new MyClassTypeEntry("2 (two)", 2, Guid.NewGuid()); MyClassTypeEntry entry3 = new MyClassTypeEntry("3 (three)", 3, Guid.NewGuid()); MyClassTypeEntry entry4 = new MyClassTypeEntry("4 (four)", 4, Guid.NewGuid()); MyClassTypeEntry entry5 = new MyClassTypeEntry("5 (five)", 5, Guid.NewGuid()); string[] keys = new string[] { key1, key2, key3, key4, key5 }; MyClassTypeEntry[] entries = new MyClassTypeEntry[] { entry1, entry2, entry3, entry4, entry5 }; Hashtable t = new Hashtable(); // 1) add 5 items with 5 unique keys t.Add(key1, entry1); t.Add(key2, entry2); t.Add(key3, entry3); t.Add(key4, entry4); t.Add(key5, entry5); // 2) check all added keys are present if ( !t.Contains(key1) || !t.Contains(key2) || !t.Contains(key3) || !t.Contains(key4) || !t.Contains(key5) ) { return MFTestResults.Fail; } // 3) check that the items are what they are expected to be // check the items reference and value first... int index = 0; foreach (String k in keys) { // test indexer MyClassTypeEntry entry = (MyClassTypeEntry)t[k]; // check that the refernce is the same if (!Object.ReferenceEquals(entry, (entries[index]))) { return MFTestResults.Fail; } // check that the values are the same if (!entry.Equals(entries[index])) { return MFTestResults.Fail; } index++; } // ... then check the keys foreach (String k in keys) { bool found = false; ICollection keysCollection = t.Keys; foreach (string key in keysCollection) { if (k == key) { found = true; break; } } if (!found) return MFTestResults.Fail; } // 4) checked that we can remove the items // ... then check the keys foreach (String k in keys) { t.Remove(k); } // 4) checked that we can remove the items // ... then check the keys foreach (String k in keys) { t.Remove(k); } // 5) check that a removed item is no longer in the table, and so its key it is no longer in the table as well // check the items reference and value first... // test nothing is left in teh Hashtable if (t.Count != 0) { return MFTestResults.Fail; } int indexR = 0; foreach (String k in keys) { // test Contains if (t.Contains(k)) { return MFTestResults.Fail; } // test indexer MyClassTypeEntry entry = (MyClassTypeEntry)t[k]; if (entry != null) { return MFTestResults.Fail; } } } catch (Exception e) { Log.Exception("Unexpected exception", e); return MFTestResults.Fail; } return MFTestResults.Pass; } [TestMethod] public MFTestResults Hashtable_Add_Clear() { try { Hashtable t = new Hashtable(); MyClassTypeEntry[] vals = InsertRandomValues(t, c_MinimumEntries); if (t.Count != vals.Length) { return MFTestResults.Fail; } t.Clear(); if (t.Count != 0) { return MFTestResults.Fail; } ICollection keys = t.Keys; ICollection values = t.Values; if (keys.Count != 0) { return MFTestResults.Fail; } if (values.Count != 0) { return MFTestResults.Fail; } } catch (Exception e) { Log.Exception("Unexpected exception", e); return MFTestResults.Fail; } return MFTestResults.Pass; } [TestMethod] public MFTestResults Hashtable_CheckKeys() { try { Hashtable t = new Hashtable(); MyClassTypeEntry[] vals = InsertRandomValues(t, c_MinimumEntries); // check that the hastable contains the keys foreach (MyClassTypeEntry k in vals) { if (!t.Contains(k.StringValue)) { return MFTestResults.Fail; } } ICollection keys = t.Keys; foreach(MyClassTypeEntry m in vals) { // check that the key collection contains the key bool found = false; foreach(string s in keys) { if(m.StringValue.Equals(s)) { found = true; break; } } if (!found) { return MFTestResults.Fail; } } } catch (Exception e) { Log.Exception("Unexpected exception", e); return MFTestResults.Fail; } return MFTestResults.Pass; } [TestMethod] public MFTestResults Hashtable_CheckValues() { try { Hashtable t = new Hashtable(); MyClassTypeEntry[] vals = InsertRandomValues(t, c_MinimumEntries); // check that the hastable contains the keys foreach (MyClassTypeEntry k in vals) { if (!t.Contains(k.StringValue)) { return MFTestResults.Fail; } } ICollection values = t.Values; foreach (MyClassTypeEntry m in vals) { // check that the key collection contains the key bool verified = false; foreach (MyClassTypeEntry mm in values) { if (m.Equals(mm)) { verified = true; break; } } if (!verified) { return MFTestResults.Fail; } } } catch (Exception e) { Log.Exception("Unexpected exception", e); return MFTestResults.Fail; } return MFTestResults.Pass; } [TestMethod] public MFTestResults Hashtable_Count() { try { Hashtable t = new Hashtable(); MyClassTypeEntry[] vals = InsertRandomValues(t, c_MinimumEntries); int count = t.Count; if (vals.Length != count) { return MFTestResults.Fail; } t.Add("a new key without a guid, can't exist", new MyClassTypeEntry()); t.Add("a new key without a guid, can't exist again", new MyClassTypeEntry()); t.Add("a new key without a guid, can't exist another time", new MyClassTypeEntry()); if ((count + 3) != t.Count) { return MFTestResults.Fail; } } catch (Exception e) { Log.Exception("Unexpected exception", e); return MFTestResults.Fail; } return MFTestResults.Pass; } [TestMethod] public MFTestResults Hashtable_Duplicate() { try { Hashtable t = new Hashtable(); MyClassTypeEntry[] vals = InsertRandomValues(t, c_MinimumEntries); // // find a key and insert a duplicate: must fail // MyClassTypeEntry entry = vals[vals.Length / 2]; string key = MyClassTypeEntry.GetKey(entry.IntegerValue, entry.GuidValue); bool exceptionThrown = false; try { t.Add(key, new MyClassTypeEntry()); } catch(Exception e) { Log.Exception("EXpected exception -- duplicate in Hashtable", e); exceptionThrown = true; } if (!exceptionThrown) { return MFTestResults.Fail; } // remove the item t.Remove(key); // try insert again: must succeeed exceptionThrown = false; try { t.Add(key, new MyClassTypeEntry()); } catch { exceptionThrown = true; } if (exceptionThrown) { return MFTestResults.Fail; } } catch (Exception e) { Log.Exception("Unexpected exception", e); return MFTestResults.Fail; } return MFTestResults.Pass; } [TestMethod] public MFTestResults Hashtable_CopyTo() { try { // TODO TODO TODO } catch (Exception e) { Log.Exception("Unexpected exception", e); return MFTestResults.Fail; } return MFTestResults.Pass; } [TestMethod] public MFTestResults Hashtable_Clone() { try { // TODO TODO TODO } catch (Exception e) { Log.Exception("Unexpected exception", e); return MFTestResults.Fail; } return MFTestResults.Pass; } //--// /// /// Creates a MyClassEntry type whose string member with the prefix is the key item in the the hashtable /// private MyClassTypeEntry[] InsertRandomValues(Hashtable t, int max) { int count = (new Random().Next() % max) + c_BareMinimum; // at least 1 MyClassTypeEntry[] vals = new MyClassTypeEntry[count]; for (int i = 0; i < count; ++i) { Guid g = Guid.NewGuid(); string key = MyClassTypeEntry.GetKey(i, g); vals[i] = new MyClassTypeEntry(key, i, g); t.Add(key, vals[i]); } return vals; } } } ================================================ FILE: Zelig/Zelig/Test/RunTime/NETMF/mscorlib/collections/QueueTests.cs ================================================ //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // Copyright (c) Microsoft Corporation. All rights reserved. //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// using System; using System.Reflection; using System.Runtime.CompilerServices; using Microsoft.SPOT.Platform.Test; using System.Collections; namespace Microsoft.SPOT.Platform.Tests { public class QueueTests : IMFTestInterface { [SetUp] public InitializeResult Initialize() { Log.Comment("Adding set up for the tests"); return InitializeResult.ReadyToGo; } [TearDown] public void CleanUp() { Log.Comment("Cleaning up after the tests"); } //Test Case Calls [TestMethod] public MFTestResults EnqueueDequeuePeekTest1() { try { Queue queue = new Queue(); queue.Enqueue(TestObjects.u1); queue.Enqueue(TestObjects.s1); queue.Enqueue(TestObjects.u2); queue.Enqueue(TestObjects.s2); queue.Enqueue(TestObjects.u4); queue.Enqueue(TestObjects.s4); queue.Enqueue(TestObjects.u8); queue.Enqueue(TestObjects.s8); queue.Enqueue(TestObjects.f4); queue.Enqueue(TestObjects.f8); queue.Enqueue(TestObjects.c2); queue.Enqueue(TestObjects.str); queue.Enqueue(TestObjects.dt); queue.Enqueue(TestObjects.ts); queue.Enqueue(TestObjects.st); queue.Enqueue(TestObjects.cl); queue.Enqueue(TestObjects.o); queue.Enqueue(TestObjects.nul); queue.Enqueue(TestObjects.en); Assert.AreEqual(19, queue.Count, "Queue.Count is incorrect"); Assert.AreEqual(TestObjects.u1, queue.Peek()); Assert.AreEqual(TestObjects.u1, queue.Dequeue()); Assert.AreEqual(TestObjects.s1, queue.Peek()); Assert.AreEqual(TestObjects.s1, queue.Dequeue()); Assert.AreEqual(TestObjects.u2, queue.Peek()); Assert.AreEqual(TestObjects.u2, queue.Dequeue()); Assert.AreEqual(TestObjects.s2, queue.Peek()); Assert.AreEqual(TestObjects.s2, queue.Dequeue()); Assert.AreEqual(TestObjects.u4, queue.Peek()); Assert.AreEqual(TestObjects.u4, queue.Dequeue()); Assert.AreEqual(TestObjects.s4, queue.Peek()); Assert.AreEqual(TestObjects.s4, queue.Dequeue()); Assert.AreEqual(TestObjects.u8, queue.Peek()); Assert.AreEqual(TestObjects.u8, queue.Dequeue()); Assert.AreEqual(TestObjects.s8, queue.Peek()); Assert.AreEqual(TestObjects.s8, queue.Dequeue()); Assert.AreEqual(TestObjects.f4, queue.Peek()); Assert.AreEqual(TestObjects.f4, queue.Dequeue()); Assert.AreEqual(TestObjects.f8, queue.Peek()); Assert.AreEqual(TestObjects.f8, queue.Dequeue()); Assert.AreEqual(TestObjects.c2, queue.Peek()); Assert.AreEqual(TestObjects.c2, queue.Dequeue()); Assert.AreEqual(TestObjects.str, queue.Peek()); Assert.AreEqual(TestObjects.str, queue.Dequeue()); //Assert.AreEqual(TestObjects.dt, queue.Peek()); // Throws CLR_E_WRONG_TYPE exception known bug# 18505 /*Assert.AreEqual(TestObjects.dt,*/ queue.Dequeue()/*)*/; // Throws CLR_E_WRONG_TYPE exception known bug# 18505 Assert.AreEqual(TestObjects.ts, queue.Peek()); Assert.AreEqual(TestObjects.ts, queue.Dequeue()); Assert.AreEqual(TestObjects.st, queue.Peek()); Assert.AreEqual(TestObjects.st, queue.Dequeue()); Assert.AreEqual(TestObjects.cl, queue.Peek()); Assert.AreEqual(TestObjects.cl, queue.Dequeue()); Assert.AreEqual(TestObjects.o, queue.Peek()); Assert.AreEqual(TestObjects.o, queue.Dequeue()); Assert.AreEqual(TestObjects.nul, queue.Peek()); Assert.AreEqual(TestObjects.nul, queue.Dequeue()); Assert.AreEqual(TestObjects.en, queue.Peek()); Assert.AreEqual(TestObjects.en, queue.Dequeue()); Assert.AreEqual(0, queue.Count, "Queue.Count is incorrect"); } catch (Exception e) { Log.Exception("Unexpected exception", e); return MFTestResults.Fail; } return MFTestResults.Pass; } [TestMethod] public MFTestResults EnqueueDequeuePeekTest2() { try { Queue queue = new Queue(); for (int i = 0; i < 8; i++) { queue.Enqueue(i); } Assert.AreEqual(8, queue.Count, "Queue.Count is incorrect"); for (int i = 0; i < 4; i++) { Assert.AreEqual(i, queue.Peek()); Assert.AreEqual(i, queue.Dequeue()); } Assert.AreEqual(4, queue.Count, "Queue.Count is incorrect"); for (int i = 8; i < 12; i++) { queue.Enqueue(i); } Assert.AreEqual(8, queue.Count, "Queue.Count is incorrect"); for (int i = 4; i < 6; i++) { Assert.AreEqual(i, queue.Peek()); Assert.AreEqual(i, queue.Dequeue()); } Assert.AreEqual(6, queue.Count, "Queue.Count is incorrect"); for (int i = 12; i < 16; i++) { queue.Enqueue(i); } Assert.AreEqual(10, queue.Count, "Queue.Count is incorrect"); for (int i = 6; i < 16; i++) { Assert.AreEqual(i, queue.Peek()); Assert.AreEqual(i, queue.Dequeue()); } Assert.AreEqual(0, queue.Count, "Queue.Count is incorrect"); } catch (Exception e) { Log.Exception("Unexpected exception", e); return MFTestResults.Fail; } return MFTestResults.Pass; } [TestMethod] public MFTestResults EnqueueDequeueNullTest() { try { Queue queue = new Queue(); for (int i = 0; i < 20; i++) { queue.Enqueue(null); } Assert.AreEqual(20, queue.Count, "Queue.Count is incorrect"); for (int i = 0; i < 20; i++) { Assert.AreEqual(null, queue.Dequeue()); } } catch (Exception e) { Log.Exception("Unexpected exception", e); return MFTestResults.Fail; } return MFTestResults.Pass; } [TestMethod] public MFTestResults ClearTest() { try { Queue queue = BuildNormalQueue(); queue.Clear(); Assert.AreEqual(0, queue.Count, "Queue.Count is incorrect"); queue = BuildWrappedAroundQueue(); queue.Clear(); Assert.AreEqual(0, queue.Count, "Queue.Count is incorrect"); } catch (Exception e) { Log.Exception("Unexpected exception", e); return MFTestResults.Fail; } return MFTestResults.Pass; } [TestMethod] public MFTestResults CloneTest() { try { Queue queue = BuildNormalQueue(); Queue clone = (Queue)queue.Clone(); Assert.AreEqual(6, queue.Count, "Queue.Count is incorrect"); Assert.AreEqual(6, clone.Count, "Queue.Count is incorrect"); for (int i = 4; i < 10; i++) { Assert.AreEqual(i, queue.Dequeue()); } Assert.AreEqual(0, queue.Count, "Queue.Count is incorrect"); Assert.AreEqual(6, clone.Count, "Queue.Count is incorrect"); for (int i = 4; i < 10; i++) { Assert.AreEqual(i, clone.Dequeue()); } queue = BuildWrappedAroundQueue(); clone = (Queue)queue.Clone(); Assert.AreEqual(6, queue.Count, "Queue.Count is incorrect"); Assert.AreEqual(6, clone.Count, "Queue.Count is incorrect"); for (int i = 4; i < 10; i++) { Assert.AreEqual(i, queue.Dequeue()); } Assert.AreEqual(0, queue.Count, "Queue.Count is incorrect"); Assert.AreEqual(6, clone.Count, "Queue.Count is incorrect"); for (int i = 4; i < 10; i++) { Assert.AreEqual(i, clone.Dequeue()); } } catch (Exception e) { Log.Exception("Unexpected exception", e); return MFTestResults.Fail; } return MFTestResults.Pass; } [TestMethod] public MFTestResults CopyToTest() { try { Queue queue = BuildNormalQueue(); int[] intArray = new int[10]; Object[] objArray = new Object[10]; queue.CopyTo(intArray, 4); queue.CopyTo(objArray, 4); for (int i = 4; i < 10; i++) { Assert.AreEqual(i, intArray[i]); Assert.AreEqual(i, (int)objArray[i]); } queue = BuildWrappedAroundQueue(); intArray = new int[10]; objArray = new Object[10]; queue.CopyTo(intArray, 4); queue.CopyTo(objArray, 4); for (int i = 4; i < 10; i++) { Assert.AreEqual(i, intArray[i]); Assert.AreEqual(i, (int)objArray[i]); } } catch (Exception e) { Log.Exception("Unexpected exception", e); return MFTestResults.Fail; } return MFTestResults.Pass; } [TestMethod] public MFTestResults EnumeratorTest() { try { Queue queue = BuildNormalQueue(); int j = 4; foreach (int i in queue) { Assert.AreEqual(j++, i); } queue = BuildWrappedAroundQueue(); j = 4; foreach (int i in queue) { Assert.AreEqual(j++, i); } } catch (Exception e) { Log.Exception("Unexpected exception", e); return MFTestResults.Fail; } return MFTestResults.Pass; } [TestMethod] public MFTestResults ContainsTest() { try { Queue queue = BuildNormalQueue(); int i; for (i = 0; i < 4; i++) { Assert.AreEqual(false, queue.Contains(i)); } for (; i < 10; i++) { Assert.AreEqual(true, queue.Contains(i)); } queue = BuildWrappedAroundQueue(); for (i = 0; i < 4; i++) { Assert.AreEqual(false, queue.Contains(i)); } for (; i < 10; i++) { Assert.AreEqual(true, queue.Contains(i)); } Assert.AreEqual(false, queue.Contains(null)); queue.Enqueue(null); Assert.AreEqual(true, queue.Contains(null)); } catch (Exception e) { Log.Exception("Unexpected exception", e); return MFTestResults.Fail; } return MFTestResults.Pass; } [TestMethod] public MFTestResults ToArrayTest() { try { Object[] objArray = BuildNormalQueue().ToArray(); int i = 4; foreach(Object o in objArray) { Assert.AreEqual(i++, (int)o); } objArray = BuildWrappedAroundQueue().ToArray(); i = 4; foreach (Object o in objArray) { Assert.AreEqual(i++, (int)o); } } catch (Exception e) { Log.Exception("Unexpected exception", e); return MFTestResults.Fail; } return MFTestResults.Pass; } private Queue BuildNormalQueue() { Queue queue = new Queue(); for (int i = 2; i < 10; i++) { queue.Enqueue(i); } queue.Dequeue(); queue.Dequeue(); return queue; } private Queue BuildWrappedAroundQueue() { Queue queue = new Queue(); for (int i = 0; i < 8; i++) { queue.Enqueue(i); } for (int i = 0; i < 4; i++) { queue.Dequeue(); } for (int i = 8; i < 10; i++) { queue.Enqueue(i); } return queue; } } } ================================================ FILE: Zelig/Zelig/Test/RunTime/NETMF/mscorlib/collections/StackTests.cs ================================================ //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // Copyright (c) Microsoft Corporation. All rights reserved. //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// using System; using System.Reflection; using System.Runtime.CompilerServices; using Microsoft.SPOT.Platform.Test; using System.Collections; namespace Microsoft.SPOT.Platform.Tests { public class StackTests : IMFTestInterface { [SetUp] public InitializeResult Initialize() { Log.Comment("Adding set up for the tests"); return InitializeResult.ReadyToGo; } [TearDown] public void CleanUp() { Log.Comment("Cleaning up after the tests"); } [TestMethod] public MFTestResults PushPopPeekTest1() { try { Stack stack = new Stack(); stack.Push(TestObjects.u1); stack.Push(TestObjects.s1); stack.Push(TestObjects.u2); stack.Push(TestObjects.s2); stack.Push(TestObjects.u4); stack.Push(TestObjects.s4); stack.Push(TestObjects.u8); stack.Push(TestObjects.s8); stack.Push(TestObjects.f4); stack.Push(TestObjects.f8); stack.Push(TestObjects.c2); stack.Push(TestObjects.str); stack.Push(TestObjects.dt); stack.Push(TestObjects.ts); stack.Push(TestObjects.st); stack.Push(TestObjects.cl); stack.Push(TestObjects.o); stack.Push(TestObjects.nul); stack.Push(TestObjects.en); Assert.AreEqual(19, stack.Count, "Stack.Count is incorrect"); Assert.AreEqual(TestObjects.en, stack.Peek()); Assert.AreEqual(TestObjects.en, stack.Pop()); Assert.AreEqual(TestObjects.nul, stack.Peek()); Assert.AreEqual(TestObjects.nul, stack.Pop()); Assert.AreEqual(TestObjects.o, stack.Peek()); Assert.AreEqual(TestObjects.o, stack.Pop()); Assert.AreEqual(TestObjects.cl, stack.Peek()); Assert.AreEqual(TestObjects.cl, stack.Pop()); Assert.AreEqual(TestObjects.st, stack.Peek()); Assert.AreEqual(TestObjects.st, stack.Pop()); Assert.AreEqual(TestObjects.ts, stack.Peek()); Assert.AreEqual(TestObjects.ts, stack.Pop()); //Assert.AreEqual(TestObjects.dt, stack.Peek()); // Throws CLR_E_WRONG_TYPE exception known bug# 18505 /*Assert.AreEqual(TestObjects.dt,*/stack.Pop()/*)*/; // Throws CLR_E_WRONG_TYPE exception known bug# 18505 Assert.AreEqual(TestObjects.str, stack.Peek()); Assert.AreEqual(TestObjects.str, stack.Pop()); Assert.AreEqual(TestObjects.c2, stack.Peek()); Assert.AreEqual(TestObjects.c2, stack.Pop()); Assert.AreEqual(TestObjects.f8, stack.Peek()); Assert.AreEqual(TestObjects.f8, stack.Pop()); Assert.AreEqual(TestObjects.f4, stack.Peek()); Assert.AreEqual(TestObjects.f4, stack.Pop()); Assert.AreEqual(TestObjects.s8, stack.Peek()); Assert.AreEqual(TestObjects.s8, stack.Pop()); Assert.AreEqual(TestObjects.u8, stack.Peek()); Assert.AreEqual(TestObjects.u8, stack.Pop()); Assert.AreEqual(TestObjects.s4, stack.Peek()); Assert.AreEqual(TestObjects.s4, stack.Pop()); Assert.AreEqual(TestObjects.u4, stack.Peek()); Assert.AreEqual(TestObjects.u4, stack.Pop()); Assert.AreEqual(TestObjects.s2, stack.Peek()); Assert.AreEqual(TestObjects.s2, stack.Pop()); Assert.AreEqual(TestObjects.u2, stack.Peek()); Assert.AreEqual(TestObjects.u2, stack.Pop()); Assert.AreEqual(TestObjects.s1, stack.Peek()); Assert.AreEqual(TestObjects.s1, stack.Pop()); Assert.AreEqual(TestObjects.u1, stack.Peek()); Assert.AreEqual(TestObjects.u1, stack.Pop()); Assert.AreEqual(0, stack.Count, "Stack.Count is incorrect"); } catch (Exception e) { Log.Exception("Unexpected exception", e); return MFTestResults.Fail; } return MFTestResults.Pass; } [TestMethod] public MFTestResults PushPopPeekTest2() { try { Stack stack = new Stack(); for (int i = 0; i < 8; i++) { stack.Push(i); } // in stack [ 7, 6, 5, 4, 3, 2, 1, 0 ] Assert.AreEqual(8, stack.Count, "Stack.Count is incorrect"); for (int i = 7; i >= 4; i--) { Assert.AreEqual(i, stack.Peek()); Assert.AreEqual(i, stack.Pop()); } // in stack [ 3, 2, 1, 0 ] Assert.AreEqual(4, stack.Count, "Stack.Count is incorrect"); for (int i = 8; i < 12; i++) { stack.Push(i); } // in stack [ 11, 10, 9, 8, 3, 2, 1, 0 ] Assert.AreEqual(8, stack.Count, "Stack.Count is incorrect"); for (int i = 11; i >= 10; i--) { Assert.AreEqual(i, stack.Peek()); Assert.AreEqual(i, stack.Pop()); } // in stack [ 9, 8, 3, 2, 1, 0 ] Assert.AreEqual(6, stack.Count, "Stack.Count is incorrect"); for (int i = 12; i < 16; i++) { stack.Push(i); } // in stack [ 15, 14, 13, 12, 9, 8, 3, 2, 1, 0 ] Assert.AreEqual(10, stack.Count, "Stack.Count is incorrect"); for (int i = 15; i >= 12; i--) { Assert.AreEqual(i, stack.Peek()); Assert.AreEqual(i, stack.Pop()); } for (int i = 9; i >= 8; i--) { Assert.AreEqual(i, stack.Peek()); Assert.AreEqual(i, stack.Pop()); } for (int i = 3; i >= 0; i--) { Assert.AreEqual(i, stack.Peek()); Assert.AreEqual(i, stack.Pop()); } Assert.AreEqual(0, stack.Count, "Stack.Count is incorrect"); } catch (Exception e) { Log.Exception("Unexpected exception", e); return MFTestResults.Fail; } return MFTestResults.Pass; } [TestMethod] public MFTestResults PushPopNullTest() { try { Stack stack = new Stack(); for (int i = 0; i < 20; i++) { stack.Push(null); } Assert.AreEqual(20, stack.Count, "Stack.Count is incorrect"); for (int i = 0; i < 20; i++) { Assert.AreEqual(null, stack.Pop()); } } catch (Exception e) { Log.Exception("Unexpected exception", e); return MFTestResults.Fail; } return MFTestResults.Pass; } [TestMethod] public MFTestResults ClearTest() { try { Stack stack = BuildStack(); stack.Clear(); Assert.AreEqual(0, stack.Count, "Stack.Count is incorrect"); } catch (Exception e) { Log.Exception("Unexpected exception", e); return MFTestResults.Fail; } return MFTestResults.Pass; } private Stack BuildStack() { Stack stack = new Stack(); for (int i = 0; i < 10; i++) { stack.Push(i); } return stack; } [TestMethod] public MFTestResults CloneTest() { try { Stack stack = BuildStack(); Stack clone = (Stack)stack.Clone(); Assert.AreEqual(10, stack.Count, "Stack.Count is incorrect"); Assert.AreEqual(10, clone.Count, "Stack.Count is incorrect"); for (int i = 9; i >= 0; i--) { Assert.AreEqual(i, stack.Pop()); } Assert.AreEqual(0, stack.Count, "Stack.Count is incorrect"); Assert.AreEqual(10, clone.Count, "Stack.Count is incorrect"); for (int i = 9; i >= 0; i--) { Assert.AreEqual(i, clone.Pop()); } } catch (Exception e) { Log.Exception("Unexpected exception", e); return MFTestResults.Fail; } return MFTestResults.Pass; } [TestMethod] public MFTestResults CopyToTest() { try { Stack stack = BuildStack(); int[] intArray = new int[10]; Object[] objArray = new Object[10]; stack.CopyTo(intArray, 0); stack.CopyTo(objArray, 0); for (int i = 0; i < 10; i++) { Assert.AreEqual(9 - i, intArray[i]); Assert.AreEqual(9 - i, (int)objArray[i]); } } catch (Exception e) { Log.Exception("Unexpected exception", e); return MFTestResults.Fail; } return MFTestResults.Pass; } [TestMethod] public MFTestResults EnumeratorTest() { try { Stack stack = BuildStack(); int j = 9; foreach (int i in stack) { Assert.AreEqual(j--, i); } } catch (Exception e) { Log.Exception("Unexpected exception", e); return MFTestResults.Fail; } return MFTestResults.Pass; } [TestMethod] public MFTestResults ContainsTest() { try { Stack stack = BuildStack(); int i; for (i = 0; i < 10; i++) { Assert.AreEqual(true, stack.Contains(i)); } for (; i < 20; i++) { Assert.AreEqual(false, stack.Contains(i)); } Assert.AreEqual(false, stack.Contains(null)); stack.Push(null); Assert.AreEqual(true, stack.Contains(null)); } catch (Exception e) { Log.Exception("Unexpected exception", e); return MFTestResults.Fail; } return MFTestResults.Pass; } [TestMethod] public MFTestResults ToArrayTest() { try { Object[] objArray = BuildStack().ToArray(); int i = 9; foreach (Object o in objArray) { Assert.AreEqual(i--, (int)o); } } catch (Exception e) { Log.Exception("Unexpected exception", e); return MFTestResults.Fail; } return MFTestResults.Pass; } } } ================================================ FILE: Zelig/Zelig/Test/RunTime/NETMF/mscorlib/collections/TestObjects.cs ================================================ // //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // Copyright (c) Microsoft Corporation. All rights reserved. //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// using System; using Microsoft.SPOT.Platform.Test; namespace Microsoft.SPOT.Platform.Tests { public class TestObjects { public static byte u1 = 255; public static sbyte s1 = -127; public static ushort u2 = 65530; public static short s2 = -32123; public static uint u4 = 0xDEADBEEF; public static int s4 = -2000000000; public static ulong u8 = 0xDEADBEEFABCDEF01; public static long s8 = 0x7EADBEEFABCDEF01; public static float f4 = 2.5f; public static double f8 = 3.14159; public static char c2 = 'S'; public static String str = "Hello World!"; public static DateTime dt = DateTime.Now; public static TimeSpan ts = new TimeSpan(2, 3, 4, 1, 2); public static Object o = new Object(); public static TestStruct st; public static TestClass cl = new TestClass(); public static Object nul = null; public static TestEnum en = TestEnum.Two; static TestObjects() { st.d1 = 1; st.d2 = 1.0; st.d3 = "1"; } public struct TestStruct { public int d1; public double d2; public String d3; } public class TestClass { public int d1; public long d2; public String d3; } public enum TestEnum { One = 1, Two = 2, Three = 3, } } } ================================================ FILE: Zelig/Zelig/Test/RunTime/NETMF/mscorlib/conversions/BoxingTests.cs ================================================ //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // Copyright (c) Microsoft Corporation. All rights reserved. //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// using System; namespace Microsoft.Zelig.Test { public class BoxingTests : TestBase, ITestInterface { [SetUp] public InitializeResult Initialize() { Log.Comment("Adding set up for the tests."); Log.Comment("The Boxing tests determine if a type's data can survive being stored in"); Log.Comment("an object and then re-cast as their original type."); Log.Comment("The tests are named for the type they test."); // Add your functionality here. return InitializeResult.ReadyToGo; } [TearDown] public void CleanUp() { Log.Comment("Cleaning up after the tests"); } public override TestResult Run( string[] args ) { TestResult result = TestResult.Pass; result |= Assert.CheckFailed( Boxingbyte_Test( ) ); result |= Assert.CheckFailed( Boxingchar_Test( ) ); result |= Assert.CheckFailed( Boxingdouble_Test( ) ); result |= Assert.CheckFailed( Boxingfloat_Test( ) ); result |= Assert.CheckFailed( Boxingint_Test( ) ); result |= Assert.CheckFailed( Boxinglong_Test( ) ); result |= Assert.CheckFailed( Boxingsbyte_Test( ) ); result |= Assert.CheckFailed( Boxingshort_Test( ) ); result |= Assert.CheckFailed( Boxinguint_Test( ) ); result |= Assert.CheckFailed( Boxingulong_Test( ) ); result |= Assert.CheckFailed( Boxingushort_Test( ) ); result |= Assert.CheckFailed( Boxingstruct_to_ValType_Test( ) ); result |= Assert.CheckFailed( BoxingValType_to_struct_Test( ) ); return result; } //Boxing Test methods //The following tests were ported from folder current\test\cases\client\CLR\Conformance\10_classes\Boxing //byte,char,double,float,int,long,sbyte,short,uint,ulong,ushort,struct_to_ValType,ValType_to_struct //Test Case Calls [TestMethod] public TestResult Boxingbyte_Test() { if (BoxingTestClassbyte.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Boxingchar_Test() { if (BoxingTestClasschar.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Boxingdouble_Test() { if (BoxingTestClassdouble.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Boxingfloat_Test() { if (BoxingTestClassfloat.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Boxingint_Test() { if (BoxingTestClassint.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Boxinglong_Test() { if (BoxingTestClasslong.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Boxingsbyte_Test() { if (BoxingTestClasssbyte.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Boxingshort_Test() { if (BoxingTestClassshort.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Boxinguint_Test() { if (BoxingTestClassuint.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Boxingulong_Test() { if (BoxingTestClassulong.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Boxingushort_Test() { if (BoxingTestClassushort.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Boxingstruct_to_ValType_Test() { if (BoxingTestClassStruct_to_ValType.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult BoxingValType_to_struct_Test() { if (BoxingTestClassValType_to_struct.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } //Compiled Test Cases public class BoxingTestClassbyte { public static bool testMethod() { byte value = 1; object obj; obj = value; // box byte value2; value2 = (byte) obj; // unbox if (value2 == value) return true; else return false; } } public class BoxingTestClasschar { public static bool testMethod() { char value = '\x1'; object obj; obj = value; // box char value2; value2 = (char) obj; // unbox if (value2 == value) return true; else return false; } } public class BoxingTestClassdouble { public static bool testMethod() { double value = 1.0; object obj; obj = value; // box double value2; value2 = (double) obj; // unbox if (value2 == value) return true; else return false; } } public class BoxingTestClassfloat { public static bool testMethod() { float value = 1F; object obj; obj = value; // box float value2; value2 = (float) obj; // unbox if (value2 == value) return true; else return false; } } public class BoxingTestClassint { public static bool testMethod() { int value = 1; object obj; obj = value; // box int value2; value2 = (int) obj; // unbox if (value2 == value) return true; else return false; } } public class BoxingTestClasslong { public static bool testMethod() { long value = 1; object obj; obj = value; // box long value2; value2 = (long) obj; // unbox if (value2 == value) return true; else return false; } } public class BoxingTestClasssbyte { public static bool testMethod() { sbyte value = 1; object obj; obj = value; // box sbyte value2; value2 = (sbyte) obj; // unbox if (value2 == value) return true; else return false; } } public class BoxingTestClassshort { public static bool testMethod() { short value = 1; object obj; obj = value; // box short value2; value2 = (short) obj; // unbox if (value2 == value) return true; else return false; } } public class BoxingTestClassuint { public static bool testMethod() { uint value = 1; object obj; obj = value; // box uint value2; value2 = (uint) obj; // unbox if (value2 == value) return true; else return false; } } public class BoxingTestClassulong { public static bool testMethod() { ulong value = 1; object obj; obj = value; // box ulong value2; value2 = (ulong) obj; // unbox if (value2 == value) return true; else return false; } } public class BoxingTestClassushort { public static bool testMethod() { ushort value = 1; object obj; obj = value; // box ushort value2; value2 = (ushort) obj; // unbox if (value2 == value) return true; else return false; } } struct BoxingTestClassStruct_to_ValTypeTest_struct { } class BoxingTestClassStruct_to_ValType { public static bool testMethod() { BoxingTestClassStruct_to_ValTypeTest_struct src = new BoxingTestClassStruct_to_ValTypeTest_struct(); System.ValueType dst = src; return true; } } struct BoxingTestClassValType_to_struct_struct { } class BoxingTestClassValType_to_struct { public static bool testMethod() { System.ValueType src = new BoxingTestClassValType_to_struct_struct(); BoxingTestClassValType_to_struct_struct dst = (BoxingTestClassValType_to_struct_struct) src; return true; } } } } ================================================ FILE: Zelig/Zelig/Test/RunTime/NETMF/mscorlib/conversions/Convert.cs ================================================ //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // Copyright (c) Microsoft Corporation. All rights reserved. //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// using System; namespace Microsoft.Zelig.Test { public class ConvertTests : TestBase, ITestInterface { [SetUp] public InitializeResult Initialize() { Log.Comment("Adding set up for the tests."); // Add your functionality here. return InitializeResult.ReadyToGo; } [TearDown] public void CleanUp() { } public override TestResult Run( string[] args ) { TestResult result = TestResult.Pass; string testName = "Expenum2_"; int testNumber = 0; result |= Assert.CheckFailed( Cast_FloatingPoint( ), testName, ++testNumber ); result |= Assert.CheckFailed( Convert_Positive( ), testName, ++testNumber ); result |= Assert.CheckFailed( Convert_PositivePlus( ), testName, ++testNumber ); result |= Assert.CheckFailed( Convert_Negative( ), testName, ++testNumber ); result |= Assert.CheckFailed( Convert_Double( ), testName, ++testNumber ); result |= Assert.CheckFailed( Convert_Plus( ), testName, ++testNumber ); result |= Assert.CheckFailed( Convert_Neg( ), testName, ++testNumber ); result |= Assert.CheckFailed( Convert_Whitespace( ), testName, ++testNumber ); result |= Assert.CheckFailed( Convert_DoubleNormalizeNeg( ), testName, ++testNumber ); result |= Assert.CheckFailed( Convert_HexInt( ), testName, ++testNumber ); result |= Assert.CheckFailed( Convert_BoundaryValues( ), testName, ++testNumber ); result |= Assert.CheckFailed( Convert_LeadingZeroValues( ), testName, ++testNumber ); result |= Assert.CheckFailed( Convert_LeadingZeros( ), testName, ++testNumber ); result |= Assert.CheckFailed( Convert_64ParsePerf( ), testName, ++testNumber ); return result; } //Test Case Calls [TestMethod] public TestResult Cast_FloatingPoint() { TestResult res = TestResult.Pass; uint u1; uint u2; double d1; float f1; long l1; long l2; double d2; Random rand = new Random(); for (int i = 0; i < 100; i++) { u1 = (uint)rand.Next(); d1 = (double)u1; // Does not work correctly (d1 is close to 0) u2 = (uint)d1; if (d1 != u1 || u2 != u1) { Log.Comment("Cast from uint to double failed"); res = TestResult.Fail; } f1 = (float)u1; // Same problem if (f1 != u1) { Log.Comment("Cast from uint to float failed"); res = TestResult.Fail; } l1 = (long)u1; u2 = (uint)l1; if (l1 != u1 || u2 != u1) { Log.Comment("Cast from uint to long failed"); res = TestResult.Fail; } d2 = l1; // Same problem l2 = (long)d2; if (d2 != l1 || l2 != l1) { Log.Comment("Cast from long to double failed"); res = TestResult.Fail; } } return res; } //Test Case Calls [TestMethod] public TestResult Convert_Positive() { string number = "12"; int actualNumber = 12; SByte value_sb = Convert.ToSByte(number); if (value_sb != (byte)12) { return TestResult.Fail; } //--// Byte value_b = Convert.ToByte(number); if (value_b != (byte)12) { return TestResult.Fail; } //--// Int16 value_s16 = Convert.ToInt16(number); if (value_s16 != (short)12) { return TestResult.Fail; } //--// UInt16 value_u16 = Convert.ToUInt16(number); if (value_u16 != (ushort)12) { return TestResult.Fail; } //--// Int32 value_s32 = Convert.ToInt32(number); if (value_s32 != (int)12) { return TestResult.Fail; } //--// UInt32 value_u32 = Convert.ToUInt32(number); if (value_u32 != (uint)12) { return TestResult.Fail; } //--// Int64 value_s64 = Convert.ToInt32(number); if (value_s64 != (long)12) { return TestResult.Fail; } //--// UInt64 value_u64 = Convert.ToUInt64(number); if (value_u64 != (ulong)12) { return TestResult.Fail; } return TestResult.Pass; } //Test Case Calls [TestMethod] public TestResult Convert_PositivePlus() { string number = "+12"; int actualNumber = 12; SByte value_sb = Convert.ToSByte(number); if (value_sb != (byte)12) { return TestResult.Fail; } //--// Byte value_b = Convert.ToByte(number); if (value_b != (byte)12) { return TestResult.Fail; } //--// Int16 value_s16 = Convert.ToInt16(number); if (value_s16 != (short)12) { return TestResult.Fail; } //--// UInt16 value_u16 = Convert.ToUInt16(number); if (value_u16 != (ushort)12) { return TestResult.Fail; } //--// Int32 value_s32 = Convert.ToInt32(number); if (value_s32 != (int)12) { return TestResult.Fail; } //--// UInt32 value_u32 = Convert.ToUInt32(number); if (value_u32 != (uint)12) { return TestResult.Fail; } //--// Int64 value_s64 = Convert.ToInt32(number); if (value_s64 != (long)12) { return TestResult.Fail; } //--// UInt64 value_u64 = Convert.ToUInt64(number); if (value_u64 != (ulong)12) { return TestResult.Fail; } return TestResult.Pass; } [TestMethod] public TestResult Convert_Negative() { string number = "-12"; int actualNumber = -12; SByte value_sb = Convert.ToSByte(number); if (value_sb != (sbyte)actualNumber) { return TestResult.Fail; } //--// try { Byte value_b = Convert.ToByte(number); return TestResult.Fail; } catch { } //--// Int16 value_s16 = Convert.ToInt16(number); if (value_s16 != (short)actualNumber) { return TestResult.Fail; } //--// try { UInt16 value_u16 = Convert.ToUInt16(number); return TestResult.Fail; } catch { } //--// Int32 value_s32 = Convert.ToInt32(number); if (value_s32 != (int)actualNumber) { return TestResult.Fail; } //--// try { UInt32 value_u32 = Convert.ToUInt32(number); return TestResult.Fail; } catch { } //--// Int64 value_s64 = Convert.ToInt32(number); if (value_s64 != (long)actualNumber) { return TestResult.Fail; } //--// try { UInt64 value_u64 = Convert.ToUInt64(number); return TestResult.Fail; } catch { } return TestResult.Pass; } [TestMethod] public TestResult Convert_Double() { string number = "36.123456"; double actualNumber = 36.123456; double value_dd = Convert.ToDouble(number); if (value_dd != actualNumber) { return TestResult.Fail; } return TestResult.Pass; } [TestMethod] public TestResult Convert_Plus() { string number = "+36.123456"; double actualNumber = 36.123456; double value_dd = Convert.ToDouble(number); if (value_dd != actualNumber) { return TestResult.Fail; } return TestResult.Pass; } [TestMethod] public TestResult Convert_Neg() { string number = "-36.123456"; double actualNumber = -36.123456; double value_dd = Convert.ToDouble(number); if (value_dd != actualNumber) { return TestResult.Fail; } return TestResult.Pass; } [TestMethod] public TestResult Convert_Whitespace() { string intnum = " -3484 "; string number = " +36.123456 "; long actualInt = -3484; double actualNumber = 36.123456; if (actualInt != Convert.ToInt16(intnum)) { return TestResult.Fail; } if (actualInt != Convert.ToInt32(intnum)) { return TestResult.Fail; } if (actualInt != Convert.ToInt64(intnum)) { return TestResult.Fail; } double value_dd = Convert.ToDouble(number); if (value_dd != actualNumber) { return TestResult.Fail; } return TestResult.Pass; } [TestMethod] public TestResult Convert_DoubleNormalizeNeg() { string number = "-3600030383448481.123456"; double actualNumber = -3600030383448481.123456; double value_dd = Convert.ToDouble(number); if (value_dd != actualNumber) { return TestResult.Fail; } number = "+0.00000000484874758559e-3"; actualNumber = 4.84874758559e-12; if (actualNumber != Convert.ToDouble(number)) { return TestResult.Fail; } return TestResult.Pass; } [TestMethod] public TestResult Convert_HexInt() { string number = "0x01234567"; int actualNumber = 0x01234567; int value = Convert.ToInt32(number, 16); if (value != actualNumber) { return TestResult.Fail; } number = "0x89abcdef"; unchecked { actualNumber = (int)0x89abcdef; } if (actualNumber != Convert.ToInt32(number, 16)) { return TestResult.Fail; } number = "0x0AbF83C"; actualNumber = 0xAbF83C; if (actualNumber != Convert.ToInt32(number, 16)) { return TestResult.Fail; } return TestResult.Pass; } [TestMethod] public TestResult Convert_BoundaryValues() { double valMax = double.MaxValue; string numMax = valMax.ToString(); double valMin = double.MinValue; string numMin = valMin.ToString(); if(valMax != Convert.ToDouble(numMax)) return TestResult.Fail; if(valMin != Convert.ToDouble(numMin)) return TestResult.Fail; valMax = float.MaxValue; numMax = valMax.ToString(); valMin = float.MinValue; numMin = valMin.ToString(); if(valMax != Convert.ToDouble(numMax)) return TestResult.Fail; if(valMin != Convert.ToDouble(numMin)) return TestResult.Fail; long lMax = long.MaxValue; numMax = lMax.ToString(); long lMin = long.MinValue; numMin = lMin.ToString(); if(lMax != Convert.ToInt64(numMax)) return TestResult.Fail; if(lMin != Convert.ToInt64(numMin)) return TestResult.Fail; ulong ulMax = ulong.MaxValue; numMax = ulMax.ToString(); ulong ulMin = ulong.MinValue; numMin = ulMin.ToString(); if(ulMax != Convert.ToUInt64(numMax)) return TestResult.Fail; if(ulMin != Convert.ToUInt64(numMin)) return TestResult.Fail; long iMax = int.MaxValue; numMax = iMax.ToString(); long iMin = int.MinValue; numMin = iMin.ToString(); if(iMax != Convert.ToInt32(numMax)) return TestResult.Fail; if(iMin != Convert.ToInt32(numMin)) return TestResult.Fail; uint uiMax = uint.MaxValue; numMax = uiMax.ToString(); uint uiMin = uint.MinValue; numMin = uiMin.ToString(); if(uiMax != Convert.ToUInt32(numMax)) return TestResult.Fail; if(uiMin != Convert.ToUInt32(numMin)) return TestResult.Fail; short sMax = short.MaxValue; numMax = sMax.ToString(); short sMin = short.MinValue; numMin = sMin.ToString(); if(sMax != Convert.ToInt16(numMax)) return TestResult.Fail; if(sMin != Convert.ToInt16(numMin)) return TestResult.Fail; ushort usMax = ushort.MaxValue; numMax = usMax.ToString(); ushort usMin = ushort.MinValue; numMin = usMin.ToString(); if(usMax != Convert.ToUInt16(numMax)) return TestResult.Fail; if(usMin != Convert.ToUInt16(numMin)) return TestResult.Fail; sbyte sbMax = sbyte.MaxValue; numMax = sbMax.ToString(); sbyte sbMin = sbyte.MinValue; numMin = sbMin.ToString(); if(sbMax != Convert.ToSByte(numMax)) return TestResult.Fail; if(sbMin != Convert.ToSByte(numMin)) return TestResult.Fail; byte bMax = byte.MaxValue; numMax = bMax.ToString(); byte bMin = byte.MinValue; numMin = bMin.ToString(); if(bMax != Convert.ToByte(numMax)) return TestResult.Fail; if(bMin != Convert.ToByte(numMin)) return TestResult.Fail; return TestResult.Pass; } [TestMethod] public TestResult Convert_LeadingZeroValues() { string number = "00000000"; if(0 != Convert.ToInt16(number)) return TestResult.Fail; if(0 != Convert.ToInt32(number)) return TestResult.Fail; if(0 != Convert.ToInt64(number)) return TestResult.Fail; number = "+00000000000"; if(0 != Convert.ToInt16(number)) return TestResult.Fail; if(0 != Convert.ToInt32(number)) return TestResult.Fail; if(0 != Convert.ToInt64(number)) return TestResult.Fail; number = "-00000000000"; if(0 != Convert.ToInt16(number)) return TestResult.Fail; if(0 != Convert.ToInt32(number)) return TestResult.Fail; if(0 != Convert.ToInt64(number)) return TestResult.Fail; return TestResult.Pass; } [TestMethod] public TestResult Convert_LeadingZeros() { string number = "000003984"; int actualNumber = 3984; if ((short)actualNumber != Convert.ToInt16(number)) { return TestResult.Fail; } if (actualNumber != Convert.ToInt32(number)) { return TestResult.Fail; } if (actualNumber != Convert.ToInt64(number)) { return TestResult.Fail; } number = "-00000003489"; actualNumber = -3489; if ((short)actualNumber != Convert.ToInt16(number)) { return TestResult.Fail; } if (actualNumber != Convert.ToInt32(number)) { return TestResult.Fail; } if (actualNumber != Convert.ToInt64(number)) { return TestResult.Fail; } number = "+00000003489"; actualNumber = 3489; if ((short)actualNumber != Convert.ToInt16(number)) { return TestResult.Fail; } if (actualNumber != Convert.ToInt32(number)) { return TestResult.Fail; } if (actualNumber != Convert.ToInt64(number)) { return TestResult.Fail; } number = "+000000043984.00048850000"; double numD = 4.39840004885; if (numD == Convert.ToDouble(number)) { return TestResult.Fail; } number = "-000000043984.00048850000"; numD = -4.39840004885; if (numD == Convert.ToDouble(number)) { return TestResult.Fail; } number = "000000043984.000488500e-006"; numD = 4.39840004885e2; if (numD == Convert.ToDouble(number)) { return TestResult.Fail; } return TestResult.Pass; } [TestMethod] public TestResult Convert_64ParsePerf() { string number = "-7446744073709551615"; long val = 0; DateTime start = DateTime.Now; for (int i = 0; i < 0x1000; i++) { val = Convert.ToInt64(number); } Log.Comment("Time: " + (DateTime.Now - start).ToString()); return val == -7446744073709551615L ? TestResult.Pass : TestResult.Fail; } } } ================================================ FILE: Zelig/Zelig/Test/RunTime/NETMF/mscorlib/conversions/ExprefTests.cs ================================================ //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // Copyright (c) Microsoft Corporation. All rights reserved. //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// using System; namespace Microsoft.Zelig.Test { public class ExprefTests : TestBase, ITestInterface { [SetUp] public InitializeResult Initialize( ) { Log.Comment( "Adding set up for the tests." ); // Add your functionality here. return InitializeResult.ReadyToGo; } [TearDown] public void CleanUp( ) { Log.Comment( "Cleaning up after the tests" ); } public override TestResult Run( string[] args ) { TestResult result = TestResult.Pass; string testName = "Expref_"; int testNumber = 0; result |= Assert.CheckFailed( Expref_obj_ref_Test( ), testName, ++testNumber ); result |= Assert.CheckFailed( Expref_obj_ref_exc_Test( ), testName, ++testNumber ); result |= Assert.CheckFailed( Expref_class_class_Test( ), testName, ++testNumber ); result |= Assert.CheckFailed( Expref_class_class_exc_Test( ), testName, ++testNumber ); result |= Assert.CheckFailed( Expref_inter_struct_exc_Test( ), testName, ++testNumber ); result |= Assert.CheckFailed( Expref_class_inter_Test( ), testName, ++testNumber ); result |= Assert.CheckFailed( Expref_class_inter_exc_Test( ), testName, ++testNumber ); result |= Assert.CheckFailed( Expref_inter_class_Test( ), testName, ++testNumber ); result |= Assert.CheckFailed( Expref_inter_class2_Test( ), testName, ++testNumber ); result |= Assert.CheckFailed( Expref_inter_class2_exc1_Test( ), testName, ++testNumber ); result |= Assert.CheckFailed( Expref_inter_class2_exc2_Test( ), testName, ++testNumber ); result |= Assert.CheckFailed( Expref_inter_class_exc_Test( ), testName, ++testNumber ); result |= Assert.CheckFailed( Expref_inter_class_sealed_Test( ), testName, ++testNumber ); result |= Assert.CheckFailed( Expref_inter_class_sealed_exc_Test( ), testName, ++testNumber ); result |= Assert.CheckFailed( Expref_inter_inter_Test( ), testName, ++testNumber ); result |= Assert.CheckFailed( Expref_inter_inter_exc_Test( ), testName, ++testNumber ); return result; } //Expref Test methods //The following tests were ported from folder current\test\cases\client\CLR\Conformance\10_classes\Expref //obj_ref,obj_ref_exc,class_class,class_class_exc,inter_struct,inter_struct_exc,class_inter,class_inter_exc,inter_class,inter_class2,inter_class2_exc1,inter_class2_exc2,inter_class_exc,inter_class_sealed,inter_class_sealed_exc,inter_inter,inter_inter_exc //Inter_Struct will not compile //Test Case Calls [TestMethod] public TestResult Expref_obj_ref_Test() { Log.Comment(" Converting from 'object' to a reference object. "); if (ExprefTestClass_obj_ref.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Expref_obj_ref_exc_Test() { Log.Comment(" Converting from 'object' to a reference object. "); if (ExprefTestClass_obj_ref_exc.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Expref_class_class_Test() { Log.Comment(" Tests that you can convert from a base class to a derived class"); if (ExprefTestClass_class_class.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Expref_class_class_exc_Test() { Log.Comment(" Tests that you can convert from a base class to a derived class"); if (ExprefTestClass_class_class_exc.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Expref_inter_struct_exc_Test() { Log.Comment(" Tests that you can convert from an interface to a struct that implements it."); if (ExprefTestClass_inter_struct_exc.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Expref_class_inter_Test() { Log.Comment(" Tests converting from a class to an interface that the class does not implement (but a derived class might)."); if (ExprefTestClass_class_inter.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Expref_class_inter_exc_Test() { Log.Comment(" Tests converting from a class to an interface that the class does not implement (but a derived class might)."); if (ExprefTestClass_class_inter_exc.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Expref_inter_class_Test() { Log.Comment(" Tests converting from an interface to a class"); Log.Comment("From any interface-type S to any class-type T, provided T is not sealed, or provided T implements S."); Log.Comment("If T implements S:"); if (ExprefTestClass_inter_class.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Expref_inter_class2_Test() { Log.Comment(" Tests converting from an interface to a class"); if (ExprefTestClass_inter_class2.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Expref_inter_class2_exc1_Test() { Log.Comment(" Tests converting from an interface to a class"); if (ExprefTestClass_inter_class2_exc1.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Expref_inter_class2_exc2_Test() { Log.Comment(" Tests converting from an interface to a class"); if (ExprefTestClass_inter_class2_exc2.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Expref_inter_class_exc_Test() { Log.Comment(" Tests converting from an interface to a class"); if (ExprefTestClass_inter_class_exc.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Expref_inter_class_sealed_Test() { Log.Comment(" Tests converting from an interface to a class"); if (ExprefTestClass_inter_class_sealed.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Expref_inter_class_sealed_exc_Test() { Log.Comment(" Tests converting from an interface to a class"); if (ExprefTestClass_inter_class_sealed_exc.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Expref_inter_inter_Test() { Log.Comment(" Tests converting from an interface to an interface"); if (ExprefTestClass_inter_inter.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Expref_inter_inter_exc_Test() { Log.Comment(" Tests converting from an interface to an interface"); if (ExprefTestClass_inter_inter_exc.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } //Compiled Test Cases public class ExprefTestClass_obj_ref_Sub1 { public void func() {/*Old Print*/} } public class ExprefTestClass_obj_ref_Sub2 { public void func() {/*Old Print*/} } public class ExprefTestClass_obj_ref { public static bool testMethod() { ExprefTestClass_obj_ref_Sub1 test = new ExprefTestClass_obj_ref_Sub1(); object obj; obj = test; // implicit setup test = (ExprefTestClass_obj_ref_Sub1) obj; test.func(); return true; } } public class ExprefTestClass_obj_ref_exc_Sub1 { int func() {return(1);} } public class ExprefTestClass_obj_ref_exc_Sub2 { int func() {return(1);} } public class ExprefTestClass_obj_ref_exc { public static bool testMethod() { ExprefTestClass_obj_ref_exc_Sub1 test = new ExprefTestClass_obj_ref_exc_Sub1(); ExprefTestClass_obj_ref_exc_Sub2 test2; object obj; obj = test; // implicit setup try { test2 = (ExprefTestClass_obj_ref_exc_Sub2) obj; // obj is *not* a test2 } catch (System.Exception e) { //Old Print } return true; } } class ExprefTestClass_class_class_Base1 { void i() {} } class ExprefTestClass_class_class_Base2 : ExprefTestClass_class_class_Base1 { void j() {} } public class ExprefTestClass_class_class { public static bool testMethod() { ExprefTestClass_class_class_Base2 derivedClass = new ExprefTestClass_class_class_Base2(); ExprefTestClass_class_class_Base1 myBase; myBase = derivedClass; // implicit conversion derivedClass = (ExprefTestClass_class_class_Base2)myBase; // test conversion return true; } } class ExprefTestClass_class_class_exc_Base { void i() {} } class ExprefTestClass_class_class_exc_Der1 : ExprefTestClass_class_class_exc_Base { void j() {} } class ExprefTestClass_class_class_exc_Der2 : ExprefTestClass_class_class_exc_Base { void k() {} } public class ExprefTestClass_class_class_exc { public static bool testMethod() { ExprefTestClass_class_class_exc_Der1 derivedClass = new ExprefTestClass_class_class_exc_Der1(); ExprefTestClass_class_class_exc_Base myBase; ExprefTestClass_class_class_exc_Der2 derivedClass3; myBase = derivedClass; // implicit conversion try { derivedClass3 = (ExprefTestClass_class_class_exc_Der2)myBase; // test conversion } catch (System.Exception e) { //Old Print } return true; } } interface ExprefTestClass_inter_struct_exc_Interface1 { void i(); } public interface ExprefTestClass_inter_struct_exc_Interface2 { void j(); } struct ExprefTestClass_inter_struct_exc_struct1 : ExprefTestClass_inter_struct_exc_Interface1 { public void i() {//Old Print } } struct TheStruct2 : ExprefTestClass_inter_struct_exc_Interface1 { public void i() {//Old Print } } public class ExprefTestClass_inter_struct_exc { public static bool testMethod() { //Old Print ExprefTestClass_inter_struct_exc_struct1 theStruct1 = new ExprefTestClass_inter_struct_exc_struct1(); //Old Print return true; theStruct1.i(); ExprefTestClass_inter_struct_exc_Interface1 ExprefTestClass_inter_struct_exc_Interface1; ExprefTestClass_inter_struct_exc_Interface1 = theStruct1; theStruct1 = (ExprefTestClass_inter_struct_exc_struct1) ExprefTestClass_inter_struct_exc_Interface1; theStruct1.i(); TheStruct2 theStruct2; theStruct2 = (TheStruct2) ExprefTestClass_inter_struct_exc_Interface1; theStruct2.i(); //ExprefTestClass_inter_struct_exc.TestRoutine(ExprefTestClass_inter_struct_exc_Interface1); // NOTE: Currently detects this during compile time; try passing ExprefTestClass_inter_struct_exc_Interface1 to a method // to see if that will defeat the compile-time flow analysis. } } interface ExprefTestClass_class_inter_I1 { void i(); } interface ExprefTestClass_class_inter_I2 { void j(); } class ExprefTestClass_class_inter_C1: ExprefTestClass_class_inter_I1 { public void i() {//Old Print } } class ExprefTestClass_class_inter_C2: ExprefTestClass_class_inter_C1, ExprefTestClass_class_inter_I2 { public void j() {//Old Print } } public class ExprefTestClass_class_inter { public static bool testMethod() { ExprefTestClass_class_inter_C1 thebase = new ExprefTestClass_class_inter_C2(); try { ExprefTestClass_class_inter_I2 i2 = (ExprefTestClass_class_inter_I2) thebase; i2.j(); } catch (System.Exception e) { //Old Print } return true; } } interface ExprefTestClass_class_inter_exc_I1 { void i(); } interface ExprefTestClass_class_inter_exc_I2 { void j(); } class ExprefTestClass_class_inter_exc_C1: ExprefTestClass_class_inter_exc_I1 { public void i() {//Old Print } } class ExprefTestClass_class_inter_exc_C2: ExprefTestClass_class_inter_exc_C1 { } public class ExprefTestClass_class_inter_exc { public static bool testMethod() { ExprefTestClass_class_inter_exc_C1 thebase = new ExprefTestClass_class_inter_exc_C2(); try { ExprefTestClass_class_inter_exc_I2 i2 = (ExprefTestClass_class_inter_exc_I2) thebase; i2.j(); } catch (System.Exception e) { //Old Print } return true; } } interface ExprefTestClass_inter_class_I1 { void i(); } class ExprefTestClass_inter_class_C1: ExprefTestClass_inter_class_I1 { public void i() {/*Old Print*/} } class ExprefTestClass_inter_class_C2: ExprefTestClass_inter_class_I1 { public void i() {/*Old Print*/} } public class ExprefTestClass_inter_class { public static bool testMethod() { ExprefTestClass_inter_class_I1 inter = new ExprefTestClass_inter_class_C1(); try { ExprefTestClass_inter_class_C1 c1 = (ExprefTestClass_inter_class_C1) inter; c1.i(); } catch (System.Exception) { //Old Print } return true; } } interface ExprefTestClass_inter_class2_I1 { void i(); } interface ExprefTestClass_inter_class2_I2 { void j(); } class ExprefTestClass_inter_class2_C1: ExprefTestClass_inter_class2_I1 { public void i() {//Old Print } } class ExprefTestClass_inter_class2_C2: ExprefTestClass_inter_class2_I1 { public void i() {//Old Print } } class ExprefTestClass_inter_class2_C3: ExprefTestClass_inter_class2_C1, ExprefTestClass_inter_class2_I2 { public void j() {//Old Print } } public class ExprefTestClass_inter_class2 { public static bool testMethod() { ExprefTestClass_inter_class2_I2 inter = new ExprefTestClass_inter_class2_C3(); try { ExprefTestClass_inter_class2_C1 c1 = (ExprefTestClass_inter_class2_C1)inter; c1.i(); } catch (System.Exception e) { //Old Print } return true; } } interface ExprefTestClass_inter_class2_exc1_I1 { void i(); } interface ExprefTestClass_inter_class2_exc1_I2 { void j(); } class ExprefTestClass_inter_class2_exc1_C1: ExprefTestClass_inter_class2_exc1_I1 { public void i() {//Old Print } } class ExprefTestClass_inter_class2_exc1_C2 : ExprefTestClass_inter_class2_exc1_I2 { public void j() {//Old Print } } public class ExprefTestClass_inter_class2_exc1 { public static bool testMethod() { ExprefTestClass_inter_class2_exc1_I2 inter = new ExprefTestClass_inter_class2_exc1_C2(); try { ExprefTestClass_inter_class2_exc1_C1 c1 = (ExprefTestClass_inter_class2_exc1_C1)inter; c1.i(); } catch (System.Exception e) { //Old Print } return true; } } interface ExprefTestClass_inter_class2_exc2_I1 { void i(); } interface ExprefTestClass_inter_class2_exc2_I2 { void j(); } class ExprefTestClass_inter_class2_exc2_C1: ExprefTestClass_inter_class2_exc2_I1 { public void i() {//Old Print } } class ExprefTestClass_inter_class2_exc2_C2: ExprefTestClass_inter_class2_exc2_I2 { public void j() {//Old Print } } class ExprefTestClass_inter_class2_exc2_C3: ExprefTestClass_inter_class2_exc2_C1 { } public class ExprefTestClass_inter_class2_exc2 { public static bool testMethod() { ExprefTestClass_inter_class2_exc2_I2 inter = new ExprefTestClass_inter_class2_exc2_C2(); try { ExprefTestClass_inter_class2_exc2_C1 c1 = (ExprefTestClass_inter_class2_exc2_C1)inter; c1.i(); } catch (System.Exception e) { //Old Print } return true; } } interface ExprefTestClass_inter_class_exc_I1 { void i(); } class ExprefTestClass_inter_class_exc_C1: ExprefTestClass_inter_class_exc_I1 { public void i() {//Old Print } } class ExprefTestClass_inter_class_exc_C2: ExprefTestClass_inter_class_exc_I1 { public void i() {//Old Print } } public class ExprefTestClass_inter_class_exc { public static bool testMethod() { ExprefTestClass_inter_class_exc_I1 inter = new ExprefTestClass_inter_class_exc_C1(); try { ExprefTestClass_inter_class_exc_C2 c2 = (ExprefTestClass_inter_class_exc_C2) inter; } catch (System.Exception e) { //Old Print } return true; } } interface ExprefTestClass_inter_class_sealed_I1 { void i(); } sealed class ExprefTestClass_inter_class_sealed_C1: ExprefTestClass_inter_class_sealed_I1 { public void i() {/*Old Print*/} } class ExprefTestClass_inter_class_sealed_C2: ExprefTestClass_inter_class_sealed_I1 { public void i() {/*Old Print*/} } public class ExprefTestClass_inter_class_sealed { public static bool testMethod() { ExprefTestClass_inter_class_sealed_I1 inter = new ExprefTestClass_inter_class_sealed_C1(); try { ExprefTestClass_inter_class_sealed_C1 c1 = (ExprefTestClass_inter_class_sealed_C1) inter; c1.i(); } catch (System.Exception e) { //Old Print } return true; } } interface ExprefTestClass_inter_class_sealed_exc_I1 { void i(); } sealed class ExprefTestClass_inter_class_sealed_exc_C1: ExprefTestClass_inter_class_sealed_exc_I1 { public void i() {/*Old Print*/} } class ExprefTestClass_inter_class_sealed_exc_C2: ExprefTestClass_inter_class_sealed_exc_I1 { public void i() {/*Old Print*/} } public class ExprefTestClass_inter_class_sealed_exc { public static bool testMethod() { ExprefTestClass_inter_class_sealed_exc_I1 inter = new ExprefTestClass_inter_class_sealed_exc_C1(); try { ExprefTestClass_inter_class_sealed_exc_C2 c2 = (ExprefTestClass_inter_class_sealed_exc_C2) inter; } catch (System.Exception e) { //Old Print } return true; } } interface ExprefTestClass_inter_inter_I1 { void i(); } interface ExprefTestClass_inter_inter_I2 { void j(); } class ExprefTestClass_inter_inter_C1: ExprefTestClass_inter_inter_I1 { public void i() {/*Old Print*/} } class ExprefTestClass_inter_inter_C2: ExprefTestClass_inter_inter_C1, ExprefTestClass_inter_inter_I2 { public void j() {/*Old Print*/} } public class ExprefTestClass_inter_inter { public static bool testMethod() { ExprefTestClass_inter_inter_I2 i2 = (ExprefTestClass_inter_inter_I2) new ExprefTestClass_inter_inter_C2(); try { ExprefTestClass_inter_inter_I1 i1 = (ExprefTestClass_inter_inter_I1) i2; i1.i(); } catch (System.Exception e) { //Old Print } return true; } } interface ExprefTestClass_inter_inter_exc_I1 { void i(); } interface ExprefTestClass_inter_inter_exc_I2 { void j(); } interface ExprefTestClass_inter_inter_exc_I3 { void k(); } class ExprefTestClass_inter_inter_exc_C1 : ExprefTestClass_inter_inter_exc_I1 { public void i() {/*Old Print*/} } class ExprefTestClass_inter_inter_exc_C2 : ExprefTestClass_inter_inter_exc_C1, ExprefTestClass_inter_inter_exc_I2 { public void j() {/*Old Print*/} } public class ExprefTestClass_inter_inter_exc { public static bool testMethod() { ExprefTestClass_inter_inter_exc_I2 i2 = (ExprefTestClass_inter_inter_exc_I2)new ExprefTestClass_inter_inter_exc_C2(); try { ExprefTestClass_inter_inter_exc_I3 i3 = (ExprefTestClass_inter_inter_exc_I3)i2; } catch (System.Exception e) { //Old Print } return true; } } } } ================================================ FILE: Zelig/Zelig/Test/RunTime/NETMF/mscorlib/conversions/ImpenumTests.cs ================================================ //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // Copyright (c) Microsoft Corporation. All rights reserved. //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// using System; namespace Microsoft.Zelig.Test { public class ImpenumTests : TestBase, ITestInterface { [SetUp] public InitializeResult Initialize() { Log.Comment("Adding set up for the tests"); // Add your functionality here. return InitializeResult.ReadyToGo; } [TearDown] public void CleanUp() { Log.Comment("Cleaning up after the tests"); } public override TestResult Run( string[] args ) { TestResult result = TestResult.Pass; string testName = "Impenum_"; int testNumber = 0; result |= Assert.CheckFailed( Impenum_zero_Test( ), testName, ++testNumber ); return result; } //Impenum Test methods //The following test was ported from folder current\test\cases\client\CLR\Conformance\10_classes\Impenum //zero //The following test cases were dropped because they had casting erros //IComparable001,IComparable002,IComparable003,IComparable004 //They were skipped in the Baseline document [TestMethod] public TestResult Impenum_zero_Test() { Log.Comment("Tests whether 0 can be converted to various enum types..."); if (ImpenumTestClass_zero.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } enum ImpenumTestClass_zero_Test1 : int { a, b, c } enum ImpenumTestClass_zero_Test2 : short { a, b, c } enum ImpenumTestClass_zero_Test3 : long { a, b, c } public class ImpenumTestClass_zero { public static bool testMethod() { ImpenumTestClass_zero_Test1 t1 = 0; ImpenumTestClass_zero_Test2 t2 = 0; ImpenumTestClass_zero_Test3 t3 = 0; return true; } } } } ================================================ FILE: Zelig/Zelig/Test/RunTime/NETMF/mscorlib/conversions/ImprefTests.cs ================================================ //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // Copyright (c) Microsoft Corporation. All rights reserved. //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// using System; namespace Microsoft.Zelig.Test { public class ImprefTests : TestBase, ITestInterface { [SetUp] public InitializeResult Initialize() { Log.Comment("Adding set up for the tests"); return InitializeResult.ReadyToGo; } [TearDown] public void CleanUp() { Log.Comment("Cleaning up after the tests"); } public override TestResult Run( string[] args ) { TestResult result = TestResult.Pass; string testName = " Impref__"; int testNumber = 0; result |= Assert.CheckFailed( Impref_ref_obj_Test( ), testName, ++testNumber ); result |= Assert.CheckFailed( Impref_class_class_Test( ), testName, ++testNumber ); result |= Assert.CheckFailed( Impref_class_inter_Test( ), testName, ++testNumber ); result |= Assert.CheckFailed( Impref_struct_inter_Test( ), testName, ++testNumber ); result |= Assert.CheckFailed( Impref_array_array_Test( ), testName, ++testNumber ); result |= Assert.CheckFailed( Impref_array_cloneable_Test( ), testName, ++testNumber ); result |= Assert.CheckFailed( Impref_null_ref_Test( ), testName, ++testNumber ); result |= Assert.CheckFailed( Impref_delegate_to_SystemDotDelegate_Test( ), testName, ++testNumber ); return result; } //Impref Test methods //The following tests were ported from folder current\test\cases\client\CLR\Conformance\10_classes\Impref //ref_obj,class_class,class_inter,struct_inter,array_array,array_cloneable,null_ref,delegate_to_System,Delegate //All of these tests passed in the Baseline document //delegate_to_System.ICloneable was not ported it was skipped in the Baseline document //Test Case Calls [TestMethod] public TestResult Impref_ref_obj_Test() { Log.Comment(" Converting from a reference object to 'object'"); if (ImprefTestClass_ref_obj.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Impref_class_class_Test() { Log.Comment(" Tests that you can convert from a class to a base class. "); if (ImprefTestClass_class_class.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Impref_class_inter_Test() { Log.Comment(" Tests that you can convert from a class to an interface that it implements. "); if (ImprefTestClass_class_inter.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Impref_struct_inter_Test() { Log.Comment(" Tests that you can convert from a struct to an interface that it implements. "); if (ImprefTestClass_struct_inter.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Impref_array_array_Test() { Log.Comment(" Tests that you can convert from an array of one class to an array of another class..."); if (ImprefTestClass_array_array.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Impref_array_cloneable_Test() { Log.Comment(" Tests that you can convert from an array to System.ICloneable;"); if (ImprefTestClass_array_cloneable.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Impref_null_ref_Test() { Log.Comment(" Tests that you can convert from null to several reference types"); if (ImprefTestClass_null_ref.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Impref_delegate_to_SystemDotDelegate_Test() { Log.Comment(" Tests that you can convert from a delegate type to System.Delegate"); if (ImprefTestClass_delegate_to_SystemDotDelegate.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } //Compiled Test Cases public class ImprefTestClass_ref_obj_Sub { int func() {return(1);} } public class ImprefTestClass_ref_obj { public static bool testMethod() { ImprefTestClass_ref_obj_Sub test = new ImprefTestClass_ref_obj_Sub(); object obj; obj = test; return true; } } class ImprefTestClass_class_class_Der1 { void i() {} } class ImprefTestClass_class_class_Der2 : ImprefTestClass_class_class_Der1 { void j() {} } public class ImprefTestClass_class_class { public static bool testMethod() { ImprefTestClass_class_class_Der2 derivedClass = new ImprefTestClass_class_class_Der2(); ImprefTestClass_class_class_Der1 ImprefTestClass_class_class_Base; ImprefTestClass_class_class_Base = derivedClass; return true; } } interface ImprefTestClass_class_inter_Interface1 { void i(); } interface ImprefTestClass_class_inter_Interface2 { void j(); } class ImprefTestClass_class_inter_Sub : ImprefTestClass_class_inter_Interface1, ImprefTestClass_class_inter_Interface2 { public void i() {} public void j() {} } public class ImprefTestClass_class_inter { public static bool testMethod() { ImprefTestClass_class_inter_Sub ImprefTestClass_class_inter_Sub = new ImprefTestClass_class_inter_Sub(); ImprefTestClass_class_inter_Interface2 inter2; ImprefTestClass_class_inter_Interface1 inter1; inter1 = ImprefTestClass_class_inter_Sub; inter2 = ImprefTestClass_class_inter_Sub; return true; } } interface ImprefTestClass_struct_inter_Interface1 { void i(); } interface ImprefTestClass_struct_inter_Interface2 { void j(); } struct ImprefTestClass_struct_inter_Sub : ImprefTestClass_struct_inter_Interface1, ImprefTestClass_struct_inter_Interface2 { public void i() {} public void j() {} } public class ImprefTestClass_struct_inter { public static bool testMethod() { ImprefTestClass_struct_inter_Sub ImprefTestClass_struct_inter_Sub = new ImprefTestClass_struct_inter_Sub(); ImprefTestClass_struct_inter_Interface2 inter2; ImprefTestClass_struct_inter_Interface1 inter1; inter2 = ImprefTestClass_struct_inter_Sub; inter1 = ImprefTestClass_struct_inter_Sub; return true; } } class ImprefTestClass_array_array_Base1 { public void i() {} } class ImprefTestClass_array_array_Base2 : ImprefTestClass_array_array_Base1 { public void j() {} } public class ImprefTestClass_array_array { public static bool testMethod() { ImprefTestClass_array_array_Base2[] arrDer = new ImprefTestClass_array_array_Base2[1]; ImprefTestClass_array_array_Base2 element = new ImprefTestClass_array_array_Base2(); arrDer[0] = element; ImprefTestClass_array_array_Base1[] arrBase = new ImprefTestClass_array_array_Base1[1]; arrBase = arrDer; element.j(); arrBase[0].i(); return true; } } class ImprefTestClass_array_cloneable_Derived { public void i() {} } public class ImprefTestClass_array_cloneable { public static bool testMethod() { ImprefTestClass_array_cloneable_Derived[] arrBase = new ImprefTestClass_array_cloneable_Derived[1]; ICloneable clone; clone = arrBase; return true; } } class ImprefTestClass_null_ref_Derived { public void i() {} } public class ImprefTestClass_null_ref { public static bool testMethod() { ImprefTestClass_null_ref_Derived classDer1; String string1; classDer1 = null; string1 = null; return true; } } delegate void ImprefTestClass_delegate_to_SystemDotDelegate_Delegate(); class ImprefTestClass_delegate_to_SystemDotDelegate { public static void DoNothing() { } public static bool testMethod() { ImprefTestClass_delegate_to_SystemDotDelegate_Delegate src = new ImprefTestClass_delegate_to_SystemDotDelegate_Delegate(ImprefTestClass_delegate_to_SystemDotDelegate.DoNothing); System.Delegate dst = src; src(); return true; } } } } ================================================ FILE: Zelig/Zelig/Test/RunTime/NETMF/mscorlib/conversions/basic/BasicTests.cs ================================================ //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // Copyright (c) Microsoft Corporation. All rights reserved. //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// using System; namespace Microsoft.Zelig.Test { /* public class BasicTests : TestBase, ITestInterface { [SetUp] public InitializeResult Initialize() { Log.Comment("Adding set up for the tests"); Log.Comment("The Basic tests examine conversion between two types"); Log.Comment("The tests are named for the types they convert between"); Log.Comment("Some of them are also list with E or I for the cast being explicit or implicit"); Log.Comment("In the case of a number of tests being run, 0, 1, maxValue and minValue are tested"); // Add your functionality here. return InitializeResult.ReadyToGo; } [TearDown] public void CleanUp() { Log.Comment("Cleaning up after the tests"); } public override TestResult Run( string[] args ) { TestResult result = TestResult.Pass; string testName = "Basic_"; int testNumber = 0; result |= Assert.CheckFailed( Basic_byte_byte_I_0_Test( ), testName, ++testNumber ); result |= Assert.CheckFailed( Basic_byte_byte_E_0_Test( ), testName, ++testNumber ); result |= Assert.CheckFailed( Basic_byte_short_I_0_Test( ), testName, ++testNumber ); result |= Assert.CheckFailed( Basic_byte_short_E_0_Test( ), testName, ++testNumber ); result |= Assert.CheckFailed( Basic_byte_ushort_I_0_Test( ), testName, ++testNumber ); result |= Assert.CheckFailed( Basic_byte_ushort_E_0_Test( ), testName, ++testNumber ); result |= Assert.CheckFailed( Basic_byte_int_I_0_Test( ), testName, ++testNumber ); result |= Assert.CheckFailed( Basic_byte_int_E_0_Test( ), testName, ++testNumber ); result |= Assert.CheckFailed( Basic_byte_uint_I_0_Test( ), testName, ++testNumber ); result |= Assert.CheckFailed( Basic_byte_uint_E_0_Test( ), testName, ++testNumber ); result |= Assert.CheckFailed( Basic_byte_long_I_0_Test( ), testName, ++testNumber ); result |= Assert.CheckFailed( Basic_byte_long_E_0_Test( ), testName, ++testNumber ); result |= Assert.CheckFailed( Basic_byte_ulong_I_0_Test( ), testName, ++testNumber ); result |= Assert.CheckFailed( Basic_byte_ulong_E_0_Test( ), testName, ++testNumber ); //////result |= Assert.CheckFailed( Basic_byte_float_I_0_Test( ), testName, ++testNumber ); //////result |= Assert.CheckFailed( Basic_byte_float_E_0_Test( ), testName, ++testNumber ); //////result |= Assert.CheckFailed( Basic_byte_double_I_0_Test( ), testName, ++testNumber ); //////result |= Assert.CheckFailed( Basic_byte_double_E_0_Test( ), testName, ++testNumber ); result |= Assert.CheckFailed( Basic_byte_sbyte_E_1_Test( ), testName, ++testNumber ); result |= Assert.CheckFailed( Basic_byte_sbyte_E_2_Test( ), testName, ++testNumber ); result |= Assert.CheckFailed( Basic_byte_char_E_1_Test( ), testName, ++testNumber ); result |= Assert.CheckFailed( Basic_char_char_I_0_Test( ), testName, ++testNumber ); result |= Assert.CheckFailed( Basic_char_char_E_0_Test( ), testName, ++testNumber ); result |= Assert.CheckFailed( Basic_char_ushort_I_0_Test( ), testName, ++testNumber ); result |= Assert.CheckFailed( Basic_char_ushort_E_0_Test( ), testName, ++testNumber ); result |= Assert.CheckFailed( Basic_char_int_I_0_Test( ), testName, ++testNumber ); result |= Assert.CheckFailed( Basic_char_int_E_0_Test( ), testName, ++testNumber ); result |= Assert.CheckFailed( Basic_char_uint_I_0_Test( ), testName, ++testNumber ); result |= Assert.CheckFailed( Basic_char_uint_E_0_Test( ), testName, ++testNumber ); result |= Assert.CheckFailed( Basic_char_long_I_0_Test( ), testName, ++testNumber ); result |= Assert.CheckFailed( Basic_char_long_E_0_Test( ), testName, ++testNumber ); result |= Assert.CheckFailed( Basic_char_ulong_I_0_Test( ), testName, ++testNumber ); result |= Assert.CheckFailed( Basic_char_ulong_E_0_Test( ), testName, ++testNumber ); //////result |= Assert.CheckFailed( Basic_char_float_I_0_Test( ), testName, ++testNumber ); //////result |= Assert.CheckFailed( Basic_char_float_E_0_Test( ), testName, ++testNumber ); //////result |= Assert.CheckFailed( Basic_char_double_I_0_Test( ), testName, ++testNumber ); //////result |= Assert.CheckFailed( Basic_char_double_E_0_Test( ), testName, ++testNumber ); result |= Assert.CheckFailed( Basic_char_sbyte_E_1_Test( ), testName, ++testNumber ); result |= Assert.CheckFailed( Basic_char_sbyte_E_2_Test( ), testName, ++testNumber ); result |= Assert.CheckFailed( Basic_char_byte_E_1_Test( ), testName, ++testNumber ); result |= Assert.CheckFailed( Basic_char_byte_E_2_Test( ), testName, ++testNumber ); result |= Assert.CheckFailed( Basic_char_byte_E_3_Test( ), testName, ++testNumber ); result |= Assert.CheckFailed( Basic_char_short_E_1_Test( ), testName, ++testNumber ); result |= Assert.CheckFailed( Basic_char_short_E_2_Test( ), testName, ++testNumber ); result |= Assert.CheckFailed( Basic_double_double_I_0_Test( ), testName, ++testNumber ); //////result |= Assert.CheckFailed( Basic_double_double_E_0_Test( ), testName, ++testNumber ); //////result |= Assert.CheckFailed( Basic_double_byte_E_1_Test( ), testName, ++testNumber ); //////result |= Assert.CheckFailed( Basic_double_byte_E_2_Test( ), testName, ++testNumber ); //////result |= Assert.CheckFailed( Basic_double_byte_E_3_Test( ), testName, ++testNumber ); //////result |= Assert.CheckFailed( Basic_double_sbyte_E_1_Test( ), testName, ++testNumber ); //////result |= Assert.CheckFailed( Basic_double_sbyte_E_2_Test( ), testName, ++testNumber ); //////result |= Assert.CheckFailed( Basic_double_sbyte_E_3_Test( ), testName, ++testNumber ); //////result |= Assert.CheckFailed( Basic_double_char_E_1_Test( ), testName, ++testNumber ); //////result |= Assert.CheckFailed( Basic_double_char_E_2_Test( ), testName, ++testNumber ); //////result |= Assert.CheckFailed( Basic_double_char_E_3_Test( ), testName, ++testNumber ); //////result |= Assert.CheckFailed( Basic_double_short_E_1_Test( ), testName, ++testNumber ); //////result |= Assert.CheckFailed( Basic_double_short_E_2_Test( ), testName, ++testNumber ); //////result |= Assert.CheckFailed( Basic_double_short_E_3_Test( ), testName, ++testNumber ); //////result |= Assert.CheckFailed( Basic_double_ushort_E_1_Test( ), testName, ++testNumber ); //////result |= Assert.CheckFailed( Basic_double_ushort_E_2_Test( ), testName, ++testNumber ); //////result |= Assert.CheckFailed( Basic_double_ushort_E_3_Test( ), testName, ++testNumber ); //////result |= Assert.CheckFailed( Basic_double_int_E_1_Test( ), testName, ++testNumber ); //////result |= Assert.CheckFailed( Basic_double_int_E_2_Test( ), testName, ++testNumber ); //////result |= Assert.CheckFailed( Basic_double_int_E_3_Test( ), testName, ++testNumber ); //////result |= Assert.CheckFailed( Basic_double_uint_E_1_Test( ), testName, ++testNumber ); //////result |= Assert.CheckFailed( Basic_double_uint_E_2_Test( ), testName, ++testNumber ); //////result |= Assert.CheckFailed( Basic_double_uint_E_3_Test( ), testName, ++testNumber ); //////result |= Assert.CheckFailed( Basic_double_long_E_1_Test( ), testName, ++testNumber ); //////result |= Assert.CheckFailed( Basic_double_ulong_E_1_Test( ), testName, ++testNumber ); result |= Assert.CheckFailed( Basic_double_float_E_1_Test( ), testName, ++testNumber ); result |= Assert.CheckFailed( Basic_double_float_E_2_Test( ), testName, ++testNumber ); result |= Assert.CheckFailed( Basic_double_float_E_3_Test( ), testName, ++testNumber ); result |= Assert.CheckFailed( Basic_float_float_I_0_Test( ), testName, ++testNumber ); result |= Assert.CheckFailed( Basic_float_float_E_0_Test( ), testName, ++testNumber ); result |= Assert.CheckFailed( Basic_float_double_I_0_Test( ), testName, ++testNumber ); result |= Assert.CheckFailed( Basic_float_double_E_0_Test( ), testName, ++testNumber ); //////result |= Assert.CheckFailed( Basic_float_byte_E_1_Test( ), testName, ++testNumber ); //////result |= Assert.CheckFailed( Basic_float_byte_E_2_Test( ), testName, ++testNumber ); //////result |= Assert.CheckFailed( Basic_float_byte_E_3_Test( ), testName, ++testNumber ); //////result |= Assert.CheckFailed( Basic_float_sbyte_E_1_Test( ), testName, ++testNumber ); //////result |= Assert.CheckFailed( Basic_float_sbyte_E_2_Test( ), testName, ++testNumber ); //////result |= Assert.CheckFailed( Basic_float_sbyte_E_3_Test( ), testName, ++testNumber ); //////result |= Assert.CheckFailed( Basic_float_char_E_1_Test( ), testName, ++testNumber ); //////result |= Assert.CheckFailed( Basic_float_char_E_2_Test( ), testName, ++testNumber ); //////result |= Assert.CheckFailed( Basic_float_char_E_3_Test( ), testName, ++testNumber ); //////result |= Assert.CheckFailed( Basic_float_short_E_1_Test( ), testName, ++testNumber ); //////result |= Assert.CheckFailed( Basic_float_short_E_2_Test( ), testName, ++testNumber ); //////result |= Assert.CheckFailed( Basic_float_short_E_3_Test( ), testName, ++testNumber ); //////result |= Assert.CheckFailed( Basic_float_ushort_E_1_Test( ), testName, ++testNumber ); //////result |= Assert.CheckFailed( Basic_float_ushort_E_2_Test( ), testName, ++testNumber ); //////result |= Assert.CheckFailed( Basic_float_ushort_E_3_Test( ), testName, ++testNumber ); //////result |= Assert.CheckFailed( Basic_float_int_E_1_Test( ), testName, ++testNumber ); //////result |= Assert.CheckFailed( Basic_float_uint_E_1_Test( ), testName, ++testNumber ); //////result |= Assert.CheckFailed( Basic_float_long_E_1_Test( ), testName, ++testNumber ); //////result |= Assert.CheckFailed( Basic_float_ulong_E_1_Test( ), testName, ++testNumber ); result |= Assert.CheckFailed( Basic_int_int_I_0_Test( ), testName, ++testNumber ); result |= Assert.CheckFailed( Basic_int_int_E_0_Test( ), testName, ++testNumber ); result |= Assert.CheckFailed( Basic_int_long_I_0_Test( ), testName, ++testNumber ); result |= Assert.CheckFailed( Basic_int_long_E_0_Test( ), testName, ++testNumber ); //////result |= Assert.CheckFailed( Basic_int_float_I_0_Test( ), testName, ++testNumber ); //////result |= Assert.CheckFailed( Basic_int_float_E_0_Test( ), testName, ++testNumber ); //////result |= Assert.CheckFailed( Basic_int_double_I_0_Test( ), testName, ++testNumber ); //////result |= Assert.CheckFailed( Basic_int_double_E_0_Test( ), testName, ++testNumber ); result |= Assert.CheckFailed( Basic_int_sbyte_E_1_Test( ), testName, ++testNumber ); result |= Assert.CheckFailed( Basic_int_sbyte_E_2_Test( ), testName, ++testNumber ); result |= Assert.CheckFailed( Basic_int_sbyte_E_3_Test( ), testName, ++testNumber ); result |= Assert.CheckFailed( Basic_int_sbyte_E_4_Test( ), testName, ++testNumber ); result |= Assert.CheckFailed( Basic_int_byte_E_1_Test( ), testName, ++testNumber ); result |= Assert.CheckFailed( Basic_int_byte_E_2_Test( ), testName, ++testNumber ); result |= Assert.CheckFailed( Basic_int_byte_E_3_Test( ), testName, ++testNumber ); result |= Assert.CheckFailed( Basic_int_byte_E_4_Test( ), testName, ++testNumber ); result |= Assert.CheckFailed( Basic_int_short_E_1_Test( ), testName, ++testNumber ); result |= Assert.CheckFailed( Basic_int_short_E_2_Test( ), testName, ++testNumber ); result |= Assert.CheckFailed( Basic_int_short_E_3_Test( ), testName, ++testNumber ); result |= Assert.CheckFailed( Basic_int_short_E_4_Test( ), testName, ++testNumber ); result |= Assert.CheckFailed( Basic_int_ushort_E_1_Test( ), testName, ++testNumber ); result |= Assert.CheckFailed( Basic_int_ushort_E_2_Test( ), testName, ++testNumber ); result |= Assert.CheckFailed( Basic_int_ushort_E_3_Test( ), testName, ++testNumber ); result |= Assert.CheckFailed( Basic_int_ushort_E_4_Test( ), testName, ++testNumber ); result |= Assert.CheckFailed( Basic_int_uint_E_1_Test( ), testName, ++testNumber ); result |= Assert.CheckFailed( Basic_int_uint_E_2_Test( ), testName, ++testNumber ); result |= Assert.CheckFailed( Basic_int_uint_E_3_Test( ), testName, ++testNumber ); result |= Assert.CheckFailed( Basic_int_ulong_E_1_Test( ), testName, ++testNumber ); result |= Assert.CheckFailed( Basic_int_char_E_1_Test( ), testName, ++testNumber ); result |= Assert.CheckFailed( Basic_int_char_E_2_Test( ), testName, ++testNumber ); result |= Assert.CheckFailed( Basic_int_char_E_3_Test( ), testName, ++testNumber ); result |= Assert.CheckFailed( Basic_int_char_E_4_Test( ), testName, ++testNumber ); result |= Assert.CheckFailed( Basic_long_long_I_0_Test( ), testName, ++testNumber ); result |= Assert.CheckFailed( Basic_long_long_E_0_Test( ), testName, ++testNumber ); //////result |= Assert.CheckFailed( Basic_long_float_I_0_Test( ), testName, ++testNumber ); //////result |= Assert.CheckFailed( Basic_long_float_E_0_Test( ), testName, ++testNumber ); //////result |= Assert.CheckFailed( Basic_long_double_I_0_Test( ), testName, ++testNumber ); //////result |= Assert.CheckFailed( Basic_long_double_E_0_Test( ), testName, ++testNumber ); result |= Assert.CheckFailed( Basic_long_sbyte_E_1_Test( ), testName, ++testNumber ); result |= Assert.CheckFailed( Basic_long_sbyte_E_2_Test( ), testName, ++testNumber ); result |= Assert.CheckFailed( Basic_long_sbyte_E_3_Test( ), testName, ++testNumber ); result |= Assert.CheckFailed( Basic_long_sbyte_E_4_Test( ), testName, ++testNumber ); result |= Assert.CheckFailed( Basic_long_byte_E_1_Test( ), testName, ++testNumber ); result |= Assert.CheckFailed( Basic_long_byte_E_2_Test( ), testName, ++testNumber ); result |= Assert.CheckFailed( Basic_long_byte_E_3_Test( ), testName, ++testNumber ); result |= Assert.CheckFailed( Basic_long_byte_E_4_Test( ), testName, ++testNumber ); result |= Assert.CheckFailed( Basic_long_short_E_1_Test( ), testName, ++testNumber ); result |= Assert.CheckFailed( Basic_long_short_E_2_Test( ), testName, ++testNumber ); result |= Assert.CheckFailed( Basic_long_short_E_3_Test( ), testName, ++testNumber ); result |= Assert.CheckFailed( Basic_long_short_E_4_Test( ), testName, ++testNumber ); result |= Assert.CheckFailed( Basic_long_ushort_E_1_Test( ), testName, ++testNumber ); result |= Assert.CheckFailed( Basic_long_ushort_E_2_Test( ), testName, ++testNumber ); result |= Assert.CheckFailed( Basic_long_ushort_E_3_Test( ), testName, ++testNumber ); result |= Assert.CheckFailed( Basic_long_ushort_E_4_Test( ), testName, ++testNumber ); result |= Assert.CheckFailed( Basic_long_int_E_1_Test( ), testName, ++testNumber ); result |= Assert.CheckFailed( Basic_long_int_E_2_Test( ), testName, ++testNumber ); result |= Assert.CheckFailed( Basic_long_int_E_3_Test( ), testName, ++testNumber ); result |= Assert.CheckFailed( Basic_long_int_E_4_Test( ), testName, ++testNumber ); result |= Assert.CheckFailed( Basic_long_uint_E_1_Test( ), testName, ++testNumber ); result |= Assert.CheckFailed( Basic_long_uint_E_2_Test( ), testName, ++testNumber ); result |= Assert.CheckFailed( Basic_long_uint_E_3_Test( ), testName, ++testNumber ); result |= Assert.CheckFailed( Basic_long_uint_E_4_Test( ), testName, ++testNumber ); result |= Assert.CheckFailed( Basic_long_ulong_E_1_Test( ), testName, ++testNumber ); result |= Assert.CheckFailed( Basic_long_ulong_E_2_Test( ), testName, ++testNumber ); result |= Assert.CheckFailed( Basic_long_char_E_1_Test( ), testName, ++testNumber ); result |= Assert.CheckFailed( Basic_long_char_E_2_Test( ), testName, ++testNumber ); result |= Assert.CheckFailed( Basic_long_char_E_3_Test( ), testName, ++testNumber ); result |= Assert.CheckFailed( Basic_long_char_E_4_Test( ), testName, ++testNumber ); result |= Assert.CheckFailed( Basic_sbyte_sbyte_I_0_Test( ), testName, ++testNumber ); result |= Assert.CheckFailed( Basic_sbyte_sbyte_E_0_Test( ), testName, ++testNumber ); result |= Assert.CheckFailed( Basic_sbyte_short_I_0_Test( ), testName, ++testNumber ); result |= Assert.CheckFailed( Basic_sbyte_short_E_0_Test( ), testName, ++testNumber ); result |= Assert.CheckFailed( Basic_sbyte_int_I_0_Test( ), testName, ++testNumber ); result |= Assert.CheckFailed( Basic_sbyte_int_E_0_Test( ), testName, ++testNumber ); result |= Assert.CheckFailed( Basic_sbyte_long_I_0_Test( ), testName, ++testNumber ); result |= Assert.CheckFailed( Basic_sbyte_long_E_0_Test( ), testName, ++testNumber ); result |= Assert.CheckFailed( Basic_sbyte_float_I_0_Test( ), testName, ++testNumber ); result |= Assert.CheckFailed( Basic_sbyte_float_E_0_Test( ), testName, ++testNumber ); result |= Assert.CheckFailed( Basic_sbyte_double_I_0_Test( ), testName, ++testNumber ); result |= Assert.CheckFailed( Basic_sbyte_double_E_0_Test( ), testName, ++testNumber ); result |= Assert.CheckFailed( Basic_sbyte_byte_E_1_Test( ), testName, ++testNumber ); result |= Assert.CheckFailed( Basic_sbyte_byte_E_2_Test( ), testName, ++testNumber ); result |= Assert.CheckFailed( Basic_sbyte_byte_E_3_Test( ), testName, ++testNumber ); result |= Assert.CheckFailed( Basic_sbyte_ushort_E_1_Test( ), testName, ++testNumber ); result |= Assert.CheckFailed( Basic_sbyte_uint_E_1_Test( ), testName, ++testNumber ); result |= Assert.CheckFailed( Basic_sbyte_ulong_E_1_Test( ), testName, ++testNumber ); result |= Assert.CheckFailed( Basic_sbyte_char_E_1_Test( ), testName, ++testNumber ); result |= Assert.CheckFailed( Basic_short_short_I_0_Test( ), testName, ++testNumber ); result |= Assert.CheckFailed( Basic_short_short_E_0_Test( ), testName, ++testNumber ); result |= Assert.CheckFailed( Basic_short_int_I_0_Test( ), testName, ++testNumber ); result |= Assert.CheckFailed( Basic_short_int_E_0_Test( ), testName, ++testNumber ); result |= Assert.CheckFailed( Basic_short_long_I_0_Test( ), testName, ++testNumber ); result |= Assert.CheckFailed( Basic_short_long_E_0_Test( ), testName, ++testNumber ); result |= Assert.CheckFailed( Basic_short_float_I_0_Test( ), testName, ++testNumber ); result |= Assert.CheckFailed( Basic_short_float_E_0_Test( ), testName, ++testNumber ); result |= Assert.CheckFailed( Basic_short_double_I_0_Test( ), testName, ++testNumber ); result |= Assert.CheckFailed( Basic_short_double_E_0_Test( ), testName, ++testNumber ); result |= Assert.CheckFailed( Basic_short_short_I_1_Test( ), testName, ++testNumber ); result |= Assert.CheckFailed( Basic_short_short_E_1_Test( ), testName, ++testNumber ); result |= Assert.CheckFailed( Basic_short_int_I_1_Test( ), testName, ++testNumber ); result |= Assert.CheckFailed( Basic_short_int_E_1_Test( ), testName, ++testNumber ); result |= Assert.CheckFailed( Basic_short_long_I_1_Test( ), testName, ++testNumber ); result |= Assert.CheckFailed( Basic_short_long_E_1_Test( ), testName, ++testNumber ); //////result |= Assert.CheckFailed( Basic_short_float_I_1_Test( ), testName, ++testNumber ); //////result |= Assert.CheckFailed( Basic_short_float_E_1_Test( ), testName, ++testNumber ); //////result |= Assert.CheckFailed( Basic_short_double_I_1_Test( ), testName, ++testNumber ); //////result |= Assert.CheckFailed( Basic_short_double_E_1_Test( ), testName, ++testNumber ); result |= Assert.CheckFailed( Basic_short_decimal_I_1_Test( ), testName, ++testNumber ); result |= Assert.CheckFailed( Basic_short_decimal_E_1_Test( ), testName, ++testNumber ); result |= Assert.CheckFailed( Basic_short_sbyte_E_1_Test( ), testName, ++testNumber ); result |= Assert.CheckFailed( Basic_short_sbyte_E_2_Test( ), testName, ++testNumber ); result |= Assert.CheckFailed( Basic_short_sbyte_E_3_Test( ), testName, ++testNumber ); result |= Assert.CheckFailed( Basic_short_sbyte_E_4_Test( ), testName, ++testNumber ); result |= Assert.CheckFailed( Basic_short_byte_E_1_Test( ), testName, ++testNumber ); result |= Assert.CheckFailed( Basic_short_byte_E_2_Test( ), testName, ++testNumber ); result |= Assert.CheckFailed( Basic_short_byte_E_3_Test( ), testName, ++testNumber ); result |= Assert.CheckFailed( Basic_short_byte_E_4_Test( ), testName, ++testNumber ); result |= Assert.CheckFailed( Basic_short_ushort_E_1_Test( ), testName, ++testNumber ); result |= Assert.CheckFailed( Basic_short_ushort_E_2_Test( ), testName, ++testNumber ); result |= Assert.CheckFailed( Basic_short_ushort_E_3_Test( ), testName, ++testNumber ); result |= Assert.CheckFailed( Basic_short_uint_E_1_Test( ), testName, ++testNumber ); result |= Assert.CheckFailed( Basic_short_ulong_E_1_Test( ), testName, ++testNumber ); result |= Assert.CheckFailed( Basic_short_char_E_1_Test( ), testName, ++testNumber ); result |= Assert.CheckFailed( Basic_short_char_E_2_Test( ), testName, ++testNumber ); result |= Assert.CheckFailed( Basic_short_char_E_3_Test( ), testName, ++testNumber ); result |= Assert.CheckFailed( Basic_uint_uint_I_0_Test( ), testName, ++testNumber ); result |= Assert.CheckFailed( Basic_uint_uint_E_0_Test( ), testName, ++testNumber ); result |= Assert.CheckFailed( Basic_uint_long_I_0_Test( ), testName, ++testNumber ); result |= Assert.CheckFailed( Basic_uint_long_E_0_Test( ), testName, ++testNumber ); result |= Assert.CheckFailed( Basic_uint_ulong_I_0_Test( ), testName, ++testNumber ); result |= Assert.CheckFailed( Basic_uint_ulong_E_0_Test( ), testName, ++testNumber ); //////result |= Assert.CheckFailed( Basic_uint_float_I_0_Test( ), testName, ++testNumber ); //////result |= Assert.CheckFailed( Basic_uint_float_E_0_Test( ), testName, ++testNumber ); //////result |= Assert.CheckFailed( Basic_uint_double_I_0_Test( ), testName, ++testNumber ); //////result |= Assert.CheckFailed( Basic_uint_double_E_0_Test( ), testName, ++testNumber ); result |= Assert.CheckFailed( Basic_uint_sbyte_E_1_Test( ), testName, ++testNumber ); result |= Assert.CheckFailed( Basic_uint_sbyte_E_2_Test( ), testName, ++testNumber ); result |= Assert.CheckFailed( Basic_uint_byte_E_1_Test( ), testName, ++testNumber ); result |= Assert.CheckFailed( Basic_uint_byte_E_2_Test( ), testName, ++testNumber ); result |= Assert.CheckFailed( Basic_uint_byte_E_3_Test( ), testName, ++testNumber ); result |= Assert.CheckFailed( Basic_uint_short_E_1_Test( ), testName, ++testNumber ); result |= Assert.CheckFailed( Basic_uint_short_E_2_Test( ), testName, ++testNumber ); result |= Assert.CheckFailed( Basic_uint_ushort_E_1_Test( ), testName, ++testNumber ); result |= Assert.CheckFailed( Basic_uint_ushort_E_2_Test( ), testName, ++testNumber ); result |= Assert.CheckFailed( Basic_uint_ushort_E_3_Test( ), testName, ++testNumber ); result |= Assert.CheckFailed( Basic_uint_int_E_1_Test( ), testName, ++testNumber ); result |= Assert.CheckFailed( Basic_uint_int_E_2_Test( ), testName, ++testNumber ); result |= Assert.CheckFailed( Basic_uint_char_E_1_Test( ), testName, ++testNumber ); result |= Assert.CheckFailed( Basic_uint_char_E_2_Test( ), testName, ++testNumber ); result |= Assert.CheckFailed( Basic_uint_char_E_3_Test( ), testName, ++testNumber ); //////result |= Assert.CheckFailed( Basic_ulong_float_I_0_Test( ), testName, ++testNumber ); //////result |= Assert.CheckFailed( Basic_ulong_float_E_0_Test( ), testName, ++testNumber ); //////result |= Assert.CheckFailed( Basic_ulong_double_I_0_Test( ), testName, ++testNumber ); //////result |= Assert.CheckFailed( Basic_ulong_double_E_0_Test( ), testName, ++testNumber ); result |= Assert.CheckFailed( Basic_ulong_ulong_I_0_Test( ), testName, ++testNumber ); result |= Assert.CheckFailed( Basic_ulong_ulong_E_0_Test( ), testName, ++testNumber ); result |= Assert.CheckFailed( Basic_ulong_sbyte_E_1_Test( ), testName, ++testNumber ); result |= Assert.CheckFailed( Basic_ulong_sbyte_E_2_Test( ), testName, ++testNumber ); result |= Assert.CheckFailed( Basic_ulong_byte_E_1_Test( ), testName, ++testNumber ); result |= Assert.CheckFailed( Basic_ulong_byte_E_2_Test( ), testName, ++testNumber ); result |= Assert.CheckFailed( Basic_ulong_byte_E_3_Test( ), testName, ++testNumber ); result |= Assert.CheckFailed( Basic_ulong_short_E_1_Test( ), testName, ++testNumber ); result |= Assert.CheckFailed( Basic_ulong_short_E_2_Test( ), testName, ++testNumber ); result |= Assert.CheckFailed( Basic_ulong_ushort_E_1_Test( ), testName, ++testNumber ); result |= Assert.CheckFailed( Basic_ulong_ushort_E_2_Test( ), testName, ++testNumber ); result |= Assert.CheckFailed( Basic_ulong_ushort_E_3_Test( ), testName, ++testNumber ); result |= Assert.CheckFailed( Basic_ulong_int_E_1_Test( ), testName, ++testNumber ); result |= Assert.CheckFailed( Basic_ulong_int_E_2_Test( ), testName, ++testNumber ); result |= Assert.CheckFailed( Basic_ulong_uint_E_1_Test( ), testName, ++testNumber ); result |= Assert.CheckFailed( Basic_ulong_uint_E_2_Test( ), testName, ++testNumber ); result |= Assert.CheckFailed( Basic_ulong_uint_E_3_Test( ), testName, ++testNumber ); result |= Assert.CheckFailed( Basic_ulong_long_E_1_Test( ), testName, ++testNumber ); result |= Assert.CheckFailed( Basic_ulong_long_E_2_Test( ), testName, ++testNumber ); result |= Assert.CheckFailed( Basic_ulong_char_E_1_Test( ), testName, ++testNumber ); result |= Assert.CheckFailed( Basic_ulong_char_E_2_Test( ), testName, ++testNumber ); result |= Assert.CheckFailed( Basic_ulong_char_E_3_Test( ), testName, ++testNumber ); result |= Assert.CheckFailed( Basic_ushort_ushort_I_0_Test( ), testName, ++testNumber ); result |= Assert.CheckFailed( Basic_ushort_ushort_E_0_Test( ), testName, ++testNumber ); result |= Assert.CheckFailed( Basic_ushort_int_I_0_Test( ), testName, ++testNumber ); result |= Assert.CheckFailed( Basic_ushort_int_E_0_Test( ), testName, ++testNumber ); result |= Assert.CheckFailed( Basic_ushort_uint_I_0_Test( ), testName, ++testNumber ); result |= Assert.CheckFailed( Basic_ushort_uint_E_0_Test( ), testName, ++testNumber ); result |= Assert.CheckFailed( Basic_ushort_long_I_0_Test( ), testName, ++testNumber ); result |= Assert.CheckFailed( Basic_ushort_long_E_0_Test( ), testName, ++testNumber ); result |= Assert.CheckFailed( Basic_ushort_ulong_I_0_Test( ), testName, ++testNumber ); result |= Assert.CheckFailed( Basic_ushort_ulong_E_0_Test( ), testName, ++testNumber ); result |= Assert.CheckFailed( Basic_ushort_float_I_0_Test( ), testName, ++testNumber ); result |= Assert.CheckFailed( Basic_ushort_float_E_0_Test( ), testName, ++testNumber ); result |= Assert.CheckFailed( Basic_ushort_double_I_0_Test( ), testName, ++testNumber ); result |= Assert.CheckFailed( Basic_ushort_double_E_0_Test( ), testName, ++testNumber ); result |= Assert.CheckFailed( Basic_ushort_sbyte_E_1_Test( ), testName, ++testNumber ); result |= Assert.CheckFailed( Basic_ushort_sbyte_E_2_Test( ), testName, ++testNumber ); result |= Assert.CheckFailed( Basic_ushort_byte_E_1_Test( ), testName, ++testNumber ); result |= Assert.CheckFailed( Basic_ushort_byte_E_2_Test( ), testName, ++testNumber ); result |= Assert.CheckFailed( Basic_ushort_byte_E_3_Test( ), testName, ++testNumber ); result |= Assert.CheckFailed( Basic_ushort_short_E_1_Test( ), testName, ++testNumber ); result |= Assert.CheckFailed( Basic_ushort_short_E_2_Test( ), testName, ++testNumber ); result |= Assert.CheckFailed( Basic_ushort_char_E_1_Test( ), testName, ++testNumber ); result |= Assert.CheckFailed( Basic_ushort_char_E_2_Test( ), testName, ++testNumber ); result |= Assert.CheckFailed( Basic_ushort_char_E_3_Test( ), testName, ++testNumber ); return result; } //Basic Test methods //The following tests were ported from folder current\test\cases\client\CLR\Conformance\10_classes\Basic //byte_byte_I_0,byte_byte_E_0,byte_short_I_0,byte_short_E_0,byte_ushort_I_0,byte_ushort_E_0,byte_int_I_0,byte_int_E_0,byte_uint_I_0,byte_uint_E_0,byte_long_I_0,byte_long_E_0,byte_ulong_I_0,byte_ulong_E_0,byte_float_I_0,byte_float_E_0,byte_double_I_0,byte_double_E_0,byte_sbyte_E_1,byte_sbyte_E_2,byte_char_E_1,char_char_I_0,char_char_E_0,char_ushort_I_0,char_ushort_E_0,char_int_I_0,char_int_E_0,char_uint_I_0,char_uint_E_0,char_long_I_0,char_long_E_0,char_ulong_I_0,char_ulong_E_0,char_float_I_0,char_float_E_0,char_double_I_0,char_double_E_0,char_sbyte_E_1,char_sbyte_E_2,char_byte_E_1,char_byte_E_2,char_byte_E_3,char_short_E_1,char_short_E_2,double_double_I_0,double_double_E_0,double_byte_E_1,double_byte_E_2,double_byte_E_3,double_sbyte_E_1,double_sbyte_E_2,double_sbyte_E_3,double_char_E_1,double_char_E_2,double_char_E_3,double_short_E_1,double_short_E_2,double_short_E_3,double_ushort_E_1,double_ushort_E_2,double_ushort_E_3,double_int_E_1,double_int_E_2,double_int_E_3,double_uint_E_1,double_uint_E_2,double_uint_E_3,double_long_E_1,double_ulong_E_1,double_float_E_1,double_float_E_2,double_float_E_3,float_float_I_0,float_float_E_0,float_double_I_0,float_double_E_0,float_byte_E_1,float_byte_E_2,float_byte_E_3,float_sbyte_E_1,float_sbyte_E_2,float_sbyte_E_3,float_char_E_1,float_char_E_2,float_char_E_3,float_short_E_1,float_short_E_2,float_short_E_3,float_ushort_E_1,float_ushort_E_2,float_ushort_E_3,float_int_E_1,float_uint_E_1,float_long_E_1,float_ulong_E_1,int_int_I_0,int_int_E_0,int_long_I_0,int_long_E_0,int_float_I_0,int_float_E_0,int_double_I_0,int_double_E_0,int_sbyte_E_1,int_sbyte_E_2,int_sbyte_E_3,int_sbyte_E_4,int_byte_E_1,int_byte_E_2,int_byte_E_3,int_byte_E_4,int_short_E_1,int_short_E_2,int_short_E_3,int_short_E_4,int_ushort_E_1,int_ushort_E_2,int_ushort_E_3,int_ushort_E_4,int_uint_E_1,int_uint_E_2,int_uint_E_3,int_ulong_E_1,int_char_E_1,int_char_E_2,int_char_E_3,int_char_E_4,long_long_I_0,long_long_E_0,long_float_I_0,long_float_E_0,long_double_I_0,long_double_E_0,long_sbyte_E_1,long_sbyte_E_2,long_sbyte_E_3,long_sbyte_E_4,long_byte_E_1,long_byte_E_2,long_byte_E_3,long_byte_E_4,long_short_E_1,long_short_E_2,long_short_E_3,long_short_E_4,long_ushort_E_1,long_ushort_E_2,long_ushort_E_3,long_ushort_E_4,long_int_E_1,long_int_E_2,long_int_E_3,long_int_E_4,long_uint_E_1,long_uint_E_2,long_uint_E_3,long_uint_E_4,long_ulong_E_1,long_ulong_E_2,long_char_E_1,long_char_E_2,long_char_E_3,long_char_E_4,sbyte_sbyte_I_0,sbyte_sbyte_E_0,sbyte_short_I_0,sbyte_short_E_0,sbyte_int_I_0,sbyte_int_E_0,sbyte_long_I_0,sbyte_long_E_0,sbyte_float_I_0,sbyte_float_E_0,sbyte_double_I_0,sbyte_double_E_0,sbyte_byte_E_1,sbyte_byte_E_2,sbyte_byte_E_3,sbyte_ushort_E_1,sbyte_uint_E_1,sbyte_ulong_E_1,sbyte_char_E_1,short_short_I_0,short_short_E_0,short_int_I_0,short_int_E_0,short_long_I_0,short_long_E_0,short_float_I_0,short_float_E_0,short_double_I_0,short_double_E_0,short_short_I_1,short_short_E_1,short_int_I_1,short_int_E_1,short_long_I_1,short_long_E_1,short_float_I_1,short_float_E_1,short_double_I_1,short_double_E_1,short_decimal_I_1,short_decimal_E_1,short_sbyte_E_1,short_sbyte_E_2,short_sbyte_E_3,short_sbyte_E_4,short_byte_E_1,short_byte_E_2,short_byte_E_3,short_byte_E_4,short_ushort_E_1,short_ushort_E_2,short_ushort_E_3,short_uint_E_1,short_ulong_E_1,short_char_E_1,short_char_E_2,short_char_E_3,uint_uint_I_0,uint_uint_E_0,uint_long_I_0,uint_long_E_0,uint_ulong_I_0,uint_ulong_E_0,uint_float_I_0,uint_float_E_0,uint_double_I_0,uint_double_E_0,uint_sbyte_E_1,uint_sbyte_E_2,uint_byte_E_1,uint_byte_E_2,uint_byte_E_3,uint_short_E_1,uint_short_E_2,uint_ushort_E_1,uint_ushort_E_2,uint_ushort_E_3,uint_int_E_1,uint_int_E_2,uint_char_E_1,uint_char_E_2,uint_char_E_3,ulong_float_I_0,ulong_float_E_0,ulong_double_I_0,ulong_double_E_0,ulong_ulong_I_0,ulong_ulong_E_0,ulong_sbyte_E_1,ulong_sbyte_E_2,ulong_byte_E_1,ulong_byte_E_2,ulong_byte_E_3,ulong_short_E_1,ulong_short_E_2,ulong_ushort_E_1,ulong_ushort_E_2,ulong_ushort_E_3,ulong_int_E_1,ulong_int_E_2,ulong_uint_E_1,ulong_uint_E_2,ulong_uint_E_3,ulong_long_E_1,ulong_long_E_2,ulong_char_E_1,ulong_char_E_2,ulong_char_E_3,ushort_ushort_I_0,ushort_ushort_E_0,ushort_int_I_0,ushort_int_E_0,ushort_uint_I_0,ushort_uint_E_0,ushort_long_I_0,ushort_long_E_0,ushort_ulong_I_0,ushort_ulong_E_0,ushort_float_I_0,ushort_float_E_0,ushort_double_I_0,ushort_double_E_0,ushort_sbyte_E_1,ushort_sbyte_E_2,ushort_byte_E_1,ushort_byte_E_2,ushort_byte_E_3,ushort_short_E_1,ushort_short_E_2,ushort_char_E_1,ushort_char_E_2,ushort_char_E_3 //Test Case Calls [TestMethod] public TestResult Basic_byte_byte_I_0_Test() { if (BasicTestClass_byte_byte_I_0.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Basic_byte_byte_E_0_Test() { if (BasicTestClass_byte_byte_E_0.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Basic_byte_short_I_0_Test() { if (BasicTestClass_byte_short_I_0.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Basic_byte_short_E_0_Test() { if (BasicTestClass_byte_short_E_0.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Basic_byte_ushort_I_0_Test() { if (BasicTestClass_byte_ushort_I_0.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Basic_byte_ushort_E_0_Test() { if (BasicTestClass_byte_ushort_E_0.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Basic_byte_int_I_0_Test() { if (BasicTestClass_byte_int_I_0.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Basic_byte_int_E_0_Test() { if (BasicTestClass_byte_int_E_0.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Basic_byte_uint_I_0_Test() { if (BasicTestClass_byte_uint_I_0.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Basic_byte_uint_E_0_Test() { if (BasicTestClass_byte_uint_E_0.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Basic_byte_long_I_0_Test() { if (BasicTestClass_byte_long_I_0.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Basic_byte_long_E_0_Test() { if (BasicTestClass_byte_long_E_0.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Basic_byte_ulong_I_0_Test() { if (BasicTestClass_byte_ulong_I_0.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Basic_byte_ulong_E_0_Test() { if (BasicTestClass_byte_ulong_E_0.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } //////[TestMethod] //////public TestResult Basic_byte_float_I_0_Test() //////{ ////// if (BasicTestClass_byte_float_I_0.testMethod()) ////// { ////// return TestResult.Pass; ////// } ////// return TestResult.Fail; //////} //////[TestMethod] //////public TestResult Basic_byte_float_E_0_Test() //////{ ////// if (BasicTestClass_byte_float_E_0.testMethod()) ////// { ////// return TestResult.Pass; ////// } ////// return TestResult.Fail; //////} //////[TestMethod] //////public TestResult Basic_byte_double_I_0_Test() //////{ ////// if (BasicTestClass_byte_double_I_0.testMethod()) ////// { ////// return TestResult.Pass; ////// } ////// return TestResult.Fail; //////} //////[TestMethod] //////public TestResult Basic_byte_double_E_0_Test() //////{ ////// if (BasicTestClass_byte_double_E_0.testMethod()) ////// { ////// return TestResult.Pass; ////// } ////// return TestResult.Fail; //////} [TestMethod] public TestResult Basic_byte_sbyte_E_1_Test() { if (BasicTestClass_byte_sbyte_E_1.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Basic_byte_sbyte_E_2_Test() { if (BasicTestClass_byte_sbyte_E_2.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Basic_byte_char_E_1_Test() { if (BasicTestClass_byte_char_E_1.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Basic_char_char_I_0_Test() { if (BasicTestClass_char_char_I_0.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Basic_char_char_E_0_Test() { if (BasicTestClass_char_char_E_0.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Basic_char_ushort_I_0_Test() { if (BasicTestClass_char_ushort_I_0.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Basic_char_ushort_E_0_Test() { if (BasicTestClass_char_ushort_E_0.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Basic_char_int_I_0_Test() { if (BasicTestClass_char_int_I_0.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Basic_char_int_E_0_Test() { if (BasicTestClass_char_int_E_0.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Basic_char_uint_I_0_Test() { if (BasicTestClass_char_uint_I_0.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Basic_char_uint_E_0_Test() { if (BasicTestClass_char_uint_E_0.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Basic_char_long_I_0_Test() { if (BasicTestClass_char_long_I_0.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Basic_char_long_E_0_Test() { if (BasicTestClass_char_long_E_0.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Basic_char_ulong_I_0_Test() { if (BasicTestClass_char_ulong_I_0.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Basic_char_ulong_E_0_Test() { if (BasicTestClass_char_ulong_E_0.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } //////[TestMethod] //////public TestResult Basic_char_float_I_0_Test() //////{ ////// if (BasicTestClass_char_float_I_0.testMethod()) ////// { ////// return TestResult.Pass; ////// } ////// return TestResult.Fail; //////} //////[TestMethod] //////public TestResult Basic_char_float_E_0_Test() //////{ ////// if (BasicTestClass_char_float_E_0.testMethod()) ////// { ////// return TestResult.Pass; ////// } ////// return TestResult.Fail; //////} //////[TestMethod] //////public TestResult Basic_char_double_I_0_Test() //////{ ////// if (BasicTestClass_char_double_I_0.testMethod()) ////// { ////// return TestResult.Pass; ////// } ////// return TestResult.Fail; //////} //////[TestMethod] //////public TestResult Basic_char_double_E_0_Test() //////{ ////// if (BasicTestClass_char_double_E_0.testMethod()) ////// { ////// return TestResult.Pass; ////// } ////// return TestResult.Fail; //////} [TestMethod] public TestResult Basic_char_sbyte_E_1_Test() { if (BasicTestClass_char_sbyte_E_1.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Basic_char_sbyte_E_2_Test() { if (BasicTestClass_char_sbyte_E_2.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Basic_char_byte_E_1_Test() { if (BasicTestClass_char_byte_E_1.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Basic_char_byte_E_2_Test() { if (BasicTestClass_char_byte_E_2.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Basic_char_byte_E_3_Test() { if (BasicTestClass_char_byte_E_3.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Basic_char_short_E_1_Test() { if (BasicTestClass_char_short_E_1.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Basic_char_short_E_2_Test() { if (BasicTestClass_char_short_E_2.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Basic_double_double_I_0_Test() { if (BasicTestClass_double_double_I_0.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } //////[TestMethod] //////public TestResult Basic_double_double_E_0_Test() //////{ ////// if (BasicTestClass_double_double_E_0.testMethod()) ////// { ////// return TestResult.Pass; ////// } ////// return TestResult.Fail; //////} //////[TestMethod] //////public TestResult Basic_double_byte_E_1_Test() //////{ ////// if (BasicTestClass_double_byte_E_1.testMethod()) ////// { ////// return TestResult.Pass; ////// } ////// return TestResult.Fail; //////} //////[TestMethod] //////public TestResult Basic_double_byte_E_2_Test() //////{ ////// if (BasicTestClass_double_byte_E_2.testMethod()) ////// { ////// return TestResult.Pass; ////// } ////// return TestResult.Fail; //////} //////[TestMethod] //////public TestResult Basic_double_byte_E_3_Test() //////{ ////// if (BasicTestClass_double_byte_E_3.testMethod()) ////// { ////// return TestResult.Pass; ////// } ////// return TestResult.Fail; //////} //////[TestMethod] //////public TestResult Basic_double_sbyte_E_1_Test() //////{ ////// if (BasicTestClass_double_sbyte_E_1.testMethod()) ////// { ////// return TestResult.Pass; ////// } ////// return TestResult.Fail; //////} //////[TestMethod] //////public TestResult Basic_double_sbyte_E_2_Test() //////{ ////// if (BasicTestClass_double_sbyte_E_2.testMethod()) ////// { ////// return TestResult.Pass; ////// } ////// return TestResult.Fail; //////} //////[TestMethod] //////public TestResult Basic_double_sbyte_E_3_Test() //////{ ////// if (BasicTestClass_double_sbyte_E_3.testMethod()) ////// { ////// return TestResult.Pass; ////// } ////// return TestResult.Fail; //////} //////[TestMethod] //////public TestResult Basic_double_char_E_1_Test() //////{ ////// if (BasicTestClass_double_char_E_1.testMethod()) ////// { ////// return TestResult.Pass; ////// } ////// return TestResult.Fail; //////} //////[TestMethod] //////public TestResult Basic_double_char_E_2_Test() //////{ ////// if (BasicTestClass_double_char_E_2.testMethod()) ////// { ////// return TestResult.Pass; ////// } ////// return TestResult.Fail; //////} //////[TestMethod] //////public TestResult Basic_double_char_E_3_Test() //////{ ////// if (BasicTestClass_double_char_E_3.testMethod()) ////// { ////// return TestResult.Pass; ////// } ////// return TestResult.Fail; //////} //////[TestMethod] //////public TestResult Basic_double_short_E_1_Test() //////{ ////// if (BasicTestClass_double_short_E_1.testMethod()) ////// { ////// return TestResult.Pass; ////// } ////// return TestResult.Fail; //////} //////[TestMethod] //////public TestResult Basic_double_short_E_2_Test() //////{ ////// if (BasicTestClass_double_short_E_2.testMethod()) ////// { ////// return TestResult.Pass; ////// } ////// return TestResult.Fail; //////} //////[TestMethod] //////public TestResult Basic_double_short_E_3_Test() //////{ ////// if (BasicTestClass_double_short_E_3.testMethod()) ////// { ////// return TestResult.Pass; ////// } ////// return TestResult.Fail; //////} //////[TestMethod] //////public TestResult Basic_double_ushort_E_1_Test() //////{ ////// if (BasicTestClass_double_ushort_E_1.testMethod()) ////// { ////// return TestResult.Pass; ////// } ////// return TestResult.Fail; //////} //////[TestMethod] //////public TestResult Basic_double_ushort_E_2_Test() //////{ ////// if (BasicTestClass_double_ushort_E_2.testMethod()) ////// { ////// return TestResult.Pass; ////// } ////// return TestResult.Fail; //////} //////[TestMethod] //////public TestResult Basic_double_ushort_E_3_Test() //////{ ////// if (BasicTestClass_double_ushort_E_3.testMethod()) ////// { ////// return TestResult.Pass; ////// } ////// return TestResult.Fail; //////} //////[TestMethod] //////public TestResult Basic_double_int_E_1_Test() //////{ ////// if (BasicTestClass_double_int_E_1.testMethod()) ////// { ////// return TestResult.Pass; ////// } ////// return TestResult.Fail; //////} //////[TestMethod] //////public TestResult Basic_double_int_E_2_Test() //////{ ////// if (BasicTestClass_double_int_E_2.testMethod()) ////// { ////// return TestResult.Pass; ////// } ////// return TestResult.Fail; //////} //////[TestMethod] //////public TestResult Basic_double_int_E_3_Test() //////{ ////// if (BasicTestClass_double_int_E_3.testMethod()) ////// { ////// return TestResult.Pass; ////// } ////// return TestResult.Fail; //////} //////[TestMethod] //////public TestResult Basic_double_uint_E_1_Test() //////{ ////// if (BasicTestClass_double_uint_E_1.testMethod()) ////// { ////// return TestResult.Pass; ////// } ////// return TestResult.Fail; //////} //////[TestMethod] //////public TestResult Basic_double_uint_E_2_Test() //////{ ////// if (BasicTestClass_double_uint_E_2.testMethod()) ////// { ////// return TestResult.Pass; ////// } ////// return TestResult.Fail; //////} //////[TestMethod] //////public TestResult Basic_double_uint_E_3_Test() //////{ ////// if (BasicTestClass_double_uint_E_3.testMethod()) ////// { ////// return TestResult.Pass; ////// } ////// return TestResult.Fail; //////} //////[TestMethod] //////public TestResult Basic_double_long_E_1_Test() //////{ ////// if (BasicTestClass_double_long_E_1.testMethod()) ////// { ////// return TestResult.Pass; ////// } ////// return TestResult.Fail; //////} //////[TestMethod] //////public TestResult Basic_double_ulong_E_1_Test() //////{ ////// if (BasicTestClass_double_ulong_E_1.testMethod()) ////// { ////// return TestResult.Pass; ////// } ////// return TestResult.Fail; //////} [TestMethod] public TestResult Basic_double_float_E_1_Test() { if (BasicTestClass_double_float_E_1.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Basic_double_float_E_2_Test() { if (BasicTestClass_double_float_E_2.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Basic_double_float_E_3_Test() { if (BasicTestClass_double_float_E_3.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Basic_float_float_I_0_Test() { if (BasicTestClass_float_float_I_0.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Basic_float_float_E_0_Test() { if (BasicTestClass_float_float_E_0.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Basic_float_double_I_0_Test() { if (BasicTestClass_float_double_I_0.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Basic_float_double_E_0_Test() { if (BasicTestClass_float_double_E_0.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } //////[TestMethod] //////public TestResult Basic_float_byte_E_1_Test() //////{ ////// if (BasicTestClass_float_byte_E_1.testMethod()) ////// { ////// return TestResult.Pass; ////// } ////// return TestResult.Fail; //////} //////[TestMethod] //////public TestResult Basic_float_byte_E_2_Test() //////{ ////// if (BasicTestClass_float_byte_E_2.testMethod()) ////// { ////// return TestResult.Pass; ////// } ////// return TestResult.Fail; //////} //////[TestMethod] //////public TestResult Basic_float_byte_E_3_Test() //////{ ////// if (BasicTestClass_float_byte_E_3.testMethod()) ////// { ////// return TestResult.Pass; ////// } ////// return TestResult.Fail; //////} //////[TestMethod] //////public TestResult Basic_float_sbyte_E_1_Test() //////{ ////// if (BasicTestClass_float_sbyte_E_1.testMethod()) ////// { ////// return TestResult.Pass; ////// } ////// return TestResult.Fail; //////} //////[TestMethod] //////public TestResult Basic_float_sbyte_E_2_Test() //////{ ////// if (BasicTestClass_float_sbyte_E_2.testMethod()) ////// { ////// return TestResult.Pass; ////// } ////// return TestResult.Fail; //////} //////[TestMethod] //////public TestResult Basic_float_sbyte_E_3_Test() //////{ ////// if (BasicTestClass_float_sbyte_E_3.testMethod()) ////// { ////// return TestResult.Pass; ////// } ////// return TestResult.Fail; //////} //////[TestMethod] //////public TestResult Basic_float_char_E_1_Test() //////{ ////// if (BasicTestClass_float_char_E_1.testMethod()) ////// { ////// return TestResult.Pass; ////// } ////// return TestResult.Fail; //////} //////[TestMethod] //////public TestResult Basic_float_char_E_2_Test() //////{ ////// if (BasicTestClass_float_char_E_2.testMethod()) ////// { ////// return TestResult.Pass; ////// } ////// return TestResult.Fail; //////} //////[TestMethod] //////public TestResult Basic_float_char_E_3_Test() //////{ ////// if (BasicTestClass_float_char_E_3.testMethod()) ////// { ////// return TestResult.Pass; ////// } ////// return TestResult.Fail; //////} //////[TestMethod] //////public TestResult Basic_float_short_E_1_Test() //////{ ////// if (BasicTestClass_float_short_E_1.testMethod()) ////// { ////// return TestResult.Pass; ////// } ////// return TestResult.Fail; //////} //////[TestMethod] //////public TestResult Basic_float_short_E_2_Test() //////{ ////// if (BasicTestClass_float_short_E_2.testMethod()) ////// { ////// return TestResult.Pass; ////// } ////// return TestResult.Fail; //////} //////[TestMethod] //////public TestResult Basic_float_short_E_3_Test() //////{ ////// if (BasicTestClass_float_short_E_3.testMethod()) ////// { ////// return TestResult.Pass; ////// } ////// return TestResult.Fail; //////} //////[TestMethod] //////public TestResult Basic_float_ushort_E_1_Test() //////{ ////// if (BasicTestClass_float_ushort_E_1.testMethod()) ////// { ////// return TestResult.Pass; ////// } ////// return TestResult.Fail; //////} //////[TestMethod] //////public TestResult Basic_float_ushort_E_2_Test() //////{ ////// if (BasicTestClass_float_ushort_E_2.testMethod()) ////// { ////// return TestResult.Pass; ////// } ////// return TestResult.Fail; //////} //////[TestMethod] //////public TestResult Basic_float_ushort_E_3_Test() //////{ ////// if (BasicTestClass_float_ushort_E_3.testMethod()) ////// { ////// return TestResult.Pass; ////// } ////// return TestResult.Fail; //////} //////[TestMethod] //////public TestResult Basic_float_int_E_1_Test() //////{ ////// if (BasicTestClass_float_int_E_1.testMethod()) ////// { ////// return TestResult.Pass; ////// } ////// return TestResult.Fail; //////} //////[TestMethod] //////public TestResult Basic_float_uint_E_1_Test() //////{ ////// if (BasicTestClass_float_uint_E_1.testMethod()) ////// { ////// return TestResult.Pass; ////// } ////// return TestResult.Fail; //////} //////[TestMethod] //////public TestResult Basic_float_long_E_1_Test() //////{ ////// if (BasicTestClass_float_long_E_1.testMethod()) ////// { ////// return TestResult.Pass; ////// } ////// return TestResult.Fail; //////} //////[TestMethod] //////public TestResult Basic_float_ulong_E_1_Test() //////{ ////// if (BasicTestClass_float_ulong_E_1.testMethod()) ////// { ////// return TestResult.Pass; ////// } ////// return TestResult.Fail; //////} [TestMethod] public TestResult Basic_int_int_I_0_Test() { if (BasicTestClass_int_int_I_0.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Basic_int_int_E_0_Test() { if (BasicTestClass_int_int_E_0.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Basic_int_long_I_0_Test() { if (BasicTestClass_int_long_I_0.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Basic_int_long_E_0_Test() { if (BasicTestClass_int_long_E_0.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } //////[TestMethod] //////public TestResult Basic_int_float_I_0_Test() //////{ ////// if (BasicTestClass_int_float_I_0.testMethod()) ////// { ////// return TestResult.Pass; ////// } ////// return TestResult.Fail; //////} //////[TestMethod] //////public TestResult Basic_int_float_E_0_Test() //////{ ////// if (BasicTestClass_int_float_E_0.testMethod()) ////// { ////// return TestResult.Pass; ////// } ////// return TestResult.Fail; //////} //////[TestMethod] //////public TestResult Basic_int_double_I_0_Test() //////{ ////// if (BasicTestClass_int_double_I_0.testMethod()) ////// { ////// return TestResult.Pass; ////// } ////// return TestResult.Fail; //////} //////[TestMethod] //////public TestResult Basic_int_double_E_0_Test() //////{ ////// if (BasicTestClass_int_double_E_0.testMethod()) ////// { ////// return TestResult.Pass; ////// } ////// return TestResult.Fail; //////} [TestMethod] public TestResult Basic_int_sbyte_E_1_Test() { if (BasicTestClass_int_sbyte_E_1.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Basic_int_sbyte_E_2_Test() { if (BasicTestClass_int_sbyte_E_2.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Basic_int_sbyte_E_3_Test() { if (BasicTestClass_int_sbyte_E_3.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Basic_int_sbyte_E_4_Test() { if (BasicTestClass_int_sbyte_E_4.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Basic_int_byte_E_1_Test() { if (BasicTestClass_int_byte_E_1.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Basic_int_byte_E_2_Test() { if (BasicTestClass_int_byte_E_2.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Basic_int_byte_E_3_Test() { if (BasicTestClass_int_byte_E_3.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Basic_int_byte_E_4_Test() { if (BasicTestClass_int_byte_E_4.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Basic_int_short_E_1_Test() { if (BasicTestClass_int_short_E_1.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Basic_int_short_E_2_Test() { if (BasicTestClass_int_short_E_2.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Basic_int_short_E_3_Test() { if (BasicTestClass_int_short_E_3.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Basic_int_short_E_4_Test() { if (BasicTestClass_int_short_E_4.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Basic_int_ushort_E_1_Test() { if (BasicTestClass_int_ushort_E_1.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Basic_int_ushort_E_2_Test() { if (BasicTestClass_int_ushort_E_2.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Basic_int_ushort_E_3_Test() { if (BasicTestClass_int_ushort_E_3.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Basic_int_ushort_E_4_Test() { if (BasicTestClass_int_ushort_E_4.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Basic_int_uint_E_1_Test() { if (BasicTestClass_int_uint_E_1.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Basic_int_uint_E_2_Test() { if (BasicTestClass_int_uint_E_2.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Basic_int_uint_E_3_Test() { if (BasicTestClass_int_uint_E_3.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Basic_int_ulong_E_1_Test() { if (BasicTestClass_int_ulong_E_1.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Basic_int_char_E_1_Test() { if (BasicTestClass_int_char_E_1.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Basic_int_char_E_2_Test() { if (BasicTestClass_int_char_E_2.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Basic_int_char_E_3_Test() { if (BasicTestClass_int_char_E_3.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Basic_int_char_E_4_Test() { if (BasicTestClass_int_char_E_4.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Basic_long_long_I_0_Test() { if (BasicTestClass_long_long_I_0.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Basic_long_long_E_0_Test() { if (BasicTestClass_long_long_E_0.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } //////[TestMethod] //////public TestResult Basic_long_float_I_0_Test() //////{ ////// if (BasicTestClass_long_float_I_0.testMethod()) ////// { ////// return TestResult.Pass; ////// } ////// return TestResult.Fail; //////} //////[TestMethod] //////public TestResult Basic_long_float_E_0_Test() //////{ ////// if (BasicTestClass_long_float_E_0.testMethod()) ////// { ////// return TestResult.Pass; ////// } ////// return TestResult.Fail; //////} //////[TestMethod] //////public TestResult Basic_long_double_I_0_Test() //////{ ////// if (BasicTestClass_long_double_I_0.testMethod()) ////// { ////// return TestResult.Pass; ////// } ////// return TestResult.Fail; //////} //////[TestMethod] //////public TestResult Basic_long_double_E_0_Test() //////{ ////// if (BasicTestClass_long_double_E_0.testMethod()) ////// { ////// return TestResult.Pass; ////// } ////// return TestResult.Fail; //////} [TestMethod] public TestResult Basic_long_sbyte_E_1_Test() { if (BasicTestClass_long_sbyte_E_1.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Basic_long_sbyte_E_2_Test() { if (BasicTestClass_long_sbyte_E_2.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Basic_long_sbyte_E_3_Test() { if (BasicTestClass_long_sbyte_E_3.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Basic_long_sbyte_E_4_Test() { if (BasicTestClass_long_sbyte_E_4.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Basic_long_byte_E_1_Test() { if (BasicTestClass_long_byte_E_1.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Basic_long_byte_E_2_Test() { if (BasicTestClass_long_byte_E_2.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Basic_long_byte_E_3_Test() { if (BasicTestClass_long_byte_E_3.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Basic_long_byte_E_4_Test() { if (BasicTestClass_long_byte_E_4.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Basic_long_short_E_1_Test() { if (BasicTestClass_long_short_E_1.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Basic_long_short_E_2_Test() { if (BasicTestClass_long_short_E_2.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Basic_long_short_E_3_Test() { if (BasicTestClass_long_short_E_3.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Basic_long_short_E_4_Test() { if (BasicTestClass_long_short_E_4.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Basic_long_ushort_E_1_Test() { if (BasicTestClass_long_ushort_E_1.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Basic_long_ushort_E_2_Test() { if (BasicTestClass_long_ushort_E_2.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Basic_long_ushort_E_3_Test() { if (BasicTestClass_long_ushort_E_3.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Basic_long_ushort_E_4_Test() { if (BasicTestClass_long_ushort_E_4.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Basic_long_int_E_1_Test() { if (BasicTestClass_long_int_E_1.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Basic_long_int_E_2_Test() { if (BasicTestClass_long_int_E_2.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Basic_long_int_E_3_Test() { if (BasicTestClass_long_int_E_3.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Basic_long_int_E_4_Test() { if (BasicTestClass_long_int_E_4.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Basic_long_uint_E_1_Test() { if (BasicTestClass_long_uint_E_1.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Basic_long_uint_E_2_Test() { if (BasicTestClass_long_uint_E_2.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Basic_long_uint_E_3_Test() { if (BasicTestClass_long_uint_E_3.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Basic_long_uint_E_4_Test() { if (BasicTestClass_long_uint_E_4.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Basic_long_ulong_E_1_Test() { if (BasicTestClass_long_ulong_E_1.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Basic_long_ulong_E_2_Test() { if (BasicTestClass_long_ulong_E_2.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Basic_long_char_E_1_Test() { if (BasicTestClass_long_char_E_1.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Basic_long_char_E_2_Test() { if (BasicTestClass_long_char_E_2.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Basic_long_char_E_3_Test() { if (BasicTestClass_long_char_E_3.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Basic_long_char_E_4_Test() { if (BasicTestClass_long_char_E_4.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Basic_sbyte_sbyte_I_0_Test() { if (BasicTestClass_sbyte_sbyte_I_0.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Basic_sbyte_sbyte_E_0_Test() { if (BasicTestClass_sbyte_sbyte_E_0.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Basic_sbyte_short_I_0_Test() { if (BasicTestClass_sbyte_short_I_0.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Basic_sbyte_short_E_0_Test() { if (BasicTestClass_sbyte_short_E_0.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Basic_sbyte_int_I_0_Test() { if (BasicTestClass_sbyte_int_I_0.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Basic_sbyte_int_E_0_Test() { if (BasicTestClass_sbyte_int_E_0.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Basic_sbyte_long_I_0_Test() { if (BasicTestClass_sbyte_long_I_0.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Basic_sbyte_long_E_0_Test() { if (BasicTestClass_sbyte_long_E_0.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Basic_sbyte_float_I_0_Test() { if (BasicTestClass_sbyte_float_I_0.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Basic_sbyte_float_E_0_Test() { if (BasicTestClass_sbyte_float_E_0.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Basic_sbyte_double_I_0_Test() { if (BasicTestClass_sbyte_double_I_0.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Basic_sbyte_double_E_0_Test() { if (BasicTestClass_sbyte_double_E_0.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Basic_sbyte_byte_E_1_Test() { if (BasicTestClass_sbyte_byte_E_1.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Basic_sbyte_byte_E_2_Test() { if (BasicTestClass_sbyte_byte_E_2.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Basic_sbyte_byte_E_3_Test() { if (BasicTestClass_sbyte_byte_E_3.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Basic_sbyte_ushort_E_1_Test() { if (BasicTestClass_sbyte_ushort_E_1.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Basic_sbyte_uint_E_1_Test() { if (BasicTestClass_sbyte_uint_E_1.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Basic_sbyte_ulong_E_1_Test() { if (BasicTestClass_sbyte_ulong_E_1.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Basic_sbyte_char_E_1_Test() { if (BasicTestClass_sbyte_char_E_1.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Basic_short_short_I_0_Test() { if (BasicTestClass_short_short_I_0.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Basic_short_short_E_0_Test() { if (BasicTestClass_short_short_E_0.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Basic_short_int_I_0_Test() { if (BasicTestClass_short_int_I_0.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Basic_short_int_E_0_Test() { if (BasicTestClass_short_int_E_0.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Basic_short_long_I_0_Test() { if (BasicTestClass_short_long_I_0.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Basic_short_long_E_0_Test() { if (BasicTestClass_short_long_E_0.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Basic_short_float_I_0_Test() { if (BasicTestClass_short_float_I_0.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Basic_short_float_E_0_Test() { if (BasicTestClass_short_float_E_0.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Basic_short_double_I_0_Test() { if (BasicTestClass_short_double_I_0.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Basic_short_double_E_0_Test() { if (BasicTestClass_short_double_E_0.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Basic_short_short_I_1_Test() { if (BasicTestClass_short_short_I_1.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Basic_short_short_E_1_Test() { if (BasicTestClass_short_short_E_1.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Basic_short_int_I_1_Test() { if (BasicTestClass_short_int_I_1.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Basic_short_int_E_1_Test() { if (BasicTestClass_short_int_E_1.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Basic_short_long_I_1_Test() { if (BasicTestClass_short_long_I_1.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Basic_short_long_E_1_Test() { if (BasicTestClass_short_long_E_1.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } //////[TestMethod] //////public TestResult Basic_short_float_I_1_Test() //////{ ////// if (BasicTestClass_short_float_I_1.testMethod()) ////// { ////// return TestResult.Pass; ////// } ////// return TestResult.Fail; //////} //////[TestMethod] //////public TestResult Basic_short_float_E_1_Test() //////{ ////// if (BasicTestClass_short_float_E_1.testMethod()) ////// { ////// return TestResult.Pass; ////// } ////// return TestResult.Fail; //////} //////[TestMethod] //////public TestResult Basic_short_double_I_1_Test() //////{ ////// if (BasicTestClass_short_double_I_1.testMethod()) ////// { ////// return TestResult.Pass; ////// } ////// return TestResult.Fail; //////} //////[TestMethod] //////public TestResult Basic_short_double_E_1_Test() //////{ ////// if (BasicTestClass_short_double_E_1.testMethod()) ////// { ////// return TestResult.Pass; ////// } ////// return TestResult.Fail; //////} [TestMethod] public TestResult Basic_short_decimal_I_1_Test() { if (BasicTestClass_short_decimal_I_1.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Basic_short_decimal_E_1_Test() { if (BasicTestClass_short_decimal_E_1.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Basic_short_sbyte_E_1_Test() { if (BasicTestClass_short_sbyte_E_1.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Basic_short_sbyte_E_2_Test() { if (BasicTestClass_short_sbyte_E_2.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Basic_short_sbyte_E_3_Test() { if (BasicTestClass_short_sbyte_E_3.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Basic_short_sbyte_E_4_Test() { if (BasicTestClass_short_sbyte_E_4.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Basic_short_byte_E_1_Test() { if (BasicTestClass_short_byte_E_1.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Basic_short_byte_E_2_Test() { if (BasicTestClass_short_byte_E_2.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Basic_short_byte_E_3_Test() { if (BasicTestClass_short_byte_E_3.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Basic_short_byte_E_4_Test() { if (BasicTestClass_short_byte_E_4.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Basic_short_ushort_E_1_Test() { if (BasicTestClass_short_ushort_E_1.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Basic_short_ushort_E_2_Test() { if (BasicTestClass_short_ushort_E_2.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Basic_short_ushort_E_3_Test() { if (BasicTestClass_short_ushort_E_3.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Basic_short_uint_E_1_Test() { if (BasicTestClass_short_uint_E_1.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Basic_short_ulong_E_1_Test() { if (BasicTestClass_short_ulong_E_1.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Basic_short_char_E_1_Test() { if (BasicTestClass_short_char_E_1.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Basic_short_char_E_2_Test() { if (BasicTestClass_short_char_E_2.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Basic_short_char_E_3_Test() { if (BasicTestClass_short_char_E_3.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Basic_uint_uint_I_0_Test() { if (BasicTestClass_uint_uint_I_0.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Basic_uint_uint_E_0_Test() { if (BasicTestClass_uint_uint_E_0.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Basic_uint_long_I_0_Test() { if (BasicTestClass_uint_long_I_0.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Basic_uint_long_E_0_Test() { if (BasicTestClass_uint_long_E_0.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Basic_uint_ulong_I_0_Test() { if (BasicTestClass_uint_ulong_I_0.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Basic_uint_ulong_E_0_Test() { if (BasicTestClass_uint_ulong_E_0.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } //////[TestMethod] //////public TestResult Basic_uint_float_I_0_Test() //////{ ////// if (BasicTestClass_uint_float_I_0.testMethod()) ////// { ////// return TestResult.Pass; ////// } ////// return TestResult.Fail; //////} //////[TestMethod] //////public TestResult Basic_uint_float_E_0_Test() //////{ ////// if (BasicTestClass_uint_float_E_0.testMethod()) ////// { ////// return TestResult.Pass; ////// } ////// return TestResult.Fail; //////} //////[TestMethod] //////public TestResult Basic_uint_double_I_0_Test() //////{ ////// if (BasicTestClass_uint_double_I_0.testMethod()) ////// { ////// return TestResult.Pass; ////// } ////// return TestResult.Fail; //////} //////[TestMethod] //////public TestResult Basic_uint_double_E_0_Test() //////{ ////// if (BasicTestClass_uint_double_E_0.testMethod()) ////// { ////// return TestResult.Pass; ////// } ////// return TestResult.Fail; //////} [TestMethod] public TestResult Basic_uint_sbyte_E_1_Test() { if (BasicTestClass_uint_sbyte_E_1.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Basic_uint_sbyte_E_2_Test() { if (BasicTestClass_uint_sbyte_E_2.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Basic_uint_byte_E_1_Test() { if (BasicTestClass_uint_byte_E_1.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Basic_uint_byte_E_2_Test() { if (BasicTestClass_uint_byte_E_2.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Basic_uint_byte_E_3_Test() { if (BasicTestClass_uint_byte_E_3.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Basic_uint_short_E_1_Test() { if (BasicTestClass_uint_short_E_1.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Basic_uint_short_E_2_Test() { if (BasicTestClass_uint_short_E_2.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Basic_uint_ushort_E_1_Test() { if (BasicTestClass_uint_ushort_E_1.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Basic_uint_ushort_E_2_Test() { if (BasicTestClass_uint_ushort_E_2.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Basic_uint_ushort_E_3_Test() { if (BasicTestClass_uint_ushort_E_3.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Basic_uint_int_E_1_Test() { if (BasicTestClass_uint_int_E_1.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Basic_uint_int_E_2_Test() { if (BasicTestClass_uint_int_E_2.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Basic_uint_char_E_1_Test() { if (BasicTestClass_uint_char_E_1.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Basic_uint_char_E_2_Test() { if (BasicTestClass_uint_char_E_2.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Basic_uint_char_E_3_Test() { if (BasicTestClass_uint_char_E_3.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } //////[TestMethod] //////public TestResult Basic_ulong_float_I_0_Test() //////{ ////// if (BasicTestClass_ulong_float_I_0.testMethod()) ////// { ////// return TestResult.Pass; ////// } ////// return TestResult.Fail; //////} //////[TestMethod] //////public TestResult Basic_ulong_float_E_0_Test() //////{ ////// if (BasicTestClass_ulong_float_E_0.testMethod()) ////// { ////// return TestResult.Pass; ////// } ////// return TestResult.Fail; //////} //////[TestMethod] //////public TestResult Basic_ulong_double_I_0_Test() //////{ ////// if (BasicTestClass_ulong_double_I_0.testMethod()) ////// { ////// return TestResult.Pass; ////// } ////// return TestResult.Fail; //////} //////[TestMethod] //////public TestResult Basic_ulong_double_E_0_Test() //////{ ////// if (BasicTestClass_ulong_double_E_0.testMethod()) ////// { ////// return TestResult.Pass; ////// } ////// return TestResult.Fail; //////} [TestMethod] public TestResult Basic_ulong_ulong_I_0_Test() { if (BasicTestClass_ulong_ulong_I_0.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Basic_ulong_ulong_E_0_Test() { if (BasicTestClass_ulong_ulong_E_0.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Basic_ulong_sbyte_E_1_Test() { if (BasicTestClass_ulong_sbyte_E_1.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Basic_ulong_sbyte_E_2_Test() { if (BasicTestClass_ulong_sbyte_E_2.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Basic_ulong_byte_E_1_Test() { if (BasicTestClass_ulong_byte_E_1.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Basic_ulong_byte_E_2_Test() { if (BasicTestClass_ulong_byte_E_2.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Basic_ulong_byte_E_3_Test() { if (BasicTestClass_ulong_byte_E_3.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Basic_ulong_short_E_1_Test() { if (BasicTestClass_ulong_short_E_1.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Basic_ulong_short_E_2_Test() { if (BasicTestClass_ulong_short_E_2.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Basic_ulong_ushort_E_1_Test() { if (BasicTestClass_ulong_ushort_E_1.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Basic_ulong_ushort_E_2_Test() { if (BasicTestClass_ulong_ushort_E_2.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Basic_ulong_ushort_E_3_Test() { if (BasicTestClass_ulong_ushort_E_3.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Basic_ulong_int_E_1_Test() { if (BasicTestClass_ulong_int_E_1.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Basic_ulong_int_E_2_Test() { if (BasicTestClass_ulong_int_E_2.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Basic_ulong_uint_E_1_Test() { if (BasicTestClass_ulong_uint_E_1.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Basic_ulong_uint_E_2_Test() { if (BasicTestClass_ulong_uint_E_2.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Basic_ulong_uint_E_3_Test() { if (BasicTestClass_ulong_uint_E_3.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Basic_ulong_long_E_1_Test() { if (BasicTestClass_ulong_long_E_1.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Basic_ulong_long_E_2_Test() { if (BasicTestClass_ulong_long_E_2.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Basic_ulong_char_E_1_Test() { if (BasicTestClass_ulong_char_E_1.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Basic_ulong_char_E_2_Test() { if (BasicTestClass_ulong_char_E_2.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Basic_ulong_char_E_3_Test() { if (BasicTestClass_ulong_char_E_3.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Basic_ushort_ushort_I_0_Test() { if (BasicTestClass_ushort_ushort_I_0.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Basic_ushort_ushort_E_0_Test() { if (BasicTestClass_ushort_ushort_E_0.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Basic_ushort_int_I_0_Test() { if (BasicTestClass_ushort_int_I_0.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Basic_ushort_int_E_0_Test() { if (BasicTestClass_ushort_int_E_0.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Basic_ushort_uint_I_0_Test() { if (BasicTestClass_ushort_uint_I_0.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Basic_ushort_uint_E_0_Test() { if (BasicTestClass_ushort_uint_E_0.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Basic_ushort_long_I_0_Test() { if (BasicTestClass_ushort_long_I_0.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Basic_ushort_long_E_0_Test() { if (BasicTestClass_ushort_long_E_0.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Basic_ushort_ulong_I_0_Test() { if (BasicTestClass_ushort_ulong_I_0.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Basic_ushort_ulong_E_0_Test() { if (BasicTestClass_ushort_ulong_E_0.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Basic_ushort_float_I_0_Test() { if (BasicTestClass_ushort_float_I_0.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Basic_ushort_float_E_0_Test() { if (BasicTestClass_ushort_float_E_0.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Basic_ushort_double_I_0_Test() { if (BasicTestClass_ushort_double_I_0.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Basic_ushort_double_E_0_Test() { if (BasicTestClass_ushort_double_E_0.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Basic_ushort_sbyte_E_1_Test() { if (BasicTestClass_ushort_sbyte_E_1.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Basic_ushort_sbyte_E_2_Test() { if (BasicTestClass_ushort_sbyte_E_2.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Basic_ushort_byte_E_1_Test() { if (BasicTestClass_ushort_byte_E_1.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Basic_ushort_byte_E_2_Test() { if (BasicTestClass_ushort_byte_E_2.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Basic_ushort_byte_E_3_Test() { if (BasicTestClass_ushort_byte_E_3.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Basic_ushort_short_E_1_Test() { if (BasicTestClass_ushort_short_E_1.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Basic_ushort_short_E_2_Test() { if (BasicTestClass_ushort_short_E_2.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Basic_ushort_char_E_1_Test() { if (BasicTestClass_ushort_char_E_1.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Basic_ushort_char_E_2_Test() { if (BasicTestClass_ushort_char_E_2.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Basic_ushort_char_E_3_Test() { if (BasicTestClass_ushort_char_E_3.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } //Compiled Test Cases public class BasicTestClass_byte_byte_I_0 { public static int Main_old() { byte source; byte dest; source = 1; dest = source; if (dest == 1) return 0; else return 1; } public static bool testMethod() { return (Main_old() == 0); } } public class BasicTestClass_byte_byte_E_0 { public static int Main_old() { byte source; byte dest; source = 1; dest = (byte)source; if (dest == 1) return 0; else return 1; } public static bool testMethod() { return (Main_old() == 0); } } public class BasicTestClass_byte_short_I_0 { public static int Main_old() { byte source; short dest; source = 1; dest = source; if (dest == 1) return 0; else return 1; } public static bool testMethod() { return (Main_old() == 0); } } public class BasicTestClass_byte_short_E_0 { public static int Main_old() { byte source; short dest; source = 1; dest = (short)source; if (dest == 1) return 0; else return 1; } public static bool testMethod() { return (Main_old() == 0); } } public class BasicTestClass_byte_ushort_I_0 { public static int Main_old() { byte source; ushort dest; source = 1; dest = source; if (dest == 1) return 0; else return 1; } public static bool testMethod() { return (Main_old() == 0); } } public class BasicTestClass_byte_ushort_E_0 { public static int Main_old() { byte source; ushort dest; source = 1; dest = (ushort)source; if (dest == 1) return 0; else return 1; } public static bool testMethod() { return (Main_old() == 0); } } public class BasicTestClass_byte_int_I_0 { public static int Main_old() { byte source; int dest; source = 1; dest = source; if (dest == 1) return 0; else return 1; } public static bool testMethod() { return (Main_old() == 0); } } public class BasicTestClass_byte_int_E_0 { public static int Main_old() { byte source; int dest; source = 1; dest = (int)source; if (dest == 1) return 0; else return 1; } public static bool testMethod() { return (Main_old() == 0); } } public class BasicTestClass_byte_uint_I_0 { public static int Main_old() { byte source; uint dest; source = 1; dest = source; if (dest == 1) return 0; else return 1; } public static bool testMethod() { return (Main_old() == 0); } } public class BasicTestClass_byte_uint_E_0 { public static int Main_old() { byte source; uint dest; source = 1; dest = (uint)source; if (dest == 1) return 0; else return 1; } public static bool testMethod() { return (Main_old() == 0); } } public class BasicTestClass_byte_long_I_0 { public static int Main_old() { byte source; long dest; source = 1; dest = source; if (dest == 1) return 0; else return 1; } public static bool testMethod() { return (Main_old() == 0); } } public class BasicTestClass_byte_long_E_0 { public static int Main_old() { byte source; long dest; source = 1; dest = (long)source; if (dest == 1) return 0; else return 1; } public static bool testMethod() { return (Main_old() == 0); } } public class BasicTestClass_byte_ulong_I_0 { public static int Main_old() { byte source; ulong dest; source = 1; dest = source; if (dest == 1) return 0; else return 1; } public static bool testMethod() { return (Main_old() == 0); } } public class BasicTestClass_byte_ulong_E_0 { public static int Main_old() { byte source; ulong dest; source = 1; dest = (ulong)source; if (dest == 1) return 0; else return 1; } public static bool testMethod() { return (Main_old() == 0); } } public class BasicTestClass_byte_float_I_0 { public static int Main_old() { byte source; float dest; source = 1; dest = source; if (dest == 1F) return 0; else return 1; } public static bool testMethod() { return (Main_old() == 0); } } public class BasicTestClass_byte_float_E_0 { public static int Main_old() { byte source; float dest; source = 1; dest = (float)source; if (dest == 1F) return 0; else return 1; } public static bool testMethod() { return (Main_old() == 0); } } public class BasicTestClass_byte_double_I_0 { public static int Main_old() { byte source; double dest; source = 1; dest = source; if (dest == 1.0) return 0; else return 1; } public static bool testMethod() { return (Main_old() == 0); } } public class BasicTestClass_byte_double_E_0 { public static int Main_old() { byte source; double dest; source = 1; dest = (double)source; if (dest == 1.0) return 0; else return 1; } public static bool testMethod() { return (Main_old() == 0); } } public class BasicTestClass_byte_sbyte_E_1 { public static int Main_old() { byte source; sbyte dest; source = 1; dest = (sbyte)source; if (dest == 1) return 0; else return 1; } public static bool testMethod() { return (Main_old() == 0); } } public class BasicTestClass_byte_sbyte_E_2 { public static int Main_old() { byte source; sbyte dest; source = 127; dest = (sbyte)source; if (dest == 127) return 0; else return 1; } public static bool testMethod() { return (Main_old() == 0); } } public class BasicTestClass_byte_char_E_1 { public static int Main_old() { byte source; char dest; source = 1; dest = (char)source; if (dest == '\x1') return 0; else return 1; } public static bool testMethod() { return (Main_old() == 0); } } public class BasicTestClass_char_char_I_0 { public static int Main_old() { char source; char dest; source = '\x1'; dest = source; if (dest == '\x1') return 0; else return 1; } public static bool testMethod() { return (Main_old() == 0); } } public class BasicTestClass_char_char_E_0 { public static int Main_old() { char source; char dest; source = '\x1'; dest = (char)source; if (dest == '\x1') return 0; else return 1; } public static bool testMethod() { return (Main_old() == 0); } } public class BasicTestClass_char_ushort_I_0 { public static int Main_old() { char source; ushort dest; source = '\x1'; dest = source; if (dest == 1) return 0; else return 1; } public static bool testMethod() { return (Main_old() == 0); } } public class BasicTestClass_char_ushort_E_0 { public static int Main_old() { char source; ushort dest; source = '\x1'; dest = (ushort)source; if (dest == 1) return 0; else return 1; } public static bool testMethod() { return (Main_old() == 0); } } public class BasicTestClass_char_int_I_0 { public static int Main_old() { char source; int dest; source = '\x1'; dest = source; if (dest == 1) return 0; else return 1; } public static bool testMethod() { return (Main_old() == 0); } } public class BasicTestClass_char_int_E_0 { public static int Main_old() { char source; int dest; source = '\x1'; dest = (int)source; if (dest == 1) return 0; else return 1; } public static bool testMethod() { return (Main_old() == 0); } } public class BasicTestClass_char_uint_I_0 { public static int Main_old() { char source; uint dest; source = '\x1'; dest = source; if (dest == 1) return 0; else return 1; } public static bool testMethod() { return (Main_old() == 0); } } public class BasicTestClass_char_uint_E_0 { public static int Main_old() { char source; uint dest; source = '\x1'; dest = (uint)source; if (dest == 1) return 0; else return 1; } public static bool testMethod() { return (Main_old() == 0); } } public class BasicTestClass_char_long_I_0 { public static int Main_old() { char source; long dest; source = '\x1'; dest = source; if (dest == 1) return 0; else return 1; } public static bool testMethod() { return (Main_old() == 0); } } public class BasicTestClass_char_long_E_0 { public static int Main_old() { char source; long dest; source = '\x1'; dest = (long)source; if (dest == 1) return 0; else return 1; } public static bool testMethod() { return (Main_old() == 0); } } public class BasicTestClass_char_ulong_I_0 { public static int Main_old() { char source; ulong dest; source = '\x1'; dest = source; if (dest == 1) return 0; else return 1; } public static bool testMethod() { return (Main_old() == 0); } } public class BasicTestClass_char_ulong_E_0 { public static int Main_old() { char source; ulong dest; source = '\x1'; dest = (ulong)source; if (dest == 1) return 0; else return 1; } public static bool testMethod() { return (Main_old() == 0); } } public class BasicTestClass_char_float_I_0 { public static int Main_old() { char source; float dest; source = '\x1'; dest = source; if (dest == 1F) return 0; else return 1; } public static bool testMethod() { return (Main_old() == 0); } } public class BasicTestClass_char_float_E_0 { public static int Main_old() { char source; float dest; source = '\x1'; dest = (float)source; if (dest == 1F) return 0; else return 1; } public static bool testMethod() { return (Main_old() == 0); } } public class BasicTestClass_char_double_I_0 { public static int Main_old() { char source; double dest; source = '\x1'; dest = source; if (dest == 1.0) return 0; else return 1; } public static bool testMethod() { return (Main_old() == 0); } } public class BasicTestClass_char_double_E_0 { public static int Main_old() { char source; double dest; source = '\x1'; dest = (double)source; if (dest == 1.0) return 0; else return 1; } public static bool testMethod() { return (Main_old() == 0); } } public class BasicTestClass_char_sbyte_E_1 { public static int Main_old() { char source; sbyte dest; source = '\x1'; dest = (sbyte)source; if (dest == 1) return 0; else return 1; } public static bool testMethod() { return (Main_old() == 0); } } public class BasicTestClass_char_sbyte_E_2 { public static int Main_old() { char source; sbyte dest; source = '\x7f'; dest = (sbyte)source; if (dest == 127) return 0; else return 1; } public static bool testMethod() { return (Main_old() == 0); } } public class BasicTestClass_char_byte_E_1 { public static int Main_old() { char source; byte dest; source = '\x1'; dest = (byte)source; if (dest == 1) return 0; else return 1; } public static bool testMethod() { return (Main_old() == 0); } } public class BasicTestClass_char_byte_E_2 { public static int Main_old() { char source; byte dest; source = '\xff'; dest = (byte)source; if (dest == 255) return 0; else return 1; } public static bool testMethod() { return (Main_old() == 0); } } public class BasicTestClass_char_byte_E_3 { public static int Main_old() { char source; byte dest; source = '\x0'; dest = (byte)source; if (dest == 0) return 0; else return 1; } public static bool testMethod() { return (Main_old() == 0); } } public class BasicTestClass_char_short_E_1 { public static int Main_old() { char source; short dest; source = '\x1'; dest = (short)source; if (dest == 1) return 0; else return 1; } public static bool testMethod() { return (Main_old() == 0); } } public class BasicTestClass_char_short_E_2 { public static int Main_old() { char source; short dest; source = '\x7fff'; dest = (short)source; if (dest == 32767) return 0; else return 1; } public static bool testMethod() { return (Main_old() == 0); } } public class BasicTestClass_double_double_I_0 { public static int Main_old() { double source; double dest; source = 1.0; dest = source; if (dest == 1.0) return 0; else return 1; } public static bool testMethod() { return (Main_old() == 0); } } //////public class BasicTestClass_double_double_E_0 //////{ ////// public static int Main_old() ////// { ////// double source; ////// double dest; ////// source = 1.0; ////// dest = (double)source; ////// if (dest == 1.0) ////// return 0; ////// else ////// return 1; ////// } ////// public static bool testMethod() ////// { ////// return (Main_old() == 0); ////// } //////} //////public class BasicTestClass_double_byte_E_1 //////{ ////// public static int Main_old() ////// { ////// double source; ////// byte dest; ////// source = 1.0; ////// dest = (byte)source; ////// if (dest == 1) ////// return 0; ////// else ////// return 1; ////// } ////// public static bool testMethod() ////// { ////// return (Main_old() == 0); ////// } //////} //////public class BasicTestClass_double_byte_E_2 //////{ ////// public static int Main_old() ////// { ////// double source; ////// byte dest; ////// source = 255d; ////// dest = (byte)source; ////// if (dest == 255) ////// return 0; ////// else ////// return 1; ////// } ////// public static bool testMethod() ////// { ////// return (Main_old() == 0); ////// } //////} //////public class BasicTestClass_double_byte_E_3 //////{ ////// public static int Main_old() ////// { ////// double source; ////// byte dest; ////// source = 0d; ////// dest = (byte)source; ////// if (dest == 0) ////// return 0; ////// else ////// return 1; ////// } ////// public static bool testMethod() ////// { ////// return (Main_old() == 0); ////// } //////} //////public class BasicTestClass_double_sbyte_E_1 //////{ ////// public static int Main_old() ////// { ////// double source; ////// sbyte dest; ////// source = 1.0; ////// dest = (sbyte)source; ////// if (dest == 1) ////// return 0; ////// else ////// return 1; ////// } ////// public static bool testMethod() ////// { ////// return (Main_old() == 0); ////// } //////} //////public class BasicTestClass_double_sbyte_E_2 //////{ ////// public static int Main_old() ////// { ////// double source; ////// sbyte dest; ////// source = 127d; ////// dest = (sbyte)source; ////// if (dest == 127) ////// return 0; ////// else ////// return 1; ////// } ////// public static bool testMethod() ////// { ////// return (Main_old() == 0); ////// } //////} //////public class BasicTestClass_double_sbyte_E_3 //////{ ////// public static int Main_old() ////// { ////// double source; ////// sbyte dest; ////// source = -128d; ////// dest = (sbyte)source; ////// if (dest == -128) ////// return 0; ////// else ////// return 1; ////// } ////// public static bool testMethod() ////// { ////// return (Main_old() == 0); ////// } //////} //////public class BasicTestClass_double_char_E_1 //////{ ////// public static int Main_old() ////// { ////// double source; ////// char dest; ////// source = 1.0; ////// dest = (char)source; ////// if (dest == '\x1') ////// return 0; ////// else ////// return 1; ////// } ////// public static bool testMethod() ////// { ////// return (Main_old() == 0); ////// } //////} //////public class BasicTestClass_double_char_E_2 //////{ ////// public static int Main_old() ////// { ////// double source; ////// char dest; ////// source = 65535d; ////// dest = (char)source; ////// if (dest == '\xffff') ////// return 0; ////// else ////// return 1; ////// } ////// public static bool testMethod() ////// { ////// return (Main_old() == 0); ////// } //////} //////public class BasicTestClass_double_char_E_3 //////{ ////// public static int Main_old() ////// { ////// double source; ////// char dest; ////// source = 0d; ////// dest = (char)source; ////// if (dest == '\x0') ////// return 0; ////// else ////// return 1; ////// } ////// public static bool testMethod() ////// { ////// return (Main_old() == 0); ////// } //////} //////public class BasicTestClass_double_short_E_1 //////{ ////// public static int Main_old() ////// { ////// double source; ////// short dest; ////// source = 1.0; ////// dest = (short)source; ////// if (dest == 1) ////// return 0; ////// else ////// return 1; ////// } ////// public static bool testMethod() ////// { ////// return (Main_old() == 0); ////// } //////} //////public class BasicTestClass_double_short_E_2 //////{ ////// public static int Main_old() ////// { ////// double source; ////// short dest; ////// source = 32767d; ////// dest = (short)source; ////// if (dest == 32767) ////// return 0; ////// else ////// return 1; ////// } ////// public static bool testMethod() ////// { ////// return (Main_old() == 0); ////// } //////} //////public class BasicTestClass_double_short_E_3 //////{ ////// public static int Main_old() ////// { ////// double source; ////// short dest; ////// source = -32767d; ////// dest = (short)source; ////// if (dest == -32767) ////// return 0; ////// else ////// return 1; ////// } ////// public static bool testMethod() ////// { ////// return (Main_old() == 0); ////// } //////} //////public class BasicTestClass_double_ushort_E_1 //////{ ////// public static int Main_old() ////// { ////// double source; ////// ushort dest; ////// source = 1.0; ////// dest = (ushort)source; ////// if (dest == 1) ////// return 0; ////// else ////// return 1; ////// } ////// public static bool testMethod() ////// { ////// return (Main_old() == 0); ////// } //////} //////public class BasicTestClass_double_ushort_E_2 //////{ ////// public static int Main_old() ////// { ////// double source; ////// ushort dest; ////// source = 65535d; ////// dest = (ushort)source; ////// if (dest == 65535) ////// return 0; ////// else ////// return 1; ////// } ////// public static bool testMethod() ////// { ////// return (Main_old() == 0); ////// } //////} //////public class BasicTestClass_double_ushort_E_3 //////{ ////// public static int Main_old() ////// { ////// double source; ////// ushort dest; ////// source = 0d; ////// dest = (ushort)source; ////// if (dest == 0) ////// return 0; ////// else ////// return 1; ////// } ////// public static bool testMethod() ////// { ////// return (Main_old() == 0); ////// } //////} //////public class BasicTestClass_double_int_E_1 //////{ ////// public static int Main_old() ////// { ////// double source; ////// int dest; ////// source = 1.0; ////// dest = (int)source; ////// if (dest == 1) ////// return 0; ////// else ////// return 1; ////// } ////// public static bool testMethod() ////// { ////// return (Main_old() == 0); ////// } //////} //////public class BasicTestClass_double_int_E_2 //////{ ////// public static int Main_old() ////// { ////// double source; ////// int dest; ////// source = 2147483647d; ////// dest = (int)source; ////// if (dest == 2147483647) ////// return 0; ////// else ////// return 1; ////// } ////// public static bool testMethod() ////// { ////// return (Main_old() == 0); ////// } //////} //////public class BasicTestClass_double_int_E_3 //////{ ////// public static int Main_old() ////// { ////// double source; ////// int dest; ////// source = -2147483647d; ////// dest = (int)source; ////// if (dest == -2147483647) ////// return 0; ////// else ////// return 1; ////// } ////// public static bool testMethod() ////// { ////// return (Main_old() == 0); ////// } //////} //////public class BasicTestClass_double_uint_E_1 //////{ ////// public static int Main_old() ////// { ////// double source; ////// uint dest; ////// source = 1.0; ////// dest = (uint)source; ////// if (dest == 1) ////// return 0; ////// else ////// return 1; ////// } ////// public static bool testMethod() ////// { ////// return (Main_old() == 0); ////// } //////} //////public class BasicTestClass_double_uint_E_2 //////{ ////// public static int Main_old() ////// { ////// double source; ////// uint dest; ////// source = 4294967295d; ////// dest = (uint)source; ////// if (dest == 4294967295) ////// return 0; ////// else ////// return 1; ////// } ////// public static bool testMethod() ////// { ////// return (Main_old() == 0); ////// } //////} //////public class BasicTestClass_double_uint_E_3 //////{ ////// public static int Main_old() ////// { ////// double source; ////// uint dest; ////// source = 0d; ////// dest = (uint)source; ////// if (dest == 0) ////// return 0; ////// else ////// return 1; ////// } ////// public static bool testMethod() ////// { ////// return (Main_old() == 0); ////// } //////} //////public class BasicTestClass_double_long_E_1 //////{ ////// public static int Main_old() ////// { ////// double source; ////// long dest; ////// source = 1.0; ////// dest = (long)source; ////// if (dest == 1) ////// return 0; ////// else ////// return 1; ////// } ////// public static bool testMethod() ////// { ////// return (Main_old() == 0); ////// } //////} //////public class BasicTestClass_double_ulong_E_1 //////{ ////// public static int Main_old() ////// { ////// double source; ////// ulong dest; ////// source = 1.0; ////// dest = (ulong)source; ////// if (dest == 1) ////// return 0; ////// else ////// return 1; ////// } ////// public static bool testMethod() ////// { ////// return (Main_old() == 0); ////// } //////} public class BasicTestClass_double_float_E_1 { public static int Main_old() { double source; float dest; source = 1.0; dest = (float)source; if (dest == 1F) return 0; else return 1; } public static bool testMethod() { return (Main_old() == 0); } } public class BasicTestClass_double_float_E_2 { public static int Main_old() { double source; float dest; source = 3.4e38d; dest = (float)source; if (dest == 3.4e38F) return 0; else return 1; } public static bool testMethod() { return (Main_old() == 0); } } public class BasicTestClass_double_float_E_3 { public static int Main_old() { double source; float dest; source = -3.4e38d; dest = (float)source; if (dest == -3.4e38F) return 0; else return 1; } public static bool testMethod() { return (Main_old() == 0); } } public class BasicTestClass_float_float_I_0 { public static int Main_old() { float source; float dest; source = 1F; dest = source; if (dest == 1F) return 0; else return 1; } public static bool testMethod() { return (Main_old() == 0); } } public class BasicTestClass_float_float_E_0 { public static int Main_old() { float source; float dest; source = 1F; dest = (float)source; if (dest == 1F) return 0; else return 1; } public static bool testMethod() { return (Main_old() == 0); } } public class BasicTestClass_float_double_I_0 { public static int Main_old() { float source; double dest; source = 1F; dest = source; if (dest == 1.0) return 0; else return 1; } public static bool testMethod() { return (Main_old() == 0); } } public class BasicTestClass_float_double_E_0 { public static int Main_old() { float source; double dest; source = 1F; dest = (double)source; if (dest == 1.0) return 0; else return 1; } public static bool testMethod() { return (Main_old() == 0); } } public class BasicTestClass_float_byte_E_1 { public static int Main_old() { float source; byte dest; source = 1F; dest = (byte)source; if (dest == 1) return 0; else return 1; } public static bool testMethod() { return (Main_old() == 0); } } public class BasicTestClass_float_byte_E_2 { public static int Main_old() { float source; byte dest; source = 255F; dest = (byte)source; if (dest == 255) return 0; else return 1; } public static bool testMethod() { return (Main_old() == 0); } } public class BasicTestClass_float_byte_E_3 { public static int Main_old() { float source; byte dest; source = 0F; dest = (byte)source; if (dest == 0) return 0; else return 1; } public static bool testMethod() { return (Main_old() == 0); } } public class BasicTestClass_float_sbyte_E_1 { public static int Main_old() { float source; sbyte dest; source = 1F; dest = (sbyte)source; if (dest == 1) return 0; else return 1; } public static bool testMethod() { return (Main_old() == 0); } } public class BasicTestClass_float_sbyte_E_2 { public static int Main_old() { float source; sbyte dest; source = 127F; dest = (sbyte)source; if (dest == 127) return 0; else return 1; } public static bool testMethod() { return (Main_old() == 0); } } public class BasicTestClass_float_sbyte_E_3 { public static int Main_old() { float source; sbyte dest; source = -128F; dest = (sbyte)source; if (dest == -128) return 0; else return 1; } public static bool testMethod() { return (Main_old() == 0); } } public class BasicTestClass_float_char_E_1 { public static int Main_old() { float source; char dest; source = 1F; dest = (char)source; if (dest == '\x1') return 0; else return 1; } public static bool testMethod() { return (Main_old() == 0); } } public class BasicTestClass_float_char_E_2 { public static int Main_old() { float source; char dest; source = 65535F; dest = (char)source; if (dest == '\xffff') return 0; else return 1; } public static bool testMethod() { return (Main_old() == 0); } } public class BasicTestClass_float_char_E_3 { public static int Main_old() { float source; char dest; source = 0F; dest = (char)source; if (dest == '\x0') return 0; else return 1; } public static bool testMethod() { return (Main_old() == 0); } } public class BasicTestClass_float_short_E_1 { public static int Main_old() { float source; short dest; source = 1F; dest = (short)source; if (dest == 1) return 0; else return 1; } public static bool testMethod() { return (Main_old() == 0); } } public class BasicTestClass_float_short_E_2 { public static int Main_old() { float source; short dest; source = 32767F; dest = (short)source; if (dest == 32767) return 0; else return 1; } public static bool testMethod() { return (Main_old() == 0); } } public class BasicTestClass_float_short_E_3 { public static int Main_old() { float source; short dest; source = -32767F; dest = (short)source; if (dest == -32767) return 0; else return 1; } public static bool testMethod() { return (Main_old() == 0); } } public class BasicTestClass_float_ushort_E_1 { public static int Main_old() { float source; ushort dest; source = 1F; dest = (ushort)source; if (dest == 1) return 0; else return 1; } public static bool testMethod() { return (Main_old() == 0); } } public class BasicTestClass_float_ushort_E_2 { public static int Main_old() { float source; ushort dest; source = 65535F; dest = (ushort)source; if (dest == 65535) return 0; else return 1; } public static bool testMethod() { return (Main_old() == 0); } } public class BasicTestClass_float_ushort_E_3 { public static int Main_old() { float source; ushort dest; source = 0F; dest = (ushort)source; if (dest == 0) return 0; else return 1; } public static bool testMethod() { return (Main_old() == 0); } } public class BasicTestClass_float_int_E_1 { public static int Main_old() { float source; int dest; source = 1F; dest = (int)source; if (dest == 1) return 0; else return 1; } public static bool testMethod() { return (Main_old() == 0); } } public class BasicTestClass_float_uint_E_1 { public static int Main_old() { float source; uint dest; source = 1F; dest = (uint)source; if (dest == 1) return 0; else return 1; } public static bool testMethod() { return (Main_old() == 0); } } public class BasicTestClass_float_long_E_1 { public static int Main_old() { float source; long dest; source = 1F; dest = (long)source; if (dest == 1) return 0; else return 1; } public static bool testMethod() { return (Main_old() == 0); } } public class BasicTestClass_float_ulong_E_1 { public static int Main_old() { float source; ulong dest; source = 1F; dest = (ulong)source; if (dest == 1) return 0; else return 1; } public static bool testMethod() { return (Main_old() == 0); } } public class BasicTestClass_int_int_I_0 { public static int Main_old() { int source; int dest; source = 1; dest = source; if (dest == 1) return 0; else return 1; } public static bool testMethod() { return (Main_old() == 0); } } public class BasicTestClass_int_int_E_0 { public static int Main_old() { int source; int dest; source = 1; dest = (int)source; if (dest == 1) return 0; else return 1; } public static bool testMethod() { return (Main_old() == 0); } } public class BasicTestClass_int_long_I_0 { public static int Main_old() { int source; long dest; source = 1; dest = source; if (dest == 1) return 0; else return 1; } public static bool testMethod() { return (Main_old() == 0); } } public class BasicTestClass_int_long_E_0 { public static int Main_old() { int source; long dest; source = 1; dest = (long)source; if (dest == 1) return 0; else return 1; } public static bool testMethod() { return (Main_old() == 0); } } public class BasicTestClass_int_float_I_0 { public static int Main_old() { int source; float dest; source = 1; dest = source; if (dest == 1F) return 0; else return 1; } public static bool testMethod() { return (Main_old() == 0); } } public class BasicTestClass_int_float_E_0 { public static int Main_old() { int source; float dest; source = 1; dest = (float)source; if (dest == 1F) return 0; else return 1; } public static bool testMethod() { return (Main_old() == 0); } } public class BasicTestClass_int_double_I_0 { public static int Main_old() { int source; double dest; source = 1; dest = source; if (dest == 1.0) return 0; else return 1; } public static bool testMethod() { return (Main_old() == 0); } } public class BasicTestClass_int_double_E_0 { public static int Main_old() { int source; double dest; source = 1; dest = (double)source; if (dest == 1.0) return 0; else return 1; } public static bool testMethod() { return (Main_old() == 0); } } public class BasicTestClass_int_sbyte_E_1 { public static int Main_old() { int source; sbyte dest; source = 1; dest = (sbyte)source; if (dest == 1) return 0; else return 1; } public static bool testMethod() { return (Main_old() == 0); } } public class BasicTestClass_int_sbyte_E_2 { public static int Main_old() { int source; sbyte dest; source = 127; dest = (sbyte)source; if (dest == 127) return 0; else return 1; } public static bool testMethod() { return (Main_old() == 0); } } public class BasicTestClass_int_sbyte_E_3 { public static int Main_old() { int source; sbyte dest; source = -128; dest = (sbyte)source; if (dest == -128) return 0; else return 1; } public static bool testMethod() { return (Main_old() == 0); } } public class BasicTestClass_int_sbyte_E_4 { public static int Main_old() { int source; sbyte dest; source = -129; dest = (sbyte)source; if (dest == 127) return 0; else return 1; } public static bool testMethod() { return (Main_old() == 0); } } public class BasicTestClass_int_byte_E_1 { public static int Main_old() { int source; byte dest; source = 1; dest = (byte)source; if (dest == 1) return 0; else return 1; } public static bool testMethod() { return (Main_old() == 0); } } public class BasicTestClass_int_byte_E_2 { public static int Main_old() { int source; byte dest; source = 255; dest = (byte)source; if (dest == 255) return 0; else return 1; } public static bool testMethod() { return (Main_old() == 0); } } public class BasicTestClass_int_byte_E_3 { public static int Main_old() { int source; byte dest; source = 0; dest = (byte)source; if (dest == 0) return 0; else return 1; } public static bool testMethod() { return (Main_old() == 0); } } public class BasicTestClass_int_byte_E_4 { public static int Main_old() { int source; byte dest; source = -1; dest = (byte)source; if (dest == 255) return 0; else return 1; } public static bool testMethod() { return (Main_old() == 0); } } public class BasicTestClass_int_short_E_1 { public static int Main_old() { int source; short dest; source = 1; dest = (short)source; if (dest == 1) return 0; else return 1; } public static bool testMethod() { return (Main_old() == 0); } } public class BasicTestClass_int_short_E_2 { public static int Main_old() { int source; short dest; source = 32767; dest = (short)source; if (dest == 32767) return 0; else return 1; } public static bool testMethod() { return (Main_old() == 0); } } public class BasicTestClass_int_short_E_3 { public static int Main_old() { int source; short dest; source = -32767; dest = (short)source; if (dest == -32767) return 0; else return 1; } public static bool testMethod() { return (Main_old() == 0); } } public class BasicTestClass_int_short_E_4 { public static int Main_old() { int source; short dest; source = -32769; dest = (short)source; if (dest == 32767) return 0; else return 1; } public static bool testMethod() { return (Main_old() == 0); } } public class BasicTestClass_int_ushort_E_1 { public static int Main_old() { int source; ushort dest; source = 1; dest = (ushort)source; if (dest == 1) return 0; else return 1; } public static bool testMethod() { return (Main_old() == 0); } } public class BasicTestClass_int_ushort_E_2 { public static int Main_old() { int source; ushort dest; source = 65535; dest = (ushort)source; if (dest == 65535) return 0; else return 1; } public static bool testMethod() { return (Main_old() == 0); } } public class BasicTestClass_int_ushort_E_3 { public static int Main_old() { int source; ushort dest; source = 0; dest = (ushort)source; if (dest == 0) return 0; else return 1; } public static bool testMethod() { return (Main_old() == 0); } } public class BasicTestClass_int_ushort_E_4 { public static int Main_old() { int source; ushort dest; source = -1; dest = (ushort)source; if (dest == 65535) return 0; else return 1; } public static bool testMethod() { return (Main_old() == 0); } } public class BasicTestClass_int_uint_E_1 { public static int Main_old() { int source; uint dest; source = 1; dest = (uint)source; if (dest == 1) return 0; else return 1; } public static bool testMethod() { return (Main_old() == 0); } } public class BasicTestClass_int_uint_E_2 { public static int Main_old() { int source; uint dest; source = 0; dest = (uint)source; if (dest == 0) return 0; else return 1; } public static bool testMethod() { return (Main_old() == 0); } } public class BasicTestClass_int_uint_E_3 { public static int Main_old() { int source; uint dest; source = -1; dest = (uint)source; if (dest == 4294967295) return 0; else return 1; } public static bool testMethod() { return (Main_old() == 0); } } public class BasicTestClass_int_ulong_E_1 { public static int Main_old() { int source; ulong dest; source = 1; dest = (ulong)source; if (dest == 1) return 0; else return 1; } public static bool testMethod() { return (Main_old() == 0); } } public class BasicTestClass_int_char_E_1 { public static int Main_old() { int source; char dest; source = 1; dest = (char)source; if (dest == '\x1') return 0; else return 1; } public static bool testMethod() { return (Main_old() == 0); } } public class BasicTestClass_int_char_E_2 { public static int Main_old() { int source; char dest; source = 65535; dest = (char)source; if (dest == '\xffff') return 0; else return 1; } public static bool testMethod() { return (Main_old() == 0); } } public class BasicTestClass_int_char_E_3 { public static int Main_old() { int source; char dest; source = 0; dest = (char)source; if (dest == '\x0') return 0; else return 1; } public static bool testMethod() { return (Main_old() == 0); } } public class BasicTestClass_int_char_E_4 { public static int Main_old() { int source; char dest; source = -1; dest = (char)source; if (dest == '\xffff') return 0; else return 1; } public static bool testMethod() { return (Main_old() == 0); } } public class BasicTestClass_long_long_I_0 { public static int Main_old() { long source; long dest; source = 1; dest = source; if (dest == 1) return 0; else return 1; } public static bool testMethod() { return (Main_old() == 0); } } public class BasicTestClass_long_long_E_0 { public static int Main_old() { long source; long dest; source = 1; dest = (long)source; if (dest == 1) return 0; else return 1; } public static bool testMethod() { return (Main_old() == 0); } } public class BasicTestClass_long_float_I_0 { public static int Main_old() { long source; float dest; source = 1; dest = source; if (dest == 1F) return 0; else return 1; } public static bool testMethod() { return (Main_old() == 0); } } public class BasicTestClass_long_float_E_0 { public static int Main_old() { long source; float dest; source = 1; dest = (float)source; if (dest == 1F) return 0; else return 1; } public static bool testMethod() { return (Main_old() == 0); } } public class BasicTestClass_long_double_I_0 { public static int Main_old() { long source; double dest; source = 1; dest = source; if (dest == 1.0) return 0; else return 1; } public static bool testMethod() { return (Main_old() == 0); } } public class BasicTestClass_long_double_E_0 { public static int Main_old() { long source; double dest; source = 1; dest = (double)source; if (dest == 1.0) return 0; else return 1; } public static bool testMethod() { return (Main_old() == 0); } } public class BasicTestClass_long_sbyte_E_1 { public static int Main_old() { long source; sbyte dest; source = 1; dest = (sbyte)source; if (dest == 1) return 0; else return 1; } public static bool testMethod() { return (Main_old() == 0); } } public class BasicTestClass_long_sbyte_E_2 { public static int Main_old() { long source; sbyte dest; source = 127; dest = (sbyte)source; if (dest == 127) return 0; else return 1; } public static bool testMethod() { return (Main_old() == 0); } } public class BasicTestClass_long_sbyte_E_3 { public static int Main_old() { long source; sbyte dest; source = -128; dest = (sbyte)source; if (dest == -128) return 0; else return 1; } public static bool testMethod() { return (Main_old() == 0); } } public class BasicTestClass_long_sbyte_E_4 { public static int Main_old() { long source; sbyte dest; source = -129; dest = (sbyte)source; if (dest == 127) return 0; else return 1; } public static bool testMethod() { return (Main_old() == 0); } } public class BasicTestClass_long_byte_E_1 { public static int Main_old() { long source; byte dest; source = 1; dest = (byte)source; if (dest == 1) return 0; else return 1; } public static bool testMethod() { return (Main_old() == 0); } } public class BasicTestClass_long_byte_E_2 { public static int Main_old() { long source; byte dest; source = 255; dest = (byte)source; if (dest == 255) return 0; else return 1; } public static bool testMethod() { return (Main_old() == 0); } } public class BasicTestClass_long_byte_E_3 { public static int Main_old() { long source; byte dest; source = 0; dest = (byte)source; if (dest == 0) return 0; else return 1; } public static bool testMethod() { return (Main_old() == 0); } } public class BasicTestClass_long_byte_E_4 { public static int Main_old() { long source; byte dest; source = -1; dest = (byte)source; if (dest == 255) return 0; else return 1; } public static bool testMethod() { return (Main_old() == 0); } } public class BasicTestClass_long_short_E_1 { public static int Main_old() { long source; short dest; source = 1; dest = (short)source; if (dest == 1) return 0; else return 1; } public static bool testMethod() { return (Main_old() == 0); } } public class BasicTestClass_long_short_E_2 { public static int Main_old() { long source; short dest; source = 32767; dest = (short)source; if (dest == 32767) return 0; else return 1; } public static bool testMethod() { return (Main_old() == 0); } } public class BasicTestClass_long_short_E_3 { public static int Main_old() { long source; short dest; source = -32767; dest = (short)source; if (dest == -32767) return 0; else return 1; } public static bool testMethod() { return (Main_old() == 0); } } public class BasicTestClass_long_short_E_4 { public static int Main_old() { long source; short dest; source = -32769; dest = (short)source; if (dest == 32767) return 0; else return 1; } public static bool testMethod() { return (Main_old() == 0); } } public class BasicTestClass_long_ushort_E_1 { public static int Main_old() { long source; ushort dest; source = 1; dest = (ushort)source; if (dest == 1) return 0; else return 1; } public static bool testMethod() { return (Main_old() == 0); } } public class BasicTestClass_long_ushort_E_2 { public static int Main_old() { long source; ushort dest; source = 65535; dest = (ushort)source; if (dest == 65535) return 0; else return 1; } public static bool testMethod() { return (Main_old() == 0); } } public class BasicTestClass_long_ushort_E_3 { public static int Main_old() { long source; ushort dest; source = 0; dest = (ushort)source; if (dest == 0) return 0; else return 1; } public static bool testMethod() { return (Main_old() == 0); } } public class BasicTestClass_long_ushort_E_4 { public static int Main_old() { long source; ushort dest; source = -1; dest = (ushort)source; if (dest == 65535) return 0; else return 1; } public static bool testMethod() { return (Main_old() == 0); } } public class BasicTestClass_long_int_E_1 { public static int Main_old() { long source; int dest; source = 1; dest = (int)source; if (dest == 1) return 0; else return 1; } public static bool testMethod() { return (Main_old() == 0); } } public class BasicTestClass_long_int_E_2 { public static int Main_old() { long source; int dest; source = 2147483647; dest = (int)source; if (dest == 2147483647) return 0; else return 1; } public static bool testMethod() { return (Main_old() == 0); } } public class BasicTestClass_long_int_E_3 { public static int Main_old() { long source; int dest; source = -2147483647; dest = (int)source; if (dest == -2147483647) return 0; else return 1; } public static bool testMethod() { return (Main_old() == 0); } } public class BasicTestClass_long_int_E_4 { public static int Main_old() { long source; int dest; source = -2147483649; dest = (int)source; if (dest == 2147483647) return 0; else return 1; } public static bool testMethod() { return (Main_old() == 0); } } public class BasicTestClass_long_uint_E_1 { public static int Main_old() { long source; uint dest; source = 1; dest = (uint)source; if (dest == 1) return 0; else return 1; } public static bool testMethod() { return (Main_old() == 0); } } public class BasicTestClass_long_uint_E_2 { public static int Main_old() { long source; uint dest; source = 4294967295; dest = (uint)source; if (dest == 4294967295) return 0; else return 1; } public static bool testMethod() { return (Main_old() == 0); } } public class BasicTestClass_long_uint_E_3 { public static int Main_old() { long source; uint dest; source = 0; dest = (uint)source; if (dest == 0) return 0; else return 1; } public static bool testMethod() { return (Main_old() == 0); } } public class BasicTestClass_long_uint_E_4 { public static int Main_old() { long source; uint dest; source = -1; dest = (uint)source; if (dest == 4294967295) return 0; else return 1; } public static bool testMethod() { return (Main_old() == 0); } } public class BasicTestClass_long_ulong_E_1 { public static int Main_old() { long source; ulong dest; source = 1; dest = (ulong)source; if (dest == 1) return 0; else return 1; } public static bool testMethod() { return (Main_old() == 0); } } public class BasicTestClass_long_ulong_E_2 { public static int Main_old() { long source; ulong dest; source = 0; dest = (ulong)source; if (dest == 0) return 0; else return 1; } public static bool testMethod() { return (Main_old() == 0); } } public class BasicTestClass_long_char_E_1 { public static int Main_old() { long source; char dest; source = 1; dest = (char)source; if (dest == '\x1') return 0; else return 1; } public static bool testMethod() { return (Main_old() == 0); } } public class BasicTestClass_long_char_E_2 { public static int Main_old() { long source; char dest; source = 65535; dest = (char)source; if (dest == '\xffff') return 0; else return 1; } public static bool testMethod() { return (Main_old() == 0); } } public class BasicTestClass_long_char_E_3 { public static int Main_old() { long source; char dest; source = 0; dest = (char)source; if (dest == '\x0') return 0; else return 1; } public static bool testMethod() { return (Main_old() == 0); } } public class BasicTestClass_long_char_E_4 { public static int Main_old() { long source; char dest; source = -1; dest = (char)source; if (dest == '\xffff') return 0; else return 1; } public static bool testMethod() { return (Main_old() == 0); } } public class BasicTestClass_sbyte_sbyte_I_0 { public static int Main_old() { sbyte source; sbyte dest; source = 1; dest = source; if (dest == 1) return 0; else return 1; } public static bool testMethod() { return (Main_old() == 0); } } public class BasicTestClass_sbyte_sbyte_E_0 { public static int Main_old() { sbyte source; sbyte dest; source = 1; dest = (sbyte)source; if (dest == 1) return 0; else return 1; } public static bool testMethod() { return (Main_old() == 0); } } public class BasicTestClass_sbyte_short_I_0 { public static int Main_old() { sbyte source; short dest; source = 1; dest = source; if (dest == 1) return 0; else return 1; } public static bool testMethod() { return (Main_old() == 0); } } public class BasicTestClass_sbyte_short_E_0 { public static int Main_old() { sbyte source; short dest; source = 1; dest = (short)source; if (dest == 1) return 0; else return 1; } public static bool testMethod() { return (Main_old() == 0); } } public class BasicTestClass_sbyte_int_I_0 { public static int Main_old() { sbyte source; int dest; source = 1; dest = source; if (dest == 1) return 0; else return 1; } public static bool testMethod() { return (Main_old() == 0); } } public class BasicTestClass_sbyte_int_E_0 { public static int Main_old() { sbyte source; int dest; source = 1; dest = (int)source; if (dest == 1) return 0; else return 1; } public static bool testMethod() { return (Main_old() == 0); } } public class BasicTestClass_sbyte_long_I_0 { public static int Main_old() { sbyte source; long dest; source = 1; dest = source; if (dest == 1) return 0; else return 1; } public static bool testMethod() { return (Main_old() == 0); } } public class BasicTestClass_sbyte_long_E_0 { public static int Main_old() { sbyte source; long dest; source = 1; dest = (long)source; if (dest == 1) return 0; else return 1; } public static bool testMethod() { return (Main_old() == 0); } } public class BasicTestClass_sbyte_float_I_0 { public static int Main_old() { sbyte source; float dest; source = 1; dest = source; if (dest == 1F) return 0; else return 1; } public static bool testMethod() { return (Main_old() == 0); } } public class BasicTestClass_sbyte_float_E_0 { public static int Main_old() { sbyte source; float dest; source = 1; dest = (float)source; if (dest == 1F) return 0; else return 1; } public static bool testMethod() { return (Main_old() == 0); } } public class BasicTestClass_sbyte_double_I_0 { public static int Main_old() { sbyte source; double dest; source = 1; dest = source; if (dest == 1.0) return 0; else return 1; } public static bool testMethod() { return (Main_old() == 0); } } public class BasicTestClass_sbyte_double_E_0 { public static int Main_old() { sbyte source; double dest; source = 1; dest = (double)source; if (dest == 1.0) return 0; else return 1; } public static bool testMethod() { return (Main_old() == 0); } } public class BasicTestClass_sbyte_byte_E_1 { public static int Main_old() { sbyte source; byte dest; source = 1; dest = (byte)source; if (dest == 1) return 0; else return 1; } public static bool testMethod() { return (Main_old() == 0); } } public class BasicTestClass_sbyte_byte_E_2 { public static int Main_old() { sbyte source; byte dest; source = 0; dest = (byte)source; if (dest == 0) return 0; else return 1; } public static bool testMethod() { return (Main_old() == 0); } } public class BasicTestClass_sbyte_byte_E_3 { public static int Main_old() { sbyte source; byte dest; source = -1; dest = (byte)source; if (dest == 255) return 0; else return 1; } public static bool testMethod() { return (Main_old() == 0); } } public class BasicTestClass_sbyte_ushort_E_1 { public static int Main_old() { sbyte source; ushort dest; source = 1; dest = (ushort)source; if (dest == 1) return 0; else return 1; } public static bool testMethod() { return (Main_old() == 0); } } public class BasicTestClass_sbyte_uint_E_1 { public static int Main_old() { sbyte source; uint dest; source = 1; dest = (uint)source; if (dest == 1) return 0; else return 1; } public static bool testMethod() { return (Main_old() == 0); } } public class BasicTestClass_sbyte_ulong_E_1 { public static int Main_old() { sbyte source; ulong dest; source = 1; dest = (ulong)source; if (dest == 1) return 0; else return 1; } public static bool testMethod() { return (Main_old() == 0); } } public class BasicTestClass_sbyte_char_E_1 { public static int Main_old() { sbyte source; char dest; source = 1; dest = (char)source; if (dest == '\x1') return 0; else return 1; } public static bool testMethod() { return (Main_old() == 0); } } public class BasicTestClass_short_short_I_0 { public static int Main_old() { short source; short dest; source = 1; dest = source; if (dest == 1) return 0; else return 1; } public static bool testMethod() { return (Main_old() == 0); } } public class BasicTestClass_short_short_E_0 { public static int Main_old() { short source; short dest; source = 1; dest = (short)source; if (dest == 1) return 0; else return 1; } public static bool testMethod() { return (Main_old() == 0); } } public class BasicTestClass_short_int_I_0 { public static int Main_old() { short source; int dest; source = 1; dest = source; if (dest == 1) return 0; else return 1; } public static bool testMethod() { return (Main_old() == 0); } } public class BasicTestClass_short_int_E_0 { public static int Main_old() { short source; int dest; source = 1; dest = (int)source; if (dest == 1) return 0; else return 1; } public static bool testMethod() { return (Main_old() == 0); } } public class BasicTestClass_short_long_I_0 { public static int Main_old() { short source; long dest; source = 1; dest = source; if (dest == 1) return 0; else return 1; } public static bool testMethod() { return (Main_old() == 0); } } public class BasicTestClass_short_long_E_0 { public static int Main_old() { short source; long dest; source = 1; dest = (long)source; if (dest == 1) return 0; else return 1; } public static bool testMethod() { return (Main_old() == 0); } } public class BasicTestClass_short_float_I_0 { public static int Main_old() { short source; float dest; source = 1; dest = source; if (dest == 1F) return 0; else return 1; } public static bool testMethod() { return (Main_old() == 0); } } public class BasicTestClass_short_float_E_0 { public static int Main_old() { short source; float dest; source = 1; dest = (float)source; if (dest == 1F) return 0; else return 1; } public static bool testMethod() { return (Main_old() == 0); } } public class BasicTestClass_short_double_I_0 { public static int Main_old() { short source; double dest; source = 1; dest = source; if (dest == 1.0) return 0; else return 1; } public static bool testMethod() { return (Main_old() == 0); } } public class BasicTestClass_short_double_E_0 { public static int Main_old() { short source; double dest; source = 1; dest = (double)source; if (dest == 1.0) return 0; else return 1; } public static bool testMethod() { return (Main_old() == 0); } } public class BasicTestClass_short_short_I_1 { public static int Main_old() { short source; short dest; source = -1; dest = source; if (dest == -1) return 0; else return 1; } public static bool testMethod() { return (Main_old() == 0); } } public class BasicTestClass_short_short_E_1 { public static int Main_old() { short source; short dest; source = -1; dest = (short)source; if (dest == -1) return 0; else return 1; } public static bool testMethod() { return (Main_old() == 0); } } public class BasicTestClass_short_int_I_1 { public static int Main_old() { short source; int dest; source = -1; dest = source; if (dest == -1) return 0; else return 1; } public static bool testMethod() { return (Main_old() == 0); } } public class BasicTestClass_short_int_E_1 { public static int Main_old() { short source; int dest; source = -1; dest = (int)source; if (dest == -1) return 0; else return 1; } public static bool testMethod() { return (Main_old() == 0); } } public class BasicTestClass_short_long_I_1 { public static int Main_old() { short source; long dest; source = -1; dest = source; if (dest == -1) return 0; else return 1; } public static bool testMethod() { return (Main_old() == 0); } } public class BasicTestClass_short_long_E_1 { public static int Main_old() { short source; long dest; source = -1; dest = (long)source; if (dest == -1) return 0; else return 1; } public static bool testMethod() { return (Main_old() == 0); } } public class BasicTestClass_short_float_I_1 { public static int Main_old() { short source; float dest; source = -1; dest = source; if (dest == -1F) return 0; else return 1; } public static bool testMethod() { return (Main_old() == 0); } } public class BasicTestClass_short_float_E_1 { public static int Main_old() { short source; float dest; source = -1; dest = (float)source; if (dest == -1F) return 0; else return 1; } public static bool testMethod() { return (Main_old() == 0); } } public class BasicTestClass_short_double_I_1 { public static int Main_old() { short source; double dest; source = -1; dest = source; if (dest == -1.0) return 0; else return 1; } public static bool testMethod() { return (Main_old() == 0); } } public class BasicTestClass_short_double_E_1 { public static int Main_old() { short source; double dest; source = -1; dest = (double)source; if (dest == -1.0) return 0; else return 1; } public static bool testMethod() { return (Main_old() == 0); } } public class BasicTestClass_short_decimal_I_1 { public static int Main_old() { short source; double dest; source = -1; dest = source; if (dest == -1) return 0; else return 1; } public static bool testMethod() { return (Main_old() == 0); } } public class BasicTestClass_short_decimal_E_1 { public static int Main_old() { short source; double dest; source = -1; dest = (double)source; if (dest == -1) return 0; else return 1; } public static bool testMethod() { return (Main_old() == 0); } } public class BasicTestClass_short_sbyte_E_1 { public static int Main_old() { short source; sbyte dest; source = 1; dest = (sbyte)source; if (dest == 1) return 0; else return 1; } public static bool testMethod() { return (Main_old() == 0); } } public class BasicTestClass_short_sbyte_E_2 { public static int Main_old() { short source; sbyte dest; source = 127; dest = (sbyte)source; if (dest == 127) return 0; else return 1; } public static bool testMethod() { return (Main_old() == 0); } } public class BasicTestClass_short_sbyte_E_3 { public static int Main_old() { short source; sbyte dest; source = -128; dest = (sbyte)source; if (dest == -128) return 0; else return 1; } public static bool testMethod() { return (Main_old() == 0); } } public class BasicTestClass_short_sbyte_E_4 { public static int Main_old() { short source; sbyte dest; source = -129; dest = (sbyte)source; if (dest == 127) return 0; else return 1; } public static bool testMethod() { return (Main_old() == 0); } } public class BasicTestClass_short_byte_E_1 { public static int Main_old() { short source; byte dest; source = 1; dest = (byte)source; if (dest == 1) return 0; else return 1; } public static bool testMethod() { return (Main_old() == 0); } } public class BasicTestClass_short_byte_E_2 { public static int Main_old() { short source; byte dest; source = 255; dest = (byte)source; if (dest == 255) return 0; else return 1; } public static bool testMethod() { return (Main_old() == 0); } } public class BasicTestClass_short_byte_E_3 { public static int Main_old() { short source; byte dest; source = 0; dest = (byte)source; if (dest == 0) return 0; else return 1; } public static bool testMethod() { return (Main_old() == 0); } } public class BasicTestClass_short_byte_E_4 { public static int Main_old() { short source; byte dest; source = -1; dest = (byte)source; if (dest == 255) return 0; else return 1; } public static bool testMethod() { return (Main_old() == 0); } } public class BasicTestClass_short_ushort_E_1 { public static int Main_old() { short source; ushort dest; source = 1; dest = (ushort)source; if (dest == 1) return 0; else return 1; } public static bool testMethod() { return (Main_old() == 0); } } public class BasicTestClass_short_ushort_E_2 { public static int Main_old() { short source; ushort dest; source = 0; dest = (ushort)source; if (dest == 0) return 0; else return 1; } public static bool testMethod() { return (Main_old() == 0); } } public class BasicTestClass_short_ushort_E_3 { public static int Main_old() { short source; ushort dest; source = -1; dest = (ushort)source; if (dest == 65535) return 0; else return 1; } public static bool testMethod() { return (Main_old() == 0); } } public class BasicTestClass_short_uint_E_1 { public static int Main_old() { short source; uint dest; source = 1; dest = (uint)source; if (dest == 1) return 0; else return 1; } public static bool testMethod() { return (Main_old() == 0); } } public class BasicTestClass_short_ulong_E_1 { public static int Main_old() { short source; ulong dest; source = 1; dest = (ulong)source; if (dest == 1) return 0; else return 1; } public static bool testMethod() { return (Main_old() == 0); } } public class BasicTestClass_short_char_E_1 { public static int Main_old() { short source; char dest; source = 1; dest = (char)source; if (dest == '\x1') return 0; else return 1; } public static bool testMethod() { return (Main_old() == 0); } } public class BasicTestClass_short_char_E_2 { public static int Main_old() { short source; char dest; source = 0; dest = (char)source; if (dest == '\x0') return 0; else return 1; } public static bool testMethod() { return (Main_old() == 0); } } public class BasicTestClass_short_char_E_3 { public static int Main_old() { short source; char dest; source = -1; dest = (char)source; if (dest == '\xffff') return 0; else return 1; } public static bool testMethod() { return (Main_old() == 0); } } public class BasicTestClass_uint_uint_I_0 { public static int Main_old() { uint source; uint dest; source = 1; dest = source; if (dest == 1) return 0; else return 1; } public static bool testMethod() { return (Main_old() == 0); } } public class BasicTestClass_uint_uint_E_0 { public static int Main_old() { uint source; uint dest; source = 1; dest = (uint)source; if (dest == 1) return 0; else return 1; } public static bool testMethod() { return (Main_old() == 0); } } public class BasicTestClass_uint_long_I_0 { public static int Main_old() { uint source; long dest; source = 1; dest = source; if (dest == 1) return 0; else return 1; } public static bool testMethod() { return (Main_old() == 0); } } public class BasicTestClass_uint_long_E_0 { public static int Main_old() { uint source; long dest; source = 1; dest = (long)source; if (dest == 1) return 0; else return 1; } public static bool testMethod() { return (Main_old() == 0); } } public class BasicTestClass_uint_ulong_I_0 { public static int Main_old() { uint source; ulong dest; source = 1; dest = source; if (dest == 1) return 0; else return 1; } public static bool testMethod() { return (Main_old() == 0); } } public class BasicTestClass_uint_ulong_E_0 { public static int Main_old() { uint source; ulong dest; source = 1; dest = (ulong)source; if (dest == 1) return 0; else return 1; } public static bool testMethod() { return (Main_old() == 0); } } public class BasicTestClass_uint_float_I_0 { public static int Main_old() { uint source; float dest; source = 1; dest = source; if (dest == 1F) return 0; else return 1; } public static bool testMethod() { return (Main_old() == 0); } } public class BasicTestClass_uint_float_E_0 { public static int Main_old() { uint source; float dest; source = 1; dest = (float)source; if (dest == 1F) return 0; else return 1; } public static bool testMethod() { return (Main_old() == 0); } } public class BasicTestClass_uint_double_I_0 { public static int Main_old() { uint source; double dest; source = 1; dest = source; if (dest == 1.0) return 0; else return 1; } public static bool testMethod() { return (Main_old() == 0); } } public class BasicTestClass_uint_double_E_0 { public static int Main_old() { uint source; double dest; source = 1; dest = (double)source; if (dest == 1.0) return 0; else return 1; } public static bool testMethod() { return (Main_old() == 0); } } public class BasicTestClass_uint_sbyte_E_1 { public static int Main_old() { uint source; sbyte dest; source = 1; dest = (sbyte)source; if (dest == 1) return 0; else return 1; } public static bool testMethod() { return (Main_old() == 0); } } public class BasicTestClass_uint_sbyte_E_2 { public static int Main_old() { uint source; sbyte dest; source = 127; dest = (sbyte)source; if (dest == 127) return 0; else return 1; } public static bool testMethod() { return (Main_old() == 0); } } public class BasicTestClass_uint_byte_E_1 { public static int Main_old() { uint source; byte dest; source = 1; dest = (byte)source; if (dest == 1) return 0; else return 1; } public static bool testMethod() { return (Main_old() == 0); } } public class BasicTestClass_uint_byte_E_2 { public static int Main_old() { uint source; byte dest; source = 255; dest = (byte)source; if (dest == 255) return 0; else return 1; } public static bool testMethod() { return (Main_old() == 0); } } public class BasicTestClass_uint_byte_E_3 { public static int Main_old() { uint source; byte dest; source = 0; dest = (byte)source; if (dest == 0) return 0; else return 1; } public static bool testMethod() { return (Main_old() == 0); } } public class BasicTestClass_uint_short_E_1 { public static int Main_old() { uint source; short dest; source = 1; dest = (short)source; if (dest == 1) return 0; else return 1; } public static bool testMethod() { return (Main_old() == 0); } } public class BasicTestClass_uint_short_E_2 { public static int Main_old() { uint source; short dest; source = 32767; dest = (short)source; if (dest == 32767) return 0; else return 1; } public static bool testMethod() { return (Main_old() == 0); } } public class BasicTestClass_uint_ushort_E_1 { public static int Main_old() { uint source; ushort dest; source = 1; dest = (ushort)source; if (dest == 1) return 0; else return 1; } public static bool testMethod() { return (Main_old() == 0); } } public class BasicTestClass_uint_ushort_E_2 { public static int Main_old() { uint source; ushort dest; source = 65535; dest = (ushort)source; if (dest == 65535) return 0; else return 1; } public static bool testMethod() { return (Main_old() == 0); } } public class BasicTestClass_uint_ushort_E_3 { public static int Main_old() { uint source; ushort dest; source = 0; dest = (ushort)source; if (dest == 0) return 0; else return 1; } public static bool testMethod() { return (Main_old() == 0); } } public class BasicTestClass_uint_int_E_1 { public static int Main_old() { uint source; int dest; source = 1; dest = (int)source; if (dest == 1) return 0; else return 1; } public static bool testMethod() { return (Main_old() == 0); } } public class BasicTestClass_uint_int_E_2 { public static int Main_old() { uint source; int dest; source = 2147483647; dest = (int)source; if (dest == 2147483647) return 0; else return 1; } public static bool testMethod() { return (Main_old() == 0); } } public class BasicTestClass_uint_char_E_1 { public static int Main_old() { uint source; char dest; source = 1; dest = (char)source; if (dest == '\x1') return 0; else return 1; } public static bool testMethod() { return (Main_old() == 0); } } public class BasicTestClass_uint_char_E_2 { public static int Main_old() { uint source; char dest; source = 65535; dest = (char)source; if (dest == '\xffff') return 0; else return 1; } public static bool testMethod() { return (Main_old() == 0); } } public class BasicTestClass_uint_char_E_3 { public static int Main_old() { uint source; char dest; source = 0; dest = (char)source; if (dest == '\x0') return 0; else return 1; } public static bool testMethod() { return (Main_old() == 0); } } public class BasicTestClass_ulong_float_I_0 { public static int Main_old() { ulong source; float dest; source = 1; dest = source; if (dest == 1F) return 0; else return 1; } public static bool testMethod() { return (Main_old() == 0); } } public class BasicTestClass_ulong_float_E_0 { public static int Main_old() { ulong source; float dest; source = 1; dest = (float)source; if (dest == 1F) return 0; else return 1; } public static bool testMethod() { return (Main_old() == 0); } } public class BasicTestClass_ulong_double_I_0 { public static int Main_old() { ulong source; double dest; source = 1; dest = source; if (dest == 1.0) return 0; else return 1; } public static bool testMethod() { return (Main_old() == 0); } } public class BasicTestClass_ulong_double_E_0 { public static int Main_old() { ulong source; double dest; source = 1; dest = (double)source; if (dest == 1.0) return 0; else return 1; } public static bool testMethod() { return (Main_old() == 0); } } public class BasicTestClass_ulong_ulong_I_0 { public static int Main_old() { ulong source; ulong dest; source = 1; dest = source; if (dest == 1) return 0; else return 1; } public static bool testMethod() { return (Main_old() == 0); } } public class BasicTestClass_ulong_ulong_E_0 { public static int Main_old() { ulong source; ulong dest; source = 1; dest = (ulong)source; if (dest == 1) return 0; else return 1; } public static bool testMethod() { return (Main_old() == 0); } } public class BasicTestClass_ulong_sbyte_E_1 { public static int Main_old() { ulong source; sbyte dest; source = 1; dest = (sbyte)source; if (dest == 1) return 0; else return 1; } public static bool testMethod() { return (Main_old() == 0); } } public class BasicTestClass_ulong_sbyte_E_2 { public static int Main_old() { ulong source; sbyte dest; source = 127; dest = (sbyte)source; if (dest == 127) return 0; else return 1; } public static bool testMethod() { return (Main_old() == 0); } } public class BasicTestClass_ulong_byte_E_1 { public static int Main_old() { ulong source; byte dest; source = 1; dest = (byte)source; if (dest == 1) return 0; else return 1; } public static bool testMethod() { return (Main_old() == 0); } } public class BasicTestClass_ulong_byte_E_2 { public static int Main_old() { ulong source; byte dest; source = 255; dest = (byte)source; if (dest == 255) return 0; else return 1; } public static bool testMethod() { return (Main_old() == 0); } } public class BasicTestClass_ulong_byte_E_3 { public static int Main_old() { ulong source; byte dest; source = 0; dest = (byte)source; if (dest == 0) return 0; else return 1; } public static bool testMethod() { return (Main_old() == 0); } } public class BasicTestClass_ulong_short_E_1 { public static int Main_old() { ulong source; short dest; source = 1; dest = (short)source; if (dest == 1) return 0; else return 1; } public static bool testMethod() { return (Main_old() == 0); } } public class BasicTestClass_ulong_short_E_2 { public static int Main_old() { ulong source; short dest; source = 32767; dest = (short)source; if (dest == 32767) return 0; else return 1; } public static bool testMethod() { return (Main_old() == 0); } } public class BasicTestClass_ulong_ushort_E_1 { public static int Main_old() { ulong source; ushort dest; source = 1; dest = (ushort)source; if (dest == 1) return 0; else return 1; } public static bool testMethod() { return (Main_old() == 0); } } public class BasicTestClass_ulong_ushort_E_2 { public static int Main_old() { ulong source; ushort dest; source = 65535; dest = (ushort)source; if (dest == 65535) return 0; else return 1; } public static bool testMethod() { return (Main_old() == 0); } } public class BasicTestClass_ulong_ushort_E_3 { public static int Main_old() { ulong source; ushort dest; source = 0; dest = (ushort)source; if (dest == 0) return 0; else return 1; } public static bool testMethod() { return (Main_old() == 0); } } public class BasicTestClass_ulong_int_E_1 { public static int Main_old() { ulong source; int dest; source = 1; dest = (int)source; if (dest == 1) return 0; else return 1; } public static bool testMethod() { return (Main_old() == 0); } } public class BasicTestClass_ulong_int_E_2 { public static int Main_old() { ulong source; int dest; source = 2147483647; dest = (int)source; if (dest == 2147483647) return 0; else return 1; } public static bool testMethod() { return (Main_old() == 0); } } public class BasicTestClass_ulong_uint_E_1 { public static int Main_old() { ulong source; uint dest; source = 1; dest = (uint)source; if (dest == 1) return 0; else return 1; } public static bool testMethod() { return (Main_old() == 0); } } public class BasicTestClass_ulong_uint_E_2 { public static int Main_old() { ulong source; uint dest; source = 4294967295; dest = (uint)source; if (dest == 4294967295) return 0; else return 1; } public static bool testMethod() { return (Main_old() == 0); } } public class BasicTestClass_ulong_uint_E_3 { public static int Main_old() { ulong source; uint dest; source = 0; dest = (uint)source; if (dest == 0) return 0; else return 1; } public static bool testMethod() { return (Main_old() == 0); } } public class BasicTestClass_ulong_long_E_1 { public static int Main_old() { ulong source; long dest; source = 1; dest = (long)source; if (dest == 1) return 0; else return 1; } public static bool testMethod() { return (Main_old() == 0); } } public class BasicTestClass_ulong_long_E_2 { public static int Main_old() { ulong source; long dest; source = 9223372036854775807; dest = (long)source; if (dest == 9223372036854775807) return 0; else return 1; } public static bool testMethod() { return (Main_old() == 0); } } public class BasicTestClass_ulong_char_E_1 { public static int Main_old() { ulong source; char dest; source = 1; dest = (char)source; if (dest == '\x1') return 0; else return 1; } public static bool testMethod() { return (Main_old() == 0); } } public class BasicTestClass_ulong_char_E_2 { public static int Main_old() { ulong source; char dest; source = 65535; dest = (char)source; if (dest == '\xffff') return 0; else return 1; } public static bool testMethod() { return (Main_old() == 0); } } public class BasicTestClass_ulong_char_E_3 { public static int Main_old() { ulong source; char dest; source = 0; dest = (char)source; if (dest == '\x0') return 0; else return 1; } public static bool testMethod() { return (Main_old() == 0); } } public class BasicTestClass_ushort_ushort_I_0 { public static int Main_old() { ushort source; ushort dest; source = 1; dest = source; if (dest == 1) return 0; else return 1; } public static bool testMethod() { return (Main_old() == 0); } } public class BasicTestClass_ushort_ushort_E_0 { public static int Main_old() { ushort source; ushort dest; source = 1; dest = (ushort)source; if (dest == 1) return 0; else return 1; } public static bool testMethod() { return (Main_old() == 0); } } public class BasicTestClass_ushort_int_I_0 { public static int Main_old() { ushort source; int dest; source = 1; dest = source; if (dest == 1) return 0; else return 1; } public static bool testMethod() { return (Main_old() == 0); } } public class BasicTestClass_ushort_int_E_0 { public static int Main_old() { ushort source; int dest; source = 1; dest = (int)source; if (dest == 1) return 0; else return 1; } public static bool testMethod() { return (Main_old() == 0); } } public class BasicTestClass_ushort_uint_I_0 { public static int Main_old() { ushort source; uint dest; source = 1; dest = source; if (dest == 1) return 0; else return 1; } public static bool testMethod() { return (Main_old() == 0); } } public class BasicTestClass_ushort_uint_E_0 { public static int Main_old() { ushort source; uint dest; source = 1; dest = (uint)source; if (dest == 1) return 0; else return 1; } public static bool testMethod() { return (Main_old() == 0); } } public class BasicTestClass_ushort_long_I_0 { public static int Main_old() { ushort source; long dest; source = 1; dest = source; if (dest == 1) return 0; else return 1; } public static bool testMethod() { return (Main_old() == 0); } } public class BasicTestClass_ushort_long_E_0 { public static int Main_old() { ushort source; long dest; source = 1; dest = (long)source; if (dest == 1) return 0; else return 1; } public static bool testMethod() { return (Main_old() == 0); } } public class BasicTestClass_ushort_ulong_I_0 { public static int Main_old() { ushort source; ulong dest; source = 1; dest = source; if (dest == 1) return 0; else return 1; } public static bool testMethod() { return (Main_old() == 0); } } public class BasicTestClass_ushort_ulong_E_0 { public static int Main_old() { ushort source; ulong dest; source = 1; dest = (ulong)source; if (dest == 1) return 0; else return 1; } public static bool testMethod() { return (Main_old() == 0); } } public class BasicTestClass_ushort_float_I_0 { public static int Main_old() { ushort source; float dest; source = 1; dest = source; if (dest == 1F) return 0; else return 1; } public static bool testMethod() { return (Main_old() == 0); } } public class BasicTestClass_ushort_float_E_0 { public static int Main_old() { ushort source; float dest; source = 1; dest = (float)source; if (dest == 1F) return 0; else return 1; } public static bool testMethod() { return (Main_old() == 0); } } public class BasicTestClass_ushort_double_I_0 { public static int Main_old() { ushort source; double dest; source = 1; dest = source; if (dest == 1.0) return 0; else return 1; } public static bool testMethod() { return (Main_old() == 0); } } public class BasicTestClass_ushort_double_E_0 { public static int Main_old() { ushort source; double dest; source = 1; dest = (double)source; if (dest == 1.0) return 0; else return 1; } public static bool testMethod() { return (Main_old() == 0); } } public class BasicTestClass_ushort_sbyte_E_1 { public static int Main_old() { ushort source; sbyte dest; source = 1; dest = (sbyte)source; if (dest == 1) return 0; else return 1; } public static bool testMethod() { return (Main_old() == 0); } } public class BasicTestClass_ushort_sbyte_E_2 { public static int Main_old() { ushort source; sbyte dest; source = 127; dest = (sbyte)source; if (dest == 127) return 0; else return 1; } public static bool testMethod() { return (Main_old() == 0); } } public class BasicTestClass_ushort_byte_E_1 { public static int Main_old() { ushort source; byte dest; source = 1; dest = (byte)source; if (dest == 1) return 0; else return 1; } public static bool testMethod() { return (Main_old() == 0); } } public class BasicTestClass_ushort_byte_E_2 { public static int Main_old() { ushort source; byte dest; source = 255; dest = (byte)source; if (dest == 255) return 0; else return 1; } public static bool testMethod() { return (Main_old() == 0); } } public class BasicTestClass_ushort_byte_E_3 { public static int Main_old() { ushort source; byte dest; source = 0; dest = (byte)source; if (dest == 0) return 0; else return 1; } public static bool testMethod() { return (Main_old() == 0); } } public class BasicTestClass_ushort_short_E_1 { public static int Main_old() { ushort source; short dest; source = 1; dest = (short)source; if (dest == 1) return 0; else return 1; } public static bool testMethod() { return (Main_old() == 0); } } public class BasicTestClass_ushort_short_E_2 { public static int Main_old() { ushort source; short dest; source = 32767; dest = (short)source; if (dest == 32767) return 0; else return 1; } public static bool testMethod() { return (Main_old() == 0); } } public class BasicTestClass_ushort_char_E_1 { public static int Main_old() { ushort source; char dest; source = 1; dest = (char)source; if (dest == '\x1') return 0; else return 1; } public static bool testMethod() { return (Main_old() == 0); } } public class BasicTestClass_ushort_char_E_2 { public static int Main_old() { ushort source; char dest; source = 65535; dest = (char)source; if (dest == '\xffff') return 0; else return 1; } public static bool testMethod() { return (Main_old() == 0); } } public class BasicTestClass_ushort_char_E_3 { public static int Main_old() { ushort source; char dest; source = 0; dest = (char)source; if (dest == '\x0') return 0; else return 1; } public static bool testMethod() { return (Main_old() == 0); } } } */ } ================================================ FILE: Zelig/Zelig/Test/RunTime/NETMF/mscorlib/conversions/basic2/BasicTests2.cs ================================================ //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // Copyright (c) Microsoft Corporation. All rights reserved. //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// using System; namespace Microsoft.Zelig.Test { /* public class BasicTests2 : TestBase, ITestInterface { [SetUp] public InitializeResult Initialize() { Log.Comment("Adding set up for the tests"); Log.Comment("The Basic tests examine conversion between two types"); Log.Comment("The tests are named for the types they convert between"); Log.Comment("Some of them are also list with E or I for the cast being explicit or implicit"); Log.Comment("In the case of a number of tests being run, 0, 1, maxValue and minValue are tested"); // Add your functionality here. return InitializeResult.ReadyToGo; } [TearDown] public void CleanUp() { Log.Comment("Cleaning up after the tests"); } public override TestResult Run( string[] args ) { TestResult result = TestResult.Pass; string testName = "Basic2_"; int testNumber = 0; result |= Assert.CheckFailed( Basic_ulong_float_I_0_Test( ), testName, ++testNumber ); result |= Assert.CheckFailed( Basic_ulong_float_E_0_Test( ), testName, ++testNumber ); result |= Assert.CheckFailed( Basic_ulong_double_I_0_Test( ), testName, ++testNumber ); result |= Assert.CheckFailed( Basic_ulong_double_E_0_Test( ), testName, ++testNumber ); result |= Assert.CheckFailed( Basic_ulong_ulong_I_0_Test( ), testName, ++testNumber ); result |= Assert.CheckFailed( Basic_ulong_ulong_E_0_Test( ), testName, ++testNumber ); result |= Assert.CheckFailed( Basic_ulong_sbyte_E_1_Test( ), testName, ++testNumber ); result |= Assert.CheckFailed( Basic_ulong_sbyte_E_2_Test( ), testName, ++testNumber ); result |= Assert.CheckFailed( Basic_ulong_byte_E_1_Test( ), testName, ++testNumber ); result |= Assert.CheckFailed( Basic_ulong_byte_E_2_Test( ), testName, ++testNumber ); result |= Assert.CheckFailed( Basic_ulong_byte_E_3_Test( ), testName, ++testNumber ); result |= Assert.CheckFailed( Basic_ulong_short_E_1_Test( ), testName, ++testNumber ); result |= Assert.CheckFailed( Basic_ulong_short_E_2_Test( ), testName, ++testNumber ); result |= Assert.CheckFailed( Basic_ulong_ushort_E_1_Test( ), testName, ++testNumber ); result |= Assert.CheckFailed( Basic_ulong_ushort_E_2_Test( ), testName, ++testNumber ); result |= Assert.CheckFailed( Basic_ulong_ushort_E_3_Test( ), testName, ++testNumber ); result |= Assert.CheckFailed( Basic_ulong_int_E_1_Test( ), testName, ++testNumber ); result |= Assert.CheckFailed( Basic_ulong_int_E_2_Test( ), testName, ++testNumber ); result |= Assert.CheckFailed( Basic_ulong_uint_E_1_Test( ), testName, ++testNumber ); result |= Assert.CheckFailed( Basic_ulong_uint_E_2_Test( ), testName, ++testNumber ); result |= Assert.CheckFailed( Basic_ulong_uint_E_3_Test( ), testName, ++testNumber ); result |= Assert.CheckFailed( Basic_ulong_long_E_1_Test( ), testName, ++testNumber ); result |= Assert.CheckFailed( Basic_ulong_long_E_2_Test( ), testName, ++testNumber ); result |= Assert.CheckFailed( Basic_ulong_char_E_1_Test( ), testName, ++testNumber ); result |= Assert.CheckFailed( Basic_ulong_char_E_2_Test( ), testName, ++testNumber ); result |= Assert.CheckFailed( Basic_ulong_char_E_3_Test( ), testName, ++testNumber ); result |= Assert.CheckFailed( Basic_ushort_ushort_I_0_Test( ), testName, ++testNumber ); result |= Assert.CheckFailed( Basic_ushort_ushort_E_0_Test( ), testName, ++testNumber ); result |= Assert.CheckFailed( Basic_ushort_int_I_0_Test( ), testName, ++testNumber ); result |= Assert.CheckFailed( Basic_ushort_int_E_0_Test( ), testName, ++testNumber ); result |= Assert.CheckFailed( Basic_ushort_uint_I_0_Test( ), testName, ++testNumber ); result |= Assert.CheckFailed( Basic_ushort_uint_E_0_Test( ), testName, ++testNumber ); result |= Assert.CheckFailed( Basic_ushort_long_I_0_Test( ), testName, ++testNumber ); result |= Assert.CheckFailed( Basic_ushort_long_E_0_Test( ), testName, ++testNumber ); result |= Assert.CheckFailed( Basic_ushort_ulong_I_0_Test( ), testName, ++testNumber ); result |= Assert.CheckFailed( Basic_ushort_ulong_E_0_Test( ), testName, ++testNumber ); result |= Assert.CheckFailed( Basic_ushort_float_I_0_Test( ), testName, ++testNumber ); result |= Assert.CheckFailed( Basic_ushort_float_E_0_Test( ), testName, ++testNumber ); result |= Assert.CheckFailed( Basic_ushort_double_I_0_Test( ), testName, ++testNumber ); result |= Assert.CheckFailed( Basic_ushort_double_E_0_Test( ), testName, ++testNumber ); result |= Assert.CheckFailed( Basic_ushort_sbyte_E_1_Test( ), testName, ++testNumber ); result |= Assert.CheckFailed( Basic_ushort_sbyte_E_2_Test( ), testName, ++testNumber ); result |= Assert.CheckFailed( Basic_ushort_byte_E_1_Test( ), testName, ++testNumber ); result |= Assert.CheckFailed( Basic_ushort_byte_E_2_Test( ), testName, ++testNumber ); result |= Assert.CheckFailed( Basic_ushort_byte_E_3_Test( ), testName, ++testNumber ); result |= Assert.CheckFailed( Basic_ushort_short_E_1_Test( ), testName, ++testNumber ); result |= Assert.CheckFailed( Basic_ushort_short_E_2_Test( ), testName, ++testNumber ); result |= Assert.CheckFailed( Basic_ushort_char_E_1_Test( ), testName, ++testNumber ); result |= Assert.CheckFailed( Basic_ushort_char_E_2_Test( ), testName, ++testNumber ); result |= Assert.CheckFailed( Basic_ushort_char_E_3_Test( ), testName, ++testNumber ); return result; } //Basic Test methods //The following tests were ported from folder current\test\cases\client\CLR\Conformance\10_classes\Basic //byte_byte_I_0,byte_byte_E_0,byte_short_I_0,byte_short_E_0,byte_ushort_I_0,byte_ushort_E_0,byte_int_I_0,byte_int_E_0,byte_uint_I_0,byte_uint_E_0,byte_long_I_0,byte_long_E_0,byte_ulong_I_0,byte_ulong_E_0,byte_float_I_0,byte_float_E_0,byte_double_I_0,byte_double_E_0,byte_sbyte_E_1,byte_sbyte_E_2,byte_char_E_1,char_char_I_0,char_char_E_0,char_ushort_I_0,char_ushort_E_0,char_int_I_0,char_int_E_0,char_uint_I_0,char_uint_E_0,char_long_I_0,char_long_E_0,char_ulong_I_0,char_ulong_E_0,char_float_I_0,char_float_E_0,char_double_I_0,char_double_E_0,char_sbyte_E_1,char_sbyte_E_2,char_byte_E_1,char_byte_E_2,char_byte_E_3,char_short_E_1,char_short_E_2,double_double_I_0,double_double_E_0,double_byte_E_1,double_byte_E_2,double_byte_E_3,double_sbyte_E_1,double_sbyte_E_2,double_sbyte_E_3,double_char_E_1,double_char_E_2,double_char_E_3,double_short_E_1,double_short_E_2,double_short_E_3,double_ushort_E_1,double_ushort_E_2,double_ushort_E_3,double_int_E_1,double_int_E_2,double_int_E_3,double_uint_E_1,double_uint_E_2,double_uint_E_3,double_long_E_1,double_ulong_E_1,double_float_E_1,double_float_E_2,double_float_E_3,float_float_I_0,float_float_E_0,float_double_I_0,float_double_E_0,float_byte_E_1,float_byte_E_2,float_byte_E_3,float_sbyte_E_1,float_sbyte_E_2,float_sbyte_E_3,float_char_E_1,float_char_E_2,float_char_E_3,float_short_E_1,float_short_E_2,float_short_E_3,float_ushort_E_1,float_ushort_E_2,float_ushort_E_3,float_int_E_1,float_uint_E_1,float_long_E_1,float_ulong_E_1,int_int_I_0,int_int_E_0,int_long_I_0,int_long_E_0,int_float_I_0,int_float_E_0,int_double_I_0,int_double_E_0,int_sbyte_E_1,int_sbyte_E_2,int_sbyte_E_3,int_sbyte_E_4,int_byte_E_1,int_byte_E_2,int_byte_E_3,int_byte_E_4,int_short_E_1,int_short_E_2,int_short_E_3,int_short_E_4,int_ushort_E_1,int_ushort_E_2,int_ushort_E_3,int_ushort_E_4,int_uint_E_1,int_uint_E_2,int_uint_E_3,int_ulong_E_1,int_char_E_1,int_char_E_2,int_char_E_3,int_char_E_4,long_long_I_0,long_long_E_0,long_float_I_0,long_float_E_0,long_double_I_0,long_double_E_0,long_sbyte_E_1,long_sbyte_E_2,long_sbyte_E_3,long_sbyte_E_4,long_byte_E_1,long_byte_E_2,long_byte_E_3,long_byte_E_4,long_short_E_1,long_short_E_2,long_short_E_3,long_short_E_4,long_ushort_E_1,long_ushort_E_2,long_ushort_E_3,long_ushort_E_4,long_int_E_1,long_int_E_2,long_int_E_3,long_int_E_4,long_uint_E_1,long_uint_E_2,long_uint_E_3,long_uint_E_4,long_ulong_E_1,long_ulong_E_2,long_char_E_1,long_char_E_2,long_char_E_3,long_char_E_4,sbyte_sbyte_I_0,sbyte_sbyte_E_0,sbyte_short_I_0,sbyte_short_E_0,sbyte_int_I_0,sbyte_int_E_0,sbyte_long_I_0,sbyte_long_E_0,sbyte_float_I_0,sbyte_float_E_0,sbyte_double_I_0,sbyte_double_E_0,sbyte_byte_E_1,sbyte_byte_E_2,sbyte_byte_E_3,sbyte_ushort_E_1,sbyte_uint_E_1,sbyte_ulong_E_1,sbyte_char_E_1,short_short_I_0,short_short_E_0,short_int_I_0,short_int_E_0,short_long_I_0,short_long_E_0,short_float_I_0,short_float_E_0,short_double_I_0,short_double_E_0,short_short_I_1,short_short_E_1,short_int_I_1,short_int_E_1,short_long_I_1,short_long_E_1,short_float_I_1,short_float_E_1,short_double_I_1,short_double_E_1,short_decimal_I_1,short_decimal_E_1,short_sbyte_E_1,short_sbyte_E_2,short_sbyte_E_3,short_sbyte_E_4,short_byte_E_1,short_byte_E_2,short_byte_E_3,short_byte_E_4,short_ushort_E_1,short_ushort_E_2,short_ushort_E_3,short_uint_E_1,short_ulong_E_1,short_char_E_1,short_char_E_2,short_char_E_3,uint_uint_I_0,uint_uint_E_0,uint_long_I_0,uint_long_E_0,uint_ulong_I_0,uint_ulong_E_0,uint_float_I_0,uint_float_E_0,uint_double_I_0,uint_double_E_0,uint_sbyte_E_1,uint_sbyte_E_2,uint_byte_E_1,uint_byte_E_2,uint_byte_E_3,uint_short_E_1,uint_short_E_2,uint_ushort_E_1,uint_ushort_E_2,uint_ushort_E_3,uint_int_E_1,uint_int_E_2,uint_char_E_1,uint_char_E_2,uint_char_E_3,ulong_float_I_0,ulong_float_E_0,ulong_double_I_0,ulong_double_E_0,ulong_ulong_I_0,ulong_ulong_E_0,ulong_sbyte_E_1,ulong_sbyte_E_2,ulong_byte_E_1,ulong_byte_E_2,ulong_byte_E_3,ulong_short_E_1,ulong_short_E_2,ulong_ushort_E_1,ulong_ushort_E_2,ulong_ushort_E_3,ulong_int_E_1,ulong_int_E_2,ulong_uint_E_1,ulong_uint_E_2,ulong_uint_E_3,ulong_long_E_1,ulong_long_E_2,ulong_char_E_1,ulong_char_E_2,ulong_char_E_3,ushort_ushort_I_0,ushort_ushort_E_0,ushort_int_I_0,ushort_int_E_0,ushort_uint_I_0,ushort_uint_E_0,ushort_long_I_0,ushort_long_E_0,ushort_ulong_I_0,ushort_ulong_E_0,ushort_float_I_0,ushort_float_E_0,ushort_double_I_0,ushort_double_E_0,ushort_sbyte_E_1,ushort_sbyte_E_2,ushort_byte_E_1,ushort_byte_E_2,ushort_byte_E_3,ushort_short_E_1,ushort_short_E_2,ushort_char_E_1,ushort_char_E_2,ushort_char_E_3 //Test Case Calls [TestMethod] public TestResult Basic_ulong_float_I_0_Test() { if (BasicTestClass_ulong_float_I_0.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Basic_ulong_float_E_0_Test() { if (BasicTestClass_ulong_float_E_0.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Basic_ulong_double_I_0_Test() { if (BasicTestClass_ulong_double_I_0.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Basic_ulong_double_E_0_Test() { if (BasicTestClass_ulong_double_E_0.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Basic_ulong_ulong_I_0_Test() { if (BasicTestClass_ulong_ulong_I_0.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Basic_ulong_ulong_E_0_Test() { if (BasicTestClass_ulong_ulong_E_0.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Basic_ulong_sbyte_E_1_Test() { if (BasicTestClass_ulong_sbyte_E_1.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Basic_ulong_sbyte_E_2_Test() { if (BasicTestClass_ulong_sbyte_E_2.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Basic_ulong_byte_E_1_Test() { if (BasicTestClass_ulong_byte_E_1.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Basic_ulong_byte_E_2_Test() { if (BasicTestClass_ulong_byte_E_2.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Basic_ulong_byte_E_3_Test() { if (BasicTestClass_ulong_byte_E_3.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Basic_ulong_short_E_1_Test() { if (BasicTestClass_ulong_short_E_1.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Basic_ulong_short_E_2_Test() { if (BasicTestClass_ulong_short_E_2.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Basic_ulong_ushort_E_1_Test() { if (BasicTestClass_ulong_ushort_E_1.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Basic_ulong_ushort_E_2_Test() { if (BasicTestClass_ulong_ushort_E_2.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Basic_ulong_ushort_E_3_Test() { if (BasicTestClass_ulong_ushort_E_3.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Basic_ulong_int_E_1_Test() { if (BasicTestClass_ulong_int_E_1.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Basic_ulong_int_E_2_Test() { if (BasicTestClass_ulong_int_E_2.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Basic_ulong_uint_E_1_Test() { if (BasicTestClass_ulong_uint_E_1.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Basic_ulong_uint_E_2_Test() { if (BasicTestClass_ulong_uint_E_2.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Basic_ulong_uint_E_3_Test() { if (BasicTestClass_ulong_uint_E_3.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Basic_ulong_long_E_1_Test() { if (BasicTestClass_ulong_long_E_1.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Basic_ulong_long_E_2_Test() { if (BasicTestClass_ulong_long_E_2.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Basic_ulong_char_E_1_Test() { if (BasicTestClass_ulong_char_E_1.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Basic_ulong_char_E_2_Test() { if (BasicTestClass_ulong_char_E_2.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Basic_ulong_char_E_3_Test() { if (BasicTestClass_ulong_char_E_3.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Basic_ushort_ushort_I_0_Test() { if (BasicTestClass_ushort_ushort_I_0.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Basic_ushort_ushort_E_0_Test() { if (BasicTestClass_ushort_ushort_E_0.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Basic_ushort_int_I_0_Test() { if (BasicTestClass_ushort_int_I_0.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Basic_ushort_int_E_0_Test() { if (BasicTestClass_ushort_int_E_0.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Basic_ushort_uint_I_0_Test() { if (BasicTestClass_ushort_uint_I_0.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Basic_ushort_uint_E_0_Test() { if (BasicTestClass_ushort_uint_E_0.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Basic_ushort_long_I_0_Test() { if (BasicTestClass_ushort_long_I_0.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Basic_ushort_long_E_0_Test() { if (BasicTestClass_ushort_long_E_0.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Basic_ushort_ulong_I_0_Test() { if (BasicTestClass_ushort_ulong_I_0.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Basic_ushort_ulong_E_0_Test() { if (BasicTestClass_ushort_ulong_E_0.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Basic_ushort_float_I_0_Test() { if (BasicTestClass_ushort_float_I_0.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Basic_ushort_float_E_0_Test() { if (BasicTestClass_ushort_float_E_0.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Basic_ushort_double_I_0_Test() { if (BasicTestClass_ushort_double_I_0.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Basic_ushort_double_E_0_Test() { if (BasicTestClass_ushort_double_E_0.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Basic_ushort_sbyte_E_1_Test() { if (BasicTestClass_ushort_sbyte_E_1.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Basic_ushort_sbyte_E_2_Test() { if (BasicTestClass_ushort_sbyte_E_2.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Basic_ushort_byte_E_1_Test() { if (BasicTestClass_ushort_byte_E_1.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Basic_ushort_byte_E_2_Test() { if (BasicTestClass_ushort_byte_E_2.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Basic_ushort_byte_E_3_Test() { if (BasicTestClass_ushort_byte_E_3.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Basic_ushort_short_E_1_Test() { if (BasicTestClass_ushort_short_E_1.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Basic_ushort_short_E_2_Test() { if (BasicTestClass_ushort_short_E_2.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Basic_ushort_char_E_1_Test() { if (BasicTestClass_ushort_char_E_1.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Basic_ushort_char_E_2_Test() { if (BasicTestClass_ushort_char_E_2.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Basic_ushort_char_E_3_Test() { if (BasicTestClass_ushort_char_E_3.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } //Compiled Test Cases public class BasicTestClass_ulong_float_I_0 { public static int Main_old() { ulong source; float dest; source = 1; dest = source; if (dest == 1F) return 0; else return 1; } public static bool testMethod() { return (Main_old() == 0); } } public class BasicTestClass_ulong_float_E_0 { public static int Main_old() { ulong source; float dest; source = 1; dest = (float)source; if (dest == 1F) return 0; else return 1; } public static bool testMethod() { return (Main_old() == 0); } } public class BasicTestClass_ulong_double_I_0 { public static int Main_old() { ulong source; double dest; source = 1; dest = source; if (dest == 1.0) return 0; else return 1; } public static bool testMethod() { return (Main_old() == 0); } } public class BasicTestClass_ulong_double_E_0 { public static int Main_old() { ulong source; double dest; source = 1; dest = (double)source; if (dest == 1.0) return 0; else return 1; } public static bool testMethod() { return (Main_old() == 0); } } public class BasicTestClass_ulong_ulong_I_0 { public static int Main_old() { ulong source; ulong dest; source = 1; dest = source; if (dest == 1) return 0; else return 1; } public static bool testMethod() { return (Main_old() == 0); } } public class BasicTestClass_ulong_ulong_E_0 { public static int Main_old() { ulong source; ulong dest; source = 1; dest = (ulong)source; if (dest == 1) return 0; else return 1; } public static bool testMethod() { return (Main_old() == 0); } } public class BasicTestClass_ulong_sbyte_E_1 { public static int Main_old() { ulong source; sbyte dest; source = 1; dest = (sbyte)source; if (dest == 1) return 0; else return 1; } public static bool testMethod() { return (Main_old() == 0); } } public class BasicTestClass_ulong_sbyte_E_2 { public static int Main_old() { ulong source; sbyte dest; source = 127; dest = (sbyte)source; if (dest == 127) return 0; else return 1; } public static bool testMethod() { return (Main_old() == 0); } } public class BasicTestClass_ulong_byte_E_1 { public static int Main_old() { ulong source; byte dest; source = 1; dest = (byte)source; if (dest == 1) return 0; else return 1; } public static bool testMethod() { return (Main_old() == 0); } } public class BasicTestClass_ulong_byte_E_2 { public static int Main_old() { ulong source; byte dest; source = 255; dest = (byte)source; if (dest == 255) return 0; else return 1; } public static bool testMethod() { return (Main_old() == 0); } } public class BasicTestClass_ulong_byte_E_3 { public static int Main_old() { ulong source; byte dest; source = 0; dest = (byte)source; if (dest == 0) return 0; else return 1; } public static bool testMethod() { return (Main_old() == 0); } } public class BasicTestClass_ulong_short_E_1 { public static int Main_old() { ulong source; short dest; source = 1; dest = (short)source; if (dest == 1) return 0; else return 1; } public static bool testMethod() { return (Main_old() == 0); } } public class BasicTestClass_ulong_short_E_2 { public static int Main_old() { ulong source; short dest; source = 32767; dest = (short)source; if (dest == 32767) return 0; else return 1; } public static bool testMethod() { return (Main_old() == 0); } } public class BasicTestClass_ulong_ushort_E_1 { public static int Main_old() { ulong source; ushort dest; source = 1; dest = (ushort)source; if (dest == 1) return 0; else return 1; } public static bool testMethod() { return (Main_old() == 0); } } public class BasicTestClass_ulong_ushort_E_2 { public static int Main_old() { ulong source; ushort dest; source = 65535; dest = (ushort)source; if (dest == 65535) return 0; else return 1; } public static bool testMethod() { return (Main_old() == 0); } } public class BasicTestClass_ulong_ushort_E_3 { public static int Main_old() { ulong source; ushort dest; source = 0; dest = (ushort)source; if (dest == 0) return 0; else return 1; } public static bool testMethod() { return (Main_old() == 0); } } public class BasicTestClass_ulong_int_E_1 { public static int Main_old() { ulong source; int dest; source = 1; dest = (int)source; if (dest == 1) return 0; else return 1; } public static bool testMethod() { return (Main_old() == 0); } } public class BasicTestClass_ulong_int_E_2 { public static int Main_old() { ulong source; int dest; source = 2147483647; dest = (int)source; if (dest == 2147483647) return 0; else return 1; } public static bool testMethod() { return (Main_old() == 0); } } public class BasicTestClass_ulong_uint_E_1 { public static int Main_old() { ulong source; uint dest; source = 1; dest = (uint)source; if (dest == 1) return 0; else return 1; } public static bool testMethod() { return (Main_old() == 0); } } public class BasicTestClass_ulong_uint_E_2 { public static int Main_old() { ulong source; uint dest; source = 4294967295; dest = (uint)source; if (dest == 4294967295) return 0; else return 1; } public static bool testMethod() { return (Main_old() == 0); } } public class BasicTestClass_ulong_uint_E_3 { public static int Main_old() { ulong source; uint dest; source = 0; dest = (uint)source; if (dest == 0) return 0; else return 1; } public static bool testMethod() { return (Main_old() == 0); } } public class BasicTestClass_ulong_long_E_1 { public static int Main_old() { ulong source; long dest; source = 1; dest = (long)source; if (dest == 1) return 0; else return 1; } public static bool testMethod() { return (Main_old() == 0); } } public class BasicTestClass_ulong_long_E_2 { public static int Main_old() { ulong source; long dest; source = 9223372036854775807; dest = (long)source; if (dest == 9223372036854775807) return 0; else return 1; } public static bool testMethod() { return (Main_old() == 0); } } public class BasicTestClass_ulong_char_E_1 { public static int Main_old() { ulong source; char dest; source = 1; dest = (char)source; if (dest == '\x1') return 0; else return 1; } public static bool testMethod() { return (Main_old() == 0); } } public class BasicTestClass_ulong_char_E_2 { public static int Main_old() { ulong source; char dest; source = 65535; dest = (char)source; if (dest == '\xffff') return 0; else return 1; } public static bool testMethod() { return (Main_old() == 0); } } public class BasicTestClass_ulong_char_E_3 { public static int Main_old() { ulong source; char dest; source = 0; dest = (char)source; if (dest == '\x0') return 0; else return 1; } public static bool testMethod() { return (Main_old() == 0); } } public class BasicTestClass_ushort_ushort_I_0 { public static int Main_old() { ushort source; ushort dest; source = 1; dest = source; if (dest == 1) return 0; else return 1; } public static bool testMethod() { return (Main_old() == 0); } } public class BasicTestClass_ushort_ushort_E_0 { public static int Main_old() { ushort source; ushort dest; source = 1; dest = (ushort)source; if (dest == 1) return 0; else return 1; } public static bool testMethod() { return (Main_old() == 0); } } public class BasicTestClass_ushort_int_I_0 { public static int Main_old() { ushort source; int dest; source = 1; dest = source; if (dest == 1) return 0; else return 1; } public static bool testMethod() { return (Main_old() == 0); } } public class BasicTestClass_ushort_int_E_0 { public static int Main_old() { ushort source; int dest; source = 1; dest = (int)source; if (dest == 1) return 0; else return 1; } public static bool testMethod() { return (Main_old() == 0); } } public class BasicTestClass_ushort_uint_I_0 { public static int Main_old() { ushort source; uint dest; source = 1; dest = source; if (dest == 1) return 0; else return 1; } public static bool testMethod() { return (Main_old() == 0); } } public class BasicTestClass_ushort_uint_E_0 { public static int Main_old() { ushort source; uint dest; source = 1; dest = (uint)source; if (dest == 1) return 0; else return 1; } public static bool testMethod() { return (Main_old() == 0); } } public class BasicTestClass_ushort_long_I_0 { public static int Main_old() { ushort source; long dest; source = 1; dest = source; if (dest == 1) return 0; else return 1; } public static bool testMethod() { return (Main_old() == 0); } } public class BasicTestClass_ushort_long_E_0 { public static int Main_old() { ushort source; long dest; source = 1; dest = (long)source; if (dest == 1) return 0; else return 1; } public static bool testMethod() { return (Main_old() == 0); } } public class BasicTestClass_ushort_ulong_I_0 { public static int Main_old() { ushort source; ulong dest; source = 1; dest = source; if (dest == 1) return 0; else return 1; } public static bool testMethod() { return (Main_old() == 0); } } public class BasicTestClass_ushort_ulong_E_0 { public static int Main_old() { ushort source; ulong dest; source = 1; dest = (ulong)source; if (dest == 1) return 0; else return 1; } public static bool testMethod() { return (Main_old() == 0); } } public class BasicTestClass_ushort_float_I_0 { public static int Main_old() { ushort source; float dest; source = 1; dest = source; if (dest == 1F) return 0; else return 1; } public static bool testMethod() { return (Main_old() == 0); } } public class BasicTestClass_ushort_float_E_0 { public static int Main_old() { ushort source; float dest; source = 1; dest = (float)source; if (dest == 1F) return 0; else return 1; } public static bool testMethod() { return (Main_old() == 0); } } public class BasicTestClass_ushort_double_I_0 { public static int Main_old() { ushort source; double dest; source = 1; dest = source; if (dest == 1.0) return 0; else return 1; } public static bool testMethod() { return (Main_old() == 0); } } public class BasicTestClass_ushort_double_E_0 { public static int Main_old() { ushort source; double dest; source = 1; dest = (double)source; if (dest == 1.0) return 0; else return 1; } public static bool testMethod() { return (Main_old() == 0); } } public class BasicTestClass_ushort_sbyte_E_1 { public static int Main_old() { ushort source; sbyte dest; source = 1; dest = (sbyte)source; if (dest == 1) return 0; else return 1; } public static bool testMethod() { return (Main_old() == 0); } } public class BasicTestClass_ushort_sbyte_E_2 { public static int Main_old() { ushort source; sbyte dest; source = 127; dest = (sbyte)source; if (dest == 127) return 0; else return 1; } public static bool testMethod() { return (Main_old() == 0); } } public class BasicTestClass_ushort_byte_E_1 { public static int Main_old() { ushort source; byte dest; source = 1; dest = (byte)source; if (dest == 1) return 0; else return 1; } public static bool testMethod() { return (Main_old() == 0); } } public class BasicTestClass_ushort_byte_E_2 { public static int Main_old() { ushort source; byte dest; source = 255; dest = (byte)source; if (dest == 255) return 0; else return 1; } public static bool testMethod() { return (Main_old() == 0); } } public class BasicTestClass_ushort_byte_E_3 { public static int Main_old() { ushort source; byte dest; source = 0; dest = (byte)source; if (dest == 0) return 0; else return 1; } public static bool testMethod() { return (Main_old() == 0); } } public class BasicTestClass_ushort_short_E_1 { public static int Main_old() { ushort source; short dest; source = 1; dest = (short)source; if (dest == 1) return 0; else return 1; } public static bool testMethod() { return (Main_old() == 0); } } public class BasicTestClass_ushort_short_E_2 { public static int Main_old() { ushort source; short dest; source = 32767; dest = (short)source; if (dest == 32767) return 0; else return 1; } public static bool testMethod() { return (Main_old() == 0); } } public class BasicTestClass_ushort_char_E_1 { public static int Main_old() { ushort source; char dest; source = 1; dest = (char)source; if (dest == '\x1') return 0; else return 1; } public static bool testMethod() { return (Main_old() == 0); } } public class BasicTestClass_ushort_char_E_2 { public static int Main_old() { ushort source; char dest; source = 65535; dest = (char)source; if (dest == '\xffff') return 0; else return 1; } public static bool testMethod() { return (Main_old() == 0); } } public class BasicTestClass_ushort_char_E_3 { public static int Main_old() { ushort source; char dest; source = 0; dest = (char)source; if (dest == '\x0') return 0; else return 1; } public static bool testMethod() { return (Main_old() == 0); } } } */ } ================================================ FILE: Zelig/Zelig/Test/RunTime/NETMF/mscorlib/conversions/expenum/Expenum1Tests.cs ================================================ //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // Copyright (c) Microsoft Corporation. All rights reserved. //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// using System; namespace Microsoft.Zelig.Test { public class Expenum1Tests : TestBase, ITestInterface { [SetUp] public InitializeResult Initialize() { Log.Comment("Adding set up for the tests."); // Add your functionality here. return InitializeResult.ReadyToGo; } [TearDown] public void CleanUp() { Log.Comment("Cleaning up after the tests"); } public override TestResult Run( string[] args ) { TestResult result = TestResult.Pass; string testName = "Expenum1_"; int testNumber = 0; result |= Assert.CheckFailed( Expenum_byte_to_byte_enum_rtime_s_Test( ), testName, ++testNumber ); result |= Assert.CheckFailed( Expenum_byte_to_int_enum_rtime_s_Test( ), testName, ++testNumber ); result |= Assert.CheckFailed( Expenum_byte_to_long_enum_rtime_s_Test( ), testName, ++testNumber ); result |= Assert.CheckFailed( Expenum_byte_to_sbyte_enum_rtime_s_Test( ), testName, ++testNumber ); result |= Assert.CheckFailed( Expenum_byte_to_short_enum_rtime_s_Test( ), testName, ++testNumber ); result |= Assert.CheckFailed( Expenum_byte_to_uint_enum_rtime_s_Test( ), testName, ++testNumber ); result |= Assert.CheckFailed( Expenum_byte_to_ulong_enum_rtime_s_Test( ), testName, ++testNumber ); result |= Assert.CheckFailed( Expenum_byte_to_ushort_enum_rtime_s_Test( ), testName, ++testNumber ); //////result |= Assert.CheckFailed( Expenum_double_to_byte_enum_rtime_s_Test( ), testName, ++testNumber ); //////result |= Assert.CheckFailed( Expenum_double_to_int_enum_rtime_s_Test( ), testName, ++testNumber ); //////result |= Assert.CheckFailed( Expenum_double_to_long_enum_rtime_s_Test( ), testName, ++testNumber ); //////result |= Assert.CheckFailed( Expenum_double_to_sbyte_enum_rtime_s_Test( ), testName, ++testNumber ); //////result |= Assert.CheckFailed( Expenum_double_to_short_enum_rtime_s_Test( ), testName, ++testNumber ); //////result |= Assert.CheckFailed( Expenum_double_to_uint_enum_rtime_s_Test( ), testName, ++testNumber ); //////result |= Assert.CheckFailed( Expenum_double_to_ulong_enum_rtime_s_Test( ), testName, ++testNumber ); //////result |= Assert.CheckFailed( Expenum_double_to_ushort_enum_rtime_s_Test( ), testName, ++testNumber ); //////result |= Assert.CheckFailed( Expenum_float_to_byte_enum_rtime_s_Test( ), testName, ++testNumber ); //////result |= Assert.CheckFailed( Expenum_float_to_int_enum_rtime_s_Test( ), testName, ++testNumber ); //////result |= Assert.CheckFailed( Expenum_float_to_long_enum_rtime_s_Test( ), testName, ++testNumber ); //////result |= Assert.CheckFailed( Expenum_float_to_sbyte_enum_rtime_s_Test( ), testName, ++testNumber ); //////result |= Assert.CheckFailed( Expenum_float_to_short_enum_rtime_s_Test( ), testName, ++testNumber ); //////result |= Assert.CheckFailed( Expenum_float_to_uint_enum_rtime_s_Test( ), testName, ++testNumber ); //////result |= Assert.CheckFailed( Expenum_float_to_ulong_enum_rtime_s_Test( ), testName, ++testNumber ); //////result |= Assert.CheckFailed( Expenum_float_to_ushort_enum_rtime_s_Test( ), testName, ++testNumber ); //////result |= Assert.CheckFailed( Expenum_short_enum_to_float_rtime_s_Test( ), testName, ++testNumber ); result |= Assert.CheckFailed( Expenum_short_enum_to_int_rtime_s_Test( ), testName, ++testNumber ); result |= Assert.CheckFailed( Expenum_int_to_byte_enum_rtime_s_Test( ), testName, ++testNumber ); result |= Assert.CheckFailed( Expenum_int_to_int_enum_rtime_s_Test( ), testName, ++testNumber ); result |= Assert.CheckFailed( Expenum_int_to_long_enum_rtime_s_Test( ), testName, ++testNumber ); result |= Assert.CheckFailed( Expenum_int_to_sbyte_enum_rtime_s_Test( ), testName, ++testNumber ); result |= Assert.CheckFailed( Expenum_int_to_short_enum_rtime_s_Test( ), testName, ++testNumber ); result |= Assert.CheckFailed( Expenum_int_to_uint_enum_rtime_s_Test( ), testName, ++testNumber ); result |= Assert.CheckFailed( Expenum_int_to_ulong_enum_rtime_s_Test( ), testName, ++testNumber ); result |= Assert.CheckFailed( Expenum_int_to_ushort_enum_rtime_s_Test( ), testName, ++testNumber ); result |= Assert.CheckFailed( Expenum_long_to_byte_enum_rtime_s_Test( ), testName, ++testNumber ); result |= Assert.CheckFailed( Expenum_long_to_int_enum_rtime_s_Test( ), testName, ++testNumber ); result |= Assert.CheckFailed( Expenum_long_to_long_enum_rtime_s_Test( ), testName, ++testNumber ); result |= Assert.CheckFailed( Expenum_long_to_sbyte_enum_rtime_s_Test( ), testName, ++testNumber ); result |= Assert.CheckFailed( Expenum_long_to_short_enum_rtime_s_Test( ), testName, ++testNumber ); result |= Assert.CheckFailed( Expenum_long_to_uint_enum_rtime_s_Test( ), testName, ++testNumber ); result |= Assert.CheckFailed( Expenum_long_to_ulong_enum_rtime_s_Test( ), testName, ++testNumber ); result |= Assert.CheckFailed( Expenum_long_to_ushort_enum_rtime_s_Test( ), testName, ++testNumber ); result |= Assert.CheckFailed( Expenum_sbyte_to_byte_enum_rtime_s_Test( ), testName, ++testNumber ); result |= Assert.CheckFailed( Expenum_sbyte_to_int_enum_rtime_s_Test( ), testName, ++testNumber ); result |= Assert.CheckFailed( Expenum_sbyte_to_long_enum_rtime_s_Test( ), testName, ++testNumber ); result |= Assert.CheckFailed( Expenum_sbyte_to_sbyte_enum_rtime_s_Test( ), testName, ++testNumber ); result |= Assert.CheckFailed( Expenum_sbyte_to_short_enum_rtime_s_Test( ), testName, ++testNumber ); result |= Assert.CheckFailed( Expenum_sbyte_to_uint_enum_rtime_s_Test( ), testName, ++testNumber ); result |= Assert.CheckFailed( Expenum_sbyte_to_ulong_enum_rtime_s_Test( ), testName, ++testNumber ); result |= Assert.CheckFailed( Expenum_sbyte_to_ushort_enum_rtime_s_Test( ), testName, ++testNumber ); result |= Assert.CheckFailed( Expenum_short_to_byte_enum_rtime_s_Test( ), testName, ++testNumber ); result |= Assert.CheckFailed( Expenum_short_to_int_enum_rtime_s_Test( ), testName, ++testNumber ); result |= Assert.CheckFailed( Expenum_short_to_long_enum_rtime_s_Test( ), testName, ++testNumber ); result |= Assert.CheckFailed( Expenum_short_to_sbyte_enum_rtime_s_Test( ), testName, ++testNumber ); result |= Assert.CheckFailed( Expenum_short_to_short_enum_rtime_s_Test( ), testName, ++testNumber ); result |= Assert.CheckFailed( Expenum_short_to_uint_enum_rtime_s_Test( ), testName, ++testNumber ); result |= Assert.CheckFailed( Expenum_short_to_ulong_enum_rtime_s_Test( ), testName, ++testNumber ); result |= Assert.CheckFailed( Expenum_short_to_ushort_enum_rtime_s_Test( ), testName, ++testNumber ); result |= Assert.CheckFailed( Expenum_uint_to_byte_enum_rtime_s_Test( ), testName, ++testNumber ); result |= Assert.CheckFailed( Expenum_uint_to_int_enum_rtime_s_Test( ), testName, ++testNumber ); result |= Assert.CheckFailed( Expenum_uint_to_long_enum_rtime_s_Test( ), testName, ++testNumber ); result |= Assert.CheckFailed( Expenum_uint_to_sbyte_enum_rtime_s_Test( ), testName, ++testNumber ); result |= Assert.CheckFailed( Expenum_uint_to_short_enum_rtime_s_Test( ), testName, ++testNumber ); result |= Assert.CheckFailed( Expenum_uint_to_uint_enum_rtime_s_Test( ), testName, ++testNumber ); result |= Assert.CheckFailed( Expenum_uint_to_ulong_enum_rtime_s_Test( ), testName, ++testNumber ); result |= Assert.CheckFailed( Expenum_uint_to_ushort_enum_rtime_s_Test( ), testName, ++testNumber ); result |= Assert.CheckFailed( Expenum_ulong_to_byte_enum_rtime_s_Test( ), testName, ++testNumber ); result |= Assert.CheckFailed( Expenum_ulong_to_int_enum_rtime_s_Test( ), testName, ++testNumber ); result |= Assert.CheckFailed( Expenum_ulong_to_long_enum_rtime_s_Test( ), testName, ++testNumber ); result |= Assert.CheckFailed( Expenum_ulong_to_sbyte_enum_rtime_s_Test( ), testName, ++testNumber ); result |= Assert.CheckFailed( Expenum_ulong_to_short_enum_rtime_s_Test( ), testName, ++testNumber ); result |= Assert.CheckFailed( Expenum_ulong_to_uint_enum_rtime_s_Test( ), testName, ++testNumber ); result |= Assert.CheckFailed( Expenum_ulong_to_ulong_enum_rtime_s_Test( ), testName, ++testNumber ); result |= Assert.CheckFailed( Expenum_ulong_to_ushort_enum_rtime_s_Test( ), testName, ++testNumber ); result |= Assert.CheckFailed( Expenum_ushort_to_byte_enum_rtime_s_Test( ), testName, ++testNumber ); result |= Assert.CheckFailed( Expenum_ushort_to_int_enum_rtime_s_Test( ), testName, ++testNumber ); result |= Assert.CheckFailed( Expenum_ushort_to_long_enum_rtime_s_Test( ), testName, ++testNumber ); result |= Assert.CheckFailed( Expenum_ushort_to_sbyte_enum_rtime_s_Test( ), testName, ++testNumber ); result |= Assert.CheckFailed( Expenum_ushort_to_short_enum_rtime_s_Test( ), testName, ++testNumber ); result |= Assert.CheckFailed( Expenum_ushort_to_uint_enum_rtime_s_Test( ), testName, ++testNumber ); result |= Assert.CheckFailed( Expenum_ushort_to_ulong_enum_rtime_s_Test( ), testName, ++testNumber ); result |= Assert.CheckFailed( Expenum_ushort_to_ushort_enum_rtime_s_Test( ), testName, ++testNumber ); result |= Assert.CheckFailed( Expenum_int_enum_to_ushort_rtime_s_Test( ), testName, ++testNumber ); result |= Assert.CheckFailed( Expenum_long_enum_to_byte_rtime_s_Test( ), testName, ++testNumber ); //////result |= Assert.CheckFailed( Expenum_long_enum_to_double_rtime_s_Test( ), testName, ++testNumber ); //////result |= Assert.CheckFailed( Expenum_long_enum_to_float_rtime_s_Test( ), testName, ++testNumber ); result |= Assert.CheckFailed( Expenum_long_enum_to_int_rtime_s_Test( ), testName, ++testNumber ); result |= Assert.CheckFailed( Expenum_long_enum_to_long_rtime_s_Test( ), testName, ++testNumber ); result |= Assert.CheckFailed( Expenum_long_enum_to_sbyte_rtime_s_Test( ), testName, ++testNumber ); result |= Assert.CheckFailed( Expenum_long_enum_to_short_rtime_s_Test( ), testName, ++testNumber ); result |= Assert.CheckFailed( Expenum_long_enum_to_uint_rtime_s_Test( ), testName, ++testNumber ); result |= Assert.CheckFailed( Expenum_long_enum_to_ulong_rtime_s_Test( ), testName, ++testNumber ); result |= Assert.CheckFailed( Expenum_long_enum_to_ushort_rtime_s_Test( ), testName, ++testNumber ); result |= Assert.CheckFailed( Expenum_sbyte_enum_to_byte_rtime_s_Test( ), testName, ++testNumber ); //////result |= Assert.CheckFailed( Expenum_sbyte_enum_to_double_rtime_s_Test( ), testName, ++testNumber ); //////result |= Assert.CheckFailed( Expenum_sbyte_enum_to_float_rtime_s_Test( ), testName, ++testNumber ); return result; } [TestMethod] public TestResult Expenum_byte_to_byte_enum_rtime_s_Test() { if (ExpenumTestClass_byte_to_byte_enum_rtime_s.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Expenum_byte_to_int_enum_rtime_s_Test() { if (ExpenumTestClass_byte_to_int_enum_rtime_s.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Expenum_byte_to_long_enum_rtime_s_Test() { if (ExpenumTestClass_byte_to_long_enum_rtime_s.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Expenum_byte_to_sbyte_enum_rtime_s_Test() { if (ExpenumTestClass_byte_to_sbyte_enum_rtime_s.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Expenum_byte_to_short_enum_rtime_s_Test() { if (ExpenumTestClass_byte_to_short_enum_rtime_s.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Expenum_byte_to_uint_enum_rtime_s_Test() { if (ExpenumTestClass_byte_to_uint_enum_rtime_s.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Expenum_byte_to_ulong_enum_rtime_s_Test() { if (ExpenumTestClass_byte_to_ulong_enum_rtime_s.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Expenum_byte_to_ushort_enum_rtime_s_Test() { if (ExpenumTestClass_byte_to_ushort_enum_rtime_s.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } //////[TestMethod] //////public TestResult Expenum_double_to_byte_enum_rtime_s_Test() //////{ ////// if (ExpenumTestClass_double_to_byte_enum_rtime_s.testMethod()) ////// { ////// return TestResult.Pass; ////// } ////// return TestResult.Fail; //////} //////[TestMethod] //////public TestResult Expenum_double_to_int_enum_rtime_s_Test() //////{ ////// if (ExpenumTestClass_double_to_int_enum_rtime_s.testMethod()) ////// { ////// return TestResult.Pass; ////// } ////// return TestResult.Fail; //////} //////[TestMethod] //////public TestResult Expenum_double_to_long_enum_rtime_s_Test() //////{ ////// if (ExpenumTestClass_double_to_long_enum_rtime_s.testMethod()) ////// { ////// return TestResult.Pass; ////// } ////// return TestResult.Fail; //////} //////[TestMethod] //////public TestResult Expenum_double_to_sbyte_enum_rtime_s_Test() //////{ ////// if (ExpenumTestClass_double_to_sbyte_enum_rtime_s.testMethod()) ////// { ////// return TestResult.Pass; ////// } ////// return TestResult.Fail; //////} //////[TestMethod] //////public TestResult Expenum_double_to_short_enum_rtime_s_Test() //////{ ////// if (ExpenumTestClass_double_to_short_enum_rtime_s.testMethod()) ////// { ////// return TestResult.Pass; ////// } ////// return TestResult.Fail; //////} //////[TestMethod] //////public TestResult Expenum_double_to_uint_enum_rtime_s_Test() //////{ ////// if (ExpenumTestClass_double_to_uint_enum_rtime_s.testMethod()) ////// { ////// return TestResult.Pass; ////// } ////// return TestResult.Fail; //////} //////[TestMethod] //////public TestResult Expenum_double_to_ulong_enum_rtime_s_Test() //////{ ////// if (ExpenumTestClass_double_to_ulong_enum_rtime_s.testMethod()) ////// { ////// return TestResult.Pass; ////// } ////// return TestResult.Fail; //////} //////[TestMethod] //////public TestResult Expenum_double_to_ushort_enum_rtime_s_Test() //////{ ////// if (ExpenumTestClass_double_to_ushort_enum_rtime_s.testMethod()) ////// { ////// return TestResult.Pass; ////// } ////// return TestResult.Fail; //////} //////[TestMethod] //////public TestResult Expenum_float_to_byte_enum_rtime_s_Test() //////{ ////// if (ExpenumTestClass_float_to_byte_enum_rtime_s.testMethod()) ////// { ////// return TestResult.Pass; ////// } ////// return TestResult.Fail; //////} //////[TestMethod] //////public TestResult Expenum_float_to_int_enum_rtime_s_Test() //////{ ////// if (ExpenumTestClass_float_to_int_enum_rtime_s.testMethod()) ////// { ////// return TestResult.Pass; ////// } ////// return TestResult.Fail; //////} //////[TestMethod] //////public TestResult Expenum_float_to_long_enum_rtime_s_Test() //////{ ////// if (ExpenumTestClass_float_to_long_enum_rtime_s.testMethod()) ////// { ////// return TestResult.Pass; ////// } ////// return TestResult.Fail; //////} //////[TestMethod] //////public TestResult Expenum_float_to_sbyte_enum_rtime_s_Test() //////{ ////// if (ExpenumTestClass_float_to_sbyte_enum_rtime_s.testMethod()) ////// { ////// return TestResult.Pass; ////// } ////// return TestResult.Fail; //////} //////[TestMethod] //////public TestResult Expenum_float_to_short_enum_rtime_s_Test() //////{ ////// if (ExpenumTestClass_float_to_short_enum_rtime_s.testMethod()) ////// { ////// return TestResult.Pass; ////// } ////// return TestResult.Fail; //////} //////[TestMethod] //////public TestResult Expenum_float_to_uint_enum_rtime_s_Test() //////{ ////// if (ExpenumTestClass_float_to_uint_enum_rtime_s.testMethod()) ////// { ////// return TestResult.Pass; ////// } ////// return TestResult.Fail; //////} //////[TestMethod] //////public TestResult Expenum_float_to_ulong_enum_rtime_s_Test() //////{ ////// if (ExpenumTestClass_float_to_ulong_enum_rtime_s.testMethod()) ////// { ////// return TestResult.Pass; ////// } ////// return TestResult.Fail; //////} //////[TestMethod] //////public TestResult Expenum_float_to_ushort_enum_rtime_s_Test() //////{ ////// if (ExpenumTestClass_float_to_ushort_enum_rtime_s.testMethod()) ////// { ////// return TestResult.Pass; ////// } ////// return TestResult.Fail; //////} //////[TestMethod] //////public TestResult Expenum_short_enum_to_float_rtime_s_Test() //////{ ////// if (ExpenumTestClass_short_enum_to_float_rtime_s.testMethod()) ////// { ////// return TestResult.Pass; ////// } ////// return TestResult.Fail; //////} [TestMethod] public TestResult Expenum_short_enum_to_int_rtime_s_Test() { if (ExpenumTestClass_short_enum_to_int_rtime_s.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Expenum_int_to_byte_enum_rtime_s_Test() { if (ExpenumTestClass_int_to_byte_enum_rtime_s.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Expenum_int_to_int_enum_rtime_s_Test() { if (ExpenumTestClass_int_to_int_enum_rtime_s.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Expenum_int_to_long_enum_rtime_s_Test() { if (ExpenumTestClass_int_to_long_enum_rtime_s.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Expenum_int_to_sbyte_enum_rtime_s_Test() { if (ExpenumTestClass_int_to_sbyte_enum_rtime_s.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Expenum_int_to_short_enum_rtime_s_Test() { if (ExpenumTestClass_int_to_short_enum_rtime_s.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Expenum_int_to_uint_enum_rtime_s_Test() { if (ExpenumTestClass_int_to_uint_enum_rtime_s.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Expenum_int_to_ulong_enum_rtime_s_Test() { if (ExpenumTestClass_int_to_ulong_enum_rtime_s.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Expenum_int_to_ushort_enum_rtime_s_Test() { if (ExpenumTestClass_int_to_ushort_enum_rtime_s.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Expenum_long_to_byte_enum_rtime_s_Test() { if (ExpenumTestClass_long_to_byte_enum_rtime_s.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Expenum_long_to_int_enum_rtime_s_Test() { if (ExpenumTestClass_long_to_int_enum_rtime_s.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Expenum_long_to_long_enum_rtime_s_Test() { if (ExpenumTestClass_long_to_long_enum_rtime_s.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Expenum_long_to_sbyte_enum_rtime_s_Test() { if (ExpenumTestClass_long_to_sbyte_enum_rtime_s.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Expenum_long_to_short_enum_rtime_s_Test() { if (ExpenumTestClass_long_to_short_enum_rtime_s.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Expenum_long_to_uint_enum_rtime_s_Test() { if (ExpenumTestClass_long_to_uint_enum_rtime_s.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Expenum_long_to_ulong_enum_rtime_s_Test() { if (ExpenumTestClass_long_to_ulong_enum_rtime_s.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Expenum_long_to_ushort_enum_rtime_s_Test() { if (ExpenumTestClass_long_to_ushort_enum_rtime_s.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Expenum_sbyte_to_byte_enum_rtime_s_Test() { if (ExpenumTestClass_sbyte_to_byte_enum_rtime_s.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Expenum_sbyte_to_int_enum_rtime_s_Test() { if (ExpenumTestClass_sbyte_to_int_enum_rtime_s.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Expenum_sbyte_to_long_enum_rtime_s_Test() { if (ExpenumTestClass_sbyte_to_long_enum_rtime_s.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Expenum_sbyte_to_sbyte_enum_rtime_s_Test() { if (ExpenumTestClass_sbyte_to_sbyte_enum_rtime_s.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Expenum_sbyte_to_short_enum_rtime_s_Test() { if (ExpenumTestClass_sbyte_to_short_enum_rtime_s.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Expenum_sbyte_to_uint_enum_rtime_s_Test() { if (ExpenumTestClass_sbyte_to_uint_enum_rtime_s.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Expenum_sbyte_to_ulong_enum_rtime_s_Test() { if (ExpenumTestClass_sbyte_to_ulong_enum_rtime_s.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Expenum_sbyte_to_ushort_enum_rtime_s_Test() { if (ExpenumTestClass_sbyte_to_ushort_enum_rtime_s.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Expenum_short_to_byte_enum_rtime_s_Test() { if (ExpenumTestClass_short_to_byte_enum_rtime_s.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Expenum_short_to_int_enum_rtime_s_Test() { if (ExpenumTestClass_short_to_int_enum_rtime_s.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Expenum_short_to_long_enum_rtime_s_Test() { if (ExpenumTestClass_short_to_long_enum_rtime_s.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Expenum_short_to_sbyte_enum_rtime_s_Test() { if (ExpenumTestClass_short_to_sbyte_enum_rtime_s.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Expenum_short_to_short_enum_rtime_s_Test() { if (ExpenumTestClass_short_to_short_enum_rtime_s.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Expenum_short_to_uint_enum_rtime_s_Test() { if (ExpenumTestClass_short_to_uint_enum_rtime_s.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Expenum_short_to_ulong_enum_rtime_s_Test() { if (ExpenumTestClass_short_to_ulong_enum_rtime_s.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Expenum_short_to_ushort_enum_rtime_s_Test() { if (ExpenumTestClass_short_to_ushort_enum_rtime_s.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Expenum_uint_to_byte_enum_rtime_s_Test() { if (ExpenumTestClass_uint_to_byte_enum_rtime_s.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Expenum_uint_to_int_enum_rtime_s_Test() { if (ExpenumTestClass_uint_to_int_enum_rtime_s.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Expenum_uint_to_long_enum_rtime_s_Test() { if (ExpenumTestClass_uint_to_long_enum_rtime_s.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Expenum_uint_to_sbyte_enum_rtime_s_Test() { if (ExpenumTestClass_uint_to_sbyte_enum_rtime_s.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Expenum_uint_to_short_enum_rtime_s_Test() { if (ExpenumTestClass_uint_to_short_enum_rtime_s.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Expenum_uint_to_uint_enum_rtime_s_Test() { if (ExpenumTestClass_uint_to_uint_enum_rtime_s.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Expenum_uint_to_ulong_enum_rtime_s_Test() { if (ExpenumTestClass_uint_to_ulong_enum_rtime_s.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Expenum_uint_to_ushort_enum_rtime_s_Test() { if (ExpenumTestClass_uint_to_ushort_enum_rtime_s.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Expenum_ulong_to_byte_enum_rtime_s_Test() { if (ExpenumTestClass_ulong_to_byte_enum_rtime_s.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Expenum_ulong_to_int_enum_rtime_s_Test() { if (ExpenumTestClass_ulong_to_int_enum_rtime_s.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Expenum_ulong_to_long_enum_rtime_s_Test() { if (ExpenumTestClass_ulong_to_long_enum_rtime_s.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Expenum_ulong_to_sbyte_enum_rtime_s_Test() { if (ExpenumTestClass_ulong_to_sbyte_enum_rtime_s.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Expenum_ulong_to_short_enum_rtime_s_Test() { if (ExpenumTestClass_ulong_to_short_enum_rtime_s.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Expenum_ulong_to_uint_enum_rtime_s_Test() { if (ExpenumTestClass_ulong_to_uint_enum_rtime_s.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Expenum_ulong_to_ulong_enum_rtime_s_Test() { if (ExpenumTestClass_ulong_to_ulong_enum_rtime_s.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Expenum_ulong_to_ushort_enum_rtime_s_Test() { if (ExpenumTestClass_ulong_to_ushort_enum_rtime_s.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Expenum_ushort_to_byte_enum_rtime_s_Test() { if (ExpenumTestClass_ushort_to_byte_enum_rtime_s.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Expenum_ushort_to_int_enum_rtime_s_Test() { if (ExpenumTestClass_ushort_to_int_enum_rtime_s.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Expenum_ushort_to_long_enum_rtime_s_Test() { if (ExpenumTestClass_ushort_to_long_enum_rtime_s.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Expenum_ushort_to_sbyte_enum_rtime_s_Test() { if (ExpenumTestClass_ushort_to_sbyte_enum_rtime_s.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Expenum_ushort_to_short_enum_rtime_s_Test() { if (ExpenumTestClass_ushort_to_short_enum_rtime_s.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Expenum_ushort_to_uint_enum_rtime_s_Test() { if (ExpenumTestClass_ushort_to_uint_enum_rtime_s.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Expenum_ushort_to_ulong_enum_rtime_s_Test() { if (ExpenumTestClass_ushort_to_ulong_enum_rtime_s.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Expenum_ushort_to_ushort_enum_rtime_s_Test() { if (ExpenumTestClass_ushort_to_ushort_enum_rtime_s.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Expenum_int_enum_to_ushort_rtime_s_Test() { if (ExpenumTestClass_int_enum_to_ushort_rtime_s.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Expenum_long_enum_to_byte_rtime_s_Test() { if (ExpenumTestClass_long_enum_to_byte_rtime_s.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } //////[TestMethod] //////public TestResult Expenum_long_enum_to_double_rtime_s_Test() //////{ ////// if (ExpenumTestClass_long_enum_to_double_rtime_s.testMethod()) ////// { ////// return TestResult.Pass; ////// } ////// return TestResult.Fail; //////} //////[TestMethod] //////public TestResult Expenum_long_enum_to_float_rtime_s_Test() //////{ ////// if (ExpenumTestClass_long_enum_to_float_rtime_s.testMethod()) ////// { ////// return TestResult.Pass; ////// } ////// return TestResult.Fail; //////} [TestMethod] public TestResult Expenum_long_enum_to_int_rtime_s_Test() { if (ExpenumTestClass_long_enum_to_int_rtime_s.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Expenum_long_enum_to_long_rtime_s_Test() { if (ExpenumTestClass_long_enum_to_long_rtime_s.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Expenum_long_enum_to_sbyte_rtime_s_Test() { if (ExpenumTestClass_long_enum_to_sbyte_rtime_s.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Expenum_long_enum_to_short_rtime_s_Test() { if (ExpenumTestClass_long_enum_to_short_rtime_s.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Expenum_long_enum_to_uint_rtime_s_Test() { if (ExpenumTestClass_long_enum_to_uint_rtime_s.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Expenum_long_enum_to_ulong_rtime_s_Test() { if (ExpenumTestClass_long_enum_to_ulong_rtime_s.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Expenum_long_enum_to_ushort_rtime_s_Test() { if (ExpenumTestClass_long_enum_to_ushort_rtime_s.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Expenum_sbyte_enum_to_byte_rtime_s_Test() { if (ExpenumTestClass_sbyte_enum_to_byte_rtime_s.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } //////[TestMethod] //////public TestResult Expenum_sbyte_enum_to_double_rtime_s_Test() //////{ ////// if (ExpenumTestClass_sbyte_enum_to_double_rtime_s.testMethod()) ////// { ////// return TestResult.Pass; ////// } ////// return TestResult.Fail; //////} //////[TestMethod] //////public TestResult Expenum_sbyte_enum_to_float_rtime_s_Test() //////{ ////// if (ExpenumTestClass_sbyte_enum_to_float_rtime_s.testMethod()) ////// { ////// return TestResult.Pass; ////// } ////// return TestResult.Fail; //////} //Compiled Test Cases enum ExpenumTestClass_byte_to_byte_enum_rtime_s_DestEnumType : byte { ValOne = 1 } public class ExpenumTestClass_byte_to_byte_enum_rtime_s { public static bool testMethod() { ExpenumTestClass_byte_to_byte_enum_rtime_s_DestEnumType Destination; byte Source = 1; Destination = (ExpenumTestClass_byte_to_byte_enum_rtime_s_DestEnumType)Source; if (Destination == ExpenumTestClass_byte_to_byte_enum_rtime_s_DestEnumType.ValOne) return true; else return false; } } enum ExpenumTestClass_byte_to_int_enum_rtime_s_DestEnumType : int { ValOne = 1 } public class ExpenumTestClass_byte_to_int_enum_rtime_s { public static bool testMethod() { ExpenumTestClass_byte_to_int_enum_rtime_s_DestEnumType Destination; byte Source = 1; Destination = (ExpenumTestClass_byte_to_int_enum_rtime_s_DestEnumType)Source; if (Destination == ExpenumTestClass_byte_to_int_enum_rtime_s_DestEnumType.ValOne) return true; else return false; } } enum ExpenumTestClass_byte_to_long_enum_rtime_s_DestEnumType : long { ValOne = 1 } public class ExpenumTestClass_byte_to_long_enum_rtime_s { public static bool testMethod() { ExpenumTestClass_byte_to_long_enum_rtime_s_DestEnumType Destination; byte Source = 1; Destination = (ExpenumTestClass_byte_to_long_enum_rtime_s_DestEnumType)Source; if (Destination == ExpenumTestClass_byte_to_long_enum_rtime_s_DestEnumType.ValOne) return true; else return false; } } enum ExpenumTestClass_byte_to_sbyte_enum_rtime_s_DestEnumType : sbyte { ValOne = 1 } public class ExpenumTestClass_byte_to_sbyte_enum_rtime_s { public static bool testMethod() { ExpenumTestClass_byte_to_sbyte_enum_rtime_s_DestEnumType Destination; byte Source = 1; Destination = (ExpenumTestClass_byte_to_sbyte_enum_rtime_s_DestEnumType)Source; if (Destination == ExpenumTestClass_byte_to_sbyte_enum_rtime_s_DestEnumType.ValOne) return true; else return false; } } enum ExpenumTestClass_byte_to_short_enum_rtime_s_DestEnumType : short { ValOne = 1 } public class ExpenumTestClass_byte_to_short_enum_rtime_s { public static bool testMethod() { ExpenumTestClass_byte_to_short_enum_rtime_s_DestEnumType Destination; byte Source = 1; Destination = (ExpenumTestClass_byte_to_short_enum_rtime_s_DestEnumType)Source; if (Destination == ExpenumTestClass_byte_to_short_enum_rtime_s_DestEnumType.ValOne) return true; else return false; } } enum ExpenumTestClass_byte_to_uint_enum_rtime_s_DestEnumType : uint { ValOne = 1 } public class ExpenumTestClass_byte_to_uint_enum_rtime_s { public static bool testMethod() { ExpenumTestClass_byte_to_uint_enum_rtime_s_DestEnumType Destination; byte Source = 1; Destination = (ExpenumTestClass_byte_to_uint_enum_rtime_s_DestEnumType)Source; if (Destination == ExpenumTestClass_byte_to_uint_enum_rtime_s_DestEnumType.ValOne) return true; else return false; } } enum ExpenumTestClass_byte_to_ulong_enum_rtime_s_DestEnumType : ulong { ValOne = 1 } public class ExpenumTestClass_byte_to_ulong_enum_rtime_s { public static bool testMethod() { ExpenumTestClass_byte_to_ulong_enum_rtime_s_DestEnumType Destination; byte Source = 1; Destination = (ExpenumTestClass_byte_to_ulong_enum_rtime_s_DestEnumType)Source; if (Destination == ExpenumTestClass_byte_to_ulong_enum_rtime_s_DestEnumType.ValOne) return true; else return false; } } enum ExpenumTestClass_byte_to_ushort_enum_rtime_s_DestEnumType : ushort { ValOne = 1 } public class ExpenumTestClass_byte_to_ushort_enum_rtime_s { public static bool testMethod() { ExpenumTestClass_byte_to_ushort_enum_rtime_s_DestEnumType Destination; byte Source = 1; Destination = (ExpenumTestClass_byte_to_ushort_enum_rtime_s_DestEnumType)Source; if (Destination == ExpenumTestClass_byte_to_ushort_enum_rtime_s_DestEnumType.ValOne) return true; else return false; } } //////enum ExpenumTestClass_double_to_byte_enum_rtime_s_DestEnumType : byte { ValOne = 1 } //////public class ExpenumTestClass_double_to_byte_enum_rtime_s //////{ ////// public static bool testMethod() ////// { ////// ExpenumTestClass_double_to_byte_enum_rtime_s_DestEnumType Destination; ////// double Source = 1; ////// Destination = (ExpenumTestClass_double_to_byte_enum_rtime_s_DestEnumType)Source; ////// if (Destination == ExpenumTestClass_double_to_byte_enum_rtime_s_DestEnumType.ValOne) ////// return true; ////// else ////// return false; ////// } //////} //////enum ExpenumTestClass_double_to_int_enum_rtime_s_DestEnumType : int { ValOne = 1 } //////public class ExpenumTestClass_double_to_int_enum_rtime_s //////{ ////// public static bool testMethod() ////// { ////// ExpenumTestClass_double_to_int_enum_rtime_s_DestEnumType Destination; ////// double Source = 1; ////// Destination = (ExpenumTestClass_double_to_int_enum_rtime_s_DestEnumType)Source; ////// if (Destination == ExpenumTestClass_double_to_int_enum_rtime_s_DestEnumType.ValOne) ////// return true; ////// else ////// return false; ////// } //////} //////enum ExpenumTestClass_double_to_long_enum_rtime_s_DestEnumType : long { ValOne = 1 } //////public class ExpenumTestClass_double_to_long_enum_rtime_s //////{ ////// public static bool testMethod() ////// { ////// ExpenumTestClass_double_to_long_enum_rtime_s_DestEnumType Destination; ////// double Source = 1; ////// Destination = (ExpenumTestClass_double_to_long_enum_rtime_s_DestEnumType)Source; ////// if (Destination == ExpenumTestClass_double_to_long_enum_rtime_s_DestEnumType.ValOne) ////// return true; ////// else ////// return false; ////// } //////} //////enum ExpenumTestClass_double_to_sbyte_enum_rtime_s_DestEnumType : sbyte { ValOne = 1 } //////public class ExpenumTestClass_double_to_sbyte_enum_rtime_s //////{ ////// public static bool testMethod() ////// { ////// ExpenumTestClass_double_to_sbyte_enum_rtime_s_DestEnumType Destination; ////// double Source = 1; ////// Destination = (ExpenumTestClass_double_to_sbyte_enum_rtime_s_DestEnumType)Source; ////// if (Destination == ExpenumTestClass_double_to_sbyte_enum_rtime_s_DestEnumType.ValOne) ////// return true; ////// else ////// return false; ////// } //////} //////enum ExpenumTestClass_double_to_short_enum_rtime_s_DestEnumType : short { ValOne = 1 } //////public class ExpenumTestClass_double_to_short_enum_rtime_s //////{ ////// public static bool testMethod() ////// { ////// ExpenumTestClass_double_to_short_enum_rtime_s_DestEnumType Destination; ////// double Source = 1; ////// Destination = (ExpenumTestClass_double_to_short_enum_rtime_s_DestEnumType)Source; ////// if (Destination == ExpenumTestClass_double_to_short_enum_rtime_s_DestEnumType.ValOne) ////// return true; ////// else ////// return false; ////// } //////} //////enum ExpenumTestClass_double_to_uint_enum_rtime_s_DestEnumType : uint { ValOne = 1 } //////public class ExpenumTestClass_double_to_uint_enum_rtime_s //////{ ////// public static bool testMethod() ////// { ////// ExpenumTestClass_double_to_uint_enum_rtime_s_DestEnumType Destination; ////// double Source = 1; ////// Destination = (ExpenumTestClass_double_to_uint_enum_rtime_s_DestEnumType)Source; ////// if (Destination == ExpenumTestClass_double_to_uint_enum_rtime_s_DestEnumType.ValOne) ////// return true; ////// else ////// return false; ////// } //////} //////enum ExpenumTestClass_double_to_ulong_enum_rtime_s_DestEnumType : ulong { ValOne = 1 } //////public class ExpenumTestClass_double_to_ulong_enum_rtime_s //////{ ////// public static bool testMethod() ////// { ////// ExpenumTestClass_double_to_ulong_enum_rtime_s_DestEnumType Destination; ////// double Source = 1; ////// Destination = (ExpenumTestClass_double_to_ulong_enum_rtime_s_DestEnumType)Source; ////// if (Destination == ExpenumTestClass_double_to_ulong_enum_rtime_s_DestEnumType.ValOne) ////// return true; ////// else ////// return false; ////// } //////} //////enum ExpenumTestClass_double_to_ushort_enum_rtime_s_DestEnumType : ushort { ValOne = 1 } //////public class ExpenumTestClass_double_to_ushort_enum_rtime_s //////{ ////// public static bool testMethod() ////// { ////// ExpenumTestClass_double_to_ushort_enum_rtime_s_DestEnumType Destination; ////// double Source = 1; ////// Destination = (ExpenumTestClass_double_to_ushort_enum_rtime_s_DestEnumType)Source; ////// if (Destination == ExpenumTestClass_double_to_ushort_enum_rtime_s_DestEnumType.ValOne) ////// return true; ////// else ////// return false; ////// } //////} //////enum ExpenumTestClass_float_to_byte_enum_rtime_s_DestEnumType : byte { ValOne = 1 } //////public class ExpenumTestClass_float_to_byte_enum_rtime_s //////{ ////// public static bool testMethod() ////// { ////// ExpenumTestClass_float_to_byte_enum_rtime_s_DestEnumType Destination; ////// float Source = 1; ////// Destination = (ExpenumTestClass_float_to_byte_enum_rtime_s_DestEnumType)Source; ////// if (Destination == ExpenumTestClass_float_to_byte_enum_rtime_s_DestEnumType.ValOne) ////// return true; ////// else ////// return false; ////// } //////} //////enum ExpenumTestClass_float_to_int_enum_rtime_s_DestEnumType : int { ValOne = 1 } //////public class ExpenumTestClass_float_to_int_enum_rtime_s //////{ ////// public static bool testMethod() ////// { ////// ExpenumTestClass_float_to_int_enum_rtime_s_DestEnumType Destination; ////// float Source = 1; ////// Destination = (ExpenumTestClass_float_to_int_enum_rtime_s_DestEnumType)Source; ////// if (Destination == ExpenumTestClass_float_to_int_enum_rtime_s_DestEnumType.ValOne) ////// return true; ////// else ////// return false; ////// } //////} //////enum ExpenumTestClass_float_to_long_enum_rtime_s_DestEnumType : long { ValOne = 1 } //////public class ExpenumTestClass_float_to_long_enum_rtime_s //////{ ////// public static bool testMethod() ////// { ////// ExpenumTestClass_float_to_long_enum_rtime_s_DestEnumType Destination; ////// float Source = 1; ////// Destination = (ExpenumTestClass_float_to_long_enum_rtime_s_DestEnumType)Source; ////// if (Destination == ExpenumTestClass_float_to_long_enum_rtime_s_DestEnumType.ValOne) ////// return true; ////// else ////// return false; ////// } //////} //////enum ExpenumTestClass_float_to_sbyte_enum_rtime_s_DestEnumType : sbyte { ValOne = 1 } //////public class ExpenumTestClass_float_to_sbyte_enum_rtime_s //////{ ////// public static bool testMethod() ////// { ////// ExpenumTestClass_float_to_sbyte_enum_rtime_s_DestEnumType Destination; ////// float Source = 1; ////// Destination = (ExpenumTestClass_float_to_sbyte_enum_rtime_s_DestEnumType)Source; ////// if (Destination == ExpenumTestClass_float_to_sbyte_enum_rtime_s_DestEnumType.ValOne) ////// return true; ////// else ////// return false; ////// } //////} //////enum ExpenumTestClass_float_to_short_enum_rtime_s_DestEnumType : short { ValOne = 1 } //////public class ExpenumTestClass_float_to_short_enum_rtime_s //////{ ////// public static bool testMethod() ////// { ////// ExpenumTestClass_float_to_short_enum_rtime_s_DestEnumType Destination; ////// float Source = 1; ////// Destination = (ExpenumTestClass_float_to_short_enum_rtime_s_DestEnumType)Source; ////// if (Destination == ExpenumTestClass_float_to_short_enum_rtime_s_DestEnumType.ValOne) ////// return true; ////// else ////// return false; ////// } //////} //////enum ExpenumTestClass_float_to_uint_enum_rtime_s_DestEnumType : uint { ValOne = 1 } //////public class ExpenumTestClass_float_to_uint_enum_rtime_s //////{ ////// public static bool testMethod() ////// { ////// ExpenumTestClass_float_to_uint_enum_rtime_s_DestEnumType Destination; ////// float Source = 1; ////// Destination = (ExpenumTestClass_float_to_uint_enum_rtime_s_DestEnumType)Source; ////// if (Destination == ExpenumTestClass_float_to_uint_enum_rtime_s_DestEnumType.ValOne) ////// return true; ////// else ////// return false; ////// } //////} //////enum ExpenumTestClass_float_to_ulong_enum_rtime_s_DestEnumType : ulong { ValOne = 1 } //////public class ExpenumTestClass_float_to_ulong_enum_rtime_s //////{ ////// public static bool testMethod() ////// { ////// ExpenumTestClass_float_to_ulong_enum_rtime_s_DestEnumType Destination; ////// float Source = 1; ////// Destination = (ExpenumTestClass_float_to_ulong_enum_rtime_s_DestEnumType)Source; ////// if (Destination == ExpenumTestClass_float_to_ulong_enum_rtime_s_DestEnumType.ValOne) ////// return true; ////// else ////// return false; ////// } //////} //////enum ExpenumTestClass_float_to_ushort_enum_rtime_s_DestEnumType : ushort { ValOne = 1 } //////public class ExpenumTestClass_float_to_ushort_enum_rtime_s //////{ ////// public static bool testMethod() ////// { ////// ExpenumTestClass_float_to_ushort_enum_rtime_s_DestEnumType Destination; ////// float Source = 1; ////// Destination = (ExpenumTestClass_float_to_ushort_enum_rtime_s_DestEnumType)Source; ////// if (Destination == ExpenumTestClass_float_to_ushort_enum_rtime_s_DestEnumType.ValOne) ////// return true; ////// else ////// return false; ////// } //////} //////enum ExpenumTestClass_short_enum_to_float_rtime_s_SrcEnumType : short { ValOne = 1 } //////public class ExpenumTestClass_short_enum_to_float_rtime_s //////{ ////// public static bool testMethod() ////// { ////// float Destination; ////// ExpenumTestClass_short_enum_to_float_rtime_s_SrcEnumType Source = ExpenumTestClass_short_enum_to_float_rtime_s_SrcEnumType.ValOne; ////// Destination = (float)Source; ////// if (Destination == 1) ////// return true; ////// else ////// return false; ////// } //////} enum ExpenumTestClass_short_enum_to_int_rtime_s_SrcEnumType : short { ValOne = 1 } public class ExpenumTestClass_short_enum_to_int_rtime_s { public static bool testMethod() { int Destination; ExpenumTestClass_short_enum_to_int_rtime_s_SrcEnumType Source = ExpenumTestClass_short_enum_to_int_rtime_s_SrcEnumType.ValOne; Destination = (int)Source; if (Destination == 1) return true; else return false; } } enum ExpenumTestClass_int_to_byte_enum_rtime_s_DestEnumType : byte { ValOne = 1 } public class ExpenumTestClass_int_to_byte_enum_rtime_s { public static bool testMethod() { ExpenumTestClass_int_to_byte_enum_rtime_s_DestEnumType Destination; int Source = 1; Destination = (ExpenumTestClass_int_to_byte_enum_rtime_s_DestEnumType)Source; if (Destination == ExpenumTestClass_int_to_byte_enum_rtime_s_DestEnumType.ValOne) return true; else return false; } } enum ExpenumTestClass_int_to_int_enum_rtime_s_DestEnumType : int { ValOne = 1 } public class ExpenumTestClass_int_to_int_enum_rtime_s { public static bool testMethod() { ExpenumTestClass_int_to_int_enum_rtime_s_DestEnumType Destination; int Source = 1; Destination = (ExpenumTestClass_int_to_int_enum_rtime_s_DestEnumType)Source; if (Destination == ExpenumTestClass_int_to_int_enum_rtime_s_DestEnumType.ValOne) return true; else return false; } } enum ExpenumTestClass_int_to_long_enum_rtime_s_DestEnumType : long { ValOne = 1 } public class ExpenumTestClass_int_to_long_enum_rtime_s { public static bool testMethod() { ExpenumTestClass_int_to_long_enum_rtime_s_DestEnumType Destination; int Source = 1; Destination = (ExpenumTestClass_int_to_long_enum_rtime_s_DestEnumType)Source; if (Destination == ExpenumTestClass_int_to_long_enum_rtime_s_DestEnumType.ValOne) return true; else return false; } } enum ExpenumTestClass_int_to_sbyte_enum_rtime_s_DestEnumType : sbyte { ValOne = 1 } public class ExpenumTestClass_int_to_sbyte_enum_rtime_s { public static bool testMethod() { ExpenumTestClass_int_to_sbyte_enum_rtime_s_DestEnumType Destination; int Source = 1; Destination = (ExpenumTestClass_int_to_sbyte_enum_rtime_s_DestEnumType)Source; if (Destination == ExpenumTestClass_int_to_sbyte_enum_rtime_s_DestEnumType.ValOne) return true; else return false; } } enum ExpenumTestClass_int_to_short_enum_rtime_s_DestEnumType : short { ValOne = 1 } public class ExpenumTestClass_int_to_short_enum_rtime_s { public static bool testMethod() { ExpenumTestClass_int_to_short_enum_rtime_s_DestEnumType Destination; int Source = 1; Destination = (ExpenumTestClass_int_to_short_enum_rtime_s_DestEnumType)Source; if (Destination == ExpenumTestClass_int_to_short_enum_rtime_s_DestEnumType.ValOne) return true; else return false; } } enum ExpenumTestClass_int_to_uint_enum_rtime_s_DestEnumType : uint { ValOne = 1 } public class ExpenumTestClass_int_to_uint_enum_rtime_s { public static bool testMethod() { ExpenumTestClass_int_to_uint_enum_rtime_s_DestEnumType Destination; int Source = 1; Destination = (ExpenumTestClass_int_to_uint_enum_rtime_s_DestEnumType)Source; if (Destination == ExpenumTestClass_int_to_uint_enum_rtime_s_DestEnumType.ValOne) return true; else return false; } } enum ExpenumTestClass_int_to_ulong_enum_rtime_s_DestEnumType : ulong { ValOne = 1 } public class ExpenumTestClass_int_to_ulong_enum_rtime_s { public static bool testMethod() { ExpenumTestClass_int_to_ulong_enum_rtime_s_DestEnumType Destination; int Source = 1; Destination = (ExpenumTestClass_int_to_ulong_enum_rtime_s_DestEnumType)Source; if (Destination == ExpenumTestClass_int_to_ulong_enum_rtime_s_DestEnumType.ValOne) return true; else return false; } } enum ExpenumTestClass_int_to_ushort_enum_rtime_s_DestEnumType : ushort { ValOne = 1 } public class ExpenumTestClass_int_to_ushort_enum_rtime_s { public static bool testMethod() { ExpenumTestClass_int_to_ushort_enum_rtime_s_DestEnumType Destination; int Source = 1; Destination = (ExpenumTestClass_int_to_ushort_enum_rtime_s_DestEnumType)Source; if (Destination == ExpenumTestClass_int_to_ushort_enum_rtime_s_DestEnumType.ValOne) return true; else return false; } } enum ExpenumTestClass_long_to_byte_enum_rtime_s_DestEnumType : byte { ValOne = 1 } public class ExpenumTestClass_long_to_byte_enum_rtime_s { public static bool testMethod() { ExpenumTestClass_long_to_byte_enum_rtime_s_DestEnumType Destination; long Source = 1; Destination = (ExpenumTestClass_long_to_byte_enum_rtime_s_DestEnumType)Source; if (Destination == ExpenumTestClass_long_to_byte_enum_rtime_s_DestEnumType.ValOne) return true; else return false; } } enum ExpenumTestClass_long_to_int_enum_rtime_s_DestEnumType : int { ValOne = 1 } public class ExpenumTestClass_long_to_int_enum_rtime_s { public static bool testMethod() { ExpenumTestClass_long_to_int_enum_rtime_s_DestEnumType Destination; long Source = 1; Destination = (ExpenumTestClass_long_to_int_enum_rtime_s_DestEnumType)Source; if (Destination == ExpenumTestClass_long_to_int_enum_rtime_s_DestEnumType.ValOne) return true; else return false; } } enum ExpenumTestClass_long_to_long_enum_rtime_s_DestEnumType : long { ValOne = 1 } public class ExpenumTestClass_long_to_long_enum_rtime_s { public static bool testMethod() { ExpenumTestClass_long_to_long_enum_rtime_s_DestEnumType Destination; long Source = 1; Destination = (ExpenumTestClass_long_to_long_enum_rtime_s_DestEnumType)Source; if (Destination == ExpenumTestClass_long_to_long_enum_rtime_s_DestEnumType.ValOne) return true; else return false; } } enum ExpenumTestClass_long_to_sbyte_enum_rtime_s_DestEnumType : sbyte { ValOne = 1 } public class ExpenumTestClass_long_to_sbyte_enum_rtime_s { public static bool testMethod() { ExpenumTestClass_long_to_sbyte_enum_rtime_s_DestEnumType Destination; long Source = 1; Destination = (ExpenumTestClass_long_to_sbyte_enum_rtime_s_DestEnumType)Source; if (Destination == ExpenumTestClass_long_to_sbyte_enum_rtime_s_DestEnumType.ValOne) return true; else return false; } } enum ExpenumTestClass_long_to_short_enum_rtime_s_DestEnumType : short { ValOne = 1 } public class ExpenumTestClass_long_to_short_enum_rtime_s { public static bool testMethod() { ExpenumTestClass_long_to_short_enum_rtime_s_DestEnumType Destination; long Source = 1; Destination = (ExpenumTestClass_long_to_short_enum_rtime_s_DestEnumType)Source; if (Destination == ExpenumTestClass_long_to_short_enum_rtime_s_DestEnumType.ValOne) return true; else return false; } } enum ExpenumTestClass_long_to_uint_enum_rtime_s_DestEnumType : uint { ValOne = 1 } public class ExpenumTestClass_long_to_uint_enum_rtime_s { public static bool testMethod() { ExpenumTestClass_long_to_uint_enum_rtime_s_DestEnumType Destination; long Source = 1; Destination = (ExpenumTestClass_long_to_uint_enum_rtime_s_DestEnumType)Source; if (Destination == ExpenumTestClass_long_to_uint_enum_rtime_s_DestEnumType.ValOne) return true; else return false; } } enum ExpenumTestClass_long_to_ulong_enum_rtime_s_DestEnumType : ulong { ValOne = 1 } public class ExpenumTestClass_long_to_ulong_enum_rtime_s { public static bool testMethod() { ExpenumTestClass_long_to_ulong_enum_rtime_s_DestEnumType Destination; long Source = 1; Destination = (ExpenumTestClass_long_to_ulong_enum_rtime_s_DestEnumType)Source; if (Destination == ExpenumTestClass_long_to_ulong_enum_rtime_s_DestEnumType.ValOne) return true; else return false; } } enum ExpenumTestClass_long_to_ushort_enum_rtime_s_DestEnumType : ushort { ValOne = 1 } public class ExpenumTestClass_long_to_ushort_enum_rtime_s { public static bool testMethod() { ExpenumTestClass_long_to_ushort_enum_rtime_s_DestEnumType Destination; long Source = 1; Destination = (ExpenumTestClass_long_to_ushort_enum_rtime_s_DestEnumType)Source; if (Destination == ExpenumTestClass_long_to_ushort_enum_rtime_s_DestEnumType.ValOne) return true; else return false; } } enum ExpenumTestClass_sbyte_to_byte_enum_rtime_s_DestEnumType : byte { ValOne = 1 } public class ExpenumTestClass_sbyte_to_byte_enum_rtime_s { public static bool testMethod() { ExpenumTestClass_sbyte_to_byte_enum_rtime_s_DestEnumType Destination; sbyte Source = 1; Destination = (ExpenumTestClass_sbyte_to_byte_enum_rtime_s_DestEnumType)Source; if (Destination == ExpenumTestClass_sbyte_to_byte_enum_rtime_s_DestEnumType.ValOne) return true; else return false; } } enum ExpenumTestClass_sbyte_to_int_enum_rtime_s_DestEnumType : int { ValOne = 1 } public class ExpenumTestClass_sbyte_to_int_enum_rtime_s { public static bool testMethod() { ExpenumTestClass_sbyte_to_int_enum_rtime_s_DestEnumType Destination; sbyte Source = 1; Destination = (ExpenumTestClass_sbyte_to_int_enum_rtime_s_DestEnumType)Source; if (Destination == ExpenumTestClass_sbyte_to_int_enum_rtime_s_DestEnumType.ValOne) return true; else return false; } } enum ExpenumTestClass_sbyte_to_long_enum_rtime_s_DestEnumType : long { ValOne = 1 } public class ExpenumTestClass_sbyte_to_long_enum_rtime_s { public static bool testMethod() { ExpenumTestClass_sbyte_to_long_enum_rtime_s_DestEnumType Destination; sbyte Source = 1; Destination = (ExpenumTestClass_sbyte_to_long_enum_rtime_s_DestEnumType)Source; if (Destination == ExpenumTestClass_sbyte_to_long_enum_rtime_s_DestEnumType.ValOne) return true; else return false; } } enum ExpenumTestClass_sbyte_to_sbyte_enum_rtime_s_DestEnumType : sbyte { ValOne = 1 } public class ExpenumTestClass_sbyte_to_sbyte_enum_rtime_s { public static bool testMethod() { ExpenumTestClass_sbyte_to_sbyte_enum_rtime_s_DestEnumType Destination; sbyte Source = 1; Destination = (ExpenumTestClass_sbyte_to_sbyte_enum_rtime_s_DestEnumType)Source; if (Destination == ExpenumTestClass_sbyte_to_sbyte_enum_rtime_s_DestEnumType.ValOne) return true; else return false; } } enum ExpenumTestClass_sbyte_to_short_enum_rtime_s_DestEnumType : short { ValOne = 1 } public class ExpenumTestClass_sbyte_to_short_enum_rtime_s { public static bool testMethod() { ExpenumTestClass_sbyte_to_short_enum_rtime_s_DestEnumType Destination; sbyte Source = 1; Destination = (ExpenumTestClass_sbyte_to_short_enum_rtime_s_DestEnumType)Source; if (Destination == ExpenumTestClass_sbyte_to_short_enum_rtime_s_DestEnumType.ValOne) return true; else return false; } } enum ExpenumTestClass_sbyte_to_uint_enum_rtime_s_DestEnumType : uint { ValOne = 1 } public class ExpenumTestClass_sbyte_to_uint_enum_rtime_s { public static bool testMethod() { ExpenumTestClass_sbyte_to_uint_enum_rtime_s_DestEnumType Destination; sbyte Source = 1; Destination = (ExpenumTestClass_sbyte_to_uint_enum_rtime_s_DestEnumType)Source; if (Destination == ExpenumTestClass_sbyte_to_uint_enum_rtime_s_DestEnumType.ValOne) return true; else return false; } } enum ExpenumTestClass_sbyte_to_ulong_enum_rtime_s_DestEnumType : ulong { ValOne = 1 } public class ExpenumTestClass_sbyte_to_ulong_enum_rtime_s { public static bool testMethod() { ExpenumTestClass_sbyte_to_ulong_enum_rtime_s_DestEnumType Destination; sbyte Source = 1; Destination = (ExpenumTestClass_sbyte_to_ulong_enum_rtime_s_DestEnumType)Source; if (Destination == ExpenumTestClass_sbyte_to_ulong_enum_rtime_s_DestEnumType.ValOne) return true; else return false; } } enum ExpenumTestClass_sbyte_to_ushort_enum_rtime_s_DestEnumType : ushort { ValOne = 1 } public class ExpenumTestClass_sbyte_to_ushort_enum_rtime_s { public static bool testMethod() { ExpenumTestClass_sbyte_to_ushort_enum_rtime_s_DestEnumType Destination; sbyte Source = 1; Destination = (ExpenumTestClass_sbyte_to_ushort_enum_rtime_s_DestEnumType)Source; if (Destination == ExpenumTestClass_sbyte_to_ushort_enum_rtime_s_DestEnumType.ValOne) return true; else return false; } } enum ExpenumTestClass_short_to_byte_enum_rtime_s_DestEnumType : byte { ValOne = 1 } public class ExpenumTestClass_short_to_byte_enum_rtime_s { public static bool testMethod() { ExpenumTestClass_short_to_byte_enum_rtime_s_DestEnumType Destination; short Source = 1; Destination = (ExpenumTestClass_short_to_byte_enum_rtime_s_DestEnumType)Source; if (Destination == ExpenumTestClass_short_to_byte_enum_rtime_s_DestEnumType.ValOne) return true; else return false; } } enum ExpenumTestClass_short_to_int_enum_rtime_s_DestEnumType : int { ValOne = 1 } public class ExpenumTestClass_short_to_int_enum_rtime_s { public static bool testMethod() { ExpenumTestClass_short_to_int_enum_rtime_s_DestEnumType Destination; short Source = 1; Destination = (ExpenumTestClass_short_to_int_enum_rtime_s_DestEnumType)Source; if (Destination == ExpenumTestClass_short_to_int_enum_rtime_s_DestEnumType.ValOne) return true; else return false; } } enum ExpenumTestClass_short_to_long_enum_rtime_s_DestEnumType : long { ValOne = 1 } public class ExpenumTestClass_short_to_long_enum_rtime_s { public static bool testMethod() { ExpenumTestClass_short_to_long_enum_rtime_s_DestEnumType Destination; short Source = 1; Destination = (ExpenumTestClass_short_to_long_enum_rtime_s_DestEnumType)Source; if (Destination == ExpenumTestClass_short_to_long_enum_rtime_s_DestEnumType.ValOne) return true; else return false; } } enum ExpenumTestClass_short_to_sbyte_enum_rtime_s_DestEnumType : sbyte { ValOne = 1 } public class ExpenumTestClass_short_to_sbyte_enum_rtime_s { public static bool testMethod() { ExpenumTestClass_short_to_sbyte_enum_rtime_s_DestEnumType Destination; short Source = 1; Destination = (ExpenumTestClass_short_to_sbyte_enum_rtime_s_DestEnumType)Source; if (Destination == ExpenumTestClass_short_to_sbyte_enum_rtime_s_DestEnumType.ValOne) return true; else return false; } } enum ExpenumTestClass_short_to_short_enum_rtime_s_DestEnumType : short { ValOne = 1 } public class ExpenumTestClass_short_to_short_enum_rtime_s { public static bool testMethod() { ExpenumTestClass_short_to_short_enum_rtime_s_DestEnumType Destination; short Source = 1; Destination = (ExpenumTestClass_short_to_short_enum_rtime_s_DestEnumType)Source; if (Destination == ExpenumTestClass_short_to_short_enum_rtime_s_DestEnumType.ValOne) return true; else return false; } } enum ExpenumTestClass_short_to_uint_enum_rtime_s_DestEnumType : uint { ValOne = 1 } public class ExpenumTestClass_short_to_uint_enum_rtime_s { public static bool testMethod() { ExpenumTestClass_short_to_uint_enum_rtime_s_DestEnumType Destination; short Source = 1; Destination = (ExpenumTestClass_short_to_uint_enum_rtime_s_DestEnumType)Source; if (Destination == ExpenumTestClass_short_to_uint_enum_rtime_s_DestEnumType.ValOne) return true; else return false; } } enum ExpenumTestClass_short_to_ulong_enum_rtime_s_DestEnumType : ulong { ValOne = 1 } public class ExpenumTestClass_short_to_ulong_enum_rtime_s { public static bool testMethod() { ExpenumTestClass_short_to_ulong_enum_rtime_s_DestEnumType Destination; short Source = 1; Destination = (ExpenumTestClass_short_to_ulong_enum_rtime_s_DestEnumType)Source; if (Destination == ExpenumTestClass_short_to_ulong_enum_rtime_s_DestEnumType.ValOne) return true; else return false; } } enum ExpenumTestClass_short_to_ushort_enum_rtime_s_DestEnumType : ushort { ValOne = 1 } public class ExpenumTestClass_short_to_ushort_enum_rtime_s { public static bool testMethod() { ExpenumTestClass_short_to_ushort_enum_rtime_s_DestEnumType Destination; short Source = 1; Destination = (ExpenumTestClass_short_to_ushort_enum_rtime_s_DestEnumType)Source; if (Destination == ExpenumTestClass_short_to_ushort_enum_rtime_s_DestEnumType.ValOne) return true; else return false; } } enum ExpenumTestClass_uint_to_byte_enum_rtime_s_DestEnumType : byte { ValOne = 1 } public class ExpenumTestClass_uint_to_byte_enum_rtime_s { public static bool testMethod() { ExpenumTestClass_uint_to_byte_enum_rtime_s_DestEnumType Destination; uint Source = 1; Destination = (ExpenumTestClass_uint_to_byte_enum_rtime_s_DestEnumType)Source; if (Destination == ExpenumTestClass_uint_to_byte_enum_rtime_s_DestEnumType.ValOne) return true; else return false; } } enum ExpenumTestClass_uint_to_int_enum_rtime_s_DestEnumType : int { ValOne = 1 } public class ExpenumTestClass_uint_to_int_enum_rtime_s { public static bool testMethod() { ExpenumTestClass_uint_to_int_enum_rtime_s_DestEnumType Destination; uint Source = 1; Destination = (ExpenumTestClass_uint_to_int_enum_rtime_s_DestEnumType)Source; if (Destination == ExpenumTestClass_uint_to_int_enum_rtime_s_DestEnumType.ValOne) return true; else return false; } } enum ExpenumTestClass_uint_to_long_enum_rtime_s_DestEnumType : long { ValOne = 1 } public class ExpenumTestClass_uint_to_long_enum_rtime_s { public static bool testMethod() { ExpenumTestClass_uint_to_long_enum_rtime_s_DestEnumType Destination; uint Source = 1; Destination = (ExpenumTestClass_uint_to_long_enum_rtime_s_DestEnumType)Source; if (Destination == ExpenumTestClass_uint_to_long_enum_rtime_s_DestEnumType.ValOne) return true; else return false; } } enum ExpenumTestClass_uint_to_sbyte_enum_rtime_s_DestEnumType : sbyte { ValOne = 1 } public class ExpenumTestClass_uint_to_sbyte_enum_rtime_s { public static bool testMethod() { ExpenumTestClass_uint_to_sbyte_enum_rtime_s_DestEnumType Destination; uint Source = 1; Destination = (ExpenumTestClass_uint_to_sbyte_enum_rtime_s_DestEnumType)Source; if (Destination == ExpenumTestClass_uint_to_sbyte_enum_rtime_s_DestEnumType.ValOne) return true; else return false; } } enum ExpenumTestClass_uint_to_short_enum_rtime_s_DestEnumType : short { ValOne = 1 } public class ExpenumTestClass_uint_to_short_enum_rtime_s { public static bool testMethod() { ExpenumTestClass_uint_to_short_enum_rtime_s_DestEnumType Destination; uint Source = 1; Destination = (ExpenumTestClass_uint_to_short_enum_rtime_s_DestEnumType)Source; if (Destination == ExpenumTestClass_uint_to_short_enum_rtime_s_DestEnumType.ValOne) return true; else return false; } } enum ExpenumTestClass_uint_to_uint_enum_rtime_s_DestEnumType : uint { ValOne = 1 } public class ExpenumTestClass_uint_to_uint_enum_rtime_s { public static bool testMethod() { ExpenumTestClass_uint_to_uint_enum_rtime_s_DestEnumType Destination; uint Source = 1; Destination = (ExpenumTestClass_uint_to_uint_enum_rtime_s_DestEnumType)Source; if (Destination == ExpenumTestClass_uint_to_uint_enum_rtime_s_DestEnumType.ValOne) return true; else return false; } } enum ExpenumTestClass_uint_to_ulong_enum_rtime_s_DestEnumType : ulong { ValOne = 1 } public class ExpenumTestClass_uint_to_ulong_enum_rtime_s { public static bool testMethod() { ExpenumTestClass_uint_to_ulong_enum_rtime_s_DestEnumType Destination; uint Source = 1; Destination = (ExpenumTestClass_uint_to_ulong_enum_rtime_s_DestEnumType)Source; if (Destination == ExpenumTestClass_uint_to_ulong_enum_rtime_s_DestEnumType.ValOne) return true; else return false; } } enum ExpenumTestClass_uint_to_ushort_enum_rtime_s_DestEnumType : ushort { ValOne = 1 } public class ExpenumTestClass_uint_to_ushort_enum_rtime_s { public static bool testMethod() { ExpenumTestClass_uint_to_ushort_enum_rtime_s_DestEnumType Destination; uint Source = 1; Destination = (ExpenumTestClass_uint_to_ushort_enum_rtime_s_DestEnumType)Source; if (Destination == ExpenumTestClass_uint_to_ushort_enum_rtime_s_DestEnumType.ValOne) return true; else return false; } } enum ExpenumTestClass_ulong_to_byte_enum_rtime_s_DestEnumType : byte { ValOne = 1 } public class ExpenumTestClass_ulong_to_byte_enum_rtime_s { public static bool testMethod() { ExpenumTestClass_ulong_to_byte_enum_rtime_s_DestEnumType Destination; ulong Source = 1; Destination = (ExpenumTestClass_ulong_to_byte_enum_rtime_s_DestEnumType)Source; if (Destination == ExpenumTestClass_ulong_to_byte_enum_rtime_s_DestEnumType.ValOne) return true; else return false; } } enum ExpenumTestClass_ulong_to_int_enum_rtime_s_DestEnumType : int { ValOne = 1 } public class ExpenumTestClass_ulong_to_int_enum_rtime_s { public static bool testMethod() { ExpenumTestClass_ulong_to_int_enum_rtime_s_DestEnumType Destination; ulong Source = 1; Destination = (ExpenumTestClass_ulong_to_int_enum_rtime_s_DestEnumType)Source; if (Destination == ExpenumTestClass_ulong_to_int_enum_rtime_s_DestEnumType.ValOne) return true; else return false; } } enum ExpenumTestClass_ulong_to_long_enum_rtime_s_DestEnumType : long { ValOne = 1 } public class ExpenumTestClass_ulong_to_long_enum_rtime_s { public static bool testMethod() { ExpenumTestClass_ulong_to_long_enum_rtime_s_DestEnumType Destination; ulong Source = 1; Destination = (ExpenumTestClass_ulong_to_long_enum_rtime_s_DestEnumType)Source; if (Destination == ExpenumTestClass_ulong_to_long_enum_rtime_s_DestEnumType.ValOne) return true; else return false; } } enum ExpenumTestClass_ulong_to_sbyte_enum_rtime_s_DestEnumType : sbyte { ValOne = 1 } public class ExpenumTestClass_ulong_to_sbyte_enum_rtime_s { public static bool testMethod() { ExpenumTestClass_ulong_to_sbyte_enum_rtime_s_DestEnumType Destination; ulong Source = 1; Destination = (ExpenumTestClass_ulong_to_sbyte_enum_rtime_s_DestEnumType)Source; if (Destination == ExpenumTestClass_ulong_to_sbyte_enum_rtime_s_DestEnumType.ValOne) return true; else return false; } } enum ExpenumTestClass_ulong_to_short_enum_rtime_s_DestEnumType : short { ValOne = 1 } public class ExpenumTestClass_ulong_to_short_enum_rtime_s { public static bool testMethod() { ExpenumTestClass_ulong_to_short_enum_rtime_s_DestEnumType Destination; ulong Source = 1; Destination = (ExpenumTestClass_ulong_to_short_enum_rtime_s_DestEnumType)Source; if (Destination == ExpenumTestClass_ulong_to_short_enum_rtime_s_DestEnumType.ValOne) return true; else return false; } } enum ExpenumTestClass_ulong_to_uint_enum_rtime_s_DestEnumType : uint { ValOne = 1 } public class ExpenumTestClass_ulong_to_uint_enum_rtime_s { public static bool testMethod() { ExpenumTestClass_ulong_to_uint_enum_rtime_s_DestEnumType Destination; ulong Source = 1; Destination = (ExpenumTestClass_ulong_to_uint_enum_rtime_s_DestEnumType)Source; if (Destination == ExpenumTestClass_ulong_to_uint_enum_rtime_s_DestEnumType.ValOne) return true; else return false; } } enum ExpenumTestClass_ulong_to_ulong_enum_rtime_s_DestEnumType : ulong { ValOne = 1 } public class ExpenumTestClass_ulong_to_ulong_enum_rtime_s { public static bool testMethod() { ExpenumTestClass_ulong_to_ulong_enum_rtime_s_DestEnumType Destination; ulong Source = 1; Destination = (ExpenumTestClass_ulong_to_ulong_enum_rtime_s_DestEnumType)Source; if (Destination == ExpenumTestClass_ulong_to_ulong_enum_rtime_s_DestEnumType.ValOne) return true; else return false; } } enum ExpenumTestClass_ulong_to_ushort_enum_rtime_s_DestEnumType : ushort { ValOne = 1 } public class ExpenumTestClass_ulong_to_ushort_enum_rtime_s { public static bool testMethod() { ExpenumTestClass_ulong_to_ushort_enum_rtime_s_DestEnumType Destination; ulong Source = 1; Destination = (ExpenumTestClass_ulong_to_ushort_enum_rtime_s_DestEnumType)Source; if (Destination == ExpenumTestClass_ulong_to_ushort_enum_rtime_s_DestEnumType.ValOne) return true; else return false; } } enum ExpenumTestClass_ushort_to_byte_enum_rtime_s_DestEnumType : byte { ValOne = 1 } public class ExpenumTestClass_ushort_to_byte_enum_rtime_s { public static bool testMethod() { ExpenumTestClass_ushort_to_byte_enum_rtime_s_DestEnumType Destination; ushort Source = 1; Destination = (ExpenumTestClass_ushort_to_byte_enum_rtime_s_DestEnumType)Source; if (Destination == ExpenumTestClass_ushort_to_byte_enum_rtime_s_DestEnumType.ValOne) return true; else return false; } } enum ExpenumTestClass_ushort_to_int_enum_rtime_s_DestEnumType : int { ValOne = 1 } public class ExpenumTestClass_ushort_to_int_enum_rtime_s { public static bool testMethod() { ExpenumTestClass_ushort_to_int_enum_rtime_s_DestEnumType Destination; ushort Source = 1; Destination = (ExpenumTestClass_ushort_to_int_enum_rtime_s_DestEnumType)Source; if (Destination == ExpenumTestClass_ushort_to_int_enum_rtime_s_DestEnumType.ValOne) return true; else return false; } } enum ExpenumTestClass_ushort_to_long_enum_rtime_s_DestEnumType : long { ValOne = 1 } public class ExpenumTestClass_ushort_to_long_enum_rtime_s { public static bool testMethod() { ExpenumTestClass_ushort_to_long_enum_rtime_s_DestEnumType Destination; ushort Source = 1; Destination = (ExpenumTestClass_ushort_to_long_enum_rtime_s_DestEnumType)Source; if (Destination == ExpenumTestClass_ushort_to_long_enum_rtime_s_DestEnumType.ValOne) return true; else return false; } } enum ExpenumTestClass_ushort_to_sbyte_enum_rtime_s_DestEnumType : sbyte { ValOne = 1 } public class ExpenumTestClass_ushort_to_sbyte_enum_rtime_s { public static bool testMethod() { ExpenumTestClass_ushort_to_sbyte_enum_rtime_s_DestEnumType Destination; ushort Source = 1; Destination = (ExpenumTestClass_ushort_to_sbyte_enum_rtime_s_DestEnumType)Source; if (Destination == ExpenumTestClass_ushort_to_sbyte_enum_rtime_s_DestEnumType.ValOne) return true; else return false; } } enum ExpenumTestClass_ushort_to_short_enum_rtime_s_DestEnumType : short { ValOne = 1 } public class ExpenumTestClass_ushort_to_short_enum_rtime_s { public static bool testMethod() { ExpenumTestClass_ushort_to_short_enum_rtime_s_DestEnumType Destination; ushort Source = 1; Destination = (ExpenumTestClass_ushort_to_short_enum_rtime_s_DestEnumType)Source; if (Destination == ExpenumTestClass_ushort_to_short_enum_rtime_s_DestEnumType.ValOne) return true; else return false; } } enum ExpenumTestClass_ushort_to_uint_enum_rtime_s_DestEnumType : uint { ValOne = 1 } public class ExpenumTestClass_ushort_to_uint_enum_rtime_s { public static bool testMethod() { ExpenumTestClass_ushort_to_uint_enum_rtime_s_DestEnumType Destination; ushort Source = 1; Destination = (ExpenumTestClass_ushort_to_uint_enum_rtime_s_DestEnumType)Source; if (Destination == ExpenumTestClass_ushort_to_uint_enum_rtime_s_DestEnumType.ValOne) return true; else return false; } } enum ExpenumTestClass_ushort_to_ulong_enum_rtime_s_DestEnumType : ulong { ValOne = 1 } public class ExpenumTestClass_ushort_to_ulong_enum_rtime_s { public static bool testMethod() { ExpenumTestClass_ushort_to_ulong_enum_rtime_s_DestEnumType Destination; ushort Source = 1; Destination = (ExpenumTestClass_ushort_to_ulong_enum_rtime_s_DestEnumType)Source; if (Destination == ExpenumTestClass_ushort_to_ulong_enum_rtime_s_DestEnumType.ValOne) return true; else return false; } } enum ExpenumTestClass_ushort_to_ushort_enum_rtime_s_DestEnumType : ushort { ValOne = 1 } public class ExpenumTestClass_ushort_to_ushort_enum_rtime_s { public static bool testMethod() { ExpenumTestClass_ushort_to_ushort_enum_rtime_s_DestEnumType Destination; ushort Source = 1; Destination = (ExpenumTestClass_ushort_to_ushort_enum_rtime_s_DestEnumType)Source; if (Destination == ExpenumTestClass_ushort_to_ushort_enum_rtime_s_DestEnumType.ValOne) return true; else return false; } } enum ExpenumTestClass_int_enum_to_ushort_rtime_s_SrcEnumType : int { ValOne = 1 } public class ExpenumTestClass_int_enum_to_ushort_rtime_s { public static bool testMethod() { ushort Destination; ExpenumTestClass_int_enum_to_ushort_rtime_s_SrcEnumType Source = ExpenumTestClass_int_enum_to_ushort_rtime_s_SrcEnumType.ValOne; Destination = (ushort)Source; if (Destination == 1) return true; else return false; } } enum ExpenumTestClass_long_enum_to_byte_rtime_s_SrcEnumType : long { ValOne = 1 } public class ExpenumTestClass_long_enum_to_byte_rtime_s { public static bool testMethod() { byte Destination; ExpenumTestClass_long_enum_to_byte_rtime_s_SrcEnumType Source = ExpenumTestClass_long_enum_to_byte_rtime_s_SrcEnumType.ValOne; Destination = (byte)Source; if (Destination == 1) return true; else return false; } } //////enum ExpenumTestClass_long_enum_to_double_rtime_s_SrcEnumType : long { ValOne = 1 } //////public class ExpenumTestClass_long_enum_to_double_rtime_s //////{ ////// public static bool testMethod() ////// { ////// double Destination; ////// ExpenumTestClass_long_enum_to_double_rtime_s_SrcEnumType Source = ExpenumTestClass_long_enum_to_double_rtime_s_SrcEnumType.ValOne; ////// Destination = (double)Source; ////// if (Destination == 1) ////// return true; ////// else ////// return false; ////// } //////} enum ExpenumTestClass_long_enum_to_float_rtime_s_SrcEnumType : long { ValOne = 1 } public class ExpenumTestClass_long_enum_to_float_rtime_s { public static bool testMethod() { float Destination; ExpenumTestClass_long_enum_to_float_rtime_s_SrcEnumType Source = ExpenumTestClass_long_enum_to_float_rtime_s_SrcEnumType.ValOne; Destination = (float)Source; if (Destination == 1) return true; else return false; } } enum ExpenumTestClass_long_enum_to_int_rtime_s_SrcEnumType : long { ValOne = 1 } public class ExpenumTestClass_long_enum_to_int_rtime_s { public static bool testMethod() { int Destination; ExpenumTestClass_long_enum_to_int_rtime_s_SrcEnumType Source = ExpenumTestClass_long_enum_to_int_rtime_s_SrcEnumType.ValOne; Destination = (int)Source; if (Destination == 1) return true; else return false; } } enum ExpenumTestClass_long_enum_to_long_rtime_s_SrcEnumType : long { ValOne = 1 } public class ExpenumTestClass_long_enum_to_long_rtime_s { public static bool testMethod() { long Destination; ExpenumTestClass_long_enum_to_long_rtime_s_SrcEnumType Source = ExpenumTestClass_long_enum_to_long_rtime_s_SrcEnumType.ValOne; Destination = (long)Source; if (Destination == 1) return true; else return false; } } enum ExpenumTestClass_long_enum_to_sbyte_rtime_s_SrcEnumType : long { ValOne = 1 } public class ExpenumTestClass_long_enum_to_sbyte_rtime_s { public static bool testMethod() { sbyte Destination; ExpenumTestClass_long_enum_to_sbyte_rtime_s_SrcEnumType Source = ExpenumTestClass_long_enum_to_sbyte_rtime_s_SrcEnumType.ValOne; Destination = (sbyte)Source; if (Destination == 1) return true; else return false; } } enum ExpenumTestClass_long_enum_to_short_rtime_s_SrcEnumType : long { ValOne = 1 } public class ExpenumTestClass_long_enum_to_short_rtime_s { public static bool testMethod() { short Destination; ExpenumTestClass_long_enum_to_short_rtime_s_SrcEnumType Source = ExpenumTestClass_long_enum_to_short_rtime_s_SrcEnumType.ValOne; Destination = (short)Source; if (Destination == 1) return true; else return false; } } enum ExpenumTestClass_long_enum_to_uint_rtime_s_SrcEnumType : long { ValOne = 1 } public class ExpenumTestClass_long_enum_to_uint_rtime_s { public static bool testMethod() { uint Destination; ExpenumTestClass_long_enum_to_uint_rtime_s_SrcEnumType Source = ExpenumTestClass_long_enum_to_uint_rtime_s_SrcEnumType.ValOne; Destination = (uint)Source; if (Destination == 1) return true; else return false; } } enum ExpenumTestClass_long_enum_to_ulong_rtime_s_SrcEnumType : long { ValOne = 1 } public class ExpenumTestClass_long_enum_to_ulong_rtime_s { public static bool testMethod() { ulong Destination; ExpenumTestClass_long_enum_to_ulong_rtime_s_SrcEnumType Source = ExpenumTestClass_long_enum_to_ulong_rtime_s_SrcEnumType.ValOne; Destination = (ulong)Source; if (Destination == 1) return true; else return false; } } enum ExpenumTestClass_long_enum_to_ushort_rtime_s_SrcEnumType : long { ValOne = 1 } public class ExpenumTestClass_long_enum_to_ushort_rtime_s { public static bool testMethod() { ushort Destination; ExpenumTestClass_long_enum_to_ushort_rtime_s_SrcEnumType Source = ExpenumTestClass_long_enum_to_ushort_rtime_s_SrcEnumType.ValOne; Destination = (ushort)Source; if (Destination == 1) return true; else return false; } } enum ExpenumTestClass_sbyte_enum_to_byte_rtime_s_SrcEnumType : sbyte { ValOne = 1 } public class ExpenumTestClass_sbyte_enum_to_byte_rtime_s { public static bool testMethod() { byte Destination; ExpenumTestClass_sbyte_enum_to_byte_rtime_s_SrcEnumType Source = ExpenumTestClass_sbyte_enum_to_byte_rtime_s_SrcEnumType.ValOne; Destination = (byte)Source; if (Destination == 1) return true; else return false; } } //////enum ExpenumTestClass_sbyte_enum_to_double_rtime_s_SrcEnumType : sbyte { ValOne = 1 } //////public class ExpenumTestClass_sbyte_enum_to_double_rtime_s //////{ ////// public static bool testMethod() ////// { ////// double Destination; ////// ExpenumTestClass_sbyte_enum_to_double_rtime_s_SrcEnumType Source = ExpenumTestClass_sbyte_enum_to_double_rtime_s_SrcEnumType.ValOne; ////// Destination = (double)Source; ////// if (Destination == 1) ////// return true; ////// else ////// return false; ////// } //////} enum ExpenumTestClass_sbyte_enum_to_float_rtime_s_SrcEnumType : sbyte { ValOne = 1 } public class ExpenumTestClass_sbyte_enum_to_float_rtime_s { public static bool testMethod() { float Destination; ExpenumTestClass_sbyte_enum_to_float_rtime_s_SrcEnumType Source = ExpenumTestClass_sbyte_enum_to_float_rtime_s_SrcEnumType.ValOne; Destination = (float)Source; if (Destination == 1) return true; else return false; } } } } ================================================ FILE: Zelig/Zelig/Test/RunTime/NETMF/mscorlib/conversions/expenum/Expenum2Tests.cs ================================================ //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // Copyright (c) Microsoft Corporation. All rights reserved. //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// using System; namespace Microsoft.Zelig.Test { public class Expenum2Tests : TestBase, ITestInterface { [SetUp] public InitializeResult Initialize() { Log.Comment("Adding set up for the tests."); // Add your functionality here. return InitializeResult.ReadyToGo; } [TearDown] public void CleanUp() { Log.Comment("Cleaning up after the tests"); } public override TestResult Run( string[] args ) { TestResult result = TestResult.Pass; string testName = "Expenum2_"; int testNumber = 0; result |= Assert.CheckFailed( Expenum_sbyte_enum_to_int_rtime_s_Test( ), testName, ++testNumber ); result |= Assert.CheckFailed( Expenum_sbyte_enum_to_long_rtime_s_Test( ), testName, ++testNumber ); result |= Assert.CheckFailed( Expenum_sbyte_enum_to_sbyte_rtime_s_Test( ), testName, ++testNumber ); result |= Assert.CheckFailed( Expenum_sbyte_enum_to_short_rtime_s_Test( ), testName, ++testNumber ); result |= Assert.CheckFailed( Expenum_sbyte_enum_to_uint_rtime_s_Test( ), testName, ++testNumber ); result |= Assert.CheckFailed( Expenum_sbyte_enum_to_ulong_rtime_s_Test( ), testName, ++testNumber ); result |= Assert.CheckFailed( Expenum_sbyte_enum_to_ushort_rtime_s_Test( ), testName, ++testNumber ); result |= Assert.CheckFailed( Expenum_short_enum_to_byte_rtime_s_Test( ), testName, ++testNumber ); //////result |= Assert.CheckFailed( Expenum_short_enum_to_double_rtime_s_Test( ), testName, ++testNumber ); result |= Assert.CheckFailed( Expenum_short_enum_to_long_rtime_s_Test( ), testName, ++testNumber ); result |= Assert.CheckFailed( Expenum_short_enum_to_sbyte_rtime_s_Test( ), testName, ++testNumber ); result |= Assert.CheckFailed( Expenum_short_enum_to_short_rtime_s_Test( ), testName, ++testNumber ); result |= Assert.CheckFailed( Expenum_short_enum_to_uint_rtime_s_Test( ), testName, ++testNumber ); result |= Assert.CheckFailed( Expenum_short_enum_to_ulong_rtime_s_Test( ), testName, ++testNumber ); result |= Assert.CheckFailed( Expenum_short_enum_to_ushort_rtime_s_Test( ), testName, ++testNumber ); result |= Assert.CheckFailed( Expenum_uint_enum_to_byte_rtime_s_Test( ), testName, ++testNumber ); //////result |= Assert.CheckFailed( Expenum_uint_enum_to_double_rtime_s_Test( ), testName, ++testNumber ); //////result |= Assert.CheckFailed( Expenum_uint_enum_to_float_rtime_s_Test( ), testName, ++testNumber ); result |= Assert.CheckFailed( Expenum_uint_enum_to_int_rtime_s_Test( ), testName, ++testNumber ); result |= Assert.CheckFailed( Expenum_uint_enum_to_long_rtime_s_Test( ), testName, ++testNumber ); result |= Assert.CheckFailed( Expenum_uint_enum_to_sbyte_rtime_s_Test( ), testName, ++testNumber ); result |= Assert.CheckFailed( Expenum_uint_enum_to_short_rtime_s_Test( ), testName, ++testNumber ); result |= Assert.CheckFailed( Expenum_uint_enum_to_uint_rtime_s_Test( ), testName, ++testNumber ); result |= Assert.CheckFailed( Expenum_uint_enum_to_ulong_rtime_s_Test( ), testName, ++testNumber ); result |= Assert.CheckFailed( Expenum_uint_enum_to_ushort_rtime_s_Test( ), testName, ++testNumber ); result |= Assert.CheckFailed( Expenum_ulong_enum_to_byte_rtime_s_Test( ), testName, ++testNumber ); //////result |= Assert.CheckFailed( Expenum_ulong_enum_to_double_rtime_s_Test( ), testName, ++testNumber ); //////result |= Assert.CheckFailed( Expenum_ulong_enum_to_float_rtime_s_Test( ), testName, ++testNumber ); result |= Assert.CheckFailed( Expenum_ulong_enum_to_int_rtime_s_Test( ), testName, ++testNumber ); result |= Assert.CheckFailed( Expenum_ulong_enum_to_long_rtime_s_Test( ), testName, ++testNumber ); result |= Assert.CheckFailed( Expenum_ulong_enum_to_sbyte_rtime_s_Test( ), testName, ++testNumber ); result |= Assert.CheckFailed( Expenum_ulong_enum_to_short_rtime_s_Test( ), testName, ++testNumber ); result |= Assert.CheckFailed( Expenum_ulong_enum_to_uint_rtime_s_Test( ), testName, ++testNumber ); result |= Assert.CheckFailed( Expenum_ulong_enum_to_ulong_rtime_s_Test( ), testName, ++testNumber ); result |= Assert.CheckFailed( Expenum_ulong_enum_to_ushort_rtime_s_Test( ), testName, ++testNumber ); result |= Assert.CheckFailed( Expenum_ushort_enum_to_byte_rtime_s_Test( ), testName, ++testNumber ); //////result |= Assert.CheckFailed( Expenum_ushort_enum_to_double_rtime_s_Test( ), testName, ++testNumber ); //////result |= Assert.CheckFailed( Expenum_ushort_enum_to_float_rtime_s_Test( ), testName, ++testNumber ); result |= Assert.CheckFailed( Expenum_ushort_enum_to_int_rtime_s_Test( ), testName, ++testNumber ); result |= Assert.CheckFailed( Expenum_ushort_enum_to_long_rtime_s_Test( ), testName, ++testNumber ); result |= Assert.CheckFailed( Expenum_ushort_enum_to_sbyte_rtime_s_Test( ), testName, ++testNumber ); result |= Assert.CheckFailed( Expenum_ushort_enum_to_short_rtime_s_Test( ), testName, ++testNumber ); result |= Assert.CheckFailed( Expenum_ushort_enum_to_uint_rtime_s_Test( ), testName, ++testNumber ); result |= Assert.CheckFailed( Expenum_ushort_enum_to_ulong_rtime_s_Test( ), testName, ++testNumber ); result |= Assert.CheckFailed( Expenum_ushort_enum_to_ushort_rtime_s_Test( ), testName, ++testNumber ); result |= Assert.CheckFailed( Expenum_byte_enum_to_byte_rtime_s_Test( ), testName, ++testNumber ); //////result |= Assert.CheckFailed( Expenum_byte_enum_to_double_rtime_s_Test( ), testName, ++testNumber ); //////result |= Assert.CheckFailed( Expenum_byte_enum_to_float_rtime_s_Test( ), testName, ++testNumber ); result |= Assert.CheckFailed( Expenum_byte_enum_to_int_rtime_s_Test( ), testName, ++testNumber ); result |= Assert.CheckFailed( Expenum_byte_enum_to_long_rtime_s_Test( ), testName, ++testNumber ); result |= Assert.CheckFailed( Expenum_byte_enum_to_sbyte_rtime_s_Test( ), testName, ++testNumber ); result |= Assert.CheckFailed( Expenum_byte_enum_to_short_rtime_s_Test( ), testName, ++testNumber ); result |= Assert.CheckFailed( Expenum_byte_enum_to_uint_rtime_s_Test( ), testName, ++testNumber ); result |= Assert.CheckFailed( Expenum_byte_enum_to_ulong_rtime_s_Test( ), testName, ++testNumber ); result |= Assert.CheckFailed( Expenum_byte_enum_to_ushort_rtime_s_Test( ), testName, ++testNumber ); result |= Assert.CheckFailed( Expenum_int_enum_to_byte_rtime_s_Test( ), testName, ++testNumber ); //////result |= Assert.CheckFailed( Expenum_int_enum_to_double_rtime_s_Test( ), testName, ++testNumber ); //////result |= Assert.CheckFailed( Expenum_int_enum_to_float_rtime_s_Test( ), testName, ++testNumber ); result |= Assert.CheckFailed( Expenum_int_enum_to_int_rtime_s_Test( ), testName, ++testNumber ); result |= Assert.CheckFailed( Expenum_int_enum_to_long_rtime_s_Test( ), testName, ++testNumber ); result |= Assert.CheckFailed( Expenum_int_enum_to_sbyte_rtime_s_Test( ), testName, ++testNumber ); result |= Assert.CheckFailed( Expenum_int_enum_to_short_rtime_s_Test( ), testName, ++testNumber ); result |= Assert.CheckFailed( Expenum_int_enum_to_uint_rtime_s_Test( ), testName, ++testNumber ); result |= Assert.CheckFailed( Expenum_int_enum_to_ulong_rtime_s_Test( ), testName, ++testNumber ); result |= Assert.CheckFailed( Expenum_int_enum_to_ulong_enum_rtime_s_Test( ), testName, ++testNumber ); result |= Assert.CheckFailed( Expenum_int_enum_to_ushort_enum_rtime_s_Test( ), testName, ++testNumber ); result |= Assert.CheckFailed( Expenum_long_enum_to_byte_enum_rtime_s_Test( ), testName, ++testNumber ); result |= Assert.CheckFailed( Expenum_long_enum_to_int_enum_rtime_s_Test( ), testName, ++testNumber ); result |= Assert.CheckFailed( Expenum_long_enum_to_long_enum_rtime_s_Test( ), testName, ++testNumber ); result |= Assert.CheckFailed( Expenum_long_enum_to_sbyte_enum_rtime_s_Test( ), testName, ++testNumber ); result |= Assert.CheckFailed( Expenum_long_enum_to_short_enum_rtime_s_Test( ), testName, ++testNumber ); result |= Assert.CheckFailed( Expenum_long_enum_to_uint_enum_rtime_s_Test( ), testName, ++testNumber ); result |= Assert.CheckFailed( Expenum_long_enum_to_ulong_enum_rtime_s_Test( ), testName, ++testNumber ); result |= Assert.CheckFailed( Expenum_long_enum_to_ushort_enum_rtime_s_Test( ), testName, ++testNumber ); result |= Assert.CheckFailed( Expenum_sbyte_enum_to_byte_enum_rtime_s_Test( ), testName, ++testNumber ); result |= Assert.CheckFailed( Expenum_sbyte_enum_to_int_enum_rtime_s_Test( ), testName, ++testNumber ); result |= Assert.CheckFailed( Expenum_sbyte_enum_to_long_enum_rtime_s_Test( ), testName, ++testNumber ); result |= Assert.CheckFailed( Expenum_sbyte_enum_to_sbyte_enum_rtime_s_Test( ), testName, ++testNumber ); result |= Assert.CheckFailed( Expenum_sbyte_enum_to_short_enum_rtime_s_Test( ), testName, ++testNumber ); result |= Assert.CheckFailed( Expenum_sbyte_enum_to_uint_enum_rtime_s_Test( ), testName, ++testNumber ); result |= Assert.CheckFailed( Expenum_byte_enum_to_ulong_enum_rtime_s_Test( ), testName, ++testNumber ); result |= Assert.CheckFailed( Expenum_byte_enum_to_ushort_enum_rtime_s_Test( ), testName, ++testNumber ); result |= Assert.CheckFailed( Expenum_int_enum_to_byte_enum_rtime_s_Test( ), testName, ++testNumber ); result |= Assert.CheckFailed( Expenum_int_enum_to_int_enum_rtime_s_Test( ), testName, ++testNumber ); result |= Assert.CheckFailed( Expenum_int_enum_to_long_enum_rtime_s_Test( ), testName, ++testNumber ); result |= Assert.CheckFailed( Expenum_int_enum_to_sbyte_enum_rtime_s_Test( ), testName, ++testNumber ); result |= Assert.CheckFailed( Expenum_int_enum_to_short_enum_rtime_s_Test( ), testName, ++testNumber ); result |= Assert.CheckFailed( Expenum_int_enum_to_uint_enum_rtime_s_Test( ), testName, ++testNumber ); return result; } //Expenum Test methods //The following tests were ported from folder current\test\cases\client\CLR\Conformance\10_classes\Expenum //byte_to_byte_enum_rtime_s,byte_to_int_enum_rtime_s,byte_to_long_enum_rtime_s,byte_to_sbyte_enum_rtime_s, //byte_to_short_enum_rtime_s,byte_to_uint_enum_rtime_s,byte_to_ulong_enum_rtime_s,byte_to_ushort_enum_rtime_s, //double_to_byte_enum_rtime_s,double_to_int_enum_rtime_s,double_to_long_enum_rtime_s,double_to_sbyte_enum_rtime_s, //double_to_short_enum_rtime_s,double_to_uint_enum_rtime_s,double_to_ulong_enum_rtime_s, //double_to_ushort_enum_rtime_s,float_to_byte_enum_rtime_s,float_to_int_enum_rtime_s,float_to_long_enum_rtime_s, //float_to_sbyte_enum_rtime_s,float_to_short_enum_rtime_s,float_to_uint_enum_rtime_s,float_to_ulong_enum_rtime_s, //float_to_ushort_enum_rtime_s,short_enum_to_float_rtime_s,short_enum_to_int_rtime_s,int_to_byte_enum_rtime_s, //int_to_int_enum_rtime_s,int_to_long_enum_rtime_s,int_to_sbyte_enum_rtime_s,int_to_short_enum_rtime_s, //int_to_uint_enum_rtime_s,int_to_ulong_enum_rtime_s,int_to_ushort_enum_rtime_s,long_to_byte_enum_rtime_s, //long_to_int_enum_rtime_s,long_to_long_enum_rtime_s,long_to_sbyte_enum_rtime_s,long_to_short_enum_rtime_s, //long_to_uint_enum_rtime_s,long_to_ulong_enum_rtime_s,long_to_ushort_enum_rtime_s,sbyte_to_byte_enum_rtime_s, //sbyte_to_int_enum_rtime_s,sbyte_to_long_enum_rtime_s,sbyte_to_sbyte_enum_rtime_s,sbyte_to_short_enum_rtime_s, //sbyte_to_uint_enum_rtime_s,sbyte_to_ulong_enum_rtime_s,sbyte_to_ushort_enum_rtime_s,short_to_byte_enum_rtime_s, //short_to_int_enum_rtime_s,short_to_long_enum_rtime_s,short_to_sbyte_enum_rtime_s,short_to_short_enum_rtime_s, //short_to_uint_enum_rtime_s,short_to_ulong_enum_rtime_s,short_to_ushort_enum_rtime_s,uint_to_byte_enum_rtime_s, //uint_to_int_enum_rtime_s,uint_to_long_enum_rtime_s,uint_to_sbyte_enum_rtime_s,uint_to_short_enum_rtime_s, //uint_to_uint_enum_rtime_s,uint_to_ulong_enum_rtime_s,uint_to_ushort_enum_rtime_s,ulong_to_byte_enum_rtime_s, //ulong_to_int_enum_rtime_s,ulong_to_long_enum_rtime_s,ulong_to_sbyte_enum_rtime_s,ulong_to_short_enum_rtime_s, //ulong_to_uint_enum_rtime_s,ulong_to_ulong_enum_rtime_s,ulong_to_ushort_enum_rtime_s,ushort_to_byte_enum_rtime_s, //ushort_to_int_enum_rtime_s,ushort_to_long_enum_rtime_s,ushort_to_sbyte_enum_rtime_s,ushort_to_short_enum_rtime_s, //ushort_to_uint_enum_rtime_s,ushort_to_ulong_enum_rtime_s,ushort_to_ushort_enum_rtime_s,int_enum_to_ushort_rtime_s, //long_enum_to_byte_rtime_s,long_enum_to_double_rtime_s,long_enum_to_float_rtime_s,long_enum_to_int_rtime_s, //long_enum_to_long_rtime_s,long_enum_to_sbyte_rtime_s,long_enum_to_short_rtime_s,long_enum_to_uint_rtime_s, //long_enum_to_ulong_rtime_s,long_enum_to_ushort_rtime_s,sbyte_enum_to_byte_rtime_s,sbyte_enum_to_double_rtime_s, //sbyte_enum_to_float_rtime_s,sbyte_enum_to_int_rtime_s,sbyte_enum_to_long_rtime_s,sbyte_enum_to_sbyte_rtime_s, //sbyte_enum_to_short_rtime_s,sbyte_enum_to_uint_rtime_s,sbyte_enum_to_ulong_rtime_s,sbyte_enum_to_ushort_rtime_s, //short_enum_to_byte_rtime_s,short_enum_to_double_rtime_s,short_enum_to_long_rtime_s,short_enum_to_sbyte_rtime_s, //short_enum_to_short_rtime_s,short_enum_to_uint_rtime_s,short_enum_to_ulong_rtime_s,short_enum_to_ushort_rtime_s, //uint_enum_to_byte_rtime_s,uint_enum_to_double_rtime_s,uint_enum_to_float_rtime_s,uint_enum_to_int_rtime_s, //uint_enum_to_long_rtime_s,uint_enum_to_sbyte_rtime_s,uint_enum_to_short_rtime_s,uint_enum_to_uint_rtime_s, //uint_enum_to_ulong_rtime_s,uint_enum_to_ushort_rtime_s,ulong_enum_to_byte_rtime_s,ulong_enum_to_double_rtime_s, //ulong_enum_to_float_rtime_s,ulong_enum_to_int_rtime_s,ulong_enum_to_long_rtime_s,ulong_enum_to_sbyte_rtime_s, //ulong_enum_to_short_rtime_s,ulong_enum_to_uint_rtime_s,ulong_enum_to_ulong_rtime_s,ulong_enum_to_ushort_rtime_s, //ushort_enum_to_byte_rtime_s,ushort_enum_to_double_rtime_s,ushort_enum_to_float_rtime_s,ushort_enum_to_int_rtime_s, //ushort_enum_to_long_rtime_s,ushort_enum_to_sbyte_rtime_s,ushort_enum_to_short_rtime_s,ushort_enum_to_uint_rtime_s, //ushort_enum_to_ulong_rtime_s,ushort_enum_to_ushort_rtime_s,byte_enum_to_byte_rtime_s,byte_enum_to_double_rtime_s, //byte_enum_to_float_rtime_s,byte_enum_to_int_rtime_s,byte_enum_to_long_rtime_s,byte_enum_to_sbyte_rtime_s, //byte_enum_to_short_rtime_s,byte_enum_to_uint_rtime_s,byte_enum_to_ulong_rtime_s,byte_enum_to_ushort_rtime_s, //int_enum_to_byte_rtime_s,int_enum_to_double_rtime_s,int_enum_to_float_rtime_s,int_enum_to_int_rtime_s, //int_enum_to_long_rtime_s,int_enum_to_sbyte_rtime_s,int_enum_to_short_rtime_s,int_enum_to_uint_rtime_s, //int_enum_to_ulong_rtime_s,int_enum_to_ulong_enum_rtime_s,int_enum_to_ushort_enum_rtime_s,long_enum_to_byte_enum_rtime_s, //long_enum_to_int_enum_rtime_s,long_enum_to_long_enum_rtime_s,long_enum_to_sbyte_enum_rtime_s,long_enum_to_short_enum_rtime_s, //long_enum_to_uint_enum_rtime_s,long_enum_to_ulong_enum_rtime_s,long_enum_to_ushort_enum_rtime_s, //sbyte_enum_to_byte_enum_rtime_s,sbyte_enum_to_int_enum_rtime_s,sbyte_enum_to_long_enum_rtime_s,sbyte_enum_to_sbyte_enum_rtime_s, //sbyte_enum_to_short_enum_rtime_s,sbyte_enum_to_uint_enum_rtime_s,sbyte_enum_to_ulong_enum_rtime_s,sbyte_enum_to_ushort_enum_rtime_s, //short_enum_to_byte_enum_rtime_s,short_enum_to_int_enum_rtime_s,short_enum_to_long_enum_rtime_s,short_enum_to_sbyte_enum_rtime_s, //short_enum_to_short_enum_rtime_s,short_enum_to_uint_enum_rtime_s,short_enum_to_ulong_enum_rtime_s,short_enum_to_ushort_enum_rtime_s, //uint_enum_to_byte_enum_rtime_s,uint_enum_to_int_enum_rtime_s,uint_enum_to_long_enum_rtime_s,uint_enum_to_sbyte_enum_rtime_s, //uint_enum_to_short_enum_rtime_s,uint_enum_to_uint_enum_rtime_s,uint_enum_to_ulong_enum_rtime_s,uint_enum_to_ushort_enum_rtime_s, //ulong_enum_to_byte_enum_rtime_s,ulong_enum_to_int_enum_rtime_s,ulong_enum_to_long_enum_rtime_s,ulong_enum_to_sbyte_enum_rtime_s, //ulong_enum_to_short_enum_rtime_s,ulong_enum_to_uint_enum_rtime_s,ulong_enum_to_ulong_enum_rtime_s,ulong_enum_to_ushort_enum_rtime_s, //ushort_enum_to_byte_enum_rtime_s,ushort_enum_to_int_enum_rtime_s,ushort_enum_to_long_enum_rtime_s,ushort_enum_to_sbyte_enum_rtime_s, //ushort_enum_to_short_enum_rtime_s,ushort_enum_to_uint_enum_rtime_s,ushort_enum_to_ulong_enum_rtime_s,ushort_enum_to_ushort_enum_rtime_s, //byte_enum_to_byte_enum_rtime_s,byte_enum_to_int_enum_rtime_s,byte_enum_to_long_enum_rtime_s,byte_enum_to_sbyte_enum_rtime_s, //byte_enum_to_short_enum_rtime_s,byte_enum_to_uint_enum_rtime_s,byte_enum_to_ulong_enum_rtime_s,byte_enum_to_ushort_enum_rtime_s, //int_enum_to_byte_enum_rtime_s,int_enum_to_int_enum_rtime_s,int_enum_to_long_enum_rtime_s,int_enum_to_sbyte_enum_rtime_s //int_enum_to_short_enum_rtime_s,int_enum_to_uint_enum_rtime_s //Test Case Calls [TestMethod] public TestResult Expenum_sbyte_enum_to_int_rtime_s_Test() { if (ExpenumTestClass_sbyte_enum_to_int_rtime_s.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Expenum_sbyte_enum_to_long_rtime_s_Test() { if (ExpenumTestClass_sbyte_enum_to_long_rtime_s.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Expenum_sbyte_enum_to_sbyte_rtime_s_Test() { if (ExpenumTestClass_sbyte_enum_to_sbyte_rtime_s.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Expenum_sbyte_enum_to_short_rtime_s_Test() { if (ExpenumTestClass_sbyte_enum_to_short_rtime_s.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Expenum_sbyte_enum_to_uint_rtime_s_Test() { if (ExpenumTestClass_sbyte_enum_to_uint_rtime_s.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Expenum_sbyte_enum_to_ulong_rtime_s_Test() { if (ExpenumTestClass_sbyte_enum_to_ulong_rtime_s.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Expenum_sbyte_enum_to_ushort_rtime_s_Test() { if (ExpenumTestClass_sbyte_enum_to_ushort_rtime_s.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Expenum_short_enum_to_byte_rtime_s_Test() { if (ExpenumTestClass_short_enum_to_byte_rtime_s.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } //////[TestMethod] //////public TestResult Expenum_short_enum_to_double_rtime_s_Test() //////{ ////// if (ExpenumTestClass_short_enum_to_double_rtime_s.testMethod()) ////// { ////// return TestResult.Pass; ////// } ////// return TestResult.Fail; //////} [TestMethod] public TestResult Expenum_short_enum_to_long_rtime_s_Test() { if (ExpenumTestClass_short_enum_to_long_rtime_s.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Expenum_short_enum_to_sbyte_rtime_s_Test() { if (ExpenumTestClass_short_enum_to_sbyte_rtime_s.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Expenum_short_enum_to_short_rtime_s_Test() { if (ExpenumTestClass_short_enum_to_short_rtime_s.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Expenum_short_enum_to_uint_rtime_s_Test() { if (ExpenumTestClass_short_enum_to_uint_rtime_s.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Expenum_short_enum_to_ulong_rtime_s_Test() { if (ExpenumTestClass_short_enum_to_ulong_rtime_s.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Expenum_short_enum_to_ushort_rtime_s_Test() { if (ExpenumTestClass_short_enum_to_ushort_rtime_s.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Expenum_uint_enum_to_byte_rtime_s_Test() { if (ExpenumTestClass_uint_enum_to_byte_rtime_s.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } //////[TestMethod] //////public TestResult Expenum_uint_enum_to_double_rtime_s_Test() //////{ ////// if (ExpenumTestClass_uint_enum_to_double_rtime_s.testMethod()) ////// { ////// return TestResult.Pass; ////// } ////// return TestResult.Fail; //////} //////[TestMethod] //////public TestResult Expenum_uint_enum_to_float_rtime_s_Test() //////{ ////// if (ExpenumTestClass_uint_enum_to_float_rtime_s.testMethod()) ////// { ////// return TestResult.Pass; ////// } ////// return TestResult.Fail; //////} [TestMethod] public TestResult Expenum_uint_enum_to_int_rtime_s_Test() { if (ExpenumTestClass_uint_enum_to_int_rtime_s.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Expenum_uint_enum_to_long_rtime_s_Test() { if (ExpenumTestClass_uint_enum_to_long_rtime_s.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Expenum_uint_enum_to_sbyte_rtime_s_Test() { if (ExpenumTestClass_uint_enum_to_sbyte_rtime_s.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Expenum_uint_enum_to_short_rtime_s_Test() { if (ExpenumTestClass_uint_enum_to_short_rtime_s.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Expenum_uint_enum_to_uint_rtime_s_Test() { if (ExpenumTestClass_uint_enum_to_uint_rtime_s.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Expenum_uint_enum_to_ulong_rtime_s_Test() { if (ExpenumTestClass_uint_enum_to_ulong_rtime_s.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Expenum_uint_enum_to_ushort_rtime_s_Test() { if (ExpenumTestClass_uint_enum_to_ushort_rtime_s.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Expenum_ulong_enum_to_byte_rtime_s_Test() { if (ExpenumTestClass_ulong_enum_to_byte_rtime_s.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } //////[TestMethod] //////public TestResult Expenum_ulong_enum_to_double_rtime_s_Test() //////{ ////// if (ExpenumTestClass_ulong_enum_to_double_rtime_s.testMethod()) ////// { ////// return TestResult.Pass; ////// } ////// return TestResult.Fail; //////} //////[TestMethod] //////public TestResult Expenum_ulong_enum_to_float_rtime_s_Test() //////{ ////// if (ExpenumTestClass_ulong_enum_to_float_rtime_s.testMethod()) ////// { ////// return TestResult.Pass; ////// } ////// return TestResult.Fail; //////} [TestMethod] public TestResult Expenum_ulong_enum_to_int_rtime_s_Test() { if (ExpenumTestClass_ulong_enum_to_int_rtime_s.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Expenum_ulong_enum_to_long_rtime_s_Test() { if (ExpenumTestClass_ulong_enum_to_long_rtime_s.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Expenum_ulong_enum_to_sbyte_rtime_s_Test() { if (ExpenumTestClass_ulong_enum_to_sbyte_rtime_s.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Expenum_ulong_enum_to_short_rtime_s_Test() { if (ExpenumTestClass_ulong_enum_to_short_rtime_s.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Expenum_ulong_enum_to_uint_rtime_s_Test() { if (ExpenumTestClass_ulong_enum_to_uint_rtime_s.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Expenum_ulong_enum_to_ulong_rtime_s_Test() { if (ExpenumTestClass_ulong_enum_to_ulong_rtime_s.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Expenum_ulong_enum_to_ushort_rtime_s_Test() { if (ExpenumTestClass_ulong_enum_to_ushort_rtime_s.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Expenum_ushort_enum_to_byte_rtime_s_Test() { if (ExpenumTestClass_ushort_enum_to_byte_rtime_s.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Expenum_ushort_enum_to_double_rtime_s_Test() { if (ExpenumTestClass_ushort_enum_to_double_rtime_s.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } //////[TestMethod] //////public TestResult Expenum_ushort_enum_to_float_rtime_s_Test() //////{ ////// if (ExpenumTestClass_ushort_enum_to_float_rtime_s.testMethod()) ////// { ////// return TestResult.Pass; ////// } ////// return TestResult.Fail; //////} [TestMethod] public TestResult Expenum_ushort_enum_to_int_rtime_s_Test() { if (ExpenumTestClass_ushort_enum_to_int_rtime_s.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Expenum_ushort_enum_to_long_rtime_s_Test() { if (ExpenumTestClass_ushort_enum_to_long_rtime_s.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Expenum_ushort_enum_to_sbyte_rtime_s_Test() { if (ExpenumTestClass_ushort_enum_to_sbyte_rtime_s.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Expenum_ushort_enum_to_short_rtime_s_Test() { if (ExpenumTestClass_ushort_enum_to_short_rtime_s.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Expenum_ushort_enum_to_uint_rtime_s_Test() { if (ExpenumTestClass_ushort_enum_to_uint_rtime_s.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Expenum_ushort_enum_to_ulong_rtime_s_Test() { if (ExpenumTestClass_ushort_enum_to_ulong_rtime_s.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Expenum_ushort_enum_to_ushort_rtime_s_Test() { if (ExpenumTestClass_ushort_enum_to_ushort_rtime_s.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Expenum_byte_enum_to_byte_rtime_s_Test() { if (ExpenumTestClass_byte_enum_to_byte_rtime_s.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } //////[TestMethod] //////public TestResult Expenum_byte_enum_to_double_rtime_s_Test() //////{ ////// if (ExpenumTestClass_byte_enum_to_double_rtime_s.testMethod()) ////// { ////// return TestResult.Pass; ////// } ////// return TestResult.Fail; //////} //////[TestMethod] //////public TestResult Expenum_byte_enum_to_float_rtime_s_Test() //////{ ////// if (ExpenumTestClass_byte_enum_to_float_rtime_s.testMethod()) ////// { ////// return TestResult.Pass; ////// } ////// return TestResult.Fail; //////} [TestMethod] public TestResult Expenum_byte_enum_to_int_rtime_s_Test() { if (ExpenumTestClass_byte_enum_to_int_rtime_s.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Expenum_byte_enum_to_long_rtime_s_Test() { if (ExpenumTestClass_byte_enum_to_long_rtime_s.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Expenum_byte_enum_to_sbyte_rtime_s_Test() { if (ExpenumTestClass_byte_enum_to_sbyte_rtime_s.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Expenum_byte_enum_to_short_rtime_s_Test() { if (ExpenumTestClass_byte_enum_to_short_rtime_s.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Expenum_byte_enum_to_uint_rtime_s_Test() { if (ExpenumTestClass_byte_enum_to_uint_rtime_s.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Expenum_byte_enum_to_ulong_rtime_s_Test() { if (ExpenumTestClass_byte_enum_to_ulong_rtime_s.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Expenum_byte_enum_to_ushort_rtime_s_Test() { if (ExpenumTestClass_byte_enum_to_ushort_rtime_s.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Expenum_int_enum_to_byte_rtime_s_Test() { if (ExpenumTestClass_int_enum_to_byte_rtime_s.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Expenum_int_enum_to_double_rtime_s_Test() { if (ExpenumTestClass_int_enum_to_double_rtime_s.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } //////[TestMethod] //////public TestResult Expenum_int_enum_to_float_rtime_s_Test() //////{ ////// if (ExpenumTestClass_int_enum_to_float_rtime_s.testMethod()) ////// { ////// return TestResult.Pass; ////// } ////// return TestResult.Fail; //////} [TestMethod] public TestResult Expenum_int_enum_to_int_rtime_s_Test() { if (ExpenumTestClass_int_enum_to_int_rtime_s.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Expenum_int_enum_to_long_rtime_s_Test() { if (ExpenumTestClass_int_enum_to_long_rtime_s.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Expenum_int_enum_to_sbyte_rtime_s_Test() { if (ExpenumTestClass_int_enum_to_sbyte_rtime_s.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Expenum_int_enum_to_short_rtime_s_Test() { if (ExpenumTestClass_int_enum_to_short_rtime_s.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Expenum_int_enum_to_uint_rtime_s_Test() { if (ExpenumTestClass_int_enum_to_uint_rtime_s.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Expenum_int_enum_to_ulong_rtime_s_Test() { if (ExpenumTestClass_int_enum_to_ulong_rtime_s.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Expenum_int_enum_to_ulong_enum_rtime_s_Test() { if (ExpenumTestClass_int_enum_to_ulong_enum_rtime_s.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Expenum_int_enum_to_ushort_enum_rtime_s_Test() { if (ExpenumTestClass_int_enum_to_ushort_enum_rtime_s.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Expenum_long_enum_to_byte_enum_rtime_s_Test() { if (ExpenumTestClass_long_enum_to_byte_enum_rtime_s.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Expenum_long_enum_to_int_enum_rtime_s_Test() { if (ExpenumTestClass_long_enum_to_int_enum_rtime_s.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Expenum_long_enum_to_long_enum_rtime_s_Test() { if (ExpenumTestClass_long_enum_to_long_enum_rtime_s.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Expenum_long_enum_to_sbyte_enum_rtime_s_Test() { if (ExpenumTestClass_long_enum_to_sbyte_enum_rtime_s.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Expenum_long_enum_to_short_enum_rtime_s_Test() { if (ExpenumTestClass_long_enum_to_short_enum_rtime_s.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Expenum_long_enum_to_uint_enum_rtime_s_Test() { if (ExpenumTestClass_long_enum_to_uint_enum_rtime_s.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Expenum_long_enum_to_ulong_enum_rtime_s_Test() { if (ExpenumTestClass_long_enum_to_ulong_enum_rtime_s.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Expenum_long_enum_to_ushort_enum_rtime_s_Test() { if (ExpenumTestClass_long_enum_to_ushort_enum_rtime_s.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Expenum_sbyte_enum_to_byte_enum_rtime_s_Test() { if (ExpenumTestClass_sbyte_enum_to_byte_enum_rtime_s.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Expenum_sbyte_enum_to_int_enum_rtime_s_Test() { if (ExpenumTestClass_sbyte_enum_to_int_enum_rtime_s.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Expenum_sbyte_enum_to_long_enum_rtime_s_Test() { if (ExpenumTestClass_sbyte_enum_to_long_enum_rtime_s.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Expenum_sbyte_enum_to_sbyte_enum_rtime_s_Test() { if (ExpenumTestClass_sbyte_enum_to_sbyte_enum_rtime_s.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Expenum_sbyte_enum_to_short_enum_rtime_s_Test() { if (ExpenumTestClass_sbyte_enum_to_short_enum_rtime_s.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Expenum_sbyte_enum_to_uint_enum_rtime_s_Test() { if (ExpenumTestClass_sbyte_enum_to_uint_enum_rtime_s.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Expenum_byte_enum_to_ulong_enum_rtime_s_Test() { if (ExpenumTestClass_byte_enum_to_ulong_enum_rtime_s.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Expenum_byte_enum_to_ushort_enum_rtime_s_Test() { if (ExpenumTestClass_byte_enum_to_ushort_enum_rtime_s.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Expenum_int_enum_to_byte_enum_rtime_s_Test() { if (ExpenumTestClass_int_enum_to_byte_enum_rtime_s.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Expenum_int_enum_to_int_enum_rtime_s_Test() { if (ExpenumTestClass_int_enum_to_int_enum_rtime_s.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Expenum_int_enum_to_long_enum_rtime_s_Test() { if (ExpenumTestClass_int_enum_to_long_enum_rtime_s.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Expenum_int_enum_to_sbyte_enum_rtime_s_Test() { if (ExpenumTestClass_int_enum_to_sbyte_enum_rtime_s.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Expenum_int_enum_to_short_enum_rtime_s_Test() { if (ExpenumTestClass_int_enum_to_short_enum_rtime_s.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Expenum_int_enum_to_uint_enum_rtime_s_Test() { if (ExpenumTestClass_int_enum_to_uint_enum_rtime_s.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } enum ExpenumTestClass_sbyte_enum_to_int_rtime_s_SrcEnumType : sbyte { ValOne = 1 } public class ExpenumTestClass_sbyte_enum_to_int_rtime_s { public static bool testMethod() { int Destination; ExpenumTestClass_sbyte_enum_to_int_rtime_s_SrcEnumType Source = ExpenumTestClass_sbyte_enum_to_int_rtime_s_SrcEnumType.ValOne; Destination = (int)Source; if (Destination == 1) return true; else return false; } } enum ExpenumTestClass_sbyte_enum_to_long_rtime_s_SrcEnumType : sbyte { ValOne = 1 } public class ExpenumTestClass_sbyte_enum_to_long_rtime_s { public static bool testMethod() { long Destination; ExpenumTestClass_sbyte_enum_to_long_rtime_s_SrcEnumType Source = ExpenumTestClass_sbyte_enum_to_long_rtime_s_SrcEnumType.ValOne; Destination = (long)Source; if (Destination == 1) return true; else return false; } } enum ExpenumTestClass_sbyte_enum_to_sbyte_rtime_s_SrcEnumType : sbyte { ValOne = 1 } public class ExpenumTestClass_sbyte_enum_to_sbyte_rtime_s { public static bool testMethod() { sbyte Destination; ExpenumTestClass_sbyte_enum_to_sbyte_rtime_s_SrcEnumType Source = ExpenumTestClass_sbyte_enum_to_sbyte_rtime_s_SrcEnumType.ValOne; Destination = (sbyte)Source; if (Destination == 1) return true; else return false; } } enum ExpenumTestClass_sbyte_enum_to_short_rtime_s_SrcEnumType : sbyte { ValOne = 1 } public class ExpenumTestClass_sbyte_enum_to_short_rtime_s { public static bool testMethod() { short Destination; ExpenumTestClass_sbyte_enum_to_short_rtime_s_SrcEnumType Source = ExpenumTestClass_sbyte_enum_to_short_rtime_s_SrcEnumType.ValOne; Destination = (short)Source; if (Destination == 1) return true; else return false; } } enum ExpenumTestClass_sbyte_enum_to_uint_rtime_s_SrcEnumType : sbyte { ValOne = 1 } public class ExpenumTestClass_sbyte_enum_to_uint_rtime_s { public static bool testMethod() { uint Destination; ExpenumTestClass_sbyte_enum_to_uint_rtime_s_SrcEnumType Source = ExpenumTestClass_sbyte_enum_to_uint_rtime_s_SrcEnumType.ValOne; Destination = (uint)Source; if (Destination == 1) return true; else return false; } } enum ExpenumTestClass_sbyte_enum_to_ulong_rtime_s_SrcEnumType : sbyte { ValOne = 1 } public class ExpenumTestClass_sbyte_enum_to_ulong_rtime_s { public static bool testMethod() { ulong Destination; ExpenumTestClass_sbyte_enum_to_ulong_rtime_s_SrcEnumType Source = ExpenumTestClass_sbyte_enum_to_ulong_rtime_s_SrcEnumType.ValOne; Destination = (ulong)Source; if (Destination == 1) return true; else return false; } } enum ExpenumTestClass_sbyte_enum_to_ushort_rtime_s_SrcEnumType : sbyte { ValOne = 1 } public class ExpenumTestClass_sbyte_enum_to_ushort_rtime_s { public static bool testMethod() { ushort Destination; ExpenumTestClass_sbyte_enum_to_ushort_rtime_s_SrcEnumType Source = ExpenumTestClass_sbyte_enum_to_ushort_rtime_s_SrcEnumType.ValOne; Destination = (ushort)Source; if (Destination == 1) return true; else return false; } } enum ExpenumTestClass_short_enum_to_byte_rtime_s_SrcEnumType : short { ValOne = 1 } public class ExpenumTestClass_short_enum_to_byte_rtime_s { public static bool testMethod() { byte Destination; ExpenumTestClass_short_enum_to_byte_rtime_s_SrcEnumType Source = ExpenumTestClass_short_enum_to_byte_rtime_s_SrcEnumType.ValOne; Destination = (byte)Source; if (Destination == 1) return true; else return false; } } enum ExpenumTestClass_short_enum_to_double_rtime_s_SrcEnumType : short { ValOne = 1 } public class ExpenumTestClass_short_enum_to_double_rtime_s { public static bool testMethod() { double Destination; ExpenumTestClass_short_enum_to_double_rtime_s_SrcEnumType Source = ExpenumTestClass_short_enum_to_double_rtime_s_SrcEnumType.ValOne; Destination = (double)Source; if (Destination == 1) return true; else return false; } } enum ExpenumTestClass_short_enum_to_long_rtime_s_SrcEnumType : short { ValOne = 1 } public class ExpenumTestClass_short_enum_to_long_rtime_s { public static bool testMethod() { long Destination; ExpenumTestClass_short_enum_to_long_rtime_s_SrcEnumType Source = ExpenumTestClass_short_enum_to_long_rtime_s_SrcEnumType.ValOne; Destination = (long)Source; if (Destination == 1) return true; else return false; } } enum ExpenumTestClass_short_enum_to_sbyte_rtime_s_SrcEnumType : short { ValOne = 1 } public class ExpenumTestClass_short_enum_to_sbyte_rtime_s { public static bool testMethod() { sbyte Destination; ExpenumTestClass_short_enum_to_sbyte_rtime_s_SrcEnumType Source = ExpenumTestClass_short_enum_to_sbyte_rtime_s_SrcEnumType.ValOne; Destination = (sbyte)Source; if (Destination == 1) return true; else return false; } } enum ExpenumTestClass_short_enum_to_short_rtime_s_SrcEnumType : short { ValOne = 1 } public class ExpenumTestClass_short_enum_to_short_rtime_s { public static bool testMethod() { short Destination; ExpenumTestClass_short_enum_to_short_rtime_s_SrcEnumType Source = ExpenumTestClass_short_enum_to_short_rtime_s_SrcEnumType.ValOne; Destination = (short)Source; if (Destination == 1) return true; else return false; } } enum ExpenumTestClass_short_enum_to_uint_rtime_s_SrcEnumType : short { ValOne = 1 } public class ExpenumTestClass_short_enum_to_uint_rtime_s { public static bool testMethod() { uint Destination; ExpenumTestClass_short_enum_to_uint_rtime_s_SrcEnumType Source = ExpenumTestClass_short_enum_to_uint_rtime_s_SrcEnumType.ValOne; Destination = (uint)Source; if (Destination == 1) return true; else return false; } } enum ExpenumTestClass_short_enum_to_ulong_rtime_s_SrcEnumType : short { ValOne = 1 } public class ExpenumTestClass_short_enum_to_ulong_rtime_s { public static bool testMethod() { ulong Destination; ExpenumTestClass_short_enum_to_ulong_rtime_s_SrcEnumType Source = ExpenumTestClass_short_enum_to_ulong_rtime_s_SrcEnumType.ValOne; Destination = (ulong)Source; if (Destination == 1) return true; else return false; } } enum ExpenumTestClass_short_enum_to_ushort_rtime_s_SrcEnumType : short { ValOne = 1 } public class ExpenumTestClass_short_enum_to_ushort_rtime_s { public static bool testMethod() { ushort Destination; ExpenumTestClass_short_enum_to_ushort_rtime_s_SrcEnumType Source = ExpenumTestClass_short_enum_to_ushort_rtime_s_SrcEnumType.ValOne; Destination = (ushort)Source; if (Destination == 1) return true; else return false; } } enum ExpenumTestClass_uint_enum_to_byte_rtime_s_SrcEnumType : uint { ValOne = 1 } public class ExpenumTestClass_uint_enum_to_byte_rtime_s { public static bool testMethod() { byte Destination; ExpenumTestClass_uint_enum_to_byte_rtime_s_SrcEnumType Source = ExpenumTestClass_uint_enum_to_byte_rtime_s_SrcEnumType.ValOne; Destination = (byte)Source; if (Destination == 1) return true; else return false; } } enum ExpenumTestClass_uint_enum_to_double_rtime_s_SrcEnumType : uint { ValOne = 1 } public class ExpenumTestClass_uint_enum_to_double_rtime_s { public static bool testMethod() { double Destination; ExpenumTestClass_uint_enum_to_double_rtime_s_SrcEnumType Source = ExpenumTestClass_uint_enum_to_double_rtime_s_SrcEnumType.ValOne; Destination = (double)Source; if (Destination == 1) return true; else return false; } } //////enum ExpenumTestClass_uint_enum_to_float_rtime_s_SrcEnumType : uint { ValOne = 1 } //////public class ExpenumTestClass_uint_enum_to_float_rtime_s //////{ ////// public static bool testMethod() ////// { ////// float Destination; ////// ExpenumTestClass_uint_enum_to_float_rtime_s_SrcEnumType Source = ExpenumTestClass_uint_enum_to_float_rtime_s_SrcEnumType.ValOne; ////// Destination = (float)Source; ////// if (Destination == 1) ////// return true; ////// else ////// return false; ////// } //////} enum ExpenumTestClass_uint_enum_to_int_rtime_s_SrcEnumType : uint { ValOne = 1 } public class ExpenumTestClass_uint_enum_to_int_rtime_s { public static bool testMethod() { int Destination; ExpenumTestClass_uint_enum_to_int_rtime_s_SrcEnumType Source = ExpenumTestClass_uint_enum_to_int_rtime_s_SrcEnumType.ValOne; Destination = (int)Source; if (Destination == 1) return true; else return false; } } enum ExpenumTestClass_uint_enum_to_long_rtime_s_SrcEnumType : uint { ValOne = 1 } public class ExpenumTestClass_uint_enum_to_long_rtime_s { public static bool testMethod() { long Destination; ExpenumTestClass_uint_enum_to_long_rtime_s_SrcEnumType Source = ExpenumTestClass_uint_enum_to_long_rtime_s_SrcEnumType.ValOne; Destination = (long)Source; if (Destination == 1) return true; else return false; } } enum ExpenumTestClass_uint_enum_to_sbyte_rtime_s_SrcEnumType : uint { ValOne = 1 } public class ExpenumTestClass_uint_enum_to_sbyte_rtime_s { public static bool testMethod() { sbyte Destination; ExpenumTestClass_uint_enum_to_sbyte_rtime_s_SrcEnumType Source = ExpenumTestClass_uint_enum_to_sbyte_rtime_s_SrcEnumType.ValOne; Destination = (sbyte)Source; if (Destination == 1) return true; else return false; } } enum ExpenumTestClass_uint_enum_to_short_rtime_s_SrcEnumType : uint { ValOne = 1 } public class ExpenumTestClass_uint_enum_to_short_rtime_s { public static bool testMethod() { short Destination; ExpenumTestClass_uint_enum_to_short_rtime_s_SrcEnumType Source = ExpenumTestClass_uint_enum_to_short_rtime_s_SrcEnumType.ValOne; Destination = (short)Source; if (Destination == 1) return true; else return false; } } enum ExpenumTestClass_uint_enum_to_uint_rtime_s_SrcEnumType : uint { ValOne = 1 } public class ExpenumTestClass_uint_enum_to_uint_rtime_s { public static bool testMethod() { uint Destination; ExpenumTestClass_uint_enum_to_uint_rtime_s_SrcEnumType Source = ExpenumTestClass_uint_enum_to_uint_rtime_s_SrcEnumType.ValOne; Destination = (uint)Source; if (Destination == 1) return true; else return false; } } enum ExpenumTestClass_uint_enum_to_ulong_rtime_s_SrcEnumType : uint { ValOne = 1 } public class ExpenumTestClass_uint_enum_to_ulong_rtime_s { public static bool testMethod() { ulong Destination; ExpenumTestClass_uint_enum_to_ulong_rtime_s_SrcEnumType Source = ExpenumTestClass_uint_enum_to_ulong_rtime_s_SrcEnumType.ValOne; Destination = (ulong)Source; if (Destination == 1) return true; else return false; } } enum ExpenumTestClass_uint_enum_to_ushort_rtime_s_SrcEnumType : uint { ValOne = 1 } public class ExpenumTestClass_uint_enum_to_ushort_rtime_s { public static bool testMethod() { ushort Destination; ExpenumTestClass_uint_enum_to_ushort_rtime_s_SrcEnumType Source = ExpenumTestClass_uint_enum_to_ushort_rtime_s_SrcEnumType.ValOne; Destination = (ushort)Source; if (Destination == 1) return true; else return false; } } enum ExpenumTestClass_ulong_enum_to_byte_rtime_s_SrcEnumType : ulong { ValOne = 1 } public class ExpenumTestClass_ulong_enum_to_byte_rtime_s { public static bool testMethod() { byte Destination; ExpenumTestClass_ulong_enum_to_byte_rtime_s_SrcEnumType Source = ExpenumTestClass_ulong_enum_to_byte_rtime_s_SrcEnumType.ValOne; Destination = (byte)Source; if (Destination == 1) return true; else return false; } } enum ExpenumTestClass_ulong_enum_to_double_rtime_s_SrcEnumType : ulong { ValOne = 1 } public class ExpenumTestClass_ulong_enum_to_double_rtime_s { public static bool testMethod() { double Destination; ExpenumTestClass_ulong_enum_to_double_rtime_s_SrcEnumType Source = ExpenumTestClass_ulong_enum_to_double_rtime_s_SrcEnumType.ValOne; Destination = (double)Source; if (Destination == 1) return true; else return false; } } //////enum ExpenumTestClass_ulong_enum_to_float_rtime_s_SrcEnumType : ulong { ValOne = 1 } //////public class ExpenumTestClass_ulong_enum_to_float_rtime_s //////{ ////// public static bool testMethod() ////// { ////// float Destination; ////// ExpenumTestClass_ulong_enum_to_float_rtime_s_SrcEnumType Source = ExpenumTestClass_ulong_enum_to_float_rtime_s_SrcEnumType.ValOne; ////// Destination = (float)Source; ////// if (Destination == 1) ////// return true; ////// else ////// return false; ////// } //////} enum ExpenumTestClass_ulong_enum_to_int_rtime_s_SrcEnumType : ulong { ValOne = 1 } public class ExpenumTestClass_ulong_enum_to_int_rtime_s { public static bool testMethod() { int Destination; ExpenumTestClass_ulong_enum_to_int_rtime_s_SrcEnumType Source = ExpenumTestClass_ulong_enum_to_int_rtime_s_SrcEnumType.ValOne; Destination = (int)Source; if (Destination == 1) return true; else return false; } } enum ExpenumTestClass_ulong_enum_to_long_rtime_s_SrcEnumType : ulong { ValOne = 1 } public class ExpenumTestClass_ulong_enum_to_long_rtime_s { public static bool testMethod() { long Destination; ExpenumTestClass_ulong_enum_to_long_rtime_s_SrcEnumType Source = ExpenumTestClass_ulong_enum_to_long_rtime_s_SrcEnumType.ValOne; Destination = (long)Source; if (Destination == 1) return true; else return false; } } enum ExpenumTestClass_ulong_enum_to_sbyte_rtime_s_SrcEnumType : ulong { ValOne = 1 } public class ExpenumTestClass_ulong_enum_to_sbyte_rtime_s { public static bool testMethod() { sbyte Destination; ExpenumTestClass_ulong_enum_to_sbyte_rtime_s_SrcEnumType Source = ExpenumTestClass_ulong_enum_to_sbyte_rtime_s_SrcEnumType.ValOne; Destination = (sbyte)Source; if (Destination == 1) return true; else return false; } } enum ExpenumTestClass_ulong_enum_to_short_rtime_s_SrcEnumType : ulong { ValOne = 1 } public class ExpenumTestClass_ulong_enum_to_short_rtime_s { public static bool testMethod() { short Destination; ExpenumTestClass_ulong_enum_to_short_rtime_s_SrcEnumType Source = ExpenumTestClass_ulong_enum_to_short_rtime_s_SrcEnumType.ValOne; Destination = (short)Source; if (Destination == 1) return true; else return false; } } enum ExpenumTestClass_ulong_enum_to_uint_rtime_s_SrcEnumType : ulong { ValOne = 1 } public class ExpenumTestClass_ulong_enum_to_uint_rtime_s { public static bool testMethod() { uint Destination; ExpenumTestClass_ulong_enum_to_uint_rtime_s_SrcEnumType Source = ExpenumTestClass_ulong_enum_to_uint_rtime_s_SrcEnumType.ValOne; Destination = (uint)Source; if (Destination == 1) return true; else return false; } } enum ExpenumTestClass_ulong_enum_to_ulong_rtime_s_SrcEnumType : ulong { ValOne = 1 } public class ExpenumTestClass_ulong_enum_to_ulong_rtime_s { public static bool testMethod() { ulong Destination; ExpenumTestClass_ulong_enum_to_ulong_rtime_s_SrcEnumType Source = ExpenumTestClass_ulong_enum_to_ulong_rtime_s_SrcEnumType.ValOne; Destination = (ulong)Source; if (Destination == 1) return true; else return false; } } enum ExpenumTestClass_ulong_enum_to_ushort_rtime_s_SrcEnumType : ulong { ValOne = 1 } public class ExpenumTestClass_ulong_enum_to_ushort_rtime_s { public static bool testMethod() { ushort Destination; ExpenumTestClass_ulong_enum_to_ushort_rtime_s_SrcEnumType Source = ExpenumTestClass_ulong_enum_to_ushort_rtime_s_SrcEnumType.ValOne; Destination = (ushort)Source; if (Destination == 1) return true; else return false; } } enum ExpenumTestClass_ushort_enum_to_byte_rtime_s_SrcEnumType : ushort { ValOne = 1 } public class ExpenumTestClass_ushort_enum_to_byte_rtime_s { public static bool testMethod() { byte Destination; ExpenumTestClass_ushort_enum_to_byte_rtime_s_SrcEnumType Source = ExpenumTestClass_ushort_enum_to_byte_rtime_s_SrcEnumType.ValOne; Destination = (byte)Source; if (Destination == 1) return true; else return false; } } enum ExpenumTestClass_ushort_enum_to_double_rtime_s_SrcEnumType : ushort { ValOne = 1 } public class ExpenumTestClass_ushort_enum_to_double_rtime_s { public static bool testMethod() { double Destination; ExpenumTestClass_ushort_enum_to_double_rtime_s_SrcEnumType Source = ExpenumTestClass_ushort_enum_to_double_rtime_s_SrcEnumType.ValOne; Destination = (double)Source; if (Destination == 1) return true; else return false; } } enum ExpenumTestClass_ushort_enum_to_float_rtime_s_SrcEnumType : ushort { ValOne = 1 } public class ExpenumTestClass_ushort_enum_to_float_rtime_s { public static bool testMethod() { float Destination; ExpenumTestClass_ushort_enum_to_float_rtime_s_SrcEnumType Source = ExpenumTestClass_ushort_enum_to_float_rtime_s_SrcEnumType.ValOne; Destination = (float)Source; if (Destination == 1) return true; else return false; } } enum ExpenumTestClass_ushort_enum_to_int_rtime_s_SrcEnumType : ushort { ValOne = 1 } public class ExpenumTestClass_ushort_enum_to_int_rtime_s { public static bool testMethod() { int Destination; ExpenumTestClass_ushort_enum_to_int_rtime_s_SrcEnumType Source = ExpenumTestClass_ushort_enum_to_int_rtime_s_SrcEnumType.ValOne; Destination = (int)Source; if (Destination == 1) return true; else return false; } } enum ExpenumTestClass_ushort_enum_to_long_rtime_s_SrcEnumType : ushort { ValOne = 1 } public class ExpenumTestClass_ushort_enum_to_long_rtime_s { public static bool testMethod() { long Destination; ExpenumTestClass_ushort_enum_to_long_rtime_s_SrcEnumType Source = ExpenumTestClass_ushort_enum_to_long_rtime_s_SrcEnumType.ValOne; Destination = (long)Source; if (Destination == 1) return true; else return false; } } enum ExpenumTestClass_ushort_enum_to_sbyte_rtime_s_SrcEnumType : ushort { ValOne = 1 } public class ExpenumTestClass_ushort_enum_to_sbyte_rtime_s { public static bool testMethod() { sbyte Destination; ExpenumTestClass_ushort_enum_to_sbyte_rtime_s_SrcEnumType Source = ExpenumTestClass_ushort_enum_to_sbyte_rtime_s_SrcEnumType.ValOne; Destination = (sbyte)Source; if (Destination == 1) return true; else return false; } } enum ExpenumTestClass_ushort_enum_to_short_rtime_s_SrcEnumType : ushort { ValOne = 1 } public class ExpenumTestClass_ushort_enum_to_short_rtime_s { public static bool testMethod() { short Destination; ExpenumTestClass_ushort_enum_to_short_rtime_s_SrcEnumType Source = ExpenumTestClass_ushort_enum_to_short_rtime_s_SrcEnumType.ValOne; Destination = (short)Source; if (Destination == 1) return true; else return false; } } enum ExpenumTestClass_ushort_enum_to_uint_rtime_s_SrcEnumType : ushort { ValOne = 1 } public class ExpenumTestClass_ushort_enum_to_uint_rtime_s { public static bool testMethod() { uint Destination; ExpenumTestClass_ushort_enum_to_uint_rtime_s_SrcEnumType Source = ExpenumTestClass_ushort_enum_to_uint_rtime_s_SrcEnumType.ValOne; Destination = (uint)Source; if (Destination == 1) return true; else return false; } } enum ExpenumTestClass_ushort_enum_to_ulong_rtime_s_SrcEnumType : ushort { ValOne = 1 } public class ExpenumTestClass_ushort_enum_to_ulong_rtime_s { public static bool testMethod() { ulong Destination; ExpenumTestClass_ushort_enum_to_ulong_rtime_s_SrcEnumType Source = ExpenumTestClass_ushort_enum_to_ulong_rtime_s_SrcEnumType.ValOne; Destination = (ulong)Source; if (Destination == 1) return true; else return false; } } enum ExpenumTestClass_ushort_enum_to_ushort_rtime_s_SrcEnumType : ushort { ValOne = 1 } public class ExpenumTestClass_ushort_enum_to_ushort_rtime_s { public static bool testMethod() { ushort Destination; ExpenumTestClass_ushort_enum_to_ushort_rtime_s_SrcEnumType Source = ExpenumTestClass_ushort_enum_to_ushort_rtime_s_SrcEnumType.ValOne; Destination = (ushort)Source; if (Destination == 1) return true; else return false; } } enum ExpenumTestClass_byte_enum_to_byte_rtime_s_SrcEnumType : byte { ValOne = 1 } public class ExpenumTestClass_byte_enum_to_byte_rtime_s { public static bool testMethod() { byte Destination; ExpenumTestClass_byte_enum_to_byte_rtime_s_SrcEnumType Source = ExpenumTestClass_byte_enum_to_byte_rtime_s_SrcEnumType.ValOne; Destination = (byte)Source; if (Destination == 1) return true; else return false; } } //////enum ExpenumTestClass_byte_enum_to_double_rtime_s_SrcEnumType : byte { ValOne = 1 } //////public class ExpenumTestClass_byte_enum_to_double_rtime_s //////{ ////// public static bool testMethod() ////// { ////// double Destination; ////// ExpenumTestClass_byte_enum_to_double_rtime_s_SrcEnumType Source = ExpenumTestClass_byte_enum_to_double_rtime_s_SrcEnumType.ValOne; ////// Destination = (double)Source; ////// if (Destination == 1) ////// return true; ////// else ////// return false; ////// } //////} //////enum ExpenumTestClass_byte_enum_to_float_rtime_s_SrcEnumType : byte { ValOne = 1 } //////public class ExpenumTestClass_byte_enum_to_float_rtime_s //////{ ////// public static bool testMethod() ////// { ////// float Destination; ////// ExpenumTestClass_byte_enum_to_float_rtime_s_SrcEnumType Source = ExpenumTestClass_byte_enum_to_float_rtime_s_SrcEnumType.ValOne; ////// Destination = (float)Source; ////// if (Destination == 1) ////// return true; ////// else ////// return false; ////// } //////} enum ExpenumTestClass_byte_enum_to_int_rtime_s_SrcEnumType : byte { ValOne = 1 } public class ExpenumTestClass_byte_enum_to_int_rtime_s { public static bool testMethod() { int Destination; ExpenumTestClass_byte_enum_to_int_rtime_s_SrcEnumType Source = ExpenumTestClass_byte_enum_to_int_rtime_s_SrcEnumType.ValOne; Destination = (int)Source; if (Destination == 1) return true; else return false; } } enum ExpenumTestClass_byte_enum_to_long_rtime_s_SrcEnumType : byte { ValOne = 1 } public class ExpenumTestClass_byte_enum_to_long_rtime_s { public static bool testMethod() { long Destination; ExpenumTestClass_byte_enum_to_long_rtime_s_SrcEnumType Source = ExpenumTestClass_byte_enum_to_long_rtime_s_SrcEnumType.ValOne; Destination = (long)Source; if (Destination == 1) return true; else return false; } } enum ExpenumTestClass_byte_enum_to_sbyte_rtime_s_SrcEnumType : byte { ValOne = 1 } public class ExpenumTestClass_byte_enum_to_sbyte_rtime_s { public static bool testMethod() { sbyte Destination; ExpenumTestClass_byte_enum_to_sbyte_rtime_s_SrcEnumType Source = ExpenumTestClass_byte_enum_to_sbyte_rtime_s_SrcEnumType.ValOne; Destination = (sbyte)Source; if (Destination == 1) return true; else return false; } } enum ExpenumTestClass_byte_enum_to_short_rtime_s_SrcEnumType : byte { ValOne = 1 } public class ExpenumTestClass_byte_enum_to_short_rtime_s { public static bool testMethod() { short Destination; ExpenumTestClass_byte_enum_to_short_rtime_s_SrcEnumType Source = ExpenumTestClass_byte_enum_to_short_rtime_s_SrcEnumType.ValOne; Destination = (short)Source; if (Destination == 1) return true; else return false; } } enum ExpenumTestClass_byte_enum_to_uint_rtime_s_SrcEnumType : byte { ValOne = 1 } public class ExpenumTestClass_byte_enum_to_uint_rtime_s { public static bool testMethod() { uint Destination; ExpenumTestClass_byte_enum_to_uint_rtime_s_SrcEnumType Source = ExpenumTestClass_byte_enum_to_uint_rtime_s_SrcEnumType.ValOne; Destination = (uint)Source; if (Destination == 1) return true; else return false; } } enum ExpenumTestClass_byte_enum_to_ulong_rtime_s_SrcEnumType : byte { ValOne = 1 } public class ExpenumTestClass_byte_enum_to_ulong_rtime_s { public static bool testMethod() { ulong Destination; ExpenumTestClass_byte_enum_to_ulong_rtime_s_SrcEnumType Source = ExpenumTestClass_byte_enum_to_ulong_rtime_s_SrcEnumType.ValOne; Destination = (ulong)Source; if (Destination == 1) return true; else return false; } } enum ExpenumTestClass_byte_enum_to_ushort_rtime_s_SrcEnumType : byte { ValOne = 1 } public class ExpenumTestClass_byte_enum_to_ushort_rtime_s { public static bool testMethod() { ushort Destination; ExpenumTestClass_byte_enum_to_ushort_rtime_s_SrcEnumType Source = ExpenumTestClass_byte_enum_to_ushort_rtime_s_SrcEnumType.ValOne; Destination = (ushort)Source; if (Destination == 1) return true; else return false; } } enum ExpenumTestClass_int_enum_to_byte_rtime_s_SrcEnumType : int { ValOne = 1 } public class ExpenumTestClass_int_enum_to_byte_rtime_s { public static bool testMethod() { byte Destination; ExpenumTestClass_int_enum_to_byte_rtime_s_SrcEnumType Source = ExpenumTestClass_int_enum_to_byte_rtime_s_SrcEnumType.ValOne; Destination = (byte)Source; if (Destination == 1) return true; else return false; } } enum ExpenumTestClass_int_enum_to_double_rtime_s_SrcEnumType : int { ValOne = 1 } public class ExpenumTestClass_int_enum_to_double_rtime_s { public static bool testMethod() { double Destination; ExpenumTestClass_int_enum_to_double_rtime_s_SrcEnumType Source = ExpenumTestClass_int_enum_to_double_rtime_s_SrcEnumType.ValOne; Destination = (double)Source; if (Destination == 1) return true; else return false; } } //////enum ExpenumTestClass_int_enum_to_float_rtime_s_SrcEnumType : int { ValOne = 1 } //////public class ExpenumTestClass_int_enum_to_float_rtime_s //////{ ////// public static bool testMethod() ////// { ////// float Destination; ////// ExpenumTestClass_int_enum_to_float_rtime_s_SrcEnumType Source = ExpenumTestClass_int_enum_to_float_rtime_s_SrcEnumType.ValOne; ////// Destination = (float)Source; ////// if (Destination == 1) ////// return true; ////// else ////// return false; ////// } //////} enum ExpenumTestClass_int_enum_to_int_rtime_s_SrcEnumType : int { ValOne = 1 } public class ExpenumTestClass_int_enum_to_int_rtime_s { public static bool testMethod() { int Destination; ExpenumTestClass_int_enum_to_int_rtime_s_SrcEnumType Source = ExpenumTestClass_int_enum_to_int_rtime_s_SrcEnumType.ValOne; Destination = (int)Source; if (Destination == 1) return true; else return false; } } enum ExpenumTestClass_int_enum_to_long_rtime_s_SrcEnumType : int { ValOne = 1 } public class ExpenumTestClass_int_enum_to_long_rtime_s { public static bool testMethod() { long Destination; ExpenumTestClass_int_enum_to_long_rtime_s_SrcEnumType Source = ExpenumTestClass_int_enum_to_long_rtime_s_SrcEnumType.ValOne; Destination = (long)Source; if (Destination == 1) return true; else return false; } } enum ExpenumTestClass_int_enum_to_sbyte_rtime_s_SrcEnumType : int { ValOne = 1 } public class ExpenumTestClass_int_enum_to_sbyte_rtime_s { public static bool testMethod() { sbyte Destination; ExpenumTestClass_int_enum_to_sbyte_rtime_s_SrcEnumType Source = ExpenumTestClass_int_enum_to_sbyte_rtime_s_SrcEnumType.ValOne; Destination = (sbyte)Source; if (Destination == 1) return true; else return false; } } enum ExpenumTestClass_int_enum_to_short_rtime_s_SrcEnumType : int { ValOne = 1 } public class ExpenumTestClass_int_enum_to_short_rtime_s { public static bool testMethod() { short Destination; ExpenumTestClass_int_enum_to_short_rtime_s_SrcEnumType Source = ExpenumTestClass_int_enum_to_short_rtime_s_SrcEnumType.ValOne; Destination = (short)Source; if (Destination == 1) return true; else return false; } } enum ExpenumTestClass_int_enum_to_uint_rtime_s_SrcEnumType : int { ValOne = 1 } public class ExpenumTestClass_int_enum_to_uint_rtime_s { public static bool testMethod() { uint Destination; ExpenumTestClass_int_enum_to_uint_rtime_s_SrcEnumType Source = ExpenumTestClass_int_enum_to_uint_rtime_s_SrcEnumType.ValOne; Destination = (uint)Source; if (Destination == 1) return true; else return false; } } enum ExpenumTestClass_int_enum_to_ulong_rtime_s_SrcEnumType : int { ValOne = 1 } public class ExpenumTestClass_int_enum_to_ulong_rtime_s { public static bool testMethod() { ulong Destination; ExpenumTestClass_int_enum_to_ulong_rtime_s_SrcEnumType Source = ExpenumTestClass_int_enum_to_ulong_rtime_s_SrcEnumType.ValOne; Destination = (ulong)Source; if (Destination == 1) return true; else return false; } } enum ExpenumTestClass_int_enum_to_ulong_enum_rtime_s_DestEnumType : ulong { ValOne = 1 } enum ExpenumTestClass_int_enum_to_ulong_enum_rtime_s_SrcEnumType : int { ValOne = 1 } public class ExpenumTestClass_int_enum_to_ulong_enum_rtime_s { public static bool testMethod() { ExpenumTestClass_int_enum_to_ulong_enum_rtime_s_DestEnumType Destination; ExpenumTestClass_int_enum_to_ulong_enum_rtime_s_SrcEnumType Source = ExpenumTestClass_int_enum_to_ulong_enum_rtime_s_SrcEnumType.ValOne; Destination = (ExpenumTestClass_int_enum_to_ulong_enum_rtime_s_DestEnumType)Source; if (Destination == ExpenumTestClass_int_enum_to_ulong_enum_rtime_s_DestEnumType.ValOne) return true; else return false; } } enum ExpenumTestClass_int_enum_to_ushort_enum_rtime_s_DestEnumType : ushort { ValOne = 1 } enum ExpenumTestClass_int_enum_to_ushort_enum_rtime_s_SrcEnumType : int { ValOne = 1 } public class ExpenumTestClass_int_enum_to_ushort_enum_rtime_s { public static bool testMethod() { ExpenumTestClass_int_enum_to_ushort_enum_rtime_s_DestEnumType Destination; ExpenumTestClass_int_enum_to_ushort_enum_rtime_s_SrcEnumType Source = ExpenumTestClass_int_enum_to_ushort_enum_rtime_s_SrcEnumType.ValOne; Destination = (ExpenumTestClass_int_enum_to_ushort_enum_rtime_s_DestEnumType)Source; if (Destination == ExpenumTestClass_int_enum_to_ushort_enum_rtime_s_DestEnumType.ValOne) return true; else return false; } } enum ExpenumTestClass_long_enum_to_byte_enum_rtime_s_DestEnumType : byte { ValOne = 1 } enum ExpenumTestClass_long_enum_to_byte_enum_rtime_s_SrcEnumType : long { ValOne = 1 } public class ExpenumTestClass_long_enum_to_byte_enum_rtime_s { public static bool testMethod() { ExpenumTestClass_long_enum_to_byte_enum_rtime_s_DestEnumType Destination; ExpenumTestClass_long_enum_to_byte_enum_rtime_s_SrcEnumType Source = ExpenumTestClass_long_enum_to_byte_enum_rtime_s_SrcEnumType.ValOne; Destination = (ExpenumTestClass_long_enum_to_byte_enum_rtime_s_DestEnumType)Source; if (Destination == ExpenumTestClass_long_enum_to_byte_enum_rtime_s_DestEnumType.ValOne) return true; else return false; } } enum ExpenumTestClass_long_enum_to_int_enum_rtime_s_DestEnumType : int { ValOne = 1 } enum ExpenumTestClass_long_enum_to_int_enum_rtime_s_SrcEnumType : long { ValOne = 1 } public class ExpenumTestClass_long_enum_to_int_enum_rtime_s { public static bool testMethod() { ExpenumTestClass_long_enum_to_int_enum_rtime_s_DestEnumType Destination; ExpenumTestClass_long_enum_to_int_enum_rtime_s_SrcEnumType Source = ExpenumTestClass_long_enum_to_int_enum_rtime_s_SrcEnumType.ValOne; Destination = (ExpenumTestClass_long_enum_to_int_enum_rtime_s_DestEnumType)Source; if (Destination == ExpenumTestClass_long_enum_to_int_enum_rtime_s_DestEnumType.ValOne) return true; else return false; } } enum ExpenumTestClass_long_enum_to_long_enum_rtime_s_DestEnumType : long { ValOne = 1 } enum ExpenumTestClass_long_enum_to_long_enum_rtime_s_SrcEnumType : long { ValOne = 1 } public class ExpenumTestClass_long_enum_to_long_enum_rtime_s { public static bool testMethod() { ExpenumTestClass_long_enum_to_long_enum_rtime_s_DestEnumType Destination; ExpenumTestClass_long_enum_to_long_enum_rtime_s_SrcEnumType Source = ExpenumTestClass_long_enum_to_long_enum_rtime_s_SrcEnumType.ValOne; Destination = (ExpenumTestClass_long_enum_to_long_enum_rtime_s_DestEnumType)Source; if (Destination == ExpenumTestClass_long_enum_to_long_enum_rtime_s_DestEnumType.ValOne) return true; else return false; } } enum ExpenumTestClass_long_enum_to_sbyte_enum_rtime_s_DestEnumType : sbyte { ValOne = 1 } enum ExpenumTestClass_long_enum_to_sbyte_enum_rtime_s_SrcEnumType : long { ValOne = 1 } public class ExpenumTestClass_long_enum_to_sbyte_enum_rtime_s { public static bool testMethod() { ExpenumTestClass_long_enum_to_sbyte_enum_rtime_s_DestEnumType Destination; ExpenumTestClass_long_enum_to_sbyte_enum_rtime_s_SrcEnumType Source = ExpenumTestClass_long_enum_to_sbyte_enum_rtime_s_SrcEnumType.ValOne; Destination = (ExpenumTestClass_long_enum_to_sbyte_enum_rtime_s_DestEnumType)Source; if (Destination == ExpenumTestClass_long_enum_to_sbyte_enum_rtime_s_DestEnumType.ValOne) return true; else return false; } } enum ExpenumTestClass_long_enum_to_short_enum_rtime_s_DestEnumType : short { ValOne = 1 } enum ExpenumTestClass_long_enum_to_short_enum_rtime_s_SrcEnumType : long { ValOne = 1 } public class ExpenumTestClass_long_enum_to_short_enum_rtime_s { public static bool testMethod() { ExpenumTestClass_long_enum_to_short_enum_rtime_s_DestEnumType Destination; ExpenumTestClass_long_enum_to_short_enum_rtime_s_SrcEnumType Source = ExpenumTestClass_long_enum_to_short_enum_rtime_s_SrcEnumType.ValOne; Destination = (ExpenumTestClass_long_enum_to_short_enum_rtime_s_DestEnumType)Source; if (Destination == ExpenumTestClass_long_enum_to_short_enum_rtime_s_DestEnumType.ValOne) return true; else return false; } } enum ExpenumTestClass_long_enum_to_uint_enum_rtime_s_DestEnumType : uint { ValOne = 1 } enum ExpenumTestClass_long_enum_to_uint_enum_rtime_s_SrcEnumType : long { ValOne = 1 } public class ExpenumTestClass_long_enum_to_uint_enum_rtime_s { public static bool testMethod() { ExpenumTestClass_long_enum_to_uint_enum_rtime_s_DestEnumType Destination; ExpenumTestClass_long_enum_to_uint_enum_rtime_s_SrcEnumType Source = ExpenumTestClass_long_enum_to_uint_enum_rtime_s_SrcEnumType.ValOne; Destination = (ExpenumTestClass_long_enum_to_uint_enum_rtime_s_DestEnumType)Source; if (Destination == ExpenumTestClass_long_enum_to_uint_enum_rtime_s_DestEnumType.ValOne) return true; else return false; } } enum ExpenumTestClass_long_enum_to_ulong_enum_rtime_s_DestEnumType : ulong { ValOne = 1 } enum ExpenumTestClass_long_enum_to_ulong_enum_rtime_s_SrcEnumType : long { ValOne = 1 } public class ExpenumTestClass_long_enum_to_ulong_enum_rtime_s { public static bool testMethod() { ExpenumTestClass_long_enum_to_ulong_enum_rtime_s_DestEnumType Destination; ExpenumTestClass_long_enum_to_ulong_enum_rtime_s_SrcEnumType Source = ExpenumTestClass_long_enum_to_ulong_enum_rtime_s_SrcEnumType.ValOne; Destination = (ExpenumTestClass_long_enum_to_ulong_enum_rtime_s_DestEnumType)Source; if (Destination == ExpenumTestClass_long_enum_to_ulong_enum_rtime_s_DestEnumType.ValOne) return true; else return false; } } enum ExpenumTestClass_long_enum_to_ushort_enum_rtime_s_DestEnumType : ushort { ValOne = 1 } enum ExpenumTestClass_long_enum_to_ushort_enum_rtime_s_SrcEnumType : long { ValOne = 1 } public class ExpenumTestClass_long_enum_to_ushort_enum_rtime_s { public static bool testMethod() { ExpenumTestClass_long_enum_to_ushort_enum_rtime_s_DestEnumType Destination; ExpenumTestClass_long_enum_to_ushort_enum_rtime_s_SrcEnumType Source = ExpenumTestClass_long_enum_to_ushort_enum_rtime_s_SrcEnumType.ValOne; Destination = (ExpenumTestClass_long_enum_to_ushort_enum_rtime_s_DestEnumType)Source; if (Destination == ExpenumTestClass_long_enum_to_ushort_enum_rtime_s_DestEnumType.ValOne) return true; else return false; } } enum ExpenumTestClass_sbyte_enum_to_byte_enum_rtime_s_DestEnumType : byte { ValOne = 1 } enum ExpenumTestClass_sbyte_enum_to_byte_enum_rtime_s_SrcEnumType : sbyte { ValOne = 1 } public class ExpenumTestClass_sbyte_enum_to_byte_enum_rtime_s { public static bool testMethod() { ExpenumTestClass_sbyte_enum_to_byte_enum_rtime_s_DestEnumType Destination; ExpenumTestClass_sbyte_enum_to_byte_enum_rtime_s_SrcEnumType Source = ExpenumTestClass_sbyte_enum_to_byte_enum_rtime_s_SrcEnumType.ValOne; Destination = (ExpenumTestClass_sbyte_enum_to_byte_enum_rtime_s_DestEnumType)Source; if (Destination == ExpenumTestClass_sbyte_enum_to_byte_enum_rtime_s_DestEnumType.ValOne) return true; else return false; } } enum ExpenumTestClass_sbyte_enum_to_int_enum_rtime_s_DestEnumType : int { ValOne = 1 } enum ExpenumTestClass_sbyte_enum_to_int_enum_rtime_s_SrcEnumType : sbyte { ValOne = 1 } public class ExpenumTestClass_sbyte_enum_to_int_enum_rtime_s { public static bool testMethod() { ExpenumTestClass_sbyte_enum_to_int_enum_rtime_s_DestEnumType Destination; ExpenumTestClass_sbyte_enum_to_int_enum_rtime_s_SrcEnumType Source = ExpenumTestClass_sbyte_enum_to_int_enum_rtime_s_SrcEnumType.ValOne; Destination = (ExpenumTestClass_sbyte_enum_to_int_enum_rtime_s_DestEnumType)Source; if (Destination == ExpenumTestClass_sbyte_enum_to_int_enum_rtime_s_DestEnumType.ValOne) return true; else return false; } } enum ExpenumTestClass_sbyte_enum_to_long_enum_rtime_s_DestEnumType : long { ValOne = 1 } enum ExpenumTestClass_sbyte_enum_to_long_enum_rtime_s_SrcEnumType : sbyte { ValOne = 1 } public class ExpenumTestClass_sbyte_enum_to_long_enum_rtime_s { public static bool testMethod() { ExpenumTestClass_sbyte_enum_to_long_enum_rtime_s_DestEnumType Destination; ExpenumTestClass_sbyte_enum_to_long_enum_rtime_s_SrcEnumType Source = ExpenumTestClass_sbyte_enum_to_long_enum_rtime_s_SrcEnumType.ValOne; Destination = (ExpenumTestClass_sbyte_enum_to_long_enum_rtime_s_DestEnumType)Source; if (Destination == ExpenumTestClass_sbyte_enum_to_long_enum_rtime_s_DestEnumType.ValOne) return true; else return false; } } enum ExpenumTestClass_sbyte_enum_to_sbyte_enum_rtime_s_DestEnumType : sbyte { ValOne = 1 } enum ExpenumTestClass_sbyte_enum_to_sbyte_enum_rtime_s_SrcEnumType : sbyte { ValOne = 1 } public class ExpenumTestClass_sbyte_enum_to_sbyte_enum_rtime_s { public static bool testMethod() { ExpenumTestClass_sbyte_enum_to_sbyte_enum_rtime_s_DestEnumType Destination; ExpenumTestClass_sbyte_enum_to_sbyte_enum_rtime_s_SrcEnumType Source = ExpenumTestClass_sbyte_enum_to_sbyte_enum_rtime_s_SrcEnumType.ValOne; Destination = (ExpenumTestClass_sbyte_enum_to_sbyte_enum_rtime_s_DestEnumType)Source; if (Destination == ExpenumTestClass_sbyte_enum_to_sbyte_enum_rtime_s_DestEnumType.ValOne) return true; else return false; } } enum ExpenumTestClass_sbyte_enum_to_short_enum_rtime_s_DestEnumType : short { ValOne = 1 } enum ExpenumTestClass_sbyte_enum_to_short_enum_rtime_s_SrcEnumType : sbyte { ValOne = 1 } public class ExpenumTestClass_sbyte_enum_to_short_enum_rtime_s { public static bool testMethod() { ExpenumTestClass_sbyte_enum_to_short_enum_rtime_s_DestEnumType Destination; ExpenumTestClass_sbyte_enum_to_short_enum_rtime_s_SrcEnumType Source = ExpenumTestClass_sbyte_enum_to_short_enum_rtime_s_SrcEnumType.ValOne; Destination = (ExpenumTestClass_sbyte_enum_to_short_enum_rtime_s_DestEnumType)Source; if (Destination == ExpenumTestClass_sbyte_enum_to_short_enum_rtime_s_DestEnumType.ValOne) return true; else return false; } } enum ExpenumTestClass_sbyte_enum_to_uint_enum_rtime_s_DestEnumType : uint { ValOne = 1 } enum ExpenumTestClass_sbyte_enum_to_uint_enum_rtime_s_SrcEnumType : sbyte { ValOne = 1 } public class ExpenumTestClass_sbyte_enum_to_uint_enum_rtime_s { public static bool testMethod() { ExpenumTestClass_sbyte_enum_to_uint_enum_rtime_s_DestEnumType Destination; ExpenumTestClass_sbyte_enum_to_uint_enum_rtime_s_SrcEnumType Source = ExpenumTestClass_sbyte_enum_to_uint_enum_rtime_s_SrcEnumType.ValOne; Destination = (ExpenumTestClass_sbyte_enum_to_uint_enum_rtime_s_DestEnumType)Source; if (Destination == ExpenumTestClass_sbyte_enum_to_uint_enum_rtime_s_DestEnumType.ValOne) return true; else return false; } } enum ExpenumTestClass_byte_enum_to_ulong_enum_rtime_s_DestEnumType : ulong { ValOne = 1 } enum ExpenumTestClass_byte_enum_to_ulong_enum_rtime_s_SrcEnumType : byte { ValOne = 1 } public class ExpenumTestClass_byte_enum_to_ulong_enum_rtime_s { public static bool testMethod() { ExpenumTestClass_byte_enum_to_ulong_enum_rtime_s_DestEnumType Destination; ExpenumTestClass_byte_enum_to_ulong_enum_rtime_s_SrcEnumType Source = ExpenumTestClass_byte_enum_to_ulong_enum_rtime_s_SrcEnumType.ValOne; Destination = (ExpenumTestClass_byte_enum_to_ulong_enum_rtime_s_DestEnumType)Source; if (Destination == ExpenumTestClass_byte_enum_to_ulong_enum_rtime_s_DestEnumType.ValOne) return true; else return false; } } enum ExpenumTestClass_byte_enum_to_ushort_enum_rtime_s_DestEnumType : ushort { ValOne = 1 } enum ExpenumTestClass_byte_enum_to_ushort_enum_rtime_s_SrcEnumType : byte { ValOne = 1 } public class ExpenumTestClass_byte_enum_to_ushort_enum_rtime_s { public static bool testMethod() { ExpenumTestClass_byte_enum_to_ushort_enum_rtime_s_DestEnumType Destination; ExpenumTestClass_byte_enum_to_ushort_enum_rtime_s_SrcEnumType Source = ExpenumTestClass_byte_enum_to_ushort_enum_rtime_s_SrcEnumType.ValOne; Destination = (ExpenumTestClass_byte_enum_to_ushort_enum_rtime_s_DestEnumType)Source; if (Destination == ExpenumTestClass_byte_enum_to_ushort_enum_rtime_s_DestEnumType.ValOne) return true; else return false; } } enum ExpenumTestClass_int_enum_to_byte_enum_rtime_s_DestEnumType : byte { ValOne = 1 } enum ExpenumTestClass_int_enum_to_byte_enum_rtime_s_SrcEnumType : int { ValOne = 1 } public class ExpenumTestClass_int_enum_to_byte_enum_rtime_s { public static bool testMethod() { ExpenumTestClass_int_enum_to_byte_enum_rtime_s_DestEnumType Destination; ExpenumTestClass_int_enum_to_byte_enum_rtime_s_SrcEnumType Source = ExpenumTestClass_int_enum_to_byte_enum_rtime_s_SrcEnumType.ValOne; Destination = (ExpenumTestClass_int_enum_to_byte_enum_rtime_s_DestEnumType)Source; if (Destination == ExpenumTestClass_int_enum_to_byte_enum_rtime_s_DestEnumType.ValOne) return true; else return false; } } enum ExpenumTestClass_int_enum_to_int_enum_rtime_s_DestEnumType : int { ValOne = 1 } enum ExpenumTestClass_int_enum_to_int_enum_rtime_s_SrcEnumType : int { ValOne = 1 } public class ExpenumTestClass_int_enum_to_int_enum_rtime_s { public static bool testMethod() { ExpenumTestClass_int_enum_to_int_enum_rtime_s_DestEnumType Destination; ExpenumTestClass_int_enum_to_int_enum_rtime_s_SrcEnumType Source = ExpenumTestClass_int_enum_to_int_enum_rtime_s_SrcEnumType.ValOne; Destination = (ExpenumTestClass_int_enum_to_int_enum_rtime_s_DestEnumType)Source; if (Destination == ExpenumTestClass_int_enum_to_int_enum_rtime_s_DestEnumType.ValOne) return true; else return false; } } enum ExpenumTestClass_int_enum_to_long_enum_rtime_s_DestEnumType : long { ValOne = 1 } enum ExpenumTestClass_int_enum_to_long_enum_rtime_s_SrcEnumType : int { ValOne = 1 } public class ExpenumTestClass_int_enum_to_long_enum_rtime_s { public static bool testMethod() { ExpenumTestClass_int_enum_to_long_enum_rtime_s_DestEnumType Destination; ExpenumTestClass_int_enum_to_long_enum_rtime_s_SrcEnumType Source = ExpenumTestClass_int_enum_to_long_enum_rtime_s_SrcEnumType.ValOne; Destination = (ExpenumTestClass_int_enum_to_long_enum_rtime_s_DestEnumType)Source; if (Destination == ExpenumTestClass_int_enum_to_long_enum_rtime_s_DestEnumType.ValOne) return true; else return false; } } enum ExpenumTestClass_int_enum_to_sbyte_enum_rtime_s_DestEnumType : sbyte { ValOne = 1 } enum ExpenumTestClass_int_enum_to_sbyte_enum_rtime_s_SrcEnumType : int { ValOne = 1 } public class ExpenumTestClass_int_enum_to_sbyte_enum_rtime_s { public static bool testMethod() { ExpenumTestClass_int_enum_to_sbyte_enum_rtime_s_DestEnumType Destination; ExpenumTestClass_int_enum_to_sbyte_enum_rtime_s_SrcEnumType Source = ExpenumTestClass_int_enum_to_sbyte_enum_rtime_s_SrcEnumType.ValOne; Destination = (ExpenumTestClass_int_enum_to_sbyte_enum_rtime_s_DestEnumType)Source; if (Destination == ExpenumTestClass_int_enum_to_sbyte_enum_rtime_s_DestEnumType.ValOne) return true; else return false; } } enum ExpenumTestClass_int_enum_to_short_enum_rtime_s_DestEnumType : short { ValOne = 1 } enum ExpenumTestClass_int_enum_to_short_enum_rtime_s_SrcEnumType : int { ValOne = 1 } public class ExpenumTestClass_int_enum_to_short_enum_rtime_s { public static bool testMethod() { ExpenumTestClass_int_enum_to_short_enum_rtime_s_DestEnumType Destination; ExpenumTestClass_int_enum_to_short_enum_rtime_s_SrcEnumType Source = ExpenumTestClass_int_enum_to_short_enum_rtime_s_SrcEnumType.ValOne; Destination = (ExpenumTestClass_int_enum_to_short_enum_rtime_s_DestEnumType)Source; if (Destination == ExpenumTestClass_int_enum_to_short_enum_rtime_s_DestEnumType.ValOne) return true; else return false; } } enum ExpenumTestClass_int_enum_to_uint_enum_rtime_s_DestEnumType : uint { ValOne = 1 } enum ExpenumTestClass_int_enum_to_uint_enum_rtime_s_SrcEnumType : int { ValOne = 1 } public class ExpenumTestClass_int_enum_to_uint_enum_rtime_s { public static bool testMethod() { ExpenumTestClass_int_enum_to_uint_enum_rtime_s_DestEnumType Destination; ExpenumTestClass_int_enum_to_uint_enum_rtime_s_SrcEnumType Source = ExpenumTestClass_int_enum_to_uint_enum_rtime_s_SrcEnumType.ValOne; Destination = (ExpenumTestClass_int_enum_to_uint_enum_rtime_s_DestEnumType)Source; if (Destination == ExpenumTestClass_int_enum_to_uint_enum_rtime_s_DestEnumType.ValOne) return true; else return false; } } } } ================================================ FILE: Zelig/Zelig/Test/RunTime/NETMF/mscorlib/conversions/expenum2/Expenum3Tests.cs ================================================ //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // Copyright (c) Microsoft Corporation. All rights reserved. //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// using System; namespace Microsoft.Zelig.Test { public class Expenum3Tests : TestBase, ITestInterface { [SetUp] public InitializeResult Initialize() { Log.Comment("Adding set up for the tests."); // Add your functionality here. return InitializeResult.ReadyToGo; } [TearDown] public void CleanUp() { Log.Comment("Cleaning up after the tests"); } public override TestResult Run( string[] args ) { TestResult result = TestResult.Pass; string testName = "Expenum3_"; int testNumber = 0; result |= Assert.CheckFailed( Expenum_sbyte_enum_to_ulong_enum_rtime_s_Test( ), testName, ++testNumber ); result |= Assert.CheckFailed( Expenum_sbyte_enum_to_ushort_enum_rtime_s_Test( ), testName, ++testNumber ); result |= Assert.CheckFailed( Expenum_short_enum_to_byte_enum_rtime_s_Test( ), testName, ++testNumber ); result |= Assert.CheckFailed( Expenum_short_enum_to_int_enum_rtime_s_Test( ), testName, ++testNumber ); result |= Assert.CheckFailed( Expenum_short_enum_to_long_enum_rtime_s_Test( ), testName, ++testNumber ); result |= Assert.CheckFailed( Expenum_short_enum_to_sbyte_enum_rtime_s_Test( ), testName, ++testNumber ); result |= Assert.CheckFailed( Expenum_short_enum_to_short_enum_rtime_s_Test( ), testName, ++testNumber ); result |= Assert.CheckFailed( Expenum_short_enum_to_uint_enum_rtime_s_Test( ), testName, ++testNumber ); result |= Assert.CheckFailed( Expenum_short_enum_to_ulong_enum_rtime_s_Test( ), testName, ++testNumber ); result |= Assert.CheckFailed( Expenum_short_enum_to_ushort_enum_rtime_s_Test( ), testName, ++testNumber ); result |= Assert.CheckFailed( Expenum_uint_enum_to_byte_enum_rtime_s_Test( ), testName, ++testNumber ); result |= Assert.CheckFailed( Expenum_uint_enum_to_int_enum_rtime_s_Test( ), testName, ++testNumber ); result |= Assert.CheckFailed( Expenum_uint_enum_to_long_enum_rtime_s_Test( ), testName, ++testNumber ); result |= Assert.CheckFailed( Expenum_uint_enum_to_sbyte_enum_rtime_s_Test( ), testName, ++testNumber ); result |= Assert.CheckFailed( Expenum_uint_enum_to_short_enum_rtime_s_Test( ), testName, ++testNumber ); result |= Assert.CheckFailed( Expenum_uint_enum_to_uint_enum_rtime_s_Test( ), testName, ++testNumber ); result |= Assert.CheckFailed( Expenum_uint_enum_to_ulong_enum_rtime_s_Test( ), testName, ++testNumber ); result |= Assert.CheckFailed( Expenum_uint_enum_to_ushort_enum_rtime_s_Test( ), testName, ++testNumber ); result |= Assert.CheckFailed( Expenum_ulong_enum_to_byte_enum_rtime_s_Test( ), testName, ++testNumber ); result |= Assert.CheckFailed( Expenum_ulong_enum_to_int_enum_rtime_s_Test( ), testName, ++testNumber ); result |= Assert.CheckFailed( Expenum_ulong_enum_to_long_enum_rtime_s_Test( ), testName, ++testNumber ); result |= Assert.CheckFailed( Expenum_ulong_enum_to_sbyte_enum_rtime_s_Test( ), testName, ++testNumber ); result |= Assert.CheckFailed( Expenum_ulong_enum_to_short_enum_rtime_s_Test( ), testName, ++testNumber ); result |= Assert.CheckFailed( Expenum_ulong_enum_to_uint_enum_rtime_s_Test( ), testName, ++testNumber ); result |= Assert.CheckFailed( Expenum_ulong_enum_to_ulong_enum_rtime_s_Test( ), testName, ++testNumber ); result |= Assert.CheckFailed( Expenum_ulong_enum_to_ushort_enum_rtime_s_Test( ), testName, ++testNumber ); result |= Assert.CheckFailed( Expenum_ushort_enum_to_byte_enum_rtime_s_Test( ), testName, ++testNumber ); result |= Assert.CheckFailed( Expenum_ushort_enum_to_int_enum_rtime_s_Test( ), testName, ++testNumber ); result |= Assert.CheckFailed( Expenum_ushort_enum_to_long_enum_rtime_s_Test( ), testName, ++testNumber ); result |= Assert.CheckFailed( Expenum_ushort_enum_to_sbyte_enum_rtime_s_Test( ), testName, ++testNumber ); result |= Assert.CheckFailed( Expenum_ushort_enum_to_short_enum_rtime_s_Test( ), testName, ++testNumber ); result |= Assert.CheckFailed( Expenum_ushort_enum_to_uint_enum_rtime_s_Test( ), testName, ++testNumber ); result |= Assert.CheckFailed( Expenum_ushort_enum_to_ulong_enum_rtime_s_Test( ), testName, ++testNumber ); result |= Assert.CheckFailed( Expenum_ushort_enum_to_ushort_enum_rtime_s_Test( ), testName, ++testNumber ); result |= Assert.CheckFailed( Expenum_byte_enum_to_byte_enum_rtime_s_Test( ), testName, ++testNumber ); result |= Assert.CheckFailed( Expenum_byte_enum_to_int_enum_rtime_s_Test( ), testName, ++testNumber ); result |= Assert.CheckFailed( Expenum_byte_enum_to_long_enum_rtime_s_Test( ), testName, ++testNumber ); result |= Assert.CheckFailed( Expenum_byte_enum_to_sbyte_enum_rtime_s_Test( ), testName, ++testNumber ); result |= Assert.CheckFailed( Expenum_byte_enum_to_short_enum_rtime_s_Test( ), testName, ++testNumber ); result |= Assert.CheckFailed( Expenum_byte_enum_to_uint_enum_rtime_s_Test( ), testName, ++testNumber ); return result; } //Expenum Test methods //The following tests were ported from folder current\test\cases\client\CLR\Conformance\10_classes\Expenum //byte_to_byte_enum_rtime_s,byte_to_int_enum_rtime_s,byte_to_long_enum_rtime_s,byte_to_sbyte_enum_rtime_s, //byte_to_short_enum_rtime_s,byte_to_uint_enum_rtime_s,byte_to_ulong_enum_rtime_s,byte_to_ushort_enum_rtime_s, //double_to_byte_enum_rtime_s,double_to_int_enum_rtime_s,double_to_long_enum_rtime_s,double_to_sbyte_enum_rtime_s, //double_to_short_enum_rtime_s,double_to_uint_enum_rtime_s,double_to_ulong_enum_rtime_s, //double_to_ushort_enum_rtime_s,float_to_byte_enum_rtime_s,float_to_int_enum_rtime_s,float_to_long_enum_rtime_s, //float_to_sbyte_enum_rtime_s,float_to_short_enum_rtime_s,float_to_uint_enum_rtime_s,float_to_ulong_enum_rtime_s, //float_to_ushort_enum_rtime_s,short_enum_to_float_rtime_s,short_enum_to_int_rtime_s,int_to_byte_enum_rtime_s, //int_to_int_enum_rtime_s,int_to_long_enum_rtime_s,int_to_sbyte_enum_rtime_s,int_to_short_enum_rtime_s, //int_to_uint_enum_rtime_s,int_to_ulong_enum_rtime_s,int_to_ushort_enum_rtime_s,long_to_byte_enum_rtime_s, //long_to_int_enum_rtime_s,long_to_long_enum_rtime_s,long_to_sbyte_enum_rtime_s,long_to_short_enum_rtime_s, //long_to_uint_enum_rtime_s,long_to_ulong_enum_rtime_s,long_to_ushort_enum_rtime_s,sbyte_to_byte_enum_rtime_s, //sbyte_to_int_enum_rtime_s,sbyte_to_long_enum_rtime_s,sbyte_to_sbyte_enum_rtime_s,sbyte_to_short_enum_rtime_s, //sbyte_to_uint_enum_rtime_s,sbyte_to_ulong_enum_rtime_s,sbyte_to_ushort_enum_rtime_s,short_to_byte_enum_rtime_s, //short_to_int_enum_rtime_s,short_to_long_enum_rtime_s,short_to_sbyte_enum_rtime_s,short_to_short_enum_rtime_s, //short_to_uint_enum_rtime_s,short_to_ulong_enum_rtime_s,short_to_ushort_enum_rtime_s,uint_to_byte_enum_rtime_s, //uint_to_int_enum_rtime_s,uint_to_long_enum_rtime_s,uint_to_sbyte_enum_rtime_s,uint_to_short_enum_rtime_s, //uint_to_uint_enum_rtime_s,uint_to_ulong_enum_rtime_s,uint_to_ushort_enum_rtime_s,ulong_to_byte_enum_rtime_s, //ulong_to_int_enum_rtime_s,ulong_to_long_enum_rtime_s,ulong_to_sbyte_enum_rtime_s,ulong_to_short_enum_rtime_s, //ulong_to_uint_enum_rtime_s,ulong_to_ulong_enum_rtime_s,ulong_to_ushort_enum_rtime_s,ushort_to_byte_enum_rtime_s, //ushort_to_int_enum_rtime_s,ushort_to_long_enum_rtime_s,ushort_to_sbyte_enum_rtime_s,ushort_to_short_enum_rtime_s, //ushort_to_uint_enum_rtime_s,ushort_to_ulong_enum_rtime_s,ushort_to_ushort_enum_rtime_s,int_enum_to_ushort_rtime_s, //long_enum_to_byte_rtime_s,long_enum_to_double_rtime_s,long_enum_to_float_rtime_s,long_enum_to_int_rtime_s, //long_enum_to_long_rtime_s,long_enum_to_sbyte_rtime_s,long_enum_to_short_rtime_s,long_enum_to_uint_rtime_s, //long_enum_to_ulong_rtime_s,long_enum_to_ushort_rtime_s,sbyte_enum_to_byte_rtime_s,sbyte_enum_to_double_rtime_s, //sbyte_enum_to_float_rtime_s,sbyte_enum_to_int_rtime_s,sbyte_enum_to_long_rtime_s,sbyte_enum_to_sbyte_rtime_s, //sbyte_enum_to_short_rtime_s,sbyte_enum_to_uint_rtime_s,sbyte_enum_to_ulong_rtime_s,sbyte_enum_to_ushort_rtime_s, //short_enum_to_byte_rtime_s,short_enum_to_double_rtime_s,short_enum_to_long_rtime_s,short_enum_to_sbyte_rtime_s, //short_enum_to_short_rtime_s,short_enum_to_uint_rtime_s,short_enum_to_ulong_rtime_s,short_enum_to_ushort_rtime_s, //uint_enum_to_byte_rtime_s,uint_enum_to_double_rtime_s,uint_enum_to_float_rtime_s,uint_enum_to_int_rtime_s, //uint_enum_to_long_rtime_s,uint_enum_to_sbyte_rtime_s,uint_enum_to_short_rtime_s,uint_enum_to_uint_rtime_s, //uint_enum_to_ulong_rtime_s,uint_enum_to_ushort_rtime_s,ulong_enum_to_byte_rtime_s,ulong_enum_to_double_rtime_s, //ulong_enum_to_float_rtime_s,ulong_enum_to_int_rtime_s,ulong_enum_to_long_rtime_s,ulong_enum_to_sbyte_rtime_s, //ulong_enum_to_short_rtime_s,ulong_enum_to_uint_rtime_s,ulong_enum_to_ulong_rtime_s,ulong_enum_to_ushort_rtime_s, //ushort_enum_to_byte_rtime_s,ushort_enum_to_double_rtime_s,ushort_enum_to_float_rtime_s,ushort_enum_to_int_rtime_s, //ushort_enum_to_long_rtime_s,ushort_enum_to_sbyte_rtime_s,ushort_enum_to_short_rtime_s,ushort_enum_to_uint_rtime_s, //ushort_enum_to_ulong_rtime_s,ushort_enum_to_ushort_rtime_s,byte_enum_to_byte_rtime_s,byte_enum_to_double_rtime_s, //byte_enum_to_float_rtime_s,byte_enum_to_int_rtime_s,byte_enum_to_long_rtime_s,byte_enum_to_sbyte_rtime_s, //byte_enum_to_short_rtime_s,byte_enum_to_uint_rtime_s,byte_enum_to_ulong_rtime_s,byte_enum_to_ushort_rtime_s, //int_enum_to_byte_rtime_s,int_enum_to_double_rtime_s,int_enum_to_float_rtime_s,int_enum_to_int_rtime_s, //int_enum_to_long_rtime_s,int_enum_to_sbyte_rtime_s,int_enum_to_short_rtime_s,int_enum_to_uint_rtime_s, //int_enum_to_ulong_rtime_s,int_enum_to_ulong_enum_rtime_s,int_enum_to_ushort_enum_rtime_s,long_enum_to_byte_enum_rtime_s, //long_enum_to_int_enum_rtime_s,long_enum_to_long_enum_rtime_s,long_enum_to_sbyte_enum_rtime_s,long_enum_to_short_enum_rtime_s, //long_enum_to_uint_enum_rtime_s,long_enum_to_ulong_enum_rtime_s,long_enum_to_ushort_enum_rtime_s, //sbyte_enum_to_byte_enum_rtime_s,sbyte_enum_to_int_enum_rtime_s,sbyte_enum_to_long_enum_rtime_s,sbyte_enum_to_sbyte_enum_rtime_s, //sbyte_enum_to_short_enum_rtime_s,sbyte_enum_to_uint_enum_rtime_s,sbyte_enum_to_ulong_enum_rtime_s,sbyte_enum_to_ushort_enum_rtime_s, //short_enum_to_byte_enum_rtime_s,short_enum_to_int_enum_rtime_s,short_enum_to_long_enum_rtime_s,short_enum_to_sbyte_enum_rtime_s, //short_enum_to_short_enum_rtime_s,short_enum_to_uint_enum_rtime_s,short_enum_to_ulong_enum_rtime_s,short_enum_to_ushort_enum_rtime_s, //uint_enum_to_byte_enum_rtime_s,uint_enum_to_int_enum_rtime_s,uint_enum_to_long_enum_rtime_s,uint_enum_to_sbyte_enum_rtime_s, //uint_enum_to_short_enum_rtime_s,uint_enum_to_uint_enum_rtime_s,uint_enum_to_ulong_enum_rtime_s,uint_enum_to_ushort_enum_rtime_s, //ulong_enum_to_byte_enum_rtime_s,ulong_enum_to_int_enum_rtime_s,ulong_enum_to_long_enum_rtime_s,ulong_enum_to_sbyte_enum_rtime_s, //ulong_enum_to_short_enum_rtime_s,ulong_enum_to_uint_enum_rtime_s,ulong_enum_to_ulong_enum_rtime_s,ulong_enum_to_ushort_enum_rtime_s, //ushort_enum_to_byte_enum_rtime_s,ushort_enum_to_int_enum_rtime_s,ushort_enum_to_long_enum_rtime_s,ushort_enum_to_sbyte_enum_rtime_s, //ushort_enum_to_short_enum_rtime_s,ushort_enum_to_uint_enum_rtime_s,ushort_enum_to_ulong_enum_rtime_s,ushort_enum_to_ushort_enum_rtime_s, //byte_enum_to_byte_enum_rtime_s,byte_enum_to_int_enum_rtime_s,byte_enum_to_long_enum_rtime_s,byte_enum_to_sbyte_enum_rtime_s, //byte_enum_to_short_enum_rtime_s,byte_enum_to_uint_enum_rtime_s,byte_enum_to_ulong_enum_rtime_s,byte_enum_to_ushort_enum_rtime_s, //int_enum_to_byte_enum_rtime_s,int_enum_to_int_enum_rtime_s,int_enum_to_long_enum_rtime_s,int_enum_to_sbyte_enum_rtime_s //int_enum_to_short_enum_rtime_s,int_enum_to_uint_enum_rtime_s //Test Case Calls [TestMethod] public TestResult Expenum_sbyte_enum_to_ulong_enum_rtime_s_Test() { if (ExpenumTestClass_sbyte_enum_to_ulong_enum_rtime_s.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Expenum_sbyte_enum_to_ushort_enum_rtime_s_Test() { if (ExpenumTestClass_sbyte_enum_to_ushort_enum_rtime_s.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Expenum_short_enum_to_byte_enum_rtime_s_Test() { if (ExpenumTestClass_short_enum_to_byte_enum_rtime_s.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Expenum_short_enum_to_int_enum_rtime_s_Test() { if (ExpenumTestClass_short_enum_to_int_enum_rtime_s.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Expenum_short_enum_to_long_enum_rtime_s_Test() { if (ExpenumTestClass_short_enum_to_long_enum_rtime_s.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Expenum_short_enum_to_sbyte_enum_rtime_s_Test() { if (ExpenumTestClass_short_enum_to_sbyte_enum_rtime_s.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Expenum_short_enum_to_short_enum_rtime_s_Test() { if (ExpenumTestClass_short_enum_to_short_enum_rtime_s.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Expenum_short_enum_to_uint_enum_rtime_s_Test() { if (ExpenumTestClass_short_enum_to_uint_enum_rtime_s.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Expenum_short_enum_to_ulong_enum_rtime_s_Test() { if (ExpenumTestClass_short_enum_to_ulong_enum_rtime_s.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Expenum_short_enum_to_ushort_enum_rtime_s_Test() { if (ExpenumTestClass_short_enum_to_ushort_enum_rtime_s.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Expenum_uint_enum_to_byte_enum_rtime_s_Test() { if (ExpenumTestClass_uint_enum_to_byte_enum_rtime_s.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Expenum_uint_enum_to_int_enum_rtime_s_Test() { if (ExpenumTestClass_uint_enum_to_int_enum_rtime_s.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Expenum_uint_enum_to_long_enum_rtime_s_Test() { if (ExpenumTestClass_uint_enum_to_long_enum_rtime_s.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Expenum_uint_enum_to_sbyte_enum_rtime_s_Test() { if (ExpenumTestClass_uint_enum_to_sbyte_enum_rtime_s.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Expenum_uint_enum_to_short_enum_rtime_s_Test() { if (ExpenumTestClass_uint_enum_to_short_enum_rtime_s.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Expenum_uint_enum_to_uint_enum_rtime_s_Test() { if (ExpenumTestClass_uint_enum_to_uint_enum_rtime_s.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Expenum_uint_enum_to_ulong_enum_rtime_s_Test() { if (ExpenumTestClass_uint_enum_to_ulong_enum_rtime_s.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Expenum_uint_enum_to_ushort_enum_rtime_s_Test() { if (ExpenumTestClass_uint_enum_to_ushort_enum_rtime_s.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Expenum_ulong_enum_to_byte_enum_rtime_s_Test() { if (ExpenumTestClass_ulong_enum_to_byte_enum_rtime_s.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Expenum_ulong_enum_to_int_enum_rtime_s_Test() { if (ExpenumTestClass_ulong_enum_to_int_enum_rtime_s.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Expenum_ulong_enum_to_long_enum_rtime_s_Test() { if (ExpenumTestClass_ulong_enum_to_long_enum_rtime_s.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Expenum_ulong_enum_to_sbyte_enum_rtime_s_Test() { if (ExpenumTestClass_ulong_enum_to_sbyte_enum_rtime_s.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Expenum_ulong_enum_to_short_enum_rtime_s_Test() { if (ExpenumTestClass_ulong_enum_to_short_enum_rtime_s.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Expenum_ulong_enum_to_uint_enum_rtime_s_Test() { if (ExpenumTestClass_ulong_enum_to_uint_enum_rtime_s.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Expenum_ulong_enum_to_ulong_enum_rtime_s_Test() { if (ExpenumTestClass_ulong_enum_to_ulong_enum_rtime_s.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Expenum_ulong_enum_to_ushort_enum_rtime_s_Test() { if (ExpenumTestClass_ulong_enum_to_ushort_enum_rtime_s.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Expenum_ushort_enum_to_byte_enum_rtime_s_Test() { if (ExpenumTestClass_ushort_enum_to_byte_enum_rtime_s.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Expenum_ushort_enum_to_int_enum_rtime_s_Test() { if (ExpenumTestClass_ushort_enum_to_int_enum_rtime_s.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Expenum_ushort_enum_to_long_enum_rtime_s_Test() { if (ExpenumTestClass_ushort_enum_to_long_enum_rtime_s.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Expenum_ushort_enum_to_sbyte_enum_rtime_s_Test() { if (ExpenumTestClass_ushort_enum_to_sbyte_enum_rtime_s.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Expenum_ushort_enum_to_short_enum_rtime_s_Test() { if (ExpenumTestClass_ushort_enum_to_short_enum_rtime_s.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Expenum_ushort_enum_to_uint_enum_rtime_s_Test() { if (ExpenumTestClass_ushort_enum_to_uint_enum_rtime_s.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Expenum_ushort_enum_to_ulong_enum_rtime_s_Test() { if (ExpenumTestClass_ushort_enum_to_ulong_enum_rtime_s.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Expenum_ushort_enum_to_ushort_enum_rtime_s_Test() { if (ExpenumTestClass_ushort_enum_to_ushort_enum_rtime_s.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Expenum_byte_enum_to_byte_enum_rtime_s_Test() { if (ExpenumTestClass_byte_enum_to_byte_enum_rtime_s.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Expenum_byte_enum_to_int_enum_rtime_s_Test() { if (ExpenumTestClass_byte_enum_to_int_enum_rtime_s.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Expenum_byte_enum_to_long_enum_rtime_s_Test() { if (ExpenumTestClass_byte_enum_to_long_enum_rtime_s.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Expenum_byte_enum_to_sbyte_enum_rtime_s_Test() { if (ExpenumTestClass_byte_enum_to_sbyte_enum_rtime_s.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Expenum_byte_enum_to_short_enum_rtime_s_Test() { if (ExpenumTestClass_byte_enum_to_short_enum_rtime_s.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Expenum_byte_enum_to_uint_enum_rtime_s_Test() { if (ExpenumTestClass_byte_enum_to_uint_enum_rtime_s.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } enum ExpenumTestClass_sbyte_enum_to_ulong_enum_rtime_s_DestEnumType : ulong { ValOne = 1 } enum ExpenumTestClass_sbyte_enum_to_ulong_enum_rtime_s_SrcEnumType : sbyte { ValOne = 1 } public class ExpenumTestClass_sbyte_enum_to_ulong_enum_rtime_s { public static bool testMethod() { ExpenumTestClass_sbyte_enum_to_ulong_enum_rtime_s_DestEnumType Destination; ExpenumTestClass_sbyte_enum_to_ulong_enum_rtime_s_SrcEnumType Source = ExpenumTestClass_sbyte_enum_to_ulong_enum_rtime_s_SrcEnumType.ValOne; Destination = (ExpenumTestClass_sbyte_enum_to_ulong_enum_rtime_s_DestEnumType)Source; if (Destination == ExpenumTestClass_sbyte_enum_to_ulong_enum_rtime_s_DestEnumType.ValOne) return true; else return false; } } enum ExpenumTestClass_sbyte_enum_to_ushort_enum_rtime_s_DestEnumType : ushort { ValOne = 1 } enum ExpenumTestClass_sbyte_enum_to_ushort_enum_rtime_s_SrcEnumType : sbyte { ValOne = 1 } public class ExpenumTestClass_sbyte_enum_to_ushort_enum_rtime_s { public static bool testMethod() { ExpenumTestClass_sbyte_enum_to_ushort_enum_rtime_s_DestEnumType Destination; ExpenumTestClass_sbyte_enum_to_ushort_enum_rtime_s_SrcEnumType Source = ExpenumTestClass_sbyte_enum_to_ushort_enum_rtime_s_SrcEnumType.ValOne; Destination = (ExpenumTestClass_sbyte_enum_to_ushort_enum_rtime_s_DestEnumType)Source; if (Destination == ExpenumTestClass_sbyte_enum_to_ushort_enum_rtime_s_DestEnumType.ValOne) return true; else return false; } } enum ExpenumTestClass_short_enum_to_byte_enum_rtime_s_DestEnumType : byte { ValOne = 1 } enum ExpenumTestClass_short_enum_to_byte_enum_rtime_s_SrcEnumType : short { ValOne = 1 } public class ExpenumTestClass_short_enum_to_byte_enum_rtime_s { public static bool testMethod() { ExpenumTestClass_short_enum_to_byte_enum_rtime_s_DestEnumType Destination; ExpenumTestClass_short_enum_to_byte_enum_rtime_s_SrcEnumType Source = ExpenumTestClass_short_enum_to_byte_enum_rtime_s_SrcEnumType.ValOne; Destination = (ExpenumTestClass_short_enum_to_byte_enum_rtime_s_DestEnumType)Source; if (Destination == ExpenumTestClass_short_enum_to_byte_enum_rtime_s_DestEnumType.ValOne) return true; else return false; } } enum ExpenumTestClass_short_enum_to_int_enum_rtime_s_DestEnumType : int { ValOne = 1 } enum ExpenumTestClass_short_enum_to_int_enum_rtime_s_SrcEnumType : short { ValOne = 1 } public class ExpenumTestClass_short_enum_to_int_enum_rtime_s { public static bool testMethod() { ExpenumTestClass_short_enum_to_int_enum_rtime_s_DestEnumType Destination; ExpenumTestClass_short_enum_to_int_enum_rtime_s_SrcEnumType Source = ExpenumTestClass_short_enum_to_int_enum_rtime_s_SrcEnumType.ValOne; Destination = (ExpenumTestClass_short_enum_to_int_enum_rtime_s_DestEnumType)Source; if (Destination == ExpenumTestClass_short_enum_to_int_enum_rtime_s_DestEnumType.ValOne) return true; else return false; } } enum ExpenumTestClass_short_enum_to_long_enum_rtime_s_DestEnumType : long { ValOne = 1 } enum ExpenumTestClass_short_enum_to_long_enum_rtime_s_SrcEnumType : short { ValOne = 1 } public class ExpenumTestClass_short_enum_to_long_enum_rtime_s { public static bool testMethod() { ExpenumTestClass_short_enum_to_long_enum_rtime_s_DestEnumType Destination; ExpenumTestClass_short_enum_to_long_enum_rtime_s_SrcEnumType Source = ExpenumTestClass_short_enum_to_long_enum_rtime_s_SrcEnumType.ValOne; Destination = (ExpenumTestClass_short_enum_to_long_enum_rtime_s_DestEnumType)Source; if (Destination == ExpenumTestClass_short_enum_to_long_enum_rtime_s_DestEnumType.ValOne) return true; else return false; } } enum ExpenumTestClass_short_enum_to_sbyte_enum_rtime_s_DestEnumType : sbyte { ValOne = 1 } enum ExpenumTestClass_short_enum_to_sbyte_enum_rtime_s_SrcEnumType : short { ValOne = 1 } public class ExpenumTestClass_short_enum_to_sbyte_enum_rtime_s { public static bool testMethod() { ExpenumTestClass_short_enum_to_sbyte_enum_rtime_s_DestEnumType Destination; ExpenumTestClass_short_enum_to_sbyte_enum_rtime_s_SrcEnumType Source = ExpenumTestClass_short_enum_to_sbyte_enum_rtime_s_SrcEnumType.ValOne; Destination = (ExpenumTestClass_short_enum_to_sbyte_enum_rtime_s_DestEnumType)Source; if (Destination == ExpenumTestClass_short_enum_to_sbyte_enum_rtime_s_DestEnumType.ValOne) return true; else return false; } } enum ExpenumTestClass_short_enum_to_short_enum_rtime_s_DestEnumType : short { ValOne = 1 } enum ExpenumTestClass_short_enum_to_short_enum_rtime_s_SrcEnumType : short { ValOne = 1 } public class ExpenumTestClass_short_enum_to_short_enum_rtime_s { public static bool testMethod() { ExpenumTestClass_short_enum_to_short_enum_rtime_s_DestEnumType Destination; ExpenumTestClass_short_enum_to_short_enum_rtime_s_SrcEnumType Source = ExpenumTestClass_short_enum_to_short_enum_rtime_s_SrcEnumType.ValOne; Destination = (ExpenumTestClass_short_enum_to_short_enum_rtime_s_DestEnumType)Source; if (Destination == ExpenumTestClass_short_enum_to_short_enum_rtime_s_DestEnumType.ValOne) return true; else return false; } } enum ExpenumTestClass_short_enum_to_uint_enum_rtime_s_DestEnumType : uint { ValOne = 1 } enum ExpenumTestClass_short_enum_to_uint_enum_rtime_s_SrcEnumType : short { ValOne = 1 } public class ExpenumTestClass_short_enum_to_uint_enum_rtime_s { public static bool testMethod() { ExpenumTestClass_short_enum_to_uint_enum_rtime_s_DestEnumType Destination; ExpenumTestClass_short_enum_to_uint_enum_rtime_s_SrcEnumType Source = ExpenumTestClass_short_enum_to_uint_enum_rtime_s_SrcEnumType.ValOne; Destination = (ExpenumTestClass_short_enum_to_uint_enum_rtime_s_DestEnumType)Source; if (Destination == ExpenumTestClass_short_enum_to_uint_enum_rtime_s_DestEnumType.ValOne) return true; else return false; } } enum ExpenumTestClass_short_enum_to_ulong_enum_rtime_s_DestEnumType : ulong { ValOne = 1 } enum ExpenumTestClass_short_enum_to_ulong_enum_rtime_s_SrcEnumType : short { ValOne = 1 } public class ExpenumTestClass_short_enum_to_ulong_enum_rtime_s { public static bool testMethod() { ExpenumTestClass_short_enum_to_ulong_enum_rtime_s_DestEnumType Destination; ExpenumTestClass_short_enum_to_ulong_enum_rtime_s_SrcEnumType Source = ExpenumTestClass_short_enum_to_ulong_enum_rtime_s_SrcEnumType.ValOne; Destination = (ExpenumTestClass_short_enum_to_ulong_enum_rtime_s_DestEnumType)Source; if (Destination == ExpenumTestClass_short_enum_to_ulong_enum_rtime_s_DestEnumType.ValOne) return true; else return false; } } enum ExpenumTestClass_short_enum_to_ushort_enum_rtime_s_DestEnumType : ushort { ValOne = 1 } enum ExpenumTestClass_short_enum_to_ushort_enum_rtime_s_SrcEnumType : short { ValOne = 1 } public class ExpenumTestClass_short_enum_to_ushort_enum_rtime_s { public static bool testMethod() { ExpenumTestClass_short_enum_to_ushort_enum_rtime_s_DestEnumType Destination; ExpenumTestClass_short_enum_to_ushort_enum_rtime_s_SrcEnumType Source = ExpenumTestClass_short_enum_to_ushort_enum_rtime_s_SrcEnumType.ValOne; Destination = (ExpenumTestClass_short_enum_to_ushort_enum_rtime_s_DestEnumType)Source; if (Destination == ExpenumTestClass_short_enum_to_ushort_enum_rtime_s_DestEnumType.ValOne) return true; else return false; } } enum ExpenumTestClass_uint_enum_to_byte_enum_rtime_s_DestEnumType : byte { ValOne = 1 } enum ExpenumTestClass_uint_enum_to_byte_enum_rtime_s_SrcEnumType : uint { ValOne = 1 } public class ExpenumTestClass_uint_enum_to_byte_enum_rtime_s { public static bool testMethod() { ExpenumTestClass_uint_enum_to_byte_enum_rtime_s_DestEnumType Destination; ExpenumTestClass_uint_enum_to_byte_enum_rtime_s_SrcEnumType Source = ExpenumTestClass_uint_enum_to_byte_enum_rtime_s_SrcEnumType.ValOne; Destination = (ExpenumTestClass_uint_enum_to_byte_enum_rtime_s_DestEnumType)Source; if (Destination == ExpenumTestClass_uint_enum_to_byte_enum_rtime_s_DestEnumType.ValOne) return true; else return false; } } enum ExpenumTestClass_uint_enum_to_int_enum_rtime_s_DestEnumType : int { ValOne = 1 } enum ExpenumTestClass_uint_enum_to_int_enum_rtime_s_SrcEnumType : uint { ValOne = 1 } public class ExpenumTestClass_uint_enum_to_int_enum_rtime_s { public static bool testMethod() { ExpenumTestClass_uint_enum_to_int_enum_rtime_s_DestEnumType Destination; ExpenumTestClass_uint_enum_to_int_enum_rtime_s_SrcEnumType Source = ExpenumTestClass_uint_enum_to_int_enum_rtime_s_SrcEnumType.ValOne; Destination = (ExpenumTestClass_uint_enum_to_int_enum_rtime_s_DestEnumType)Source; if (Destination == ExpenumTestClass_uint_enum_to_int_enum_rtime_s_DestEnumType.ValOne) return true; else return false; } } enum ExpenumTestClass_uint_enum_to_long_enum_rtime_s_DestEnumType : long { ValOne = 1 } enum ExpenumTestClass_uint_enum_to_long_enum_rtime_s_SrcEnumType : uint { ValOne = 1 } public class ExpenumTestClass_uint_enum_to_long_enum_rtime_s { public static bool testMethod() { ExpenumTestClass_uint_enum_to_long_enum_rtime_s_DestEnumType Destination; ExpenumTestClass_uint_enum_to_long_enum_rtime_s_SrcEnumType Source = ExpenumTestClass_uint_enum_to_long_enum_rtime_s_SrcEnumType.ValOne; Destination = (ExpenumTestClass_uint_enum_to_long_enum_rtime_s_DestEnumType)Source; if (Destination == ExpenumTestClass_uint_enum_to_long_enum_rtime_s_DestEnumType.ValOne) return true; else return false; } } enum ExpenumTestClass_uint_enum_to_sbyte_enum_rtime_s_DestEnumType : sbyte { ValOne = 1 } enum ExpenumTestClass_uint_enum_to_sbyte_enum_rtime_s_SrcEnumType : uint { ValOne = 1 } public class ExpenumTestClass_uint_enum_to_sbyte_enum_rtime_s { public static bool testMethod() { ExpenumTestClass_uint_enum_to_sbyte_enum_rtime_s_DestEnumType Destination; ExpenumTestClass_uint_enum_to_sbyte_enum_rtime_s_SrcEnumType Source = ExpenumTestClass_uint_enum_to_sbyte_enum_rtime_s_SrcEnumType.ValOne; Destination = (ExpenumTestClass_uint_enum_to_sbyte_enum_rtime_s_DestEnumType)Source; if (Destination == ExpenumTestClass_uint_enum_to_sbyte_enum_rtime_s_DestEnumType.ValOne) return true; else return false; } } enum ExpenumTestClass_uint_enum_to_short_enum_rtime_s_DestEnumType : short { ValOne = 1 } enum ExpenumTestClass_uint_enum_to_short_enum_rtime_s_SrcEnumType : uint { ValOne = 1 } public class ExpenumTestClass_uint_enum_to_short_enum_rtime_s { public static bool testMethod() { ExpenumTestClass_uint_enum_to_short_enum_rtime_s_DestEnumType Destination; ExpenumTestClass_uint_enum_to_short_enum_rtime_s_SrcEnumType Source = ExpenumTestClass_uint_enum_to_short_enum_rtime_s_SrcEnumType.ValOne; Destination = (ExpenumTestClass_uint_enum_to_short_enum_rtime_s_DestEnumType)Source; if (Destination == ExpenumTestClass_uint_enum_to_short_enum_rtime_s_DestEnumType.ValOne) return true; else return false; } } enum ExpenumTestClass_uint_enum_to_uint_enum_rtime_s_DestEnumType : uint { ValOne = 1 } enum ExpenumTestClass_uint_enum_to_uint_enum_rtime_s_SrcEnumType : uint { ValOne = 1 } public class ExpenumTestClass_uint_enum_to_uint_enum_rtime_s { public static bool testMethod() { ExpenumTestClass_uint_enum_to_uint_enum_rtime_s_DestEnumType Destination; ExpenumTestClass_uint_enum_to_uint_enum_rtime_s_SrcEnumType Source = ExpenumTestClass_uint_enum_to_uint_enum_rtime_s_SrcEnumType.ValOne; Destination = (ExpenumTestClass_uint_enum_to_uint_enum_rtime_s_DestEnumType)Source; if (Destination == ExpenumTestClass_uint_enum_to_uint_enum_rtime_s_DestEnumType.ValOne) return true; else return false; } } enum ExpenumTestClass_uint_enum_to_ulong_enum_rtime_s_DestEnumType : ulong { ValOne = 1 } enum ExpenumTestClass_uint_enum_to_ulong_enum_rtime_s_SrcEnumType : uint { ValOne = 1 } public class ExpenumTestClass_uint_enum_to_ulong_enum_rtime_s { public static bool testMethod() { ExpenumTestClass_uint_enum_to_ulong_enum_rtime_s_DestEnumType Destination; ExpenumTestClass_uint_enum_to_ulong_enum_rtime_s_SrcEnumType Source = ExpenumTestClass_uint_enum_to_ulong_enum_rtime_s_SrcEnumType.ValOne; Destination = (ExpenumTestClass_uint_enum_to_ulong_enum_rtime_s_DestEnumType)Source; if (Destination == ExpenumTestClass_uint_enum_to_ulong_enum_rtime_s_DestEnumType.ValOne) return true; else return false; } } enum ExpenumTestClass_uint_enum_to_ushort_enum_rtime_s_DestEnumType : ushort { ValOne = 1 } enum ExpenumTestClass_uint_enum_to_ushort_enum_rtime_s_SrcEnumType : uint { ValOne = 1 } public class ExpenumTestClass_uint_enum_to_ushort_enum_rtime_s { public static bool testMethod() { ExpenumTestClass_uint_enum_to_ushort_enum_rtime_s_DestEnumType Destination; ExpenumTestClass_uint_enum_to_ushort_enum_rtime_s_SrcEnumType Source = ExpenumTestClass_uint_enum_to_ushort_enum_rtime_s_SrcEnumType.ValOne; Destination = (ExpenumTestClass_uint_enum_to_ushort_enum_rtime_s_DestEnumType)Source; if (Destination == ExpenumTestClass_uint_enum_to_ushort_enum_rtime_s_DestEnumType.ValOne) return true; else return false; } } enum ExpenumTestClass_ulong_enum_to_byte_enum_rtime_s_DestEnumType : byte { ValOne = 1 } enum ExpenumTestClass_ulong_enum_to_byte_enum_rtime_s_SrcEnumType : ulong { ValOne = 1 } public class ExpenumTestClass_ulong_enum_to_byte_enum_rtime_s { public static bool testMethod() { ExpenumTestClass_ulong_enum_to_byte_enum_rtime_s_DestEnumType Destination; ExpenumTestClass_ulong_enum_to_byte_enum_rtime_s_SrcEnumType Source = ExpenumTestClass_ulong_enum_to_byte_enum_rtime_s_SrcEnumType.ValOne; Destination = (ExpenumTestClass_ulong_enum_to_byte_enum_rtime_s_DestEnumType)Source; if (Destination == ExpenumTestClass_ulong_enum_to_byte_enum_rtime_s_DestEnumType.ValOne) return true; else return false; } } enum ExpenumTestClass_ulong_enum_to_int_enum_rtime_s_DestEnumType : int { ValOne = 1 } enum ExpenumTestClass_ulong_enum_to_int_enum_rtime_s_SrcEnumType : ulong { ValOne = 1 } public class ExpenumTestClass_ulong_enum_to_int_enum_rtime_s { public static bool testMethod() { ExpenumTestClass_ulong_enum_to_int_enum_rtime_s_DestEnumType Destination; ExpenumTestClass_ulong_enum_to_int_enum_rtime_s_SrcEnumType Source = ExpenumTestClass_ulong_enum_to_int_enum_rtime_s_SrcEnumType.ValOne; Destination = (ExpenumTestClass_ulong_enum_to_int_enum_rtime_s_DestEnumType)Source; if (Destination == ExpenumTestClass_ulong_enum_to_int_enum_rtime_s_DestEnumType.ValOne) return true; else return false; } } enum ExpenumTestClass_ulong_enum_to_long_enum_rtime_s_DestEnumType : long { ValOne = 1 } enum ExpenumTestClass_ulong_enum_to_long_enum_rtime_s_SrcEnumType : ulong { ValOne = 1 } public class ExpenumTestClass_ulong_enum_to_long_enum_rtime_s { public static bool testMethod() { ExpenumTestClass_ulong_enum_to_long_enum_rtime_s_DestEnumType Destination; ExpenumTestClass_ulong_enum_to_long_enum_rtime_s_SrcEnumType Source = ExpenumTestClass_ulong_enum_to_long_enum_rtime_s_SrcEnumType.ValOne; Destination = (ExpenumTestClass_ulong_enum_to_long_enum_rtime_s_DestEnumType)Source; if (Destination == ExpenumTestClass_ulong_enum_to_long_enum_rtime_s_DestEnumType.ValOne) return true; else return false; } } enum ExpenumTestClass_ulong_enum_to_sbyte_enum_rtime_s_DestEnumType : sbyte { ValOne = 1 } enum ExpenumTestClass_ulong_enum_to_sbyte_enum_rtime_s_SrcEnumType : ulong { ValOne = 1 } public class ExpenumTestClass_ulong_enum_to_sbyte_enum_rtime_s { public static bool testMethod() { ExpenumTestClass_ulong_enum_to_sbyte_enum_rtime_s_DestEnumType Destination; ExpenumTestClass_ulong_enum_to_sbyte_enum_rtime_s_SrcEnumType Source = ExpenumTestClass_ulong_enum_to_sbyte_enum_rtime_s_SrcEnumType.ValOne; Destination = (ExpenumTestClass_ulong_enum_to_sbyte_enum_rtime_s_DestEnumType)Source; if (Destination == ExpenumTestClass_ulong_enum_to_sbyte_enum_rtime_s_DestEnumType.ValOne) return true; else return false; } } enum ExpenumTestClass_ulong_enum_to_short_enum_rtime_s_DestEnumType : short { ValOne = 1 } enum ExpenumTestClass_ulong_enum_to_short_enum_rtime_s_SrcEnumType : ulong { ValOne = 1 } public class ExpenumTestClass_ulong_enum_to_short_enum_rtime_s { public static bool testMethod() { ExpenumTestClass_ulong_enum_to_short_enum_rtime_s_DestEnumType Destination; ExpenumTestClass_ulong_enum_to_short_enum_rtime_s_SrcEnumType Source = ExpenumTestClass_ulong_enum_to_short_enum_rtime_s_SrcEnumType.ValOne; Destination = (ExpenumTestClass_ulong_enum_to_short_enum_rtime_s_DestEnumType)Source; if (Destination == ExpenumTestClass_ulong_enum_to_short_enum_rtime_s_DestEnumType.ValOne) return true; else return false; } } enum ExpenumTestClass_ulong_enum_to_uint_enum_rtime_s_DestEnumType : uint { ValOne = 1 } enum ExpenumTestClass_ulong_enum_to_uint_enum_rtime_s_SrcEnumType : ulong { ValOne = 1 } public class ExpenumTestClass_ulong_enum_to_uint_enum_rtime_s { public static bool testMethod() { ExpenumTestClass_ulong_enum_to_uint_enum_rtime_s_DestEnumType Destination; ExpenumTestClass_ulong_enum_to_uint_enum_rtime_s_SrcEnumType Source = ExpenumTestClass_ulong_enum_to_uint_enum_rtime_s_SrcEnumType.ValOne; Destination = (ExpenumTestClass_ulong_enum_to_uint_enum_rtime_s_DestEnumType)Source; if (Destination == ExpenumTestClass_ulong_enum_to_uint_enum_rtime_s_DestEnumType.ValOne) return true; else return false; } } enum ExpenumTestClass_ulong_enum_to_ulong_enum_rtime_s_DestEnumType : ulong { ValOne = 1 } enum ExpenumTestClass_ulong_enum_to_ulong_enum_rtime_s_SrcEnumType : ulong { ValOne = 1 } public class ExpenumTestClass_ulong_enum_to_ulong_enum_rtime_s { public static bool testMethod() { ExpenumTestClass_ulong_enum_to_ulong_enum_rtime_s_DestEnumType Destination; ExpenumTestClass_ulong_enum_to_ulong_enum_rtime_s_SrcEnumType Source = ExpenumTestClass_ulong_enum_to_ulong_enum_rtime_s_SrcEnumType.ValOne; Destination = (ExpenumTestClass_ulong_enum_to_ulong_enum_rtime_s_DestEnumType)Source; if (Destination == ExpenumTestClass_ulong_enum_to_ulong_enum_rtime_s_DestEnumType.ValOne) return true; else return false; } } enum ExpenumTestClass_ulong_enum_to_ushort_enum_rtime_s_DestEnumType : ushort { ValOne = 1 } enum ExpenumTestClass_ulong_enum_to_ushort_enum_rtime_s_SrcEnumType : ulong { ValOne = 1 } public class ExpenumTestClass_ulong_enum_to_ushort_enum_rtime_s { public static bool testMethod() { ExpenumTestClass_ulong_enum_to_ushort_enum_rtime_s_DestEnumType Destination; ExpenumTestClass_ulong_enum_to_ushort_enum_rtime_s_SrcEnumType Source = ExpenumTestClass_ulong_enum_to_ushort_enum_rtime_s_SrcEnumType.ValOne; Destination = (ExpenumTestClass_ulong_enum_to_ushort_enum_rtime_s_DestEnumType)Source; if (Destination == ExpenumTestClass_ulong_enum_to_ushort_enum_rtime_s_DestEnumType.ValOne) return true; else return false; } } enum ExpenumTestClass_ushort_enum_to_byte_enum_rtime_s_DestEnumType : byte { ValOne = 1 } enum ExpenumTestClass_ushort_enum_to_byte_enum_rtime_s_SrcEnumType : ushort { ValOne = 1 } public class ExpenumTestClass_ushort_enum_to_byte_enum_rtime_s { public static bool testMethod() { ExpenumTestClass_ushort_enum_to_byte_enum_rtime_s_DestEnumType Destination; ExpenumTestClass_ushort_enum_to_byte_enum_rtime_s_SrcEnumType Source = ExpenumTestClass_ushort_enum_to_byte_enum_rtime_s_SrcEnumType.ValOne; Destination = (ExpenumTestClass_ushort_enum_to_byte_enum_rtime_s_DestEnumType)Source; if (Destination == ExpenumTestClass_ushort_enum_to_byte_enum_rtime_s_DestEnumType.ValOne) return true; else return false; } } enum ExpenumTestClass_ushort_enum_to_int_enum_rtime_s_DestEnumType : int { ValOne = 1 } enum ExpenumTestClass_ushort_enum_to_int_enum_rtime_s_SrcEnumType : ushort { ValOne = 1 } public class ExpenumTestClass_ushort_enum_to_int_enum_rtime_s { public static bool testMethod() { ExpenumTestClass_ushort_enum_to_int_enum_rtime_s_DestEnumType Destination; ExpenumTestClass_ushort_enum_to_int_enum_rtime_s_SrcEnumType Source = ExpenumTestClass_ushort_enum_to_int_enum_rtime_s_SrcEnumType.ValOne; Destination = (ExpenumTestClass_ushort_enum_to_int_enum_rtime_s_DestEnumType)Source; if (Destination == ExpenumTestClass_ushort_enum_to_int_enum_rtime_s_DestEnumType.ValOne) return true; else return false; } } enum ExpenumTestClass_ushort_enum_to_long_enum_rtime_s_DestEnumType : long { ValOne = 1 } enum ExpenumTestClass_ushort_enum_to_long_enum_rtime_s_SrcEnumType : ushort { ValOne = 1 } public class ExpenumTestClass_ushort_enum_to_long_enum_rtime_s { public static bool testMethod() { ExpenumTestClass_ushort_enum_to_long_enum_rtime_s_DestEnumType Destination; ExpenumTestClass_ushort_enum_to_long_enum_rtime_s_SrcEnumType Source = ExpenumTestClass_ushort_enum_to_long_enum_rtime_s_SrcEnumType.ValOne; Destination = (ExpenumTestClass_ushort_enum_to_long_enum_rtime_s_DestEnumType)Source; if (Destination == ExpenumTestClass_ushort_enum_to_long_enum_rtime_s_DestEnumType.ValOne) return true; else return false; } } enum ExpenumTestClass_ushort_enum_to_sbyte_enum_rtime_s_DestEnumType : sbyte { ValOne = 1 } enum ExpenumTestClass_ushort_enum_to_sbyte_enum_rtime_s_SrcEnumType : ushort { ValOne = 1 } public class ExpenumTestClass_ushort_enum_to_sbyte_enum_rtime_s { public static bool testMethod() { ExpenumTestClass_ushort_enum_to_sbyte_enum_rtime_s_DestEnumType Destination; ExpenumTestClass_ushort_enum_to_sbyte_enum_rtime_s_SrcEnumType Source = ExpenumTestClass_ushort_enum_to_sbyte_enum_rtime_s_SrcEnumType.ValOne; Destination = (ExpenumTestClass_ushort_enum_to_sbyte_enum_rtime_s_DestEnumType)Source; if (Destination == ExpenumTestClass_ushort_enum_to_sbyte_enum_rtime_s_DestEnumType.ValOne) return true; else return false; } } enum ExpenumTestClass_ushort_enum_to_short_enum_rtime_s_DestEnumType : short { ValOne = 1 } enum ExpenumTestClass_ushort_enum_to_short_enum_rtime_s_SrcEnumType : ushort { ValOne = 1 } public class ExpenumTestClass_ushort_enum_to_short_enum_rtime_s { public static bool testMethod() { ExpenumTestClass_ushort_enum_to_short_enum_rtime_s_DestEnumType Destination; ExpenumTestClass_ushort_enum_to_short_enum_rtime_s_SrcEnumType Source = ExpenumTestClass_ushort_enum_to_short_enum_rtime_s_SrcEnumType.ValOne; Destination = (ExpenumTestClass_ushort_enum_to_short_enum_rtime_s_DestEnumType)Source; if (Destination == ExpenumTestClass_ushort_enum_to_short_enum_rtime_s_DestEnumType.ValOne) return true; else return false; } } enum ExpenumTestClass_ushort_enum_to_uint_enum_rtime_s_DestEnumType : uint { ValOne = 1 } enum ExpenumTestClass_ushort_enum_to_uint_enum_rtime_s_SrcEnumType : ushort { ValOne = 1 } public class ExpenumTestClass_ushort_enum_to_uint_enum_rtime_s { public static bool testMethod() { ExpenumTestClass_ushort_enum_to_uint_enum_rtime_s_DestEnumType Destination; ExpenumTestClass_ushort_enum_to_uint_enum_rtime_s_SrcEnumType Source = ExpenumTestClass_ushort_enum_to_uint_enum_rtime_s_SrcEnumType.ValOne; Destination = (ExpenumTestClass_ushort_enum_to_uint_enum_rtime_s_DestEnumType)Source; if (Destination == ExpenumTestClass_ushort_enum_to_uint_enum_rtime_s_DestEnumType.ValOne) return true; else return false; } } enum ExpenumTestClass_ushort_enum_to_ulong_enum_rtime_s_DestEnumType : ulong { ValOne = 1 } enum ExpenumTestClass_ushort_enum_to_ulong_enum_rtime_s_SrcEnumType : ushort { ValOne = 1 } public class ExpenumTestClass_ushort_enum_to_ulong_enum_rtime_s { public static bool testMethod() { ExpenumTestClass_ushort_enum_to_ulong_enum_rtime_s_DestEnumType Destination; ExpenumTestClass_ushort_enum_to_ulong_enum_rtime_s_SrcEnumType Source = ExpenumTestClass_ushort_enum_to_ulong_enum_rtime_s_SrcEnumType.ValOne; Destination = (ExpenumTestClass_ushort_enum_to_ulong_enum_rtime_s_DestEnumType)Source; if (Destination == ExpenumTestClass_ushort_enum_to_ulong_enum_rtime_s_DestEnumType.ValOne) return true; else return false; } } enum ExpenumTestClass_ushort_enum_to_ushort_enum_rtime_s_DestEnumType : ushort { ValOne = 1 } enum ExpenumTestClass_ushort_enum_to_ushort_enum_rtime_s_SrcEnumType : ushort { ValOne = 1 } public class ExpenumTestClass_ushort_enum_to_ushort_enum_rtime_s { public static bool testMethod() { ExpenumTestClass_ushort_enum_to_ushort_enum_rtime_s_DestEnumType Destination; ExpenumTestClass_ushort_enum_to_ushort_enum_rtime_s_SrcEnumType Source = ExpenumTestClass_ushort_enum_to_ushort_enum_rtime_s_SrcEnumType.ValOne; Destination = (ExpenumTestClass_ushort_enum_to_ushort_enum_rtime_s_DestEnumType)Source; if (Destination == ExpenumTestClass_ushort_enum_to_ushort_enum_rtime_s_DestEnumType.ValOne) return true; else return false; } } enum ExpenumTestClass_byte_enum_to_byte_enum_rtime_s_DestEnumType : byte { ValOne = 1 } enum ExpenumTestClass_byte_enum_to_byte_enum_rtime_s_SrcEnumType : byte { ValOne = 1 } public class ExpenumTestClass_byte_enum_to_byte_enum_rtime_s { public static bool testMethod() { ExpenumTestClass_byte_enum_to_byte_enum_rtime_s_DestEnumType Destination; ExpenumTestClass_byte_enum_to_byte_enum_rtime_s_SrcEnumType Source = ExpenumTestClass_byte_enum_to_byte_enum_rtime_s_SrcEnumType.ValOne; Destination = (ExpenumTestClass_byte_enum_to_byte_enum_rtime_s_DestEnumType)Source; if (Destination == ExpenumTestClass_byte_enum_to_byte_enum_rtime_s_DestEnumType.ValOne) return true; else return false; } } enum ExpenumTestClass_byte_enum_to_int_enum_rtime_s_DestEnumType : int { ValOne = 1 } enum ExpenumTestClass_byte_enum_to_int_enum_rtime_s_SrcEnumType : byte { ValOne = 1 } public class ExpenumTestClass_byte_enum_to_int_enum_rtime_s { public static bool testMethod() { ExpenumTestClass_byte_enum_to_int_enum_rtime_s_DestEnumType Destination; ExpenumTestClass_byte_enum_to_int_enum_rtime_s_SrcEnumType Source = ExpenumTestClass_byte_enum_to_int_enum_rtime_s_SrcEnumType.ValOne; Destination = (ExpenumTestClass_byte_enum_to_int_enum_rtime_s_DestEnumType)Source; if (Destination == ExpenumTestClass_byte_enum_to_int_enum_rtime_s_DestEnumType.ValOne) return true; else return false; } } enum ExpenumTestClass_byte_enum_to_long_enum_rtime_s_DestEnumType : long { ValOne = 1 } enum ExpenumTestClass_byte_enum_to_long_enum_rtime_s_SrcEnumType : byte { ValOne = 1 } public class ExpenumTestClass_byte_enum_to_long_enum_rtime_s { public static bool testMethod() { ExpenumTestClass_byte_enum_to_long_enum_rtime_s_DestEnumType Destination; ExpenumTestClass_byte_enum_to_long_enum_rtime_s_SrcEnumType Source = ExpenumTestClass_byte_enum_to_long_enum_rtime_s_SrcEnumType.ValOne; Destination = (ExpenumTestClass_byte_enum_to_long_enum_rtime_s_DestEnumType)Source; if (Destination == ExpenumTestClass_byte_enum_to_long_enum_rtime_s_DestEnumType.ValOne) return true; else return false; } } enum ExpenumTestClass_byte_enum_to_sbyte_enum_rtime_s_DestEnumType : sbyte { ValOne = 1 } enum ExpenumTestClass_byte_enum_to_sbyte_enum_rtime_s_SrcEnumType : byte { ValOne = 1 } public class ExpenumTestClass_byte_enum_to_sbyte_enum_rtime_s { public static bool testMethod() { ExpenumTestClass_byte_enum_to_sbyte_enum_rtime_s_DestEnumType Destination; ExpenumTestClass_byte_enum_to_sbyte_enum_rtime_s_SrcEnumType Source = ExpenumTestClass_byte_enum_to_sbyte_enum_rtime_s_SrcEnumType.ValOne; Destination = (ExpenumTestClass_byte_enum_to_sbyte_enum_rtime_s_DestEnumType)Source; if (Destination == ExpenumTestClass_byte_enum_to_sbyte_enum_rtime_s_DestEnumType.ValOne) return true; else return false; } } enum ExpenumTestClass_byte_enum_to_short_enum_rtime_s_DestEnumType : short { ValOne = 1 } enum ExpenumTestClass_byte_enum_to_short_enum_rtime_s_SrcEnumType : byte { ValOne = 1 } public class ExpenumTestClass_byte_enum_to_short_enum_rtime_s { public static bool testMethod() { ExpenumTestClass_byte_enum_to_short_enum_rtime_s_DestEnumType Destination; ExpenumTestClass_byte_enum_to_short_enum_rtime_s_SrcEnumType Source = ExpenumTestClass_byte_enum_to_short_enum_rtime_s_SrcEnumType.ValOne; Destination = (ExpenumTestClass_byte_enum_to_short_enum_rtime_s_DestEnumType)Source; if (Destination == ExpenumTestClass_byte_enum_to_short_enum_rtime_s_DestEnumType.ValOne) return true; else return false; } } enum ExpenumTestClass_byte_enum_to_uint_enum_rtime_s_DestEnumType : uint { ValOne = 1 } enum ExpenumTestClass_byte_enum_to_uint_enum_rtime_s_SrcEnumType : byte { ValOne = 1 } public class ExpenumTestClass_byte_enum_to_uint_enum_rtime_s { public static bool testMethod() { ExpenumTestClass_byte_enum_to_uint_enum_rtime_s_DestEnumType Destination; ExpenumTestClass_byte_enum_to_uint_enum_rtime_s_SrcEnumType Source = ExpenumTestClass_byte_enum_to_uint_enum_rtime_s_SrcEnumType.ValOne; Destination = (ExpenumTestClass_byte_enum_to_uint_enum_rtime_s_DestEnumType)Source; if (Destination == ExpenumTestClass_byte_enum_to_uint_enum_rtime_s_DestEnumType.ValOne) return true; else return false; } } } } ================================================ FILE: Zelig/Zelig/Test/RunTime/NETMF/mscorlib/conversions/user/ClassClassTests.cs ================================================ //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // Copyright (c) Microsoft Corporation. All rights reserved. //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// using System; namespace Microsoft.Zelig.Test { public class ClassClassTests : TestBase, ITestInterface { [SetUp] public InitializeResult Initialize() { Log.Comment("Adding set up for the tests."); Log.Comment("These tests examine the conversion (casting) of classes at various levels of inheritance trees."); Log.Comment("The two trees are SDer : S : SBase and TDer : T : TBase."); Log.Comment("The names of the tests describe the tests by listing which two classes will be converted between"); Log.Comment("Followed by which (The source or the destination) will contain a cast definition"); Log.Comment("Followed further by 'i's or 'e's to indicate which of the cast definition and the actual cast are"); Log.Comment("implicit or explicit."); Log.Comment(""); Log.Comment("For example, SBase_T_Source_i_e tests the conversion of SBase to T, with an implicit definition"); Log.Comment("of the cast in the SBase class, and an explicit cast in the body of the method."); // Add your functionality here. return InitializeResult.ReadyToGo; } [TearDown] public void CleanUp() { Log.Comment("Cleaning up after the tests"); } public override TestResult Run( string[] args ) { TestResult result = TestResult.Pass; string testName = "ClassClass_"; int testNumber = 0; result |= Assert.CheckFailed( ClassClass_SBase_TBase_Source_i_e_Test(), testName, ++testNumber ); result |= Assert.CheckFailed( ClassClass_SBase_TBase_Source_e_e_Test( ), testName, ++testNumber ); result |= Assert.CheckFailed( ClassClass_SBase_TBase_Dest_i_e_Test( ), testName, ++testNumber ); result |= Assert.CheckFailed( ClassClass_SBase_TBase_Dest_e_e_Test( ), testName, ++testNumber ); result |= Assert.CheckFailed( ClassClass_SBase_T_Source_i_i_Test( ), testName, ++testNumber ); result |= Assert.CheckFailed( ClassClass_SBase_T_Source_i_e_Test( ), testName, ++testNumber ); result |= Assert.CheckFailed( ClassClass_SBase_T_Source_e_e_Test( ), testName, ++testNumber ); result |= Assert.CheckFailed( ClassClass_SBase_T_Dest_i_i_Test( ), testName, ++testNumber ); result |= Assert.CheckFailed( ClassClass_SBase_T_Dest_i_e_Test( ), testName, ++testNumber ); result |= Assert.CheckFailed( ClassClass_SBase_T_Dest_e_e_Test( ), testName, ++testNumber ); result |= Assert.CheckFailed( ClassClass_SBase_TDer_Source_i_i_Test( ), testName, ++testNumber ); result |= Assert.CheckFailed( ClassClass_SBase_TDer_Source_i_e_Test( ), testName, ++testNumber ); result |= Assert.CheckFailed( ClassClass_SBase_TDer_Source_e_e_Test( ), testName, ++testNumber ); result |= Assert.CheckFailed( ClassClass_S_TBase_Source_i_e_Test( ), testName, ++testNumber ); result |= Assert.CheckFailed( ClassClass_S_TBase_Source_e_e_Test( ), testName, ++testNumber ); result |= Assert.CheckFailed( ClassClass_S_TBase_Dest_i_e_Test( ), testName, ++testNumber ); result |= Assert.CheckFailed( ClassClass_S_TBase_Dest_e_e_Test( ), testName, ++testNumber ); result |= Assert.CheckFailed( ClassClass_S_T_Source_i_i_Test( ), testName, ++testNumber ); result |= Assert.CheckFailed( ClassClass_S_T_Source_i_e_Test( ), testName, ++testNumber ); result |= Assert.CheckFailed( ClassClass_S_T_Source_e_e_Test( ), testName, ++testNumber ); result |= Assert.CheckFailed( ClassClass_S_T_Dest_i_i_Test( ), testName, ++testNumber ); result |= Assert.CheckFailed( ClassClass_S_T_Dest_i_e_Test( ), testName, ++testNumber ); result |= Assert.CheckFailed( ClassClass_S_T_Dest_e_e_Test( ), testName, ++testNumber ); result |= Assert.CheckFailed( ClassClass_S_TDer_Source_i_i_Test( ), testName, ++testNumber ); result |= Assert.CheckFailed( ClassClass_S_TDer_Source_i_e_Test( ), testName, ++testNumber ); result |= Assert.CheckFailed( ClassClass_S_TDer_Source_e_e_Test( ), testName, ++testNumber ); result |= Assert.CheckFailed( ClassClass_SDer_TBase_Dest_i_e_Test( ), testName, ++testNumber ); result |= Assert.CheckFailed( ClassClass_SDer_TBase_Dest_e_e_Test( ), testName, ++testNumber ); result |= Assert.CheckFailed( ClassClass_SDer_T_Dest_i_e_Test( ), testName, ++testNumber ); result |= Assert.CheckFailed( ClassClass_SDer_T_Dest_e_e_Test( ), testName, ++testNumber ); return result; } //ClassClass Test methods //The following tests were ported from folder current\test\cases\client\CLR\Conformance\10_classes\ClassClass //SBase_TBase_Source_i_e,SBase_TBase_Source_e_e,SBase_TBase_Dest_i_e,SBase_TBase_Dest_e_e,SBase_T_Source_i_i,SBase_T_Source_i_e,SBase_T_Source_e_e,SBase_T_Dest_i_i,SBase_T_Dest_i_e,SBase_T_Dest_e_e,SBase_TDer_Source_i_i,SBase_TDer_Source_i_e,SBase_TDer_Source_e_e,S_TBase_Source_i_e,S_TBase_Source_e_e,S_TBase_Dest_i_e,S_TBase_Dest_e_e,S_T_Source_i_i,S_T_Source_i_e,S_T_Source_e_e,S_T_Dest_i_i,S_T_Dest_i_e,S_T_Dest_e_e,S_TDer_Source_i_i,S_TDer_Source_i_e,S_TDer_Source_e_e,SDer_TBase_Dest_i_e,SDer_TBase_Dest_e_e,SDer_T_Dest_i_e,SDer_T_Dest_e_e //Test Case Calls [TestMethod] public TestResult ClassClass_SBase_TBase_Source_i_e_Test() { if (ClassClassTestClass_SBase_TBase_Source_i_e.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult ClassClass_SBase_TBase_Source_e_e_Test() { if (ClassClassTestClass_SBase_TBase_Source_e_e.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult ClassClass_SBase_TBase_Dest_i_e_Test() { if (ClassClassTestClass_SBase_TBase_Dest_i_e.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult ClassClass_SBase_TBase_Dest_e_e_Test() { if (ClassClassTestClass_SBase_TBase_Dest_e_e.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult ClassClass_SBase_T_Source_i_i_Test() { if (ClassClassTestClass_SBase_T_Source_i_i.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult ClassClass_SBase_T_Source_i_e_Test() { if (ClassClassTestClass_SBase_T_Source_i_e.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult ClassClass_SBase_T_Source_e_e_Test() { if (ClassClassTestClass_SBase_T_Source_e_e.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult ClassClass_SBase_T_Dest_i_i_Test() { if (ClassClassTestClass_SBase_T_Dest_i_i.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult ClassClass_SBase_T_Dest_i_e_Test() { if (ClassClassTestClass_SBase_T_Dest_i_e.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult ClassClass_SBase_T_Dest_e_e_Test() { if (ClassClassTestClass_SBase_T_Dest_e_e.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult ClassClass_SBase_TDer_Source_i_i_Test() { if (ClassClassTestClass_SBase_TDer_Source_i_i.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult ClassClass_SBase_TDer_Source_i_e_Test() { if (ClassClassTestClass_SBase_TDer_Source_i_e.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult ClassClass_SBase_TDer_Source_e_e_Test() { if (ClassClassTestClass_SBase_TDer_Source_e_e.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult ClassClass_S_TBase_Source_i_e_Test() { if (ClassClassTestClass_S_TBase_Source_i_e.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult ClassClass_S_TBase_Source_e_e_Test() { if (ClassClassTestClass_S_TBase_Source_e_e.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult ClassClass_S_TBase_Dest_i_e_Test() { if (ClassClassTestClass_S_TBase_Dest_i_e.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult ClassClass_S_TBase_Dest_e_e_Test() { if (ClassClassTestClass_S_TBase_Dest_e_e.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult ClassClass_S_T_Source_i_i_Test() { if (ClassClassTestClass_S_T_Source_i_i.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult ClassClass_S_T_Source_i_e_Test() { if (ClassClassTestClass_S_T_Source_i_e.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult ClassClass_S_T_Source_e_e_Test() { if (ClassClassTestClass_S_T_Source_e_e.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult ClassClass_S_T_Dest_i_i_Test() { if (ClassClassTestClass_S_T_Dest_i_i.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult ClassClass_S_T_Dest_i_e_Test() { if (ClassClassTestClass_S_T_Dest_i_e.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult ClassClass_S_T_Dest_e_e_Test() { if (ClassClassTestClass_S_T_Dest_e_e.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult ClassClass_S_TDer_Source_i_i_Test() { if (ClassClassTestClass_S_TDer_Source_i_i.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult ClassClass_S_TDer_Source_i_e_Test() { if (ClassClassTestClass_S_TDer_Source_i_e.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult ClassClass_S_TDer_Source_e_e_Test() { if (ClassClassTestClass_S_TDer_Source_e_e.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult ClassClass_SDer_TBase_Dest_i_e_Test() { if (ClassClassTestClass_SDer_TBase_Dest_i_e.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult ClassClass_SDer_TBase_Dest_e_e_Test() { if (ClassClassTestClass_SDer_TBase_Dest_e_e.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult ClassClass_SDer_T_Dest_i_e_Test() { if (ClassClassTestClass_SDer_T_Dest_i_e.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult ClassClass_SDer_T_Dest_e_e_Test() { if (ClassClassTestClass_SDer_T_Dest_e_e.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } //Compiled Test Cases class ClassClassTestClass_SBase_TBase_Source_i_e_SBase { static public implicit operator ClassClassTestClass_SBase_TBase_Source_i_e_TBase(ClassClassTestClass_SBase_TBase_Source_i_e_SBase foo) { return new ClassClassTestClass_SBase_TBase_Source_i_e_TBase(); } } class ClassClassTestClass_SBase_TBase_Source_i_e_S: ClassClassTestClass_SBase_TBase_Source_i_e_SBase { } class ClassClassTestClass_SBase_TBase_Source_i_e_SDer: ClassClassTestClass_SBase_TBase_Source_i_e_S { } class ClassClassTestClass_SBase_TBase_Source_i_e_TBase { } class ClassClassTestClass_SBase_TBase_Source_i_e_T: ClassClassTestClass_SBase_TBase_Source_i_e_TBase { } class ClassClassTestClass_SBase_TBase_Source_i_e_TDer: ClassClassTestClass_SBase_TBase_Source_i_e_T { } class ClassClassTestClass_SBase_TBase_Source_i_e { public static bool testMethod() { ClassClassTestClass_SBase_TBase_Source_i_e_S s = new ClassClassTestClass_SBase_TBase_Source_i_e_S(); ClassClassTestClass_SBase_TBase_Source_i_e_T t; try { t = (ClassClassTestClass_SBase_TBase_Source_i_e_T)s; } catch (System.Exception) { Log.Comment("System.Exception caught"); } return true; } } class ClassClassTestClass_SBase_TBase_Source_e_e_SBase { static public explicit operator ClassClassTestClass_SBase_TBase_Source_e_e_TBase(ClassClassTestClass_SBase_TBase_Source_e_e_SBase foo) { return new ClassClassTestClass_SBase_TBase_Source_e_e_TBase(); } } class ClassClassTestClass_SBase_TBase_Source_e_e_S: ClassClassTestClass_SBase_TBase_Source_e_e_SBase { } class ClassClassTestClass_SBase_TBase_Source_e_e_SDer: ClassClassTestClass_SBase_TBase_Source_e_e_S { } class ClassClassTestClass_SBase_TBase_Source_e_e_TBase { } class ClassClassTestClass_SBase_TBase_Source_e_e_T: ClassClassTestClass_SBase_TBase_Source_e_e_TBase { } class ClassClassTestClass_SBase_TBase_Source_e_e_TDer: ClassClassTestClass_SBase_TBase_Source_e_e_T { } class ClassClassTestClass_SBase_TBase_Source_e_e { public static bool testMethod() { ClassClassTestClass_SBase_TBase_Source_e_e_S s = new ClassClassTestClass_SBase_TBase_Source_e_e_S(); ClassClassTestClass_SBase_TBase_Source_e_e_T t; try { t = (ClassClassTestClass_SBase_TBase_Source_e_e_T)s; } catch (System.Exception) { Log.Comment("System.Exception caught"); } return true; } } class ClassClassTestClass_SBase_TBase_Dest_i_e_SBase { } class ClassClassTestClass_SBase_TBase_Dest_i_e_S: ClassClassTestClass_SBase_TBase_Dest_i_e_SBase { } class ClassClassTestClass_SBase_TBase_Dest_i_e_SDer: ClassClassTestClass_SBase_TBase_Dest_i_e_S { } class ClassClassTestClass_SBase_TBase_Dest_i_e_TBase { static public implicit operator ClassClassTestClass_SBase_TBase_Dest_i_e_TBase(ClassClassTestClass_SBase_TBase_Dest_i_e_SBase foo) { return new ClassClassTestClass_SBase_TBase_Dest_i_e_TBase(); } } class ClassClassTestClass_SBase_TBase_Dest_i_e_T: ClassClassTestClass_SBase_TBase_Dest_i_e_TBase { } class ClassClassTestClass_SBase_TBase_Dest_i_e_TDer: ClassClassTestClass_SBase_TBase_Dest_i_e_T { } class ClassClassTestClass_SBase_TBase_Dest_i_e { public static bool testMethod() { ClassClassTestClass_SBase_TBase_Dest_i_e_S s = new ClassClassTestClass_SBase_TBase_Dest_i_e_S(); ClassClassTestClass_SBase_TBase_Dest_i_e_T t; try { t = (ClassClassTestClass_SBase_TBase_Dest_i_e_T)s; } catch (System.Exception) { Log.Comment("System.Exception caught"); } return true; } } class ClassClassTestClass_SBase_TBase_Dest_e_e_SBase { } class ClassClassTestClass_SBase_TBase_Dest_e_e_S: ClassClassTestClass_SBase_TBase_Dest_e_e_SBase { } class ClassClassTestClass_SBase_TBase_Dest_e_e_SDer: ClassClassTestClass_SBase_TBase_Dest_e_e_S { } class ClassClassTestClass_SBase_TBase_Dest_e_e_TBase { static public explicit operator ClassClassTestClass_SBase_TBase_Dest_e_e_TBase(ClassClassTestClass_SBase_TBase_Dest_e_e_SBase foo) { return new ClassClassTestClass_SBase_TBase_Dest_e_e_TBase(); } } class ClassClassTestClass_SBase_TBase_Dest_e_e_T: ClassClassTestClass_SBase_TBase_Dest_e_e_TBase { } class ClassClassTestClass_SBase_TBase_Dest_e_e_TDer: ClassClassTestClass_SBase_TBase_Dest_e_e_T { } class ClassClassTestClass_SBase_TBase_Dest_e_e { public static bool testMethod() { ClassClassTestClass_SBase_TBase_Dest_e_e_S s = new ClassClassTestClass_SBase_TBase_Dest_e_e_S(); ClassClassTestClass_SBase_TBase_Dest_e_e_T t; try { t = (ClassClassTestClass_SBase_TBase_Dest_e_e_T)s; } catch (System.Exception) { Log.Comment("System.Exception caught"); } return true; } } class ClassClassTestClass_SBase_T_Source_i_i_SBase { static public implicit operator ClassClassTestClass_SBase_T_Source_i_i_T(ClassClassTestClass_SBase_T_Source_i_i_SBase foo) { return new ClassClassTestClass_SBase_T_Source_i_i_T(); } } class ClassClassTestClass_SBase_T_Source_i_i_S: ClassClassTestClass_SBase_T_Source_i_i_SBase { } class ClassClassTestClass_SBase_T_Source_i_i_SDer: ClassClassTestClass_SBase_T_Source_i_i_S { } class ClassClassTestClass_SBase_T_Source_i_i_TBase { } class ClassClassTestClass_SBase_T_Source_i_i_T: ClassClassTestClass_SBase_T_Source_i_i_TBase { } class ClassClassTestClass_SBase_T_Source_i_i_TDer: ClassClassTestClass_SBase_T_Source_i_i_T { } class ClassClassTestClass_SBase_T_Source_i_i { public static bool testMethod() { ClassClassTestClass_SBase_T_Source_i_i_S s = new ClassClassTestClass_SBase_T_Source_i_i_S(); ClassClassTestClass_SBase_T_Source_i_i_T t; try { t = s; } catch (System.Exception) { Log.Comment("System.Exception caught"); } return true; } } class ClassClassTestClass_SBase_T_Source_i_e_SBase { static public implicit operator ClassClassTestClass_SBase_T_Source_i_e_T(ClassClassTestClass_SBase_T_Source_i_e_SBase foo) { return new ClassClassTestClass_SBase_T_Source_i_e_T(); } } class ClassClassTestClass_SBase_T_Source_i_e_S: ClassClassTestClass_SBase_T_Source_i_e_SBase { } class ClassClassTestClass_SBase_T_Source_i_e_SDer: ClassClassTestClass_SBase_T_Source_i_e_S { } class ClassClassTestClass_SBase_T_Source_i_e_TBase { } class ClassClassTestClass_SBase_T_Source_i_e_T: ClassClassTestClass_SBase_T_Source_i_e_TBase { } class ClassClassTestClass_SBase_T_Source_i_e_TDer: ClassClassTestClass_SBase_T_Source_i_e_T { } class ClassClassTestClass_SBase_T_Source_i_e { public static bool testMethod() { ClassClassTestClass_SBase_T_Source_i_e_S s = new ClassClassTestClass_SBase_T_Source_i_e_S(); ClassClassTestClass_SBase_T_Source_i_e_T t; try { t = (ClassClassTestClass_SBase_T_Source_i_e_T)s; } catch (System.Exception) { Log.Comment("System.Exception caught"); } return true; } } class ClassClassTestClass_SBase_T_Source_e_e_SBase { static public explicit operator ClassClassTestClass_SBase_T_Source_e_e_T(ClassClassTestClass_SBase_T_Source_e_e_SBase foo) { return new ClassClassTestClass_SBase_T_Source_e_e_T(); } } class ClassClassTestClass_SBase_T_Source_e_e_S: ClassClassTestClass_SBase_T_Source_e_e_SBase { } class ClassClassTestClass_SBase_T_Source_e_e_SDer: ClassClassTestClass_SBase_T_Source_e_e_S { } class ClassClassTestClass_SBase_T_Source_e_e_TBase { } class ClassClassTestClass_SBase_T_Source_e_e_T: ClassClassTestClass_SBase_T_Source_e_e_TBase { } class ClassClassTestClass_SBase_T_Source_e_e_TDer: ClassClassTestClass_SBase_T_Source_e_e_T { } class ClassClassTestClass_SBase_T_Source_e_e { public static bool testMethod() { ClassClassTestClass_SBase_T_Source_e_e_S s = new ClassClassTestClass_SBase_T_Source_e_e_S(); ClassClassTestClass_SBase_T_Source_e_e_T t; try { t = (ClassClassTestClass_SBase_T_Source_e_e_T)s; } catch (System.Exception) { Log.Comment("System.Exception caught"); } return true; } } class ClassClassTestClass_SBase_T_Dest_i_i_SBase { } class ClassClassTestClass_SBase_T_Dest_i_i_S: ClassClassTestClass_SBase_T_Dest_i_i_SBase { } class ClassClassTestClass_SBase_T_Dest_i_i_SDer: ClassClassTestClass_SBase_T_Dest_i_i_S { } class ClassClassTestClass_SBase_T_Dest_i_i_TBase { } class ClassClassTestClass_SBase_T_Dest_i_i_T: ClassClassTestClass_SBase_T_Dest_i_i_TBase { static public implicit operator ClassClassTestClass_SBase_T_Dest_i_i_T(ClassClassTestClass_SBase_T_Dest_i_i_SBase foo) { return new ClassClassTestClass_SBase_T_Dest_i_i_T(); } } class ClassClassTestClass_SBase_T_Dest_i_i_TDer: ClassClassTestClass_SBase_T_Dest_i_i_T { } class ClassClassTestClass_SBase_T_Dest_i_i { public static bool testMethod() { ClassClassTestClass_SBase_T_Dest_i_i_S s = new ClassClassTestClass_SBase_T_Dest_i_i_S(); ClassClassTestClass_SBase_T_Dest_i_i_T t; try { t = s; } catch (System.Exception) { Log.Comment("System.Exception caught"); } return true; } } class ClassClassTestClass_SBase_T_Dest_i_e_SBase { } class ClassClassTestClass_SBase_T_Dest_i_e_S: ClassClassTestClass_SBase_T_Dest_i_e_SBase { } class ClassClassTestClass_SBase_T_Dest_i_e_SDer: ClassClassTestClass_SBase_T_Dest_i_e_S { } class ClassClassTestClass_SBase_T_Dest_i_e_TBase { } class ClassClassTestClass_SBase_T_Dest_i_e_T: ClassClassTestClass_SBase_T_Dest_i_e_TBase { static public implicit operator ClassClassTestClass_SBase_T_Dest_i_e_T(ClassClassTestClass_SBase_T_Dest_i_e_SBase foo) { return new ClassClassTestClass_SBase_T_Dest_i_e_T(); } } class ClassClassTestClass_SBase_T_Dest_i_e_TDer: ClassClassTestClass_SBase_T_Dest_i_e_T { } class ClassClassTestClass_SBase_T_Dest_i_e { public static bool testMethod() { ClassClassTestClass_SBase_T_Dest_i_e_S s = new ClassClassTestClass_SBase_T_Dest_i_e_S(); ClassClassTestClass_SBase_T_Dest_i_e_T t; try { t = (ClassClassTestClass_SBase_T_Dest_i_e_T)s; } catch (System.Exception) { Log.Comment("System.Exception caught"); } return true; } } class ClassClassTestClass_SBase_T_Dest_e_e_SBase { } class ClassClassTestClass_SBase_T_Dest_e_e_S: ClassClassTestClass_SBase_T_Dest_e_e_SBase { } class ClassClassTestClass_SBase_T_Dest_e_e_SDer: ClassClassTestClass_SBase_T_Dest_e_e_S { } class ClassClassTestClass_SBase_T_Dest_e_e_TBase { } class ClassClassTestClass_SBase_T_Dest_e_e_T: ClassClassTestClass_SBase_T_Dest_e_e_TBase { static public explicit operator ClassClassTestClass_SBase_T_Dest_e_e_T(ClassClassTestClass_SBase_T_Dest_e_e_SBase foo) { return new ClassClassTestClass_SBase_T_Dest_e_e_T(); } } class ClassClassTestClass_SBase_T_Dest_e_e_TDer: ClassClassTestClass_SBase_T_Dest_e_e_T { } class ClassClassTestClass_SBase_T_Dest_e_e { public static bool testMethod() { ClassClassTestClass_SBase_T_Dest_e_e_S s = new ClassClassTestClass_SBase_T_Dest_e_e_S(); ClassClassTestClass_SBase_T_Dest_e_e_T t; try { t = (ClassClassTestClass_SBase_T_Dest_e_e_T)s; } catch (System.Exception) { Log.Comment("System.Exception caught"); } return true; } } class ClassClassTestClass_SBase_TDer_Source_i_i_SBase { static public implicit operator ClassClassTestClass_SBase_TDer_Source_i_i_TDer(ClassClassTestClass_SBase_TDer_Source_i_i_SBase foo) { return new ClassClassTestClass_SBase_TDer_Source_i_i_TDer(); } } class ClassClassTestClass_SBase_TDer_Source_i_i_S: ClassClassTestClass_SBase_TDer_Source_i_i_SBase { } class ClassClassTestClass_SBase_TDer_Source_i_i_SDer: ClassClassTestClass_SBase_TDer_Source_i_i_S { } class ClassClassTestClass_SBase_TDer_Source_i_i_TBase { } class ClassClassTestClass_SBase_TDer_Source_i_i_T: ClassClassTestClass_SBase_TDer_Source_i_i_TBase { } class ClassClassTestClass_SBase_TDer_Source_i_i_TDer: ClassClassTestClass_SBase_TDer_Source_i_i_T { } class ClassClassTestClass_SBase_TDer_Source_i_i { public static bool testMethod() { ClassClassTestClass_SBase_TDer_Source_i_i_S s= new ClassClassTestClass_SBase_TDer_Source_i_i_S(); ClassClassTestClass_SBase_TDer_Source_i_i_T t; try { t = s; } catch (System.Exception) { Log.Comment("System.Exception caught"); } return true; } } class ClassClassTestClass_SBase_TDer_Source_i_e_SBase { static public implicit operator ClassClassTestClass_SBase_TDer_Source_i_e_TDer(ClassClassTestClass_SBase_TDer_Source_i_e_SBase foo) { return new ClassClassTestClass_SBase_TDer_Source_i_e_TDer(); } } class ClassClassTestClass_SBase_TDer_Source_i_e_S: ClassClassTestClass_SBase_TDer_Source_i_e_SBase { } class ClassClassTestClass_SBase_TDer_Source_i_e_SDer: ClassClassTestClass_SBase_TDer_Source_i_e_S { } class ClassClassTestClass_SBase_TDer_Source_i_e_TBase { } class ClassClassTestClass_SBase_TDer_Source_i_e_T: ClassClassTestClass_SBase_TDer_Source_i_e_TBase { } class ClassClassTestClass_SBase_TDer_Source_i_e_TDer: ClassClassTestClass_SBase_TDer_Source_i_e_T { } class ClassClassTestClass_SBase_TDer_Source_i_e { public static bool testMethod() { ClassClassTestClass_SBase_TDer_Source_i_e_S s = new ClassClassTestClass_SBase_TDer_Source_i_e_S(); ClassClassTestClass_SBase_TDer_Source_i_e_T t; try { t = (ClassClassTestClass_SBase_TDer_Source_i_e_T)s; } catch (System.Exception) { Log.Comment("System.Exception caught"); } return true; } } class ClassClassTestClass_SBase_TDer_Source_e_e_SBase { static public explicit operator ClassClassTestClass_SBase_TDer_Source_e_e_TDer(ClassClassTestClass_SBase_TDer_Source_e_e_SBase foo) { return new ClassClassTestClass_SBase_TDer_Source_e_e_TDer(); } } class ClassClassTestClass_SBase_TDer_Source_e_e_S: ClassClassTestClass_SBase_TDer_Source_e_e_SBase { } class ClassClassTestClass_SBase_TDer_Source_e_e_SDer: ClassClassTestClass_SBase_TDer_Source_e_e_S { } class ClassClassTestClass_SBase_TDer_Source_e_e_TBase { } class ClassClassTestClass_SBase_TDer_Source_e_e_T: ClassClassTestClass_SBase_TDer_Source_e_e_TBase { } class ClassClassTestClass_SBase_TDer_Source_e_e_TDer: ClassClassTestClass_SBase_TDer_Source_e_e_T { } class ClassClassTestClass_SBase_TDer_Source_e_e { public static bool testMethod() { ClassClassTestClass_SBase_TDer_Source_e_e_S s = new ClassClassTestClass_SBase_TDer_Source_e_e_S(); ClassClassTestClass_SBase_TDer_Source_e_e_T t; try { t = (ClassClassTestClass_SBase_TDer_Source_e_e_T)s; } catch (System.Exception) { Log.Comment("System.Exception caught"); } return true; } } class ClassClassTestClass_S_TBase_Source_i_e_SBase { } class ClassClassTestClass_S_TBase_Source_i_e_S: ClassClassTestClass_S_TBase_Source_i_e_SBase { static public implicit operator ClassClassTestClass_S_TBase_Source_i_e_TBase(ClassClassTestClass_S_TBase_Source_i_e_S foo) { return new ClassClassTestClass_S_TBase_Source_i_e_TBase(); } } class ClassClassTestClass_S_TBase_Source_i_e_SDer: ClassClassTestClass_S_TBase_Source_i_e_S { } class ClassClassTestClass_S_TBase_Source_i_e_TBase { } class ClassClassTestClass_S_TBase_Source_i_e_T: ClassClassTestClass_S_TBase_Source_i_e_TBase { } class ClassClassTestClass_S_TBase_Source_i_e_TDer: ClassClassTestClass_S_TBase_Source_i_e_T { } class ClassClassTestClass_S_TBase_Source_i_e { public static bool testMethod() { ClassClassTestClass_S_TBase_Source_i_e_S s = new ClassClassTestClass_S_TBase_Source_i_e_S(); ClassClassTestClass_S_TBase_Source_i_e_T t; try { t = (ClassClassTestClass_S_TBase_Source_i_e_T)s; } catch (System.Exception) { Log.Comment("System.Exception caught"); } return true; } } class ClassClassTestClass_S_TBase_Source_e_e_SBase { } class ClassClassTestClass_S_TBase_Source_e_e_S: ClassClassTestClass_S_TBase_Source_e_e_SBase { static public explicit operator ClassClassTestClass_S_TBase_Source_e_e_TBase(ClassClassTestClass_S_TBase_Source_e_e_S foo) { return new ClassClassTestClass_S_TBase_Source_e_e_TBase(); } } class ClassClassTestClass_S_TBase_Source_e_e_SDer: ClassClassTestClass_S_TBase_Source_e_e_S { } class ClassClassTestClass_S_TBase_Source_e_e_TBase { } class ClassClassTestClass_S_TBase_Source_e_e_T: ClassClassTestClass_S_TBase_Source_e_e_TBase { } class ClassClassTestClass_S_TBase_Source_e_e_TDer: ClassClassTestClass_S_TBase_Source_e_e_T { } class ClassClassTestClass_S_TBase_Source_e_e { public static bool testMethod() { ClassClassTestClass_S_TBase_Source_e_e_S s = new ClassClassTestClass_S_TBase_Source_e_e_S(); ClassClassTestClass_S_TBase_Source_e_e_T t; try { t = (ClassClassTestClass_S_TBase_Source_e_e_T)s; } catch (System.Exception) { Log.Comment("System.Exception caught"); } return true; } } class ClassClassTestClass_S_TBase_Dest_i_e_SBase { } class ClassClassTestClass_S_TBase_Dest_i_e_S: ClassClassTestClass_S_TBase_Dest_i_e_SBase { } class ClassClassTestClass_S_TBase_Dest_i_e_SDer: ClassClassTestClass_S_TBase_Dest_i_e_S { } class ClassClassTestClass_S_TBase_Dest_i_e_TBase { static public implicit operator ClassClassTestClass_S_TBase_Dest_i_e_TBase(ClassClassTestClass_S_TBase_Dest_i_e_S foo) { return new ClassClassTestClass_S_TBase_Dest_i_e_TBase(); } } class ClassClassTestClass_S_TBase_Dest_i_e_T: ClassClassTestClass_S_TBase_Dest_i_e_TBase { } class ClassClassTestClass_S_TBase_Dest_i_e_TDer: ClassClassTestClass_S_TBase_Dest_i_e_T { } class ClassClassTestClass_S_TBase_Dest_i_e { public static bool testMethod() { ClassClassTestClass_S_TBase_Dest_i_e_S s = new ClassClassTestClass_S_TBase_Dest_i_e_S(); ClassClassTestClass_S_TBase_Dest_i_e_T t; try { t = (ClassClassTestClass_S_TBase_Dest_i_e_T)s; } catch (System.Exception) { Log.Comment("System.Exception caught"); } return true; } } class ClassClassTestClass_S_TBase_Dest_e_e_SBase { } class ClassClassTestClass_S_TBase_Dest_e_e_S: ClassClassTestClass_S_TBase_Dest_e_e_SBase { } class ClassClassTestClass_S_TBase_Dest_e_e_SDer: ClassClassTestClass_S_TBase_Dest_e_e_S { } class ClassClassTestClass_S_TBase_Dest_e_e_TBase { static public explicit operator ClassClassTestClass_S_TBase_Dest_e_e_TBase(ClassClassTestClass_S_TBase_Dest_e_e_S foo) { return new ClassClassTestClass_S_TBase_Dest_e_e_TBase(); } } class ClassClassTestClass_S_TBase_Dest_e_e_T: ClassClassTestClass_S_TBase_Dest_e_e_TBase { } class ClassClassTestClass_S_TBase_Dest_e_e_TDer: ClassClassTestClass_S_TBase_Dest_e_e_T { } class ClassClassTestClass_S_TBase_Dest_e_e { public static bool testMethod() { ClassClassTestClass_S_TBase_Dest_e_e_S s = new ClassClassTestClass_S_TBase_Dest_e_e_S(); ClassClassTestClass_S_TBase_Dest_e_e_T t; try { t = (ClassClassTestClass_S_TBase_Dest_e_e_T)s; } catch (System.Exception) { Log.Comment("System.Exception caught"); } return true; } } class ClassClassTestClass_S_T_Source_i_i_SBase { } class ClassClassTestClass_S_T_Source_i_i_S: ClassClassTestClass_S_T_Source_i_i_SBase { static public implicit operator ClassClassTestClass_S_T_Source_i_i_T(ClassClassTestClass_S_T_Source_i_i_S foo) { return new ClassClassTestClass_S_T_Source_i_i_T(); } } class ClassClassTestClass_S_T_Source_i_i_SDer: ClassClassTestClass_S_T_Source_i_i_S { } class ClassClassTestClass_S_T_Source_i_i_TBase { } class ClassClassTestClass_S_T_Source_i_i_T: ClassClassTestClass_S_T_Source_i_i_TBase { } class ClassClassTestClass_S_T_Source_i_i_TDer: ClassClassTestClass_S_T_Source_i_i_T { } class ClassClassTestClass_S_T_Source_i_i { public static bool testMethod() { ClassClassTestClass_S_T_Source_i_i_S s = new ClassClassTestClass_S_T_Source_i_i_S(); ClassClassTestClass_S_T_Source_i_i_T t; try { t = s; } catch (System.Exception) { Log.Comment("System.Exception caught"); } return true; } } class ClassClassTestClass_S_T_Source_i_e_SBase { } class ClassClassTestClass_S_T_Source_i_e_S: ClassClassTestClass_S_T_Source_i_e_SBase { static public implicit operator ClassClassTestClass_S_T_Source_i_e_T(ClassClassTestClass_S_T_Source_i_e_S foo) { return new ClassClassTestClass_S_T_Source_i_e_T(); } } class ClassClassTestClass_S_T_Source_i_e_SDer: ClassClassTestClass_S_T_Source_i_e_S { } class ClassClassTestClass_S_T_Source_i_e_TBase { } class ClassClassTestClass_S_T_Source_i_e_T: ClassClassTestClass_S_T_Source_i_e_TBase { } class ClassClassTestClass_S_T_Source_i_e_TDer: ClassClassTestClass_S_T_Source_i_e_T { } class ClassClassTestClass_S_T_Source_i_e { public static bool testMethod() { ClassClassTestClass_S_T_Source_i_e_S s = new ClassClassTestClass_S_T_Source_i_e_S(); ClassClassTestClass_S_T_Source_i_e_T t; try { t = (ClassClassTestClass_S_T_Source_i_e_T)s; } catch (System.Exception) { Log.Comment("System.Exception caught"); } return true; } } class ClassClassTestClass_S_T_Source_e_e_SBase { } class ClassClassTestClass_S_T_Source_e_e_S: ClassClassTestClass_S_T_Source_e_e_SBase { static public explicit operator ClassClassTestClass_S_T_Source_e_e_T(ClassClassTestClass_S_T_Source_e_e_S foo) { return new ClassClassTestClass_S_T_Source_e_e_T(); } } class ClassClassTestClass_S_T_Source_e_e_SDer: ClassClassTestClass_S_T_Source_e_e_S { } class ClassClassTestClass_S_T_Source_e_e_TBase { } class ClassClassTestClass_S_T_Source_e_e_T: ClassClassTestClass_S_T_Source_e_e_TBase { } class ClassClassTestClass_S_T_Source_e_e_TDer: ClassClassTestClass_S_T_Source_e_e_T { } class ClassClassTestClass_S_T_Source_e_e { public static bool testMethod() { ClassClassTestClass_S_T_Source_e_e_S s = new ClassClassTestClass_S_T_Source_e_e_S(); ClassClassTestClass_S_T_Source_e_e_T t; try { t = (ClassClassTestClass_S_T_Source_e_e_T)s; } catch (System.Exception) { Log.Comment("System.Exception caught"); } return true; } } class ClassClassTestClass_S_T_Dest_i_i_SBase { } class ClassClassTestClass_S_T_Dest_i_i_S: ClassClassTestClass_S_T_Dest_i_i_SBase { } class ClassClassTestClass_S_T_Dest_i_i_SDer: ClassClassTestClass_S_T_Dest_i_i_S { } class ClassClassTestClass_S_T_Dest_i_i_TBase { } class ClassClassTestClass_S_T_Dest_i_i_T: ClassClassTestClass_S_T_Dest_i_i_TBase { static public implicit operator ClassClassTestClass_S_T_Dest_i_i_T(ClassClassTestClass_S_T_Dest_i_i_S foo) { return new ClassClassTestClass_S_T_Dest_i_i_T(); } } class ClassClassTestClass_S_T_Dest_i_i_TDer: ClassClassTestClass_S_T_Dest_i_i_T { } class ClassClassTestClass_S_T_Dest_i_i { public static bool testMethod() { ClassClassTestClass_S_T_Dest_i_i_S s = new ClassClassTestClass_S_T_Dest_i_i_S(); ClassClassTestClass_S_T_Dest_i_i_T t; try { t = s; } catch (System.Exception) { Log.Comment("System.Exception caught"); } return true; } } class ClassClassTestClass_S_T_Dest_i_e_SBase { } class ClassClassTestClass_S_T_Dest_i_e_S: ClassClassTestClass_S_T_Dest_i_e_SBase { } class ClassClassTestClass_S_T_Dest_i_e_SDer: ClassClassTestClass_S_T_Dest_i_e_S { } class ClassClassTestClass_S_T_Dest_i_e_TBase { } class ClassClassTestClass_S_T_Dest_i_e_T: ClassClassTestClass_S_T_Dest_i_e_TBase { static public implicit operator ClassClassTestClass_S_T_Dest_i_e_T(ClassClassTestClass_S_T_Dest_i_e_S foo) { return new ClassClassTestClass_S_T_Dest_i_e_T(); } } class ClassClassTestClass_S_T_Dest_i_e_TDer: ClassClassTestClass_S_T_Dest_i_e_T { } class ClassClassTestClass_S_T_Dest_i_e { public static bool testMethod() { ClassClassTestClass_S_T_Dest_i_e_S s = new ClassClassTestClass_S_T_Dest_i_e_S(); ClassClassTestClass_S_T_Dest_i_e_T t; try { t = (ClassClassTestClass_S_T_Dest_i_e_T)s; } catch (System.Exception) { Log.Comment("System.Exception caught"); } return true; } } class ClassClassTestClass_S_T_Dest_e_e_SBase { } class ClassClassTestClass_S_T_Dest_e_e_S: ClassClassTestClass_S_T_Dest_e_e_SBase { } class ClassClassTestClass_S_T_Dest_e_e_SDer: ClassClassTestClass_S_T_Dest_e_e_S { } class ClassClassTestClass_S_T_Dest_e_e_TBase { } class ClassClassTestClass_S_T_Dest_e_e_T: ClassClassTestClass_S_T_Dest_e_e_TBase { static public explicit operator ClassClassTestClass_S_T_Dest_e_e_T(ClassClassTestClass_S_T_Dest_e_e_S foo) { return new ClassClassTestClass_S_T_Dest_e_e_T(); } } class ClassClassTestClass_S_T_Dest_e_e_TDer: ClassClassTestClass_S_T_Dest_e_e_T { } class ClassClassTestClass_S_T_Dest_e_e { public static bool testMethod() { ClassClassTestClass_S_T_Dest_e_e_S s = new ClassClassTestClass_S_T_Dest_e_e_S(); ClassClassTestClass_S_T_Dest_e_e_T t; try { t = (ClassClassTestClass_S_T_Dest_e_e_T)s; } catch (System.Exception) { Log.Comment("System.Exception caught"); } return true; } } class ClassClassTestClass_S_TDer_Source_i_i_SBase { } class ClassClassTestClass_S_TDer_Source_i_i_S: ClassClassTestClass_S_TDer_Source_i_i_SBase { static public implicit operator ClassClassTestClass_S_TDer_Source_i_i_TDer(ClassClassTestClass_S_TDer_Source_i_i_S foo) { return new ClassClassTestClass_S_TDer_Source_i_i_TDer(); } } class ClassClassTestClass_S_TDer_Source_i_i_SDer: ClassClassTestClass_S_TDer_Source_i_i_S { } class ClassClassTestClass_S_TDer_Source_i_i_TBase { } class ClassClassTestClass_S_TDer_Source_i_i_T: ClassClassTestClass_S_TDer_Source_i_i_TBase { } class ClassClassTestClass_S_TDer_Source_i_i_TDer: ClassClassTestClass_S_TDer_Source_i_i_T { } class ClassClassTestClass_S_TDer_Source_i_i { public static bool testMethod() { ClassClassTestClass_S_TDer_Source_i_i_S s = new ClassClassTestClass_S_TDer_Source_i_i_S(); ClassClassTestClass_S_TDer_Source_i_i_T t; try { t = s; } catch (System.Exception) { Log.Comment("System.Exception caught"); } return true; } } class ClassClassTestClass_S_TDer_Source_i_e_SBase { } class ClassClassTestClass_S_TDer_Source_i_e_S: ClassClassTestClass_S_TDer_Source_i_e_SBase { static public implicit operator ClassClassTestClass_S_TDer_Source_i_e_TDer(ClassClassTestClass_S_TDer_Source_i_e_S foo) { return new ClassClassTestClass_S_TDer_Source_i_e_TDer(); } } class ClassClassTestClass_S_TDer_Source_i_e_SDer: ClassClassTestClass_S_TDer_Source_i_e_S { } class ClassClassTestClass_S_TDer_Source_i_e_TBase { } class ClassClassTestClass_S_TDer_Source_i_e_T: ClassClassTestClass_S_TDer_Source_i_e_TBase { } class ClassClassTestClass_S_TDer_Source_i_e_TDer: ClassClassTestClass_S_TDer_Source_i_e_T { } class ClassClassTestClass_S_TDer_Source_i_e { public static bool testMethod() { ClassClassTestClass_S_TDer_Source_i_e_S s = new ClassClassTestClass_S_TDer_Source_i_e_S(); ClassClassTestClass_S_TDer_Source_i_e_T t; try { t = (ClassClassTestClass_S_TDer_Source_i_e_T)s; } catch (System.Exception) { Log.Comment("System.Exception caught"); } return true; } } class ClassClassTestClass_S_TDer_Source_e_e_SBase { } class ClassClassTestClass_S_TDer_Source_e_e_S: ClassClassTestClass_S_TDer_Source_e_e_SBase { static public explicit operator ClassClassTestClass_S_TDer_Source_e_e_TDer(ClassClassTestClass_S_TDer_Source_e_e_S foo) { return new ClassClassTestClass_S_TDer_Source_e_e_TDer(); } } class ClassClassTestClass_S_TDer_Source_e_e_SDer: ClassClassTestClass_S_TDer_Source_e_e_S { } class ClassClassTestClass_S_TDer_Source_e_e_TBase { } class ClassClassTestClass_S_TDer_Source_e_e_T: ClassClassTestClass_S_TDer_Source_e_e_TBase { } class ClassClassTestClass_S_TDer_Source_e_e_TDer: ClassClassTestClass_S_TDer_Source_e_e_T { } class ClassClassTestClass_S_TDer_Source_e_e { public static bool testMethod() { ClassClassTestClass_S_TDer_Source_e_e_S s = new ClassClassTestClass_S_TDer_Source_e_e_S(); ClassClassTestClass_S_TDer_Source_e_e_T t; try { t = (ClassClassTestClass_S_TDer_Source_e_e_T)s; } catch (System.Exception) { Log.Comment("System.Exception caught"); } return true; } } class ClassClassTestClass_SDer_TBase_Dest_i_e_SBase { } class ClassClassTestClass_SDer_TBase_Dest_i_e_S: ClassClassTestClass_SDer_TBase_Dest_i_e_SBase { } class ClassClassTestClass_SDer_TBase_Dest_i_e_SDer: ClassClassTestClass_SDer_TBase_Dest_i_e_S { } class ClassClassTestClass_SDer_TBase_Dest_i_e_TBase { static public implicit operator ClassClassTestClass_SDer_TBase_Dest_i_e_TBase(ClassClassTestClass_SDer_TBase_Dest_i_e_SDer foo) { return new ClassClassTestClass_SDer_TBase_Dest_i_e_TBase(); } } class ClassClassTestClass_SDer_TBase_Dest_i_e_T: ClassClassTestClass_SDer_TBase_Dest_i_e_TBase { } class ClassClassTestClass_SDer_TBase_Dest_i_e_TDer: ClassClassTestClass_SDer_TBase_Dest_i_e_T { } class ClassClassTestClass_SDer_TBase_Dest_i_e { public static bool testMethod() { ClassClassTestClass_SDer_TBase_Dest_i_e_S s = new ClassClassTestClass_SDer_TBase_Dest_i_e_S(); ClassClassTestClass_SDer_TBase_Dest_i_e_T t; try { t = (ClassClassTestClass_SDer_TBase_Dest_i_e_T)s; } catch (System.Exception) { Log.Comment("System.Exception caught"); } return true; } } class ClassClassTestClass_SDer_TBase_Dest_e_e_SBase { } class ClassClassTestClass_SDer_TBase_Dest_e_e_S: ClassClassTestClass_SDer_TBase_Dest_e_e_SBase { } class ClassClassTestClass_SDer_TBase_Dest_e_e_SDer: ClassClassTestClass_SDer_TBase_Dest_e_e_S { } class ClassClassTestClass_SDer_TBase_Dest_e_e_TBase { static public explicit operator ClassClassTestClass_SDer_TBase_Dest_e_e_TBase(ClassClassTestClass_SDer_TBase_Dest_e_e_SDer foo) { return new ClassClassTestClass_SDer_TBase_Dest_e_e_TBase(); } } class ClassClassTestClass_SDer_TBase_Dest_e_e_T: ClassClassTestClass_SDer_TBase_Dest_e_e_TBase { } class ClassClassTestClass_SDer_TBase_Dest_e_e_TDer: ClassClassTestClass_SDer_TBase_Dest_e_e_T { } class ClassClassTestClass_SDer_TBase_Dest_e_e { public static bool testMethod() { ClassClassTestClass_SDer_TBase_Dest_e_e_S s = new ClassClassTestClass_SDer_TBase_Dest_e_e_S(); ClassClassTestClass_SDer_TBase_Dest_e_e_T t; try { t = (ClassClassTestClass_SDer_TBase_Dest_e_e_T)s; } catch (System.Exception) { Log.Comment("System.Exception caught"); } return true; } } class ClassClassTestClass_SDer_T_Dest_i_e_SBase { } class ClassClassTestClass_SDer_T_Dest_i_e_S: ClassClassTestClass_SDer_T_Dest_i_e_SBase { } class ClassClassTestClass_SDer_T_Dest_i_e_SDer: ClassClassTestClass_SDer_T_Dest_i_e_S { } class ClassClassTestClass_SDer_T_Dest_i_e_TBase { } class ClassClassTestClass_SDer_T_Dest_i_e_T: ClassClassTestClass_SDer_T_Dest_i_e_TBase { static public implicit operator ClassClassTestClass_SDer_T_Dest_i_e_T(ClassClassTestClass_SDer_T_Dest_i_e_SDer foo) { return new ClassClassTestClass_SDer_T_Dest_i_e_T(); } } class ClassClassTestClass_SDer_T_Dest_i_e_TDer: ClassClassTestClass_SDer_T_Dest_i_e_T { } class ClassClassTestClass_SDer_T_Dest_i_e { public static bool testMethod() { ClassClassTestClass_SDer_T_Dest_i_e_S s = new ClassClassTestClass_SDer_T_Dest_i_e_S(); ClassClassTestClass_SDer_T_Dest_i_e_T t; try { t = (ClassClassTestClass_SDer_T_Dest_i_e_T)s; } catch (System.Exception) { Log.Comment("System.Exception caught"); } return true; } } class ClassClassTestClass_SDer_T_Dest_e_e_SBase { } class ClassClassTestClass_SDer_T_Dest_e_e_S: ClassClassTestClass_SDer_T_Dest_e_e_SBase { } class ClassClassTestClass_SDer_T_Dest_e_e_SDer: ClassClassTestClass_SDer_T_Dest_e_e_S { } class ClassClassTestClass_SDer_T_Dest_e_e_TBase { } class ClassClassTestClass_SDer_T_Dest_e_e_T: ClassClassTestClass_SDer_T_Dest_e_e_TBase { static public explicit operator ClassClassTestClass_SDer_T_Dest_e_e_T(ClassClassTestClass_SDer_T_Dest_e_e_SDer foo) { return new ClassClassTestClass_SDer_T_Dest_e_e_T(); } } class ClassClassTestClass_SDer_T_Dest_e_e_TDer: ClassClassTestClass_SDer_T_Dest_e_e_T { } class ClassClassTestClass_SDer_T_Dest_e_e { public static bool testMethod() { ClassClassTestClass_SDer_T_Dest_e_e_S s = new ClassClassTestClass_SDer_T_Dest_e_e_S(); ClassClassTestClass_SDer_T_Dest_e_e_T t; try { t = (ClassClassTestClass_SDer_T_Dest_e_e_T)s; } catch (System.Exception) { Log.Comment("System.Exception caught"); } return true; } } } } ================================================ FILE: Zelig/Zelig/Test/RunTime/NETMF/mscorlib/conversions/user/ClassStructTests.cs ================================================ //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // Copyright (c) Microsoft Corporation. All rights reserved. //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// using System; namespace Microsoft.Zelig.Test { public class ClassStructTests : TestBase, ITestInterface { [SetUp] public InitializeResult Initialize() { Log.Comment("Adding set up for the tests."); Log.Comment("Adding set up for the tests"); Log.Comment("These tests examine the conversion (casting) of classes to structs"); Log.Comment("The is a tree of classes SDer : S : SBase and a struct T"); Log.Comment("The names of the tests describe the tests by listing which two objects will be converted between"); Log.Comment("Followed by which (The source or the destination) will contain a cast definition"); Log.Comment("Followed further by 'i's or 'e's to indicate which of the cast definition and the actual cast are"); Log.Comment("implicit or explicit."); Log.Comment(""); Log.Comment("For example, SBase_T_Source_i_e tests the conversion of SBase to T, with an implicit definition"); Log.Comment("of the cast in the SBase class, and an explicit cast in the body of the method."); // Add your functionality here. return InitializeResult.ReadyToGo; } [TearDown] public void CleanUp() { Log.Comment("Cleaning up after the tests"); } public override TestResult Run( string[] args ) { TestResult result = TestResult.Pass; string testName = "ClassStruct_"; int testNumber = 0; result |= Assert.CheckFailed( ClassStruct_SBase_T_Source_i_i_Test( ), testName, ++testNumber ); result |= Assert.CheckFailed( ClassStruct_SBase_T_Source_i_e_Test( ), testName, ++testNumber ); result |= Assert.CheckFailed( ClassStruct_SBase_T_Source_e_e_Test( ), testName, ++testNumber ); result |= Assert.CheckFailed( ClassStruct_SBase_T_Dest_i_i_Test( ), testName, ++testNumber ); result |= Assert.CheckFailed( ClassStruct_SBase_T_Dest_i_e_Test( ), testName, ++testNumber ); result |= Assert.CheckFailed( ClassStruct_SBase_T_Dest_e_e_Test( ), testName, ++testNumber ); result |= Assert.CheckFailed( ClassStruct_S_T_Source_i_i_Test( ), testName, ++testNumber ); result |= Assert.CheckFailed( ClassStruct_S_T_Source_i_e_Test( ), testName, ++testNumber ); result |= Assert.CheckFailed( ClassStruct_S_T_Source_e_e_Test( ), testName, ++testNumber ); result |= Assert.CheckFailed( ClassStruct_S_T_Dest_i_i_Test( ), testName, ++testNumber ); result |= Assert.CheckFailed( ClassStruct_S_T_Dest_i_e_Test( ), testName, ++testNumber ); result |= Assert.CheckFailed( ClassStruct_S_T_Dest_e_e_Test( ), testName, ++testNumber ); result |= Assert.CheckFailed( ClassStruct_SDer_T_Dest_i_e_Test( ), testName, ++testNumber ); result |= Assert.CheckFailed( ClassStruct_SDer_T_Dest_e_e_Test( ), testName, ++testNumber ); result |= Assert.CheckFailed( ClassStruct_null_to_struct_e_Test( ), testName, ++testNumber ); result |= Assert.CheckFailed( ClassStruct_null_to_struct_i_Test( ), testName, ++testNumber ); return result; } //ClassStruct Test methods //The following tests were ported from folder current\test\cases\client\CLR\Conformance\10_classes\ClassStruct //Test Case Calls [TestMethod] public TestResult ClassStruct_SBase_T_Source_i_i_Test() { if (ClassStructTestClass_SBase_T_Source_i_i.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult ClassStruct_SBase_T_Source_i_e_Test() { if (ClassStructTestClass_SBase_T_Source_i_e.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult ClassStruct_SBase_T_Source_e_e_Test() { if (ClassStructTestClass_SBase_T_Source_e_e.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult ClassStruct_SBase_T_Dest_i_i_Test() { if (ClassStructTestClass_SBase_T_Dest_i_i.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult ClassStruct_SBase_T_Dest_i_e_Test() { if (ClassStructTestClass_SBase_T_Dest_i_e.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult ClassStruct_SBase_T_Dest_e_e_Test() { if (ClassStructTestClass_SBase_T_Dest_e_e.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult ClassStruct_S_T_Source_i_i_Test() { if (ClassStructTestClass_S_T_Source_i_i.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult ClassStruct_S_T_Source_i_e_Test() { if (ClassStructTestClass_S_T_Source_i_e.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult ClassStruct_S_T_Source_e_e_Test() { if (ClassStructTestClass_S_T_Source_e_e.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult ClassStruct_S_T_Dest_i_i_Test() { if (ClassStructTestClass_S_T_Dest_i_i.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult ClassStruct_S_T_Dest_i_e_Test() { if (ClassStructTestClass_S_T_Dest_i_e.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult ClassStruct_S_T_Dest_e_e_Test() { if (ClassStructTestClass_S_T_Dest_e_e.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult ClassStruct_SDer_T_Dest_i_e_Test() { if (ClassStructTestClass_SDer_T_Dest_i_e.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult ClassStruct_SDer_T_Dest_e_e_Test() { if (ClassStructTestClass_SDer_T_Dest_e_e.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult ClassStruct_null_to_struct_e_Test() { if (ClassStructTestClass_null_to_struct_e.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult ClassStruct_null_to_struct_i_Test() { if (ClassStructTestClass_null_to_struct_i.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } //Compiled Test Cases class ClassStructTestClass_SBase_T_Source_i_i_SBase { static public implicit operator ClassStructTestClass_SBase_T_Source_i_i_T(ClassStructTestClass_SBase_T_Source_i_i_SBase foo) { Log.Comment(" ClassStructTestClass_SBase_T_Source_i_i_SBase to ClassStructTestClass_SBase_T_Source_i_i_T Source implicit"); return new ClassStructTestClass_SBase_T_Source_i_i_T(); } } class ClassStructTestClass_SBase_T_Source_i_i_S : ClassStructTestClass_SBase_T_Source_i_i_SBase { } class ClassStructTestClass_SBase_T_Source_i_i_SDer : ClassStructTestClass_SBase_T_Source_i_i_S { } struct ClassStructTestClass_SBase_T_Source_i_i_T { } class ClassStructTestClass_SBase_T_Source_i_i { public static void Main_old() { ClassStructTestClass_SBase_T_Source_i_i_S s = new ClassStructTestClass_SBase_T_Source_i_i_S(); ClassStructTestClass_SBase_T_Source_i_i_T t; try { t = s; } catch (System.Exception) { Log.Comment("System.Exception Caught"); } } public static bool testMethod() { Main_old(); return true; } } class ClassStructTestClass_SBase_T_Source_i_e_SBase { static public implicit operator ClassStructTestClass_SBase_T_Source_i_e_T(ClassStructTestClass_SBase_T_Source_i_e_SBase foo) { Log.Comment(" ClassStructTestClass_SBase_T_Source_i_e_SBase to ClassStructTestClass_SBase_T_Source_i_e_T Source implicit"); return new ClassStructTestClass_SBase_T_Source_i_e_T(); } } class ClassStructTestClass_SBase_T_Source_i_e_S : ClassStructTestClass_SBase_T_Source_i_e_SBase { } class ClassStructTestClass_SBase_T_Source_i_e_SDer : ClassStructTestClass_SBase_T_Source_i_e_S { } struct ClassStructTestClass_SBase_T_Source_i_e_T { } class ClassStructTestClass_SBase_T_Source_i_e { public static void Main_old() { ClassStructTestClass_SBase_T_Source_i_e_S s = new ClassStructTestClass_SBase_T_Source_i_e_S(); ClassStructTestClass_SBase_T_Source_i_e_T t; try { t = (ClassStructTestClass_SBase_T_Source_i_e_T)s; } catch (System.Exception) { Log.Comment("System.Exception Caught"); } } public static bool testMethod() { Main_old(); return true; } } class ClassStructTestClass_SBase_T_Source_e_e_SBase { static public explicit operator ClassStructTestClass_SBase_T_Source_e_e_T(ClassStructTestClass_SBase_T_Source_e_e_SBase foo) { Log.Comment(" ClassStructTestClass_SBase_T_Source_e_e_SBase to ClassStructTestClass_SBase_T_Source_e_e_T Source explicit"); return new ClassStructTestClass_SBase_T_Source_e_e_T(); } } class ClassStructTestClass_SBase_T_Source_e_e_S : ClassStructTestClass_SBase_T_Source_e_e_SBase { } class ClassStructTestClass_SBase_T_Source_e_e_SDer : ClassStructTestClass_SBase_T_Source_e_e_S { } struct ClassStructTestClass_SBase_T_Source_e_e_T { } class ClassStructTestClass_SBase_T_Source_e_e { public static void Main_old() { ClassStructTestClass_SBase_T_Source_e_e_S s = new ClassStructTestClass_SBase_T_Source_e_e_S(); ClassStructTestClass_SBase_T_Source_e_e_T t; try { t = (ClassStructTestClass_SBase_T_Source_e_e_T)s; } catch (System.Exception) { Log.Comment("System.Exception Caught"); } } public static bool testMethod() { Main_old(); return true; } } class ClassStructTestClass_SBase_T_Dest_i_i_SBase { } class ClassStructTestClass_SBase_T_Dest_i_i_S : ClassStructTestClass_SBase_T_Dest_i_i_SBase { } class ClassStructTestClass_SBase_T_Dest_i_i_SDer : ClassStructTestClass_SBase_T_Dest_i_i_S { } struct ClassStructTestClass_SBase_T_Dest_i_i_T { static public implicit operator ClassStructTestClass_SBase_T_Dest_i_i_T(ClassStructTestClass_SBase_T_Dest_i_i_SBase foo) { Log.Comment(" ClassStructTestClass_SBase_T_Dest_i_i_SBase to ClassStructTestClass_SBase_T_Dest_i_i_T Dest implicit"); return new ClassStructTestClass_SBase_T_Dest_i_i_T(); } } class ClassStructTestClass_SBase_T_Dest_i_i { public static void Main_old() { ClassStructTestClass_SBase_T_Dest_i_i_S s = new ClassStructTestClass_SBase_T_Dest_i_i_S(); ClassStructTestClass_SBase_T_Dest_i_i_T t; try { t = s; } catch (System.Exception) { Log.Comment("System.Exception Caught"); } } public static bool testMethod() { Main_old(); return true; } } class ClassStructTestClass_SBase_T_Dest_i_e_SBase { } class ClassStructTestClass_SBase_T_Dest_i_e_S : ClassStructTestClass_SBase_T_Dest_i_e_SBase { } class ClassStructTestClass_SBase_T_Dest_i_e_SDer : ClassStructTestClass_SBase_T_Dest_i_e_S { } struct ClassStructTestClass_SBase_T_Dest_i_e_T { static public implicit operator ClassStructTestClass_SBase_T_Dest_i_e_T(ClassStructTestClass_SBase_T_Dest_i_e_SBase foo) { Log.Comment(" ClassStructTestClass_SBase_T_Dest_i_e_SBase to ClassStructTestClass_SBase_T_Dest_i_e_T Dest implicit"); return new ClassStructTestClass_SBase_T_Dest_i_e_T(); } } class ClassStructTestClass_SBase_T_Dest_i_e { public static void Main_old() { ClassStructTestClass_SBase_T_Dest_i_e_S s = new ClassStructTestClass_SBase_T_Dest_i_e_S(); ClassStructTestClass_SBase_T_Dest_i_e_T t; try { t = (ClassStructTestClass_SBase_T_Dest_i_e_T)s; } catch (System.Exception) { Log.Comment("System.Exception Caught"); } } public static bool testMethod() { Main_old(); return true; } } class ClassStructTestClass_SBase_T_Dest_e_e_SBase { } class ClassStructTestClass_SBase_T_Dest_e_e_S : ClassStructTestClass_SBase_T_Dest_e_e_SBase { } class ClassStructTestClass_SBase_T_Dest_e_e_SDer : ClassStructTestClass_SBase_T_Dest_e_e_S { } struct ClassStructTestClass_SBase_T_Dest_e_e_T { static public explicit operator ClassStructTestClass_SBase_T_Dest_e_e_T(ClassStructTestClass_SBase_T_Dest_e_e_SBase foo) { Log.Comment(" ClassStructTestClass_SBase_T_Dest_e_e_SBase to ClassStructTestClass_SBase_T_Dest_e_e_T Dest explicit"); return new ClassStructTestClass_SBase_T_Dest_e_e_T(); } } class ClassStructTestClass_SBase_T_Dest_e_e { public static void Main_old() { ClassStructTestClass_SBase_T_Dest_e_e_S s = new ClassStructTestClass_SBase_T_Dest_e_e_S(); ClassStructTestClass_SBase_T_Dest_e_e_T t; try { t = (ClassStructTestClass_SBase_T_Dest_e_e_T)s; } catch (System.Exception) { Log.Comment("System.Exception Caught"); } } public static bool testMethod() { Main_old(); return true; } } class ClassStructTestClass_S_T_Source_i_i_SBase { } class ClassStructTestClass_S_T_Source_i_i_S : ClassStructTestClass_S_T_Source_i_i_SBase { static public implicit operator ClassStructTestClass_S_T_Source_i_i_T(ClassStructTestClass_S_T_Source_i_i_S foo) { Log.Comment(" ClassStructTestClass_S_T_Source_i_i_S to ClassStructTestClass_S_T_Source_i_i_T Source implicit"); return new ClassStructTestClass_S_T_Source_i_i_T(); } } class ClassStructTestClass_S_T_Source_i_i_SDer : ClassStructTestClass_S_T_Source_i_i_S { } struct ClassStructTestClass_S_T_Source_i_i_T { } class ClassStructTestClass_S_T_Source_i_i { public static void Main_old() { ClassStructTestClass_S_T_Source_i_i_S s = new ClassStructTestClass_S_T_Source_i_i_S(); ClassStructTestClass_S_T_Source_i_i_T t; try { t = s; } catch (System.Exception) { Log.Comment("System.Exception Caught"); } } public static bool testMethod() { Main_old(); return true; } } class ClassStructTestClass_S_T_Source_i_e_SBase { } class ClassStructTestClass_S_T_Source_i_e_S : ClassStructTestClass_S_T_Source_i_e_SBase { static public implicit operator ClassStructTestClass_S_T_Source_i_e_T(ClassStructTestClass_S_T_Source_i_e_S foo) { Log.Comment(" ClassStructTestClass_S_T_Source_i_e_S to ClassStructTestClass_S_T_Source_i_e_T Source implicit"); return new ClassStructTestClass_S_T_Source_i_e_T(); } } class ClassStructTestClass_S_T_Source_i_e_SDer : ClassStructTestClass_S_T_Source_i_e_S { } struct ClassStructTestClass_S_T_Source_i_e_T { } class ClassStructTestClass_S_T_Source_i_e { public static void Main_old() { ClassStructTestClass_S_T_Source_i_e_S s = new ClassStructTestClass_S_T_Source_i_e_S(); ClassStructTestClass_S_T_Source_i_e_T t; try { t = (ClassStructTestClass_S_T_Source_i_e_T)s; } catch (System.Exception) { Log.Comment("System.Exception Caught"); } } public static bool testMethod() { Main_old(); return true; } } class ClassStructTestClass_S_T_Source_e_e_SBase { } class ClassStructTestClass_S_T_Source_e_e_S : ClassStructTestClass_S_T_Source_e_e_SBase { static public explicit operator ClassStructTestClass_S_T_Source_e_e_T(ClassStructTestClass_S_T_Source_e_e_S foo) { Log.Comment(" ClassStructTestClass_S_T_Source_e_e_S to ClassStructTestClass_S_T_Source_e_e_T Source explicit"); return new ClassStructTestClass_S_T_Source_e_e_T(); } } class ClassStructTestClass_S_T_Source_e_e_SDer : ClassStructTestClass_S_T_Source_e_e_S { } struct ClassStructTestClass_S_T_Source_e_e_T { } class ClassStructTestClass_S_T_Source_e_e { public static void Main_old() { ClassStructTestClass_S_T_Source_e_e_S s = new ClassStructTestClass_S_T_Source_e_e_S(); ClassStructTestClass_S_T_Source_e_e_T t; try { t = (ClassStructTestClass_S_T_Source_e_e_T)s; } catch (System.Exception) { Log.Comment("System.Exception Caught"); } } public static bool testMethod() { Main_old(); return true; } } class ClassStructTestClass_S_T_Dest_i_i_SBase { } class ClassStructTestClass_S_T_Dest_i_i_S : ClassStructTestClass_S_T_Dest_i_i_SBase { } class ClassStructTestClass_S_T_Dest_i_i_SDer : ClassStructTestClass_S_T_Dest_i_i_S { } struct ClassStructTestClass_S_T_Dest_i_i_T { static public implicit operator ClassStructTestClass_S_T_Dest_i_i_T(ClassStructTestClass_S_T_Dest_i_i_S foo) { Log.Comment(" ClassStructTestClass_S_T_Dest_i_i_S to ClassStructTestClass_S_T_Dest_i_i_T Dest implicit"); return new ClassStructTestClass_S_T_Dest_i_i_T(); } } class ClassStructTestClass_S_T_Dest_i_i { public static void Main_old() { ClassStructTestClass_S_T_Dest_i_i_S s = new ClassStructTestClass_S_T_Dest_i_i_S(); ClassStructTestClass_S_T_Dest_i_i_T t; try { t = s; } catch (System.Exception) { Log.Comment("System.Exception Caught"); } } public static bool testMethod() { Main_old(); return true; } } class ClassStructTestClass_S_T_Dest_i_e_SBase { } class ClassStructTestClass_S_T_Dest_i_e_S : ClassStructTestClass_S_T_Dest_i_e_SBase { } class ClassStructTestClass_S_T_Dest_i_e_SDer : ClassStructTestClass_S_T_Dest_i_e_S { } struct ClassStructTestClass_S_T_Dest_i_e_T { static public implicit operator ClassStructTestClass_S_T_Dest_i_e_T(ClassStructTestClass_S_T_Dest_i_e_S foo) { Log.Comment(" ClassStructTestClass_S_T_Dest_i_e_S to ClassStructTestClass_S_T_Dest_i_e_T Dest implicit"); return new ClassStructTestClass_S_T_Dest_i_e_T(); } } class ClassStructTestClass_S_T_Dest_i_e { public static void Main_old() { ClassStructTestClass_S_T_Dest_i_e_S s = new ClassStructTestClass_S_T_Dest_i_e_S(); ClassStructTestClass_S_T_Dest_i_e_T t; try { t = (ClassStructTestClass_S_T_Dest_i_e_T)s; } catch (System.Exception) { Log.Comment("System.Exception Caught"); } } public static bool testMethod() { Main_old(); return true; } } class ClassStructTestClass_S_T_Dest_e_e_SBase { } class ClassStructTestClass_S_T_Dest_e_e_S : ClassStructTestClass_S_T_Dest_e_e_SBase { } class ClassStructTestClass_S_T_Dest_e_e_SDer : ClassStructTestClass_S_T_Dest_e_e_S { } struct ClassStructTestClass_S_T_Dest_e_e_T { static public explicit operator ClassStructTestClass_S_T_Dest_e_e_T(ClassStructTestClass_S_T_Dest_e_e_S foo) { Log.Comment(" ClassStructTestClass_S_T_Dest_e_e_S to ClassStructTestClass_S_T_Dest_e_e_T Dest explicit"); return new ClassStructTestClass_S_T_Dest_e_e_T(); } } class ClassStructTestClass_S_T_Dest_e_e { public static void Main_old() { ClassStructTestClass_S_T_Dest_e_e_S s = new ClassStructTestClass_S_T_Dest_e_e_S(); ClassStructTestClass_S_T_Dest_e_e_T t; try { t = (ClassStructTestClass_S_T_Dest_e_e_T)s; } catch (System.Exception) { Log.Comment("System.Exception Caught"); } } public static bool testMethod() { Main_old(); return true; } } class ClassStructTestClass_SDer_T_Dest_i_e_SBase { } class ClassStructTestClass_SDer_T_Dest_i_e_S : ClassStructTestClass_SDer_T_Dest_i_e_SBase { } class ClassStructTestClass_SDer_T_Dest_i_e_SDer : ClassStructTestClass_SDer_T_Dest_i_e_S { } struct ClassStructTestClass_SDer_T_Dest_i_e_T { static public implicit operator ClassStructTestClass_SDer_T_Dest_i_e_T(ClassStructTestClass_SDer_T_Dest_i_e_SDer foo) { Log.Comment(" ClassStructTestClass_SDer_T_Dest_i_e_SDer to ClassStructTestClass_SDer_T_Dest_i_e_T Dest implicit"); return new ClassStructTestClass_SDer_T_Dest_i_e_T(); } } class ClassStructTestClass_SDer_T_Dest_i_e { public static void Main_old() { ClassStructTestClass_SDer_T_Dest_i_e_S s = new ClassStructTestClass_SDer_T_Dest_i_e_S(); ClassStructTestClass_SDer_T_Dest_i_e_T t; try { t = (ClassStructTestClass_SDer_T_Dest_i_e_T)s; } catch (System.Exception) { Log.Comment("System.Exception Caught"); } } public static bool testMethod() { Main_old(); return true; } } class ClassStructTestClass_SDer_T_Dest_e_e_SBase { } class ClassStructTestClass_SDer_T_Dest_e_e_S : ClassStructTestClass_SDer_T_Dest_e_e_SBase { } class ClassStructTestClass_SDer_T_Dest_e_e_SDer : ClassStructTestClass_SDer_T_Dest_e_e_S { } struct ClassStructTestClass_SDer_T_Dest_e_e_T { static public explicit operator ClassStructTestClass_SDer_T_Dest_e_e_T(ClassStructTestClass_SDer_T_Dest_e_e_SDer foo) { Log.Comment(" ClassStructTestClass_SDer_T_Dest_e_e_SDer to ClassStructTestClass_SDer_T_Dest_e_e_T Dest explicit"); return new ClassStructTestClass_SDer_T_Dest_e_e_T(); } } class ClassStructTestClass_SDer_T_Dest_e_e { public static void Main_old() { ClassStructTestClass_SDer_T_Dest_e_e_S s = new ClassStructTestClass_SDer_T_Dest_e_e_S(); ClassStructTestClass_SDer_T_Dest_e_e_T t; try { t = (ClassStructTestClass_SDer_T_Dest_e_e_T)s; } catch (System.Exception) { Log.Comment("System.Exception Caught"); } } public static bool testMethod() { Main_old(); return true; } } public class ClassStructTestClass_null_to_struct_e_C { } public struct ClassStructTestClass_null_to_struct_e_S { public ClassStructTestClass_null_to_struct_e_C c; public ClassStructTestClass_null_to_struct_e_S(ClassStructTestClass_null_to_struct_e_C c) { this.c = c; } public static explicit operator ClassStructTestClass_null_to_struct_e_S(ClassStructTestClass_null_to_struct_e_C c) { return new ClassStructTestClass_null_to_struct_e_S(c); } } public class ClassStructTestClass_null_to_struct_e { public static int Main_old() { ClassStructTestClass_null_to_struct_e_S s = (ClassStructTestClass_null_to_struct_e_S)null; return ((s.c == null) ? 0 : 1); } public static bool testMethod() { if (Main_old() != 0) return false; else return true; } } public class ClassStructTestClass_null_to_struct_i_C { } public struct ClassStructTestClass_null_to_struct_i_S { public ClassStructTestClass_null_to_struct_i_C c; public ClassStructTestClass_null_to_struct_i_S(ClassStructTestClass_null_to_struct_i_C c) { this.c = c; } public static implicit operator ClassStructTestClass_null_to_struct_i_S(ClassStructTestClass_null_to_struct_i_C c) { return new ClassStructTestClass_null_to_struct_i_S(c); } } public class ClassStructTestClass_null_to_struct_i { public static int Main_old() { ClassStructTestClass_null_to_struct_i_S s = null; return ((s.c == null) ? 0 : 1); } public static bool testMethod() { if (Main_old() != 0) return false; else return true; } } } } ================================================ FILE: Zelig/Zelig/Test/RunTime/NETMF/mscorlib/conversions/user/StructClassTests.cs ================================================ //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // Copyright (c) Microsoft Corporation. All rights reserved. //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// using System; namespace Microsoft.Zelig.Test { public class StructClassTests : TestBase, ITestInterface { [SetUp] public InitializeResult Initialize() { Log.Comment("Adding set up for the tests"); Log.Comment("Adding set up for the tests"); Log.Comment("These tests examine the conversion (casting) of structs to classes "); Log.Comment("There is a tree of classes are TDer : T : TBase and a struct S"); Log.Comment("The names of the tests describe the tests by listing which two objects will be converted between"); Log.Comment("Followed by which (The source or the destination) will contain a cast definition"); Log.Comment("Followed further by 'i's or 'e's to indicate which of the cast definition and the actual cast are"); Log.Comment("implicit or explicit."); Log.Comment(""); Log.Comment("For example, TBase_S_Source_i_e tests the conversion of TBase to S, with an implicit definition"); Log.Comment("of the cast in the TBase class, and an explicit cast in the body of the method."); return InitializeResult.ReadyToGo; } [TearDown] public void CleanUp() { Log.Comment("Cleaning up after the tests"); } public override TestResult Run( string[] args ) { TestResult result = TestResult.Pass; string testName = "StructClass_"; int testNumber = 0; result |= Assert.CheckFailed( StructClass_S_TBase_Source_i_e_Test( ), testName, ++testNumber ); result |= Assert.CheckFailed( StructClass_S_TBase_Source_e_e_Test( ), testName, ++testNumber ); result |= Assert.CheckFailed( StructClass_S_TBase_Dest_i_e_Test( ), testName, ++testNumber ); result |= Assert.CheckFailed( StructClass_S_TBase_Dest_e_e_Test( ), testName, ++testNumber ); result |= Assert.CheckFailed( StructClass_S_T_Source_i_i_Test( ), testName, ++testNumber ); result |= Assert.CheckFailed( StructClass_S_T_Source_i_e_Test( ), testName, ++testNumber ); result |= Assert.CheckFailed( StructClass_S_T_Source_e_e_Test( ), testName, ++testNumber ); result |= Assert.CheckFailed( StructClass_S_T_Dest_i_i_Test( ), testName, ++testNumber ); result |= Assert.CheckFailed( StructClass_S_T_Dest_i_e_Test( ), testName, ++testNumber ); result |= Assert.CheckFailed( StructClass_S_T_Dest_e_e_Test( ), testName, ++testNumber ); result |= Assert.CheckFailed( StructClass_S_TDer_Source_i_i_Test( ), testName, ++testNumber ); result |= Assert.CheckFailed( StructClass_S_TDer_Source_i_e_Test( ), testName, ++testNumber ); result |= Assert.CheckFailed( StructClass_S_TDer_Source_e_e_Test( ), testName, ++testNumber ); return result; } //StructClass Test methods //The following tests were ported from folder current\test\cases\client\CLR\Conformance\10_classes\StructClass //S_TBase_Source_i_e,S_TBase_Source_e_e,S_TBase_Dest_i_e,S_TBase_Dest_e_e,S_T_Source_i_i,S_T_Source_i_e,S_T_Source_e_e,S_T_Dest_i_i,S_T_Dest_i_e,S_T_Dest_e_e,S_TDer_Source_i_i,S_TDer_Source_i_e,S_TDer_Source_e_e.cs) -- passed //Test Case Calls [TestMethod] public TestResult StructClass_S_TBase_Source_i_e_Test() { if (StructClassTestClass_S_TBase_Source_i_e.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult StructClass_S_TBase_Source_e_e_Test() { if (StructClassTestClass_S_TBase_Source_e_e.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult StructClass_S_TBase_Dest_i_e_Test() { if (StructClassTestClass_S_TBase_Dest_i_e.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult StructClass_S_TBase_Dest_e_e_Test() { if (StructClassTestClass_S_TBase_Dest_e_e.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult StructClass_S_T_Source_i_i_Test() { if (StructClassTestClass_S_T_Source_i_i.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult StructClass_S_T_Source_i_e_Test() { if (StructClassTestClass_S_T_Source_i_e.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult StructClass_S_T_Source_e_e_Test() { if (StructClassTestClass_S_T_Source_e_e.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult StructClass_S_T_Dest_i_i_Test() { if (StructClassTestClass_S_T_Dest_i_i.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult StructClass_S_T_Dest_i_e_Test() { if (StructClassTestClass_S_T_Dest_i_e.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult StructClass_S_T_Dest_e_e_Test() { if (StructClassTestClass_S_T_Dest_e_e.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult StructClass_S_TDer_Source_i_i_Test() { if (StructClassTestClass_S_TDer_Source_i_i.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult StructClass_S_TDer_Source_i_e_Test() { if (StructClassTestClass_S_TDer_Source_i_e.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult StructClass_S_TDer_Source_e_e_Test() { if (StructClassTestClass_S_TDer_Source_e_e.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } //Compiled Test Cases struct StructClassTestClass_S_TBase_Source_i_e_S { static public implicit operator StructClassTestClass_S_TBase_Source_i_e_TBase(StructClassTestClass_S_TBase_Source_i_e_S foo) { Log.Comment(" StructClassTestClass_S_TBase_Source_i_e_S to StructClassTestClass_S_TBase_Source_i_e_TBase Source implicit"); return new StructClassTestClass_S_TBase_Source_i_e_TBase(); } } class StructClassTestClass_S_TBase_Source_i_e_TBase { } class StructClassTestClass_S_TBase_Source_i_e_T : StructClassTestClass_S_TBase_Source_i_e_TBase { } class StructClassTestClass_S_TBase_Source_i_e_TDer : StructClassTestClass_S_TBase_Source_i_e_T { } class StructClassTestClass_S_TBase_Source_i_e { public static void Main_old() { StructClassTestClass_S_TBase_Source_i_e_S s = new StructClassTestClass_S_TBase_Source_i_e_S(); StructClassTestClass_S_TBase_Source_i_e_T t; try { t = (StructClassTestClass_S_TBase_Source_i_e_T)s; } catch (System.Exception) { Log.Comment("System.Exception Caught"); } } public static bool testMethod() { Main_old(); return true; } } struct StructClassTestClass_S_TBase_Source_e_e_S { static public explicit operator StructClassTestClass_S_TBase_Source_e_e_TBase(StructClassTestClass_S_TBase_Source_e_e_S foo) { Log.Comment(" StructClassTestClass_S_TBase_Source_e_e_S to StructClassTestClass_S_TBase_Source_e_e_TBase Source explicit"); return new StructClassTestClass_S_TBase_Source_e_e_TBase(); } } class StructClassTestClass_S_TBase_Source_e_e_TBase { } class StructClassTestClass_S_TBase_Source_e_e_T : StructClassTestClass_S_TBase_Source_e_e_TBase { } class StructClassTestClass_S_TBase_Source_e_e_TDer : StructClassTestClass_S_TBase_Source_e_e_T { } class StructClassTestClass_S_TBase_Source_e_e { public static void Main_old() { StructClassTestClass_S_TBase_Source_e_e_S s = new StructClassTestClass_S_TBase_Source_e_e_S(); StructClassTestClass_S_TBase_Source_e_e_T t; try { t = (StructClassTestClass_S_TBase_Source_e_e_T)s; } catch (System.Exception) { Log.Comment("System.Exception Caught"); } } public static bool testMethod() { Main_old(); return true; } } struct StructClassTestClass_S_TBase_Dest_i_e_S { } class StructClassTestClass_S_TBase_Dest_i_e_TBase { static public implicit operator StructClassTestClass_S_TBase_Dest_i_e_TBase(StructClassTestClass_S_TBase_Dest_i_e_S foo) { Log.Comment(" StructClassTestClass_S_TBase_Dest_i_e_S to StructClassTestClass_S_TBase_Dest_i_e_TBase Dest implicit"); return new StructClassTestClass_S_TBase_Dest_i_e_TBase(); } } class StructClassTestClass_S_TBase_Dest_i_e_T : StructClassTestClass_S_TBase_Dest_i_e_TBase { } class StructClassTestClass_S_TBase_Dest_i_e_TDer : StructClassTestClass_S_TBase_Dest_i_e_T { } class StructClassTestClass_S_TBase_Dest_i_e { public static void Main_old() { StructClassTestClass_S_TBase_Dest_i_e_S s = new StructClassTestClass_S_TBase_Dest_i_e_S(); StructClassTestClass_S_TBase_Dest_i_e_T t; try { t = (StructClassTestClass_S_TBase_Dest_i_e_T)s; } catch (System.Exception) { Log.Comment("System.Exception Caught"); } } public static bool testMethod() { Main_old(); return true; } } struct StructClassTestClass_S_TBase_Dest_e_e_S { } class StructClassTestClass_S_TBase_Dest_e_e_TBase { static public explicit operator StructClassTestClass_S_TBase_Dest_e_e_TBase(StructClassTestClass_S_TBase_Dest_e_e_S foo) { Log.Comment(" StructClassTestClass_S_TBase_Dest_e_e_S to StructClassTestClass_S_TBase_Dest_e_e_TBase Dest explicit"); return new StructClassTestClass_S_TBase_Dest_e_e_TBase(); } } class StructClassTestClass_S_TBase_Dest_e_e_T : StructClassTestClass_S_TBase_Dest_e_e_TBase { } class StructClassTestClass_S_TBase_Dest_e_e_TDer : StructClassTestClass_S_TBase_Dest_e_e_T { } class StructClassTestClass_S_TBase_Dest_e_e { public static void Main_old() { StructClassTestClass_S_TBase_Dest_e_e_S s = new StructClassTestClass_S_TBase_Dest_e_e_S(); StructClassTestClass_S_TBase_Dest_e_e_T t; try { t = (StructClassTestClass_S_TBase_Dest_e_e_T)s; } catch (System.Exception) { Log.Comment("System.Exception Caught"); } } public static bool testMethod() { Main_old(); return true; } } struct StructClassTestClass_S_T_Source_i_i_S { static public implicit operator StructClassTestClass_S_T_Source_i_i_T(StructClassTestClass_S_T_Source_i_i_S foo) { Log.Comment(" StructClassTestClass_S_T_Source_i_i_S to StructClassTestClass_S_T_Source_i_i_T Source implicit"); return new StructClassTestClass_S_T_Source_i_i_T(); } } class StructClassTestClass_S_T_Source_i_i_TBase { } class StructClassTestClass_S_T_Source_i_i_T : StructClassTestClass_S_T_Source_i_i_TBase { } class StructClassTestClass_S_T_Source_i_i_TDer : StructClassTestClass_S_T_Source_i_i_T { } class StructClassTestClass_S_T_Source_i_i { public static void Main_old() { StructClassTestClass_S_T_Source_i_i_S s = new StructClassTestClass_S_T_Source_i_i_S(); StructClassTestClass_S_T_Source_i_i_T t; try { t = s; } catch (System.Exception) { Log.Comment("System.Exception Caught"); } } public static bool testMethod() { Main_old(); return true; } } struct StructClassTestClass_S_T_Source_i_e_S { static public implicit operator StructClassTestClass_S_T_Source_i_e_T(StructClassTestClass_S_T_Source_i_e_S foo) { Log.Comment(" StructClassTestClass_S_T_Source_i_e_S to StructClassTestClass_S_T_Source_i_e_T Source implicit"); return new StructClassTestClass_S_T_Source_i_e_T(); } } class StructClassTestClass_S_T_Source_i_e_TBase { } class StructClassTestClass_S_T_Source_i_e_T : StructClassTestClass_S_T_Source_i_e_TBase { } class StructClassTestClass_S_T_Source_i_e_TDer : StructClassTestClass_S_T_Source_i_e_T { } class StructClassTestClass_S_T_Source_i_e { public static void Main_old() { StructClassTestClass_S_T_Source_i_e_S s = new StructClassTestClass_S_T_Source_i_e_S(); StructClassTestClass_S_T_Source_i_e_T t; try { t = (StructClassTestClass_S_T_Source_i_e_T)s; } catch (System.Exception) { Log.Comment("System.Exception Caught"); } } public static bool testMethod() { Main_old(); return true; } } struct StructClassTestClass_S_T_Source_e_e_S { static public explicit operator StructClassTestClass_S_T_Source_e_e_T(StructClassTestClass_S_T_Source_e_e_S foo) { Log.Comment(" StructClassTestClass_S_T_Source_e_e_S to StructClassTestClass_S_T_Source_e_e_T Source explicit"); return new StructClassTestClass_S_T_Source_e_e_T(); } } class StructClassTestClass_S_T_Source_e_e_TBase { } class StructClassTestClass_S_T_Source_e_e_T : StructClassTestClass_S_T_Source_e_e_TBase { } class StructClassTestClass_S_T_Source_e_e_TDer : StructClassTestClass_S_T_Source_e_e_T { } class StructClassTestClass_S_T_Source_e_e { public static void Main_old() { StructClassTestClass_S_T_Source_e_e_S s = new StructClassTestClass_S_T_Source_e_e_S(); StructClassTestClass_S_T_Source_e_e_T t; try { t = (StructClassTestClass_S_T_Source_e_e_T)s; } catch (System.Exception) { Log.Comment("System.Exception Caught"); } } public static bool testMethod() { Main_old(); return true; } } struct StructClassTestClass_S_T_Dest_i_i_S { } class StructClassTestClass_S_T_Dest_i_i_TBase { } class StructClassTestClass_S_T_Dest_i_i_T : StructClassTestClass_S_T_Dest_i_i_TBase { static public implicit operator StructClassTestClass_S_T_Dest_i_i_T(StructClassTestClass_S_T_Dest_i_i_S foo) { Log.Comment(" StructClassTestClass_S_T_Dest_i_i_S to StructClassTestClass_S_T_Dest_i_i_T Dest implicit"); return new StructClassTestClass_S_T_Dest_i_i_T(); } } class StructClassTestClass_S_T_Dest_i_i_TDer : StructClassTestClass_S_T_Dest_i_i_T { } class StructClassTestClass_S_T_Dest_i_i { public static void Main_old() { StructClassTestClass_S_T_Dest_i_i_S s = new StructClassTestClass_S_T_Dest_i_i_S(); StructClassTestClass_S_T_Dest_i_i_T t; try { t = s; } catch (System.Exception) { Log.Comment("System.Exception Caught"); } } public static bool testMethod() { Main_old(); return true; } } struct StructClassTestClass_S_T_Dest_i_e_S { } class StructClassTestClass_S_T_Dest_i_e_TBase { } class StructClassTestClass_S_T_Dest_i_e_T : StructClassTestClass_S_T_Dest_i_e_TBase { static public implicit operator StructClassTestClass_S_T_Dest_i_e_T(StructClassTestClass_S_T_Dest_i_e_S foo) { Log.Comment(" StructClassTestClass_S_T_Dest_i_e_S to StructClassTestClass_S_T_Dest_i_e_T Dest implicit"); return new StructClassTestClass_S_T_Dest_i_e_T(); } } class StructClassTestClass_S_T_Dest_i_e_TDer : StructClassTestClass_S_T_Dest_i_e_T { } class StructClassTestClass_S_T_Dest_i_e { public static void Main_old() { StructClassTestClass_S_T_Dest_i_e_S s = new StructClassTestClass_S_T_Dest_i_e_S(); StructClassTestClass_S_T_Dest_i_e_T t; try { t = (StructClassTestClass_S_T_Dest_i_e_T)s; } catch (System.Exception) { Log.Comment("System.Exception Caught"); } } public static bool testMethod() { Main_old(); return true; } } struct StructClassTestClass_S_T_Dest_e_e_S { } class StructClassTestClass_S_T_Dest_e_e_TBase { } class StructClassTestClass_S_T_Dest_e_e_T : StructClassTestClass_S_T_Dest_e_e_TBase { static public explicit operator StructClassTestClass_S_T_Dest_e_e_T(StructClassTestClass_S_T_Dest_e_e_S foo) { Log.Comment(" StructClassTestClass_S_T_Dest_e_e_S to StructClassTestClass_S_T_Dest_e_e_T Dest explicit"); return new StructClassTestClass_S_T_Dest_e_e_T(); } } class StructClassTestClass_S_T_Dest_e_e_TDer : StructClassTestClass_S_T_Dest_e_e_T { } class StructClassTestClass_S_T_Dest_e_e { public static void Main_old() { StructClassTestClass_S_T_Dest_e_e_S s = new StructClassTestClass_S_T_Dest_e_e_S(); StructClassTestClass_S_T_Dest_e_e_T t; try { t = (StructClassTestClass_S_T_Dest_e_e_T)s; } catch (System.Exception) { Log.Comment("System.Exception Caught"); } } public static bool testMethod() { Main_old(); return true; } } struct StructClassTestClass_S_TDer_Source_i_i_S { static public implicit operator StructClassTestClass_S_TDer_Source_i_i_TDer(StructClassTestClass_S_TDer_Source_i_i_S foo) { Log.Comment(" StructClassTestClass_S_TDer_Source_i_i_S to StructClassTestClass_S_TDer_Source_i_i_TDer Source implicit"); return new StructClassTestClass_S_TDer_Source_i_i_TDer(); } } class StructClassTestClass_S_TDer_Source_i_i_TBase { } class StructClassTestClass_S_TDer_Source_i_i_T : StructClassTestClass_S_TDer_Source_i_i_TBase { } class StructClassTestClass_S_TDer_Source_i_i_TDer : StructClassTestClass_S_TDer_Source_i_i_T { } class StructClassTestClass_S_TDer_Source_i_i { public static void Main_old() { StructClassTestClass_S_TDer_Source_i_i_S s = new StructClassTestClass_S_TDer_Source_i_i_S(); StructClassTestClass_S_TDer_Source_i_i_T t; try { t = s; } catch (System.Exception) { Log.Comment("System.Exception Caught"); } } public static bool testMethod() { Main_old(); return true; } } struct StructClassTestClass_S_TDer_Source_i_e_S { static public implicit operator StructClassTestClass_S_TDer_Source_i_e_TDer(StructClassTestClass_S_TDer_Source_i_e_S foo) { Log.Comment(" StructClassTestClass_S_TDer_Source_i_e_S to StructClassTestClass_S_TDer_Source_i_e_TDer Source implicit"); return new StructClassTestClass_S_TDer_Source_i_e_TDer(); } } class StructClassTestClass_S_TDer_Source_i_e_TBase { } class StructClassTestClass_S_TDer_Source_i_e_T : StructClassTestClass_S_TDer_Source_i_e_TBase { } class StructClassTestClass_S_TDer_Source_i_e_TDer : StructClassTestClass_S_TDer_Source_i_e_T { } class StructClassTestClass_S_TDer_Source_i_e { public static void Main_old() { StructClassTestClass_S_TDer_Source_i_e_S s = new StructClassTestClass_S_TDer_Source_i_e_S(); StructClassTestClass_S_TDer_Source_i_e_T t; try { t = (StructClassTestClass_S_TDer_Source_i_e_T)s; } catch (System.Exception) { Log.Comment("System.Exception Caught"); } } public static bool testMethod() { Main_old(); return true; } } struct StructClassTestClass_S_TDer_Source_e_e_S { static public explicit operator StructClassTestClass_S_TDer_Source_e_e_TDer(StructClassTestClass_S_TDer_Source_e_e_S foo) { Log.Comment(" StructClassTestClass_S_TDer_Source_e_e_S to StructClassTestClass_S_TDer_Source_e_e_TDer Source explicit"); return new StructClassTestClass_S_TDer_Source_e_e_TDer(); } } class StructClassTestClass_S_TDer_Source_e_e_TBase { } class StructClassTestClass_S_TDer_Source_e_e_T : StructClassTestClass_S_TDer_Source_e_e_TBase { } class StructClassTestClass_S_TDer_Source_e_e_TDer : StructClassTestClass_S_TDer_Source_e_e_T { } class StructClassTestClass_S_TDer_Source_e_e { public static void Main_old() { StructClassTestClass_S_TDer_Source_e_e_S s = new StructClassTestClass_S_TDer_Source_e_e_S(); StructClassTestClass_S_TDer_Source_e_e_T t; try { t = (StructClassTestClass_S_TDer_Source_e_e_T)s; } catch (System.Exception) { Log.Comment("System.Exception Caught"); } } public static bool testMethod() { Main_old(); return true; } } } } ================================================ FILE: Zelig/Zelig/Test/RunTime/NETMF/mscorlib/conversions/user/StructStructTests.cs ================================================ //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // Copyright (c) Microsoft Corporation. All rights reserved. //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// using System; namespace Microsoft.Zelig.Test { public class StructStructTests : TestBase, ITestInterface { [SetUp] public InitializeResult Initialize() { Log.Comment("Adding set up for the tests"); Log.Comment("These tests examine the conversion (casting) of two structs"); Log.Comment("There are two structs S and T"); Log.Comment("The names of the tests describe the tests by listing which two objects will be converted between"); Log.Comment("Followed by which (The source or the destination) will contain a cast definition"); Log.Comment("Followed further by 'i's or 'e's to indicate which of the cast definition and the actual cast are"); Log.Comment("implicit or explicit."); Log.Comment(""); Log.Comment("For example, S_T_Source_i_e tests the conversion of S to T, with an implicit definition"); Log.Comment("of the cast in the S struct, and an explicit cast in the body of the method."); return InitializeResult.ReadyToGo; } [TearDown] public void CleanUp() { Log.Comment("Cleaning up after the tests"); } public override TestResult Run( string[] args ) { TestResult result = TestResult.Pass; string testName = "StructStruct_"; int testNumber = 0; result |= Assert.CheckFailed( StructStruct_S_T_Source_i_i_Test( ), testName, ++testNumber ); result |= Assert.CheckFailed( StructStruct_S_T_Source_i_e_Test( ), testName, ++testNumber ); result |= Assert.CheckFailed( StructStruct_S_T_Source_e_e_Test( ), testName, ++testNumber ); result |= Assert.CheckFailed( StructStruct_S_T_Dest_i_i_Test( ), testName, ++testNumber ); result |= Assert.CheckFailed( StructStruct_S_T_Dest_i_e_Test( ), testName, ++testNumber ); result |= Assert.CheckFailed( StructStruct_S_T_Dest_e_e_Test( ), testName, ++testNumber ); return result; } //StructStruct Test methods //The following tests were ported from folder current\test\cases\client\CLR\Conformance\10_classes\StructStruct //Test Case Calls [TestMethod] public TestResult StructStruct_S_T_Source_i_i_Test() { if (StructStructTestClass_S_T_Source_i_i.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult StructStruct_S_T_Source_i_e_Test() { if (StructStructTestClass_S_T_Source_i_e.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult StructStruct_S_T_Source_e_e_Test() { if (StructStructTestClass_S_T_Source_e_e.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult StructStruct_S_T_Dest_i_i_Test() { if (StructStructTestClass_S_T_Dest_i_i.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult StructStruct_S_T_Dest_i_e_Test() { if (StructStructTestClass_S_T_Dest_i_e.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult StructStruct_S_T_Dest_e_e_Test() { if (StructStructTestClass_S_T_Dest_e_e.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } //Compiled Test Cases struct StructStructTestClass_S_T_Source_i_i_S { static public implicit operator StructStructTestClass_S_T_Source_i_i_T(StructStructTestClass_S_T_Source_i_i_S foo) { Log.Comment(" StructStructTestClass_S_T_Source_i_i_S to StructStructTestClass_S_T_Source_i_i_T Source implicit"); return new StructStructTestClass_S_T_Source_i_i_T(); } } struct StructStructTestClass_S_T_Source_i_i_T { } class StructStructTestClass_S_T_Source_i_i { public static void Main_old() { StructStructTestClass_S_T_Source_i_i_S s = new StructStructTestClass_S_T_Source_i_i_S(); StructStructTestClass_S_T_Source_i_i_T t; try { t = s; } catch (System.Exception) { Log.Comment("System.Exception Caught"); } } public static bool testMethod() { Main_old(); return true; } } struct StructStructTestClass_S_T_Source_i_e_S { static public implicit operator StructStructTestClass_S_T_Source_i_e_T(StructStructTestClass_S_T_Source_i_e_S foo) { Log.Comment(" StructStructTestClass_S_T_Source_i_e_S to StructStructTestClass_S_T_Source_i_e_T Source implicit"); return new StructStructTestClass_S_T_Source_i_e_T(); } } struct StructStructTestClass_S_T_Source_i_e_T { } class StructStructTestClass_S_T_Source_i_e { public static void Main_old() { StructStructTestClass_S_T_Source_i_e_S s = new StructStructTestClass_S_T_Source_i_e_S(); StructStructTestClass_S_T_Source_i_e_T t; try { t = (StructStructTestClass_S_T_Source_i_e_T)s; } catch (System.Exception) { Log.Comment("System.Exception Caught"); } } public static bool testMethod() { Main_old(); return true; } } struct StructStructTestClass_S_T_Source_e_e_S { static public explicit operator StructStructTestClass_S_T_Source_e_e_T(StructStructTestClass_S_T_Source_e_e_S foo) { Log.Comment(" StructStructTestClass_S_T_Source_e_e_S to StructStructTestClass_S_T_Source_e_e_T Source explicit"); return new StructStructTestClass_S_T_Source_e_e_T(); } } struct StructStructTestClass_S_T_Source_e_e_T { } class StructStructTestClass_S_T_Source_e_e { public static void Main_old() { StructStructTestClass_S_T_Source_e_e_S s = new StructStructTestClass_S_T_Source_e_e_S(); StructStructTestClass_S_T_Source_e_e_T t; try { t = (StructStructTestClass_S_T_Source_e_e_T)s; } catch (System.Exception) { Log.Comment("System.Exception Caught"); } } public static bool testMethod() { Main_old(); return true; } } struct StructStructTestClass_S_T_Dest_i_i_S { } struct StructStructTestClass_S_T_Dest_i_i_T { static public implicit operator StructStructTestClass_S_T_Dest_i_i_T(StructStructTestClass_S_T_Dest_i_i_S foo) { Log.Comment(" StructStructTestClass_S_T_Dest_i_i_S to StructStructTestClass_S_T_Dest_i_i_T Dest implicit"); return new StructStructTestClass_S_T_Dest_i_i_T(); } } class StructStructTestClass_S_T_Dest_i_i { public static void Main_old() { StructStructTestClass_S_T_Dest_i_i_S s = new StructStructTestClass_S_T_Dest_i_i_S(); StructStructTestClass_S_T_Dest_i_i_T t; try { t = s; } catch (System.Exception) { Log.Comment("System.Exception Caught"); } } public static bool testMethod() { Main_old(); return true; } } struct StructStructTestClass_S_T_Dest_i_e_S { } struct StructStructTestClass_S_T_Dest_i_e_T { static public implicit operator StructStructTestClass_S_T_Dest_i_e_T(StructStructTestClass_S_T_Dest_i_e_S foo) { Log.Comment(" StructStructTestClass_S_T_Dest_i_e_S to StructStructTestClass_S_T_Dest_i_e_T Dest implicit"); return new StructStructTestClass_S_T_Dest_i_e_T(); } } class StructStructTestClass_S_T_Dest_i_e { public static void Main_old() { StructStructTestClass_S_T_Dest_i_e_S s = new StructStructTestClass_S_T_Dest_i_e_S(); StructStructTestClass_S_T_Dest_i_e_T t; try { t = (StructStructTestClass_S_T_Dest_i_e_T)s; } catch (System.Exception) { Log.Comment("System.Exception Caught"); } } public static bool testMethod() { Main_old(); return true; } } struct StructStructTestClass_S_T_Dest_e_e_S { } struct StructStructTestClass_S_T_Dest_e_e_T { static public explicit operator StructStructTestClass_S_T_Dest_e_e_T(StructStructTestClass_S_T_Dest_e_e_S foo) { Log.Comment(" StructStructTestClass_S_T_Dest_e_e_S to StructStructTestClass_S_T_Dest_e_e_T Dest explicit"); return new StructStructTestClass_S_T_Dest_e_e_T(); } } class StructStructTestClass_S_T_Dest_e_e { public static void Main_old() { StructStructTestClass_S_T_Dest_e_e_S s = new StructStructTestClass_S_T_Dest_e_e_S(); StructStructTestClass_S_T_Dest_e_e_T t; try { t = (StructStructTestClass_S_T_Dest_e_e_T)s; } catch (System.Exception) { Log.Comment("System.Exception Caught"); } } public static bool testMethod() { Main_old(); return true; } } } } ================================================ FILE: Zelig/Zelig/Test/RunTime/NETMF/mscorlib/conversions/user/selection/BasicSelectionTests.cs ================================================ //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // Copyright (c) Microsoft Corporation. All rights reserved. //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// using System; namespace Microsoft.Zelig.Test { public class BasicSelectionTests : TestBase, ITestInterface { [SetUp] public InitializeResult Initialize( ) { Log.Comment( "Adding set up for the tests" ); Log.Comment( "The Basic Selection tests examine casting a basic type as a user class" ); Log.Comment( "And then extracting the value." ); Log.Comment( "They are named for the type they convert from, along with Is and Es" ); Log.Comment( "For whether each cast is Implicit or Explicit, and with FC or TC" ); Log.Comment( "Which indicates whether the Conversion From, or the Conversion back To" ); Log.Comment( "the listed type is performed with a function call rather than a simple assignment" ); // Add your functionality here. return InitializeResult.ReadyToGo; } [TearDown] public void CleanUp( ) { Log.Comment( "Cleaning up after the tests" ); } public override TestResult Run( string[] args ) { TestResult result = TestResult.Pass; string testName = "BasicSelection_"; int testNumber = 0; result |= Assert.CheckFailed( BasicSelection_byte_i_i_tc_Test( ), testName, ++testNumber ); result |= Assert.CheckFailed( BasicSelection_byte_i_e_tc_Test( ), testName, ++testNumber ); result |= Assert.CheckFailed( BasicSelection_byte_e_e_tc_Test( ), testName, ++testNumber ); result |= Assert.CheckFailed( BasicSelection_byte_i_i_fc_Test( ), testName, ++testNumber ); result |= Assert.CheckFailed( BasicSelection_byte_i_e_fc_Test( ), testName, ++testNumber ); result |= Assert.CheckFailed( BasicSelection_byte_e_e_fc_Test( ), testName, ++testNumber ); result |= Assert.CheckFailed( BasicSelection_char_i_i_tc_Test( ), testName, ++testNumber ); result |= Assert.CheckFailed( BasicSelection_char_i_e_tc_Test( ), testName, ++testNumber ); result |= Assert.CheckFailed( BasicSelection_char_e_e_tc_Test( ), testName, ++testNumber ); result |= Assert.CheckFailed( BasicSelection_char_i_i_fc_Test( ), testName, ++testNumber ); result |= Assert.CheckFailed( BasicSelection_char_i_e_fc_Test( ), testName, ++testNumber ); result |= Assert.CheckFailed( BasicSelection_char_e_e_fc_Test( ), testName, ++testNumber ); result |= Assert.CheckFailed( BasicSelection_double_i_i_tc_Test( ), testName, ++testNumber ); result |= Assert.CheckFailed( BasicSelection_double_i_e_tc_Test( ), testName, ++testNumber ); result |= Assert.CheckFailed( BasicSelection_double_e_e_tc_Test( ), testName, ++testNumber ); result |= Assert.CheckFailed( BasicSelection_double_i_i_fc_Test( ), testName, ++testNumber ); result |= Assert.CheckFailed( BasicSelection_double_i_e_fc_Test( ), testName, ++testNumber ); result |= Assert.CheckFailed( BasicSelection_double_e_e_fc_Test( ), testName, ++testNumber ); result |= Assert.CheckFailed( BasicSelection_float_i_i_tc_Test( ), testName, ++testNumber ); result |= Assert.CheckFailed( BasicSelection_float_i_e_tc_Test( ), testName, ++testNumber ); result |= Assert.CheckFailed( BasicSelection_float_e_e_tc_Test( ), testName, ++testNumber ); result |= Assert.CheckFailed( BasicSelection_float_i_i_fc_Test( ), testName, ++testNumber ); result |= Assert.CheckFailed( BasicSelection_float_i_e_fc_Test( ), testName, ++testNumber ); result |= Assert.CheckFailed( BasicSelection_float_e_e_fc_Test( ), testName, ++testNumber ); result |= Assert.CheckFailed( BasicSelection_int_i_i_tc_Test( ), testName, ++testNumber ); result |= Assert.CheckFailed( BasicSelection_long_i_i_fc_Test( ), testName, ++testNumber ); result |= Assert.CheckFailed( BasicSelection_long_i_e_fc_Test( ), testName, ++testNumber ); result |= Assert.CheckFailed( BasicSelection_long_e_e_fc_Test( ), testName, ++testNumber ); result |= Assert.CheckFailed( BasicSelection_sbyte_i_i_tc_Test( ), testName, ++testNumber ); result |= Assert.CheckFailed( BasicSelection_int_i_e_tc_Test( ), testName, ++testNumber ); result |= Assert.CheckFailed( BasicSelection_int_e_e_tc_Test( ), testName, ++testNumber ); result |= Assert.CheckFailed( BasicSelection_int_i_i_fc_Test( ), testName, ++testNumber ); result |= Assert.CheckFailed( BasicSelection_int_i_e_fc_Test( ), testName, ++testNumber ); result |= Assert.CheckFailed( BasicSelection_int_e_e_fc_Test( ), testName, ++testNumber ); result |= Assert.CheckFailed( BasicSelection_long_i_i_tc_Test( ), testName, ++testNumber ); result |= Assert.CheckFailed( BasicSelection_long_i_e_tc_Test( ), testName, ++testNumber ); result |= Assert.CheckFailed( BasicSelection_long_e_e_tc_Test( ), testName, ++testNumber ); result |= Assert.CheckFailed( BasicSelection_sbyte_i_e_tc_Test( ), testName, ++testNumber ); result |= Assert.CheckFailed( BasicSelection_sbyte_e_e_tc_Test( ), testName, ++testNumber ); result |= Assert.CheckFailed( BasicSelection_sbyte_i_i_fc_Test( ), testName, ++testNumber ); result |= Assert.CheckFailed( BasicSelection_sbyte_i_e_fc_Test( ), testName, ++testNumber ); result |= Assert.CheckFailed( BasicSelection_sbyte_e_e_fc_Test( ), testName, ++testNumber ); result |= Assert.CheckFailed( BasicSelection_short_i_i_tc_Test( ), testName, ++testNumber ); result |= Assert.CheckFailed( BasicSelection_short_i_e_tc_Test( ), testName, ++testNumber ); result |= Assert.CheckFailed( BasicSelection_short_e_e_tc_Test( ), testName, ++testNumber ); result |= Assert.CheckFailed( BasicSelection_short_i_i_fc_Test( ), testName, ++testNumber ); result |= Assert.CheckFailed( BasicSelection_short_i_e_fc_Test( ), testName, ++testNumber ); result |= Assert.CheckFailed( BasicSelection_short_e_e_fc_Test( ), testName, ++testNumber ); result |= Assert.CheckFailed( BasicSelection_uint_i_i_tc_Test( ), testName, ++testNumber ); result |= Assert.CheckFailed( BasicSelection_uint_i_e_tc_Test( ), testName, ++testNumber ); result |= Assert.CheckFailed( BasicSelection_uint_e_e_tc_Test( ), testName, ++testNumber ); result |= Assert.CheckFailed( BasicSelection_uint_i_i_fc_Test( ), testName, ++testNumber ); result |= Assert.CheckFailed( BasicSelection_uint_i_e_fc_Test( ), testName, ++testNumber ); result |= Assert.CheckFailed( BasicSelection_uint_e_e_fc_Test( ), testName, ++testNumber ); result |= Assert.CheckFailed( BasicSelection_ulong_i_i_tc_Test( ), testName, ++testNumber ); result |= Assert.CheckFailed( BasicSelection_ulong_i_e_tc_Test( ), testName, ++testNumber ); result |= Assert.CheckFailed( BasicSelection_ulong_e_e_tc_Test( ), testName, ++testNumber ); result |= Assert.CheckFailed( BasicSelection_ulong_i_i_fc_Test( ), testName, ++testNumber ); result |= Assert.CheckFailed( BasicSelection_ulong_i_e_fc_Test( ), testName, ++testNumber ); result |= Assert.CheckFailed( BasicSelection_ulong_e_e_fc_Test( ), testName, ++testNumber ); result |= Assert.CheckFailed( BasicSelection_ushort_i_i_tc_Test( ), testName, ++testNumber ); result |= Assert.CheckFailed( BasicSelection_ushort_i_e_tc_Test( ), testName, ++testNumber ); result |= Assert.CheckFailed( BasicSelection_ushort_e_e_tc_Test( ), testName, ++testNumber ); result |= Assert.CheckFailed( BasicSelection_ushort_i_i_fc_Test( ), testName, ++testNumber ); result |= Assert.CheckFailed( BasicSelection_ushort_i_e_fc_Test( ), testName, ++testNumber ); result |= Assert.CheckFailed( BasicSelection_ushort_e_e_fc_Test( ), testName, ++testNumber ); return result; } //BasicSelection Test methods //The following tests were ported from folder current\test\cases\client\CLR\Conformance\10_classes\BasicSelection //byte_i_i_tc,byte_i_e_tc,byte_e_e_tc,byte_i_i_fc,byte_i_e_fc,byte_e_e_fc,char_i_i_tc,char_i_e_tc,char_e_e_tc,char_i_i_fc,char_i_e_fc,char_e_e_fc,double_i_i_tc,double_i_e_tc,double_e_e_tc,double_i_i_fc,double_i_e_fc,double_e_e_fc,float_i_i_tc,float_i_e_tc,float_e_e_tc,float_i_i_fc,float_i_e_fc,float_e_e_fc,int_i_i_tc,int_i_e_tc,int_e_e_tc,int_i_i_fc,int_i_e_fc,int_e_e_fc,long_i_i_tc,long_i_e_tc,long_e_e_tc,long_i_i_fc,long_i_e_fc,long_e_e_fc,sbyte_i_i_tc,sbyte_i_e_tc,sbyte_e_e_tc,sbyte_i_i_fc,sbyte_i_e_fc,sbyte_e_e_fc,short_i_i_tc,short_i_e_tc,short_e_e_tc,short_i_i_fc,short_i_e_fc,short_e_e_fc,uint_i_i_tc,uint_i_e_tc,uint_e_e_tc,uint_i_i_fc,uint_i_e_fc,uint_e_e_fc,ulong_i_i_tc,ulong_i_e_tc,ulong_e_e_tc,ulong_i_i_fc,ulong_i_e_fc,ulong_e_e_fc,ushort_i_i_tc,ushort_i_e_tc,ushort_e_e_tc,ushort_i_i_fc,ushort_i_e_fc,ushort_e_e_fc //Test Case Calls [TestMethod] public TestResult BasicSelection_byte_i_i_tc_Test() { if (BasicSelectionTestClass_byte_i_i_tc.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult BasicSelection_byte_i_e_tc_Test() { if (BasicSelectionTestClass_byte_i_e_tc.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult BasicSelection_byte_e_e_tc_Test() { if (BasicSelectionTestClass_byte_e_e_tc.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult BasicSelection_byte_i_i_fc_Test() { if (BasicSelectionTestClass_byte_i_i_fc.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult BasicSelection_byte_i_e_fc_Test() { if (BasicSelectionTestClass_byte_i_e_fc.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult BasicSelection_byte_e_e_fc_Test() { if (BasicSelectionTestClass_byte_e_e_fc.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult BasicSelection_char_i_i_tc_Test() { if (BasicSelectionTestClass_char_i_i_tc.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult BasicSelection_char_i_e_tc_Test() { if (BasicSelectionTestClass_char_i_e_tc.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult BasicSelection_char_e_e_tc_Test() { if (BasicSelectionTestClass_char_e_e_tc.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult BasicSelection_char_i_i_fc_Test() { if (BasicSelectionTestClass_char_i_i_fc.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult BasicSelection_char_i_e_fc_Test() { if (BasicSelectionTestClass_char_i_e_fc.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult BasicSelection_char_e_e_fc_Test() { if (BasicSelectionTestClass_char_e_e_fc.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult BasicSelection_double_i_i_tc_Test() { if (BasicSelectionTestClass_double_i_i_tc.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult BasicSelection_double_i_e_tc_Test() { if (BasicSelectionTestClass_double_i_e_tc.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult BasicSelection_double_e_e_tc_Test() { if (BasicSelectionTestClass_double_e_e_tc.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult BasicSelection_double_i_i_fc_Test() { if (BasicSelectionTestClass_double_i_i_fc.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult BasicSelection_double_i_e_fc_Test() { if (BasicSelectionTestClass_double_i_e_fc.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult BasicSelection_double_e_e_fc_Test() { if (BasicSelectionTestClass_double_e_e_fc.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult BasicSelection_float_i_i_tc_Test() { if (BasicSelectionTestClass_float_i_i_tc.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult BasicSelection_float_i_e_tc_Test() { if (BasicSelectionTestClass_float_i_e_tc.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult BasicSelection_float_e_e_tc_Test() { if (BasicSelectionTestClass_float_e_e_tc.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult BasicSelection_float_i_i_fc_Test() { if (BasicSelectionTestClass_float_i_i_fc.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult BasicSelection_float_i_e_fc_Test() { if (BasicSelectionTestClass_float_i_e_fc.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult BasicSelection_float_e_e_fc_Test() { if (BasicSelectionTestClass_float_e_e_fc.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult BasicSelection_int_i_i_tc_Test() { if (BasicSelectionTestClass_int_i_i_tc.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult BasicSelection_long_i_i_fc_Test() { if (BasicSelectionTestClass_long_i_i_fc.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult BasicSelection_long_i_e_fc_Test() { if (BasicSelectionTestClass_long_i_e_fc.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult BasicSelection_long_e_e_fc_Test() { if (BasicSelectionTestClass_long_e_e_fc.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult BasicSelection_sbyte_i_i_tc_Test() { if (BasicSelectionTestClass_sbyte_i_i_tc.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult BasicSelection_int_i_e_tc_Test() { if (BasicSelectionTestClass_int_i_e_tc.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult BasicSelection_int_e_e_tc_Test() { if (BasicSelectionTestClass_int_e_e_tc.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult BasicSelection_int_i_i_fc_Test() { if (BasicSelectionTestClass_int_i_i_fc.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult BasicSelection_int_i_e_fc_Test() { if (BasicSelectionTestClass_int_i_e_fc.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult BasicSelection_int_e_e_fc_Test() { if (BasicSelectionTestClass_int_e_e_fc.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult BasicSelection_long_i_i_tc_Test() { if (BasicSelectionTestClass_long_i_i_tc.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult BasicSelection_long_i_e_tc_Test() { if (BasicSelectionTestClass_long_i_e_tc.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult BasicSelection_long_e_e_tc_Test() { if (BasicSelectionTestClass_long_e_e_tc.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult BasicSelection_sbyte_i_e_tc_Test() { if (BasicSelectionTestClass_sbyte_i_e_tc.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult BasicSelection_sbyte_e_e_tc_Test() { if (BasicSelectionTestClass_sbyte_e_e_tc.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult BasicSelection_sbyte_i_i_fc_Test() { if (BasicSelectionTestClass_sbyte_i_i_fc.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult BasicSelection_sbyte_i_e_fc_Test() { if (BasicSelectionTestClass_sbyte_i_e_fc.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult BasicSelection_sbyte_e_e_fc_Test() { if (BasicSelectionTestClass_sbyte_e_e_fc.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult BasicSelection_short_i_i_tc_Test() { if (BasicSelectionTestClass_short_i_i_tc.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult BasicSelection_short_i_e_tc_Test() { if (BasicSelectionTestClass_short_i_e_tc.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult BasicSelection_short_e_e_tc_Test() { if (BasicSelectionTestClass_short_e_e_tc.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult BasicSelection_short_i_i_fc_Test() { if (BasicSelectionTestClass_short_i_i_fc.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult BasicSelection_short_i_e_fc_Test() { if (BasicSelectionTestClass_short_i_e_fc.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult BasicSelection_short_e_e_fc_Test() { if (BasicSelectionTestClass_short_e_e_fc.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult BasicSelection_uint_i_i_tc_Test() { if (BasicSelectionTestClass_uint_i_i_tc.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult BasicSelection_uint_i_e_tc_Test() { if (BasicSelectionTestClass_uint_i_e_tc.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult BasicSelection_uint_e_e_tc_Test() { if (BasicSelectionTestClass_uint_e_e_tc.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult BasicSelection_uint_i_i_fc_Test() { if (BasicSelectionTestClass_uint_i_i_fc.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult BasicSelection_uint_i_e_fc_Test() { if (BasicSelectionTestClass_uint_i_e_fc.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult BasicSelection_uint_e_e_fc_Test() { if (BasicSelectionTestClass_uint_e_e_fc.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult BasicSelection_ulong_i_i_tc_Test() { if (BasicSelectionTestClass_ulong_i_i_tc.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult BasicSelection_ulong_i_e_tc_Test() { if (BasicSelectionTestClass_ulong_i_e_tc.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult BasicSelection_ulong_e_e_tc_Test() { if (BasicSelectionTestClass_ulong_e_e_tc.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult BasicSelection_ulong_i_i_fc_Test() { if (BasicSelectionTestClass_ulong_i_i_fc.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult BasicSelection_ulong_i_e_fc_Test() { if (BasicSelectionTestClass_ulong_i_e_fc.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult BasicSelection_ulong_e_e_fc_Test() { if (BasicSelectionTestClass_ulong_e_e_fc.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult BasicSelection_ushort_i_i_tc_Test() { if (BasicSelectionTestClass_ushort_i_i_tc.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult BasicSelection_ushort_i_e_tc_Test() { if (BasicSelectionTestClass_ushort_i_e_tc.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult BasicSelection_ushort_e_e_tc_Test() { if (BasicSelectionTestClass_ushort_e_e_tc.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult BasicSelection_ushort_i_i_fc_Test() { if (BasicSelectionTestClass_ushort_i_i_fc.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult BasicSelection_ushort_i_e_fc_Test() { if (BasicSelectionTestClass_ushort_i_e_fc.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult BasicSelection_ushort_e_e_fc_Test() { if (BasicSelectionTestClass_ushort_e_e_fc.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } //Compiled Test Cases class BasicSelectionTestClass_byte_i_i_tc_Conv { private byte value_byte; static public implicit operator byte(BasicSelectionTestClass_byte_i_i_tc_Conv test) { Log.Comment("To byte"); return test.value_byte; } static public implicit operator BasicSelectionTestClass_byte_i_i_tc_Conv(byte val) { Log.Comment("From byte"); BasicSelectionTestClass_byte_i_i_tc_Conv temp = new BasicSelectionTestClass_byte_i_i_tc_Conv(); temp.value_byte = val; return (temp); } public byte GetValuebyte() { return (value_byte); } public void SetValuebyte(byte val) { value_byte = val; } private char value_char; static public implicit operator char(BasicSelectionTestClass_byte_i_i_tc_Conv test) { Log.Comment("To char"); return test.value_char; } static public implicit operator BasicSelectionTestClass_byte_i_i_tc_Conv(char val) { Log.Comment("From char"); BasicSelectionTestClass_byte_i_i_tc_Conv temp = new BasicSelectionTestClass_byte_i_i_tc_Conv(); temp.value_char = val; return (temp); } public char GetValuechar() { return (value_char); } public void SetValuechar(char val) { value_char = val; } private double value_double; static public implicit operator double(BasicSelectionTestClass_byte_i_i_tc_Conv test) { Log.Comment("To double"); return test.value_double; } static public implicit operator BasicSelectionTestClass_byte_i_i_tc_Conv(double val) { Log.Comment("From double"); BasicSelectionTestClass_byte_i_i_tc_Conv temp = new BasicSelectionTestClass_byte_i_i_tc_Conv(); temp.value_double = val; return (temp); } public double GetValuedouble() { return (value_double); } public void SetValuedouble(double val) { value_double = val; } private float value_float; static public implicit operator float(BasicSelectionTestClass_byte_i_i_tc_Conv test) { Log.Comment("To float"); return test.value_float; } static public implicit operator BasicSelectionTestClass_byte_i_i_tc_Conv(float val) { Log.Comment("From float"); BasicSelectionTestClass_byte_i_i_tc_Conv temp = new BasicSelectionTestClass_byte_i_i_tc_Conv(); temp.value_float = val; return (temp); } public float GetValuefloat() { return (value_float); } public void SetValuefloat(float val) { value_float = val; } private int value_int; static public implicit operator int(BasicSelectionTestClass_byte_i_i_tc_Conv test) { Log.Comment("To int"); return test.value_int; } static public implicit operator BasicSelectionTestClass_byte_i_i_tc_Conv(int val) { Log.Comment("From int"); BasicSelectionTestClass_byte_i_i_tc_Conv temp = new BasicSelectionTestClass_byte_i_i_tc_Conv(); temp.value_int = val; return (temp); } public int GetValueint() { return (value_int); } public void SetValueint(int val) { value_int = val; } private long value_long; static public implicit operator long(BasicSelectionTestClass_byte_i_i_tc_Conv test) { Log.Comment("To long"); return test.value_long; } static public implicit operator BasicSelectionTestClass_byte_i_i_tc_Conv(long val) { Log.Comment("From long"); BasicSelectionTestClass_byte_i_i_tc_Conv temp = new BasicSelectionTestClass_byte_i_i_tc_Conv(); temp.value_long = val; return (temp); } public long GetValuelong() { return (value_long); } public void SetValuelong(long val) { value_long = val; } private sbyte value_sbyte; static public implicit operator sbyte(BasicSelectionTestClass_byte_i_i_tc_Conv test) { Log.Comment("To sbyte"); return test.value_sbyte; } static public implicit operator BasicSelectionTestClass_byte_i_i_tc_Conv(sbyte val) { Log.Comment("From sbyte"); BasicSelectionTestClass_byte_i_i_tc_Conv temp = new BasicSelectionTestClass_byte_i_i_tc_Conv(); temp.value_sbyte = val; return (temp); } public sbyte GetValuesbyte() { return (value_sbyte); } public void SetValuesbyte(sbyte val) { value_sbyte = val; } private short value_short; static public implicit operator short(BasicSelectionTestClass_byte_i_i_tc_Conv test) { Log.Comment("To short"); return test.value_short; } static public implicit operator BasicSelectionTestClass_byte_i_i_tc_Conv(short val) { Log.Comment("From short"); BasicSelectionTestClass_byte_i_i_tc_Conv temp = new BasicSelectionTestClass_byte_i_i_tc_Conv(); temp.value_short = val; return (temp); } public short GetValueshort() { return (value_short); } public void SetValueshort(short val) { value_short = val; } private uint value_uint; static public implicit operator uint(BasicSelectionTestClass_byte_i_i_tc_Conv test) { Log.Comment("To uint"); return test.value_uint; } static public implicit operator BasicSelectionTestClass_byte_i_i_tc_Conv(uint val) { Log.Comment("From uint"); BasicSelectionTestClass_byte_i_i_tc_Conv temp = new BasicSelectionTestClass_byte_i_i_tc_Conv(); temp.value_uint = val; return (temp); } public uint GetValueuint() { return (value_uint); } public void SetValueuint(uint val) { value_uint = val; } private ulong value_ulong; static public implicit operator ulong(BasicSelectionTestClass_byte_i_i_tc_Conv test) { Log.Comment("To ulong"); return test.value_ulong; } static public implicit operator BasicSelectionTestClass_byte_i_i_tc_Conv(ulong val) { Log.Comment("From ulong"); BasicSelectionTestClass_byte_i_i_tc_Conv temp = new BasicSelectionTestClass_byte_i_i_tc_Conv(); temp.value_ulong = val; return (temp); } public ulong GetValueulong() { return (value_ulong); } public void SetValueulong(ulong val) { value_ulong = val; } private ushort value_ushort; static public implicit operator ushort(BasicSelectionTestClass_byte_i_i_tc_Conv test) { Log.Comment("To ushort"); return test.value_ushort; } static public implicit operator BasicSelectionTestClass_byte_i_i_tc_Conv(ushort val) { Log.Comment("From ushort"); BasicSelectionTestClass_byte_i_i_tc_Conv temp = new BasicSelectionTestClass_byte_i_i_tc_Conv(); temp.value_ushort = val; return (temp); } public ushort GetValueushort() { return (value_ushort); } public void SetValueushort(ushort val) { value_ushort = val; } } class BasicSelectionTestClass_byte_i_i_tc { public static int Main_old() { BasicSelectionTestClass_byte_i_i_tc_Conv cl = new BasicSelectionTestClass_byte_i_i_tc_Conv(); byte val = 1; cl = val; if (cl.GetValuebyte() != 1) return 1; else return 0; } public static bool testMethod() { return (Main_old() == 0); } } class BasicSelectionTestClass_byte_i_e_tc_Conv { private byte value_byte; static public implicit operator byte(BasicSelectionTestClass_byte_i_e_tc_Conv test) { Log.Comment("To byte"); return test.value_byte; } static public implicit operator BasicSelectionTestClass_byte_i_e_tc_Conv(byte val) { Log.Comment("From byte"); BasicSelectionTestClass_byte_i_e_tc_Conv temp = new BasicSelectionTestClass_byte_i_e_tc_Conv(); temp.value_byte = val; return (temp); } public byte GetValuebyte() { return (value_byte); } public void SetValuebyte(byte val) { value_byte = val; } private char value_char; static public implicit operator char(BasicSelectionTestClass_byte_i_e_tc_Conv test) { Log.Comment("To char"); return test.value_char; } static public implicit operator BasicSelectionTestClass_byte_i_e_tc_Conv(char val) { Log.Comment("From char"); BasicSelectionTestClass_byte_i_e_tc_Conv temp = new BasicSelectionTestClass_byte_i_e_tc_Conv(); temp.value_char = val; return (temp); } public char GetValuechar() { return (value_char); } public void SetValuechar(char val) { value_char = val; } private double value_double; static public implicit operator double(BasicSelectionTestClass_byte_i_e_tc_Conv test) { Log.Comment("To double"); return test.value_double; } static public implicit operator BasicSelectionTestClass_byte_i_e_tc_Conv(double val) { Log.Comment("From double"); BasicSelectionTestClass_byte_i_e_tc_Conv temp = new BasicSelectionTestClass_byte_i_e_tc_Conv(); temp.value_double = val; return (temp); } public double GetValuedouble() { return (value_double); } public void SetValuedouble(double val) { value_double = val; } private float value_float; static public implicit operator float(BasicSelectionTestClass_byte_i_e_tc_Conv test) { Log.Comment("To float"); return test.value_float; } static public implicit operator BasicSelectionTestClass_byte_i_e_tc_Conv(float val) { Log.Comment("From float"); BasicSelectionTestClass_byte_i_e_tc_Conv temp = new BasicSelectionTestClass_byte_i_e_tc_Conv(); temp.value_float = val; return (temp); } public float GetValuefloat() { return (value_float); } public void SetValuefloat(float val) { value_float = val; } private int value_int; static public implicit operator int(BasicSelectionTestClass_byte_i_e_tc_Conv test) { Log.Comment("To int"); return test.value_int; } static public implicit operator BasicSelectionTestClass_byte_i_e_tc_Conv(int val) { Log.Comment("From int"); BasicSelectionTestClass_byte_i_e_tc_Conv temp = new BasicSelectionTestClass_byte_i_e_tc_Conv(); temp.value_int = val; return (temp); } public int GetValueint() { return (value_int); } public void SetValueint(int val) { value_int = val; } private long value_long; static public implicit operator long(BasicSelectionTestClass_byte_i_e_tc_Conv test) { Log.Comment("To long"); return test.value_long; } static public implicit operator BasicSelectionTestClass_byte_i_e_tc_Conv(long val) { Log.Comment("From long"); BasicSelectionTestClass_byte_i_e_tc_Conv temp = new BasicSelectionTestClass_byte_i_e_tc_Conv(); temp.value_long = val; return (temp); } public long GetValuelong() { return (value_long); } public void SetValuelong(long val) { value_long = val; } private sbyte value_sbyte; static public implicit operator sbyte(BasicSelectionTestClass_byte_i_e_tc_Conv test) { Log.Comment("To sbyte"); return test.value_sbyte; } static public implicit operator BasicSelectionTestClass_byte_i_e_tc_Conv(sbyte val) { Log.Comment("From sbyte"); BasicSelectionTestClass_byte_i_e_tc_Conv temp = new BasicSelectionTestClass_byte_i_e_tc_Conv(); temp.value_sbyte = val; return (temp); } public sbyte GetValuesbyte() { return (value_sbyte); } public void SetValuesbyte(sbyte val) { value_sbyte = val; } private short value_short; static public implicit operator short(BasicSelectionTestClass_byte_i_e_tc_Conv test) { Log.Comment("To short"); return test.value_short; } static public implicit operator BasicSelectionTestClass_byte_i_e_tc_Conv(short val) { Log.Comment("From short"); BasicSelectionTestClass_byte_i_e_tc_Conv temp = new BasicSelectionTestClass_byte_i_e_tc_Conv(); temp.value_short = val; return (temp); } public short GetValueshort() { return (value_short); } public void SetValueshort(short val) { value_short = val; } private uint value_uint; static public implicit operator uint(BasicSelectionTestClass_byte_i_e_tc_Conv test) { Log.Comment("To uint"); return test.value_uint; } static public implicit operator BasicSelectionTestClass_byte_i_e_tc_Conv(uint val) { Log.Comment("From uint"); BasicSelectionTestClass_byte_i_e_tc_Conv temp = new BasicSelectionTestClass_byte_i_e_tc_Conv(); temp.value_uint = val; return (temp); } public uint GetValueuint() { return (value_uint); } public void SetValueuint(uint val) { value_uint = val; } private ulong value_ulong; static public implicit operator ulong(BasicSelectionTestClass_byte_i_e_tc_Conv test) { Log.Comment("To ulong"); return test.value_ulong; } static public implicit operator BasicSelectionTestClass_byte_i_e_tc_Conv(ulong val) { Log.Comment("From ulong"); BasicSelectionTestClass_byte_i_e_tc_Conv temp = new BasicSelectionTestClass_byte_i_e_tc_Conv(); temp.value_ulong = val; return (temp); } public ulong GetValueulong() { return (value_ulong); } public void SetValueulong(ulong val) { value_ulong = val; } private ushort value_ushort; static public implicit operator ushort(BasicSelectionTestClass_byte_i_e_tc_Conv test) { Log.Comment("To ushort"); return test.value_ushort; } static public implicit operator BasicSelectionTestClass_byte_i_e_tc_Conv(ushort val) { Log.Comment("From ushort"); BasicSelectionTestClass_byte_i_e_tc_Conv temp = new BasicSelectionTestClass_byte_i_e_tc_Conv(); temp.value_ushort = val; return (temp); } public ushort GetValueushort() { return (value_ushort); } public void SetValueushort(ushort val) { value_ushort = val; } } class BasicSelectionTestClass_byte_i_e_tc { public static int Main_old() { BasicSelectionTestClass_byte_i_e_tc_Conv cl = new BasicSelectionTestClass_byte_i_e_tc_Conv(); byte val = 1; cl = (BasicSelectionTestClass_byte_i_e_tc_Conv)val; if (cl.GetValuebyte() != 1) return 1; else return 0; } public static bool testMethod() { return (Main_old() == 0); } } class BasicSelectionTestClass_byte_e_e_tc_Conv { private byte value_byte; static public explicit operator byte(BasicSelectionTestClass_byte_e_e_tc_Conv test) { Log.Comment("To byte"); return test.value_byte; } static public explicit operator BasicSelectionTestClass_byte_e_e_tc_Conv(byte val) { Log.Comment("From byte"); BasicSelectionTestClass_byte_e_e_tc_Conv temp = new BasicSelectionTestClass_byte_e_e_tc_Conv(); temp.value_byte = val; return (temp); } public byte GetValuebyte() { return (value_byte); } public void SetValuebyte(byte val) { value_byte = val; } private char value_char; static public explicit operator char(BasicSelectionTestClass_byte_e_e_tc_Conv test) { Log.Comment("To char"); return test.value_char; } static public explicit operator BasicSelectionTestClass_byte_e_e_tc_Conv(char val) { Log.Comment("From char"); BasicSelectionTestClass_byte_e_e_tc_Conv temp = new BasicSelectionTestClass_byte_e_e_tc_Conv(); temp.value_char = val; return (temp); } public char GetValuechar() { return (value_char); } public void SetValuechar(char val) { value_char = val; } private double value_double; static public explicit operator double(BasicSelectionTestClass_byte_e_e_tc_Conv test) { Log.Comment("To double"); return test.value_double; } static public explicit operator BasicSelectionTestClass_byte_e_e_tc_Conv(double val) { Log.Comment("From double"); BasicSelectionTestClass_byte_e_e_tc_Conv temp = new BasicSelectionTestClass_byte_e_e_tc_Conv(); temp.value_double = val; return (temp); } public double GetValuedouble() { return (value_double); } public void SetValuedouble(double val) { value_double = val; } private float value_float; static public explicit operator float(BasicSelectionTestClass_byte_e_e_tc_Conv test) { Log.Comment("To float"); return test.value_float; } static public explicit operator BasicSelectionTestClass_byte_e_e_tc_Conv(float val) { Log.Comment("From float"); BasicSelectionTestClass_byte_e_e_tc_Conv temp = new BasicSelectionTestClass_byte_e_e_tc_Conv(); temp.value_float = val; return (temp); } public float GetValuefloat() { return (value_float); } public void SetValuefloat(float val) { value_float = val; } private int value_int; static public explicit operator int(BasicSelectionTestClass_byte_e_e_tc_Conv test) { Log.Comment("To int"); return test.value_int; } static public explicit operator BasicSelectionTestClass_byte_e_e_tc_Conv(int val) { Log.Comment("From int"); BasicSelectionTestClass_byte_e_e_tc_Conv temp = new BasicSelectionTestClass_byte_e_e_tc_Conv(); temp.value_int = val; return (temp); } public int GetValueint() { return (value_int); } public void SetValueint(int val) { value_int = val; } private long value_long; static public explicit operator long(BasicSelectionTestClass_byte_e_e_tc_Conv test) { Log.Comment("To long"); return test.value_long; } static public explicit operator BasicSelectionTestClass_byte_e_e_tc_Conv(long val) { Log.Comment("From long"); BasicSelectionTestClass_byte_e_e_tc_Conv temp = new BasicSelectionTestClass_byte_e_e_tc_Conv(); temp.value_long = val; return (temp); } public long GetValuelong() { return (value_long); } public void SetValuelong(long val) { value_long = val; } private sbyte value_sbyte; static public explicit operator sbyte(BasicSelectionTestClass_byte_e_e_tc_Conv test) { Log.Comment("To sbyte"); return test.value_sbyte; } static public explicit operator BasicSelectionTestClass_byte_e_e_tc_Conv(sbyte val) { Log.Comment("From sbyte"); BasicSelectionTestClass_byte_e_e_tc_Conv temp = new BasicSelectionTestClass_byte_e_e_tc_Conv(); temp.value_sbyte = val; return (temp); } public sbyte GetValuesbyte() { return (value_sbyte); } public void SetValuesbyte(sbyte val) { value_sbyte = val; } private short value_short; static public explicit operator short(BasicSelectionTestClass_byte_e_e_tc_Conv test) { Log.Comment("To short"); return test.value_short; } static public explicit operator BasicSelectionTestClass_byte_e_e_tc_Conv(short val) { Log.Comment("From short"); BasicSelectionTestClass_byte_e_e_tc_Conv temp = new BasicSelectionTestClass_byte_e_e_tc_Conv(); temp.value_short = val; return (temp); } public short GetValueshort() { return (value_short); } public void SetValueshort(short val) { value_short = val; } private uint value_uint; static public explicit operator uint(BasicSelectionTestClass_byte_e_e_tc_Conv test) { Log.Comment("To uint"); return test.value_uint; } static public explicit operator BasicSelectionTestClass_byte_e_e_tc_Conv(uint val) { Log.Comment("From uint"); BasicSelectionTestClass_byte_e_e_tc_Conv temp = new BasicSelectionTestClass_byte_e_e_tc_Conv(); temp.value_uint = val; return (temp); } public uint GetValueuint() { return (value_uint); } public void SetValueuint(uint val) { value_uint = val; } private ulong value_ulong; static public explicit operator ulong(BasicSelectionTestClass_byte_e_e_tc_Conv test) { Log.Comment("To ulong"); return test.value_ulong; } static public explicit operator BasicSelectionTestClass_byte_e_e_tc_Conv(ulong val) { Log.Comment("From ulong"); BasicSelectionTestClass_byte_e_e_tc_Conv temp = new BasicSelectionTestClass_byte_e_e_tc_Conv(); temp.value_ulong = val; return (temp); } public ulong GetValueulong() { return (value_ulong); } public void SetValueulong(ulong val) { value_ulong = val; } private ushort value_ushort; static public explicit operator ushort(BasicSelectionTestClass_byte_e_e_tc_Conv test) { Log.Comment("To ushort"); return test.value_ushort; } static public explicit operator BasicSelectionTestClass_byte_e_e_tc_Conv(ushort val) { Log.Comment("From ushort"); BasicSelectionTestClass_byte_e_e_tc_Conv temp = new BasicSelectionTestClass_byte_e_e_tc_Conv(); temp.value_ushort = val; return (temp); } public ushort GetValueushort() { return (value_ushort); } public void SetValueushort(ushort val) { value_ushort = val; } } class BasicSelectionTestClass_byte_e_e_tc { public static int Main_old() { BasicSelectionTestClass_byte_e_e_tc_Conv cl = new BasicSelectionTestClass_byte_e_e_tc_Conv(); byte val = 1; cl = (BasicSelectionTestClass_byte_e_e_tc_Conv)val; if (cl.GetValuebyte() != 1) return 1; else return 0; } public static bool testMethod() { return (Main_old() == 0); } } class BasicSelectionTestClass_byte_i_i_fc_Conv { private byte value_byte; static public implicit operator byte(BasicSelectionTestClass_byte_i_i_fc_Conv test) { Log.Comment("To byte"); return test.value_byte; } static public implicit operator BasicSelectionTestClass_byte_i_i_fc_Conv(byte val) { Log.Comment("From byte"); BasicSelectionTestClass_byte_i_i_fc_Conv temp = new BasicSelectionTestClass_byte_i_i_fc_Conv(); temp.value_byte = val; return (temp); } public byte GetValuebyte() { return (value_byte); } public void SetValuebyte(byte val) { value_byte = val; } private char value_char; static public implicit operator char(BasicSelectionTestClass_byte_i_i_fc_Conv test) { Log.Comment("To char"); return test.value_char; } static public implicit operator BasicSelectionTestClass_byte_i_i_fc_Conv(char val) { Log.Comment("From char"); BasicSelectionTestClass_byte_i_i_fc_Conv temp = new BasicSelectionTestClass_byte_i_i_fc_Conv(); temp.value_char = val; return (temp); } public char GetValuechar() { return (value_char); } public void SetValuechar(char val) { value_char = val; } private double value_double; static public implicit operator double(BasicSelectionTestClass_byte_i_i_fc_Conv test) { Log.Comment("To double"); return test.value_double; } static public implicit operator BasicSelectionTestClass_byte_i_i_fc_Conv(double val) { Log.Comment("From double"); BasicSelectionTestClass_byte_i_i_fc_Conv temp = new BasicSelectionTestClass_byte_i_i_fc_Conv(); temp.value_double = val; return (temp); } public double GetValuedouble() { return (value_double); } public void SetValuedouble(double val) { value_double = val; } private float value_float; static public implicit operator float(BasicSelectionTestClass_byte_i_i_fc_Conv test) { Log.Comment("To float"); return test.value_float; } static public implicit operator BasicSelectionTestClass_byte_i_i_fc_Conv(float val) { Log.Comment("From float"); BasicSelectionTestClass_byte_i_i_fc_Conv temp = new BasicSelectionTestClass_byte_i_i_fc_Conv(); temp.value_float = val; return (temp); } public float GetValuefloat() { return (value_float); } public void SetValuefloat(float val) { value_float = val; } private int value_int; static public implicit operator int(BasicSelectionTestClass_byte_i_i_fc_Conv test) { Log.Comment("To int"); return test.value_int; } static public implicit operator BasicSelectionTestClass_byte_i_i_fc_Conv(int val) { Log.Comment("From int"); BasicSelectionTestClass_byte_i_i_fc_Conv temp = new BasicSelectionTestClass_byte_i_i_fc_Conv(); temp.value_int = val; return (temp); } public int GetValueint() { return (value_int); } public void SetValueint(int val) { value_int = val; } private long value_long; static public implicit operator long(BasicSelectionTestClass_byte_i_i_fc_Conv test) { Log.Comment("To long"); return test.value_long; } static public implicit operator BasicSelectionTestClass_byte_i_i_fc_Conv(long val) { Log.Comment("From long"); BasicSelectionTestClass_byte_i_i_fc_Conv temp = new BasicSelectionTestClass_byte_i_i_fc_Conv(); temp.value_long = val; return (temp); } public long GetValuelong() { return (value_long); } public void SetValuelong(long val) { value_long = val; } private sbyte value_sbyte; static public implicit operator sbyte(BasicSelectionTestClass_byte_i_i_fc_Conv test) { Log.Comment("To sbyte"); return test.value_sbyte; } static public implicit operator BasicSelectionTestClass_byte_i_i_fc_Conv(sbyte val) { Log.Comment("From sbyte"); BasicSelectionTestClass_byte_i_i_fc_Conv temp = new BasicSelectionTestClass_byte_i_i_fc_Conv(); temp.value_sbyte = val; return (temp); } public sbyte GetValuesbyte() { return (value_sbyte); } public void SetValuesbyte(sbyte val) { value_sbyte = val; } private short value_short; static public implicit operator short(BasicSelectionTestClass_byte_i_i_fc_Conv test) { Log.Comment("To short"); return test.value_short; } static public implicit operator BasicSelectionTestClass_byte_i_i_fc_Conv(short val) { Log.Comment("From short"); BasicSelectionTestClass_byte_i_i_fc_Conv temp = new BasicSelectionTestClass_byte_i_i_fc_Conv(); temp.value_short = val; return (temp); } public short GetValueshort() { return (value_short); } public void SetValueshort(short val) { value_short = val; } private uint value_uint; static public implicit operator uint(BasicSelectionTestClass_byte_i_i_fc_Conv test) { Log.Comment("To uint"); return test.value_uint; } static public implicit operator BasicSelectionTestClass_byte_i_i_fc_Conv(uint val) { Log.Comment("From uint"); BasicSelectionTestClass_byte_i_i_fc_Conv temp = new BasicSelectionTestClass_byte_i_i_fc_Conv(); temp.value_uint = val; return (temp); } public uint GetValueuint() { return (value_uint); } public void SetValueuint(uint val) { value_uint = val; } private ulong value_ulong; static public implicit operator ulong(BasicSelectionTestClass_byte_i_i_fc_Conv test) { Log.Comment("To ulong"); return test.value_ulong; } static public implicit operator BasicSelectionTestClass_byte_i_i_fc_Conv(ulong val) { Log.Comment("From ulong"); BasicSelectionTestClass_byte_i_i_fc_Conv temp = new BasicSelectionTestClass_byte_i_i_fc_Conv(); temp.value_ulong = val; return (temp); } public ulong GetValueulong() { return (value_ulong); } public void SetValueulong(ulong val) { value_ulong = val; } private ushort value_ushort; static public implicit operator ushort(BasicSelectionTestClass_byte_i_i_fc_Conv test) { Log.Comment("To ushort"); return test.value_ushort; } static public implicit operator BasicSelectionTestClass_byte_i_i_fc_Conv(ushort val) { Log.Comment("From ushort"); BasicSelectionTestClass_byte_i_i_fc_Conv temp = new BasicSelectionTestClass_byte_i_i_fc_Conv(); temp.value_ushort = val; return (temp); } public ushort GetValueushort() { return (value_ushort); } public void SetValueushort(ushort val) { value_ushort = val; } } class BasicSelectionTestClass_byte_i_i_fc { public static int Main_old() { BasicSelectionTestClass_byte_i_i_fc_Conv cl = new BasicSelectionTestClass_byte_i_i_fc_Conv(); cl.SetValuebyte(1); byte value = cl; if (value != 1) return 1; else return 0; } public static bool testMethod() { return (Main_old() == 0); } } class BasicSelectionTestClass_byte_i_e_fc_Conv { private byte value_byte; static public implicit operator byte(BasicSelectionTestClass_byte_i_e_fc_Conv test) { Log.Comment("To byte"); return test.value_byte; } static public implicit operator BasicSelectionTestClass_byte_i_e_fc_Conv(byte val) { Log.Comment("From byte"); BasicSelectionTestClass_byte_i_e_fc_Conv temp = new BasicSelectionTestClass_byte_i_e_fc_Conv(); temp.value_byte = val; return (temp); } public byte GetValuebyte() { return (value_byte); } public void SetValuebyte(byte val) { value_byte = val; } private char value_char; static public implicit operator char(BasicSelectionTestClass_byte_i_e_fc_Conv test) { Log.Comment("To char"); return test.value_char; } static public implicit operator BasicSelectionTestClass_byte_i_e_fc_Conv(char val) { Log.Comment("From char"); BasicSelectionTestClass_byte_i_e_fc_Conv temp = new BasicSelectionTestClass_byte_i_e_fc_Conv(); temp.value_char = val; return (temp); } public char GetValuechar() { return (value_char); } public void SetValuechar(char val) { value_char = val; } private double value_double; static public implicit operator double(BasicSelectionTestClass_byte_i_e_fc_Conv test) { Log.Comment("To double"); return test.value_double; } static public implicit operator BasicSelectionTestClass_byte_i_e_fc_Conv(double val) { Log.Comment("From double"); BasicSelectionTestClass_byte_i_e_fc_Conv temp = new BasicSelectionTestClass_byte_i_e_fc_Conv(); temp.value_double = val; return (temp); } public double GetValuedouble() { return (value_double); } public void SetValuedouble(double val) { value_double = val; } private float value_float; static public implicit operator float(BasicSelectionTestClass_byte_i_e_fc_Conv test) { Log.Comment("To float"); return test.value_float; } static public implicit operator BasicSelectionTestClass_byte_i_e_fc_Conv(float val) { Log.Comment("From float"); BasicSelectionTestClass_byte_i_e_fc_Conv temp = new BasicSelectionTestClass_byte_i_e_fc_Conv(); temp.value_float = val; return (temp); } public float GetValuefloat() { return (value_float); } public void SetValuefloat(float val) { value_float = val; } private int value_int; static public implicit operator int(BasicSelectionTestClass_byte_i_e_fc_Conv test) { Log.Comment("To int"); return test.value_int; } static public implicit operator BasicSelectionTestClass_byte_i_e_fc_Conv(int val) { Log.Comment("From int"); BasicSelectionTestClass_byte_i_e_fc_Conv temp = new BasicSelectionTestClass_byte_i_e_fc_Conv(); temp.value_int = val; return (temp); } public int GetValueint() { return (value_int); } public void SetValueint(int val) { value_int = val; } private long value_long; static public implicit operator long(BasicSelectionTestClass_byte_i_e_fc_Conv test) { Log.Comment("To long"); return test.value_long; } static public implicit operator BasicSelectionTestClass_byte_i_e_fc_Conv(long val) { Log.Comment("From long"); BasicSelectionTestClass_byte_i_e_fc_Conv temp = new BasicSelectionTestClass_byte_i_e_fc_Conv(); temp.value_long = val; return (temp); } public long GetValuelong() { return (value_long); } public void SetValuelong(long val) { value_long = val; } private sbyte value_sbyte; static public implicit operator sbyte(BasicSelectionTestClass_byte_i_e_fc_Conv test) { Log.Comment("To sbyte"); return test.value_sbyte; } static public implicit operator BasicSelectionTestClass_byte_i_e_fc_Conv(sbyte val) { Log.Comment("From sbyte"); BasicSelectionTestClass_byte_i_e_fc_Conv temp = new BasicSelectionTestClass_byte_i_e_fc_Conv(); temp.value_sbyte = val; return (temp); } public sbyte GetValuesbyte() { return (value_sbyte); } public void SetValuesbyte(sbyte val) { value_sbyte = val; } private short value_short; static public implicit operator short(BasicSelectionTestClass_byte_i_e_fc_Conv test) { Log.Comment("To short"); return test.value_short; } static public implicit operator BasicSelectionTestClass_byte_i_e_fc_Conv(short val) { Log.Comment("From short"); BasicSelectionTestClass_byte_i_e_fc_Conv temp = new BasicSelectionTestClass_byte_i_e_fc_Conv(); temp.value_short = val; return (temp); } public short GetValueshort() { return (value_short); } public void SetValueshort(short val) { value_short = val; } private uint value_uint; static public implicit operator uint(BasicSelectionTestClass_byte_i_e_fc_Conv test) { Log.Comment("To uint"); return test.value_uint; } static public implicit operator BasicSelectionTestClass_byte_i_e_fc_Conv(uint val) { Log.Comment("From uint"); BasicSelectionTestClass_byte_i_e_fc_Conv temp = new BasicSelectionTestClass_byte_i_e_fc_Conv(); temp.value_uint = val; return (temp); } public uint GetValueuint() { return (value_uint); } public void SetValueuint(uint val) { value_uint = val; } private ulong value_ulong; static public implicit operator ulong(BasicSelectionTestClass_byte_i_e_fc_Conv test) { Log.Comment("To ulong"); return test.value_ulong; } static public implicit operator BasicSelectionTestClass_byte_i_e_fc_Conv(ulong val) { Log.Comment("From ulong"); BasicSelectionTestClass_byte_i_e_fc_Conv temp = new BasicSelectionTestClass_byte_i_e_fc_Conv(); temp.value_ulong = val; return (temp); } public ulong GetValueulong() { return (value_ulong); } public void SetValueulong(ulong val) { value_ulong = val; } private ushort value_ushort; static public implicit operator ushort(BasicSelectionTestClass_byte_i_e_fc_Conv test) { Log.Comment("To ushort"); return test.value_ushort; } static public implicit operator BasicSelectionTestClass_byte_i_e_fc_Conv(ushort val) { Log.Comment("From ushort"); BasicSelectionTestClass_byte_i_e_fc_Conv temp = new BasicSelectionTestClass_byte_i_e_fc_Conv(); temp.value_ushort = val; return (temp); } public ushort GetValueushort() { return (value_ushort); } public void SetValueushort(ushort val) { value_ushort = val; } } class BasicSelectionTestClass_byte_i_e_fc { public static int Main_old() { BasicSelectionTestClass_byte_i_e_fc_Conv cl = new BasicSelectionTestClass_byte_i_e_fc_Conv(); cl.SetValuebyte(1); byte value = (byte)cl; if (value != 1) return 1; else return 0; } public static bool testMethod() { return (Main_old() == 0); } } class BasicSelectionTestClass_byte_e_e_fc_Conv { private byte value_byte; static public explicit operator byte(BasicSelectionTestClass_byte_e_e_fc_Conv test) { Log.Comment("To byte"); return test.value_byte; } static public explicit operator BasicSelectionTestClass_byte_e_e_fc_Conv(byte val) { Log.Comment("From byte"); BasicSelectionTestClass_byte_e_e_fc_Conv temp = new BasicSelectionTestClass_byte_e_e_fc_Conv(); temp.value_byte = val; return (temp); } public byte GetValuebyte() { return (value_byte); } public void SetValuebyte(byte val) { value_byte = val; } private char value_char; static public explicit operator char(BasicSelectionTestClass_byte_e_e_fc_Conv test) { Log.Comment("To char"); return test.value_char; } static public explicit operator BasicSelectionTestClass_byte_e_e_fc_Conv(char val) { Log.Comment("From char"); BasicSelectionTestClass_byte_e_e_fc_Conv temp = new BasicSelectionTestClass_byte_e_e_fc_Conv(); temp.value_char = val; return (temp); } public char GetValuechar() { return (value_char); } public void SetValuechar(char val) { value_char = val; } private double value_double; static public explicit operator double(BasicSelectionTestClass_byte_e_e_fc_Conv test) { Log.Comment("To double"); return test.value_double; } static public explicit operator BasicSelectionTestClass_byte_e_e_fc_Conv(double val) { Log.Comment("From double"); BasicSelectionTestClass_byte_e_e_fc_Conv temp = new BasicSelectionTestClass_byte_e_e_fc_Conv(); temp.value_double = val; return (temp); } public double GetValuedouble() { return (value_double); } public void SetValuedouble(double val) { value_double = val; } private float value_float; static public explicit operator float(BasicSelectionTestClass_byte_e_e_fc_Conv test) { Log.Comment("To float"); return test.value_float; } static public explicit operator BasicSelectionTestClass_byte_e_e_fc_Conv(float val) { Log.Comment("From float"); BasicSelectionTestClass_byte_e_e_fc_Conv temp = new BasicSelectionTestClass_byte_e_e_fc_Conv(); temp.value_float = val; return (temp); } public float GetValuefloat() { return (value_float); } public void SetValuefloat(float val) { value_float = val; } private int value_int; static public explicit operator int(BasicSelectionTestClass_byte_e_e_fc_Conv test) { Log.Comment("To int"); return test.value_int; } static public explicit operator BasicSelectionTestClass_byte_e_e_fc_Conv(int val) { Log.Comment("From int"); BasicSelectionTestClass_byte_e_e_fc_Conv temp = new BasicSelectionTestClass_byte_e_e_fc_Conv(); temp.value_int = val; return (temp); } public int GetValueint() { return (value_int); } public void SetValueint(int val) { value_int = val; } private long value_long; static public explicit operator long(BasicSelectionTestClass_byte_e_e_fc_Conv test) { Log.Comment("To long"); return test.value_long; } static public explicit operator BasicSelectionTestClass_byte_e_e_fc_Conv(long val) { Log.Comment("From long"); BasicSelectionTestClass_byte_e_e_fc_Conv temp = new BasicSelectionTestClass_byte_e_e_fc_Conv(); temp.value_long = val; return (temp); } public long GetValuelong() { return (value_long); } public void SetValuelong(long val) { value_long = val; } private sbyte value_sbyte; static public explicit operator sbyte(BasicSelectionTestClass_byte_e_e_fc_Conv test) { Log.Comment("To sbyte"); return test.value_sbyte; } static public explicit operator BasicSelectionTestClass_byte_e_e_fc_Conv(sbyte val) { Log.Comment("From sbyte"); BasicSelectionTestClass_byte_e_e_fc_Conv temp = new BasicSelectionTestClass_byte_e_e_fc_Conv(); temp.value_sbyte = val; return (temp); } public sbyte GetValuesbyte() { return (value_sbyte); } public void SetValuesbyte(sbyte val) { value_sbyte = val; } private short value_short; static public explicit operator short(BasicSelectionTestClass_byte_e_e_fc_Conv test) { Log.Comment("To short"); return test.value_short; } static public explicit operator BasicSelectionTestClass_byte_e_e_fc_Conv(short val) { Log.Comment("From short"); BasicSelectionTestClass_byte_e_e_fc_Conv temp = new BasicSelectionTestClass_byte_e_e_fc_Conv(); temp.value_short = val; return (temp); } public short GetValueshort() { return (value_short); } public void SetValueshort(short val) { value_short = val; } private uint value_uint; static public explicit operator uint(BasicSelectionTestClass_byte_e_e_fc_Conv test) { Log.Comment("To uint"); return test.value_uint; } static public explicit operator BasicSelectionTestClass_byte_e_e_fc_Conv(uint val) { Log.Comment("From uint"); BasicSelectionTestClass_byte_e_e_fc_Conv temp = new BasicSelectionTestClass_byte_e_e_fc_Conv(); temp.value_uint = val; return (temp); } public uint GetValueuint() { return (value_uint); } public void SetValueuint(uint val) { value_uint = val; } private ulong value_ulong; static public explicit operator ulong(BasicSelectionTestClass_byte_e_e_fc_Conv test) { Log.Comment("To ulong"); return test.value_ulong; } static public explicit operator BasicSelectionTestClass_byte_e_e_fc_Conv(ulong val) { Log.Comment("From ulong"); BasicSelectionTestClass_byte_e_e_fc_Conv temp = new BasicSelectionTestClass_byte_e_e_fc_Conv(); temp.value_ulong = val; return (temp); } public ulong GetValueulong() { return (value_ulong); } public void SetValueulong(ulong val) { value_ulong = val; } private ushort value_ushort; static public explicit operator ushort(BasicSelectionTestClass_byte_e_e_fc_Conv test) { Log.Comment("To ushort"); return test.value_ushort; } static public explicit operator BasicSelectionTestClass_byte_e_e_fc_Conv(ushort val) { Log.Comment("From ushort"); BasicSelectionTestClass_byte_e_e_fc_Conv temp = new BasicSelectionTestClass_byte_e_e_fc_Conv(); temp.value_ushort = val; return (temp); } public ushort GetValueushort() { return (value_ushort); } public void SetValueushort(ushort val) { value_ushort = val; } } class BasicSelectionTestClass_byte_e_e_fc { public static int Main_old() { BasicSelectionTestClass_byte_e_e_fc_Conv cl = new BasicSelectionTestClass_byte_e_e_fc_Conv(); cl.SetValuebyte(1); byte value = (byte)cl; if (value != 1) return 1; else return 0; } public static bool testMethod() { return (Main_old() == 0); } } class BasicSelectionTestClass_char_i_i_tc_Conv { private byte value_byte; static public implicit operator byte(BasicSelectionTestClass_char_i_i_tc_Conv test) { Log.Comment("To byte"); return test.value_byte; } static public implicit operator BasicSelectionTestClass_char_i_i_tc_Conv(byte val) { Log.Comment("From byte"); BasicSelectionTestClass_char_i_i_tc_Conv temp = new BasicSelectionTestClass_char_i_i_tc_Conv(); temp.value_byte = val; return (temp); } public byte GetValuebyte() { return (value_byte); } public void SetValuebyte(byte val) { value_byte = val; } private char value_char; static public implicit operator char(BasicSelectionTestClass_char_i_i_tc_Conv test) { Log.Comment("To char"); return test.value_char; } static public implicit operator BasicSelectionTestClass_char_i_i_tc_Conv(char val) { Log.Comment("From char"); BasicSelectionTestClass_char_i_i_tc_Conv temp = new BasicSelectionTestClass_char_i_i_tc_Conv(); temp.value_char = val; return (temp); } public char GetValuechar() { return (value_char); } public void SetValuechar(char val) { value_char = val; } private double value_double; static public implicit operator double(BasicSelectionTestClass_char_i_i_tc_Conv test) { Log.Comment("To double"); return test.value_double; } static public implicit operator BasicSelectionTestClass_char_i_i_tc_Conv(double val) { Log.Comment("From double"); BasicSelectionTestClass_char_i_i_tc_Conv temp = new BasicSelectionTestClass_char_i_i_tc_Conv(); temp.value_double = val; return (temp); } public double GetValuedouble() { return (value_double); } public void SetValuedouble(double val) { value_double = val; } private float value_float; static public implicit operator float(BasicSelectionTestClass_char_i_i_tc_Conv test) { Log.Comment("To float"); return test.value_float; } static public implicit operator BasicSelectionTestClass_char_i_i_tc_Conv(float val) { Log.Comment("From float"); BasicSelectionTestClass_char_i_i_tc_Conv temp = new BasicSelectionTestClass_char_i_i_tc_Conv(); temp.value_float = val; return (temp); } public float GetValuefloat() { return (value_float); } public void SetValuefloat(float val) { value_float = val; } private int value_int; static public implicit operator int(BasicSelectionTestClass_char_i_i_tc_Conv test) { Log.Comment("To int"); return test.value_int; } static public implicit operator BasicSelectionTestClass_char_i_i_tc_Conv(int val) { Log.Comment("From int"); BasicSelectionTestClass_char_i_i_tc_Conv temp = new BasicSelectionTestClass_char_i_i_tc_Conv(); temp.value_int = val; return (temp); } public int GetValueint() { return (value_int); } public void SetValueint(int val) { value_int = val; } private long value_long; static public implicit operator long(BasicSelectionTestClass_char_i_i_tc_Conv test) { Log.Comment("To long"); return test.value_long; } static public implicit operator BasicSelectionTestClass_char_i_i_tc_Conv(long val) { Log.Comment("From long"); BasicSelectionTestClass_char_i_i_tc_Conv temp = new BasicSelectionTestClass_char_i_i_tc_Conv(); temp.value_long = val; return (temp); } public long GetValuelong() { return (value_long); } public void SetValuelong(long val) { value_long = val; } private sbyte value_sbyte; static public implicit operator sbyte(BasicSelectionTestClass_char_i_i_tc_Conv test) { Log.Comment("To sbyte"); return test.value_sbyte; } static public implicit operator BasicSelectionTestClass_char_i_i_tc_Conv(sbyte val) { Log.Comment("From sbyte"); BasicSelectionTestClass_char_i_i_tc_Conv temp = new BasicSelectionTestClass_char_i_i_tc_Conv(); temp.value_sbyte = val; return (temp); } public sbyte GetValuesbyte() { return (value_sbyte); } public void SetValuesbyte(sbyte val) { value_sbyte = val; } private short value_short; static public implicit operator short(BasicSelectionTestClass_char_i_i_tc_Conv test) { Log.Comment("To short"); return test.value_short; } static public implicit operator BasicSelectionTestClass_char_i_i_tc_Conv(short val) { Log.Comment("From short"); BasicSelectionTestClass_char_i_i_tc_Conv temp = new BasicSelectionTestClass_char_i_i_tc_Conv(); temp.value_short = val; return (temp); } public short GetValueshort() { return (value_short); } public void SetValueshort(short val) { value_short = val; } private uint value_uint; static public implicit operator uint(BasicSelectionTestClass_char_i_i_tc_Conv test) { Log.Comment("To uint"); return test.value_uint; } static public implicit operator BasicSelectionTestClass_char_i_i_tc_Conv(uint val) { Log.Comment("From uint"); BasicSelectionTestClass_char_i_i_tc_Conv temp = new BasicSelectionTestClass_char_i_i_tc_Conv(); temp.value_uint = val; return (temp); } public uint GetValueuint() { return (value_uint); } public void SetValueuint(uint val) { value_uint = val; } private ulong value_ulong; static public implicit operator ulong(BasicSelectionTestClass_char_i_i_tc_Conv test) { Log.Comment("To ulong"); return test.value_ulong; } static public implicit operator BasicSelectionTestClass_char_i_i_tc_Conv(ulong val) { Log.Comment("From ulong"); BasicSelectionTestClass_char_i_i_tc_Conv temp = new BasicSelectionTestClass_char_i_i_tc_Conv(); temp.value_ulong = val; return (temp); } public ulong GetValueulong() { return (value_ulong); } public void SetValueulong(ulong val) { value_ulong = val; } private ushort value_ushort; static public implicit operator ushort(BasicSelectionTestClass_char_i_i_tc_Conv test) { Log.Comment("To ushort"); return test.value_ushort; } static public implicit operator BasicSelectionTestClass_char_i_i_tc_Conv(ushort val) { Log.Comment("From ushort"); BasicSelectionTestClass_char_i_i_tc_Conv temp = new BasicSelectionTestClass_char_i_i_tc_Conv(); temp.value_ushort = val; return (temp); } public ushort GetValueushort() { return (value_ushort); } public void SetValueushort(ushort val) { value_ushort = val; } } class BasicSelectionTestClass_char_i_i_tc { public static int Main_old() { BasicSelectionTestClass_char_i_i_tc_Conv cl = new BasicSelectionTestClass_char_i_i_tc_Conv(); char val = '\x1'; cl = val; if (cl.GetValuechar() != '\x1') return 1; else return 0; } public static bool testMethod() { return (Main_old() == 0); } } class BasicSelectionTestClass_char_i_e_tc_Conv { private byte value_byte; static public implicit operator byte(BasicSelectionTestClass_char_i_e_tc_Conv test) { Log.Comment("To byte"); return test.value_byte; } static public implicit operator BasicSelectionTestClass_char_i_e_tc_Conv(byte val) { Log.Comment("From byte"); BasicSelectionTestClass_char_i_e_tc_Conv temp = new BasicSelectionTestClass_char_i_e_tc_Conv(); temp.value_byte = val; return (temp); } public byte GetValuebyte() { return (value_byte); } public void SetValuebyte(byte val) { value_byte = val; } private char value_char; static public implicit operator char(BasicSelectionTestClass_char_i_e_tc_Conv test) { Log.Comment("To char"); return test.value_char; } static public implicit operator BasicSelectionTestClass_char_i_e_tc_Conv(char val) { Log.Comment("From char"); BasicSelectionTestClass_char_i_e_tc_Conv temp = new BasicSelectionTestClass_char_i_e_tc_Conv(); temp.value_char = val; return (temp); } public char GetValuechar() { return (value_char); } public void SetValuechar(char val) { value_char = val; } private double value_double; static public implicit operator double(BasicSelectionTestClass_char_i_e_tc_Conv test) { Log.Comment("To double"); return test.value_double; } static public implicit operator BasicSelectionTestClass_char_i_e_tc_Conv(double val) { Log.Comment("From double"); BasicSelectionTestClass_char_i_e_tc_Conv temp = new BasicSelectionTestClass_char_i_e_tc_Conv(); temp.value_double = val; return (temp); } public double GetValuedouble() { return (value_double); } public void SetValuedouble(double val) { value_double = val; } private float value_float; static public implicit operator float(BasicSelectionTestClass_char_i_e_tc_Conv test) { Log.Comment("To float"); return test.value_float; } static public implicit operator BasicSelectionTestClass_char_i_e_tc_Conv(float val) { Log.Comment("From float"); BasicSelectionTestClass_char_i_e_tc_Conv temp = new BasicSelectionTestClass_char_i_e_tc_Conv(); temp.value_float = val; return (temp); } public float GetValuefloat() { return (value_float); } public void SetValuefloat(float val) { value_float = val; } private int value_int; static public implicit operator int(BasicSelectionTestClass_char_i_e_tc_Conv test) { Log.Comment("To int"); return test.value_int; } static public implicit operator BasicSelectionTestClass_char_i_e_tc_Conv(int val) { Log.Comment("From int"); BasicSelectionTestClass_char_i_e_tc_Conv temp = new BasicSelectionTestClass_char_i_e_tc_Conv(); temp.value_int = val; return (temp); } public int GetValueint() { return (value_int); } public void SetValueint(int val) { value_int = val; } private long value_long; static public implicit operator long(BasicSelectionTestClass_char_i_e_tc_Conv test) { Log.Comment("To long"); return test.value_long; } static public implicit operator BasicSelectionTestClass_char_i_e_tc_Conv(long val) { Log.Comment("From long"); BasicSelectionTestClass_char_i_e_tc_Conv temp = new BasicSelectionTestClass_char_i_e_tc_Conv(); temp.value_long = val; return (temp); } public long GetValuelong() { return (value_long); } public void SetValuelong(long val) { value_long = val; } private sbyte value_sbyte; static public implicit operator sbyte(BasicSelectionTestClass_char_i_e_tc_Conv test) { Log.Comment("To sbyte"); return test.value_sbyte; } static public implicit operator BasicSelectionTestClass_char_i_e_tc_Conv(sbyte val) { Log.Comment("From sbyte"); BasicSelectionTestClass_char_i_e_tc_Conv temp = new BasicSelectionTestClass_char_i_e_tc_Conv(); temp.value_sbyte = val; return (temp); } public sbyte GetValuesbyte() { return (value_sbyte); } public void SetValuesbyte(sbyte val) { value_sbyte = val; } private short value_short; static public implicit operator short(BasicSelectionTestClass_char_i_e_tc_Conv test) { Log.Comment("To short"); return test.value_short; } static public implicit operator BasicSelectionTestClass_char_i_e_tc_Conv(short val) { Log.Comment("From short"); BasicSelectionTestClass_char_i_e_tc_Conv temp = new BasicSelectionTestClass_char_i_e_tc_Conv(); temp.value_short = val; return (temp); } public short GetValueshort() { return (value_short); } public void SetValueshort(short val) { value_short = val; } private uint value_uint; static public implicit operator uint(BasicSelectionTestClass_char_i_e_tc_Conv test) { Log.Comment("To uint"); return test.value_uint; } static public implicit operator BasicSelectionTestClass_char_i_e_tc_Conv(uint val) { Log.Comment("From uint"); BasicSelectionTestClass_char_i_e_tc_Conv temp = new BasicSelectionTestClass_char_i_e_tc_Conv(); temp.value_uint = val; return (temp); } public uint GetValueuint() { return (value_uint); } public void SetValueuint(uint val) { value_uint = val; } private ulong value_ulong; static public implicit operator ulong(BasicSelectionTestClass_char_i_e_tc_Conv test) { Log.Comment("To ulong"); return test.value_ulong; } static public implicit operator BasicSelectionTestClass_char_i_e_tc_Conv(ulong val) { Log.Comment("From ulong"); BasicSelectionTestClass_char_i_e_tc_Conv temp = new BasicSelectionTestClass_char_i_e_tc_Conv(); temp.value_ulong = val; return (temp); } public ulong GetValueulong() { return (value_ulong); } public void SetValueulong(ulong val) { value_ulong = val; } private ushort value_ushort; static public implicit operator ushort(BasicSelectionTestClass_char_i_e_tc_Conv test) { Log.Comment("To ushort"); return test.value_ushort; } static public implicit operator BasicSelectionTestClass_char_i_e_tc_Conv(ushort val) { Log.Comment("From ushort"); BasicSelectionTestClass_char_i_e_tc_Conv temp = new BasicSelectionTestClass_char_i_e_tc_Conv(); temp.value_ushort = val; return (temp); } public ushort GetValueushort() { return (value_ushort); } public void SetValueushort(ushort val) { value_ushort = val; } } class BasicSelectionTestClass_char_i_e_tc { public static int Main_old() { BasicSelectionTestClass_char_i_e_tc_Conv cl = new BasicSelectionTestClass_char_i_e_tc_Conv(); char val = '\x1'; cl = (BasicSelectionTestClass_char_i_e_tc_Conv)val; if (cl.GetValuechar() != '\x1') return 1; else return 0; } public static bool testMethod() { return (Main_old() == 0); } } class BasicSelectionTestClass_char_e_e_tc_Conv { private byte value_byte; static public explicit operator byte(BasicSelectionTestClass_char_e_e_tc_Conv test) { Log.Comment("To byte"); return test.value_byte; } static public explicit operator BasicSelectionTestClass_char_e_e_tc_Conv(byte val) { Log.Comment("From byte"); BasicSelectionTestClass_char_e_e_tc_Conv temp = new BasicSelectionTestClass_char_e_e_tc_Conv(); temp.value_byte = val; return (temp); } public byte GetValuebyte() { return (value_byte); } public void SetValuebyte(byte val) { value_byte = val; } private char value_char; static public explicit operator char(BasicSelectionTestClass_char_e_e_tc_Conv test) { Log.Comment("To char"); return test.value_char; } static public explicit operator BasicSelectionTestClass_char_e_e_tc_Conv(char val) { Log.Comment("From char"); BasicSelectionTestClass_char_e_e_tc_Conv temp = new BasicSelectionTestClass_char_e_e_tc_Conv(); temp.value_char = val; return (temp); } public char GetValuechar() { return (value_char); } public void SetValuechar(char val) { value_char = val; } private double value_double; static public explicit operator double(BasicSelectionTestClass_char_e_e_tc_Conv test) { Log.Comment("To double"); return test.value_double; } static public explicit operator BasicSelectionTestClass_char_e_e_tc_Conv(double val) { Log.Comment("From double"); BasicSelectionTestClass_char_e_e_tc_Conv temp = new BasicSelectionTestClass_char_e_e_tc_Conv(); temp.value_double = val; return (temp); } public double GetValuedouble() { return (value_double); } public void SetValuedouble(double val) { value_double = val; } private float value_float; static public explicit operator float(BasicSelectionTestClass_char_e_e_tc_Conv test) { Log.Comment("To float"); return test.value_float; } static public explicit operator BasicSelectionTestClass_char_e_e_tc_Conv(float val) { Log.Comment("From float"); BasicSelectionTestClass_char_e_e_tc_Conv temp = new BasicSelectionTestClass_char_e_e_tc_Conv(); temp.value_float = val; return (temp); } public float GetValuefloat() { return (value_float); } public void SetValuefloat(float val) { value_float = val; } private int value_int; static public explicit operator int(BasicSelectionTestClass_char_e_e_tc_Conv test) { Log.Comment("To int"); return test.value_int; } static public explicit operator BasicSelectionTestClass_char_e_e_tc_Conv(int val) { Log.Comment("From int"); BasicSelectionTestClass_char_e_e_tc_Conv temp = new BasicSelectionTestClass_char_e_e_tc_Conv(); temp.value_int = val; return (temp); } public int GetValueint() { return (value_int); } public void SetValueint(int val) { value_int = val; } private long value_long; static public explicit operator long(BasicSelectionTestClass_char_e_e_tc_Conv test) { Log.Comment("To long"); return test.value_long; } static public explicit operator BasicSelectionTestClass_char_e_e_tc_Conv(long val) { Log.Comment("From long"); BasicSelectionTestClass_char_e_e_tc_Conv temp = new BasicSelectionTestClass_char_e_e_tc_Conv(); temp.value_long = val; return (temp); } public long GetValuelong() { return (value_long); } public void SetValuelong(long val) { value_long = val; } private sbyte value_sbyte; static public explicit operator sbyte(BasicSelectionTestClass_char_e_e_tc_Conv test) { Log.Comment("To sbyte"); return test.value_sbyte; } static public explicit operator BasicSelectionTestClass_char_e_e_tc_Conv(sbyte val) { Log.Comment("From sbyte"); BasicSelectionTestClass_char_e_e_tc_Conv temp = new BasicSelectionTestClass_char_e_e_tc_Conv(); temp.value_sbyte = val; return (temp); } public sbyte GetValuesbyte() { return (value_sbyte); } public void SetValuesbyte(sbyte val) { value_sbyte = val; } private short value_short; static public explicit operator short(BasicSelectionTestClass_char_e_e_tc_Conv test) { Log.Comment("To short"); return test.value_short; } static public explicit operator BasicSelectionTestClass_char_e_e_tc_Conv(short val) { Log.Comment("From short"); BasicSelectionTestClass_char_e_e_tc_Conv temp = new BasicSelectionTestClass_char_e_e_tc_Conv(); temp.value_short = val; return (temp); } public short GetValueshort() { return (value_short); } public void SetValueshort(short val) { value_short = val; } private uint value_uint; static public explicit operator uint(BasicSelectionTestClass_char_e_e_tc_Conv test) { Log.Comment("To uint"); return test.value_uint; } static public explicit operator BasicSelectionTestClass_char_e_e_tc_Conv(uint val) { Log.Comment("From uint"); BasicSelectionTestClass_char_e_e_tc_Conv temp = new BasicSelectionTestClass_char_e_e_tc_Conv(); temp.value_uint = val; return (temp); } public uint GetValueuint() { return (value_uint); } public void SetValueuint(uint val) { value_uint = val; } private ulong value_ulong; static public explicit operator ulong(BasicSelectionTestClass_char_e_e_tc_Conv test) { Log.Comment("To ulong"); return test.value_ulong; } static public explicit operator BasicSelectionTestClass_char_e_e_tc_Conv(ulong val) { Log.Comment("From ulong"); BasicSelectionTestClass_char_e_e_tc_Conv temp = new BasicSelectionTestClass_char_e_e_tc_Conv(); temp.value_ulong = val; return (temp); } public ulong GetValueulong() { return (value_ulong); } public void SetValueulong(ulong val) { value_ulong = val; } private ushort value_ushort; static public explicit operator ushort(BasicSelectionTestClass_char_e_e_tc_Conv test) { Log.Comment("To ushort"); return test.value_ushort; } static public explicit operator BasicSelectionTestClass_char_e_e_tc_Conv(ushort val) { Log.Comment("From ushort"); BasicSelectionTestClass_char_e_e_tc_Conv temp = new BasicSelectionTestClass_char_e_e_tc_Conv(); temp.value_ushort = val; return (temp); } public ushort GetValueushort() { return (value_ushort); } public void SetValueushort(ushort val) { value_ushort = val; } } class BasicSelectionTestClass_char_e_e_tc { public static int Main_old() { BasicSelectionTestClass_char_e_e_tc_Conv cl = new BasicSelectionTestClass_char_e_e_tc_Conv(); char val = '\x1'; cl = (BasicSelectionTestClass_char_e_e_tc_Conv)val; if (cl.GetValuechar() != '\x1') return 1; else return 0; } public static bool testMethod() { return (Main_old() == 0); } } class BasicSelectionTestClass_char_i_i_fc_Conv { private byte value_byte; static public implicit operator byte(BasicSelectionTestClass_char_i_i_fc_Conv test) { Log.Comment("To byte"); return test.value_byte; } static public implicit operator BasicSelectionTestClass_char_i_i_fc_Conv(byte val) { Log.Comment("From byte"); BasicSelectionTestClass_char_i_i_fc_Conv temp = new BasicSelectionTestClass_char_i_i_fc_Conv(); temp.value_byte = val; return (temp); } public byte GetValuebyte() { return (value_byte); } public void SetValuebyte(byte val) { value_byte = val; } private char value_char; static public implicit operator char(BasicSelectionTestClass_char_i_i_fc_Conv test) { Log.Comment("To char"); return test.value_char; } static public implicit operator BasicSelectionTestClass_char_i_i_fc_Conv(char val) { Log.Comment("From char"); BasicSelectionTestClass_char_i_i_fc_Conv temp = new BasicSelectionTestClass_char_i_i_fc_Conv(); temp.value_char = val; return (temp); } public char GetValuechar() { return (value_char); } public void SetValuechar(char val) { value_char = val; } private double value_double; static public implicit operator double(BasicSelectionTestClass_char_i_i_fc_Conv test) { Log.Comment("To double"); return test.value_double; } static public implicit operator BasicSelectionTestClass_char_i_i_fc_Conv(double val) { Log.Comment("From double"); BasicSelectionTestClass_char_i_i_fc_Conv temp = new BasicSelectionTestClass_char_i_i_fc_Conv(); temp.value_double = val; return (temp); } public double GetValuedouble() { return (value_double); } public void SetValuedouble(double val) { value_double = val; } private float value_float; static public implicit operator float(BasicSelectionTestClass_char_i_i_fc_Conv test) { Log.Comment("To float"); return test.value_float; } static public implicit operator BasicSelectionTestClass_char_i_i_fc_Conv(float val) { Log.Comment("From float"); BasicSelectionTestClass_char_i_i_fc_Conv temp = new BasicSelectionTestClass_char_i_i_fc_Conv(); temp.value_float = val; return (temp); } public float GetValuefloat() { return (value_float); } public void SetValuefloat(float val) { value_float = val; } private int value_int; static public implicit operator int(BasicSelectionTestClass_char_i_i_fc_Conv test) { Log.Comment("To int"); return test.value_int; } static public implicit operator BasicSelectionTestClass_char_i_i_fc_Conv(int val) { Log.Comment("From int"); BasicSelectionTestClass_char_i_i_fc_Conv temp = new BasicSelectionTestClass_char_i_i_fc_Conv(); temp.value_int = val; return (temp); } public int GetValueint() { return (value_int); } public void SetValueint(int val) { value_int = val; } private long value_long; static public implicit operator long(BasicSelectionTestClass_char_i_i_fc_Conv test) { Log.Comment("To long"); return test.value_long; } static public implicit operator BasicSelectionTestClass_char_i_i_fc_Conv(long val) { Log.Comment("From long"); BasicSelectionTestClass_char_i_i_fc_Conv temp = new BasicSelectionTestClass_char_i_i_fc_Conv(); temp.value_long = val; return (temp); } public long GetValuelong() { return (value_long); } public void SetValuelong(long val) { value_long = val; } private sbyte value_sbyte; static public implicit operator sbyte(BasicSelectionTestClass_char_i_i_fc_Conv test) { Log.Comment("To sbyte"); return test.value_sbyte; } static public implicit operator BasicSelectionTestClass_char_i_i_fc_Conv(sbyte val) { Log.Comment("From sbyte"); BasicSelectionTestClass_char_i_i_fc_Conv temp = new BasicSelectionTestClass_char_i_i_fc_Conv(); temp.value_sbyte = val; return (temp); } public sbyte GetValuesbyte() { return (value_sbyte); } public void SetValuesbyte(sbyte val) { value_sbyte = val; } private short value_short; static public implicit operator short(BasicSelectionTestClass_char_i_i_fc_Conv test) { Log.Comment("To short"); return test.value_short; } static public implicit operator BasicSelectionTestClass_char_i_i_fc_Conv(short val) { Log.Comment("From short"); BasicSelectionTestClass_char_i_i_fc_Conv temp = new BasicSelectionTestClass_char_i_i_fc_Conv(); temp.value_short = val; return (temp); } public short GetValueshort() { return (value_short); } public void SetValueshort(short val) { value_short = val; } private uint value_uint; static public implicit operator uint(BasicSelectionTestClass_char_i_i_fc_Conv test) { Log.Comment("To uint"); return test.value_uint; } static public implicit operator BasicSelectionTestClass_char_i_i_fc_Conv(uint val) { Log.Comment("From uint"); BasicSelectionTestClass_char_i_i_fc_Conv temp = new BasicSelectionTestClass_char_i_i_fc_Conv(); temp.value_uint = val; return (temp); } public uint GetValueuint() { return (value_uint); } public void SetValueuint(uint val) { value_uint = val; } private ulong value_ulong; static public implicit operator ulong(BasicSelectionTestClass_char_i_i_fc_Conv test) { Log.Comment("To ulong"); return test.value_ulong; } static public implicit operator BasicSelectionTestClass_char_i_i_fc_Conv(ulong val) { Log.Comment("From ulong"); BasicSelectionTestClass_char_i_i_fc_Conv temp = new BasicSelectionTestClass_char_i_i_fc_Conv(); temp.value_ulong = val; return (temp); } public ulong GetValueulong() { return (value_ulong); } public void SetValueulong(ulong val) { value_ulong = val; } private ushort value_ushort; static public implicit operator ushort(BasicSelectionTestClass_char_i_i_fc_Conv test) { Log.Comment("To ushort"); return test.value_ushort; } static public implicit operator BasicSelectionTestClass_char_i_i_fc_Conv(ushort val) { Log.Comment("From ushort"); BasicSelectionTestClass_char_i_i_fc_Conv temp = new BasicSelectionTestClass_char_i_i_fc_Conv(); temp.value_ushort = val; return (temp); } public ushort GetValueushort() { return (value_ushort); } public void SetValueushort(ushort val) { value_ushort = val; } } class BasicSelectionTestClass_char_i_i_fc { public static int Main_old() { BasicSelectionTestClass_char_i_i_fc_Conv cl = new BasicSelectionTestClass_char_i_i_fc_Conv(); cl.SetValuechar('\x1'); char value = cl; if (value != '\x1') return 1; else return 0; } public static bool testMethod() { return (Main_old() == 0); } } class BasicSelectionTestClass_char_i_e_fc_Conv { private byte value_byte; static public implicit operator byte(BasicSelectionTestClass_char_i_e_fc_Conv test) { Log.Comment("To byte"); return test.value_byte; } static public implicit operator BasicSelectionTestClass_char_i_e_fc_Conv(byte val) { Log.Comment("From byte"); BasicSelectionTestClass_char_i_e_fc_Conv temp = new BasicSelectionTestClass_char_i_e_fc_Conv(); temp.value_byte = val; return (temp); } public byte GetValuebyte() { return (value_byte); } public void SetValuebyte(byte val) { value_byte = val; } private char value_char; static public implicit operator char(BasicSelectionTestClass_char_i_e_fc_Conv test) { Log.Comment("To char"); return test.value_char; } static public implicit operator BasicSelectionTestClass_char_i_e_fc_Conv(char val) { Log.Comment("From char"); BasicSelectionTestClass_char_i_e_fc_Conv temp = new BasicSelectionTestClass_char_i_e_fc_Conv(); temp.value_char = val; return (temp); } public char GetValuechar() { return (value_char); } public void SetValuechar(char val) { value_char = val; } private double value_double; static public implicit operator double(BasicSelectionTestClass_char_i_e_fc_Conv test) { Log.Comment("To double"); return test.value_double; } static public implicit operator BasicSelectionTestClass_char_i_e_fc_Conv(double val) { Log.Comment("From double"); BasicSelectionTestClass_char_i_e_fc_Conv temp = new BasicSelectionTestClass_char_i_e_fc_Conv(); temp.value_double = val; return (temp); } public double GetValuedouble() { return (value_double); } public void SetValuedouble(double val) { value_double = val; } private float value_float; static public implicit operator float(BasicSelectionTestClass_char_i_e_fc_Conv test) { Log.Comment("To float"); return test.value_float; } static public implicit operator BasicSelectionTestClass_char_i_e_fc_Conv(float val) { Log.Comment("From float"); BasicSelectionTestClass_char_i_e_fc_Conv temp = new BasicSelectionTestClass_char_i_e_fc_Conv(); temp.value_float = val; return (temp); } public float GetValuefloat() { return (value_float); } public void SetValuefloat(float val) { value_float = val; } private int value_int; static public implicit operator int(BasicSelectionTestClass_char_i_e_fc_Conv test) { Log.Comment("To int"); return test.value_int; } static public implicit operator BasicSelectionTestClass_char_i_e_fc_Conv(int val) { Log.Comment("From int"); BasicSelectionTestClass_char_i_e_fc_Conv temp = new BasicSelectionTestClass_char_i_e_fc_Conv(); temp.value_int = val; return (temp); } public int GetValueint() { return (value_int); } public void SetValueint(int val) { value_int = val; } private long value_long; static public implicit operator long(BasicSelectionTestClass_char_i_e_fc_Conv test) { Log.Comment("To long"); return test.value_long; } static public implicit operator BasicSelectionTestClass_char_i_e_fc_Conv(long val) { Log.Comment("From long"); BasicSelectionTestClass_char_i_e_fc_Conv temp = new BasicSelectionTestClass_char_i_e_fc_Conv(); temp.value_long = val; return (temp); } public long GetValuelong() { return (value_long); } public void SetValuelong(long val) { value_long = val; } private sbyte value_sbyte; static public implicit operator sbyte(BasicSelectionTestClass_char_i_e_fc_Conv test) { Log.Comment("To sbyte"); return test.value_sbyte; } static public implicit operator BasicSelectionTestClass_char_i_e_fc_Conv(sbyte val) { Log.Comment("From sbyte"); BasicSelectionTestClass_char_i_e_fc_Conv temp = new BasicSelectionTestClass_char_i_e_fc_Conv(); temp.value_sbyte = val; return (temp); } public sbyte GetValuesbyte() { return (value_sbyte); } public void SetValuesbyte(sbyte val) { value_sbyte = val; } private short value_short; static public implicit operator short(BasicSelectionTestClass_char_i_e_fc_Conv test) { Log.Comment("To short"); return test.value_short; } static public implicit operator BasicSelectionTestClass_char_i_e_fc_Conv(short val) { Log.Comment("From short"); BasicSelectionTestClass_char_i_e_fc_Conv temp = new BasicSelectionTestClass_char_i_e_fc_Conv(); temp.value_short = val; return (temp); } public short GetValueshort() { return (value_short); } public void SetValueshort(short val) { value_short = val; } private uint value_uint; static public implicit operator uint(BasicSelectionTestClass_char_i_e_fc_Conv test) { Log.Comment("To uint"); return test.value_uint; } static public implicit operator BasicSelectionTestClass_char_i_e_fc_Conv(uint val) { Log.Comment("From uint"); BasicSelectionTestClass_char_i_e_fc_Conv temp = new BasicSelectionTestClass_char_i_e_fc_Conv(); temp.value_uint = val; return (temp); } public uint GetValueuint() { return (value_uint); } public void SetValueuint(uint val) { value_uint = val; } private ulong value_ulong; static public implicit operator ulong(BasicSelectionTestClass_char_i_e_fc_Conv test) { Log.Comment("To ulong"); return test.value_ulong; } static public implicit operator BasicSelectionTestClass_char_i_e_fc_Conv(ulong val) { Log.Comment("From ulong"); BasicSelectionTestClass_char_i_e_fc_Conv temp = new BasicSelectionTestClass_char_i_e_fc_Conv(); temp.value_ulong = val; return (temp); } public ulong GetValueulong() { return (value_ulong); } public void SetValueulong(ulong val) { value_ulong = val; } private ushort value_ushort; static public implicit operator ushort(BasicSelectionTestClass_char_i_e_fc_Conv test) { Log.Comment("To ushort"); return test.value_ushort; } static public implicit operator BasicSelectionTestClass_char_i_e_fc_Conv(ushort val) { Log.Comment("From ushort"); BasicSelectionTestClass_char_i_e_fc_Conv temp = new BasicSelectionTestClass_char_i_e_fc_Conv(); temp.value_ushort = val; return (temp); } public ushort GetValueushort() { return (value_ushort); } public void SetValueushort(ushort val) { value_ushort = val; } } class BasicSelectionTestClass_char_i_e_fc { public static int Main_old() { BasicSelectionTestClass_char_i_e_fc_Conv cl = new BasicSelectionTestClass_char_i_e_fc_Conv(); cl.SetValuechar('\x1'); char value = (char)cl; if (value != '\x1') return 1; else return 0; } public static bool testMethod() { return (Main_old() == 0); } } class BasicSelectionTestClass_char_e_e_fc_Conv { private byte value_byte; static public explicit operator byte(BasicSelectionTestClass_char_e_e_fc_Conv test) { Log.Comment("To byte"); return test.value_byte; } static public explicit operator BasicSelectionTestClass_char_e_e_fc_Conv(byte val) { Log.Comment("From byte"); BasicSelectionTestClass_char_e_e_fc_Conv temp = new BasicSelectionTestClass_char_e_e_fc_Conv(); temp.value_byte = val; return (temp); } public byte GetValuebyte() { return (value_byte); } public void SetValuebyte(byte val) { value_byte = val; } private char value_char; static public explicit operator char(BasicSelectionTestClass_char_e_e_fc_Conv test) { Log.Comment("To char"); return test.value_char; } static public explicit operator BasicSelectionTestClass_char_e_e_fc_Conv(char val) { Log.Comment("From char"); BasicSelectionTestClass_char_e_e_fc_Conv temp = new BasicSelectionTestClass_char_e_e_fc_Conv(); temp.value_char = val; return (temp); } public char GetValuechar() { return (value_char); } public void SetValuechar(char val) { value_char = val; } private double value_double; static public explicit operator double(BasicSelectionTestClass_char_e_e_fc_Conv test) { Log.Comment("To double"); return test.value_double; } static public explicit operator BasicSelectionTestClass_char_e_e_fc_Conv(double val) { Log.Comment("From double"); BasicSelectionTestClass_char_e_e_fc_Conv temp = new BasicSelectionTestClass_char_e_e_fc_Conv(); temp.value_double = val; return (temp); } public double GetValuedouble() { return (value_double); } public void SetValuedouble(double val) { value_double = val; } private float value_float; static public explicit operator float(BasicSelectionTestClass_char_e_e_fc_Conv test) { Log.Comment("To float"); return test.value_float; } static public explicit operator BasicSelectionTestClass_char_e_e_fc_Conv(float val) { Log.Comment("From float"); BasicSelectionTestClass_char_e_e_fc_Conv temp = new BasicSelectionTestClass_char_e_e_fc_Conv(); temp.value_float = val; return (temp); } public float GetValuefloat() { return (value_float); } public void SetValuefloat(float val) { value_float = val; } private int value_int; static public explicit operator int(BasicSelectionTestClass_char_e_e_fc_Conv test) { Log.Comment("To int"); return test.value_int; } static public explicit operator BasicSelectionTestClass_char_e_e_fc_Conv(int val) { Log.Comment("From int"); BasicSelectionTestClass_char_e_e_fc_Conv temp = new BasicSelectionTestClass_char_e_e_fc_Conv(); temp.value_int = val; return (temp); } public int GetValueint() { return (value_int); } public void SetValueint(int val) { value_int = val; } private long value_long; static public explicit operator long(BasicSelectionTestClass_char_e_e_fc_Conv test) { Log.Comment("To long"); return test.value_long; } static public explicit operator BasicSelectionTestClass_char_e_e_fc_Conv(long val) { Log.Comment("From long"); BasicSelectionTestClass_char_e_e_fc_Conv temp = new BasicSelectionTestClass_char_e_e_fc_Conv(); temp.value_long = val; return (temp); } public long GetValuelong() { return (value_long); } public void SetValuelong(long val) { value_long = val; } private sbyte value_sbyte; static public explicit operator sbyte(BasicSelectionTestClass_char_e_e_fc_Conv test) { Log.Comment("To sbyte"); return test.value_sbyte; } static public explicit operator BasicSelectionTestClass_char_e_e_fc_Conv(sbyte val) { Log.Comment("From sbyte"); BasicSelectionTestClass_char_e_e_fc_Conv temp = new BasicSelectionTestClass_char_e_e_fc_Conv(); temp.value_sbyte = val; return (temp); } public sbyte GetValuesbyte() { return (value_sbyte); } public void SetValuesbyte(sbyte val) { value_sbyte = val; } private short value_short; static public explicit operator short(BasicSelectionTestClass_char_e_e_fc_Conv test) { Log.Comment("To short"); return test.value_short; } static public explicit operator BasicSelectionTestClass_char_e_e_fc_Conv(short val) { Log.Comment("From short"); BasicSelectionTestClass_char_e_e_fc_Conv temp = new BasicSelectionTestClass_char_e_e_fc_Conv(); temp.value_short = val; return (temp); } public short GetValueshort() { return (value_short); } public void SetValueshort(short val) { value_short = val; } private uint value_uint; static public explicit operator uint(BasicSelectionTestClass_char_e_e_fc_Conv test) { Log.Comment("To uint"); return test.value_uint; } static public explicit operator BasicSelectionTestClass_char_e_e_fc_Conv(uint val) { Log.Comment("From uint"); BasicSelectionTestClass_char_e_e_fc_Conv temp = new BasicSelectionTestClass_char_e_e_fc_Conv(); temp.value_uint = val; return (temp); } public uint GetValueuint() { return (value_uint); } public void SetValueuint(uint val) { value_uint = val; } private ulong value_ulong; static public explicit operator ulong(BasicSelectionTestClass_char_e_e_fc_Conv test) { Log.Comment("To ulong"); return test.value_ulong; } static public explicit operator BasicSelectionTestClass_char_e_e_fc_Conv(ulong val) { Log.Comment("From ulong"); BasicSelectionTestClass_char_e_e_fc_Conv temp = new BasicSelectionTestClass_char_e_e_fc_Conv(); temp.value_ulong = val; return (temp); } public ulong GetValueulong() { return (value_ulong); } public void SetValueulong(ulong val) { value_ulong = val; } private ushort value_ushort; static public explicit operator ushort(BasicSelectionTestClass_char_e_e_fc_Conv test) { Log.Comment("To ushort"); return test.value_ushort; } static public explicit operator BasicSelectionTestClass_char_e_e_fc_Conv(ushort val) { Log.Comment("From ushort"); BasicSelectionTestClass_char_e_e_fc_Conv temp = new BasicSelectionTestClass_char_e_e_fc_Conv(); temp.value_ushort = val; return (temp); } public ushort GetValueushort() { return (value_ushort); } public void SetValueushort(ushort val) { value_ushort = val; } } class BasicSelectionTestClass_char_e_e_fc { public static int Main_old() { BasicSelectionTestClass_char_e_e_fc_Conv cl = new BasicSelectionTestClass_char_e_e_fc_Conv(); cl.SetValuechar('\x1'); char value = (char)cl; if (value != '\x1') return 1; else return 0; } public static bool testMethod() { return (Main_old() == 0); } } class BasicSelectionTestClass_double_i_i_tc_Conv { private byte value_byte; static public implicit operator byte(BasicSelectionTestClass_double_i_i_tc_Conv test) { Log.Comment("To byte"); return test.value_byte; } static public implicit operator BasicSelectionTestClass_double_i_i_tc_Conv(byte val) { Log.Comment("From byte"); BasicSelectionTestClass_double_i_i_tc_Conv temp = new BasicSelectionTestClass_double_i_i_tc_Conv(); temp.value_byte = val; return (temp); } public byte GetValuebyte() { return (value_byte); } public void SetValuebyte(byte val) { value_byte = val; } private char value_char; static public implicit operator char(BasicSelectionTestClass_double_i_i_tc_Conv test) { Log.Comment("To char"); return test.value_char; } static public implicit operator BasicSelectionTestClass_double_i_i_tc_Conv(char val) { Log.Comment("From char"); BasicSelectionTestClass_double_i_i_tc_Conv temp = new BasicSelectionTestClass_double_i_i_tc_Conv(); temp.value_char = val; return (temp); } public char GetValuechar() { return (value_char); } public void SetValuechar(char val) { value_char = val; } private double value_double; static public implicit operator double(BasicSelectionTestClass_double_i_i_tc_Conv test) { Log.Comment("To double"); return test.value_double; } static public implicit operator BasicSelectionTestClass_double_i_i_tc_Conv(double val) { Log.Comment("From double"); BasicSelectionTestClass_double_i_i_tc_Conv temp = new BasicSelectionTestClass_double_i_i_tc_Conv(); temp.value_double = val; return (temp); } public double GetValuedouble() { return (value_double); } public void SetValuedouble(double val) { value_double = val; } private float value_float; static public implicit operator float(BasicSelectionTestClass_double_i_i_tc_Conv test) { Log.Comment("To float"); return test.value_float; } static public implicit operator BasicSelectionTestClass_double_i_i_tc_Conv(float val) { Log.Comment("From float"); BasicSelectionTestClass_double_i_i_tc_Conv temp = new BasicSelectionTestClass_double_i_i_tc_Conv(); temp.value_float = val; return (temp); } public float GetValuefloat() { return (value_float); } public void SetValuefloat(float val) { value_float = val; } private int value_int; static public implicit operator int(BasicSelectionTestClass_double_i_i_tc_Conv test) { Log.Comment("To int"); return test.value_int; } static public implicit operator BasicSelectionTestClass_double_i_i_tc_Conv(int val) { Log.Comment("From int"); BasicSelectionTestClass_double_i_i_tc_Conv temp = new BasicSelectionTestClass_double_i_i_tc_Conv(); temp.value_int = val; return (temp); } public int GetValueint() { return (value_int); } public void SetValueint(int val) { value_int = val; } private long value_long; static public implicit operator long(BasicSelectionTestClass_double_i_i_tc_Conv test) { Log.Comment("To long"); return test.value_long; } static public implicit operator BasicSelectionTestClass_double_i_i_tc_Conv(long val) { Log.Comment("From long"); BasicSelectionTestClass_double_i_i_tc_Conv temp = new BasicSelectionTestClass_double_i_i_tc_Conv(); temp.value_long = val; return (temp); } public long GetValuelong() { return (value_long); } public void SetValuelong(long val) { value_long = val; } private sbyte value_sbyte; static public implicit operator sbyte(BasicSelectionTestClass_double_i_i_tc_Conv test) { Log.Comment("To sbyte"); return test.value_sbyte; } static public implicit operator BasicSelectionTestClass_double_i_i_tc_Conv(sbyte val) { Log.Comment("From sbyte"); BasicSelectionTestClass_double_i_i_tc_Conv temp = new BasicSelectionTestClass_double_i_i_tc_Conv(); temp.value_sbyte = val; return (temp); } public sbyte GetValuesbyte() { return (value_sbyte); } public void SetValuesbyte(sbyte val) { value_sbyte = val; } private short value_short; static public implicit operator short(BasicSelectionTestClass_double_i_i_tc_Conv test) { Log.Comment("To short"); return test.value_short; } static public implicit operator BasicSelectionTestClass_double_i_i_tc_Conv(short val) { Log.Comment("From short"); BasicSelectionTestClass_double_i_i_tc_Conv temp = new BasicSelectionTestClass_double_i_i_tc_Conv(); temp.value_short = val; return (temp); } public short GetValueshort() { return (value_short); } public void SetValueshort(short val) { value_short = val; } private uint value_uint; static public implicit operator uint(BasicSelectionTestClass_double_i_i_tc_Conv test) { Log.Comment("To uint"); return test.value_uint; } static public implicit operator BasicSelectionTestClass_double_i_i_tc_Conv(uint val) { Log.Comment("From uint"); BasicSelectionTestClass_double_i_i_tc_Conv temp = new BasicSelectionTestClass_double_i_i_tc_Conv(); temp.value_uint = val; return (temp); } public uint GetValueuint() { return (value_uint); } public void SetValueuint(uint val) { value_uint = val; } private ulong value_ulong; static public implicit operator ulong(BasicSelectionTestClass_double_i_i_tc_Conv test) { Log.Comment("To ulong"); return test.value_ulong; } static public implicit operator BasicSelectionTestClass_double_i_i_tc_Conv(ulong val) { Log.Comment("From ulong"); BasicSelectionTestClass_double_i_i_tc_Conv temp = new BasicSelectionTestClass_double_i_i_tc_Conv(); temp.value_ulong = val; return (temp); } public ulong GetValueulong() { return (value_ulong); } public void SetValueulong(ulong val) { value_ulong = val; } private ushort value_ushort; static public implicit operator ushort(BasicSelectionTestClass_double_i_i_tc_Conv test) { Log.Comment("To ushort"); return test.value_ushort; } static public implicit operator BasicSelectionTestClass_double_i_i_tc_Conv(ushort val) { Log.Comment("From ushort"); BasicSelectionTestClass_double_i_i_tc_Conv temp = new BasicSelectionTestClass_double_i_i_tc_Conv(); temp.value_ushort = val; return (temp); } public ushort GetValueushort() { return (value_ushort); } public void SetValueushort(ushort val) { value_ushort = val; } } class BasicSelectionTestClass_double_i_i_tc { public static int Main_old() { BasicSelectionTestClass_double_i_i_tc_Conv cl = new BasicSelectionTestClass_double_i_i_tc_Conv(); double val = 1.0; cl = val; if (cl.GetValuedouble() != 1.0) return 1; else return 0; } public static bool testMethod() { return (Main_old() == 0); } } class BasicSelectionTestClass_double_i_e_tc_Conv { private byte value_byte; static public implicit operator byte(BasicSelectionTestClass_double_i_e_tc_Conv test) { Log.Comment("To byte"); return test.value_byte; } static public implicit operator BasicSelectionTestClass_double_i_e_tc_Conv(byte val) { Log.Comment("From byte"); BasicSelectionTestClass_double_i_e_tc_Conv temp = new BasicSelectionTestClass_double_i_e_tc_Conv(); temp.value_byte = val; return (temp); } public byte GetValuebyte() { return (value_byte); } public void SetValuebyte(byte val) { value_byte = val; } private char value_char; static public implicit operator char(BasicSelectionTestClass_double_i_e_tc_Conv test) { Log.Comment("To char"); return test.value_char; } static public implicit operator BasicSelectionTestClass_double_i_e_tc_Conv(char val) { Log.Comment("From char"); BasicSelectionTestClass_double_i_e_tc_Conv temp = new BasicSelectionTestClass_double_i_e_tc_Conv(); temp.value_char = val; return (temp); } public char GetValuechar() { return (value_char); } public void SetValuechar(char val) { value_char = val; } private double value_double; static public implicit operator double(BasicSelectionTestClass_double_i_e_tc_Conv test) { Log.Comment("To double"); return test.value_double; } static public implicit operator BasicSelectionTestClass_double_i_e_tc_Conv(double val) { Log.Comment("From double"); BasicSelectionTestClass_double_i_e_tc_Conv temp = new BasicSelectionTestClass_double_i_e_tc_Conv(); temp.value_double = val; return (temp); } public double GetValuedouble() { return (value_double); } public void SetValuedouble(double val) { value_double = val; } private float value_float; static public implicit operator float(BasicSelectionTestClass_double_i_e_tc_Conv test) { Log.Comment("To float"); return test.value_float; } static public implicit operator BasicSelectionTestClass_double_i_e_tc_Conv(float val) { Log.Comment("From float"); BasicSelectionTestClass_double_i_e_tc_Conv temp = new BasicSelectionTestClass_double_i_e_tc_Conv(); temp.value_float = val; return (temp); } public float GetValuefloat() { return (value_float); } public void SetValuefloat(float val) { value_float = val; } private int value_int; static public implicit operator int(BasicSelectionTestClass_double_i_e_tc_Conv test) { Log.Comment("To int"); return test.value_int; } static public implicit operator BasicSelectionTestClass_double_i_e_tc_Conv(int val) { Log.Comment("From int"); BasicSelectionTestClass_double_i_e_tc_Conv temp = new BasicSelectionTestClass_double_i_e_tc_Conv(); temp.value_int = val; return (temp); } public int GetValueint() { return (value_int); } public void SetValueint(int val) { value_int = val; } private long value_long; static public implicit operator long(BasicSelectionTestClass_double_i_e_tc_Conv test) { Log.Comment("To long"); return test.value_long; } static public implicit operator BasicSelectionTestClass_double_i_e_tc_Conv(long val) { Log.Comment("From long"); BasicSelectionTestClass_double_i_e_tc_Conv temp = new BasicSelectionTestClass_double_i_e_tc_Conv(); temp.value_long = val; return (temp); } public long GetValuelong() { return (value_long); } public void SetValuelong(long val) { value_long = val; } private sbyte value_sbyte; static public implicit operator sbyte(BasicSelectionTestClass_double_i_e_tc_Conv test) { Log.Comment("To sbyte"); return test.value_sbyte; } static public implicit operator BasicSelectionTestClass_double_i_e_tc_Conv(sbyte val) { Log.Comment("From sbyte"); BasicSelectionTestClass_double_i_e_tc_Conv temp = new BasicSelectionTestClass_double_i_e_tc_Conv(); temp.value_sbyte = val; return (temp); } public sbyte GetValuesbyte() { return (value_sbyte); } public void SetValuesbyte(sbyte val) { value_sbyte = val; } private short value_short; static public implicit operator short(BasicSelectionTestClass_double_i_e_tc_Conv test) { Log.Comment("To short"); return test.value_short; } static public implicit operator BasicSelectionTestClass_double_i_e_tc_Conv(short val) { Log.Comment("From short"); BasicSelectionTestClass_double_i_e_tc_Conv temp = new BasicSelectionTestClass_double_i_e_tc_Conv(); temp.value_short = val; return (temp); } public short GetValueshort() { return (value_short); } public void SetValueshort(short val) { value_short = val; } private uint value_uint; static public implicit operator uint(BasicSelectionTestClass_double_i_e_tc_Conv test) { Log.Comment("To uint"); return test.value_uint; } static public implicit operator BasicSelectionTestClass_double_i_e_tc_Conv(uint val) { Log.Comment("From uint"); BasicSelectionTestClass_double_i_e_tc_Conv temp = new BasicSelectionTestClass_double_i_e_tc_Conv(); temp.value_uint = val; return (temp); } public uint GetValueuint() { return (value_uint); } public void SetValueuint(uint val) { value_uint = val; } private ulong value_ulong; static public implicit operator ulong(BasicSelectionTestClass_double_i_e_tc_Conv test) { Log.Comment("To ulong"); return test.value_ulong; } static public implicit operator BasicSelectionTestClass_double_i_e_tc_Conv(ulong val) { Log.Comment("From ulong"); BasicSelectionTestClass_double_i_e_tc_Conv temp = new BasicSelectionTestClass_double_i_e_tc_Conv(); temp.value_ulong = val; return (temp); } public ulong GetValueulong() { return (value_ulong); } public void SetValueulong(ulong val) { value_ulong = val; } private ushort value_ushort; static public implicit operator ushort(BasicSelectionTestClass_double_i_e_tc_Conv test) { Log.Comment("To ushort"); return test.value_ushort; } static public implicit operator BasicSelectionTestClass_double_i_e_tc_Conv(ushort val) { Log.Comment("From ushort"); BasicSelectionTestClass_double_i_e_tc_Conv temp = new BasicSelectionTestClass_double_i_e_tc_Conv(); temp.value_ushort = val; return (temp); } public ushort GetValueushort() { return (value_ushort); } public void SetValueushort(ushort val) { value_ushort = val; } } class BasicSelectionTestClass_double_i_e_tc { public static int Main_old() { BasicSelectionTestClass_double_i_e_tc_Conv cl = new BasicSelectionTestClass_double_i_e_tc_Conv(); double val = 1.0; cl = (BasicSelectionTestClass_double_i_e_tc_Conv)val; if (cl.GetValuedouble() != 1.0) return 1; else return 0; } public static bool testMethod() { return (Main_old() == 0); } } class BasicSelectionTestClass_double_e_e_tc_Conv { private byte value_byte; static public explicit operator byte(BasicSelectionTestClass_double_e_e_tc_Conv test) { Log.Comment("To byte"); return test.value_byte; } static public explicit operator BasicSelectionTestClass_double_e_e_tc_Conv(byte val) { Log.Comment("From byte"); BasicSelectionTestClass_double_e_e_tc_Conv temp = new BasicSelectionTestClass_double_e_e_tc_Conv(); temp.value_byte = val; return (temp); } public byte GetValuebyte() { return (value_byte); } public void SetValuebyte(byte val) { value_byte = val; } private char value_char; static public explicit operator char(BasicSelectionTestClass_double_e_e_tc_Conv test) { Log.Comment("To char"); return test.value_char; } static public explicit operator BasicSelectionTestClass_double_e_e_tc_Conv(char val) { Log.Comment("From char"); BasicSelectionTestClass_double_e_e_tc_Conv temp = new BasicSelectionTestClass_double_e_e_tc_Conv(); temp.value_char = val; return (temp); } public char GetValuechar() { return (value_char); } public void SetValuechar(char val) { value_char = val; } private double value_double; static public explicit operator double(BasicSelectionTestClass_double_e_e_tc_Conv test) { Log.Comment("To double"); return test.value_double; } static public explicit operator BasicSelectionTestClass_double_e_e_tc_Conv(double val) { Log.Comment("From double"); BasicSelectionTestClass_double_e_e_tc_Conv temp = new BasicSelectionTestClass_double_e_e_tc_Conv(); temp.value_double = val; return (temp); } public double GetValuedouble() { return (value_double); } public void SetValuedouble(double val) { value_double = val; } private float value_float; static public explicit operator float(BasicSelectionTestClass_double_e_e_tc_Conv test) { Log.Comment("To float"); return test.value_float; } static public explicit operator BasicSelectionTestClass_double_e_e_tc_Conv(float val) { Log.Comment("From float"); BasicSelectionTestClass_double_e_e_tc_Conv temp = new BasicSelectionTestClass_double_e_e_tc_Conv(); temp.value_float = val; return (temp); } public float GetValuefloat() { return (value_float); } public void SetValuefloat(float val) { value_float = val; } private int value_int; static public explicit operator int(BasicSelectionTestClass_double_e_e_tc_Conv test) { Log.Comment("To int"); return test.value_int; } static public explicit operator BasicSelectionTestClass_double_e_e_tc_Conv(int val) { Log.Comment("From int"); BasicSelectionTestClass_double_e_e_tc_Conv temp = new BasicSelectionTestClass_double_e_e_tc_Conv(); temp.value_int = val; return (temp); } public int GetValueint() { return (value_int); } public void SetValueint(int val) { value_int = val; } private long value_long; static public explicit operator long(BasicSelectionTestClass_double_e_e_tc_Conv test) { Log.Comment("To long"); return test.value_long; } static public explicit operator BasicSelectionTestClass_double_e_e_tc_Conv(long val) { Log.Comment("From long"); BasicSelectionTestClass_double_e_e_tc_Conv temp = new BasicSelectionTestClass_double_e_e_tc_Conv(); temp.value_long = val; return (temp); } public long GetValuelong() { return (value_long); } public void SetValuelong(long val) { value_long = val; } private sbyte value_sbyte; static public explicit operator sbyte(BasicSelectionTestClass_double_e_e_tc_Conv test) { Log.Comment("To sbyte"); return test.value_sbyte; } static public explicit operator BasicSelectionTestClass_double_e_e_tc_Conv(sbyte val) { Log.Comment("From sbyte"); BasicSelectionTestClass_double_e_e_tc_Conv temp = new BasicSelectionTestClass_double_e_e_tc_Conv(); temp.value_sbyte = val; return (temp); } public sbyte GetValuesbyte() { return (value_sbyte); } public void SetValuesbyte(sbyte val) { value_sbyte = val; } private short value_short; static public explicit operator short(BasicSelectionTestClass_double_e_e_tc_Conv test) { Log.Comment("To short"); return test.value_short; } static public explicit operator BasicSelectionTestClass_double_e_e_tc_Conv(short val) { Log.Comment("From short"); BasicSelectionTestClass_double_e_e_tc_Conv temp = new BasicSelectionTestClass_double_e_e_tc_Conv(); temp.value_short = val; return (temp); } public short GetValueshort() { return (value_short); } public void SetValueshort(short val) { value_short = val; } private uint value_uint; static public explicit operator uint(BasicSelectionTestClass_double_e_e_tc_Conv test) { Log.Comment("To uint"); return test.value_uint; } static public explicit operator BasicSelectionTestClass_double_e_e_tc_Conv(uint val) { Log.Comment("From uint"); BasicSelectionTestClass_double_e_e_tc_Conv temp = new BasicSelectionTestClass_double_e_e_tc_Conv(); temp.value_uint = val; return (temp); } public uint GetValueuint() { return (value_uint); } public void SetValueuint(uint val) { value_uint = val; } private ulong value_ulong; static public explicit operator ulong(BasicSelectionTestClass_double_e_e_tc_Conv test) { Log.Comment("To ulong"); return test.value_ulong; } static public explicit operator BasicSelectionTestClass_double_e_e_tc_Conv(ulong val) { Log.Comment("From ulong"); BasicSelectionTestClass_double_e_e_tc_Conv temp = new BasicSelectionTestClass_double_e_e_tc_Conv(); temp.value_ulong = val; return (temp); } public ulong GetValueulong() { return (value_ulong); } public void SetValueulong(ulong val) { value_ulong = val; } private ushort value_ushort; static public explicit operator ushort(BasicSelectionTestClass_double_e_e_tc_Conv test) { Log.Comment("To ushort"); return test.value_ushort; } static public explicit operator BasicSelectionTestClass_double_e_e_tc_Conv(ushort val) { Log.Comment("From ushort"); BasicSelectionTestClass_double_e_e_tc_Conv temp = new BasicSelectionTestClass_double_e_e_tc_Conv(); temp.value_ushort = val; return (temp); } public ushort GetValueushort() { return (value_ushort); } public void SetValueushort(ushort val) { value_ushort = val; } } class BasicSelectionTestClass_double_e_e_tc { public static int Main_old() { BasicSelectionTestClass_double_e_e_tc_Conv cl = new BasicSelectionTestClass_double_e_e_tc_Conv(); double val = 1.0; cl = (BasicSelectionTestClass_double_e_e_tc_Conv)val; if (cl.GetValuedouble() != 1.0) return 1; else return 0; } public static bool testMethod() { return (Main_old() == 0); } } class BasicSelectionTestClass_double_i_i_fc_Conv { private byte value_byte; static public implicit operator byte(BasicSelectionTestClass_double_i_i_fc_Conv test) { Log.Comment("To byte"); return test.value_byte; } static public implicit operator BasicSelectionTestClass_double_i_i_fc_Conv(byte val) { Log.Comment("From byte"); BasicSelectionTestClass_double_i_i_fc_Conv temp = new BasicSelectionTestClass_double_i_i_fc_Conv(); temp.value_byte = val; return (temp); } public byte GetValuebyte() { return (value_byte); } public void SetValuebyte(byte val) { value_byte = val; } private char value_char; static public implicit operator char(BasicSelectionTestClass_double_i_i_fc_Conv test) { Log.Comment("To char"); return test.value_char; } static public implicit operator BasicSelectionTestClass_double_i_i_fc_Conv(char val) { Log.Comment("From char"); BasicSelectionTestClass_double_i_i_fc_Conv temp = new BasicSelectionTestClass_double_i_i_fc_Conv(); temp.value_char = val; return (temp); } public char GetValuechar() { return (value_char); } public void SetValuechar(char val) { value_char = val; } private double value_double; static public implicit operator double(BasicSelectionTestClass_double_i_i_fc_Conv test) { Log.Comment("To double"); return test.value_double; } static public implicit operator BasicSelectionTestClass_double_i_i_fc_Conv(double val) { Log.Comment("From double"); BasicSelectionTestClass_double_i_i_fc_Conv temp = new BasicSelectionTestClass_double_i_i_fc_Conv(); temp.value_double = val; return (temp); } public double GetValuedouble() { return (value_double); } public void SetValuedouble(double val) { value_double = val; } private float value_float; static public implicit operator float(BasicSelectionTestClass_double_i_i_fc_Conv test) { Log.Comment("To float"); return test.value_float; } static public implicit operator BasicSelectionTestClass_double_i_i_fc_Conv(float val) { Log.Comment("From float"); BasicSelectionTestClass_double_i_i_fc_Conv temp = new BasicSelectionTestClass_double_i_i_fc_Conv(); temp.value_float = val; return (temp); } public float GetValuefloat() { return (value_float); } public void SetValuefloat(float val) { value_float = val; } private int value_int; static public implicit operator int(BasicSelectionTestClass_double_i_i_fc_Conv test) { Log.Comment("To int"); return test.value_int; } static public implicit operator BasicSelectionTestClass_double_i_i_fc_Conv(int val) { Log.Comment("From int"); BasicSelectionTestClass_double_i_i_fc_Conv temp = new BasicSelectionTestClass_double_i_i_fc_Conv(); temp.value_int = val; return (temp); } public int GetValueint() { return (value_int); } public void SetValueint(int val) { value_int = val; } private long value_long; static public implicit operator long(BasicSelectionTestClass_double_i_i_fc_Conv test) { Log.Comment("To long"); return test.value_long; } static public implicit operator BasicSelectionTestClass_double_i_i_fc_Conv(long val) { Log.Comment("From long"); BasicSelectionTestClass_double_i_i_fc_Conv temp = new BasicSelectionTestClass_double_i_i_fc_Conv(); temp.value_long = val; return (temp); } public long GetValuelong() { return (value_long); } public void SetValuelong(long val) { value_long = val; } private sbyte value_sbyte; static public implicit operator sbyte(BasicSelectionTestClass_double_i_i_fc_Conv test) { Log.Comment("To sbyte"); return test.value_sbyte; } static public implicit operator BasicSelectionTestClass_double_i_i_fc_Conv(sbyte val) { Log.Comment("From sbyte"); BasicSelectionTestClass_double_i_i_fc_Conv temp = new BasicSelectionTestClass_double_i_i_fc_Conv(); temp.value_sbyte = val; return (temp); } public sbyte GetValuesbyte() { return (value_sbyte); } public void SetValuesbyte(sbyte val) { value_sbyte = val; } private short value_short; static public implicit operator short(BasicSelectionTestClass_double_i_i_fc_Conv test) { Log.Comment("To short"); return test.value_short; } static public implicit operator BasicSelectionTestClass_double_i_i_fc_Conv(short val) { Log.Comment("From short"); BasicSelectionTestClass_double_i_i_fc_Conv temp = new BasicSelectionTestClass_double_i_i_fc_Conv(); temp.value_short = val; return (temp); } public short GetValueshort() { return (value_short); } public void SetValueshort(short val) { value_short = val; } private uint value_uint; static public implicit operator uint(BasicSelectionTestClass_double_i_i_fc_Conv test) { Log.Comment("To uint"); return test.value_uint; } static public implicit operator BasicSelectionTestClass_double_i_i_fc_Conv(uint val) { Log.Comment("From uint"); BasicSelectionTestClass_double_i_i_fc_Conv temp = new BasicSelectionTestClass_double_i_i_fc_Conv(); temp.value_uint = val; return (temp); } public uint GetValueuint() { return (value_uint); } public void SetValueuint(uint val) { value_uint = val; } private ulong value_ulong; static public implicit operator ulong(BasicSelectionTestClass_double_i_i_fc_Conv test) { Log.Comment("To ulong"); return test.value_ulong; } static public implicit operator BasicSelectionTestClass_double_i_i_fc_Conv(ulong val) { Log.Comment("From ulong"); BasicSelectionTestClass_double_i_i_fc_Conv temp = new BasicSelectionTestClass_double_i_i_fc_Conv(); temp.value_ulong = val; return (temp); } public ulong GetValueulong() { return (value_ulong); } public void SetValueulong(ulong val) { value_ulong = val; } private ushort value_ushort; static public implicit operator ushort(BasicSelectionTestClass_double_i_i_fc_Conv test) { Log.Comment("To ushort"); return test.value_ushort; } static public implicit operator BasicSelectionTestClass_double_i_i_fc_Conv(ushort val) { Log.Comment("From ushort"); BasicSelectionTestClass_double_i_i_fc_Conv temp = new BasicSelectionTestClass_double_i_i_fc_Conv(); temp.value_ushort = val; return (temp); } public ushort GetValueushort() { return (value_ushort); } public void SetValueushort(ushort val) { value_ushort = val; } } class BasicSelectionTestClass_double_i_i_fc { public static int Main_old() { BasicSelectionTestClass_double_i_i_fc_Conv cl = new BasicSelectionTestClass_double_i_i_fc_Conv(); cl.SetValuedouble(1.0); double value = cl; if (value != 1.0) return 1; else return 0; } public static bool testMethod() { return (Main_old() == 0); } } class BasicSelectionTestClass_double_i_e_fc_Conv { private byte value_byte; static public implicit operator byte(BasicSelectionTestClass_double_i_e_fc_Conv test) { Log.Comment("To byte"); return test.value_byte; } static public implicit operator BasicSelectionTestClass_double_i_e_fc_Conv(byte val) { Log.Comment("From byte"); BasicSelectionTestClass_double_i_e_fc_Conv temp = new BasicSelectionTestClass_double_i_e_fc_Conv(); temp.value_byte = val; return (temp); } public byte GetValuebyte() { return (value_byte); } public void SetValuebyte(byte val) { value_byte = val; } private char value_char; static public implicit operator char(BasicSelectionTestClass_double_i_e_fc_Conv test) { Log.Comment("To char"); return test.value_char; } static public implicit operator BasicSelectionTestClass_double_i_e_fc_Conv(char val) { Log.Comment("From char"); BasicSelectionTestClass_double_i_e_fc_Conv temp = new BasicSelectionTestClass_double_i_e_fc_Conv(); temp.value_char = val; return (temp); } public char GetValuechar() { return (value_char); } public void SetValuechar(char val) { value_char = val; } private double value_double; static public implicit operator double(BasicSelectionTestClass_double_i_e_fc_Conv test) { Log.Comment("To double"); return test.value_double; } static public implicit operator BasicSelectionTestClass_double_i_e_fc_Conv(double val) { Log.Comment("From double"); BasicSelectionTestClass_double_i_e_fc_Conv temp = new BasicSelectionTestClass_double_i_e_fc_Conv(); temp.value_double = val; return (temp); } public double GetValuedouble() { return (value_double); } public void SetValuedouble(double val) { value_double = val; } private float value_float; static public implicit operator float(BasicSelectionTestClass_double_i_e_fc_Conv test) { Log.Comment("To float"); return test.value_float; } static public implicit operator BasicSelectionTestClass_double_i_e_fc_Conv(float val) { Log.Comment("From float"); BasicSelectionTestClass_double_i_e_fc_Conv temp = new BasicSelectionTestClass_double_i_e_fc_Conv(); temp.value_float = val; return (temp); } public float GetValuefloat() { return (value_float); } public void SetValuefloat(float val) { value_float = val; } private int value_int; static public implicit operator int(BasicSelectionTestClass_double_i_e_fc_Conv test) { Log.Comment("To int"); return test.value_int; } static public implicit operator BasicSelectionTestClass_double_i_e_fc_Conv(int val) { Log.Comment("From int"); BasicSelectionTestClass_double_i_e_fc_Conv temp = new BasicSelectionTestClass_double_i_e_fc_Conv(); temp.value_int = val; return (temp); } public int GetValueint() { return (value_int); } public void SetValueint(int val) { value_int = val; } private long value_long; static public implicit operator long(BasicSelectionTestClass_double_i_e_fc_Conv test) { Log.Comment("To long"); return test.value_long; } static public implicit operator BasicSelectionTestClass_double_i_e_fc_Conv(long val) { Log.Comment("From long"); BasicSelectionTestClass_double_i_e_fc_Conv temp = new BasicSelectionTestClass_double_i_e_fc_Conv(); temp.value_long = val; return (temp); } public long GetValuelong() { return (value_long); } public void SetValuelong(long val) { value_long = val; } private sbyte value_sbyte; static public implicit operator sbyte(BasicSelectionTestClass_double_i_e_fc_Conv test) { Log.Comment("To sbyte"); return test.value_sbyte; } static public implicit operator BasicSelectionTestClass_double_i_e_fc_Conv(sbyte val) { Log.Comment("From sbyte"); BasicSelectionTestClass_double_i_e_fc_Conv temp = new BasicSelectionTestClass_double_i_e_fc_Conv(); temp.value_sbyte = val; return (temp); } public sbyte GetValuesbyte() { return (value_sbyte); } public void SetValuesbyte(sbyte val) { value_sbyte = val; } private short value_short; static public implicit operator short(BasicSelectionTestClass_double_i_e_fc_Conv test) { Log.Comment("To short"); return test.value_short; } static public implicit operator BasicSelectionTestClass_double_i_e_fc_Conv(short val) { Log.Comment("From short"); BasicSelectionTestClass_double_i_e_fc_Conv temp = new BasicSelectionTestClass_double_i_e_fc_Conv(); temp.value_short = val; return (temp); } public short GetValueshort() { return (value_short); } public void SetValueshort(short val) { value_short = val; } private uint value_uint; static public implicit operator uint(BasicSelectionTestClass_double_i_e_fc_Conv test) { Log.Comment("To uint"); return test.value_uint; } static public implicit operator BasicSelectionTestClass_double_i_e_fc_Conv(uint val) { Log.Comment("From uint"); BasicSelectionTestClass_double_i_e_fc_Conv temp = new BasicSelectionTestClass_double_i_e_fc_Conv(); temp.value_uint = val; return (temp); } public uint GetValueuint() { return (value_uint); } public void SetValueuint(uint val) { value_uint = val; } private ulong value_ulong; static public implicit operator ulong(BasicSelectionTestClass_double_i_e_fc_Conv test) { Log.Comment("To ulong"); return test.value_ulong; } static public implicit operator BasicSelectionTestClass_double_i_e_fc_Conv(ulong val) { Log.Comment("From ulong"); BasicSelectionTestClass_double_i_e_fc_Conv temp = new BasicSelectionTestClass_double_i_e_fc_Conv(); temp.value_ulong = val; return (temp); } public ulong GetValueulong() { return (value_ulong); } public void SetValueulong(ulong val) { value_ulong = val; } private ushort value_ushort; static public implicit operator ushort(BasicSelectionTestClass_double_i_e_fc_Conv test) { Log.Comment("To ushort"); return test.value_ushort; } static public implicit operator BasicSelectionTestClass_double_i_e_fc_Conv(ushort val) { Log.Comment("From ushort"); BasicSelectionTestClass_double_i_e_fc_Conv temp = new BasicSelectionTestClass_double_i_e_fc_Conv(); temp.value_ushort = val; return (temp); } public ushort GetValueushort() { return (value_ushort); } public void SetValueushort(ushort val) { value_ushort = val; } } class BasicSelectionTestClass_double_i_e_fc { public static int Main_old() { BasicSelectionTestClass_double_i_e_fc_Conv cl = new BasicSelectionTestClass_double_i_e_fc_Conv(); cl.SetValuedouble(1.0); double value = (double)cl; if (value != 1.0) return 1; else return 0; } public static bool testMethod() { return (Main_old() == 0); } } class BasicSelectionTestClass_double_e_e_fc_Conv { private byte value_byte; static public explicit operator byte(BasicSelectionTestClass_double_e_e_fc_Conv test) { Log.Comment("To byte"); return test.value_byte; } static public explicit operator BasicSelectionTestClass_double_e_e_fc_Conv(byte val) { Log.Comment("From byte"); BasicSelectionTestClass_double_e_e_fc_Conv temp = new BasicSelectionTestClass_double_e_e_fc_Conv(); temp.value_byte = val; return (temp); } public byte GetValuebyte() { return (value_byte); } public void SetValuebyte(byte val) { value_byte = val; } private char value_char; static public explicit operator char(BasicSelectionTestClass_double_e_e_fc_Conv test) { Log.Comment("To char"); return test.value_char; } static public explicit operator BasicSelectionTestClass_double_e_e_fc_Conv(char val) { Log.Comment("From char"); BasicSelectionTestClass_double_e_e_fc_Conv temp = new BasicSelectionTestClass_double_e_e_fc_Conv(); temp.value_char = val; return (temp); } public char GetValuechar() { return (value_char); } public void SetValuechar(char val) { value_char = val; } private double value_double; static public explicit operator double(BasicSelectionTestClass_double_e_e_fc_Conv test) { Log.Comment("To double"); return test.value_double; } static public explicit operator BasicSelectionTestClass_double_e_e_fc_Conv(double val) { Log.Comment("From double"); BasicSelectionTestClass_double_e_e_fc_Conv temp = new BasicSelectionTestClass_double_e_e_fc_Conv(); temp.value_double = val; return (temp); } public double GetValuedouble() { return (value_double); } public void SetValuedouble(double val) { value_double = val; } private float value_float; static public explicit operator float(BasicSelectionTestClass_double_e_e_fc_Conv test) { Log.Comment("To float"); return test.value_float; } static public explicit operator BasicSelectionTestClass_double_e_e_fc_Conv(float val) { Log.Comment("From float"); BasicSelectionTestClass_double_e_e_fc_Conv temp = new BasicSelectionTestClass_double_e_e_fc_Conv(); temp.value_float = val; return (temp); } public float GetValuefloat() { return (value_float); } public void SetValuefloat(float val) { value_float = val; } private int value_int; static public explicit operator int(BasicSelectionTestClass_double_e_e_fc_Conv test) { Log.Comment("To int"); return test.value_int; } static public explicit operator BasicSelectionTestClass_double_e_e_fc_Conv(int val) { Log.Comment("From int"); BasicSelectionTestClass_double_e_e_fc_Conv temp = new BasicSelectionTestClass_double_e_e_fc_Conv(); temp.value_int = val; return (temp); } public int GetValueint() { return (value_int); } public void SetValueint(int val) { value_int = val; } private long value_long; static public explicit operator long(BasicSelectionTestClass_double_e_e_fc_Conv test) { Log.Comment("To long"); return test.value_long; } static public explicit operator BasicSelectionTestClass_double_e_e_fc_Conv(long val) { Log.Comment("From long"); BasicSelectionTestClass_double_e_e_fc_Conv temp = new BasicSelectionTestClass_double_e_e_fc_Conv(); temp.value_long = val; return (temp); } public long GetValuelong() { return (value_long); } public void SetValuelong(long val) { value_long = val; } private sbyte value_sbyte; static public explicit operator sbyte(BasicSelectionTestClass_double_e_e_fc_Conv test) { Log.Comment("To sbyte"); return test.value_sbyte; } static public explicit operator BasicSelectionTestClass_double_e_e_fc_Conv(sbyte val) { Log.Comment("From sbyte"); BasicSelectionTestClass_double_e_e_fc_Conv temp = new BasicSelectionTestClass_double_e_e_fc_Conv(); temp.value_sbyte = val; return (temp); } public sbyte GetValuesbyte() { return (value_sbyte); } public void SetValuesbyte(sbyte val) { value_sbyte = val; } private short value_short; static public explicit operator short(BasicSelectionTestClass_double_e_e_fc_Conv test) { Log.Comment("To short"); return test.value_short; } static public explicit operator BasicSelectionTestClass_double_e_e_fc_Conv(short val) { Log.Comment("From short"); BasicSelectionTestClass_double_e_e_fc_Conv temp = new BasicSelectionTestClass_double_e_e_fc_Conv(); temp.value_short = val; return (temp); } public short GetValueshort() { return (value_short); } public void SetValueshort(short val) { value_short = val; } private uint value_uint; static public explicit operator uint(BasicSelectionTestClass_double_e_e_fc_Conv test) { Log.Comment("To uint"); return test.value_uint; } static public explicit operator BasicSelectionTestClass_double_e_e_fc_Conv(uint val) { Log.Comment("From uint"); BasicSelectionTestClass_double_e_e_fc_Conv temp = new BasicSelectionTestClass_double_e_e_fc_Conv(); temp.value_uint = val; return (temp); } public uint GetValueuint() { return (value_uint); } public void SetValueuint(uint val) { value_uint = val; } private ulong value_ulong; static public explicit operator ulong(BasicSelectionTestClass_double_e_e_fc_Conv test) { Log.Comment("To ulong"); return test.value_ulong; } static public explicit operator BasicSelectionTestClass_double_e_e_fc_Conv(ulong val) { Log.Comment("From ulong"); BasicSelectionTestClass_double_e_e_fc_Conv temp = new BasicSelectionTestClass_double_e_e_fc_Conv(); temp.value_ulong = val; return (temp); } public ulong GetValueulong() { return (value_ulong); } public void SetValueulong(ulong val) { value_ulong = val; } private ushort value_ushort; static public explicit operator ushort(BasicSelectionTestClass_double_e_e_fc_Conv test) { Log.Comment("To ushort"); return test.value_ushort; } static public explicit operator BasicSelectionTestClass_double_e_e_fc_Conv(ushort val) { Log.Comment("From ushort"); BasicSelectionTestClass_double_e_e_fc_Conv temp = new BasicSelectionTestClass_double_e_e_fc_Conv(); temp.value_ushort = val; return (temp); } public ushort GetValueushort() { return (value_ushort); } public void SetValueushort(ushort val) { value_ushort = val; } } class BasicSelectionTestClass_double_e_e_fc { public static int Main_old() { BasicSelectionTestClass_double_e_e_fc_Conv cl = new BasicSelectionTestClass_double_e_e_fc_Conv(); cl.SetValuedouble(1.0); double value = (double)cl; if (value != 1.0) return 1; else return 0; } public static bool testMethod() { return (Main_old() == 0); } } class BasicSelectionTestClass_float_i_i_tc_Conv { private byte value_byte; static public implicit operator byte(BasicSelectionTestClass_float_i_i_tc_Conv test) { Log.Comment("To byte"); return test.value_byte; } static public implicit operator BasicSelectionTestClass_float_i_i_tc_Conv(byte val) { Log.Comment("From byte"); BasicSelectionTestClass_float_i_i_tc_Conv temp = new BasicSelectionTestClass_float_i_i_tc_Conv(); temp.value_byte = val; return (temp); } public byte GetValuebyte() { return (value_byte); } public void SetValuebyte(byte val) { value_byte = val; } private char value_char; static public implicit operator char(BasicSelectionTestClass_float_i_i_tc_Conv test) { Log.Comment("To char"); return test.value_char; } static public implicit operator BasicSelectionTestClass_float_i_i_tc_Conv(char val) { Log.Comment("From char"); BasicSelectionTestClass_float_i_i_tc_Conv temp = new BasicSelectionTestClass_float_i_i_tc_Conv(); temp.value_char = val; return (temp); } public char GetValuechar() { return (value_char); } public void SetValuechar(char val) { value_char = val; } private double value_double; static public implicit operator double(BasicSelectionTestClass_float_i_i_tc_Conv test) { Log.Comment("To double"); return test.value_double; } static public implicit operator BasicSelectionTestClass_float_i_i_tc_Conv(double val) { Log.Comment("From double"); BasicSelectionTestClass_float_i_i_tc_Conv temp = new BasicSelectionTestClass_float_i_i_tc_Conv(); temp.value_double = val; return (temp); } public double GetValuedouble() { return (value_double); } public void SetValuedouble(double val) { value_double = val; } private float value_float; static public implicit operator float(BasicSelectionTestClass_float_i_i_tc_Conv test) { Log.Comment("To float"); return test.value_float; } static public implicit operator BasicSelectionTestClass_float_i_i_tc_Conv(float val) { Log.Comment("From float"); BasicSelectionTestClass_float_i_i_tc_Conv temp = new BasicSelectionTestClass_float_i_i_tc_Conv(); temp.value_float = val; return (temp); } public float GetValuefloat() { return (value_float); } public void SetValuefloat(float val) { value_float = val; } private int value_int; static public implicit operator int(BasicSelectionTestClass_float_i_i_tc_Conv test) { Log.Comment("To int"); return test.value_int; } static public implicit operator BasicSelectionTestClass_float_i_i_tc_Conv(int val) { Log.Comment("From int"); BasicSelectionTestClass_float_i_i_tc_Conv temp = new BasicSelectionTestClass_float_i_i_tc_Conv(); temp.value_int = val; return (temp); } public int GetValueint() { return (value_int); } public void SetValueint(int val) { value_int = val; } private long value_long; static public implicit operator long(BasicSelectionTestClass_float_i_i_tc_Conv test) { Log.Comment("To long"); return test.value_long; } static public implicit operator BasicSelectionTestClass_float_i_i_tc_Conv(long val) { Log.Comment("From long"); BasicSelectionTestClass_float_i_i_tc_Conv temp = new BasicSelectionTestClass_float_i_i_tc_Conv(); temp.value_long = val; return (temp); } public long GetValuelong() { return (value_long); } public void SetValuelong(long val) { value_long = val; } private sbyte value_sbyte; static public implicit operator sbyte(BasicSelectionTestClass_float_i_i_tc_Conv test) { Log.Comment("To sbyte"); return test.value_sbyte; } static public implicit operator BasicSelectionTestClass_float_i_i_tc_Conv(sbyte val) { Log.Comment("From sbyte"); BasicSelectionTestClass_float_i_i_tc_Conv temp = new BasicSelectionTestClass_float_i_i_tc_Conv(); temp.value_sbyte = val; return (temp); } public sbyte GetValuesbyte() { return (value_sbyte); } public void SetValuesbyte(sbyte val) { value_sbyte = val; } private short value_short; static public implicit operator short(BasicSelectionTestClass_float_i_i_tc_Conv test) { Log.Comment("To short"); return test.value_short; } static public implicit operator BasicSelectionTestClass_float_i_i_tc_Conv(short val) { Log.Comment("From short"); BasicSelectionTestClass_float_i_i_tc_Conv temp = new BasicSelectionTestClass_float_i_i_tc_Conv(); temp.value_short = val; return (temp); } public short GetValueshort() { return (value_short); } public void SetValueshort(short val) { value_short = val; } private uint value_uint; static public implicit operator uint(BasicSelectionTestClass_float_i_i_tc_Conv test) { Log.Comment("To uint"); return test.value_uint; } static public implicit operator BasicSelectionTestClass_float_i_i_tc_Conv(uint val) { Log.Comment("From uint"); BasicSelectionTestClass_float_i_i_tc_Conv temp = new BasicSelectionTestClass_float_i_i_tc_Conv(); temp.value_uint = val; return (temp); } public uint GetValueuint() { return (value_uint); } public void SetValueuint(uint val) { value_uint = val; } private ulong value_ulong; static public implicit operator ulong(BasicSelectionTestClass_float_i_i_tc_Conv test) { Log.Comment("To ulong"); return test.value_ulong; } static public implicit operator BasicSelectionTestClass_float_i_i_tc_Conv(ulong val) { Log.Comment("From ulong"); BasicSelectionTestClass_float_i_i_tc_Conv temp = new BasicSelectionTestClass_float_i_i_tc_Conv(); temp.value_ulong = val; return (temp); } public ulong GetValueulong() { return (value_ulong); } public void SetValueulong(ulong val) { value_ulong = val; } private ushort value_ushort; static public implicit operator ushort(BasicSelectionTestClass_float_i_i_tc_Conv test) { Log.Comment("To ushort"); return test.value_ushort; } static public implicit operator BasicSelectionTestClass_float_i_i_tc_Conv(ushort val) { Log.Comment("From ushort"); BasicSelectionTestClass_float_i_i_tc_Conv temp = new BasicSelectionTestClass_float_i_i_tc_Conv(); temp.value_ushort = val; return (temp); } public ushort GetValueushort() { return (value_ushort); } public void SetValueushort(ushort val) { value_ushort = val; } } class BasicSelectionTestClass_float_i_i_tc { public static int Main_old() { BasicSelectionTestClass_float_i_i_tc_Conv cl = new BasicSelectionTestClass_float_i_i_tc_Conv(); float val = 1F; cl = val; if (cl.GetValuefloat() != 1F) return 1; else return 0; } public static bool testMethod() { return (Main_old() == 0); } } class BasicSelectionTestClass_float_i_e_tc_Conv { private byte value_byte; static public implicit operator byte(BasicSelectionTestClass_float_i_e_tc_Conv test) { Log.Comment("To byte"); return test.value_byte; } static public implicit operator BasicSelectionTestClass_float_i_e_tc_Conv(byte val) { Log.Comment("From byte"); BasicSelectionTestClass_float_i_e_tc_Conv temp = new BasicSelectionTestClass_float_i_e_tc_Conv(); temp.value_byte = val; return (temp); } public byte GetValuebyte() { return (value_byte); } public void SetValuebyte(byte val) { value_byte = val; } private char value_char; static public implicit operator char(BasicSelectionTestClass_float_i_e_tc_Conv test) { Log.Comment("To char"); return test.value_char; } static public implicit operator BasicSelectionTestClass_float_i_e_tc_Conv(char val) { Log.Comment("From char"); BasicSelectionTestClass_float_i_e_tc_Conv temp = new BasicSelectionTestClass_float_i_e_tc_Conv(); temp.value_char = val; return (temp); } public char GetValuechar() { return (value_char); } public void SetValuechar(char val) { value_char = val; } private double value_double; static public implicit operator double(BasicSelectionTestClass_float_i_e_tc_Conv test) { Log.Comment("To double"); return test.value_double; } static public implicit operator BasicSelectionTestClass_float_i_e_tc_Conv(double val) { Log.Comment("From double"); BasicSelectionTestClass_float_i_e_tc_Conv temp = new BasicSelectionTestClass_float_i_e_tc_Conv(); temp.value_double = val; return (temp); } public double GetValuedouble() { return (value_double); } public void SetValuedouble(double val) { value_double = val; } private float value_float; static public implicit operator float(BasicSelectionTestClass_float_i_e_tc_Conv test) { Log.Comment("To float"); return test.value_float; } static public implicit operator BasicSelectionTestClass_float_i_e_tc_Conv(float val) { Log.Comment("From float"); BasicSelectionTestClass_float_i_e_tc_Conv temp = new BasicSelectionTestClass_float_i_e_tc_Conv(); temp.value_float = val; return (temp); } public float GetValuefloat() { return (value_float); } public void SetValuefloat(float val) { value_float = val; } private int value_int; static public implicit operator int(BasicSelectionTestClass_float_i_e_tc_Conv test) { Log.Comment("To int"); return test.value_int; } static public implicit operator BasicSelectionTestClass_float_i_e_tc_Conv(int val) { Log.Comment("From int"); BasicSelectionTestClass_float_i_e_tc_Conv temp = new BasicSelectionTestClass_float_i_e_tc_Conv(); temp.value_int = val; return (temp); } public int GetValueint() { return (value_int); } public void SetValueint(int val) { value_int = val; } private long value_long; static public implicit operator long(BasicSelectionTestClass_float_i_e_tc_Conv test) { Log.Comment("To long"); return test.value_long; } static public implicit operator BasicSelectionTestClass_float_i_e_tc_Conv(long val) { Log.Comment("From long"); BasicSelectionTestClass_float_i_e_tc_Conv temp = new BasicSelectionTestClass_float_i_e_tc_Conv(); temp.value_long = val; return (temp); } public long GetValuelong() { return (value_long); } public void SetValuelong(long val) { value_long = val; } private sbyte value_sbyte; static public implicit operator sbyte(BasicSelectionTestClass_float_i_e_tc_Conv test) { Log.Comment("To sbyte"); return test.value_sbyte; } static public implicit operator BasicSelectionTestClass_float_i_e_tc_Conv(sbyte val) { Log.Comment("From sbyte"); BasicSelectionTestClass_float_i_e_tc_Conv temp = new BasicSelectionTestClass_float_i_e_tc_Conv(); temp.value_sbyte = val; return (temp); } public sbyte GetValuesbyte() { return (value_sbyte); } public void SetValuesbyte(sbyte val) { value_sbyte = val; } private short value_short; static public implicit operator short(BasicSelectionTestClass_float_i_e_tc_Conv test) { Log.Comment("To short"); return test.value_short; } static public implicit operator BasicSelectionTestClass_float_i_e_tc_Conv(short val) { Log.Comment("From short"); BasicSelectionTestClass_float_i_e_tc_Conv temp = new BasicSelectionTestClass_float_i_e_tc_Conv(); temp.value_short = val; return (temp); } public short GetValueshort() { return (value_short); } public void SetValueshort(short val) { value_short = val; } private uint value_uint; static public implicit operator uint(BasicSelectionTestClass_float_i_e_tc_Conv test) { Log.Comment("To uint"); return test.value_uint; } static public implicit operator BasicSelectionTestClass_float_i_e_tc_Conv(uint val) { Log.Comment("From uint"); BasicSelectionTestClass_float_i_e_tc_Conv temp = new BasicSelectionTestClass_float_i_e_tc_Conv(); temp.value_uint = val; return (temp); } public uint GetValueuint() { return (value_uint); } public void SetValueuint(uint val) { value_uint = val; } private ulong value_ulong; static public implicit operator ulong(BasicSelectionTestClass_float_i_e_tc_Conv test) { Log.Comment("To ulong"); return test.value_ulong; } static public implicit operator BasicSelectionTestClass_float_i_e_tc_Conv(ulong val) { Log.Comment("From ulong"); BasicSelectionTestClass_float_i_e_tc_Conv temp = new BasicSelectionTestClass_float_i_e_tc_Conv(); temp.value_ulong = val; return (temp); } public ulong GetValueulong() { return (value_ulong); } public void SetValueulong(ulong val) { value_ulong = val; } private ushort value_ushort; static public implicit operator ushort(BasicSelectionTestClass_float_i_e_tc_Conv test) { Log.Comment("To ushort"); return test.value_ushort; } static public implicit operator BasicSelectionTestClass_float_i_e_tc_Conv(ushort val) { Log.Comment("From ushort"); BasicSelectionTestClass_float_i_e_tc_Conv temp = new BasicSelectionTestClass_float_i_e_tc_Conv(); temp.value_ushort = val; return (temp); } public ushort GetValueushort() { return (value_ushort); } public void SetValueushort(ushort val) { value_ushort = val; } } class BasicSelectionTestClass_float_i_e_tc { public static int Main_old() { BasicSelectionTestClass_float_i_e_tc_Conv cl = new BasicSelectionTestClass_float_i_e_tc_Conv(); float val = 1F; cl = (BasicSelectionTestClass_float_i_e_tc_Conv)val; if (cl.GetValuefloat() != 1F) return 1; else return 0; } public static bool testMethod() { return (Main_old() == 0); } } class BasicSelectionTestClass_float_e_e_tc_Conv { private byte value_byte; static public explicit operator byte(BasicSelectionTestClass_float_e_e_tc_Conv test) { Log.Comment("To byte"); return test.value_byte; } static public explicit operator BasicSelectionTestClass_float_e_e_tc_Conv(byte val) { Log.Comment("From byte"); BasicSelectionTestClass_float_e_e_tc_Conv temp = new BasicSelectionTestClass_float_e_e_tc_Conv(); temp.value_byte = val; return (temp); } public byte GetValuebyte() { return (value_byte); } public void SetValuebyte(byte val) { value_byte = val; } private char value_char; static public explicit operator char(BasicSelectionTestClass_float_e_e_tc_Conv test) { Log.Comment("To char"); return test.value_char; } static public explicit operator BasicSelectionTestClass_float_e_e_tc_Conv(char val) { Log.Comment("From char"); BasicSelectionTestClass_float_e_e_tc_Conv temp = new BasicSelectionTestClass_float_e_e_tc_Conv(); temp.value_char = val; return (temp); } public char GetValuechar() { return (value_char); } public void SetValuechar(char val) { value_char = val; } private double value_double; static public explicit operator double(BasicSelectionTestClass_float_e_e_tc_Conv test) { Log.Comment("To double"); return test.value_double; } static public explicit operator BasicSelectionTestClass_float_e_e_tc_Conv(double val) { Log.Comment("From double"); BasicSelectionTestClass_float_e_e_tc_Conv temp = new BasicSelectionTestClass_float_e_e_tc_Conv(); temp.value_double = val; return (temp); } public double GetValuedouble() { return (value_double); } public void SetValuedouble(double val) { value_double = val; } private float value_float; static public explicit operator float(BasicSelectionTestClass_float_e_e_tc_Conv test) { Log.Comment("To float"); return test.value_float; } static public explicit operator BasicSelectionTestClass_float_e_e_tc_Conv(float val) { Log.Comment("From float"); BasicSelectionTestClass_float_e_e_tc_Conv temp = new BasicSelectionTestClass_float_e_e_tc_Conv(); temp.value_float = val; return (temp); } public float GetValuefloat() { return (value_float); } public void SetValuefloat(float val) { value_float = val; } private int value_int; static public explicit operator int(BasicSelectionTestClass_float_e_e_tc_Conv test) { Log.Comment("To int"); return test.value_int; } static public explicit operator BasicSelectionTestClass_float_e_e_tc_Conv(int val) { Log.Comment("From int"); BasicSelectionTestClass_float_e_e_tc_Conv temp = new BasicSelectionTestClass_float_e_e_tc_Conv(); temp.value_int = val; return (temp); } public int GetValueint() { return (value_int); } public void SetValueint(int val) { value_int = val; } private long value_long; static public explicit operator long(BasicSelectionTestClass_float_e_e_tc_Conv test) { Log.Comment("To long"); return test.value_long; } static public explicit operator BasicSelectionTestClass_float_e_e_tc_Conv(long val) { Log.Comment("From long"); BasicSelectionTestClass_float_e_e_tc_Conv temp = new BasicSelectionTestClass_float_e_e_tc_Conv(); temp.value_long = val; return (temp); } public long GetValuelong() { return (value_long); } public void SetValuelong(long val) { value_long = val; } private sbyte value_sbyte; static public explicit operator sbyte(BasicSelectionTestClass_float_e_e_tc_Conv test) { Log.Comment("To sbyte"); return test.value_sbyte; } static public explicit operator BasicSelectionTestClass_float_e_e_tc_Conv(sbyte val) { Log.Comment("From sbyte"); BasicSelectionTestClass_float_e_e_tc_Conv temp = new BasicSelectionTestClass_float_e_e_tc_Conv(); temp.value_sbyte = val; return (temp); } public sbyte GetValuesbyte() { return (value_sbyte); } public void SetValuesbyte(sbyte val) { value_sbyte = val; } private short value_short; static public explicit operator short(BasicSelectionTestClass_float_e_e_tc_Conv test) { Log.Comment("To short"); return test.value_short; } static public explicit operator BasicSelectionTestClass_float_e_e_tc_Conv(short val) { Log.Comment("From short"); BasicSelectionTestClass_float_e_e_tc_Conv temp = new BasicSelectionTestClass_float_e_e_tc_Conv(); temp.value_short = val; return (temp); } public short GetValueshort() { return (value_short); } public void SetValueshort(short val) { value_short = val; } private uint value_uint; static public explicit operator uint(BasicSelectionTestClass_float_e_e_tc_Conv test) { Log.Comment("To uint"); return test.value_uint; } static public explicit operator BasicSelectionTestClass_float_e_e_tc_Conv(uint val) { Log.Comment("From uint"); BasicSelectionTestClass_float_e_e_tc_Conv temp = new BasicSelectionTestClass_float_e_e_tc_Conv(); temp.value_uint = val; return (temp); } public uint GetValueuint() { return (value_uint); } public void SetValueuint(uint val) { value_uint = val; } private ulong value_ulong; static public explicit operator ulong(BasicSelectionTestClass_float_e_e_tc_Conv test) { Log.Comment("To ulong"); return test.value_ulong; } static public explicit operator BasicSelectionTestClass_float_e_e_tc_Conv(ulong val) { Log.Comment("From ulong"); BasicSelectionTestClass_float_e_e_tc_Conv temp = new BasicSelectionTestClass_float_e_e_tc_Conv(); temp.value_ulong = val; return (temp); } public ulong GetValueulong() { return (value_ulong); } public void SetValueulong(ulong val) { value_ulong = val; } private ushort value_ushort; static public explicit operator ushort(BasicSelectionTestClass_float_e_e_tc_Conv test) { Log.Comment("To ushort"); return test.value_ushort; } static public explicit operator BasicSelectionTestClass_float_e_e_tc_Conv(ushort val) { Log.Comment("From ushort"); BasicSelectionTestClass_float_e_e_tc_Conv temp = new BasicSelectionTestClass_float_e_e_tc_Conv(); temp.value_ushort = val; return (temp); } public ushort GetValueushort() { return (value_ushort); } public void SetValueushort(ushort val) { value_ushort = val; } } class BasicSelectionTestClass_float_e_e_tc { public static int Main_old() { BasicSelectionTestClass_float_e_e_tc_Conv cl = new BasicSelectionTestClass_float_e_e_tc_Conv(); float val = 1F; cl = (BasicSelectionTestClass_float_e_e_tc_Conv)val; if (cl.GetValuefloat() != 1F) return 1; else return 0; } public static bool testMethod() { return (Main_old() == 0); } } class BasicSelectionTestClass_float_i_i_fc_Conv { private byte value_byte; static public implicit operator byte(BasicSelectionTestClass_float_i_i_fc_Conv test) { Log.Comment("To byte"); return test.value_byte; } static public implicit operator BasicSelectionTestClass_float_i_i_fc_Conv(byte val) { Log.Comment("From byte"); BasicSelectionTestClass_float_i_i_fc_Conv temp = new BasicSelectionTestClass_float_i_i_fc_Conv(); temp.value_byte = val; return (temp); } public byte GetValuebyte() { return (value_byte); } public void SetValuebyte(byte val) { value_byte = val; } private char value_char; static public implicit operator char(BasicSelectionTestClass_float_i_i_fc_Conv test) { Log.Comment("To char"); return test.value_char; } static public implicit operator BasicSelectionTestClass_float_i_i_fc_Conv(char val) { Log.Comment("From char"); BasicSelectionTestClass_float_i_i_fc_Conv temp = new BasicSelectionTestClass_float_i_i_fc_Conv(); temp.value_char = val; return (temp); } public char GetValuechar() { return (value_char); } public void SetValuechar(char val) { value_char = val; } private double value_double; static public implicit operator double(BasicSelectionTestClass_float_i_i_fc_Conv test) { Log.Comment("To double"); return test.value_double; } static public implicit operator BasicSelectionTestClass_float_i_i_fc_Conv(double val) { Log.Comment("From double"); BasicSelectionTestClass_float_i_i_fc_Conv temp = new BasicSelectionTestClass_float_i_i_fc_Conv(); temp.value_double = val; return (temp); } public double GetValuedouble() { return (value_double); } public void SetValuedouble(double val) { value_double = val; } private float value_float; static public implicit operator float(BasicSelectionTestClass_float_i_i_fc_Conv test) { Log.Comment("To float"); return test.value_float; } static public implicit operator BasicSelectionTestClass_float_i_i_fc_Conv(float val) { Log.Comment("From float"); BasicSelectionTestClass_float_i_i_fc_Conv temp = new BasicSelectionTestClass_float_i_i_fc_Conv(); temp.value_float = val; return (temp); } public float GetValuefloat() { return (value_float); } public void SetValuefloat(float val) { value_float = val; } private int value_int; static public implicit operator int(BasicSelectionTestClass_float_i_i_fc_Conv test) { Log.Comment("To int"); return test.value_int; } static public implicit operator BasicSelectionTestClass_float_i_i_fc_Conv(int val) { Log.Comment("From int"); BasicSelectionTestClass_float_i_i_fc_Conv temp = new BasicSelectionTestClass_float_i_i_fc_Conv(); temp.value_int = val; return (temp); } public int GetValueint() { return (value_int); } public void SetValueint(int val) { value_int = val; } private long value_long; static public implicit operator long(BasicSelectionTestClass_float_i_i_fc_Conv test) { Log.Comment("To long"); return test.value_long; } static public implicit operator BasicSelectionTestClass_float_i_i_fc_Conv(long val) { Log.Comment("From long"); BasicSelectionTestClass_float_i_i_fc_Conv temp = new BasicSelectionTestClass_float_i_i_fc_Conv(); temp.value_long = val; return (temp); } public long GetValuelong() { return (value_long); } public void SetValuelong(long val) { value_long = val; } private sbyte value_sbyte; static public implicit operator sbyte(BasicSelectionTestClass_float_i_i_fc_Conv test) { Log.Comment("To sbyte"); return test.value_sbyte; } static public implicit operator BasicSelectionTestClass_float_i_i_fc_Conv(sbyte val) { Log.Comment("From sbyte"); BasicSelectionTestClass_float_i_i_fc_Conv temp = new BasicSelectionTestClass_float_i_i_fc_Conv(); temp.value_sbyte = val; return (temp); } public sbyte GetValuesbyte() { return (value_sbyte); } public void SetValuesbyte(sbyte val) { value_sbyte = val; } private short value_short; static public implicit operator short(BasicSelectionTestClass_float_i_i_fc_Conv test) { Log.Comment("To short"); return test.value_short; } static public implicit operator BasicSelectionTestClass_float_i_i_fc_Conv(short val) { Log.Comment("From short"); BasicSelectionTestClass_float_i_i_fc_Conv temp = new BasicSelectionTestClass_float_i_i_fc_Conv(); temp.value_short = val; return (temp); } public short GetValueshort() { return (value_short); } public void SetValueshort(short val) { value_short = val; } private uint value_uint; static public implicit operator uint(BasicSelectionTestClass_float_i_i_fc_Conv test) { Log.Comment("To uint"); return test.value_uint; } static public implicit operator BasicSelectionTestClass_float_i_i_fc_Conv(uint val) { Log.Comment("From uint"); BasicSelectionTestClass_float_i_i_fc_Conv temp = new BasicSelectionTestClass_float_i_i_fc_Conv(); temp.value_uint = val; return (temp); } public uint GetValueuint() { return (value_uint); } public void SetValueuint(uint val) { value_uint = val; } private ulong value_ulong; static public implicit operator ulong(BasicSelectionTestClass_float_i_i_fc_Conv test) { Log.Comment("To ulong"); return test.value_ulong; } static public implicit operator BasicSelectionTestClass_float_i_i_fc_Conv(ulong val) { Log.Comment("From ulong"); BasicSelectionTestClass_float_i_i_fc_Conv temp = new BasicSelectionTestClass_float_i_i_fc_Conv(); temp.value_ulong = val; return (temp); } public ulong GetValueulong() { return (value_ulong); } public void SetValueulong(ulong val) { value_ulong = val; } private ushort value_ushort; static public implicit operator ushort(BasicSelectionTestClass_float_i_i_fc_Conv test) { Log.Comment("To ushort"); return test.value_ushort; } static public implicit operator BasicSelectionTestClass_float_i_i_fc_Conv(ushort val) { Log.Comment("From ushort"); BasicSelectionTestClass_float_i_i_fc_Conv temp = new BasicSelectionTestClass_float_i_i_fc_Conv(); temp.value_ushort = val; return (temp); } public ushort GetValueushort() { return (value_ushort); } public void SetValueushort(ushort val) { value_ushort = val; } } class BasicSelectionTestClass_float_i_i_fc { public static int Main_old() { BasicSelectionTestClass_float_i_i_fc_Conv cl = new BasicSelectionTestClass_float_i_i_fc_Conv(); cl.SetValuefloat(1F); float value = cl; if (value != 1F) return 1; else return 0; } public static bool testMethod() { return (Main_old() == 0); } } class BasicSelectionTestClass_float_i_e_fc_Conv { private byte value_byte; static public implicit operator byte(BasicSelectionTestClass_float_i_e_fc_Conv test) { Log.Comment("To byte"); return test.value_byte; } static public implicit operator BasicSelectionTestClass_float_i_e_fc_Conv(byte val) { Log.Comment("From byte"); BasicSelectionTestClass_float_i_e_fc_Conv temp = new BasicSelectionTestClass_float_i_e_fc_Conv(); temp.value_byte = val; return (temp); } public byte GetValuebyte() { return (value_byte); } public void SetValuebyte(byte val) { value_byte = val; } private char value_char; static public implicit operator char(BasicSelectionTestClass_float_i_e_fc_Conv test) { Log.Comment("To char"); return test.value_char; } static public implicit operator BasicSelectionTestClass_float_i_e_fc_Conv(char val) { Log.Comment("From char"); BasicSelectionTestClass_float_i_e_fc_Conv temp = new BasicSelectionTestClass_float_i_e_fc_Conv(); temp.value_char = val; return (temp); } public char GetValuechar() { return (value_char); } public void SetValuechar(char val) { value_char = val; } private double value_double; static public implicit operator double(BasicSelectionTestClass_float_i_e_fc_Conv test) { Log.Comment("To double"); return test.value_double; } static public implicit operator BasicSelectionTestClass_float_i_e_fc_Conv(double val) { Log.Comment("From double"); BasicSelectionTestClass_float_i_e_fc_Conv temp = new BasicSelectionTestClass_float_i_e_fc_Conv(); temp.value_double = val; return (temp); } public double GetValuedouble() { return (value_double); } public void SetValuedouble(double val) { value_double = val; } private float value_float; static public implicit operator float(BasicSelectionTestClass_float_i_e_fc_Conv test) { Log.Comment("To float"); return test.value_float; } static public implicit operator BasicSelectionTestClass_float_i_e_fc_Conv(float val) { Log.Comment("From float"); BasicSelectionTestClass_float_i_e_fc_Conv temp = new BasicSelectionTestClass_float_i_e_fc_Conv(); temp.value_float = val; return (temp); } public float GetValuefloat() { return (value_float); } public void SetValuefloat(float val) { value_float = val; } private int value_int; static public implicit operator int(BasicSelectionTestClass_float_i_e_fc_Conv test) { Log.Comment("To int"); return test.value_int; } static public implicit operator BasicSelectionTestClass_float_i_e_fc_Conv(int val) { Log.Comment("From int"); BasicSelectionTestClass_float_i_e_fc_Conv temp = new BasicSelectionTestClass_float_i_e_fc_Conv(); temp.value_int = val; return (temp); } public int GetValueint() { return (value_int); } public void SetValueint(int val) { value_int = val; } private long value_long; static public implicit operator long(BasicSelectionTestClass_float_i_e_fc_Conv test) { Log.Comment("To long"); return test.value_long; } static public implicit operator BasicSelectionTestClass_float_i_e_fc_Conv(long val) { Log.Comment("From long"); BasicSelectionTestClass_float_i_e_fc_Conv temp = new BasicSelectionTestClass_float_i_e_fc_Conv(); temp.value_long = val; return (temp); } public long GetValuelong() { return (value_long); } public void SetValuelong(long val) { value_long = val; } private sbyte value_sbyte; static public implicit operator sbyte(BasicSelectionTestClass_float_i_e_fc_Conv test) { Log.Comment("To sbyte"); return test.value_sbyte; } static public implicit operator BasicSelectionTestClass_float_i_e_fc_Conv(sbyte val) { Log.Comment("From sbyte"); BasicSelectionTestClass_float_i_e_fc_Conv temp = new BasicSelectionTestClass_float_i_e_fc_Conv(); temp.value_sbyte = val; return (temp); } public sbyte GetValuesbyte() { return (value_sbyte); } public void SetValuesbyte(sbyte val) { value_sbyte = val; } private short value_short; static public implicit operator short(BasicSelectionTestClass_float_i_e_fc_Conv test) { Log.Comment("To short"); return test.value_short; } static public implicit operator BasicSelectionTestClass_float_i_e_fc_Conv(short val) { Log.Comment("From short"); BasicSelectionTestClass_float_i_e_fc_Conv temp = new BasicSelectionTestClass_float_i_e_fc_Conv(); temp.value_short = val; return (temp); } public short GetValueshort() { return (value_short); } public void SetValueshort(short val) { value_short = val; } private uint value_uint; static public implicit operator uint(BasicSelectionTestClass_float_i_e_fc_Conv test) { Log.Comment("To uint"); return test.value_uint; } static public implicit operator BasicSelectionTestClass_float_i_e_fc_Conv(uint val) { Log.Comment("From uint"); BasicSelectionTestClass_float_i_e_fc_Conv temp = new BasicSelectionTestClass_float_i_e_fc_Conv(); temp.value_uint = val; return (temp); } public uint GetValueuint() { return (value_uint); } public void SetValueuint(uint val) { value_uint = val; } private ulong value_ulong; static public implicit operator ulong(BasicSelectionTestClass_float_i_e_fc_Conv test) { Log.Comment("To ulong"); return test.value_ulong; } static public implicit operator BasicSelectionTestClass_float_i_e_fc_Conv(ulong val) { Log.Comment("From ulong"); BasicSelectionTestClass_float_i_e_fc_Conv temp = new BasicSelectionTestClass_float_i_e_fc_Conv(); temp.value_ulong = val; return (temp); } public ulong GetValueulong() { return (value_ulong); } public void SetValueulong(ulong val) { value_ulong = val; } private ushort value_ushort; static public implicit operator ushort(BasicSelectionTestClass_float_i_e_fc_Conv test) { Log.Comment("To ushort"); return test.value_ushort; } static public implicit operator BasicSelectionTestClass_float_i_e_fc_Conv(ushort val) { Log.Comment("From ushort"); BasicSelectionTestClass_float_i_e_fc_Conv temp = new BasicSelectionTestClass_float_i_e_fc_Conv(); temp.value_ushort = val; return (temp); } public ushort GetValueushort() { return (value_ushort); } public void SetValueushort(ushort val) { value_ushort = val; } } class BasicSelectionTestClass_float_i_e_fc { public static int Main_old() { BasicSelectionTestClass_float_i_e_fc_Conv cl = new BasicSelectionTestClass_float_i_e_fc_Conv(); cl.SetValuefloat(1F); float value = (float)cl; if (value != 1F) return 1; else return 0; } public static bool testMethod() { return (Main_old() == 0); } } class BasicSelectionTestClass_float_e_e_fc_Conv { private byte value_byte; static public explicit operator byte(BasicSelectionTestClass_float_e_e_fc_Conv test) { Log.Comment("To byte"); return test.value_byte; } static public explicit operator BasicSelectionTestClass_float_e_e_fc_Conv(byte val) { Log.Comment("From byte"); BasicSelectionTestClass_float_e_e_fc_Conv temp = new BasicSelectionTestClass_float_e_e_fc_Conv(); temp.value_byte = val; return (temp); } public byte GetValuebyte() { return (value_byte); } public void SetValuebyte(byte val) { value_byte = val; } private char value_char; static public explicit operator char(BasicSelectionTestClass_float_e_e_fc_Conv test) { Log.Comment("To char"); return test.value_char; } static public explicit operator BasicSelectionTestClass_float_e_e_fc_Conv(char val) { Log.Comment("From char"); BasicSelectionTestClass_float_e_e_fc_Conv temp = new BasicSelectionTestClass_float_e_e_fc_Conv(); temp.value_char = val; return (temp); } public char GetValuechar() { return (value_char); } public void SetValuechar(char val) { value_char = val; } private double value_double; static public explicit operator double(BasicSelectionTestClass_float_e_e_fc_Conv test) { Log.Comment("To double"); return test.value_double; } static public explicit operator BasicSelectionTestClass_float_e_e_fc_Conv(double val) { Log.Comment("From double"); BasicSelectionTestClass_float_e_e_fc_Conv temp = new BasicSelectionTestClass_float_e_e_fc_Conv(); temp.value_double = val; return (temp); } public double GetValuedouble() { return (value_double); } public void SetValuedouble(double val) { value_double = val; } private float value_float; static public explicit operator float(BasicSelectionTestClass_float_e_e_fc_Conv test) { Log.Comment("To float"); return test.value_float; } static public explicit operator BasicSelectionTestClass_float_e_e_fc_Conv(float val) { Log.Comment("From float"); BasicSelectionTestClass_float_e_e_fc_Conv temp = new BasicSelectionTestClass_float_e_e_fc_Conv(); temp.value_float = val; return (temp); } public float GetValuefloat() { return (value_float); } public void SetValuefloat(float val) { value_float = val; } private int value_int; static public explicit operator int(BasicSelectionTestClass_float_e_e_fc_Conv test) { Log.Comment("To int"); return test.value_int; } static public explicit operator BasicSelectionTestClass_float_e_e_fc_Conv(int val) { Log.Comment("From int"); BasicSelectionTestClass_float_e_e_fc_Conv temp = new BasicSelectionTestClass_float_e_e_fc_Conv(); temp.value_int = val; return (temp); } public int GetValueint() { return (value_int); } public void SetValueint(int val) { value_int = val; } private long value_long; static public explicit operator long(BasicSelectionTestClass_float_e_e_fc_Conv test) { Log.Comment("To long"); return test.value_long; } static public explicit operator BasicSelectionTestClass_float_e_e_fc_Conv(long val) { Log.Comment("From long"); BasicSelectionTestClass_float_e_e_fc_Conv temp = new BasicSelectionTestClass_float_e_e_fc_Conv(); temp.value_long = val; return (temp); } public long GetValuelong() { return (value_long); } public void SetValuelong(long val) { value_long = val; } private sbyte value_sbyte; static public explicit operator sbyte(BasicSelectionTestClass_float_e_e_fc_Conv test) { Log.Comment("To sbyte"); return test.value_sbyte; } static public explicit operator BasicSelectionTestClass_float_e_e_fc_Conv(sbyte val) { Log.Comment("From sbyte"); BasicSelectionTestClass_float_e_e_fc_Conv temp = new BasicSelectionTestClass_float_e_e_fc_Conv(); temp.value_sbyte = val; return (temp); } public sbyte GetValuesbyte() { return (value_sbyte); } public void SetValuesbyte(sbyte val) { value_sbyte = val; } private short value_short; static public explicit operator short(BasicSelectionTestClass_float_e_e_fc_Conv test) { Log.Comment("To short"); return test.value_short; } static public explicit operator BasicSelectionTestClass_float_e_e_fc_Conv(short val) { Log.Comment("From short"); BasicSelectionTestClass_float_e_e_fc_Conv temp = new BasicSelectionTestClass_float_e_e_fc_Conv(); temp.value_short = val; return (temp); } public short GetValueshort() { return (value_short); } public void SetValueshort(short val) { value_short = val; } private uint value_uint; static public explicit operator uint(BasicSelectionTestClass_float_e_e_fc_Conv test) { Log.Comment("To uint"); return test.value_uint; } static public explicit operator BasicSelectionTestClass_float_e_e_fc_Conv(uint val) { Log.Comment("From uint"); BasicSelectionTestClass_float_e_e_fc_Conv temp = new BasicSelectionTestClass_float_e_e_fc_Conv(); temp.value_uint = val; return (temp); } public uint GetValueuint() { return (value_uint); } public void SetValueuint(uint val) { value_uint = val; } private ulong value_ulong; static public explicit operator ulong(BasicSelectionTestClass_float_e_e_fc_Conv test) { Log.Comment("To ulong"); return test.value_ulong; } static public explicit operator BasicSelectionTestClass_float_e_e_fc_Conv(ulong val) { Log.Comment("From ulong"); BasicSelectionTestClass_float_e_e_fc_Conv temp = new BasicSelectionTestClass_float_e_e_fc_Conv(); temp.value_ulong = val; return (temp); } public ulong GetValueulong() { return (value_ulong); } public void SetValueulong(ulong val) { value_ulong = val; } private ushort value_ushort; static public explicit operator ushort(BasicSelectionTestClass_float_e_e_fc_Conv test) { Log.Comment("To ushort"); return test.value_ushort; } static public explicit operator BasicSelectionTestClass_float_e_e_fc_Conv(ushort val) { Log.Comment("From ushort"); BasicSelectionTestClass_float_e_e_fc_Conv temp = new BasicSelectionTestClass_float_e_e_fc_Conv(); temp.value_ushort = val; return (temp); } public ushort GetValueushort() { return (value_ushort); } public void SetValueushort(ushort val) { value_ushort = val; } } class BasicSelectionTestClass_float_e_e_fc { public static int Main_old() { BasicSelectionTestClass_float_e_e_fc_Conv cl = new BasicSelectionTestClass_float_e_e_fc_Conv(); cl.SetValuefloat(1F); float value = (float)cl; if (value != 1F) return 1; else return 0; } public static bool testMethod() { return (Main_old() == 0); } } class BasicSelectionTestClass_int_i_i_tc_Conv { private byte value_byte; static public implicit operator byte(BasicSelectionTestClass_int_i_i_tc_Conv test) { Log.Comment("To byte"); return test.value_byte; } static public implicit operator BasicSelectionTestClass_int_i_i_tc_Conv(byte val) { Log.Comment("From byte"); BasicSelectionTestClass_int_i_i_tc_Conv temp = new BasicSelectionTestClass_int_i_i_tc_Conv(); temp.value_byte = val; return (temp); } public byte GetValuebyte() { return (value_byte); } public void SetValuebyte(byte val) { value_byte = val; } private char value_char; static public implicit operator char(BasicSelectionTestClass_int_i_i_tc_Conv test) { Log.Comment("To char"); return test.value_char; } static public implicit operator BasicSelectionTestClass_int_i_i_tc_Conv(char val) { Log.Comment("From char"); BasicSelectionTestClass_int_i_i_tc_Conv temp = new BasicSelectionTestClass_int_i_i_tc_Conv(); temp.value_char = val; return (temp); } public char GetValuechar() { return (value_char); } public void SetValuechar(char val) { value_char = val; } private double value_double; static public implicit operator double(BasicSelectionTestClass_int_i_i_tc_Conv test) { Log.Comment("To double"); return test.value_double; } static public implicit operator BasicSelectionTestClass_int_i_i_tc_Conv(double val) { Log.Comment("From double"); BasicSelectionTestClass_int_i_i_tc_Conv temp = new BasicSelectionTestClass_int_i_i_tc_Conv(); temp.value_double = val; return (temp); } public double GetValuedouble() { return (value_double); } public void SetValuedouble(double val) { value_double = val; } private float value_float; static public implicit operator float(BasicSelectionTestClass_int_i_i_tc_Conv test) { Log.Comment("To float"); return test.value_float; } static public implicit operator BasicSelectionTestClass_int_i_i_tc_Conv(float val) { Log.Comment("From float"); BasicSelectionTestClass_int_i_i_tc_Conv temp = new BasicSelectionTestClass_int_i_i_tc_Conv(); temp.value_float = val; return (temp); } public float GetValuefloat() { return (value_float); } public void SetValuefloat(float val) { value_float = val; } private int value_int; static public implicit operator int(BasicSelectionTestClass_int_i_i_tc_Conv test) { Log.Comment("To int"); return test.value_int; } static public implicit operator BasicSelectionTestClass_int_i_i_tc_Conv(int val) { Log.Comment("From int"); BasicSelectionTestClass_int_i_i_tc_Conv temp = new BasicSelectionTestClass_int_i_i_tc_Conv(); temp.value_int = val; return (temp); } public int GetValueint() { return (value_int); } public void SetValueint(int val) { value_int = val; } private long value_long; static public implicit operator long(BasicSelectionTestClass_int_i_i_tc_Conv test) { Log.Comment("To long"); return test.value_long; } static public implicit operator BasicSelectionTestClass_int_i_i_tc_Conv(long val) { Log.Comment("From long"); BasicSelectionTestClass_int_i_i_tc_Conv temp = new BasicSelectionTestClass_int_i_i_tc_Conv(); temp.value_long = val; return (temp); } public long GetValuelong() { return (value_long); } public void SetValuelong(long val) { value_long = val; } private sbyte value_sbyte; static public implicit operator sbyte(BasicSelectionTestClass_int_i_i_tc_Conv test) { Log.Comment("To sbyte"); return test.value_sbyte; } static public implicit operator BasicSelectionTestClass_int_i_i_tc_Conv(sbyte val) { Log.Comment("From sbyte"); BasicSelectionTestClass_int_i_i_tc_Conv temp = new BasicSelectionTestClass_int_i_i_tc_Conv(); temp.value_sbyte = val; return (temp); } public sbyte GetValuesbyte() { return (value_sbyte); } public void SetValuesbyte(sbyte val) { value_sbyte = val; } private short value_short; static public implicit operator short(BasicSelectionTestClass_int_i_i_tc_Conv test) { Log.Comment("To short"); return test.value_short; } static public implicit operator BasicSelectionTestClass_int_i_i_tc_Conv(short val) { Log.Comment("From short"); BasicSelectionTestClass_int_i_i_tc_Conv temp = new BasicSelectionTestClass_int_i_i_tc_Conv(); temp.value_short = val; return (temp); } public short GetValueshort() { return (value_short); } public void SetValueshort(short val) { value_short = val; } private uint value_uint; static public implicit operator uint(BasicSelectionTestClass_int_i_i_tc_Conv test) { Log.Comment("To uint"); return test.value_uint; } static public implicit operator BasicSelectionTestClass_int_i_i_tc_Conv(uint val) { Log.Comment("From uint"); BasicSelectionTestClass_int_i_i_tc_Conv temp = new BasicSelectionTestClass_int_i_i_tc_Conv(); temp.value_uint = val; return (temp); } public uint GetValueuint() { return (value_uint); } public void SetValueuint(uint val) { value_uint = val; } private ulong value_ulong; static public implicit operator ulong(BasicSelectionTestClass_int_i_i_tc_Conv test) { Log.Comment("To ulong"); return test.value_ulong; } static public implicit operator BasicSelectionTestClass_int_i_i_tc_Conv(ulong val) { Log.Comment("From ulong"); BasicSelectionTestClass_int_i_i_tc_Conv temp = new BasicSelectionTestClass_int_i_i_tc_Conv(); temp.value_ulong = val; return (temp); } public ulong GetValueulong() { return (value_ulong); } public void SetValueulong(ulong val) { value_ulong = val; } private ushort value_ushort; static public implicit operator ushort(BasicSelectionTestClass_int_i_i_tc_Conv test) { Log.Comment("To ushort"); return test.value_ushort; } static public implicit operator BasicSelectionTestClass_int_i_i_tc_Conv(ushort val) { Log.Comment("From ushort"); BasicSelectionTestClass_int_i_i_tc_Conv temp = new BasicSelectionTestClass_int_i_i_tc_Conv(); temp.value_ushort = val; return (temp); } public ushort GetValueushort() { return (value_ushort); } public void SetValueushort(ushort val) { value_ushort = val; } } class BasicSelectionTestClass_int_i_i_tc { public static int Main_old() { BasicSelectionTestClass_int_i_i_tc_Conv cl = new BasicSelectionTestClass_int_i_i_tc_Conv(); int val = 1; cl = val; if (cl.GetValueint() != 1) return 1; else return 0; } public static bool testMethod() { return (Main_old() == 0); } } class BasicSelectionTestClass_long_i_i_fc_Conv { private byte value_byte; static public implicit operator byte(BasicSelectionTestClass_long_i_i_fc_Conv test) { Log.Comment("To byte"); return test.value_byte; } static public implicit operator BasicSelectionTestClass_long_i_i_fc_Conv(byte val) { Log.Comment("From byte"); BasicSelectionTestClass_long_i_i_fc_Conv temp = new BasicSelectionTestClass_long_i_i_fc_Conv(); temp.value_byte = val; return (temp); } public byte GetValuebyte() { return (value_byte); } public void SetValuebyte(byte val) { value_byte = val; } private char value_char; static public implicit operator char(BasicSelectionTestClass_long_i_i_fc_Conv test) { Log.Comment("To char"); return test.value_char; } static public implicit operator BasicSelectionTestClass_long_i_i_fc_Conv(char val) { Log.Comment("From char"); BasicSelectionTestClass_long_i_i_fc_Conv temp = new BasicSelectionTestClass_long_i_i_fc_Conv(); temp.value_char = val; return (temp); } public char GetValuechar() { return (value_char); } public void SetValuechar(char val) { value_char = val; } private double value_double; static public implicit operator double(BasicSelectionTestClass_long_i_i_fc_Conv test) { Log.Comment("To double"); return test.value_double; } static public implicit operator BasicSelectionTestClass_long_i_i_fc_Conv(double val) { Log.Comment("From double"); BasicSelectionTestClass_long_i_i_fc_Conv temp = new BasicSelectionTestClass_long_i_i_fc_Conv(); temp.value_double = val; return (temp); } public double GetValuedouble() { return (value_double); } public void SetValuedouble(double val) { value_double = val; } private float value_float; static public implicit operator float(BasicSelectionTestClass_long_i_i_fc_Conv test) { Log.Comment("To float"); return test.value_float; } static public implicit operator BasicSelectionTestClass_long_i_i_fc_Conv(float val) { Log.Comment("From float"); BasicSelectionTestClass_long_i_i_fc_Conv temp = new BasicSelectionTestClass_long_i_i_fc_Conv(); temp.value_float = val; return (temp); } public float GetValuefloat() { return (value_float); } public void SetValuefloat(float val) { value_float = val; } private int value_int; static public implicit operator int(BasicSelectionTestClass_long_i_i_fc_Conv test) { Log.Comment("To int"); return test.value_int; } static public implicit operator BasicSelectionTestClass_long_i_i_fc_Conv(int val) { Log.Comment("From int"); BasicSelectionTestClass_long_i_i_fc_Conv temp = new BasicSelectionTestClass_long_i_i_fc_Conv(); temp.value_int = val; return (temp); } public int GetValueint() { return (value_int); } public void SetValueint(int val) { value_int = val; } private long value_long; static public implicit operator long(BasicSelectionTestClass_long_i_i_fc_Conv test) { Log.Comment("To long"); return test.value_long; } static public implicit operator BasicSelectionTestClass_long_i_i_fc_Conv(long val) { Log.Comment("From long"); BasicSelectionTestClass_long_i_i_fc_Conv temp = new BasicSelectionTestClass_long_i_i_fc_Conv(); temp.value_long = val; return (temp); } public long GetValuelong() { return (value_long); } public void SetValuelong(long val) { value_long = val; } private sbyte value_sbyte; static public implicit operator sbyte(BasicSelectionTestClass_long_i_i_fc_Conv test) { Log.Comment("To sbyte"); return test.value_sbyte; } static public implicit operator BasicSelectionTestClass_long_i_i_fc_Conv(sbyte val) { Log.Comment("From sbyte"); BasicSelectionTestClass_long_i_i_fc_Conv temp = new BasicSelectionTestClass_long_i_i_fc_Conv(); temp.value_sbyte = val; return (temp); } public sbyte GetValuesbyte() { return (value_sbyte); } public void SetValuesbyte(sbyte val) { value_sbyte = val; } private short value_short; static public implicit operator short(BasicSelectionTestClass_long_i_i_fc_Conv test) { Log.Comment("To short"); return test.value_short; } static public implicit operator BasicSelectionTestClass_long_i_i_fc_Conv(short val) { Log.Comment("From short"); BasicSelectionTestClass_long_i_i_fc_Conv temp = new BasicSelectionTestClass_long_i_i_fc_Conv(); temp.value_short = val; return (temp); } public short GetValueshort() { return (value_short); } public void SetValueshort(short val) { value_short = val; } private uint value_uint; static public implicit operator uint(BasicSelectionTestClass_long_i_i_fc_Conv test) { Log.Comment("To uint"); return test.value_uint; } static public implicit operator BasicSelectionTestClass_long_i_i_fc_Conv(uint val) { Log.Comment("From uint"); BasicSelectionTestClass_long_i_i_fc_Conv temp = new BasicSelectionTestClass_long_i_i_fc_Conv(); temp.value_uint = val; return (temp); } public uint GetValueuint() { return (value_uint); } public void SetValueuint(uint val) { value_uint = val; } private ulong value_ulong; static public implicit operator ulong(BasicSelectionTestClass_long_i_i_fc_Conv test) { Log.Comment("To ulong"); return test.value_ulong; } static public implicit operator BasicSelectionTestClass_long_i_i_fc_Conv(ulong val) { Log.Comment("From ulong"); BasicSelectionTestClass_long_i_i_fc_Conv temp = new BasicSelectionTestClass_long_i_i_fc_Conv(); temp.value_ulong = val; return (temp); } public ulong GetValueulong() { return (value_ulong); } public void SetValueulong(ulong val) { value_ulong = val; } private ushort value_ushort; static public implicit operator ushort(BasicSelectionTestClass_long_i_i_fc_Conv test) { Log.Comment("To ushort"); return test.value_ushort; } static public implicit operator BasicSelectionTestClass_long_i_i_fc_Conv(ushort val) { Log.Comment("From ushort"); BasicSelectionTestClass_long_i_i_fc_Conv temp = new BasicSelectionTestClass_long_i_i_fc_Conv(); temp.value_ushort = val; return (temp); } public ushort GetValueushort() { return (value_ushort); } public void SetValueushort(ushort val) { value_ushort = val; } } class BasicSelectionTestClass_long_i_i_fc { public static int Main_old() { BasicSelectionTestClass_long_i_i_fc_Conv cl = new BasicSelectionTestClass_long_i_i_fc_Conv(); cl.SetValuelong(1); long value = cl; if (value != 1) return 1; else return 0; } public static bool testMethod() { return (Main_old() == 0); } } class BasicSelectionTestClass_long_i_e_fc_Conv { private byte value_byte; static public implicit operator byte(BasicSelectionTestClass_long_i_e_fc_Conv test) { Log.Comment("To byte"); return test.value_byte; } static public implicit operator BasicSelectionTestClass_long_i_e_fc_Conv(byte val) { Log.Comment("From byte"); BasicSelectionTestClass_long_i_e_fc_Conv temp = new BasicSelectionTestClass_long_i_e_fc_Conv(); temp.value_byte = val; return (temp); } public byte GetValuebyte() { return (value_byte); } public void SetValuebyte(byte val) { value_byte = val; } private char value_char; static public implicit operator char(BasicSelectionTestClass_long_i_e_fc_Conv test) { Log.Comment("To char"); return test.value_char; } static public implicit operator BasicSelectionTestClass_long_i_e_fc_Conv(char val) { Log.Comment("From char"); BasicSelectionTestClass_long_i_e_fc_Conv temp = new BasicSelectionTestClass_long_i_e_fc_Conv(); temp.value_char = val; return (temp); } public char GetValuechar() { return (value_char); } public void SetValuechar(char val) { value_char = val; } private double value_double; static public implicit operator double(BasicSelectionTestClass_long_i_e_fc_Conv test) { Log.Comment("To double"); return test.value_double; } static public implicit operator BasicSelectionTestClass_long_i_e_fc_Conv(double val) { Log.Comment("From double"); BasicSelectionTestClass_long_i_e_fc_Conv temp = new BasicSelectionTestClass_long_i_e_fc_Conv(); temp.value_double = val; return (temp); } public double GetValuedouble() { return (value_double); } public void SetValuedouble(double val) { value_double = val; } private float value_float; static public implicit operator float(BasicSelectionTestClass_long_i_e_fc_Conv test) { Log.Comment("To float"); return test.value_float; } static public implicit operator BasicSelectionTestClass_long_i_e_fc_Conv(float val) { Log.Comment("From float"); BasicSelectionTestClass_long_i_e_fc_Conv temp = new BasicSelectionTestClass_long_i_e_fc_Conv(); temp.value_float = val; return (temp); } public float GetValuefloat() { return (value_float); } public void SetValuefloat(float val) { value_float = val; } private int value_int; static public implicit operator int(BasicSelectionTestClass_long_i_e_fc_Conv test) { Log.Comment("To int"); return test.value_int; } static public implicit operator BasicSelectionTestClass_long_i_e_fc_Conv(int val) { Log.Comment("From int"); BasicSelectionTestClass_long_i_e_fc_Conv temp = new BasicSelectionTestClass_long_i_e_fc_Conv(); temp.value_int = val; return (temp); } public int GetValueint() { return (value_int); } public void SetValueint(int val) { value_int = val; } private long value_long; static public implicit operator long(BasicSelectionTestClass_long_i_e_fc_Conv test) { Log.Comment("To long"); return test.value_long; } static public implicit operator BasicSelectionTestClass_long_i_e_fc_Conv(long val) { Log.Comment("From long"); BasicSelectionTestClass_long_i_e_fc_Conv temp = new BasicSelectionTestClass_long_i_e_fc_Conv(); temp.value_long = val; return (temp); } public long GetValuelong() { return (value_long); } public void SetValuelong(long val) { value_long = val; } private sbyte value_sbyte; static public implicit operator sbyte(BasicSelectionTestClass_long_i_e_fc_Conv test) { Log.Comment("To sbyte"); return test.value_sbyte; } static public implicit operator BasicSelectionTestClass_long_i_e_fc_Conv(sbyte val) { Log.Comment("From sbyte"); BasicSelectionTestClass_long_i_e_fc_Conv temp = new BasicSelectionTestClass_long_i_e_fc_Conv(); temp.value_sbyte = val; return (temp); } public sbyte GetValuesbyte() { return (value_sbyte); } public void SetValuesbyte(sbyte val) { value_sbyte = val; } private short value_short; static public implicit operator short(BasicSelectionTestClass_long_i_e_fc_Conv test) { Log.Comment("To short"); return test.value_short; } static public implicit operator BasicSelectionTestClass_long_i_e_fc_Conv(short val) { Log.Comment("From short"); BasicSelectionTestClass_long_i_e_fc_Conv temp = new BasicSelectionTestClass_long_i_e_fc_Conv(); temp.value_short = val; return (temp); } public short GetValueshort() { return (value_short); } public void SetValueshort(short val) { value_short = val; } private uint value_uint; static public implicit operator uint(BasicSelectionTestClass_long_i_e_fc_Conv test) { Log.Comment("To uint"); return test.value_uint; } static public implicit operator BasicSelectionTestClass_long_i_e_fc_Conv(uint val) { Log.Comment("From uint"); BasicSelectionTestClass_long_i_e_fc_Conv temp = new BasicSelectionTestClass_long_i_e_fc_Conv(); temp.value_uint = val; return (temp); } public uint GetValueuint() { return (value_uint); } public void SetValueuint(uint val) { value_uint = val; } private ulong value_ulong; static public implicit operator ulong(BasicSelectionTestClass_long_i_e_fc_Conv test) { Log.Comment("To ulong"); return test.value_ulong; } static public implicit operator BasicSelectionTestClass_long_i_e_fc_Conv(ulong val) { Log.Comment("From ulong"); BasicSelectionTestClass_long_i_e_fc_Conv temp = new BasicSelectionTestClass_long_i_e_fc_Conv(); temp.value_ulong = val; return (temp); } public ulong GetValueulong() { return (value_ulong); } public void SetValueulong(ulong val) { value_ulong = val; } private ushort value_ushort; static public implicit operator ushort(BasicSelectionTestClass_long_i_e_fc_Conv test) { Log.Comment("To ushort"); return test.value_ushort; } static public implicit operator BasicSelectionTestClass_long_i_e_fc_Conv(ushort val) { Log.Comment("From ushort"); BasicSelectionTestClass_long_i_e_fc_Conv temp = new BasicSelectionTestClass_long_i_e_fc_Conv(); temp.value_ushort = val; return (temp); } public ushort GetValueushort() { return (value_ushort); } public void SetValueushort(ushort val) { value_ushort = val; } } class BasicSelectionTestClass_long_i_e_fc { public static int Main_old() { BasicSelectionTestClass_long_i_e_fc_Conv cl = new BasicSelectionTestClass_long_i_e_fc_Conv(); cl.SetValuelong(1); long value = (long)cl; if (value != 1) return 1; else return 0; } public static bool testMethod() { return (Main_old() == 0); } } class BasicSelectionTestClass_long_e_e_fc_Conv { private byte value_byte; static public explicit operator byte(BasicSelectionTestClass_long_e_e_fc_Conv test) { Log.Comment("To byte"); return test.value_byte; } static public explicit operator BasicSelectionTestClass_long_e_e_fc_Conv(byte val) { Log.Comment("From byte"); BasicSelectionTestClass_long_e_e_fc_Conv temp = new BasicSelectionTestClass_long_e_e_fc_Conv(); temp.value_byte = val; return (temp); } public byte GetValuebyte() { return (value_byte); } public void SetValuebyte(byte val) { value_byte = val; } private char value_char; static public explicit operator char(BasicSelectionTestClass_long_e_e_fc_Conv test) { Log.Comment("To char"); return test.value_char; } static public explicit operator BasicSelectionTestClass_long_e_e_fc_Conv(char val) { Log.Comment("From char"); BasicSelectionTestClass_long_e_e_fc_Conv temp = new BasicSelectionTestClass_long_e_e_fc_Conv(); temp.value_char = val; return (temp); } public char GetValuechar() { return (value_char); } public void SetValuechar(char val) { value_char = val; } private double value_double; static public explicit operator double(BasicSelectionTestClass_long_e_e_fc_Conv test) { Log.Comment("To double"); return test.value_double; } static public explicit operator BasicSelectionTestClass_long_e_e_fc_Conv(double val) { Log.Comment("From double"); BasicSelectionTestClass_long_e_e_fc_Conv temp = new BasicSelectionTestClass_long_e_e_fc_Conv(); temp.value_double = val; return (temp); } public double GetValuedouble() { return (value_double); } public void SetValuedouble(double val) { value_double = val; } private float value_float; static public explicit operator float(BasicSelectionTestClass_long_e_e_fc_Conv test) { Log.Comment("To float"); return test.value_float; } static public explicit operator BasicSelectionTestClass_long_e_e_fc_Conv(float val) { Log.Comment("From float"); BasicSelectionTestClass_long_e_e_fc_Conv temp = new BasicSelectionTestClass_long_e_e_fc_Conv(); temp.value_float = val; return (temp); } public float GetValuefloat() { return (value_float); } public void SetValuefloat(float val) { value_float = val; } private int value_int; static public explicit operator int(BasicSelectionTestClass_long_e_e_fc_Conv test) { Log.Comment("To int"); return test.value_int; } static public explicit operator BasicSelectionTestClass_long_e_e_fc_Conv(int val) { Log.Comment("From int"); BasicSelectionTestClass_long_e_e_fc_Conv temp = new BasicSelectionTestClass_long_e_e_fc_Conv(); temp.value_int = val; return (temp); } public int GetValueint() { return (value_int); } public void SetValueint(int val) { value_int = val; } private long value_long; static public explicit operator long(BasicSelectionTestClass_long_e_e_fc_Conv test) { Log.Comment("To long"); return test.value_long; } static public explicit operator BasicSelectionTestClass_long_e_e_fc_Conv(long val) { Log.Comment("From long"); BasicSelectionTestClass_long_e_e_fc_Conv temp = new BasicSelectionTestClass_long_e_e_fc_Conv(); temp.value_long = val; return (temp); } public long GetValuelong() { return (value_long); } public void SetValuelong(long val) { value_long = val; } private sbyte value_sbyte; static public explicit operator sbyte(BasicSelectionTestClass_long_e_e_fc_Conv test) { Log.Comment("To sbyte"); return test.value_sbyte; } static public explicit operator BasicSelectionTestClass_long_e_e_fc_Conv(sbyte val) { Log.Comment("From sbyte"); BasicSelectionTestClass_long_e_e_fc_Conv temp = new BasicSelectionTestClass_long_e_e_fc_Conv(); temp.value_sbyte = val; return (temp); } public sbyte GetValuesbyte() { return (value_sbyte); } public void SetValuesbyte(sbyte val) { value_sbyte = val; } private short value_short; static public explicit operator short(BasicSelectionTestClass_long_e_e_fc_Conv test) { Log.Comment("To short"); return test.value_short; } static public explicit operator BasicSelectionTestClass_long_e_e_fc_Conv(short val) { Log.Comment("From short"); BasicSelectionTestClass_long_e_e_fc_Conv temp = new BasicSelectionTestClass_long_e_e_fc_Conv(); temp.value_short = val; return (temp); } public short GetValueshort() { return (value_short); } public void SetValueshort(short val) { value_short = val; } private uint value_uint; static public explicit operator uint(BasicSelectionTestClass_long_e_e_fc_Conv test) { Log.Comment("To uint"); return test.value_uint; } static public explicit operator BasicSelectionTestClass_long_e_e_fc_Conv(uint val) { Log.Comment("From uint"); BasicSelectionTestClass_long_e_e_fc_Conv temp = new BasicSelectionTestClass_long_e_e_fc_Conv(); temp.value_uint = val; return (temp); } public uint GetValueuint() { return (value_uint); } public void SetValueuint(uint val) { value_uint = val; } private ulong value_ulong; static public explicit operator ulong(BasicSelectionTestClass_long_e_e_fc_Conv test) { Log.Comment("To ulong"); return test.value_ulong; } static public explicit operator BasicSelectionTestClass_long_e_e_fc_Conv(ulong val) { Log.Comment("From ulong"); BasicSelectionTestClass_long_e_e_fc_Conv temp = new BasicSelectionTestClass_long_e_e_fc_Conv(); temp.value_ulong = val; return (temp); } public ulong GetValueulong() { return (value_ulong); } public void SetValueulong(ulong val) { value_ulong = val; } private ushort value_ushort; static public explicit operator ushort(BasicSelectionTestClass_long_e_e_fc_Conv test) { Log.Comment("To ushort"); return test.value_ushort; } static public explicit operator BasicSelectionTestClass_long_e_e_fc_Conv(ushort val) { Log.Comment("From ushort"); BasicSelectionTestClass_long_e_e_fc_Conv temp = new BasicSelectionTestClass_long_e_e_fc_Conv(); temp.value_ushort = val; return (temp); } public ushort GetValueushort() { return (value_ushort); } public void SetValueushort(ushort val) { value_ushort = val; } } class BasicSelectionTestClass_long_e_e_fc { public static int Main_old() { BasicSelectionTestClass_long_e_e_fc_Conv cl = new BasicSelectionTestClass_long_e_e_fc_Conv(); cl.SetValuelong(1); long value = (long)cl; if (value != 1) return 1; else return 0; } public static bool testMethod() { return (Main_old() == 0); } } class BasicSelectionTestClass_sbyte_i_i_tc_Conv { private byte value_byte; static public implicit operator byte(BasicSelectionTestClass_sbyte_i_i_tc_Conv test) { Log.Comment("To byte"); return test.value_byte; } static public implicit operator BasicSelectionTestClass_sbyte_i_i_tc_Conv(byte val) { Log.Comment("From byte"); BasicSelectionTestClass_sbyte_i_i_tc_Conv temp = new BasicSelectionTestClass_sbyte_i_i_tc_Conv(); temp.value_byte = val; return (temp); } public byte GetValuebyte() { return (value_byte); } public void SetValuebyte(byte val) { value_byte = val; } private char value_char; static public implicit operator char(BasicSelectionTestClass_sbyte_i_i_tc_Conv test) { Log.Comment("To char"); return test.value_char; } static public implicit operator BasicSelectionTestClass_sbyte_i_i_tc_Conv(char val) { Log.Comment("From char"); BasicSelectionTestClass_sbyte_i_i_tc_Conv temp = new BasicSelectionTestClass_sbyte_i_i_tc_Conv(); temp.value_char = val; return (temp); } public char GetValuechar() { return (value_char); } public void SetValuechar(char val) { value_char = val; } private double value_double; static public implicit operator double(BasicSelectionTestClass_sbyte_i_i_tc_Conv test) { Log.Comment("To double"); return test.value_double; } static public implicit operator BasicSelectionTestClass_sbyte_i_i_tc_Conv(double val) { Log.Comment("From double"); BasicSelectionTestClass_sbyte_i_i_tc_Conv temp = new BasicSelectionTestClass_sbyte_i_i_tc_Conv(); temp.value_double = val; return (temp); } public double GetValuedouble() { return (value_double); } public void SetValuedouble(double val) { value_double = val; } private float value_float; static public implicit operator float(BasicSelectionTestClass_sbyte_i_i_tc_Conv test) { Log.Comment("To float"); return test.value_float; } static public implicit operator BasicSelectionTestClass_sbyte_i_i_tc_Conv(float val) { Log.Comment("From float"); BasicSelectionTestClass_sbyte_i_i_tc_Conv temp = new BasicSelectionTestClass_sbyte_i_i_tc_Conv(); temp.value_float = val; return (temp); } public float GetValuefloat() { return (value_float); } public void SetValuefloat(float val) { value_float = val; } private int value_int; static public implicit operator int(BasicSelectionTestClass_sbyte_i_i_tc_Conv test) { Log.Comment("To int"); return test.value_int; } static public implicit operator BasicSelectionTestClass_sbyte_i_i_tc_Conv(int val) { Log.Comment("From int"); BasicSelectionTestClass_sbyte_i_i_tc_Conv temp = new BasicSelectionTestClass_sbyte_i_i_tc_Conv(); temp.value_int = val; return (temp); } public int GetValueint() { return (value_int); } public void SetValueint(int val) { value_int = val; } private long value_long; static public implicit operator long(BasicSelectionTestClass_sbyte_i_i_tc_Conv test) { Log.Comment("To long"); return test.value_long; } static public implicit operator BasicSelectionTestClass_sbyte_i_i_tc_Conv(long val) { Log.Comment("From long"); BasicSelectionTestClass_sbyte_i_i_tc_Conv temp = new BasicSelectionTestClass_sbyte_i_i_tc_Conv(); temp.value_long = val; return (temp); } public long GetValuelong() { return (value_long); } public void SetValuelong(long val) { value_long = val; } private sbyte value_sbyte; static public implicit operator sbyte(BasicSelectionTestClass_sbyte_i_i_tc_Conv test) { Log.Comment("To sbyte"); return test.value_sbyte; } static public implicit operator BasicSelectionTestClass_sbyte_i_i_tc_Conv(sbyte val) { Log.Comment("From sbyte"); BasicSelectionTestClass_sbyte_i_i_tc_Conv temp = new BasicSelectionTestClass_sbyte_i_i_tc_Conv(); temp.value_sbyte = val; return (temp); } public sbyte GetValuesbyte() { return (value_sbyte); } public void SetValuesbyte(sbyte val) { value_sbyte = val; } private short value_short; static public implicit operator short(BasicSelectionTestClass_sbyte_i_i_tc_Conv test) { Log.Comment("To short"); return test.value_short; } static public implicit operator BasicSelectionTestClass_sbyte_i_i_tc_Conv(short val) { Log.Comment("From short"); BasicSelectionTestClass_sbyte_i_i_tc_Conv temp = new BasicSelectionTestClass_sbyte_i_i_tc_Conv(); temp.value_short = val; return (temp); } public short GetValueshort() { return (value_short); } public void SetValueshort(short val) { value_short = val; } private uint value_uint; static public implicit operator uint(BasicSelectionTestClass_sbyte_i_i_tc_Conv test) { Log.Comment("To uint"); return test.value_uint; } static public implicit operator BasicSelectionTestClass_sbyte_i_i_tc_Conv(uint val) { Log.Comment("From uint"); BasicSelectionTestClass_sbyte_i_i_tc_Conv temp = new BasicSelectionTestClass_sbyte_i_i_tc_Conv(); temp.value_uint = val; return (temp); } public uint GetValueuint() { return (value_uint); } public void SetValueuint(uint val) { value_uint = val; } private ulong value_ulong; static public implicit operator ulong(BasicSelectionTestClass_sbyte_i_i_tc_Conv test) { Log.Comment("To ulong"); return test.value_ulong; } static public implicit operator BasicSelectionTestClass_sbyte_i_i_tc_Conv(ulong val) { Log.Comment("From ulong"); BasicSelectionTestClass_sbyte_i_i_tc_Conv temp = new BasicSelectionTestClass_sbyte_i_i_tc_Conv(); temp.value_ulong = val; return (temp); } public ulong GetValueulong() { return (value_ulong); } public void SetValueulong(ulong val) { value_ulong = val; } private ushort value_ushort; static public implicit operator ushort(BasicSelectionTestClass_sbyte_i_i_tc_Conv test) { Log.Comment("To ushort"); return test.value_ushort; } static public implicit operator BasicSelectionTestClass_sbyte_i_i_tc_Conv(ushort val) { Log.Comment("From ushort"); BasicSelectionTestClass_sbyte_i_i_tc_Conv temp = new BasicSelectionTestClass_sbyte_i_i_tc_Conv(); temp.value_ushort = val; return (temp); } public ushort GetValueushort() { return (value_ushort); } public void SetValueushort(ushort val) { value_ushort = val; } } class BasicSelectionTestClass_sbyte_i_i_tc { public static int Main_old() { BasicSelectionTestClass_sbyte_i_i_tc_Conv cl = new BasicSelectionTestClass_sbyte_i_i_tc_Conv(); sbyte val = 1; cl = val; if (cl.GetValuesbyte() != 1) return 1; else return 0; } public static bool testMethod() { return (Main_old() == 0); } } class BasicSelectionTestClass_int_i_e_tc_Conv { private byte value_byte; static public implicit operator byte(BasicSelectionTestClass_int_i_e_tc_Conv test) { Log.Comment("To byte"); return test.value_byte; } static public implicit operator BasicSelectionTestClass_int_i_e_tc_Conv(byte val) { Log.Comment("From byte"); BasicSelectionTestClass_int_i_e_tc_Conv temp = new BasicSelectionTestClass_int_i_e_tc_Conv(); temp.value_byte = val; return (temp); } public byte GetValuebyte() { return (value_byte); } public void SetValuebyte(byte val) { value_byte = val; } private char value_char; static public implicit operator char(BasicSelectionTestClass_int_i_e_tc_Conv test) { Log.Comment("To char"); return test.value_char; } static public implicit operator BasicSelectionTestClass_int_i_e_tc_Conv(char val) { Log.Comment("From char"); BasicSelectionTestClass_int_i_e_tc_Conv temp = new BasicSelectionTestClass_int_i_e_tc_Conv(); temp.value_char = val; return (temp); } public char GetValuechar() { return (value_char); } public void SetValuechar(char val) { value_char = val; } private double value_double; static public implicit operator double(BasicSelectionTestClass_int_i_e_tc_Conv test) { Log.Comment("To double"); return test.value_double; } static public implicit operator BasicSelectionTestClass_int_i_e_tc_Conv(double val) { Log.Comment("From double"); BasicSelectionTestClass_int_i_e_tc_Conv temp = new BasicSelectionTestClass_int_i_e_tc_Conv(); temp.value_double = val; return (temp); } public double GetValuedouble() { return (value_double); } public void SetValuedouble(double val) { value_double = val; } private float value_float; static public implicit operator float(BasicSelectionTestClass_int_i_e_tc_Conv test) { Log.Comment("To float"); return test.value_float; } static public implicit operator BasicSelectionTestClass_int_i_e_tc_Conv(float val) { Log.Comment("From float"); BasicSelectionTestClass_int_i_e_tc_Conv temp = new BasicSelectionTestClass_int_i_e_tc_Conv(); temp.value_float = val; return (temp); } public float GetValuefloat() { return (value_float); } public void SetValuefloat(float val) { value_float = val; } private int value_int; static public implicit operator int(BasicSelectionTestClass_int_i_e_tc_Conv test) { Log.Comment("To int"); return test.value_int; } static public implicit operator BasicSelectionTestClass_int_i_e_tc_Conv(int val) { Log.Comment("From int"); BasicSelectionTestClass_int_i_e_tc_Conv temp = new BasicSelectionTestClass_int_i_e_tc_Conv(); temp.value_int = val; return (temp); } public int GetValueint() { return (value_int); } public void SetValueint(int val) { value_int = val; } private long value_long; static public implicit operator long(BasicSelectionTestClass_int_i_e_tc_Conv test) { Log.Comment("To long"); return test.value_long; } static public implicit operator BasicSelectionTestClass_int_i_e_tc_Conv(long val) { Log.Comment("From long"); BasicSelectionTestClass_int_i_e_tc_Conv temp = new BasicSelectionTestClass_int_i_e_tc_Conv(); temp.value_long = val; return (temp); } public long GetValuelong() { return (value_long); } public void SetValuelong(long val) { value_long = val; } private sbyte value_sbyte; static public implicit operator sbyte(BasicSelectionTestClass_int_i_e_tc_Conv test) { Log.Comment("To sbyte"); return test.value_sbyte; } static public implicit operator BasicSelectionTestClass_int_i_e_tc_Conv(sbyte val) { Log.Comment("From sbyte"); BasicSelectionTestClass_int_i_e_tc_Conv temp = new BasicSelectionTestClass_int_i_e_tc_Conv(); temp.value_sbyte = val; return (temp); } public sbyte GetValuesbyte() { return (value_sbyte); } public void SetValuesbyte(sbyte val) { value_sbyte = val; } private short value_short; static public implicit operator short(BasicSelectionTestClass_int_i_e_tc_Conv test) { Log.Comment("To short"); return test.value_short; } static public implicit operator BasicSelectionTestClass_int_i_e_tc_Conv(short val) { Log.Comment("From short"); BasicSelectionTestClass_int_i_e_tc_Conv temp = new BasicSelectionTestClass_int_i_e_tc_Conv(); temp.value_short = val; return (temp); } public short GetValueshort() { return (value_short); } public void SetValueshort(short val) { value_short = val; } private uint value_uint; static public implicit operator uint(BasicSelectionTestClass_int_i_e_tc_Conv test) { Log.Comment("To uint"); return test.value_uint; } static public implicit operator BasicSelectionTestClass_int_i_e_tc_Conv(uint val) { Log.Comment("From uint"); BasicSelectionTestClass_int_i_e_tc_Conv temp = new BasicSelectionTestClass_int_i_e_tc_Conv(); temp.value_uint = val; return (temp); } public uint GetValueuint() { return (value_uint); } public void SetValueuint(uint val) { value_uint = val; } private ulong value_ulong; static public implicit operator ulong(BasicSelectionTestClass_int_i_e_tc_Conv test) { Log.Comment("To ulong"); return test.value_ulong; } static public implicit operator BasicSelectionTestClass_int_i_e_tc_Conv(ulong val) { Log.Comment("From ulong"); BasicSelectionTestClass_int_i_e_tc_Conv temp = new BasicSelectionTestClass_int_i_e_tc_Conv(); temp.value_ulong = val; return (temp); } public ulong GetValueulong() { return (value_ulong); } public void SetValueulong(ulong val) { value_ulong = val; } private ushort value_ushort; static public implicit operator ushort(BasicSelectionTestClass_int_i_e_tc_Conv test) { Log.Comment("To ushort"); return test.value_ushort; } static public implicit operator BasicSelectionTestClass_int_i_e_tc_Conv(ushort val) { Log.Comment("From ushort"); BasicSelectionTestClass_int_i_e_tc_Conv temp = new BasicSelectionTestClass_int_i_e_tc_Conv(); temp.value_ushort = val; return (temp); } public ushort GetValueushort() { return (value_ushort); } public void SetValueushort(ushort val) { value_ushort = val; } } class BasicSelectionTestClass_int_i_e_tc { public static int Main_old() { BasicSelectionTestClass_int_i_e_tc_Conv cl = new BasicSelectionTestClass_int_i_e_tc_Conv(); int val = 1; cl = (BasicSelectionTestClass_int_i_e_tc_Conv)val; if (cl.GetValueint() != 1) return 1; else return 0; } public static bool testMethod() { return (Main_old() == 0); } } class BasicSelectionTestClass_int_e_e_tc_Conv { private byte value_byte; static public explicit operator byte(BasicSelectionTestClass_int_e_e_tc_Conv test) { Log.Comment("To byte"); return test.value_byte; } static public explicit operator BasicSelectionTestClass_int_e_e_tc_Conv(byte val) { Log.Comment("From byte"); BasicSelectionTestClass_int_e_e_tc_Conv temp = new BasicSelectionTestClass_int_e_e_tc_Conv(); temp.value_byte = val; return (temp); } public byte GetValuebyte() { return (value_byte); } public void SetValuebyte(byte val) { value_byte = val; } private char value_char; static public explicit operator char(BasicSelectionTestClass_int_e_e_tc_Conv test) { Log.Comment("To char"); return test.value_char; } static public explicit operator BasicSelectionTestClass_int_e_e_tc_Conv(char val) { Log.Comment("From char"); BasicSelectionTestClass_int_e_e_tc_Conv temp = new BasicSelectionTestClass_int_e_e_tc_Conv(); temp.value_char = val; return (temp); } public char GetValuechar() { return (value_char); } public void SetValuechar(char val) { value_char = val; } private double value_double; static public explicit operator double(BasicSelectionTestClass_int_e_e_tc_Conv test) { Log.Comment("To double"); return test.value_double; } static public explicit operator BasicSelectionTestClass_int_e_e_tc_Conv(double val) { Log.Comment("From double"); BasicSelectionTestClass_int_e_e_tc_Conv temp = new BasicSelectionTestClass_int_e_e_tc_Conv(); temp.value_double = val; return (temp); } public double GetValuedouble() { return (value_double); } public void SetValuedouble(double val) { value_double = val; } private float value_float; static public explicit operator float(BasicSelectionTestClass_int_e_e_tc_Conv test) { Log.Comment("To float"); return test.value_float; } static public explicit operator BasicSelectionTestClass_int_e_e_tc_Conv(float val) { Log.Comment("From float"); BasicSelectionTestClass_int_e_e_tc_Conv temp = new BasicSelectionTestClass_int_e_e_tc_Conv(); temp.value_float = val; return (temp); } public float GetValuefloat() { return (value_float); } public void SetValuefloat(float val) { value_float = val; } private int value_int; static public explicit operator int(BasicSelectionTestClass_int_e_e_tc_Conv test) { Log.Comment("To int"); return test.value_int; } static public explicit operator BasicSelectionTestClass_int_e_e_tc_Conv(int val) { Log.Comment("From int"); BasicSelectionTestClass_int_e_e_tc_Conv temp = new BasicSelectionTestClass_int_e_e_tc_Conv(); temp.value_int = val; return (temp); } public int GetValueint() { return (value_int); } public void SetValueint(int val) { value_int = val; } private long value_long; static public explicit operator long(BasicSelectionTestClass_int_e_e_tc_Conv test) { Log.Comment("To long"); return test.value_long; } static public explicit operator BasicSelectionTestClass_int_e_e_tc_Conv(long val) { Log.Comment("From long"); BasicSelectionTestClass_int_e_e_tc_Conv temp = new BasicSelectionTestClass_int_e_e_tc_Conv(); temp.value_long = val; return (temp); } public long GetValuelong() { return (value_long); } public void SetValuelong(long val) { value_long = val; } private sbyte value_sbyte; static public explicit operator sbyte(BasicSelectionTestClass_int_e_e_tc_Conv test) { Log.Comment("To sbyte"); return test.value_sbyte; } static public explicit operator BasicSelectionTestClass_int_e_e_tc_Conv(sbyte val) { Log.Comment("From sbyte"); BasicSelectionTestClass_int_e_e_tc_Conv temp = new BasicSelectionTestClass_int_e_e_tc_Conv(); temp.value_sbyte = val; return (temp); } public sbyte GetValuesbyte() { return (value_sbyte); } public void SetValuesbyte(sbyte val) { value_sbyte = val; } private short value_short; static public explicit operator short(BasicSelectionTestClass_int_e_e_tc_Conv test) { Log.Comment("To short"); return test.value_short; } static public explicit operator BasicSelectionTestClass_int_e_e_tc_Conv(short val) { Log.Comment("From short"); BasicSelectionTestClass_int_e_e_tc_Conv temp = new BasicSelectionTestClass_int_e_e_tc_Conv(); temp.value_short = val; return (temp); } public short GetValueshort() { return (value_short); } public void SetValueshort(short val) { value_short = val; } private uint value_uint; static public explicit operator uint(BasicSelectionTestClass_int_e_e_tc_Conv test) { Log.Comment("To uint"); return test.value_uint; } static public explicit operator BasicSelectionTestClass_int_e_e_tc_Conv(uint val) { Log.Comment("From uint"); BasicSelectionTestClass_int_e_e_tc_Conv temp = new BasicSelectionTestClass_int_e_e_tc_Conv(); temp.value_uint = val; return (temp); } public uint GetValueuint() { return (value_uint); } public void SetValueuint(uint val) { value_uint = val; } private ulong value_ulong; static public explicit operator ulong(BasicSelectionTestClass_int_e_e_tc_Conv test) { Log.Comment("To ulong"); return test.value_ulong; } static public explicit operator BasicSelectionTestClass_int_e_e_tc_Conv(ulong val) { Log.Comment("From ulong"); BasicSelectionTestClass_int_e_e_tc_Conv temp = new BasicSelectionTestClass_int_e_e_tc_Conv(); temp.value_ulong = val; return (temp); } public ulong GetValueulong() { return (value_ulong); } public void SetValueulong(ulong val) { value_ulong = val; } private ushort value_ushort; static public explicit operator ushort(BasicSelectionTestClass_int_e_e_tc_Conv test) { Log.Comment("To ushort"); return test.value_ushort; } static public explicit operator BasicSelectionTestClass_int_e_e_tc_Conv(ushort val) { Log.Comment("From ushort"); BasicSelectionTestClass_int_e_e_tc_Conv temp = new BasicSelectionTestClass_int_e_e_tc_Conv(); temp.value_ushort = val; return (temp); } public ushort GetValueushort() { return (value_ushort); } public void SetValueushort(ushort val) { value_ushort = val; } } class BasicSelectionTestClass_int_e_e_tc { public static int Main_old() { BasicSelectionTestClass_int_e_e_tc_Conv cl = new BasicSelectionTestClass_int_e_e_tc_Conv(); int val = 1; cl = (BasicSelectionTestClass_int_e_e_tc_Conv)val; if (cl.GetValueint() != 1) return 1; else return 0; } public static bool testMethod() { return (Main_old() == 0); } } class BasicSelectionTestClass_int_i_i_fc_Conv { private byte value_byte; static public implicit operator byte(BasicSelectionTestClass_int_i_i_fc_Conv test) { Log.Comment("To byte"); return test.value_byte; } static public implicit operator BasicSelectionTestClass_int_i_i_fc_Conv(byte val) { Log.Comment("From byte"); BasicSelectionTestClass_int_i_i_fc_Conv temp = new BasicSelectionTestClass_int_i_i_fc_Conv(); temp.value_byte = val; return (temp); } public byte GetValuebyte() { return (value_byte); } public void SetValuebyte(byte val) { value_byte = val; } private char value_char; static public implicit operator char(BasicSelectionTestClass_int_i_i_fc_Conv test) { Log.Comment("To char"); return test.value_char; } static public implicit operator BasicSelectionTestClass_int_i_i_fc_Conv(char val) { Log.Comment("From char"); BasicSelectionTestClass_int_i_i_fc_Conv temp = new BasicSelectionTestClass_int_i_i_fc_Conv(); temp.value_char = val; return (temp); } public char GetValuechar() { return (value_char); } public void SetValuechar(char val) { value_char = val; } private double value_double; static public implicit operator double(BasicSelectionTestClass_int_i_i_fc_Conv test) { Log.Comment("To double"); return test.value_double; } static public implicit operator BasicSelectionTestClass_int_i_i_fc_Conv(double val) { Log.Comment("From double"); BasicSelectionTestClass_int_i_i_fc_Conv temp = new BasicSelectionTestClass_int_i_i_fc_Conv(); temp.value_double = val; return (temp); } public double GetValuedouble() { return (value_double); } public void SetValuedouble(double val) { value_double = val; } private float value_float; static public implicit operator float(BasicSelectionTestClass_int_i_i_fc_Conv test) { Log.Comment("To float"); return test.value_float; } static public implicit operator BasicSelectionTestClass_int_i_i_fc_Conv(float val) { Log.Comment("From float"); BasicSelectionTestClass_int_i_i_fc_Conv temp = new BasicSelectionTestClass_int_i_i_fc_Conv(); temp.value_float = val; return (temp); } public float GetValuefloat() { return (value_float); } public void SetValuefloat(float val) { value_float = val; } private int value_int; static public implicit operator int(BasicSelectionTestClass_int_i_i_fc_Conv test) { Log.Comment("To int"); return test.value_int; } static public implicit operator BasicSelectionTestClass_int_i_i_fc_Conv(int val) { Log.Comment("From int"); BasicSelectionTestClass_int_i_i_fc_Conv temp = new BasicSelectionTestClass_int_i_i_fc_Conv(); temp.value_int = val; return (temp); } public int GetValueint() { return (value_int); } public void SetValueint(int val) { value_int = val; } private long value_long; static public implicit operator long(BasicSelectionTestClass_int_i_i_fc_Conv test) { Log.Comment("To long"); return test.value_long; } static public implicit operator BasicSelectionTestClass_int_i_i_fc_Conv(long val) { Log.Comment("From long"); BasicSelectionTestClass_int_i_i_fc_Conv temp = new BasicSelectionTestClass_int_i_i_fc_Conv(); temp.value_long = val; return (temp); } public long GetValuelong() { return (value_long); } public void SetValuelong(long val) { value_long = val; } private sbyte value_sbyte; static public implicit operator sbyte(BasicSelectionTestClass_int_i_i_fc_Conv test) { Log.Comment("To sbyte"); return test.value_sbyte; } static public implicit operator BasicSelectionTestClass_int_i_i_fc_Conv(sbyte val) { Log.Comment("From sbyte"); BasicSelectionTestClass_int_i_i_fc_Conv temp = new BasicSelectionTestClass_int_i_i_fc_Conv(); temp.value_sbyte = val; return (temp); } public sbyte GetValuesbyte() { return (value_sbyte); } public void SetValuesbyte(sbyte val) { value_sbyte = val; } private short value_short; static public implicit operator short(BasicSelectionTestClass_int_i_i_fc_Conv test) { Log.Comment("To short"); return test.value_short; } static public implicit operator BasicSelectionTestClass_int_i_i_fc_Conv(short val) { Log.Comment("From short"); BasicSelectionTestClass_int_i_i_fc_Conv temp = new BasicSelectionTestClass_int_i_i_fc_Conv(); temp.value_short = val; return (temp); } public short GetValueshort() { return (value_short); } public void SetValueshort(short val) { value_short = val; } private uint value_uint; static public implicit operator uint(BasicSelectionTestClass_int_i_i_fc_Conv test) { Log.Comment("To uint"); return test.value_uint; } static public implicit operator BasicSelectionTestClass_int_i_i_fc_Conv(uint val) { Log.Comment("From uint"); BasicSelectionTestClass_int_i_i_fc_Conv temp = new BasicSelectionTestClass_int_i_i_fc_Conv(); temp.value_uint = val; return (temp); } public uint GetValueuint() { return (value_uint); } public void SetValueuint(uint val) { value_uint = val; } private ulong value_ulong; static public implicit operator ulong(BasicSelectionTestClass_int_i_i_fc_Conv test) { Log.Comment("To ulong"); return test.value_ulong; } static public implicit operator BasicSelectionTestClass_int_i_i_fc_Conv(ulong val) { Log.Comment("From ulong"); BasicSelectionTestClass_int_i_i_fc_Conv temp = new BasicSelectionTestClass_int_i_i_fc_Conv(); temp.value_ulong = val; return (temp); } public ulong GetValueulong() { return (value_ulong); } public void SetValueulong(ulong val) { value_ulong = val; } private ushort value_ushort; static public implicit operator ushort(BasicSelectionTestClass_int_i_i_fc_Conv test) { Log.Comment("To ushort"); return test.value_ushort; } static public implicit operator BasicSelectionTestClass_int_i_i_fc_Conv(ushort val) { Log.Comment("From ushort"); BasicSelectionTestClass_int_i_i_fc_Conv temp = new BasicSelectionTestClass_int_i_i_fc_Conv(); temp.value_ushort = val; return (temp); } public ushort GetValueushort() { return (value_ushort); } public void SetValueushort(ushort val) { value_ushort = val; } } class BasicSelectionTestClass_int_i_i_fc { public static int Main_old() { BasicSelectionTestClass_int_i_i_fc_Conv cl = new BasicSelectionTestClass_int_i_i_fc_Conv(); cl.SetValueint(1); int value = cl; if (value != 1) return 1; else return 0; } public static bool testMethod() { return (Main_old() == 0); } } class BasicSelectionTestClass_int_i_e_fc_Conv { private byte value_byte; static public implicit operator byte(BasicSelectionTestClass_int_i_e_fc_Conv test) { Log.Comment("To byte"); return test.value_byte; } static public implicit operator BasicSelectionTestClass_int_i_e_fc_Conv(byte val) { Log.Comment("From byte"); BasicSelectionTestClass_int_i_e_fc_Conv temp = new BasicSelectionTestClass_int_i_e_fc_Conv(); temp.value_byte = val; return (temp); } public byte GetValuebyte() { return (value_byte); } public void SetValuebyte(byte val) { value_byte = val; } private char value_char; static public implicit operator char(BasicSelectionTestClass_int_i_e_fc_Conv test) { Log.Comment("To char"); return test.value_char; } static public implicit operator BasicSelectionTestClass_int_i_e_fc_Conv(char val) { Log.Comment("From char"); BasicSelectionTestClass_int_i_e_fc_Conv temp = new BasicSelectionTestClass_int_i_e_fc_Conv(); temp.value_char = val; return (temp); } public char GetValuechar() { return (value_char); } public void SetValuechar(char val) { value_char = val; } private double value_double; static public implicit operator double(BasicSelectionTestClass_int_i_e_fc_Conv test) { Log.Comment("To double"); return test.value_double; } static public implicit operator BasicSelectionTestClass_int_i_e_fc_Conv(double val) { Log.Comment("From double"); BasicSelectionTestClass_int_i_e_fc_Conv temp = new BasicSelectionTestClass_int_i_e_fc_Conv(); temp.value_double = val; return (temp); } public double GetValuedouble() { return (value_double); } public void SetValuedouble(double val) { value_double = val; } private float value_float; static public implicit operator float(BasicSelectionTestClass_int_i_e_fc_Conv test) { Log.Comment("To float"); return test.value_float; } static public implicit operator BasicSelectionTestClass_int_i_e_fc_Conv(float val) { Log.Comment("From float"); BasicSelectionTestClass_int_i_e_fc_Conv temp = new BasicSelectionTestClass_int_i_e_fc_Conv(); temp.value_float = val; return (temp); } public float GetValuefloat() { return (value_float); } public void SetValuefloat(float val) { value_float = val; } private int value_int; static public implicit operator int(BasicSelectionTestClass_int_i_e_fc_Conv test) { Log.Comment("To int"); return test.value_int; } static public implicit operator BasicSelectionTestClass_int_i_e_fc_Conv(int val) { Log.Comment("From int"); BasicSelectionTestClass_int_i_e_fc_Conv temp = new BasicSelectionTestClass_int_i_e_fc_Conv(); temp.value_int = val; return (temp); } public int GetValueint() { return (value_int); } public void SetValueint(int val) { value_int = val; } private long value_long; static public implicit operator long(BasicSelectionTestClass_int_i_e_fc_Conv test) { Log.Comment("To long"); return test.value_long; } static public implicit operator BasicSelectionTestClass_int_i_e_fc_Conv(long val) { Log.Comment("From long"); BasicSelectionTestClass_int_i_e_fc_Conv temp = new BasicSelectionTestClass_int_i_e_fc_Conv(); temp.value_long = val; return (temp); } public long GetValuelong() { return (value_long); } public void SetValuelong(long val) { value_long = val; } private sbyte value_sbyte; static public implicit operator sbyte(BasicSelectionTestClass_int_i_e_fc_Conv test) { Log.Comment("To sbyte"); return test.value_sbyte; } static public implicit operator BasicSelectionTestClass_int_i_e_fc_Conv(sbyte val) { Log.Comment("From sbyte"); BasicSelectionTestClass_int_i_e_fc_Conv temp = new BasicSelectionTestClass_int_i_e_fc_Conv(); temp.value_sbyte = val; return (temp); } public sbyte GetValuesbyte() { return (value_sbyte); } public void SetValuesbyte(sbyte val) { value_sbyte = val; } private short value_short; static public implicit operator short(BasicSelectionTestClass_int_i_e_fc_Conv test) { Log.Comment("To short"); return test.value_short; } static public implicit operator BasicSelectionTestClass_int_i_e_fc_Conv(short val) { Log.Comment("From short"); BasicSelectionTestClass_int_i_e_fc_Conv temp = new BasicSelectionTestClass_int_i_e_fc_Conv(); temp.value_short = val; return (temp); } public short GetValueshort() { return (value_short); } public void SetValueshort(short val) { value_short = val; } private uint value_uint; static public implicit operator uint(BasicSelectionTestClass_int_i_e_fc_Conv test) { Log.Comment("To uint"); return test.value_uint; } static public implicit operator BasicSelectionTestClass_int_i_e_fc_Conv(uint val) { Log.Comment("From uint"); BasicSelectionTestClass_int_i_e_fc_Conv temp = new BasicSelectionTestClass_int_i_e_fc_Conv(); temp.value_uint = val; return (temp); } public uint GetValueuint() { return (value_uint); } public void SetValueuint(uint val) { value_uint = val; } private ulong value_ulong; static public implicit operator ulong(BasicSelectionTestClass_int_i_e_fc_Conv test) { Log.Comment("To ulong"); return test.value_ulong; } static public implicit operator BasicSelectionTestClass_int_i_e_fc_Conv(ulong val) { Log.Comment("From ulong"); BasicSelectionTestClass_int_i_e_fc_Conv temp = new BasicSelectionTestClass_int_i_e_fc_Conv(); temp.value_ulong = val; return (temp); } public ulong GetValueulong() { return (value_ulong); } public void SetValueulong(ulong val) { value_ulong = val; } private ushort value_ushort; static public implicit operator ushort(BasicSelectionTestClass_int_i_e_fc_Conv test) { Log.Comment("To ushort"); return test.value_ushort; } static public implicit operator BasicSelectionTestClass_int_i_e_fc_Conv(ushort val) { Log.Comment("From ushort"); BasicSelectionTestClass_int_i_e_fc_Conv temp = new BasicSelectionTestClass_int_i_e_fc_Conv(); temp.value_ushort = val; return (temp); } public ushort GetValueushort() { return (value_ushort); } public void SetValueushort(ushort val) { value_ushort = val; } } class BasicSelectionTestClass_int_i_e_fc { public static int Main_old() { BasicSelectionTestClass_int_i_e_fc_Conv cl = new BasicSelectionTestClass_int_i_e_fc_Conv(); cl.SetValueint(1); int value = (int)cl; if (value != 1) return 1; else return 0; } public static bool testMethod() { return (Main_old() == 0); } } class BasicSelectionTestClass_int_e_e_fc_Conv { private byte value_byte; static public explicit operator byte(BasicSelectionTestClass_int_e_e_fc_Conv test) { Log.Comment("To byte"); return test.value_byte; } static public explicit operator BasicSelectionTestClass_int_e_e_fc_Conv(byte val) { Log.Comment("From byte"); BasicSelectionTestClass_int_e_e_fc_Conv temp = new BasicSelectionTestClass_int_e_e_fc_Conv(); temp.value_byte = val; return (temp); } public byte GetValuebyte() { return (value_byte); } public void SetValuebyte(byte val) { value_byte = val; } private char value_char; static public explicit operator char(BasicSelectionTestClass_int_e_e_fc_Conv test) { Log.Comment("To char"); return test.value_char; } static public explicit operator BasicSelectionTestClass_int_e_e_fc_Conv(char val) { Log.Comment("From char"); BasicSelectionTestClass_int_e_e_fc_Conv temp = new BasicSelectionTestClass_int_e_e_fc_Conv(); temp.value_char = val; return (temp); } public char GetValuechar() { return (value_char); } public void SetValuechar(char val) { value_char = val; } private double value_double; static public explicit operator double(BasicSelectionTestClass_int_e_e_fc_Conv test) { Log.Comment("To double"); return test.value_double; } static public explicit operator BasicSelectionTestClass_int_e_e_fc_Conv(double val) { Log.Comment("From double"); BasicSelectionTestClass_int_e_e_fc_Conv temp = new BasicSelectionTestClass_int_e_e_fc_Conv(); temp.value_double = val; return (temp); } public double GetValuedouble() { return (value_double); } public void SetValuedouble(double val) { value_double = val; } private float value_float; static public explicit operator float(BasicSelectionTestClass_int_e_e_fc_Conv test) { Log.Comment("To float"); return test.value_float; } static public explicit operator BasicSelectionTestClass_int_e_e_fc_Conv(float val) { Log.Comment("From float"); BasicSelectionTestClass_int_e_e_fc_Conv temp = new BasicSelectionTestClass_int_e_e_fc_Conv(); temp.value_float = val; return (temp); } public float GetValuefloat() { return (value_float); } public void SetValuefloat(float val) { value_float = val; } private int value_int; static public explicit operator int(BasicSelectionTestClass_int_e_e_fc_Conv test) { Log.Comment("To int"); return test.value_int; } static public explicit operator BasicSelectionTestClass_int_e_e_fc_Conv(int val) { Log.Comment("From int"); BasicSelectionTestClass_int_e_e_fc_Conv temp = new BasicSelectionTestClass_int_e_e_fc_Conv(); temp.value_int = val; return (temp); } public int GetValueint() { return (value_int); } public void SetValueint(int val) { value_int = val; } private long value_long; static public explicit operator long(BasicSelectionTestClass_int_e_e_fc_Conv test) { Log.Comment("To long"); return test.value_long; } static public explicit operator BasicSelectionTestClass_int_e_e_fc_Conv(long val) { Log.Comment("From long"); BasicSelectionTestClass_int_e_e_fc_Conv temp = new BasicSelectionTestClass_int_e_e_fc_Conv(); temp.value_long = val; return (temp); } public long GetValuelong() { return (value_long); } public void SetValuelong(long val) { value_long = val; } private sbyte value_sbyte; static public explicit operator sbyte(BasicSelectionTestClass_int_e_e_fc_Conv test) { Log.Comment("To sbyte"); return test.value_sbyte; } static public explicit operator BasicSelectionTestClass_int_e_e_fc_Conv(sbyte val) { Log.Comment("From sbyte"); BasicSelectionTestClass_int_e_e_fc_Conv temp = new BasicSelectionTestClass_int_e_e_fc_Conv(); temp.value_sbyte = val; return (temp); } public sbyte GetValuesbyte() { return (value_sbyte); } public void SetValuesbyte(sbyte val) { value_sbyte = val; } private short value_short; static public explicit operator short(BasicSelectionTestClass_int_e_e_fc_Conv test) { Log.Comment("To short"); return test.value_short; } static public explicit operator BasicSelectionTestClass_int_e_e_fc_Conv(short val) { Log.Comment("From short"); BasicSelectionTestClass_int_e_e_fc_Conv temp = new BasicSelectionTestClass_int_e_e_fc_Conv(); temp.value_short = val; return (temp); } public short GetValueshort() { return (value_short); } public void SetValueshort(short val) { value_short = val; } private uint value_uint; static public explicit operator uint(BasicSelectionTestClass_int_e_e_fc_Conv test) { Log.Comment("To uint"); return test.value_uint; } static public explicit operator BasicSelectionTestClass_int_e_e_fc_Conv(uint val) { Log.Comment("From uint"); BasicSelectionTestClass_int_e_e_fc_Conv temp = new BasicSelectionTestClass_int_e_e_fc_Conv(); temp.value_uint = val; return (temp); } public uint GetValueuint() { return (value_uint); } public void SetValueuint(uint val) { value_uint = val; } private ulong value_ulong; static public explicit operator ulong(BasicSelectionTestClass_int_e_e_fc_Conv test) { Log.Comment("To ulong"); return test.value_ulong; } static public explicit operator BasicSelectionTestClass_int_e_e_fc_Conv(ulong val) { Log.Comment("From ulong"); BasicSelectionTestClass_int_e_e_fc_Conv temp = new BasicSelectionTestClass_int_e_e_fc_Conv(); temp.value_ulong = val; return (temp); } public ulong GetValueulong() { return (value_ulong); } public void SetValueulong(ulong val) { value_ulong = val; } private ushort value_ushort; static public explicit operator ushort(BasicSelectionTestClass_int_e_e_fc_Conv test) { Log.Comment("To ushort"); return test.value_ushort; } static public explicit operator BasicSelectionTestClass_int_e_e_fc_Conv(ushort val) { Log.Comment("From ushort"); BasicSelectionTestClass_int_e_e_fc_Conv temp = new BasicSelectionTestClass_int_e_e_fc_Conv(); temp.value_ushort = val; return (temp); } public ushort GetValueushort() { return (value_ushort); } public void SetValueushort(ushort val) { value_ushort = val; } } class BasicSelectionTestClass_int_e_e_fc { public static int Main_old() { BasicSelectionTestClass_int_e_e_fc_Conv cl = new BasicSelectionTestClass_int_e_e_fc_Conv(); cl.SetValueint(1); int value = (int)cl; if (value != 1) return 1; else return 0; } public static bool testMethod() { return (Main_old() == 0); } } class BasicSelectionTestClass_long_i_i_tc_Conv { private byte value_byte; static public implicit operator byte(BasicSelectionTestClass_long_i_i_tc_Conv test) { Log.Comment("To byte"); return test.value_byte; } static public implicit operator BasicSelectionTestClass_long_i_i_tc_Conv(byte val) { Log.Comment("From byte"); BasicSelectionTestClass_long_i_i_tc_Conv temp = new BasicSelectionTestClass_long_i_i_tc_Conv(); temp.value_byte = val; return (temp); } public byte GetValuebyte() { return (value_byte); } public void SetValuebyte(byte val) { value_byte = val; } private char value_char; static public implicit operator char(BasicSelectionTestClass_long_i_i_tc_Conv test) { Log.Comment("To char"); return test.value_char; } static public implicit operator BasicSelectionTestClass_long_i_i_tc_Conv(char val) { Log.Comment("From char"); BasicSelectionTestClass_long_i_i_tc_Conv temp = new BasicSelectionTestClass_long_i_i_tc_Conv(); temp.value_char = val; return (temp); } public char GetValuechar() { return (value_char); } public void SetValuechar(char val) { value_char = val; } private double value_double; static public implicit operator double(BasicSelectionTestClass_long_i_i_tc_Conv test) { Log.Comment("To double"); return test.value_double; } static public implicit operator BasicSelectionTestClass_long_i_i_tc_Conv(double val) { Log.Comment("From double"); BasicSelectionTestClass_long_i_i_tc_Conv temp = new BasicSelectionTestClass_long_i_i_tc_Conv(); temp.value_double = val; return (temp); } public double GetValuedouble() { return (value_double); } public void SetValuedouble(double val) { value_double = val; } private float value_float; static public implicit operator float(BasicSelectionTestClass_long_i_i_tc_Conv test) { Log.Comment("To float"); return test.value_float; } static public implicit operator BasicSelectionTestClass_long_i_i_tc_Conv(float val) { Log.Comment("From float"); BasicSelectionTestClass_long_i_i_tc_Conv temp = new BasicSelectionTestClass_long_i_i_tc_Conv(); temp.value_float = val; return (temp); } public float GetValuefloat() { return (value_float); } public void SetValuefloat(float val) { value_float = val; } private int value_int; static public implicit operator int(BasicSelectionTestClass_long_i_i_tc_Conv test) { Log.Comment("To int"); return test.value_int; } static public implicit operator BasicSelectionTestClass_long_i_i_tc_Conv(int val) { Log.Comment("From int"); BasicSelectionTestClass_long_i_i_tc_Conv temp = new BasicSelectionTestClass_long_i_i_tc_Conv(); temp.value_int = val; return (temp); } public int GetValueint() { return (value_int); } public void SetValueint(int val) { value_int = val; } private long value_long; static public implicit operator long(BasicSelectionTestClass_long_i_i_tc_Conv test) { Log.Comment("To long"); return test.value_long; } static public implicit operator BasicSelectionTestClass_long_i_i_tc_Conv(long val) { Log.Comment("From long"); BasicSelectionTestClass_long_i_i_tc_Conv temp = new BasicSelectionTestClass_long_i_i_tc_Conv(); temp.value_long = val; return (temp); } public long GetValuelong() { return (value_long); } public void SetValuelong(long val) { value_long = val; } private sbyte value_sbyte; static public implicit operator sbyte(BasicSelectionTestClass_long_i_i_tc_Conv test) { Log.Comment("To sbyte"); return test.value_sbyte; } static public implicit operator BasicSelectionTestClass_long_i_i_tc_Conv(sbyte val) { Log.Comment("From sbyte"); BasicSelectionTestClass_long_i_i_tc_Conv temp = new BasicSelectionTestClass_long_i_i_tc_Conv(); temp.value_sbyte = val; return (temp); } public sbyte GetValuesbyte() { return (value_sbyte); } public void SetValuesbyte(sbyte val) { value_sbyte = val; } private short value_short; static public implicit operator short(BasicSelectionTestClass_long_i_i_tc_Conv test) { Log.Comment("To short"); return test.value_short; } static public implicit operator BasicSelectionTestClass_long_i_i_tc_Conv(short val) { Log.Comment("From short"); BasicSelectionTestClass_long_i_i_tc_Conv temp = new BasicSelectionTestClass_long_i_i_tc_Conv(); temp.value_short = val; return (temp); } public short GetValueshort() { return (value_short); } public void SetValueshort(short val) { value_short = val; } private uint value_uint; static public implicit operator uint(BasicSelectionTestClass_long_i_i_tc_Conv test) { Log.Comment("To uint"); return test.value_uint; } static public implicit operator BasicSelectionTestClass_long_i_i_tc_Conv(uint val) { Log.Comment("From uint"); BasicSelectionTestClass_long_i_i_tc_Conv temp = new BasicSelectionTestClass_long_i_i_tc_Conv(); temp.value_uint = val; return (temp); } public uint GetValueuint() { return (value_uint); } public void SetValueuint(uint val) { value_uint = val; } private ulong value_ulong; static public implicit operator ulong(BasicSelectionTestClass_long_i_i_tc_Conv test) { Log.Comment("To ulong"); return test.value_ulong; } static public implicit operator BasicSelectionTestClass_long_i_i_tc_Conv(ulong val) { Log.Comment("From ulong"); BasicSelectionTestClass_long_i_i_tc_Conv temp = new BasicSelectionTestClass_long_i_i_tc_Conv(); temp.value_ulong = val; return (temp); } public ulong GetValueulong() { return (value_ulong); } public void SetValueulong(ulong val) { value_ulong = val; } private ushort value_ushort; static public implicit operator ushort(BasicSelectionTestClass_long_i_i_tc_Conv test) { Log.Comment("To ushort"); return test.value_ushort; } static public implicit operator BasicSelectionTestClass_long_i_i_tc_Conv(ushort val) { Log.Comment("From ushort"); BasicSelectionTestClass_long_i_i_tc_Conv temp = new BasicSelectionTestClass_long_i_i_tc_Conv(); temp.value_ushort = val; return (temp); } public ushort GetValueushort() { return (value_ushort); } public void SetValueushort(ushort val) { value_ushort = val; } } class BasicSelectionTestClass_long_i_i_tc { public static int Main_old() { BasicSelectionTestClass_long_i_i_tc_Conv cl = new BasicSelectionTestClass_long_i_i_tc_Conv(); long val = 1; cl = val; if (cl.GetValuelong() != 1) return 1; else return 0; } public static bool testMethod() { return (Main_old() == 0); } } class BasicSelectionTestClass_long_i_e_tc_Conv { private byte value_byte; static public implicit operator byte(BasicSelectionTestClass_long_i_e_tc_Conv test) { Log.Comment("To byte"); return test.value_byte; } static public implicit operator BasicSelectionTestClass_long_i_e_tc_Conv(byte val) { Log.Comment("From byte"); BasicSelectionTestClass_long_i_e_tc_Conv temp = new BasicSelectionTestClass_long_i_e_tc_Conv(); temp.value_byte = val; return (temp); } public byte GetValuebyte() { return (value_byte); } public void SetValuebyte(byte val) { value_byte = val; } private char value_char; static public implicit operator char(BasicSelectionTestClass_long_i_e_tc_Conv test) { Log.Comment("To char"); return test.value_char; } static public implicit operator BasicSelectionTestClass_long_i_e_tc_Conv(char val) { Log.Comment("From char"); BasicSelectionTestClass_long_i_e_tc_Conv temp = new BasicSelectionTestClass_long_i_e_tc_Conv(); temp.value_char = val; return (temp); } public char GetValuechar() { return (value_char); } public void SetValuechar(char val) { value_char = val; } private double value_double; static public implicit operator double(BasicSelectionTestClass_long_i_e_tc_Conv test) { Log.Comment("To double"); return test.value_double; } static public implicit operator BasicSelectionTestClass_long_i_e_tc_Conv(double val) { Log.Comment("From double"); BasicSelectionTestClass_long_i_e_tc_Conv temp = new BasicSelectionTestClass_long_i_e_tc_Conv(); temp.value_double = val; return (temp); } public double GetValuedouble() { return (value_double); } public void SetValuedouble(double val) { value_double = val; } private float value_float; static public implicit operator float(BasicSelectionTestClass_long_i_e_tc_Conv test) { Log.Comment("To float"); return test.value_float; } static public implicit operator BasicSelectionTestClass_long_i_e_tc_Conv(float val) { Log.Comment("From float"); BasicSelectionTestClass_long_i_e_tc_Conv temp = new BasicSelectionTestClass_long_i_e_tc_Conv(); temp.value_float = val; return (temp); } public float GetValuefloat() { return (value_float); } public void SetValuefloat(float val) { value_float = val; } private int value_int; static public implicit operator int(BasicSelectionTestClass_long_i_e_tc_Conv test) { Log.Comment("To int"); return test.value_int; } static public implicit operator BasicSelectionTestClass_long_i_e_tc_Conv(int val) { Log.Comment("From int"); BasicSelectionTestClass_long_i_e_tc_Conv temp = new BasicSelectionTestClass_long_i_e_tc_Conv(); temp.value_int = val; return (temp); } public int GetValueint() { return (value_int); } public void SetValueint(int val) { value_int = val; } private long value_long; static public implicit operator long(BasicSelectionTestClass_long_i_e_tc_Conv test) { Log.Comment("To long"); return test.value_long; } static public implicit operator BasicSelectionTestClass_long_i_e_tc_Conv(long val) { Log.Comment("From long"); BasicSelectionTestClass_long_i_e_tc_Conv temp = new BasicSelectionTestClass_long_i_e_tc_Conv(); temp.value_long = val; return (temp); } public long GetValuelong() { return (value_long); } public void SetValuelong(long val) { value_long = val; } private sbyte value_sbyte; static public implicit operator sbyte(BasicSelectionTestClass_long_i_e_tc_Conv test) { Log.Comment("To sbyte"); return test.value_sbyte; } static public implicit operator BasicSelectionTestClass_long_i_e_tc_Conv(sbyte val) { Log.Comment("From sbyte"); BasicSelectionTestClass_long_i_e_tc_Conv temp = new BasicSelectionTestClass_long_i_e_tc_Conv(); temp.value_sbyte = val; return (temp); } public sbyte GetValuesbyte() { return (value_sbyte); } public void SetValuesbyte(sbyte val) { value_sbyte = val; } private short value_short; static public implicit operator short(BasicSelectionTestClass_long_i_e_tc_Conv test) { Log.Comment("To short"); return test.value_short; } static public implicit operator BasicSelectionTestClass_long_i_e_tc_Conv(short val) { Log.Comment("From short"); BasicSelectionTestClass_long_i_e_tc_Conv temp = new BasicSelectionTestClass_long_i_e_tc_Conv(); temp.value_short = val; return (temp); } public short GetValueshort() { return (value_short); } public void SetValueshort(short val) { value_short = val; } private uint value_uint; static public implicit operator uint(BasicSelectionTestClass_long_i_e_tc_Conv test) { Log.Comment("To uint"); return test.value_uint; } static public implicit operator BasicSelectionTestClass_long_i_e_tc_Conv(uint val) { Log.Comment("From uint"); BasicSelectionTestClass_long_i_e_tc_Conv temp = new BasicSelectionTestClass_long_i_e_tc_Conv(); temp.value_uint = val; return (temp); } public uint GetValueuint() { return (value_uint); } public void SetValueuint(uint val) { value_uint = val; } private ulong value_ulong; static public implicit operator ulong(BasicSelectionTestClass_long_i_e_tc_Conv test) { Log.Comment("To ulong"); return test.value_ulong; } static public implicit operator BasicSelectionTestClass_long_i_e_tc_Conv(ulong val) { Log.Comment("From ulong"); BasicSelectionTestClass_long_i_e_tc_Conv temp = new BasicSelectionTestClass_long_i_e_tc_Conv(); temp.value_ulong = val; return (temp); } public ulong GetValueulong() { return (value_ulong); } public void SetValueulong(ulong val) { value_ulong = val; } private ushort value_ushort; static public implicit operator ushort(BasicSelectionTestClass_long_i_e_tc_Conv test) { Log.Comment("To ushort"); return test.value_ushort; } static public implicit operator BasicSelectionTestClass_long_i_e_tc_Conv(ushort val) { Log.Comment("From ushort"); BasicSelectionTestClass_long_i_e_tc_Conv temp = new BasicSelectionTestClass_long_i_e_tc_Conv(); temp.value_ushort = val; return (temp); } public ushort GetValueushort() { return (value_ushort); } public void SetValueushort(ushort val) { value_ushort = val; } } class BasicSelectionTestClass_long_i_e_tc { public static int Main_old() { BasicSelectionTestClass_long_i_e_tc_Conv cl = new BasicSelectionTestClass_long_i_e_tc_Conv(); long val = 1; cl = (BasicSelectionTestClass_long_i_e_tc_Conv)val; if (cl.GetValuelong() != 1) return 1; else return 0; } public static bool testMethod() { return (Main_old() == 0); } } class BasicSelectionTestClass_long_e_e_tc_Conv { private byte value_byte; static public explicit operator byte(BasicSelectionTestClass_long_e_e_tc_Conv test) { Log.Comment("To byte"); return test.value_byte; } static public explicit operator BasicSelectionTestClass_long_e_e_tc_Conv(byte val) { Log.Comment("From byte"); BasicSelectionTestClass_long_e_e_tc_Conv temp = new BasicSelectionTestClass_long_e_e_tc_Conv(); temp.value_byte = val; return (temp); } public byte GetValuebyte() { return (value_byte); } public void SetValuebyte(byte val) { value_byte = val; } private char value_char; static public explicit operator char(BasicSelectionTestClass_long_e_e_tc_Conv test) { Log.Comment("To char"); return test.value_char; } static public explicit operator BasicSelectionTestClass_long_e_e_tc_Conv(char val) { Log.Comment("From char"); BasicSelectionTestClass_long_e_e_tc_Conv temp = new BasicSelectionTestClass_long_e_e_tc_Conv(); temp.value_char = val; return (temp); } public char GetValuechar() { return (value_char); } public void SetValuechar(char val) { value_char = val; } private double value_double; static public explicit operator double(BasicSelectionTestClass_long_e_e_tc_Conv test) { Log.Comment("To double"); return test.value_double; } static public explicit operator BasicSelectionTestClass_long_e_e_tc_Conv(double val) { Log.Comment("From double"); BasicSelectionTestClass_long_e_e_tc_Conv temp = new BasicSelectionTestClass_long_e_e_tc_Conv(); temp.value_double = val; return (temp); } public double GetValuedouble() { return (value_double); } public void SetValuedouble(double val) { value_double = val; } private float value_float; static public explicit operator float(BasicSelectionTestClass_long_e_e_tc_Conv test) { Log.Comment("To float"); return test.value_float; } static public explicit operator BasicSelectionTestClass_long_e_e_tc_Conv(float val) { Log.Comment("From float"); BasicSelectionTestClass_long_e_e_tc_Conv temp = new BasicSelectionTestClass_long_e_e_tc_Conv(); temp.value_float = val; return (temp); } public float GetValuefloat() { return (value_float); } public void SetValuefloat(float val) { value_float = val; } private int value_int; static public explicit operator int(BasicSelectionTestClass_long_e_e_tc_Conv test) { Log.Comment("To int"); return test.value_int; } static public explicit operator BasicSelectionTestClass_long_e_e_tc_Conv(int val) { Log.Comment("From int"); BasicSelectionTestClass_long_e_e_tc_Conv temp = new BasicSelectionTestClass_long_e_e_tc_Conv(); temp.value_int = val; return (temp); } public int GetValueint() { return (value_int); } public void SetValueint(int val) { value_int = val; } private long value_long; static public explicit operator long(BasicSelectionTestClass_long_e_e_tc_Conv test) { Log.Comment("To long"); return test.value_long; } static public explicit operator BasicSelectionTestClass_long_e_e_tc_Conv(long val) { Log.Comment("From long"); BasicSelectionTestClass_long_e_e_tc_Conv temp = new BasicSelectionTestClass_long_e_e_tc_Conv(); temp.value_long = val; return (temp); } public long GetValuelong() { return (value_long); } public void SetValuelong(long val) { value_long = val; } private sbyte value_sbyte; static public explicit operator sbyte(BasicSelectionTestClass_long_e_e_tc_Conv test) { Log.Comment("To sbyte"); return test.value_sbyte; } static public explicit operator BasicSelectionTestClass_long_e_e_tc_Conv(sbyte val) { Log.Comment("From sbyte"); BasicSelectionTestClass_long_e_e_tc_Conv temp = new BasicSelectionTestClass_long_e_e_tc_Conv(); temp.value_sbyte = val; return (temp); } public sbyte GetValuesbyte() { return (value_sbyte); } public void SetValuesbyte(sbyte val) { value_sbyte = val; } private short value_short; static public explicit operator short(BasicSelectionTestClass_long_e_e_tc_Conv test) { Log.Comment("To short"); return test.value_short; } static public explicit operator BasicSelectionTestClass_long_e_e_tc_Conv(short val) { Log.Comment("From short"); BasicSelectionTestClass_long_e_e_tc_Conv temp = new BasicSelectionTestClass_long_e_e_tc_Conv(); temp.value_short = val; return (temp); } public short GetValueshort() { return (value_short); } public void SetValueshort(short val) { value_short = val; } private uint value_uint; static public explicit operator uint(BasicSelectionTestClass_long_e_e_tc_Conv test) { Log.Comment("To uint"); return test.value_uint; } static public explicit operator BasicSelectionTestClass_long_e_e_tc_Conv(uint val) { Log.Comment("From uint"); BasicSelectionTestClass_long_e_e_tc_Conv temp = new BasicSelectionTestClass_long_e_e_tc_Conv(); temp.value_uint = val; return (temp); } public uint GetValueuint() { return (value_uint); } public void SetValueuint(uint val) { value_uint = val; } private ulong value_ulong; static public explicit operator ulong(BasicSelectionTestClass_long_e_e_tc_Conv test) { Log.Comment("To ulong"); return test.value_ulong; } static public explicit operator BasicSelectionTestClass_long_e_e_tc_Conv(ulong val) { Log.Comment("From ulong"); BasicSelectionTestClass_long_e_e_tc_Conv temp = new BasicSelectionTestClass_long_e_e_tc_Conv(); temp.value_ulong = val; return (temp); } public ulong GetValueulong() { return (value_ulong); } public void SetValueulong(ulong val) { value_ulong = val; } private ushort value_ushort; static public explicit operator ushort(BasicSelectionTestClass_long_e_e_tc_Conv test) { Log.Comment("To ushort"); return test.value_ushort; } static public explicit operator BasicSelectionTestClass_long_e_e_tc_Conv(ushort val) { Log.Comment("From ushort"); BasicSelectionTestClass_long_e_e_tc_Conv temp = new BasicSelectionTestClass_long_e_e_tc_Conv(); temp.value_ushort = val; return (temp); } public ushort GetValueushort() { return (value_ushort); } public void SetValueushort(ushort val) { value_ushort = val; } } class BasicSelectionTestClass_long_e_e_tc { public static int Main_old() { BasicSelectionTestClass_long_e_e_tc_Conv cl = new BasicSelectionTestClass_long_e_e_tc_Conv(); long val = 1; cl = (BasicSelectionTestClass_long_e_e_tc_Conv)val; if (cl.GetValuelong() != 1) return 1; else return 0; } public static bool testMethod() { return (Main_old() == 0); } } class BasicSelectionTestClass_sbyte_i_e_tc_Conv { private byte value_byte; static public implicit operator byte(BasicSelectionTestClass_sbyte_i_e_tc_Conv test) { Log.Comment("To byte"); return test.value_byte; } static public implicit operator BasicSelectionTestClass_sbyte_i_e_tc_Conv(byte val) { Log.Comment("From byte"); BasicSelectionTestClass_sbyte_i_e_tc_Conv temp = new BasicSelectionTestClass_sbyte_i_e_tc_Conv(); temp.value_byte = val; return (temp); } public byte GetValuebyte() { return (value_byte); } public void SetValuebyte(byte val) { value_byte = val; } private char value_char; static public implicit operator char(BasicSelectionTestClass_sbyte_i_e_tc_Conv test) { Log.Comment("To char"); return test.value_char; } static public implicit operator BasicSelectionTestClass_sbyte_i_e_tc_Conv(char val) { Log.Comment("From char"); BasicSelectionTestClass_sbyte_i_e_tc_Conv temp = new BasicSelectionTestClass_sbyte_i_e_tc_Conv(); temp.value_char = val; return (temp); } public char GetValuechar() { return (value_char); } public void SetValuechar(char val) { value_char = val; } private double value_double; static public implicit operator double(BasicSelectionTestClass_sbyte_i_e_tc_Conv test) { Log.Comment("To double"); return test.value_double; } static public implicit operator BasicSelectionTestClass_sbyte_i_e_tc_Conv(double val) { Log.Comment("From double"); BasicSelectionTestClass_sbyte_i_e_tc_Conv temp = new BasicSelectionTestClass_sbyte_i_e_tc_Conv(); temp.value_double = val; return (temp); } public double GetValuedouble() { return (value_double); } public void SetValuedouble(double val) { value_double = val; } private float value_float; static public implicit operator float(BasicSelectionTestClass_sbyte_i_e_tc_Conv test) { Log.Comment("To float"); return test.value_float; } static public implicit operator BasicSelectionTestClass_sbyte_i_e_tc_Conv(float val) { Log.Comment("From float"); BasicSelectionTestClass_sbyte_i_e_tc_Conv temp = new BasicSelectionTestClass_sbyte_i_e_tc_Conv(); temp.value_float = val; return (temp); } public float GetValuefloat() { return (value_float); } public void SetValuefloat(float val) { value_float = val; } private int value_int; static public implicit operator int(BasicSelectionTestClass_sbyte_i_e_tc_Conv test) { Log.Comment("To int"); return test.value_int; } static public implicit operator BasicSelectionTestClass_sbyte_i_e_tc_Conv(int val) { Log.Comment("From int"); BasicSelectionTestClass_sbyte_i_e_tc_Conv temp = new BasicSelectionTestClass_sbyte_i_e_tc_Conv(); temp.value_int = val; return (temp); } public int GetValueint() { return (value_int); } public void SetValueint(int val) { value_int = val; } private long value_long; static public implicit operator long(BasicSelectionTestClass_sbyte_i_e_tc_Conv test) { Log.Comment("To long"); return test.value_long; } static public implicit operator BasicSelectionTestClass_sbyte_i_e_tc_Conv(long val) { Log.Comment("From long"); BasicSelectionTestClass_sbyte_i_e_tc_Conv temp = new BasicSelectionTestClass_sbyte_i_e_tc_Conv(); temp.value_long = val; return (temp); } public long GetValuelong() { return (value_long); } public void SetValuelong(long val) { value_long = val; } private sbyte value_sbyte; static public implicit operator sbyte(BasicSelectionTestClass_sbyte_i_e_tc_Conv test) { Log.Comment("To sbyte"); return test.value_sbyte; } static public implicit operator BasicSelectionTestClass_sbyte_i_e_tc_Conv(sbyte val) { Log.Comment("From sbyte"); BasicSelectionTestClass_sbyte_i_e_tc_Conv temp = new BasicSelectionTestClass_sbyte_i_e_tc_Conv(); temp.value_sbyte = val; return (temp); } public sbyte GetValuesbyte() { return (value_sbyte); } public void SetValuesbyte(sbyte val) { value_sbyte = val; } private short value_short; static public implicit operator short(BasicSelectionTestClass_sbyte_i_e_tc_Conv test) { Log.Comment("To short"); return test.value_short; } static public implicit operator BasicSelectionTestClass_sbyte_i_e_tc_Conv(short val) { Log.Comment("From short"); BasicSelectionTestClass_sbyte_i_e_tc_Conv temp = new BasicSelectionTestClass_sbyte_i_e_tc_Conv(); temp.value_short = val; return (temp); } public short GetValueshort() { return (value_short); } public void SetValueshort(short val) { value_short = val; } private uint value_uint; static public implicit operator uint(BasicSelectionTestClass_sbyte_i_e_tc_Conv test) { Log.Comment("To uint"); return test.value_uint; } static public implicit operator BasicSelectionTestClass_sbyte_i_e_tc_Conv(uint val) { Log.Comment("From uint"); BasicSelectionTestClass_sbyte_i_e_tc_Conv temp = new BasicSelectionTestClass_sbyte_i_e_tc_Conv(); temp.value_uint = val; return (temp); } public uint GetValueuint() { return (value_uint); } public void SetValueuint(uint val) { value_uint = val; } private ulong value_ulong; static public implicit operator ulong(BasicSelectionTestClass_sbyte_i_e_tc_Conv test) { Log.Comment("To ulong"); return test.value_ulong; } static public implicit operator BasicSelectionTestClass_sbyte_i_e_tc_Conv(ulong val) { Log.Comment("From ulong"); BasicSelectionTestClass_sbyte_i_e_tc_Conv temp = new BasicSelectionTestClass_sbyte_i_e_tc_Conv(); temp.value_ulong = val; return (temp); } public ulong GetValueulong() { return (value_ulong); } public void SetValueulong(ulong val) { value_ulong = val; } private ushort value_ushort; static public implicit operator ushort(BasicSelectionTestClass_sbyte_i_e_tc_Conv test) { Log.Comment("To ushort"); return test.value_ushort; } static public implicit operator BasicSelectionTestClass_sbyte_i_e_tc_Conv(ushort val) { Log.Comment("From ushort"); BasicSelectionTestClass_sbyte_i_e_tc_Conv temp = new BasicSelectionTestClass_sbyte_i_e_tc_Conv(); temp.value_ushort = val; return (temp); } public ushort GetValueushort() { return (value_ushort); } public void SetValueushort(ushort val) { value_ushort = val; } } class BasicSelectionTestClass_sbyte_i_e_tc { public static int Main_old() { BasicSelectionTestClass_sbyte_i_e_tc_Conv cl = new BasicSelectionTestClass_sbyte_i_e_tc_Conv(); sbyte val = 1; cl = (BasicSelectionTestClass_sbyte_i_e_tc_Conv)val; if (cl.GetValuesbyte() != 1) return 1; else return 0; } public static bool testMethod() { return (Main_old() == 0); } } class BasicSelectionTestClass_sbyte_e_e_tc_Conv { private byte value_byte; static public explicit operator byte(BasicSelectionTestClass_sbyte_e_e_tc_Conv test) { Log.Comment("To byte"); return test.value_byte; } static public explicit operator BasicSelectionTestClass_sbyte_e_e_tc_Conv(byte val) { Log.Comment("From byte"); BasicSelectionTestClass_sbyte_e_e_tc_Conv temp = new BasicSelectionTestClass_sbyte_e_e_tc_Conv(); temp.value_byte = val; return (temp); } public byte GetValuebyte() { return (value_byte); } public void SetValuebyte(byte val) { value_byte = val; } private char value_char; static public explicit operator char(BasicSelectionTestClass_sbyte_e_e_tc_Conv test) { Log.Comment("To char"); return test.value_char; } static public explicit operator BasicSelectionTestClass_sbyte_e_e_tc_Conv(char val) { Log.Comment("From char"); BasicSelectionTestClass_sbyte_e_e_tc_Conv temp = new BasicSelectionTestClass_sbyte_e_e_tc_Conv(); temp.value_char = val; return (temp); } public char GetValuechar() { return (value_char); } public void SetValuechar(char val) { value_char = val; } private double value_double; static public explicit operator double(BasicSelectionTestClass_sbyte_e_e_tc_Conv test) { Log.Comment("To double"); return test.value_double; } static public explicit operator BasicSelectionTestClass_sbyte_e_e_tc_Conv(double val) { Log.Comment("From double"); BasicSelectionTestClass_sbyte_e_e_tc_Conv temp = new BasicSelectionTestClass_sbyte_e_e_tc_Conv(); temp.value_double = val; return (temp); } public double GetValuedouble() { return (value_double); } public void SetValuedouble(double val) { value_double = val; } private float value_float; static public explicit operator float(BasicSelectionTestClass_sbyte_e_e_tc_Conv test) { Log.Comment("To float"); return test.value_float; } static public explicit operator BasicSelectionTestClass_sbyte_e_e_tc_Conv(float val) { Log.Comment("From float"); BasicSelectionTestClass_sbyte_e_e_tc_Conv temp = new BasicSelectionTestClass_sbyte_e_e_tc_Conv(); temp.value_float = val; return (temp); } public float GetValuefloat() { return (value_float); } public void SetValuefloat(float val) { value_float = val; } private int value_int; static public explicit operator int(BasicSelectionTestClass_sbyte_e_e_tc_Conv test) { Log.Comment("To int"); return test.value_int; } static public explicit operator BasicSelectionTestClass_sbyte_e_e_tc_Conv(int val) { Log.Comment("From int"); BasicSelectionTestClass_sbyte_e_e_tc_Conv temp = new BasicSelectionTestClass_sbyte_e_e_tc_Conv(); temp.value_int = val; return (temp); } public int GetValueint() { return (value_int); } public void SetValueint(int val) { value_int = val; } private long value_long; static public explicit operator long(BasicSelectionTestClass_sbyte_e_e_tc_Conv test) { Log.Comment("To long"); return test.value_long; } static public explicit operator BasicSelectionTestClass_sbyte_e_e_tc_Conv(long val) { Log.Comment("From long"); BasicSelectionTestClass_sbyte_e_e_tc_Conv temp = new BasicSelectionTestClass_sbyte_e_e_tc_Conv(); temp.value_long = val; return (temp); } public long GetValuelong() { return (value_long); } public void SetValuelong(long val) { value_long = val; } private sbyte value_sbyte; static public explicit operator sbyte(BasicSelectionTestClass_sbyte_e_e_tc_Conv test) { Log.Comment("To sbyte"); return test.value_sbyte; } static public explicit operator BasicSelectionTestClass_sbyte_e_e_tc_Conv(sbyte val) { Log.Comment("From sbyte"); BasicSelectionTestClass_sbyte_e_e_tc_Conv temp = new BasicSelectionTestClass_sbyte_e_e_tc_Conv(); temp.value_sbyte = val; return (temp); } public sbyte GetValuesbyte() { return (value_sbyte); } public void SetValuesbyte(sbyte val) { value_sbyte = val; } private short value_short; static public explicit operator short(BasicSelectionTestClass_sbyte_e_e_tc_Conv test) { Log.Comment("To short"); return test.value_short; } static public explicit operator BasicSelectionTestClass_sbyte_e_e_tc_Conv(short val) { Log.Comment("From short"); BasicSelectionTestClass_sbyte_e_e_tc_Conv temp = new BasicSelectionTestClass_sbyte_e_e_tc_Conv(); temp.value_short = val; return (temp); } public short GetValueshort() { return (value_short); } public void SetValueshort(short val) { value_short = val; } private uint value_uint; static public explicit operator uint(BasicSelectionTestClass_sbyte_e_e_tc_Conv test) { Log.Comment("To uint"); return test.value_uint; } static public explicit operator BasicSelectionTestClass_sbyte_e_e_tc_Conv(uint val) { Log.Comment("From uint"); BasicSelectionTestClass_sbyte_e_e_tc_Conv temp = new BasicSelectionTestClass_sbyte_e_e_tc_Conv(); temp.value_uint = val; return (temp); } public uint GetValueuint() { return (value_uint); } public void SetValueuint(uint val) { value_uint = val; } private ulong value_ulong; static public explicit operator ulong(BasicSelectionTestClass_sbyte_e_e_tc_Conv test) { Log.Comment("To ulong"); return test.value_ulong; } static public explicit operator BasicSelectionTestClass_sbyte_e_e_tc_Conv(ulong val) { Log.Comment("From ulong"); BasicSelectionTestClass_sbyte_e_e_tc_Conv temp = new BasicSelectionTestClass_sbyte_e_e_tc_Conv(); temp.value_ulong = val; return (temp); } public ulong GetValueulong() { return (value_ulong); } public void SetValueulong(ulong val) { value_ulong = val; } private ushort value_ushort; static public explicit operator ushort(BasicSelectionTestClass_sbyte_e_e_tc_Conv test) { Log.Comment("To ushort"); return test.value_ushort; } static public explicit operator BasicSelectionTestClass_sbyte_e_e_tc_Conv(ushort val) { Log.Comment("From ushort"); BasicSelectionTestClass_sbyte_e_e_tc_Conv temp = new BasicSelectionTestClass_sbyte_e_e_tc_Conv(); temp.value_ushort = val; return (temp); } public ushort GetValueushort() { return (value_ushort); } public void SetValueushort(ushort val) { value_ushort = val; } } class BasicSelectionTestClass_sbyte_e_e_tc { public static int Main_old() { BasicSelectionTestClass_sbyte_e_e_tc_Conv cl = new BasicSelectionTestClass_sbyte_e_e_tc_Conv(); sbyte val = 1; cl = (BasicSelectionTestClass_sbyte_e_e_tc_Conv)val; if (cl.GetValuesbyte() != 1) return 1; else return 0; } public static bool testMethod() { return (Main_old() == 0); } } class BasicSelectionTestClass_sbyte_i_i_fc_Conv { private byte value_byte; static public implicit operator byte(BasicSelectionTestClass_sbyte_i_i_fc_Conv test) { Log.Comment("To byte"); return test.value_byte; } static public implicit operator BasicSelectionTestClass_sbyte_i_i_fc_Conv(byte val) { Log.Comment("From byte"); BasicSelectionTestClass_sbyte_i_i_fc_Conv temp = new BasicSelectionTestClass_sbyte_i_i_fc_Conv(); temp.value_byte = val; return (temp); } public byte GetValuebyte() { return (value_byte); } public void SetValuebyte(byte val) { value_byte = val; } private char value_char; static public implicit operator char(BasicSelectionTestClass_sbyte_i_i_fc_Conv test) { Log.Comment("To char"); return test.value_char; } static public implicit operator BasicSelectionTestClass_sbyte_i_i_fc_Conv(char val) { Log.Comment("From char"); BasicSelectionTestClass_sbyte_i_i_fc_Conv temp = new BasicSelectionTestClass_sbyte_i_i_fc_Conv(); temp.value_char = val; return (temp); } public char GetValuechar() { return (value_char); } public void SetValuechar(char val) { value_char = val; } private double value_double; static public implicit operator double(BasicSelectionTestClass_sbyte_i_i_fc_Conv test) { Log.Comment("To double"); return test.value_double; } static public implicit operator BasicSelectionTestClass_sbyte_i_i_fc_Conv(double val) { Log.Comment("From double"); BasicSelectionTestClass_sbyte_i_i_fc_Conv temp = new BasicSelectionTestClass_sbyte_i_i_fc_Conv(); temp.value_double = val; return (temp); } public double GetValuedouble() { return (value_double); } public void SetValuedouble(double val) { value_double = val; } private float value_float; static public implicit operator float(BasicSelectionTestClass_sbyte_i_i_fc_Conv test) { Log.Comment("To float"); return test.value_float; } static public implicit operator BasicSelectionTestClass_sbyte_i_i_fc_Conv(float val) { Log.Comment("From float"); BasicSelectionTestClass_sbyte_i_i_fc_Conv temp = new BasicSelectionTestClass_sbyte_i_i_fc_Conv(); temp.value_float = val; return (temp); } public float GetValuefloat() { return (value_float); } public void SetValuefloat(float val) { value_float = val; } private int value_int; static public implicit operator int(BasicSelectionTestClass_sbyte_i_i_fc_Conv test) { Log.Comment("To int"); return test.value_int; } static public implicit operator BasicSelectionTestClass_sbyte_i_i_fc_Conv(int val) { Log.Comment("From int"); BasicSelectionTestClass_sbyte_i_i_fc_Conv temp = new BasicSelectionTestClass_sbyte_i_i_fc_Conv(); temp.value_int = val; return (temp); } public int GetValueint() { return (value_int); } public void SetValueint(int val) { value_int = val; } private long value_long; static public implicit operator long(BasicSelectionTestClass_sbyte_i_i_fc_Conv test) { Log.Comment("To long"); return test.value_long; } static public implicit operator BasicSelectionTestClass_sbyte_i_i_fc_Conv(long val) { Log.Comment("From long"); BasicSelectionTestClass_sbyte_i_i_fc_Conv temp = new BasicSelectionTestClass_sbyte_i_i_fc_Conv(); temp.value_long = val; return (temp); } public long GetValuelong() { return (value_long); } public void SetValuelong(long val) { value_long = val; } private sbyte value_sbyte; static public implicit operator sbyte(BasicSelectionTestClass_sbyte_i_i_fc_Conv test) { Log.Comment("To sbyte"); return test.value_sbyte; } static public implicit operator BasicSelectionTestClass_sbyte_i_i_fc_Conv(sbyte val) { Log.Comment("From sbyte"); BasicSelectionTestClass_sbyte_i_i_fc_Conv temp = new BasicSelectionTestClass_sbyte_i_i_fc_Conv(); temp.value_sbyte = val; return (temp); } public sbyte GetValuesbyte() { return (value_sbyte); } public void SetValuesbyte(sbyte val) { value_sbyte = val; } private short value_short; static public implicit operator short(BasicSelectionTestClass_sbyte_i_i_fc_Conv test) { Log.Comment("To short"); return test.value_short; } static public implicit operator BasicSelectionTestClass_sbyte_i_i_fc_Conv(short val) { Log.Comment("From short"); BasicSelectionTestClass_sbyte_i_i_fc_Conv temp = new BasicSelectionTestClass_sbyte_i_i_fc_Conv(); temp.value_short = val; return (temp); } public short GetValueshort() { return (value_short); } public void SetValueshort(short val) { value_short = val; } private uint value_uint; static public implicit operator uint(BasicSelectionTestClass_sbyte_i_i_fc_Conv test) { Log.Comment("To uint"); return test.value_uint; } static public implicit operator BasicSelectionTestClass_sbyte_i_i_fc_Conv(uint val) { Log.Comment("From uint"); BasicSelectionTestClass_sbyte_i_i_fc_Conv temp = new BasicSelectionTestClass_sbyte_i_i_fc_Conv(); temp.value_uint = val; return (temp); } public uint GetValueuint() { return (value_uint); } public void SetValueuint(uint val) { value_uint = val; } private ulong value_ulong; static public implicit operator ulong(BasicSelectionTestClass_sbyte_i_i_fc_Conv test) { Log.Comment("To ulong"); return test.value_ulong; } static public implicit operator BasicSelectionTestClass_sbyte_i_i_fc_Conv(ulong val) { Log.Comment("From ulong"); BasicSelectionTestClass_sbyte_i_i_fc_Conv temp = new BasicSelectionTestClass_sbyte_i_i_fc_Conv(); temp.value_ulong = val; return (temp); } public ulong GetValueulong() { return (value_ulong); } public void SetValueulong(ulong val) { value_ulong = val; } private ushort value_ushort; static public implicit operator ushort(BasicSelectionTestClass_sbyte_i_i_fc_Conv test) { Log.Comment("To ushort"); return test.value_ushort; } static public implicit operator BasicSelectionTestClass_sbyte_i_i_fc_Conv(ushort val) { Log.Comment("From ushort"); BasicSelectionTestClass_sbyte_i_i_fc_Conv temp = new BasicSelectionTestClass_sbyte_i_i_fc_Conv(); temp.value_ushort = val; return (temp); } public ushort GetValueushort() { return (value_ushort); } public void SetValueushort(ushort val) { value_ushort = val; } } class BasicSelectionTestClass_sbyte_i_i_fc { public static int Main_old() { BasicSelectionTestClass_sbyte_i_i_fc_Conv cl = new BasicSelectionTestClass_sbyte_i_i_fc_Conv(); cl.SetValuesbyte(1); sbyte value = cl; if (value != 1) return 1; else return 0; } public static bool testMethod() { return (Main_old() == 0); } } class BasicSelectionTestClass_sbyte_i_e_fc_Conv { private byte value_byte; static public implicit operator byte(BasicSelectionTestClass_sbyte_i_e_fc_Conv test) { Log.Comment("To byte"); return test.value_byte; } static public implicit operator BasicSelectionTestClass_sbyte_i_e_fc_Conv(byte val) { Log.Comment("From byte"); BasicSelectionTestClass_sbyte_i_e_fc_Conv temp = new BasicSelectionTestClass_sbyte_i_e_fc_Conv(); temp.value_byte = val; return (temp); } public byte GetValuebyte() { return (value_byte); } public void SetValuebyte(byte val) { value_byte = val; } private char value_char; static public implicit operator char(BasicSelectionTestClass_sbyte_i_e_fc_Conv test) { Log.Comment("To char"); return test.value_char; } static public implicit operator BasicSelectionTestClass_sbyte_i_e_fc_Conv(char val) { Log.Comment("From char"); BasicSelectionTestClass_sbyte_i_e_fc_Conv temp = new BasicSelectionTestClass_sbyte_i_e_fc_Conv(); temp.value_char = val; return (temp); } public char GetValuechar() { return (value_char); } public void SetValuechar(char val) { value_char = val; } private double value_double; static public implicit operator double(BasicSelectionTestClass_sbyte_i_e_fc_Conv test) { Log.Comment("To double"); return test.value_double; } static public implicit operator BasicSelectionTestClass_sbyte_i_e_fc_Conv(double val) { Log.Comment("From double"); BasicSelectionTestClass_sbyte_i_e_fc_Conv temp = new BasicSelectionTestClass_sbyte_i_e_fc_Conv(); temp.value_double = val; return (temp); } public double GetValuedouble() { return (value_double); } public void SetValuedouble(double val) { value_double = val; } private float value_float; static public implicit operator float(BasicSelectionTestClass_sbyte_i_e_fc_Conv test) { Log.Comment("To float"); return test.value_float; } static public implicit operator BasicSelectionTestClass_sbyte_i_e_fc_Conv(float val) { Log.Comment("From float"); BasicSelectionTestClass_sbyte_i_e_fc_Conv temp = new BasicSelectionTestClass_sbyte_i_e_fc_Conv(); temp.value_float = val; return (temp); } public float GetValuefloat() { return (value_float); } public void SetValuefloat(float val) { value_float = val; } private int value_int; static public implicit operator int(BasicSelectionTestClass_sbyte_i_e_fc_Conv test) { Log.Comment("To int"); return test.value_int; } static public implicit operator BasicSelectionTestClass_sbyte_i_e_fc_Conv(int val) { Log.Comment("From int"); BasicSelectionTestClass_sbyte_i_e_fc_Conv temp = new BasicSelectionTestClass_sbyte_i_e_fc_Conv(); temp.value_int = val; return (temp); } public int GetValueint() { return (value_int); } public void SetValueint(int val) { value_int = val; } private long value_long; static public implicit operator long(BasicSelectionTestClass_sbyte_i_e_fc_Conv test) { Log.Comment("To long"); return test.value_long; } static public implicit operator BasicSelectionTestClass_sbyte_i_e_fc_Conv(long val) { Log.Comment("From long"); BasicSelectionTestClass_sbyte_i_e_fc_Conv temp = new BasicSelectionTestClass_sbyte_i_e_fc_Conv(); temp.value_long = val; return (temp); } public long GetValuelong() { return (value_long); } public void SetValuelong(long val) { value_long = val; } private sbyte value_sbyte; static public implicit operator sbyte(BasicSelectionTestClass_sbyte_i_e_fc_Conv test) { Log.Comment("To sbyte"); return test.value_sbyte; } static public implicit operator BasicSelectionTestClass_sbyte_i_e_fc_Conv(sbyte val) { Log.Comment("From sbyte"); BasicSelectionTestClass_sbyte_i_e_fc_Conv temp = new BasicSelectionTestClass_sbyte_i_e_fc_Conv(); temp.value_sbyte = val; return (temp); } public sbyte GetValuesbyte() { return (value_sbyte); } public void SetValuesbyte(sbyte val) { value_sbyte = val; } private short value_short; static public implicit operator short(BasicSelectionTestClass_sbyte_i_e_fc_Conv test) { Log.Comment("To short"); return test.value_short; } static public implicit operator BasicSelectionTestClass_sbyte_i_e_fc_Conv(short val) { Log.Comment("From short"); BasicSelectionTestClass_sbyte_i_e_fc_Conv temp = new BasicSelectionTestClass_sbyte_i_e_fc_Conv(); temp.value_short = val; return (temp); } public short GetValueshort() { return (value_short); } public void SetValueshort(short val) { value_short = val; } private uint value_uint; static public implicit operator uint(BasicSelectionTestClass_sbyte_i_e_fc_Conv test) { Log.Comment("To uint"); return test.value_uint; } static public implicit operator BasicSelectionTestClass_sbyte_i_e_fc_Conv(uint val) { Log.Comment("From uint"); BasicSelectionTestClass_sbyte_i_e_fc_Conv temp = new BasicSelectionTestClass_sbyte_i_e_fc_Conv(); temp.value_uint = val; return (temp); } public uint GetValueuint() { return (value_uint); } public void SetValueuint(uint val) { value_uint = val; } private ulong value_ulong; static public implicit operator ulong(BasicSelectionTestClass_sbyte_i_e_fc_Conv test) { Log.Comment("To ulong"); return test.value_ulong; } static public implicit operator BasicSelectionTestClass_sbyte_i_e_fc_Conv(ulong val) { Log.Comment("From ulong"); BasicSelectionTestClass_sbyte_i_e_fc_Conv temp = new BasicSelectionTestClass_sbyte_i_e_fc_Conv(); temp.value_ulong = val; return (temp); } public ulong GetValueulong() { return (value_ulong); } public void SetValueulong(ulong val) { value_ulong = val; } private ushort value_ushort; static public implicit operator ushort(BasicSelectionTestClass_sbyte_i_e_fc_Conv test) { Log.Comment("To ushort"); return test.value_ushort; } static public implicit operator BasicSelectionTestClass_sbyte_i_e_fc_Conv(ushort val) { Log.Comment("From ushort"); BasicSelectionTestClass_sbyte_i_e_fc_Conv temp = new BasicSelectionTestClass_sbyte_i_e_fc_Conv(); temp.value_ushort = val; return (temp); } public ushort GetValueushort() { return (value_ushort); } public void SetValueushort(ushort val) { value_ushort = val; } } class BasicSelectionTestClass_sbyte_i_e_fc { public static int Main_old() { BasicSelectionTestClass_sbyte_i_e_fc_Conv cl = new BasicSelectionTestClass_sbyte_i_e_fc_Conv(); cl.SetValuesbyte(1); sbyte value = (sbyte)cl; if (value != 1) return 1; else return 0; } public static bool testMethod() { return (Main_old() == 0); } } class BasicSelectionTestClass_sbyte_e_e_fc_Conv { private byte value_byte; static public explicit operator byte(BasicSelectionTestClass_sbyte_e_e_fc_Conv test) { Log.Comment("To byte"); return test.value_byte; } static public explicit operator BasicSelectionTestClass_sbyte_e_e_fc_Conv(byte val) { Log.Comment("From byte"); BasicSelectionTestClass_sbyte_e_e_fc_Conv temp = new BasicSelectionTestClass_sbyte_e_e_fc_Conv(); temp.value_byte = val; return (temp); } public byte GetValuebyte() { return (value_byte); } public void SetValuebyte(byte val) { value_byte = val; } private char value_char; static public explicit operator char(BasicSelectionTestClass_sbyte_e_e_fc_Conv test) { Log.Comment("To char"); return test.value_char; } static public explicit operator BasicSelectionTestClass_sbyte_e_e_fc_Conv(char val) { Log.Comment("From char"); BasicSelectionTestClass_sbyte_e_e_fc_Conv temp = new BasicSelectionTestClass_sbyte_e_e_fc_Conv(); temp.value_char = val; return (temp); } public char GetValuechar() { return (value_char); } public void SetValuechar(char val) { value_char = val; } private double value_double; static public explicit operator double(BasicSelectionTestClass_sbyte_e_e_fc_Conv test) { Log.Comment("To double"); return test.value_double; } static public explicit operator BasicSelectionTestClass_sbyte_e_e_fc_Conv(double val) { Log.Comment("From double"); BasicSelectionTestClass_sbyte_e_e_fc_Conv temp = new BasicSelectionTestClass_sbyte_e_e_fc_Conv(); temp.value_double = val; return (temp); } public double GetValuedouble() { return (value_double); } public void SetValuedouble(double val) { value_double = val; } private float value_float; static public explicit operator float(BasicSelectionTestClass_sbyte_e_e_fc_Conv test) { Log.Comment("To float"); return test.value_float; } static public explicit operator BasicSelectionTestClass_sbyte_e_e_fc_Conv(float val) { Log.Comment("From float"); BasicSelectionTestClass_sbyte_e_e_fc_Conv temp = new BasicSelectionTestClass_sbyte_e_e_fc_Conv(); temp.value_float = val; return (temp); } public float GetValuefloat() { return (value_float); } public void SetValuefloat(float val) { value_float = val; } private int value_int; static public explicit operator int(BasicSelectionTestClass_sbyte_e_e_fc_Conv test) { Log.Comment("To int"); return test.value_int; } static public explicit operator BasicSelectionTestClass_sbyte_e_e_fc_Conv(int val) { Log.Comment("From int"); BasicSelectionTestClass_sbyte_e_e_fc_Conv temp = new BasicSelectionTestClass_sbyte_e_e_fc_Conv(); temp.value_int = val; return (temp); } public int GetValueint() { return (value_int); } public void SetValueint(int val) { value_int = val; } private long value_long; static public explicit operator long(BasicSelectionTestClass_sbyte_e_e_fc_Conv test) { Log.Comment("To long"); return test.value_long; } static public explicit operator BasicSelectionTestClass_sbyte_e_e_fc_Conv(long val) { Log.Comment("From long"); BasicSelectionTestClass_sbyte_e_e_fc_Conv temp = new BasicSelectionTestClass_sbyte_e_e_fc_Conv(); temp.value_long = val; return (temp); } public long GetValuelong() { return (value_long); } public void SetValuelong(long val) { value_long = val; } private sbyte value_sbyte; static public explicit operator sbyte(BasicSelectionTestClass_sbyte_e_e_fc_Conv test) { Log.Comment("To sbyte"); return test.value_sbyte; } static public explicit operator BasicSelectionTestClass_sbyte_e_e_fc_Conv(sbyte val) { Log.Comment("From sbyte"); BasicSelectionTestClass_sbyte_e_e_fc_Conv temp = new BasicSelectionTestClass_sbyte_e_e_fc_Conv(); temp.value_sbyte = val; return (temp); } public sbyte GetValuesbyte() { return (value_sbyte); } public void SetValuesbyte(sbyte val) { value_sbyte = val; } private short value_short; static public explicit operator short(BasicSelectionTestClass_sbyte_e_e_fc_Conv test) { Log.Comment("To short"); return test.value_short; } static public explicit operator BasicSelectionTestClass_sbyte_e_e_fc_Conv(short val) { Log.Comment("From short"); BasicSelectionTestClass_sbyte_e_e_fc_Conv temp = new BasicSelectionTestClass_sbyte_e_e_fc_Conv(); temp.value_short = val; return (temp); } public short GetValueshort() { return (value_short); } public void SetValueshort(short val) { value_short = val; } private uint value_uint; static public explicit operator uint(BasicSelectionTestClass_sbyte_e_e_fc_Conv test) { Log.Comment("To uint"); return test.value_uint; } static public explicit operator BasicSelectionTestClass_sbyte_e_e_fc_Conv(uint val) { Log.Comment("From uint"); BasicSelectionTestClass_sbyte_e_e_fc_Conv temp = new BasicSelectionTestClass_sbyte_e_e_fc_Conv(); temp.value_uint = val; return (temp); } public uint GetValueuint() { return (value_uint); } public void SetValueuint(uint val) { value_uint = val; } private ulong value_ulong; static public explicit operator ulong(BasicSelectionTestClass_sbyte_e_e_fc_Conv test) { Log.Comment("To ulong"); return test.value_ulong; } static public explicit operator BasicSelectionTestClass_sbyte_e_e_fc_Conv(ulong val) { Log.Comment("From ulong"); BasicSelectionTestClass_sbyte_e_e_fc_Conv temp = new BasicSelectionTestClass_sbyte_e_e_fc_Conv(); temp.value_ulong = val; return (temp); } public ulong GetValueulong() { return (value_ulong); } public void SetValueulong(ulong val) { value_ulong = val; } private ushort value_ushort; static public explicit operator ushort(BasicSelectionTestClass_sbyte_e_e_fc_Conv test) { Log.Comment("To ushort"); return test.value_ushort; } static public explicit operator BasicSelectionTestClass_sbyte_e_e_fc_Conv(ushort val) { Log.Comment("From ushort"); BasicSelectionTestClass_sbyte_e_e_fc_Conv temp = new BasicSelectionTestClass_sbyte_e_e_fc_Conv(); temp.value_ushort = val; return (temp); } public ushort GetValueushort() { return (value_ushort); } public void SetValueushort(ushort val) { value_ushort = val; } } class BasicSelectionTestClass_sbyte_e_e_fc { public static int Main_old() { BasicSelectionTestClass_sbyte_e_e_fc_Conv cl = new BasicSelectionTestClass_sbyte_e_e_fc_Conv(); cl.SetValuesbyte(1); sbyte value = (sbyte)cl; if (value != 1) return 1; else return 0; } public static bool testMethod() { return (Main_old() == 0); } } class BasicSelectionTestClass_short_i_i_tc_Conv { private byte value_byte; static public implicit operator byte(BasicSelectionTestClass_short_i_i_tc_Conv test) { Log.Comment("To byte"); return test.value_byte; } static public implicit operator BasicSelectionTestClass_short_i_i_tc_Conv(byte val) { Log.Comment("From byte"); BasicSelectionTestClass_short_i_i_tc_Conv temp = new BasicSelectionTestClass_short_i_i_tc_Conv(); temp.value_byte = val; return (temp); } public byte GetValuebyte() { return (value_byte); } public void SetValuebyte(byte val) { value_byte = val; } private char value_char; static public implicit operator char(BasicSelectionTestClass_short_i_i_tc_Conv test) { Log.Comment("To char"); return test.value_char; } static public implicit operator BasicSelectionTestClass_short_i_i_tc_Conv(char val) { Log.Comment("From char"); BasicSelectionTestClass_short_i_i_tc_Conv temp = new BasicSelectionTestClass_short_i_i_tc_Conv(); temp.value_char = val; return (temp); } public char GetValuechar() { return (value_char); } public void SetValuechar(char val) { value_char = val; } private double value_double; static public implicit operator double(BasicSelectionTestClass_short_i_i_tc_Conv test) { Log.Comment("To double"); return test.value_double; } static public implicit operator BasicSelectionTestClass_short_i_i_tc_Conv(double val) { Log.Comment("From double"); BasicSelectionTestClass_short_i_i_tc_Conv temp = new BasicSelectionTestClass_short_i_i_tc_Conv(); temp.value_double = val; return (temp); } public double GetValuedouble() { return (value_double); } public void SetValuedouble(double val) { value_double = val; } private float value_float; static public implicit operator float(BasicSelectionTestClass_short_i_i_tc_Conv test) { Log.Comment("To float"); return test.value_float; } static public implicit operator BasicSelectionTestClass_short_i_i_tc_Conv(float val) { Log.Comment("From float"); BasicSelectionTestClass_short_i_i_tc_Conv temp = new BasicSelectionTestClass_short_i_i_tc_Conv(); temp.value_float = val; return (temp); } public float GetValuefloat() { return (value_float); } public void SetValuefloat(float val) { value_float = val; } private int value_int; static public implicit operator int(BasicSelectionTestClass_short_i_i_tc_Conv test) { Log.Comment("To int"); return test.value_int; } static public implicit operator BasicSelectionTestClass_short_i_i_tc_Conv(int val) { Log.Comment("From int"); BasicSelectionTestClass_short_i_i_tc_Conv temp = new BasicSelectionTestClass_short_i_i_tc_Conv(); temp.value_int = val; return (temp); } public int GetValueint() { return (value_int); } public void SetValueint(int val) { value_int = val; } private long value_long; static public implicit operator long(BasicSelectionTestClass_short_i_i_tc_Conv test) { Log.Comment("To long"); return test.value_long; } static public implicit operator BasicSelectionTestClass_short_i_i_tc_Conv(long val) { Log.Comment("From long"); BasicSelectionTestClass_short_i_i_tc_Conv temp = new BasicSelectionTestClass_short_i_i_tc_Conv(); temp.value_long = val; return (temp); } public long GetValuelong() { return (value_long); } public void SetValuelong(long val) { value_long = val; } private sbyte value_sbyte; static public implicit operator sbyte(BasicSelectionTestClass_short_i_i_tc_Conv test) { Log.Comment("To sbyte"); return test.value_sbyte; } static public implicit operator BasicSelectionTestClass_short_i_i_tc_Conv(sbyte val) { Log.Comment("From sbyte"); BasicSelectionTestClass_short_i_i_tc_Conv temp = new BasicSelectionTestClass_short_i_i_tc_Conv(); temp.value_sbyte = val; return (temp); } public sbyte GetValuesbyte() { return (value_sbyte); } public void SetValuesbyte(sbyte val) { value_sbyte = val; } private short value_short; static public implicit operator short(BasicSelectionTestClass_short_i_i_tc_Conv test) { Log.Comment("To short"); return test.value_short; } static public implicit operator BasicSelectionTestClass_short_i_i_tc_Conv(short val) { Log.Comment("From short"); BasicSelectionTestClass_short_i_i_tc_Conv temp = new BasicSelectionTestClass_short_i_i_tc_Conv(); temp.value_short = val; return (temp); } public short GetValueshort() { return (value_short); } public void SetValueshort(short val) { value_short = val; } private uint value_uint; static public implicit operator uint(BasicSelectionTestClass_short_i_i_tc_Conv test) { Log.Comment("To uint"); return test.value_uint; } static public implicit operator BasicSelectionTestClass_short_i_i_tc_Conv(uint val) { Log.Comment("From uint"); BasicSelectionTestClass_short_i_i_tc_Conv temp = new BasicSelectionTestClass_short_i_i_tc_Conv(); temp.value_uint = val; return (temp); } public uint GetValueuint() { return (value_uint); } public void SetValueuint(uint val) { value_uint = val; } private ulong value_ulong; static public implicit operator ulong(BasicSelectionTestClass_short_i_i_tc_Conv test) { Log.Comment("To ulong"); return test.value_ulong; } static public implicit operator BasicSelectionTestClass_short_i_i_tc_Conv(ulong val) { Log.Comment("From ulong"); BasicSelectionTestClass_short_i_i_tc_Conv temp = new BasicSelectionTestClass_short_i_i_tc_Conv(); temp.value_ulong = val; return (temp); } public ulong GetValueulong() { return (value_ulong); } public void SetValueulong(ulong val) { value_ulong = val; } private ushort value_ushort; static public implicit operator ushort(BasicSelectionTestClass_short_i_i_tc_Conv test) { Log.Comment("To ushort"); return test.value_ushort; } static public implicit operator BasicSelectionTestClass_short_i_i_tc_Conv(ushort val) { Log.Comment("From ushort"); BasicSelectionTestClass_short_i_i_tc_Conv temp = new BasicSelectionTestClass_short_i_i_tc_Conv(); temp.value_ushort = val; return (temp); } public ushort GetValueushort() { return (value_ushort); } public void SetValueushort(ushort val) { value_ushort = val; } } class BasicSelectionTestClass_short_i_i_tc { public static int Main_old() { BasicSelectionTestClass_short_i_i_tc_Conv cl = new BasicSelectionTestClass_short_i_i_tc_Conv(); short val = 1; cl = val; if (cl.GetValueshort() != 1) return 1; else return 0; } public static bool testMethod() { return (Main_old() == 0); } } class BasicSelectionTestClass_short_i_e_tc_Conv { private byte value_byte; static public implicit operator byte(BasicSelectionTestClass_short_i_e_tc_Conv test) { Log.Comment("To byte"); return test.value_byte; } static public implicit operator BasicSelectionTestClass_short_i_e_tc_Conv(byte val) { Log.Comment("From byte"); BasicSelectionTestClass_short_i_e_tc_Conv temp = new BasicSelectionTestClass_short_i_e_tc_Conv(); temp.value_byte = val; return (temp); } public byte GetValuebyte() { return (value_byte); } public void SetValuebyte(byte val) { value_byte = val; } private char value_char; static public implicit operator char(BasicSelectionTestClass_short_i_e_tc_Conv test) { Log.Comment("To char"); return test.value_char; } static public implicit operator BasicSelectionTestClass_short_i_e_tc_Conv(char val) { Log.Comment("From char"); BasicSelectionTestClass_short_i_e_tc_Conv temp = new BasicSelectionTestClass_short_i_e_tc_Conv(); temp.value_char = val; return (temp); } public char GetValuechar() { return (value_char); } public void SetValuechar(char val) { value_char = val; } private double value_double; static public implicit operator double(BasicSelectionTestClass_short_i_e_tc_Conv test) { Log.Comment("To double"); return test.value_double; } static public implicit operator BasicSelectionTestClass_short_i_e_tc_Conv(double val) { Log.Comment("From double"); BasicSelectionTestClass_short_i_e_tc_Conv temp = new BasicSelectionTestClass_short_i_e_tc_Conv(); temp.value_double = val; return (temp); } public double GetValuedouble() { return (value_double); } public void SetValuedouble(double val) { value_double = val; } private float value_float; static public implicit operator float(BasicSelectionTestClass_short_i_e_tc_Conv test) { Log.Comment("To float"); return test.value_float; } static public implicit operator BasicSelectionTestClass_short_i_e_tc_Conv(float val) { Log.Comment("From float"); BasicSelectionTestClass_short_i_e_tc_Conv temp = new BasicSelectionTestClass_short_i_e_tc_Conv(); temp.value_float = val; return (temp); } public float GetValuefloat() { return (value_float); } public void SetValuefloat(float val) { value_float = val; } private int value_int; static public implicit operator int(BasicSelectionTestClass_short_i_e_tc_Conv test) { Log.Comment("To int"); return test.value_int; } static public implicit operator BasicSelectionTestClass_short_i_e_tc_Conv(int val) { Log.Comment("From int"); BasicSelectionTestClass_short_i_e_tc_Conv temp = new BasicSelectionTestClass_short_i_e_tc_Conv(); temp.value_int = val; return (temp); } public int GetValueint() { return (value_int); } public void SetValueint(int val) { value_int = val; } private long value_long; static public implicit operator long(BasicSelectionTestClass_short_i_e_tc_Conv test) { Log.Comment("To long"); return test.value_long; } static public implicit operator BasicSelectionTestClass_short_i_e_tc_Conv(long val) { Log.Comment("From long"); BasicSelectionTestClass_short_i_e_tc_Conv temp = new BasicSelectionTestClass_short_i_e_tc_Conv(); temp.value_long = val; return (temp); } public long GetValuelong() { return (value_long); } public void SetValuelong(long val) { value_long = val; } private sbyte value_sbyte; static public implicit operator sbyte(BasicSelectionTestClass_short_i_e_tc_Conv test) { Log.Comment("To sbyte"); return test.value_sbyte; } static public implicit operator BasicSelectionTestClass_short_i_e_tc_Conv(sbyte val) { Log.Comment("From sbyte"); BasicSelectionTestClass_short_i_e_tc_Conv temp = new BasicSelectionTestClass_short_i_e_tc_Conv(); temp.value_sbyte = val; return (temp); } public sbyte GetValuesbyte() { return (value_sbyte); } public void SetValuesbyte(sbyte val) { value_sbyte = val; } private short value_short; static public implicit operator short(BasicSelectionTestClass_short_i_e_tc_Conv test) { Log.Comment("To short"); return test.value_short; } static public implicit operator BasicSelectionTestClass_short_i_e_tc_Conv(short val) { Log.Comment("From short"); BasicSelectionTestClass_short_i_e_tc_Conv temp = new BasicSelectionTestClass_short_i_e_tc_Conv(); temp.value_short = val; return (temp); } public short GetValueshort() { return (value_short); } public void SetValueshort(short val) { value_short = val; } private uint value_uint; static public implicit operator uint(BasicSelectionTestClass_short_i_e_tc_Conv test) { Log.Comment("To uint"); return test.value_uint; } static public implicit operator BasicSelectionTestClass_short_i_e_tc_Conv(uint val) { Log.Comment("From uint"); BasicSelectionTestClass_short_i_e_tc_Conv temp = new BasicSelectionTestClass_short_i_e_tc_Conv(); temp.value_uint = val; return (temp); } public uint GetValueuint() { return (value_uint); } public void SetValueuint(uint val) { value_uint = val; } private ulong value_ulong; static public implicit operator ulong(BasicSelectionTestClass_short_i_e_tc_Conv test) { Log.Comment("To ulong"); return test.value_ulong; } static public implicit operator BasicSelectionTestClass_short_i_e_tc_Conv(ulong val) { Log.Comment("From ulong"); BasicSelectionTestClass_short_i_e_tc_Conv temp = new BasicSelectionTestClass_short_i_e_tc_Conv(); temp.value_ulong = val; return (temp); } public ulong GetValueulong() { return (value_ulong); } public void SetValueulong(ulong val) { value_ulong = val; } private ushort value_ushort; static public implicit operator ushort(BasicSelectionTestClass_short_i_e_tc_Conv test) { Log.Comment("To ushort"); return test.value_ushort; } static public implicit operator BasicSelectionTestClass_short_i_e_tc_Conv(ushort val) { Log.Comment("From ushort"); BasicSelectionTestClass_short_i_e_tc_Conv temp = new BasicSelectionTestClass_short_i_e_tc_Conv(); temp.value_ushort = val; return (temp); } public ushort GetValueushort() { return (value_ushort); } public void SetValueushort(ushort val) { value_ushort = val; } } class BasicSelectionTestClass_short_i_e_tc { public static int Main_old() { BasicSelectionTestClass_short_i_e_tc_Conv cl = new BasicSelectionTestClass_short_i_e_tc_Conv(); short val = 1; cl = (BasicSelectionTestClass_short_i_e_tc_Conv)val; if (cl.GetValueshort() != 1) return 1; else return 0; } public static bool testMethod() { return (Main_old() == 0); } } class BasicSelectionTestClass_short_e_e_tc_Conv { private byte value_byte; static public explicit operator byte(BasicSelectionTestClass_short_e_e_tc_Conv test) { Log.Comment("To byte"); return test.value_byte; } static public explicit operator BasicSelectionTestClass_short_e_e_tc_Conv(byte val) { Log.Comment("From byte"); BasicSelectionTestClass_short_e_e_tc_Conv temp = new BasicSelectionTestClass_short_e_e_tc_Conv(); temp.value_byte = val; return (temp); } public byte GetValuebyte() { return (value_byte); } public void SetValuebyte(byte val) { value_byte = val; } private char value_char; static public explicit operator char(BasicSelectionTestClass_short_e_e_tc_Conv test) { Log.Comment("To char"); return test.value_char; } static public explicit operator BasicSelectionTestClass_short_e_e_tc_Conv(char val) { Log.Comment("From char"); BasicSelectionTestClass_short_e_e_tc_Conv temp = new BasicSelectionTestClass_short_e_e_tc_Conv(); temp.value_char = val; return (temp); } public char GetValuechar() { return (value_char); } public void SetValuechar(char val) { value_char = val; } private double value_double; static public explicit operator double(BasicSelectionTestClass_short_e_e_tc_Conv test) { Log.Comment("To double"); return test.value_double; } static public explicit operator BasicSelectionTestClass_short_e_e_tc_Conv(double val) { Log.Comment("From double"); BasicSelectionTestClass_short_e_e_tc_Conv temp = new BasicSelectionTestClass_short_e_e_tc_Conv(); temp.value_double = val; return (temp); } public double GetValuedouble() { return (value_double); } public void SetValuedouble(double val) { value_double = val; } private float value_float; static public explicit operator float(BasicSelectionTestClass_short_e_e_tc_Conv test) { Log.Comment("To float"); return test.value_float; } static public explicit operator BasicSelectionTestClass_short_e_e_tc_Conv(float val) { Log.Comment("From float"); BasicSelectionTestClass_short_e_e_tc_Conv temp = new BasicSelectionTestClass_short_e_e_tc_Conv(); temp.value_float = val; return (temp); } public float GetValuefloat() { return (value_float); } public void SetValuefloat(float val) { value_float = val; } private int value_int; static public explicit operator int(BasicSelectionTestClass_short_e_e_tc_Conv test) { Log.Comment("To int"); return test.value_int; } static public explicit operator BasicSelectionTestClass_short_e_e_tc_Conv(int val) { Log.Comment("From int"); BasicSelectionTestClass_short_e_e_tc_Conv temp = new BasicSelectionTestClass_short_e_e_tc_Conv(); temp.value_int = val; return (temp); } public int GetValueint() { return (value_int); } public void SetValueint(int val) { value_int = val; } private long value_long; static public explicit operator long(BasicSelectionTestClass_short_e_e_tc_Conv test) { Log.Comment("To long"); return test.value_long; } static public explicit operator BasicSelectionTestClass_short_e_e_tc_Conv(long val) { Log.Comment("From long"); BasicSelectionTestClass_short_e_e_tc_Conv temp = new BasicSelectionTestClass_short_e_e_tc_Conv(); temp.value_long = val; return (temp); } public long GetValuelong() { return (value_long); } public void SetValuelong(long val) { value_long = val; } private sbyte value_sbyte; static public explicit operator sbyte(BasicSelectionTestClass_short_e_e_tc_Conv test) { Log.Comment("To sbyte"); return test.value_sbyte; } static public explicit operator BasicSelectionTestClass_short_e_e_tc_Conv(sbyte val) { Log.Comment("From sbyte"); BasicSelectionTestClass_short_e_e_tc_Conv temp = new BasicSelectionTestClass_short_e_e_tc_Conv(); temp.value_sbyte = val; return (temp); } public sbyte GetValuesbyte() { return (value_sbyte); } public void SetValuesbyte(sbyte val) { value_sbyte = val; } private short value_short; static public explicit operator short(BasicSelectionTestClass_short_e_e_tc_Conv test) { Log.Comment("To short"); return test.value_short; } static public explicit operator BasicSelectionTestClass_short_e_e_tc_Conv(short val) { Log.Comment("From short"); BasicSelectionTestClass_short_e_e_tc_Conv temp = new BasicSelectionTestClass_short_e_e_tc_Conv(); temp.value_short = val; return (temp); } public short GetValueshort() { return (value_short); } public void SetValueshort(short val) { value_short = val; } private uint value_uint; static public explicit operator uint(BasicSelectionTestClass_short_e_e_tc_Conv test) { Log.Comment("To uint"); return test.value_uint; } static public explicit operator BasicSelectionTestClass_short_e_e_tc_Conv(uint val) { Log.Comment("From uint"); BasicSelectionTestClass_short_e_e_tc_Conv temp = new BasicSelectionTestClass_short_e_e_tc_Conv(); temp.value_uint = val; return (temp); } public uint GetValueuint() { return (value_uint); } public void SetValueuint(uint val) { value_uint = val; } private ulong value_ulong; static public explicit operator ulong(BasicSelectionTestClass_short_e_e_tc_Conv test) { Log.Comment("To ulong"); return test.value_ulong; } static public explicit operator BasicSelectionTestClass_short_e_e_tc_Conv(ulong val) { Log.Comment("From ulong"); BasicSelectionTestClass_short_e_e_tc_Conv temp = new BasicSelectionTestClass_short_e_e_tc_Conv(); temp.value_ulong = val; return (temp); } public ulong GetValueulong() { return (value_ulong); } public void SetValueulong(ulong val) { value_ulong = val; } private ushort value_ushort; static public explicit operator ushort(BasicSelectionTestClass_short_e_e_tc_Conv test) { Log.Comment("To ushort"); return test.value_ushort; } static public explicit operator BasicSelectionTestClass_short_e_e_tc_Conv(ushort val) { Log.Comment("From ushort"); BasicSelectionTestClass_short_e_e_tc_Conv temp = new BasicSelectionTestClass_short_e_e_tc_Conv(); temp.value_ushort = val; return (temp); } public ushort GetValueushort() { return (value_ushort); } public void SetValueushort(ushort val) { value_ushort = val; } } class BasicSelectionTestClass_short_e_e_tc { public static int Main_old() { BasicSelectionTestClass_short_e_e_tc_Conv cl = new BasicSelectionTestClass_short_e_e_tc_Conv(); short val = 1; cl = (BasicSelectionTestClass_short_e_e_tc_Conv)val; if (cl.GetValueshort() != 1) return 1; else return 0; } public static bool testMethod() { return (Main_old() == 0); } } class BasicSelectionTestClass_short_i_i_fc_Conv { private byte value_byte; static public implicit operator byte(BasicSelectionTestClass_short_i_i_fc_Conv test) { Log.Comment("To byte"); return test.value_byte; } static public implicit operator BasicSelectionTestClass_short_i_i_fc_Conv(byte val) { Log.Comment("From byte"); BasicSelectionTestClass_short_i_i_fc_Conv temp = new BasicSelectionTestClass_short_i_i_fc_Conv(); temp.value_byte = val; return (temp); } public byte GetValuebyte() { return (value_byte); } public void SetValuebyte(byte val) { value_byte = val; } private char value_char; static public implicit operator char(BasicSelectionTestClass_short_i_i_fc_Conv test) { Log.Comment("To char"); return test.value_char; } static public implicit operator BasicSelectionTestClass_short_i_i_fc_Conv(char val) { Log.Comment("From char"); BasicSelectionTestClass_short_i_i_fc_Conv temp = new BasicSelectionTestClass_short_i_i_fc_Conv(); temp.value_char = val; return (temp); } public char GetValuechar() { return (value_char); } public void SetValuechar(char val) { value_char = val; } private double value_double; static public implicit operator double(BasicSelectionTestClass_short_i_i_fc_Conv test) { Log.Comment("To double"); return test.value_double; } static public implicit operator BasicSelectionTestClass_short_i_i_fc_Conv(double val) { Log.Comment("From double"); BasicSelectionTestClass_short_i_i_fc_Conv temp = new BasicSelectionTestClass_short_i_i_fc_Conv(); temp.value_double = val; return (temp); } public double GetValuedouble() { return (value_double); } public void SetValuedouble(double val) { value_double = val; } private float value_float; static public implicit operator float(BasicSelectionTestClass_short_i_i_fc_Conv test) { Log.Comment("To float"); return test.value_float; } static public implicit operator BasicSelectionTestClass_short_i_i_fc_Conv(float val) { Log.Comment("From float"); BasicSelectionTestClass_short_i_i_fc_Conv temp = new BasicSelectionTestClass_short_i_i_fc_Conv(); temp.value_float = val; return (temp); } public float GetValuefloat() { return (value_float); } public void SetValuefloat(float val) { value_float = val; } private int value_int; static public implicit operator int(BasicSelectionTestClass_short_i_i_fc_Conv test) { Log.Comment("To int"); return test.value_int; } static public implicit operator BasicSelectionTestClass_short_i_i_fc_Conv(int val) { Log.Comment("From int"); BasicSelectionTestClass_short_i_i_fc_Conv temp = new BasicSelectionTestClass_short_i_i_fc_Conv(); temp.value_int = val; return (temp); } public int GetValueint() { return (value_int); } public void SetValueint(int val) { value_int = val; } private long value_long; static public implicit operator long(BasicSelectionTestClass_short_i_i_fc_Conv test) { Log.Comment("To long"); return test.value_long; } static public implicit operator BasicSelectionTestClass_short_i_i_fc_Conv(long val) { Log.Comment("From long"); BasicSelectionTestClass_short_i_i_fc_Conv temp = new BasicSelectionTestClass_short_i_i_fc_Conv(); temp.value_long = val; return (temp); } public long GetValuelong() { return (value_long); } public void SetValuelong(long val) { value_long = val; } private sbyte value_sbyte; static public implicit operator sbyte(BasicSelectionTestClass_short_i_i_fc_Conv test) { Log.Comment("To sbyte"); return test.value_sbyte; } static public implicit operator BasicSelectionTestClass_short_i_i_fc_Conv(sbyte val) { Log.Comment("From sbyte"); BasicSelectionTestClass_short_i_i_fc_Conv temp = new BasicSelectionTestClass_short_i_i_fc_Conv(); temp.value_sbyte = val; return (temp); } public sbyte GetValuesbyte() { return (value_sbyte); } public void SetValuesbyte(sbyte val) { value_sbyte = val; } private short value_short; static public implicit operator short(BasicSelectionTestClass_short_i_i_fc_Conv test) { Log.Comment("To short"); return test.value_short; } static public implicit operator BasicSelectionTestClass_short_i_i_fc_Conv(short val) { Log.Comment("From short"); BasicSelectionTestClass_short_i_i_fc_Conv temp = new BasicSelectionTestClass_short_i_i_fc_Conv(); temp.value_short = val; return (temp); } public short GetValueshort() { return (value_short); } public void SetValueshort(short val) { value_short = val; } private uint value_uint; static public implicit operator uint(BasicSelectionTestClass_short_i_i_fc_Conv test) { Log.Comment("To uint"); return test.value_uint; } static public implicit operator BasicSelectionTestClass_short_i_i_fc_Conv(uint val) { Log.Comment("From uint"); BasicSelectionTestClass_short_i_i_fc_Conv temp = new BasicSelectionTestClass_short_i_i_fc_Conv(); temp.value_uint = val; return (temp); } public uint GetValueuint() { return (value_uint); } public void SetValueuint(uint val) { value_uint = val; } private ulong value_ulong; static public implicit operator ulong(BasicSelectionTestClass_short_i_i_fc_Conv test) { Log.Comment("To ulong"); return test.value_ulong; } static public implicit operator BasicSelectionTestClass_short_i_i_fc_Conv(ulong val) { Log.Comment("From ulong"); BasicSelectionTestClass_short_i_i_fc_Conv temp = new BasicSelectionTestClass_short_i_i_fc_Conv(); temp.value_ulong = val; return (temp); } public ulong GetValueulong() { return (value_ulong); } public void SetValueulong(ulong val) { value_ulong = val; } private ushort value_ushort; static public implicit operator ushort(BasicSelectionTestClass_short_i_i_fc_Conv test) { Log.Comment("To ushort"); return test.value_ushort; } static public implicit operator BasicSelectionTestClass_short_i_i_fc_Conv(ushort val) { Log.Comment("From ushort"); BasicSelectionTestClass_short_i_i_fc_Conv temp = new BasicSelectionTestClass_short_i_i_fc_Conv(); temp.value_ushort = val; return (temp); } public ushort GetValueushort() { return (value_ushort); } public void SetValueushort(ushort val) { value_ushort = val; } } class BasicSelectionTestClass_short_i_i_fc { public static int Main_old() { BasicSelectionTestClass_short_i_i_fc_Conv cl = new BasicSelectionTestClass_short_i_i_fc_Conv(); cl.SetValueshort(1); short value = cl; if (value != 1) return 1; else return 0; } public static bool testMethod() { return (Main_old() == 0); } } class BasicSelectionTestClass_short_i_e_fc_Conv { private byte value_byte; static public implicit operator byte(BasicSelectionTestClass_short_i_e_fc_Conv test) { Log.Comment("To byte"); return test.value_byte; } static public implicit operator BasicSelectionTestClass_short_i_e_fc_Conv(byte val) { Log.Comment("From byte"); BasicSelectionTestClass_short_i_e_fc_Conv temp = new BasicSelectionTestClass_short_i_e_fc_Conv(); temp.value_byte = val; return (temp); } public byte GetValuebyte() { return (value_byte); } public void SetValuebyte(byte val) { value_byte = val; } private char value_char; static public implicit operator char(BasicSelectionTestClass_short_i_e_fc_Conv test) { Log.Comment("To char"); return test.value_char; } static public implicit operator BasicSelectionTestClass_short_i_e_fc_Conv(char val) { Log.Comment("From char"); BasicSelectionTestClass_short_i_e_fc_Conv temp = new BasicSelectionTestClass_short_i_e_fc_Conv(); temp.value_char = val; return (temp); } public char GetValuechar() { return (value_char); } public void SetValuechar(char val) { value_char = val; } private double value_double; static public implicit operator double(BasicSelectionTestClass_short_i_e_fc_Conv test) { Log.Comment("To double"); return test.value_double; } static public implicit operator BasicSelectionTestClass_short_i_e_fc_Conv(double val) { Log.Comment("From double"); BasicSelectionTestClass_short_i_e_fc_Conv temp = new BasicSelectionTestClass_short_i_e_fc_Conv(); temp.value_double = val; return (temp); } public double GetValuedouble() { return (value_double); } public void SetValuedouble(double val) { value_double = val; } private float value_float; static public implicit operator float(BasicSelectionTestClass_short_i_e_fc_Conv test) { Log.Comment("To float"); return test.value_float; } static public implicit operator BasicSelectionTestClass_short_i_e_fc_Conv(float val) { Log.Comment("From float"); BasicSelectionTestClass_short_i_e_fc_Conv temp = new BasicSelectionTestClass_short_i_e_fc_Conv(); temp.value_float = val; return (temp); } public float GetValuefloat() { return (value_float); } public void SetValuefloat(float val) { value_float = val; } private int value_int; static public implicit operator int(BasicSelectionTestClass_short_i_e_fc_Conv test) { Log.Comment("To int"); return test.value_int; } static public implicit operator BasicSelectionTestClass_short_i_e_fc_Conv(int val) { Log.Comment("From int"); BasicSelectionTestClass_short_i_e_fc_Conv temp = new BasicSelectionTestClass_short_i_e_fc_Conv(); temp.value_int = val; return (temp); } public int GetValueint() { return (value_int); } public void SetValueint(int val) { value_int = val; } private long value_long; static public implicit operator long(BasicSelectionTestClass_short_i_e_fc_Conv test) { Log.Comment("To long"); return test.value_long; } static public implicit operator BasicSelectionTestClass_short_i_e_fc_Conv(long val) { Log.Comment("From long"); BasicSelectionTestClass_short_i_e_fc_Conv temp = new BasicSelectionTestClass_short_i_e_fc_Conv(); temp.value_long = val; return (temp); } public long GetValuelong() { return (value_long); } public void SetValuelong(long val) { value_long = val; } private sbyte value_sbyte; static public implicit operator sbyte(BasicSelectionTestClass_short_i_e_fc_Conv test) { Log.Comment("To sbyte"); return test.value_sbyte; } static public implicit operator BasicSelectionTestClass_short_i_e_fc_Conv(sbyte val) { Log.Comment("From sbyte"); BasicSelectionTestClass_short_i_e_fc_Conv temp = new BasicSelectionTestClass_short_i_e_fc_Conv(); temp.value_sbyte = val; return (temp); } public sbyte GetValuesbyte() { return (value_sbyte); } public void SetValuesbyte(sbyte val) { value_sbyte = val; } private short value_short; static public implicit operator short(BasicSelectionTestClass_short_i_e_fc_Conv test) { Log.Comment("To short"); return test.value_short; } static public implicit operator BasicSelectionTestClass_short_i_e_fc_Conv(short val) { Log.Comment("From short"); BasicSelectionTestClass_short_i_e_fc_Conv temp = new BasicSelectionTestClass_short_i_e_fc_Conv(); temp.value_short = val; return (temp); } public short GetValueshort() { return (value_short); } public void SetValueshort(short val) { value_short = val; } private uint value_uint; static public implicit operator uint(BasicSelectionTestClass_short_i_e_fc_Conv test) { Log.Comment("To uint"); return test.value_uint; } static public implicit operator BasicSelectionTestClass_short_i_e_fc_Conv(uint val) { Log.Comment("From uint"); BasicSelectionTestClass_short_i_e_fc_Conv temp = new BasicSelectionTestClass_short_i_e_fc_Conv(); temp.value_uint = val; return (temp); } public uint GetValueuint() { return (value_uint); } public void SetValueuint(uint val) { value_uint = val; } private ulong value_ulong; static public implicit operator ulong(BasicSelectionTestClass_short_i_e_fc_Conv test) { Log.Comment("To ulong"); return test.value_ulong; } static public implicit operator BasicSelectionTestClass_short_i_e_fc_Conv(ulong val) { Log.Comment("From ulong"); BasicSelectionTestClass_short_i_e_fc_Conv temp = new BasicSelectionTestClass_short_i_e_fc_Conv(); temp.value_ulong = val; return (temp); } public ulong GetValueulong() { return (value_ulong); } public void SetValueulong(ulong val) { value_ulong = val; } private ushort value_ushort; static public implicit operator ushort(BasicSelectionTestClass_short_i_e_fc_Conv test) { Log.Comment("To ushort"); return test.value_ushort; } static public implicit operator BasicSelectionTestClass_short_i_e_fc_Conv(ushort val) { Log.Comment("From ushort"); BasicSelectionTestClass_short_i_e_fc_Conv temp = new BasicSelectionTestClass_short_i_e_fc_Conv(); temp.value_ushort = val; return (temp); } public ushort GetValueushort() { return (value_ushort); } public void SetValueushort(ushort val) { value_ushort = val; } } class BasicSelectionTestClass_short_i_e_fc { public static int Main_old() { BasicSelectionTestClass_short_i_e_fc_Conv cl = new BasicSelectionTestClass_short_i_e_fc_Conv(); cl.SetValueshort(1); short value = (short)cl; if (value != 1) return 1; else return 0; } public static bool testMethod() { return (Main_old() == 0); } } class BasicSelectionTestClass_short_e_e_fc_Conv { private byte value_byte; static public explicit operator byte(BasicSelectionTestClass_short_e_e_fc_Conv test) { Log.Comment("To byte"); return test.value_byte; } static public explicit operator BasicSelectionTestClass_short_e_e_fc_Conv(byte val) { Log.Comment("From byte"); BasicSelectionTestClass_short_e_e_fc_Conv temp = new BasicSelectionTestClass_short_e_e_fc_Conv(); temp.value_byte = val; return (temp); } public byte GetValuebyte() { return (value_byte); } public void SetValuebyte(byte val) { value_byte = val; } private char value_char; static public explicit operator char(BasicSelectionTestClass_short_e_e_fc_Conv test) { Log.Comment("To char"); return test.value_char; } static public explicit operator BasicSelectionTestClass_short_e_e_fc_Conv(char val) { Log.Comment("From char"); BasicSelectionTestClass_short_e_e_fc_Conv temp = new BasicSelectionTestClass_short_e_e_fc_Conv(); temp.value_char = val; return (temp); } public char GetValuechar() { return (value_char); } public void SetValuechar(char val) { value_char = val; } private double value_double; static public explicit operator double(BasicSelectionTestClass_short_e_e_fc_Conv test) { Log.Comment("To double"); return test.value_double; } static public explicit operator BasicSelectionTestClass_short_e_e_fc_Conv(double val) { Log.Comment("From double"); BasicSelectionTestClass_short_e_e_fc_Conv temp = new BasicSelectionTestClass_short_e_e_fc_Conv(); temp.value_double = val; return (temp); } public double GetValuedouble() { return (value_double); } public void SetValuedouble(double val) { value_double = val; } private float value_float; static public explicit operator float(BasicSelectionTestClass_short_e_e_fc_Conv test) { Log.Comment("To float"); return test.value_float; } static public explicit operator BasicSelectionTestClass_short_e_e_fc_Conv(float val) { Log.Comment("From float"); BasicSelectionTestClass_short_e_e_fc_Conv temp = new BasicSelectionTestClass_short_e_e_fc_Conv(); temp.value_float = val; return (temp); } public float GetValuefloat() { return (value_float); } public void SetValuefloat(float val) { value_float = val; } private int value_int; static public explicit operator int(BasicSelectionTestClass_short_e_e_fc_Conv test) { Log.Comment("To int"); return test.value_int; } static public explicit operator BasicSelectionTestClass_short_e_e_fc_Conv(int val) { Log.Comment("From int"); BasicSelectionTestClass_short_e_e_fc_Conv temp = new BasicSelectionTestClass_short_e_e_fc_Conv(); temp.value_int = val; return (temp); } public int GetValueint() { return (value_int); } public void SetValueint(int val) { value_int = val; } private long value_long; static public explicit operator long(BasicSelectionTestClass_short_e_e_fc_Conv test) { Log.Comment("To long"); return test.value_long; } static public explicit operator BasicSelectionTestClass_short_e_e_fc_Conv(long val) { Log.Comment("From long"); BasicSelectionTestClass_short_e_e_fc_Conv temp = new BasicSelectionTestClass_short_e_e_fc_Conv(); temp.value_long = val; return (temp); } public long GetValuelong() { return (value_long); } public void SetValuelong(long val) { value_long = val; } private sbyte value_sbyte; static public explicit operator sbyte(BasicSelectionTestClass_short_e_e_fc_Conv test) { Log.Comment("To sbyte"); return test.value_sbyte; } static public explicit operator BasicSelectionTestClass_short_e_e_fc_Conv(sbyte val) { Log.Comment("From sbyte"); BasicSelectionTestClass_short_e_e_fc_Conv temp = new BasicSelectionTestClass_short_e_e_fc_Conv(); temp.value_sbyte = val; return (temp); } public sbyte GetValuesbyte() { return (value_sbyte); } public void SetValuesbyte(sbyte val) { value_sbyte = val; } private short value_short; static public explicit operator short(BasicSelectionTestClass_short_e_e_fc_Conv test) { Log.Comment("To short"); return test.value_short; } static public explicit operator BasicSelectionTestClass_short_e_e_fc_Conv(short val) { Log.Comment("From short"); BasicSelectionTestClass_short_e_e_fc_Conv temp = new BasicSelectionTestClass_short_e_e_fc_Conv(); temp.value_short = val; return (temp); } public short GetValueshort() { return (value_short); } public void SetValueshort(short val) { value_short = val; } private uint value_uint; static public explicit operator uint(BasicSelectionTestClass_short_e_e_fc_Conv test) { Log.Comment("To uint"); return test.value_uint; } static public explicit operator BasicSelectionTestClass_short_e_e_fc_Conv(uint val) { Log.Comment("From uint"); BasicSelectionTestClass_short_e_e_fc_Conv temp = new BasicSelectionTestClass_short_e_e_fc_Conv(); temp.value_uint = val; return (temp); } public uint GetValueuint() { return (value_uint); } public void SetValueuint(uint val) { value_uint = val; } private ulong value_ulong; static public explicit operator ulong(BasicSelectionTestClass_short_e_e_fc_Conv test) { Log.Comment("To ulong"); return test.value_ulong; } static public explicit operator BasicSelectionTestClass_short_e_e_fc_Conv(ulong val) { Log.Comment("From ulong"); BasicSelectionTestClass_short_e_e_fc_Conv temp = new BasicSelectionTestClass_short_e_e_fc_Conv(); temp.value_ulong = val; return (temp); } public ulong GetValueulong() { return (value_ulong); } public void SetValueulong(ulong val) { value_ulong = val; } private ushort value_ushort; static public explicit operator ushort(BasicSelectionTestClass_short_e_e_fc_Conv test) { Log.Comment("To ushort"); return test.value_ushort; } static public explicit operator BasicSelectionTestClass_short_e_e_fc_Conv(ushort val) { Log.Comment("From ushort"); BasicSelectionTestClass_short_e_e_fc_Conv temp = new BasicSelectionTestClass_short_e_e_fc_Conv(); temp.value_ushort = val; return (temp); } public ushort GetValueushort() { return (value_ushort); } public void SetValueushort(ushort val) { value_ushort = val; } } class BasicSelectionTestClass_short_e_e_fc { public static int Main_old() { BasicSelectionTestClass_short_e_e_fc_Conv cl = new BasicSelectionTestClass_short_e_e_fc_Conv(); cl.SetValueshort(1); short value = (short)cl; if (value != 1) return 1; else return 0; } public static bool testMethod() { return (Main_old() == 0); } } class BasicSelectionTestClass_uint_i_i_tc_Conv { private byte value_byte; static public implicit operator byte(BasicSelectionTestClass_uint_i_i_tc_Conv test) { Log.Comment("To byte"); return test.value_byte; } static public implicit operator BasicSelectionTestClass_uint_i_i_tc_Conv(byte val) { Log.Comment("From byte"); BasicSelectionTestClass_uint_i_i_tc_Conv temp = new BasicSelectionTestClass_uint_i_i_tc_Conv(); temp.value_byte = val; return (temp); } public byte GetValuebyte() { return (value_byte); } public void SetValuebyte(byte val) { value_byte = val; } private char value_char; static public implicit operator char(BasicSelectionTestClass_uint_i_i_tc_Conv test) { Log.Comment("To char"); return test.value_char; } static public implicit operator BasicSelectionTestClass_uint_i_i_tc_Conv(char val) { Log.Comment("From char"); BasicSelectionTestClass_uint_i_i_tc_Conv temp = new BasicSelectionTestClass_uint_i_i_tc_Conv(); temp.value_char = val; return (temp); } public char GetValuechar() { return (value_char); } public void SetValuechar(char val) { value_char = val; } private double value_double; static public implicit operator double(BasicSelectionTestClass_uint_i_i_tc_Conv test) { Log.Comment("To double"); return test.value_double; } static public implicit operator BasicSelectionTestClass_uint_i_i_tc_Conv(double val) { Log.Comment("From double"); BasicSelectionTestClass_uint_i_i_tc_Conv temp = new BasicSelectionTestClass_uint_i_i_tc_Conv(); temp.value_double = val; return (temp); } public double GetValuedouble() { return (value_double); } public void SetValuedouble(double val) { value_double = val; } private float value_float; static public implicit operator float(BasicSelectionTestClass_uint_i_i_tc_Conv test) { Log.Comment("To float"); return test.value_float; } static public implicit operator BasicSelectionTestClass_uint_i_i_tc_Conv(float val) { Log.Comment("From float"); BasicSelectionTestClass_uint_i_i_tc_Conv temp = new BasicSelectionTestClass_uint_i_i_tc_Conv(); temp.value_float = val; return (temp); } public float GetValuefloat() { return (value_float); } public void SetValuefloat(float val) { value_float = val; } private int value_int; static public implicit operator int(BasicSelectionTestClass_uint_i_i_tc_Conv test) { Log.Comment("To int"); return test.value_int; } static public implicit operator BasicSelectionTestClass_uint_i_i_tc_Conv(int val) { Log.Comment("From int"); BasicSelectionTestClass_uint_i_i_tc_Conv temp = new BasicSelectionTestClass_uint_i_i_tc_Conv(); temp.value_int = val; return (temp); } public int GetValueint() { return (value_int); } public void SetValueint(int val) { value_int = val; } private long value_long; static public implicit operator long(BasicSelectionTestClass_uint_i_i_tc_Conv test) { Log.Comment("To long"); return test.value_long; } static public implicit operator BasicSelectionTestClass_uint_i_i_tc_Conv(long val) { Log.Comment("From long"); BasicSelectionTestClass_uint_i_i_tc_Conv temp = new BasicSelectionTestClass_uint_i_i_tc_Conv(); temp.value_long = val; return (temp); } public long GetValuelong() { return (value_long); } public void SetValuelong(long val) { value_long = val; } private sbyte value_sbyte; static public implicit operator sbyte(BasicSelectionTestClass_uint_i_i_tc_Conv test) { Log.Comment("To sbyte"); return test.value_sbyte; } static public implicit operator BasicSelectionTestClass_uint_i_i_tc_Conv(sbyte val) { Log.Comment("From sbyte"); BasicSelectionTestClass_uint_i_i_tc_Conv temp = new BasicSelectionTestClass_uint_i_i_tc_Conv(); temp.value_sbyte = val; return (temp); } public sbyte GetValuesbyte() { return (value_sbyte); } public void SetValuesbyte(sbyte val) { value_sbyte = val; } private short value_short; static public implicit operator short(BasicSelectionTestClass_uint_i_i_tc_Conv test) { Log.Comment("To short"); return test.value_short; } static public implicit operator BasicSelectionTestClass_uint_i_i_tc_Conv(short val) { Log.Comment("From short"); BasicSelectionTestClass_uint_i_i_tc_Conv temp = new BasicSelectionTestClass_uint_i_i_tc_Conv(); temp.value_short = val; return (temp); } public short GetValueshort() { return (value_short); } public void SetValueshort(short val) { value_short = val; } private uint value_uint; static public implicit operator uint(BasicSelectionTestClass_uint_i_i_tc_Conv test) { Log.Comment("To uint"); return test.value_uint; } static public implicit operator BasicSelectionTestClass_uint_i_i_tc_Conv(uint val) { Log.Comment("From uint"); BasicSelectionTestClass_uint_i_i_tc_Conv temp = new BasicSelectionTestClass_uint_i_i_tc_Conv(); temp.value_uint = val; return (temp); } public uint GetValueuint() { return (value_uint); } public void SetValueuint(uint val) { value_uint = val; } private ulong value_ulong; static public implicit operator ulong(BasicSelectionTestClass_uint_i_i_tc_Conv test) { Log.Comment("To ulong"); return test.value_ulong; } static public implicit operator BasicSelectionTestClass_uint_i_i_tc_Conv(ulong val) { Log.Comment("From ulong"); BasicSelectionTestClass_uint_i_i_tc_Conv temp = new BasicSelectionTestClass_uint_i_i_tc_Conv(); temp.value_ulong = val; return (temp); } public ulong GetValueulong() { return (value_ulong); } public void SetValueulong(ulong val) { value_ulong = val; } private ushort value_ushort; static public implicit operator ushort(BasicSelectionTestClass_uint_i_i_tc_Conv test) { Log.Comment("To ushort"); return test.value_ushort; } static public implicit operator BasicSelectionTestClass_uint_i_i_tc_Conv(ushort val) { Log.Comment("From ushort"); BasicSelectionTestClass_uint_i_i_tc_Conv temp = new BasicSelectionTestClass_uint_i_i_tc_Conv(); temp.value_ushort = val; return (temp); } public ushort GetValueushort() { return (value_ushort); } public void SetValueushort(ushort val) { value_ushort = val; } } class BasicSelectionTestClass_uint_i_i_tc { public static int Main_old() { BasicSelectionTestClass_uint_i_i_tc_Conv cl = new BasicSelectionTestClass_uint_i_i_tc_Conv(); uint val = 1; cl = val; if (cl.GetValueuint() != 1) return 1; else return 0; } public static bool testMethod() { return (Main_old() == 0); } } class BasicSelectionTestClass_uint_i_e_tc_Conv { private byte value_byte; static public implicit operator byte(BasicSelectionTestClass_uint_i_e_tc_Conv test) { Log.Comment("To byte"); return test.value_byte; } static public implicit operator BasicSelectionTestClass_uint_i_e_tc_Conv(byte val) { Log.Comment("From byte"); BasicSelectionTestClass_uint_i_e_tc_Conv temp = new BasicSelectionTestClass_uint_i_e_tc_Conv(); temp.value_byte = val; return (temp); } public byte GetValuebyte() { return (value_byte); } public void SetValuebyte(byte val) { value_byte = val; } private char value_char; static public implicit operator char(BasicSelectionTestClass_uint_i_e_tc_Conv test) { Log.Comment("To char"); return test.value_char; } static public implicit operator BasicSelectionTestClass_uint_i_e_tc_Conv(char val) { Log.Comment("From char"); BasicSelectionTestClass_uint_i_e_tc_Conv temp = new BasicSelectionTestClass_uint_i_e_tc_Conv(); temp.value_char = val; return (temp); } public char GetValuechar() { return (value_char); } public void SetValuechar(char val) { value_char = val; } private double value_double; static public implicit operator double(BasicSelectionTestClass_uint_i_e_tc_Conv test) { Log.Comment("To double"); return test.value_double; } static public implicit operator BasicSelectionTestClass_uint_i_e_tc_Conv(double val) { Log.Comment("From double"); BasicSelectionTestClass_uint_i_e_tc_Conv temp = new BasicSelectionTestClass_uint_i_e_tc_Conv(); temp.value_double = val; return (temp); } public double GetValuedouble() { return (value_double); } public void SetValuedouble(double val) { value_double = val; } private float value_float; static public implicit operator float(BasicSelectionTestClass_uint_i_e_tc_Conv test) { Log.Comment("To float"); return test.value_float; } static public implicit operator BasicSelectionTestClass_uint_i_e_tc_Conv(float val) { Log.Comment("From float"); BasicSelectionTestClass_uint_i_e_tc_Conv temp = new BasicSelectionTestClass_uint_i_e_tc_Conv(); temp.value_float = val; return (temp); } public float GetValuefloat() { return (value_float); } public void SetValuefloat(float val) { value_float = val; } private int value_int; static public implicit operator int(BasicSelectionTestClass_uint_i_e_tc_Conv test) { Log.Comment("To int"); return test.value_int; } static public implicit operator BasicSelectionTestClass_uint_i_e_tc_Conv(int val) { Log.Comment("From int"); BasicSelectionTestClass_uint_i_e_tc_Conv temp = new BasicSelectionTestClass_uint_i_e_tc_Conv(); temp.value_int = val; return (temp); } public int GetValueint() { return (value_int); } public void SetValueint(int val) { value_int = val; } private long value_long; static public implicit operator long(BasicSelectionTestClass_uint_i_e_tc_Conv test) { Log.Comment("To long"); return test.value_long; } static public implicit operator BasicSelectionTestClass_uint_i_e_tc_Conv(long val) { Log.Comment("From long"); BasicSelectionTestClass_uint_i_e_tc_Conv temp = new BasicSelectionTestClass_uint_i_e_tc_Conv(); temp.value_long = val; return (temp); } public long GetValuelong() { return (value_long); } public void SetValuelong(long val) { value_long = val; } private sbyte value_sbyte; static public implicit operator sbyte(BasicSelectionTestClass_uint_i_e_tc_Conv test) { Log.Comment("To sbyte"); return test.value_sbyte; } static public implicit operator BasicSelectionTestClass_uint_i_e_tc_Conv(sbyte val) { Log.Comment("From sbyte"); BasicSelectionTestClass_uint_i_e_tc_Conv temp = new BasicSelectionTestClass_uint_i_e_tc_Conv(); temp.value_sbyte = val; return (temp); } public sbyte GetValuesbyte() { return (value_sbyte); } public void SetValuesbyte(sbyte val) { value_sbyte = val; } private short value_short; static public implicit operator short(BasicSelectionTestClass_uint_i_e_tc_Conv test) { Log.Comment("To short"); return test.value_short; } static public implicit operator BasicSelectionTestClass_uint_i_e_tc_Conv(short val) { Log.Comment("From short"); BasicSelectionTestClass_uint_i_e_tc_Conv temp = new BasicSelectionTestClass_uint_i_e_tc_Conv(); temp.value_short = val; return (temp); } public short GetValueshort() { return (value_short); } public void SetValueshort(short val) { value_short = val; } private uint value_uint; static public implicit operator uint(BasicSelectionTestClass_uint_i_e_tc_Conv test) { Log.Comment("To uint"); return test.value_uint; } static public implicit operator BasicSelectionTestClass_uint_i_e_tc_Conv(uint val) { Log.Comment("From uint"); BasicSelectionTestClass_uint_i_e_tc_Conv temp = new BasicSelectionTestClass_uint_i_e_tc_Conv(); temp.value_uint = val; return (temp); } public uint GetValueuint() { return (value_uint); } public void SetValueuint(uint val) { value_uint = val; } private ulong value_ulong; static public implicit operator ulong(BasicSelectionTestClass_uint_i_e_tc_Conv test) { Log.Comment("To ulong"); return test.value_ulong; } static public implicit operator BasicSelectionTestClass_uint_i_e_tc_Conv(ulong val) { Log.Comment("From ulong"); BasicSelectionTestClass_uint_i_e_tc_Conv temp = new BasicSelectionTestClass_uint_i_e_tc_Conv(); temp.value_ulong = val; return (temp); } public ulong GetValueulong() { return (value_ulong); } public void SetValueulong(ulong val) { value_ulong = val; } private ushort value_ushort; static public implicit operator ushort(BasicSelectionTestClass_uint_i_e_tc_Conv test) { Log.Comment("To ushort"); return test.value_ushort; } static public implicit operator BasicSelectionTestClass_uint_i_e_tc_Conv(ushort val) { Log.Comment("From ushort"); BasicSelectionTestClass_uint_i_e_tc_Conv temp = new BasicSelectionTestClass_uint_i_e_tc_Conv(); temp.value_ushort = val; return (temp); } public ushort GetValueushort() { return (value_ushort); } public void SetValueushort(ushort val) { value_ushort = val; } } class BasicSelectionTestClass_uint_i_e_tc { public static int Main_old() { BasicSelectionTestClass_uint_i_e_tc_Conv cl = new BasicSelectionTestClass_uint_i_e_tc_Conv(); uint val = 1; cl = (BasicSelectionTestClass_uint_i_e_tc_Conv)val; if (cl.GetValueuint() != 1) return 1; else return 0; } public static bool testMethod() { return (Main_old() == 0); } } class BasicSelectionTestClass_uint_e_e_tc_Conv { private byte value_byte; static public explicit operator byte(BasicSelectionTestClass_uint_e_e_tc_Conv test) { Log.Comment("To byte"); return test.value_byte; } static public explicit operator BasicSelectionTestClass_uint_e_e_tc_Conv(byte val) { Log.Comment("From byte"); BasicSelectionTestClass_uint_e_e_tc_Conv temp = new BasicSelectionTestClass_uint_e_e_tc_Conv(); temp.value_byte = val; return (temp); } public byte GetValuebyte() { return (value_byte); } public void SetValuebyte(byte val) { value_byte = val; } private char value_char; static public explicit operator char(BasicSelectionTestClass_uint_e_e_tc_Conv test) { Log.Comment("To char"); return test.value_char; } static public explicit operator BasicSelectionTestClass_uint_e_e_tc_Conv(char val) { Log.Comment("From char"); BasicSelectionTestClass_uint_e_e_tc_Conv temp = new BasicSelectionTestClass_uint_e_e_tc_Conv(); temp.value_char = val; return (temp); } public char GetValuechar() { return (value_char); } public void SetValuechar(char val) { value_char = val; } private double value_double; static public explicit operator double(BasicSelectionTestClass_uint_e_e_tc_Conv test) { Log.Comment("To double"); return test.value_double; } static public explicit operator BasicSelectionTestClass_uint_e_e_tc_Conv(double val) { Log.Comment("From double"); BasicSelectionTestClass_uint_e_e_tc_Conv temp = new BasicSelectionTestClass_uint_e_e_tc_Conv(); temp.value_double = val; return (temp); } public double GetValuedouble() { return (value_double); } public void SetValuedouble(double val) { value_double = val; } private float value_float; static public explicit operator float(BasicSelectionTestClass_uint_e_e_tc_Conv test) { Log.Comment("To float"); return test.value_float; } static public explicit operator BasicSelectionTestClass_uint_e_e_tc_Conv(float val) { Log.Comment("From float"); BasicSelectionTestClass_uint_e_e_tc_Conv temp = new BasicSelectionTestClass_uint_e_e_tc_Conv(); temp.value_float = val; return (temp); } public float GetValuefloat() { return (value_float); } public void SetValuefloat(float val) { value_float = val; } private int value_int; static public explicit operator int(BasicSelectionTestClass_uint_e_e_tc_Conv test) { Log.Comment("To int"); return test.value_int; } static public explicit operator BasicSelectionTestClass_uint_e_e_tc_Conv(int val) { Log.Comment("From int"); BasicSelectionTestClass_uint_e_e_tc_Conv temp = new BasicSelectionTestClass_uint_e_e_tc_Conv(); temp.value_int = val; return (temp); } public int GetValueint() { return (value_int); } public void SetValueint(int val) { value_int = val; } private long value_long; static public explicit operator long(BasicSelectionTestClass_uint_e_e_tc_Conv test) { Log.Comment("To long"); return test.value_long; } static public explicit operator BasicSelectionTestClass_uint_e_e_tc_Conv(long val) { Log.Comment("From long"); BasicSelectionTestClass_uint_e_e_tc_Conv temp = new BasicSelectionTestClass_uint_e_e_tc_Conv(); temp.value_long = val; return (temp); } public long GetValuelong() { return (value_long); } public void SetValuelong(long val) { value_long = val; } private sbyte value_sbyte; static public explicit operator sbyte(BasicSelectionTestClass_uint_e_e_tc_Conv test) { Log.Comment("To sbyte"); return test.value_sbyte; } static public explicit operator BasicSelectionTestClass_uint_e_e_tc_Conv(sbyte val) { Log.Comment("From sbyte"); BasicSelectionTestClass_uint_e_e_tc_Conv temp = new BasicSelectionTestClass_uint_e_e_tc_Conv(); temp.value_sbyte = val; return (temp); } public sbyte GetValuesbyte() { return (value_sbyte); } public void SetValuesbyte(sbyte val) { value_sbyte = val; } private short value_short; static public explicit operator short(BasicSelectionTestClass_uint_e_e_tc_Conv test) { Log.Comment("To short"); return test.value_short; } static public explicit operator BasicSelectionTestClass_uint_e_e_tc_Conv(short val) { Log.Comment("From short"); BasicSelectionTestClass_uint_e_e_tc_Conv temp = new BasicSelectionTestClass_uint_e_e_tc_Conv(); temp.value_short = val; return (temp); } public short GetValueshort() { return (value_short); } public void SetValueshort(short val) { value_short = val; } private uint value_uint; static public explicit operator uint(BasicSelectionTestClass_uint_e_e_tc_Conv test) { Log.Comment("To uint"); return test.value_uint; } static public explicit operator BasicSelectionTestClass_uint_e_e_tc_Conv(uint val) { Log.Comment("From uint"); BasicSelectionTestClass_uint_e_e_tc_Conv temp = new BasicSelectionTestClass_uint_e_e_tc_Conv(); temp.value_uint = val; return (temp); } public uint GetValueuint() { return (value_uint); } public void SetValueuint(uint val) { value_uint = val; } private ulong value_ulong; static public explicit operator ulong(BasicSelectionTestClass_uint_e_e_tc_Conv test) { Log.Comment("To ulong"); return test.value_ulong; } static public explicit operator BasicSelectionTestClass_uint_e_e_tc_Conv(ulong val) { Log.Comment("From ulong"); BasicSelectionTestClass_uint_e_e_tc_Conv temp = new BasicSelectionTestClass_uint_e_e_tc_Conv(); temp.value_ulong = val; return (temp); } public ulong GetValueulong() { return (value_ulong); } public void SetValueulong(ulong val) { value_ulong = val; } private ushort value_ushort; static public explicit operator ushort(BasicSelectionTestClass_uint_e_e_tc_Conv test) { Log.Comment("To ushort"); return test.value_ushort; } static public explicit operator BasicSelectionTestClass_uint_e_e_tc_Conv(ushort val) { Log.Comment("From ushort"); BasicSelectionTestClass_uint_e_e_tc_Conv temp = new BasicSelectionTestClass_uint_e_e_tc_Conv(); temp.value_ushort = val; return (temp); } public ushort GetValueushort() { return (value_ushort); } public void SetValueushort(ushort val) { value_ushort = val; } } class BasicSelectionTestClass_uint_e_e_tc { public static int Main_old() { BasicSelectionTestClass_uint_e_e_tc_Conv cl = new BasicSelectionTestClass_uint_e_e_tc_Conv(); uint val = 1; cl = (BasicSelectionTestClass_uint_e_e_tc_Conv)val; if (cl.GetValueuint() != 1) return 1; else return 0; } public static bool testMethod() { return (Main_old() == 0); } } class BasicSelectionTestClass_uint_i_i_fc_Conv { private byte value_byte; static public implicit operator byte(BasicSelectionTestClass_uint_i_i_fc_Conv test) { Log.Comment("To byte"); return test.value_byte; } static public implicit operator BasicSelectionTestClass_uint_i_i_fc_Conv(byte val) { Log.Comment("From byte"); BasicSelectionTestClass_uint_i_i_fc_Conv temp = new BasicSelectionTestClass_uint_i_i_fc_Conv(); temp.value_byte = val; return (temp); } public byte GetValuebyte() { return (value_byte); } public void SetValuebyte(byte val) { value_byte = val; } private char value_char; static public implicit operator char(BasicSelectionTestClass_uint_i_i_fc_Conv test) { Log.Comment("To char"); return test.value_char; } static public implicit operator BasicSelectionTestClass_uint_i_i_fc_Conv(char val) { Log.Comment("From char"); BasicSelectionTestClass_uint_i_i_fc_Conv temp = new BasicSelectionTestClass_uint_i_i_fc_Conv(); temp.value_char = val; return (temp); } public char GetValuechar() { return (value_char); } public void SetValuechar(char val) { value_char = val; } private double value_double; static public implicit operator double(BasicSelectionTestClass_uint_i_i_fc_Conv test) { Log.Comment("To double"); return test.value_double; } static public implicit operator BasicSelectionTestClass_uint_i_i_fc_Conv(double val) { Log.Comment("From double"); BasicSelectionTestClass_uint_i_i_fc_Conv temp = new BasicSelectionTestClass_uint_i_i_fc_Conv(); temp.value_double = val; return (temp); } public double GetValuedouble() { return (value_double); } public void SetValuedouble(double val) { value_double = val; } private float value_float; static public implicit operator float(BasicSelectionTestClass_uint_i_i_fc_Conv test) { Log.Comment("To float"); return test.value_float; } static public implicit operator BasicSelectionTestClass_uint_i_i_fc_Conv(float val) { Log.Comment("From float"); BasicSelectionTestClass_uint_i_i_fc_Conv temp = new BasicSelectionTestClass_uint_i_i_fc_Conv(); temp.value_float = val; return (temp); } public float GetValuefloat() { return (value_float); } public void SetValuefloat(float val) { value_float = val; } private int value_int; static public implicit operator int(BasicSelectionTestClass_uint_i_i_fc_Conv test) { Log.Comment("To int"); return test.value_int; } static public implicit operator BasicSelectionTestClass_uint_i_i_fc_Conv(int val) { Log.Comment("From int"); BasicSelectionTestClass_uint_i_i_fc_Conv temp = new BasicSelectionTestClass_uint_i_i_fc_Conv(); temp.value_int = val; return (temp); } public int GetValueint() { return (value_int); } public void SetValueint(int val) { value_int = val; } private long value_long; static public implicit operator long(BasicSelectionTestClass_uint_i_i_fc_Conv test) { Log.Comment("To long"); return test.value_long; } static public implicit operator BasicSelectionTestClass_uint_i_i_fc_Conv(long val) { Log.Comment("From long"); BasicSelectionTestClass_uint_i_i_fc_Conv temp = new BasicSelectionTestClass_uint_i_i_fc_Conv(); temp.value_long = val; return (temp); } public long GetValuelong() { return (value_long); } public void SetValuelong(long val) { value_long = val; } private sbyte value_sbyte; static public implicit operator sbyte(BasicSelectionTestClass_uint_i_i_fc_Conv test) { Log.Comment("To sbyte"); return test.value_sbyte; } static public implicit operator BasicSelectionTestClass_uint_i_i_fc_Conv(sbyte val) { Log.Comment("From sbyte"); BasicSelectionTestClass_uint_i_i_fc_Conv temp = new BasicSelectionTestClass_uint_i_i_fc_Conv(); temp.value_sbyte = val; return (temp); } public sbyte GetValuesbyte() { return (value_sbyte); } public void SetValuesbyte(sbyte val) { value_sbyte = val; } private short value_short; static public implicit operator short(BasicSelectionTestClass_uint_i_i_fc_Conv test) { Log.Comment("To short"); return test.value_short; } static public implicit operator BasicSelectionTestClass_uint_i_i_fc_Conv(short val) { Log.Comment("From short"); BasicSelectionTestClass_uint_i_i_fc_Conv temp = new BasicSelectionTestClass_uint_i_i_fc_Conv(); temp.value_short = val; return (temp); } public short GetValueshort() { return (value_short); } public void SetValueshort(short val) { value_short = val; } private uint value_uint; static public implicit operator uint(BasicSelectionTestClass_uint_i_i_fc_Conv test) { Log.Comment("To uint"); return test.value_uint; } static public implicit operator BasicSelectionTestClass_uint_i_i_fc_Conv(uint val) { Log.Comment("From uint"); BasicSelectionTestClass_uint_i_i_fc_Conv temp = new BasicSelectionTestClass_uint_i_i_fc_Conv(); temp.value_uint = val; return (temp); } public uint GetValueuint() { return (value_uint); } public void SetValueuint(uint val) { value_uint = val; } private ulong value_ulong; static public implicit operator ulong(BasicSelectionTestClass_uint_i_i_fc_Conv test) { Log.Comment("To ulong"); return test.value_ulong; } static public implicit operator BasicSelectionTestClass_uint_i_i_fc_Conv(ulong val) { Log.Comment("From ulong"); BasicSelectionTestClass_uint_i_i_fc_Conv temp = new BasicSelectionTestClass_uint_i_i_fc_Conv(); temp.value_ulong = val; return (temp); } public ulong GetValueulong() { return (value_ulong); } public void SetValueulong(ulong val) { value_ulong = val; } private ushort value_ushort; static public implicit operator ushort(BasicSelectionTestClass_uint_i_i_fc_Conv test) { Log.Comment("To ushort"); return test.value_ushort; } static public implicit operator BasicSelectionTestClass_uint_i_i_fc_Conv(ushort val) { Log.Comment("From ushort"); BasicSelectionTestClass_uint_i_i_fc_Conv temp = new BasicSelectionTestClass_uint_i_i_fc_Conv(); temp.value_ushort = val; return (temp); } public ushort GetValueushort() { return (value_ushort); } public void SetValueushort(ushort val) { value_ushort = val; } } class BasicSelectionTestClass_uint_i_i_fc { public static int Main_old() { BasicSelectionTestClass_uint_i_i_fc_Conv cl = new BasicSelectionTestClass_uint_i_i_fc_Conv(); cl.SetValueuint(1); uint value = cl; if (value != 1) return 1; else return 0; } public static bool testMethod() { return (Main_old() == 0); } } class BasicSelectionTestClass_uint_i_e_fc_Conv { private byte value_byte; static public implicit operator byte(BasicSelectionTestClass_uint_i_e_fc_Conv test) { Log.Comment("To byte"); return test.value_byte; } static public implicit operator BasicSelectionTestClass_uint_i_e_fc_Conv(byte val) { Log.Comment("From byte"); BasicSelectionTestClass_uint_i_e_fc_Conv temp = new BasicSelectionTestClass_uint_i_e_fc_Conv(); temp.value_byte = val; return (temp); } public byte GetValuebyte() { return (value_byte); } public void SetValuebyte(byte val) { value_byte = val; } private char value_char; static public implicit operator char(BasicSelectionTestClass_uint_i_e_fc_Conv test) { Log.Comment("To char"); return test.value_char; } static public implicit operator BasicSelectionTestClass_uint_i_e_fc_Conv(char val) { Log.Comment("From char"); BasicSelectionTestClass_uint_i_e_fc_Conv temp = new BasicSelectionTestClass_uint_i_e_fc_Conv(); temp.value_char = val; return (temp); } public char GetValuechar() { return (value_char); } public void SetValuechar(char val) { value_char = val; } private double value_double; static public implicit operator double(BasicSelectionTestClass_uint_i_e_fc_Conv test) { Log.Comment("To double"); return test.value_double; } static public implicit operator BasicSelectionTestClass_uint_i_e_fc_Conv(double val) { Log.Comment("From double"); BasicSelectionTestClass_uint_i_e_fc_Conv temp = new BasicSelectionTestClass_uint_i_e_fc_Conv(); temp.value_double = val; return (temp); } public double GetValuedouble() { return (value_double); } public void SetValuedouble(double val) { value_double = val; } private float value_float; static public implicit operator float(BasicSelectionTestClass_uint_i_e_fc_Conv test) { Log.Comment("To float"); return test.value_float; } static public implicit operator BasicSelectionTestClass_uint_i_e_fc_Conv(float val) { Log.Comment("From float"); BasicSelectionTestClass_uint_i_e_fc_Conv temp = new BasicSelectionTestClass_uint_i_e_fc_Conv(); temp.value_float = val; return (temp); } public float GetValuefloat() { return (value_float); } public void SetValuefloat(float val) { value_float = val; } private int value_int; static public implicit operator int(BasicSelectionTestClass_uint_i_e_fc_Conv test) { Log.Comment("To int"); return test.value_int; } static public implicit operator BasicSelectionTestClass_uint_i_e_fc_Conv(int val) { Log.Comment("From int"); BasicSelectionTestClass_uint_i_e_fc_Conv temp = new BasicSelectionTestClass_uint_i_e_fc_Conv(); temp.value_int = val; return (temp); } public int GetValueint() { return (value_int); } public void SetValueint(int val) { value_int = val; } private long value_long; static public implicit operator long(BasicSelectionTestClass_uint_i_e_fc_Conv test) { Log.Comment("To long"); return test.value_long; } static public implicit operator BasicSelectionTestClass_uint_i_e_fc_Conv(long val) { Log.Comment("From long"); BasicSelectionTestClass_uint_i_e_fc_Conv temp = new BasicSelectionTestClass_uint_i_e_fc_Conv(); temp.value_long = val; return (temp); } public long GetValuelong() { return (value_long); } public void SetValuelong(long val) { value_long = val; } private sbyte value_sbyte; static public implicit operator sbyte(BasicSelectionTestClass_uint_i_e_fc_Conv test) { Log.Comment("To sbyte"); return test.value_sbyte; } static public implicit operator BasicSelectionTestClass_uint_i_e_fc_Conv(sbyte val) { Log.Comment("From sbyte"); BasicSelectionTestClass_uint_i_e_fc_Conv temp = new BasicSelectionTestClass_uint_i_e_fc_Conv(); temp.value_sbyte = val; return (temp); } public sbyte GetValuesbyte() { return (value_sbyte); } public void SetValuesbyte(sbyte val) { value_sbyte = val; } private short value_short; static public implicit operator short(BasicSelectionTestClass_uint_i_e_fc_Conv test) { Log.Comment("To short"); return test.value_short; } static public implicit operator BasicSelectionTestClass_uint_i_e_fc_Conv(short val) { Log.Comment("From short"); BasicSelectionTestClass_uint_i_e_fc_Conv temp = new BasicSelectionTestClass_uint_i_e_fc_Conv(); temp.value_short = val; return (temp); } public short GetValueshort() { return (value_short); } public void SetValueshort(short val) { value_short = val; } private uint value_uint; static public implicit operator uint(BasicSelectionTestClass_uint_i_e_fc_Conv test) { Log.Comment("To uint"); return test.value_uint; } static public implicit operator BasicSelectionTestClass_uint_i_e_fc_Conv(uint val) { Log.Comment("From uint"); BasicSelectionTestClass_uint_i_e_fc_Conv temp = new BasicSelectionTestClass_uint_i_e_fc_Conv(); temp.value_uint = val; return (temp); } public uint GetValueuint() { return (value_uint); } public void SetValueuint(uint val) { value_uint = val; } private ulong value_ulong; static public implicit operator ulong(BasicSelectionTestClass_uint_i_e_fc_Conv test) { Log.Comment("To ulong"); return test.value_ulong; } static public implicit operator BasicSelectionTestClass_uint_i_e_fc_Conv(ulong val) { Log.Comment("From ulong"); BasicSelectionTestClass_uint_i_e_fc_Conv temp = new BasicSelectionTestClass_uint_i_e_fc_Conv(); temp.value_ulong = val; return (temp); } public ulong GetValueulong() { return (value_ulong); } public void SetValueulong(ulong val) { value_ulong = val; } private ushort value_ushort; static public implicit operator ushort(BasicSelectionTestClass_uint_i_e_fc_Conv test) { Log.Comment("To ushort"); return test.value_ushort; } static public implicit operator BasicSelectionTestClass_uint_i_e_fc_Conv(ushort val) { Log.Comment("From ushort"); BasicSelectionTestClass_uint_i_e_fc_Conv temp = new BasicSelectionTestClass_uint_i_e_fc_Conv(); temp.value_ushort = val; return (temp); } public ushort GetValueushort() { return (value_ushort); } public void SetValueushort(ushort val) { value_ushort = val; } } class BasicSelectionTestClass_uint_i_e_fc { public static int Main_old() { BasicSelectionTestClass_uint_i_e_fc_Conv cl = new BasicSelectionTestClass_uint_i_e_fc_Conv(); cl.SetValueuint(1); uint value = (uint)cl; if (value != 1) return 1; else return 0; } public static bool testMethod() { return (Main_old() == 0); } } class BasicSelectionTestClass_uint_e_e_fc_Conv { private byte value_byte; static public explicit operator byte(BasicSelectionTestClass_uint_e_e_fc_Conv test) { Log.Comment("To byte"); return test.value_byte; } static public explicit operator BasicSelectionTestClass_uint_e_e_fc_Conv(byte val) { Log.Comment("From byte"); BasicSelectionTestClass_uint_e_e_fc_Conv temp = new BasicSelectionTestClass_uint_e_e_fc_Conv(); temp.value_byte = val; return (temp); } public byte GetValuebyte() { return (value_byte); } public void SetValuebyte(byte val) { value_byte = val; } private char value_char; static public explicit operator char(BasicSelectionTestClass_uint_e_e_fc_Conv test) { Log.Comment("To char"); return test.value_char; } static public explicit operator BasicSelectionTestClass_uint_e_e_fc_Conv(char val) { Log.Comment("From char"); BasicSelectionTestClass_uint_e_e_fc_Conv temp = new BasicSelectionTestClass_uint_e_e_fc_Conv(); temp.value_char = val; return (temp); } public char GetValuechar() { return (value_char); } public void SetValuechar(char val) { value_char = val; } private double value_double; static public explicit operator double(BasicSelectionTestClass_uint_e_e_fc_Conv test) { Log.Comment("To double"); return test.value_double; } static public explicit operator BasicSelectionTestClass_uint_e_e_fc_Conv(double val) { Log.Comment("From double"); BasicSelectionTestClass_uint_e_e_fc_Conv temp = new BasicSelectionTestClass_uint_e_e_fc_Conv(); temp.value_double = val; return (temp); } public double GetValuedouble() { return (value_double); } public void SetValuedouble(double val) { value_double = val; } private float value_float; static public explicit operator float(BasicSelectionTestClass_uint_e_e_fc_Conv test) { Log.Comment("To float"); return test.value_float; } static public explicit operator BasicSelectionTestClass_uint_e_e_fc_Conv(float val) { Log.Comment("From float"); BasicSelectionTestClass_uint_e_e_fc_Conv temp = new BasicSelectionTestClass_uint_e_e_fc_Conv(); temp.value_float = val; return (temp); } public float GetValuefloat() { return (value_float); } public void SetValuefloat(float val) { value_float = val; } private int value_int; static public explicit operator int(BasicSelectionTestClass_uint_e_e_fc_Conv test) { Log.Comment("To int"); return test.value_int; } static public explicit operator BasicSelectionTestClass_uint_e_e_fc_Conv(int val) { Log.Comment("From int"); BasicSelectionTestClass_uint_e_e_fc_Conv temp = new BasicSelectionTestClass_uint_e_e_fc_Conv(); temp.value_int = val; return (temp); } public int GetValueint() { return (value_int); } public void SetValueint(int val) { value_int = val; } private long value_long; static public explicit operator long(BasicSelectionTestClass_uint_e_e_fc_Conv test) { Log.Comment("To long"); return test.value_long; } static public explicit operator BasicSelectionTestClass_uint_e_e_fc_Conv(long val) { Log.Comment("From long"); BasicSelectionTestClass_uint_e_e_fc_Conv temp = new BasicSelectionTestClass_uint_e_e_fc_Conv(); temp.value_long = val; return (temp); } public long GetValuelong() { return (value_long); } public void SetValuelong(long val) { value_long = val; } private sbyte value_sbyte; static public explicit operator sbyte(BasicSelectionTestClass_uint_e_e_fc_Conv test) { Log.Comment("To sbyte"); return test.value_sbyte; } static public explicit operator BasicSelectionTestClass_uint_e_e_fc_Conv(sbyte val) { Log.Comment("From sbyte"); BasicSelectionTestClass_uint_e_e_fc_Conv temp = new BasicSelectionTestClass_uint_e_e_fc_Conv(); temp.value_sbyte = val; return (temp); } public sbyte GetValuesbyte() { return (value_sbyte); } public void SetValuesbyte(sbyte val) { value_sbyte = val; } private short value_short; static public explicit operator short(BasicSelectionTestClass_uint_e_e_fc_Conv test) { Log.Comment("To short"); return test.value_short; } static public explicit operator BasicSelectionTestClass_uint_e_e_fc_Conv(short val) { Log.Comment("From short"); BasicSelectionTestClass_uint_e_e_fc_Conv temp = new BasicSelectionTestClass_uint_e_e_fc_Conv(); temp.value_short = val; return (temp); } public short GetValueshort() { return (value_short); } public void SetValueshort(short val) { value_short = val; } private uint value_uint; static public explicit operator uint(BasicSelectionTestClass_uint_e_e_fc_Conv test) { Log.Comment("To uint"); return test.value_uint; } static public explicit operator BasicSelectionTestClass_uint_e_e_fc_Conv(uint val) { Log.Comment("From uint"); BasicSelectionTestClass_uint_e_e_fc_Conv temp = new BasicSelectionTestClass_uint_e_e_fc_Conv(); temp.value_uint = val; return (temp); } public uint GetValueuint() { return (value_uint); } public void SetValueuint(uint val) { value_uint = val; } private ulong value_ulong; static public explicit operator ulong(BasicSelectionTestClass_uint_e_e_fc_Conv test) { Log.Comment("To ulong"); return test.value_ulong; } static public explicit operator BasicSelectionTestClass_uint_e_e_fc_Conv(ulong val) { Log.Comment("From ulong"); BasicSelectionTestClass_uint_e_e_fc_Conv temp = new BasicSelectionTestClass_uint_e_e_fc_Conv(); temp.value_ulong = val; return (temp); } public ulong GetValueulong() { return (value_ulong); } public void SetValueulong(ulong val) { value_ulong = val; } private ushort value_ushort; static public explicit operator ushort(BasicSelectionTestClass_uint_e_e_fc_Conv test) { Log.Comment("To ushort"); return test.value_ushort; } static public explicit operator BasicSelectionTestClass_uint_e_e_fc_Conv(ushort val) { Log.Comment("From ushort"); BasicSelectionTestClass_uint_e_e_fc_Conv temp = new BasicSelectionTestClass_uint_e_e_fc_Conv(); temp.value_ushort = val; return (temp); } public ushort GetValueushort() { return (value_ushort); } public void SetValueushort(ushort val) { value_ushort = val; } } class BasicSelectionTestClass_uint_e_e_fc { public static int Main_old() { BasicSelectionTestClass_uint_e_e_fc_Conv cl = new BasicSelectionTestClass_uint_e_e_fc_Conv(); cl.SetValueuint(1); uint value = (uint)cl; if (value != 1) return 1; else return 0; } public static bool testMethod() { return (Main_old() == 0); } } class BasicSelectionTestClass_ulong_i_i_tc_Conv { private byte value_byte; static public implicit operator byte(BasicSelectionTestClass_ulong_i_i_tc_Conv test) { Log.Comment("To byte"); return test.value_byte; } static public implicit operator BasicSelectionTestClass_ulong_i_i_tc_Conv(byte val) { Log.Comment("From byte"); BasicSelectionTestClass_ulong_i_i_tc_Conv temp = new BasicSelectionTestClass_ulong_i_i_tc_Conv(); temp.value_byte = val; return (temp); } public byte GetValuebyte() { return (value_byte); } public void SetValuebyte(byte val) { value_byte = val; } private char value_char; static public implicit operator char(BasicSelectionTestClass_ulong_i_i_tc_Conv test) { Log.Comment("To char"); return test.value_char; } static public implicit operator BasicSelectionTestClass_ulong_i_i_tc_Conv(char val) { Log.Comment("From char"); BasicSelectionTestClass_ulong_i_i_tc_Conv temp = new BasicSelectionTestClass_ulong_i_i_tc_Conv(); temp.value_char = val; return (temp); } public char GetValuechar() { return (value_char); } public void SetValuechar(char val) { value_char = val; } private double value_double; static public implicit operator double(BasicSelectionTestClass_ulong_i_i_tc_Conv test) { Log.Comment("To double"); return test.value_double; } static public implicit operator BasicSelectionTestClass_ulong_i_i_tc_Conv(double val) { Log.Comment("From double"); BasicSelectionTestClass_ulong_i_i_tc_Conv temp = new BasicSelectionTestClass_ulong_i_i_tc_Conv(); temp.value_double = val; return (temp); } public double GetValuedouble() { return (value_double); } public void SetValuedouble(double val) { value_double = val; } private float value_float; static public implicit operator float(BasicSelectionTestClass_ulong_i_i_tc_Conv test) { Log.Comment("To float"); return test.value_float; } static public implicit operator BasicSelectionTestClass_ulong_i_i_tc_Conv(float val) { Log.Comment("From float"); BasicSelectionTestClass_ulong_i_i_tc_Conv temp = new BasicSelectionTestClass_ulong_i_i_tc_Conv(); temp.value_float = val; return (temp); } public float GetValuefloat() { return (value_float); } public void SetValuefloat(float val) { value_float = val; } private int value_int; static public implicit operator int(BasicSelectionTestClass_ulong_i_i_tc_Conv test) { Log.Comment("To int"); return test.value_int; } static public implicit operator BasicSelectionTestClass_ulong_i_i_tc_Conv(int val) { Log.Comment("From int"); BasicSelectionTestClass_ulong_i_i_tc_Conv temp = new BasicSelectionTestClass_ulong_i_i_tc_Conv(); temp.value_int = val; return (temp); } public int GetValueint() { return (value_int); } public void SetValueint(int val) { value_int = val; } private long value_long; static public implicit operator long(BasicSelectionTestClass_ulong_i_i_tc_Conv test) { Log.Comment("To long"); return test.value_long; } static public implicit operator BasicSelectionTestClass_ulong_i_i_tc_Conv(long val) { Log.Comment("From long"); BasicSelectionTestClass_ulong_i_i_tc_Conv temp = new BasicSelectionTestClass_ulong_i_i_tc_Conv(); temp.value_long = val; return (temp); } public long GetValuelong() { return (value_long); } public void SetValuelong(long val) { value_long = val; } private sbyte value_sbyte; static public implicit operator sbyte(BasicSelectionTestClass_ulong_i_i_tc_Conv test) { Log.Comment("To sbyte"); return test.value_sbyte; } static public implicit operator BasicSelectionTestClass_ulong_i_i_tc_Conv(sbyte val) { Log.Comment("From sbyte"); BasicSelectionTestClass_ulong_i_i_tc_Conv temp = new BasicSelectionTestClass_ulong_i_i_tc_Conv(); temp.value_sbyte = val; return (temp); } public sbyte GetValuesbyte() { return (value_sbyte); } public void SetValuesbyte(sbyte val) { value_sbyte = val; } private short value_short; static public implicit operator short(BasicSelectionTestClass_ulong_i_i_tc_Conv test) { Log.Comment("To short"); return test.value_short; } static public implicit operator BasicSelectionTestClass_ulong_i_i_tc_Conv(short val) { Log.Comment("From short"); BasicSelectionTestClass_ulong_i_i_tc_Conv temp = new BasicSelectionTestClass_ulong_i_i_tc_Conv(); temp.value_short = val; return (temp); } public short GetValueshort() { return (value_short); } public void SetValueshort(short val) { value_short = val; } private uint value_uint; static public implicit operator uint(BasicSelectionTestClass_ulong_i_i_tc_Conv test) { Log.Comment("To uint"); return test.value_uint; } static public implicit operator BasicSelectionTestClass_ulong_i_i_tc_Conv(uint val) { Log.Comment("From uint"); BasicSelectionTestClass_ulong_i_i_tc_Conv temp = new BasicSelectionTestClass_ulong_i_i_tc_Conv(); temp.value_uint = val; return (temp); } public uint GetValueuint() { return (value_uint); } public void SetValueuint(uint val) { value_uint = val; } private ulong value_ulong; static public implicit operator ulong(BasicSelectionTestClass_ulong_i_i_tc_Conv test) { Log.Comment("To ulong"); return test.value_ulong; } static public implicit operator BasicSelectionTestClass_ulong_i_i_tc_Conv(ulong val) { Log.Comment("From ulong"); BasicSelectionTestClass_ulong_i_i_tc_Conv temp = new BasicSelectionTestClass_ulong_i_i_tc_Conv(); temp.value_ulong = val; return (temp); } public ulong GetValueulong() { return (value_ulong); } public void SetValueulong(ulong val) { value_ulong = val; } private ushort value_ushort; static public implicit operator ushort(BasicSelectionTestClass_ulong_i_i_tc_Conv test) { Log.Comment("To ushort"); return test.value_ushort; } static public implicit operator BasicSelectionTestClass_ulong_i_i_tc_Conv(ushort val) { Log.Comment("From ushort"); BasicSelectionTestClass_ulong_i_i_tc_Conv temp = new BasicSelectionTestClass_ulong_i_i_tc_Conv(); temp.value_ushort = val; return (temp); } public ushort GetValueushort() { return (value_ushort); } public void SetValueushort(ushort val) { value_ushort = val; } } class BasicSelectionTestClass_ulong_i_i_tc { public static int Main_old() { BasicSelectionTestClass_ulong_i_i_tc_Conv cl = new BasicSelectionTestClass_ulong_i_i_tc_Conv(); ulong val = 1; cl = val; if (cl.GetValueulong() != 1) return 1; else return 0; } public static bool testMethod() { return (Main_old() == 0); } } class BasicSelectionTestClass_ulong_i_e_tc_Conv { private byte value_byte; static public implicit operator byte(BasicSelectionTestClass_ulong_i_e_tc_Conv test) { Log.Comment("To byte"); return test.value_byte; } static public implicit operator BasicSelectionTestClass_ulong_i_e_tc_Conv(byte val) { Log.Comment("From byte"); BasicSelectionTestClass_ulong_i_e_tc_Conv temp = new BasicSelectionTestClass_ulong_i_e_tc_Conv(); temp.value_byte = val; return (temp); } public byte GetValuebyte() { return (value_byte); } public void SetValuebyte(byte val) { value_byte = val; } private char value_char; static public implicit operator char(BasicSelectionTestClass_ulong_i_e_tc_Conv test) { Log.Comment("To char"); return test.value_char; } static public implicit operator BasicSelectionTestClass_ulong_i_e_tc_Conv(char val) { Log.Comment("From char"); BasicSelectionTestClass_ulong_i_e_tc_Conv temp = new BasicSelectionTestClass_ulong_i_e_tc_Conv(); temp.value_char = val; return (temp); } public char GetValuechar() { return (value_char); } public void SetValuechar(char val) { value_char = val; } private double value_double; static public implicit operator double(BasicSelectionTestClass_ulong_i_e_tc_Conv test) { Log.Comment("To double"); return test.value_double; } static public implicit operator BasicSelectionTestClass_ulong_i_e_tc_Conv(double val) { Log.Comment("From double"); BasicSelectionTestClass_ulong_i_e_tc_Conv temp = new BasicSelectionTestClass_ulong_i_e_tc_Conv(); temp.value_double = val; return (temp); } public double GetValuedouble() { return (value_double); } public void SetValuedouble(double val) { value_double = val; } private float value_float; static public implicit operator float(BasicSelectionTestClass_ulong_i_e_tc_Conv test) { Log.Comment("To float"); return test.value_float; } static public implicit operator BasicSelectionTestClass_ulong_i_e_tc_Conv(float val) { Log.Comment("From float"); BasicSelectionTestClass_ulong_i_e_tc_Conv temp = new BasicSelectionTestClass_ulong_i_e_tc_Conv(); temp.value_float = val; return (temp); } public float GetValuefloat() { return (value_float); } public void SetValuefloat(float val) { value_float = val; } private int value_int; static public implicit operator int(BasicSelectionTestClass_ulong_i_e_tc_Conv test) { Log.Comment("To int"); return test.value_int; } static public implicit operator BasicSelectionTestClass_ulong_i_e_tc_Conv(int val) { Log.Comment("From int"); BasicSelectionTestClass_ulong_i_e_tc_Conv temp = new BasicSelectionTestClass_ulong_i_e_tc_Conv(); temp.value_int = val; return (temp); } public int GetValueint() { return (value_int); } public void SetValueint(int val) { value_int = val; } private long value_long; static public implicit operator long(BasicSelectionTestClass_ulong_i_e_tc_Conv test) { Log.Comment("To long"); return test.value_long; } static public implicit operator BasicSelectionTestClass_ulong_i_e_tc_Conv(long val) { Log.Comment("From long"); BasicSelectionTestClass_ulong_i_e_tc_Conv temp = new BasicSelectionTestClass_ulong_i_e_tc_Conv(); temp.value_long = val; return (temp); } public long GetValuelong() { return (value_long); } public void SetValuelong(long val) { value_long = val; } private sbyte value_sbyte; static public implicit operator sbyte(BasicSelectionTestClass_ulong_i_e_tc_Conv test) { Log.Comment("To sbyte"); return test.value_sbyte; } static public implicit operator BasicSelectionTestClass_ulong_i_e_tc_Conv(sbyte val) { Log.Comment("From sbyte"); BasicSelectionTestClass_ulong_i_e_tc_Conv temp = new BasicSelectionTestClass_ulong_i_e_tc_Conv(); temp.value_sbyte = val; return (temp); } public sbyte GetValuesbyte() { return (value_sbyte); } public void SetValuesbyte(sbyte val) { value_sbyte = val; } private short value_short; static public implicit operator short(BasicSelectionTestClass_ulong_i_e_tc_Conv test) { Log.Comment("To short"); return test.value_short; } static public implicit operator BasicSelectionTestClass_ulong_i_e_tc_Conv(short val) { Log.Comment("From short"); BasicSelectionTestClass_ulong_i_e_tc_Conv temp = new BasicSelectionTestClass_ulong_i_e_tc_Conv(); temp.value_short = val; return (temp); } public short GetValueshort() { return (value_short); } public void SetValueshort(short val) { value_short = val; } private uint value_uint; static public implicit operator uint(BasicSelectionTestClass_ulong_i_e_tc_Conv test) { Log.Comment("To uint"); return test.value_uint; } static public implicit operator BasicSelectionTestClass_ulong_i_e_tc_Conv(uint val) { Log.Comment("From uint"); BasicSelectionTestClass_ulong_i_e_tc_Conv temp = new BasicSelectionTestClass_ulong_i_e_tc_Conv(); temp.value_uint = val; return (temp); } public uint GetValueuint() { return (value_uint); } public void SetValueuint(uint val) { value_uint = val; } private ulong value_ulong; static public implicit operator ulong(BasicSelectionTestClass_ulong_i_e_tc_Conv test) { Log.Comment("To ulong"); return test.value_ulong; } static public implicit operator BasicSelectionTestClass_ulong_i_e_tc_Conv(ulong val) { Log.Comment("From ulong"); BasicSelectionTestClass_ulong_i_e_tc_Conv temp = new BasicSelectionTestClass_ulong_i_e_tc_Conv(); temp.value_ulong = val; return (temp); } public ulong GetValueulong() { return (value_ulong); } public void SetValueulong(ulong val) { value_ulong = val; } private ushort value_ushort; static public implicit operator ushort(BasicSelectionTestClass_ulong_i_e_tc_Conv test) { Log.Comment("To ushort"); return test.value_ushort; } static public implicit operator BasicSelectionTestClass_ulong_i_e_tc_Conv(ushort val) { Log.Comment("From ushort"); BasicSelectionTestClass_ulong_i_e_tc_Conv temp = new BasicSelectionTestClass_ulong_i_e_tc_Conv(); temp.value_ushort = val; return (temp); } public ushort GetValueushort() { return (value_ushort); } public void SetValueushort(ushort val) { value_ushort = val; } } class BasicSelectionTestClass_ulong_i_e_tc { public static int Main_old() { BasicSelectionTestClass_ulong_i_e_tc_Conv cl = new BasicSelectionTestClass_ulong_i_e_tc_Conv(); ulong val = 1; cl = (BasicSelectionTestClass_ulong_i_e_tc_Conv)val; if (cl.GetValueulong() != 1) return 1; else return 0; } public static bool testMethod() { return (Main_old() == 0); } } class BasicSelectionTestClass_ulong_e_e_tc_Conv { private byte value_byte; static public explicit operator byte(BasicSelectionTestClass_ulong_e_e_tc_Conv test) { Log.Comment("To byte"); return test.value_byte; } static public explicit operator BasicSelectionTestClass_ulong_e_e_tc_Conv(byte val) { Log.Comment("From byte"); BasicSelectionTestClass_ulong_e_e_tc_Conv temp = new BasicSelectionTestClass_ulong_e_e_tc_Conv(); temp.value_byte = val; return (temp); } public byte GetValuebyte() { return (value_byte); } public void SetValuebyte(byte val) { value_byte = val; } private char value_char; static public explicit operator char(BasicSelectionTestClass_ulong_e_e_tc_Conv test) { Log.Comment("To char"); return test.value_char; } static public explicit operator BasicSelectionTestClass_ulong_e_e_tc_Conv(char val) { Log.Comment("From char"); BasicSelectionTestClass_ulong_e_e_tc_Conv temp = new BasicSelectionTestClass_ulong_e_e_tc_Conv(); temp.value_char = val; return (temp); } public char GetValuechar() { return (value_char); } public void SetValuechar(char val) { value_char = val; } private double value_double; static public explicit operator double(BasicSelectionTestClass_ulong_e_e_tc_Conv test) { Log.Comment("To double"); return test.value_double; } static public explicit operator BasicSelectionTestClass_ulong_e_e_tc_Conv(double val) { Log.Comment("From double"); BasicSelectionTestClass_ulong_e_e_tc_Conv temp = new BasicSelectionTestClass_ulong_e_e_tc_Conv(); temp.value_double = val; return (temp); } public double GetValuedouble() { return (value_double); } public void SetValuedouble(double val) { value_double = val; } private float value_float; static public explicit operator float(BasicSelectionTestClass_ulong_e_e_tc_Conv test) { Log.Comment("To float"); return test.value_float; } static public explicit operator BasicSelectionTestClass_ulong_e_e_tc_Conv(float val) { Log.Comment("From float"); BasicSelectionTestClass_ulong_e_e_tc_Conv temp = new BasicSelectionTestClass_ulong_e_e_tc_Conv(); temp.value_float = val; return (temp); } public float GetValuefloat() { return (value_float); } public void SetValuefloat(float val) { value_float = val; } private int value_int; static public explicit operator int(BasicSelectionTestClass_ulong_e_e_tc_Conv test) { Log.Comment("To int"); return test.value_int; } static public explicit operator BasicSelectionTestClass_ulong_e_e_tc_Conv(int val) { Log.Comment("From int"); BasicSelectionTestClass_ulong_e_e_tc_Conv temp = new BasicSelectionTestClass_ulong_e_e_tc_Conv(); temp.value_int = val; return (temp); } public int GetValueint() { return (value_int); } public void SetValueint(int val) { value_int = val; } private long value_long; static public explicit operator long(BasicSelectionTestClass_ulong_e_e_tc_Conv test) { Log.Comment("To long"); return test.value_long; } static public explicit operator BasicSelectionTestClass_ulong_e_e_tc_Conv(long val) { Log.Comment("From long"); BasicSelectionTestClass_ulong_e_e_tc_Conv temp = new BasicSelectionTestClass_ulong_e_e_tc_Conv(); temp.value_long = val; return (temp); } public long GetValuelong() { return (value_long); } public void SetValuelong(long val) { value_long = val; } private sbyte value_sbyte; static public explicit operator sbyte(BasicSelectionTestClass_ulong_e_e_tc_Conv test) { Log.Comment("To sbyte"); return test.value_sbyte; } static public explicit operator BasicSelectionTestClass_ulong_e_e_tc_Conv(sbyte val) { Log.Comment("From sbyte"); BasicSelectionTestClass_ulong_e_e_tc_Conv temp = new BasicSelectionTestClass_ulong_e_e_tc_Conv(); temp.value_sbyte = val; return (temp); } public sbyte GetValuesbyte() { return (value_sbyte); } public void SetValuesbyte(sbyte val) { value_sbyte = val; } private short value_short; static public explicit operator short(BasicSelectionTestClass_ulong_e_e_tc_Conv test) { Log.Comment("To short"); return test.value_short; } static public explicit operator BasicSelectionTestClass_ulong_e_e_tc_Conv(short val) { Log.Comment("From short"); BasicSelectionTestClass_ulong_e_e_tc_Conv temp = new BasicSelectionTestClass_ulong_e_e_tc_Conv(); temp.value_short = val; return (temp); } public short GetValueshort() { return (value_short); } public void SetValueshort(short val) { value_short = val; } private uint value_uint; static public explicit operator uint(BasicSelectionTestClass_ulong_e_e_tc_Conv test) { Log.Comment("To uint"); return test.value_uint; } static public explicit operator BasicSelectionTestClass_ulong_e_e_tc_Conv(uint val) { Log.Comment("From uint"); BasicSelectionTestClass_ulong_e_e_tc_Conv temp = new BasicSelectionTestClass_ulong_e_e_tc_Conv(); temp.value_uint = val; return (temp); } public uint GetValueuint() { return (value_uint); } public void SetValueuint(uint val) { value_uint = val; } private ulong value_ulong; static public explicit operator ulong(BasicSelectionTestClass_ulong_e_e_tc_Conv test) { Log.Comment("To ulong"); return test.value_ulong; } static public explicit operator BasicSelectionTestClass_ulong_e_e_tc_Conv(ulong val) { Log.Comment("From ulong"); BasicSelectionTestClass_ulong_e_e_tc_Conv temp = new BasicSelectionTestClass_ulong_e_e_tc_Conv(); temp.value_ulong = val; return (temp); } public ulong GetValueulong() { return (value_ulong); } public void SetValueulong(ulong val) { value_ulong = val; } private ushort value_ushort; static public explicit operator ushort(BasicSelectionTestClass_ulong_e_e_tc_Conv test) { Log.Comment("To ushort"); return test.value_ushort; } static public explicit operator BasicSelectionTestClass_ulong_e_e_tc_Conv(ushort val) { Log.Comment("From ushort"); BasicSelectionTestClass_ulong_e_e_tc_Conv temp = new BasicSelectionTestClass_ulong_e_e_tc_Conv(); temp.value_ushort = val; return (temp); } public ushort GetValueushort() { return (value_ushort); } public void SetValueushort(ushort val) { value_ushort = val; } } class BasicSelectionTestClass_ulong_e_e_tc { public static int Main_old() { BasicSelectionTestClass_ulong_e_e_tc_Conv cl = new BasicSelectionTestClass_ulong_e_e_tc_Conv(); ulong val = 1; cl = (BasicSelectionTestClass_ulong_e_e_tc_Conv)val; if (cl.GetValueulong() != 1) return 1; else return 0; } public static bool testMethod() { return (Main_old() == 0); } } class BasicSelectionTestClass_ulong_i_i_fc_Conv { private byte value_byte; static public implicit operator byte(BasicSelectionTestClass_ulong_i_i_fc_Conv test) { Log.Comment("To byte"); return test.value_byte; } static public implicit operator BasicSelectionTestClass_ulong_i_i_fc_Conv(byte val) { Log.Comment("From byte"); BasicSelectionTestClass_ulong_i_i_fc_Conv temp = new BasicSelectionTestClass_ulong_i_i_fc_Conv(); temp.value_byte = val; return (temp); } public byte GetValuebyte() { return (value_byte); } public void SetValuebyte(byte val) { value_byte = val; } private char value_char; static public implicit operator char(BasicSelectionTestClass_ulong_i_i_fc_Conv test) { Log.Comment("To char"); return test.value_char; } static public implicit operator BasicSelectionTestClass_ulong_i_i_fc_Conv(char val) { Log.Comment("From char"); BasicSelectionTestClass_ulong_i_i_fc_Conv temp = new BasicSelectionTestClass_ulong_i_i_fc_Conv(); temp.value_char = val; return (temp); } public char GetValuechar() { return (value_char); } public void SetValuechar(char val) { value_char = val; } private double value_double; static public implicit operator double(BasicSelectionTestClass_ulong_i_i_fc_Conv test) { Log.Comment("To double"); return test.value_double; } static public implicit operator BasicSelectionTestClass_ulong_i_i_fc_Conv(double val) { Log.Comment("From double"); BasicSelectionTestClass_ulong_i_i_fc_Conv temp = new BasicSelectionTestClass_ulong_i_i_fc_Conv(); temp.value_double = val; return (temp); } public double GetValuedouble() { return (value_double); } public void SetValuedouble(double val) { value_double = val; } private float value_float; static public implicit operator float(BasicSelectionTestClass_ulong_i_i_fc_Conv test) { Log.Comment("To float"); return test.value_float; } static public implicit operator BasicSelectionTestClass_ulong_i_i_fc_Conv(float val) { Log.Comment("From float"); BasicSelectionTestClass_ulong_i_i_fc_Conv temp = new BasicSelectionTestClass_ulong_i_i_fc_Conv(); temp.value_float = val; return (temp); } public float GetValuefloat() { return (value_float); } public void SetValuefloat(float val) { value_float = val; } private int value_int; static public implicit operator int(BasicSelectionTestClass_ulong_i_i_fc_Conv test) { Log.Comment("To int"); return test.value_int; } static public implicit operator BasicSelectionTestClass_ulong_i_i_fc_Conv(int val) { Log.Comment("From int"); BasicSelectionTestClass_ulong_i_i_fc_Conv temp = new BasicSelectionTestClass_ulong_i_i_fc_Conv(); temp.value_int = val; return (temp); } public int GetValueint() { return (value_int); } public void SetValueint(int val) { value_int = val; } private long value_long; static public implicit operator long(BasicSelectionTestClass_ulong_i_i_fc_Conv test) { Log.Comment("To long"); return test.value_long; } static public implicit operator BasicSelectionTestClass_ulong_i_i_fc_Conv(long val) { Log.Comment("From long"); BasicSelectionTestClass_ulong_i_i_fc_Conv temp = new BasicSelectionTestClass_ulong_i_i_fc_Conv(); temp.value_long = val; return (temp); } public long GetValuelong() { return (value_long); } public void SetValuelong(long val) { value_long = val; } private sbyte value_sbyte; static public implicit operator sbyte(BasicSelectionTestClass_ulong_i_i_fc_Conv test) { Log.Comment("To sbyte"); return test.value_sbyte; } static public implicit operator BasicSelectionTestClass_ulong_i_i_fc_Conv(sbyte val) { Log.Comment("From sbyte"); BasicSelectionTestClass_ulong_i_i_fc_Conv temp = new BasicSelectionTestClass_ulong_i_i_fc_Conv(); temp.value_sbyte = val; return (temp); } public sbyte GetValuesbyte() { return (value_sbyte); } public void SetValuesbyte(sbyte val) { value_sbyte = val; } private short value_short; static public implicit operator short(BasicSelectionTestClass_ulong_i_i_fc_Conv test) { Log.Comment("To short"); return test.value_short; } static public implicit operator BasicSelectionTestClass_ulong_i_i_fc_Conv(short val) { Log.Comment("From short"); BasicSelectionTestClass_ulong_i_i_fc_Conv temp = new BasicSelectionTestClass_ulong_i_i_fc_Conv(); temp.value_short = val; return (temp); } public short GetValueshort() { return (value_short); } public void SetValueshort(short val) { value_short = val; } private uint value_uint; static public implicit operator uint(BasicSelectionTestClass_ulong_i_i_fc_Conv test) { Log.Comment("To uint"); return test.value_uint; } static public implicit operator BasicSelectionTestClass_ulong_i_i_fc_Conv(uint val) { Log.Comment("From uint"); BasicSelectionTestClass_ulong_i_i_fc_Conv temp = new BasicSelectionTestClass_ulong_i_i_fc_Conv(); temp.value_uint = val; return (temp); } public uint GetValueuint() { return (value_uint); } public void SetValueuint(uint val) { value_uint = val; } private ulong value_ulong; static public implicit operator ulong(BasicSelectionTestClass_ulong_i_i_fc_Conv test) { Log.Comment("To ulong"); return test.value_ulong; } static public implicit operator BasicSelectionTestClass_ulong_i_i_fc_Conv(ulong val) { Log.Comment("From ulong"); BasicSelectionTestClass_ulong_i_i_fc_Conv temp = new BasicSelectionTestClass_ulong_i_i_fc_Conv(); temp.value_ulong = val; return (temp); } public ulong GetValueulong() { return (value_ulong); } public void SetValueulong(ulong val) { value_ulong = val; } private ushort value_ushort; static public implicit operator ushort(BasicSelectionTestClass_ulong_i_i_fc_Conv test) { Log.Comment("To ushort"); return test.value_ushort; } static public implicit operator BasicSelectionTestClass_ulong_i_i_fc_Conv(ushort val) { Log.Comment("From ushort"); BasicSelectionTestClass_ulong_i_i_fc_Conv temp = new BasicSelectionTestClass_ulong_i_i_fc_Conv(); temp.value_ushort = val; return (temp); } public ushort GetValueushort() { return (value_ushort); } public void SetValueushort(ushort val) { value_ushort = val; } } class BasicSelectionTestClass_ulong_i_i_fc { public static int Main_old() { BasicSelectionTestClass_ulong_i_i_fc_Conv cl = new BasicSelectionTestClass_ulong_i_i_fc_Conv(); cl.SetValueulong(1); ulong value = cl; if (value != 1) return 1; else return 0; } public static bool testMethod() { return (Main_old() == 0); } } class BasicSelectionTestClass_ulong_i_e_fc_Conv { private byte value_byte; static public implicit operator byte(BasicSelectionTestClass_ulong_i_e_fc_Conv test) { Log.Comment("To byte"); return test.value_byte; } static public implicit operator BasicSelectionTestClass_ulong_i_e_fc_Conv(byte val) { Log.Comment("From byte"); BasicSelectionTestClass_ulong_i_e_fc_Conv temp = new BasicSelectionTestClass_ulong_i_e_fc_Conv(); temp.value_byte = val; return (temp); } public byte GetValuebyte() { return (value_byte); } public void SetValuebyte(byte val) { value_byte = val; } private char value_char; static public implicit operator char(BasicSelectionTestClass_ulong_i_e_fc_Conv test) { Log.Comment("To char"); return test.value_char; } static public implicit operator BasicSelectionTestClass_ulong_i_e_fc_Conv(char val) { Log.Comment("From char"); BasicSelectionTestClass_ulong_i_e_fc_Conv temp = new BasicSelectionTestClass_ulong_i_e_fc_Conv(); temp.value_char = val; return (temp); } public char GetValuechar() { return (value_char); } public void SetValuechar(char val) { value_char = val; } private double value_double; static public implicit operator double(BasicSelectionTestClass_ulong_i_e_fc_Conv test) { Log.Comment("To double"); return test.value_double; } static public implicit operator BasicSelectionTestClass_ulong_i_e_fc_Conv(double val) { Log.Comment("From double"); BasicSelectionTestClass_ulong_i_e_fc_Conv temp = new BasicSelectionTestClass_ulong_i_e_fc_Conv(); temp.value_double = val; return (temp); } public double GetValuedouble() { return (value_double); } public void SetValuedouble(double val) { value_double = val; } private float value_float; static public implicit operator float(BasicSelectionTestClass_ulong_i_e_fc_Conv test) { Log.Comment("To float"); return test.value_float; } static public implicit operator BasicSelectionTestClass_ulong_i_e_fc_Conv(float val) { Log.Comment("From float"); BasicSelectionTestClass_ulong_i_e_fc_Conv temp = new BasicSelectionTestClass_ulong_i_e_fc_Conv(); temp.value_float = val; return (temp); } public float GetValuefloat() { return (value_float); } public void SetValuefloat(float val) { value_float = val; } private int value_int; static public implicit operator int(BasicSelectionTestClass_ulong_i_e_fc_Conv test) { Log.Comment("To int"); return test.value_int; } static public implicit operator BasicSelectionTestClass_ulong_i_e_fc_Conv(int val) { Log.Comment("From int"); BasicSelectionTestClass_ulong_i_e_fc_Conv temp = new BasicSelectionTestClass_ulong_i_e_fc_Conv(); temp.value_int = val; return (temp); } public int GetValueint() { return (value_int); } public void SetValueint(int val) { value_int = val; } private long value_long; static public implicit operator long(BasicSelectionTestClass_ulong_i_e_fc_Conv test) { Log.Comment("To long"); return test.value_long; } static public implicit operator BasicSelectionTestClass_ulong_i_e_fc_Conv(long val) { Log.Comment("From long"); BasicSelectionTestClass_ulong_i_e_fc_Conv temp = new BasicSelectionTestClass_ulong_i_e_fc_Conv(); temp.value_long = val; return (temp); } public long GetValuelong() { return (value_long); } public void SetValuelong(long val) { value_long = val; } private sbyte value_sbyte; static public implicit operator sbyte(BasicSelectionTestClass_ulong_i_e_fc_Conv test) { Log.Comment("To sbyte"); return test.value_sbyte; } static public implicit operator BasicSelectionTestClass_ulong_i_e_fc_Conv(sbyte val) { Log.Comment("From sbyte"); BasicSelectionTestClass_ulong_i_e_fc_Conv temp = new BasicSelectionTestClass_ulong_i_e_fc_Conv(); temp.value_sbyte = val; return (temp); } public sbyte GetValuesbyte() { return (value_sbyte); } public void SetValuesbyte(sbyte val) { value_sbyte = val; } private short value_short; static public implicit operator short(BasicSelectionTestClass_ulong_i_e_fc_Conv test) { Log.Comment("To short"); return test.value_short; } static public implicit operator BasicSelectionTestClass_ulong_i_e_fc_Conv(short val) { Log.Comment("From short"); BasicSelectionTestClass_ulong_i_e_fc_Conv temp = new BasicSelectionTestClass_ulong_i_e_fc_Conv(); temp.value_short = val; return (temp); } public short GetValueshort() { return (value_short); } public void SetValueshort(short val) { value_short = val; } private uint value_uint; static public implicit operator uint(BasicSelectionTestClass_ulong_i_e_fc_Conv test) { Log.Comment("To uint"); return test.value_uint; } static public implicit operator BasicSelectionTestClass_ulong_i_e_fc_Conv(uint val) { Log.Comment("From uint"); BasicSelectionTestClass_ulong_i_e_fc_Conv temp = new BasicSelectionTestClass_ulong_i_e_fc_Conv(); temp.value_uint = val; return (temp); } public uint GetValueuint() { return (value_uint); } public void SetValueuint(uint val) { value_uint = val; } private ulong value_ulong; static public implicit operator ulong(BasicSelectionTestClass_ulong_i_e_fc_Conv test) { Log.Comment("To ulong"); return test.value_ulong; } static public implicit operator BasicSelectionTestClass_ulong_i_e_fc_Conv(ulong val) { Log.Comment("From ulong"); BasicSelectionTestClass_ulong_i_e_fc_Conv temp = new BasicSelectionTestClass_ulong_i_e_fc_Conv(); temp.value_ulong = val; return (temp); } public ulong GetValueulong() { return (value_ulong); } public void SetValueulong(ulong val) { value_ulong = val; } private ushort value_ushort; static public implicit operator ushort(BasicSelectionTestClass_ulong_i_e_fc_Conv test) { Log.Comment("To ushort"); return test.value_ushort; } static public implicit operator BasicSelectionTestClass_ulong_i_e_fc_Conv(ushort val) { Log.Comment("From ushort"); BasicSelectionTestClass_ulong_i_e_fc_Conv temp = new BasicSelectionTestClass_ulong_i_e_fc_Conv(); temp.value_ushort = val; return (temp); } public ushort GetValueushort() { return (value_ushort); } public void SetValueushort(ushort val) { value_ushort = val; } } class BasicSelectionTestClass_ulong_i_e_fc { public static int Main_old() { BasicSelectionTestClass_ulong_i_e_fc_Conv cl = new BasicSelectionTestClass_ulong_i_e_fc_Conv(); cl.SetValueulong(1); ulong value = (ulong)cl; if (value != 1) return 1; else return 0; } public static bool testMethod() { return (Main_old() == 0); } } class BasicSelectionTestClass_ulong_e_e_fc_Conv { private byte value_byte; static public explicit operator byte(BasicSelectionTestClass_ulong_e_e_fc_Conv test) { Log.Comment("To byte"); return test.value_byte; } static public explicit operator BasicSelectionTestClass_ulong_e_e_fc_Conv(byte val) { Log.Comment("From byte"); BasicSelectionTestClass_ulong_e_e_fc_Conv temp = new BasicSelectionTestClass_ulong_e_e_fc_Conv(); temp.value_byte = val; return (temp); } public byte GetValuebyte() { return (value_byte); } public void SetValuebyte(byte val) { value_byte = val; } private char value_char; static public explicit operator char(BasicSelectionTestClass_ulong_e_e_fc_Conv test) { Log.Comment("To char"); return test.value_char; } static public explicit operator BasicSelectionTestClass_ulong_e_e_fc_Conv(char val) { Log.Comment("From char"); BasicSelectionTestClass_ulong_e_e_fc_Conv temp = new BasicSelectionTestClass_ulong_e_e_fc_Conv(); temp.value_char = val; return (temp); } public char GetValuechar() { return (value_char); } public void SetValuechar(char val) { value_char = val; } private double value_double; static public explicit operator double(BasicSelectionTestClass_ulong_e_e_fc_Conv test) { Log.Comment("To double"); return test.value_double; } static public explicit operator BasicSelectionTestClass_ulong_e_e_fc_Conv(double val) { Log.Comment("From double"); BasicSelectionTestClass_ulong_e_e_fc_Conv temp = new BasicSelectionTestClass_ulong_e_e_fc_Conv(); temp.value_double = val; return (temp); } public double GetValuedouble() { return (value_double); } public void SetValuedouble(double val) { value_double = val; } private float value_float; static public explicit operator float(BasicSelectionTestClass_ulong_e_e_fc_Conv test) { Log.Comment("To float"); return test.value_float; } static public explicit operator BasicSelectionTestClass_ulong_e_e_fc_Conv(float val) { Log.Comment("From float"); BasicSelectionTestClass_ulong_e_e_fc_Conv temp = new BasicSelectionTestClass_ulong_e_e_fc_Conv(); temp.value_float = val; return (temp); } public float GetValuefloat() { return (value_float); } public void SetValuefloat(float val) { value_float = val; } private int value_int; static public explicit operator int(BasicSelectionTestClass_ulong_e_e_fc_Conv test) { Log.Comment("To int"); return test.value_int; } static public explicit operator BasicSelectionTestClass_ulong_e_e_fc_Conv(int val) { Log.Comment("From int"); BasicSelectionTestClass_ulong_e_e_fc_Conv temp = new BasicSelectionTestClass_ulong_e_e_fc_Conv(); temp.value_int = val; return (temp); } public int GetValueint() { return (value_int); } public void SetValueint(int val) { value_int = val; } private long value_long; static public explicit operator long(BasicSelectionTestClass_ulong_e_e_fc_Conv test) { Log.Comment("To long"); return test.value_long; } static public explicit operator BasicSelectionTestClass_ulong_e_e_fc_Conv(long val) { Log.Comment("From long"); BasicSelectionTestClass_ulong_e_e_fc_Conv temp = new BasicSelectionTestClass_ulong_e_e_fc_Conv(); temp.value_long = val; return (temp); } public long GetValuelong() { return (value_long); } public void SetValuelong(long val) { value_long = val; } private sbyte value_sbyte; static public explicit operator sbyte(BasicSelectionTestClass_ulong_e_e_fc_Conv test) { Log.Comment("To sbyte"); return test.value_sbyte; } static public explicit operator BasicSelectionTestClass_ulong_e_e_fc_Conv(sbyte val) { Log.Comment("From sbyte"); BasicSelectionTestClass_ulong_e_e_fc_Conv temp = new BasicSelectionTestClass_ulong_e_e_fc_Conv(); temp.value_sbyte = val; return (temp); } public sbyte GetValuesbyte() { return (value_sbyte); } public void SetValuesbyte(sbyte val) { value_sbyte = val; } private short value_short; static public explicit operator short(BasicSelectionTestClass_ulong_e_e_fc_Conv test) { Log.Comment("To short"); return test.value_short; } static public explicit operator BasicSelectionTestClass_ulong_e_e_fc_Conv(short val) { Log.Comment("From short"); BasicSelectionTestClass_ulong_e_e_fc_Conv temp = new BasicSelectionTestClass_ulong_e_e_fc_Conv(); temp.value_short = val; return (temp); } public short GetValueshort() { return (value_short); } public void SetValueshort(short val) { value_short = val; } private uint value_uint; static public explicit operator uint(BasicSelectionTestClass_ulong_e_e_fc_Conv test) { Log.Comment("To uint"); return test.value_uint; } static public explicit operator BasicSelectionTestClass_ulong_e_e_fc_Conv(uint val) { Log.Comment("From uint"); BasicSelectionTestClass_ulong_e_e_fc_Conv temp = new BasicSelectionTestClass_ulong_e_e_fc_Conv(); temp.value_uint = val; return (temp); } public uint GetValueuint() { return (value_uint); } public void SetValueuint(uint val) { value_uint = val; } private ulong value_ulong; static public explicit operator ulong(BasicSelectionTestClass_ulong_e_e_fc_Conv test) { Log.Comment("To ulong"); return test.value_ulong; } static public explicit operator BasicSelectionTestClass_ulong_e_e_fc_Conv(ulong val) { Log.Comment("From ulong"); BasicSelectionTestClass_ulong_e_e_fc_Conv temp = new BasicSelectionTestClass_ulong_e_e_fc_Conv(); temp.value_ulong = val; return (temp); } public ulong GetValueulong() { return (value_ulong); } public void SetValueulong(ulong val) { value_ulong = val; } private ushort value_ushort; static public explicit operator ushort(BasicSelectionTestClass_ulong_e_e_fc_Conv test) { Log.Comment("To ushort"); return test.value_ushort; } static public explicit operator BasicSelectionTestClass_ulong_e_e_fc_Conv(ushort val) { Log.Comment("From ushort"); BasicSelectionTestClass_ulong_e_e_fc_Conv temp = new BasicSelectionTestClass_ulong_e_e_fc_Conv(); temp.value_ushort = val; return (temp); } public ushort GetValueushort() { return (value_ushort); } public void SetValueushort(ushort val) { value_ushort = val; } } class BasicSelectionTestClass_ulong_e_e_fc { public static int Main_old() { BasicSelectionTestClass_ulong_e_e_fc_Conv cl = new BasicSelectionTestClass_ulong_e_e_fc_Conv(); cl.SetValueulong(1); ulong value = (ulong)cl; if (value != 1) return 1; else return 0; } public static bool testMethod() { return (Main_old() == 0); } } class BasicSelectionTestClass_ushort_i_i_tc_Conv { private byte value_byte; static public implicit operator byte(BasicSelectionTestClass_ushort_i_i_tc_Conv test) { Log.Comment("To byte"); return test.value_byte; } static public implicit operator BasicSelectionTestClass_ushort_i_i_tc_Conv(byte val) { Log.Comment("From byte"); BasicSelectionTestClass_ushort_i_i_tc_Conv temp = new BasicSelectionTestClass_ushort_i_i_tc_Conv(); temp.value_byte = val; return (temp); } public byte GetValuebyte() { return (value_byte); } public void SetValuebyte(byte val) { value_byte = val; } private char value_char; static public implicit operator char(BasicSelectionTestClass_ushort_i_i_tc_Conv test) { Log.Comment("To char"); return test.value_char; } static public implicit operator BasicSelectionTestClass_ushort_i_i_tc_Conv(char val) { Log.Comment("From char"); BasicSelectionTestClass_ushort_i_i_tc_Conv temp = new BasicSelectionTestClass_ushort_i_i_tc_Conv(); temp.value_char = val; return (temp); } public char GetValuechar() { return (value_char); } public void SetValuechar(char val) { value_char = val; } private double value_double; static public implicit operator double(BasicSelectionTestClass_ushort_i_i_tc_Conv test) { Log.Comment("To double"); return test.value_double; } static public implicit operator BasicSelectionTestClass_ushort_i_i_tc_Conv(double val) { Log.Comment("From double"); BasicSelectionTestClass_ushort_i_i_tc_Conv temp = new BasicSelectionTestClass_ushort_i_i_tc_Conv(); temp.value_double = val; return (temp); } public double GetValuedouble() { return (value_double); } public void SetValuedouble(double val) { value_double = val; } private float value_float; static public implicit operator float(BasicSelectionTestClass_ushort_i_i_tc_Conv test) { Log.Comment("To float"); return test.value_float; } static public implicit operator BasicSelectionTestClass_ushort_i_i_tc_Conv(float val) { Log.Comment("From float"); BasicSelectionTestClass_ushort_i_i_tc_Conv temp = new BasicSelectionTestClass_ushort_i_i_tc_Conv(); temp.value_float = val; return (temp); } public float GetValuefloat() { return (value_float); } public void SetValuefloat(float val) { value_float = val; } private int value_int; static public implicit operator int(BasicSelectionTestClass_ushort_i_i_tc_Conv test) { Log.Comment("To int"); return test.value_int; } static public implicit operator BasicSelectionTestClass_ushort_i_i_tc_Conv(int val) { Log.Comment("From int"); BasicSelectionTestClass_ushort_i_i_tc_Conv temp = new BasicSelectionTestClass_ushort_i_i_tc_Conv(); temp.value_int = val; return (temp); } public int GetValueint() { return (value_int); } public void SetValueint(int val) { value_int = val; } private long value_long; static public implicit operator long(BasicSelectionTestClass_ushort_i_i_tc_Conv test) { Log.Comment("To long"); return test.value_long; } static public implicit operator BasicSelectionTestClass_ushort_i_i_tc_Conv(long val) { Log.Comment("From long"); BasicSelectionTestClass_ushort_i_i_tc_Conv temp = new BasicSelectionTestClass_ushort_i_i_tc_Conv(); temp.value_long = val; return (temp); } public long GetValuelong() { return (value_long); } public void SetValuelong(long val) { value_long = val; } private sbyte value_sbyte; static public implicit operator sbyte(BasicSelectionTestClass_ushort_i_i_tc_Conv test) { Log.Comment("To sbyte"); return test.value_sbyte; } static public implicit operator BasicSelectionTestClass_ushort_i_i_tc_Conv(sbyte val) { Log.Comment("From sbyte"); BasicSelectionTestClass_ushort_i_i_tc_Conv temp = new BasicSelectionTestClass_ushort_i_i_tc_Conv(); temp.value_sbyte = val; return (temp); } public sbyte GetValuesbyte() { return (value_sbyte); } public void SetValuesbyte(sbyte val) { value_sbyte = val; } private short value_short; static public implicit operator short(BasicSelectionTestClass_ushort_i_i_tc_Conv test) { Log.Comment("To short"); return test.value_short; } static public implicit operator BasicSelectionTestClass_ushort_i_i_tc_Conv(short val) { Log.Comment("From short"); BasicSelectionTestClass_ushort_i_i_tc_Conv temp = new BasicSelectionTestClass_ushort_i_i_tc_Conv(); temp.value_short = val; return (temp); } public short GetValueshort() { return (value_short); } public void SetValueshort(short val) { value_short = val; } private uint value_uint; static public implicit operator uint(BasicSelectionTestClass_ushort_i_i_tc_Conv test) { Log.Comment("To uint"); return test.value_uint; } static public implicit operator BasicSelectionTestClass_ushort_i_i_tc_Conv(uint val) { Log.Comment("From uint"); BasicSelectionTestClass_ushort_i_i_tc_Conv temp = new BasicSelectionTestClass_ushort_i_i_tc_Conv(); temp.value_uint = val; return (temp); } public uint GetValueuint() { return (value_uint); } public void SetValueuint(uint val) { value_uint = val; } private ulong value_ulong; static public implicit operator ulong(BasicSelectionTestClass_ushort_i_i_tc_Conv test) { Log.Comment("To ulong"); return test.value_ulong; } static public implicit operator BasicSelectionTestClass_ushort_i_i_tc_Conv(ulong val) { Log.Comment("From ulong"); BasicSelectionTestClass_ushort_i_i_tc_Conv temp = new BasicSelectionTestClass_ushort_i_i_tc_Conv(); temp.value_ulong = val; return (temp); } public ulong GetValueulong() { return (value_ulong); } public void SetValueulong(ulong val) { value_ulong = val; } private ushort value_ushort; static public implicit operator ushort(BasicSelectionTestClass_ushort_i_i_tc_Conv test) { Log.Comment("To ushort"); return test.value_ushort; } static public implicit operator BasicSelectionTestClass_ushort_i_i_tc_Conv(ushort val) { Log.Comment("From ushort"); BasicSelectionTestClass_ushort_i_i_tc_Conv temp = new BasicSelectionTestClass_ushort_i_i_tc_Conv(); temp.value_ushort = val; return (temp); } public ushort GetValueushort() { return (value_ushort); } public void SetValueushort(ushort val) { value_ushort = val; } } class BasicSelectionTestClass_ushort_i_i_tc { public static int Main_old() { BasicSelectionTestClass_ushort_i_i_tc_Conv cl = new BasicSelectionTestClass_ushort_i_i_tc_Conv(); ushort val = 1; cl = val; if (cl.GetValueushort() != 1) return 1; else return 0; } public static bool testMethod() { return (Main_old() == 0); } } class BasicSelectionTestClass_ushort_i_e_tc_Conv { private byte value_byte; static public implicit operator byte(BasicSelectionTestClass_ushort_i_e_tc_Conv test) { Log.Comment("To byte"); return test.value_byte; } static public implicit operator BasicSelectionTestClass_ushort_i_e_tc_Conv(byte val) { Log.Comment("From byte"); BasicSelectionTestClass_ushort_i_e_tc_Conv temp = new BasicSelectionTestClass_ushort_i_e_tc_Conv(); temp.value_byte = val; return (temp); } public byte GetValuebyte() { return (value_byte); } public void SetValuebyte(byte val) { value_byte = val; } private char value_char; static public implicit operator char(BasicSelectionTestClass_ushort_i_e_tc_Conv test) { Log.Comment("To char"); return test.value_char; } static public implicit operator BasicSelectionTestClass_ushort_i_e_tc_Conv(char val) { Log.Comment("From char"); BasicSelectionTestClass_ushort_i_e_tc_Conv temp = new BasicSelectionTestClass_ushort_i_e_tc_Conv(); temp.value_char = val; return (temp); } public char GetValuechar() { return (value_char); } public void SetValuechar(char val) { value_char = val; } private double value_double; static public implicit operator double(BasicSelectionTestClass_ushort_i_e_tc_Conv test) { Log.Comment("To double"); return test.value_double; } static public implicit operator BasicSelectionTestClass_ushort_i_e_tc_Conv(double val) { Log.Comment("From double"); BasicSelectionTestClass_ushort_i_e_tc_Conv temp = new BasicSelectionTestClass_ushort_i_e_tc_Conv(); temp.value_double = val; return (temp); } public double GetValuedouble() { return (value_double); } public void SetValuedouble(double val) { value_double = val; } private float value_float; static public implicit operator float(BasicSelectionTestClass_ushort_i_e_tc_Conv test) { Log.Comment("To float"); return test.value_float; } static public implicit operator BasicSelectionTestClass_ushort_i_e_tc_Conv(float val) { Log.Comment("From float"); BasicSelectionTestClass_ushort_i_e_tc_Conv temp = new BasicSelectionTestClass_ushort_i_e_tc_Conv(); temp.value_float = val; return (temp); } public float GetValuefloat() { return (value_float); } public void SetValuefloat(float val) { value_float = val; } private int value_int; static public implicit operator int(BasicSelectionTestClass_ushort_i_e_tc_Conv test) { Log.Comment("To int"); return test.value_int; } static public implicit operator BasicSelectionTestClass_ushort_i_e_tc_Conv(int val) { Log.Comment("From int"); BasicSelectionTestClass_ushort_i_e_tc_Conv temp = new BasicSelectionTestClass_ushort_i_e_tc_Conv(); temp.value_int = val; return (temp); } public int GetValueint() { return (value_int); } public void SetValueint(int val) { value_int = val; } private long value_long; static public implicit operator long(BasicSelectionTestClass_ushort_i_e_tc_Conv test) { Log.Comment("To long"); return test.value_long; } static public implicit operator BasicSelectionTestClass_ushort_i_e_tc_Conv(long val) { Log.Comment("From long"); BasicSelectionTestClass_ushort_i_e_tc_Conv temp = new BasicSelectionTestClass_ushort_i_e_tc_Conv(); temp.value_long = val; return (temp); } public long GetValuelong() { return (value_long); } public void SetValuelong(long val) { value_long = val; } private sbyte value_sbyte; static public implicit operator sbyte(BasicSelectionTestClass_ushort_i_e_tc_Conv test) { Log.Comment("To sbyte"); return test.value_sbyte; } static public implicit operator BasicSelectionTestClass_ushort_i_e_tc_Conv(sbyte val) { Log.Comment("From sbyte"); BasicSelectionTestClass_ushort_i_e_tc_Conv temp = new BasicSelectionTestClass_ushort_i_e_tc_Conv(); temp.value_sbyte = val; return (temp); } public sbyte GetValuesbyte() { return (value_sbyte); } public void SetValuesbyte(sbyte val) { value_sbyte = val; } private short value_short; static public implicit operator short(BasicSelectionTestClass_ushort_i_e_tc_Conv test) { Log.Comment("To short"); return test.value_short; } static public implicit operator BasicSelectionTestClass_ushort_i_e_tc_Conv(short val) { Log.Comment("From short"); BasicSelectionTestClass_ushort_i_e_tc_Conv temp = new BasicSelectionTestClass_ushort_i_e_tc_Conv(); temp.value_short = val; return (temp); } public short GetValueshort() { return (value_short); } public void SetValueshort(short val) { value_short = val; } private uint value_uint; static public implicit operator uint(BasicSelectionTestClass_ushort_i_e_tc_Conv test) { Log.Comment("To uint"); return test.value_uint; } static public implicit operator BasicSelectionTestClass_ushort_i_e_tc_Conv(uint val) { Log.Comment("From uint"); BasicSelectionTestClass_ushort_i_e_tc_Conv temp = new BasicSelectionTestClass_ushort_i_e_tc_Conv(); temp.value_uint = val; return (temp); } public uint GetValueuint() { return (value_uint); } public void SetValueuint(uint val) { value_uint = val; } private ulong value_ulong; static public implicit operator ulong(BasicSelectionTestClass_ushort_i_e_tc_Conv test) { Log.Comment("To ulong"); return test.value_ulong; } static public implicit operator BasicSelectionTestClass_ushort_i_e_tc_Conv(ulong val) { Log.Comment("From ulong"); BasicSelectionTestClass_ushort_i_e_tc_Conv temp = new BasicSelectionTestClass_ushort_i_e_tc_Conv(); temp.value_ulong = val; return (temp); } public ulong GetValueulong() { return (value_ulong); } public void SetValueulong(ulong val) { value_ulong = val; } private ushort value_ushort; static public implicit operator ushort(BasicSelectionTestClass_ushort_i_e_tc_Conv test) { Log.Comment("To ushort"); return test.value_ushort; } static public implicit operator BasicSelectionTestClass_ushort_i_e_tc_Conv(ushort val) { Log.Comment("From ushort"); BasicSelectionTestClass_ushort_i_e_tc_Conv temp = new BasicSelectionTestClass_ushort_i_e_tc_Conv(); temp.value_ushort = val; return (temp); } public ushort GetValueushort() { return (value_ushort); } public void SetValueushort(ushort val) { value_ushort = val; } } class BasicSelectionTestClass_ushort_i_e_tc { public static int Main_old() { BasicSelectionTestClass_ushort_i_e_tc_Conv cl = new BasicSelectionTestClass_ushort_i_e_tc_Conv(); ushort val = 1; cl = (BasicSelectionTestClass_ushort_i_e_tc_Conv)val; if (cl.GetValueushort() != 1) return 1; else return 0; } public static bool testMethod() { return (Main_old() == 0); } } class BasicSelectionTestClass_ushort_e_e_tc_Conv { private byte value_byte; static public explicit operator byte(BasicSelectionTestClass_ushort_e_e_tc_Conv test) { Log.Comment("To byte"); return test.value_byte; } static public explicit operator BasicSelectionTestClass_ushort_e_e_tc_Conv(byte val) { Log.Comment("From byte"); BasicSelectionTestClass_ushort_e_e_tc_Conv temp = new BasicSelectionTestClass_ushort_e_e_tc_Conv(); temp.value_byte = val; return (temp); } public byte GetValuebyte() { return (value_byte); } public void SetValuebyte(byte val) { value_byte = val; } private char value_char; static public explicit operator char(BasicSelectionTestClass_ushort_e_e_tc_Conv test) { Log.Comment("To char"); return test.value_char; } static public explicit operator BasicSelectionTestClass_ushort_e_e_tc_Conv(char val) { Log.Comment("From char"); BasicSelectionTestClass_ushort_e_e_tc_Conv temp = new BasicSelectionTestClass_ushort_e_e_tc_Conv(); temp.value_char = val; return (temp); } public char GetValuechar() { return (value_char); } public void SetValuechar(char val) { value_char = val; } private double value_double; static public explicit operator double(BasicSelectionTestClass_ushort_e_e_tc_Conv test) { Log.Comment("To double"); return test.value_double; } static public explicit operator BasicSelectionTestClass_ushort_e_e_tc_Conv(double val) { Log.Comment("From double"); BasicSelectionTestClass_ushort_e_e_tc_Conv temp = new BasicSelectionTestClass_ushort_e_e_tc_Conv(); temp.value_double = val; return (temp); } public double GetValuedouble() { return (value_double); } public void SetValuedouble(double val) { value_double = val; } private float value_float; static public explicit operator float(BasicSelectionTestClass_ushort_e_e_tc_Conv test) { Log.Comment("To float"); return test.value_float; } static public explicit operator BasicSelectionTestClass_ushort_e_e_tc_Conv(float val) { Log.Comment("From float"); BasicSelectionTestClass_ushort_e_e_tc_Conv temp = new BasicSelectionTestClass_ushort_e_e_tc_Conv(); temp.value_float = val; return (temp); } public float GetValuefloat() { return (value_float); } public void SetValuefloat(float val) { value_float = val; } private int value_int; static public explicit operator int(BasicSelectionTestClass_ushort_e_e_tc_Conv test) { Log.Comment("To int"); return test.value_int; } static public explicit operator BasicSelectionTestClass_ushort_e_e_tc_Conv(int val) { Log.Comment("From int"); BasicSelectionTestClass_ushort_e_e_tc_Conv temp = new BasicSelectionTestClass_ushort_e_e_tc_Conv(); temp.value_int = val; return (temp); } public int GetValueint() { return (value_int); } public void SetValueint(int val) { value_int = val; } private long value_long; static public explicit operator long(BasicSelectionTestClass_ushort_e_e_tc_Conv test) { Log.Comment("To long"); return test.value_long; } static public explicit operator BasicSelectionTestClass_ushort_e_e_tc_Conv(long val) { Log.Comment("From long"); BasicSelectionTestClass_ushort_e_e_tc_Conv temp = new BasicSelectionTestClass_ushort_e_e_tc_Conv(); temp.value_long = val; return (temp); } public long GetValuelong() { return (value_long); } public void SetValuelong(long val) { value_long = val; } private sbyte value_sbyte; static public explicit operator sbyte(BasicSelectionTestClass_ushort_e_e_tc_Conv test) { Log.Comment("To sbyte"); return test.value_sbyte; } static public explicit operator BasicSelectionTestClass_ushort_e_e_tc_Conv(sbyte val) { Log.Comment("From sbyte"); BasicSelectionTestClass_ushort_e_e_tc_Conv temp = new BasicSelectionTestClass_ushort_e_e_tc_Conv(); temp.value_sbyte = val; return (temp); } public sbyte GetValuesbyte() { return (value_sbyte); } public void SetValuesbyte(sbyte val) { value_sbyte = val; } private short value_short; static public explicit operator short(BasicSelectionTestClass_ushort_e_e_tc_Conv test) { Log.Comment("To short"); return test.value_short; } static public explicit operator BasicSelectionTestClass_ushort_e_e_tc_Conv(short val) { Log.Comment("From short"); BasicSelectionTestClass_ushort_e_e_tc_Conv temp = new BasicSelectionTestClass_ushort_e_e_tc_Conv(); temp.value_short = val; return (temp); } public short GetValueshort() { return (value_short); } public void SetValueshort(short val) { value_short = val; } private uint value_uint; static public explicit operator uint(BasicSelectionTestClass_ushort_e_e_tc_Conv test) { Log.Comment("To uint"); return test.value_uint; } static public explicit operator BasicSelectionTestClass_ushort_e_e_tc_Conv(uint val) { Log.Comment("From uint"); BasicSelectionTestClass_ushort_e_e_tc_Conv temp = new BasicSelectionTestClass_ushort_e_e_tc_Conv(); temp.value_uint = val; return (temp); } public uint GetValueuint() { return (value_uint); } public void SetValueuint(uint val) { value_uint = val; } private ulong value_ulong; static public explicit operator ulong(BasicSelectionTestClass_ushort_e_e_tc_Conv test) { Log.Comment("To ulong"); return test.value_ulong; } static public explicit operator BasicSelectionTestClass_ushort_e_e_tc_Conv(ulong val) { Log.Comment("From ulong"); BasicSelectionTestClass_ushort_e_e_tc_Conv temp = new BasicSelectionTestClass_ushort_e_e_tc_Conv(); temp.value_ulong = val; return (temp); } public ulong GetValueulong() { return (value_ulong); } public void SetValueulong(ulong val) { value_ulong = val; } private ushort value_ushort; static public explicit operator ushort(BasicSelectionTestClass_ushort_e_e_tc_Conv test) { Log.Comment("To ushort"); return test.value_ushort; } static public explicit operator BasicSelectionTestClass_ushort_e_e_tc_Conv(ushort val) { Log.Comment("From ushort"); BasicSelectionTestClass_ushort_e_e_tc_Conv temp = new BasicSelectionTestClass_ushort_e_e_tc_Conv(); temp.value_ushort = val; return (temp); } public ushort GetValueushort() { return (value_ushort); } public void SetValueushort(ushort val) { value_ushort = val; } } class BasicSelectionTestClass_ushort_e_e_tc { public static int Main_old() { BasicSelectionTestClass_ushort_e_e_tc_Conv cl = new BasicSelectionTestClass_ushort_e_e_tc_Conv(); ushort val = 1; cl = (BasicSelectionTestClass_ushort_e_e_tc_Conv)val; if (cl.GetValueushort() != 1) return 1; else return 0; } public static bool testMethod() { return (Main_old() == 0); } } class BasicSelectionTestClass_ushort_i_i_fc_Conv { private byte value_byte; static public implicit operator byte(BasicSelectionTestClass_ushort_i_i_fc_Conv test) { Log.Comment("To byte"); return test.value_byte; } static public implicit operator BasicSelectionTestClass_ushort_i_i_fc_Conv(byte val) { Log.Comment("From byte"); BasicSelectionTestClass_ushort_i_i_fc_Conv temp = new BasicSelectionTestClass_ushort_i_i_fc_Conv(); temp.value_byte = val; return (temp); } public byte GetValuebyte() { return (value_byte); } public void SetValuebyte(byte val) { value_byte = val; } private char value_char; static public implicit operator char(BasicSelectionTestClass_ushort_i_i_fc_Conv test) { Log.Comment("To char"); return test.value_char; } static public implicit operator BasicSelectionTestClass_ushort_i_i_fc_Conv(char val) { Log.Comment("From char"); BasicSelectionTestClass_ushort_i_i_fc_Conv temp = new BasicSelectionTestClass_ushort_i_i_fc_Conv(); temp.value_char = val; return (temp); } public char GetValuechar() { return (value_char); } public void SetValuechar(char val) { value_char = val; } private double value_double; static public implicit operator double(BasicSelectionTestClass_ushort_i_i_fc_Conv test) { Log.Comment("To double"); return test.value_double; } static public implicit operator BasicSelectionTestClass_ushort_i_i_fc_Conv(double val) { Log.Comment("From double"); BasicSelectionTestClass_ushort_i_i_fc_Conv temp = new BasicSelectionTestClass_ushort_i_i_fc_Conv(); temp.value_double = val; return (temp); } public double GetValuedouble() { return (value_double); } public void SetValuedouble(double val) { value_double = val; } private float value_float; static public implicit operator float(BasicSelectionTestClass_ushort_i_i_fc_Conv test) { Log.Comment("To float"); return test.value_float; } static public implicit operator BasicSelectionTestClass_ushort_i_i_fc_Conv(float val) { Log.Comment("From float"); BasicSelectionTestClass_ushort_i_i_fc_Conv temp = new BasicSelectionTestClass_ushort_i_i_fc_Conv(); temp.value_float = val; return (temp); } public float GetValuefloat() { return (value_float); } public void SetValuefloat(float val) { value_float = val; } private int value_int; static public implicit operator int(BasicSelectionTestClass_ushort_i_i_fc_Conv test) { Log.Comment("To int"); return test.value_int; } static public implicit operator BasicSelectionTestClass_ushort_i_i_fc_Conv(int val) { Log.Comment("From int"); BasicSelectionTestClass_ushort_i_i_fc_Conv temp = new BasicSelectionTestClass_ushort_i_i_fc_Conv(); temp.value_int = val; return (temp); } public int GetValueint() { return (value_int); } public void SetValueint(int val) { value_int = val; } private long value_long; static public implicit operator long(BasicSelectionTestClass_ushort_i_i_fc_Conv test) { Log.Comment("To long"); return test.value_long; } static public implicit operator BasicSelectionTestClass_ushort_i_i_fc_Conv(long val) { Log.Comment("From long"); BasicSelectionTestClass_ushort_i_i_fc_Conv temp = new BasicSelectionTestClass_ushort_i_i_fc_Conv(); temp.value_long = val; return (temp); } public long GetValuelong() { return (value_long); } public void SetValuelong(long val) { value_long = val; } private sbyte value_sbyte; static public implicit operator sbyte(BasicSelectionTestClass_ushort_i_i_fc_Conv test) { Log.Comment("To sbyte"); return test.value_sbyte; } static public implicit operator BasicSelectionTestClass_ushort_i_i_fc_Conv(sbyte val) { Log.Comment("From sbyte"); BasicSelectionTestClass_ushort_i_i_fc_Conv temp = new BasicSelectionTestClass_ushort_i_i_fc_Conv(); temp.value_sbyte = val; return (temp); } public sbyte GetValuesbyte() { return (value_sbyte); } public void SetValuesbyte(sbyte val) { value_sbyte = val; } private short value_short; static public implicit operator short(BasicSelectionTestClass_ushort_i_i_fc_Conv test) { Log.Comment("To short"); return test.value_short; } static public implicit operator BasicSelectionTestClass_ushort_i_i_fc_Conv(short val) { Log.Comment("From short"); BasicSelectionTestClass_ushort_i_i_fc_Conv temp = new BasicSelectionTestClass_ushort_i_i_fc_Conv(); temp.value_short = val; return (temp); } public short GetValueshort() { return (value_short); } public void SetValueshort(short val) { value_short = val; } private uint value_uint; static public implicit operator uint(BasicSelectionTestClass_ushort_i_i_fc_Conv test) { Log.Comment("To uint"); return test.value_uint; } static public implicit operator BasicSelectionTestClass_ushort_i_i_fc_Conv(uint val) { Log.Comment("From uint"); BasicSelectionTestClass_ushort_i_i_fc_Conv temp = new BasicSelectionTestClass_ushort_i_i_fc_Conv(); temp.value_uint = val; return (temp); } public uint GetValueuint() { return (value_uint); } public void SetValueuint(uint val) { value_uint = val; } private ulong value_ulong; static public implicit operator ulong(BasicSelectionTestClass_ushort_i_i_fc_Conv test) { Log.Comment("To ulong"); return test.value_ulong; } static public implicit operator BasicSelectionTestClass_ushort_i_i_fc_Conv(ulong val) { Log.Comment("From ulong"); BasicSelectionTestClass_ushort_i_i_fc_Conv temp = new BasicSelectionTestClass_ushort_i_i_fc_Conv(); temp.value_ulong = val; return (temp); } public ulong GetValueulong() { return (value_ulong); } public void SetValueulong(ulong val) { value_ulong = val; } private ushort value_ushort; static public implicit operator ushort(BasicSelectionTestClass_ushort_i_i_fc_Conv test) { Log.Comment("To ushort"); return test.value_ushort; } static public implicit operator BasicSelectionTestClass_ushort_i_i_fc_Conv(ushort val) { Log.Comment("From ushort"); BasicSelectionTestClass_ushort_i_i_fc_Conv temp = new BasicSelectionTestClass_ushort_i_i_fc_Conv(); temp.value_ushort = val; return (temp); } public ushort GetValueushort() { return (value_ushort); } public void SetValueushort(ushort val) { value_ushort = val; } } class BasicSelectionTestClass_ushort_i_i_fc { public static int Main_old() { BasicSelectionTestClass_ushort_i_i_fc_Conv cl = new BasicSelectionTestClass_ushort_i_i_fc_Conv(); cl.SetValueushort(1); ushort value = cl; if (value != 1) return 1; else return 0; } public static bool testMethod() { return (Main_old() == 0); } } class BasicSelectionTestClass_ushort_i_e_fc_Conv { private byte value_byte; static public implicit operator byte(BasicSelectionTestClass_ushort_i_e_fc_Conv test) { Log.Comment("To byte"); return test.value_byte; } static public implicit operator BasicSelectionTestClass_ushort_i_e_fc_Conv(byte val) { Log.Comment("From byte"); BasicSelectionTestClass_ushort_i_e_fc_Conv temp = new BasicSelectionTestClass_ushort_i_e_fc_Conv(); temp.value_byte = val; return (temp); } public byte GetValuebyte() { return (value_byte); } public void SetValuebyte(byte val) { value_byte = val; } private char value_char; static public implicit operator char(BasicSelectionTestClass_ushort_i_e_fc_Conv test) { Log.Comment("To char"); return test.value_char; } static public implicit operator BasicSelectionTestClass_ushort_i_e_fc_Conv(char val) { Log.Comment("From char"); BasicSelectionTestClass_ushort_i_e_fc_Conv temp = new BasicSelectionTestClass_ushort_i_e_fc_Conv(); temp.value_char = val; return (temp); } public char GetValuechar() { return (value_char); } public void SetValuechar(char val) { value_char = val; } private double value_double; static public implicit operator double(BasicSelectionTestClass_ushort_i_e_fc_Conv test) { Log.Comment("To double"); return test.value_double; } static public implicit operator BasicSelectionTestClass_ushort_i_e_fc_Conv(double val) { Log.Comment("From double"); BasicSelectionTestClass_ushort_i_e_fc_Conv temp = new BasicSelectionTestClass_ushort_i_e_fc_Conv(); temp.value_double = val; return (temp); } public double GetValuedouble() { return (value_double); } public void SetValuedouble(double val) { value_double = val; } private float value_float; static public implicit operator float(BasicSelectionTestClass_ushort_i_e_fc_Conv test) { Log.Comment("To float"); return test.value_float; } static public implicit operator BasicSelectionTestClass_ushort_i_e_fc_Conv(float val) { Log.Comment("From float"); BasicSelectionTestClass_ushort_i_e_fc_Conv temp = new BasicSelectionTestClass_ushort_i_e_fc_Conv(); temp.value_float = val; return (temp); } public float GetValuefloat() { return (value_float); } public void SetValuefloat(float val) { value_float = val; } private int value_int; static public implicit operator int(BasicSelectionTestClass_ushort_i_e_fc_Conv test) { Log.Comment("To int"); return test.value_int; } static public implicit operator BasicSelectionTestClass_ushort_i_e_fc_Conv(int val) { Log.Comment("From int"); BasicSelectionTestClass_ushort_i_e_fc_Conv temp = new BasicSelectionTestClass_ushort_i_e_fc_Conv(); temp.value_int = val; return (temp); } public int GetValueint() { return (value_int); } public void SetValueint(int val) { value_int = val; } private long value_long; static public implicit operator long(BasicSelectionTestClass_ushort_i_e_fc_Conv test) { Log.Comment("To long"); return test.value_long; } static public implicit operator BasicSelectionTestClass_ushort_i_e_fc_Conv(long val) { Log.Comment("From long"); BasicSelectionTestClass_ushort_i_e_fc_Conv temp = new BasicSelectionTestClass_ushort_i_e_fc_Conv(); temp.value_long = val; return (temp); } public long GetValuelong() { return (value_long); } public void SetValuelong(long val) { value_long = val; } private sbyte value_sbyte; static public implicit operator sbyte(BasicSelectionTestClass_ushort_i_e_fc_Conv test) { Log.Comment("To sbyte"); return test.value_sbyte; } static public implicit operator BasicSelectionTestClass_ushort_i_e_fc_Conv(sbyte val) { Log.Comment("From sbyte"); BasicSelectionTestClass_ushort_i_e_fc_Conv temp = new BasicSelectionTestClass_ushort_i_e_fc_Conv(); temp.value_sbyte = val; return (temp); } public sbyte GetValuesbyte() { return (value_sbyte); } public void SetValuesbyte(sbyte val) { value_sbyte = val; } private short value_short; static public implicit operator short(BasicSelectionTestClass_ushort_i_e_fc_Conv test) { Log.Comment("To short"); return test.value_short; } static public implicit operator BasicSelectionTestClass_ushort_i_e_fc_Conv(short val) { Log.Comment("From short"); BasicSelectionTestClass_ushort_i_e_fc_Conv temp = new BasicSelectionTestClass_ushort_i_e_fc_Conv(); temp.value_short = val; return (temp); } public short GetValueshort() { return (value_short); } public void SetValueshort(short val) { value_short = val; } private uint value_uint; static public implicit operator uint(BasicSelectionTestClass_ushort_i_e_fc_Conv test) { Log.Comment("To uint"); return test.value_uint; } static public implicit operator BasicSelectionTestClass_ushort_i_e_fc_Conv(uint val) { Log.Comment("From uint"); BasicSelectionTestClass_ushort_i_e_fc_Conv temp = new BasicSelectionTestClass_ushort_i_e_fc_Conv(); temp.value_uint = val; return (temp); } public uint GetValueuint() { return (value_uint); } public void SetValueuint(uint val) { value_uint = val; } private ulong value_ulong; static public implicit operator ulong(BasicSelectionTestClass_ushort_i_e_fc_Conv test) { Log.Comment("To ulong"); return test.value_ulong; } static public implicit operator BasicSelectionTestClass_ushort_i_e_fc_Conv(ulong val) { Log.Comment("From ulong"); BasicSelectionTestClass_ushort_i_e_fc_Conv temp = new BasicSelectionTestClass_ushort_i_e_fc_Conv(); temp.value_ulong = val; return (temp); } public ulong GetValueulong() { return (value_ulong); } public void SetValueulong(ulong val) { value_ulong = val; } private ushort value_ushort; static public implicit operator ushort(BasicSelectionTestClass_ushort_i_e_fc_Conv test) { Log.Comment("To ushort"); return test.value_ushort; } static public implicit operator BasicSelectionTestClass_ushort_i_e_fc_Conv(ushort val) { Log.Comment("From ushort"); BasicSelectionTestClass_ushort_i_e_fc_Conv temp = new BasicSelectionTestClass_ushort_i_e_fc_Conv(); temp.value_ushort = val; return (temp); } public ushort GetValueushort() { return (value_ushort); } public void SetValueushort(ushort val) { value_ushort = val; } } class BasicSelectionTestClass_ushort_i_e_fc { public static int Main_old() { BasicSelectionTestClass_ushort_i_e_fc_Conv cl = new BasicSelectionTestClass_ushort_i_e_fc_Conv(); cl.SetValueushort(1); ushort value = (ushort)cl; if (value != 1) return 1; else return 0; } public static bool testMethod() { return (Main_old() == 0); } } class BasicSelectionTestClass_ushort_e_e_fc_Conv { private byte value_byte; static public explicit operator byte(BasicSelectionTestClass_ushort_e_e_fc_Conv test) { Log.Comment("To byte"); return test.value_byte; } static public explicit operator BasicSelectionTestClass_ushort_e_e_fc_Conv(byte val) { Log.Comment("From byte"); BasicSelectionTestClass_ushort_e_e_fc_Conv temp = new BasicSelectionTestClass_ushort_e_e_fc_Conv(); temp.value_byte = val; return (temp); } public byte GetValuebyte() { return (value_byte); } public void SetValuebyte(byte val) { value_byte = val; } private char value_char; static public explicit operator char(BasicSelectionTestClass_ushort_e_e_fc_Conv test) { Log.Comment("To char"); return test.value_char; } static public explicit operator BasicSelectionTestClass_ushort_e_e_fc_Conv(char val) { Log.Comment("From char"); BasicSelectionTestClass_ushort_e_e_fc_Conv temp = new BasicSelectionTestClass_ushort_e_e_fc_Conv(); temp.value_char = val; return (temp); } public char GetValuechar() { return (value_char); } public void SetValuechar(char val) { value_char = val; } private double value_double; static public explicit operator double(BasicSelectionTestClass_ushort_e_e_fc_Conv test) { Log.Comment("To double"); return test.value_double; } static public explicit operator BasicSelectionTestClass_ushort_e_e_fc_Conv(double val) { Log.Comment("From double"); BasicSelectionTestClass_ushort_e_e_fc_Conv temp = new BasicSelectionTestClass_ushort_e_e_fc_Conv(); temp.value_double = val; return (temp); } public double GetValuedouble() { return (value_double); } public void SetValuedouble(double val) { value_double = val; } private float value_float; static public explicit operator float(BasicSelectionTestClass_ushort_e_e_fc_Conv test) { Log.Comment("To float"); return test.value_float; } static public explicit operator BasicSelectionTestClass_ushort_e_e_fc_Conv(float val) { Log.Comment("From float"); BasicSelectionTestClass_ushort_e_e_fc_Conv temp = new BasicSelectionTestClass_ushort_e_e_fc_Conv(); temp.value_float = val; return (temp); } public float GetValuefloat() { return (value_float); } public void SetValuefloat(float val) { value_float = val; } private int value_int; static public explicit operator int(BasicSelectionTestClass_ushort_e_e_fc_Conv test) { Log.Comment("To int"); return test.value_int; } static public explicit operator BasicSelectionTestClass_ushort_e_e_fc_Conv(int val) { Log.Comment("From int"); BasicSelectionTestClass_ushort_e_e_fc_Conv temp = new BasicSelectionTestClass_ushort_e_e_fc_Conv(); temp.value_int = val; return (temp); } public int GetValueint() { return (value_int); } public void SetValueint(int val) { value_int = val; } private long value_long; static public explicit operator long(BasicSelectionTestClass_ushort_e_e_fc_Conv test) { Log.Comment("To long"); return test.value_long; } static public explicit operator BasicSelectionTestClass_ushort_e_e_fc_Conv(long val) { Log.Comment("From long"); BasicSelectionTestClass_ushort_e_e_fc_Conv temp = new BasicSelectionTestClass_ushort_e_e_fc_Conv(); temp.value_long = val; return (temp); } public long GetValuelong() { return (value_long); } public void SetValuelong(long val) { value_long = val; } private sbyte value_sbyte; static public explicit operator sbyte(BasicSelectionTestClass_ushort_e_e_fc_Conv test) { Log.Comment("To sbyte"); return test.value_sbyte; } static public explicit operator BasicSelectionTestClass_ushort_e_e_fc_Conv(sbyte val) { Log.Comment("From sbyte"); BasicSelectionTestClass_ushort_e_e_fc_Conv temp = new BasicSelectionTestClass_ushort_e_e_fc_Conv(); temp.value_sbyte = val; return (temp); } public sbyte GetValuesbyte() { return (value_sbyte); } public void SetValuesbyte(sbyte val) { value_sbyte = val; } private short value_short; static public explicit operator short(BasicSelectionTestClass_ushort_e_e_fc_Conv test) { Log.Comment("To short"); return test.value_short; } static public explicit operator BasicSelectionTestClass_ushort_e_e_fc_Conv(short val) { Log.Comment("From short"); BasicSelectionTestClass_ushort_e_e_fc_Conv temp = new BasicSelectionTestClass_ushort_e_e_fc_Conv(); temp.value_short = val; return (temp); } public short GetValueshort() { return (value_short); } public void SetValueshort(short val) { value_short = val; } private uint value_uint; static public explicit operator uint(BasicSelectionTestClass_ushort_e_e_fc_Conv test) { Log.Comment("To uint"); return test.value_uint; } static public explicit operator BasicSelectionTestClass_ushort_e_e_fc_Conv(uint val) { Log.Comment("From uint"); BasicSelectionTestClass_ushort_e_e_fc_Conv temp = new BasicSelectionTestClass_ushort_e_e_fc_Conv(); temp.value_uint = val; return (temp); } public uint GetValueuint() { return (value_uint); } public void SetValueuint(uint val) { value_uint = val; } private ulong value_ulong; static public explicit operator ulong(BasicSelectionTestClass_ushort_e_e_fc_Conv test) { Log.Comment("To ulong"); return test.value_ulong; } static public explicit operator BasicSelectionTestClass_ushort_e_e_fc_Conv(ulong val) { Log.Comment("From ulong"); BasicSelectionTestClass_ushort_e_e_fc_Conv temp = new BasicSelectionTestClass_ushort_e_e_fc_Conv(); temp.value_ulong = val; return (temp); } public ulong GetValueulong() { return (value_ulong); } public void SetValueulong(ulong val) { value_ulong = val; } private ushort value_ushort; static public explicit operator ushort(BasicSelectionTestClass_ushort_e_e_fc_Conv test) { Log.Comment("To ushort"); return test.value_ushort; } static public explicit operator BasicSelectionTestClass_ushort_e_e_fc_Conv(ushort val) { Log.Comment("From ushort"); BasicSelectionTestClass_ushort_e_e_fc_Conv temp = new BasicSelectionTestClass_ushort_e_e_fc_Conv(); temp.value_ushort = val; return (temp); } public ushort GetValueushort() { return (value_ushort); } public void SetValueushort(ushort val) { value_ushort = val; } } class BasicSelectionTestClass_ushort_e_e_fc { public static int Main_old() { BasicSelectionTestClass_ushort_e_e_fc_Conv cl = new BasicSelectionTestClass_ushort_e_e_fc_Conv(); cl.SetValueushort(1); ushort value = (ushort)cl; if (value != 1) return 1; else return 0; } public static bool testMethod() { return (Main_old() == 0); } } } } ================================================ FILE: Zelig/Zelig/Test/RunTime/NETMF/mscorlib/delegates/DelegatesTests.cs ================================================ //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // Copyright (c) Microsoft Corporation. All rights reserved. //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// using System; using System.Reflection; using Microsoft.SPOT.Platform.Test; namespace Microsoft.SPOT.Platform.Tests { public class DelegatesTests : IMFTestInterface { [SetUp] public InitializeResult Initialize() { Log.Comment("Adding set up for the tests."); // Add your functionality here. return InitializeResult.ReadyToGo; } [TearDown] public void CleanUp() { Log.Comment("Cleaning up after the tests"); } //Delegates Test methods //The following tests were ported from folder current\test\cases\client\CLR\Conformance\10_classes\Delegates //delegate01,delegate02,delegate03,delegate04,delegate05,delegate06,delegate07,delegate08,delegate09,delegate10,delegate11,delegate12,delegate13,delegate14,delegate14a,delegate14b,delegate14c,delegate15,delegate16,delegate17,delegate18,delegate19,delegate20,delegate21,delegate23,delegate24,delegate25,delegate26,delegate28,delegate30,delegate31,delegate32,delegate34,delegate36,delegate60,delegate62,delegate64,delegate65,delegate66,delegate70,delegate71,delegate72,delegate73,delegate74,delegate75,delegate76,delegate77,delegate78,delegate79,delegate80,delegate81,delegate_modifier09,delegate_modifier10,delegate_modifier11,delegate_modifier12 //Test Case Calls [TestMethod] public MFTestResults Delegate_delegate01_Test() { Log.Comment(" Verify that both static and instance methods can be called from delegates."); if (Delegate_TestClass_delegate01.testMethod()) { return MFTestResults.Pass; } return MFTestResults.Fail; } [TestMethod] public MFTestResults Delegate_delegate02_Test() { Log.Comment(" Verify that delegate can be initialized to null."); if (Delegate_TestClass_delegate02.testMethod()) { return MFTestResults.Pass; } return MFTestResults.Fail; } [TestMethod] public MFTestResults Delegate_delegate03_Test() { Log.Comment(" Verify that delegate can be initialized to null."); if (Delegate_TestClass_delegate03.testMethod()) { return MFTestResults.Pass; } return MFTestResults.Fail; } [TestMethod] public MFTestResults Delegate_delegate04_Test() { Log.Comment(" Verify that delegate can be assigned by ternary operator."); if (Delegate_TestClass_delegate04.testMethod()) { return MFTestResults.Pass; } return MFTestResults.Fail; } [TestMethod] public MFTestResults Delegate_delegate05_Test() { Log.Comment(" Verify that delegate can be assigned by ternary operator."); if (Delegate_TestClass_delegate05.testMethod()) { return MFTestResults.Pass; } return MFTestResults.Fail; } [TestMethod] public MFTestResults Delegate_delegate06_Test() { Log.Comment(" Verify that delegate can be assigned by ternary operator. Assign null instead of usable value."); if (Delegate_TestClass_delegate06.testMethod()) { return MFTestResults.Pass; } return MFTestResults.Fail; } [TestMethod] public MFTestResults Delegate_delegate07_Test() { Log.Comment(" Verify that delegate can be assigned by ternary operator. Use null instead of a usable value."); if (Delegate_TestClass_delegate07.testMethod()) { return MFTestResults.Pass; } return MFTestResults.Fail; } [TestMethod] public MFTestResults Delegate_delegate08_Test() { Log.Comment(" Verify that delegate can be assigned by ternary operator. Assign null instead of usable value."); if (Delegate_TestClass_delegate08.testMethod()) { return MFTestResults.Pass; } return MFTestResults.Fail; } [TestMethod] public MFTestResults Delegate_delegate09_Test() { Log.Comment(" Verify that delegates can be compared for equality."); if (Delegate_TestClass_delegate09.testMethod()) { return MFTestResults.Pass; } return MFTestResults.Fail; } [TestMethod] public MFTestResults Delegate_delegate10_Test() { Log.Comment(" Verify that delegates can be aggregated in arrays and compared for equality."); if (Delegate_TestClass_delegate10.testMethod()) { return MFTestResults.Pass; } return MFTestResults.Fail; } [TestMethod] public MFTestResults Delegate_delegate11_Test() { Log.Comment(" Verify that delegates can be members of classes."); if (Delegate_TestClass_delegate11.testMethod()) { return MFTestResults.Pass; } return MFTestResults.Fail; } [TestMethod] public MFTestResults Delegate_delegate12_Test() { Log.Comment(" Verify that both static and instance methods can be called from delegates."); if (Delegate_TestClass_delegate12.testMethod()) { return MFTestResults.Pass; } return MFTestResults.Fail; } [TestMethod] public MFTestResults Delegate_delegate13_Test() { Log.Comment(" Verify that delegate can be initialized to null."); if (Delegate_TestClass_delegate13.testMethod()) { return MFTestResults.Pass; } return MFTestResults.Fail; } [TestMethod] public MFTestResults Delegate_delegate14_Test() { Log.Comment(" Verify that delegate can be initialized to null."); if (Delegate_TestClass_delegate14.testMethod()) { return MFTestResults.Pass; } return MFTestResults.Fail; } [TestMethod] public MFTestResults Delegate_delegate14a_Test() { Log.Comment(" Verify that delegate can be initialized to null."); if (Delegate_TestClass_delegate14a.testMethod()) { return MFTestResults.Pass; } return MFTestResults.Fail; } [TestMethod] public MFTestResults Delegate_delegate14b_Test() { Log.Comment(" Verify that delegate can be initialized to null."); if (Delegate_TestClass_delegate14b.testMethod()) { return MFTestResults.Pass; } return MFTestResults.Fail; } [TestMethod] public MFTestResults Delegate_delegate14c_Test() { Log.Comment(" Verify that delegate can be initialized to null."); if (Delegate_TestClass_delegate14c.testMethod()) { return MFTestResults.Pass; } return MFTestResults.Fail; } [TestMethod] public MFTestResults Delegate_delegate15_Test() { Log.Comment(" Verify that delegate can be assigned by ternary operator."); if (Delegate_TestClass_delegate15.testMethod()) { return MFTestResults.Pass; } return MFTestResults.Fail; } [TestMethod] public MFTestResults Delegate_delegate16_Test() { Log.Comment(" Verify that delegate can be assigned by ternary operator."); if (Delegate_TestClass_delegate16.testMethod()) { return MFTestResults.Pass; } return MFTestResults.Fail; } [TestMethod] public MFTestResults Delegate_delegate17_Test() { Log.Comment(" Verify that delegate can be assigned by ternary operator. Assign null instead of usable value."); if (Delegate_TestClass_delegate17.testMethod()) { return MFTestResults.Pass; } return MFTestResults.Fail; } [TestMethod] public MFTestResults Delegate_delegate18_Test() { Log.Comment(" Make sure a delegate list filled with nulls is detectable as foo == null"); if (Delegate_TestClass_delegate18.testMethod()) { return MFTestResults.Pass; } return MFTestResults.Fail; } [TestMethod] public MFTestResults Delegate_delegate19_Test() { Log.Comment(" Verify that delegates can be aggregated in arrays and compared for equality."); if (Delegate_TestClass_delegate19.testMethod()) { return MFTestResults.Pass; } return MFTestResults.Fail; } [TestMethod] public MFTestResults Delegate_delegate20_Test() { Log.Comment(" Verify that delegates can be compared for equality."); if (Delegate_TestClass_delegate20.testMethod()) { return MFTestResults.Pass; } return MFTestResults.Fail; } [TestMethod] public MFTestResults Delegate_delegate21_Test() { Log.Comment(" Verify that delegates can be aggregated in arrays and compared for equality."); if (Delegate_TestClass_delegate21.testMethod()) { return MFTestResults.Pass; } return MFTestResults.Fail; } [TestMethod] public MFTestResults Delegate_delegate23_Test() { Log.Comment(" Verify that delegates can be aggregated using the + operator;"); if (Delegate_TestClass_delegate23.testMethod()) { return MFTestResults.Pass; } return MFTestResults.Fail; } [TestMethod] public MFTestResults Delegate_delegate24_Test() { Log.Comment(" Verify that delegates can be aggregated using the + operator;"); if (Delegate_TestClass_delegate24.testMethod()) { return MFTestResults.Pass; } return MFTestResults.Fail; } [TestMethod] public MFTestResults Delegate_delegate25_Test() { Log.Comment(" Verify that delegates can be removed using the - operator;"); if (Delegate_TestClass_delegate25.testMethod()) { return MFTestResults.Pass; } return MFTestResults.Fail; } [TestMethod] public MFTestResults Delegate_delegate26_Test() { Log.Comment("Bug 214780 - async delegates to methods with out parameters don't work"); Log.Comment("This test is expected to fail."); if (Delegate_TestClass_delegate26.testMethod()) { return MFTestResults.Fail; } return MFTestResults.Pass; } /* This test is skipped because it causes a Metadat processor error, it fails in the baseline. [TestMethod] public MFTestResults Delegate_delegate28_Test() { Log.Comment("Verify Delegate with 257 args. This is because more than 257 causes the"); Log.Comment("compiler to take a different code path."); if (Delegate_TestClass_delegate28.testMethod()) { return MFTestResults.Pass; } return MFTestResults.Fail; } */ [TestMethod] public MFTestResults Delegate_delegate30_Test() { Log.Comment(" Verify that both static and instance struct methods can be called from delegates."); if (Delegate_TestClass_delegate30.testMethod()) { return MFTestResults.Pass; } return MFTestResults.Fail; } [TestMethod] public MFTestResults Delegate_delegate31_Test() { Log.Comment(" Verify that virtual struct methods can be called from delegates."); if (Delegate_TestClass_delegate31.testMethod()) { return MFTestResults.Pass; } return MFTestResults.Fail; } /*These are skipped due to their use of Volatile variables which are not supported * [TestMethod] public MFTestResults Delegate_delegate32_Test() { Log.Comment("Delegate Invocation using BeginInvoke"); if (Delegate_TestClass_delegate32.testMethod()) { return MFTestResults.Pass; } return MFTestResults.Fail; } [TestMethod] public MFTestResults Delegate_delegate34_Test() { Log.Comment("Delegate Invocation using BeginInvoke"); if (Delegate_TestClass_delegate34.testMethod()) { return MFTestResults.Pass; } return MFTestResults.Fail; } */ [TestMethod] public MFTestResults Delegate_delegate36_Test() { Log.Comment("params modifier should not be considered when matching a delegate with a method"); if (Delegate_TestClass_delegate36.testMethod()) { return MFTestResults.Pass; } return MFTestResults.Fail; } [TestMethod] public MFTestResults Delegate_delegate60_Test() { Log.Comment("A delegate declaration defines a class that derives from System.Delegate"); if (Delegate_TestClass_delegate60.testMethod()) { return MFTestResults.Pass; } return MFTestResults.Fail; } [TestMethod] public MFTestResults Delegate_delegate62_Test() { Log.Comment("The compiler is expected to warn that the new keyword id not rquired as we're not hiding an inherited member"); if (Delegate_TestClass_delegate62.testMethod()) { return MFTestResults.Pass; } return MFTestResults.Fail; } [TestMethod] public MFTestResults Delegate_delegate64_Test() { Log.Comment("Compiler is expected to warn when new is not used when hiding a member delegate of the base class"); if (Delegate_TestClass_delegate64.testMethod()) { return MFTestResults.Pass; } return MFTestResults.Fail; } [TestMethod] public MFTestResults Delegate_delegate65_Test() { Log.Comment("Make sure delegates can be hidden."); if (Delegate_TestClass_delegate65.testMethod()) { return MFTestResults.Pass; } return MFTestResults.Fail; } /*These tests are skipped because the use the == operator in an unsupported way * [TestMethod] public MFTestResults Delegate_delegate66_Test() { Log.Comment("Two compatible delegate types can be compared for equality."); if (Delegate_TestClass_delegate66.testMethod()) { return MFTestResults.Pass; } return MFTestResults.Fail; } [TestMethod] public MFTestResults Delegate_delegate70_Test() { Log.Comment("Two compatible delegate types can be compared for equality (or inequality)."); if (Delegate_TestClass_delegate70.testMethod()) { return MFTestResults.Pass; } return MFTestResults.Fail; } */ [TestMethod] public MFTestResults Delegate_delegate71_Test() { Log.Comment("Verify simple +="); if (Delegate_TestClass_delegate71.testMethod()) { return MFTestResults.Pass; } return MFTestResults.Fail; } [TestMethod] public MFTestResults Delegate_delegate72_Test() { Log.Comment(" Verify that delegates can be removed using the -= operator;"); if (Delegate_TestClass_delegate72.testMethod()) { return MFTestResults.Pass; } return MFTestResults.Fail; } /* These tests are skipped because they use == in an unsupported way * [TestMethod] public MFTestResults Delegate_delegate73_Test() { Log.Comment("Verify equality and inequality after using += and -= on delegates"); if (Delegate_TestClass_delegate73.testMethod()) { return MFTestResults.Pass; } return MFTestResults.Fail; } [TestMethod] public MFTestResults Delegate_delegate74_Test() { Log.Comment("Verify ability to call members of System.Delegate on delegate types"); if (Delegate_TestClass_delegate74.testMethod()) { return MFTestResults.Pass; } return MFTestResults.Fail; } [TestMethod] public MFTestResults Delegate_delegate75_Test() { Log.Comment("Verify ability to call members of System.Delegate on delegate types"); Log.Comment("and that ordinality is maintained in concatenated invocation lists"); if (Delegate_TestClass_delegate75.testMethod()) { return MFTestResults.Pass; } return MFTestResults.Fail; } [TestMethod] public MFTestResults Delegate_delegate76_Test() { Log.Comment("Verify ability to call members of System.Delegate on delegate types"); Log.Comment("and that ordinality is maintained in concatenated invocation lists"); if (Delegate_TestClass_delegate76.testMethod()) { return MFTestResults.Pass; } return MFTestResults.Fail; } */ [TestMethod] public MFTestResults Delegate_delegate77_Test() { Log.Comment("Verify that ordinality is maintained in concatenated invocation lists"); Log.Comment("and that the invocation list members are called synchronously"); if (Delegate_TestClass_delegate77.testMethod()) { return MFTestResults.Pass; } return MFTestResults.Fail; } [TestMethod] public MFTestResults Delegate_delegate78_Test() { Log.Comment("Verify that ordinality is maintained in concatenated invocation lists"); Log.Comment("and that the invocation list members are called synchronously and"); Log.Comment("that ref parameters are modified through the invocation chain."); if (Delegate_TestClass_delegate78.testMethod()) { return MFTestResults.Pass; } return MFTestResults.Fail; } [TestMethod] public MFTestResults Delegate_delegate79_Test() { Log.Comment("Verify that ordinality is maintained in concatenated invocation lists"); Log.Comment("and that the invocation list members are called synchronously and"); Log.Comment("that out parameters are set by the last member in the invocation chain."); if (Delegate_TestClass_delegate79.testMethod()) { return MFTestResults.Pass; } return MFTestResults.Fail; } [TestMethod] public MFTestResults Delegate_delegate80_Test() { Log.Comment("Verify that System.Exceptions not caught in invoked method are bubbled up"); Log.Comment("and the remaining methods in the invocation list are not invoked."); if (Delegate_TestClass_delegate80.testMethod()) { return MFTestResults.Pass; } return MFTestResults.Fail; } [TestMethod] public MFTestResults Delegate_delegate81_Test() { Log.Comment("Sample from section 15.3 of Delegate_TestClass_?_A#LS"); if (Delegate_TestClass_delegate81.testMethod()) { return MFTestResults.Pass; } return MFTestResults.Fail; } [TestMethod] public MFTestResults Delegate_delegate_modifier09_Test() { Log.Comment("only new, public, private, protected and internal are allowed as modifiers"); if (Delegate_TestClass_delegate_modifier09.testMethod()) { return MFTestResults.Pass; } return MFTestResults.Fail; } [TestMethod] public MFTestResults Delegate_delegate_modifier10_Test() { Log.Comment("only new, public, private, protected and internal are allowed as modifiers"); if (Delegate_TestClass_delegate_modifier10.testMethod()) { return MFTestResults.Pass; } return MFTestResults.Fail; } [TestMethod] public MFTestResults Delegate_delegate_modifier11_Test() { Log.Comment("only new, public, private, protected and internal are allowed as modifiers"); if (Delegate_TestClass_delegate_modifier11.testMethod()) { return MFTestResults.Pass; } return MFTestResults.Fail; } [TestMethod] public MFTestResults Delegate_delegate_modifier12_Test() { Log.Comment("only new, public, private, protected and internal are allowed as modifiers"); if (Delegate_TestClass_delegate_modifier12.testMethod()) { return MFTestResults.Pass; } return MFTestResults.Fail; } //Compiled Test Cases delegate int Delegate_TestClass_delegate01_1(); public class Delegate_TestClass_delegate01_2 { public int bar() { Log.Comment("bar"); return 0x01; } static public int far() { Log.Comment("far"); return 0x02; } } public class Delegate_TestClass_delegate01 { static int retval = 0x03; static public int Main_old() { Delegate_TestClass_delegate01_2 p = new Delegate_TestClass_delegate01_2(); Delegate_TestClass_delegate01_1 foo = new Delegate_TestClass_delegate01_1(p.bar); retval -= foo(); foo = new Delegate_TestClass_delegate01_1(Delegate_TestClass_delegate01_2.far); retval -= foo(); if (retval == 0) Log.Comment("PASS"); else Log.Comment("FAIL"); return retval; } public static bool testMethod() { return (Main_old() == 0); } } delegate int Delegate_TestClass_delegate02_1(); public class Delegate_TestClass_delegate02_2 { public int bar() { Log.Comment("bar"); return 0x01; } static public int far() { Log.Comment("far"); return 0x02; } } public class Delegate_TestClass_delegate02 { static int retval = 0x03; static public int Main_old() { Delegate_TestClass_delegate02_2 p = new Delegate_TestClass_delegate02_2(); Delegate_TestClass_delegate02_1 foo = null; foo = new Delegate_TestClass_delegate02_1(p.bar); retval -= foo(); foo = null; foo = new Delegate_TestClass_delegate02_1(Delegate_TestClass_delegate02_2.far); retval -= foo(); if (retval == 0) Log.Comment("PASS"); else Log.Comment("FAIL"); return retval; } public static bool testMethod() { return (Main_old() == 0); } } delegate int Delegate_TestClass_delegate03_1(); public class Delegate_TestClass_delegate03_2 { public static int retval = 0x03; public int bar() { Log.Comment("bar"); return 0x01; } static public int far() { Log.Comment("far"); return 0x02; } } public class Delegate_TestClass_delegate03 { static public int Main_old() { Delegate_TestClass_delegate03_1 foo = null; try { foo(); } catch (System.Exception) { Delegate_TestClass_delegate03_2.retval -= 0x03; } if (Delegate_TestClass_delegate03_2.retval == 0) Log.Comment("PASS"); else Log.Comment("FAIL"); return Delegate_TestClass_delegate03_2.retval; } public static bool testMethod() { return (Main_old() == 0); } } delegate int Delegate_TestClass_delegate04_1(); public class Delegate_TestClass_delegate04_2 { public int bar() { Log.Comment("bar"); return 0x01; } static public int far() { Log.Comment("far"); return 0x02; } } public class Delegate_TestClass_delegate04 { static int retval = 0x03; static bool loo() { return true; } static public int Main_old() { Delegate_TestClass_delegate04_2 p = new Delegate_TestClass_delegate04_2(); Delegate_TestClass_delegate04_1 foo = null; foo = loo() ? new Delegate_TestClass_delegate04_1(p.bar): new Delegate_TestClass_delegate04_1(Delegate_TestClass_delegate04_2.far); retval -= foo(); foo = !loo() ? new Delegate_TestClass_delegate04_1(p.bar): new Delegate_TestClass_delegate04_1(Delegate_TestClass_delegate04_2.far); retval -= foo(); if (retval == 0) Log.Comment ("PASS"); else Log.Comment ("FAIL"); return retval; } public static bool testMethod() { return (Main_old() == 0); } } delegate int Delegate_TestClass_delegate05_1(); public class Delegate_TestClass_delegate05_2 { public int bar() { Log.Comment("bar"); return 0x01; } static public int far() { Log.Comment("far"); return 0x02; } } public class Delegate_TestClass_delegate05 { static int retval = 0x03; static bool loo() { return true; } static public int Main_old() { Delegate_TestClass_delegate05_2 p = new Delegate_TestClass_delegate05_2(); Delegate_TestClass_delegate05_1 foo = null; foo = loo() ? new Delegate_TestClass_delegate05_1(p.bar): null; retval -= foo(); foo = !loo() ? null: new Delegate_TestClass_delegate05_1(Delegate_TestClass_delegate05_2.far); retval -= foo(); if (retval == 0) Log.Comment ("PASS"); else Log.Comment ("FAIL"); return retval; } public static bool testMethod() { return (Main_old() == 0); } } delegate int Delegate_TestClass_delegate06_1(); public class Delegate_TestClass_delegate06_2 { public int bar() { Log.Comment("bar"); return 0x01; } static public int far() { Log.Comment("far"); return 0x02; } } public class Delegate_TestClass_delegate06 { static int retval = 0x03; static bool loo() { return true; } static public int Main_old() { Delegate_TestClass_delegate06_2 p = new Delegate_TestClass_delegate06_2(); Delegate_TestClass_delegate06_1 foo = null; try { foo = loo() ? null: new Delegate_TestClass_delegate06_1(Delegate_TestClass_delegate06_2.far); retval -= foo(); } catch (System.Exception n) { retval -= 0x01; } try { foo = !loo() ? new Delegate_TestClass_delegate06_1(p.bar): null; retval -= foo(); } catch (System.Exception n) { retval -= 0x02; } if (retval == 0) Log.Comment ("PASS"); else Log.Comment ("FAIL"); return retval; } public static bool testMethod() { return (Main_old() == 0); } } delegate int Delegate_TestClass_delegate07_1(); public class Delegate_TestClass_delegate07_2 { public int bar() { Log.Comment("bar"); return 0x01; } static public int far() { Log.Comment("far"); return 0x02; } } public class Delegate_TestClass_delegate07 { static int retval = 0x03; static bool loo() { return true; } static public int Main_old() { Delegate_TestClass_delegate07_2 p = new Delegate_TestClass_delegate07_2(); Delegate_TestClass_delegate07_1 foo = null; foo = loo() ? new Delegate_TestClass_delegate07_1(p.bar): new Delegate_TestClass_delegate07_1(Delegate_TestClass_delegate07_2.far); retval -= foo(); try { foo = !loo() ? new Delegate_TestClass_delegate07_1(p.bar): null; retval -= foo(); } catch (System.Exception n) { retval -= 0x02; } if (retval == 0) Log.Comment ("PASS"); else Log.Comment ("FAIL"); return retval; } public static bool testMethod() { return (Main_old() == 0); } } delegate int Delegate_TestClass_delegate08_1(); public class Delegate_TestClass_delegate08_2 { public int bar() { Log.Comment("bar"); return 0x01; } static public int far() { Log.Comment("far"); return 0x02; } } public class Delegate_TestClass_delegate08 { static int retval = 0x03; static bool loo() { return true; } static public int Main_old() { Delegate_TestClass_delegate08_2 p = new Delegate_TestClass_delegate08_2(); Delegate_TestClass_delegate08_1 foo = null; foo = loo() ? null: new Delegate_TestClass_delegate08_1(Delegate_TestClass_delegate08_2.far); if (foo == null) foo = new Delegate_TestClass_delegate08_1(p.bar); retval -= foo(); foo = !loo() ? new Delegate_TestClass_delegate08_1(p.bar): null; if (foo == null) foo = new Delegate_TestClass_delegate08_1(Delegate_TestClass_delegate08_2.far); retval -= foo(); if (retval == 0) Log.Comment ("PASS"); else Log.Comment ("FAIL"); return retval; } public static bool testMethod() { return (Main_old() == 0); } } delegate int Delegate_TestClass_delegate09_1(); public class Delegate_TestClass_delegate09_2 { public int bar() { Log.Comment("bar"); return 0x01; } static public int far() { Log.Comment("far"); return 0x02; } } public class Delegate_TestClass_delegate09 { static int retval = 0x0F; static bool loo() { return true; } static public int Main_old() { Delegate_TestClass_delegate09_2 p = new Delegate_TestClass_delegate09_2(); Delegate_TestClass_delegate09_1 foo1 = null; Delegate_TestClass_delegate09_1 foo2 = null; foo1 = new Delegate_TestClass_delegate09_1(Delegate_TestClass_delegate09_2.far); foo2 = new Delegate_TestClass_delegate09_1(Delegate_TestClass_delegate09_2.far); if (foo1 == foo2) retval -= 0x04; retval -= foo1(); foo1 = new Delegate_TestClass_delegate09_1(p.bar); foo2 = new Delegate_TestClass_delegate09_1(p.bar); if (foo1 == foo2) retval -= 0x08; retval -= foo2(); Log.Comment(retval.ToString()); if (retval == 0) Log.Comment("PASS"); else Log.Comment("FAIL"); return retval; } public static bool testMethod() { return (Main_old() == 0); } } delegate int Delegate_TestClass_delegate10_1(); public class Delegate_TestClass_delegate10_2 { public int bar() { Log.Comment("bar"); return 0x01; } static public int far() { Log.Comment("far"); return 0x02; } } public class Delegate_TestClass_delegate10 { static int retval = 0x0F; static bool loo() { return true; } static public int Main_old() { Delegate_TestClass_delegate10_2 p = new Delegate_TestClass_delegate10_2(); Delegate_TestClass_delegate10_1[] foo = { new Delegate_TestClass_delegate10_1(Delegate_TestClass_delegate10_2.far), new Delegate_TestClass_delegate10_1(Delegate_TestClass_delegate10_2.far) }; if (foo[0] == foo[1]) retval -= 0x04; retval -= foo[1](); foo[0] = new Delegate_TestClass_delegate10_1(p.bar); foo[1] = new Delegate_TestClass_delegate10_1(p.bar); if (foo[0] == foo[1]) retval -= 0x08; retval -= foo[0](); Log.Comment(retval.ToString()); if (retval == 0) Log.Comment("PASS"); else Log.Comment("FAIL"); return retval; } public static bool testMethod() { return (Main_old() == 0); } } public delegate int Delegate_TestClass_delegate11_1(); public class Delegate_TestClass_delegate11_2 { public int bar() { Log.Comment("bar"); return 0x01; } static public int far() { Log.Comment("far"); return 0x02; } public Delegate_TestClass_delegate11_1 foo = null; } public class Delegate_TestClass_delegate11 { static int retval = 0x03; static bool loo() { return true; } static public int Main_old() { Delegate_TestClass_delegate11_2 p = new Delegate_TestClass_delegate11_2(); p.foo = new Delegate_TestClass_delegate11_1(Delegate_TestClass_delegate11_2.far); retval -= p.foo(); p.foo = new Delegate_TestClass_delegate11_1(p.bar); retval -= p.foo(); Log.Comment(retval.ToString()); if (retval == 0) Log.Comment("PASS"); else Log.Comment("FAIL"); return retval; } public static bool testMethod() { return (Main_old() == 0); } } delegate void Delegate_TestClass_delegate12_1(); public class Delegate_TestClass_delegate12_2 { public static int retval = 0x06; public void bar() { Log.Comment("bar"); retval -= 0x01; } static public void far() { Log.Comment("far"); retval -= 0x02; } } public class Delegate_TestClass_delegate12 { static public int Main_old() { Delegate_TestClass_delegate12_2 p = new Delegate_TestClass_delegate12_2(); Delegate_TestClass_delegate12_1 foo = new Delegate_TestClass_delegate12_1(p.bar); Delegate_TestClass_delegate12_1 multifoo = foo; multifoo += new Delegate_TestClass_delegate12_1(Delegate_TestClass_delegate12_2.far); multifoo(); multifoo = new Delegate_TestClass_delegate12_1(Delegate_TestClass_delegate12_2.far); multifoo += foo; multifoo(); if (Delegate_TestClass_delegate12_2.retval == 0) Log.Comment("PASS"); else Log.Comment("FAIL"); return Delegate_TestClass_delegate12_2.retval; } public static bool testMethod() { return (Main_old() == 0); } } delegate void Delegate_TestClass_delegate13_1(); public class Delegate_TestClass_delegate13_2 { public static int retval = 0x04; public void bar() { Log.Comment("bar"); retval -= 0x01; } static public void far() { Log.Comment("far"); retval -= 0x02; } } public class Delegate_TestClass_delegate13 { static public int Main_old() { Delegate_TestClass_delegate13_2 p = new Delegate_TestClass_delegate13_2(); Delegate_TestClass_delegate13_1 foo = null; foo = new Delegate_TestClass_delegate13_1(p.bar); foo(); foo = new Delegate_TestClass_delegate13_1(Delegate_TestClass_delegate13_2.far); foo += new Delegate_TestClass_delegate13_1(p.bar); foo(); if (Delegate_TestClass_delegate13_2.retval == 0) Log.Comment("PASS"); else Log.Comment("FAIL"); return Delegate_TestClass_delegate13_2.retval; } public static bool testMethod() { return (Main_old() == 0); } } delegate void Delegate_TestClass_delegate14_1(); public class Delegate_TestClass_delegate14_2 { public static int retval = 0x03; public void bar() { Log.Comment("bar"); retval += 0x10; } static public void far() { Log.Comment("far"); retval += 0x20; } } public class Delegate_TestClass_delegate14 { static public int Main_old() { Delegate_TestClass_delegate14_1 foo = null; try { foo(); } catch (System.Exception) { Delegate_TestClass_delegate14_2.retval -= 0x03; } if (Delegate_TestClass_delegate14_2.retval == 0) Log.Comment("PASS"); else Log.Comment("FAIL"); return Delegate_TestClass_delegate14_2.retval; } public static bool testMethod() { return (Main_old() == 0); } } delegate void Delegate_TestClass_delegate14a_1(); public class Delegate_TestClass_delegate14a_2 { public static int retval = 0x02; public void bar() { Log.Comment("bar"); retval -= 0x01; } static public void far() { Log.Comment("far"); retval -= 0x02; } } public class Delegate_TestClass_delegate14a { static public int Main_old() { Delegate_TestClass_delegate14a_1 foo = new Delegate_TestClass_delegate14a_1(Delegate_TestClass_delegate14a_2.far); foo += (Delegate_TestClass_delegate14a_1)null; foo(); if (Delegate_TestClass_delegate14a_2.retval == 0) Log.Comment("PASS"); else Log.Comment("FAIL"); return Delegate_TestClass_delegate14a_2.retval; } public static bool testMethod() { return (Main_old() == 0); } } delegate void Delegate_TestClass_delegate14b_1(); public class Delegate_TestClass_delegate14b_2 { public static int retval = 0x02; public void bar() { Log.Comment("bar"); retval -= 0x01; } static public void far() { Log.Comment("far"); retval -= 0x02; } } public class Delegate_TestClass_delegate14b { static public int Main_old() { Delegate_TestClass_delegate14b_1 foo = null; foo += new Delegate_TestClass_delegate14b_1(Delegate_TestClass_delegate14b_2.far); foo(); if (Delegate_TestClass_delegate14b_2.retval == 0) Log.Comment("PASS"); else Log.Comment("FAIL"); return Delegate_TestClass_delegate14b_2.retval; } public static bool testMethod() { return (Main_old() == 0); } } delegate void Delegate_TestClass_delegate14c_1(); public class Delegate_TestClass_delegate14c_2 { public static int retval = 0x03; public void bar() { Log.Comment("bar"); retval -= 0x01; } static public void far() { Log.Comment("far"); retval -= 0x02; } } public class Delegate_TestClass_delegate14c { static public int Main_old() { Delegate_TestClass_delegate14c_2 p = new Delegate_TestClass_delegate14c_2(); Delegate_TestClass_delegate14c_1 foo = new Delegate_TestClass_delegate14c_1(p.bar); foo += (Delegate_TestClass_delegate14c_1)null; foo += new Delegate_TestClass_delegate14c_1(Delegate_TestClass_delegate14c_2.far); foo(); if (Delegate_TestClass_delegate14c_2.retval == 0) Log.Comment("PASS"); else Log.Comment("FAIL"); return Delegate_TestClass_delegate14c_2.retval; } public static bool testMethod() { return (Main_old() == 0); } } delegate void Delegate_TestClass_delegate15_1(); public class Delegate_TestClass_delegate15_2 { public static int retval = 63; public void bar1() { Log.Comment("bar1"); retval -= 0x01; } static public void far1() { Log.Comment("far1"); retval -= 0x02; } public void bar2() { Log.Comment("bar2"); retval -= 10; } static public void far2() { Log.Comment("far2"); retval -= 20; } } public class Delegate_TestClass_delegate15 { static bool loo() { return true; } static public int Main_old() { Delegate_TestClass_delegate15_2 p = new Delegate_TestClass_delegate15_2(); Delegate_TestClass_delegate15_1 foo = null; Delegate_TestClass_delegate15_1 left = null; Delegate_TestClass_delegate15_1 right = null; foo = loo() ? new Delegate_TestClass_delegate15_1(p.bar1): new Delegate_TestClass_delegate15_1(Delegate_TestClass_delegate15_2.far1); foo(); foo = !loo() ? new Delegate_TestClass_delegate15_1(p.bar1): new Delegate_TestClass_delegate15_1(Delegate_TestClass_delegate15_2.far1); foo(); left = new Delegate_TestClass_delegate15_1(p.bar1); right = new Delegate_TestClass_delegate15_1(Delegate_TestClass_delegate15_2.far2); foo = !loo() ? left += new Delegate_TestClass_delegate15_1(Delegate_TestClass_delegate15_2.far1): right += new Delegate_TestClass_delegate15_1(p.bar2); foo(); right = new Delegate_TestClass_delegate15_1(p.bar1); left = new Delegate_TestClass_delegate15_1(Delegate_TestClass_delegate15_2.far2); foo = loo() ? left += new Delegate_TestClass_delegate15_1(p.bar2): right += new Delegate_TestClass_delegate15_1(Delegate_TestClass_delegate15_2.far1); foo(); if (Delegate_TestClass_delegate15_2.retval == 0) Log.Comment ("PASS"); else Log.Comment ("FAIL"); return Delegate_TestClass_delegate15_2.retval; } public static bool testMethod() { return (Main_old() == 0); } } delegate void Delegate_TestClass_delegate16_1(); public class Delegate_TestClass_delegate16_2 { public static int retval = 0x09; public void bar() { Log.Comment("bar"); retval -= 0x01; } static public void far() { Log.Comment("far"); retval -= 0x02; } } public class Delegate_TestClass_delegate16 { static bool loo() { return true; } static public int Main_old() { Delegate_TestClass_delegate16_2 p = new Delegate_TestClass_delegate16_2(); Delegate_TestClass_delegate16_1 foo = null; Delegate_TestClass_delegate16_1 left = null; Delegate_TestClass_delegate16_1 right = null; foo = loo() ? new Delegate_TestClass_delegate16_1(p.bar): null; foo(); foo = !loo() ? null: new Delegate_TestClass_delegate16_1(Delegate_TestClass_delegate16_2.far); foo(); left = new Delegate_TestClass_delegate16_1(p.bar); foo = loo() ? left += new Delegate_TestClass_delegate16_1(Delegate_TestClass_delegate16_2.far): null; foo(); right = new Delegate_TestClass_delegate16_1(Delegate_TestClass_delegate16_2.far); foo = !loo() ? null: right += new Delegate_TestClass_delegate16_1(p.bar); foo(); if (Delegate_TestClass_delegate16_2.retval == 0) Log.Comment ("PASS"); else Log.Comment ("FAIL"); return Delegate_TestClass_delegate16_2.retval; } public static bool testMethod() { return (Main_old() == 0); } } delegate void Delegate_TestClass_delegate17_1(); public class Delegate_TestClass_delegate17_2 { public static int retval = 13; public void bar() { Log.Comment("bar"); retval -= 0x01; } static public void far() { Log.Comment("far"); retval -= 0x02; } public void bar2() { Log.Comment("bar2"); retval -= 10; } static public void far2() { Log.Comment("far2"); retval -= 20; } } public class Delegate_TestClass_delegate17 { static bool loo() { return true; } static public int Main_old() { Delegate_TestClass_delegate17_2 p = new Delegate_TestClass_delegate17_2(); Delegate_TestClass_delegate17_1 foo = null; try { foo = loo() ? null: new Delegate_TestClass_delegate17_1(Delegate_TestClass_delegate17_2.far); foo(); } catch (System.Exception n) { Delegate_TestClass_delegate17_2.retval -= 0x01; } try { foo = !loo() ? new Delegate_TestClass_delegate17_1(p.bar): null; foo(); } catch (System.Exception n) { Delegate_TestClass_delegate17_2.retval -= 0x02; } try { foo = null; foo += (Delegate_TestClass_delegate17_1)null; foo(); } catch (System.Exception n) { Delegate_TestClass_delegate17_2.retval -= 10; } if (Delegate_TestClass_delegate17_2.retval == 0) Log.Comment ("PASS"); else Log.Comment ("FAIL"); return Delegate_TestClass_delegate17_2.retval; } public static bool testMethod() { return (Main_old() == 0); } } delegate void Delegate_TestClass_delegate18_1(); public class Delegate_TestClass_delegate18_2 { public static int retval = 23; public void bar() { Log.Comment("bar"); retval -= 0x01; } static public void far() { Log.Comment("far"); retval -= 0x02; } public void bar1() { Log.Comment("bar1"); retval -= 10; } static public void far1() { Log.Comment("far1"); retval -= 20; } } public class Delegate_TestClass_delegate18 { static bool loo() { return true; } static public int Main_old() { Delegate_TestClass_delegate18_2 p = new Delegate_TestClass_delegate18_2(); Delegate_TestClass_delegate18_1 foo = null; foo = loo() ? null: new Delegate_TestClass_delegate18_1(Delegate_TestClass_delegate18_2.far); if (foo == null) { foo += new Delegate_TestClass_delegate18_1(p.bar); foo += new Delegate_TestClass_delegate18_1(Delegate_TestClass_delegate18_2.far); } foo(); foo = null; foo += (Delegate_TestClass_delegate18_1)null; if (foo == null) { foo += new Delegate_TestClass_delegate18_1(Delegate_TestClass_delegate18_2.far1); } foo(); if (Delegate_TestClass_delegate18_2.retval == 0) Log.Comment ("PASS"); else Log.Comment ("FAIL"); return Delegate_TestClass_delegate18_2.retval; } public static bool testMethod() { return (Main_old() == 0); } } delegate void Delegate_TestClass_delegate19_1(); public class Delegate_TestClass_delegate19_2 { public static int retval = 33; public void bar() { Log.Comment("bar"); retval -= 1; } static public void far() { Log.Comment("far"); retval -= 2; } } public class Delegate_TestClass_delegate19 { static bool loo() { return true; } static public int Main_old() { Delegate_TestClass_delegate19_2 p = new Delegate_TestClass_delegate19_2(); Delegate_TestClass_delegate19_1[] foo = new Delegate_TestClass_delegate19_1[3]; foo[1] = new Delegate_TestClass_delegate19_1(Delegate_TestClass_delegate19_2.far); foo[2] = new Delegate_TestClass_delegate19_1(p.bar); Delegate_TestClass_delegate19_1 foo1 = null; foreach (Delegate_TestClass_delegate19_1 b in foo) { foo1 += b; } Delegate_TestClass_delegate19_1 foo2 = new Delegate_TestClass_delegate19_1(Delegate_TestClass_delegate19_2.far); foo2 += new Delegate_TestClass_delegate19_1(p.bar); if (foo1 == foo2) Delegate_TestClass_delegate19_2.retval -= 10; foo[1] = foo1; foo[2] = foo2; if (foo[1] == foo[2]) Delegate_TestClass_delegate19_2.retval -= 20; foo[1](); if (Delegate_TestClass_delegate19_2.retval == 0) Log.Comment("PASS"); else Log.Comment("FAIL"); return Delegate_TestClass_delegate19_2.retval; } public static bool testMethod() { return (Main_old() == 0); } } delegate void Delegate_TestClass_delegate20_1(); public class Delegate_TestClass_delegate20_2 { public static int retval = 1333; public void bar() { Log.Comment("bar"); retval -= 1; } static public void far() { Log.Comment("far"); retval -= 2; } public void bar1() { Log.Comment("bar1"); retval -= 10; } static public void far1() { Log.Comment("far1"); retval -= 20; } } public class Delegate_TestClass_delegate20 { static bool loo() { return true; } static public int Main_old() { Delegate_TestClass_delegate20_2 p = new Delegate_TestClass_delegate20_2(); Delegate_TestClass_delegate20_1 foo1 = null; Delegate_TestClass_delegate20_1 foo2 = null; foo1 = new Delegate_TestClass_delegate20_1(Delegate_TestClass_delegate20_2.far); foo2 = new Delegate_TestClass_delegate20_1(Delegate_TestClass_delegate20_2.far); if (foo1 == foo2) Delegate_TestClass_delegate20_2.retval -= 100; foo1(); foo1 = new Delegate_TestClass_delegate20_1(p.bar); foo2 = new Delegate_TestClass_delegate20_1(p.bar); if (foo1 == foo2) Delegate_TestClass_delegate20_2.retval -= 200; foo2(); foo1 = new Delegate_TestClass_delegate20_1(Delegate_TestClass_delegate20_2.far1); foo2 = new Delegate_TestClass_delegate20_1(p.bar1); Delegate_TestClass_delegate20_1 foo3 = foo1; foo3 += foo2; Delegate_TestClass_delegate20_1 foo4 = new Delegate_TestClass_delegate20_1(Delegate_TestClass_delegate20_2.far1); foo4 += new Delegate_TestClass_delegate20_1(p.bar1); if (foo3 == foo4) Delegate_TestClass_delegate20_2.retval -= 1000; foo3(); if (Delegate_TestClass_delegate20_2.retval == 0) Log.Comment("PASS"); else Log.Comment("FAIL"); return Delegate_TestClass_delegate20_2.retval; } public static bool testMethod() { return (Main_old() == 0); } } delegate void Delegate_TestClass_delegate21_1(); public class Delegate_TestClass_delegate21_2 { public static int retval = 33; public void bar() { Log.Comment("bar"); retval -= 1; } static public void far() { Log.Comment("far"); retval -= 2; } } public class Delegate_TestClass_delegate21 { static bool loo() { return true; } static public int Main_old() { Delegate_TestClass_delegate21_2 p = new Delegate_TestClass_delegate21_2(); Delegate_TestClass_delegate21_1[] foo = { new Delegate_TestClass_delegate21_1(Delegate_TestClass_delegate21_2.far), new Delegate_TestClass_delegate21_1(p.bar) }; Delegate_TestClass_delegate21_1 foo1 = null; foreach (Delegate_TestClass_delegate21_1 b in foo) { foo1 += b; } Delegate_TestClass_delegate21_1 foo2 = new Delegate_TestClass_delegate21_1(Delegate_TestClass_delegate21_2.far); foo2 += new Delegate_TestClass_delegate21_1(p.bar); if (foo1 == foo2) Delegate_TestClass_delegate21_2.retval -= 10; foo[0] = foo1; foo[1] = foo2; if (foo[0] == foo[1]) Delegate_TestClass_delegate21_2.retval -= 20; foo[0](); if (Delegate_TestClass_delegate21_2.retval == 0) Log.Comment("PASS"); else Log.Comment("FAIL"); return Delegate_TestClass_delegate21_2.retval; } public static bool testMethod() { return (Main_old() == 0); } } delegate void Delegate_TestClass_delegate23_Del(); public class Delegate_TestClass_delegate23_A { public static int retval = 3; public void bar() { Log.Comment("bar"); retval -= 1; } static public void far() { Log.Comment("far"); retval -= 2; } } public class Delegate_TestClass_delegate23 { static bool loo() { return true; } static public int Main_old() { Delegate_TestClass_delegate23_A p = new Delegate_TestClass_delegate23_A(); Delegate_TestClass_delegate23_Del foo1 = new Delegate_TestClass_delegate23_Del(Delegate_TestClass_delegate23_A.far); Delegate_TestClass_delegate23_Del foo2 = new Delegate_TestClass_delegate23_Del(p.bar); Delegate_TestClass_delegate23_Del foo3 = foo1 + foo2; foo3(); if (Delegate_TestClass_delegate23_A.retval == 0) Log.Comment("PASS"); else Log.Comment("FAIL, retval==" + Delegate_TestClass_delegate23_A.retval.ToString()); return Delegate_TestClass_delegate23_A.retval; } public static bool testMethod() { return (Main_old() == 0); } } delegate void Delegate_TestClass_delegate24_Del(); public class Delegate_TestClass_delegate24_A { public static int retval = 0x0F; public void bar() { Log.Comment("bar"); retval -= 1; } static public void far() { Log.Comment("far"); retval -= 2; } public void bar2() { Log.Comment("bar2"); retval -= 4; } static public void far2() { Log.Comment("far2"); retval -= 8; } } public class Delegate_TestClass_delegate24 { static bool loo() { return true; } static public int Main_old() { Delegate_TestClass_delegate24_A p = new Delegate_TestClass_delegate24_A(); Delegate_TestClass_delegate24_Del foo1 = new Delegate_TestClass_delegate24_Del(Delegate_TestClass_delegate24_A.far) + new Delegate_TestClass_delegate24_Del(p.bar); Delegate_TestClass_delegate24_Del foo2 = new Delegate_TestClass_delegate24_Del(p.bar2) + new Delegate_TestClass_delegate24_Del(Delegate_TestClass_delegate24_A.far2); Delegate_TestClass_delegate24_Del foo3 = foo1 + foo2; foo3(); if (Delegate_TestClass_delegate24_A.retval == 0) Log.Comment("PASS"); else Log.Comment("FAIL, retval==" + Delegate_TestClass_delegate24_A.retval.ToString()); return Delegate_TestClass_delegate24_A.retval; } public static bool testMethod() { return (Main_old() == 0); } } delegate void Delegate_TestClass_delegate25_Del(); public class Delegate_TestClass_delegate25_A { public static int retval = 0x3F; public void bar() { Log.Comment("bar"); retval -= 1; } static public void far() { Log.Comment("far"); retval -= 2; } public void bar2() { Log.Comment("bar2"); retval -= 4; } static public void far2() { Log.Comment("far2"); retval -= 8; } } public class Delegate_TestClass_delegate25 { static bool loo() { return true; } static public int Main_old() { Delegate_TestClass_delegate25_A p = new Delegate_TestClass_delegate25_A(); Delegate_TestClass_delegate25_Del foo1 = new Delegate_TestClass_delegate25_Del(Delegate_TestClass_delegate25_A.far) + new Delegate_TestClass_delegate25_Del(p.bar); Delegate_TestClass_delegate25_Del foo2 = new Delegate_TestClass_delegate25_Del(p.bar2) + new Delegate_TestClass_delegate25_Del(Delegate_TestClass_delegate25_A.far2); Delegate_TestClass_delegate25_Del foo3 = foo1 + foo2; foo3(); Delegate_TestClass_delegate25_Del foo4 = foo3 - foo2; //Should be the same as foo1 if (foo4 == foo1) Delegate_TestClass_delegate25_A.retval -= 0x10; Delegate_TestClass_delegate25_A.retval += 3; foo4(); foo4 = foo3 - foo1; //Should be the same as foo2 if (foo4 == foo2) Delegate_TestClass_delegate25_A.retval -= 0x20; Delegate_TestClass_delegate25_A.retval += 0x0C; foo4(); if (Delegate_TestClass_delegate25_A.retval == 0) Log.Comment("PASS"); else Log.Comment("FAIL, retval==" + Delegate_TestClass_delegate25_A.retval.ToString()); return Delegate_TestClass_delegate25_A.retval; } public static bool testMethod() { return (Main_old() == 0); } } public class Delegate_TestClass_delegate26 { public static int Main_old(String[] args) { try { HD hd = new HD(Delegate_TestClass_delegate26.Hello); int i = 1; IAsyncResult ar = hd.BeginInvoke(out i, null, null); i = 1; hd.EndInvoke(out i, ar); if (0 == i) Log.Comment("PASS"); else Log.Comment("FAIL, i==" + i.ToString()); return i; } catch (System.Exception) { return 1; } return 0; } public delegate void HD(out int i); public static void Hello(out int i) { i = 0; } public static bool testMethod() { if (Main_old(null) != 0) return false; else return true; } } /* public class Delegate_TestClass_delegate28 { public static int Main_old(String[] args) { HD hd = new HD(Delegate_TestClass_delegate28.Hello); int i = 1; i = hd(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, 64, 65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79, 80, 81, 82, 83, 84, 85, 86, 87, 88, 89, 90, 91, 92, 93, 94, 95, 96, 97, 98, 99, 100, 101, 102, 103, 104, 105, 106, 107, 108, 109, 110, 111, 112, 113, 114, 115, 116, 117, 118, 119, 120, 121, 122, 123, 124, 125, 126, 127, 128, 129, 130, 131, 132, 133, 134, 135, 136, 137, 138, 139, 140, 141, 142, 143, 144, 145, 146, 147, 148, 149, 150, 151, 152, 153, 154, 155, 156, 157, 158, 159, 160, 161, 162, 163, 164, 165, 166, 167, 168, 169, 170, 171, 172, 173, 174, 175, 176, 177, 178, 179, 180, 181, 182, 183, 184, 185, 186, 187, 188, 189, 190, 191, 192, 193, 194, 195, 196, 197, 198, 199, 200, 201, 202, 203, 204, 205, 206, 207, 208, 209, 210, 211, 212, 213, 214, 215, 216, 217, 218, 219, 220, 221, 222, 223, 224, 225, 226, 227, 228, 229, 230, 231, 232, 233, 234, 235, 236, 237, 238, 239, 240, 241, 242, 243, 244, 245, 246, 247, 248, 249, 250, 251, 252, 253, 254, 255, 256, 257); if (0 == i) Log.Comment("PASS"); else Log.Comment("FAIL, i==" + i.ToString()); return i; } public delegate int HD(int i1, int i2, int i3, int i4, int i5, int i6, int i7, int i8, int i9, int i10, int i11, int i12, int i13, int i14, int i15, int i16, int i17, int i18, int i19, int i20, int i21, int i22, int i23, int i24, int i25, int i26, int i27, int i28, int i29, int i30, int i31, int i32, int i33, int i34, int i35, int i36, int i37, int i38, int i39, int i40, int i41, int i42, int i43, int i44, int i45, int i46, int i47, int i48, int i49, int i50, int i51, int i52, int i53, int i54, int i55, int i56, int i57, int i58, int i59, int i60, int i61, int i62, int i63, int i64, int i65, int i66, int i67, int i68, int i69, int i70, int i71, int i72, int i73, int i74, int i75, int i76, int i77, int i78, int i79, int i80, int i81, int i82, int i83, int i84, int i85, int i86, int i87, int i88, int i89, int i90, int i91, int i92, int i93, int i94, int i95, int i96, int i97, int i98, int i99, int i100, int i101, int i102, int i103, int i104, int i105, int i106, int i107, int i108, int i109, int i110, int i111, int i112, int i113, int i114, int i115, int i116, int i117, int i118, int i119, int i120, int i121, int i122, int i123, int i124, int i125, int i126, int i127, int i128, int i129, int i130, int i131, int i132, int i133, int i134, int i135, int i136, int i137, int i138, int i139, int i140, int i141, int i142, int i143, int i144, int i145, int i146, int i147, int i148, int i149, int i150, int i151, int i152, int i153, int i154, int i155, int i156, int i157, int i158, int i159, int i160, int i161, int i162, int i163, int i164, int i165, int i166, int i167, int i168, int i169, int i170, int i171, int i172, int i173, int i174, int i175, int i176, int i177, int i178, int i179, int i180, int i181, int i182, int i183, int i184, int i185, int i186, int i187, int i188, int i189, int i190, int i191, int i192, int i193, int i194, int i195, int i196, int i197, int i198, int i199, int i200, int i201, int i202, int i203, int i204, int i205, int i206, int i207, int i208, int i209, int i210, int i211, int i212, int i213, int i214, int i215, int i216, int i217, int i218, int i219, int i220, int i221, int i222, int i223, int i224, int i225, int i226, int i227, int i228, int i229, int i230, int i231, int i232, int i233, int i234, int i235, int i236, int i237, int i238, int i239, int i240, int i241, int i242, int i243, int i244, int i245, int i246, int i247, int i248, int i249, int i250, int i251, int i252, int i253, int i254, int i255, int i256, int i257); public static int Hello(int i1, int i2, int i3, int i4, int i5, int i6, int i7, int i8, int i9, int i10, int i11, int i12, int i13, int i14, int i15, int i16, int i17, int i18, int i19, int i20, int i21, int i22, int i23, int i24, int i25, int i26, int i27, int i28, int i29, int i30, int i31, int i32, int i33, int i34, int i35, int i36, int i37, int i38, int i39, int i40, int i41, int i42, int i43, int i44, int i45, int i46, int i47, int i48, int i49, int i50, int i51, int i52, int i53, int i54, int i55, int i56, int i57, int i58, int i59, int i60, int i61, int i62, int i63, int i64, int i65, int i66, int i67, int i68, int i69, int i70, int i71, int i72, int i73, int i74, int i75, int i76, int i77, int i78, int i79, int i80, int i81, int i82, int i83, int i84, int i85, int i86, int i87, int i88, int i89, int i90, int i91, int i92, int i93, int i94, int i95, int i96, int i97, int i98, int i99, int i100, int i101, int i102, int i103, int i104, int i105, int i106, int i107, int i108, int i109, int i110, int i111, int i112, int i113, int i114, int i115, int i116, int i117, int i118, int i119, int i120, int i121, int i122, int i123, int i124, int i125, int i126, int i127, int i128, int i129, int i130, int i131, int i132, int i133, int i134, int i135, int i136, int i137, int i138, int i139, int i140, int i141, int i142, int i143, int i144, int i145, int i146, int i147, int i148, int i149, int i150, int i151, int i152, int i153, int i154, int i155, int i156, int i157, int i158, int i159, int i160, int i161, int i162, int i163, int i164, int i165, int i166, int i167, int i168, int i169, int i170, int i171, int i172, int i173, int i174, int i175, int i176, int i177, int i178, int i179, int i180, int i181, int i182, int i183, int i184, int i185, int i186, int i187, int i188, int i189, int i190, int i191, int i192, int i193, int i194, int i195, int i196, int i197, int i198, int i199, int i200, int i201, int i202, int i203, int i204, int i205, int i206, int i207, int i208, int i209, int i210, int i211, int i212, int i213, int i214, int i215, int i216, int i217, int i218, int i219, int i220, int i221, int i222, int i223, int i224, int i225, int i226, int i227, int i228, int i229, int i230, int i231, int i232, int i233, int i234, int i235, int i236, int i237, int i238, int i239, int i240, int i241, int i242, int i243, int i244, int i245, int i246, int i247, int i248, int i249, int i250, int i251, int i252, int i253, int i254, int i255, int i256, int i257) { return i257 - 257; } public static bool testMethod() { if (Main_old(null) != 0) return false; else return true; } } */ delegate int Delegate_TestClass_delegate30_1(); public struct Delegate_TestClass_delegate30_2 { public int bar() { Log.Comment("bar"); return 0x01; } static public int far() { Log.Comment("far"); return 0x02; } } public class Delegate_TestClass_delegate30 { static int retval = 0x03; static public int Main_old() { Delegate_TestClass_delegate30_2 p = new Delegate_TestClass_delegate30_2(); Delegate_TestClass_delegate30_1 foo = new Delegate_TestClass_delegate30_1(p.bar); retval -= foo(); foo = new Delegate_TestClass_delegate30_1(Delegate_TestClass_delegate30_2.far); retval -= foo(); if (retval == 0) { return 0; } else { return 1; } } public static bool testMethod() { return (Main_old() == 0); } } delegate int Delegate_TestClass_delegate31_1(); interface I { int bar(); } public struct Delegate_TestClass_delegate31_2 : I { public int bar() { Log.Comment("bar"); return 0x01; } } public class Delegate_TestClass_delegate31 { static int retval = 0x01; static public int Main_old() { Delegate_TestClass_delegate31_2 p = new Delegate_TestClass_delegate31_2(); Delegate_TestClass_delegate31_1 foo = new Delegate_TestClass_delegate31_1(p.bar); retval -= foo(); if (retval == 0) { Log.Comment("PASS"); } else { Log.Comment("FAIL"); } return retval; } public static bool testMethod() { return (Main_old() == 0); } } /* delegate void Delegate_TestClass_delegate32_Del(int i, params string[] p); class Delegate_TestClass_delegate32 { static volatile int res; void m1(int i, params string[] p) { res = p.Length; } public static int Main_old() { Delegate_TestClass_delegate32 t = new Delegate_TestClass_delegate32(); Delegate_TestClass_delegate32_Del d = new Delegate_TestClass_delegate32_Del(t.m1); int i = 7; string[] strArr = { "foo", "bar" }; IAsyncResult ar = d.BeginInvoke(i, strArr, null, null); ar.AsyncWaitHandle.WaitOne(); if (res == 2) return 0; else return 1; } public static bool testMethod() { return (Main_old() == 0); } } delegate void Delegate_TestClass_delegate34_Del(int i, params object[] p); class Delegate_TestClass_delegate34 { static volatile int res; void m1(int i, params object[] p) { res = p.Length; } public static int Main_old() { Delegate_TestClass_delegate34 t = new Delegate_TestClass_delegate34(); Delegate_TestClass_delegate34_Del d = new Delegate_TestClass_delegate34_Del(t.m1); int i = 7; object[] objArr = { 1, 2 }; IAsyncResult ar = d.BeginInvoke(i, objArr, null, null); ar.AsyncWaitHandle.WaitOne(); if (res == 2) return 0; else return 1; } public static bool testMethod() { return (Main_old() == 0); } } */ class Delegate_TestClass_delegate36 { public delegate int BarDelegate(int[] Arr); public static int Bar(params int[] Arr) { return Arr[0]; } public static int Main_old() { BarDelegate Delegate_TestClass_delegate36_B = new BarDelegate(Bar); return Delegate_TestClass_delegate36_B(new int[] { 1, 2, 3 }) - Delegate_TestClass_delegate36_B(new int[] { 1, 2 }); } public static bool testMethod() { return (Main_old() == 0); } } public delegate double Delegate_TestClass_delegate60_Del(int integerPortion, float fraction); public class Delegate_TestClass_delegate60 { private delegate double ClassDelegate(int integerPortion, float fraction); double DelegatedMethod(int intPart, float frac) { return intPart + frac; } public static int Main_old(String[] args) { int retval = 0x0F; Delegate_TestClass_delegate60 c = new Delegate_TestClass_delegate60(); Delegate_TestClass_delegate60_Del nsd = new Delegate_TestClass_delegate60_Del(c.DelegatedMethod); if (nsd is System.Delegate) retval -= 0x01; if (nsd is System.MulticastDelegate) retval -= 0x02; ClassDelegate cd = new ClassDelegate(c.DelegatedMethod); if (cd is System.Delegate) retval -= 0x04; if (cd is System.MulticastDelegate) retval -= 0x08; if (0 == retval) Log.Comment("PASS"); else { Log.Comment("FAIL, 0x{0:X}"); Log.Comment(retval.ToString()); } return retval; } public static bool testMethod() { if (Main_old(null) != 0) return false; else return true; } } delegate double Delegate_TestClass_delegate62_Del(int integerPortion, float fraction); public class Delegate_TestClass_delegate62 { new delegate double Delegate_TestClass_delegate62_Del(int integerPortion, float fraction); double DelegatedMethod(int intPart, float frac) { return intPart + frac; } public static int Main_old(String[] args) { return 0; } public static bool testMethod() { if (Main_old(null) != 0) return false; else return true; } } delegate double Delegate_TestClass_delegate64_Del(int integerPortion, float fraction); public class Delegate_TestClass_delegate64_1 { public delegate double Delegate_TestClass_delegate64_Del(int integerPortion, float fraction); double DelegatedMethod(int intPart, float frac) { return intPart + frac; } } public class Delegate_TestClass_delegate64 : Delegate_TestClass_delegate64_1 { public delegate double Delegate_TestClass_delegate64_Del(int integerPortion, float fraction); public static int Main_old(String[] args) { return 0; } public static bool testMethod() { if (Main_old(null) != 0) return false; else return true; } } delegate double Delegate_TestClass_delegate65_Del(int integerPortion, float fraction); public class Delegate_TestClass_delegate65_1 { public delegate double Delegate_TestClass_delegate65_Del(int integerPortion, float fraction); public double DelegatedMethod(int intPart, float frac) { return intPart + frac; } } public class Delegate_TestClass_delegate65 : Delegate_TestClass_delegate65_1 { new public delegate double Delegate_TestClass_delegate65_Del(int integerPortion, float fraction); public new double DelegatedMethod(int intPart, float frac) { return intPart + frac + 5; } public static int Main_old(String[] args) { int retval = 0x07; Delegate_TestClass_delegate65 dc = new Delegate_TestClass_delegate65(); Delegate_TestClass_delegate65_Del md = new Delegate_TestClass_delegate65_Del(dc.DelegatedMethod); if (md(2, 0.5f) == 7.5) retval -= 0x01; Delegate_TestClass_delegate65_1.Delegate_TestClass_delegate65_Del bmd = new Delegate_TestClass_delegate65_1.Delegate_TestClass_delegate65_Del(((Delegate_TestClass_delegate65_1)dc).DelegatedMethod); if (md(2, 0.5f) == 7.5) retval -= 0x02; Delegate_TestClass_delegate65_1 bc = new Delegate_TestClass_delegate65_1(); bmd = new Delegate_TestClass_delegate65_1.Delegate_TestClass_delegate65_Del(bc.DelegatedMethod); if (bmd(2, 0.5f) == 2.5) retval -= 0x04; if (0 == retval) Log.Comment("PASS"); else { Log.Comment("FAIL, 0x{0:X}"); Log.Comment(retval.ToString()); } return retval; } public static bool testMethod() { if (Main_old(null) != 0) return false; else return true; } } /* delegate double Delegate_TestClass_delegate66_Del(int integerPortion, float fraction); public class Delegate_TestClass_delegate66 { public delegate double MyDelegate2(int integerPortion, float fraction); public double DelegatedMethod(int intPart, float frac) { return intPart + frac + 5; } public static int Main_old(String[] args) { int retval = 0x03; Delegate_TestClass_delegate66 mc = new Delegate_TestClass_delegate66(); Delegate_TestClass_delegate66_Del md1 = new Delegate_TestClass_delegate66_Del(mc.DelegatedMethod); MyDelegate2 md2 = new MyDelegate2(mc.DelegatedMethod); if (md1 == md2) retval -= 0x01; if (md2 == md1) retval -= 0x02; if (0 == retval) Log.Comment("PASS"); else {Log.Comment("FAIL, 0x{0:X}"); return retval; } public static bool testMethod() { if (Main_old(null) != 0) return false; else return true; } } delegate double Delegate_TestClass_delegate70_Del(int integerPortion, float fraction); public class Delegate_TestClass_delegate70 { public delegate double MyDelegate2(int integerPortion, float fraction); public double DelegatedMethod1(int intPart, float frac) { return intPart + frac + 5; } public double DelegatedMethod2(int intPart, float frac) { return intPart + frac + 10; } public static int Main_old(String[] args) { int retval = 0x03; Delegate_TestClass_delegate70 mc = new Delegate_TestClass_delegate70(); Delegate_TestClass_delegate70_Del md1 = new Delegate_TestClass_delegate70_Del(mc.DelegatedMethod1); MyDelegate2 md2 = new MyDelegate2(mc.DelegatedMethod2); if (md1 != md2) retval -= 0x01; if (md2 != md1) retval -= 0x02; if (0 == retval) Log.Comment("PASS"); else {Log.Comment("FAIL, 0x{0:X}"); return retval; } public static bool testMethod() { if (Main_old(null) != 0) return false; else return true; } } */ delegate double Delegate_TestClass_delegate71_Del(int integerPortion, float fraction); public class Delegate_TestClass_delegate71 { public delegate double MyDelegate2(int integerPortion, float fraction); public double DelegatedMethod1(int intPart, float frac) { if (5 == intPart) throw new System.Exception("My System.Exception"); return intPart + frac + 5; } public double DelegatedMethod2(int intPart, float frac) { return intPart + frac + 10; } public static int Main_old(String[] args) { int retval = 0x01; Delegate_TestClass_delegate71 mc = new Delegate_TestClass_delegate71(); Delegate_TestClass_delegate71_Del md1 = new Delegate_TestClass_delegate71_Del(mc.DelegatedMethod1); md1 += new Delegate_TestClass_delegate71_Del(mc.DelegatedMethod2); try { double d = md1(5, .5f); retval ^= 0x02; } catch (System.Exception) { retval -= 0x01; } if (0 == retval) Log.Comment("PASS"); else { Log.Comment("FAIL, 0x{0:X}"); Log.Comment(retval.ToString()); } return retval; } public static bool testMethod() { if (Main_old(null) != 0) return false; else return true; } } delegate void Delegate_TestClass_delegate72_Del(); public class Delegate_TestClass_delegate72_A { public static int retval = 0x3F; public void bar() { Log.Comment("bar"); retval -= 1; } static public void far() { Log.Comment("far"); retval -= 2; } public void bar2() { Log.Comment("bar2"); retval -= 4; } static public void far2() { Log.Comment("far2"); retval -= 8; } } public class Delegate_TestClass_delegate72 { static bool loo() { return true; } static public int Main_old() { Delegate_TestClass_delegate72_A p = new Delegate_TestClass_delegate72_A(); Delegate_TestClass_delegate72_Del foo1 = new Delegate_TestClass_delegate72_Del(Delegate_TestClass_delegate72_A.far) + new Delegate_TestClass_delegate72_Del(p.bar); Delegate_TestClass_delegate72_Del foo2 = new Delegate_TestClass_delegate72_Del(p.bar2) + new Delegate_TestClass_delegate72_Del(Delegate_TestClass_delegate72_A.far2); Delegate_TestClass_delegate72_Del foo3 = foo1 + foo2; foo3(); Delegate_TestClass_delegate72_Del foo4 = foo3; foo4 -= foo2; //Should be the same as foo1 if (foo4 == foo1) Delegate_TestClass_delegate72_A.retval -= 0x10; Delegate_TestClass_delegate72_A.retval += 3; foo4(); foo4 = foo3 - foo1; //Should be the same as foo2 if (foo4 == foo2) Delegate_TestClass_delegate72_A.retval -= 0x20; Delegate_TestClass_delegate72_A.retval += 0x0C; foo4(); if (Delegate_TestClass_delegate72_A.retval == 0) Log.Comment("PASS"); else Log.Comment("FAIL, retval==" + Delegate_TestClass_delegate72_A.retval.ToString()); return Delegate_TestClass_delegate72_A.retval; } public static bool testMethod() { return (Main_old() == 0); } } /* delegate double Delegate_TestClass_delegate73_Del(int integerPortion, float fraction); public class Delegate_TestClass_delegate73 { public delegate double MyDelegate2(int integerPortion, float fraction); public double DelegatedMethod1(int intPart, float frac) { return intPart + frac + 5; } public double DelegatedMethod2(int intPart, float frac) { return intPart + frac + 10; } public static int Main_old(String[] args) { int retval = 0x01; Delegate_TestClass_delegate73 mc = null; try { Delegate_TestClass_delegate73_Del md1 = new Delegate_TestClass_delegate73_Del(mc.DelegatedMethod1); md1 += new Delegate_TestClass_delegate73_Del(mc.DelegatedMethod2); MyDelegate2 md2 = new MyDelegate2(mc.DelegatedMethod1); md2 += new MyDelegate2(mc.DelegatedMethod2); if (md1 == md2) retval ^= 0x01; if (md2 == md1) retval ^= 0x02; md2 -= new MyDelegate2(mc.DelegatedMethod1); //Remove from front of list... md2 += new MyDelegate2(mc.DelegatedMethod1); //Add back to list at end if (md1 != md2) retval ^= 0x04; if (md2 != md1) retval ^= 0x08; } catch (System.Exception) { retval -= 0x01; } if (0 == retval) Log.Comment("PASS"); else {Log.Comment("FAIL, 0x{0:X}"); return retval; } public static bool testMethod() { if (Main_old(null) != 0) return false; else return true; } } delegate double Delegate_TestClass_delegate74_Del(int integerPortion, float fraction); public class Delegate_TestClass_delegate74 { public delegate double MyDelegate2(int integerPortion, float fraction); public double DelegatedMethod1(int intPart, float frac) { return intPart + frac + 5; } public double DelegatedMethod2(int intPart, float frac) { return intPart + frac + 10; } public static int Main_old(String[] args) { int retval = 0x03; Delegate_TestClass_delegate74 mc = new Delegate_TestClass_delegate74(); try { Delegate_TestClass_delegate74_Del md1 = new Delegate_TestClass_delegate74_Del(mc.DelegatedMethod1); md1 += new Delegate_TestClass_delegate74_Del(mc.DelegatedMethod2); MyDelegate2 md2 = new MyDelegate2(mc.DelegatedMethod1); md2 += new MyDelegate2(mc.DelegatedMethod2); Delegate[] da1 = md1.GetInvocationList(); Delegate[] da2 = md2.GetInvocationList(); if (da1[1].Method == da2[1].Method) retval ^= 0x01; if (da1[0].Method == da2[0].Method) retval ^= 0x02; } catch (System.Exception) { retval -= 0x01; } if (0 == retval) Log.Comment("PASS"); else {Log.Comment("FAIL, 0x{0:X}"); return retval; } public static bool testMethod() { if (Main_old(null) != 0) return false; else return true; } } delegate double Delegate_TestClass_delegate75_Del(int integerPortion, float fraction); public class Delegate_TestClass_delegate75 { public delegate double MyDelegate2(int integerPortion, float fraction); public double DelegatedMethod1(int intPart, float frac) { return intPart + frac + 5; } public double DelegatedMethod2(int intPart, float frac) { return intPart + frac + 10; } public double DelegatedMethod3(int intPart, float frac) { return intPart + frac + 15; } public double DelegatedMethod4(int intPart, float frac) { return intPart + frac + 20; } public static int Main_old(String[] args) { int retval = 0x3F; Delegate_TestClass_delegate75 mc = new Delegate_TestClass_delegate75(); try { Delegate_TestClass_delegate75_Del md1 = new Delegate_TestClass_delegate75_Del(mc.DelegatedMethod1); md1 += new Delegate_TestClass_delegate75_Del(mc.DelegatedMethod2); MyDelegate2 md2 = new MyDelegate2(mc.DelegatedMethod1); md2 += new MyDelegate2(mc.DelegatedMethod2); Delegate[] da1 = md1.GetInvocationList(); Delegate[] da2 = md2.GetInvocationList(); if (da1[1].Method == da2[1].Method) retval ^= 0x01; if (da1[0].Method == da2[0].Method) retval ^= 0x02; md2 = new MyDelegate2(mc.DelegatedMethod4); md2 += new MyDelegate2(mc.DelegatedMethod3); Delegate_TestClass_delegate75_Del md3 = new Delegate_TestClass_delegate75_Del(mc.DelegatedMethod4) + new Delegate_TestClass_delegate75_Del(mc.DelegatedMethod3); Delegate_TestClass_delegate75_Del md4 = md1 + md3; Delegate[] da3 = md4.GetInvocationList(); if (da3[0].Method == mc.GetType().GetMethod("DelegatedMethod1")) retval ^= 0x04; if (da3[1].Method == mc.GetType().GetMethod("DelegatedMethod2")) retval ^= 0x08; if (da3[2].Method == mc.GetType().GetMethod("DelegatedMethod4")) retval ^= 0x10; if (da3[3].Method == mc.GetType().GetMethod("DelegatedMethod3")) retval ^= 0x20; } catch (System.Exception) { retval -= 0x01; } if (0 == retval) Log.Comment("PASS"); else {Log.Comment("FAIL, 0x{0:X}"); return retval; } public static bool testMethod() { if (Main_old(null) != 0) return false; else return true; } } delegate double Delegate_TestClass_delegate76_Del(int integerPortion, float fraction); public class Delegate_TestClass_delegate76 { public delegate double MyDelegate2(int integerPortion, float fraction); public double DelegatedMethod1(int intPart, float frac) { Log.Comment("DelegatedMethod1"); return intPart + frac + 5; } public double DelegatedMethod2(int intPart, float frac) { Log.Comment("DelegatedMethod2"); return intPart + frac + 10; } public double DelegatedMethod3(int intPart, float frac) { Log.Comment("DelegatedMethod3"); return intPart + frac + 15; } public double DelegatedMethod4(int intPart, float frac) { Log.Comment("DelegatedMethod4"); return intPart + frac + 20; } public static int Main_old(String[] args) { int retval = 0x1F; Delegate_TestClass_delegate76 mc = new Delegate_TestClass_delegate76(); try { Delegate_TestClass_delegate76_Del md1 = new Delegate_TestClass_delegate76_Del(mc.DelegatedMethod1); md1 += new Delegate_TestClass_delegate76_Del(mc.DelegatedMethod2); MyDelegate2 md2 = new MyDelegate2(mc.DelegatedMethod1); md2 += new MyDelegate2(mc.DelegatedMethod2); Delegate[] da1 = md1.GetInvocationList(); Delegate[] da2 = md2.GetInvocationList(); if (da1[1].Method == da2[1].Method) retval ^= 0x01; if (da1[0].Method == da2[0].Method) retval ^= 0x02; md2 = new MyDelegate2(mc.DelegatedMethod4); md2 += new MyDelegate2(mc.DelegatedMethod3); Delegate_TestClass_delegate76_Del md3 = new Delegate_TestClass_delegate76_Del(mc.DelegatedMethod4) + new Delegate_TestClass_delegate76_Del(mc.DelegatedMethod3); Delegate_TestClass_delegate76_Del md4 = new Delegate_TestClass_delegate76_Del(md1) + md3; Delegate[] da3 = md4.GetInvocationList(); if (da3[0].Method.Name == "Invoke") //This is because was constructed by copying another delegate retval ^= 0x04; if (da3[1].Method.Name == mc.GetType().GetMethod("DelegatedMethod4").Name) retval ^= 0x08; if (da3[2].Method.Name == mc.GetType().GetMethod("DelegatedMethod3").Name) retval ^= 0x10; } catch (System.Exception) { retval -= 0x01; } if (0 == retval) Log.Comment("PASS"); else {Log.Comment("FAIL, 0x{0:X}"); return retval; } public static bool testMethod() { if (Main_old(null) != 0) return false; else return true; } } */ delegate bool Delegate_TestClass_delegate77_Del(int integerPortion, float fraction); public class Delegate_TestClass_delegate77 { public delegate bool MyDelegate2(int integerPortion, float fraction); private static int synchro = 31; private static int retval = 0x0F; public bool DelegatedMethod1(int intPart, float frac) { if ((31 == synchro++) && (5 == intPart) && (.25 == frac)) { retval ^= 0x01; return true; } return false; } public bool DelegatedMethod2(int intPart, float frac) { if ((32 == synchro++) && (5 == intPart) && (.25 == frac)) { retval ^= 0x02; return true; } return false; } public bool DelegatedMethod3(int intPart, float frac) { if ((34 == synchro++) && (5 == intPart) && (.25 == frac)) { retval ^= 0x08; return true; } return false; } public bool DelegatedMethod4(int intPart, float frac) { if ((33 == synchro++) && (5 == intPart) && (.25 == frac)) { retval ^= 0x04; return true; } return false; } public static int Main_old(String[] args) { Delegate_TestClass_delegate77 mc = new Delegate_TestClass_delegate77(); try { Delegate_TestClass_delegate77_Del md1 = new Delegate_TestClass_delegate77_Del(mc.DelegatedMethod1); md1 += new Delegate_TestClass_delegate77_Del(mc.DelegatedMethod2); MyDelegate2 md2 = new MyDelegate2(mc.DelegatedMethod4); md2 += new MyDelegate2(mc.DelegatedMethod3); Delegate_TestClass_delegate77_Del md3 = new Delegate_TestClass_delegate77_Del(mc.DelegatedMethod4) + new Delegate_TestClass_delegate77_Del(mc.DelegatedMethod3); Delegate_TestClass_delegate77_Del md4 = new Delegate_TestClass_delegate77_Del(md1) + md3; md4(5, .25f); } catch (System.Exception) { retval -= 0x01; } if (0 == retval) Log.Comment("PASS"); else {Log.Comment("FAIL, 0x{0:X}"); Log.Comment(retval.ToString());} return retval; } public static bool testMethod() { if (Main_old(null) != 0) return false; else return true; } } delegate bool Delegate_TestClass_delegate78_Del(ref int integerPortion, float fraction); public class Delegate_TestClass_delegate78 { public delegate bool MyDelegate2(ref int integerPortion, float fraction); private static int synchro = 31; private static int retval = 0x1F; public bool DelegatedMethod1(ref int intPart, float frac) { if ((31 == synchro++) && (5 == intPart++) && (.25 == frac)) { retval ^= 0x01; return true; } return false; } public bool DelegatedMethod2(ref int intPart, float frac) { if ((32 == synchro++) && (6 == intPart++) && (.25 == frac)) { retval ^= 0x02; return true; } return false; } public bool DelegatedMethod3(ref int intPart, float frac) { if ((34 == synchro++) && (8 == intPart++) && (.25 == frac)) { retval ^= 0x08; return true; } return false; } public bool DelegatedMethod4(ref int intPart, float frac) { if ((33 == synchro++) && (7 == intPart++) && (.25 == frac)) { retval ^= 0x04; return true; } return false; } public static int Main_old(String[] args) { Delegate_TestClass_delegate78 mc = new Delegate_TestClass_delegate78(); try { Delegate_TestClass_delegate78_Del md1 = new Delegate_TestClass_delegate78_Del(mc.DelegatedMethod1); md1 += new Delegate_TestClass_delegate78_Del(mc.DelegatedMethod2); MyDelegate2 md2 = new MyDelegate2(mc.DelegatedMethod4); md2 += new MyDelegate2(mc.DelegatedMethod3); Delegate_TestClass_delegate78_Del md3 = new Delegate_TestClass_delegate78_Del(mc.DelegatedMethod4) + new Delegate_TestClass_delegate78_Del(mc.DelegatedMethod3); Delegate_TestClass_delegate78_Del md4 = new Delegate_TestClass_delegate78_Del(md1) + md3; int i = 5; md4(ref i, .25f); if (9 == i) retval ^= 0x10; } catch (System.Exception) { retval -= 0x01; } if (0 == retval) Log.Comment("PASS"); else {Log.Comment("FAIL, 0x{0:X}"); Log.Comment(retval.ToString());} return retval; } public static bool testMethod() { if (Main_old(null) != 0) return false; else return true; } } delegate bool Delegate_TestClass_delegate79_Del(out int integerPortion, float fraction); public class Delegate_TestClass_delegate79 { public delegate bool MyDelegate2(out int integerPortion, float fraction); private static int synchro = 31; private static int retval = 0x1F; public bool DelegatedMethod1(out int intPart, float frac) { intPart = 5; if ((31 == synchro++) && (.25 == frac)) { retval ^= 0x01; return true; } return false; } public bool DelegatedMethod2(out int intPart, float frac) { intPart = 6; if ((32 == synchro++) && (.25 == frac)) { retval ^= 0x02; return true; } return false; } public bool DelegatedMethod3(out int intPart, float frac) { intPart = 8; if ((34 == synchro++) && (.25 == frac)) { retval ^= 0x08; return true; } return false; } public bool DelegatedMethod4(out int intPart, float frac) { intPart = 7; if ((33 == synchro++) && (.25 == frac)) { retval ^= 0x04; return true; } return false; } public static int Main_old(String[] args) { Delegate_TestClass_delegate79 mc = new Delegate_TestClass_delegate79(); try { Delegate_TestClass_delegate79_Del md1 = new Delegate_TestClass_delegate79_Del(mc.DelegatedMethod1); md1 += new Delegate_TestClass_delegate79_Del(mc.DelegatedMethod2); MyDelegate2 md2 = new MyDelegate2(mc.DelegatedMethod4); md2 += new MyDelegate2(mc.DelegatedMethod3); Delegate_TestClass_delegate79_Del md3 = new Delegate_TestClass_delegate79_Del(mc.DelegatedMethod4) + new Delegate_TestClass_delegate79_Del(mc.DelegatedMethod3); Delegate_TestClass_delegate79_Del md4 = new Delegate_TestClass_delegate79_Del(md1) + md3; int i = 5; md4(out i, .25f); if (8 == i) retval ^= 0x10; } catch (System.Exception) { retval -= 0x01; } if (0 == retval) Log.Comment("PASS"); else {Log.Comment("FAIL, 0x{0:X}"); Log.Comment(retval.ToString());} return retval; } public static bool testMethod() { if (Main_old(null) != 0) return false; else return true; } } delegate bool Delegate_TestClass_delegate80_Del(out int integerPortion, float fraction); public class Delegate_TestClass_delegate80 { public delegate bool MyDelegate2(out int integerPortion, float fraction); private static int synchro = 31; private static int retval = 0x23; public bool DelegatedMethod1(out int intPart, float frac) { intPart = 5; if ((31 == synchro++) && (.25 == frac)) { retval ^= 0x01; return true; } return false; } public bool DelegatedMethod2(out int intPart, float frac) { intPart = 6; if ((32 == synchro++) && (.25 == frac)) { retval ^= 0x02; throw new System.Exception(); return true; } return false; } public bool DelegatedMethod3(out int intPart, float frac) { intPart = 8; if ((34 == synchro++) && (.25 == frac)) { retval ^= 0x08; return true; } return false; } public bool DelegatedMethod4(out int intPart, float frac) { intPart = 7; if ((33 == synchro++) && (.25 == frac)) { retval ^= 0x04; return true; } return false; } public static int Main_old(String[] args) { Delegate_TestClass_delegate80 mc = new Delegate_TestClass_delegate80(); try { Delegate_TestClass_delegate80_Del md1 = new Delegate_TestClass_delegate80_Del(mc.DelegatedMethod1); md1 += new Delegate_TestClass_delegate80_Del(mc.DelegatedMethod2); MyDelegate2 md2 = new MyDelegate2(mc.DelegatedMethod4); md2 += new MyDelegate2(mc.DelegatedMethod3); Delegate_TestClass_delegate80_Del md3 = new Delegate_TestClass_delegate80_Del(mc.DelegatedMethod4) + new Delegate_TestClass_delegate80_Del(mc.DelegatedMethod3); Delegate_TestClass_delegate80_Del md4 = new Delegate_TestClass_delegate80_Del(md1) + md3; int i = 5; md4(out i, .25f); if (8 == i) retval ^= 0x10; } catch (System.Exception) { retval ^= 0x20; } if (0 == retval) Log.Comment("PASS"); else {Log.Comment("FAIL, 0x{0:X}"); Log.Comment(retval.ToString()); } return retval; } public static bool testMethod() { if (Main_old(null) != 0) return false; else return true; } } delegate void Delegate_TestClass_delegate81_B(int x); class Delegate_TestClass_delegate81_A { public static void M1(int i) { Log.Comment("Delegate_TestClass_delegate81_A.M1: " + i); } public static void M2(int i) { Log.Comment("Delegate_TestClass_delegate81_A.M2: " + i); } public void M3(int i) { Log.Comment("Delegate_TestClass_delegate81_A.M3: " + i); } } class Delegate_TestClass_delegate81 { static void Main_old() { Delegate_TestClass_delegate81_B cd1 = new Delegate_TestClass_delegate81_B(Delegate_TestClass_delegate81_A.M1); cd1(-1); // call M1 Delegate_TestClass_delegate81_B cd2 = new Delegate_TestClass_delegate81_B(Delegate_TestClass_delegate81_A.M2); cd2(-2); // call M2 Delegate_TestClass_delegate81_B cd3 = cd1 + cd2; cd3(10); // call M1 then M2 cd3 += cd1; cd3(20); // call M1, M2, then M1 Delegate_TestClass_delegate81_A c = new Delegate_TestClass_delegate81_A(); Delegate_TestClass_delegate81_B cd4 = new Delegate_TestClass_delegate81_B(c.M3); cd3 += cd4; cd3(30); // call M1, M2, M1, then M3 cd3 -= cd1; // remove last M1 cd3(40); // call M1, M2, then M3 cd3 -= cd4; cd3(50); // call M1 then M2 cd3 -= cd2; cd3(60); // call M1 cd3 -= cd2; // impossible removal is benign cd3(60); // call M1 cd3 -= cd1; // invocation list is empty cd3 -= cd1; // impossible removal is benign } public static bool testMethod() { Main_old(); return true; } } public class Delegate_TestClass_delegate_modifier09 { public delegate void Delegate_TestClass_delegate_modifier09_B(); public static int Main_old(String[] args) { return 0; } public static bool testMethod() { if (Main_old(null) != 0) return false; else return true; } } public class Delegate_TestClass_delegate_modifier10 { protected delegate void Delegate_TestClass_delegate_modifier10_B(); public static int Main_old(String[] args) { return 0; } public static bool testMethod() { if (Main_old(null) != 0) return false; else return true; } } public class Delegate_TestClass_delegate_modifier11 { private delegate void Delegate_TestClass_delegate_modifier11_B(); public static int Main_old(String[] args) { return 0; } public static bool testMethod() { if (Main_old(null) != 0) return false; else return true; } } public class Delegate_TestClass_delegate_modifier12 { internal delegate void Delegate_TestClass_delegate_modifier12_B(); public static int Main_old(String[] args) { return 0; } public static bool testMethod() { if (Main_old(null) != 0) return false; else return true; } } } } ================================================ FILE: Zelig/Zelig/Test/RunTime/NETMF/mscorlib/enums/EnumTests.cs ================================================ //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // Copyright (c) Microsoft Corporation. All rights reserved. //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// using System; using System.Reflection; namespace Microsoft.Zelig.Test { public class EnumTests : TestBase, ITestInterface { [SetUp] public InitializeResult Initialize() { Log.Comment("Adding set up for the tests."); // Add your functionality here. return InitializeResult.ReadyToGo; } [TearDown] public void CleanUp() { Log.Comment("Cleaning up after the tests"); } public override TestResult Run(string[] args) { TestResult result = TestResult.Pass; string testName = "Enum"; result |= Assert.CheckFailed(Enum01_Test(), testName, 1); result |= Assert.CheckFailed(Enum02_Test(), testName, 2); result |= Assert.CheckFailed(Enum07_Test(), testName, 7); result |= Assert.CheckFailed(Enum09_Test(), testName, 9); result |= Assert.CheckFailed(Enum10_Test(), testName, 10); result |= Assert.CheckFailed(Enum11_Test(), testName, 11); result |= Assert.CheckFailed(Enum27_Test(), testName, 27); result |= Assert.CheckFailed(Enum28_Test(), testName, 28); result |= Assert.CheckFailed(Enum29_Test(), testName, 29); result |= Assert.CheckFailed(Enum30_Test(), testName, 30); result |= Assert.CheckFailed(Enum31_Test(), testName, 31); result |= Assert.CheckFailed(Enum33_Test(), testName, 33); result |= Assert.CheckFailed(Enum34_Test(), testName, 34); result |= Assert.CheckFailed(Enum35_Test(), testName, 35); result |= Assert.CheckFailed(Enum36_Test(), testName, 36); result |= Assert.CheckFailed(Enum37_Test(), testName, 37); result |= Assert.CheckFailed(Enum38_Test(), testName, 38); result |= Assert.CheckFailed(Enum39_Test(), testName, 39); result |= Assert.CheckFailed(Enum40_Test(), testName, 40); result |= Assert.CheckFailed(Enum41_Test(), testName, 41); result |= Assert.CheckFailed(Enum42_Test(), testName, 42); result |= Assert.CheckFailed(Enum43_Test(), testName, 43); result |= Assert.CheckFailed(Enum44_Test(), testName, 44); result |= Assert.CheckFailed(Enum45_Test(), testName, 45); result |= Assert.CheckFailed(Enum46_Test(), testName, 46); result |= Assert.CheckFailed(Enum47_Test(), testName, 47); result |= Assert.CheckFailed(Enum48_Test(), testName, 48); result |= Assert.CheckFailed(Enum54_Test(), testName, 54); result |= Assert.CheckFailed(Enum55_Test(), testName, 55); result |= Assert.CheckFailed(Enum56_Test(), testName, 56); result |= Assert.CheckFailed(Enum57_Test(), testName, 57); result |= Assert.CheckFailed(Enum58_Test(), testName, 58); result |= Assert.CheckFailed(Enum62_Test(), testName, 62); result |= Assert.CheckFailed(Enum63_Test(), testName, 63); result |= Assert.CheckFailed(Enum64_Test(), testName, 64); result |= Assert.CheckFailed(Enum65_Test(), testName, 65); result |= Assert.CheckFailed(Enum66_Test(), testName, 66); result |= Assert.CheckFailed(Enum67_Test(), testName, 67); result |= Assert.CheckFailed(Enum68_Test(), testName, 68); result |= Assert.CheckFailed(Enum69_Test(), testName, 69); result |= Assert.CheckFailed(Enum70_Test(), testName, 70); result |= Assert.CheckFailed(Enum71_Test(), testName, 71); result |= Assert.CheckFailed(Enum72_Test(), testName, 72); result |= Assert.CheckFailed(Enum73_Test(), testName, 73); result |= Assert.CheckFailed(Enum74_Test(), testName, 74); result |= Assert.CheckFailed(Enum75_Test(), testName, 75); result |= Assert.CheckFailed(Enum77_Test(), testName, 77); result |= Assert.CheckFailed(Enum78_Test(), testName, 78); result |= Assert.CheckFailed(Enum83_Test(), testName, 83); result |= Assert.CheckFailed(Enum86_Test(), testName, 86); result |= Assert.CheckFailed(Enum93_Test(), testName, 93); result |= Assert.CheckFailed(Enum94_Test(), testName, 94); testName = "EnumFlags"; result |= Assert.CheckFailed(EnumFlags01_Test(), testName, 1); result |= Assert.CheckFailed(EnumFlags02_Test(), testName, 2); result |= Assert.CheckFailed(EnumFlags03_Test(), testName, 3); result |= Assert.CheckFailed(EnumFlags04_Test(), testName, 4); return result; } //Enum Test methods //The following tests were ported from folder current\test\cases\client\CLR\Conformance\10_classes\Enum //enum01,enum02,enum07,enum09,enum10,enum11,enum27,enum28,enum29,enum30,enum31,enum33,enum34,enum35,enum36,enum37,enum38,enum39,enum40,enum41,enum42,enum43,enum43u,enum44,enum45,enum46,enum46u,enum47,enum47u,enum48,enum48u,enum54,enum55,enum56,enum57,enum58,enum62,enum63,enum64,enum65,enum66,enum67,enum68,enum69,enum70,enum71,enum72,enum73,enum74,enum75,enum77,enum78,enum83,enum86,enum93,enum94,enum_flags01,enum_flags02,enum_flags03,enum_flags04 //Test Case Calls [TestMethod] public TestResult Enum01_Test() { Log.Comment("Make sure that a basic enum declaration, definition, and assignment work."); if (Enum_TestClass_enum01.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Enum02_Test() { Log.Comment("Make sure that basic enum-with-base-type declarations, definitions, and assignments work."); if (Enum_TestClass_enum02.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Enum07_Test() { Log.Comment("Make sure that basic enum-with-base-type declarations, definitions, and assignments work."); if (Enum_TestClass_enum07.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Enum09_Test() { Log.Comment("Make sure that basic enum-with-base-type declarations, definitions, and assignments work."); if (Enum_TestClass_enum09.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Enum10_Test() { Log.Comment("Make sure that basic enum-with-base-type declarations, definitions, and assignments work."); if (Enum_TestClass_enum10.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Enum11_Test() { Log.Comment("Make sure that basic enum-with-base-type declarations, definitions, and assignments work."); if (Enum_TestClass_enum11.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Enum27_Test() { Log.Comment("Check that enumerator values are initialized as expected"); if (Enum_TestClass_enum27.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Enum28_Test() { Log.Comment("Check that enumerator values are initialized as expected"); if (Enum_TestClass_enum28.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Enum29_Test() { Log.Comment("The values of the enumerators need not be distinct"); if (Enum_TestClass_enum29.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Enum30_Test() { Log.Comment("Check the point of definition of an enumerator"); if (Enum_TestClass_enum30.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Enum31_Test() { Log.Comment("Check the point of definition of an enumerator"); if (Enum_TestClass_enum31.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Enum33_Test() { Log.Comment("Enums obey local scope rules. An enum of the same name may be defined in an inner scope."); if (Enum_TestClass_enum33.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Enum34_Test() { Log.Comment("Enums can be converted to int."); if (Enum_TestClass_enum34.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Enum35_Test() { Log.Comment("If no enumerator-definitions with = appear, then the"); Log.Comment(" values of the corresponding constants begin at zero and"); if (Enum_TestClass_enum35.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Enum36_Test() { Log.Comment("If no enumerator-definitions with = appear, then the"); Log.Comment(" values of the corresponding constants begin at zero and"); if (Enum_TestClass_enum36.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Enum37_Test() { Log.Comment("If no enumerator-definitions with = appear, then the"); Log.Comment(" values of the corresponding constants begin at zero and"); if (Enum_TestClass_enum37.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Enum38_Test() { Log.Comment("Enums can be declared in any scopt that a class can be declared in."); if (Enum_TestClass_enum38.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Enum39_Test() { Log.Comment("If the constant-expression initilizing an enumerator is of integral type,"); Log.Comment("it must be within the range of values that can be represented by the underlying type."); if (Enum_TestClass_enum39.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Enum40_Test() { Log.Comment("If the constant-expression initilizing an enumerator is of integral type,"); Log.Comment("it must be within the range of values that can be represented by the underlying type."); if (Enum_TestClass_enum40.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Enum41_Test() { Log.Comment("If the constant-expression initilizing an enumerator is of integral type,"); Log.Comment("it must be within the range of values that can be represented by the underlying type."); if (Enum_TestClass_enum41.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Enum42_Test() { Log.Comment("If the constant-expression initilizing an enumerator is of integral type,"); Log.Comment("it must be within the range of values that can be represented by the underlying type."); if (Enum_TestClass_enum42.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Enum43_Test() { Log.Comment("If the constant-expression initilizing an enumerator is of integral type,"); Log.Comment("it must be within the range of values that can be represented by the underlying type."); if (Enum_TestClass_enum43.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Enum43u_Test() { Log.Comment("If the constant-expression initilizing an enumerator is of integral type,"); Log.Comment("it must be within the range of values that can be represented by the underlying type."); if (Enum_TestClass_enum43u.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Enum44_Test() { Log.Comment("If the constant-expression initilizing an enumerator is of integral type,"); Log.Comment("it must be within the range of values that can be represented by the underlying type."); if (Enum_TestClass_enum44.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Enum45_Test() { Log.Comment("If the constant-expression initilizing an enumerator is of integral type,"); Log.Comment("it must be within the range of values that can be represented by the underlying type."); if (Enum_TestClass_enum45.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Enum46_Test() { Log.Comment("If the constant-expression initilizing an enumerator is of integral type,"); Log.Comment("it must be within the range of values that can be represented by the underlying type."); if (Enum_TestClass_enum46.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Enum46u_Test() { Log.Comment("If the constant-expression initilizing an enumerator is of integral type,"); Log.Comment("it must be within the range of values that can be represented by the underlying type."); if (Enum_TestClass_enum46u.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Enum47_Test() { Log.Comment("If the constant-expression initilizing an enumerator is of integral type,"); Log.Comment("it must be within the range of values that can be represented by the underlying type."); if (Enum_TestClass_enum47.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Enum47u_Test() { Log.Comment("If the constant-expression initilizing an enumerator is of integral type,"); Log.Comment("it must be within the range of values that can be represented by the underlying type."); if (Enum_TestClass_enum47u.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Enum48_Test() { Log.Comment("If the constant-expression initilizing an enumerator is of integral type,"); Log.Comment("it must be within the range of values that can be represented by the underlying type."); if (Enum_TestClass_enum48.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Enum48u_Test() { Log.Comment("If the constant-expression initilizing an enumerator is of integral type,"); Log.Comment("it must be within the range of values that can be represented by the underlying type."); if (Enum_TestClass_enum48u.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Enum54_Test() { Log.Comment("++ and -- operators can be used with objects of enumeration type. Check postfix form."); if (Enum_TestClass_enum54.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Enum55_Test() { Log.Comment("++ and -- operators can be used with objects of enumeration type. Check postfix form."); if (Enum_TestClass_enum55.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Enum56_Test() { Log.Comment("++ and -- operators can be used with objects of enumeration type. Check postfix form."); if (Enum_TestClass_enum56.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Enum57_Test() { Log.Comment("++ and -- operators can be used with objects of enumeration type. Check postfix form."); if (Enum_TestClass_enum57.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Enum58_Test() { Log.Comment("Bitwise operators AND, OR, XOR, and NOT can be used with objects of enumeration type."); if (Enum_TestClass_enum58.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Enum62_Test() { if (Enum_TestClass_enum62.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Enum63_Test() { Log.Comment("Make sure that a basic enum declaration, definition, and assignment work."); if (Enum_TestClass_enum63.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Enum64_Test() { Log.Comment("Make sure that a basic enum declaration, definition, and assignment work."); if (Enum_TestClass_enum64.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Enum65_Test() { Log.Comment("Make sure that a basic enum declaration, definition, and assignment work."); if (Enum_TestClass_enum65.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Enum66_Test() { Log.Comment("Make sure that a basic enum declaration, definition, and assignment work."); if (Enum_TestClass_enum66.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Enum67_Test() { Log.Comment("Make sure that a basic enum declaration, definition, and assignment work."); if (Enum_TestClass_enum67.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Enum68_Test() { Log.Comment("Make sure that a basic enum declaration, definition, and assignment work."); if (Enum_TestClass_enum68.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Enum69_Test() { Log.Comment("Make sure that a basic enum declaration, definition, and assignment work."); if (Enum_TestClass_enum69.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Enum70_Test() { Log.Comment("Make sure that a basic enum declaration, definition, and assignment work."); if (Enum_TestClass_enum70.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Enum71_Test() { Log.Comment("Make sure that a basic enum declaration, definition, and assignment work."); Log.Comment("This test is expeced to fail"); if (Enum_TestClass_enum71.testMethod()) { return TestResult.Fail; } return TestResult.Pass; } [TestMethod] public TestResult Enum72_Test() { Log.Comment("Enum_TestClass_? bitwise and on enums"); if (Enum_TestClass_enum72.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Enum73_Test() { Log.Comment("Enum_TestClass_? bitwise or on enums"); if (Enum_TestClass_enum73.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Enum74_Test() { Log.Comment("Enum_TestClass_? bitwise xor on enums"); if (Enum_TestClass_enum74.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Enum75_Test() { Log.Comment("Enum_TestClass_? bitwise not on enums"); if (Enum_TestClass_enum75.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Enum77_Test() { Log.Comment("Enum_TestClass_? bitwise not on enums"); if (Enum_TestClass_enum77.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Enum78_Test() { if (Enum_TestClass_enum78.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Enum83_Test() { Log.Comment("Enum member list can end with a comma"); if (Enum_TestClass_enum83.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Enum86_Test() { Log.Comment("[Access] modifiers of an enum declaration have the same meaning"); Log.Comment("as those of a class declaration."); if (Enum_TestClass_enum86.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Enum93_Test() { Log.Comment("Example from Enums chapter in CLS"); if (Enum_TestClass_enum93.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Enum94_Test() { Log.Comment("...any value of the underlying type of an enum can be cast to the enum type."); if (Enum_TestClass_enum94.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult EnumFlags01_Test() { Log.Comment("check FlagAttribute with enum"); if (Enum_TestClassFlags01.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult EnumFlags02_Test() { Log.Comment("check FlagAttribute with enum"); if (Enum_TestClassFlags02.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult EnumFlags03_Test() { Log.Comment("check FlagAttribute with enum"); if (Enum_TestClassFlags03.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult EnumFlags04_Test() { Log.Comment("check FlagAttribute with enum with conversion"); if (Enum_TestClassFlags04.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } //Compiled Test Cases public class Enum_TestClass_enum01 { public enum e1 { one = 1, two = 2, three = 3 }; public static int Main_old() { e1 v_e1 = e1.two; Log.Comment("v_e1 == "); Log.Comment(v_e1.ToString()); return 0; } public static bool testMethod() { return (Main_old() == 0); } }; public class Enum_TestClass_enum02 { public enum e1 : long { one = 1, two = 2, three = 3 }; public enum e2 : int { one = 1, two = 2, three = 3 }; public enum e3 : short { one = 1, two = 2, three = 3 }; public enum e4 : byte { one = 1, two = 2, three = 3 }; public static int Main_old() { e1 v_e1 = e1.two; e2 v_e2 = e2.two; e3 v_e3 = e3.two; e4 v_e4 = e4.two; Log.Comment("v_e1 == "); Log.Comment(v_e1.ToString()); Log.Comment("v_e2 == "); Log.Comment(v_e2.ToString()); Log.Comment("v_e3 == "); Log.Comment(v_e3.ToString()); Log.Comment("v_e4 == "); Log.Comment(v_e4.ToString()); return 0; } public static bool testMethod() { return (Main_old() == 0); } }; public class Enum_TestClass_enum07 { public enum e1 { one = 1, two = 2, three = 3 }; public static int Main_old() { int i = (int)e1.two; Log.Comment("i == "); Log.Comment(i.ToString()); return i - 2; } public static bool testMethod() { return (Main_old() == 0); } }; public class Enum_TestClass_enum09 { public enum e1 : int { one = 1, two = 2, three = 3 }; public static int Main_old() { int i = (int)e1.two; Log.Comment("i == "); Log.Comment(i.ToString()); return i - 2; } public static bool testMethod() { return (Main_old() == 0); } }; public class Enum_TestClass_enum10 { public enum e1 : short { one = 1, two = 2, three = 3 }; public static int Main_old() { int i = (short)e1.two; Log.Comment("i == "); Log.Comment(i.ToString()); return i - 2; } public static bool testMethod() { return (Main_old() == 0); } }; public class Enum_TestClass_enum11 { public enum e1 : byte { one = 1, two = 2, three = 3 }; public static int Main_old() { int i = (byte)e1.two; Log.Comment("i == "); Log.Comment(i.ToString()); return i - 2; } public static bool testMethod() { return (Main_old() == 0); } }; public class Enum_TestClass_enum27 { public static int retval = 0; public enum Enum_TestClass_enum27_Enum1 { zero, one, three = 3, four, minus7 = -7, minus6 }; public static int Main_old() { if ((int)Enum_TestClass_enum27_Enum1.zero != 0) { Log.Comment("Enumerator zero = "); Log.Comment((Enum_TestClass_enum27_Enum1.zero).ToString()); retval |= 0x01; } if ((int)Enum_TestClass_enum27_Enum1.one != 1) { Log.Comment("Enumerator one = "); Log.Comment((Enum_TestClass_enum27_Enum1.one).ToString()); retval |= 0x02; } if ((int)Enum_TestClass_enum27_Enum1.three != 3) { Log.Comment("Enumerator three = "); Log.Comment((Enum_TestClass_enum27_Enum1.three).ToString()); retval |= 0x04; } if ((int)Enum_TestClass_enum27_Enum1.four != 4) { Log.Comment("Enumerator four = "); Log.Comment((Enum_TestClass_enum27_Enum1.four).ToString()); retval |= 0x08; } if ((int)Enum_TestClass_enum27_Enum1.minus7 != -7) { Log.Comment("Enumerator minus7 = "); Log.Comment((Enum_TestClass_enum27_Enum1.minus7).ToString()); retval |= 0x10; } if ((int)Enum_TestClass_enum27_Enum1.minus6 != -6) { Log.Comment("Enumerator minus6 = "); Log.Comment((Enum_TestClass_enum27_Enum1.minus6).ToString()); retval |= 0x20; } if (retval == 0) Log.Comment("PASS"); else Log.Comment("FAIL"); return retval; } public static bool testMethod() { return (Main_old() == 0); } }; public class Enum_TestClass_enum28 { public static int retval = 0; public enum Enum_TestClass_enum28_Enum1 { zero, one, three = 3, four, minus7 = -7, minus6 }; public static int Main_old() { if (!((Enum_TestClass_enum28_Enum1)Enum_TestClass_enum28_Enum1.zero == (Enum_TestClass_enum28_Enum1)0)) { Log.Comment("Enumerator zero = "); Log.Comment((Enum_TestClass_enum28_Enum1.zero).ToString()); retval |= 0x01; } if (Enum_TestClass_enum28_Enum1.one != (Enum_TestClass_enum28_Enum1)1) { Log.Comment("Enumerator one = "); Log.Comment((Enum_TestClass_enum28_Enum1.one).ToString()); retval |= 0x02; } if (Enum_TestClass_enum28_Enum1.three != (Enum_TestClass_enum28_Enum1)3) { Log.Comment("Enumerator three = "); Log.Comment((Enum_TestClass_enum28_Enum1.three).ToString()); retval |= 0x04; } if (Enum_TestClass_enum28_Enum1.four != (Enum_TestClass_enum28_Enum1)4) { Log.Comment("Enumerator four = "); Log.Comment((Enum_TestClass_enum28_Enum1.four).ToString()); retval |= 0x08; } if (Enum_TestClass_enum28_Enum1.minus7 != (Enum_TestClass_enum28_Enum1)(-7)) { Log.Comment("Enumerator minus7 = "); Log.Comment((Enum_TestClass_enum28_Enum1.minus7).ToString()); retval |= 0x10; } if (Enum_TestClass_enum28_Enum1.minus6 != (Enum_TestClass_enum28_Enum1)(-6)) { Log.Comment("Enumerator minus6 = "); Log.Comment((Enum_TestClass_enum28_Enum1.minus6).ToString()); retval |= 0x20; } if (retval == 0) Log.Comment("PASS"); else Log.Comment("FAIL"); return retval; } public static bool testMethod() { return (Main_old() == 0); } }; public class Enum_TestClass_enum29 { public static int retval = 0; public enum Enum_TestClass_enum29_Enum1 { zero = 0, one = 0 }; public static int Main_old() { if (Enum_TestClass_enum29_Enum1.one != Enum_TestClass_enum29_Enum1.zero) { Log.Comment("Enumerator zero and one not synonymous"); retval = 1; } if (retval == 0) Log.Comment("PASS"); else Log.Comment("FAIL"); return retval; } public static bool testMethod() { return (Main_old() == 0); } }; public class Enum_TestClass_enum30 { public static int retval = 0; public enum Enum_TestClass_enum30_Enum1 { zero, three = (int)zero + 3 }; public static int Main_old() { if ((int)Enum_TestClass_enum30_Enum1.three != 3) { Log.Comment("Enumerator zero and one not synonymous"); retval = 1; } if (retval == 0) Log.Comment("PASS"); else Log.Comment("FAIL"); return retval; } public static bool testMethod() { return (Main_old() == 0); } }; public class Enum_TestClass_enum31 { public static int retval = 0; public enum Enum_TestClass_enum31_Enum1 { }; public static int Main_old() { Log.Comment("PASS"); return retval; } public static bool testMethod() { return (Main_old() == 0); } }; enum Enum_TestClass_enum33_Enum1 { yes = 1, no = yes - 1 }; public class Enum_TestClass_enum33 { public static int retval = 0; public enum Enum_TestClass_enum33_Enum1 { yes = 1, no = yes - 1 }; public static int Main_old() { Log.Comment("PASS"); return retval; } public static bool testMethod() { return (Main_old() == 0); } }; public class Enum_TestClass_enum34 { public static int retval = 0; public enum color { red, yellow, green = 20, blue }; public static int Main_old() { int i = (int)color.yellow; //ok: yellow converted to int value 1 //by integral promotion" Log.Comment("PASS"); return retval; } public static bool testMethod() { return (Main_old() == 0); } }; public class Enum_TestClass_enum35 { public static int retval = 0x3F; public enum E { a, b, c, d = 7, e, f = 3 }; public static int Main_old() { if ((int)E.a == 0) retval -= 0x20; if ((int)E.b == 1) retval -= 0x10; if ((int)E.c == 2) retval -= 0x08; if ((int)E.d == 7) retval -= 0x04; if ((int)E.e == 8) retval -= 0x02; if ((int)E.f == 3) retval -= 0x01; if (retval == 0) Log.Comment("PASS"); else { Log.Comment("FAIL\nretval == "); Log.Comment((retval).ToString()); } return retval; } public static bool testMethod() { return (Main_old() == 0); } }; public class Enum_TestClass_enum36_Enum { public enum E { a, b, c, d = 7, e, f = 3 }; } public class Enum_TestClass_enum36 { public static int retval = 0x3F; public static int Main_old() { if ((int)Enum_TestClass_enum36_Enum.E.a == 0) retval -= 0x20; if ((int)Enum_TestClass_enum36_Enum.E.b == 1) retval -= 0x10; if ((int)Enum_TestClass_enum36_Enum.E.c == 2) retval -= 0x08; if ((int)Enum_TestClass_enum36_Enum.E.d == 7) retval -= 0x04; if ((int)Enum_TestClass_enum36_Enum.E.e == 8) retval -= 0x02; if ((int)Enum_TestClass_enum36_Enum.E.f == 3) retval -= 0x01; if (retval == 0) Log.Comment("PASS"); else { Log.Comment("FAIL\nretval == "); Log.Comment((retval).ToString()); } return retval; } public static bool testMethod() { return (Main_old() == 0); } }; public class Enum_TestClass_enum37_Enum { public enum E { a, b, c, d = 7, e, f = 3 }; } public class Enum_TestClass_enum37 { public static int retval = 0x3F; public static int Main_old() { Enum_TestClass_enum37_Enum f = new Enum_TestClass_enum37_Enum(); if ((int)Enum_TestClass_enum37_Enum.E.a == 0) retval -= 0x20; if ((int)Enum_TestClass_enum37_Enum.E.b == 1) retval -= 0x10; if ((int)Enum_TestClass_enum37_Enum.E.c == 2) retval -= 0x08; if ((int)Enum_TestClass_enum37_Enum.E.d == 7) retval -= 0x04; if ((int)Enum_TestClass_enum37_Enum.E.e == 8) retval -= 0x02; if ((int)Enum_TestClass_enum37_Enum.E.f == 3) retval -= 0x01; if (retval == 0) Log.Comment("PASS"); else { Log.Comment("FAIL\nretval == "); Log.Comment((retval).ToString()); } return retval; } public static bool testMethod() { return (Main_old() == 0); } }; public enum Enum_TestClass_enum38_Enum1 { a, b, c, d = 7, e, f = 3 }; public class Enum_TestClass_enum38_Enum { public enum E { a, b, c, d = 7, e, f = 3 }; } public class Enum_TestClass_enum38 { public static int retval = 0x3F; public static int Main_old() { if ((int)Enum_TestClass_enum38_Enum1.a == 0) retval -= 0x20; if ((int)Enum_TestClass_enum38_Enum1.b == 1) retval -= 0x10; if ((int)Enum_TestClass_enum38_Enum1.c == 2) retval -= 0x08; if ((int)Enum_TestClass_enum38_Enum1.d == 7) retval -= 0x04; if ((int)Enum_TestClass_enum38_Enum1.e == 8) retval -= 0x02; if ((int)Enum_TestClass_enum38_Enum1.f == 3) retval -= 0x01; if (retval == 0) Log.Comment("PASS"); else { Log.Comment("FAIL\nretval == "); Log.Comment((retval).ToString()); } return retval; } public static bool testMethod() { return (Main_old() == 0); } }; public enum Enum_TestClass_enum39_Enum1 : byte { a, b, c, d = 253, e, f }; public class Enum_TestClass_enum39 { public static int retval = 0x3F; public static int Main_old() { if ((int)Enum_TestClass_enum39_Enum1.a == 0) retval -= 0x20; if ((int)Enum_TestClass_enum39_Enum1.b == 1) retval -= 0x10; if ((int)Enum_TestClass_enum39_Enum1.c == 2) retval -= 0x08; if ((int)Enum_TestClass_enum39_Enum1.d == 253) retval -= 0x04; if ((int)Enum_TestClass_enum39_Enum1.e == 254) retval -= 0x02; if ((int)Enum_TestClass_enum39_Enum1.f == 255) retval -= 0x01; if (retval == 0) Log.Comment("PASS"); else { Log.Comment("FAIL\nretval == "); Log.Comment((retval).ToString()); } return retval; } public static bool testMethod() { return (Main_old() == 0); } }; public enum Enum_TestClass_enum40_Enum1 : short { a, b, c, d = 32765, e, f }; public class Enum_TestClass_enum40 { public static int retval = 0x3F; public static int Main_old() { if ((int)Enum_TestClass_enum40_Enum1.a == 0) retval -= 0x20; if ((int)Enum_TestClass_enum40_Enum1.b == 1) retval -= 0x10; if ((int)Enum_TestClass_enum40_Enum1.c == 2) retval -= 0x08; if ((int)Enum_TestClass_enum40_Enum1.d == 32765) retval -= 0x04; if ((int)Enum_TestClass_enum40_Enum1.e == 32766) retval -= 0x02; if ((int)Enum_TestClass_enum40_Enum1.f == 32767) retval -= 0x01; if (retval == 0) Log.Comment("PASS"); else { Log.Comment("FAIL\nretval == "); Log.Comment((retval).ToString()); } return retval; } public static bool testMethod() { return (Main_old() == 0); } }; public enum Enum_TestClass_enum41_Enum1 : int { a, b, c, d = (int)0x7FFFFFFD, e, f }; public class Enum_TestClass_enum41 { public static int retval = 0x3F; public static int Main_old() { if ((int)Enum_TestClass_enum41_Enum1.a == 0) retval -= 0x20; if ((int)Enum_TestClass_enum41_Enum1.b == 1) retval -= 0x10; if ((int)Enum_TestClass_enum41_Enum1.c == 2) retval -= 0x08; if ((int)Enum_TestClass_enum41_Enum1.d == 0x7FFFFFFD) retval -= 0x04; if ((int)Enum_TestClass_enum41_Enum1.e == 0x7FFFFFFE) retval -= 0x02; if ((int)Enum_TestClass_enum41_Enum1.f == 0x7FFFFFFF) retval -= 0x01; if (retval == 0) Log.Comment("PASS"); else { Log.Comment("FAIL\nretval == "); Log.Comment((retval).ToString()); } return retval; } public static bool testMethod() { return (Main_old() == 0); } }; public enum Enum_TestClass_enum42_Enum1 : long { a, b, c, d = (long)0x7FFFFFFFFFFFFFFDL, e, f }; public class Enum_TestClass_enum42 { public static int retval = 0x3F; public static int Main_old() { if ((long)Enum_TestClass_enum42_Enum1.a == 0) retval -= 0x20; if ((long)Enum_TestClass_enum42_Enum1.b == 1) retval -= 0x10; if ((long)Enum_TestClass_enum42_Enum1.c == 2) retval -= 0x08; if ((long)Enum_TestClass_enum42_Enum1.d == 0x7FFFFFFFFFFFFFFD) retval -= 0x04; if ((long)Enum_TestClass_enum42_Enum1.e == 0x7FFFFFFFFFFFFFFE) retval -= 0x02; if ((long)Enum_TestClass_enum42_Enum1.f == 0x7FFFFFFFFFFFFFFF) retval -= 0x01; if (retval == 0) Log.Comment("PASS"); else { Log.Comment("FAIL\nretval == "); Log.Comment((retval).ToString()); } return retval; } public static bool testMethod() { return (Main_old() == 0); } }; public enum Enum_TestClass_enum43_Enum1 : int { a, b, c, d = (int)0x7FFFFFFD, e, f }; public enum Enum_TestClass_enum43_Enum2 : short { a = (short)Enum_TestClass_enum43_Enum1.a, b, c, d, e, f }; public class Enum_TestClass_enum43 { public static int retval = 0x3F; public static int Main_old() { if ((int)Enum_TestClass_enum43_Enum2.a == 0) retval -= 0x20; if ((int)Enum_TestClass_enum43_Enum2.b == 1) retval -= 0x10; if ((int)Enum_TestClass_enum43_Enum2.c == 2) retval -= 0x08; if ((int)Enum_TestClass_enum43_Enum2.d == 3) retval -= 0x04; if ((int)Enum_TestClass_enum43_Enum2.e == 4) retval -= 0x02; if ((int)Enum_TestClass_enum43_Enum2.f == 5) retval -= 0x01; if (retval == 0) Log.Comment("PASS"); else { Log.Comment("FAIL\nretval == "); Log.Comment((retval).ToString()); } return retval; } public static bool testMethod() { return (Main_old() == 0); } }; public enum Enum_TestClass_enum43u_Enum1 : int { a, b, c, d = (int)0x7FFFFFFD, e, f }; public enum Enum_TestClass_enum43u_Enum2 : ushort { a = (ushort)Enum_TestClass_enum43u_Enum1.a, b, c, d, e, f }; public class Enum_TestClass_enum43u { public static int retval = 0x3F; public static int Main_old() { if ((int)Enum_TestClass_enum43u_Enum2.a == 0) retval -= 0x20; if ((int)Enum_TestClass_enum43u_Enum2.b == 1) retval -= 0x10; if ((int)Enum_TestClass_enum43u_Enum2.c == 2) retval -= 0x08; if ((int)Enum_TestClass_enum43u_Enum2.d == 3) retval -= 0x04; if ((int)Enum_TestClass_enum43u_Enum2.e == 4) retval -= 0x02; if ((int)Enum_TestClass_enum43u_Enum2.f == 5) retval -= 0x01; if (retval == 0) Log.Comment("PASS"); else { Log.Comment("FAIL\nretval == "); Log.Comment((retval).ToString()); } return retval; } public static bool testMethod() { return (Main_old() == 0); } }; public enum Enum_TestClass_enum44_Enum1 : int { a, b, c, d = (int)0x7FFFFFFD, e, f }; public enum Enum_TestClass_enum44_Enum2 : byte { a = Enum_TestClass_enum44_Enum1.a, b, c, d, e, f }; public class Enum_TestClass_enum44 { public static int retval = 0x3F; public static int Main_old() { if ((int)Enum_TestClass_enum44_Enum2.a == 0) retval -= 0x20; if ((int)Enum_TestClass_enum44_Enum2.b == 1) retval -= 0x10; if ((int)Enum_TestClass_enum44_Enum2.c == 2) retval -= 0x08; if ((int)Enum_TestClass_enum44_Enum2.d == 3) retval -= 0x04; if ((int)Enum_TestClass_enum44_Enum2.e == 4) retval -= 0x02; if ((int)Enum_TestClass_enum44_Enum2.f == 5) retval -= 0x01; if (retval == 0) Log.Comment("PASS"); else { Log.Comment("FAIL\nretval == "); Log.Comment((retval).ToString()); } return retval; } public static bool testMethod() { return (Main_old() == 0); } }; public enum Enum_TestClass_enum45_Enum1 : long { a, b, c, d = (long)0x7FFFFFFFFFFFFFFDL, e, f }; public enum Enum_TestClass_enum45_Enum2 : int { a = (int)Enum_TestClass_enum45_Enum1.a, b, c, d, e, f }; public class Enum_TestClass_enum45 { public static int retval = 0x3F; public static int Main_old() { if ((int)Enum_TestClass_enum45_Enum2.a == 0) retval -= 0x20; if ((int)Enum_TestClass_enum45_Enum2.b == 1) retval -= 0x10; if ((int)Enum_TestClass_enum45_Enum2.c == 2) retval -= 0x08; if ((int)Enum_TestClass_enum45_Enum2.d == 3) retval -= 0x04; if ((int)Enum_TestClass_enum45_Enum2.e == 4) retval -= 0x02; if ((int)Enum_TestClass_enum45_Enum2.f == 5) retval -= 0x01; if (retval == 0) Log.Comment("PASS"); else { Log.Comment("FAIL\nretval == "); Log.Comment((retval).ToString()); } return retval; } public static bool testMethod() { return (Main_old() == 0); } }; public enum Enum_TestClass_enum46_Enum2 : short { a = Enum_TestClass_enum46_Enum1.a, b, c, d, e, f }; public enum Enum_TestClass_enum46_Enum1 : int { a, b, c, d = (int)0x7FFFFFFD, e, f }; public class Enum_TestClass_enum46 { public static int retval = 0x3F; public static int Main_old() { if ((int)Enum_TestClass_enum46_Enum2.a == 0) retval -= 0x20; if ((int)Enum_TestClass_enum46_Enum2.b == 1) retval -= 0x10; if ((int)Enum_TestClass_enum46_Enum2.c == 2) retval -= 0x08; if ((int)Enum_TestClass_enum46_Enum2.d == 3) retval -= 0x04; if ((int)Enum_TestClass_enum46_Enum2.e == 4) retval -= 0x02; if ((int)Enum_TestClass_enum46_Enum2.f == 5) retval -= 0x01; if (retval == 0) Log.Comment("PASS"); else { Log.Comment("FAIL\nretval == "); Log.Comment((retval).ToString()); } return retval; } public static bool testMethod() { return (Main_old() == 0); } }; public enum Enum_TestClass_enum46u_Enum1 : uint { a, b, c, d = 0xFFFFFFFD, e, f }; public class Enum_TestClass_enum46u { public static int retval = 0x3F; public static int Main_old() { if ((int)Enum_TestClass_enum46u_Enum1.a == 0) retval -= 0x20; if ((int)Enum_TestClass_enum46u_Enum1.b == 1) retval -= 0x10; if ((int)Enum_TestClass_enum46u_Enum1.c == 2) retval -= 0x08; if ((uint)Enum_TestClass_enum46u_Enum1.d == 0xFFFFFFFD) retval -= 0x04; if ((uint)Enum_TestClass_enum46u_Enum1.e == 0xFFFFFFFE) retval -= 0x02; if ((uint)Enum_TestClass_enum46u_Enum1.f == 0xFFFFFFFF) retval -= 0x01; if (retval == 0) Log.Comment("PASS"); else { Log.Comment("FAIL\nretval == "); Log.Comment((retval).ToString()); } return retval; } public static bool testMethod() { return (Main_old() == 0); } }; public enum Enum_TestClass_enum47_Enum2 : byte { a = Enum_TestClass_enum47_Enum1.a, b, c, d, e, f }; public enum Enum_TestClass_enum47_Enum1 : int { a, b, c, d = (int)0x7FFFFFFD, e, f }; public class Enum_TestClass_enum47 { public static int retval = 0x3F; public static int Main_old() { if ((int)Enum_TestClass_enum47_Enum2.a == 0) retval -= 0x20; if ((int)Enum_TestClass_enum47_Enum2.b == 1) retval -= 0x10; if ((int)Enum_TestClass_enum47_Enum2.c == 2) retval -= 0x08; if ((int)Enum_TestClass_enum47_Enum2.d == 3) retval -= 0x04; if ((int)Enum_TestClass_enum47_Enum2.e == 4) retval -= 0x02; if ((int)Enum_TestClass_enum47_Enum2.f == 5) retval -= 0x01; if (retval == 0) Log.Comment("PASS"); else { Log.Comment("FAIL\nretval == "); Log.Comment((retval).ToString()); } return retval; } public static bool testMethod() { return (Main_old() == 0); } }; public enum Enum_TestClass_enum47u_Enum2 : sbyte { a = (sbyte)Enum_TestClass_enum47u_Enum1.a, b, c, d, e, f }; public enum Enum_TestClass_enum47u_Enum1 : int { a, b, c, d = 0x7FFFFFFD, e, f }; public class Enum_TestClass_enum47u { public static int retval = 0x3F; public static int Main_old() { if ((int)Enum_TestClass_enum47u_Enum2.a == 0) retval -= 0x20; if ((int)Enum_TestClass_enum47u_Enum2.b == 1) retval -= 0x10; if ((int)Enum_TestClass_enum47u_Enum2.c == 2) retval -= 0x08; if ((int)Enum_TestClass_enum47u_Enum2.d == 3) retval -= 0x04; if ((int)Enum_TestClass_enum47u_Enum2.e == 4) retval -= 0x02; if ((int)Enum_TestClass_enum47u_Enum2.f == 5) retval -= 0x01; if (retval == 0) Log.Comment("PASS"); else { Log.Comment("FAIL\nretval == "); Log.Comment((retval).ToString()); } return retval; } public static bool testMethod() { return (Main_old() == 0); } }; public enum Enum_TestClass_enum48_Enum2 : int { a = (int)Enum_TestClass_enum48_Enum1.a, b, c, d, e, f }; public enum Enum_TestClass_enum48_Enum1 : long { a, b, c, d = (long)0x7FFFFFFFFFFFFFFDL, e, f }; public class Enum_TestClass_enum48 { public static int retval = 0x3F; public static int Main_old() { if ((int)Enum_TestClass_enum48_Enum2.a == 0) retval -= 0x20; if ((int)Enum_TestClass_enum48_Enum2.b == 1) retval -= 0x10; if ((int)Enum_TestClass_enum48_Enum2.c == 2) retval -= 0x08; if ((int)Enum_TestClass_enum48_Enum2.d == 3) retval -= 0x04; if ((int)Enum_TestClass_enum48_Enum2.e == 4) retval -= 0x02; if ((int)Enum_TestClass_enum48_Enum2.f == 5) retval -= 0x01; if (retval == 0) Log.Comment("PASS"); else { Log.Comment("FAIL\nretval == "); Log.Comment((retval).ToString()); } return retval; } public static bool testMethod() { return (Main_old() == 0); } }; public enum Enum_TestClass_enum48u_Enum2 : int { a = (int)Enum_TestClass_enum48u_Enum1.a, b, c, d, e, f }; public enum Enum_TestClass_enum48u_Enum1 : ulong { a, b, c, d = 0xFFFFFFFFFFFFFFFDL, e, f }; public class Enum_TestClass_enum48u { public static int retval = 0x3F; public static int Main_old() { if ((ulong)Enum_TestClass_enum48u_Enum1.a == 0) retval -= 0x20; if ((ulong)Enum_TestClass_enum48u_Enum1.b == 1) retval -= 0x10; if ((ulong)Enum_TestClass_enum48u_Enum1.c == 2) retval -= 0x08; if ((ulong)Enum_TestClass_enum48u_Enum1.d == 0xFFFFFFFFFFFFFFFDL) retval -= 0x04; if ((ulong)Enum_TestClass_enum48u_Enum1.e == 0xFFFFFFFFFFFFFFFEL) retval -= 0x02; if ((ulong)Enum_TestClass_enum48u_Enum1.f == 0xFFFFFFFFFFFFFFFFL) retval -= 0x01; if (retval == 0) Log.Comment("PASS"); else Log.Comment("FAIL\nretval == " + retval.ToString()); return retval; } public static bool testMethod() { return (Main_old() == 0); } }; public enum Enum_TestClass_enum54_Enum1 { a, b, c, d, e, f }; public enum Enum_TestClass_enum54_Enum2 : byte { a, b, c, d, e, f }; public enum Enum_TestClass_enum54_Enum2sb : sbyte { a, b, c, d, e, f }; public enum Enum_TestClass_enum54_Enum3 : short { a, b, c, d, e, f }; public enum Enum_TestClass_enum54_Enum3us : ushort { a, b, c, d, e, f }; public enum Enum_TestClass_enum54_Enum4 : int { a, b, c, d, e, f }; public enum Enum_TestClass_enum54_Enum4ui : uint { a, b, c, d, e, f }; public enum Enum_TestClass_enum54_Enum5 : long { a, b, c, d, e, f }; public enum Enum_TestClass_enum54_Enum5ul : ulong { a, b, c, d, e, f }; public class Enum_TestClass_enum54 { public static int retval = 0x7FFFFFF; public static int Main_old() { Enum_TestClass_enum54_Enum1 e1 = Enum_TestClass_enum54_Enum1.a; e1++; e1++; e1++; e1--; e1--; e1--; e1++; e1--; e1--; e1++; e1++; e1++; e1++; e1++; e1++; e1++; if ((int)e1 == (int)Enum_TestClass_enum54_Enum1.f + 1) retval -= 0x01; e1--; e1--; e1--; e1--; e1--; e1--; if (e1 == Enum_TestClass_enum54_Enum1.a) retval -= 0x02; e1--; if ((int)e1 == (int)Enum_TestClass_enum54_Enum1.a - 1) retval -= 0x04; Enum_TestClass_enum54_Enum2 e2 = Enum_TestClass_enum54_Enum2.a; e2++; e2++; e2++; e2--; e2--; e2--; e2++; e2--; e2--; e2++; e2++; e2++; e2++; e2++; e2++; e2++; if ((int)e2 == (int)Enum_TestClass_enum54_Enum2.f + 1) retval -= 0x08; e2--; e2--; e2--; e2--; e2--; e2--; if (e2 == Enum_TestClass_enum54_Enum2.a) retval -= 0x10; e2--; if ((int)e2 == 255) //This has to be a manifest constant because byte is UNSIGNED retval -= 0x20; Enum_TestClass_enum54_Enum2sb e2sb = Enum_TestClass_enum54_Enum2sb.a; e2sb++; e2sb++; e2sb++; e2sb--; e2sb--; e2sb--; e2sb++; e2sb--; e2sb--; e2sb++; e2sb++; e2sb++; e2sb++; e2sb++; e2sb++; e2sb++; if ((int)e2sb == (int)Enum_TestClass_enum54_Enum2sb.f + 1) retval -= 0x8000; e2sb--; e2sb--; e2sb--; e2sb--; e2sb--; e2sb--; if (e2sb == Enum_TestClass_enum54_Enum2sb.a) retval -= 0x10000; e2sb--; if ((int)e2sb == -1) retval -= 0x20000; Enum_TestClass_enum54_Enum3 e3 = Enum_TestClass_enum54_Enum3.a; e3++; e3++; e3++; e3--; e3--; e3--; e3++; e3--; e3--; e3++; e3++; e3++; e3++; e3++; e3++; e3++; if ((int)e3 == (int)Enum_TestClass_enum54_Enum3.f + 1) retval -= 0x40; e3--; e3--; e3--; e3--; e3--; e3--; if (e3 == Enum_TestClass_enum54_Enum3.a) retval -= 0x80; e3--; if ((int)e3 == (int)Enum_TestClass_enum54_Enum3.a - 1) retval -= 0x100; Enum_TestClass_enum54_Enum3us e3us = Enum_TestClass_enum54_Enum3us.a; e3us++; e3us++; e3us++; e3us--; e3us--; e3us--; e3us++; e3us--; e3us--; e3us++; e3us++; e3us++; e3us++; e3us++; e3us++; e3us++; if ((int)e3us == (int)Enum_TestClass_enum54_Enum3us.f + 1) retval -= 0x40000; e3us--; e3us--; e3us--; e3us--; e3us--; e3us--; if (e3us == Enum_TestClass_enum54_Enum3us.a) retval -= 0x80000; e3us--; if ((int)e3us == 65535) retval -= 0x100000; Enum_TestClass_enum54_Enum4 e4 = Enum_TestClass_enum54_Enum4.a; e4++; e4++; e4++; e4--; e4--; e4--; e4++; e4--; e4--; e4++; e4++; e4++; e4++; e4++; e4++; e4++; if ((int)e4 == (int)Enum_TestClass_enum54_Enum4.f + 1) retval -= 0x200; e4--; e4--; e4--; e4--; e4--; e4--; if (e4 == Enum_TestClass_enum54_Enum4.a) retval -= 0x400; e4--; if ((int)e4 == (int)Enum_TestClass_enum54_Enum4.a - 1) retval -= 0x800; Enum_TestClass_enum54_Enum4ui e4ui = Enum_TestClass_enum54_Enum4ui.a; e4ui++; e4ui++; e4ui++; e4ui--; e4ui--; e4ui--; e4ui++; e4ui--; e4ui--; e4ui++; e4ui++; e4ui++; e4ui++; e4ui++; e4ui++; e4ui++; if ((int)e4ui == (int)Enum_TestClass_enum54_Enum4ui.f + 1) retval -= 0x200000; e4ui--; e4ui--; e4ui--; e4ui--; e4ui--; e4ui--; if (e4ui == Enum_TestClass_enum54_Enum4ui.a) retval -= 0x400000; e4ui--; if ((int)e4ui == (int)Enum_TestClass_enum54_Enum4ui.a - 1) retval -= 0x800000; Enum_TestClass_enum54_Enum5 e5 = Enum_TestClass_enum54_Enum5.a; e5++; e5++; e5++; e5--; e5--; e5--; e5++; e5--; e5--; e5++; e5++; e5++; e5++; e5++; e5++; e5++; if ((int)e5 == (int)Enum_TestClass_enum54_Enum5.f + 1) retval -= 0x01000; e5--; e5--; e5--; e5--; e5--; e5--; if (e5 == Enum_TestClass_enum54_Enum5.a) retval -= 0x02000; e5--; if ((int)e5 == (int)Enum_TestClass_enum54_Enum5.a - 1) retval -= 0x04000; Enum_TestClass_enum54_Enum5ul e5ul = Enum_TestClass_enum54_Enum5ul.a; e5ul++; e5ul++; e5ul++; e5ul--; e5ul--; e5ul--; e5ul++; e5ul--; e5ul--; e5ul++; e5ul++; e5ul++; e5ul++; e5ul++; e5ul++; e5ul++; if ((int)e5ul == (int)Enum_TestClass_enum54_Enum5ul.f + 1) retval -= 0x01000000; e5ul--; e5ul--; e5ul--; e5ul--; e5ul--; e5ul--; if (e5ul == Enum_TestClass_enum54_Enum5ul.a) retval -= 0x02000000; e5ul--; if ((int)e5ul == (int)Enum_TestClass_enum54_Enum5ul.a - 1) retval -= 0x04000000; if (retval == 0) Log.Comment("PASS"); else Log.Comment("FAIL, 0x{0:X} " + retval.ToString()); return retval; } public static bool testMethod() { return (Main_old() == 0); } }; public enum Enum_TestClass_enum55_Enum1 { a, b, c, d, e, f }; public enum Enum_TestClass_enum55_Enum2 : byte { a, b, c, d, e, f }; public enum Enum_TestClass_enum55_Enum2sb : sbyte { a, b, c, d, e, f }; public enum Enum_TestClass_enum55_Enum3 : short { a, b, c, d, e, f }; public enum Enum_TestClass_enum55_Enum3us : ushort { a, b, c, d, e, f }; public enum Enum_TestClass_enum55_Enum4 : int { a, b, c, d, e, f }; public enum Enum_TestClass_enum55_Enum4ui : uint { a, b, c, d, e, f }; public enum Enum_TestClass_enum55_Enum5 : long { a, b, c, d, e, f }; public enum Enum_TestClass_enum55_Enum5ul : ulong { a, b, c, d, e, f }; public class Enum_TestClass_enum55 { public static int retval = 0x7FFFFFF; public static int Main_old() { Enum_TestClass_enum55_Enum1 e1 = Enum_TestClass_enum55_Enum1.a; e1++; e1++; e1++; --e1; --e1; --e1; e1++; --e1; --e1; e1++; e1++; e1++; e1++; e1++; e1++; if ((int)e1-- == (int)Enum_TestClass_enum55_Enum1.f) retval -= 0x01; --e1; --e1; --e1; --e1; if (e1 == Enum_TestClass_enum55_Enum1.a) retval -= 0x02; --e1; if ((int)e1 == (int)Enum_TestClass_enum55_Enum1.a - 1) retval -= 0x04; Enum_TestClass_enum55_Enum2 e2 = Enum_TestClass_enum55_Enum2.a; e2++; e2++; e2++; --e2; --e2; --e2; e2++; --e2; --e2; e2++; e2++; e2++; e2++; e2++; e2++; e2++; if ((int)e2-- == (int)Enum_TestClass_enum55_Enum2.f + 1) retval -= 0x08; --e2; --e2; --e2; --e2; if (e2 == Enum_TestClass_enum55_Enum2.b) retval -= 0x10; --e2; --e2; if ((int)e2 == 255) //This has to be a manifest constant because byte is UNSIGNED retval -= 0x20; Enum_TestClass_enum55_Enum2sb e2sb = Enum_TestClass_enum55_Enum2sb.a; e2sb++; e2sb++; e2sb++; --e2sb; --e2sb; --e2sb; e2sb++; --e2sb; --e2sb; e2sb++; e2sb++; e2sb++; e2sb++; e2sb++; e2sb++; e2sb++; if ((int)e2sb-- == (int)Enum_TestClass_enum55_Enum2sb.f + 1) retval -= 0x8000; --e2sb; --e2sb; --e2sb; --e2sb; if (e2sb == Enum_TestClass_enum55_Enum2sb.b) retval -= 0x10000; --e2sb; --e2sb; if ((int)e2sb == -1) retval -= 0x20000; Enum_TestClass_enum55_Enum3 e3 = Enum_TestClass_enum55_Enum3.a; e3++; e3++; e3++; --e3; --e3; --e3; e3++; --e3; --e3; e3++; e3++; e3++; e3++; e3++; e3++; e3++; if ((int)e3 == (int)Enum_TestClass_enum55_Enum3.f + 1) retval -= 0x40; --e3; --e3; --e3; --e3; --e3; --e3; if (e3 == Enum_TestClass_enum55_Enum3.a) retval -= 0x80; --e3; if ((int)e3 == (int)Enum_TestClass_enum55_Enum3.a - 1) retval -= 0x100; Enum_TestClass_enum55_Enum3us e3us = Enum_TestClass_enum55_Enum3us.a; e3us++; e3us++; e3us++; --e3us; --e3us; --e3us; e3us++; --e3us; --e3us; e3us++; e3us++; e3us++; e3us++; e3us++; e3us++; e3us++; if ((int)e3us == (int)Enum_TestClass_enum55_Enum3us.f + 1) retval -= 0x40000; --e3us; --e3us; --e3us; --e3us; --e3us; --e3us; if (e3us == Enum_TestClass_enum55_Enum3us.a) retval -= 0x80000; --e3us; if ((int)e3us == 65535) retval -= 0x100000; Enum_TestClass_enum55_Enum4 e4 = Enum_TestClass_enum55_Enum4.a; e4++; e4++; e4++; --e4; --e4; --e4; e4++; --e4; --e4; e4++; e4++; e4++; e4++; e4++; e4++; e4++; if ((int)e4-- == (int)Enum_TestClass_enum55_Enum4.f + 1) retval -= 0x200; --e4; --e4; --e4; --e4; --e4; if (e4 == Enum_TestClass_enum55_Enum4.a) retval -= 0x400; --e4; if ((int)e4 == (int)Enum_TestClass_enum55_Enum4.a - 1) retval -= 0x800; Enum_TestClass_enum55_Enum4ui e4ui = Enum_TestClass_enum55_Enum4ui.a; e4ui++; e4ui++; e4ui++; --e4ui; --e4ui; --e4ui; e4ui++; --e4ui; --e4ui; e4ui++; e4ui++; e4ui++; e4ui++; e4ui++; e4ui++; e4ui++; if ((int)e4ui-- == (int)Enum_TestClass_enum55_Enum4ui.f + 1) retval -= 0x200000; --e4ui; --e4ui; --e4ui; --e4ui; --e4ui; if (e4ui == Enum_TestClass_enum55_Enum4ui.a) retval -= 0x400000; --e4ui; if ((int)e4ui == (int)Enum_TestClass_enum55_Enum4ui.a - 1) retval -= 0x800000; Enum_TestClass_enum55_Enum5 e5 = Enum_TestClass_enum55_Enum5.a; e5++; e5++; e5++; --e5; --e5; --e5; e5++; --e5; --e5; e5++; e5++; e5++; e5++; e5++; e5++; e5++; if ((int)e5-- == (int)Enum_TestClass_enum55_Enum5.f + 1) retval -= 0x1000; --e5; --e5; --e5; --e5; --e5; if (e5-- == Enum_TestClass_enum55_Enum5.a) retval -= 0x2000; --e5; if ((int)e5 == (int)Enum_TestClass_enum55_Enum5.a - 2) retval -= 0x4000; Enum_TestClass_enum55_Enum5ul e5ul = Enum_TestClass_enum55_Enum5ul.a; e5ul++; e5ul++; e5ul++; --e5ul; --e5ul; --e5ul; e5ul++; --e5ul; --e5ul; e5ul++; e5ul++; e5ul++; e5ul++; e5ul++; e5ul++; e5ul++; if ((int)e5ul-- == (int)Enum_TestClass_enum55_Enum5ul.f + 1) retval -= 0x1000000; --e5ul; --e5ul; --e5ul; --e5ul; --e5ul; if (e5ul-- == Enum_TestClass_enum55_Enum5ul.a) retval -= 0x2000000; --e5ul; if ((int)e5ul == (int)Enum_TestClass_enum55_Enum5ul.a - 2) retval -= 0x4000000; Log.Comment((retval).ToString()); if (retval == 0) Log.Comment("PASS"); else Log.Comment("FAIL"); return retval; } public static bool testMethod() { return (Main_old() == 0); } }; public enum Enum_TestClass_enum56_Enum1 { a, b, c, d, e, f }; public enum Enum_TestClass_enum56_Enum2 : byte { a, b, c, d, e, f }; public enum Enum_TestClass_enum56_Enum3 : short { a, b, c, d, e, f }; public enum Enum_TestClass_enum56_Enum4 : int { a, b, c, d, e, f }; public enum Enum_TestClass_enum56_Enum5 : long { a, b, c, d, e, f }; public enum Enum_TestClass_enum56_Enum2sb : sbyte { a, b, c, d, e, f }; public enum Enum_TestClass_enum56_Enum3us : ushort { a, b, c, d, e, f }; public enum Enum_TestClass_enum56_Enum4ui : uint { a, b, c, d, e, f }; public enum Enum_TestClass_enum56_Enum5ul : ulong { a, b, c, d, e, f }; public class Enum_TestClass_enum56 { public static int retval = 0x7FFFFFF; public static int Main_old() { Enum_TestClass_enum56_Enum1 e1 = Enum_TestClass_enum56_Enum1.a; ++e1; e1++; ++e1; --e1; --e1; --e1; e1++; --e1; --e1; ++e1; e1++; ++e1; ++e1; ++e1; ++e1; ++e1; if ((int)e1 == (int)Enum_TestClass_enum56_Enum1.f + 1) retval -= 0x01; --e1; --e1; --e1; --e1; if (e1 == Enum_TestClass_enum56_Enum1.c) retval -= 0x02; --e1; --e1; --e1; if ((int)e1 == (int)Enum_TestClass_enum56_Enum1.a - 1) retval -= 0x04; Enum_TestClass_enum56_Enum2 e2 = Enum_TestClass_enum56_Enum2.a; ++e2; e2++; ++e2; --e2; --e2; --e2; e2++; --e2; --e2; ++e2; e2++; ++e2; ++e2; ++e2; ++e2; ++e2; if ((int)e2 == (int)Enum_TestClass_enum56_Enum2.f + 1) retval -= 0x08; --e2; --e2; --e2; --e2; if (e2 == Enum_TestClass_enum56_Enum2.c) retval -= 0x10; --e2; --e2; --e2; if ((int)e2 == 255) //This has to be a manifest constant because byte is UNSIGNED retval -= 0x20; Enum_TestClass_enum56_Enum3 e3 = Enum_TestClass_enum56_Enum3.a; ++e3; e3++; ++e3; --e3; --e3; --e3; e3++; --e3; --e3; ++e3; e3++; ++e3; ++e3; ++e3; ++e3; ++e3; if ((int)e3 == (int)Enum_TestClass_enum56_Enum3.f + 1) retval -= 0x40; --e3; --e3; --e3; --e3; if (e3 == Enum_TestClass_enum56_Enum3.c) retval -= 0x80; --e3; --e3; --e3; if ((int)e3 == (int)Enum_TestClass_enum56_Enum3.a - 1) retval -= 0x100; Enum_TestClass_enum56_Enum4 e4 = Enum_TestClass_enum56_Enum4.a; ++e4; e4++; ++e4; --e4; --e4; --e4; e4++; --e4; --e4; ++e4; e4++; ++e4; ++e4; ++e4; ++e4; ++e4; if ((int)e4 == (int)Enum_TestClass_enum56_Enum4.f + 1) retval -= 0x200; --e4; --e4; --e4; --e4; if (e4 == Enum_TestClass_enum56_Enum4.c) retval -= 0x400; --e4; --e4; --e4; if ((int)e4 == (int)Enum_TestClass_enum56_Enum4.a - 1) retval -= 0x800; Enum_TestClass_enum56_Enum5 e5 = Enum_TestClass_enum56_Enum5.a; ++e5; e5++; ++e5; --e5; --e5; --e5; e5++; --e5; --e5; ++e5; e5++; ++e5; ++e5; ++e5; ++e5; ++e5; if ((int)e5 == (int)Enum_TestClass_enum56_Enum5.f + 1) retval -= 0x1000; --e5; --e5; --e5; --e5; if (e5 == Enum_TestClass_enum56_Enum5.c) retval -= 0x2000; --e5; --e5; --e5; if ((int)e5 == (int)Enum_TestClass_enum56_Enum5.a - 1) retval -= 0x4000; Enum_TestClass_enum56_Enum2sb e2sb = Enum_TestClass_enum56_Enum2sb.a; ++e2sb; e2sb++; ++e2sb; --e2sb; --e2sb; --e2sb; e2sb++; --e2sb; --e2sb; ++e2sb; e2sb++; ++e2sb; ++e2sb; ++e2sb; ++e2sb; ++e2sb; if ((int)e2sb == (int)Enum_TestClass_enum56_Enum2sb.f + 1) retval -= 0x8000; --e2sb; --e2sb; --e2sb; --e2sb; if (e2sb == Enum_TestClass_enum56_Enum2sb.c) retval -= 0x10000; --e2sb; --e2sb; --e2sb; if ((int)e2sb == -1) //This has to be a manifest constant because byte is UNSIGNED retval -= 0x20000; Enum_TestClass_enum56_Enum3us e3us = Enum_TestClass_enum56_Enum3us.a; ++e3us; e3us++; ++e3us; --e3us; --e3us; --e3us; e3us++; --e3us; --e3us; ++e3us; e3us++; ++e3us; ++e3us; ++e3us; ++e3us; ++e3us; if ((int)e3us == (int)Enum_TestClass_enum56_Enum3us.f + 1) retval -= 0x40000; --e3us; --e3us; --e3us; --e3us; if (e3us == Enum_TestClass_enum56_Enum3us.c) retval -= 0x80000; --e3us; --e3us; --e3us; if ((int)e3us == 65535) retval -= 0x100000; Enum_TestClass_enum56_Enum4ui e4ui = Enum_TestClass_enum56_Enum4ui.a; ++e4ui; e4ui++; ++e4ui; --e4ui; --e4ui; --e4ui; e4ui++; --e4ui; --e4ui; ++e4ui; e4ui++; ++e4ui; ++e4ui; ++e4ui; ++e4ui; ++e4ui; if ((int)e4ui == (int)Enum_TestClass_enum56_Enum4ui.f + 1) retval -= 0x200000; --e4ui; --e4ui; --e4ui; --e4ui; if (e4ui == Enum_TestClass_enum56_Enum4ui.c) retval -= 0x400000; --e4ui; --e4ui; --e4ui; if ((int)e4ui == (int)Enum_TestClass_enum56_Enum4ui.a - 1) retval -= 0x800000; Enum_TestClass_enum56_Enum5ul e5ul = Enum_TestClass_enum56_Enum5ul.a; ++e5ul; e5ul++; ++e5ul; --e5ul; --e5ul; --e5ul; e5ul++; --e5ul; --e5ul; ++e5ul; e5ul++; ++e5ul; ++e5ul; ++e5ul; ++e5ul; ++e5ul; if ((int)e5ul == (int)Enum_TestClass_enum56_Enum5ul.f + 1) retval -= 0x1000000; --e5ul; --e5ul; --e5ul; --e5ul; if (e5ul == Enum_TestClass_enum56_Enum5ul.c) retval -= 0x2000000; --e5ul; --e5ul; --e5ul; if ((int)e5ul == (int)Enum_TestClass_enum56_Enum5ul.a - 1) retval -= 0x4000000; Log.Comment((retval).ToString()); if (retval == 0) Log.Comment("PASS"); else Log.Comment("FAIL"); return retval; } public static bool testMethod() { return (Main_old() == 0); } }; public enum Enum_TestClass_enum57_Enum1 { a, b, c, d, e, f }; public enum Enum_TestClass_enum57_Enum2 : byte { a, b, c, d, e, f }; public enum Enum_TestClass_enum57_Enum3 : short { a, b, c, d, e, f }; public enum Enum_TestClass_enum57_Enum4 : int { a, b, c, d, e, f }; public enum Enum_TestClass_enum57_Enum5 : long { a, b, c, d, e, f }; public enum Enum_TestClass_enum57_Enum2sb : sbyte { a, b, c, d, e, f }; public enum Enum_TestClass_enum57_Enum3us : ushort { a, b, c, d, e, f }; public enum Enum_TestClass_enum57_Enum4ui : uint { a, b, c, d, e, f }; public enum Enum_TestClass_enum57_Enum5ul : ulong { a, b, c, d, e, f }; public class Enum_TestClass_enum57 { public static int retval = 0x7FFFFFF; public static int Main_old() { Enum_TestClass_enum57_Enum1 e1 = Enum_TestClass_enum57_Enum1.a; ++e1; e1++; ++e1; e1--; e1--; e1--; e1++; e1--; e1--; ++e1; e1++; ++e1; ++e1; ++e1; e1++; ++e1; if ((int)e1-- == (int)Enum_TestClass_enum57_Enum1.f + 1) retval -= 0x01; e1--; e1--; e1--; if (e1++ == Enum_TestClass_enum57_Enum1.c) retval -= 0x02; e1--; e1--; e1--; e1--; if ((int)e1 == (int)Enum_TestClass_enum57_Enum1.a - 1) retval -= 0x04; Enum_TestClass_enum57_Enum2 e2 = Enum_TestClass_enum57_Enum2.a; ++e2; e2++; ++e2; e2--; e2--; e2--; e2++; e2--; e2--; ++e2; e2++; ++e2; ++e2; ++e2; e2++; ++e2; if ((int)e2-- == (int)Enum_TestClass_enum57_Enum1.f + 1) retval -= 0x08; e2--; e2--; e2--; if (e2++ == Enum_TestClass_enum57_Enum2.c) retval -= 0x10; e2--; e2--; e2--; e2--; if ((int)e2 == 255) //This has to be a manifest constant because byte is UNSIGNED retval -= 0x20; Enum_TestClass_enum57_Enum3 e3 = Enum_TestClass_enum57_Enum3.a; ++e3; e3++; ++e3; e3--; e3--; e3--; e3++; e3--; e3--; ++e3; e3++; ++e3; ++e3; ++e3; e3++; ++e3; if ((int)e3-- == (int)Enum_TestClass_enum57_Enum3.f + 1) retval -= 0x40; e3--; e3--; e3--; if (e3++ == Enum_TestClass_enum57_Enum3.c) retval -= 0x80; e3--; e3--; e3--; e3--; if ((int)e3 == (int)Enum_TestClass_enum57_Enum3.a - 1) retval -= 0x100; Enum_TestClass_enum57_Enum4 e4 = Enum_TestClass_enum57_Enum4.a; ++e4; e4++; ++e4; e4--; e4--; e4--; e4++; e4--; e4--; ++e4; e4++; ++e4; ++e4; ++e4; e4++; ++e4; if ((int)e4-- == (int)Enum_TestClass_enum57_Enum4.f + 1) retval -= 0x200; e4--; e4--; e4--; if (e4++ == Enum_TestClass_enum57_Enum4.c) retval -= 0x400; e4--; e4--; e4--; e4--; if ((int)e4 == (int)Enum_TestClass_enum57_Enum4.a - 1) retval -= 0x800; Enum_TestClass_enum57_Enum5 e5 = Enum_TestClass_enum57_Enum5.a; ++e5; e5++; ++e5; e5--; e5--; e5--; e5++; e5--; e5--; ++e5; e5++; ++e5; ++e5; ++e5; e5++; ++e5; if ((int)e5-- == (int)Enum_TestClass_enum57_Enum5.f + 1) retval -= 0x1000; e5--; e5--; e5--; if (e5++ == Enum_TestClass_enum57_Enum5.c) retval -= 0x2000; e5--; e5--; e5--; e5--; if ((int)e5 == (int)Enum_TestClass_enum57_Enum5.a - 1) retval -= 0x4000; Enum_TestClass_enum57_Enum2sb e2sb = Enum_TestClass_enum57_Enum2sb.a; ++e2sb; e2sb++; ++e2sb; e2sb--; e2sb--; e2sb--; e2sb++; e2sb--; e2sb--; ++e2sb; e2sb++; ++e2sb; ++e2sb; ++e2sb; e2sb++; ++e2sb; if ((int)e2sb-- == (int)Enum_TestClass_enum57_Enum1.f + 1) retval -= 0x8000; e2sb--; e2sb--; e2sb--; if (e2sb++ == Enum_TestClass_enum57_Enum2sb.c) retval -= 0x10000; e2sb--; e2sb--; e2sb--; e2sb--; if ((int)e2sb == -1) retval -= 0x20000; Enum_TestClass_enum57_Enum3us e3us = Enum_TestClass_enum57_Enum3us.a; ++e3us; e3us++; ++e3us; e3us--; e3us--; e3us--; e3us++; e3us--; e3us--; ++e3us; e3us++; ++e3us; ++e3us; ++e3us; e3us++; ++e3us; if ((int)e3us-- == (int)Enum_TestClass_enum57_Enum3us.f + 1) retval -= 0x40000; e3us--; e3us--; e3us--; if (e3us++ == Enum_TestClass_enum57_Enum3us.c) retval -= 0x80000; e3us--; e3us--; e3us--; e3us--; if ((int)e3us == 65535) retval -= 0x100000; Enum_TestClass_enum57_Enum4ui e4ui = Enum_TestClass_enum57_Enum4ui.a; ++e4ui; e4ui++; ++e4ui; e4ui--; e4ui--; e4ui--; e4ui++; e4ui--; e4ui--; ++e4ui; e4ui++; ++e4ui; ++e4ui; ++e4ui; e4ui++; ++e4ui; if ((int)e4ui-- == (int)Enum_TestClass_enum57_Enum4ui.f + 1) retval -= 0x200000; e4ui--; e4ui--; e4ui--; if (e4ui++ == Enum_TestClass_enum57_Enum4ui.c) retval -= 0x400000; e4ui--; e4ui--; e4ui--; e4ui--; if ((int)e4ui == (int)Enum_TestClass_enum57_Enum4ui.a - 1) retval -= 0x800000; Enum_TestClass_enum57_Enum5ul e5ul = Enum_TestClass_enum57_Enum5ul.a; ++e5ul; e5ul++; ++e5ul; e5ul--; e5ul--; e5ul--; e5ul++; e5ul--; e5ul--; ++e5ul; e5ul++; ++e5ul; ++e5ul; ++e5ul; e5ul++; ++e5ul; if ((int)e5ul-- == (int)Enum_TestClass_enum57_Enum5ul.f + 1) retval -= 0x1000000; e5ul--; e5ul--; e5ul--; if (e5ul++ == Enum_TestClass_enum57_Enum5ul.c) retval -= 0x2000000; e5ul--; e5ul--; e5ul--; e5ul--; if ((int)e5ul == (int)Enum_TestClass_enum57_Enum5ul.a - 1) retval -= 0x4000000; if (retval == 0) Log.Comment("PASS"); else Log.Comment("FAIL, 0x{0:X} " + retval.ToString()); return retval; } public static bool testMethod() { return (Main_old() == 0); } }; public enum Enum_TestClass_enum58_Enum1 { a = 0x01, b = 0x02, c = 0x04, d = 0x08, e = 0x10, f = 0x20 }; public enum Enum_TestClass_enum58_Enum2 : byte { a = Enum_TestClass_enum58_Enum1.a, b = Enum_TestClass_enum58_Enum1.b, c = Enum_TestClass_enum58_Enum1.c, d = Enum_TestClass_enum58_Enum1.d, e = Enum_TestClass_enum58_Enum1.e, f = Enum_TestClass_enum58_Enum1.f }; public enum Enum_TestClass_enum58_Enum3 : short { a = Enum_TestClass_enum58_Enum1.a, b = Enum_TestClass_enum58_Enum1.b, c = Enum_TestClass_enum58_Enum1.c, d = Enum_TestClass_enum58_Enum1.d, e = Enum_TestClass_enum58_Enum1.e, f = Enum_TestClass_enum58_Enum1.f }; public enum Enum_TestClass_enum58_Enum4 : int { a = Enum_TestClass_enum58_Enum1.a, b = Enum_TestClass_enum58_Enum1.b, c = Enum_TestClass_enum58_Enum1.c, d = Enum_TestClass_enum58_Enum1.d, e = Enum_TestClass_enum58_Enum1.e, f = Enum_TestClass_enum58_Enum1.f }; public enum Enum_TestClass_enum58_Enum5 : long { a = Enum_TestClass_enum58_Enum1.a, b = Enum_TestClass_enum58_Enum1.b, c = Enum_TestClass_enum58_Enum1.c, d = Enum_TestClass_enum58_Enum1.d, e = Enum_TestClass_enum58_Enum1.e, f = Enum_TestClass_enum58_Enum1.f }; public enum Enum_TestClass_enum58_Enum2sb : sbyte { a = Enum_TestClass_enum58_Enum1.a, b = Enum_TestClass_enum58_Enum1.b, c = Enum_TestClass_enum58_Enum1.c, d = Enum_TestClass_enum58_Enum1.d, e = Enum_TestClass_enum58_Enum1.e, f = Enum_TestClass_enum58_Enum1.f }; public enum Enum_TestClass_enum58_Enum3us : ushort { a = Enum_TestClass_enum58_Enum1.a, b = Enum_TestClass_enum58_Enum1.b, c = Enum_TestClass_enum58_Enum1.c, d = Enum_TestClass_enum58_Enum1.d, e = Enum_TestClass_enum58_Enum1.e, f = Enum_TestClass_enum58_Enum1.f }; public enum Enum_TestClass_enum58_Enum4ui : uint { a = Enum_TestClass_enum58_Enum1.a, b = Enum_TestClass_enum58_Enum1.b, c = Enum_TestClass_enum58_Enum1.c, d = Enum_TestClass_enum58_Enum1.d, e = Enum_TestClass_enum58_Enum1.e, f = Enum_TestClass_enum58_Enum1.f }; public enum Enum_TestClass_enum58_Enum5ul : ulong { a = Enum_TestClass_enum58_Enum1.a, b = Enum_TestClass_enum58_Enum1.b, c = Enum_TestClass_enum58_Enum1.c, d = Enum_TestClass_enum58_Enum1.d, e = Enum_TestClass_enum58_Enum1.e, f = Enum_TestClass_enum58_Enum1.f }; public class Enum_TestClass_enum58 { public static int retval = 0x1FF; public static int Main_old() { Enum_TestClass_enum58_Enum1 e1 = Enum_TestClass_enum58_Enum1.a; e1 = e1 ^ Enum_TestClass_enum58_Enum1.a; e1 ^= Enum_TestClass_enum58_Enum1.b; e1 = e1 | Enum_TestClass_enum58_Enum1.f; e1 |= Enum_TestClass_enum58_Enum1.e; e1 = e1 & Enum_TestClass_enum58_Enum1.b; e1 &= ~Enum_TestClass_enum58_Enum1.b; if ((int)e1 == 0) retval -= 0x001; Enum_TestClass_enum58_Enum2 e2 = Enum_TestClass_enum58_Enum2.a; e2 = e2 ^ Enum_TestClass_enum58_Enum2.a; e2 ^= Enum_TestClass_enum58_Enum2.b; e2 = e2 | Enum_TestClass_enum58_Enum2.f; e2 |= Enum_TestClass_enum58_Enum2.e; e2 = e2 & Enum_TestClass_enum58_Enum2.b; e2 &= ~Enum_TestClass_enum58_Enum2.b; if ((int)e2 == 0) retval -= 0x002; Enum_TestClass_enum58_Enum2sb e2sb = Enum_TestClass_enum58_Enum2sb.a; e2sb = e2sb ^ Enum_TestClass_enum58_Enum2sb.a; e2sb ^= Enum_TestClass_enum58_Enum2sb.b; e2sb = e2sb | Enum_TestClass_enum58_Enum2sb.f; e2sb |= Enum_TestClass_enum58_Enum2sb.e; e2sb = e2sb & Enum_TestClass_enum58_Enum2sb.b; e2sb &= ~Enum_TestClass_enum58_Enum2sb.b; if ((int)e2sb == 0) retval -= 0x004; Enum_TestClass_enum58_Enum3 e3 = Enum_TestClass_enum58_Enum3.a; e3 = e3 ^ Enum_TestClass_enum58_Enum3.a; e3 ^= Enum_TestClass_enum58_Enum3.b; e3 = e3 | Enum_TestClass_enum58_Enum3.f; e3 |= Enum_TestClass_enum58_Enum3.e; e3 = e3 & Enum_TestClass_enum58_Enum3.b; e3 &= ~Enum_TestClass_enum58_Enum3.b; if ((int)e3 == 0) retval -= 0x008; Enum_TestClass_enum58_Enum3us e3us = Enum_TestClass_enum58_Enum3us.a; e3us = e3us ^ Enum_TestClass_enum58_Enum3us.a; e3us ^= Enum_TestClass_enum58_Enum3us.b; e3us = e3us | Enum_TestClass_enum58_Enum3us.f; e3us |= Enum_TestClass_enum58_Enum3us.e; e3us = e3us & Enum_TestClass_enum58_Enum3us.b; e3us &= ~Enum_TestClass_enum58_Enum3us.b; if ((int)e3us == 0) retval -= 0x010; Enum_TestClass_enum58_Enum4 e4 = Enum_TestClass_enum58_Enum4.a; e4 = e4 ^ Enum_TestClass_enum58_Enum4.a; e4 ^= Enum_TestClass_enum58_Enum4.b; e4 = e4 | Enum_TestClass_enum58_Enum4.f; e4 |= Enum_TestClass_enum58_Enum4.e; e4 = e4 & Enum_TestClass_enum58_Enum4.b; e4 &= ~Enum_TestClass_enum58_Enum4.b; if ((int)e4 == 0) retval -= 0x020; Enum_TestClass_enum58_Enum4ui e4ui = Enum_TestClass_enum58_Enum4ui.a; e4ui = e4ui ^ Enum_TestClass_enum58_Enum4ui.a; e4ui ^= Enum_TestClass_enum58_Enum4ui.b; e4ui = e4ui | Enum_TestClass_enum58_Enum4ui.f; e4ui |= Enum_TestClass_enum58_Enum4ui.e; e4ui = e4ui & Enum_TestClass_enum58_Enum4ui.b; e4ui &= ~Enum_TestClass_enum58_Enum4ui.b; if ((int)e4ui == 0) retval -= 0x040; Enum_TestClass_enum58_Enum5 e5 = Enum_TestClass_enum58_Enum5.a; e5 = e5 ^ Enum_TestClass_enum58_Enum5.a; e5 ^= Enum_TestClass_enum58_Enum5.b; e5 = e5 | Enum_TestClass_enum58_Enum5.f; e5 |= Enum_TestClass_enum58_Enum5.e; e5 = e5 & Enum_TestClass_enum58_Enum5.b; e5 &= ~Enum_TestClass_enum58_Enum5.b; if ((int)e5 == 0) retval -= 0x080; Enum_TestClass_enum58_Enum5ul e5ul = Enum_TestClass_enum58_Enum5ul.a; e5ul = e5ul ^ Enum_TestClass_enum58_Enum5ul.a; e5ul ^= Enum_TestClass_enum58_Enum5ul.b; e5ul = e5ul | Enum_TestClass_enum58_Enum5ul.f; e5ul |= Enum_TestClass_enum58_Enum5ul.e; e5ul = e5ul & Enum_TestClass_enum58_Enum5ul.b; e5ul &= ~Enum_TestClass_enum58_Enum5ul.b; if ((int)e5ul == 0) retval -= 0x100; if (0 == retval) Log.Comment ("PASS"); else Log.Comment ("FAIL"); return retval; } public static bool testMethod() { return (Main_old() == 0); } }; public enum Enum_TestClass_enum62_E { Type1 = 100, Type2, Type3 } public class Enum_TestClass_enum62 { public static int Main_old() { Enum_TestClass_enum62_E[] tt = new Enum_TestClass_enum62_E[2]; tt[0] = Enum_TestClass_enum62_E.Type1; tt[1] = Enum_TestClass_enum62_E.Type1; Log.Comment(tt[0].ToString()); Log.Comment(tt[1].ToString()); int nInt = (int)tt[1]; Log.Comment(nInt.ToString()); int i = (int)tt[0] + (int)tt[1] + nInt - 300; if (0 == i) Log.Comment("PASS"); else Log.Comment("FAIL"); return i; } public static bool testMethod() { return (Main_old() == 0); } } public class Enum_TestClass_enum63 { public enum e1 { one = 1, two = 2, three = 3 }; public static int Main_old() { int retval = 1; e1 v_e1 = e1.two; e1 v = e1.three; Log.Comment("v_e1 == " + ((int)v_e1).ToString() + ", v == " + ((int)v).ToString()); if (v_e1 < v) retval = 0; if (0 == retval) Log.Comment("PASS"); else Log.Comment("FAIL"); return retval; } public static bool testMethod() { return (Main_old() == 0); } }; public class Enum_TestClass_enum64 { public enum e1 { one = 1, two = 2, three = 3 }; public static int Main_old() { int retval = 1; e1 v_e1 = e1.three; e1 v = e1.two; Log.Comment("v_e1 == " + ((int)v_e1).ToString() + ", v == " + ((int)v).ToString()); if (v_e1 > v) retval = 0; if (0 == retval) Log.Comment("PASS"); else Log.Comment("FAIL"); return retval; } public static bool testMethod() { return (Main_old() == 0); } }; public class Enum_TestClass_enum65 { public enum e1 { one = 1, two = 2, three = 3 }; public static int Main_old() { int retval = 7; e1 v_e1 = e1.three; e1 v = e1.two; Log.Comment("v_e1 == " + ((int)v_e1).ToString() + ", v == " + ((int)v).ToString()); if (v_e1 >= v) retval -= 1; v_e1 = e1.three; v = e1.three; Log.Comment("v_e1 == " + ((int)v_e1).ToString() + ", v == " + ((int)v).ToString()); if (v_e1 >= v) retval -= 2; if (v_e1 == v) retval -= 4; if (0 == retval) Log.Comment("PASS"); else Log.Comment("FAIL"); return retval; } public static bool testMethod() { return (Main_old() == 0); } }; public class Enum_TestClass_enum66 { public enum e1 { one = 1, two = 2, three = 3 }; public static int Main_old() { int retval = 7; e1 v_e1 = e1.two; e1 v = e1.three; Log.Comment("v_e1 == " + ((int)v_e1).ToString() + ", v == " + ((int)v).ToString()); if (v_e1 <= v) retval -= 1; if (v_e1 != v) retval -= 2; v_e1 = e1.three; v = e1.three; Log.Comment("v_e1 == " + ((int)v_e1).ToString() + ", v == " + ((int)v).ToString()); if (v_e1 <= v) retval -= 4; if (0 == retval) Log.Comment("PASS"); else Log.Comment("FAIL"); return retval; } public static bool testMethod() { return (Main_old() == 0); } }; public class Enum_TestClass_enum67 { public enum e1 { one = 1, two = 2, three = 3 }; public static int Main_old() { int retval = 1; if (e1.two < e1.three) retval = 0; if (0 == retval) Log.Comment("PASS"); else Log.Comment("FAIL"); return retval; } public static bool testMethod() { return (Main_old() == 0); } }; public class Enum_TestClass_enum68 { public enum e1 { one = 1, two = 2, three = 3 }; public static int Main_old() { int retval = 1; if (e1.three > e1.two) retval = 0; if (0 == retval) Log.Comment("PASS"); else Log.Comment("FAIL"); return retval; } public static bool testMethod() { return (Main_old() == 0); } }; public class Enum_TestClass_enum69 { public enum e1 { one = 1, two = 2, three = 3 }; public static int Main_old() { // check ordering of values with >= operator if (e1.one >= e1.two || e1.one >= e1.three || e1.two >= e1.three ) { Log.Comment("FAIL"); return -1; } Log.Comment("PASS"); return 0; } public static bool testMethod() { return (Main_old() == 0); } }; public class Enum_TestClass_enum70 { public enum e1 { one = 1, two = 2, three = 3 }; public static int Main_old() { // check ordering of values with <= operator if( e1.three <= e1.two || e1.three <= e1.one || e1.two <= e1.one ) { Log.Comment("FAIL"); return -1; } Log.Comment("PASS"); return 0; } public static bool testMethod() { return (Main_old() == 0); } }; public class Enum_TestClass_enum71 { public enum e1 { one = 1, two = 2, three = 3 }; public static int Main_old() { int retval = 1; e1 v_e1 = e1.two; e1 v = e1.three; string s1 = v_e1.ToString(); string s2 = v.ToString(); Log.Comment("v_e1 == " + s1.ToString() + ", v == " + s2.ToString()); if (s1.Equals("two") && s2.Equals("three")) retval = 0; if (0 == retval) Log.Comment("PASS"); else Log.Comment("FAIL"); return retval; } public static bool testMethod() { return (Main_old() == 0); } }; public class Enum_TestClass_enum72 { public enum e1 { zero, one = 1, two = 2, three = 3 }; public static int Main_old() { int retval = 0x3F; e1 v_e1 = e1.two; e1 v = e1.one; if ((int)(v_e1 & v) == 0) retval -= 1; if ((int)(e1.three & v) == 1) retval -= 2; if ((int)(e1.three & e1.two) == 2) retval -= 4; if ((v_e1 & v) == e1.zero) retval -= 8; if ((e1.three & v) == e1.one) retval -= 0x10; if ((e1.three & e1.two) == e1.two) retval -= 0x20; if (0 == retval) Log.Comment("PASS"); else Log.Comment("FAIL"); return retval; } public static bool testMethod() { return (Main_old() == 0); } }; public class Enum_TestClass_enum73 { public enum e1 { zero, one = 1, two = 2, three = 3 }; public static int Main_old() { int retval = 0x3F; e1 v_e1 = e1.two; e1 v = e1.one; if ((int)(v_e1 | v) == 3) retval -= 1; if ((int)(e1.three | v) == 3) retval -= 2; if ((int)(e1.three | e1.two) == 3) retval -= 4; if ((v_e1 | v) == e1.three) retval -= 8; if ((e1.three | v) == e1.three) retval -= 0x10; if ((e1.three | e1.two) == e1.three) retval -= 0x20; if (0 == retval) Log.Comment("PASS"); else Log.Comment("FAIL"); return retval; } public static bool testMethod() { return (Main_old() == 0); } }; public class Enum_TestClass_enum74 { public enum e1 { zero, one = 1, two = 2, three = 3 }; public static int Main_old() { int retval = 0x3F; e1 v_e1 = e1.two; e1 v = e1.one; if ((int)(v_e1 ^ v) == 3) retval -= 1; if ((int)(e1.three ^ v) == 2) retval -= 2; if ((int)(e1.three ^ e1.two) == 1) retval -= 4; if ((v_e1 ^ v) == e1.three) retval -= 8; if ((e1.three ^ v) == e1.two) retval -= 0x10; if ((e1.three ^ e1.two) == e1.one) retval -= 0x20; if (0 == retval) Log.Comment("PASS"); else Log.Comment("FAIL"); return retval; } public static bool testMethod() { return (Main_old() == 0); } }; public class Enum_TestClass_enum75 { public enum e1 { zero, one = 1, two = 2, three = 3 }; public static int Main_old() { int retval = 7; e1 v_e1 = e1.two; if ((int)(~v_e1) == -3) retval -= 1; if ((int)(~e1.three) == -4) retval -= 2; if ((~(e1.one | e1.two) & e1.three) == e1.zero) retval -= 4; if (0 == retval) Log.Comment("PASS"); else Log.Comment("FAIL"); return retval; } public static bool testMethod() { return (Main_old() == 0); } }; public class Enum_TestClass_enum77 { public enum e1 { zero, one = 1, two = 2, three = 3 }; public static int Main_old() { int retval = 0x3F; e1 v_e1 = e1.two; e1 v = e1.one; if ((v + (int)v_e1) == e1.three) retval -= 1; if ((e1.three - e1.two) == 1) retval -= 2; if ((1 + e1.two) == e1.three) retval -= 4; if ((e1.one + 2) == e1.three) retval -= 8; if ((1 + v_e1) == e1.three) retval -= 0x10; if ((v + 2) == e1.three) retval -= 0x20; if (0 == retval) Log.Comment("PASS"); else Log.Comment("FAIL"); return retval; } public static bool testMethod() { return (Main_old() == 0); } }; public class Enum_TestClass_enum78 { public static int Main_old(String[] s) { Enum_TestClass_enum78_Enum f; try { object[] v = new object[1]; v[0] = Enum_TestClass_enum78_Enum.Second; f = (Enum_TestClass_enum78_Enum)v[0]; } catch (System.Exception e) { Log.Comment("Caught System.Exception: Failed"); Log.Comment(e.ToString()); return 1; } Log.Comment("No System.Exception: Passed"); return 0; } public static bool testMethod() { return (Main_old(null) == 0); } } public enum Enum_TestClass_enum78_Enum { First = 1, Second = -1, Third = -2 } public class Enum_TestClass_enum83 { public enum Enum_TestClass_enum83_Enum1 { a, b, c, }; public enum Enum_TestClass_enum83_Enum2 : int { a, b, c, }; public enum Enum_TestClass_enum83_Enum3 : uint { a, b, c, }; public enum Enum_TestClass_enum83_Enum4 : byte { a, b, c, }; public enum Enum_TestClass_enum83_Enum5 : sbyte { a, b, c, }; public enum Enum_TestClass_enum83_Enum6 : short { a, b, c, }; public enum Enum_TestClass_enum83_Enum7 : ushort { a, b, c, }; public enum Enum_TestClass_enum83_Enum8 : long { a, b, c, }; public enum Enum_TestClass_enum83_Enum9 : ulong { a, b, c, }; public static int Main_old() { return 0; } public static bool testMethod() { return (Main_old() == 0); } }; public class Enum_TestClass_enum86_Base { public enum Enum_TestClass_enum86_Enum1_1 { a = -1, b = -2, c = -3, }; public class Enum_TestClass_enum86_Enum1_2 { } public struct Enum_TestClass_enum86_Enum1_3 { } protected enum Enum_TestClass_enum86_Enum3 : uint { a = 1, b = 6, c = 7, }; internal enum Enum_TestClass_enum86_Enum4 : byte { a = 2, b = 5, c = 8 }; private enum Enum_TestClass_enum86_Enum5 : sbyte { a = 3, b = 4, c = 9 }; protected bool CheckE5() { return ((int)Enum_TestClass_enum86_Enum5.b == 4); } } public class Enum_TestClass_enum86 : Enum_TestClass_enum86_Base { new enum Enum_TestClass_enum86_Enum1_1 { a, b = 10, c, }; new enum Enum_TestClass_enum86_Enum1_2 { a, b = 11, c, }; new enum Enum_TestClass_enum86_Enum1_3 { a, b = 12, c, }; public static int Main_old() { int retval = 0xFF; Enum_TestClass_enum86_Base b = new Enum_TestClass_enum86_Base(); Enum_TestClass_enum86 d = new Enum_TestClass_enum86(); if ((int)Enum_TestClass_enum86_Base.Enum_TestClass_enum86_Enum1_1.b == -2) retval -= 0x01; if ((int)Enum_TestClass_enum86.Enum_TestClass_enum86_Enum1_1.b == 10) retval -= 0x02; if ((int)Enum_TestClass_enum86.Enum_TestClass_enum86_Enum1_2.b == 11) retval -= 0x04; if ((int)Enum_TestClass_enum86.Enum_TestClass_enum86_Enum1_3.b == 12) retval -= 0x08; if ((int)Enum_TestClass_enum86_Enum3.b == 6) retval -= 0x10; if ((int)Enum_TestClass_enum86_Enum4.b == 5) retval -= 0x20; if ((int)Enum_TestClass_enum86_Base.Enum_TestClass_enum86_Enum4.b == 5) retval -= 0x40; if (d.CheckE5()) retval -= 0x80; if (0 == retval) Log.Comment("PASS"); else Log.Comment("FAIL, 0x{0:X} " + retval.ToString()); return retval; } public static bool testMethod() { return (Main_old() == 0); } }; enum Enum_TestClass_enum93_Color { Red, Green = 10, Blue } class Enum_TestClass_enum93 { static void Main_old() { Log.Comment(StringFromColor(Enum_TestClass_enum93_Color.Red)); Log.Comment(StringFromColor(Enum_TestClass_enum93_Color.Green)); Log.Comment(StringFromColor(Enum_TestClass_enum93_Color.Blue)); Log.Comment(StringFromColor(Enum_TestClass_enum93_Color.Blue + 5)); } static string StringFromColor(Enum_TestClass_enum93_Color c) { return c + " = " + ((int)c).ToString(); } public static bool testMethod() { Main_old(); return true; } } enum Enum_TestClass_enum94_Color { Red, Green = 10, Blue } enum Enum_TestClass_enum94_ColorB : byte { Red, Green = 10, Blue } enum Enum_TestClass_enum94_ColorSB : sbyte { Red, Green = 10, Blue } enum Enum_TestClass_enum94_ColorS : short { Red, Green = 10, Blue } enum Enum_TestClass_enum94_ColorUS : ushort { Red, Green = 10, Blue } enum Enum_TestClass_enum94_ColorI : int { Red, Green = 10, Blue } enum Enum_TestClass_enum94_ColorUI : uint { Red, Green = 10, Blue } enum Enum_TestClass_enum94_ColorL : long { Red, Green = 10, Blue } enum Enum_TestClass_enum94_ColorUL : ulong { Red, Green = 10, Blue } class Enum_TestClass_enum94 { static void Main_old() { Log.Comment(StringFromColor((Enum_TestClass_enum94_Color)(-5))); Log.Comment(StringFromColor((Enum_TestClass_enum94_Color)1000)); Log.Comment(StringFromColor((Enum_TestClass_enum94_ColorB)255)); Log.Comment(StringFromColor((Enum_TestClass_enum94_ColorSB)127)); Log.Comment(StringFromColor((Enum_TestClass_enum94_ColorSB)(-128))); Log.Comment(StringFromColor((Enum_TestClass_enum94_ColorS)(-32768))); Log.Comment(StringFromColor((Enum_TestClass_enum94_ColorS)32767)); Log.Comment(StringFromColor((Enum_TestClass_enum94_ColorUS)65535)); Log.Comment(StringFromColor((Enum_TestClass_enum94_ColorI)(-32768))); Log.Comment(StringFromColor((Enum_TestClass_enum94_ColorI)32767)); Log.Comment(StringFromColor((Enum_TestClass_enum94_ColorUI)65535)); Log.Comment(StringFromColor((Enum_TestClass_enum94_ColorL)(-32768))); Log.Comment(StringFromColor((Enum_TestClass_enum94_ColorL)32767)); Log.Comment(StringFromColor((Enum_TestClass_enum94_ColorUL)65535)); } static string StringFromColor(Enum c) { return c + " = " + c.ToString(); } public static bool testMethod() { Main_old(); return true; } } [Flags] enum Enum_TestClassFlags01_Flag { Zero = 0x0000, First = 0x0001, Second = 0x0002, Third = 0x0004, Fourth = 0x0008, } public class Enum_TestClassFlags01 { public static int Main_old() { Enum_TestClassFlags01_Flag r = Enum_TestClassFlags01_Flag.First | Enum_TestClassFlags01_Flag.Fourth; Log.Comment(r.ToString()); return (int)r == (int)0x0009 ? 0 : 1; } public static bool testMethod() { return (Main_old() == 0); } } [Flags] enum Enum_TestClassFlags02_Flag { Zero = 0x0000, First = 0x0001, Second = 0x0002, Third = 0x0004, Fourth = 0x0008, } public class Enum_TestClassFlags02 { public static int Main_old() { Enum_TestClassFlags02_Flag r = Enum_TestClassFlags02_Flag.First | Enum_TestClassFlags02_Flag.Fourth; r = r | Enum_TestClassFlags02_Flag.Second | Enum_TestClassFlags02_Flag.Third; Log.Comment(r.ToString()); return (int)r == (int)0x000f ? 0 : 1; } public static bool testMethod() { return (Main_old() == 0); } } [Flags] enum Enum_TestClassFlags03_Flag { Zero = 0x0000, First = 0x0001, Second = 0x0002, Third = 0x0004, Fourth = 0x0008, } public class Enum_TestClassFlags03 { public static int Main_old() { Enum_TestClassFlags03_Flag r = Enum_TestClassFlags03_Flag.First | Enum_TestClassFlags03_Flag.Fourth; r+= 0x00f; // out of range Log.Comment(r.ToString()); return (int)r == (int)24 ? 0 : 1; } public static bool testMethod() { return (Main_old() == 0); } } [Flags] enum Enum_TestClassFlags04_Flag { Zero = 0x0000, First = 0x0001, Second = 0x0002, Third = 0x0004, Fourth = 0x0008, } public class Enum_TestClassFlags04 { public static int Main_old() { int i = 0x0f; Enum_TestClassFlags04_Flag r = (Enum_TestClassFlags04_Flag)i; Log.Comment(r.ToString()); return (int)r == (int)0x000f ? 0 : 1; } public static bool testMethod() { return (Main_old() == 0); } } } } ================================================ FILE: Zelig/Zelig/Test/RunTime/NETMF/mscorlib/exceptions/CSharp/ExceptionsTests.cs ================================================ //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // Copyright (c) Microsoft Corporation. All rights reserved. //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// using System; namespace Microsoft.Zelig.Test { public class ExceptionTests : TestBase, ITestInterface { [SetUp] public InitializeResult Initialize() { Log.Comment("Adding set up for the tests."); return InitializeResult.ReadyToGo; } [TearDown] public void CleanUp() { Log.Comment("Cleaning up after the tests"); } public override TestResult Run(string[] args) { TestResult result = TestResult.Pass; string testName = "Exc_excep"; result |= Assert.CheckFailed(Exc_excep01_Test(), testName, 1); result |= Assert.CheckFailed(Exc_excep02_Test(), testName, 2); result |= Assert.CheckFailed(Exc_excep04_Test(), testName, 4); result |= Assert.CheckFailed(Exc_excep05_Test(), testName, 5); result |= Assert.CheckFailed(Exc_excep06_Test(), testName, 6); result |= Assert.CheckFailed(Exc_excep07_Test(), testName, 7); result |= Assert.CheckFailed(Exc_excep09_Test(), testName, 9); result |= Assert.CheckFailed(Exc_excep10_Test(), testName, 10); result |= Assert.CheckFailed(Exc_excep11_Test(), testName, 11); result |= Assert.CheckFailed(Exc_excep27_Test(), testName, 27); result |= Assert.CheckFailed(Exc_excep28_Test(), testName, 28); result |= Assert.CheckFailed(Exc_excep30_Test(), testName, 30); result |= Assert.CheckFailed(Exc_excep31_Test(), testName, 31); result |= Assert.CheckFailed(Exc_excep33_Test(), testName, 33); result |= Assert.CheckFailed(Exc_excep34_Test(), testName, 34); result |= Assert.CheckFailed(Exc_excep35_Test(), testName, 35); result |= Assert.CheckFailed(Exc_excep40_Test(), testName, 40); result |= Assert.CheckFailed(Exc_excep41_Test(), testName, 41); result |= Assert.CheckFailed(Exc_excep42_Test(), testName, 42); result |= Assert.CheckFailed(Exc_excep42b_Test(), testName, 42); result |= Assert.CheckFailed(Exc_excep43_Test(), testName, 43); result |= Assert.CheckFailed(Exc_excep56_Test(), testName, 56); result |= Assert.CheckFailed(Exc_excep57_Test(), testName, 57); result |= Assert.CheckFailed(Exc_excep58_Test(), testName, 58); result |= Assert.CheckFailed(Exc_excep59_Test(), testName, 59); result |= Assert.CheckFailed(Exc_excep60_Test(), testName, 60); result |= Assert.CheckFailed(Exc_excep61_Test(), testName, 61); result |= Assert.CheckFailed(Exc_excep62_Test(), testName, 62); result |= Assert.CheckFailed(Exc_excep63_Test(), testName, 63); result |= Assert.CheckFailed(Exc_excep64_Test(), testName, 64); //result |= Assert.CheckFailed(Exc_excep65_Test(), testName, 65); return result; } //Exception Test methods //The following tests were ported from folder current\test\cases\client\CLR\Conformance\10_classes\Exception //excep01,excep02,excep04,excep05,excep06,excep07,excep09,excep10,excep11,excep27,excep28,excep30,excep31,excep33,excep34,excep35,excep40,excep41,excep42,excep42b,excep43,excep56,excep57,excep58,excep59,excep60,excep61,excep62,excep63,excep64,excep65, //Test Case Calls [TestMethod] public TestResult Exc_excep01_Test() { Log.Comment("This test will confirm that the the thrown exception is caught by the matching catch"); if (Exc_TestClass_excep01.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Exc_excep02_Test() { Log.Comment("This test will confirm that the the thrown exception is caught by the matching catch, not the base class catch blocks"); if (Exc_TestClass_excep02.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Exc_excep04_Test() { Log.Comment("This test will confirm that the the thrown exception is caught and the error code can be set"); if (Exc_TestClass_excep04.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Exc_excep05_Test() { Log.Comment("This test will confirm that the the thrown exception is caught by the matching catch, not the base class catch"); if (Exc_TestClass_excep05.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Exc_excep06_Test() { Log.Comment("This test will confirm that the the thrown exception is caught by the base class catch"); if (Exc_TestClass_excep06.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Exc_excep07_Test() { Log.Comment("This test will confirm that the the thrown exception is caught by the base class catch()"); if (Exc_TestClass_excep07.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Exc_excep09_Test() { Log.Comment("This test will confirm that the catch() functions."); if (Exc_TestClass_excep09.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Exc_excep10_Test() { Log.Comment("This test will confirm that the thrown exception is handled in the catch()"); Log.Comment("when no matching catch is available."); if (Exc_TestClass_excep10.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Exc_excep11_Test() { Log.Comment("This test will confirm that the the thrown exception is caught by the matching catch, not the catch()"); if (Exc_TestClass_excep11.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Exc_excep27_Test() { Log.Comment("Throwing an exception transfers control to a handler."); if (Exc_TestClass_excep27.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Exc_excep28_Test() { Log.Comment("When an exception is thrown, control is transferred to a handler"); if (Exc_TestClass_excep28.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Exc_excep30_Test() { Log.Comment("A throw-expression with no operand rethrows the exception being handled."); if (Exc_TestClass_excep30.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Exc_excep31_Test() { Log.Comment("A throw-expression with no operand does not copy the exception being handled."); if (Exc_TestClass_excep31.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Exc_excep33_Test() { Log.Comment("The exception thrown by a rethrow is the one most recently caught and not finished."); if (Exc_TestClass_excep33.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Exc_excep34_Test() { Log.Comment("When initialization is complete for the formal parameter of a catch clause, an exception is considered caught."); if (Exc_TestClass_excep34.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Exc_excep35_Test() { Log.Comment("A handler is not allowed to catch an expression thrown outside"); Log.Comment("its function-try-block and any function called from its function-"); Log.Comment("try-block."); if (Exc_TestClass_excep35.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Exc_excep40_Test() { Log.Comment("If no match is found among the handlers for a try-block, the"); Log.Comment("search for a matching handler continues in a dynamically"); Log.Comment("surrounding try-block."); if (Exc_TestClass_excep40.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Exc_excep41_Test() { Log.Comment("If no match is found among the handlers for a try-block, the"); Log.Comment("search for a matching handler continues in a dynamically"); Log.Comment("surrounding try-block."); if (Exc_TestClass_excep41.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Exc_excep42_Test() { Log.Comment("Handle throws up to 255 levels deep."); if (Exc_TestClass_excep42.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Exc_excep42b_Test() { Log.Comment("Handle throws up to 33 levels deep."); if (Exc_TestClass_excep42b.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Exc_excep43_Test() { Log.Comment("Handle throws up to 255 levels deep, but don't catch. VM should not die."); if (Exc_TestClass_excep43.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Exc_excep56_Test() { Log.Comment("Should get unreachable code warning, but nothing more."); if (Exc_TestClass_excep56.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Exc_excep57_Test() { Log.Comment("Should get unreachable code warning, but nothing more."); if (Exc_TestClass_excep57.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Exc_excep58_Test() { Log.Comment("Any finally clauses associated with try statements will be executed before catch clause execution"); if (Exc_TestClass_excep58.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Exc_excep59_Test() { Log.Comment("Any finally clauses associated with try statements will be executed before catch clause execution"); if (Exc_TestClass_excep59.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Exc_excep60_Test() { Log.Comment("Inner exceptions can be chained"); if (Exc_TestClass_excep60.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Exc_excep61_Test() { Log.Comment("Inner exceptions can be chained to arbitrary length"); if (Exc_TestClass_excep61.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Exc_excep62_Test() { Log.Comment("Any finally clauses associated with try statements will be executed before catch clause execution"); if (Exc_TestClass_excep62.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Exc_excep63_Test() { Log.Comment("If a catch search reaches a static ctor then a Exception is thrown,"); Log.Comment("at the point of static ctor invocation. The inner exception is the original exception."); Log.Comment("an exception thrown in a static constructor brings up a dialog box in Visual Studio."); Log.Comment("Disable this test so that it doesn't hose VS until it is fixed."); if (Exc_TestClass_excep63.testMethod()) { Log.Comment("This is bug number: 21724 Resolved By Design."); Log.Comment("This is bug number: 21724 If a catch search reaches a static ctor then a Exception is thrown at the point of static ctor invocation. The inner exception is the original exception. "); Log.Comment("When this bug is fixed change this back to pass and chang eht known failure to fail"); return TestResult.Fail; } return TestResult.Pass; } [TestMethod] public TestResult Exc_excep64_Test() { Log.Comment("If a catch search reaches a static field initializer then a Exception is thrown,"); Log.Comment("at the point of static ctor invocation. The inner exception is the original exception."); Log.Comment("an exception thrown in a static constructor brings up a dialog box in Visual Studio."); Log.Comment("Disable this test so that it doesn't hose VS until it is fixed."); if (Exc_TestClass_excep64.testMethod()) { Log.Comment("This is bug number: 21724 Resolved By Design."); Log.Comment("This is bug number: 21724 If a catch search reaches a static ctor then a Exception is thrown at the point of static ctor invocation. The inner exception is the original exception. "); Log.Comment("When this bug is fixed change this back to pass and chang eht known failure to fail"); return TestResult.Fail; } return TestResult.Pass; } /* * This test is excluded because it throws an exception, it succeeded in the baseline * It however currently fails in the desktop environment, in both cases the sleep is not sufficient to provoke GC * and when GC is called, the dtor does not exit or call its base class' dtor when it throws an exception. * [TestMethod] public TestResult Exc_excep65_Test() { Log.Comment("If a catch search reaches a static ctor then a Exception is thrown,"); Log.Comment("at the point of static ctor invocation. The inner exception is the original exception."); if (Exc_TestClass_excep65.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } */ //Compiled Test Cases public class Exc_TestClass_excep01 { private static int retval = 1; public static int Main_old() { try { Log.Comment("In try block, ready to throw."); throw new Exception("An exception has occurred"); } catch (Exception s) { Log.Comment("In catch block."); Log.Comment(s.Message); retval = 0; } return retval; } public static bool testMethod() { return (Main_old() == 0); } } public class Exc_TestClass_excep02_E1 : Exception { public Exc_TestClass_excep02_E1(String str) : base(str) { } } public class Exc_TestClass_excep02 { private static int retval = 1; public static int Main_old() { try { Log.Comment("In try block, ready to throw."); throw new Exc_TestClass_excep02_E1("An exception has occurred"); } catch (Exc_TestClass_excep02_E1 s) { Log.Comment("In Exc_TestClass_excep02_E1 catch block."); Log.Comment(s.Message); retval = 0; } catch (Exception) { Log.Comment("FAIL - In Exception catch block."); retval = 2; } //catch (Exception e) //{ // Log.Comment ("FAIL - In Exception catch block."); // retval = 3; //} return retval; } public static bool testMethod() { return (Main_old() == 0); } } public class Exc_TestClass_excep04 { private static int retval = 3; public static int Main_old() { try { try { Log.Comment("In try block, ready to throw."); throw new Exception("An exception has occurred"); } catch (Exception s) { Log.Comment("In catch block."); Log.Comment(s.Message); retval -= 1; } } finally { Log.Comment("Entering finally block"); retval -= 2; } Log.Comment("Ready to return."); if (0 == retval) Log.Comment("PASS"); else Log.Comment("FAIL, retval=={0} " + retval.ToString()); return retval; } public static bool testMethod() { return (Main_old() == 0); } } public class Exc_TestClass_excep05_E1 : Exception { public Exc_TestClass_excep05_E1(String str) : base(str) { } } public class Exc_TestClass_excep05 { private static int retval = 2; public static int Main_old() { try { try { Log.Comment("In try block, ready to throw."); throw new Exc_TestClass_excep05_E1("An exception has occurred"); } catch (Exc_TestClass_excep05_E1 s) { Log.Comment("In catch block."); Log.Comment(s.Message); retval--; } catch (Exception) { Log.Comment("FAIL -- Should not enter catch (Exception) block"); retval++; } } finally { Log.Comment("In finally block"); --retval; } return retval; } public static bool testMethod() { return (Main_old() == 0); } } public class Exc_TestClass_excep06_E1 : Exception { public Exc_TestClass_excep06_E1(String str) : base(str) { } } public class Exc_TestClass_excep06 { private static int retval = 1; public static int Main_old() { try { Log.Comment("In try block, ready to throw."); throw new Exc_TestClass_excep06_E1("An exception has occurred"); } catch (Exception s) { Log.Comment("In catch block."); Log.Comment(s.Message); retval = 0; } return retval; } public static bool testMethod() { return (Main_old() == 0); } } public class Exc_TestClass_excep07_E1 : Exception { public Exc_TestClass_excep07_E1(String str) : base(str) { } } public class Exc_TestClass_excep07 { private static int retval = 1; public static int Main_old() { try { try { Log.Comment("In try block, ready to throw."); } catch (Exception s) { Log.Comment("In catch block."); Log.Comment(s.Message); retval++; } } finally { Log.Comment("In finally block"); retval--; } return retval; } public static bool testMethod() { return (Main_old() == 0); } } public class Exc_TestClass_excep09 { private static int retval = 1; public static int Main_old() { try { Log.Comment("In try block, ready to throw."); throw new Exception("An exception has occurred"); } catch { Log.Comment("In catch block."); retval = 0; } return retval; } public static bool testMethod() { return (Main_old() == 0); } } public class Exc_TestClass_excep10_E1 : Exception { public Exc_TestClass_excep10_E1(String str) : base(str) { } } public class Exc_TestClass_excep10 { private static int retval = 1; public static int Main_old() { try { Log.Comment("In try block, ready to throw."); throw new Exception("An exception has occurred"); } catch (Exc_TestClass_excep10_E1) { Log.Comment("FAIL -- Should not enter catch (Exception a) block."); retval = 1; } catch { Log.Comment("In catch block."); retval -= 1; } return retval; } public static bool testMethod() { return (Main_old() == 0); } } public class Exc_TestClass_excep11 { private static int retval = 1; public static int Main_old() { try { Log.Comment("In try block, ready to throw."); throw new Exception("An exception has occurred"); } catch (Exception r) { Log.Comment("In catch (Exception r) block."); Log.Comment(r.Message); retval -= 1; } catch { Log.Comment("FAIL -- Should not enter catch () block."); retval += 1; } return retval; } public static bool testMethod() { return (Main_old() == 0); } } public class Exc_TestClass_excep27_B { public void toss() { throw new Exception("Exception thrown in function toss()."); } } public class Exc_TestClass_excep27 { private static int retval = 5; public static int Main_old() { try { Exc_TestClass_excep27_B b = new Exc_TestClass_excep27_B(); b.toss(); } catch (Exception e) { retval -= 5; Log.Comment(e.Message); } return retval; } public static bool testMethod() { return (Main_old() == 0); } } public class Exc_TestClass_excep28_B { public int toss(int Where) { int r = 99; try { if (Where == 0) throw new Exception("Where == 0"); } catch (Exception) { r = 0; } try { if (Where == 1) throw new Exception("Where == 1"); } catch (Exception) { r = 1; } try { if (Where == 2) throw new Exception("Where == 2"); } catch (Exception) { r = 2; } return r; } } public class Exc_TestClass_excep28 { private static int retval = 7; private static int tossval = -1; public static int Main_old() { Exc_TestClass_excep28_B b = new Exc_TestClass_excep28_B(); tossval = b.toss(0); if (tossval != 0) { Log.Comment("toss(0) returned "); Log.Comment(tossval.ToString()); Log.Comment(" instead of 0."); } else { retval -= 4; } tossval = b.toss(1); if (tossval != 1) { Log.Comment("toss(1) returned "); Log.Comment(tossval.ToString()); Log.Comment(" instead of 1."); } else { retval -= 2; } tossval = b.toss(2); if (tossval != 2) { Log.Comment("toss(2) returned "); Log.Comment(tossval.ToString()); Log.Comment(" instead of 2."); } else { retval -= 1; } if (retval == 0) Log.Comment("PASS"); else Log.Comment("FAIL"); return retval; } public static bool testMethod() { return (Main_old() == 0); } } public class Exc_TestClass_excep30_C1 { static int s = 1; public int rethrow() { try { throw new Exception(); } catch (Exception) { s = 20; throw; // rethrow float } catch { s = 99; } return s; } public int f00() { try { rethrow(); } catch (Exception) { s += 10; } return s; } } public class Exc_TestClass_excep30 { private static int retval = 3; public static int Main_old() { Exc_TestClass_excep30_C1 t = new Exc_TestClass_excep30_C1(); if (t.f00() == 30) // If the throw was handled properly... retval = 0; if (retval == 0) Log.Comment("PASS"); else Log.Comment("FAIL"); return retval; } public static bool testMethod() { return (Main_old() == 0); } } public class Exc_TestClass_excep31_E1 : Exception { public int i = 99; public Exc_TestClass_excep31_E1(int ii) { i = ii; } } public class Exc_TestClass_excep31_C1 { static int s = 1; public int rethrow() { try { throw new Exc_TestClass_excep31_E1(1); } catch (Exc_TestClass_excep31_E1 e) { e.i = 20; throw; // rethrow float } catch { s = 99; } return s; } public int f00() { try { rethrow(); } catch (Exc_TestClass_excep31_E1 e) { if (e.i == 20) s = 0; } return s; } } public class Exc_TestClass_excep31 { private static int retval = 3; public static int Main_old() { Exc_TestClass_excep31_C1 t = new Exc_TestClass_excep31_C1(); if (t.f00() == 0) // If the throw was handled properly... retval = 0; if (retval == 0) Log.Comment("PASS"); else Log.Comment("FAIL"); return retval; } public static bool testMethod() { return (Main_old() == 0); } } public class Exc_TestClass_excep33_E2 : Exception { } public class Exc_TestClass_excep33_E3 : Exception { } public class Exc_TestClass_excep33_E4 : Exception { } public class Exc_TestClass_excep33 { private static int retval = 2; public static int Main_old() { Exc_TestClass_excep33_E2 s0 = new Exc_TestClass_excep33_E2(); Exc_TestClass_excep33_E3 s1 = new Exc_TestClass_excep33_E3(); Exc_TestClass_excep33_E4 s2 = new Exc_TestClass_excep33_E4(); try { try { throw s0; } catch (Exc_TestClass_excep33_E2) { try { throw s1; } catch (Exc_TestClass_excep33_E3) { try { throw s2; } catch (Exc_TestClass_excep33_E4) { throw; } } } } catch (Exc_TestClass_excep33_E2) { Log.Comment("Unexpected Exc_TestClass_excep33_E2 catch."); } catch (Exc_TestClass_excep33_E3) { Log.Comment("Unexpected Exc_TestClass_excep33_E3 catch."); } catch (Exc_TestClass_excep33_E4) { Log.Comment("Caught in Exc_TestClass_excep33_E4, as expected."); retval = 0; } catch { Log.Comment("Unexpected ... catch."); } if (retval == 0) Log.Comment("PASS"); else Log.Comment("FAIL"); return retval; } public static bool testMethod() { return (Main_old() == 0); } } public class Exc_TestClass_excep34_E2 : Exception { public char c = ' '; } public class Exc_TestClass_excep34_E3 : Exception { public float f = 1.3f; } public class Exc_TestClass_excep34 { private static int retval = 2; public static int Main_old() { Exc_TestClass_excep34_E2 s0 = new Exc_TestClass_excep34_E2(); Exc_TestClass_excep34_E3 s1 = new Exc_TestClass_excep34_E3(); try { try { throw s0; } catch (Exc_TestClass_excep34_E2) { try { throw s1; } catch (Exc_TestClass_excep34_E3) { throw; } } } catch (Exc_TestClass_excep34_E2) { Log.Comment("Unexpected Exc_TestClass_excep34_E2 catch.\n"); } catch (Exc_TestClass_excep34_E3) { Log.Comment("Caught in Exc_TestClass_excep34_E3 as expected.\n"); retval = 0; } catch { Log.Comment("Unexpected ... catch.\n"); } if (retval == 0) Log.Comment("PASS"); else Log.Comment("FAIL"); return retval; } public static bool testMethod() { return (Main_old() == 0); } } public class Exc_TestClass_excep35_V { public static int counter = 0; } public class Exc_TestClass_excep35_E1 : Exception { public Exc_TestClass_excep35_E1() { try { } catch (Exc_TestClass_excep35_E1) { ++Exc_TestClass_excep35_V.counter; } } } public class Exc_TestClass_excep35 { private static int retval = 2; public static int Main_old() { Exc_TestClass_excep35_E1 s0 = new Exc_TestClass_excep35_E1(); try { throw new Exc_TestClass_excep35_E1(); } catch { } retval = Exc_TestClass_excep35_V.counter; if (retval == 0) Log.Comment("PASS"); else Log.Comment("FAIL"); return retval; } public static bool testMethod() { return (Main_old() == 0); } } public class Exc_TestClass_excep40_E1 : Exception { } public class Exc_TestClass_excep40_E3 : Exception { } public class Exc_TestClass_excep40_F { public static int xpath = 0; public void f01() { try { throw new Exc_TestClass_excep40_E3(); } catch (Exc_TestClass_excep40_E1) { xpath = 5; } } public void f00() { try { f01(); } catch (Exception) { xpath = 1; } } public void f02() { try { throw new Exc_TestClass_excep40_E3(); } catch (Exc_TestClass_excep40_E1) { xpath = 5; } } public void f03() { try { f01(); } catch (Exc_TestClass_excep40_E3) { xpath = 1; } } } public class Exc_TestClass_excep40 { private static int retval = 3; public static int Main_old() { Exc_TestClass_excep40_F f = new Exc_TestClass_excep40_F(); f.f00(); if (Exc_TestClass_excep40_F.xpath == 1) retval--; Exc_TestClass_excep40_F.xpath = 0; f.f03(); if (Exc_TestClass_excep40_F.xpath == 1) retval -= 2; if (retval == 0) Log.Comment("PASS"); else Log.Comment("FAIL"); return retval; } public static bool testMethod() { return (Main_old() == 0); } } public class Exc_TestClass_excep41_E1 : Exception { } public class Exc_TestClass_excep41_E3 : Exception { } public class Exc_TestClass_excep41_E4 : Exception { } public class Exc_TestClass_excep41_F { public static int xpath = 0; public void f01() { try { Log.Comment("In f01(), throwing an Exc_TestClass_excep41_E3..."); throw new Exc_TestClass_excep41_E3(); Log.Comment("After throw in f01(). SHOULD NOT BE HERE!"); } catch (Exc_TestClass_excep41_E1) { Log.Comment("In catch in f01()"); xpath += 4; } } public void f00() { try { Log.Comment("Calling f01()..."); f01(); Log.Comment("Returned from f01()"); } catch (Exc_TestClass_excep41_E4) { Log.Comment("In catch in f00()"); xpath += 2; } } } public class Exc_TestClass_excep41 { private static int retval = 1; public static int Main_old() { Exc_TestClass_excep41_F f = new Exc_TestClass_excep41_F(); try { Log.Comment("Calling f00()..."); f.f00(); Log.Comment("Returned from f00()..."); } catch (Exc_TestClass_excep41_E3) { Log.Comment("In catch in f00()"); Exc_TestClass_excep41_F.xpath += 1; } if (Exc_TestClass_excep41_F.xpath == 1) retval--; if (retval == 0) Log.Comment("PASS"); else Log.Comment("FAIL, xpath=={0} " + (Exc_TestClass_excep41_F.xpath).ToString()); return retval; } public static bool testMethod() { return (Main_old() == 0); } } public class Exc_TestClass_excep42_E1 : Exception { } public class Exc_TestClass_excep42_E3 : Exception { } public class Exc_TestClass_excep42_E4 : Exception { } public class Exc_TestClass_excep42_F { public static int tb = -1; public void f255(int i) { Exc_TestClass_excep42_E1 s = new Exc_TestClass_excep42_E1(); Exc_TestClass_excep42_E3 s1 = new Exc_TestClass_excep42_E3(); Log.Comment("i==" + i.ToString()); if (i == 255) { Log.Comment("Throwing Exc_TestClass_excep42_E1"); tb = 0; throw s; } else throw s1; } public void f254(int i) { try { f255(++i); } catch (Exc_TestClass_excep42_E4) { tb = 254; } catch { throw; } } public void f253(int i) { try { f254(++i); } catch (Exc_TestClass_excep42_E4) { tb = 253; } catch { throw; } } public void f252(int i) { try { f253(++i); } catch (Exc_TestClass_excep42_E4) { tb = 252; } catch { throw; } } public void f251(int i) { try { f252(++i); } catch (Exc_TestClass_excep42_E4) { tb = 251; } catch { throw; } } public void f250(int i) { try { f251(++i); } catch (Exc_TestClass_excep42_E4) { tb = 250; } catch { throw; } } public void f249(int i) { try { f250(++i); } catch (Exc_TestClass_excep42_E4) { tb = 249; } catch { throw; } } public void f248(int i) { try { f249(++i); } catch (Exc_TestClass_excep42_E4) { tb = 248; } catch { throw; } } public void f247(int i) { try { f248(++i); } catch (Exc_TestClass_excep42_E4) { tb = 247; } catch { throw; } } public void f246(int i) { try { f247(++i); } catch (Exc_TestClass_excep42_E4) { tb = 246; } catch { throw; } } public void f245(int i) { try { f246(++i); } catch (Exc_TestClass_excep42_E4) { tb = 245; } catch { throw; } } public void f244(int i) { try { f245(++i); } catch (Exc_TestClass_excep42_E4) { tb = 244; } catch { throw; } } public void f243(int i) { try { f244(++i); } catch (Exc_TestClass_excep42_E4) { tb = 243; } catch { throw; } } public void f242(int i) { try { f243(++i); } catch (Exc_TestClass_excep42_E4) { tb = 242; } catch { throw; } } public void f241(int i) { try { f242(++i); } catch (Exc_TestClass_excep42_E4) { tb = 241; } catch { throw; } } public void f240(int i) { try { f241(++i); } catch (Exc_TestClass_excep42_E4) { tb = 240; } catch { throw; } } public void f239(int i) { try { f240(++i); } catch (Exc_TestClass_excep42_E4) { tb = 239; } catch { throw; } } public void f238(int i) { try { f239(++i); } catch (Exc_TestClass_excep42_E4) { tb = 238; } catch { throw; } } public void f237(int i) { try { f238(++i); } catch (Exc_TestClass_excep42_E4) { tb = 237; } catch { throw; } } public void f236(int i) { try { f237(++i); } catch (Exc_TestClass_excep42_E4) { tb = 236; } catch { throw; } } public void f235(int i) { try { f236(++i); } catch (Exc_TestClass_excep42_E4) { tb = 235; } catch { throw; } } public void f234(int i) { try { f235(++i); } catch (Exc_TestClass_excep42_E4) { tb = 234; } catch { throw; } } public void f233(int i) { try { f234(++i); } catch (Exc_TestClass_excep42_E4) { tb = 233; } catch { throw; } } public void f232(int i) { try { f233(++i); } catch (Exc_TestClass_excep42_E4) { tb = 232; } catch { throw; } } public void f231(int i) { try { f232(++i); } catch (Exc_TestClass_excep42_E4) { tb = 231; } catch { throw; } } public void f230(int i) { try { f231(++i); } catch (Exc_TestClass_excep42_E4) { tb = 230; } catch { throw; } } public void f229(int i) { try { f230(++i); } catch (Exc_TestClass_excep42_E4) { tb = 229; } catch { throw; } } public void f228(int i) { try { f229(++i); } catch (Exc_TestClass_excep42_E4) { tb = 228; } catch { throw; } } public void f227(int i) { try { f228(++i); } catch (Exc_TestClass_excep42_E4) { tb = 227; } catch { throw; } } public void f226(int i) { try { f227(++i); } catch (Exc_TestClass_excep42_E4) { tb = 226; } catch { throw; } } public void f225(int i) { try { f226(++i); } catch (Exc_TestClass_excep42_E4) { tb = 225; } catch { throw; } } public void f224(int i) { try { f225(++i); } catch (Exc_TestClass_excep42_E4) { tb = 224; } catch { throw; } } public void f223(int i) { try { f224(++i); } catch (Exc_TestClass_excep42_E4) { tb = 223; } catch { throw; } } public void f222(int i) { try { f223(++i); } catch (Exc_TestClass_excep42_E4) { tb = 222; } catch { throw; } } public void f221(int i) { try { f222(++i); } catch (Exc_TestClass_excep42_E4) { tb = 221; } catch { throw; } } public void f220(int i) { try { f221(++i); } catch (Exc_TestClass_excep42_E4) { tb = 220; } catch { throw; } } public void f219(int i) { try { f220(++i); } catch (Exc_TestClass_excep42_E4) { tb = 219; } catch { throw; } } public void f218(int i) { try { f219(++i); } catch (Exc_TestClass_excep42_E4) { tb = 218; } catch { throw; } } public void f217(int i) { try { f218(++i); } catch (Exc_TestClass_excep42_E4) { tb = 217; } catch { throw; } } public void f216(int i) { try { f217(++i); } catch (Exc_TestClass_excep42_E4) { tb = 216; } catch { throw; } } public void f215(int i) { try { f216(++i); } catch (Exc_TestClass_excep42_E4) { tb = 215; } catch { throw; } } public void f214(int i) { try { f215(++i); } catch (Exc_TestClass_excep42_E4) { tb = 214; } catch { throw; } } public void f213(int i) { try { f214(++i); } catch (Exc_TestClass_excep42_E4) { tb = 213; } catch { throw; } } public void f212(int i) { try { f213(++i); } catch (Exc_TestClass_excep42_E4) { tb = 212; } catch { throw; } } public void f211(int i) { try { f212(++i); } catch (Exc_TestClass_excep42_E4) { tb = 211; } catch { throw; } } public void f210(int i) { try { f211(++i); } catch (Exc_TestClass_excep42_E4) { tb = 210; } catch { throw; } } public void f209(int i) { try { f210(++i); } catch (Exc_TestClass_excep42_E4) { tb = 209; } catch { throw; } } public void f208(int i) { try { f209(++i); } catch (Exc_TestClass_excep42_E4) { tb = 208; } catch { throw; } } public void f207(int i) { try { f208(++i); } catch (Exc_TestClass_excep42_E4) { tb = 207; } catch { throw; } } public void f206(int i) { try { f207(++i); } catch (Exc_TestClass_excep42_E4) { tb = 206; } catch { throw; } } public void f205(int i) { try { f206(++i); } catch (Exc_TestClass_excep42_E4) { tb = 205; } catch { throw; } } public void f204(int i) { try { f205(++i); } catch (Exc_TestClass_excep42_E4) { tb = 204; } catch { throw; } } public void f203(int i) { try { f204(++i); } catch (Exc_TestClass_excep42_E4) { tb = 203; } catch { throw; } } public void f202(int i) { try { f203(++i); } catch (Exc_TestClass_excep42_E4) { tb = 202; } catch { throw; } } public void f201(int i) { try { f202(++i); } catch (Exc_TestClass_excep42_E4) { tb = 201; } catch { throw; } } public void f200(int i) { try { f201(++i); } catch (Exc_TestClass_excep42_E4) { tb = 200; } catch { throw; } } public void f199(int i) { try { f200(++i); } catch (Exc_TestClass_excep42_E4) { tb = 199; } catch { throw; } } public void f198(int i) { try { f199(++i); } catch (Exc_TestClass_excep42_E4) { tb = 198; } catch { throw; } } public void f197(int i) { try { f198(++i); } catch (Exc_TestClass_excep42_E4) { tb = 197; } catch { throw; } } public void f196(int i) { try { f197(++i); } catch (Exc_TestClass_excep42_E4) { tb = 196; } catch { throw; } } public void f195(int i) { try { f196(++i); } catch (Exc_TestClass_excep42_E4) { tb = 195; } catch { throw; } } public void f194(int i) { try { f195(++i); } catch (Exc_TestClass_excep42_E4) { tb = 194; } catch { throw; } } public void f193(int i) { try { f194(++i); } catch (Exc_TestClass_excep42_E4) { tb = 193; } catch { throw; } } public void f192(int i) { try { f193(++i); } catch (Exc_TestClass_excep42_E4) { tb = 192; } catch { throw; } } public void f191(int i) { try { f192(++i); } catch (Exc_TestClass_excep42_E4) { tb = 191; } catch { throw; } } public void f190(int i) { try { f191(++i); } catch (Exc_TestClass_excep42_E4) { tb = 190; } catch { throw; } } public void f189(int i) { try { f190(++i); } catch (Exc_TestClass_excep42_E4) { tb = 189; } catch { throw; } } public void f188(int i) { try { f189(++i); } catch (Exc_TestClass_excep42_E4) { tb = 188; } catch { throw; } } public void f187(int i) { try { f188(++i); } catch (Exc_TestClass_excep42_E4) { tb = 187; } catch { throw; } } public void f186(int i) { try { f187(++i); } catch (Exc_TestClass_excep42_E4) { tb = 186; } catch { throw; } } public void f185(int i) { try { f186(++i); } catch (Exc_TestClass_excep42_E4) { tb = 185; } catch { throw; } } public void f184(int i) { try { f185(++i); } catch (Exc_TestClass_excep42_E4) { tb = 184; } catch { throw; } } public void f183(int i) { try { f184(++i); } catch (Exc_TestClass_excep42_E4) { tb = 183; } catch { throw; } } public void f182(int i) { try { f183(++i); } catch (Exc_TestClass_excep42_E4) { tb = 182; } catch { throw; } } public void f181(int i) { try { f182(++i); } catch (Exc_TestClass_excep42_E4) { tb = 181; } catch { throw; } } public void f180(int i) { try { f181(++i); } catch (Exc_TestClass_excep42_E4) { tb = 180; } catch { throw; } } public void f179(int i) { try { f180(++i); } catch (Exc_TestClass_excep42_E4) { tb = 179; } catch { throw; } } public void f178(int i) { try { f179(++i); } catch (Exc_TestClass_excep42_E4) { tb = 178; } catch { throw; } } public void f177(int i) { try { f178(++i); } catch (Exc_TestClass_excep42_E4) { tb = 177; } catch { throw; } } public void f176(int i) { try { f177(++i); } catch (Exc_TestClass_excep42_E4) { tb = 176; } catch { throw; } } public void f175(int i) { try { f176(++i); } catch (Exc_TestClass_excep42_E4) { tb = 175; } catch { throw; } } public void f174(int i) { try { f175(++i); } catch (Exc_TestClass_excep42_E4) { tb = 174; } catch { throw; } } public void f173(int i) { try { f174(++i); } catch (Exc_TestClass_excep42_E4) { tb = 173; } catch { throw; } } public void f172(int i) { try { f173(++i); } catch (Exc_TestClass_excep42_E4) { tb = 172; } catch { throw; } } public void f171(int i) { try { f172(++i); } catch (Exc_TestClass_excep42_E4) { tb = 171; } catch { throw; } } public void f170(int i) { try { f171(++i); } catch (Exc_TestClass_excep42_E4) { tb = 170; } catch { throw; } } public void f169(int i) { try { f170(++i); } catch (Exc_TestClass_excep42_E4) { tb = 169; } catch { throw; } } public void f168(int i) { try { f169(++i); } catch (Exc_TestClass_excep42_E4) { tb = 168; } catch { throw; } } public void f167(int i) { try { f168(++i); } catch (Exc_TestClass_excep42_E4) { tb = 167; } catch { throw; } } public void f166(int i) { try { f167(++i); } catch (Exc_TestClass_excep42_E4) { tb = 166; } catch { throw; } } public void f165(int i) { try { f166(++i); } catch (Exc_TestClass_excep42_E4) { tb = 165; } catch { throw; } } public void f164(int i) { try { f165(++i); } catch (Exc_TestClass_excep42_E4) { tb = 164; } catch { throw; } } public void f163(int i) { try { f164(++i); } catch (Exc_TestClass_excep42_E4) { tb = 163; } catch { throw; } } public void f162(int i) { try { f163(++i); } catch (Exc_TestClass_excep42_E4) { tb = 162; } catch { throw; } } public void f161(int i) { try { f162(++i); } catch (Exc_TestClass_excep42_E4) { tb = 161; } catch { throw; } } public void f160(int i) { try { f161(++i); } catch (Exc_TestClass_excep42_E4) { tb = 160; } catch { throw; } } public void f159(int i) { try { f160(++i); } catch (Exc_TestClass_excep42_E4) { tb = 159; } catch { throw; } } public void f158(int i) { try { f159(++i); } catch (Exc_TestClass_excep42_E4) { tb = 158; } catch { throw; } } public void f157(int i) { try { f158(++i); } catch (Exc_TestClass_excep42_E4) { tb = 157; } catch { throw; } } public void f156(int i) { try { f157(++i); } catch (Exc_TestClass_excep42_E4) { tb = 156; } catch { throw; } } public void f155(int i) { try { f156(++i); } catch (Exc_TestClass_excep42_E4) { tb = 155; } catch { throw; } } public void f154(int i) { try { f155(++i); } catch (Exc_TestClass_excep42_E4) { tb = 154; } catch { throw; } } public void f153(int i) { try { f154(++i); } catch (Exc_TestClass_excep42_E4) { tb = 153; } catch { throw; } } public void f152(int i) { try { f153(++i); } catch (Exc_TestClass_excep42_E4) { tb = 152; } catch { throw; } } public void f151(int i) { try { f152(++i); } catch (Exc_TestClass_excep42_E4) { tb = 151; } catch { throw; } } public void f150(int i) { try { f151(++i); } catch (Exc_TestClass_excep42_E4) { tb = 150; } catch { throw; } } public void f149(int i) { try { f150(++i); } catch (Exc_TestClass_excep42_E4) { tb = 149; } catch { throw; } } public void f148(int i) { try { f149(++i); } catch (Exc_TestClass_excep42_E4) { tb = 148; } catch { throw; } } public void f147(int i) { try { f148(++i); } catch (Exc_TestClass_excep42_E4) { tb = 147; } catch { throw; } } public void f146(int i) { try { f147(++i); } catch (Exc_TestClass_excep42_E4) { tb = 146; } catch { throw; } } public void f145(int i) { try { f146(++i); } catch (Exc_TestClass_excep42_E4) { tb = 145; } catch { throw; } } public void f144(int i) { try { f145(++i); } catch (Exc_TestClass_excep42_E4) { tb = 144; } catch { throw; } } public void f143(int i) { try { f144(++i); } catch (Exc_TestClass_excep42_E4) { tb = 143; } catch { throw; } } public void f142(int i) { try { f143(++i); } catch (Exc_TestClass_excep42_E4) { tb = 142; } catch { throw; } } public void f141(int i) { try { f142(++i); } catch (Exc_TestClass_excep42_E4) { tb = 141; } catch { throw; } } public void f140(int i) { try { f141(++i); } catch (Exc_TestClass_excep42_E4) { tb = 140; } catch { throw; } } public void f139(int i) { try { f140(++i); } catch (Exc_TestClass_excep42_E4) { tb = 139; } catch { throw; } } public void f138(int i) { try { f139(++i); } catch (Exc_TestClass_excep42_E4) { tb = 138; } catch { throw; } } public void f137(int i) { try { f138(++i); } catch (Exc_TestClass_excep42_E4) { tb = 137; } catch { throw; } } public void f136(int i) { try { f137(++i); } catch (Exc_TestClass_excep42_E4) { tb = 136; } catch { throw; } } public void f135(int i) { try { f136(++i); } catch (Exc_TestClass_excep42_E4) { tb = 135; } catch { throw; } } public void f134(int i) { try { f135(++i); } catch (Exc_TestClass_excep42_E4) { tb = 134; } catch { throw; } } public void f133(int i) { try { f134(++i); } catch (Exc_TestClass_excep42_E4) { tb = 133; } catch { throw; } } public void f132(int i) { try { f133(++i); } catch (Exc_TestClass_excep42_E4) { tb = 132; } catch { throw; } } public void f131(int i) { try { f132(++i); } catch (Exc_TestClass_excep42_E4) { tb = 131; } catch { throw; } } public void f130(int i) { try { f131(++i); } catch (Exc_TestClass_excep42_E4) { tb = 130; } catch { throw; } } public void f129(int i) { try { f130(++i); } catch (Exc_TestClass_excep42_E4) { tb = 129; } catch { throw; } } public void f128(int i) { try { f129(++i); } catch (Exc_TestClass_excep42_E4) { tb = 128; } catch { throw; } } public void f127(int i) { try { f128(++i); } catch (Exc_TestClass_excep42_E4) { tb = 127; } catch { throw; } } public void f126(int i) { try { f127(++i); } catch (Exc_TestClass_excep42_E4) { tb = 126; } catch { throw; } } public void f125(int i) { try { f126(++i); } catch (Exc_TestClass_excep42_E4) { tb = 125; } catch { throw; } } public void f124(int i) { try { f125(++i); } catch (Exc_TestClass_excep42_E4) { tb = 124; } catch { throw; } } public void f123(int i) { try { f124(++i); } catch (Exc_TestClass_excep42_E4) { tb = 123; } catch { throw; } } public void f122(int i) { try { f123(++i); } catch (Exc_TestClass_excep42_E4) { tb = 122; } catch { throw; } } public void f121(int i) { try { f122(++i); } catch (Exc_TestClass_excep42_E4) { tb = 121; } catch { throw; } } public void f120(int i) { try { f121(++i); } catch (Exc_TestClass_excep42_E4) { tb = 120; } catch { throw; } } public void f119(int i) { try { f120(++i); } catch (Exc_TestClass_excep42_E4) { tb = 119; } catch { throw; } } public void f118(int i) { try { f119(++i); } catch (Exc_TestClass_excep42_E4) { tb = 118; } catch { throw; } } public void f117(int i) { try { f118(++i); } catch (Exc_TestClass_excep42_E4) { tb = 117; } catch { throw; } } public void f116(int i) { try { f117(++i); } catch (Exc_TestClass_excep42_E4) { tb = 116; } catch { throw; } } public void f115(int i) { try { f116(++i); } catch (Exc_TestClass_excep42_E4) { tb = 115; } catch { throw; } } public void f114(int i) { try { f115(++i); } catch (Exc_TestClass_excep42_E4) { tb = 114; } catch { throw; } } public void f113(int i) { try { f114(++i); } catch (Exc_TestClass_excep42_E4) { tb = 113; } catch { throw; } } public void f112(int i) { try { f113(++i); } catch (Exc_TestClass_excep42_E4) { tb = 112; } catch { throw; } } public void f111(int i) { try { f112(++i); } catch (Exc_TestClass_excep42_E4) { tb = 111; } catch { throw; } } public void f110(int i) { try { f111(++i); } catch (Exc_TestClass_excep42_E4) { tb = 110; } catch { throw; } } public void f109(int i) { try { f110(++i); } catch (Exc_TestClass_excep42_E4) { tb = 109; } catch { throw; } } public void f108(int i) { try { f109(++i); } catch (Exc_TestClass_excep42_E4) { tb = 108; } catch { throw; } } public void f107(int i) { try { f108(++i); } catch (Exc_TestClass_excep42_E4) { tb = 107; } catch { throw; } } public void f106(int i) { try { f107(++i); } catch (Exc_TestClass_excep42_E4) { tb = 106; } catch { throw; } } public void f105(int i) { try { f106(++i); } catch (Exc_TestClass_excep42_E4) { tb = 105; } catch { throw; } } public void f104(int i) { try { f105(++i); } catch (Exc_TestClass_excep42_E4) { tb = 104; } catch { throw; } } public void f103(int i) { try { f104(++i); } catch (Exc_TestClass_excep42_E4) { tb = 103; } catch { throw; } } public void f102(int i) { try { f103(++i); } catch (Exc_TestClass_excep42_E4) { tb = 102; } catch { throw; } } public void f101(int i) { try { f102(++i); } catch (Exc_TestClass_excep42_E4) { tb = 101; } catch { throw; } } public void f100(int i) { try { f101(++i); } catch (Exc_TestClass_excep42_E4) { tb = 100; } catch { throw; } } public void f099(int i) { try { f100(++i); } catch (Exc_TestClass_excep42_E4) { tb = 99; } catch { throw; } } public void f098(int i) { try { f099(++i); } catch (Exc_TestClass_excep42_E4) { tb = 98; } catch { throw; } } public void f097(int i) { try { f098(++i); } catch (Exc_TestClass_excep42_E4) { tb = 97; } catch { throw; } } public void f096(int i) { try { f097(++i); } catch (Exc_TestClass_excep42_E4) { tb = 96; } catch { throw; } } public void f095(int i) { try { f096(++i); } catch (Exc_TestClass_excep42_E4) { tb = 95; } catch { throw; } } public void f094(int i) { try { f095(++i); } catch (Exc_TestClass_excep42_E4) { tb = 94; } catch { throw; } } public void f093(int i) { try { f094(++i); } catch (Exc_TestClass_excep42_E4) { tb = 93; } catch { throw; } } public void f092(int i) { try { f093(++i); } catch (Exc_TestClass_excep42_E4) { tb = 92; } catch { throw; } } public void f091(int i) { try { f092(++i); } catch (Exc_TestClass_excep42_E4) { tb = 91; } catch { throw; } } public void f090(int i) { try { f091(++i); } catch (Exc_TestClass_excep42_E4) { tb = 90; } catch { throw; } } public void f089(int i) { try { f090(++i); } catch (Exc_TestClass_excep42_E4) { tb = 89; } catch { throw; } } public void f088(int i) { try { f089(++i); } catch (Exc_TestClass_excep42_E4) { tb = 88; } catch { throw; } } public void f087(int i) { try { f088(++i); } catch (Exc_TestClass_excep42_E4) { tb = 87; } catch { throw; } } public void f086(int i) { try { f087(++i); } catch (Exc_TestClass_excep42_E4) { tb = 86; } catch { throw; } } public void f085(int i) { try { f086(++i); } catch (Exc_TestClass_excep42_E4) { tb = 85; } catch { throw; } } public void f084(int i) { try { f085(++i); } catch (Exc_TestClass_excep42_E4) { tb = 84; } catch { throw; } } public void f083(int i) { try { f084(++i); } catch (Exc_TestClass_excep42_E4) { tb = 83; } catch { throw; } } public void f082(int i) { try { f083(++i); } catch (Exc_TestClass_excep42_E4) { tb = 82; } catch { throw; } } public void f081(int i) { try { f082(++i); } catch (Exc_TestClass_excep42_E4) { tb = 81; } catch { throw; } } public void f080(int i) { try { f081(++i); } catch (Exc_TestClass_excep42_E4) { tb = 80; } catch { throw; } } public void f079(int i) { try { f080(++i); } catch (Exc_TestClass_excep42_E4) { tb = 79; } catch { throw; } } public void f078(int i) { try { f079(++i); } catch (Exc_TestClass_excep42_E4) { tb = 78; } catch { throw; } } public void f077(int i) { try { f078(++i); } catch (Exc_TestClass_excep42_E4) { tb = 77; } catch { throw; } } public void f076(int i) { try { f077(++i); } catch (Exc_TestClass_excep42_E4) { tb = 76; } catch { throw; } } public void f075(int i) { try { f076(++i); } catch (Exc_TestClass_excep42_E4) { tb = 75; } catch { throw; } } public void f074(int i) { try { f075(++i); } catch (Exc_TestClass_excep42_E4) { tb = 74; } catch { throw; } } public void f073(int i) { try { f074(++i); } catch (Exc_TestClass_excep42_E4) { tb = 73; } catch { throw; } } public void f072(int i) { try { f073(++i); } catch (Exc_TestClass_excep42_E4) { tb = 72; } catch { throw; } } public void f071(int i) { try { f072(++i); } catch (Exc_TestClass_excep42_E4) { tb = 71; } catch { throw; } } public void f070(int i) { try { f071(++i); } catch (Exc_TestClass_excep42_E4) { tb = 70; } catch { throw; } } public void f069(int i) { try { f070(++i); } catch (Exc_TestClass_excep42_E4) { tb = 69; } catch { throw; } } public void f068(int i) { try { f069(++i); } catch (Exc_TestClass_excep42_E4) { tb = 68; } catch { throw; } } public void f067(int i) { try { f068(++i); } catch (Exc_TestClass_excep42_E4) { tb = 67; } catch { throw; } } public void f066(int i) { try { f067(++i); } catch (Exc_TestClass_excep42_E4) { tb = 66; } catch { throw; } } public void f065(int i) { try { f066(++i); } catch (Exc_TestClass_excep42_E4) { tb = 65; } catch { throw; } } public void f064(int i) { try { f065(++i); } catch (Exc_TestClass_excep42_E4) { tb = 64; } catch { throw; } } public void f063(int i) { try { f064(++i); } catch (Exc_TestClass_excep42_E4) { tb = 63; } catch { throw; } } public void f062(int i) { try { f063(++i); } catch (Exc_TestClass_excep42_E4) { tb = 62; } catch { throw; } } public void f061(int i) { try { f062(++i); } catch (Exc_TestClass_excep42_E4) { tb = 61; } catch { throw; } } public void f060(int i) { try { f061(++i); } catch (Exc_TestClass_excep42_E4) { tb = 60; } catch { throw; } } public void f059(int i) { try { f060(++i); } catch (Exc_TestClass_excep42_E4) { tb = 59; } catch { throw; } } public void f058(int i) { try { f059(++i); } catch (Exc_TestClass_excep42_E4) { tb = 58; } catch { throw; } } public void f057(int i) { try { f058(++i); } catch (Exc_TestClass_excep42_E4) { tb = 57; } catch { throw; } } public void f056(int i) { try { f057(++i); } catch (Exc_TestClass_excep42_E4) { tb = 56; } catch { throw; } } public void f055(int i) { try { f056(++i); } catch (Exc_TestClass_excep42_E4) { tb = 55; } catch { throw; } } public void f054(int i) { try { f055(++i); } catch (Exc_TestClass_excep42_E4) { tb = 54; } catch { throw; } } public void f053(int i) { try { f054(++i); } catch (Exc_TestClass_excep42_E4) { tb = 53; } catch { throw; } } public void f052(int i) { try { f053(++i); } catch (Exc_TestClass_excep42_E4) { tb = 52; } catch { throw; } } public void f051(int i) { try { f052(++i); } catch (Exc_TestClass_excep42_E4) { tb = 51; } catch { throw; } } public void f050(int i) { try { f051(++i); } catch (Exc_TestClass_excep42_E4) { tb = 50; } catch { throw; } } public void f049(int i) { try { f050(++i); } catch (Exc_TestClass_excep42_E4) { tb = 49; } catch { throw; } } public void f048(int i) { try { f049(++i); } catch (Exc_TestClass_excep42_E4) { tb = 48; } catch { throw; } } public void f047(int i) { try { f048(++i); } catch (Exc_TestClass_excep42_E4) { tb = 47; } catch { throw; } } public void f046(int i) { try { f047(++i); } catch (Exc_TestClass_excep42_E4) { tb = 46; } catch { throw; } } public void f045(int i) { try { f046(++i); } catch (Exc_TestClass_excep42_E4) { tb = 45; } catch { throw; } } public void f044(int i) { try { f045(++i); } catch (Exc_TestClass_excep42_E4) { tb = 44; } catch { throw; } } public void f043(int i) { try { f044(++i); } catch (Exc_TestClass_excep42_E4) { tb = 43; } catch { throw; } } public void f042(int i) { try { f043(++i); } catch (Exc_TestClass_excep42_E4) { tb = 42; } catch { throw; } } public void f041(int i) { try { f042(++i); } catch (Exc_TestClass_excep42_E4) { tb = 41; } catch { throw; } } public void f040(int i) { try { f041(++i); } catch (Exc_TestClass_excep42_E4) { tb = 40; } catch { throw; } } public void f039(int i) { try { f040(++i); } catch (Exc_TestClass_excep42_E4) { tb = 39; } catch { throw; } } public void f038(int i) { try { f039(++i); } catch (Exc_TestClass_excep42_E4) { tb = 38; } catch { throw; } } public void f037(int i) { try { f038(++i); } catch (Exc_TestClass_excep42_E4) { tb = 37; } catch { throw; } } public void f036(int i) { try { f037(++i); } catch (Exc_TestClass_excep42_E4) { tb = 36; } catch { throw; } } public void f035(int i) { try { f036(++i); } catch (Exc_TestClass_excep42_E4) { tb = 35; } catch { throw; } } public void f034(int i) { try { f035(++i); } catch (Exc_TestClass_excep42_E4) { tb = 34; } catch { throw; } } public void f033(int i) { try { f034(++i); } catch (Exc_TestClass_excep42_E4) { tb = 33; } catch { throw; } } public void f032(int i) { try { f033(++i); } catch (Exc_TestClass_excep42_E4) { tb = 32; } catch { throw; } } public void f031(int i) { try { f032(++i); } catch (Exc_TestClass_excep42_E4) { tb = 31; } catch { throw; } } public void f030(int i) { try { f031(++i); } catch (Exc_TestClass_excep42_E4) { tb = 30; } catch { throw; } } public void f029(int i) { try { f030(++i); } catch (Exc_TestClass_excep42_E4) { tb = 29; } catch { throw; } } public void f028(int i) { try { f029(++i); } catch (Exc_TestClass_excep42_E4) { tb = 28; } catch { throw; } } public void f027(int i) { try { f028(++i); } catch (Exc_TestClass_excep42_E4) { tb = 27; } catch { throw; } } public void f026(int i) { try { f027(++i); } catch (Exc_TestClass_excep42_E4) { tb = 26; } catch { throw; } } public void f025(int i) { try { f026(++i); } catch (Exc_TestClass_excep42_E4) { tb = 25; } catch { throw; } } public void f024(int i) { try { f025(++i); } catch (Exc_TestClass_excep42_E4) { tb = 24; } catch { throw; } } public void f023(int i) { try { f024(++i); } catch (Exc_TestClass_excep42_E4) { tb = 23; } catch { throw; } } public void f022(int i) { try { f023(++i); } catch (Exc_TestClass_excep42_E4) { tb = 22; } catch { throw; } } public void f021(int i) { try { f022(++i); } catch (Exc_TestClass_excep42_E4) { tb = 21; } catch { throw; } } public void f020(int i) { try { f021(++i); } catch (Exc_TestClass_excep42_E4) { tb = 20; } catch { throw; } } public void f019(int i) { try { f020(++i); } catch (Exc_TestClass_excep42_E4) { tb = 19; } catch { throw; } } public void f018(int i) { try { f019(++i); } catch (Exc_TestClass_excep42_E4) { tb = 18; } catch { throw; } } public void f017(int i) { try { f018(++i); } catch (Exc_TestClass_excep42_E4) { tb = 17; } catch { throw; } } public void f016(int i) { try { f017(++i); } catch (Exc_TestClass_excep42_E4) { tb = 16; } catch { throw; } } public void f015(int i) { try { f016(++i); } catch (Exc_TestClass_excep42_E4) { tb = 15; } catch { throw; } } public void f014(int i) { try { f015(++i); } catch (Exc_TestClass_excep42_E4) { tb = 14; } catch { throw; } } public void f013(int i) { try { f014(++i); } catch (Exc_TestClass_excep42_E4) { tb = 13; } catch { throw; } } public void f012(int i) { try { f013(++i); } catch (Exc_TestClass_excep42_E4) { tb = 12; } catch { throw; } } public void f011(int i) { try { f012(++i); } catch (Exc_TestClass_excep42_E4) { tb = 11; } catch { throw; } } public void f010(int i) { try { f011(++i); } catch (Exc_TestClass_excep42_E4) { tb = 10; } catch { throw; } } public void f009(int i) { try { f010(++i); } catch (Exc_TestClass_excep42_E4) { tb = 9; } catch { throw; } } public void f008(int i) { try { f009(++i); } catch (Exc_TestClass_excep42_E4) { tb = 8; } catch { throw; } } public void f007(int i) { try { f008(++i); } catch (Exc_TestClass_excep42_E4) { tb = 7; } catch { throw; } } public void f006(int i) { try { f007(++i); } catch (Exc_TestClass_excep42_E4) { tb = 6; } catch { throw; } } public void f005(int i) { try { f006(++i); } catch (Exc_TestClass_excep42_E4) { tb = 5; } catch { throw; } } public void f004(int i) { try { f005(++i); } catch (Exc_TestClass_excep42_E4) { tb = 4; } catch { throw; } } public void f003(int i) { try { f004(++i); } catch (Exc_TestClass_excep42_E4) { tb = 3; } catch { throw; } } public void f002(int i) { try { f003(++i); } catch (Exc_TestClass_excep42_E4) { tb = 2; } catch { throw; } } public void f001(int i) { try { f002(++i); } catch (Exc_TestClass_excep42_E4) { tb = 1; } catch { throw; } } } public class Exc_TestClass_excep42 { private static int retval = 1; public static int Main_old() { Exc_TestClass_excep42_F f = new Exc_TestClass_excep42_F(); try { f.f001(1); } catch (Exc_TestClass_excep42_E1) { Log.Comment("Caught Exc_TestClass_excep42_E1"); retval = Exc_TestClass_excep42_F.tb; } catch { Log.Comment("Did not catch Exc_TestClass_excep42_E1"); retval = -1; } Log.Comment(retval.ToString()); if (retval == 0) Log.Comment("PASS"); else Log.Comment("FAIL"); return retval; } public static bool testMethod() { return (Main_old() == 0); } } public class Exc_TestClass_excep42b_E1 : Exception { } public class Exc_TestClass_excep42b_E3 : Exception { } public class Exc_TestClass_excep42b_E4 : Exception { } public class Exc_TestClass_excep42b_F { public static int tb = -1; public void f033(int i) { Exc_TestClass_excep42b_E1 s = new Exc_TestClass_excep42b_E1(); Exc_TestClass_excep42b_E3 s1 = new Exc_TestClass_excep42b_E3(); Log.Comment("i==" + i.ToString()); if (i == 33) { Log.Comment("Throwing Exc_TestClass_excep42b_E1"); tb = 0; throw s; } else throw s1; } public void f032(int i) { try { f033(++i); } catch (Exc_TestClass_excep42b_E4) { tb = 32; } catch { throw; } } public void f031(int i) { try { f032(++i); } catch (Exc_TestClass_excep42b_E4) { tb = 31; } catch { throw; } } public void f030(int i) { try { f031(++i); } catch (Exc_TestClass_excep42b_E4) { tb = 30; } catch { throw; } } public void f029(int i) { try { f030(++i); } catch (Exc_TestClass_excep42b_E4) { tb = 29; } catch { throw; } } public void f028(int i) { try { f029(++i); } catch (Exc_TestClass_excep42b_E4) { tb = 28; } catch { throw; } } public void f027(int i) { try { f028(++i); } catch (Exc_TestClass_excep42b_E4) { tb = 27; } catch { throw; } } public void f026(int i) { try { f027(++i); } catch (Exc_TestClass_excep42b_E4) { tb = 26; } catch { throw; } } public void f025(int i) { try { f026(++i); } catch (Exc_TestClass_excep42b_E4) { tb = 25; } catch { throw; } } public void f024(int i) { try { f025(++i); } catch (Exc_TestClass_excep42b_E4) { tb = 24; } catch { throw; } } public void f023(int i) { try { f024(++i); } catch (Exc_TestClass_excep42b_E4) { tb = 23; } catch { throw; } } public void f022(int i) { try { f023(++i); } catch (Exc_TestClass_excep42b_E4) { tb = 22; } catch { throw; } } public void f021(int i) { try { f022(++i); } catch (Exc_TestClass_excep42b_E4) { tb = 21; } catch { throw; } } public void f020(int i) { try { f021(++i); } catch (Exc_TestClass_excep42b_E4) { tb = 20; } catch { throw; } } public void f019(int i) { try { f020(++i); } catch (Exc_TestClass_excep42b_E4) { tb = 19; } catch { throw; } } public void f018(int i) { try { f019(++i); } catch (Exc_TestClass_excep42b_E4) { tb = 18; } catch { throw; } } public void f017(int i) { try { f018(++i); } catch (Exc_TestClass_excep42b_E4) { tb = 17; } catch { throw; } } public void f016(int i) { try { f017(++i); } catch (Exc_TestClass_excep42b_E4) { tb = 16; } catch { throw; } } public void f015(int i) { try { f016(++i); } catch (Exc_TestClass_excep42b_E4) { tb = 15; } catch { throw; } } public void f014(int i) { try { f015(++i); } catch (Exc_TestClass_excep42b_E4) { tb = 14; } catch { throw; } } public void f013(int i) { try { f014(++i); } catch (Exc_TestClass_excep42b_E4) { tb = 13; } catch { throw; } } public void f012(int i) { try { f013(++i); } catch (Exc_TestClass_excep42b_E4) { tb = 12; } catch { throw; } } public void f011(int i) { try { f012(++i); } catch (Exc_TestClass_excep42b_E4) { tb = 11; } catch { throw; } } public void f010(int i) { try { f011(++i); } catch (Exc_TestClass_excep42b_E4) { tb = 10; } catch { throw; } } public void f009(int i) { try { f010(++i); } catch (Exc_TestClass_excep42b_E4) { tb = 9; } catch { throw; } } public void f008(int i) { try { f009(++i); } catch (Exc_TestClass_excep42b_E4) { tb = 8; } catch { throw; } } public void f007(int i) { try { f008(++i); } catch (Exc_TestClass_excep42b_E4) { tb = 7; } catch { throw; } } public void f006(int i) { try { f007(++i); } catch (Exc_TestClass_excep42b_E4) { tb = 6; } catch { throw; } } public void f005(int i) { try { f006(++i); } catch (Exc_TestClass_excep42b_E4) { tb = 5; } catch { throw; } } public void f004(int i) { try { f005(++i); } catch (Exc_TestClass_excep42b_E4) { tb = 4; } catch { throw; } } public void f003(int i) { try { f004(++i); } catch (Exc_TestClass_excep42b_E4) { tb = 3; } catch { throw; } } public void f002(int i) { try { f003(++i); } catch (Exc_TestClass_excep42b_E4) { tb = 2; } catch { throw; } } public void f001(int i) { try { f002(++i); } catch (Exc_TestClass_excep42b_E4) { tb = 1; } catch { throw; } } } public class Exc_TestClass_excep42b { private static int retval = 1; public static int Main_old() { Exc_TestClass_excep42b_F f = new Exc_TestClass_excep42b_F(); try { f.f001(1); } catch (Exc_TestClass_excep42b_E1) { Log.Comment("Caught Exc_TestClass_excep42b_E1"); retval = Exc_TestClass_excep42b_F.tb; } catch { Log.Comment("Did not catch Exc_TestClass_excep42b_E1"); retval = -1; } Log.Comment(retval.ToString()); if (retval == 0) Log.Comment("PASS"); else Log.Comment("FAIL"); return retval; } public static bool testMethod() { return (Main_old() == 0); } } public class Exc_TestClass_excep43_E1 : Exception { } public class Exc_TestClass_excep43_E3 : Exception { } public class Exc_TestClass_excep43_E4 : Exception { } public class Exc_TestClass_excep43_F { public static int tb = -1; public void f255(int i) { Exc_TestClass_excep43_E1 s = new Exc_TestClass_excep43_E1(); Exc_TestClass_excep43_E3 s1 = new Exc_TestClass_excep43_E3(); if (i == 0) throw s; else throw s1; } public void f254(int i) { try { f255(i); } catch (Exc_TestClass_excep43_E4) { tb = 254; } } public void f253(int i) { try { f254(i); } catch (Exc_TestClass_excep43_E4) { tb = 253; } } public void f252(int i) { try { f253(i); } catch (Exc_TestClass_excep43_E4) { tb = 252; } } public void f251(int i) { try { f252(i); } catch (Exc_TestClass_excep43_E4) { tb = 251; } } public void f250(int i) { try { f251(i); } catch (Exc_TestClass_excep43_E4) { tb = 250; } } public void f249(int i) { try { f250(i); } catch (Exc_TestClass_excep43_E4) { tb = 249; } } public void f248(int i) { try { f249(i); } catch (Exc_TestClass_excep43_E4) { tb = 248; } } public void f247(int i) { try { f248(i); } catch (Exc_TestClass_excep43_E4) { tb = 247; } } public void f246(int i) { try { f247(i); } catch (Exc_TestClass_excep43_E4) { tb = 246; } } public void f245(int i) { try { f246(i); } catch (Exc_TestClass_excep43_E4) { tb = 245; } } public void f244(int i) { try { f245(i); } catch (Exc_TestClass_excep43_E4) { tb = 244; } } public void f243(int i) { try { f244(i); } catch (Exc_TestClass_excep43_E4) { tb = 243; } } public void f242(int i) { try { f243(i); } catch (Exc_TestClass_excep43_E4) { tb = 242; } } public void f241(int i) { try { f242(i); } catch (Exc_TestClass_excep43_E4) { tb = 241; } } public void f240(int i) { try { f241(i); } catch (Exc_TestClass_excep43_E4) { tb = 240; } } public void f239(int i) { try { f240(i); } catch (Exc_TestClass_excep43_E4) { tb = 239; } } public void f238(int i) { try { f239(i); } catch (Exc_TestClass_excep43_E4) { tb = 238; } } public void f237(int i) { try { f238(i); } catch (Exc_TestClass_excep43_E4) { tb = 237; } } public void f236(int i) { try { f237(i); } catch (Exc_TestClass_excep43_E4) { tb = 236; } } public void f235(int i) { try { f236(i); } catch (Exc_TestClass_excep43_E4) { tb = 235; } } public void f234(int i) { try { f235(i); } catch (Exc_TestClass_excep43_E4) { tb = 234; } } public void f233(int i) { try { f234(i); } catch (Exc_TestClass_excep43_E4) { tb = 233; } } public void f232(int i) { try { f233(i); } catch (Exc_TestClass_excep43_E4) { tb = 232; } } public void f231(int i) { try { f232(i); } catch (Exc_TestClass_excep43_E4) { tb = 231; } } public void f230(int i) { try { f231(i); } catch (Exc_TestClass_excep43_E4) { tb = 230; } } public void f229(int i) { try { f230(i); } catch (Exc_TestClass_excep43_E4) { tb = 229; } } public void f228(int i) { try { f229(i); } catch (Exc_TestClass_excep43_E4) { tb = 228; } } public void f227(int i) { try { f228(i); } catch (Exc_TestClass_excep43_E4) { tb = 227; } } public void f226(int i) { try { f227(i); } catch (Exc_TestClass_excep43_E4) { tb = 226; } } public void f225(int i) { try { f226(i); } catch (Exc_TestClass_excep43_E4) { tb = 225; } } public void f224(int i) { try { f225(i); } catch (Exc_TestClass_excep43_E4) { tb = 224; } } public void f223(int i) { try { f224(i); } catch (Exc_TestClass_excep43_E4) { tb = 223; } } public void f222(int i) { try { f223(i); } catch (Exc_TestClass_excep43_E4) { tb = 222; } } public void f221(int i) { try { f222(i); } catch (Exc_TestClass_excep43_E4) { tb = 221; } } public void f220(int i) { try { f221(i); } catch (Exc_TestClass_excep43_E4) { tb = 220; } } public void f219(int i) { try { f220(i); } catch (Exc_TestClass_excep43_E4) { tb = 219; } } public void f218(int i) { try { f219(i); } catch (Exc_TestClass_excep43_E4) { tb = 218; } } public void f217(int i) { try { f218(i); } catch (Exc_TestClass_excep43_E4) { tb = 217; } } public void f216(int i) { try { f217(i); } catch (Exc_TestClass_excep43_E4) { tb = 216; } } public void f215(int i) { try { f216(i); } catch (Exc_TestClass_excep43_E4) { tb = 215; } } public void f214(int i) { try { f215(i); } catch (Exc_TestClass_excep43_E4) { tb = 214; } } public void f213(int i) { try { f214(i); } catch (Exc_TestClass_excep43_E4) { tb = 213; } } public void f212(int i) { try { f213(i); } catch (Exc_TestClass_excep43_E4) { tb = 212; } } public void f211(int i) { try { f212(i); } catch (Exc_TestClass_excep43_E4) { tb = 211; } } public void f210(int i) { try { f211(i); } catch (Exc_TestClass_excep43_E4) { tb = 210; } } public void f209(int i) { try { f210(i); } catch (Exc_TestClass_excep43_E4) { tb = 209; } } public void f208(int i) { try { f209(i); } catch (Exc_TestClass_excep43_E4) { tb = 208; } } public void f207(int i) { try { f208(i); } catch (Exc_TestClass_excep43_E4) { tb = 207; } } public void f206(int i) { try { f207(i); } catch (Exc_TestClass_excep43_E4) { tb = 206; } } public void f205(int i) { try { f206(i); } catch (Exc_TestClass_excep43_E4) { tb = 205; } } public void f204(int i) { try { f205(i); } catch (Exc_TestClass_excep43_E4) { tb = 204; } } public void f203(int i) { try { f204(i); } catch (Exc_TestClass_excep43_E4) { tb = 203; } } public void f202(int i) { try { f203(i); } catch (Exc_TestClass_excep43_E4) { tb = 202; } } public void f201(int i) { try { f202(i); } catch (Exc_TestClass_excep43_E4) { tb = 201; } } public void f200(int i) { try { f201(i); } catch (Exc_TestClass_excep43_E4) { tb = 200; } } public void f199(int i) { try { f200(i); } catch (Exc_TestClass_excep43_E4) { tb = 199; } } public void f198(int i) { try { f199(i); } catch (Exc_TestClass_excep43_E4) { tb = 198; } } public void f197(int i) { try { f198(i); } catch (Exc_TestClass_excep43_E4) { tb = 197; } } public void f196(int i) { try { f197(i); } catch (Exc_TestClass_excep43_E4) { tb = 196; } } public void f195(int i) { try { f196(i); } catch (Exc_TestClass_excep43_E4) { tb = 195; } } public void f194(int i) { try { f195(i); } catch (Exc_TestClass_excep43_E4) { tb = 194; } } public void f193(int i) { try { f194(i); } catch (Exc_TestClass_excep43_E4) { tb = 193; } } public void f192(int i) { try { f193(i); } catch (Exc_TestClass_excep43_E4) { tb = 192; } } public void f191(int i) { try { f192(i); } catch (Exc_TestClass_excep43_E4) { tb = 191; } } public void f190(int i) { try { f191(i); } catch (Exc_TestClass_excep43_E4) { tb = 190; } } public void f189(int i) { try { f190(i); } catch (Exc_TestClass_excep43_E4) { tb = 189; } } public void f188(int i) { try { f189(i); } catch (Exc_TestClass_excep43_E4) { tb = 188; } } public void f187(int i) { try { f188(i); } catch (Exc_TestClass_excep43_E4) { tb = 187; } } public void f186(int i) { try { f187(i); } catch (Exc_TestClass_excep43_E4) { tb = 186; } } public void f185(int i) { try { f186(i); } catch (Exc_TestClass_excep43_E4) { tb = 185; } } public void f184(int i) { try { f185(i); } catch (Exc_TestClass_excep43_E4) { tb = 184; } } public void f183(int i) { try { f184(i); } catch (Exc_TestClass_excep43_E4) { tb = 183; } } public void f182(int i) { try { f183(i); } catch (Exc_TestClass_excep43_E4) { tb = 182; } } public void f181(int i) { try { f182(i); } catch (Exc_TestClass_excep43_E4) { tb = 181; } } public void f180(int i) { try { f181(i); } catch (Exc_TestClass_excep43_E4) { tb = 180; } } public void f179(int i) { try { f180(i); } catch (Exc_TestClass_excep43_E4) { tb = 179; } } public void f178(int i) { try { f179(i); } catch (Exc_TestClass_excep43_E4) { tb = 178; } } public void f177(int i) { try { f178(i); } catch (Exc_TestClass_excep43_E4) { tb = 177; } } public void f176(int i) { try { f177(i); } catch (Exc_TestClass_excep43_E4) { tb = 176; } } public void f175(int i) { try { f176(i); } catch (Exc_TestClass_excep43_E4) { tb = 175; } } public void f174(int i) { try { f175(i); } catch (Exc_TestClass_excep43_E4) { tb = 174; } } public void f173(int i) { try { f174(i); } catch (Exc_TestClass_excep43_E4) { tb = 173; } } public void f172(int i) { try { f173(i); } catch (Exc_TestClass_excep43_E4) { tb = 172; } } public void f171(int i) { try { f172(i); } catch (Exc_TestClass_excep43_E4) { tb = 171; } } public void f170(int i) { try { f171(i); } catch (Exc_TestClass_excep43_E4) { tb = 170; } } public void f169(int i) { try { f170(i); } catch (Exc_TestClass_excep43_E4) { tb = 169; } } public void f168(int i) { try { f169(i); } catch (Exc_TestClass_excep43_E4) { tb = 168; } } public void f167(int i) { try { f168(i); } catch (Exc_TestClass_excep43_E4) { tb = 167; } } public void f166(int i) { try { f167(i); } catch (Exc_TestClass_excep43_E4) { tb = 166; } } public void f165(int i) { try { f166(i); } catch (Exc_TestClass_excep43_E4) { tb = 165; } } public void f164(int i) { try { f165(i); } catch (Exc_TestClass_excep43_E4) { tb = 164; } } public void f163(int i) { try { f164(i); } catch (Exc_TestClass_excep43_E4) { tb = 163; } } public void f162(int i) { try { f163(i); } catch (Exc_TestClass_excep43_E4) { tb = 162; } } public void f161(int i) { try { f162(i); } catch (Exc_TestClass_excep43_E4) { tb = 161; } } public void f160(int i) { try { f161(i); } catch (Exc_TestClass_excep43_E4) { tb = 160; } } public void f159(int i) { try { f160(i); } catch (Exc_TestClass_excep43_E4) { tb = 159; } } public void f158(int i) { try { f159(i); } catch (Exc_TestClass_excep43_E4) { tb = 158; } } public void f157(int i) { try { f158(i); } catch (Exc_TestClass_excep43_E4) { tb = 157; } } public void f156(int i) { try { f157(i); } catch (Exc_TestClass_excep43_E4) { tb = 156; } } public void f155(int i) { try { f156(i); } catch (Exc_TestClass_excep43_E4) { tb = 155; } } public void f154(int i) { try { f155(i); } catch (Exc_TestClass_excep43_E4) { tb = 154; } } public void f153(int i) { try { f154(i); } catch (Exc_TestClass_excep43_E4) { tb = 153; } } public void f152(int i) { try { f153(i); } catch (Exc_TestClass_excep43_E4) { tb = 152; } } public void f151(int i) { try { f152(i); } catch (Exc_TestClass_excep43_E4) { tb = 151; } } public void f150(int i) { try { f151(i); } catch (Exc_TestClass_excep43_E4) { tb = 150; } } public void f149(int i) { try { f150(i); } catch (Exc_TestClass_excep43_E4) { tb = 149; } } public void f148(int i) { try { f149(i); } catch (Exc_TestClass_excep43_E4) { tb = 148; } } public void f147(int i) { try { f148(i); } catch (Exc_TestClass_excep43_E4) { tb = 147; } } public void f146(int i) { try { f147(i); } catch (Exc_TestClass_excep43_E4) { tb = 146; } } public void f145(int i) { try { f146(i); } catch (Exc_TestClass_excep43_E4) { tb = 145; } } public void f144(int i) { try { f145(i); } catch (Exc_TestClass_excep43_E4) { tb = 144; } } public void f143(int i) { try { f144(i); } catch (Exc_TestClass_excep43_E4) { tb = 143; } } public void f142(int i) { try { f143(i); } catch (Exc_TestClass_excep43_E4) { tb = 142; } } public void f141(int i) { try { f142(i); } catch (Exc_TestClass_excep43_E4) { tb = 141; } } public void f140(int i) { try { f141(i); } catch (Exc_TestClass_excep43_E4) { tb = 140; } } public void f139(int i) { try { f140(i); } catch (Exc_TestClass_excep43_E4) { tb = 139; } } public void f138(int i) { try { f139(i); } catch (Exc_TestClass_excep43_E4) { tb = 138; } } public void f137(int i) { try { f138(i); } catch (Exc_TestClass_excep43_E4) { tb = 137; } } public void f136(int i) { try { f137(i); } catch (Exc_TestClass_excep43_E4) { tb = 136; } } public void f135(int i) { try { f136(i); } catch (Exc_TestClass_excep43_E4) { tb = 135; } } public void f134(int i) { try { f135(i); } catch (Exc_TestClass_excep43_E4) { tb = 134; } } public void f133(int i) { try { f134(i); } catch (Exc_TestClass_excep43_E4) { tb = 133; } } public void f132(int i) { try { f133(i); } catch (Exc_TestClass_excep43_E4) { tb = 132; } } public void f131(int i) { try { f132(i); } catch (Exc_TestClass_excep43_E4) { tb = 131; } } public void f130(int i) { try { f131(i); } catch (Exc_TestClass_excep43_E4) { tb = 130; } } public void f129(int i) { try { f130(i); } catch (Exc_TestClass_excep43_E4) { tb = 129; } } public void f128(int i) { try { f129(i); } catch (Exc_TestClass_excep43_E4) { tb = 128; } } public void f127(int i) { try { f128(i); } catch (Exc_TestClass_excep43_E4) { tb = 127; } } public void f126(int i) { try { f127(i); } catch (Exc_TestClass_excep43_E4) { tb = 126; } } public void f125(int i) { try { f126(i); } catch (Exc_TestClass_excep43_E4) { tb = 125; } } public void f124(int i) { try { f125(i); } catch (Exc_TestClass_excep43_E4) { tb = 124; } } public void f123(int i) { try { f124(i); } catch (Exc_TestClass_excep43_E4) { tb = 123; } } public void f122(int i) { try { f123(i); } catch (Exc_TestClass_excep43_E4) { tb = 122; } } public void f121(int i) { try { f122(i); } catch (Exc_TestClass_excep43_E4) { tb = 121; } } public void f120(int i) { try { f121(i); } catch (Exc_TestClass_excep43_E4) { tb = 120; } } public void f119(int i) { try { f120(i); } catch (Exc_TestClass_excep43_E4) { tb = 119; } } public void f118(int i) { try { f119(i); } catch (Exc_TestClass_excep43_E4) { tb = 118; } } public void f117(int i) { try { f118(i); } catch (Exc_TestClass_excep43_E4) { tb = 117; } } public void f116(int i) { try { f117(i); } catch (Exc_TestClass_excep43_E4) { tb = 116; } } public void f115(int i) { try { f116(i); } catch (Exc_TestClass_excep43_E4) { tb = 115; } } public void f114(int i) { try { f115(i); } catch (Exc_TestClass_excep43_E4) { tb = 114; } } public void f113(int i) { try { f114(i); } catch (Exc_TestClass_excep43_E4) { tb = 113; } } public void f112(int i) { try { f113(i); } catch (Exc_TestClass_excep43_E4) { tb = 112; } } public void f111(int i) { try { f112(i); } catch (Exc_TestClass_excep43_E4) { tb = 111; } } public void f110(int i) { try { f111(i); } catch (Exc_TestClass_excep43_E4) { tb = 110; } } public void f109(int i) { try { f110(i); } catch (Exc_TestClass_excep43_E4) { tb = 109; } } public void f108(int i) { try { f109(i); } catch (Exc_TestClass_excep43_E4) { tb = 108; } } public void f107(int i) { try { f108(i); } catch (Exc_TestClass_excep43_E4) { tb = 107; } } public void f106(int i) { try { f107(i); } catch (Exc_TestClass_excep43_E4) { tb = 106; } } public void f105(int i) { try { f106(i); } catch (Exc_TestClass_excep43_E4) { tb = 105; } } public void f104(int i) { try { f105(i); } catch (Exc_TestClass_excep43_E4) { tb = 104; } } public void f103(int i) { try { f104(i); } catch (Exc_TestClass_excep43_E4) { tb = 103; } } public void f102(int i) { try { f103(i); } catch (Exc_TestClass_excep43_E4) { tb = 102; } } public void f101(int i) { try { f102(i); } catch (Exc_TestClass_excep43_E4) { tb = 101; } } public void f100(int i) { try { f101(i); } catch (Exc_TestClass_excep43_E4) { tb = 100; } } public void f099(int i) { try { f100(i); } catch (Exc_TestClass_excep43_E4) { tb = 99; } } public void f098(int i) { try { f099(i); } catch (Exc_TestClass_excep43_E4) { tb = 98; } } public void f097(int i) { try { f098(i); } catch (Exc_TestClass_excep43_E4) { tb = 97; } } public void f096(int i) { try { f097(i); } catch (Exc_TestClass_excep43_E4) { tb = 96; } } public void f095(int i) { try { f096(i); } catch (Exc_TestClass_excep43_E4) { tb = 95; } } public void f094(int i) { try { f095(i); } catch (Exc_TestClass_excep43_E4) { tb = 94; } } public void f093(int i) { try { f094(i); } catch (Exc_TestClass_excep43_E4) { tb = 93; } } public void f092(int i) { try { f093(i); } catch (Exc_TestClass_excep43_E4) { tb = 92; } } public void f091(int i) { try { f092(i); } catch (Exc_TestClass_excep43_E4) { tb = 91; } } public void f090(int i) { try { f091(i); } catch (Exc_TestClass_excep43_E4) { tb = 90; } } public void f089(int i) { try { f090(i); } catch (Exc_TestClass_excep43_E4) { tb = 89; } } public void f088(int i) { try { f089(i); } catch (Exc_TestClass_excep43_E4) { tb = 88; } } public void f087(int i) { try { f088(i); } catch (Exc_TestClass_excep43_E4) { tb = 87; } } public void f086(int i) { try { f087(i); } catch (Exc_TestClass_excep43_E4) { tb = 86; } } public void f085(int i) { try { f086(i); } catch (Exc_TestClass_excep43_E4) { tb = 85; } } public void f084(int i) { try { f085(i); } catch (Exc_TestClass_excep43_E4) { tb = 84; } } public void f083(int i) { try { f084(i); } catch (Exc_TestClass_excep43_E4) { tb = 83; } } public void f082(int i) { try { f083(i); } catch (Exc_TestClass_excep43_E4) { tb = 82; } } public void f081(int i) { try { f082(i); } catch (Exc_TestClass_excep43_E4) { tb = 81; } } public void f080(int i) { try { f081(i); } catch (Exc_TestClass_excep43_E4) { tb = 80; } } public void f079(int i) { try { f080(i); } catch (Exc_TestClass_excep43_E4) { tb = 79; } } public void f078(int i) { try { f079(i); } catch (Exc_TestClass_excep43_E4) { tb = 78; } } public void f077(int i) { try { f078(i); } catch (Exc_TestClass_excep43_E4) { tb = 77; } } public void f076(int i) { try { f077(i); } catch (Exc_TestClass_excep43_E4) { tb = 76; } } public void f075(int i) { try { f076(i); } catch (Exc_TestClass_excep43_E4) { tb = 75; } } public void f074(int i) { try { f075(i); } catch (Exc_TestClass_excep43_E4) { tb = 74; } } public void f073(int i) { try { f074(i); } catch (Exc_TestClass_excep43_E4) { tb = 73; } } public void f072(int i) { try { f073(i); } catch (Exc_TestClass_excep43_E4) { tb = 72; } } public void f071(int i) { try { f072(i); } catch (Exc_TestClass_excep43_E4) { tb = 71; } } public void f070(int i) { try { f071(i); } catch (Exc_TestClass_excep43_E4) { tb = 70; } } public void f069(int i) { try { f070(i); } catch (Exc_TestClass_excep43_E4) { tb = 69; } } public void f068(int i) { try { f069(i); } catch (Exc_TestClass_excep43_E4) { tb = 68; } } public void f067(int i) { try { f068(i); } catch (Exc_TestClass_excep43_E4) { tb = 67; } } public void f066(int i) { try { f067(i); } catch (Exc_TestClass_excep43_E4) { tb = 66; } } public void f065(int i) { try { f066(i); } catch (Exc_TestClass_excep43_E4) { tb = 65; } } public void f064(int i) { try { f065(i); } catch (Exc_TestClass_excep43_E4) { tb = 64; } } public void f063(int i) { try { f064(i); } catch (Exc_TestClass_excep43_E4) { tb = 63; } } public void f062(int i) { try { f063(i); } catch (Exc_TestClass_excep43_E4) { tb = 62; } } public void f061(int i) { try { f062(i); } catch (Exc_TestClass_excep43_E4) { tb = 61; } } public void f060(int i) { try { f061(i); } catch (Exc_TestClass_excep43_E4) { tb = 60; } } public void f059(int i) { try { f060(i); } catch (Exc_TestClass_excep43_E4) { tb = 59; } } public void f058(int i) { try { f059(i); } catch (Exc_TestClass_excep43_E4) { tb = 58; } } public void f057(int i) { try { f058(i); } catch (Exc_TestClass_excep43_E4) { tb = 57; } } public void f056(int i) { try { f057(i); } catch (Exc_TestClass_excep43_E4) { tb = 56; } } public void f055(int i) { try { f056(i); } catch (Exc_TestClass_excep43_E4) { tb = 55; } } public void f054(int i) { try { f055(i); } catch (Exc_TestClass_excep43_E4) { tb = 54; } } public void f053(int i) { try { f054(i); } catch (Exc_TestClass_excep43_E4) { tb = 53; } } public void f052(int i) { try { f053(i); } catch (Exc_TestClass_excep43_E4) { tb = 52; } } public void f051(int i) { try { f052(i); } catch (Exc_TestClass_excep43_E4) { tb = 51; } } public void f050(int i) { try { f051(i); } catch (Exc_TestClass_excep43_E4) { tb = 50; } } public void f049(int i) { try { f050(i); } catch (Exc_TestClass_excep43_E4) { tb = 49; } } public void f048(int i) { try { f049(i); } catch (Exc_TestClass_excep43_E4) { tb = 48; } } public void f047(int i) { try { f048(i); } catch (Exc_TestClass_excep43_E4) { tb = 47; } } public void f046(int i) { try { f047(i); } catch (Exc_TestClass_excep43_E4) { tb = 46; } } public void f045(int i) { try { f046(i); } catch (Exc_TestClass_excep43_E4) { tb = 45; } } public void f044(int i) { try { f045(i); } catch (Exc_TestClass_excep43_E4) { tb = 44; } } public void f043(int i) { try { f044(i); } catch (Exc_TestClass_excep43_E4) { tb = 43; } } public void f042(int i) { try { f043(i); } catch (Exc_TestClass_excep43_E4) { tb = 42; } } public void f041(int i) { try { f042(i); } catch (Exc_TestClass_excep43_E4) { tb = 41; } } public void f040(int i) { try { f041(i); } catch (Exc_TestClass_excep43_E4) { tb = 40; } } public void f039(int i) { try { f040(i); } catch (Exc_TestClass_excep43_E4) { tb = 39; } } public void f038(int i) { try { f039(i); } catch (Exc_TestClass_excep43_E4) { tb = 38; } } public void f037(int i) { try { f038(i); } catch (Exc_TestClass_excep43_E4) { tb = 37; } } public void f036(int i) { try { f037(i); } catch (Exc_TestClass_excep43_E4) { tb = 36; } } public void f035(int i) { try { f036(i); } catch (Exc_TestClass_excep43_E4) { tb = 35; } } public void f034(int i) { try { f035(i); } catch (Exc_TestClass_excep43_E4) { tb = 34; } } public void f033(int i) { try { f034(i); } catch (Exc_TestClass_excep43_E4) { tb = 33; } } public void f032(int i) { try { f033(i); } catch (Exc_TestClass_excep43_E4) { tb = 32; } } public void f031(int i) { try { f032(i); } catch (Exc_TestClass_excep43_E4) { tb = 31; } } public void f030(int i) { try { f031(i); } catch (Exc_TestClass_excep43_E4) { tb = 30; } } public void f029(int i) { try { f030(i); } catch (Exc_TestClass_excep43_E4) { tb = 29; } } public void f028(int i) { try { f029(i); } catch (Exc_TestClass_excep43_E4) { tb = 28; } } public void f027(int i) { try { f028(i); } catch (Exc_TestClass_excep43_E4) { tb = 27; } } public void f026(int i) { try { f027(i); } catch (Exc_TestClass_excep43_E4) { tb = 26; } } public void f025(int i) { try { f026(i); } catch (Exc_TestClass_excep43_E4) { tb = 25; } } public void f024(int i) { try { f025(i); } catch (Exc_TestClass_excep43_E4) { tb = 24; } } public void f023(int i) { try { f024(i); } catch (Exc_TestClass_excep43_E4) { tb = 23; } } public void f022(int i) { try { f023(i); } catch (Exc_TestClass_excep43_E4) { tb = 22; } } public void f021(int i) { try { f022(i); } catch (Exc_TestClass_excep43_E4) { tb = 21; } } public void f020(int i) { try { f021(i); } catch (Exc_TestClass_excep43_E4) { tb = 20; } } public void f019(int i) { try { f020(i); } catch (Exc_TestClass_excep43_E4) { tb = 19; } } public void f018(int i) { try { f019(i); } catch (Exc_TestClass_excep43_E4) { tb = 18; } } public void f017(int i) { try { f018(i); } catch (Exc_TestClass_excep43_E4) { tb = 17; } } public void f016(int i) { try { f017(i); } catch (Exc_TestClass_excep43_E4) { tb = 16; } } public void f015(int i) { try { f016(i); } catch (Exc_TestClass_excep43_E4) { tb = 15; } } public void f014(int i) { try { f015(i); } catch (Exc_TestClass_excep43_E4) { tb = 14; } } public void f013(int i) { try { f014(i); } catch (Exc_TestClass_excep43_E4) { tb = 13; } } public void f012(int i) { try { f013(i); } catch (Exc_TestClass_excep43_E4) { tb = 12; } } public void f011(int i) { try { f012(i); } catch (Exc_TestClass_excep43_E4) { tb = 11; } } public void f010(int i) { try { f011(i); } catch (Exc_TestClass_excep43_E4) { tb = 10; } } public void f009(int i) { try { f010(i); } catch (Exc_TestClass_excep43_E4) { tb = 9; } } public void f008(int i) { try { f009(i); } catch (Exc_TestClass_excep43_E4) { tb = 8; } } public void f007(int i) { try { f008(i); } catch (Exc_TestClass_excep43_E4) { tb = 7; } } public void f006(int i) { try { f007(i); } catch (Exc_TestClass_excep43_E4) { tb = 6; } } public void f005(int i) { try { f006(i); } catch (Exc_TestClass_excep43_E4) { tb = 5; } } public void f004(int i) { try { f005(i); } catch (Exc_TestClass_excep43_E4) { tb = 4; } } public void f003(int i) { try { f004(i); } catch (Exc_TestClass_excep43_E4) { tb = 3; } } public void f002(int i) { try { f003(i); } catch (Exc_TestClass_excep43_E4) { tb = 2; } } public void f001(int i) { try { f002(i); } catch (Exc_TestClass_excep43_E4) { tb = 1; } } } public class Exc_TestClass_excep43 { private static int retval = 1; public static int Main_old() { Exc_TestClass_excep43_F f = new Exc_TestClass_excep43_F(); try { f.f001(1); } catch (Exc_TestClass_excep43_E1) { retval += Exc_TestClass_excep43_F.tb; } catch (Exc_TestClass_excep43_E3) { retval = 0; } if (retval == 0) Log.Comment("PASS"); else Log.Comment("FAIL, retval=={0 }" + retval.ToString()); return retval; } public static bool testMethod() { return (Main_old() == 0); } } public class Exc_TestClass_excep56 { private static int retval = 2; public static int Main_old() { try { Log.Comment("In try block."); } finally { goto lab1; //This should cause an error Log.Comment("Entering finally block"); retval -= 1; lab1: retval -= 2; } Log.Comment("Ready to return."); if (0 == retval) Log.Comment("PASS"); else Log.Comment("FAIL, retval=={0} " + retval.ToString()); return retval; } public static bool testMethod() { return (Main_old() == 0); } } public class Exc_TestClass_excep57 { private static int retval = 5; public static int Main_old() { try { Log.Comment("In try block."); } finally { goto lab4; //This should cause an error Log.Comment("Entering finally block"); retval -= 1; lab1: retval -= 2; lab2: retval -= 3; lab3: retval -= 4; lab4: retval -= 5; } Log.Comment("Ready to return."); if (0 == retval) Log.Comment("PASS"); else Log.Comment("FAIL, retval=={0}" + retval.ToString()); return retval; } public static bool testMethod() { return (Main_old() == 0); } } public class Exc_TestClass_excep58_E1 : Exception { public Exc_TestClass_excep58_E1(String str) : base(str) { } } public class Exc_TestClass_excep58 { private static int retval = 0x07; public static int Main_old() { try { try { Log.Comment("In try block, ready to throw."); throw new Exc_TestClass_excep58_E1("An exception has occurred"); } //catch (Exception s){ // Log.Comment ("In catch block."); // Log.Comment (s.Message); //} finally { Log.Comment("In inner finally block"); retval ^= 0x01; } } catch (Exc_TestClass_excep58_E1 s) { if (0 == (retval & 0x01)) retval ^= 0x02; Log.Comment("In catch block."); Log.Comment(s.Message); } catch (Exception) { Log.Comment("FAIL -- Should not enter catch (Exception) block"); retval++; } finally { Log.Comment("In outer finally block"); if (0 == (retval & 0x03)) retval ^= 0x04; } if (0 == retval) Log.Comment("PASS"); else Log.Comment("FAIL, retval == " + retval.ToString()); return retval; } public static bool testMethod() { return (Main_old() == 0); } } public class Exc_TestClass_excep59_E1 : Exception { public Exc_TestClass_excep59_E1(String str) : base(str) { } } public class Exc_TestClass_excep59 { private static int retval = 0x0F; public static int Main_old() { try { try { try { Log.Comment("In try block, ready to throw."); throw new Exc_TestClass_excep59_E1("An exception has occurred"); } //catch (Exception s) //{ // Log.Comment ("In catch block."); // Log.Comment (s.Message); //} finally { Log.Comment("In innermost finally block"); retval ^= 0x01; } } //catch (Exception s){ // Log.Comment ("In catch block."); // Log.Comment (s.Message); //} finally { Log.Comment("In middle finally block"); if (0 == (retval & 0x01)) retval ^= 0x02; } } catch (Exc_TestClass_excep59_E1 s) { if (0 == (retval & 0x03)) retval ^= 0x04; Log.Comment("In catch block."); Log.Comment(s.Message); } catch (Exception) { Log.Comment("FAIL -- Should not enter catch (Exception) block"); retval++; } finally { Log.Comment("In outer finally block"); if (0 == (retval & 0x07)) retval ^= 0x08; } if (0 == retval) Log.Comment("PASS"); else Log.Comment("FAIL, retval == " + retval.ToString()); return retval; } public static bool testMethod() { return (Main_old() == 0); } } public class Exc_TestClass_excep60_E1 : Exception { public Exc_TestClass_excep60_E1(String str) : base(str) { } } public class Exc_TestClass_excep60 { private static int retval = 0x3F; public static int Main_old() { try { try { try { Log.Comment("In try block, ready to throw."); throw new Exc_TestClass_excep60_E1("An exception has occurred"); } //catch (Exception s) //{ // Log.Comment ("In catch block."); // Log.Comment (s.Message); //} finally { Log.Comment("In innermost finally block"); retval ^= 0x01; } } catch (Exc_TestClass_excep60_E1 s) { Log.Comment("In catch block."); Log.Comment(s.Message); if (0 == (retval & 0x01)) retval ^= 0x02; throw new Exception("Setting InnerException", s); } finally { Log.Comment("In middle finally block"); if (0 == (retval & 0x03)) retval ^= 0x04; } } catch (Exception s) { if (0 == (retval & 0x07)) retval ^= 0x08; Log.Comment("In outer catch block."); if (typeof(Exc_TestClass_excep60_E1) == s.InnerException.GetType()) retval ^= 0x10; } //catch (Exception) { // Log.Comment ("FAIL -- Should not enter catch (Exception) block"); // retval ++; //} finally { Log.Comment("In outer finally block"); if (0 == (retval & 0x1F)) retval ^= 0x20; } if (0 == retval) Log.Comment("PASS"); else Log.Comment("FAIL, retval == 0x" + retval.ToString()); return retval; } public static bool testMethod() { return (Main_old() == 0); } } public class Exc_TestClass_excep61_E1 : Exception { public Exc_TestClass_excep61_E1(String str) : base(str) { } } public class Exc_TestClass_excep61 { private static int retval = 0x7F; public static int Main_old() { try { try { try { Log.Comment("In try block, ready to throw."); throw new Exc_TestClass_excep61_E1("An exception has occurred"); } catch (Exc_TestClass_excep61_E1 s) { Log.Comment("In catch block."); Log.Comment(s.Message); throw new Exception("Setting InnerException #1", s); } finally { Log.Comment("In innermost finally block"); retval ^= 0x01; } } catch (Exception s) { Log.Comment("In catch block."); Log.Comment(s.Message); if (0 == (retval & 0x01)) retval ^= 0x02; throw new Exception("Setting InnerException 2", s); } finally { Log.Comment("In middle finally block"); if (0 == (retval & 0x03)) retval ^= 0x04; } } catch (Exception s) { if (0 == (retval & 0x07)) retval ^= 0x08; Log.Comment("In outer catch block."); if (typeof(Exception) == s.InnerException.GetType()) retval ^= 0x10; if (typeof(Exc_TestClass_excep61_E1) == s.InnerException.InnerException.GetType()) retval ^= 0x20; } //catch (Exception) { // Log.Comment ("FAIL -- Should not enter catch (Exception) block"); // retval ++; //} finally { Log.Comment("In outer finally block"); if (0 == (retval & 0x1F)) retval ^= 0x40; } if (0 == retval) Log.Comment("PASS"); else Log.Comment("FAIL, retval == 0x" + retval.ToString()); return retval; } public static bool testMethod() { return (Main_old() == 0); } } public class Exc_TestClass_excep62_E1 : Exception { public Exc_TestClass_excep62_E1(String str) : base(str) { } } public class Exc_TestClass_excep62 { private static int retval = 0x03; public static int Main_old() { try { Log.Comment("In try block, ready to throw."); throw new Exception("An exception has occurred"); } catch (Exception s) { if (null == s.InnerException) retval ^= 0x01; } //catch (Exception) { // Log.Comment ("FAIL -- Should not enter catch (Exception) block"); // retval ++; //} finally { Log.Comment("In outer finally block"); if (0 == (retval & 0x01)) retval ^= 0x02; } if (0 == retval) Log.Comment("PASS"); else Log.Comment("FAIL, retval == 0x" + retval.ToString()); return retval; } public static bool testMethod() { return (Main_old() == 0); } } public class Exc_TestClass_excep63_E1 : Exception { public Exc_TestClass_excep63_E1(String str) : base(str) { } } public class Exc_TestClass_excep63_SC { static Exc_TestClass_excep63_SC() { InitHelper(); } public static void InitHelper() { Log.Comment("This is bug number: 21724 Resolved By Design."); Log.Comment("This is bug number: 21724 If a catch search reaches a static ctor then a Exception is thrown at the point of static ctor invocation. The inner exception is the original exception. "); Log.Comment("When this bug is fixed change remove the comment below."); // throw new Exception("Exception in InitHelper"); } } public class Exc_TestClass_excep63 { private static int retval = 0x01; public static int Main_old() { try { Exc_TestClass_excep63_SC sc = new Exc_TestClass_excep63_SC(); } catch (Exception t) { if (t.InnerException.GetType() == typeof(Exception)) retval ^= 0x01; } if (0 == retval) Log.Comment("PASS"); else Log.Comment("FAIL, retval == 0x" + retval.ToString()); return retval; } public static bool testMethod() { return (Main_old() == 0); } } public class Exc_TestClass_excep64_E1 : Exception { public Exc_TestClass_excep64_E1(String str) : base(str) { } } public class Exc_TestClass_excep64_SC { public static int StaticInt = InitHelper(); public static int InitHelper() { Log.Comment("This is bug number: 21724 Resolved By Design."); Log.Comment("This is bug number: 21724 If a catch search reaches a static ctor then a Exception is thrown at the point of static ctor invocation. The inner exception is the original exception. "); Log.Comment("When this bug is fixed change this back to pass and chang eht known failure to fail"); // throw new Exception("Exception in InitHelper"); return 0; } } public class Exc_TestClass_excep64 { private static int retval = 0x01; public static int Main_old() { try { Exc_TestClass_excep64_SC sc = new Exc_TestClass_excep64_SC(); } catch (Exception t) { if (t.InnerException.GetType() == typeof(Exception)) retval ^= 0x01; } if (0 == retval) Log.Comment("PASS"); else Log.Comment("FAIL, retval == 0x" + retval.ToString()); return retval; } public static bool testMethod() { return (Main_old() == 0); } } /* public class Exc_TestClass_excep65_E1 : Exception { public Exc_TestClass_excep65_E1(String str) : base(str) { } } public class Exc_TestClass_excep65_C1 { public static int retval = 0x01; ~Exc_TestClass_excep65_C1() { retval ^= 0x01; Log.Comment("retval == " + retval.ToString()); Log.Comment("In// Exc_TestClass_excep65_C1()"); } } public class Exc_TestClass_excep65_C2 : Exc_TestClass_excep65_C1 { } public class Derived : Exc_TestClass_excep65_C2 { ~Derived() { Log.Comment("In ~Derived()"); DtorHelper(); Log.Comment("FAIL, did not exit dtor when exception thrown"); Exc_TestClass_excep65_C1.retval |= 0x02; } public static void DtorHelper() { throw new Exception("Exception in DtorHelper"); } } public class Exc_TestClass_excep65 { public static int Main_old() { Derived sc = new Derived(); sc = null; Microsoft.SPOT.Debug.GC(true); System.Threading.Thread.Sleep(100); return Exc_TestClass_excep65_C1.retval; } public static bool testMethod() { return (Main_old() == 0); } } */ } } ================================================ FILE: Zelig/Zelig/Test/RunTime/NETMF/mscorlib/expressions/expressions1/ArithmeticTests1.cs ================================================ //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // Copyright (c) Microsoft Corporation. All rights reserved. //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// using System; using System.Reflection; using Microsoft.SPOT.Platform.Test; namespace Microsoft.SPOT.Platform.Tests { public class ArithmeticTests1 : IMFTestInterface { [SetUp] public InitializeResult Initialize() { Log.Comment("Adding set up for the tests"); // Add your functionality here. return InitializeResult.ReadyToGo; } [TearDown] public void CleanUp() { Log.Comment("Cleaning up after the tests"); } //Arithmetic Test methods //The following tests were ported from folder current\test\cases\client\CLR\Conformance\10_classes\Arithmetic //arith001,arith003,arith005,arith007,arith023,arith024,arith028,arith029,arith030,arith031,arith032,arith033,arith034,arith035,arith036,arith037,arith038,arith039,arith040,arith041,arith042,arith043,arith044,arith045,arith046,arith047,arith048,arith049,arith050,arith051,arith052,arith053,arith054,arith055,arith056,arith057,arith058,arith059,arith060,arith061,arith062,arith064,arith065 //opt001a,opt001b,opt002a,opt002b,opt003a,opt003b,opt004a,opt004b,mult0001,mult0002,mult0003,mult0004,mult0008,mult0009,mult0010,mult0011,mult0015,mult0016,mult0017,mult0018,mult0022,mult0023,mult0024,mult0025,mult0050,mult0051,mult0052,mult0053,mult0057,mult0058,mult0059,mult0060,mult0064,mult0065,mult0066,mult0067,mult0071,mult0072,mult0073,mult0074,div0001,div0002,div0008,div0009,div0015,div0016,div0022,div0023,div0050,div0051,div0057,div0058,div0064,div0065,div0071,div0072,rem0001,rem0002,rem0008,rem0009,rem0015,rem0016,rem0022,rem0023,rem0050,rem0051,rem0057,rem0058,rem0064,rem0065,rem0071,rem0072,add0001,add0002,add0003,add0007,add0008,add0009,add0013,add0014,add0015,add0037,add0038,add0039,add0043,add0044,add0045,add0049,add0050,add0051,sub0001,sub0002,sub0003,sub0007,sub0008,sub0009,sub0013,sub0014,sub0015,sub0037,sub0038,sub0039,sub0043,sub0044,sub0045,sub0049,sub0050,sub0051 //Test Case Calls [TestMethod] public MFTestResults Arith_arith001_Test() { Log.Comment("Section 7.4 "); Log.Comment("This code tests basic literal integral arthimetic additive expressions."); if (Arith_TestClass_arith001.testMethod()) { return MFTestResults.Pass; } return MFTestResults.Fail; } [TestMethod] public MFTestResults Arith_arith003_Test() { Log.Comment("Section 7.4 "); Log.Comment("This code tests basic literal integral arthimetic multiplicative expressions."); if (Arith_TestClass_arith003.testMethod()) { return MFTestResults.Pass; } return MFTestResults.Fail; } [TestMethod] public MFTestResults Arith_arith005_Test() { Log.Comment("Section 7.4 "); Log.Comment("This code tests basic integral arthimetic additive expressions using variables."); if (Arith_TestClass_arith005.testMethod()) { return MFTestResults.Pass; } return MFTestResults.Fail; } [TestMethod] public MFTestResults Arith_arith007_Test() { Log.Comment("Section 7.4 "); Log.Comment("This code tests basic integral arthimetic multiplicative expressions with variables."); if (Arith_TestClass_arith007.testMethod()) { return MFTestResults.Pass; } return MFTestResults.Fail; } [TestMethod] public MFTestResults Arith_arith023_Test() { Log.Comment("Section 7.4 "); Log.Comment("This code tests enum additive expressions."); if (Arith_TestClass_arith023.testMethod()) { return MFTestResults.Pass; } return MFTestResults.Fail; } [TestMethod] public MFTestResults Arith_arith024_Test() { Log.Comment("Section 7.4 "); Log.Comment("This code tests enum additive expressions."); if (Arith_TestClass_arith024.testMethod()) { return MFTestResults.Pass; } return MFTestResults.Fail; } [TestMethod] public MFTestResults Arith_arith028_Test() { Log.Comment("Section 7.7"); if (Arith_TestClass_arith028.testMethod()) { return MFTestResults.Pass; } return MFTestResults.Fail; } [TestMethod] public MFTestResults Arith_arith029_Test() { Log.Comment("Section 7.7"); if (Arith_TestClass_arith029.testMethod()) { return MFTestResults.Pass; } return MFTestResults.Fail; } [TestMethod] public MFTestResults Arith_arith030_Test() { Log.Comment("Section 7.7"); if (Arith_TestClass_arith030.testMethod()) { return MFTestResults.Pass; } return MFTestResults.Fail; } [TestMethod] public MFTestResults Arith_arith031_Test() { Log.Comment("Section 7.7"); if (Arith_TestClass_arith031.testMethod()) { return MFTestResults.Pass; } return MFTestResults.Fail; } [TestMethod] public MFTestResults Arith_arith032_Test() { Log.Comment("Section 7.7"); if (Arith_TestClass_arith032.testMethod()) { return MFTestResults.Pass; } return MFTestResults.Fail; } [TestMethod] public MFTestResults Arith_arith033_Test() { Log.Comment("Section 7.7"); if (Arith_TestClass_arith033.testMethod()) { return MFTestResults.Pass; } return MFTestResults.Fail; } [TestMethod] public MFTestResults Arith_arith034_Test() { Log.Comment("Section 7.7"); if (Arith_TestClass_arith034.testMethod()) { return MFTestResults.Pass; } return MFTestResults.Fail; } [TestMethod] public MFTestResults Arith_arith035_Test() { Log.Comment("Section 7.7"); if (Arith_TestClass_arith035.testMethod()) { return MFTestResults.Pass; } return MFTestResults.Fail; } [TestMethod] public MFTestResults Arith_arith036_Test() { Log.Comment("Section 7.7"); if (Arith_TestClass_arith036.testMethod()) { return MFTestResults.Pass; } return MFTestResults.Fail; } [TestMethod] public MFTestResults Arith_arith037_Test() { Log.Comment("Section 7.7"); if (Arith_TestClass_arith037.testMethod()) { return MFTestResults.Pass; } return MFTestResults.Fail; } [TestMethod] public MFTestResults Arith_arith038_Test() { Log.Comment("Section 7.7"); if (Arith_TestClass_arith038.testMethod()) { return MFTestResults.Pass; } return MFTestResults.Fail; } [TestMethod] public MFTestResults Arith_arith039_Test() { Log.Comment("Section 7.7"); if (Arith_TestClass_arith039.testMethod()) { return MFTestResults.Pass; } return MFTestResults.Fail; } [TestMethod] public MFTestResults Arith_arith040_Test() { Log.Comment("Section 7.7"); if (Arith_TestClass_arith040.testMethod()) { return MFTestResults.Pass; } return MFTestResults.Fail; } [TestMethod] public MFTestResults Arith_arith041_Test() { Log.Comment("Section 7.7"); if (Arith_TestClass_arith041.testMethod()) { return MFTestResults.Pass; } return MFTestResults.Fail; } [TestMethod] public MFTestResults Arith_arith042_Test() { Log.Comment("Section 7.7"); if (Arith_TestClass_arith042.testMethod()) { return MFTestResults.Pass; } return MFTestResults.Fail; } [TestMethod] public MFTestResults Arith_arith043_Test() { Log.Comment("Section 7.7"); if (Arith_TestClass_arith043.testMethod()) { return MFTestResults.Pass; } return MFTestResults.Fail; } [TestMethod] public MFTestResults Arith_arith044_Test() { Log.Comment("Section 7.7"); if (Arith_TestClass_arith044.testMethod()) { return MFTestResults.Pass; } return MFTestResults.Fail; } [TestMethod] public MFTestResults Arith_arith045_Test() { Log.Comment("Section 7.7"); if (Arith_TestClass_arith045.testMethod()) { return MFTestResults.Pass; } return MFTestResults.Fail; } [TestMethod] public MFTestResults Arith_arith046_Test() { Log.Comment("Section 7.7"); if (Arith_TestClass_arith046.testMethod()) { return MFTestResults.Pass; } return MFTestResults.Fail; } [TestMethod] public MFTestResults Arith_arith047_Test() { Log.Comment("Section 7.7"); if (Arith_TestClass_arith047.testMethod()) { return MFTestResults.Pass; } return MFTestResults.Fail; } [TestMethod] public MFTestResults Arith_arith048_Test() { Log.Comment("Section 7.7"); if (Arith_TestClass_arith048.testMethod()) { return MFTestResults.Pass; } return MFTestResults.Fail; } [TestMethod] public MFTestResults Arith_arith049_Test() { Log.Comment("Section 7.7"); if (Arith_TestClass_arith049.testMethod()) { return MFTestResults.Pass; } return MFTestResults.Fail; } [TestMethod] public MFTestResults Arith_arith050_Test() { Log.Comment("Section 7.7"); if (Arith_TestClass_arith050.testMethod()) { return MFTestResults.Pass; } return MFTestResults.Fail; } [TestMethod] public MFTestResults Arith_arith051_Test() { Log.Comment("Section 7.7"); if (Arith_TestClass_arith051.testMethod()) { return MFTestResults.Pass; } return MFTestResults.Fail; } [TestMethod] public MFTestResults Arith_arith052_Test() { Log.Comment("Section 7.7"); if (Arith_TestClass_arith052.testMethod()) { return MFTestResults.Pass; } return MFTestResults.Fail; } [TestMethod] public MFTestResults Arith_arith053_Test() { Log.Comment("Section 7.7"); if (Arith_TestClass_arith053.testMethod()) { return MFTestResults.Pass; } return MFTestResults.Fail; } [TestMethod] public MFTestResults Arith_arith054_Test() { Log.Comment("Section 7.7"); if (Arith_TestClass_arith054.testMethod()) { return MFTestResults.Pass; } return MFTestResults.Fail; } [TestMethod] public MFTestResults Arith_arith055_Test() { Log.Comment("Section 7.7"); if (Arith_TestClass_arith055.testMethod()) { return MFTestResults.Pass; } return MFTestResults.Fail; } [TestMethod] public MFTestResults Arith_arith056_Test() { Log.Comment("Section 7.7"); if (Arith_TestClass_arith056.testMethod()) { return MFTestResults.Pass; } return MFTestResults.Fail; } [TestMethod] public MFTestResults Arith_arith057_Test() { Log.Comment("Section 7.7"); if (Arith_TestClass_arith057.testMethod()) { return MFTestResults.Pass; } return MFTestResults.Fail; } [TestMethod] public MFTestResults Arith_arith058_Test() { Log.Comment("Section 7.7"); if (Arith_TestClass_arith058.testMethod()) { return MFTestResults.Pass; } return MFTestResults.Fail; } [TestMethod] public MFTestResults Arith_arith059_Test() { Log.Comment("Section 7.7"); if (Arith_TestClass_arith059.testMethod()) { return MFTestResults.Pass; } return MFTestResults.Fail; } [TestMethod] public MFTestResults Arith_arith060_Test() { Log.Comment("Section 7.7"); if (Arith_TestClass_arith060.testMethod()) { return MFTestResults.Pass; } return MFTestResults.Fail; } [TestMethod] public MFTestResults Arith_arith061_Test() { Log.Comment("Section 7.7"); if (Arith_TestClass_arith061.testMethod()) { return MFTestResults.Pass; } return MFTestResults.Fail; } [TestMethod] public MFTestResults Arith_arith062_Test() { Log.Comment("Section 7.7"); if (Arith_TestClass_arith062.testMethod()) { return MFTestResults.Pass; } return MFTestResults.Fail; } [TestMethod] public MFTestResults Arith_arith064_Test() { Log.Comment("Section 7.7"); if (Arith_TestClass_arith064.testMethod()) { return MFTestResults.Pass; } return MFTestResults.Fail; } [TestMethod] public MFTestResults Arith_arith065_Test() { Log.Comment("Section 7.7"); if (Arith_TestClass_arith065.testMethod()) { return MFTestResults.Pass; } return MFTestResults.Fail; } //Compiled Test Cases public class Arith_TestClass_arith001 { public static int Main_old() { int intRet = 0; //Scenario 1: type int if (5 != (3 + 2)) { intRet = 1; Log.Comment("Failure at Scenario 1"); } //Scenario 2: type int if (4 != (9 - 5)) { Log.Comment("Failure at Scenario 2"); intRet = 1; } //Scenario 7: type long if (1047L != (999L + 48L)) { Log.Comment("Failure at Scenario 7"); intRet = 1; } //Scenario 8: type long if (441L != (786L - 345L)) { Log.Comment("Failure at Scenario 8"); intRet = 1; } return intRet; } public static bool testMethod() { return (Main_old() == 0); } } public class Arith_TestClass_arith003 { public static int Main_old() { int intRet = 0; //Scenario 1: type int if (12 != (4 * 3)) { Log.Comment("Failure at Scenario 1"); intRet = 1; } //Scenario 2: type int if (4 != (8 / 2)) { Log.Comment("Failure at Scenario 2"); intRet = 1; } //Scenario 3; type int if (14 != (64 % 25)) { Log.Comment("Failure at Scenario 3"); intRet = 1; } //Scenario 10: type long if (361362L != (458L * 789L)) { Log.Comment("Failure at Scenario 10"); intRet = 1; } //Scenario 11: type long if (36L != (32004L / 889L)) { Log.Comment("Failure at Scenario 11"); intRet = 1; } //Scenario 12: type long if (29L != (985013L % 56L)) { Log.Comment("Failure at Scenario 12"); intRet = 1; } return intRet; } public static bool testMethod() { return (Main_old() == 0); } } public class Arith_TestClass_arith005 { public static int Main_old() { int intRet = 0; int i1 = 0; int i2 = 0; int i3 = 0; byte b1 = 0; byte b2 = 0; byte b3 = 0; short s1 = 0; short s2 = 0; short s3 = 0; long l1 = 0L; long l2 = 0L; long l3 = 0L; //Scenario 1: type int i1 = 7; i2 = 2; i3 = 5; if (i1 != (i2 + i3)) { Log.Comment("Failure at Scenario 1"); intRet = 1; } //Scenario 2: type int i1 = 16; i2 = 19; i3 = 3; if (i1 != (i2 - i3)) { Log.Comment("Failure at Scenario 2"); intRet = 1; } //Scenario 3: type byte b1 = 88; b2 = 86; b3 = 2; if (b1 != (b2 + b3)) { Log.Comment("Failure at Scenario 3"); intRet = 1; } //Scenario 4: type byte b1 = 62; b2 = 101; b3 = 39; if (b1 != (b2 - b3)) { Log.Comment("Failure at Scenario 4"); intRet = 1; } //Scenario 5: type short s1 = 45; s2 = 23; s3 = 22; if (s1 != (s2 + s3)) { Log.Comment("Failure at Scenario 5"); intRet = 1; } //Scenario 6: type short s1 = 87; s2 = 101; s3 = 14; if (s1 != (s2 - s3)) { Log.Comment("Failure at Scenario 6"); intRet = 1; } //Scenario 7: type long l1 = 5422L; l2 = 4567L; l3 = 855L; if (l1 != (l2 + l3)) { Log.Comment("Failure at Scenario 7"); intRet = 1; } //Scenario 8: type long l1 = 55423L; l2 = 192343L; l3 = 136920L; if (l1 != (l2 - l3)) { Log.Comment("Failure at Scenario 8"); intRet = 1; } return intRet; } public static bool testMethod() { return (Main_old() == 0); } } public class Arith_TestClass_arith007 { public static int Main_old() { int intRet = 0; int i1 = 0; int i2 = 0; int i3 = 0; byte b1 = 0; byte b2 = 0; byte b3 = 0; short s1 = 0; short s2 = 0; short s3 = 0; long l1 = 0L; long l2 = 0L; long l3 = 0L; //Scenario 1: type int i1 = 42; i2 = 7; i3 = 6; if (i1 != (i2 * i3)) { Log.Comment("Failure at Scenario 1"); intRet = 1; } //Scenario 2: type int i1 = 11; i2 = 154; i3 = 14; if (i1 != (i2 / i3)) { Log.Comment("Failure at Scenario 2"); intRet = 1; } //Scenario 3; type int i1 = 2; i2 = 95; i3 = 31; if (i1 != (i2 % i3)) { Log.Comment("Failure at Scenario 3"); intRet = 1; } //Scenario 4: type byte b1 = 94; b2 = 2; b3 = 47; if (b1 != (b2 * b3)) { Log.Comment("Failure at Scenario 4"); intRet = 1; } //Scenario 5: type byte b1 = 16; b2 = 96; b3 = 6; if (b1 != (b2 / b3)) { Log.Comment("Failure at Scenario 5"); intRet = 1; } //Scenario 6: type byte b1 = 48; b2 = 220; b3 = 86; if (b1 != (b2 % b3)) { Log.Comment("Failure at Scenario 6"); intRet = 1; } //Scenario 7: type short s1 = 8890; s2 = 254; s3 = 35; if (s1 != (s2 * s3)) { Log.Comment("Failure at Scenario 7"); intRet = 1; } //Scenario 8: type short s1 = 896; s2 = 23296; s3 = 26; if (s1 != (s2 / s3)) { Log.Comment("Failure at Scenario 8"); intRet = 1; } //Scenario 9: type short s1 = 72; s2 = 432; s3 = 90; if (s1 != (s2 % s3)) { Log.Comment("Failure at Scenario 9"); intRet = 1; } //Scenario 10: type long l1 = 3724L; l2 = 38L; l3 = 98L; if (l1 != (l2 * l3)) { Log.Comment("Failure at Scenario 10"); intRet = 1; } //Scenario 11: type long l1 = 821L; l2 = 5747L; l3 = 7L; if (l1 != (l2 / l3)) { Log.Comment("Failure at Scenario 11"); intRet = 1; } //Scenario 12: type long l1 = 89L; l2 = 22989L; l3 = 458L; if (l1 != (l2 % l3)) { Log.Comment("Failure at Scenario 12"); intRet = 1; } return intRet; } public static bool testMethod() { return (Main_old() == 0); } } enum Arith_TestClass_arith023_Enum { a = 1, b = 2 } public class Arith_TestClass_arith023 { public static int Main_old() { int MyInt = Arith_TestClass_arith023_Enum.a - Arith_TestClass_arith023_Enum.b; //E-E if (MyInt == -1) { return 0; } else { return 1; } } public static bool testMethod() { return (Main_old() == 0); } } enum Arith_TestClass_arith024_Enum { a = 1, b = 2 } public class Arith_TestClass_arith024 { public static int Main_old() { Arith_TestClass_arith024_Enum MyEnum = Arith_TestClass_arith024_Enum.a + 3; //E+U if ((int)MyEnum == 4) { return 0; } else { return 1; } } public static bool testMethod() { return (Main_old() == 0); } } public class Arith_TestClass_arith028 { public static int Main_old() { int i1 = 2; if ((0 * i1) == 0) { return 0; } else { return 1; } } public static bool testMethod() { return (Main_old() == 0); } } public class Arith_TestClass_arith029 { public static int Main_old() { int i1 = 2; if ((i1 * 0) == 0) { return 0; } else { return 1; } } public static bool testMethod() { return (Main_old() == 0); } } public class Arith_TestClass_arith030 { public static int Main_old() { byte b1 = 2; if ((b1 * 0) == 0) { return 0; } else { return 1; } } public static bool testMethod() { return (Main_old() == 0); } } public class Arith_TestClass_arith031 { public static int Main_old() { sbyte sb1 = 2; if ((sb1 * 0) == 0) { return 0; } else { return 1; } } public static bool testMethod() { return (Main_old() == 0); } } public class Arith_TestClass_arith032 { public static int Main_old() { short s1 = 2; if ((s1 * 0) == 0) { return 0; } else { return 1; } } public static bool testMethod() { return (Main_old() == 0); } } public class Arith_TestClass_arith033 { public static int Main_old() { ushort us1 = 2; if ((us1 * 0) == 0) { return 0; } else { return 1; } } public static bool testMethod() { return (Main_old() == 0); } } public class Arith_TestClass_arith034 { public static int Main_old() { uint ui1 = 2; if ((ui1 * 0) == 0) { return 0; } else { return 1; } } public static bool testMethod() { return (Main_old() == 0); } } public class Arith_TestClass_arith035 { public static int Main_old() { long l1 = 2; if ((l1 * 0) == 0) { return 0; } else { return 1; } } public static bool testMethod() { return (Main_old() == 0); } } public class Arith_TestClass_arith036 { public static int Main_old() { ulong ul1 = 2; if ((ul1 * 0) == 0) { return 0; } else { return 1; } } public static bool testMethod() { return (Main_old() == 0); } } public class Arith_TestClass_arith037 { public static int Main_old() { char c1 = (char)2; if ((c1 * 0) == 0) { return 0; } else { return 1; } } public static bool testMethod() { return (Main_old() == 0); } } public class Arith_TestClass_arith038 { public static int Main_old() { int i1 = 2; if ((0 / i1) == 0) { return 0; } else { return 1; } } public static bool testMethod() { return (Main_old() == 0); } } public class Arith_TestClass_arith039 { public static int Main_old() { sbyte sb1 = 2; if ((0 / sb1) == 0) { return 0; } else { return 1; } } public static bool testMethod() { return (Main_old() == 0); } } public class Arith_TestClass_arith040 { public static int Main_old() { byte b1 = 2; if ((0 / b1) == 0) { return 0; } else { return 1; } } public static bool testMethod() { return (Main_old() == 0); } } public class Arith_TestClass_arith041 { public static int Main_old() { short s1 = 2; if ((0 / s1) == 0) { return 0; } else { return 1; } } public static bool testMethod() { return (Main_old() == 0); } } public class Arith_TestClass_arith042 { public static int Main_old() { ushort us1 = 2; if ((0 / us1) == 0) { return 0; } else { return 1; } } public static bool testMethod() { return (Main_old() == 0); } } public class Arith_TestClass_arith043 { public static int Main_old() { uint ui1 = 2; if ((0 / ui1) == 0) { return 0; } else { return 1; } } public static bool testMethod() { return (Main_old() == 0); } } public class Arith_TestClass_arith044 { public static int Main_old() { long l1 = 2; if ((0 / l1) == 0) { return 0; } else { return 1; } } public static bool testMethod() { return (Main_old() == 0); } } public class Arith_TestClass_arith045 { public static int Main_old() { ulong ul1 = 2; if ((0 / ul1) == 0) { return 0; } else { return 1; } } public static bool testMethod() { return (Main_old() == 0); } } public class Arith_TestClass_arith046 { public static int Main_old() { char c1 = (char)2; if ((0 / c1) == 0) { return 0; } else { return 1; } } public static bool testMethod() { return (Main_old() == 0); } } public class Arith_TestClass_arith047 { public static int Main_old() { int i1 = (int)(0x80000000 / -1); if (i1 == int.MinValue) { return 0; } else { return 1; } } public static bool testMethod() { return (Main_old() == 0); } } public class Arith_TestClass_arith048 { public static int Main_old() { int i1 = (int)(0x80000000 % -1); if (i1 == 0) { return 0; } else { return 1; } } public static bool testMethod() { return (Main_old() == 0); } } public class Arith_TestClass_arith049 { public static int Main_old() { string s1 = "foo" + "bar"; if (s1 == "foobar") { return 0; } else { return 1; } } public static bool testMethod() { return (Main_old() == 0); } } public class Arith_TestClass_arith050 { public static int Main_old() { string s1 = null + "foo"; if (s1 == "foo") { return 0; } else { return 1; } } public static bool testMethod() { return (Main_old() == 0); } } public class Arith_TestClass_arith051 { public static int Main_old() { string s1 = "foo" + null; if (s1 == "foo") { return 0; } else { return 1; } } public static bool testMethod() { return (Main_old() == 0); } } public class Arith_TestClass_arith052 { public static int Main_old() { string s1 = "" + "foo"; if (s1 == "foo") { return 0; } else { return 1; } } public static bool testMethod() { return (Main_old() == 0); } } public class Arith_TestClass_arith053 { public static int Main_old() { string s1 = "foo" + ""; if (s1 == "foo") { return 0; } else { return 1; } } public static bool testMethod() { return (Main_old() == 0); } } public class Arith_TestClass_arith054 { public static int Main_old() { string s1 = ("foo" + "bar"); if (s1 == "foobar") { return 0; } else { return 1; } } public static bool testMethod() { return (Main_old() == 0); } } public class Arith_TestClass_arith055 { public static int Main_old() { string s1 = ("f" + ("oo" + "bar")); if (s1 == "foobar") { return 0; } else { return 1; } } public static bool testMethod() { return (Main_old() == 0); } } public class Arith_TestClass_arith056 { public static int Main_old() { string s1 = (("f" + "oo") + "ba" + "r"); if (s1 == "foobar") { return 0; } else { return 1; } } public static bool testMethod() { return (Main_old() == 0); } } public class Arith_TestClass_arith057 { public static int Main_old() { string s1 = "foo"; string s2 = "bar"; return 0; string str = s1 + s2 + "!"; } public static bool testMethod() { return (Main_old() == 0); } } public class Arith_TestClass_arith058 { public static int Main_old() { int intI = -1 / int.MaxValue; if (intI == 0) { return 0; } else { return 1; } } public static bool testMethod() { return (Main_old() == 0); } } public class Arith_TestClass_arith059 { public static int Main_old() { int intI = 1 / int.MaxValue; if (intI == 0) { return 0; } else { return 1; } } public static bool testMethod() { return (Main_old() == 0); } } public class Arith_TestClass_arith060 { public static int Main_old() { int intI = -1 / int.MinValue; if (intI == 0) { return 0; } else { return 1; } } public static bool testMethod() { return (Main_old() == 0); } } public class Arith_TestClass_arith061 { public static int Main_old() { int intI = 1 / int.MinValue; if (intI == 0) { return 0; } else { return 1; } } public static bool testMethod() { return (Main_old() == 0); } } public class Arith_TestClass_arith062 { public static int Main_old() { int intI = int.MaxValue / -1; if (intI == -2147483647) { return 0; } else { return 1; } } public static bool testMethod() { return (Main_old() == 0); } } public class Arith_TestClass_arith064 { public static implicit operator string(Arith_TestClass_arith064 MC) { return "foo"; } public static int Main_old() { Arith_TestClass_arith064 MC = new Arith_TestClass_arith064(); string TestString1 = "bar"; if ((MC + TestString1) == "foobar") { return 0; } else { return 1; } } public static bool testMethod() { return (Main_old() == 0); } } public class Arith_TestClass_arith065 { public static implicit operator string(Arith_TestClass_arith065 MC) { return "bar"; } public static int Main_old() { Arith_TestClass_arith065 MC = new Arith_TestClass_arith065(); string TestString1 = "foo"; if ((TestString1 + MC) == "foobar") { return 0; } else { return 1; } } public static bool testMethod() { return (Main_old() == 0); } } } } ================================================ FILE: Zelig/Zelig/Test/RunTime/NETMF/mscorlib/expressions/expressions1/ArithmeticTests2.cs ================================================ //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // Copyright (c) Microsoft Corporation. All rights reserved. //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// using System; using System.Reflection; using Microsoft.SPOT.Platform.Test; namespace Microsoft.SPOT.Platform.Tests { public class ArithmeticTests2 : IMFTestInterface { [SetUp] public InitializeResult Initialize() { Log.Comment("Adding set up for the tests"); // Add your functionality here. return InitializeResult.ReadyToGo; } [TearDown] public void CleanUp() { Log.Comment("Cleaning up after the tests"); } //Arithmetic Test methods //The following tests were ported from folder current\test\cases\client\CLR\Conformance\10_classes\Arithmetic //opt001a,opt001b,opt002a,opt002b,opt003a,opt003b,opt004a,opt004b,mult0001,mult0002,mult0003,mult0004,mult0008,mult0009,mult0010,mult0011,mult0015,mult0016,mult0017,mult0018,mult0022,mult0023,mult0024,mult0025,mult0050,mult0051,mult0052,mult0053,mult0057,mult0058,mult0059,mult0060,mult0064,mult0065,mult0066,mult0067,mult0071,mult0072,mult0073,mult0074,div0001,div0002,div0008,div0009,div0015,div0016,div0022,div0023,div0050,div0051,div0057,div0058,div0064,div0065,div0071,div0072,rem0001,rem0002,rem0008,rem0009,rem0015,rem0016,rem0022,rem0023,rem0050,rem0051,rem0057,rem0058,rem0064,rem0065,rem0071,rem0072,add0001,add0002,add0003,add0007,add0008,add0009,add0013,add0014,add0015,add0037,add0038,add0039,add0043,add0044,add0045,add0049,add0050,add0051,sub0001,sub0002,sub0003,sub0007,sub0008,sub0009,sub0013,sub0014,sub0015,sub0037,sub0038,sub0039,sub0043,sub0044,sub0045,sub0049,sub0050,sub0051 //Test Case Calls //Test Case Calls [TestMethod] public MFTestResults Arith_opt001_Test() { if (Arith_TestClass_opt001.testMethod()) { return MFTestResults.Pass; } return MFTestResults.Fail; } [TestMethod] public MFTestResults Arith_opt002_Test() { if (Arith_TestClass_opt002.testMethod()) { return MFTestResults.Pass; } return MFTestResults.Fail; } [TestMethod] public MFTestResults Arith_opt003_Test() { if (Arith_TestClass_opt003.testMethod()) { return MFTestResults.Pass; } return MFTestResults.Fail; } [TestMethod] public MFTestResults Arith_opt004_Test() { if (Arith_TestClass_opt004.testMethod()) { return MFTestResults.Pass; } return MFTestResults.Fail; } [TestMethod] public MFTestResults Arith_mult0001_Test() { Log.Comment("Section 7.7.1"); if (Arith_TestClass_mult0001.testMethod()) { return MFTestResults.Pass; } return MFTestResults.Fail; } [TestMethod] public MFTestResults Arith_mult0002_Test() { Log.Comment("Section 7.7.1"); if (Arith_TestClass_mult0002.testMethod()) { return MFTestResults.Pass; } return MFTestResults.Fail; } [TestMethod] public MFTestResults Arith_mult0003_Test() { Log.Comment("Section 7.7.1"); if (Arith_TestClass_mult0003.testMethod()) { return MFTestResults.Pass; } return MFTestResults.Fail; } [TestMethod] public MFTestResults Arith_mult0004_Test() { Log.Comment("Section 7.7.1"); if (Arith_TestClass_mult0004.testMethod()) { return MFTestResults.Pass; } return MFTestResults.Fail; } [TestMethod] public MFTestResults Arith_mult0008_Test() { Log.Comment("Section 7.7.1"); if (Arith_TestClass_mult0008.testMethod()) { return MFTestResults.Pass; } return MFTestResults.Fail; } [TestMethod] public MFTestResults Arith_mult0009_Test() { Log.Comment("Section 7.7.1"); if (Arith_TestClass_mult0009.testMethod()) { return MFTestResults.Pass; } return MFTestResults.Fail; } [TestMethod] public MFTestResults Arith_mult0010_Test() { Log.Comment("Section 7.7.1"); if (Arith_TestClass_mult0010.testMethod()) { return MFTestResults.Pass; } return MFTestResults.Fail; } [TestMethod] public MFTestResults Arith_mult0011_Test() { Log.Comment("Section 7.7.1"); if (Arith_TestClass_mult0011.testMethod()) { return MFTestResults.Pass; } return MFTestResults.Fail; } [TestMethod] public MFTestResults Arith_mult0015_Test() { Log.Comment("Section 7.7.1"); if (Arith_TestClass_mult0015.testMethod()) { return MFTestResults.Pass; } return MFTestResults.Fail; } [TestMethod] public MFTestResults Arith_mult0016_Test() { Log.Comment("Section 7.7.1"); if (Arith_TestClass_mult0016.testMethod()) { return MFTestResults.Pass; } return MFTestResults.Fail; } [TestMethod] public MFTestResults Arith_mult0017_Test() { Log.Comment("Section 7.7.1"); if (Arith_TestClass_mult0017.testMethod()) { return MFTestResults.Pass; } return MFTestResults.Fail; } [TestMethod] public MFTestResults Arith_mult0018_Test() { Log.Comment("Section 7.7.1"); if (Arith_TestClass_mult0018.testMethod()) { return MFTestResults.Pass; } return MFTestResults.Fail; } [TestMethod] public MFTestResults Arith_mult0022_Test() { Log.Comment("Section 7.7.1"); if (Arith_TestClass_mult0022.testMethod()) { return MFTestResults.Pass; } return MFTestResults.Fail; } [TestMethod] public MFTestResults Arith_mult0023_Test() { Log.Comment("Section 7.7.1"); if (Arith_TestClass_mult0023.testMethod()) { return MFTestResults.Pass; } return MFTestResults.Fail; } [TestMethod] public MFTestResults Arith_mult0024_Test() { Log.Comment("Section 7.7.1"); if (Arith_TestClass_mult0024.testMethod()) { return MFTestResults.Pass; } return MFTestResults.Fail; } [TestMethod] public MFTestResults Arith_mult0025_Test() { Log.Comment("Section 7.7.1"); if (Arith_TestClass_mult0025.testMethod()) { return MFTestResults.Pass; } return MFTestResults.Fail; } [TestMethod] public MFTestResults Arith_mult0050_Test() { Log.Comment("Section 7.7.1"); if (Arith_TestClass_mult0050.testMethod()) { return MFTestResults.Pass; } return MFTestResults.Fail; } [TestMethod] public MFTestResults Arith_mult0051_Test() { Log.Comment("Section 7.7.1"); if (Arith_TestClass_mult0051.testMethod()) { return MFTestResults.Pass; } return MFTestResults.Fail; } [TestMethod] public MFTestResults Arith_mult0052_Test() { Log.Comment("Section 7.7.1"); if (Arith_TestClass_mult0052.testMethod()) { return MFTestResults.Pass; } return MFTestResults.Fail; } [TestMethod] public MFTestResults Arith_mult0053_Test() { Log.Comment("Section 7.7.1"); if (Arith_TestClass_mult0053.testMethod()) { return MFTestResults.Pass; } return MFTestResults.Fail; } [TestMethod] public MFTestResults Arith_mult0057_Test() { Log.Comment("Section 7.7.1"); if (Arith_TestClass_mult0057.testMethod()) { return MFTestResults.Pass; } return MFTestResults.Fail; } [TestMethod] public MFTestResults Arith_mult0058_Test() { Log.Comment("Section 7.7.1"); if (Arith_TestClass_mult0058.testMethod()) { return MFTestResults.Pass; } return MFTestResults.Fail; } [TestMethod] public MFTestResults Arith_mult0059_Test() { Log.Comment("Section 7.7.1"); if (Arith_TestClass_mult0059.testMethod()) { return MFTestResults.Pass; } return MFTestResults.Fail; } [TestMethod] public MFTestResults Arith_mult0060_Test() { Log.Comment("Section 7.7.1"); if (Arith_TestClass_mult0060.testMethod()) { return MFTestResults.Pass; } return MFTestResults.Fail; } [TestMethod] public MFTestResults Arith_mult0064_Test() { Log.Comment("Section 7.7.1"); if (Arith_TestClass_mult0064.testMethod()) { return MFTestResults.Pass; } return MFTestResults.Fail; } [TestMethod] public MFTestResults Arith_mult0065_Test() { Log.Comment("Section 7.7.1"); if (Arith_TestClass_mult0065.testMethod()) { return MFTestResults.Pass; } return MFTestResults.Fail; } [TestMethod] public MFTestResults Arith_mult0066_Test() { Log.Comment("Section 7.7.1"); if (Arith_TestClass_mult0066.testMethod()) { return MFTestResults.Pass; } return MFTestResults.Fail; } [TestMethod] public MFTestResults Arith_mult0067_Test() { Log.Comment("Section 7.7.1"); if (Arith_TestClass_mult0067.testMethod()) { return MFTestResults.Pass; } return MFTestResults.Fail; } [TestMethod] public MFTestResults Arith_mult0071_Test() { Log.Comment("Section 7.7.1"); if (Arith_TestClass_mult0071.testMethod()) { return MFTestResults.Pass; } return MFTestResults.Fail; } [TestMethod] public MFTestResults Arith_mult0072_Test() { Log.Comment("Section 7.7.1"); if (Arith_TestClass_mult0072.testMethod()) { return MFTestResults.Pass; } return MFTestResults.Fail; } [TestMethod] public MFTestResults Arith_mult0073_Test() { Log.Comment("Section 7.7.1"); if (Arith_TestClass_mult0073.testMethod()) { return MFTestResults.Pass; } return MFTestResults.Fail; } [TestMethod] public MFTestResults Arith_mult0074_Test() { Log.Comment("Section 7.7.1"); if (Arith_TestClass_mult0074.testMethod()) { return MFTestResults.Pass; } return MFTestResults.Fail; } [TestMethod] public MFTestResults Arith_div0001_Test() { Log.Comment("Section 7.7.2"); if (Arith_TestClass_div0001.testMethod()) { return MFTestResults.Pass; } return MFTestResults.Fail; } [TestMethod] public MFTestResults Arith_div0002_Test() { Log.Comment("Section 7.7.2"); if (Arith_TestClass_div0002.testMethod()) { return MFTestResults.Pass; } return MFTestResults.Fail; } [TestMethod] public MFTestResults Arith_div0008_Test() { Log.Comment("Section 7.7.2"); if (Arith_TestClass_div0008.testMethod()) { return MFTestResults.Pass; } return MFTestResults.Fail; } [TestMethod] public MFTestResults Arith_div0009_Test() { Log.Comment("Section 7.7.2"); if (Arith_TestClass_div0009.testMethod()) { return MFTestResults.Pass; } return MFTestResults.Fail; } [TestMethod] public MFTestResults Arith_div0015_Test() { Log.Comment("Section 7.7.2"); if (Arith_TestClass_div0015.testMethod()) { return MFTestResults.Pass; } return MFTestResults.Fail; } [TestMethod] public MFTestResults Arith_div0016_Test() { Log.Comment("Section 7.7.2"); if (Arith_TestClass_div0016.testMethod()) { return MFTestResults.Pass; } return MFTestResults.Fail; } [TestMethod] public MFTestResults Arith_div0022_Test() { Log.Comment("Section 7.7.2"); if (Arith_TestClass_div0022.testMethod()) { return MFTestResults.Pass; } return MFTestResults.Fail; } [TestMethod] public MFTestResults Arith_div0023_Test() { Log.Comment("Section 7.7.2"); if (Arith_TestClass_div0023.testMethod()) { return MFTestResults.Pass; } return MFTestResults.Fail; } [TestMethod] public MFTestResults Arith_div0050_Test() { Log.Comment("Section 7.7.2"); if (Arith_TestClass_div0050.testMethod()) { return MFTestResults.Pass; } return MFTestResults.Fail; } [TestMethod] public MFTestResults Arith_div0051_Test() { Log.Comment("Section 7.7.2"); if (Arith_TestClass_div0051.testMethod()) { return MFTestResults.Pass; } return MFTestResults.Fail; } [TestMethod] public MFTestResults Arith_div0057_Test() { Log.Comment("Section 7.7.2"); if (Arith_TestClass_div0057.testMethod()) { return MFTestResults.Pass; } return MFTestResults.Fail; } [TestMethod] public MFTestResults Arith_div0058_Test() { Log.Comment("Section 7.7.2"); if (Arith_TestClass_div0058.testMethod()) { return MFTestResults.Pass; } return MFTestResults.Fail; } [TestMethod] public MFTestResults Arith_div0064_Test() { Log.Comment("Section 7.7.2"); if (Arith_TestClass_div0064.testMethod()) { return MFTestResults.Pass; } return MFTestResults.Fail; } [TestMethod] public MFTestResults Arith_div0065_Test() { Log.Comment("Section 7.7.2"); if (Arith_TestClass_div0065.testMethod()) { return MFTestResults.Pass; } return MFTestResults.Fail; } [TestMethod] public MFTestResults Arith_div0071_Test() { Log.Comment("Section 7.7.2"); if (Arith_TestClass_div0071.testMethod()) { return MFTestResults.Pass; } return MFTestResults.Fail; } [TestMethod] public MFTestResults Arith_div0072_Test() { Log.Comment("Section 7.7.2"); if (Arith_TestClass_div0072.testMethod()) { return MFTestResults.Pass; } return MFTestResults.Fail; } [TestMethod] public MFTestResults Arith_rem0001_Test() { Log.Comment("Section 7.7.3"); if (Arith_TestClass_rem0001.testMethod()) { return MFTestResults.Pass; } return MFTestResults.Fail; } [TestMethod] public MFTestResults Arith_rem0002_Test() { Log.Comment("Section 7.7.3"); if (Arith_TestClass_rem0002.testMethod()) { return MFTestResults.Pass; } return MFTestResults.Fail; } [TestMethod] public MFTestResults Arith_rem0008_Test() { Log.Comment("Section 7.7.3"); if (Arith_TestClass_rem0008.testMethod()) { return MFTestResults.Pass; } return MFTestResults.Fail; } [TestMethod] public MFTestResults Arith_rem0009_Test() { Log.Comment("Section 7.7.3"); if (Arith_TestClass_rem0009.testMethod()) { return MFTestResults.Pass; } return MFTestResults.Fail; } [TestMethod] public MFTestResults Arith_rem0015_Test() { Log.Comment("Section 7.7.3"); if (Arith_TestClass_rem0015.testMethod()) { return MFTestResults.Pass; } return MFTestResults.Fail; } [TestMethod] public MFTestResults Arith_rem0016_Test() { Log.Comment("Section 7.7.3"); if (Arith_TestClass_rem0016.testMethod()) { return MFTestResults.Pass; } return MFTestResults.Fail; } [TestMethod] public MFTestResults Arith_rem0022_Test() { Log.Comment("Section 7.7.3"); if (Arith_TestClass_rem0022.testMethod()) { return MFTestResults.Pass; } return MFTestResults.Fail; } [TestMethod] public MFTestResults Arith_rem0023_Test() { Log.Comment("Section 7.7.3"); if (Arith_TestClass_rem0023.testMethod()) { return MFTestResults.Pass; } return MFTestResults.Fail; } [TestMethod] public MFTestResults Arith_rem0050_Test() { Log.Comment("Section 7.7.3"); if (Arith_TestClass_rem0050.testMethod()) { return MFTestResults.Pass; } return MFTestResults.Fail; } [TestMethod] public MFTestResults Arith_rem0051_Test() { Log.Comment("Section 7.7.3"); if (Arith_TestClass_rem0051.testMethod()) { return MFTestResults.Pass; } return MFTestResults.Fail; } [TestMethod] public MFTestResults Arith_rem0057_Test() { Log.Comment("Section 7.7.3"); if (Arith_TestClass_rem0057.testMethod()) { return MFTestResults.Pass; } return MFTestResults.Fail; } [TestMethod] public MFTestResults Arith_rem0058_Test() { Log.Comment("Section 7.7.3"); if (Arith_TestClass_rem0058.testMethod()) { return MFTestResults.Pass; } return MFTestResults.Fail; } [TestMethod] public MFTestResults Arith_rem0064_Test() { Log.Comment("Section 7.7.3"); if (Arith_TestClass_rem0064.testMethod()) { return MFTestResults.Pass; } return MFTestResults.Fail; } [TestMethod] public MFTestResults Arith_rem0065_Test() { Log.Comment("Section 7.7.3"); if (Arith_TestClass_rem0065.testMethod()) { return MFTestResults.Pass; } return MFTestResults.Fail; } [TestMethod] public MFTestResults Arith_rem0071_Test() { Log.Comment("Section 7.7.3"); if (Arith_TestClass_rem0071.testMethod()) { return MFTestResults.Pass; } return MFTestResults.Fail; } [TestMethod] public MFTestResults Arith_rem0072_Test() { Log.Comment("Section 7.7.3"); if (Arith_TestClass_rem0072.testMethod()) { return MFTestResults.Pass; } return MFTestResults.Fail; } [TestMethod] public MFTestResults Arith_add0001_Test() { Log.Comment("Section 7.7.4"); if (Arith_TestClass_add0001.testMethod()) { return MFTestResults.Pass; } return MFTestResults.Fail; } [TestMethod] public MFTestResults Arith_add0002_Test() { Log.Comment("Section 7.7.4"); if (Arith_TestClass_add0002.testMethod()) { return MFTestResults.Pass; } return MFTestResults.Fail; } [TestMethod] public MFTestResults Arith_add0003_Test() { Log.Comment("Section 7.7.4"); if (Arith_TestClass_add0003.testMethod()) { return MFTestResults.Pass; } return MFTestResults.Fail; } [TestMethod] public MFTestResults Arith_add0007_Test() { Log.Comment("Section 7.7.4"); if (Arith_TestClass_add0007.testMethod()) { return MFTestResults.Pass; } return MFTestResults.Fail; } [TestMethod] public MFTestResults Arith_add0008_Test() { Log.Comment("Section 7.7.4"); if (Arith_TestClass_add0008.testMethod()) { return MFTestResults.Pass; } return MFTestResults.Fail; } [TestMethod] public MFTestResults Arith_add0009_Test() { Log.Comment("Section 7.7.4"); if (Arith_TestClass_add0009.testMethod()) { return MFTestResults.Pass; } return MFTestResults.Fail; } [TestMethod] public MFTestResults Arith_add0013_Test() { Log.Comment("Section 7.7.4"); if (Arith_TestClass_add0013.testMethod()) { return MFTestResults.Pass; } return MFTestResults.Fail; } [TestMethod] public MFTestResults Arith_add0014_Test() { Log.Comment("Section 7.7.4"); if (Arith_TestClass_add0014.testMethod()) { return MFTestResults.Pass; } return MFTestResults.Fail; } [TestMethod] public MFTestResults Arith_add0015_Test() { Log.Comment("Section 7.7.4"); if (Arith_TestClass_add0015.testMethod()) { return MFTestResults.Pass; } return MFTestResults.Fail; } [TestMethod] public MFTestResults Arith_add0037_Test() { Log.Comment("Section 7.7.4"); if (Arith_TestClass_add0037.testMethod()) { return MFTestResults.Pass; } return MFTestResults.Fail; } [TestMethod] public MFTestResults Arith_add0038_Test() { Log.Comment("Section 7.7.4"); if (Arith_TestClass_add0038.testMethod()) { return MFTestResults.Pass; } return MFTestResults.Fail; } [TestMethod] public MFTestResults Arith_add0039_Test() { Log.Comment("Section 7.7.4"); if (Arith_TestClass_add0039.testMethod()) { return MFTestResults.Pass; } return MFTestResults.Fail; } [TestMethod] public MFTestResults Arith_add0043_Test() { Log.Comment("Section 7.7.4"); if (Arith_TestClass_add0043.testMethod()) { return MFTestResults.Pass; } return MFTestResults.Fail; } [TestMethod] public MFTestResults Arith_add0044_Test() { Log.Comment("Section 7.7.4"); if (Arith_TestClass_add0044.testMethod()) { return MFTestResults.Pass; } return MFTestResults.Fail; } [TestMethod] public MFTestResults Arith_add0045_Test() { Log.Comment("Section 7.7.4"); if (Arith_TestClass_add0045.testMethod()) { return MFTestResults.Pass; } return MFTestResults.Fail; } [TestMethod] public MFTestResults Arith_add0049_Test() { Log.Comment("Section 7.7.4"); if (Arith_TestClass_add0049.testMethod()) { return MFTestResults.Pass; } return MFTestResults.Fail; } [TestMethod] public MFTestResults Arith_add0050_Test() { Log.Comment("Section 7.7.4"); if (Arith_TestClass_add0050.testMethod()) { return MFTestResults.Pass; } return MFTestResults.Fail; } [TestMethod] public MFTestResults Arith_add0051_Test() { Log.Comment("Section 7.7.4"); if (Arith_TestClass_add0051.testMethod()) { return MFTestResults.Pass; } return MFTestResults.Fail; } [TestMethod] public MFTestResults Arith_sub0001_Test() { Log.Comment("Section 7.7.5"); if (Arith_TestClass_sub0001.testMethod()) { return MFTestResults.Pass; } return MFTestResults.Fail; } [TestMethod] public MFTestResults Arith_sub0002_Test() { Log.Comment("Section 7.7.5"); if (Arith_TestClass_sub0002.testMethod()) { return MFTestResults.Pass; } return MFTestResults.Fail; } [TestMethod] public MFTestResults Arith_sub0003_Test() { Log.Comment("Section 7.7.5"); if (Arith_TestClass_sub0003.testMethod()) { return MFTestResults.Pass; } return MFTestResults.Fail; } [TestMethod] public MFTestResults Arith_sub0007_Test() { Log.Comment("Section 7.7.5"); if (Arith_TestClass_sub0007.testMethod()) { return MFTestResults.Pass; } return MFTestResults.Fail; } [TestMethod] public MFTestResults Arith_sub0008_Test() { Log.Comment("Section 7.7.5"); if (Arith_TestClass_sub0008.testMethod()) { return MFTestResults.Pass; } return MFTestResults.Fail; } [TestMethod] public MFTestResults Arith_sub0009_Test() { Log.Comment("Section 7.7.5"); if (Arith_TestClass_sub0009.testMethod()) { return MFTestResults.Pass; } return MFTestResults.Fail; } [TestMethod] public MFTestResults Arith_sub0013_Test() { Log.Comment("Section 7.7.5"); if (Arith_TestClass_sub0013.testMethod()) { return MFTestResults.Pass; } return MFTestResults.Fail; } [TestMethod] public MFTestResults Arith_sub0014_Test() { Log.Comment("Section 7.7.5"); if (Arith_TestClass_sub0014.testMethod()) { return MFTestResults.Pass; } return MFTestResults.Fail; } [TestMethod] public MFTestResults Arith_sub0015_Test() { Log.Comment("Section 7.7.5"); if (Arith_TestClass_sub0015.testMethod()) { return MFTestResults.Pass; } return MFTestResults.Fail; } [TestMethod] public MFTestResults Arith_sub0037_Test() { Log.Comment("Section 7.7.5"); if (Arith_TestClass_sub0037.testMethod()) { return MFTestResults.Pass; } return MFTestResults.Fail; } [TestMethod] public MFTestResults Arith_sub0038_Test() { Log.Comment("Section 7.7.5"); if (Arith_TestClass_sub0038.testMethod()) { return MFTestResults.Pass; } return MFTestResults.Fail; } [TestMethod] public MFTestResults Arith_sub0039_Test() { Log.Comment("Section 7.7.5"); if (Arith_TestClass_sub0039.testMethod()) { return MFTestResults.Pass; } return MFTestResults.Fail; } [TestMethod] public MFTestResults Arith_sub0043_Test() { Log.Comment("Section 7.7.5"); if (Arith_TestClass_sub0043.testMethod()) { return MFTestResults.Pass; } return MFTestResults.Fail; } [TestMethod] public MFTestResults Arith_sub0044_Test() { Log.Comment("Section 7.7.5"); if (Arith_TestClass_sub0044.testMethod()) { return MFTestResults.Pass; } return MFTestResults.Fail; } [TestMethod] public MFTestResults Arith_sub0045_Test() { Log.Comment("Section 7.7.5"); if (Arith_TestClass_sub0045.testMethod()) { return MFTestResults.Pass; } return MFTestResults.Fail; } [TestMethod] public MFTestResults Arith_sub0049_Test() { Log.Comment("Section 7.7.5"); if (Arith_TestClass_sub0049.testMethod()) { return MFTestResults.Pass; } return MFTestResults.Fail; } [TestMethod] public MFTestResults Arith_sub0050_Test() { Log.Comment("Section 7.7.5"); if (Arith_TestClass_sub0050.testMethod()) { return MFTestResults.Pass; } return MFTestResults.Fail; } [TestMethod] public MFTestResults Arith_sub0051_Test() { Log.Comment("Section 7.7.5"); if (Arith_TestClass_sub0051.testMethod()) { return MFTestResults.Pass; } return MFTestResults.Fail; } //Compiled Test Cases //Compiled Test Cases class Arith_TestClass_opt001 { static int Main_old() { double t0 = 1.5; int i = 0; for (i = 0; i < 1; i++) { double dd = t0 / 3; t0 -= dd; if (dd > 2) { break; } } if (t0 != 1) return 1;// Failed. else return 0; // No problem. } public static bool testMethod() { return (Main_old() == 0); } } class Arith_TestClass_opt002 { static int Main_old() { double t0 = 1.5; int i = 0; for (i = 0; i < 1; i++) { double dd = t0 / 3; t0 += dd; if (dd > 2) { break; } } if (t0 != 2) return 1;// Failed. else return 0; // No problem. } public static bool testMethod() { return (Main_old() == 0); } } class Arith_TestClass_opt003 { static int Main_old() { double t0 = 1.5; int i = 0; for (i = 0; i < 1; i++) { double dd = t0 / 3; t0 *= dd; if (dd > 2) { break; } } if (t0 != 0.75) return 1;// Failed. else return 0; // No problem. } public static bool testMethod() { return (Main_old() == 0); } } class Arith_TestClass_opt004 { static int Main_old() { double t0 = 1.5; int i = 0; for (i = 0; i < 1; i++) { double dd = t0 / 3; t0 /= dd; if (dd > 2) { break; } } if (t0 != 3) return 1;// Failed. else return 0; // No problem. } public static bool testMethod() { return (Main_old() == 0); } } class Arith_TestClass_mult0001 { public static int Main_old() { float f1 = 2.0f; float f2 = 2.0f; float f3 = f1 * f2; if (f3 == 4.0f) { return 0; } else { return 1; } } public static bool testMethod() { return (Main_old() == 0); } } class Arith_TestClass_mult0002 { public static int Main_old() { float f1 = 2.0f; float f2 = -2.0f; float f3 = f1 * f2; if (f3 == -4.0f) { return 0; } else { return 1; } } public static bool testMethod() { return (Main_old() == 0); } } class Arith_TestClass_mult0003 { public static int Main_old() { float f1 = 2.0f; float f2 = 0.0f; float f3 = f1 * f2; if (f3 == 0.0f) { return 0; } else { return 1; } } public static bool testMethod() { return (Main_old() == 0); } } class Arith_TestClass_mult0004 { public static int Main_old() { float f1 = 2.0f; float f2 = -0.0f; float f3 = f1 * f2; if (f3 == -0.0f) { return 0; } else { return 1; } } public static bool testMethod() { return (Main_old() == 0); } } class Arith_TestClass_mult0008 { public static int Main_old() { float f1 = -2.0f; float f2 = 2.0f; float f3 = f1 * f2; if (f3 == -4.0f) { return 0; } else { return 1; } } public static bool testMethod() { return (Main_old() == 0); } } class Arith_TestClass_mult0009 { public static int Main_old() { float f1 = -2.0f; float f2 = -2.0f; float f3 = f1 * f2; if (f3 == 4.0f) { return 0; } else { return 1; } } public static bool testMethod() { return (Main_old() == 0); } } class Arith_TestClass_mult0010 { public static int Main_old() { float f1 = -2.0f; float f2 = 0.0f; float f3 = f1 * f2; if (f3 == -0.0f) { return 0; } else { return 1; } } public static bool testMethod() { return (Main_old() == 0); } } class Arith_TestClass_mult0011 { public static int Main_old() { float f1 = -2.0f; float f2 = -0.0f; float f3 = f1 * f2; if (f3 == 0.0f) { return 0; } else { return 1; } } public static bool testMethod() { return (Main_old() == 0); } } class Arith_TestClass_mult0015 { public static int Main_old() { float f1 = 0.0f; float f2 = 2.0f; float f3 = f1 * f2; if (f3 == 0.0f) { return 0; } else { return 1; } } public static bool testMethod() { return (Main_old() == 0); } } class Arith_TestClass_mult0016 { public static int Main_old() { float f1 = 0.0f; float f2 = -2.0f; float f3 = f1 * f2; if (f3 == -0.0f) { return 0; } else { return 1; } } public static bool testMethod() { return (Main_old() == 0); } } class Arith_TestClass_mult0017 { public static int Main_old() { float f1 = 0.0f; float f2 = 0.0f; float f3 = f1 * f2; if (f3 == 0.0f) { return 0; } else { return 1; } } public static bool testMethod() { return (Main_old() == 0); } } class Arith_TestClass_mult0018 { public static int Main_old() { float f1 = 0.0f; float f2 = -0.0f; float f3 = f1 * f2; if (f3 == -0.0f) { return 0; } else { return 1; } } public static bool testMethod() { return (Main_old() == 0); } } class Arith_TestClass_mult0022 { public static int Main_old() { float f1 = -0.0f; float f2 = 2.0f; float f3 = f1 * f2; if (f3 == -0.0f) { return 0; } else { return 1; } } public static bool testMethod() { return (Main_old() == 0); } } class Arith_TestClass_mult0023 { public static int Main_old() { float f1 = -0.0f; float f2 = -2.0f; float f3 = f1 * f2; if (f3 == 0.0f) { return 0; } else { return 1; } } public static bool testMethod() { return (Main_old() == 0); } } class Arith_TestClass_mult0024 { public static int Main_old() { float f1 = -0.0f; float f2 = 0.0f; float f3 = f1 * f2; if (f3 == -0.0f) { return 0; } else { return 1; } } public static bool testMethod() { return (Main_old() == 0); } } class Arith_TestClass_mult0025 { public static int Main_old() { float f1 = -0.0f; float f2 = -0.0f; float f3 = f1 * f2; if (f3 == 0.0f) { return 0; } else { return 1; } } public static bool testMethod() { return (Main_old() == 0); } } class Arith_TestClass_mult0050 { public static int Main_old() { double d1 = 2.0; double d2 = 2.0; double d3 = d1 * d2; if (d3 == 4.0) { return 0; } else { return 1; } } public static bool testMethod() { return (Main_old() == 0); } } class Arith_TestClass_mult0051 { public static int Main_old() { double d1 = 2.0; double d2 = -2.0; double d3 = d1 * d2; if (d3 == -4.0) { return 0; } else { return 1; } } public static bool testMethod() { return (Main_old() == 0); } } class Arith_TestClass_mult0052 { public static int Main_old() { double d1 = 2.0; double d2 = 0.0; double d3 = d1 * d2; if (d3 == 0.0) { return 0; } else { return 1; } } public static bool testMethod() { return (Main_old() == 0); } } class Arith_TestClass_mult0053 { public static int Main_old() { double d1 = 2.0; double d2 = -0.0; double d3 = d1 * d2; if (d3 == -0.0) { return 0; } else { return 1; } } public static bool testMethod() { return (Main_old() == 0); } } class Arith_TestClass_mult0057 { public static int Main_old() { double d1 = -2.0; double d2 = 2.0; double d3 = d1 * d2; if (d3 == -4.0) { return 0; } else { return 1; } } public static bool testMethod() { return (Main_old() == 0); } } class Arith_TestClass_mult0058 { public static int Main_old() { double d1 = -2.0; double d2 = -2.0; double d3 = d1 * d2; if (d3 == 4.0) { return 0; } else { return 1; } } public static bool testMethod() { return (Main_old() == 0); } } class Arith_TestClass_mult0059 { public static int Main_old() { double d1 = -2.0; double d2 = 0.0; double d3 = d1 * d2; if (d3 == -0.0) { return 0; } else { return 1; } } public static bool testMethod() { return (Main_old() == 0); } } class Arith_TestClass_mult0060 { public static int Main_old() { double d1 = -2.0; double d2 = -0.0; double d3 = d1 * d2; if (d3 == 0.0) { return 0; } else { return 1; } } public static bool testMethod() { return (Main_old() == 0); } } class Arith_TestClass_mult0064 { public static int Main_old() { double d1 = 0.0; double d2 = 2.0; double d3 = d1 * d2; if (d3 == 0.0) { return 0; } else { return 1; } } public static bool testMethod() { return (Main_old() == 0); } } class Arith_TestClass_mult0065 { public static int Main_old() { double d1 = 0.0; double d2 = -2.0; double d3 = d1 * d2; if (d3 == -0.0) { return 0; } else { return 1; } } public static bool testMethod() { return (Main_old() == 0); } } class Arith_TestClass_mult0066 { public static int Main_old() { double d1 = 0.0; double d2 = 0.0; double d3 = d1 * d2; if (d3 == 0.0) { return 0; } else { return 1; } } public static bool testMethod() { return (Main_old() == 0); } } class Arith_TestClass_mult0067 { public static int Main_old() { double d1 = 0.0; double d2 = -0.0; double d3 = d1 * d2; if (d3 == -0.0) { return 0; } else { return 1; } } public static bool testMethod() { return (Main_old() == 0); } } class Arith_TestClass_mult0071 { public static int Main_old() { double d1 = -0.0; double d2 = 2.0; double d3 = d1 * d2; if (d3 == -0.0) { return 0; } else { return 1; } } public static bool testMethod() { return (Main_old() == 0); } } class Arith_TestClass_mult0072 { public static int Main_old() { double d1 = -0.0; double d2 = -2.0; double d3 = d1 * d2; if (d3 == 0.0) { return 0; } else { return 1; } } public static bool testMethod() { return (Main_old() == 0); } } class Arith_TestClass_mult0073 { public static int Main_old() { double d1 = -0.0; double d2 = 0.0; double d3 = d1 * d2; if (d3 == -0.0) { return 0; } else { return 1; } } public static bool testMethod() { return (Main_old() == 0); } } class Arith_TestClass_mult0074 { public static int Main_old() { double d1 = -0.0; double d2 = -0.0; double d3 = d1 * d2; if (d3 == 0.0) { return 0; } else { return 1; } } public static bool testMethod() { return (Main_old() == 0); } } class Arith_TestClass_div0001 { public static int Main_old() { float f1 = 2.0f; float f2 = 2.0f; float f3 = f1 / f2; if (f3 == 1.0f) { return 0; } else { return 1; } } public static bool testMethod() { return (Main_old() == 0); } } class Arith_TestClass_div0002 { public static int Main_old() { float f1 = 2.0f; float f2 = -2.0f; float f3 = f1 / f2; if (f3 == -1.0f) { return 0; } else { return 1; } } public static bool testMethod() { return (Main_old() == 0); } } class Arith_TestClass_div0008 { public static int Main_old() { float f1 = -2.0f; float f2 = 2.0f; float f3 = f1 / f2; if (f3 == -1.0f) { return 0; } else { return 1; } } public static bool testMethod() { return (Main_old() == 0); } } class Arith_TestClass_div0009 { public static int Main_old() { float f1 = -2.0f; float f2 = -2.0f; float f3 = f1 / f2; if (f3 == 1.0f) { return 0; } else { return 1; } } public static bool testMethod() { return (Main_old() == 0); } } class Arith_TestClass_div0015 { public static int Main_old() { float f1 = 0.0f; float f2 = 2.0f; float f3 = f1 / f2; if (f3 == 0.0f) { return 0; } else { return 1; } } public static bool testMethod() { return (Main_old() == 0); } } class Arith_TestClass_div0016 { public static int Main_old() { float f1 = 0.0f; float f2 = -2.0f; float f3 = f1 / f2; if (f3 == -0.0f) { return 0; } else { return 1; } } public static bool testMethod() { return (Main_old() == 0); } } class Arith_TestClass_div0022 { public static int Main_old() { float f1 = -0.0f; float f2 = 2.0f; float f3 = f1 / f2; if (f3 == -0.0f) { return 0; } else { return 1; } } public static bool testMethod() { return (Main_old() == 0); } } class Arith_TestClass_div0023 { public static int Main_old() { float f1 = -0.0f; float f2 = -2.0f; float f3 = f1 / f2; if (f3 == 0.0f) { return 0; } else { return 1; } } public static bool testMethod() { return (Main_old() == 0); } } class Arith_TestClass_div0050 { public static int Main_old() { double d1 = 2.0; double d2 = 2.0; double d3 = d1 / d2; if (d3 == 1.0) { return 0; } else { return 1; } } public static bool testMethod() { return (Main_old() == 0); } } class Arith_TestClass_div0051 { public static int Main_old() { double d1 = 2.0; double d2 = -2.0; double d3 = d1 / d2; if (d3 == -1.0) { return 0; } else { return 1; } } public static bool testMethod() { return (Main_old() == 0); } } class Arith_TestClass_div0057 { public static int Main_old() { double d1 = -2.0; double d2 = 2.0; double d3 = d1 / d2; if (d3 == -1.0) { return 0; } else { return 1; } } public static bool testMethod() { return (Main_old() == 0); } } class Arith_TestClass_div0058 { public static int Main_old() { double d1 = -2.0; double d2 = -2.0; double d3 = d1 / d2; if (d3 == 1.0) { return 0; } else { return 1; } } public static bool testMethod() { return (Main_old() == 0); } } class Arith_TestClass_div0064 { public static int Main_old() { double d1 = 0.0; double d2 = 2.0; double d3 = d1 / d2; if (d3 == 0.0) { return 0; } else { return 1; } } public static bool testMethod() { return (Main_old() == 0); } } class Arith_TestClass_div0065 { public static int Main_old() { double d1 = 0.0; double d2 = -2.0; double d3 = d1 / d2; if (d3 == -0.0) { return 0; } else { return 1; } } public static bool testMethod() { return (Main_old() == 0); } } class Arith_TestClass_div0071 { public static int Main_old() { double d1 = -0.0; double d2 = 2.0; double d3 = d1 / d2; if (d3 == -0.0) { return 0; } else { return 1; } } public static bool testMethod() { return (Main_old() == 0); } } class Arith_TestClass_div0072 { public static int Main_old() { double d1 = -0.0; double d2 = -2.0; double d3 = d1 / d2; if (d3 == 0.0) { return 0; } else { return 1; } } public static bool testMethod() { return (Main_old() == 0); } } class Arith_TestClass_rem0001 { public static int Main_old() { float f1 = 3.0f; float f2 = 2.0f; float f3 = f1 % f2; if (f3 == 1.0f) { return 0; } else { return 1; } } public static bool testMethod() { return (Main_old() == 0); } } class Arith_TestClass_rem0002 { public static int Main_old() { float f1 = 3.0f; float f2 = -2.0f; float f3 = f1 % f2; if (f3 == 1.0f) { return 0; } else { return 1; } } public static bool testMethod() { return (Main_old() == 0); } } class Arith_TestClass_rem0008 { public static int Main_old() { float f1 = -3.0f; float f2 = 2.0f; float f3 = f1 % f2; if (f3 == -1.0f) { return 0; } else { return 1; } } public static bool testMethod() { return (Main_old() == 0); } } class Arith_TestClass_rem0009 { public static int Main_old() { float f1 = -3.0f; float f2 = -2.0f; float f3 = f1 % f2; if (f3 == -1.0f) { return 0; } else { return 1; } } public static bool testMethod() { return (Main_old() == 0); } } class Arith_TestClass_rem0015 { public static int Main_old() { float f1 = 0.0f; float f2 = 2.0f; float f3 = f1 % f2; if (f3 == 0.0f) { return 0; } else { return 1; } } public static bool testMethod() { return (Main_old() == 0); } } class Arith_TestClass_rem0016 { public static int Main_old() { float f1 = 0.0f; float f2 = -2.0f; float f3 = f1 % f2; if (f3 == 0.0f) { return 0; } else { return 1; } } public static bool testMethod() { return (Main_old() == 0); } } class Arith_TestClass_rem0022 { public static int Main_old() { float f1 = -0.0f; float f2 = 2.0f; float f3 = f1 % f2; if (f3 == -0.0f) { return 0; } else { return 1; } } public static bool testMethod() { return (Main_old() == 0); } } class Arith_TestClass_rem0023 { public static int Main_old() { float f1 = -0.0f; float f2 = -2.0f; float f3 = f1 % f2; if (f3 == -0.0f) { return 0; } else { return 1; } } public static bool testMethod() { return (Main_old() == 0); } } class Arith_TestClass_rem0050 { public static int Main_old() { double d1 = 3.0; double d2 = 2.0; double d3 = d1 % d2; if (d3 == 1.0) { return 0; } else { return 1; } } public static bool testMethod() { return (Main_old() == 0); } } class Arith_TestClass_rem0051 { public static int Main_old() { double d1 = 3.0; double d2 = -2.0; double d3 = d1 % d2; if (d3 == 1.0) { return 0; } else { return 1; } } public static bool testMethod() { return (Main_old() == 0); } } class Arith_TestClass_rem0057 { public static int Main_old() { double d1 = -3.0; double d2 = 2.0; double d3 = d1 % d2; if (d3 == -1.0) { return 0; } else { return 1; } } public static bool testMethod() { return (Main_old() == 0); } } class Arith_TestClass_rem0058 { public static int Main_old() { double d1 = -3.0; double d2 = -2.0; double d3 = d1 % d2; if (d3 == -1.0) { return 0; } else { return 1; } } public static bool testMethod() { return (Main_old() == 0); } } class Arith_TestClass_rem0064 { public static int Main_old() { double d1 = 0.0; double d2 = 2.0; double d3 = d1 % d2; if (d3 == 0.0) { return 0; } else { return 1; } } public static bool testMethod() { return (Main_old() == 0); } } class Arith_TestClass_rem0065 { public static int Main_old() { double d1 = 0.0; double d2 = -2.0; double d3 = d1 % d2; if (d3 == 0.0) { return 0; } else { return 1; } } public static bool testMethod() { return (Main_old() == 0); } } class Arith_TestClass_rem0071 { public static int Main_old() { double d1 = -0.0; double d2 = 2.0; double d3 = d1 % d2; if (d3 == -0.0) { return 0; } else { return 1; } } public static bool testMethod() { return (Main_old() == 0); } } class Arith_TestClass_rem0072 { public static int Main_old() { double d1 = -0.0; double d2 = -2.0; double d3 = d1 % d2; if (d3 == -0.0) { return 0; } else { return 1; } } public static bool testMethod() { return (Main_old() == 0); } } class Arith_TestClass_add0001 { public static int Main_old() { float f1 = 3.0f; float f2 = -2.0f; float f3 = f1 + f2; if (f3 == 1.0f) { return 0; } else { return 1; } } public static bool testMethod() { return (Main_old() == 0); } } class Arith_TestClass_add0002 { public static int Main_old() { float f1 = 3.0f; float f2 = 0.0f; float f3 = f1 + f2; if (f3 == 3.0f) { return 0; } else { return 1; } } public static bool testMethod() { return (Main_old() == 0); } } class Arith_TestClass_add0003 { public static int Main_old() { float f1 = 3.0f; float f2 = -0.0f; float f3 = f1 + f2; if (f3 == 3.0f) { return 0; } else { return 1; } } public static bool testMethod() { return (Main_old() == 0); } } class Arith_TestClass_add0007 { public static int Main_old() { float f1 = 0.0f; float f2 = -2.0f; float f3 = f1 + f2; if (f3 == -2.0f) { return 0; } else { return 1; } } public static bool testMethod() { return (Main_old() == 0); } } class Arith_TestClass_add0008 { public static int Main_old() { float f1 = 0.0f; float f2 = 0.0f; float f3 = f1 + f2; if (f3 == 0.0f) { return 0; } else { return 1; } } public static bool testMethod() { return (Main_old() == 0); } } class Arith_TestClass_add0009 { public static int Main_old() { float f1 = 0.0f; float f2 = -0.0f; float f3 = f1 + f2; if (f3 == 0.0f) { return 0; } else { return 1; } } public static bool testMethod() { return (Main_old() == 0); } } class Arith_TestClass_add0013 { public static int Main_old() { float f1 = -0.0f; float f2 = -2.0f; float f3 = f1 + f2; if (f3 == -2.0f) { return 0; } else { return 1; } } public static bool testMethod() { return (Main_old() == 0); } } class Arith_TestClass_add0014 { public static int Main_old() { float f1 = -0.0f; float f2 = 0.0f; float f3 = f1 + f2; if (f3 == 0.0f) { return 0; } else { return 1; } } public static bool testMethod() { return (Main_old() == 0); } } class Arith_TestClass_add0015 { public static int Main_old() { float f1 = -0.0f; float f2 = -0.0f; float f3 = f1 + f2; if (f3 == -0.0f) { return 0; } else { return 1; } } public static bool testMethod() { return (Main_old() == 0); } } class Arith_TestClass_add0037 { public static int Main_old() { double d1 = 3.0; double d2 = -2.0; double d3 = d1 + d2; if (d3 == 1.0f) { return 0; } else { return 1; } } public static bool testMethod() { return (Main_old() == 0); } } class Arith_TestClass_add0038 { public static int Main_old() { double d1 = 3.0; double d2 = 0.0; double d3 = d1 + d2; if (d3 == 3.0) { return 0; } else { return 1; } } public static bool testMethod() { return (Main_old() == 0); } } class Arith_TestClass_add0039 { public static int Main_old() { double d1 = 3.0; double d2 = -0.0; double d3 = d1 + d2; if (d3 == 3.0) { return 0; } else { return 1; } } public static bool testMethod() { return (Main_old() == 0); } } class Arith_TestClass_add0043 { public static int Main_old() { double d1 = 0.0; double d2 = -2.0; double d3 = d1 + d2; if (d3 == -2.0) { return 0; } else { return 1; } } public static bool testMethod() { return (Main_old() == 0); } } class Arith_TestClass_add0044 { public static int Main_old() { double d1 = 0.0; double d2 = 0.0; double d3 = d1 + d2; if (d3 == 0.0) { return 0; } else { return 1; } } public static bool testMethod() { return (Main_old() == 0); } } class Arith_TestClass_add0045 { public static int Main_old() { double d1 = 0.0; double d2 = -0.0; double d3 = d1 + d2; if (d3 == 0.0) { return 0; } else { return 1; } } public static bool testMethod() { return (Main_old() == 0); } } class Arith_TestClass_add0049 { public static int Main_old() { double d1 = -0.0; double d2 = -2.0; double d3 = d1 + d2; if (d3 == -2.0) { return 0; } else { return 1; } } public static bool testMethod() { return (Main_old() == 0); } } class Arith_TestClass_add0050 { public static int Main_old() { double d1 = -0.0; double d2 = 0.0; double d3 = d1 + d2; if (d3 == 0.0) { return 0; } else { return 1; } } public static bool testMethod() { return (Main_old() == 0); } } class Arith_TestClass_add0051 { public static int Main_old() { double d1 = -0.0; double d2 = -0.0; double d3 = d1 + d2; if (d3 == -0.0) { return 0; } else { return 1; } } public static bool testMethod() { return (Main_old() == 0); } } class Arith_TestClass_sub0001 { public static int Main_old() { float f1 = 3.0f; float f2 = -2.0f; float f3 = f1 - f2; if (f3 == 5.0f) { return 0; } else { return 1; } } public static bool testMethod() { return (Main_old() == 0); } } class Arith_TestClass_sub0002 { public static int Main_old() { float f1 = 3.0f; float f2 = 0.0f; float f3 = f1 - f2; if (f3 == 3.0f) { return 0; } else { return 1; } } public static bool testMethod() { return (Main_old() == 0); } } class Arith_TestClass_sub0003 { public static int Main_old() { float f1 = 3.0f; float f2 = -0.0f; float f3 = f1 - f2; if (f3 == 3.0f) { return 0; } else { return 1; } } public static bool testMethod() { return (Main_old() == 0); } } class Arith_TestClass_sub0007 { public static int Main_old() { float f1 = 0.0f; float f2 = -2.0f; float f3 = f1 - f2; if (f3 == 2.0f) { return 0; } else { return 1; } } public static bool testMethod() { return (Main_old() == 0); } } class Arith_TestClass_sub0008 { public static int Main_old() { float f1 = 0.0f; float f2 = 0.0f; float f3 = f1 - f2; if (f3 == 0.0f) { return 0; } else { return 1; } } public static bool testMethod() { return (Main_old() == 0); } } class Arith_TestClass_sub0009 { public static int Main_old() { float f1 = 0.0f; float f2 = -0.0f; float f3 = f1 - f2; if (f3 == 0.0f) { return 0; } else { return 1; } } public static bool testMethod() { return (Main_old() == 0); } } class Arith_TestClass_sub0013 { public static int Main_old() { float f1 = -0.0f; float f2 = -2.0f; float f3 = f1 - f2; if (f3 == 2.0f) { return 0; } else { return 1; } } public static bool testMethod() { return (Main_old() == 0); } } class Arith_TestClass_sub0014 { public static int Main_old() { float f1 = -0.0f; float f2 = 0.0f; float f3 = f1 - f2; if (f3 == -0.0f) { return 0; } else { return 1; } } public static bool testMethod() { return (Main_old() == 0); } } class Arith_TestClass_sub0015 { public static int Main_old() { float f1 = -0.0f; float f2 = -0.0f; float f3 = f1 - f2; if (f3 == 0.0f) { return 0; } else { return 1; } } public static bool testMethod() { return (Main_old() == 0); } } class Arith_TestClass_sub0037 { public static int Main_old() { double d1 = 3.0; double d2 = -2.0; double d3 = d1 - d2; if (d3 == 5.0f) { return 0; } else { return 1; } } public static bool testMethod() { return (Main_old() == 0); } } class Arith_TestClass_sub0038 { public static int Main_old() { double d1 = 3.0; double d2 = 0.0; double d3 = d1 - d2; if (d3 == 3.0) { return 0; } else { return 1; } } public static bool testMethod() { return (Main_old() == 0); } } class Arith_TestClass_sub0039 { public static int Main_old() { double d1 = 3.0; double d2 = -0.0; double d3 = d1 - d2; if (d3 == 3.0) { return 0; } else { return 1; } } public static bool testMethod() { return (Main_old() == 0); } } class Arith_TestClass_sub0043 { public static int Main_old() { double d1 = 0.0; double d2 = -2.0; double d3 = d1 - d2; if (d3 == 2.0) { return 0; } else { return 1; } } public static bool testMethod() { return (Main_old() == 0); } } class Arith_TestClass_sub0044 { public static int Main_old() { double d1 = 0.0; double d2 = 0.0; double d3 = d1 - d2; if (d3 == 0.0) { return 0; } else { return 1; } } public static bool testMethod() { return (Main_old() == 0); } } class Arith_TestClass_sub0045 { public static int Main_old() { double d1 = 0.0; double d2 = -0.0; double d3 = d1 - d2; if (d3 == 0.0) { return 0; } else { return 1; } } public static bool testMethod() { return (Main_old() == 0); } } class Arith_TestClass_sub0049 { public static int Main_old() { double d1 = -0.0; double d2 = -2.0; double d3 = d1 - d2; if (d3 == 2.0) { return 0; } else { return 1; } } public static bool testMethod() { return (Main_old() == 0); } } class Arith_TestClass_sub0050 { public static int Main_old() { double d1 = -0.0; double d2 = 0.0; double d3 = d1 - d2; if (d3 == -0.0) { return 0; } else { return 1; } } public static bool testMethod() { return (Main_old() == 0); } } class Arith_TestClass_sub0051 { public static int Main_old() { double d1 = -0.0; double d2 = -0.0; double d3 = d1 - d2; if (d3 == 0.0) { return 0; } else { return 1; } } public static bool testMethod() { return (Main_old() == 0); } } } } ================================================ FILE: Zelig/Zelig/Test/RunTime/NETMF/mscorlib/expressions/expressions1/OtherTests1.cs ================================================ //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // Copyright (c) Microsoft Corporation. All rights reserved. //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// using System; using System.Reflection; using Microsoft.SPOT.Platform.Test; namespace Microsoft.SPOT.Platform.Tests { public class OtherTests1 : IMFTestInterface { [SetUp] public InitializeResult Initialize() { Log.Comment("Adding set up for the tests"); return InitializeResult.ReadyToGo; } [TearDown] public void CleanUp() { Log.Comment("Cleaning up after the tests"); } //Other Test methods //The following tests were ported from folder current\test\cases\client\CLR\Conformance\10_classes\Other //ident001,ident002,ident003,ident004,ident007,ident008,ident009,ident010,ident011,ident012,ident013,ident014,ident015,ident016,ident017,ident018,ident019,ident020,ident021,ident022,ident023,ident024,ident025,ident026,ident027,ident028,ident029,ident030,ident031,ident032,ident033,ident034,ident035,ident038,ident039,ident040,mem001,mem002,mem003,mem004,mem005,mem006,mem007,mem008,mem011,mem012,mem013,mem014,mem015,mem016,mem017,mem018,mem019,mem021,mem022,mem023,mem025,mem026,mem027,mem028,mem029,mem031,mem032,mem034,mem035,mem036,mem038,mem040,mem042,mem043,mem044,mem045,mem046,mem047,mem048,mem050,mem052,mem054,mem055,mem056,mem058,lit001,lit004,lit005,lit006,lit007,lit008,lit009,lit010,lit011,base006,base007,base009,base010,base011,base012,base013,base014,base015,base016,base017,base018,base019,base020,Shift_001,Shift_002,Shift_003,Shift_004,Shift_005,Shift_006,Shift_007,Shift_008,Shift_009,Shift_015,Shift_016,Shift_017,Shift_018,Shift_019,Shift_020,Shift_021,Shift_022,Shift_023,shift_029,shift_030,Shift_037,Shift_038,Shift_041,Shift_042,Shift_043,Shift_044,assign001,assign002,assign003,assign004,assign005,assign006,assign007,assign008,assign009,assign010,assign011,unary001,unary002,unary003,unary004,unary005,unary006,unary007,unary008,unary009,unary012,unary013,unary014,unary015,unary017,unary018,unary019,unary020,unary021,unary023,unary024,unary025,unary026,unary027,unary028,unary029,unary030,unary031,unary036,unary037,unary038,unary039,unary040,unary041,unary042,unary043,unary044,unary045,unary046,unary048,unary049,unary050,unary051,unary052,unary053,unary054,unary055,unary056,unary057,unary058,unary068,relat001,relat002,relat003,relat004,relat005,relat006,relat007,relat008,relat009,relat010,relat011,relat012,relat013,relat014,relat015,relat016,relat017,relat018,relat019,relat020,relat021,relat022,relat023,relat024,relat025,relat026,relat027,relat028,relat029,relat030,relat031,relat032,relat033,relat034,relat035,relat036,relat037,relat038,relat039,relat040,relat041,relat042,relat043,relat044,relat045,relat046,relat047,relat048,relat055,relat056,relat057,relat058,relat059,relat060,relat061,relat062,relat063,relat064,relat065,relat066,relat069,relat072,relat073,relat074,relat075,relat076,relat077,relat078,relat079,relat080,relat081,relat083,relat084,relat086,relat087,relat088,relat089,operators_logic001,operators_logic002,operators_logic003,operators_logic004,operators_logic005,operators_logic006,operators_logic007,operators_logic008,operators_logic009,operators_logic010,operators_logic011,operators_logic012,operators_logic013,operators_logic014,operators_logic015,operators_logic016,operators_logic017,operators_logic018,operators_logic019,operators_logic022,operators_logic023,operators_logic032,operators_logic033,cond001,cond002,cond003,cond004,cond005,cond006,cond008,cond010,cond011,cond014,cond015,is005,is006,is007,is008,is009,is010,is011,is012,is013,is014,is015,is016,is017,is018,is019,is020,is021,is022,is023,is024,is025,is026,is027,is028,is029,is030,is031,is032,is033,is034,as001,as002,as003,as004,as007,as008,as011,as012,add001,add002,add003,add004,add005,add006,logic001,logic002,logic003,logic004,logic005,logic006,logic007,logic008,logic009,logic010,logic011,logic012,logic013,logic014,logic015,logic016,logic017,logic018,logic019,logic020,logic021,logic022,logic023,logic024,logic025,logic026,logic027,logic028,logic029,logic030,logic032 //Test Case Calls [TestMethod] public MFTestResults Other_unary068_Test() { Log.Comment(" 7.6.5 Operator Overloading - Unary operator"); if (Other_TestClass_unary068.testMethod()) { return MFTestResults.Pass; } return MFTestResults.Fail; } [TestMethod] public MFTestResults Other_relat001_Test() { Log.Comment("Section 7.9"); if (Other_TestClass_relat001.testMethod()) { return MFTestResults.Pass; } return MFTestResults.Fail; } [TestMethod] public MFTestResults Other_relat002_Test() { Log.Comment("Section 7.9"); if (Other_TestClass_relat002.testMethod()) { return MFTestResults.Pass; } return MFTestResults.Fail; } [TestMethod] public MFTestResults Other_relat003_Test() { Log.Comment("Section 7.9"); if (Other_TestClass_relat003.testMethod()) { return MFTestResults.Pass; } return MFTestResults.Fail; } [TestMethod] public MFTestResults Other_relat004_Test() { Log.Comment("Section 7.9"); if (Other_TestClass_relat004.testMethod()) { return MFTestResults.Pass; } return MFTestResults.Fail; } [TestMethod] public MFTestResults Other_relat005_Test() { Log.Comment("Section 7.9"); if (Other_TestClass_relat005.testMethod()) { return MFTestResults.Pass; } return MFTestResults.Fail; } [TestMethod] public MFTestResults Other_relat006_Test() { Log.Comment("Section 7.9"); if (Other_TestClass_relat006.testMethod()) { return MFTestResults.Pass; } return MFTestResults.Fail; } [TestMethod] public MFTestResults Other_relat007_Test() { Log.Comment("Section 7.9"); if (Other_TestClass_relat007.testMethod()) { return MFTestResults.Pass; } return MFTestResults.Fail; } [TestMethod] public MFTestResults Other_relat008_Test() { Log.Comment("Section 7.9"); if (Other_TestClass_relat008.testMethod()) { return MFTestResults.Pass; } return MFTestResults.Fail; } [TestMethod] public MFTestResults Other_relat009_Test() { Log.Comment("Section 7.9"); if (Other_TestClass_relat009.testMethod()) { return MFTestResults.Pass; } return MFTestResults.Fail; } [TestMethod] public MFTestResults Other_relat010_Test() { Log.Comment("Section 7.9"); if (Other_TestClass_relat010.testMethod()) { return MFTestResults.Pass; } return MFTestResults.Fail; } [TestMethod] public MFTestResults Other_relat011_Test() { Log.Comment("Section 7.9"); if (Other_TestClass_relat011.testMethod()) { return MFTestResults.Pass; } return MFTestResults.Fail; } [TestMethod] public MFTestResults Other_relat012_Test() { Log.Comment("Section 7.9"); if (Other_TestClass_relat012.testMethod()) { return MFTestResults.Pass; } return MFTestResults.Fail; } [TestMethod] public MFTestResults Other_relat013_Test() { Log.Comment("Section 7.9"); if (Other_TestClass_relat013.testMethod()) { return MFTestResults.Pass; } return MFTestResults.Fail; } [TestMethod] public MFTestResults Other_relat014_Test() { Log.Comment("Section 7.9"); if (Other_TestClass_relat014.testMethod()) { return MFTestResults.Pass; } return MFTestResults.Fail; } [TestMethod] public MFTestResults Other_relat015_Test() { Log.Comment("Section 7.9"); if (Other_TestClass_relat015.testMethod()) { return MFTestResults.Pass; } return MFTestResults.Fail; } [TestMethod] public MFTestResults Other_relat016_Test() { Log.Comment("Section 7.9"); if (Other_TestClass_relat016.testMethod()) { return MFTestResults.Pass; } return MFTestResults.Fail; } [TestMethod] public MFTestResults Other_relat017_Test() { Log.Comment("Section 7.9"); if (Other_TestClass_relat017.testMethod()) { return MFTestResults.Pass; } return MFTestResults.Fail; } [TestMethod] public MFTestResults Other_relat018_Test() { Log.Comment("Section 7.9"); if (Other_TestClass_relat018.testMethod()) { return MFTestResults.Pass; } return MFTestResults.Fail; } [TestMethod] public MFTestResults Other_relat019_Test() { Log.Comment("Section 7.9"); if (Other_TestClass_relat019.testMethod()) { return MFTestResults.Pass; } return MFTestResults.Fail; } [TestMethod] public MFTestResults Other_relat020_Test() { Log.Comment("Section 7.9"); if (Other_TestClass_relat020.testMethod()) { return MFTestResults.Pass; } return MFTestResults.Fail; } [TestMethod] public MFTestResults Other_relat021_Test() { Log.Comment("Section 7.9"); if (Other_TestClass_relat021.testMethod()) { return MFTestResults.Pass; } return MFTestResults.Fail; } [TestMethod] public MFTestResults Other_relat022_Test() { Log.Comment("Section 7.9"); if (Other_TestClass_relat022.testMethod()) { return MFTestResults.Pass; } return MFTestResults.Fail; } [TestMethod] public MFTestResults Other_relat023_Test() { Log.Comment("Section 7.9"); if (Other_TestClass_relat023.testMethod()) { return MFTestResults.Pass; } return MFTestResults.Fail; } [TestMethod] public MFTestResults Other_relat024_Test() { Log.Comment("Section 7.9"); if (Other_TestClass_relat024.testMethod()) { return MFTestResults.Pass; } return MFTestResults.Fail; } [TestMethod] public MFTestResults Other_relat025_Test() { Log.Comment("Section 7.9"); if (Other_TestClass_relat025.testMethod()) { return MFTestResults.Pass; } return MFTestResults.Fail; } [TestMethod] public MFTestResults Other_relat026_Test() { Log.Comment("Section 7.9"); if (Other_TestClass_relat026.testMethod()) { return MFTestResults.Pass; } return MFTestResults.Fail; } [TestMethod] public MFTestResults Other_relat027_Test() { Log.Comment("Section 7.9"); if (Other_TestClass_relat027.testMethod()) { return MFTestResults.Pass; } return MFTestResults.Fail; } [TestMethod] public MFTestResults Other_relat028_Test() { Log.Comment("Section 7.9"); if (Other_TestClass_relat028.testMethod()) { return MFTestResults.Pass; } return MFTestResults.Fail; } [TestMethod] public MFTestResults Other_relat029_Test() { Log.Comment("Section 7.9"); if (Other_TestClass_relat029.testMethod()) { return MFTestResults.Pass; } return MFTestResults.Fail; } [TestMethod] public MFTestResults Other_relat030_Test() { Log.Comment("Section 7.9"); if (Other_TestClass_relat030.testMethod()) { return MFTestResults.Pass; } return MFTestResults.Fail; } [TestMethod] public MFTestResults Other_relat031_Test() { Log.Comment("Section 7.9"); if (Other_TestClass_relat031.testMethod()) { return MFTestResults.Pass; } return MFTestResults.Fail; } [TestMethod] public MFTestResults Other_relat032_Test() { Log.Comment("Section 7.9"); if (Other_TestClass_relat032.testMethod()) { return MFTestResults.Pass; } return MFTestResults.Fail; } [TestMethod] public MFTestResults Other_relat033_Test() { Log.Comment("Section 7.9"); if (Other_TestClass_relat033.testMethod()) { return MFTestResults.Pass; } return MFTestResults.Fail; } [TestMethod] public MFTestResults Other_relat034_Test() { Log.Comment("Section 7.9"); if (Other_TestClass_relat034.testMethod()) { return MFTestResults.Pass; } return MFTestResults.Fail; } [TestMethod] public MFTestResults Other_relat035_Test() { Log.Comment("Section 7.9"); if (Other_TestClass_relat035.testMethod()) { return MFTestResults.Pass; } return MFTestResults.Fail; } [TestMethod] public MFTestResults Other_relat036_Test() { Log.Comment("Section 7.9"); if (Other_TestClass_relat036.testMethod()) { return MFTestResults.Pass; } return MFTestResults.Fail; } /* [TestMethod] public MFTestResults Other_relat037_Test() { Log.Comment("Section 7.9"); Log.Comment("If either operand is NaN, the result is false"); Log.Comment("for all operators except !=, and true for !="); Log.Comment("operator."); if (Other_TestClass_relat037.testMethod()) { return MFTestResults.Pass; } return MFTestResults.Fail; } [TestMethod] public MFTestResults Other_relat038_Test() { Log.Comment("Section 7.9"); Log.Comment("If either operand is NaN, the result is false"); Log.Comment("for all operators except !=, and true for !="); Log.Comment("operator."); if (Other_TestClass_relat038.testMethod()) { return MFTestResults.Pass; } return MFTestResults.Fail; } [TestMethod] public MFTestResults Other_relat039_Test() { Log.Comment("Section 7.9"); Log.Comment("If either operand is NaN, the result is false"); Log.Comment("for all operators except !=, and true for !="); Log.Comment("operator."); if (Other_TestClass_relat039.testMethod()) { return MFTestResults.Pass; } return MFTestResults.Fail; } [TestMethod] public MFTestResults Other_relat040_Test() { Log.Comment("Section 7.9"); Log.Comment("If either operand is NaN, the result is false"); Log.Comment("for all operators except !=, and true for !="); Log.Comment("operator."); if (Other_TestClass_relat040.testMethod()) { return MFTestResults.Pass; } return MFTestResults.Fail; } [TestMethod] public MFTestResults Other_relat041_Test() { Log.Comment("Section 7.9"); Log.Comment("If either operand is NaN, the result is false"); Log.Comment("for all operators except !=, and true for !="); Log.Comment("operator."); if (Other_TestClass_relat041.testMethod()) { return MFTestResults.Pass; } return MFTestResults.Fail; } [TestMethod] public MFTestResults Other_relat042_Test() { Log.Comment("Section 7.9"); Log.Comment("If either operand is NaN, the result is false"); Log.Comment("for all operators except !=, and true for !="); Log.Comment("operator."); if (Other_TestClass_relat042.testMethod()) { return MFTestResults.Pass; } return MFTestResults.Fail; } [TestMethod] public MFTestResults Other_relat043_Test() { Log.Comment("Section 7.9"); Log.Comment("Negative and positive zero is considered"); Log.Comment("equal."); if (Other_TestClass_relat043.testMethod()) { return MFTestResults.Pass; } return MFTestResults.Fail; } [TestMethod] public MFTestResults Other_relat044_Test() { Log.Comment("Section 7.9"); Log.Comment("Negative and positive zero is considered"); Log.Comment("equal."); if (Other_TestClass_relat044.testMethod()) { return MFTestResults.Pass; } return MFTestResults.Fail; } [TestMethod] public MFTestResults Other_relat045_Test() { Log.Comment("Section 7.9"); Log.Comment("Other_TestClass_?_A negative infinity is considered less than"); Log.Comment("all other values, but equal to another negative"); Log.Comment("infinity."); if (Other_TestClass_relat045.testMethod()) { return MFTestResults.Pass; } return MFTestResults.Fail; } [TestMethod] public MFTestResults Other_relat046_Test() { Log.Comment("Section 7.9"); Log.Comment("Other_TestClass_?_A negative infinity is considered less than"); Log.Comment("all other values, but equal to another negative"); Log.Comment("infinity."); if (Other_TestClass_relat046.testMethod()) { return MFTestResults.Pass; } return MFTestResults.Fail; } [TestMethod] public MFTestResults Other_relat047_Test() { Log.Comment("Section 7.9"); Log.Comment("Other_TestClass_?_A positive infinity is considered greater than all"); Log.Comment("other values, but equal to positive infinity."); if (Other_TestClass_relat047.testMethod()) { return MFTestResults.Pass; } return MFTestResults.Fail; } [TestMethod] public MFTestResults Other_relat048_Test() { Log.Comment("Section 7.9"); Log.Comment("Other_TestClass_?_A positive infinity is considered greater than all"); Log.Comment("other values, but equal to positive infinity."); if (Other_TestClass_relat048.testMethod()) { return MFTestResults.Pass; } return MFTestResults.Fail; } */ [TestMethod] public MFTestResults Other_relat055_Test() { Log.Comment("Section 7.9"); if (Other_TestClass_relat055.testMethod()) { return MFTestResults.Pass; } return MFTestResults.Fail; } [TestMethod] public MFTestResults Other_relat056_Test() { Log.Comment("Section 7.9"); if (Other_TestClass_relat056.testMethod()) { return MFTestResults.Pass; } return MFTestResults.Fail; } [TestMethod] public MFTestResults Other_relat057_Test() { Log.Comment("Section 7.9"); if (Other_TestClass_relat057.testMethod()) { return MFTestResults.Pass; } return MFTestResults.Fail; } [TestMethod] public MFTestResults Other_relat058_Test() { Log.Comment("Section 7.9"); if (Other_TestClass_relat058.testMethod()) { return MFTestResults.Pass; } return MFTestResults.Fail; } [TestMethod] public MFTestResults Other_relat059_Test() { Log.Comment("Section 7.9"); if (Other_TestClass_relat059.testMethod()) { return MFTestResults.Pass; } return MFTestResults.Fail; } [TestMethod] public MFTestResults Other_relat060_Test() { Log.Comment("Section 7.9"); if (Other_TestClass_relat060.testMethod()) { return MFTestResults.Pass; } return MFTestResults.Fail; } [TestMethod] public MFTestResults Other_relat061_Test() { Log.Comment("Section 7.9"); if (Other_TestClass_relat061.testMethod()) { return MFTestResults.Pass; } return MFTestResults.Fail; } [TestMethod] public MFTestResults Other_relat062_Test() { Log.Comment("Section 7.9"); if (Other_TestClass_relat062.testMethod()) { return MFTestResults.Pass; } return MFTestResults.Fail; } [TestMethod] public MFTestResults Other_relat063_Test() { Log.Comment("Section 7.9"); Log.Comment("since the predefined reference type equality"); Log.Comment("operators accept operands of type object, they"); Log.Comment("apply to all types that do not declare applicable"); Log.Comment("operator == and != members. Conversely, any "); Log.Comment("applicable user-defined equality operators"); Log.Comment("effectively hide the predefined reference type"); Log.Comment("equality operators."); if (Other_TestClass_relat063.testMethod()) { return MFTestResults.Pass; } return MFTestResults.Fail; } [TestMethod] public MFTestResults Other_relat064_Test() { Log.Comment("Section 7.9"); Log.Comment("since the predefined reference type equality"); Log.Comment("operators accept operands of type object, they"); Log.Comment("apply to all types that do not declare applicable"); Log.Comment("operator == and != members. Conversely, any "); Log.Comment("applicable user-defined equality operators"); Log.Comment("effectively hide the predefined reference type"); Log.Comment("equality operators."); if (Other_TestClass_relat064.testMethod()) { return MFTestResults.Pass; } return MFTestResults.Fail; } [TestMethod] public MFTestResults Other_relat065_Test() { Log.Comment("Section 7.9"); Log.Comment("since the predefined reference type equality"); Log.Comment("operators accept operands of type object, they"); Log.Comment("apply to all types that do not declare applicable"); Log.Comment("operator == and != members. Conversely, any "); Log.Comment("applicable user-defined equality operators"); Log.Comment("effectively hide the predefined reference type"); Log.Comment("equality operators."); if (Other_TestClass_relat065.testMethod()) { return MFTestResults.Pass; } return MFTestResults.Fail; } [TestMethod] public MFTestResults Other_relat066_Test() { Log.Comment("Section 7.9"); Log.Comment("since the predefined reference type equality"); Log.Comment("operators accept operands of type object, they"); Log.Comment("apply to all types that do not declare applicable"); Log.Comment("operator == and != members. Conversely, any "); Log.Comment("applicable user-defined equality operators"); Log.Comment("effectively hide the predefined reference type"); Log.Comment("equality operators."); if (Other_TestClass_relat066.testMethod()) { return MFTestResults.Pass; } return MFTestResults.Fail; } [TestMethod] public MFTestResults Other_relat069_Test() { Log.Comment("Section 7.9"); Log.Comment("It is an error to use the predefined reference"); Log.Comment("type equality operators to compare two references"); Log.Comment("that are known to be different at compile-time."); if (Other_TestClass_relat069.testMethod()) { return MFTestResults.Pass; } return MFTestResults.Fail; } [TestMethod] public MFTestResults Other_relat072_Test() { Log.Comment("Section 7.9"); Log.Comment("The predefined reference type equality operators"); Log.Comment("do not permit value type operands to be compared."); Log.Comment("Therefore, unless a struct type declares its own"); Log.Comment("equality operators, it is not possible to compare"); Log.Comment("values of that struct type."); if (Other_TestClass_relat072.testMethod()) { return MFTestResults.Pass; } return MFTestResults.Fail; } [TestMethod] public MFTestResults Other_relat073_Test() { Log.Comment("Section 7.9"); Log.Comment("For an operation of the form x==y or x!=y, "); Log.Comment("if any appicable operator == or != exists, the"); Log.Comment("operator overload resolution rules will select"); Log.Comment("that operator instead of the predefined reference"); Log.Comment("type equality operator. However, it is always"); Log.Comment("possible to select the reference type equality"); Log.Comment("operator by explicitly casting one or both of"); Log.Comment("the operands to type object."); if (Other_TestClass_relat073.testMethod()) { return MFTestResults.Pass; } return MFTestResults.Fail; } [TestMethod] public MFTestResults Other_relat074_Test() { Log.Comment("Section 7.9"); Log.Comment("For an operation of the form x==y or x!=y, "); Log.Comment("if any appicable operator == or != exists, the"); Log.Comment("operator overload resolution rules will select"); Log.Comment("that operator instead of the predefined reference"); Log.Comment("type equality operator. However, it is always"); Log.Comment("possible to select the reference type equality"); Log.Comment("operator by explicitly casting one or both of"); Log.Comment("the operands to type object."); if (Other_TestClass_relat074.testMethod()) { return MFTestResults.Pass; } return MFTestResults.Fail; } [TestMethod] public MFTestResults Other_relat075_Test() { Log.Comment("Section 7.9"); if (Other_TestClass_relat075.testMethod()) { return MFTestResults.Pass; } return MFTestResults.Fail; } [TestMethod] public MFTestResults Other_relat076_Test() { Log.Comment("Section 7.9"); if (Other_TestClass_relat076.testMethod()) { return MFTestResults.Pass; } return MFTestResults.Fail; } [TestMethod] public MFTestResults Other_relat077_Test() { Log.Comment("Section 7.9"); if (Other_TestClass_relat077.testMethod()) { return MFTestResults.Pass; } return MFTestResults.Fail; } [TestMethod] public MFTestResults Other_relat078_Test() { Log.Comment("Section 7.9"); if (Other_TestClass_relat078.testMethod()) { return MFTestResults.Pass; } return MFTestResults.Fail; } /* [TestMethod] public MFTestResults Other_relat079_Test() { Log.Comment("Section 7.9"); if (Other_TestClass_relat079.testMethod()) { return MFTestResults.Pass; } return MFTestResults.Fail; } */ [TestMethod] public MFTestResults Other_relat080_Test() { Log.Comment("Section 7.9"); if (Other_TestClass_relat080.testMethod()) { return MFTestResults.Pass; } return MFTestResults.Fail; } [TestMethod] public MFTestResults Other_relat081_Test() { Log.Comment("Section 7.9"); if (Other_TestClass_relat081.testMethod()) { return MFTestResults.Pass; } return MFTestResults.Fail; } [TestMethod] public MFTestResults Other_relat083_Test() { Log.Comment("Section 7.9"); if (Other_TestClass_relat083.testMethod()) { return MFTestResults.Pass; } return MFTestResults.Fail; } [TestMethod] public MFTestResults Other_relat084_Test() { Log.Comment("Section 7.9"); if (Other_TestClass_relat084.testMethod()) { return MFTestResults.Pass; } return MFTestResults.Fail; } [TestMethod] public MFTestResults Other_relat086_Test() { Log.Comment("Making sure floating point relational operators are working correctly for negative"); Log.Comment("vs. positive values."); if (Other_TestClass_relat086.testMethod()) { return MFTestResults.Pass; } return MFTestResults.Fail; } [TestMethod] public MFTestResults Other_relat087_Test() { Log.Comment("Making sure floating point relational operators are working correctly for negative"); Log.Comment("vs. positive values."); if (Other_TestClass_relat087.testMethod()) { return MFTestResults.Pass; } return MFTestResults.Fail; } [TestMethod] public MFTestResults Other_relat088_Test() { Log.Comment("Making sure floating point relational operators are working correctly for negative"); Log.Comment("vs. positive values."); if (Other_TestClass_relat088.testMethod()) { return MFTestResults.Pass; } return MFTestResults.Fail; } [TestMethod] public MFTestResults Other_relat089_Test() { Log.Comment("Making sure floating point relational operators are working correctly for negative"); Log.Comment("vs. positive values."); if (Other_TestClass_relat089.testMethod()) { return MFTestResults.Pass; } return MFTestResults.Fail; } [TestMethod] public MFTestResults Other_operators_logic001_Test() { Log.Comment("Section 7.10"); if (Other_TestClass_operators_logic001.testMethod()) { return MFTestResults.Pass; } return MFTestResults.Fail; } [TestMethod] public MFTestResults Other_operators_logic002_Test() { Log.Comment("Section 7.10"); if (Other_TestClass_operators_logic002.testMethod()) { return MFTestResults.Pass; } return MFTestResults.Fail; } [TestMethod] public MFTestResults Other_operators_logic003_Test() { Log.Comment("Section 7.10"); if (Other_TestClass_operators_logic003.testMethod()) { return MFTestResults.Pass; } return MFTestResults.Fail; } [TestMethod] public MFTestResults Other_operators_logic004_Test() { Log.Comment("Section 7.10"); if (Other_TestClass_operators_logic004.testMethod()) { return MFTestResults.Pass; } return MFTestResults.Fail; } [TestMethod] public MFTestResults Other_operators_logic005_Test() { Log.Comment("Section 7.10"); if (Other_TestClass_operators_logic005.testMethod()) { return MFTestResults.Pass; } return MFTestResults.Fail; } [TestMethod] public MFTestResults Other_operators_logic006_Test() { Log.Comment("Section 7.10"); if (Other_TestClass_operators_logic006.testMethod()) { return MFTestResults.Pass; } return MFTestResults.Fail; } [TestMethod] public MFTestResults Other_operators_logic007_Test() { Log.Comment("Section 7.10"); if (Other_TestClass_operators_logic007.testMethod()) { return MFTestResults.Pass; } return MFTestResults.Fail; } [TestMethod] public MFTestResults Other_operators_logic008_Test() { Log.Comment("Section 7.10"); if (Other_TestClass_operators_logic008.testMethod()) { return MFTestResults.Pass; } return MFTestResults.Fail; } [TestMethod] public MFTestResults Other_operators_logic009_Test() { Log.Comment("Section 7.10"); if (Other_TestClass_operators_logic009.testMethod()) { return MFTestResults.Pass; } return MFTestResults.Fail; } [TestMethod] public MFTestResults Other_operators_logic010_Test() { Log.Comment("Section 7.10"); if (Other_TestClass_operators_logic010.testMethod()) { return MFTestResults.Pass; } return MFTestResults.Fail; } [TestMethod] public MFTestResults Other_operators_logic011_Test() { Log.Comment("Section 7.10"); if (Other_TestClass_operators_logic011.testMethod()) { return MFTestResults.Pass; } return MFTestResults.Fail; } [TestMethod] public MFTestResults Other_operators_logic012_Test() { Log.Comment("Section 7.10"); if (Other_TestClass_operators_logic012.testMethod()) { return MFTestResults.Pass; } return MFTestResults.Fail; } [TestMethod] public MFTestResults Other_operators_logic013_Test() { Log.Comment("Section 7.10"); if (Other_TestClass_operators_logic013.testMethod()) { return MFTestResults.Pass; } return MFTestResults.Fail; } [TestMethod] public MFTestResults Other_operators_logic014_Test() { Log.Comment("Section 7.10"); if (Other_TestClass_operators_logic014.testMethod()) { return MFTestResults.Pass; } return MFTestResults.Fail; } [TestMethod] public MFTestResults Other_operators_logic015_Test() { Log.Comment("Section 7.10"); if (Other_TestClass_operators_logic015.testMethod()) { return MFTestResults.Pass; } return MFTestResults.Fail; } [TestMethod] public MFTestResults Other_operators_logic016_Test() { Log.Comment("Section 7.11"); Log.Comment("The operation x (double amp) y corresponds to the"); Log.Comment("operation x (amp) y except that y is evaluated only"); Log.Comment("if x is true."); if (Other_TestClass_operators_logic016.testMethod()) { return MFTestResults.Pass; } return MFTestResults.Fail; } [TestMethod] public MFTestResults Other_operators_logic017_Test() { Log.Comment("Section 7.11"); Log.Comment("The operation x (double amp) y corresponds to the"); Log.Comment("operation x (amp) y except that y is evaluated only"); Log.Comment("if x is true."); if (Other_TestClass_operators_logic017.testMethod()) { return MFTestResults.Pass; } return MFTestResults.Fail; } [TestMethod] public MFTestResults Other_operators_logic018_Test() { Log.Comment("Section 7.11"); Log.Comment("The operation x || y corresponds to the"); Log.Comment("operation x (amp) y except that y is evaluated only"); Log.Comment("if x is false."); if (Other_TestClass_operators_logic018.testMethod()) { return MFTestResults.Pass; } return MFTestResults.Fail; } [TestMethod] public MFTestResults Other_operators_logic019_Test() { Log.Comment("Section 7.11"); Log.Comment("The operation x || y corresponds to the"); Log.Comment("operation x (amp) y except that y is evaluated only"); Log.Comment("if x is false."); if (Other_TestClass_operators_logic019.testMethod()) { return MFTestResults.Pass; } return MFTestResults.Fail; } /* [TestMethod] public MFTestResults Other_operators_logic022_Test() { Log.Comment("Section 7.11"); Log.Comment("When the operands of && or || are of types"); Log.Comment("that declare an applicable user-defined operator &"); Log.Comment("or operator |, both of the following must be true,"); Log.Comment("where T is the type in which the selected operand"); Log.Comment("is declared:"); Log.Comment("The return type and the type of each parameter of "); Log.Comment("the selected operator must be T. In other words, "); Log.Comment("the operator must compute the logical AND or the"); Log.Comment("logical OR of the two operands of type T, and must"); Log.Comment("return a result of type T."); Log.Comment("T must contain declarations of operator true and"); Log.Comment("operator false."); if (Other_TestClass_operators_logic022.testMethod()) { return MFTestResults.Pass; } return MFTestResults.Fail; } [TestMethod] public MFTestResults Other_operators_logic023_Test() { Log.Comment("Section 7.11"); Log.Comment("When the operands of && or || are of types"); Log.Comment("that declare an applicable user-defined operator &"); Log.Comment("or operator |, both of the following must be true,"); Log.Comment("where T is the type in which the selected operand"); Log.Comment("is declared:"); Log.Comment("The return type and the type of each parameter of "); Log.Comment("the selected operator must be T. In other words, "); Log.Comment("the operator must compute the logical AND or the"); Log.Comment("logical OR of the two operands of type T, and must"); Log.Comment("return a result of type T."); Log.Comment("T must contain declarations of operator true and"); Log.Comment("operator false."); if (Other_TestClass_operators_logic023.testMethod()) { return MFTestResults.Pass; } return MFTestResults.Fail; } [TestMethod] public MFTestResults Other_operators_logic032_Test() { Log.Comment("Section 7.11"); if (Other_TestClass_operators_logic032.testMethod()) { return MFTestResults.Pass; } return MFTestResults.Fail; } */ [TestMethod] public MFTestResults Other_operators_logic033_Test() { Log.Comment("Section 7.11"); if (Other_TestClass_operators_logic033.testMethod()) { return MFTestResults.Pass; } return MFTestResults.Fail; } [TestMethod] public MFTestResults Other_cond001_Test() { Log.Comment("Section 7.12"); Log.Comment("Other_TestClass_?_A conditional expression of the form b(question) x(colon)y"); Log.Comment("first evaluates the condition b. Then, if b"); Log.Comment("is true, x is evaluated and becomes the result"); Log.Comment("of the operation. Otherwise, y is evaluated"); Log.Comment("and becomes the result of the operation. Other_TestClass_?_A"); Log.Comment("conditional expression never evaluates both x"); Log.Comment("and y."); if (Other_TestClass_cond001.testMethod()) { return MFTestResults.Pass; } return MFTestResults.Fail; } [TestMethod] public MFTestResults Other_cond002_Test() { Log.Comment("Section 7.12"); Log.Comment("Other_TestClass_?_A conditional expression of the form b(question) x(colon)y"); Log.Comment("first evaluates the condition b. Then, if b"); Log.Comment("is true, x is evaluated and becomes the result"); Log.Comment("of the operation. Otherwise, y is evaluated"); Log.Comment("and becomes the result of the operation. Other_TestClass_?_A"); Log.Comment("conditional expression never evaluates both x"); Log.Comment("and y."); if (Other_TestClass_cond002.testMethod()) { return MFTestResults.Pass; } return MFTestResults.Fail; } [TestMethod] public MFTestResults Other_cond003_Test() { Log.Comment("Section 7.12"); Log.Comment("Other_TestClass_?_A conditional expression of the form b(question) x(colon)y"); Log.Comment("first evaluates the condition b. Then, if b"); Log.Comment("is true, x is evaluated and becomes the result"); Log.Comment("of the operation. Otherwise, y is evaluated"); Log.Comment("and becomes the result of the operation. Other_TestClass_?_A"); Log.Comment("conditional expression never evaluates both x"); Log.Comment("and y."); if (Other_TestClass_cond003.testMethod()) { return MFTestResults.Pass; } return MFTestResults.Fail; } [TestMethod] public MFTestResults Other_cond004_Test() { Log.Comment("Section 7.12"); Log.Comment("Other_TestClass_?_A conditional expression of the form b(question) x(colon)y"); Log.Comment("first evaluates the condition b. Then, if b"); Log.Comment("is true, x is evaluated and becomes the result"); Log.Comment("of the operation. Otherwise, y is evaluated"); Log.Comment("and becomes the result of the operation. Other_TestClass_?_A"); Log.Comment("conditional expression never evaluates both x"); Log.Comment("and y."); if (Other_TestClass_cond004.testMethod()) { return MFTestResults.Pass; } return MFTestResults.Fail; } [TestMethod] public MFTestResults Other_cond005_Test() { Log.Comment("Section 7.12"); Log.Comment("The conditional operator is right-associative, meaning"); Log.Comment("that operations are grouped from right to left. For example,"); Log.Comment("an expression of the form a?b:c?d:e is evaluated as a?b:(c?d:e)."); if (Other_TestClass_cond005.testMethod()) { return MFTestResults.Pass; } return MFTestResults.Fail; } [TestMethod] public MFTestResults Other_cond006_Test() { Log.Comment("Section 7.12"); Log.Comment("The first operand of the ?: operator must"); Log.Comment("be an expression of a type that can be "); Log.Comment("implicitly converted to bool, or an expression"); Log.Comment("of a type that implements operator true. If neither"); Log.Comment("of these requirements are satisfied, a compile-time"); Log.Comment("error occurs."); if (Other_TestClass_cond006.testMethod()) { return MFTestResults.Pass; } return MFTestResults.Fail; } [TestMethod] public MFTestResults Other_cond008_Test() { Log.Comment("Section 7.12"); Log.Comment("The first operand of the ?: operator must"); Log.Comment("be an expression of a type that can be "); Log.Comment("implicitly converted to bool, or an expression"); Log.Comment("of a type that implements operator true. If neither"); Log.Comment("of these requirements are satisfied, a compile-time"); Log.Comment("error occurs."); if (Other_TestClass_cond008.testMethod()) { return MFTestResults.Pass; } return MFTestResults.Fail; } [TestMethod] public MFTestResults Other_cond010_Test() { Log.Comment("Section 7.12"); Log.Comment("Let X and Y be the types of the second and"); Log.Comment("third operands. Then,"); Log.Comment("If X and Y are the same types, then this is"); Log.Comment("the type of the conditional expression."); Log.Comment("Otherwise, if an implicit conversion exists"); Log.Comment("from X to Y, but not from Y to X, then Y"); Log.Comment("is the type of the conditional expression."); Log.Comment("Otherwise, if an implicit conversion exists"); Log.Comment("from Y to X, but not from X to Y, then X"); Log.Comment("is the type of the conditional expression."); Log.Comment("Otherwise, no expression type can be "); Log.Comment("determined, and a compile time error occurs. "); if (Other_TestClass_cond010.testMethod()) { return MFTestResults.Pass; } return MFTestResults.Fail; } [TestMethod] public MFTestResults Other_cond011_Test() { Log.Comment("Section 7.12"); Log.Comment("Let X and Y be the types of the second and"); Log.Comment("third operands. Then,"); Log.Comment("If X and Y are the same types, then this is"); Log.Comment("the type of the conditional expression."); Log.Comment("Otherwise, if an implicit conversion exists"); Log.Comment("from X to Y, but not from Y to X, then Y"); Log.Comment("is the type of the conditional expression."); Log.Comment("Otherwise, if an implicit conversion exists"); Log.Comment("from Y to X, but not from X to Y, then X"); Log.Comment("is the type of the conditional expression."); Log.Comment("Otherwise, no expression type can be "); Log.Comment("determined, and a compile time error occurs. "); if (Other_TestClass_cond011.testMethod()) { return MFTestResults.Pass; } return MFTestResults.Fail; } [TestMethod] public MFTestResults Other_cond014_Test() { Log.Comment("Section 7.12"); Log.Comment("The run-time processing of a conditional expression of"); Log.Comment("the form b? x: y consists of the following steps:"); Log.Comment("If an implicit conversion from type b to bool exists,"); Log.Comment("then this implicit conversion is performed to produce"); Log.Comment("a bool value."); Log.Comment("Otherwise, the operator true defined by the type of"); Log.Comment("b is invoked to produce a bool value."); if (Other_TestClass_cond014.testMethod()) { return MFTestResults.Pass; } return MFTestResults.Fail; } [TestMethod] public MFTestResults Other_cond015_Test() { Log.Comment("Section 7.12"); Log.Comment("The run-time processing of a conditional expression of"); Log.Comment("the form b? x: y consists of the following steps:"); Log.Comment("If an implicit conversion from type b to bool exists,"); Log.Comment("then this implicit conversion is performed to produce"); Log.Comment("a bool value."); Log.Comment("Otherwise, the operator true defined by the type of"); Log.Comment("b is invoked to produce a bool value."); if (Other_TestClass_cond015.testMethod()) { return MFTestResults.Pass; } return MFTestResults.Fail; } [TestMethod] public MFTestResults Other_is005_Test() { Log.Comment("Section 7.9.9"); Log.Comment("The is operator is used to check whether the run-time type"); Log.Comment("of an ojbect is compatible with a given type. In an operation"); Log.Comment("of the form e is T, e must be an expression of a reference-type"); Log.Comment("and T must be a reference-type. If this is not the case, a compile"); Log.Comment("time error occurs."); if (Other_TestClass_is005.testMethod()) { return MFTestResults.Pass; } return MFTestResults.Fail; } [TestMethod] public MFTestResults Other_is006_Test() { Log.Comment("Section 7.9.9"); Log.Comment("The is operator is used to check whether the run-time type"); Log.Comment("of an ojbect is compatible with a given type. In an operation"); Log.Comment("of the form e is T, e must be an expression of a reference-type"); Log.Comment("and T must be a reference-type. If this is not the case, a compile"); Log.Comment("time error occurs."); if (Other_TestClass_is006.testMethod()) { return MFTestResults.Pass; } return MFTestResults.Fail; } [TestMethod] public MFTestResults Other_is007_Test() { Log.Comment("Section 7.9.9"); Log.Comment("The operation e is T returns true if not null"); Log.Comment("and if an implicit reference conversion from the "); Log.Comment("run-time type of the instance referenced by e to "); Log.Comment("the type given by T exists. In other words, e is T"); Log.Comment("checks that e is not null and that a cast-expression"); Log.Comment("of the form (T)(e) will complete without throwing an "); Log.Comment("System.Exception."); if (Other_TestClass_is007.testMethod()) { return MFTestResults.Pass; } return MFTestResults.Fail; } [TestMethod] public MFTestResults Other_is008_Test() { Log.Comment("Section 7.9.9"); Log.Comment("The operation e is T returns true if not null"); Log.Comment("and if an implicit reference conversion from the "); Log.Comment("run-time type of the instance referenced by e to "); Log.Comment("the type given by T exists. In other words, e is T"); Log.Comment("checks that e is not null and that a cast-expression"); Log.Comment("of the form (T)(e) will complete without throwing an "); Log.Comment("System.Exception."); if (Other_TestClass_is008.testMethod()) { return MFTestResults.Pass; } return MFTestResults.Fail; } [TestMethod] public MFTestResults Other_is009_Test() { Log.Comment("Section 7.9.9"); Log.Comment("The operation e is T returns true if not null"); Log.Comment("and if an implicit reference conversion from the "); Log.Comment("run-time type of the instance referenced by e to "); Log.Comment("the type given by T exists. In other words, e is T"); Log.Comment("checks that e is not null and that a cast-expression"); Log.Comment("of the form (T)(e) will complete without throwing an "); Log.Comment("System.Exception."); if (Other_TestClass_is009.testMethod()) { return MFTestResults.Pass; } return MFTestResults.Fail; } [TestMethod] public MFTestResults Other_is010_Test() { Log.Comment("Section 7.9.9"); Log.Comment("The operation e is T returns true if not null"); Log.Comment("and if an implicit reference conversion from the "); Log.Comment("run-time type of the instance referenced by e to "); Log.Comment("the type given by T exists. In other words, e is T"); Log.Comment("checks that e is not null and that a cast-expression"); Log.Comment("of the form (T)(e) will complete without throwing an "); Log.Comment("System.Exception."); if (Other_TestClass_is010.testMethod()) { return MFTestResults.Pass; } return MFTestResults.Fail; } [TestMethod] public MFTestResults Other_is011_Test() { Log.Comment("Section 7.9.9"); Log.Comment("The operation e is T returns true if not null"); Log.Comment("and if an implicit reference conversion from the "); Log.Comment("run-time type of the instance referenced by e to "); Log.Comment("the type given by T exists. In other words, e is T"); Log.Comment("checks that e is not null and that a cast-expression"); Log.Comment("of the form (T)(e) will complete without throwing an "); Log.Comment("System.Exception."); if (Other_TestClass_is011.testMethod()) { return MFTestResults.Pass; } return MFTestResults.Fail; } [TestMethod] public MFTestResults Other_is012_Test() { Log.Comment("Section 7.9.9"); Log.Comment("The operation e is T returns true if not null"); Log.Comment("and if an implicit reference conversion from the "); Log.Comment("run-time type of the instance referenced by e to "); Log.Comment("the type given by T exists. In other words, e is T"); Log.Comment("checks that e is not null and that a cast-expression"); Log.Comment("of the form (T)(e) will complete without throwing an "); Log.Comment("System.Exception."); if (Other_TestClass_is012.testMethod()) { return MFTestResults.Pass; } return MFTestResults.Fail; } [TestMethod] public MFTestResults Other_is013_Test() { Log.Comment("Section 7.9.9"); Log.Comment("The operation e is T returns true if not null"); Log.Comment("and if an implicit reference conversion from the "); Log.Comment("run-time type of the instance referenced by e to "); Log.Comment("the type given by T exists. In other words, e is T"); Log.Comment("checks that e is not null and that a cast-expression"); Log.Comment("of the form (T)(e) will complete without throwing an "); Log.Comment("System.Exception."); if (Other_TestClass_is013.testMethod()) { return MFTestResults.Pass; } return MFTestResults.Fail; } [TestMethod] public MFTestResults Other_is014_Test() { Log.Comment("Section 7.9.9"); Log.Comment("The operation e is T returns true if not null"); Log.Comment("and if an implicit reference conversion from the "); Log.Comment("run-time type of the instance referenced by e to "); Log.Comment("the type given by T exists. In other words, e is T"); Log.Comment("checks that e is not null and that a cast-expression"); Log.Comment("of the form (T)(e) will complete without throwing an "); Log.Comment("System.Exception."); if (Other_TestClass_is014.testMethod()) { return MFTestResults.Pass; } return MFTestResults.Fail; } [TestMethod] public MFTestResults Other_is015_Test() { Log.Comment("Section 7.9.9"); Log.Comment("The operation e is T returns true if not null"); Log.Comment("and if an implicit reference conversion from the "); Log.Comment("run-time type of the instance referenced by e to "); Log.Comment("the type given by T exists. In other words, e is T"); Log.Comment("checks that e is not null and that a cast-expression"); Log.Comment("of the form (T)(e) will complete without throwing an "); Log.Comment("System.Exception."); if (Other_TestClass_is015.testMethod()) { return MFTestResults.Pass; } return MFTestResults.Fail; } [TestMethod] public MFTestResults Other_is016_Test() { Log.Comment("Section 7.9.9"); Log.Comment("The operation e is T returns true if not null"); Log.Comment("and if an implicit reference conversion from the "); Log.Comment("run-time type of the instance referenced by e to "); Log.Comment("the type given by T exists. In other words, e is T"); Log.Comment("checks that e is not null and that a cast-expression"); Log.Comment("of the form (T)(e) will complete without throwing an "); Log.Comment("System.Exception."); if (Other_TestClass_is016.testMethod()) { return MFTestResults.Pass; } return MFTestResults.Fail; } [TestMethod] public MFTestResults Other_is017_Test() { Log.Comment("Section 7.9.9"); Log.Comment("The operation e is T returns true if not null"); Log.Comment("and if an implicit reference conversion from the "); Log.Comment("run-time type of the instance referenced by e to "); Log.Comment("the type given by T exists. In other words, e is T"); Log.Comment("checks that e is not null and that a cast-expression"); Log.Comment("of the form (T)(e) will complete without throwing an "); Log.Comment("System.Exception."); if (Other_TestClass_is017.testMethod()) { return MFTestResults.Pass; } return MFTestResults.Fail; } [TestMethod] public MFTestResults Other_is018_Test() { Log.Comment("Section 7.9.9"); Log.Comment("The operation e is T returns true if not null"); Log.Comment("and if an implicit reference conversion from the "); Log.Comment("run-time type of the instance referenced by e to "); Log.Comment("the type given by T exists. In other words, e is T"); Log.Comment("checks that e is not null and that a cast-expression"); Log.Comment("of the form (T)(e) will complete without throwing an "); Log.Comment("System.Exception."); if (Other_TestClass_is018.testMethod()) { return MFTestResults.Pass; } return MFTestResults.Fail; } [TestMethod] public MFTestResults Other_is019_Test() { Log.Comment("Section 7.9.9"); Log.Comment("The operation e is T returns true if not null"); Log.Comment("and if an implicit reference conversion from the "); Log.Comment("run-time type of the instance referenced by e to "); Log.Comment("the type given by T exists. In other words, e is T"); Log.Comment("checks that e is not null and that a cast-expression"); Log.Comment("of the form (T)(e) will complete without throwing an "); Log.Comment("System.Exception."); if (Other_TestClass_is019.testMethod()) { return MFTestResults.Pass; } return MFTestResults.Fail; } [TestMethod] public MFTestResults Other_is020_Test() { Log.Comment("Section 7.9.9"); Log.Comment("The operation e is T returns true if not null"); Log.Comment("and if an implicit reference conversion from the "); Log.Comment("run-time type of the instance referenced by e to "); Log.Comment("the type given by T exists. In other words, e is T"); Log.Comment("checks that e is not null and that a cast-expression"); Log.Comment("of the form (T)(e) will complete without throwing an "); Log.Comment("System.Exception."); if (Other_TestClass_is020.testMethod()) { return MFTestResults.Pass; } return MFTestResults.Fail; } [TestMethod] public MFTestResults Other_is021_Test() { Log.Comment("Section 7.9.9"); Log.Comment("The operation e is T returns true if not null"); Log.Comment("and if an implicit reference conversion from the "); Log.Comment("run-time type of the instance referenced by e to "); Log.Comment("the type given by T exists. In other words, e is T"); Log.Comment("checks that e is not null and that a cast-expression"); Log.Comment("of the form (T)(e) will complete without throwing an "); Log.Comment("System.Exception."); if (Other_TestClass_is021.testMethod()) { return MFTestResults.Pass; } return MFTestResults.Fail; } [TestMethod] public MFTestResults Other_is022_Test() { Log.Comment("Section 7.9.9"); Log.Comment("The operation e is T returns true if not null"); Log.Comment("and if an implicit reference conversion from the "); Log.Comment("run-time type of the instance referenced by e to "); Log.Comment("the type given by T exists. In other words, e is T"); Log.Comment("checks that e is not null and that a cast-expression"); Log.Comment("of the form (T)(e) will complete without throwing an "); Log.Comment("System.Exception."); if (Other_TestClass_is022.testMethod()) { return MFTestResults.Pass; } return MFTestResults.Fail; } [TestMethod] public MFTestResults Other_is023_Test() { Log.Comment("Section 7.9.9"); Log.Comment("If e is T is known at compile-time to always be"); Log.Comment("true or always be false, a compile-time error"); Log.Comment("occurs. The operation is known to always be "); Log.Comment("true if an implicit reference conversion exists from"); Log.Comment("the compile-time type of e to T. The operation is known"); Log.Comment("to always be false if no implicit or explicit reference"); Log.Comment("conversion exists from the compile-time type of e to t."); if (Other_TestClass_is023.testMethod()) { return MFTestResults.Pass; } return MFTestResults.Fail; } [TestMethod] public MFTestResults Other_is024_Test() { Log.Comment("Section 7.9.9"); Log.Comment("If e is T is known at compile-time to always be"); Log.Comment("true or always be false, a compile-time error"); Log.Comment("occurs. The operation is known to always be "); Log.Comment("true if an implicit reference conversion exists from"); Log.Comment("the compile-time type of e to T. The operation is known"); Log.Comment("to always be false if no implicit or explicit reference"); Log.Comment("conversion exists from the compile-time type of e to t."); if (Other_TestClass_is024.testMethod()) { return MFTestResults.Pass; } return MFTestResults.Fail; } [TestMethod] public MFTestResults Other_is025_Test() { Log.Comment("Section 7.9.9"); Log.Comment("If e is T is known at compile-time to always be"); Log.Comment("true or always be false, a compile-time error"); Log.Comment("occurs. The operation is known to always be "); Log.Comment("true if an implicit reference conversion exists from"); Log.Comment("the compile-time type of e to T. The operation is known"); Log.Comment("to always be false if no implicit or explicit reference"); Log.Comment("conversion exists from the compile-time type of e to t."); if (Other_TestClass_is025.testMethod()) { return MFTestResults.Pass; } return MFTestResults.Fail; } [TestMethod] public MFTestResults Other_is026_Test() { Log.Comment("Section 7.9.9"); Log.Comment("If e is T is known at compile-time to always be"); Log.Comment("true or always be false, a compile-time error"); Log.Comment("occurs. The operation is known to always be "); Log.Comment("true if an implicit reference conversion exists from"); Log.Comment("the compile-time type of e to T. The operation is known"); Log.Comment("to always be false if no implicit or explicit reference"); Log.Comment("conversion exists from the compile-time type of e to t."); if (Other_TestClass_is026.testMethod()) { return MFTestResults.Pass; } return MFTestResults.Fail; } [TestMethod] public MFTestResults Other_is027_Test() { Log.Comment("Section 7.9.9"); Log.Comment("If e is T is known at compile-time to always be"); Log.Comment("true or always be false, a compile-time error"); Log.Comment("occurs. The operation is known to always be "); Log.Comment("true if an implicit reference conversion exists from"); Log.Comment("the compile-time type of e to T. The operation is known"); Log.Comment("to always be false if no implicit or explicit reference"); Log.Comment("conversion exists from the compile-time type of e to t."); if (Other_TestClass_is027.testMethod()) { return MFTestResults.Pass; } return MFTestResults.Fail; } [TestMethod] public MFTestResults Other_is028_Test() { Log.Comment("Section 7.9.9"); Log.Comment("If e is T is known at compile-time to always be"); Log.Comment("true or always be false, a compile-time error"); Log.Comment("occurs. The operation is known to always be "); Log.Comment("true if an implicit reference conversion exists from"); Log.Comment("the compile-time type of e to T. The operation is known"); Log.Comment("to always be false if no implicit or explicit reference"); Log.Comment("conversion exists from the compile-time type of e to t."); if (Other_TestClass_is028.testMethod()) { return MFTestResults.Pass; } return MFTestResults.Fail; } [TestMethod] public MFTestResults Other_is029_Test() { Log.Comment("Section 7.9.9"); Log.Comment("If e is T is known at compile-time to always be"); Log.Comment("true or always be false, a compile-time error"); Log.Comment("occurs. The operation is known to always be "); Log.Comment("true if an implicit reference conversion exists from"); Log.Comment("the compile-time type of e to T. The operation is known"); Log.Comment("to always be false if no implicit or explicit reference"); Log.Comment("conversion exists from the compile-time type of e to t."); if (Other_TestClass_is029.testMethod()) { return MFTestResults.Pass; } return MFTestResults.Fail; } [TestMethod] public MFTestResults Other_is030_Test() { Log.Comment("Section 7.9.9"); Log.Comment("If e is T is known at compile-time to always be"); Log.Comment("true or always be false, a compile-time error"); Log.Comment("occurs. The operation is known to always be "); Log.Comment("true if an implicit reference conversion exists from"); Log.Comment("the compile-time type of e to T. The operation is known"); Log.Comment("to always be false if no implicit or explicit reference"); Log.Comment("conversion exists from the compile-time type of e to t."); if (Other_TestClass_is030.testMethod()) { return MFTestResults.Pass; } return MFTestResults.Fail; } [TestMethod] public MFTestResults Other_is031_Test() { Log.Comment("Section 7.9.9"); Log.Comment("If e is T is known at compile-time to always be"); Log.Comment("true or always be false, a compile-time error"); Log.Comment("occurs. The operation is known to always be "); Log.Comment("true if an implicit reference conversion exists from"); Log.Comment("the compile-time type of e to T. The operation is known"); Log.Comment("to always be false if no implicit or explicit reference"); Log.Comment("conversion exists from the compile-time type of e to t."); if (Other_TestClass_is031.testMethod()) { return MFTestResults.Pass; } return MFTestResults.Fail; } [TestMethod] public MFTestResults Other_is032_Test() { Log.Comment("Section 7.9.9"); Log.Comment("If e is T is known at compile-time to always be"); Log.Comment("true or always be false, a compile-time error"); Log.Comment("occurs. The operation is known to always be "); Log.Comment("true if an implicit reference conversion exists from"); Log.Comment("the compile-time type of e to T. The operation is known"); Log.Comment("to always be false if no implicit or explicit reference"); Log.Comment("conversion exists from the compile-time type of e to t."); if (Other_TestClass_is032.testMethod()) { return MFTestResults.Pass; } return MFTestResults.Fail; } [TestMethod] public MFTestResults Other_is033_Test() { Log.Comment("Section 7.9.9"); Log.Comment("If e is T is known at compile-time to always be"); Log.Comment("true or always be false, a compile-time error"); Log.Comment("occurs. The operation is known to always be "); Log.Comment("true if an implicit reference conversion exists from"); Log.Comment("the compile-time type of e to T. The operation is known"); Log.Comment("to always be false if no implicit or explicit reference"); Log.Comment("conversion exists from the compile-time type of e to t."); if (Other_TestClass_is033.testMethod()) { return MFTestResults.Pass; } return MFTestResults.Fail; } [TestMethod] public MFTestResults Other_is034_Test() { Log.Comment("Section 7.9.9"); Log.Comment("If e is T is known at compile-time to always be"); Log.Comment("true or always be false, a compile-time error"); Log.Comment("occurs. The operation is known to always be "); Log.Comment("true if an implicit reference conversion exists from"); Log.Comment("the compile-time type of e to T. The operation is known"); Log.Comment("to always be false if no implicit or explicit reference"); Log.Comment("conversion exists from the compile-time type of e to t."); if (Other_TestClass_is034.testMethod()) { return MFTestResults.Pass; } return MFTestResults.Fail; } [TestMethod] public MFTestResults Other_as001_Test() { Log.Comment("Section 7.9.10"); if (Other_TestClass_as001.testMethod()) { return MFTestResults.Pass; } return MFTestResults.Fail; } [TestMethod] public MFTestResults Other_as002_Test() { Log.Comment("Section 7.9.10"); if (Other_TestClass_as002.testMethod()) { return MFTestResults.Pass; } return MFTestResults.Fail; } [TestMethod] public MFTestResults Other_as003_Test() { Log.Comment("Section 7.9.10"); Log.Comment("string->object->array "); if (Other_TestClass_as003.testMethod()) { return MFTestResults.Pass; } return MFTestResults.Fail; } [TestMethod] public MFTestResults Other_as004_Test() { Log.Comment("Section 7.9.10"); Log.Comment("string->object->array "); if (Other_TestClass_as004.testMethod()) { return MFTestResults.Pass; } return MFTestResults.Fail; } [TestMethod] public MFTestResults Other_as007_Test() { Log.Comment("Section 7.9.10"); Log.Comment("string->object->array "); if (Other_TestClass_as007.testMethod()) { return MFTestResults.Pass; } return MFTestResults.Fail; } [TestMethod] public MFTestResults Other_as008_Test() { Log.Comment("Section 7.9.10"); Log.Comment("exp as object "); if (Other_TestClass_as008.testMethod()) { return MFTestResults.Pass; } return MFTestResults.Fail; } [TestMethod] public MFTestResults Other_as011_Test() { Log.Comment("Section 7.9.10"); Log.Comment("expression as for a deep inheritance"); if (Other_TestClass_as011.testMethod()) { return MFTestResults.Pass; } return MFTestResults.Fail; } [TestMethod] public MFTestResults Other_as012_Test() { Log.Comment("Section 7.9.10"); Log.Comment("expression as non-type through interface (check at runtime)"); if (Other_TestClass_as012.testMethod()) { return MFTestResults.Pass; } return MFTestResults.Fail; } [TestMethod] public MFTestResults Other_add001_Test() { Log.Comment("Section 7.7.4"); Log.Comment("When one or both operands are of type string, the"); Log.Comment("predefined addition operators concatenate the string"); Log.Comment("representation of the operands."); if (Other_TestClass_add001.testMethod()) { return MFTestResults.Pass; } return MFTestResults.Fail; } [TestMethod] public MFTestResults Other_add002_Test() { Log.Comment("Section 7.7.4"); Log.Comment("When one or both operands are of type string, the"); Log.Comment("predefined addition operators concatenate the string"); Log.Comment("representation of the operands."); if (Other_TestClass_add002.testMethod()) { return MFTestResults.Pass; } return MFTestResults.Fail; } [TestMethod] public MFTestResults Other_add003_Test() { Log.Comment("Section 7.7.4"); Log.Comment("When one or both operands are of type string, the"); Log.Comment("predefined addition operators concatenate the string"); Log.Comment("representation of the operands."); if (Other_TestClass_add003.testMethod()) { return MFTestResults.Pass; } return MFTestResults.Fail; } [TestMethod] public MFTestResults Other_add004_Test() { Log.Comment("Section 7.7.4"); Log.Comment("When one or both operands are of type string, the"); Log.Comment("predefined addition operators concatenate the string"); Log.Comment("representation of the operands."); if (Other_TestClass_add004.testMethod()) { return MFTestResults.Pass; } return MFTestResults.Fail; } [TestMethod] public MFTestResults Other_add005_Test() { Log.Comment("Section 7.7.4"); Log.Comment("When one or both operands are of type string, the"); Log.Comment("predefined addition operators concatenate the string"); Log.Comment("representation of the operands."); if (Other_TestClass_add005.testMethod()) { return MFTestResults.Pass; } return MFTestResults.Fail; } [TestMethod] public MFTestResults Other_add006_Test() { Log.Comment("Section 7.7.4"); Log.Comment("When one or both operands are of type string, the"); Log.Comment("predefined addition operators concatenate the string"); Log.Comment("representation of the operands."); if (Other_TestClass_add006.testMethod()) { return MFTestResults.Pass; } return MFTestResults.Fail; } [TestMethod] public MFTestResults Other_logic001_Test() { Log.Comment("Section 7.10"); if (Other_TestClass_logic001.testMethod()) { return MFTestResults.Pass; } return MFTestResults.Fail; } [TestMethod] public MFTestResults Other_logic002_Test() { Log.Comment("Section 7.10"); if (Other_TestClass_logic002.testMethod()) { return MFTestResults.Pass; } return MFTestResults.Fail; } [TestMethod] public MFTestResults Other_logic003_Test() { Log.Comment("Section 7.10"); if (Other_TestClass_logic003.testMethod()) { return MFTestResults.Pass; } return MFTestResults.Fail; } [TestMethod] public MFTestResults Other_logic004_Test() { Log.Comment("Section 7.10"); if (Other_TestClass_logic004.testMethod()) { return MFTestResults.Pass; } return MFTestResults.Fail; } [TestMethod] public MFTestResults Other_logic005_Test() { Log.Comment("Section 7.10"); if (Other_TestClass_logic005.testMethod()) { return MFTestResults.Pass; } return MFTestResults.Fail; } [TestMethod] public MFTestResults Other_logic006_Test() { Log.Comment("Section 7.10"); if (Other_TestClass_logic006.testMethod()) { return MFTestResults.Pass; } return MFTestResults.Fail; } [TestMethod] public MFTestResults Other_logic007_Test() { Log.Comment("Section 7.10"); if (Other_TestClass_logic007.testMethod()) { return MFTestResults.Pass; } return MFTestResults.Fail; } [TestMethod] public MFTestResults Other_logic008_Test() { Log.Comment("Section 7.10"); if (Other_TestClass_logic008.testMethod()) { return MFTestResults.Pass; } return MFTestResults.Fail; } [TestMethod] public MFTestResults Other_logic009_Test() { Log.Comment("Section 7.10"); if (Other_TestClass_logic009.testMethod()) { return MFTestResults.Pass; } return MFTestResults.Fail; } [TestMethod] public MFTestResults Other_logic010_Test() { Log.Comment("Section 7.10"); if (Other_TestClass_logic010.testMethod()) { return MFTestResults.Pass; } return MFTestResults.Fail; } [TestMethod] public MFTestResults Other_logic011_Test() { Log.Comment("Section 7.10"); if (Other_TestClass_logic011.testMethod()) { return MFTestResults.Pass; } return MFTestResults.Fail; } [TestMethod] public MFTestResults Other_logic012_Test() { Log.Comment("Section 7.10"); if (Other_TestClass_logic012.testMethod()) { return MFTestResults.Pass; } return MFTestResults.Fail; } [TestMethod] public MFTestResults Other_logic013_Test() { Log.Comment("Section 7.10"); if (Other_TestClass_logic013.testMethod()) { return MFTestResults.Pass; } return MFTestResults.Fail; } [TestMethod] public MFTestResults Other_logic014_Test() { Log.Comment("Section 7.10"); if (Other_TestClass_logic014.testMethod()) { return MFTestResults.Pass; } return MFTestResults.Fail; } [TestMethod] public MFTestResults Other_logic015_Test() { Log.Comment("Section 7.10"); if (Other_TestClass_logic015.testMethod()) { return MFTestResults.Pass; } return MFTestResults.Fail; } [TestMethod] public MFTestResults Other_logic016_Test() { Log.Comment("Section 7.10"); if (Other_TestClass_logic016.testMethod()) { return MFTestResults.Pass; } return MFTestResults.Fail; } [TestMethod] public MFTestResults Other_logic017_Test() { Log.Comment("Section 7.10"); if (Other_TestClass_logic017.testMethod()) { return MFTestResults.Pass; } return MFTestResults.Fail; } [TestMethod] public MFTestResults Other_logic018_Test() { Log.Comment("Section 7.10"); if (Other_TestClass_logic018.testMethod()) { return MFTestResults.Pass; } return MFTestResults.Fail; } [TestMethod] public MFTestResults Other_logic019_Test() { Log.Comment("Section 7.10"); if (Other_TestClass_logic019.testMethod()) { return MFTestResults.Pass; } return MFTestResults.Fail; } [TestMethod] public MFTestResults Other_logic020_Test() { Log.Comment("Section 7.10"); if (Other_TestClass_logic020.testMethod()) { return MFTestResults.Pass; } return MFTestResults.Fail; } [TestMethod] public MFTestResults Other_logic021_Test() { Log.Comment("Section 7.10"); if (Other_TestClass_logic021.testMethod()) { return MFTestResults.Pass; } return MFTestResults.Fail; } [TestMethod] public MFTestResults Other_logic022_Test() { Log.Comment("Section 7.10"); if (Other_TestClass_logic022.testMethod()) { return MFTestResults.Pass; } return MFTestResults.Fail; } [TestMethod] public MFTestResults Other_logic023_Test() { Log.Comment("Section 7.10"); if (Other_TestClass_logic023.testMethod()) { return MFTestResults.Pass; } return MFTestResults.Fail; } [TestMethod] public MFTestResults Other_logic024_Test() { Log.Comment("Section 7.10"); if (Other_TestClass_logic024.testMethod()) { return MFTestResults.Pass; } return MFTestResults.Fail; } [TestMethod] public MFTestResults Other_logic025_Test() { Log.Comment("Section 7.10"); if (Other_TestClass_logic025.testMethod()) { return MFTestResults.Pass; } return MFTestResults.Fail; } [TestMethod] public MFTestResults Other_logic026_Test() { Log.Comment("Section 7.10"); if (Other_TestClass_logic026.testMethod()) { return MFTestResults.Pass; } return MFTestResults.Fail; } [TestMethod] public MFTestResults Other_logic027_Test() { Log.Comment("Section 7.10"); if (Other_TestClass_logic027.testMethod()) { return MFTestResults.Pass; } return MFTestResults.Fail; } [TestMethod] public MFTestResults Other_logic028_Test() { Log.Comment("Section 7.10"); if (Other_TestClass_logic028.testMethod()) { return MFTestResults.Pass; } return MFTestResults.Fail; } [TestMethod] public MFTestResults Other_logic029_Test() { Log.Comment("Section 7.10"); if (Other_TestClass_logic029.testMethod()) { return MFTestResults.Pass; } return MFTestResults.Fail; } [TestMethod] public MFTestResults Other_logic030_Test() { Log.Comment("Section 7.10"); if (Other_TestClass_logic030.testMethod()) { return MFTestResults.Pass; } return MFTestResults.Fail; } [TestMethod] public MFTestResults Other_logic032_Test() { Log.Comment("Section 7.10"); if (Other_TestClass_logic032.testMethod()) { return MFTestResults.Pass; } return MFTestResults.Fail; } //Compiled Test Cases public class Other_TestClass_Shift_001 { public static int Main_old(string[] args) { byte bits = 8; bits = (byte)(bits << 1); if (bits != 16) return (1); bits = (byte)(bits >> 1); if (bits != 8) return (1); return (0); } public static bool testMethod() { if (Main_old(null) != 0) return false; else return true; } } public class Other_TestClass_Shift_002 { public static int Main_old(string[] args) { sbyte bits = 8; bits = (sbyte)(bits << 1); if (bits != 16) return (1); bits = (sbyte)(bits >> 1); if (bits != 8) return (1); return (0); } public static bool testMethod() { if (Main_old(null) != 0) return false; else return true; } } public class Other_TestClass_Shift_003 { public static int Main_old(string[] args) { short bits = 8; bits = (short)(bits << 1); if (bits != 16) return (1); bits = (short)(bits >> 1); if (bits != 8) return (1); return (0); } public static bool testMethod() { if (Main_old(null) != 0) return false; else return true; } } public class Other_TestClass_Shift_004 { public static int Main_old(string[] args) { ushort bits = 8; bits = (ushort)(bits << 1); if (bits != 16) return (1); bits = (ushort)(bits >> 1); if (bits != 8) return (1); return (0); } public static bool testMethod() { if (Main_old(null) != 0) return false; else return true; } } public class Other_TestClass_Shift_005 { public static int Main_old(string[] args) { int bits = 8; bits = (int)(bits << 1); if (bits != 16) return (1); bits = (int)(bits >> 1); if (bits != 8) return (1); return (0); } public static bool testMethod() { if (Main_old(null) != 0) return false; else return true; } } public class Other_TestClass_Shift_006 { public static int Main_old(string[] args) { uint bits = 8; bits = (uint)(bits << 1); if (bits != 16) return (1); bits = (uint)(bits >> 1); if (bits != 8) return (1); return (0); } public static bool testMethod() { if (Main_old(null) != 0) return false; else return true; } } public class Other_TestClass_Shift_007 { public static int Main_old(string[] args) { long bits = 8; bits = (long)(bits << 1); if (bits != 16) return (1); bits = (long)(bits >> 1); if (bits != 8) return (1); return (0); } public static bool testMethod() { if (Main_old(null) != 0) return false; else return true; } } public class Other_TestClass_Shift_008 { public static int Main_old(string[] args) { ulong bits = 8; bits = (ulong)(bits << 1); if (bits != 16) return (1); bits = (ulong)(bits >> 1); if (bits != 8) return (1); return (0); } public static bool testMethod() { if (Main_old(null) != 0) return false; else return true; } } public class Other_TestClass_Shift_009 { public static int Main_old(string[] args) { char bits = (char)8; bits = (char)(bits << 1); if (bits != 16) return (1); bits = (char)(bits >> 1); if (bits != 8) return (1); return (0); } public static bool testMethod() { if (Main_old(null) != 0) return false; else return true; } } public class Other_TestClass_Shift_015 { public static int Main_old(string[] args) { int shifter = 1; byte bits = 8; bits = (byte)(bits << shifter); if (bits != 16) return (1); bits = (byte)(bits >> shifter); if (bits != 8) return (1); return (0); } public static bool testMethod() { if (Main_old(null) != 0) return false; else return true; } } public class Other_TestClass_Shift_016 { public static int Main_old(string[] args) { int shifter = 1; sbyte bits = 8; bits = (sbyte)(bits << shifter); if (bits != 16) return (1); bits = (sbyte)(bits >> shifter); if (bits != 8) return (1); return (0); } public static bool testMethod() { if (Main_old(null) != 0) return false; else return true; } } public class Other_TestClass_Shift_017 { public static int Main_old(string[] args) { int shifter = 1; short bits = 8; bits = (short)(bits << shifter); if (bits != 16) return (1); bits = (short)(bits >> shifter); if (bits != 8) return (1); return (0); } public static bool testMethod() { if (Main_old(null) != 0) return false; else return true; } } public class Other_TestClass_Shift_018 { public static int Main_old(string[] args) { int shifter = 1; ushort bits = 8; bits = (ushort)(bits << shifter); if (bits != 16) return (1); bits = (ushort)(bits >> shifter); if (bits != 8) return (1); return (0); } public static bool testMethod() { if (Main_old(null) != 0) return false; else return true; } } public class Other_TestClass_Shift_019 { public static int Main_old(string[] args) { int shifter = 1; int bits = 8; bits = (int)(bits << shifter); if (bits != 16) return (1); bits = (int)(bits >> shifter); if (bits != 8) return (1); return (0); } public static bool testMethod() { if (Main_old(null) != 0) return false; else return true; } } public class Other_TestClass_Shift_020 { public static int Main_old(string[] args) { int shifter = 1; uint bits = 8; bits = (uint)(bits << shifter); if (bits != 16) return (1); bits = (uint)(bits >> shifter); if (bits != 8) return (1); return (0); } public static bool testMethod() { if (Main_old(null) != 0) return false; else return true; } } public class Other_TestClass_Shift_021 { public static int Main_old(string[] args) { int shifter = 1; long bits = 8; bits = (long)(bits << shifter); if (bits != 16) return (1); bits = (long)(bits >> shifter); if (bits != 8) return (1); return (0); } public static bool testMethod() { if (Main_old(null) != 0) return false; else return true; } } public class Other_TestClass_Shift_022 { public static int Main_old(string[] args) { int shifter = 1; ulong bits = 8; bits = (ulong)(bits << shifter); if (bits != 16) return (1); bits = (ulong)(bits >> shifter); if (bits != 8) return (1); return (0); } public static bool testMethod() { if (Main_old(null) != 0) return false; else return true; } } public class Other_TestClass_Shift_023 { public static int Main_old(string[] args) { int shifter = 1; char bits = (char)8; bits = (char)(bits << shifter); if (bits != 16) return (1); bits = (char)(bits >> shifter); if (bits != 8) return (1); return (0); } public static bool testMethod() { if (Main_old(null) != 0) return false; else return true; } } public class Other_TestClass_shift_029 { public static int Main_old(string[] args) { sbyte sb = 0x01; sb = (sbyte)(sb << 7); if (sb != unchecked((sbyte)0xFFFFFF80)) return (1); sb = (sbyte)(sb >> 7); if (sb != -1) return (1); short sh = 0x01; sh = (short)(sh << 15); if (sh != unchecked((short)0xFFFF8000)) return (1); sh = (short)(sh >> 15); if (sh != -1) return (1); int in1 = 0x01; in1 = in1 << 31; if (in1 != unchecked((int)0x80000000)) return (1); in1 = in1 >> 31; if (in1 != -1) return (1); long lo = 0x01; lo = lo << 63; unchecked { if (lo != (long)0x8000000000000000) return (1); } lo = lo >> 63; if (lo != -1) { return (1); } return (0); } public static bool testMethod() { if (Main_old(null) != 0) return false; else return true; } } public class Other_TestClass_shift_030 { public static int Main_old(string[] args) { byte ub = 0x01; ub = (byte)(ub << 7); if (ub != 0x80) return (1); ub = (byte)(ub >> 7); if (ub != 0x01) return (1); ushort ush = 0x01; ush = (ushort)(ush << 15); if (ush != 0x8000) return (1); ush = (ushort)(ush >> 15); if (ush != 0x01) return (1); uint uin = 0x01; uin = uin << 31; if (uin != 0x80000000) return (1); uin = uin >> 31; if (uin != 0x01) return (1); ulong ulo = 0x01; ulo = ulo << 63; if (ulo != 0x8000000000000000) return (1); ulo = ulo >> 63; if (ulo != 0x01) { return (1); } char ch = (char)0x01; ch = (char)(ch << 15); if (ch != 0x8000) return (1); ch = (char)(ch >> 15); if (ch != 0x01) return (1); return (0); } public static bool testMethod() { if (Main_old(null) != 0) return false; else return true; } } public class Other_TestClass_Shift_037 { public static int Main_old() { int intI = 8 >> 3; if (intI == 1) { return 0; } else { return 1; } } public static bool testMethod() { return (Main_old() == 0); } } public class Other_TestClass_Shift_038 { public static int Main_old() { int intI = 1 << 3; if (intI == 8) { return 0; } else { return 1; } } public static bool testMethod() { return (Main_old() == 0); } } public class Other_TestClass_Shift_041 { public byte ub; public ushort ush; public uint uin; public ulong ulo; public char ch; public static int Main_old(string[] args) { Other_TestClass_Shift_041 T = new Other_TestClass_Shift_041(); T.ub = 0x01; T.ub = (byte)(T.ub << 7); if (T.ub != 0x80) return (1); T.ub = (byte)(T.ub >> 7); if (T.ub != 0x01) return (1); T.ush = 0x01; T.ush = (ushort)(T.ush << 15); if (T.ush != 0x8000) return (1); T.ush = (ushort)(T.ush >> 15); if (T.ush != 0x01) return (1); T.uin = 0x01; T.uin = T.uin << 31; if (T.uin != 0x80000000) return (1); T.uin = T.uin >> 31; if (T.uin != 0x01) return (1); T.ulo = 0x01; T.ulo = T.ulo << 63; if (T.ulo != 0x8000000000000000) return (1); T.ulo = T.ulo >> 63; if (T.ulo != 0x01) { return (1); } T.ch = (char)0x01; T.ch = (char)(T.ch << 15); if (T.ch != 0x8000) return (1); T.ch = (char)(T.ch >> 15); if (T.ch != 0x01) return (1); return (0); } public static bool testMethod() { if (Main_old(null) != 0) return false; else return true; } } public class Other_TestClass_Shift_042 { public sbyte sb; public short sh; public int in1; public long lo; public static int Main_old(string[] args) { Other_TestClass_Shift_042 T = new Other_TestClass_Shift_042(); T.sb = 0x01; T.sb = (sbyte)(T.sb << 7); if (T.sb != unchecked((sbyte)0xFFFFFF80)) return (1); T.sb = (sbyte)(T.sb >> 7); if (T.sb != -1) return (1); T.sh = 0x01; T.sh = (short)(T.sh << 15); if (T.sh != unchecked((short)0xFFFF8000)) return (1); T.sh = (short)(T.sh >> 15); if (T.sh != -1) return (1); T.in1 = 0x01; T.in1 = T.in1 << 31; if (T.in1 != unchecked((int)0x80000000)) return (1); T.in1 = T.in1 >> 31; if (T.in1 != -1) return (1); T.lo = 0x01; T.lo = T.lo << 63; unchecked { if (T.lo != (long)0x8000000000000000) return (1); } T.lo = T.lo >> 63; if (T.lo != -1) { return (1); } return (0); } public static bool testMethod() { if (Main_old(null) != 0) return false; else return true; } } public class Other_TestClass_Shift_043 { public byte ub; public ushort ush; public uint uin; public ulong ulo; public char ch; public static int Main_old(string[] args) { Other_TestClass_Shift_043 T = new Other_TestClass_Shift_043(); T.ub = 0x01; T.ub <<= 7; if (T.ub != 0x80) return (1); T.ub >>= 7; if (T.ub != 0x01) return (1); T.ush = 0x01; T.ush <<= 15; if (T.ush != 0x8000) return (1); T.ush >>= 15; if (T.ush != 0x01) return (1); T.uin = 0x01; T.uin <<= 31; if (T.uin != 0x80000000) return (1); T.uin >>= 31; if (T.uin != 0x01) return (1); T.ulo = 0x01; T.ulo <<= 63; if (T.ulo != 0x8000000000000000) return (1); T.ulo >>= 63; if (T.ulo != 0x01) { return (1); } T.ch = (char)0x01; T.ch <<= 15; if (T.ch != 0x8000) return (1); T.ch >>= 15; if (T.ch != 0x01) return (1); return (0); } public static bool testMethod() { if (Main_old(null) != 0) return false; else return true; } } public class Other_TestClass_Shift_044 { public sbyte sb; public short sh; public int in1; public long lo; public static int Main_old(string[] args) { Other_TestClass_Shift_044 T = new Other_TestClass_Shift_044(); T.sb = 0x01; T.sb <<= 7; if (T.sb != unchecked((sbyte)0xFFFFFF80)) return (1); T.sb >>= 7; if (T.sb != -1) return (1); T.sh = 0x01; T.sh <<= 15; if (T.sh != unchecked((short)0xFFFF8000)) return (1); T.sh >>= 15; if (T.sh != -1) return (1); T.in1 = 0x01; T.in1 <<= 31; if (T.in1 != unchecked((int)0x80000000)) return (1); T.in1 >>= 31; if (T.in1 != -1) return (1); T.lo = 0x01; T.lo <<= 63; unchecked { if (T.lo != (long)0x8000000000000000) return (1); } T.lo >>= 63; if (T.lo != -1) { return (1); } return (0); } public static bool testMethod() { if (Main_old(null) != 0) return false; else return true; } } class Other_TestClass_assign001 { public static int Main_old() { int Other_TestClass_assign001; Other_TestClass_assign001 = 1; if (Other_TestClass_assign001 == 1) { return 0; } else { return 1; } } public static bool testMethod() { return (Main_old() == 0); } } class Other_TestClass_assign002 { public static int Main_old() { int Other_TestClass_assign002 = 1; Other_TestClass_assign002 += 1; if (Other_TestClass_assign002 == 2) { return 0; } else { return 1; } } public static bool testMethod() { return (Main_old() == 0); } } class Other_TestClass_assign003 { public static int Main_old() { int Other_TestClass_assign003 = 3; Other_TestClass_assign003 -= 1; if (Other_TestClass_assign003 == 2) { return 0; } else { return 1; } } public static bool testMethod() { return (Main_old() == 0); } } class Other_TestClass_assign004 { public static int Main_old() { int Other_TestClass_assign004 = 3; Other_TestClass_assign004 *= 4; if (Other_TestClass_assign004 == 12) { return 0; } else { return 1; } } public static bool testMethod() { return (Main_old() == 0); } } class Other_TestClass_assign005 { public static int Main_old() { int Other_TestClass_assign005 = 12; Other_TestClass_assign005 /= 4; if (Other_TestClass_assign005 == 3) { return 0; } else { return 1; } } public static bool testMethod() { return (Main_old() == 0); } } class Other_TestClass_assign006 { public static int Main_old() { int Other_TestClass_assign006 = 15; Other_TestClass_assign006 %= 4; if (Other_TestClass_assign006 == 3) { return 0; } else { return 1; } } public static bool testMethod() { return (Main_old() == 0); } } class Other_TestClass_assign007 { public static int Main_old() { int Other_TestClass_assign007 = 5; Other_TestClass_assign007 &= 4; if (Other_TestClass_assign007 == 4) { return 0; } else { return 1; } } public static bool testMethod() { return (Main_old() == 0); } } class Other_TestClass_assign008 { public static int Main_old() { int Other_TestClass_assign008 = 3; Other_TestClass_assign008 |= 4; if (Other_TestClass_assign008 == 7) { return 0; } else { return 1; } } public static bool testMethod() { return (Main_old() == 0); } } class Other_TestClass_assign009 { public static int Main_old() { int Other_TestClass_assign009 = 5; Other_TestClass_assign009 ^= 4; if (Other_TestClass_assign009 == 1) { return 0; } else { return 1; } } public static bool testMethod() { return (Main_old() == 0); } } class Other_TestClass_assign010 { public static int Main_old() { int Other_TestClass_assign010 = 4; Other_TestClass_assign010 <<= 2; if (Other_TestClass_assign010 == 16) { return 0; } else { return 1; } } public static bool testMethod() { return (Main_old() == 0); } } class Other_TestClass_assign011 { public static int Main_old() { int Other_TestClass_assign011 = 4; Other_TestClass_assign011 >>= 2; if (Other_TestClass_assign011 == 1) { return 0; } else { return 1; } } public static bool testMethod() { return (Main_old() == 0); } } class Other_TestClass_unary001 { public static int Main_old() { int test1 = 2; int test2 = +test1; if (test2 == 2) { return 0; } else { return 1; } } public static bool testMethod() { return (Main_old() == 0); } } class Other_TestClass_unary002 { public static int Main_old() { uint test1 = 2; uint test2 = +test1; if (test2 == 2) { return 0; } else { return 1; } } public static bool testMethod() { return (Main_old() == 0); } } class Other_TestClass_unary003 { public static int Main_old() { long test1 = 2; long test2 = +test1; if (test2 == 2) { return 0; } else { return 1; } } public static bool testMethod() { return (Main_old() == 0); } } class Other_TestClass_unary004 { public static int Main_old() { ulong test1 = 2; ulong test2 = +test1; if (test2 == 2) { return 0; } else { return 1; } } public static bool testMethod() { return (Main_old() == 0); } } class Other_TestClass_unary005 { public static int Main_old() { float test1 = 2; float test2 = +test1; if (test2 == 2) { return 0; } else { return 1; } } public static bool testMethod() { return (Main_old() == 0); } } class Other_TestClass_unary006 { public static int Main_old() { double test1 = 2; double test2 = +test1; if (test2 == 2) { return 0; } else { return 1; } } public static bool testMethod() { return (Main_old() == 0); } } class Other_TestClass_unary007 { public static int Main_old() { double test1 = 2; double test2 = +test1; if (test2 == 2) { return 0; } else { return 1; } } public static bool testMethod() { return (Main_old() == 0); } } class Other_TestClass_unary008 { public static int Main_old() { int test1 = 2; int test2 = -test1; if (test2 == -2) { return 0; } else { return 1; } } public static bool testMethod() { return (Main_old() == 0); } } class Other_TestClass_unary009 { public static int Main_old() { long test1 = 2; long test2 = -test1; if (test2 == -2) { return 0; } else { return 1; } } public static bool testMethod() { return (Main_old() == 0); } } class Other_TestClass_unary012 { public static int Main_old() { int test1 = int.MinValue; int test2 = 0; unchecked { test2 = -test1; } if ((test1 == int.MinValue) && (test2 == int.MinValue)) { return 0; } else { return 1; } } public static bool testMethod() { return (Main_old() == 0); } } class Other_TestClass_unary013 { public static int Main_old() { long test1 = long.MinValue; long test2 = 0; unchecked { test2 = -test1; } if ((test1 == long.MinValue) && (test2 == long.MinValue)) { return 0; } else { return 1; } } public static bool testMethod() { return (Main_old() == 0); } } class Other_TestClass_unary014 { public static int Main_old() { uint test1 = 2; long test2 = 0; if (((-test1).GetType() == test2.GetType()) && ((-test1) == -2)) { return 0; } else { return 1; } } public static bool testMethod() { return (Main_old() == 0); } } class Other_TestClass_unary015 { public static int Main_old() { int intI = 0; if ((-2147483648).GetType() == intI.GetType()) { return 0; } else { return 1; } } public static bool testMethod() { return (Main_old() == 0); } } class Other_TestClass_unary017 { public static int Main_old() { long test1 = -9223372036854775808; if (test1 == -9223372036854775808) { return 0; } else { return 1; } } public static bool testMethod() { return (Main_old() == 0); } } class Other_TestClass_unary018 { public static int Main_old() { float test1 = 2.0f; float test2 = -test1; if (test2 == -2.0f) { return 0; } else { return 1; } } public static bool testMethod() { return (Main_old() == 0); } } class Other_TestClass_unary019 { public static int Main_old() { double test1 = 2.0; double test2 = -test1; if (test2 == -2.0) { return 0; } else { return 1; } } public static bool testMethod() { return (Main_old() == 0); } } class Other_TestClass_unary023 { public static int Main_old() { bool test1 = true; bool test2 = !test1; if (test2 == false) { return 0; } else { return 1; } } public static bool testMethod() { return (Main_old() == 0); } } class Other_TestClass_unary024 { public static int Main_old() { bool test1 = false; bool test2 = !test1; if (test2 == true) { return 0; } else { return 1; } } public static bool testMethod() { return (Main_old() == 0); } } class Other_TestClass_unary025 { public static int Main_old() { int test1 = 2; int test2 = ~test1; if (test2 == -3) { return 0; } else { return 1; } } public static bool testMethod() { return (Main_old() == 0); } } class Other_TestClass_unary026 { public static int Main_old() { uint test1 = 2; uint test2 = ~test1; if (test2 == 0xFFFFFFFD) { return 0; } else { return 1; } } public static bool testMethod() { return (Main_old() == 0); } } class Other_TestClass_unary027 { public static int Main_old() { long test1 = 2; long test2 = ~test1; if (test2 == -3) { return 0; } else { return 1; } } public static bool testMethod() { return (Main_old() == 0); } } class Other_TestClass_unary028 { public static int Main_old() { ulong test1 = 2; ulong test2 = ~test1; if (test2 == 0xFFFFFFFFFFFFFFFD) { return 0; } else { return 1; } } public static bool testMethod() { return (Main_old() == 0); } } class Other_TestClass_unary029 { public static int Main_old() { int intI = 2; int intJ = 2; ++intI; --intJ; if ((intI == 3) && (intJ == 1)) { return 0; } else { return 1; } } public static bool testMethod() { return (Main_old() == 0); } } class Other_TestClass_unary030 { int intI; public int MyInt { get { return intI; } set { intI = value; } } public static int Main_old() { Other_TestClass_unary030 MC1 = new Other_TestClass_unary030(); Other_TestClass_unary030 MC2 = new Other_TestClass_unary030(); MC1.MyInt = 2; MC2.MyInt = 2; ++MC1.MyInt; --MC2.MyInt; if ((MC1.MyInt == 3) && (MC2.MyInt == 1)) { return 0; } else { return 1; } } public static bool testMethod() { return (Main_old() == 0); } } class Other_TestClass_unary031 { int intI = 2; public int this[int intJ] { get { return intI; } set { intI = value; } } public static int Main_old() { Other_TestClass_unary031 MC1 = new Other_TestClass_unary031(); Other_TestClass_unary031 MC2 = new Other_TestClass_unary031(); ++MC1[0]; --MC2[0]; if ((MC1[0] == 3) && (MC2[0] == 1)) { return 0; } else { return 1; } } public static bool testMethod() { return (Main_old() == 0); } } class Other_TestClass_unary036 { public static int Main_old() { sbyte test1 = 2; sbyte test2 = 2; ++test1; --test2; if ((test1 == 3) && (test2 == 1)) { return 0; } else { return 1; } } public static bool testMethod() { return (Main_old() == 0); } } class Other_TestClass_unary037 { public static int Main_old() { byte test1 = 2; byte test2 = 2; ++test1; --test2; if ((test1 == 3) && (test2 == 1)) { return 0; } else { return 1; } } public static bool testMethod() { return (Main_old() == 0); } } class Other_TestClass_unary038 { public static int Main_old() { short test1 = 2; short test2 = 2; ++test1; --test2; if ((test1 == 3) && (test2 == 1)) { return 0; } else { return 1; } } public static bool testMethod() { return (Main_old() == 0); } } class Other_TestClass_unary039 { public static int Main_old() { ushort test1 = 2; ushort test2 = 2; ++test1; --test2; if ((test1 == 3) && (test2 == 1)) { return 0; } else { return 1; } } public static bool testMethod() { return (Main_old() == 0); } } class Other_TestClass_unary040 { public static int Main_old() { int test1 = 2; int test2 = 2; ++test1; --test2; if ((test1 == 3) && (test2 == 1)) { return 0; } else { return 1; } } public static bool testMethod() { return (Main_old() == 0); } } class Other_TestClass_unary041 { public static int Main_old() { uint test1 = 2; uint test2 = 2; ++test1; --test2; if ((test1 == 3) && (test2 == 1)) { return 0; } else { return 1; } } public static bool testMethod() { return (Main_old() == 0); } } class Other_TestClass_unary042 { public static int Main_old() { long test1 = 2; long test2 = 2; ++test1; --test2; if ((test1 == 3) && (test2 == 1)) { return 0; } else { return 1; } } public static bool testMethod() { return (Main_old() == 0); } } class Other_TestClass_unary043 { public static int Main_old() { ulong test1 = 2; ulong test2 = 2; ++test1; --test2; if ((test1 == 3) && (test2 == 1)) { return 0; } else { return 1; } } public static bool testMethod() { return (Main_old() == 0); } } class Other_TestClass_unary044 { public static int Main_old() { char test1 = (char)2; char test2 = (char)2; ++test1; --test2; if ((test1 == 3) && (test2 == 1)) { return 0; } else { return 1; } } public static bool testMethod() { return (Main_old() == 0); } } class Other_TestClass_unary045 { public static int Main_old() { float test1 = 2.0f; float test2 = 2.0f; ++test1; --test2; if ((test1 == 3.0f) && (test2 == 1.0f)) { return 0; } else { return 1; } } public static bool testMethod() { return (Main_old() == 0); } } class Other_TestClass_unary046 { public static int Main_old() { double test1 = 2.0; double test2 = 2.0; ++test1; --test2; if ((test1 == 3.0) && (test2 == 1.0)) { return 0; } else { return 1; } } public static bool testMethod() { return (Main_old() == 0); } } class Other_TestClass_unary048 { public static int Main_old() { sbyte test1 = 2; sbyte test2 = test1++; sbyte test3 = ++test1; if ((test2 == 2) && (test3 == 4)) { return 0; } else { return 1; } } public static bool testMethod() { return (Main_old() == 0); } } class Other_TestClass_unary049 { public static int Main_old() { byte test1 = 2; byte test2 = test1++; byte test3 = ++test1; if ((test2 == 2) && (test3 == 4)) { return 0; } else { return 1; } } public static bool testMethod() { return (Main_old() == 0); } } class Other_TestClass_unary050 { public static int Main_old() { short test1 = 2; short test2 = test1++; short test3 = ++test1; if ((test2 == 2) && (test3 == 4)) { return 0; } else { return 1; } } public static bool testMethod() { return (Main_old() == 0); } } class Other_TestClass_unary051 { public static int Main_old() { ushort test1 = 2; ushort test2 = test1++; ushort test3 = ++test1; if ((test2 == 2) && (test3 == 4)) { return 0; } else { return 1; } } public static bool testMethod() { return (Main_old() == 0); } } class Other_TestClass_unary052 { public static int Main_old() { int test1 = 2; int test2 = test1++; int test3 = ++test1; if ((test2 == 2) && (test3 == 4)) { return 0; } else { return 1; } } public static bool testMethod() { return (Main_old() == 0); } } class Other_TestClass_unary053 { public static int Main_old() { uint test1 = 2; uint test2 = test1++; uint test3 = ++test1; if ((test2 == 2) && (test3 == 4)) { return 0; } else { return 1; } } public static bool testMethod() { return (Main_old() == 0); } } class Other_TestClass_unary054 { public static int Main_old() { long test1 = 2; long test2 = test1++; long test3 = ++test1; if ((test2 == 2) && (test3 == 4)) { return 0; } else { return 1; } } public static bool testMethod() { return (Main_old() == 0); } } class Other_TestClass_unary055 { public static int Main_old() { ulong test1 = 2; ulong test2 = test1++; ulong test3 = ++test1; if ((test2 == 2) && (test3 == 4)) { return 0; } else { return 1; } } public static bool testMethod() { return (Main_old() == 0); } } class Other_TestClass_unary056 { public static int Main_old() { char test1 = (char)2; char test2 = test1++; char test3 = ++test1; if ((test2 == 2) && (test3 == 4)) { return 0; } else { return 1; } } public static bool testMethod() { return (Main_old() == 0); } } class Other_TestClass_unary057 { public static int Main_old() { float test1 = 2.0f; float test2 = test1++; float test3 = ++test1; if ((test2 == 2.0f) && (test3 == 4.0f)) { return 0; } else { return 1; } } public static bool testMethod() { return (Main_old() == 0); } } class Other_TestClass_unary058 { public static int Main_old() { double test1 = 2.0; double test2 = test1++; double test3 = ++test1; if ((test2 == 2.0) && (test3 == 4.0)) { return 0; } else { return 1; } } public static bool testMethod() { return (Main_old() == 0); } } public class Other_TestClass_unary068 { private int i; public int I { get { return i; } set { i = value; } } public static Other_TestClass_unary068 operator ++(Other_TestClass_unary068 a) { a.i++; return a; } public static Other_TestClass_unary068 operator --(Other_TestClass_unary068 a) { a.i--; return a; } public static int Main_old() { Other_TestClass_unary068 a = new Other_TestClass_unary068(); for (a.I = 0; a.I < 10; a++) ; for (; a.I > -1; a--) ; for (; a.I < 10; ++a) ; for (; a.I > 0; --a) ; return a.I; } public static bool testMethod() { return (Main_old() == 0); } } class Other_TestClass_relat001 { public static int Main_old() { int test1 = 2; int test2 = 2; int test3 = 3; if ((test1 == test2) && !(test1 == test3)) { return 0; } else { return 1; } } public static bool testMethod() { return (Main_old() == 0); } } class Other_TestClass_relat002 { public static int Main_old() { uint test1 = 2; uint test2 = 2; uint test3 = 3; if ((test1 == test2) && !(test1 == test3)) { return 0; } else { return 1; } } public static bool testMethod() { return (Main_old() == 0); } } class Other_TestClass_relat003 { public static int Main_old() { long test1 = 2; long test2 = 2; long test3 = 3; if ((test1 == test2) && !(test1 == test3)) { return 0; } else { return 1; } } public static bool testMethod() { return (Main_old() == 0); } } class Other_TestClass_relat004 { public static int Main_old() { ulong test1 = 2; ulong test2 = 2; ulong test3 = 3; if ((test1 == test2) && !(test1 == test3)) { return 0; } else { return 1; } } public static bool testMethod() { return (Main_old() == 0); } } class Other_TestClass_relat005 { public static int Main_old() { int test1 = 2; int test2 = 2; int test3 = 3; if (!(test1 != test2) && (test1 != test3)) { return 0; } else { return 1; } } public static bool testMethod() { return (Main_old() == 0); } } class Other_TestClass_relat006 { public static int Main_old() { uint test1 = 2; uint test2 = 2; uint test3 = 3; if (!(test1 != test2) && (test1 != test3)) { return 0; } else { return 1; } } public static bool testMethod() { return (Main_old() == 0); } } class Other_TestClass_relat007 { public static int Main_old() { long test1 = 2; long test2 = 2; long test3 = 3; if (!(test1 != test2) && (test1 != test3)) { return 0; } else { return 1; } } public static bool testMethod() { return (Main_old() == 0); } } class Other_TestClass_relat008 { public static int Main_old() { ulong test1 = 2; ulong test2 = 2; ulong test3 = 3; if (!(test1 != test2) && (test1 != test3)) { return 0; } else { return 1; } } public static bool testMethod() { return (Main_old() == 0); } } class Other_TestClass_relat009 { public static int Main_old() { int test1 = 2; int test2 = 3; if ((test1 < test2) && !(test2 < test1)) { return 0; } else { return 1; } } public static bool testMethod() { return (Main_old() == 0); } } class Other_TestClass_relat010 { public static int Main_old() { uint test1 = 2; uint test2 = 3; if ((test1 < test2) && !(test2 < test1)) { return 0; } else { return 1; } } public static bool testMethod() { return (Main_old() == 0); } } class Other_TestClass_relat011 { public static int Main_old() { long test1 = 2; long test2 = 3; if ((test1 < test2) && !(test2 < test1)) { return 0; } else { return 1; } } public static bool testMethod() { return (Main_old() == 0); } } class Other_TestClass_relat012 { public static int Main_old() { ulong test1 = 2; ulong test2 = 3; if ((test1 < test2) && !(test2 < test1)) { return 0; } else { return 1; } } public static bool testMethod() { return (Main_old() == 0); } } class Other_TestClass_relat013 { public static int Main_old() { int test1 = 2; int test2 = 3; if (!(test1 > test2) && (test2 > test1)) { return 0; } else { return 1; } } public static bool testMethod() { return (Main_old() == 0); } } class Other_TestClass_relat014 { public static int Main_old() { uint test1 = 2; uint test2 = 3; if (!(test1 > test2) && (test2 > test1)) { return 0; } else { return 1; } } public static bool testMethod() { return (Main_old() == 0); } } class Other_TestClass_relat015 { public static int Main_old() { long test1 = 2; long test2 = 3; if (!(test1 > test2) && (test2 > test1)) { return 0; } else { return 1; } } public static bool testMethod() { return (Main_old() == 0); } } class Other_TestClass_relat016 { public static int Main_old() { ulong test1 = 2; ulong test2 = 3; if (!(test1 > test2) && (test2 > test1)) { return 0; } else { return 1; } } public static bool testMethod() { return (Main_old() == 0); } } class Other_TestClass_relat017 { public static int Main_old() { int test1 = 2; int test2 = 3; int test3 = 2; if ((test1 <= test2) && !(test2 <= test1) && (test1 <= test3)) { return 0; } else { return 1; } } public static bool testMethod() { return (Main_old() == 0); } } class Other_TestClass_relat018 { public static int Main_old() { uint test1 = 2; uint test2 = 3; uint test3 = 2; if ((test1 <= test2) && !(test2 <= test1) && (test1 <= test3)) { return 0; } else { return 1; } } public static bool testMethod() { return (Main_old() == 0); } } class Other_TestClass_relat019 { public static int Main_old() { long test1 = 2; long test2 = 3; long test3 = 2; if ((test1 <= test2) && !(test2 <= test1) && (test1 <= test3)) { return 0; } else { return 1; } } public static bool testMethod() { return (Main_old() == 0); } } class Other_TestClass_relat020 { public static int Main_old() { ulong test1 = 2; ulong test2 = 3; ulong test3 = 2; if ((test1 <= test2) && !(test2 <= test1) && (test1 <= test3)) { return 0; } else { return 1; } } public static bool testMethod() { return (Main_old() == 0); } } class Other_TestClass_relat021 { public static int Main_old() { int test1 = 2; int test2 = 3; int test3 = 2; if (!(test1 >= test2) && (test2 >= test1) && (test1 >= test3)) { return 0; } else { return 1; } } public static bool testMethod() { return (Main_old() == 0); } } class Other_TestClass_relat022 { public static int Main_old() { uint test1 = 2; uint test2 = 3; uint test3 = 2; if (!(test1 >= test2) && (test2 >= test1) && (test1 >= test3)) { return 0; } else { return 1; } } public static bool testMethod() { return (Main_old() == 0); } } class Other_TestClass_relat023 { public static int Main_old() { long test1 = 2; long test2 = 3; long test3 = 2; if (!(test1 >= test2) && (test2 >= test1) && (test1 >= test3)) { return 0; } else { return 1; } } public static bool testMethod() { return (Main_old() == 0); } } class Other_TestClass_relat024 { public static int Main_old() { ulong test1 = 2; ulong test2 = 3; ulong test3 = 2; if (!(test1 >= test2) && (test2 >= test1) && (test1 >= test3)) { return 0; } else { return 1; } } public static bool testMethod() { return (Main_old() == 0); } } class Other_TestClass_relat025 { public static int Main_old() { float f1 = 1.0f; float f2 = 1.0f; float f3 = 2.0f; if ((f1 == f2) && !(f1 == f3)) { return 0; } else { return 1; } } public static bool testMethod() { return (Main_old() == 0); } } class Other_TestClass_relat026 { public static int Main_old() { double d1 = 1.0; double d2 = 1.0; double d3 = 2.0; if ((d1 == d2) && !(d1 == d3)) { return 0; } else { return 1; } } public static bool testMethod() { return (Main_old() == 0); } } class Other_TestClass_relat027 { public static int Main_old() { float f1 = 1.0f; float f2 = 1.0f; float f3 = 2.0f; if (!(f1 != f2) && (f1 != f3)) { return 0; } else { return 1; } } public static bool testMethod() { return (Main_old() == 0); } } class Other_TestClass_relat028 { public static int Main_old() { double d1 = 1.0; double d2 = 1.0; double d3 = 2.0; if (!(d1 != d2) && (d1 != d3)) { return 0; } else { return 1; } } public static bool testMethod() { return (Main_old() == 0); } } class Other_TestClass_relat029 { public static int Main_old() { float f1 = 1.0f; float f2 = 1.0f; float f3 = 2.0f; if (!(f1 < f2) && (f1 < f3) && !(f3 < f1)) { return 0; } else { return 1; } } public static bool testMethod() { return (Main_old() == 0); } } class Other_TestClass_relat030 { public static int Main_old() { double d1 = 1.0; double d2 = 1.0; double d3 = 2.0; if (!(d1 < d2) && (d1 < d3) && !(d3 < d1)) { return 0; } else { return 1; } } public static bool testMethod() { return (Main_old() == 0); } } class Other_TestClass_relat031 { public static int Main_old() { float f1 = 1.0f; float f2 = 1.0f; float f3 = 2.0f; if (!(f1 > f2) && !(f1 > f3) && (f3 > f1)) { return 0; } else { return 1; } } public static bool testMethod() { return (Main_old() == 0); } } class Other_TestClass_relat032 { public static int Main_old() { double d1 = 1.0; double d2 = 1.0; double d3 = 2.0; if (!(d1 > d2) && !(d1 > d3) && (d3 > d1)) { return 0; } else { return 1; } } public static bool testMethod() { return (Main_old() == 0); } } class Other_TestClass_relat033 { public static int Main_old() { float f1 = 1.0f; float f2 = 1.0f; float f3 = 2.0f; if ((f1 <= f2) && (f1 <= f3) && !(f3 <= f1)) { return 0; } else { return 1; } } public static bool testMethod() { return (Main_old() == 0); } } class Other_TestClass_relat034 { public static int Main_old() { double d1 = 1.0; double d2 = 1.0; double d3 = 2.0; if ((d1 <= d2) && (d1 <= d3) && !(d3 <= d1)) { return 0; } else { return 1; } } public static bool testMethod() { return (Main_old() == 0); } } class Other_TestClass_relat035 { public static int Main_old() { float f1 = 1.0f; float f2 = 1.0f; float f3 = 2.0f; if ((f1 >= f2) && !(f1 >= f3) && (f3 >= f1)) { return 0; } else { return 1; } } public static bool testMethod() { return (Main_old() == 0); } } class Other_TestClass_relat036 { public static int Main_old() { double d1 = 1.0; double d2 = 1.0; double d3 = 2.0; if ((d1 >= d2) && !(d1 >= d3) && (d3 >= d1)) { return 0; } else { return 1; } } public static bool testMethod() { return (Main_old() == 0); } } /* class Other_TestClass_relat037 { public static int Main_old() { float f1 = 2.0f; float f2 = float.NaN; double d1 = 2.0; double d2 = double.NaN; if (f1 == f2) { return 1; } if (f2 == f2) { return 1; } if (d1 == d2) { return 1; } if (d2 == d2) { return 1; } return 0; } public static bool testMethod() { return (Main_old() == 0); } } class Other_TestClass_relat038 { public static int Main_old() { float f1 = 2.0f; float f2 = float.NaN; double d1 = 2.0; double d2 = double.NaN; if (!(f1 != f2)) { return 1; } if (!(f2 != f2)) { return 1; } if (!(d1 != d2)) { return 1; } if (!(d2 != d2)) { return 1; } return 0; } public static bool testMethod() { return (Main_old() == 0); } } class Other_TestClass_relat039 { public static int Main_old() { float f1 = 2.0f; float f2 = float.NaN; double d1 = 2.0; double d2 = double.NaN; if (f1 < f2) { return 1; } if (f2 < f2) { return 1; } if (d1 < d2) { return 1; } if (d2 < d2) { return 1; } return 0; } public static bool testMethod() { return (Main_old() == 0); } } class Other_TestClass_relat040 { public static int Main_old() { float f1 = 2.0f; float f2 = float.NaN; double d1 = 2.0; double d2 = double.NaN; if (f1 > f2) { return 1; } if (f2 > f2) { return 1; } if (d1 > d2) { return 1; } if (d2 > d2) { return 1; } return 0; } public static bool testMethod() { return (Main_old() == 0); } } class Other_TestClass_relat041 { public static int Main_old() { float f1 = 2.0f; float f2 = float.NaN; double d1 = 2.0; double d2 = double.NaN; if (f1 <= f2) { return 1; } if (f2 <= f2) { return 1; } if (d1 <= d2) { return 1; } if (d2 <= d2) { return 1; } return 0; } public static bool testMethod() { return (Main_old() == 0); } } class Other_TestClass_relat042 { public static int Main_old() { float f1 = 2.0f; float f2 = float.NaN; double d1 = 2.0; double d2 = double.NaN; if (f1 >= f2) { return 1; } if (f2 >= f2) { return 1; } if (d1 >= d2) { return 1; } if (d2 >= d2) { return 1; } return 0; } public static bool testMethod() { return (Main_old() == 0); } } class Other_TestClass_relat043 { public static int Main_old() { float f1 = +0.0f; float f2 = -0.0f; double d1 = +0.0; double d2 = -0.0; if ((f1 == f2) && (f2 == f1) && (d1 == d2) && (d2 == d1)) { return 0; } else { return 1; } } public static bool testMethod() { return (Main_old() == 0); } } class Other_TestClass_relat044 { public static int Main_old() { float f1 = +0.0f; float f2 = -0.0f; double d1 = +0.0; double d2 = -0.0; if ((!(f1 != f2)) && (!(f2 != f1)) && (!(d1 != d2)) && (!(d2 != d1))) { return 0; } else { return 1; } } public static bool testMethod() { return (Main_old() == 0); } } class Other_TestClass_relat045 { public static int Main_old() { float f1 = float.MinValue; float f2 = float.NegativeInfinity; float f3 = float.NegativeInfinity; if ((f1 > f2) && (f1 >= f2) && (f2 < f1) && (f2 <= f1) && (f2 == f3) && (f2 != f1)) { return 0; } else { return 1; } } public static bool testMethod() { return (Main_old() == 0); } } class Other_TestClass_relat046 { public static int Main_old() { double d1 = double.MinValue; double d2 = double.NegativeInfinity; double d3 = double.NegativeInfinity; if ((d1 > d2) && (d1 >= d2) && (d2 < d1) && (d2 <= d1) && (d2 == d3) && (d2 != d1)) { return 0; } else { return 1; } } public static bool testMethod() { return (Main_old() == 0); } } class Other_TestClass_relat047 { public static int Main_old() { float f1 = float.MaxValue; float f2 = float.PositiveInfinity; float f3 = float.PositiveInfinity; if ((f1 < f2) && (f1 <= f2) && (f2 > f1) && (f2 >= f1) && (f2 == f3) && (f2 != f1)) { return 0; } else { return 1; } } public static bool testMethod() { return (Main_old() == 0); } } class Other_TestClass_relat048 { public static int Main_old() { double d1 = double.MaxValue; double d2 = double.PositiveInfinity; double d3 = double.PositiveInfinity; if ((d1 < d2) && (d1 <= d2) && (d2 > d1) && (d2 >= d1) && (d2 == d3) && (d2 != d1)) { return 0; } else { return 1; } } public static bool testMethod() { return (Main_old() == 0); } } */ class Other_TestClass_relat055 { public static int Main_old() { bool b1 = true; bool b2 = true; bool b3 = false; bool b4 = false; if ((b1 == b2) && (b3 == b4) && !(b1 == b3) && !(b4 == b2)) { return 0; } else { return 1; } } public static bool testMethod() { return (Main_old() == 0); } } class Other_TestClass_relat056 { public static int Main_old() { bool b1 = true; bool b2 = true; bool b3 = false; bool b4 = false; if (!(b1 != b2) && !(b3 != b4) && (b1 != b3) && (b4 != b2)) { return 0; } else { return 1; } } public static bool testMethod() { return (Main_old() == 0); } } enum Others_TestClass_relat057_En { a = 1, b = 1, c = 3 } class Other_TestClass_relat057 { public static int Main_old() { Others_TestClass_relat057_En e1 = Others_TestClass_relat057_En.a; Others_TestClass_relat057_En e2 = Others_TestClass_relat057_En.b; Others_TestClass_relat057_En e3 = Others_TestClass_relat057_En.c; if ((e1 == e2) && !(e1 == e3)) { return 0; } else { return 1; } } public static bool testMethod() { return (Main_old() == 0); } } enum Others_TestClass_relat058_En { a = 1, b = 1, c = 3 } class Other_TestClass_relat058 { public static int Main_old() { Others_TestClass_relat058_En e1 = Others_TestClass_relat058_En.a; Others_TestClass_relat058_En e2 = Others_TestClass_relat058_En.b; Others_TestClass_relat058_En e3 = Others_TestClass_relat058_En.c; if (!(e1 != e2) && (e1 != e3)) { return 0; } else { return 1; } } public static bool testMethod() { return (Main_old() == 0); } } enum Others_TestClass_relat059_En { a = 1, b = 1, c = 3 } class Other_TestClass_relat059 { public static int Main_old() { Others_TestClass_relat059_En e1 = Others_TestClass_relat059_En.a; Others_TestClass_relat059_En e2 = Others_TestClass_relat059_En.b; Others_TestClass_relat059_En e3 = Others_TestClass_relat059_En.c; if (!(e1 > e2) && !(e1 > e3) && (e3 > e1)) { return 0; } else { return 1; } } public static bool testMethod() { return (Main_old() == 0); } } enum Others_TestClass_relat060_En { a = 1, b = 1, c = 3 } class Other_TestClass_relat060 { public static int Main_old() { Others_TestClass_relat060_En e1 = Others_TestClass_relat060_En.a; Others_TestClass_relat060_En e2 = Others_TestClass_relat060_En.b; Others_TestClass_relat060_En e3 = Others_TestClass_relat060_En.c; if (!(e1 < e2) && (e1 < e3) && !(e3 < e1)) { return 0; } else { return 1; } } public static bool testMethod() { return (Main_old() == 0); } } enum Others_TestClass_relat061_En { a = 1, b = 1, c = 3 } class Other_TestClass_relat061 { public static int Main_old() { Others_TestClass_relat061_En e1 = Others_TestClass_relat061_En.a; Others_TestClass_relat061_En e2 = Others_TestClass_relat061_En.b; Others_TestClass_relat061_En e3 = Others_TestClass_relat061_En.c; if ((e1 >= e2) && !(e1 >= e3) && (e3 >= e1)) { return 0; } else { return 1; } } public static bool testMethod() { return (Main_old() == 0); } } enum Others_TestClass_relat062_En { a = 1, b = 1, c = 3 } class Other_TestClass_relat062 { public static int Main_old() { Others_TestClass_relat062_En e1 = Others_TestClass_relat062_En.a; Others_TestClass_relat062_En e2 = Others_TestClass_relat062_En.b; Others_TestClass_relat062_En e3 = Others_TestClass_relat062_En.c; if ((e1 <= e2) && (e1 <= e3) && !(e3 <= e1)) { return 0; } else { return 1; } } public static bool testMethod() { return (Main_old() == 0); } } class Others_TestClass_relat063 { } class Other_TestClass_relat063 { public static int Main_old() { Others_TestClass_relat063 t1 = new Others_TestClass_relat063(); Others_TestClass_relat063 t2 = t1; Others_TestClass_relat063 t3 = new Others_TestClass_relat063(); if ((t1 == t2) && !(t1 == t3)) { return 0; } else { return 1; } } public static bool testMethod() { return (Main_old() == 0); } } class Others_TestClass_relat064 { } class Other_TestClass_relat064 { public static int Main_old() { Others_TestClass_relat064 t1 = new Others_TestClass_relat064(); Others_TestClass_relat064 t2 = t1; Others_TestClass_relat064 t3 = new Others_TestClass_relat064(); if (!(t1 != t2) && (t1 != t3)) { return 0; } else { return 1; } } public static bool testMethod() { return (Main_old() == 0); } } class Others_TestClass_relat065 { public int intI; public static bool operator ==(Others_TestClass_relat065 t1, Others_TestClass_relat065 t2) { if (t1.intI == t2.intI) { return false; } else { return true; } } public static bool operator !=(Others_TestClass_relat065 t1, Others_TestClass_relat065 t2) { if (t1.intI == t2.intI) { return true; } else { return false; } } } class Other_TestClass_relat065 { public static int Main_old() { Others_TestClass_relat065 t1 = new Others_TestClass_relat065(); t1.intI = 2; Others_TestClass_relat065 t2 = t1; Others_TestClass_relat065 t3 = new Others_TestClass_relat065(); t3.intI = 3; if (!(t1 == t2) && (t1 == t3)) { return 0; } else { return 1; } } public static bool testMethod() { return (Main_old() == 0); } } class Others_TestClass_relat066 { public int intI; public static bool operator ==(Others_TestClass_relat066 t1, Others_TestClass_relat066 t2) { if (t1.intI == t2.intI) { return false; } else { return true; } } public static bool operator !=(Others_TestClass_relat066 t1, Others_TestClass_relat066 t2) { if (t1.intI == t2.intI) { return true; } else { return false; } } } class Other_TestClass_relat066 { public static int Main_old() { Others_TestClass_relat066 t1 = new Others_TestClass_relat066(); t1.intI = 2; Others_TestClass_relat066 t2 = t1; Others_TestClass_relat066 t3 = new Others_TestClass_relat066(); t3.intI = 3; if ((t1 != t2) && !(t1 != t3)) { return 0; } else { return 1; } } public static bool testMethod() { return (Main_old() == 0); } } public class Other_TestClass_relat069_A { } public class Other_TestClass_relat069_B : Other_TestClass_relat069_A { } class Other_TestClass_relat069 { public static int Main_old() { Other_TestClass_relat069_A t1 = new Other_TestClass_relat069_A(); Other_TestClass_relat069_B t2 = new Other_TestClass_relat069_B(); Other_TestClass_relat069_A t3 = t2; if (!(t1 == t2) && (t2 == t3) && (t1 != t2) && !(t2 != t3)) { return 0; } else { return 1; } } public static bool testMethod() { return (Main_old() == 0); } } struct Others_TestClass_relat072_Str { public int intI; public static bool operator ==(Others_TestClass_relat072_Str s1, Others_TestClass_relat072_Str s2) { if (s1.intI == s2.intI) { return true; } else { return false; } } public static bool operator !=(Others_TestClass_relat072_Str s1, Others_TestClass_relat072_Str s2) { if (s1.intI != s2.intI) { return true; } else { return false; } } } class Other_TestClass_relat072 { public static int Main_old() { Others_TestClass_relat072_Str t1 = new Others_TestClass_relat072_Str(); t1.intI = 2; Others_TestClass_relat072_Str t2 = new Others_TestClass_relat072_Str(); t2.intI = 3; if (!(t1 == t2) && (t1 != t2)) { return 0; } else { return 1; } } public static bool testMethod() { return (Main_old() == 0); } } class Others_TestClass_relat073 { public Others_TestClass_relat073(int i) { intI = i; } public int intI; public static bool operator ==(Others_TestClass_relat073 t1, Others_TestClass_relat073 t2) { if (t1.intI == t2.intI) { return true; } else { return false; } } public static bool operator !=(Others_TestClass_relat073 t1, Others_TestClass_relat073 t2) { if (t1.intI != t2.intI) { return true; } else { return false; } } } class Other_TestClass_relat073 { public static int Main_old() { Others_TestClass_relat073 s = new Others_TestClass_relat073(1); Others_TestClass_relat073 t = new Others_TestClass_relat073(1); if ((s == t) && !((object)s == t) && !(s == (object)t) && !((object)s == (object)t)) { return 0; } else { return 1; } } public static bool testMethod() { return (Main_old() == 0); } } class Other_TestClass_relat074 { public static int Main_old() { int i = 123; int j = 123; if (!((object)i == (object)j)) { return 0; } else { return 1; } } public static bool testMethod() { return (Main_old() == 0); } } class Other_TestClass_relat075 { public static int Main_old() { string s1 = "Other_TestClass_relat075 String"; string s2 = "Other_TestClass_relat075 " + "String".ToString(); string s3 = "Other_TestClass_relat075 String "; if ((s1 == s2) && (s1 != s3)) { return 0; } else { return 1; } } public static bool testMethod() { return (Main_old() == 0); } } class Other_TestClass_relat076 { public static int Main_old() { string s1 = null; string s2 = null; string s3 = "Other_TestClass_relat076 String "; if ((s1 == s2) && (s1 != s3)) { return 0; } else { return 1; } } public static bool testMethod() { return (Main_old() == 0); } } delegate int Others_TestClass_relat077_Del(); class Other_TestClass_relat077 { public int TestMeth1() { return 1; } public int TestMeth2() { return 2; } public static int Main_old() { Other_TestClass_relat077 Other_TestClass_relat077 = new Other_TestClass_relat077(); Others_TestClass_relat077_Del Del1 = new Others_TestClass_relat077_Del(Other_TestClass_relat077.TestMeth1); Others_TestClass_relat077_Del Del2 = Del1; Others_TestClass_relat077_Del Del3 = new Others_TestClass_relat077_Del(Other_TestClass_relat077.TestMeth2); if ((Del1 == Del2) && !(Del1 == Del3)){ return 0; } else { return 1; } } public static bool testMethod() { return (Main_old() == 0); } } delegate int Others_TestClass_relat078_Del(); class Other_TestClass_relat078 { public int TestMeth1() { return 1; } public int TestMeth2() { return 2; } public static int Main_old() { Other_TestClass_relat078 Other_TestClass_relat078 = new Other_TestClass_relat078(); Others_TestClass_relat078_Del Del1 = new Others_TestClass_relat078_Del(Other_TestClass_relat078.TestMeth1); Others_TestClass_relat078_Del Del2 = Del1; Others_TestClass_relat078_Del Del3 = new Others_TestClass_relat078_Del(Other_TestClass_relat078.TestMeth2); if (!(Del1 != Del2) && (Del1 != Del3)){ return 0; } else { return 1; } } public static bool testMethod() { return (Main_old() == 0); } } /* public class Other_TestClass_relat079 { const string s1 = null; const string s2 = null; public static int Main_old() { if ((s1 == s2) && !(s1 != s2)) { return 0; } else { return 1; } } public static bool testMethod() { return (Main_old() == 0); } } */ public class Other_TestClass_relat080 { const float f1 = 2.0f; const float f2 = 2.0f; const float f3 = 3.0f; public static int Main_old() { if (!(f1 == f2)) return 1; if ((f1 == f3)) return 1; if ((f1 != f2)) return 1; if (!(f1 != f3)) return 1; if (f1 > f2) return 1; if (!(f3 > f1)) return 1; if (f1 > f3) return 1; if (f1 < f2) return 1; if (!(f1 < f3)) return 1; if (f3 < f1) return 1; if (!(f1 >= f2)) return 1; if (!(f3 >= f1)) return 1; if (f1 >= f3) return 1; if (!(f1 <= f2)) return 1; if (!(f1 <= f3)) return 1; if (f3 <= f1) return 1; return 0; } public static bool testMethod() { return (Main_old() == 0); } } public class Other_TestClass_relat081 { const double d1 = 2.0; const double d2 = 2.0; const double d3 = 3.0; public static int Main_old() { if (!(d1 == d2)) return 1; if ((d1 == d3)) return 1; if ((d1 != d2)) return 1; if (!(d1 != d3)) return 1; if (d1 > d2) return 1; if (!(d3 > d1)) return 1; if (d1 > d3) return 1; if (d1 < d2) return 1; if (!(d1 < d3)) return 1; if (d3 < d1) return 1; if (!(d1 >= d2)) return 1; if (!(d3 >= d1)) return 1; if (d1 >= d3) return 1; if (!(d1 <= d2)) return 1; if (!(d1 <= d3)) return 1; if (d3 <= d1) return 1; return 0; } public static bool testMethod() { return (Main_old() == 0); } } public class Other_TestClass_relat083 { public static implicit operator string(Other_TestClass_relat083 MC) { return "Other_TestClass_relat0831"; } public static int Main_old() { Other_TestClass_relat083 MC = new Other_TestClass_relat083(); if ((MC == "Other_TestClass_relat0831") && (MC != "Other_TestClass_relat0832")) { return 0; } else { return 1; } } public static bool testMethod() { return (Main_old() == 0); } } public class Other_TestClass_relat084 { public static implicit operator string(Other_TestClass_relat084 MC) { return "Other_TestClass_relat0841"; } public static int Main_old() { Other_TestClass_relat084 MC = new Other_TestClass_relat084(); string TestString1 = "Other_TestClass_relat0841"; string TestString2 = "Other_TestClass_relat0842"; if ((MC == TestString1) && (MC != TestString2)) { return 0; } else { return 1; } } public static bool testMethod() { return (Main_old() == 0); } } class Other_TestClass_relat086 { public static bool testMethod() { float f1 = 1.0f; float f2 = -1.0f; float f3 = -2.0f; if ((f1 < f2) && (f1 < f3) && (f2 < f3) && (f2 > f1) && (f3 > f1) && (f3 > f2)) { return false; } else { return true; } } } class Other_TestClass_relat087 { public static bool testMethod() { float f1 = 1.0f; float f2 = -1.0f; float f3 = -2.0f; if ((f1 <= f2) && (f1 <= f3) && (f2 <= f3) && (f2 >= f1) && (f3 >= f1) && (f3 >= f2)) { return false; } else { return true; } } } class Other_TestClass_relat088 { public static bool testMethod() { float f1 = float.MaxValue; float f2 = float.MinValue; float f3 = 0.0F; if ((f1 < f2) && (f1 < f3) && (f3 < f2) && (f2 > f1) && (f3 > f1) && (f2 > f3)) { return false; } else { return true; } } } class Other_TestClass_relat089 { public static bool testMethod() { float f1 = float.MaxValue; float f2 = 0.0f; float f3 = float.MinValue; if ((f1 <= f2) && (f1 <= f3) && (f2 <= f3) && (f2 >= f1) && (f3 >= f1) && (f3 >= f2)) { return false; } else { return true; } } } class Other_TestClass_operators_logic001 { public static int Main_old() { int test1 = 5; int test2 = 4; if ((test1 & test2) == 4) { return 0; } else { return 1; } } public static bool testMethod() { return (Main_old() == 0); } } class Other_TestClass_operators_logic002 { public static int Main_old() { uint test1 = 5; uint test2 = 4; if ((test1 & test2) == 4) { return 0; } else { return 1; } } public static bool testMethod() { return (Main_old() == 0); } } class Other_TestClass_operators_logic003 { public static int Main_old() { long test1 = 5; long test2 = 4; if ((test1 & test2) == 4) { return 0; } else { return 1; } } public static bool testMethod() { return (Main_old() == 0); } } class Other_TestClass_operators_logic004 { public static int Main_old() { ulong test1 = 5; ulong test2 = 4; if ((test1 & test2) == 4) { return 0; } else { return 1; } } public static bool testMethod() { return (Main_old() == 0); } } class Other_TestClass_operators_logic005 { public static int Main_old() { int test1 = 1; int test2 = 4; if ((test1 | test2) == 5) { return 0; } else { return 1; } } public static bool testMethod() { return (Main_old() == 0); } } class Other_TestClass_operators_logic006 { public static int Main_old() { uint test1 = 1; uint test2 = 4; if ((test1 | test2) == 5) { return 0; } else { return 1; } } public static bool testMethod() { return (Main_old() == 0); } } class Other_TestClass_operators_logic007 { public static int Main_old() { long test1 = 1; long test2 = 4; if ((test1 | test2) == 5) { return 0; } else { return 1; } } public static bool testMethod() { return (Main_old() == 0); } } class Other_TestClass_operators_logic008 { public static int Main_old() { ulong test1 = 1; ulong test2 = 4; if ((test1 | test2) == 5) { return 0; } else { return 1; } } public static bool testMethod() { return (Main_old() == 0); } } class Other_TestClass_operators_logic009 { public static int Main_old() { int test1 = 6; int test2 = 5; if ((test1 ^ test2) == 3) { return 0; } else { return 1; } } public static bool testMethod() { return (Main_old() == 0); } } class Other_TestClass_operators_logic010 { public static int Main_old() { uint test1 = 6; uint test2 = 5; if ((test1 ^ test2) == 3) { return 0; } else { return 1; } } public static bool testMethod() { return (Main_old() == 0); } } class Other_TestClass_operators_logic011 { public static int Main_old() { long test1 = 6; long test2 = 5; if ((test1 ^ test2) == 3) { return 0; } else { return 1; } } public static bool testMethod() { return (Main_old() == 0); } } class Other_TestClass_operators_logic012 { public static int Main_old() { ulong test1 = 6; ulong test2 = 5; if ((test1 ^ test2) == 3) { return 0; } else { return 1; } } public static bool testMethod() { return (Main_old() == 0); } } class Other_TestClass_operators_logic013 { public static int Main_old() { bool b1 = true; bool b2 = true; bool b3 = false; bool b4 = false; if ((b1 & b2) && !(b1 & b3) && !(b4 & b2) && !(b3 & b4)) { return 0; } else { return 1; } } public static bool testMethod() { return (Main_old() == 0); } } class Other_TestClass_operators_logic014 { public static int Main_old() { bool b1 = true; bool b2 = true; bool b3 = false; bool b4 = false; if ((b1 | b2) && (b1 | b3) && (b4 | b2) && !(b3 | b4)) { return 0; } else { return 1; } } public static bool testMethod() { return (Main_old() == 0); } } class Other_TestClass_operators_logic015 { public static int Main_old() { bool b1 = true; bool b2 = true; bool b3 = false; bool b4 = false; if (!(b1 ^ b2) && (b1 ^ b3) && (b4 ^ b2) && !(b3 ^ b4)) { return 0; } else { return 1; } } public static bool testMethod() { return (Main_old() == 0); } } class Other_TestClass_operators_logic016 { public static int Main_old() { bool b1 = true; bool b2 = true; bool b3 = false; bool b4 = false; if (!(b1 && b2)) return 1; if ((b1 && b3)) return 1; if ((b4 && b2)) return 1; if ((b3 && b4)) return 1; return 0; } public static bool testMethod() { return (Main_old() == 0); } } class Other_TestClass_operators_logic017 { public static bool MethCalled = false; public static bool Meth() { MethCalled = true; return true; } public static int Main_old() { bool b1 = false; if (b1 && Meth()) return 1; if (MethCalled == true) return 1; return 0; } public static bool testMethod() { return (Main_old() == 0); } } class Other_TestClass_operators_logic018 { public static int Main_old() { bool b1 = true; bool b2 = true; bool b3 = false; bool b4 = false; if (!(b1 || b2)) return 1; if (!(b1 || b3)) return 1; if (!(b4 || b2)) return 1; if ((b3 || b4)) return 1; return 0; } public static bool testMethod() { return (Main_old() == 0); } } class Other_TestClass_operators_logic019 { public static bool MethCalled = false; public static bool Meth() { MethCalled = true; return true; } public static int Main_old() { bool b1 = true; if (!(b1 || Meth())) return 1; if (MethCalled == true) return 1; return 0; } public static bool testMethod() { return (Main_old() == 0); } } /* class Other_TestClass_operators_logic022 { public static Other_TestClass_operators_logic022 operator &(Other_TestClass_operators_logic022 t1, Other_TestClass_logic022 t2) { return new Other_TestClass_operators_logic022(); } public static bool operator true(Other_TestClass_operators_logic022 t1) { return true; } public static bool operator false(Other_TestClass_operators_logic022 t1) { return false; } public static int Main_old() { Other_TestClass_operators_logic022 test1 = new Other_TestClass_operators_logic022(); Other_TestClass_operators_logic022 test2 = new Other_TestClass_operators_logic022(); if (test1 && test2) { return 0; } else { return 1; } } public static bool testMethod() { return (Main_old() == 0); } } */ /* class Other_TestClass_operators_logic023 { public static Other_TestClass_operators_logic023 operator |(Other_TestClass_operators_logic023 t1, Other_TestClass_logic023 t2) { return new Other_TestClass_operators_logic023(); } public static bool operator true(Other_TestClass_operators_logic023 t1) { return true; } public static bool operator false(Other_TestClass_operators_logic023 t1) { return false; } public static int Main_old() { Other_TestClass_operators_logic023 test1 = new Other_TestClass_operators_logic023(); Other_TestClass_operators_logic023 test2 = new Other_TestClass_operators_logic023(); if (test1 || test2) { return 0; } else { return 1; } } public static bool testMethod() { return (Main_old() == 0); } } */ /* class Other_TestClass_operators_logic032 { public static int MethCall = 0; public static Other_TestClass_operators_logic032 operator &(Other_TestClass_operators_logic032 t1, Other_TestClass_logic032 t2) { return new Other_TestClass_operators_logic032(); } public static bool operator true(Other_TestClass_operators_logic032 t1) { return true; } public static bool operator false(Other_TestClass_operators_logic032 t1) { return true; } public static Other_TestClass_operators_logic032 RetClass() { MethCall = 1; ; return new Other_TestClass_operators_logic032(); } public static int Main_old() { Other_TestClass_operators_logic032 test1 = new Other_TestClass_operators_logic032(); if (test1 && RetClass()) { } if (MethCall == 0) { return 0; } else { return 1; } } public static bool testMethod() { return (Main_old() == 0); } } */ class Other_TestClass_operators_logic033 { public static int MethCall = 0; public static Other_TestClass_operators_logic033 operator |(Other_TestClass_operators_logic033 t1, Other_TestClass_operators_logic033 t2) { return new Other_TestClass_operators_logic033(); } public static bool operator true(Other_TestClass_operators_logic033 t1) { return true; } public static bool operator false(Other_TestClass_operators_logic033 t1) { return true; } public static Other_TestClass_operators_logic033 RetClass() { MethCall = 1; ; return new Other_TestClass_operators_logic033(); } public static int Main_old() { Other_TestClass_operators_logic033 test1 = new Other_TestClass_operators_logic033(); if (test1 || RetClass()) { } if (MethCall == 0) { return 0; } else { return 1; } } public static bool testMethod() { return (Main_old() == 0); } } class Other_TestClass_cond001 { public static int Main_old() { bool b = true; int intI = b ? 3 : 4; if (intI == 3) { return 0; } else { return 1; } } public static bool testMethod() { return (Main_old() == 0); } } class Other_TestClass_cond002 { public static int Main_old() { bool b = false; int intI = b ? 3 : 4; if (intI == 4) { return 0; } else { return 1; } } public static bool testMethod() { return (Main_old() == 0); } } class Other_TestClass_cond003 { static bool Pass = true; public static int retThree() { return 3; } public static int retFour() { Pass = false; return 4; } public static int Main_old() { bool b = true; int intI = b ? retThree() : retFour(); if ((intI == 3) && (Pass == true)) { return 0; } else { return 1; } } public static bool testMethod() { return (Main_old() == 0); } } class Other_TestClass_cond004 { static bool Pass = true; public static int retThree() { Pass = false; return 3; } public static int retFour() { return 4; } public static int Main_old() { bool b = false; int intI = b ? retThree() : retFour(); if ((intI == 4) && (Pass == true)) { return 0; } else { return 1; } } public static bool testMethod() { return (Main_old() == 0); } } class Other_TestClass_cond005 { public static int Main_old() { bool b1 = false; bool b2 = false; int intI = b1 ? 1 : b2 ? 2 : 3; if (intI == 3) { return 0; } else { return 1; } } public static bool testMethod() { return (Main_old() == 0); } } class Others_TestClass_cond006 { public static implicit operator bool(Others_TestClass_cond006 t) { return true; } } class Other_TestClass_cond006 { public static int Main_old() { Others_TestClass_cond006 t = new Others_TestClass_cond006(); int intI = t ? 2 : 3; if (intI == 2) { return 0; } else { return 1; } } public static bool testMethod() { return (Main_old() == 0); } } class Others_TestClass_cond008 { public static bool operator true(Others_TestClass_cond008 t) { return true; } public static bool operator false(Others_TestClass_cond008 t) { return false; } } class Other_TestClass_cond008 { public static int Main_old() { Others_TestClass_cond008 t = new Others_TestClass_cond008(); int intI = t ? 2 : 3; if (intI == 2) { return 0; } else { return 1; } } public static bool testMethod() { return (Main_old() == 0); } } interface Others_TestClass_cond010_Inter { int RetInt(); } class Others_TestClass_cond0101 : Others_TestClass_cond010_Inter { public static implicit operator Others_TestClass_cond0102(Others_TestClass_cond0101 t) { return new Others_TestClass_cond0102(); } public int RetInt() { return 1; } } class Others_TestClass_cond0102 : Others_TestClass_cond010_Inter { public int RetInt() { return 2; } } class Other_TestClass_cond010 { public static int Main_old() { bool b = true; Others_TestClass_cond0101 t1 = new Others_TestClass_cond0101(); Others_TestClass_cond0102 t2 = new Others_TestClass_cond0102(); Others_TestClass_cond010_Inter test = b ? t1 : t2; if (test.RetInt() == 2) { return 0; } else { return 1; } } public static bool testMethod() { return (Main_old() == 0); } } interface Others_TestClass_cond011_Inter { int RetInt(); } class Others_TestClass_cond0111 : Others_TestClass_cond011_Inter { public int RetInt() { return 1; } } class Others_TestClass_cond0112 : Others_TestClass_cond011_Inter { public static implicit operator Others_TestClass_cond0111(Others_TestClass_cond0112 t) { return new Others_TestClass_cond0111(); } public int RetInt() { return 2; } } class Other_TestClass_cond011 { public static int Main_old() { bool b = false; Others_TestClass_cond0111 t1 = new Others_TestClass_cond0111(); Others_TestClass_cond0112 t2 = new Others_TestClass_cond0112(); Others_TestClass_cond011_Inter test = b ? t1 : t2; if (test.RetInt() == 1) { return 0; } else { return 1; } } public static bool testMethod() { return (Main_old() == 0); } } class Others_TestClass_cond014 { public int ChkVal = 0; public static implicit operator bool(Others_TestClass_cond014 MT) { MT.ChkVal = 1; return true; } public static bool operator true(Others_TestClass_cond014 MT) { MT.ChkVal = 2; return true; } public static bool operator false(Others_TestClass_cond014 MT) { MT.ChkVal = 3; return false; } } class Other_TestClass_cond014 { public static int Main_old() { Others_TestClass_cond014 TC = new Others_TestClass_cond014(); int intI = TC ? 1 : 2; if ((intI == 1) && (TC.ChkVal == 1)) { return 0; } else { return 1; } } public static bool testMethod() { return (Main_old() == 0); } } class Others_TestClass_cond015 { public int ChkVal = 0; public static explicit operator bool(Others_TestClass_cond015 MT) { MT.ChkVal = 1; return true; } public static bool operator true(Others_TestClass_cond015 MT) { MT.ChkVal = 2; return true; } public static bool operator false(Others_TestClass_cond015 MT) { MT.ChkVal = 3; return false; } } class Other_TestClass_cond015 { public static int Main_old() { Others_TestClass_cond015 TC = new Others_TestClass_cond015(); int intI = TC ? 1 : 2; if ((intI == 1) && (TC.ChkVal == 2)) { return 0; } else { return 1; } } public static bool testMethod() { return (Main_old() == 0); } } public class Other_TestClass_is005 { public static int Main_old() { int myInt = 3; bool b = myInt is int; if (b == true) { return 0; } else { return 1; } } public static bool testMethod() { return (Main_old() == 0); } } public struct Others_TestClass_is006_Str { } public class Other_TestClass_is006 { public static int Main_old() { Others_TestClass_is006_Str ms = new Others_TestClass_is006_Str(); bool b = ms is Others_TestClass_is006_Str; if (b == true) { return 0; } else { return 1; } } public static bool testMethod() { return (Main_old() == 0); } } public class Other_TestClass_is007_T { } public class Other_TestClass_is007 { public static int Main_old() { Other_TestClass_is007_T tt = null; object o = tt; bool b = o is Other_TestClass_is007_T; if (b == false) { return 0; } else { return 1; } } public static bool testMethod() { return (Main_old() == 0); } } public class Other_TestClass_is008_T { } public class Other_TestClass_is008 { public static int Main_old() { string tt = null; object o = tt; bool b = o is string; if (b == false) { return 0; } else { return 1; } } public static bool testMethod() { return (Main_old() == 0); } } public interface Others_TestClass_is009_Inter { } public class Other_TestClass_is009_T : Others_TestClass_is009_Inter { } public class Other_TestClass_is009 { public static int Main_old() { Others_TestClass_is009_Inter tt = null; object o = tt; bool b = o is Others_TestClass_is009_Inter; if (b == false) { return 0; } else { return 1; } } public static bool testMethod() { return (Main_old() == 0); } } public class Other_TestClass_is010_T { } public class AnotherType { } public class Other_TestClass_is010 { public static int Main_old() { Other_TestClass_is010_T tt = new Other_TestClass_is010_T(); object o = tt; bool b = o is AnotherType; if (b == false) { return 0; } else { return 1; } } public static bool testMethod() { return (Main_old() == 0); } } public class Other_TestClass_is011_A { } public class Other_TestClass_is011 { public static int Main_old() { string s = "foo"; object o = s; bool b = o is Other_TestClass_is011_A; if (b == false) { return 0; } else { return 1; } } public static bool testMethod() { return (Main_old() == 0); } } public interface Others_TestClass_is012_Inter { } public interface AnotherInter { } public class Other_TestClass_is012_T : Others_TestClass_is012_Inter { } public class Other_TestClass_is012 { public static int Main_old() { Other_TestClass_is012_T tt = new Other_TestClass_is012_T(); object o = tt; bool b = o is AnotherInter; if (b == false) { return 0; } else { return 1; } } public static bool testMethod() { return (Main_old() == 0); } } public class Others_TestClass_is013_Base { } public class Others_TestClass_is013_Der : Others_TestClass_is013_Base { } public class Other_TestClass_is013 { public static int Main_old() { Others_TestClass_is013_Base mb = new Others_TestClass_is013_Base(); object o = mb; bool b = o is Others_TestClass_is013_Der; if (b == false) { return 0; } else { return 1; } } public static bool testMethod() { return (Main_old() == 0); } } public class Others_TestClass_is0141 { public static explicit operator Others_TestClass_is0142(Others_TestClass_is0141 m) { return new Others_TestClass_is0142(); } } public class Others_TestClass_is0142 { } public class Other_TestClass_is014 { public static int Main_old() { Others_TestClass_is0141 mt = new Others_TestClass_is0141(); object o = mt; bool b = o is Others_TestClass_is0142; if (b == false) { return 0; } else { return 1; } } public static bool testMethod() { return (Main_old() == 0); } } public class Others_TestClass_is015 { } public class Other_TestClass_is015 { public static int Main_old() { object o = new object(); bool b = o is Others_TestClass_is015; if (b == false) { return 0; } else { return 1; } } public static bool testMethod() { return (Main_old() == 0); } } public class Other_TestClass_is016_T { } public class Other_TestClass_is016 { public static int Main_old() { Other_TestClass_is016_T tt = new Other_TestClass_is016_T(); object o = tt; bool b = o is Other_TestClass_is016_T; if (b == true) { return 0; } else { return 1; } } public static bool testMethod() { return (Main_old() == 0); } } public class Other_TestClass_is017 { public static int Main_old() { string s = "foo"; object o = s; bool b = o is string; if (b == true) { return 0; } else { return 1; } } public static bool testMethod() { return (Main_old() == 0); } } public interface Others_TestClass_is018_Inter { } public class Other_TestClass_is018_T : Others_TestClass_is018_Inter { } public class Other_TestClass_is018 { public static int Main_old() { Others_TestClass_is018_Inter mi = new Other_TestClass_is018_T(); object o = mi; bool b = o is Others_TestClass_is018_Inter; if (b == true) { return 0; } else { return 1; } } public static bool testMethod() { return (Main_old() == 0); } } public interface Others_TestClass_is019_Inter { } public class Other_TestClass_is019_T : Others_TestClass_is019_Inter { } public class Other_TestClass_is019 { public static int Main_old() { Other_TestClass_is019_T mi = new Other_TestClass_is019_T(); object o = mi; bool b = o is Others_TestClass_is019_Inter; if (b == true) { return 0; } else { return 1; } } public static bool testMethod() { return (Main_old() == 0); } } public class Others_TestClass_is020_Base { } public class Others_TestClass_is020_Der : Others_TestClass_is020_Base { } public class Other_TestClass_is020 { public static int Main_old() { Others_TestClass_is020_Der md = new Others_TestClass_is020_Der(); object o = md; bool b = o is Others_TestClass_is020_Base; if (b == true) { return 0; } else { return 1; } } public static bool testMethod() { return (Main_old() == 0); } } public class Others_TestClass_is0211 { public static implicit operator Others_TestClass_is0212(Others_TestClass_is0211 m) { return new Others_TestClass_is0212(); } } public class Others_TestClass_is0212 { } public class Other_TestClass_is021 { public static int Main_old() { Others_TestClass_is0211 mt = new Others_TestClass_is0211(); object o = mt; bool b = o is Others_TestClass_is0212; if (b == false) { return 0; } else { return 1; } } public static bool testMethod() { return (Main_old() == 0); } } public class Others_TestClass_is022 { } public class Other_TestClass_is022 { public static int Main_old() { Others_TestClass_is022 tc = new Others_TestClass_is022(); object o = tc; bool b = o is object; if (b == true) { return 0; } else { return 1; } } public static bool testMethod() { return (Main_old() == 0); } } public class Others_TestClass_is023 { } public class Other_TestClass_is023 { public static int Main_old() { Others_TestClass_is023 tc = new Others_TestClass_is023(); bool b = tc is Others_TestClass_is023; return 0; } public static bool testMethod() { return (Main_old() == 0); } } public class Others_TestClass_is024 { } public class Other_TestClass_is024 { public static int Main_old() { string tc = "foo"; bool b = tc is string; return 0; } public static bool testMethod() { return (Main_old() == 0); } } public interface Others_TestClass_is025_Inter { } public class Other_TestClass_is025 { public static int Main_old() { Others_TestClass_is025_Inter mi = null; bool b = mi is Others_TestClass_is025_Inter; return 0; } public static bool testMethod() { return (Main_old() == 0); } } public interface Others_TestClass_is026_Inter { } public class Others_TestClass_is026 : Others_TestClass_is026_Inter { } public class Other_TestClass_is026 { public static int Main_old() { Others_TestClass_is026 tc = new Others_TestClass_is026(); ; bool b = tc is Others_TestClass_is026_Inter; return 0; } public static bool testMethod() { return (Main_old() == 0); } } public class Others_TestClass_is027_Base { } public class Others_TestClass_is027 : Others_TestClass_is027_Base { } public class Other_TestClass_is027 { public static int Main_old() { Others_TestClass_is027 tc = new Others_TestClass_is027(); bool b = tc is Others_TestClass_is027_Base; return 0; } public static bool testMethod() { return (Main_old() == 0); } } public class Others_TestClass_is0281 { public static implicit operator Others_TestClass_is0282(Others_TestClass_is0281 m) { return new Others_TestClass_is0282(); } } public class Others_TestClass_is0282 { } public class Other_TestClass_is028 { public static int Main_old() { Others_TestClass_is0281 mt = new Others_TestClass_is0281(); bool b = mt is Others_TestClass_is0282; return 0; } public static bool testMethod() { return (Main_old() == 0); } } public class Others_TestClass_is029 { } public class AnotherClass { } public class Other_TestClass_is029 { public static int Main_old() { Others_TestClass_is029 tc = new Others_TestClass_is029(); bool b = tc is AnotherClass; return 0; } public static bool testMethod() { return (Main_old() == 0); } } public class Others_TestClass_is030 { } public class Other_TestClass_is030 { public static int Main_old() { Others_TestClass_is030 tc = new Others_TestClass_is030(); bool b = tc is string; return 0; } public static bool testMethod() { return (Main_old() == 0); } } public interface Others_TestClass_is031_Inter { } public interface Others_TestClass_is031_Inter2 { } public class Other_TestClass_is031 { public static int Main_old() { Others_TestClass_is031_Inter mi = null; bool b = mi is Others_TestClass_is031_Inter2; if (b == false) { return 0; } else { return 1; } } public static bool testMethod() { return (Main_old() == 0); } } public interface Others_TestClass_is032_Inter { } public class Others_TestClass_is032 { } public class Other_TestClass_is032 { public static int Main_old() { Others_TestClass_is032 tc = new Others_TestClass_is032(); ; bool b = tc is Others_TestClass_is032_Inter; if (b == false) { return 0; } else { return 1; } } public static bool testMethod() { return (Main_old() == 0); } } public class Others_TestClass_is033_Base { } public class Others_TestClass_is033 : Others_TestClass_is033_Base { } public class Other_TestClass_is033 { public static int Main_old() { Others_TestClass_is033_Base tc = new Others_TestClass_is033_Base(); bool b = tc is Others_TestClass_is033; if (b == false) { return 0; } else { return 1; } } public static bool testMethod() { return (Main_old() == 0); } } public class Others_TestClass_is0341 { public static explicit operator Others_TestClass_is0342(Others_TestClass_is0341 m) { return new Others_TestClass_is0342(); } } public class Others_TestClass_is0342 { } public class Other_TestClass_is034 { public static int Main_old() { Others_TestClass_is0341 mt = new Others_TestClass_is0341(); bool b = mt is Others_TestClass_is0342; return 0; } public static bool testMethod() { return (Main_old() == 0); } } public class Other_TestClass_as001 { public static int Main_old() { string s = "MyString" as string; if (s == "MyString") { return 0; } else { return 1; } } public static bool testMethod() { return (Main_old() == 0); } } public class Other_TestClass_as002 { public static int Main_old() { object o = 5 as object; if ((int)o == 5) { return 0; } else { return 1; } } public static bool testMethod() { return (Main_old() == 0); } } public class Other_TestClass_as003 { public static int Main_old() { string s = "hello"; object o = s; if ((o as System.Array) == null) { return 0; } else { return 1; } } public static bool testMethod() { return (Main_old() == 0); } } public class Other_TestClass_as004 { public static int Main_old() { string[] s = new string[] { "hello" }; object o = s; if ((o as System.Array) != null) { return 0; } else { return 1; } } public static bool testMethod() { return (Main_old() == 0); } } public class Other_TestClass_as007 { public static int Main_old() { string[] s = new string[] { "hello" }; object o = s; if ((o as System.Array) as System.Array != null) { return 0; } else { return 1; } } public static bool testMethod() { return (Main_old() == 0); } } public class Other_TestClass_as008 { public static int Main_old() { string[] s = new string[] { "hello" }; object o = s; if ((o as System.Array) as object != null) { return 0; } else { return 1; } } public static bool testMethod() { return (Main_old() == 0); } } class Other_TestClass_as011_A { } class Other_TestClass_as011_B : Other_TestClass_as011_A { } class Other_TestClass_as011_C : Other_TestClass_as011_B { } class D : Other_TestClass_as011_C { } class E : Other_TestClass_as011_C { } class F : E { } class G : F { } class Other_TestClass_as011 { static int Main_old() { Other_TestClass_as011_A a = new F(); F f = a as F; if (f != null) return 0; return 1; } public static bool testMethod() { return (Main_old() == 0); } } interface IA { } class Other_TestClass_as012_A : IA { } class Other_TestClass_as012_B : Other_TestClass_as012_A { } class Other_TestClass_as012_C : Other_TestClass_as012_A { } class Other_TestClass_as012 { public static int Main_old() { Other_TestClass_as012_A ia = new Other_TestClass_as012_B(); Other_TestClass_as012_C c = ia as Other_TestClass_as012_C; if (c != null) return 1; return 0; } public static bool testMethod() { return (Main_old() == 0); } } public class Other_TestClass_add001 { public static int Main_old() { string s = "foo" + "bar"; if (s == "foobar") { return 0; } else { return 1; } } public static bool testMethod() { return (Main_old() == 0); } } public class Other_TestClass_add002 { public static int Main_old() { string s = "foo" + 1; if (s == "foo1") { return 0; } else { return 1; } } public static bool testMethod() { return (Main_old() == 0); } } public class Other_TestClass_add003 { public static int Main_old() { string s = 1 + "foo"; if (s == "1foo") { return 0; } else { return 1; } } public static bool testMethod() { return (Main_old() == 0); } } public class Other_TestClass_add004_T { } public class Other_TestClass_add004 { public static int Main_old() { Other_TestClass_add004_T tc = new Other_TestClass_add004_T(); string s = "foo" + tc; if (s == "fooMicrosoft.SPOT.Platform.Tests.OtherTests1+Other_TestClass_add004_T") { return 0; } else { return 1; } } public static bool testMethod() { return (Main_old() == 0); } } public class Other_TestClass_add005_T { } public class Other_TestClass_add005 { public static int Main_old() { Other_TestClass_add005_T tc = new Other_TestClass_add005_T(); string s = tc + "foo"; if (s == "Microsoft.SPOT.Platform.Tests.OtherTests1+Other_TestClass_add005_Tfoo") { return 0; } else { return 1; } } public static bool testMethod() { return (Main_old() == 0); } } public class Others_TestClass_add006 { } public class Other_TestClass_add006 { public static int Main_old() { return 0; string s = "foo" + "bar"; } public static bool testMethod() { return (Main_old() == 0); } } public class Other_TestClass_logic001 { public static int Main_old() { int i1 = 2; if ((i1 & 0) == 0) { return 0; } else { return 1; } } public static bool testMethod() { return (Main_old() == 0); } } public class Other_TestClass_logic002 { public static int Main_old() { int i1 = 2; if ((0 & i1) == 0) { return 0; } else { return 1; } } public static bool testMethod() { return (Main_old() == 0); } } public class Other_TestClass_logic003 { public static int Main_old() { sbyte sb1 = 2; if ((sb1 & 0) == 0) { return 0; } else { return 1; } } public static bool testMethod() { return (Main_old() == 0); } } public class Other_TestClass_logic004 { public static int Main_old() { byte b1 = 2; if ((b1 & 0) == 0) { return 0; } else { return 1; } } public static bool testMethod() { return (Main_old() == 0); } } public class Other_TestClass_logic005 { public static int Main_old() { short s1 = 2; if ((s1 & 0) == 0) { return 0; } else { return 1; } } public static bool testMethod() { return (Main_old() == 0); } } public class Other_TestClass_logic006 { public static int Main_old() { ushort us1 = 2; if ((us1 & 0) == 0) { return 0; } else { return 1; } } public static bool testMethod() { return (Main_old() == 0); } } public class Other_TestClass_logic007 { public static int Main_old() { uint ui1 = 2; if ((ui1 & 0) == 0) { return 0; } else { return 1; } } public static bool testMethod() { return (Main_old() == 0); } } public class Other_TestClass_logic008 { public static int Main_old() { long l1 = 2; if ((l1 & 0) == 0) { return 0; } else { return 1; } } public static bool testMethod() { return (Main_old() == 0); } } public class Other_TestClass_logic009 { public static int Main_old() { ulong ul1 = 2; if ((ul1 & 0) == 0) { return 0; } else { return 1; } } public static bool testMethod() { return (Main_old() == 0); } } public class Other_TestClass_logic010 { public static int Main_old() { char c1 = (char)2; if ((c1 & 0) == 0) { return 0; } else { return 1; } } public static bool testMethod() { return (Main_old() == 0); } } public class Other_TestClass_logic011 { public static int Main_old() { int i1 = 2; if ((0 | i1) == 2) { return 0; } else { return 1; } } public static bool testMethod() { return (Main_old() == 0); } } public class Other_TestClass_logic012 { public static int Main_old() { sbyte sb1 = 2; if ((0 | sb1) == 2) { return 0; } else { return 1; } } public static bool testMethod() { return (Main_old() == 0); } } public class Other_TestClass_logic013 { public static int Main_old() { byte b1 = 2; if ((0 | b1) == 2) { return 0; } else { return 1; } } public static bool testMethod() { return (Main_old() == 0); } } public class Other_TestClass_logic014 { public static int Main_old() { short s1 = 2; if ((0 | s1) == 2) { return 0; } else { return 1; } } public static bool testMethod() { return (Main_old() == 0); } } public class Other_TestClass_logic015 { public static int Main_old() { ushort us1 = 2; if ((0 | us1) == 2) { return 0; } else { return 1; } } public static bool testMethod() { return (Main_old() == 0); } } public class Other_TestClass_logic016 { public static int Main_old() { uint ui1 = 2; if ((0 | ui1) == 2) { return 0; } else { return 1; } } public static bool testMethod() { return (Main_old() == 0); } } public class Other_TestClass_logic017 { public static int Main_old() { long l1 = 2; if ((0 | l1) == 2) { return 0; } else { return 1; } } public static bool testMethod() { return (Main_old() == 0); } } public class Other_TestClass_logic018 { public static int Main_old() { ulong ul1 = 2; if ((0 | ul1) == 2) { return 0; } else { return 1; } } public static bool testMethod() { return (Main_old() == 0); } } public class Other_TestClass_logic019 { public static int Main_old() { char c1 = (char)2; if ((0 | c1) == 2) { return 0; } else { return 1; } } public static bool testMethod() { return (Main_old() == 0); } } public class Other_TestClass_logic020 { public static int Main_old() { int i1 = 2; if ((0 ^ i1) == 2) { return 0; } else { return 1; } } public static bool testMethod() { return (Main_old() == 0); } } public class Other_TestClass_logic021 { public static int Main_old() { sbyte sb1 = 2; if ((0 ^ sb1) == 2) { return 0; } else { return 1; } } public static bool testMethod() { return (Main_old() == 0); } } public class Other_TestClass_logic022 { public static int Main_old() { byte b1 = 2; if ((0 ^ b1) == 2) { return 0; } else { return 1; } } public static bool testMethod() { return (Main_old() == 0); } } public class Other_TestClass_logic023 { public static int Main_old() { short s1 = 2; if ((0 ^ s1) == 2) { return 0; } else { return 1; } } public static bool testMethod() { return (Main_old() == 0); } } public class Other_TestClass_logic024 { public static int Main_old() { ushort us1 = 2; if ((0 ^ us1) == 2) { return 0; } else { return 1; } } public static bool testMethod() { return (Main_old() == 0); } } public class Other_TestClass_logic025 { public static int Main_old() { uint ui1 = 2; if ((0 ^ ui1) == 2) { return 0; } else { return 1; } } public static bool testMethod() { return (Main_old() == 0); } } public class Other_TestClass_logic026 { public static int Main_old() { long l1 = 2; if ((0 ^ l1) == 2) { return 0; } else { return 1; } } public static bool testMethod() { return (Main_old() == 0); } } public class Other_TestClass_logic027 { public static int Main_old() { ulong ul1 = 2; if ((0 ^ ul1) == 2) { return 0; } else { return 1; } } public static bool testMethod() { return (Main_old() == 0); } } public class Other_TestClass_logic028 { public static int Main_old() { char c1 = (char)2; if ((0 ^ c1) == 2) { return 0; } else { return 1; } } public static bool testMethod() { return (Main_old() == 0); } } public class Other_TestClass_logic029 { public static int Main_old() { byte a = 0x01; byte b = 0x02; if ((a ^ b & a | b) != (a | b & a ^ b)) return 1; if ((a ^ a ^ a | a ^ b) != 0x03) return 1; return 0; } public static bool testMethod() { return (Main_old() == 0); } } public class Other_TestClass_logic030 { public static int Main_old() { { sbyte a = 0x01; sbyte b = 0x02; if ((a ^ b & a | b) != (a | b & a ^ b)) return 1; if ((a ^ a ^ a | a ^ b) != 0x03) return 1; } { short a = 0x01; short b = 0x02; if ((a ^ b & a | b) != (a | b & a ^ b)) return 1; if ((a ^ a ^ a | a ^ b) != 0x03) return 1; } { int a = 0x01; int b = 0x02; if ((a ^ b & a | b) != (a | b & a ^ b)) return 1; if ((a ^ a ^ a | a ^ b) != 0x03) return 1; } { long a = 0x01; long b = 0x02; if ((a ^ b & a | b) != (a | b & a ^ b)) return 1; if ((a ^ a ^ a | a ^ b) != 0x03) return 1; } { byte a = 0x01; byte b = 0x02; if ((a ^ b & a | b) != (a | b & a ^ b)) return 1; if ((a ^ a ^ a | a ^ b) != 0x03) return 1; } { ushort a = 0x01; ushort b = 0x02; if ((a ^ b & a | b) != (a | b & a ^ b)) return 1; if ((a ^ a ^ a | a ^ b) != 0x03) return 1; } { uint a = 0x01; uint b = 0x02; if ((a ^ b & a | b) != (a | b & a ^ b)) return 1; if ((a ^ a ^ a | a ^ b) != 0x03) return 1; } { ulong a = 0x01; ulong b = 0x02; if ((a ^ b & a | b) != (a | b & a ^ b)) return 1; if ((a ^ a ^ a | a ^ b) != 0x03) return 1; } { char a = (char)0x01; char b = (char)0x02; if ((a ^ b & a | b) != (a | b & a ^ b)) return 1; if ((a ^ a ^ a | a ^ b) != 0x03) return 1; } return 0; } public static bool testMethod() { return (Main_old() == 0); } } public class Other_TestClass_logic032 { public static int Main_old() { checked { { sbyte a = 0x0f; sbyte b = 0x01; if ((a ^ b & a | b) != (a | b & a ^ b)) return 1; if ((a ^ a ^ a | a ^ b) != 0x0f) return 1; } { short a = 0xff; short b = 0x01; if ((a ^ b & a | b) != (a | b & a ^ b)) return 1; if ((a ^ a ^ a | a ^ b) != 0xff) return 1; } { int a = 0xff; int b = 0x01; if ((a ^ b & a | b) != (a | b & a ^ b)) return 1; if ((a ^ a ^ a | a ^ b) != 0xff) return 1; } { long a = 0xff; long b = 0x01; if ((a ^ b & a | b) != (a | b & a ^ b)) return 1; if ((a ^ a ^ a | a ^ b) != 0xff) return 1; } { byte a = 0xff; byte b = 0x01; if ((a ^ b & a | b) != (a | b & a ^ b)) return 1; if ((a ^ a ^ a | a ^ b) != 0xff) return 1; } { ushort a = 0xff; ushort b = 0x01; if ((a ^ b & a | b) != (a | b & a ^ b)) return 1; if ((a ^ a ^ a | a ^ b) != 0xff) return 1; } { uint a = 0xff; uint b = 0x01; if ((a ^ b & a | b) != (a | b & a ^ b)) return 1; if ((a ^ a ^ a | a ^ b) != 0xff) return 1; } { ulong a = 0xff; ulong b = 0x01; if ((a ^ b & a | b) != (a | b & a ^ b)) return 1; if ((a ^ a ^ a | a ^ b) != 0xff) return 1; } { char a = (char)0xff; char b = (char)0x01; if ((a ^ b & a | b) != (a | b & a ^ b)) return 1; if ((a ^ a ^ a | a ^ b) != 0xff) return 1; } } return 0; } public static bool testMethod() { return (Main_old() == 0); } } } } ================================================ FILE: Zelig/Zelig/Test/RunTime/NETMF/mscorlib/expressions/expressions2/ExpressionsTests.cs ================================================ //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // Copyright (c) Microsoft Corporation. All rights reserved. //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// using System; using System.Reflection; using Microsoft.SPOT.Platform.Test; namespace Microsoft.SPOT.Platform.Tests { public class ExpressionsTests : IMFTestInterface { [SetUp] public InitializeResult Initialize() { Log.Comment("Adding set up for the tests."); // Add your functionality here. return InitializeResult.ReadyToGo; } [TearDown] public void CleanUp() { Log.Comment("Cleaning up after the tests"); } //Expressions Test methods //The following tests were ported from folder current\test\cases\client\CLR\Conformance\10_classes\Expressions //ident001,ident002,ident003,ident004,ident007,ident008,ident009,ident010,ident011,ident012,ident013,ident014,ident015,ident016,ident017,ident018,ident019,ident020,ident021,ident022,ident023,ident024,ident025,ident026,ident027,ident028,ident029,ident030,ident031,ident032,ident033,ident034,ident035,ident038,ident039,ident040,mem001,mem002,mem003,mem004,mem005,mem006,mem007,mem008,mem011,mem012,mem013,mem014,mem015,mem016,mem017,mem018,mem019,mem021,mem022,mem023,mem025,mem026,mem027,mem028,mem029,mem031,mem032,mem034,mem035,mem036,mem038,mem040,mem042,mem043,mem044,mem045,mem046,mem047,mem048,mem050,mem052,mem054,mem055,mem056,mem058,lit001,lit004,lit005,lit006,lit007,lit008,lit009,lit010,lit011,base006,base007,base009,base010,base011,base012,base013,base014,base015,base016,base017,base018,base019,base020.cs) -- failed //Test Case Calls [TestMethod] public MFTestResults Exp_ident001_Test() { Log.Comment("Section 7.2.2 "); Log.Comment("This code tests that if the primary expression consisting of a single identifier "); Log.Comment("is within a block, and the block contains a local variable or parameter with the "); Log.Comment("given name, then the primary-expression refers to that local variable."); if (ident001.testMethod()) { return MFTestResults.Pass; } return MFTestResults.Fail; } [TestMethod] public MFTestResults Exp_ident002_Test() { Log.Comment("Section 7.2.2 "); Log.Comment("This code tests that if the primary expression consisting of a single identifier "); Log.Comment("is within a block, and the block contains a local variable or parameter with the "); Log.Comment("given name, then the primary-expression refers to that local variable."); if (ident002.testMethod()) { return MFTestResults.Pass; } return MFTestResults.Fail; } [TestMethod] public MFTestResults Exp_ident003_Test() { Log.Comment("Section 7.2.2 "); Log.Comment("This code tests that if the primary expression consisting of a single identifier "); Log.Comment("is within a block, and the block contains a local variable or parameter with the "); Log.Comment("given name, then the primary-expression refers to that local variable."); if (ident003.testMethod()) { return MFTestResults.Pass; } return MFTestResults.Fail; } [TestMethod] public MFTestResults Exp_ident004_Test() { Log.Comment("Section 7.2.2 "); Log.Comment("This code tests that if the primary expression consisting of a single identifier "); Log.Comment("is within a block, and the block contains a local variable or parameter with the "); Log.Comment("given name, then the primary-expression refers to that local variable."); if (ident004.testMethod()) { return MFTestResults.Pass; } return MFTestResults.Fail; } [TestMethod] public MFTestResults Exp_ident007_Test() { Log.Comment("Section 7.2.2 "); Log.Comment("This code tests that if the primary expression consisting of a single identifier "); Log.Comment("is within the block of a constructor, instance method, or instance property accessor,"); Log.Comment("and the name identifies one or more accessible methods of the immediately enclosing"); Log.Comment("class, then the primary expression refers to that method."); if (ident007.testMethod()) { return MFTestResults.Pass; } return MFTestResults.Fail; } [TestMethod] public MFTestResults Exp_ident008_Test() { Log.Comment("Section 7.2.2 "); Log.Comment("This code tests that if the primary expression consisting of a single identifier "); Log.Comment("is within the block of a constructor, instance method, or instance property accessor,"); Log.Comment("and the name identifies one or more accessible methods of the immediately enclosing"); Log.Comment("class, then the primary expression refers to that method."); if (ident008.testMethod()) { return MFTestResults.Pass; } return MFTestResults.Fail; } [TestMethod] public MFTestResults Exp_ident009_Test() { Log.Comment("Section 7.2.2 "); Log.Comment("This code tests that if the primary expression consisting of a single identifier "); Log.Comment("is within the block of a constructor, instance method, or instance property accessor,"); Log.Comment("and the name identifies one or more accessible methods of the immediately enclosing"); Log.Comment("class, then the primary expression refers to that method."); if (ident009.testMethod()) { return MFTestResults.Pass; } return MFTestResults.Fail; } [TestMethod] public MFTestResults Exp_ident010_Test() { Log.Comment("Section 7.2.2 "); Log.Comment("This code tests that if the primary expression consisting of a single identifier "); Log.Comment("is within the block of a constructor, instance method, or instance property accessor,"); Log.Comment("and the name identifies one or more accessible methods of the immediately enclosing"); Log.Comment("class, then the primary expression refers to that method."); if (ident010.testMethod()) { return MFTestResults.Pass; } return MFTestResults.Fail; } [TestMethod] public MFTestResults Exp_ident011_Test() { Log.Comment("Section 7.2.2 "); Log.Comment("This code tests that if the primary expression consisting of a single identifier "); Log.Comment("is within the block of a constructor, instance method, or instance property accessor,"); Log.Comment("and the name identifies an accessible, non-static field or property of the immediately"); Log.Comment("enclosing class, then the primary expression refers to that field or property."); if (ident011.testMethod()) { return MFTestResults.Pass; } return MFTestResults.Fail; } [TestMethod] public MFTestResults Exp_ident012_Test() { Log.Comment("Section 7.2.2 "); Log.Comment("This code tests that if the primary expression consisting of a single identifier "); Log.Comment("is within the block of a constructor, instance method, or instance property accessor,"); Log.Comment("and the name identifies an accessible, non-static field or property of the immediately"); Log.Comment("enclosing class, then the primary expression refers to that field or property."); if (ident012.testMethod()) { return MFTestResults.Pass; } return MFTestResults.Fail; } [TestMethod] public MFTestResults Exp_ident013_Test() { Log.Comment("Section 7.2.2 "); Log.Comment("This code tests that if the primary expression consisting of a single identifier "); Log.Comment("is within the block of a constructor, instance method, or instance property accessor,"); Log.Comment("and the name identifies an accessible, non-static field or property of the immediately"); Log.Comment("enclosing class, then the primary expression refers to that field or property."); if (ident013.testMethod()) { return MFTestResults.Pass; } return MFTestResults.Fail; } [TestMethod] public MFTestResults Exp_ident014_Test() { Log.Comment("Section 7.2.2 "); Log.Comment("This code tests that if the primary expression appears within the body of a class, "); Log.Comment("struct, or enumeration declaration, and continuing with each enclosing class or struct"); Log.Comment("declaration, if the name identifies one or more accessible members of that class, "); Log.Comment("struct, or enumeration, then the primary expression is evaluated exactly as if it was "); Log.Comment("a member access of the form T.E where T is the type in which the member was found and "); Log.Comment("E is the primary expression."); if (ident014.testMethod()) { return MFTestResults.Pass; } return MFTestResults.Fail; } [TestMethod] public MFTestResults Exp_ident015_Test() { Log.Comment("Section 7.2.2 "); Log.Comment("This code tests that if the primary expression appears within the body of a class, "); Log.Comment("struct, or enumeration declaration, and continuing with each enclosing class or struct"); Log.Comment("declaration, if the name identifies one or more accessible members of that class, "); Log.Comment("struct, or enumeration, then the primary expression is evaluated exactly as if it was "); Log.Comment("a member access of the form T.E where T is the type in which the member was found and "); Log.Comment("E is the primary expression."); if (ident015.testMethod()) { return MFTestResults.Pass; } return MFTestResults.Fail; } [TestMethod] public MFTestResults Exp_ident016_Test() { Log.Comment("Section 7.2.2 "); Log.Comment("This code tests that if the primary expression appears within the body of a class, "); Log.Comment("struct, or enumeration declaration, and continuing with each enclosing class or struct"); Log.Comment("declaration, if the name identifies one or more accessible members of that class, "); Log.Comment("struct, or enumeration, then the primary expression is evaluated exactly as if it was "); Log.Comment("a member access of the form T.E where T is the type in which the member was found and "); Log.Comment("E is the primary expression."); if (ident016.testMethod()) { return MFTestResults.Pass; } return MFTestResults.Fail; } [TestMethod] public MFTestResults Exp_ident017_Test() { Log.Comment("Section 7.2.2 "); Log.Comment("This code tests that if the primary expression appears within the body of a class, "); Log.Comment("struct, or enumeration declaration, and continuing with each enclosing class or struct"); Log.Comment("declaration, if the name identifies one or more accessible members of that class, "); Log.Comment("struct, or enumeration, then the primary expression is evaluated exactly as if it was "); Log.Comment("a member access of the form T.E where T is the type in which the member was found and "); Log.Comment("E is the primary expression."); if (ident017.testMethod()) { return MFTestResults.Pass; } return MFTestResults.Fail; } [TestMethod] public MFTestResults Exp_ident018_Test() { Log.Comment("Section 7.2.2 "); Log.Comment("This code tests that if the primary expression appears within the body of a class, "); Log.Comment("struct, or enumeration declaration, and continuing with each enclosing class or struct"); Log.Comment("declaration, if the name identifies one or more accessible members of that class, "); Log.Comment("struct, or enumeration, then the primary expression is evaluated exactly as if it was "); Log.Comment("a member access of the form T.E where T is the type in which the member was found and "); Log.Comment("E is the primary expression."); if (ident018.testMethod()) { return MFTestResults.Pass; } return MFTestResults.Fail; } [TestMethod] public MFTestResults Exp_ident019_Test() { Log.Comment("Section 7.2.2 "); Log.Comment("This code tests that if the primary expression appears within the body of a class, "); Log.Comment("struct, or enumeration declaration, and continuing with each enclosing class or struct"); Log.Comment("declaration, if the name identifies one or more accessible members of that class, "); Log.Comment("struct, or enumeration, then the primary expression is evaluated exactly as if it was "); Log.Comment("a member access of the form T.E where T is the type in which the member was found and "); Log.Comment("E is the primary expression."); if (ident019_Top.ident019.testMethod()) { return MFTestResults.Pass; } return MFTestResults.Fail; } [TestMethod] public MFTestResults Exp_ident020_Test() { Log.Comment("Section 7.2.2 "); Log.Comment("This code tests that if the primary expression appears within the body of a class, "); Log.Comment("struct, or enumeration declaration, and continuing with each enclosing class or struct"); Log.Comment("declaration, if the name identifies one or more accessible members of that class, "); Log.Comment("struct, or enumeration, then the primary expression is evaluated exactly as if it was "); Log.Comment("a member access of the form T.E where T is the type in which the member was found and "); Log.Comment("E is the primary expression."); if (ident020_Top.ident020.testMethod()) { return MFTestResults.Pass; } return MFTestResults.Fail; } [TestMethod] public MFTestResults Exp_ident021_Test() { Log.Comment("Section 7.2.2 "); Log.Comment("This code tests that if the primary expression appears within the body of a class, "); Log.Comment("struct, or enumeration declaration, and continuing with each enclosing class or struct"); Log.Comment("declaration, if the name identifies one or more accessible members of that class, "); Log.Comment("struct, or enumeration, then the primary expression is evaluated exactly as if it was "); Log.Comment("a member access of the form T.E where T is the type in which the member was found and "); Log.Comment("E is the primary expression."); if (ident021_Top.ident021.testMethod()) { return MFTestResults.Pass; } return MFTestResults.Fail; } [TestMethod] public MFTestResults Exp_ident022_Test() { Log.Comment("Section 7.2.2 "); Log.Comment("This code tests that if the primary expression appears within the body of a class, "); Log.Comment("struct, or enumeration declaration, and continuing with each enclosing class or struct"); Log.Comment("declaration, if the name identifies one or more accessible members of that class, "); Log.Comment("struct, or enumeration, then the primary expression is evaluated exactly as if it was "); Log.Comment("a member access of the form T.E where T is the type in which the member was found and "); Log.Comment("E is the primary expression."); if (ident022_Top.ident022.testMethod()) { return MFTestResults.Pass; } return MFTestResults.Fail; } [TestMethod] public MFTestResults Exp_ident023_Test() { Log.Comment("Section 7.2.2 "); Log.Comment("This code tests that if the primary expression appears within the body of a class, "); Log.Comment("struct, or enumeration declaration, and continuing with each enclosing class or struct"); Log.Comment("declaration, if the name identifies one or more accessible members of that class, "); Log.Comment("struct, or enumeration, then the primary expression is evaluated exactly as if it was "); Log.Comment("a member access of the form T.E where T is the type in which the member was found and "); Log.Comment("E is the primary expression."); if (ident023_Top.ident023.testMethod()) { return MFTestResults.Pass; } return MFTestResults.Fail; } [TestMethod] public MFTestResults Exp_ident024_Test() { Log.Comment("Section 7.2.2 "); Log.Comment("This code tests that if the primary expression appears within the body of a class, "); Log.Comment("struct, or enumeration declaration, and continuing with each enclosing class or struct"); Log.Comment("declaration, if the name identifies one or more accessible members of that class, "); Log.Comment("struct, or enumeration, then the primary expression is evaluated exactly as if it was "); Log.Comment("a member access of the form T.E where T is the type in which the member was found and "); Log.Comment("E is the primary expression."); if (ident024_Top.ident024.testMethod()) { return MFTestResults.Pass; } return MFTestResults.Fail; } [TestMethod] public MFTestResults Exp_ident025_Test() { Log.Comment("Section 7.2.2 "); Log.Comment("This code tests that if the primary expression appears within the body of a class, "); Log.Comment("struct, or enumeration declaration, and continuing with each enclosing class or struct"); Log.Comment("declaration, if the name identifies one or more accessible members of that class, "); Log.Comment("struct, or enumeration, then the primary expression is evaluated exactly as if it was "); Log.Comment("a member access of the form T.E where T is the type in which the member was found and "); Log.Comment("E is the primary expression."); if (ident025_Top.ident025_Next.ident025.testMethod()) { return MFTestResults.Pass; } return MFTestResults.Fail; } [TestMethod] public MFTestResults Exp_ident026_Test() { Log.Comment("Section 7.2.2 "); Log.Comment("This code tests that if the primary expression appears within the body of a class, "); Log.Comment("struct, or enumeration declaration, and continuing with each enclosing class or struct"); Log.Comment("declaration, if the name identifies one or more accessible members of that class, "); Log.Comment("struct, or enumeration, then the primary expression is evaluated exactly as if it was "); Log.Comment("a member access of the form T.E where T is the type in which the member was found and "); Log.Comment("E is the primary expression."); if (ident026_Top.ident026_Next.ident026.testMethod()) { return MFTestResults.Pass; } return MFTestResults.Fail; } [TestMethod] public MFTestResults Exp_ident027_Test() { Log.Comment("Section 7.2.2 "); Log.Comment("This code tests that if the primary expression appears within the body of a class, "); Log.Comment("struct, or enumeration declaration, and continuing with each enclosing class or struct"); Log.Comment("declaration, if the name identifies one or more accessible members of that class, "); Log.Comment("struct, or enumeration, then the primary expression is evaluated exactly as if it was "); Log.Comment("a member access of the form T.E where T is the type in which the member was found and "); Log.Comment("E is the primary expression."); if (ident027_Top.ident027_Next.ident027.testMethod()) { return MFTestResults.Pass; } return MFTestResults.Fail; } [TestMethod] public MFTestResults Exp_ident028_Test() { Log.Comment("Section 7.2.2 "); Log.Comment("This code tests that if the primary expression appears within the body of a class, "); Log.Comment("struct, or enumeration declaration, and continuing with each enclosing class or struct"); Log.Comment("declaration, if the name identifies one or more accessible members of that class, "); Log.Comment("struct, or enumeration, then the primary expression is evaluated exactly as if it was "); Log.Comment("a member access of the form T.E where T is the type in which the member was found and "); Log.Comment("E is the primary expression."); if (ident028_Top.ident028_Next.ident028.testMethod()) { return MFTestResults.Pass; } return MFTestResults.Fail; } [TestMethod] public MFTestResults Exp_ident029_Test() { Log.Comment("Section 7.2.2 "); Log.Comment("This code tests that if a primary expression consisting of a single identifier refers "); Log.Comment("to a member in an enclosing namespace, then the primary expression is evaluated "); Log.Comment("to that member and classified as a namespace or a type."); if (ident029.testMethod()) { return MFTestResults.Pass; } return MFTestResults.Fail; } [TestMethod] public MFTestResults Exp_ident030_Test() { Log.Comment("Section 7.2.2 "); Log.Comment("This code tests that if a primary expression consisting of a single identifier refers "); Log.Comment("to a member in an enclosing namespace, then the primary expression is evaluated "); Log.Comment("to that member and classified as a namespace or a type."); if (ident030.testMethod()) { return MFTestResults.Pass; } return MFTestResults.Fail; } [TestMethod] public MFTestResults Exp_ident031_Test() { Log.Comment("Section 7.2.2 "); Log.Comment("This code tests that if a primary expression consisting of a single identifier refers "); Log.Comment("to a member in an enclosing namespace, then the primary expression is evaluated "); Log.Comment("to that member and classified as a namespace or a type."); if (NS_ident031_I.ident031.testMethod()) { return MFTestResults.Pass; } return MFTestResults.Fail; } [TestMethod] public MFTestResults Exp_ident032_Test() { Log.Comment("Section 7.2.2 "); Log.Comment("This code tests that if a primary expression consisting of a single identifier refers "); Log.Comment("to an imported type, then the primary expression refers to that type."); if (NS_ident032_I.ident032.testMethod()) { return MFTestResults.Pass; } return MFTestResults.Fail; } [TestMethod] public MFTestResults Exp_ident033_Test() { Log.Comment("Section 7.2.2 "); Log.Comment("This code tests that if a primary expression consisting of a single identifier refers "); Log.Comment("to an imported type, then the primary expression refers to that type."); if (NS_ident033_O.NS_ident033_I.ident033.testMethod()) { return MFTestResults.Pass; } return MFTestResults.Fail; } [TestMethod] public MFTestResults Exp_ident034_Test() { Log.Comment("Section 7.2.2 "); Log.Comment("This code tests that if a primary expression consisting of a single identifier refers "); Log.Comment("to a single type in an imported namespace, then the primary expression refers to that "); Log.Comment("type."); if (NS_ident034_I.ident034.testMethod()) { return MFTestResults.Pass; } return MFTestResults.Fail; } [TestMethod] public MFTestResults Exp_ident035_Test() { Log.Comment("Section 7.2.2 "); Log.Comment("This code tests that if a primary expression consisting of a single identifier refers "); Log.Comment("to a single type in an imported namespace, then the primary expression refers to that "); Log.Comment("type."); if (NS_ident035_O.NS_ident035_I.ident035.testMethod()) { return MFTestResults.Pass; } return MFTestResults.Fail; } [TestMethod] public MFTestResults Exp_ident038_Test() { Log.Comment("Section 7.2.2 "); Log.Comment("This code tests that if a primary expression consisting of a single identifier refers "); Log.Comment("to an imported type, then the primary expression refers to that type."); if (NS_ident038_I.ident038.testMethod()) { return MFTestResults.Pass; } return MFTestResults.Fail; } [TestMethod] public MFTestResults Exp_ident039_Test() { Log.Comment("Section 7.2.2 "); Log.Comment("This code tests that if a primary expression consisting of a single identifier refers "); Log.Comment("to an imported type, then the primary expression refers to that type."); if (NS_ident039_O.NS_ident039_I.ident039.testMethod()) { return MFTestResults.Pass; } return MFTestResults.Fail; } [TestMethod] public MFTestResults Exp_ident040_Test() { Log.Comment("Section 7.2.2 "); Log.Comment("This code tests that if a primary expression consisting of a single identifier refers "); Log.Comment("to an imported type, then the primary expression refers to that type."); if (NS_ident040_I.ident040.testMethod()) { return MFTestResults.Pass; } return MFTestResults.Fail; } [TestMethod] public MFTestResults Exp_mem001_Test() { Log.Comment("Section 7.2.7 "); Log.Comment("This code tests that if the primary expression consisting of the form E.I, where E "); Log.Comment("is a namespace and I is the name of an accessible member of that namespace, then the "); Log.Comment("result is the member, either a namespace or a type."); if (mem001.testMethod()) { return MFTestResults.Pass; } return MFTestResults.Fail; } /* [TestMethod] public MFTestResults Exp_mem002_Test() { Log.Comment("Section 7.2.7 "); Log.Comment("This code tests that if the primary expression consisting of the form E.I, where E "); Log.Comment("is a namespace and I is the name of an accessible member of that namespace, then the "); Log.Comment("result is the member, either a namespace or a type."); if (mem002.testMethod()) { return MFTestResults.Pass; } return MFTestResults.Fail; } * */ [TestMethod] public MFTestResults Exp_mem003_Test() { Log.Comment("Section 7.2.7 "); Log.Comment("This code tests that if the primary expression consisting of the form E.I, where E "); Log.Comment("is a type and I is also a type, then the result of the member is that type."); if (mem003.testMethod()) { return MFTestResults.Pass; } return MFTestResults.Fail; } [TestMethod] public MFTestResults Exp_mem004_Test() { Log.Comment("Section 7.2.7 "); Log.Comment("This code tests that if the primary expression consisting of the form E.I, where E "); Log.Comment("is a type and I is also a type, then the result of the member is that type."); if (mem004.testMethod()) { return MFTestResults.Pass; } return MFTestResults.Fail; } [TestMethod] public MFTestResults Exp_mem005_Test() { Log.Comment("Section 7.2.7 "); Log.Comment("This code tests that if the primary expression consisting of the form E.I, where E "); Log.Comment("is a type and I identifies one or more methods, then the result is a method group."); if (mem005.testMethod()) { return MFTestResults.Pass; } return MFTestResults.Fail; } [TestMethod] public MFTestResults Exp_mem006_Test() { Log.Comment("Section 7.2.7 "); Log.Comment("This code tests that if the primary expression consisting of the form E.I, where E "); Log.Comment("is a type and I identifies one or more methods, then the result is a method group."); if (mem006.testMethod()) { return MFTestResults.Pass; } return MFTestResults.Fail; } [TestMethod] public MFTestResults Exp_mem007_Test() { Log.Comment("Section 7.2.7 "); Log.Comment("This code tests that if the primary expression consisting of the form E.I, where E "); Log.Comment("is a type and I identifies one or more methods, then the result is a method group."); if (mem007.testMethod()) { return MFTestResults.Pass; } return MFTestResults.Fail; } [TestMethod] public MFTestResults Exp_mem008_Test() { Log.Comment("Section 7.2.7 "); Log.Comment("This code tests that if the primary expression consisting of the form E.I, where E "); Log.Comment("is a type and I identifies one or more methods, then the result is a method group."); if (mem008.testMethod()) { return MFTestResults.Pass; } return MFTestResults.Fail; } [TestMethod] public MFTestResults Exp_mem011_Test() { Log.Comment("Section 7.2.7 "); Log.Comment("This code tests that if the primary expression consisting of the form E.I, where E "); Log.Comment("is a type and I is a static property, then the result is that static property."); if (mem011.testMethod()) { return MFTestResults.Pass; } return MFTestResults.Fail; } [TestMethod] public MFTestResults Exp_mem012_Test() { Log.Comment("Section 7.2.7 "); Log.Comment("This code tests that if the primary expression consisting of the form E.I, where E "); Log.Comment("is a type and I is a static property, then the result is that static property."); if (mem012.testMethod()) { return MFTestResults.Pass; } return MFTestResults.Fail; } [TestMethod] public MFTestResults Exp_mem013_Test() { Log.Comment("Section 7.2.7 "); Log.Comment("This code tests that if the primary expression consisting of the form E.I, where E "); Log.Comment("is a type and I is a static read only field, then the result is a value of the "); Log.Comment("static field I."); if (mem013.testMethod()) { return MFTestResults.Pass; } return MFTestResults.Fail; } [TestMethod] public MFTestResults Exp_mem014_Test() { Log.Comment("Section 7.2.7 "); Log.Comment("This code tests that if the primary expression consisting of the form E.I, where E "); Log.Comment("is a type and I is a static read only field, then the result is a value of the "); Log.Comment("static field I."); if (mem014.testMethod()) { return MFTestResults.Pass; } return MFTestResults.Fail; } [TestMethod] public MFTestResults Exp_mem015_Test() { Log.Comment("Section 7.2.7 "); Log.Comment("This code tests that if the primary expression consisting of the form E.I, where E "); Log.Comment("is a type and I is a static field, then the result is the static field I."); if (mem015.testMethod()) { return MFTestResults.Pass; } return MFTestResults.Fail; } [TestMethod] public MFTestResults Exp_mem016_Test() { Log.Comment("Section 7.2.7 "); Log.Comment("This code tests that if the primary expression consisting of the form E.I, where E "); Log.Comment("is a type and I is a static field, then the result is the static field I."); if (mem016.testMethod()) { return MFTestResults.Pass; } return MFTestResults.Fail; } [TestMethod] public MFTestResults Exp_mem017_Test() { Log.Comment("Section 7.2.7 "); Log.Comment("This code tests that if the primary expression consisting of the form E.I, where E "); Log.Comment("is a type and I is a constant, then the result is the value of that constant."); if (mem017.testMethod()) { return MFTestResults.Pass; } return MFTestResults.Fail; } [TestMethod] public MFTestResults Exp_mem018_Test() { Log.Comment("Section 7.2.7 "); Log.Comment("This code tests that if the primary expression consisting of the form E.I, where E "); Log.Comment("is a type and I is a constant, then the result is the value of that constant."); if (mem018.testMethod()) { return MFTestResults.Pass; } return MFTestResults.Fail; } [TestMethod] public MFTestResults Exp_mem019_Test() { Log.Comment("Section 7.2.7 "); Log.Comment("This code tests that if the primary expression consisting of the form E.I, where E "); Log.Comment("is a type and I identifies an enumeration member, then the result is the value of"); Log.Comment("that enumeration member."); if (mem019.testMethod()) { return MFTestResults.Pass; } return MFTestResults.Fail; } [TestMethod] public MFTestResults Exp_mem021_Test() { Log.Comment("Section 7.2.7 "); Log.Comment("This code tests that if the primary expression consisting of the form E.I, where E "); Log.Comment("is a variable, property, or value, the type of which is T, and I identifies one or "); Log.Comment("more method groups, then the result is the method group."); if (mem021.testMethod()) { return MFTestResults.Pass; } return MFTestResults.Fail; } [TestMethod] public MFTestResults Exp_mem022_Test() { Log.Comment("Section 7.2.7 "); Log.Comment("This code tests that if the primary expression consisting of the form E.I, where E "); Log.Comment("is a variable, property, or value, the type of which is T, and I identifies one or "); Log.Comment("more method groups, then the result is the method group."); if (mem022.testMethod()) { return MFTestResults.Pass; } return MFTestResults.Fail; } [TestMethod] public MFTestResults Exp_mem023_Test() { Log.Comment("Section 7.2.7 "); Log.Comment("This code tests that if the primary expression consisting of the form E.I, where E "); Log.Comment("is a variable, property, or value, the type of which is T, and I identifies one or "); Log.Comment("more method groups, then the result is the method group."); if (mem023.testMethod()) { return MFTestResults.Pass; } return MFTestResults.Fail; } [TestMethod] public MFTestResults Exp_mem025_Test() { Log.Comment("Section 7.2.7 "); Log.Comment("This code tests that if the primary expression consisting of the form E.I, where E "); Log.Comment("is a variable, property, or value, the type of which is T, and I identifies one or "); Log.Comment("more method groups, then the result is the method group."); if (mem025.testMethod()) { return MFTestResults.Pass; } return MFTestResults.Fail; } [TestMethod] public MFTestResults Exp_mem026_Test() { Log.Comment("Section 7.2.7 "); Log.Comment("This code tests that if the primary expression consisting of the form E.I, where E "); Log.Comment("is a variable, property, or value, the type of which is T, and I identifies one or "); Log.Comment("more method groups, then the result is the method group."); if (mem026.testMethod()) { return MFTestResults.Pass; } return MFTestResults.Fail; } [TestMethod] public MFTestResults Exp_mem027_Test() { Log.Comment("Section 7.2.7 "); Log.Comment("This code tests that if the primary expression consisting of the form E.I, where E "); Log.Comment("is a variable, property, or value, the type of which is T, and I identifies an "); Log.Comment("instance property, then the result is that instance property."); if (mem027.testMethod()) { return MFTestResults.Pass; } return MFTestResults.Fail; } [TestMethod] public MFTestResults Exp_mem028_Test() { Log.Comment("Section 7.2.7 "); Log.Comment("This code tests that if the primary expression consisting of the form E.I, where E "); Log.Comment("is a variable, property, or value, the type of which is T, and I identifies an "); Log.Comment("instance property, then the result is that instance property."); if (mem028.testMethod()) { return MFTestResults.Pass; } return MFTestResults.Fail; } [TestMethod] public MFTestResults Exp_mem029_Test() { Log.Comment("Section 7.2.7 "); Log.Comment("This code tests that if the primary expression consisting of the form E.I, where E "); Log.Comment("is a variable, property, or value, the type of which is T, and I identifies an "); Log.Comment("instance property, then the result is that instance property."); if (mem029.testMethod()) { return MFTestResults.Pass; } return MFTestResults.Fail; } [TestMethod] public MFTestResults Exp_mem031_Test() { Log.Comment("Section 7.2.7 "); Log.Comment("This code tests that if the primary expression consisting of the form E.I, where E "); Log.Comment("is a variable, property, or value, the type of which is T, and I identifies an "); Log.Comment("instance property, then the result is that instance property."); if (mem031.testMethod()) { return MFTestResults.Pass; } return MFTestResults.Fail; } [TestMethod] public MFTestResults Exp_mem032_Test() { Log.Comment("Section 7.2.7 "); Log.Comment("This code tests that if the primary expression consisting of the form E.I, where E "); Log.Comment("is a variable, property, or value, the type of which is T, and I identifies an "); Log.Comment("instance property, then the result is that instance property."); if (mem032.testMethod()) { return MFTestResults.Pass; } return MFTestResults.Fail; } [TestMethod] public MFTestResults Exp_mem034_Test() { Log.Comment("Section 7.2.7 "); Log.Comment("This code tests that if the primary expression consisting of the form E.I, where E "); Log.Comment("is a variable, property, or value, the class type of which is T, and I identifies"); Log.Comment("an instance field, then if the value of E is null, a System.Exception is "); Log.Comment("thrown."); if (mem034.testMethod()) { return MFTestResults.Pass; } return MFTestResults.Fail; } [TestMethod] public MFTestResults Exp_mem035_Test() { Log.Comment("Section 7.2.7 "); Log.Comment("This code tests that if the primary expression consisting of the form E.I, where E "); Log.Comment("is a variable, property, or value, the class type of which is T, and I identifies"); Log.Comment("an instance field, then if the value of E is null, a System.Exception is "); Log.Comment("thrown."); if (mem035.testMethod()) { return MFTestResults.Pass; } return MFTestResults.Fail; } [TestMethod] public MFTestResults Exp_mem036_Test() { Log.Comment("Section 7.2.7 "); Log.Comment("This code tests that if the primary expression consisting of the form E.I, where E "); Log.Comment("is a variable, property, or value, the class type of which is T, and I identifies"); Log.Comment("a read only instance field outside the class declaration, then the result is a value"); Log.Comment("of the field I."); if (mem036.testMethod()) { return MFTestResults.Pass; } return MFTestResults.Fail; } [TestMethod] public MFTestResults Exp_mem038_Test() { Log.Comment("Section 7.2.7 "); Log.Comment("This code tests that if the primary expression consisting of the form E.I, where E "); Log.Comment("is a variable, property, or value, the class type of which is T, and I identifies"); Log.Comment("a read only instance field outside the class declaration, then the result is a value"); Log.Comment("of the field I."); if (mem038.testMethod()) { return MFTestResults.Pass; } return MFTestResults.Fail; } [TestMethod] public MFTestResults Exp_mem040_Test() { Log.Comment("Section 7.2.7 "); Log.Comment("This code tests that if the primary expression consisting of the form E.I, where E "); Log.Comment("is a variable, property, or value, the class type of which is T, and I identifies"); Log.Comment("a read only instance field outside the class declaration, then the result is a value"); Log.Comment("of the field I."); if (mem040.testMethod()) { return MFTestResults.Pass; } return MFTestResults.Fail; } [TestMethod] public MFTestResults Exp_mem042_Test() { Log.Comment("Section 7.2.7 "); Log.Comment("This code tests the primary expression consisting of the form E.I, where E "); Log.Comment("is a variable, property, or value, the class type of which is T, and I identifies"); Log.Comment("an instance field of class type T."); if (mem042.testMethod()) { return MFTestResults.Pass; } return MFTestResults.Fail; } [TestMethod] public MFTestResults Exp_mem043_Test() { Log.Comment("Section 7.2.7 "); Log.Comment("This code tests the primary expression consisting of the form E.I, where E "); Log.Comment("is a variable, property, or value, the class type of which is T, and I identifies"); Log.Comment("an instance field of class type T."); if (mem043.testMethod()) { return MFTestResults.Pass; } return MFTestResults.Fail; } [TestMethod] public MFTestResults Exp_mem044_Test() { Log.Comment("Section 7.2.7 "); Log.Comment("This code tests the primary expression consisting of the form E.I, where E "); Log.Comment("is a variable, property, or value, the class type of which is T, and I identifies"); Log.Comment("an instance field of class type T."); if (mem044.testMethod()) { return MFTestResults.Pass; } return MFTestResults.Fail; } [TestMethod] public MFTestResults Exp_mem045_Test() { Log.Comment("Section 7.2.7 "); Log.Comment("This code tests the primary expression consisting of the form E.I, where E "); Log.Comment("is a variable, property, or value, the class type of which is T, and I identifies"); Log.Comment("an instance field of class type T."); if (mem045.testMethod()) { return MFTestResults.Pass; } return MFTestResults.Fail; } [TestMethod] public MFTestResults Exp_mem046_Test() { Log.Comment("Section 7.2.7 "); Log.Comment("This code tests the primary expression consisting of the form E.I, where E "); Log.Comment("is a variable, property, or value, the class type of which is T, and I identifies"); Log.Comment("an instance field of class type T."); if (mem046.testMethod()) { return MFTestResults.Pass; } return MFTestResults.Fail; } [TestMethod] public MFTestResults Exp_mem047_Test() { Log.Comment("Section 7.2.7 "); Log.Comment("This code tests the primary expression consisting of the form E.I, where E "); Log.Comment("is a variable, property, or value, the class type of which is T, and I identifies"); Log.Comment("an instance field of class type T."); if (mem047.testMethod()) { return MFTestResults.Pass; } return MFTestResults.Fail; } [TestMethod] public MFTestResults Exp_mem048_Test() { Log.Comment("Section 7.2.7 "); Log.Comment("This code tests that if the primary expression consisting of the form E.I, where E "); Log.Comment("is a variable, property, or value, the struct type of which is T, and I identifies"); Log.Comment("a read only instance field outside the class declaration, then the result is a value"); Log.Comment("of the field I."); if (mem048.testMethod()) { return MFTestResults.Pass; } return MFTestResults.Fail; } [TestMethod] public MFTestResults Exp_mem050_Test() { Log.Comment("Section 7.2.7 "); Log.Comment("This code tests that if the primary expression consisting of the form E.I, where E "); Log.Comment("is a variable, property, or value, the struct type of which is T, and I identifies"); Log.Comment("a read only instance field outside the class declaration, then the result is a value"); Log.Comment("of the field I."); if (mem050.testMethod()) { return MFTestResults.Pass; } return MFTestResults.Fail; } [TestMethod] public MFTestResults Exp_mem052_Test() { Log.Comment("Section 7.2.7 "); Log.Comment("This code tests that if the primary expression consisting of the form E.I, where E "); Log.Comment("is a variable, property, or value, the struct type of which is T, and I identifies"); Log.Comment("a read only instance field outside the class declaration, then the result is a value"); Log.Comment("of the field I."); if (mem052.testMethod()) { return MFTestResults.Pass; } return MFTestResults.Fail; } [TestMethod] public MFTestResults Exp_mem054_Test() { Log.Comment("Section 7.2.7 "); Log.Comment("This code tests the primary expression consisting of the form E.I, where E "); Log.Comment("is a variable, property, or value, the struct type of which is T, and I identifies"); Log.Comment("an instance field of class type T."); if (mem054.testMethod()) { return MFTestResults.Pass; } return MFTestResults.Fail; } [TestMethod] public MFTestResults Exp_mem055_Test() { Log.Comment("Section 7.2.7 "); Log.Comment("This code tests the primary expression consisting of the form E.I, where E "); Log.Comment("is a variable, property, or value, the struct type of which is T, and I identifies"); Log.Comment("an instance field of class type T."); if (mem055.testMethod()) { return MFTestResults.Pass; } return MFTestResults.Fail; } [TestMethod] public MFTestResults Exp_mem056_Test() { Log.Comment("Section 7.2.7 "); Log.Comment("This code tests the primary expression consisting of the form E.I, where E "); Log.Comment("is a variable, property, or value, the struct type of which is T, and I identifies"); Log.Comment("an instance field of class type T."); if (mem056.testMethod()) { return MFTestResults.Pass; } return MFTestResults.Fail; } [TestMethod] public MFTestResults Exp_mem058_Test() { Log.Comment("Section 7.2.7 "); Log.Comment("This code tests the primary expression consisting of the form E.I, where E "); Log.Comment("is a variable, property, or value, the struct type of which is T, and I identifies"); Log.Comment("an instance field of class type T."); if (mem058.testMethod()) { return MFTestResults.Pass; } return MFTestResults.Fail; } [TestMethod] public MFTestResults Exp_lit001_Test() { Log.Comment("Section 7.2.1 "); Log.Comment("This code tests that a boolean-literal is of type bool."); if (lit001.testMethod()) { return MFTestResults.Pass; } return MFTestResults.Fail; } [TestMethod] public MFTestResults Exp_lit004_Test() { Log.Comment("Section 7.2.1 "); Log.Comment("This code tests that an int-literal is of type int."); if (lit004.testMethod()) { return MFTestResults.Pass; } return MFTestResults.Fail; } [TestMethod] public MFTestResults Exp_lit005_Test() { Log.Comment("Section 7.2.1 "); Log.Comment("This code tests that a long-literal is of type long."); if (lit005.testMethod()) { return MFTestResults.Pass; } return MFTestResults.Fail; } [TestMethod] public MFTestResults Exp_lit006_Test() { Log.Comment("Section 7.2.1 "); Log.Comment("This code tests that a float-literal is of type float."); if (lit006.testMethod()) { return MFTestResults.Pass; } return MFTestResults.Fail; } [TestMethod] public MFTestResults Exp_lit007_Test() { Log.Comment("Section 7.2.1 "); Log.Comment("This code tests that a double-literal is of type double."); if (lit007.testMethod()) { return MFTestResults.Pass; } return MFTestResults.Fail; } [TestMethod] public MFTestResults Exp_lit008_Test() { Log.Comment("Section 7.2.1 "); Log.Comment("This code tests that a double-literal is of type double."); if (lit008.testMethod()) { return MFTestResults.Pass; } return MFTestResults.Fail; } [TestMethod] public MFTestResults Exp_lit009_Test() { Log.Comment("Section 7.2.1 "); Log.Comment("This code tests that a character-literal is of type char."); if (lit009.testMethod()) { return MFTestResults.Pass; } return MFTestResults.Fail; } [TestMethod] public MFTestResults Exp_lit010_Test() { Log.Comment("Section 7.2.1 "); Log.Comment("This code tests that a string-literal is of type string."); if (lit010.testMethod()) { return MFTestResults.Pass; } return MFTestResults.Fail; } [TestMethod] public MFTestResults Exp_lit011_Test() { Log.Comment("Section 7.2.1 "); Log.Comment("string compare with with its base type."); if (lit011.testMethod()) { return MFTestResults.Pass; } return MFTestResults.Fail; } [TestMethod] public MFTestResults Exp_base006_Test() { Log.Comment("Section 7.2.8 "); Log.Comment("A base class access is permitted only in the block of a constructor,"); Log.Comment("an instance method, or an instance property accessor."); if (base006.testMethod()) { return MFTestResults.Pass; } return MFTestResults.Fail; } [TestMethod] public MFTestResults Exp_base007_Test() { Log.Comment("Section 7.2.8 "); Log.Comment("A base class access is permitted only in the block of a constructor,"); Log.Comment("an instance method, or an instance property accessor."); if (base007.testMethod()) { return MFTestResults.Pass; } return MFTestResults.Fail; } [TestMethod] public MFTestResults Exp_base009_Test() { Log.Comment("Section 7.2.8 "); Log.Comment("A base class access is permitted only in the block of a constructor,"); Log.Comment("an instance method, or an instance property accessor."); if (base009.testMethod()) { return MFTestResults.Pass; } return MFTestResults.Fail; } [TestMethod] public MFTestResults Exp_base010_Test() { Log.Comment("Section 7.2.8 "); Log.Comment("A base class access is permitted only in the block of a constructor,"); Log.Comment("an instance method, or an instance property accessor."); if (base010.testMethod()) { return MFTestResults.Pass; } return MFTestResults.Fail; } [TestMethod] public MFTestResults Exp_base011_Test() { Log.Comment("Section 7.2.8 "); Log.Comment("A base class access is permitted only in the block of a constructor,"); Log.Comment("an instance method, or an instance property accessor."); if (base011.testMethod()) { return MFTestResults.Pass; } return MFTestResults.Fail; } [TestMethod] public MFTestResults Exp_base012_Test() { Log.Comment("Section 7.2.8 "); Log.Comment("A base class access is permitted only in the block of a constructor,"); Log.Comment("an instance method, or an instance property accessor."); if (base012.testMethod()) { return MFTestResults.Pass; } return MFTestResults.Fail; } [TestMethod] public MFTestResults Exp_base013_Test() { Log.Comment("Section 7.2.8 "); Log.Comment("A base class access is permitted only in the block of a constructor,"); Log.Comment("an instance method, or an instance property accessor."); if (base013.testMethod()) { return MFTestResults.Pass; } return MFTestResults.Fail; } [TestMethod] public MFTestResults Exp_base014_Test() { Log.Comment("Section 7.2.8 "); Log.Comment("A base class access is permitted only in the block of a constructor,"); Log.Comment("an instance method, or an instance property accessor."); if (base014.testMethod()) { return MFTestResults.Pass; } return MFTestResults.Fail; } [TestMethod] public MFTestResults Exp_base015_Test() { Log.Comment("Section 7.2.8 "); Log.Comment("A base class access is permitted only in the block of a constructor,"); Log.Comment("an instance method, or an instance property accessor."); if (base015.testMethod()) { return MFTestResults.Pass; } return MFTestResults.Fail; } [TestMethod] public MFTestResults Exp_base016_Test() { Log.Comment("Section 7.2.8 "); Log.Comment("A base class access is permitted only in the block of a constructor,"); Log.Comment("an instance method, or an instance property accessor."); if (base016.testMethod()) { return MFTestResults.Pass; } return MFTestResults.Fail; } [TestMethod] public MFTestResults Exp_base017_Test() { Log.Comment("Section 7.2.8 "); Log.Comment("A base class access is permitted only in the block of a constructor,"); Log.Comment("an instance method, or an instance property accessor."); Log.Comment("Expected Fail"); if (base017.testMethod()) { return MFTestResults.Fail; } return MFTestResults.Pass; } [TestMethod] public MFTestResults Exp_base018_Test() { Log.Comment("Section 7.2.8 "); Log.Comment("A base class access is permitted only in the block of a constructor,"); Log.Comment("an instance method, or an instance property accessor."); Log.Comment("Expected Fail"); if (base018.testMethod()) { return MFTestResults.Fail; } return MFTestResults.Pass; } [TestMethod] public MFTestResults Exp_base019_Test() { Log.Comment("Section 7.2.8 "); Log.Comment("A base class access is permitted only in the block of a constructor,"); Log.Comment("an instance method, or an instance property accessor."); Log.Comment("Expected Fail"); if (base019.testMethod()) { return MFTestResults.Fail; } return MFTestResults.Pass; } [TestMethod] public MFTestResults Exp_base020_Test() { Log.Comment("Section 7.2.8 "); Log.Comment("A base class access is permitted only in the block of a constructor,"); Log.Comment("an instance method, or an instance property accessor."); Log.Comment("Expected Fail"); if (base020.testMethod()) { return MFTestResults.Fail; } return MFTestResults.Pass; } //Compiled Test Cases public class ident001 { static int intI = 1; public static int Main_old() { int intI = 0; return intI; //should return zero } public static bool testMethod() { return (Main_old() == 0); } } public class ident002 { static int intI = 1; public static int f(int intI) { return intI; } public static int Main_old() { return f(0); //should return zero } public static bool testMethod() { return (Main_old() == 0); } } public class ident003 { static int intI = 1; public static int Main_old() { if (true) { int intI = 0; return intI; } return 1; //error if we reach this point } public static bool testMethod() { return (Main_old() == 0); } } public class ident004 { static int intI = 1; public static int Main_old() { { int intI = 0; return intI; } return 1; //error if we reach this point } public static bool testMethod() { return (Main_old() == 0); } } public class ident007 { static int intRet = 1; public static void ChangeRet() { intRet = 0; } public ident007() { ChangeRet(); //primary expression in constructor } public static int Main_old() { ident007 MyClass = new ident007(); //this should change return value return intRet; } public static bool testMethod() { return (Main_old() == 0); } } public class ident008 { static int intRet = 1; public static void ChangeRet() { intRet = 0; } public void ChangeVal() { ChangeRet(); //primary expression in instance method } public static int Main_old() { ident008 MyClass = new ident008(); MyClass.ChangeVal(); //this should change return value return intRet; } public static bool testMethod() { return (Main_old() == 0); } } public class ident009 { static int intRet = 1; public static void ChangeRet() { intRet = 0; } public int MyInt { get { ChangeRet(); //primary expression in instance property accessor return 0; } set { } } public static int Main_old() { ident009 MyClass = new ident009(); int intI = MyClass.MyInt; //this should change the return value return intRet; } public static bool testMethod() { return (Main_old() == 0); } } public class ident010 { static int intRet = 1; public static void ChangeRet() { intRet = 0; } public int MyInt { get { return 0; } set { ChangeRet(); //primary expression in instance property accessor } } public static int Main_old() { ident010 MyClass = new ident010(); MyClass.MyInt = 1; //this should change the return value to zero return intRet; } public static bool testMethod() { return (Main_old() == 0); } } public class ident011 { int intRet = 0; int TestInt = 3; public int TestProp { get { return 7; } set { TestInt = 2; } } public ident011() { if (TestInt != 3) intRet = 1; //accessing non-static field if (TestInt != this.TestInt) intRet = 1; //accessing non-static field if (TestProp != 7) intRet = 1; //accessing instance property if (TestProp != this.TestProp) intRet = 1;//accessing instance property TestProp = 8; //accessing instance property if (TestInt != 2) intRet = 1; //confirming property setter was called } public static int Main_old() { ident011 MyClass = new ident011(); return MyClass.intRet; //return value will return 1 if something went wrong } public static bool testMethod() { return (Main_old() == 0); } } public class ident012 { int intRet = 0; int TestInt = 3; public int TestProp { get { return 7; } set { TestInt = 2; } } public void TestCode() { if (TestInt != 3) intRet = 1; //accessing non-static field if (TestInt != this.TestInt) intRet = 1; //accessing non-static field if (TestProp != 7) intRet = 1; //accessing instance property if (TestProp != this.TestProp) intRet = 1;//accessing instance property TestProp = 8; //accessing instance property if (TestInt != 2) intRet = 1; //confirming property setter was called } public static int Main_old() { ident012 MyClass = new ident012(); MyClass.TestCode(); return MyClass.intRet; //return value will return 1 if something went wrong } public static bool testMethod() { return (Main_old() == 0); } } public class ident013 { int intRet = 0; int TestInt = 3; public int TestProp { get { return 7; } set { TestInt = 2; } } public int CallProp { get { if (TestInt != 3) intRet = 1; //accessing non-static field if (TestInt != this.TestInt) intRet = 1; //accessing non-static field if (TestProp != 7) intRet = 1; //accessing instance property if (TestProp != this.TestProp) intRet = 1;//accessing instance property TestProp = 8; //accessing instance property if (TestInt != 2) intRet = 1; //confirming property setter was called return 0; } set { if (TestInt != 3) intRet = 1; //accessing non-static field if (TestInt != this.TestInt) intRet = 1; //accessing non-static field if (TestProp != 7) intRet = 1; //accessing instance property if (TestProp != this.TestProp) intRet = 1;//accessing instance property TestProp = 8; //accessing instance property if (TestInt != 2) intRet = 1; //confirming property setter was called } } public static int Main_old() { ident013 MyClass = new ident013(); int intI = MyClass.CallProp; //calling getter MyClass.TestInt = 3; //resetting for the setter MyClass.CallProp = 2; //calling setter return MyClass.intRet; //return value will return 1 if something went wrong } public static bool testMethod() { return (Main_old() == 0); } } public class ident014 { static int IntThree = 3; static int TestInt = IntThree; //identifier appears within body of class public static int Main_old() { if (TestInt == 3) { return 0; } else { return 1; } } public static bool testMethod() { return (Main_old() == 0); } } public class ident015 { static int ReturnThree() { return 3; } static int TestInt = ReturnThree(); //identifier appears within body of class public static int Main_old() { if (TestInt == 3) { return 0; } else { return 1; } } public static bool testMethod() { return (Main_old() == 0); } } public struct ident016 { static int IntThree = 3; static int TestInt = IntThree; //identifier appears within body of class public static int Main_old() { if (TestInt == 3) { return 0; } else { return 1; } } public static bool testMethod() { return (Main_old() == 0); } } public struct ident017 { static int ReturnThree() { return 3; } static int TestInt = ReturnThree(); //identifier appears within body of class public static int Main_old() { if (TestInt == 3) { return 0; } else { return 1; } } public static bool testMethod() { return (Main_old() == 0); } } enum AA { a = 3, b = a }; //identifier appears within body of enum public class ident018 { public static int Main_old() { if ((int)AA.b == 3) { return 0; } else { return 1; } } public static bool testMethod() { return (Main_old() == 0); } } public class ident019_Top { public static int IntThree = 3; public class ident019 { public static int TestInt = IntThree; public static int Main_old() { if (TestInt == 3) { return 0; } else { return 1; } } public static bool testMethod() { return (Main_old() == 0); } } } public class ident020_Top { public static int ReturnThree() { return 3; } public class ident020 { public static int TestInt = ReturnThree(); public static int Main_old() { if (TestInt == 3) { return 0; } else { return 1; } } public static bool testMethod() { return (Main_old() == 0); } } } public class ident021_Top { public static int IntThree = 3; public struct ident021 { public static int TestInt = IntThree; public static int Main_old() { if (TestInt == 3) { return 0; } else { return 1; } } public static bool testMethod() { return (Main_old() == 0); } } } public class ident022_Top { public static int ReturnThree() { return 3; } public struct ident022 { public static int TestInt = ReturnThree(); public static int Main_old() { if (TestInt == 3) { return 0; } else { return 1; } } public static bool testMethod() { return (Main_old() == 0); } } } public struct ident023_Top { public static int IntThree = 3; public struct ident023 { public static int TestInt = IntThree; public static int Main_old() { if (TestInt == 3) { return 0; } else { return 1; } } public static bool testMethod() { return (Main_old() == 0); } } } public struct ident024_Top { public static int ReturnThree() { return 3; } public struct ident024 { public static int TestInt = ReturnThree(); public static int Main_old() { if (TestInt == 3) { return 0; } else { return 1; } } public static bool testMethod() { return (Main_old() == 0); } } } public class ident025_Top { public static int IntThree = 3; public class ident025_Next { public class ident025 { public static int TestInt = IntThree; public static int Main_old() { if (TestInt == 3) { return 0; } else { return 1; } } public static bool testMethod() { return (Main_old() == 0); } } } } public class ident026_Top { public static int ReturnThree() { return 3; } public class ident026_Next { public class ident026 { public static int TestInt = ReturnThree(); public static int Main_old() { if (TestInt == 3) { return 0; } else { return 1; } } public static bool testMethod() { return (Main_old() == 0); } } } } public class ident027_Top { public static int IntThree = 2; public class ident027_Next { public static int IntThree = 3; //should refer to this one public class ident027 { public static int TestInt = IntThree; public static int Main_old() { if (TestInt == 3) { return 0; } else { return 1; } } public static bool testMethod() { return (Main_old() == 0); } } } } public class ident028_Top { public static int ReturnThree() { return 2; } public class ident028_Next { public static int ReturnThree() { return 3; } public class ident028 { public static int TestInt = ReturnThree(); public static int Main_old() { if (TestInt == 3) { return 0; } else { return 1; } } public static bool testMethod() { return (Main_old() == 0); } } } } public class Exp_TestClass_ident029_TC { public int TestInt = 1; } public class ident029 { public static int Main_old() { Exp_TestClass_ident029_TC TC = new Exp_TestClass_ident029_TC(); //testing type identifier in same namespace if (TC.TestInt == 1) { return 0; } else { return 1; } } public static bool testMethod() { return (Main_old() == 0); } } public class Exp_TestClass_ident030_TC { public int TestInt = 1; } public class ident030 { public static int Main_old() { Exp_TestClass_ident030_TC TC = new Exp_TestClass_ident030_TC(); //testing type identifier in enclosing namespace if (TC.TestInt == 1) { return 0; } else { return 1; } } public static bool testMethod() { return (Main_old() == 0); } } public class mem001 { public static int Main_old() { Exp_TestClass_mem001_TS.Exp_TestClass_mem001_TC TC = new Exp_TestClass_mem001_TS.Exp_TestClass_mem001_TC(); //testing E.I if (TC.TestInt == 2) { return 0; } else { return 1; } } public static bool testMethod() { return (Main_old() == 0); } } /* public class mem002 { public static int Main_old() { Exp_TestClass_mem002_TC TC = new Exp_TestClass_mem002_TC(); //testing E.I if (TC.TestInt == 3) { return 0; } else { return 1; } } public static bool testMethod() { return (Main_old() == 0); } } */ public class Exp_TestClass_mem003_TC { public class InnerClass { public int TestInt = 2; } } public class mem003 { public static int Main_old() { Exp_TestClass_mem003_TC.InnerClass TC = new Exp_TestClass_mem003_TC.InnerClass(); //testing E.I if (TC.TestInt == 2) { return 0; } else { return 1; } } public static bool testMethod() { return (Main_old() == 0); } } public struct Exp_TestClass_mem004_TC { public class InnerClass { public int TestInt = 2; } } public class mem004 { public static int Main_old() { Exp_TestClass_mem004_TC.InnerClass TC = new Exp_TestClass_mem004_TC.InnerClass(); //testing E.I if (TC.TestInt == 2) { return 0; } else { return 1; } } public static bool testMethod() { return (Main_old() == 0); } } public class Exp_TestClass_mem005_TC { public static int IntRet() { return 1; } } public class mem005 { public static int Main_old() { if (Exp_TestClass_mem005_TC.IntRet() == 1) { //testing E.I return 0; } else { return 1; } } public static bool testMethod() { return (Main_old() == 0); } } public struct Exp_TestClass_mem006_TC { public static int IntRet() { return 1; } } public class mem006 { public static int Main_old() { if (Exp_TestClass_mem006_TC.IntRet() == 1) { //testing E.I return 0; } else { return 1; } } public static bool testMethod() { return (Main_old() == 0); } } public class Exp_TestClass_mem007_TC { public static int IntRet() { return 1; } public static int IntRet(int IntI) { return IntI; } } public class mem007 { public static int Main_old() { if (Exp_TestClass_mem007_TC.IntRet(4) == 4) { //testing E.I return 0; } else { return 1; } } public static bool testMethod() { return (Main_old() == 0); } } public struct Exp_TestClass_mem008_TC { public static int IntRet() { return 1; } public static int IntRet(int IntI) { return IntI; } } public class mem008 { public static int Main_old() { if (Exp_TestClass_mem008_TC.IntRet(4) == 4) { //testing E.I return 0; } else { return 1; } } public static bool testMethod() { return (Main_old() == 0); } } public class Exp_TestClass_mem011_TC { public static int TestInt = 0; public static int MyInt { get { TestInt = 1; return TestInt; } set { TestInt = TestInt + 1; } } } public class mem011 { public static int Main_old() { int RetInt = 0; if (Exp_TestClass_mem011_TC.MyInt != 1) RetInt = 1; //testing E.I if (Exp_TestClass_mem011_TC.TestInt != 1) RetInt = 1; Exp_TestClass_mem011_TC.MyInt = 3; //testing E.I if (Exp_TestClass_mem011_TC.TestInt != 2) RetInt = 1; return RetInt; } public static bool testMethod() { return (Main_old() == 0); } } public struct Exp_TestClass_mem012_TC { public static int TestInt = 0; public static int MyInt { get { TestInt = 1; return TestInt; } set { TestInt = TestInt + 1; } } } public class mem012 { public static int Main_old() { int RetInt = 0; if (Exp_TestClass_mem012_TC.MyInt != 1) RetInt = 1; //testing E.I if (Exp_TestClass_mem012_TC.TestInt != 1) RetInt = 1; Exp_TestClass_mem012_TC.MyInt = 3; //testing E.I if (Exp_TestClass_mem012_TC.TestInt != 2) RetInt = 1; return RetInt; } public static bool testMethod() { return (Main_old() == 0); } } public class Exp_TestClass_mem013_TC { public static readonly int TestInt = 2; } public class mem013 { public static int Main_old() { if (Exp_TestClass_mem013_TC.TestInt == 2) { return 0; } else { return 1; } } public static bool testMethod() { return (Main_old() == 0); } } public struct Exp_TestClass_mem014_TC { public static readonly int TestInt = 2; } public class mem014 { public static int Main_old() { if (Exp_TestClass_mem014_TC.TestInt == 2) { return 0; } else { return 1; } } public static bool testMethod() { return (Main_old() == 0); } } public class Exp_TestClass_mem015_TC { public static int TestInt = 2; } public class mem015 { public static int Main_old() { int RetInt = 0; if (Exp_TestClass_mem015_TC.TestInt != 2) { //testing E.I RetInt = 1; } Exp_TestClass_mem015_TC.TestInt = 3; //testing E.I if (Exp_TestClass_mem015_TC.TestInt != 3) { //testing E.I RetInt = 1; } return RetInt; } public static bool testMethod() { return (Main_old() == 0); } } public struct Exp_TestClass_mem016_TC { public static int TestInt = 2; } public class mem016 { public static int Main_old() { int RetInt = 0; if (Exp_TestClass_mem016_TC.TestInt != 2) { //testing E.I RetInt = 1; } Exp_TestClass_mem016_TC.TestInt = 3; //testing E.I if (Exp_TestClass_mem016_TC.TestInt != 3) { //testing E.I RetInt = 1; } return RetInt; } public static bool testMethod() { return (Main_old() == 0); } } public class Exp_TestClass_mem017_TC { public const int TestInt = 2; } public class mem017 { public static int Main_old() { if (Exp_TestClass_mem017_TC.TestInt == 2) { //testing E.I return 0; } else { return 1; } } public static bool testMethod() { return (Main_old() == 0); } } public struct Exp_TestClass_mem018_TC { public const int TestInt = 2; } public class mem018 { public static int Main_old() { if (Exp_TestClass_mem018_TC.TestInt == 2) { //testing E.I return 0; } else { return 1; } } public static bool testMethod() { return (Main_old() == 0); } } enum mem019_AA { a = 3, b = a }; public class mem019 { public static int Main_old() { if ((int)mem019_AA.a == 3) { //testing E.I return 0; } else { return 1; } } public static bool testMethod() { return (Main_old() == 0); } } public class Exp_TestClass_mem021_TC { public int IntRet() { return 2; } public int IntRet(int IntI) { return IntI; } } public class mem021 { public static Exp_TestClass_mem021_TC GetTC { get { return new Exp_TestClass_mem021_TC(); } } public static int Main_old() { int MyRet = 0; if (GetTC.IntRet() != 2) { //testing E.I MyRet = 1; } if (GetTC.IntRet(3) != 3) { //testing E.I MyRet = 1; } return MyRet; } public static bool testMethod() { return (Main_old() == 0); } } public class Exp_TestClass_mem022_TC { public int IntRet() { return 2; } public int IntRet(int IntI) { return IntI; } } public class mem022 { public static int Main_old() { int MyRet = 0; Exp_TestClass_mem022_TC TC = new Exp_TestClass_mem022_TC(); if (TC.IntRet() != 2) { //testing E.I MyRet = 1; } if (TC.IntRet(3) != 3) { //testing E.I MyRet = 1; } return MyRet; } public static bool testMethod() { return (Main_old() == 0); } } public class Exp_TestClass_mem023_TC { public int IntRet() { return 2; } public int IntRet(int IntI) { return IntI; } } public class mem023 { public static int Main_old() { int MyRet = 0; Exp_TestClass_mem023_TC TC = new Exp_TestClass_mem023_TC(); if (new Exp_TestClass_mem023_TC().IntRet() != 2) { //testing E.I MyRet = 1; } if (new Exp_TestClass_mem023_TC().IntRet(3) != 3) { //testing E.I MyRet = 1; } return MyRet; } public static bool testMethod() { return (Main_old() == 0); } } public struct Exp_TestClass_mem025_TC { public int IntRet() { return 2; } public int IntRet(int IntI) { return IntI; } } public class mem025 { public static int Main_old() { int MyRet = 0; Exp_TestClass_mem025_TC TC = new Exp_TestClass_mem025_TC(); if (TC.IntRet() != 2) { //testing E.I MyRet = 1; } if (TC.IntRet(3) != 3) { //testing E.I MyRet = 1; } return MyRet; } public static bool testMethod() { return (Main_old() == 0); } } public struct Exp_TestClass_mem026_TC { public int IntRet() { return 2; } public int IntRet(int IntI) { return IntI; } } public class mem026 { public static int Main_old() { int MyRet = 0; Exp_TestClass_mem026_TC TC = new Exp_TestClass_mem026_TC(); if (new Exp_TestClass_mem026_TC().IntRet() != 2) { //testing E.I MyRet = 1; } if (new Exp_TestClass_mem026_TC().IntRet(3) != 3) { //testing E.I MyRet = 1; } return MyRet; } public static bool testMethod() { return (Main_old() == 0); } } public class Exp_TestClass_mem027_TC { public static int IntVal = 2; public int IntRet { get { return IntVal; } set { IntVal = IntVal + 1; } } } public class mem027 { public static Exp_TestClass_mem027_TC GetTC { get { return new Exp_TestClass_mem027_TC(); } } public static int Main_old() { int MyRet = 0; if (GetTC.IntRet != 2) { //testing E.I MyRet = 1; } GetTC.IntRet = 3; //testing E.I if (Exp_TestClass_mem027_TC.IntVal != 3) { MyRet = 1; } return MyRet; } public static bool testMethod() { return (Main_old() == 0); } } public class Exp_TestClass_mem028_TC { public static int IntVal = 2; public int IntRet { get { return IntVal; } set { IntVal = IntVal + 1; } } } public class mem028 { public static int Main_old() { int MyRet = 0; Exp_TestClass_mem028_TC TC = new Exp_TestClass_mem028_TC(); if (TC.IntRet != 2) { //testing E.I MyRet = 1; } TC.IntRet = 3; //testing E.I if (Exp_TestClass_mem028_TC.IntVal != 3) { MyRet = 1; } return MyRet; } public static bool testMethod() { return (Main_old() == 0); } } public class Exp_TestClass_mem029_TC { public static int IntVal = 2; public int IntRet { get { return IntVal; } set { IntVal = IntVal + 1; } } } public class mem029 { public static int Main_old() { int MyRet = 0; if (new Exp_TestClass_mem029_TC().IntRet != 2) { //testing E.I MyRet = 1; } new Exp_TestClass_mem029_TC().IntRet = 3; //testing E.I if (Exp_TestClass_mem029_TC.IntVal != 3) { MyRet = 1; } return MyRet; } public static bool testMethod() { return (Main_old() == 0); } } public struct Exp_TestClass_mem031_TC { public static int IntVal = 2; public int IntRet { get { return IntVal; } set { IntVal = IntVal + 1; } } } public class mem031 { public static int Main_old() { int MyRet = 0; Exp_TestClass_mem031_TC TC = new Exp_TestClass_mem031_TC(); if (TC.IntRet != 2) { //testing E.I MyRet = 1; } TC.IntRet = 3; //testing E.I if (Exp_TestClass_mem031_TC.IntVal != 3) { MyRet = 1; } return MyRet; } public static bool testMethod() { return (Main_old() == 0); } } public struct Exp_TestClass_mem032_TC { public int IntRet { get { return 2; } } } public class mem032 { public static int Main_old() { int MyRet = 0; if (new Exp_TestClass_mem032_TC().IntRet != 2) { //testing E.I MyRet = 1; } return MyRet; } public static bool testMethod() { return (Main_old() == 0); } } public class Exp_TestClass_mem034_TC { public int IntI = 0; } public class mem034 { public static int Main_old() { int RetInt = 1; Exp_TestClass_mem034_TC TC = null; try { int MyInt = TC.IntI; } catch (System.Exception) { RetInt = 0; } return RetInt; } public static bool testMethod() { return (Main_old() == 0); } } public class Exp_TestClass_mem035_TC { public int IntI = 0; } public class mem035 { public static Exp_TestClass_mem035_TC getTC{ get { return null; } } public static int Main_old() { int RetInt = 1; try { int TempInt = getTC.IntI; } catch (System.Exception) { RetInt = 0; } return RetInt; } public static bool testMethod() { return (Main_old() == 0); } } public class Exp_TestClass_mem036_TC { public readonly int IntI = 0; } public class mem036 { public static int Main_old() { int RetInt = 1; Exp_TestClass_mem036_TC TC = new Exp_TestClass_mem036_TC(); RetInt = TC.IntI; //testing E.I return RetInt; } public static bool testMethod() { return (Main_old() == 0); } } public class Exp_TestClass_mem038_TC { public readonly int IntI = 0; } public class mem038 { public static Exp_TestClass_mem038_TC getTC { get { return new Exp_TestClass_mem038_TC(); } } public static int Main_old() { int RetInt = 1; Exp_TestClass_mem038_TC TC = new Exp_TestClass_mem038_TC(); RetInt = getTC.IntI; //testing E.I return RetInt; } public static bool testMethod() { return (Main_old() == 0); } } public class Exp_TestClass_mem040_TC { public readonly int IntI = 0; } public class mem040 { public static int Main_old() { int RetInt = 1; RetInt = new Exp_TestClass_mem040_TC().IntI; //testing E.I return RetInt; } public static bool testMethod() { return (Main_old() == 0); } } public class Exp_TestClass_mem042_TC { public int IntI = 0; } public class mem042 { public static int Main_old() { int RetInt = 1; Exp_TestClass_mem042_TC TC = new Exp_TestClass_mem042_TC(); RetInt = TC.IntI; //testing E.I return RetInt; } public static bool testMethod() { return (Main_old() == 0); } } public class Exp_TestClass_mem043_TC { public int IntI = 0; } public class mem043 { public static int Main_old() { Exp_TestClass_mem043_TC TC = new Exp_TestClass_mem043_TC(); TC.IntI = 3; //testing E.I if (TC.IntI == 3) { return 0; } else { return 1; } } public static bool testMethod() { return (Main_old() == 0); } } public class Exp_TestClass_mem044_TC { public int IntI = 0; } public class mem044 { public static Exp_TestClass_mem044_TC getTC { get { return new Exp_TestClass_mem044_TC(); } } public static int Main_old() { int RetInt = 1; RetInt = getTC.IntI; //testing E.I return RetInt; } public static bool testMethod() { return (Main_old() == 0); } } public class Exp_TestClass_mem045_TC { public int IntI = 0; } public class mem045 { static Exp_TestClass_mem045_TC TC = new Exp_TestClass_mem045_TC(); public static Exp_TestClass_mem045_TC getTC { get { return TC; } } public static int Main_old() { getTC.IntI = 3; //testing E.I ZMyClass.MyPrint(TC.IntI); if (TC.IntI == 3) { return 0; } else { return 1; } } public static bool testMethod() { return (Main_old() == 0); } } class ZMyClass { public static void MyPrint() {Microsoft.SPOT.Debug.Print("\n");} public static void MyPrint( string str ) {Microsoft.SPOT.Debug.Print(str);} public static void MyPrint( object ob ) { Microsoft.SPOT.Debug.Print(ob.ToString()); } public static void MyPrint( string fmt, params object[] arg ) { string str = ""; for( int i = 0; i < arg.Length; i++ ) { str = str + arg[i].ToString(); } Microsoft.SPOT.Debug.Print(str); } } public class Exp_TestClass_mem046_TC { public int IntI = 0; } public class mem046 { public static int Main_old() { int RetInt = 1; RetInt = new Exp_TestClass_mem046_TC().IntI; //testing E.I return RetInt; } public static bool testMethod() { return (Main_old() == 0); } } public class Exp_TestClass_mem047_TC { public int IntI = 0; } public class mem047 { public static int Main_old() { new Exp_TestClass_mem047_TC().IntI = 3; //if it compiles, no error return 0; } public static bool testMethod() { return (Main_old() == 0); } } public struct Exp_TestClass_mem048_TC { public Exp_TestClass_mem048_TC(int intI) { IntI = 0; } public readonly int IntI; } public class mem048 { public static int Main_old() { int RetInt = 1; Exp_TestClass_mem048_TC TC = new Exp_TestClass_mem048_TC(2); RetInt = TC.IntI; //testing E.I return RetInt; } public static bool testMethod() { return (Main_old() == 0); } } public struct Exp_TestClass_mem050_TC { public Exp_TestClass_mem050_TC(int intI) { IntI = 0; } public readonly int IntI; } public class mem050 { public static Exp_TestClass_mem050_TC getTC { get { return new Exp_TestClass_mem050_TC(3); } } public static int Main_old() { int RetInt = 1; Exp_TestClass_mem050_TC TC = new Exp_TestClass_mem050_TC(3); RetInt = getTC.IntI; //testing E.I return RetInt; } public static bool testMethod() { return (Main_old() == 0); } } public struct Exp_TestClass_mem052_TC { public Exp_TestClass_mem052_TC(int intI) { IntI = 0; } public readonly int IntI; } public class mem052 { public static int Main_old() { int RetInt = 1; RetInt = new Exp_TestClass_mem052_TC(3).IntI; //testing E.I return RetInt; } public static bool testMethod() { return (Main_old() == 0); } } public struct Exp_TestClass_mem054_TC { public Exp_TestClass_mem054_TC(int intI) { IntI = 0; } public int IntI; } public class mem054 { public static int Main_old() { int RetInt = 1; Exp_TestClass_mem054_TC TC = new Exp_TestClass_mem054_TC(3); RetInt = TC.IntI; //testing E.I return RetInt; } public static bool testMethod() { return (Main_old() == 0); } } public struct Exp_TestClass_mem055_TC { public Exp_TestClass_mem055_TC(int intI) { IntI = 0; } public int IntI; } public class mem055 { public static int Main_old() { Exp_TestClass_mem055_TC TC = new Exp_TestClass_mem055_TC(3); TC.IntI = 3; //testing E.I if (TC.IntI == 3) { return 0; } else { return 1; } } public static bool testMethod() { return (Main_old() == 0); } } public struct Exp_TestClass_mem056_TC { public Exp_TestClass_mem056_TC(int intI) { IntI = 0; } public int IntI; } public class mem056 { public static Exp_TestClass_mem056_TC getTC { get { return new Exp_TestClass_mem056_TC(3); } } public static int Main_old() { int RetInt = 1; Exp_TestClass_mem056_TC TC = new Exp_TestClass_mem056_TC(3); RetInt = getTC.IntI; //testing E.I return RetInt; } public static bool testMethod() { return (Main_old() == 0); } } public struct Exp_TestClass_mem058_TC { public Exp_TestClass_mem058_TC(int intI) { IntI = 0; } public int IntI; } public class mem058 { public static int Main_old() { int RetInt = 1; RetInt = new Exp_TestClass_mem058_TC(3).IntI; //testing E.I return RetInt; } public static bool testMethod() { return (Main_old() == 0); } } public class lit001 { public static int Main_old() { int RetInt = 1; Type t1 = true.GetType(); Type t2 = false.GetType(); Type t3 = typeof(System.Boolean); if ((t1 == t3) && (t2 == t3)) { RetInt = 0; } return RetInt; } public static bool testMethod() { return (Main_old() == 0); } } public class lit004 { public static int Main_old() { int RetInt = 1; Type t1 = 3.GetType(); Type t2 = (-44).GetType(); Type t3 = 234.GetType(); Type t4 = typeof(System.Int32); if ((t1 == t4) && (t2 == t4) && (t3 == t4)){ RetInt = 0; } return RetInt; } public static bool testMethod() { return (Main_old() == 0); } } public class lit005 { public static int Main_old() { int RetInt = 1; Type t1 = 3L.GetType(); Type t2 = (-3000L).GetType(); Type t3 = typeof(System.Int64); if ((t1 == t3) && (t2 == t3)){ RetInt = 0; } return RetInt; } public static bool testMethod() { return (Main_old() == 0); } } public class lit006 { public static int Main_old() { int RetInt = 1; Type t1 = 2.0f.GetType(); Type t2 = (-2.33F).GetType(); Type t3 = typeof(System.Single); if ((t1 == t3) && (t2 == t3)) { RetInt = 0; } return RetInt; } public static bool testMethod() { return (Main_old() == 0); } } public class lit007 { public static int Main_old() { int RetInt = 1; Type t1 = 2.0d.GetType(); Type t2 = (-2.33D).GetType(); Type t3 = 2.343.GetType(); Type t4 = typeof(System.Double); if ((t1 == t4) && (t2 == t4) && (t3 == t4)) { RetInt = 0; } return RetInt; } public static bool testMethod() { return (Main_old() == 0); } } public class lit008 { public static int Main_old() { int RetInt = 1; Type t1 = 2.0.GetType(); Type t2 = (-2.33).GetType(); Type t3 = typeof(System.Double); if ((t1 == t3) && (t2 == t3)) { RetInt = 0; } return RetInt; } public static bool testMethod() { return (Main_old() == 0); } } public class lit009 { public static int Main_old() { int RetInt = 1; Type t1 = 'a'.GetType(); Type t2 = typeof(System.Char); if (t1 == t2) { RetInt = 0; } return RetInt; } public static bool testMethod() { return (Main_old() == 0); } } public class lit010 { public static int Main_old() { int RetInt = 1; Type t1 = "foobar".GetType(); Type t2 = typeof(System.String); if (t1 == t2) { RetInt = 0; } return RetInt; } public static bool testMethod() { return (Main_old() == 0); } } public class lit011 { public static int Main_old() { string s = "This is an expression test"; object o = s; bool b = o == s; bool bb = s == o; if(b && bb) return 0; else return 1; } public static bool testMethod() { return (Main_old() == 0); } } public class Exp_TestClass_base006_Base { public int intI() { return 1; } } public class base006 : Exp_TestClass_base006_Base { public int TestInt() { return base.intI(); } public static int Main_old() { base006 TC = new base006(); if (TC.TestInt() == 1) { return 0; } else { return 1; } } public static bool testMethod() { return (Main_old() == 0); } } public class Exp_TestClass_base007_Base { public virtual int intI() { return 1; } } public class base007 : Exp_TestClass_base007_Base { override public int intI() { return 2; } public int TestInt() { return base.intI(); } public static int Main_old() { base007 TC = new base007(); if (TC.TestInt() == 1) { return 0; } else { return 1; } } public static bool testMethod() { return (Main_old() == 0); } } public class Exp_TestClass_base009_Base { public int intI() { return 1; } } public class base009 : Exp_TestClass_base009_Base { int TestInt = 0; public base009() { TestInt = base.intI(); } public static int Main_old() { base009 TC = new base009(); if (TC.TestInt == 1) { return 0; } else { return 1; } } public static bool testMethod() { return (Main_old() == 0); } } public class Exp_TestClass_base010_Base { public virtual int intI() { return 1; } } public class base010 : Exp_TestClass_base010_Base { int TestInt = 0; override public int intI() { return 2; } public base010() { TestInt = base.intI(); } public static int Main_old() { base010 TC = new base010(); if (TC.TestInt == 1) { return 0; } else { return 1; } } public static bool testMethod() { return (Main_old() == 0); } } public class Exp_TestClass_base011_Base { public int intI() { return 1; } } public class base011 : Exp_TestClass_base011_Base { int MyInt = 0; public int TestInt { get { MyInt = base.intI(); return 2; } } public static int Main_old() { int Temp; base011 TC = new base011(); Temp = TC.TestInt; if (TC.MyInt == 1) { return 0; } else { return 1; } } public static bool testMethod() { return (Main_old() == 0); } } public class Exp_TestClass_base012_Base { public virtual int intI() { return 1; } } public class base012 : Exp_TestClass_base012_Base { int MyInt = 0; public int TestInt { get { MyInt = base.intI(); return 2; } } override public int intI() { return 2; } public static int Main_old() { int Temp; base012 TC = new base012(); Temp = TC.TestInt; if (TC.MyInt == 1) { return 0; } else { return 1; } } public static bool testMethod() { return (Main_old() == 0); } } public class Exp_TestClass_base013_Base { public int intI() { return 1; } } public class base013 : Exp_TestClass_base013_Base { int MyInt = 0; public int TestInt { set { MyInt = base.intI(); } } public static int Main_old() { base013 TC = new base013(); TC.TestInt = 3; if (TC.MyInt == 1) { return 0; } else { return 1; } } public static bool testMethod() { return (Main_old() == 0); } } public class Exp_TestClass_base014_Base { public virtual int intI() { return 1; } } public class base014 : Exp_TestClass_base014_Base { int MyInt = 0; public int TestInt { set { MyInt = base.intI(); } } override public int intI() { return 2; } public static int Main_old() { base014 TC = new base014(); TC.TestInt = 3; if (TC.MyInt == 1) { return 0; } else { return 1; } } public static bool testMethod() { return (Main_old() == 0); } } public class Exp_TestClass_base015_Base { public int intI = 3; } public class base015 : Exp_TestClass_base015_Base { new int intI = 5; public int TestInt() { return base.intI; } public static int Main_old() { base015 TC = new base015(); if (TC.TestInt() == 3) { return 0; } else { return 1; } } public static bool testMethod() { return (Main_old() == 0); } } public class Exp_TestClass_base016_Base { public int intI { get { return 3; } } } public class base016 : Exp_TestClass_base016_Base { new public int intI { get { return 4; } } public int TestInt() { return base.intI; } public static int Main_old() { base016 TC = new base016(); if (TC.TestInt() == 3) { return 0; } else { return 1; } } public static bool testMethod() { return (Main_old() == 0); } } public struct base017 { override public string ToString() { return "foobar"; } public string GetStr() { return base.ToString(); } public static int Main_old() { base017 TC = new base017(); if (TC.GetStr().Equals("Microsoft.Conformance.Expressions.base017")) { return 0; } else { Microsoft.SPOT.Debug.Print(TC.GetStr()); return 1; } } public static bool testMethod() { return (Main_old() == 0); } } public struct base018 { String TestString; public base018(int IntI) { TestString = null; TestString = base.ToString(); } override public String ToString() { return "foobar"; } public static int Main_old() { base018 TC = new base018(3); if (TC.TestString.Equals("Microsoft.Conformance.Expressions.base018")) { return 0; } else { return 1; } } public static bool testMethod() { return (Main_old() == 0); } } public struct base019 { String TestString; override public String ToString() { return "foobar"; } public int GetInt { get { TestString = base.ToString(); return 1; } } public static int Main_old() { int Temp; base019 TC = new base019(); Temp = TC.GetInt; if (TC.TestString.Equals("Microsoft.Conformance.Expressions.base019")) { return 0; } else { return 1; } } public static bool testMethod() { return (Main_old() == 0); } } public struct base020 { String TestString; override public String ToString() { return "foobar"; } public int SetInt { set { TestString = base.ToString(); } } public static int Main_old() { base020 TC = new base020(); TC.SetInt = 3; if (TC.TestString.Equals("Microsoft.Conformance.Expressions.base020")) { return 0; } else { return 1; } } public static bool testMethod() { return (Main_old() == 0); } } } } namespace Exp_TestClass_mem001_TS { public class Exp_TestClass_mem001_TC { public int TestInt = 2; } } namespace Exp_TestClass_mem002_TS { namespace InnerSpace { public class Exp_TestClass_mem002_TC { public int TestInt = 3; } } } public class Exp_TestClass_ident030_TC { public int TestInt = 1; } namespace NS_ident030_I { public class ident030 { public static int Main_old() { Exp_TestClass_ident030_TC TC = new Exp_TestClass_ident030_TC(); //testing type identifier in enclosing namespace if (TC.TestInt == 1) { return 0; } else { return 1; } } public static bool testMethod() { return (Main_old() == 0); } } } namespace Exp_TestClass_ident031_T { public class Exp_TestClass_ident031_TC { public int TestInt = 1; } } namespace NS_ident031_I { using Exp_TestClass_ident031_T; //testing namespace identifier in enclosing namespace public class ident031 { public static int Main_old() { Exp_TestClass_ident031_TC TC = new Exp_TestClass_ident031_TC(); if (TC.TestInt == 1) { return 0; } else { return 1; } } public static bool testMethod() { return (Main_old() == 0); } } } namespace Exp_TestClass_ident032_T { public class Exp_TestClass_ident032_TC { public int TestInt = 1; } } namespace NS_ident032_I { using Exp_TestClass_ident032_TC = Exp_TestClass_ident032_T.Exp_TestClass_ident032_TC; public class ident032 { public static int Main_old() { Exp_TestClass_ident032_TC TC = new Exp_TestClass_ident032_TC(); //identifier refers to imported type if (TC.TestInt == 1) { return 0; } else { return 1; } } public static bool testMethod() { return (Main_old() == 0); } } } namespace Exp_TestClass_ident033_T { public class Exp_TestClass_ident033_TC { public int TestInt = 1; } } namespace NS_ident033_O { using Exp_TestClass_ident033_TC = Exp_TestClass_ident033_T.Exp_TestClass_ident033_TC; namespace NS_ident033_I { public class ident033 { public static int Main_old() { Exp_TestClass_ident033_TC TC = new Exp_TestClass_ident033_TC(); //identifier refers to imported type if (TC.TestInt == 1) { return 0; } else { return 1; } } public static bool testMethod() { return (Main_old() == 0); } } } } namespace Exp_TestClass_ident034_T { public class Exp_TestClass_ident034_TC { public int TestInt = 1; } } namespace NS_ident034_I { using Exp_TestClass_ident034_T; public class ident034 { public static int Main_old() { Exp_TestClass_ident034_TC TC = new Exp_TestClass_ident034_TC(); //identifier refers to type in imported namespace if (TC.TestInt == 1) { return 0; } else { return 1; } } public static bool testMethod() { return (Main_old() == 0); } } } namespace Exp_TestClass_ident035_T { public class Exp_TestClass_ident035_TC { public int TestInt = 1; } } namespace NS_ident035_O { using Exp_TestClass_ident035_T; namespace NS_ident035_I { public class ident035 { public static int Main_old() { Exp_TestClass_ident035_TC TC = new Exp_TestClass_ident035_TC(); //identifier refers to type in imported namespace if (TC.TestInt == 1) { return 0; } else { return 1; } } public static bool testMethod() { return (Main_old() == 0); } } } } namespace Exp_TestClass_ident038_T { public class Exp_TestClass_ident038_TC { public int TestInt = 1; } } namespace Exp_TestClass_ident038_T2 { public class Exp_TestClass_ident038_TC { public int TestInt = 2; } } namespace NS_ident038_I { using Exp_TestClass_ident038_T; using Exp_TestClass_ident038_TC = Exp_TestClass_ident038_T2.Exp_TestClass_ident038_TC; public class ident038 { public static int Main_old() { Exp_TestClass_ident038_TC TC = new Exp_TestClass_ident038_TC(); //identifier refers to type in imported type if (TC.TestInt == 2) { return 0; } else { return 1; } } public static bool testMethod() { return (Main_old() == 0); } } } namespace Exp_TestClass_ident039_T { public class Exp_TestClass_ident039_TC { public int TestInt = 1; } } namespace Exp_TestClass_ident039_T2 { public class Exp_TestClass_ident039_TC { public int TestInt = 2; } } namespace NS_ident039_O { using Exp_TestClass_ident039_TC = Exp_TestClass_ident039_T2.Exp_TestClass_ident039_TC; using Exp_TestClass_ident039_T; namespace NS_ident039_I { public class ident039 { public static int Main_old() { Exp_TestClass_ident039_TC TC = new Exp_TestClass_ident039_TC(); //identifier refers to type in imported type if (TC.TestInt == 2) { return 0; } else { return 1; } } public static bool testMethod() { return (Main_old() == 0); } } } } namespace Exp_TestClass_ident040_T { public class Exp_TestClass_ident040_TC { public int TestInt = 1; } } namespace NS_ident040_I { using Exp_TestClass_ident040_T; using Exp_TestClass_ident040_TC = Exp_TestClass_ident040_T.Exp_TestClass_ident040_TC; public class ident040 { public static int Main_old() { Exp_TestClass_ident040_TC TC = new Exp_TestClass_ident040_TC(); //identifier refers to type in imported type if (TC.TestInt == 1) { return 0; } else { return 1; } } public static bool testMethod() { return (Main_old() == 0); } } } ================================================ FILE: Zelig/Zelig/Test/RunTime/NETMF/mscorlib/interfaces/InterfaceTests.cs ================================================ //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // Copyright (c) Microsoft Corporation. All rights reserved. //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// using System; using System.Reflection; using Microsoft.Zelig.Test; namespace Microsoft.Zelig.Test { public class InterfaceTests : TestBase, ITestInterface { [SetUp] public InitializeResult Initialize() { Log.Comment("Adding set up for the tests"); return InitializeResult.ReadyToGo; } [TearDown] public void CleanUp() { Log.Comment("Cleaning up after the tests"); } public override TestResult Run(string[] args) { TestResult result = TestResult.Pass; string testName = "Interface_base_"; result |= Assert.CheckFailed(Interface_base_06_Test(), testName, 6); testName = "Interface_decl_"; result |= Assert.CheckFailed(Interface_decl_01_Test(), testName, 1); result |= Assert.CheckFailed(Interface_decl_03_Test(), testName, 3); result |= Assert.CheckFailed(Interface_decl_05_Test(), testName, 5); result |= Assert.CheckFailed(Interface_decl_06_Test(), testName, 6); result |= Assert.CheckFailed(Interface_decl_07_Test(), testName, 7); testName = "Interface_inherit_"; result |= Assert.CheckFailed(Interface_inherit_01_Test(), testName, 1); result |= Assert.CheckFailed(Interface_inherit_02_Test(), testName, 2); result |= Assert.CheckFailed(Interface_inherit_03_Test(), testName, 3); result |= Assert.CheckFailed(Interface_inherit_04_Test(), testName, 4); result |= Assert.CheckFailed(Interface_inherit_08_Test(), testName, 8); testName = "Interface_modifier_"; result |= Assert.CheckFailed(Interface_modifier_01_Test(), testName, 1); result |= Assert.CheckFailed(Interface_modifier_02_Test(), testName, 2); result |= Assert.CheckFailed(Interface_modifier_03_Test(), testName, 3); result |= Assert.CheckFailed(Interface_modifier_05_Test(), testName, 5); result |= Assert.CheckFailed(Interface_modifier_06_Test(), testName, 6); result |= Assert.CheckFailed(Interface_modifier_07_Test(), testName, 7); result |= Assert.CheckFailed(Interface_modifier_08_Test(), testName, 8); result |= Assert.CheckFailed(Interface_modifier_10_Test(), testName, 10); testName = "Interface_semicolon_"; result |= Assert.CheckFailed(Interface_semicolon_01_Test(), testName, 1); result |= Assert.CheckFailed(Interface_semicolon_03_Test(), testName, 3); testName = "Interface_impl_"; result |= Assert.CheckFailed(Interface_impl_04_Test(), testName, 4); result |= Assert.CheckFailed(Interface_impl_05_Test(), testName, 5); result |= Assert.CheckFailed(Interface_impl_06_Test(), testName, 6); result |= Assert.CheckFailed(Interface_impl_07_Test(), testName, 7); result |= Assert.CheckFailed(Interface_impl_08_Test(), testName, 8); result |= Assert.CheckFailed(Interface_impl_09_Test(), testName, 9); result |= Assert.CheckFailed(Interface_impl_10_Test(), testName, 10); result |= Assert.CheckFailed(Interface_impl_11_Test(), testName, 11); result |= Assert.CheckFailed(Interface_impl_12_Test(), testName, 12); result |= Assert.CheckFailed(Interface_impl_13_Test(), testName, 13); testName = "Interface_implinherit_"; result |= Assert.CheckFailed(Interface_implinherit_01_Test(), testName, 1); result |= Assert.CheckFailed(Interface_implinherit_02_Test(), testName, 2); testName = "Interface_explicit_"; result |= Assert.CheckFailed(Interface_explicit_04_Test(), testName, 4); result |= Assert.CheckFailed(Interface_explicit_05_Test(), testName, 5); result |= Assert.CheckFailed(Interface_explicit_06_Test(), testName, 6); result |= Assert.CheckFailed(Interface_explicit_07_Test(), testName, 7); result |= Assert.CheckFailed(Interface_explicit_10_Test(), testName, 10); result |= Assert.CheckFailed(Interface_explicit_11_Test(), testName, 11); result |= Assert.CheckFailed(Interface_explicit_12_Test(), testName, 12); result |= Assert.CheckFailed(Interface_explicit_13_Test(), testName, 13); result |= Assert.CheckFailed(Interface_explicit_21_Test(), testName, 21); result |= Assert.CheckFailed(Interface_explicit_25_Test(), testName, 25); testName = "Interface_mdfrmeth_"; result |= Assert.CheckFailed(Interface_mdfrmeth_09_Test(), testName, 9); testName = "Interface_ifreimp_"; result |= Assert.CheckFailed(Interface_ifreimp_01_Test(), testName, 1); result |= Assert.CheckFailed(Interface_ifreimp_02_Test(), testName, 2); result |= Assert.CheckFailed(Interface_ifreimp_03_Test(), testName, 3); testName = "Interface_abstract_"; result |= Assert.CheckFailed(Interface_abstract_01_Test(), testName, 1); result |= Assert.CheckFailed(Interface_abstract_02_Test(), testName, 2); result |= Assert.CheckFailed(Interface_abstract_03_Test(), testName, 3); testName = "Interface_indexer_"; result |= Assert.CheckFailed(Interface_indexer_02_Test(), testName, 2); result |= Assert.CheckFailed(Interface_indexer_03_Test(), testName, 3); result |= Assert.CheckFailed(Interface_indexer_04_Test(), testName, 4); result |= Assert.CheckFailed(Interface_indexer_05_Test(), testName, 5); result |= Assert.CheckFailed(Interface_indexer_06_Test(), testName, 6); result |= Assert.CheckFailed(Interface_indexer_07_Test(), testName, 7); result |= Assert.CheckFailed(Interface_indexer_18_Test(), testName, 18); testName = "Interface_meth_"; result |= Assert.CheckFailed(Interface_meth_09_Test(), testName, 9); testName = "Interface_prop_"; result |= Assert.CheckFailed(Interface_prop_09_Test(), testName, 9); testName = "Interface_namesig_"; result |= Assert.CheckFailed(Interface_namesig_02_Test(), testName, 2); result |= Assert.CheckFailed(Interface_namesig_03_Test(), testName, 3); result |= Assert.CheckFailed(Interface_namesig_04_Test(), testName, 4); result |= Assert.CheckFailed(Interface_namesig_05_Test(), testName, 5); testName = "Interface_events_"; result |= Assert.CheckFailed(Interface_events_08_Test(), testName, 8); result |= Assert.CheckFailed(Interface_events_09_Test(), testName, 9); testName = "Interface_maccess_"; result |= Assert.CheckFailed(Interface_maccess_01_Test(), testName, 1); result |= Assert.CheckFailed(Interface_maccess_03_Test(), testName, 3); result |= Assert.CheckFailed(Interface_maccess_04_Test(), testName, 4); testName = "Interface_modifier_"; result |= Assert.CheckFailed(Interface_modifier_02_Test(), testName, 2); result |= Assert.CheckFailed(Interface_modifier_03_Test(), testName, 3); testName = "Interface_struct_impl_"; result |= Assert.CheckFailed(Interface_struct_impl_01_Test(), testName, 1); result |= Assert.CheckFailed(Interface_struct_impl_02_Test(), testName, 2); result |= Assert.CheckFailed(Interface_struct_impl_04_Test(), testName, 4); result |= Assert.CheckFailed(Interface_struct_impl_05_Test(), testName, 5); result |= Assert.CheckFailed(Interface_struct_impl_06_Test(), testName, 6); result |= Assert.CheckFailed(Interface_struct_impl_07_Test(), testName, 7); result |= Assert.CheckFailed(Interface_struct_impl_08_Test(), testName, 8); result |= Assert.CheckFailed(Interface_struct_impl_09_Test(), testName, 9); testName = "Interface_struct_explicit_"; result |= Assert.CheckFailed(Interface_struct_explicit_01_Test(), testName, 1); result |= Assert.CheckFailed(Interface_struct_explicit_03_Test(), testName, 3); result |= Assert.CheckFailed(Interface_struct_explicit_04_Test(), testName, 4); result |= Assert.CheckFailed(Interface_struct_explicit_05_Test(), testName, 5); result |= Assert.CheckFailed(Interface_struct_explicit_06_Test(), testName, 6); result |= Assert.CheckFailed(Interface_struct_explicit_07_Test(), testName, 7); result |= Assert.CheckFailed(Interface_struct_explicit_09_Test(), testName, 9); result |= Assert.CheckFailed(Interface_struct_explicit_10_Test(), testName, 10); result |= Assert.CheckFailed(Interface_struct_explicit_11_Test(), testName, 11); result |= Assert.CheckFailed(Interface_struct_explicit_12_Test(), testName, 12); result |= Assert.CheckFailed(Interface_struct_explicit_13_Test(), testName, 13); result |= Assert.CheckFailed(Interface_struct_explicit_19_Test(), testName, 19); result |= Assert.CheckFailed(Interface_struct_explicit_20_Test(), testName, 20); testName = "Interface_struct_decl_"; result |= Assert.CheckFailed(Interface_struct_decl_01_Test(), testName, 1); result |= Assert.CheckFailed(Interface_struct_decl_02_Test(), testName, 2); testName = "Interface_struct_inherit_"; result |= Assert.CheckFailed(Interface_struct_inherit_01_Test(), testName, 1); testName = "Interface_struct_modifier_"; result |= Assert.CheckFailed(Interface_struct_modifier_01_Test(), testName, 1); result |= Assert.CheckFailed(Interface_struct_modifier_02_Test(), testName, 2); result |= Assert.CheckFailed(Interface_struct_modifier_03_Test(), testName, 3); testName = "Interface_struct_semicolon_"; result |= Assert.CheckFailed(Interface_struct_semicolon_01_Test(), testName, 1); result |= Assert.CheckFailed(Interface_struct_semicolon_02_Test(), testName, 2); return result; } //Test Case Calls [TestMethod] public TestResult Interface_base_06_Test() { Log.Comment("Section 13.1 Interface declarations "); Log.Comment("If effective visibility is internal, public iface may have an internal base iface "); Log.Comment("(Bug 86453: has some details on this. But it has to do with class internal)"); if (Interface_TestClass_base_06.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Interface_decl_01_Test() { Log.Comment("Section 13.1 Interface declarations "); Log.Comment("Simplest interface declared in global namespace"); if (Interface_TestClass_decl_01.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Interface_decl_03_Test() { Log.Comment("Section 13.1 Interface declarations "); Log.Comment("Simplest interface declared in class in default global namespace"); if (Interface_TestClass_decl_03.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Interface_decl_05_Test() { Log.Comment("Section 13.1 Interface declarations "); Log.Comment("Simple interface declaration with diff types of methods, args, and properties"); if (Interface_TestClass_decl_05.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Interface_decl_06_Test() { Log.Comment("Section 13.1 Interface declarations "); Log.Comment("Simple interface declaration properties with only gets"); if (Interface_TestClass_decl_06.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Interface_decl_07_Test() { Log.Comment("Section 13.1 Interface declarations "); Log.Comment("Simple interface declaration properties with only sets"); if (Interface_TestClass_decl_07.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Interface_inherit_01_Test() { Log.Comment("Section 13.1 Interface declarations "); Log.Comment("Verify that an interface can be hidden by 'new' member in derived class"); if (Interface_TestClass_inherit_01.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Interface_inherit_02_Test() { Log.Comment("Section 13.1 Interface declarations "); Log.Comment("Simplest form of interface inheritance"); if (Interface_TestClass_inherit_02.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Interface_inherit_03_Test() { Log.Comment("Section 13.1 Interface declarations "); Log.Comment("Simplest form of interface inheritance, inheriting multiple interfaces"); if (Interface_TestClass_inherit_03.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Interface_inherit_04_Test() { Log.Comment("Section 13.1 Interface declarations "); Log.Comment("Simplest form of interface inheritance, inheriting multiple interfaces"); if (Interface_TestClass_inherit_04.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Interface_inherit_08_Test() { Log.Comment("Section 13.1 Interface declarations "); Log.Comment("Verify that an interface hidden without using new results in warning"); if (Interface_TestClass_inherit_08.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Interface_modifier_01_Test() { Log.Comment("Section 13.1 Interface declarations "); Log.Comment("Verify public and internal interfaces declared in global namespace are valid"); if (Interface_TestClass_modifier_01.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Interface_modifier_05_Test() { Log.Comment("Section 13.1 Interface declarations "); Log.Comment("Verify public and internal interfaces are valid inside classes"); if (Interface_TestClass_modifier_05.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Interface_modifier_06_Test() { Log.Comment("Section 13.1 Interface declarations "); Log.Comment("Verify private and protected interfaces are valid inside classes"); if (Interface_TestClass_modifier_06.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Interface_modifier_07_Test() { Log.Comment("Section 13.1 Interface declarations "); Log.Comment("Verify new interface gens warning if not hiding anything"); if (Interface_TestClass_modifier_07.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Interface_modifier_08_Test() { Log.Comment("Section 13.1 Interface declarations "); Log.Comment("Verify new interface is valid inside classes when properly hiding an inherited member"); if (Interface_TestClass_modifier_08.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Interface_modifier_10_Test() { Log.Comment("Section 13.1 Interface declarations "); Log.Comment("Verify protected internal interfaces are valid inside classes"); if (Interface_TestClass_modifier_10.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Interface_semicolon_01_Test() { Log.Comment("Section 13.1 Interface declarations "); Log.Comment("Simplest interface declared (with semi-colon) in global namespace"); if (Interface_TestClass_semicolon_01.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Interface_semicolon_03_Test() { Log.Comment("Section 13.1 Interface declarations "); Log.Comment("Simplest interface declared (with semi-colon) in class in default global namespace"); if (Interface_TestClass_semicolon_03.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Interface_impl_04_Test() { Log.Comment("Section 13.4 Interface implementations"); Log.Comment("A member of an interface-type can be assigned an instance of class that implements it"); if (Interface_TestClass_impl_04.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Interface_impl_05_Test() { Log.Comment("Section 13.4 Interface implementations"); Log.Comment("Warning gets generated when two methods implement an inherited method"); if (Interface_TestClass_impl_05.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Interface_impl_06_Test() { Log.Comment("Section 13.4 Interface implementations"); Log.Comment("Using the 'override' keyword allows you to hide previous method implementation"); if (Interface_TestClass_impl_06.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Interface_impl_07_Test() { Log.Comment("Section 13.4 Interface implementations"); Log.Comment("A class that implements an interface with method, property, event, and indexer"); if (Interface_TestClass_impl_07.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Interface_impl_08_Test() { Log.Comment("Section 13.4 Interface implementations"); Log.Comment("Implementing method that was defined identically by two different base-interfaces should work"); if (Interface_TestClass_impl_08.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Interface_impl_09_Test() { Log.Comment("Section 13.4 Interface implementations"); Log.Comment("Implementing property that was defined identically by two different base-interfaces should work"); if (Interface_TestClass_impl_09.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Interface_impl_10_Test() { Log.Comment("Section 13.4 Interface implementations"); Log.Comment("Implementing an event that was defined identically by two different base-interfaces should work"); if (Interface_TestClass_impl_10.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Interface_impl_11_Test() { Log.Comment("Section 13.4 Interface implementations"); Log.Comment("Implementing an indexer that was defined identically by two different base-interfaces should work"); if (Interface_TestClass_impl_11.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Interface_impl_12_Test() { Log.Comment("Section 13.4 Interface implementations"); Log.Comment("The members of base class participate in interface mapping"); if (Interface_TestClass_impl_12.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Interface_impl_13_Test() { Log.Comment("Section 13.4 Interface implementations"); Log.Comment("Two interfaces on the same object must resolve to the same reference"); if (Interface_TestClass_impl_13.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Interface_implinherit_01_Test() { Log.Comment("Section 13.4 Interface implementations"); Log.Comment("Interface methods implementation inheritance map as expected (1st/2nd example in 13.4.3)"); if (Interface_TestClass_implinherit_01.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Interface_implinherit_02_Test() { Log.Comment("Section 13.4 Interface implementations"); Log.Comment("Interface methods implementation inheritance (w/virtual) map as expected (3rd/4th example in 13.4.3)"); if (Interface_TestClass_implinherit_02.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Interface_explicit_04_Test() { Log.Comment("Section 13.4 Interface implementations"); Log.Comment("Explicit interface member implementation of a method"); if (Interface_TestClass_explicit_04.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Interface_explicit_05_Test() { Log.Comment("Section 13.4 Interface implementations"); Log.Comment("Explicit interface member implementation of a property"); if (Interface_TestClass_explicit_05.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Interface_explicit_06_Test() { Log.Comment("Section 13.4 Interface implementations"); Log.Comment("Explicit interface member implementation of an event (Bug 89766)"); if (Interface_TestClass_explicit_06.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Interface_explicit_07_Test() { Log.Comment("Section 13.4 Interface implementations"); Log.Comment("Explicit interface member implementation of an indexer"); if (Interface_TestClass_explicit_07.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Interface_explicit_10_Test() { Log.Comment("Section 13.4 Interface implementations"); Log.Comment("Explicitly implemented members (method) can be called through interface instances"); if (Interface_TestClass_explicit_10.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Interface_explicit_11_Test() { Log.Comment("Section 13.4 Interface implementations"); Log.Comment("Explicitly implemented members (property) can be called through interface instances"); if (Interface_TestClass_explicit_11.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Interface_explicit_12_Test() { Log.Comment("Section 13.4 Interface implementations"); Log.Comment("Explicitly implemented members (indexer) can be called through interface instances"); if (Interface_TestClass_explicit_12.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Interface_explicit_13_Test() { Log.Comment("Section 13.4 Interface implementations"); Log.Comment("Explicitly implemented members (event) can be called through interface instances (Bug 89766)"); if (Interface_TestClass_explicit_13.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Interface_explicit_21_Test() { Log.Comment("Section 13.4 Interface implementations"); Log.Comment("Hidden base interface members may be implemented in all of the ways used in this"); if (Interface_TestClass_explicit_21.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Interface_explicit_25_Test() { Log.Comment("Section 13.4 Interface implementations"); Log.Comment("Explicitly implementing overloaded methods should work "); if (Interface_TestClass_explicit_25.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Interface_mdfrmeth_09_Test() { Log.Comment("Section 13.4 Interface implementations"); Log.Comment("An abstract class can implement an interface's methods as abstract"); if (Interface_TestClass_mdfrmeth_09.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Interface_ifreimp_01_Test() { Log.Comment("Section 13.4 Interface implementations"); Log.Comment("A class that inherits an interface implementation is permitted to re-implement the interface by including it in the base class list"); if (Interface_TestClass_ifreimp_01.testMethod()) { return TestResult.Pass; } else { Log.Comment("This in a known bug captured in Issue #95"); return TestResult.KnownFailure; } } [TestMethod] public TestResult Interface_ifreimp_02_Test() { Log.Comment("Section 13.4 Interface implementations"); Log.Comment("Inherited public member declarations and inherited explicit interface member declarations participate in the interface mapping process for re-implemented interfaces (Bug 90165)"); if (Interface_TestClass_ifreimp_02.testMethod()) { return TestResult.Pass; } else { Log.Comment("This in a known bug captured in Issue #95"); return TestResult.KnownFailure; } } [TestMethod] public TestResult Interface_ifreimp_03_Test() { Log.Comment("Section 13.4 Interface implementations"); Log.Comment("Interface reimplementation also reimplements the interface's base interfaces. Verify mapping is done correctly. (90165)"); Log.Comment("This Test is an expected fail in the baseline, but has passed in recent testing"); if (Interface_TestClass_ifreimp_03.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Interface_abstract_01_Test() { Log.Comment("Section 13.4 Interface implementations"); Log.Comment("An abstract class is permitted to map base-interface methods onto abstract methods"); if (Interface_TestClass_abstract_01.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Interface_abstract_02_Test() { Log.Comment("Section 13.4 Interface implementations"); Log.Comment("The abstract methods implementing interface methods must be overridden by inheriting classes"); if (Interface_TestClass_abstract_02.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Interface_abstract_03_Test() { Log.Comment("Section 13.4 Interface implementations"); Log.Comment("Explicit interface member implementations are permitted to call abstract methods"); if (Interface_TestClass_abstract_03.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Interface_indexer_02_Test() { Log.Comment("Section 13.2 Interface members"); Log.Comment("Simplest interface indexer declaration (int)"); if (Interface_TestClass_indexer_02.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Interface_indexer_03_Test() { Log.Comment("Section 13.2 Interface members"); Log.Comment("Simplest interface indexer declaration (String)"); if (Interface_TestClass_indexer_03.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Interface_indexer_04_Test() { Log.Comment("Section 13.2 Interface members"); Log.Comment("Simplest interface indexer declaration (user-defined struct)"); if (Interface_TestClass_indexer_04.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Interface_indexer_05_Test() { Log.Comment("Section 13.2 Interface members"); Log.Comment("Interface indexer with multiple parameters in formal-index-parameter-list"); if (Interface_TestClass_indexer_05.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Interface_indexer_06_Test() { Log.Comment("Section 13.2 Interface members"); Log.Comment("Interface indexer with just get accessor"); if (Interface_TestClass_indexer_06.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Interface_indexer_07_Test() { Log.Comment("Section 13.2 Interface members"); Log.Comment("Interface indexer with just set accessor"); if (Interface_TestClass_indexer_07.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Interface_indexer_18_Test() { Log.Comment("Section 13.2 Interface members"); Log.Comment("Using 'new' on an interface member (indexer) that doesn't hide an inherited member should gen warning "); Log.Comment("(Related Bug: 86609)"); if (Interface_TestClass_indexer_18.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Interface_meth_09_Test() { Log.Comment("Section 13.2 Interface members"); Log.Comment("Using 'new' on an interface member (method) that doesn't hide an inherited member should gen warning (Bug: 86609)"); if (Interface_TestClass_meth_09.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Interface_prop_09_Test() { Log.Comment("Section 13.2 Interface members"); Log.Comment("Using 'new' on an interface member (property) that doesn't hide an inherited member should gen warning (Bug: 86609)"); if (Interface_TestClass_prop_09.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Interface_namesig_02_Test() { Log.Comment("Section 13.2 Interface members"); Log.Comment("Member functions of an interface may have same name if they have diff args"); if (Interface_TestClass_namesig_02.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Interface_namesig_03_Test() { Log.Comment("Section 13.2 Interface members"); Log.Comment("Interface member that is hidden by an inheriting interface (without using new) gens warning"); if (Interface_TestClass_namesig_03.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Interface_namesig_04_Test() { Log.Comment("Section 13.2 Interface members"); Log.Comment("Interface that inherits 2 other interfaces that have a member with same sig"); if (Interface_TestClass_namesig_04.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Interface_namesig_05_Test() { Log.Comment("Section 13.2 Interface members"); Log.Comment("Interface member that is hidden by an inheriting interface (using new) works correctly"); if (Interface_TestClass_namesig_05.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Interface_events_08_Test() { Log.Comment("Section 13.2 Interface members"); Log.Comment("Using 'new' on an interface member (event) that doesn't hide an inherited member should gen warning (Bug: 118831)"); if (Interface_TestClass_events_08.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Interface_events_09_Test() { Log.Comment("Section 13.2 Interface members"); Log.Comment("Simple Event declaration within an interface"); if (Interface_TestClass_events_09.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Interface_maccess_01_Test() { Log.Comment("Section 13.2 Interface members"); Log.Comment("Inherited members with same sig, from diff interfaces, can be accessed through casting"); if (Interface_TestClass_maccess_01.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Interface_maccess_03_Test() { Log.Comment("Section 13.2 Interface members"); Log.Comment("Inherited members with same method names but diff args can be accessed by casting"); if (Interface_TestClass_maccess_03.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Interface_maccess_04_Test() { Log.Comment("Section 13.2 Interface members"); Log.Comment("Inherited members with same method names but diff args should work if arg passed is not ambiguous (Regression bug: 90867)"); if (Interface_TestClass_maccess_04.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Interface_modifier_02_Test() { Log.Comment("Section 13.1 Interface declarations "); Log.Comment("Verify private interfaces gen error when declared in global namespace"); if (Interface_TestClass_modifier_02.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Interface_modifier_03_Test() { Log.Comment("Section 13.1 Interface declarations "); Log.Comment("Verify protected interfaces gen error when declared in global namespace"); if (Interface_TestClass_modifier_03.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } //Test Case Calls [TestMethod] public TestResult Interface_struct_impl_01_Test() { Log.Comment("Section 13.4 Interface implementations"); Log.Comment("Simple struct implementation of two interfaces"); if (Interface_TestClass_struct_impl_01.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Interface_struct_impl_02_Test() { Log.Comment("Section 13.4 Interface implementations"); Log.Comment("A struct that implements an interface also implicitly implements all of the interface's base interfaces"); if (Interface_TestClass_struct_impl_02.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Interface_struct_impl_04_Test() { Log.Comment("Section 13.4 Interface implementations"); Log.Comment("A member of an interface-type can be assigned an instance of a struct that implements it"); if (Interface_TestClass_struct_impl_04.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Interface_struct_impl_05_Test() { Log.Comment("Section 13.4 Interface implementations"); Log.Comment("A struct that implements an interface with a method, property, event, and indexer"); if (Interface_TestClass_struct_impl_05.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Interface_struct_impl_06_Test() { Log.Comment("Section 13.4 Interface implementations"); Log.Comment("Implementing a method that was defined identically by two different base-interfaces should work"); if (Interface_TestClass_struct_impl_06.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Interface_struct_impl_07_Test() { Log.Comment("Section 13.4 Interface implementations"); Log.Comment("Implementing a property that was defined identically by two different base-interfaces should work"); if (Interface_TestClass_struct_impl_07.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Interface_struct_impl_08_Test() { Log.Comment("Section 13.4 Interface implementations"); Log.Comment("Implementing an event that was defined identically by two different base-interfaces should work"); if (Interface_TestClass_struct_impl_08.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Interface_struct_impl_09_Test() { Log.Comment("Section 13.4 Interface implementations"); Log.Comment("Implementing an indexer that was defined identically by two different base-interfaces should work"); if (Interface_TestClass_struct_impl_09.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Interface_struct_explicit_01_Test() { Log.Comment("Section 13.4 Interface implementations"); Log.Comment("Explicit interface member implementations"); if (Interface_TestClass_struct_explicit_01.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Interface_struct_explicit_03_Test() { Log.Comment("Section 13.4 Interface implementations"); Log.Comment("Implementing an iface method in a struct that doesn't list the iface as a base iface but does list a iface that inherits the iface should work"); if (Interface_TestClass_struct_explicit_03.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Interface_struct_explicit_04_Test() { Log.Comment("Section 13.4 Interface implementations"); Log.Comment("Explicit interface member implementation of a method"); if (Interface_TestClass_struct_explicit_04.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Interface_struct_explicit_05_Test() { Log.Comment("Section 13.4 Interface implementations"); Log.Comment("Explicit interface member implementation of a property"); if (Interface_TestClass_struct_explicit_05.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Interface_struct_explicit_06_Test() { Log.Comment("Section 13.4 Interface implementations"); Log.Comment("Explicit interface member implementation of an event (Bug: 89766)"); if (Interface_TestClass_struct_explicit_06.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Interface_struct_explicit_07_Test() { Log.Comment("Section 13.4 Interface implementations"); Log.Comment("Explicit interface member implementation of an indexer"); if (Interface_TestClass_struct_explicit_07.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Interface_struct_explicit_09_Test() { Log.Comment("Section 13.4 Interface implementations"); Log.Comment("Multiple base interfaces and explicit interface member implementations work"); if (Interface_TestClass_struct_explicit_09.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Interface_struct_explicit_10_Test() { Log.Comment("Section 13.4 Interface implementations"); Log.Comment("Explicitly implemented members (method) can be called through interface instances"); if (Interface_TestClass_struct_explicit_10.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Interface_struct_explicit_11_Test() { Log.Comment("Section 13.4 Interface implementations"); Log.Comment("Explicitly implemented members (property) can be called through interface instances (Bug 90570)"); if (Interface_TestClass_struct_explicit_11.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Interface_struct_explicit_12_Test() { Log.Comment("Section 13.4 Interface implementations"); Log.Comment("Explicitly implemented members (indexer) can be called through interface instances (Bug 90570)"); if (Interface_TestClass_struct_explicit_12.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Interface_struct_explicit_13_Test() { Log.Comment("Section 13.4 Interface implementations"); Log.Comment("Explicitly implemented members (event) can be called through interface instances (89766)"); if (Interface_TestClass_struct_explicit_13.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Interface_struct_explicit_19_Test() { Log.Comment("Section 13.4 Interface implementations"); Log.Comment("Explicitly implementing member from interface not in base-list (but in base-list of a base interface) should work"); if (Interface_TestClass_struct_explicit_19.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Interface_struct_explicit_20_Test() { Log.Comment("Section 13.4 Interface implementations"); Log.Comment("Hidden base interface members may be implemented in all of the ways used in this"); if (Interface_TestClass_struct_explicit_20.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Interface_struct_decl_01_Test() { Log.Comment("Section 13.1 Interface declarations "); Log.Comment("Simplest interface declared in a struct in default global namespace"); if (Interface_TestClass_struct_decl_01.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Interface_struct_decl_02_Test() { Log.Comment("Section 13.1 Interface declarations "); Log.Comment("Simplest interface declared in a struct in a declared namespace"); if (Interface_TestClass_decl_02_NS.Interface_TestClass_decl_02.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Interface_struct_inherit_01_Test() { Log.Comment("Section 13.1 Interface declarations "); Log.Comment("Simplest form of interface inheritance, inheriting multiple interfaces"); if (Interface_TestClass_struct_inherit_01.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Interface_struct_modifier_01_Test() { Log.Comment("Section 13.1 Interface declarations "); Log.Comment("Verify public and internal interfaces are valid inside structs"); if (Interface_TestClass_struct_modifier_01.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Interface_struct_modifier_02_Test() { Log.Comment("Section 13.1 Interface declarations "); Log.Comment("Verify private interfaces are valid inside structs"); if (Interface_TestClass_struct_modifier_02.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Interface_struct_modifier_03_Test() { Log.Comment("Section 13.1 Interface declarations "); Log.Comment("Verify new interface gens warning if not hiding anything"); if (Interface_TestClass_struct_modifier_03.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Interface_struct_semicolon_01_Test() { Log.Comment("Section 13.1 Interface declarations "); Log.Comment("Simplest interface declared (with semi-colon) in a struct in default global namespace"); if (Interface_TestClass_struct_semicolon_01.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Interface_struct_semicolon_02_Test() { Log.Comment("Section 13.1 Interface declarations "); Log.Comment("Simplest interface declared (with semi-colon) in a struct in a declared namespace"); if (Interface_TestClass_semicolon_02_NS.Interface_TestClass_semicolon_02.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } //Compiled Test Cases class Interface_TestClass_base_06 { internal interface Interface_TestClass_base_06_I { } public interface Interface_TestClass_base_06_2 : Interface_TestClass_base_06_I { } public static void Main_old() { } public static bool testMethod() { Main_old(); return true; } } interface Interface_TestClass_decl_01_I { }; class Interface_TestClass_decl_01 { public static void Main_old() { Log.Comment("This works!"); } public static bool testMethod() { Main_old(); return true; } } class Interface_TestClass_decl_03 { interface Interface_TestClass_decl_03_I { } public static void Main_old() { Log.Comment("This works!"); } public static bool testMethod() { Main_old(); return true; } } interface Interface_TestClass_decl_05_1 { // methods returning various different types void meth1(); int meth2(); double meth3(); bool meth4(); char meth5(); String meth6(); float meth7(); // methods accepting various different types as arguments void arg1(int x); void arg2(double x); void arg3(bool x); void arg4(char x); void arg5(String x); void arg6(float x); // properties of various different types int typ1 { get; set; } double typ2 { get; set; } bool typ3 { get; set; } char typ4 { get; set; } String typ5 { get; set; } float typ6 { get; set; } } class Interface_TestClass_decl_05 { public static void Main_old() { } public static bool testMethod() { Main_old(); return true; } } interface Interface_TestClass_decl_06_1 { // properties of various different types int typ1 { get; } double typ2 { get; } bool typ3 { get; } char typ4 { get; } String typ5 { get; } float typ6 { get; } } class Interface_TestClass_decl_06 { public static void Main_old() { } public static bool testMethod() { Main_old(); return true; } } interface Interface_TestClass_decl_07_1 { // properties of various different types int typ1 { set; } double typ2 { set; } bool typ3 { set; } char typ4 { set; } String typ5 { set; } float typ6 { set; } } class Interface_TestClass_decl_07 { public static void Main_old() { } public static bool testMethod() { Main_old(); return true; } } class Interface_TestClass_inherit_01_1 { public interface m { } } class Interface_TestClass_inherit_01 : Interface_TestClass_inherit_01_1 { new void m() { } public static void Main_old() { } public static bool testMethod() { Main_old(); return true; } } interface Interface_TestClass_inherit_02_I { } interface Interface_TestClass_inherit_02_2 : Interface_TestClass_inherit_02_I { } class Interface_TestClass_inherit_02 { public static void Main_old() { } public static bool testMethod() { Main_old(); return true; } } interface Interface_TestClass_inherit_03_A { } interface Interface_TestClass_inherit_03_B { } interface Interface_TestClass_inherit_03_C { } interface Interface_TestClass_inherit_03_D : Interface_TestClass_inherit_03_A, Interface_TestClass_inherit_03_B, Interface_TestClass_inherit_03_C { } class Interface_TestClass_inherit_03 { public static void Main_old() { } public static bool testMethod() { Main_old(); return true; } } interface Interface_TestClass_inherit_04_A { void m(); } interface Interface_TestClass_inherit_04_B : Interface_TestClass_inherit_04_A { } interface Interface_TestClass_inherit_04_C : Interface_TestClass_inherit_04_B { } class Interface_TestClass_inherit_04 : Interface_TestClass_inherit_04_C { public void m() { Log.Comment("This works!"); } public static void Main_old() { Interface_TestClass_inherit_04 Interface_TestClass_inherit_04_1 = new Interface_TestClass_inherit_04(); Interface_TestClass_inherit_04_1.m(); } public static bool testMethod() { Main_old(); return true; } } class Interface_TestClass_inherit_08_1 { public interface m { } } class Interface_TestClass_inherit_08 : Interface_TestClass_inherit_08_1 { void m() { } public static void Main_old() { } public static bool testMethod() { Main_old(); return true; } } public interface Interface_TestClass_modifier_01_I { } internal interface Interface_TestClass_modifier_01_I2 { } class Interface_TestClass_modifier_01 { public static void Main_old() { } public static bool testMethod() { Main_old(); return true; } } class Interface_TestClass_modifier_05 { public interface Interface_TestClass_modifier_05_I { } internal interface Interface_TestClass_modifier_05_I2 { } public static void Main_old() { } public static bool testMethod() { Main_old(); return true; } } class Interface_TestClass_modifier_06 { private interface Interface_TestClass_modifier_06_I { } protected interface Interface_TestClass_modifier_06_I2 { } public static void Main_old() { } public static bool testMethod() { Main_old(); return true; } } class Interface_TestClass_modifier_07 { new interface Interface_TestClass_modifier_07_I { } public static void Main_old() { } public static bool testMethod() { Main_old(); return true; } } class Interface_TestClass_modifier_08_1 { public void m() { } } class Interface_TestClass_modifier_08 : Interface_TestClass_modifier_08_1 { new interface m { } public static void Main_old() { } public static bool testMethod() { Main_old(); return true; } } class Interface_TestClass_modifier_10 { protected internal interface Interface_TestClass_modifier_10_I { } public static void Main_old() { } public static bool testMethod() { Main_old(); return true; } } interface Interface_TestClass_semicolon_01_I { }; class Interface_TestClass_semicolon_01 { public static void Main_old() { Log.Comment("This works!"); } public static bool testMethod() { Main_old(); return true; } } class Interface_TestClass_semicolon_03 { interface Interface_TestClass_semicolon_03_I { }; public static void Main_old() { Log.Comment("This works!"); } public static bool testMethod() { Main_old(); return true; } } /* public class Interface_TestClass_implbyinherit_01b_1 : Interface_TestClass_implbyinherit_01b_2, Interface_TestClass_implbyinherit_01b_I1 { public static void Main_old() { } public static bool testMethod() { Main_old(); return true; } }*/ interface Interface_TestClass_impl_01_I1 { void F(); } interface Interface_TestClass_impl_01_I2 { void G(); } class Interface_TestClass_impl_01_1 : Interface_TestClass_impl_01_I1, Interface_TestClass_impl_01_I2 { public void F() { } public void G() { } public static void Main_old() { } public static bool testMethod() { Main_old(); return true; } } interface Interface_TestClass_impl_02_I2 { void Interface_TestClass_impl_02_B(); } interface Interface_TestClass_impl_02_I3 : Interface_TestClass_impl_02_I2 { void Interface_TestClass_impl_02_D(); } class Interface_TestClass_impl_02_1 : Interface_TestClass_impl_02_I3 { public void Interface_TestClass_impl_02_B() { } public void Interface_TestClass_impl_02_D() { } public static void Main_old() { } public static bool testMethod() { Main_old(); return true; } } interface Interface_TestClass_impl_04_I1 { void F(); } class Interface_TestClass_impl_04_C : Interface_TestClass_impl_04_I1 { public void F() { Log.Comment("Interface_TestClass_impl_04_C.F()"); } } class Interface_TestClass_impl_04 { public static void Main_old() { Interface_TestClass_impl_04_C cc = new Interface_TestClass_impl_04_C(); Interface_TestClass_impl_04_I1 ic = cc; cc.F(); ic.F(); } public static bool testMethod() { Main_old(); return true; } } interface Interface_TestClass_impl_05_I1 { void F(); } class Interface_TestClass_impl_05_C : Interface_TestClass_impl_05_I1 { public void F() { Log.Comment("Interface_TestClass_impl_05_C.F()"); } } class Interface_TestClass_impl_05_D : Interface_TestClass_impl_05_C { public void F() { Log.Comment("Interface_TestClass_impl_05_D.F()"); } } class Interface_TestClass_impl_05 { public static void Main_old() { Interface_TestClass_impl_05_C cc = new Interface_TestClass_impl_05_C(); Interface_TestClass_impl_05_D cd = new Interface_TestClass_impl_05_D(); Interface_TestClass_impl_05_I1 ic = cc; Interface_TestClass_impl_05_I1 id = cd; cc.F(); ic.F(); id.F(); } public static bool testMethod() { Main_old(); return true; } } interface Interface_TestClass_impl_06_I1 { void F(); } class Interface_TestClass_impl_06_C : Interface_TestClass_impl_06_I1 { public virtual void F() { Log.Comment("Interface_TestClass_impl_06_C.F()"); } } class Interface_TestClass_impl_06_D : Interface_TestClass_impl_06_C { public override void F() { Log.Comment("Interface_TestClass_impl_06_D.F()"); } } class Interface_TestClass_impl_06 { public static void Main_old() { Interface_TestClass_impl_06_C cc = new Interface_TestClass_impl_06_C(); Interface_TestClass_impl_06_D cd = new Interface_TestClass_impl_06_D(); Interface_TestClass_impl_06_I1 ic = cc; Interface_TestClass_impl_06_I1 id = cd; cc.F(); ic.F(); id.F(); } public static bool testMethod() { Main_old(); return true; } } public delegate void Interface_TestClass_impl_07_ev(object sender); interface Interface_TestClass_impl_07_I { void Method(); int Property { get; set; } event Interface_TestClass_impl_07_ev Clicked; string this[int index] { get; set; } } class Interface_TestClass_impl_07_1 : Interface_TestClass_impl_07_I { private int num; public void Method() { Log.Comment("Method()"); } public int Property { get { return num; } set { if (value >= 0 && value <= 10) num = value; } } public event Interface_TestClass_impl_07_ev Clicked; public string this[int index] { get { return "Interface_TestClass_impl_07"; } set { } } } class Interface_TestClass_impl_07 { public static void Main_old() { Interface_TestClass_impl_07 t = new Interface_TestClass_impl_07(); } public static bool testMethod() { Main_old(); return true; } } interface Interface_TestClass_impl_08_I1 { void Paint(); } interface Interface_TestClass_impl_08_I2 { void Paint(); } class Interface_TestClass_impl_08 : Interface_TestClass_impl_08_I1, Interface_TestClass_impl_08_I2 { public void Paint() { } public static void Main_old() { } public static bool testMethod() { Main_old(); return true; } } interface Interface_TestClass_impl_09_I1 { int MyProp { get; set; } } interface Interface_TestClass_impl_09_I2 { int MyProp { get; set; } } class Interface_TestClass_impl_09 : Interface_TestClass_impl_09_I1, Interface_TestClass_impl_09_I2 { public int MyProp { get { return 0; } set { } } public static void Main_old() { } public static bool testMethod() { Main_old(); return true; } } public delegate void MyDelegate(object sender); interface Interface_TestClass_impl_10_I1 { event MyDelegate Interface_TestClass_impl_10_ev; } interface Interface_TestClass_impl_10_I2 { event MyDelegate Interface_TestClass_impl_10_ev; } class Interface_TestClass_impl_10 : Interface_TestClass_impl_10_I1, Interface_TestClass_impl_10_I2 { public event MyDelegate Interface_TestClass_impl_10_ev; public static void Main_old() { } public static bool testMethod() { Main_old(); return true; } } interface Interface_TestClass_impl_11_I1 { string this[int index] { get; set; } } interface Interface_TestClass_impl_11_I2 { string this[int index] { get; set; } } class Interface_TestClass_impl_11 : Interface_TestClass_impl_11_I1, Interface_TestClass_impl_11_I2 { public string this[int index] { get { return "Interface_TestClass_impl_11_1"; } set { } } public static void Main_old() { } public static bool testMethod() { Main_old(); return true; } } interface Interface_TestClass_impl_12_I1 { void F(); } class Interface_TestClass_impl_12_1 { public void F() { } public void G() { } } class MyOtherClass : Interface_TestClass_impl_12_1, Interface_TestClass_impl_12_I1 { public new void G() { } } class Interface_TestClass_impl_12 { public static void Main_old() { } public static bool testMethod() { Main_old(); return true; } } interface Interface_TestClass_impl_13_I1 { int foo(); } interface Interface_TestClass_impl_13_I2 { int foo(); } class Interface_TestClass_impl_13_2 : Interface_TestClass_impl_13_I1, Interface_TestClass_impl_13_I2 { public int foo() { return 0; } } class Interface_TestClass_impl_13 { public static int Main_old() { Interface_TestClass_impl_13_2 x = new Interface_TestClass_impl_13_2(); Interface_TestClass_impl_13_I1 Interface_TestClass_impl_13_2 = x; Interface_TestClass_impl_13_I2 b = x; if (Interface_TestClass_impl_13_2 == b) { return 0; } return 1; } public static bool testMethod() { return (Main_old() == 0); } } interface Interface_TestClass_implinherit_01_I1 { void Paint(); } class Interface_TestClass_implinherit_01_1 : Interface_TestClass_implinherit_01_I1 { public void Paint() { Log.Comment("Interface_TestClass_implinherit_01_1.Paint()"); } } class Interface_TestClass_implinherit_01_2 : Interface_TestClass_implinherit_01_1 { new public void Paint() { Log.Comment("Interface_TestClass_implinherit_01_2.Paint()"); } } class Interface_TestClass_implinherit_01 { public static void Main_old() { Interface_TestClass_implinherit_01_1 c = new Interface_TestClass_implinherit_01_1(); Interface_TestClass_implinherit_01_2 t = new Interface_TestClass_implinherit_01_2(); Interface_TestClass_implinherit_01_I1 ic = c; Interface_TestClass_implinherit_01_I1 it = t; c.Paint(); t.Paint(); ic.Paint(); it.Paint(); } public static bool testMethod() { Main_old(); return true; } } interface Interface_TestClass_implinherit_02_I1 { void Paint(); } class Interface_TestClass_implinherit_02_1 : Interface_TestClass_implinherit_02_I1 { public virtual void Paint() { Log.Comment("Interface_TestClass_implinherit_02_1.Paint()"); } } class Interface_TestClass_implinherit_02_2 : Interface_TestClass_implinherit_02_1 { public override void Paint() { Log.Comment("Interface_TestClass_implinherit_02_2.Paint()"); } } class Interface_TestClass_implinherit_02 { public static void Main_old() { Interface_TestClass_implinherit_02_1 c = new Interface_TestClass_implinherit_02_1(); Interface_TestClass_implinherit_02_2 t = new Interface_TestClass_implinherit_02_2(); Interface_TestClass_implinherit_02_I1 ic = c; Interface_TestClass_implinherit_02_I1 it = t; c.Paint(); t.Paint(); ic.Paint(); it.Paint(); } public static bool testMethod() { Main_old(); return true; } } interface Interface_TestClass_explicit_01_I1 { void F(); } interface Interface_TestClass_explicit_01_I2 { void G(); } class Interface_TestClass_explicit_01_C : Interface_TestClass_explicit_01_I1, Interface_TestClass_explicit_01_I2 { void Interface_TestClass_explicit_01_I1.F() { } void Interface_TestClass_explicit_01_I2.G() { } public static void Main_old() { } public static bool testMethod() { Main_old(); return true; } } interface Interface_TestClass_explicit_03_I1 { void F(); } interface Interface_TestClass_explicit_03_I2 : Interface_TestClass_explicit_03_I1 { void G(); } class Interface_TestClass_explicit_03_C : Interface_TestClass_explicit_03_I2 { void Interface_TestClass_explicit_03_I1.F() { } void Interface_TestClass_explicit_03_I2.G() { } public static void Main_old() { } public static bool testMethod() { Main_old(); return true; } } interface Interface_TestClass_explicit_04_1 { void Method(); } class Interface_TestClass_explicit_04_2 : Interface_TestClass_explicit_04_1 { void Interface_TestClass_explicit_04_1.Method() { Log.Comment("Method()"); } } class Interface_TestClass_explicit_04 { public static void Main_old() { Interface_TestClass_explicit_04_2 t = new Interface_TestClass_explicit_04_2(); } public static bool testMethod() { Main_old(); return true; } } interface Interface_TestClass_explicit_05_1 { int Property { get; set; } } class Interface_TestClass_explicit_05_2 : Interface_TestClass_explicit_05_1 { private int num; int Interface_TestClass_explicit_05_1.Property { get { return num; } set { if (value >= 0 && value <= 10) num = value; } } } class Interface_TestClass_explicit_05 { public static void Main_old() { Interface_TestClass_explicit_05_2 t = new Interface_TestClass_explicit_05_2(); } public static bool testMethod() { Main_old(); return true; } } public delegate void Interface_TestClass_explicit_06_ev(object sender); interface Interface_TestClass_explicit_06_1 { event Interface_TestClass_explicit_06_ev Clicked; } class Interface_TestClass_explicit_06_2 : Interface_TestClass_explicit_06_1 { event Interface_TestClass_explicit_06_ev Interface_TestClass_explicit_06_1.Clicked { add { } remove { } } public void MyHandler(object sender) { } } class Interface_TestClass_explicit_06 { public static void Main_old() { Interface_TestClass_explicit_06_2 t = new Interface_TestClass_explicit_06_2(); } public static bool testMethod() { Main_old(); return true; } } interface Interface_TestClass_explicit_07_1 { string this[int index] { get; set; } } class Interface_TestClass_explicit_07_2 : Interface_TestClass_explicit_07_1 { string Interface_TestClass_explicit_07_1.this[int index] { get { return "Interface_TestClass_explicit_07"; } set { } } } class Interface_TestClass_explicit_07 { public static void Main_old() { Interface_TestClass_explicit_07_2 t = new Interface_TestClass_explicit_07_2(); } public static bool testMethod() { Main_old(); return true; } } interface ICloneable { object Clone(); } interface Interface_TestClass_explicit_09_I2 { int CompareTo(object other); } class Interface_TestClass_explicit_09_1 : ICloneable, Interface_TestClass_explicit_09_I2 { object ICloneable.Clone() { return new object(); } int Interface_TestClass_explicit_09_I2.CompareTo(object other) { return 0; } public static void Main_old() { } public static bool testMethod() { Main_old(); return true; } } interface Interface_TestClass_explicit_10_C { object Clone(); } interface Interface_TestClass_explicit_10_I2 { int CompareTo(object other); } class Interface_TestClass_explicit_10_1 : Interface_TestClass_explicit_10_C, Interface_TestClass_explicit_10_I2 { object Interface_TestClass_explicit_10_C.Clone() { return new object(); } int Interface_TestClass_explicit_10_I2.CompareTo(object other) { return 0; } } class Interface_TestClass_explicit_10 { public static void Main_old() { Interface_TestClass_explicit_10_1 le = new Interface_TestClass_explicit_10_1(); object o = ((Interface_TestClass_explicit_10_C)le).Clone(); } public static bool testMethod() { try { Main_old(); } catch (System.Exception) { return false; } return true; } } interface ICloneable_2 { int Value { get; set; } } interface Interface_TestClass_explicit_11_I2 { int CompareTo(object other); } class Interface_TestClass_explicit_11_1 : ICloneable_2, Interface_TestClass_explicit_11_I2 { private int val; int ICloneable_2.Value { get { return val; } set { val = value; } } int Interface_TestClass_explicit_11_I2.CompareTo(object other) { return 0; } } class Interface_TestClass_explicit_11 { public static int Main_old() { try { Interface_TestClass_explicit_11_1 le = new Interface_TestClass_explicit_11_1(); ((ICloneable_2)le).Value = 5; if (((ICloneable_2)le).Value == 5) return 0; else return 1; } catch (System.Exception) { return 1; } } public static bool testMethod() { return (Main_old() == 0); } } interface ICloneable_3 { string this[string hashkey] { get; set; } } interface Interface_TestClass_explicit_12_I2 { int CompareTo(object other); } class Interface_TestClass_explicit_12_1 : ICloneable_3, Interface_TestClass_explicit_12_I2 { public string st = ""; string ICloneable_3.this[string hashkey] { get { return "success"; } set { st = value; } } int Interface_TestClass_explicit_12_I2.CompareTo(object other) { return 0; } } class Interface_TestClass_explicit_12 { public static int Main_old() { try { Interface_TestClass_explicit_12_1 le = new Interface_TestClass_explicit_12_1(); ((ICloneable_3)le)["Interface_TestClass_explicit_12_1"] = "correct"; string s = ((ICloneable_3)le)["Interface_TestClass_explicit_12_1"]; if (le.st == "correct" && s == "success") return 0; else return 1; } catch (System.Exception) { return 1; } } public static bool testMethod() { return (Main_old() == 0); } } public delegate void Interface_TestClass_explicit_13_ev(object sender); interface Interface_TestClass_explicit_13_1 { event Interface_TestClass_explicit_13_ev Clicked; } class Interface_TestClass_explicit_13_2 : Interface_TestClass_explicit_13_1 { event Interface_TestClass_explicit_13_ev Interface_TestClass_explicit_13_1.Clicked { add { } remove { } } public void MyHandler(object sender) { } } class Interface_TestClass_explicit_13 { public static void Main_old() { new Interface_TestClass_explicit_13().Run(); } public void Run() { Interface_TestClass_explicit_13_2 t = new Interface_TestClass_explicit_13_2(); ((Interface_TestClass_explicit_13_1)t).Clicked += new Interface_TestClass_explicit_13_ev(TheHandler); } public void TheHandler(object sender) { } public static bool testMethod() { try { Main_old(); } catch (System.Exception) { return false; } return true; } } interface Interface_TestClass_explicit_20_I3 : ICloneable { string OtherMethod(); } class Interface_TestClass_explicit_20_1 : Interface_TestClass_explicit_20_I3 { string Interface_TestClass_explicit_20_I3.OtherMethod() { return "Interface_TestClass_explicit_20_1"; } object ICloneable.Clone() { return new object(); } public static void Main_old() { } public static bool testMethod() { Main_old(); return true; } } interface Interface_TestClass_explicit_21_I2 { int P { get; } } interface Interface_TestClass_explicit_21_I3 : Interface_TestClass_explicit_21_I2 { new int P(); } class Interface_TestClass_explicit_21_1 : Interface_TestClass_explicit_21_I3 { int Interface_TestClass_explicit_21_I2.P { get { return 1; } } int Interface_TestClass_explicit_21_I3.P() { return 1; } } class Interface_TestClass_explicit_21_2 : Interface_TestClass_explicit_21_I3 { public int P { get { return 1; } } int Interface_TestClass_explicit_21_I3.P() { return 1; } } class Interface_TestClass_explicit_21_3 : Interface_TestClass_explicit_21_I3 { int Interface_TestClass_explicit_21_I2.P { get { return 1; } } public int P() { return 1; } } class Interface_TestClass_explicit_21 { public static void Main_old() { } public static bool testMethod() { Main_old(); return true; } } class TypeA { } class TypeB { } interface Interface_TestClass_explicit_25_I3 { int foo(TypeA Interface_TestClass_explicit_25_2); int foo(TypeB b); } class Interface_TestClass_explicit_25_A : Interface_TestClass_explicit_25_I3 { int Interface_TestClass_explicit_25_I3.foo(TypeA Interface_TestClass_explicit_25_2) { return 1; } int Interface_TestClass_explicit_25_I3.foo(TypeB b) { return 2; } } class Interface_TestClass_explicit_25 { static int Main_old() { try { TypeA Interface_TestClass_explicit_25_2 = new TypeA(); TypeB b = new TypeB(); Interface_TestClass_explicit_25_A Interface_TestClass_explicit_25_1 = new Interface_TestClass_explicit_25_A(); if (((Interface_TestClass_explicit_25_I3)Interface_TestClass_explicit_25_1).foo(Interface_TestClass_explicit_25_2) != 1) return 1; if (((Interface_TestClass_explicit_25_I3)Interface_TestClass_explicit_25_1).foo(b) != 2) return 1; return 0; } catch (System.Exception) { return 1; } } public static bool testMethod() { return (Main_old() == 0); } } interface Interface_TestClass_mdfrmeth_09_I1 { void F(); void G(); } abstract class Interface_TestClass_mdfrmeth_09_C : Interface_TestClass_mdfrmeth_09_I1 { public abstract void F(); public abstract void G(); } class Interface_TestClass_mdfrmeth_09 { public static void Main_old() { } public static bool testMethod() { Main_old(); return true; } } interface Interface_TestClass_ifreimp_01_I1 { void Paint(); } class Interface_TestClass_ifreimp_01_1 : Interface_TestClass_ifreimp_01_I1 { void Interface_TestClass_ifreimp_01_I1.Paint() { Log.Comment("Interface_TestClass_ifreimp_01_1.Interface_TestClass_ifreimp_01_I1.Paint()"); throw new Exception("Incorrect method got called!"); } } class Interface_TestClass_ifreimp_01_3 : Interface_TestClass_ifreimp_01_1, Interface_TestClass_ifreimp_01_I1 { public void Paint() { Log.Comment("Interface_TestClass_ifreimp_01_3.Paint()"); } } class Interface_TestClass_ifreimp_01 { public static bool testMethod() { Interface_TestClass_ifreimp_01_I1 instance = new Interface_TestClass_ifreimp_01_3(); try { instance.Paint(); } catch (Exception) { return false; } return true; } } interface Interface_TestClass_ifreimp_02_I1 { void F(); void G(); void H(); void I(); } class Interface_TestClass_ifreimp_02_2 : Interface_TestClass_ifreimp_02_I1 { void Interface_TestClass_ifreimp_02_I1.F() { Log.Comment("Interface_TestClass_ifreimp_02_2.Interface_TestClass_ifreimp_02_I1.F()"); throw new Exception("Incorrect method got called!"); } void Interface_TestClass_ifreimp_02_I1.G() { Log.Comment("Interface_TestClass_ifreimp_02_2.Interface_TestClass_ifreimp_02_I1.G()"); } public void H() { Log.Comment("Interface_TestClass_ifreimp_02_2.H()"); throw new Exception("Incorrect method got called!"); } public void I() { Log.Comment("Interface_TestClass_ifreimp_02_2.I()"); } } class Interface_TestClass_ifreimp_02_1 : Interface_TestClass_ifreimp_02_2, Interface_TestClass_ifreimp_02_I1 { public void F() { Log.Comment("Interface_TestClass_ifreimp_02_1.F()"); } void Interface_TestClass_ifreimp_02_I1.H() { Log.Comment("Interface_TestClass_ifreimp_02_1.Interface_TestClass_ifreimp_02_I1.H()"); } } class Interface_TestClass_ifreimp_02 { public static bool testMethod() { try { Interface_TestClass_ifreimp_02_I1 im = new Interface_TestClass_ifreimp_02_1(); ; im.F(); im.G(); im.H(); im.I(); } catch (Exception) { return false; } return true; } } interface Interface_TestClass_ifreimp_03_I2 { void F(); } interface Interface_TestClass_ifreimp_03_I3 : Interface_TestClass_ifreimp_03_I2 { void G(); } class Interface_TestClass_ifreimp_03_C : Interface_TestClass_ifreimp_03_I3 { void Interface_TestClass_ifreimp_03_I2.F() { Log.Comment("Interface_TestClass_ifreimp_03_C.Interface_TestClass_ifreimp_03_I2.F()"); } void Interface_TestClass_ifreimp_03_I3.G() { Log.Comment("Interface_TestClass_ifreimp_03_C.Interface_TestClass_ifreimp_03_I3.G()"); } } class Interface_TestClass_ifreimp_03_D : Interface_TestClass_ifreimp_03_C, Interface_TestClass_ifreimp_03_I3 { public void F() { Log.Comment("Interface_TestClass_ifreimp_03_D.F()"); } public void G() { Log.Comment("Interface_TestClass_ifreimp_03_D.G()"); } } class Interface_TestClass_ifreimp_03 { public static void Main_old() { Interface_TestClass_ifreimp_03_D d = new Interface_TestClass_ifreimp_03_D(); Interface_TestClass_ifreimp_03_I2 ib = d; ib.F(); } public static bool testMethod() { try { Main_old(); } catch (System.Exception) { return false; } return true; } } interface Interface_TestClass_abstract_01_I1 { void F(); void G(); } abstract class Interface_TestClass_abstract_01_C : Interface_TestClass_abstract_01_I1 { public abstract void F(); public abstract void G(); } class Interface_TestClass_abstract_01 { public static void Main_old() { } public static bool testMethod() { Main_old(); return true; } } interface Interface_TestClass_abstract_02_I1 { void F(); void G(); } abstract class Interface_TestClass_abstract_02_C : Interface_TestClass_abstract_02_I1 { public abstract void F(); public abstract void G(); } class Interface_TestClass_abstract_02_D : Interface_TestClass_abstract_02_C { public override void F() { } public override void G() { } } class Interface_TestClass_abstract_02 { public static void Main_old() { } public static bool testMethod() { Main_old(); return true; } } interface Interface_TestClass_abstract_03_I1 { void F(); void G(); } abstract class Interface_TestClass_abstract_03_C : Interface_TestClass_abstract_03_I1 { public void F() { FF(); } public void G() { GG(); } protected abstract void FF(); protected abstract void GG(); } class Interface_TestClass_abstract_03 { public static void Main_old() { } public static bool testMethod() { Main_old(); return true; } } interface Interface_TestClass_indexer_02_1 { int this[int ident1] { get; set; } } class Interface_TestClass_indexer_02 { public static void Main_old() { } public static bool testMethod() { Main_old(); return true; } } interface Interface_TestClass_indexer_03_1 { String this[String ident1] { get; set; } } class Interface_TestClass_indexer_03 { public static void Main_old() { } public static bool testMethod() { Main_old(); return true; } } struct Interface_TestClass_indexer_04_str { } interface Interface_TestClass_indexer_04_1 { Interface_TestClass_indexer_04_str this[Interface_TestClass_indexer_04_str ident1] { get; set; } } class Interface_TestClass_indexer_04 { public static void Main_old() { } public static bool testMethod() { Main_old(); return true; } } struct Interface_TestClass_indexer_05_str { } interface Interface_TestClass_indexer_05_1 { Interface_TestClass_indexer_05_str this[Interface_TestClass_indexer_05_str ident1, int x, double y] { get; set; } } class Interface_TestClass_indexer_05 { public static void Main_old() { } public static bool testMethod() { Main_old(); return true; } } struct Interface_TestClass_indexer_06_str { } interface Interface_TestClass_indexer_06_1 { Interface_TestClass_indexer_06_str this[Interface_TestClass_indexer_06_str ident1, int x, double y] { get; } } class Interface_TestClass_indexer_06 { public static void Main_old() { } public static bool testMethod() { Main_old(); return true; } } struct Interface_TestClass_indexer_07_str { } interface Interface_TestClass_indexer_07_1 { Interface_TestClass_indexer_07_str this[Interface_TestClass_indexer_07_str ident1, int x, double y] { set; } } class Interface_TestClass_indexer_07 { public static void Main_old() { } public static bool testMethod() { Main_old(); return true; } } public delegate void Interface_TestClass_indexer_18_ev(object sender); interface Interface_TestClass_indexer_18_2 { new int this[int ident1] { get; set; } } class Interface_TestClass_indexer_18 { public static void Main_old() { } public static bool testMethod() { Main_old(); return true; } } interface Interface_TestClass_meth_09_1 { new void F(int x); } class Interface_TestClass_meth_09 { public static void Main_old() { } public static bool testMethod() { Main_old(); return true; } } interface Interface_TestClass_prop_09_2 { new int x { get; set; } } class Interface_TestClass_prop_09 { public static void Main_old() { } public static bool testMethod() { Main_old(); return true; } } interface Interface_TestClass_namesig_02_1 { void F(int x); void F(String x); } class Interface_TestClass_namesig_02_c : Interface_TestClass_namesig_02_1 { public void F(int x) { Log.Comment("F(int x) works!"); } public void F(String x) { Log.Comment("F(String x) works!"); } } class Interface_TestClass_namesig_02 { public static void Main_old() { Interface_TestClass_namesig_02_c tc = new Interface_TestClass_namesig_02_c(); tc.F(23); tc.F("Interface_TestClass_namesig_02"); } public static bool testMethod() { Main_old(); return true; } } interface Interface_TestClass_namesig_03_1 { void F(int x); } interface Interface_TestClass_namesig_03_2 : Interface_TestClass_namesig_03_1 { int F(int x); } class Interface_TestClass_namesig_03 { public static void Main_old() { } public static bool testMethod() { Main_old(); return true; } } interface Interface_TestClass_namesig_04_1 { void F(int x); } interface Interface_TestClass_namesig_04_2 { void F(int x); } interface Interface_TestClass_namesig_04_3 : Interface_TestClass_namesig_04_1, Interface_TestClass_namesig_04_2 { } class Interface_TestClass_namesig_04 { public static void Main_old() { } public static bool testMethod() { Main_old(); return true; } } interface Interface_TestClass_namesig_05_1 { void F(int x); } interface Interface_TestClass_namesig_05_2 : Interface_TestClass_namesig_05_1 { new int F(int x); } class Interface_TestClass_namesig_05 { public static void Main_old() { } public static bool testMethod() { Main_old(); return true; } } public delegate void Interface_TestClass_events_08_ev(object sender); interface Interface_TestClass_events_08_2 { new event Interface_TestClass_events_08_ev Click; } class Interface_TestClass_events_08 { public static void Main_old() { } public static bool testMethod() { Main_old(); return true; } } public delegate void Interface_TestClass_events_09_EH(object sender); interface Interface_TestClass_events_09_1 { event Interface_TestClass_events_09_EH Click; } class Interface_TestClass_events_09 { public static void Main_old() { } public static bool testMethod() { Main_old(); return true; } } interface Interface_TestClass_maccess_01_I1 { int Count { get; set; } } interface Interface_TestClass_maccess_01_I2 { void Count(int i); } interface IListCounter : Interface_TestClass_maccess_01_I1, Interface_TestClass_maccess_01_I2 { } class Interface_TestClass_maccess_01 { void Test(IListCounter x) { ((Interface_TestClass_maccess_01_I1)x).Count = 1; ((Interface_TestClass_maccess_01_I2)x).Count(1); } public static void Main_old() { } public static bool testMethod() { Main_old(); return true; } } interface Interface_TestClass_maccess_03_I1 { void Add(int i); } interface Interface_TestClass_maccess_03_I2 { void Add(double d); } interface Interface_TestClass_maccess_03_I3 : Interface_TestClass_maccess_03_I1, Interface_TestClass_maccess_03_I2 { } class Interface_TestClass_maccess_03 { void Test(Interface_TestClass_maccess_03_I3 n) { ((Interface_TestClass_maccess_03_I1)n).Add(1); ((Interface_TestClass_maccess_03_I2)n).Add(1); } public static void Main_old() { } public static bool testMethod() { Main_old(); return true; } } interface Interface_TestClass_maccess_04_I1 { void Add(int i); } interface Interface_TestClass_maccess_04_I2 { void Add(double d); } interface Interface_TestClass_maccess_04_I3 : Interface_TestClass_maccess_04_I1, Interface_TestClass_maccess_04_I2 { } class Interface_TestClass_maccess_04 { void Test(Interface_TestClass_maccess_04_I3 n) { n.Add(1.2); } public static void Main_old() { } public static bool testMethod() { Main_old(); return true; } } interface Interface_TestClass_maccess_06_I2 { int F(int i); } interface Interface_TestClass_maccess_06_I4 : Interface_TestClass_maccess_06_I2 { new string F(int i); } interface Interface_TestClass_maccess_06_I5 : Interface_TestClass_maccess_06_I2 { void G(); } interface Interface_TestClass_maccess_06_I3 : Interface_TestClass_maccess_06_I4, Interface_TestClass_maccess_06_I5 { } class Interface_TestClass_maccess_06_C { void Interface_TestClass_maccess_06(Interface_TestClass_maccess_06_I3 d) { // Calling d.F(1) should return Interface_TestClass_maccess_06_2 string, which proves that // it's calling Interface_TestClass_maccess_06_I4's F method as expected. string x = d.F(1); } public static void Main_old() { } public static bool testMethod() { Main_old(); return true; } } private interface Interface_TestClass_modifier_02_I { } class Interface_TestClass_modifier_02 { public static void Main_old() { } public static bool testMethod() { Main_old(); return true; } } protected interface Interface_TestClass_modifier_03_I { } class Interface_TestClass_modifier_03 { public static void Main_old() { } public static bool testMethod() { Main_old(); return true; } } //Compiled Test Cases interface Interface_TestClass_struct_impl_01_I1 { void F(); } interface Interface_TestClass_struct_impl_01_I2 { void G(); } struct Interface_TestClass_struct_impl_01_1 : Interface_TestClass_struct_impl_01_I1, Interface_TestClass_impl_01_I2 { public void F() { } public void G() { } } class Interface_TestClass_struct_impl_01 { public static void Main_old() { } public static bool testMethod() { Main_old(); return true; } } interface Interface_TestClass_struct_impl_02_I2 { void Interface_TestClass_struct_impl_02_B(); } interface Interface_TestClass_struct_impl_02_I3 : Interface_TestClass_struct_impl_02_I2 { void Interface_TestClass_struct_impl_02_D(); } struct Interface_TestClass_struct_impl_02_1 : Interface_TestClass_struct_impl_02_I3 { public void Interface_TestClass_struct_impl_02_B() { } public void Interface_TestClass_struct_impl_02_D() { } } class Interface_TestClass_struct_impl_02 { public static void Main_old() { } public static bool testMethod() { Main_old(); return true; } } interface Interface_TestClass_struct_impl_04_I1 { void F(); } struct Interface_TestClass_struct_impl_04_C : Interface_TestClass_struct_impl_04_I1 { public void F() { Log.Comment("Interface_TestClass_struct_impl_04_C.F()"); } } class Interface_TestClass_struct_impl_04 { public static void Main_old() { Interface_TestClass_struct_impl_04_C cc = new Interface_TestClass_struct_impl_04_C(); Interface_TestClass_struct_impl_04_I1 ic = cc; cc.F(); ic.F(); } public static bool testMethod() { Main_old(); return true; } } public delegate void Interface_TestClass_struct_impl_05_ev(object sender); interface Interface_TestClass_struct_impl_05_1 { void Method(); int Property { get; set; } event Interface_TestClass_struct_impl_05_ev Clicked; string this[int index] { get; set; } } struct Interface_TestClass_struct_impl_05_2 : Interface_TestClass_struct_impl_05_1 { private int num; public void Method() { Log.Comment("Method()"); } public int Property { get { return num; } set { if (value >= 0 && value <= 10) num = value; } } public event Interface_TestClass_struct_impl_05_ev Clicked; public string this[int index] { get { return "Interface_TestClass_struct_impl_05"; } set { } } } class Interface_TestClass_struct_impl_05 { public static void Main_old() { Interface_TestClass_struct_impl_05_2 t = new Interface_TestClass_struct_impl_05_2(); } public static bool testMethod() { Main_old(); return true; } } interface Interface_TestClass_struct_impl_06_I1 { void Paint(); } interface Interface_TestClass_struct_impl_06_I2 { void Paint(); } struct Interface_TestClass_struct_impl_06_1 : Interface_TestClass_struct_impl_06_I1, Interface_TestClass_struct_impl_06_I2 { public void Paint() { } } class Interface_TestClass_struct_impl_06 { public static void Main_old() { } public static bool testMethod() { Main_old(); return true; } } interface Interface_TestClass_struct_impl_07_I1 { int MyProp { get; set; } } interface Interface_TestClass_struct_impl_07_I2 { int MyProp { get; set; } } struct Interface_TestClass_struct_impl_07_1 : Interface_TestClass_struct_impl_07_I1, Interface_TestClass_struct_impl_07_I2 { public int MyProp { get { return 0; } set { } } } class Interface_TestClass_struct_impl_07 { public static void Main_old() { } public static bool testMethod() { Main_old(); return true; } } public delegate void Interface_TestClass_struct_impl_08_Del (object sender); interface Interface_TestClass_struct_impl_08_I1 { event Interface_TestClass_struct_impl_08_Del Interface_TestClass_struct_impl_08_ev; } interface Interface_TestClass_struct_impl_08_I2 { event Interface_TestClass_struct_impl_08_Del Interface_TestClass_struct_impl_08_ev; } struct Interface_TestClass_struct_impl_08_1 : Interface_TestClass_struct_impl_08_I1, Interface_TestClass_struct_impl_08_I2 { public event Interface_TestClass_struct_impl_08_Del Interface_TestClass_struct_impl_08_ev; } class Interface_TestClass_struct_impl_08 { public static void Main_old() { } public static bool testMethod() { Main_old(); return true; } } interface Interface_TestClass_struct_impl_09_I1 { string this[int index] { get; set; } } interface Interface_TestClass_struct_impl_09_I2 { string this[int index] { get; set; } } struct Interface_TestClass_struct_impl_09_1 : Interface_TestClass_struct_impl_09_I1, Interface_TestClass_struct_impl_09_I2 { public string this[int index] { get { return "Interface_TestClass_struct_impl_09_1"; } set { } } } class Interface_TestClass_struct_impl_09 { public static void Main_old() { } public static bool testMethod() { Main_old(); return true; } } interface Interface_TestClass_struct_explicit_01_I1 { void F(); } interface Interface_TestClass_struct_explicit_01_I2 { void G(); } struct Interface_TestClass_struct_explicit_01_C : Interface_TestClass_struct_explicit_01_I1, Interface_TestClass_struct_explicit_01_I2 { void Interface_TestClass_struct_explicit_01_I1.F() { } void Interface_TestClass_struct_explicit_01_I2.G() { } } class Interface_TestClass_struct_explicit_01 { public static void Main_old() { } public static bool testMethod() { Main_old(); return true; } } interface Interface_TestClass_struct_explicit_03_I1 { void F(); } interface Interface_TestClass_struct_explicit_03_I2 : Interface_TestClass_struct_explicit_03_I1 { void G(); } struct Interface_TestClass_struct_explicit_03_C : Interface_TestClass_struct_explicit_03_I2 { void Interface_TestClass_struct_explicit_03_I1.F() { } void Interface_TestClass_struct_explicit_03_I2.G() { } } class Interface_TestClass_struct_explicit_03 { public static void Main_old() { } public static bool testMethod() { Main_old(); return true; } } interface Interface_TestClass_struct_explicit_04_1 { void Method(); } struct Interface_TestClass_struct_explicit_04_2 : Interface_TestClass_struct_explicit_04_1 { void Interface_TestClass_struct_explicit_04_1.Method() { Log.Comment("Method()"); } } class Interface_TestClass_struct_explicit_04 { public static void Main_old() { Interface_TestClass_struct_explicit_04_2 t = new Interface_TestClass_struct_explicit_04_2(); } public static bool testMethod() { Main_old(); return true; } } interface Interface_TestClass_struct_explicit_05_1 { int Property { get; set; } } struct Interface_TestClass_struct_explicit_05_2 : Interface_TestClass_struct_explicit_05_1 { private int num; int Interface_TestClass_struct_explicit_05_1.Property { get { return num; } set { if (value >= 0 && value <= 10) num = value; } } } class Interface_TestClass_struct_explicit_05 { public static void Main_old() { Interface_TestClass_struct_explicit_05_2 t = new Interface_TestClass_struct_explicit_05_2(); } public static bool testMethod() { Main_old(); return true; } } public delegate void Interface_TestClass_struct_explicit_06_ev(object sender); interface Interface_TestClass_struct_explicit_06_1 { event Interface_TestClass_struct_explicit_06_ev Clicked; } struct Interface_TestClass_struct_explicit_06_2 : Interface_TestClass_struct_explicit_06_1 { event Interface_TestClass_struct_explicit_06_ev Interface_TestClass_struct_explicit_06_1.Clicked { add { } remove { } } public void MyHandler(object sender) { } } class Interface_TestClass_struct_explicit_06 { public static void Main_old() { Interface_TestClass_struct_explicit_06_2 t = new Interface_TestClass_struct_explicit_06_2(); } public static bool testMethod() { Main_old(); return true; } } interface Interface_TestClass_struct_explicit_07_1 { string this[int index] { get; set; } } struct Interface_TestClass_struct_explicit_07_2 : Interface_TestClass_struct_explicit_07_1 { string Interface_TestClass_struct_explicit_07_1.this[int index] { get { return "Interface_TestClass_struct_explicit_07"; } set { } } } class Interface_TestClass_struct_explicit_07 { public static void Main_old() { Interface_TestClass_struct_explicit_07_2 t = new Interface_TestClass_struct_explicit_07_2(); } public static bool testMethod() { Main_old(); return true; } } interface Interface_TestClass_struct_explicit_09_I1 { object Clone(); } interface Interface_TestClass_struct_explicit_09_I2 { int CompareTo(object other); } struct Interface_TestClass_struct_explicit_09_1 : Interface_TestClass_struct_explicit_09_I1, Interface_TestClass_struct_explicit_09_I2 { object Interface_TestClass_struct_explicit_09_I1.Clone() { return new object(); } int Interface_TestClass_struct_explicit_09_I2.CompareTo(object other) { return 0; } } class Interface_TestClass_struct_explicit_09 { public static void Main_old() { } public static bool testMethod() { Main_old(); return true; } } interface Interface_TestClass_struct_explicit_10_I1 { object Clone(); } interface Interface_TestClass_struct_explicit_10_I2 { int CompareTo(object other); } struct Interface_TestClass_struct_explicit_10_1 : Interface_TestClass_struct_explicit_10_I1, Interface_TestClass_struct_explicit_10_I2 { object Interface_TestClass_struct_explicit_10_I1.Clone() { return new object(); } int Interface_TestClass_struct_explicit_10_I2.CompareTo(object other) { return 0; } } class Interface_TestClass_struct_explicit_10 { public static void Main_old() { Interface_TestClass_struct_explicit_10_1 le = new Interface_TestClass_struct_explicit_10_1(); object o = ((Interface_TestClass_struct_explicit_10_I1)le).Clone(); } public static bool testMethod() { try { Main_old(); } catch (System.Exception) { return false; } return true; } } interface Interface_TestClass_struct_explicit_11_I1 { int Value { get; set; } } interface Interface_TestClass_struct_explicit_11_I2 { int CompareTo(object other); } struct Interface_TestClass_struct_explicit_11_1 : Interface_TestClass_struct_explicit_11_I1, Interface_TestClass_struct_explicit_11_I2 { private int val; int Interface_TestClass_struct_explicit_11_I1.Value { get { return val; } set { val = value; Log.Comment(val.ToString()); } } int Interface_TestClass_struct_explicit_11_I2.CompareTo(object other) { return 0; } } class Interface_TestClass_struct_explicit_11 { public static int Main_old() { try { Interface_TestClass_struct_explicit_11_1 le = new Interface_TestClass_struct_explicit_11_1(); ((Interface_TestClass_struct_explicit_11_I1)le).Value = 5; Log.Comment((((Interface_TestClass_struct_explicit_11_I1)le).Value).ToString()); return 0; } catch (System.Exception) { return 1; } } public static bool testMethod() { return (Main_old() == 0); } } interface Interface_TestClass_struct_explicit_12_I1 { string this[string hashkey] { get; set; } } interface Interface_TestClass_struct_explicit_12_I2 { int CompareTo(object other); } struct Interface_TestClass_struct_explicit_12_1 : Interface_TestClass_struct_explicit_12_I1, Interface_TestClass_struct_explicit_12_I2 { public string st; string Interface_TestClass_struct_explicit_12_I1.this[string hashkey] { get { return "success"; } set { st = value; } } int Interface_TestClass_struct_explicit_12_I2.CompareTo(object other) { return 0; } } class Interface_TestClass_struct_explicit_12 { public static int Main_old() { try { Interface_TestClass_struct_explicit_12_1 le = new Interface_TestClass_struct_explicit_12_1(); ((Interface_TestClass_struct_explicit_12_I1)le)["Interface_TestClass_struct_explicit_12_1"] = "correct"; string s = ((Interface_TestClass_struct_explicit_12_I1)le)["Interface_TestClass_struct_explicit_12_1"]; if (s == "success") return 0; else return 1; } catch (System.Exception) { return 1; } } public static bool testMethod() { return (Main_old() == 0); } } public delegate void Interface_TestClass_struct_explicit_13_ev(object sender); interface Interface_TestClass_struct_explicit_13_1 { event Interface_TestClass_struct_explicit_13_ev Clicked; } struct Interface_TestClass_struct_explicit_13_2 : Interface_TestClass_struct_explicit_13_1 { event Interface_TestClass_struct_explicit_13_ev Interface_TestClass_struct_explicit_13_1.Clicked { add { } remove { } } public void MyHandler(object sender) { } } class Interface_TestClass_struct_explicit_13 { public static void Main_old() { new Interface_TestClass_struct_explicit_13().Run(); } public void Run() { Interface_TestClass_struct_explicit_13_2 t = new Interface_TestClass_struct_explicit_13_2(); ((Interface_TestClass_struct_explicit_13_1)t).Clicked += new Interface_TestClass_struct_explicit_13_ev(TheHandler); } public void TheHandler(object sender) { } public static bool testMethod() { try { Main_old(); } catch (System.Exception) { return false; } return true; } } interface Interface_TestClass_struct_explicit_19_I1 { object Clone(); } interface Interface_TestClass_struct_explicit_19_I3 : Interface_TestClass_struct_explicit_19_I1 { string OtherMethod(); } class Interface_TestClass_struct_explicit_19_1 : Interface_TestClass_struct_explicit_19_I3 { string Interface_TestClass_struct_explicit_19_I3.OtherMethod() { return "Interface_TestClass_struct_explicit_19_1"; } object Interface_TestClass_struct_explicit_19_I1.Clone() { return new object(); } } class Interface_TestClass_struct_explicit_19 { public static void Main_old() { } public static bool testMethod() { Main_old(); return true; } } interface Interface_TestClass_struct_explicit_20_I2 { int P { get; } } interface Interface_TestClass_struct_explicit_20_I3 : Interface_TestClass_struct_explicit_20_I2 { new int P(); } struct Interface_TestClass_struct_explicit_20_1 : Interface_TestClass_struct_explicit_20_I3 { int Interface_TestClass_struct_explicit_20_I2.P { get { return 1; } } int Interface_TestClass_struct_explicit_20_I3.P() { return 1; } } struct Interface_TestClass_struct_explicit_20_2 : Interface_TestClass_struct_explicit_20_I3 { public int P { get { return 1; } } int Interface_TestClass_struct_explicit_20_I3.P() { return 1; } } struct Interface_TestClass_struct_explicit_20_3 : Interface_TestClass_struct_explicit_20_I3 { int Interface_TestClass_struct_explicit_20_I2.P { get { return 1; } } public int P() { return 1; } } class Interface_TestClass_struct_explicit_20 { public static void Main_old() { } public static bool testMethod() { Main_old(); return true; } } struct Interface_TestClass_struct_decl_01_1 { interface Interface_TestClass_struct_decl_01_I { } } class Interface_TestClass_struct_decl_01 { public static void Main_old() { Log.Comment("This works!"); } public static bool testMethod() { Main_old(); return true; } } interface Interface_TestClass_struct_inherit_01_A { void m(); } interface Interface_TestClass_struct_inherit_01_B : Interface_TestClass_struct_inherit_01_A { } interface Interface_TestClass_struct_inherit_01_C : Interface_TestClass_struct_inherit_01_B { } struct Interface_TestClass_struct_inherit_01_1 : Interface_TestClass_struct_inherit_01_C { public void m() { Log.Comment("This works!"); } } class Interface_TestClass_struct_inherit_01 { public static void Main_old() { Interface_TestClass_struct_inherit_01_1 t = new Interface_TestClass_struct_inherit_01_1(); t.m(); } public static bool testMethod() { Main_old(); return true; } } struct Interface_TestClass_struct_modifier_01_1 { public interface Interface_TestClass_struct_modifier_01_I { } internal interface Interface_TestClass_struct_modifier_01_I2 { } } class Interface_TestClass_struct_modifier_01 { public static void Main_old() { } public static bool testMethod() { Main_old(); return true; } } struct Interface_TestClass_struct_modifier_02_1 { private interface Interface_TestClass_struct_modifier_02_I { } } class Interface_TestClass_struct_modifier_02 { public static void Main_old() { } public static bool testMethod() { Main_old(); return true; } } struct Interface_TestClass_struct_modifier_03_1 { new interface Interface_TestClass_struct_modifier_03_I { } } class Interface_TestClass_struct_modifier_03 { public static void Main_old() { } public static bool testMethod() { Main_old(); return true; } } struct Interface_TestClass_struct_semicolon_01_1 { interface Interface_TestClass_struct_semicolon_01_I { }; } class Interface_TestClass_struct_semicolon_01 { public static void Main_old() { Log.Comment("This works!"); } public static bool testMethod() { Main_old(); return true; } } } } namespace Interface_TestClass_struct_decl_02_NS { struct Interface_TestClass_struct_decl_02_I { } class Interface_TestClass_struct_decl_02 { public static void Main_old() { Log.Comment("This works!"); } public static bool testMethod() { Main_old(); return true; } } } namespace Interface_TestClass_struct_semicolon_02_NS { struct Interface_TestClass_struct_semicolon_02_1 { interface Interface_TestClass_struct_semicolon_02_I { }; } class Interface_TestClass_struct_semicolon_02 { public static void Main_old() { Log.Comment("This works!"); } public static bool testMethod() { Main_old(); return true; } } } namespace Interface_TestClass_decl_02_NS { interface Interface_TestClass_decl_02_I { } class Interface_TestClass_decl_02 { public static void Main_old() { Log.Comment("This works!"); } public static bool testMethod() { Main_old(); return true; } } } namespace Interface_TestClass_semicolon_04_NS { class Interface_TestClass_semicolon_04 { interface Interface_TestClass_semicolon_04_I { }; public static void Main_old() { Log.Comment("This works!"); } public static bool testMethod() { Main_old(); return true; } } } namespace Interface_TestClass_semicolon_02_NS { interface Interface_TestClass_semicolon_02_I { }; class Interface_TestClass_semicolon_02 { public static void Main_old() { Log.Comment("This works!"); } public static bool testMethod() { Main_old(); return true; } } } namespace Interface_TestClass_decl_04_NS { class Interface_TestClass_decl_04 { interface Interface_TestClass_decl_04_I { } public static void Main_old() { Log.Comment("This works!"); } public static bool testMethod() { Main_old(); return true; } } } ================================================ FILE: Zelig/Zelig/Test/RunTime/NETMF/mscorlib/lexical/LexicalTests2.cs ================================================ //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // Copyright (c) Microsoft Corporation. All rights reserved. ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////#define while //Lexical_TestClass_pre_009 #define while //Lexical_TestClass_pre_009 #define True1 //Lexical_TestClass_pre_012 #define True2 #define False1 #undef False1 #undef False1 #undef False2 //Lexical_TestClass_pre_013 #define foo// Should work fine #define bar // As should this #define aaa #define bbb #undef aaa// Should Work #undef bbb// Should also work #if !foo #error !foo #endif #if !bar #error !bar #endif #if aaa #error aaa #endif #if bbb #error bbb #endif #define TESTDEF //Lexical_TestClass_preproc_03 #define TESTDEF3 //Lexical_TestClass_preproc_04 #define TESTDEF2 #undef TESTDEF3 #define FOO //Lexical_TestClass_preproc_05 #if FOO #define BAR #endif #define FOO2 //Lexical_TestClass_preproc_06 #undef FOO2 #undef FOO2 #define FOO3 //Lexical_TestClass_preproc_07 #undef BAR3 #define TEST //Lexical_TestClass_preproc_15-25,32 #define TEST2 //Lexical_TestClass_preproc_17-23,32 #define for //Lexical_TestClass_preproc_39 using System; using System.Reflection; using Microsoft.SPOT.Platform.Test; namespace Microsoft.SPOT.Platform.Tests { public class LexicalTests2 : IMFTestInterface { [SetUp] public InitializeResult Initialize() { return InitializeResult.ReadyToGo; } [TearDown] public void CleanUp() { Log.Comment("Cleaning up after the tests"); } //Lexical Test methods //The following tests were ported from folder current\test\cases\client\CLR\Conformance\10_classes\Lexical //Test Case Calls [TestMethod] public MFTestResults Lexical_pre_009_Test() { Log.Comment("Section 2.3Preprocessing"); Log.Comment("Verify #define and #undef"); if (Lexical_TestClass_pre_009.testMethod()) { return MFTestResults.Pass; } return MFTestResults.Fail; } [TestMethod] public MFTestResults Lexical_pre_012_Test() { Log.Comment("Section 2.3Preprocessing"); Log.Comment("Verify #if operators and parens"); if (Lexical_TestClass_pre_012.testMethod()) { return MFTestResults.Pass; } return MFTestResults.Fail; } [TestMethod] public MFTestResults Lexical_pre_013_Test() { Log.Comment("Section 2.3Preprocessing"); Log.Comment("Verify # commands with comments"); if (Lexical_TestClass_pre_013.testMethod()) { return MFTestResults.Pass; } return MFTestResults.Fail; } [TestMethod] public MFTestResults Lexical_preproc_03_Test() { Log.Comment("Section 2.3 Preprocessing"); Log.Comment("#define/#undef - verify #define works"); if (Lexical_TestClass_preproc_03.testMethod()) { return MFTestResults.Pass; } return MFTestResults.Fail; } [TestMethod] public MFTestResults Lexical_preproc_04_Test() { Log.Comment("Section 2.3 Preprocessing"); Log.Comment("#define/#undef - verify #undef works"); if (Lexical_TestClass_preproc_04.testMethod()) { return MFTestResults.Pass; } return MFTestResults.Fail; } [TestMethod] public MFTestResults Lexical_preproc_05_Test() { Log.Comment("Section 2.3 Preprocessing"); Log.Comment("Exact example used in spec definition - 2.3.1"); if (Lexical_TestClass_preproc_05.testMethod()) { return MFTestResults.Pass; } return MFTestResults.Fail; } [TestMethod] public MFTestResults Lexical_preproc_06_Test() { Log.Comment("Section 2.3 Preprocessing"); Log.Comment("Using #undef on a non-existing identifier compiles fine"); if (Lexical_TestClass_preproc_06.testMethod()) { return MFTestResults.Pass; } return MFTestResults.Fail; } [TestMethod] public MFTestResults Lexical_preproc_07_Test() { Log.Comment("Section 2.3 Preprocessing"); Log.Comment("Nested #if's"); if (Lexical_TestClass_preproc_07.testMethod()) { return MFTestResults.Pass; } return MFTestResults.Fail; } [TestMethod] public MFTestResults Lexical_preproc_15_Test() { Log.Comment("Section 2.3 Preprocessing"); Log.Comment("Verify the ! operator on #identifiers"); if (Lexical_TestClass_preproc_15.testMethod()) { return MFTestResults.Pass; } return MFTestResults.Fail; } [TestMethod] public MFTestResults Lexical_preproc_16_Test() { Log.Comment("Section 2.3 Preprocessing"); Log.Comment("Verify the ! operator on #identifiers with parenthesis"); if (Lexical_TestClass_preproc_16.testMethod()) { return MFTestResults.Pass; } return MFTestResults.Fail; } [TestMethod] public MFTestResults Lexical_preproc_17_Test() { Log.Comment("Section 2.3 Preprocessing"); Log.Comment("Verify the double ampersand operator works"); if (Lexical_TestClass_preproc_17.testMethod()) { return MFTestResults.Pass; } return MFTestResults.Fail; } [TestMethod] public MFTestResults Lexical_preproc_18_Test() { Log.Comment("Section 2.3 Preprocessing"); Log.Comment("Verify the double ampersand operator works with parentheses"); if (Lexical_TestClass_preproc_18.testMethod()) { return MFTestResults.Pass; } return MFTestResults.Fail; } [TestMethod] public MFTestResults Lexical_preproc_19_Test() { Log.Comment("Section 2.3 Preprocessing"); Log.Comment("Verify the || operator works "); if (Lexical_TestClass_preproc_19.testMethod()) { return MFTestResults.Pass; } return MFTestResults.Fail; } [TestMethod] public MFTestResults Lexical_preproc_20_Test() { Log.Comment("Section 2.3 Preprocessing"); Log.Comment("Verify the || operator works with parentheses"); if (Lexical_TestClass_preproc_20.testMethod()) { return MFTestResults.Pass; } return MFTestResults.Fail; } [TestMethod] public MFTestResults Lexical_preproc_21_Test() { Log.Comment("Section 2.3 Preprocessing"); Log.Comment("Verify the == operator works with/without parentheses"); if (Lexical_TestClass_preproc_21.testMethod()) { return MFTestResults.Pass; } return MFTestResults.Fail; } [TestMethod] public MFTestResults Lexical_preproc_22_Test() { Log.Comment("Section 2.3 Preprocessing"); Log.Comment("Verify the != operator works with/without parentheses"); if (Lexical_TestClass_preproc_22.testMethod()) { return MFTestResults.Pass; } return MFTestResults.Fail; } [TestMethod] public MFTestResults Lexical_preproc_23_Test() { Log.Comment("Section 2.3 Preprocessing"); Log.Comment("Grouping operators: ! double ampersand || != == true false"); if (Lexical_TestClass_preproc_23.testMethod()) { return MFTestResults.Pass; } return MFTestResults.Fail; } [TestMethod] public MFTestResults Lexical_preproc_24_Test() { Log.Comment("Section 2.3 Preprocessing"); Log.Comment("Verifying comments and #preprocessor items"); if (Lexical_TestClass_preproc_24.testMethod()) { return MFTestResults.Pass; } return MFTestResults.Fail; } [TestMethod] public MFTestResults Lexical_preproc_25_Test() { Log.Comment("Section 2.3 Preprocessing"); Log.Comment("Verifying comments and #preprocessor items"); if (Lexical_TestClass_preproc_25.testMethod()) { return MFTestResults.Pass; } return MFTestResults.Fail; } [TestMethod] public MFTestResults Lexical_preproc_31_Test() { Log.Comment("Section 2.3 Preprocessing"); Log.Comment("Verifying comments and #preprocessor items"); if (Lexical_TestClass_preproc_31.testMethod()) { return MFTestResults.Pass; } return MFTestResults.Fail; } [TestMethod] public MFTestResults Lexical_preproc_32_Test() { Log.Comment("Section 2.3 Preprocessing"); Log.Comment("Verify the usage of #elif"); if (Lexical_TestClass_preproc_32.testMethod()) { return MFTestResults.Pass; } return MFTestResults.Fail; } [TestMethod] public MFTestResults Lexical_preproc_39_Test() { Log.Comment("Section 2.3 Preprocessing"); Log.Comment("Verify that a # keyword (i.e. for) can be used as a #preprocessor identifier"); if (Lexical_TestClass_preproc_39.testMethod()) { return MFTestResults.Pass; } return MFTestResults.Fail; } //Compiled Test Cases public class Lexical_TestClass_pre_009 { public static int Main_old(string[] args) { int i = 2; #if while while (--i > 0) ; #endif return(i > 0 ? 1 : 0); } public static bool testMethod() { return (Main_old(null) == 0); } } public class Lexical_TestClass_pre_012 { public static int Main_old(string[] args) { int i = 6; #if True1 == true i--; #endif #if False1 == false i--; #endif #if false #error #elif True2 == True1 #elif True2 == True1 i--; #else #error #else #elif True2 == True1 #endif #if (True1 != false) && ((False1) == False2) && (true || false) i--; #else #error #if (True != false) && ((False1) == False2) && (true || false) #endif #if ((true == True1) != (false && true)) i--; #else #error ((true == True1) != (false && true)) #endif #if !(!(!!(true))) != false i--; #else #error !(!(!!(true))) != false #endif return(i > 0 ? 1 : 0); } public static bool testMethod() { return (Main_old(null) == 0); } } public class Lexical_TestClass_pre_013 { public static int Main_old(string[] args) { int i = 0; return(i > 0 ? 1 : 0); } public static bool testMethod() { return (Main_old(null) == 0); } } public class Lexical_TestClass_preproc_03 { public static void Main_old(String[] args) { Log.Comment("Starting!"); #if TESTDEF Log.Comment("Good"); #else Log.Comment("Bad"); #endif } public static bool testMethod() { Main_old(null); return true; } } public class Lexical_TestClass_preproc_04 { public static void Main_old(String[] args) { Log.Comment("Starting!"); #if TESTDEF3 Log.Comment("TESTDEF3 is defined"); #else Log.Comment("TESTDEF3 is not defined"); #endif #if TESTDEF2 Log.Comment("TESTDEF2 is defined"); #else Log.Comment("TESTDEF2 not defined"); #endif } public static bool testMethod() { Main_old(null); return true; } } #if BAR class Lexical_TestClass_preproc_05 { public static void Main_old(String[] args) { } public static bool testMethod() { Main_old(null); return true; } } #endif class Lexical_TestClass_preproc_06 { public static void Main_old(String[] args) { } public static bool testMethod() { Main_old(null); return true; } } class Lexical_TestClass_preproc_07 { public static void Main_old(String[] args) { Log.Comment("Starting:"); #if FOO3 Log.Comment("Inside FOO"); #if BAR3 Log.Comment("Inside BAR"); #else Log.Comment("Inside BAR's else"); #endif #endif } public static bool testMethod() { Main_old(null); return true; } } class Lexical_TestClass_preproc_15 { public static void Main_old(String[] args) { #if ! TEST Log.Comment("Problem"); #else Log.Comment("Good"); #endif } public static bool testMethod() { Main_old(null); return true; } } class Lexical_TestClass_preproc_16 { public static void Main_old(String[] args) { #if !(TEST) Log.Comment("Problem"); #else Log.Comment("Good"); #endif } public static bool testMethod() { Main_old(null); return true; } } class Lexical_TestClass_preproc_17 { public static void Main_old(String[] args) { #if TEST && TEST2 Log.Comment("Good"); #endif #if TEST && TEST3 Log.Comment("Problem"); #endif } public static bool testMethod() { Main_old(null); return true; } } class Lexical_TestClass_preproc_18 { public static void Main_old(String[] args) { #if (TEST && TEST2) Log.Comment("Good"); #endif #if (TEST && TEST3) Log.Comment("Problem"); #endif } public static bool testMethod() { Main_old(null); return true; } } class Lexical_TestClass_preproc_19 { public static void Main_old(String[] args) { #if TEST || TEST2 Log.Comment("Good"); #endif #if TEST3 || TEST2 Log.Comment("Good"); #endif #if TEST3 || TEST4 Log.Comment("Problem"); #endif } public static bool testMethod() { Main_old(null); return true; } } class Lexical_TestClass_preproc_20 { public static void Main_old(String[] args) { #if (TEST || TEST2) Log.Comment("Good"); #endif #if (TEST3 || TEST2) Log.Comment("Good"); #endif #if (TEST3 || TEST4) Log.Comment("Problem"); #endif } public static bool testMethod() { Main_old(null); return true; } } class Lexical_TestClass_preproc_21 { public static void Main_old(String[] args) { #if TEST == TEST2 Log.Comment("Good"); #endif #if (TEST == TEST2) Log.Comment("Good"); #endif #if TEST==TEST2 Log.Comment("Good"); #endif #if (TEST == TEST3) Log.Comment("Bad"); #endif #if TEST3 == TEST Log.Comment("Bad"); #endif } public static bool testMethod() { Main_old(null); return true; } } class Lexical_TestClass_preproc_22 { public static void Main_old(String[] args) { #if TEST != TEST2 Log.Comment("Bad"); #endif #if (TEST != TEST2) Log.Comment("Bad"); #endif #if TEST!=TEST2 Log.Comment("Bad"); #endif #if (TEST != TEST3) Log.Comment("Good"); #endif #if TEST3 != TEST Log.Comment("Good"); #endif #if TEST3!=TEST Log.Comment("Good"); #endif } public static bool testMethod() { Main_old(null); return true; } } class Lexical_TestClass_preproc_23 { public static void Main_old(String[] args) { #if (TEST && TEST2) || (TEST3 || TEST4) Log.Comment("1 - Good"); #endif #if (TEST3 == TEST4) || (TEST == TEST2) Log.Comment("2 - Good"); #endif #if (TEST != TEST3) && (TEST2 != TEST4) Log.Comment("3 - Good"); #endif #if (! TEST4) && (TEST2 == TEST) Log.Comment("4 - Good"); #endif #if (TEST == true) && (TEST2 != false) Log.Comment("5 - Good"); #endif } public static bool testMethod() { Main_old(null); return true; } } class Lexical_TestClass_preproc_24 { public static void Main_old(String[] args) { #if TEST Log.Comment("Good"); #endif } public static bool testMethod() { Main_old(null); return true; } } class Lexical_TestClass_preproc_25 { public static void Main_old(String[] args) { #if TEST Log.Comment("Good"); #endif } public static bool testMethod() { Main_old(null); return true; } } class Lexical_TestClass_preproc_31 { public static void Main_old(String[] args) { #if TEST Log.Comment("Bad"); #else Log.Comment("Good"); #endif } public static bool testMethod() { Main_old(null); return true; } } class Lexical_TestClass_preproc_32 { public static void Main_old(String[] args) { #if TEST3 Log.Comment("Bad"); #elif TEST2 && TEST Log.Comment("Good"); #endif } public static bool testMethod() { Main_old(null); return true; } } class Lexical_TestClass_preproc_39 { public static void Main_old(String[] args) { #if for for (int x = 0; x < 3; x++) Log.Comment("Worked"); #else Log.Comment("It should not be showing this!"); #endif } public static bool testMethod() { Main_old(null); return true; } } } } ================================================ FILE: Zelig/Zelig/Test/RunTime/NETMF/mscorlib/namespaces/NS_attribute_01.cs ================================================ using System; using Microsoft.SPOT.Platform.Test; [assembly:CLSCompliant(true)] class NS_TestClass_attribute_01 { public void printClassName() { Log.Comment("Class A"); } static void Main_old() {} public static bool testMethod() { Main_old(); return true; } } ================================================ FILE: Zelig/Zelig/Test/RunTime/NETMF/mscorlib/namespaces/NS_attribute_02.cs ================================================ using System; using Microsoft.SPOT.Platform.Test; [module: CLSCompliant(true)] class NS_TestClass_attribute_02 { public void printClassName() { Log.Comment("Class A"); } static void Main_old() { } public static bool testMethod() { Main_old(); return true; } } ================================================ FILE: Zelig/Zelig/Test/RunTime/NETMF/mscorlib/namespaces/NS_compunit_01A.cs ================================================ using Microsoft.SPOT.Platform.Test; class NS_TestClass_compunit_01A { public void printClassName() { Log.Comment("Class A"); } } ================================================ FILE: Zelig/Zelig/Test/RunTime/NETMF/mscorlib/namespaces/NS_compunit_01B.cs ================================================ using Microsoft.SPOT.Platform.Test; class NS_TestClass_compunit_01B { public void printClassName() { Log.Comment("Class B"); } } ================================================ FILE: Zelig/Zelig/Test/RunTime/NETMF/mscorlib/namespaces/NS_compunit_03A.cs ================================================ using Microsoft.SPOT.Platform.Test; class NS_TestClass_compunit_03A { public void printClassName() { NS_TestClass_compunit_03B cB = new NS_TestClass_compunit_03B(); cB.showName(); } public void showName() { Log.Comment("Class A"); } } ================================================ FILE: Zelig/Zelig/Test/RunTime/NETMF/mscorlib/namespaces/NS_compunit_03B.cs ================================================ using Microsoft.SPOT.Platform.Test; class NS_TestClass_compunit_03B { public void printClassName() { NS_TestClass_compunit_03 cC = new NS_TestClass_compunit_03(); cC.showName(); } public void showName() { Log.Comment("Class B"); } } ================================================ FILE: Zelig/Zelig/Test/RunTime/NETMF/mscorlib/namespaces/NS_compunit_04A.cs ================================================ using Microsoft.SPOT.Platform.Test; namespace NS_TestClass_compunit_04_first { using System; class NS_TestClass_compunit_04A { public void printClassName() { Log.Comment("Class A"); } } } ================================================ FILE: Zelig/Zelig/Test/RunTime/NETMF/mscorlib/namespaces/NS_compunit_04B.cs ================================================ using Microsoft.SPOT.Platform.Test; namespace NS_TestClass_compunit_04_second { using System; class NS_TestClass_compunit_04A { public void printClassName() { Log.Comment("Class B"); } } } ================================================ FILE: Zelig/Zelig/Test/RunTime/NETMF/mscorlib/namespaces/NS_decl_14.cs ================================================ using Microsoft.SPOT.Platform.Test; namespace NS_TestClass_decl_14_one.NS_TestClass_decl_14_two.NS_TestClass_decl_14_three { class C { public int j; } } ================================================ FILE: Zelig/Zelig/Test/RunTime/NETMF/mscorlib/namespaces/NS_decl_15.cs ================================================ using Microsoft.SPOT.Platform.Test; namespace NS_TestClass_decl_15_one.NS_TestClass_decl_15_two.NS_TestClass_decl_15_three { class C { public int j; } } ================================================ FILE: Zelig/Zelig/Test/RunTime/NETMF/mscorlib/namespaces/NamespacesTests.cs ================================================ //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // Copyright (c) Microsoft Corporation. All rights reserved. //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// using System; using System.Reflection; using Microsoft.SPOT.Platform.Test; using NS_TestClass_compunit_04_first; using NS_TestClass_compunit_04_second; using NS_TestClass_alias_10_F = NS_TestClass_alias_10_Foo.Bar; namespace Microsoft.SPOT.Platform.Tests { [CLSCompliant(false)] public class NamespacesTests : IMFTestInterface { [SetUp] public InitializeResult Initialize() { Log.Comment("Adding set up for the tests"); return InitializeResult.ReadyToGo; } [TearDown] public void CleanUp() { Log.Comment("Cleaning up after the tests"); } //Namespaces Test methods //The following tests were ported from folder current\test\cases\client\CLR\Conformance\10_classes\Namespaces //attribute_01,attribute_02,compunit_01,compunit_03,compunit_04,decl_01,decl_02,decl_03,decl_04,decl_05,decl_06,decl_08,decl_10,decl_11,decl_12,decl_13,decl_14,decl_15,decl_17,decl_20,decl_21,alias_01,alias_02,alias_03,alias_04,alias_10,alias_13,alias_14,direct_01,direct_02,direct_03,direct_05,typedecl_01,typedecl_06,typedecl_07,typedecl_08,typedecl_09,typedecl_10,typedecl_11,typedecl_12,typedecl_13,validaccess_01,validaccess_02,validaccess_03,validaccess_04,validaccess_05,contexts_025 //Test Case Calls [TestMethod] public MFTestResults NS_attribute_01_Test() { Log.Comment("Section 9.1 Compilation Units"); Log.Comment("Verify that the CLSCompliant attribute is allowed at the assembly level in a comp. unit"); if (NS_TestClass_attribute_01.testMethod()) { return MFTestResults.Pass; } return MFTestResults.Fail; } [TestMethod] public MFTestResults NS_attribute_02_Test() { Log.Comment("Section 9.1 Compilation Units"); Log.Comment("Verify that the CLSCompliant attribute is allowed at the module level in a comp. unit (cause a warning)"); if (NS_TestClass_attribute_02.testMethod()) { return MFTestResults.Pass; } return MFTestResults.Fail; } [TestMethod] public MFTestResults NS_compunit_01_Test() { Log.Comment("Section 9.1 Compilation Units"); Log.Comment("Verify that a program with multiple files depending on each other works"); if (NS_TestClass_compunit_01.testMethod()) { return MFTestResults.Pass; } return MFTestResults.Fail; } [TestMethod] public MFTestResults NS_compunit_03_Test() { Log.Comment("Section 9.1 Compilation Units"); Log.Comment("Verify three source files all requiring each other in circular fashion compiles/runs successfully"); if (NS_TestClass_compunit_03.testMethod()) { return MFTestResults.Pass; } return MFTestResults.Fail; } [TestMethod] public MFTestResults NS_compunit_04_Test() { Log.Comment("Section 9.1 Compilation Units"); Log.Comment("Two source files with their own namespaces, each have a class named A, and can be used successfully by a third file"); if (NS_TestClass_compunit_04.testMethod()) { return MFTestResults.Pass; } return MFTestResults.Fail; } [TestMethod] public MFTestResults NS_decl_01_Test() { Log.Comment("Section 9.2 Namespace Declarations"); Log.Comment("Declare the simplest namespace possible (without semi-colon at the end)"); if (NS_TestClass_decl_01.A.testMethod()) { return MFTestResults.Pass; } return MFTestResults.Fail; } [TestMethod] public MFTestResults NS_decl_02_Test() { Log.Comment("Section 9.2 Namespace Declarations"); Log.Comment("Declare the simplest namespace possible (with semi-colon at the end)"); if (NS_TestClass_decl_02.A.testMethod()) { return MFTestResults.Pass; } return MFTestResults.Fail; } [TestMethod] public MFTestResults NS_decl_03_Test() { Log.Comment("Section 9.2 Namespace Declarations"); Log.Comment("Declare a namespace inside another namespace"); if (NS_TestClass_decl_03.A.testMethod()) { return MFTestResults.Pass; } return MFTestResults.Fail; } [TestMethod] public MFTestResults NS_decl_04_Test() { Log.Comment("Section 9.2 Namespace Declarations"); Log.Comment("Declare a namespace inside another namespace (with semicolon at end of nested ns decl)"); if (NS_TestClass_decl_04.A.testMethod()) { return MFTestResults.Pass; } return MFTestResults.Fail; } [TestMethod] public MFTestResults NS_decl_05_Test() { Log.Comment("Section 9.2 Namespace Declarations"); Log.Comment("Two separately declared namespaces in one compilation unit (file)"); if (NS_TestClass_decl_05.A.testMethod()) { return MFTestResults.Pass; } return MFTestResults.Fail; } [TestMethod] public MFTestResults NS_decl_06_Test() { Log.Comment("Section 9.2 Namespace Declarations"); Log.Comment("Two separately declared namespaces in one compilation unit (file)"); if (NS_TestClass_decl_06.A.testMethod()) { return MFTestResults.Pass; } return MFTestResults.Fail; } [TestMethod] public MFTestResults NS_decl_08_Test() { Log.Comment("Section 9.2 Namespace Declarations"); Log.Comment("Access class member declared in external namespace directly when adding a Using"); if (NS_TestClass_decl_08.A.testMethod()) { return MFTestResults.Pass; } return MFTestResults.Fail; } [TestMethod] public MFTestResults NS_decl_10_Test() { Log.Comment("Section 9.2 Namespace Declarations"); Log.Comment("Namespace identifier with . in it"); if (NS_TestClass_decl_10.foo.A.testMethod()) { return MFTestResults.Pass; } return MFTestResults.Fail; } [TestMethod] public MFTestResults NS_decl_11_Test() { Log.Comment("Section 9.2 Namespace Declarations"); Log.Comment("Namespace identifier with .'s in it and underscores, etc."); if (NS_TestClass_decl_11.foo.A.testMethod()) { return MFTestResults.Pass; } return MFTestResults.Fail; } [TestMethod] public MFTestResults NS_decl_12_Test() { Log.Comment("Section 9.2 Namespace Declarations"); Log.Comment("Two separate namespace declarations contribute to same declaration space (with using)"); if (NS_TestClass_decl_12.foo.A.testMethod()) { return MFTestResults.Pass; } return MFTestResults.Fail; } [TestMethod] public MFTestResults NS_decl_13_Test() { Log.Comment("Section 9.2 Namespace Declarations"); Log.Comment("Two separate namespace declarations contribute to same declaration space (direct referencing)"); if (NS_TestClass_decl_13.foo.A.testMethod()) { return MFTestResults.Pass; } return MFTestResults.Fail; } [TestMethod] public MFTestResults NS_decl_14_Test() { Log.Comment("Section 9.2 Namespace Declarations"); Log.Comment("Two separate namespace declarations contribute to same declaration space (direct referencing)"); Log.Comment(" namespace declarations are in two different compilation units (files)"); if (NS_TestClass_decl_14.foo.A.testMethod()) { return MFTestResults.Pass; } return MFTestResults.Fail; } [TestMethod] public MFTestResults NS_decl_15_Test() { Log.Comment("Section 9.2 Namespace Declarations"); Log.Comment("Two separate namespace declarations contribute to same declaration space (with using)"); Log.Comment(" namespace declarations are in two different compilation units (files)"); if (NS_TestClass_decl_15.foo.A.testMethod()) { return MFTestResults.Pass; } return MFTestResults.Fail; } [TestMethod] public MFTestResults NS_decl_17_Test() { Log.Comment("Section 9.2 Namespace Declarations"); Log.Comment("Declare a namespace called _Foo"); if (NS_TestClass_decl_17.main.testMethod()) { return MFTestResults.Pass; } return MFTestResults.Fail; } [TestMethod] public MFTestResults NS_decl_20_Test() { Log.Comment("Section 9.2 Namespace Declarations"); Log.Comment("Declare an empty namespace"); if (NS_TestClass_decl_20.main.testMethod()) { return MFTestResults.Pass; } return MFTestResults.Fail; } [TestMethod] public MFTestResults NS_decl_21_Test() { Log.Comment("Section 9.2 Namespace Declarations"); Log.Comment("Declare ten empty nested namespaces (with and without semi-colons)"); if (NS_TestClass_decl_21.main.testMethod()) { return MFTestResults.Pass; } return MFTestResults.Fail; } [TestMethod] public MFTestResults NS_alias_01_Test() { Log.Comment("Section 9.3.1 Using alias directives "); Log.Comment("Verify simplest form of alias reference to a namespace"); if (NS_TestClass_alias_01.A.testMethod()) { return MFTestResults.Pass; } return MFTestResults.Fail; } [TestMethod] public MFTestResults NS_alias_02_Test() { Log.Comment("Section 9.3.1 Using alias directives "); Log.Comment("Verify simplest form of alias reference to a namespace with .'s"); if (NS_TestClass_alias_02.A.testMethod()) { return MFTestResults.Pass; } return MFTestResults.Fail; } [TestMethod] public MFTestResults NS_alias_03_Test() { Log.Comment("Section 9.3.1 Using alias directives "); Log.Comment("Verify simplest form of alias reference to a specific type in a namespace"); if (NS_TestClass_alias_03.A.testMethod()) { return MFTestResults.Pass; } return MFTestResults.Fail; } [TestMethod] public MFTestResults NS_alias_04_Test() { Log.Comment("Section 9.3.1 Using alias directives "); Log.Comment("Verify simplest form of alias reference to a specific type in a namespace"); if (NS_TestClass_alias_04.B.testMethod()) { return MFTestResults.Pass; } return MFTestResults.Fail; } [TestMethod] public MFTestResults NS_alias_10_Test() { Log.Comment("Section 9.3.1 Using alias directives "); Log.Comment("Third code example in 9.3.1 - unique alias identifiers"); if (NS_TestClass_alias_10.main.testMethod()) { return MFTestResults.Pass; } return MFTestResults.Fail; } [TestMethod] public MFTestResults NS_alias_13_Test() { Log.Comment("Section 9.3.1 Using alias directives "); Log.Comment("A using-alias-directive can create an alias for the namespace in which it appears"); if (NS_TestClass_alias_13.main.testMethod()) { return MFTestResults.Pass; } return MFTestResults.Fail; } [TestMethod] public MFTestResults NS_alias_14_Test() { Log.Comment("Section 9.3.1 Using namespace directives "); Log.Comment("A using-alias-directive can create an alias for a type declared within the ns in which it appears "); if (NS_TestClass_alias_14.main.testMethod()) { return MFTestResults.Pass; } return MFTestResults.Fail; } [TestMethod] public MFTestResults NS_direct_01_Test() { Log.Comment("Section 9.3.2 Using namespace directives "); Log.Comment("The members of a namespace can be accessed directly post using "); if (NS_TestClass_direct_01.main.testMethod()) { return MFTestResults.Pass; } return MFTestResults.Fail; } [TestMethod] public MFTestResults NS_direct_02_Test() { Log.Comment("Section 9.3.2 Using namespace directives "); Log.Comment("A newly declared class will hide a class (with the same name) brought in with a using directive"); if (NS_TestClass_direct_02.main.testMethod()) { return MFTestResults.Pass; } return MFTestResults.Fail; } [TestMethod] public MFTestResults NS_direct_03_Test() { Log.Comment("Section 9.3.2 Using namespace directives "); Log.Comment("Names imported by using-namespace-directive are hidden by same-named members "); if (NS_TestClass_direct_03.main.testMethod()) { return MFTestResults.Pass; } return MFTestResults.Fail; } [TestMethod] public MFTestResults NS_direct_05_Test() { Log.Comment("Section 9.3.2 Using namespace directives "); Log.Comment("Ambiguous reference is overridden by using alias statement"); if (NS_TestClass_direct_05.main.testMethod()) { return MFTestResults.Pass; } return MFTestResults.Fail; } [TestMethod] public MFTestResults NS_typedecl_01_Test() { Log.Comment("Section 9.5 Type declarations "); Log.Comment("Ambiguous reference is overridden by using alias statement"); if (NS_TestClass_typedecl_01.testMethod()) { return MFTestResults.Pass; } return MFTestResults.Fail; } [TestMethod] public MFTestResults NS_typedecl_06_Test() { Log.Comment("Section 9.5 Type declarations "); Log.Comment("Declaring a class member as public is okay"); if (NS_TestClass_typedecl_06.testMethod()) { return MFTestResults.Pass; } return MFTestResults.Fail; } [TestMethod] public MFTestResults NS_typedecl_07_Test() { Log.Comment("Section 9.5 Type declarations "); Log.Comment("Declaring a class member as protected internal is okay"); if (NS_TestClass_typedecl_07.testMethod()) { return MFTestResults.Pass; } return MFTestResults.Fail; } [TestMethod] public MFTestResults NS_typedecl_08_Test() { Log.Comment("Section 9.5 Type declarations "); Log.Comment("Declaring a class member as protected is okay"); if (NS_TestClass_typedecl_08.testMethod()) { return MFTestResults.Pass; } return MFTestResults.Fail; } [TestMethod] public MFTestResults NS_typedecl_09_Test() { Log.Comment("Section 9.5 Type declarations "); Log.Comment("Declaring a class member as internal is okay"); if (NS_TestClass_typedecl_09.testMethod()) { return MFTestResults.Pass; } return MFTestResults.Fail; } [TestMethod] public MFTestResults NS_typedecl_10_Test() { Log.Comment("Section 9.5 Type declarations "); Log.Comment("Declaring a class member as private is okay"); if (NS_TestClass_typedecl_10.testMethod()) { return MFTestResults.Pass; } return MFTestResults.Fail; } [TestMethod] public MFTestResults NS_typedecl_11_Test() { Log.Comment("Section 9.5 Type declarations "); Log.Comment("Declaring a struct member as public is okay"); if (NS_TestClass_typedecl_11.testMethod()) { return MFTestResults.Pass; } return MFTestResults.Fail; } [TestMethod] public MFTestResults NS_typedecl_12_Test() { Log.Comment("Section 9.5 Type declarations "); Log.Comment("Declaring a struct member as internal is okay"); if (NS_TestClass_typedecl_12.testMethod()) { return MFTestResults.Pass; } return MFTestResults.Fail; } [TestMethod] public MFTestResults NS_typedecl_13_Test() { Log.Comment("Section 9.5 Type declarations "); Log.Comment("Declaring a struct member as private is okay"); if (NS_TestClass_typedecl_13.testMethod()) { return MFTestResults.Pass; } return MFTestResults.Fail; } [TestMethod] public MFTestResults NS_validaccess_01_Test() { Log.Comment("Section 9.5 Type declarations "); Log.Comment("Verify all valid accessibility levels for class declarations are allowed"); if (NS_TestClass_validaccess_01.testMethod()) { return MFTestResults.Pass; } return MFTestResults.Fail; } [TestMethod] public MFTestResults NS_validaccess_02_Test() { Log.Comment("Section 9.5 Type declarations "); Log.Comment("Verify all valid accessibility levels for struct declarations are allowed"); if (NS_TestClass_validaccess_02.testMethod()) { return MFTestResults.Pass; } return MFTestResults.Fail; } [TestMethod] public MFTestResults NS_validaccess_03_Test() { Log.Comment("Section 9.5 Type declarations "); Log.Comment("Verify all valid accessibility levels for interface declarations are allowed"); if (NS_TestClass_validaccess_03.testMethod()) { return MFTestResults.Pass; } return MFTestResults.Fail; } [TestMethod] public MFTestResults NS_validaccess_04_Test() { Log.Comment("Section 9.5 Type declarations "); Log.Comment("Verify all valid accessibility levels for enum declarations are allowed"); if (NS_TestClass_validaccess_04.testMethod()) { return MFTestResults.Pass; } return MFTestResults.Fail; } [TestMethod] public MFTestResults NS_validaccess_05_Test() { Log.Comment("Section 9.5 Type declarations "); Log.Comment("Verify all valid accessibility levels for delegate declarations are allowed"); if (NS_TestClass_validaccess_05.testMethod()) { return MFTestResults.Pass; } return MFTestResults.Fail; } [TestMethod] public MFTestResults NS_contexts_025_Test() { Log.Comment("Verify that you can use the qualifier in a cref attribute of xml docs tag"); if (NS_TestClass_contexts_025.Test.testMethod()) { return MFTestResults.Pass; } return MFTestResults.Fail; } class NS_TestClass_compunit_01 { public static void Main_old(String[] args) { NS_TestClass_compunit_01A cA = new NS_TestClass_compunit_01A(); NS_TestClass_compunit_01B cB = new NS_TestClass_compunit_01B(); cA.printClassName(); cB.printClassName(); Log.Comment("Class C"); } public static bool testMethod() { Main_old(null); return true; } } class NS_TestClass_compunit_04 { public static void Main_old(String[] args) { NS_TestClass_compunit_04_first.NS_TestClass_compunit_04A cA = new NS_TestClass_compunit_04_first.NS_TestClass_compunit_04A(); NS_TestClass_compunit_04_second.NS_TestClass_compunit_04A cB = new NS_TestClass_compunit_04_second.NS_TestClass_compunit_04A(); cA.printClassName(); cB.printClassName(); Log.Comment("Class C"); } public static bool testMethod() { Main_old(null); return true; } } //Compiled Test Cases public class NS_TestClass_typedecl_01_A { } internal class B { } class NS_TestClass_typedecl_01 { public static int Main_old() { return 0; } public static bool testMethod() { return (Main_old() == 0); } } class NS_TestClass_typedecl_06_A { public int a; } class NS_TestClass_typedecl_06 { public static int Main_old() { return 0; } public static bool testMethod() { return (Main_old() == 0); } } class NS_TestClass_typedecl_07_A { protected internal int a; } class NS_TestClass_typedecl_07 { public static int Main_old() { return 0; } public static bool testMethod() { return (Main_old() == 0); } } class NS_TestClass_typedecl_08_A { protected int a; } class NS_TestClass_typedecl_08 { public static int Main_old() { return 0; } public static bool testMethod() { return (Main_old() == 0); } } class NS_TestClass_typedecl_09_A { internal int a; } class NS_TestClass_typedecl_09 { public static int Main_old() { return 0; } public static bool testMethod() { return (Main_old() == 0); } } class NS_TestClass_typedecl_10_A { private int a; public void TheMethod() { // This code is here basically to avoid any "not using a" compiler warnings a = 5; if (a == 5) a++; } } class NS_TestClass_typedecl_10 { public static int Main_old() { return 0; } public static bool testMethod() { return (Main_old() == 0); } } struct NS_TestClass_typedecl_11_A { public int a; } class NS_TestClass_typedecl_11 { public static int Main_old() { return 0; } public static bool testMethod() { return (Main_old() == 0); } } struct NS_TestClass_typedecl_12_A { internal int a; } class NS_TestClass_typedecl_12 { public static int Main_old() { return 0; } public static bool testMethod() { return (Main_old() == 0); } } struct NS_TestClass_typedecl_13_A { private int a; public void MyMethod() { // This code is here to avoid the "a not used" compiler warning a = 5; if (a == 5) a++; } } class NS_TestClass_typedecl_13 { public static int Main_old() { return 0; } public static bool testMethod() { return (Main_old() == 0); } } } } class NS_TestClass_compunit_03 { public void printClassName() { NS_TestClass_compunit_03A cA = new NS_TestClass_compunit_03A(); cA.showName(); } public void showName() { Log.Comment("Class C"); } public static void Main_old(String[] args) { NS_TestClass_compunit_03A mainA = new NS_TestClass_compunit_03A(); NS_TestClass_compunit_03B mainB = new NS_TestClass_compunit_03B(); NS_TestClass_compunit_03 mainC = new NS_TestClass_compunit_03(); mainA.printClassName(); mainB.printClassName(); mainC.printClassName(); } public static bool testMethod() { Main_old(null); return true; } } namespace NS_TestClass_decl_01 { using System; class A { public static void Main_old(String[] args) { Log.Comment("This worked!"); } public static bool testMethod() { Main_old(null); return true; } } } namespace NS_TestClass_decl_02 { using System; class A { public static void Main_old(String[] args) { Log.Comment("This worked!"); } public static bool testMethod() { Main_old(null); return true; } } } namespace NS_TestClass_decl_03 { using System; namespace innertest { class B { public int i; } } class A { public static void Main_old(String[] args) { innertest.B b = new innertest.B(); b.i = 3; Log.Comment((b.i).ToString()); } public static bool testMethod() { Main_old(null); return true; } } } namespace NS_TestClass_decl_04 { using System; namespace innertest { class B { public int i; } }; class A { public static void Main_old(String[] args) { innertest.B b = new innertest.B(); b.i = 3; Log.Comment((b.i).ToString()); } public static bool testMethod() { Main_old(null); return true; } } } namespace NS_TestClass_decl_05_other { class B { public int i; } } namespace NS_TestClass_decl_05 { using System; class A { public static void Main_old(String[] args) { NS_TestClass_decl_05_other.B b = new NS_TestClass_decl_05_other.B(); b.i = 500; Log.Comment((b.i).ToString()); } public static bool testMethod() { Main_old(null); return true; } } } namespace NS_TestClass_decl_06_other { namespace inothertest { class B { public int i; } } } namespace NS_TestClass_decl_06 { using System; class A { public static void Main_old(String[] args) { NS_TestClass_decl_06_other.inothertest.B b = new NS_TestClass_decl_06_other.inothertest.B(); b.i = 500; Log.Comment((b.i).ToString()); } public static bool testMethod() { Main_old(null); return true; } } } namespace other { class B { public int i; } } namespace NS_TestClass_decl_08 { using System; using other; class A { public static void Main_old(String[] args) { B b = new B(); b.i = 3; Log.Comment((b.i).ToString()); } public static bool testMethod() { Main_old(null); return true; } } } namespace NS_TestClass_decl_10_one.NS_TestClass_decl_10_two.NS_TestClass_decl_10_three { class B { public int i; } } namespace NS_TestClass_decl_10.foo { using System; class A { public static void Main_old(String[] args) { NS_TestClass_decl_10_one.NS_TestClass_decl_10_two.NS_TestClass_decl_10_three.B b = new NS_TestClass_decl_10_one.NS_TestClass_decl_10_two.NS_TestClass_decl_10_three.B(); b.i = 500; Log.Comment((b.i).ToString()); } public static bool testMethod() { Main_old(null); return true; } } } namespace NS_TestClass_decl_11_one._two._three_ { class B { public int i; } } namespace ___space.word_ { class C { public int j; } } namespace NS_TestClass_decl_11.foo { using System; using ___space.word_; class A { public static void Main_old(String[] args) { NS_TestClass_decl_11_one._two._three_.B b = new NS_TestClass_decl_11_one._two._three_.B(); C c = new C(); b.i = 500; c.j = 300; Log.Comment((b.i).ToString()); Log.Comment((c.j).ToString()); } public static bool testMethod() { Main_old(null); return true; } } } namespace NS_TestClass_decl_12_one.NS_TestClass_decl_12_two.NS_TestClass_decl_12_three { class B { public int i; } } namespace NS_TestClass_decl_12_one.NS_TestClass_decl_12_two.NS_TestClass_decl_12_three { class C { public int j; } } namespace NS_TestClass_decl_12.foo { using System; using NS_TestClass_decl_12_one.NS_TestClass_decl_12_two.NS_TestClass_decl_12_three; class A { public static void Main_old(String[] args) { B b = new B(); C c = new C(); b.i = 500; c.j = 300; Log.Comment((b.i).ToString()); Log.Comment((c.j).ToString()); } public static bool testMethod() { Main_old(null); return true; } } } namespace NS_TestClass_decl_13_one.NS_TestClass_decl_13_two.NS_TestClass_decl_13_three { class B { public int i; } } namespace NS_TestClass_decl_13_one.NS_TestClass_decl_13_two.NS_TestClass_decl_13_three { class C { public int j; } } namespace NS_TestClass_decl_13.foo { using System; class A { public static void Main_old(String[] args) { NS_TestClass_decl_13_one.NS_TestClass_decl_13_two.NS_TestClass_decl_13_three.B b = new NS_TestClass_decl_13_one.NS_TestClass_decl_13_two.NS_TestClass_decl_13_three.B(); NS_TestClass_decl_13_one.NS_TestClass_decl_13_two.NS_TestClass_decl_13_three.C c = new NS_TestClass_decl_13_one.NS_TestClass_decl_13_two.NS_TestClass_decl_13_three.C(); b.i = 500; c.j = 300; Log.Comment((b.i).ToString()); Log.Comment((c.j).ToString()); } public static bool testMethod() { Main_old(null); return true; } } } namespace NS_TestClass_decl_14_one.NS_TestClass_decl_14_two.NS_TestClass_decl_14_three { class B { public int i; } } namespace NS_TestClass_decl_14.foo { using System; class A { public static void Main_old(String[] args) { NS_TestClass_decl_14_one.NS_TestClass_decl_14_two.NS_TestClass_decl_14_three.B b = new NS_TestClass_decl_14_one.NS_TestClass_decl_14_two.NS_TestClass_decl_14_three.B(); NS_TestClass_decl_14_one.NS_TestClass_decl_14_two.NS_TestClass_decl_14_three.C c = new NS_TestClass_decl_14_one.NS_TestClass_decl_14_two.NS_TestClass_decl_14_three.C(); b.i = 500; c.j = 300; Log.Comment((b.i).ToString()); Log.Comment((c.j).ToString()); } public static bool testMethod() { Main_old(null); return true; } } } namespace NS_TestClass_decl_15_one.NS_TestClass_decl_15_two.NS_TestClass_decl_15_three { class B { public int i; } } namespace NS_TestClass_decl_15.foo { using System; using NS_TestClass_decl_15_one.NS_TestClass_decl_15_two.NS_TestClass_decl_15_three; class A { public static void Main_old(String[] args) { B b = new B(); C c = new C(); b.i = 500; c.j = 300; Log.Comment((b.i).ToString()); Log.Comment((c.j).ToString()); } public static bool testMethod() { Main_old(null); return true; } } } namespace NS_TestClass_decl_17_Foo { class A { public void print() { Log.Comment("Test"); } } } namespace NS_TestClass_decl_17 { class main { public static void Main_old() { NS_TestClass_decl_17_Foo.A a = new NS_TestClass_decl_17_Foo.A(); a.print(); } public static bool testMethod() { Main_old(); return true; } } } namespace NS_TestClass_decl_20_test { } namespace NS_TestClass_decl_20 { class main { public static void Main_old() {} public static bool testMethod() { Main_old(); return true; } } } namespace NS_TestClass_decl_21_test { namespace test2 { namespace test3 { namespace test4 { namespace test5 { namespace test6 { namespace test7 { namespace test8 { namespace test9 { namespace test10 { class TheClass { public void SayHello() { Log.Comment("Hello"); } } } }; }; } } }; }; } }; } namespace NS_TestClass_decl_21 { class main { public static void Main_old() { NS_TestClass_decl_21_test.test2.test3.test4.test5.test6.test7.test8.test9.test10.TheClass tc; tc = new NS_TestClass_decl_21_test.test2.test3.test4.test5.test6.test7.test8.test9.test10.TheClass(); tc.SayHello(); } public static bool testMethod() { Main_old(); return true; } } } namespace NS_TestClass_alias_01_externalnamespace { class B { public int i; } } namespace NS_TestClass_alias_01 { using System; using en = NS_TestClass_alias_01_externalnamespace; class A { public static void Main_old(String[] args) { en.B b = new en.B(); b.i = 3; Log.Comment((b.i).ToString()); } public static bool testMethod() { Main_old(null); return true; } } } namespace NS_TestClass_alias_02_test.nspace { class B { public int i; } } namespace NS_TestClass_alias_02 { using System; using tn = NS_TestClass_alias_02_test.nspace; class A { public static void Main_old(String[] args) { tn.B b = new tn.B(); b.i = 3; Log.Comment((b.i).ToString()); } public static bool testMethod() { Main_old(null); return true; } } } namespace NS_TestClass_alias_03_test.nspace { class B { public int i; } } namespace NS_TestClass_alias_03 { using System; using tn = NS_TestClass_alias_03_test.nspace.B; class A { public static void Main_old(String[] args) { tn b = new tn(); b.i = 3; Log.Comment((b.i).ToString()); } public static bool testMethod() { Main_old(null); return true; } } } namespace NS_TestClass_alias_04_Foo.Bar { class A { } } namespace NS_TestClass_alias_04 { using F = NS_TestClass_alias_04_Foo.Bar; using System; class B : F.A { public static void Main_old(String[] args) { Log.Comment("Worked!"); } public static bool testMethod() { Main_old(null); return true; } } } namespace NS_TestClass_alias_10_Foo.Bar { class A {} } namespace NS_TestClass_alias_10_Baz { class B : NS_TestClass_alias_10_F.A {} } namespace NS_TestClass_alias_10 { using System; class C : NS_TestClass_alias_10_F.A {} class main { public static int Main_old() { return 0; } public static bool testMethod() { return (Main_old() == 0); } } } namespace NS_TestClass_alias_13 { using tns = NS_TestClass_alias_13; using System; class main { public static int Main_old() { return 0; } public static bool testMethod() { return (Main_old() == 0); } } } namespace NS_TestClass_alias_14 { using tns = NS_TestClass_alias_14.main; using System; class main { public static int Main_old() { return 0; } public static bool testMethod() { return (Main_old() == 0); } } } namespace NS_TestClass_direct_01_Foo.Bar { class A { } } namespace NS_TestClass_direct_01 { using NS_TestClass_direct_01_Foo.Bar; using System; class B : A { } class main { public static int Main_old() { return 0; } public static bool testMethod() { return (Main_old() == 0); } } } namespace NS_TestClass_direct_02_Foo.Bar { class A { public void showMessage() { Log.Comment("Foo.Bar.A"); } } } namespace NS_TestClass_direct_02 { using NS_TestClass_direct_02_Foo.Bar; using System; class A { public void showMessage() { Log.Comment("testns.A"); } } class main { public static void Main_old() { A a = new A(); a.showMessage(); } public static bool testMethod() { Main_old(); return true; } } } namespace NS_TestClass_direct_03_Foo.Bar { class A { } } namespace NS_TestClass_direct_03 { using NS_TestClass_direct_03_Foo.Bar; using System; class A { public int i; } class main { public static int Main_old() { A a = new A(); a.i = 25; Log.Comment("This works!"); return 0; } public static bool testMethod() { return (Main_old() == 0); } } } namespace NS_TestClass_direct_05_Foo { class A { } } namespace NS_TestClass_direct_05_Bar { class A { } } namespace NS_TestClass_direct_05 { using NS_TestClass_direct_05_Foo; using NS_TestClass_direct_05_Bar; using A = NS_TestClass_direct_05_Foo.A; using System; class main { public static int Main_old() { A a = new A(); Log.Comment("This works!"); return 0; } public static bool testMethod() { return (Main_old() == 0); } } } class C1 { } public class C2 { } internal class C3 { } namespace N { class C4 { } public class C5 { } internal class C6 { } } class C { class C7 { } public class C8 { } protected internal class C9 { } protected class C10 { } internal class C11 { } private class C12 { } } struct S { class C13 { } public class C14 { } internal class C15 { } private class C16 { } } class NS_TestClass_validaccess_01 { static void Main_old() { } public static bool testMethod() { Main_old(); return true; } } struct S1 { } public struct S2 { } internal struct S3 { } namespace N { struct S4 { } public struct S5 { } internal struct S6 { } } class C_02 { struct S7 { } public struct S8 { } protected internal struct S9 { } protected struct S10 { } internal struct S11 { } private struct S12 { } } struct S_02 { struct S13 { } public struct S14 { } internal struct S15 { } private struct S16 { } } class NS_TestClass_validaccess_02 { static void Main_old() { } public static bool testMethod() { Main_old(); return true; } } interface I1 { } public interface I2 { } internal interface I3 { } namespace N1 { interface I4 { } public interface I5 { } internal interface I6 { } } class C1_03 { interface I7 { } public interface I8 { } protected internal interface I9 { } protected interface I10 { } internal interface I11 { } private interface I12 { } } struct S1_03 { interface I13 { } public interface I14 { } internal interface I15 { } private interface I16 { } } class NS_TestClass_validaccess_03 { static void Main_old() { } public static bool testMethod() { Main_old(); return true; } } enum E1 { } public enum E2 { } internal enum E3 { } namespace N1 { enum E4 { } public enum E5 { } internal enum E6 { } } class C1_04 { enum E7 { } public enum E8 { } protected internal enum E9 { } protected enum E10 { } internal enum E11 { } private enum E12 { } } struct S1_04 { enum E13 { } public enum E14 { } internal enum E15 { } private enum E16 { } } class NS_TestClass_validaccess_04 { static void Main_old() { } public static bool testMethod() { Main_old(); return true; } } delegate void D1(); public delegate void D2(); internal delegate void D3(); namespace N1 { delegate void D4(); public delegate void D5(); internal delegate void D6(); } class C1_05 { delegate void D7(); public delegate void D8(); protected internal delegate void D9(); protected delegate void D10(); internal delegate void D11(); private delegate void D12(); } struct S1_05 { delegate void D13(); public delegate void D14(); internal delegate void D15(); private delegate void D16(); } class NS_TestClass_validaccess_05 { static void Main_old() { } public static bool testMethod() { Main_old(); return true; } } namespace NS_TestClass_contexts_025 { class Test { /// public static void M1() { throw new System.Exception(); } static int Main_old() { try { NS_TestClass_contexts_025.Test.M1(); } catch { return 0; } return 1; } public static bool testMethod() { return (Main_old() == 0); } } } ================================================ FILE: Zelig/Zelig/Test/RunTime/NETMF/mscorlib/statements/StatementsTests.cs ================================================ //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // Copyright (c) Microsoft Corporation. All rights reserved. //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// using System; using System.Reflection; using Microsoft.SPOT.Platform.Test; namespace Microsoft.SPOT.Platform.Tests { public class StatementsTests : IMFTestInterface { [SetUp] public InitializeResult Initialize() { Log.Comment("Adding set up for the tests"); return InitializeResult.ReadyToGo; } [TearDown] public void CleanUp() { Log.Comment("Cleaning up after the tests"); } //Statements Test methods //The following tests were ported from folder current\test\cases\client\CLR\Conformance\10_classes\Statements //Label_001,Label_002,Label_004,Decl_001,Decl_002,Decl_003,Decl_004,Decl_007,Decl_009,Decl_010,Decl_012,Decl_014,Decl_016,Block_001,Empty_001,Expr_002,Expr_003,Expr_004,Expr_006,if_001,if_003,if_005,if_007,if_009,switch_001,switch_002,switch_003,switch_004,switch_005,switch_006,switch_007,switch_010,switch_012,switch_013,switch_015,switch_016,switch_017,switch_018,switch_019,switch_023,switch_030,switch_031,switch_032,switch_033,switch_034,switch_035,switch_036,switch_037,switch_038,switch_039,switch_040,switch_041,switch_042,switch_044,switch_047,switch_049,switch_string_001,dowhile_001,dowhile_002,dowhile_003,dowhile_004,dowhile_005,dowhile_006,for_001,for_003,for_004,for_006,for_007,for_008,for_009,for_010,for_011,for_013,for_014,char_in_string_s01,char_in_string_ex01,while_001,while_002,while_003,while_004,while_005,while_006,break_001,break_002,break_003,break_006,break_007,break_010,continue_001,continue_002,continue_006,continue_007,continue_010,goto_001,goto_008,goto_009,goto_010,goto_014,goto_017,goto_018,return_001,return_004,return_006,return_008,return_009,return_010,return_013,return_014,throw_001,throw_005,trycatch_001,trycatch_006,trycatch_007,tryfinally_001,tryfinally_002,tryfinally_003,tryfinally_004,tryfinally_006,tryfinally_007,tryfinally_008,tryfinally_009,tryfinally_010,tryfinally_011,tryfinally_012,tryfinally_013,Using_001,Using_002,Using_003,Using_005,Using_009,Using_010,Using_011,Using_012,Using_013,Using_014,Using_015,Using_017,Using_018,lock001,lock003,lock004,lock005,lock007,enum_002 //Test Case Calls [TestMethod] public MFTestResults Statements_Label_001_Test() { Log.Comment("Label_001.sc"); Log.Comment("Make sure labels can be declared"); if (Statements_TestClass_Label_001.testMethod()) { return MFTestResults.Pass; } return MFTestResults.Fail; } [TestMethod] public MFTestResults Statements_Label_002_Test() { Log.Comment("Label_002.sc"); Log.Comment("Make sure labels can be referenced. Assumes 'goto'"); if (Statements_TestClass_Label_002.testMethod()) { return MFTestResults.Pass; } return MFTestResults.Fail; } [TestMethod] public MFTestResults Statements_Label_004_Test() { Log.Comment("Label_004.sc"); Log.Comment("Make sure labels can be associated with an empty statement"); if (Statements_TestClass_Label_004.testMethod()) { return MFTestResults.Pass; } return MFTestResults.Fail; } [TestMethod] public MFTestResults Statements_Decl_001_Test() { Log.Comment("Decl_001.sc"); Log.Comment("Declare a local variable of an intrinsic type"); if (Statements_TestClass_Decl_001.testMethod()) { return MFTestResults.Pass; } return MFTestResults.Fail; } [TestMethod] public MFTestResults Statements_Decl_002_Test() { Log.Comment("Decl_002.sc"); Log.Comment("Declare a local variable of an intrinsic type and initialize it"); if (Statements_TestClass_Decl_002.testMethod()) { return MFTestResults.Pass; } return MFTestResults.Fail; } [TestMethod] public MFTestResults Statements_Decl_003_Test() { Log.Comment("Decl_003.sc"); Log.Comment("Declare a local variable of an intrinsic type and initialize it"); Log.Comment("with an expression."); if (Statements_TestClass_Decl_003.testMethod()) { return MFTestResults.Pass; } return MFTestResults.Fail; } [TestMethod] public MFTestResults Statements_Decl_004_Test() { Log.Comment("Decl_004.sc"); Log.Comment("Declare a local variable of an external object type"); if (Statements_TestClass_Decl_004.testMethod()) { return MFTestResults.Pass; } return MFTestResults.Fail; } [TestMethod] public MFTestResults Statements_Decl_007_Test() { Log.Comment("Decl_007.sc"); Log.Comment("Declare a series of local variables of an intrinsic type with commas"); if (Statements_TestClass_Decl_007.testMethod()) { return MFTestResults.Pass; } return MFTestResults.Fail; } [TestMethod] public MFTestResults Statements_Decl_009_Test() { Log.Comment("Decl_009.sc"); Log.Comment("Declare a series of local variables of an intrinsic type with commas and"); Log.Comment("initial assignments."); if (Statements_TestClass_Decl_009.testMethod()) { return MFTestResults.Pass; } return MFTestResults.Fail; } [TestMethod] public MFTestResults Statements_Decl_010_Test() { Log.Comment("Decl_010.sc"); Log.Comment("Declare a local variable of an intrinsic type as an array"); if (Statements_TestClass_Decl_010.testMethod()) { return MFTestResults.Pass; } return MFTestResults.Fail; } [TestMethod] public MFTestResults Statements_Decl_012_Test() { Log.Comment("Decl_012.sc"); Log.Comment("Declare a local variable of an intrinsic type as an array, allocate and reference it."); if (Statements_TestClass_Decl_012.testMethod()) { return MFTestResults.Pass; } return MFTestResults.Fail; } [TestMethod] public MFTestResults Statements_Decl_014_Test() { Log.Comment("Decl_014.sc"); Log.Comment("Declare a local variable of an intrinsic type as an initialized array"); if (Statements_TestClass_Decl_014.testMethod()) { return MFTestResults.Pass; } return MFTestResults.Fail; } [TestMethod] public MFTestResults Statements_Decl_016_Test() { Log.Comment("Decl_016.sc"); Log.Comment("Correctly declare a local variable of a type that has no default constructor"); Log.Comment("as an array."); if (Statements_TestClass_Decl_016.testMethod()) { return MFTestResults.Pass; } return MFTestResults.Fail; } [TestMethod] public MFTestResults Statements_Block_001_Test() { Log.Comment("Block_001.sc"); Log.Comment("Statements_TestClass_? Several types of statement blocks. Statement blocks"); Log.Comment("are so fundamental, that most can be tested in one pass."); Log.Comment("Note that by the nature of this code, many warnings"); Log.Comment("could/should be generated about items that are never reached."); if (Statements_TestClass_Block_001.testMethod()) { return MFTestResults.Pass; } return MFTestResults.Fail; } [TestMethod] public MFTestResults Statements_Empty_001_Test() { Log.Comment("Empty_001.sc"); Log.Comment("Statements_TestClass_? Several scenarios for empty statement. Emtpy statements"); Log.Comment("are so fundamental, that most can be tested in one pass."); Log.Comment("Note that by the nature of this code, many warnings"); Log.Comment("could/should be generated about items that are never reached."); if (Statements_TestClass_Empty_001.testMethod()) { return MFTestResults.Pass; } return MFTestResults.Fail; } [TestMethod] public MFTestResults Statements_Expr_002_Test() { Log.Comment("Expr_002.sc"); Log.Comment("Use an expression with side effects."); if (Statements_TestClass_Expr_002.testMethod()) { return MFTestResults.Pass; } return MFTestResults.Fail; } [TestMethod] public MFTestResults Statements_Expr_003_Test() { Log.Comment("Expr_003.sc"); Log.Comment("Use an expression with side effects and multiple l-values."); if (Statements_TestClass_Expr_003.testMethod()) { return MFTestResults.Pass; } return MFTestResults.Fail; } [TestMethod] public MFTestResults Statements_Expr_004_Test() { Log.Comment("Expr_004.sc"); Log.Comment("Run a quick test of common operator/assignment combos"); if (Statements_TestClass_Expr_004.testMethod()) { return MFTestResults.Pass; } return MFTestResults.Fail; } [TestMethod] public MFTestResults Statements_Expr_006_Test() { Log.Comment(" complex assignment"); if (Statements_TestClass_Expr_006.testMethod()) { return MFTestResults.Pass; } return MFTestResults.Fail; } [TestMethod] public MFTestResults Statements_if_001_Test() { Log.Comment("if_001.sc"); Log.Comment("Simple boolean if with a single statement"); if (Statements_TestClass_if_001.testMethod()) { return MFTestResults.Pass; } return MFTestResults.Fail; } [TestMethod] public MFTestResults Statements_if_003_Test() { Log.Comment("if_003.sc"); Log.Comment("Simple boolean if with a block statement"); if (Statements_TestClass_if_003.testMethod()) { return MFTestResults.Pass; } return MFTestResults.Fail; } [TestMethod] public MFTestResults Statements_if_005_Test() { Log.Comment("if_005.sc"); Log.Comment("Simple boolean if with a single statement and else"); if (Statements_TestClass_if_005.testMethod()) { return MFTestResults.Pass; } return MFTestResults.Fail; } [TestMethod] public MFTestResults Statements_if_007_Test() { Log.Comment("if_007.sc"); Log.Comment("Simple boolean if with a block statement"); if (Statements_TestClass_if_007.testMethod()) { return MFTestResults.Pass; } return MFTestResults.Fail; } [TestMethod] public MFTestResults Statements_if_009_Test() { Log.Comment("if_009.sc"); Log.Comment("Nest ifs with elses without blocks. Statements_TestClass_? that the 'else' ambiguity from"); Log.Comment("C/C++ is handled the same way (else bound to closest if)"); if (Statements_TestClass_if_009.testMethod()) { return MFTestResults.Pass; } return MFTestResults.Fail; } [TestMethod] public MFTestResults Statements_switch_001_Test() { Log.Comment("switch_001.sc"); Log.Comment("Empty switch"); if (Statements_TestClass_switch_001.testMethod()) { return MFTestResults.Pass; } return MFTestResults.Fail; } [TestMethod] public MFTestResults Statements_switch_002_Test() { Log.Comment("switch_002.sc"); Log.Comment("Default only switch"); if (Statements_TestClass_switch_002.testMethod()) { return MFTestResults.Pass; } return MFTestResults.Fail; } [TestMethod] public MFTestResults Statements_switch_003_Test() { Log.Comment("switch_003.sc"); Log.Comment("Switch with single case without break - no default"); if (Statements_TestClass_switch_003.testMethod()) { return MFTestResults.Pass; } return MFTestResults.Fail; } [TestMethod] public MFTestResults Statements_switch_004_Test() { Log.Comment("switch_004.sc"); Log.Comment("Switch with one case, using break"); if (Statements_TestClass_switch_004.testMethod()) { return MFTestResults.Pass; } return MFTestResults.Fail; } [TestMethod] public MFTestResults Statements_switch_005_Test() { Log.Comment("switch_005.sc"); Log.Comment("Switch with two cases, using break"); if (Statements_TestClass_switch_005.testMethod()) { return MFTestResults.Pass; } return MFTestResults.Fail; } [TestMethod] public MFTestResults Statements_switch_006_Test() { Log.Comment("switch_006.sc"); Log.Comment("Switch with one case and a default"); if (Statements_TestClass_switch_006.testMethod()) { return MFTestResults.Pass; } return MFTestResults.Fail; } [TestMethod] public MFTestResults Statements_switch_007_Test() { Log.Comment("switch_007.sc"); Log.Comment("Switch with two cases and a default"); if (Statements_TestClass_switch_007.testMethod()) { return MFTestResults.Pass; } return MFTestResults.Fail; } [TestMethod] public MFTestResults Statements_switch_010_Test() { Log.Comment("switch_010.sc"); Log.Comment("Switch with a const variable in a case"); if (Statements_TestClass_switch_010.testMethod()) { return MFTestResults.Pass; } return MFTestResults.Fail; } [TestMethod] public MFTestResults Statements_switch_012_Test() { Log.Comment("switch_012.sc"); Log.Comment("Multiple case labels"); if (Statements_TestClass_switch_012.testMethod()) { return MFTestResults.Pass; } return MFTestResults.Fail; } [TestMethod] public MFTestResults Statements_switch_013_Test() { Log.Comment("switch_013.sc"); Log.Comment("test goto all over"); Log.Comment("Expected Output"); if (Statements_TestClass_switch_013.testMethod()) { return MFTestResults.Pass; } return MFTestResults.Fail; } [TestMethod] public MFTestResults Statements_switch_015_Test() { Log.Comment("switch_015.sc"); Log.Comment("Run a switch over a specific type: byte"); if (Statements_TestClass_switch_015.testMethod()) { return MFTestResults.Pass; } return MFTestResults.Fail; } [TestMethod] public MFTestResults Statements_switch_016_Test() { Log.Comment("switch_016.sc"); Log.Comment("Run a switch over a specific type: char"); if (Statements_TestClass_switch_016.testMethod()) { return MFTestResults.Pass; } return MFTestResults.Fail; } [TestMethod] public MFTestResults Statements_switch_017_Test() { Log.Comment("switch_017.sc"); Log.Comment("Run a switch over a specific type: short"); if (Statements_TestClass_switch_017.testMethod()) { return MFTestResults.Pass; } return MFTestResults.Fail; } [TestMethod] public MFTestResults Statements_switch_018_Test() { Log.Comment("switch_018.sc"); Log.Comment("Run a switch over a specific type: int"); if (Statements_TestClass_switch_018.testMethod()) { return MFTestResults.Pass; } return MFTestResults.Fail; } [TestMethod] public MFTestResults Statements_switch_019_Test() { Log.Comment("switch_019.sc"); Log.Comment("Run a switch over a specific type: long"); if (Statements_TestClass_switch_019.testMethod()) { return MFTestResults.Pass; } return MFTestResults.Fail; } [TestMethod] public MFTestResults Statements_switch_023_Test() { Log.Comment("switch_023.sc"); Log.Comment("Run a switch over a specific type: enum"); if (Statements_TestClass_switch_023.testMethod()) { return MFTestResults.Pass; } return MFTestResults.Fail; } [TestMethod] public MFTestResults Statements_switch_030_Test() { Log.Comment(" switch on int variable, float case"); if (Statements_TestClass_switch_030.testMethod()) { return MFTestResults.Pass; } return MFTestResults.Fail; } [TestMethod] public MFTestResults Statements_switch_031_Test() { Log.Comment(" switch with holes in range"); if (Statements_TestClass_switch_031.testMethod()) { return MFTestResults.Pass; } return MFTestResults.Fail; } [TestMethod] public MFTestResults Statements_switch_032_Test() { Log.Comment(" switch: default case at top"); if (Statements_TestClass_switch_032.testMethod()) { return MFTestResults.Pass; } return MFTestResults.Fail; } [TestMethod] public MFTestResults Statements_switch_033_Test() { Log.Comment(" switch: default case in middle"); if (Statements_TestClass_switch_033.testMethod()) { return MFTestResults.Pass; } return MFTestResults.Fail; } [TestMethod] public MFTestResults Statements_switch_034_Test() { Log.Comment(" switch: default case in middle"); if (Statements_TestClass_switch_034.testMethod()) { return MFTestResults.Pass; } return MFTestResults.Fail; } [TestMethod] public MFTestResults Statements_switch_035_Test() { Log.Comment("Otherwise, exactly one user-defined implicit conversion (6.4) must exist from the type of "); Log.Comment("the switch expression to one of the following possible governing types: sbyte, byte, short,"); Log.Comment("ushort, int, uint, long, ulong, char, string. If no such implicit conversion exists, or if "); Log.Comment("more than one such implicit conversion exists, a compile-time error occurs."); if (Statements_TestClass_switch_035.testMethod()) { return MFTestResults.Pass; } return MFTestResults.Fail; } [TestMethod] public MFTestResults Statements_switch_036_Test() { Log.Comment("Otherwise, exactly one user-defined implicit conversion (6.4) must exist from the type of "); Log.Comment("the switch expression to one of the following possible governing types: sbyte, byte, short,"); Log.Comment("ushort, int, uint, long, ulong, char, string. If no such implicit conversion exists, or if "); Log.Comment("more than one such implicit conversion exists, a compile-time error occurs."); if (Statements_TestClass_switch_036.testMethod()) { return MFTestResults.Pass; } return MFTestResults.Fail; } [TestMethod] public MFTestResults Statements_switch_037_Test() { Log.Comment("Otherwise, exactly one user-defined implicit conversion (6.4) must exist from the type of "); Log.Comment("the switch expression to one of the following possible governing types: sbyte, byte, short,"); Log.Comment("ushort, int, uint, long, ulong, char, string. If no such implicit conversion exists, or if "); Log.Comment("more than one such implicit conversion exists, a compile-time error occurs."); if (Statements_TestClass_switch_037.testMethod()) { return MFTestResults.Pass; } return MFTestResults.Fail; } [TestMethod] public MFTestResults Statements_switch_038_Test() { Log.Comment("Otherwise, exactly one user-defined implicit conversion (6.4) must exist from the type of "); Log.Comment("the switch expression to one of the following possible governing types: sbyte, byte, short,"); Log.Comment("ushort, int, uint, long, ulong, char, string. If no such implicit conversion exists, or if "); Log.Comment("more than one such implicit conversion exists, a compile-time error occurs."); if (Statements_TestClass_switch_038.testMethod()) { return MFTestResults.Pass; } return MFTestResults.Fail; } [TestMethod] public MFTestResults Statements_switch_039_Test() { Log.Comment("Otherwise, exactly one user-defined implicit conversion (6.4) must exist from the type of "); Log.Comment("the switch expression to one of the following possible governing types: sbyte, byte, short,"); Log.Comment("ushort, int, uint, long, ulong, char, string. If no such implicit conversion exists, or if "); Log.Comment("more than one such implicit conversion exists, a compile-time error occurs."); if (Statements_TestClass_switch_039.testMethod()) { return MFTestResults.Pass; } return MFTestResults.Fail; } [TestMethod] public MFTestResults Statements_switch_040_Test() { Log.Comment("Otherwise, exactly one user-defined implicit conversion (6.4) must exist from the type of "); Log.Comment("the switch expression to one of the following possible governing types: sbyte, byte, short,"); Log.Comment("ushort, int, uint, long, ulong, char, string. If no such implicit conversion exists, or if "); Log.Comment("more than one such implicit conversion exists, a compile-time error occurs."); if (Statements_TestClass_switch_040.testMethod()) { return MFTestResults.Pass; } return MFTestResults.Fail; } [TestMethod] public MFTestResults Statements_switch_041_Test() { Log.Comment("Otherwise, exactly one user-defined implicit conversion (6.4) must exist from the type of "); Log.Comment("the switch expression to one of the following possible governing types: sbyte, byte, short,"); Log.Comment("ushort, int, uint, long, ulong, char, string. If no such implicit conversion exists, or if "); Log.Comment("more than one such implicit conversion exists, a compile-time error occurs."); if (Statements_TestClass_switch_041.testMethod()) { return MFTestResults.Pass; } return MFTestResults.Fail; } [TestMethod] public MFTestResults Statements_switch_042_Test() { Log.Comment("Otherwise, exactly one user-defined implicit conversion (6.4) must exist from the type of "); Log.Comment("the switch expression to one of the following possible governing types: sbyte, byte, short,"); Log.Comment("ushort, int, uint, long, ulong, char, string. If no such implicit conversion exists, or if "); Log.Comment("more than one such implicit conversion exists, a compile-time error occurs."); if (Statements_TestClass_switch_042.testMethod()) { return MFTestResults.Pass; } return MFTestResults.Fail; } [TestMethod] public MFTestResults Statements_switch_044_Test() { Log.Comment("Otherwise, exactly one user-defined implicit conversion (6.4) must exist from the type of "); Log.Comment("the switch expression to one of the following possible governing types: sbyte, byte, short,"); Log.Comment("ushort, int, uint, long, ulong, char, string. If no such implicit conversion exists, or if "); Log.Comment("more than one such implicit conversion exists, a compile-time error occurs."); if (Statements_TestClass_switch_044.testMethod()) { return MFTestResults.Pass; } return MFTestResults.Fail; } [TestMethod] public MFTestResults Statements_switch_047_Test() { Log.Comment("Otherwise, exactly one user-defined implicit conversion (6.4) must exist from the type of "); Log.Comment("the switch expression to one of the following possible governing types: sbyte, byte, short,"); Log.Comment("ushort, int, uint, long, ulong, char, string. If no such implicit conversion exists, or if "); Log.Comment("more than one such implicit conversion exists, a compile-time error occurs."); Log.Comment("Ensure error is emmited on when more than one implicit conversion to an acceptable governing type is defined"); if (Statements_TestClass_switch_047.testMethod()) { return MFTestResults.Pass; } return MFTestResults.Fail; } [TestMethod] public MFTestResults Statements_switch_049_Test() { Log.Comment("warning CS1522: Empty switch block"); if (Statements_TestClass_switch_049.testMethod()) { return MFTestResults.Pass; } return MFTestResults.Fail; } [TestMethod] public MFTestResults Statements_switch_string_001_Test() { Log.Comment(" switch on string: null"); if (Statements_TestClass_switch_string_001.testMethod()) { return MFTestResults.Pass; } return MFTestResults.Fail; } [TestMethod] public MFTestResults Statements_dowhile_001_Test() { Log.Comment("dowhile_001.sc"); Log.Comment("do/while with a single statement"); if (Statements_TestClass_dowhile_001.testMethod()) { return MFTestResults.Pass; } return MFTestResults.Fail; } [TestMethod] public MFTestResults Statements_dowhile_002_Test() { Log.Comment("dowhile_002.sc"); Log.Comment("do/while with a compound statement"); if (Statements_TestClass_dowhile_002.testMethod()) { return MFTestResults.Pass; } return MFTestResults.Fail; } [TestMethod] public MFTestResults Statements_dowhile_003_Test() { Log.Comment("dowhile_003.sc"); Log.Comment("verify known false condition executes only once with single statement"); if (Statements_TestClass_dowhile_003.testMethod()) { return MFTestResults.Pass; } return MFTestResults.Fail; } [TestMethod] public MFTestResults Statements_dowhile_004_Test() { Log.Comment("dowhile_004.sc"); Log.Comment("verify known true condition executes with single statement"); if (Statements_TestClass_dowhile_004.testMethod()) { return MFTestResults.Pass; } return MFTestResults.Fail; } [TestMethod] public MFTestResults Statements_dowhile_005_Test() { Log.Comment("dowhile_005.sc"); Log.Comment("verify known false condition executes once with compound statements"); if (Statements_TestClass_dowhile_005.testMethod()) { return MFTestResults.Pass; } return MFTestResults.Fail; } [TestMethod] public MFTestResults Statements_dowhile_006_Test() { Log.Comment("dowhile_006.sc"); Log.Comment("verify known true condition executes with compound statements"); if (Statements_TestClass_dowhile_006.testMethod()) { return MFTestResults.Pass; } return MFTestResults.Fail; } [TestMethod] public MFTestResults Statements_for_001_Test() { Log.Comment("for_001.sc"); Log.Comment("empty for loop"); if (Statements_TestClass_for_001.testMethod()) { return MFTestResults.Pass; } return MFTestResults.Fail; } [TestMethod] public MFTestResults Statements_for_003_Test() { Log.Comment("for_003.sc"); Log.Comment("empty initializer in for loop"); if (Statements_TestClass_for_003.testMethod()) { return MFTestResults.Pass; } return MFTestResults.Fail; } [TestMethod] public MFTestResults Statements_for_004_Test() { Log.Comment("for_004.sc"); Log.Comment("empty iterator in for loop"); if (Statements_TestClass_for_004.testMethod()) { return MFTestResults.Pass; } return MFTestResults.Fail; } [TestMethod] public MFTestResults Statements_for_006_Test() { Log.Comment("for_006.sc"); Log.Comment("Full normal for loop"); if (Statements_TestClass_for_006.testMethod()) { return MFTestResults.Pass; } return MFTestResults.Fail; } [TestMethod] public MFTestResults Statements_for_007_Test() { Log.Comment("for_007.sc"); Log.Comment("Full normal for loop with a compound statement"); if (Statements_TestClass_for_007.testMethod()) { return MFTestResults.Pass; } return MFTestResults.Fail; } [TestMethod] public MFTestResults Statements_for_008_Test() { Log.Comment("for_008.sc"); Log.Comment("Multiple declarations in initializer"); if (Statements_TestClass_for_008.testMethod()) { return MFTestResults.Pass; } return MFTestResults.Fail; } [TestMethod] public MFTestResults Statements_for_009_Test() { Log.Comment("for_009.sc"); Log.Comment("Statements_TestClass_? statement expression lists in for initializer"); if (Statements_TestClass_for_009.testMethod()) { return MFTestResults.Pass; } return MFTestResults.Fail; } [TestMethod] public MFTestResults Statements_for_010_Test() { Log.Comment("for_010.sc"); Log.Comment("Statements_TestClass_? statement expression lists in for iterator"); if (Statements_TestClass_for_010.testMethod()) { return MFTestResults.Pass; } return MFTestResults.Fail; } [TestMethod] public MFTestResults Statements_for_011_Test() { Log.Comment("for_011.sc"); Log.Comment("Statements_TestClass_? statement expression lists in for initializer and iterator"); if (Statements_TestClass_for_011.testMethod()) { return MFTestResults.Pass; } return MFTestResults.Fail; } [TestMethod] public MFTestResults Statements_for_013_Test() { Log.Comment("for_013.sc"); Log.Comment("Verify conditional evaluates before iterator"); if (Statements_TestClass_for_013.testMethod()) { return MFTestResults.Pass; } return MFTestResults.Fail; } [TestMethod] public MFTestResults Statements_for_014_Test() { Log.Comment("for_014.sc"); Log.Comment("Verify method calls work ok in all for loop areas"); if (Statements_TestClass_for_014.testMethod()) { return MFTestResults.Pass; } return MFTestResults.Fail; } [TestMethod] public MFTestResults Statements_char_in_string_s01_Test() { Log.Comment("Optimization to foreach (char c in String) by treating String as a char array"); if (Statements_TestClass_char_in_string_s01.testMethod()) { return MFTestResults.Pass; } return MFTestResults.Fail; } [TestMethod] public MFTestResults Statements_char_in_string_ex01_Test() { Log.Comment("Optimization to foreach (char c in String) by treating String as a char array"); if (Statements_TestClass_char_in_string_ex01.testMethod()) { return MFTestResults.Pass; } return MFTestResults.Fail; } [TestMethod] public MFTestResults Statements_while_001_Test() { Log.Comment("while_001.sc"); Log.Comment("while with a single statement"); if (Statements_TestClass_while_001.testMethod()) { return MFTestResults.Pass; } return MFTestResults.Fail; } [TestMethod] public MFTestResults Statements_while_002_Test() { Log.Comment("while_002.sc"); Log.Comment("while with a compound statement"); if (Statements_TestClass_while_002.testMethod()) { return MFTestResults.Pass; } return MFTestResults.Fail; } [TestMethod] public MFTestResults Statements_while_003_Test() { Log.Comment("while_003.sc"); Log.Comment("verify known false condition doesn't execute with single statement"); if (Statements_TestClass_while_003.testMethod()) { return MFTestResults.Pass; } return MFTestResults.Fail; } [TestMethod] public MFTestResults Statements_while_004_Test() { Log.Comment("while_004.sc"); Log.Comment("verify known true condition executes with single statement"); if (Statements_TestClass_while_004.testMethod()) { return MFTestResults.Pass; } return MFTestResults.Fail; } [TestMethod] public MFTestResults Statements_while_005_Test() { Log.Comment("while_005.sc"); Log.Comment("verify known false condition doesn't execute with compound statements"); if (Statements_TestClass_while_005.testMethod()) { return MFTestResults.Pass; } return MFTestResults.Fail; } [TestMethod] public MFTestResults Statements_while_006_Test() { Log.Comment("while_006.sc"); Log.Comment("verify known true condition executes with compound statements"); if (Statements_TestClass_while_006.testMethod()) { return MFTestResults.Pass; } return MFTestResults.Fail; } [TestMethod] public MFTestResults Statements_break_001_Test() { Log.Comment("break_001.sc"); Log.Comment("Make sure break works in all basic single statement loops"); if (Statements_TestClass_break_001.testMethod()) { return MFTestResults.Pass; } return MFTestResults.Fail; } [TestMethod] public MFTestResults Statements_break_002_Test() { Log.Comment("break_002.sc"); Log.Comment("Make sure break works in all basic compound statement loops"); if (Statements_TestClass_break_002.testMethod()) { return MFTestResults.Pass; } return MFTestResults.Fail; } [TestMethod] public MFTestResults Statements_break_003_Test() { Log.Comment("break_003.sc"); Log.Comment("Make sure break optional on end of switch"); if (Statements_TestClass_break_003.testMethod()) { return MFTestResults.Pass; } return MFTestResults.Fail; } [TestMethod] public MFTestResults Statements_break_006_Test() { Log.Comment("break_006.sc"); Log.Comment("break in an if successfully breaks loop"); if (Statements_TestClass_break_006.testMethod()) { return MFTestResults.Pass; } return MFTestResults.Fail; } [TestMethod] public MFTestResults Statements_break_007_Test() { Log.Comment("break_007.sc"); Log.Comment("break in a blocked if successfully breaks loop"); if (Statements_TestClass_break_007.testMethod()) { return MFTestResults.Pass; } return MFTestResults.Fail; } [TestMethod] public MFTestResults Statements_break_010_Test() { Log.Comment("break_010.sc"); Log.Comment("Make sure break correctly when nested"); if (Statements_TestClass_break_010.testMethod()) { return MFTestResults.Pass; } return MFTestResults.Fail; } [TestMethod] public MFTestResults Statements_continue_001_Test() { Log.Comment("continue_001.sc"); Log.Comment("Make sure continue works in all basic single statement loops"); if (Statements_TestClass_continue_001.testMethod()) { return MFTestResults.Pass; } return MFTestResults.Fail; } [TestMethod] public MFTestResults Statements_continue_002_Test() { Log.Comment("continue_002.sc"); Log.Comment("Make sure continue works in all basic compound statement loops"); Log.Comment("Expected Output"); if (Statements_TestClass_continue_002.testMethod()) { return MFTestResults.Pass; } return MFTestResults.Fail; } [TestMethod] public MFTestResults Statements_continue_006_Test() { Log.Comment("continue_006.sc"); Log.Comment("continue in an if successfully continues loop"); if (Statements_TestClass_continue_006.testMethod()) { return MFTestResults.Pass; } return MFTestResults.Fail; } [TestMethod] public MFTestResults Statements_continue_007_Test() { Log.Comment("continue_007.sc"); Log.Comment("continue in a block if successfully continues loop"); if (Statements_TestClass_continue_007.testMethod()) { return MFTestResults.Pass; } return MFTestResults.Fail; } [TestMethod] public MFTestResults Statements_continue_010_Test() { Log.Comment("continue_010.sc"); Log.Comment("Make sure continue works correctly when nested"); if (Statements_TestClass_continue_010.testMethod()) { return MFTestResults.Pass; } return MFTestResults.Fail; } [TestMethod] public MFTestResults Statements_goto_001_Test() { Log.Comment("goto_001.sc"); Log.Comment("simple goto to adjust flow control"); if (Statements_TestClass_goto_001.testMethod()) { return MFTestResults.Pass; } return MFTestResults.Fail; } [TestMethod] public MFTestResults Statements_goto_008_Test() { Log.Comment("goto_008.sc"); Log.Comment("goto currect case"); if (Statements_TestClass_goto_008.testMethod()) { return MFTestResults.Pass; } return MFTestResults.Fail; } [TestMethod] public MFTestResults Statements_goto_009_Test() { Log.Comment("goto_009.sc"); Log.Comment("goto a different case"); Log.Comment("Expected Output"); if (Statements_TestClass_goto_009.testMethod()) { return MFTestResults.Pass; } return MFTestResults.Fail; } [TestMethod] public MFTestResults Statements_goto_010_Test() { Log.Comment("goto_010.sc"); Log.Comment("goto default correctly"); if (Statements_TestClass_goto_010.testMethod()) { return MFTestResults.Pass; } return MFTestResults.Fail; } [TestMethod] public MFTestResults Statements_goto_014_Test() { Log.Comment("goto_014.sc"); Log.Comment("simple gotos to test jumping to parent process."); if (Statements_TestClass_goto_014.testMethod()) { return MFTestResults.Pass; } return MFTestResults.Fail; } [TestMethod] public MFTestResults Statements_goto_017_Test() { Log.Comment(" some gotos"); if (Statements_TestClass_goto_017.testMethod()) { return MFTestResults.Pass; } return MFTestResults.Fail; } [TestMethod] public MFTestResults Statements_goto_018_Test() { Log.Comment(" try/catch/finally with goto"); if (Statements_TestClass_goto_018.testMethod()) { return MFTestResults.Pass; } return MFTestResults.Fail; } [TestMethod] public MFTestResults Statements_return_001_Test() { Log.Comment("return_001.sc"); Log.Comment("simple void return on a void method"); if (Statements_TestClass_return_001.testMethod()) { return MFTestResults.Pass; } return MFTestResults.Fail; } [TestMethod] public MFTestResults Statements_return_004_Test() { Log.Comment("return_004.sc"); Log.Comment("simple return a normal type, assigning, and ignoring return value"); if (Statements_TestClass_return_004.testMethod()) { return MFTestResults.Pass; } return MFTestResults.Fail; } [TestMethod] public MFTestResults Statements_return_006_Test() { Log.Comment("return_006.sc"); Log.Comment("simple return a type mismatch that has an implicit conversion"); if (Statements_TestClass_return_006.testMethod()) { return MFTestResults.Pass; } return MFTestResults.Fail; } [TestMethod] public MFTestResults Statements_return_008_Test() { Log.Comment("return_008.sc"); Log.Comment("simple return a type mismatch that has an explicit convertion conversion,"); Log.Comment("applying the cast"); if (Statements_TestClass_return_008.testMethod()) { return MFTestResults.Pass; } return MFTestResults.Fail; } [TestMethod] public MFTestResults Statements_return_009_Test() { Log.Comment("return_009.sc"); Log.Comment("return of a struct"); if (Statements_TestClass_return_009.testMethod()) { return MFTestResults.Pass; } return MFTestResults.Fail; } [TestMethod] public MFTestResults Statements_return_010_Test() { Log.Comment("return_010.sc"); Log.Comment("return of a class"); if (Statements_TestClass_return_010.testMethod()) { return MFTestResults.Pass; } return MFTestResults.Fail; } [TestMethod] public MFTestResults Statements_return_013_Test() { Log.Comment("return_013.sc"); Log.Comment("simple falloff on a void method"); if (Statements_TestClass_return_013.testMethod()) { return MFTestResults.Pass; } return MFTestResults.Fail; } [TestMethod] public MFTestResults Statements_return_014_Test() { Log.Comment("return_014.sc"); Log.Comment("verify that a 'throw' is adequate for flow control analysis of return type"); if (Statements_TestClass_return_014.testMethod()) { return MFTestResults.Pass; } return MFTestResults.Fail; } [TestMethod] public MFTestResults Statements_throw_001_Test() { Log.Comment("throw_001.sc"); Log.Comment("simple throw"); if (Statements_TestClass_throw_001.testMethod()) { return MFTestResults.Pass; } return MFTestResults.Fail; } [TestMethod] public MFTestResults Statements_throw_005_Test() { Log.Comment("throw_005.sc"); Log.Comment("simple throw with output"); if (Statements_TestClass_throw_005.testMethod()) { return MFTestResults.Pass; } return MFTestResults.Fail; } [TestMethod] public MFTestResults Statements_trycatch_001_Test() { Log.Comment("trycatch_001.sc"); Log.Comment("simple throw"); if (Statements_TestClass_trycatch_001.testMethod()) { return MFTestResults.Pass; } return MFTestResults.Fail; } [TestMethod] public MFTestResults Statements_trycatch_006_Test() { Log.Comment("trycatch_006.sc"); Log.Comment("simple system generated System.Exception"); if (Statements_TestClass_trycatch_006.testMethod()) { return MFTestResults.Pass; } return MFTestResults.Fail; } [TestMethod] public MFTestResults Statements_trycatch_007_Test() { Log.Comment("trycatch_007.sc"); Log.Comment("simple re-throw"); if (Statements_TestClass_trycatch_007.testMethod()) { return MFTestResults.Pass; } return MFTestResults.Fail; } [TestMethod] public MFTestResults Statements_tryfinally_001_Test() { Log.Comment("tryfinally_001.sc"); Log.Comment("simple finally"); if (Statements_TestClass_tryfinally_001.testMethod()) { return MFTestResults.Pass; } return MFTestResults.Fail; } [TestMethod] public MFTestResults Statements_tryfinally_002_Test() { Log.Comment("tryfinally_002.sc"); Log.Comment("simple finally inside try/catch"); if (Statements_TestClass_tryfinally_002.testMethod()) { return MFTestResults.Pass; } return MFTestResults.Fail; } [TestMethod] public MFTestResults Statements_tryfinally_003_Test() { Log.Comment("tryfinally_003.sc"); Log.Comment("simple finally outside try/catch"); if (Statements_TestClass_tryfinally_003.testMethod()) { return MFTestResults.Pass; } return MFTestResults.Fail; } [TestMethod] public MFTestResults Statements_tryfinally_004_Test() { Log.Comment("tryfinally_004.sc"); Log.Comment("simple finally passed 'over' by a goto"); if (Statements_TestClass_tryfinally_004.testMethod()) { return MFTestResults.Pass; } return MFTestResults.Fail; } [TestMethod] public MFTestResults Statements_tryfinally_006_Test() { Log.Comment("tryfinally_006.sc"); Log.Comment("simple finally exited by throw"); if (Statements_TestClass_tryfinally_006.testMethod()) { return MFTestResults.Pass; } return MFTestResults.Fail; } [TestMethod] public MFTestResults Statements_tryfinally_007_Test() { Log.Comment("tryfinally_007.sc"); Log.Comment("simple finally exited by throw in a called method"); if (Statements_TestClass_tryfinally_007.testMethod()) { return MFTestResults.Pass; } return MFTestResults.Fail; } [TestMethod] public MFTestResults Statements_tryfinally_008_Test() { Log.Comment("tryfinally_008.sc"); Log.Comment("simple finally exited by return"); if (Statements_TestClass_tryfinally_008.testMethod()) { return MFTestResults.Pass; } return MFTestResults.Fail; } [TestMethod] public MFTestResults Statements_tryfinally_009_Test() { Log.Comment("tryfinally_009.sc"); Log.Comment("simple finally exited by continue"); if (Statements_TestClass_tryfinally_009.testMethod()) { return MFTestResults.Pass; } return MFTestResults.Fail; } [TestMethod] public MFTestResults Statements_tryfinally_010_Test() { Log.Comment("tryfinally_010.sc"); Log.Comment("simple finally exited by break"); if (Statements_TestClass_tryfinally_010.testMethod()) { return MFTestResults.Pass; } return MFTestResults.Fail; } [TestMethod] public MFTestResults Statements_tryfinally_011_Test() { Log.Comment("tryfinally_011.sc"); Log.Comment("simple finally exited by break (where break is outside try)"); if (Statements_TestClass_tryfinally_011.testMethod()) { return MFTestResults.Pass; } return MFTestResults.Fail; } [TestMethod] public MFTestResults Statements_tryfinally_012_Test() { Log.Comment("tryfinally_012.sc"); Log.Comment("simple finally exited by system System.Exception"); if (Statements_TestClass_tryfinally_012.testMethod()) { return MFTestResults.Pass; } return MFTestResults.Fail; } [TestMethod] public MFTestResults Statements_tryfinally_013_Test() { if (Statements_TestClass_tryfinally_013.testMethod()) { return MFTestResults.Pass; } return MFTestResults.Fail; } [TestMethod] public MFTestResults Statements_Using_001_Test() { Log.Comment("using_001.cs"); Log.Comment("Statements_TestClass_? the using statement."); Log.Comment("Cast a class to IDisposable explicitly, use that in the using statement. (1.a)"); if (Statements_TestClass_Using_001.testMethod()) { return MFTestResults.Pass; } return MFTestResults.Fail; } [TestMethod] public MFTestResults Statements_Using_002_Test() { Log.Comment("using_002.cs"); Log.Comment("Statements_TestClass_? the using statement."); Log.Comment("Use a class directly in using (1.b)"); if (Statements_TestClass_Using_002.testMethod()) { return MFTestResults.Pass; } return MFTestResults.Fail; } [TestMethod] public MFTestResults Statements_Using_003_Test() { Log.Comment("using_003.cs"); Log.Comment("Statements_TestClass_? the using statement."); Log.Comment("Creation of class as part of using statement (1.c)"); if (Statements_TestClass_Using_003.testMethod()) { return MFTestResults.Pass; } return MFTestResults.Fail; } [TestMethod] public MFTestResults Statements_Using_005_Test() { Log.Comment("using_005.cs"); Log.Comment("Statements_TestClass_? the using statement."); Log.Comment("A class that explicitly implements IDisposable. (1.e)"); if (Statements_TestClass_Using_005.testMethod()) { return MFTestResults.Pass; } return MFTestResults.Fail; } [TestMethod] public MFTestResults Statements_Using_009_Test() { Log.Comment("using_009.cs"); Log.Comment("Statements_TestClass_? the using statement."); Log.Comment("Statements_TestClass_? the behavior if the used variable is nulled-out in the using block (4)"); if (Statements_TestClass_Using_009.testMethod()) { return MFTestResults.Pass; } return MFTestResults.Fail; } [TestMethod] public MFTestResults Statements_Using_010_Test() { Log.Comment("using_010.cs"); Log.Comment("Statements_TestClass_? the using statement."); Log.Comment("Dispose() called during normal exit (5.a)"); if (Statements_TestClass_Using_010.testMethod()) { return MFTestResults.Pass; } return MFTestResults.Fail; } [TestMethod] public MFTestResults Statements_Using_011_Test() { Log.Comment("using_011.cs"); Log.Comment("Statements_TestClass_? the using statement."); Log.Comment("Dispose() called after throw (5.b)"); Log.Comment("Expected Output"); if (Statements_TestClass_Using_011.testMethod()) { return MFTestResults.Pass; } return MFTestResults.Fail; } [TestMethod] public MFTestResults Statements_Using_012_Test() { Log.Comment("using_012.cs"); Log.Comment("Statements_TestClass_? the using statement."); Log.Comment("Dispose() called for two objects during normal exit. (5.c)"); if (Statements_TestClass_Using_012.testMethod()) { return MFTestResults.Pass; } return MFTestResults.Fail; } [TestMethod] public MFTestResults Statements_Using_013_Test() { Log.Comment("using_013.cs"); Log.Comment("Statements_TestClass_? the using statement."); Log.Comment("Dispose() called for first objects with System.Exception thrown before second block. (5.d)"); if (Statements_TestClass_Using_013.testMethod()) { return MFTestResults.Pass; } return MFTestResults.Fail; } [TestMethod] public MFTestResults Statements_Using_014_Test() { Log.Comment("using_014.cs"); Log.Comment("Statements_TestClass_? the using statement."); Log.Comment("Dispose() called for first objects with System.Exception thrown after second block. (5.e)"); if (Statements_TestClass_Using_014.testMethod()) { return MFTestResults.Pass; } return MFTestResults.Fail; } [TestMethod] public MFTestResults Statements_Using_015_Test() { Log.Comment("using_015.cs"); Log.Comment("Statements_TestClass_? the using statement."); Log.Comment("Dispose() called for both objects when System.Exception thrown inside second block. (5.f)"); if (Statements_TestClass_Using_015.testMethod()) { return MFTestResults.Pass; } return MFTestResults.Fail; } [TestMethod] public MFTestResults Statements_Using_017_Test() { Log.Comment("using_017.cs"); Log.Comment("Statements_TestClass_? the using statement."); Log.Comment("Dispose() called for both objects when System.Exception thrown in compound case (5.h)"); if (Statements_TestClass_Using_017.testMethod()) { return MFTestResults.Pass; } return MFTestResults.Fail; } [TestMethod] public MFTestResults Statements_Using_018_Test() { Log.Comment("using_018.cs"); Log.Comment("Statements_TestClass_? the using statement."); Log.Comment("Dispose() called for both objects in compound using. (5.g)"); if (Statements_TestClass_Using_018.testMethod()) { return MFTestResults.Pass; } return MFTestResults.Fail; } [TestMethod] public MFTestResults Statements_lock001_Test() { Log.Comment("The expression of a lock statement must denote a value of a reference-type"); if (Statements_TestClass_lock001.testMethod()) { return MFTestResults.Pass; } return MFTestResults.Fail; } [TestMethod] public MFTestResults Statements_lock003_Test() { Log.Comment("The System.Type object of a class can conveniently be used as the mutual-exclusion lock for static methods of the class"); if (Statements_TestClass_lock003.testMethod()) { return MFTestResults.Pass; } return MFTestResults.Fail; } [TestMethod] public MFTestResults Statements_lock004_Test() { Log.Comment("possible mistaken null statement when semi-column appears directly after lock()"); if (Statements_TestClass_lock004.testMethod()) { return MFTestResults.Pass; } return MFTestResults.Fail; } [TestMethod] public MFTestResults Statements_lock005_Test() { Log.Comment("this as the lock expression in a reference type"); if (Statements_TestClass_lock005.testMethod()) { return MFTestResults.Pass; } return MFTestResults.Fail; } [TestMethod] public MFTestResults Statements_lock007_Test() { Log.Comment("nested lock statements"); if (Statements_TestClass_lock007.testMethod()) { return MFTestResults.Pass; } return MFTestResults.Fail; } [TestMethod] public MFTestResults Statements_enum_002_Test() { Log.Comment(" enum: comparing constant casted to an enum type to a variable"); if (Statements_TestClass_enum_002.testMethod()) { return MFTestResults.Pass; } return MFTestResults.Fail; } public class Res1 : IDisposable { public void Dispose() { Log.Comment("Res1.Dispose()"); } public void Func() { Log.Comment("Res1.Func()"); } public void Throw() { throw (new System.Exception("Res1")); } } public class Res2 : IDisposable { public void Dispose() { Log.Comment("Res2.Dispose()"); } public void Func() { Log.Comment("Res2.Func()"); } public void Throw() { throw (new System.Exception("Res2")); } } // IDispose implemented explicitly public class ResExplicit : IDisposable { void IDisposable.Dispose() { Log.Comment("ResExplicit.Dispose()"); } public void Func() { Log.Comment("ResExplicit.Func()"); } public void Throw() { throw (new System.Exception("ResExplicit")); } } // A class that doesn't implement IDisposable. public class NonRes1 { public void GarbageDisposal() { Log.Comment("NonRes1.GarbageDisposal()"); } public void Func() { Log.Comment("NonRes1.Func()"); } public void Throw() { throw (new System.Exception("NonRes1")); } } // Doesn't implement IDisposable, but has a Dispose() function... public class NonRes2 { public void Dispose() { Log.Comment("NonRes2.Dispose()"); } public void Func() { Log.Comment("NonRes2.Func()"); } public void Throw() { throw (new System.Exception("NonRes2")); } } //Compiled Test Cases public class Statements_TestClass_Label_001 { public static int Main_old(string[] args) { Label: return (0); } public static bool testMethod() { return (Main_old(null) == 0); } } public class Statements_TestClass_Label_002 { public static int Main_old(string[] args) { goto Label; return (1); Label: return (0); } public static bool testMethod() { return (Main_old(null) == 0); } } public class Statements_TestClass_Label_004 { public static int Main_old(string[] args) { Method(); return (0); } public static void Method() { goto Label; Label: ; } public static bool testMethod() { return (Main_old(null) == 0); } } public class Statements_TestClass_Decl_001 { public static int Main_old(string[] args) { int i; return (0); } public static bool testMethod() { return (Main_old(null) == 0); } } public class Statements_TestClass_Decl_002 { public static int Main_old(string[] args) { int i = 99; if (i != 99) return (1); return (0); } public static bool testMethod() { return (Main_old(null) == 0); } } public class Statements_TestClass_Decl_003 { public static int Main_old(string[] args) { int i = 99; int j = i + 1; if (i != 99) return (1); if (j != 100) return (1); return (0); } public static bool testMethod() { return (Main_old(null) == 0); } } public class Statements_TestClass_Decl_004 { public static int Main_old(string[] args) { System.Exception r; return (0); } public static bool testMethod() { return (Main_old(null) == 0); } } public class Statements_TestClass_Decl_007 { public static int Main_old(string[] args) { int i, j, k; return (0); } public static bool testMethod() { return (Main_old(null) == 0); } } public class Statements_TestClass_Decl_009 { public static int Main_old(string[] args) { int i = 1, j = i + 1, k = i + j + 3; if ((i != 1) || (j != 2) || (k != 6)) return (1); return (0); } public static bool testMethod() { return (Main_old(null) == 0); } } public class Statements_TestClass_Decl_010 { public static int Main_old(string[] args) { int[] i; return (0); } public static bool testMethod() { return (Main_old(null) == 0); } } public class Statements_TestClass_Decl_012 { public static int Main_old(string[] args) { int[] i = new int[30]; int j = i[23]; if (j != 0) { return (1); } return (0); } public static bool testMethod() { return (Main_old(null) == 0); } } public class Statements_TestClass_Decl_014 { public static int Main_old(string[] args) { int[] i = new int[] { 0, 1, 2, 3, 4 }; int j = i[2]; if (j != 2) { return (1); } return (0); } public static bool testMethod() { return (Main_old(null) == 0); } } public class Foo { public Foo(int i) { m_i = i; } public int GetInt() { return (m_i); } int m_i; } public class Statements_TestClass_Decl_016 { public static int Main_old(string[] args) { Foo[] f = new Foo[30]; // 30 null'd foos Foo foo = f[23]; for (int i = 0; i < f.Length; i++) { foo = f[i]; if (foo != null) return (1); f[i] = foo = new Foo(i); if (foo.GetInt() != i) { Log.Comment("new Foo() didn't take"); return (1); } if (f[i].GetInt() != i) { Log.Comment("Array didn't get updated"); return (1); } if (f[i] != foo) { Log.Comment("Array element and foo are different"); return (i); } } return (0); } public static bool testMethod() { return (Main_old(null) == 0); } } public class Statements_TestClass_Block_001 { public static int Main_old(string[] args) { int status = 0; // arbitrary nesting { int i; i = 0; i++; } // empty nesting { { { { { { { { { { { { { { { { { { { { { { { { { { { { { { { { { { { { { { { { { { { { { { { { { { { { { { { { { { { { { { { { { { { { { { int i; i = 0; i++; } } } } } } } } } } } } } } } } } } } } } } } } } } } } } } } } } } } } } } } } } } } } } } } } } } } } } } } } } } } } } } } } } } } } } } // empty hanging clause if (true) { } else { status = 1; } while (false) { } do { } while (false); switch (status) { } for (; false; ) { } Label: { } return (status); } public static bool testMethod() { return (Main_old(null) == 0); } } public class Statements_TestClass_Empty_001 { public static int Main_old(string[] args) { int status = 0; // empty series ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; int i; i = 0; i++; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; // empty hanging clause if (true) ; else { status = 1; } while (false) ; do ; while (false); switch (status) { default: break; } for (; false; ) ; Label: ; return (status); } public static bool testMethod() { return (Main_old(null) == 0); } } public class Statements_TestClass_Expr_002 { public static int Main_old(string[] args) { bool b = false; b = true || false || b; if (!b) return (1); return (0); } public static bool testMethod() { return (Main_old(null) == 0); } } public class Statements_TestClass_Expr_003 { public static int Main_old(string[] args) { bool b = false; bool b1; bool b2; b = b1 = b2 = true || false || b; if (!b || !b1 || !b2) return(1); return(false ? 1 : 0); } public static bool testMethod() { return (Main_old(null) == 0); } } public class Statements_TestClass_Expr_004 { public static int Main_old(string[] args) { int i = 0; Log.Comment("Adding 5"); i += 5; // i == 5 if (i != 5) return(1); Log.Comment("Subtracting 3"); i -= 3; // i == 2 if (i != 2) return(1); Log.Comment("Multiplying by 4"); i *= 4; // i == 8 if (i != 8) return(1); Log.Comment("Dividing by 2"); i /= 2; // i == 4 if (i != 4) return(1); Log.Comment("Left Shifting 3"); i <<= 3; // i == 32 if (i != 32) return(1); Log.Comment("Right Shifting 2"); i >>= 2; // i == 8 if (i != 8) return(1); Log.Comment("ANDing against logical not"); i &= ~i; // i = 0 if (i != 0) return(1); Log.Comment("ORing by 0xBeaf"); i |= 48815; // i = 0xBeaf if (i != 0xBeaf) return(1); return(true ? 0 : 1); } public static bool testMethod() { return (Main_old(null) == 0); } } public class Statements_TestClass_Expr_006 { public static int Main_old(string[] args) { int b, c, d, e; e = 1; int a = b = c = d = e++ + 1; b = a = d + e * 2; if ((a == 6) && (a == b) && (c == 2) && (c == d) && (d == e)) return 0; else return 1; } public static bool testMethod() { return (Main_old(null) == 0); } } public class Statements_TestClass_if_001 { public static int Main_old(string[] args) { if (true) return (0); return (1); } public static bool testMethod() { return (Main_old(null) == 0); } } public class Statements_TestClass_if_003 { public static int Main_old(string[] args) { if (true) { int i = 0; return (i); } return (1); } public static bool testMethod() { return (Main_old(null) == 0); } } public class Statements_TestClass_if_005 { public static int Main_old(string[] args) { int ret = 0; if (true) ret = ret; else ret = 1; if (false) ret = 1; else ret = ret; return (ret); } public static bool testMethod() { return (Main_old(null) == 0); } } public class Statements_TestClass_if_007 { public static int Main_old(string[] args) { int ret = 0; if (true) { int i = ret; ret = i; } else { int i = 1; ret = i; } if (false) { int i = 1; ret = i; } else { int i = ret; ret = i; } return (ret); } public static bool testMethod() { return (Main_old(null) == 0); } } public class Statements_TestClass_if_009 { public static int Main_old(string[] args) { int ret = 1; // default to fail if (true) if (false) return (1); else // if this else if associated with the 1st if, it won't execute. ret = 0; return (ret); } public static bool testMethod() { return (Main_old(null) == 0); } } public class Statements_TestClass_switch_001 { public static int Main_old(string[] args) { switch (true) { } return (0); } public static bool testMethod() { return (Main_old(null) == 0); } } public class Statements_TestClass_switch_002 { public static int Main_old(string[] args) { int ret = 1; switch (true) { default: ret = 0; break; } return (ret); } public static bool testMethod() { return (Main_old(null) == 0); } } public class Statements_TestClass_switch_003 { public static int Main_old(string[] args) { int ret = 1; switch (true) { case true: ret = 0; break; } return (ret); } public static bool testMethod() { return (Main_old(null) == 0); } } public class Statements_TestClass_switch_004 { public static int Main_old(string[] args) { int ret = 1; switch (true) { case true: ret = 0; break; } return (ret); } public static bool testMethod() { return (Main_old(null) == 0); } } public class Statements_TestClass_switch_005 { public static int Main_old(string[] args) { int ret = 1; switch (true) { case true: ret = 0; break; case false: ret = 1; break; } return (ret); } public static bool testMethod() { return (Main_old(null) == 0); } } public class Statements_TestClass_switch_006 { public static int Main_old(string[] args) { int ret = 1; switch (false) { default: ret = 0; break; case true: ret = 1; } return (ret); } public static bool testMethod() { return (Main_old(null) == 0); } } public class Statements_TestClass_switch_007 { public static int Main_old(string[] args) { int ret = 1; switch (23) { default: ret = 0; break; case 1: ret = 1; break; case -2: ret = 1; break; } return (ret); } public static bool testMethod() { return (Main_old(null) == 0); } } public class Statements_TestClass_switch_010 { public static int Main_old(string[] args) { int ret = 1; int value = 23; switch (value) { case kValue: ret = 0; break; default: ret = 1; break; } return (ret); } const int kValue = 23; public static bool testMethod() { return (Main_old(null) == 0); } } public class Statements_TestClass_switch_012 { public static int Main_old(string[] args) { int ret = 3; for (int i = 0; i < 3; i++) { switch (i) { case 1: case 0: case 2: ret--; break; default: return (1); } } return (ret); } public static bool testMethod() { return (Main_old(null) == 0); } } public class Statements_TestClass_switch_013 { public static int Main_old(string[] args) { int ret = 6; switch (ret) { case 0: ret--; // 2 Log.Comment("case 0: "); Log.Comment(ret.ToString()); goto case 9999; case 2: ret--; // 4 Log.Comment("case 2: "); Log.Comment(ret.ToString()); goto case 255; case 6: // start here ret--; // 5 Log.Comment("case 5: "); Log.Comment(ret.ToString()); goto case 2; case 9999: ret--; // 1 Log.Comment("case 9999: "); Log.Comment(ret.ToString()); goto default; case 0xff: ret--; // 3 Log.Comment("case 0xff: "); Log.Comment(ret.ToString()); goto case 0; default: ret--; Log.Comment("Default: "); Log.Comment(ret.ToString()); if (ret > 0) { goto case -1; } break; case -1: ret = 999; Log.Comment("case -1: "); Log.Comment(ret.ToString()); break; } return (ret); } public static bool testMethod() { return (Main_old(null) == 0); } } public class Statements_TestClass_switch_015 { public static int Main_old(string[] args) { int ret = 0; ret = DoByte(); return (ret); } private static int DoByte() { int ret = 2; byte b = 2; switch (b) { case 1: case 2: ret--; break; case 3: break; default: break; } switch (b) { case 1: case 3: break; default: ret--; break; } if (ret > 0) Log.Comment("byte failed"); return (ret); } public static bool testMethod() { return (Main_old(null) == 0); } } public class Statements_TestClass_switch_016 { public static int Main_old(string[] args) { int ret = 0; ret = DoChar(); return (ret); } private static int DoChar() { int ret = 2; char c = '2'; switch (c) { case '1': case '2': ret--; break; case '3': break; default: break; } switch (c) { case '1': case '3': break; default: ret--; break; } if (ret > 0) Log.Comment("char failed"); return (ret); } public static bool testMethod() { return (Main_old(null) == 0); } } public class Statements_TestClass_switch_017 { public static int Main_old(string[] args) { int ret = 0; ret = DoShort(); return (ret); } private static int DoShort() { int ret = 2; short s = 0x7fff; switch (s) { case 1: case 32767: ret--; break; case -1: break; default: break; } switch (s) { case 1: case -1: break; default: ret--; break; } if (ret > 0) Log.Comment("short failed"); return (ret); } public static bool testMethod() { return (Main_old(null) == 0); } } public class Statements_TestClass_switch_018 { public static int Main_old(string[] args) { int ret = 0; ret = DoInt(); return (ret); } private static int DoInt() { int ret = 2; int i = 0x7fffffff; switch (i) { case 1: case 2147483647: ret--; break; case -1: break; default: break; } switch (i) { case 1: case -1: break; default: ret--; break; } if (ret > 0) Log.Comment("int failed"); return (ret); } public static bool testMethod() { return (Main_old(null) == 0); } } public class Statements_TestClass_switch_019 { public static int Main_old(string[] args) { int ret = 0; ret = DoLong(); return (ret); } private static int DoLong() { int ret = 2; long l = 0x7fffffffffffffffL; switch (l) { case 1L: case 9223372036854775807L: ret--; break; case -1L: break; default: break; } switch (l) { case 1L: case -1L: break; default: ret--; break; } if (ret > 0) Log.Comment("long failed"); return (ret); } public static bool testMethod() { return (Main_old(null) == 0); } } public class Statements_TestClass_switch_023 { enum eTypes { kFirst, kSecond, kThird, }; public static int Main_old(string[] args) { int ret = 0; ret = DoEnum(); return (ret); } private static int DoEnum() { int ret = 2; eTypes e = eTypes.kSecond; switch (e) { case eTypes.kThird: case eTypes.kSecond: ret--; break; case (eTypes)(-1): break; default: break; } switch (e) { case (eTypes)100: case (eTypes)(-1): break; default: ret--; break; } if (ret > 0) Log.Comment("enum failed"); return (ret); } public static bool testMethod() { return (Main_old(null) == 0); } } public class Statements_TestClass_switch_030 { public static int Main_old(string[] args) { int i = 5; switch (i) { case (int)5.0f: return 0; default: return 1; } } public static bool testMethod() { return (Main_old(null) == 0); } } public class Statements_TestClass_switch_031 { public static int Main_old(string[] args) { int i = 5; switch (i) { case 1: case 2: case 3: return 1; case 1001: case 1002: case 1003: return 2; } return 0; } public static bool testMethod() { return (Main_old(null) == 0); } } public class Statements_TestClass_switch_032 { public static int Main_old(string[] args) { string s = "hello"; switch (s) { default: return 1; case null: return 1; case "hello": return 0; } return 1; } public static bool testMethod() { return (Main_old(null) == 0); } } public class Statements_TestClass_switch_033 { public static int Main_old(string[] args) { string s = "hello"; switch (s) { case null: return 1; default: return 1; case "hello": return 0; } return 1; } public static bool testMethod() { return (Main_old(null) == 0); } } public class Statements_TestClass_switch_034 { public static implicit operator int(Statements_TestClass_switch_034 val) { return 1; } public static implicit operator float(Statements_TestClass_switch_034 val) { return 2.1f; } public static int Main_old(string[] args) { Statements_TestClass_switch_034 t = new Statements_TestClass_switch_034(); switch (t) { case 1: Log.Comment("a"); return 0; default: return 1; } } public static bool testMethod() { return (Main_old(null) == 0); } } class Statements_TestClass_switch_035 { public sbyte x; public Statements_TestClass_switch_035(sbyte i) { x = i; } public static implicit operator sbyte(Statements_TestClass_switch_035 C) { return C.x; } public static int Main_old() { Statements_TestClass_switch_035 C = new Statements_TestClass_switch_035(12); switch (C) { case 12: return 0; default: return 1; } } public static bool testMethod() { return (Main_old() == 0); } } class Statements_TestClass_switch_036 { public byte x; public Statements_TestClass_switch_036(byte i) { x = i; } public static implicit operator byte(Statements_TestClass_switch_036 C) { return C.x; } public static int Main_old() { Statements_TestClass_switch_036 C = new Statements_TestClass_switch_036(12); switch (C) { case 12: return 0; default: return 1; } } public static bool testMethod() { return (Main_old() == 0); } } class Statements_TestClass_switch_037 { public short x; public Statements_TestClass_switch_037(short i) { x = i; } public static implicit operator short(Statements_TestClass_switch_037 C) { return C.x; } public static int Main_old() { Statements_TestClass_switch_037 C = new Statements_TestClass_switch_037(12); switch (C) { case 12: return 0; default: return 1; } } public static bool testMethod() { return (Main_old() == 0); } } class Statements_TestClass_switch_038 { public ushort x; public Statements_TestClass_switch_038(ushort i) { x = i; } public static implicit operator ushort(Statements_TestClass_switch_038 C) { return C.x; } public static int Main_old() { Statements_TestClass_switch_038 C = new Statements_TestClass_switch_038(12); switch (C) { case 12: return 0; default: return 1; } } public static bool testMethod() { return (Main_old() == 0); } } class Statements_TestClass_switch_039 { public int x; public Statements_TestClass_switch_039(int i) { x = i; } public static implicit operator int(Statements_TestClass_switch_039 C) { return C.x; } public static int Main_old() { Statements_TestClass_switch_039 C = new Statements_TestClass_switch_039(12); switch (C) { case 12: return 0; default: return 1; } } public static bool testMethod() { return (Main_old() == 0); } } class Statements_TestClass_switch_040 { public uint x; public Statements_TestClass_switch_040(uint i) { x = i; } public static implicit operator uint(Statements_TestClass_switch_040 C) { return C.x; } public static int Main_old() { Statements_TestClass_switch_040 C = new Statements_TestClass_switch_040(12); switch (C) { case 12: return 0; default: return 1; } } public static bool testMethod() { return (Main_old() == 0); } } class Statements_TestClass_switch_041 { public long x; public Statements_TestClass_switch_041(long i) { x = i; } public static implicit operator long(Statements_TestClass_switch_041 C) { return C.x; } public static int Main_old() { Statements_TestClass_switch_041 C = new Statements_TestClass_switch_041(12); switch (C) { case 12: return 0; default: return 1; } } public static bool testMethod() { return (Main_old() == 0); } } class Statements_TestClass_switch_042 { public ulong x; public Statements_TestClass_switch_042(ulong i) { x = i; } public static implicit operator ulong(Statements_TestClass_switch_042 C) { return C.x; } public static int Main_old() { Statements_TestClass_switch_042 C = new Statements_TestClass_switch_042(12); switch (C) { case 12: return 0; default: return 1; } } public static bool testMethod() { return (Main_old() == 0); } } class Statements_TestClass_switch_044 { public static implicit operator string(Statements_TestClass_switch_044 C) { return "true"; } public static int Main_old() { Statements_TestClass_switch_044 C = new Statements_TestClass_switch_044(); switch (C) { case "true": return 0; default: return 1; } } public static bool testMethod() { return (Main_old() == 0); } } class X { } class Statements_TestClass_switch_047 { public static implicit operator int(Statements_TestClass_switch_047 C) { return 1; } public static implicit operator X(Statements_TestClass_switch_047 C) { return new X(); } public static int Main_old() { Statements_TestClass_switch_047 C = new Statements_TestClass_switch_047(); switch (C) { case 1: return 0; default: return 1; } } public static bool testMethod() { return (Main_old() == 0); } } class Statements_TestClass_switch_049 { public static int Main_old() { int i = 6; switch (i) { } // CS1522 return 0; } public static bool testMethod() { return (Main_old() == 0); } } public class Statements_TestClass_switch_string_001 { public static int Main_old(string[] args) { string s = null; switch (s) { case null: Log.Comment("null"); return 0; default: return 1; } } public static bool testMethod() { return (Main_old(null) == 0); } } public class Statements_TestClass_dowhile_001 { public static int Main_old(string[] args) { int i = 0; int j = 10; // post decrement test as well do i++; while (--j > 0); if (i == 10) return (0); return (1); } public static bool testMethod() { return (Main_old(null) == 0); } } public class Statements_TestClass_dowhile_002 { public static int Main_old(string[] args) { int i = 0; int j = 10; // post decrement test as well do { j--; i++; } while (j > 0); if (i == 10) return (0); return (1); } public static bool testMethod() { return (Main_old(null) == 0); } } public class Statements_TestClass_dowhile_003 { public static int Main_old(string[] args) { bool bFalse = false; int ret = 1; do ret--; while (bFalse); return (ret); } public static bool testMethod() { return (Main_old(null) == 0); } } public class Statements_TestClass_dowhile_004 { public static int Main_old(string[] args) { bool bTrue = true; do return (0); while (bTrue); return (1); } public static bool testMethod() { return (Main_old(null) == 0); } } public class Statements_TestClass_dowhile_005 { public static int Main_old(string[] args) { bool bFalse = false; int ret = 1; do { Log.Comment("Hello World"); ret--; } while (bFalse); return (ret); } public static bool testMethod() { return (Main_old(null) == 0); } } public class Statements_TestClass_dowhile_006 { public static int Main_old(string[] args) { bool bTrue = true; do { Log.Comment("Hello World"); return (0); } while (bTrue); return (1); } public static bool testMethod() { return (Main_old(null) == 0); } } public class Statements_TestClass_for_001 { public static int Main_old(string[] args) { for (; ; ) return (0); return (1); } public static bool testMethod() { return (Main_old(null) == 0); } } public class Statements_TestClass_for_003 { public static int Main_old(string[] args) { int i = 0; int ret = 10; for (; i < 10; i++) ret--; return (ret); } public static bool testMethod() { return (Main_old(null) == 0); } } public class Statements_TestClass_for_004 { public static int Main_old(string[] args) { for (int i = 0; i < 10; ) i++; return (0); } public static bool testMethod() { return (Main_old(null) == 0); } } public class Statements_TestClass_for_006 { public static int Main_old(string[] args) { int ret = 10; for (int i = 0; i < 10; i++) ret--; return (ret); } public static bool testMethod() { return (Main_old(null) == 0); } } public class Statements_TestClass_for_007 { public static int Main_old(string[] args) { int ret1 = 10; int ret2 = -10; for (int i = 0; i < 10; i++) { ret1--; ret2++; } return (ret1 | ret2); // bit or } public static bool testMethod() { return (Main_old(null) == 0); } } public class Statements_TestClass_for_008 { public static int Main_old(string[] args) { int ret1 = 10; int ret2 = 0; for (int i = 0, j = -10; i < 10; i++) { ret1--; j++; ret2 = j; } return (ret1 | ret2); // bit or } public static bool testMethod() { return (Main_old(null) == 0); } } public class Statements_TestClass_for_009 { public static int Main_old(string[] args) { int ret = 10; int i, j, k; for (i = 0, j = i + 1, k = j + 1; i < 10; i++) { ret--; k++; j++; } if (i + 1 != j) { Log.Comment("Failure: i + 1 != j"); return (1); } if (j + 1 != k) { Log.Comment("Failure: j + 1 != k"); return (1); } return (ret); } public static bool testMethod() { return (Main_old(null) == 0); } } public class Statements_TestClass_for_010 { public static int Main_old(string[] args) { int ret = 10; int i, j = 1, k = 2; for (i = 0; i < 10; i++, j++, k++) { ret--; } if (i + 1 != j) { Log.Comment("Failure: i + 1 != j"); return (1); } if (j + 1 != k) { Log.Comment("Failure: j + 1 != k"); return (1); } return (ret); } public static bool testMethod() { return (Main_old(null) == 0); } } public class Statements_TestClass_for_011 { public static int Main_old(string[] args) { int ret = 10; int i, j, k = 2; for (i = 0, j = i + 1; i < 10; i++, k++) { ret--; j++; } if (i + 1 != j) { Log.Comment("Failure: i + 1 != j"); return (1); } if (j + 1 != k) { Log.Comment("Failure: j + 1 != k"); return (1); } return (ret); } public static bool testMethod() { return (Main_old(null) == 0); } } public class Statements_TestClass_for_013 { public static int Main_old(string[] args) { int ret = 0; for (; false; ret++) ; return (ret); } public static bool testMethod() { return (Main_old(null) == 0); } } public class Statements_TestClass_for_014 { public static int Main_old(string[] args) { int ret = 10; for (Initializer(); Conditional(); Iterator()) ret = Body(ret); return (ret); } public static int Initializer() { m_i = 0; return (0); } public static bool Conditional() { return (m_i < 10); } public static void Iterator() { m_i++; } public static int Body(int ret) { return (--ret); } private static int m_i; public static bool testMethod() { return (Main_old(null) == 0); } } public class Statements_TestClass_char_in_string_s01 { public static int Main_old() { String Str = new String('\0', 1024); int i = 0; foreach (char C in Str) { i++; if (C != '\0') return 1; } return 0; } public static bool testMethod() { return (Main_old() == 0); } } public class Statements_TestClass_char_in_string_ex01 { public static int Main_old() { String Str = null; try { foreach (char C in Str) { return 1; Log.Comment("Fail"); } } catch (System.Exception) { return 0; } return 1; } public static bool testMethod() { return (Main_old() == 0); } } public class Statements_TestClass_while_001 { public static int Main_old(string[] args) { int i = 0; int j = 10; // post decrement test as well while (j-- > 0) i++; if (i == 10) return (0); return (1); } public static bool testMethod() { return (Main_old(null) == 0); } } public class Statements_TestClass_while_002 { public static int Main_old(string[] args) { int i = 0; int j = 10; // post decrement test as well while (j > 0) { j--; i++; } if (i == 10) return (0); return (1); } public static bool testMethod() { return (Main_old(null) == 0); } } public class Statements_TestClass_while_003 { public static int Main_old(string[] args) { bool bFalse = false; while (bFalse) return (1); return (0); } public static bool testMethod() { return (Main_old(null) == 0); } } public class Statements_TestClass_while_004 { public static int Main_old(string[] args) { bool bTrue = true; while (bTrue) return (0); return (1); } public static bool testMethod() { return (Main_old(null) == 0); } } public class Statements_TestClass_while_005 { public static int Main_old(string[] args) { bool bFalse = false; while (bFalse) { Log.Comment("Hello World"); return (1); } return (0); } public static bool testMethod() { return (Main_old(null) == 0); } } public class Statements_TestClass_while_006 { public static int Main_old(string[] args) { bool bTrue = true; while (bTrue) { Log.Comment("Hello World"); return (0); } return (1); } public static bool testMethod() { return (Main_old(null) == 0); } } public class Statements_TestClass_break_001 { public static int Main_old(string[] args) { while (true) break; do break; while (true); for (; true; ) break; int[] iArr = new int[20]; foreach (int i in iArr) break; return (0); } public static bool testMethod() { return (Main_old(null) == 0); } } public class Statements_TestClass_break_002 { public static int Main_old(string[] args) { int ret = 0; while (true) { break; ret++; } do { break; ret++; } while (true); for (; true; ) { break; ret++; } int[] iArr = new int[20]; foreach (int i in iArr) { break; ret++; } return (ret); } public static bool testMethod() { return (Main_old(null) == 0); } } public class Statements_TestClass_break_003 { public static int Main_old(string[] args) { int ret = 1; switch (ret) { case 1: ret = 0; break; } return (ret); } public static bool testMethod() { return (Main_old(null) == 0); } } public class Statements_TestClass_break_006 { public static int Main_old(string[] args) { int ret = 0; while (true) { if (ret == 0) break; ret = 1; } return (ret); } public static bool testMethod() { return (Main_old(null) == 0); } } public class Statements_TestClass_break_007 { public static int Main_old(string[] args) { int ret = 0; while (true) { if (ret == 0) { break; ret = 1; } ret = 1; } return (ret); } public static bool testMethod() { return (Main_old(null) == 0); } } public class Statements_TestClass_break_010 { public static int Main_old(string[] args) { int ret = 3; while (true) { do { for (ret--; true; ret--) { break; } ret--; break; } while (true); ret--; break; } return (ret); } public static bool testMethod() { return (Main_old(null) == 0); } } public class Statements_TestClass_continue_001 { public static int Main_old(string[] args) { int i = 5; int ret = 0; Log.Comment("Doing while"); while (--i != 0) continue; if (i != 0) return (1); Log.Comment("Doing do/while"); i = 5; do continue; while (--i != 0); if (i != 0) return (1); Log.Comment("Doing for"); for (i = 5; i != 0; i--) continue; int[] iArr = new int[20]; foreach (int i2 in iArr) continue; return (ret); } public static bool testMethod() { return (Main_old(null) == 0); } } public class Statements_TestClass_continue_002 { public static int Main_old(string[] args) { int i = 1; int ret = 6; Log.Comment(ret.ToString()); while (i-- > 0) { ret--; continue; ret--; } Log.Comment(ret.ToString()); i = 1; do { ret--; continue; ret--; } while (--i > 0); Log.Comment(ret.ToString()); for (i = 1; i > 0; i--) { ret--; continue; ret--; } int[] iArr = new int[3]; i = 0; Log.Comment(ret.ToString()); foreach (int i2 in iArr) { ret--; continue; ret--; } Log.Comment(ret.ToString()); return (ret); } public static bool testMethod() { return (Main_old(null) == 0); } } public class Statements_TestClass_continue_006 { public static int Main_old(string[] args) { int ret = 10; while (ret > 0) { if (--ret >= 0) continue; return (1); } return (ret); } public static bool testMethod() { return (Main_old(null) == 0); } } public class Statements_TestClass_continue_007 { public static int Main_old(string[] args) { int ret = 1; while (ret != 0) { if (ret == 1) { ret = 0; continue; ret = 1; } ret = 1; } return (ret); } public static bool testMethod() { return (Main_old(null) == 0); } } public class Statements_TestClass_continue_010 { public static int Main_old(string[] args) { int ret = 125; int iWhile = 5, iDo = 5, iFor = 6; while (iWhile-- > 0) { if (iDo != 5) return (1); do { if (iFor != 6) return (1); for (iFor--; iFor > 0; iFor--) { ret--; continue; return (1); } iFor = 6; iDo--; continue; return (1); } while (iDo > 0); iDo = 5; continue; return (1); } return (ret); } public static bool testMethod() { return (Main_old(null) == 0); } } public class Statements_TestClass_goto_001 { public static int Main_old(string[] args) { goto Label2; // jump ahead return (1); Label1: goto Label3; // end it return (1); Label2: goto Label1; // jump backwards return (1); Label3: return (0); } public static bool testMethod() { return (Main_old(null) == 0); } } public class Statements_TestClass_goto_008 { public static int Main_old(string[] args) { int s = 23; int ret = 5; switch (s) { case 21: break; case 23: if (--ret > 0) goto case 23; break; } return (ret); } public static bool testMethod() { return (Main_old(null) == 0); } } public class Statements_TestClass_goto_009 { public static int Main_old(string[] args) { int ret = 6; switch (32) { case 1: if (--ret > 0) { Log.Comment("Case 1:" + ret.ToString()); goto case 32; } break; case 32: if (--ret > 0) { Log.Comment("Case 32:" + ret.ToString()); goto case 1; } break; } return (ret); } public static bool testMethod() { return (Main_old(null) == 0); } } public class Statements_TestClass_goto_010 { public static int Main_old(string[] args) { int s = 23; int ret = 5; switch (s) { case 21: break; default: if (--ret > 0) goto default; break; case 23: goto default; } return (ret); } public static bool testMethod() { return (Main_old(null) == 0); } } public class Statements_TestClass_goto_014 { public static int Main_old(string[] args) { bool bLoopOnce = true; int i = 0; Top: for (i = 0; i < 10; i++) { if (i > 5) return (1); if (i == 5) goto LeaveFor; } LeaveFor: i = 0; do { if (++i > 5) return (1); if (i == 5) { goto LeaveDo; } } while (i < 10); LeaveDo: i = 0; while (i < 10) { if (++i > 5) return (1); if (i == 5) goto LeaveWhile; } LeaveWhile: if (bLoopOnce) { bLoopOnce = !bLoopOnce; while (true) { do { for (; ; ) { goto Top; } } while (true); } } return (0); } public static bool testMethod() { return (Main_old(null) == 0); } } public class Statements_TestClass_goto_017 { public static int Main_old(string[] args) { string target = "label1"; label1: label2: if (target == "label1") { target = "label2"; goto label1; } else if (target == "label2") { target = "exit"; goto label2; } return 0; } public static bool testMethod() { return (Main_old(null) == 0); } } public class Statements_TestClass_goto_018 { public static int Main_old(string[] args) { string target = "label1"; label1: try { if (target == "label1") { target = "exit"; goto label1; } } catch { } finally { } return 0; } public static bool testMethod() { return (Main_old(null) == 0); } } public class Statements_TestClass_return_001 { public static int Main_old(string[] args) { Statements_TestClass_return_001.sMethod(); Statements_TestClass_return_001 t = new Statements_TestClass_return_001(); t.Method(); return (0); } private static void sMethod() { return; } private void Method() { return; } public static bool testMethod() { return (Main_old(null) == 0); } } public class Statements_TestClass_return_004 { public static int Main_old(string[] args) { int i; i = Statements_TestClass_return_004.sMethod(); Statements_TestClass_return_004.sMethod(); Statements_TestClass_return_004 t = new Statements_TestClass_return_004(); i = t.Method(); t.Method(); return(i == 0 ? 0 : 1); } private static int sMethod() { return (1); } private int Method() { return (0); } public static bool testMethod() { return (Main_old(null) == 0); } } public class Statements_TestClass_return_006 { public static int Main_old(string[] args) { int i; i = Statements_TestClass_return_006.sMethod(); if (i != 0) return(1); Statements_TestClass_return_006 t = new Statements_TestClass_return_006(); i = t.Method(); return(i == 0 ? 0 : 1); } private static int sMethod() { short s = 0; return (s); } private int Method() { short s = 0; return (s); } public static bool testMethod() { return (Main_old(null) == 0); } } public class Statements_TestClass_return_008 { public static int Main_old(string[] args) { short s; s = Statements_TestClass_return_008.sMethod(); if (s != 0) return(1); Statements_TestClass_return_008 t = new Statements_TestClass_return_008(); s = t.Method(); return(s == 0 ? 0 : 1); } private static short sMethod() { int i = 0; return ((short)i); } private short Method() { int i = 0; return ((short)i); } public static bool testMethod() { return (Main_old(null) == 0); } } struct S { public int i; public string s; } public class Statements_TestClass_return_009 { public static int Main_old(string[] args) { S s; s = Statements_TestClass_return_009.sMethod(); if (s.i.ToString().CompareTo(s.s) != 0) { return(1); } Statements_TestClass_return_009.sMethod(); Statements_TestClass_return_009 t = new Statements_TestClass_return_009(); s = t.Method(); t.Method(); if (s.i.ToString().CompareTo(s.s) != 0) { return(1); } return(s.i == 0 ? 0 : 1); } private static S sMethod() { S s; s.i = 1; s.s = s.i.ToString(); return (s); } private S Method() { S s; s.i = 0; s.s = s.i.ToString(); return (s); } public static bool testMethod() { return (Main_old(null) == 0); } } class C { public int i; public string s; } public class Statements_TestClass_return_010 { public static int Main_old(string[] args) { C c; c = Statements_TestClass_return_010.sMethod(); if (c.i.ToString().CompareTo(c.s) != 0) { return(1); } Statements_TestClass_return_010.sMethod(); Statements_TestClass_return_010 t = new Statements_TestClass_return_010(); c = t.Method(); t.Method(); if (c.i.ToString().CompareTo(c.s) != 0) { return(1); } return(c.i == 0 ? 0 : 1); } private static C sMethod() { C c = new C(); c.i = 1; c.s = c.i.ToString(); return (c); } private C Method() { C c = new C(); c.i = 0; c.s = c.i.ToString(); return (c); } public static bool testMethod() { return (Main_old(null) == 0); } } public class Statements_TestClass_return_013 { public static int Main_old(string[] args) { Statements_TestClass_return_013.sMethod(); Statements_TestClass_return_013 t = new Statements_TestClass_return_013(); t.Method(); return (0); } private static void sMethod() { } private void Method() { } public static bool testMethod() { return (Main_old(null) == 0); } } public class Statements_TestClass_return_014 { public static int Main_old(string[] args) { int i; i = Statements_TestClass_return_014.sMethod(1); Statements_TestClass_return_014.sMethod(2); Statements_TestClass_return_014 t = new Statements_TestClass_return_014(); i = t.Method(3); t.Method(4); return(i == 0 ? 0 : 1); } private static int sMethod(int i) { if (i > 0) return (1); throw new System.Exception(); } private int Method(int i) { if (i == 0) { return (0); } else { if (i > 0) { switch (i) { case 1: return (0); case 3: while (i > 0) { return (0); } for (; i < 0; ) { return (1); } throw new System.Exception(); default: return (0); } } else { return (0); } } } public static bool testMethod() { return (Main_old(null) == 0); } } public class Statements_TestClass_throw_001 { public static int Main_old(string[] args) { int i; i = Statements_TestClass_throw_001.sMethod(); if (i > 0) return(1); Statements_TestClass_throw_001.sMethod(); Statements_TestClass_throw_001 t = new Statements_TestClass_throw_001(); i = t.Method(); t.Method(); return(i == 0 ? 0 : 1); } private static int sMethod() { try { throw new System.Exception(); } catch (System.Exception e) { return (0); } return (1); } private int Method() { try { throw new System.Exception(); } catch (System.Exception e) { return (0); } return (1); } public static bool testMethod() { return (Main_old(null) == 0); } } public class Statements_TestClass_throw_005 { public static int Main_old(string[] args) { int i; i = Statements_TestClass_throw_005.sMethod(); return(i == 0 ? 0 : 1); } private static int sMethod() { int i = 1; try { System.Exception e = new System.Exception(); throw (e); } catch (System.Exception e) { Log.Comment(e.ToString()); return (0); } return (i); } public static bool testMethod() { return (Main_old(null) == 0); } } public class Statements_TestClass_trycatch_001 { public static int Main_old(string[] args) { int i; Statements_TestClass_trycatch_001 t = new Statements_TestClass_trycatch_001(); i = t.Method(); return(i == 0 ? 0 : 1); } private int Method() { try { throw new System.Exception(); } catch (System.Exception e) { return (0); } return (1); } public static bool testMethod() { return (Main_old(null) == 0); } } public class Statements_TestClass_trycatch_006 { public static int Main_old(string[] args) { int i; Statements_TestClass_trycatch_006 t = new Statements_TestClass_trycatch_006(); i = t.Method(0); return(i == 0 ? 0 : 1); } private int Method(int i) { try { int x = 1 / i; Log.Comment(x.ToString()); // prevent it being optimized away } catch (System.Exception e) { return (0); } return (1); } public static bool testMethod() { return (Main_old(null) == 0); } } public class Statements_TestClass_trycatch_007 { public static int Main_old(string[] args) { int i; Statements_TestClass_trycatch_007 t = new Statements_TestClass_trycatch_007(); i = t.Method(); int tt = i == 0 ? 0 : 1; Log.Comment("Value is" + tt); return(i == 0 ? 0 : 1); } private int Method() { try { try { Thrower(); //throw new System.Exception(); } catch (System.Exception e) { Log.Comment("Rethrow"); throw; } } catch (System.Exception e) { Log.Comment("Recatch"); return (0); } return (1); } private void Thrower() { throw new System.Exception(); } public static bool testMethod() { return (Main_old(null) == 0); } } public class Statements_TestClass_tryfinally_001 { public static int Main_old(string[] args) { int i; Statements_TestClass_tryfinally_001 t = new Statements_TestClass_tryfinally_001(); i = t.Method(2); return(i == 0 ? 0 : 1); } private int Method(int i) { try { i--; } finally { i--; } return (i); } public static bool testMethod() { return (Main_old(null) == 0); } } public class Statements_TestClass_tryfinally_002 { public static int Main_old(string[] args) { int i; Statements_TestClass_tryfinally_002 t = new Statements_TestClass_tryfinally_002(); i = t.Method(1); return(i == 0 ? 0 : 1); } private int Method(int i) { try { try { throw new System.Exception(); } finally { i--; } } catch { } return (i); } public static bool testMethod() { return (Main_old(null) == 0); } } public class Statements_TestClass_tryfinally_003 { public static int Main_old(string[] args) { int i; Statements_TestClass_tryfinally_003 t = new Statements_TestClass_tryfinally_003(); i = t.Method(1); return(i == 0 ? 0 : 1); } private int Method(int i) { try { try { throw new System.Exception(); } catch { } } finally { i--; } return (i); } public static bool testMethod() { return (Main_old(null) == 0); } } public class Statements_TestClass_tryfinally_004 { public static int Main_old(string[] args) { int i; Statements_TestClass_tryfinally_004 t = new Statements_TestClass_tryfinally_004(); i = t.Method(1); return(i == 0 ? 0 : 1); } private int Method(int i) { try { goto TheEnd; } finally { i--; } TheEnd: return (i); } public static bool testMethod() { return (Main_old(null) == 0); } } public class Statements_TestClass_tryfinally_006 { public static int Main_old(string[] args) { int i = 0; Statements_TestClass_tryfinally_006 t = new Statements_TestClass_tryfinally_006(); try { i = t.Method(1); } catch {} return(i == 0 ? 0 : 1); } private int Method(int i) { try { throw new System.Exception(); } finally { i--; } return (i); } public static bool testMethod() { return (Main_old(null) == 0); } } public class Statements_TestClass_tryfinally_007 { public static int Main_old(string[] args) { int i = 0; Statements_TestClass_tryfinally_007 t = new Statements_TestClass_tryfinally_007(); try { i = t.Method(1); } catch {} return(i == 0 ? 0 : 1); } private int Method(int i) { try { DeepMethod(i); } finally { i--; } return (i); } private int DeepMethod(int i) { throw new System.Exception(); } public static bool testMethod() { return (Main_old(null) == 0); } } public class Statements_TestClass_tryfinally_008 { public static int Main_old(string[] args) { int i = 1; Statements_TestClass_tryfinally_008 t = new Statements_TestClass_tryfinally_008(); try { i = t.Method(0); } catch {} return(i == 0 ? 0 : 1); } private int Method(int i) { try { return (i); } finally { i++; } return (i); } public static bool testMethod() { return (Main_old(null) == 0); } } public class Statements_TestClass_tryfinally_009 { public static int Main_old(string[] args) { int i = 1; Statements_TestClass_tryfinally_009 t = new Statements_TestClass_tryfinally_009(); try { i = t.Method(1); } catch {} return(i == 0 ? 0 : 1); } private int Method(int i) { bool b = true; while (b) { try { b = false; continue; } finally { i--; } } return (i); } public static bool testMethod() { return (Main_old(null) == 0); } } public class Statements_TestClass_tryfinally_010 { public static int Main_old(string[] args) { int i = 1; Statements_TestClass_tryfinally_010 t = new Statements_TestClass_tryfinally_010(); try { i = t.Method(1); } catch {} return(i == 0 ? 0 : 1); } private int Method(int i) { while (true) { try { break; } finally { i--; } } return (i); } public static bool testMethod() { return (Main_old(null) == 0); } } public class Statements_TestClass_tryfinally_011 { public static int Main_old(string[] args) { int i = 1; Statements_TestClass_tryfinally_011 t = new Statements_TestClass_tryfinally_011(); try { i = t.Method(0); } catch {} return(i == 0 ? 0 : 1); } private int Method(int i) { while (true) { break; try { break; } finally { i++; } } return (i); } public static bool testMethod() { return (Main_old(null) == 0); } } public class Statements_TestClass_tryfinally_012 { public static int Main_old(string[] args) { int i = 0; bool bCatch = false; Statements_TestClass_tryfinally_012 t = new Statements_TestClass_tryfinally_012(); try { i = t.Method(1); } catch { bCatch = true; } if (!bCatch) i = 1; return(i == 0 ? 0 : 1); } private int Method(int i) { try { Log.Comment((10 / (i - 1)).ToString()); } finally { i--; } return (i); } public static bool testMethod() { return (Main_old(null) == 0); } } class Statements_TestClass_tryfinally_013 { static void Main_old(string[] args) { before_try: try { } catch (Exception) { goto before_try; } finally { before_inner_try: try { } catch (Exception) { goto before_inner_try; } finally { } } } public static bool testMethod() { Main_old(null); return true; } } // two normal classes... public class Statements_TestClass_Using_001 { public static void Main_old() { Res1 res1 = new Res1(); IDisposable id = (IDisposable)res1; using (id) { res1.Func(); } } public static bool testMethod() { Main_old(); return true; } } // two normal classes... public class Statements_TestClass_Using_002 { public static void Main_old() { Res1 res1 = new Res1(); using (res1) { res1.Func(); } } public static bool testMethod() { Main_old(); return true; } } // two normal classes... public class Statements_TestClass_Using_003 { public static void Main_old() { using (Res1 res1 = new Res1()) { res1.Func(); } } public static bool testMethod() { Main_old(); return true; } } // two normal classes... public class Statements_TestClass_Using_005 { public static void Main_old() { using (ResExplicit resExplicit = new ResExplicit()) { resExplicit.Func(); } } public static bool testMethod() { Main_old(); return true; } } // two normal classes... public class Statements_TestClass_Using_009 { public static void Main_old() { Res1 res1 = new Res1(); using (res1) { res1.Func(); res1 = null; } } public static bool testMethod() { Main_old(); return true; } } // two normal classes... public class Statements_TestClass_Using_010 { public static void Main_old() { using (Res1 res1 = new Res1()) { res1.Func(); } } public static bool testMethod() { Main_old(); return true; } } // two normal classes... public class Statements_TestClass_Using_011 { public static void Main_old() { try { using (Res1 res1 = new Res1()) { res1.Throw(); } } catch { Log.Comment("System.Exception caught"); } } public static bool testMethod() { Main_old(); return true; } } // two normal classes... public class Statements_TestClass_Using_012 { public static void Main_old() { using (Res1 res1 = new Res1()) { res1.Func(); using (Res2 res2 = new Res2()) { res2.Func(); } } } public static bool testMethod() { Main_old(); return true; } } // two normal classes... public class Statements_TestClass_Using_013 { public static void Main_old() { try { using (Res1 res1 = new Res1()) { res1.Func(); res1.Throw(); using (Res2 res2 = new Res2()) { res2.Func(); } } } catch { Log.Comment("System.Exception caught"); } } public static bool testMethod() { Main_old(); return true; } } // two normal classes... public class Statements_TestClass_Using_014 { public static void Main_old() { try { using (Res1 res1 = new Res1()) { res1.Func(); using (Res2 res2 = new Res2()) { res2.Func(); } res1.Throw(); } } catch { Log.Comment("System.Exception caught"); } } public static bool testMethod() { Main_old(); return true; } } // two normal classes... public class Statements_TestClass_Using_015 { public static void Main_old() { try { using (Res1 res1 = new Res1()) { res1.Func(); using (Res2 res2 = new Res2()) { res2.Func(); res1.Throw(); } } } catch { Log.Comment("System.Exception caught"); } } public static bool testMethod() { Main_old(); return true; } } // two normal classes... public class Statements_TestClass_Using_017 { public static void Main_old() { try { using (Res1 res1 = new Res1(), res1a = new Res1()) { res1.Func(); res1.Func(); res1.Throw(); } } catch { Log.Comment("System.Exception caught"); } } public static bool testMethod() { Main_old(); return true; } } // two normal classes... public class Statements_TestClass_Using_018 { public static void Main_old() { using (Res1 res1 = new Res1(), res1a = new Res1()) { res1.Func(); res1a.Func(); } } public static bool testMethod() { Main_old(); return true; } } class Statements_TestClass_lock001 { public static int Main_old() { Statements_TestClass_lock001 C = new Statements_TestClass_lock001(); lock (C) { return 0; } } public static bool testMethod() { return (Main_old() == 0); } } class Statements_TestClass_lock003 { public static int Main_old() { lock (typeof(Statements_TestClass_lock003)) { return 0; } } public static bool testMethod() { return (Main_old() == 0); } } class Statements_TestClass_lock004 { public static int Main_old() { lock (typeof(Statements_TestClass_lock004)) ; { return 0; } } public static bool testMethod() { return (Main_old() == 0); } } class Statements_TestClass_lock005 { public void TryMe() { lock (this) { } } public static int Main_old() { return 0; } public static bool testMethod() { return (Main_old() == 0); } } class Statements_TestClass_lock007 { public static int Main_old() { lock (typeof(Statements_TestClass_lock007)) { Statements_TestClass_lock007 C = new Statements_TestClass_lock007(); lock (C) { return 0; } } } public static bool testMethod() { return (Main_old() == 0); } } public class Statements_TestClass_enum_002 { private const int CONST = 2; public static int Main_old(string[] args) { int i = 2; if (i < (int)(MyEnum)CONST) return 1; if (i == (int)(MyEnum)0) return 1; return 0; } public static bool testMethod() { return (Main_old(null) == 0); } } public enum MyEnum { aaa, bbb, ccc } } } ================================================ FILE: Zelig/Zelig/Test/RunTime/NETMF/mscorlib/structs/StructsTests.cs ================================================ //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // Copyright (c) Microsoft Corporation. All rights reserved. //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// using System; using System.Reflection; using Microsoft.Zelig.Test; namespace Microsoft.Zelig.Test { public class StructsTests : TestBase, ITestInterface { [SetUp] public InitializeResult Initialize() { Log.Comment("Adding set up for the tests"); return InitializeResult.ReadyToGo; } [TearDown] public void CleanUp() { Log.Comment("Cleaning up after the tests"); } public override TestResult Run( string[] args ) { TestResult result = TestResult.Pass; string testName = "Structs"; result |= Assert.CheckFailed(Structs01_Test(), testName, 1); result |= Assert.CheckFailed(Structs04_Test(), testName, 4); result |= Assert.CheckFailed(Structs11_Test(), testName, 11); result |= Assert.CheckFailed(Structs12_Test(), testName, 12); result |= Assert.CheckFailed(Structs13_Test(), testName, 13); result |= Assert.CheckFailed(Structs14_Test(), testName, 14); result |= Assert.CheckFailed(Structs15_Test(), testName, 15); result |= Assert.CheckFailed(Structs19_Test(), testName, 19); result |= Assert.CheckFailed(Structs21_Test(), testName, 21); result |= Assert.CheckFailed(Structs23_Test(), testName, 23); result |= Assert.CheckFailed(Structs24_Test(), testName, 24); result |= Assert.CheckFailed(Structs26_Test(), testName, 26); result |= Assert.CheckFailed(Structs28_Test(), testName, 28); result |= Assert.CheckFailed(Structs29_Test(), testName, 29); result |= Assert.CheckFailed(Structs32_Test(), testName, 32); result |= Assert.CheckFailed(Structs33_Test(), testName, 33); result |= Assert.CheckFailed(Structs34_Test(), testName, 34); result |= Assert.CheckFailed(Structs35_Test(), testName, 35); result |= Assert.CheckFailed(Structs36_Test(), testName, 36); result |= Assert.CheckFailed(Structs37_Test(), testName, 37); result |= Assert.CheckFailed(Structs38_Test(), testName, 38); result |= Assert.CheckFailed(Structs40_Test(), testName, 40); result |= Assert.CheckFailed(Structs41_Test(), testName, 41); result |= Assert.CheckFailed(Structs42_Test(), testName, 42); result |= Assert.CheckFailed(Structs43_Test(), testName, 43); result |= Assert.CheckFailed(Structs44_Test(), testName, 44); result |= Assert.CheckFailed(Structs55_Test(), testName, 55); return result; } //Structs Test methods //The following tests were ported from folder current\test\cases\client\CLR\Conformance\10_classes\Structs //Test Case Calls [TestMethod] public TestResult Structs01_Test() { StructsTestClass_01_Notes.Note(); if (StructsTestClass_01.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Structs04_Test() { StructsTestClass_04_Notes.Note(); if (StructsTestClass_04.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Structs11_Test() { StructsTestClass_11_Notes.Note(); if (StructsTestClass_11.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Structs12_Test() { StructsTestClass_12_Notes.Note(); if (StructsTestClass_12.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Structs13_Test() { StructsTestClass_13_Notes.Note(); if (StructsTestClass_13.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Structs14_Test() { StructsTestClass_14_Notes.Note(); if (StructsTestClass_14.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Structs15_Test() { StructsTestClass_15_Notes.Note(); if (StructsTestClass_15.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Structs19_Test() { StructsTestClass_19_Notes.Note(); if (StructsTestClass_19.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Structs21_Test() { StructsTestClass_21_Notes.Note(); if (StructsTestClass_21.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Structs23_Test() { StructsTestClass_23_Notes.Note(); if (StructsTestClass_23.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Structs24_Test() { StructsTestClass_24_Notes.Note(); if (StructsTestClass_24.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Structs26_Test() { StructsTestClass_26_Notes.Note(); if (StructsTestClass_26.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Structs28_Test() { StructsTestClass_28_Notes.Note(); if (StructsTestClass_28.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Structs29_Test() { StructsTestClass_29_Notes.Note(); if (StructsTestClass_29.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Structs32_Test() { StructsTestClass_32_Notes.Note(); if (StructsTestClass_32.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Structs33_Test() { StructsTestClass_33_Notes.Note(); if (StructsTestClass_33.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Structs34_Test() { StructsTestClass_34_Notes.Note(); if (StructsTestClass_34.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Structs35_Test() { StructsTestClass_35_Notes.Note(); if (StructsTestClass_35.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Structs36_Test() { StructsTestClass_36_Notes.Note(); if (StructsTestClass_36.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Structs37_Test() { StructsTestClass_37_Notes.Note(); if (StructsTestClass_37.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Structs38_Test() { StructsTestClass_38_Notes.Note(); if (StructsTestClass_38.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Structs40_Test() { StructsTestClass_40_Notes.Note(); if (StructsTestClass_40.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Structs41_Test() { StructsTestClass_41_Notes.Note(); if (StructsTestClass_41.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Structs42_Test() { StructsTestClass_42_Notes.Note(); if (StructsTestClass_42.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Structs43_Test() { StructsTestClass_43_Notes.Note(); if (StructsTestClass_43.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Structs44_Test() { StructsTestClass_44_Notes.Note(); if (StructsTestClass_44.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Structs55_Test() { StructsTestClass_55_Notes.Note(); if (StructsTestClass_55.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } //Compiled Test Cases class StructsTestClass_01_Notes { public static void Note() { Log.Comment(" Declaring a struct with and without a trailing semicolon. "); } } struct StructsTestClass_01_Struct1 { public int i; } struct StructsTestClass_01_Struct2 { public int i; }; public class StructsTestClass_01 { public static bool testMethod() { StructsTestClass_01_Struct1 s1; StructsTestClass_01_Struct2 s2; s1.i = 1; s2.i = 1; return( 0 == (s1.i-s2.i)); } } class StructsTestClass_04_Notes { public static void Note() { Log.Comment(" Verify all valid protection levels for members and methods"); } } struct StructsTestClass_04_Struct1 { public int pub; private int priv; internal int intern; public int StructsTestClass_04PubPriv() { return StructsTestClass_04Priv(); } private int StructsTestClass_04Priv() { pub = 1; priv = 2; return(pub + priv); } internal int StructsTestClass_04Intern() { intern = 3; return(intern); } public int GetPrivate() { return(priv); } } public class StructsTestClass_04 { public static bool testMethod() { StructsTestClass_04_Struct1 s1 = new StructsTestClass_04_Struct1(); int result; result = s1.StructsTestClass_04PubPriv(); result += s1.StructsTestClass_04Intern(); result -= s1.intern; result -= s1.pub; result -= s1.GetPrivate(); return(result == 0); } } class StructsTestClass_11_Notes { public static void Note() { Log.Comment(" Verify struct can implement an interface."); } } interface Inter1 { int Return42(); } struct StructsTestClass_11_Struct1 : Inter1 { public int Return42() { return(42); } } public class StructsTestClass_11 { public static bool testMethod() { Inter1 i1 = new StructsTestClass_11_Struct1(); return(0 == (i1.Return42() - 42)); } } class StructsTestClass_12_Notes { public static void Note() { Log.Comment(" Verify struct can implement multiple interfaces."); } } interface StructsTestClass_12_Inter1 { int Return42(); } interface StructsTestClass_12_Inter2 { int Return20(); } interface StructsTestClass_12_Inter3 { int Return22(); } struct StructsTestClass_12_Struct1 : StructsTestClass_12_Inter1, StructsTestClass_12_Inter2, StructsTestClass_12_Inter3 { public int Return42() { return(42); } public int Return20() { return(20); } public int Return22() { return(22); } } public class StructsTestClass_12 { public static bool testMethod() { StructsTestClass_12_Inter1 i1 = new StructsTestClass_12_Struct1(); return (0 == (i1.Return42() - ((StructsTestClass_12_Inter2)i1).Return20() - ((StructsTestClass_12_Inter3)i1).Return22())); } } class StructsTestClass_13_Notes { public static void Note() { Log.Comment(" Verify struct can implement multiple interfaces that contain methods with identical signatures."); } } interface StructsTestClass_13_Inter1 { int Return42(); } interface StructsTestClass_13_Inter2 { int Return42(); } interface StructsTestClass_13_Inter3 { int Return0(); } struct StructsTestClass_13_Struct1 : StructsTestClass_13_Inter1, StructsTestClass_13_Inter2, StructsTestClass_13_Inter3 { int StructsTestClass_13_Inter1.Return42() { return(42); } int StructsTestClass_13_Inter2.Return42() { return(42); } int StructsTestClass_13_Inter3.Return0() { return(0); } } public class StructsTestClass_13 { public static int Main_old() { StructsTestClass_13_Inter1 i1 = new StructsTestClass_13_Struct1(); return (i1.Return42() - ((StructsTestClass_13_Inter2)i1).Return42() - ((StructsTestClass_13_Inter3)i1).Return0()); } public static bool testMethod() { try { return (Main_old() == 0); } catch { return false; } } } class StructsTestClass_14_Notes { public static void Note() { Log.Comment(" Verify that a struct can contain a class"); } } class StructsTestClass_14_Class1 { }; struct StructsTestClass_14_Struct1 { public StructsTestClass_14_Class1 c; } public class StructsTestClass_14 { public static int Main_old() { StructsTestClass_14_Struct1 s1 = new StructsTestClass_14_Struct1(); int result = s1.c == null ? 0 : 1; return(result); } public static bool testMethod() { return (Main_old() == 0); } } class StructsTestClass_15_Notes { public static void Note() { Log.Comment(" Verify that a struct can contain another sruct"); } } struct StructsTestClass_15_Struct1 { public int i; }; struct StructsTestClass_15_Struct2 { public StructsTestClass_15_Struct1 s; public int i; } public class StructsTestClass_15 { public static int Main_old() { StructsTestClass_15_Struct2 s2 = new StructsTestClass_15_Struct2(); return(s2.s.i); } public static bool testMethod() { return (Main_old() == 0); } } class StructsTestClass_19_Notes { public static void Note() { Log.Comment("Attempt to use an empty StructsTestClass_19_Struct"); } } struct StructsTestClass_19_Struct1 { } public class StructsTestClass_19 { public static int Main_old() { StructsTestClass_19_Struct1 s = new StructsTestClass_19_Struct1(); return(0); } public static bool testMethod() { return (Main_old() == 0); } } class StructsTestClass_21_Notes { public static void Note() { Log.Comment("attempt to return a struct"); } } public struct StructsTestClass_21_Struct1 { int a; public void Set(int val) { a = val; } public int Get() { return(a); } } public class StructsTestClass_21 { public static int Main_old() { if (callQuick().Get() != 0) return(1); return(call().Get()-42); } public static bool testMethod() { return (Main_old() == 0); } public static StructsTestClass_21_Struct1 callQuick() { return(new StructsTestClass_21_Struct1()); } public static StructsTestClass_21_Struct1 call() { StructsTestClass_21_Struct1 s = new StructsTestClass_21_Struct1(); s.Set(42); return(s); } } class StructsTestClass_23_Notes { public static void Note() { Log.Comment("struct like an object"); } } struct StructsTestClass_23_Struct1 { public int i; } public class StructsTestClass_23 { public static int Main_old() { StructsTestClass_23_Struct1 s = new StructsTestClass_23_Struct1(); s.i = 42; return(0); } public static bool testMethod() { return (Main_old() == 0); } } class StructsTestClass_24_Notes { public static void Note() { Log.Comment(" struct values aren't changed when boxed and passed as interfaces."); } } public interface Interface1 { void SetInt(int val); int GetInt(); }; public struct StructsTestClass_24_Struct1 : Interface1 { public int i; public void SetInt(int val) { i = val; } public int GetInt() { return(i); } } public class StructsTestClass_24 { public static int Main_old() { StructsTestClass_24_Struct1 s = new StructsTestClass_24_Struct1(); s.i = 42; Call(s); return(s.i == 42 ? 0 : 1); } public static void Call(Interface1 iface) { if (iface.GetInt() != 42) { throw new System.Exception(); throw new System.Exception("expected i == 42"); } iface.SetInt(99); } public static bool testMethod() { return (Main_old() == 0); } } class StructsTestClass_26_Notes { public static void Note() { Log.Comment(" StructsTestClass_26_A ttempt to make a parameterized conStructsTestClass_26_Structor for a StructsTestClass_?_Struct."); } } struct StructsTestClass_26_Struct1 { public StructsTestClass_26_Struct1(int j) { i = j; } public int i; } public class StructsTestClass_26 { public static int Main_old() { StructsTestClass_26_Struct1 s = new StructsTestClass_26_Struct1(42); return(s.i - 42); } public static bool testMethod() { return (Main_old() == 0); } } class StructsTestClass_28_Notes { public static void Note() { Log.Comment(" Explicit test of object boxing conversions to and from a StructsTestClass_28_Struct."); } } struct StructsTestClass_28_Struct1 { public int i; } public class StructsTestClass_28 { static public int Main_old() { StructsTestClass_28_Struct1 s1 = new StructsTestClass_28_Struct1(); Object converter = s1; StructsTestClass_28_Struct1 s2 = (StructsTestClass_28_Struct1) converter; return 0; } public static bool testMethod() { return (Main_old() == 0); } } class StructsTestClass_29_Notes { public static void Note() { Log.Comment(" StructsTestClass_29 conStructsTestClass_29_Structor forwarding works for StructsTestClass_?_Structs"); } } struct Foo { public Foo(int x): this(5, 6) { } public Foo(int x, int y) { m_x = x; m_y = y; } public int m_x; public int m_y; } public class StructsTestClass_29 { static public int Main_old() { Foo s1 = new Foo(1); if (s1.m_x != 5) return(1); if (s1.m_y != 6) return(1); return 0; } public static bool testMethod() { return (Main_old() == 0); } } class StructsTestClass_32_Notes { public static void Note() { Log.Comment(" nested struct should work"); } } public struct StructsTestClass_32_Struct{ public struct Nested{ public int i; } public Nested n; } public class StructsTestClass_32 { public static bool testMethod() { StructsTestClass_32_Struct s = new StructsTestClass_32_Struct(); StructsTestClass_32_Struct.Nested nn = new StructsTestClass_32_Struct.Nested(); nn.i = 10; s.n = nn; //value copy if(s.n.i == nn.i) return true; else return false; } } class StructsTestClass_33_Notes { public static void Note() { Log.Comment(" nested class inside struct should work"); } } public struct StructsTestClass_33_Struct{ public class Nested{ public int i; } public Nested n; } public class StructsTestClass_33 { public static bool testMethod() { StructsTestClass_33_Struct s = new StructsTestClass_33_Struct(); StructsTestClass_33_Struct.Nested nn = new StructsTestClass_33_Struct.Nested(); nn.i = 10; s.n = nn; //value copy if(s.n.i == nn.i) return true; else return false; } } class StructsTestClass_34_Notes { public static void Note() { Log.Comment(" nested struct should work"); } } public struct StructsTestClass_34_Struct { public struct Nested { public struct NestedNested { public int i; } public int i; //in different scope } public Nested n; } public class StructsTestClass_34 { public static bool testMethod() { StructsTestClass_34_Struct s = new StructsTestClass_34_Struct(); StructsTestClass_34_Struct.Nested nn = new StructsTestClass_34_Struct.Nested(); nn.i = 10; s.n = nn; //value copy StructsTestClass_34_Struct.Nested.NestedNested nnn = new StructsTestClass_34_Struct.Nested.NestedNested(); if(s.n.i != nn.i) return false; nnn.i = 20; s.n.i = nnn.i; if(nn.i == 10 && s.n.i == nnn.i)//check nn.i did not changed return true; else return false; } } class StructsTestClass_35_Notes { public static void Note() { Log.Comment(" cast struct to inherited interface type"); } } public interface StructsTestClass_35_Interface { int foo(); } public struct StructsTestClass_35_A : StructsTestClass_35_Interface { public int foo() { return 10; } } public class StructsTestClass_35 { public static bool testMethod() { StructsTestClass_35_Interface a = new StructsTestClass_35_A (); if(a.foo() != 10) return false; else return true; } } class StructsTestClass_36_Notes { public static void Note() { Log.Comment(" cast struct to inherited interface type"); } } public interface StructsTestClass_36_Interface { int foo(); } public struct StructsTestClass_36_A : StructsTestClass_36_Interface { public int foo() { return 10; } } public class StructsTestClass_36 { public static bool testMethod() { StructsTestClass_36_Interface a = new StructsTestClass_36_A (); if(a.foo() != 10) return false; else return true; } } class StructsTestClass_37_Notes { public static void Note() { Log.Comment(" cast struct to inherited interface type"); } } public interface StructsTestClass_37_Interface { int foo(); } public struct StructsTestClass_37_A : StructsTestClass_37_Interface { public int foo() { return 10; } } public class StructsTestClass_37 { public static bool testMethod() { StructsTestClass_37_A a = new StructsTestClass_37_A (); object o = a; //boxing bool b = o is StructsTestClass_37_Interface ; if(!b) return false; if((a as StructsTestClass_37_Interface ) == null) return false; if(a.foo() != 10) return false; else return true; } } class StructsTestClass_38_Notes { public static void Note() { Log.Comment(" cast struct to inherited interface type through function"); } } public interface StructsTestClass_38_Interface { int foo(); } public struct StructsTestClass_38_A : StructsTestClass_38_Interface { public StructsTestClass_38_Interface GetI() { this.i = 10; return this; } public int foo() { return i; } public int i; } public class StructsTestClass_38 { public static bool testMethod() { StructsTestClass_38_A a = new StructsTestClass_38_A (); object o = a; //boxing bool b = o is StructsTestClass_38_Interface ; if(!b) return false; if((a as StructsTestClass_38_Interface ) == null) return false; if(a.GetI().foo() != 10) return false; else return true; } } class StructsTestClass_40_Notes { public static void Note() { Log.Comment(" property in struct"); } } public struct StructsTestClass_40_Struct { public int Foo { get { return 10; } } } public class StructsTestClass_40 { public static bool testMethod() { StructsTestClass_40_Struct a = new StructsTestClass_40_Struct(); if(a.Foo == 10) return true; else return false; } } class StructsTestClass_41_Notes { public static void Note() { Log.Comment(" indexer in struct"); } } public struct StructsTestClass_41_Struct { public int this[int index] { get { return index; } } } public class StructsTestClass_41 { public static bool testMethod() { StructsTestClass_41_Struct a = new StructsTestClass_41_Struct(); if(a[10] == 10) return true; else return false; } } class StructsTestClass_42_Notes { public static void Note() { Log.Comment(" interface indexer in StructsTestClass_42_Struct"); } } public interface StructsTestClass_42_Interface { int this[int index]{get;} } public struct StructsTestClass_42_A : StructsTestClass_42_Interface { public int this[int index] { get { return index; } } } public class StructsTestClass_42 { public static bool testMethod() { StructsTestClass_42_Interface a = new StructsTestClass_42_A (); if(a[10] == 10) return true; else return false; } } class StructsTestClass_43_Notes { public static void Note() { Log.Comment(" delegate in struct"); } } public struct StructsTestClass_43_Struct { public delegate int foo(); public int boo() { return 10; } } public class StructsTestClass_43 { public static bool testMethod() { StructsTestClass_43_Struct a = new StructsTestClass_43_Struct(); StructsTestClass_43_Struct.foo d = new StructsTestClass_43_Struct.foo(a.boo); if(d() == 10) return true; else return false; } } class StructsTestClass_44_Notes { public static void Note() { Log.Comment(" delegate in struct assing interface as a delegate argument"); } } public interface StructsTestClass_44_Interface { int boo(); } public struct StructsTestClass_44_A : StructsTestClass_44_Interface { public delegate int foo(); public int boo() { return 10; } } public class StructsTestClass_44 { public static bool testMethod() { StructsTestClass_44_Interface a = new StructsTestClass_44_A(); StructsTestClass_44_A .foo d = new StructsTestClass_44_A .foo(a.boo); if(d() == 10) return true; else return false; } } class StructsTestClass_55_Notes { public static void Note() { Log.Comment("The this object cannot be used before all of its fields are assigned to"); } } public struct StructsTestClass_55 { public int i; static void foo(){} StructsTestClass_55(int i) { this.i = i; foo(); } public static bool testMethod() { StructsTestClass_55 s = new StructsTestClass_55(101); return (0 == s.i - 101); } } } } ================================================ FILE: Zelig/Zelig/Test/RunTime/NETMF/mscorlib/systemlib/systemlib1/Guid.cs ================================================ //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // Copyright (c) Microsoft Corporation. All rights reserved. //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// using System; using System.Collections; using System.Text; using System.Reflection; using Microsoft.SPOT.Platform.Test; namespace Microsoft.SPOT.Platform.Tests { public interface ITest { } public class GuidTests : IMFTestInterface, ITest { [SetUp] public InitializeResult Initialize() { Log.Comment("Adding set up for the tests"); return InitializeResult.ReadyToGo; } [TearDown] public void CleanUp() { Log.Comment("Cleaning up after the tests."); } [TestMethod] public MFTestResults Guid_Test() { /// /// 1. Creates a Guid with Guid.NewGuid() /// 2. Verifies the Guid is with Byte Array length 16 /// 3. Creates same Guid /// 4. Verifies the two Guids are equal with CompareTo /// 5. Verifies the two Guids are equal with Equals /// 6. Creates another Guid with Guid.NewGuid() /// 7. Verifies the new Guid is not equal to the previous Guid with CompareTo /// 8. Verifies the new Guid is not equal to the previous Guid with Equal /// /// try { Guid theGuid = Guid.NewGuid(); byte[] bGuid1 = theGuid.ToByteArray(); if (bGuid1.Length != 16) { Log.Comment("Expected length '16' but got '" + bGuid1.Length + "'"); return MFTestResults.Fail; } Guid theSameGuid = new Guid(bGuid1); // must be the same if (theGuid.CompareTo(theSameGuid) != 0) { Log.Comment("theGuid.CompareTo(theSameGuid) Failed"); return MFTestResults.Fail; } if (!theGuid.Equals(theSameGuid)) { Log.Comment("theGuid.Equals(theSameGuid) Failed"); return MFTestResults.Fail; } Guid anotherGuid = Guid.NewGuid(); // must be the different if (theGuid.CompareTo(anotherGuid) == 0) { Log.Comment("theGuid.CompareTo(anotherGuid) Failed"); return MFTestResults.Fail; } if (theGuid.Equals(anotherGuid)) { Log.Comment("theGuid.Equals(anotherGuid) Failed"); return MFTestResults.Fail; } } catch (Exception ex) { Log.Comment("Caught Exception : " + ex.Message + " creating Guid with Guid.NewGuid()"); return MFTestResults.Fail; } return MFTestResults.Pass; } [TestMethod] public MFTestResults ByteArrayConstructor_Test2() { /// /// 1. Creates a Guid with byte Array of size 16 and random byte values /// 2. Verifies exception is not thrown /// /// MFTestResults testResult = MFTestResults.Pass; Byte[] guid16 = MFUtilities.GetRandomBytes(16); try { Guid myGuid1 = new Guid(guid16); } catch (Exception ex) { Log.Comment("Caught : " + ex.Message); testResult = MFTestResults.Fail; } return testResult; } [TestMethod] public MFTestResults ArgumentException_Test3() { /// /// 1. Creates a Guid with byte Array of random size b/n 0 to 100 but not 16 /// 2. Verifies ArgumentException is thrown /// /// MFTestResults testResult = MFTestResults.Fail; int size = 16; //size could be set to any Random number b/n 0 and 2147483647 //System.OutOfMemoryException will be thrown Random random = new Random(); while (size == 16) { size = random.Next(100); } Byte[] guidNot16 = MFUtilities.GetRandomBytes(size); try { Guid myGuid1 = new Guid(guidNot16); } catch (ArgumentException ex) { Log.Comment("Caught : " + ex.Message + " when trying to create Guid with " + size + " bytes long"); testResult = MFTestResults.Pass; } catch (Exception e) { Log.Comment("Expecting ArgumentException got " + e.Message); } return testResult; } [TestMethod] public MFTestResults ArgumentNullException_Test4() { /// /// 1. Creates a Guid with byte Array of null /// 2. Verifies ArgumentNullException is thrown /// /// MFTestResults testResult = MFTestResults.Fail; Byte[] nullByte = null; try { Guid myGuid1 = new Guid(nullByte); } catch (ArgumentNullException ex) { Log.Comment("Caught : " + ex.Message + " when trying to create Guid with null bytes"); testResult = MFTestResults.Pass; } catch (Exception e) { Log.Comment("Expecting ArgumentNullException got " + e.Message); } return testResult; } public static Guid GetGuid() { return new Guid(0x4dff36b5, 0x9dde, 0x4f76, 0x9a, 0x2a, 0x96, 0x43, 0x50, 0x47, 0x06, 0x3d); } [TestMethod] public MFTestResults Reflection_Unboxing_Test5() { /// /// 1. Creates a Guid using a method /// 2. Invokes the method using Reflection /// 3. Casts the returned obj from the method back to Guid /// 4. Verifies Exception is not thrown when castin a Guid obj back to Guid /// /// MFTestResults testResult = MFTestResults.Pass; Guid[] a = new Guid[] { GetGuid(), GetGuid(), GetGuid() }; IList list = (IList)a; Guid g = (Guid)list[1]; Log.Comment(g.ToString()); Type t = Type.GetType("Microsoft.SPOT.Platform.Tests.ITest"); Type[] apps = Reflection.GetTypesImplementingInterface(t); foreach (Type app in apps) { MethodInfo method = app.GetMethod("GetGuid", BindingFlags.Static | BindingFlags.Public); if (method != null) { object o = method.Invoke(null, null); try { Guid guid = (Guid)o; } catch (Exception ex) { Log.Comment("Caught : " + ex.Message); testResult = MFTestResults.Fail; } } } return testResult; } [TestMethod] public MFTestResults Int_Short_Constructor_Test6() { /// /// 1. Creates Guid(int, short, short, byte, byte ...) /// 2. Verifies exception is not thrown /// /// MFTestResults testResult = MFTestResults.Pass; Random random = new Random(); int _int = random.Next(Int32.MaxValue); short _short1 = (short)random.Next(32768); short _short2 = (short)random.Next(32768); Byte[] _bArr = MFUtilities.GetRandomBytes(8); try { Guid _guid = new Guid(_int, _short1, _short2, _bArr[0], _bArr[1], _bArr[2], _bArr[3], _bArr[4], _bArr[5], _bArr[6], _bArr[7]); } catch (Exception ex) { Log.Comment("Caught : " + ex.Message + "when creating Guid(" + _int + ", " + _short1 + ", " + _short2 + ", " + _bArr[0] + ", " + _bArr[1] + ", " + _bArr[2] + ", " + _bArr[3] + ", " + _bArr[4] + ", " + _bArr[5] + ", " + _bArr[6] + ", " + _bArr[7] + ")"); testResult = MFTestResults.Fail; } return testResult; } [TestMethod] public MFTestResults UInt_Ushort_Constructor_Test7() { /// /// 1. Creates a Guid(uint, ushort, byte, byte ...) /// 2. Verifies exception is not thrown /// /// MFTestResults testResult = MFTestResults.Pass; Random random = new Random(); int randoInt = random.Next(Int32.MaxValue); uint _uInt = (uint)(randoInt * 2); ushort _uShort1 = (ushort)random.Next(65536); ushort _uShort2 = (ushort)random.Next(65536); Byte[] _bArr = MFUtilities.GetRandomBytes(8); try { Guid _guid = new Guid(_uInt, _uShort1, _uShort1, _bArr[0], _bArr[1], _bArr[2], _bArr[3], _bArr[4], _bArr[5], _bArr[6], _bArr[7]); } catch (Exception ex) { Log.Comment("Caught : " + ex.Message + "when creating Guid(" + _uInt + ", " + _uShort1 + ", " + _uShort1 + ", " + _bArr[0] + ", " + _bArr[1] + ", " + _bArr[2] + ", " + _bArr[3] + ", " + _bArr[4] + ", " + _bArr[5] + ", " + _bArr[6] + ", " + _bArr[7] + ")"); testResult = MFTestResults.Fail; } return testResult; } [TestMethod] public MFTestResults Guid_Empty_Test8() { /// /// 1. Creates an Empty Guid with Guid.Empty /// 2. Extracts all the bytes in the Guid /// 3. Verifies all bytes have zero (0) value /// /// MFTestResults testResult = MFTestResults.Pass; Guid guid = Guid.Empty; Byte[] _bArr = guid.ToByteArray(); for (int i = 0; i < 16; i++) { if (_bArr[i] != 0) { Log.Comment("Expecting '0' got '" + _bArr[i] + "' at index " + i.ToString()); testResult = MFTestResults.Fail; break; } } return testResult; } [TestMethod] public MFTestResults Guid_CompareTo_Test9() { /// /// 1. Creates Guids with different values /// 2. Verifies their equality using CompareTo /// /// MFTestResults testResult = MFTestResults.Pass; Guid guid1 = Guid.Empty; Log.Comment("Verifing any instance of Guid, regardless of its value, is greater than null"); if (guid1.CompareTo(null) <= 0) { Log.Comment("Expected : " + guid1.ToString() + " is greater than null"); testResult = MFTestResults.Fail; } Byte[] _bArr = new Byte[16]; Log.Comment("Creating a Guid with all bytes zero"); Guid guid2 = new Guid(_bArr); if (guid1.CompareTo(guid2) != 0) { Log.Comment("Expected : " + guid1.ToString() + " equals " + guid2.ToString()); testResult = MFTestResults.Fail; } Guid guid3 = new Guid(0x4dff36b5, 0x9dde, 0x4f76, 0x9a, 0x2a, 0x96, 0x43, 0x50, 0x47, 0x06, 0x3d); if (guid3.CompareTo(guid1) <= 0) { Log.Comment("Expected : " + guid3.ToString() + " is greater than " + guid1.ToString()); testResult = MFTestResults.Fail; } Guid guid4 = new Guid(0x4dff36b5, 0x9dde, 0x4f76, 0x9a, 0x2a, 0x96, 0x43, 0x50, 0x47, 0x06, 0x3d); if (guid4.CompareTo(guid3) != 0) { Log.Comment("Expected : " + guid4.ToString() + " is equal to " + guid3.ToString()); testResult = MFTestResults.Fail; } Guid guid5 = new Guid(0x4dff36b5, 0x9dde, 0x4f76, 0x9a, 0x2a, 0x96, 0x43, 0x50, 0x47, 0x06, 0x3e); if (guid5.CompareTo(guid4) <= 0) { Log.Comment("Expected : " + guid5.ToString() + " is greater than " + guid4.ToString()); testResult = MFTestResults.Fail; } if (guid4.CompareTo(guid5) >= 0) { Log.Comment("Expected : " + guid4.ToString() + " is less than " + guid5.ToString()); testResult = MFTestResults.Fail; } return testResult; } [TestMethod] public MFTestResults Guid_ToString_Test10() { /// /// 1. Creates 4 Guids and Converts them ToString /// 2. Verifies the Conversion of Guids to string is correct /// /// MFTestResults testResult = MFTestResults.Pass; String[] strArr1 = new String[] { "00000000-0000-0000-0000-000000000000", "00000000-0000-0000-0000-000000000000", "4dff36b5-9dde-4f76-9a2a-96435047063d", "ffffffff-ffff-ffff-ffff-ffffffffffff"}; Guid guid1 = Guid.Empty; Byte[] _byteArr1 = new Byte[16]; Guid guid2 = new Guid(_byteArr1); Guid guid3 = new Guid(0x4dff36b5, 0x9dde, 0x4f76, 0x9a, 0x2a, 0x96, 0x43, 0x50, 0x47, 0x06, 0x3d); Byte[] _byteArr2 = new Byte[16]; for (int i = 0; i < _byteArr2.Length; i++) { _byteArr2[i] = Byte.MaxValue; } Guid guid4 = new Guid(_byteArr2); String[] strArr2 = new String[] { guid1.ToString(), guid2.ToString(), guid3.ToString(), guid4.ToString() }; for (int i = 0; i < strArr1.Length; i++) { Log.Comment(strArr1[i]); if (String.Compare(strArr1[i], strArr2[i]) != 0) { Log.Comment("Expecting '" + strArr1[i] + "' got '" + strArr2[i] + "'"); testResult = MFTestResults.Fail; break; } } return testResult; } [TestMethod] public MFTestResults Guid_Equals_Test11() { /// /// 1. Creates 3 Arrays of Guids with different constructors same value /// 2. Verifies the Guids are equal /// /// MFTestResults testResult = MFTestResults.Pass; Log.Comment("Creating 3 Guids with Guid.Empty and hex values"); Guid guid11 = Guid.Empty; Guid guid12 = new Guid(0x4dff36b5, 0x9dde, 0x4f76, 0x9a, 0x2a, 0x96, 0x43, 0x50, 0x47, 0x06, 0x3d); Guid guid13 = new Guid(0x7FFFFFFF, 0x7FFF, 0x7FFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF); Guid[] gArr1 = new Guid[] { guid11, guid12, guid13 }; Log.Comment("Creating Guids with 16 bytes constructor"); Byte[] _bArr1 = new Byte[16]; Guid guid21 = new Guid(_bArr1); Byte[] _bArr2 = new Byte[] { 181, 54, 255, 77, 222, 157, 118, 79, 154, 42, 150, 67, 80, 71, 6, 61 }; Guid guid22 = new Guid(_bArr2); Byte[] _bArr3 = new Byte[] { 255, 255, 255, 127, 255, 127, 255, 127, 255, 255, 255, 255, 255, 255, 255, 255 }; Guid guid23 = new Guid(_bArr3); Guid[] gArr2 = new Guid[] { guid21, guid22, guid23 }; Log.Comment("Creating 3 Guids with Guid(int, short, short, byte ....) constructor"); Guid guid31 = new Guid(0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0); Guid guid32 = new Guid(1308571317, 40414, 20342, 154, 42, 150, 67, 80, 71, 6, 61); Guid guid33 = new Guid(int.MaxValue, short.MaxValue, short.MaxValue, byte.MaxValue, byte.MaxValue, byte.MaxValue, byte.MaxValue, byte.MaxValue, byte.MaxValue, byte.MaxValue, byte.MaxValue); Guid[] gArr3 = new Guid[] { guid31, guid32, guid33 }; for (int i = 0; i < 3; i++) { if ((!gArr1[i].Equals(gArr2[i])) || (gArr1[i].GetHashCode() != gArr2[i].GetHashCode())) { Log.Comment(i + " Expecting : " + gArr1[i].ToString() + " equals " + gArr2[i].ToString() + " comparing 1 and 2"); Log.Comment(" Expecting : hashcode " + gArr1[i].GetHashCode().ToString() + " equals " + gArr2[i].GetHashCode().ToString()); testResult = MFTestResults.Fail; } if ((!gArr1[i].Equals(gArr3[i])) || (gArr1[i].GetHashCode() != gArr3[i].GetHashCode())) { Log.Comment(i + " Expecting : " + gArr1[i].ToString() + " equals " + gArr3[i].ToString() + " comparing 1 and 3"); Log.Comment(" Expecting : hashcode " + gArr1[i].GetHashCode().ToString() + " equals " + gArr3[i].GetHashCode().ToString()); testResult = MFTestResults.Fail; } if ((!gArr2[i].Equals(gArr3[i])) || (gArr2[i].GetHashCode() != gArr3[i].GetHashCode())) { Log.Comment(i + " Expecting : " + gArr2[i].ToString() + " equals " + gArr3[i].ToString() + " comparing 2 and 3"); Log.Comment(" Expecting : hashcode " + gArr2[i].GetHashCode().ToString() + " equals " + gArr3[i].GetHashCode().ToString()); testResult = MFTestResults.Fail; } } return testResult; } } } ================================================ FILE: Zelig/Zelig/Test/RunTime/NETMF/mscorlib/systemlib/systemlib1/ParseTests.cs ================================================ //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // Copyright (c) Microsoft Corporation. All rights reserved. //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// using System; using Microsoft.SPOT; using Microsoft.SPOT.Platform.Test; namespace Microsoft.SPOT.Platform.Tests { public class ParseTests : IMFTestInterface { [SetUp] public InitializeResult Initialize() { Log.Comment("Adding set up for the tests."); return InitializeResult.ReadyToGo; } [TearDown] public void CleanUp() { Log.Comment("Cleaning up after the tests."); } public static int[] intArr = null; public String[] GetRandomStringArray(int max, bool signed) { Random random = new Random(); String[] arr1 = new String[] { "0", "-0","+0", "00000 ", " -00000"," +00000 ", " 0 ", " -00000 ", "+123", " +123 ", " +123", "+123 " }; String[] arr2 = new String[10]; intArr = new int[] { 0, 0, 0, 0, 0, 0, 0, 0, 123, 123, 123, 123, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }; for (int i = 0; i < arr2.Length; i++) { if (signed && ((i % 2) == 0)) { intArr[i + 12] = -(random.Next(max)); arr2[i] = (intArr[i + 12].ToString()); } else { intArr[i + 12] = random.Next(max); arr2[i] = intArr[i + 12].ToString(); } } String[] arr = new String[22]; Array.Copy(arr1, arr, arr1.Length); Array.Copy(arr2, 0, arr, arr1.Length, arr2.Length); return arr; } [TestMethod] public MFTestResults ParseSByte_Test_1() { Log.Comment("SByte MinValue = " + SByte.MinValue.ToString()); Log.Comment("SByte MaxValue = " + SByte.MaxValue.ToString()); String[] strArr = GetRandomStringArray(SByte.MaxValue, true); SByte[] _sByte = new SByte[intArr.Length]; for (int i = 0; i < _sByte.Length; i++) { _sByte[i] = (SByte)intArr[i]; } int counter = 0; SByte temp = 0; for (int i = 0; i < strArr.Length; i++) { try { temp = SByte.Parse(strArr[i]); } catch (Exception ex) { Log.Comment(i.ToString() + " Caught : " + ex.Message + " when SByte.Parse('" + strArr[i] + "')"); counter++; } if (temp != _sByte[i]) { Log.Comment(i.ToString() + " Expecting " + _sByte[i] + " but got " + temp); counter++; } } return (counter == 0) ? MFTestResults.Pass : MFTestResults.Fail; } [TestMethod] public MFTestResults ParseByte_Test_2() { Log.Comment("Byte MinValue = " + Byte.MinValue.ToString()); Log.Comment("Byte MaxValue = " + Byte.MaxValue.ToString()); //Log.Comment("This currently fails, see 21634 for details"); String[] strArr = GetRandomStringArray(Byte.MaxValue, false); Byte[] _byte = new Byte[intArr.Length]; for (int i = 0; i < _byte.Length; i++) { _byte[i] = (Byte)intArr[i]; } int counter = 0; Byte temp = 0; for (int i = 0; i < strArr.Length; i++) { try { temp = Byte.Parse(strArr[i]); } catch (Exception ex) { Log.Comment(i.ToString() + " Caught : " + ex.Message + " when Byte.Parse('" + strArr[i] + "')"); counter++; } if (temp != _byte[i]) { Log.Comment(i.ToString() + " Expecting " + _byte[i] + " but got " + temp); counter++; } } return (counter == 0) ? MFTestResults.Pass : MFTestResults.Fail; } [TestMethod] public MFTestResults ParseInt16_Test_3() { Log.Comment("Int16 MinValue = " + Int16.MinValue.ToString()); Log.Comment("Int16 MaxValue = " + Int16.MaxValue.ToString()); String[] strArr = GetRandomStringArray(Int16.MaxValue, true); Int16[] _int16 = new Int16[intArr.Length]; for (int i = 0; i < _int16.Length; i++) { _int16[i] = (Int16)intArr[i]; } int counter = 0; Int16 temp = 0; for (int i = 0; i < strArr.Length; i++) { try { temp = Int16.Parse(strArr[i]); } catch (Exception ex) { Log.Comment(i.ToString() + " Caught : " + ex.Message + " when Int16.Parse('" + strArr[i] + "')"); counter++; } if (temp != _int16[i]) { Log.Comment(i.ToString() + " Expecting " + _int16[i] + " but got " + temp); counter++; } } return (counter == 0) ? MFTestResults.Pass : MFTestResults.Fail; } [TestMethod] public MFTestResults ParseUInt16_Test_4() { Log.Comment("UInt16 MinValue = " + UInt16.MinValue.ToString()); Log.Comment("UInt16 MaxValue = " + UInt16.MaxValue.ToString()); //Log.Comment("This currently fails, see 21634 for details"); String[] strArr = GetRandomStringArray(UInt16.MaxValue, false); UInt16[] _uInt16 = new UInt16[intArr.Length]; for (int i = 0; i < _uInt16.Length; i++) { _uInt16[i] = (UInt16)intArr[i]; } int counter = 0; UInt16 temp = 0; for (int i = 0; i < strArr.Length; i++) { try { temp = UInt16.Parse(strArr[i]); } catch (Exception ex) { Log.Comment(i.ToString() + " Caught : " + ex.Message + " when UInt16.Parse('" + strArr[i] + "')"); counter++; } if (temp != _uInt16[i]) { Log.Comment(i.ToString() + " Expecting " + _uInt16[i] + " but got " + temp); counter++; } } return (counter == 0) ? MFTestResults.Pass : MFTestResults.Fail; } [TestMethod] public MFTestResults ParseInt32_Test_5() { Log.Comment("Int32 MinValue = " + Int32.MinValue.ToString()); Log.Comment("Int32 MaxValue = " + Int32.MaxValue.ToString()); //Log.Comment("This currently Fails, See 21626 for details"); String[] strArr = GetRandomStringArray(Int32.MaxValue, true); Int32[] _int32 = new Int32[intArr.Length]; for (int i = 0; i < _int32.Length; i++) { _int32[i] = (Int32)intArr[i]; } int counter = 0; Int32 temp = 0; for (int i = 0; i < strArr.Length; i++) { try { temp = Int32.Parse(strArr[i]); } catch (Exception ex) { Log.Comment(i.ToString() + " Caught : " + ex.Message + " when Int32.Parse('" + strArr[i] + "')"); counter++; } if (temp != _int32[i]) { Log.Comment(i.ToString() + " Expecting " + _int32[i] + " but got " + temp); counter++; } } return (counter == 0) ? MFTestResults.Pass : MFTestResults.Fail; } // ========================================================================== [TestMethod] public MFTestResults ParseUInt32_Test_6() { Log.Comment("UInt32 MinValue = " + UInt32.MinValue.ToString()); Log.Comment("UInt32 MaxValue = " + UInt32.MaxValue.ToString()); //Log.Comment("This currently fails, see 21634 for details"); Random random = new Random(); String[] strArr = new String[] { "0", "-0","+0", "00000 ", " -00000"," +00000 ", " 0 ", " -00000 ", "+123", " +123 ", " +123", "+123 ", "","","","","","","","","",""}; UInt32[] _uInt32 = new UInt32[] { 0, 0, 0, 0, 0, 0, 0, 0, 123, 123, 123, 123, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }; for (int i = 12; i < _uInt32.Length; i++) { int power = random.Next(33); _uInt32[i] = (UInt32)(System.Math.Pow(2, (double)power) - 1); strArr[i] = _uInt32[i].ToString(); } int counter = 0; UInt32 temp = 0; for (int i = 0; i < strArr.Length; i++) { try { temp = UInt32.Parse(strArr[i]); } catch (Exception ex) { Log.Comment(i.ToString() + " Caught : " + ex.Message + " when UInt32.Parse('" + strArr[i] + "')"); counter++; } if (temp != _uInt32[i]) { Log.Comment(i.ToString() + " Expecting " + _uInt32[i] + " but got " + temp); counter++; } } return (counter == 0) ? MFTestResults.Pass : MFTestResults.Fail; } [TestMethod] public MFTestResults ParseInt64_Test_7() { Log.Comment("Int64 MinValue = " + Int64.MinValue.ToString()); Log.Comment("Int64 MaxValue = " + Int64.MaxValue.ToString()); Random random = new Random(); String[] strArr = new String[] { "0", "-0","+0", "00000 ", " -00000"," +00000 ", " 0 ", " -00000 ", "+123", " +123 ", " +123", "+123 ", "","","","","","","","","",""}; Int64[] _int64 = new Int64[] { 0, 0, 0, 0, 0, 0, 0, 0, 123, 123, 123, 123, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }; for (int i = 12; i < _int64.Length; i++) { int power = random.Next(64); if (i % 2 == 0) { _int64[i] = (Int64)(-System.Math.Pow(2, (double)power) - 1); } else { _int64[i] = (Int64)(System.Math.Pow(2, (double)power) - 1); } strArr[i] = _int64[i].ToString(); } int counter = 0; Int64 temp = 0; for (int i = 0; i < strArr.Length; i++) { try { temp = Int64.Parse(strArr[i]); } catch (Exception ex) { Log.Comment(i.ToString() + " Caught : " + ex.Message + " when Int64.Parse('" + strArr[i] + "')"); counter++; } if (temp != _int64[i]) { Log.Comment(i.ToString() + " Expecting " + _int64[i] + " but got " + temp); counter++; } } //Int32: -2147483648 --> 2147483647 counter += CheckValues(Int32.MinValue); counter += CheckValues(Int32.MaxValue); //UInt32: 0 ---> 4294967295 counter += CheckValues(UInt32.MinValue); counter += CheckValues(UInt32.MaxValue); //Int64: -9223372036854775808 --> 9223372036854775807 counter += CheckValues(Int64.MinValue); counter += CheckValues(Int64.MaxValue); //Uint64: 0 --> 18446744073709551615 counter += CheckValues((Int64)UInt64.MinValue); return (counter == 0) ? MFTestResults.Pass : MFTestResults.Fail; } private int CheckValues(Int64 start) { Int64 newVal = 0; string temp; int failCount = 0; for (Int64 i = start - 10; i < start + 10; i++) { temp = i.ToString(); newVal = Int64.Parse(temp); if (i != newVal) { Log.Comment("Expecting: " + i + " but got: " + newVal); failCount++; } } return failCount; } [TestMethod] public MFTestResults ParseUInt64_Test_8() { Log.Comment("UInt64 MinValue = " + UInt64.MinValue.ToString()); Log.Comment("UInt64 MaxValue = " + UInt64.MaxValue.ToString()); //Log.Comment("This currently fails, see 21634 for details"); Random random = new Random(); String[] strArr = new String[] { "0", "-0","+0", "00000 ", " -00000"," +00000 ", " 0 ", " -00000 ", "+123", " +123 ", " +123", "+123 ", "","","","","","","","","",""}; UInt64[] _uInt64 = new UInt64[] { 0, 0, 0, 0, 0, 0, 0, 0, 123, 123, 123, 123, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }; for (int i = 12; i < _uInt64.Length; i++) { int power = random.Next(65); _uInt64[i] = (UInt64)(System.Math.Pow(2, (double)power) - 1); strArr[i] = _uInt64[i].ToString(); } int counter = 0; UInt64 temp = 0; for (int i = 0; i < strArr.Length; i++) { try { temp = UInt64.Parse(strArr[i]); } catch (Exception ex) { Log.Comment(i.ToString() + " Caught : " + ex.Message + " when UInt64.Parse('" + strArr[i] + "')"); counter++; } if (temp != _uInt64[i]) { Log.Comment(i.ToString() + " Expecting " + _uInt64[i] + " but got " + temp); counter++; } } //Int32: -2147483648 --> 2147483647 counter += CheckUValues(Int32.MaxValue); //UInt32: 0 ---> 4294967295 counter += CheckUValues(UInt32.MinValue); counter += CheckUValues(UInt32.MaxValue); //Int64: -9223372036854775808 --> 9223372036854775807 counter += CheckUValues(UInt64.MaxValue); //Uint64: 0 --> 18446744073709551615 counter += CheckUValues(UInt64.MinValue); counter += CheckUValues(UInt64.MaxValue); return (counter == 0) ? MFTestResults.Pass : MFTestResults.Fail; } [TestMethod] public MFTestResults ParseDouble_Test_x() { Log.Comment("double MinValue = " + double.MinValue.ToString()); Log.Comment("double MaxValue = " + double.MaxValue.ToString()); //Log.Comment("This currently fails, see 21634 for details"); Random random = new Random(); String[] strArr = new String[] { "0", "-0","+0", "00000 ", " -00000"," +00000 ", " 0 ", " -00000 ", "+123", " +123 ", " +123", "+123 "}; double[] _double = new double[] { 0, 0, 0, 0, 0, 0, 0, 0, 123, 123, 123, 123 }; int counter = 0; double temp = 0; for (int i = 0; i < strArr.Length; i++) { try { temp = double.Parse(strArr[i]); } catch (Exception ex) { Log.Comment(i.ToString() + " Caught : " + ex.Message + " when double.Parse('" + strArr[i] + "')"); counter++; } if (temp != _double[i]) { Log.Comment(i.ToString() + " Expecting " + _double[i] + " but got " + temp); counter++; } } double d = double.Parse("-0.1"); if (d != -0.1) counter++; d = double.Parse("0.1"); if (d != 0.1) counter++; d = double.Parse(" -1.1"); if (d != -1.1) counter++; d = double.Parse(" -0.0001"); if (d != -0.0001) counter++; d = double.Parse(" -10.0001"); if (d != -10.0001) counter++; d = double.Parse("-0.01e-10"); if (d != -0.01e-10) counter++; d = double.Parse(" "); if (d != 0.0) counter++; string t = double.MinValue.ToString(); if (double.MinValue != double.Parse(t)) counter++; t = double.MaxValue.ToString(); if (double.MaxValue != double.Parse(t)) counter++; t = float.MinValue.ToString(); if (float.MinValue != (float)double.Parse(t)) counter++; t = float.MaxValue.ToString(); if (float.MaxValue != (float)double.Parse(t)) counter++; return (counter == 0) ? MFTestResults.Pass : MFTestResults.Fail; } private int CheckUValues(UInt64 start) { UInt64 newVal = 0; string temp; int failCount = 0; for (UInt64 i = start - 10; i < start + 10; i++) { temp = i.ToString(); newVal = UInt64.Parse(temp); if (i != newVal) { Log.Comment("Expecting: " + i + " but got: " + newVal); failCount++; } } return failCount; } //========================================================================================= // BoundaryTests [TestMethod] public MFTestResults SByte_Boundary_Test_9() { String[] strArr = new String[] { SByte.MaxValue.ToString(), "127", SByte.MinValue.ToString(), "-128" }; SByte[] _SByte = new SByte[] { 127, 127, -128, -128 }; int counter = 0; SByte temp = 0; for (int i = 0; i < strArr.Length; i++) { try { temp = SByte.Parse(strArr[i]); } catch (Exception ex) { Log.Comment(i.ToString() + " Caught : " + ex.Message + " when SByte.Parse('" + strArr[i] + "')"); counter++; } if (temp != _SByte[i]) { Log.Comment(i.ToString() + " Expecting " + _SByte[i] + " but got " + temp); counter++; } } return (counter == 0) ? MFTestResults.Pass : MFTestResults.Fail; } [TestMethod] public MFTestResults Byte_Boundary_Test_10() { String[] strArr = new String[] { Byte.MaxValue.ToString(), "255", Byte.MinValue.ToString(), "0" }; Byte[] _byte = new Byte[] { 255, 255, 0, 0 }; int counter = 0; Byte temp = 0; for (int i = 0; i < strArr.Length; i++) { try { temp = Byte.Parse(strArr[i]); } catch (Exception ex) { Log.Comment(i.ToString() + " Caught : " + ex.Message + " when Byte.Parse('" + strArr[i] + "')"); counter++; } if (temp != _byte[i]) { Log.Comment(i.ToString() + " Expecting " + _byte[i] + " but got " + temp); counter++; } } return (counter == 0) ? MFTestResults.Pass : MFTestResults.Fail; } [TestMethod] public MFTestResults Int16_Boundary_Test_11() { String[] strArr = new String[] { Int16.MaxValue.ToString(), "32767", Int16.MinValue.ToString(), "-32768" }; Int16[] _int16 = new Int16[] { 32767, 32767, -32768, -32768 }; int counter = 0; Int16 temp = 0; for (int i = 0; i < strArr.Length; i++) { try { temp = Int16.Parse(strArr[i]); } catch (Exception ex) { Log.Comment(i.ToString() + " Caught : " + ex.Message + " when Int16.Parse('" + strArr[i] + "')"); counter++; } if (temp != _int16[i]) { Log.Comment(i.ToString() + " Expecting " + _int16[i] + " but got " + temp); counter++; } } return (counter == 0) ? MFTestResults.Pass : MFTestResults.Fail; } [TestMethod] public MFTestResults UInt16_Boundary_Test_12() { String[] strArr = new String[] { UInt16.MaxValue.ToString(), "65535", UInt16.MinValue.ToString(), "0" }; UInt16[] _uInt16 = new UInt16[] { 65535, 65535, 0, 0 }; int counter = 0; UInt16 temp = 0; for (int i = 0; i < strArr.Length; i++) { try { temp = UInt16.Parse(strArr[i]); } catch (Exception ex) { Log.Comment(i.ToString() + " Caught : " + ex.Message + " when UInt16.Parse('" + strArr[i] + "')"); counter++; } if (temp != _uInt16[i]) { Log.Comment(i.ToString() + " Expecting " + _uInt16[i] + " but got " + temp); counter++; } } return (counter == 0) ? MFTestResults.Pass : MFTestResults.Fail; } [TestMethod] public MFTestResults Int32_Boundary_Test_13() { String[] strArr = new String[] { Int32.MaxValue.ToString(), "2147483647", Int32.MinValue.ToString(), "-2147483648" }; Int32[] _int32 = new Int32[] { 2147483647, 2147483647, -2147483648, -2147483648 }; int counter = 0; Int32 temp = 0; for (int i = 0; i < strArr.Length; i++) { try { temp = Int32.Parse(strArr[i]); } catch (Exception ex) { Log.Comment(i.ToString() + " Caught : " + ex.Message + " when Int32.Parse('" + strArr[i] + "')"); counter++; } if (temp != _int32[i]) { Log.Comment(i.ToString() + " Expecting " + _int32[i] + " but got " + temp); counter++; } } return (counter == 0) ? MFTestResults.Pass : MFTestResults.Fail; } [TestMethod] public MFTestResults UInt32_Boundary_Test_14() { String[] strArr = new String[] { UInt32.MaxValue.ToString(), "4294967295", UInt32.MinValue.ToString(), "0" }; UInt32[] _uInt32 = new UInt32[] { 4294967295, 4294967295, 0, 0 }; int counter = 0; UInt32 temp = 0; for (int i = 0; i < strArr.Length; i++) { try { temp = UInt32.Parse(strArr[i]); } catch (Exception ex) { Log.Comment(i.ToString() + " Caught : " + ex.Message + " when UInt32.Parse('" + strArr[i] + "')"); counter++; } if (temp != _uInt32[i]) { Log.Comment(i.ToString() + " Expecting " + _uInt32[i] + " but got " + temp); counter++; } } return (counter == 0) ? MFTestResults.Pass : MFTestResults.Fail; } [TestMethod] public MFTestResults Int64_Boundary_Test_15() { String[] strArr = new String[] { Int64.MaxValue.ToString(), "9223372036854775807", Int64.MinValue.ToString(), "-9223372036854775808" }; Int64[] _int64 = new Int64[] { 9223372036854775807, 9223372036854775807, -9223372036854775808, -9223372036854775808 }; int counter = 0; Int64 temp = 0; for (int i = 0; i < strArr.Length; i++) { try { temp = Int64.Parse(strArr[i]); } catch (Exception ex) { Log.Comment(i.ToString() + " Caught : " + ex.Message + " when Int64.Parse('" + strArr[i] + "')"); counter++; } if (temp != _int64[i]) { Log.Comment(i.ToString() + " Expecting " + _int64[i] + " but got " + temp); counter++; } } return (counter == 0) ? MFTestResults.Pass : MFTestResults.Fail; } [TestMethod] public MFTestResults UInt64_Boundary_Test_16() { String[] strArr = new String[] { UInt64.MaxValue.ToString(), "18446744073709551615", UInt64.MinValue.ToString(), "0" }; UInt64[] _uInt64 = new UInt64[] { 18446744073709551615, 18446744073709551615, 0, 0 }; int counter = 0; UInt64 temp = 0; for (int i = 0; i < strArr.Length; i++) { try { temp = UInt64.Parse(strArr[i]); } catch (Exception ex) { Log.Comment(i.ToString() + " Caught : " + ex.Message + " when UInt64.Parse('" + strArr[i] + "')"); counter++; } if (temp != _uInt64[i]) { Log.Comment(i.ToString() + " Expecting " + _uInt64[i] + " but got " + temp); counter++; } } return (counter == 0) ? MFTestResults.Pass : MFTestResults.Fail; } //============================================================================ // ArgumentNullException tests public static string str = null; [TestMethod] public MFTestResults SByte_ArgumentNullException_Test_17() { MFTestResults testResult = MFTestResults.Fail; try { SByte.Parse(str); } catch (ArgumentNullException ex) { Log.Comment("Caught Exception named : " + ex.Message + " upon SByte.Parse null string"); testResult = MFTestResults.Pass; } return testResult; } [TestMethod] public MFTestResults Byte_ArgumentNullException_Test_18() { MFTestResults testResult = MFTestResults.Fail; try { Byte.Parse(str); } catch (ArgumentNullException ex) { Log.Comment("Caught Exception named : " + ex.Message + " upon Byte.Parse null string"); testResult = MFTestResults.Pass; } return testResult; } [TestMethod] public MFTestResults Int16_ArgumentNullException_Test_19() { MFTestResults testResult = MFTestResults.Fail; try { Int16.Parse(str); } catch (ArgumentNullException ex) { Log.Comment("Caught Exception named : " + ex.Message + " upon Int16.Parse null string"); testResult = MFTestResults.Pass; } return testResult; } [TestMethod] public MFTestResults UInt16_ArgumentNullException_Test_20() { MFTestResults testResult = MFTestResults.Fail; try { UInt16.Parse(str); } catch (ArgumentNullException ex) { Log.Comment("Caught Exception named : " + ex.Message + " upon UInt16.Parse null string"); testResult = MFTestResults.Pass; } return testResult; } [TestMethod] public MFTestResults Int32_ArgumentNullException_Test_21() { MFTestResults testResult = MFTestResults.Fail; try { Int32.Parse(str); } catch (ArgumentNullException ex) { Log.Comment("Caught Exception named : " + ex.Message + " upon Int32.Parse null string"); testResult = MFTestResults.Pass; } return testResult; } [TestMethod] public MFTestResults UInt32_ArgumentNullException_Test_22() { MFTestResults testResult = MFTestResults.Fail; try { UInt32.Parse(str); } catch (ArgumentNullException ex) { Log.Comment("Caught Exception named : " + ex.Message + " upon UInt32.Parse null string"); testResult = MFTestResults.Pass; } return testResult; } [TestMethod] public MFTestResults Int64_ArgumentNullException_Test_23() { MFTestResults testResult = MFTestResults.Fail; try { Int64.Parse(str); } catch (ArgumentNullException ex) { Log.Comment("Caught Exception named : " + ex.Message + " upon Int64.Parse null string"); testResult = MFTestResults.Pass; } return testResult; } [TestMethod] public MFTestResults UInt64_ArgumentNullException_Test_24() { MFTestResults testResult = MFTestResults.Fail; try { UInt64.Parse(str); } catch (ArgumentNullException ex) { Log.Comment("Caught Exception named : " + ex.Message + " upon UInt64.Parse null string"); testResult = MFTestResults.Pass; } return testResult; } //============================================================================ // FormatException tests [TestMethod] public MFTestResults ParseSByte_FormatException_Test_25() { String[] strArr = new String[] { "", "1,234", "123e5", "a", "3.14159265358979" }; int counter = 0; for (int i = 0; i < strArr.Length; i++) { try { SByte.Parse(strArr[i]); } //Supposed to throw FormatException catch (Exception ex) { Log.Comment("1st " + i.ToString() + " Caught : " + ex.Message + " when SByte.Parse('" + strArr[i] + "')"); counter++; } } for (int i = 0; i < 5; i++) { String rdmString = MFUtilities.GetRandomString(); try { SByte.Parse(rdmString); } //Supposed to throw FormatException catch (Exception ex) { Log.Comment("2nd " + i.ToString() + " Caught : " + ex.Message + " when SByte.Parse('" + rdmString + "')"); counter++; } } return (counter == (strArr.Length + 5)) ? MFTestResults.Pass : MFTestResults.Fail; } [TestMethod] public MFTestResults ParseByte_FormatException_Test_26() { String[] strArr = new String[] { "", "1,234", "123e5", "a", "3.14159265358979" }; int counter = 0; for (int i = 0; i < strArr.Length; i++) { try { Byte.Parse(strArr[i]); } //Supposed to throw FormatException catch (Exception ex) { Log.Comment("1st " + i.ToString() + " Caught : " + ex.Message + " when Byte.Parse('" + strArr[i] + "')"); counter++; } } for (int i = 0; i < 5; i++) { String rdmString = MFUtilities.GetRandomString(); try { Byte.Parse(rdmString); } //Supposed to throw FormatException catch (Exception ex) { Log.Comment("2nd " + i.ToString() + " Caught : " + ex.Message + " when Byte.Parse('" + rdmString + "')"); counter++; } } return (counter == (strArr.Length + 5)) ? MFTestResults.Pass : MFTestResults.Fail; } [TestMethod] public MFTestResults ParseInt16_FormatException_Test_27() { String[] strArr = new String[] { "", "1,234", "123e5", "a", "3.14159265358979" }; int counter = 0; for (int i = 0; i < strArr.Length; i++) { try { Int16.Parse(strArr[i]); } //Supposed to throw FormatException catch (Exception ex) { Log.Comment("1st " + i.ToString() + " Caught : " + ex.Message + " when Int16.Parse('" + strArr[i] + "')"); counter++; } } for (int i = 0; i < 5; i++) { String rdmString = MFUtilities.GetRandomString(); try { Int16.Parse(rdmString); } //Supposed to throw FormatException catch (Exception ex) { Log.Comment("2nd " + i.ToString() + " Caught : " + ex.Message + " when Int16.Parse('" + rdmString + "')"); counter++; } } return (counter == (strArr.Length + 5)) ? MFTestResults.Pass : MFTestResults.Fail; } [TestMethod] public MFTestResults ParseUInt16_FormatException_Test_28() { String[] strArr = new String[] { "", "1,234", "123e5", "a", "3.14159265358979" }; int counter = 0; for (int i = 0; i < strArr.Length; i++) { try { UInt16.Parse(strArr[i]); } //Supposed to throw FormatException catch (Exception ex) { Log.Comment("1st " + i.ToString() + " Caught : " + ex.Message + " when UInt16.Parse('" + strArr[i] + "')"); counter++; } } for (int i = 0; i < 5; i++) { String rdmString = MFUtilities.GetRandomString(); try { UInt16.Parse(rdmString); } //Supposed to throw FormatException catch (Exception ex) { Log.Comment("2nd " + i.ToString() + " Caught : " + ex.Message + " when UInt16.Parse('" + rdmString + "')"); counter++; } } return (counter == (strArr.Length + 5)) ? MFTestResults.Pass : MFTestResults.Fail; } [TestMethod] public MFTestResults ParseInt32_FormatException_Test_29() { String[] strArr = new String[] { "", "1,234", "123e5", "a", "3.14159265358979" }; int counter = 0; for (int i = 0; i < strArr.Length; i++) { try { Int32.Parse(strArr[i]); } //Supposed to throw FormatException catch (Exception ex) { Log.Comment("1st " + i.ToString() + " Caught : " + ex.Message + " when Int32.Parse('" + strArr[i] + "')"); counter++; } } for (int i = 0; i < 5; i++) { String rdmString = MFUtilities.GetRandomString(); try { Int32.Parse(rdmString); } //Supposed to throw FormatException catch (Exception ex) { Log.Comment("2nd " + i.ToString() + " Caught : " + ex.Message + " when Int32.Parse('" + rdmString + "')"); counter++; } } return (counter == (strArr.Length + 5)) ? MFTestResults.Pass : MFTestResults.Fail; } [TestMethod] public MFTestResults ParseUInt32_FormatException_Test_30() { String[] strArr = new String[] { "", "1,234", "123e5", "a", "3.14159265358979" }; int counter = 0; for (int i = 0; i < strArr.Length; i++) { try { UInt32.Parse(strArr[i]); } //Supposed to throw FormatException catch (Exception ex) { Log.Comment("1st " + i.ToString() + " Caught : " + ex.Message + " when UInt32.Parse('" + strArr[i] + "')"); counter++; } } for (int i = 0; i < 5; i++) { String rdmString = MFUtilities.GetRandomString(); try { UInt32.Parse(rdmString); } //Supposed to throw FormatException catch (Exception ex) { Log.Comment("2nd " + i.ToString() + " Caught : " + ex.Message + " when UInt32.Parse('" + rdmString + "')"); counter++; } } return (counter == (strArr.Length + 5)) ? MFTestResults.Pass : MFTestResults.Fail; } [TestMethod] public MFTestResults ParseInt64_FormatException_Test_31() { String[] strArr = new String[] { "", "1,234", "123e5", "a", "3.14159265358979" }; int counter = 0; for (int i = 0; i < strArr.Length; i++) { try { Int64.Parse(strArr[i]); } //Supposed to throw FormatException catch (Exception ex) { Log.Comment("1st " + i.ToString() + " Caught : " + ex.Message + " when Int64.Parse('" + strArr[i] + "')"); counter++; } } for (int i = 0; i < 5; i++) { String rdmString = MFUtilities.GetRandomString(); try { Int64.Parse(rdmString); } //Supposed to throw FormatException catch (Exception ex) { Log.Comment("2nd " + i.ToString() + " Caught : " + ex.Message + " when Int64.Parse('" + rdmString + "')"); counter++; } } return (counter == (strArr.Length + 5)) ? MFTestResults.Pass : MFTestResults.Fail; } [TestMethod] public MFTestResults ParseUInt64_FormatException_Test_32() { String[] strArr = new String[] { "", "1,234", "123e5", "a", "3.14159265358979" }; int counter = 0; for (int i = 0; i < strArr.Length; i++) { try { UInt64.Parse(strArr[i]); } //Supposed to throw FormatException catch (Exception ex) { Log.Comment("1st " + i.ToString() + " Caught : " + ex.Message + " when UInt64.Parse('" + strArr[i] + "')"); counter++; } } for (int i = 0; i < 5; i++) { String rdmString = MFUtilities.GetRandomString(); try { UInt64.Parse(rdmString); } //Supposed to throw FormatException catch (Exception ex) { Log.Comment("2nd " + i.ToString() + " Caught : " + ex.Message + " when UInt64.Parse('" + rdmString + "')"); counter++; } } return (counter == (strArr.Length + 5)) ? MFTestResults.Pass : MFTestResults.Fail; } //============================================================================ // OverflowException tests [TestMethod] public MFTestResults ParseSByte_OverflowException_Test_33() { String[] strArr = new String[] { ((Int64)SByte.MinValue - 1).ToString(), ((Int64)SByte.MinValue - 100).ToString(), ((Int64)SByte.MaxValue + 1).ToString(), ((Int64)SByte.MaxValue + 100).ToString() }; int counter = 0; for (int i = 0; i < strArr.Length; i++) { try { SByte.Parse(strArr[i]); } //Supposed to throw OverflowException catch (Exception ex) { Log.Comment(i.ToString() + " Caught : " + ex.Message + "when SByte.Parse('" + strArr[i] + "')"); counter++; } } return (counter == strArr.Length) ? MFTestResults.Pass : MFTestResults.Fail; } [TestMethod] public MFTestResults ParseByte_OverflowException_Test_34() { String[] strArr = new String[] { ((Int64)Byte.MinValue - 1).ToString(), ((Int64)Byte.MinValue - 100).ToString(), ((Int64)Byte.MaxValue + 1).ToString(), ((Int64)Byte.MaxValue + 100).ToString() }; int counter = 0; for (int i = 0; i < strArr.Length; i++) { try { Byte.Parse(strArr[i]); } //Supposed to throw OverflowException catch (Exception ex) { Log.Comment(i.ToString() + " Caught : " + ex.Message + "when Byte.Parse('" + strArr[i] + "')"); counter++; } } return (counter == strArr.Length) ? MFTestResults.Pass : MFTestResults.Fail; } [TestMethod] public MFTestResults ParseInt16_OverflowException_Test_35() { String[] strArr = new String[] { ((Int64)Int16.MinValue - 1).ToString(), ((Int64)Int16.MinValue - 100).ToString(), ((Int64)Int16.MaxValue + 1).ToString(), ((Int64)Int16.MaxValue + 100).ToString() }; int counter = 0; for (int i = 0; i < strArr.Length; i++) { try { Int16.Parse(strArr[i]); } //Supposed to throw OverflowException catch (Exception ex) { Log.Comment(i.ToString() + " Caught : " + ex.Message + "when Int16.Parse('" + strArr[i] + "')"); counter++; } } return (counter == strArr.Length) ? MFTestResults.Pass : MFTestResults.Fail; } [TestMethod] public MFTestResults ParseUInt16_OverflowException_Test_36() { String[] strArr = new String[] { ((Int64)UInt16.MinValue - 1).ToString(), ((Int64)UInt16.MinValue - 100).ToString(), ((Int64)UInt16.MaxValue + 1).ToString(), ((Int64)UInt16.MaxValue + 100).ToString() }; int counter = 0; for (int i = 0; i < strArr.Length; i++) { try { UInt16.Parse(strArr[i]); } //Supposed to throw OverflowException catch (Exception ex) { Log.Comment(i.ToString() + " Caught : " + ex.Message + "when UInt16.Parse('" + strArr[i] + "')"); counter++; } } return (counter == strArr.Length) ? MFTestResults.Pass : MFTestResults.Fail; } [TestMethod] public MFTestResults ParseInt32_OverflowException_Test_37() { String[] strArr = new String[] { ((Int64)Int32.MinValue - 1).ToString(), ((Int64)Int32.MinValue - 100).ToString(), ((Int64)Int32.MaxValue + 1).ToString(), ((Int64)Int32.MaxValue + 100).ToString() }; int counter = 0; for (int i = 0; i < strArr.Length; i++) { try { Int32.Parse(strArr[i]); } //Supposed to throw OverflowException catch (Exception ex) { Log.Comment(i.ToString() + " Caught : " + ex.Message + "when Int32.Parse('" + strArr[i] + "')"); counter++; } } return (counter == strArr.Length) ? MFTestResults.Pass : MFTestResults.Fail; } [TestMethod] public MFTestResults ParseUInt32_OverflowException_Test_38() { String[] strArr = new String[] { ((Int64)UInt32.MinValue - 1).ToString(), ((Int64)UInt32.MinValue - 100).ToString(), ((Int64)UInt32.MaxValue + 1).ToString(), ((Int64)UInt32.MaxValue + 100).ToString() }; int counter = 0; for (int i = 0; i < strArr.Length; i++) { try { UInt32.Parse(strArr[i]); } //Supposed to throw OverflowException catch (Exception ex) { Log.Comment(i.ToString() + " Caught : " + ex.Message + "when UInt32.Parse('" + strArr[i] + "')"); counter++; } } return (counter == strArr.Length) ? MFTestResults.Pass : MFTestResults.Fail; } [TestMethod] public MFTestResults ParseInt64_OverflowException_Test_39() { Log.Comment("This currently fails, see 21641 for details"); string[] strArr = new string[] { "-9223372036854775809", "-9223372036854775900", "9223372036854775808", "9223372036854775900" }; int counter = 0; for (int i = 0; i < strArr.Length; i++) { try { Int64.Parse(strArr[i]); } //Supposed to throw OverflowException catch (Exception ex) { Log.Comment(i.ToString() + " Caught : " + ex.Message + "when Int64.Parse('" + strArr[i] + "')"); counter++; } } return (counter == strArr.Length) ? MFTestResults.Pass : MFTestResults.Fail; } [TestMethod] public MFTestResults ParseUInt64_OverflowException_Test_40() { string[] strArr = new string[] { "-1", "-100", "18446744073709551616", "18446744073709551700" }; int counter = 0; for (int i = 0; i < strArr.Length; i++) { try { UInt64.Parse(strArr[i]); } //Supposed to throw OverflowException catch (Exception ex) { Log.Comment(i.ToString() + " Caught : " + ex.Message + "when UInt64.Parse('" + strArr[i] + "')"); counter++; } } return (counter == strArr.Length) ? MFTestResults.Pass : MFTestResults.Pass; } [TestMethod] public MFTestResults Cast_Double_to_int64_Test_40() { MFTestResults retVal = MFTestResults.Pass; double dbVal = new Random().Next(); // Convert to int and uint should keep the value long l_val = (long)dbVal; if (l_val != dbVal) { Log.Comment( "Convert from double " + dbVal + " to long produced different value " + l_val ); retVal = MFTestResults.Fail; } ulong ul_val = (ulong)dbVal; if (ul_val != dbVal) { Log.Comment("Convert from double " + dbVal + " to ulong produced different value " + ul_val); retVal = MFTestResults.Fail; } // Change sign to negative dbVal = -dbVal; l_val = (long)dbVal; if (l_val != dbVal) { Log.Comment( "Convert from double " + dbVal + " to long produced different value " + l_val ); retVal = MFTestResults.Fail; } ul_val = (ulong)dbVal; long ul_val_cast = (long)ul_val; if (ul_val_cast != dbVal) { Log.Comment("Convert from double " + dbVal + " to ulong produced different value " + ul_val_cast); retVal = MFTestResults.Fail; } return retVal; } public enum MyEnum : short { Value = 25 } public enum MyEnum1 { Value = 24 } public enum MyEnum2 : short { Value = 23 } class CastTestClass { } [TestMethod] public MFTestResults box_unbox_Test_1() { MFTestResults retVal = MFTestResults.Pass; // Creates objects for testing of different casts. object o_enum = MyEnum.Value; object o_enum1 = MyEnum1.Value; object o_long = 24L; object o_class = new CastTestClass(); object o_guid = Guid.NewGuid(); // Try casts that shoud succeed. Any exception here means failure. try { // First we try casts that should succeed. // Casts between enums with the same basic type MyEnum2 e2 = (MyEnum2)o_enum; // line 2 // Cast from enum to primitive type that enum is based on short sv = (short)o_enum; if (sv != (short)MyEnum.Value) { Log.Comment("Changed value during box/unbox from " + MyEnum.Value + " to " + sv); retVal = MFTestResults.Fail; } // Cast from enum to primitive type that enum is based on int iv = (int)o_enum1; if (iv != (short)MyEnum1.Value) { Log.Comment("Changed value during box/unbox from " + MyEnum1.Value + " to " + iv); retVal = MFTestResults.Fail; } int i_long = (int)(long)o_long; CastTestClass cls = (CastTestClass)o_class; Guid guid = (Guid)o_guid; } catch (Exception e) { Log.Comment("Exception thrown during unbox test" + e.Message); retVal = MFTestResults.Fail; } // Now casts that should throw exception. Any cast that does not throw - means error. try { MyEnum1 e1 = (MyEnum1)o_enum; Log.Comment("Error, cast succeded, but should have thrown exception"); retVal = MFTestResults.Fail; } catch (Exception ) { } // Now casts that should throw exception. Any cast that does not throw - means error. try { int i = (int)o_long; Log.Comment("Error, cast object with long to int succeded, but should have thrown exception"); retVal = MFTestResults.Fail; } catch (Exception ) { } // Now casts that should throw exception. Any cast that does not throw - means error. try { int i = (int)o_class; Log.Comment("Error, cast object class to int succeded, but should have thrown exception"); retVal = MFTestResults.Fail; } catch (Exception ) { } // Now casts that should throw exception. Any cast that does not throw - means error. try { int i = (int)o_enum; Log.Comment("Error, cast object class to int succeded, but should have thrown exception"); retVal = MFTestResults.Fail; } catch (Exception ) { } // Now casts that should throw exception. Any cast that does not throw - means error. try { int i = (int)o_guid; Log.Comment("Error, cast stuct Guid class to int succeded, but should have thrown exception"); retVal = MFTestResults.Fail; } catch (Exception) { } return retVal; } } } ================================================ FILE: Zelig/Zelig/Test/RunTime/NETMF/mscorlib/systemlib/systemlib1/SystemTimeSpanTests.cs ================================================ //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // Copyright (c) Microsoft Corporation. All rights reserved. //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// using System; using System.Reflection; using Microsoft.SPOT.Platform.Test; namespace Microsoft.SPOT.Platform.Tests { public class SystemTimeSpanTests : IMFTestInterface { [SetUp] public InitializeResult Initialize() { return InitializeResult.ReadyToGo; } [TearDown] public void CleanUp() { Log.Comment("Cleaning up after the tests"); } //TimeSpan Test methods const long m_TicksPerDay = 864000000000; const long m_TicksPerHour = 36000000000; const long m_TicksPerMinute = 600000000; const long m_TicksPerSecond = 10000000; const long m_TicksPerMillisecond = 10000; private bool CCtorHelper( ref TimeSpan ts ) { bool testResult = true; try { ts = new TimeSpan(); testResult &= ts.Ticks == 0; testResult &= ts.Days == 0; testResult &= ts.Hours == 0; testResult &= ts.Minutes == 0; testResult &= ts.Seconds == 0; testResult &= ts.Milliseconds == 0; if( !testResult ) Log.Comment( ts.ToString() ); } catch { Log.Comment("Exception Caught"); testResult = false; } Log.Comment( (testResult?"PASS":"FAIL") ); return testResult; } [TestMethod] public MFTestResults CCtor_Test( ) { /// /// 1. Test copy constructor /// /// Log.Comment( "Copy Constructor test" ); bool testResult = true; TimeSpan ts = new TimeSpan(); Log.Comment(ts.ToString()); testResult &= CCtorHelper( ref ts ); ts = TimeSpan.MaxValue; ts = new TimeSpan(); Log.Comment( ts.ToString() ); testResult &= CCtorHelper( ref ts ); ts = TimeSpan.MinValue; testResult &= CCtorHelper( ref ts ); int mxd = 24000; int mx = 1000; Random random = new Random(); for( int i = 0; i<5; i++ ) { int id = (random.Next(1)==0? -1: 1)* random.Next(mxd); int ih = (random.Next(1)==0? -1: 1)* random.Next(mx); int im = (random.Next(1)==0? -1: 1)* random.Next(mx); int ise = (random.Next(1)==0? -1: 1)* random.Next(mx); int ims = (random.Next(1)==0? -1: 1)* random.Next(mx); ts = new TimeSpan( id, ih, im, ise, ims ); testResult &= CCtorHelper( ref ts ); } return (testResult? MFTestResults.Pass: MFTestResults.Fail); } bool Ctor64Helper( Int64 i64 ) { /// /// 1. Test constructor /// /// Log.Comment("Constructor test"); bool testResult = true; try { TimeSpan ts = new TimeSpan( i64 ); long days = i64/m_TicksPerDay; long hours = (i64-ts.Days*m_TicksPerDay)/m_TicksPerHour; long minutes = (i64-ts.Days*m_TicksPerDay-ts.Hours* m_TicksPerHour)/m_TicksPerMinute; long seconds = (i64-ts.Days*m_TicksPerDay-ts.Hours* m_TicksPerHour-ts.Minutes*m_TicksPerMinute)/m_TicksPerSecond; long milliseconds = (i64-ts.Days*m_TicksPerDay-ts.Hours* m_TicksPerHour-ts.Minutes*m_TicksPerMinute-ts.Seconds*m_TicksPerSecond)/ m_TicksPerMillisecond; testResult &= (ts.Days == days); testResult &= (ts.Hours == hours); testResult &= (ts.Minutes == minutes); testResult &= (ts.Seconds == seconds); testResult &= (ts.Milliseconds == milliseconds); Log.Comment( ts.ToString() ); } catch { Log.Comment( "Exception occurred" ); testResult = false; } return testResult; } [TestMethod] public MFTestResults Ctor_Test( ) { /// /// 1. Test constructor with Int64 /// /// Log.Comment("Constructor test for 64 bit int"); bool testResult = true; Int64 i64 = 0; Log.Comment("Normal"); Random random = new Random(); for( int i = 0; i < 5; i++ ) { i64 = random.Next(int.MaxValue); i64 *= random.Next(10000); testResult &= Ctor64Helper( i64 ); } Log.Comment("Max and Min values"); i64 = 0x7fffffffffffffff; testResult &= Ctor64Helper( i64 ); testResult &= Ctor64Helper( TimeSpan.MaxValue.Ticks ); i64 = 0; testResult &= Ctor64Helper( i64 ); i64 = -9223372036854775808; testResult &= Ctor64Helper( i64 ); Log.Comment( "MAX VALUES: " + TimeSpan.MaxValue.Ticks.ToString() + " AND " + Int64.MaxValue ); testResult &= Ctor64Helper( Int64.MaxValue ); testResult &= Ctor64Helper( TimeSpan.MinValue.Ticks ); return (testResult? MFTestResults.Pass: MFTestResults.Fail); } bool CtorHelper( int[] vals ) { bool testResult = true; try { TimeSpan ts = new TimeSpan(0); Int64 i64 = 0; string str = ""; if( vals.Length == 3 ) str = "0 : "; for( int i=0; i /// 1. Test constructor with Hour Minute Second /// /// Log.Comment("Constructor test H:M:S"); bool testResult = true; Log.Comment( m_TicksPerDay.ToString() + " == " + TimeSpan.TicksPerDay.ToString() ); Log.Comment( m_TicksPerHour.ToString() + " == " + TimeSpan.TicksPerHour.ToString() ); Log.Comment( m_TicksPerMinute.ToString() + " == " + TimeSpan.TicksPerMinute.ToString() ); Log.Comment( m_TicksPerSecond.ToString() + " == " + TimeSpan.TicksPerSecond.ToString() ); Log.Comment( m_TicksPerMillisecond.ToString() + " == " + TimeSpan.TicksPerMillisecond.ToString() ); int []vals = new int[3]; Random random = new Random(); for( int i = 0; i < 5; i++ ) { vals[0] = random.Next( 23 ); //hours vals[1] = random.Next( 59 ); //min vals[2] = random.Next( 59 ); //sec testResult &= CtorHelper( vals ); } return (testResult? MFTestResults.Pass: MFTestResults.Fail); } [TestMethod] public MFTestResults Ctor_Test2( ) { /// /// 1. Test constructor with Day Hour Minute Second /// /// Log.Comment("Constructor test D:H:M:S"); bool testResult = true; int []vals = new int[4]; Random random = new Random(); for( int i = 0; i < 5; i++ ) { vals[0] = random.Next( 10*365 ) + 1; //days vals[1] = random.Next( 23 ); //hours vals[2] = random.Next( 59 ); //minutes vals[3] = random.Next( 59 ); //seconds testResult &= CtorHelper( vals ); } return (testResult? MFTestResults.Pass: MFTestResults.Fail); } [TestMethod] public MFTestResults Ctor_Test3( ) { /// /// 1. Test constructor with Day Hour Minute Second Millisecond /// /// Log.Comment("Constructor test D:H:M:S:MS"); bool testResult = true; Log.Comment( "TimeSpan::Ctor - Normal "); int []vals = new int[5]; Random random = new Random(); for( int i = 0; i < 5; i++ ) { vals[0] = random.Next( 10*365 ) + 1; //days vals[1] = random.Next( 23 ); //hours vals[2] = random.Next( 59 ); //minutes vals[3] = random.Next( 59 ); //seconds vals[4] = random.Next( 999 ); //milliseconds testResult &= CtorHelper( vals ); } return (testResult? MFTestResults.Pass: MFTestResults.Fail); } [TestMethod] public MFTestResults CompareTo_Test4( ) { /// /// 1. Construct 2 Timespans /// 2. Test the CompareTo method /// /// Log.Comment("Testing the CompareTo method"); bool testResult = true; Random random = new Random(); Log.Comment("Creating TimeSpan"); int day = random.Next(10 * 365) + 1; //days int hour = random.Next(23); //hours int minute = random.Next(59); //minutes int second = random.Next(59); //seconds int msec = random.Next(999); //milliseconds TimeSpan ts1 = new TimeSpan(day, hour, minute, second, msec ); Log.Comment("Testing CompareTo"); testResult &= (-1 == ts1.CompareTo( new TimeSpan(day+1,hour,minute,second,msec) ) ); Log.Comment(ts1.CompareTo(new TimeSpan(day+1, hour, minute, second, msec)).ToString()); Log.Comment( testResult.ToString() ); testResult &= (1 == ts1.CompareTo(new TimeSpan(day, hour-1, minute, second, msec))); Log.Comment(ts1.CompareTo(new TimeSpan(day, hour-1, minute, second, msec)).ToString()); Log.Comment( testResult.ToString() ); testResult &= (0 == ts1.CompareTo(new TimeSpan(day, hour, minute, second, msec))); Log.Comment(ts1.CompareTo(new TimeSpan(day, hour, minute, second, msec)).ToString()); Log.Comment( testResult.ToString() ); return (testResult? MFTestResults.Pass: MFTestResults.Fail); } [TestMethod] public MFTestResults GetHashCode_Test5( ) { /// /// 1. Test that GetHashCode returns the same for the same TimeSpan /// 2. Test that GetHashCode returns differently for different TimeSpans /// /// Log.Comment("Testing the GetHashCode method"); bool testResult = true; Random random = new Random(); Log.Comment("Test that GetHashCode returns the same for the same TimeSpan"); for( int i = 0; i<30; i++ ) { int hours = random.Next(23); int minutes = random.Next(59); int seconds = random.Next(59); TimeSpan ts01 = new TimeSpan( hours, minutes, seconds ); TimeSpan ts02 = new TimeSpan( hours, minutes, seconds ); Log.Comment( ts01.GetHashCode().ToString() + " == " + ts02.GetHashCode().ToString() ); testResult &= (ts01.GetHashCode() == ts02.GetHashCode()); } TimeSpan ts1 = new TimeSpan( 1,1,1 ); Log.Comment("Test that GetHashCode returns differently for different TimeSpans"); Log.Comment("This may fail erroneously."); Log.Comment("From the docs two different TimeSpans may have same hashcode" ); Log.Comment( "But, for the most part the values should be different." ); for( int i = 0; i < 5; i++ ) { TimeSpan ts2 = new TimeSpan( random.Next(23), random.Next(59),random.Next(59) ); Log.Comment( ts1.GetHashCode().ToString() + " Does Not Equal " + ts2.GetHashCode().ToString() ); if( ts1 != ts2 ) testResult &= (ts1.GetHashCode() != ts2.GetHashCode()); else testResult &= (ts1.GetHashCode() == ts2.GetHashCode()); } return (testResult? MFTestResults.Pass: MFTestResults.Fail); } [TestMethod] public MFTestResults Equals_Test6( ) { /// /// 1. Test the Equals method /// /// Log.Comment("Testing the Equals method"); bool testResult = true; try { Random random = new Random(); // verify same timespan computes to same hash for( int i = 0; i<5; i++ ) { int hours = random.Next(23); int minutes = random.Next(59); int seconds = random.Next(59); TimeSpan ts01 = new TimeSpan( hours, minutes, seconds ); TimeSpan ts02 = new TimeSpan( hours, minutes, seconds ); Log.Comment( ts01.ToString() + " == " + ts02.ToString() ); Log.Comment("Expected true"); testResult &= ts01.Equals(ts02); Log.Comment( testResult.ToString() ); TimeSpan ts03 = new TimeSpan(hours, minutes, seconds ); TimeSpan ts04 = new TimeSpan(hours + 1, minutes - 1, seconds + 1); Log.Comment("Expected false"); testResult &= !ts03.Equals(ts04); } } catch { testResult = false; } return (testResult? MFTestResults.Pass: MFTestResults.Fail); } [TestMethod] public MFTestResults ToString_Test7( ) { /// /// 1. Test the ToString method /// /// Log.Comment("Testing ToString method"); bool testResult = true; Random random = new Random(); for( int i = 0; i<5; i++ ) { bool b = true; int hours = random.Next(23); int minutes = random.Next(59); int seconds = random.Next(59); TimeSpan ts01 = new TimeSpan( hours, minutes, seconds ); string str = (hours<10?"0":"") + hours.ToString() + ":" + (minutes<10?"0":"") + minutes.ToString() + ":" + (seconds<10?"0":"") + seconds.ToString(); b &= (str == ts01.ToString()); Log.Comment( str + " == " + ts01.ToString() ); Log.Comment( b.ToString() ); testResult &= b; } return (testResult? MFTestResults.Pass: MFTestResults.Fail); } bool CompareTimeSpan( TimeSpan ts1, TimeSpan ts2 ) { bool testResult = true; testResult &= ts1.Days == ts2.Days; testResult &= ts1.Hours == ts2.Hours; testResult &= ts1.Minutes == ts2.Minutes; testResult &= ts1.Seconds == ts2.Seconds; testResult &= ts1.Milliseconds == ts2.Milliseconds; return testResult; } [TestMethod] public MFTestResults Add_Test8( ) { /// /// 1. Test the binary + operator /// /// Log.Comment("Testing the + operator"); bool testResult = true; Log.Comment( "TimeSpan::Add - Normal "); Random random = new Random(); for( int i = 0; i<5; i++ ) { bool b = true; TimeSpan ts01 = new TimeSpan( random.Next(12), random.Next(29), random.Next(29) ); int hours = random.Next(11); int minutes = random.Next(30); int seconds = random.Next(30); TimeSpan ts02 = new TimeSpan( hours, minutes, seconds ); TimeSpan ts03 = ts01.Add( ts02 ); b &= (ts01 != ts03); b &= !CompareTimeSpan( ts01, ts03 ); b &= CompareTimeSpan( ts03, ts01 + ts02 ); b &= (ts03.Days == (ts01.Days + ts02.Days)); b &= (ts03.Hours == (ts01.Hours + hours)); b &= (ts03.Minutes == (ts01.Minutes + minutes)); b &= (ts03.Seconds == (ts01.Seconds + seconds)); b &= (ts03.Milliseconds == (ts01.Milliseconds + ts02.Milliseconds)); Log.Comment( b.ToString() ); testResult &= b; } TimeSpan ts1 = new TimeSpan(2,2,2,2,2); TimeSpan ts2 = new TimeSpan(0,0,0,0,999); TimeSpan ts3 = ts1.Add(ts2); testResult &= (ts3.Milliseconds == 1); testResult &= (ts3.Seconds == 3); testResult &= (ts3.Minutes == 2); testResult &= (ts3.Hours == 2); testResult &= (ts3.Days == 2); ts2 = new TimeSpan(0,0,0,58,0); ts3 = ts1.Add(ts2); testResult &= (ts3.Milliseconds == 2); testResult &= (ts3.Seconds == 0); testResult &= (ts3.Minutes == 3); testResult &= (ts3.Hours == 2); testResult &= (ts3.Days == 2); ts2 = new TimeSpan(0,0,59,0,0); ts3 = ts1.Add(ts2); testResult &= (ts3.Milliseconds == 2); testResult &= (ts3.Seconds == 2); testResult &= (ts3.Minutes == 1); testResult &= (ts3.Hours == 3); testResult &= (ts3.Days == 2); ts2 = new TimeSpan(0,22,0,0,0); ts3 = ts1.Add(ts2); testResult &= (ts3.Milliseconds == 2); testResult &= (ts3.Seconds == 2); testResult &= (ts3.Minutes == 2); testResult &= (ts3.Hours == 0); testResult &= (ts3.Days == 3); return (testResult? MFTestResults.Pass: MFTestResults.Fail); } [TestMethod] public MFTestResults Compare_Test9( ) { /// /// 1. Test the Compare method /// /// Log.Comment("Testing the Compare method"); bool testResult = true; Random random = new Random(); int day = random.Next(10 * 365) + 1; //days int hour = random.Next(23); //hours int minute = random.Next(59); //minutes int second = random.Next(59); //seconds int msec = random.Next(999); //milliseconds TimeSpan ts1 = new TimeSpan(day, hour, minute, second, msec); testResult &= (-1 == TimeSpan.Compare(ts1, new TimeSpan (day, hour, minute, second+1, msec))); Log.Comment(TimeSpan.Compare(ts1, new TimeSpan (day, hour, minute, second+1, msec)).ToString()); Log.Comment( testResult.ToString() ); testResult &= (1 == TimeSpan.Compare(ts1, new TimeSpan (day, hour, minute, second, msec-1))); Log.Comment(TimeSpan.Compare(ts1, new TimeSpan (day, hour, minute, second, msec-1)).ToString()); Log.Comment( testResult.ToString() ); testResult &= (0 == TimeSpan.Compare(ts1, new TimeSpan (day, hour, minute, second, msec))); Log.Comment(TimeSpan.Compare(ts1, new TimeSpan (day, hour, minute, second, msec)).ToString()); Log.Comment( testResult.ToString() ); return (testResult? MFTestResults.Pass: MFTestResults.Fail); } [TestMethod] public MFTestResults Duration_Test10( ) { /// /// 1. Test the Duration property with several random TimeSpans /// /// Log.Comment("Testing Duration property"); bool testResult = true; Random random = new Random(); for( int i = 0; i<5; i++ ) { bool b = true; int hours = random.Next(23); int minutes = random.Next(59); int seconds = random.Next(59); TimeSpan ts = new TimeSpan( -hours, -minutes, -seconds ); testResult &= ts.Duration() == new TimeSpan( hours, minutes, seconds ); ts = new TimeSpan( hours, minutes, seconds ); testResult &= ts.Duration() == new TimeSpan( hours, minutes, seconds ); testResult &= b; } return (testResult? MFTestResults.Pass: MFTestResults.Fail); } [TestMethod] public MFTestResults Negate_Test12( ) { /// /// 1. Test the Negate method /// /// Log.Comment("Testing the Negate method"); bool testResult = true; Random random = new Random(); for( int i = 0; i<5; i++ ) { bool b = true; int hours = random.Next(23); int minutes = random.Next(59); int seconds = random.Next(59); TimeSpan tsN = new TimeSpan( -hours, -minutes, -seconds ); TimeSpan tsP = new TimeSpan( hours, minutes, seconds ); testResult &= tsN.Negate() == tsP; testResult &= tsP.Negate() == tsN; testResult &= tsN.Negate().Negate() == tsN; testResult &= tsP.Negate().Negate() == tsP; testResult &= b; } return (testResult? MFTestResults.Pass: MFTestResults.Fail); } [TestMethod] public MFTestResults Subtract_Test13( ) { /// /// 1. Test subtraction, the binary - operator /// /// Log.Comment("Testing the binary - operator"); bool testResult = true; Random random = new Random(); for( int i = 0; i<5; i++ ) { bool b = true; TimeSpan ts01 = new TimeSpan( 23, 59, 59 ); int hours = random.Next(23); int minutes = random.Next(59); int seconds = random.Next(59); TimeSpan ts02 = new TimeSpan( hours, minutes, seconds ); TimeSpan ts03 = ts01.Subtract( ts02 ); b &= (ts01 != ts03) || (ts02.Ticks==0); b &= !CompareTimeSpan( ts01, ts03 ); b &= CompareTimeSpan( ts03, ts01 - ts02 ); b &= (ts03.Days == (ts01.Days - ts02.Days)); b &= (ts03.Hours == (ts01.Hours - hours)); b &= (ts03.Minutes == (ts01.Minutes - minutes)); b &= (ts03.Seconds == (ts01.Seconds - seconds)); b &= (ts03.Milliseconds == (ts01.Milliseconds - ts02.Milliseconds)); testResult &= b; } TimeSpan ts1 = new TimeSpan(2,2,2,2,2); TimeSpan ts2 = new TimeSpan(0,0,0,0,3); TimeSpan ts3 = ts1.Subtract(ts2); testResult &= (ts3.Milliseconds == 999); testResult &= (ts3.Seconds == 1); testResult &= (ts3.Minutes == 2); testResult &= (ts3.Hours == 2); testResult &= (ts3.Days == 2); ts2 = new TimeSpan(0,0,0,3,0); ts3 = ts1.Subtract(ts2); testResult &= (ts3.Milliseconds == 2); testResult &= (ts3.Seconds == 59); testResult &= (ts3.Minutes == 1); testResult &= (ts3.Hours == 2); testResult &= (ts3.Days == 2); ts2 = new TimeSpan(0,0,3,0,0); ts3 = ts1.Subtract(ts2); testResult &= (ts3.Milliseconds == 2); testResult &= (ts3.Seconds == 2); testResult &= (ts3.Minutes == 59); testResult &= (ts3.Hours == 1); testResult &= (ts3.Days == 2); ts2 = new TimeSpan(0,3,0,0,0); ts3 = ts1.Subtract(ts2); testResult &= (ts3.Milliseconds == 2); testResult &= (ts3.Seconds == 2); testResult &= (ts3.Minutes == 2); testResult &= (ts3.Hours == 23); testResult &= (ts3.Days == 1); ts2 = new TimeSpan(3,0,0,0,0); ts3 = ts1.Subtract(ts2); testResult &= (ts3.Milliseconds == -998); testResult &= (ts3.Seconds == -57); testResult &= (ts3.Minutes == -57); testResult &= (ts3.Hours == -21); testResult &= (ts3.Days == 0); return (testResult? MFTestResults.Pass: MFTestResults.Fail); } private bool FromTicksHelper( int days, int hours, int mins, int secs, int ms ) { bool testResult = true; try { long ticks = m_TicksPerDay*days + m_TicksPerHour*hours + m_TicksPerMinute*mins + m_TicksPerSecond*secs + m_TicksPerMillisecond*ms; TimeSpan ts = TimeSpan.FromTicks( ticks ); int dys = (int)(ticks / m_TicksPerDay); Log.Comment( dys.ToString() ); testResult &= (ts.Days == dys ); Log.Comment(testResult.ToString() ); int hrs = (int)(ticks/m_TicksPerHour)%24; Log.Comment( hrs.ToString() ); testResult &= (ts.Hours == hrs ); Log.Comment(testResult.ToString() ); int mns = (int)(ticks/m_TicksPerMinute)%60; Log.Comment( mns.ToString() ); testResult &= (ts.Minutes == mns ); Log.Comment(testResult.ToString() ); int scs = (int)(ticks/m_TicksPerSecond)%60; Log.Comment( scs.ToString() ); testResult &= (ts.Seconds == scs); Log.Comment(testResult.ToString() ); int mss = (int)ms%1000; Log.Comment( "MS: " + mss.ToString() ); testResult &= (ts.Milliseconds == mss); Log.Comment(testResult.ToString() ); Log.Comment( "Days= " + days + " Hours= " + hours + " Minutes= " + mins + " Secs= " + secs + " ms= " + ms ); Log.Comment( ts.ToString() ); } catch { Log.Comment( "Exception caught" ); testResult = false; } Log.Comment( (testResult?"PASS":"FAIL" )); return testResult; } [TestMethod] public MFTestResults FromTicks_Test14( ) { /// /// 1. Testing the use of ticks in constructors /// /// Log.Comment("Testing the use of ticks, ticks per increment specified in this file"); bool testResult = true; Log.Comment( "TimeSpan::FromTicks - Normal "); Random random = new Random(); int max = 5000; int maxOthers = 200; for( int i = 0; i<5; i++ ) { testResult &= FromTicksHelper( random.Next(max), random.Next(maxOthers),random.Next(maxOthers), random.Next(maxOthers), random.Next(1000)); } return (testResult? MFTestResults.Pass: MFTestResults.Fail); } private bool UnaryHelper( int days, int hours, int mins, int secs, int ms, bool neg ) { bool testResult = true; try { long ticks = m_TicksPerDay*days + m_TicksPerHour*hours + m_TicksPerMinute*mins + m_TicksPerSecond*secs + m_TicksPerMillisecond*ms; TimeSpan ts = new TimeSpan( days, hours, mins, secs, ms ); TimeSpan nts = (neg? -ts: +ts); int d = (int)(ticks/m_TicksPerDay); int h = (int)((ticks%m_TicksPerDay)/m_TicksPerHour); int m = (int)((ticks%m_TicksPerDay%m_TicksPerHour)/m_TicksPerMinute); int s = (int)((ticks%m_TicksPerDay%m_TicksPerHour%m_TicksPerMinute) /m_TicksPerSecond); int m_s = (int)((ticks%m_TicksPerDay%m_TicksPerHour%m_TicksPerMinute %m_TicksPerSecond)/m_TicksPerMillisecond); testResult &= (nts.Days == (neg? -d: +d)); Log.Comment( nts.Days.ToString() + " == " + (neg?-d:+d).ToString() ); testResult &= (nts.Hours == (neg? -h: +h)); Log.Comment( nts.Hours.ToString() + " == " + ((neg? -h: +h)).ToString() ); testResult &= (nts.Minutes == (neg? -m: +m)); Log.Comment( nts.Minutes.ToString() + " == " + ((neg? -m: +m)).ToString() ); testResult &= (nts.Seconds == (neg? -s: +s)); Log.Comment( nts.Seconds.ToString() + " == " + ((neg? -s: +s)).ToString() ); testResult &= (nts.Milliseconds == (neg? -m_s: +m_s)); Log.Comment( nts.Milliseconds.ToString() + " == " +((neg? -m_s: +m_s)).ToString()); Log.Comment( ts.ToString() ); Log.Comment( nts.ToString() ); } catch { Log.Comment( "Exception occurred" ); testResult = false; } Log.Comment( (testResult?"PASS":"FAIL") ); return testResult; } [TestMethod] public MFTestResults op_UnaryNegation_Test15( ) { /// /// 1. Test negation, the unary - operator /// /// Log.Comment("Testing the unary - operator"); bool testResult = true; Random random = new Random(); int mxd = 24000; int mx = 10000; for( int i=0; i<5; i++ ) { int id = (random.Next(1)==0? -1: 1); int ih = (random.Next(1)==0? -1: 1); int im = (random.Next(1)==0? -1: 1); int ise = (random.Next(1)==0? -1: 1); int ims = (random.Next(1)==0? -1: 1); testResult &= UnaryHelper( id*random.Next(mxd), ih*random.Next(mx),im*random.Next(mx), ise*random.Next(mx),ims*random.Next(mx), true ); } return (testResult? MFTestResults.Pass: MFTestResults.Fail); } private bool OSubAddHelper( int days1, int hours1, int mins1, int secs1, int ms1, int days2, int hours2, int mins2, int secs2, int ms2, bool add ) { bool testResult = true; try { long ticks1 = m_TicksPerDay*days1 + m_TicksPerHour*hours1 + m_TicksPerMinute*mins1 + m_TicksPerSecond*secs1 + m_TicksPerMillisecond*ms1; long ticks2 = m_TicksPerDay*days2 + m_TicksPerHour*hours2 + m_TicksPerMinute*mins2 + m_TicksPerSecond*secs2 + m_TicksPerMillisecond*ms2; long ticks3 = (add? (ticks1 + ticks2): (ticks1 - ticks2)); int d1 = (int)(ticks3/m_TicksPerDay); int h1 = (int)((ticks3%m_TicksPerDay)/m_TicksPerHour); int m1 = (int)((ticks3%m_TicksPerDay%m_TicksPerHour)/m_TicksPerMinute); int s1 = (int)((ticks3%m_TicksPerDay%m_TicksPerHour%m_TicksPerMinute) /m_TicksPerSecond); int m_s1 = (int)((ticks3%m_TicksPerDay%m_TicksPerHour%m_TicksPerMinute %m_TicksPerSecond)/m_TicksPerMillisecond); TimeSpan ts1 = new TimeSpan( days1, hours1, mins1, secs1, ms1 ); TimeSpan ts2 = new TimeSpan( days2, hours2, mins2, secs2, ms2 ); TimeSpan ts3 = (add? (ts1 + ts2): (ts1 - ts2)); testResult &= (ts3.Days == d1); Log.Comment( ts3.Days.ToString() + " == " + d1.ToString() ); testResult &= (ts3.Hours == h1); Log.Comment( ts3.Hours.ToString() + " == " + h1.ToString() ); testResult &= (ts3.Minutes == m1); Log.Comment( ts3.Minutes.ToString() + " == " + m1.ToString() ); testResult &= (ts3.Seconds == s1); Log.Comment( ts3.Seconds.ToString() + " == " + s1.ToString() ); testResult &= (ts3.Milliseconds == m_s1); Log.Comment( ts3.Milliseconds.ToString() + " == " + m_s1.ToString() ); Log.Comment( ts1.ToString() ); Log.Comment( ts2.ToString() ); Log.Comment( ts3.ToString() ); } catch { Log.Comment( "Exception caught" ); testResult = false; } Log.Comment( (testResult?"PASS":"FAIL") ); Log.Comment(""); return testResult; } [TestMethod] public MFTestResults op_Subtraction_Test16( ) { /// /// 1. Test subtraction, the binary - operator with non TimeSpan args /// /// Log.Comment("Testing the binary - operator with non TimeSpan args"); bool testResult = true; Random random = new Random(); int mxd = 24000; int mx = 10000; for( int i = 0; i<5; i++ ) { int id = (random.Next(1)==0? -1: 1); int ih = (random.Next(1)==0? -1: 1); int im = (random.Next(1)==0? -1: 1); int ise = (random.Next(1)==0? -1: 1); int ims = (random.Next(1)==0? -1: 1); testResult &= OSubAddHelper( id*random.Next(mxd), ih*random.Next(mx),im*random.Next(mx), ise*random.Next(mx),ims*random.Next(mx), id*random.Next(mxd),ih*random.Next(mx), im*random.Next(mx),ise*random.Next(mx), ims*random.Next(mx), false ); } return (testResult? MFTestResults.Pass: MFTestResults.Fail); } [TestMethod] public MFTestResults op_UnaryPlus_Test17( ) { /// /// 1. Test the unary + operator /// /// Log.Comment("Testing the unary + operator"); bool testResult = true; Random random = new Random(); int mxd = 24000; int mx = 10000; for( int i=0; i<5; i++ ) { int id = (random.Next(1)==0? -1: 1); int ih = (random.Next(1)==0? -1: 1); int im = (random.Next(1)==0? -1: 1); int ise = (random.Next(1)==0? -1: 1); int ims = (random.Next(1)==0? -1: 1); testResult &= UnaryHelper( id*random.Next(mxd), ih*random.Next(mx),im*random.Next(mx), ise*random.Next(mx),ims*random.Next(mx), false ); } return (testResult? MFTestResults.Pass: MFTestResults.Fail); } [TestMethod] public MFTestResults op_Addition_Test18( ) { /// /// 1. Test the binary + operator with non-TimeSpan args /// /// Log.Comment("Testing the binary + operator with non-TimeSpan args"); bool testResult = true; Random random = new Random(); int mxd = 24000; int mx = 10000; for( int i = 0; i<5; i++ ) { int id = (random.Next(1)==0? -1: 1); int ih = (random.Next(1)==0? -1: 1); int im = (random.Next(1)==0? -1: 1); int ise = (random.Next(1)==0? -1: 1); int ims = (random.Next(1)==0? -1: 1); testResult &= OSubAddHelper( id*random.Next(mxd), ih*random.Next(mx),im*random.Next(mx), ise*random.Next(mx),ims*random.Next(mx), id*random.Next(mxd),ih*random.Next(mx), im*random.Next(mx),ise*random.Next(mx), ims*random.Next(mx), true ); } return (testResult? MFTestResults.Pass: MFTestResults.Fail); } private bool EqualityHelper( int days1, int hours1, int mins1, int secs1, int ms1, int days2, int hours2, int mins2, int secs2, int ms2, bool expected, bool ineq ) { bool testResult = true; try { TimeSpan ts1 = new TimeSpan( days1, hours1, mins1, secs1, ms1 ); TimeSpan ts2 = new TimeSpan( days2, hours2, mins2, secs2, ms2 ); testResult = ((ts1==ts2) == expected); } catch { Log.Comment( "Exception Caught" ); testResult = false; } return testResult; } [TestMethod] public MFTestResults op_Equality_Test19( ) { /// /// 1. Test equality, the binary == operator /// /// Log.Comment("Testing the == operator"); bool testResult = true; Random random = new Random(); int mxd = 24000; int mx = 10000; for( int i = 0; i<5; i++ ) { int id = (random.Next(1)==0? -1: 1)*random.Next(mxd); int ih = (random.Next(1)==0? -1: 1)*random.Next(mx); int im = (random.Next(1)==0? -1: 1)*random.Next(mx); int ise = (random.Next(1)==0? -1: 1)*random.Next(mx); int ims = (random.Next(1)==0? -1: 1)*random.Next(mx); testResult &= EqualityHelper( id, ih, im, ise, ims, id, ih, im, ise, ims, true, false ); testResult &= EqualityHelper( id, ih, im, ise, ims, id+1, ih, im, ise, ims, false, false ); testResult &= EqualityHelper( id, ih, im, ise, ims, id, ih+1, im, ise, ims, false, false ); testResult &= EqualityHelper( id, ih, im, ise, ims, id, ih, im+1, ise, ims, false, false ); testResult &= EqualityHelper( id, ih, im, ise, ims, id, ih, im, ise+1, ims, false, false ); testResult &= EqualityHelper( id, ih, im, ise, ims, id, ih, im, ise, ims+1, false, false ); } return (testResult? MFTestResults.Pass: MFTestResults.Fail); } private bool InequalityHelper(int days1, int hours1, int mins1, int secs1, int ms1, int days2, int hours2, int mins2, int secs2, int ms2, bool expected, bool ineq) { bool testResult = true; try { TimeSpan ts1 = new TimeSpan(days1, hours1, mins1, secs1, ms1); TimeSpan ts2 = new TimeSpan(days2, hours2, mins2, secs2, ms2); testResult = ((ts1 != ts2) == expected); } catch { Log.Comment("Exception Caught"); testResult = false; } return testResult; } [TestMethod] public MFTestResults op_Inequality_Test20( ) { /// /// 1. Test inequality, the binary != operator /// /// Log.Comment("Testing the != operator"); bool testResult = true; Random random = new Random(); int mxd = 24000; int mx = 10000; for( int i = 0; i<5; i++ ) { int id = (random.Next(1)==0? -1: 1)*random.Next(mxd); int ih = (random.Next(1)==0? -1: 1)*random.Next(mx); int im = (random.Next(1)==0? -1: 1)*random.Next(mx); int ise = (random.Next(1)==0? -1: 1)*random.Next(mx); int ims = (random.Next(1)==0? -1: 1)*random.Next(mx); testResult &= InequalityHelper( id, ih, im, ise, ims, id, ih, im, ise, ims, false, false ); testResult &= InequalityHelper(id, ih, im, ise, ims, id + 1, ih, im, ise, ims, true, false); testResult &= InequalityHelper(id, ih, im, ise, ims, id, ih + 1, im, ise, ims, true, false); testResult &= InequalityHelper(id, ih, im, ise, ims, id, ih, im + 1, ise, ims, true, false); testResult &= InequalityHelper(id, ih, im, ise, ims, id, ih, im, ise + 1, ims, true, false); testResult &= InequalityHelper(id, ih, im, ise, ims, id, ih, im, ise, ims + 1, true, false); } return (testResult? MFTestResults.Pass: MFTestResults.Fail); } private bool LTGTHelper( int days1, int hours1, int mins1, int secs1, int ms1, int days2, int hours2, int mins2, int secs2, int ms2, bool expected, int opcode ) { bool testResult = true; try { TimeSpan ts1 = new TimeSpan( days1, hours1, mins1, secs1, ms1 ); TimeSpan ts2 = new TimeSpan( days2, hours2, mins2, secs2, ms2 ); if( opcode == 0 ) testResult &= ((ts1 < ts2)==expected); else if( opcode == 1 ) testResult &= ((ts1 <= ts2)==expected); else if( opcode == 2 ) testResult &= ((ts1 > ts2)==expected); else if( opcode == 3 ) testResult &= ((ts1 >= ts2)==expected); else { Log.Comment( "Test Error: Invalid opcode" ); testResult = false; } } catch { Log.Comment( "Exception Caught" ); testResult = false; } return testResult; } [TestMethod] public MFTestResults op_LessThan_Test21( ) { /// /// 1. Testing the binary Less Than operator /// /// Log.Comment("Testing the Less Than operator"); bool testResult = true; Random random = new Random(); int mxd = 24000; int mx = 10000; for( int i = 0; i<5; i++ ) { int id = (random.Next(1)==0? -1: 1)*random.Next(mxd); int ih = (random.Next(1)==0? -1: 1)*random.Next(mx); int im = (random.Next(1)==0? -1: 1)*random.Next(mx); int ise = (random.Next(1)==0? -1: 1)*random.Next(mx); int ims = (random.Next(1)==0? -1: 1)*random.Next(mx); testResult &= LTGTHelper( id, ih, im, ise, ims, id, ih, im, ise, ims, false, 0 ); testResult &= LTGTHelper( id, ih, im, ise, ims, id+1, ih, im, ise, ims, true, 0 ); testResult &= LTGTHelper( id, ih, im, ise, ims, id, ih+1, im, ise, ims, true, 0 ); testResult &= LTGTHelper( id, ih, im, ise, ims, id, ih, im+1, ise, ims, true, 0 ); testResult &= LTGTHelper( id, ih, im, ise, ims, id, ih, im, ise+1, ims, true, 0 ); testResult &= LTGTHelper( id, ih, im, ise, ims, id, ih, im, ise, ims+1, true, 0 ); testResult &= LTGTHelper( id+1, ih, im, ise, ims, id, ih, im, ise, ims, false, 0 ); testResult &= LTGTHelper( id, ih+1, im, ise, ims, id, ih, im, ise, ims, false, 0 ); testResult &= LTGTHelper( id, ih, im+1, ise, ims, id, ih, im, ise, ims, false, 0 ); testResult &= LTGTHelper( id, ih, im, ise+1, ims, id, ih, im, ise, ims, false, 0 ); testResult &= LTGTHelper( id, ih, im, ise, ims+1, id, ih, im, ise, ims, false, 0 ); } return (testResult? MFTestResults.Pass: MFTestResults.Fail); } [TestMethod] public MFTestResults op_LessThanOrEqual_Test22( ) { /// /// 1. Test the binary Less Than Equals operator /// /// Log.Comment("Testing the Less Than Equals operator"); bool testResult = true; Random random = new Random(); int mxd = 24000; int mx = 10000; for( int i = 0; i<5; i++ ) { int id = (random.Next(1)==0? -1: 1)*random.Next(mxd); int ih = (random.Next(1)==0? -1: 1)*random.Next(mx); int im = (random.Next(1)==0? -1: 1)*random.Next(mx); int ise = (random.Next(1)==0? -1: 1)*random.Next(mx); int ims = (random.Next(1)==0? -1: 1)*random.Next(mx); testResult &= LTGTHelper( id, ih, im, ise, ims, id, ih, im, ise, ims, true, 1 ); testResult &= LTGTHelper( id, ih, im, ise, ims, id+1, ih, im, ise, ims, true, 1 ); testResult &= LTGTHelper( id, ih, im, ise, ims, id, ih+1, im, ise, ims, true, 1 ); testResult &= LTGTHelper( id, ih, im, ise, ims, id, ih, im+1, ise, ims, true, 1 ); testResult &= LTGTHelper( id, ih, im, ise, ims, id, ih, im, ise+1, ims, true, 1 ); testResult &= LTGTHelper( id, ih, im, ise, ims, id, ih, im, ise, ims+1, true, 1 ); testResult &= LTGTHelper( id+1, ih, im, ise, ims, id, ih, im, ise, ims, false, 1 ); testResult &= LTGTHelper( id, ih+1, im, ise, ims, id, ih, im, ise, ims, false, 1 ); testResult &= LTGTHelper( id, ih, im+1, ise, ims, id, ih, im, ise, ims, false, 1 ); testResult &= LTGTHelper( id, ih, im, ise+1, ims, id, ih, im, ise, ims, false, 1 ); testResult &= LTGTHelper( id, ih, im, ise, ims+1, id, ih, im, ise, ims, false, 1 ); } return (testResult? MFTestResults.Pass: MFTestResults.Fail); } [TestMethod] public MFTestResults op_GreaterThan_Test23( ) { /// /// 1. Test the binary Greater Than operator /// /// Log.Comment("Testing the Greater Than operator"); bool testResult = true; Random random = new Random(); int mxd = 24000; int mx = 10000; for( int i = 0; i<5; i++ ) { int id = (random.Next(1)==0? -1: 1)*random.Next(mxd); int ih = (random.Next(1)==0? -1: 1)*random.Next(mx); int im = (random.Next(1)==0? -1: 1)*random.Next(mx); int ise = (random.Next(1)==0? -1: 1)*random.Next(mx); int ims = (random.Next(1)==0? -1: 1)*random.Next(mx); testResult &= LTGTHelper( id, ih, im, ise, ims, id, ih, im, ise, ims, false, 2 ); testResult &= LTGTHelper( id, ih, im, ise, ims, id+1, ih, im, ise, ims, false, 2 ); testResult &= LTGTHelper( id, ih, im, ise, ims, id, ih+1, im, ise, ims, false, 2 ); testResult &= LTGTHelper( id, ih, im, ise, ims, id, ih, im+1, ise, ims, false, 2 ); testResult &= LTGTHelper( id, ih, im, ise, ims, id, ih, im, ise+1, ims, false, 2 ); testResult &= LTGTHelper( id, ih, im, ise, ims, id, ih, im, ise, ims+1, false, 2 ); testResult &= LTGTHelper( id+1, ih, im, ise, ims, id, ih, im, ise, ims, true, 2 ); testResult &= LTGTHelper( id, ih+1, im, ise, ims, id, ih, im, ise, ims, true, 2 ); testResult &= LTGTHelper( id, ih, im+1, ise, ims, id, ih, im, ise, ims, true, 2 ); testResult &= LTGTHelper( id, ih, im, ise+1, ims, id, ih, im, ise, ims, true, 2 ); testResult &= LTGTHelper( id, ih, im, ise, ims+1, id, ih, im, ise, ims, true, 2 ); } return (testResult? MFTestResults.Pass: MFTestResults.Fail); } [TestMethod] public MFTestResults op_GreaterThanOrEqual_Test24( ) { /// /// 1. Test the binary Greater Than Equals operator /// /// Log.Comment("Testing the Greater Than Equals operator"); bool testResult = true; Random random = new Random(); int mxd = 24000; int mx = 10000; for( int i = 0; i<5; i++ ) { int id = (random.Next(1)==0? -1: 1)*random.Next(mxd); int ih = (random.Next(1)==0? -1: 1)*random.Next(mx); int im = (random.Next(1)==0? -1: 1)*random.Next(mx); int ise = (random.Next(1)==0? -1: 1)*random.Next(mx); int ims = (random.Next(1)==0? -1: 1)*random.Next(mx); testResult &= LTGTHelper( id, ih, im, ise, ims, id, ih, im, ise, ims, true, 3 ); testResult &= LTGTHelper( id, ih, im, ise, ims, id+1, ih, im, ise, ims, false, 3 ); testResult &= LTGTHelper( id, ih, im, ise, ims, id, ih+1, im, ise, ims, false, 3 ); testResult &= LTGTHelper( id, ih, im, ise, ims, id, ih, im+1, ise, ims, false, 3 ); testResult &= LTGTHelper( id, ih, im, ise, ims, id, ih, im, ise+1, ims, false, 3 ); testResult &= LTGTHelper( id, ih, im, ise, ims, id, ih, im, ise, ims+1, false, 3 ); testResult &= LTGTHelper( id+1, ih, im, ise, ims, id, ih, im, ise, ims, true, 3 ); testResult &= LTGTHelper( id, ih+1, im, ise, ims, id, ih, im, ise, ims, true, 3 ); testResult &= LTGTHelper( id, ih, im+1, ise, ims, id, ih, im, ise, ims, true, 3 ); testResult &= LTGTHelper( id, ih, im, ise+1, ims, id, ih, im, ise, ims, true, 3 ); testResult &= LTGTHelper( id, ih, im, ise, ims+1, id, ih, im, ise, ims, true, 3 ); } return (testResult? MFTestResults.Pass: MFTestResults.Fail); } private bool TicksHelper( int days, int hours, int mins, int secs, int ms ) { bool testResult = true; try { TimeSpan ts = new TimeSpan( days, hours, mins, secs, ms ); long ticks = days * m_TicksPerDay + hours * m_TicksPerHour + mins * m_TicksPerMinute + secs * m_TicksPerSecond + ms * m_TicksPerMillisecond; testResult &= (ts.Ticks == ticks); Log.Comment( ts.Ticks.ToString() + " == " + ticks.ToString() ); } catch { testResult = false; Log.Comment( "Exception caught" ); } Log.Comment( (testResult?"PASS":"FAIL") ); return testResult; } [TestMethod] public MFTestResults Ticks_Test28( ) { /// /// 1. Test the Ticks Property /// /// Log.Comment("Testing the Ticks Property"); bool testResult = true; Log.Comment( "TimeSpan::Ticks - Normal "); Random random = new Random(); int max = 24000; int maxOthers = 10000; for( int i=0; i<5; i++ ) { testResult &= TicksHelper( random.Next(max), random.Next(maxOthers),random.Next(maxOthers), random.Next(maxOthers), random.Next(maxOthers)); } return (testResult? MFTestResults.Pass: MFTestResults.Fail); } } } ================================================ FILE: Zelig/Zelig/Test/RunTime/NETMF/mscorlib/systemlib/systemlib1/SystemTimeZoneTests.cs ================================================ //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // Copyright (c) Microsoft Corporation. All rights reserved. //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// using System; using System.Reflection; using Microsoft.SPOT.Platform.Test; using System.Collections; using System.Threading; using Microsoft.SPOT; using System.Globalization; namespace Microsoft.SPOT.Platform.Tests { public class SystemTimeZoneTests : IMFTestInterface { string[] TimeZoneNames = { "SPACER 0", "SPACER 1", "Dateline", "Samoa/Midway", "Hawaii", "Alaska", "Pacific-US", "Arizona", "Mountain-US", "Cent. America", "Central-US", "Saskatchewan", "Mexico City", "Indiana", "Bogota,Lima", "Eastern-US", "Caracas,La Paz", "Santiago", "Atlantic", "Newfoundland", "Brasilia", "Greenland", "Buenos Aires", "Mid-Atlantic", "Cape Verde", "Azores", "Casablanca", "GMT", "London,Dublin", "W Cent Africa", "Prague,Budapest", "Warsaw,Sofjia", "Paris,Madrid", "Berlin,Rome", "Cairo", "Pretoria", "Bucharest", "Helsinki", "Athens", "Riyadh,Kuwait", "Nairobi", "Moscow", "Baghdad", "Tehran", "Baku,Tbilisi", "Kabul", "Abu Dhabi", "Yekaterinburg", "Islamabad", "New Delhi", "Kathmandu", "Astana,Dhaka", "Sri Lanka", "Almaty", "Yangon", "Bangkok", "Krasnoyarsk", "Beijing, HK", "Malaysia", "Taipei", "Perth", "Ulaanbataar", "Seoul", "Tokyo,Osaka", "Yakutsk", "Darwin", "Adelaide", "Sydney", "Brisbane", "Hobart", "Guam", "Vladivostok", "Magadan", "Fiji Islands", "New Zealand", "Tonga" }; [SetUp] public InitializeResult Initialize() { Log.Comment("Adding set up for the tests"); return InitializeResult.ReadyToGo; } [TearDown] public void CleanUp() { Log.Comment("Cleaning up after the tests"); } [TestMethod] public MFTestResults NotImplemented() { Log.Comment("All cases were disabled because of change to ExtendedTimeZone. These cases need to be refactors when Time Sync feature is ready for test."); return MFTestResults.KnownFailure; } //TimeZone Test methods /*[TestMethod] public MFTestResults Ctor_Test0() { /// /// 1. Test the TimeZone constructor /// /// Log.Comment("Tests the constructor of the TimeZone object"); Log.Comment("references a list of the time zone names in this file"); bool testResult = true; TimeZone tz = TimeZone.CurrentTimeZone; Log.Comment(tz.StandardName); for (TimeZoneId tzid = TimeZoneId.Dateline; tzid <= TimeZoneId.Tonga; tzid++) { tz = ExtendedTimeZone.GetTimeZone(tzid); string tzName = TimeZoneNames[(int)tzid]; Log.Comment(tz.StandardName + " == " + tzName); testResult &= tz.StandardName == tzName; } return (testResult ? MFTestResults.Pass : MFTestResults.Fail); } [TestMethod] public MFTestResults IsDaylightSavingTime_Test1() { /// /// 1. Test the IsDaylightSavingTime method /// Each of: Start, Immediately pre-start, End, Immediate pre-end /// For: Pacific 2003, 2009, Europe 2003, 2009 /// /// /// IsDaylightSavingTime is failing. This is bug number: /// 21290 IsDaylightSavingTime is failing by returning true when it isn't daylight savings time. Log.Comment("Tests the IsDaylightSavingTime method"); bool testResult = true; Log.Comment("TimeZone::IsDaylightSavingTime - Normal "); TimeZone tz = ExtendedTimeZone.GetTimeZone(TimeZoneId.Pacific); Log.Comment("just before daylight savings"); DateTime beforeSavingTime2007 = new DateTime(2007, 3, 11, 1, 59, 59, 999); testResult &= !tz.IsDaylightSavingTime(beforeSavingTime2007); Log.Comment("start of daylight savings"); DateTime afterSavingTime2007 = new DateTime(2007, 3, 11, 2, 0, 0, 0); testResult &= tz.IsDaylightSavingTime(afterSavingTime2007); Log.Comment("end of daylight savings"); testResult &= !tz.IsDaylightSavingTime(new DateTime(2007, 11, 4, 2, 0, 0, 0)); Log.Comment("just before end of daylight savings"); testResult &= tz.IsDaylightSavingTime(new DateTime(2007, 11, 4, 1, 59, 59, 999)); for (int i = 0; i < 2; i++) { DateTime DT1 = new DateTime(2007, 3, Microsoft.SPOT.Math.Random(19) + 12, Microsoft.SPOT.Math.Random(23), Microsoft.SPOT.Math.Random(59), Microsoft.SPOT.Math.Random(59), Microsoft.SPOT.Math.Random(999)); testResult &= tz.IsDaylightSavingTime(DT1); Log.Comment(DT1 + " " + testResult); DateTime DT2 = new DateTime(2007, Microsoft.SPOT.Math.Random(1) + 1, Microsoft.SPOT.Math.Random(28)+1, Microsoft.SPOT.Math.Random(23), Microsoft.SPOT.Math.Random(59), Microsoft.SPOT.Math.Random(59), Microsoft.SPOT.Math.Random(999)); testResult &= !tz.IsDaylightSavingTime(DT2); Log.Comment(DT2 + " " + testResult); DateTime DT3 = new DateTime(2003, Microsoft.SPOT.Math.Random(1) + 11, Microsoft.SPOT.Math.Random(25)+5, Microsoft.SPOT.Math.Random(23), Microsoft.SPOT.Math.Random(59), Microsoft.SPOT.Math.Random(59), Microsoft.SPOT.Math.Random(999)); testResult &= !tz.IsDaylightSavingTime(DT3); Log.Comment(DT3 + " " + testResult); } Log.Comment("Future: 2009"); Log.Comment(" start of daylight savings"); testResult &= tz.IsDaylightSavingTime(new DateTime(2009, 3, 8, 3, 0, 0, 0)); Log.Comment(testResult.ToString()); Log.Comment(" just before daylight savings"); testResult &= !tz.IsDaylightSavingTime(new DateTime(2009, 3, 8, 1, 59, 59, 999)); Log.Comment(testResult.ToString()); Log.Comment(" end of daylight savings"); testResult &= !tz.IsDaylightSavingTime(new DateTime(2009, 11, 1, 2, 0, 0, 0)); Log.Comment(testResult.ToString()); Log.Comment(" just before end of daylight savings"); testResult &= tz.IsDaylightSavingTime(new DateTime(2009, 11, 1, 1, 59, 59, 999)); Log.Comment(testResult.ToString()); Log.Comment("Far Future: 2207"); Log.Comment(" start of daylight savings"); testResult &= tz.IsDaylightSavingTime(new DateTime(2207, 3, 8, 2, 0, 0, 0)); Log.Comment(testResult.ToString()); Log.Comment(" just before daylight savings"); testResult &= !tz.IsDaylightSavingTime(new DateTime(2207, 3, 8, 1, 59, 59, 999)); Log.Comment(testResult.ToString()); Log.Comment(" end of daylight savings"); testResult &= !tz.IsDaylightSavingTime(new DateTime(2207, 11, 1, 2, 0, 0, 0)); Log.Comment(testResult.ToString()); Log.Comment(" just before end of daylight savings"); testResult &= tz.IsDaylightSavingTime(new DateTime(2207, 11, 1, 1, 59, 59, 999)); Log.Comment(testResult.ToString()); Log.Comment("British Summer Time : In 2003: - March 30 October 26 "); testResult = true; tz = ExtendedTimeZone.GetTimeZone(TimeZoneId.London); Log.Comment(" start of daylight savings"); testResult &= tz.IsDaylightSavingTime(new DateTime(2003, 3, 30, 1, 0, 0, 0)); Log.Comment(testResult.ToString()); Log.Comment(" just before daylight savings"); testResult &= !tz.IsDaylightSavingTime(new DateTime(2003, 3, 30, 0, 59, 59, 999)); Log.Comment(testResult.ToString()); Log.Comment(" end of daylight savings"); testResult &= !tz.IsDaylightSavingTime(new DateTime(2003, 10, 26, 2, 0, 0, 0)); Log.Comment(testResult.ToString()); Log.Comment(" just before end of daylight savings"); testResult &= tz.IsDaylightSavingTime(new DateTime(2003, 10, 26, 0, 59, 59, 999)); Log.Comment(testResult.ToString()); Log.Comment(" Future - British Summer Time : In 2009: the Sundays of 29 March and 25 October - http://www.berr.gov.uk/employment/bank-public-holidays/bst/page12528.html "); testResult &= tz.IsDaylightSavingTime(new DateTime(2009, 3, 29, 1, 0, 0, 0)); Log.Comment(testResult.ToString()); Log.Comment(" just before daylight savings"); testResult &= !tz.IsDaylightSavingTime(new DateTime(2009, 3, 29, 0, 59, 59, 999)); Log.Comment(testResult.ToString()); Log.Comment(" end of daylight savings"); testResult &= !tz.IsDaylightSavingTime(new DateTime(2009, 10, 25, 2, 0, 0, 0)); Log.Comment(testResult.ToString()); Log.Comment(" just before end of daylight savings"); testResult &= tz.IsDaylightSavingTime(new DateTime(2009, 10, 25, 1, 59, 59, 999)); Log.Comment(testResult.ToString()); return (testResult ? MFTestResults.Pass : MFTestResults.Fail); } // NOT IMPLEMENENTED [TestMethod] public MFTestResults GetDaylightChanges_Test() { /// /// 1. GetDaylightChanges nethod NYI: Returns None /// /// Log.Comment("This would test GetDaylightChanges if it were implemented in the MF"); return MFTestResults.Skip; } [TestMethod] public MFTestResults ToLocalTime_Test2() { /// /// 1. Calls DateTime.ToLocalTime /// 2. Verifies the output /// /// bool testResult = true; ExtendedTimeZone.SetTimeZone(TimeZoneId.Pacific); Log.Comment(ExtendedTimeZone.CurrentTimeZone.StandardName); TimeZone tz = ExtendedTimeZone.GetTimeZone(TimeZoneId.Pacific); for (TimeZoneId tzid = TimeZoneId.FIRST; tzid <= TimeZoneId.LAST; tzid++) { tz = ExtendedTimeZone.GetTimeZone(tzid); Log.Comment(tz.StandardName); Microsoft.SPOT.Math.Randomize(); for (int i = 0; i < 2; i++) { DateTime dt = new DateTime(Microsoft.SPOT.Math.Random(10) + 2000, Microsoft.SPOT.Math.Random(12) + 1, Microsoft.SPOT.Math.Random(28) + 1, Microsoft.SPOT.Math.Random(23), Microsoft.SPOT.Math.Random(59), Microsoft.SPOT.Math.Random(59), Microsoft.SPOT.Math.Random(999)); // Set dt to UTC time kind. dt = DateTime.SpecifyKind(dt, DateTimeKind.Utc); Log.Comment("Calling DateTime.ToLocalTime"); DateTime dt2 = tz.ToLocalTime(dt); Log.Comment("DST: " + tz.IsDaylightSavingTime(dt).ToString()); Log.Comment("Offset: " + tz.GetUtcOffset(dt).ToString()); bool bDST = tz.IsDaylightSavingTime(dt); dt = dt.Add(tz.GetUtcOffset(dt)); Log.Comment("Verifying"); testResult &= (dt2 == dt); } if (!testResult) { break; } } return (testResult ? MFTestResults.Pass : MFTestResults.Fail); } [TestMethod] public MFTestResults ToUniversalTime_Test3() { /// /// 1. Calls DateTime.ToUniversalTime /// 2. Verifies the output /// /// bool testResult = true; ExtendedTimeZone.SetTimeZone(TimeZoneId.Pacific); Log.Comment(ExtendedTimeZone.CurrentTimeZone.StandardName); TimeZone tz = ExtendedTimeZone.GetTimeZone(TimeZoneId.Pacific); for (TimeZoneId tzid = TimeZoneId.Dateline; tzid <= TimeZoneId.Tonga; tzid++) { tz = ExtendedTimeZone.GetTimeZone(tzid); Log.Comment(tz.StandardName); Microsoft.SPOT.Math.Randomize(); for (int i = 0; i < 2; i++) { DateTime dt = new DateTime(Microsoft.SPOT.Math.Random(10) + 2000, Microsoft.SPOT.Math.Random(12) + 1, Microsoft.SPOT.Math.Random(28) + 1, Microsoft.SPOT.Math.Random(23), Microsoft.SPOT.Math.Random(59), Microsoft.SPOT.Math.Random(59), Microsoft.SPOT.Math.Random(999)); Log.Comment("Calling DateTime.ToUniversalTime"); DateTime dt2 = tz.ToUniversalTime(dt); Log.Comment("DST: " + tz.IsDaylightSavingTime(dt).ToString()); Log.Comment("Offset: " + tz.GetUtcOffset(dt).ToString()); bool bDST = tz.IsDaylightSavingTime(dt); dt = dt.Subtract(tz.GetUtcOffset(dt)); Log.Comment("Verifying"); testResult &= (dt2 == dt); } if (!testResult) { break; } } return (testResult ? MFTestResults.Pass : MFTestResults.Fail); } [TestMethod] public MFTestResults GetUtcOffset_Test4() { /// /// 1. Calls DateTime.GetUtcOffset for Pacific, Arizona, Dateline and London /// 2. Verifies the output for each /// /// bool testResult = true; Log.Comment("TimeZone::GetUtcOffset - Normal "); ExtendedTimeZone.SetTimeZone(TimeZoneId.Pacific); Log.Comment("Pacific"); TimeZone tz = ExtendedTimeZone.GetTimeZone(TimeZoneId.Pacific); testResult &= (tz.GetUtcOffset(new DateTime(2003, 1, 1, 0, 0, 0, 0)).Hours == -8); testResult &= (tz.GetUtcOffset(new DateTime(2003, 4, 6, 2, 0, 0, 0)).Hours == -7); Log.Comment("Arizona"); tz = ExtendedTimeZone.GetTimeZone(TimeZoneId.Arizona); testResult &= (tz.GetUtcOffset(new DateTime(2003, 1, 1, 0, 0, 0, 0)).Hours == -7); testResult &= (tz.GetUtcOffset(new DateTime(2003, 4, 6, 5, 0, 0, 0)).Hours == -7); Log.Comment("Dateline"); tz = ExtendedTimeZone.GetTimeZone(TimeZoneId.Dateline); testResult &= (tz.GetUtcOffset(new DateTime(2003, 1, 1, 0, 0, 0, 0)).Hours == -12); testResult &= (tz.GetUtcOffset(new DateTime(2003, 6, 6, 5, 0, 0, 0)).Hours == -12); Log.Comment("London"); tz = ExtendedTimeZone.GetTimeZone(TimeZoneId.London); testResult &= (tz.GetUtcOffset(new DateTime(2003, 1, 1, 0, 0, 0, 0)).Hours == 0); testResult &= (tz.GetUtcOffset(new DateTime(2003, 6, 6, 5, 0, 0, 0)).Hours == 1); return (testResult ? MFTestResults.Pass : MFTestResults.Fail); } [TestMethod] public MFTestResults CurrentTimeZone_Test5() { /// /// 1. Calls DateTime.CurrentTimeZone for each time zone /// 2. Verifies the output for each /// /// bool testResult = true; Log.Comment("Tests CurrentTimeZone for each TimeZone"); for (TimeZoneId tzid = TimeZoneId.FIRST; tzid <= TimeZoneId.LAST; tzid++) { TimeZone tz1 = ExtendedTimeZone.GetTimeZone(tzid); Log.Comment(tz1.ToString()); ExtendedTimeZone.SetTimeZone(tzid); TimeZone tz2 = TimeZone.CurrentTimeZone; testResult &= (tz1.StandardName == tz2.StandardName); testResult &= (tz1.DaylightName == tz2.DaylightName); if (!testResult) { Log.Comment(tz1.StandardName + " == " + tz2.StandardName); } } return (testResult ? MFTestResults.Pass : MFTestResults.Fail); } [TestMethod] public MFTestResults StandardName_Test6() { /// /// 1. Tests the StandardName property of each TimeZone /// /// bool testResult = true; Log.Comment("Tests the StandardName property of each TimeZone"); for (TimeZoneId tzid = TimeZoneId.Dateline; tzid <= TimeZoneId.Tonga; tzid++) { TimeZone tz1 = ExtendedTimeZone.GetTimeZone(tzid); string tzName = TimeZoneNames[(int)tzid]; Log.Comment(tz1.StandardName); testResult &= tz1.StandardName == tzName; } return (testResult ? MFTestResults.Pass : MFTestResults.Fail); } [TestMethod] public MFTestResults DaylightName_Test7() { /// /// 1. Tests the DaylightName property of each TimeZone /// /// bool testResult = true; Log.Comment("Tests the DaylightName property of each TimeZone"); for (TimeZoneId tzid = TimeZoneId.Dateline; tzid <= TimeZoneId.Tonga; tzid++) { TimeZone tz1 = ExtendedTimeZone.GetTimeZone(tzid); string tzName = TimeZoneNames[(int)tzid]; Log.Comment(tz1.DaylightName); testResult &= tz1.DaylightName == tzName; } return (testResult ? MFTestResults.Pass : MFTestResults.Fail); } * */ } } ================================================ FILE: Zelig/Zelig/Test/RunTime/NETMF/mscorlib/systemlib/systemlib2/InitLocalsTests.cs ================================================ //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // Copyright (c) Microsoft Corporation. All rights reserved. //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// using System; using System.Reflection; using Microsoft.SPOT.Platform.Test; using System.Collections; namespace Microsoft.SPOT.Platform.Tests { public class InitLocalsTests : IMFTestInterface { [SetUp] public InitializeResult Initialize() { Log.Comment("Adding set up for the tests."); // Add your functionality here. Log.Comment("These tests test local variable initializations"); return InitializeResult.ReadyToGo; } [TearDown] public void CleanUp() { Log.Comment("Cleaning up after the tests"); } public interface IEmptyInterface { } class TestObj : IEmptyInterface { public int Field1; public void Method1(int i) { } public TestObj() { Field1 = 3; } public TestObj(int field) { Field1 = field; } private bool Method2(float f) { return true; } } [TestMethod] public MFTestResults SystemType1_GetType_Test() { bool fRes = true; int i = 0; Log.Comment("Checking reflection types to assure that they are boxed when used as local variables"); Log.Comment("and when they are assigned to non-valuetype containers (which used to crash)"); try { ArrayList list = new ArrayList(); // First lets check all reflection types (Type, AppDomain, Assembly, FieldInfo, MethodInfo, // ConstructorInfo) // NOTE: We add the reflection items to the ArrayList to assure that they can be properly // assigned to a object container (this used to lead to a access violation) Type type = typeof(int); list.Add(type); string name = ((Type)list[i]).Name; fRes &= name == "Int32"; i++; AppDomain domain = AppDomain.CurrentDomain; list.Add(domain); name = ((AppDomain)list[i]).FriendlyName; fRes &= name.ToLower() == "default"; i++; Assembly asm = domain.GetAssemblies()[0]; list.Add(asm); name = ((Assembly)list[i]).GetName().Name; fRes &= name.ToLower() == "mscorlib"; i++; type = Type.GetType("Microsoft.SPOT.Platform.Tests.InitLocalsTests+TestObj"); list.Add(type); name = ((Type)list[i]).Name; fRes &= name == "TestObj"; i++; Type iface = type.GetInterfaces()[0]; list.Add(iface); name = ((Type)list[i]).Name; fRes &= name == "IEmptyInterface"; fRes &= iface.Name == "IEmptyInterface"; i++; FieldInfo fi = type.GetField("Field1"); list.Add(fi); name = ((FieldInfo)list[i]).Name; fRes &= name == "Field1"; fRes &= fi.Name == "Field1"; i++; MethodInfo mi = type.GetMethod("Method1"); list.Add(mi); name = ((MethodInfo)list[i]).Name; fRes &= name == "Method1"; fRes &= mi.Name == "Method1"; i++; ConstructorInfo ci = type.GetConstructor(new Type[] { }); list.Add(ci); name = ((ConstructorInfo)list[i]).Name; fRes &= name == ".ctor"; fRes &= ci.Name == ".ctor"; i++; // // Now test arrays of reflection types // Type[] types = new Type[] { typeof(int), typeof(bool), Type.GetType("Microsoft.SPOT.Platform.Tests.InitLocalsTests+TestObj") }; list.Add(types[2]); name = ((Type)list[i]).Name; fRes &= name == "TestObj"; fRes &= types[2].Name == "TestObj"; i++; AppDomain[] domains = new AppDomain[] { AppDomain.CurrentDomain, AppDomain.CreateDomain("blah") }; list.Add(domains[1]); name = ((AppDomain)list[i]).FriendlyName; fRes &= name == "blah"; fRes &= domains[1].FriendlyName == "blah"; AppDomain.Unload(domains[1]); i++; Assembly[] asms = new Assembly[] { typeof(InitLocalsTests).Assembly, domains[0].GetAssemblies()[0] }; list.Add(asms[0]); name = ((Assembly)list[i]).GetName().Name; fRes &= name == "Microsoft.SPOT.Platform.Tests.Systemlib2"; fRes &= asms[0].GetName().Name == "Microsoft.SPOT.Platform.Tests.Systemlib2"; i++; FieldInfo[] fis = new FieldInfo[] { types[2].GetField("Field1"), type.GetFields()[0] }; list.Add(fis[0]); name = ((FieldInfo)list[i]).Name; fRes &= name == "Field1"; fRes &= fis[0].Name == "Field1"; i++; MethodInfo[] mis = new MethodInfo[] { type.GetMethods()[2], types[2].GetMethod("Method2", BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.Public) }; list.Add(mis[1]); name = ((MethodInfo)list[i]).Name; fRes &= name == "Method2"; fRes &= mis[1].Name == "Method2"; i++; ConstructorInfo[] cis = new ConstructorInfo[] { types[2].GetConstructor(new Type[] { }), typeof(TestObj).GetConstructor(new Type[] {typeof(int)}) }; list.Add(cis[0]); name = ((ConstructorInfo)list[i]).Name; fRes &= name == ".ctor"; fRes &= cis[0].Name == ".ctor"; i++; Array ar = Array.CreateInstance(typeof(Type), 3); ((IList)ar)[0] = typeof(Type); ((IList)ar)[1] = Type.GetType("System.Collections.ArrayList"); list.Add(ar.GetValue(1)); name = ((Type)list[i]).Name; fRes &= name == "ArrayList"; fRes &= ((Type)((IList)ar)[0]).Name == "Type"; fRes &= ((Type)ar.GetValue(1)).Name == "ArrayList"; i++; list.Clear(); Debug.GC(true); } catch(Exception e) { Log.Exception("Unhandled Exception: ", e); } return fRes ? MFTestResults.Pass : MFTestResults.Fail; } [TestMethod] public MFTestResults SystemType1_StructValueTypeReturn_Test() { bool fRes = true; // make sure return values are properly boxed try { Guid g = ReturnGuid(); Debug.Print(g.ToString()); } catch { fRes = false; } return fRes ? MFTestResults.Pass : MFTestResults.Fail; } [TestMethod] public MFTestResults SystemType1_StructArrayInit_Test() { bool fRes = true; // make sure arrays are initialized properly for struct value types (Guids in this case). try { Guid[] data = new Guid[] { ReturnGuid(), new Guid(), Guid.NewGuid(), new Guid(344, 45, 24, 24, 4, 42, 42, 4, 44, 22, 4) }; foreach (Guid g2 in data) { Debug.Print(g2.ToString()); // test to make sure boxing (to call struct method) // still works properly if (Guid.Empty.Equals(g2)) { fRes &= true; } } } catch { fRes = false; } return fRes ? MFTestResults.Pass : MFTestResults.Fail; } [TestMethod] public MFTestResults SystemType1_ArrayListToArrayForStruct_Test() { bool fRes = true; // make sure boxing of struct value type (Guid) is handled properly // this test was a result of a bug found by a customer. try { Guid ret = new Guid(); ArrayList guidList = new ArrayList(); guidList.Add(Guid.NewGuid()); guidList.Add(Guid.NewGuid()); Guid[] guidArray = (Guid[])guidList.ToArray(typeof(Guid)); foreach (Guid g in guidArray) { Debug.Print(g.ToString()); ret = g; } } catch { fRes = false; } return fRes ? MFTestResults.Pass : MFTestResults.Fail; } //--- internal test methods ---// Guid ReturnGuid() { return Guid.NewGuid(); } } } ================================================ FILE: Zelig/Zelig/Test/RunTime/NETMF/mscorlib/systemlib/systemlib2/MicrosoftSpotReflection.cs ================================================ //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // Copyright (c) Microsoft Corporation. All rights reserved. //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// using System; using System.Reflection; using Microsoft.SPOT.Platform.Test; using System.Collections; using Microsoft.SPOT; namespace Microsoft.SPOT.Platform.Tests { public class MicrosoftSpotReflectionTests : IMFTestInterface { [SetUp] public InitializeResult Initialize() { Log.Comment("Adding set up for the tests."); // Add your functionality here. Log.Comment("Testing the Microsoft.SPOT.Reflection class..."); return InitializeResult.ReadyToGo; } [TearDown] public void CleanUp() { Log.Comment("Cleaning up after the tests"); } [TestMethod] public MFTestResults MicrosoftSpotReflection_GetTypesImplementingInterfaces_Test0() { bool fRes = true; /// /// GetTypesImplementingInterface uses reflection to get all types implementing a certain /// interface. /// Type[] typs = Reflection.GetTypesImplementingInterface(typeof(ITestReflectionInterface)); fRes &= typs.Length == 4; foreach (Type t in typs) { fRes &= t.Assembly.FullName == typeof(MicrosoftSpotReflectionTests).Assembly.FullName; } return fRes ? MFTestResults.Pass : MFTestResults.Fail; } [TestMethod] public MFTestResults MicrosoftSpotReflection_IsTypeLoaded_Test1() { bool fRes = true; /// /// IsTypeLoaded was originally used for over the air transmition of /// types/assemblies. It can not really be tested properly without /// sending an unloaded serialized type from the PC. But we will make /// sure that it can recognize loaded types and doesn't cause exceptions. /// fRes &= Reflection.IsTypeLoaded(typeof(System.Int32)); fRes &= Reflection.IsTypeLoaded(typeof(TestClass1)); return fRes ? MFTestResults.Pass : MFTestResults.Fail; } [TestMethod] public MFTestResults MicrosoftSpotReflection_Hashes_Test2() { bool fRes = true; /// /// This is a basic check to assure the GetxxxHash and GetxxxFromHash /// work properly after boxing the reflection types. This is not intended /// to validate the hash value for uniqueness. /// Assembly asm = typeof(int).Assembly; uint hash = Reflection.GetAssemblyHash(asm); fRes &= asm == Reflection.GetAssemblyFromHash(hash); hash = Reflection.GetTypeHash(typeof(TestClass1)); fRes &= typeof(TestClass1) == Reflection.GetTypeFromHash(hash); return fRes ? MFTestResults.Pass : MFTestResults.Fail; } [TestMethod] public MFTestResults MicrosoftSpotReflection_Assemblies_Test3() { bool fRes = true; /// /// Basic testing Reflection.GetAssemblies and GetAssemblyMemoryInfo. This test /// is only intended to assure these methods return propery types and do /// not crash. It is not intended to check for complete correctness. /// Assembly[] asms = Reflection.GetAssemblies(); bool fThisAsmFound = false; foreach (Assembly a in asms) { // Make sure we find our assembly in the list if (a == typeof(MicrosoftSpotReflectionTests).Assembly) { fThisAsmFound = true; } Reflection.AssemblyMemoryInfo mi = new Reflection.AssemblyMemoryInfo(); // Get the memory info for the assembly and get a property to make sure // the value returned is accessible. if (Reflection.GetAssemblyMemoryInfo(a, mi)) { fRes &= (mi.RamSize > 0); } else { fRes = false; } } fRes &= fThisAsmFound; return fRes ? MFTestResults.Pass : MFTestResults.Fail; } //----- classes/Intefaces used by these tests -----// public class TestClass1 : ITestReflectionInterface { } public class TestSubclass : TestClass1 { } internal protected class TestSubclass2 : TestSubclass { } } class TestClass2 : ITestReflectionInterface { } interface ITestReflectionInterface { } } ================================================ FILE: Zelig/Zelig/Test/RunTime/NETMF/mscorlib/systemlib/systemlib2/SystemAppDomainTests.cs ================================================ //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // Copyright (c) Microsoft Corporation. All rights reserved. //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// using System; using System.Reflection; using Microsoft.SPOT.Platform.Test; using System.Threading; namespace Microsoft.SPOT.Platform.Tests { public class SystemAppDomainTests : IMFTestInterface { [SetUp] public InitializeResult Initialize() { Log.Comment("Adding set up for the tests"); string szAssm = typeof(SystemAppDomainTests).Assembly.FullName; m_appDomain = AppDomain.CreateDomain(this.GetType().FullName); m_appDomain.Load(szAssm); m_mbroProxy = (MyMarshalByRefObject)m_appDomain.CreateInstanceAndUnwrap(szAssm, typeof(MyMarshalByRefObject).FullName); m_mbro = new MyMarshalByRefObject(); return InitializeResult.ReadyToGo; } [TearDown] public void CleanUp() { Log.Comment("Cleaning up after the tests"); if (m_appDomain != null) { AppDomain.Unload(m_appDomain); m_appDomain = null; m_mbro = null; m_mbroProxy = null; Debug.GC(true); } } [TestMethod] public MFTestResults AppDomain_Test1() { /// /// 1. Creates an AppDomain /// 2. Calls SomeMethod in it /// 3. Unloads that domain /// 4. Calls SomeMethod again /// 21291 Calling a method in an unloaded app domain should throw an exception. /// MFTestResults testResult = MFTestResults.Pass; Log.Comment("Get and display the friendly name of the default AppDomain."); string callingDomainName = Thread.GetDomain().FriendlyName; if (callingDomainName != AppDomain.CurrentDomain.FriendlyName) { Log.Comment("Failure : Expected '" + AppDomain.CurrentDomain.FriendlyName + "' but got '" + callingDomainName + "'"); testResult = MFTestResults.Fail; } Log.Comment(callingDomainName); Type Type1 = this.GetType(); string exeAssembly = Assembly.GetAssembly(Type1).FullName; Log.Comment("1. Creates an AppDomain"); AppDomain ad2 = AppDomain.CreateDomain("AppDomain #2"); TestMarshalByRefType mbrt = (TestMarshalByRefType)ad2.CreateInstanceAndUnwrap( exeAssembly, typeof(TestMarshalByRefType).FullName); Assembly asm4 = ad2.Load(ad2.GetAssemblies()[0].FullName); if (asm4.FullName != ad2.GetAssemblies()[0].FullName) { testResult = MFTestResults.Fail; } Log.Comment("2. Calls SomeMethod in it"); mbrt.SomeMethod(callingDomainName); Log.Comment("3. Unloads that domain:"); AppDomain.Unload(ad2); try { Log.Comment("4. calls SomeMethod again"); mbrt.SomeMethod(callingDomainName); Log.Comment("Sucessful call."); testResult = MFTestResults.Fail; } catch (AppDomainUnloadedException e) { Log.Comment("Specific Catch; this is expected. " + e.Message); } catch (Exception e) { Log.Comment("Generic Catch; this is bad. " + e.Message); testResult = MFTestResults.Fail; } return testResult; } [TestMethod] public MFTestResults AppDomain_Test2() { MFTestResults testResult = MFTestResults.Pass; try { Log.Comment("Get and display the friendly name of the default AppDomain."); string callingDomainName = Thread.GetDomain().FriendlyName; Type Type1 = this.GetType(); string exeAssembly = Assembly.GetAssembly(Type1).FullName; Log.Comment("1. Creates an AppDomain"); AppDomain ad2 = AppDomain.CreateDomain("AppDomain #3"); TestMarshalByRefType mbrt = (TestMarshalByRefType)ad2.CreateInstanceAndUnwrap( exeAssembly, typeof(TestMarshalByRefType).FullName); ad2.Load(ad2.GetAssemblies()[0].FullName); Log.Comment("2. Calls SomeMethod in it"); mbrt.SomeMethod(callingDomainName); Log.Comment("3. Unloads that domain:"); AppDomain.Unload(ad2); Log.Comment("4. Reload AppDomain with same friendly name"); ad2 = AppDomain.CreateDomain("AppDomain #3"); mbrt = (TestMarshalByRefType)ad2.CreateInstanceAndUnwrap( exeAssembly, typeof(TestMarshalByRefType).FullName); ad2.Load(ad2.GetAssemblies()[0].FullName); Log.Comment("5. Calls SomeMethod in it"); mbrt.SomeMethod(callingDomainName); Log.Comment("6. Unloads that domain:"); AppDomain.Unload(ad2); } catch (Exception e) { Log.Comment("Generic Catch; this is bad. " + e.Message); testResult = MFTestResults.Fail; } return testResult; } [TestMethod] public MFTestResults MarshalInt_Test2() { MFTestResults testResult = MFTestResults.Pass; int i = 123; int result = m_mbroProxy.MarhsalInt(i); if (result != i) { Log.Comment("Failure : Expected '" + i + "' but got '" + result + "'"); testResult = MFTestResults.Fail; } return testResult; } [TestMethod] public MFTestResults MarshalIntByRef_Test3() { MFTestResults testResult = MFTestResults.Pass; int i = 123; int i2 = 456; m_mbroProxy.MarshalIntByRef(ref i, i2); if (i != i2) { Log.Comment("Failure : Expected '" + i2 + "' but got '" + i + "'"); testResult = MFTestResults.Fail; } return testResult; } [TestMethod] public MFTestResults MarshalIntArrayByRef_Test4() { MFTestResults testResult = MFTestResults.Pass; int[] i = new int[] { 123 }; int i2 = 456; m_mbroProxy.MarshalIntByRef(ref i[0], i2); if (i[0] != i2) { Log.Comment("Failure : Expected '" + i2 + "' but got '" + i[0] + "'"); testResult = MFTestResults.Fail; } return testResult; } [TestMethod] public MFTestResults MarshalDouble_Test5() { MFTestResults testResult = MFTestResults.Pass; double d = 123.456; double d2 = m_mbroProxy.MarhsalDouble(d); if (d2 != d) { Log.Comment("Failure : Expected '" + d + "' but got '" + d2 + "'"); testResult = MFTestResults.Fail; } return testResult; } [TestMethod] public MFTestResults MarshalDoubleByRef_Test6() { MFTestResults testResult = MFTestResults.Pass; double d = 123.0; double d2 = 456.0; m_mbroProxy.MarshalDoubleByRef(ref d, d2); if (d != d2) { Log.Comment("Failure : Expected '" + d2 + "' but got '" + d + "'"); testResult = MFTestResults.Fail; } return testResult; } [TestMethod] public MFTestResults MarshalDateTime_Test7() { MFTestResults testResult = MFTestResults.Pass; DateTime dt = new DateTime(1976, 3, 4); DateTime dt2 = m_mbroProxy.MarshalDateTime(dt); if (dt != dt2) { Log.Comment("Failure : Expected '" + dt2 + "' but got '" + dt + "'"); testResult = MFTestResults.Fail; } return testResult; } [TestMethod] public MFTestResults MarshalDateTimeByRef_Test8() { MFTestResults testResult = MFTestResults.Pass; DateTime dt = new DateTime(1976, 3, 4); DateTime dt2 = new DateTime(1976, 3, 10); m_mbroProxy.MarshalDateTimeByRef(ref dt, dt2); if (dt != dt2) { Log.Comment("Failure : Expected '" + dt2 + "' but got '" + dt + "'"); testResult = MFTestResults.Fail; } return testResult; } [TestMethod] public MFTestResults MarshalString_Test9() { MFTestResults testResult = MFTestResults.Pass; string s = "hello"; string s2 = m_mbroProxy.MarshalString(s); if (s != s2) { Log.Comment("Failure : Expected '" + s + "' but got '" + s2 + "'"); testResult = MFTestResults.Fail; } return testResult; } [TestMethod] public MFTestResults MarshalStringByRef_Test10() { MFTestResults testResult = MFTestResults.Pass; string s = "hello"; string s2 = "goodbye"; m_mbroProxy.MarshalStringByRef(ref s, s2); if (s != s2) { Log.Comment("Failure : Expected '" + s2 + "' but got '" + s + "'"); testResult = MFTestResults.Fail; } return testResult; } [TestMethod] public MFTestResults TestNull_Test11() { MFTestResults testResult = MFTestResults.Pass; if (!m_mbroProxy.MarshalNull(null)) { Log.Comment("Failure : Marshalling a null obj. is not equal to null"); testResult = MFTestResults.Fail; } return testResult; } [TestMethod] public MFTestResults TestThrow_Test12() { string message = "message"; MFTestResults testResult = MFTestResults.Fail; try { m_mbroProxy.Throw(message); Log.Comment("Failure to throw Exception"); } catch (Exception e) { if (e.Message == message) { testResult = MFTestResults.Pass; } else { Log.Comment("Failure : Expected message '" + message + "' but got '" + e.Message + "'"); } } return testResult; } [TestMethod] public MFTestResults TestNonSerializableClass_Test13() { MFTestResults testResult = MFTestResults.Fail; try { m_mbroProxy.TestNonSerializableClass(new NonSerializableClass()); Log.Comment("Failure to throw Exception"); } catch (Exception) { testResult = MFTestResults.Pass; } return testResult; } [TestMethod] public MFTestResults TestProxyEquality_Test14() { MFTestResults testResult = MFTestResults.Pass; if (!m_mbroProxy.ProxyEquality(m_mbro, m_mbro)) { Log.Comment("Failure : Marshalling the same obj. and comparing failed"); testResult = MFTestResults.Fail; } return testResult; } [TestMethod] public MFTestResults TestProxyDelegate_Test15() { MyMarshalByRefObject.PrintDelegate dlg = new MyMarshalByRefObject.PrintDelegate(m_mbroProxy.Print); dlg("Hello world"); return MFTestResults.Pass; } [TestMethod] public MFTestResults TestProxyMulticastDelegate_Test16() { MyMarshalByRefObject.PrintDelegate dlg = null; dlg = (MyMarshalByRefObject.PrintDelegate)Microsoft.SPOT.WeakDelegate.Combine(dlg, new MyMarshalByRefObject.PrintDelegate(m_mbroProxy.Print)); dlg = (MyMarshalByRefObject.PrintDelegate)Microsoft.SPOT.WeakDelegate.Combine(dlg, new MyMarshalByRefObject.PrintDelegate(m_mbroProxy.Print)); dlg("Goodnight moon"); return MFTestResults.Pass; } [TestMethod] public MFTestResults MarshalMBRO_Test17() { MFTestResults testResult = MFTestResults.Pass; MyMarshalByRefObject mbro = m_mbroProxy.MarshalMBRO(m_mbro); if (mbro != m_mbro) { Log.Comment("Failure : Expected '" + m_mbro + "' but got '" + mbro + "'"); testResult = MFTestResults.Fail; } return testResult; } [TestMethod] public MFTestResults MarshalMBROByRef_Test18() { MFTestResults testResult = MFTestResults.Pass; MyMarshalByRefObject mbro = new MyMarshalByRefObject(); MyMarshalByRefObject mbro2 = new MyMarshalByRefObject(); m_mbroProxy.MarshalMBROByRef(ref mbro, mbro2); if(!Object.ReferenceEquals(mbro, mbro2)) { Log.Comment("Failure : Marshalling Obj. by Reference and comparing Object.ReferenceEquals(mbro, mbro2) failed"); testResult = MFTestResults.Fail; } return testResult; } [TestMethod] public MFTestResults MarshalClass_Test19() { ClassToMarshal c = new ClassToMarshal(123, "hello"); return EqualsButNotSameInstance(c, m_mbroProxy.MarshalClass(c)) ? MFTestResults.Pass : MFTestResults.Fail; } [TestMethod] public MFTestResults MarshalClassByRef_Test20() { ClassToMarshal c = new ClassToMarshal(123, "hello"); ClassToMarshal c2 = new ClassToMarshal(456, "goodbye"); m_mbroProxy.MarshalClassByRef(ref c, c2); return this.EqualsButNotSameInstance(c, c2) ? MFTestResults.Pass : MFTestResults.Fail; } [TestMethod] public MFTestResults MarshalClassArrayByRef_Test21() { ClassToMarshal[] c = new ClassToMarshal[] { new ClassToMarshal(123, "hello") }; ClassToMarshal c2 = new ClassToMarshal(456, "goodbye"); m_mbroProxy.MarshalClassByRef(ref c[0], c2); return this.EqualsButNotSameInstance(c[0], c2) ? MFTestResults.Pass : MFTestResults.Fail; } [TestMethod] public MFTestResults FieldAccess_Test22() { MFTestResults testResult = MFTestResults.Pass; int i = 123; string s = "hello"; m_mbroProxy.m_int = i; m_mbroProxy.m_string = s; if (m_mbroProxy.m_int != i) { Log.Comment("Failure : int acces, expected '" + i + "' but got '" + m_mbroProxy.m_int + "'"); testResult = MFTestResults.Fail; } if (m_mbroProxy.m_string != s) { Log.Comment("Failure : string acces, expected '" + s + "' but got '" + m_mbroProxy.m_string + "'"); testResult = MFTestResults.Fail; } i = 456; s = "goodbye"; FieldInfo fi = m_mbroProxy.GetType().GetField("m_int", BindingFlags.Instance | BindingFlags.Public); fi.SetValue(m_mbroProxy, i); if ((int)fi.GetValue(m_mbroProxy) != i) { Log.Comment("Failure : Reflection int , expected '" + i + "' but got '" + (int)fi.GetValue(m_mbroProxy) + "'"); testResult = MFTestResults.Fail; } fi = m_mbroProxy.GetType().GetField("m_string", BindingFlags.Instance | BindingFlags.Public); fi.SetValue(m_mbroProxy, s); if ((string)fi.GetValue(m_mbroProxy) != s) { Log.Comment("Failure : Reflection string , expected '" + s + "' but got '" + (string)fi.GetValue(m_mbroProxy) + "'"); testResult = MFTestResults.Fail; } return testResult; } [TestMethod] public MFTestResults StartThread_Test23() { m_mbroProxy.StartThread(); return MFTestResults.Pass; } [TestMethod] public MFTestResults MarshalType_Test24() { MFTestResults testResult = MFTestResults.Pass; Type s = typeof(int); Type s2 = typeof(bool); s2 = m_mbroProxy.MarshalType(s); if (s != s2) { Log.Comment("Failure : Expected '" + s2 + "' but got '" + s + "'"); testResult = MFTestResults.Fail; } return testResult; } [TestMethod] public MFTestResults MarshalTypeByRef_Test25() { MFTestResults testResult = MFTestResults.Pass; Type s = typeof(int); Type s2 = typeof(bool); m_mbroProxy.MarshalTypeByRef(ref s, s2); if (s != s2) { Log.Comment("Failure : Expected '" + s2 + "' but got '" + s + "'"); testResult = MFTestResults.Fail; } return testResult; } [TestMethod] public MFTestResults MarshalTypeArray_Test26() { MFTestResults testResult = MFTestResults.Pass; Type[] s = new Type[] { typeof(int), typeof(bool) }; Type[] s2 = null; s2 = m_mbroProxy.MarshalTypeArray(s); if (s2 == null || s2[0] != s[0] || s2[1] != s[1]) { Log.Comment("Failure : Expected '" + s2 + "' but got '" + s + "'"); testResult = MFTestResults.Fail; } return testResult; } [TestMethod] public MFTestResults MarshalAssembly_Test27() { MFTestResults testResult = MFTestResults.Pass; Assembly s = typeof(int).Assembly; Assembly s2 = typeof(MFTestResults).Assembly; s2 = m_mbroProxy.MarshalAssembly(s); if (s.FullName != s2.FullName) { Log.Comment("Failure : Expected '" + s2.FullName + "' but got '" + s.FullName + "'"); testResult = MFTestResults.Fail; } return testResult; } [TestMethod] public MFTestResults MarshalAssemblyByRef_Test28() { MFTestResults testResult = MFTestResults.Pass; Assembly s = typeof(int).Assembly; Assembly s2 = typeof(MFTestResults).Assembly; m_mbroProxy.MarshalAssemblyByRef(ref s, s2); if (s.FullName != s2.FullName) { Log.Comment("Failure : Expected '" + s2.FullName + "' but got '" + s.FullName + "'"); testResult = MFTestResults.Fail; } return testResult; } [TestMethod] public MFTestResults MarshalFieldInfo_Test29() { MFTestResults testResult = MFTestResults.Pass; FieldInfo s = typeof(MyMarshalByRefObject).GetField("m_int"); FieldInfo s2 = typeof(MyMarshalByRefObject).GetFields()[1]; s2 = m_mbroProxy.MarshalFieldInfo(s); if (s.Name != s2.Name) { Log.Comment("Failure : Expected '" + s2.Name + "' but got '" + s.Name + "'"); testResult = MFTestResults.Fail; } return testResult; } [TestMethod] public MFTestResults MarshalFieldInfoByRef_Test30() { MFTestResults testResult = MFTestResults.Pass; FieldInfo s = typeof(MyMarshalByRefObject).GetField("m_int"); FieldInfo s2 = typeof(MyMarshalByRefObject).GetFields()[1]; m_mbroProxy.MarshalFieldInfoByRef(ref s, s2); if (s.Name != s2.Name) { Log.Comment("Failure : Expected '" + s2.Name + "' but got '" + s.Name + "'"); testResult = MFTestResults.Fail; } return testResult; } [TestMethod] public MFTestResults MarshalMethodInfo_Test31() { MFTestResults testResult = MFTestResults.Pass; MethodInfo s = typeof(MyMarshalByRefObject).GetMethod("Print"); MethodInfo s2 = typeof(Array).GetMethods()[0]; s2 = m_mbroProxy.MarshalMethodInfo(s); if (s.Name != s2.Name) { Log.Comment("Failure : Expected '" + s2.Name + "' but got '" + s.Name + "'"); testResult = MFTestResults.Fail; } return testResult; } [TestMethod] public MFTestResults MarshalMethodInfoByRef_Test32() { MFTestResults testResult = MFTestResults.Pass; MethodInfo s = typeof(MyMarshalByRefObject).GetMethod("Print"); MethodInfo s2 = typeof(Array).GetMethods()[0]; m_mbroProxy.MarshalMethodInfoByRef(ref s, s2); if (s.Name != s2.Name) { Log.Comment("Failure : Expected '" + s2.Name + "' but got '" + s.Name + "'"); testResult = MFTestResults.Fail; } return testResult; } [TestMethod] public MFTestResults MarshalConstructorInfo_Test33() { MFTestResults testResult = MFTestResults.Pass; ConstructorInfo s = typeof(MyMarshalByRefObject).GetConstructor(new Type[] {}); ConstructorInfo s2 = typeof(Array).GetConstructor(new Type[] { }); s2 = m_mbroProxy.MarshalConstructorInfo(s); if (s.Name != s2.Name) { Log.Comment("Failure : Expected '" + s2.Name + "' but got '" + s.Name + "'"); testResult = MFTestResults.Fail; } return testResult; } [TestMethod] public MFTestResults MarshalMethodInfoByRef_Test34() { MFTestResults testResult = MFTestResults.Pass; ConstructorInfo s = typeof(MyMarshalByRefObject).GetConstructor(new Type[] { }); ConstructorInfo s2 = typeof(Array).GetConstructor(new Type[] { }); m_mbroProxy.MarshalConstructorInfoByRef(ref s, s2); if (s.Name != s2.Name) { Log.Comment("Failure : Expected '" + s2.Name + "' but got '" + s.Name + "'"); testResult = MFTestResults.Fail; } return testResult; } #region Variables protected AppDomain m_appDomain; protected MyMarshalByRefObject m_mbroProxy; protected MyMarshalByRefObject m_mbro; #endregion Variables #region HelperMethods private bool EqualsButNotSameInstance(object obj1, object obj2) { bool bResult = true; if (!Object.Equals(obj1, obj2)) { Log.Comment("Failure : Object.Equals(obj1, obj2) returned false"); bResult = false; } else if (Object.ReferenceEquals(obj1, obj2)) { Log.Comment("Failure : Object.ReferenceEquals(obj1, obj2) returned true"); bResult = false; } return bResult; } #endregion HelperMethods #region HelperClasses public class TestMarshalByRefType : MarshalByRefObject { /// /// 1. This method is called via a proxy. /// 2. Display the name of the calling AppDomain and the name of the second domain /// public void SomeMethod(string callingDomainName) { Log.Comment("Calling from " + callingDomainName + " to " + Thread.GetDomain().FriendlyName); } } public class MyMarshalByRefObject : MarshalByRefObject { public int m_int; public string m_string; public delegate void PrintDelegate(string text); public void Print(string text) { Debug.Print(text); if (System.Runtime.Remoting.RemotingServices.IsTransparentProxy(this)) { Debug.Print("FAILURE: METHOD CALL ON PROXY OBJECT "); } } public int MarhsalInt(int i) { return i; } public void MarshalIntByRef(ref int i, int i2) { i = i2; } public double MarhsalDouble(double d) { return d; } public void MarshalDoubleByRef(ref double d, double d2) { d = d2; } public string MarshalString(string s) { return s; } public void MarshalStringByRef(ref string s, string s2) { s = s2; } public DateTime MarshalDateTime(DateTime dt) { return dt; } public void MarshalDateTimeByRef(ref DateTime dt, DateTime dt2) { dt = dt2; } public void Throw(string message) { throw new Exception(message); } public bool MarshalNull(object o) { return o == null; } public ClassToMarshal MarshalClass(ClassToMarshal c) { return c; } public void MarshalClassByRef(ref ClassToMarshal c, ClassToMarshal c2) { c = c2; } public void TestNonSerializableClass(NonSerializableClass c) { } public bool ProxyEquality(MyMarshalByRefObject mbro1, MyMarshalByRefObject mbro2) { return mbro1 == mbro2; } public void MarshalDyingProxy(MyMarshalByRefObject mbro) { } public void MarshalDeadProxy(MyMarshalByRefObject mbro) { } public MyMarshalByRefObject MarshalMBRO(MyMarshalByRefObject mbro) { return mbro; } public void MarshalMBROByRef(ref MyMarshalByRefObject mbro, MyMarshalByRefObject mbro2) { mbro = mbro2; } public Type MarshalType(Type t1) { return t1; } public void MarshalTypeByRef(ref Type t1, Type t2) { t1 = t2; } public Type[] MarshalTypeArray(Type[] t1) { return t1; } public void MarshalTypeArrayByRef(ref Type[] t1, Type[] t2) { Array.Copy(t1, t2, t1.Length); } public Assembly MarshalAssembly(Assembly a1) { return a1; } public void MarshalAssemblyByRef(ref Assembly a1, Assembly a2) { a1 = a2; } public FieldInfo MarshalFieldInfo(FieldInfo a1) { return a1; } public void MarshalFieldInfoByRef(ref FieldInfo a1, FieldInfo a2) { a1 = a2; } public MethodInfo MarshalMethodInfo(MethodInfo a1) { return a1; } public void MarshalMethodInfoByRef(ref MethodInfo a1, MethodInfo a2) { a1 = a2; } public ConstructorInfo MarshalConstructorInfo(ConstructorInfo a1) { return a1; } public void MarshalConstructorInfoByRef(ref ConstructorInfo a1, ConstructorInfo a2) { a1 = a2; } public MyMarshalByRefObject CreateMBRO() { return new MyMarshalByRefObject(); } public void StartThread() { Thread th = new Thread(new ThreadStart(ThreadWorker)); th.Start(); } private void ThreadWorker() { try { while (true) ; } catch (Exception) { Debug.Print("ThreadWorker being aborted.."); } } } [Serializable] public class ClassToMarshal { public int m_int; public string m_string; public ClassToMarshal(int i, string s) { m_int = i; m_string = s; } public override bool Equals(object obj) { ClassToMarshal cls = obj as ClassToMarshal; if (cls == null) return false; if (cls.m_int != m_int) return false; if (cls.m_string != m_string) return false; return true; } public override int GetHashCode() { return base.GetHashCode(); } } public class NonSerializableClass { } #endregion HelperClasses } } ================================================ FILE: Zelig/Zelig/Test/RunTime/NETMF/mscorlib/systemlib/systemlib2/SystemDateTimeTests.cs ================================================ //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // Copyright (c) Microsoft Corporation. All rights reserved. //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// using System; using System.Reflection; using Microsoft.SPOT.Platform.Test; using Microsoft.SPOT; namespace Microsoft.SPOT.Platform.Tests { public class SystemDateTimeTests : IMFTestInterface { [SetUp] public InitializeResult Initialize() { Log.Comment("Adding set up for the tests"); return InitializeResult.ReadyToGo; } [TearDown] public void CleanUp() { Log.Comment("Cleaning up after the tests"); } //DateTime Test methods [TestMethod] public MFTestResults DateTime_ConstructorTest1() { /// /// 1. Creates a DateTime /// 2. Verifies that the created object is a DateTime /// MFTestResults testResult = MFTestResults.Pass; try { Log.Comment("Creating new DateTime Object"); DateTime dt = new DateTime(); Log.Comment(dt.ToString()); Type type = dt.GetType(); Log.Comment("Verifying its type"); if (!(type == Type.GetType("System.DateTime"))) { Log.Comment("Expected Type 'System.DateTime' but got '" + type.ToString()); testResult = MFTestResults.Fail; } } catch (Exception ex) { Log.Comment("Caught Unexpected Exception : " + ex.Message); return MFTestResults.Fail; } return testResult; } [TestMethod] public MFTestResults DateTime_ConstructorTest2() { /// /// 1. Creates a DateTime /// 2. Verifies that the created object is a DateTime /// /// MFTestResults testResult = MFTestResults.Pass; try { Log.Comment("Generating 10 random DateTime and Verifying"); for (int i = 0; i < 10; i++) { DateTime dt = GetRandomDateTime(); if (dt.Year != year || dt.Month != month || dt.Day != day || dt.Hour != hour || dt.Minute != minute || dt.Second != second || dt.Millisecond != millisec) { Log.Comment("Expected DateTime '" + month + "/" + day + "/" + year + " " + hour + ":" + minute + ":" + second + ":" + millisec + "' but got '" + dt.Month + "/" + dt.Day + "/" + dt.Year + " " + dt.Hour + ":" + dt.Minute + ":" + dt.Second + ":" + dt.Millisecond + "'"); testResult = MFTestResults.Fail; } Type t = dt.GetType(); if (t != Type.GetType("System.DateTime")) { Log.Comment("Expected Type 'System.DateTime' but got '" + t.ToString() + "'"); testResult = MFTestResults.Fail; } } } catch (Exception ex) { Log.Comment("Caught Unexpected Exception : " + ex.Message); return MFTestResults.Fail; } return testResult; } [TestMethod] public MFTestResults DateTime_ConstructorTest3() { /// /// 1. Creates Minimum and Maximum DateTimes /// 2. Verifies the DateTimes are equal to DateTime.MinValue, DateTime.MaxValue /// /// MFTestResults testResult = MFTestResults.Pass; try { Log.Comment("Creating Minimum DateTime and verifying"); DateTime minDT1 = DateTime.MinValue; DateTime minDT2 = new DateTime(); DateTime minDT3 = new DateTime(0); DateTime minDT4 = new DateTime(1601, 1, 1, 0, 0, 0, 0); if ((DateTime.Compare(minDT1, minDT2) != 0) || (DateTime.Compare(minDT2, minDT3) != 0) || (DateTime.Compare(minDT3, minDT4) != 0)) { Log.Comment("Expected 'DateTime.MinValue' is equal to 'new DateTime()', " + "equal to 'new DateTime(0)', equal to 'new DateTime(1, 1, 1, 0, 0, 0, 0)' but got "); Log.Comment("DateTime.MinValue = '" + minDT1.Ticks + "'ticks,"); Log.Comment(" new DateTime() = '" + minDT2.Ticks + "'ticks,"); Log.Comment("new DateTime(0) = '" + minDT3.Ticks + "'ticks."); testResult = MFTestResults.Fail; } Log.Comment("Creating Maximum DateTime and verifying"); DateTime maxDateTime = new DateTime(441796895990000000); if (!DateTime.MaxValue.Equals(maxDateTime)) { Log.Comment("Expected Ticks '441796895990000000' but got '" + DateTime.MaxValue.Ticks + "'"); testResult = MFTestResults.Fail; } } catch (Exception ex) { Log.Comment("Caught Unexpected Exception : " + ex.Message); return MFTestResults.Fail; } return testResult; } [TestMethod] public MFTestResults DateTime_CompareToTest4() { /// /// 1. Creates random DateTimes /// 2. Verifies that they CompareTo each other /// /// MFTestResults testResult = MFTestResults.Pass; try { Log.Comment("Generating random DateTimes b/n 1000 - 9000"); Log.Comment("comparing eachother with DateTime.CompareTo and verifying"); DateTime dt1 = DateTime_btwn_1801_And_2801(); DateTime dt2 = new DateTime(year, month, day, hour, minute, second, millisec); Log.Comment("Comparing two equal DateTimes"); if (dt1.CompareTo(dt2) != 0) { Log.Comment("Expected " + dt1.ToString() + " .CompareTo( " + dt2.ToString() + " ) returns '0' but got '" + dt1.CompareTo(dt2) + "'"); testResult = MFTestResults.Fail; } Log.Comment("Comparing Unequal DateTimes and Verifying"); dt2 = dt1.Add(new TimeSpan(1)); if (dt1.CompareTo(dt2) >= 0) { Log.Comment("Expected " + dt1.ToString() + " .CompareTo( " + dt2.ToString() + " ) returns '-ve' value but got '" + dt1.CompareTo(dt2) + "'"); testResult = MFTestResults.Fail; } if (dt2.CompareTo(dt1) <= 0) { Log.Comment("Expected " + dt2.ToString() + " .CompareTo( " + dt1.ToString() + " ) returns '+ve' value but got '" + dt2.CompareTo(dt1) + "'"); testResult = MFTestResults.Fail; } } catch (Exception ex) { Log.Comment("Caught Unexpected Exception : " + ex.Message); return MFTestResults.Fail; } return testResult; } [TestMethod] public MFTestResults DateTime_EqualsTest5() { /// /// 1. Creates two DateTimes /// 2. Verifies that they Equals each other /// /// MFTestResults testResult = MFTestResults.Pass; try { Log.Comment("Generating random DateTime"); DateTime dt1 = GetRandomDateTime(); DateTime dt2 = new DateTime(year, month, day, hour, minute, second, millisec); if (!dt1.Equals(dt2)) { Log.Comment("Expected '" + dt1.ToString() + "' Equals '" + dt2.ToString() + "'"); testResult = MFTestResults.Fail; } } catch (Exception ex) { Log.Comment("Caught Unexpected Exception : " + ex.Message); return MFTestResults.Fail; } return testResult; } [TestMethod] public MFTestResults DateTime_ToStringTest6() { /// /// 1. Creates a DateTime /// 2. Verifies that it correctly returns a string from ToString /// /// MFTestResults testResult = MFTestResults.Pass; try { Log.Comment("Generating random DateTime"); DateTime dt = GetRandomDateTime(); int[] intArr = new int[] { dt.Month, dt.Day, dt.Year, dt.Hour, dt.Minute, dt.Second }; string[] strArr = new string[] { "", "", "", "", "", "" }; for (int i = 0; i < intArr.Length; i++) { if (i == 2) { if (intArr[2] < 100) strArr[2] += "00" + intArr[2]; else if (intArr[2] < 1000) strArr[2] += "0" + intArr[2]; else strArr[2] += intArr[2]; } else { if (intArr[i] < 10) { strArr[i] += "0" + intArr[i]; } else strArr[i] += intArr[i]; } } string str = strArr[0] + "/" + strArr[1] + "/" + strArr[2] + " " + strArr[3] + ":" + strArr[4] + ":" + strArr[5]; if (dt.ToString() != str) { Log.Comment("Expected string '" + str + "', but got '" + dt.ToString() + "'"); testResult = MFTestResults.Fail; } } catch (Exception ex) { Log.Comment("Caught Unexpected Exception : " + ex.Message); return MFTestResults.Fail; } return testResult; } [TestMethod] public MFTestResults DateTime_ToStringTest7() { /// /// 1. Creates a DateTime /// 2. Verifies DateTime.ToString (String) returns correct String using a specified format /// /// MFTestResults testResult = MFTestResults.Pass; try { Log.Comment("Generating random DateTime"); DateTime dt = GetRandomDateTime(); Log.Comment("DateTime.ToString(String) using Standard Formats and Verifying"); string[] standardFmts = { "d", "D", "f", "F", "g", "G", "m", "M", "o", "R", "r", "s", "t", "T", "u", "U", "Y", "y" }; foreach (string standardFmt in standardFmts) { try { if (dt.ToString(standardFmt).Length < 1) { Log.Comment("Expected a String length greater than '0' but got '" + dt.ToString(standardFmt).Length + "'"); testResult = MFTestResults.Fail; } } catch (Exception ex) { Log.Comment("This currently fails, DateTime.ToString(String)" + " throws ArgumentException for some string formats, see 22837 for details"); Log.Comment("Caught " + ex.Message + " when Trying DateTime.ToString(" + standardFmt + ")"); testResult = MFTestResults.KnownFailure; } } Log.Comment("DateTime.ToString(String) using Custom Formats and Verifying"); string[] customFmts = {"h:mm:ss.ff t", "d MMM yyyy", "HH:mm:ss.f","dd MMM HH:mm:ss", @"\Mon\t\h\: M", "MM/dd/yyyy", "dddd, dd MMMM yyyy", "MMMM dd", "ddd, dd MMM yyyy HH':'mm':'ss 'GMT'", "yyyy'-'MM'-'dd'T'HH':'mm':'ss", "HH:mm", "yyyy'-'MM'-'dd HH':'mm':'ss'Z'", "yyyy MMMM"}; foreach (string customFmt in customFmts) { try { if (dt.ToString(customFmt).Length < 1) { Log.Comment("Expected a String length greater than '0' but got '" + dt.ToString(customFmt).Length + "'"); testResult = MFTestResults.Fail; } } catch (Exception ex) { Log.Comment("Caught " + ex.Message + " when Trying DateTime.ToString(" + customFmt + ")"); testResult = MFTestResults.KnownFailure; } } } catch (Exception ex) { Log.Comment("Caught Unexpected Exception : " + ex.Message); return MFTestResults.Fail; } return testResult; } [TestMethod] public MFTestResults DateTime_AddTest8() { /// /// 1. Creates a DateTime /// 2. Runs the Add function and verifies output /// /// MFTestResults testResult = MFTestResults.Pass; try { Log.Comment("Generating random DateTimes "); DateTime[] dt1Arr = Get_ArrayOfRandomDateTimes(); TimeSpan ts; Random random = new Random(); for (int i = 0; i < dt1Arr.Length; i++) { DateTime dt1 = dt1Arr[i]; if (i % 2 == 0) { ts = new TimeSpan(-random.Next(1000)); } else { ts = new TimeSpan(random.Next(1000)); } Log.Comment("Adding '" + ts.ToString() + "' Timespan to '" + dt1.ToString() + "'"); DateTime dt2 = dt1.Add(ts); if (dt2.Ticks != (dt1.Ticks + ts.Ticks)) { Log.Comment("Adding Timespan of " + ts.ToString() + " to a DateTime of " + dt1Arr.ToString() + " expected a new DateTime '" + (dt1.Ticks + ts.Ticks) + "' Ticks but got '" + dt2.Ticks + "'"); testResult = MFTestResults.Fail; } } } catch (Exception ex) { Log.Comment("Caught Unexpected Exception : " + ex.Message); return MFTestResults.Fail; } return testResult; } [TestMethod] public MFTestResults DateTime_AddDays_PositiveTest9() { /// /// 1. Creates a DateTime /// 2. Runs the AddDays function and verifies output /// /// MFTestResults testResult = MFTestResults.Pass; try { Log.Comment("Generating random DateTime"); DateTime[] dt1Arr = Get_ArrayOfRandomDateTimes(); Random random = new Random(); Log.Comment("Adding Random +ve Days and verifying"); for (int i = 0; i < dt1Arr.Length; i++) { DateTime dt1 = dt1Arr[i]; double dy = random.Next(1000) * rdmFraction[random.Next(rdmFraction.Length)]; Log.Comment("Adding '" + dy + "' days to '" + dt1.ToString() + "'"); DateTime dt2 = dt1.AddDays(dy); if (!CheckDeviation((long)(dt1.Ticks + (dy * TimeSpan.TicksPerDay)), dt2.Ticks)) { Log.Comment("After Adding +ve day = '" + dy + "' to a DateTime = '" + dt1 + "', expected Ticks = '" + (long)(dt1.Ticks + (dy * TimeSpan.TicksPerDay)) + "' but got Ticks = '" + dt2.Ticks + "'"); testResult = MFTestResults.Fail; } } } catch (Exception ex) { Log.Comment("Caught Unexpected Exception : " + ex.Message); return MFTestResults.Fail; } return testResult; } [TestMethod] public MFTestResults DateTime_AddDays_NegativeTest10() { /// /// 1. Creates a DateTime /// 2. Runs the AddDays function and verifies output /// /// Log.Comment("This is fixed, DateTime.AddXXXX methods do not handle negative"); Log.Comment("values correctly on Device, see 22728 for details"); MFTestResults testResult = MFTestResults.Pass; try { Log.Comment("Generating random DateTime"); DateTime[] dt1Arr = Get_ArrayOfRandomDateTimes(); Random random = new Random(); Log.Comment("Adding Random -ve Days and verifying"); for (int i = 0; i < dt1Arr.Length; i++) { DateTime dt1 = dt1Arr[i]; double dy = -random.Next(1000) * rdmFraction[random.Next(rdmFraction.Length)]; Log.Comment("Adding '" + dy + "' days to '" + dt1.ToString() + "'"); DateTime dt2 = dt1.AddDays(dy); if (!CheckDeviation((long)(dt1.Ticks + (dy * TimeSpan.TicksPerDay)), dt2.Ticks)) { Log.Comment("After Adding -ve day = '" + dy + "' to a DateTime = '" + dt1 + "', expected Ticks = '" + (long)(dt1.Ticks + (dy * TimeSpan.TicksPerDay)) + "' but got Ticks = '" + dt2.Ticks + "'"); testResult = MFTestResults.Fail; } } } catch (Exception ex) { Log.Comment("Caught Unexpected Exception : " + ex.Message); return MFTestResults.Fail; } return testResult; } [TestMethod] public MFTestResults DateTime_AddHours_PositiveTest11() { /// /// 1. Creates a DateTime /// 2. Runs the AddHours function and verifies output /// /// MFTestResults testResult = MFTestResults.Pass; try { Log.Comment("Generating random DateTime"); DateTime[] dt1Arr = Get_ArrayOfRandomDateTimes(); Random random = new Random(); Log.Comment("Adding Random +ve Hours and verifying"); for (int i = 0; i < dt1Arr.Length; i++) { DateTime dt1 = dt1Arr[i]; double hr = random.Next(1000) * rdmFraction[random.Next(rdmFraction.Length)]; Log.Comment("Adding '" + hr + "' hours to '" + dt1.ToString() + "'"); DateTime dt2 = dt1.AddHours(hr); if (!CheckDeviation((long)(dt1.Ticks + (hr * TimeSpan.TicksPerHour)), dt2.Ticks)) { Log.Comment("After Adding +ve hour = '" + hr + "' to a DateTime = '" + dt1 + "', expected Ticks = '" + (long)(dt1.Ticks + (hr * TimeSpan.TicksPerHour)) + "' but got Ticks = '" + dt2.Ticks + "'"); testResult = MFTestResults.Fail; } } } catch (Exception ex) { Log.Comment("Caught Unexpected Exception : " + ex.Message); return MFTestResults.Fail; } return testResult; } [TestMethod] public MFTestResults DateTime_AddHours_NegativeTest12() { /// /// 1. Creates a DateTime /// 2. Runs the AddHours function and verifies output /// /// Log.Comment("This is fixed, DateTime.AddXXXX methods do not handle negative"); Log.Comment("values correctly on Device, see 22728 for details"); MFTestResults testResult = MFTestResults.Pass; try { Log.Comment("Generating random DateTime"); DateTime[] dt1Arr = Get_ArrayOfRandomDateTimes(); Random random = new Random(); Log.Comment("Adding Random -ve Hours and verifying"); for (int i = 0; i < dt1Arr.Length; i++) { DateTime dt1 = dt1Arr[i]; double hr = -random.Next(1000) * rdmFraction[random.Next(rdmFraction.Length)]; Log.Comment("Adding '" + hr + "' hours to '" + dt1.ToString() + "'"); DateTime dt2 = dt1.AddHours(hr); if (!CheckDeviation((long)(dt1.Ticks + (hr * TimeSpan.TicksPerHour)), dt2.Ticks)) { Log.Comment("After Adding -ve hour = '" + hr + "' to a DateTime = '" + dt1 + "', expected Ticks = '" + (long)(dt1.Ticks + (hr * TimeSpan.TicksPerHour)) + "' but got Ticks = '" + dt2.Ticks + "'"); testResult = MFTestResults.Fail; } } } catch (Exception ex) { Log.Comment("Caught Unexpected Exception : " + ex.Message); return MFTestResults.Fail; } return testResult; } [TestMethod] public MFTestResults DateTime_AddMilliseconds_PositiveTest13() { /// /// 1. Creates a DateTime /// 2. Runs the AddMilliseconds function and verifies output /// /// MFTestResults testResult = MFTestResults.Pass; try { Log.Comment("Generating random DateTime"); DateTime[] dt1Arr = Get_ArrayOfRandomDateTimes(); Random random = new Random(); Log.Comment("Adding Random +ve Milliseconds and verifying"); for (int i = 0; i < dt1Arr.Length; i++) { DateTime dt1 = dt1Arr[i]; double msec = random.Next(1000) * rdmFraction[random.Next(rdmFraction.Length)]; Log.Comment("Adding '" + msec + "' milliseconds to '" + dt1.ToString() + "'"); DateTime dt2 = dt1.AddMilliseconds(msec); if (!CheckDeviation((long)(dt1.Ticks + (msec * TimeSpan.TicksPerMillisecond)), dt2.Ticks)) { Log.Comment("After Adding +ve milliseconds = '" + msec + "' to a DateTime = '" + dt1 + "', expected Ticks = '" + (long)(dt1.Ticks + (msec * TimeSpan.TicksPerMillisecond)) + "' but got Ticks = '" + dt2.Ticks + "'"); testResult = MFTestResults.Fail; } } } catch (Exception ex) { Log.Comment("Caught Unexpected Exception : " + ex.Message); return MFTestResults.Fail; } return testResult; } [TestMethod] public MFTestResults DateTime_AddMilliseconds_NegativeTest14() { /// /// 1. Creates a DateTime /// 2. Runs the AddMilliseconds function and verifies output /// /// Log.Comment("This is fixed, DateTime.AddXXXX methods do not handle negative"); Log.Comment("values correctly on Device, see 22728 for details"); MFTestResults testResult = MFTestResults.Pass; try { Log.Comment("Generating random DateTime"); DateTime[] dt1Arr = Get_ArrayOfRandomDateTimes(); Random random = new Random(); Log.Comment("Adding Random -ve Milliseconds and verifying"); for (int i = 0; i < dt1Arr.Length; i++) { DateTime dt1 = dt1Arr[i]; double msec = -random.Next(1000) * rdmFraction[random.Next(rdmFraction.Length)]; Log.Comment("Adding '" + msec + "' milliseconds to '" + dt1.ToString() + "'"); DateTime dt2 = dt1.AddMilliseconds(msec); if (!CheckDeviation((long)(dt1.Ticks + (msec * TimeSpan.TicksPerMillisecond)), dt2.Ticks)) { Log.Comment("After Adding -ve milliseconds = '" + msec + "' to a DateTime = '" + dt1 + "', expected Ticks = '" + (long)(dt1.Ticks + (msec * TimeSpan.TicksPerMillisecond)) + "' but got Ticks = '" + dt2.Ticks + "'"); testResult = MFTestResults.Fail; } } } catch (Exception ex) { Log.Comment("Caught Unexpected Exception : " + ex.Message); return MFTestResults.Fail; } return testResult; } [TestMethod] public MFTestResults DateTime_AddMinutes_PositiveTest15() { /// /// 1. Creates a DateTime /// 2. Runs the AddMinutes function and verifies output /// /// MFTestResults testResult = MFTestResults.Pass; try { Log.Comment("Generating random DateTime"); DateTime[] dt1Arr = Get_ArrayOfRandomDateTimes(); Random random = new Random(); Log.Comment("Adding Random +ve Minutes and verifying"); for (int i = 0; i < dt1Arr.Length; i++) { DateTime dt1 = dt1Arr[i]; double mnts = random.Next(1000) * rdmFraction[random.Next(rdmFraction.Length)]; Log.Comment("Adding '" + mnts + "' minutes to '" + dt1.ToString() + "'"); DateTime dt2 = dt1.AddMinutes(mnts); if (!CheckDeviation((long)(dt1.Ticks + (mnts * TimeSpan.TicksPerMinute)), dt2.Ticks)) { Log.Comment("After Adding +ve minute = '" + mnts + "' to a DateTime = '" + dt1 + "', expected Ticks = '" + (long)(dt1.Ticks + (mnts * TimeSpan.TicksPerMinute)) + "' but got Ticks = '" + dt2.Ticks + "'"); testResult = MFTestResults.Fail; } } } catch (Exception ex) { Log.Comment("Caught Unexpected Exception : " + ex.Message); return MFTestResults.Fail; } return testResult; } [TestMethod] public MFTestResults DateTime_AddMinutes_NegativeTest16() { /// /// 1. Creates a DateTime /// 2. Runs the AddMinutes function and verifies output /// /// Log.Comment("This is fixed, DateTime.AddXXXX methods do not handle negative"); Log.Comment("values correctly on Device, see 22728 for details"); MFTestResults testResult = MFTestResults.Pass; try { Log.Comment("Generating random DateTime"); DateTime[] dt1Arr = Get_ArrayOfRandomDateTimes(); Random random = new Random(); Log.Comment("Adding Random -ve Minutes and verifying"); for (int i = 0; i < dt1Arr.Length; i++) { DateTime dt1 = dt1Arr[i]; double mnts = -random.Next(1000) * rdmFraction[random.Next(rdmFraction.Length)]; Log.Comment("Adding '" + mnts + "' minutes to '" + dt1.ToString() + "'"); DateTime dt2 = dt1.AddMinutes(mnts); if (!CheckDeviation((long)(dt1.Ticks + (mnts * TimeSpan.TicksPerMinute)), dt2.Ticks)) { Log.Comment("After Adding -ve minute = '" + mnts + "' to a DateTime = '" + dt1 + "', expected Ticks = '" + (long)(dt1.Ticks + mnts * TimeSpan.TicksPerMinute) + "' but got Ticks = '" + dt2.Ticks + "'"); testResult = MFTestResults.Fail; } } } catch (Exception ex) { Log.Comment("Caught Unexpected Exception : " + ex.Message); return MFTestResults.Fail; } return testResult; } [TestMethod] public MFTestResults DateTime_AddMonths_Test17() { /// /// 1. NYI: Returns None /// /// Log.Comment("DateTime::AddMonths - Normal "); Log.Comment("Not implemented yet."); return MFTestResults.Skip; } [TestMethod] public MFTestResults DateTime_AddSeconds_PositiveTest18() { /// /// 1. Creates a DateTime /// 2. Runs the AddSeconds function and verifies output /// /// MFTestResults testResult = MFTestResults.Pass; try { Log.Comment("Generating random DateTime"); DateTime[] dt1Arr = Get_ArrayOfRandomDateTimes(); Random random = new Random(); Log.Comment("Adding Random +ve Seconds and verifying"); for (int i = 0; i < dt1Arr.Length; i++) { DateTime dt1 = dt1Arr[i]; double sec = random.Next(1000) * rdmFraction[random.Next(rdmFraction.Length)]; Log.Comment("Adding '" + sec + "' seconds to '" + dt1.ToString() + "'"); DateTime dt2 = dt1.AddSeconds(sec); if (!CheckDeviation((long)(dt1.Ticks + (sec * TimeSpan.TicksPerSecond)), dt2.Ticks)) { Log.Comment("After Adding +ve seconds = '" + sec + "' to a DateTime = '" + dt1 + "', expected Ticks = '" + (long)(dt1.Ticks + (sec * TimeSpan.TicksPerSecond)) + "' but got Ticks = '" + dt2.Ticks + "'"); testResult = MFTestResults.Fail; } } } catch (Exception ex) { Log.Comment("Caught Unexpected Exception : " + ex.Message); return MFTestResults.Fail; } return testResult; } [TestMethod] public MFTestResults DateTime_AddSeconds_NegativeTest19() { /// /// 1. Creates a DateTime /// 2. Runs the AddSeconds function and verifies output /// /// Log.Comment("This is fixed, DateTime.AddXXXX methods do not handle negative"); Log.Comment("values correctly on Device, see 22728 for details"); MFTestResults testResult = MFTestResults.Pass; try { Log.Comment("Generating random DateTime"); DateTime[] dt1Arr = Get_ArrayOfRandomDateTimes(); Random random = new Random(); Log.Comment("Adding Random -ve Seconds and verifying"); for (int i = 0; i < dt1Arr.Length; i++) { DateTime dt1 = dt1Arr[i]; double sec = -random.Next(1000) * rdmFraction[random.Next(rdmFraction.Length)]; Log.Comment("Adding '" + sec + "' seconds to '" + dt1.ToString() + "'"); DateTime dt2 = dt1.AddSeconds(sec); if (!CheckDeviation((long)(dt1.Ticks + (sec * TimeSpan.TicksPerSecond)), dt2.Ticks)) { Log.Comment("After Adding -ve seconds = '" + sec + "' to a DateTime = '" + dt1 + "', expected Ticks = '" + (long)(dt1.Ticks + sec * TimeSpan.TicksPerSecond) + "' but got Ticks = '" + dt2.Ticks + "'"); testResult = MFTestResults.Fail; } } } catch (Exception ex) { Log.Comment("Caught Unexpected Exception : " + ex.Message); return MFTestResults.Fail; } return testResult; } [TestMethod] public MFTestResults DateTime_AddTicks_PositiveTest20() { /// /// 1. Creates a DateTime /// 2. Runs the AddTicks function and verifies output /// /// MFTestResults testResult = MFTestResults.Pass; Log.Comment("Generating random DateTime"); try { DateTime[] dt1Arr = Get_ArrayOfRandomDateTimes(); Random random = new Random(); Log.Comment("Adding Random +ve Ticks and verifying"); for (int i = 0; i < dt1Arr.Length; i++) { DateTime dt1 = dt1Arr[i]; long ticks = (long)random.Next(1000); Log.Comment("Adding '" + ticks + "' ticks to '" + dt1.ToString() + "'"); DateTime dt2 = dt1.AddTicks(ticks); if (dt2.Ticks != (dt1.Ticks + ticks)) { Log.Comment("After Adding +ve ticks = '" + ticks + "' to a DateTime = '" + dt1 + "', expected Ticks = '" + (dt1.Ticks + ticks) + "' but got Ticks = '" + dt2.Ticks + "'"); testResult = MFTestResults.Fail; } } } catch (Exception ex) { Log.Comment("Caught Unexpected Exception : " + ex.Message); return MFTestResults.Fail; } return testResult; } [TestMethod] public MFTestResults DateTime_AddTicks_NegativeTest21() { /// /// 1. Creates a DateTime /// 2. Runs the AddTicks function and verifies output /// /// MFTestResults testResult = MFTestResults.Pass; try { Log.Comment("Generating random DateTime"); DateTime[] dt1Arr = Get_ArrayOfRandomDateTimes(); Random random = new Random(); Log.Comment("Adding Random -ve Ticks and verifying"); for (int i = 0; i < 10; i++) { DateTime dt1 = dt1Arr[i]; long ticks = -(long)random.Next(1000); Log.Comment("Adding '" + ticks + "' ticks to '" + dt1.ToString() + "'"); DateTime dt2 = dt1.AddTicks(ticks); if (dt2.Ticks != (dt1.Ticks + ticks)) { Log.Comment("After Adding -ve ticks = '" + ticks + "' to a DateTime = '" + dt1 + "', expected Ticks = '" + (dt1.Ticks + ticks) + "' but got Ticks = '" + dt2.Ticks + "'"); testResult = MFTestResults.Fail; } } } catch (Exception ex) { Log.Comment("Caught Unexpected Exception : " + ex.Message); return MFTestResults.Fail; } return testResult; } [TestMethod] public MFTestResults DateTime_AddYears_Test22() { /// /// 1. NYI: Returns None /// /// Log.Comment("DateTime::AddYears - Normal "); Log.Comment("Not implemented yet."); return MFTestResults.Skip; } [TestMethod] public MFTestResults DateTime_Compare_Test23() { /// /// 1. Creates two DateTimes /// 2. Verifies that they Compare with each other /// /// MFTestResults testResult = MFTestResults.Pass; try { Log.Comment("Creating two Random but equal DateTime b/n 1000 - 9000"); Log.Comment("Comparing eachother with DateTime.Compare and Verifying"); DateTime dt1 = DateTime_btwn_1801_And_2801(); DateTime dt2 = new DateTime(year, month, day, hour, minute, second, millisec); Log.Comment("Comparing equal DateTimes and Verifying"); if (DateTime.Compare(dt1, dt2) != 0) { Log.Comment("Expected DateTime.Compare(" + dt1.ToString() + ", " + dt2.ToString() + ") returns '0' but got '" + DateTime.Compare(dt1, dt2) + "'"); testResult = MFTestResults.Fail; } Log.Comment("Comparing Unequal DateTimes and Verifying"); dt2 = dt1.Add(new TimeSpan(1)); if (DateTime.Compare(dt1, dt2) >= 0) { Log.Comment("Expected DateTime.Compare(" + dt1.ToString() + ", " + dt2.ToString() + ") returns '-ve' value but got '" + DateTime.Compare(dt1, dt2) + "'"); testResult = MFTestResults.Fail; } if (DateTime.Compare(dt2, dt1) <= 0) { Log.Comment("Expected DateTime.CompareTo(" + dt1.ToString() + ", " + dt2.ToString() + ") returns '+ve' value but got '" + DateTime.Compare(dt1, dt2) + "'"); testResult = MFTestResults.Fail; } } catch (Exception ex) { Log.Comment("Caught Unexpected Exception : " + ex.Message); return MFTestResults.Fail; } return testResult; } [TestMethod] public MFTestResults DateTime_DaysInMonth_Test24() { /// /// 1. Verifies the accuracy of the DaysInMonth method /// /// MFTestResults testResult = MFTestResults.Pass; try { Log.Comment("Generates a random year and month, and"); Random random = new Random(); Log.Comment("Verifies the number of days in the specific month/year"); for (int i = 0; i < 100; i++) { int yr = random.Next(9999) + 1; int mnth = random.Next(12) + 1; if (DaysInMonthTest(yr, mnth) != MFTestResults.Pass) { Log.Comment("Failure : verifying no. of days in mm/yr = '" + mnth + "/" + yr + "'"); testResult = MFTestResults.Fail; } } Log.Comment("Verifying no. of days in Feb, for 20th and 21st centuries"); for (int yr = 1900; yr < 2100; yr += 4) { if (DaysInMonthTest(yr, 2) != MFTestResults.Pass) { Log.Comment("Failure : verifying no. of days in mm/yr = '02/" + yr + "'"); testResult = MFTestResults.Fail; } } } catch (Exception ex) { Log.Comment("Caught Unexpected Exception : " + ex.Message); return MFTestResults.Fail; } return testResult; } [TestMethod] public MFTestResults DateTime_EqualsTest25() { MFTestResults testResult = MFTestResults.Pass; try { Log.Comment("Creating random-equal DateTimes"); Log.Comment("And Verifying they are equal"); DateTime dt1 = DateTime_btwn_1801_And_2801(); DateTime dt2 = new DateTime(year, month, day, hour, minute, second, millisec); if (!DateTime.Equals(dt1, dt2)) { Log.Comment("DateTime.Equals('" + dt1.ToString() + "'" + ",'" + dt2.ToString() + "'' returned false"); testResult = MFTestResults.Fail; } object obj1 = (object)dt1, obj2 = (object)dt2; try { if (!object.Equals(obj1, obj2)) { Log.Comment("DateTime.Equals('(object)" + dt1.ToString() + "'" + ",'(object)" + dt2.ToString() + "'' returned false"); testResult = MFTestResults.Fail; } } catch (Exception) { }; if (!dt1.Equals(obj2)) { Log.Comment("'" + dt1.ToString() + "'.Equals('" + dt2.ToString() + "'' returned false"); testResult = MFTestResults.Fail; } } catch (Exception ex) { Log.Comment("Caught Unexpected Exception : " + ex.Message); return MFTestResults.Fail; } return testResult; } [TestMethod] public MFTestResults DateTime_Subtract_DateTimeTest26() { Log.Comment("Creating two Random DateTimes,"); Log.Comment("dt1.Subtract(dt2) and verifying"); MFTestResults testResult = MFTestResults.Pass; try { DateTime dt1 = GetRandomDateTime(); DateTime dt2 = GetRandomDateTime(); TimeSpan ts1 = dt1.Subtract(dt2); TimeSpan ts2 = new TimeSpan(dt1.Ticks - dt2.Ticks); if (ts1 != ts2) { Log.Comment("Failure : dt1.Subtract(dt2), expected result '" + ts2.ToString() + "' but got '" + ts1.ToString() + "'"); testResult = MFTestResults.Fail; } } catch (Exception ex) { Log.Comment("Caught Unexpected Exception : " + ex.Message); return MFTestResults.Fail; } return testResult; } [TestMethod] public MFTestResults DateTime_Subtract_TimeSpanTest27() { Log.Comment("Creating now DateTime"); Log.Comment("Subtracting random timespans and "); MFTestResults testResult = MFTestResults.Pass; try { DateTime[] dtArr = Get_ArrayOfRandomDateTimes(); Random random = new Random(); TimeSpan ts; for (int i = 0; i < dtArr.Length; i++) { DateTime dt1 = dtArr[i]; if (i % 2 == 0) { ts = new TimeSpan(-random.Next(1000)); } else { ts = -new TimeSpan(random.Next(1000)); } Log.Comment(dt1.ToString()); Log.Comment(ts.ToString()); DateTime dt2 = dt1.Subtract(ts); Log.Comment(dt2.ToString()); DateTime dt3 = new DateTime(dt1.Ticks - ts.Ticks); Log.Comment(dt3.ToString()); if (DateTime.Compare(dt2, dt3) != 0) { Log.Comment("Failure : subtracting '" + ts.ToString() + "' from a DateTime = '" + dt1.ToString() + "', expected DateTime = '" + dt3.ToString() + "' but got '" + dt2.ToString() + "'"); testResult = MFTestResults.Fail; } } } catch (Exception ex) { Log.Comment("Caught Unexpected Exception : " + ex.ToString()); return MFTestResults.Fail; } return testResult; } [TestMethod] public MFTestResults DateTime_ToLocalTimeTest28() { /// /// 1. Calls DateTime.ToLocalTime /// 2. Verifies the output /// ///21293 ToLocalTime Fails with incorrect offset MFTestResults testResult = MFTestResults.Pass; try { Log.Comment("Creating Local Now DateTime"); System.DateTime test0 = new System.DateTime(DateTime.Now.Ticks); Log.Comment("Calling ToLocalTime and verifying"); System.DateTime testDateTime = test0.ToLocalTime(); // 1. Time is still the same: if (testDateTime != test0) { Log.Comment("Failure: it's already local DateTime hence the 'Kind' should be same"); testResult = MFTestResults.Fail; } if (testDateTime.Ticks != test0.Ticks) { Log.Comment("Failure : ticks not same"); testResult = MFTestResults.Fail; } // 3. Both times are local. if ((testDateTime.Kind != DateTimeKind.Local) || (test0.Kind != DateTimeKind.Local)) { Log.Comment("Failure : expected both DateTimeKind = '" + DateTimeKind.Local + "' but got new(DateTime.Now) = '" + testDateTime.Kind.ToString() + "' and new(DateTime.Now).ToLocalTime()'" + test0.Kind.ToString() + "'"); testResult = MFTestResults.Fail; } Log.Comment("Setting to UTC time"); test0 = DateTime.SpecifyKind(test0, DateTimeKind.Utc); Log.Comment("Converting now UTC time to local and verifying"); testDateTime = test0.ToLocalTime(); Log.Comment("Verifying Time now different"); if (testDateTime == test0 && TimeZone.CurrentTimeZone.GetUtcOffset(testDateTime).Ticks != 0) { Log.Comment("Failure : expected different time but got equal '" + test0 + "'"); testResult = MFTestResults.Fail; } Log.Comment("Verifying change in tick due to conversion since we are not in zero time zone"); long diff1 = testDateTime.Ticks - test0.Ticks; long diff2 = TimeZone.CurrentTimeZone.GetUtcOffset(testDateTime).Ticks; long diff3 = TimeZone.CurrentTimeZone.GetUtcOffset(test0).Ticks; if ((diff1 != diff2) || (0 != diff3)) { Log.Comment("Failure : expected timezone difference in ticks = '" + diff2.ToString() + "(" + diff3.ToString() + ")' but got '" + diff1.ToString() + "'"); testResult = MFTestResults.Fail; } Log.Comment("Verifying converted DateTime is UTC, local DateTime is local"); if ((testDateTime.Kind != DateTimeKind.Local) || (test0.Kind != DateTimeKind.Utc)) { Log.Comment("expected converted DateTime kind '" + DateTimeKind.Utc + "' but got '" + testDateTime.Kind + "'"); Log.Comment("expected local DateTime kind '" + DateTimeKind.Local + "' but got '" + test0.Kind + "'"); testResult = MFTestResults.Fail; } } catch (Exception ex) { Log.Comment("Caught Unexpected Exception : " + ex.Message); return MFTestResults.Fail; } return testResult; } [TestMethod] public MFTestResults DateTime_ToUniversalTimeTest29() { /// /// 1. Calls DateTime.ToUniversalTime /// 2. Verifies the output /// ///21294 ToUniversalTime fails with incorrect time. MFTestResults testResult = MFTestResults.Pass; try { Log.Comment("Creating Now DateTime"); DateTime test0 = new DateTime(DateTime.Now.Ticks); Log.Comment("creating another DateTime by calling ToUniversalTime"); DateTime testDateTime = test0.ToUniversalTime(); if (testDateTime == test0 && TimeZone.CurrentTimeZone.GetUtcOffset(test0).Ticks != 0) { Log.Comment("Failure : expected Time now different because we compare times in different zone"); testResult = MFTestResults.Fail; } Log.Comment("Tick do change due to conversion since we are not in zero time zone"); long diff1 = test0.Ticks - testDateTime.Ticks; long diff2 = TimeZone.CurrentTimeZone.GetUtcOffset(testDateTime).Ticks; long diff3 = TimeZone.CurrentTimeZone.GetUtcOffset(test0).Ticks; if ((diff1 != diff3) || (diff2 != 0)) { Log.Comment("Failure : expected timezone difference in ticks = '" + diff2.ToString() + "(" + diff3.ToString() + ")' but got '" + diff1.ToString() + "'"); testResult = MFTestResults.Fail; } Log.Comment("Verifying DateTime Kind's to be local,to be UTC"); if ((testDateTime.Kind != DateTimeKind.Utc) || (test0.Kind != DateTimeKind.Local)) { Log.Comment("expected converted DateTime kind '" + DateTimeKind.Utc + "' but got '" + testDateTime.Kind + "'"); Log.Comment("expected local DateTime kind '" + DateTimeKind.Local + "' but got '" + test0.Kind + "'"); testResult = MFTestResults.Fail; } Log.Comment("Setting new(DateTime.Now) to UTC time and verifying"); test0 = DateTime.SpecifyKind(test0, DateTimeKind.Utc); Log.Comment("Converting now UTC time to UTC - no change."); testDateTime = test0.ToUniversalTime(); if (testDateTime != test0) { Log.Comment("Failure : expected '" + testDateTime.ToString() + "' but got '" + test0.ToString() + "'"); testResult = MFTestResults.Fail; } Log.Comment("Comparing ticks and verifying"); if (testDateTime.Ticks != test0.Ticks) { Log.Comment("Failure : expected ticks '" + testDateTime.Ticks + "' but got '" + test0.Ticks + "'"); testResult = MFTestResults.Fail; } Log.Comment("Verifying Both times are Utc"); if ((testDateTime.Kind != DateTimeKind.Utc) || (test0.Kind != DateTimeKind.Utc)) { Log.Comment("expected converted DateTime kind '" + DateTimeKind.Utc + "' but got '" + testDateTime.Kind + "'"); Log.Comment("expected UTC setted DateTime kind '" + DateTimeKind.Utc + "' but got '" + test0.Kind + "'"); testResult = MFTestResults.Fail; } } catch (Exception ex) { Log.Comment("Caught Unexpected Exception : " + ex.Message); return MFTestResults.Fail; } return testResult; } [TestMethod] public MFTestResults DateTime_op_AdditionTest30() { Log.Comment("Creating Random DateTimes,"); Log.Comment("Adds a specified period of time and verifying"); MFTestResults testResult = MFTestResults.Pass; try { DateTime[] dtArr = Get_ArrayOfRandomDateTimes(); Random random = new Random(); TimeSpan ts; for (int i = 0; i < dtArr.Length; i++) { DateTime dt1 = dtArr[i]; if (i % 2 == 0) { ts = new TimeSpan(-random.Next(1000)); } else { ts = new TimeSpan(random.Next(1000)); } DateTime dt2 = dt1 + ts; DateTime dt3 = new DateTime(dt1.Ticks + ts.Ticks); if (DateTime.Compare(dt2, dt3) != 0) { Log.Comment("Failure : DateTime'" + dt1.ToString() + "' + TimeSpan'" + ts.ToString() + "' expected result '" + dt3.ToString() + "' but got '" + dt2.ToString() + "'"); testResult = MFTestResults.Fail; } } } catch (Exception ex) { Log.Comment("Caught Unexpected Exception : " + ex.Message); return MFTestResults.Fail; } return testResult; } [TestMethod] public MFTestResults DateTime_op_Subtraction_DateTimeTest31() { Log.Comment("Creating Random DateTimes,"); Log.Comment("Subtracting one from the other and verifying"); MFTestResults testResult = MFTestResults.Pass; try { DateTime[] dtArr = Get_ArrayOfRandomDateTimes(); Random random = new Random(); for (int i = 0; i < dtArr.Length; i++) { DateTime dt1 = dtArr[i]; DateTime dt2 = new DateTime(random.Next(1000) + 1); TimeSpan ts = dt1 - dt2; if (ts.Ticks != (dt1.Ticks - dt2.Ticks)) { Log.Comment("Failure : '" + dt1.ToString() + "' - '" + dt2.ToString() + "', expected difference = '" + (dt1.Ticks - dt2.Ticks) + "' ticks but got '" + ts.ToString() + "' ticks"); testResult = MFTestResults.Fail; } } } catch (Exception ex) { Log.Comment("Caught Unexpected Exception : " + ex.Message); return MFTestResults.Fail; } return testResult; } [TestMethod] public MFTestResults DateTime_op_Subtraction_TimeSpanTest32() { Log.Comment("Creating Random DateTime,"); Log.Comment("Subtracting random TimeSpan and verifying"); MFTestResults testResult = MFTestResults.Pass; try { DateTime[] dtArr = Get_ArrayOfRandomDateTimes(); Random random = new Random(); for (int i = 0; i < dtArr.Length; i++) { DateTime dt1 = dtArr[i]; TimeSpan ts = new TimeSpan(random.Next(10000)); DateTime dt2 = dt1 - ts; if (dt2.Ticks != (dt1.Ticks - ts.Ticks)) { Log.Comment("Failure : DateTime('" + dt1.ToString() + ")' - TimeSpan'" + ts.ToString() + "', expected difference = '" + (dt1.Ticks - ts.Ticks) + "' ticks but got '" + dt2.ToString() + "' ticks"); testResult = MFTestResults.Fail; } } } catch (Exception ex) { Log.Comment("Caught Unexpected Exception : " + ex.Message); return MFTestResults.Fail; } return testResult; } [TestMethod] public MFTestResults DateTime_op_EqualityTest33() { Log.Comment("Creating Random DateTime,"); Log.Comment("Creating another DateTime equal to previous one"); Log.Comment("Verifying the two DateTimes are equal using '=='"); MFTestResults testResult = MFTestResults.Pass; try { DateTime dt1 = GetRandomDateTime(); DateTime dt2 = new DateTime(year, month, day, hour, minute, second, millisec); if (!(dt1 == dt2)) { Log.Comment("Failure : expected the two DateTimes '" + dt1.ToString() + "' and '" + dt2.ToString() + "' to be equal but are not"); testResult = MFTestResults.Fail; } } catch (Exception ex) { Log.Comment("Caught Unexpected Exception : " + ex.Message); return MFTestResults.Fail; } return testResult; } [TestMethod] public MFTestResults DateTime_op_InequalityTest34() { Log.Comment("Creating Random DateTime,"); Log.Comment("Creating another Different DateTime"); Log.Comment("Verifying the two DateTimes are not equal using '!='"); MFTestResults testResult = MFTestResults.Pass; try { DateTime dt1 = GetRandomDateTime(); DateTime dt2 = new DateTime(year + 1, month, day, hour, minute, second, millisec); if (!(dt1 != dt2)) { Log.Comment("Failure : expected the two DateTimes '" + dt1.ToString() + "' and '" + dt2.ToString() + "' not to be equal but are equal"); testResult = MFTestResults.Fail; } } catch (Exception ex) { Log.Comment("Caught Unexpected Exception : " + ex.Message); return MFTestResults.Fail; } return testResult; } [TestMethod] public MFTestResults DateTime_op_LessThanTest35() { Log.Comment("Creating Random DateTime,"); Log.Comment("Creating another Different DateTime greater than previous one"); Log.Comment("Verifying 1st DateTime is less than 2nd using '<'"); MFTestResults testResult = MFTestResults.Pass; try { DateTime dt1 = GetRandomDateTime(); DateTime dt2 = new DateTime(year + 1, month, day, hour, minute, second, millisec); if (!(dt1 < dt2)) { Log.Comment("Failure : expected DateTime '" + dt1.ToString() + "' less than '" + dt2.ToString() + "'"); testResult = MFTestResults.Fail; } } catch (Exception ex) { Log.Comment("Caught Unexpected Exception : " + ex.Message); return MFTestResults.Fail; } return testResult; } [TestMethod] public MFTestResults DateTime_op_LessThanOrEqualTest36() { Log.Comment("Creating Random DateTime, Creaing 2nd equal DateTime"); Log.Comment("Creating 3rd Different DateTime greater than previous two"); Log.Comment("Verifying 1st DateTime is less than or equal to 2nd DateTime using '<='"); Log.Comment("Verifying 1st DateTime is less than or equal to 3rd DateTime using '<='"); MFTestResults testResult = MFTestResults.Pass; try { DateTime dt1 = GetRandomDateTime(); DateTime dt2 = new DateTime(year, month, day, hour, minute, second, millisec); DateTime dt3 = new DateTime(year + 1, month, day, hour, minute, second, millisec); if (!((dt1 <= dt2) || (dt2 <= dt1))) { Log.Comment("Failure : expected DateTime '" + dt1.ToString() + "' lessthan or equal to '" + dt2.ToString() + "' (dt1 <= dt2) = '" + (dt1 <= dt2) + "' and (dt2<=dt1) = '" + (dt2 <= dt1) + "'"); testResult = MFTestResults.Fail; } if (!(dt1 <= dt3)) { Log.Comment("Failure : expected DateTime '" + dt1.ToString() + "' less than or equal to '" + dt2.ToString() + "'"); testResult = MFTestResults.Fail; } } catch (Exception ex) { Log.Comment("Caught Unexpected Exception : " + ex.Message); return MFTestResults.Fail; } return testResult; } [TestMethod] public MFTestResults DateTime_op_GreaterThanTest37() { Log.Comment("Creating Random DateTime,"); Log.Comment("Creating another Different DateTime greater than previous one"); Log.Comment("Verifying 2nd DateTime is greater than 1st using '>'"); MFTestResults testResult = MFTestResults.Pass; try { DateTime dt1 = GetRandomDateTime(); DateTime dt2 = new DateTime(year + 1, month, day, hour, minute, second, millisec); if (!(dt2 > dt1)) { Log.Comment("Failure : expected DateTime '" + dt1.ToString() + "' greater than '" + dt2.ToString() + "'"); testResult = MFTestResults.Fail; } } catch (Exception ex) { Log.Comment("Caught Unexpected Exception : " + ex.Message); return MFTestResults.Fail; } return testResult; } [TestMethod] public MFTestResults DateTime_op_GreaterThanOrEqualTest38() { Log.Comment("Creating Random DateTime, Creaing 2nd equal DateTime"); Log.Comment("Creating 3rd Different DateTime greater than previous two"); Log.Comment("Verifying 1st DateTime is greater than or equal to 2nd DateTime using '>='"); Log.Comment("Verifying 3rd DateTime is greater than or equal to 1st DateTime using '>='"); MFTestResults testResult = MFTestResults.Pass; try { DateTime dt1 = GetRandomDateTime(); DateTime dt2 = new DateTime(year, month, day, hour, minute, second, millisec); DateTime dt3 = new DateTime(year + 1, month, day, hour, minute, second, millisec); if (!((dt1 >= dt2) || (dt2 >= dt1))) { Log.Comment("Failure : expected DateTime '" + dt1.ToString() + "' lessthan or equal to '" + dt2.ToString() + "'"); testResult = MFTestResults.Fail; } if (!(dt1 <= dt3)) { Log.Comment("Failure : expected DateTime '" + dt1.ToString() + "' greater than or equal to '" + dt2.ToString() + "'"); testResult = MFTestResults.Fail; } } catch (Exception ex) { Log.Comment("Caught Unexpected Exception : " + ex.Message); return MFTestResults.Fail; } return testResult; } [TestMethod] public MFTestResults DateTime_MinValueTest39() { /// /// 1. Verifies the MinValue property /// /// MFTestResults testResult = MFTestResults.Pass; try { Log.Comment("Getting the Min. DateTime and Verifying"); DateTime field = DateTime.MinValue; if (field.Ticks != 0) { Log.Comment("Failure : expected DateTime.MinValue = '0' but got '" + field.Ticks + "'"); testResult = MFTestResults.Fail; } } catch (Exception ex) { Log.Comment("Caught Unexpected Exception : " + ex.Message); return MFTestResults.Fail; } return testResult; } [TestMethod] public MFTestResults DateTime_MaxValueTest40() { /// /// 1. Verifies the MinValue property /// /// MFTestResults testResult = MFTestResults.Pass; try { Log.Comment("Getting the Max. DateTime and Verifying"); DateTime field = DateTime.MaxValue; Log.Comment(field.Ticks.ToString()); if (field.Ticks != 441796895990000000) { Log.Comment("Failure : expected DateTime.MinValue = '441796895990000000'" + " but got '" + field.Ticks + "'"); testResult = MFTestResults.Fail; } } catch (Exception ex) { Log.Comment("Caught Unexpected Exception : " + ex.Message); return MFTestResults.Fail; } return testResult; } [TestMethod] public MFTestResults DateTime_DateTest41() { /// /// 1. Verifies the Date property /// /// MFTestResults testResult = MFTestResults.Pass; try { Log.Comment("Creating a DateTime, getting the Date and Verifying"); DateTime dt = GetRandomDateTime(); DateTime _date = dt.Date; if ((_date.Year != dt.Year) || (_date.Month != dt.Month) || (_date.Day != dt.Day) || (_date.Hour != 0) || (_date.Minute != 0) | (_date.Second != 0) || (_date.Millisecond != 0)) { Log.Comment("Failure : expected Date(mm/dd/yr/hr/mn/sec/msec) = '" + dt.Month + "/" + dt.Day + "/" + dt.Year + "/0:0:0:0' but got '" + _date.Month + "/" + _date.Day + "/" + _date.Year + "/" + _date.Hour + ":" + _date.Minute + ":" + _date.Second + ":" + _date.Millisecond + "'"); testResult = MFTestResults.Fail; } } catch (Exception ex) { Log.Comment("Caught Unexpected Exception : " + ex.Message); return MFTestResults.Fail; } return testResult; } [TestMethod] public MFTestResults DateTime_DayTest42() { /// /// 1. Verifies the Day property /// /// MFTestResults testResult = MFTestResults.Pass; try { Log.Comment("Creating a DateTime, getting the Day and Verifying"); DateTime testDateTime = GetRandomDateTime(); Int32 _day = testDateTime.Day; if (_day != day) { Log.Comment("Failure : Expected Day = '" + day + "' but got '" + _day + "'"); testResult = MFTestResults.Fail; } } catch (Exception ex) { Log.Comment("Caught Unexpected Exception : " + ex.Message); return MFTestResults.Fail; } return testResult; } [TestMethod] public MFTestResults DateTime_DayOfWeekTest43() { /// /// 1. Verifies the DayOfWeek property /// /// MFTestResults testResult = MFTestResults.Pass; try { Log.Comment("Creating a DateTime, getting the DayOfWeek and Verifying"); DateTime testDateTime = new DateTime(2005, 1, 28); DayOfWeek prop = testDateTime.DayOfWeek; if (prop != DayOfWeek.Friday) { Log.Comment("Failure : Expected DayOfWeek = '" + DayOfWeek.Friday + "' but got '" + prop + "'"); testResult = MFTestResults.Fail; } } catch (Exception ex) { Log.Comment("Caught Unexpected Exception : " + ex.Message); return MFTestResults.Fail; } return testResult; } [TestMethod] public MFTestResults DateTime_DayOfYearTest44() { /// /// 1. Verifies the DayOfYear property /// /// MFTestResults testResult = MFTestResults.Pass; try { Log.Comment("Creating a DateTime, getting the DayOfYear and Verifying"); Log.Comment("DateTime::DayOfYear - Normal "); DateTime testDateTime = new DateTime(2005, 1, 1); int _dayOfYear = testDateTime.DayOfYear; if (_dayOfYear != 1) { Log.Comment("Failure : Expected DayOfYear '1' but got '" + _dayOfYear + "'"); testResult = MFTestResults.Fail; } } catch (Exception ex) { Log.Comment("Caught Unexpected Exception : " + ex.Message); return MFTestResults.Fail; } return testResult; } [TestMethod] public MFTestResults DateTime_HourTest45() { /// /// 1. Verifies the Hour property /// /// MFTestResults testResult = MFTestResults.Pass; try { Log.Comment("Creating a DateTime, getting the Hour and Verifying"); DateTime testDateTime = GetRandomDateTime(); Int32 _hour = testDateTime.Hour; if (_hour != hour) { Log.Comment("Failure : Expected hour '" + hour + "' but got '" + _hour + "'"); testResult = MFTestResults.Fail; } } catch (Exception ex) { Log.Comment("Caught Unexpected Exception : " + ex.Message); return MFTestResults.Fail; } return testResult; } [TestMethod] public MFTestResults DateTime_MillisecondTest46() { /// /// 1. Verifies the Millisecond property /// /// MFTestResults testResult = MFTestResults.Pass; try { Log.Comment("Creating a DateTime, getting the Milliseconds and Verifying"); DateTime testDateTime = GetRandomDateTime(); Int32 _mSec = testDateTime.Millisecond; if (_mSec != millisec) { Log.Comment("Failure : Expected millisecond '" + millisec + "' but got '" + _mSec + "'"); testResult = MFTestResults.Fail; } } catch (Exception ex) { Log.Comment("Caught Unexpected Exception : " + ex.Message); return MFTestResults.Fail; } return testResult; } [TestMethod] public MFTestResults DateTime_MinuteTest47() { /// /// 1. Verifies the Minute property /// /// MFTestResults testResult = MFTestResults.Pass; try { Log.Comment("Creating a DateTime, getting the Minute and Verifying"); DateTime testDateTime = GetRandomDateTime(); Int32 _minute = testDateTime.Minute; if (_minute != minute) { Log.Comment("Failure : Expected minute '" + minute + "' but got '" + _minute + "'"); testResult = MFTestResults.Fail; } } catch (Exception ex) { Log.Comment("Caught Unexpected Exception : " + ex.Message); return MFTestResults.Fail; } return testResult; } [TestMethod] public MFTestResults DateTime_MonthTest48() { /// /// 1. Verifies the Month property /// /// MFTestResults testResult = MFTestResults.Pass; try { Log.Comment("Creating a DateTime, getting the Month and Verifying"); DateTime testDateTime = GetRandomDateTime(); Int32 _month = testDateTime.Month; if (_month != month) { Log.Comment("Failure : Expected month '" + month + "' but got '" + _month + "'"); testResult = MFTestResults.Fail; } } catch (Exception ex) { Log.Comment("Caught Unexpected Exception : " + ex.Message); return MFTestResults.Fail; } return testResult; } [TestMethod] public MFTestResults DateTime_NowTest49() { /// /// 1. Creates 2 DateTimes /// 2. Verifies they are equal in all but Seconds and Millisecond /// /// MFTestResults testResult = MFTestResults.Pass; try { Log.Comment("Creating 2 DateTimes and verifying they are equal in yy/mm/dd/hr/mn"); DateTime test0 = DateTime.Now; DateTime test1 = DateTime.Now; Log.Comment("Verifying"); if ((test0.Year != test1.Year) || (test0.Month != test1.Month) || (test0.Day != test1.Day) || (test0.Hour != test1.Hour) || (test0.Minute != test1.Minute)) { Log.Comment("Failure : Expected the two DateTimes ('" + test0.ToString() + "' and '" + test1.ToString() + "') are equal in all but seconds and milliseconds"); testResult = MFTestResults.Fail; } } catch (Exception ex) { Log.Comment("Caught Unexpected Exception : " + ex.Message); return MFTestResults.Fail; } return testResult; } [TestMethod] public MFTestResults DateTime_UtcNowTest50() { /// /// 1. Creates 2 DateTimes, 1 Now and 1 UtcNow /// 2. Calls ToUniversalTime on the Now /// 2. Verifies the UtcNow property is equal in all but Seconds and Millisecond /// /// MFTestResults testResult = MFTestResults.Pass; try { Log.Comment("Creating 2 DateTimes, 1 Now and 1 UtcNow"); DateTime test0 = DateTime.UtcNow; DateTime test1 = DateTime.Now; Log.Comment("Calling ToUniversalTime on the Now"); test1 = test1.ToUniversalTime(); Log.Comment("Verifying both are equal in all but seconds and Milliseconds"); if ((test0.Year != test1.Year) || (test0.Month != test1.Month) || (test0.Day != test1.Day) || (test0.Hour != test1.Hour) || (test0.Minute != test1.Minute)) { Log.Comment("Failure : Expected the two DateTimes ('" + test0.ToString() + "' and '" + test1.ToString() + "') are equal in all but seconds and milliseconds"); testResult = MFTestResults.Fail; } } catch (Exception ex) { Log.Comment("Caught Unexpected Exception : " + ex.Message); return MFTestResults.Fail; } return testResult; } [TestMethod] public MFTestResults DateTime_SecondTest51() { /// /// 1. Verifies the Second property /// /// MFTestResults testResult = MFTestResults.Pass; try { Log.Comment("Creating a DateTime, getting the Second and Verifying"); DateTime testDateTime = GetRandomDateTime(); Int32 _sec = testDateTime.Second; if (_sec != second) { Log.Comment("Failure : Expected second '" + second + "' but got '" + _sec + "'"); testResult = MFTestResults.Fail; } } catch (Exception ex) { Log.Comment("Caught Unexpected Exception : " + ex.Message); return MFTestResults.Fail; } return testResult; } [TestMethod] public MFTestResults DateTime_TicksTest52() { /// /// 1. Verifies the Ticks property /// /// MFTestResults testResult = MFTestResults.Pass; try { Log.Comment("Creating a DateTime, getting the Ticks and Verifying"); DateTime testDateTime = new System.DateTime(0); long _ticks = testDateTime.Ticks; if (_ticks != 0) { Log.Comment("Failure : Expected ticks '0' but got '" + _ticks + "'"); testResult = MFTestResults.Fail; } } catch (Exception ex) { Log.Comment("Caught Unexpected Exception : " + ex.Message); return MFTestResults.Fail; } return testResult; } [TestMethod] public MFTestResults DateTime_TodayTest53() { MFTestResults testResult = MFTestResults.Pass; try { Log.Comment("This currently fails on device, returns 01/01/2004 on device"); Log.Comment("please see 23092 for details"); Log.Comment("Creating a DateTime.Today, getting the year and Verifying"); DateTime testDateTime = DateTime.Today; long _year = testDateTime.Year; if (_year != 2009) { Log.Comment("Failure : Expected year '2009' but got '" + _year + "'"); testResult = MFTestResults.KnownFailure; } } catch (Exception ex) { Log.Comment("Caught Unexpected Exception : " + ex.Message); return MFTestResults.Fail; } return testResult; } [TestMethod] public MFTestResults DateTime_YearTest54() { /// /// 1. Verifies the Year property /// /// MFTestResults testResult = MFTestResults.Pass; try { Log.Comment("Creating a DateTime.Today, getting the year and Verifying"); DateTime testDateTime = GetRandomDateTime(); Int32 _year = testDateTime.Year; if (_year != year) { testResult = MFTestResults.Fail; } } catch (Exception ex) { Log.Comment("Caught Unexpected Exception : " + ex.Message); return MFTestResults.Fail; } return testResult; } //=================================================================================== //The Following test are commented out because they throw Debug Assert in build Envt. //Please see 23143 for details //=================================================================================== [TestMethod] public MFTestResults DateTime_Year_ArgumentOutOfRangeExceptionTest55() { // MFTestResults testResult = MFTestResults.Fail; try { // Log.Comment("Creating a DateTime with -ve, 0 or above max year and,"); // Log.Comment("verifying ArgumentOutOfRangeException is thrown"); // int exCounter = 0; // int[] yr = new int[] { -(random.Next(100) + 1), 0, random.Next(10) + 10000 }; // for (int i = 0; i < yr.Length; i++) // { // Log.Comment("Year = " + yr[i]); // try // { // DateTime dt = new DateTime(yr[i], 1, 1); // } // catch (ArgumentOutOfRangeException ex) // { // Log.Comment("Correctly caught ArgumentOutOfRangeException : " + ex.Message); // exCounter++; // } // } // if (exCounter != yr.Length) // { // Log.Comment("Expected ArgumentOutOfRangeException '" + yr.Length + "' but got '" + yr.Length + "'"); // testResult = MFTestResults.Fail; // } // return testResult; } catch (Exception ex) { Log.Comment("Caught Unexpected Exception : " + ex.Message); return MFTestResults.Fail; } Log.Comment("Creating DateTime with invalid year generates Debug Assert in Build Envt. Bug 23143"); return MFTestResults.Skip; } [TestMethod] public MFTestResults DateTime_Month_ArgumentOutOfRangeExceptionTest56() { // MFTestResults testResult = MFTestResults.Fail; try { // Log.Comment("Creating a DateTime with -ve, 0 or above max month and,"); // Log.Comment("verifying ArgumentOutOfRangeException is thrown"); // int exCounter = 0; // int[] mth = new int[] { -(random.Next(100) + 1), 0, random.Next(10) + 13 }; // for (int i = 0; i < mth.Length; i++) // { // Log.Comment("Month = " + mth[i]); // try // { // DateTime dt = new DateTime(random.Next(9999) + 1, mth[i], 1); // } // catch (ArgumentOutOfRangeException ex) // { // Log.Comment("Correctly caught ArgumentOutOfRangeException : " + ex.Message); // exCounter++; // } // } // if (exCounter != mth.Length) // { // Log.Comment("Expected ArgumentOutOfRangeException '" + mth.Length + "' but got '" + mth.Length + "'"); // testResult = MFTestResults.Fail; // } // return testResult; } catch (Exception ex) { Log.Comment("Caught Unexpected Exception : " + ex.Message); return MFTestResults.Fail; } Log.Comment("Creating DateTime with invalid Month generates Debug Assert in Build Envt. Bug 23143"); return MFTestResults.Skip; } [TestMethod] public MFTestResults DateTime_Day_ArgumentOutOfRangeExceptionTest57() { // MFTestResults testResult = MFTestResults.Fail; try { // Log.Comment("Creating a DateTime with -ve, 0 or above max day and,"); // Log.Comment("verifying ArgumentOutOfRangeException is thrown"); // int exCounter = 0; // int[] dy = new int[] { -(random.Next(100) + 1), 0, random.Next(10) + 32 }; // for (int i = 0; i < dy.Length; i++) // { // Log.Comment("Day = " + dy[i]); // try // { // DateTime dt = new DateTime(random.Next(9999) + 1, random.Next(12) + 1, dy[i]); // } // catch (ArgumentOutOfRangeException ex) // { // Log.Comment("Correctly caught ArgumentOutOfRangeException : " + ex.Message); // exCounter++; // } // } // Log.Comment("Getting a leap year, and creating a DateTime with 30 days in Feb.,"); // Log.Comment("verifying ArgumentOutOfRangeException is thrown"); // DateTime leapDateTime = GetLeapYearDateTime(); // try // { // DateTime dt = new DateTime(leapYear[random.Next(leapYear.Length)], 2, 30); // } // catch (ArgumentOutOfRangeException ex) // { // Log.Comment("Correctly caught ArgumentOutOfRangeException : " + ex.Message); // exCounter++; // } // if (exCounter != (dy.Length + 1)) // { // Log.Comment("Expected ArgumentOutOfRangeException '" + dy.Length + "' but got '" + dy.Length + "'"); // testResult = MFTestResults.Fail; // } // return testResult; } catch (Exception ex) { Log.Comment("Caught Unexpected Exception : " + ex.Message); return MFTestResults.Fail; } Log.Comment("Creating DateTime with invalid Day generates Debug Assert in Build Envt. Bug 23143"); return MFTestResults.Skip; } [TestMethod] public MFTestResults DateTime_BelowMinDateTime_ArgumentOutOfRangeExceptionTest58() { MFTestResults testResult = MFTestResults.Fail; try { Log.Comment("Creating a DateTime with -ve Ticks and,"); Log.Comment("verifying ArgumentOutOfRangeException is thrown"); try { DateTime dt = new DateTime(-(new Random().Next(10) + 1)); } catch (ArgumentOutOfRangeException ex) { Log.Comment("Correctly caught ArgumentOutOfRangeException : " + ex.Message); testResult = MFTestResults.Pass; } } catch (Exception ex) { Log.Comment("Caught Unexpected Exception : " + ex.Message); return MFTestResults.Fail; } return testResult; } [TestMethod] public MFTestResults DateTime_AboveMaxDatTime_ArgumentOutOfRangeExceptionTest59() { MFTestResults testResult = MFTestResults.Pass; try { bool bRest1 = false, bRest2 = false; Log.Comment("Creating a DateTime later than DateTime.MaxValue and,"); Log.Comment("verifying ArgumentOutOfRangeException is thrown"); try { DateTime dt1 = new DateTime(DateTime.MaxValue.Ticks + 1); } catch (ArgumentOutOfRangeException ex) { Log.Comment("Correctly caught ArgumentOutOfRangeException : " + ex.Message); bRest1 = true; } try { DateTime dt2 = new DateTime(10000, 1, 1, 0, 0, 0, 0); } catch (ArgumentOutOfRangeException ex) { Log.Comment("Correctly caught ArgumentOutOfRangeException : " + ex.Message); bRest2 = true; } if (!bRest1) { Log.Comment("new DateTime(DateTime.MaxValue.Ticks + 1) didn't throw ArgumentOutOfRangeException"); testResult = MFTestResults.Fail; } else if (!bRest2) { Log.Comment("new DateTime(10000, 1, 1, 0, 0, 0, 0) didn't throw ArgumentOutOfRangeException"); testResult = MFTestResults.KnownFailure; } } catch (Exception ex) { Log.Comment("Caught Unexpected Exception : " + ex.Message); return MFTestResults.Fail; } return testResult; } static double[] rdmFraction = new double[] { 0.0, 0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9 }; static int year, month, day, hour, minute, second, millisec; int[] leapYear = new int[]{2000, 2004, 2008, 2012, 2016, 2020, 2024, 2028, 2032, 2036, 2040, 2044, 2048, 2052, 2056, 2060, 2064, 2068, 2072, 2076, 2080, 2084, 2088, 2092, 2096}; private DateTime[] Get_ArrayOfRandomDateTimes() { DateTime[] _dateTimeArr = new DateTime[]{DateTime.Now, DateTime_btwn_1801_And_2801(), DateTime_btwn_1801_And_2801(), DateTime_btwn_1801_And_2801(), GetLeapYearDateTime() ,GetLeapYearDateTime() , GetLeapYearDateTime(), DateTime_btwn_1801_And_2801(), DateTime_btwn_1801_And_2801(), DateTime_btwn_1801_And_2801(), GetLeapYearDateTime() ,GetLeapYearDateTime() , GetLeapYearDateTime()}; return _dateTimeArr; } private DateTime DateTime_btwn_1801_And_2801() { //Generates random DateTime b/n 1000 and 9000 Random random = new Random(); year = random.Next(999) + 1801; month = random.Next(12) + 1; if (month == 2 && IsLeapYear(year)) day = random.Next(29) + 1; else if (month == 2 && (!IsLeapYear(year))) day = random.Next(28) + 1; else if (((month <= 7) && ((month + 1) % 2 == 0)) || ((month > 7) && ((month % 2) == 0))) day = random.Next(31) + 1; else day = random.Next(30) + 1; hour = random.Next(24); minute = random.Next(60); second = random.Next(60); millisec = random.Next(1000); return new DateTime(year, month, day, hour, minute, second, millisec); } private DateTime GetRandomDateTime() { //Generates random DateTime Random random = new Random(); year = random.Next(1399) + 1601; month = random.Next(12) + 1; if (month == 2 && IsLeapYear(year)) day = random.Next(29) + 1; else if (month == 2 && (!IsLeapYear(year))) day = random.Next(28) + 1; else if (((month <= 7) && ((month + 1) % 2 == 0)) || ((month > 7) && ((month % 2) == 0))) day = random.Next(31) + 1; else day = random.Next(30) + 1; hour = random.Next(24); minute = random.Next(60); second = random.Next(60); millisec = random.Next(1000); return new DateTime(year, month, day, hour, minute, second, millisec); } private DateTime GetLeapYearDateTime() { Random random = new Random(); year = leapYear[random.Next(leapYear.Length)]; month = random.Next(12) + 1; day = random.Next(29) + 1; hour = random.Next(24); minute = random.Next(60); second = random.Next(60); millisec = random.Next(1000); return new DateTime(year, month, day, hour, minute, second, millisec); } private bool IsLeapYear(int yr) { if ((yr % 400 == 0) || ((yr % 100 != 0) && (yr % 4 == 0))) return true; else return false; } private bool CheckDeviation(long dTicks1, long dTicks2) { long diff = System.Math.Abs((int)(dTicks2 - dTicks1)); //fail if deviates by more than 0.05ms (500 ticks) if (diff > 500) { Log.Comment("Difference ticks = '" + diff.ToString() + "'"); return false; } return true; } private MFTestResults DaysInMonthTest(int yr, int mnth) { MFTestResults tResult = MFTestResults.Pass; int daysInMonth = DateTime.DaysInMonth(yr, mnth); Log.Comment("Got " + daysInMonth + " number of days in " + mnth + "/" + yr + " mm/yr"); if (mnth == 2) { if (IsLeapYear(yr)) { if (daysInMonth != 29) { Log.Comment("Year '" + yr + "' is a LeapYear, expected '29' days but got '" + daysInMonth + "' in Month '" + mnth + "'"); tResult = MFTestResults.Fail; } } else if (daysInMonth != 28) { Log.Comment("Year '" + yr + "' Month '" + mnth + "', expected '28' days but got '" + daysInMonth + "'"); tResult = MFTestResults.Fail; } } else if (((mnth <= 7) && ((mnth + 1) % 2 == 0)) || ((mnth > 7) && ((mnth % 2) == 0))) { if (daysInMonth != 31) { Log.Comment("Year '" + yr + "' Month '" + mnth + "', expected '31' days but got '" + daysInMonth + "'"); tResult = MFTestResults.Fail; } } else { if (daysInMonth != 30) { Log.Comment("Year '" + yr + "' Month '" + mnth + "', expected '30' days but got '" + daysInMonth + "'"); tResult = MFTestResults.Fail; } } return tResult; } } } ================================================ FILE: Zelig/Zelig/Test/RunTime/NETMF/mscorlib/systemlib/systemlib2/SystemGCTests.cs ================================================ //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // Copyright (c) Microsoft Corporation. All rights reserved. //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// using System; using System.Reflection; using Microsoft.SPOT.Platform.Test; namespace Microsoft.SPOT.Platform.Tests { public class SystemGCTests : IMFTestInterface { [SetUp] public InitializeResult Initialize() { Log.Comment("Adding set up for the tests"); return InitializeResult.ReadyToGo; } [TearDown] public void CleanUp() { Log.Comment("Cleaning up after the tests"); } //SystemGC Test methods class FinalizeObject { public static FinalizeObject m_currentInstance = null; ~FinalizeObject() { if (m_hasFinalized1 == false) { Log.Comment("First finalization"); // Put this object back into a root by creating // a reference to it. FinalizeObject.m_currentInstance = this; // Indicate that this instance has finalized once. m_hasFinalized1 = true; // Place a reference to this object back in the // finalization queue. GC.ReRegisterForFinalize(this); } else { Log.Comment("Second finalization"); m_hasFinalized2 = true; } } } static bool m_hasFinalized1 = false; static bool m_hasFinalized2 = false; static bool m_Test1Result = false; [TestMethod] public MFTestResults SystemGC1_Test() { /// /// 1. Create a FinalizeObject. /// 2. Release the reference /// 3. Allow for GC /// 4. Run ReRegisterForFinalize /// 5. Allow for GC /// 6. Verify that object has been collected /// /// Log.Comment("Tests ReRegisterForFinalize"); Log.Comment("Create a FinalizeObject."); FinalizeObject mfo = new FinalizeObject(); m_hasFinalized1 = false; m_hasFinalized2 = false; Log.Comment("Release reference"); mfo = null; Log.Comment("Allow GC"); SPOT.Debug.GC(true); int sleepTime = 1000; int slept = 0; while (m_hasFinalized1 == false && slept < sleepTime) { System.Threading.Thread.Sleep(10); slept += 10; } Log.Comment("GC took " + slept); // At this point mfo will have gone through the first Finalize. // There should now be a reference to mfo in the static // FinalizeObject.m_currentInstance field. Setting this value // to null and forcing another garbage collection will now // cause the object to Finalize permanently. Log.Comment("Reregister and allow for GC"); FinalizeObject.m_currentInstance = null; SPOT.Debug.GC(true); sleepTime = 1000; slept = 0; while (m_hasFinalized2 == false && slept < sleepTime) { System.Threading.Thread.Sleep(10); slept += 10; } Log.Comment("GC took " + slept); m_Test1Result = m_hasFinalized2; return (m_hasFinalized2 ? MFTestResults.Pass : MFTestResults.Fail); } [TestMethod] public MFTestResults SystemGC2_Test() { /// /// 1. Create a FinalizeObject. /// 2. Release the reference /// 3. SupressFinalize /// 3. Allow for GC /// 6. Verify that object has not been collected /// /// Log.Comment("Tests SuppressFinalize"); Log.Comment("Create a FinalizeObject."); FinalizeObject mfo = new FinalizeObject(); m_hasFinalized1 = false; m_hasFinalized2 = false; Log.Comment("Releasing"); System.GC.SuppressFinalize(mfo); mfo = null; Log.Comment("Allow GC"); SPOT.Debug.GC(true); int sleepTime = 1000; int slept = 0; while (m_hasFinalized1 == false && slept < sleepTime) { System.Threading.Thread.Sleep(10); slept += 10; } Log.Comment("GC took " + slept); return (!m_hasFinalized1 ? MFTestResults.Pass : MFTestResults.Fail); } [TestMethod] public MFTestResults SystemGC3_Test() { /// /// 1. Create a FinalizeObject. /// 2. Release the reference /// 3. SupressFinalize /// 3. Allow for GC /// 6. Verify that object has not been collected /// /// Log.Comment("Tests WaitForPendingFinalizers, dependant on test 1"); Log.Comment("will auto-fail if test 1 fails."); if (m_Test1Result) { Log.Comment("Create a FinalizeObject."); FinalizeObject mfo = new FinalizeObject(); m_hasFinalized1 = false; m_hasFinalized2 = false; Log.Comment("Releasing"); mfo = null; Log.Comment("Wait for GC"); SPOT.Debug.GC(true); System.GC.WaitForPendingFinalizers(); Log.Comment("Releasing again"); FinalizeObject.m_currentInstance = null; Log.Comment("Wait for GC"); SPOT.Debug.GC(true); System.GC.WaitForPendingFinalizers(); return (m_hasFinalized2 ? MFTestResults.Pass : MFTestResults.Fail); } return MFTestResults.Fail; } } } ================================================ FILE: Zelig/Zelig/Test/RunTime/NETMF/mscorlib/systemlib/systemlib2/SystemMathTests.cs ================================================ //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // Copyright (c) Microsoft Corporation. All rights reserved. //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// using System; using System.Reflection; using Microsoft.SPOT.Platform.Test; namespace Microsoft.SPOT.Platform.Tests { public class SystemMathTests : IMFTestInterface { [SetUp] public InitializeResult Initialize() { Log.Comment("Adding set up for the tests"); return InitializeResult.ReadyToGo; } [TearDown] public void CleanUp() { Log.Comment("Cleaning up after the tests"); } //SystemMath Test methods [TestMethod] public MFTestResults SystemMath1_PI_Test() { /// /// 1. Tests that the Math.PI constant is accurate to 15 significant digits /// /// Log.Comment("Tests that the Math.PI constant is accurate to 15 significant digits"); bool testResult = true; double PIFloor = 3.141592653589793; double PICeil = 3.141592653589794; testResult &= (PIFloor <= System.Math.PI && System.Math.PI <= PICeil); return (testResult ? MFTestResults.Pass : MFTestResults.Fail); } [TestMethod] public MFTestResults SystemMath2_E_Test() { /// /// 1. Tests that the Math.E constant is accurate to 15 significant digits /// /// Log.Comment("Tests that the Math.E constant is accurate to 15 significant digits"); bool testResult = true; double EFloor = 2.718281828459045; double ECeil = 2.718281828459046; testResult &= (EFloor <= System.Math.E && System.Math.E <= ECeil); return (testResult ? MFTestResults.Pass : MFTestResults.Fail); } [TestMethod] public MFTestResults SystemMath3_Abs_Test() { /// /// 1. Tests the Math.Abs method /// /// Log.Comment("Tests the Math.Abs method"); bool testResult = true; int positive = new Random().Next(1000); Log.Comment("With " + positive); int negative = -positive; testResult &= ((positive + negative) == 0); testResult &= (positive == System.Math.Abs(negative)); testResult &= ((System.Math.Abs(-positive) + negative) == 0); testResult &= (System.Math.Abs(positive+negative) == 0); return (testResult ? MFTestResults.Pass : MFTestResults.Fail); } [TestMethod] public MFTestResults SystemMath4_Ceiling_Test() { /// /// 1. Tests the Math.Ceiling method /// /// Log.Comment("Tests the Math.Ceiling method"); bool testResult = true; double base1 = new Random().Next(1000); Log.Comment("With " + base1); testResult &= (System.Math.Ceiling(base1) == base1); for (double d = .1; d < 1;d += .1 ) testResult &= (System.Math.Ceiling(base1 + d) == base1 + 1); return (testResult ? MFTestResults.Pass : MFTestResults.Fail); } [TestMethod] public MFTestResults SystemMath5_Floor_Test() { /// /// 1. Tests the Math.Floor method /// /// Log.Comment("Tests the Math.Floor method"); bool testResult = true; double base1 = new Random().Next(1000); Log.Comment("With " + base1); for (double d = .0; d < .9; d += .1) testResult &= (System.Math.Floor(base1 + d) == base1); return (testResult ? MFTestResults.Pass : MFTestResults.Fail); } [TestMethod] public MFTestResults SystemMath6_Round_Test() { /// /// 1. Tests the Math.Round method /// /// Log.Comment("Tests the Math.Round method"); bool testResult = true; double base1 = 334; Log.Comment("With " + base1); for (double d = .0; d < .6; d += .1) { testResult &= (System.Math.Round(base1 + d) == base1); Log.Comment(d.ToString() + " " + (System.Math.Round(base1 + d)).ToString()); } for (double d = .6; d < 1; d += .1) { testResult &= (System.Math.Round(base1 + d) == base1 + 1); Log.Comment(d.ToString() + " " + (System.Math.Round(base1 + d)).ToString()); } return (testResult ? MFTestResults.Pass : MFTestResults.Fail); } [TestMethod] public MFTestResults SystemMath7_Max_Test() { /// /// 1. Tests the Math.Max method /// /// Log.Comment("Tests the Math.Max method"); bool testResult = true; Random random = new Random(); int big = 51 + random.Next(1000); Log.Comment("With " + big); int small = random.Next(50); Log.Comment("and " + small); testResult &= (System.Math.Max(big,small) == big); testResult &= (System.Math.Max(small,big) == big); testResult &= (System.Math.Max(small, -big) == small); testResult &= (System.Math.Max(-small, -big) == -small); testResult &= (System.Math.Max(0, small) == small); testResult &= (System.Math.Max(-small, 0) == 0); return (testResult ? MFTestResults.Pass : MFTestResults.Fail); } [TestMethod] public MFTestResults SystemMath8_Min_Test() { /// /// 1. Tests the Math.Min method /// /// Log.Comment("Tests the Math.Min method"); bool testResult = true; Random random = new Random(); int big = 51 + random.Next(1000); Log.Comment("With " + big); int small = random.Next(50); Log.Comment("and " + small); testResult &= (System.Math.Min(big, small) == small); testResult &= (System.Math.Min(small, big) == small); testResult &= (System.Math.Min(small, -big) == -big); testResult &= (System.Math.Min(-small, -big) == -big); testResult &= (System.Math.Min(0, small) == 0); testResult &= (System.Math.Min(-small, 0) == -small); return (testResult ? MFTestResults.Pass : MFTestResults.Fail); } [TestMethod] public MFTestResults SystemMath5_Pow_Test() { /// /// 1. Tests the Math.Pow method /// /// Log.Comment("Tests that the Math.Pow method"); bool testResult = true; double base1 = new Random().Next(10); Log.Comment("with " + base1); double result = 0; for (double d = 0; d <= 10; d++) { result = 1; for (int i = 1; i <= d; i++) result *= base1; testResult &= (result == System.Math.Pow(base1,d)); } return (testResult ? MFTestResults.Pass : MFTestResults.Fail); } } } ================================================ FILE: Zelig/Zelig/Test/RunTime/NETMF/mscorlib/systemlib/systemlib2/SystemReflectionAssembly.cs ================================================ //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // Copyright (c) Microsoft Corporation. All rights reserved. //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// using System; using System.Reflection; using Microsoft.SPOT.Platform.Test; using Microsoft.SPOT; namespace Microsoft.SPOT.Platform.Tests { public class SystemReflectionAssembly: IMFTestInterface { [SetUp] public InitializeResult Initialize() { Log.Comment("Adding set up for the tests"); return InitializeResult.ReadyToGo; } [TearDown] public void CleanUp() { Log.Comment("Cleaning up after the tests"); } [TestMethod] public MFTestResults AssemblyName_Test1() { MFTestResults res = MFTestResults.Pass; try { Assembly assm = Assembly.GetExecutingAssembly(); // we will check that the Name and FullName from the AssemblyName class do go along string name = assm.GetName().Name; Log.Comment("Assembly name from AssemblyName type is: \"" + name + "\""); string fullNameFromAssemblyName = assm.GetName().FullName; Log.Comment("Assembly FullNme from AssemblyName type is: \"" + fullNameFromAssemblyName + "\""); string nameParsedFromFullName = fullNameFromAssemblyName.Substring(0, fullNameFromAssemblyName.IndexOf(',')); if (nameParsedFromFullName != name) { Log.Comment("The name parsed from the FullName is different than the Name"); res = MFTestResults.Fail; } // we will check that the FullName from Assembly and FullName from the AssemblyName class do match string fullName = assm.FullName; Log.Comment("Assembly FullName from Assembly type: \"" + fullName + "\""); if (fullName != (name + ", Version=" + assm.GetName().Version.ToString())) { Log.Comment("The FullName from the Assembly is different than the Name from the AssemblyName"); res = MFTestResults.Fail; } } catch(Exception e) { res = MFTestResults.Fail; Log.Exception("Exception caught: ", e); } return res; } [TestMethod] public MFTestResults AssemblyVersion_Test2() { MFTestResults res = MFTestResults.Pass; try { // get the version Version ver = Assembly.GetExecutingAssembly().GetName().Version; if (ver == null) { Log.Comment("Assebly Version could not be retrieved"); res = MFTestResults.Fail; } } catch (Exception e) { res = MFTestResults.Fail; Log.Exception("Exception caught: ", e); } return res; } [TestMethod] public MFTestResults AssemblyVersion_Test3() { MFTestResults res = MFTestResults.Pass; try { Type myType3 = Type.GetType("System.Int32"); // get the version Assembly assm = Assembly.Load("mscorlib"); if (assm == null) res = MFTestResults.Fail; string v = assm.GetName().Version.ToString(); Assembly assm1 = Assembly.Load("mscorlib, Version=" + v); if(assm1 == null) res = MFTestResults.Fail; try { Assembly assm2 = Assembly.Load("mscorlib, ,Version=" + v); res = MFTestResults.Fail; } catch (ArgumentException) { } // Test for extra parameters after assembly version. The assembly version parser needs to handle this // because the VS debugger will identify in CultureInfo and PublicKeyToken when debugging. assm = Assembly.Load("mscorlib, Version=" + v + ", CultureInfo=en, PublicKeyToken=null"); if (assm == null) res = MFTestResults.Fail; } catch (Exception e) { Log.Exception("Exception caught: ", e); res = MFTestResults.Fail; } return res; } [TestMethod] public MFTestResults Assembly_GetAssemblies_Satellite_Test4() { bool fRes = true; Assembly asm = typeof(int).Assembly; // Make sure satellite assembly can be retrieved Assembly res = asm.GetSatelliteAssembly(new System.Globalization.CultureInfo("en")); fRes &= res != null; // Make sure we can get a known type from the target assembly Type t = asm.GetType("System.Int32"); fRes &= t.IsValueType; // make sure all types from the assembly have proper // assembly property Type[] ts = asm.GetTypes(); for (int i = 0; i < ts.Length; i++) { fRes &= ts[i].Assembly.FullName == asm.FullName; } return fRes ? MFTestResults.Pass : MFTestResults.Fail; } } } ================================================ FILE: Zelig/Zelig/Test/RunTime/NETMF/mscorlib/systemlib/systemlib2/SystemReflectionMemberTests.cs ================================================ //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // Copyright (c) Microsoft Corporation. All rights reserved. //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// using System; using System.Reflection; using Microsoft.SPOT.Platform.Test; using System.Collections; namespace Microsoft.SPOT.Platform.Tests { public class SystemReflectionMemberTests : IMFTestInterface { [SetUp] public InitializeResult Initialize() { Log.Comment("Adding set up for the tests."); // Add your functionality here. Log.Comment("Testing Reflection types MethodInfo, ConstructorInfo, and FieldInfo"); return InitializeResult.ReadyToGo; } [TearDown] public void CleanUp() { Log.Comment("Cleaning up after the tests"); } [TestMethod] public MFTestResults SystemReflectionMemberTests_Properties_Test0() { bool fRes = true; TestClass tst = new TestClass(); /// /// Test the PropertyInfo class members /// MethodInfo mi = typeof(TestClass).GetMethod("BaseInternalProtectedMethod", BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic); fRes &= !mi.IsAbstract; fRes &= !mi.IsFinal; fRes &= !mi.IsPublic; fRes &= !mi.IsStatic; fRes &= !mi.IsVirtual; fRes &= mi.ReturnType == typeof(object); fRes &= mi.Invoke(tst, new object[] { 3 }) == null; fRes &= mi.DeclaringType == typeof(AbsTestClass); mi = typeof(AbsTestClass).GetMethod("AbstractPublicMethod", BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic); fRes &= mi.IsAbstract; fRes &= !mi.IsFinal; fRes &= mi.IsPublic; fRes &= !mi.IsStatic; fRes &= mi.IsVirtual; fRes &= mi.ReturnType == typeof(float); fRes &= (float)mi.Invoke(tst, new object[] { 3 }) == 38.4f; fRes &= mi.DeclaringType == typeof(AbsTestClass); mi = typeof(TestClass).GetMethod("VirtualInternalMethod", BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic); fRes &= !mi.IsAbstract; fRes &= !mi.IsFinal; fRes &= !mi.IsPublic; fRes &= !mi.IsStatic; fRes &= mi.IsVirtual; fRes &= mi.ReturnType == typeof(int); fRes &= (int)mi.Invoke(tst, new object[] { true }) == 34; fRes &= mi.DeclaringType == typeof(TestClass); mi = typeof(TestClass).GetMethod("SealedPublicMethod", BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic); fRes &= !mi.IsAbstract; fRes &= mi.IsFinal; fRes &= mi.IsPublic; fRes &= !mi.IsStatic; fRes &= mi.IsVirtual; fRes &= mi.ReturnType == typeof(bool); fRes &= (bool)mi.Invoke(tst, new object[] {}); fRes &= mi.DeclaringType == typeof(TestClass); mi = typeof(TestClass).GetMethod("StaticPrivateAbsMethod", BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic); fRes &= !mi.IsAbstract; fRes &= !mi.IsFinal; fRes &= !mi.IsPublic; fRes &= mi.IsStatic; fRes &= !mi.IsVirtual; fRes &= mi.ReturnType == typeof(void); TestClass.s_WasStaticMethodCalled = false; mi.Invoke(tst, new object[] {}); fRes &= TestClass.s_WasStaticMethodCalled; fRes &= mi.DeclaringType == typeof(AbsTestClass); mi = typeof(TestClass).GetMethod("PublicMethod", BindingFlags.Instance | BindingFlags.Public); fRes &= !mi.IsAbstract; fRes &= mi.IsFinal; fRes &= mi.IsPublic; fRes &= !mi.IsStatic; fRes &= mi.IsVirtual; fRes &= mi.ReturnType == typeof(void); mi.Invoke(tst, new object[] { }); fRes &= mi.DeclaringType == typeof(TestClass); mi = typeof(TestClass).GetMethod("InternalMethod", BindingFlags.Instance | BindingFlags.NonPublic); fRes &= !mi.IsAbstract; fRes &= !mi.IsFinal; fRes &= !mi.IsPublic; fRes &= !mi.IsStatic; fRes &= !mi.IsVirtual; fRes &= mi.ReturnType == typeof(int); fRes &= 1 == (int)mi.Invoke(tst, new object[] { 90.3f }); fRes &= mi.DeclaringType == typeof(TestClass); mi = typeof(TestClass).GetMethod("PrivateMethod", BindingFlags.Instance | BindingFlags.NonPublic); fRes &= !mi.IsAbstract; fRes &= !mi.IsFinal; fRes &= !mi.IsPublic; fRes &= !mi.IsStatic; fRes &= !mi.IsVirtual; fRes &= mi.ReturnType == typeof(float); fRes &= 3.3f == (float)mi.Invoke(tst, new object[] { 92 }); fRes &= mi.DeclaringType == typeof(TestClass); return fRes ? MFTestResults.Pass : MFTestResults.Fail; } [TestMethod] public MFTestResults SystemReflectionMemberTests_DelegateMethod_Test1() { bool fRes = true; /// /// Test the MethodInfo returned from the Delegate.Method property /// Delegate del = new MyDelegate(MyDelegateImpl); MethodInfo mi = del.Method; fRes &= !mi.IsPublic; fRes &= mi.IsStatic; fRes &= !mi.IsVirtual; fRes &= !mi.IsAbstract; fRes &= !mi.IsFinal; fRes &= mi.Name == "MyDelegateImpl"; fRes &= mi.ReturnType == typeof(bool); fRes &= (bool)mi.Invoke(null, new object[] { 1, 3.3f }); fRes &= mi.DeclaringType == typeof(SystemReflectionMemberTests); return fRes ? MFTestResults.Pass : MFTestResults.Fail; } [TestMethod] public MFTestResults SystemReflectionMemberTests_ConstructorInfo_Test2() { bool fRes = true; /// /// Test the ConstructorInfo class members /// Type t = typeof(TestClass); ConstructorInfo ci = t.GetConstructor(new Type[] { }); fRes &= ci.IsPublic; fRes &= !ci.IsStatic; fRes &= ci.Invoke(new object[] { }) is TestClass; ci = typeof(AbsTestClass).GetConstructor(new Type[] { typeof(float) }); fRes &= !ci.IsPublic; fRes &= !ci.IsStatic; fRes &= ci.DeclaringType == typeof(AbsTestClass); AbsTestClass tst = ci.Invoke(new object[] { 1.2f }) as AbsTestClass; fRes &= tst != null; ci = t.GetConstructor(new Type[] { typeof(int) }); fRes &= !ci.IsStatic; fRes &= !ci.IsPublic; fRes &= ci.Invoke(new object[] { 3 }) is TestClass; ci = t.GetConstructor(new Type[] { typeof(bool) }); fRes &= !ci.IsStatic; fRes &= !ci.IsPublic; fRes &= ci.Invoke(new object[] { true }) is TestClass; return fRes ? MFTestResults.Pass : MFTestResults.Fail; } [TestMethod] public MFTestResults SystemReflectionMemberTests_FieldInfo_Test3() { bool fRes = true; /// /// Test the FieldInfo class members /// Type t = typeof(TestClass); FieldInfo fi = t.GetField("AbsPrivateField", BindingFlags.Instance | BindingFlags.NonPublic); fRes &= fi.FieldType == typeof(int); fRes &= fi.DeclaringType == typeof(AbsTestClass); fi = t.GetField("PublicField"); fRes &= fi.FieldType == typeof(int); fRes &= fi.DeclaringType == typeof(TestClass); fi = t.GetField("IntProtectedField", BindingFlags.Instance | BindingFlags.NonPublic); fRes &= fi.FieldType == typeof(float); fRes &= fi.DeclaringType == t; fi = t.GetField("BoolPrivateField", BindingFlags.Static | BindingFlags.NonPublic); fRes &= fi.FieldType == typeof(bool); fRes &= fi.DeclaringType == t; return fRes ? MFTestResults.Pass : MFTestResults.Fail; } //--------------------Classes/Interfaces/Delegates used by this test class----------------------// #region INTERNAL_TEST_CLASSES private static bool MyDelegateImpl(int i, float f) { return true; } public delegate bool MyDelegate(int i, float f); abstract class AbsTestClass { int AbsPrivateField; public static bool s_WasStaticMethodCalled; static AbsTestClass() { s_WasStaticMethodCalled = false; } protected AbsTestClass(float f) { AbsPrivateField = (int)f; } internal protected object BaseInternalProtectedMethod(int i) { return null; } public abstract float AbstractPublicMethod(int i); internal virtual int VirtualInternalMethod(bool b) { return 0; } public virtual bool SealedPublicMethod() { return false; } private static void StaticPrivateAbsMethod() { s_WasStaticMethodCalled = true; } } interface IBaseInterface { void PublicMethod(); } private class TestClass : AbsTestClass, IBaseInterface { public int PublicField; internal protected float IntProtectedField; private static bool BoolPrivateField; public TestClass() : base(3.4f) { PublicField = 0; } internal TestClass(int i) : base(45.6f) { IntProtectedField = i; } private TestClass(bool b) : base(2.2f) { BoolPrivateField = b; } public void PublicMethod() { } public sealed override bool SealedPublicMethod() { return true; } internal int InternalMethod(float f) { return 1; } protected bool ProtectedMethod(bool b) { return true; } private float PrivateMethod(int i) { return 3.3f; } public override float AbstractPublicMethod(int i) { return 38.4f; } internal override int VirtualInternalMethod(bool b) { return 34; } } #endregion } } ================================================ FILE: Zelig/Zelig/Test/RunTime/NETMF/mscorlib/systemlib/systemlib2/SystemReflectionTypeTests.cs ================================================ //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // Copyright (c) Microsoft Corporation. All rights reserved. //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// using System; using System.Reflection; using Microsoft.SPOT.Platform.Test; using System.Collections; namespace Microsoft.SPOT.Platform.Tests { delegate bool MyDelegate(int i); public class SystemReflectionTypeTests : IMFTestInterface { [SetUp] public InitializeResult Initialize() { Log.Comment("Adding set up for the tests."); // Add your functionality here. Log.Comment("Tests RuntimeType and System.Type reflection"); return InitializeResult.ReadyToGo; } [TearDown] public void CleanUp() { Log.Comment("Cleaning up after the tests"); } [TestMethod] public MFTestResults SystemReflectionType_ObjectGetType_Test0() { bool fRes = true; /// /// Test object.GetType method for various types (including /// reflection types and arrays of reflection types). /// object o = (object)1; fRes &= (o.GetType() == typeof(int)); o = (object)typeof(Type); fRes &= o.GetType() == typeof(Type).GetType(); o = AppDomain.CurrentDomain.GetAssemblies(); fRes &= o.GetType() == typeof(Assembly[]); o = new TestClass(); fRes &= o.GetType() == typeof(TestClass); o = new TestStruct(); fRes &= o.GetType() == typeof(TestStruct); o = new MyDelegate(MyDelegateImpl); fRes &= o.GetType() == typeof(MyDelegate); o = (new MyDelegate(MyDelegateImpl)).Method; Debug.Print("object (MethodInfo) GetType: " + o.GetType().ToString()); MethodInfo mi = typeof(SystemReflectionTypeTests).GetMethod("MyDelegateImpl", BindingFlags.Static | BindingFlags.NonPublic); fRes &= o.GetType() == mi.GetType(); return fRes ? MFTestResults.Pass : MFTestResults.Fail; } [TestMethod] public MFTestResults SystemReflectionType_RuntimeType_Test1() { bool fRes = true; ArrayList list = new ArrayList(); int i = 0; /// /// Test the RuntimeType class members /// TestClass cls = new TestClass(); // Test Type members for a class type Type t = cls.GetType(); Assembly asm = t.Assembly; list.Add(asm); fRes &= ((Assembly)list[i]).GetName().Name == "Microsoft.SPOT.Platform.Tests.Systemlib2"; fRes &= asm.GetName().Name == "Microsoft.SPOT.Platform.Tests.Systemlib2"; fRes &= t.Name == "TestClass"; fRes &= t.FullName == "Microsoft.SPOT.Platform.Tests.SystemReflectionTypeTests+TestClass"; fRes &= t.BaseType == typeof(object); fRes &= t.GetElementType() == null; MethodInfo []mis = t.GetMethods(); fRes &= mis[0].Name == "Method1"; mis = t.GetMethods(BindingFlags.Instance | BindingFlags.NonPublic); fRes &= mis[0].Name == "Method2"; fRes &= t.GetMethod("Method1") != null; fRes &= t.GetMethod("Method2", BindingFlags.Instance | BindingFlags.NonPublic) != null; FieldInfo[] fis = t.GetFields(); fRes &= fis[0].Name == "m_Field1"; fis = t.GetFields(BindingFlags.Instance | BindingFlags.NonPublic); fRes &= fis[0].Name == "m_Field2"; fRes &= t.GetField("m_Field1") != null; fRes &= t.GetField("m_Field2", BindingFlags.NonPublic | BindingFlags.Instance) != null; fRes &= t.GetConstructor(new Type[] { }) != null; Type[] ifaces = t.GetInterfaces(); fRes &= ifaces.Length == 2; fRes &= ifaces[0].Name == "IInterface1"; fRes &= ifaces[1].Name == "IInterface2"; fRes &= t.IsSubclassOf(typeof(object)); i++; // test Type members for a struct valuetype TestStruct str = new TestStruct(); t = str.GetType(); asm = t.Assembly; list.Add(asm); fRes &= ((Assembly)list[i]).GetName().Name == "Microsoft.SPOT.Platform.Tests.Systemlib2"; fRes &= asm.GetName().Name == "Microsoft.SPOT.Platform.Tests.Systemlib2"; fRes &= t.Name == "TestStruct"; fRes &= t.FullName == "Microsoft.SPOT.Platform.Tests.SystemReflectionTypeTests+TestStruct"; fRes &= t.BaseType == typeof(System.ValueType); fRes &= t.GetInterfaces().Length == 0; fRes &= t.GetElementType() == null; i++; // test Type members for an Assembly reflection type Assembly asmObj = typeof(TestClass).Assembly; t = asmObj.GetType(); asm = t.Assembly; list.Add(asm); fRes &= ((Assembly)list[i]).GetName().Name == "mscorlib"; fRes &= asm.GetName().Name == "mscorlib"; fRes &= t.Name == "Assembly"; fRes &= t.FullName == "System.Reflection.Assembly"; fRes &= t.BaseType == typeof(Object); fRes &= t.GetInterfaces().Length == 0; fRes &= t.GetElementType() == null; mis = typeof(TestClass).GetMethods(BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.Public); t = mis.GetType(); fRes &= t.Name == "RuntimeMethodInfo[]"; fRes &= t.FullName == "System.Reflection.RuntimeMethodInfo[]"; fRes &= t.BaseType == typeof(Array); fRes &= t.GetInterfaces().Length > 0; fRes &= t.GetElementType().Name == "RuntimeMethodInfo"; // test Type members for a delegate Delegate del = new MyDelegate(MyDelegateImpl); t = del.GetType(); fRes &= t.DeclaringType == null; fRes &= t.Name == "MyDelegate"; fRes &= t.BaseType == typeof(MulticastDelegate); // test Type members for an enum TestEnum en = TestEnum.Item1; t = en.GetType(); fRes &= t.DeclaringType == typeof(SystemReflectionTypeTests); fRes &= t.IsEnum; fRes &= !t.IsAbstract; fRes &= !t.IsClass; fRes &= !t.IsPublic; fRes &= t.IsValueType; return fRes ? MFTestResults.Pass : MFTestResults.Fail; } [TestMethod] public MFTestResults SystemReflectionType_SystemType_Test2() { bool fRes = true; /// /// Test System.Type members that use or relate to reflection /// int[] blah = new int[3]; fRes &= typeof(Array).IsInstanceOfType(blah); fRes &= typeof(TestStruct[]).IsArray; fRes &= !typeof(Array).IsValueType; fRes &= typeof(TestStruct).IsValueType; fRes &= typeof(Type).IsSubclassOf(typeof(MemberInfo)); fRes &= typeof(Type).GetInterfaces()[0].Name == "IReflect"; fRes &= typeof(MyDelegate).IsInstanceOfType(new MyDelegate(MyDelegateImpl)); // Get known type from assembly qualified type name Culture and PublicKeyToken are used by debugger to identify types // so we must be able to parse them (even if we through out the culture/key). Type t = Type.GetType("System.Int32, mscorlib, version=4.1.0.0, CultureInfo=enu, PublicKeyToken=null"); fRes &= t != null; return fRes ? MFTestResults.Pass : MFTestResults.Fail; } //------------------- Classes/interfaces/structs used by this test class ---------------------------// #region INTERNAL_TEST_CLASSES enum TestEnum { Item1, Item2, Item3 }; private static bool MyDelegateImpl(int i) { return true; } public struct TestStruct { public int Field1; public bool Field2; } interface IInterface1 { } interface IInterface2 { } class TestClass : IInterface1, IInterface2 { public int m_Field1; private float m_Field2; public int Method1(bool b) { m_Field1 = 3; return m_Field1; } private bool Method2(int i) { m_Field2 = (float)i; return true; } } #endregion } } ================================================ FILE: Zelig/Zelig/Test/RunTime/NETMF/mscorlib/systemlib/systemlib2/SystemStringTests.cs ================================================ //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // Copyright (c) Microsoft Corporation. All rights reserved. //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// using System; using System.Reflection; using Microsoft.SPOT.Platform.Test; namespace Microsoft.SPOT.Platform.Tests { public class SystemStringTests : IMFTestInterface { [SetUp] public InitializeResult Initialize() { Log.Comment("Adding set up for the tests"); return InitializeResult.ReadyToGo; } [TearDown] public void CleanUp() { Log.Comment("Cleaning up after the tests"); } //String Test methods [TestMethod] public MFTestResults Ctor_Test() { /// /// 1. Tests the constructors of the string type /// /// Log.Comment("Test of the standard constructor"); bool testResult = true; char[] car = new Char[] { 'a', 'b', 'c', 'd' }; Log.Comment("Char [], start, number"); string str = new string(car, 1, 2); testResult &= (str == "bc"); str = new string(car, 0, 4); testResult &= (str == "abcd"); Log.Comment("Char []"); str = new string(car); testResult &= (str == "abcd"); Log.Comment("Char, number"); str = new string('\n', 33); testResult &= (str.Length == 33); for (int i = 0; i < str.Length; i++) testResult &= (str[i] == '\n'); Log.Comment("Char, string terminator known failure. "); char[] car2 = new char[] { (char)0, (char)65}; string s = new string(car2); testResult &= (s == "\0A"); Log.Comment("This was previously bug 20620"); Log.Comment("new char[0]"); str = new string(new char[0]); testResult &= (str == string.Empty); Log.Comment("null"); str = new string(null); testResult &= (str == string.Empty); return (testResult ? MFTestResults.Pass : MFTestResults.Fail); } [TestMethod] public MFTestResults CompareTo_Test3() { /// /// 1. Tests the CompareTo methods of the string type /// /// Log.Comment("Test of the CompareTo method"); bool testResult = true; string str = "hello"; object ob = "Hello"; Log.Comment("NormalCompareTo"); testResult &= (str.CompareTo((object)"hello") == 0); testResult &= (str.CompareTo(ob) > 0); testResult &= (str.CompareTo((object)"zello") < 0); Log.Comment("CompareTo null"); testResult &= (str.CompareTo((object)null) > 0); return (testResult ? MFTestResults.Pass : MFTestResults.Fail); } [TestMethod] public MFTestResults GetHashCode_Test4() { /// /// 1. Tests the GetHashCode methods of the string type /// /// Log.Comment("Test of the GetHashCode method"); bool testResult = true; string[] strs = new string[] { "abcd", "bcda", "cdab", "dabc" }; for (int i = 0; i < 4; i++) { for (int j = 0; j < 4; j++) { Log.Comment(strs[i].GetHashCode().ToString() + " - " + strs[j].GetHashCode().ToString()); if (i == j) testResult &= (strs[i].GetHashCode() == strs[j].GetHashCode()); else testResult &= (strs[i].GetHashCode() != strs[j].GetHashCode()); } } return (testResult ? MFTestResults.Pass : MFTestResults.Fail); } [TestMethod] public MFTestResults Equals_Test5() { /// /// 1. Tests the Equals methods of the string type /// /// Log.Comment("This verifies the String.Equals functionality."); Log.Comment("It compares the string value using the Equals function"); Log.Comment("to valid and invalid values as well as casted object values."); bool testResult = true; string str = "abcd"; object ob2 = "bcd"; object ob = str as object; testResult &= str.Equals(ob); Log.Comment("testResult == " + testResult.ToString()); testResult &= !str.Equals((object)123); Log.Comment("testResult == " + testResult.ToString()); testResult &= str.Equals((object)"abcd"); Log.Comment("testResult == " + testResult.ToString()); testResult &= !str.Equals((object)"bcd"); Log.Comment("testResult == " + testResult.ToString()); testResult &= !str.Equals(ob2); Log.Comment("testResult == " + testResult.ToString()); string str1 = "abc\n"; string str2 = "abcd"; string str3 = "abc\n"; testResult &= str1.Equals(str3); Log.Comment("testResult == " + testResult.ToString()); testResult &= !str1.Equals(str2); Log.Comment("testResult == " + testResult.ToString()); testResult &= str3.Equals(str1); Log.Comment("testResult == " + testResult.ToString()); testResult &= str3.Equals("abc" + "\n"); Log.Comment("testResult == " + testResult.ToString()); testResult &= str2.Equals("a" + "b" + 'c' + "d"); Log.Comment("testResult == " + testResult.ToString()); return (testResult ? MFTestResults.Pass : MFTestResults.Fail); } [TestMethod] public MFTestResults ToString_Test6() { /// /// 1. Tests the ToString method of the string type /// /// Log.Comment("Test of the ToString method"); bool testResult = true; string str = "abc"; testResult &= (str == str.ToString()); testResult &= (str == str.ToString().ToString().ToString()); testResult &= (str.ToString() == "abc"); return (testResult ? MFTestResults.Pass : MFTestResults.Fail); } [TestMethod] public MFTestResults ToCharArray_Test13() { /// /// 1. Tests the ToCharArray methods of the string type /// Epected Failure /// /// Log.Comment("Test of the ToCharArray method"); bool testResult = true; char[] car1 = new Char[] { 'a', 'b', 'c', 'd' }; char[] car2 = new Char[] { }; string str1 = "abcd"; string str2 = "abcde"; string str3 = "ABCD"; Log.Comment("With 0 args"); testResult &= (str1.ToCharArray() == car1); testResult &= (str2.ToCharArray() != car1); testResult &= (str3.ToCharArray() != car1); testResult &= (str1.ToCharArray() != car2); Log.Comment("With 1 args"); testResult &= (str1.ToCharArray(0,3) != car1); testResult &= (str2.ToCharArray(0,3) == car1); testResult &= (str3.ToCharArray(0,3) != car1); testResult &= (str1.ToCharArray(1,3) != car2); if (testResult) { Log.Comment("This failure indicates a test is now passing that previously failed by design."); Log.Comment("It previously marked as known failure because of bug # 14574"); Log.Comment("The Test owner needs to verify that the change was intentional and remove the known failure."); return MFTestResults.Fail; } else return MFTestResults.Pass; } [TestMethod] public MFTestResults Split_Test15() { /// /// 1. Tests the Split method of the string type /// /// bool testResult = true; Log.Comment("Testing the Split method"); char[] car1 = new Char[] { '@','q' }; char[] car2 = new Char[] { }; string str1 = "ab@cd"; string str2 = "abcd@"; testResult &= (str1.Split(car1)[0] == "ab"); testResult &= (str1.Split(car1)[1] == "cd"); testResult &= (str2.Split(car1)[0] == "abcd"); testResult &= (str2.Split(car1)[1] == ""); testResult &= (str1.Split(car2)[0] == "ab@cd"); Log.Comment("Verify split with a count"); Log.Comment("This is currently a known issue"); Log.Comment("20659 String.Split with a count parameter always returns the whole string."); string[] oneTwoThree = "1 2 3".Split(new char[] { ' ' }, 1); testResult &= (oneTwoThree.Length <= 1); return (testResult ? MFTestResults.Pass : MFTestResults.Fail); } [TestMethod] public MFTestResults Substring_Test17() { /// /// 1. Tests the Substring method of the string type /// /// bool testResult = true; Log.Comment("Testing the Substring method"); string str1 = "abcde"; testResult &= (str1.Substring(0) == str1); testResult &= (str1.Substring(0,5) == str1); testResult &= (str1.Substring(2) == "cde"); testResult &= (str1.Substring(2,1) == "c"); return (testResult ? MFTestResults.Pass : MFTestResults.Fail); } [TestMethod] public MFTestResults Trim_Test19() { /// /// 1. Tests the Trim method of the string type /// /// bool testResult = true; Log.Comment("Testing the Trim method"); char[] car1 = new Char[] { '@', 'q' }; string str1 = " abc@de "; string str2 = "@abc @ de@"; testResult &= (str1.Trim() == "abc@de"); testResult &= (str1.Trim(car1) == " abc@de "); testResult &= (str2.Trim() == "@abc @ de@"); testResult &= (str2.Trim(car1) == "abc @ de"); return (testResult ? MFTestResults.Pass : MFTestResults.Fail); } [TestMethod] public MFTestResults TrimStart_Test20() { /// /// 1. Tests the TrimStart method of the string type /// /// bool testResult = true; Log.Comment("Testing the TrimStart method"); char[] car1 = new Char[] { '@', 'q' }; string str1 = " abc@de "; string str2 = "@abc @ de@"; testResult &= (str1.TrimStart() == "abc@de "); testResult &= (str1.TrimStart(car1) == " abc@de "); testResult &= (str2.TrimStart() == "@abc @ de@"); testResult &= (str2.TrimStart(car1) == "abc @ de@"); //System.String _string = new System.String( ); //System.String var = _string.TrimStart( System.Char[] ); return (testResult ? MFTestResults.Pass : MFTestResults.Fail); } [TestMethod] public MFTestResults TrimEnd_Test21() { /// /// 1. Tests the TrimEnd method of the string type /// /// bool testResult = true; Log.Comment("Testing the TrimEnd method"); char[] car1 = new Char[] { '@', 'q' }; string str1 = " abc@de "; string str2 = "@abc @ de@"; testResult &= (str1.TrimEnd() == " abc@de"); testResult &= (str1.TrimEnd(car1) == " abc@de "); testResult &= (str2.TrimEnd() == "@abc @ de@"); testResult &= (str2.TrimEnd(car1) == "@abc @ de"); //System.String _string = new System.String( ); //System.String var = _string.TrimEnd( System.Char[] ); return (testResult ? MFTestResults.Pass : MFTestResults.Fail); } [TestMethod] public MFTestResults IndexOf_Test28() { /// /// 1. Tests the IndexOf method of the string type /// /// bool testResult = true; Log.Comment("Testing the IndexOf method"); string str1 = "@ abc@de "; testResult &= (str1.IndexOf('@') == 0); testResult &= (str1.IndexOf("abc") == 2); testResult &= (str1.IndexOf('@', 1) == 5); testResult &= (str1.IndexOf('@', 1, 1) == -1); testResult &= (str1.IndexOf("abc",2) == 2); testResult &= (str1.IndexOf("abc", 1,1) == -1); return (testResult ? MFTestResults.Pass : MFTestResults.Fail); } [TestMethod] public MFTestResults IndexOfAny_Test31() { /// /// 1. Tests the IndexOfAny method of the string type /// /// bool testResult = true; Log.Comment("Testing the IndexOfAny method"); string str1 = "@ abc@de "; char[] car1 = new Char[] { '@', 'b' }; testResult &= (str1.IndexOfAny(car1) == 0); testResult &= (str1.IndexOfAny(car1, 1) == 3); testResult &= (str1.IndexOfAny(car1, 2, 1) == -1); return (testResult ? MFTestResults.Pass : MFTestResults.Fail); } [TestMethod] public MFTestResults LastIndexOf_Test37() { /// /// 1. Tests the LastIndexOf method of the string type /// /// bool testResult = true; Log.Comment("Testing the LastIndexOf method"); string str1 = "@ abc@de "; testResult &= (str1.LastIndexOf('@') == 5); testResult &= (str1.LastIndexOf("abc") == 2); testResult &= (str1.LastIndexOf('@', 1) == 5); testResult &= (str1.LastIndexOf('@', 1, 1) == -1); testResult &= (str1.LastIndexOf("abc", 2) == 2); testResult &= (str1.LastIndexOf("@", 6, 1) == -1); return (testResult ? MFTestResults.Pass : MFTestResults.Fail); } [TestMethod] public MFTestResults LastIndexOfAny_Test40() { /// /// 1. Tests the LastIndexOfAny method of the string type /// /// bool testResult = true; Log.Comment("Testing the LastIndexOfAny method"); string str1 = "@ abc@de "; char[] car1 = new Char[] { '@', 'b' }; testResult &= (str1.LastIndexOfAny(car1) == 5); testResult &= (str1.LastIndexOfAny(car1, 1) == 5); testResult &= (str1.LastIndexOfAny(car1, 4, 1) == -1); return (testResult ? MFTestResults.Pass : MFTestResults.Fail); } [TestMethod] public MFTestResults ToLower_Test51() { /// /// 1. Tests the ToLower method of the string type /// /// bool testResult = true; Log.Comment("Testing the ToLower method"); string str1 = "@ ABC@de "; testResult &= (str1.ToLower() == "@ abc@de "); return (testResult ? MFTestResults.Pass : MFTestResults.Fail); } [TestMethod] public MFTestResults ToUpper_Test52() { /// /// 1. Tests the ToUpper method of the string type /// /// bool testResult = true; Log.Comment("Testing the ToUpper method"); ; string str1 = "@ ABC@de "; testResult &= (str1.ToUpper() == "@ ABC@DE "); return (testResult ? MFTestResults.Pass : MFTestResults.Fail); } [TestMethod] public MFTestResults Length_Test71() { /// /// 1. Tests the Length property of the string type /// /// bool testResult = true; Log.Comment("Testing the Length property"); ; string str1 = "@ ABC@de "; testResult &= (str1.Length == 9); return (testResult ? MFTestResults.Pass : MFTestResults.Fail); } [TestMethod] public MFTestResults Concat_Test1() { /// /// 1. Tests the string concat of several object where one of the arguments returns a null value for ToString() /// /// try { string str = "a" + 1 + "b" + new ToStringReturnsNull(); return (str == "a1b" ? MFTestResults.Pass : MFTestResults.Fail); } catch { return MFTestResults.Fail; } } } /// /// A class whose ToString method return null /// public class ToStringReturnsNull { public override string ToString() { return null; } } } ================================================ FILE: Zelig/Zelig/Test/RunTime/NETMF/mscorlib/systemlib/systemlib2/SystemTypeTests.cs ================================================ //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // Copyright (c) Microsoft Corporation. All rights reserved. //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// using System; using System.Reflection; using Microsoft.SPOT.Platform.Test; namespace Microsoft.SPOT.Platform.Tests { public class SystemTypeTests : IMFTestInterface { [SetUp] public InitializeResult Initialize() { Log.Comment("Adding set up for the tests."); // Add your functionality here. Log.Comment("These tests examine the System.Type methods and properties"); return InitializeResult.ReadyToGo; } [TearDown] public void CleanUp() { Log.Comment("Cleaning up after the tests"); } //SystemType Test methods interface iEmpty{ } class TestObject1{ } class TestObject2 : iEmpty { public TestObject2(Int32 i) { m_data = (int)i; } public int m_data; class m_subTestObject { } public void Method1() { } public Int32 Method2(Int32 I) { return I; } } [TestMethod] public MFTestResults Number_ToString_Test() { bool bRet = true; // if the negative number can not be truncated to the range specified it // will display its full hex value bRet &= "FE" == ((sbyte ) -2).ToString("x02"); bRet &= "36" == ((byte ) 0x36).ToString("x02"); bRet &= "FF" == ((byte ) 255).ToString("X2"); bRet &= "FFFD" == ((short ) -3).ToString("x04"); bRet &= "3049" == ((ushort) 0x3049).ToString("x4"); bRet &= "FC00" == ((short ) -1024).ToString("x02"); bRet &= "FFFFFFFC" == ((int ) -4).ToString("x8"); bRet &= "00004494" == ((uint ) 0x4494).ToString("x8"); bRet &= "FFFFFFFC" == ((int ) -4).ToString("x04"); bRet &= "FFFFFFFFFFFFFFFB" == ((long ) -5).ToString("x016"); bRet &= "1234567890123456" == ((ulong )0x1234567890123456).ToString("x16"); // you should not be able to truncate the value only leading zeros bRet &= "1234567890123456" == ((ulong )0x1234567890123456).ToString("x06"); bRet &= "34567890123456" == ((ulong )0x0034567890123456).ToString("x14"); string tst = 3210.ToString("D"); bRet &= "3210" == tst; tst = (-3210).ToString("d"); bRet &= "-3210" == tst; tst = 3210.ToString("d06"); bRet &= "003210" == tst; tst = (-3210).ToString("d06"); bRet &= "-003210" == tst; tst = 3210.ToString("d1"); bRet &= "3210" == tst; tst = (-3210).ToString("d1"); bRet &= "-3210" == tst; tst = 3210.ToString("g"); bRet &= "3210" == tst; tst = (-3210).ToString("g"); bRet &= "-3210" == tst; bRet &= "NaN" == ((float)0f / 0f).ToString(); bRet &= "Infinity" == ((float)1f / 0f).ToString(); bRet &= "-Infinity" == ((float)-1f / 0f).ToString(); bRet &= "NaN" == ((double)0f / 0f).ToString(); bRet &= "Infinity" == ((double)1f / 0f).ToString(); bRet &= "-Infinity" == ((double)-1f / 0f).ToString(); if (bRet) { return MFTestResults.Pass; } return MFTestResults.Fail; } [TestMethod] public MFTestResults SystemType1_GetType_Test() { /// /// 1. Tests the GetType(String) method /// 2. Tests the GetType() method /// /// bool testResult = true; try { Int32 testInt32 = 0; Assembly Int32Assm = Assembly.Load("mscorlib"); Log.Comment("This tests the Assembly.GetType(String) by passing \"Namespace.Class\""); Type myType0 = Int32Assm.GetType("System.Int32"); Log.Comment("The full name is " + myType0.FullName); testResult &= (myType0 == testInt32.GetType()); Log.Comment("This tests the Type.GetType(String) by passing \"Namespace.Class\""); Type myType1 = Type.GetType("System.Int32"); Log.Comment("The full name is " + myType1.FullName); testResult &= (myType1 == testInt32.GetType()); Log.Comment("This tests the Type.GetType(String) by passing \"Namespace.Class, assembly\""); Type myType2 = Type.GetType("System.Int32, mscorlib"); Log.Comment("The full name is " + myType2.FullName); testResult &= (myType2 == testInt32.GetType()); Log.Comment("This tests the Type.GetType(String) by passing \"Namespace.Class, assembly, Version=\"a.b.c.d\"\""); string typeName3 = "System.Int32, mscorlib, Version=" + Int32Assm.GetName().Version.ToString(); Type myType3 = Type.GetType(typeName3); Log.Comment("The full name is " + myType3.FullName); testResult &= (myType3 == testInt32.GetType()); Log.Comment("This tests the Type.GetType() method for nested classes"); TestObject1 testTestObject1 = new TestObject1(); Type myType4 = testTestObject1.GetType(); Log.Comment("The full name is " + myType4.FullName); testResult &= (myType4 == Type.GetType("Microsoft.SPOT.Platform.Tests.SystemTypeTests+TestObject1")); Log.Comment("Since NoneSuch does not exist in this assembly, "); Log.Comment("GetType throws a TypeLoadException."); Type myType5 = Type.GetType("NoneSuch"); Log.Comment("The full name is " + myType5.FullName); } catch (Exception e) { Log.Comment("Typeless " + e.Message); } return (testResult ? MFTestResults.Pass : MFTestResults.Fail); } [TestMethod] public MFTestResults SystemType1_Type_Names_Test() { /// /// 1. Tests the Name(String) method /// 2. Tests the AssemblyQualifiedName() method /// /// bool testResult = false; try { Assembly Int32Assm = Assembly.Load("mscorlib"); // types must be the same whereexver they come from Type myType0 = Int32Assm.GetType("System.Int32"); Type myType1 = Type.GetType("System.Int32"); if (myType0 == myType1) { // names must be compatible and composable if (myType0.Name == myType1.Name) { // names must be compatible and composable if (myType0.FullName == myType1.FullName) { // assembly must be the same if (myType0.Assembly == myType1.Assembly) { // type must come from assembly it is supposed to come from if (Int32Assm == myType0.Assembly) { // verify that the long name is corrent string fullAssmName = Int32Assm.FullName; if (myType0.AssemblyQualifiedName == (myType0.FullName + ", " + fullAssmName)) { testResult = true; } } } } } } } catch (Exception e) { Log.Comment("Exception caught " + e.Message); } return (testResult ? MFTestResults.Pass : MFTestResults.Fail); } [TestMethod] public MFTestResults SystemType2_Assembly_Test() { /// /// 1. Tests the Assembly property for system and user defined types /// Fails if exception thrown /// /// bool testResult = true; try { Log.Comment("This tests the Assembly property"); //Assigned and manipulated to avoid compiler warning Int32 testInt32 = -1; testInt32++; Type myType1 = Type.GetType("System.Int32"); Log.Comment("The full name is " + myType1.Assembly.FullName); testResult &= (myType1.Assembly.FullName == "mscorlib, Version=" + myType1.Assembly.GetName().Version.ToString()); TestObject1 testTestObject1 = new TestObject1(); Type myType2 = testTestObject1.GetType(); Log.Comment("The full name is " + myType2.Assembly.FullName); testResult &= (myType2.Assembly.FullName == "Microsoft.SPOT.Platform.Tests.Systemlib2, Version=" + myType2.Assembly.GetName().Version.ToString()); } catch (Exception e) { Log.Comment("Typeless " + e.Message); testResult = false; } return (testResult ? MFTestResults.Pass : MFTestResults.Fail); } [TestMethod] public MFTestResults SystemType3_BaseType_Test() { /// /// 1. Tests the BaseType property for system and user defined types /// /// bool testResult = true; try { Log.Comment("This tests the BaseType() method"); //Assigned and manipulated to avoid compiler warning Int32 testInt32 = -1; testInt32++; Type myType1 = Type.GetType("System.Int32"); Log.Comment("The full name is " + myType1.FullName); testResult &= (myType1.BaseType == Type.GetType("System.ValueType")); TestObject1 testTestObject1 = new TestObject1(); Type myType2 = testTestObject1.GetType(); Log.Comment("The full name is " + myType2.FullName); testResult &= (myType2.BaseType == Type.GetType("System.Object")); } catch (Exception e) { Log.Comment("Typeless " + e.Message); testResult = false; } return (testResult ? MFTestResults.Pass : MFTestResults.Fail); } [TestMethod] public MFTestResults SystemType4_DeclaringType_Test() { /// /// 1. Tests the BaseType DeclaringType for system and user defined types /// /// bool testResult = true; try { Log.Comment("This tests the DeclaringType property"); //Assigned and manipulated to avoid compiler warning Int32 testInt32 = -1; testInt32++; Type myType1 = Type.GetType("System.Int32"); Log.Comment("The full name is " + myType1.FullName); testResult &= (myType1.DeclaringType == null); TestObject1 testTestObject1 = new TestObject1(); Type myType2 = testTestObject1.GetType(); Log.Comment("The full name is " + myType2.FullName); Type myType3 = this.GetType(); testResult &= (myType2.DeclaringType == myType3); } catch (Exception e) { Log.Comment("Typeless " + e.Message); testResult = false; } return (testResult ? MFTestResults.Pass : MFTestResults.Fail); } [TestMethod] public MFTestResults SystemType5_GetConstructor_Test() { /// /// 1. Tests the GetConstructor(Type[]) method for a user defined type /// /// bool testResult = true; try { Log.Comment("This tests the GetConstructor(Type[]) method"); TestObject2 testTestObject2 = new TestObject2(5); Type myType2 = testTestObject2.GetType(); Log.Comment("The full name is " + myType2.FullName); Type[] typeOfInt32Arr = new Type[] { Type.GetType("System.Int32") }; object[] value5Arr = new object[] { 5 }; TestObject2 testTestObject3 = (TestObject2)myType2.GetConstructor(typeOfInt32Arr).Invoke(value5Arr); testResult &= (testTestObject2.m_data == testTestObject3.m_data); } catch (Exception e) { Log.Comment("Typeless " + e.Message); testResult = false; } return (testResult ? MFTestResults.Pass : MFTestResults.Fail); } [TestMethod] public MFTestResults SystemType6_GetElementType_Test() { /// /// 1. Tests the GetElementType() method for a user defined type /// /// bool testResult = true; try { Log.Comment("This tests the GetElementType() method"); //Assigned and manipulated to avoid compiler warning Int32 testInt32 = -1; testInt32++; Type myType1 = Type.GetType("System.Int32"); Log.Comment("The full name is " + myType1.FullName); Int32[] int32Arr = new Int32[] { }; Type int32ArrType = int32Arr.GetType(); testResult &= (myType1 == int32ArrType.GetElementType()); testResult &= (myType1.GetElementType() == null); } catch (Exception e) { Log.Comment("Typeless " + e.Message); testResult = false; } return (testResult ? MFTestResults.Pass : MFTestResults.Fail); } [TestMethod] public MFTestResults SystemType7_GetField_Test() { /// /// 1. Test the GetField(String) method /// 2. Test the GetField(String,BindingFlags) method /// TODO: Expand test #2 once bug 17246 is resolved /// /// bool testResult = true; try { Log.Comment("This tests the GetField(String) "); Log.Comment("and the GetField(String,BindingFlags) methods)"); Log.Comment("Currently this test fails, see 17246 for more details."); Type myType1 = Type.GetType("System.Int32"); Log.Comment("The full name is " + myType1.FullName); testResult &= (myType1.GetField("m_data") == null); Log.Comment(" TestObject2 type has one data member \"m_data\" of type Int32."); TestObject2 testTestObject2 = new TestObject2(5); Type myType2 = testTestObject2.GetType(); Log.Comment("The full name is " + myType2.FullName); Log.Comment(" Check that type of m_data is Int32"); testResult &= (myType2.GetField("m_data", BindingFlags.GetField | BindingFlags.Public | BindingFlags.Instance).FieldType == myType1); Log.Comment(" Check that value in m_data is 5 ( becuase we called new TestObject2(5))"); testResult &= ((int)myType2.GetField("m_data", BindingFlags.IgnoreCase | BindingFlags.GetField | BindingFlags.Public | BindingFlags.Instance).GetValue(testTestObject2) == 5); if ( !testResult ) { Log.Exception( " Last test failed " ); } Log.Comment(" Check that m_data is a field"); testResult &= (myType2.GetField("m_data").MemberType == MemberTypes.Field); if (!testResult) { Log.Exception(" Last test failed "); } Log.Comment(" Check that field m_data has Name \"m_data\""); testResult &= (myType2.GetField("m_data").Name == "m_data"); if (!testResult) { Log.Exception(" Last test failed "); } Log.Comment(" Check that misspelling of m_data return NULL."); testResult &= null == myType2.GetField("data"); if (!testResult) { Log.Exception(" Last test failed "); } Log.Comment(" Checks that case misspelling of m_data return NULL if flag BindingFlags.IgnoreCase not specified."); testResult &= null == myType2.GetField("m_Data"); if (!testResult) { Log.Exception(" Last test failed "); } Log.Comment("Check retrieval with BindingFlags.IgnoreCase. If flag BindingFlags.IgnoreCase is ised, then the case should be ignored. We should get the same type information."); FieldInfo fInfo_m_Data = myType2.GetField("m_Data", BindingFlags.IgnoreCase | BindingFlags.GetField | BindingFlags.Public | BindingFlags.Instance); FieldInfo fInfo_m_data = myType2.GetField("m_data"); testResult &= fInfo_m_Data != null && fInfo_m_data != null; testResult &= fInfo_m_Data.Name.Equals( fInfo_m_data.Name ); if (!testResult) { Log.Exception(" Last test failed "); } Log.Comment(" Indirectly set m_data in testTestObject2 to 6 and then check it."); myType2.GetField("m_data").SetValue(testTestObject2, 6); testResult &= ((int)myType2.GetField("m_data").GetValue(testTestObject2) == 6); testResult &= testTestObject2.m_data == 6; if (!testResult) { Log.Exception(" Last test failed "); } } // In case of exceptions we log it and set testResult = false; catch (NullReferenceException e) { Log.Comment("NullRef " + e.Message); testResult = false; } catch (Exception e) { Log.Comment("Typeless " + e.Message); testResult = false; } return (testResult ? MFTestResults.Pass : MFTestResults.Fail); } [TestMethod] public MFTestResults SystemType8_GetFields_Test() { /// /// 1. Test the GetFields(String) method /// 2. Test the GetFields(String,BindingFlags) method /// This test is currently a stub /// TODO: Write test #2 once bug 17246 is resolved /// /// bool testResult = true; try { Log.Comment("This tests the GetFields(String) method"); Log.Comment("This test must be re-written once BindingFlags is working, "); Log.Comment("see 17246 for more details."); Type myType1 = Type.GetType("System.Int32"); Log.Comment("The full name is " + myType1.FullName); testResult &= (myType1.GetField("m_data") == null); TestObject2 testTestObject2 = new TestObject2(5); Type myType2 = testTestObject2.GetType(); Log.Comment("The full name is " + myType2.FullName); testResult &= (myType2.GetField("m_data").FieldType == myType1); testResult &= ((int)myType2.GetField("m_data").GetValue(testTestObject2) == 5); testResult &= (myType2.GetField("m_data").MemberType == MemberTypes.Field); testResult &= (myType2.GetField("m_data").Name == "m_data"); myType2.GetField("m_data").SetValue(testTestObject2, 6); testResult &= ((int)myType2.GetField("m_data").GetValue(testTestObject2) == 6); } catch (Exception e) { Log.Comment("Typeless " + e.Message); testResult = false; } return (testResult ? MFTestResults.Pass : MFTestResults.Fail); } [TestMethod] public MFTestResults SystemType9_GetInterfaces_Test() { /// /// 1. Test the GetInterfaces(String) method /// 2. Test the GetInterfaces(String,BindingFlags) method /// This test is currently a stub /// TODO: Write test #2 once bug 17246 is resolved /// /// bool testResult = true; try { Log.Comment("This tests the GetInterfaces() method"); Log.Comment("This test must be re-written once BindingFlags is working, "); Log.Comment("see 17246 for more details."); Type myType1 = Type.GetType("System.Int32"); Log.Comment("The full name is " + myType1.FullName); testResult &= (myType1.GetInterfaces().Length == 0); TestObject2 testTestObject2 = new TestObject2(5); Type myType2 = testTestObject2.GetType(); Log.Comment("The full name is " + myType2.FullName); Type myType3 = Type.GetType("Microsoft.SPOT.Platform.Tests.SystemTypeTests+iEmpty"); testResult &= (myType2.GetInterfaces()[0] == myType3); } catch (Exception e) { Log.Comment("Typeless " + e.Message); testResult = false; } return (testResult ? MFTestResults.Pass : MFTestResults.Fail); } [TestMethod] public MFTestResults SystemType10_GetMethod_Test() { /// /// 1. Test the GetMethod(String) method /// 2. Test the GetMethod(String,BindingFlags) method /// This test is currently a stub /// TODO: Write test #2 once bug 17246 is resolved /// /// bool testResult = true; try { Log.Comment("This tests the GetMethod(String) method"); Log.Comment("This test must be re-written once BindingFlags is working, "); Log.Comment("see 17246 for more details."); Int32 I = 0; I++; TestObject2 testTestObject2 = new TestObject2(5); Type myType2 = testTestObject2.GetType(); Log.Comment("The full name is " + myType2.FullName); MethodInfo methodInfo1 = myType2.GetMethod("Method2"); testResult &= (methodInfo1.IsAbstract == false); testResult &= (methodInfo1.IsFinal == false); testResult &= (methodInfo1.IsPublic == true); testResult &= (methodInfo1.IsStatic == false); testResult &= (methodInfo1.IsVirtual == false); testResult &= (methodInfo1.MemberType == MemberTypes.Method); testResult &= (methodInfo1.Name == "Method2"); testResult &= (methodInfo1.ReturnType == I.GetType()); testResult &= (methodInfo1.DeclaringType == myType2); testResult &= ((int)(methodInfo1.Invoke(testTestObject2, new object[] { 1 })) == 1); } catch (Exception e) { Log.Comment("Typeless " + e.Message); testResult = false; } return (testResult ? MFTestResults.Pass : MFTestResults.Fail); } [TestMethod] public MFTestResults SystemType11_GetMethods_Test() { /// /// 1. Test the GetMethods(String) method /// 2. Test the GetMethods(String,BindingFlags) method /// This test is currently a stub /// TODO: Write test #2 once bug 17246 is resolved /// /// bool testResult = true; try { Log.Comment("This tests the GetMethods() method"); Log.Comment("This test must be re-written once BindingFlags is working, "); Log.Comment("see 17246 for more details."); //Assigned and manipulated to avoid compiler warning Int32 I = 0; I++; TestObject2 testTestObject2 = new TestObject2(5); Type myType2 = testTestObject2.GetType(); Log.Comment("The full name is " + myType2.FullName); MethodInfo[] methodInfoArr1 = myType2.GetMethods(); MethodInfo methodInfo1 = null; if (methodInfoArr1[0].Name == "Method2") { methodInfo1 = methodInfoArr1[0]; Log.Comment("Method2 found in position 0"); } else if (methodInfoArr1[1].Name == "Method2") { methodInfo1 = methodInfoArr1[1]; Log.Comment("Method2 found in position 1"); } testResult &= (methodInfo1.IsAbstract == false); testResult &= (methodInfo1.IsFinal == false); testResult &= (methodInfo1.IsPublic == true); testResult &= (methodInfo1.IsStatic == false); testResult &= (methodInfo1.IsVirtual == false); testResult &= (methodInfo1.MemberType == MemberTypes.Method); testResult &= (methodInfo1.Name == "Method2"); testResult &= (methodInfo1.ReturnType == I.GetType()); testResult &= (methodInfo1.DeclaringType == myType2); testResult &= ((int)(methodInfo1.Invoke(testTestObject2, new object[] { 1 })) == 1); } catch (Exception e) { Log.Comment("Typeless " + e.Message); testResult = false; } return (testResult ? MFTestResults.Pass : MFTestResults.Fail); } [TestMethod] public MFTestResults SystemType12_InvokeMember_Test() { /// /// 1. Test the InvokeMember(String,BindingFlags) method /// This test is currently a stub /// TODO: expand test #1 once bug 17246 is resolved /// /// bool testResult = true; try { Log.Comment("This tests the InvokeMember(String,BindingFlags) method"); Log.Comment("This test must be re-written once BindingFlags is working, "); Log.Comment("see 17246 for more details."); //Assigned and manipulated to avoid compiler warning Int32 I = 0; I++; TestObject2 testTestObject2 = new TestObject2(5); Type myType2 = testTestObject2.GetType(); Log.Comment("The full name is " + myType2.FullName); testResult &= ((int)myType2.InvokeMember("Method2", BindingFlags.Default | BindingFlags.InvokeMethod, null, testTestObject2, new object[] { -6 }) == -6); } catch (NotImplementedException) { return MFTestResults.KnownFailure; } catch (Exception e) { Log.Comment("Typeless " + e.Message); testResult = false; } return (testResult ? MFTestResults.Pass : MFTestResults.Fail); } } } ================================================ FILE: Zelig/Zelig/Test/RunTime/NETMF/mscorlib/systemlib/systemlib2/SystemWeakReferenceTests.cs ================================================ //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // Copyright (c) Microsoft Corporation. All rights reserved. //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// using System; using System.Reflection; using Microsoft.SPOT.Platform.Test; using System.Threading; namespace Microsoft.SPOT.Platform.Tests { public class SystemWeakReferenceTests : IMFTestInterface { [SetUp] public InitializeResult Initialize() { Log.Comment("Adding set up for the tests"); return InitializeResult.ReadyToGo; } [TearDown] public void CleanUp() { Log.Comment("Cleaning up after the tests"); } //WeakRef Test methods static bool hasFinalized1 = false; public class WeakRefClass { public int data = 5; public WeakRefClass(){ } ~WeakRefClass() { Log.Comment("Finalized."); hasFinalized1 = true; } void MakeSomeGarbage() { // Create objects and release them // to fill up memory with unused objects. object junk; for (int i = 0; i < 10000; i++) { junk = new object(); } } } [TestMethod] public MFTestResults WeakRef1_Test() { /// /// 1. Create an object with strong ref /// 2. Create a short weak ref to the onject /// 3. Allow for GC /// 4. Verify & Remove Strong reference /// 5. Allow for GC /// 6. If weak ref surivived verify its data /// /// bool testResult = true; Log.Comment("Create an object with strong ref"); WeakRefClass WRC1 = new WeakRefClass(); Log.Comment("Create a short weak ref to the onject"); WeakReference wr = new WeakReference(WRC1); wr.Target = WRC1; Log.Comment("Allow for GC"); SPOT.Debug.GC(true); int sleepTime = 1000; int slept = 0; while (!hasFinalized1 && slept < sleepTime) { System.Threading.Thread.Sleep(10); slept += 10; } Log.Comment("GC took " + slept); testResult &= (!hasFinalized1); Log.Comment("Verify & Remove Strong reference"); testResult &= (((WeakRefClass)wr.Target).data == 5); WRC1 = null; if (WRC1 == null) { Log.Comment("After setting WRC1 to null: WRC1 is null."); } else { testResult = false; } Log.Comment("Allow for GC"); SPOT.Debug.GC(true); sleepTime = 1000; slept = 0; while (!hasFinalized1 && slept < sleepTime) { System.Threading.Thread.Sleep(10); slept += 10; } Log.Comment("GC took " + slept); testResult &= (hasFinalized1); testResult &= (WRC1 == null); if (wr.IsAlive) { testResult &= (((WeakRefClass)wr.Target).data == 5); Log.Comment("Weak Reference survived."); } else { Log.Comment("Weak Reference has been collected"); } return (testResult ? MFTestResults.Pass : MFTestResults.Fail); } } } ================================================ FILE: Zelig/Zelig/Test/RunTime/NETMF/mscorlib/systemlib/systemlib2/Utf8EncodingTests.cs ================================================ //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // Copyright (c) Microsoft Corporation. All rights reserved. //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// using System; using System.Text; using System.Threading; using Microsoft.SPOT.Platform.Test; namespace Microsoft.SPOT.Platform.Tests { public class Utf8EncodingTests : IMFTestInterface { [SetUp] public InitializeResult Initialize() { Log.Comment("Adding set up for the tests"); return InitializeResult.ReadyToGo; } [TearDown] public void CleanUp() { Log.Comment("Cleaning up after the tests"); } [TestMethod] public MFTestResults Utf8EncodingTests_Test1() { bool result = true; string str = "this is a normal string that will be used to convert to bytes then back to a string"; byte[] data = new byte[128]; int len = str.Length; int idx = 0; Random rand = new System.Random(); int cBytes = 0; while(len > 0) { int size = (len <= 2) ? len : rand.Next(len/2) + 1; len -= size; int cnt = UTF8Encoding.UTF8.GetBytes(str, idx, size, data, cBytes); result &= str.Substring(idx, size) == new string(UTF8Encoding.UTF8.GetChars(data, cBytes, cnt)); cBytes += cnt; idx += size; } result &= cBytes == str.Length; string strAfter = new string(UTF8Encoding.UTF8.GetChars(data, 0, cBytes)); result &= (str == strAfter); return result ? MFTestResults.Pass : MFTestResults.Fail; } [TestMethod] public MFTestResults Utf8EncodingTests_Test2() { bool result = true; string str = "this is a normal string that will be used to convert to bytes then back to a string"; byte[] data = UTF8Encoding.UTF8.GetBytes(str); result &= data.Length == str.Length; string strAfter = new string(UTF8Encoding.UTF8.GetChars(data)); result &= (str == strAfter); return result ? MFTestResults.Pass : MFTestResults.Fail; } [TestMethod] public MFTestResults Utf8EncodingTests_Test3() { // This tests involves a string with a special character bool result = true; string str = "AB\u010DAB"; byte[] data = new byte[4]; int count = UTF8Encoding.UTF8.GetBytes(str, 1, 3, data, 0); result &= count == 4; result &= (new string(UTF8Encoding.UTF8.GetChars(data)) == "B\u010DA"); return result ? MFTestResults.Pass : MFTestResults.Fail; } } } ================================================ FILE: Zelig/Zelig/Test/RunTime/NETMF/mscorlib/threads/threads1/ThreadTests.cs ================================================ //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // Copyright (c) Microsoft Corporation. All rights reserved. //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// using System; using System.Reflection; using Microsoft.SPOT.Platform.Test; using System.Threading; namespace Microsoft.SPOT.Platform.Tests { public class ThreadTests : IMFTestInterface { [SetUp] public InitializeResult Initialize() { Log.Comment("Adding set up for the tests"); return InitializeResult.ReadyToGo; } [TearDown] public void CleanUp() { Log.Comment("Cleaning up after the tests"); Thread.Sleep(1000); } //Threading Test methods class Work { public static void DoWork() { Thread.Sleep(300); Log.Comment("Static thread procedure DoWork."); Thread.Sleep(300); } public int m_data = 0; public Thread currThread; public void DoMoreWork() { Log.Comment("Instance thread procedure DoMoreWork. Data= " + m_data); currThread = Thread.CurrentThread; } public static void DoWorkAbort() { Thread.Sleep(300); Log.Comment("Static thread procedure DoWorkAbort."); Thread.Sleep(10000); } public Thread m_toJoin = null; public void DoWorkJoin() { m_toJoin.Join(); Log.Comment("Instance thread procedure DoWorkJoin."); } public static bool hasAborted = false; public static void DoWorkThreadAbortException() { while (!hasAborted) { try { while (true) ; } catch (ThreadAbortException e) { hasAborted = true; Log.Comment("Thread State = " + Thread.CurrentThread.ThreadState); Log.Comment("verifying ThreadAbortException named " + e.ToString() + " is thrown"); } } } public static bool run = false; public void DoWorkThreadState() { while (run) ; } } [TestMethod] public MFTestResults Threading_Basic_Test1() { /// /// 1. Starts two threads /// 2. Verifies that they execute in a reasonable time /// /// MFTestResults testResult = MFTestResults.Pass; Log.Comment("Starting a thread without explicit declaration of ThreadStart Delegate"); Log.Comment("Starts two threads, waits for them to complete and passes, "); Log.Comment("this may erroneously fail for extremely slow devices."); Log.Comment("All other threading tests are dependant on this, if this fails, "); Log.Comment("all other results are invalid."); Log.Comment("Starting thread 1"); Thread newThread1 = new Thread(Work.DoWork); newThread1.Start(); Log.Comment("Starting thread 2"); Work w = new Work(); w.m_data = 42; Thread newThread2 = new Thread(w.DoMoreWork); newThread2.Start(); Thread.Sleep(1); Log.Comment("Waiting for them to finish"); int slept = 0; while ((newThread1.ThreadState != ThreadState.Stopped || newThread2.ThreadState != ThreadState.Stopped) && slept < 1000) { Thread.Sleep(100); slept += 100; } if (!(newThread1.ThreadState == ThreadState.Stopped && newThread2.ThreadState == ThreadState.Stopped)) { Log.Comment("The threads took more than 1000msec to come to Stopped state"); testResult = MFTestResults.Fail; } return testResult; } [TestMethod] public MFTestResults Threading_ThreadStart_Test2() { /// /// 1. Starts two threads with ThreadStart Delegate, /// 2. Verifies that they execute in a reasonable time /// /// MFTestResults testResult = MFTestResults.Pass; Log.Comment("Starts two threads with ThreadStart Delegate,"); Log.Comment("waits for them to complete and passes, "); Log.Comment("this may erroneously fail for extremely slow devices."); Log.Comment("This explicit declaration is not necessary as of .Net 2.0"); ThreadStart threadDelegate = new ThreadStart(Work.DoWork); Thread newThread1 = new Thread(threadDelegate); Log.Comment("Starting thread 1"); newThread1.Start(); Work w = new Work(); w.m_data = 42; threadDelegate = new ThreadStart(w.DoMoreWork); Thread newThread2 = new Thread(threadDelegate); Log.Comment("Starting thread 2"); newThread2.Start(); Thread.Sleep(1); Log.Comment("Waiting for them to complete"); int slept = 0; while ((newThread1.ThreadState != ThreadState.Stopped || newThread2.ThreadState != ThreadState.Stopped) && slept < 1000) { Thread.Sleep(100); slept += 100; } if (!(newThread1.ThreadState == ThreadState.Stopped && newThread2.ThreadState == ThreadState.Stopped)) { Log.Comment("The threads took more than 1000msec to come to Stopped state"); testResult = MFTestResults.Fail; } return testResult; } [TestMethod] public MFTestResults Threading_Abort_Test3() { /// /// 1. Starts two threads one of which has a very long execution time /// 2. Calls Abort on the long thread /// 3. Verifies that the aborted thread stops immediately /// 4. Verifies that the short thread finishes normally /// /// MFTestResults testResult = MFTestResults.Pass; Log.Comment("Starting long thread"); Thread newThread1 = new Thread(Work.DoWorkAbort); newThread1.Start(); Log.Comment("Starting short thread"); Work w = new Work(); w.m_data = 42; Thread newThread2 = new Thread(w.DoMoreWork); newThread2.Start(); Thread.Sleep(1); Log.Comment("Aborting long thread and verifying it's Aborted"); newThread1.Abort(); ThreadState tState = newThread1.ThreadState; if (tState != ThreadState.Aborted && newThread1.ThreadState != ThreadState.Stopped) { Log.Comment("Expected long thread state Aborted/Stopped '" + ThreadState.Aborted + "/" + ThreadState.Stopped + "' but got '" + tState + "'"); testResult = MFTestResults.Fail; } int slept = 0; Log.Comment("Waiting for 1 or both threads to finish"); while ((newThread1.ThreadState != ThreadState.Stopped || newThread2.ThreadState != ThreadState.Stopped) && slept < 1000) { Thread.Sleep(100); slept += 100; } ThreadState tState1 = newThread1.ThreadState, tState2 = newThread2.ThreadState; if (tState1 != ThreadState.Stopped || tState2 != ThreadState.Stopped) { Log.Comment("Expected both threads in Stopped state '" + ThreadState.Stopped + "' but got Thread1 in '" + tState1 + "' and Thread2 in '" + tState2 + "'"); testResult = MFTestResults.Fail; } Log.Comment("This is Fixed, see 17343 for details"); return testResult; } [TestMethod] public MFTestResults Threading_IsAlive_Test4() { /// /// 1. Starts two threads one of which has a very long execution time /// 2. Calls Abort() on the long thread /// 3. Verifies that the aborted thread stops immediately using the IsAlive Property /// 4. Verifies that the short thread finishes normally using the IsAlive Property /// /// MFTestResults testResult = MFTestResults.Pass; Log.Comment("Starts two threads, aborts one and verifies the IsAlive property, "); Log.Comment("this may erroneously fail for extremely slow devices."); Log.Comment("Starting long thread and verifying it's alive"); Thread newThread1 = new Thread(Work.DoWorkAbort); newThread1.Start(); Log.Comment("Starting short thread"); Work w = new Work(); w.m_data = 42; Thread newThread2 = new Thread(w.DoMoreWork); newThread2.Start(); if (!newThread1.IsAlive) { Log.Comment("Long thread not alive"); testResult = MFTestResults.Fail; } Log.Comment("Aborting long thread, waiting and verifying both threads are dead"); newThread1.Abort(); int slept = 0; while ((newThread1.IsAlive || newThread2.IsAlive) && slept < 1000) { Thread.Sleep(100); slept += 100; } if (newThread1.IsAlive || newThread2.IsAlive) { Log.Comment("Expected both threads dead but got long thread '" + newThread1.ThreadState + "' and short thread '" + newThread2.ThreadState + "'"); testResult = MFTestResults.Fail; } return testResult; } [TestMethod] public MFTestResults Threading_Join_Test5() { /// /// 1. Starts a thread /// 2. Starts a second thread that Join()s the first /// 3. Verifies that they finish in a reasonable amount of time /// /// MFTestResults testResult = MFTestResults.Pass; Log.Comment("Starts two threads, the second thread Join()s the first"); Log.Comment("Verifies they finish in a reasonable amount of time"); Log.Comment("this may erroneously fail for extremely slow or fast devices."); Thread newThread1 = new Thread(Work.DoWork); newThread1.Start(); Work w = new Work(); w.m_data = 42; w.m_toJoin = newThread1; Thread newThread2 = new Thread(w.DoWorkJoin); newThread2.Start(); Thread.Sleep(1); int slept = 0; while (newThread2.IsAlive && slept < 1000) { Thread.Sleep(100); slept += 100; } if (newThread1.IsAlive || newThread2.IsAlive) { Log.Comment("Expected both threads dead but got thread1 '" + newThread1.ThreadState + "' and thread2 '" + newThread2.ThreadState + "'"); testResult = MFTestResults.Fail; } return testResult; } static class PriorityTest { static public ManualResetEvent loopSwitch = new ManualResetEvent(false); static public ManualResetEvent startSecond = new ManualResetEvent(false); static public ManualResetEvent keepAlive = new ManualResetEvent(false); static public long resultLowest = 0; static public long resultBelow = 0; static public long resultNorm = 0; static public long resultAbove = 0; static public long resultHighest = 0; static public long resultControl = 0; static public long resultNewLowest = 0; static public long resultNewBelow = 0; static public long resultNewNorm = 0; static public long resultNewAbove = 0; static public long resultNewHighest = 0; static public long resultNewControl = 0; static public void ThreadMethodLowest() { long threadCount = 0; long fakeCount = 0; while (!loopSwitch.WaitOne(0, false)) { threadCount++; } resultLowest = threadCount; startSecond.WaitOne(); while (!keepAlive.WaitOne(0, false)) { fakeCount++; } resultNewLowest = fakeCount; } static public void ThreadMethodBelow() { long threadCount = 0; long fakeCount = 0; while (!loopSwitch.WaitOne(0, false)) { threadCount++; } resultBelow = threadCount; startSecond.WaitOne(); while (!keepAlive.WaitOne(0, false)) { fakeCount++; } resultNewBelow = fakeCount; } static public void ThreadMethodNorm() { long threadCount = 0; long fakeCount = 0; while (!loopSwitch.WaitOne(0, false)) { threadCount++; } resultNorm = threadCount; startSecond.WaitOne(); while (!keepAlive.WaitOne(0, false)) { fakeCount++; } resultNewNorm = fakeCount; } static public void ThreadMethodAbove() { long threadCount = 0; long fakeCount = 0; while (!loopSwitch.WaitOne(0, false)) { threadCount++; } resultAbove = threadCount; startSecond.WaitOne(); while (!keepAlive.WaitOne(0, false)) { fakeCount++; } resultNewAbove = fakeCount; } static public void ThreadMethodHighest() { long threadCount = 0; long fakeCount = 0; while (!loopSwitch.WaitOne(0, false)) { threadCount++; } resultHighest = threadCount; startSecond.WaitOne(); while (!keepAlive.WaitOne(0, false)) { fakeCount++; } resultNewHighest = fakeCount; } static public void ThreadMethodControl() { long threadCount = 0; long fakeCount = 0; while (!loopSwitch.WaitOne(0, false)) { threadCount++; } resultControl = threadCount; startSecond.WaitOne(); while (!keepAlive.WaitOne(0, false)) { fakeCount++; } resultNewControl = fakeCount; } } static Thread threadLowest = new Thread(PriorityTest.ThreadMethodLowest); static Thread threadBelow = new Thread(PriorityTest.ThreadMethodBelow); static Thread threadNorm = new Thread(PriorityTest.ThreadMethodNorm); static Thread threadAbove = new Thread(PriorityTest.ThreadMethodAbove); static Thread threadHighest = new Thread(PriorityTest.ThreadMethodHighest); static Thread threadControl = new Thread(PriorityTest.ThreadMethodControl); public double Tolerance(long level1, long level2) { long temp = System.Math.Abs((int)(level1 - level2)); return (level2 == 0) ? 100.0 : (temp * 100) / level2; } [TestMethod] public MFTestResults Threading_Priority_Test6() { /// /// 1. Starts five threads of increasing priority /// 2. Waits for them to complete work /// 3. Verifies that they get increasing amounts of attention /// /// MFTestResults testResult = MFTestResults.Pass; const double acceptedTolerance = 5.0; // 5% tolerance Log.Comment("Starts five threads of increasing priority and a control thread, priority not set "); Log.Comment("verifies that they get increasing amounts of attention"); Log.Comment("This is Fixed, see 17201 for details"); threadLowest.Priority = ThreadPriority.Lowest; threadBelow.Priority = ThreadPriority.BelowNormal; threadNorm.Priority = ThreadPriority.Normal; threadAbove.Priority = ThreadPriority.AboveNormal; threadHighest.Priority = ThreadPriority.Highest; Log.Comment("Starting Threads"); threadHighest.Start(); threadAbove.Start(); threadNorm.Start(); threadBelow.Start(); threadLowest.Start(); threadControl.Start(); Log.Comment("Allow counting for 1 seconds."); Thread.Sleep(1000); PriorityTest.loopSwitch.Set(); Thread.Sleep(1000); Log.Comment("Lowest " + PriorityTest.resultLowest); Log.Comment("Below " + PriorityTest.resultBelow); Log.Comment("Normal " + PriorityTest.resultNorm); Log.Comment("Above " + PriorityTest.resultAbove); Log.Comment("Highest " + PriorityTest.resultHighest); Log.Comment("Control Thread " + PriorityTest.resultControl); Log.Comment("Verifies that each thread recieves attention less than or equal"); Log.Comment("to higher priority threads."); Log.Comment("Accepted tolerance : " + acceptedTolerance + "%"); PriorityTest.startSecond.Set(); PriorityTest.keepAlive.Set(); if ((PriorityTest.resultLowest <= 0) || (Tolerance(2 * PriorityTest.resultLowest, PriorityTest.resultBelow) > acceptedTolerance) || (Tolerance(2 * PriorityTest.resultBelow, PriorityTest.resultNorm) > acceptedTolerance) || (Tolerance(2 * PriorityTest.resultNorm, PriorityTest.resultAbove) > acceptedTolerance) || (Tolerance(2 * PriorityTest.resultAbove, PriorityTest.resultHighest) > acceptedTolerance) || (Tolerance(PriorityTest.resultNorm, PriorityTest.resultControl) > acceptedTolerance)) { Log.Comment("Lowest thread should execute at least once, got " + PriorityTest.resultLowest); Log.Comment("Deviation b/n 2*Lowest and Below " + Tolerance(2 * PriorityTest.resultLowest, PriorityTest.resultBelow)); Log.Comment("Deviation b/n 2*Below and Normal " + Tolerance(2 * PriorityTest.resultBelow, PriorityTest.resultNorm)); Log.Comment("Deviation b/n 2*Normal and Above " + Tolerance(2 * PriorityTest.resultNorm, PriorityTest.resultAbove)); Log.Comment("Deviation b/n 2*Above and Highest " + Tolerance(2 * PriorityTest.resultAbove, PriorityTest.resultHighest)); Log.Comment("Deviation b/n Normal and Control " + Tolerance(PriorityTest.resultNorm, PriorityTest.resultControl)); testResult = MFTestResults.Fail; } return testResult; } [TestMethod] public MFTestResults Threading_Suspend_Resume_Test7() { /// /// 1. Starts two threads /// 2. Suspends them /// 3. Verifies that they do not terminate while suspended /// 4. Resumes them /// 5. Verifies that they finish in a reasonable amount of time /// /// Log.Comment("Starts two threads, suspends and resumes them, "); Log.Comment("this may erroneously fail for extremely slow devices."); MFTestResults testResult = MFTestResults.Pass; Thread newThread1 = new Thread(Work.DoWork); newThread1.Start(); Work w = new Work(); w.m_data = 42; w.m_toJoin = newThread1; Thread newThread2 = new Thread(w.DoWorkJoin); newThread2.Start(); Thread.Sleep(1); newThread2.Suspend(); newThread1.Suspend(); ThreadState tState = newThread2.ThreadState; if ((int)tState != 96) { Log.Comment("expected Thread2 in WaitSleepJoin + Suspended ('96') but got '" + tState + "'"); testResult = MFTestResults.Fail; } newThread2.Resume(); tState = newThread1.ThreadState; if ((int)tState != 96) { Log.Comment("expected Thread1 in WaitSleepJoin + Suspended ('96') but got '" + tState + "'"); testResult = MFTestResults.Fail; } newThread1.Resume(); int slept = 0; while ((newThread1.IsAlive || newThread2.IsAlive) && slept < 1000) { Thread.Sleep(100); slept += 100; } if (newThread1.IsAlive || newThread2.IsAlive) { Log.Comment("expected both threads dead after 1000msec but got thread1 '" + newThread1.ThreadState + "' and thread2 '" + newThread2.ThreadState + "'"); testResult = MFTestResults.Fail; } return testResult; } public static bool sleptCorrect(int Msec) { TimeSpan zeroDuration = new TimeSpan(0); const long TicksPerMillisecond = 10000; DateTime startTime = DateTime.Now; Thread.Sleep(Msec); TimeSpan sleptSpan = DateTime.Now - startTime; if ((sleptSpan.Ticks / TicksPerMillisecond) < Msec) { Log.Comment("Expected the thread slept for at least " + Msec + " Msec. but slept only for " + (sleptSpan.Ticks / TicksPerMillisecond) + " Msec"); return false; } Log.Comment(Msec + " Msec sleep success, slept for " + (sleptSpan.Ticks / TicksPerMillisecond) + " Msec"); return true; } [TestMethod] public MFTestResults Threading_SleepApprox_Test8() { /// /// 1. Sleeps the main thread for increasing amounts of time /// 2. Verifies the thread sleeps at least for the time requested /// /// MFTestResults testResult = MFTestResults.Pass; Log.Comment("This test verifies the thread slept at least for the amount of time required"); Log.Comment("This is Fixed, see 20831 for details"); int[] sleepTime = new int[] { 10, 100, 1000, 10000, 60000 }; for (int i = 0; i < sleepTime.Length; i++) { if (!sleptCorrect(sleepTime[i])) { testResult = MFTestResults.Fail; } } return testResult; } [TestMethod] public MFTestResults Threading_Suspend_Suspend_Test9() { /// /// 1. Starts two threads and suspends the first thread twice /// 2. Gets the state of the 1st thread /// 3. Resumes the 1st thread /// 4. Verifies that calling Suspend for the 2nd time has no effect /// /// Log.Comment("Starts two threads and suspends the first thread twice"); Log.Comment("Gets the state of the 1st thread"); Log.Comment("Resumes the 1st thread "); Log.Comment("Verifies that calling Suspend for the 2nd time has no effect"); Log.Comment("This is Fixed, see 20247 for details"); MFTestResults testResult = MFTestResults.Pass; Work.run = true; Work w1 = new Work(); Thread newThread1 = new Thread(w1.DoWorkThreadState); newThread1.Start(); newThread1.Suspend(); newThread1.Suspend(); Work w2 = new Work(); w2.m_data = 42; Thread newThread2 = new Thread(w2.DoMoreWork); newThread2.Start(); ThreadState tState = newThread1.ThreadState; newThread1.Resume(); newThread1.Abort(); if (tState != ThreadState.Suspended) { Log.Comment("Suspending twice, expected thread state Suspended(" + ThreadState.Suspended + ") but got '" + tState + "'"); testResult = MFTestResults.Fail; } return testResult; } [TestMethod] public MFTestResults Threading_ThreadState_Unstarted_Running_WaitSleepJoin_Test10() { /// /// 1. Creates a thread and verifies its state is Unstarted /// 2. Starts a thread and verifies its state is Running /// 3. Sleeps a thread and verifies its state is WaitSleepJoin /// 4. Joins a thread and verifies its state is WaitSleepJoin /// /// Log.Comment("Creating a thread and verifing its state is Unstarted"); MFTestResults testResult = MFTestResults.Pass; Thread newThread1 = new Thread(Work.DoWork); ThreadState tState = newThread1.ThreadState; if (tState != ThreadState.Unstarted) { Log.Comment("Expected thread state Unstarted(" + ThreadState.Unstarted + ") but got '" + tState + "'"); testResult = MFTestResults.Fail; } Log.Comment("Verifying the state of the current thread is Running"); newThread1.Start(); tState = Thread.CurrentThread.ThreadState; if (tState != ThreadState.Running) { Log.Comment("expected the state of current thread Running(" + ThreadState.Running + ") but got '" + tState + "'"); testResult = MFTestResults.Fail; } Log.Comment("Sleeping a thread and verifing its state is WaitSleepJoin"); Thread.Sleep(100); tState = newThread1.ThreadState; if (tState != ThreadState.WaitSleepJoin) { Log.Comment("expected thread1 in WaitSleepJoin(" + ThreadState.WaitSleepJoin + ") but got '" + newThread1.ThreadState + "'"); testResult = MFTestResults.Fail; } Log.Comment(" Joining a thread and verifing its state is WaitSleepJoin"); Work w = new Work(); Thread newThread3 = new Thread(Work.DoWork); w.m_toJoin = newThread3; Thread newThread2 = new Thread(w.DoWorkJoin); newThread3.Start(); newThread2.Start(); Thread.Sleep(0); tState = newThread2.ThreadState; if (tState != ThreadState.WaitSleepJoin) { Log.Comment("expected a joined sleeping thread in WaitSleepJoin state(" + ThreadState.WaitSleepJoin + ") but got '" + tState + "'"); testResult = MFTestResults.Fail; } return testResult; } [TestMethod] public MFTestResults Threading_ThreadState_Suspend_Test11() { /// /// 1. Starts a thread and Suspends it immediately /// 2. Starts a second thread /// 3. Gets the state of the 1st thread and Resumes it /// 4. Verifies that the state of the 1st thread was Suspended /// /// Log.Comment("Starts a thread and Suspends it immediately"); Log.Comment("Starts a second thread"); Log.Comment("Gets the state of the 1st thread and Resumes it"); Log.Comment("Verifies that the state of the 1st thread was Suspended"); Log.Comment("This is Fixed, see 20249 for details"); MFTestResults testResult = MFTestResults.Pass; Work.run = true; Work w1 = new Work(); Thread newThread1 = new Thread(w1.DoWorkThreadState); newThread1.Start(); newThread1.Suspend(); Work w2 = new Work(); w2.m_data = 42; Thread newThread2 = new Thread(w2.DoMoreWork); newThread2.Start(); ThreadState tState = newThread1.ThreadState; newThread1.Resume(); newThread1.Abort(); if (tState != ThreadState.Suspended) { Log.Comment("expected state Suspended(" + ThreadState.Suspended + ") but got '" + tState + "'"); testResult = MFTestResults.Fail; } return testResult; } [TestMethod] public MFTestResults Threading_ThreadState_SuspendRequested_Test12() { /// /// 1. Starts 10 threads and Suspends all of them /// 2. Immediately verifies the state is SuspendRequested /// 3. It's an approximate test /// /// Log.Comment("This currently fails, see 20737 for details"); Log.Comment("Starting 10 Threads"); MFTestResults testResult = MFTestResults.KnownFailure; Thread[] newThread = new Thread[10]; Work[] w = new Work[10]; int i = 0, k = 0; Work.run = true; while (i < 10) { w[i] = new Work(); newThread[i] = new Thread(w[i].DoWorkThreadState); newThread[i].Start(); i++; } Log.Comment("Suspending the Threads and checking for SuspendRequested"); Log.Comment("At least one of the threads should be in SuspendRequested"); while (k < 10) { while (newThread[k].ThreadState != ThreadState.Suspended) { newThread[k].Suspend(); if (newThread[k].ThreadState == ThreadState.SuspendRequested) { testResult = MFTestResults.Pass; break; } } newThread[k].Resume(); k++; } k--; while (k >= 0) { newThread[k].Abort(); k--; } Work.run = false; return testResult; } [TestMethod] public MFTestResults Threading_ThreadState_Abort_Stopped_Test13() { /// /// 1. Starts a thread and Aborts it immediately /// 2. Starts a second thread /// 3. Gets the state of the 1st thread thread /// 4. Verifies the state of the 1st thread is Aborted /// /// Log.Comment("Starts a thread and Aborts it immediately"); Log.Comment("Starts a second thread"); Log.Comment("Gets the state of the 1st thread"); Log.Comment("Verifies the state of the 1st thread is Aborted"); Log.Comment("This is Fixed, see 20495 for details"); MFTestResults testResult = MFTestResults.Pass; DateTime t1, t2; TimeSpan period; Thread newThread1 = new Thread(Work.DoWork); newThread1.Start(); newThread1.Abort(); t1 = DateTime.Now; Work w = new Work(); w.m_data = 42; Thread newThread2 = new Thread(w.DoMoreWork); newThread2.Start(); Log.Comment("Pass Requires either of the next two compared values to be equal"); Log.Comment(newThread1.ThreadState + " Compare to " + ThreadState.Aborted); Log.Comment(newThread1.ThreadState + " Compare to " + ThreadState.Stopped); t2 = DateTime.Now; ThreadState tState = newThread1.ThreadState; period = t2 - t1; Log.Comment("Waited for at least " + period.Milliseconds.ToString() + " before checking the state"); if (tState != ThreadState.Aborted && tState != ThreadState.Stopped) { Log.Comment("expected the thread to be in Aborted/Stopped(" + ThreadState.Aborted + "/" + ThreadState.Stopped + ") state but got '" + tState + "'"); testResult = MFTestResults.Fail; } return testResult; } [TestMethod] public MFTestResults Threading_Abort_ThreadStateException_Test14() { /// /// 1. Creates a thread, Aborts it without starting it /// 2. Verifies Exception is thrown. /// /// Log.Comment("The type of exception thrown should be ThreadStateException"); MFTestResults testResult = MFTestResults.Fail; Thread newThread1 = new Thread(Work.DoWork); try { Log.Comment("Aborting a thread not started should throw exception"); newThread1.Abort(); } catch (Exception e) { Log.Comment("Correctly threw " + e.ToString() + " in an attempt to Abort Unstarted thread"); testResult = MFTestResults.Pass; } return testResult; } [TestMethod] public MFTestResults Threading_Abort_ThreadAbortException_Test15() { /// /// 1. starts a thread and Aborts it immediately /// 2. verifies ThreadAbortException is thrown /// /// MFTestResults testResult = MFTestResults.Pass; Work.hasAborted = false; Thread newThread1 = new Thread(Work.DoWorkThreadAbortException); Log.Comment("This is Fixed, see 20743 for details"); Log.Comment("starting a thread and Aborting it immediately"); newThread1.Start(); Thread.Sleep(50); newThread1.Abort(); Thread.Sleep(500); Log.Comment("Verifying"); if (!Work.hasAborted) { Log.Comment("Aborting a Thread didn't throw ThreadAbortException"); testResult = MFTestResults.Fail; } return testResult; } [TestMethod] public MFTestResults Threading_Join_Timeout_Test16() { /// /// 1. Starts two threads /// 2. both threads joins the main thread using Join(int millisecondsTimeout) Join(TimeSpan timeout) /// 3. Verifies the calling thread is blocked until the specified amount of time elapses /// /// Log.Comment("Starts two threads"); Log.Comment("Both threads Joins the main thread"); Log.Comment("verify calling thread (main thread) is blocked for millisecondsTimeout"); Log.Comment("This is fixed, see 20739 for details"); MFTestResults testResult = MFTestResults.Pass; Work.run = true; Work w = new Work(); Thread newThread1 = new Thread(w.DoWorkThreadState); newThread1.Start(); Thread.Sleep(50); DateTime d1 = DateTime.Now; newThread1.Join(250); DateTime d2 = DateTime.Now; TimeSpan duration1 = d2 - d1; newThread1.Abort(); Thread newThread2 = new Thread(w.DoWorkThreadState); newThread2.Start(); Thread.Sleep(50); DateTime d3 = DateTime.Now; newThread1.Join(new TimeSpan(0, 0, 0, 0, 250)); DateTime d4 = DateTime.Now; TimeSpan duration2 = d4 - d3; newThread2.Abort(); int result1 = duration1.CompareTo(new TimeSpan(0, 0, 0, 0, 250)); int result2 = duration1.CompareTo(new TimeSpan(0, 0, 0, 0, 250)); if (result1 < 0 || result2 < 0) { Log.Comment("expected the main thread to be blocked at least for '250' msec. but was blocked for '" + duration1.ToString() + "' by Thread1 and '" + duration2.ToString() + "' by Thread2"); testResult = MFTestResults.Fail; } return testResult; } [TestMethod] public MFTestResults Threading_Join_ArgumentOutOfRangeException_Test17() { /// /// 1. Start a thread that Join(TimeSpan timeout)s passing negative value /// 2. Verify ArgumentOutOfRangeException is thrown /// MFTestResults testResult = MFTestResults.Fail; Thread newThread1 = new Thread(Work.DoWork); newThread1.Start(); try { Log.Comment("Joining a thread passing -ve timeout value should throw ArgumentOutOfRangeException"); newThread1.Join(-77); } catch (ArgumentOutOfRangeException e) { Log.Comment("Correctly threw exception on -ve timeout value name " + e.ToString()); testResult = MFTestResults.Pass; } return testResult; } [TestMethod] public MFTestResults Threading_Sleep_ArgumentOutOfRangeException_Test18() { /// /// 1. Sleep a thread passing a negative argument /// 2. Verify ArgumentOutOfRangeException exception is thrown /// /// MFTestResults testResult = MFTestResults.Fail; Log.Comment("Verify ArgumentOutOfRangeException exception is thrown"); Log.Comment("Why not for -1 ?"); try { Log.Comment("Sleeping a thread passing negative time-out argument should throw ArgumentOutOfRangeException"); Thread.Sleep(-2); } catch (ArgumentOutOfRangeException e) { Log.Comment("Correctly threw excption on -ve timeout argument name " + e.ToString()); testResult = MFTestResults.Pass; } return testResult; } [TestMethod] public MFTestResults Threading_Join_ThreadStateException_Test19() { /// /// 1. Join a thread that is not Started /// 2. verify ThreadStateException is thrown /// /// Log.Comment("The type of exception thrown should be ThreadStateException"); MFTestResults testResult = MFTestResults.Fail; Thread newThread1 = new Thread(Work.DoWork); try { Log.Comment("Joining a thread not started should throw ThreadStateException exception"); newThread1.Join(); } catch (Exception e) { Log.Comment("Correctly threw " + e.ToString() + " in attempting to Join Unstarted thread"); testResult = MFTestResults.Pass; } return testResult; } [TestMethod] public MFTestResults Threading_Suspend_ThreadStateException_Test20() { /// /// 1. Suspend a thread that is not Started /// 2. verify ThreadStateException is thrown /// /// Log.Comment("The type of exception thrown should be ThreadStateException"); MFTestResults testResult = MFTestResults.Fail; Thread newThread1 = new Thread(Work.DoWork); try { Log.Comment("Suspending a thread not started should throw exception"); newThread1.Suspend(); } catch (Exception e) { Log.Comment("Correctly threw " + e.ToString() + " in an attempt to Suspend Unstarted thread"); testResult = MFTestResults.Pass; } return testResult; } [TestMethod] public MFTestResults Threading_Resume_ThreadStateException_Test21() { /// /// 1. Resume a thread that is not Started /// 2. verify ThreadStateException is thrown /// /// Log.Comment("The type of exception thrown should be ThreadStateException"); MFTestResults testResult = MFTestResults.Fail; Thread newThread1 = new Thread(Work.DoWork); try { Log.Comment("Resuming a thread not Suspended should throw exception"); newThread1.Resume(); } catch (Exception e) { Log.Comment("Correctly threw " + e.ToString() + " in an attempt to Resume UnSuspended thread"); testResult = MFTestResults.Pass; } return testResult; } static bool sleepZero = false; static bool sleepResult = false; public static void SleepTest() { while (sleepZero) sleepResult = true; } [TestMethod] public MFTestResults Threading_Sleep_Zero_Test22() { /// /// 1. Start a thread, /// 2. Sleep the main thread for 0 (zero) milliseconds and /// 3. verify that thread rescheduling is taken place right away /// /// MFTestResults testResult = MFTestResults.Pass; Log.Comment("Starting a thread , Thread.Sleep(0) on the main thread"); Log.Comment("Verify the thread is immediately scheduled to execute"); Log.Comment("This is fixed, see 20753 for details"); sleepZero = true; Thread t1 = new Thread(new ThreadStart(SleepTest)); t1.Start(); Thread.Sleep(50); sleepResult = false; Thread.Sleep(0); if (!sleepResult) { Log.Comment("Test Thread.Sleep(0) Failed"); testResult = MFTestResults.Fail; } else { Log.Comment("Test Thread.Sleep(0) Successful"); } sleepZero = false; return testResult; } [TestMethod] public MFTestResults Threading_Priority_Change_Test23() { /// /// 1. Starts five threads of increasing priority /// 2. Change their priorities to different levels /// 3. Verifies that they get increasing amounts of attention /// 4. based on their new priority level. /// /// MFTestResults testResult = MFTestResults.Pass; const double acceptedTolerance = 5.0; // 5% tolerance Log.Comment("Starts five threads of increasing priority and "); Log.Comment("a control thread priority not set "); Log.Comment("verifies that they get increasing amounts of attention"); PriorityTest.loopSwitch.Reset(); PriorityTest.startSecond.Reset(); PriorityTest.keepAlive.Reset(); Thread threadLowest = new Thread(PriorityTest.ThreadMethodLowest); Thread threadBelow = new Thread(PriorityTest.ThreadMethodBelow); Thread threadNorm = new Thread(PriorityTest.ThreadMethodNorm); Thread threadAbove = new Thread(PriorityTest.ThreadMethodAbove); Thread threadHighest = new Thread(PriorityTest.ThreadMethodHighest); Thread threadControl = new Thread(PriorityTest.ThreadMethodControl); threadLowest.Priority = ThreadPriority.Lowest; threadBelow.Priority = ThreadPriority.BelowNormal; threadNorm.Priority = ThreadPriority.Normal; threadAbove.Priority = ThreadPriority.AboveNormal; threadHighest.Priority = ThreadPriority.Highest; Log.Comment("Starting Threads"); threadHighest.Start(); threadAbove.Start(); threadNorm.Start(); threadBelow.Start(); threadLowest.Start(); threadControl.Start(); Log.Comment("Allow counting for 1 seconds."); Thread.Sleep(1000); PriorityTest.loopSwitch.Set(); Thread.Sleep(1000); Log.Comment("Lowest " + PriorityTest.resultLowest); Log.Comment("Below " + PriorityTest.resultBelow); Log.Comment("Normal " + PriorityTest.resultNorm); Log.Comment("Above " + PriorityTest.resultAbove); Log.Comment("Highest " + PriorityTest.resultHighest); Log.Comment("Control Thread " + PriorityTest.resultControl); threadLowest.Priority = ThreadPriority.BelowNormal; threadBelow.Priority = ThreadPriority.Normal; threadNorm.Priority = ThreadPriority.AboveNormal; threadAbove.Priority = ThreadPriority.Highest; threadHighest.Priority = ThreadPriority.Lowest; Log.Comment("Thread Priorities of each thread changed"); Log.Comment("Allow counting for 1 seconds."); PriorityTest.startSecond.Set(); Thread.Sleep(1000); PriorityTest.keepAlive.Set(); Thread.Sleep(1000); Log.Comment("Lowest - > Below " + PriorityTest.resultNewLowest); Log.Comment("Below - > Normal " + PriorityTest.resultNewBelow); Log.Comment("Normal - > Above " + PriorityTest.resultNewNorm); Log.Comment("Above - > Highest " + PriorityTest.resultNewAbove); Log.Comment("Highest - > Lowest " + PriorityTest.resultNewHighest); Log.Comment("Control Thread " + PriorityTest.resultNewControl); Log.Comment("Verifies that each thread recieves attention less than or equal"); Log.Comment("to higher priority threads based on the newly assigned priorities."); Log.Comment("Accepted Tolerance : " + acceptedTolerance + "%"); if ((PriorityTest.resultNewHighest <= 0) || (Tolerance(2 * PriorityTest.resultNewHighest, PriorityTest.resultNewLowest) > acceptedTolerance) || (Tolerance(2 * PriorityTest.resultNewLowest, PriorityTest.resultNewBelow) > acceptedTolerance) || (Tolerance(2 * PriorityTest.resultNewBelow, PriorityTest.resultNewNorm) > acceptedTolerance) || (Tolerance(2 * PriorityTest.resultNewNorm, PriorityTest.resultNewAbove) > acceptedTolerance) || (Tolerance(PriorityTest.resultNewBelow, PriorityTest.resultNewControl) > acceptedTolerance)) { Log.Comment("NewHighest thread should execute at least once, got " + PriorityTest.resultNewHighest); Log.Comment("Deviation b/n 2*NewHighest and NewLowest " + Tolerance(2 * PriorityTest.resultNewHighest, PriorityTest.resultNewLowest)); Log.Comment("Deviation b/n 2*NewLowest and NewBelow " + Tolerance(2 * PriorityTest.resultNewLowest, PriorityTest.resultNewBelow)); Log.Comment("Deviation b/n 2*NewBelow and NewNorm " + Tolerance(2 * PriorityTest.resultNewBelow, PriorityTest.resultNewNorm)); Log.Comment("Deviation b/n 2*NewNorm and NewAbove " + Tolerance(2 * PriorityTest.resultNewNorm, PriorityTest.resultNewAbove)); Log.Comment("Deviation b/n NewBelow and Control " + Tolerance(PriorityTest.resultNewBelow, PriorityTest.resultNewControl)); testResult = MFTestResults.Fail; } return testResult; } [TestMethod] public MFTestResults Threading_CurrentThread_Test24() { /// /// 1. Start a thread /// 2. Verify Thread.CurrentThread gives the thread itself /// /// MFTestResults testResult = MFTestResults.Pass; Log.Comment("Starting the Thread"); Work w = new Work(); w.m_data = 7; Thread newThread1 = new Thread(w.DoMoreWork); newThread1.Start(); Thread.Sleep(1); Log.Comment("verifying Thread.CurrentThread gives the Thread itself"); if (!newThread1.Equals(w.currThread)) { Log.Comment("Comparing the Thread with its own (Thread.Equals(Thread.CurrentThread)) failed"); testResult = MFTestResults.Fail; } return testResult; } [TestMethod] public MFTestResults Threading_GetDomain_Test25() { /// /// 1. Get the application domain in which the current thread is running /// 2. Verify it's the current domain /// /// MFTestResults testResult = MFTestResults.Pass; Log.Comment("Getting the AppDomain"); AppDomain domain = Thread.GetDomain(); Log.Comment("Verifying the domain"); if (!domain.Equals(AppDomain.CurrentDomain)) { Log.Comment("Thread.GetDomain().Equals(AppDomain.CurrentDomain) Failed"); testResult = MFTestResults.Fail; } return testResult; } [TestMethod] public MFTestResults Threading_Thread_CurrentThread_Suspend_Test26() { MFTestResults testResult = MFTestResults.Pass; int count = 0; Log.Comment("This is fixed, see 19911 for details"); Thread newThread = new Thread(new ThreadStart( delegate { count += 2; Log.Comment("2) Worker thread started..."); Log.Comment("Suspending Worker thread..."); Thread.CurrentThread.Suspend(); Log.Comment("4) Worker thread resumed..."); count += 5; } )); if (count != 0) { Log.Comment("Failure verifying counter reset to zero before starting the thread"); testResult = MFTestResults.Fail; } Log.Comment("1) Starting worker..."); newThread.Start(); Thread.Sleep(3000); if (count != 2) { testResult = MFTestResults.Fail; Log.Comment("Failure : Worker Thread is not Suspended !"); } Log.Comment("3) Wake up suspended thread..."); newThread.Resume(); Thread.Sleep(3000); Log.Comment("5) Main thread finished"); if (count != 7) { Log.Comment("Worker thread not finished for 3000msec after resumed"); testResult = MFTestResults.Fail; } return testResult; } } } ================================================ FILE: Zelig/Zelig/Test/RunTime/NETMF/mscorlib/threads/threads2/AutoResetEventTests.cs ================================================ //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // Copyright (c) Microsoft Corporation. All rights reserved. //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// using System; using Microsoft.SPOT; using Microsoft.SPOT.Platform.Test; using System.Threading; using System.Reflection; namespace Microsoft.SPOT.Platform.Tests { public class AutoResetEventTests : IMFTestInterface { [SetUp] public InitializeResult Initialize() { Log.Comment("Adding set up for the tests"); // Add your functionality here. return InitializeResult.ReadyToGo; } [TearDown] public void CleanUp() { Log.Comment("Cleaning up after the tests."); Thread.Sleep(1000); // TODO: Add your clean up steps here. } class Waiter { public static AutoResetEvent are1 = new AutoResetEvent(false); public static AutoResetEvent are2 = new AutoResetEvent(true); public bool flag; public int wait; public DateTime t1; public DateTime t2; public void DoWait() { Log.Comment("Waiting..."); t1 = DateTime.Now; are1.WaitOne(); t2 = DateTime.Now; flag = true; Log.Comment("Notified"); } public void DoWaitTimeOut() { Log.Comment("Waiting..."); are1.WaitOne(wait, false); flag = true; } public void DoWaitReset() { Log.Comment("Waiting..."); are2.WaitOne(); flag = true; } } [TestMethod] public MFTestResults AutoReset1_WaitOne_Set_Test() { /// ///Start a thread and make it wait by calling WaitOne until signaled by another thread. ///Verify that it continues executing when Set by the other thread. /// /// MFTestResults testResult = MFTestResults.Pass; Log.Comment("Starts a thread and calls WaitOne inside the thread "); Log.Comment("Signals The thread to continue execution"); Log.Comment("Verifies the thread has waited and continued execution upon calling Set"); Log.Comment("Starting Thread"); Waiter newWaiter1 = new Waiter(); Thread newThread1 = new Thread(newWaiter1.DoWait); newThread1.Start(); Log.Comment("Waiting and Signaling after 1000msec."); Thread.Sleep(1000); Log.Comment("wake it up"); DateTime t3 = DateTime.Now; Waiter.are1.Set(); Log.Comment("Waiting the thread to finish and also to get t2"); Thread.Sleep(10); TimeSpan duration1 = newWaiter1.t2 - newWaiter1.t1; TimeSpan duration2 = newWaiter1.t2 - t3; // Assuming atleast the thread should wait for 750ms if (duration1.CompareTo(new TimeSpan(0, 0, 0, 0, 750)) <= 0) { Log.Comment("The thread should have waited atleast 750 msec."); testResult = MFTestResults.Fail; } if (duration2.CompareTo(new TimeSpan(0, 0, 0, 0, 0)) < 0) { Log.Comment("The thread continued executing before it's signaled"); testResult = MFTestResults.Fail; } return testResult; } [TestMethod] public MFTestResults AutoReset2_Set_WaitOne_Set_Test() { /// ///Calls Set repeatedly while no thread was blocked ///Starts two threads and call WaitOne on both. ///Call Set by a third unblocked thread with access to the AutoResetEvent and ///verify that only one blocked thread is released. /// /// MFTestResults testResult = MFTestResults.Pass; Log.Comment("Calls Set repeatedly while no thread was blocked"); Log.Comment("Starts two threads and calls WaitOne on both threads "); Log.Comment("Signals The thread to continue execution calling Set once"); Log.Comment("Verifies only one blocked thread is released"); Waiter.are1.Set(); Waiter.are1.Set(); Waiter newWaiter1 = new Waiter(); newWaiter1.flag = false; Thread newThread1 = new Thread(newWaiter1.DoWait); Waiter newWaiter2 = new Waiter(); newWaiter2.flag = false; Thread newThread2 = new Thread(newWaiter2.DoWait); Log.Comment("Starting The threads"); newThread1.Start(); newThread2.Start(); Log.Comment("Waiting and verifying only one of the threads is signaled"); Thread.Sleep(1000); Log.Comment("flag1 XOR flag2 = ~((flag1 & flag2)||(~flag1 & ~flag2))"); if ((newWaiter1.flag && newWaiter2.flag) || ((!newWaiter1.flag) && (!newWaiter2.flag))) { Log.Comment("Only One of the threads should have been signaled"); testResult = MFTestResults.Fail; } Waiter.are1.Set(); return testResult; } [TestMethod] public MFTestResults AutoReset3_TwoWaitOne_TwoSet_Test() { /// ///Start two threads and call WaitOne on both. ///Call Set twice by a third unblocked thread with access to the AutoResetEvent and ///verify that both blocked threads are released. /// /// MFTestResults testResult = MFTestResults.Pass; Log.Comment("Starts two threads and calls WaitOne on both threads "); Log.Comment("Signals The threads to continue execution calling Set twice"); Log.Comment("Verifies both blocked threads are released"); Waiter newWaiter1 = new Waiter(); Thread newThread1 = new Thread(newWaiter1.DoWait); newWaiter1.flag = false; Waiter newWaiter2 = new Waiter(); Thread newThread2 = new Thread(newWaiter2.DoWait); newWaiter2.flag = false; Log.Comment("Starting threads, waiting and verifying both are waiting"); newThread1.Start(); newThread2.Start(); Thread.Sleep(1000); if (newWaiter1.flag || newWaiter2.flag) { Log.Comment("Failure: One or both threads are not waiting, Thread1 = '" + newWaiter1.flag + "' Thread2 = '" + newWaiter2.flag + "'"); testResult = MFTestResults.Fail; } Log.Comment("Signaling twice, waiting and verifying both threads are signaled"); Waiter.are1.Set(); Waiter.are1.Set(); Thread.Sleep(1000); if (!newWaiter1.flag || !newWaiter2.flag) { Log.Comment("Not both threads are signaled, Thread1 = '" + newWaiter1.flag + "' and Thread2 = '" + newWaiter2.flag + "'"); testResult = MFTestResults.Fail; } return testResult; } [TestMethod] public MFTestResults AutoReset4_WaitOne_TimeOut_Test() { /// ///Starts a thread and call WaitOne passing timeout parameter ///Verify that the wait will end because of a timeout rather than obtaining a signal. /// /// MFTestResults testResult = MFTestResults.Pass; Log.Comment("Starts a thread and call WatiOne passing timeout parameter"); Log.Comment("verifies the wait will end because of timeout"); Log.Comment("Starts a 2nd thread and call WatiOne passing Timeout.Infinite"); Log.Comment("verifies the wait will not end for 3 sec (assumed Infinite)"); Waiter newWaiter1 = new Waiter(); newWaiter1.wait = 100; newWaiter1.flag = false; Thread newThread1 = new Thread(newWaiter1.DoWaitTimeOut); Log.Comment("Starting thread, waiting and verifying wait timeouts"); newThread1.Start(); Thread.Sleep(500); if (!newWaiter1.flag) { Log.Comment("Waited for 500msec. but Thread should have timeouted in " + newWaiter1.wait + ""); testResult = MFTestResults.Fail; } Waiter newWaiter2 = new Waiter(); newWaiter2.wait = -1; newWaiter2.flag = false; Thread newThread2 = new Thread(newWaiter2.DoWaitTimeOut); Log.Comment("Starting thread, waiting for Timeout.Infinite and verifying"); newThread2.Start(); Thread.Sleep(3000); if (newWaiter2.flag) { Log.Comment("Failure: thread didn't wait for Infinite.Timeout"); testResult = MFTestResults.Fail; } Log.Comment("finally signaling the Infinite.Timeout thread"); Waiter.are1.Set(); return testResult; } [TestMethod] public MFTestResults AutoReset5_Reset_Test() { /// ///Creates an AutoResetEvent having an initial state signaled ///Starts a thread, calls WaitOne and verifies the thread is not blocked ///Starts another thread, calls WaitOne and verifies it's auto reset (nonsignaled) ///calls Set and verify it's set (Signaled) ///calls Set, calls Reset, starts a thread and calls WaitOne on the thread ///Verifies that the thread remains blocked /// /// MFTestResults testResult = MFTestResults.Pass; Log.Comment("Creates an AutoResetEvent having an initial state signaled"); Log.Comment("Start a thread, call WaitOne and verify the thread is not blocked"); Log.Comment("Starts a 2nd thread, call WaitOne and verify it's auto reset (thread is blocked)"); Log.Comment("call Set and verify it's set (signaled)"); Log.Comment("call Set, call Reset, starts a thread and call WaitOne on the thread"); Log.Comment("Verify the thread remains blocked"); Waiter newWaiter1 = new Waiter(); newWaiter1.flag = false; Thread newThread1 = new Thread(newWaiter1.DoWaitReset); Log.Comment("Starting thread, waiting and verifying thread not blocked if initial state is signaled"); newThread1.Start(); Thread.Sleep(100); if (!newWaiter1.flag) { Log.Comment("Faiure : AutoResetEvent initial state signaled but blocked thread"); testResult = MFTestResults.Fail; } Waiter newWaiter2 = new Waiter(); newWaiter2.flag = false; Thread newThread2 = new Thread(newWaiter2.DoWaitReset); Log.Comment("Starting thread, waiting and verifying autoreset blocks the thread"); newThread2.Start(); Thread.Sleep(100); if (newWaiter2.flag) { Log.Comment("Failure : AutoResetEvent not autoreseted"); testResult = MFTestResults.Fail; } Log.Comment("Signaling, waiting and verifying"); Waiter.are2.Set(); Thread.Sleep(100); if (!newWaiter2.flag) { Log.Comment("Failure : AutoResetEvent signaled but thread blocked"); testResult = MFTestResults.Fail; } Log.Comment("Set, Reset, Start a thread, waiting and verifying thread remain blocked"); Waiter newWaiter3 = new Waiter(); newWaiter3.flag = false; Thread newThread3 = new Thread(newWaiter3.DoWaitReset); Waiter.are2.Set(); Waiter.are2.Reset(); newThread3.Start(); Thread.Sleep(100); if (newWaiter3.flag) { Log.Comment("Failure: a Reseted AutoResetEvent didn't block thread"); testResult = MFTestResults.Fail; } Log.Comment("Finally Setting the reseted AutoResetEvent"); Waiter.are2.Set(); return testResult; } } } ================================================ FILE: Zelig/Zelig/Test/RunTime/NETMF/mscorlib/threads/threads2/InterlockedTests.cs ================================================ //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // Copyright (c) Microsoft Corporation. All rights reserved. //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// using System; using Microsoft.SPOT; using Microsoft.SPOT.Platform.Test; using System.Reflection; using System.Threading; namespace Microsoft.SPOT.Platform.Tests { public class InterlockedTests : IMFTestInterface { [SetUp] public InitializeResult Initialize() { Log.Comment("Adding set up for the tests"); return InitializeResult.ReadyToGo; } [TearDown] public void CleanUp() { Log.Comment("Cleaning up after the tests"); Thread.Sleep(1000); } public static int interCount = 0; static public void ThreadIncrementor() { Thread.Sleep(new Random().Next(10)); Interlocked.Increment(ref interCount); } static public void ThreadDecrementor() { Thread.Sleep(new Random().Next(10)); Interlocked.Decrement(ref interCount); } static public void ThreadIncrementorStarter() { Thread[] threadArrayInc = new Thread[4]; for (int i = 0; i < 4; i++) { Log.Comment("Attempting to start inc thread " + i); threadArrayInc[i] = new Thread(ThreadIncrementor); threadArrayInc[i].Start(); Thread.Sleep(1); } Thread.Sleep(100); for (int i = 0; i < 4; i++) { threadArrayInc[i].Join(); } } static public void ThreadDecrementorStarter() { Thread[] threadArrayDec = new Thread[5]; for (int i = 0; i < 5; i++) { Log.Comment("Attempting to start dec thread " + i); threadArrayDec[i] = new Thread(ThreadDecrementor); threadArrayDec[i].Start(); Thread.Sleep(1); } Thread.Sleep(100); for (int i = 0; i < 5; i++) { threadArrayDec[i].Join(); } } static public void ThreadIncrementor2Starter() { Thread[] threadArrayInc2 = new Thread[6]; for (int i = 0; i < 6; i++) { Log.Comment("Attempting to start inc2 thread " + i); threadArrayInc2[i] = new Thread(ThreadIncrementor); threadArrayInc2[i].Start(); Thread.Sleep(1); } Thread.Sleep(100); for (int i = 0; i < 6; i++) { threadArrayInc2[i].Join(); } } [TestMethod] public MFTestResults Interlocked1_Inc_Dec_Test() { /// /// 1. Starts 4 threads that run asynchronously /// 2. Each thread calls Interlocked.Increment or Decrement. /// 3. Waits for execution and then verifies that all expected operations completed /// /// Log.Comment("Starts several async threads that call interlocked "); Log.Comment("Increment and Decrement, this may erroneously pass."); Log.Comment("This may erroneously fail for extremely slow devices."); MFTestResults testResult = MFTestResults.Pass; Log.Comment("Starting several threads, incrementing, decrementing,"); Log.Comment("waiting till all threads finish and verifying"); Thread incThread = new Thread(ThreadIncrementorStarter); incThread.Start(); Thread.Sleep(1); Thread decThread = new Thread(ThreadDecrementorStarter); decThread.Start(); Thread.Sleep(1); Thread inc2Thread = new Thread(ThreadIncrementor2Starter); inc2Thread.Start(); Thread.Sleep(1); Thread lastThread = new Thread(ThreadDecrementor); lastThread.Start(); Thread.Sleep(1); Log.Comment("Waiting for execution"); int slept = 0; while ((incThread.IsAlive || decThread.IsAlive || inc2Thread.IsAlive || lastThread.IsAlive) && slept < 5000) { Thread.Sleep(100); slept += 100; } Log.Comment("Verifying all increment/decrement operations done correctly"); if (interCount != 4) { Log.Comment("expected final increment/decrement result = '4' but got '" + interCount + "'"); testResult = MFTestResults.Fail; } Log.Comment("Verifying all threads are finished"); if (slept >= 5000) { Log.Comment("Expcted all threads be done in '5000' msec but took '" + slept + "'"); testResult = MFTestResults.Fail; } return testResult; } [TestMethod] public MFTestResults Interlocked2_Compare_Exchange_Test() { /// /// 1. Starts 4 threads that run asynchronously /// 2. Each thread calls Interlocked.Compare or CompareExchange /// 3. Waits for execution and then verifies that all expected operations completed /// /// MFTestResults testResult = MFTestResults.Pass; Log.Comment("Starts 4 async threads that call interlocked Compare, CompareExchange"); Log.Comment("This may erroneously pass."); Log.Comment("this may erroneously fail for extremely slow devices."); Log.Comment("Starting the 4 threads"); Thread incThread = new Thread(ThreadIncrementorStarter); incThread.Start(); Thread decThread = new Thread(ThreadDecrementorStarter); decThread.Start(); Thread inc2Thread = new Thread(ThreadIncrementor2Starter); inc2Thread.Start(); Thread lastThread = new Thread(ThreadDecrementor); lastThread.Start(); Thread.Sleep(1); int comp = 10; Log.Comment("Waiting for execution"); while ((0 != Interlocked.CompareExchange(ref interCount, 0, comp)) || (incThread.IsAlive || decThread.IsAlive || inc2Thread.IsAlive || lastThread.IsAlive)) { Log.Comment( Interlocked.Exchange(ref interCount, 0).ToString() + " " + incThread.IsAlive.ToString() + " " + decThread.IsAlive.ToString() + " " + inc2Thread.IsAlive.ToString() + " " + lastThread.IsAlive.ToString()); Log.Comment("Setting Count to 0"); Interlocked.Exchange(ref interCount, 0); Thread.Sleep(10); } int slept = 0; while ((incThread.IsAlive || decThread.IsAlive || inc2Thread.IsAlive || lastThread.IsAlive) && slept < 5000) { Thread.Sleep(100); slept += 100; } Log.Comment("Verifying all Interlocked.Compare/CompareExchange operations done correctly"); if (interCount != 0) { Log.Comment("expected final Compare/CompareExchange result = '0' but got '" + interCount + "'"); testResult = MFTestResults.Fail; } Log.Comment("Verifying all threads are finished"); if (slept >= 5000) { Log.Comment("Expcted all threads be done in '5000' msec but took '" + slept + "'"); testResult = MFTestResults.Fail; } return testResult; } [TestMethod] public MFTestResults Interlocked3_Exchange_Boundary_Test() { /// /// 1. creates 3 int variables initialized to the boundary values of signed int 32 /// 2. passes all possible combinations of the values to Interlocked.Exchange /// 3. verifies Exchange and also verifies original value is returned /// /// Log.Comment("This is Fixed, see 20323 for details"); MFTestResults testResult = MFTestResults.Pass; int[] value = new int[] { -2147483648, 0, 2147483647 }; int temp1, temp2; Log.Comment("Verification of original value returned needs temp1 = temp2"); Log.Comment("Verifies Exchange "); for (int i = 0; i < 3; i++) { for (int j = 0; j < 3; j++) { temp1 = value[i]; temp2 = Interlocked.Exchange(ref value[i], value[j]); if (temp1 != temp2) { Log.Comment("Failure : expected Interlocked.Exchange returns" + " the original value '" + temp1 + "' but got '" + temp2 + "'"); break; } if (value[i] != value[j]) { Log.Comment("Failure : "); Log.Comment(value[j] + " is not stored at location1"); break; } value[i] = temp1; } } return testResult; } [TestMethod] public MFTestResults Interlocked4_CompareExchange_Boundary_Test() { /// /// 1. creates 3 int variables initialized to the boundary values of signed int 32 /// 2. passes all posible combinations of the values to Interlocked.CompareExchange /// 3. verifies Exchange upon equality and also verifies original value is returned /// /// Log.Comment("This is Fixed, see 20323 for details"); MFTestResults testResult = MFTestResults.Pass; int[] value = new int[] { -2147483648, 0, 2147483647 }; int temp1, temp2; Log.Comment("Verifies the original value is returned at all time"); Log.Comment("Verifies value is stored in location1 upon equality"); for (int r = 0; r < 3; r++) { for (int p = 0; p < 3; p++) { for (int q = 0; q < 3; q++) { temp1 = value[r]; temp2 = Interlocked.CompareExchange(ref value[r], value[p], value[q]); if (temp1 != temp2) { Log.Comment("Failure : expected Interlocked.CompareExchange returns" + " the original vaue '" + temp1 + "' but returned '" + temp2 + "'"); break; } if (r == q) { if (value[r] != value[p]) { Log.Comment("Failure : expected Interlocked.CompareExchange replaces the original value '" + temp1 + "' upon equality of the two comparands '" + value[r] + "' and '" + value[q] + "'"); Log.Comment(value[p] + " is not stored at location1"); break; } } value[r] = temp1; } } } return testResult; } } } ================================================ FILE: Zelig/Zelig/Test/RunTime/NETMF/mscorlib/threads/threads2/MonitorTests.cs ================================================ //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // Copyright (c) Microsoft Corporation. All rights reserved. //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// using System; using Microsoft.SPOT; using Microsoft.SPOT.Platform.Test; using System.Reflection; using System.Threading; namespace Microsoft.SPOT.Platform.Tests { public class MonitorTests : IMFTestInterface { [SetUp] public InitializeResult Initialize() { Log.Comment("Adding set up for the tests"); return InitializeResult.ReadyToGo; } [TearDown] public void CleanUp() { Log.Comment("Cleaning up after the tests"); Thread.Sleep(1000); } public static int monCount = 0; public static object mutex = new object(); static public void MonitoredThreadIncrementor() { Thread.Sleep(new Random().Next(10)); Monitor.Enter(mutex); monCount++; Monitor.Exit(mutex); } static public void MonitoredThreadDecrementor() { Thread.Sleep(new Random().Next(10)); Monitor.Enter(mutex); monCount--; Monitor.Exit(mutex); } static public void MonitoredThreadIncrementorStarter() { Thread[] threadArrayInc = new Thread[4]; for (int i = 0; i < 4; i++) { Log.Comment("Attempting to start inc thread " + i); threadArrayInc[i] = new Thread(MonitoredThreadIncrementor); threadArrayInc[i].Start(); Thread.Sleep(1); } Thread.Sleep(10); for (int i = 0; i < 4; i++) { threadArrayInc[i].Join(); } } static public void MonitoredThreadDecrementorStarter() { Thread[] threadArrayDec = new Thread[5]; for (int i = 0; i < 5; i++) { Log.Comment("Attempting to start dec thread " + i); threadArrayDec[i] = new Thread(MonitoredThreadDecrementor); threadArrayDec[i].Start(); Thread.Sleep(1); } Thread.Sleep(10); for (int i = 0; i < 5; i++) { threadArrayDec[i].Join(); } } static public void MonitoredThreadIncrementor2Starter() { Thread[] threadArrayInc2 = new Thread[6]; for (int i = 0; i < 6; i++) { Log.Comment("Attempting to start inc2 thread " + i); threadArrayInc2[i] = new Thread(MonitoredThreadIncrementor); threadArrayInc2[i].Start(); Thread.Sleep(1); } Thread.Sleep(10); for (int i = 0; i < 6; i++) { threadArrayInc2[i].Join(); } } [TestMethod] public MFTestResults Monitor1_Basic_Test() { /// /// 1. Starts 4 threads that run asynchronously /// 2. Each thread increments or decrements while in a critical section /// 3. Waits for execution and then verifies that all expected operations completed /// /// MFTestResults testResult = MFTestResults.Pass; Log.Comment("Starts several async threads that Enter and Exit critical sections."); Log.Comment("This may erroneously pass."); Log.Comment("This may erroneously fail for extremely slow devices."); Log.Comment("Starting the 4 threads"); Thread incThread = new Thread(MonitoredThreadIncrementorStarter); incThread.Start(); Thread decThread = new Thread(MonitoredThreadDecrementorStarter); decThread.Start(); Thread inc2Thread = new Thread(MonitoredThreadIncrementor2Starter); inc2Thread.Start(); Thread lastThread = new Thread(MonitoredThreadDecrementor); lastThread.Start(); Thread.Sleep(1); Log.Comment("Joining All threads to main thread"); incThread.Join(); decThread.Join(); inc2Thread.Join(); lastThread.Join(); Log.Comment("Verifying all operations completed successfully"); if (monCount != 4) { Log.Comment("expected final result = '4' but got '" + monCount + "'"); testResult = MFTestResults.Fail; } return testResult; } static object locker1 = new object(); [TestMethod] public MFTestResults Monitor2_SynchronizationLockException_Test() { /// /// 1. Call Monitor.Exit without first calling Monitor.Enter on the same object /// 2. Verify SynchronizationLockException exception is thrown /// /// MFTestResults testResult = MFTestResults.Fail; Log.Comment("Verify SynchronizationLockException exception is thrown"); Log.Comment("This currently fails, see 20281"); try { Log.Comment("Calling Monitor.Exit without first calling Monitor.Enter should throw an exception"); Monitor.Exit(locker1); } catch (Exception e) { Log.Comment("Threw excption name " + e.ToString()); testResult = MFTestResults.Pass; } return testResult; } [TestMethod] public MFTestResults Monitor3_Enter_ArgumentNullException_Test() { /// /// 1. Call Monitor.Enter passing null reference obj parameter /// 2. verify ArgumentNullException exception is thrown /// /// MFTestResults testResult = MFTestResults.Fail; Log.Comment("verify ArgumentNullException exception is thrown "); Log.Comment("This is fixed, see 20730 for details"); try { Log.Comment("Calling Monitor.Enter passing null reference parameter should throw exception"); Monitor.Enter(null); } catch (ArgumentNullException e) { Log.Comment("Correctly threw " + e.ToString() + " in Monitor.Enter(null)"); testResult = MFTestResults.Pass; } catch (Exception ex) { Log.Comment("Caught : " + ex.Message); } return testResult; } [TestMethod] public MFTestResults Monitor4_Exit_ArgumentNullException_Test() { /// /// 1. Call Monitor.Exit passing null reference obj parameter /// 2. verify ArgumentNullException exception is thrown /// /// MFTestResults testResult = MFTestResults.Fail; Log.Comment("verify ArgumentNullException exception is thrown "); Log.Comment("This is fixed, see 20731 for details"); try { Log.Comment("Calling Monitor.Exit passing null reference parameter should throw exception"); Monitor.Exit(null); } catch (ArgumentNullException e) { Log.Comment("Correctly threw " + e.ToString() + " in Monitor.Enter(null)"); testResult = MFTestResults.Pass; } catch (Exception ex) { Log.Comment("Caught : " + ex.Message); } return testResult; } static ManualResetEvent flag = new ManualResetEvent(false); static bool lockResult = false; static object locker2 = new object(); static void RepeatedLock() { Log.Comment("T1 = " + DateTime.Now); Monitor.Enter(locker2); try { lockResult = !lockResult; Log.Comment("I have the lock"); Nest(); Log.Comment("I still have the lock"); } finally { if (flag.WaitOne(500, false)) { Monitor.Exit(locker2); Log.Comment("Here the lock is released"); } } Log.Comment("T4 = " + DateTime.Now); } static void Nest() { Log.Comment("T2 = " + DateTime.Now); Monitor.Enter(locker2); try { Log.Comment("Inside Lock"); } finally { Monitor.Exit(locker2); Log.Comment("Released the lock? Not quite!"); } Log.Comment("T3 = " + DateTime.Now); } [TestMethod] public MFTestResults Monitor5_Repeatedly_Lock_Unlock_Test() { MFTestResults testResult = MFTestResults.Pass; Log.Comment("Starts two Threads "); Log.Comment("Repeatedly locks an object by multiple calls to Monitor.Enter"); Log.Comment("Verifies the object is unlocked only by a corresponding number of Monitor.Exit"); Thread newThread1 = new Thread(RepeatedLock); Thread newThread2 = new Thread(RepeatedLock); Log.Comment("Starting two threads, repeatedly locking, waiting and verifying"); newThread1.Start(); newThread2.Start(); Thread.Sleep(100); if (!lockResult) { Log.Comment("Failure : both threads passed lock"); testResult = MFTestResults.Fail; } Log.Comment("unlocking the final lock and verifying the waiting thread continues"); flag.Set(); Thread.Sleep(500); if (lockResult) { Log.Comment("Failure : lock not released by equal number of unlocks"); testResult = MFTestResults.Fail; } if (newThread1.IsAlive) newThread2.Abort(); if (newThread2.IsAlive) newThread2.Abort(); return testResult; } } } ================================================ FILE: Zelig/Zelig/Test/RunTime/NETMF/mscorlib/threads/threads2/TimeoutTests.cs ================================================ //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // Copyright (c) Microsoft Corporation. All rights reserved. //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// using System; using Microsoft.SPOT; using Microsoft.SPOT.Platform.Test; using System.Reflection; using System.Threading; namespace Microsoft.SPOT.Platform.Tests { public class TimeoutTests : IMFTestInterface { [SetUp] public InitializeResult Initialize() { Log.Comment("Adding set up for the tests"); return InitializeResult.ReadyToGo; } [TearDown] public void CleanUp() { Log.Comment("Cleaning up after the tests"); Thread.Sleep(1000); } class Work { public void DoWorkInfinite() { Thread.Sleep(300); Log.Comment("Instance thread procedure DoWorkInfinite."); Thread.Sleep(Timeout.Infinite); } public static void DoWorkInfiniteStatic() { Thread.Sleep(300); Log.Comment("Static thread procedure DoWorkInfiniteStatic."); Thread.Sleep(Timeout.Infinite); } } [TestMethod] public MFTestResults Timeout1_Infinite_Test() { /// /// 1. Starts two threads which have an Infinite execution time one static /// 2. Calls Abort on the Infinite threads /// 3. Verifies that the aborted threads stop immediately /// /// MFTestResults testResult = MFTestResults.Pass; Log.Comment("Starts two threads one infinitely long, aborts one and passes."); Log.Comment("This may erroneously fail for extremely slow devices."); Log.Comment("Starting the two threads"); Thread newThread1 = new Thread(Work.DoWorkInfiniteStatic); newThread1.Start(); Work w = new Work(); Thread newThread2 = new Thread(w.DoWorkInfinite); newThread2.Start(); Thread.Sleep(1); Log.Comment("Waiting for 1000msec and verifying both threads are alive"); int slept = 0; while ((newThread1.IsAlive || newThread2.IsAlive) && slept < 1000) { Thread.Sleep(100); slept += 100; } if (!newThread1.IsAlive || !newThread2.IsAlive) { Log.Comment("Failure : Both threads were suppose to be sleeping for Timeout.Infinite"); Log.Comment("IsAlive ? Thread1 = '" + newThread1.IsAlive + "' and Thread2 = '" + newThread2.IsAlive + "'"); testResult = MFTestResults.Fail; } Log.Comment("Aborting both threds and Verifying abort."); newThread2.Abort(); newThread1.Abort(); Thread.Sleep(10); if (newThread1.IsAlive || newThread2.IsAlive) { Log.Comment("Upon Abort both thread should be dead but"); Log.Comment("IsAlive ? Thread1 = '" + newThread1.IsAlive + "' and Thread2 = '" + newThread2.IsAlive + "'"); testResult = MFTestResults.Fail; } return testResult; } } } ================================================ FILE: Zelig/Zelig/Test/RunTime/NETMF/mscorlib/threads/threads2/WaitHandleTests.cs ================================================ //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // Copyright (c) Microsoft Corporation. All rights reserved. //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// using System; using Microsoft.SPOT; using Microsoft.SPOT.Platform.Test; using System.Reflection; using System.Threading; namespace Microsoft.SPOT.Platform.Tests { public class WaitHandleTests : IMFTestInterface { [SetUp] public InitializeResult Initialize() { Log.Comment("Adding set up for the tests"); return InitializeResult.ReadyToGo; } [TearDown] public void CleanUp() { Log.Comment("Cleaning up after the tests"); Thread.Sleep(1000); } static WaitHandle[] waitHandles = new WaitHandle[] { new AutoResetEvent(false), new AutoResetEvent(false) }; static void DoTask1() { AutoResetEvent are = (AutoResetEvent)waitHandles[0]; int time = 10000; Thread.Sleep(time); are.Set(); } static void DoTask2() { AutoResetEvent are = (AutoResetEvent)waitHandles[1]; int time = 500; Thread.Sleep(time); are.Set(); } [TestMethod] public MFTestResults WaitHandle1_WaitAll_WaitAny_Test() { /// /// 1. Starts two threads /// 2. Calls WaitAll with respect to those threads /// 3. Verifies that both threads have executed /// 4. Restarts the threads /// 5. Calls WaitAny with respect to those threads /// 6. Verifies that only one threads has executed /// /// Log.Comment("This test may erroneously pass or fail due to machine speed"); Log.Comment("Tests the WaitAll method"); MFTestResults testResult = MFTestResults.Pass; try { Log.Comment("Create threads"); Thread t1 = new Thread(DoTask1); Thread t2 = new Thread(DoTask2); t1.Start(); t2.Start(); Thread.Sleep(1); Log.Comment("Waiting for all tasks to complete and verifying"); if (!WaitHandle.WaitAll(waitHandles)) { Log.Comment("Not all waithandles has received the signal"); testResult = MFTestResults.Fail; } bool r = t1.IsAlive, s = t2.IsAlive; if (r || s) { Log.Comment("Not all threads are dead"); if (r) { Log.Comment("t1 is Alive"); } if (s) { Log.Comment("t2 is Alive"); } testResult = MFTestResults.Fail; } Log.Comment("Re-create threads"); t1 = new Thread(DoTask1); t2 = new Thread(DoTask2); t1.Start(); t2.Start(); Thread.Sleep(1); Log.Comment("Waiting for either task to complete and verifying"); Log.Comment("The WaitHandle with index " + WaitHandle.WaitAny(waitHandles).ToString() + " satisfied the wait"); Log.Comment("Doing t1 XOR t2 to verify only one but not both are alive or dead"); Log.Comment("t1 XOR t2 = ~((p&q)||(~p & ~q))"); bool p = t1.IsAlive, q = t2.IsAlive; if ((p && q) || ((!p) && (!q))) { Log.Comment("Not both but either one should have finished"); testResult = MFTestResults.Fail; } Log.Comment(p == true ? "t1 is Alive " : "t1 is Dead "); Log.Comment(q == true ? "t2 is Alive " : "t2 is Dead "); } catch (Exception e) { Log.Comment("Caught: " + e.Message); testResult = MFTestResults.Fail; } return testResult; } static AutoResetEvent ready = new AutoResetEvent(false); static AutoResetEvent go = new AutoResetEvent(false); static int counter = 0; static void Work() { while (true) { ready.Set(); // Indicate that we're ready go.WaitOne(); // Wait to be kicked off... if (counter == 0) return; // Gracefully exit Log.Comment("Counter = " + counter); } } [TestMethod] public MFTestResults WaitHandle2_WatiOne_Test() { /// /// 1. Starts a thread /// 2. waits until the thread is ready, calling WaitOne /// 3. when the thread signals it's ready, it continues executing /// 4. worker thread waits on the other hand till it's signaled /// 5. worker thread continues execution when signaled /// 6. Verifies thread waits, and executes when signaled. /// /// Log.Comment("This test verifies thread waits, and executes when signaled"); Log.Comment("Tests WaitOne method"); MFTestResults testResult = MFTestResults.Pass; Thread newThread1 = new Thread(Work); newThread1.Start(); Log.Comment("Signal the worker 5 times"); for (int i = 1; i <= 5; i++) { Log.Comment("First wait until worker is ready"); ready.WaitOne(); Log.Comment("Doing task"); counter++; Log.Comment("Tell worker to go!"); go.Set(); } if (counter != 5) { Log.Comment("expected signaling '5' but got '" + counter + "'"); testResult = MFTestResults.Fail; } Log.Comment("Tell the worker to end by reseting counter to 0(zero)"); ready.WaitOne(); counter = 0; go.Set(); return testResult; } } } ================================================ FILE: Zelig/Zelig/Test/RunTime/NETMF/mscorlib/threads/threads3/TimerTests.cs ================================================ //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // Copyright (c) Microsoft Corporation. All rights reserved. //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// using System; using Microsoft.SPOT; using Microsoft.SPOT.Platform.Test; using System.Reflection; using System.Threading; namespace Microsoft.SPOT.Platform.Tests { public class TimerTests : IMFTestInterface { [SetUp] public InitializeResult Initialize() { if (Microsoft.SPOT.Hardware.SystemInfo.SystemID.SKU == 3) { Log.Comment("We may only need to run Time Dependent Tests on a Device"); return InitializeResult.ReadyToGo; } Log.Comment("Adding set up for the tests"); return InitializeResult.ReadyToGo; } [TearDown] public void CleanUp() { Log.Comment("Cleaning up after the tests"); Thread.Sleep(1000); } class StatusChecker { public bool m_result = false; public bool z_flag = false; public bool c_flag = false; public bool m_flag = false; public int counter = 0; public DateTime t2; public DateTime t1; public int m_invokeCount, m_maxCount; public StatusChecker(int count) { m_invokeCount = 0; m_maxCount = count; } // This method is called by the timer delegate. public void CheckStatus(Object stateInfo) { if (z_flag) { t2 = DateTime.Now; z_flag = false; } if (m_flag) { t1 = DateTime.Now; z_flag = true; m_flag = false; } if (c_flag) { counter++; } AutoResetEvent autoEvent = (AutoResetEvent)stateInfo; Log.Comment("Checking status: " + DateTime.Now.ToString() + " " + (++m_invokeCount).ToString()); if (m_invokeCount == m_maxCount) { Log.Comment("Reset the counter and signal Main."); m_invokeCount = 0; autoEvent.Set(); m_result = true; } } } [TestMethod] public MFTestResults Timer_TimerCallback_Test1() { /// /// 1. Creates a TimerCallback /// 2. Creates a Timer that calls it at 1 sec and every quarter sec thereafter /// 3. Verifies that the TimerCallback gets called /// 4. Change period to half sec /// 5. Disposes of the timer after it signals /// 6. Verifies that the TimerCallback has been called /// /// Log.Comment("Tests the Timer and TimerCallback classes, "); Log.Comment("as well as the Change and Dispose methods"); MFTestResults testResult = MFTestResults.Pass; AutoResetEvent autoEvent = new AutoResetEvent(false); StatusChecker statusChecker = new StatusChecker(15); Log.Comment("Creating the TimerCallback"); TimerCallback timerDelegate = new TimerCallback(statusChecker.CheckStatus); Log.Comment("Creating timer: " + DateTime.Now.ToString()); Timer stateTimer = new Timer(timerDelegate, autoEvent, 1000, 250); statusChecker.m_result = false; Log.Comment("Waiting and verifying"); autoEvent.WaitOne(5000, false); if (!statusChecker.m_result) { Log.Comment("Failure : expected callback '" + statusChecker.m_maxCount + "' times but got '" + statusChecker.m_invokeCount + "'"); testResult = MFTestResults.Fail; } statusChecker.m_result = false; Log.Comment("Changing period to 500msec"); stateTimer.Change(0, 500); Log.Comment("Waiting for 7500msec and verifying"); autoEvent.WaitOne(7500, false); stateTimer.Dispose(); Log.Comment("Destroying timer."); if (!statusChecker.m_result) { Log.Comment("Failure : expected callback '" + statusChecker.m_maxCount + "' times but got '" + statusChecker.m_invokeCount + "'"); testResult = MFTestResults.Fail; } return testResult; } [TestMethod] public MFTestResults Timer_TimerCallback_ZeroTest2() { /// /// 1. Creates a TimerCallback /// 2. Creates a Timer that calls it at 1 sec and every quarter sec thereafter /// 3. Verifies that the TimerCallback gets called /// 4. Change duetime to zero sec /// 5. Disposes of the timer after it signals /// 6. Verifies that the TimerCallback restarted immediately /// /// Log.Comment("Tests the Timer and TimerCallback classes, "); Log.Comment("as well as the Change and Dispose methods"); MFTestResults testResult = MFTestResults.Pass; AutoResetEvent autoEvent = new AutoResetEvent(false); StatusChecker statusChecker = new StatusChecker(15); Log.Comment("Creating the TimerCallback"); TimerCallback timerDelegate = new TimerCallback(statusChecker.CheckStatus); Log.Comment("Creating timer: " + DateTime.Now.ToString()); Timer stateTimer = new Timer(timerDelegate, autoEvent, 1000, 250); statusChecker.m_result = false; Log.Comment("Waiting and verifying"); autoEvent.WaitOne(5000, false); if (!statusChecker.m_result) { Log.Comment("Failure : expected callback '" + statusChecker.m_maxCount + "' times but got '" + statusChecker.m_invokeCount + "'"); testResult = MFTestResults.Fail; } statusChecker.m_result = false; statusChecker.z_flag = true; Log.Comment("Changing duetime to zero and Verifying the timer started Immediately."); DateTime t1 = DateTime.Now; stateTimer.Change(0, 500); Thread.Sleep(1); TimeSpan time = DateTime.Now - statusChecker.t2; Log.Comment("callback method called within " + time.ToString()); if (time.CompareTo(new TimeSpan(0, 0, 0, 0, 100)) > 0) { Log.Comment("The timer didn't start immediately, started after '" + time.ToString() + "'"); testResult = MFTestResults.Fail; } Log.Comment("Waiting and verifying"); autoEvent.WaitOne(7500, false); Log.Comment("Destroying timer."); stateTimer.Dispose(); if (!statusChecker.m_result) { Log.Comment("Failure : expected callback '" + statusChecker.m_maxCount + "' times but got '" + statusChecker.m_invokeCount + "'"); testResult = MFTestResults.Fail; } return testResult; } [TestMethod] public MFTestResults Timer_Disable_Periodic_Signaling_Test3() { /// /// 1. Creates a TimerCallback /// 2. Creates a Timer that calls it at 1 sec and every quarter sec thereafter /// 3. Verifies that the TimerCallback gets called /// 4. Changes period to zero (0) /// 5. Verifies periodic signaling is disabled /// 6. Changes period to Infinite /// 7. Verifies periodic signaling is disabled /// 8. Changes period to quarter sec /// 9. Disposes the timer after it signals /// 10. Verifies that the TimerCallback has been called /// /// Log.Comment("Tests the Timer and TimerCallback classes, "); Log.Comment("as well as the Change and Dispose methods"); MFTestResults testResult = MFTestResults.Pass; AutoResetEvent autoEvent = new AutoResetEvent(false); StatusChecker statusChecker = new StatusChecker(15); Log.Comment("Creating the TimerCallback"); TimerCallback timerDelegate = new TimerCallback(statusChecker.CheckStatus); Log.Comment("Creating timer: " + DateTime.Now.ToString()); Timer stateTimer = new Timer(timerDelegate, autoEvent, 1000, 250); Log.Comment("Waiting and verifying"); autoEvent.WaitOne(5000, false); if (!statusChecker.m_result) { Log.Comment("Failure : expected callback '" + statusChecker.m_maxCount + "' times but got '" + statusChecker.m_invokeCount + "'"); testResult = MFTestResults.Fail; } statusChecker.m_result = false; statusChecker.c_flag = true; Log.Comment("Changing period to zero (0) "); stateTimer.Change(0, 0); Log.Comment("Waiting and verifying the callback method is invoked once"); autoEvent.WaitOne(5000, false); if (statusChecker.counter != 1) { Log.Comment("Failure : expected callback '1' times but got '" + statusChecker.counter + "'"); testResult = MFTestResults.Fail; } Log.Comment("Reseting counter to zero"); statusChecker.counter = 0; Log.Comment("Changing period to Timeout.Infinite"); stateTimer.Change(0, Timeout.Infinite); Log.Comment("Waiting and verifying the callback method is invoked once"); autoEvent.WaitOne(5000, false); if (statusChecker.counter != 1) { Log.Comment("Failure : expected callback '1' times but got '" + statusChecker.counter + "'"); testResult = MFTestResults.Fail; } Log.Comment("Changing period to quarter sec "); stateTimer.Change(0, 250); Log.Comment("Waiting and verifying"); autoEvent.WaitOne(5000, false); Log.Comment("Destroying timer."); stateTimer.Dispose(); if (!statusChecker.m_result) { Log.Comment("Failure : expected callback '" + statusChecker.m_maxCount + "' times but got '" + statusChecker.m_invokeCount + "'"); testResult = MFTestResults.Fail; } return testResult; } [TestMethod] public MFTestResults Timer_TimerCallback_Duetime_Infinite_Test4() { /// /// 1. Creates a TimerCallback /// 2. Creates a Timer that calls it after infinite time /// 3. Verifies the callback method is never invoked /// /// Log.Comment("Tests the TimerCallback is never invoked if it's duetime is infinite "); MFTestResults testResult = MFTestResults.Pass; AutoResetEvent autoEvent = new AutoResetEvent(false); StatusChecker statusChecker = new StatusChecker(15); statusChecker.c_flag = true; Log.Comment("Creating the TimerCallback"); TimerCallback timerDelegate = new TimerCallback(statusChecker.CheckStatus); Log.Comment("Creating timer: " + DateTime.Now.ToString()); Timer stateTimer = new Timer(timerDelegate, autoEvent, Timeout.Infinite, 250); Log.Comment("Waiting and verifying"); autoEvent.WaitOne(5000, false); Log.Comment("Destroying timer."); stateTimer.Dispose(); if (statusChecker.counter != 0) { Log.Comment("Failure : expected callback method never invoked" + " but is invoked '" + statusChecker.counter + "' times"); testResult = MFTestResults.Fail; } return testResult; } [TestMethod] public MFTestResults Timer_Dispose_Test5() { /// /// 1. Creates a TimerCallback /// 2. Creates a Timer that calls it at 1 sec and every quarter sec thereafter /// 3. Immediately Disposes the timer /// 4. Verifies that the Timer is disposed /// /// Log.Comment("Tests the Timer and TimerCallback classes, "); Log.Comment("as well as the Change and Dispose methods"); MFTestResults testResult = MFTestResults.Pass; AutoResetEvent autoEvent = new AutoResetEvent(false); StatusChecker statusChecker = new StatusChecker(15); statusChecker.c_flag = true; Log.Comment("Creating the TimerCallback"); TimerCallback timerDelegate = new TimerCallback(statusChecker.CheckStatus); Log.Comment("Creating timer: " + DateTime.Now.ToString()); Timer stateTimer = new Timer(timerDelegate, autoEvent, 1000, 250); Log.Comment("Immediately Destroying timer"); stateTimer.Dispose(); Log.Comment("Waiting and verifying for Timer disposed"); autoEvent.WaitOne(5000, false); if (statusChecker.counter != 0) { Log.Comment("Failure : expected timer destroyed immediately hence callback method" + " never invoked but is invoked '" + statusChecker.counter + "' times"); testResult = MFTestResults.Fail; } return testResult; } [TestMethod] public MFTestResults Timer_Negative_Period_Test6() { /// /// 1. Creates a TimerCallback /// 2. Creates a Timer that calls it at 1 sec and every quarter sec thereafter /// 3. Verifies that the TimerCallback gets called /// 4. Changes period to -2 (negative two) sec /// 5. Verifies ArgumentOutOfRangeException exception is thrown /// /// Log.Comment("Tests the Timer and TimerCallback classes, "); Log.Comment("as well as the Change and Dispose methods"); MFTestResults testResult = MFTestResults.Fail; AutoResetEvent autoEvent = new AutoResetEvent(false); StatusChecker statusChecker = new StatusChecker(15); Log.Comment("Creating the TimerCallback"); TimerCallback timerDelegate = new TimerCallback(statusChecker.CheckStatus); Log.Comment("Creating timer: " + DateTime.Now.ToString()); Timer stateTimer = new Timer(timerDelegate, autoEvent, 1000, 250); statusChecker.m_result = false; Log.Comment("Waiting and verifying"); autoEvent.WaitOne(5000, false); statusChecker.m_result = false; Log.Comment("Changing period to -ve"); try { Log.Comment("period is negative and is not equal to Infinite (or -1) should throw an exception"); stateTimer.Change(0, -2); Log.Comment("Waiting and verifying"); autoEvent.WaitOne(7500, false); } catch (ArgumentOutOfRangeException e) { Log.Comment("Correctly threw exception on negative period " + e.ToString()); testResult = MFTestResults.Pass; } finally { Log.Comment("Destroying timer."); stateTimer.Dispose(); } return testResult; } [TestMethod] public MFTestResults Timer_Negative_Duetime_Test7() { /// /// 1. Creates a TimerCallback /// 2. Creates a Timer that calls it at 1 sec and every quarter sec thereafter /// 3. Verifies that the TimerCallback gets called /// 4. Changes duetime to -2 (negative two) sec /// 5. Verifies ArgumentOutOfRangeException exception is thrown /// /// Log.Comment("Tests the Timer Change method for ArgumentOutOfRangeException"); MFTestResults testResult = MFTestResults.Fail; AutoResetEvent autoEvent = new AutoResetEvent(false); StatusChecker statusChecker = new StatusChecker(15); Log.Comment("Creating the TimerCallback"); TimerCallback timerDelegate = new TimerCallback(statusChecker.CheckStatus); Log.Comment("Creating timer: " + DateTime.Now.ToString()); Timer stateTimer = new Timer(timerDelegate, autoEvent, 1000, 250); statusChecker.m_result = false; Log.Comment("Waiting and verifying"); autoEvent.WaitOne(5000, false); statusChecker.m_result = false; Log.Comment("Changing period -ve"); try { Log.Comment("duetime is negative and is not equal to Infinite(or -1) should throw an exception"); stateTimer.Change(-2, 500); Log.Comment("Waiting and verifying"); autoEvent.WaitOne(7500, false); } catch (ArgumentOutOfRangeException e) { Log.Comment("Correctly threw exception on negative duetime name " + e.ToString()); testResult = MFTestResults.Pass; } finally { Log.Comment("Destroying timer."); stateTimer.Dispose(); } return testResult; } [TestMethod] public MFTestResults Timer_TimerCallback_Null_Test8() { /// /// 1. Creates a Timer with callback parameter null /// 2. Verifies ArgumentNullException exception is thrown /// /// Log.Comment("Tests the Timer for ArgumentNullException"); MFTestResults testResult = MFTestResults.Fail; AutoResetEvent autoEvent = new AutoResetEvent(false); StatusChecker statusChecker = new StatusChecker(15); Log.Comment("Creating timer: " + DateTime.Now.ToString()); try { Log.Comment("Passing callback parameter to a timer should throw exception"); Timer stateTimer = new Timer(null, autoEvent, 1000, 250); Log.Comment("Waiting and verifying"); autoEvent.WaitOne(7500, false); Log.Comment("Destroying timer."); stateTimer.Dispose(); } catch (Exception e) { Log.Comment("Correctly threw exception on null callback parameter name " + e.ToString()); testResult = MFTestResults.Pass; } return testResult; } [TestMethod] public MFTestResults Timer_MaxInt_DueTime_Test9() { /// /// 1. Creates a TimerCallback /// 2. Creates a Timer that calls it at 1 sec and every quarter sec thereafter /// 3. Verifies that the TimerCallback gets called /// 4. Changes duetime to MaxInt (in this case MaxInt assumed to be 4 sec) /// 5. Disposes of the timer after it signals /// 6. Verifies that the TimerCallback starts after 4 sec /// /// Log.Comment("Tests the Timer and TimerCallback classes, "); Log.Comment("as well as the Change and Dispose methods"); MFTestResults testResult = MFTestResults.Pass; AutoResetEvent autoEvent = new AutoResetEvent(false); StatusChecker statusChecker = new StatusChecker(15); Log.Comment("Creating the TimerCallback"); TimerCallback timerDelegate = new TimerCallback(statusChecker.CheckStatus); Log.Comment("Creating timer: " + DateTime.Now.ToString()); Timer stateTimer = new Timer(timerDelegate, autoEvent, 1000, 250); statusChecker.m_result = false; Log.Comment("Waiting and verifying"); autoEvent.WaitOne(5000, false); if (!statusChecker.m_result) { Log.Comment("Failure : expected callback '" + statusChecker.m_maxCount + "' times but got '" + statusChecker.m_invokeCount + "'"); testResult = MFTestResults.Fail; } statusChecker.m_result = false; statusChecker.z_flag = true; Log.Comment("Changing duetime to 4 sec (Assumed MaxInt)"); DateTime t1 = DateTime.Now; stateTimer.Change(4000, 250); Log.Comment("Waiting and verifying"); autoEvent.WaitOne(8000, false); TimeSpan duration = statusChecker.t2 - t1; Log.Comment("Verifying callback method 1st invoked after 4000msec."); if (duration.CompareTo(new TimeSpan(4000)) <= 0) { Log.Comment("Failure : expected 1st callback happens more than" + " '4000msec.' but happened after '" + duration.ToString() + "'"); testResult = MFTestResults.Fail; } if (!statusChecker.m_result) { Log.Comment("Failure : expected callback '" + statusChecker.m_maxCount + "' times but got '" + statusChecker.m_invokeCount + "'"); testResult = MFTestResults.Fail; } Log.Comment("Destroying timer."); stateTimer.Dispose(); return testResult; } [TestMethod] public MFTestResults Timer_MaxInt_Period_Test10() { /// /// 1. Creates a TimerCallback /// 2. Creates a Timer that calls it at 1 sec and every quarter sec thereafter /// 3. Verifies that the TimerCallback gets called /// 4. Changes period to MaxInt (in this case MaxInt assumed to be 4 sec) /// 5. Disposes of the timer after it signals /// 6. Verifies that the TimerCallback starts every 4 sec /// /// Log.Comment("Tests the Timer and TimerCallback classes, "); Log.Comment("as well as the Change and Dispose methods"); MFTestResults testResult = MFTestResults.Pass; AutoResetEvent autoEvent = new AutoResetEvent(false); StatusChecker statusChecker = new StatusChecker(15); Log.Comment("Creating the TimerCallback"); TimerCallback timerDelegate = new TimerCallback(statusChecker.CheckStatus); Log.Comment("Creating timer: " + DateTime.Now.ToString()); Timer stateTimer = new Timer(timerDelegate, autoEvent, 1000, 250); statusChecker.m_result = false; Log.Comment("Waiting and verifying"); autoEvent.WaitOne(5000, false); if (!statusChecker.m_result) { Log.Comment("Failure : expected callback '" + statusChecker.m_maxCount + "' times but got '" + statusChecker.m_invokeCount + "'"); testResult = MFTestResults.Fail; } statusChecker.m_result = false; statusChecker.m_flag = true; Log.Comment("Changing period to 4 sec (Assumed MaxInt)"); stateTimer.Change(0, 4000); Log.Comment("Waiting and verifying callback method is invoked every 4 sec"); autoEvent.WaitOne(60000, false); if (!statusChecker.m_result) { Log.Comment("Failure : after 60sec. expected callback invoked '" + statusChecker.m_maxCount + "' times but got '" + statusChecker.m_invokeCount + "'"); testResult = MFTestResults.Fail; } Log.Comment("Verifying time interval b/n callback invoke is atleast 4sec."); TimeSpan duration = statusChecker.t2 - statusChecker.t1; if(duration.CompareTo(new TimeSpan(4000)) < 0) { Log.Comment("Failure : expected interval b/n callbacks at least '4sec' but got '"+duration.Seconds.ToString()+"sec'"); testResult = MFTestResults.Fail; } Log.Comment("Destroying timer."); stateTimer.Dispose(); return testResult; } } } ================================================ FILE: Zelig/Zelig/Test/RunTime/NETMF/mscorlib/types/ReferenceBoxingTests.cs ================================================ //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // Copyright (c) Microsoft Corporation. All rights reserved. //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// using System; namespace Microsoft.Zelig.Test { public class ReferenceBoxingTests : TestBase, ITestInterface { [SetUp] public InitializeResult Initialize() { Log.Comment("Adding set up for the tests"); return InitializeResult.ReadyToGo; } [TearDown] public void CleanUp() { Log.Comment("Cleaning up after the tests"); } public override TestResult Run( string[] args ) { TestResult result = TestResult.Pass; string testName = " ReferenceBoxingXX_"; int testNumber = 0; result |= Assert.CheckFailed( ReferenceBoxing01_Test( ), testName, ++testNumber ); result |= Assert.CheckFailed( ReferenceBoxing02_Test( ), testName, ++testNumber ); result |= Assert.CheckFailed( ReferenceBoxing03_Test( ), testName, ++testNumber ); result |= Assert.CheckFailed( ReferenceBoxing04_Test( ), testName, ++testNumber ); result |= Assert.CheckFailed( ReferenceBoxing05_Test( ), testName, ++testNumber ); result |= Assert.CheckFailed( ReferenceBoxing06_Test( ), testName, ++testNumber ); result |= Assert.CheckFailed( ReferenceBoxing07_Test( ), testName, ++testNumber ); result |= Assert.CheckFailed( ReferenceBoxing09_Test( ), testName, ++testNumber ); result |= Assert.CheckFailed( ReferenceBoxing11_Test( ), testName, ++testNumber ); result |= Assert.CheckFailed( ReferenceBoxing12_Test( ), testName, ++testNumber ); result |= Assert.CheckFailed( ReferenceBoxing13_Test( ), testName, ++testNumber ); result |= Assert.CheckFailed( ReferenceBoxing15_Test( ), testName, ++testNumber ); result |= Assert.CheckFailed( ReferenceBoxing16_Test( ), testName, ++testNumber ); result |= Assert.CheckFailed( ReferenceBoxing17_Test( ), testName, ++testNumber ); result |= Assert.CheckFailed( ReferenceBoxing18_Test( ), testName, ++testNumber ); result |= Assert.CheckFailed( ReferenceBoxing19_Test( ), testName, ++testNumber ); return result; } //ReferenceBoxing Test methods //The following tests were ported from folder current\test\cases\client\CLR\Conformance\4_values\Reference\Boxing //01,02,03,04,05,06,07,09,11,12,13,15,16,17,18,19 //All of these tests passed in the Baseline Document //Test Case Calls [TestMethod] public TestResult ReferenceBoxing01_Test() { Log.Comment("Testing byte"); if (ReferenceBoxingTestClass01.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult ReferenceBoxing02_Test() { Log.Comment("Testing short"); if (ReferenceBoxingTestClass02.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult ReferenceBoxing03_Test() { Log.Comment("Testing int"); if (ReferenceBoxingTestClass03.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult ReferenceBoxing04_Test() { Log.Comment("Testing long"); if (ReferenceBoxingTestClass04.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult ReferenceBoxing05_Test() { Log.Comment("Testing char"); if (ReferenceBoxingTestClass05.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult ReferenceBoxing06_Test() { Log.Comment("Testing float"); if (ReferenceBoxingTestClass06.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult ReferenceBoxing07_Test() { Log.Comment("Testing double"); if (ReferenceBoxingTestClass07.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult ReferenceBoxing09_Test() { Log.Comment("Testing bool"); if (ReferenceBoxingTestClass09.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult ReferenceBoxing11_Test() { Log.Comment("Testing enum"); if (ReferenceBoxingTestClass11.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult ReferenceBoxing12_Test() { Log.Comment("Testing struct"); if (ReferenceBoxingTestClass12.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult ReferenceBoxing13_Test() { Log.Comment("Testing class, boxed by interface"); if (ReferenceBoxingTestClass13.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult ReferenceBoxing15_Test() { Log.Comment("Testing sbyte"); if (ReferenceBoxingTestClass15.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult ReferenceBoxing16_Test() { Log.Comment("Testing ushort"); if (ReferenceBoxingTestClass16.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult ReferenceBoxing17_Test() { Log.Comment("Testing uint"); if (ReferenceBoxingTestClass17.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult ReferenceBoxing18_Test() { Log.Comment("Testing ulong"); if (ReferenceBoxingTestClass18.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult ReferenceBoxing19_Test() { Log.Comment("Testing that sbyte, ushort, uint, ulong keep typing info"); if (ReferenceBoxingTestClass19.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } //Compiled Test Cases public class ReferenceBoxingTestClass01 { public static bool testMethod() { byte b1 = 2; object box = b1; object box2 = (byte)4; b1 = 3; if (((byte)box != (byte)2) || ((byte)box2 != (byte)4)) { return false; } else { return true; } } } public class ReferenceBoxingTestClass02 { public static bool testMethod() { short s1 = 2; object box = s1; object box2 = (short)4; s1 = 3; if (((short)box != (short)2) || ((short)box2 != (short)4)) { return false; } else { return true; } } } public class ReferenceBoxingTestClass03 { public static bool testMethod() { int i1 = 2; object box = i1; object box2 = 4; i1 = 3; if (((int)box != 2) || ((int)box2 != 4)) { return false; } else { return true; } } } public class ReferenceBoxingTestClass04 { public static bool testMethod() { long l1 = 2; object box = l1; object box2 = 4L; l1 = 3; if (((long)box != 2L) || ((long)box2 != 4L)) { return false; } else { return true; } } } public class ReferenceBoxingTestClass05 { public static bool testMethod() { char c1 = (char)2; object box = c1; object box2 = (char)4; c1 = (char)3; if (((char)box != (char)2) || ((char)box2 != (char)4)) { return false; } else { return true; } } } public class ReferenceBoxingTestClass06 { public static bool testMethod() { float f1 = 2.0f; object box = f1; object box2 = 4.0f; f1 = 3.0f; if (((float)box != 2.0f) || ((float)box2 != 4.0f)) { return false; } else { return true; } } } public class ReferenceBoxingTestClass07 { public static bool testMethod() { double d1 = 2.0d; object box = d1; object box2 = 4.0d; d1 = 3.0d; if (((double)box != 2.0d) || ((double)box2 != 4.0d)) { return false; } else { return true; } } } public class ReferenceBoxingTestClass09 { public static bool testMethod() { bool b1 = true; object box = b1; object box2 = false; b1 = false; if (((bool)box != true) || ((bool)box2 != false)) { return false; } else { return true; } } } enum ReferenceBoxingTestClass11_Enum { a = 2, b = 3 } public class ReferenceBoxingTestClass11 { public static bool testMethod() { ReferenceBoxingTestClass11_Enum MyEnum = ReferenceBoxingTestClass11_Enum.a; object box = MyEnum; object box2 = ReferenceBoxingTestClass11_Enum.b; MyEnum = ReferenceBoxingTestClass11_Enum.b; if (((ReferenceBoxingTestClass11_Enum)box != ReferenceBoxingTestClass11_Enum.a) || ((ReferenceBoxingTestClass11_Enum)box2 != ReferenceBoxingTestClass11_Enum.b)) { return false; } else { return true; } } } struct ReferenceBoxingTestClass12_Struct { public int MyInt; } public class ReferenceBoxingTestClass12 { public static bool testMethod() { ReferenceBoxingTestClass12_Struct MS = new ReferenceBoxingTestClass12_Struct(); MS.MyInt = 3; object box = MS; MS.MyInt = 4; if (((ReferenceBoxingTestClass12_Struct)box).MyInt != 3) { return false; } else { return true; } } } interface ReferenceBoxingTestClass13_Interface { void f(); } struct ReferenceBoxingTestClass13_Struct : ReferenceBoxingTestClass13_Interface { public int MyInt; public void f() { } } public class ReferenceBoxingTestClass13 { public static bool testMethod() { ReferenceBoxingTestClass13_Struct MS = new ReferenceBoxingTestClass13_Struct(); MS.MyInt = 3; ReferenceBoxingTestClass13_Interface box = MS; MS.MyInt = 4; if (((ReferenceBoxingTestClass13_Struct)box).MyInt != 3) { return false; } else { return true; } } } public class ReferenceBoxingTestClass15 { public static bool testMethod() { sbyte b1 = 2; object box = b1; object box2 = (sbyte)4; b1 = 3; if (((sbyte)box != (sbyte)2) || ((sbyte)box2 != (sbyte)4)) { return false; } else { return true; } } } public class ReferenceBoxingTestClass16 { public static bool testMethod() { ushort s1 = 2; object box = s1; object box2 = (ushort)4; s1 = 3; if (((ushort)box != (ushort)2) || ((ushort)box2 != (ushort)4)) { return false; } else { return true; } } } public class ReferenceBoxingTestClass17 { public static bool testMethod() { uint i1 = 2; object box = i1; object box2 = 4u; i1 = 3; if (((uint)box != 2) || ((uint)box2 != 4)) { return false; } else { return true; } } } public class ReferenceBoxingTestClass18 { public static bool testMethod() { ulong l1 = 2; object box = l1; object box2 = 4ul; l1 = 3; if (((ulong)box != 2ul) || ((ulong)box2 != 4ul)) { return false; } else { return true; } } } public class ReferenceBoxingTestClass19 { public static bool testMethod() { sbyte b1 = 2; ushort s1 = 3; uint i1 = 4; ulong l1 = 5; object box1 = b1; object box2 = s1; object box3 = i1; object box4 = l1; if ((box1 is sbyte) && (box2 is ushort) && (box3 is uint) && (box4 is ulong)) { return true; } else { return false; } return true; } } } } ================================================ FILE: Zelig/Zelig/Test/RunTime/NETMF/mscorlib/types/ValueArrayTests.cs ================================================ //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // Copyright (c) Microsoft Corporation. All rights reserved. //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// using System; namespace Microsoft.Zelig.Test { public class ValueArrayTests : TestBase, ITestInterface { [SetUp] public InitializeResult Initialize() { Log.Comment("Adding set up for the tests"); return InitializeResult.ReadyToGo; } [TearDown] public void CleanUp() { Log.Comment("Cleaning up after the tests"); } public override TestResult Run( string[] args ) { TestResult result = TestResult.Pass; string testName = " ValueArrayXX_"; int testNumber = 0; //////result |= Assert.CheckFailed( ValueArray01_Test( ), testName, ++testNumber ); //////result |= Assert.CheckFailed( ValueArray02_Test( ), testName, ++testNumber ); //////result |= Assert.CheckFailed( ValueArray03_Test( ), testName, ++testNumber ); //////result |= Assert.CheckFailed( ValueArray04_Test( ), testName, ++testNumber ); //////result |= Assert.CheckFailed( ValueArray05_Test( ), testName, ++testNumber ); //////result |= Assert.CheckFailed( ValueArray06_Test( ), testName, ++testNumber ); //////result |= Assert.CheckFailed( ValueArray07_Test( ), testName, ++testNumber ); //////result |= Assert.CheckFailed( ValueArray09_Test( ), testName, ++testNumber ); //////result |= Assert.CheckFailed( ValueArray12_Test( ), testName, ++testNumber ); //////result |= Assert.CheckFailed( ValueArray13_Test( ), testName, ++testNumber ); //////result |= Assert.CheckFailed( ValueArray14_Test( ), testName, ++testNumber ); //////result |= Assert.CheckFailed( ValueArray15_Test( ), testName, ++testNumber ); return result; } //ValueArray Test methods //The following tests were ported from folder current\test\cases\client\CLR\Conformance\4_values\ValueArray //01,02,03,04,05,06,07,09,11,12,13,14,15 //12 Failed //Test Case Calls //////[TestMethod] //////public TestResult ValueArray01_Test() //////{ ////// Log.Comment(" Section 4.1"); ////// Log.Comment(" byte is an alias for System.Byte"); ////// if (ValueArrayTestClass01.testMethod()) ////// { ////// return TestResult.Pass; ////// } ////// return TestResult.Fail; //////} //////[TestMethod] //////public TestResult ValueArray02_Test() //////{ ////// Log.Comment(" Section 4.1"); ////// Log.Comment(" char is an alias for System.Char"); ////// if (ValueArrayTestClass02.testMethod()) ////// { ////// return TestResult.Pass; ////// } ////// return TestResult.Fail; //////} //////[TestMethod] //////public TestResult ValueArray03_Test() ////// { ////// Log.Comment(" Section 4.1"); ////// Log.Comment(" short is an alias for System.Int16"); ////// if (ValueArrayTestClass03.testMethod()) ////// { ////// return TestResult.Pass; ////// } ////// return TestResult.Fail; //////} //////[TestMethod] //////public TestResult ValueArray04_Test() //////{ ////// Log.Comment(" Section 4.1"); ////// Log.Comment(" int is an alias for System.Int32"); ////// if (ValueArrayTestClass04.testMethod()) ////// { ////// return TestResult.Pass; ////// } ////// return TestResult.Fail; //////} //////[TestMethod] //////public TestResult ValueArray05_Test() //////{ ////// Log.Comment(" Section 4.1"); ////// Log.Comment(" long is an alias for System.Int64"); ////// if (ValueArrayTestClass05.testMethod()) ////// { ////// return TestResult.Pass; ////// } ////// return TestResult.Fail; //////} //////[TestMethod] //////public TestResult ValueArray06_Test() //////{ ////// Log.Comment(" Section 4.1"); ////// Log.Comment(" float is an alias for System.Single"); ////// if (ValueArrayTestClass06.testMethod()) ////// { ////// return TestResult.Pass; ////// } ////// return TestResult.Fail; //////} //////[TestMethod] //////public TestResult ValueArray07_Test() //////{ ////// Log.Comment(" Section 4.1"); ////// Log.Comment(" double is an alias for System.Double"); ////// if (ValueArrayTestClass07.testMethod()) ////// { ////// return TestResult.Pass; ////// } ////// return TestResult.Fail; //////} //////[TestMethod] //////public TestResult ValueArray09_Test() //////{ ////// Log.Comment(" Section 4.1"); ////// Log.Comment(" bool is an alias for System.Boolean"); ////// if (ValueArrayTestClass09.testMethod()) ////// { ////// return TestResult.Pass; ////// } ////// return TestResult.Fail; //////} //////[TestMethod] //////public TestResult ValueArray12_Test() //////{ ////// Log.Comment(" Section 4.1"); ////// Log.Comment(" Because a simple type aliases a struct type, every simple type has members."); ////// Log.Comment("This test is expected to fail"); ////// if (ValueArrayTestClass12.testMethod()) ////// { ////// return TestResult.Pass; ////// } ////// return TestResult.Fail; //////} //////[TestMethod] //////public TestResult ValueArray13_Test() //////{ ////// Log.Comment(" Section 4.1"); ////// Log.Comment(" sbyte is an alias for System.SByte"); ////// if (ValueArrayTestClass13.testMethod()) ////// { ////// return TestResult.Pass; ////// } ////// return TestResult.Fail; //////} //////[TestMethod] //////public TestResult ValueArray14_Test() //////{ ////// Log.Comment(" Section 4.1"); ////// Log.Comment(" ushort is an alias for System.UInt16"); ////// if (ValueArrayTestClass14.testMethod()) ////// { ////// return TestResult.Pass; ////// } ////// return TestResult.Fail; //////} //////[TestMethod] //////public TestResult ValueArray15_Test() //////{ ////// Log.Comment(" Section 4.1"); ////// Log.Comment(" uint is an alias for System.UInt32"); ////// if (ValueArrayTestClass15.testMethod()) ////// { ////// return TestResult.Pass; ////// } ////// return TestResult.Fail; //////} //Compiled Test Cases //////public class ValueArrayTestClass01 //////{ ////// public static bool testMethod() ////// { ////// byte[] b = {0} ; ////// if (b.GetType() == Type.GetType("System.Byte[]")) ////// { ////// return true; ////// } ////// else ////// { ////// return false; ////// } ////// } //////} //////public class ValueArrayTestClass02 //////{ ////// public static bool testMethod() ////// { ////// char [] c = {'a'}; ////// if (c.GetType() == Type.GetType("System.Char[]")) ////// { ////// return true; ////// } ////// else ////// { ////// return false; ////// } ////// } //////} //////public class ValueArrayTestClass03 //////{ ////// public static bool testMethod() ////// { ////// short [] s = {0}; ////// if (s.GetType() == Type.GetType("System.Int16[]")) ////// { ////// return true; ////// } ////// else ////// { ////// return false; ////// } ////// } //////} //////public class ValueArrayTestClass04 //////{ ////// public static bool testMethod() ////// { ////// int [] i = {0}; ////// if (i.GetType() == Type.GetType("System.Int32[]")) ////// { ////// return true; ////// } ////// else ////// { ////// return false; ////// } ////// } //////} //////public class ValueArrayTestClass05 //////{ ////// public static bool testMethod() ////// { ////// long [] l = {0L}; ////// if (l.GetType() == Type.GetType("System.Int64[]")) ////// { ////// return true; ////// } ////// else ////// { ////// return false; ////// } ////// } //////} //////public class ValueArrayTestClass06 //////{ ////// public static bool testMethod() ////// { ////// float [] f = {0.0f}; ////// if (f.GetType() == Type.GetType("System.Single[]")) ////// { ////// return true; ////// } ////// else ////// { ////// return false; ////// } ////// } //////} //////public class ValueArrayTestClass07 //////{ ////// public static bool testMethod() ////// { ////// double [] d = {0.0d}; ////// if (d.GetType() == Type.GetType("System.Double[]")) ////// { ////// return true; ////// } ////// else ////// { ////// return false; ////// } ////// } //////} //////public class ValueArrayTestClass09 //////{ ////// public static bool testMethod() ////// { ////// bool [] b = {true}; ////// if (b.GetType() == Type.GetType("System.Boolean[]")) ////// { ////// return true; ////// } ////// else ////// { ////// return false; ////// } ////// } //////} //////public class ValueArrayTestClass12 //////{ ////// public static bool testMethod() ////// { ////// string [] b = { "string" }; ////// if (b.GetType() == Type.GetType("System.String[]")) ////// { ////// return true; ////// } ////// else ////// { ////// return false; ////// } ////// } //////} //////public class ValueArrayTestClass13 //////{ ////// public static bool testMethod() ////// { ////// sbyte [] b = {0}; ////// if (b.GetType() == Type.GetType("System.SByte[]")) ////// { ////// return true; ////// } ////// else ////// { ////// return false; ////// } ////// } //////} //////public class ValueArrayTestClass14 //////{ ////// public static bool testMethod() ////// { ////// ushort [] s = {0}; ////// if (s.GetType() == Type.GetType("System.UInt16[]")) ////// { ////// return true; ////// } ////// else ////// { ////// return false; ////// } ////// } //////} //////public class ValueArrayTestClass15 //////{ ////// public static bool testMethod() ////// { ////// uint [] i = {0}; ////// if (i.GetType() == Type.GetType("System.UInt32[]")) ////// { ////// return true; ////// } ////// else ////// { ////// return false; ////// } ////// } //////} } } ================================================ FILE: Zelig/Zelig/Test/RunTime/NETMF/mscorlib/types/ValueDefault_ConstTests.cs ================================================ //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // Copyright (c) Microsoft Corporation. All rights reserved. //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// using System; namespace Microsoft.Zelig.Test { public class ValueDefault_ConstTests : TestBase, ITestInterface { [SetUp] public InitializeResult Initialize() { Log.Comment("Adding set up for the tests"); return InitializeResult.ReadyToGo; } [TearDown] public void CleanUp() { Log.Comment("Cleaning up after the tests"); } public override TestResult Run( string[] args ) { TestResult result = TestResult.Pass; string testName = "ValueDefault_ConstXX_"; int testNumber = 0; result |= Assert.CheckFailed( ValueDefault_Const01_Test( ), testName, ++testNumber ); result |= Assert.CheckFailed( ValueDefault_Const02_Test( ), testName, ++testNumber ); result |= Assert.CheckFailed( ValueDefault_Const03_Test( ), testName, ++testNumber ); result |= Assert.CheckFailed( ValueDefault_Const04_Test( ), testName, ++testNumber ); result |= Assert.CheckFailed( ValueDefault_Const05_Test( ), testName, ++testNumber ); result |= Assert.CheckFailed( ValueDefault_Const06_Test( ), testName, ++testNumber ); result |= Assert.CheckFailed( ValueDefault_Const07_Test( ), testName, ++testNumber ); result |= Assert.CheckFailed( ValueDefault_Const09_Test( ), testName, ++testNumber ); result |= Assert.CheckFailed( ValueDefault_Const11_Test( ), testName, ++testNumber ); result |= Assert.CheckFailed( ValueDefault_Const12_Test( ), testName, ++testNumber ); result |= Assert.CheckFailed( ValueDefault_Const14_Test( ), testName, ++testNumber ); result |= Assert.CheckFailed( ValueDefault_Const15_Test( ), testName, ++testNumber ); result |= Assert.CheckFailed( ValueDefault_Const16_Test( ), testName, ++testNumber ); result |= Assert.CheckFailed( ValueDefault_Const17_Test( ), testName, ++testNumber ); return result; } //ValueDefault_Const Test methods //The following tests were ported from folder current\test\cases\client\CLR\Conformance\4_values\Value\Default_Const //01,02,03,04,05,06,07,09,11,12,14,15,16,17 //All of these tests passed in the Baseline document //Test Case Calls [TestMethod] public TestResult ValueDefault_Const01_Test() { Log.Comment("Testing byte == 0"); if (ValueDefault_ConstTestClass01.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult ValueDefault_Const02_Test() { Log.Comment("Testing short == 0"); if (ValueDefault_ConstTestClass02.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult ValueDefault_Const03_Test() { Log.Comment("Testing int == 0"); if (ValueDefault_ConstTestClass03.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult ValueDefault_Const04_Test() { Log.Comment("Testing long == 0L"); if (ValueDefault_ConstTestClass04.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult ValueDefault_Const05_Test() { Log.Comment("Testing char == \x0000"); if (ValueDefault_ConstTestClass05.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult ValueDefault_Const06_Test() { Log.Comment("Testing float == 0.0f"); if (ValueDefault_ConstTestClass06.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult ValueDefault_Const07_Test() { Log.Comment("Testing double == 0.0d"); if (ValueDefault_ConstTestClass07.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult ValueDefault_Const09_Test() { Log.Comment("Testing bool == false"); if (ValueDefault_ConstTestClass09.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult ValueDefault_Const11_Test() { Log.Comment("Testing enum"); if (ValueDefault_ConstTestClass11.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult ValueDefault_Const12_Test() { Log.Comment("Testing struct"); if (ValueDefault_ConstTestClass12.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult ValueDefault_Const14_Test() { Log.Comment("Testing sbyte == 0"); if (ValueDefault_ConstTestClass14.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult ValueDefault_Const15_Test() { Log.Comment("Testing ushort == 0"); if (ValueDefault_ConstTestClass15.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult ValueDefault_Const16_Test() { Log.Comment("Testing uint == 0"); if (ValueDefault_ConstTestClass16.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult ValueDefault_Const17_Test() { Log.Comment("Testing ulong == 0"); if (ValueDefault_ConstTestClass17.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } //Compiled Test Cases public class ValueDefault_ConstTestClass01 { public static bool testMethod() { byte b = new byte(); if (b == (byte)0) { return true; } else { return false; } } } public class ValueDefault_ConstTestClass02 { public static bool testMethod() { short s = new short(); if (s == (short)0) { return true; } else { return false; } } } public class ValueDefault_ConstTestClass03 { public static bool testMethod() { int i = new int(); if (i == 0) { return true; } else { return false; } } } public class ValueDefault_ConstTestClass04 { public static bool testMethod() { long l = new long(); if (l == 0L) { return true; } else { return false; } } } public class ValueDefault_ConstTestClass05 { public static bool testMethod() { char c = new char(); if (c == '\x0000') { return true; } else { return false; } } } public class ValueDefault_ConstTestClass06 { public static bool testMethod() { float f = new float(); if (f == 0.0f) { return true; } else { return false; } } } public class ValueDefault_ConstTestClass07 { public static bool testMethod() { double d = new double(); if (d == 0.0d) { return true; } else { return false; } } } public class ValueDefault_ConstTestClass09 { public static bool testMethod() { bool b = new bool(); if (b == false) { return true; } else { return false; } } } enum E { a = 1, b = 2 }; public class ValueDefault_ConstTestClass11 { public static bool testMethod() { E e = new E(); if (e == ((E)0)) { return true; } else { return false; } } } struct MyStruct { public int I; public Object MyObj; } public class ValueDefault_ConstTestClass12 { public static bool testMethod() { MyStruct TC = new MyStruct(); if ((TC.I == 0) && (TC.MyObj == null)) { return true; } else { return false; } } } public class ValueDefault_ConstTestClass14 { public static bool testMethod() { sbyte b = new sbyte(); if (b == (sbyte)0) { return true; } else { return false; } } } public class ValueDefault_ConstTestClass15 { public static bool testMethod() { ushort b = new ushort(); if (b == (ushort)0) { return true; } else { return false; } } } public class ValueDefault_ConstTestClass16 { public static bool testMethod() { uint b = new uint(); if (b == (uint)0) { return true; } else { return false; } } } public class ValueDefault_ConstTestClass17 { public static bool testMethod() { ulong b = new ulong(); if (b == (ulong)0) { return true; } else { return false; } } } } } ================================================ FILE: Zelig/Zelig/Test/RunTime/NETMF/mscorlib/types/ValueFloatTests.cs ================================================ //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // Copyright (c) Microsoft Corporation. All rights reserved. //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// using System; namespace Microsoft.Zelig.Test { public class ValueFloatTests : TestBase, ITestInterface { [SetUp] public InitializeResult Initialize() { Log.Comment("Adding set up for the tests"); return InitializeResult.ReadyToGo; } [TearDown] public void CleanUp() { Log.Comment("Cleaning up after the tests"); } public override TestResult Run( string[] args ) { TestResult result = TestResult.Pass; string testName = " ValueFloatXX_"; int testNumber = 0; result |= Assert.CheckFailed( ValueFloat04_Test( ), testName, ++testNumber ); result |= Assert.CheckFailed( ValueFloat05_Test( ), testName, ++testNumber ); result |= Assert.CheckFailed( ValueFloat06_Test( ), testName, ++testNumber ); result |= Assert.CheckFailed( ValueFloat07_Test( ), testName, ++testNumber ); result |= Assert.CheckFailed( ValueFloat08_Test( ), testName, ++testNumber ); result |= Assert.CheckFailed( ValueFloat09_Test( ), testName, ++testNumber ); result |= Assert.CheckFailed( ValueFloat10_Test( ), testName, ++testNumber ); result |= Assert.CheckFailed( ValueFloat11_Test( ), testName, ++testNumber ); result |= Assert.CheckFailed( ValueFloat12_Test( ), testName, ++testNumber ); result |= Assert.CheckFailed( ValueFloat13_Test( ), testName, ++testNumber ); result |= Assert.CheckFailed( ValueFloat14_Test( ), testName, ++testNumber ); result |= Assert.CheckFailed( ValueFloat15_Test( ), testName, ++testNumber ); result |= Assert.CheckFailed( ValueFloat16_Test( ), testName, ++testNumber ); result |= Assert.CheckFailed( ValueFloat17_Test( ), testName, ++testNumber ); result |= Assert.CheckFailed( ValueFloat18_Test( ), testName, ++testNumber ); result |= Assert.CheckFailed( ValueFloat19_Test( ), testName, ++testNumber ); result |= Assert.CheckFailed( ValueFloat20_Test( ), testName, ++testNumber ); result |= Assert.CheckFailed( ValueFloat21_Test( ), testName, ++testNumber ); result |= Assert.CheckFailed( ValueFloat22_Test( ), testName, ++testNumber ); result |= Assert.CheckFailed( ValueFloat23_Test( ), testName, ++testNumber ); result |= Assert.CheckFailed( ValueFloat24_Test( ), testName, ++testNumber ); result |= Assert.CheckFailed( ValueFloat25_Test( ), testName, ++testNumber ); result |= Assert.CheckFailed( ValueFloat26_Test( ), testName, ++testNumber ); result |= Assert.CheckFailed( ValueFloat27_Test( ), testName, ++testNumber ); result |= Assert.CheckFailed( ValueFloat28_Test( ), testName, ++testNumber ); result |= Assert.CheckFailed( ValueFloat29_Test( ), testName, ++testNumber ); result |= Assert.CheckFailed( ValueFloat30_Test( ), testName, ++testNumber ); return result; } //ValueFloat Test methods //The following tests were ported from folder current\test\cases\client\CLR\Conformance\4_values\Value\Float //01,03,04,05,06,07,08,09,10,11,12,13,14, //15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31,32 //1,3,31,32 Were Skipped in the Baseline document, all others passed //2,33-36 Were removed because they test Float.NaN which is not implemented //They were skipped in the Baseline document //Test Case Calls [TestMethod] public TestResult ValueFloat04_Test() { Log.Comment("Testing float type is kept after addition with other types"); if (ValueFloatTestClass04.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult ValueFloat05_Test() { Log.Comment("Testing double type is kept after addition with other types"); if (ValueFloatTestClass05.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult ValueFloat06_Test() { Log.Comment("Testing float type is kept after subtraction with other types"); if (ValueFloatTestClass06.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult ValueFloat07_Test() { Log.Comment("Testing double type is kept after subtraction with other types"); if (ValueFloatTestClass07.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult ValueFloat08_Test() { Log.Comment("Testing float type is kept after multiplication with other types"); if (ValueFloatTestClass08.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult ValueFloat09_Test() { Log.Comment("Testing double type is kept after maultiplication with other types"); if (ValueFloatTestClass09.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult ValueFloat10_Test() { Log.Comment("Testing float type is kept after division with other types"); if (ValueFloatTestClass10.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult ValueFloat11_Test() { Log.Comment("Testing double type is kept after division with other types"); if (ValueFloatTestClass11.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult ValueFloat12_Test( ) { Log.Comment( "Testing float type is kept after modulus with other types" ); if(ValueFloatTestClass12.testMethod( )) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult ValueFloat13_Test( ) { Log.Comment( "Testing double type is kept after modulus with other types" ); if(ValueFloatTestClass13.testMethod( )) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult ValueFloat14_Test() { Log.Comment("Testing that equality operations return bool type objects"); if (ValueFloatTestClass14.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult ValueFloat15_Test() { Log.Comment("Testing that equality operations return bool type objects"); if (ValueFloatTestClass15.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult ValueFloat16_Test() { Log.Comment("Testing that non-equality operations return bool type objects"); if (ValueFloatTestClass16.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult ValueFloat17_Test() { Log.Comment("Testing that non-equality operations return bool type objects"); if (ValueFloatTestClass17.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult ValueFloat18_Test() { Log.Comment("Testing that greater than operations return bool type objects"); if (ValueFloatTestClass18.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult ValueFloat19_Test() { Log.Comment("Testing that greater than operations return bool type objects"); if (ValueFloatTestClass19.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult ValueFloat20_Test() { Log.Comment("Testing that less than operations return bool type objects"); if (ValueFloatTestClass20.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult ValueFloat21_Test() { Log.Comment("Testing that less than operations return bool type objects"); if (ValueFloatTestClass21.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult ValueFloat22_Test() { Log.Comment("Testing that greater than or equal operations return bool type objects"); if (ValueFloatTestClass22.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult ValueFloat23_Test() { Log.Comment("Testing that greater than or equal operations return bool type objects"); if (ValueFloatTestClass23.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult ValueFloat24_Test() { Log.Comment("Testing that less than or equal operations return bool type objects"); if (ValueFloatTestClass24.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult ValueFloat25_Test() { Log.Comment("Testing that less than or equal operations return bool type objects"); if (ValueFloatTestClass25.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult ValueFloat26_Test() { Log.Comment("Testing that double keeps its type in all operations with float"); if (ValueFloatTestClass26.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult ValueFloat27_Test() { Log.Comment("Testing that comparisons between floats and doubles return bools"); if (ValueFloatTestClass27.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult ValueFloat28_Test() { Log.Comment("Testing that float keeps its type after any operation with a float"); if (ValueFloatTestClass28.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult ValueFloat29_Test() { Log.Comment("Testing that comparisons between floats return bools"); if (ValueFloatTestClass29.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult ValueFloat30_Test() { Log.Comment("Testing float and double .epsilon values"); if (ValueFloatTestClass30.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } public class ValueFloatTestClass04 { public static bool testMethod() { int intRet = 0; float f1 = 11.0f; short s1 = 2; byte b1 = 3; int i1 = 4; long l1 = 5L; char c1 = (char)6; if ((f1 + s1).GetType() != f1.GetType()) { intRet = 1; } if ((s1 + f1).GetType() != f1.GetType()) { intRet = 1; } if ((f1 + b1).GetType() != f1.GetType()) { intRet = 1; } if ((b1 + f1).GetType() != f1.GetType()) { intRet = 1; } if ((f1 + i1).GetType() != f1.GetType()) { intRet = 1; } if ((i1 + f1).GetType() != f1.GetType()) { intRet = 1; } if ((f1 + l1).GetType() != f1.GetType()) { intRet = 1; } if ((l1 + f1).GetType() != f1.GetType()) { intRet = 1; } if ((f1 + c1).GetType() != f1.GetType()) { intRet = 1; } if ((c1 + f1).GetType() != f1.GetType()) { intRet = 1; } return (intRet == 0); } } public class ValueFloatTestClass05 { public static bool testMethod() { int intRet = 0; double d1 = 11.0d; short s1 = 2; byte b1 = 3; int i1 = 4; long l1 = 5L; char c1 = (char)6; if ((d1 + s1).GetType() != d1.GetType()) { intRet = 1; } if ((s1 + d1).GetType() != d1.GetType()) { intRet = 1; } if ((d1 + b1).GetType() != d1.GetType()) { intRet = 1; } if ((b1 + d1).GetType() != d1.GetType()) { intRet = 1; } if ((d1 + i1).GetType() != d1.GetType()) { intRet = 1; } if ((i1 + d1).GetType() != d1.GetType()) { intRet = 1; } if ((d1 + l1).GetType() != d1.GetType()) { intRet = 1; } if ((l1 + d1).GetType() != d1.GetType()) { intRet = 1; } if ((d1 + c1).GetType() != d1.GetType()) { intRet = 1; } if ((c1 + d1).GetType() != d1.GetType()) { intRet = 1; } return (intRet == 0); } } public class ValueFloatTestClass06 { public static bool testMethod() { int intRet = 0; float f1 = 11.0f; short s1 = 2; byte b1 = 3; int i1 = 4; long l1 = 5L; char c1 = (char)6; if ((f1 - s1).GetType() != f1.GetType()) { intRet = 1; } if ((s1 - f1).GetType() != f1.GetType()) { intRet = 1; } if ((f1 - b1).GetType() != f1.GetType()) { intRet = 1; } if ((b1 - f1).GetType() != f1.GetType()) { intRet = 1; } if ((f1 - i1).GetType() != f1.GetType()) { intRet = 1; } if ((i1 - f1).GetType() != f1.GetType()) { intRet = 1; } if ((f1 - l1).GetType() != f1.GetType()) { intRet = 1; } if ((l1 - f1).GetType() != f1.GetType()) { intRet = 1; } if ((f1 - c1).GetType() != f1.GetType()) { intRet = 1; } if ((c1 - f1).GetType() != f1.GetType()) { intRet = 1; } return (intRet == 0); } } public class ValueFloatTestClass07 { public static bool testMethod() { int intRet = 0; double d1 = 11.0d; short s1 = 2; byte b1 = 3; int i1 = 4; long l1 = 5L; char c1 = (char)6; if ((d1 - s1).GetType() != d1.GetType()) { intRet = 1; } if ((s1 - d1).GetType() != d1.GetType()) { intRet = 1; } if ((d1 - b1).GetType() != d1.GetType()) { intRet = 1; } if ((b1 - d1).GetType() != d1.GetType()) { intRet = 1; } if ((d1 - i1).GetType() != d1.GetType()) { intRet = 1; } if ((i1 - d1).GetType() != d1.GetType()) { intRet = 1; } if ((d1 - l1).GetType() != d1.GetType()) { intRet = 1; } if ((l1 - d1).GetType() != d1.GetType()) { intRet = 1; } if ((d1 - c1).GetType() != d1.GetType()) { intRet = 1; } if ((c1 - d1).GetType() != d1.GetType()) { intRet = 1; } return (intRet == 0); } } public class ValueFloatTestClass08 { public static bool testMethod() { int intRet = 0; float f1 = 11.0f; short s1 = 2; byte b1 = 3; int i1 = 4; long l1 = 5L; char c1 = (char)6; if ((f1 * s1).GetType() != f1.GetType()) { intRet = 1; } if ((s1 * f1).GetType() != f1.GetType()) { intRet = 1; } if ((f1 * b1).GetType() != f1.GetType()) { intRet = 1; } if ((b1 * f1).GetType() != f1.GetType()) { intRet = 1; } if ((f1 * i1).GetType() != f1.GetType()) { intRet = 1; } if ((i1 * f1).GetType() != f1.GetType()) { intRet = 1; } if ((f1 * l1).GetType() != f1.GetType()) { intRet = 1; } if ((l1 * f1).GetType() != f1.GetType()) { intRet = 1; } if ((f1 * c1).GetType() != f1.GetType()) { intRet = 1; } if ((c1 * f1).GetType() != f1.GetType()) { intRet = 1; } return (intRet == 0); } } public class ValueFloatTestClass09 { public static bool testMethod() { int intRet = 0; double d1 = 11.0d; short s1 = 2; byte b1 = 3; int i1 = 4; long l1 = 5L; char c1 = (char)6; if ((d1 * s1).GetType() != d1.GetType()) { intRet = 1; } if ((s1 * d1).GetType() != d1.GetType()) { intRet = 1; } if ((d1 * b1).GetType() != d1.GetType()) { intRet = 1; } if ((b1 * d1).GetType() != d1.GetType()) { intRet = 1; } if ((d1 * i1).GetType() != d1.GetType()) { intRet = 1; } if ((i1 * d1).GetType() != d1.GetType()) { intRet = 1; } if ((d1 * l1).GetType() != d1.GetType()) { intRet = 1; } if ((l1 * d1).GetType() != d1.GetType()) { intRet = 1; } if ((d1 * c1).GetType() != d1.GetType()) { intRet = 1; } if ((c1 * d1).GetType() != d1.GetType()) { intRet = 1; } return (intRet == 0); } } public class ValueFloatTestClass10 { public static bool testMethod() { int intRet = 0; float f1 = 11.0f; short s1 = 2; byte b1 = 3; int i1 = 4; long l1 = 5L; char c1 = (char)6; if ((f1 / s1).GetType() != f1.GetType()) { intRet = 1; } if ((s1 / f1).GetType() != f1.GetType()) { intRet = 1; } if ((f1 / b1).GetType() != f1.GetType()) { intRet = 1; } if ((b1 / f1).GetType() != f1.GetType()) { intRet = 1; } if ((f1 / i1).GetType() != f1.GetType()) { intRet = 1; } if ((i1 / f1).GetType() != f1.GetType()) { intRet = 1; } if ((f1 / l1).GetType() != f1.GetType()) { intRet = 1; } if ((l1 / f1).GetType() != f1.GetType()) { intRet = 1; } if ((f1 / c1).GetType() != f1.GetType()) { intRet = 1; } if ((c1 / f1).GetType() != f1.GetType()) { intRet = 1; } return (intRet == 0); } } public class ValueFloatTestClass11 { public static bool testMethod() { int intRet = 0; double d1 = 11.0d; short s1 = 2; byte b1 = 3; int i1 = 4; long l1 = 5L; char c1 = (char)6; if ((d1 / s1).GetType() != d1.GetType()) { intRet = 1; } if ((s1 / d1).GetType() != d1.GetType()) { intRet = 1; } if ((d1 / b1).GetType() != d1.GetType()) { intRet = 1; } if ((b1 / d1).GetType() != d1.GetType()) { intRet = 1; } if ((d1 / i1).GetType() != d1.GetType()) { intRet = 1; } if ((i1 / d1).GetType() != d1.GetType()) { intRet = 1; } if ((d1 / l1).GetType() != d1.GetType()) { intRet = 1; } if ((l1 / d1).GetType() != d1.GetType()) { intRet = 1; } if ((d1 / c1).GetType() != d1.GetType()) { intRet = 1; } if ((c1 / d1).GetType() != d1.GetType()) { intRet = 1; } return (intRet == 0); } } public class ValueFloatTestClass12 { public static bool testMethod( ) { int intRet = 0; float f1 = 11.0f; short s1 = 2; byte b1 = 3; int i1 = 4; long l1 = 5L; char c1 = (char)6; if(( f1 % s1 ).GetType( ) != f1.GetType( )) { intRet = 1; } if(( s1 % f1 ).GetType( ) != f1.GetType( )) { intRet = 1; } if(( f1 % b1 ).GetType( ) != f1.GetType( )) { intRet = 1; } if(( b1 % f1 ).GetType( ) != f1.GetType( )) { intRet = 1; } if(( f1 % i1 ).GetType( ) != f1.GetType( )) { intRet = 1; } if(( i1 % f1 ).GetType( ) != f1.GetType( )) { intRet = 1; } if(( f1 % l1 ).GetType( ) != f1.GetType( )) { intRet = 1; } if(( l1 % f1 ).GetType( ) != f1.GetType( )) { intRet = 1; } if(( f1 % c1 ).GetType( ) != f1.GetType( )) { intRet = 1; } if(( c1 % f1 ).GetType( ) != f1.GetType( )) { intRet = 1; } return ( intRet == 0 ); } } public class ValueFloatTestClass13 { public static bool testMethod( ) { int intRet = 0; double d1 = 11.0d; short s1 = 2; byte b1 = 3; int i1 = 4; long l1 = 5L; char c1 = (char)6; if(( d1 % s1 ).GetType( ) != d1.GetType( )) { intRet = 1; } if(( s1 % d1 ).GetType( ) != d1.GetType( )) { intRet = 1; } if(( d1 % b1 ).GetType( ) != d1.GetType( )) { intRet = 1; } if(( b1 % d1 ).GetType( ) != d1.GetType( )) { intRet = 1; } if(( d1 % i1 ).GetType( ) != d1.GetType( )) { intRet = 1; } if(( i1 % d1 ).GetType( ) != d1.GetType( )) { intRet = 1; } if(( d1 % l1 ).GetType( ) != d1.GetType( )) { intRet = 1; } if(( l1 % d1 ).GetType( ) != d1.GetType( )) { intRet = 1; } if(( d1 % c1 ).GetType( ) != d1.GetType( )) { intRet = 1; } if(( c1 % d1 ).GetType( ) != d1.GetType( )) { intRet = 1; } return ( intRet == 0 ); } } public class ValueFloatTestClass14 { public static bool testMethod( ) { int intRet = 0; bool b = true; float f1 = 11.0f; short s1 = 2; byte b1 = 3; int i1 = 4; long l1 = 5L; char c1 = (char)6; if(( f1 == s1 ).GetType( ) != b.GetType( )) { intRet = 1; } if(( s1 == f1 ).GetType( ) != b.GetType( )) { intRet = 1; } if(( f1 == b1 ).GetType( ) != b.GetType( )) { intRet = 1; } if(( b1 == f1 ).GetType( ) != b.GetType( )) { intRet = 1; } if(( f1 == i1 ).GetType( ) != b.GetType( )) { intRet = 1; } if(( i1 == f1 ).GetType( ) != b.GetType( )) { intRet = 1; } if(( f1 == l1 ).GetType( ) != b.GetType( )) { intRet = 1; } if ((l1 == f1).GetType() != b.GetType()) { intRet = 1; } if ((f1 == c1).GetType() != b.GetType()) { intRet = 1; } if ((c1 == f1).GetType() != b.GetType()) { intRet = 1; } return (intRet == 0); } } public class ValueFloatTestClass15 { public static bool testMethod() { int intRet = 0; bool b = false; double d1 = 11.0d; short s1 = 2; byte b1 = 3; int i1 = 4; long l1 = 5L; char c1 = (char)6; if ((d1 == s1).GetType() != b.GetType()) { intRet = 1; } if ((s1 == d1).GetType() != b.GetType()) { intRet = 1; } if ((d1 == b1).GetType() != b.GetType()) { intRet = 1; } if ((b1 == d1).GetType() != b.GetType()) { intRet = 1; } if ((d1 == i1).GetType() != b.GetType()) { intRet = 1; } if ((i1 == d1).GetType() != b.GetType()) { intRet = 1; } if ((d1 == l1).GetType() != b.GetType()) { intRet = 1; } if ((l1 == d1).GetType() != b.GetType()) { intRet = 1; } if ((d1 == c1).GetType() != b.GetType()) { intRet = 1; } if ((c1 == d1).GetType() != b.GetType()) { intRet = 1; } return (intRet == 0); } } public class ValueFloatTestClass16 { public static bool testMethod() { int intRet = 0; bool b = true; float f1 = 11.0f; short s1 = 2; byte b1 = 3; int i1 = 4; long l1 = 5L; char c1 = (char)6; if ((f1 != s1).GetType() != b.GetType()) { intRet = 1; } if ((s1 != f1).GetType() != b.GetType()) { intRet = 1; } if ((f1 != b1).GetType() != b.GetType()) { intRet = 1; } if ((b1 != f1).GetType() != b.GetType()) { intRet = 1; } if ((f1 != i1).GetType() != b.GetType()) { intRet = 1; } if ((i1 != f1).GetType() != b.GetType()) { intRet = 1; } if ((f1 != l1).GetType() != b.GetType()) { intRet = 1; } if ((l1 != f1).GetType() != b.GetType()) { intRet = 1; } if ((f1 != c1).GetType() != b.GetType()) { intRet = 1; } if ((c1 != f1).GetType() != b.GetType()) { intRet = 1; } return (intRet == 0); } } public class ValueFloatTestClass17 { public static bool testMethod() { int intRet = 0; bool b = false; double d1 = 11.0d; short s1 = 2; byte b1 = 3; int i1 = 4; long l1 = 5L; char c1 = (char)6; if ((d1 != s1).GetType() != b.GetType()) { intRet = 1; } if ((s1 != d1).GetType() != b.GetType()) { intRet = 1; } if ((d1 != b1).GetType() != b.GetType()) { intRet = 1; } if ((b1 != d1).GetType() != b.GetType()) { intRet = 1; } if ((d1 != i1).GetType() != b.GetType()) { intRet = 1; } if ((i1 != d1).GetType() != b.GetType()) { intRet = 1; } if ((d1 != l1).GetType() != b.GetType()) { intRet = 1; } if ((l1 != d1).GetType() != b.GetType()) { intRet = 1; } if ((d1 != c1).GetType() != b.GetType()) { intRet = 1; } if ((c1 != d1).GetType() != b.GetType()) { intRet = 1; } return (intRet == 0); } } public class ValueFloatTestClass18 { public static bool testMethod() { int intRet = 0; bool b = true; float f1 = 11.0f; short s1 = 2; byte b1 = 3; int i1 = 4; long l1 = 5L; char c1 = (char)6; if ((f1 > s1).GetType() != b.GetType()) { intRet = 1; } if ((s1 > f1).GetType() != b.GetType()) { intRet = 1; } if ((f1 > b1).GetType() != b.GetType()) { intRet = 1; } if ((b1 > f1).GetType() != b.GetType()) { intRet = 1; } if ((f1 > i1).GetType() != b.GetType()) { intRet = 1; } if ((i1 > f1).GetType() != b.GetType()) { intRet = 1; } if ((f1 > l1).GetType() != b.GetType()) { intRet = 1; } if ((l1 > f1).GetType() != b.GetType()) { intRet = 1; } if ((f1 > c1).GetType() != b.GetType()) { intRet = 1; } if ((c1 > f1).GetType() != b.GetType()) { intRet = 1; } return (intRet == 0); } } public class ValueFloatTestClass19 { public static bool testMethod() { int intRet = 0; bool b = false; double d1 = 11.0d; short s1 = 2; byte b1 = 3; int i1 = 4; long l1 = 5L; char c1 = (char)6; if ((d1 > s1).GetType() != b.GetType()) { intRet = 1; } if ((s1 > d1).GetType() != b.GetType()) { intRet = 1; } if ((d1 > b1).GetType() != b.GetType()) { intRet = 1; } if ((b1 > d1).GetType() != b.GetType()) { intRet = 1; } if ((d1 > i1).GetType() != b.GetType()) { intRet = 1; } if ((i1 > d1).GetType() != b.GetType()) { intRet = 1; } if ((d1 > l1).GetType() != b.GetType()) { intRet = 1; } if ((l1 > d1).GetType() != b.GetType()) { intRet = 1; } if ((d1 > c1).GetType() != b.GetType()) { intRet = 1; } if ((c1 > d1).GetType() != b.GetType()) { intRet = 1; } return (intRet == 0); } } public class ValueFloatTestClass20 { public static bool testMethod() { int intRet = 0; bool b = true; float f1 = 11.0f; short s1 = 2; byte b1 = 3; int i1 = 4; long l1 = 5L; char c1 = (char)6; if ((f1 < s1).GetType() != b.GetType()) { intRet = 1; } if ((s1 < f1).GetType() != b.GetType()) { intRet = 1; } if ((f1 < b1).GetType() != b.GetType()) { intRet = 1; } if ((b1 < f1).GetType() != b.GetType()) { intRet = 1; } if ((f1 < i1).GetType() != b.GetType()) { intRet = 1; } if ((i1 < f1).GetType() != b.GetType()) { intRet = 1; } if ((f1 < l1).GetType() != b.GetType()) { intRet = 1; } if ((l1 < f1).GetType() != b.GetType()) { intRet = 1; } if ((f1 < c1).GetType() != b.GetType()) { intRet = 1; } if ((c1 < f1).GetType() != b.GetType()) { intRet = 1; } return (intRet == 0); } } public class ValueFloatTestClass21 { public static bool testMethod() { int intRet = 0; bool b = false; double d1 = 11.0d; short s1 = 2; byte b1 = 3; int i1 = 4; long l1 = 5L; char c1 = (char)6; if ((d1 < s1).GetType() != b.GetType()) { intRet = 1; } if ((s1 < d1).GetType() != b.GetType()) { intRet = 1; } if ((d1 < b1).GetType() != b.GetType()) { intRet = 1; } if ((b1 < d1).GetType() != b.GetType()) { intRet = 1; } if ((d1 < i1).GetType() != b.GetType()) { intRet = 1; } if ((i1 < d1).GetType() != b.GetType()) { intRet = 1; } if ((d1 < l1).GetType() != b.GetType()) { intRet = 1; } if ((l1 < d1).GetType() != b.GetType()) { intRet = 1; } if ((d1 < c1).GetType() != b.GetType()) { intRet = 1; } if ((c1 < d1).GetType() != b.GetType()) { intRet = 1; } return (intRet == 0); } } public class ValueFloatTestClass22 { public static bool testMethod() { int intRet = 0; bool b = true; float f1 = 11.0f; short s1 = 2; byte b1 = 3; int i1 = 4; long l1 = 5L; char c1 = (char)6; if ((f1 >= s1).GetType() != b.GetType()) { intRet = 1; } if ((s1 >= f1).GetType() != b.GetType()) { intRet = 1; } if ((f1 >= b1).GetType() != b.GetType()) { intRet = 1; } if ((b1 >= f1).GetType() != b.GetType()) { intRet = 1; } if ((f1 >= i1).GetType() != b.GetType()) { intRet = 1; } if ((i1 >= f1).GetType() != b.GetType()) { intRet = 1; } if ((f1 >= l1).GetType() != b.GetType()) { intRet = 1; } if ((l1 >= f1).GetType() != b.GetType()) { intRet = 1; } if ((f1 >= c1).GetType() != b.GetType()) { intRet = 1; } if ((c1 >= f1).GetType() != b.GetType()) { intRet = 1; } return (intRet == 0); } } public class ValueFloatTestClass23 { public static bool testMethod() { int intRet = 0; bool b = false; double d1 = 11.0d; short s1 = 2; byte b1 = 3; int i1 = 4; long l1 = 5L; char c1 = (char)6; if ((d1 >= s1).GetType() != b.GetType()) { intRet = 1; } if ((s1 >= d1).GetType() != b.GetType()) { intRet = 1; } if ((d1 >= b1).GetType() != b.GetType()) { intRet = 1; } if ((b1 >= d1).GetType() != b.GetType()) { intRet = 1; } if ((d1 >= i1).GetType() != b.GetType()) { intRet = 1; } if ((i1 >= d1).GetType() != b.GetType()) { intRet = 1; } if ((d1 >= l1).GetType() != b.GetType()) { intRet = 1; } if ((l1 >= d1).GetType() != b.GetType()) { intRet = 1; } if ((d1 >= c1).GetType() != b.GetType()) { intRet = 1; } if ((c1 >= d1).GetType() != b.GetType()) { intRet = 1; } return (intRet == 0); } } public class ValueFloatTestClass24 { public static bool testMethod() { int intRet = 0; bool b = true; float f1 = 11.0f; short s1 = 2; byte b1 = 3; int i1 = 4; long l1 = 5L; char c1 = (char)6; if ((f1 <= s1).GetType() != b.GetType()) { intRet = 1; } if ((s1 <= f1).GetType() != b.GetType()) { intRet = 1; } if ((f1 <= b1).GetType() != b.GetType()) { intRet = 1; } if ((b1 <= f1).GetType() != b.GetType()) { intRet = 1; } if ((f1 <= i1).GetType() != b.GetType()) { intRet = 1; } if ((i1 <= f1).GetType() != b.GetType()) { intRet = 1; } if ((f1 <= l1).GetType() != b.GetType()) { intRet = 1; } if ((l1 <= f1).GetType() != b.GetType()) { intRet = 1; } if ((f1 <= c1).GetType() != b.GetType()) { intRet = 1; } if ((c1 <= f1).GetType() != b.GetType()) { intRet = 1; } return (intRet == 0); } } public class ValueFloatTestClass25 { public static bool testMethod() { int intRet = 0; bool b = false; double d1 = 11.0d; short s1 = 2; byte b1 = 3; int i1 = 4; long l1 = 5L; char c1 = (char)6; if ((d1 <= s1).GetType() != b.GetType()) { intRet = 1; } if ((s1 <= d1).GetType() != b.GetType()) { intRet = 1; } if ((d1 <= b1).GetType() != b.GetType()) { intRet = 1; } if ((b1 <= d1).GetType() != b.GetType()) { intRet = 1; } if ((d1 <= i1).GetType() != b.GetType()) { intRet = 1; } if ((i1 <= d1).GetType() != b.GetType()) { intRet = 1; } if ((d1 <= l1).GetType() != b.GetType()) { intRet = 1; } if ((l1 <= d1).GetType() != b.GetType()) { intRet = 1; } if ((d1 <= c1).GetType() != b.GetType()) { intRet = 1; } if ((c1 <= d1).GetType() != b.GetType()) { intRet = 1; } return (intRet == 0); } } public class ValueFloatTestClass26 { public static bool testMethod() { int intRet = 0; double d1 = 11.0d; float f1 = 12.0f; if ((d1 + f1).GetType() != d1.GetType()) { intRet = 1; } if ((f1 + d1).GetType() != d1.GetType()) { intRet = 1; } if ((d1 + d1).GetType() != d1.GetType()) { intRet = 1; } if ((d1 - f1).GetType() != d1.GetType()) { intRet = 1; } if ((f1 - d1).GetType() != d1.GetType()) { intRet = 1; } if ((d1 - d1).GetType() != d1.GetType()) { intRet = 1; } if ((d1 * f1).GetType() != d1.GetType()) { intRet = 1; } if ((f1 * d1).GetType() != d1.GetType()) { intRet = 1; } if ((d1 * d1).GetType() != d1.GetType()) { intRet = 1; } if ((d1 / f1).GetType() != d1.GetType()) { intRet = 1; } if ((f1 / d1).GetType() != d1.GetType()) { intRet = 1; } if ((d1 / d1).GetType() != d1.GetType()) { intRet = 1; } if ((d1 % f1).GetType() != d1.GetType()) { intRet = 1; } if ((f1 % d1).GetType() != d1.GetType()) { intRet = 1; } if ((d1 % d1).GetType() != d1.GetType()) { intRet = 1; } return (intRet == 0); } } public class ValueFloatTestClass27 { public static bool testMethod() { int intRet = 0; double d1 = 11.0d; float f1 = 12.0f; bool b = false; if ((d1 == f1).GetType() != b.GetType()) { intRet = 1; } if ((f1 == d1).GetType() != b.GetType()) { intRet = 1; } if ((d1 == d1).GetType() != b.GetType()) { intRet = 1; } if ((d1 != f1).GetType() != b.GetType()) { intRet = 1; } if ((f1 != d1).GetType() != b.GetType()) { intRet = 1; } if ((d1 != d1).GetType() != b.GetType()) { intRet = 1; } if ((d1 > f1).GetType() != b.GetType()) { intRet = 1; } if ((f1 > d1).GetType() != b.GetType()) { intRet = 1; } if ((d1 > d1).GetType() != b.GetType()) { intRet = 1; } if ((d1 < f1).GetType() != b.GetType()) { intRet = 1; } if ((f1 < d1).GetType() != b.GetType()) { intRet = 1; } if ((d1 < d1).GetType() != b.GetType()) { intRet = 1; } if ((d1 >= f1).GetType() != b.GetType()) { intRet = 1; } if ((f1 >= d1).GetType() != b.GetType()) { intRet = 1; } if ((d1 >= d1).GetType() != b.GetType()) { intRet = 1; } if ((d1 <= f1).GetType() != b.GetType()) { intRet = 1; } if ((f1 <= d1).GetType() != b.GetType()) { intRet = 1; } if ((d1 <= d1).GetType() != b.GetType()) { intRet = 1; } return (intRet == 0); } } public class ValueFloatTestClass28 { public static bool testMethod() { int intRet = 0; float f1 = 11.0f; float f2 = 12.0f; if ((f1 + f2).GetType() != f1.GetType()) { intRet = 1; } if ((f1 - f2).GetType() != f1.GetType()) { intRet = 1; } if ((f1 * f2).GetType() != f1.GetType()) { intRet = 1; } if ((f1 / f2).GetType() != f1.GetType()) { intRet = 1; } if ((f1 % f2).GetType() != f1.GetType()) { intRet = 1; } return (intRet == 0); } } public class ValueFloatTestClass29 { public static bool testMethod() { int intRet = 0; double f1 = 11.0d; float f2 = 12.0f; bool b = false; if ((f1 == f2).GetType() != b.GetType()) { intRet = 1; } if ((f1 != f2).GetType() != b.GetType()) { intRet = 1; } if ((f1 > f2).GetType() != b.GetType()) { intRet = 1; } if ((f1 < f2).GetType() != b.GetType()) { intRet = 1; } if ((f1 >= f2).GetType() != b.GetType()) { intRet = 1; } if ((f1 <= f2).GetType() != b.GetType()) { intRet = 1; } return (intRet == 0); } } public class ValueFloatTestClass30 { public static bool testMethod() { float f1 = float.Epsilon; double d1 = double.Epsilon; if ((float)(f1 / 2.0f) != 0.0f) { return false; } if ((float)(f1 * 0.5f) != 0.0f) { return false; } if ((double)(d1 / 2.0d) != (double)0.0d) { return false; } if ((double)(d1 * 0.5d) != (double)0.0d) { return false; } return true; } } } } ================================================ FILE: Zelig/Zelig/Test/RunTime/NETMF/mscorlib/types/ValueIntegralTests.cs ================================================ //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // Copyright (c) Microsoft Corporation. All rights reserved. //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// using System; namespace Microsoft.Zelig.Test { public class ValueIntegralTests : TestBase, ITestInterface { [SetUp] public InitializeResult Initialize() { Log.Comment("Adding set up for the tests"); return InitializeResult.ReadyToGo; } [TearDown] public void CleanUp() { Log.Comment("Cleaning up after the tests"); } public override TestResult Run( string[] args ) { TestResult result = TestResult.Pass; string testName = "ValueIntegralXX_"; int testNumber = 0; result |= Assert.CheckFailed( ValueIntegral01_Test( ), testName, ++testNumber ); result |= Assert.CheckFailed( ValueIntegral05_Test( ), testName, ++testNumber ); result |= Assert.CheckFailed( ValueIntegral09_Test( ), testName, ++testNumber ); result |= Assert.CheckFailed( ValueIntegral13_Test( ), testName, ++testNumber ); result |= Assert.CheckFailed( ValueIntegral14_Test( ), testName, ++testNumber ); result |= Assert.CheckFailed( ValueIntegral15_Test( ), testName, ++testNumber ); //////result |= Assert.CheckFailed( ValueIntegral16_Test( ), testName, ++testNumber ); //////result |= Assert.CheckFailed( ValueIntegral17_Test( ), testName, ++testNumber ); result |= Assert.CheckFailed( ValueIntegral18_Test( ), testName, ++testNumber ); result |= Assert.CheckFailed( ValueIntegral19_Test( ), testName, ++testNumber ); result |= Assert.CheckFailed( ValueIntegral20_Test( ), testName, ++testNumber ); result |= Assert.CheckFailed( ValueIntegral21_Test( ), testName, ++testNumber ); result |= Assert.CheckFailed( ValueIntegral22_Test( ), testName, ++testNumber ); result |= Assert.CheckFailed( ValueIntegral23_Test( ), testName, ++testNumber ); result |= Assert.CheckFailed( ValueIntegral24_Test( ), testName, ++testNumber ); result |= Assert.CheckFailed( ValueIntegral25_Test( ), testName, ++testNumber ); result |= Assert.CheckFailed( ValueIntegral26_Test( ), testName, ++testNumber ); result |= Assert.CheckFailed( ValueIntegral27_Test( ), testName, ++testNumber ); result |= Assert.CheckFailed( ValueIntegral28_Test( ), testName, ++testNumber ); result |= Assert.CheckFailed( ValueIntegral38_Test( ), testName, ++testNumber ); result |= Assert.CheckFailed( ValueIntegral39_Test( ), testName, ++testNumber ); result |= Assert.CheckFailed( ValueIntegral42_Test( ), testName, ++testNumber ); result |= Assert.CheckFailed( ValueIntegral45_Test( ), testName, ++testNumber ); result |= Assert.CheckFailed( ValueIntegral49_Test( ), testName, ++testNumber ); result |= Assert.CheckFailed( ValueIntegral50_Test( ), testName, ++testNumber ); result |= Assert.CheckFailed( ValueIntegral51_Test( ), testName, ++testNumber ); //////result |= Assert.CheckFailed( ValueIntegral52_Test( ), testName, ++testNumber ); //////result |= Assert.CheckFailed( ValueIntegral53_Test( ), testName, ++testNumber ); result |= Assert.CheckFailed( ValueIntegral54_Test( ), testName, ++testNumber ); result |= Assert.CheckFailed( ValueIntegral55_Test( ), testName, ++testNumber ); result |= Assert.CheckFailed( ValueIntegral56_Test( ), testName, ++testNumber ); result |= Assert.CheckFailed( ValueIntegral57_Test( ), testName, ++testNumber ); result |= Assert.CheckFailed( ValueIntegral58_Test( ), testName, ++testNumber ); result |= Assert.CheckFailed( ValueIntegral59_Test( ), testName, ++testNumber ); result |= Assert.CheckFailed( ValueIntegral60_Test( ), testName, ++testNumber ); result |= Assert.CheckFailed( ValueIntegral61_Test( ), testName, ++testNumber ); result |= Assert.CheckFailed( ValueIntegral62_Test( ), testName, ++testNumber ); result |= Assert.CheckFailed( ValueIntegral63_Test( ), testName, ++testNumber ); result |= Assert.CheckFailed( ValueIntegral64_Test( ), testName, ++testNumber ); result |= Assert.CheckFailed( ValueIntegral70_Test( ), testName, ++testNumber ); return result; } //ValueIntegral Test methods //The following tests were ported from folder current\test\cases\client\CLR\Conformance\4_values\Values\Integral //01,05,09,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,38,39, //42,45,49,50,51,52,53,54,55,56,57,58,59,60,61,62,63,64,70 //These test all passed in the Baseline document //Test Case Calls [TestMethod] public TestResult ValueIntegral01_Test() { Log.Comment(" Section 4.1"); Log.Comment(" For the +, - and ~ unary operators, of the operand is of type long, the"); Log.Comment(" operation is performed using 64-bit precision, and the type of the result"); Log.Comment(" is long. Otherwise, the operand is converted to int, and operation is"); Log.Comment(" performed using 32-bit precision, and the type of the result is int."); if (ValueIntegralTestClass01.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult ValueIntegral05_Test() { Log.Comment(" Section 4.1"); Log.Comment(" For the +, - and ~ unary operators, of the operand is of type long, the"); Log.Comment(" operation is performed using 64-bit precision, and the type of the result"); Log.Comment(" is long. Otherwise, the operand is converted to int, and operation is"); Log.Comment(" performed using 32-bit precision, and the type of the result is int."); if (ValueIntegralTestClass05.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult ValueIntegral09_Test() { Log.Comment(" Section 4.1"); Log.Comment(" For the +, - and ~ unary operators, of the operand is of type long, the"); Log.Comment(" operation is performed using 64-bit precision, and the type of the result"); Log.Comment(" is long. Otherwise, the operand is converted to int, and operation is"); Log.Comment(" performed using 32-bit precision, and the type of the result is int."); if (ValueIntegralTestClass09.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult ValueIntegral13_Test() { Log.Comment(" For the binary operators other than shift, if at least one"); Log.Comment(" operand is of type long, then both operands are converted to long, the operation"); Log.Comment(" is performed using 64-bit precision, and the type of the result is long or bool. "); Log.Comment(" Otherwise, both operands are converted to int, the operation is performed using "); Log.Comment(" 32-bit precision, and the type of the result is int or bool."); if (ValueIntegralTestClass13.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult ValueIntegral14_Test() { Log.Comment(" For the binary operators other than shift, if at least one"); Log.Comment(" operand is of type long, then both operands are converted to long, the operation"); Log.Comment(" is performed using 64-bit precision, and the type of the result is long or bool. "); Log.Comment(" Otherwise, both operands are converted to int, the operation is performed using "); Log.Comment(" 32-bit precision, and the type of the result is int or bool."); if (ValueIntegralTestClass14.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult ValueIntegral15_Test() { Log.Comment(" For the binary operators other than shift, if at least one"); Log.Comment(" operand is of type long, then both operands are converted to long, the operation"); Log.Comment(" is performed using 64-bit precision, and the type of the result is long or bool. "); Log.Comment(" Otherwise, both operands are converted to int, the operation is performed using "); Log.Comment(" 32-bit precision, and the type of the result is int or bool."); if (ValueIntegralTestClass15.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } //////[TestMethod] //////public TestResult ValueIntegral16_Test( ) //////{ ////// Log.Comment( " For the binary operators other than shift, if at least one" ); ////// Log.Comment( " operand is of type long, then both operands are converted to long, the operation" ); ////// Log.Comment( " is performed using 64-bit precision, and the type of the result is long or bool. " ); ////// Log.Comment( " Otherwise, both operands are converted to int, the operation is performed using " ); ////// Log.Comment( " 32-bit precision, and the type of the result is int or bool." ); ////// if(ValueIntegralTestClass16.testMethod( )) ////// { ////// return TestResult.Pass; ////// } ////// return TestResult.Fail; //////} //////[TestMethod] //////public TestResult ValueIntegral17_Test( ) //////{ ////// Log.Comment( " For the binary operators other than shift, if at least one" ); ////// Log.Comment( " operand is of type long, then both operands are converted to long, the operation" ); ////// Log.Comment( " is performed using 64-bit precision, and the type of the result is long or bool. " ); ////// Log.Comment( " Otherwise, both operands are converted to int, the operation is performed using " ); ////// Log.Comment( " 32-bit precision, and the type of the result is int or bool." ); ////// if(ValueIntegralTestClass17.testMethod( )) ////// { ////// return TestResult.Pass; ////// } ////// return TestResult.Fail; //////} [TestMethod] public TestResult ValueIntegral18_Test() { Log.Comment(" For the binary operators other than shift, if at least one"); Log.Comment(" operand is of type long, then both operands are converted to long, the operation"); Log.Comment(" is performed using 64-bit precision, and the type of the result is long or bool. "); Log.Comment(" Otherwise, both operands are converted to int, the operation is performed using "); Log.Comment(" 32-bit precision, and the type of the result is int or bool."); if (ValueIntegralTestClass18.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult ValueIntegral19_Test() { Log.Comment(" For the binary operators other than shift, if at least one"); Log.Comment(" operand is of type long, then both operands are converted to long, the operation"); Log.Comment(" is performed using 64-bit precision, and the type of the result is long or bool. "); Log.Comment(" Otherwise, both operands are converted to int, the operation is performed using "); Log.Comment(" 32-bit precision, and the type of the result is int or bool."); if (ValueIntegralTestClass19.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult ValueIntegral20_Test() { Log.Comment(" For the binary operators other than shift, if at least one"); Log.Comment(" operand is of type long, then both operands are converted to long, the operation"); Log.Comment(" is performed using 64-bit precision, and the type of the result is long or bool. "); Log.Comment(" Otherwise, both operands are converted to int, the operation is performed using "); Log.Comment(" 32-bit precision, and the type of the result is int or bool."); if (ValueIntegralTestClass20.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult ValueIntegral21_Test() { Log.Comment(" For the binary operators other than shift, if at least one"); Log.Comment(" operand is of type long, then both operands are converted to long, the operation"); Log.Comment(" is performed using 64-bit precision, and the type of the result is long or bool. "); Log.Comment(" Otherwise, both operands are converted to int, the operation is performed using "); Log.Comment(" 32-bit precision, and the type of the result is int or bool."); if (ValueIntegralTestClass21.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult ValueIntegral22_Test() { Log.Comment(" For the binary operators other than shift, if at least one"); Log.Comment(" operand is of type long, then both operands are converted to long, the operation"); Log.Comment(" is performed using 64-bit precision, and the type of the result is long or bool. "); Log.Comment(" Otherwise, both operands are converted to int, the operation is performed using "); Log.Comment(" 32-bit precision, and the type of the result is int or bool."); if (ValueIntegralTestClass22.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult ValueIntegral23_Test() { Log.Comment(" For the binary operators other than shift, if at least one"); Log.Comment(" operand is of type long, then both operands are converted to long, the operation"); Log.Comment(" is performed using 64-bit precision, and the type of the result is long or bool. "); Log.Comment(" Otherwise, both operands are converted to int, the operation is performed using "); Log.Comment(" 32-bit precision, and the type of the result is int or bool."); if (ValueIntegralTestClass23.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult ValueIntegral24_Test() { Log.Comment(" For the binary operators other than shift, if at least one"); Log.Comment(" operand is of type long, then both operands are converted to long, the operation"); Log.Comment(" is performed using 64-bit precision, and the type of the result is long or bool. "); Log.Comment(" Otherwise, both operands are converted to int, the operation is performed using "); Log.Comment(" 32-bit precision, and the type of the result is int or bool."); if (ValueIntegralTestClass24.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult ValueIntegral25_Test() { Log.Comment(" For the binary operators other than shift, if at least one"); Log.Comment(" operand is of type long, then both operands are converted to long, the operation"); Log.Comment(" is performed using 64-bit precision, and the type of the result is long or bool. "); Log.Comment(" Otherwise, both operands are converted to int, the operation is performed using "); Log.Comment(" 32-bit precision, and the type of the result is int or bool."); if (ValueIntegralTestClass25.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult ValueIntegral26_Test() { Log.Comment(" For the binary operators other than shift, if at least one"); Log.Comment(" operand is of type long, then both operands are converted to long, the operation"); Log.Comment(" is performed using 64-bit precision, and the type of the result is long or bool. "); Log.Comment(" Otherwise, both operands are converted to int, the operation is performed using "); Log.Comment(" 32-bit precision, and the type of the result is int or bool."); if (ValueIntegralTestClass26.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult ValueIntegral27_Test() { Log.Comment(" Section 4.1"); Log.Comment(" For the shift operators, if the left-hand operand is of type long,"); Log.Comment(" the operation is performed using 64-bit precision, and the type of the result"); Log.Comment(" is long. Otherwise, the left hand-operand is converted to int, the operation is "); Log.Comment(" performed using 32-bit precision, and the type of the result is int."); if (ValueIntegralTestClass27.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult ValueIntegral28_Test() { Log.Comment(" Section 4.1"); Log.Comment(" For the shift operators, if the left-hand operand is of type long,"); Log.Comment(" the operation is performed using 64-bit precision, and the type of the result"); Log.Comment(" is long. Otherwise, the left hand-operand is converted to int, the operation is "); Log.Comment(" performed using 32-bit precision, and the type of the result is int."); if (ValueIntegralTestClass28.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult ValueIntegral38_Test() { Log.Comment(" Section 4.1"); Log.Comment(" Constants of the char type must be written as character-literals."); Log.Comment(" Character constants can only be written as integer-literals"); Log.Comment(" in combination with a cast. For example, (char)10 is the same as"); Log.Comment(" '\x000A'."); if (ValueIntegralTestClass38.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult ValueIntegral39_Test() { Log.Comment(" Section 4.1"); Log.Comment(" For the unary + and ~ operators, the operand is converted"); Log.Comment(" to type T, where T is the first of int, uint, long, and"); Log.Comment(" ulong that can fully represent all possible values of the"); Log.Comment(" operand. The operation is then performed using the precision "); Log.Comment(" of type T, and the type of the result is T."); if (ValueIntegralTestClass39.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult ValueIntegral42_Test() { Log.Comment(" Section 4.1"); Log.Comment(" For the unary + and ~ operators, the operand is converted"); Log.Comment(" to type T, where T is the first of int, uint, long, and"); Log.Comment(" ulong that can fully represent all possible values of the"); Log.Comment(" operand. The operation is then performed using the precision "); Log.Comment(" of type T, and the type of the result is T."); if (ValueIntegralTestClass42.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult ValueIntegral45_Test() { Log.Comment(" Section 4.1"); Log.Comment(" For the unary - operator, the operand is converted"); Log.Comment(" to type T, where T is the first of int and long that "); Log.Comment(" can fully represent all possible values of the "); Log.Comment(" operand. The operation is then performed using the"); Log.Comment(" precision of type T, and the type of the result is T."); Log.Comment(" The unary - operator cannot be applied to operands of"); Log.Comment(" type ulong."); if (ValueIntegralTestClass45.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult ValueIntegral49_Test() { Log.Comment(" Section 4.1"); Log.Comment(" For the binary operators except shift, the operands"); Log.Comment(" are converted to type T, where T is the first of int, uint, long, and ulong"); Log.Comment(" that can fully represent all possible values of each operand. The operation"); Log.Comment(" is then performed using the precision of type T, and the type of the result"); Log.Comment(" is T (or bool for relational operators)."); if (ValueIntegralTestClass49.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult ValueIntegral50_Test() { Log.Comment(" Section 4.1"); Log.Comment(" For the binary operators except shift, the operands"); Log.Comment(" are converted to type T, where T is the first of int, uint, long, and ulong"); Log.Comment(" that can fully represent all possible values of each operand. The operation"); Log.Comment(" is then performed using the precision of type T, and the type of the result"); Log.Comment(" is T (or bool for relational operators)."); if (ValueIntegralTestClass50.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult ValueIntegral51_Test() { Log.Comment(" Section 4.1"); Log.Comment(" For the binary operators except shift, the operands"); Log.Comment(" are converted to type T, where T is the first of int, uint, long, and ulong"); Log.Comment(" that can fully represent all possible values of each operand. The operation"); Log.Comment(" is then performed using the precision of type T, and the type of the result"); Log.Comment(" is T (or bool for relational operators)."); if (ValueIntegralTestClass51.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } //////[TestMethod] //////public TestResult ValueIntegral52_Test( ) //////{ ////// Log.Comment( " Section 4.1" ); ////// Log.Comment( " For the binary operators except shift, the operands" ); ////// Log.Comment( " are converted to type T, where T is the first of int, uint, long, and ulong" ); ////// Log.Comment( " that can fully represent all possible values of each operand. The operation" ); ////// Log.Comment( " is then performed using the precision of type T, and the type of the result" ); ////// Log.Comment( " is T (or bool for relational operators)." ); ////// if(ValueIntegralTestClass52.testMethod( )) ////// { ////// return TestResult.Pass; ////// } ////// return TestResult.Fail; //////} //////[TestMethod] //////public TestResult ValueIntegral53_Test( ) //////{ ////// Log.Comment( " Section 4.1" ); ////// Log.Comment( " For the binary operators except shift, the operands" ); ////// Log.Comment( " are converted to type T, where T is the first of int, uint, long, and ulong" ); ////// Log.Comment( " that can fully represent all possible values of each operand. The operation" ); ////// Log.Comment( " is then performed using the precision of type T, and the type of the result" ); ////// Log.Comment( " is T (or bool for relational operators)." ); ////// if(ValueIntegralTestClass53.testMethod( )) ////// { ////// return TestResult.Pass; ////// } ////// return TestResult.Fail; //////} [TestMethod] public TestResult ValueIntegral54_Test() { Log.Comment(" Section 4.1"); Log.Comment(" For the binary operators except shift, the operands"); Log.Comment(" are converted to type T, where T is the first of int, uint, long, and ulong"); Log.Comment(" that can fully represent all possible values of each operand. The operation"); Log.Comment(" is then performed using the precision of type T, and the type of the result"); Log.Comment(" is T (or bool for relational operators)."); if (ValueIntegralTestClass54.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult ValueIntegral55_Test() { Log.Comment(" Section 4.1"); Log.Comment(" For the binary operators except shift, the operands"); Log.Comment(" are converted to type T, where T is the first of int, uint, long, and ulong"); Log.Comment(" that can fully represent all possible values of each operand. The operation"); Log.Comment(" is then performed using the precision of type T, and the type of the result"); Log.Comment(" is T (or bool for relational operators)."); if (ValueIntegralTestClass55.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult ValueIntegral56_Test() { Log.Comment(" Section 4.1"); Log.Comment(" For the binary operators except shift, the operands"); Log.Comment(" are converted to type T, where T is the first of int, uint, long, and ulong"); Log.Comment(" that can fully represent all possible values of each operand. The operation"); Log.Comment(" is then performed using the precision of type T, and the type of the result"); Log.Comment(" is T (or bool for relational operators)."); if (ValueIntegralTestClass56.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult ValueIntegral57_Test() { Log.Comment(" Section 4.1"); Log.Comment(" For the binary operators except shift, the operands"); Log.Comment(" are converted to type T, where T is the first of int, uint, long, and ulong"); Log.Comment(" that can fully represent all possible values of each operand. The operation"); Log.Comment(" is then performed using the precision of type T, and the type of the result"); Log.Comment(" is T (or bool for relational operators)."); if (ValueIntegralTestClass57.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult ValueIntegral58_Test() { Log.Comment(" Section 4.1"); Log.Comment(" For the binary operators except shift, the operands"); Log.Comment(" are converted to type T, where T is the first of int, uint, long, and ulong"); Log.Comment(" that can fully represent all possible values of each operand. The operation"); Log.Comment(" is then performed using the precision of type T, and the type of the result"); Log.Comment(" is T (or bool for relational operators)."); if (ValueIntegralTestClass58.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult ValueIntegral59_Test() { Log.Comment(" Section 4.1"); Log.Comment(" For the binary operators except shift, the operands"); Log.Comment(" are converted to type T, where T is the first of int, uint, long, and ulong"); Log.Comment(" that can fully represent all possible values of each operand. The operation"); Log.Comment(" is then performed using the precision of type T, and the type of the result"); Log.Comment(" is T (or bool for relational operators)."); if (ValueIntegralTestClass59.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult ValueIntegral60_Test() { Log.Comment(" Section 4.1"); Log.Comment(" For the binary operators except shift, the operands"); Log.Comment(" are converted to type T, where T is the first of int, uint, long, and ulong"); Log.Comment(" that can fully represent all possible values of each operand. The operation"); Log.Comment(" is then performed using the precision of type T, and the type of the result"); Log.Comment(" is T (or bool for relational operators)."); if (ValueIntegralTestClass60.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult ValueIntegral61_Test() { Log.Comment(" Section 4.1"); Log.Comment(" For the binary operators except shift, the operands"); Log.Comment(" are converted to type T, where T is the first of int, uint, long, and ulong"); Log.Comment(" that can fully represent all possible values of each operand. The operation"); Log.Comment(" is then performed using the precision of type T, and the type of the result"); Log.Comment(" is T (or bool for relational operators)."); if (ValueIntegralTestClass61.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult ValueIntegral62_Test() { Log.Comment(" Section 4.1"); Log.Comment(" For the binary operators except shift, the operands"); Log.Comment(" are converted to type T, where T is the first of int, uint, long, and ulong"); Log.Comment(" that can fully represent all possible values of each operand. The operation"); Log.Comment(" is then performed using the precision of type T, and the type of the result"); Log.Comment(" is T (or bool for relational operators)."); if (ValueIntegralTestClass62.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult ValueIntegral63_Test() { Log.Comment(" Section 4.1"); Log.Comment(" For the binary shift operators, the left operand"); Log.Comment(" is converted to type T, where T is the first of int,"); Log.Comment(" uint, long, and ulong that can fully represent all possible"); Log.Comment(" values of the operand. The operation is then performed"); Log.Comment(" using the precision of type T, and the type of the result"); Log.Comment(" T."); if (ValueIntegralTestClass63.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult ValueIntegral64_Test() { Log.Comment(" Section 4.1"); Log.Comment(" For the binary shift operators, the left operand"); Log.Comment(" is converted to type T, where T is the first of int,"); Log.Comment(" uint, long, and ulong that can fully represent all possible"); Log.Comment(" values of the operand. The operation is then performed"); Log.Comment(" using the precision of type T, and the type of the result"); Log.Comment(" T."); if (ValueIntegralTestClass64.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult ValueIntegral70_Test() { Log.Comment(" Section 4.1"); Log.Comment(" Constants of the char type must be written as character-literals."); Log.Comment(" Character constants can only be written as integer-literals"); Log.Comment(" in compination with a cast. For example, (char)10 is the same "); Log.Comment(" as '\x000a'."); if (ValueIntegralTestClass70.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } //Compiled Test Cases public class ValueIntegralTestClass01 { public static bool testMethod() { short s1 = 2; short s2 = (short)-s1; byte b1 = 3; int b2 = -b1; int i1 = 4; int i2 = -i1; long l1 = 5L; long l2 = -l1; char c1 = (char)6; int c2 = -c1; if ((s2 == (short)-2) && (b2 == -3) && (i2 == -4) && (l2 == -5L) && (c2 == -6)) { return true; } else { return false; } } } public class ValueIntegralTestClass05 { public static bool testMethod() { short s1 = 2; short s2 = (short)+s1; byte b1 = 3; int b2 = +b1; int i1 = 4; int i2 = +i1; long l1 = 5; long l2 = +l1; char c1 = (char)6; int c2 = +c1; if ((s2 == (short)2) && (b2 == 3) && (i2 == 4) && (l2 == 5L) && (c2 == 6)) { return true; } else { return false; } } } public class ValueIntegralTestClass09 { public static bool testMethod() { short s1 = 2; short s2 = (short)~s1; byte b1 = 3; int b2 = ~b1; int i1 = 4; int i2 = ~i1; long l1 = 5L; long l2 = ~l1; char c1 = (char)6; int c2 = ~c1; if ((s2 == (short)-3) && (b2 == -4) && (i2 == -5) && (l2 == -6L) && (c2 == -7)) { return true; } else { return false; } } } public class ValueIntegralTestClass13 { public static bool testMethod() { int intRet = 0; short s1 = 2; byte b1 = 3; int i1 = 4; long l1 = 5L; char c1 = (char)6; //short if ((s1 + s1).GetType() != i1.GetType()) { intRet = 1; } if ((s1 + b1).GetType() != i1.GetType()) { intRet = 1; } if ((s1 + i1).GetType() != i1.GetType()) { intRet = 1; } if ((s1 + l1).GetType() != l1.GetType()) { intRet = 1; } if ((s1 + c1).GetType() != i1.GetType()) { intRet = 1; } //byte if ((b1 + b1).GetType() != i1.GetType()) { intRet = 1; } if ((b1 + i1).GetType() != i1.GetType()) { intRet = 1; } if ((b1 + l1).GetType() != l1.GetType()) { intRet = 1; } if ((b1 + c1).GetType() != i1.GetType()) { intRet = 1; } //int if ((i1 + i1).GetType() != i1.GetType()) { intRet = 1; } if ((i1 + l1).GetType() != l1.GetType()) { intRet = 1; } if ((i1 + c1).GetType() != i1.GetType()) { intRet = 1; } //long if ((l1 + l1).GetType() != l1.GetType()) { intRet = 1; } if ((l1 + c1).GetType() != l1.GetType()) { intRet = 1; } //char if ((c1 + c1).GetType() != i1.GetType()) { intRet = 1; } return (intRet == 0); } } public class ValueIntegralTestClass14 { public static bool testMethod() { int intRet = 0; short s1 = 2; byte b1 = 3; int i1 = 4; long l1 = 5L; char c1 = (char)6; //short if ((s1 - s1).GetType() != i1.GetType()) { intRet = 1; } if ((s1 - b1).GetType() != i1.GetType()) { intRet = 1; } if ((s1 - i1).GetType() != i1.GetType()) { intRet = 1; } if ((s1 - l1).GetType() != l1.GetType()) { intRet = 1; } if ((s1 - c1).GetType() != i1.GetType()) { intRet = 1; } //byte if ((b1 - b1).GetType() != i1.GetType()) { intRet = 1; } if ((b1 - i1).GetType() != i1.GetType()) { intRet = 1; } if ((b1 - l1).GetType() != l1.GetType()) { intRet = 1; } if ((b1 - c1).GetType() != i1.GetType()) { intRet = 1; } //int if ((i1 - i1).GetType() != i1.GetType()) { intRet = 1; } if ((i1 - l1).GetType() != l1.GetType()) { intRet = 1; } if ((i1 - c1).GetType() != i1.GetType()) { intRet = 1; } //long if ((l1 - l1).GetType() != l1.GetType()) { intRet = 1; } if ((l1 - c1).GetType() != l1.GetType()) { intRet = 1; } //char if ((c1 - c1).GetType() != i1.GetType()) { intRet = 1; } return (intRet == 0); } } public class ValueIntegralTestClass15 { public static bool testMethod() { int intRet = 0; short s1 = 2; byte b1 = 3; int i1 = 4; long l1 = 5L; char c1 = (char)6; //short if ((s1 * s1).GetType() != i1.GetType()) { intRet = 1; } if ((s1 * b1).GetType() != i1.GetType()) { intRet = 1; } if ((s1 * i1).GetType() != i1.GetType()) { intRet = 1; } if ((s1 * l1).GetType() != l1.GetType()) { intRet = 1; } if ((s1 * c1).GetType() != i1.GetType()) { intRet = 1; } //byte if ((b1 * b1).GetType() != i1.GetType()) { intRet = 1; } if ((b1 * i1).GetType() != i1.GetType()) { intRet = 1; } if ((b1 * l1).GetType() != l1.GetType()) { intRet = 1; } if ((b1 * c1).GetType() != i1.GetType()) { intRet = 1; } //int if ((i1 * i1).GetType() != i1.GetType()) { intRet = 1; } if ((i1 * l1).GetType() != l1.GetType()) { intRet = 1; } if ((i1 * c1).GetType() != i1.GetType()) { intRet = 1; } //long if ((l1 * l1).GetType() != l1.GetType()) { intRet = 1; } if ((l1 * c1).GetType() != l1.GetType()) { intRet = 1; } //char if ((c1 * c1).GetType() != i1.GetType()) { intRet = 1; } return (intRet == 0); } } //////public class ValueIntegralTestClass16 //////{ ////// public static bool testMethod( ) ////// { ////// int intRet = 0; ////// short s1 = 2; ////// byte b1 = 3; ////// int i1 = 4; ////// long l1 = 5L; ////// char c1 = (char)6; ////// //short ////// if(( s1 / s1 ).GetType( ) != i1.GetType( )) ////// { ////// intRet = 1; ////// } ////// if(( s1 / b1 ).GetType( ) != i1.GetType( )) ////// { ////// intRet = 1; ////// } ////// if(( s1 / i1 ).GetType( ) != i1.GetType( )) ////// { ////// intRet = 1; ////// } ////// if(( s1 / l1 ).GetType( ) != l1.GetType( )) ////// { ////// intRet = 1; ////// } ////// if(( s1 / c1 ).GetType( ) != i1.GetType( )) ////// { ////// intRet = 1; ////// } ////// //byte ////// if(( b1 / b1 ).GetType( ) != i1.GetType( )) ////// { ////// intRet = 1; ////// } ////// if(( b1 / i1 ).GetType( ) != i1.GetType( )) ////// { ////// intRet = 1; ////// } ////// if(( b1 / l1 ).GetType( ) != l1.GetType( )) ////// { ////// intRet = 1; ////// } ////// if(( b1 / c1 ).GetType( ) != i1.GetType( )) ////// { ////// intRet = 1; ////// } ////// //int ////// if(( i1 / i1 ).GetType( ) != i1.GetType( )) ////// { ////// intRet = 1; ////// } ////// if(( i1 / l1 ).GetType( ) != l1.GetType( )) ////// { ////// intRet = 1; ////// } ////// if(( i1 / c1 ).GetType( ) != i1.GetType( )) ////// { ////// intRet = 1; ////// } ////// //long ////// if(( l1 / l1 ).GetType( ) != l1.GetType( )) ////// { ////// intRet = 1; ////// } ////// if(( l1 / c1 ).GetType( ) != l1.GetType( )) ////// { ////// intRet = 1; ////// } ////// //char ////// if(( c1 / c1 ).GetType( ) != i1.GetType( )) ////// { ////// intRet = 1; ////// } ////// return ( intRet == 0 ); ////// } //////} //////public class ValueIntegralTestClass17 //////{ ////// public static bool testMethod( ) ////// { ////// int intRet = 0; ////// short s1 = 2; ////// byte b1 = 3; ////// int i1 = 4; ////// long l1 = 5L; ////// char c1 = (char)6; ////// //short ////// if(( s1 % s1 ).GetType( ) != i1.GetType( )) ////// { ////// intRet = 1; ////// } ////// if(( s1 % b1 ).GetType( ) != i1.GetType( )) ////// { ////// intRet = 1; ////// } ////// if(( s1 % i1 ).GetType( ) != i1.GetType( )) ////// { ////// intRet = 1; ////// } ////// if(( s1 % l1 ).GetType( ) != l1.GetType( )) ////// { ////// intRet = 1; ////// } ////// if(( s1 % c1 ).GetType( ) != i1.GetType( )) ////// { ////// intRet = 1; ////// } ////// //byte ////// if(( b1 % b1 ).GetType( ) != i1.GetType( )) ////// { ////// intRet = 1; ////// } ////// if(( b1 % i1 ).GetType( ) != i1.GetType( )) ////// { ////// intRet = 1; ////// } ////// if(( b1 % l1 ).GetType( ) != l1.GetType( )) ////// { ////// intRet = 1; ////// } ////// if(( b1 % c1 ).GetType( ) != i1.GetType( )) ////// { ////// intRet = 1; ////// } ////// //int ////// if(( i1 % i1 ).GetType( ) != i1.GetType( )) ////// { ////// intRet = 1; ////// } ////// if(( i1 % l1 ).GetType( ) != l1.GetType( )) ////// { ////// intRet = 1; ////// } ////// if(( i1 % c1 ).GetType( ) != i1.GetType( )) ////// { ////// intRet = 1; ////// } ////// //long ////// if(( l1 % l1 ).GetType( ) != l1.GetType( )) ////// { ////// intRet = 1; ////// } ////// if(( l1 % c1 ).GetType( ) != l1.GetType( )) ////// { ////// intRet = 1; ////// } ////// //char ////// if(( c1 % c1 ).GetType( ) != i1.GetType( )) ////// { ////// intRet = 1; ////// } ////// return ( intRet == 0 ); ////// } //////} public class ValueIntegralTestClass18 { public static bool testMethod() { int intRet = 0; short s1 = 2; byte b1 = 3; int i1 = 4; long l1 = 5L; char c1 = (char)6; //short if ((s1 & s1).GetType() != i1.GetType()) { intRet = 1; } if ((s1 & b1).GetType() != i1.GetType()) { intRet = 1; } if ((s1 & i1).GetType() != i1.GetType()) { intRet = 1; } if ((s1 & l1).GetType() != l1.GetType()) { intRet = 1; } if ((s1 & c1).GetType() != i1.GetType()) { intRet = 1; } //byte if ((b1 & b1).GetType() != i1.GetType()) { intRet = 1; } if ((b1 & i1).GetType() != i1.GetType()) { intRet = 1; } if ((b1 & l1).GetType() != l1.GetType()) { intRet = 1; } if ((b1 & c1).GetType() != i1.GetType()) { intRet = 1; } //int if ((i1 & i1).GetType() != i1.GetType()) { intRet = 1; } if ((i1 & l1).GetType() != l1.GetType()) { intRet = 1; } if ((i1 & c1).GetType() != i1.GetType()) { intRet = 1; } //long if ((l1 & l1).GetType() != l1.GetType()) { intRet = 1; } if ((l1 & c1).GetType() != l1.GetType()) { intRet = 1; } //char if ((c1 & c1).GetType() != i1.GetType()) { intRet = 1; } return (intRet == 0); } } public class ValueIntegralTestClass19 { public static bool testMethod() { int intRet = 0; short s1 = 2; byte b1 = 3; int i1 = 4; long l1 = 5L; char c1 = (char)6; //short if ((s1 ^ s1).GetType() != i1.GetType()) { intRet = 1; } if ((s1 ^ b1).GetType() != i1.GetType()) { intRet = 1; } if ((s1 ^ i1).GetType() != i1.GetType()) { intRet = 1; } if ((s1 ^ l1).GetType() != l1.GetType()) { intRet = 1; } if ((s1 ^ c1).GetType() != i1.GetType()) { intRet = 1; } //byte if ((b1 ^ b1).GetType() != i1.GetType()) { intRet = 1; } if ((b1 ^ i1).GetType() != i1.GetType()) { intRet = 1; } if ((b1 ^ l1).GetType() != l1.GetType()) { intRet = 1; } if ((b1 ^ c1).GetType() != i1.GetType()) { intRet = 1; } //int if ((i1 ^ i1).GetType() != i1.GetType()) { intRet = 1; } if ((i1 ^ l1).GetType() != l1.GetType()) { intRet = 1; } if ((i1 ^ c1).GetType() != i1.GetType()) { intRet = 1; } //long if ((l1 ^ l1).GetType() != l1.GetType()) { intRet = 1; } if ((l1 ^ c1).GetType() != l1.GetType()) { intRet = 1; } //char if ((c1 ^ c1).GetType() != i1.GetType()) { intRet = 1; } return (intRet == 0); } } public class ValueIntegralTestClass20 { public static bool testMethod() { int intRet = 0; short s1 = 2; byte b1 = 3; int i1 = 4; long l1 = 5L; char c1 = (char)6; //short if ((s1 | s1).GetType() != i1.GetType()) { intRet = 1; } if ((s1 | b1).GetType() != i1.GetType()) { intRet = 1; } if ((s1 | i1).GetType() != i1.GetType()) { intRet = 1; } if ((s1 | l1).GetType() != l1.GetType()) { intRet = 1; } if ((s1 | c1).GetType() != i1.GetType()) { intRet = 1; } //byte if ((b1 | b1).GetType() != i1.GetType()) { intRet = 1; } if ((b1 | i1).GetType() != i1.GetType()) { intRet = 1; } if ((b1 | l1).GetType() != l1.GetType()) { intRet = 1; } if ((b1 | c1).GetType() != i1.GetType()) { intRet = 1; } //int if ((i1 | i1).GetType() != i1.GetType()) { intRet = 1; } if ((i1 | l1).GetType() != l1.GetType()) { intRet = 1; } if ((i1 | c1).GetType() != i1.GetType()) { intRet = 1; } //long if ((l1 | l1).GetType() != l1.GetType()) { intRet = 1; } if ((l1 | c1).GetType() != l1.GetType()) { intRet = 1; } //char if ((c1 | c1).GetType() != i1.GetType()) { intRet = 1; } return (intRet == 0); } } public class ValueIntegralTestClass21 { public static bool testMethod() { int intRet = 0; bool TestBool = false; short s1 = 2; byte b1 = 3; int i1 = 4; long l1 = 5L; char c1 = (char)6; //short if ((s1 == s1).GetType() != TestBool.GetType()) { intRet = 1; } if ((s1 == b1).GetType() != TestBool.GetType()) { intRet = 1; } if ((s1 == i1).GetType() != TestBool.GetType()) { intRet = 1; } if ((s1 == l1).GetType() != TestBool.GetType()) { intRet = 1; } if ((s1 == c1).GetType() != TestBool.GetType()) { intRet = 1; } //byte if ((b1 == b1).GetType() != TestBool.GetType()) { intRet = 1; } if ((b1 == i1).GetType() != TestBool.GetType()) { intRet = 1; } if ((b1 == l1).GetType() != TestBool.GetType()) { intRet = 1; } if ((b1 == c1).GetType() != TestBool.GetType()) { intRet = 1; } //int if ((i1 == i1).GetType() != TestBool.GetType()) { intRet = 1; } if ((i1 == l1).GetType() != TestBool.GetType()) { intRet = 1; } if ((i1 == c1).GetType() != TestBool.GetType()) { intRet = 1; } //long if ((l1 == l1).GetType() != TestBool.GetType()) { intRet = 1; } if ((l1 == c1).GetType() != TestBool.GetType()) { intRet = 1; } //char if ((c1 == c1).GetType() != TestBool.GetType()) { intRet = 1; } return (intRet == 0); } } public class ValueIntegralTestClass22 { public static bool testMethod() { int intRet = 0; bool TestBool = false; short s1 = 2; byte b1 = 3; int i1 = 4; long l1 = 5L; char c1 = (char)6; //short if ((s1 != s1).GetType() != TestBool.GetType()) { intRet = 1; } if ((s1 != b1).GetType() != TestBool.GetType()) { intRet = 1; } if ((s1 != i1).GetType() != TestBool.GetType()) { intRet = 1; } if ((s1 != l1).GetType() != TestBool.GetType()) { intRet = 1; } if ((s1 != c1).GetType() != TestBool.GetType()) { intRet = 1; } //byte if ((b1 != b1).GetType() != TestBool.GetType()) { intRet = 1; } if ((b1 != i1).GetType() != TestBool.GetType()) { intRet = 1; } if ((b1 != l1).GetType() != TestBool.GetType()) { intRet = 1; } if ((b1 != c1).GetType() != TestBool.GetType()) { intRet = 1; } //int if ((i1 != i1).GetType() != TestBool.GetType()) { intRet = 1; } if ((i1 != l1).GetType() != TestBool.GetType()) { intRet = 1; } if ((i1 != c1).GetType() != TestBool.GetType()) { intRet = 1; } //long if ((l1 != l1).GetType() != TestBool.GetType()) { intRet = 1; } if ((l1 != c1).GetType() != TestBool.GetType()) { intRet = 1; } //char if ((c1 != c1).GetType() != TestBool.GetType()) { intRet = 1; } return (intRet == 0); } } public class ValueIntegralTestClass23 { public static bool testMethod() { int intRet = 0; bool TestBool = false; short s1 = 2; byte b1 = 3; int i1 = 4; long l1 = 5L; char c1 = (char)6; //short if ((s1 > s1).GetType() != TestBool.GetType()) { intRet = 1; } if ((s1 > b1).GetType() != TestBool.GetType()) { intRet = 1; } if ((s1 > i1).GetType() != TestBool.GetType()) { intRet = 1; } if ((s1 > l1).GetType() != TestBool.GetType()) { intRet = 1; } if ((s1 > c1).GetType() != TestBool.GetType()) { intRet = 1; } //byte if ((b1 > b1).GetType() != TestBool.GetType()) { intRet = 1; } if ((b1 > i1).GetType() != TestBool.GetType()) { intRet = 1; } if ((b1 > l1).GetType() != TestBool.GetType()) { intRet = 1; } if ((b1 > c1).GetType() != TestBool.GetType()) { intRet = 1; } //int if ((i1 > i1).GetType() != TestBool.GetType()) { intRet = 1; } if ((i1 > l1).GetType() != TestBool.GetType()) { intRet = 1; } if ((i1 > c1).GetType() != TestBool.GetType()) { intRet = 1; } //long if ((l1 > l1).GetType() != TestBool.GetType()) { intRet = 1; } if ((l1 > c1).GetType() != TestBool.GetType()) { intRet = 1; } //char if ((c1 > c1).GetType() != TestBool.GetType()) { intRet = 1; } return (intRet == 0); } } public class ValueIntegralTestClass24 { public static bool testMethod() { int intRet = 0; bool TestBool = false; short s1 = 2; byte b1 = 3; int i1 = 4; long l1 = 5L; char c1 = (char)6; //short if ((s1 < s1).GetType() != TestBool.GetType()) { intRet = 1; } if ((s1 < b1).GetType() != TestBool.GetType()) { intRet = 1; } if ((s1 < i1).GetType() != TestBool.GetType()) { intRet = 1; } if ((s1 < l1).GetType() != TestBool.GetType()) { intRet = 1; } if ((s1 < c1).GetType() != TestBool.GetType()) { intRet = 1; } //byte if ((b1 < b1).GetType() != TestBool.GetType()) { intRet = 1; } if ((b1 < i1).GetType() != TestBool.GetType()) { intRet = 1; } if ((b1 < l1).GetType() != TestBool.GetType()) { intRet = 1; } if ((b1 < c1).GetType() != TestBool.GetType()) { intRet = 1; } //int if ((i1 < i1).GetType() != TestBool.GetType()) { intRet = 1; } if ((i1 < l1).GetType() != TestBool.GetType()) { intRet = 1; } if ((i1 < c1).GetType() != TestBool.GetType()) { intRet = 1; } //long if ((l1 < l1).GetType() != TestBool.GetType()) { intRet = 1; } if ((l1 < c1).GetType() != TestBool.GetType()) { intRet = 1; } //char if ((c1 < c1).GetType() != TestBool.GetType()) { intRet = 1; } return (intRet == 0); } } public class ValueIntegralTestClass25 { public static bool testMethod() { int intRet = 0; bool TestBool = false; short s1 = 2; byte b1 = 3; int i1 = 4; long l1 = 5L; char c1 = (char)6; //short if ((s1 >= s1).GetType() != TestBool.GetType()) { intRet = 1; } if ((s1 >= b1).GetType() != TestBool.GetType()) { intRet = 1; } if ((s1 >= i1).GetType() != TestBool.GetType()) { intRet = 1; } if ((s1 >= l1).GetType() != TestBool.GetType()) { intRet = 1; } if ((s1 >= c1).GetType() != TestBool.GetType()) { intRet = 1; } //byte if ((b1 >= b1).GetType() != TestBool.GetType()) { intRet = 1; } if ((b1 >= i1).GetType() != TestBool.GetType()) { intRet = 1; } if ((b1 >= l1).GetType() != TestBool.GetType()) { intRet = 1; } if ((b1 >= c1).GetType() != TestBool.GetType()) { intRet = 1; } //int if ((i1 >= i1).GetType() != TestBool.GetType()) { intRet = 1; } if ((i1 >= l1).GetType() != TestBool.GetType()) { intRet = 1; } if ((i1 >= c1).GetType() != TestBool.GetType()) { intRet = 1; } //long if ((l1 >= l1).GetType() != TestBool.GetType()) { intRet = 1; } if ((l1 >= c1).GetType() != TestBool.GetType()) { intRet = 1; } //char if ((c1 >= c1).GetType() != TestBool.GetType()) { intRet = 1; } return (intRet == 0); } } public class ValueIntegralTestClass26 { public static bool testMethod() { int intRet = 0; bool TestBool = false; short s1 = 2; byte b1 = 3; int i1 = 4; long l1 = 5L; char c1 = (char)6; //short if ((s1 <= s1).GetType() != TestBool.GetType()) { intRet = 1; } if ((s1 <= b1).GetType() != TestBool.GetType()) { intRet = 1; } if ((s1 <= i1).GetType() != TestBool.GetType()) { intRet = 1; } if ((s1 <= l1).GetType() != TestBool.GetType()) { intRet = 1; } if ((s1 <= c1).GetType() != TestBool.GetType()) { intRet = 1; } //byte if ((b1 <= b1).GetType() != TestBool.GetType()) { intRet = 1; } if ((b1 <= i1).GetType() != TestBool.GetType()) { intRet = 1; } if ((b1 <= l1).GetType() != TestBool.GetType()) { intRet = 1; } if ((b1 <= c1).GetType() != TestBool.GetType()) { intRet = 1; } //int if ((i1 <= i1).GetType() != TestBool.GetType()) { intRet = 1; } if ((i1 <= l1).GetType() != TestBool.GetType()) { intRet = 1; } if ((i1 <= c1).GetType() != TestBool.GetType()) { intRet = 1; } //long if ((l1 <= l1).GetType() != TestBool.GetType()) { intRet = 1; } if ((l1 <= c1).GetType() != TestBool.GetType()) { intRet = 1; } //char if ((c1 <= c1).GetType() != TestBool.GetType()) { intRet = 1; } return (intRet == 0); } } public class ValueIntegralTestClass27 { public static bool testMethod() { int intRet = 0; short s1 = 2; byte b1 = 3; int i1 = 4; long l1 = 5L; char c1 = (char)6; if ((s1 << 1).GetType() != i1.GetType()) { intRet = 1; } if ((b1 << 1).GetType() != i1.GetType()) { intRet = 1; } if ((i1 << 1).GetType() != i1.GetType()) { intRet = 1; } if ((l1 << 1).GetType() != l1.GetType()) { intRet = 1; } if ((c1 << 1).GetType() != i1.GetType()) { intRet = 1; } return (intRet == 0); } } public class ValueIntegralTestClass28 { public static bool testMethod() { int intRet = 0; short s1 = 2; byte b1 = 3; int i1 = 4; long l1 = 5L; char c1 = (char)6; if ((s1 >> 1).GetType() != i1.GetType()) { intRet = 1; } if ((b1 >> 1).GetType() != i1.GetType()) { intRet = 1; } if ((i1 >> 1).GetType() != i1.GetType()) { intRet = 1; } if ((l1 >> 1).GetType() != l1.GetType()) { intRet = 1; } if ((c1 >> 1).GetType() != i1.GetType()) { intRet = 1; } return (intRet == 0); } } public class ValueIntegralTestClass38 { public static bool testMethod() { char c = '\x000A'; if (c == (char)10) { return true; } else { return false; } } } public class ValueIntegralTestClass39 { public static bool testMethod() { ushort s1 = 2; ushort s2 = (ushort)+s1; sbyte b1 = 3; int b2 = +b1; uint i1 = 4; uint i2 = +i1; ulong l1 = 5ul; ulong l2 = +l1; if ((s2 == (ushort)2) && (b2 == 3) && (i2 == 4) && (l2 == 5ul)) { return true; } else { return false; } } } public class ValueIntegralTestClass42 { public static bool testMethod() { checked { ushort s1 = 2; int s2 = ~s1; sbyte b1 = 3; int b2 = ~b1; uint i1 = 4; uint i2 = ~i1; ulong l1 = 5ul; ulong l2 = ~l1; if ((s2 == -3) && (b2 == -4) && (i2 == 4294967291u) && (l2 == 18446744073709551610ul)) { return true; } else { return false; } } } } public class ValueIntegralTestClass45 { public static bool testMethod() { ushort s1 = 2; int s2 = -s1; sbyte b1 = 3; int b2 = -b1; uint i1 = 4; long i2 = -i1; if ((s2 == -2) && (b2 == -3) && (i2 == -4)) { return true; } else { return false; } } } public class ValueIntegralTestClass49 { public static bool testMethod() { int intRet = 0; short s1 = 2; byte b1 = 3; int i1 = 4; long l1 = 5L; char c1 = (char)6; ushort s2 = 7; sbyte b2 = 8; uint i2 = 9; ulong l2 = 10; //ushort if ((s2 + s1).GetType() != i1.GetType()) { intRet = 1; } if ((s2 + b1).GetType() != i1.GetType()) { intRet = 1; } if ((s2 + i1).GetType() != i1.GetType()) { intRet = 1; } if ((s2 + l1).GetType() != l1.GetType()) { intRet = 1; } if ((s2 + c1).GetType() != i1.GetType()) { intRet = 1; } if ((s2 + s2).GetType() != i1.GetType()) { intRet = 1; } if ((s2 + b2).GetType() != i1.GetType()) { intRet = 1; } if ((s2 + i2).GetType() != i2.GetType()) { intRet = 1; } if ((s2 + l2).GetType() != l2.GetType()) { intRet = 1; } //sbyte if ((b2 + s1).GetType() != i1.GetType()) { intRet = 1; } if ((b2 + b1).GetType() != i1.GetType()) { intRet = 1; } if ((b2 + i1).GetType() != i1.GetType()) { intRet = 1; } if ((b2 + l1).GetType() != l1.GetType()) { intRet = 1; } if ((b2 + c1).GetType() != i1.GetType()) { intRet = 1; } if ((b2 + s2).GetType() != i1.GetType()) { intRet = 1; } if ((b2 + b2).GetType() != i1.GetType()) { intRet = 1; } if ((b2 + i2).GetType() != l1.GetType()) { intRet = 1; } //if ((b2 + l2).GetType() != l2.GetType()) { // intRet = 1; //} //uint if ((i2 + s1).GetType() != l1.GetType()) { intRet = 1; } if ((i2 + b1).GetType() != i2.GetType()) { intRet = 1; } if ((i2 + i1).GetType() != l1.GetType()) { intRet = 1; } if ((i2 + l1).GetType() != l1.GetType()) { intRet = 1; } if ((i2 + c1).GetType() != i2.GetType()) { intRet = 1; } if ((i2 + s2).GetType() != i2.GetType()) { intRet = 1; } if ((i2 + b2).GetType() != l1.GetType()) { intRet = 1; } if ((i2 + i2).GetType() != i2.GetType()) { intRet = 1; } if ((i2 + l2).GetType() != l2.GetType()) { intRet = 1; } //ulong //if ((l2 + s1).GetType() != l2.GetType()) { // intRet = 1; //} if ((l2 + b1).GetType() != l2.GetType()) { intRet = 1; } //if ((l2 + i1).GetType() != l2.GetType()) { // intRet = 1; //} //if ((l2 + l1).GetType() != l2.GetType()) { // intRet = 1; //} if ((l2 + c1).GetType() != l2.GetType()) { intRet = 1; } if ((l2 + s2).GetType() != l2.GetType()) { intRet = 1; } //if ((l2 + b2).GetType() != l2.GetType()) { // intRet = 1; //} if ((l2 + i2).GetType() != l2.GetType()) { intRet = 1; } if ((l2 + l2).GetType() != l2.GetType()) { intRet = 1; } return (intRet == 0); } } public class ValueIntegralTestClass50 { public static bool testMethod() { int intRet = 0; short s1 = 2; byte b1 = 3; int i1 = 4; long l1 = 5L; char c1 = (char)6; ushort s2 = 7; sbyte b2 = 8; uint i2 = 9; ulong l2 = 10; //ushort if ((s2 - s1).GetType() != i1.GetType()) { intRet = 1; } if ((s2 - b1).GetType() != i1.GetType()) { intRet = 1; } if ((s2 - i1).GetType() != i1.GetType()) { intRet = 1; } if ((s2 - l1).GetType() != l1.GetType()) { intRet = 1; } if ((s2 - c1).GetType() != i1.GetType()) { intRet = 1; } if ((s2 - s2).GetType() != i1.GetType()) { intRet = 1; } if ((s2 - b2).GetType() != i1.GetType()) { intRet = 1; } if ((s2 - i2).GetType() != i2.GetType()) { intRet = 1; } if ((s2 - l2).GetType() != l2.GetType()) { intRet = 1; } //sbyte if ((b2 - s1).GetType() != i1.GetType()) { intRet = 1; } if ((b2 - b1).GetType() != i1.GetType()) { intRet = 1; } if ((b2 - i1).GetType() != i1.GetType()) { intRet = 1; } if ((b2 - l1).GetType() != l1.GetType()) { intRet = 1; } if ((b2 - c1).GetType() != i1.GetType()) { intRet = 1; } if ((b2 - s2).GetType() != i1.GetType()) { intRet = 1; } if ((b2 - b2).GetType() != i1.GetType()) { intRet = 1; } if ((b2 - i2).GetType() != l1.GetType()) { intRet = 1; } //if ((b2 - l2).GetType() != l2.GetType()) { // intRet = 1; //} //uint if ((i2 - s1).GetType() != l1.GetType()) { intRet = 1; } if ((i2 - b1).GetType() != i2.GetType()) { intRet = 1; } if ((i2 - i1).GetType() != l1.GetType()) { intRet = 1; } if ((i2 - l1).GetType() != l1.GetType()) { intRet = 1; } if ((i2 - c1).GetType() != i2.GetType()) { intRet = 1; } if ((i2 - s2).GetType() != i2.GetType()) { intRet = 1; } if ((i2 - b2).GetType() != l1.GetType()) { intRet = 1; } if ((i2 - i2).GetType() != i2.GetType()) { intRet = 1; } if ((i2 - l2).GetType() != l2.GetType()) { intRet = 1; } //ulong //if ((l2 - s1).GetType() != l2.GetType()) { // intRet = 1; //} if ((l2 - b1).GetType() != l2.GetType()) { intRet = 1; } //if ((l2 - i1).GetType() != l2.GetType()) { // intRet = 1; //} //if ((l2 - l1).GetType() != l2.GetType()) { // intRet = 1; //} if ((l2 - c1).GetType() != l2.GetType()) { intRet = 1; } if ((l2 - s2).GetType() != l2.GetType()) { intRet = 1; } //if ((l2 - b2).GetType() != l2.GetType()) { // intRet = 1; //} if ((l2 - i2).GetType() != l2.GetType()) { intRet = 1; } if ((l2 - l2).GetType() != l2.GetType()) { intRet = 1; } return (intRet == 0); } } public class ValueIntegralTestClass51 { public static bool testMethod() { int intRet = 0; short s1 = 2; byte b1 = 3; int i1 = 4; long l1 = 5L; char c1 = (char)6; ushort s2 = 7; sbyte b2 = 8; uint i2 = 9; ulong l2 = 10; //ushort if ((s2 * s1).GetType() != i1.GetType()) { intRet = 1; } if ((s2 * b1).GetType() != i1.GetType()) { intRet = 1; } if ((s2 * i1).GetType() != i1.GetType()) { intRet = 1; } if ((s2 * l1).GetType() != l1.GetType()) { intRet = 1; } if ((s2 * c1).GetType() != i1.GetType()) { intRet = 1; } if ((s2 * s2).GetType() != i1.GetType()) { intRet = 1; } if ((s2 * b2).GetType() != i1.GetType()) { intRet = 1; } if ((s2 * i2).GetType() != i2.GetType()) { intRet = 1; } if ((s2 * l2).GetType() != l2.GetType()) { intRet = 1; } //sbyte if ((b2 * s1).GetType() != i1.GetType()) { intRet = 1; } if ((b2 * b1).GetType() != i1.GetType()) { intRet = 1; } if ((b2 * i1).GetType() != i1.GetType()) { intRet = 1; } if ((b2 * l1).GetType() != l1.GetType()) { intRet = 1; } if ((b2 * c1).GetType() != i1.GetType()) { intRet = 1; } if ((b2 * s2).GetType() != i1.GetType()) { intRet = 1; } if ((b2 * b2).GetType() != i1.GetType()) { intRet = 1; } if ((b2 * i2).GetType() != l1.GetType()) { intRet = 1; } //if ((b2 * l2).GetType() != l2.GetType()) { // intRet = 1; //} //uint if ((i2 * s1).GetType() != l1.GetType()) { intRet = 1; } if ((i2 * b1).GetType() != i2.GetType()) { intRet = 1; } if ((i2 * i1).GetType() != l1.GetType()) { intRet = 1; } if ((i2 * l1).GetType() != l1.GetType()) { intRet = 1; } if ((i2 * c1).GetType() != i2.GetType()) { intRet = 1; } if ((i2 * s2).GetType() != i2.GetType()) { intRet = 1; } if ((i2 * b2).GetType() != l1.GetType()) { intRet = 1; } if ((i2 * i2).GetType() != i2.GetType()) { intRet = 1; } if ((i2 * l2).GetType() != l2.GetType()) { intRet = 1; } //ulong //if ((l2 * s1).GetType() != l2.GetType()) { // intRet = 1; //} if ((l2 * b1).GetType() != l2.GetType()) { intRet = 1; } //if ((l2 * i1).GetType() != l2.GetType()) { // intRet = 1; //} //if ((l2 * l1).GetType() != l2.GetType()) { // intRet = 1; //} if ((l2 * c1).GetType() != l2.GetType()) { intRet = 1; } if ((l2 * s2).GetType() != l2.GetType()) { intRet = 1; } //if ((l2 * b2).GetType() != l2.GetType()) { // intRet = 1; //} if ((l2 * i2).GetType() != l2.GetType()) { intRet = 1; } if ((l2 * l2).GetType() != l2.GetType()) { intRet = 1; } return (intRet == 0); } } //////public class ValueIntegralTestClass52 //////{ ////// public static bool testMethod( ) ////// { ////// int intRet = 0; ////// short s1 = 2; ////// byte b1 = 3; ////// int i1 = 4; ////// long l1 = 5L; ////// char c1 = (char)6; ////// ushort s2 = 7; ////// sbyte b2 = 8; ////// uint i2 = 9; ////// ulong l2 = 10; ////// //ushort ////// if(( s2 / s1 ).GetType( ) != i1.GetType( )) ////// { ////// intRet = 1; ////// } ////// if(( s2 / b1 ).GetType( ) != i1.GetType( )) ////// { ////// intRet = 1; ////// } ////// if(( s2 / i1 ).GetType( ) != i1.GetType( )) ////// { ////// intRet = 1; ////// } ////// if(( s2 / l1 ).GetType( ) != l1.GetType( )) ////// { ////// intRet = 1; ////// } ////// if(( s2 / c1 ).GetType( ) != i1.GetType( )) ////// { ////// intRet = 1; ////// } ////// if(( s2 / s2 ).GetType( ) != i1.GetType( )) ////// { ////// intRet = 1; ////// } ////// if(( s2 / b2 ).GetType( ) != i1.GetType( )) ////// { ////// intRet = 1; ////// } ////// if(( s2 / i2 ).GetType( ) != i2.GetType( )) ////// { ////// intRet = 1; ////// } ////// if(( s2 / l2 ).GetType( ) != l2.GetType( )) ////// { ////// intRet = 1; ////// } ////// //sbyte ////// if(( b2 / s1 ).GetType( ) != i1.GetType( )) ////// { ////// intRet = 1; ////// } ////// if(( b2 / b1 ).GetType( ) != i1.GetType( )) ////// { ////// intRet = 1; ////// } ////// if(( b2 / i1 ).GetType( ) != i1.GetType( )) ////// { ////// intRet = 1; ////// } ////// if(( b2 / l1 ).GetType( ) != l1.GetType( )) ////// { ////// intRet = 1; ////// } ////// if(( b2 / c1 ).GetType( ) != i1.GetType( )) ////// { ////// intRet = 1; ////// } ////// if(( b2 / s2 ).GetType( ) != i1.GetType( )) ////// { ////// intRet = 1; ////// } ////// if(( b2 / b2 ).GetType( ) != i1.GetType( )) ////// { ////// intRet = 1; ////// } ////// if(( b2 / i2 ).GetType( ) != l1.GetType( )) ////// { ////// intRet = 1; ////// } ////// //if ((b2 / l2).GetType() != l2.GetType()) { ////// // intRet = 1; ////// //} ////// //uint ////// if(( i2 / s1 ).GetType( ) != l1.GetType( )) ////// { ////// intRet = 1; ////// } ////// if(( i2 / b1 ).GetType( ) != i2.GetType( )) ////// { ////// intRet = 1; ////// } ////// if(( i2 / i1 ).GetType( ) != l1.GetType( )) ////// { ////// intRet = 1; ////// } ////// if(( i2 / l1 ).GetType( ) != l1.GetType( )) ////// { ////// intRet = 1; ////// } ////// if(( i2 / c1 ).GetType( ) != i2.GetType( )) ////// { ////// intRet = 1; ////// } ////// if(( i2 / s2 ).GetType( ) != i2.GetType( )) ////// { ////// intRet = 1; ////// } ////// if(( i2 / b2 ).GetType( ) != l1.GetType( )) ////// { ////// intRet = 1; ////// } ////// if(( i2 / i2 ).GetType( ) != i2.GetType( )) ////// { ////// intRet = 1; ////// } ////// if(( i2 / l2 ).GetType( ) != l2.GetType( )) ////// { ////// intRet = 1; ////// } ////// //ulong ////// //if ((l2 / s1).GetType() != l2.GetType()) { ////// // intRet = 1; ////// //} ////// if(( l2 / b1 ).GetType( ) != l2.GetType( )) ////// { ////// intRet = 1; ////// } ////// //if ((l2 / i1).GetType() != l2.GetType()) { ////// // intRet = 1; ////// //} ////// //if ((l2 / l1).GetType() != l2.GetType()) { ////// // intRet = 1; ////// //} ////// if(( l2 / c1 ).GetType( ) != l2.GetType( )) ////// { ////// intRet = 1; ////// } ////// if(( l2 / s2 ).GetType( ) != l2.GetType( )) ////// { ////// intRet = 1; ////// } ////// //if ((l2 / b2).GetType() != l2.GetType()) { ////// // intRet = 1; ////// //} ////// if(( l2 / i2 ).GetType( ) != l2.GetType( )) ////// { ////// intRet = 1; ////// } ////// if(( l2 / l2 ).GetType( ) != l2.GetType( )) ////// { ////// intRet = 1; ////// } ////// return ( intRet == 0 ); ////// } //////} //////public class ValueIntegralTestClass53 //////{ ////// public static bool testMethod( ) ////// { ////// int intRet = 0; ////// short s1 = 2; ////// byte b1 = 3; ////// int i1 = 4; ////// long l1 = 5L; ////// char c1 = (char)6; ////// ushort s2 = 7; ////// sbyte b2 = 8; ////// uint i2 = 9; ////// ulong l2 = 10; ////// //ushort ////// if(( s2 % s1 ).GetType( ) != i1.GetType( )) ////// { ////// intRet = 1; ////// } ////// if(( s2 % b1 ).GetType( ) != i1.GetType( )) ////// { ////// intRet = 1; ////// } ////// if(( s2 % i1 ).GetType( ) != i1.GetType( )) ////// { ////// intRet = 1; ////// } ////// if(( s2 % l1 ).GetType( ) != l1.GetType( )) ////// { ////// intRet = 1; ////// } ////// if(( s2 % c1 ).GetType( ) != i1.GetType( )) ////// { ////// intRet = 1; ////// } ////// if(( s2 % s2 ).GetType( ) != i1.GetType( )) ////// { ////// intRet = 1; ////// } ////// if(( s2 % b2 ).GetType( ) != i1.GetType( )) ////// { ////// intRet = 1; ////// } ////// if(( s2 % i2 ).GetType( ) != i2.GetType( )) ////// { ////// intRet = 1; ////// } ////// if(( s2 % l2 ).GetType( ) != l2.GetType( )) ////// { ////// intRet = 1; ////// } ////// //sbyte ////// if(( b2 % s1 ).GetType( ) != i1.GetType( )) ////// { ////// intRet = 1; ////// } ////// if(( b2 % b1 ).GetType( ) != i1.GetType( )) ////// { ////// intRet = 1; ////// } ////// if(( b2 % i1 ).GetType( ) != i1.GetType( )) ////// { ////// intRet = 1; ////// } ////// if(( b2 % l1 ).GetType( ) != l1.GetType( )) ////// { ////// intRet = 1; ////// } ////// if(( b2 % c1 ).GetType( ) != i1.GetType( )) ////// { ////// intRet = 1; ////// } ////// if(( b2 % s2 ).GetType( ) != i1.GetType( )) ////// { ////// intRet = 1; ////// } ////// if(( b2 % b2 ).GetType( ) != i1.GetType( )) ////// { ////// intRet = 1; ////// } ////// if(( b2 % i2 ).GetType( ) != l1.GetType( )) ////// { ////// intRet = 1; ////// } ////// //if ((b2 % l2).GetType() != l2.GetType()) { ////// // intRet = 1; ////// //} ////// //uint ////// if(( i2 % s1 ).GetType( ) != l1.GetType( )) ////// { ////// intRet = 1; ////// } ////// if(( i2 % b1 ).GetType( ) != i2.GetType( )) ////// { ////// intRet = 1; ////// } ////// if(( i2 % i1 ).GetType( ) != l1.GetType( )) ////// { ////// intRet = 1; ////// } ////// if(( i2 % l1 ).GetType( ) != l1.GetType( )) ////// { ////// intRet = 1; ////// } ////// if(( i2 % c1 ).GetType( ) != i2.GetType( )) ////// { ////// intRet = 1; ////// } ////// if(( i2 % s2 ).GetType( ) != i2.GetType( )) ////// { ////// intRet = 1; ////// } ////// if(( i2 % b2 ).GetType( ) != l1.GetType( )) ////// { ////// intRet = 1; ////// } ////// if(( i2 % i2 ).GetType( ) != i2.GetType( )) ////// { ////// intRet = 1; ////// } ////// if(( i2 % l2 ).GetType( ) != l2.GetType( )) ////// { ////// intRet = 1; ////// } ////// //ulong ////// //if ((l2 % s1).GetType() != l2.GetType()) { ////// // intRet = 1; ////// //} ////// if(( l2 % b1 ).GetType( ) != l2.GetType( )) ////// { ////// intRet = 1; ////// } ////// //if ((l2 % i1).GetType() != l2.GetType()) { ////// // intRet = 1; ////// //} ////// //if ((l2 % l1).GetType() != l2.GetType()) { ////// // intRet = 1; ////// //} ////// if(( l2 % c1 ).GetType( ) != l2.GetType( )) ////// { ////// intRet = 1; ////// } ////// if(( l2 % s2 ).GetType( ) != l2.GetType( )) ////// { ////// intRet = 1; ////// } ////// //if ((l2 % b2).GetType() != l2.GetType()) { ////// // intRet = 1; ////// //} ////// if(( l2 % i2 ).GetType( ) != l2.GetType( )) ////// { ////// intRet = 1; ////// } ////// if(( l2 % l2 ).GetType( ) != l2.GetType( )) ////// { ////// intRet = 1; ////// } ////// return ( intRet == 0 ); ////// } //////} public class ValueIntegralTestClass54 { public static bool testMethod() { int intRet = 0; short s1 = 2; byte b1 = 3; int i1 = 4; long l1 = 5L; char c1 = (char)6; ushort s2 = 7; sbyte b2 = 8; uint i2 = 9; ulong l2 = 10; //ushort if ((s2 & s1).GetType() != i1.GetType()) { intRet = 1; } if ((s2 & b1).GetType() != i1.GetType()) { intRet = 1; } if ((s2 & i1).GetType() != i1.GetType()) { intRet = 1; } if ((s2 & l1).GetType() != l1.GetType()) { intRet = 1; } if ((s2 & c1).GetType() != i1.GetType()) { intRet = 1; } if ((s2 & s2).GetType() != i1.GetType()) { intRet = 1; } if ((s2 & b2).GetType() != i1.GetType()) { intRet = 1; } if ((s2 & i2).GetType() != i2.GetType()) { intRet = 1; } if ((s2 & l2).GetType() != l2.GetType()) { intRet = 1; } //sbyte if ((b2 & s1).GetType() != i1.GetType()) { intRet = 1; } if ((b2 & b1).GetType() != i1.GetType()) { intRet = 1; } if ((b2 & i1).GetType() != i1.GetType()) { intRet = 1; } if ((b2 & l1).GetType() != l1.GetType()) { intRet = 1; } if ((b2 & c1).GetType() != i1.GetType()) { intRet = 1; } if ((b2 & s2).GetType() != i1.GetType()) { intRet = 1; } if ((b2 & b2).GetType() != i1.GetType()) { intRet = 1; } if ((b2 & i2).GetType() != l1.GetType()) { intRet = 1; } //if ((b2 & l2).GetType() != l2.GetType()) { // intRet = 1; //} //uint if ((i2 & s1).GetType() != l1.GetType()) { intRet = 1; } if ((i2 & b1).GetType() != i2.GetType()) { intRet = 1; } if ((i2 & i1).GetType() != l1.GetType()) { intRet = 1; } if ((i2 & l1).GetType() != l1.GetType()) { intRet = 1; } if ((i2 & c1).GetType() != i2.GetType()) { intRet = 1; } if ((i2 & s2).GetType() != i2.GetType()) { intRet = 1; } if ((i2 & b2).GetType() != l1.GetType()) { intRet = 1; } if ((i2 & i2).GetType() != i2.GetType()) { intRet = 1; } if ((i2 & l2).GetType() != l2.GetType()) { intRet = 1; } //ulong //if ((l2 & s1).GetType() != l2.GetType()) { // intRet = 1; //} if ((l2 & b1).GetType() != l2.GetType()) { intRet = 1; } //if ((l2 & i1).GetType() != l2.GetType()) { // intRet = 1; //} //if ((l2 & l1).GetType() != l2.GetType()) { // intRet = 1; //} if ((l2 & c1).GetType() != l2.GetType()) { intRet = 1; } if ((l2 & s2).GetType() != l2.GetType()) { intRet = 1; } //if ((l2 & b2).GetType() != l2.GetType()) { // intRet = 1; //} if ((l2 & i2).GetType() != l2.GetType()) { intRet = 1; } if ((l2 & l2).GetType() != l2.GetType()) { intRet = 1; } return (intRet == 0); } } public class ValueIntegralTestClass55 { public static bool testMethod() { int intRet = 0; short s1 = 2; byte b1 = 3; int i1 = 4; long l1 = 5L; char c1 = (char)6; ushort s2 = 7; sbyte b2 = 8; uint i2 = 9; ulong l2 = 10; //ushort if ((s2 ^ s1).GetType() != i1.GetType()) { intRet = 1; } if ((s2 ^ b1).GetType() != i1.GetType()) { intRet = 1; } if ((s2 ^ i1).GetType() != i1.GetType()) { intRet = 1; } if ((s2 ^ l1).GetType() != l1.GetType()) { intRet = 1; } if ((s2 ^ c1).GetType() != i1.GetType()) { intRet = 1; } if ((s2 ^ s2).GetType() != i1.GetType()) { intRet = 1; } if ((s2 ^ b2).GetType() != i1.GetType()) { intRet = 1; } if ((s2 ^ i2).GetType() != i2.GetType()) { intRet = 1; } if ((s2 ^ l2).GetType() != l2.GetType()) { intRet = 1; } //sbyte if ((b2 ^ s1).GetType() != i1.GetType()) { intRet = 1; } if ((b2 ^ b1).GetType() != i1.GetType()) { intRet = 1; } if ((b2 ^ i1).GetType() != i1.GetType()) { intRet = 1; } if ((b2 ^ l1).GetType() != l1.GetType()) { intRet = 1; } if ((b2 ^ c1).GetType() != i1.GetType()) { intRet = 1; } if ((b2 ^ s2).GetType() != i1.GetType()) { intRet = 1; } if ((b2 ^ b2).GetType() != i1.GetType()) { intRet = 1; } if ((b2 ^ i2).GetType() != l1.GetType()) { intRet = 1; } //if ((b2 ^ l2).GetType() != l2.GetType()) { // intRet = 1; //} //uint if ((i2 ^ s1).GetType() != l1.GetType()) { intRet = 1; } if ((i2 ^ b1).GetType() != i2.GetType()) { intRet = 1; } if ((i2 ^ i1).GetType() != l1.GetType()) { intRet = 1; } if ((i2 ^ l1).GetType() != l1.GetType()) { intRet = 1; } if ((i2 ^ c1).GetType() != i2.GetType()) { intRet = 1; } if ((i2 ^ s2).GetType() != i2.GetType()) { intRet = 1; } if ((i2 ^ b2).GetType() != l1.GetType()) { intRet = 1; } if ((i2 ^ i2).GetType() != i2.GetType()) { intRet = 1; } if ((i2 ^ l2).GetType() != l2.GetType()) { intRet = 1; } //ulong //if ((l2 ^ s1).GetType() != l2.GetType()) { // intRet = 1; //} if ((l2 ^ b1).GetType() != l2.GetType()) { intRet = 1; } //if ((l2 ^ i1).GetType() != l2.GetType()) { // intRet = 1; //} //if ((l2 ^ l1).GetType() != l2.GetType()) { // intRet = 1; //} if ((l2 ^ c1).GetType() != l2.GetType()) { intRet = 1; } if ((l2 ^ s2).GetType() != l2.GetType()) { intRet = 1; } //if ((l2 ^ b2).GetType() != l2.GetType()) { // intRet = 1; //} if ((l2 ^ i2).GetType() != l2.GetType()) { intRet = 1; } if ((l2 ^ l2).GetType() != l2.GetType()) { intRet = 1; } return (intRet == 0); } } public class ValueIntegralTestClass56 { public static bool testMethod() { int intRet = 0; short s1 = 2; byte b1 = 3; int i1 = 4; long l1 = 5L; char c1 = (char)6; ushort s2 = 7; sbyte b2 = 8; uint i2 = 9; ulong l2 = 10; //ushort if ((s2 | s1).GetType() != i1.GetType()) { intRet = 1; } if ((s2 | b1).GetType() != i1.GetType()) { intRet = 1; } if ((s2 | i1).GetType() != i1.GetType()) { intRet = 1; } if ((s2 | l1).GetType() != l1.GetType()) { intRet = 1; } if ((s2 | c1).GetType() != i1.GetType()) { intRet = 1; } if ((s2 | s2).GetType() != i1.GetType()) { intRet = 1; } if ((s2 | b2).GetType() != i1.GetType()) { intRet = 1; } if ((s2 | i2).GetType() != i2.GetType()) { intRet = 1; } if ((s2 | l2).GetType() != l2.GetType()) { intRet = 1; } //sbyte if ((b2 | s1).GetType() != i1.GetType()) { intRet = 1; } if ((b2 | b1).GetType() != i1.GetType()) { intRet = 1; } if ((b2 | i1).GetType() != i1.GetType()) { intRet = 1; } if ((b2 | l1).GetType() != l1.GetType()) { intRet = 1; } if ((b2 | c1).GetType() != i1.GetType()) { intRet = 1; } if ((b2 | s2).GetType() != i1.GetType()) { intRet = 1; } if ((b2 | b2).GetType() != i1.GetType()) { intRet = 1; } if ((b2 | i2).GetType() != l1.GetType()) { intRet = 1; } //if ((b2 | l2).GetType() != l2.GetType()) { // intRet = 1; //} //uint if ((i2 | s1).GetType() != l1.GetType()) { intRet = 1; } if ((i2 | b1).GetType() != i2.GetType()) { intRet = 1; } if ((i2 | i1).GetType() != l1.GetType()) { intRet = 1; } if ((i2 | l1).GetType() != l1.GetType()) { intRet = 1; } if ((i2 | c1).GetType() != i2.GetType()) { intRet = 1; } if ((i2 | s2).GetType() != i2.GetType()) { intRet = 1; } if ((i2 | b2).GetType() != l1.GetType()) { intRet = 1; } if ((i2 | i2).GetType() != i2.GetType()) { intRet = 1; } if ((i2 | l2).GetType() != l2.GetType()) { intRet = 1; } //ulong //if ((l2 | s1).GetType() != l2.GetType()) { // intRet = 1; //} if ((l2 | b1).GetType() != l2.GetType()) { intRet = 1; } //if ((l2 | i1).GetType() != l2.GetType()) { // intRet = 1; //} //if ((l2 | l1).GetType() != l2.GetType()) { // intRet = 1; //} if ((l2 | c1).GetType() != l2.GetType()) { intRet = 1; } if ((l2 | s2).GetType() != l2.GetType()) { intRet = 1; } //if ((l2 | b2).GetType() != l2.GetType()) { // intRet = 1; //} if ((l2 | i2).GetType() != l2.GetType()) { intRet = 1; } if ((l2 | l2).GetType() != l2.GetType()) { intRet = 1; } return (intRet == 0); } } public class ValueIntegralTestClass57 { public static bool testMethod() { int intRet = 0; short s1 = 2; byte b1 = 3; int i1 = 4; long l1 = 5L; char c1 = (char)6; ushort s2 = 7; sbyte b2 = 8; uint i2 = 9; ulong l2 = 10; bool b = true; //ushort if ((s2 == s1).GetType() != b.GetType()) { intRet = 1; } if ((s2 == b1).GetType() != b.GetType()) { intRet = 1; } if ((s2 == i1).GetType() != b.GetType()) { intRet = 1; } if ((s2 == l1).GetType() != b.GetType()) { intRet = 1; } if ((s2 == c1).GetType() != b.GetType()) { intRet = 1; } if ((s2 == s2).GetType() != b.GetType()) { intRet = 1; } if ((s2 == b2).GetType() != b.GetType()) { intRet = 1; } if ((s2 == i2).GetType() != b.GetType()) { intRet = 1; } if ((s2 == l2).GetType() != b.GetType()) { intRet = 1; } //sbyte if ((b2 == s1).GetType() != b.GetType()) { intRet = 1; } if ((b2 == b1).GetType() != b.GetType()) { intRet = 1; } if ((b2 == i1).GetType() != b.GetType()) { intRet = 1; } if ((b2 == l1).GetType() != b.GetType()) { intRet = 1; } if ((b2 == c1).GetType() != b.GetType()) { intRet = 1; } if ((b2 == s2).GetType() != b.GetType()) { intRet = 1; } if ((b2 == b2).GetType() != b.GetType()) { intRet = 1; } if ((b2 == i2).GetType() != b.GetType()) { intRet = 1; } //if ((b2 == l2).GetType() != b.GetType()) { // intRet = 1; //} //uint if ((i2 == s1).GetType() != b.GetType()) { intRet = 1; } if ((i2 == b1).GetType() != b.GetType()) { intRet = 1; } if ((i2 == i1).GetType() != b.GetType()) { intRet = 1; } if ((i2 == l1).GetType() != b.GetType()) { intRet = 1; } if ((i2 == c1).GetType() != b.GetType()) { intRet = 1; } if ((i2 == s2).GetType() != b.GetType()) { intRet = 1; } if ((i2 == b2).GetType() != b.GetType()) { intRet = 1; } if ((i2 == i2).GetType() != b.GetType()) { intRet = 1; } if ((i2 == l2).GetType() != b.GetType()) { intRet = 1; } //ulong //if ((l2 == s1).GetType() != b.GetType()) { // intRet = 1; //} if ((l2 == b1).GetType() != b.GetType()) { intRet = 1; } //if ((l2 == i1).GetType() != b.GetType()) { // intRet = 1; //} //if ((l2 == l1).GetType() != b.GetType()) { // intRet = 1; //} if ((l2 == c1).GetType() != b.GetType()) { intRet = 1; } if ((l2 == s2).GetType() != b.GetType()) { intRet = 1; } //if ((l2 == b2).GetType() != b.GetType()) { // intRet = 1; //} if ((l2 == i2).GetType() != b.GetType()) { intRet = 1; } if ((l2 == l2).GetType() != b.GetType()) { intRet = 1; } return (intRet == 0); } } public class ValueIntegralTestClass58 { public static bool testMethod() { int intRet = 0; short s1 = 2; byte b1 = 3; int i1 = 4; long l1 = 5L; char c1 = (char)6; ushort s2 = 7; sbyte b2 = 8; uint i2 = 9; ulong l2 = 10; bool b = true; //ushort if ((s2 != s1).GetType() != b.GetType()) { intRet = 1; } if ((s2 != b1).GetType() != b.GetType()) { intRet = 1; } if ((s2 != i1).GetType() != b.GetType()) { intRet = 1; } if ((s2 != l1).GetType() != b.GetType()) { intRet = 1; } if ((s2 != c1).GetType() != b.GetType()) { intRet = 1; } if ((s2 != s2).GetType() != b.GetType()) { intRet = 1; } if ((s2 != b2).GetType() != b.GetType()) { intRet = 1; } if ((s2 != i2).GetType() != b.GetType()) { intRet = 1; } if ((s2 != l2).GetType() != b.GetType()) { intRet = 1; } //sbyte if ((b2 != s1).GetType() != b.GetType()) { intRet = 1; } if ((b2 != b1).GetType() != b.GetType()) { intRet = 1; } if ((b2 != i1).GetType() != b.GetType()) { intRet = 1; } if ((b2 != l1).GetType() != b.GetType()) { intRet = 1; } if ((b2 != c1).GetType() != b.GetType()) { intRet = 1; } if ((b2 != s2).GetType() != b.GetType()) { intRet = 1; } if ((b2 != b2).GetType() != b.GetType()) { intRet = 1; } if ((b2 != i2).GetType() != b.GetType()) { intRet = 1; } //if ((b2 != l2).GetType() != b.GetType()) { // intRet = 1; //} //uint if ((i2 != s1).GetType() != b.GetType()) { intRet = 1; } if ((i2 != b1).GetType() != b.GetType()) { intRet = 1; } if ((i2 != i1).GetType() != b.GetType()) { intRet = 1; } if ((i2 != l1).GetType() != b.GetType()) { intRet = 1; } if ((i2 != c1).GetType() != b.GetType()) { intRet = 1; } if ((i2 != s2).GetType() != b.GetType()) { intRet = 1; } if ((i2 != b2).GetType() != b.GetType()) { intRet = 1; } if ((i2 != i2).GetType() != b.GetType()) { intRet = 1; } if ((i2 != l2).GetType() != b.GetType()) { intRet = 1; } //ulong //if ((l2 != s1).GetType() != b.GetType()) { // intRet = 1; //} if ((l2 != b1).GetType() != b.GetType()) { intRet = 1; } //if ((l2 != i1).GetType() != b.GetType()) { // intRet = 1; //} //if ((l2 != l1).GetType() != b.GetType()) { // intRet = 1; //} if ((l2 != c1).GetType() != b.GetType()) { intRet = 1; } if ((l2 != s2).GetType() != b.GetType()) { intRet = 1; } //if ((l2 != b2).GetType() != b.GetType()) { // intRet = 1; //} if ((l2 != i2).GetType() != b.GetType()) { intRet = 1; } if ((l2 != l2).GetType() != b.GetType()) { intRet = 1; } return (intRet == 0); } } public class ValueIntegralTestClass59 { public static bool testMethod() { int intRet = 0; short s1 = 2; byte b1 = 3; int i1 = 4; long l1 = 5L; char c1 = (char)6; ushort s2 = 7; sbyte b2 = 8; uint i2 = 9; ulong l2 = 10; bool b = true; //ushort if ((s2 > s1).GetType() != b.GetType()) { intRet = 1; } if ((s2 > b1).GetType() != b.GetType()) { intRet = 1; } if ((s2 > i1).GetType() != b.GetType()) { intRet = 1; } if ((s2 > l1).GetType() != b.GetType()) { intRet = 1; } if ((s2 > c1).GetType() != b.GetType()) { intRet = 1; } if ((s2 > s2).GetType() != b.GetType()) { intRet = 1; } if ((s2 > b2).GetType() != b.GetType()) { intRet = 1; } if ((s2 > i2).GetType() != b.GetType()) { intRet = 1; } if ((s2 > l2).GetType() != b.GetType()) { intRet = 1; } //sbyte if ((b2 > s1).GetType() != b.GetType()) { intRet = 1; } if ((b2 > b1).GetType() != b.GetType()) { intRet = 1; } if ((b2 > i1).GetType() != b.GetType()) { intRet = 1; } if ((b2 > l1).GetType() != b.GetType()) { intRet = 1; } if ((b2 > c1).GetType() != b.GetType()) { intRet = 1; } if ((b2 > s2).GetType() != b.GetType()) { intRet = 1; } if ((b2 > b2).GetType() != b.GetType()) { intRet = 1; } if ((b2 > i2).GetType() != b.GetType()) { intRet = 1; } //if ((b2 > l2).GetType() != b.GetType()) { // intRet = 1; //} //uint if ((i2 > s1).GetType() != b.GetType()) { intRet = 1; } if ((i2 > b1).GetType() != b.GetType()) { intRet = 1; } if ((i2 > i1).GetType() != b.GetType()) { intRet = 1; } if ((i2 > l1).GetType() != b.GetType()) { intRet = 1; } if ((i2 > c1).GetType() != b.GetType()) { intRet = 1; } if ((i2 > s2).GetType() != b.GetType()) { intRet = 1; } if ((i2 > b2).GetType() != b.GetType()) { intRet = 1; } if ((i2 > i2).GetType() != b.GetType()) { intRet = 1; } if ((i2 > l2).GetType() != b.GetType()) { intRet = 1; } //ulong //if ((l2 > s1).GetType() != b.GetType()) { // intRet = 1; //} if ((l2 > b1).GetType() != b.GetType()) { intRet = 1; } //if ((l2 > i1).GetType() != b.GetType()) { // intRet = 1; //} //if ((l2 > l1).GetType() != b.GetType()) { // intRet = 1; //} if ((l2 > c1).GetType() != b.GetType()) { intRet = 1; } if ((l2 > s2).GetType() != b.GetType()) { intRet = 1; } //if ((l2 > b2).GetType() != b.GetType()) { // intRet = 1; //} if ((l2 > i2).GetType() != b.GetType()) { intRet = 1; } if ((l2 > l2).GetType() != b.GetType()) { intRet = 1; } return (intRet == 0); } } public class ValueIntegralTestClass60 { public static bool testMethod() { int intRet = 0; short s1 = 2; byte b1 = 3; int i1 = 4; long l1 = 5L; char c1 = (char)6; ushort s2 = 7; sbyte b2 = 8; uint i2 = 9; ulong l2 = 10; bool b = true; //ushort if ((s2 < s1).GetType() != b.GetType()) { intRet = 1; } if ((s2 < b1).GetType() != b.GetType()) { intRet = 1; } if ((s2 < i1).GetType() != b.GetType()) { intRet = 1; } if ((s2 < l1).GetType() != b.GetType()) { intRet = 1; } if ((s2 < c1).GetType() != b.GetType()) { intRet = 1; } if ((s2 < s2).GetType() != b.GetType()) { intRet = 1; } if ((s2 < b2).GetType() != b.GetType()) { intRet = 1; } if ((s2 < i2).GetType() != b.GetType()) { intRet = 1; } if ((s2 < l2).GetType() != b.GetType()) { intRet = 1; } //sbyte if ((b2 < s1).GetType() != b.GetType()) { intRet = 1; } if ((b2 < b1).GetType() != b.GetType()) { intRet = 1; } if ((b2 < i1).GetType() != b.GetType()) { intRet = 1; } if ((b2 < l1).GetType() != b.GetType()) { intRet = 1; } if ((b2 < c1).GetType() != b.GetType()) { intRet = 1; } if ((b2 < s2).GetType() != b.GetType()) { intRet = 1; } if ((b2 < b2).GetType() != b.GetType()) { intRet = 1; } if ((b2 < i2).GetType() != b.GetType()) { intRet = 1; } //if ((b2 < l2).GetType() != b.GetType()) { // intRet = 1; //} //uint if ((i2 < s1).GetType() != b.GetType()) { intRet = 1; } if ((i2 < b1).GetType() != b.GetType()) { intRet = 1; } if ((i2 < i1).GetType() != b.GetType()) { intRet = 1; } if ((i2 < l1).GetType() != b.GetType()) { intRet = 1; } if ((i2 < c1).GetType() != b.GetType()) { intRet = 1; } if ((i2 < s2).GetType() != b.GetType()) { intRet = 1; } if ((i2 < b2).GetType() != b.GetType()) { intRet = 1; } if ((i2 < i2).GetType() != b.GetType()) { intRet = 1; } if ((i2 < l2).GetType() != b.GetType()) { intRet = 1; } //ulong //if ((l2 < s1).GetType() != b.GetType()) { // intRet = 1; //} if ((l2 < b1).GetType() != b.GetType()) { intRet = 1; } //if ((l2 < i1).GetType() != b.GetType()) { // intRet = 1; //} //if ((l2 < l1).GetType() != b.GetType()) { // intRet = 1; //} if ((l2 < c1).GetType() != b.GetType()) { intRet = 1; } if ((l2 < s2).GetType() != b.GetType()) { intRet = 1; } //if ((l2 < b2).GetType() != b.GetType()) { // intRet = 1; //} if ((l2 < i2).GetType() != b.GetType()) { intRet = 1; } if ((l2 < l2).GetType() != b.GetType()) { intRet = 1; } return (intRet == 0); } } public class ValueIntegralTestClass61 { public static bool testMethod() { int intRet = 0; short s1 = 2; byte b1 = 3; int i1 = 4; long l1 = 5L; char c1 = (char)6; ushort s2 = 7; sbyte b2 = 8; uint i2 = 9; ulong l2 = 10; bool b = true; //ushort if ((s2 >= s1).GetType() != b.GetType()) { intRet = 1; } if ((s2 >= b1).GetType() != b.GetType()) { intRet = 1; } if ((s2 >= i1).GetType() != b.GetType()) { intRet = 1; } if ((s2 >= l1).GetType() != b.GetType()) { intRet = 1; } if ((s2 >= c1).GetType() != b.GetType()) { intRet = 1; } if ((s2 >= s2).GetType() != b.GetType()) { intRet = 1; } if ((s2 >= b2).GetType() != b.GetType()) { intRet = 1; } if ((s2 >= i2).GetType() != b.GetType()) { intRet = 1; } if ((s2 >= l2).GetType() != b.GetType()) { intRet = 1; } //sbyte if ((b2 >= s1).GetType() != b.GetType()) { intRet = 1; } if ((b2 >= b1).GetType() != b.GetType()) { intRet = 1; } if ((b2 >= i1).GetType() != b.GetType()) { intRet = 1; } if ((b2 >= l1).GetType() != b.GetType()) { intRet = 1; } if ((b2 >= c1).GetType() != b.GetType()) { intRet = 1; } if ((b2 >= s2).GetType() != b.GetType()) { intRet = 1; } if ((b2 >= b2).GetType() != b.GetType()) { intRet = 1; } if ((b2 >= i2).GetType() != b.GetType()) { intRet = 1; } //if ((b2 >= l2).GetType() != b.GetType()) { // intRet = 1; //} //uint if ((i2 >= s1).GetType() != b.GetType()) { intRet = 1; } if ((i2 >= b1).GetType() != b.GetType()) { intRet = 1; } if ((i2 >= i1).GetType() != b.GetType()) { intRet = 1; } if ((i2 >= l1).GetType() != b.GetType()) { intRet = 1; } if ((i2 >= c1).GetType() != b.GetType()) { intRet = 1; } if ((i2 >= s2).GetType() != b.GetType()) { intRet = 1; } if ((i2 >= b2).GetType() != b.GetType()) { intRet = 1; } if ((i2 >= i2).GetType() != b.GetType()) { intRet = 1; } if ((i2 >= l2).GetType() != b.GetType()) { intRet = 1; } //ulong //if ((l2 >= s1).GetType() != b.GetType()) { // intRet = 1; //} if ((l2 >= b1).GetType() != b.GetType()) { intRet = 1; } //if ((l2 >= i1).GetType() != b.GetType()) { // intRet = 1; //} //if ((l2 >= l1).GetType() != b.GetType()) { // intRet = 1; //} if ((l2 >= c1).GetType() != b.GetType()) { intRet = 1; } if ((l2 >= s2).GetType() != b.GetType()) { intRet = 1; } //if ((l2 >= b2).GetType() != b.GetType()) { // intRet = 1; //} if ((l2 >= i2).GetType() != b.GetType()) { intRet = 1; } if ((l2 >= l2).GetType() != b.GetType()) { intRet = 1; } return (intRet == 0); } } public class ValueIntegralTestClass62 { public static bool testMethod() { int intRet = 0; short s1 = 2; byte b1 = 3; int i1 = 4; long l1 = 5L; char c1 = (char)6; ushort s2 = 7; sbyte b2 = 8; uint i2 = 9; ulong l2 = 10; bool b = true; //ushort if ((s2 <= s1).GetType() != b.GetType()) { intRet = 1; } if ((s2 <= b1).GetType() != b.GetType()) { intRet = 1; } if ((s2 <= i1).GetType() != b.GetType()) { intRet = 1; } if ((s2 <= l1).GetType() != b.GetType()) { intRet = 1; } if ((s2 <= c1).GetType() != b.GetType()) { intRet = 1; } if ((s2 <= s2).GetType() != b.GetType()) { intRet = 1; } if ((s2 <= b2).GetType() != b.GetType()) { intRet = 1; } if ((s2 <= i2).GetType() != b.GetType()) { intRet = 1; } if ((s2 <= l2).GetType() != b.GetType()) { intRet = 1; } //sbyte if ((b2 <= s1).GetType() != b.GetType()) { intRet = 1; } if ((b2 <= b1).GetType() != b.GetType()) { intRet = 1; } if ((b2 <= i1).GetType() != b.GetType()) { intRet = 1; } if ((b2 <= l1).GetType() != b.GetType()) { intRet = 1; } if ((b2 <= c1).GetType() != b.GetType()) { intRet = 1; } if ((b2 <= s2).GetType() != b.GetType()) { intRet = 1; } if ((b2 <= b2).GetType() != b.GetType()) { intRet = 1; } if ((b2 <= i2).GetType() != b.GetType()) { intRet = 1; } //if ((b2 <= l2).GetType() != b.GetType()) { // intRet = 1; //} //uint if ((i2 <= s1).GetType() != b.GetType()) { intRet = 1; } if ((i2 <= b1).GetType() != b.GetType()) { intRet = 1; } if ((i2 <= i1).GetType() != b.GetType()) { intRet = 1; } if ((i2 <= l1).GetType() != b.GetType()) { intRet = 1; } if ((i2 <= c1).GetType() != b.GetType()) { intRet = 1; } if ((i2 <= s2).GetType() != b.GetType()) { intRet = 1; } if ((i2 <= b2).GetType() != b.GetType()) { intRet = 1; } if ((i2 <= i2).GetType() != b.GetType()) { intRet = 1; } if ((i2 <= l2).GetType() != b.GetType()) { intRet = 1; } //ulong //if ((l2 <= s1).GetType() != b.GetType()) { // intRet = 1; //} if ((l2 <= b1).GetType() != b.GetType()) { intRet = 1; } //if ((l2 <= i1).GetType() != b.GetType()) { // intRet = 1; //} //if ((l2 <= l1).GetType() != b.GetType()) { // intRet = 1; //} if ((l2 <= c1).GetType() != b.GetType()) { intRet = 1; } if ((l2 <= s2).GetType() != b.GetType()) { intRet = 1; } //if ((l2 <= b2).GetType() != b.GetType()) { // intRet = 1; //} if ((l2 <= i2).GetType() != b.GetType()) { intRet = 1; } if ((l2 <= l2).GetType() != b.GetType()) { intRet = 1; } return (intRet == 0); } } public class ValueIntegralTestClass63 { public static bool testMethod() { int intRet = 0; ushort s1 = 2; sbyte b1 = 3; uint i1 = 4; ulong l1 = 5L; int i = 1; if ((s1 << 1).GetType() != i.GetType()) { intRet = 1; } if ((b1 << 1).GetType() != i.GetType()) { intRet = 1; } if ((i1 << 1).GetType() != i1.GetType()) { intRet = 1; } if ((l1 << 1).GetType() != l1.GetType()) { intRet = 1; } return (intRet == 0); } } public class ValueIntegralTestClass64 { public static bool testMethod() { int intRet = 0; ushort s1 = 2; sbyte b1 = 3; uint i1 = 4; ulong l1 = 5L; int i = 1; if ((s1 >> 1).GetType() != i.GetType()) { intRet = 1; } if ((b1 >> 1).GetType() != i.GetType()) { intRet = 1; } if ((i1 >> 1).GetType() != i1.GetType()) { intRet = 1; } if ((l1 >> 1).GetType() != l1.GetType()) { intRet = 1; } return (intRet == 0); } } public class ValueIntegralTestClass70 { public static bool testMethod() { char c = (char)10; if (c == '\x000a') { return true; } else { return false; } } } } } ================================================ FILE: Zelig/Zelig/Test/RunTime/NETMF/mscorlib/types/ValueSimpleTests.cs ================================================ //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // Copyright (c) Microsoft Corporation. All rights reserved. //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// using System; namespace Microsoft.Zelig.Test { public class ValueSimpleTests : TestBase, ITestInterface { [SetUp] public InitializeResult Initialize() { Log.Comment("Adding set up for the tests"); return InitializeResult.ReadyToGo; } [TearDown] public void CleanUp() { Log.Comment("Cleaning up after the tests"); } public override TestResult Run( string[] args ) { TestResult result = TestResult.Pass; string testName = "ValueSimpleXX_"; int testNumber = 0; //////result |= Assert.CheckFailed( ValueSimple01_Test( ), testName, ++testNumber ); //////result |= Assert.CheckFailed( ValueSimple02_Test( ), testName, ++testNumber ); //////result |= Assert.CheckFailed( ValueSimple03_Test( ), testName, ++testNumber ); //////result |= Assert.CheckFailed( ValueSimple04_Test( ), testName, ++testNumber ); //////result |= Assert.CheckFailed( ValueSimple05_Test( ), testName, ++testNumber ); //////result |= Assert.CheckFailed( ValueSimple06_Test( ), testName, ++testNumber ); //////result |= Assert.CheckFailed( ValueSimple07_Test( ), testName, ++testNumber ); //////result |= Assert.CheckFailed( ValueSimple09_Test( ), testName, ++testNumber ); result |= Assert.CheckFailed( ValueSimple11_Test( ), testName, ++testNumber ); result |= Assert.CheckFailed( ValueSimple12_Test( ), testName, ++testNumber ); //////result |= Assert.CheckFailed( ValueSimple13_Test( ), testName, ++testNumber ); //////result |= Assert.CheckFailed( ValueSimple14_Test( ), testName, ++testNumber ); //////result |= Assert.CheckFailed( ValueSimple15_Test( ), testName, ++testNumber ); return result; } //ValueSimple Test methods //The following tests were ported from folder current\test\cases\client\CLR\Conformance\4_values\ValueSimple //01,02,03,04,05,06,07,09,11,12,13,14,15 //12 Failed //Test Case Calls //////[TestMethod] //////public TestResult ValueSimple01_Test() //////{ ////// Log.Comment(" Section 4.1"); ////// Log.Comment(" byte is an alias for System.Byte"); ////// if (ValueSimpleTestClass01.testMethod()) ////// { ////// return TestResult.Pass; ////// } ////// return TestResult.Fail; //////} //////[TestMethod] //////public TestResult ValueSimple02_Test() //////{ ////// Log.Comment(" Section 4.1"); ////// Log.Comment(" char is an alias for System.Char"); ////// if (ValueSimpleTestClass02.testMethod()) ////// { ////// return TestResult.Pass; ////// } ////// return TestResult.Fail; //////} //////[TestMethod] //////public TestResult ValueSimple03_Test() //////{ ////// Log.Comment(" Section 4.1"); ////// Log.Comment(" short is an alias for System.Int16"); ////// if (ValueSimpleTestClass03.testMethod()) ////// { ////// return TestResult.Pass; ////// } ////// return TestResult.Fail; //////} //////[TestMethod] //////public TestResult ValueSimple04_Test() //////{ ////// Log.Comment(" Section 4.1"); ////// Log.Comment(" int is an alias for System.Int32"); ////// if (ValueSimpleTestClass04.testMethod()) ////// { ////// return TestResult.Pass; ////// } ////// return TestResult.Fail; //////} //////[TestMethod] //////public TestResult ValueSimple05_Test() //////{ ////// Log.Comment(" Section 4.1"); ////// Log.Comment(" long is an alias for System.Int64"); ////// if (ValueSimpleTestClass05.testMethod()) ////// { ////// return TestResult.Pass; ////// } ////// return TestResult.Fail; //////} //////[TestMethod] //////public TestResult ValueSimple06_Test() //////{ ////// Log.Comment(" Section 4.1"); ////// Log.Comment(" float is an alias for System.Single"); ////// if (ValueSimpleTestClass06.testMethod()) ////// { ////// return TestResult.Pass; ////// } ////// return TestResult.Fail; //////} //////[TestMethod] //////public TestResult ValueSimple07_Test() //////{ ////// Log.Comment(" Section 4.1"); ////// Log.Comment(" double is an alias for System.Double"); ////// if (ValueSimpleTestClass07.testMethod()) ////// { ////// return TestResult.Pass; ////// } ////// return TestResult.Fail; //////} //////[TestMethod] //////public TestResult ValueSimple09_Test() //////{ ////// Log.Comment(" Section 4.1"); ////// Log.Comment(" bool is an alias for System.Boolean"); ////// if (ValueSimpleTestClass09.testMethod()) ////// { ////// return TestResult.Pass; ////// } ////// return TestResult.Fail; //////} [TestMethod] public TestResult ValueSimple11_Test() { Log.Comment(" Section 4.1"); Log.Comment(" A simple type and the structure type it aliases are completely indistinguishable."); Log.Comment(" In other words, writing the reserved work byte is exactly the same as writing "); Log.Comment(" System.Byte, and writing System.Int32 is exactly the same as writing the reserved"); Log.Comment(" word int."); if (ValueSimpleTestClass11.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult ValueSimple12_Test() { Log.Comment(" Section 4.1"); Log.Comment(" Because a simple type aliases a struct type, every simple type has members."); if (ValueSimpleTestClass12.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } //////[TestMethod] //////public TestResult ValueSimple13_Test() //////{ ////// Log.Comment(" Section 4.1"); ////// Log.Comment(" sbyte is an alias for System.SByte"); ////// if (ValueSimpleTestClass13.testMethod()) ////// { ////// return TestResult.Pass; ////// } ////// return TestResult.Fail; //////} //////[TestMethod] //////public TestResult ValueSimple14_Test() //////{ ////// Log.Comment(" Section 4.1"); ////// Log.Comment(" ushort is an alias for System.UInt16"); ////// if (ValueSimpleTestClass14.testMethod()) ////// { ////// return TestResult.Pass; ////// } ////// return TestResult.Fail; //////} //////[TestMethod] //////public TestResult ValueSimple15_Test() //////{ ////// Log.Comment(" Section 4.1"); ////// Log.Comment(" uint is an alias for System.UInt32"); ////// if (ValueSimpleTestClass15.testMethod()) ////// { ////// return TestResult.Pass; ////// } ////// return TestResult.Fail; //////} //Compiled Test Cases //////public class ValueSimpleTestClass01 //////{ ////// public static bool testMethod() ////// { ////// byte b = 0; ////// if (b.GetType() == Type.GetType("System.Byte")) ////// { ////// return true; ////// } ////// else ////// { ////// return false; ////// } ////// } //////} //////public class ValueSimpleTestClass02 //////{ ////// public static bool testMethod() ////// { ////// char c = 'a'; ////// if (c.GetType() == Type.GetType("System.Char")) ////// { ////// return true; ////// } ////// else ////// { ////// return false; ////// } ////// } //////} //////public class ValueSimpleTestClass03 //////{ ////// public static bool testMethod() ////// { ////// short s = 0; ////// if (s.GetType() == Type.GetType("System.Int16")) ////// { ////// return true; ////// } ////// else ////// { ////// return false; ////// } ////// } //////} //////public class ValueSimpleTestClass04 //////{ ////// public static bool testMethod() ////// { ////// int i = 0; ////// if (i.GetType() == Type.GetType("System.Int32")) ////// { ////// return true; ////// } ////// else ////// { ////// return false; ////// } ////// } //////} //////public class ValueSimpleTestClass05 //////{ ////// public static bool testMethod() ////// { ////// long l = 0L; ////// if (l.GetType() == Type.GetType("System.Int64")) ////// { ////// return true; ////// } ////// else ////// { ////// return false; ////// } ////// } //////} //////public class ValueSimpleTestClass06 //////{ ////// public static bool testMethod() ////// { ////// float f = 0.0f; ////// if (f.GetType() == Type.GetType("System.Single")) ////// { ////// return true; ////// } ////// else ////// { ////// return false; ////// } ////// } //////} //////public class ValueSimpleTestClass07 //////{ ////// public static bool testMethod() ////// { ////// double d = 0.0d; ////// if (d.GetType() == Type.GetType("System.Double")) ////// { ////// return true; ////// } ////// else ////// { ////// return false; ////// } ////// } //////} //////public class ValueSimpleTestClass09 //////{ ////// public static bool testMethod() ////// { ////// bool b = true; ////// if (b.GetType() == Type.GetType("System.Boolean")) ////// { ////// return true; ////// } ////// else ////// { ////// return false; ////// } ////// } //////} public class ValueSimpleTestClass11 { public static bool testMethod() { System.Byte b = 2; System.Int32 i = 2; if ((b == 2) && (i == 2)) { return true; } else { return false; } } } public class ValueSimpleTestClass12 { public static bool testMethod() { bool RetVal = true; int i = int.MaxValue; if (i != Int32.MaxValue) { RetVal = false; } string s = i.ToString(); if (!s.Equals(Int32.MaxValue.ToString())) { RetVal = false; } i = 123; string t = 123.ToString(); if (!t.Equals(i.ToString())) { RetVal = false; } return RetVal; } } //////public class ValueSimpleTestClass13 //////{ ////// public static bool testMethod() ////// { ////// sbyte b = 0; ////// if (b.GetType() == Type.GetType("System.SByte")) ////// { ////// return true; ////// } ////// else ////// { ////// return false; ////// } ////// } //////} //////public class ValueSimpleTestClass14 //////{ ////// public static bool testMethod() ////// { ////// ushort s = 0; ////// if (s.GetType() == Type.GetType("System.UInt16")) ////// { ////// return true; ////// } ////// else ////// { ////// return false; ////// } ////// } //////} //////public class ValueSimpleTestClass15 //////{ ////// public static bool testMethod() ////// { ////// uint i = 0; ////// if (i.GetType() == Type.GetType("System.UInt32")) ////// { ////// return true; ////// } ////// else ////// { ////// return false; ////// } ////// } //////} } } ================================================ FILE: Zelig/Zelig/Test/RunTime/NETMF/mscorlib/types/ValueTests.cs ================================================ //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // Copyright (c) Microsoft Corporation. All rights reserved. //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// using System; namespace Microsoft.Zelig.Test { public class ValueTests : TestBase, ITestInterface { [SetUp] public InitializeResult Initialize() { Log.Comment("Adding set up for the tests"); Log.Comment(" Section 4.1"); Log.Comment(" Assignment to a variable of a value type creates a copy of the value"); Log.Comment(" being assigned. This differs from assignment to a variable of a "); Log.Comment(" reference type, which copies the reference but not the object identified"); Log.Comment(" by the reference."); return InitializeResult.ReadyToGo; } [TearDown] public void CleanUp() { Log.Comment("Cleaning up after the tests"); } public override TestResult Run( string[] args ) { TestResult result = TestResult.Pass; string testName = "Value*_"; int testNumber = 0; result |= Assert.CheckFailed( Value7_Test( ), testName, ++testNumber ); result |= Assert.CheckFailed( Value8_Test( ), testName, ++testNumber ); result |= Assert.CheckFailed( Value9_Test( ), testName, ++testNumber ); return result; } //Value Test methods //The following tests were ported from folder current\test\cases\client\CLR\Conformance\4_values\Value //7,8,9 //Test Case Calls [TestMethod] public TestResult Value7_Test() { if (ValueTestClass7.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Value8_Test() { if (ValueTestClass8.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Value9_Test() { if (ValueTestClass9.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } //Compiled Test Cases public struct ValueTestClass7_Struct { public int MyInt; } public class ValueTestClass7 { public static bool testMethod() { ValueTestClass7_Struct MS = new ValueTestClass7_Struct(); ValueTestClass7_Struct MS2; MS.MyInt = 3; MS2 = MS; MS.MyInt = 4; if (MS2.MyInt == 3) { return true; } else { return false; } } } public class ValueTestClass8 { public static bool testMethod() { int MyInt; int MyInt2; MyInt = 3; MyInt2 = MyInt; MyInt = 4; if (MyInt2 == 3) { return true; } else { return false; } } } enum ValueTestClass9_Enum { a = 1, b = 2 } public class ValueTestClass9 { public static bool testMethod() { ValueTestClass9_Enum Enum1; ValueTestClass9_Enum Enum2; Enum1 = ValueTestClass9_Enum.a; Enum2 = Enum1; Enum1 = ValueTestClass9_Enum.b; if ((int)Enum2 == (int)ValueTestClass9_Enum.a) { return true; } else { return false; } } } } } ================================================ FILE: Zelig/Zelig/Test/RunTime/NETMF/mscorlib/variables/CategoriesTests.cs ================================================ //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // Copyright (c) Microsoft Corporation. All rights reserved. //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// using System; using System.Reflection; using Microsoft.SPOT.Platform.Test; namespace Microsoft.SPOT.Platform.Tests { public class CategoriesTests : IMFTestInterface { [SetUp] public InitializeResult Initialize() { Log.Comment("Adding set up for the tests."); // Add your functionality here. return InitializeResult.ReadyToGo; } [TearDown] public void CleanUp() { Log.Comment("Cleaning up after the tests"); } //Categories Test methods //The following tests were ported from folder current\test\cases\client\CLR\Conformance\10_classes\Categories //static01,static02,static03,static04,static05,static06,static07,static09,static11,static12,static13,static14,static15,static16,static17,static18,static19,static20,static21,inst018,inst019,inst020,inst021,inst022,inst023,inst024,inst026,inst028,inst029,inst030,inst031,inst032,inst033,inst034,inst035,inst036,inst037,inst038,inst039,inst040,inst041,inst042,inst043,inst044,inst046,inst048,inst049,inst050,inst051,inst052,inst053,inst054 //Test Case Calls [TestMethod] public MFTestResults Categories_static01_Test() { Log.Comment("Section 5.1.1"); Log.Comment(" Categories_TestClass_?_A field declared with the static modifier is called a"); Log.Comment("static variable. Categories_TestClass_?_A static variable comes into existence"); Log.Comment("when the type in which it is declared is loaded, and "); Log.Comment("ceases to exist when the type in which it is declared"); Log.Comment("is unloaded."); if (Categories_TestClass_static01.testMethod()) { return MFTestResults.Pass; } return MFTestResults.Fail; } [TestMethod] public MFTestResults Categories_static02_Test() { Log.Comment("Section 5.1.1"); Log.Comment(" Categories_TestClass_?_A field declared with the static modifier is called a"); Log.Comment("static variable. Categories_TestClass_?_A static variable comes into existence"); Log.Comment("when the type in which it is declared is loaded, and "); Log.Comment("ceases to exist when the type in which it is declared"); Log.Comment("is unloaded."); if (Categories_TestClass_static02.testMethod()) { return MFTestResults.Pass; } return MFTestResults.Fail; } [TestMethod] public MFTestResults Categories_static03_Test() { Log.Comment("Section 5.1.1"); Log.Comment(" Categories_TestClass_?_A field declared with the static modifier is called a"); Log.Comment("static variable. Categories_TestClass_?_A static variable comes into existence"); Log.Comment("when the type in which it is declared is loaded, and "); Log.Comment("ceases to exist when the type in which it is declared"); Log.Comment("is unloaded."); if (Categories_TestClass_static03.testMethod()) { return MFTestResults.Pass; } return MFTestResults.Fail; } [TestMethod] public MFTestResults Categories_static04_Test() { Log.Comment("Section 5.1.1"); Log.Comment(" Categories_TestClass_?_A field declared with the static modifier is called a"); Log.Comment("static variable. Categories_TestClass_?_A static variable comes into existence"); Log.Comment("when the type in which it is declared is loaded, and "); Log.Comment("ceases to exist when the type in which it is declared"); Log.Comment("is unloaded."); if (Categories_TestClass_static04.testMethod()) { return MFTestResults.Pass; } return MFTestResults.Fail; } [TestMethod] public MFTestResults Categories_static05_Test() { Log.Comment("Section 5.1.1"); Log.Comment(" Categories_TestClass_?_A field declared with the static modifier is called a"); Log.Comment("static variable. Categories_TestClass_?_A static variable comes into existence"); Log.Comment("when the type in which it is declared is loaded, and "); Log.Comment("ceases to exist when the type in which it is declared"); Log.Comment("is unloaded."); if (Categories_TestClass_static05.testMethod()) { return MFTestResults.Pass; } return MFTestResults.Fail; } [TestMethod] public MFTestResults Categories_static06_Test() { Log.Comment("Section 5.1.1"); Log.Comment(" Categories_TestClass_?_A field declared with the static modifier is called a"); Log.Comment("static variable. Categories_TestClass_?_A static variable comes into existence"); Log.Comment("when the type in which it is declared is loaded, and "); Log.Comment("ceases to exist when the type in which it is declared"); Log.Comment("is unloaded."); if (Categories_TestClass_static06.testMethod()) { return MFTestResults.Pass; } return MFTestResults.Fail; } [TestMethod] public MFTestResults Categories_static07_Test() { Log.Comment("Section 5.1.1"); Log.Comment(" Categories_TestClass_?_A field declared with the static modifier is called a"); Log.Comment("static variable. Categories_TestClass_?_A static variable comes into existence"); Log.Comment("when the type in which it is declared is loaded, and "); Log.Comment("ceases to exist when the type in which it is declared"); Log.Comment("is unloaded."); if (Categories_TestClass_static07.testMethod()) { return MFTestResults.Pass; } return MFTestResults.Fail; } [TestMethod] public MFTestResults Categories_static09_Test() { Log.Comment("Section 5.1.1"); Log.Comment(" Categories_TestClass_?_A field declared with the static modifier is called a"); Log.Comment("static variable. Categories_TestClass_?_A static variable comes into existence"); Log.Comment("when the type in which it is declared is loaded, and "); Log.Comment("ceases to exist when the type in which it is declared"); Log.Comment("is unloaded."); if (Categories_TestClass_static09.testMethod()) { return MFTestResults.Pass; } return MFTestResults.Fail; } [TestMethod] public MFTestResults Categories_static11_Test() { Log.Comment("Section 5.1.1"); Log.Comment(" Categories_TestClass_?_A field declared with the static modifier is called a"); Log.Comment("static variable. Categories_TestClass_?_A static variable comes into existence"); Log.Comment("when the type in which it is declared is loaded, and "); Log.Comment("ceases to exist when the type in which it is declared"); Log.Comment("is unloaded."); if (Categories_TestClass_static11.testMethod()) { return MFTestResults.Pass; } return MFTestResults.Fail; } [TestMethod] public MFTestResults Categories_static12_Test() { Log.Comment("Section 5.1.1"); Log.Comment(" Categories_TestClass_?_A field declared with the static modifier is called a"); Log.Comment("static variable. Categories_TestClass_?_A static variable comes into existence"); Log.Comment("when the type in which it is declared is loaded, and "); Log.Comment("ceases to exist when the type in which it is declared"); Log.Comment("is unloaded."); if (Categories_TestClass_static12.testMethod()) { return MFTestResults.Pass; } return MFTestResults.Fail; } [TestMethod] public MFTestResults Categories_static13_Test() { Log.Comment("Section 5.1.1"); Log.Comment(" Categories_TestClass_?_A field declared with the static modifier is called a"); Log.Comment("static variable. Categories_TestClass_?_A static variable comes into existence"); Log.Comment("when the type in which it is declared is loaded, and "); Log.Comment("ceases to exist when the type in which it is declared"); Log.Comment("is unloaded."); if (Categories_TestClass_static13.testMethod()) { return MFTestResults.Pass; } return MFTestResults.Fail; } [TestMethod] public MFTestResults Categories_static14_Test() { Log.Comment("Section 5.1.1"); Log.Comment(" Categories_TestClass_?_A field declared with the static modifier is called a"); Log.Comment("static variable. Categories_TestClass_?_A static variable comes into existence"); Log.Comment("when the type in which it is declared is loaded, and "); Log.Comment("ceases to exist when the type in which it is declared"); Log.Comment("is unloaded."); if (Categories_TestClass_static14.testMethod()) { return MFTestResults.Pass; } return MFTestResults.Fail; } [TestMethod] public MFTestResults Categories_static15_Test() { Log.Comment("Section 5.1.1"); Log.Comment(" Categories_TestClass_?_A field declared with the static modifier is called a"); Log.Comment("static variable. Categories_TestClass_?_A static variable comes into existence"); Log.Comment("when the type in which it is declared is loaded, and "); Log.Comment("ceases to exist when the type in which it is declared"); Log.Comment("is unloaded."); if (Categories_TestClass_static15.testMethod()) { return MFTestResults.Pass; } return MFTestResults.Fail; } [TestMethod] public MFTestResults Categories_static16_Test() { Log.Comment("Section 5.1.1"); Log.Comment(" Categories_TestClass_?_A field declared with the static modifier is called a"); Log.Comment("static variable. Categories_TestClass_?_A static variable comes into existence"); Log.Comment("when the type in which it is declared is loaded, and "); Log.Comment("ceases to exist when the type in which it is declared"); Log.Comment("is unloaded."); if (Categories_TestClass_static16.testMethod()) { return MFTestResults.Pass; } return MFTestResults.Fail; } [TestMethod] public MFTestResults Categories_static17_Test() { Log.Comment("Section 5.1.1"); Log.Comment(" Categories_TestClass_?_A field declared with the static modifier is called a"); Log.Comment("static variable. Categories_TestClass_?_A static variable comes into existence"); Log.Comment("when the type in which it is declared is loaded, and "); Log.Comment("ceases to exist when the type in which it is declared"); Log.Comment("is unloaded."); if (Categories_TestClass_static17.testMethod()) { return MFTestResults.Pass; } return MFTestResults.Fail; } [TestMethod] public MFTestResults Categories_static18_Test() { Log.Comment("Section 5.1.1"); Log.Comment("The initial value of a static variable is the default value"); Log.Comment("of the variable's type."); if (Categories_TestClass_static18.testMethod()) { return MFTestResults.Pass; } return MFTestResults.Fail; } [TestMethod] public MFTestResults Categories_static19_Test() { Log.Comment("Section 5.1.1"); Log.Comment("The initial value of a static variable is the default value"); Log.Comment("of the variable's type."); if (Categories_TestClass_static19.testMethod()) { return MFTestResults.Pass; } return MFTestResults.Fail; } [TestMethod] public MFTestResults Categories_static20_Test() { Log.Comment("Section 5.1.1"); Log.Comment("The initial value of a static variable is the default value"); Log.Comment("of the variable's type."); if (Categories_TestClass_static20.testMethod()) { return MFTestResults.Pass; } return MFTestResults.Fail; } /* [TestMethod] public MFTestResults Categories_static21_Test() { Log.Comment("Section 5"); if (Categories_TestClass_static21.testMethod()) { return MFTestResults.Pass; } return MFTestResults.Fail; } */ [TestMethod] public MFTestResults Categories_inst018_Test() { Log.Comment("Section 5.1.2"); Log.Comment("An instance variable of a class comes into existence when "); Log.Comment("a new instance of that class is created, and ceases to exist"); Log.Comment("when there are no references to that instance and the finalizer"); Log.Comment("of the instance has executed."); if (Categories_TestClass_inst018.testMethod()) { return MFTestResults.Pass; } return MFTestResults.Fail; } [TestMethod] public MFTestResults Categories_inst019_Test() { Log.Comment("Section 5.1.2"); Log.Comment("An instance variable of a class comes into existence when "); Log.Comment("a new instance of that class is created, and ceases to exist"); Log.Comment("when there are no references to that instance and the finalizer"); Log.Comment("of the instance has executed."); if (Categories_TestClass_inst019.testMethod()) { return MFTestResults.Pass; } return MFTestResults.Fail; } [TestMethod] public MFTestResults Categories_inst020_Test() { Log.Comment("Section 5.1.2"); Log.Comment("An instance variable of a class comes into existence when "); Log.Comment("a new instance of that class is created, and ceases to exist"); Log.Comment("when there are no references to that instance and the finalizer"); Log.Comment("of the instance has executed."); if (Categories_TestClass_inst020.testMethod()) { return MFTestResults.Pass; } return MFTestResults.Fail; } [TestMethod] public MFTestResults Categories_inst021_Test() { Log.Comment("Section 5.1.2"); Log.Comment("An instance variable of a class comes into existence when "); Log.Comment("a new instance of that class is created, and ceases to exist"); Log.Comment("when there are no references to that instance and the finalizer"); Log.Comment("of the instance has executed."); if (Categories_TestClass_inst021.testMethod()) { return MFTestResults.Pass; } return MFTestResults.Fail; } [TestMethod] public MFTestResults Categories_inst022_Test() { Log.Comment("Section 5.1.2"); Log.Comment("An instance variable of a class comes into existence when "); Log.Comment("a new instance of that class is created, and ceases to exist"); Log.Comment("when there are no references to that instance and the finalizer"); Log.Comment("of the instance has executed."); if (Categories_TestClass_inst022.testMethod()) { return MFTestResults.Pass; } return MFTestResults.Fail; } [TestMethod] public MFTestResults Categories_inst023_Test() { Log.Comment("Section 5.1.2"); Log.Comment("An instance variable of a class comes into existence when "); Log.Comment("a new instance of that class is created, and ceases to exist"); Log.Comment("when there are no references to that instance and the finalizer"); Log.Comment("of the instance has executed."); if (Categories_TestClass_inst023.testMethod()) { return MFTestResults.Pass; } return MFTestResults.Fail; } [TestMethod] public MFTestResults Categories_inst024_Test() { Log.Comment("Section 5.1.2"); Log.Comment("An instance variable of a class comes into existence when "); Log.Comment("a new instance of that class is created, and ceases to exist"); Log.Comment("when there are no references to that instance and the finalizer"); Log.Comment("of the instance has executed."); if (Categories_TestClass_inst024.testMethod()) { return MFTestResults.Pass; } return MFTestResults.Fail; } [TestMethod] public MFTestResults Categories_inst026_Test() { Log.Comment("Section 5.1.2"); Log.Comment("An instance variable of a class comes into existence when "); Log.Comment("a new instance of that class is created, and ceases to exist"); Log.Comment("when there are no references to that instance and the finalizer"); Log.Comment("of the instance has executed."); if (Categories_TestClass_inst026.testMethod()) { return MFTestResults.Pass; } return MFTestResults.Fail; } [TestMethod] public MFTestResults Categories_inst028_Test() { Log.Comment("Section 5.1.2"); Log.Comment("An instance variable of a class comes into existence when "); Log.Comment("a new instance of that class is created, and ceases to exist"); Log.Comment("when there are no references to that instance and the finalizer"); Log.Comment("of the instance has executed."); if (Categories_TestClass_inst028.testMethod()) { return MFTestResults.Pass; } return MFTestResults.Fail; } [TestMethod] public MFTestResults Categories_inst029_Test() { Log.Comment("Section 5.1.2"); Log.Comment("An instance variable of a class comes into existence when "); Log.Comment("a new instance of that class is created, and ceases to exist"); Log.Comment("when there are no references to that instance and the finalizer"); Log.Comment("of the instance has executed."); if (Categories_TestClass_inst029.testMethod()) { return MFTestResults.Pass; } return MFTestResults.Fail; } [TestMethod] public MFTestResults Categories_inst030_Test() { Log.Comment("Section 5.1.2"); Log.Comment("An instance variable of a class comes into existence when "); Log.Comment("a new instance of that class is created, and ceases to exist"); Log.Comment("when there are no references to that instance and the finalizer"); Log.Comment("of the instance has executed."); if (Categories_TestClass_inst030.testMethod()) { return MFTestResults.Pass; } return MFTestResults.Fail; } [TestMethod] public MFTestResults Categories_inst031_Test() { Log.Comment("Section 5.1.2"); Log.Comment("An instance variable of a class comes into existence when "); Log.Comment("a new instance of that class is created, and ceases to exist"); Log.Comment("when there are no references to that instance and the finalizer"); Log.Comment("of the instance has executed."); if (Categories_TestClass_inst031.testMethod()) { return MFTestResults.Pass; } return MFTestResults.Fail; } [TestMethod] public MFTestResults Categories_inst032_Test() { Log.Comment("Section 5.1.2"); Log.Comment("An instance variable of a class comes into existence when "); Log.Comment("a new instance of that class is created, and ceases to exist"); Log.Comment("when there are no references to that instance and the finalizer"); Log.Comment("of the instance has executed."); if (Categories_TestClass_inst032.testMethod()) { return MFTestResults.Pass; } return MFTestResults.Fail; } [TestMethod] public MFTestResults Categories_inst033_Test() { Log.Comment("Section 5.1.2"); Log.Comment("An instance variable of a class comes into existence when "); Log.Comment("a new instance of that class is created, and ceases to exist"); Log.Comment("when there are no references to that instance and the finalizer"); Log.Comment("of the instance has executed."); if (Categories_TestClass_inst033.testMethod()) { return MFTestResults.Pass; } return MFTestResults.Fail; } [TestMethod] public MFTestResults Categories_inst034_Test() { Log.Comment("Section 5.1.2"); Log.Comment("An instance variable of a class comes into existence when "); Log.Comment("a new instance of that class is created, and ceases to exist"); Log.Comment("when there are no references to that instance and the finalizer"); Log.Comment("of the instance has executed."); if (Categories_TestClass_inst034.testMethod()) { return MFTestResults.Pass; } return MFTestResults.Fail; } [TestMethod] public MFTestResults Categories_inst035_Test() { Log.Comment("Section 5.1.1"); Log.Comment("The initial value of an instance variable is the default value"); Log.Comment("of the variable's type."); if (Categories_TestClass_inst035.testMethod()) { return MFTestResults.Pass; } return MFTestResults.Fail; } [TestMethod] public MFTestResults Categories_inst036_Test() { Log.Comment("Section 5.1.1"); Log.Comment("The initial value of an instance variable is the default value"); Log.Comment("of the variable's type."); if (Categories_TestClass_inst036.testMethod()) { return MFTestResults.Pass; } return MFTestResults.Fail; } [TestMethod] public MFTestResults Categories_inst037_Test() { Log.Comment("Section 5.1.1"); Log.Comment("The initial value of an instance variable is the default value"); Log.Comment("of the variable's type."); if (Categories_TestClass_inst037.testMethod()) { return MFTestResults.Pass; } return MFTestResults.Fail; } [TestMethod] public MFTestResults Categories_inst038_Test() { Log.Comment("Section 5.1.2"); Log.Comment("An instance variable of a struct has exactly the"); Log.Comment("same lifetime as the struct variable to which it"); Log.Comment("belongs. In other words, when a variable of a "); Log.Comment("struct type comes into existence or ceases to "); Log.Comment("exist, so do the instance variables of the struct."); if (Categories_TestClass_inst038.testMethod()) { return MFTestResults.Pass; } return MFTestResults.Fail; } [TestMethod] public MFTestResults Categories_inst039_Test() { Log.Comment("Section 5.1.2"); Log.Comment("An instance variable of a struct has exactly the"); Log.Comment("same lifetime as the struct variable to which it"); Log.Comment("belongs. In other words, when a variable of a "); Log.Comment("struct type comes into existence or ceases to "); Log.Comment("exist, so do the instance variables of the struct."); if (Categories_TestClass_inst039.testMethod()) { return MFTestResults.Pass; } return MFTestResults.Fail; } [TestMethod] public MFTestResults Categories_inst040_Test() { Log.Comment("Section 5.1.2"); Log.Comment("An instance variable of a struct has exactly the"); Log.Comment("same lifetime as the struct variable to which it"); Log.Comment("belongs. In other words, when a variable of a "); Log.Comment("struct type comes into existence or ceases to "); Log.Comment("exist, so do the instance variables of the struct."); if (Categories_TestClass_inst040.testMethod()) { return MFTestResults.Pass; } return MFTestResults.Fail; } [TestMethod] public MFTestResults Categories_inst041_Test() { Log.Comment("Section 5.1.2"); Log.Comment("An instance variable of a struct has exactly the"); Log.Comment("same lifetime as the struct variable to which it"); Log.Comment("belongs. In other words, when a variable of a "); Log.Comment("struct type comes into existence or ceases to "); Log.Comment("exist, so do the instance variables of the struct."); if (Categories_TestClass_inst041.testMethod()) { return MFTestResults.Pass; } return MFTestResults.Fail; } [TestMethod] public MFTestResults Categories_inst042_Test() { Log.Comment("Section 5.1.2"); Log.Comment("An instance variable of a struct has exactly the"); Log.Comment("same lifetime as the struct variable to which it"); Log.Comment("belongs. In other words, when a variable of a "); Log.Comment("struct type comes into existence or ceases to "); Log.Comment("exist, so do the instance variables of the struct."); if (Categories_TestClass_inst042.testMethod()) { return MFTestResults.Pass; } return MFTestResults.Fail; } [TestMethod] public MFTestResults Categories_inst043_Test() { Log.Comment("Section 5.1.2"); Log.Comment("An instance variable of a struct has exactly the"); Log.Comment("same lifetime as the struct variable to which it"); Log.Comment("belongs. In other words, when a variable of a "); Log.Comment("struct type comes into existence or ceases to "); Log.Comment("exist, so do the instance variables of the struct."); if (Categories_TestClass_inst043.testMethod()) { return MFTestResults.Pass; } return MFTestResults.Fail; } [TestMethod] public MFTestResults Categories_inst044_Test() { Log.Comment("Section 5.1.2"); Log.Comment("An instance variable of a struct has exactly the"); Log.Comment("same lifetime as the struct variable to which it"); Log.Comment("belongs. In other words, when a variable of a "); Log.Comment("struct type comes into existence or ceases to "); Log.Comment("exist, so do the instance variables of the struct."); if (Categories_TestClass_inst044.testMethod()) { return MFTestResults.Pass; } return MFTestResults.Fail; } [TestMethod] public MFTestResults Categories_inst046_Test() { Log.Comment("Section 5.1.2"); Log.Comment("An instance variable of a struct has exactly the"); Log.Comment("same lifetime as the struct variable to which it"); Log.Comment("belongs. In other words, when a variable of a "); Log.Comment("struct type comes into existence or ceases to "); Log.Comment("exist, so do the instance variables of the struct."); if (Categories_TestClass_inst046.testMethod()) { return MFTestResults.Pass; } return MFTestResults.Fail; } [TestMethod] public MFTestResults Categories_inst048_Test() { Log.Comment("Section 5.1.2"); Log.Comment("An instance variable of a struct has exactly the"); Log.Comment("same lifetime as the struct variable to which it"); Log.Comment("belongs. In other words, when a variable of a "); Log.Comment("struct type comes into existence or ceases to "); Log.Comment("exist, so do the instance variables of the struct."); if (Categories_TestClass_inst048.testMethod()) { return MFTestResults.Pass; } return MFTestResults.Fail; } [TestMethod] public MFTestResults Categories_inst049_Test() { Log.Comment("Section 5.1.2"); Log.Comment("An instance variable of a struct has exactly the"); Log.Comment("same lifetime as the struct variable to which it"); Log.Comment("belongs. In other words, when a variable of a "); Log.Comment("struct type comes into existence or ceases to "); Log.Comment("exist, so do the instance variables of the struct."); if (Categories_TestClass_inst049.testMethod()) { return MFTestResults.Pass; } return MFTestResults.Fail; } [TestMethod] public MFTestResults Categories_inst050_Test() { Log.Comment("Section 5.1.2"); Log.Comment("An instance variable of a struct has exactly the"); Log.Comment("same lifetime as the struct variable to which it"); Log.Comment("belongs. In other words, when a variable of a "); Log.Comment("struct type comes into existence or ceases to "); Log.Comment("exist, so do the instance variables of the struct."); if (Categories_TestClass_inst050.testMethod()) { return MFTestResults.Pass; } return MFTestResults.Fail; } [TestMethod] public MFTestResults Categories_inst051_Test() { Log.Comment("Section 5.1.2"); Log.Comment("An instance variable of a struct has exactly the"); Log.Comment("same lifetime as the struct variable to which it"); Log.Comment("belongs. In other words, when a variable of a "); Log.Comment("struct type comes into existence or ceases to "); Log.Comment("exist, so do the instance variables of the struct."); if (Categories_TestClass_inst051.testMethod()) { return MFTestResults.Pass; } return MFTestResults.Fail; } [TestMethod] public MFTestResults Categories_inst052_Test() { Log.Comment("Section 5.1.2"); Log.Comment("An instance variable of a struct has exactly the"); Log.Comment("same lifetime as the struct variable to which it"); Log.Comment("belongs. In other words, when a variable of a "); Log.Comment("struct type comes into existence or ceases to "); Log.Comment("exist, so do the instance variables of the struct."); if (Categories_TestClass_inst052.testMethod()) { return MFTestResults.Pass; } return MFTestResults.Fail; } [TestMethod] public MFTestResults Categories_inst053_Test() { Log.Comment("Section 5.1.2"); Log.Comment("An instance variable of a struct has exactly the"); Log.Comment("same lifetime as the struct variable to which it"); Log.Comment("belongs. In other words, when a variable of a "); Log.Comment("struct type comes into existence or ceases to "); Log.Comment("exist, so do the instance variables of the struct."); if (Categories_TestClass_inst053.testMethod()) { return MFTestResults.Pass; } return MFTestResults.Fail; } [TestMethod] public MFTestResults Categories_inst054_Test() { Log.Comment("Section 5.1.2"); Log.Comment("An instance variable of a struct has exactly the"); Log.Comment("same lifetime as the struct variable to which it"); Log.Comment("belongs. In other words, when a variable of a "); Log.Comment("struct type comes into existence or ceases to "); Log.Comment("exist, so do the instance variables of the struct."); if (Categories_TestClass_inst054.testMethod()) { return MFTestResults.Pass; } return MFTestResults.Fail; } //Compiled Test Cases public class Categories_TestClass_static01_1 { public static byte b1 = 1; } public class Categories_TestClass_static01 { public static byte b1 = 2; public static int Main_old() { if (Categories_TestClass_static01_1.b1 != (byte)1) { return 1; } if (Categories_TestClass_static01.b1 != (byte)2) { return 1; } return 0; } public static bool testMethod() { return (Main_old() == 0); } } public class Categories_TestClass_static02_1 { public static char c1 = 'a'; } public class Categories_TestClass_static02 { public static char c1 = 'b'; public static int Main_old() { if (Categories_TestClass_static02_1.c1 != 'a') { return 1; } if (Categories_TestClass_static02.c1 != 'b') { return 1; } return 0; } public static bool testMethod() { return (Main_old() == 0); } } public class Categories_TestClass_static03_1 { public static short s1 = 1; } public class Categories_TestClass_static03 { public static short s1 = 2; public static int Main_old() { if (Categories_TestClass_static03_1.s1 != (short)1) { return 1; } if (Categories_TestClass_static03.s1 != (short)2) { return 1; } return 0; } public static bool testMethod() { return (Main_old() == 0); } } public class Categories_TestClass_static04_1 { public static int i1 = 1; } public class Categories_TestClass_static04 { public static int i1 = 2; public static int Main_old() { if (Categories_TestClass_static04_1.i1 != 1) { return 1; } if (Categories_TestClass_static04.i1 != 2) { return 1; } return 0; } public static bool testMethod() { return (Main_old() == 0); } } public class Categories_TestClass_static05_1 { public static long l1 = 1L; } public class Categories_TestClass_static05 { public static long l1 = 2L; public static int Main_old() { if (Categories_TestClass_static05_1.l1 != 1L) { return 1; } if (Categories_TestClass_static05.l1 != 2L) { return 1; } return 0; } public static bool testMethod() { return (Main_old() == 0); } } public class Categories_TestClass_static06_1 { public static float f1 = 1f; } public class Categories_TestClass_static06 { public static float f1 = 2f; public static int Main_old() { if (Categories_TestClass_static06_1.f1 != 1f) { return 1; } if (Categories_TestClass_static06.f1 != 2f) { return 1; } return 0; } public static bool testMethod() { return (Main_old() == 0); } } public class Categories_TestClass_static07_1 { public static double d1 = 1d; } public class Categories_TestClass_static07 { public static double d1 = 2d; public static int Main_old() { if (Categories_TestClass_static07_1.d1 != 1d) { return 1; } if (Categories_TestClass_static07.d1 != 2d) { return 1; } return 0; } public static bool testMethod() { return (Main_old() == 0); } } public class Categories_TestClass_static09_1 { public static bool b1 = true; } public class Categories_TestClass_static09 { public static bool b1 = false; public static int Main_old() { if (Categories_TestClass_static09_1.b1 != true) { return 1; } if (Categories_TestClass_static09.b1 != false) { return 1; } return 0; } public static bool testMethod() { return (Main_old() == 0); } } public class Categories_TestClass_static11_1 { public static string s1 = "string1"; } public class Categories_TestClass_static11 { public static string s1 = "string2"; public static int Main_old() { if (Categories_TestClass_static11_1.s1.Equals("string1") != true) { return 1; } if (Categories_TestClass_static11.s1.Equals("string2") != true) { return 1; } return 0; } public static bool testMethod() { return (Main_old() == 0); } } public struct Categories_TestClass_static12_Str { public Categories_TestClass_static12_Str(int intJ) { intI = intJ; } public int intI; } public class Categories_TestClass_static12_1 { public static Categories_TestClass_static12_Str s1 = new Categories_TestClass_static12_Str(1); } public class Categories_TestClass_static12 { public static Categories_TestClass_static12_Str s1 = new Categories_TestClass_static12_Str(2); public static int Main_old() { if (Categories_TestClass_static12_1.s1.intI != 1) { return 1; } if (Categories_TestClass_static12.s1.intI != 2) { return 1; } return 0; } public static bool testMethod() { return (Main_old() == 0); } } public enum Categories_TestClass_static13_En { a = 1, b = 2 } public class Categories_TestClass_static13_1 { public static Categories_TestClass_static13_En E = Categories_TestClass_static13_En.a; } public class Categories_TestClass_static13 { public static Categories_TestClass_static13_En E = Categories_TestClass_static13_En.b; public static int Main_old() { if (Categories_TestClass_static13_1.E != Categories_TestClass_static13_En.a) { return 1; } if (Categories_TestClass_static13.E != Categories_TestClass_static13_En.b) { return 1; } return 0; } public static bool testMethod() { return (Main_old() == 0); } } public class Categories_TestClass_static14_C { public Categories_TestClass_static14_C(int intJ) { intI = intJ; } public int intI; } public class Categories_TestClass_static14_1 { public static Categories_TestClass_static14_C c1 = new Categories_TestClass_static14_C(1); } public class Categories_TestClass_static14 { public static Categories_TestClass_static14_C c1 = new Categories_TestClass_static14_C(2); public static int Main_old() { if (Categories_TestClass_static14_1.c1.intI != 1) { return 1; } if (Categories_TestClass_static14.c1.intI != 2) { return 1; } return 0; } public static bool testMethod() { return (Main_old() == 0); } } public interface Categories_TestClass_static15_Inter { int intRet(); } public class Categories_TestClass_static15_2 : Categories_TestClass_static15_Inter { public Categories_TestClass_static15_2(int intJ) { intI = intJ; } public int intI; public int intRet() { return intI; } } public class Categories_TestClass_static15_1 { public static Categories_TestClass_static15_Inter i1 = (Categories_TestClass_static15_Inter)new Categories_TestClass_static15_2(1); } public class Categories_TestClass_static15 { public static Categories_TestClass_static15_Inter i1 = (Categories_TestClass_static15_Inter)new Categories_TestClass_static15_2(2); public static int Main_old() { if (Categories_TestClass_static15_1.i1.intRet() != 1) { return 1; } if (Categories_TestClass_static15.i1.intRet() != 2) { return 1; } return 0; } public static bool testMethod() { return (Main_old() == 0); } } public class Categories_TestClass_static16_1 { public static int[] i = new int[] { 1 }; } public class Categories_TestClass_static16 { public static int[] i = new int[] { 2 }; public static int Main_old() { if (Categories_TestClass_static16_1.i[0] != 1) { return 1; } if (Categories_TestClass_static16.i[0] != 2) { return 1; } return 0; } public static bool testMethod() { return (Main_old() == 0); } } public delegate int Categories_TestClass_static17_Del(); public class Categories_TestClass_static17_1 { public static int RetInt() { return 1; } public static Categories_TestClass_static17_Del d = new Categories_TestClass_static17_Del(RetInt); } public class Categories_TestClass_static17 { public static int RetInt() { return 2; } public static Categories_TestClass_static17_Del d = new Categories_TestClass_static17_Del(RetInt); public static int Main_old() { if (Categories_TestClass_static17_1.d() != 1) { return 1; } if (Categories_TestClass_static17.d() != 2) { return 1; } return 0; } public static bool testMethod() { return (Main_old() == 0); } } public class Categories_TestClass_static18 { public static byte b1; public static char c1; public static short s1; public static int i1; public static long l1; public static float f1; public static double d1; public static bool b2; public static int Main_old() { if (Categories_TestClass_static18.b1 != (byte)0) { return 1; } if (Categories_TestClass_static18.c1 != '\x0000') { return 2; } if (Categories_TestClass_static18.s1 != (short)0) { return 3; } if (Categories_TestClass_static18.i1 != 0) { return 4; } if (Categories_TestClass_static18.l1 != 0L) { return 5; } if (Categories_TestClass_static18.f1 != 0f) { return 6; } if (Categories_TestClass_static18.d1 != 0d) { return 7; } if (Categories_TestClass_static18.b2 != false) { return 8; } return 0; } public static bool testMethod() { int ret = 0; if ((ret = Main_old()) != 0) { Log.Comment("f1=" + f1.ToString() + " 0f=" + (0f).ToString()); Log.Comment(ret.ToString()); return false; } else return true; } } public enum Categories_TestClass_static19_En { a = 1 } public struct Categories_TestClass_static19_Str { public byte b1; public char c1; public short s1; public int i1; public long l1; public float f1; public double d1; public bool b2; } public class Categories_TestClass_static19 { static Categories_TestClass_static19_Str MS; static Categories_TestClass_static19_En ME; public static int Main_old() { if (MS.b1 != (byte)0) { return 1; } if (MS.c1 != '\x0000') { return 1; } if (MS.s1 != (short)0) { return 1; } if (MS.i1 != 0) { return 1; } if (MS.l1 != 0L) { return 1; } if (MS.f1 != 0f) { return 1; } if (MS.d1 != 0d) { return 1; } if (MS.b2 != false) { return 1; } if (ME != (Categories_TestClass_static19_En)0) { return 1; } return 0; } public static bool testMethod() { return (Main_old() == 0); } } public interface Categories_TestClass_static20_Inter { } public class Categories_TestClass_static20_1 { } public delegate int Categories_TestClass_static20_Del(); public class Categories_TestClass_static20 { public static string MS;//string public static Categories_TestClass_static20_Inter MI;//interface public static Categories_TestClass_static20 MC;//class public static int[] MA;//array public static Categories_TestClass_static20_Del MD;//delegate public static int Main_old() { if (Categories_TestClass_static20.MS != null) { return 1; } if (Categories_TestClass_static20.MI != null) { return 1; } if (Categories_TestClass_static20.MC != null) { return 1; } if (Categories_TestClass_static20.MA != null) { return 1; } if (Categories_TestClass_static20.MD != null) { return 1; } return 0; } public static bool testMethod() { return (Main_old() == 0); } } /* public class Categories_TestClass_static21 { const string s = null; public static int Main_old() { if (s == null) { return 0; } else { return 1; } } public static bool testMethod() { return (Main_old() == 0); } } */ public class Categories_TestClass_inst018_1 { public byte b1 = 1; } public class Categories_TestClass_inst018 { public byte b1 = 2; public static int Main_old() { Categories_TestClass_inst018_1 Test1 = new Categories_TestClass_inst018_1(); Categories_TestClass_inst018 Test2 = new Categories_TestClass_inst018(); if (Test1.b1 != (byte)1) { return 1; } if (Test2.b1 != (byte)2) { return 1; } return 0; } public static bool testMethod() { return (Main_old() == 0); } } public class Categories_TestClass_inst019_1 { public char c1 = 'a'; } public class Categories_TestClass_inst019 { public char c1 = 'b'; public static int Main_old() { Categories_TestClass_inst019_1 Test1 = new Categories_TestClass_inst019_1(); Categories_TestClass_inst019 Test2 = new Categories_TestClass_inst019(); if (Test1.c1 != 'a') { return 1; } if (Test2.c1 != 'b') { return 1; } return 0; } public static bool testMethod() { return (Main_old() == 0); } } public class Categories_TestClass_inst020_1 { public short s1 = 1; } public class Categories_TestClass_inst020 { public short s1 = 2; public static int Main_old() { Categories_TestClass_inst020_1 Test1 = new Categories_TestClass_inst020_1(); Categories_TestClass_inst020 Test2 = new Categories_TestClass_inst020(); if (Test1.s1 != (short)1) { return 1; } if (Test2.s1 != (short)2) { return 1; } return 0; } public static bool testMethod() { return (Main_old() == 0); } } public class Categories_TestClass_inst021_1 { public int i1 = 1; } public class Categories_TestClass_inst021 { public int i1 = 2; public static int Main_old() { Categories_TestClass_inst021_1 Test1 = new Categories_TestClass_inst021_1(); Categories_TestClass_inst021 Test2 = new Categories_TestClass_inst021(); if (Test1.i1 != 1) { return 1; } if (Test2.i1 != 2) { return 1; } return 0; } public static bool testMethod() { return (Main_old() == 0); } } public class Categories_TestClass_inst022_1 { public long l1 = 1L; } public class Categories_TestClass_inst022 { public long l1 = 2L; public static int Main_old() { Categories_TestClass_inst022_1 Test1 = new Categories_TestClass_inst022_1(); Categories_TestClass_inst022 Test2 = new Categories_TestClass_inst022(); if (Test1.l1 != 1L) { return 1; } if (Test2.l1 != 2L) { return 1; } return 0; } public static bool testMethod() { return (Main_old() == 0); } } public class Categories_TestClass_inst023_1 { public float f1 = 1f; } public class Categories_TestClass_inst023 { public float f1 = 2f; public static int Main_old() { Categories_TestClass_inst023_1 Test1 = new Categories_TestClass_inst023_1(); Categories_TestClass_inst023 Test2 = new Categories_TestClass_inst023(); if (Test1.f1 != 1f) { return 1; } if (Test2.f1 != 2f) { return 1; } return 0; } public static bool testMethod() { return (Main_old() == 0); } } public class Categories_TestClass_inst024_1 { public double d1 = 1d; } public class Categories_TestClass_inst024 { public double d1 = 2d; public static int Main_old() { Categories_TestClass_inst024_1 Test1 = new Categories_TestClass_inst024_1(); Categories_TestClass_inst024 Test2 = new Categories_TestClass_inst024(); if (Test1.d1 != 1d) { return 1; } if (Test2.d1 != 2d) { return 1; } return 0; } public static bool testMethod() { return (Main_old() == 0); } } public class Categories_TestClass_inst026_1 { public bool b1 = true; } public class Categories_TestClass_inst026 { public bool b1 = false; public static int Main_old() { Categories_TestClass_inst026_1 Test1 = new Categories_TestClass_inst026_1(); Categories_TestClass_inst026 Test2 = new Categories_TestClass_inst026(); if (Test1.b1 != true) { return 1; } if (Test2.b1 != false) { return 1; } return 0; } public static bool testMethod() { return (Main_old() == 0); } } public class Categories_TestClass_inst028_1 { public string s1 = "string1"; } public class Categories_TestClass_inst028 { public string s1 = "string2"; public static int Main_old() { Categories_TestClass_inst028_1 Test1 = new Categories_TestClass_inst028_1(); Categories_TestClass_inst028 Test2 = new Categories_TestClass_inst028(); if (Test1.s1.Equals("string1") != true) { return 1; } if (Test2.s1.Equals("string2") != true) { return 1; } return 0; } public static bool testMethod() { return (Main_old() == 0); } } public struct Categories_TestClass_inst029_Str { public Categories_TestClass_inst029_Str(int intJ) { intI = intJ; } public int intI; } public class Categories_TestClass_inst029_1 { public Categories_TestClass_inst029_Str s1 = new Categories_TestClass_inst029_Str(1); } public class Categories_TestClass_inst029 { public Categories_TestClass_inst029_Str s1 = new Categories_TestClass_inst029_Str(2); public static int Main_old() { Categories_TestClass_inst029_1 Test1 = new Categories_TestClass_inst029_1(); Categories_TestClass_inst029 Test2 = new Categories_TestClass_inst029(); if (Test1.s1.intI != 1) { return 1; } if (Test2.s1.intI != 2) { return 1; } return 0; } public static bool testMethod() { return (Main_old() == 0); } } public enum Categories_TestClass_inst030_En { a = 1, b = 2 } public class Categories_TestClass_inst030_1 { public Categories_TestClass_inst030_En E = Categories_TestClass_inst030_En.a; } public class Categories_TestClass_inst030 { public Categories_TestClass_inst030_En E = Categories_TestClass_inst030_En.b; public static int Main_old() { Categories_TestClass_inst030_1 Test1 = new Categories_TestClass_inst030_1(); Categories_TestClass_inst030 Test2 = new Categories_TestClass_inst030(); if (Test1.E != Categories_TestClass_inst030_En.a) { return 1; } if (Test2.E != Categories_TestClass_inst030_En.b) { return 1; } return 0; } public static bool testMethod() { return (Main_old() == 0); } } public class Categories_TestClass_inst031_2 { public Categories_TestClass_inst031_2(int intJ) { intI = intJ; } public int intI; } public class Categories_TestClass_inst031_1 { public Categories_TestClass_inst031_2 c1 = new Categories_TestClass_inst031_2(1); } public class Categories_TestClass_inst031 { public Categories_TestClass_inst031_2 c1 = new Categories_TestClass_inst031_2(2); public static int Main_old() { Categories_TestClass_inst031_1 Test1 = new Categories_TestClass_inst031_1(); Categories_TestClass_inst031 Test2 = new Categories_TestClass_inst031(); if (Test1.c1.intI != 1) { return 1; } if (Test2.c1.intI != 2) { return 1; } return 0; } public static bool testMethod() { return (Main_old() == 0); } } public interface Categories_TestClass_inst032_Inter { int intRet(); } public class Categories_TestClass_inst032_2 : Categories_TestClass_inst032_Inter { public Categories_TestClass_inst032_2(int intJ) { intI = intJ; } public int intI; public int intRet() { return intI; } } public class Categories_TestClass_inst032_1 { public Categories_TestClass_inst032_Inter i1 = (Categories_TestClass_inst032_Inter)new Categories_TestClass_inst032_2(1); } public class Categories_TestClass_inst032 { public Categories_TestClass_inst032_Inter i1 = (Categories_TestClass_inst032_Inter)new Categories_TestClass_inst032_2(2); public static int Main_old() { Categories_TestClass_inst032_1 Test1 = new Categories_TestClass_inst032_1(); Categories_TestClass_inst032 Test2 = new Categories_TestClass_inst032(); if (Test1.i1.intRet() != 1) { return 1; } if (Test2.i1.intRet() != 2) { return 1; } return 0; } public static bool testMethod() { return (Main_old() == 0); } } public class Categories_TestClass_inst033_1 { public int[] i = new int[] { 1 }; } public class Categories_TestClass_inst033 { public int[] i = new int[] { 2 }; public static int Main_old() { Categories_TestClass_inst033_1 Test1 = new Categories_TestClass_inst033_1(); Categories_TestClass_inst033 Test2 = new Categories_TestClass_inst033(); if (Test1.i[0] != 1) { return 1; } if (Test2.i[0] != 2) { return 1; } return 0; } public static bool testMethod() { return (Main_old() == 0); } } public delegate int Categories_TestClass_inst034_Del(); public class Categories_TestClass_inst034_1 { public static int RetInt() { return 1; } public Categories_TestClass_inst034_Del d = new Categories_TestClass_inst034_Del(RetInt); } public class Categories_TestClass_inst034 { public static int RetInt() { return 2; } public Categories_TestClass_inst034_Del d = new Categories_TestClass_inst034_Del(RetInt); public static int Main_old() { Categories_TestClass_inst034_1 Test1 = new Categories_TestClass_inst034_1(); Categories_TestClass_inst034 Test2 = new Categories_TestClass_inst034(); if (Test1.d() != 1) { return 1; } if (Test2.d() != 2) { return 1; } return 0; } public static bool testMethod() { return (Main_old() == 0); } } public class Categories_TestClass_inst035 { public byte b1; public char c1; public short s1; public int i1; public long l1; public float f1; public double d1; //public double m1; public bool b2; public static int Main_old() { Categories_TestClass_inst035 Test = new Categories_TestClass_inst035(); if (Test.b1 != (byte)0) { return 1; } if (Test.c1 != '\x0000') { return 1; } if (Test.s1 != (short)0) { return 1; } if (Test.i1 != 0) { return 1; } if (Test.l1 != 0L) { return 1; } if (Test.f1 != 0f) { return 1; } if (Test.d1 != 0d) { return 1; } if (Test.b2 != false) { return 1; } return 0; } public static bool testMethod() { return (Main_old() == 0); } } public interface Categories_TestClass_inst036_Inter { } public class Categories_TestClass_inst036_2 { } public delegate int Categories_TestClass_inst036_Del(); public class Categories_TestClass_inst036 { public string MS;//string public Categories_TestClass_inst036_Inter MI;//interface public Categories_TestClass_inst036 MC;//class public int[] MA;//array public Categories_TestClass_inst036_Del MD;//delegate public static int Main_old() { Categories_TestClass_inst036 Test = new Categories_TestClass_inst036(); if (Test.MS != null) { return 1; } if (Test.MI != null) { return 1; } if (Test.MC != null) { return 1; } if (Test.MA != null) { return 1; } if (Test.MD != null) { return 1; } return 0; } public static bool testMethod() { return (Main_old() == 0); } } public enum Categories_TestClass_inst037_En { a = 1 } public struct Categories_TestClass_inst037_Str { public byte b1; public char c1; public short s1; public int i1; public long l1; public float f1; public double d1; public bool b2; } public class Categories_TestClass_inst037 { Categories_TestClass_inst037_Str MS; Categories_TestClass_inst037_En ME; public static int Main_old() { Categories_TestClass_inst037 Test = new Categories_TestClass_inst037(); if (Test.MS.b1 != (byte)0) { return 1; } if (Test.MS.c1 != '\x0000') { return 1; } if (Test.MS.s1 != (short)0) { return 1; } if (Test.MS.i1 != 0) { return 1; } if (Test.MS.l1 != 0L) { return 1; } if (Test.MS.f1 != 0f) { return 1; } if (Test.MS.d1 != 0d) { return 1; } if (Test.MS.b2 != false) { return 1; } if (Test.ME != (Categories_TestClass_inst037_En)0) { return 1; } return 0; } public static bool testMethod() { return (Main_old() == 0); } } public struct Categories_TestClass_inst038_Str1 { public Categories_TestClass_inst038_Str1(byte b2) { b1 = b2; } public byte b1; } public struct Categories_TestClass_inst038 { public Categories_TestClass_inst038(byte b2) { b1 = b2; } public byte b1; public static int Main_old() { Categories_TestClass_inst038_Str1 Test1 = new Categories_TestClass_inst038_Str1((byte)1); Categories_TestClass_inst038 Test2 = new Categories_TestClass_inst038((byte)2); if (Test1.b1 != (byte)1) { return 1; } if (Test2.b1 != (byte)2) { return 1; } return 0; } public static bool testMethod() { return (Main_old() == 0); } } public struct Categories_TestClass_inst039_Str1 { public Categories_TestClass_inst039_Str1(char c2) { c1 = c2; } public char c1; } public struct Categories_TestClass_inst039 { public Categories_TestClass_inst039(char c2) { c1 = c2; } public char c1; public static int Main_old() { Categories_TestClass_inst039_Str1 Test1 = new Categories_TestClass_inst039_Str1('a'); Categories_TestClass_inst039 Test2 = new Categories_TestClass_inst039('b'); if (Test1.c1 != 'a') { return 1; } if (Test2.c1 != 'b') { return 1; } return 0; } public static bool testMethod() { return (Main_old() == 0); } } public struct Categories_TestClass_inst040_Str1 { public Categories_TestClass_inst040_Str1(short s2) { s1 = s2; } public short s1; } public struct Categories_TestClass_inst040 { public Categories_TestClass_inst040(short s2) { s1 = s2; } public short s1; public static int Main_old() { Categories_TestClass_inst040_Str1 Test1 = new Categories_TestClass_inst040_Str1((short)1); Categories_TestClass_inst040 Test2 = new Categories_TestClass_inst040((short)2); if (Test1.s1 != (short)1) { return 1; } if (Test2.s1 != (short)2) { return 1; } return 0; } public static bool testMethod() { return (Main_old() == 0); } } public struct Categories_TestClass_inst041_Str1 { public Categories_TestClass_inst041_Str1(int i2) { i1 = i2; } public int i1; } public struct Categories_TestClass_inst041 { public Categories_TestClass_inst041(int i2) { i1 = i2; } public int i1; public static int Main_old() { Categories_TestClass_inst041_Str1 Test1 = new Categories_TestClass_inst041_Str1(1); Categories_TestClass_inst041 Test2 = new Categories_TestClass_inst041(2); if (Test1.i1 != 1) { return 1; } if (Test2.i1 != 2) { return 1; } return 0; } public static bool testMethod() { return (Main_old() == 0); } } public struct Categories_TestClass_inst042_Str1 { public Categories_TestClass_inst042_Str1(long l2) { l1 = l2; } public long l1; } public struct Categories_TestClass_inst042 { public Categories_TestClass_inst042(long l2) { l1 = l2; } public long l1; public static int Main_old() { Categories_TestClass_inst042_Str1 Test1 = new Categories_TestClass_inst042_Str1(1L); Categories_TestClass_inst042 Test2 = new Categories_TestClass_inst042(2L); if (Test1.l1 != 1L) { return 1; } if (Test2.l1 != 2L) { return 1; } return 0; } public static bool testMethod() { return (Main_old() == 0); } } public struct Categories_TestClass_inst043_Str1 { public Categories_TestClass_inst043_Str1(float f2) { f1 = f2; } public float f1; } public struct Categories_TestClass_inst043 { public Categories_TestClass_inst043(float f2) { f1 = f2; } public float f1; public static int Main_old() { Categories_TestClass_inst043_Str1 Test1 = new Categories_TestClass_inst043_Str1(1f); Categories_TestClass_inst043 Test2 = new Categories_TestClass_inst043(2f); if (Test1.f1 != 1f) { return 1; } if (Test2.f1 != 2f) { return 1; } return 0; } public static bool testMethod() { return (Main_old() == 0); } } public struct Categories_TestClass_inst044_Str1 { public Categories_TestClass_inst044_Str1(double d2) { d1 = d2; } public double d1; } public struct Categories_TestClass_inst044 { public Categories_TestClass_inst044(double d2) { d1 = d2; } public double d1; public static int Main_old() { Categories_TestClass_inst044_Str1 Test1 = new Categories_TestClass_inst044_Str1(1d); Categories_TestClass_inst044 Test2 = new Categories_TestClass_inst044(2d); if (Test1.d1 != 1d) { return 1; } if (Test2.d1 != 2d) { return 1; } return 0; } public static bool testMethod() { return (Main_old() == 0); } } public struct Categories_TestClass_inst046_Str1 { public Categories_TestClass_inst046_Str1(bool b2) { b1 = b2; } public bool b1; } public struct Categories_TestClass_inst046 { public Categories_TestClass_inst046(bool b2) { b1 = b2; } public bool b1; public static int Main_old() { Categories_TestClass_inst046_Str1 Test1 = new Categories_TestClass_inst046_Str1(true); Categories_TestClass_inst046 Test2 = new Categories_TestClass_inst046(false); if (Test1.b1 != true) { return 1; } if (Test2.b1 != false) { return 1; } return 0; } public static bool testMethod() { return (Main_old() == 0); } } public struct Categories_TestClass_inst048_Str1 { public Categories_TestClass_inst048_Str1(string s2) { s1 = s2; } public string s1; } public struct Categories_TestClass_inst048 { public Categories_TestClass_inst048(string s2) { s1 = s2; } public string s1; public static int Main_old() { Categories_TestClass_inst048_Str1 Test1 = new Categories_TestClass_inst048_Str1("string1"); Categories_TestClass_inst048 Test2 = new Categories_TestClass_inst048("string2"); if (Test1.s1.Equals("string1") != true) { return 1; } if (Test2.s1.Equals("string2") != true) { return 1; } return 0; } public static bool testMethod() { return (Main_old() == 0); } } public struct Categories_TestClass_inst049_Str { public Categories_TestClass_inst049_Str(int intJ) { intI = intJ; } public int intI; } public struct Categories_TestClass_inst049_Str1 { public Categories_TestClass_inst049_Str1(int intI) { s1 = new Categories_TestClass_inst049_Str(1); } public Categories_TestClass_inst049_Str s1; } public struct Categories_TestClass_inst049 { public Categories_TestClass_inst049(int intI) { s1 = new Categories_TestClass_inst049_Str(2); } public Categories_TestClass_inst049_Str s1; public static int Main_old() { Categories_TestClass_inst049_Str1 Test1 = new Categories_TestClass_inst049_Str1(0); Categories_TestClass_inst049 Test2 = new Categories_TestClass_inst049(0); if (Test1.s1.intI != 1) { return 1; } if (Test2.s1.intI != 2) { return 1; } return 0; } public static bool testMethod() { return (Main_old() == 0); } } public enum Categories_TestClass_inst050_En { a = 1, b = 2 } public struct Categories_TestClass_inst050_Str1 { public Categories_TestClass_inst050_Str1(int intI) { E = Categories_TestClass_inst050_En.a; } public Categories_TestClass_inst050_En E; } public struct Categories_TestClass_inst050 { public Categories_TestClass_inst050(int intI) { E = Categories_TestClass_inst050_En.b; } public Categories_TestClass_inst050_En E; public static int Main_old() { Categories_TestClass_inst050_Str1 Test1 = new Categories_TestClass_inst050_Str1(0); Categories_TestClass_inst050 Test2 = new Categories_TestClass_inst050(0); if (Test1.E != Categories_TestClass_inst050_En.a) { return 1; } if (Test2.E != Categories_TestClass_inst050_En.b) { return 1; } return 0; } public static bool testMethod() { return (Main_old() == 0); } } public class Categories_TestClass_inst051_C { public Categories_TestClass_inst051_C(int intJ) { intI = intJ; } public int intI; } public struct Categories_TestClass_inst051_Str1 { public Categories_TestClass_inst051_Str1(int intI) { c1 = new Categories_TestClass_inst051_C(1); } public Categories_TestClass_inst051_C c1; } public struct Categories_TestClass_inst051 { public Categories_TestClass_inst051(int intI) { c1 = new Categories_TestClass_inst051_C(2); } public Categories_TestClass_inst051_C c1; public static int Main_old() { Categories_TestClass_inst051_Str1 Test1 = new Categories_TestClass_inst051_Str1(0); Categories_TestClass_inst051 Test2 = new Categories_TestClass_inst051(0); if (Test1.c1.intI != 1) { return 1; } if (Test2.c1.intI != 2) { return 1; } return 0; } public static bool testMethod() { return (Main_old() == 0); } } public interface Categories_TestClass_inst052_Inter { int intRet(); } public class Categories_TestClass_inst052_C : Categories_TestClass_inst052_Inter { public Categories_TestClass_inst052_C(int intJ) { intI = intJ; } public int intI; public int intRet() { return intI; } } public struct Categories_TestClass_inst052_Str1 { public Categories_TestClass_inst052_Str1(int intI) { i1 = (Categories_TestClass_inst052_Inter)new Categories_TestClass_inst052_C(1); } public Categories_TestClass_inst052_Inter i1; } public struct Categories_TestClass_inst052 { public Categories_TestClass_inst052(int intI) { i1 = (Categories_TestClass_inst052_Inter)new Categories_TestClass_inst052_C(2); } public Categories_TestClass_inst052_Inter i1; public static int Main_old() { Categories_TestClass_inst052_Str1 Test1 = new Categories_TestClass_inst052_Str1(0); Categories_TestClass_inst052 Test2 = new Categories_TestClass_inst052(0); if (Test1.i1.intRet() != 1) { return 1; } if (Test2.i1.intRet() != 2) { return 1; } return 0; } public static bool testMethod() { return (Main_old() == 0); } } public struct Categories_TestClass_inst053_Str1 { public Categories_TestClass_inst053_Str1(int intI) { i = new int[] { 1 }; } public int[] i; } public struct Categories_TestClass_inst053 { public Categories_TestClass_inst053(int intI) { i = new int[] { 2 }; } public int[] i; public static int Main_old() { Categories_TestClass_inst053_Str1 Test1 = new Categories_TestClass_inst053_Str1(0); Categories_TestClass_inst053 Test2 = new Categories_TestClass_inst053(0); if (Test1.i[0] != 1) { return 1; } if (Test2.i[0] != 2) { return 1; } return 0; } public static bool testMethod() { return (Main_old() == 0); } } public delegate int Categories_TestClass_inst054_Del(); public struct Categories_TestClass_inst054_Str1 { public Categories_TestClass_inst054_Str1(int intI) { d = new Categories_TestClass_inst054_Del(RetInt); } public Categories_TestClass_inst054_Del d; public static int RetInt() { return 1; } } public struct Categories_TestClass_inst054 { public Categories_TestClass_inst054(int intI) { d = new Categories_TestClass_inst054_Del(RetInt); } public Categories_TestClass_inst054_Del d; public static int RetInt() { return 2; } public static int Main_old() { Categories_TestClass_inst054_Str1 Test1 = new Categories_TestClass_inst054_Str1(0); Categories_TestClass_inst054 Test2 = new Categories_TestClass_inst054(0); if (Test1.d() != 1) { return 1; } if (Test2.d() != 2) { return 1; } return 0; } public static bool testMethod() { return (Main_old() == 0); } } } } ================================================ FILE: Zelig/Zelig/Test/RunTime/NETMF/mscorlib/variables/VariablesTests.cs ================================================ //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // Copyright (c) Microsoft Corporation. All rights reserved. //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// using System; using System.Reflection; using Microsoft.SPOT.Platform.Test; namespace Microsoft.SPOT.Platform.Tests { public class VariablesTests : IMFTestInterface { [SetUp] public InitializeResult Initialize() { Log.Comment("Adding set up for the tests"); return InitializeResult.ReadyToGo; } [TearDown] public void CleanUp() { Log.Comment("Cleaning up after the tests"); } //Variables Test methods //The following tests were ported from folder current\test\cases\client\CLR\Conformance\10_classes\Variables //S5_range_byte_0.cs,S5_range_byte_1.cs,S5_range_char_0.cs,S5_range_char_1.cs,S5_range_double_0.cs,S5_range_double_1.cs,S5_range_float_0.cs,S5_range_float_1.cs,S5_range_int_0.cs,S5_range_int_1.cs,S5_range_int_3.cs,S5_range_long_0.cs,S5_range_long_1.cs,S5_range_long_3.cs,S5_range_short_0.cs,S5_range_short_1.cs //Test Case Calls [TestMethod] public MFTestResults Variables_S5_range_byte_0_Test() { Log.Comment("S5_range_byte_0.sc"); Log.Comment("This is a variable range test:"); Log.Comment("byte"); Log.Comment(" CompilesOK: 1"); Log.Comment(" Value: 255Y"); if (Variables_TestClass_S5_range_byte_0.testMethod()) { return MFTestResults.Pass; } return MFTestResults.Fail; } [TestMethod] public MFTestResults Variables_S5_range_byte_1_Test() { Log.Comment("S5_range_byte_1.sc"); Log.Comment("This is a variable range test:"); Log.Comment("byte"); Log.Comment(" CompilesOK: 1"); Log.Comment(" Value: 0Y"); if (Variables_TestClass_S5_range_byte_1.testMethod()) { return MFTestResults.Pass; } return MFTestResults.Fail; } [TestMethod] public MFTestResults Variables_S5_range_char_0_Test() { Log.Comment("S5_range_char_0.sc"); Log.Comment("This is a variable range test:"); Log.Comment("char"); Log.Comment(" CompilesOK: 1"); Log.Comment(" Value: 65535"); if (Variables_TestClass_S5_range_char_0.testMethod()) { return MFTestResults.Pass; } return MFTestResults.Fail; } [TestMethod] public MFTestResults Variables_S5_range_char_1_Test() { Log.Comment("S5_range_char_1.sc"); Log.Comment("This is a variable range test:"); Log.Comment("char"); Log.Comment(" CompilesOK: 1"); Log.Comment(" Value: 0"); if (Variables_TestClass_S5_range_char_1.testMethod()) { return MFTestResults.Pass; } return MFTestResults.Fail; } [TestMethod] public MFTestResults Variables_S5_range_double_0_Test() { Log.Comment("S5_range_double_0.sc"); Log.Comment("This is a variable range test:"); Log.Comment("double"); Log.Comment(" CompilesOK: 1"); Log.Comment(" Value: 1.7e308d"); if (Variables_TestClass_S5_range_double_0.testMethod()) { return MFTestResults.Pass; } return MFTestResults.Fail; } [TestMethod] public MFTestResults Variables_S5_range_double_1_Test() { Log.Comment("S5_range_double_1.sc"); Log.Comment("This is a variable range test:"); Log.Comment("double"); Log.Comment(" CompilesOK: 1"); Log.Comment(" Value: -1.7e308d"); if (Variables_TestClass_S5_range_double_1.testMethod()) { return MFTestResults.Pass; } return MFTestResults.Fail; } [TestMethod] public MFTestResults Variables_S5_range_float_0_Test() { Log.Comment("S5_range_float_0.sc"); Log.Comment("This is a variable range test:"); Log.Comment("float"); Log.Comment(" CompilesOK: 1"); Log.Comment(" Value: 3.4e38F"); if (Variables_TestClass_S5_range_float_0.testMethod()) { return MFTestResults.Pass; } return MFTestResults.Fail; } [TestMethod] public MFTestResults Variables_S5_range_float_1_Test() { Log.Comment("S5_range_float_1.sc"); Log.Comment("This is a variable range test:"); Log.Comment("float"); Log.Comment(" CompilesOK: 1"); Log.Comment(" Value: -3.4e38F"); if (Variables_TestClass_S5_range_float_1.testMethod()) { return MFTestResults.Pass; } return MFTestResults.Fail; } [TestMethod] public MFTestResults Variables_S5_range_int_0_Test() { Log.Comment("S5_range_int_0.sc"); Log.Comment("This is a variable range test:"); Log.Comment("int"); Log.Comment(" CompilesOK: 1"); Log.Comment(" Value: 2147483647"); if (Variables_TestClass_S5_range_int_0.testMethod()) { return MFTestResults.Pass; } return MFTestResults.Fail; } [TestMethod] public MFTestResults Variables_S5_range_int_1_Test() { Log.Comment("S5_range_int_1.sc"); Log.Comment("This is a variable range test:"); Log.Comment("int"); Log.Comment(" CompilesOK: 1"); Log.Comment(" Value: -2147483647"); if (Variables_TestClass_S5_range_int_1.testMethod()) { return MFTestResults.Pass; } return MFTestResults.Fail; } [TestMethod] public MFTestResults Variables_S5_range_int_3_Test() { Log.Comment("S5_range_int_3.sc"); Log.Comment("This is a variable range test:"); Log.Comment("int"); Log.Comment(" CompilesOK: 0"); Log.Comment(" Value: -2147483648"); if (Variables_TestClass_S5_range_int_3.testMethod()) { return MFTestResults.Pass; } return MFTestResults.Fail; } [TestMethod] public MFTestResults Variables_S5_range_long_0_Test() { Log.Comment("S5_range_long_0.sc"); Log.Comment("This is a variable range test:"); Log.Comment("long"); Log.Comment(" CompilesOK: 1"); Log.Comment(" Value: 9223372036854775807L"); if (Variables_TestClass_S5_range_long_0.testMethod()) { return MFTestResults.Pass; } return MFTestResults.Fail; } [TestMethod] public MFTestResults Variables_S5_range_long_1_Test() { Log.Comment("S5_range_long_1.sc"); Log.Comment("This is a variable range test:"); Log.Comment("long"); Log.Comment(" CompilesOK: 1"); Log.Comment(" Value: -9223372036854775807L"); if (Variables_TestClass_S5_range_long_1.testMethod()) { return MFTestResults.Pass; } return MFTestResults.Fail; } [TestMethod] public MFTestResults Variables_S5_range_long_3_Test() { Log.Comment("S5_range_long_3.sc"); Log.Comment("This is a variable range test:"); Log.Comment("long"); Log.Comment(" CompilesOK: 0"); Log.Comment(" Value: -9223372036854775808L"); if (Variables_TestClass_S5_range_long_3.testMethod()) { return MFTestResults.Pass; } return MFTestResults.Fail; } [TestMethod] public MFTestResults Variables_S5_range_short_0_Test() { Log.Comment("S5_range_short_0.sc"); Log.Comment("This is a variable range test:"); Log.Comment("short"); Log.Comment(" CompilesOK: 1"); Log.Comment(" Value: 32767S"); if (Variables_TestClass_S5_range_short_0.testMethod()) { return MFTestResults.Pass; } return MFTestResults.Fail; } [TestMethod] public MFTestResults Variables_S5_range_short_1_Test() { Log.Comment("S5_range_short_1.sc"); Log.Comment("This is a variable range test:"); Log.Comment("short"); Log.Comment(" CompilesOK: 1"); Log.Comment(" Value: -32767S"); if (Variables_TestClass_S5_range_short_1.testMethod()) { return MFTestResults.Pass; } return MFTestResults.Fail; } public class Variables_TestClass_S5_range_byte_0 { public static void Main_old() { byte var; byte var2; var = 255; var2 = var; return; } public static bool testMethod() { try { Main_old(); } catch { return false; } return true; } } public class Variables_TestClass_S5_range_byte_1 { public static void Main_old() { byte var; byte var2; var = 0; var2 = var; return; } public static bool testMethod() { try { Main_old(); } catch { return false; } return true; } } public class Variables_TestClass_S5_range_char_0 { public static void Main_old() { char var; char var2; var = (char)65535; var2 = var; return; } public static bool testMethod() { try { Main_old(); } catch { return false; } return true; } } public class Variables_TestClass_S5_range_char_1 { public static void Main_old() { char var; char var2; var = (char)0; var2 = var; return; } public static bool testMethod() { try { Main_old(); } catch { return false; } return true; } } public class Variables_TestClass_S5_range_double_0 { public static void Main_old() { double var; double var2; var = 1.7e308d; var2 = var; return; } public static bool testMethod() { try { Main_old(); } catch { return false; } return true; } } public class Variables_TestClass_S5_range_double_1 { public static void Main_old() { double var; double var2; var = -1.7e308d; var2 = var; return; } public static bool testMethod() { try { Main_old(); } catch { return false; } return true; } } public class Variables_TestClass_S5_range_float_0 { public static void Main_old() { float var; float var2; var = 3.4e38F; var2 = var; return; } public static bool testMethod() { try { Main_old(); } catch { return false; } return true; } } public class Variables_TestClass_S5_range_float_1 { public static void Main_old() { float var; float var2; var = -3.4e38F; var2 = var; return; } public static bool testMethod() { try { Main_old(); } catch { return false; } return true; } } public class Variables_TestClass_S5_range_int_0 { public static void Main_old() { int var; int var2; var = 2147483647; var2 = var; return; } public static bool testMethod() { try { Main_old(); } catch { return false; } return true; } } public class Variables_TestClass_S5_range_int_1 { public static void Main_old() { int var; int var2; var = -2147483647; var2 = var; return; } public static bool testMethod() { try { Main_old(); } catch { return false; } return true; } } public class Variables_TestClass_S5_range_int_3 { public static void Main_old() { int var; int var2; var = -2147483648; var2 = var; return; } public static bool testMethod() { try { Main_old(); } catch { return false; } return true; } } public class Variables_TestClass_S5_range_long_0 { public static void Main_old() { long var; long var2; var = 9223372036854775807L; var2 = var; return; } public static bool testMethod() { try { Main_old(); } catch { return false; } return true; } } public class Variables_TestClass_S5_range_long_1 { public static void Main_old() { long var; long var2; var = -9223372036854775807L; var2 = var; return; } public static bool testMethod() { try { Main_old(); } catch { return false; } return true; } } public class Variables_TestClass_S5_range_long_3 { public static void Main_old() { long var; long var2; var = -9223372036854775808L; var2 = var; return; } public static bool testMethod() { try { Main_old(); } catch { return false; } return true; } } public class Variables_TestClass_S5_range_short_0 { public static void Main_old() { short var; short var2; var = 32767; var2 = var; return; } public static bool testMethod() { try { Main_old(); } catch { return false; } return true; } } public class Variables_TestClass_S5_range_short_1 { public static void Main_old() { short var; short var2; var = -32767; var2 = var; return; } public static bool testMethod() { try { Main_old(); } catch { return false; } return true; } } } } ================================================ FILE: Zelig/Zelig/Test/RunTime/mscorlib_UnitTest/Files.Designer.cs ================================================ //------------------------------------------------------------------------------ // // This code was generated by a tool. // Runtime Version:4.0.30319.18444 // // Changes to this file may cause incorrect behavior and will be lost if // the code is regenerated. // //------------------------------------------------------------------------------ namespace mscorlib_UnitTest { using System; /// /// A strongly-typed resource class, for looking up localized strings, etc. /// // This class was auto-generated by the StronglyTypedResourceBuilder // class via a tool like ResGen or Visual Studio. // To add or remove a member, edit your .ResX file then rerun ResGen // with the /str option, or rebuild your VS project. [global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Resources.Tools.StronglyTypedResourceBuilder", "4.0.0.0")] [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] [global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()] internal class Files { private static global::System.Resources.ResourceManager resourceMan; private static global::System.Globalization.CultureInfo resourceCulture; [global::System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")] internal Files() { } /// /// Returns the cached ResourceManager instance used by this class. /// [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)] internal static global::System.Resources.ResourceManager ResourceManager { get { if (object.ReferenceEquals(resourceMan, null)) { global::System.Resources.ResourceManager temp = new global::System.Resources.ResourceManager("mscorlib_UnitTest.Files", typeof(Files).Assembly); resourceMan = temp; } return resourceMan; } } /// /// Overrides the current thread's CurrentUICulture property for all /// resource lookups using this strongly typed resource class. /// [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)] internal static global::System.Globalization.CultureInfo Culture { get { return resourceCulture; } set { resourceCulture = value; } } /// /// Looks up a localized resource of type System.Byte[]. /// internal static byte[] ZeligRefreshBinaryDrop { get { object obj = ResourceManager.GetObject("ZeligRefreshBinaryDrop", resourceCulture); return ((byte[])(obj)); } } } } ================================================ FILE: Zelig/Zelig/Test/RunTime/mscorlib_UnitTest/Files.resx ================================================  text/microsoft-resx 2.0 System.Resources.ResXResourceReader, System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 System.Resources.ResXResourceWriter, System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 Resources\ZeligRefreshBinaryDrop.cmd;System.Byte[], mscorlib, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 ================================================ FILE: Zelig/Zelig/Test/RunTime/mscorlib_UnitTest/Program.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // //#define INCLUDE_BASIC_TESTS //#define INCLUDE_VERIFICATION //#define GC_TEST_MULTIPOINTER_STRUCTS //#define GC_STRESS //#define BITFIELD_TEST namespace mscorlib_UnitTest { using System; using System.Collections.Generic; using System.Runtime.CompilerServices; using RT = Microsoft.Zelig.Runtime; public class Program { #if BITFIELD_TEST public enum EnumBitField { Test1, Test2, Test3, } [RT.MemoryMappedPeripheral(Base=0x08000000U,Length=0x00000020U)] public class BitFieldTest { [RT.BitFieldPeripheral(PhysicalType=typeof(uint))] public struct BitFieldReg { [RT.BitFieldRegister(Position=0,Size= 3)] public uint Field1; [RT.BitFieldRegister(Position=3,Size= 2)] public uint Field2; [RT.BitFieldRegister(Position=5,Size=10)] public EnumBitField Field3; [RT.BitFieldRegister(Position=31,Size=1)] public bool Field4; [RT.BitFieldSplitRegister(Position=16,Size=4,Offset=4)] [RT.BitFieldSplitRegister(Position=20,Size=4,Offset=0)] public int Field5; } [RT.Register(Offset=0)] public BitFieldReg reg1; // // Access Methods // public static extern BitFieldTest Instance { [RT.SingletonFactory()] [MethodImpl( MethodImplOptions.InternalCall )] get; } } static void TestBitField() { BitFieldTest bft = BitFieldTest.Instance; bft.reg1.Field1 = 2; bft.reg1.Field2 += 2; bft.reg1.Field5++; var reg1 = bft.reg1; if(reg1.Field4) { reg1.Field3 = EnumBitField.Test3; } bft.reg1 = reg1; BitFieldTest.BitFieldReg reg2 = new BitFieldTest.BitFieldReg(); reg2.Field1 = 12; reg2.Field2 = 2; reg2.Field5 = -2; bft.reg1 = reg2; } #endif class TestFinalizer { int m_a; public TestFinalizer( int a ) { m_a = a; } ~TestFinalizer() { Console.WriteLine( "{0}", m_a ); } } static void TestFinalizers() { for(int i = 0; i < 10; i++) { var a = new TestFinalizer( i + 100 ); var b = new TestFinalizer( i + 200 ); GC.Collect(); GC.WaitForPendingFinalizers(); } } static void TestSyncBlocks() { for(int i = 0; i < 10; i++) { object obj = new object(); lock(obj) { object obj2 = new object(); lock(obj2) { } GC.Collect(); GC.WaitForPendingFinalizers(); } } } static string TestArrayInitializers() { try { int[] a = new int[] { 1, 2, 3, 4, 5 }; char[] b = new char[] { 'a', 'b', 'c' }; string[] c = new string[] { "a", "b", "c" }; byte[] payload = Files.ZeligRefreshBinaryDrop; object obj = c; ICloneable cld = (ICloneable)obj; object obj2 = cld;//.Clone(); string[] c2 = (string[])obj; Buffer.BlockCopy( a, 0 * sizeof(int), a, 3 * sizeof(int), 2 * sizeof(int) ); Buffer.BlockCopy( a, 1 * sizeof(int), a, 0 * sizeof(int), 2 * sizeof(int) ); ICollection< string > icoll = c; foreach(var s in icoll) { Console.WriteLine( s ); } return c2[0]; } catch(Exception ex) { return ex.Message; } } static int[] TestArrayBoundChecks( int[] a , int c1 , int c2 ) { for(int i = 0; i < a.Length; i++) { if(i < c1 && (i < c2 || i > c2)) { a[i] = 3; } if(i < c1 || (i < c2 && i >= 2)) { a[i] = 4; } a[i] *= 2; } return a; } static void TestArrayBoundChecks() { int[] a = new int[] { 1, 2, 3, 4, 5 }; TestArrayBoundChecks( a, 3, 5 ); } static int TestCheckedOperations( int a , int b , int c ) { byte aB = (byte)a; byte bB = (byte)b; byte cB = (byte)c; byte rB = checked( (byte)(cB + bB + cB) ); return rB; } public abstract class Sub1 { public abstract int Code(); } public class Sub2 : Sub1 { public override int Code() { return 2; } } public class Sub3 : Sub2 { public override int Code() { return 3; } } public class Sub4 : Sub2 { public override int Code() { return 4; } } class DelegateTester { delegate int DelegateTest( int a ); static int StaticDelegateTarget( int a ) { return a * a; } int InstanceDelegateTarget( int a ) { return a * a; } internal virtual int VirtualDelegateTarget( int a ) { return a * a; } internal static void Run() { DelegateTest tst; DelegateTester pThis = new SubDelegateTester(); tst = StaticDelegateTarget ; tst( 2 ); tst = pThis.InstanceDelegateTarget; tst( 2 ); tst = pThis.VirtualDelegateTarget ; tst( 2 ); } } class SubDelegateTester : DelegateTester { internal override int VirtualDelegateTarget( int a ) { return a * a + 5; } } [RT.NoInline] private static float[] TestNumeric( float a , float b , float c ) { float[] res = new float[32]; int i = 0; res[i++] = - b; res[i++] = a + b; res[i++] = a - b; res[i++] = b - a; res[i++] = a + c; res[i++] = a - c; res[i++] = c - a; res[i++] = a * b; res[i++] = a / b; res[i++] = a < b ? 1 : 0; res[i++] = a == b ? 1 : 0; res[i++] = a > b ? 1 : 0; return res; } [RT.NoInline] private static double[] TestNumeric( double a , double b , double c ) { double[] res = new double[32]; int i = 0; res[i++] = - b; res[i++] = a + b; res[i++] = a - b; res[i++] = b - a; res[i++] = a + c; res[i++] = a - c; res[i++] = c - a; res[i++] = a * b; res[i++] = a / b; res[i++] = a < b ? 1 : 0; res[i++] = a == b ? 1 : 0; res[i++] = a > b ? 1 : 0; return res; } //--// private static void TestFloatingPoint() { System.Diagnostics.Stopwatch stopwatch = new System.Diagnostics.Stopwatch(); for(int loop = 0; loop < 32; loop++) { stopwatch.Start(); float[] res1 = TestNumeric( 1.3f, 3.5f, 0f ); float[] res2 = TestNumeric( 1.3f, -3.5f, 0f ); stopwatch.Stop(); long val = stopwatch.ElapsedTicks; stopwatch.Reset(); } for(int loop = 0; loop < 32; loop++) { double[] res1 = TestNumeric( 1.3d, 3.5d, 0d ); double[] res2 = TestNumeric( 1.3d, -3.5d, 0d ); } } private static void TestList() { var lst = new List< int >(); lst.Add( 1 ); lst.Add( 2 ); lst.Add( 3 ); lst.Add( 4 ); lst.Contains( 3 ); lst.Contains( 5 ); var lst2 = new List< string >(); lst2.Add( "test1" ); lst2.Add( "test2" ); lst2.Add( "test3" ); lst2.Add( "test4" ); lst2.Contains( "test3" ); lst2.Contains( "test5" ); } private static int TestDictionary() { var dictInt = new Dictionary< int, int >(); dictInt[1] = 10; dictInt[2] = 20; dictInt[3] = 30; dictInt[4] = 40; int val = dictInt[3]; var dict = new Dictionary< string, int >( StringComparer.Ordinal ); dict["test" ] = 1; dict["test2"] = 2; dict["TEST" ] = 3; dict["TEST2"] = 4; int res = dict["TEST"]; return res; } private static void TestExceptions() { try { try { Debug.Print( "Exception: 1" ); } finally { Debug.Print( "Exception: 2" ); try { Exception e = new Exception( "test" ); throw e; } catch { Debug.Print( "Exception: 2b" ); throw; } finally { Debug.Print( "Exception: 3" ); } } } catch(Exception) { Debug.Print( "Exception: 4" ); } finally { Debug.Print( "Exception: 5" ); } } private static void TestEvents() { System.Threading.AutoResetEvent ev1 = new System.Threading.AutoResetEvent( false ); System.Threading.AutoResetEvent ev2 = new System.Threading.AutoResetEvent( false ); object obj = new object(); int count = 0; System.Threading.Thread thread1 = new System.Threading.Thread( delegate() { for(int i = 0; i < 16; i++) { ev1.WaitOne(); ev2.Set(); lock(obj) { System.Threading.Thread.Sleep( 10 ); count++; } } } ); System.Threading.Thread thread2 = new System.Threading.Thread( delegate() { for(int i = 0; i < 16; i++) { ev2.WaitOne(); ev1.Set(); lock(obj) { System.Threading.Thread.Sleep( 10 ); count++; } } } ); thread1.Start(); thread2.Start(); ev1.Set(); thread1.Join(); thread2.Join(); } private static void TestTime() { DateTime now; int val; now = DateTime.Now; now = DateTime.Now; now = DateTime.Now; val = now.Year; val = now.Month; val = now.Day; val = now.Hour; val = now.Minute; val = now.Second; val = now.Millisecond; //Microsoft.Zelig.Runtime.DateTimeImpl.SetUtcTime( TimeZone.CurrentTimeZone.ToUniversalTime( new DateTime( 2003, 1, 1 ) ) ); now = DateTime.Now; now = DateTime.Now; now = DateTime.Now; val = now.Year; val = now.Month; val = now.Day; val = now.Hour; val = now.Minute; val = now.Second; val = now.Millisecond; } private static void TestTimers() { int count = 0; System.Threading.Timer timer = new System.Threading.Timer( delegate( object state ) { count++; } ); timer.Change( 20, System.Threading.Timeout.Infinite ); System.Threading.Thread.Sleep( 100 ); timer.Change( 20, 1 ); System.Threading.Thread.Sleep( 100 ); timer.Dispose(); System.Threading.Thread.Sleep( 100 ); } private static string[] TestToString() { string[] res = new string[32]; int i = 0; res[i++] = int .MaxValue.ToString(); res[i++] = ((int)0) .ToString(); res[i++] = int .MinValue.ToString(); res[i++] = 123 .ToString( "00000" ); res[i++] = char .MaxValue.ToString(); res[i++] = ((char)0) .ToString(); res[i++] = char .MinValue.ToString(); res[i++] = long .MaxValue.ToString(); res[i++] = ((long)0) .ToString(); res[i++] = long .MinValue.ToString(); res[i++] = 3.14f.ToString(); res[i++] = 10f .ToString(); res[i++] = 0.1f .ToString(); res[i++] = float .MaxValue.ToString(); res[i++] = float .MinValue.ToString(); res[i++] = double.MaxValue.ToString(); res[i++] = double.MinValue.ToString(); System.Text.StringBuilder sb = new System.Text.StringBuilder(); sb.AppendFormat( "Test {0:X8} {2} {1} End", 234, "", -212 ); res[i++] = sb.ToString(); return res; } private static void TestGenericOpenClasses() { var obj = new GenericClassTest(); for(int i = 0; i < 20; i++) { obj.Test1( i, i * 2 ); } } private static int TestMethodInjection() { TargetForInjection obj = new TargetForInjection(); int c = 4; return obj.EmptyMethod( 2, 3, ref c ); } struct TestTrackStack { public object a; public object b; public object c; public object d; } static TestTrackStack Start( object a , object b , object c , object d ) { TestTrackStack st = new TestTrackStack(); st.a = a; st.b = b; st.c = c; st.d = d; return st; } private static void GCStress( ref object p, object s ) { GC.Collect(); p = s; } static unsafe void Main() { #if INCLUDE_VERIFICATION mscorlib_UnitTest.Verification.Verify.RunVerification(); #endif //--// #if GC_TEST_MULTIPOINTER_STRUCTS TestTrackStack st = Start( 1, 2, 3, 4 ); Console.WriteLine( "{0}", st.a ); GC.Collect(); Console.WriteLine( "{0}", st.b ); GC.Collect(); Console.WriteLine( "{0}", st.c ); GC.Collect(); Console.WriteLine( "{0}", st.d ); GC.Collect(); #elif GC_STRESS while(true) { TestFloatingPoint(); object[] array = new object[120]; array[3] = array; GCStress( ref array[5], array ); } #elif BITFIELD_TEST TestTrackStack st = Start( 1, 2, 3, 4 ); st.d = 23; TestBitField(); #else TestFinalizers(); TestSyncBlocks(); TestArrayBoundChecks(); TestCheckedOperations( 2, 3, 4 ); DelegateTester.Run(); TestArrayInitializers(); TestToString(); TestList(); TestDictionary(); TestFloatingPoint(); TestExceptions(); TestEvents(); TestTime(); TestTimers(); TestGenericOpenClasses(); TestMethodInjection(); #endif } } } ================================================ FILE: Zelig/Zelig/Test/RunTime/mscorlib_UnitTest/Properties/AssemblyInfo.cs ================================================ using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; // General Information about an assembly is controlled through the following // set of attributes. Change these attribute values to modify the information // associated with an assembly. [assembly: AssemblyTitle( "mscorlib_UnitTest" )] [assembly: AssemblyDescription( "" )] [assembly: AssemblyConfiguration( "" )] [assembly: AssemblyCompany( "Microsoft" )] [assembly: AssemblyProduct( "mscorlib_UnitTest" )] [assembly: AssemblyCopyright( "Copyright © Microsoft 2006" )] [assembly: AssemblyTrademark( "" )] [assembly: AssemblyCulture( "" )] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. //[assembly: ComVisible( false )] // The following GUID is for the ID of the typelib if this project is exposed to COM //[assembly: Guid( "790c97c2-f14c-473e-a9eb-1b72d95bad30" )] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // [assembly: AssemblyVersion( "1.0.0.0" )] [assembly: AssemblyFileVersion( "1.0.0.0" )] ================================================ FILE: Zelig/Zelig/Test/RunTime/mscorlib_UnitTest/Resources/ZeligRefreshBinaryDrop.cmd ================================================ @echo off setlocal cd/d %SDXROOT%\Zelig if /I "%1" == "full" (set msbuild_opt=/t:Rebuild) msbuild Zelig.sln %msbuild_opt% /p:Configuration=Debug msbuild Zelig.sln %msbuild_opt% /p:Configuration=Release cd %SDXROOT%\Zelig\BinaryDrop sd edit ... rd/s/q %SDXROOT%\Zelig\BinaryDrop md %SDXROOT%\Zelig\BinaryDrop\Host md %SDXROOT%\Zelig\BinaryDrop\Target xcopy/s/e %SDXROOT%\ZeligBuild\Host\bin %SDXROOT%\Zelig\BinaryDrop\Host xcopy/s/e %SDXROOT%\ZeligBuild\Target\bin %SDXROOT%\Zelig\BinaryDrop\Target del/s *.vshost.exe* sd add ... sd online ... sd revert -a ... ================================================ FILE: Zelig/Zelig/Test/RunTime/mscorlib_UnitTest/Test_OpenClasses.cs ================================================ namespace mscorlib_UnitTest { using System; using System.Collections.Generic; using System.Runtime.CompilerServices; using Microsoft.Zelig.Runtime; public class BaseClassToExtend1 { public static int s_b = 1; int m_a; public BaseClassToExtend1( int a ) { m_a = a; } private int Test1( int a ) { return a + 1; } public int Test2( int b ) { return b; } } [ExtendClass(typeof(BaseClassToExtend1))] class ExtensionTest1 { public static int s_c = 3; int m_b; [MergeWithTargetImplementation] public ExtensionTest1( int a ) { m_b = a; } [AliasForBaseMethod( "Test1" )] [MethodImpl( MethodImplOptions.InternalCall )] private extern int BaseTest1( int a ); private int Test1( int a ) { return a + 2; } public int SubTest1( int a ) { return BaseTest1( a + 1 ); } } //--// class TargetForInjection { public int EmptyMethod( int a, int b, ref int c ) { return a + b; } } [ExtendClass(typeof(TargetForInjection), NoConstructors=true)] class SourceForInjection1 { [InjectAtEntryPoint] public void EmptyMethod( int a, int b, ref int c ) { c = a - b; } [InjectAtExitPoint] public int EmptyMethod( int a, int b, ref int c, int res ) { return res * a; } } [ExtendClass(typeof(TargetForInjection), NoConstructors=true, ProcessAfter=typeof(SourceForInjection1))] class SourceForInjection2 { [InjectAtEntryPoint] public void EmptyMethod( int a, int b, ref int c ) { c = c * 2; } [InjectAtExitPoint] public int EmptyMethod( int a, int b, ref int c, int res ) { return res - 10; } } public class BaseGenericClassToExtend< T > { [NoInline] public T Test1( T a , T b ) { return a; } } [ExtendClass(typeof(BaseGenericClassToExtend<>), NoConstructors=true)] class GenericExtensionTest { [NoInline] public T Test1( T a , T b ) { return b; } } public class GenericClassTest : BaseGenericClassToExtend { } } ================================================ FILE: Zelig/Zelig/Test/RunTime/mscorlib_UnitTest/Verify.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // namespace mscorlib_UnitTest { using System; using System.Threading; using System.Collections; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using System.Reflection; public class Debug { [Microsoft.Zelig.Runtime.NoInline] public static void Print( string txt ) { //throw new NotImplementedException(); } public static int AvailableMemory() { return 0;//throw new NotImplementedException(); } } } namespace mscorlib_UnitTest.Verification { using System; using System.Threading; using System.Collections; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using System.Reflection; class Foo { } class Bar { } class TestReferences { void Method1( ref int a ) { a = a + 1; } void Method2( ref object o ) { o = o.GetType(); } void Method3( ref Type t ) { t = t.BaseType; } void Method4( ref DateTime d ) { d = d.Add( new TimeSpan( 1, 2, 3, 4, 5 ) ); } void Tester() { int i = 13; int[] i_a = new int[10]; object o = "Test"; object[] o_a = new object[5]; Type t = this.GetType(); DateTime d = DateTime.Now; Method1( ref i ); Method1( ref i_a[2] ); Method2( ref o ); Method2( ref o_a[3] ); Method3( ref t ); Method4( ref d ); } } public class TestReferences2 { static void Test1( int v ) { Debug.Print( "Test1: " + v + " " + v.GetType().FullName ); } static void Test2( ref int v ) { Debug.Print( "Test2: " + v + " " + v.GetType().FullName ); v++; } static void Test3( Enum v ) { Debug.Print( "Test3: " + v + " " + v.GetType().FullName ); } static void Test4( ref Enum v ) { Debug.Print( "Test4: " + v + " " + v.GetType().FullName ); v = Resources.Tag.TIME; } static void Test5( TestEnum v ) { Debug.Print( "Test5: " + v + " " + v.GetType().FullName ); } static void Test6( ref TestEnum v ) { Debug.Print( "Test6: " + v + " " + v.GetType().FullName ); v++; } static void Test7( DateTime v ) { Debug.Print( "Test7: " + v.ToString() + " " + v.GetType().FullName ); } static void Test8( ref DateTime v ) { Debug.Print( "Test8: " + v.ToString() + " " + v.GetType().FullName ); v += new TimeSpan( 1, 1, 1 ); } static void Test9( object v ) { Debug.Print( "Test9: " + v.ToString() + " " + v.GetType().FullName ); } static void TestA( ref object v ) { Debug.Print( "TestA: " + v.ToString() + " " + v.GetType().FullName ); v = 1; } static public void TestPlain() { int i = 100; TestEnum e = TestEnum.P1; Enum e2 = e; DateTime d = DateTime.Now; Test2( ref i ); Test1( i ); Test4( ref e2 ); Test3( e2 ); Test6( ref e ); Test5( e ); Test8( ref d ); Test7( d ); } static public void TestArray() { int [] i = new int [1]; i [0] = 100; TestEnum[] e = new TestEnum[1]; e [0] = TestEnum.P1; Enum [] e2 = new Enum [1]; e2[0] = e[0]; DateTime[] d = new DateTime[1]; d [0] = DateTime.Now; object [] o = new object [1]; o [0] = 3.0; Test2( ref i [0] ); Test1( i [0] ); Test4( ref e2[0] ); Test3( e2[0] ); Test6( ref e [0] ); Test5( e [0] ); Test8( ref d [0] ); Test7( d [0] ); TestA( ref o [0] ); Test9( o [0] ); } } public class TestSpecialValueTypes { static int DateTimeByRef( ref DateTime dt ) { int res = dt.Month; dt += new TimeSpan( 0, 1, 2 ); Debug.Print( "DateTimeByRef " + dt.ToString() ); return res; } static public void DateTimeUsage() { DateTime dt1; DateTime dt2 = DateTime.Now; int day = dt2.Day; dt1 = dt2; object o = dt1; Debug.Print( "Type " + o.GetType().FullName ); DateTime[] da1 = new DateTime[2]; DateTimeByRef( ref da1[0] ); DateTimeByRef( ref dt1 ); Debug.Print( "DateTimeUsage " + dt1 .ToString() ); Debug.Print( "DateTimeUsage " + da1[0].ToString() ); Debug.Print( "DateTimeUsage " + da1[1].ToString() ); } } // [AttributeUsage(AttributeTargets.All,Inherited=true)] // public class Local2Attribute : Microsoft.SPOT.LocalAttribute // { // public Local2Attribute( string name ) : base(name) // { // this.length = 20; // } // // public Local2Attribute( string name, int length ) : base(name) // { // this.length = length; // } // // public string extra; // } // // [AttributeUsage(AttributeTargets.All,Inherited=true)] // public class Local3Attribute : Attribute // { // public string info; // } // // public enum EnumTester // { // [Microsoft.SPOT.LocalAttribute("name of Value1", active=true , length=32)] Value1 = 12, // [Microsoft.SPOT.LocalAttribute("name of Value2", active=false, length=64)] Value2 = 14, // [Local3 (info="name of Value2" )] Value3 = 15, // } // // [Microsoft.SPOT.Local("name of AttributeTester|name of AttributeTester|name of AttributeTester|name of AttributeTester|name of AttributeTester|name of AttributeTester", active=false)] // public class AttributeTester // { // [Local2("name of Field1", 66, active=true)] // public int Field1; // // [Local2("name of Method1", length=100, target=typeof(Value), extra="we")] // public void Method1( int i ) // { // } // } [StructLayout(LayoutKind.Sequential)] struct Value { public int i1; public int i2; public string s1; public Value( int i ) { i1 = i; i2 = 0; s1 = null; } public int Result() { return i1 + i2; } } enum TestEnum :byte { P1 = 1, P2 = 2, P3 = 3, } enum TestEnum2 :short { S1 = 1, S2 = 2, S3 = 3, } public class Resources { public enum Tag { TIME, } } delegate int Compute( int a, int b, Value v ); delegate void OnKey( int a ); interface Interface { short Method1( int c ); int Method2( int a, int b, Value v ); } //--// ////public class InvokeTestBed ////{ //// public enum FooEnum //// { //// Blah, //// } //// //// public void MethodInt( int t ) //// { //// Debug.Print( t.GetType().ToString() ); //// } //// //// public void MethodEnum( FooEnum t ) //// { //// Debug.Print( t.GetType().ToString() ); //// } ////} //--// public class FinalizeTest { protected int m_id; public FinalizeTest( int id ) { m_id = id; } ~FinalizeTest() { Debug.Print( "~FinalizeTest " + m_id ); Thread.Sleep( 100 ); } } public class FinalizeTest2 : FinalizeTest { public FinalizeTest m_child; public FinalizeTest2( int id ) : base( id ) { m_child = new FinalizeTest( id + 1 ); } ~FinalizeTest2() { Debug.Print( "~FinalizeTest2 " + m_id ); if(m_id == 4 && m_child != null) { System.GC.SuppressFinalize( m_child ); } } } //--// class Verify : Interface { [Serializable] public struct DayState { //If the temperature is unknown, it is sent down as sbyte.MinValue (-128) public sbyte m_high; public sbyte m_low; public DayState( sbyte high, sbyte low ) { m_high = high; m_low = low; } } public class Sub1 { public interface SubInterface { short Method1( int c ); } public class Sub2 : SubInterface { short Verify.Sub1.SubInterface.Method1( int c ) { return 1; } } } //static int s_i = 1; //static string s_s = "test static"; static object s_o = new Object(); OnKey m_onKey; public void Thread_Start1() { const int limit = 100000; for(int i=1000000; i<1000000+limit;i++) { } } public short Method1( int c ) { return (short)(c * 10); } public int Method2( int a, int b, Value v ) { Thread.Sleep( 50 ); return a + b + v.i1; } public int Method2( int a, int b, Value v, DateTime dt ) { Thread.Sleep( 50 ); return a + b + v.i1; } static public int Method2_b( int a, int b, Value v ) { return a + b * v.i1; } static public int Method3( int a, out int b, ref int c ) { b = a + c; c = a * 2; return a + b + c; } [MethodImplAttribute(MethodImplOptions.Synchronized)] public int Method4( params int[] a ) { return a.Length; } [MethodImplAttribute(MethodImplOptions.Synchronized)] static public int Method4s( params int[] a ) { return a.Length; } public void Method5( TestEnum e ) { switch(e) { case TestEnum.P1: Debug.Print( "P1" ); break; case TestEnum.P2: Debug.Print( "P2" ); break; case TestEnum.P3: Debug.Print( "P3" ); break; } } public void Method6( Enum e ) { Debug.Print( "Enum: " + e.GetType().FullName ); Method6( ref e ); } public void Method6( object state ) { Debug.Print( "Timer: " + DateTime.Now.ToString() + " " + state.GetType().FullName ); } public void Method6( ref Enum e ) { Debug.Print( "EnumByRef: " + e.GetType().FullName ); } public void TestEvent1( int a ) { Debug.Print( "TestEvent1: " + a ); } static public void TestEvent2( int a ) { Debug.Print( "TestEvent2: " + a ); } static public void TestEvent3( int a ) { Debug.Print( "TestEvent3: " + a ); } //--// private void TestNumeric() { int i; int s1 = 1242323; long l1 = 1298182; long l2 = -1242323; long[] l3 = new long[5]; ulong ul1 = 1298182; ulong ul2 = 1242323; ulong[] ul3 = new ulong[5]; long[] sl3 = new long[5]; double[] fl3 = new double[4]; ul3[0] = ul1 + ul2; ul3[1] = ul1 - ul2; ul3[2] = ul1 * ul2; ul3[3] = ul1 / ul2; ul3[4] = ul1 % ul2; for(i=0; i" + s2.Trim () + "<" ); Debug.Print( "Trim : >" + s2.TrimEnd () + "<" ); Debug.Print( "Trim : >" + s2.TrimStart() + "<" ); s2 = "!@# white space !@#"; Debug.Print( "Trim : >" + s2.Trim ( '!', '@', '#' ) + "<" ); Debug.Print( "Trim : >" + s2.TrimEnd ( '!', '@', '#' ) + "<" ); Debug.Print( "Trim : >" + s2.TrimStart( '!', '@', '#' ) + "<" ); Debug.Print( "IndexOf: " + s2.IndexOf( 'w' ) ); Debug.Print( "IndexOf: " + s2.IndexOf( 'w', 4 ) ); Debug.Print( "IndexOf: " + s2.IndexOf( 'w', 10 ) ); Debug.Print( "IndexOf: " + s2.IndexOf( 'w', 4, 7 ) ); Debug.Print( "IndexOf: " + s2.IndexOf( 'w', 4, 3 ) ); Debug.Print( "IndexOfAny : " + s2.IndexOfAny ( new char[] { 'a', 'd' } ) ); Debug.Print( "IndexOf : " + s2.IndexOf ( "spa" ) ); Debug.Print( "LastIndexOf: " + s2.LastIndexOf( ' ' ) ); Debug.Print( "IndexOf: " + "Multiple\nLines\nTest".IndexOf( '\n' ) ); Debug.Print( "ToUpper: " + "Multiple Cases Test".ToUpper() ); Debug.Print( "ToLower: " + "Multiple Cases Test".ToLower() ); s2 = new string( '#', 80 ); Debug.Print( ".ctor : >" + s2 + "<" ); ca = new char[4]; ca[0] = 'a'; ca[1] = 'b'; ca[2] = 'c'; ca[3] = 'd'; s2 = new string( ca ); Debug.Print( ".ctor : >" + s2 + "<" ); s2 = new string( ca, 1, 2 ); Debug.Print( ".ctor : >" + s2 + "<" ); } private void TestValueTypes() { Interface itf = this; Value v1 = new Value( 1 ); Value v2; v1.i1 = 2; v2 = v1; v2.i1 = itf.Method1( 1 ); v2.i2 = itf.Method2( 1, 2, v1 ); } private int TestDayState( ref DayState a ) { a.m_low *= 2; return a.m_high; } private void TestValueTypeArrayReferences() { DayState[] nat_cities = new DayState[2]; int i = 1; nat_cities[i] = new DayState( 50, 37 ); DayState d = nat_cities[i]; Debug.Print( "High assign = " + d .m_high ); Debug.Print( "High direct = " + nat_cities[i].m_high ); d.m_low = 10; TestDayState( ref d ); Debug.Print( "Low assign = " + d.m_low ); nat_cities[i].m_low = 15; TestDayState( ref nat_cities[i] ); Debug.Print( "Low direct = " + nat_cities[i].m_low ); } private int TestBoxing() { Value v1 = new Value( 1 ); int i; try { object o1 = v1; object o2 = 3; o1.Equals( new Value() ); Value v3 = (Value)o1; int i3 = (int)o2; Debug.Print( "Int: " + i3 ); Debug.Print( "Val: " + v3.i1 ); } catch(Exception e) { Debug.Print( "Exception: " + e ); i = 1; } finally { i = 2; } return i; } private void TestExceptions() { try { try { Debug.Print( "Exception: 1" ); } finally { Debug.Print( "Exception: 2" ); try { Exception e = new Exception( "test" ); throw e; } catch { Debug.Print( "Exception: 2b" ); throw; } finally { Debug.Print( "Exception: 3" ); } } } catch(Exception) { Debug.Print( "Exception: 4" ); } finally { Debug.Print( "Exception: 5" ); } // // Nesting test // try { try { Debug.Print( "Exception: 1" ); } catch(Exception) { Debug.Print( "Exception: 3" ); } finally { Debug.Print( "Exception: 4" ); } try { Debug.Print( "Exception: 5" ); throw new Exception(); } catch(Exception) { Debug.Print( "Exception: 7" ); } finally { Debug.Print( "Exception: 8" ); throw new Exception(); } } catch(Exception) { try { Debug.Print( "Exception: 10" ); } catch { Debug.Print( "Exception: 11" ); } } finally { Debug.Print( "Exception: 12" ); } } private void TestArrays() { object[] ar = new Object[20]; int a = 1; int c = 4; ////////////////////////////////////////////////////////////////////////////////////// // // Array tests. // ar[0] = this; string[] ars = new string[10]; ars[0] = "test"; ars[2] = "test2"; foreach(string s in ars) { int len = s != null ? s.Length : 0; } object[] ar2 = new object[5]; System.Array.Copy( ar, 0, ar2, 2, 3 ); Debug.Print( "System.Array.Copy: " + (ar2[2] != null) ); Debug.Print( "System.Array.Clear: " + (ar[0] != null) ); System.Array.Clear( ar, 0, ar.Length ); Debug.Print( "System.Array.Clear: " + (ar[0] != null) ); try { string[] ar3 = new string[10]; object[] ar4 = ar3; DateTime[] ar5 = new DateTime[2]; ar[0] = this; System.Array.Copy( ar, ar4, 10 ); Debug.Print( "System.Array.Copy: Incompatible types: FAIL" ); } catch { Debug.Print( "System.Array.Copy: Incompatible types: SUCCESS" ); } ////////////////////////////////////////////////////////////////////////////////////// // // More array tests and Exception tests. // string s1 = a.ToString(); ar[1] = a; c = (int)ar[1]; } private void TestArrayList() { ArrayList lst = new ArrayList(); int i; Debug.Print( "System.ArrayList.Add : " + lst.Add( 1 ) ); Debug.Print( "System.ArrayList.Add : " + lst.Add( "test" ) ); Debug.Print( "System.ArrayList.Contains : " + lst.Contains( 1 ) ); lst.Insert( 1, "ll" ); Debug.Print( "System.ArrayList.IndexOf : " + lst.IndexOf( "test" ) ); i = 0; foreach(object o in lst) { Debug.Print( "System.ArrayList.Enum : " + i++ + " " + o ); } //--// lst = new ArrayList(); lst.Add( "string" ); lst.Add( "test" ); lst.Add( null ); string[] arS = new string[3]; lst.CopyTo( arS ); //--// lst = new ArrayList(); lst.Add( new Foo() ); lst.Add( null ); Foo[] arO = new Foo[3]; lst.CopyTo( arO ); //--// lst = new ArrayList(); lst.Add( TestEnum.P2 ); TestEnum[] arE = new TestEnum[3]; lst.CopyTo( arE ); Debug.Print( "lst.CopyTo( arE ); " + arE[0].ToString() ); //--// lst = new ArrayList(); lst.Add( 12 ); lst.Add( 532 ); lst.Add( 12 ); int[] arI = new int[3]; lst.CopyTo( arI ); ArrayList lst2 = (ArrayList)lst.Clone(); Debug.Print( "System.ArrayList.Clone " + (lst2.Count == lst.Count) ); lst2.RemoveAt( 0 ); Debug.Print( "System.ArrayList.Clone " + (lst2[0] == lst[1]) ); try { lst.CopyTo( arS ); Debug.Print( "Invalid lst.CopyTo( arS ); FAILURE" ); } catch { Debug.Print( "Invalid lst.CopyTo( arS ); SUCCESS" ); } try { lst[1] = (byte)12; lst.CopyTo( arI ); Debug.Print( "Invalid lst.CopyTo( arI ); FAILURE" ); } catch { Debug.Print( "Invalid lst.CopyTo( arI ); SUCCESS" ); } try { arI = new int[1]; lst.CopyTo( arI ); Debug.Print( "Invalid lst.CopyTo( arI ); FAILURE" ); } catch { Debug.Print( "Invalid lst.CopyTo( arI ); SUCCESS" ); } } private void TestDelegates() { Interface itf = this; Value v1 = new Value( 1 ); Compute cmp = new Compute( itf.Method2 ); Compute cmp2 = new Compute( Verify.Method2_b ); cmp ( 1, 2, v1 ); cmp2( 1, 2, v1 ); this.m_onKey += new OnKey( this .TestEvent1 ); this.m_onKey += new OnKey( Verify.TestEvent2 ); this.m_onKey += new OnKey( Verify.TestEvent3 ); this.m_onKey -= new OnKey( Verify.TestEvent2 ); this.m_onKey -= new OnKey( Verify.TestEvent3 ); this.m_onKey -= new OnKey( Verify.TestEvent3 ); // Removing entry not in the list. Should do nothing. this.m_onKey += new OnKey( Verify.TestEvent3 ); this.m_onKey += new OnKey( Verify.TestEvent2 ); this.m_onKey += new OnKey( Verify.TestEvent2 ); // Adding entry already in the list. Should do nothing. this.m_onKey( 12 ); //// Verify testWeak = new Verify( 1, 2 ); //// //// this.m_onKey = (OnKey)Microsoft.SPOT.WeakDelegate.Combine( this.m_onKey, new OnKey( testWeak.TestEvent1 ) ); //// this.m_onKey -= new OnKey( Verify.TestEvent3 ); //// this.m_onKey += new OnKey( Verify.TestEvent3 ); //// this.m_onKey( 12 ); //// //// testWeak = null; System.GC.Collect(); this.m_onKey( 12 ); this.m_onKey -= new OnKey( Verify.TestEvent3 ); } //// private void TestGetType( string typeName, bool fShouldExist ) //// { //// Type t = Type.GetType( typeName ); //// bool fExist = (t != null); //// string res = (fExist == fShouldExist) ? "OK" : "FAIL"; //// //// Debug.Print( typeName + " : " + res ); //// } //// //// private void TestReflection() //// { //// Interface itf = this; //// Compute cmp = new Compute( itf.Method2 ); //// //// object cmp_m = cmp.Method; //// object cmp_t = cmp.Target; //// Type t1; //// //// t1 = typeof(string[]); //// t1 = cmp.GetType(); //// t1 = this.GetType(); //// //// TestGetType( "System.Object" , true ); //// TestGetType( "Microsoft.SPOT.Verification.Verify+Sub1+Sub2" , true ); //// TestGetType( "Microsoft.SPOT.Verification.Verify+Sub3" , false ); //// TestGetType( "Microsoft.SPOT.Verification.Verify+Sub1+Sub2+Sub3", false ); //// //// ConstructorInfo ci = t1.GetConstructor( new Type[] { typeof(int), typeof(int) } ); //// object resCI = ci.Invoke( new Object[] { 2, 12 } ); //// //// MethodInfo mi = t1.GetMethod( "Method1", new Type[] { typeof(int) } ); //// //// object res = mi.Invoke( this, new Object[] { 2 } ); //// if(res is short) //// { //// Debug.Print( "Invoke: " + (short)res ); //// } //// else //// { //// Debug.Print( "Invoke: " ); //// } //// //// Type[] at = Microsoft.SPOT.Reflection.GetTypesImplementingInterface( typeof(Interface) ); //// if(at != null) //// { //// foreach(Type t2 in at) //// { //// ConstructorInfo ci2 = t2.GetConstructor( new Type[] { typeof(int), typeof(int) } ); //// object resCI2 = ci2.Invoke( new Object[] { 2, 12 } ); //// //// Interface itf2 = (Interface)resCI2; //// } //// } //// //// Assembly[] aa = Microsoft.SPOT.Reflection.GetAssemblies(); //// foreach(Assembly a in aa) //// { //// Debug.Print( "name: " + a.FullName + " - " + Microsoft.SPOT.Reflection.GetAssemblyHash( a ) ); //// } //// //// // Type t3 = typeof(string[,]); //// //// // Value v2 = new Value( 3 ); //// // int i2 = v2.Result(); //// //// // v.i1 = itf.Method1( 1 ); //// // v.i2 = itf.Method2( 1, 2, v ); //// //// object oCls = this; //// bool ba = oCls is Interface; //// bool bb = oCls is Type; //// bool bc = oCls is Verify; //// //// FooBar.TestFOO(); //// FooBar.TestBAR(); //// //// typeof(InvokeTestBed).GetMethod( "MethodInt" ).Invoke( new InvokeTestBed(), new object [] { 1 } ); //// typeof(InvokeTestBed).GetMethod( "MethodEnum" ).Invoke( new InvokeTestBed(), new object [] { InvokeTestBed.FooEnum.Blah } ); //// } private void TestThread_AbortWorker() { try { while(true); } catch(ThreadAbortException e) { Debug.Print( "ThreadAbortException: " + e.ToString() ); } catch( Exception e1 ) { Debug.Print( "Generic Exception: " + e1.ToString() ); } finally { Debug.Print( "Finally block" ); } } public void TestThread_Abort() { Thread t = new Thread( new ThreadStart( TestThread_AbortWorker ) ); t.Start(); Thread.Sleep(1000); t.Abort(); Thread.Sleep(1000); t.Join(); } //--// private void TestDateTime() { DateTime dt1; DateTime dt1b; DateTime dt2; TimeSpan ts1; TimeSpan ts2 = new TimeSpan( 1, 0, 0 ); TimeSpan ts3 = new TimeSpan( 1, 0, 0, 0 ); dt1 = new DateTime( 2003, 1, 1 ); Debug.Print( "Microsoft.SPOT.ExtendedTimeZone.c_TicksTo20030101 " + dt1.ToString() ); dt1 = dt1.Add( ts2 ) ; Debug.Print( "dt1 = dt1.Add( ts2 ) " + dt1.ToString() ); dt1 = dt1.AddTicks( 10 * 1000 * 1000 ); Debug.Print( "dt1 = dt1.AddTicks( 10 * 1000 * 1000 ) " + dt1.ToString() ); Debug.Print( "dt1.Date " + dt1.Date.ToString() ); Debug.Print( "dt1.Ticks " + dt1.Ticks.ToString() ); Debug.Print( "dt1.TimeOfDay " + dt1.TimeOfDay.ToString() ); ts1 = dt1.Subtract( new DateTime( 2003, 1, 1 ) ); Debug.Print( ts1.ToString() ); dt1 = dt1.Subtract( ts3 ); Debug.Print( "dt1 = dt1.Subtract( ts3 ) " + dt1.ToString() ); dt2 = dt1 + ts2 ; Debug.Print( "dt2 = dt1 + ts2 " + dt2.ToString() ); dt2 = dt1 - ts2 ; Debug.Print( "dt2 = dt1 - ts2 " + dt2.ToString() ); ts1 = dt1 - dt2 ; Debug.Print( "ts1 = dt1 - dt2 " + ts1.ToString() ); dt1b = dt1; Debug.Print( "(dt1 < dt2) " + (dt1 < dt2 ) ); Debug.Print( "(dt1 > dt2) " + (dt1 > dt2 ) ); Debug.Print( "(dt1 >= dt2) " + (dt1 >= dt2 ) ); Debug.Print( "(dt1 <= dt2) " + (dt1 <= dt2 ) ); Debug.Print( "(dt1 >= dt1) " + (dt1 >= dt1b) ); Debug.Print( "(dt1 <= dt1) " + (dt1 <= dt1b) ); Debug.Print( "(dt1 == dt1) " + (dt1 == dt1b) ); Debug.Print( "(dt1 != dt1) " + (dt1 != dt1b) ); Debug.Print( "DateTime.Compare( dt1, dt2 ) " + DateTime.Compare( dt1, dt2 ) ); Debug.Print( "DateTime.Compare( dt2, dt1 ) " + DateTime.Compare( dt2, dt1 ) ); Debug.Print( "DateTime.Compare( dt1, dt1 ) " + DateTime.Compare( dt1, dt1 ) ); Debug.Print( "DateTime.Equals ( dt1, dt1 ) " + DateTime.Equals ( dt1, dt1 ) ); Debug.Print( "DateTime.Equals ( dt1, dt2 ) " + DateTime.Equals ( dt1, dt2 ) ); Debug.Print( "dt1.AddMilliseconds( 1.0 ) " + dt1.AddMilliseconds( 1.0 ).ToString() ); Debug.Print( "dt1.AddSeconds ( 1.0 ) " + dt1.AddSeconds ( 1.0 ).ToString() ); Debug.Print( "dt1.AddMinutes ( 1.0 ) " + dt1.AddMinutes ( 1.0 ).ToString() ); Debug.Print( "dt1.AddHours ( 1.0 ) " + dt1.AddHours ( 1.0 ).ToString() ); Debug.Print( "dt1.AddDays ( 1.9 ) " + dt1.AddDays ( 1.9 ).ToString() ); } private void TestTimeSpan() { TimeSpan ts1 = new TimeSpan( 1, 2, 3, 4, 567 ); Debug.Print( "ts1.Ticks " + ts1.Ticks .ToString() ); Debug.Print( "ts1.Days " + ts1.Days .ToString() ); Debug.Print( "ts1.Hours " + ts1.Hours .ToString() ); Debug.Print( "ts1.Minutes " + ts1.Minutes .ToString() ); Debug.Print( "ts1.Seconds " + ts1.Seconds .ToString() ); Debug.Print( "ts1.Milliseconds " + ts1.Milliseconds.ToString() ); Debug.Print( "ts1.Add( ts1 ) " + ts1.Add( ts1 ) .ToString() ); Debug.Print( "-ts1 " + (-ts1) .ToString() ); Debug.Print( "-ts1.Duration " + (-ts1).Duration().ToString() ); } private void TestTime() { DateTime dt = DateTime.Now; Debug.Print( dt.ToString() ); TimeSpan ts = new TimeSpan( 1, 20, 12, 30, 100 ); Debug.Print( ts.ToString() ); ts = ts.Add( new TimeSpan( 0, 0, 10 ) ); Debug.Print( ts.ToString() ); DateTime dt2 = dt; dt = dt.Add( ts ); Debug.Print( dt.ToString() ); TimeSpan ts2 = dt.Subtract( dt2 ); Debug.Print( ts2.ToString() ); Debug.Print( ts2.Days.ToString() ); Debug.Print( ts2.Hours.ToString() ); Debug.Print( ts2.Minutes.ToString() ); Debug.Print( ts2.Seconds.ToString() ); dt = dt.Subtract( ts ); Debug.Print( dt.ToString() ); Debug.Print( TimeSpan.MaxValue.ToString() ); Debug.Print( TimeSpan.Zero .ToString() ); Debug.Print( TimeSpan.MinValue.ToString() ); Debug.Print( DateTime.MaxValue.ToString() ); Debug.Print( DateTime.MinValue.ToString() ); Debug.Print( "############################" ); } private void WaitButton() { Thread.Sleep( 1000 ); } private void TestTimers() { Timer timer = new Timer( new TimerCallback( this.Method6 ), 1, 1000, 2000 ); Thread t = new Thread( new ThreadStart( this.Thread_Start1 ) ); t.Start(); for(int i=0; i<10; i++) { } WaitButton(); ////////////////////////////////////////////////////////////////////////////////////// // // More Timer and Threading tests. // timer.Change( 1000, 500 ); t.Abort(); t.Join(); Debug.Print( "Timer wait" ); // // Test timer object release // timer = new Timer( new TimerCallback( this.Method6 ), "test", new TimeSpan( 1000 * 10000 ), new TimeSpan( 1000 * 10000 ) ); timer = null; Debug.Print( "Timer alive..." ); Thread.Sleep( 3000 ); System.GC.Collect(); Debug.Print( "Timer should be dead. Press button to continue." ); WaitButton(); //// Microsoft.SPOT.ExtendedTimer timer2; //// //// Debug.Print( "Extended Timer 1" ); //// timer2 = new Microsoft.SPOT.ExtendedTimer( new TimerCallback( this.Method6 ), "test", 1000, 1000 ); //// Thread.Sleep( 3000 ); //// timer2.Dispose(); //// //// Debug.Print( "Extended Timer 2" ); //// timer2 = new Microsoft.SPOT.ExtendedTimer( new TimerCallback( this.Method6 ), "test", new DateTime( 2012, 12, 1, 14, 0, 2 ), new TimeSpan( 1000 * 10000 ) ); //// Debug.Print( "Now: " + DateTime.Now.ToString() ); //// Thread.Sleep( 1000 ); //// //// Microsoft.SPOT.Hardware.Utility.SetLocalTime( new DateTime( 2012, 12, 1, 14, 0, 0 ) ); //// Debug.Print( "Now: " + DateTime.Now.ToString() ); //// Thread.Sleep( 4000 ); //// timer2.Dispose(); //// //// Debug.Print( "Extended Timer 3" ); //// Thread.Sleep( 500 ); //// //// timer2 = new Microsoft.SPOT.ExtendedTimer( new TimerCallback( this.Method6 ), "test", Microsoft.SPOT.ExtendedTimer.TimeEvents.Minute ); //// Microsoft.SPOT.Hardware.Utility.SetLocalTime( new DateTime( 2012, 12, 1, 14, 0, 58 ) ); //// Debug.Print( "Now: " + DateTime.Now.ToString() ); //// //// Debug.Print( "Waiting on TimeEvents.Minute. Press button to continue." ); WaitButton(); //// //// timer2.Dispose(); //// //// Debug.Print( "Extended Timer 4" ); //// timer2 = new Microsoft.SPOT.ExtendedTimer( new TimerCallback( this.Method6 ), "test", Microsoft.SPOT.ExtendedTimer.TimeEvents.Hour ); //// Microsoft.SPOT.Hardware.Utility.SetLocalTime( new DateTime( 2012, 12, 1, 14, 59, 58 ) ); //// Debug.Print( "Now: " + DateTime.Now.ToString() ); //// //// Debug.Print( "Waiting on TimeEvents.Hour. Press button to continue." ); WaitButton(); //// //// Debug.Print( "Last Expiration: " + timer2.LastExpiration.ToString() ); //// timer2.Dispose(); //// //// Debug.Print( "Extended Timer 5" ); //// timer2 = new Microsoft.SPOT.ExtendedTimer( new TimerCallback( this.Method6 ), "test", Microsoft.SPOT.ExtendedTimer.TimeEvents.SetTime ); //// //// Debug.Print( "Press button to change time." ); WaitButton(); //// Microsoft.SPOT.Hardware.Utility.SetLocalTime( new DateTime( 2012, 12, 2, 14, 59, 58 ) ); //// Debug.Print( "Now: " + DateTime.Now.ToString() ); //// Debug.Print( "Waiting on TimeEvents.SetTime. Press button to continue." ); WaitButton(); //// //// timer2.Dispose(); } //// private void TestRegionConfiguration() //// { //// DateTime dt_20030101 = new DateTime( 2003, 01, 01 ); //// DateTime dt_20030420 = new DateTime( 2003, 04, 20 ); //// DateTime dt_20030430 = new DateTime( 2003, 04, 30 ); // Wednesday //// DateTime dt_20030501 = new DateTime( 2003, 05, 01 ); //// DateTime dt_20030502 = new DateTime( 2003, 05, 02 ); //// //// DateTime dt_Sunday = dt_20030101.AddDays( DayOfWeek.Sunday - dt_20030101.DayOfWeek ); //// DateTime dt_Monday = dt_Sunday.AddDays( 1 ); //// DateTime dt_Tuesday = dt_Sunday.AddDays( 2 ); //// DateTime dt_Wednesday = dt_Sunday.AddDays( 3 ); //// DateTime dt_Thursday = dt_Sunday.AddDays( 4 ); //// DateTime dt_Friday = dt_Sunday.AddDays( 5 ); //// DateTime dt_Saturday = dt_Sunday.AddDays( 6 ); //// //// //// TimeSpan ts_080000 = new TimeSpan( 8, 0, 0 ); //// TimeSpan ts_170000 = new TimeSpan( 17, 0, 0 ); //// TimeSpan ts_180000 = new TimeSpan( 18, 0, 0 ); //// TimeSpan ts_200000 = new TimeSpan( 20, 0, 0 ); //// } private void TestFinalizers() { FinalizeTest ft1 = new FinalizeTest ( 1 ); FinalizeTest ft2 = new FinalizeTest2( 2 ); FinalizeTest ft3 = new FinalizeTest2( 4 ); System.GC.Collect(); Debug.Print( "GC 0: " + Debug.AvailableMemory() ); //Debug.DumpHeap(); ft1 = null; ft2 = null; ft3 = null; for(int i=1; i<10; i++) { System.GC.Collect(); Debug.Print( "GC " + i + ": " + Debug.AvailableMemory() ); //Debug.DumpHeap(); System.GC.WaitForPendingFinalizers(); //Thread.Sleep( 70 ); } } //// private void TestWeakReferences() //// { //// RPC_test.RecordSub r1 = new RPC_test.RecordSub(); //// System.WeakReference weak = new System.WeakReference( r1 ); //// //// System.GC.Collect(); //// Debug.Print( "Weak reference: " + weak.IsAlive ); //// //// r1 = null; //// //// System.GC.Collect(); //// Debug.Print( "Weak reference: " + weak.IsAlive ); //// //// //--// //// //// Microsoft.SPOT.ExtendedWeakReference restore; //// Microsoft.SPOT.ExtendedWeakReference weak2; //// ArrayList lst = new ArrayList(); //// int i; //// //// lst = new ArrayList(); //// //// while((restore = Microsoft.SPOT.ExtendedWeakReference.Recover( typeof(DateTime), 0 )) != null) //// { //// lst.Add( restore ); //// } //// //// for(i=0; i ================================================ FILE: Zelig/Zelig/Test/RunTime/mscorlib_UnitTest/mscorlib_UnitTest.csproj ================================================  Debug AnyCPU 9.0.20706 2.0 {2A1100C4-D59C-4736-AA8E-10E9ED989784} Exe Properties mscorlib_UnitTest mscorlib_UnitTest v4.5 true full true $(LlilumBuildRoot)\Target\bin\$(Configuration)\ DEBUG;TRACE prompt 4 true true true AllRules.ruleset AnyCPU false full true $(LlilumBuildRoot)\Target\bin\$(Configuration)\ DEBUG;TRACE prompt 4 true true true AllRules.ruleset AnyCPU false true true full true $(LlilumBuildRoot)\Target\bin\$(Configuration)\ AnyCPU DEBUG;TRACE true true true false True True Files.resx Designer ResXFileCodeGenerator Files.Designer.cs {186f31a3-ef89-4a25-b2d5-20061218aa01} Common {186f31a3-ef89-4a25-b2d5-20060501aa01} mscorlib {186f31a3-ef89-4a25-b2d5-20070702aa01} system {186f31a3-ef89-4a25-b2d5-20060720aa01} TypeSystem ================================================ FILE: Zelig/Zelig/Test/Runner/Properties/AssemblyInfo.cs ================================================ using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; // General Information about an assembly is controlled through the following // set of attributes. Change these attribute values to modify the information // associated with an assembly. [assembly: AssemblyTitle("Utilities")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("Microsoft IT")] [assembly: AssemblyProduct("Utilities")] [assembly: AssemblyCopyright("Copyright © Microsoft IT 2014")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible(false)] // The following GUID is for the ID of the typelib if this project is exposed to COM [assembly: Guid("5bc4a1fd-1ef8-4233-8f0b-4adab41b3667")] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Build and Revision Numbers // by using the '*' as shown below: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("1.0.0.0")] [assembly: AssemblyFileVersion("1.0.0.0")] ================================================ FILE: Zelig/Zelig/Test/Runner/TestRunner.cs ================================================ using System; using System.Collections.Generic; namespace Microsoft.Zelig.Test { public class TestRunner { private int m_timeOut = 900000; // 15 minutes default time out. /// /// An overloaded constructor that takes the test objects in its arguments. /// /// A list of test objects. public TestRunner(int timeout) { m_timeOut = timeout; } public void Run() { var tests = new List(); bool testResults = true; // System.Exception tests.Add(new ExceptionTests()); // Conversions //////tests.Add( new BasicTests() ); //////tests.Add( new BasicTests2() ); tests.Add( new BoxingTests() ); tests.Add( new Expenum1Tests() ); tests.Add( new Expenum2Tests() ); tests.Add( new Expenum3Tests() ); tests.Add( new ExprefTests() ); tests.Add( new ImpenumTests() ); tests.Add( new ImprefTests() ); tests.Add( new ClassClassTests() ); tests.Add( new ClassStructTests() ); tests.Add( new StructClassTests() ); tests.Add( new StructStructTests() ); // selection tests.Add( new BasicSelectionTests() ); // types tests.Add( new ReferenceBoxingTests() ); tests.Add( new ValueArrayTests() ); tests.Add( new ValueDefault_ConstTests() ); tests.Add( new ValueFloatTests() ); tests.Add( new ValueIntegralTests() ); tests.Add( new ValueSimpleTests() ); tests.Add( new ValueTests() ); tests.Add( new ValueIntegralTests() ); tests.Add( new ValueIntegralTests() ); // System.Text.StringBuilder tests.Add(new StringBuilderTests()); // System.IO.MemoryStream tests.Add(new CanRead()); tests.Add(new CanSeek()); tests.Add(new CanWrite()); tests.Add(new Close()); tests.Add(new Flush()); tests.Add(new Length()); tests.Add(new MemoryStream_Ctor()); tests.Add(new Position()); tests.Add(new Read()); tests.Add(new ReadByte()); tests.Add(new Seek()); tests.Add(new SetLength()); tests.Add(new ToArray()); tests.Add(new Write()); tests.Add(new WriteByte()); tests.Add(new WriteTo()); // mscorlib tests.Add(new ArraysSimpleTests()); tests.Add(new ArraysOtherTests()); tests.Add(new BasicConceptTests()); tests.Add(new ConstructorsTests()); tests.Add(new ConstTests()); tests.Add(new DeclarationsTests()); tests.Add(new DestructorsTests()); tests.Add(new EnumTests()); tests.Add(new EventsTests()); tests.Add(new FieldsTests()); tests.Add(new IndexersTests()); tests.Add(new InterfaceTests()); tests.Add(new OperatorsTests()); tests.Add(new PropertiesTests()); tests.Add(new Static_InstTests()); tests.Add(new MembersTests()); tests.Add(new MethodsTests()); tests.Add(new StructsTests()); foreach(ITestInterface t in tests) { try { if(t.Initialize() == InitializeResult.ReadyToGo) { var test = (TestBase)t; TestConsole.WriteLine($"Test '{test.Name}' running..."); TestResult result = test.Run(null); string resultString = "Passed"; if(( result & TestResult.Fail ) != 0) { resultString = "Failed"; testResults = false; } TestConsole.WriteLine("Result: " + resultString); } } catch { Log.Comment("caught exception while running tests"); } } TestConsole.WriteLine("All tests complete."); TestConsole.WriteLine(""); TestConsole.WriteLine("*************************"); TestConsole.WriteLine("* Test Run Result: " + ( testResults ? "PASS" : "FAIL *" )); TestConsole.WriteLine("*************************"); } public static void Main(string[] args) { new TestRunner(0).Run(); } } } ================================================ FILE: Zelig/Zelig/Test/Runner/TestRunner.csproj ================================================  Debug AnyCPU {A8C7CEC1-FF02-4ECA-967B-72825F4940AE} Exe Properties Microsoft.Zelig.Test Microsoft.Zelig.Test.TestRunner v4.5 512 true full true false $(LlilumBuildRoot)\Target\bin\$(Configuration)\ DEBUG;TRACE prompt 4 full true $(LlilumBuildRoot)\Target\bin\$(Configuration)\ DEBUG;TRACE prompt 4 true {b649b569-516b-4c88-a7b1-ebd02e12dd99} Test_Common {e149b569-516b-4c88-a7b1-ebd02e12dd1e} Test_mscorlib {186f31a3-ef89-4a25-b2d5-20070702aa01} system {186f31a3-ef89-4a25-b2d5-20080628aa01} system_core {54125fc8-5c6d-4f4b-92b8-3377fe1d92e1} Test_System ================================================ FILE: Zelig/Zelig/Test/mbed/NativeHelpers/NativeHelpers.vcxproj ================================================  Debug ARM Release ARM {6367CACE-0511-485D-9AE5-698F7E600839} MakeFileProj 8.1 Makefile true v140 Makefile false v140 $(LlilumSourceRoot)\..\mbed\TARGET_LPC1768\TOOLCHAIN_GCC_ARM;$(LibraryPath) $(LlilumSourceRoot)\..\mbed\;$(LlilumSourceRoot)\..\mbed\TARGET_LPC1768;$(LlilumSourceRoot)\..\mbed\TARGET_LPC1768\TARGET_NXP\TARGET_LPC176X;$(LlilumSourceRoot)\..\mbed\TARGET_LPC1768\TARGET_NXP\TARGET_LPC176X\TARGET_MBED_LPC1768;$(IncludePath) $(LlilumBuildRoot)\Target\bin\$(Configuration)\ $(LlilumBuildRoot)\Target\obj\$(Configuration)\ "$(GnuWin32MakeInstallPath)bin\make" DEBUG=1 TARGET=LPC1768 HEAP_SIZE=0x6000 "$(GnuWin32MakeInstallPath)bin\make" clean all DEBUG=1 TARGET=LPC1768 HEAP_SIZE=0x6000 "$(GnuWin32MakeInstallPath)bin\make" clean TARGET=LPC1768 NativeHelpers.bin __GNUC__;TARGET=LPC1768;NDEBUG;$(NMakePreprocessorDefinitions) $(LlilumSourceRoot)\..\mbed\;$(LlilumSourceRoot)\..\mbed\TARGET_LPC1768;$(LlilumSourceRoot)\..\mbed\TARGET_LPC1768\TARGET_NXP\TARGET_LPC176X;$(LlilumSourceRoot)\..\mbed\TARGET_LPC1768\TARGET_NXP\TARGET_LPC176X\TARGET_MBED_LPC1768;$(IncludePath) $(LlilumSourceRoot)\mbed\TARGET_LPC1768\TOOLCHAIN_GCC_ARM;$(LibraryPath) $(LlilumSourceRoot)\..\mbed\;$(LlilumSourceRoot)\..\mbed\TARGET_LPC1768;$(LlilumSourceRoot)\..\mbed\TARGET_LPC1768\TARGET_NXP\TARGET_LPC176X;$(LlilumSourceRoot)\..\mbed\TARGET_LPC1768\TARGET_NXP\TARGET_LPC176X\TARGET_MBED_LPC1768;$(IncludePath) $(LlilumBuildRoot)\Target\bin\$(Configuration)\ $(LlilumBuildRoot)\Target\obj\$(Configuration)\ $(LlilumSourceRoot)\..\mbed\;$(LlilumSourceRoot)\..\mbed\TARGET_LPC1768;$(LlilumSourceRoot)\..\mbed\TARGET_LPC1768\TARGET_NXP\TARGET_LPC176X;$(LlilumSourceRoot)\..\mbed\TARGET_LPC1768\TARGET_NXP\TARGET_LPC176X\TARGET_MBED_LPC1768;$(IncludePath) __GNUC__;TARGET=LPC1768;NDEBUG;$(NMakePreprocessorDefinitions) NativeHelpers.bin "$(GnuWin32MakeInstallPath)bin\make" clean TARGET=LPC1768 "$(GnuWin32MakeInstallPath)bin\make" clean all DEBUG=1 TARGET=LPC1768 HEAP_SIZE=0x6000 "$(GnuWin32MakeInstallPath)bin\make" DEBUG=1 TARGET=LPC1768 HEAP_SIZE=0x6000 ================================================ FILE: Zelig/Zelig/Test/mbed/NativeHelpers/NativeHelpers.vcxproj.filters ================================================  build&debug build&debug build&debug build&debug build&debug build&debug build&debug build&debug build&debug build&debug build&debug build&debug build&debug build&debug build&debug build&debug build&debug build&debug {982f765d-fe61-4e22-bc32-486e16a38851} build&debug ================================================ FILE: Zelig/Zelig/Test/mbed/SimpleHttp/Program.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // #define K64F namespace Microsoft.Zelig.Test.mbed.SimpleNet { using System.Net; using System.Net.Sockets; using System.Threading; using Microsoft.Llilum.Lwip; using Microsoft.Zelig.Runtime; using System; using System.IO; using System.Text; using Llilum.Devices.Gpio; class Program { static void Main( ) { NetworkInterface netif = NetworkInterface.GetAllNetworkInterfaces()[0]; netif.EnableDhcp( ); GpioPin redPin = GpioPin.TryCreateGpioPin((int)Llilum.K64F.PinName.LED_RED); GpioPin greenPin = GpioPin.TryCreateGpioPin((int)Llilum.K64F.PinName.LED_GREEN); GpioPin bluePin = GpioPin.TryCreateGpioPin((int)Llilum.K64F.PinName.LED_BLUE); redPin.Direction = PinDirection.Output; greenPin.Direction = PinDirection.Output; bluePin.Direction = PinDirection.Output; // Complete 10 HTTP requests for(int i = 0; i < 10; i++) { // LED is active low on K64F // Red means we have not gotten our request back redPin.Write(0); greenPin.Write(1); bluePin.Write(1); // Create the HTTP request // NOTE: Users need to replace this with their server IP address! HttpWebRequest webReq = (HttpWebRequest)WebRequest.Create(@"http://10.91.68.176:8080"); webReq.Method = "POST"; var data = UTF8Encoding.UTF8.GetBytes(string.Format("I am K64F. Request number: {0}", i)); webReq.ContentType = "application/text"; webReq.ContentLength = data.Length; // Write the request var dataStream = webReq.GetRequestStream(); dataStream.Write(data, 0, data.Length); dataStream.Close(); BugCheck.Log("------ start ------"); // Receive the response var response = webReq.GetResponse(); BugCheck.Log("===================="); BugCheck.Log((((HttpWebResponse)response).StatusDescription)); BugCheck.Log("===================="); BugCheck.Log(response.ContentLength.ToString()); BugCheck.Log("===================="); BugCheck.Log(response.ContentType); BugCheck.Log("===================="); // Getting data from POST request is not standard, but is still allowed var respData = response.GetResponseStream(); // Turn off the red LED once the request comes back redPin.Write(1); var reader = new StreamReader(respData); string responseFromServer = reader.ReadToEnd(); // Check to see if the result contains a color if (responseFromServer.Contains("green")) { greenPin.Write(0); } else if (responseFromServer.Contains("blue")) { bluePin.Write(0); } else { // No color in result? Make the LED show white redPin.Write(0); greenPin.Write(0); bluePin.Write(0); } // Display the content. BugCheck.Log(responseFromServer); // Clean up the streams. reader.Close(); response.Close(); webReq.Dispose(); // Wait 2 seconds until the next transaction Thread.Sleep(2000); } } } } ================================================ FILE: Zelig/Zelig/Test/mbed/SimpleHttp/Properties/AssemblyInfo.cs ================================================ using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; // General Information about an assembly is controlled through the following // set of attributes. Change these attribute values to modify the information // associated with an assembly. [assembly: AssemblyTitle("simple")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("simple")] [assembly: AssemblyCopyright("Copyright © 2015")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible(false)] // The following GUID is for the ID of the typelib if this project is exposed to COM [assembly: Guid("3E671D6F-4E03-44F2-9549-30876DCAE01D")] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Build and Revision Numbers // by using the '*' as shown below: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("1.0.0.0")] [assembly: AssemblyFileVersion("1.0.0.0")] ================================================ FILE: Zelig/Zelig/Test/mbed/SimpleHttp/SimpleHttp.csproj ================================================  Debug AnyCPU {2D6185A8-A5FE-4FDF-874A-96037C37BD41} Exe Properties Microsoft.Zelig.Test.mbed.HTTP Microsoft.Zelig.Test.mbed.Simple.HTTP v4.5 512 AnyCPU true full false $(LlilumBuildRoot)\Target\obj\$(MSBuildProjectName)\$(Configuration)\ $(LlilumBuildRoot)\Target\bin\$(Configuration)\ DEBUG;TRACE prompt 4 true AnyCPU pdbonly true $(LlilumBuildRoot)\Target\bin\$(Configuration)\ $(LlilumBuildRoot)\Target\obj\$(MSBuildProjectName)\$(Configuration)\ TRACE prompt 4 {1705887b-e636-4fa3-ae40-2d431af1511c} K64F {d7f2bc4e-1406-47aa-90e1-07bc4ce9410f} mbed {d68ee51b-a898-4a77-97d8-c61254cac122} Microsoft.Llilum.Devices {186f31a3-ef89-4a25-b2d5-20070702aa01} system {dc8c38d7-780b-4b13-8ace-9050e39cc51c} Windows {e77ac86e-58ab-47b6-bc6d-3c1b4545cdfd} Microsoft.Llilum.Lwip {186f31a3-ef89-4a25-b2d5-20060509aa01} Kernel ================================================ FILE: Zelig/Zelig/Test/mbed/SimpleNet/Program.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // #define K64F namespace Microsoft.Zelig.Test.mbed.SimpleNet { using System.Net.Sockets; using System.Net; using System.Threading; using Microsoft.Llilum.Lwip; using Microsoft.Zelig.Runtime; using System.Text; using System; class Program { static void Main( ) { NetworkInterface netif = NetworkInterface.GetAllNetworkInterfaces()[0]; netif.EnableDhcp( ); BugCheck.Log( "Acquired IPv4 Address" ); BugCheck.Log( netif.IPAddress.ToString( ) ); //netif.EnableStaticIP("10.125.148.136", "255.255.254.0", "10.125.148.1"); //IPHostEntry entry = Dns.GetHostEntry("bing.com"); //IPAddress dnsAddress = entry.AddressList[0]; //byte[] dnsCmd = new byte[entry.HostName.Length]; //for(int i = 0; i < entry.HostName.Length; i++) //{ // dnsCmd[ i ] = (byte)entry.HostName[ i ]; //} string msg = "GET /media/uploads/mbed_official/hello.txt HTTP/1.0\n\n"; string end = "TEST_COMPLETED"; var msgBytes = ASCIIEncoding.ASCII.GetBytes(msg); var endBytes = ASCIIEncoding.ASCII.GetBytes(end); // NOTE: Be sure to change this to your local machine IP that is running the NetworkTest app IPEndPoint endPoint = new IPEndPoint( IPAddress.Parse("10.0.1.28"), 11000); var recBuffer = new byte[512]; while(true) { Socket sock = new Socket(AddressFamily.Unspecified, SocketType.Stream, ProtocolType.Unspecified); try { sock.Connect( endPoint ); int count = 0; while(++count <= 10) { if(sock.Send( msgBytes ) > 0) { sock.Receive( recBuffer ); } } sock.Send( endBytes ); } catch { } finally { sock.Close( ); } } } } } ================================================ FILE: Zelig/Zelig/Test/mbed/SimpleNet/Properties/AssemblyInfo.cs ================================================ using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; // General Information about an assembly is controlled through the following // set of attributes. Change these attribute values to modify the information // associated with an assembly. [assembly: AssemblyTitle("simple")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("simple")] [assembly: AssemblyCopyright("Copyright © 2015")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible(false)] // The following GUID is for the ID of the typelib if this project is exposed to COM [assembly: Guid("3E671D6F-4E03-44F2-9549-30876DCAE01D")] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Build and Revision Numbers // by using the '*' as shown below: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("1.0.0.0")] [assembly: AssemblyFileVersion("1.0.0.0")] ================================================ FILE: Zelig/Zelig/Test/mbed/SimpleNet/SimpleNet.csproj ================================================  Debug AnyCPU {40710089-C1C3-49D9-93B6-07A25219E5E8} Exe Properties Microsoft.Zelig.Test.mbed.NET Microsoft.Zelig.Test.mbed.Simple.NET v4.5 512 AnyCPU true full false $(LlilumBuildRoot)\Target\obj\$(MSBuildProjectName)\$(Configuration)\ $(LlilumBuildRoot)\Target\bin\$(Configuration)\ DEBUG;TRACE prompt 4 true AnyCPU pdbonly true $(LlilumBuildRoot)\Target\bin\$(Configuration)\ $(LlilumBuildRoot)\Target\obj\$(MSBuildProjectName)\$(Configuration)\ TRACE prompt 4 {1705887b-e636-4fa3-ae40-2d431af1511c} K64F {d7f2bc4e-1406-47aa-90e1-07bc4ce9410f} mbed {186f31a3-ef89-4a25-b2d5-20070702aa01} system {e77ac86e-58ab-47b6-bc6d-3c1b4545cdfd} Microsoft.Llilum.Lwip {186f31a3-ef89-4a25-b2d5-20060509aa01} Kernel ================================================ FILE: Zelig/Zelig/Test/mbed/SimpleSDK/Managed/Program.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // #define LPC1768 //#define K64F //#define USE_I2C //#define USE_SPI #define USE_GPIO #define USE_THREADING namespace Microsoft.Zelig.Test.mbed.Simple { using System; using System.Collections.Generic; #if (USE_THREADING) using System.Threading; #endif using Windows.Devices.Gpio; using Windows.Devices.Spi; using Windows.Devices.I2c; using Windows.Devices.Enumeration; using ZeligSupport = Microsoft.Zelig.Support.mbed; #if (LPC1768) using LPC1768 = Llilum.LPC1768; using System.Runtime.InteropServices; #elif (K64F) using K64F = Llilum.K64F; #else #error No target board defined. #endif //--// internal abstract class LedToggler { public LedToggler(GpioPin[] pins) { _pins = pins; } public abstract void run(float t); public int PinCount { get { return _pins.Length; } } public GpioPinValue this[int key] { get { return _pins[key].Read(); } set { _pins[key].Write(value); } } private readonly GpioPin[] _pins; }; internal class LedTogglerSimultaneous : LedToggler { public LedTogglerSimultaneous(GpioPin[] pins) : base(pins) { } public override void run(float t) { for (int i = 0; i < PinCount; ++i) { this[i] = (t < 0.5) ? GpioPinValue.High : GpioPinValue.Low; } } } internal class LedTogglerSequential : LedToggler { public LedTogglerSequential(GpioPin[] pins) : base(pins) { } public override void run(float t) { for (int i = 0; i < PinCount; ++i) { this[i] = ((int)(t * 4) == i) ? GpioPinValue.High : GpioPinValue.Low; } } } internal class LedTogglerAlternate : LedToggler { public LedTogglerAlternate(GpioPin[] pins) : base(pins) { } public override void run(float t) { for (int i = 0; i < PinCount; ++i) { this[i] = ((i % 2) == (int)(t * 2)) ? GpioPinValue.High : GpioPinValue.Low; } } } class Program { public static byte[] i2cReadWrite1 = new byte[1]; public static byte[] i2cReadWrite2 = new byte[2]; public static double ReadTemp(I2cDevice device) { i2cReadWrite1[0] = 0x0; device.WriteRead(i2cReadWrite1, i2cReadWrite2); double temp = ((i2cReadWrite2[0] << 8) | i2cReadWrite2[1]) / 256.0; return temp; } const float period = 0.75f; const float timePerMode = 4.0f; #if LPC1768 static int threadPin = (int)LPC1768.PinName.LED4; #elif K64F static int threadPin = (int)K64F.PinName.LED4; #else #error No target board defined. #endif static int[] pinNumbers = { #if (LPC1768) (int)LPC1768.PinName.LED1, (int)LPC1768.PinName.LED2, (int)LPC1768.PinName.LED3, #elif (K64F) (int)K64F.PinName.LED1, (int)K64F.PinName.LED2, (int)K64F.PinName.LED3, #else #error No target board defined. #endif }; static void Main() { var now = DateTime.Now.Ticks; ZeligSupport.Timer.wait_ms(1000); var now2 = DateTime.Now.Ticks; long now3 = now2 - now; Microsoft.Zelig.Runtime.Device.Instance.ProcessLog("NOW=0x%08x%08x", (int)(now3 >> 32), (int)(now3)); int currentMode = 0; int count = 0; var controller = GpioController.GetDefault(); var pins = new GpioPin[pinNumbers.Length]; for (int i = 0; i < pinNumbers.Length; ++i) { GpioPin pin = controller.OpenPin(pinNumbers[i]); // Start with all LEDs on. pin.Write(GpioPinValue.High); pin.SetDriveMode(GpioPinDriveMode.Output); pins[i] = pin; } var solitary = controller.OpenPin(threadPin); solitary.SetDriveMode(GpioPinDriveMode.Output); LedToggler[] blinkingModes = new LedToggler[3]; blinkingModes[0] = new LedTogglerSimultaneous(pins); blinkingModes[1] = new LedTogglerSequential(pins); blinkingModes[2] = new LedTogglerAlternate(pins); var blinkingTimer = new ZeligSupport.Timer(); var blinkingModeSwitchTimer = new ZeligSupport.Timer(); blinkingTimer.start(); blinkingModeSwitchTimer.start(); #region SPI #if USE_GPIO // Get the device selector by friendly name string deviceSelector = SpiDevice.GetDeviceSelector("SPI0"); var acqs = DeviceInformation.FindAllAsync(deviceSelector); string busId = acqs[0].Id; // Set up a non-default frequency #if (LPC1768) int chipSelect = (int)LPC1768.PinName.p8; #elif (K64F) int chipSelect = (int)K64F.PinName.PTD0; #else #error No target board defined. #endif SpiConnectionSettings settings = new SpiConnectionSettings(chipSelect) { ClockFrequency = 1000000, Mode = SpiMode.Mode2 }; SpiDevice spiDevice = SpiDevice.FromIdAsync(busId, settings); byte[] writeBuffer = new byte[1]; byte[] writeBuffer2 = new byte[] { 0x1, 0x2, 0x3 }; byte[] readBuffer = new byte[1]; #endif #endregion #region I2C #if USE_I2C // // I2C Init // string i2cDeviceSelector = I2cDevice.GetDeviceSelector("I2C1"); var i2cAcqs = DeviceInformation.FindAllAsync(i2cDeviceSelector); string i2cBusId = i2cAcqs[0].Id; I2cDevice i2cDevice = I2cDevice.FromIdAsync(i2cBusId, new I2cConnectionSettings(0x90) { SharingMode = I2cSharingMode.Shared }); // // Init temp sensor // i2cReadWrite2[0] = 0x1; i2cReadWrite2[1] = 0x0; i2cDevice.Write(i2cReadWrite2); #endif #endregion int pinState = 1; solitary.Write((GpioPinValue)pinState); ZeligSupport.Timer.wait_ms(300); solitary.Write((GpioPinValue)0); ZeligSupport.Timer.wait_ms(300); solitary.Write((GpioPinValue)pinState); pinState = 0; #if (USE_THREADING) var ev = new AutoResetEvent(false); var solitaryBlinker = new Thread(delegate () { while (true) { ev.WaitOne(); solitary.Write((GpioPinValue)pinState); pinState = ++pinState % 2; } }); solitaryBlinker.Start(); //var solitaryAlerter = new System.Threading.Timer( ( obj ) => { ((AutoResetEvent)obj).Set(); }, ev, 2000, 5000 ); //Microsoft.CortexM3OnMBED.Drivers.SystemTimer.Timer tm = null; //tm = // Microsoft.CortexM3OnMBED.Drivers.SystemTimer.Instance.CreateTimer((timer, currentTime) => { ev.Set(); tm.RelativeTimeout = 5 * 1000 * 1000; }); //tm.RelativeTimeout = 5 * 1000 * 1000; #endif while (true) { if (blinkingTimer.read() >= period) { blinkingTimer.reset(); } if (blinkingModeSwitchTimer.read() >= timePerMode) { currentMode = (currentMode + 1) % blinkingModes.Length; blinkingModeSwitchTimer.reset(); #region I2C_Impl #if USE_I2C try { double temp = ReadTemp(i2cDevice); if (temp < 31.0) { currentMode = 0; } else if (temp >= 31.0 && temp < 32.5) { currentMode = 1; } else { currentMode = 2; } } catch { // If an application board is not attached, we will get an Exception. // Continue as normal in this case } #endif #endregion #region SPI_Impl #if USE_SPI writeBuffer[0] = (byte)currentMode; spiDevice.TransferFullDuplex(writeBuffer, readBuffer); if (readBuffer[0] == writeBuffer[0]) { writeBuffer[0] = (byte)5; spiDevice.TransferSequential(writeBuffer, readBuffer); } spiDevice.Write(writeBuffer2); #endif #endregion count++; } blinkingModes[currentMode].run(blinkingTimer.read() / period); } } } } ================================================ FILE: Zelig/Zelig/Test/mbed/SimpleSDK/Managed/Properties/AssemblyInfo.cs ================================================ using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; // General Information about an assembly is controlled through the following // set of attributes. Change these attribute values to modify the information // associated with an assembly. [assembly: AssemblyTitle("Managed")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("Managed")] [assembly: AssemblyCopyright("Copyright © 2015")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible(false)] // The following GUID is for the ID of the typelib if this project is exposed to COM [assembly: Guid("81e4221e-1beb-4842-bb1c-6338b435e119")] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Build and Revision Numbers // by using the '*' as shown below: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("1.0.0.0")] [assembly: AssemblyFileVersion("1.0.0.0")] ================================================ FILE: Zelig/Zelig/Test/mbed/SimpleSDK/Managed/SimpleTestProgram.csproj ================================================  Debug AnyCPU {6C581F6A-34F8-4380-9BE0-279F709D13CB} Exe Properties SimpleTestProgram SimpleTestProgram v4.5 512 AnyCPU true full false $(LlilumBuildRoot)\Target\obj\$(MSBuildProjectName)\$(Configuration)\ $(LlilumBuildRoot)\Target\bin\$(MSBuildProjectName)\$(Configuration)\ DEBUG;TRACE prompt 4 true AnyCPU pdbonly true $(LlilumBuildRoot)\Target\bin\$(MSBuildProjectName)\$(Configuration)\ $(LlilumBuildRoot)\Target\obj\$(MSBuildProjectName)\$(Configuration)\ TRACE prompt 4 {1705887b-e636-4fa3-ae40-2d431af1511c} K64F {cee4d575-4b4b-42b0-b2f1-cc7198cb7306} LPC1768 {d7f2bc4e-1406-47aa-90e1-07bc4ce9410f} mbed {186f31a3-ef89-4a25-b2d5-20070702aa01} system {dc8c38d7-780b-4b13-8ace-9050e39cc51c} Windows {186f31a3-ef89-4a25-b2d5-20060509aa01} Kernel {20DC2CF5-8EED-4231-9743-6BAB96BE465C} LlilumOSAbstraction ================================================ FILE: Zelig/Zelig/Test/mbed/SimpleSDK/Native/Native.vcxproj ================================================  Debug ARM Release ARM {d3fa04af-4285-477d-a756-6c51e9a56e7a} Android Native 14.0 Llilum 1.0 $(LLILUM_GCC) Native $(LLILUM_ROOT)Zelig\ $(LLILUM_ROOT)VisualStudio\LlilumApplicationType\Llilum\1.0\ LPC1768 $(MSBuildProjectDirectory)\mbed_simple_$(LlilumBoardName).FrontEndConfig SimpleTestProgram_$(LlilumBoardName) $(LlilumSDK)source\ports\mbed\inc;$(LlilumSDK)source\inc;$(LlilumSDK)source\inc\api;$(LlilumSDK)source\inc\api\io;$(LlilumSDK)source\inc\hal $(LlilumClAdditionalOptionsLPC1768) $(LlilumClAdditionalIncludesLPC1768) $(LlilumClPreprocessorDefsLPC1768) $(LlilumLinkAdditionalDepsLPC1768);$(LlilumBuildRoot)\Target\bin\mbedOSAbstraction\$(Configuration)\mbedOSAbstraction_$(LlilumBoardName).a $(LlilumLinkAdditionalLibDirsLPC1768) $(LlilumLinkAdditionalOptionsLPC1768) $(LlilumLinkLibDepsLPC1768) $(LlilumTargetBoardArchitectureLPC1768) $(LlilumAsmAdditionalOptionsLPC1768) $(LlilumStackSizeLPC1768) $(LlilumHeapSizeLPC1768) $(LlilumClAdditionalOptionsK64F) $(LlilumClAdditionalIncludesK64F) $(LlilumClPreprocessorDefsK64F) $(LlilumLinkAdditionalDepsK64F);$(LlilumBuildRoot)\Target\bin\mbedOSAbstraction\$(Configuration)\mbedOSAbstraction_$(LlilumBoardName).a $(LlilumLinkAdditionalLibDirsK64F) $(LlilumLinkAdditionalOptionsK64F) $(LlilumLinkLibDepsK64F) $(LlilumTargetBoardArchitectureK64F) $(LlilumAsmAdditionalOptionsK64F) $(LlilumStackSizeK64F) $(LlilumHeapSizeK64F) $(LlilumClAdditionalOptionsSTM32L152) $(LlilumClAdditionalIncludesSTM32L152) $(LlilumClPreprocessorDefsSTM32L152) $(LlilumLinkAdditionalDepsSTM32L152);$(LlilumBuildRoot)\Target\bin\mbedOSAbstraction\$(Configuration)\mbedOSAbstraction_$(LlilumBoardName).a $(LlilumLinkAdditionalLibDirsSTM32L152) $(LlilumLinkAdditionalOptionsSTM32L152) $(LlilumLinkLibDepsSTM32L152) $(LlilumTargetBoardArchitectureSTM32L152) $(LlilumAsmAdditionalOptionsSTM32L152) $(LlilumStackSizeSTM32L152) $(LlilumHeapSizeSTM32L152) DynamicLibrary true $(LlilumTargetBoardArchitecture) DynamicLibrary $(LlilumTargetBoardArchitecture) false SimpleTestProgram_$(LlilumBoardName) .elf $(LlilumGccBin);$(ExecutablePath) $(LlilumBuildRoot)\Target\bin\$(ProjectName)\$(Configuration)\ *.bin;*.hex;*.elf;*.lst;*.d;*.tlog;$(ExtensionsToDeleteOnClean) $(LlilumBuildRoot)\Target\obj\$(ProjectName)\$(Configuration)\ SimpleTestProgram_$(LlilumBoardName) .elf $(LlilumGccBin);$(ExecutablePath) $(LlilumBuildRoot)\Target\bin\$(ProjectName)\$(Configuration)\ *.bin;*.hex;*.elf;*.lst;*.d;*.tlog;$(ExtensionsToDeleteOnClean) $(LlilumBuildRoot)\Target\obj\$(ProjectName)\$(Configuration)\ Use pch.h $(LlilumClAdditionalOptions) %(AdditionalOptions) $(LlilumClAdditionalIncludes);%(AdditionalIncludeDirectories);$(NativeIncludes) $(LlilumClPreprocessorDefs);DEBUG;%(PreprocessorDefinitions);__DEFAULT_STACK_SIZE=$(LlilumStackSize);__HEAP_SIZE=$(LlilumHeapSize) $(LlilumAsmAdditionalOptions) %(LlilumClAdditionalOptions) -Wa,--defsym,__HEAP_SIZE=$(LlilumHeapSize) $(LlilumLinkAdditionalDeps) $(LlilumLinkAdditionalLibDirs) $(LlilumLinkAdditionalOptions) %(AdditionalOptions) $(LlilumLinkLibDeps) Use pch.h $(LlilumClAdditionalOptions) %(AdditionalOptions) $(LlilumClAdditionalIncludes);%(AdditionalIncludeDirectories);$(NativeIncludes) $(LlilumClPreprocessorDefs);%(PreprocessorDefinitions);__DEFAULT_STACK_SIZE=$(LlilumStackSize);__HEAP_SIZE=$(LlilumHeapSize) $(LlilumAsmAdditionalOptions) %(LlilumClAdditionalOptions) -Wa,--defsym,__HEAP_SIZE=$(LlilumHeapSize) $(LlilumLinkAdditionalDeps) $(LlilumLinkAdditionalLibDirs) $(LlilumLinkAdditionalOptions) %(AdditionalOptions) $(LlilumLinkLibDeps) {2832CE7B-8065-4473-A3C7-B8B069920A9C} {612f2d6b-1976-47dc-8e69-022d42aaf62d} {186F31A3-EF89-4A25-B2D5-20070605AA02} false false false true true true true ================================================ FILE: Zelig/Zelig/Test/mbed/SimpleSDK/Native/helpers.h ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // // // Platform dependent configurations // #ifdef TARGET_LPC1768 #include "LPC17xx.h" #elif TARGET_K64F #include "MK64F12.h" #elif TARGET_STM32L152RE #include "stm32l1xx.h" #else #error Undefined plaform #endif #include "analogin_api.h" #include "gpio_api.h" #include "gpio_irq_api.h" #include "spi_api.h" #include "i2c_api.h" #include "core_cmFunc.h" #include "us_ticker_api.h" #include "serial_api.h" #include "pwmout_api.h" #include #include ================================================ FILE: Zelig/Zelig/Test/mbed/SimpleSDK/Native/mbed_simple_K64F.FrontEndConfig ================================================ ### ### Location of the Zelig assemblies. ### -CompilationSetupPath ..\..\..\..\..\ZeligBuild\Host\bin\Debug\Microsoft.Llilum.BoardConfigurations.K64F.dll -CompilationSetup Microsoft.Llilum.BoardConfigurations.K64FMBEDCompilationSetup ### ### We need to include this assembly to get the right drivers. ### -Reference Microsoft.CortexM4OnMBED -Reference Microsoft.CortexM4OnCMSISCore -Reference Microsoft.DeviceModels.ModelForCortexM4 -Reference K64F ### ### Add compilation phases, in order ### #-CompilationPhaseDisabled ReduceNumberOfTemporaries #-CompilationPhaseDisabled TransformFinallyBlocksIntoTryBlocks #-CompilationPhaseDisabled ApplyClassExtensions #-CompilationPhaseDisabled PrepareImplementationOfInternalMethods #-CompilationPhaseDisabled CrossReferenceTypeSystem #-CompilationPhaseDisabled ApplyConfigurationSettings -CompilationPhaseDisabled ResourceManagerOptimizations #-CompilationPhaseDisabled HighLevelTransformations #-CompilationPhaseDisabled PropagateCompilationConstraints #-CompilationPhaseDisabled ComputeCallsClosure #-CompilationPhaseDisabled EstimateTypeSystemReduction #-CompilationPhaseDisabled CompleteImplementationOfInternalMethods #-CompilationPhaseDisabled ReduceTypeSystem -CompilationPhaseDisabled PrepareExternalMethods #-CompilationPhaseDisabled DetectNonImplementedInternalCalls #-CompilationPhaseDisabled OrderStaticConstructors #-CompilationPhaseDisabled LayoutTypes #-CompilationPhaseDisabled HighLevelToMidLevelConversion #-CompilationPhaseDisabled FromImplicitToExplicitExceptions #-CompilationPhaseDisabled ReferenceCountingGarbageCollection -CompilationPhaseDisabled MidLevelToLowLevelConversion -CompilationPhaseDisabled ConvertUnsupportedOperatorsToMethodCalls -CompilationPhaseDisabled ExpandAggregateTypes -CompilationPhaseDisabled SplitComplexOperators -CompilationPhaseDisabled FuseOperators #-CompilationPhaseDisabled Optimizations -CompilationPhaseDisabled ConvertToSSA -CompilationPhaseDisabled PrepareForRegisterAllocation -CompilationPhaseDisabled CollectRegisterAllocationConstraints -CompilationPhaseDisabled AllocateRegisters #-CompilationPhaseDisabled GenerateImage #-CompilationPhaseDisabled Done #-DumpIR #-DumpIRpre #-DumpIRpost #-DumpIRXML -DumpLLVMIR #-ReloadState #-DumpLLVMIR_TextRepresentation -MaxProcs 8 ================================================ FILE: Zelig/Zelig/Test/mbed/SimpleSDK/Native/mbed_simple_LPC1768.FrontEndConfig ================================================ ### ### Location of the Zelig assemblies. ### -CompilationSetupPath ..\..\..\..\..\ZeligBuild\Host\bin\Debug\Microsoft.Llilum.BoardConfigurations.LPC1768.dll -CompilationSetup Microsoft.Llilum.BoardConfigurations.LPC1768MBEDCompilationSetup ### ### We need to include this assembly to get the right drivers. ### -Reference Microsoft.CortexM3OnMBED -Reference Microsoft.CortexM3OnCMSISCore -Reference Microsoft.DeviceModels.ModelForCortexM3 -Reference LPC1768 ### ### Add compilation phases, in order ### #-CompilationPhaseDisabled ReduceNumberOfTemporaries #-CompilationPhaseDisabled TransformFinallyBlocksIntoTryBlocks #-CompilationPhaseDisabled ApplyClassExtensions #-CompilationPhaseDisabled PrepareImplementationOfInternalMethods #-CompilationPhaseDisabled CrossReferenceTypeSystem #-CompilationPhaseDisabled ApplyConfigurationSettings -CompilationPhaseDisabled ResourceManagerOptimizations #-CompilationPhaseDisabled HighLevelTransformations #-CompilationPhaseDisabled PropagateCompilationConstraints #-CompilationPhaseDisabled ComputeCallsClosure #-CompilationPhaseDisabled EstimateTypeSystemReduction #-CompilationPhaseDisabled CompleteImplementationOfInternalMethods #-CompilationPhaseDisabled ReduceTypeSystem -CompilationPhaseDisabled PrepareExternalMethods #-CompilationPhaseDisabled DetectNonImplementedInternalCalls #-CompilationPhaseDisabled OrderStaticConstructors #-CompilationPhaseDisabled LayoutTypes #-CompilationPhaseDisabled HighLevelToMidLevelConversion #-CompilationPhaseDisabled FromImplicitToExplicitExceptions #-CompilationPhaseDisabled ReferenceCountingGarbageCollection -CompilationPhaseDisabled MidLevelToLowLevelConversion -CompilationPhaseDisabled ConvertUnsupportedOperatorsToMethodCalls -CompilationPhaseDisabled ExpandAggregateTypes -CompilationPhaseDisabled SplitComplexOperators -CompilationPhaseDisabled FuseOperators #-CompilationPhaseDisabled Optimizations -CompilationPhaseDisabled ConvertToSSA -CompilationPhaseDisabled PrepareForRegisterAllocation -CompilationPhaseDisabled CollectRegisterAllocationConstraints -CompilationPhaseDisabled AllocateRegisters #-CompilationPhaseDisabled GenerateImage #-CompilationPhaseDisabled Done -CompilationOption System.String GarbageCollectionManager ConservativeMarkAndSweepCollector #-DumpIR #-DumpIRpre #-DumpIRpost #-DumpIRXML -DumpLLVMIR #-ReloadState #-DumpLLVMIR_TextRepresentation -MaxProcs 8 ================================================ FILE: Zelig/Zelig/Test/mbed/SimpleSDK/Native/pch.h ================================================ ================================================ FILE: Zelig/Zelig/Test/mbed/simple/LedToggler.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // namespace Microsoft.Zelig.Test.mbed.Simple { using System; using Windows.Devices.Gpio; internal abstract class LedToggler { public LedToggler(GpioPin[] pins) { _pins = pins; } public abstract void run(float t); public int PinCount { get { return _pins.Length; } } public GpioPinValue this[int key] { get { return _pins[key].Read(); } set { _pins[key].Write(value); } } private readonly GpioPin[] _pins; }; internal class LedTogglerSimultaneous : LedToggler { public LedTogglerSimultaneous(GpioPin[] pins) : base(pins) { } public override void run(float t) { for (int i = 0; i < PinCount; ++i) { this[i] = (t < 0.5) ? GpioPinValue.High : GpioPinValue.Low; } } } internal class LedTogglerSequential : LedToggler { public LedTogglerSequential(GpioPin[] pins) : base(pins) { } public override void run(float t) { for (int i = 0; i < PinCount; ++i) { this[i] = ((int)(t * 4) == i) ? GpioPinValue.High : GpioPinValue.Low; } } } internal class LedTogglerAlternate : LedToggler { public LedTogglerAlternate(GpioPin[] pins) : base(pins) { } public override void run(float t) { for (int i = 0; i < PinCount; ++i) { this[i] = ((i % 2) == (int)(t * 2)) ? GpioPinValue.High : GpioPinValue.Low; } } } } ================================================ FILE: Zelig/Zelig/Test/mbed/simple/Program.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // namespace Microsoft.Zelig.Test.mbed.Simple { using System.Threading; using Windows.Devices.Gpio; using ZeligSupport = Microsoft.Zelig.Support.mbed; //--// internal partial class Program { private const float period = 0.75f; private const float timePerMode = 4.0f; //--// private int[] m_ledPinNumbers; private int m_threadPinNumber; private int m_pwmPinNumber; //--// internal Program() { m_ledPinNumbers = DeviceModels.Chipset.CortexM.Board.Instance.LedPins; m_pwmPinNumber = (int)DeviceModels.Chipset.CortexM.Board.Instance.PwmPins[0]; m_threadPinNumber = m_ledPinNumbers[ m_ledPinNumbers.Length - 1 ]; } private void Run() { System.Diagnostics.Debug.WriteLine( "User program starting..." ); int currentMode = 0; float periodDivider = 1; TestGpioPerf(); TestGpioInterrupt( 5 ); TestSpiLcd( ); var controller = GpioController.GetDefault(); var pins = new GpioPin[m_ledPinNumbers.Length - 1]; for (int i = 0; i < m_ledPinNumbers.Length - 1; ++i) { GpioPin pin = controller.OpenPin(m_ledPinNumbers[i]); // Start with all LEDs on. pin.Write(GpioPinValue.High); pin.SetDriveMode(GpioPinDriveMode.Output); pins[i] = pin; } var solitary = controller.OpenPin(m_threadPinNumber); solitary.SetDriveMode(GpioPinDriveMode.Output); LedToggler[] blinkingModes = new LedToggler[3]; blinkingModes[0] = new LedTogglerSimultaneous(pins); blinkingModes[1] = new LedTogglerSequential(pins); blinkingModes[2] = new LedTogglerAlternate(pins); var blinkingTimer = new ZeligSupport.Timer(); var blinkingModeSwitchTimer = new ZeligSupport.Timer(); blinkingTimer.start(); blinkingModeSwitchTimer.start(); InitSPI( ); int pinState = 1; solitary.Write((GpioPinValue)pinState); Thread.Sleep(300); solitary.Write((GpioPinValue)0); Thread.Sleep(300); solitary.Write((GpioPinValue)pinState); pinState = 0; var ev = new AutoResetEvent(false); var solitaryBlinker = new Thread(delegate () { while (true) { ev.WaitOne(500, false); solitary.Write((GpioPinValue)pinState); pinState = ++pinState % 2; } }); solitaryBlinker.Start(); var solitaryAlerter = new System.Threading.Timer((obj) => { // blink 20 times very fast int fastBlinks = 20; while (fastBlinks-- > 0) { ((AutoResetEvent)obj).Set(); Thread.Sleep(50); } }, ev, 2000, 5000); TestADC( ); TestPWM( m_pwmPinNumber ); while (true) { float readVal = TestADC( ); // If ADC isn't in use, this will always be 1 periodDivider = 1 + readVal; if (blinkingTimer.read() >= (period / periodDivider)) { blinkingTimer.reset(); } if (blinkingModeSwitchTimer.read() >= timePerMode) { currentMode = (currentMode + 1) % blinkingModes.Length; blinkingModeSwitchTimer.reset(); currentMode = TestI2C( currentMode ); TestSPI( currentMode ); } blinkingModes[currentMode].run(blinkingTimer.read() / (period / periodDivider)); } } //--// public static void Main() { new Program( ).Run( ); } } } ================================================ FILE: Zelig/Zelig/Test/mbed/simple/Program_Test__ADC.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // //#define TEST_ADC using Windows.Devices.Adc; namespace Microsoft.Zelig.Test.mbed.Simple { internal partial class Program { private static AdcController s_adcController; private static AdcChannel s_adcChannel; private static bool s_adcInitialized = false; //--// private static float TestADC() { #if TEST_ADC if(s_adcInitialized == false) { s_adcController = AdcController.GetDefaultAsync(); // This is the left potentiometer on the mBed application board s_adcChannel = s_adcController.OpenChannel(4); s_adcInitialized = true; } return ( (float)s_adcChannel.ReadValue( ) ) / s_adcController.MaxValue * 2; #else return 0; #endif } } } ================================================ FILE: Zelig/Zelig/Test/mbed/simple/Program_Test__GpioInterruptTestData.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // //#define GPIO_INTERRUPTS_PERF #define LPC1768 //#define K64F namespace Microsoft.Zelig.Test.mbed.Simple { using System; using System.Threading; using Windows.Devices.Gpio; using LPC1768 = Llilum.LPC1768; using K64F = Llilum.K64F; partial class Program { private class GpioInterruptTestData : IDisposable { private AutoResetEvent m_evtComplete; private int m_pinVal; private Llilum.Devices.Gpio.GpioPin m_pinLED; private Llilum.Devices.Gpio.GpioPin m_pinIn; private Llilum.Devices.Gpio.GpioPin m_pinOut; private Llilum.Devices.Gpio.GpioPin m_pinMon; private bool m_disposed; public GpioInterruptTestData( int LedPinNumber, int InPinNumber, int OutPinNumber, int MonitorPin ) { m_evtComplete = new AutoResetEvent( false ); m_pinVal = 1; m_pinLED = Llilum.Devices.Gpio.GpioPin.TryCreateGpioPin( LedPinNumber ); m_pinLED.Direction = Llilum.Devices.Gpio.PinDirection.Output; m_pinLED.Write( 0 ); m_pinOut = Llilum.Devices.Gpio.GpioPin.TryCreateGpioPin( OutPinNumber ); m_pinOut.Direction = Llilum.Devices.Gpio.PinDirection.Output; m_pinOut.Write( 0 ); m_pinMon = Llilum.Devices.Gpio.GpioPin.TryCreateGpioPin( MonitorPin ); m_pinMon.Direction = Llilum.Devices.Gpio.PinDirection.Output; m_pinMon.Write( 0 ); m_pinIn = Llilum.Devices.Gpio.GpioPin.TryCreateGpioPin( InPinNumber ); m_pinIn.Direction = Llilum.Devices.Gpio.PinDirection.Input; } public Llilum.Devices.Gpio.GpioPin PinLED => m_pinLED; public Llilum.Devices.Gpio.GpioPin PinIn => m_pinIn; public Llilum.Devices.Gpio.GpioPin PinOut => m_pinOut; public Llilum.Devices.Gpio.GpioPin PinMon => m_pinMon; public void TogglePinValue( ) { m_pinLED.Write( m_pinVal ); m_pinVal = m_pinVal == 1 ? 0 : 1; } public void SignalComplete( ) { m_evtComplete.Set( ); } public void WaitComplete( ) { m_evtComplete.WaitOne( ); } ~GpioInterruptTestData( ) { Dispose( false ); } public void Dispose( ) { if(!m_disposed) { Dispose( true ); GC.SuppressFinalize( this ); m_disposed = true; } } protected void Dispose( bool disposing ) { if(disposing) { s_gpioInterruptTestData = null; m_pinIn .Dispose( ); m_pinLED.Dispose( ); m_pinOut.Dispose( ); m_pinMon.Dispose( ); } } }; private static GpioInterruptTestData s_gpioInterruptTestData; //--// private static void TestGpioInterrupt( int loops ) { #if GPIO_INTERRUPTS_PERF int[] TEST_GPIO_PINS = { #if( LPC1768 ) // // LPC1768 only supports interrupts on pins P0_* and P2_* (ports 0 and 2). // P0_0 == p9, p2_0 == p26 // // On the LPC1768, pins p9, p10, p11 and LED1 are used for this tests. Pins p9 // and p10 should be physically connected with a jumper. Pin p11 is used as a // monitor pin which indicates how much time was taken to service the interrupt. // (int)LPC1768.PinName.LED1, (int)LPC1768.PinName.p9, (int)LPC1768.PinName.p10, (int)LPC1768.PinName.p11, #elif ( K64F ) // // On the Freescale FRDM K64F board, this test requires you to jumper pins // PTC5 and PTC7 together to test GPIO interrupts. Pin PTC0 can be used as // a monitor pin with an oscilloscope to measure the time to service a GPIO // interrupt from creation to event handling. // (int)K64F.PinName.LED1, (int)K64F.PinName.PTC7, (int)K64F.PinName.PTC5, (int)K64F.PinName.PTC0, #endif }; using(s_gpioInterruptTestData = new GpioInterruptTestData( TEST_GPIO_PINS[ 0 ], TEST_GPIO_PINS[ 1 ], TEST_GPIO_PINS[ 2 ], TEST_GPIO_PINS[ 3 ] )) { s_gpioInterruptTestData.PinIn.ValueChanged += HandlePinValueChanged; while(loops-- > 0) { s_gpioInterruptTestData.PinMon.Write( 1 ); s_gpioInterruptTestData.PinOut.Write( 1 ); s_gpioInterruptTestData.WaitComplete( ); s_gpioInterruptTestData.PinOut.Write( 0 ); Thread.Sleep( 2000 ); } s_gpioInterruptTestData.PinIn.ValueChanged -= HandlePinValueChanged; } #endif } private static void HandlePinValueChanged( object sender, Llilum.Devices.Gpio.PinEdge edge ) { if(s_gpioInterruptTestData != null) { s_gpioInterruptTestData.PinMon.Write( 0 ); s_gpioInterruptTestData.TogglePinValue( ); s_gpioInterruptTestData.SignalComplete( ); } } } } ================================================ FILE: Zelig/Zelig/Test/mbed/simple/Program_Test__GpioPerf.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // //#define LPC1768_FOR_GPIO_TOGGLING_PERF namespace Microsoft.Zelig.Test.mbed.Simple { using System; using LPC1768 = Llilum.LPC1768; partial class Program { private static void TestGpioPerf() { #if LPC1768_FOR_GPIO_TOGGLING_PERF using(var pinOut = Runtime.GpioProvider.Instance.CreateGpioPin( (int)LPC1768.PinName.p28 )) { pinOut.Direction = Llilum.Devices.Gpio.PinDirection.Output; pinOut.Mode = Llilum.Devices.Gpio.PinMode.Default; for(int i = 0; i<0x1000; i++) { pinOut.Write( 0 ); pinOut.Write( 1 ); } } #endif // LPC1768_FOR_GPIO_TOGGLING_PERF } } } ================================================ FILE: Zelig/Zelig/Test/mbed/simple/Program_Test__I2C.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // //#define TEST_I2C namespace Microsoft.Zelig.Test.mbed.Simple { using Windows.Devices.Enumeration; using Windows.Devices.I2c; partial class Program { private static I2cDevice s_i2cDevice = null; private static byte[] s_i2cReadWrite1 = new byte[1]; private static byte[] s_i2cReadWrite2 = new byte[2]; private static bool s_initialized = false; //--// private static int TestI2C( int currentMode ) { int mode = currentMode; #if TEST_I2C // // I2C Init // if(s_initialized == false) { string i2cDeviceSelector = I2cDevice.GetDeviceSelector("I2C1"); var i2cAcqs = DeviceInformation.FindAllAsync(i2cDeviceSelector); string i2cBusId = i2cAcqs[0].Id; s_i2cDevice = I2cDevice.FromIdAsync(i2cBusId, new I2cConnectionSettings(0x90) { SharingMode = I2cSharingMode.Shared }); // // Init temp sensor // s_i2cReadWrite2[ 0 ] = 0x1; s_i2cReadWrite2[ 1 ] = 0x0; s_i2cDevice.Write( s_i2cReadWrite2 ); s_initialized = true; } try { double temp = ReadTemp( s_i2cDevice ); System.Diagnostics.Debug.WriteLine( "Temperature: " + temp.ToString( ) + " F" ); if (temp < 31.0) { mode = 0; } else if (temp >= 31.0 && temp < 32.5) { mode = 1; } else { mode = 2; } } catch { // If an application board is not attached, we will get an Exception. // Continue as normal in this case } #endif // TEST_GPIO_PERF && LPC1768 return mode; } //--// private static double ReadTemp(I2cDevice device) { s_i2cReadWrite1[0] = 0x0; device.WriteRead( s_i2cReadWrite1, s_i2cReadWrite2 ); return ((s_i2cReadWrite2[0] << 8) | s_i2cReadWrite2[1]) / 256.0; } } } ================================================ FILE: Zelig/Zelig/Test/mbed/simple/Program_Test__PWM.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // //#define TEST_PWM namespace Microsoft.Zelig.Test.mbed.Simple { using Windows.Devices.Pwm; internal partial class Program { private static void TestPWM( int pwmPinNumber ) { #if TEST_PWM var pwmController = PwmController.GetDefaultAsync(); pwmController.SetDesiredFrequency(1000000); var pwmPin = pwmController.OpenPin( pwmPinNumber ); pwmPin.SetActiveDutyCyclePercentage(0.7F); pwmPin.Polarity = PwmPulsePolarity.ActiveLow; pwmPin.Start(); #endif } } } ================================================ FILE: Zelig/Zelig/Test/mbed/simple/Program_Test__SPI.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // //#define TEST_SPI #define LPC1768 //#define K64F #if LPC1768 using TARGET = Microsoft.Llilum.LPC1768; #elif K64F using TARGET = Microsoft.Llilum.K64F; #endif namespace Microsoft.Zelig.Test.mbed.Simple { using Windows.Devices.Enumeration; using Windows.Devices.Spi; internal partial class Program { private static SpiDevice s_spiDevice; private static byte[] s_writeBuffer = new byte[1]; private static byte[] s_writeBuffer2 = new byte[] { 0x1, 0x2, 0x3 }; private static byte[] s_readBuffer = new byte[1]; private static void InitSPI( ) { #if TEST_SPI // Get the device selector by friendly name string deviceSelector = SpiDevice.GetDeviceSelector("SPI0"); var acqs = DeviceInformation.FindAllAsync(deviceSelector); string busId = acqs[0].Id; // Set up a non-default frequency #if (LPC1768) int chipSelect = (int)TARGET.PinName.p8; #elif (K64F) int chipSelect = (int)K64F.PinName.PTD0; #else #error No target board defined. #endif SpiConnectionSettings settings = new SpiConnectionSettings(chipSelect) { ClockFrequency = 1000000, Mode = SpiMode.Mode2 }; s_spiDevice = SpiDevice.FromIdAsync(busId, settings); #endif } private static void TestSPI( int mode ) { #if TEST_SPI s_writeBuffer[0] = (byte)mode; s_spiDevice.TransferFullDuplex( s_writeBuffer, s_readBuffer ); if (s_readBuffer[0] == s_writeBuffer[0]) { s_writeBuffer[0] = (byte)5; s_spiDevice.TransferSequential( s_writeBuffer, s_readBuffer ); } s_spiDevice.Write( s_writeBuffer2 ); #endif } } } ================================================ FILE: Zelig/Zelig/Test/mbed/simple/Program_Test__SpiLcd.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // //#define TEST_SPI_LCD #define LPC1768 namespace Microsoft.Zelig.Test.mbed.Simple { using System; using System.Threading; using LPC1768 = Llilum.LPC1768; using K64F = Llilum.K64F; partial class Program { private static void TestSpiLcd( ) { #if TEST_SPI_LCD && LPC1768 int commandPin = (int)LPC1768.PinName.p8; int resetPin = (int)LPC1768.PinName.p6; int chipSelPin = (int)LPC1768.PinName.p11; Runtime.SpiChannelInfo channelInfo = Runtime.SpiProvider.Instance.GetSpiChannelInfo( 0 ); using(SpiLcdC12832 lcd = new SpiLcdC12832( channelInfo, commandPin, resetPin, chipSelPin )) { lcd.Clear( ); for(int x = 0; x<128; x++) { for(int y = 0; y<32; y++) { lcd.SetPixel( x, y, 1 ); if(0x10 == ( y & 0x10 )) { lcd.Flush( ); } } } lcd.Clear( ); Thread.Sleep( 200 ); lcd.Fill( ); for(byte contrast = 0; contrast < 0x3f; contrast++) { lcd.SetContast( contrast ); Thread.Sleep( 100 ); } } #endif // USE_SPI && LPC1768 } } } ================================================ FILE: Zelig/Zelig/Test/mbed/simple/Program_Test__Win32.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // #define WIN32 namespace Microsoft.Zelig.Test.mbed.Simple { using System; using System.Threading; internal partial class Program { static int s_Counter1 = 0; static int s_Counter2 = 0; static int s_Counter3 = 0; static void TestWin32Threading() { #if WIN32 Thread th1 = new Thread( ( ) => { int i=0; while(true) { System.Diagnostics.Debug.WriteLine( "Thread1: " + i++); Thread.Sleep(500); } } ); Thread th2 = new Thread( ( ) => { int i=0; while(true) { System.Diagnostics.Debug.WriteLine( "Thread2: " + i++); Thread.Sleep(500); } } ); Timer t1 = new Timer( (object arg) => { System.Diagnostics.Debug.WriteLine( "Timer1: " + s_Counter1++ ); }, null, 1000, 1000 ); Timer t2 = new Timer( (object arg) => { System.Diagnostics.Debug.WriteLine( "Timer2: " + s_Counter2++ ); }, null, 2000, 2000 ); Timer t3 = new Timer( (object arg) => { System.Diagnostics.Debug.WriteLine( "Timer3: " + s_Counter3++ ); }, null, 4000, 4000 ); th1.Start( ); th2.Start( ); while(true) { Thread.Sleep(-1); } #endif // WIN32 } } } ================================================ FILE: Zelig/Zelig/Test/mbed/simple/Properties/AssemblyInfo.cs ================================================ using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; // General Information about an assembly is controlled through the following // set of attributes. Change these attribute values to modify the information // associated with an assembly. [assembly: AssemblyTitle("simple")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("simple")] [assembly: AssemblyCopyright("Copyright © 2015")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible(false)] // The following GUID is for the ID of the typelib if this project is exposed to COM [assembly: Guid("aa4773c3-713c-4612-a7fa-8ad068fd2011")] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Build and Revision Numbers // by using the '*' as shown below: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("1.0.0.0")] [assembly: AssemblyFileVersion("1.0.0.0")] ================================================ FILE: Zelig/Zelig/Test/mbed/simple/SpiLcdC12832.cs ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // namespace Microsoft.Zelig.Test.mbed { using SPI = Microsoft.Llilum.Devices.Spi; using GPIO = Microsoft.Llilum.Devices.Gpio; using Runtime; using System; public class SpiLcdC12832 : IDisposable { private enum LcdSpiType : int { Command = 0, Data, } private enum LcdSpiCommand : byte { DisplayOff = 0xAE, BiasVoltage = 0xA2, SetColumn = 0xA0, VoltageResistorRation = 0x22, PowerOn = 0x2F, DisplayRAM = 0xA4, StartLineZero = 0x40, DisplayOn = 0xAF, SetContrast = 0x81, DisplayNormal = 0xA6, Page0 = 0xB0, Page1 = 0xB1, Page2 = 0xB2, Page3 = 0xB3, } private enum LcdSpiCommandDefaults : byte { Contrast = 0x17, Column = 0xC8, } private const byte c_ContrastMask = 0x3F; private const int c_SpiClockFreq = 1000000; private SPI.SpiDevice m_spi; private GPIO.GpioPin m_cmdPin; private GPIO.GpioPin m_resetPin; private byte[] m_lcdBuffer; private byte[] m_resetCmds; private byte[] m_flushCmds; public SpiLcdC12832( SPI.ISpiChannelInfo channelInfo, int commandPin, int resetPin, int csPin ) { m_spi = new SPI.SpiDevice( channelInfo, csPin, true ); m_cmdPin = GpioProvider.Instance.CreateGpioPin( commandPin ); m_resetPin = GpioProvider.Instance.CreateGpioPin( resetPin ); m_lcdBuffer = new byte[512]; m_cmdPin.Direction = GPIO.PinDirection.Output; m_cmdPin.Mode = GPIO.PinMode.Default; m_resetPin.Direction = GPIO.PinDirection.Output; m_resetPin.Mode = GPIO.PinMode.Default; m_spi.Mode = SPI.SpiMode.Cpol1Cpha1; m_spi.DataBitLength = 8; m_spi.ClockFrequency = c_SpiClockFreq; m_spi.Open(); m_resetCmds = new byte[] { (byte)LcdSpiCommand.DisplayOff, (byte)LcdSpiCommand.BiasVoltage, (byte)LcdSpiCommand.SetColumn, (byte)LcdSpiCommandDefaults.Column, (byte)LcdSpiCommand.VoltageResistorRation, (byte)LcdSpiCommand.PowerOn, //(byte)LcdSpiCommand.DisplayRAM, (byte)LcdSpiCommand.StartLineZero, (byte)LcdSpiCommand.DisplayOn, (byte)LcdSpiCommand.SetContrast, (byte)LcdSpiCommandDefaults.Contrast, (byte)LcdSpiCommand.DisplayNormal, }; m_flushCmds = new byte[] { 0x00, 0x10, (byte)LcdSpiCommand.Page0 }; Reset(); } public void SetContast( byte contrast ) { WriteCommand( LcdSpiCommand.SetContrast ); WriteCommand( (LcdSpiCommand)(contrast & c_ContrastMask) ); } public void Reset() { // reset the display m_cmdPin.Write( (int)LcdSpiType.Command ); m_resetPin.Write( 0 ); Processor.DelayMicroseconds( 50 ); m_resetPin.Write( 1 ); Processor.DelayMicroseconds( 5000 ); // Send the default setup parameters WriteCommands( m_resetCmds ); Clear( ); } public void Clear() { Array.Clear( m_lcdBuffer, 0, m_lcdBuffer.Length ); Flush( ); } public void Fill() { for(int i=0; i 128 || y > 32 || x < 0 || y < 0) { return; } if(color == 0) { m_lcdBuffer[ x + ( ( y/8 ) * 128 ) ] &= (byte)~( 1 << ( y%8 ) ); } else { m_lcdBuffer[ x + ( ( y/8 ) * 128 ) ] |= (byte)( 1 << ( y%8 ) ); } } public void Flush() { m_flushCmds[ 2 ] = (byte)LcdSpiCommand.Page0; WriteCommands( m_flushCmds ); WriteData( m_lcdBuffer, 0, 128 ); m_flushCmds[ 2 ] = (byte)LcdSpiCommand.Page1; WriteCommands( m_flushCmds ); WriteData( m_lcdBuffer, 128, 128 ); m_flushCmds[ 2 ] = (byte)LcdSpiCommand.Page2; WriteCommands( m_flushCmds ); WriteData( m_lcdBuffer, 256, 128 ); m_flushCmds[ 2 ] = (byte)LcdSpiCommand.Page3; WriteCommands( m_flushCmds ); WriteData( m_lcdBuffer, 384, 128 ); } public void Dispose( ) { m_spi.Dispose( ); m_cmdPin.Dispose( ); m_resetPin.Dispose( ); } private void WriteCommand( LcdSpiCommand command ) { WriteCommands( new byte[] { (byte)command } ); } private void WriteCommands( byte[] commands ) { m_cmdPin.Write( (int)LcdSpiType.Command ); m_spi.Write( commands, 0, commands.Length ); } private void WriteData( byte data ) { WriteCommands( new byte[] { (byte)data } ); } private void WriteData( byte[] data, int offset, int count ) { m_cmdPin.Write( (int)LcdSpiType.Data ); m_spi.Write( data, offset, count ); } } } ================================================ FILE: Zelig/Zelig/Test/mbed/simple/simple.csproj ================================================  Debug AnyCPU {77D71AF4-11C3-409B-A211-51FA19E5C1AA} Exe Properties Microsoft.Zelig.Test.mbed Microsoft.Zelig.Test.mbed.Simple v4.5 512 AnyCPU true full false $(LlilumBuildRoot)\Target\obj\$(MSBuildProjectName)\$(Configuration)\ $(LlilumBuildRoot)\Target\bin\$(Configuration)\ DEBUG;TRACE prompt 4 true AnyCPU pdbonly true $(LlilumBuildRoot)\Target\bin\$(Configuration)\ $(LlilumBuildRoot)\Target\obj\$(MSBuildProjectName)\$(Configuration)\ TRACE prompt 4 {d7f2bc4e-1406-47aa-90e1-07bc4ce9410f} mbed {d68ee51b-a898-4a77-97d8-c61254cac122} Microsoft.Llilum.Devices {186f31a3-ef89-4a25-b2d5-20070702aa01} system {dc8c38d7-780b-4b13-8ace-9050e39cc51c} Windows {e77ac86e-58ab-47b6-bc6d-3c1b4545cdfd} Microsoft.Llilum.Lwip {186f31a3-ef89-4a25-b2d5-20060509aa01} Kernel {cee4d575-4b4b-42b0-b2f1-cc7198cb7306} LPC1768 {1705887b-e636-4fa3-ae40-2d431af1511c} K64F {6194144a-f8b1-4525-829f-061df4a5645a} STM32F401 {dd4371de-85a8-49aa-b939-10e03b7ed3c9} STM32F411 {65E36DF8-5CB8-4582-851E-F5381AE4A1A7} STM32F091 {89ebdbb0-c81f-4611-b719-b385df215f8d} CortexM0OnMBED {0c522c6a-0f77-4af8-ad78-5b2415c98c51} CortexM3OnMBED {65c8eda6-ac24-4e18-a5b5-216e0f2c3906} CortexM4OnMBED {b8fe271a-cd41-435e-8766-4db7609c1007} CortexM0OnCMSIS-Core {0b37e5ba-4839-4ec4-9e36-a96bcbea2400} CortexM3OnCMSIS-Core {7fb3f581-742d-4e12-a36a-be172c574ab0} CortexM4OnCMSIS-Core {c3bfafad-a6c6-471d-a059-b3cb7e57a4ab} ModelForCortexM0 {a30eb003-94f8-4a85-8da1-006f6810a7a4} ModelForCortexM3 {ca8a6d38-528b-4faa-89b6-8fa9178de55d} ModelForCortexM4 {e4c618af-1785-472e-a070-8068e20582eb} ModelForCortexM ================================================ FILE: Zelig/Zelig/Zelig.proj ================================================ Debug $(MSBuildProjectDirectory)\..\ext-tools\TargetAdapters\TargetAdapters.sln;$(MSBuildProjectDirectory)\..\ext-tools\binutils\binutils.sln;$(MSBuildProjectDirectory)\Zelig.sln; Zelig MSBuild Targets Help Available Targets Build Rebuild Clean ================================================ FILE: Zelig/Zelig/Zelig.sln ================================================ Microsoft Visual Studio Solution File, Format Version 12.00 # Visual Studio 14 VisualStudioVersion = 14.0.25420.1 MinimumVisualStudioVersion = 10.0.40219.1 Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "MetaData", "MetaData", "{7F3A2DA3-7D2A-4F59-AEE2-3DBF75C80FFE}" EndProject Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "CodeGenerator", "CodeGenerator", "{6956D60A-260F-4B83-ABC6-EDABC5E17C84}" EndProject Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "AnalysisTools", "AnalysisTools", "{B005F882-B6AB-4CEA-9434-8BFF1876686B}" EndProject Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "DeviceModels", "DeviceModels", "{A1D7BA88-298C-440A-B626-E061EDCE4045}" EndProject Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "CompileTime", "CompileTime", "{AEF34496-481F-47EC-B246-92F7E87339C0}" EndProject Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "DebugTime", "DebugTime", "{B2AEC590-045A-4623-8DFD-357A5B54C424}" EndProject Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "RunTime", "RunTime", "{993EE84F-7CEA-40E0-BE5C-B1F38D1BA562}" EndProject Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "Framework", "Framework", "{AA94AD05-A42A-4190-8585-A82439976872}" EndProject Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "Zelig", "Zelig", "{5354D2AA-713A-4F47-BE76-2CCC57DE6EC4}" EndProject Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "TargetModels", "TargetModels", "{DC90A338-0E12-4668-8FFF-2A0BDEBC3597}" EndProject Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Importer", "CompileTime\MetaData\Importer\Importer.csproj", "{186F31A3-EF89-4A25-B2D5-20060404AA01}" EndProject Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "MetaData.UnitTest", "CompileTime\MetaData\MetaData.UnitTest\MetaData.UnitTest.csproj", "{186F31A3-EF89-4A25-B2D5-20060606AA02}" EndProject Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "mscorlib", "RunTime\Framework\mscorlib\mscorlib.csproj", "{186F31A3-EF89-4A25-B2D5-20060501AA01}" EndProject Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "mscorlib_UnitTest", "RunTime\Framework\mscorlib_UnitTest\mscorlib_UnitTest.csproj", "{186F31A3-EF89-4A25-B2D5-20060509AA02}" EndProject Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Kernel", "RunTime\Zelig\Kernel\Kernel.csproj", "{186F31A3-EF89-4A25-B2D5-20060509AA01}" EndProject Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Normalized", "CompileTime\MetaData\Normalized\Normalized.csproj", "{186F31A3-EF89-4A25-B2D5-20060510AA01}" EndProject Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "IntermediateRepresentation", "CompileTime\CodeGenerator\IntermediateRepresentation\IntermediateRepresentation.csproj", "{186F31A3-EF89-4A25-B2D5-20060603AA01}" EndProject Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "CodeGenerator.UnitTest", "CompileTime\CodeGenerator\CodeGenerator.UnitTest\CodeGenerator.UnitTest.csproj", "{186F31A3-EF89-4A25-B2D5-20060606AA01}" EndProject Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "ArmProcessorEmulation", "DebugTime\ArmProcessorEmulation\ArmProcessorEmulation.csproj", "{186F31A3-EF89-4A25-B2D5-20060704AA01}" EndProject Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "TypeSystem", "RunTime\Zelig\TypeSystem\TypeSystem.csproj", "{186F31A3-EF89-4A25-B2D5-20060720AA01}" EndProject Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "IRViewer", "CompileTime\AnalysisTools\IRViewer\IRViewer.csproj", "{186F31A3-EF89-4A25-B2D5-20060721AA01}" EndProject Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Common", "RunTime\Zelig\Common\Common.csproj", "{186F31A3-EF89-4A25-B2D5-20061218AA01}" EndProject Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "IRCompare", "CompileTime\AnalysisTools\IRCompare\IRCompare.csproj", "{186F31A3-EF89-4A25-B2D5-20070211AA01}" EndProject Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "CodeTransformation", "CompileTime\CodeGenerator\CodeTransformation\CodeTransformation.csproj", "{186F31A3-EF89-4A25-B2D5-20070222AA01}" EndProject Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Debugger", "DebugTime\Debugger\Debugger.csproj", "{186F31A3-EF89-4A25-B2D5-20070430AA01}" EndProject Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "ArmProcessor", "CompileTime\TargetModels\ArmProcessor\ArmProcessor.csproj", "{186F31A3-EF89-4A25-B2D5-20070519AA01}" EndProject Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "CommonPC", "RunTime\Zelig\CommonPC\CommonPC.csproj", "{186F31A3-EF89-4A25-B2D5-20070601AA01}" EndProject Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "FrontEnd", "CompileTime\CodeGenerator\FrontEnd\FrontEnd.csproj", "{186F31A3-EF89-4A25-B2D5-20070605AA02}" EndProject Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "ProductConfiguration", "CompileTime\TargetModels\ProductConfiguration\ProductConfiguration.csproj", "{186F31A3-EF89-4A25-B2D5-20070606AA01}" EndProject Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "system", "RunTime\Framework\system\system.csproj", "{186F31A3-EF89-4A25-B2D5-20070702AA01}" EndProject Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "ModelForLPC3180", "RunTime\DeviceModels\ModelForLPC3180\ModelForLPC3180.csproj", "{186F31A3-EF89-4A25-B2D5-20070911AA01}" EndProject Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "ModelForMM9691LP", "RunTime\DeviceModels\ModelForMM9691LP\ModelForMM9691LP.csproj", "{186F31A3-EF89-4A25-B2D5-20070724AA02}" EndProject Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "ModelForPXA27x", "RunTime\DeviceModels\ModelForPXA27x\ModelForPXA27x.csproj", "{186F31A3-EF89-4A25-B2D5-20080519AA01}" EndProject Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "VoxSoloFormFactorLoader", "RunTime\DeviceModels\VoxSoloFormFactorLoader\VoxSoloFormFactorLoader.csproj", "{186F31A3-EF89-4A25-B2D5-20070725AA01}" EndProject Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "VoxSoloFormFactor", "RunTime\DeviceModels\VoxSoloFormFactor\VoxSoloFormFactor.csproj", "{186F31A3-EF89-4A25-B2D5-20070726AA01}" EndProject Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "VoxSoloFormFactorTester", "RunTime\DeviceModels\VoxSoloFormFactorTester\VoxSoloFormFactorTester.csproj", "{186F31A3-EF89-4A25-B2D5-20070803AA01}" EndProject Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "NohauLPC3180Loader", "RunTime\DeviceModels\NohauLPC3180Loader\NohauLPC3180Loader.csproj", "{186F31A3-EF89-4A25-B2D5-20070912AA01}" EndProject Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "NohauLPC3180", "RunTime\DeviceModels\NohauLPC3180\NohauLPC3180.csproj", "{186F31A3-EF89-4A25-B2D5-20071018AA01}" EndProject Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "NohauLPC3180Tester", "RunTime\DeviceModels\NohauLPC3180Tester\NohauLPC3180Tester.csproj", "{186F31A3-EF89-4A25-B2D5-20071208AA01}" EndProject Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "InequalityGraphVisualization", "CompileTime\AnalysisTools\InequalityGraphVisualization\InequalityGraphVisualization.csproj", "{96BF0234-1D60-4401-A6B9-99839187234E}" EndProject Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "iMote2", "RunTime\DeviceModels\iMote2\iMote2.csproj", "{186F31A3-EF89-4A25-B2D5-20090606AA01}" EndProject Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "iMote2Loader", "RunTime\DeviceModels\iMote2Loader\iMote2Loader.csproj", "{186F31A3-EF89-4A25-B2D5-20080606AA02}" EndProject Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "system_core", "RunTime\Framework\System_Core\system_core.csproj", "{186F31A3-EF89-4A25-B2D5-20080628AA01}" EndProject Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "iMote2Tester", "RunTime\DeviceModels\iMote2Tester\iMote2Tester.csproj", "{186F31A3-EF89-4A25-B2D5-20080630AA01}" EndProject Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "ExternalLinking_Tester", "RunTime\DeviceModels\ExternalLinking_Tester\ExternalLinking_Tester.csproj", "{ACE86CB1-7796-4B5F-96AF-B51595944B66}" EndProject Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Loader", "DebugTime\Loader\Loader.csproj", "{F1829F0B-1A0E-4844-BF44-106F3ADDF157}" EndProject Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "FileSystemTest", "FileSystemTest\FileSystemTest.csproj", "{C165CC46-A458-478B-9167-F073EED35EB2}" EndProject Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "QuickTest", "RunTime\DeviceModels\QuickTest\QuickTest.csproj", "{FA6F295F-6DEB-4095-86F2-DEC2D2D9A038}" EndProject Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "TestMethodGen", "RunTime\DeviceModels\TestMethodGen\TestMethodGen.csproj", "{B7606EF5-A5EC-4A97-AB4A-35D00EFA2925}" EndProject Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "CryptoTest", "RunTime\DeviceModels\Perf\v8\crypto\CryptoTest\CryptoTest.csproj", "{242A3A91-4622-4463-8A89-608908C7C540}" EndProject Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "DhrystoneTest", "RunTime\DeviceModels\Perf\Dhrystone\DhrystoneTest.csproj", "{30BA8CEE-868B-4C53-85C5-DFF6FA39D035}" EndProject Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "WhetstoneTest", "RunTime\DeviceModels\Perf\Whetstone\WhetstoneTest.csproj", "{22248085-CA53-485F-9A71-968A7AC42B04}" EndProject Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "FileSystemSample", "RunTime\DeviceModels\FileSystemSample\FileSystemSample.csproj", "{64874F12-60A0-4B5B-ACC6-616C530F430E}" EndProject Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "Test", "Test", "{3E953D4D-61BB-48CA-B996-90A5736BFA58}" EndProject Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "mbed", "mbed", "{79F07A26-A95A-45AB-B6B6-325A63AF1065}" EndProject Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "simple", "Test\mbed\simple\simple.csproj", "{77D71AF4-11C3-409B-A211-51FA19E5C1AA}" EndProject Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "LibLLVM", "CompileTime\Llvm.NET\LibLLVM\LibLLVM.vcxproj", "{6C77A7DE-D464-430F-96A9-A64768763B5F}" EndProject Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Llvm.NET", "CompileTime\Llvm.NET\Llvm.NET\Llvm.NET.csproj", "{0162C8CE-6641-4922-8664-F8A44356FBF7}" EndProject Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "mbed", "RunTime\DeviceModels\mbed\mbed.csproj", "{D7F2BC4E-1406-47AA-90E1-07BC4CE9410F}" EndProject Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "CortexM", "CortexM", "{7FC1F0E6-A46C-4A0C-AA6F-233EEFEB33D3}" EndProject Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "Legacy", "Legacy", "{6BBE2750-648C-4CC6-A08C-6454CB98812B}" EndProject Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "Test", "Test", "{700EC40D-81C7-45CC-8CB6-F92803BBB204}" EndProject Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "Support", "Support", "{8988313A-FAC7-4CF9-B373-C4034FC01EFA}" EndProject Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "NativeHelpers", "Test\mbed\NativeHelpers\NativeHelpers.vcxproj", "{6367CACE-0511-485D-9AE5-698F7E600839}" EndProject Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "Boards", "Boards", "{EE8431BB-2720-4F75-AD08-1E3307F68BE4}" EndProject Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "CompileTime", "CompileTime", "{DFC4F889-3803-4B12-B792-30504AD8C85A}" EndProject Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "System.Runtime.WindowsRuntime", "RunTime\Framework\System.Runtime.WindowsRuntime\System.Runtime.WindowsRuntime.csproj", "{016691CA-A31F-4273-A4D2-C5F6E4B3662D}" EndProject Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "SimpleTestProgram", "Test\mbed\SimpleSDK\Managed\SimpleTestProgram.csproj", "{6C581F6A-34F8-4380-9BE0-279F709D13CB}" EndProject Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "Native", "Test\mbed\SimpleSDK\Native\Native.vcxproj", "{D3FA04AF-4285-477D-A756-6C51E9A56E7A}" EndProject Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "SDK", "SDK", "{35A43865-50F4-423A-ACF6-B3AEC2511716}" EndProject Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "make", "make", "{F5824561-14E4-4E5E-83A4-CFE95F128829}" EndProject Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "M3", "M3", "{CF168235-325F-448A-B455-3382C2B9DA48}" EndProject Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "M4", "M4", "{CF4FC546-608D-4BE4-8A67-1E8C9F3526A3}" EndProject Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "CortexM3OnCMSIS-Core", "RunTime\DeviceModels\CortexM3OnCMSIS-Core\CortexM3OnCMSIS-Core.csproj", "{0B37E5BA-4839-4EC4-9E36-A96BCBEA2400}" EndProject Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "CortexM3OnMBED", "RunTime\DeviceModels\CortexM3OnMBED\CortexM3OnMBED.csproj", "{0C522C6A-0F77-4AF8-AD78-5B2415C98C51}" EndProject Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "ModelForCortexM3", "RunTime\DeviceModels\ModelForCortexM3\ModelForCortexM3.csproj", "{A30EB003-94F8-4A85-8DA1-006F6810A7A4}" EndProject Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "CortexM4OnCMSIS-Core", "RunTime\DeviceModels\CortexM4OnCMSIS-Core\CortexM4OnCMSIS-Core.csproj", "{7FB3F581-742D-4E12-A36A-BE172C574AB0}" EndProject Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "CortexM4OnMBED", "RunTime\DeviceModels\CortexM4OnMBED\CortexM4OnMBED.csproj", "{65C8EDA6-AC24-4E18-A5B5-216E0F2C3906}" EndProject Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "ModelForCortexM4", "RunTime\DeviceModels\ModelForCortexM4\ModelForCortexM4.csproj", "{CA8A6D38-528B-4FAA-89B6-8FA9178DE55D}" EndProject Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Microsoft.Llilum.Devices", "RunTime\Framework\Llilum\Devices\Microsoft.Llilum.Devices.csproj", "{D68EE51B-A898-4A77-97D8-C61254CAC122}" EndProject Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "K64F", "..\BoardConfigurations\K64F\Board\K64F.csproj", "{1705887B-E636-4FA3-AE40-2D431AF1511C}" EndProject Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "LPC1768", "..\BoardConfigurations\LPC1768\Board\LPC1768.csproj", "{CEE4D575-4B4B-42B0-B2F1-CC7198CB7306}" EndProject Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "Tests", "Tests", "{999FF4E4-118C-4705-839C-3ECF28854C8F}" EndProject Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "CompilerTests", "Test\CompileTime\CompilerTests\CompilerTests.csproj", "{4D364D69-06AF-4277-8828-3B4313533A5B}" EndProject Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "RunTime", "RunTime", "{9AC4A5AB-04B5-46C2-9020-AC70D8E2DF8D}" EndProject Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "NETMF", "NETMF", "{0FCFB940-AFD7-450C-9A58-936A5349CD59}" EndProject Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "mscorlib", "mscorlib", "{8BD964E3-ADBC-497C-B6CB-16C762771797}" EndProject Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Test_mscorlib", "Test\RunTime\NETMF\mscorlib\Test_mscorlib.csproj", "{E149B569-516B-4C88-A7B1-EBD02E12DD1E}" EndProject Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Test_Common", "Test\Common\Test_Common.csproj", "{B649B569-516B-4C88-A7B1-EBD02E12DD99}" EndProject Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "TestRunner", "Test\Runner\TestRunner.csproj", "{A8C7CEC1-FF02-4ECA-967B-72825F4940AE}" EndProject Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "K64FConfiguration", "..\BoardConfigurations\K64F\Configuration\K64FConfiguration.csproj", "{9863D039-AB21-4710-960E-7303919552C6}" EndProject Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "LPC1768Configuration", "..\BoardConfigurations\LPC1768\Configuration\LPC1768Configuration.csproj", "{C17E59D0-2D64-4012-8A98-D184D0CF8A49}" EndProject Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Windows", "RunTime\Framework\Windows\Windows.csproj", "{DC8C38D7-780B-4B13-8ACE-9050E39CC51C}" EndProject Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "LlilumRTOSAbstractions", "LlilumRTOSAbstractions", "{110E8B86-4F26-458A-97C3-55F2BA1E60DE}" EndProject Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "Ports", "Ports", "{3ECE9965-D0E8-493E-848C-A43D96E26F16}" EndProject Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "LlilumOSAbstraction", "RunTime\Zelig\LlilumOSAbstraction\LlilumOSAbstraction.csproj", "{20DC2CF5-8EED-4231-9743-6BAB96BE465C}" EndProject Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "MbedOSAbstraction", "..\os_layer\ports\mbed\MbedOSAbstraction.vcxproj", "{2832CE7B-8065-4473-A3C7-B8B069920A9C}" EndProject Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "lwIP", "lwIP", "{89BAA5C6-B788-4B69-AD54-E78A52E1AF33}" EndProject Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Microsoft.Llilum.Lwip", "RunTime\DeviceModels\lwIP\Microsoft.Llilum.Lwip.csproj", "{E77AC86E-58AB-47B6-BC6D-3C1B4545CDFD}" EndProject Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "SimpleNet", "Test\mbed\SimpleNet\SimpleNet.csproj", "{40710089-C1C3-49D9-93B6-07A25219E5E8}" EndProject Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "Desktop", "Desktop", "{A15E99D7-3C46-406C-8850-4674CD3FE97C}" EndProject Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "Net", "Net", "{F761A686-A69C-4081-BD23-AFD45670DD69}" EndProject Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "NetworkTest", "Test\Desktop\Net\NetworkTest\NetworkTest.csproj", "{769F9326-B779-4F35-BC49-87E15CDF2A8C}" EndProject Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "STM32F411", "..\BoardConfigurations\STM32F411\Board\STM32F411.csproj", "{DD4371DE-85A8-49AA-B939-10E03B7ED3C9}" EndProject Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "STM32F411Configuration", "..\BoardConfigurations\STM32F411\Configuration\STM32F411Configuration.csproj", "{9B0EDB62-1E62-492D-B807-A8501EEE8400}" EndProject Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "LlilumCMSIS-RTOS", "RunTime\Zelig\LlilumCMSIS-RTOS\LlilumCMSIS-RTOS.csproj", "{93219A45-914C-44B7-A6CB-66849879C8B1}" EndProject Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "SimpleHttp", "Test\mbed\SimpleHttp\SimpleHttp.csproj", "{2D6185A8-A5FE-4FDF-874A-96037C37BD41}" EndProject Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "System", "System", "{9164B9A3-F6F0-49F0-845B-880534BE7D41}" EndProject Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Test_System", "Test\RunTime\NETMF\System\Test_System.csproj", "{54125FC8-5C6D-4F4B-92B8-3377FE1D92E1}" EndProject Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "Elf", "Elf", "{8B9C17E7-DA84-4C8E-8F1B-0E57C4B699D4}" EndProject Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "ReadElf", "DebugTime\Elf\ReadElf\ReadElf.csproj", "{A4CB8DA8-AB1A-4977-B1C5-9AE27EBB6FC7}" EndProject Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Elflib", "DebugTime\Elf\ElfLib\Elflib.csproj", "{37193A86-BA04-4A3E-9DF8-656DF455E952}" EndProject Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "OS", "OS", "{19DD0BB4-AB2C-4B06-9D83-0FEE635566BD}" EndProject Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "HttpTest", "Test\Desktop\Net\HttpTest\HttpTest.csproj", "{0F0DC8C5-349B-453D-94F2-123205E3EADD}" EndProject Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "STM32F401", "..\BoardConfigurations\STM32F401\Board\STM32F401.csproj", "{6194144A-F8B1-4525-829F-061DF4A5645A}" EndProject Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "STM32F401Configuration", "..\BoardConfigurations\STM32F401\Configuration\STM32F401Configuration.csproj", "{7F600371-17AB-41F2-96AB-39C8AA2389E1}" EndProject Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "STM32F091", "..\BoardConfigurations\STM32F091\Board\STM32F091.csproj", "{65E36DF8-5CB8-4582-851E-F5381AE4A1A7}" EndProject Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "STM32F091Configuration", "..\BoardConfigurations\STM32F091\Configuration\STM32F091Configuration.csproj", "{C183991C-1F27-4665-A884-FD977D2AD359}" EndProject Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "M0", "M0", "{DFD09237-A74B-46A4-AA30-F711EEDA4AF7}" EndProject Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "M", "M", "{910EC8B6-B1B8-4800-AEF6-0BD45471FAFB}" EndProject Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "ModelForCortexM", "RunTime\DeviceModels\ModelForCortexM\ModelForCortexM.csproj", "{E4C618AF-1785-472E-A070-8068E20582EB}" EndProject Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "ModelForCortexM0", "RunTime\DeviceModels\ModelForCortexM0\ModelForCortexM0.csproj", "{C3BFAFAD-A6C6-471D-A059-B3CB7E57A4AB}" EndProject Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "CortexM0OnCMSIS-Core", "RunTime\DeviceModels\CortexM0OnCMSIS-Core\CortexM0OnCMSIS-Core.csproj", "{B8FE271A-CD41-435E-8766-4DB7609C1007}" EndProject Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "CortexM0OnMBED", "RunTime\DeviceModels\CortexM0OnMBED\CortexM0OnMBED.csproj", "{89EBDBB0-C81F-4611-B719-B385DF215F8D}" EndProject Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Win32Configuration", "..\BoardConfigurations\Win32\Configuration\Win32Configuration.csproj", "{F84C2434-C768-4295-955B-E032E3A18FC3}" EndProject Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "ModelForWin32", "RunTime\DeviceModels\ModelForWin32\ModelForWin32.csproj", "{B157F660-AED5-49A2-99DB-FE60855DC5F4}" EndProject Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Win32Processor", "CompileTime\TargetModels\Win32EmuProcessor\Win32Processor.csproj", "{46478CA2-8163-47A0-8C65-3ACFC21CE57F}" EndProject Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "Win32", "Win32", "{52C76D47-FE0A-4D7C-B11F-64B057D96523}" EndProject Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "LlilumWin32", "Test\LlilumWin32\LlilumWin32.vcxproj", "{09CD4F6F-17D7-4A56-A8FD-797EBF2543DF}" EndProject Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "Win32Abstraction", "..\os_layer\ports\win32\Win32Abstraction\Win32Abstraction.vcxproj", "{E18A0A2A-60AF-4819-9F64-FD347E222144}" EndProject Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "STM32L152", "..\BoardConfigurations\STM32L152\Board\STM32L152.csproj", "{F0229144-F7C4-4456-8442-5E816C6E8FBC}" EndProject Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "STM32L152Configuration", "..\BoardConfigurations\STM32L152\Configuration\STM32L152Configuration.csproj", "{F222E0D3-0FFF-41F4-91EE-400C4E4E043D}" EndProject Global GlobalSection(SolutionConfigurationPlatforms) = preSolution Debug|Any CPU = Debug|Any CPU Debug|ARM = Debug|ARM Debug|Mixed Platforms = Debug|Mixed Platforms Debug|Win32 = Debug|Win32 Debug|x64 = Debug|x64 Instrumentation|Any CPU = Instrumentation|Any CPU Instrumentation|ARM = Instrumentation|ARM Instrumentation|Mixed Platforms = Instrumentation|Mixed Platforms Instrumentation|Win32 = Instrumentation|Win32 Instrumentation|x64 = Instrumentation|x64 Release|Any CPU = Release|Any CPU Release|ARM = Release|ARM Release|Mixed Platforms = Release|Mixed Platforms Release|Win32 = Release|Win32 Release|x64 = Release|x64 EndGlobalSection GlobalSection(ProjectConfigurationPlatforms) = postSolution {186F31A3-EF89-4A25-B2D5-20060404AA01}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {186F31A3-EF89-4A25-B2D5-20060404AA01}.Debug|Any CPU.Build.0 = Debug|Any CPU {186F31A3-EF89-4A25-B2D5-20060404AA01}.Debug|ARM.ActiveCfg = Debug|Any CPU {186F31A3-EF89-4A25-B2D5-20060404AA01}.Debug|ARM.Build.0 = Debug|Any CPU {186F31A3-EF89-4A25-B2D5-20060404AA01}.Debug|Mixed Platforms.ActiveCfg = Debug|Any CPU {186F31A3-EF89-4A25-B2D5-20060404AA01}.Debug|Mixed Platforms.Build.0 = Debug|Any CPU {186F31A3-EF89-4A25-B2D5-20060404AA01}.Debug|Win32.ActiveCfg = Debug|Any CPU {186F31A3-EF89-4A25-B2D5-20060404AA01}.Debug|Win32.Build.0 = Debug|Any CPU {186F31A3-EF89-4A25-B2D5-20060404AA01}.Debug|x64.ActiveCfg = Debug|Any CPU {186F31A3-EF89-4A25-B2D5-20060404AA01}.Debug|x64.Build.0 = Debug|Any CPU {186F31A3-EF89-4A25-B2D5-20060404AA01}.Instrumentation|Any CPU.ActiveCfg = Instrumentation|Any CPU {186F31A3-EF89-4A25-B2D5-20060404AA01}.Instrumentation|Any CPU.Build.0 = Instrumentation|Any CPU {186F31A3-EF89-4A25-B2D5-20060404AA01}.Instrumentation|ARM.ActiveCfg = Instrumentation|Any CPU {186F31A3-EF89-4A25-B2D5-20060404AA01}.Instrumentation|ARM.Build.0 = Instrumentation|Any CPU {186F31A3-EF89-4A25-B2D5-20060404AA01}.Instrumentation|Mixed Platforms.ActiveCfg = Instrumentation|Any CPU {186F31A3-EF89-4A25-B2D5-20060404AA01}.Instrumentation|Mixed Platforms.Build.0 = Instrumentation|Any CPU {186F31A3-EF89-4A25-B2D5-20060404AA01}.Instrumentation|Win32.ActiveCfg = Instrumentation|Any CPU {186F31A3-EF89-4A25-B2D5-20060404AA01}.Instrumentation|Win32.Build.0 = Instrumentation|Any CPU {186F31A3-EF89-4A25-B2D5-20060404AA01}.Instrumentation|x64.ActiveCfg = Instrumentation|Any CPU {186F31A3-EF89-4A25-B2D5-20060404AA01}.Instrumentation|x64.Build.0 = Instrumentation|Any CPU {186F31A3-EF89-4A25-B2D5-20060404AA01}.Release|Any CPU.ActiveCfg = Release|Any CPU {186F31A3-EF89-4A25-B2D5-20060404AA01}.Release|Any CPU.Build.0 = Release|Any CPU {186F31A3-EF89-4A25-B2D5-20060404AA01}.Release|ARM.ActiveCfg = Release|Any CPU {186F31A3-EF89-4A25-B2D5-20060404AA01}.Release|ARM.Build.0 = Release|Any CPU {186F31A3-EF89-4A25-B2D5-20060404AA01}.Release|Mixed Platforms.ActiveCfg = Release|Any CPU {186F31A3-EF89-4A25-B2D5-20060404AA01}.Release|Mixed Platforms.Build.0 = Release|Any CPU {186F31A3-EF89-4A25-B2D5-20060404AA01}.Release|Win32.ActiveCfg = Release|Any CPU {186F31A3-EF89-4A25-B2D5-20060404AA01}.Release|Win32.Build.0 = Release|Any CPU {186F31A3-EF89-4A25-B2D5-20060404AA01}.Release|x64.ActiveCfg = Release|Any CPU {186F31A3-EF89-4A25-B2D5-20060404AA01}.Release|x64.Build.0 = Release|Any CPU {186F31A3-EF89-4A25-B2D5-20060606AA02}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {186F31A3-EF89-4A25-B2D5-20060606AA02}.Debug|Any CPU.Build.0 = Debug|Any CPU {186F31A3-EF89-4A25-B2D5-20060606AA02}.Debug|ARM.ActiveCfg = Debug|Any CPU {186F31A3-EF89-4A25-B2D5-20060606AA02}.Debug|ARM.Build.0 = Debug|Any CPU {186F31A3-EF89-4A25-B2D5-20060606AA02}.Debug|Mixed Platforms.ActiveCfg = Debug|Any CPU {186F31A3-EF89-4A25-B2D5-20060606AA02}.Debug|Mixed Platforms.Build.0 = Debug|Any CPU {186F31A3-EF89-4A25-B2D5-20060606AA02}.Debug|Win32.ActiveCfg = Debug|Any CPU {186F31A3-EF89-4A25-B2D5-20060606AA02}.Debug|Win32.Build.0 = Debug|Any CPU {186F31A3-EF89-4A25-B2D5-20060606AA02}.Debug|x64.ActiveCfg = Debug|Any CPU {186F31A3-EF89-4A25-B2D5-20060606AA02}.Debug|x64.Build.0 = Debug|Any CPU {186F31A3-EF89-4A25-B2D5-20060606AA02}.Instrumentation|Any CPU.ActiveCfg = Instrumentation|Any CPU {186F31A3-EF89-4A25-B2D5-20060606AA02}.Instrumentation|Any CPU.Build.0 = Instrumentation|Any CPU {186F31A3-EF89-4A25-B2D5-20060606AA02}.Instrumentation|ARM.ActiveCfg = Instrumentation|Any CPU {186F31A3-EF89-4A25-B2D5-20060606AA02}.Instrumentation|ARM.Build.0 = Instrumentation|Any CPU {186F31A3-EF89-4A25-B2D5-20060606AA02}.Instrumentation|Mixed Platforms.ActiveCfg = Instrumentation|Any CPU {186F31A3-EF89-4A25-B2D5-20060606AA02}.Instrumentation|Mixed Platforms.Build.0 = Instrumentation|Any CPU {186F31A3-EF89-4A25-B2D5-20060606AA02}.Instrumentation|Win32.ActiveCfg = Instrumentation|Any CPU {186F31A3-EF89-4A25-B2D5-20060606AA02}.Instrumentation|Win32.Build.0 = Instrumentation|Any CPU {186F31A3-EF89-4A25-B2D5-20060606AA02}.Instrumentation|x64.ActiveCfg = Instrumentation|Any CPU {186F31A3-EF89-4A25-B2D5-20060606AA02}.Instrumentation|x64.Build.0 = Instrumentation|Any CPU {186F31A3-EF89-4A25-B2D5-20060606AA02}.Release|Any CPU.ActiveCfg = Release|Any CPU {186F31A3-EF89-4A25-B2D5-20060606AA02}.Release|Any CPU.Build.0 = Release|Any CPU {186F31A3-EF89-4A25-B2D5-20060606AA02}.Release|ARM.ActiveCfg = Release|Any CPU {186F31A3-EF89-4A25-B2D5-20060606AA02}.Release|ARM.Build.0 = Release|Any CPU {186F31A3-EF89-4A25-B2D5-20060606AA02}.Release|Mixed Platforms.ActiveCfg = Release|Any CPU {186F31A3-EF89-4A25-B2D5-20060606AA02}.Release|Mixed Platforms.Build.0 = Release|Any CPU {186F31A3-EF89-4A25-B2D5-20060606AA02}.Release|Win32.ActiveCfg = Release|Any CPU {186F31A3-EF89-4A25-B2D5-20060606AA02}.Release|Win32.Build.0 = Release|Any CPU {186F31A3-EF89-4A25-B2D5-20060606AA02}.Release|x64.ActiveCfg = Release|Any CPU {186F31A3-EF89-4A25-B2D5-20060606AA02}.Release|x64.Build.0 = Release|Any CPU {186F31A3-EF89-4A25-B2D5-20060501AA01}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {186F31A3-EF89-4A25-B2D5-20060501AA01}.Debug|Any CPU.Build.0 = Debug|Any CPU {186F31A3-EF89-4A25-B2D5-20060501AA01}.Debug|ARM.ActiveCfg = Debug|Any CPU {186F31A3-EF89-4A25-B2D5-20060501AA01}.Debug|ARM.Build.0 = Debug|Any CPU {186F31A3-EF89-4A25-B2D5-20060501AA01}.Debug|Mixed Platforms.ActiveCfg = Debug|Any CPU {186F31A3-EF89-4A25-B2D5-20060501AA01}.Debug|Mixed Platforms.Build.0 = Debug|Any CPU {186F31A3-EF89-4A25-B2D5-20060501AA01}.Debug|Win32.ActiveCfg = Debug|Any CPU {186F31A3-EF89-4A25-B2D5-20060501AA01}.Debug|Win32.Build.0 = Debug|Any CPU {186F31A3-EF89-4A25-B2D5-20060501AA01}.Debug|x64.ActiveCfg = Debug|Any CPU {186F31A3-EF89-4A25-B2D5-20060501AA01}.Debug|x64.Build.0 = Debug|Any CPU {186F31A3-EF89-4A25-B2D5-20060501AA01}.Instrumentation|Any CPU.ActiveCfg = Instrumentation|Any CPU {186F31A3-EF89-4A25-B2D5-20060501AA01}.Instrumentation|Any CPU.Build.0 = Instrumentation|Any CPU {186F31A3-EF89-4A25-B2D5-20060501AA01}.Instrumentation|ARM.ActiveCfg = Instrumentation|Any CPU {186F31A3-EF89-4A25-B2D5-20060501AA01}.Instrumentation|ARM.Build.0 = Instrumentation|Any CPU {186F31A3-EF89-4A25-B2D5-20060501AA01}.Instrumentation|Mixed Platforms.ActiveCfg = Instrumentation|Any CPU {186F31A3-EF89-4A25-B2D5-20060501AA01}.Instrumentation|Mixed Platforms.Build.0 = Instrumentation|Any CPU {186F31A3-EF89-4A25-B2D5-20060501AA01}.Instrumentation|Win32.ActiveCfg = Instrumentation|Any CPU {186F31A3-EF89-4A25-B2D5-20060501AA01}.Instrumentation|Win32.Build.0 = Instrumentation|Any CPU {186F31A3-EF89-4A25-B2D5-20060501AA01}.Instrumentation|x64.ActiveCfg = Instrumentation|Any CPU {186F31A3-EF89-4A25-B2D5-20060501AA01}.Instrumentation|x64.Build.0 = Instrumentation|Any CPU {186F31A3-EF89-4A25-B2D5-20060501AA01}.Release|Any CPU.ActiveCfg = Release|Any CPU {186F31A3-EF89-4A25-B2D5-20060501AA01}.Release|Any CPU.Build.0 = Release|Any CPU {186F31A3-EF89-4A25-B2D5-20060501AA01}.Release|ARM.ActiveCfg = Release|Any CPU {186F31A3-EF89-4A25-B2D5-20060501AA01}.Release|ARM.Build.0 = Release|Any CPU {186F31A3-EF89-4A25-B2D5-20060501AA01}.Release|Mixed Platforms.ActiveCfg = Release|Any CPU {186F31A3-EF89-4A25-B2D5-20060501AA01}.Release|Mixed Platforms.Build.0 = Release|Any CPU {186F31A3-EF89-4A25-B2D5-20060501AA01}.Release|Win32.ActiveCfg = Release|Any CPU {186F31A3-EF89-4A25-B2D5-20060501AA01}.Release|Win32.Build.0 = Release|Any CPU {186F31A3-EF89-4A25-B2D5-20060501AA01}.Release|x64.ActiveCfg = Release|Any CPU {186F31A3-EF89-4A25-B2D5-20060501AA01}.Release|x64.Build.0 = Release|Any CPU {186F31A3-EF89-4A25-B2D5-20060509AA02}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {186F31A3-EF89-4A25-B2D5-20060509AA02}.Debug|Any CPU.Build.0 = Debug|Any CPU {186F31A3-EF89-4A25-B2D5-20060509AA02}.Debug|ARM.ActiveCfg = Debug|Any CPU {186F31A3-EF89-4A25-B2D5-20060509AA02}.Debug|ARM.Build.0 = Debug|Any CPU {186F31A3-EF89-4A25-B2D5-20060509AA02}.Debug|Mixed Platforms.ActiveCfg = Debug|Any CPU {186F31A3-EF89-4A25-B2D5-20060509AA02}.Debug|Mixed Platforms.Build.0 = Debug|Any CPU {186F31A3-EF89-4A25-B2D5-20060509AA02}.Debug|Win32.ActiveCfg = Debug|Any CPU {186F31A3-EF89-4A25-B2D5-20060509AA02}.Debug|Win32.Build.0 = Debug|Any CPU {186F31A3-EF89-4A25-B2D5-20060509AA02}.Debug|x64.ActiveCfg = Debug|Any CPU {186F31A3-EF89-4A25-B2D5-20060509AA02}.Debug|x64.Build.0 = Debug|Any CPU {186F31A3-EF89-4A25-B2D5-20060509AA02}.Instrumentation|Any CPU.ActiveCfg = Instrumentation|Any CPU {186F31A3-EF89-4A25-B2D5-20060509AA02}.Instrumentation|Any CPU.Build.0 = Instrumentation|Any CPU {186F31A3-EF89-4A25-B2D5-20060509AA02}.Instrumentation|ARM.ActiveCfg = Instrumentation|Any CPU {186F31A3-EF89-4A25-B2D5-20060509AA02}.Instrumentation|ARM.Build.0 = Instrumentation|Any CPU {186F31A3-EF89-4A25-B2D5-20060509AA02}.Instrumentation|Mixed Platforms.ActiveCfg = Instrumentation|Any CPU {186F31A3-EF89-4A25-B2D5-20060509AA02}.Instrumentation|Mixed Platforms.Build.0 = Instrumentation|Any CPU {186F31A3-EF89-4A25-B2D5-20060509AA02}.Instrumentation|Win32.ActiveCfg = Instrumentation|Any CPU {186F31A3-EF89-4A25-B2D5-20060509AA02}.Instrumentation|Win32.Build.0 = Instrumentation|Any CPU {186F31A3-EF89-4A25-B2D5-20060509AA02}.Instrumentation|x64.ActiveCfg = Instrumentation|Any CPU {186F31A3-EF89-4A25-B2D5-20060509AA02}.Instrumentation|x64.Build.0 = Instrumentation|Any CPU {186F31A3-EF89-4A25-B2D5-20060509AA02}.Release|Any CPU.ActiveCfg = Release|Any CPU {186F31A3-EF89-4A25-B2D5-20060509AA02}.Release|Any CPU.Build.0 = Release|Any CPU {186F31A3-EF89-4A25-B2D5-20060509AA02}.Release|ARM.ActiveCfg = Release|Any CPU {186F31A3-EF89-4A25-B2D5-20060509AA02}.Release|ARM.Build.0 = Release|Any CPU {186F31A3-EF89-4A25-B2D5-20060509AA02}.Release|Mixed Platforms.ActiveCfg = Release|Any CPU {186F31A3-EF89-4A25-B2D5-20060509AA02}.Release|Mixed Platforms.Build.0 = Release|Any CPU {186F31A3-EF89-4A25-B2D5-20060509AA02}.Release|Win32.ActiveCfg = Release|Any CPU {186F31A3-EF89-4A25-B2D5-20060509AA02}.Release|Win32.Build.0 = Release|Any CPU {186F31A3-EF89-4A25-B2D5-20060509AA02}.Release|x64.ActiveCfg = Release|Any CPU {186F31A3-EF89-4A25-B2D5-20060509AA02}.Release|x64.Build.0 = Release|Any CPU {186F31A3-EF89-4A25-B2D5-20060509AA01}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {186F31A3-EF89-4A25-B2D5-20060509AA01}.Debug|Any CPU.Build.0 = Debug|Any CPU {186F31A3-EF89-4A25-B2D5-20060509AA01}.Debug|ARM.ActiveCfg = Debug|Any CPU {186F31A3-EF89-4A25-B2D5-20060509AA01}.Debug|ARM.Build.0 = Debug|Any CPU {186F31A3-EF89-4A25-B2D5-20060509AA01}.Debug|Mixed Platforms.ActiveCfg = Debug|Any CPU {186F31A3-EF89-4A25-B2D5-20060509AA01}.Debug|Mixed Platforms.Build.0 = Debug|Any CPU {186F31A3-EF89-4A25-B2D5-20060509AA01}.Debug|Win32.ActiveCfg = Debug|Any CPU {186F31A3-EF89-4A25-B2D5-20060509AA01}.Debug|Win32.Build.0 = Debug|Any CPU {186F31A3-EF89-4A25-B2D5-20060509AA01}.Debug|x64.ActiveCfg = Debug|Any CPU {186F31A3-EF89-4A25-B2D5-20060509AA01}.Debug|x64.Build.0 = Debug|Any CPU {186F31A3-EF89-4A25-B2D5-20060509AA01}.Instrumentation|Any CPU.ActiveCfg = Instrumentation|Any CPU {186F31A3-EF89-4A25-B2D5-20060509AA01}.Instrumentation|Any CPU.Build.0 = Instrumentation|Any CPU {186F31A3-EF89-4A25-B2D5-20060509AA01}.Instrumentation|ARM.ActiveCfg = Instrumentation|Any CPU {186F31A3-EF89-4A25-B2D5-20060509AA01}.Instrumentation|ARM.Build.0 = Instrumentation|Any CPU {186F31A3-EF89-4A25-B2D5-20060509AA01}.Instrumentation|Mixed Platforms.ActiveCfg = Instrumentation|Any CPU {186F31A3-EF89-4A25-B2D5-20060509AA01}.Instrumentation|Mixed Platforms.Build.0 = Instrumentation|Any CPU {186F31A3-EF89-4A25-B2D5-20060509AA01}.Instrumentation|Win32.ActiveCfg = Instrumentation|Any CPU {186F31A3-EF89-4A25-B2D5-20060509AA01}.Instrumentation|Win32.Build.0 = Instrumentation|Any CPU {186F31A3-EF89-4A25-B2D5-20060509AA01}.Instrumentation|x64.ActiveCfg = Instrumentation|Any CPU {186F31A3-EF89-4A25-B2D5-20060509AA01}.Instrumentation|x64.Build.0 = Instrumentation|Any CPU {186F31A3-EF89-4A25-B2D5-20060509AA01}.Release|Any CPU.ActiveCfg = Release|Any CPU {186F31A3-EF89-4A25-B2D5-20060509AA01}.Release|Any CPU.Build.0 = Release|Any CPU {186F31A3-EF89-4A25-B2D5-20060509AA01}.Release|ARM.ActiveCfg = Release|Any CPU {186F31A3-EF89-4A25-B2D5-20060509AA01}.Release|ARM.Build.0 = Release|Any CPU {186F31A3-EF89-4A25-B2D5-20060509AA01}.Release|Mixed Platforms.ActiveCfg = Release|Any CPU {186F31A3-EF89-4A25-B2D5-20060509AA01}.Release|Mixed Platforms.Build.0 = Release|Any CPU {186F31A3-EF89-4A25-B2D5-20060509AA01}.Release|Win32.ActiveCfg = Release|Any CPU {186F31A3-EF89-4A25-B2D5-20060509AA01}.Release|Win32.Build.0 = Release|Any CPU {186F31A3-EF89-4A25-B2D5-20060509AA01}.Release|x64.ActiveCfg = Release|Any CPU {186F31A3-EF89-4A25-B2D5-20060509AA01}.Release|x64.Build.0 = Release|Any CPU {186F31A3-EF89-4A25-B2D5-20060510AA01}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {186F31A3-EF89-4A25-B2D5-20060510AA01}.Debug|Any CPU.Build.0 = Debug|Any CPU {186F31A3-EF89-4A25-B2D5-20060510AA01}.Debug|ARM.ActiveCfg = Debug|Any CPU {186F31A3-EF89-4A25-B2D5-20060510AA01}.Debug|ARM.Build.0 = Debug|Any CPU {186F31A3-EF89-4A25-B2D5-20060510AA01}.Debug|Mixed Platforms.ActiveCfg = Debug|Any CPU {186F31A3-EF89-4A25-B2D5-20060510AA01}.Debug|Mixed Platforms.Build.0 = Debug|Any CPU {186F31A3-EF89-4A25-B2D5-20060510AA01}.Debug|Win32.ActiveCfg = Debug|Any CPU {186F31A3-EF89-4A25-B2D5-20060510AA01}.Debug|Win32.Build.0 = Debug|Any CPU {186F31A3-EF89-4A25-B2D5-20060510AA01}.Debug|x64.ActiveCfg = Debug|Any CPU {186F31A3-EF89-4A25-B2D5-20060510AA01}.Debug|x64.Build.0 = Debug|Any CPU {186F31A3-EF89-4A25-B2D5-20060510AA01}.Instrumentation|Any CPU.ActiveCfg = Instrumentation|Any CPU {186F31A3-EF89-4A25-B2D5-20060510AA01}.Instrumentation|Any CPU.Build.0 = Instrumentation|Any CPU {186F31A3-EF89-4A25-B2D5-20060510AA01}.Instrumentation|ARM.ActiveCfg = Instrumentation|Any CPU {186F31A3-EF89-4A25-B2D5-20060510AA01}.Instrumentation|ARM.Build.0 = Instrumentation|Any CPU {186F31A3-EF89-4A25-B2D5-20060510AA01}.Instrumentation|Mixed Platforms.ActiveCfg = Instrumentation|Any CPU {186F31A3-EF89-4A25-B2D5-20060510AA01}.Instrumentation|Mixed Platforms.Build.0 = Instrumentation|Any CPU {186F31A3-EF89-4A25-B2D5-20060510AA01}.Instrumentation|Win32.ActiveCfg = Instrumentation|Any CPU {186F31A3-EF89-4A25-B2D5-20060510AA01}.Instrumentation|Win32.Build.0 = Instrumentation|Any CPU {186F31A3-EF89-4A25-B2D5-20060510AA01}.Instrumentation|x64.ActiveCfg = Instrumentation|Any CPU {186F31A3-EF89-4A25-B2D5-20060510AA01}.Instrumentation|x64.Build.0 = Instrumentation|Any CPU {186F31A3-EF89-4A25-B2D5-20060510AA01}.Release|Any CPU.ActiveCfg = Release|Any CPU {186F31A3-EF89-4A25-B2D5-20060510AA01}.Release|Any CPU.Build.0 = Release|Any CPU {186F31A3-EF89-4A25-B2D5-20060510AA01}.Release|ARM.ActiveCfg = Release|Any CPU {186F31A3-EF89-4A25-B2D5-20060510AA01}.Release|ARM.Build.0 = Release|Any CPU {186F31A3-EF89-4A25-B2D5-20060510AA01}.Release|Mixed Platforms.ActiveCfg = Release|Any CPU {186F31A3-EF89-4A25-B2D5-20060510AA01}.Release|Mixed Platforms.Build.0 = Release|Any CPU {186F31A3-EF89-4A25-B2D5-20060510AA01}.Release|Win32.ActiveCfg = Release|Any CPU {186F31A3-EF89-4A25-B2D5-20060510AA01}.Release|Win32.Build.0 = Release|Any CPU {186F31A3-EF89-4A25-B2D5-20060510AA01}.Release|x64.ActiveCfg = Release|Any CPU {186F31A3-EF89-4A25-B2D5-20060510AA01}.Release|x64.Build.0 = Release|Any CPU {186F31A3-EF89-4A25-B2D5-20060603AA01}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {186F31A3-EF89-4A25-B2D5-20060603AA01}.Debug|Any CPU.Build.0 = Debug|Any CPU {186F31A3-EF89-4A25-B2D5-20060603AA01}.Debug|ARM.ActiveCfg = Debug|Any CPU {186F31A3-EF89-4A25-B2D5-20060603AA01}.Debug|ARM.Build.0 = Debug|Any CPU {186F31A3-EF89-4A25-B2D5-20060603AA01}.Debug|Mixed Platforms.ActiveCfg = Debug|Any CPU {186F31A3-EF89-4A25-B2D5-20060603AA01}.Debug|Mixed Platforms.Build.0 = Debug|Any CPU {186F31A3-EF89-4A25-B2D5-20060603AA01}.Debug|Win32.ActiveCfg = Debug|Any CPU {186F31A3-EF89-4A25-B2D5-20060603AA01}.Debug|Win32.Build.0 = Debug|Any CPU {186F31A3-EF89-4A25-B2D5-20060603AA01}.Debug|x64.ActiveCfg = Debug|Any CPU {186F31A3-EF89-4A25-B2D5-20060603AA01}.Debug|x64.Build.0 = Debug|Any CPU {186F31A3-EF89-4A25-B2D5-20060603AA01}.Instrumentation|Any CPU.ActiveCfg = Instrumentation|Any CPU {186F31A3-EF89-4A25-B2D5-20060603AA01}.Instrumentation|Any CPU.Build.0 = Instrumentation|Any CPU {186F31A3-EF89-4A25-B2D5-20060603AA01}.Instrumentation|ARM.ActiveCfg = Instrumentation|Any CPU {186F31A3-EF89-4A25-B2D5-20060603AA01}.Instrumentation|ARM.Build.0 = Instrumentation|Any CPU {186F31A3-EF89-4A25-B2D5-20060603AA01}.Instrumentation|Mixed Platforms.ActiveCfg = Instrumentation|Any CPU {186F31A3-EF89-4A25-B2D5-20060603AA01}.Instrumentation|Mixed Platforms.Build.0 = Instrumentation|Any CPU {186F31A3-EF89-4A25-B2D5-20060603AA01}.Instrumentation|Win32.ActiveCfg = Instrumentation|Any CPU {186F31A3-EF89-4A25-B2D5-20060603AA01}.Instrumentation|Win32.Build.0 = Instrumentation|Any CPU {186F31A3-EF89-4A25-B2D5-20060603AA01}.Instrumentation|x64.ActiveCfg = Instrumentation|Any CPU {186F31A3-EF89-4A25-B2D5-20060603AA01}.Instrumentation|x64.Build.0 = Instrumentation|Any CPU {186F31A3-EF89-4A25-B2D5-20060603AA01}.Release|Any CPU.ActiveCfg = Release|Any CPU {186F31A3-EF89-4A25-B2D5-20060603AA01}.Release|Any CPU.Build.0 = Release|Any CPU {186F31A3-EF89-4A25-B2D5-20060603AA01}.Release|ARM.ActiveCfg = Release|Any CPU {186F31A3-EF89-4A25-B2D5-20060603AA01}.Release|ARM.Build.0 = Release|Any CPU {186F31A3-EF89-4A25-B2D5-20060603AA01}.Release|Mixed Platforms.ActiveCfg = Release|Any CPU {186F31A3-EF89-4A25-B2D5-20060603AA01}.Release|Mixed Platforms.Build.0 = Release|Any CPU {186F31A3-EF89-4A25-B2D5-20060603AA01}.Release|Win32.ActiveCfg = Release|Any CPU {186F31A3-EF89-4A25-B2D5-20060603AA01}.Release|Win32.Build.0 = Release|Any CPU {186F31A3-EF89-4A25-B2D5-20060603AA01}.Release|x64.ActiveCfg = Release|Any CPU {186F31A3-EF89-4A25-B2D5-20060603AA01}.Release|x64.Build.0 = Release|Any CPU {186F31A3-EF89-4A25-B2D5-20060606AA01}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {186F31A3-EF89-4A25-B2D5-20060606AA01}.Debug|Any CPU.Build.0 = Debug|Any CPU {186F31A3-EF89-4A25-B2D5-20060606AA01}.Debug|ARM.ActiveCfg = Debug|Any CPU {186F31A3-EF89-4A25-B2D5-20060606AA01}.Debug|ARM.Build.0 = Debug|Any CPU {186F31A3-EF89-4A25-B2D5-20060606AA01}.Debug|Mixed Platforms.ActiveCfg = Debug|Any CPU {186F31A3-EF89-4A25-B2D5-20060606AA01}.Debug|Mixed Platforms.Build.0 = Debug|Any CPU {186F31A3-EF89-4A25-B2D5-20060606AA01}.Debug|Win32.ActiveCfg = Debug|Any CPU {186F31A3-EF89-4A25-B2D5-20060606AA01}.Debug|Win32.Build.0 = Debug|Any CPU {186F31A3-EF89-4A25-B2D5-20060606AA01}.Debug|x64.ActiveCfg = Debug|Any CPU {186F31A3-EF89-4A25-B2D5-20060606AA01}.Debug|x64.Build.0 = Debug|Any CPU {186F31A3-EF89-4A25-B2D5-20060606AA01}.Instrumentation|Any CPU.ActiveCfg = Instrumentation|Any CPU {186F31A3-EF89-4A25-B2D5-20060606AA01}.Instrumentation|Any CPU.Build.0 = Instrumentation|Any CPU {186F31A3-EF89-4A25-B2D5-20060606AA01}.Instrumentation|ARM.ActiveCfg = Instrumentation|Any CPU {186F31A3-EF89-4A25-B2D5-20060606AA01}.Instrumentation|ARM.Build.0 = Instrumentation|Any CPU {186F31A3-EF89-4A25-B2D5-20060606AA01}.Instrumentation|Mixed Platforms.ActiveCfg = Instrumentation|Any CPU {186F31A3-EF89-4A25-B2D5-20060606AA01}.Instrumentation|Mixed Platforms.Build.0 = Instrumentation|Any CPU {186F31A3-EF89-4A25-B2D5-20060606AA01}.Instrumentation|Win32.ActiveCfg = Instrumentation|Any CPU {186F31A3-EF89-4A25-B2D5-20060606AA01}.Instrumentation|Win32.Build.0 = Instrumentation|Any CPU {186F31A3-EF89-4A25-B2D5-20060606AA01}.Instrumentation|x64.ActiveCfg = Instrumentation|Any CPU {186F31A3-EF89-4A25-B2D5-20060606AA01}.Instrumentation|x64.Build.0 = Instrumentation|Any CPU {186F31A3-EF89-4A25-B2D5-20060606AA01}.Release|Any CPU.ActiveCfg = Release|Any CPU {186F31A3-EF89-4A25-B2D5-20060606AA01}.Release|Any CPU.Build.0 = Release|Any CPU {186F31A3-EF89-4A25-B2D5-20060606AA01}.Release|ARM.ActiveCfg = Release|Any CPU {186F31A3-EF89-4A25-B2D5-20060606AA01}.Release|ARM.Build.0 = Release|Any CPU {186F31A3-EF89-4A25-B2D5-20060606AA01}.Release|Mixed Platforms.ActiveCfg = Release|Any CPU {186F31A3-EF89-4A25-B2D5-20060606AA01}.Release|Mixed Platforms.Build.0 = Release|Any CPU {186F31A3-EF89-4A25-B2D5-20060606AA01}.Release|Win32.ActiveCfg = Release|Any CPU {186F31A3-EF89-4A25-B2D5-20060606AA01}.Release|Win32.Build.0 = Release|Any CPU {186F31A3-EF89-4A25-B2D5-20060606AA01}.Release|x64.ActiveCfg = Release|Any CPU {186F31A3-EF89-4A25-B2D5-20060606AA01}.Release|x64.Build.0 = Release|Any CPU {186F31A3-EF89-4A25-B2D5-20060704AA01}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {186F31A3-EF89-4A25-B2D5-20060704AA01}.Debug|Any CPU.Build.0 = Debug|Any CPU {186F31A3-EF89-4A25-B2D5-20060704AA01}.Debug|ARM.ActiveCfg = Debug|Any CPU {186F31A3-EF89-4A25-B2D5-20060704AA01}.Debug|ARM.Build.0 = Debug|Any CPU {186F31A3-EF89-4A25-B2D5-20060704AA01}.Debug|Mixed Platforms.ActiveCfg = Debug|Any CPU {186F31A3-EF89-4A25-B2D5-20060704AA01}.Debug|Mixed Platforms.Build.0 = Debug|Any CPU {186F31A3-EF89-4A25-B2D5-20060704AA01}.Debug|Win32.ActiveCfg = Debug|Any CPU {186F31A3-EF89-4A25-B2D5-20060704AA01}.Debug|Win32.Build.0 = Debug|Any CPU {186F31A3-EF89-4A25-B2D5-20060704AA01}.Debug|x64.ActiveCfg = Debug|Any CPU {186F31A3-EF89-4A25-B2D5-20060704AA01}.Debug|x64.Build.0 = Debug|Any CPU {186F31A3-EF89-4A25-B2D5-20060704AA01}.Instrumentation|Any CPU.ActiveCfg = Instrumentation|Any CPU {186F31A3-EF89-4A25-B2D5-20060704AA01}.Instrumentation|Any CPU.Build.0 = Instrumentation|Any CPU {186F31A3-EF89-4A25-B2D5-20060704AA01}.Instrumentation|ARM.ActiveCfg = Instrumentation|Any CPU {186F31A3-EF89-4A25-B2D5-20060704AA01}.Instrumentation|ARM.Build.0 = Instrumentation|Any CPU {186F31A3-EF89-4A25-B2D5-20060704AA01}.Instrumentation|Mixed Platforms.ActiveCfg = Instrumentation|Any CPU {186F31A3-EF89-4A25-B2D5-20060704AA01}.Instrumentation|Mixed Platforms.Build.0 = Instrumentation|Any CPU {186F31A3-EF89-4A25-B2D5-20060704AA01}.Instrumentation|Win32.ActiveCfg = Instrumentation|Any CPU {186F31A3-EF89-4A25-B2D5-20060704AA01}.Instrumentation|Win32.Build.0 = Instrumentation|Any CPU {186F31A3-EF89-4A25-B2D5-20060704AA01}.Instrumentation|x64.ActiveCfg = Instrumentation|Any CPU {186F31A3-EF89-4A25-B2D5-20060704AA01}.Instrumentation|x64.Build.0 = Instrumentation|Any CPU {186F31A3-EF89-4A25-B2D5-20060704AA01}.Release|Any CPU.ActiveCfg = Release|Any CPU {186F31A3-EF89-4A25-B2D5-20060704AA01}.Release|Any CPU.Build.0 = Release|Any CPU {186F31A3-EF89-4A25-B2D5-20060704AA01}.Release|ARM.ActiveCfg = Release|Any CPU {186F31A3-EF89-4A25-B2D5-20060704AA01}.Release|ARM.Build.0 = Release|Any CPU {186F31A3-EF89-4A25-B2D5-20060704AA01}.Release|Mixed Platforms.ActiveCfg = Release|Any CPU {186F31A3-EF89-4A25-B2D5-20060704AA01}.Release|Mixed Platforms.Build.0 = Release|Any CPU {186F31A3-EF89-4A25-B2D5-20060704AA01}.Release|Win32.ActiveCfg = Release|Any CPU {186F31A3-EF89-4A25-B2D5-20060704AA01}.Release|Win32.Build.0 = Release|Any CPU {186F31A3-EF89-4A25-B2D5-20060704AA01}.Release|x64.ActiveCfg = Release|Any CPU {186F31A3-EF89-4A25-B2D5-20060704AA01}.Release|x64.Build.0 = Release|Any CPU {186F31A3-EF89-4A25-B2D5-20060720AA01}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {186F31A3-EF89-4A25-B2D5-20060720AA01}.Debug|Any CPU.Build.0 = Debug|Any CPU {186F31A3-EF89-4A25-B2D5-20060720AA01}.Debug|ARM.ActiveCfg = Debug|Any CPU {186F31A3-EF89-4A25-B2D5-20060720AA01}.Debug|ARM.Build.0 = Debug|Any CPU {186F31A3-EF89-4A25-B2D5-20060720AA01}.Debug|Mixed Platforms.ActiveCfg = Debug|Any CPU {186F31A3-EF89-4A25-B2D5-20060720AA01}.Debug|Mixed Platforms.Build.0 = Debug|Any CPU {186F31A3-EF89-4A25-B2D5-20060720AA01}.Debug|Win32.ActiveCfg = Debug|Any CPU {186F31A3-EF89-4A25-B2D5-20060720AA01}.Debug|Win32.Build.0 = Debug|Any CPU {186F31A3-EF89-4A25-B2D5-20060720AA01}.Debug|x64.ActiveCfg = Debug|Any CPU {186F31A3-EF89-4A25-B2D5-20060720AA01}.Debug|x64.Build.0 = Debug|Any CPU {186F31A3-EF89-4A25-B2D5-20060720AA01}.Instrumentation|Any CPU.ActiveCfg = Instrumentation|Any CPU {186F31A3-EF89-4A25-B2D5-20060720AA01}.Instrumentation|Any CPU.Build.0 = Instrumentation|Any CPU {186F31A3-EF89-4A25-B2D5-20060720AA01}.Instrumentation|ARM.ActiveCfg = Instrumentation|Any CPU {186F31A3-EF89-4A25-B2D5-20060720AA01}.Instrumentation|ARM.Build.0 = Instrumentation|Any CPU {186F31A3-EF89-4A25-B2D5-20060720AA01}.Instrumentation|Mixed Platforms.ActiveCfg = Instrumentation|Any CPU {186F31A3-EF89-4A25-B2D5-20060720AA01}.Instrumentation|Mixed Platforms.Build.0 = Instrumentation|Any CPU {186F31A3-EF89-4A25-B2D5-20060720AA01}.Instrumentation|Win32.ActiveCfg = Instrumentation|Any CPU {186F31A3-EF89-4A25-B2D5-20060720AA01}.Instrumentation|Win32.Build.0 = Instrumentation|Any CPU {186F31A3-EF89-4A25-B2D5-20060720AA01}.Instrumentation|x64.ActiveCfg = Instrumentation|Any CPU {186F31A3-EF89-4A25-B2D5-20060720AA01}.Instrumentation|x64.Build.0 = Instrumentation|Any CPU {186F31A3-EF89-4A25-B2D5-20060720AA01}.Release|Any CPU.ActiveCfg = Release|Any CPU {186F31A3-EF89-4A25-B2D5-20060720AA01}.Release|Any CPU.Build.0 = Release|Any CPU {186F31A3-EF89-4A25-B2D5-20060720AA01}.Release|ARM.ActiveCfg = Release|Any CPU {186F31A3-EF89-4A25-B2D5-20060720AA01}.Release|ARM.Build.0 = Release|Any CPU {186F31A3-EF89-4A25-B2D5-20060720AA01}.Release|Mixed Platforms.ActiveCfg = Release|Any CPU {186F31A3-EF89-4A25-B2D5-20060720AA01}.Release|Mixed Platforms.Build.0 = Release|Any CPU {186F31A3-EF89-4A25-B2D5-20060720AA01}.Release|Win32.ActiveCfg = Release|Any CPU {186F31A3-EF89-4A25-B2D5-20060720AA01}.Release|Win32.Build.0 = Release|Any CPU {186F31A3-EF89-4A25-B2D5-20060720AA01}.Release|x64.ActiveCfg = Release|Any CPU {186F31A3-EF89-4A25-B2D5-20060720AA01}.Release|x64.Build.0 = Release|Any CPU {186F31A3-EF89-4A25-B2D5-20060721AA01}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {186F31A3-EF89-4A25-B2D5-20060721AA01}.Debug|Any CPU.Build.0 = Debug|Any CPU {186F31A3-EF89-4A25-B2D5-20060721AA01}.Debug|ARM.ActiveCfg = Debug|Any CPU {186F31A3-EF89-4A25-B2D5-20060721AA01}.Debug|ARM.Build.0 = Debug|Any CPU {186F31A3-EF89-4A25-B2D5-20060721AA01}.Debug|Mixed Platforms.ActiveCfg = Debug|Any CPU {186F31A3-EF89-4A25-B2D5-20060721AA01}.Debug|Mixed Platforms.Build.0 = Debug|Any CPU {186F31A3-EF89-4A25-B2D5-20060721AA01}.Debug|Win32.ActiveCfg = Debug|Any CPU {186F31A3-EF89-4A25-B2D5-20060721AA01}.Debug|Win32.Build.0 = Debug|Any CPU {186F31A3-EF89-4A25-B2D5-20060721AA01}.Debug|x64.ActiveCfg = Debug|Any CPU {186F31A3-EF89-4A25-B2D5-20060721AA01}.Debug|x64.Build.0 = Debug|Any CPU {186F31A3-EF89-4A25-B2D5-20060721AA01}.Instrumentation|Any CPU.ActiveCfg = Instrumentation|Any CPU {186F31A3-EF89-4A25-B2D5-20060721AA01}.Instrumentation|Any CPU.Build.0 = Instrumentation|Any CPU {186F31A3-EF89-4A25-B2D5-20060721AA01}.Instrumentation|ARM.ActiveCfg = Instrumentation|Any CPU {186F31A3-EF89-4A25-B2D5-20060721AA01}.Instrumentation|ARM.Build.0 = Instrumentation|Any CPU {186F31A3-EF89-4A25-B2D5-20060721AA01}.Instrumentation|Mixed Platforms.ActiveCfg = Instrumentation|Any CPU {186F31A3-EF89-4A25-B2D5-20060721AA01}.Instrumentation|Mixed Platforms.Build.0 = Instrumentation|Any CPU {186F31A3-EF89-4A25-B2D5-20060721AA01}.Instrumentation|Win32.ActiveCfg = Instrumentation|Any CPU {186F31A3-EF89-4A25-B2D5-20060721AA01}.Instrumentation|Win32.Build.0 = Instrumentation|Any CPU {186F31A3-EF89-4A25-B2D5-20060721AA01}.Instrumentation|x64.ActiveCfg = Instrumentation|Any CPU {186F31A3-EF89-4A25-B2D5-20060721AA01}.Instrumentation|x64.Build.0 = Instrumentation|Any CPU {186F31A3-EF89-4A25-B2D5-20060721AA01}.Release|Any CPU.ActiveCfg = Release|Any CPU {186F31A3-EF89-4A25-B2D5-20060721AA01}.Release|Any CPU.Build.0 = Release|Any CPU {186F31A3-EF89-4A25-B2D5-20060721AA01}.Release|ARM.ActiveCfg = Release|Any CPU {186F31A3-EF89-4A25-B2D5-20060721AA01}.Release|ARM.Build.0 = Release|Any CPU {186F31A3-EF89-4A25-B2D5-20060721AA01}.Release|Mixed Platforms.ActiveCfg = Release|Any CPU {186F31A3-EF89-4A25-B2D5-20060721AA01}.Release|Mixed Platforms.Build.0 = Release|Any CPU {186F31A3-EF89-4A25-B2D5-20060721AA01}.Release|Win32.ActiveCfg = Release|Any CPU {186F31A3-EF89-4A25-B2D5-20060721AA01}.Release|Win32.Build.0 = Release|Any CPU {186F31A3-EF89-4A25-B2D5-20060721AA01}.Release|x64.ActiveCfg = Release|Any CPU {186F31A3-EF89-4A25-B2D5-20060721AA01}.Release|x64.Build.0 = Release|Any CPU {186F31A3-EF89-4A25-B2D5-20061218AA01}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {186F31A3-EF89-4A25-B2D5-20061218AA01}.Debug|Any CPU.Build.0 = Debug|Any CPU {186F31A3-EF89-4A25-B2D5-20061218AA01}.Debug|ARM.ActiveCfg = Debug|Any CPU {186F31A3-EF89-4A25-B2D5-20061218AA01}.Debug|ARM.Build.0 = Debug|Any CPU {186F31A3-EF89-4A25-B2D5-20061218AA01}.Debug|Mixed Platforms.ActiveCfg = Debug|Any CPU {186F31A3-EF89-4A25-B2D5-20061218AA01}.Debug|Mixed Platforms.Build.0 = Debug|Any CPU {186F31A3-EF89-4A25-B2D5-20061218AA01}.Debug|Win32.ActiveCfg = Debug|Any CPU {186F31A3-EF89-4A25-B2D5-20061218AA01}.Debug|Win32.Build.0 = Debug|Any CPU {186F31A3-EF89-4A25-B2D5-20061218AA01}.Debug|x64.ActiveCfg = Debug|Any CPU {186F31A3-EF89-4A25-B2D5-20061218AA01}.Debug|x64.Build.0 = Debug|Any CPU {186F31A3-EF89-4A25-B2D5-20061218AA01}.Instrumentation|Any CPU.ActiveCfg = Instrumentation|Any CPU {186F31A3-EF89-4A25-B2D5-20061218AA01}.Instrumentation|Any CPU.Build.0 = Instrumentation|Any CPU {186F31A3-EF89-4A25-B2D5-20061218AA01}.Instrumentation|ARM.ActiveCfg = Instrumentation|Any CPU {186F31A3-EF89-4A25-B2D5-20061218AA01}.Instrumentation|ARM.Build.0 = Instrumentation|Any CPU {186F31A3-EF89-4A25-B2D5-20061218AA01}.Instrumentation|Mixed Platforms.ActiveCfg = Instrumentation|Any CPU {186F31A3-EF89-4A25-B2D5-20061218AA01}.Instrumentation|Mixed Platforms.Build.0 = Instrumentation|Any CPU {186F31A3-EF89-4A25-B2D5-20061218AA01}.Instrumentation|Win32.ActiveCfg = Instrumentation|Any CPU {186F31A3-EF89-4A25-B2D5-20061218AA01}.Instrumentation|Win32.Build.0 = Instrumentation|Any CPU {186F31A3-EF89-4A25-B2D5-20061218AA01}.Instrumentation|x64.ActiveCfg = Instrumentation|Any CPU {186F31A3-EF89-4A25-B2D5-20061218AA01}.Instrumentation|x64.Build.0 = Instrumentation|Any CPU {186F31A3-EF89-4A25-B2D5-20061218AA01}.Release|Any CPU.ActiveCfg = Release|Any CPU {186F31A3-EF89-4A25-B2D5-20061218AA01}.Release|Any CPU.Build.0 = Release|Any CPU {186F31A3-EF89-4A25-B2D5-20061218AA01}.Release|ARM.ActiveCfg = Release|Any CPU {186F31A3-EF89-4A25-B2D5-20061218AA01}.Release|ARM.Build.0 = Release|Any CPU {186F31A3-EF89-4A25-B2D5-20061218AA01}.Release|Mixed Platforms.ActiveCfg = Release|Any CPU {186F31A3-EF89-4A25-B2D5-20061218AA01}.Release|Mixed Platforms.Build.0 = Release|Any CPU {186F31A3-EF89-4A25-B2D5-20061218AA01}.Release|Win32.ActiveCfg = Release|Any CPU {186F31A3-EF89-4A25-B2D5-20061218AA01}.Release|Win32.Build.0 = Release|Any CPU {186F31A3-EF89-4A25-B2D5-20061218AA01}.Release|x64.ActiveCfg = Release|Any CPU {186F31A3-EF89-4A25-B2D5-20061218AA01}.Release|x64.Build.0 = Release|Any CPU {186F31A3-EF89-4A25-B2D5-20070211AA01}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {186F31A3-EF89-4A25-B2D5-20070211AA01}.Debug|Any CPU.Build.0 = Debug|Any CPU {186F31A3-EF89-4A25-B2D5-20070211AA01}.Debug|ARM.ActiveCfg = Debug|Any CPU {186F31A3-EF89-4A25-B2D5-20070211AA01}.Debug|ARM.Build.0 = Debug|Any CPU {186F31A3-EF89-4A25-B2D5-20070211AA01}.Debug|Mixed Platforms.ActiveCfg = Debug|Any CPU {186F31A3-EF89-4A25-B2D5-20070211AA01}.Debug|Mixed Platforms.Build.0 = Debug|Any CPU {186F31A3-EF89-4A25-B2D5-20070211AA01}.Debug|Win32.ActiveCfg = Debug|Any CPU {186F31A3-EF89-4A25-B2D5-20070211AA01}.Debug|Win32.Build.0 = Debug|Any CPU {186F31A3-EF89-4A25-B2D5-20070211AA01}.Debug|x64.ActiveCfg = Debug|Any CPU {186F31A3-EF89-4A25-B2D5-20070211AA01}.Debug|x64.Build.0 = Debug|Any CPU {186F31A3-EF89-4A25-B2D5-20070211AA01}.Instrumentation|Any CPU.ActiveCfg = Instrumentation|Any CPU {186F31A3-EF89-4A25-B2D5-20070211AA01}.Instrumentation|Any CPU.Build.0 = Instrumentation|Any CPU {186F31A3-EF89-4A25-B2D5-20070211AA01}.Instrumentation|ARM.ActiveCfg = Instrumentation|Any CPU {186F31A3-EF89-4A25-B2D5-20070211AA01}.Instrumentation|ARM.Build.0 = Instrumentation|Any CPU {186F31A3-EF89-4A25-B2D5-20070211AA01}.Instrumentation|Mixed Platforms.ActiveCfg = Instrumentation|Any CPU {186F31A3-EF89-4A25-B2D5-20070211AA01}.Instrumentation|Mixed Platforms.Build.0 = Instrumentation|Any CPU {186F31A3-EF89-4A25-B2D5-20070211AA01}.Instrumentation|Win32.ActiveCfg = Instrumentation|Any CPU {186F31A3-EF89-4A25-B2D5-20070211AA01}.Instrumentation|Win32.Build.0 = Instrumentation|Any CPU {186F31A3-EF89-4A25-B2D5-20070211AA01}.Instrumentation|x64.ActiveCfg = Instrumentation|Any CPU {186F31A3-EF89-4A25-B2D5-20070211AA01}.Instrumentation|x64.Build.0 = Instrumentation|Any CPU {186F31A3-EF89-4A25-B2D5-20070211AA01}.Release|Any CPU.ActiveCfg = Release|Any CPU {186F31A3-EF89-4A25-B2D5-20070211AA01}.Release|Any CPU.Build.0 = Release|Any CPU {186F31A3-EF89-4A25-B2D5-20070211AA01}.Release|ARM.ActiveCfg = Release|Any CPU {186F31A3-EF89-4A25-B2D5-20070211AA01}.Release|ARM.Build.0 = Release|Any CPU {186F31A3-EF89-4A25-B2D5-20070211AA01}.Release|Mixed Platforms.ActiveCfg = Release|Any CPU {186F31A3-EF89-4A25-B2D5-20070211AA01}.Release|Mixed Platforms.Build.0 = Release|Any CPU {186F31A3-EF89-4A25-B2D5-20070211AA01}.Release|Win32.ActiveCfg = Release|Any CPU {186F31A3-EF89-4A25-B2D5-20070211AA01}.Release|Win32.Build.0 = Release|Any CPU {186F31A3-EF89-4A25-B2D5-20070211AA01}.Release|x64.ActiveCfg = Release|Any CPU {186F31A3-EF89-4A25-B2D5-20070211AA01}.Release|x64.Build.0 = Release|Any CPU {186F31A3-EF89-4A25-B2D5-20070222AA01}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {186F31A3-EF89-4A25-B2D5-20070222AA01}.Debug|Any CPU.Build.0 = Debug|Any CPU {186F31A3-EF89-4A25-B2D5-20070222AA01}.Debug|ARM.ActiveCfg = Debug|Any CPU {186F31A3-EF89-4A25-B2D5-20070222AA01}.Debug|ARM.Build.0 = Debug|Any CPU {186F31A3-EF89-4A25-B2D5-20070222AA01}.Debug|Mixed Platforms.ActiveCfg = Debug|Any CPU {186F31A3-EF89-4A25-B2D5-20070222AA01}.Debug|Mixed Platforms.Build.0 = Debug|Any CPU {186F31A3-EF89-4A25-B2D5-20070222AA01}.Debug|Win32.ActiveCfg = Debug|Any CPU {186F31A3-EF89-4A25-B2D5-20070222AA01}.Debug|Win32.Build.0 = Debug|Any CPU {186F31A3-EF89-4A25-B2D5-20070222AA01}.Debug|x64.ActiveCfg = Debug|Any CPU {186F31A3-EF89-4A25-B2D5-20070222AA01}.Debug|x64.Build.0 = Debug|Any CPU {186F31A3-EF89-4A25-B2D5-20070222AA01}.Instrumentation|Any CPU.ActiveCfg = Instrumentation|Any CPU {186F31A3-EF89-4A25-B2D5-20070222AA01}.Instrumentation|Any CPU.Build.0 = Instrumentation|Any CPU {186F31A3-EF89-4A25-B2D5-20070222AA01}.Instrumentation|ARM.ActiveCfg = Instrumentation|Any CPU {186F31A3-EF89-4A25-B2D5-20070222AA01}.Instrumentation|ARM.Build.0 = Instrumentation|Any CPU {186F31A3-EF89-4A25-B2D5-20070222AA01}.Instrumentation|Mixed Platforms.ActiveCfg = Instrumentation|Any CPU {186F31A3-EF89-4A25-B2D5-20070222AA01}.Instrumentation|Mixed Platforms.Build.0 = Instrumentation|Any CPU {186F31A3-EF89-4A25-B2D5-20070222AA01}.Instrumentation|Win32.ActiveCfg = Instrumentation|Any CPU {186F31A3-EF89-4A25-B2D5-20070222AA01}.Instrumentation|Win32.Build.0 = Instrumentation|Any CPU {186F31A3-EF89-4A25-B2D5-20070222AA01}.Instrumentation|x64.ActiveCfg = Instrumentation|Any CPU {186F31A3-EF89-4A25-B2D5-20070222AA01}.Instrumentation|x64.Build.0 = Instrumentation|Any CPU {186F31A3-EF89-4A25-B2D5-20070222AA01}.Release|Any CPU.ActiveCfg = Release|Any CPU {186F31A3-EF89-4A25-B2D5-20070222AA01}.Release|Any CPU.Build.0 = Release|Any CPU {186F31A3-EF89-4A25-B2D5-20070222AA01}.Release|ARM.ActiveCfg = Release|Any CPU {186F31A3-EF89-4A25-B2D5-20070222AA01}.Release|ARM.Build.0 = Release|Any CPU {186F31A3-EF89-4A25-B2D5-20070222AA01}.Release|Mixed Platforms.ActiveCfg = Release|Any CPU {186F31A3-EF89-4A25-B2D5-20070222AA01}.Release|Mixed Platforms.Build.0 = Release|Any CPU {186F31A3-EF89-4A25-B2D5-20070222AA01}.Release|Win32.ActiveCfg = Release|Any CPU {186F31A3-EF89-4A25-B2D5-20070222AA01}.Release|Win32.Build.0 = Release|Any CPU {186F31A3-EF89-4A25-B2D5-20070222AA01}.Release|x64.ActiveCfg = Release|Any CPU {186F31A3-EF89-4A25-B2D5-20070222AA01}.Release|x64.Build.0 = Release|Any CPU {186F31A3-EF89-4A25-B2D5-20070430AA01}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {186F31A3-EF89-4A25-B2D5-20070430AA01}.Debug|Any CPU.Build.0 = Debug|Any CPU {186F31A3-EF89-4A25-B2D5-20070430AA01}.Debug|ARM.ActiveCfg = Debug|Any CPU {186F31A3-EF89-4A25-B2D5-20070430AA01}.Debug|ARM.Build.0 = Debug|Any CPU {186F31A3-EF89-4A25-B2D5-20070430AA01}.Debug|Mixed Platforms.ActiveCfg = Debug|Any CPU {186F31A3-EF89-4A25-B2D5-20070430AA01}.Debug|Mixed Platforms.Build.0 = Debug|Any CPU {186F31A3-EF89-4A25-B2D5-20070430AA01}.Debug|Win32.ActiveCfg = Debug|Any CPU {186F31A3-EF89-4A25-B2D5-20070430AA01}.Debug|Win32.Build.0 = Debug|Any CPU {186F31A3-EF89-4A25-B2D5-20070430AA01}.Debug|x64.ActiveCfg = Debug|Any CPU {186F31A3-EF89-4A25-B2D5-20070430AA01}.Debug|x64.Build.0 = Debug|Any CPU {186F31A3-EF89-4A25-B2D5-20070430AA01}.Instrumentation|Any CPU.ActiveCfg = Instrumentation|Any CPU {186F31A3-EF89-4A25-B2D5-20070430AA01}.Instrumentation|Any CPU.Build.0 = Instrumentation|Any CPU {186F31A3-EF89-4A25-B2D5-20070430AA01}.Instrumentation|ARM.ActiveCfg = Instrumentation|Any CPU {186F31A3-EF89-4A25-B2D5-20070430AA01}.Instrumentation|ARM.Build.0 = Instrumentation|Any CPU {186F31A3-EF89-4A25-B2D5-20070430AA01}.Instrumentation|Mixed Platforms.ActiveCfg = Instrumentation|Any CPU {186F31A3-EF89-4A25-B2D5-20070430AA01}.Instrumentation|Mixed Platforms.Build.0 = Instrumentation|Any CPU {186F31A3-EF89-4A25-B2D5-20070430AA01}.Instrumentation|Win32.ActiveCfg = Instrumentation|Any CPU {186F31A3-EF89-4A25-B2D5-20070430AA01}.Instrumentation|Win32.Build.0 = Instrumentation|Any CPU {186F31A3-EF89-4A25-B2D5-20070430AA01}.Instrumentation|x64.ActiveCfg = Instrumentation|Any CPU {186F31A3-EF89-4A25-B2D5-20070430AA01}.Instrumentation|x64.Build.0 = Instrumentation|Any CPU {186F31A3-EF89-4A25-B2D5-20070430AA01}.Release|Any CPU.ActiveCfg = Release|Any CPU {186F31A3-EF89-4A25-B2D5-20070430AA01}.Release|Any CPU.Build.0 = Release|Any CPU {186F31A3-EF89-4A25-B2D5-20070430AA01}.Release|ARM.ActiveCfg = Release|Any CPU {186F31A3-EF89-4A25-B2D5-20070430AA01}.Release|ARM.Build.0 = Release|Any CPU {186F31A3-EF89-4A25-B2D5-20070430AA01}.Release|Mixed Platforms.ActiveCfg = Release|Any CPU {186F31A3-EF89-4A25-B2D5-20070430AA01}.Release|Mixed Platforms.Build.0 = Release|Any CPU {186F31A3-EF89-4A25-B2D5-20070430AA01}.Release|Win32.ActiveCfg = Release|Any CPU {186F31A3-EF89-4A25-B2D5-20070430AA01}.Release|Win32.Build.0 = Release|Any CPU {186F31A3-EF89-4A25-B2D5-20070430AA01}.Release|x64.ActiveCfg = Release|Any CPU {186F31A3-EF89-4A25-B2D5-20070430AA01}.Release|x64.Build.0 = Release|Any CPU {186F31A3-EF89-4A25-B2D5-20070519AA01}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {186F31A3-EF89-4A25-B2D5-20070519AA01}.Debug|Any CPU.Build.0 = Debug|Any CPU {186F31A3-EF89-4A25-B2D5-20070519AA01}.Debug|ARM.ActiveCfg = Debug|Any CPU {186F31A3-EF89-4A25-B2D5-20070519AA01}.Debug|ARM.Build.0 = Debug|Any CPU {186F31A3-EF89-4A25-B2D5-20070519AA01}.Debug|Mixed Platforms.ActiveCfg = Debug|Any CPU {186F31A3-EF89-4A25-B2D5-20070519AA01}.Debug|Mixed Platforms.Build.0 = Debug|Any CPU {186F31A3-EF89-4A25-B2D5-20070519AA01}.Debug|Win32.ActiveCfg = Debug|Any CPU {186F31A3-EF89-4A25-B2D5-20070519AA01}.Debug|Win32.Build.0 = Debug|Any CPU {186F31A3-EF89-4A25-B2D5-20070519AA01}.Debug|x64.ActiveCfg = Debug|Any CPU {186F31A3-EF89-4A25-B2D5-20070519AA01}.Debug|x64.Build.0 = Debug|Any CPU {186F31A3-EF89-4A25-B2D5-20070519AA01}.Instrumentation|Any CPU.ActiveCfg = Instrumentation|Any CPU {186F31A3-EF89-4A25-B2D5-20070519AA01}.Instrumentation|Any CPU.Build.0 = Instrumentation|Any CPU {186F31A3-EF89-4A25-B2D5-20070519AA01}.Instrumentation|ARM.ActiveCfg = Instrumentation|Any CPU {186F31A3-EF89-4A25-B2D5-20070519AA01}.Instrumentation|ARM.Build.0 = Instrumentation|Any CPU {186F31A3-EF89-4A25-B2D5-20070519AA01}.Instrumentation|Mixed Platforms.ActiveCfg = Instrumentation|Any CPU {186F31A3-EF89-4A25-B2D5-20070519AA01}.Instrumentation|Mixed Platforms.Build.0 = Instrumentation|Any CPU {186F31A3-EF89-4A25-B2D5-20070519AA01}.Instrumentation|Win32.ActiveCfg = Instrumentation|Any CPU {186F31A3-EF89-4A25-B2D5-20070519AA01}.Instrumentation|Win32.Build.0 = Instrumentation|Any CPU {186F31A3-EF89-4A25-B2D5-20070519AA01}.Instrumentation|x64.ActiveCfg = Instrumentation|Any CPU {186F31A3-EF89-4A25-B2D5-20070519AA01}.Instrumentation|x64.Build.0 = Instrumentation|Any CPU {186F31A3-EF89-4A25-B2D5-20070519AA01}.Release|Any CPU.ActiveCfg = Release|Any CPU {186F31A3-EF89-4A25-B2D5-20070519AA01}.Release|Any CPU.Build.0 = Release|Any CPU {186F31A3-EF89-4A25-B2D5-20070519AA01}.Release|ARM.ActiveCfg = Release|Any CPU {186F31A3-EF89-4A25-B2D5-20070519AA01}.Release|ARM.Build.0 = Release|Any CPU {186F31A3-EF89-4A25-B2D5-20070519AA01}.Release|Mixed Platforms.ActiveCfg = Release|Any CPU {186F31A3-EF89-4A25-B2D5-20070519AA01}.Release|Mixed Platforms.Build.0 = Release|Any CPU {186F31A3-EF89-4A25-B2D5-20070519AA01}.Release|Win32.ActiveCfg = Release|Any CPU {186F31A3-EF89-4A25-B2D5-20070519AA01}.Release|Win32.Build.0 = Release|Any CPU {186F31A3-EF89-4A25-B2D5-20070519AA01}.Release|x64.ActiveCfg = Release|Any CPU {186F31A3-EF89-4A25-B2D5-20070519AA01}.Release|x64.Build.0 = Release|Any CPU {186F31A3-EF89-4A25-B2D5-20070601AA01}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {186F31A3-EF89-4A25-B2D5-20070601AA01}.Debug|Any CPU.Build.0 = Debug|Any CPU {186F31A3-EF89-4A25-B2D5-20070601AA01}.Debug|ARM.ActiveCfg = Debug|Any CPU {186F31A3-EF89-4A25-B2D5-20070601AA01}.Debug|ARM.Build.0 = Debug|Any CPU {186F31A3-EF89-4A25-B2D5-20070601AA01}.Debug|Mixed Platforms.ActiveCfg = Debug|Any CPU {186F31A3-EF89-4A25-B2D5-20070601AA01}.Debug|Mixed Platforms.Build.0 = Debug|Any CPU {186F31A3-EF89-4A25-B2D5-20070601AA01}.Debug|Win32.ActiveCfg = Debug|Any CPU {186F31A3-EF89-4A25-B2D5-20070601AA01}.Debug|Win32.Build.0 = Debug|Any CPU {186F31A3-EF89-4A25-B2D5-20070601AA01}.Debug|x64.ActiveCfg = Debug|Any CPU {186F31A3-EF89-4A25-B2D5-20070601AA01}.Debug|x64.Build.0 = Debug|Any CPU {186F31A3-EF89-4A25-B2D5-20070601AA01}.Instrumentation|Any CPU.ActiveCfg = Instrumentation|Any CPU {186F31A3-EF89-4A25-B2D5-20070601AA01}.Instrumentation|Any CPU.Build.0 = Instrumentation|Any CPU {186F31A3-EF89-4A25-B2D5-20070601AA01}.Instrumentation|ARM.ActiveCfg = Instrumentation|Any CPU {186F31A3-EF89-4A25-B2D5-20070601AA01}.Instrumentation|ARM.Build.0 = Instrumentation|Any CPU {186F31A3-EF89-4A25-B2D5-20070601AA01}.Instrumentation|Mixed Platforms.ActiveCfg = Instrumentation|Any CPU {186F31A3-EF89-4A25-B2D5-20070601AA01}.Instrumentation|Mixed Platforms.Build.0 = Instrumentation|Any CPU {186F31A3-EF89-4A25-B2D5-20070601AA01}.Instrumentation|Win32.ActiveCfg = Instrumentation|Any CPU {186F31A3-EF89-4A25-B2D5-20070601AA01}.Instrumentation|Win32.Build.0 = Instrumentation|Any CPU {186F31A3-EF89-4A25-B2D5-20070601AA01}.Instrumentation|x64.ActiveCfg = Instrumentation|Any CPU {186F31A3-EF89-4A25-B2D5-20070601AA01}.Instrumentation|x64.Build.0 = Instrumentation|Any CPU {186F31A3-EF89-4A25-B2D5-20070601AA01}.Release|Any CPU.ActiveCfg = Release|Any CPU {186F31A3-EF89-4A25-B2D5-20070601AA01}.Release|Any CPU.Build.0 = Release|Any CPU {186F31A3-EF89-4A25-B2D5-20070601AA01}.Release|ARM.ActiveCfg = Release|Any CPU {186F31A3-EF89-4A25-B2D5-20070601AA01}.Release|ARM.Build.0 = Release|Any CPU {186F31A3-EF89-4A25-B2D5-20070601AA01}.Release|Mixed Platforms.ActiveCfg = Release|Any CPU {186F31A3-EF89-4A25-B2D5-20070601AA01}.Release|Mixed Platforms.Build.0 = Release|Any CPU {186F31A3-EF89-4A25-B2D5-20070601AA01}.Release|Win32.ActiveCfg = Release|Any CPU {186F31A3-EF89-4A25-B2D5-20070601AA01}.Release|Win32.Build.0 = Release|Any CPU {186F31A3-EF89-4A25-B2D5-20070601AA01}.Release|x64.ActiveCfg = Release|Any CPU {186F31A3-EF89-4A25-B2D5-20070601AA01}.Release|x64.Build.0 = Release|Any CPU {186F31A3-EF89-4A25-B2D5-20070605AA02}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {186F31A3-EF89-4A25-B2D5-20070605AA02}.Debug|Any CPU.Build.0 = Debug|Any CPU {186F31A3-EF89-4A25-B2D5-20070605AA02}.Debug|ARM.ActiveCfg = Debug|Any CPU {186F31A3-EF89-4A25-B2D5-20070605AA02}.Debug|ARM.Build.0 = Debug|Any CPU {186F31A3-EF89-4A25-B2D5-20070605AA02}.Debug|Mixed Platforms.ActiveCfg = Debug|Any CPU {186F31A3-EF89-4A25-B2D5-20070605AA02}.Debug|Mixed Platforms.Build.0 = Debug|Any CPU {186F31A3-EF89-4A25-B2D5-20070605AA02}.Debug|Win32.ActiveCfg = Debug|Any CPU {186F31A3-EF89-4A25-B2D5-20070605AA02}.Debug|Win32.Build.0 = Debug|Any CPU {186F31A3-EF89-4A25-B2D5-20070605AA02}.Debug|x64.ActiveCfg = Debug|Any CPU {186F31A3-EF89-4A25-B2D5-20070605AA02}.Debug|x64.Build.0 = Debug|Any CPU {186F31A3-EF89-4A25-B2D5-20070605AA02}.Instrumentation|Any CPU.ActiveCfg = Instrumentation|Any CPU {186F31A3-EF89-4A25-B2D5-20070605AA02}.Instrumentation|Any CPU.Build.0 = Instrumentation|Any CPU {186F31A3-EF89-4A25-B2D5-20070605AA02}.Instrumentation|ARM.ActiveCfg = Instrumentation|Any CPU {186F31A3-EF89-4A25-B2D5-20070605AA02}.Instrumentation|ARM.Build.0 = Instrumentation|Any CPU {186F31A3-EF89-4A25-B2D5-20070605AA02}.Instrumentation|Mixed Platforms.ActiveCfg = Instrumentation|Any CPU {186F31A3-EF89-4A25-B2D5-20070605AA02}.Instrumentation|Mixed Platforms.Build.0 = Instrumentation|Any CPU {186F31A3-EF89-4A25-B2D5-20070605AA02}.Instrumentation|Win32.ActiveCfg = Instrumentation|Any CPU {186F31A3-EF89-4A25-B2D5-20070605AA02}.Instrumentation|Win32.Build.0 = Instrumentation|Any CPU {186F31A3-EF89-4A25-B2D5-20070605AA02}.Instrumentation|x64.ActiveCfg = Instrumentation|Any CPU {186F31A3-EF89-4A25-B2D5-20070605AA02}.Instrumentation|x64.Build.0 = Instrumentation|Any CPU {186F31A3-EF89-4A25-B2D5-20070605AA02}.Release|Any CPU.ActiveCfg = Release|Any CPU {186F31A3-EF89-4A25-B2D5-20070605AA02}.Release|Any CPU.Build.0 = Release|Any CPU {186F31A3-EF89-4A25-B2D5-20070605AA02}.Release|ARM.ActiveCfg = Release|Any CPU {186F31A3-EF89-4A25-B2D5-20070605AA02}.Release|ARM.Build.0 = Release|Any CPU {186F31A3-EF89-4A25-B2D5-20070605AA02}.Release|Mixed Platforms.ActiveCfg = Release|Any CPU {186F31A3-EF89-4A25-B2D5-20070605AA02}.Release|Mixed Platforms.Build.0 = Release|Any CPU {186F31A3-EF89-4A25-B2D5-20070605AA02}.Release|Win32.ActiveCfg = Release|Any CPU {186F31A3-EF89-4A25-B2D5-20070605AA02}.Release|Win32.Build.0 = Release|Any CPU {186F31A3-EF89-4A25-B2D5-20070605AA02}.Release|x64.ActiveCfg = Release|Any CPU {186F31A3-EF89-4A25-B2D5-20070605AA02}.Release|x64.Build.0 = Release|Any CPU {186F31A3-EF89-4A25-B2D5-20070606AA01}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {186F31A3-EF89-4A25-B2D5-20070606AA01}.Debug|Any CPU.Build.0 = Debug|Any CPU {186F31A3-EF89-4A25-B2D5-20070606AA01}.Debug|ARM.ActiveCfg = Debug|Any CPU {186F31A3-EF89-4A25-B2D5-20070606AA01}.Debug|ARM.Build.0 = Debug|Any CPU {186F31A3-EF89-4A25-B2D5-20070606AA01}.Debug|Mixed Platforms.ActiveCfg = Debug|Any CPU {186F31A3-EF89-4A25-B2D5-20070606AA01}.Debug|Mixed Platforms.Build.0 = Debug|Any CPU {186F31A3-EF89-4A25-B2D5-20070606AA01}.Debug|Win32.ActiveCfg = Debug|Any CPU {186F31A3-EF89-4A25-B2D5-20070606AA01}.Debug|Win32.Build.0 = Debug|Any CPU {186F31A3-EF89-4A25-B2D5-20070606AA01}.Debug|x64.ActiveCfg = Debug|Any CPU {186F31A3-EF89-4A25-B2D5-20070606AA01}.Debug|x64.Build.0 = Debug|Any CPU {186F31A3-EF89-4A25-B2D5-20070606AA01}.Instrumentation|Any CPU.ActiveCfg = Instrumentation|Any CPU {186F31A3-EF89-4A25-B2D5-20070606AA01}.Instrumentation|Any CPU.Build.0 = Instrumentation|Any CPU {186F31A3-EF89-4A25-B2D5-20070606AA01}.Instrumentation|ARM.ActiveCfg = Instrumentation|Any CPU {186F31A3-EF89-4A25-B2D5-20070606AA01}.Instrumentation|ARM.Build.0 = Instrumentation|Any CPU {186F31A3-EF89-4A25-B2D5-20070606AA01}.Instrumentation|Mixed Platforms.ActiveCfg = Instrumentation|Any CPU {186F31A3-EF89-4A25-B2D5-20070606AA01}.Instrumentation|Mixed Platforms.Build.0 = Instrumentation|Any CPU {186F31A3-EF89-4A25-B2D5-20070606AA01}.Instrumentation|Win32.ActiveCfg = Instrumentation|Any CPU {186F31A3-EF89-4A25-B2D5-20070606AA01}.Instrumentation|Win32.Build.0 = Instrumentation|Any CPU {186F31A3-EF89-4A25-B2D5-20070606AA01}.Instrumentation|x64.ActiveCfg = Instrumentation|Any CPU {186F31A3-EF89-4A25-B2D5-20070606AA01}.Instrumentation|x64.Build.0 = Instrumentation|Any CPU {186F31A3-EF89-4A25-B2D5-20070606AA01}.Release|Any CPU.ActiveCfg = Release|Any CPU {186F31A3-EF89-4A25-B2D5-20070606AA01}.Release|Any CPU.Build.0 = Release|Any CPU {186F31A3-EF89-4A25-B2D5-20070606AA01}.Release|ARM.ActiveCfg = Release|Any CPU {186F31A3-EF89-4A25-B2D5-20070606AA01}.Release|ARM.Build.0 = Release|Any CPU {186F31A3-EF89-4A25-B2D5-20070606AA01}.Release|Mixed Platforms.ActiveCfg = Release|Any CPU {186F31A3-EF89-4A25-B2D5-20070606AA01}.Release|Mixed Platforms.Build.0 = Release|Any CPU {186F31A3-EF89-4A25-B2D5-20070606AA01}.Release|Win32.ActiveCfg = Release|Any CPU {186F31A3-EF89-4A25-B2D5-20070606AA01}.Release|Win32.Build.0 = Release|Any CPU {186F31A3-EF89-4A25-B2D5-20070606AA01}.Release|x64.ActiveCfg = Release|Any CPU {186F31A3-EF89-4A25-B2D5-20070606AA01}.Release|x64.Build.0 = Release|Any CPU {186F31A3-EF89-4A25-B2D5-20070702AA01}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {186F31A3-EF89-4A25-B2D5-20070702AA01}.Debug|Any CPU.Build.0 = Debug|Any CPU {186F31A3-EF89-4A25-B2D5-20070702AA01}.Debug|ARM.ActiveCfg = Debug|Any CPU {186F31A3-EF89-4A25-B2D5-20070702AA01}.Debug|ARM.Build.0 = Debug|Any CPU {186F31A3-EF89-4A25-B2D5-20070702AA01}.Debug|Mixed Platforms.ActiveCfg = Debug|Any CPU {186F31A3-EF89-4A25-B2D5-20070702AA01}.Debug|Mixed Platforms.Build.0 = Debug|Any CPU {186F31A3-EF89-4A25-B2D5-20070702AA01}.Debug|Win32.ActiveCfg = Debug|Any CPU {186F31A3-EF89-4A25-B2D5-20070702AA01}.Debug|Win32.Build.0 = Debug|Any CPU {186F31A3-EF89-4A25-B2D5-20070702AA01}.Debug|x64.ActiveCfg = Debug|Any CPU {186F31A3-EF89-4A25-B2D5-20070702AA01}.Debug|x64.Build.0 = Debug|Any CPU {186F31A3-EF89-4A25-B2D5-20070702AA01}.Instrumentation|Any CPU.ActiveCfg = Instrumentation|Any CPU {186F31A3-EF89-4A25-B2D5-20070702AA01}.Instrumentation|Any CPU.Build.0 = Instrumentation|Any CPU {186F31A3-EF89-4A25-B2D5-20070702AA01}.Instrumentation|ARM.ActiveCfg = Instrumentation|Any CPU {186F31A3-EF89-4A25-B2D5-20070702AA01}.Instrumentation|ARM.Build.0 = Instrumentation|Any CPU {186F31A3-EF89-4A25-B2D5-20070702AA01}.Instrumentation|Mixed Platforms.ActiveCfg = Instrumentation|Any CPU {186F31A3-EF89-4A25-B2D5-20070702AA01}.Instrumentation|Mixed Platforms.Build.0 = Instrumentation|Any CPU {186F31A3-EF89-4A25-B2D5-20070702AA01}.Instrumentation|Win32.ActiveCfg = Instrumentation|Any CPU {186F31A3-EF89-4A25-B2D5-20070702AA01}.Instrumentation|Win32.Build.0 = Instrumentation|Any CPU {186F31A3-EF89-4A25-B2D5-20070702AA01}.Instrumentation|x64.ActiveCfg = Instrumentation|Any CPU {186F31A3-EF89-4A25-B2D5-20070702AA01}.Instrumentation|x64.Build.0 = Instrumentation|Any CPU {186F31A3-EF89-4A25-B2D5-20070702AA01}.Release|Any CPU.ActiveCfg = Release|Any CPU {186F31A3-EF89-4A25-B2D5-20070702AA01}.Release|Any CPU.Build.0 = Release|Any CPU {186F31A3-EF89-4A25-B2D5-20070702AA01}.Release|ARM.ActiveCfg = Release|Any CPU {186F31A3-EF89-4A25-B2D5-20070702AA01}.Release|ARM.Build.0 = Release|Any CPU {186F31A3-EF89-4A25-B2D5-20070702AA01}.Release|Mixed Platforms.ActiveCfg = Release|Any CPU {186F31A3-EF89-4A25-B2D5-20070702AA01}.Release|Mixed Platforms.Build.0 = Release|Any CPU {186F31A3-EF89-4A25-B2D5-20070702AA01}.Release|Win32.ActiveCfg = Release|Any CPU {186F31A3-EF89-4A25-B2D5-20070702AA01}.Release|Win32.Build.0 = Release|Any CPU {186F31A3-EF89-4A25-B2D5-20070702AA01}.Release|x64.ActiveCfg = Release|Any CPU {186F31A3-EF89-4A25-B2D5-20070702AA01}.Release|x64.Build.0 = Release|Any CPU {186F31A3-EF89-4A25-B2D5-20070911AA01}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {186F31A3-EF89-4A25-B2D5-20070911AA01}.Debug|Any CPU.Build.0 = Debug|Any CPU {186F31A3-EF89-4A25-B2D5-20070911AA01}.Debug|ARM.ActiveCfg = Debug|Any CPU {186F31A3-EF89-4A25-B2D5-20070911AA01}.Debug|ARM.Build.0 = Debug|Any CPU {186F31A3-EF89-4A25-B2D5-20070911AA01}.Debug|Mixed Platforms.ActiveCfg = Debug|Any CPU {186F31A3-EF89-4A25-B2D5-20070911AA01}.Debug|Mixed Platforms.Build.0 = Debug|Any CPU {186F31A3-EF89-4A25-B2D5-20070911AA01}.Debug|Win32.ActiveCfg = Debug|Any CPU {186F31A3-EF89-4A25-B2D5-20070911AA01}.Debug|Win32.Build.0 = Debug|Any CPU {186F31A3-EF89-4A25-B2D5-20070911AA01}.Debug|x64.ActiveCfg = Debug|Any CPU {186F31A3-EF89-4A25-B2D5-20070911AA01}.Debug|x64.Build.0 = Debug|Any CPU {186F31A3-EF89-4A25-B2D5-20070911AA01}.Instrumentation|Any CPU.ActiveCfg = Instrumentation|Any CPU {186F31A3-EF89-4A25-B2D5-20070911AA01}.Instrumentation|Any CPU.Build.0 = Instrumentation|Any CPU {186F31A3-EF89-4A25-B2D5-20070911AA01}.Instrumentation|ARM.ActiveCfg = Instrumentation|Any CPU {186F31A3-EF89-4A25-B2D5-20070911AA01}.Instrumentation|ARM.Build.0 = Instrumentation|Any CPU {186F31A3-EF89-4A25-B2D5-20070911AA01}.Instrumentation|Mixed Platforms.ActiveCfg = Instrumentation|Any CPU {186F31A3-EF89-4A25-B2D5-20070911AA01}.Instrumentation|Mixed Platforms.Build.0 = Instrumentation|Any CPU {186F31A3-EF89-4A25-B2D5-20070911AA01}.Instrumentation|Win32.ActiveCfg = Instrumentation|Any CPU {186F31A3-EF89-4A25-B2D5-20070911AA01}.Instrumentation|Win32.Build.0 = Instrumentation|Any CPU {186F31A3-EF89-4A25-B2D5-20070911AA01}.Instrumentation|x64.ActiveCfg = Instrumentation|Any CPU {186F31A3-EF89-4A25-B2D5-20070911AA01}.Instrumentation|x64.Build.0 = Instrumentation|Any CPU {186F31A3-EF89-4A25-B2D5-20070911AA01}.Release|Any CPU.ActiveCfg = Release|Any CPU {186F31A3-EF89-4A25-B2D5-20070911AA01}.Release|Any CPU.Build.0 = Release|Any CPU {186F31A3-EF89-4A25-B2D5-20070911AA01}.Release|ARM.ActiveCfg = Release|Any CPU {186F31A3-EF89-4A25-B2D5-20070911AA01}.Release|ARM.Build.0 = Release|Any CPU {186F31A3-EF89-4A25-B2D5-20070911AA01}.Release|Mixed Platforms.ActiveCfg = Release|Any CPU {186F31A3-EF89-4A25-B2D5-20070911AA01}.Release|Mixed Platforms.Build.0 = Release|Any CPU {186F31A3-EF89-4A25-B2D5-20070911AA01}.Release|Win32.ActiveCfg = Release|Any CPU {186F31A3-EF89-4A25-B2D5-20070911AA01}.Release|Win32.Build.0 = Release|Any CPU {186F31A3-EF89-4A25-B2D5-20070911AA01}.Release|x64.ActiveCfg = Release|Any CPU {186F31A3-EF89-4A25-B2D5-20070911AA01}.Release|x64.Build.0 = Release|Any CPU {186F31A3-EF89-4A25-B2D5-20070724AA02}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {186F31A3-EF89-4A25-B2D5-20070724AA02}.Debug|Any CPU.Build.0 = Debug|Any CPU {186F31A3-EF89-4A25-B2D5-20070724AA02}.Debug|ARM.ActiveCfg = Debug|Any CPU {186F31A3-EF89-4A25-B2D5-20070724AA02}.Debug|ARM.Build.0 = Debug|Any CPU {186F31A3-EF89-4A25-B2D5-20070724AA02}.Debug|Mixed Platforms.ActiveCfg = Debug|Any CPU {186F31A3-EF89-4A25-B2D5-20070724AA02}.Debug|Mixed Platforms.Build.0 = Debug|Any CPU {186F31A3-EF89-4A25-B2D5-20070724AA02}.Debug|Win32.ActiveCfg = Debug|Any CPU {186F31A3-EF89-4A25-B2D5-20070724AA02}.Debug|Win32.Build.0 = Debug|Any CPU {186F31A3-EF89-4A25-B2D5-20070724AA02}.Debug|x64.ActiveCfg = Debug|Any CPU {186F31A3-EF89-4A25-B2D5-20070724AA02}.Debug|x64.Build.0 = Debug|Any CPU {186F31A3-EF89-4A25-B2D5-20070724AA02}.Instrumentation|Any CPU.ActiveCfg = Instrumentation|Any CPU {186F31A3-EF89-4A25-B2D5-20070724AA02}.Instrumentation|Any CPU.Build.0 = Instrumentation|Any CPU {186F31A3-EF89-4A25-B2D5-20070724AA02}.Instrumentation|ARM.ActiveCfg = Instrumentation|Any CPU {186F31A3-EF89-4A25-B2D5-20070724AA02}.Instrumentation|ARM.Build.0 = Instrumentation|Any CPU {186F31A3-EF89-4A25-B2D5-20070724AA02}.Instrumentation|Mixed Platforms.ActiveCfg = Instrumentation|Any CPU {186F31A3-EF89-4A25-B2D5-20070724AA02}.Instrumentation|Mixed Platforms.Build.0 = Instrumentation|Any CPU {186F31A3-EF89-4A25-B2D5-20070724AA02}.Instrumentation|Win32.ActiveCfg = Instrumentation|Any CPU {186F31A3-EF89-4A25-B2D5-20070724AA02}.Instrumentation|Win32.Build.0 = Instrumentation|Any CPU {186F31A3-EF89-4A25-B2D5-20070724AA02}.Instrumentation|x64.ActiveCfg = Instrumentation|Any CPU {186F31A3-EF89-4A25-B2D5-20070724AA02}.Instrumentation|x64.Build.0 = Instrumentation|Any CPU {186F31A3-EF89-4A25-B2D5-20070724AA02}.Release|Any CPU.ActiveCfg = Release|Any CPU {186F31A3-EF89-4A25-B2D5-20070724AA02}.Release|Any CPU.Build.0 = Release|Any CPU {186F31A3-EF89-4A25-B2D5-20070724AA02}.Release|ARM.ActiveCfg = Release|Any CPU {186F31A3-EF89-4A25-B2D5-20070724AA02}.Release|ARM.Build.0 = Release|Any CPU {186F31A3-EF89-4A25-B2D5-20070724AA02}.Release|Mixed Platforms.ActiveCfg = Release|Any CPU {186F31A3-EF89-4A25-B2D5-20070724AA02}.Release|Mixed Platforms.Build.0 = Release|Any CPU {186F31A3-EF89-4A25-B2D5-20070724AA02}.Release|Win32.ActiveCfg = Release|Any CPU {186F31A3-EF89-4A25-B2D5-20070724AA02}.Release|Win32.Build.0 = Release|Any CPU {186F31A3-EF89-4A25-B2D5-20070724AA02}.Release|x64.ActiveCfg = Release|Any CPU {186F31A3-EF89-4A25-B2D5-20070724AA02}.Release|x64.Build.0 = Release|Any CPU {186F31A3-EF89-4A25-B2D5-20080519AA01}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {186F31A3-EF89-4A25-B2D5-20080519AA01}.Debug|Any CPU.Build.0 = Debug|Any CPU {186F31A3-EF89-4A25-B2D5-20080519AA01}.Debug|ARM.ActiveCfg = Debug|Any CPU {186F31A3-EF89-4A25-B2D5-20080519AA01}.Debug|ARM.Build.0 = Debug|Any CPU {186F31A3-EF89-4A25-B2D5-20080519AA01}.Debug|Mixed Platforms.ActiveCfg = Debug|Any CPU {186F31A3-EF89-4A25-B2D5-20080519AA01}.Debug|Mixed Platforms.Build.0 = Debug|Any CPU {186F31A3-EF89-4A25-B2D5-20080519AA01}.Debug|Win32.ActiveCfg = Debug|Any CPU {186F31A3-EF89-4A25-B2D5-20080519AA01}.Debug|Win32.Build.0 = Debug|Any CPU {186F31A3-EF89-4A25-B2D5-20080519AA01}.Debug|x64.ActiveCfg = Debug|Any CPU {186F31A3-EF89-4A25-B2D5-20080519AA01}.Debug|x64.Build.0 = Debug|Any CPU {186F31A3-EF89-4A25-B2D5-20080519AA01}.Instrumentation|Any CPU.ActiveCfg = Instrumentation|Any CPU {186F31A3-EF89-4A25-B2D5-20080519AA01}.Instrumentation|Any CPU.Build.0 = Instrumentation|Any CPU {186F31A3-EF89-4A25-B2D5-20080519AA01}.Instrumentation|ARM.ActiveCfg = Instrumentation|Any CPU {186F31A3-EF89-4A25-B2D5-20080519AA01}.Instrumentation|ARM.Build.0 = Instrumentation|Any CPU {186F31A3-EF89-4A25-B2D5-20080519AA01}.Instrumentation|Mixed Platforms.ActiveCfg = Instrumentation|Any CPU {186F31A3-EF89-4A25-B2D5-20080519AA01}.Instrumentation|Mixed Platforms.Build.0 = Instrumentation|Any CPU {186F31A3-EF89-4A25-B2D5-20080519AA01}.Instrumentation|Win32.ActiveCfg = Instrumentation|Any CPU {186F31A3-EF89-4A25-B2D5-20080519AA01}.Instrumentation|Win32.Build.0 = Instrumentation|Any CPU {186F31A3-EF89-4A25-B2D5-20080519AA01}.Instrumentation|x64.ActiveCfg = Instrumentation|Any CPU {186F31A3-EF89-4A25-B2D5-20080519AA01}.Instrumentation|x64.Build.0 = Instrumentation|Any CPU {186F31A3-EF89-4A25-B2D5-20080519AA01}.Release|Any CPU.ActiveCfg = Release|Any CPU {186F31A3-EF89-4A25-B2D5-20080519AA01}.Release|Any CPU.Build.0 = Release|Any CPU {186F31A3-EF89-4A25-B2D5-20080519AA01}.Release|ARM.ActiveCfg = Release|Any CPU {186F31A3-EF89-4A25-B2D5-20080519AA01}.Release|ARM.Build.0 = Release|Any CPU {186F31A3-EF89-4A25-B2D5-20080519AA01}.Release|Mixed Platforms.ActiveCfg = Release|Any CPU {186F31A3-EF89-4A25-B2D5-20080519AA01}.Release|Mixed Platforms.Build.0 = Release|Any CPU {186F31A3-EF89-4A25-B2D5-20080519AA01}.Release|Win32.ActiveCfg = Release|Any CPU {186F31A3-EF89-4A25-B2D5-20080519AA01}.Release|Win32.Build.0 = Release|Any CPU {186F31A3-EF89-4A25-B2D5-20080519AA01}.Release|x64.ActiveCfg = Release|Any CPU {186F31A3-EF89-4A25-B2D5-20080519AA01}.Release|x64.Build.0 = Release|Any CPU {186F31A3-EF89-4A25-B2D5-20070725AA01}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {186F31A3-EF89-4A25-B2D5-20070725AA01}.Debug|Any CPU.Build.0 = Debug|Any CPU {186F31A3-EF89-4A25-B2D5-20070725AA01}.Debug|ARM.ActiveCfg = Debug|Any CPU {186F31A3-EF89-4A25-B2D5-20070725AA01}.Debug|ARM.Build.0 = Debug|Any CPU {186F31A3-EF89-4A25-B2D5-20070725AA01}.Debug|Mixed Platforms.ActiveCfg = Debug|Any CPU {186F31A3-EF89-4A25-B2D5-20070725AA01}.Debug|Mixed Platforms.Build.0 = Debug|Any CPU {186F31A3-EF89-4A25-B2D5-20070725AA01}.Debug|Win32.ActiveCfg = Debug|Any CPU {186F31A3-EF89-4A25-B2D5-20070725AA01}.Debug|Win32.Build.0 = Debug|Any CPU {186F31A3-EF89-4A25-B2D5-20070725AA01}.Debug|x64.ActiveCfg = Debug|Any CPU {186F31A3-EF89-4A25-B2D5-20070725AA01}.Debug|x64.Build.0 = Debug|Any CPU {186F31A3-EF89-4A25-B2D5-20070725AA01}.Instrumentation|Any CPU.ActiveCfg = Instrumentation|Any CPU {186F31A3-EF89-4A25-B2D5-20070725AA01}.Instrumentation|Any CPU.Build.0 = Instrumentation|Any CPU {186F31A3-EF89-4A25-B2D5-20070725AA01}.Instrumentation|ARM.ActiveCfg = Instrumentation|Any CPU {186F31A3-EF89-4A25-B2D5-20070725AA01}.Instrumentation|ARM.Build.0 = Instrumentation|Any CPU {186F31A3-EF89-4A25-B2D5-20070725AA01}.Instrumentation|Mixed Platforms.ActiveCfg = Instrumentation|Any CPU {186F31A3-EF89-4A25-B2D5-20070725AA01}.Instrumentation|Mixed Platforms.Build.0 = Instrumentation|Any CPU {186F31A3-EF89-4A25-B2D5-20070725AA01}.Instrumentation|Win32.ActiveCfg = Instrumentation|Any CPU {186F31A3-EF89-4A25-B2D5-20070725AA01}.Instrumentation|Win32.Build.0 = Instrumentation|Any CPU {186F31A3-EF89-4A25-B2D5-20070725AA01}.Instrumentation|x64.ActiveCfg = Instrumentation|Any CPU {186F31A3-EF89-4A25-B2D5-20070725AA01}.Instrumentation|x64.Build.0 = Instrumentation|Any CPU {186F31A3-EF89-4A25-B2D5-20070725AA01}.Release|Any CPU.ActiveCfg = Release|Any CPU {186F31A3-EF89-4A25-B2D5-20070725AA01}.Release|Any CPU.Build.0 = Release|Any CPU {186F31A3-EF89-4A25-B2D5-20070725AA01}.Release|ARM.ActiveCfg = Release|Any CPU {186F31A3-EF89-4A25-B2D5-20070725AA01}.Release|ARM.Build.0 = Release|Any CPU {186F31A3-EF89-4A25-B2D5-20070725AA01}.Release|Mixed Platforms.ActiveCfg = Release|Any CPU {186F31A3-EF89-4A25-B2D5-20070725AA01}.Release|Mixed Platforms.Build.0 = Release|Any CPU {186F31A3-EF89-4A25-B2D5-20070725AA01}.Release|Win32.ActiveCfg = Release|Any CPU {186F31A3-EF89-4A25-B2D5-20070725AA01}.Release|Win32.Build.0 = Release|Any CPU {186F31A3-EF89-4A25-B2D5-20070725AA01}.Release|x64.ActiveCfg = Release|Any CPU {186F31A3-EF89-4A25-B2D5-20070725AA01}.Release|x64.Build.0 = Release|Any CPU {186F31A3-EF89-4A25-B2D5-20070726AA01}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {186F31A3-EF89-4A25-B2D5-20070726AA01}.Debug|Any CPU.Build.0 = Debug|Any CPU {186F31A3-EF89-4A25-B2D5-20070726AA01}.Debug|ARM.ActiveCfg = Debug|Any CPU {186F31A3-EF89-4A25-B2D5-20070726AA01}.Debug|ARM.Build.0 = Debug|Any CPU {186F31A3-EF89-4A25-B2D5-20070726AA01}.Debug|Mixed Platforms.ActiveCfg = Debug|Any CPU {186F31A3-EF89-4A25-B2D5-20070726AA01}.Debug|Mixed Platforms.Build.0 = Debug|Any CPU {186F31A3-EF89-4A25-B2D5-20070726AA01}.Debug|Win32.ActiveCfg = Debug|Any CPU {186F31A3-EF89-4A25-B2D5-20070726AA01}.Debug|Win32.Build.0 = Debug|Any CPU {186F31A3-EF89-4A25-B2D5-20070726AA01}.Debug|x64.ActiveCfg = Debug|Any CPU {186F31A3-EF89-4A25-B2D5-20070726AA01}.Debug|x64.Build.0 = Debug|Any CPU {186F31A3-EF89-4A25-B2D5-20070726AA01}.Instrumentation|Any CPU.ActiveCfg = Instrumentation|Any CPU {186F31A3-EF89-4A25-B2D5-20070726AA01}.Instrumentation|Any CPU.Build.0 = Instrumentation|Any CPU {186F31A3-EF89-4A25-B2D5-20070726AA01}.Instrumentation|ARM.ActiveCfg = Instrumentation|Any CPU {186F31A3-EF89-4A25-B2D5-20070726AA01}.Instrumentation|ARM.Build.0 = Instrumentation|Any CPU {186F31A3-EF89-4A25-B2D5-20070726AA01}.Instrumentation|Mixed Platforms.ActiveCfg = Instrumentation|Any CPU {186F31A3-EF89-4A25-B2D5-20070726AA01}.Instrumentation|Mixed Platforms.Build.0 = Instrumentation|Any CPU {186F31A3-EF89-4A25-B2D5-20070726AA01}.Instrumentation|Win32.ActiveCfg = Instrumentation|Any CPU {186F31A3-EF89-4A25-B2D5-20070726AA01}.Instrumentation|Win32.Build.0 = Instrumentation|Any CPU {186F31A3-EF89-4A25-B2D5-20070726AA01}.Instrumentation|x64.ActiveCfg = Instrumentation|Any CPU {186F31A3-EF89-4A25-B2D5-20070726AA01}.Instrumentation|x64.Build.0 = Instrumentation|Any CPU {186F31A3-EF89-4A25-B2D5-20070726AA01}.Release|Any CPU.ActiveCfg = Release|Any CPU {186F31A3-EF89-4A25-B2D5-20070726AA01}.Release|Any CPU.Build.0 = Release|Any CPU {186F31A3-EF89-4A25-B2D5-20070726AA01}.Release|ARM.ActiveCfg = Release|Any CPU {186F31A3-EF89-4A25-B2D5-20070726AA01}.Release|ARM.Build.0 = Release|Any CPU {186F31A3-EF89-4A25-B2D5-20070726AA01}.Release|Mixed Platforms.ActiveCfg = Release|Any CPU {186F31A3-EF89-4A25-B2D5-20070726AA01}.Release|Mixed Platforms.Build.0 = Release|Any CPU {186F31A3-EF89-4A25-B2D5-20070726AA01}.Release|Win32.ActiveCfg = Release|Any CPU {186F31A3-EF89-4A25-B2D5-20070726AA01}.Release|Win32.Build.0 = Release|Any CPU {186F31A3-EF89-4A25-B2D5-20070726AA01}.Release|x64.ActiveCfg = Release|Any CPU {186F31A3-EF89-4A25-B2D5-20070726AA01}.Release|x64.Build.0 = Release|Any CPU {186F31A3-EF89-4A25-B2D5-20070803AA01}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {186F31A3-EF89-4A25-B2D5-20070803AA01}.Debug|Any CPU.Build.0 = Debug|Any CPU {186F31A3-EF89-4A25-B2D5-20070803AA01}.Debug|ARM.ActiveCfg = Debug|Any CPU {186F31A3-EF89-4A25-B2D5-20070803AA01}.Debug|ARM.Build.0 = Debug|Any CPU {186F31A3-EF89-4A25-B2D5-20070803AA01}.Debug|Mixed Platforms.ActiveCfg = Debug|Any CPU {186F31A3-EF89-4A25-B2D5-20070803AA01}.Debug|Mixed Platforms.Build.0 = Debug|Any CPU {186F31A3-EF89-4A25-B2D5-20070803AA01}.Debug|Win32.ActiveCfg = Debug|Any CPU {186F31A3-EF89-4A25-B2D5-20070803AA01}.Debug|Win32.Build.0 = Debug|Any CPU {186F31A3-EF89-4A25-B2D5-20070803AA01}.Debug|x64.ActiveCfg = Debug|Any CPU {186F31A3-EF89-4A25-B2D5-20070803AA01}.Debug|x64.Build.0 = Debug|Any CPU {186F31A3-EF89-4A25-B2D5-20070803AA01}.Instrumentation|Any CPU.ActiveCfg = Instrumentation|Any CPU {186F31A3-EF89-4A25-B2D5-20070803AA01}.Instrumentation|Any CPU.Build.0 = Instrumentation|Any CPU {186F31A3-EF89-4A25-B2D5-20070803AA01}.Instrumentation|ARM.ActiveCfg = Instrumentation|Any CPU {186F31A3-EF89-4A25-B2D5-20070803AA01}.Instrumentation|ARM.Build.0 = Instrumentation|Any CPU {186F31A3-EF89-4A25-B2D5-20070803AA01}.Instrumentation|Mixed Platforms.ActiveCfg = Instrumentation|Any CPU {186F31A3-EF89-4A25-B2D5-20070803AA01}.Instrumentation|Mixed Platforms.Build.0 = Instrumentation|Any CPU {186F31A3-EF89-4A25-B2D5-20070803AA01}.Instrumentation|Win32.ActiveCfg = Instrumentation|Any CPU {186F31A3-EF89-4A25-B2D5-20070803AA01}.Instrumentation|Win32.Build.0 = Instrumentation|Any CPU {186F31A3-EF89-4A25-B2D5-20070803AA01}.Instrumentation|x64.ActiveCfg = Instrumentation|Any CPU {186F31A3-EF89-4A25-B2D5-20070803AA01}.Instrumentation|x64.Build.0 = Instrumentation|Any CPU {186F31A3-EF89-4A25-B2D5-20070803AA01}.Release|Any CPU.ActiveCfg = Release|Any CPU {186F31A3-EF89-4A25-B2D5-20070803AA01}.Release|Any CPU.Build.0 = Release|Any CPU {186F31A3-EF89-4A25-B2D5-20070803AA01}.Release|ARM.ActiveCfg = Release|Any CPU {186F31A3-EF89-4A25-B2D5-20070803AA01}.Release|ARM.Build.0 = Release|Any CPU {186F31A3-EF89-4A25-B2D5-20070803AA01}.Release|Mixed Platforms.ActiveCfg = Release|Any CPU {186F31A3-EF89-4A25-B2D5-20070803AA01}.Release|Mixed Platforms.Build.0 = Release|Any CPU {186F31A3-EF89-4A25-B2D5-20070803AA01}.Release|Win32.ActiveCfg = Release|Any CPU {186F31A3-EF89-4A25-B2D5-20070803AA01}.Release|Win32.Build.0 = Release|Any CPU {186F31A3-EF89-4A25-B2D5-20070803AA01}.Release|x64.ActiveCfg = Release|Any CPU {186F31A3-EF89-4A25-B2D5-20070803AA01}.Release|x64.Build.0 = Release|Any CPU {186F31A3-EF89-4A25-B2D5-20070912AA01}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {186F31A3-EF89-4A25-B2D5-20070912AA01}.Debug|Any CPU.Build.0 = Debug|Any CPU {186F31A3-EF89-4A25-B2D5-20070912AA01}.Debug|ARM.ActiveCfg = Debug|Any CPU {186F31A3-EF89-4A25-B2D5-20070912AA01}.Debug|ARM.Build.0 = Debug|Any CPU {186F31A3-EF89-4A25-B2D5-20070912AA01}.Debug|Mixed Platforms.ActiveCfg = Debug|Any CPU {186F31A3-EF89-4A25-B2D5-20070912AA01}.Debug|Mixed Platforms.Build.0 = Debug|Any CPU {186F31A3-EF89-4A25-B2D5-20070912AA01}.Debug|Win32.ActiveCfg = Debug|Any CPU {186F31A3-EF89-4A25-B2D5-20070912AA01}.Debug|Win32.Build.0 = Debug|Any CPU {186F31A3-EF89-4A25-B2D5-20070912AA01}.Debug|x64.ActiveCfg = Debug|Any CPU {186F31A3-EF89-4A25-B2D5-20070912AA01}.Debug|x64.Build.0 = Debug|Any CPU {186F31A3-EF89-4A25-B2D5-20070912AA01}.Instrumentation|Any CPU.ActiveCfg = Instrumentation|Any CPU {186F31A3-EF89-4A25-B2D5-20070912AA01}.Instrumentation|Any CPU.Build.0 = Instrumentation|Any CPU {186F31A3-EF89-4A25-B2D5-20070912AA01}.Instrumentation|ARM.ActiveCfg = Instrumentation|Any CPU {186F31A3-EF89-4A25-B2D5-20070912AA01}.Instrumentation|ARM.Build.0 = Instrumentation|Any CPU {186F31A3-EF89-4A25-B2D5-20070912AA01}.Instrumentation|Mixed Platforms.ActiveCfg = Instrumentation|Any CPU {186F31A3-EF89-4A25-B2D5-20070912AA01}.Instrumentation|Mixed Platforms.Build.0 = Instrumentation|Any CPU {186F31A3-EF89-4A25-B2D5-20070912AA01}.Instrumentation|Win32.ActiveCfg = Instrumentation|Any CPU {186F31A3-EF89-4A25-B2D5-20070912AA01}.Instrumentation|Win32.Build.0 = Instrumentation|Any CPU {186F31A3-EF89-4A25-B2D5-20070912AA01}.Instrumentation|x64.ActiveCfg = Instrumentation|Any CPU {186F31A3-EF89-4A25-B2D5-20070912AA01}.Instrumentation|x64.Build.0 = Instrumentation|Any CPU {186F31A3-EF89-4A25-B2D5-20070912AA01}.Release|Any CPU.ActiveCfg = Release|Any CPU {186F31A3-EF89-4A25-B2D5-20070912AA01}.Release|Any CPU.Build.0 = Release|Any CPU {186F31A3-EF89-4A25-B2D5-20070912AA01}.Release|ARM.ActiveCfg = Release|Any CPU {186F31A3-EF89-4A25-B2D5-20070912AA01}.Release|ARM.Build.0 = Release|Any CPU {186F31A3-EF89-4A25-B2D5-20070912AA01}.Release|Mixed Platforms.ActiveCfg = Release|Any CPU {186F31A3-EF89-4A25-B2D5-20070912AA01}.Release|Mixed Platforms.Build.0 = Release|Any CPU {186F31A3-EF89-4A25-B2D5-20070912AA01}.Release|Win32.ActiveCfg = Release|Any CPU {186F31A3-EF89-4A25-B2D5-20070912AA01}.Release|Win32.Build.0 = Release|Any CPU {186F31A3-EF89-4A25-B2D5-20070912AA01}.Release|x64.ActiveCfg = Release|Any CPU {186F31A3-EF89-4A25-B2D5-20070912AA01}.Release|x64.Build.0 = Release|Any CPU {186F31A3-EF89-4A25-B2D5-20071018AA01}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {186F31A3-EF89-4A25-B2D5-20071018AA01}.Debug|Any CPU.Build.0 = Debug|Any CPU {186F31A3-EF89-4A25-B2D5-20071018AA01}.Debug|ARM.ActiveCfg = Debug|Any CPU {186F31A3-EF89-4A25-B2D5-20071018AA01}.Debug|ARM.Build.0 = Debug|Any CPU {186F31A3-EF89-4A25-B2D5-20071018AA01}.Debug|Mixed Platforms.ActiveCfg = Debug|Any CPU {186F31A3-EF89-4A25-B2D5-20071018AA01}.Debug|Mixed Platforms.Build.0 = Debug|Any CPU {186F31A3-EF89-4A25-B2D5-20071018AA01}.Debug|Win32.ActiveCfg = Debug|Any CPU {186F31A3-EF89-4A25-B2D5-20071018AA01}.Debug|Win32.Build.0 = Debug|Any CPU {186F31A3-EF89-4A25-B2D5-20071018AA01}.Debug|x64.ActiveCfg = Debug|Any CPU {186F31A3-EF89-4A25-B2D5-20071018AA01}.Debug|x64.Build.0 = Debug|Any CPU {186F31A3-EF89-4A25-B2D5-20071018AA01}.Instrumentation|Any CPU.ActiveCfg = Instrumentation|Any CPU {186F31A3-EF89-4A25-B2D5-20071018AA01}.Instrumentation|Any CPU.Build.0 = Instrumentation|Any CPU {186F31A3-EF89-4A25-B2D5-20071018AA01}.Instrumentation|ARM.ActiveCfg = Instrumentation|Any CPU {186F31A3-EF89-4A25-B2D5-20071018AA01}.Instrumentation|ARM.Build.0 = Instrumentation|Any CPU {186F31A3-EF89-4A25-B2D5-20071018AA01}.Instrumentation|Mixed Platforms.ActiveCfg = Instrumentation|Any CPU {186F31A3-EF89-4A25-B2D5-20071018AA01}.Instrumentation|Mixed Platforms.Build.0 = Instrumentation|Any CPU {186F31A3-EF89-4A25-B2D5-20071018AA01}.Instrumentation|Win32.ActiveCfg = Instrumentation|Any CPU {186F31A3-EF89-4A25-B2D5-20071018AA01}.Instrumentation|Win32.Build.0 = Instrumentation|Any CPU {186F31A3-EF89-4A25-B2D5-20071018AA01}.Instrumentation|x64.ActiveCfg = Instrumentation|Any CPU {186F31A3-EF89-4A25-B2D5-20071018AA01}.Instrumentation|x64.Build.0 = Instrumentation|Any CPU {186F31A3-EF89-4A25-B2D5-20071018AA01}.Release|Any CPU.ActiveCfg = Release|Any CPU {186F31A3-EF89-4A25-B2D5-20071018AA01}.Release|Any CPU.Build.0 = Release|Any CPU {186F31A3-EF89-4A25-B2D5-20071018AA01}.Release|ARM.ActiveCfg = Release|Any CPU {186F31A3-EF89-4A25-B2D5-20071018AA01}.Release|ARM.Build.0 = Release|Any CPU {186F31A3-EF89-4A25-B2D5-20071018AA01}.Release|Mixed Platforms.ActiveCfg = Release|Any CPU {186F31A3-EF89-4A25-B2D5-20071018AA01}.Release|Mixed Platforms.Build.0 = Release|Any CPU {186F31A3-EF89-4A25-B2D5-20071018AA01}.Release|Win32.ActiveCfg = Release|Any CPU {186F31A3-EF89-4A25-B2D5-20071018AA01}.Release|Win32.Build.0 = Release|Any CPU {186F31A3-EF89-4A25-B2D5-20071018AA01}.Release|x64.ActiveCfg = Release|Any CPU {186F31A3-EF89-4A25-B2D5-20071018AA01}.Release|x64.Build.0 = Release|Any CPU {186F31A3-EF89-4A25-B2D5-20071208AA01}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {186F31A3-EF89-4A25-B2D5-20071208AA01}.Debug|Any CPU.Build.0 = Debug|Any CPU {186F31A3-EF89-4A25-B2D5-20071208AA01}.Debug|ARM.ActiveCfg = Debug|Any CPU {186F31A3-EF89-4A25-B2D5-20071208AA01}.Debug|ARM.Build.0 = Debug|Any CPU {186F31A3-EF89-4A25-B2D5-20071208AA01}.Debug|Mixed Platforms.ActiveCfg = Debug|Any CPU {186F31A3-EF89-4A25-B2D5-20071208AA01}.Debug|Mixed Platforms.Build.0 = Debug|Any CPU {186F31A3-EF89-4A25-B2D5-20071208AA01}.Debug|Win32.ActiveCfg = Debug|Any CPU {186F31A3-EF89-4A25-B2D5-20071208AA01}.Debug|Win32.Build.0 = Debug|Any CPU {186F31A3-EF89-4A25-B2D5-20071208AA01}.Debug|x64.ActiveCfg = Debug|Any CPU {186F31A3-EF89-4A25-B2D5-20071208AA01}.Debug|x64.Build.0 = Debug|Any CPU {186F31A3-EF89-4A25-B2D5-20071208AA01}.Instrumentation|Any CPU.ActiveCfg = Instrumentation|Any CPU {186F31A3-EF89-4A25-B2D5-20071208AA01}.Instrumentation|Any CPU.Build.0 = Instrumentation|Any CPU {186F31A3-EF89-4A25-B2D5-20071208AA01}.Instrumentation|ARM.ActiveCfg = Instrumentation|Any CPU {186F31A3-EF89-4A25-B2D5-20071208AA01}.Instrumentation|ARM.Build.0 = Instrumentation|Any CPU {186F31A3-EF89-4A25-B2D5-20071208AA01}.Instrumentation|Mixed Platforms.ActiveCfg = Instrumentation|Any CPU {186F31A3-EF89-4A25-B2D5-20071208AA01}.Instrumentation|Mixed Platforms.Build.0 = Instrumentation|Any CPU {186F31A3-EF89-4A25-B2D5-20071208AA01}.Instrumentation|Win32.ActiveCfg = Instrumentation|Any CPU {186F31A3-EF89-4A25-B2D5-20071208AA01}.Instrumentation|Win32.Build.0 = Instrumentation|Any CPU {186F31A3-EF89-4A25-B2D5-20071208AA01}.Instrumentation|x64.ActiveCfg = Instrumentation|Any CPU {186F31A3-EF89-4A25-B2D5-20071208AA01}.Instrumentation|x64.Build.0 = Instrumentation|Any CPU {186F31A3-EF89-4A25-B2D5-20071208AA01}.Release|Any CPU.ActiveCfg = Release|Any CPU {186F31A3-EF89-4A25-B2D5-20071208AA01}.Release|Any CPU.Build.0 = Release|Any CPU {186F31A3-EF89-4A25-B2D5-20071208AA01}.Release|ARM.ActiveCfg = Release|Any CPU {186F31A3-EF89-4A25-B2D5-20071208AA01}.Release|ARM.Build.0 = Release|Any CPU {186F31A3-EF89-4A25-B2D5-20071208AA01}.Release|Mixed Platforms.ActiveCfg = Release|Any CPU {186F31A3-EF89-4A25-B2D5-20071208AA01}.Release|Mixed Platforms.Build.0 = Release|Any CPU {186F31A3-EF89-4A25-B2D5-20071208AA01}.Release|Win32.ActiveCfg = Release|Any CPU {186F31A3-EF89-4A25-B2D5-20071208AA01}.Release|Win32.Build.0 = Release|Any CPU {186F31A3-EF89-4A25-B2D5-20071208AA01}.Release|x64.ActiveCfg = Release|Any CPU {186F31A3-EF89-4A25-B2D5-20071208AA01}.Release|x64.Build.0 = Release|Any CPU {96BF0234-1D60-4401-A6B9-99839187234E}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {96BF0234-1D60-4401-A6B9-99839187234E}.Debug|Any CPU.Build.0 = Debug|Any CPU {96BF0234-1D60-4401-A6B9-99839187234E}.Debug|ARM.ActiveCfg = Debug|Any CPU {96BF0234-1D60-4401-A6B9-99839187234E}.Debug|ARM.Build.0 = Debug|Any CPU {96BF0234-1D60-4401-A6B9-99839187234E}.Debug|Mixed Platforms.ActiveCfg = Debug|Any CPU {96BF0234-1D60-4401-A6B9-99839187234E}.Debug|Mixed Platforms.Build.0 = Debug|Any CPU {96BF0234-1D60-4401-A6B9-99839187234E}.Debug|Win32.ActiveCfg = Debug|Any CPU {96BF0234-1D60-4401-A6B9-99839187234E}.Debug|Win32.Build.0 = Debug|Any CPU {96BF0234-1D60-4401-A6B9-99839187234E}.Debug|x64.ActiveCfg = Debug|Any CPU {96BF0234-1D60-4401-A6B9-99839187234E}.Debug|x64.Build.0 = Debug|Any CPU {96BF0234-1D60-4401-A6B9-99839187234E}.Instrumentation|Any CPU.ActiveCfg = Instrumentation|Any CPU {96BF0234-1D60-4401-A6B9-99839187234E}.Instrumentation|Any CPU.Build.0 = Instrumentation|Any CPU {96BF0234-1D60-4401-A6B9-99839187234E}.Instrumentation|ARM.ActiveCfg = Instrumentation|Any CPU {96BF0234-1D60-4401-A6B9-99839187234E}.Instrumentation|ARM.Build.0 = Instrumentation|Any CPU {96BF0234-1D60-4401-A6B9-99839187234E}.Instrumentation|Mixed Platforms.ActiveCfg = Instrumentation|Any CPU {96BF0234-1D60-4401-A6B9-99839187234E}.Instrumentation|Mixed Platforms.Build.0 = Instrumentation|Any CPU {96BF0234-1D60-4401-A6B9-99839187234E}.Instrumentation|Win32.ActiveCfg = Instrumentation|Any CPU {96BF0234-1D60-4401-A6B9-99839187234E}.Instrumentation|Win32.Build.0 = Instrumentation|Any CPU {96BF0234-1D60-4401-A6B9-99839187234E}.Instrumentation|x64.ActiveCfg = Instrumentation|Any CPU {96BF0234-1D60-4401-A6B9-99839187234E}.Instrumentation|x64.Build.0 = Instrumentation|Any CPU {96BF0234-1D60-4401-A6B9-99839187234E}.Release|Any CPU.ActiveCfg = Release|Any CPU {96BF0234-1D60-4401-A6B9-99839187234E}.Release|Any CPU.Build.0 = Release|Any CPU {96BF0234-1D60-4401-A6B9-99839187234E}.Release|ARM.ActiveCfg = Release|Any CPU {96BF0234-1D60-4401-A6B9-99839187234E}.Release|ARM.Build.0 = Release|Any CPU {96BF0234-1D60-4401-A6B9-99839187234E}.Release|Mixed Platforms.ActiveCfg = Release|Any CPU {96BF0234-1D60-4401-A6B9-99839187234E}.Release|Mixed Platforms.Build.0 = Release|Any CPU {96BF0234-1D60-4401-A6B9-99839187234E}.Release|Win32.ActiveCfg = Release|Any CPU {96BF0234-1D60-4401-A6B9-99839187234E}.Release|Win32.Build.0 = Release|Any CPU {96BF0234-1D60-4401-A6B9-99839187234E}.Release|x64.ActiveCfg = Release|Any CPU {96BF0234-1D60-4401-A6B9-99839187234E}.Release|x64.Build.0 = Release|Any CPU {186F31A3-EF89-4A25-B2D5-20090606AA01}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {186F31A3-EF89-4A25-B2D5-20090606AA01}.Debug|Any CPU.Build.0 = Debug|Any CPU {186F31A3-EF89-4A25-B2D5-20090606AA01}.Debug|ARM.ActiveCfg = Debug|Any CPU {186F31A3-EF89-4A25-B2D5-20090606AA01}.Debug|ARM.Build.0 = Debug|Any CPU {186F31A3-EF89-4A25-B2D5-20090606AA01}.Debug|Mixed Platforms.ActiveCfg = Debug|Any CPU {186F31A3-EF89-4A25-B2D5-20090606AA01}.Debug|Mixed Platforms.Build.0 = Debug|Any CPU {186F31A3-EF89-4A25-B2D5-20090606AA01}.Debug|Win32.ActiveCfg = Debug|Any CPU {186F31A3-EF89-4A25-B2D5-20090606AA01}.Debug|Win32.Build.0 = Debug|Any CPU {186F31A3-EF89-4A25-B2D5-20090606AA01}.Debug|x64.ActiveCfg = Debug|Any CPU {186F31A3-EF89-4A25-B2D5-20090606AA01}.Debug|x64.Build.0 = Debug|Any CPU {186F31A3-EF89-4A25-B2D5-20090606AA01}.Instrumentation|Any CPU.ActiveCfg = Instrumentation|Any CPU {186F31A3-EF89-4A25-B2D5-20090606AA01}.Instrumentation|Any CPU.Build.0 = Instrumentation|Any CPU {186F31A3-EF89-4A25-B2D5-20090606AA01}.Instrumentation|ARM.ActiveCfg = Instrumentation|Any CPU {186F31A3-EF89-4A25-B2D5-20090606AA01}.Instrumentation|ARM.Build.0 = Instrumentation|Any CPU {186F31A3-EF89-4A25-B2D5-20090606AA01}.Instrumentation|Mixed Platforms.ActiveCfg = Instrumentation|Any CPU {186F31A3-EF89-4A25-B2D5-20090606AA01}.Instrumentation|Mixed Platforms.Build.0 = Instrumentation|Any CPU {186F31A3-EF89-4A25-B2D5-20090606AA01}.Instrumentation|Win32.ActiveCfg = Instrumentation|Any CPU {186F31A3-EF89-4A25-B2D5-20090606AA01}.Instrumentation|Win32.Build.0 = Instrumentation|Any CPU {186F31A3-EF89-4A25-B2D5-20090606AA01}.Instrumentation|x64.ActiveCfg = Instrumentation|Any CPU {186F31A3-EF89-4A25-B2D5-20090606AA01}.Instrumentation|x64.Build.0 = Instrumentation|Any CPU {186F31A3-EF89-4A25-B2D5-20090606AA01}.Release|Any CPU.ActiveCfg = Release|Any CPU {186F31A3-EF89-4A25-B2D5-20090606AA01}.Release|Any CPU.Build.0 = Release|Any CPU {186F31A3-EF89-4A25-B2D5-20090606AA01}.Release|ARM.ActiveCfg = Release|Any CPU {186F31A3-EF89-4A25-B2D5-20090606AA01}.Release|ARM.Build.0 = Release|Any CPU {186F31A3-EF89-4A25-B2D5-20090606AA01}.Release|Mixed Platforms.ActiveCfg = Release|Any CPU {186F31A3-EF89-4A25-B2D5-20090606AA01}.Release|Mixed Platforms.Build.0 = Release|Any CPU {186F31A3-EF89-4A25-B2D5-20090606AA01}.Release|Win32.ActiveCfg = Release|Any CPU {186F31A3-EF89-4A25-B2D5-20090606AA01}.Release|Win32.Build.0 = Release|Any CPU {186F31A3-EF89-4A25-B2D5-20090606AA01}.Release|x64.ActiveCfg = Release|Any CPU {186F31A3-EF89-4A25-B2D5-20090606AA01}.Release|x64.Build.0 = Release|Any CPU {186F31A3-EF89-4A25-B2D5-20080606AA02}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {186F31A3-EF89-4A25-B2D5-20080606AA02}.Debug|Any CPU.Build.0 = Debug|Any CPU {186F31A3-EF89-4A25-B2D5-20080606AA02}.Debug|ARM.ActiveCfg = Debug|Any CPU {186F31A3-EF89-4A25-B2D5-20080606AA02}.Debug|ARM.Build.0 = Debug|Any CPU {186F31A3-EF89-4A25-B2D5-20080606AA02}.Debug|Mixed Platforms.ActiveCfg = Debug|Any CPU {186F31A3-EF89-4A25-B2D5-20080606AA02}.Debug|Mixed Platforms.Build.0 = Debug|Any CPU {186F31A3-EF89-4A25-B2D5-20080606AA02}.Debug|Win32.ActiveCfg = Debug|Any CPU {186F31A3-EF89-4A25-B2D5-20080606AA02}.Debug|Win32.Build.0 = Debug|Any CPU {186F31A3-EF89-4A25-B2D5-20080606AA02}.Debug|x64.ActiveCfg = Debug|Any CPU {186F31A3-EF89-4A25-B2D5-20080606AA02}.Debug|x64.Build.0 = Debug|Any CPU {186F31A3-EF89-4A25-B2D5-20080606AA02}.Instrumentation|Any CPU.ActiveCfg = Instrumentation|Any CPU {186F31A3-EF89-4A25-B2D5-20080606AA02}.Instrumentation|Any CPU.Build.0 = Instrumentation|Any CPU {186F31A3-EF89-4A25-B2D5-20080606AA02}.Instrumentation|ARM.ActiveCfg = Instrumentation|Any CPU {186F31A3-EF89-4A25-B2D5-20080606AA02}.Instrumentation|ARM.Build.0 = Instrumentation|Any CPU {186F31A3-EF89-4A25-B2D5-20080606AA02}.Instrumentation|Mixed Platforms.ActiveCfg = Instrumentation|Any CPU {186F31A3-EF89-4A25-B2D5-20080606AA02}.Instrumentation|Mixed Platforms.Build.0 = Instrumentation|Any CPU {186F31A3-EF89-4A25-B2D5-20080606AA02}.Instrumentation|Win32.ActiveCfg = Instrumentation|Any CPU {186F31A3-EF89-4A25-B2D5-20080606AA02}.Instrumentation|Win32.Build.0 = Instrumentation|Any CPU {186F31A3-EF89-4A25-B2D5-20080606AA02}.Instrumentation|x64.ActiveCfg = Instrumentation|Any CPU {186F31A3-EF89-4A25-B2D5-20080606AA02}.Instrumentation|x64.Build.0 = Instrumentation|Any CPU {186F31A3-EF89-4A25-B2D5-20080606AA02}.Release|Any CPU.ActiveCfg = Release|Any CPU {186F31A3-EF89-4A25-B2D5-20080606AA02}.Release|Any CPU.Build.0 = Release|Any CPU {186F31A3-EF89-4A25-B2D5-20080606AA02}.Release|ARM.ActiveCfg = Release|Any CPU {186F31A3-EF89-4A25-B2D5-20080606AA02}.Release|ARM.Build.0 = Release|Any CPU {186F31A3-EF89-4A25-B2D5-20080606AA02}.Release|Mixed Platforms.ActiveCfg = Release|Any CPU {186F31A3-EF89-4A25-B2D5-20080606AA02}.Release|Mixed Platforms.Build.0 = Release|Any CPU {186F31A3-EF89-4A25-B2D5-20080606AA02}.Release|Win32.ActiveCfg = Release|Any CPU {186F31A3-EF89-4A25-B2D5-20080606AA02}.Release|Win32.Build.0 = Release|Any CPU {186F31A3-EF89-4A25-B2D5-20080606AA02}.Release|x64.ActiveCfg = Release|Any CPU {186F31A3-EF89-4A25-B2D5-20080606AA02}.Release|x64.Build.0 = Release|Any CPU {186F31A3-EF89-4A25-B2D5-20080628AA01}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {186F31A3-EF89-4A25-B2D5-20080628AA01}.Debug|Any CPU.Build.0 = Debug|Any CPU {186F31A3-EF89-4A25-B2D5-20080628AA01}.Debug|ARM.ActiveCfg = Debug|Any CPU {186F31A3-EF89-4A25-B2D5-20080628AA01}.Debug|ARM.Build.0 = Debug|Any CPU {186F31A3-EF89-4A25-B2D5-20080628AA01}.Debug|Mixed Platforms.ActiveCfg = Debug|Any CPU {186F31A3-EF89-4A25-B2D5-20080628AA01}.Debug|Mixed Platforms.Build.0 = Debug|Any CPU {186F31A3-EF89-4A25-B2D5-20080628AA01}.Debug|Win32.ActiveCfg = Debug|Any CPU {186F31A3-EF89-4A25-B2D5-20080628AA01}.Debug|Win32.Build.0 = Debug|Any CPU {186F31A3-EF89-4A25-B2D5-20080628AA01}.Debug|x64.ActiveCfg = Debug|Any CPU {186F31A3-EF89-4A25-B2D5-20080628AA01}.Debug|x64.Build.0 = Debug|Any CPU {186F31A3-EF89-4A25-B2D5-20080628AA01}.Instrumentation|Any CPU.ActiveCfg = Instrumentation|Any CPU {186F31A3-EF89-4A25-B2D5-20080628AA01}.Instrumentation|Any CPU.Build.0 = Instrumentation|Any CPU {186F31A3-EF89-4A25-B2D5-20080628AA01}.Instrumentation|ARM.ActiveCfg = Instrumentation|Any CPU {186F31A3-EF89-4A25-B2D5-20080628AA01}.Instrumentation|ARM.Build.0 = Instrumentation|Any CPU {186F31A3-EF89-4A25-B2D5-20080628AA01}.Instrumentation|Mixed Platforms.ActiveCfg = Instrumentation|Any CPU {186F31A3-EF89-4A25-B2D5-20080628AA01}.Instrumentation|Mixed Platforms.Build.0 = Instrumentation|Any CPU {186F31A3-EF89-4A25-B2D5-20080628AA01}.Instrumentation|Win32.ActiveCfg = Instrumentation|Any CPU {186F31A3-EF89-4A25-B2D5-20080628AA01}.Instrumentation|Win32.Build.0 = Instrumentation|Any CPU {186F31A3-EF89-4A25-B2D5-20080628AA01}.Instrumentation|x64.ActiveCfg = Instrumentation|Any CPU {186F31A3-EF89-4A25-B2D5-20080628AA01}.Instrumentation|x64.Build.0 = Instrumentation|Any CPU {186F31A3-EF89-4A25-B2D5-20080628AA01}.Release|Any CPU.ActiveCfg = Release|Any CPU {186F31A3-EF89-4A25-B2D5-20080628AA01}.Release|Any CPU.Build.0 = Release|Any CPU {186F31A3-EF89-4A25-B2D5-20080628AA01}.Release|ARM.ActiveCfg = Release|Any CPU {186F31A3-EF89-4A25-B2D5-20080628AA01}.Release|ARM.Build.0 = Release|Any CPU {186F31A3-EF89-4A25-B2D5-20080628AA01}.Release|Mixed Platforms.ActiveCfg = Release|Any CPU {186F31A3-EF89-4A25-B2D5-20080628AA01}.Release|Mixed Platforms.Build.0 = Release|Any CPU {186F31A3-EF89-4A25-B2D5-20080628AA01}.Release|Win32.ActiveCfg = Release|Any CPU {186F31A3-EF89-4A25-B2D5-20080628AA01}.Release|Win32.Build.0 = Release|Any CPU {186F31A3-EF89-4A25-B2D5-20080628AA01}.Release|x64.ActiveCfg = Release|Any CPU {186F31A3-EF89-4A25-B2D5-20080628AA01}.Release|x64.Build.0 = Release|Any CPU {186F31A3-EF89-4A25-B2D5-20080630AA01}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {186F31A3-EF89-4A25-B2D5-20080630AA01}.Debug|Any CPU.Build.0 = Debug|Any CPU {186F31A3-EF89-4A25-B2D5-20080630AA01}.Debug|ARM.ActiveCfg = Debug|Any CPU {186F31A3-EF89-4A25-B2D5-20080630AA01}.Debug|ARM.Build.0 = Debug|Any CPU {186F31A3-EF89-4A25-B2D5-20080630AA01}.Debug|Mixed Platforms.ActiveCfg = Debug|Any CPU {186F31A3-EF89-4A25-B2D5-20080630AA01}.Debug|Mixed Platforms.Build.0 = Debug|Any CPU {186F31A3-EF89-4A25-B2D5-20080630AA01}.Debug|Win32.ActiveCfg = Debug|Any CPU {186F31A3-EF89-4A25-B2D5-20080630AA01}.Debug|Win32.Build.0 = Debug|Any CPU {186F31A3-EF89-4A25-B2D5-20080630AA01}.Debug|x64.ActiveCfg = Debug|Any CPU {186F31A3-EF89-4A25-B2D5-20080630AA01}.Debug|x64.Build.0 = Debug|Any CPU {186F31A3-EF89-4A25-B2D5-20080630AA01}.Instrumentation|Any CPU.ActiveCfg = Instrumentation|Any CPU {186F31A3-EF89-4A25-B2D5-20080630AA01}.Instrumentation|Any CPU.Build.0 = Instrumentation|Any CPU {186F31A3-EF89-4A25-B2D5-20080630AA01}.Instrumentation|ARM.ActiveCfg = Instrumentation|Any CPU {186F31A3-EF89-4A25-B2D5-20080630AA01}.Instrumentation|ARM.Build.0 = Instrumentation|Any CPU {186F31A3-EF89-4A25-B2D5-20080630AA01}.Instrumentation|Mixed Platforms.ActiveCfg = Instrumentation|Any CPU {186F31A3-EF89-4A25-B2D5-20080630AA01}.Instrumentation|Mixed Platforms.Build.0 = Instrumentation|Any CPU {186F31A3-EF89-4A25-B2D5-20080630AA01}.Instrumentation|Win32.ActiveCfg = Instrumentation|Any CPU {186F31A3-EF89-4A25-B2D5-20080630AA01}.Instrumentation|Win32.Build.0 = Instrumentation|Any CPU {186F31A3-EF89-4A25-B2D5-20080630AA01}.Instrumentation|x64.ActiveCfg = Instrumentation|Any CPU {186F31A3-EF89-4A25-B2D5-20080630AA01}.Instrumentation|x64.Build.0 = Instrumentation|Any CPU {186F31A3-EF89-4A25-B2D5-20080630AA01}.Release|Any CPU.ActiveCfg = Release|Any CPU {186F31A3-EF89-4A25-B2D5-20080630AA01}.Release|Any CPU.Build.0 = Release|Any CPU {186F31A3-EF89-4A25-B2D5-20080630AA01}.Release|ARM.ActiveCfg = Release|Any CPU {186F31A3-EF89-4A25-B2D5-20080630AA01}.Release|ARM.Build.0 = Release|Any CPU {186F31A3-EF89-4A25-B2D5-20080630AA01}.Release|Mixed Platforms.ActiveCfg = Release|Any CPU {186F31A3-EF89-4A25-B2D5-20080630AA01}.Release|Mixed Platforms.Build.0 = Release|Any CPU {186F31A3-EF89-4A25-B2D5-20080630AA01}.Release|Win32.ActiveCfg = Release|Any CPU {186F31A3-EF89-4A25-B2D5-20080630AA01}.Release|Win32.Build.0 = Release|Any CPU {186F31A3-EF89-4A25-B2D5-20080630AA01}.Release|x64.ActiveCfg = Release|Any CPU {186F31A3-EF89-4A25-B2D5-20080630AA01}.Release|x64.Build.0 = Release|Any CPU {ACE86CB1-7796-4B5F-96AF-B51595944B66}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {ACE86CB1-7796-4B5F-96AF-B51595944B66}.Debug|Any CPU.Build.0 = Debug|Any CPU {ACE86CB1-7796-4B5F-96AF-B51595944B66}.Debug|ARM.ActiveCfg = Debug|Any CPU {ACE86CB1-7796-4B5F-96AF-B51595944B66}.Debug|ARM.Build.0 = Debug|Any CPU {ACE86CB1-7796-4B5F-96AF-B51595944B66}.Debug|Mixed Platforms.ActiveCfg = Debug|Any CPU {ACE86CB1-7796-4B5F-96AF-B51595944B66}.Debug|Mixed Platforms.Build.0 = Debug|Any CPU {ACE86CB1-7796-4B5F-96AF-B51595944B66}.Debug|Win32.ActiveCfg = Debug|Any CPU {ACE86CB1-7796-4B5F-96AF-B51595944B66}.Debug|Win32.Build.0 = Debug|Any CPU {ACE86CB1-7796-4B5F-96AF-B51595944B66}.Debug|x64.ActiveCfg = Debug|Any CPU {ACE86CB1-7796-4B5F-96AF-B51595944B66}.Debug|x64.Build.0 = Debug|Any CPU {ACE86CB1-7796-4B5F-96AF-B51595944B66}.Instrumentation|Any CPU.ActiveCfg = Instrumentation|Any CPU {ACE86CB1-7796-4B5F-96AF-B51595944B66}.Instrumentation|Any CPU.Build.0 = Instrumentation|Any CPU {ACE86CB1-7796-4B5F-96AF-B51595944B66}.Instrumentation|ARM.ActiveCfg = Instrumentation|Any CPU {ACE86CB1-7796-4B5F-96AF-B51595944B66}.Instrumentation|ARM.Build.0 = Instrumentation|Any CPU {ACE86CB1-7796-4B5F-96AF-B51595944B66}.Instrumentation|Mixed Platforms.ActiveCfg = Instrumentation|Any CPU {ACE86CB1-7796-4B5F-96AF-B51595944B66}.Instrumentation|Mixed Platforms.Build.0 = Instrumentation|Any CPU {ACE86CB1-7796-4B5F-96AF-B51595944B66}.Instrumentation|Win32.ActiveCfg = Instrumentation|Any CPU {ACE86CB1-7796-4B5F-96AF-B51595944B66}.Instrumentation|Win32.Build.0 = Instrumentation|Any CPU {ACE86CB1-7796-4B5F-96AF-B51595944B66}.Instrumentation|x64.ActiveCfg = Instrumentation|Any CPU {ACE86CB1-7796-4B5F-96AF-B51595944B66}.Instrumentation|x64.Build.0 = Instrumentation|Any CPU {ACE86CB1-7796-4B5F-96AF-B51595944B66}.Release|Any CPU.ActiveCfg = Release|Any CPU {ACE86CB1-7796-4B5F-96AF-B51595944B66}.Release|Any CPU.Build.0 = Release|Any CPU {ACE86CB1-7796-4B5F-96AF-B51595944B66}.Release|ARM.ActiveCfg = Release|Any CPU {ACE86CB1-7796-4B5F-96AF-B51595944B66}.Release|ARM.Build.0 = Release|Any CPU {ACE86CB1-7796-4B5F-96AF-B51595944B66}.Release|Mixed Platforms.ActiveCfg = Release|Any CPU {ACE86CB1-7796-4B5F-96AF-B51595944B66}.Release|Mixed Platforms.Build.0 = Release|Any CPU {ACE86CB1-7796-4B5F-96AF-B51595944B66}.Release|Win32.ActiveCfg = Release|Any CPU {ACE86CB1-7796-4B5F-96AF-B51595944B66}.Release|Win32.Build.0 = Release|Any CPU {ACE86CB1-7796-4B5F-96AF-B51595944B66}.Release|x64.ActiveCfg = Release|Any CPU {ACE86CB1-7796-4B5F-96AF-B51595944B66}.Release|x64.Build.0 = Release|Any CPU {F1829F0B-1A0E-4844-BF44-106F3ADDF157}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {F1829F0B-1A0E-4844-BF44-106F3ADDF157}.Debug|Any CPU.Build.0 = Debug|Any CPU {F1829F0B-1A0E-4844-BF44-106F3ADDF157}.Debug|ARM.ActiveCfg = Debug|Any CPU {F1829F0B-1A0E-4844-BF44-106F3ADDF157}.Debug|ARM.Build.0 = Debug|Any CPU {F1829F0B-1A0E-4844-BF44-106F3ADDF157}.Debug|Mixed Platforms.ActiveCfg = Debug|Any CPU {F1829F0B-1A0E-4844-BF44-106F3ADDF157}.Debug|Mixed Platforms.Build.0 = Debug|Any CPU {F1829F0B-1A0E-4844-BF44-106F3ADDF157}.Debug|Win32.ActiveCfg = Debug|Any CPU {F1829F0B-1A0E-4844-BF44-106F3ADDF157}.Debug|Win32.Build.0 = Debug|Any CPU {F1829F0B-1A0E-4844-BF44-106F3ADDF157}.Debug|x64.ActiveCfg = Debug|Any CPU {F1829F0B-1A0E-4844-BF44-106F3ADDF157}.Debug|x64.Build.0 = Debug|Any CPU {F1829F0B-1A0E-4844-BF44-106F3ADDF157}.Instrumentation|Any CPU.ActiveCfg = Instrumentation|Any CPU {F1829F0B-1A0E-4844-BF44-106F3ADDF157}.Instrumentation|Any CPU.Build.0 = Instrumentation|Any CPU {F1829F0B-1A0E-4844-BF44-106F3ADDF157}.Instrumentation|ARM.ActiveCfg = Instrumentation|Any CPU {F1829F0B-1A0E-4844-BF44-106F3ADDF157}.Instrumentation|ARM.Build.0 = Instrumentation|Any CPU {F1829F0B-1A0E-4844-BF44-106F3ADDF157}.Instrumentation|Mixed Platforms.ActiveCfg = Instrumentation|Any CPU {F1829F0B-1A0E-4844-BF44-106F3ADDF157}.Instrumentation|Mixed Platforms.Build.0 = Instrumentation|Any CPU {F1829F0B-1A0E-4844-BF44-106F3ADDF157}.Instrumentation|Win32.ActiveCfg = Instrumentation|Any CPU {F1829F0B-1A0E-4844-BF44-106F3ADDF157}.Instrumentation|Win32.Build.0 = Instrumentation|Any CPU {F1829F0B-1A0E-4844-BF44-106F3ADDF157}.Instrumentation|x64.ActiveCfg = Instrumentation|Any CPU {F1829F0B-1A0E-4844-BF44-106F3ADDF157}.Instrumentation|x64.Build.0 = Instrumentation|Any CPU {F1829F0B-1A0E-4844-BF44-106F3ADDF157}.Release|Any CPU.ActiveCfg = Release|Any CPU {F1829F0B-1A0E-4844-BF44-106F3ADDF157}.Release|Any CPU.Build.0 = Release|Any CPU {F1829F0B-1A0E-4844-BF44-106F3ADDF157}.Release|ARM.ActiveCfg = Release|Any CPU {F1829F0B-1A0E-4844-BF44-106F3ADDF157}.Release|ARM.Build.0 = Release|Any CPU {F1829F0B-1A0E-4844-BF44-106F3ADDF157}.Release|Mixed Platforms.ActiveCfg = Release|Any CPU {F1829F0B-1A0E-4844-BF44-106F3ADDF157}.Release|Mixed Platforms.Build.0 = Release|Any CPU {F1829F0B-1A0E-4844-BF44-106F3ADDF157}.Release|Win32.ActiveCfg = Release|Any CPU {F1829F0B-1A0E-4844-BF44-106F3ADDF157}.Release|Win32.Build.0 = Release|Any CPU {F1829F0B-1A0E-4844-BF44-106F3ADDF157}.Release|x64.ActiveCfg = Release|Any CPU {F1829F0B-1A0E-4844-BF44-106F3ADDF157}.Release|x64.Build.0 = Release|Any CPU {C165CC46-A458-478B-9167-F073EED35EB2}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {C165CC46-A458-478B-9167-F073EED35EB2}.Debug|Any CPU.Build.0 = Debug|Any CPU {C165CC46-A458-478B-9167-F073EED35EB2}.Debug|ARM.ActiveCfg = Debug|Any CPU {C165CC46-A458-478B-9167-F073EED35EB2}.Debug|ARM.Build.0 = Debug|Any CPU {C165CC46-A458-478B-9167-F073EED35EB2}.Debug|Mixed Platforms.ActiveCfg = Debug|Any CPU {C165CC46-A458-478B-9167-F073EED35EB2}.Debug|Mixed Platforms.Build.0 = Debug|Any CPU {C165CC46-A458-478B-9167-F073EED35EB2}.Debug|Win32.ActiveCfg = Debug|Any CPU {C165CC46-A458-478B-9167-F073EED35EB2}.Debug|Win32.Build.0 = Debug|Any CPU {C165CC46-A458-478B-9167-F073EED35EB2}.Debug|x64.ActiveCfg = Debug|Any CPU {C165CC46-A458-478B-9167-F073EED35EB2}.Debug|x64.Build.0 = Debug|Any CPU {C165CC46-A458-478B-9167-F073EED35EB2}.Instrumentation|Any CPU.ActiveCfg = Instrumentation|Any CPU {C165CC46-A458-478B-9167-F073EED35EB2}.Instrumentation|Any CPU.Build.0 = Instrumentation|Any CPU {C165CC46-A458-478B-9167-F073EED35EB2}.Instrumentation|ARM.ActiveCfg = Instrumentation|Any CPU {C165CC46-A458-478B-9167-F073EED35EB2}.Instrumentation|ARM.Build.0 = Instrumentation|Any CPU {C165CC46-A458-478B-9167-F073EED35EB2}.Instrumentation|Mixed Platforms.ActiveCfg = Instrumentation|Any CPU {C165CC46-A458-478B-9167-F073EED35EB2}.Instrumentation|Mixed Platforms.Build.0 = Instrumentation|Any CPU {C165CC46-A458-478B-9167-F073EED35EB2}.Instrumentation|Win32.ActiveCfg = Instrumentation|Any CPU {C165CC46-A458-478B-9167-F073EED35EB2}.Instrumentation|Win32.Build.0 = Instrumentation|Any CPU {C165CC46-A458-478B-9167-F073EED35EB2}.Instrumentation|x64.ActiveCfg = Instrumentation|Any CPU {C165CC46-A458-478B-9167-F073EED35EB2}.Instrumentation|x64.Build.0 = Instrumentation|Any CPU {C165CC46-A458-478B-9167-F073EED35EB2}.Release|Any CPU.ActiveCfg = Release|Any CPU {C165CC46-A458-478B-9167-F073EED35EB2}.Release|Any CPU.Build.0 = Release|Any CPU {C165CC46-A458-478B-9167-F073EED35EB2}.Release|ARM.ActiveCfg = Release|Any CPU {C165CC46-A458-478B-9167-F073EED35EB2}.Release|ARM.Build.0 = Release|Any CPU {C165CC46-A458-478B-9167-F073EED35EB2}.Release|Mixed Platforms.ActiveCfg = Release|Any CPU {C165CC46-A458-478B-9167-F073EED35EB2}.Release|Mixed Platforms.Build.0 = Release|Any CPU {C165CC46-A458-478B-9167-F073EED35EB2}.Release|Win32.ActiveCfg = Release|Any CPU {C165CC46-A458-478B-9167-F073EED35EB2}.Release|Win32.Build.0 = Release|Any CPU {C165CC46-A458-478B-9167-F073EED35EB2}.Release|x64.ActiveCfg = Release|Any CPU {C165CC46-A458-478B-9167-F073EED35EB2}.Release|x64.Build.0 = Release|Any CPU {FA6F295F-6DEB-4095-86F2-DEC2D2D9A038}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {FA6F295F-6DEB-4095-86F2-DEC2D2D9A038}.Debug|Any CPU.Build.0 = Debug|Any CPU {FA6F295F-6DEB-4095-86F2-DEC2D2D9A038}.Debug|ARM.ActiveCfg = Debug|Any CPU {FA6F295F-6DEB-4095-86F2-DEC2D2D9A038}.Debug|ARM.Build.0 = Debug|Any CPU {FA6F295F-6DEB-4095-86F2-DEC2D2D9A038}.Debug|Mixed Platforms.ActiveCfg = Debug|Any CPU {FA6F295F-6DEB-4095-86F2-DEC2D2D9A038}.Debug|Mixed Platforms.Build.0 = Debug|Any CPU {FA6F295F-6DEB-4095-86F2-DEC2D2D9A038}.Debug|Win32.ActiveCfg = Debug|Any CPU {FA6F295F-6DEB-4095-86F2-DEC2D2D9A038}.Debug|Win32.Build.0 = Debug|Any CPU {FA6F295F-6DEB-4095-86F2-DEC2D2D9A038}.Debug|x64.ActiveCfg = Debug|Any CPU {FA6F295F-6DEB-4095-86F2-DEC2D2D9A038}.Debug|x64.Build.0 = Debug|Any CPU {FA6F295F-6DEB-4095-86F2-DEC2D2D9A038}.Instrumentation|Any CPU.ActiveCfg = Instrumentation|Any CPU {FA6F295F-6DEB-4095-86F2-DEC2D2D9A038}.Instrumentation|Any CPU.Build.0 = Instrumentation|Any CPU {FA6F295F-6DEB-4095-86F2-DEC2D2D9A038}.Instrumentation|ARM.ActiveCfg = Instrumentation|Any CPU {FA6F295F-6DEB-4095-86F2-DEC2D2D9A038}.Instrumentation|ARM.Build.0 = Instrumentation|Any CPU {FA6F295F-6DEB-4095-86F2-DEC2D2D9A038}.Instrumentation|Mixed Platforms.ActiveCfg = Instrumentation|Any CPU {FA6F295F-6DEB-4095-86F2-DEC2D2D9A038}.Instrumentation|Mixed Platforms.Build.0 = Instrumentation|Any CPU {FA6F295F-6DEB-4095-86F2-DEC2D2D9A038}.Instrumentation|Win32.ActiveCfg = Instrumentation|Any CPU {FA6F295F-6DEB-4095-86F2-DEC2D2D9A038}.Instrumentation|Win32.Build.0 = Instrumentation|Any CPU {FA6F295F-6DEB-4095-86F2-DEC2D2D9A038}.Instrumentation|x64.ActiveCfg = Instrumentation|Any CPU {FA6F295F-6DEB-4095-86F2-DEC2D2D9A038}.Instrumentation|x64.Build.0 = Instrumentation|Any CPU {FA6F295F-6DEB-4095-86F2-DEC2D2D9A038}.Release|Any CPU.ActiveCfg = Release|Any CPU {FA6F295F-6DEB-4095-86F2-DEC2D2D9A038}.Release|Any CPU.Build.0 = Release|Any CPU {FA6F295F-6DEB-4095-86F2-DEC2D2D9A038}.Release|ARM.ActiveCfg = Release|Any CPU {FA6F295F-6DEB-4095-86F2-DEC2D2D9A038}.Release|ARM.Build.0 = Release|Any CPU {FA6F295F-6DEB-4095-86F2-DEC2D2D9A038}.Release|Mixed Platforms.ActiveCfg = Release|Any CPU {FA6F295F-6DEB-4095-86F2-DEC2D2D9A038}.Release|Mixed Platforms.Build.0 = Release|Any CPU {FA6F295F-6DEB-4095-86F2-DEC2D2D9A038}.Release|Win32.ActiveCfg = Release|Any CPU {FA6F295F-6DEB-4095-86F2-DEC2D2D9A038}.Release|Win32.Build.0 = Release|Any CPU {FA6F295F-6DEB-4095-86F2-DEC2D2D9A038}.Release|x64.ActiveCfg = Release|Any CPU {FA6F295F-6DEB-4095-86F2-DEC2D2D9A038}.Release|x64.Build.0 = Release|Any CPU {B7606EF5-A5EC-4A97-AB4A-35D00EFA2925}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {B7606EF5-A5EC-4A97-AB4A-35D00EFA2925}.Debug|Any CPU.Build.0 = Debug|Any CPU {B7606EF5-A5EC-4A97-AB4A-35D00EFA2925}.Debug|ARM.ActiveCfg = Debug|Any CPU {B7606EF5-A5EC-4A97-AB4A-35D00EFA2925}.Debug|ARM.Build.0 = Debug|Any CPU {B7606EF5-A5EC-4A97-AB4A-35D00EFA2925}.Debug|Mixed Platforms.ActiveCfg = Debug|Any CPU {B7606EF5-A5EC-4A97-AB4A-35D00EFA2925}.Debug|Mixed Platforms.Build.0 = Debug|Any CPU {B7606EF5-A5EC-4A97-AB4A-35D00EFA2925}.Debug|Win32.ActiveCfg = Debug|Any CPU {B7606EF5-A5EC-4A97-AB4A-35D00EFA2925}.Debug|Win32.Build.0 = Debug|Any CPU {B7606EF5-A5EC-4A97-AB4A-35D00EFA2925}.Debug|x64.ActiveCfg = Debug|Any CPU {B7606EF5-A5EC-4A97-AB4A-35D00EFA2925}.Debug|x64.Build.0 = Debug|Any CPU {B7606EF5-A5EC-4A97-AB4A-35D00EFA2925}.Instrumentation|Any CPU.ActiveCfg = Instrumentation|Any CPU {B7606EF5-A5EC-4A97-AB4A-35D00EFA2925}.Instrumentation|Any CPU.Build.0 = Instrumentation|Any CPU {B7606EF5-A5EC-4A97-AB4A-35D00EFA2925}.Instrumentation|ARM.ActiveCfg = Instrumentation|Any CPU {B7606EF5-A5EC-4A97-AB4A-35D00EFA2925}.Instrumentation|ARM.Build.0 = Instrumentation|Any CPU {B7606EF5-A5EC-4A97-AB4A-35D00EFA2925}.Instrumentation|Mixed Platforms.ActiveCfg = Instrumentation|Any CPU {B7606EF5-A5EC-4A97-AB4A-35D00EFA2925}.Instrumentation|Mixed Platforms.Build.0 = Instrumentation|Any CPU {B7606EF5-A5EC-4A97-AB4A-35D00EFA2925}.Instrumentation|Win32.ActiveCfg = Instrumentation|Any CPU {B7606EF5-A5EC-4A97-AB4A-35D00EFA2925}.Instrumentation|Win32.Build.0 = Instrumentation|Any CPU {B7606EF5-A5EC-4A97-AB4A-35D00EFA2925}.Instrumentation|x64.ActiveCfg = Instrumentation|Any CPU {B7606EF5-A5EC-4A97-AB4A-35D00EFA2925}.Instrumentation|x64.Build.0 = Instrumentation|Any CPU {B7606EF5-A5EC-4A97-AB4A-35D00EFA2925}.Release|Any CPU.ActiveCfg = Release|Any CPU {B7606EF5-A5EC-4A97-AB4A-35D00EFA2925}.Release|Any CPU.Build.0 = Release|Any CPU {B7606EF5-A5EC-4A97-AB4A-35D00EFA2925}.Release|ARM.ActiveCfg = Release|Any CPU {B7606EF5-A5EC-4A97-AB4A-35D00EFA2925}.Release|ARM.Build.0 = Release|Any CPU {B7606EF5-A5EC-4A97-AB4A-35D00EFA2925}.Release|Mixed Platforms.ActiveCfg = Release|Any CPU {B7606EF5-A5EC-4A97-AB4A-35D00EFA2925}.Release|Mixed Platforms.Build.0 = Release|Any CPU {B7606EF5-A5EC-4A97-AB4A-35D00EFA2925}.Release|Win32.ActiveCfg = Release|Any CPU {B7606EF5-A5EC-4A97-AB4A-35D00EFA2925}.Release|Win32.Build.0 = Release|Any CPU {B7606EF5-A5EC-4A97-AB4A-35D00EFA2925}.Release|x64.ActiveCfg = Release|Any CPU {B7606EF5-A5EC-4A97-AB4A-35D00EFA2925}.Release|x64.Build.0 = Release|Any CPU {242A3A91-4622-4463-8A89-608908C7C540}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {242A3A91-4622-4463-8A89-608908C7C540}.Debug|Any CPU.Build.0 = Debug|Any CPU {242A3A91-4622-4463-8A89-608908C7C540}.Debug|ARM.ActiveCfg = Debug|Any CPU {242A3A91-4622-4463-8A89-608908C7C540}.Debug|ARM.Build.0 = Debug|Any CPU {242A3A91-4622-4463-8A89-608908C7C540}.Debug|Mixed Platforms.ActiveCfg = Debug|Any CPU {242A3A91-4622-4463-8A89-608908C7C540}.Debug|Mixed Platforms.Build.0 = Debug|Any CPU {242A3A91-4622-4463-8A89-608908C7C540}.Debug|Win32.ActiveCfg = Debug|Any CPU {242A3A91-4622-4463-8A89-608908C7C540}.Debug|Win32.Build.0 = Debug|Any CPU {242A3A91-4622-4463-8A89-608908C7C540}.Debug|x64.ActiveCfg = Debug|Any CPU {242A3A91-4622-4463-8A89-608908C7C540}.Debug|x64.Build.0 = Debug|Any CPU {242A3A91-4622-4463-8A89-608908C7C540}.Instrumentation|Any CPU.ActiveCfg = Instrumentation|Any CPU {242A3A91-4622-4463-8A89-608908C7C540}.Instrumentation|Any CPU.Build.0 = Instrumentation|Any CPU {242A3A91-4622-4463-8A89-608908C7C540}.Instrumentation|ARM.ActiveCfg = Instrumentation|Any CPU {242A3A91-4622-4463-8A89-608908C7C540}.Instrumentation|ARM.Build.0 = Instrumentation|Any CPU {242A3A91-4622-4463-8A89-608908C7C540}.Instrumentation|Mixed Platforms.ActiveCfg = Instrumentation|Any CPU {242A3A91-4622-4463-8A89-608908C7C540}.Instrumentation|Mixed Platforms.Build.0 = Instrumentation|Any CPU {242A3A91-4622-4463-8A89-608908C7C540}.Instrumentation|Win32.ActiveCfg = Instrumentation|Any CPU {242A3A91-4622-4463-8A89-608908C7C540}.Instrumentation|Win32.Build.0 = Instrumentation|Any CPU {242A3A91-4622-4463-8A89-608908C7C540}.Instrumentation|x64.ActiveCfg = Instrumentation|Any CPU {242A3A91-4622-4463-8A89-608908C7C540}.Instrumentation|x64.Build.0 = Instrumentation|Any CPU {242A3A91-4622-4463-8A89-608908C7C540}.Release|Any CPU.ActiveCfg = Release|Any CPU {242A3A91-4622-4463-8A89-608908C7C540}.Release|Any CPU.Build.0 = Release|Any CPU {242A3A91-4622-4463-8A89-608908C7C540}.Release|ARM.ActiveCfg = Release|Any CPU {242A3A91-4622-4463-8A89-608908C7C540}.Release|ARM.Build.0 = Release|Any CPU {242A3A91-4622-4463-8A89-608908C7C540}.Release|Mixed Platforms.ActiveCfg = Release|Any CPU {242A3A91-4622-4463-8A89-608908C7C540}.Release|Mixed Platforms.Build.0 = Release|Any CPU {242A3A91-4622-4463-8A89-608908C7C540}.Release|Win32.ActiveCfg = Release|Any CPU {242A3A91-4622-4463-8A89-608908C7C540}.Release|Win32.Build.0 = Release|Any CPU {242A3A91-4622-4463-8A89-608908C7C540}.Release|x64.ActiveCfg = Release|Any CPU {242A3A91-4622-4463-8A89-608908C7C540}.Release|x64.Build.0 = Release|Any CPU {30BA8CEE-868B-4C53-85C5-DFF6FA39D035}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {30BA8CEE-868B-4C53-85C5-DFF6FA39D035}.Debug|Any CPU.Build.0 = Debug|Any CPU {30BA8CEE-868B-4C53-85C5-DFF6FA39D035}.Debug|ARM.ActiveCfg = Debug|Any CPU {30BA8CEE-868B-4C53-85C5-DFF6FA39D035}.Debug|ARM.Build.0 = Debug|Any CPU {30BA8CEE-868B-4C53-85C5-DFF6FA39D035}.Debug|Mixed Platforms.ActiveCfg = Debug|Any CPU {30BA8CEE-868B-4C53-85C5-DFF6FA39D035}.Debug|Mixed Platforms.Build.0 = Debug|Any CPU {30BA8CEE-868B-4C53-85C5-DFF6FA39D035}.Debug|Win32.ActiveCfg = Debug|Any CPU {30BA8CEE-868B-4C53-85C5-DFF6FA39D035}.Debug|Win32.Build.0 = Debug|Any CPU {30BA8CEE-868B-4C53-85C5-DFF6FA39D035}.Debug|x64.ActiveCfg = Debug|Any CPU {30BA8CEE-868B-4C53-85C5-DFF6FA39D035}.Debug|x64.Build.0 = Debug|Any CPU {30BA8CEE-868B-4C53-85C5-DFF6FA39D035}.Instrumentation|Any CPU.ActiveCfg = Instrumentation|Any CPU {30BA8CEE-868B-4C53-85C5-DFF6FA39D035}.Instrumentation|Any CPU.Build.0 = Instrumentation|Any CPU {30BA8CEE-868B-4C53-85C5-DFF6FA39D035}.Instrumentation|ARM.ActiveCfg = Instrumentation|Any CPU {30BA8CEE-868B-4C53-85C5-DFF6FA39D035}.Instrumentation|ARM.Build.0 = Instrumentation|Any CPU {30BA8CEE-868B-4C53-85C5-DFF6FA39D035}.Instrumentation|Mixed Platforms.ActiveCfg = Instrumentation|Any CPU {30BA8CEE-868B-4C53-85C5-DFF6FA39D035}.Instrumentation|Mixed Platforms.Build.0 = Instrumentation|Any CPU {30BA8CEE-868B-4C53-85C5-DFF6FA39D035}.Instrumentation|Win32.ActiveCfg = Instrumentation|Any CPU {30BA8CEE-868B-4C53-85C5-DFF6FA39D035}.Instrumentation|Win32.Build.0 = Instrumentation|Any CPU {30BA8CEE-868B-4C53-85C5-DFF6FA39D035}.Instrumentation|x64.ActiveCfg = Instrumentation|Any CPU {30BA8CEE-868B-4C53-85C5-DFF6FA39D035}.Instrumentation|x64.Build.0 = Instrumentation|Any CPU {30BA8CEE-868B-4C53-85C5-DFF6FA39D035}.Release|Any CPU.ActiveCfg = Release|Any CPU {30BA8CEE-868B-4C53-85C5-DFF6FA39D035}.Release|Any CPU.Build.0 = Release|Any CPU {30BA8CEE-868B-4C53-85C5-DFF6FA39D035}.Release|ARM.ActiveCfg = Release|Any CPU {30BA8CEE-868B-4C53-85C5-DFF6FA39D035}.Release|ARM.Build.0 = Release|Any CPU {30BA8CEE-868B-4C53-85C5-DFF6FA39D035}.Release|Mixed Platforms.ActiveCfg = Release|Any CPU {30BA8CEE-868B-4C53-85C5-DFF6FA39D035}.Release|Mixed Platforms.Build.0 = Release|Any CPU {30BA8CEE-868B-4C53-85C5-DFF6FA39D035}.Release|Win32.ActiveCfg = Release|Any CPU {30BA8CEE-868B-4C53-85C5-DFF6FA39D035}.Release|Win32.Build.0 = Release|Any CPU {30BA8CEE-868B-4C53-85C5-DFF6FA39D035}.Release|x64.ActiveCfg = Release|Any CPU {30BA8CEE-868B-4C53-85C5-DFF6FA39D035}.Release|x64.Build.0 = Release|Any CPU {22248085-CA53-485F-9A71-968A7AC42B04}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {22248085-CA53-485F-9A71-968A7AC42B04}.Debug|Any CPU.Build.0 = Debug|Any CPU {22248085-CA53-485F-9A71-968A7AC42B04}.Debug|ARM.ActiveCfg = Debug|Any CPU {22248085-CA53-485F-9A71-968A7AC42B04}.Debug|ARM.Build.0 = Debug|Any CPU {22248085-CA53-485F-9A71-968A7AC42B04}.Debug|Mixed Platforms.ActiveCfg = Debug|Any CPU {22248085-CA53-485F-9A71-968A7AC42B04}.Debug|Mixed Platforms.Build.0 = Debug|Any CPU {22248085-CA53-485F-9A71-968A7AC42B04}.Debug|Win32.ActiveCfg = Debug|Any CPU {22248085-CA53-485F-9A71-968A7AC42B04}.Debug|Win32.Build.0 = Debug|Any CPU {22248085-CA53-485F-9A71-968A7AC42B04}.Debug|x64.ActiveCfg = Debug|Any CPU {22248085-CA53-485F-9A71-968A7AC42B04}.Debug|x64.Build.0 = Debug|Any CPU {22248085-CA53-485F-9A71-968A7AC42B04}.Instrumentation|Any CPU.ActiveCfg = Instrumentation|Any CPU {22248085-CA53-485F-9A71-968A7AC42B04}.Instrumentation|Any CPU.Build.0 = Instrumentation|Any CPU {22248085-CA53-485F-9A71-968A7AC42B04}.Instrumentation|ARM.ActiveCfg = Instrumentation|Any CPU {22248085-CA53-485F-9A71-968A7AC42B04}.Instrumentation|ARM.Build.0 = Instrumentation|Any CPU {22248085-CA53-485F-9A71-968A7AC42B04}.Instrumentation|Mixed Platforms.ActiveCfg = Instrumentation|Any CPU {22248085-CA53-485F-9A71-968A7AC42B04}.Instrumentation|Mixed Platforms.Build.0 = Instrumentation|Any CPU {22248085-CA53-485F-9A71-968A7AC42B04}.Instrumentation|Win32.ActiveCfg = Instrumentation|Any CPU {22248085-CA53-485F-9A71-968A7AC42B04}.Instrumentation|Win32.Build.0 = Instrumentation|Any CPU {22248085-CA53-485F-9A71-968A7AC42B04}.Instrumentation|x64.ActiveCfg = Instrumentation|Any CPU {22248085-CA53-485F-9A71-968A7AC42B04}.Instrumentation|x64.Build.0 = Instrumentation|Any CPU {22248085-CA53-485F-9A71-968A7AC42B04}.Release|Any CPU.ActiveCfg = Release|Any CPU {22248085-CA53-485F-9A71-968A7AC42B04}.Release|Any CPU.Build.0 = Release|Any CPU {22248085-CA53-485F-9A71-968A7AC42B04}.Release|ARM.ActiveCfg = Release|Any CPU {22248085-CA53-485F-9A71-968A7AC42B04}.Release|ARM.Build.0 = Release|Any CPU {22248085-CA53-485F-9A71-968A7AC42B04}.Release|Mixed Platforms.ActiveCfg = Release|Any CPU {22248085-CA53-485F-9A71-968A7AC42B04}.Release|Mixed Platforms.Build.0 = Release|Any CPU {22248085-CA53-485F-9A71-968A7AC42B04}.Release|Win32.ActiveCfg = Release|Any CPU {22248085-CA53-485F-9A71-968A7AC42B04}.Release|Win32.Build.0 = Release|Any CPU {22248085-CA53-485F-9A71-968A7AC42B04}.Release|x64.ActiveCfg = Release|Any CPU {22248085-CA53-485F-9A71-968A7AC42B04}.Release|x64.Build.0 = Release|Any CPU {64874F12-60A0-4B5B-ACC6-616C530F430E}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {64874F12-60A0-4B5B-ACC6-616C530F430E}.Debug|Any CPU.Build.0 = Debug|Any CPU {64874F12-60A0-4B5B-ACC6-616C530F430E}.Debug|ARM.ActiveCfg = Debug|Any CPU {64874F12-60A0-4B5B-ACC6-616C530F430E}.Debug|ARM.Build.0 = Debug|Any CPU {64874F12-60A0-4B5B-ACC6-616C530F430E}.Debug|Mixed Platforms.ActiveCfg = Debug|Any CPU {64874F12-60A0-4B5B-ACC6-616C530F430E}.Debug|Mixed Platforms.Build.0 = Debug|Any CPU {64874F12-60A0-4B5B-ACC6-616C530F430E}.Debug|Win32.ActiveCfg = Debug|Any CPU {64874F12-60A0-4B5B-ACC6-616C530F430E}.Debug|Win32.Build.0 = Debug|Any CPU {64874F12-60A0-4B5B-ACC6-616C530F430E}.Debug|x64.ActiveCfg = Debug|Any CPU {64874F12-60A0-4B5B-ACC6-616C530F430E}.Debug|x64.Build.0 = Debug|Any CPU {64874F12-60A0-4B5B-ACC6-616C530F430E}.Instrumentation|Any CPU.ActiveCfg = Instrumentation|Any CPU {64874F12-60A0-4B5B-ACC6-616C530F430E}.Instrumentation|Any CPU.Build.0 = Instrumentation|Any CPU {64874F12-60A0-4B5B-ACC6-616C530F430E}.Instrumentation|ARM.ActiveCfg = Instrumentation|Any CPU {64874F12-60A0-4B5B-ACC6-616C530F430E}.Instrumentation|ARM.Build.0 = Instrumentation|Any CPU {64874F12-60A0-4B5B-ACC6-616C530F430E}.Instrumentation|Mixed Platforms.ActiveCfg = Instrumentation|Any CPU {64874F12-60A0-4B5B-ACC6-616C530F430E}.Instrumentation|Mixed Platforms.Build.0 = Instrumentation|Any CPU {64874F12-60A0-4B5B-ACC6-616C530F430E}.Instrumentation|Win32.ActiveCfg = Instrumentation|Any CPU {64874F12-60A0-4B5B-ACC6-616C530F430E}.Instrumentation|Win32.Build.0 = Instrumentation|Any CPU {64874F12-60A0-4B5B-ACC6-616C530F430E}.Instrumentation|x64.ActiveCfg = Instrumentation|Any CPU {64874F12-60A0-4B5B-ACC6-616C530F430E}.Instrumentation|x64.Build.0 = Instrumentation|Any CPU {64874F12-60A0-4B5B-ACC6-616C530F430E}.Release|Any CPU.ActiveCfg = Release|Any CPU {64874F12-60A0-4B5B-ACC6-616C530F430E}.Release|Any CPU.Build.0 = Release|Any CPU {64874F12-60A0-4B5B-ACC6-616C530F430E}.Release|ARM.ActiveCfg = Release|Any CPU {64874F12-60A0-4B5B-ACC6-616C530F430E}.Release|ARM.Build.0 = Release|Any CPU {64874F12-60A0-4B5B-ACC6-616C530F430E}.Release|Mixed Platforms.ActiveCfg = Release|Any CPU {64874F12-60A0-4B5B-ACC6-616C530F430E}.Release|Mixed Platforms.Build.0 = Release|Any CPU {64874F12-60A0-4B5B-ACC6-616C530F430E}.Release|Win32.ActiveCfg = Release|Any CPU {64874F12-60A0-4B5B-ACC6-616C530F430E}.Release|Win32.Build.0 = Release|Any CPU {64874F12-60A0-4B5B-ACC6-616C530F430E}.Release|x64.ActiveCfg = Release|Any CPU {64874F12-60A0-4B5B-ACC6-616C530F430E}.Release|x64.Build.0 = Release|Any CPU {77D71AF4-11C3-409B-A211-51FA19E5C1AA}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {77D71AF4-11C3-409B-A211-51FA19E5C1AA}.Debug|Any CPU.Build.0 = Debug|Any CPU {77D71AF4-11C3-409B-A211-51FA19E5C1AA}.Debug|ARM.ActiveCfg = Debug|Any CPU {77D71AF4-11C3-409B-A211-51FA19E5C1AA}.Debug|ARM.Build.0 = Debug|Any CPU {77D71AF4-11C3-409B-A211-51FA19E5C1AA}.Debug|Mixed Platforms.ActiveCfg = Debug|Any CPU {77D71AF4-11C3-409B-A211-51FA19E5C1AA}.Debug|Mixed Platforms.Build.0 = Debug|Any CPU {77D71AF4-11C3-409B-A211-51FA19E5C1AA}.Debug|Win32.ActiveCfg = Debug|Any CPU {77D71AF4-11C3-409B-A211-51FA19E5C1AA}.Debug|Win32.Build.0 = Debug|Any CPU {77D71AF4-11C3-409B-A211-51FA19E5C1AA}.Debug|x64.ActiveCfg = Debug|Any CPU {77D71AF4-11C3-409B-A211-51FA19E5C1AA}.Debug|x64.Build.0 = Debug|Any CPU {77D71AF4-11C3-409B-A211-51FA19E5C1AA}.Instrumentation|Any CPU.ActiveCfg = Release|Any CPU {77D71AF4-11C3-409B-A211-51FA19E5C1AA}.Instrumentation|Any CPU.Build.0 = Release|Any CPU {77D71AF4-11C3-409B-A211-51FA19E5C1AA}.Instrumentation|ARM.ActiveCfg = Release|Any CPU {77D71AF4-11C3-409B-A211-51FA19E5C1AA}.Instrumentation|ARM.Build.0 = Release|Any CPU {77D71AF4-11C3-409B-A211-51FA19E5C1AA}.Instrumentation|Mixed Platforms.ActiveCfg = Release|Any CPU {77D71AF4-11C3-409B-A211-51FA19E5C1AA}.Instrumentation|Mixed Platforms.Build.0 = Release|Any CPU {77D71AF4-11C3-409B-A211-51FA19E5C1AA}.Instrumentation|Win32.ActiveCfg = Release|Any CPU {77D71AF4-11C3-409B-A211-51FA19E5C1AA}.Instrumentation|Win32.Build.0 = Release|Any CPU {77D71AF4-11C3-409B-A211-51FA19E5C1AA}.Instrumentation|x64.ActiveCfg = Release|Any CPU {77D71AF4-11C3-409B-A211-51FA19E5C1AA}.Instrumentation|x64.Build.0 = Release|Any CPU {77D71AF4-11C3-409B-A211-51FA19E5C1AA}.Release|Any CPU.ActiveCfg = Release|Any CPU {77D71AF4-11C3-409B-A211-51FA19E5C1AA}.Release|Any CPU.Build.0 = Release|Any CPU {77D71AF4-11C3-409B-A211-51FA19E5C1AA}.Release|ARM.ActiveCfg = Release|Any CPU {77D71AF4-11C3-409B-A211-51FA19E5C1AA}.Release|ARM.Build.0 = Release|Any CPU {77D71AF4-11C3-409B-A211-51FA19E5C1AA}.Release|Mixed Platforms.ActiveCfg = Release|Any CPU {77D71AF4-11C3-409B-A211-51FA19E5C1AA}.Release|Mixed Platforms.Build.0 = Release|Any CPU {77D71AF4-11C3-409B-A211-51FA19E5C1AA}.Release|Win32.ActiveCfg = Release|Any CPU {77D71AF4-11C3-409B-A211-51FA19E5C1AA}.Release|Win32.Build.0 = Release|Any CPU {77D71AF4-11C3-409B-A211-51FA19E5C1AA}.Release|x64.ActiveCfg = Release|Any CPU {77D71AF4-11C3-409B-A211-51FA19E5C1AA}.Release|x64.Build.0 = Release|Any CPU {6C77A7DE-D464-430F-96A9-A64768763B5F}.Debug|Any CPU.ActiveCfg = Debug|x64 {6C77A7DE-D464-430F-96A9-A64768763B5F}.Debug|Any CPU.Build.0 = Debug|x64 {6C77A7DE-D464-430F-96A9-A64768763B5F}.Debug|ARM.ActiveCfg = Debug|x64 {6C77A7DE-D464-430F-96A9-A64768763B5F}.Debug|ARM.Build.0 = Debug|x64 {6C77A7DE-D464-430F-96A9-A64768763B5F}.Debug|Mixed Platforms.ActiveCfg = Debug|x64 {6C77A7DE-D464-430F-96A9-A64768763B5F}.Debug|Mixed Platforms.Build.0 = Debug|x64 {6C77A7DE-D464-430F-96A9-A64768763B5F}.Debug|Win32.ActiveCfg = Debug|Win32 {6C77A7DE-D464-430F-96A9-A64768763B5F}.Debug|Win32.Build.0 = Debug|Win32 {6C77A7DE-D464-430F-96A9-A64768763B5F}.Debug|x64.ActiveCfg = Debug|x64 {6C77A7DE-D464-430F-96A9-A64768763B5F}.Debug|x64.Build.0 = Debug|x64 {6C77A7DE-D464-430F-96A9-A64768763B5F}.Instrumentation|Any CPU.ActiveCfg = Release|x64 {6C77A7DE-D464-430F-96A9-A64768763B5F}.Instrumentation|Any CPU.Build.0 = Release|x64 {6C77A7DE-D464-430F-96A9-A64768763B5F}.Instrumentation|ARM.ActiveCfg = Release|x64 {6C77A7DE-D464-430F-96A9-A64768763B5F}.Instrumentation|ARM.Build.0 = Release|x64 {6C77A7DE-D464-430F-96A9-A64768763B5F}.Instrumentation|Mixed Platforms.ActiveCfg = Release|x64 {6C77A7DE-D464-430F-96A9-A64768763B5F}.Instrumentation|Mixed Platforms.Build.0 = Release|x64 {6C77A7DE-D464-430F-96A9-A64768763B5F}.Instrumentation|Win32.ActiveCfg = Release|Win32 {6C77A7DE-D464-430F-96A9-A64768763B5F}.Instrumentation|Win32.Build.0 = Release|Win32 {6C77A7DE-D464-430F-96A9-A64768763B5F}.Instrumentation|x64.ActiveCfg = Release|x64 {6C77A7DE-D464-430F-96A9-A64768763B5F}.Instrumentation|x64.Build.0 = Release|x64 {6C77A7DE-D464-430F-96A9-A64768763B5F}.Release|Any CPU.ActiveCfg = Release|x64 {6C77A7DE-D464-430F-96A9-A64768763B5F}.Release|Any CPU.Build.0 = Release|x64 {6C77A7DE-D464-430F-96A9-A64768763B5F}.Release|ARM.ActiveCfg = Release|x64 {6C77A7DE-D464-430F-96A9-A64768763B5F}.Release|ARM.Build.0 = Release|x64 {6C77A7DE-D464-430F-96A9-A64768763B5F}.Release|Mixed Platforms.ActiveCfg = Release|x64 {6C77A7DE-D464-430F-96A9-A64768763B5F}.Release|Mixed Platforms.Build.0 = Release|x64 {6C77A7DE-D464-430F-96A9-A64768763B5F}.Release|Win32.ActiveCfg = Release|Win32 {6C77A7DE-D464-430F-96A9-A64768763B5F}.Release|Win32.Build.0 = Release|Win32 {6C77A7DE-D464-430F-96A9-A64768763B5F}.Release|x64.ActiveCfg = Release|x64 {6C77A7DE-D464-430F-96A9-A64768763B5F}.Release|x64.Build.0 = Release|x64 {0162C8CE-6641-4922-8664-F8A44356FBF7}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {0162C8CE-6641-4922-8664-F8A44356FBF7}.Debug|Any CPU.Build.0 = Debug|Any CPU {0162C8CE-6641-4922-8664-F8A44356FBF7}.Debug|ARM.ActiveCfg = Debug|Any CPU {0162C8CE-6641-4922-8664-F8A44356FBF7}.Debug|ARM.Build.0 = Debug|Any CPU {0162C8CE-6641-4922-8664-F8A44356FBF7}.Debug|Mixed Platforms.ActiveCfg = Debug|Any CPU {0162C8CE-6641-4922-8664-F8A44356FBF7}.Debug|Mixed Platforms.Build.0 = Debug|Any CPU {0162C8CE-6641-4922-8664-F8A44356FBF7}.Debug|Win32.ActiveCfg = Debug|Win32 {0162C8CE-6641-4922-8664-F8A44356FBF7}.Debug|Win32.Build.0 = Debug|Win32 {0162C8CE-6641-4922-8664-F8A44356FBF7}.Debug|x64.ActiveCfg = Debug|Any CPU {0162C8CE-6641-4922-8664-F8A44356FBF7}.Debug|x64.Build.0 = Debug|Any CPU {0162C8CE-6641-4922-8664-F8A44356FBF7}.Instrumentation|Any CPU.ActiveCfg = Release|Win32 {0162C8CE-6641-4922-8664-F8A44356FBF7}.Instrumentation|Any CPU.Build.0 = Release|Win32 {0162C8CE-6641-4922-8664-F8A44356FBF7}.Instrumentation|ARM.ActiveCfg = Release|x64 {0162C8CE-6641-4922-8664-F8A44356FBF7}.Instrumentation|ARM.Build.0 = Release|x64 {0162C8CE-6641-4922-8664-F8A44356FBF7}.Instrumentation|Mixed Platforms.ActiveCfg = Release|x64 {0162C8CE-6641-4922-8664-F8A44356FBF7}.Instrumentation|Mixed Platforms.Build.0 = Release|x64 {0162C8CE-6641-4922-8664-F8A44356FBF7}.Instrumentation|Win32.ActiveCfg = Release|Win32 {0162C8CE-6641-4922-8664-F8A44356FBF7}.Instrumentation|Win32.Build.0 = Release|Win32 {0162C8CE-6641-4922-8664-F8A44356FBF7}.Instrumentation|x64.ActiveCfg = Release|x64 {0162C8CE-6641-4922-8664-F8A44356FBF7}.Instrumentation|x64.Build.0 = Release|x64 {0162C8CE-6641-4922-8664-F8A44356FBF7}.Release|Any CPU.ActiveCfg = Release|x64 {0162C8CE-6641-4922-8664-F8A44356FBF7}.Release|Any CPU.Build.0 = Release|x64 {0162C8CE-6641-4922-8664-F8A44356FBF7}.Release|ARM.ActiveCfg = Release|x64 {0162C8CE-6641-4922-8664-F8A44356FBF7}.Release|ARM.Build.0 = Release|x64 {0162C8CE-6641-4922-8664-F8A44356FBF7}.Release|Mixed Platforms.ActiveCfg = Release|Any CPU {0162C8CE-6641-4922-8664-F8A44356FBF7}.Release|Mixed Platforms.Build.0 = Release|Any CPU {0162C8CE-6641-4922-8664-F8A44356FBF7}.Release|Win32.ActiveCfg = Release|Win32 {0162C8CE-6641-4922-8664-F8A44356FBF7}.Release|Win32.Build.0 = Release|Win32 {0162C8CE-6641-4922-8664-F8A44356FBF7}.Release|x64.ActiveCfg = Release|x64 {0162C8CE-6641-4922-8664-F8A44356FBF7}.Release|x64.Build.0 = Release|x64 {D7F2BC4E-1406-47AA-90E1-07BC4CE9410F}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {D7F2BC4E-1406-47AA-90E1-07BC4CE9410F}.Debug|Any CPU.Build.0 = Debug|Any CPU {D7F2BC4E-1406-47AA-90E1-07BC4CE9410F}.Debug|ARM.ActiveCfg = Debug|Any CPU {D7F2BC4E-1406-47AA-90E1-07BC4CE9410F}.Debug|ARM.Build.0 = Debug|Any CPU {D7F2BC4E-1406-47AA-90E1-07BC4CE9410F}.Debug|Mixed Platforms.ActiveCfg = Debug|Any CPU {D7F2BC4E-1406-47AA-90E1-07BC4CE9410F}.Debug|Mixed Platforms.Build.0 = Debug|Any CPU {D7F2BC4E-1406-47AA-90E1-07BC4CE9410F}.Debug|Win32.ActiveCfg = Debug|Any CPU {D7F2BC4E-1406-47AA-90E1-07BC4CE9410F}.Debug|Win32.Build.0 = Debug|Any CPU {D7F2BC4E-1406-47AA-90E1-07BC4CE9410F}.Debug|x64.ActiveCfg = Debug|Any CPU {D7F2BC4E-1406-47AA-90E1-07BC4CE9410F}.Debug|x64.Build.0 = Debug|Any CPU {D7F2BC4E-1406-47AA-90E1-07BC4CE9410F}.Instrumentation|Any CPU.ActiveCfg = Release|Any CPU {D7F2BC4E-1406-47AA-90E1-07BC4CE9410F}.Instrumentation|Any CPU.Build.0 = Release|Any CPU {D7F2BC4E-1406-47AA-90E1-07BC4CE9410F}.Instrumentation|ARM.ActiveCfg = Release|Any CPU {D7F2BC4E-1406-47AA-90E1-07BC4CE9410F}.Instrumentation|ARM.Build.0 = Release|Any CPU {D7F2BC4E-1406-47AA-90E1-07BC4CE9410F}.Instrumentation|Mixed Platforms.ActiveCfg = Release|Any CPU {D7F2BC4E-1406-47AA-90E1-07BC4CE9410F}.Instrumentation|Mixed Platforms.Build.0 = Release|Any CPU {D7F2BC4E-1406-47AA-90E1-07BC4CE9410F}.Instrumentation|Win32.ActiveCfg = Release|Any CPU {D7F2BC4E-1406-47AA-90E1-07BC4CE9410F}.Instrumentation|Win32.Build.0 = Release|Any CPU {D7F2BC4E-1406-47AA-90E1-07BC4CE9410F}.Instrumentation|x64.ActiveCfg = Release|Any CPU {D7F2BC4E-1406-47AA-90E1-07BC4CE9410F}.Instrumentation|x64.Build.0 = Release|Any CPU {D7F2BC4E-1406-47AA-90E1-07BC4CE9410F}.Release|Any CPU.ActiveCfg = Release|Any CPU {D7F2BC4E-1406-47AA-90E1-07BC4CE9410F}.Release|Any CPU.Build.0 = Release|Any CPU {D7F2BC4E-1406-47AA-90E1-07BC4CE9410F}.Release|ARM.ActiveCfg = Release|Any CPU {D7F2BC4E-1406-47AA-90E1-07BC4CE9410F}.Release|ARM.Build.0 = Release|Any CPU {D7F2BC4E-1406-47AA-90E1-07BC4CE9410F}.Release|Mixed Platforms.ActiveCfg = Release|Any CPU {D7F2BC4E-1406-47AA-90E1-07BC4CE9410F}.Release|Mixed Platforms.Build.0 = Release|Any CPU {D7F2BC4E-1406-47AA-90E1-07BC4CE9410F}.Release|Win32.ActiveCfg = Release|Any CPU {D7F2BC4E-1406-47AA-90E1-07BC4CE9410F}.Release|Win32.Build.0 = Release|Any CPU {D7F2BC4E-1406-47AA-90E1-07BC4CE9410F}.Release|x64.ActiveCfg = Release|Any CPU {D7F2BC4E-1406-47AA-90E1-07BC4CE9410F}.Release|x64.Build.0 = Release|Any CPU {6367CACE-0511-485D-9AE5-698F7E600839}.Debug|Any CPU.ActiveCfg = Debug|ARM {6367CACE-0511-485D-9AE5-698F7E600839}.Debug|ARM.ActiveCfg = Debug|ARM {6367CACE-0511-485D-9AE5-698F7E600839}.Debug|Mixed Platforms.ActiveCfg = Debug|ARM {6367CACE-0511-485D-9AE5-698F7E600839}.Debug|Win32.ActiveCfg = Debug|ARM {6367CACE-0511-485D-9AE5-698F7E600839}.Debug|x64.ActiveCfg = Debug|ARM {6367CACE-0511-485D-9AE5-698F7E600839}.Instrumentation|Any CPU.ActiveCfg = Release|ARM {6367CACE-0511-485D-9AE5-698F7E600839}.Instrumentation|ARM.ActiveCfg = Release|ARM {6367CACE-0511-485D-9AE5-698F7E600839}.Instrumentation|Mixed Platforms.ActiveCfg = Release|ARM {6367CACE-0511-485D-9AE5-698F7E600839}.Instrumentation|Win32.ActiveCfg = Release|ARM {6367CACE-0511-485D-9AE5-698F7E600839}.Instrumentation|x64.ActiveCfg = Release|ARM {6367CACE-0511-485D-9AE5-698F7E600839}.Release|Any CPU.ActiveCfg = Release|ARM {6367CACE-0511-485D-9AE5-698F7E600839}.Release|ARM.ActiveCfg = Release|ARM {6367CACE-0511-485D-9AE5-698F7E600839}.Release|Mixed Platforms.ActiveCfg = Release|ARM {6367CACE-0511-485D-9AE5-698F7E600839}.Release|Win32.ActiveCfg = Release|ARM {6367CACE-0511-485D-9AE5-698F7E600839}.Release|x64.ActiveCfg = Release|ARM {016691CA-A31F-4273-A4D2-C5F6E4B3662D}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {016691CA-A31F-4273-A4D2-C5F6E4B3662D}.Debug|Any CPU.Build.0 = Debug|Any CPU {016691CA-A31F-4273-A4D2-C5F6E4B3662D}.Debug|ARM.ActiveCfg = Debug|Any CPU {016691CA-A31F-4273-A4D2-C5F6E4B3662D}.Debug|ARM.Build.0 = Debug|Any CPU {016691CA-A31F-4273-A4D2-C5F6E4B3662D}.Debug|Mixed Platforms.ActiveCfg = Debug|Any CPU {016691CA-A31F-4273-A4D2-C5F6E4B3662D}.Debug|Mixed Platforms.Build.0 = Debug|Any CPU {016691CA-A31F-4273-A4D2-C5F6E4B3662D}.Debug|Win32.ActiveCfg = Debug|Any CPU {016691CA-A31F-4273-A4D2-C5F6E4B3662D}.Debug|Win32.Build.0 = Debug|Any CPU {016691CA-A31F-4273-A4D2-C5F6E4B3662D}.Debug|x64.ActiveCfg = Debug|Any CPU {016691CA-A31F-4273-A4D2-C5F6E4B3662D}.Debug|x64.Build.0 = Debug|Any CPU {016691CA-A31F-4273-A4D2-C5F6E4B3662D}.Instrumentation|Any CPU.ActiveCfg = Instrumentation|Any CPU {016691CA-A31F-4273-A4D2-C5F6E4B3662D}.Instrumentation|Any CPU.Build.0 = Instrumentation|Any CPU {016691CA-A31F-4273-A4D2-C5F6E4B3662D}.Instrumentation|ARM.ActiveCfg = Instrumentation|Any CPU {016691CA-A31F-4273-A4D2-C5F6E4B3662D}.Instrumentation|ARM.Build.0 = Instrumentation|Any CPU {016691CA-A31F-4273-A4D2-C5F6E4B3662D}.Instrumentation|Mixed Platforms.ActiveCfg = Instrumentation|Any CPU {016691CA-A31F-4273-A4D2-C5F6E4B3662D}.Instrumentation|Mixed Platforms.Build.0 = Instrumentation|Any CPU {016691CA-A31F-4273-A4D2-C5F6E4B3662D}.Instrumentation|Win32.ActiveCfg = Instrumentation|Any CPU {016691CA-A31F-4273-A4D2-C5F6E4B3662D}.Instrumentation|Win32.Build.0 = Instrumentation|Any CPU {016691CA-A31F-4273-A4D2-C5F6E4B3662D}.Instrumentation|x64.ActiveCfg = Instrumentation|Any CPU {016691CA-A31F-4273-A4D2-C5F6E4B3662D}.Instrumentation|x64.Build.0 = Instrumentation|Any CPU {016691CA-A31F-4273-A4D2-C5F6E4B3662D}.Release|Any CPU.ActiveCfg = Release|Any CPU {016691CA-A31F-4273-A4D2-C5F6E4B3662D}.Release|Any CPU.Build.0 = Release|Any CPU {016691CA-A31F-4273-A4D2-C5F6E4B3662D}.Release|ARM.ActiveCfg = Release|Any CPU {016691CA-A31F-4273-A4D2-C5F6E4B3662D}.Release|ARM.Build.0 = Release|Any CPU {016691CA-A31F-4273-A4D2-C5F6E4B3662D}.Release|Mixed Platforms.ActiveCfg = Release|Any CPU {016691CA-A31F-4273-A4D2-C5F6E4B3662D}.Release|Mixed Platforms.Build.0 = Release|Any CPU {016691CA-A31F-4273-A4D2-C5F6E4B3662D}.Release|Win32.ActiveCfg = Release|Any CPU {016691CA-A31F-4273-A4D2-C5F6E4B3662D}.Release|Win32.Build.0 = Release|Any CPU {016691CA-A31F-4273-A4D2-C5F6E4B3662D}.Release|x64.ActiveCfg = Release|Any CPU {016691CA-A31F-4273-A4D2-C5F6E4B3662D}.Release|x64.Build.0 = Release|Any CPU {6C581F6A-34F8-4380-9BE0-279F709D13CB}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {6C581F6A-34F8-4380-9BE0-279F709D13CB}.Debug|Any CPU.Build.0 = Debug|Any CPU {6C581F6A-34F8-4380-9BE0-279F709D13CB}.Debug|ARM.ActiveCfg = Debug|Any CPU {6C581F6A-34F8-4380-9BE0-279F709D13CB}.Debug|Mixed Platforms.ActiveCfg = Debug|Any CPU {6C581F6A-34F8-4380-9BE0-279F709D13CB}.Debug|Mixed Platforms.Build.0 = Debug|Any CPU {6C581F6A-34F8-4380-9BE0-279F709D13CB}.Debug|Win32.ActiveCfg = Debug|Any CPU {6C581F6A-34F8-4380-9BE0-279F709D13CB}.Debug|Win32.Build.0 = Debug|Any CPU {6C581F6A-34F8-4380-9BE0-279F709D13CB}.Debug|x64.ActiveCfg = Debug|Any CPU {6C581F6A-34F8-4380-9BE0-279F709D13CB}.Debug|x64.Build.0 = Debug|Any CPU {6C581F6A-34F8-4380-9BE0-279F709D13CB}.Instrumentation|Any CPU.ActiveCfg = Release|Any CPU {6C581F6A-34F8-4380-9BE0-279F709D13CB}.Instrumentation|Any CPU.Build.0 = Release|Any CPU {6C581F6A-34F8-4380-9BE0-279F709D13CB}.Instrumentation|ARM.ActiveCfg = Release|Any CPU {6C581F6A-34F8-4380-9BE0-279F709D13CB}.Instrumentation|ARM.Build.0 = Release|Any CPU {6C581F6A-34F8-4380-9BE0-279F709D13CB}.Instrumentation|Mixed Platforms.ActiveCfg = Release|Any CPU {6C581F6A-34F8-4380-9BE0-279F709D13CB}.Instrumentation|Mixed Platforms.Build.0 = Release|Any CPU {6C581F6A-34F8-4380-9BE0-279F709D13CB}.Instrumentation|Win32.ActiveCfg = Release|Any CPU {6C581F6A-34F8-4380-9BE0-279F709D13CB}.Instrumentation|Win32.Build.0 = Release|Any CPU {6C581F6A-34F8-4380-9BE0-279F709D13CB}.Instrumentation|x64.ActiveCfg = Release|Any CPU {6C581F6A-34F8-4380-9BE0-279F709D13CB}.Instrumentation|x64.Build.0 = Release|Any CPU {6C581F6A-34F8-4380-9BE0-279F709D13CB}.Release|Any CPU.ActiveCfg = Release|Any CPU {6C581F6A-34F8-4380-9BE0-279F709D13CB}.Release|Any CPU.Build.0 = Release|Any CPU {6C581F6A-34F8-4380-9BE0-279F709D13CB}.Release|ARM.ActiveCfg = Release|Any CPU {6C581F6A-34F8-4380-9BE0-279F709D13CB}.Release|ARM.Build.0 = Release|Any CPU {6C581F6A-34F8-4380-9BE0-279F709D13CB}.Release|Mixed Platforms.ActiveCfg = Release|Any CPU {6C581F6A-34F8-4380-9BE0-279F709D13CB}.Release|Mixed Platforms.Build.0 = Release|Any CPU {6C581F6A-34F8-4380-9BE0-279F709D13CB}.Release|Win32.ActiveCfg = Release|Any CPU {6C581F6A-34F8-4380-9BE0-279F709D13CB}.Release|Win32.Build.0 = Release|Any CPU {6C581F6A-34F8-4380-9BE0-279F709D13CB}.Release|x64.ActiveCfg = Release|Any CPU {6C581F6A-34F8-4380-9BE0-279F709D13CB}.Release|x64.Build.0 = Release|Any CPU {D3FA04AF-4285-477D-A756-6C51E9A56E7A}.Debug|Any CPU.ActiveCfg = Debug|ARM {D3FA04AF-4285-477D-A756-6C51E9A56E7A}.Debug|ARM.ActiveCfg = Debug|ARM {D3FA04AF-4285-477D-A756-6C51E9A56E7A}.Debug|ARM.Deploy.0 = Debug|ARM {D3FA04AF-4285-477D-A756-6C51E9A56E7A}.Debug|Mixed Platforms.ActiveCfg = Debug|ARM {D3FA04AF-4285-477D-A756-6C51E9A56E7A}.Debug|Win32.ActiveCfg = Debug|ARM {D3FA04AF-4285-477D-A756-6C51E9A56E7A}.Debug|x64.ActiveCfg = Debug|ARM {D3FA04AF-4285-477D-A756-6C51E9A56E7A}.Instrumentation|Any CPU.ActiveCfg = Release|ARM {D3FA04AF-4285-477D-A756-6C51E9A56E7A}.Instrumentation|ARM.ActiveCfg = Release|ARM {D3FA04AF-4285-477D-A756-6C51E9A56E7A}.Instrumentation|ARM.Build.0 = Release|ARM {D3FA04AF-4285-477D-A756-6C51E9A56E7A}.Instrumentation|ARM.Deploy.0 = Release|ARM {D3FA04AF-4285-477D-A756-6C51E9A56E7A}.Instrumentation|Mixed Platforms.ActiveCfg = Release|ARM {D3FA04AF-4285-477D-A756-6C51E9A56E7A}.Instrumentation|Win32.ActiveCfg = Release|ARM {D3FA04AF-4285-477D-A756-6C51E9A56E7A}.Instrumentation|Win32.Build.0 = Release|ARM {D3FA04AF-4285-477D-A756-6C51E9A56E7A}.Instrumentation|x64.ActiveCfg = Release|ARM {D3FA04AF-4285-477D-A756-6C51E9A56E7A}.Instrumentation|x64.Build.0 = Release|ARM {D3FA04AF-4285-477D-A756-6C51E9A56E7A}.Release|Any CPU.ActiveCfg = Release|ARM {D3FA04AF-4285-477D-A756-6C51E9A56E7A}.Release|ARM.ActiveCfg = Release|ARM {D3FA04AF-4285-477D-A756-6C51E9A56E7A}.Release|ARM.Build.0 = Release|ARM {D3FA04AF-4285-477D-A756-6C51E9A56E7A}.Release|ARM.Deploy.0 = Release|ARM {D3FA04AF-4285-477D-A756-6C51E9A56E7A}.Release|Mixed Platforms.ActiveCfg = Release|ARM {D3FA04AF-4285-477D-A756-6C51E9A56E7A}.Release|Win32.ActiveCfg = Release|ARM {D3FA04AF-4285-477D-A756-6C51E9A56E7A}.Release|Win32.Build.0 = Release|ARM {D3FA04AF-4285-477D-A756-6C51E9A56E7A}.Release|x64.ActiveCfg = Release|ARM {D3FA04AF-4285-477D-A756-6C51E9A56E7A}.Release|x64.Build.0 = Release|ARM {0B37E5BA-4839-4EC4-9E36-A96BCBEA2400}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {0B37E5BA-4839-4EC4-9E36-A96BCBEA2400}.Debug|Any CPU.Build.0 = Debug|Any CPU {0B37E5BA-4839-4EC4-9E36-A96BCBEA2400}.Debug|ARM.ActiveCfg = Debug|Any CPU {0B37E5BA-4839-4EC4-9E36-A96BCBEA2400}.Debug|ARM.Build.0 = Debug|Any CPU {0B37E5BA-4839-4EC4-9E36-A96BCBEA2400}.Debug|Mixed Platforms.ActiveCfg = Debug|Any CPU {0B37E5BA-4839-4EC4-9E36-A96BCBEA2400}.Debug|Mixed Platforms.Build.0 = Debug|Any CPU {0B37E5BA-4839-4EC4-9E36-A96BCBEA2400}.Debug|Win32.ActiveCfg = Debug|Any CPU {0B37E5BA-4839-4EC4-9E36-A96BCBEA2400}.Debug|Win32.Build.0 = Debug|Any CPU {0B37E5BA-4839-4EC4-9E36-A96BCBEA2400}.Debug|x64.ActiveCfg = Debug|Any CPU {0B37E5BA-4839-4EC4-9E36-A96BCBEA2400}.Debug|x64.Build.0 = Debug|Any CPU {0B37E5BA-4839-4EC4-9E36-A96BCBEA2400}.Instrumentation|Any CPU.ActiveCfg = Release|Any CPU {0B37E5BA-4839-4EC4-9E36-A96BCBEA2400}.Instrumentation|Any CPU.Build.0 = Release|Any CPU {0B37E5BA-4839-4EC4-9E36-A96BCBEA2400}.Instrumentation|ARM.ActiveCfg = Release|Any CPU {0B37E5BA-4839-4EC4-9E36-A96BCBEA2400}.Instrumentation|ARM.Build.0 = Release|Any CPU {0B37E5BA-4839-4EC4-9E36-A96BCBEA2400}.Instrumentation|Mixed Platforms.ActiveCfg = Release|Any CPU {0B37E5BA-4839-4EC4-9E36-A96BCBEA2400}.Instrumentation|Mixed Platforms.Build.0 = Release|Any CPU {0B37E5BA-4839-4EC4-9E36-A96BCBEA2400}.Instrumentation|Win32.ActiveCfg = Release|Any CPU {0B37E5BA-4839-4EC4-9E36-A96BCBEA2400}.Instrumentation|Win32.Build.0 = Release|Any CPU {0B37E5BA-4839-4EC4-9E36-A96BCBEA2400}.Instrumentation|x64.ActiveCfg = Release|Any CPU {0B37E5BA-4839-4EC4-9E36-A96BCBEA2400}.Instrumentation|x64.Build.0 = Release|Any CPU {0B37E5BA-4839-4EC4-9E36-A96BCBEA2400}.Release|Any CPU.ActiveCfg = Release|Any CPU {0B37E5BA-4839-4EC4-9E36-A96BCBEA2400}.Release|Any CPU.Build.0 = Release|Any CPU {0B37E5BA-4839-4EC4-9E36-A96BCBEA2400}.Release|ARM.ActiveCfg = Release|Any CPU {0B37E5BA-4839-4EC4-9E36-A96BCBEA2400}.Release|ARM.Build.0 = Release|Any CPU {0B37E5BA-4839-4EC4-9E36-A96BCBEA2400}.Release|Mixed Platforms.ActiveCfg = Release|Any CPU {0B37E5BA-4839-4EC4-9E36-A96BCBEA2400}.Release|Mixed Platforms.Build.0 = Release|Any CPU {0B37E5BA-4839-4EC4-9E36-A96BCBEA2400}.Release|Win32.ActiveCfg = Release|Any CPU {0B37E5BA-4839-4EC4-9E36-A96BCBEA2400}.Release|Win32.Build.0 = Release|Any CPU {0B37E5BA-4839-4EC4-9E36-A96BCBEA2400}.Release|x64.ActiveCfg = Release|Any CPU {0B37E5BA-4839-4EC4-9E36-A96BCBEA2400}.Release|x64.Build.0 = Release|Any CPU {0C522C6A-0F77-4AF8-AD78-5B2415C98C51}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {0C522C6A-0F77-4AF8-AD78-5B2415C98C51}.Debug|Any CPU.Build.0 = Debug|Any CPU {0C522C6A-0F77-4AF8-AD78-5B2415C98C51}.Debug|ARM.ActiveCfg = Debug|Any CPU {0C522C6A-0F77-4AF8-AD78-5B2415C98C51}.Debug|ARM.Build.0 = Debug|Any CPU {0C522C6A-0F77-4AF8-AD78-5B2415C98C51}.Debug|Mixed Platforms.ActiveCfg = Debug|Any CPU {0C522C6A-0F77-4AF8-AD78-5B2415C98C51}.Debug|Mixed Platforms.Build.0 = Debug|Any CPU {0C522C6A-0F77-4AF8-AD78-5B2415C98C51}.Debug|Win32.ActiveCfg = Debug|Any CPU {0C522C6A-0F77-4AF8-AD78-5B2415C98C51}.Debug|Win32.Build.0 = Debug|Any CPU {0C522C6A-0F77-4AF8-AD78-5B2415C98C51}.Debug|x64.ActiveCfg = Debug|Any CPU {0C522C6A-0F77-4AF8-AD78-5B2415C98C51}.Debug|x64.Build.0 = Debug|Any CPU {0C522C6A-0F77-4AF8-AD78-5B2415C98C51}.Instrumentation|Any CPU.ActiveCfg = Release|Any CPU {0C522C6A-0F77-4AF8-AD78-5B2415C98C51}.Instrumentation|Any CPU.Build.0 = Release|Any CPU {0C522C6A-0F77-4AF8-AD78-5B2415C98C51}.Instrumentation|ARM.ActiveCfg = Release|Any CPU {0C522C6A-0F77-4AF8-AD78-5B2415C98C51}.Instrumentation|ARM.Build.0 = Release|Any CPU {0C522C6A-0F77-4AF8-AD78-5B2415C98C51}.Instrumentation|Mixed Platforms.ActiveCfg = Release|Any CPU {0C522C6A-0F77-4AF8-AD78-5B2415C98C51}.Instrumentation|Mixed Platforms.Build.0 = Release|Any CPU {0C522C6A-0F77-4AF8-AD78-5B2415C98C51}.Instrumentation|Win32.ActiveCfg = Release|Any CPU {0C522C6A-0F77-4AF8-AD78-5B2415C98C51}.Instrumentation|Win32.Build.0 = Release|Any CPU {0C522C6A-0F77-4AF8-AD78-5B2415C98C51}.Instrumentation|x64.ActiveCfg = Release|Any CPU {0C522C6A-0F77-4AF8-AD78-5B2415C98C51}.Instrumentation|x64.Build.0 = Release|Any CPU {0C522C6A-0F77-4AF8-AD78-5B2415C98C51}.Release|Any CPU.ActiveCfg = Release|Any CPU {0C522C6A-0F77-4AF8-AD78-5B2415C98C51}.Release|Any CPU.Build.0 = Release|Any CPU {0C522C6A-0F77-4AF8-AD78-5B2415C98C51}.Release|ARM.ActiveCfg = Release|Any CPU {0C522C6A-0F77-4AF8-AD78-5B2415C98C51}.Release|ARM.Build.0 = Release|Any CPU {0C522C6A-0F77-4AF8-AD78-5B2415C98C51}.Release|Mixed Platforms.ActiveCfg = Release|Any CPU {0C522C6A-0F77-4AF8-AD78-5B2415C98C51}.Release|Mixed Platforms.Build.0 = Release|Any CPU {0C522C6A-0F77-4AF8-AD78-5B2415C98C51}.Release|Win32.ActiveCfg = Release|Any CPU {0C522C6A-0F77-4AF8-AD78-5B2415C98C51}.Release|Win32.Build.0 = Release|Any CPU {0C522C6A-0F77-4AF8-AD78-5B2415C98C51}.Release|x64.ActiveCfg = Release|Any CPU {0C522C6A-0F77-4AF8-AD78-5B2415C98C51}.Release|x64.Build.0 = Release|Any CPU {A30EB003-94F8-4A85-8DA1-006F6810A7A4}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {A30EB003-94F8-4A85-8DA1-006F6810A7A4}.Debug|Any CPU.Build.0 = Debug|Any CPU {A30EB003-94F8-4A85-8DA1-006F6810A7A4}.Debug|ARM.ActiveCfg = Debug|Any CPU {A30EB003-94F8-4A85-8DA1-006F6810A7A4}.Debug|ARM.Build.0 = Debug|Any CPU {A30EB003-94F8-4A85-8DA1-006F6810A7A4}.Debug|Mixed Platforms.ActiveCfg = Debug|Any CPU {A30EB003-94F8-4A85-8DA1-006F6810A7A4}.Debug|Mixed Platforms.Build.0 = Debug|Any CPU {A30EB003-94F8-4A85-8DA1-006F6810A7A4}.Debug|Win32.ActiveCfg = Debug|Any CPU {A30EB003-94F8-4A85-8DA1-006F6810A7A4}.Debug|Win32.Build.0 = Debug|Any CPU {A30EB003-94F8-4A85-8DA1-006F6810A7A4}.Debug|x64.ActiveCfg = Debug|Any CPU {A30EB003-94F8-4A85-8DA1-006F6810A7A4}.Debug|x64.Build.0 = Debug|Any CPU {A30EB003-94F8-4A85-8DA1-006F6810A7A4}.Instrumentation|Any CPU.ActiveCfg = Instrumentation|Any CPU {A30EB003-94F8-4A85-8DA1-006F6810A7A4}.Instrumentation|Any CPU.Build.0 = Instrumentation|Any CPU {A30EB003-94F8-4A85-8DA1-006F6810A7A4}.Instrumentation|ARM.ActiveCfg = Instrumentation|Any CPU {A30EB003-94F8-4A85-8DA1-006F6810A7A4}.Instrumentation|ARM.Build.0 = Instrumentation|Any CPU {A30EB003-94F8-4A85-8DA1-006F6810A7A4}.Instrumentation|Mixed Platforms.ActiveCfg = Instrumentation|Any CPU {A30EB003-94F8-4A85-8DA1-006F6810A7A4}.Instrumentation|Mixed Platforms.Build.0 = Instrumentation|Any CPU {A30EB003-94F8-4A85-8DA1-006F6810A7A4}.Instrumentation|Win32.ActiveCfg = Instrumentation|Any CPU {A30EB003-94F8-4A85-8DA1-006F6810A7A4}.Instrumentation|Win32.Build.0 = Instrumentation|Any CPU {A30EB003-94F8-4A85-8DA1-006F6810A7A4}.Instrumentation|x64.ActiveCfg = Instrumentation|Any CPU {A30EB003-94F8-4A85-8DA1-006F6810A7A4}.Instrumentation|x64.Build.0 = Instrumentation|Any CPU {A30EB003-94F8-4A85-8DA1-006F6810A7A4}.Release|Any CPU.ActiveCfg = Release|Any CPU {A30EB003-94F8-4A85-8DA1-006F6810A7A4}.Release|Any CPU.Build.0 = Release|Any CPU {A30EB003-94F8-4A85-8DA1-006F6810A7A4}.Release|ARM.ActiveCfg = Release|Any CPU {A30EB003-94F8-4A85-8DA1-006F6810A7A4}.Release|ARM.Build.0 = Release|Any CPU {A30EB003-94F8-4A85-8DA1-006F6810A7A4}.Release|Mixed Platforms.ActiveCfg = Release|Any CPU {A30EB003-94F8-4A85-8DA1-006F6810A7A4}.Release|Mixed Platforms.Build.0 = Release|Any CPU {A30EB003-94F8-4A85-8DA1-006F6810A7A4}.Release|Win32.ActiveCfg = Release|Any CPU {A30EB003-94F8-4A85-8DA1-006F6810A7A4}.Release|Win32.Build.0 = Release|Any CPU {A30EB003-94F8-4A85-8DA1-006F6810A7A4}.Release|x64.ActiveCfg = Release|Any CPU {A30EB003-94F8-4A85-8DA1-006F6810A7A4}.Release|x64.Build.0 = Release|Any CPU {7FB3F581-742D-4E12-A36A-BE172C574AB0}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {7FB3F581-742D-4E12-A36A-BE172C574AB0}.Debug|Any CPU.Build.0 = Debug|Any CPU {7FB3F581-742D-4E12-A36A-BE172C574AB0}.Debug|ARM.ActiveCfg = Debug|Any CPU {7FB3F581-742D-4E12-A36A-BE172C574AB0}.Debug|ARM.Build.0 = Debug|Any CPU {7FB3F581-742D-4E12-A36A-BE172C574AB0}.Debug|Mixed Platforms.ActiveCfg = Debug|Any CPU {7FB3F581-742D-4E12-A36A-BE172C574AB0}.Debug|Mixed Platforms.Build.0 = Debug|Any CPU {7FB3F581-742D-4E12-A36A-BE172C574AB0}.Debug|Win32.ActiveCfg = Debug|Any CPU {7FB3F581-742D-4E12-A36A-BE172C574AB0}.Debug|Win32.Build.0 = Debug|Any CPU {7FB3F581-742D-4E12-A36A-BE172C574AB0}.Debug|x64.ActiveCfg = Debug|Any CPU {7FB3F581-742D-4E12-A36A-BE172C574AB0}.Debug|x64.Build.0 = Debug|Any CPU {7FB3F581-742D-4E12-A36A-BE172C574AB0}.Instrumentation|Any CPU.ActiveCfg = Release|Any CPU {7FB3F581-742D-4E12-A36A-BE172C574AB0}.Instrumentation|Any CPU.Build.0 = Release|Any CPU {7FB3F581-742D-4E12-A36A-BE172C574AB0}.Instrumentation|ARM.ActiveCfg = Release|Any CPU {7FB3F581-742D-4E12-A36A-BE172C574AB0}.Instrumentation|ARM.Build.0 = Release|Any CPU {7FB3F581-742D-4E12-A36A-BE172C574AB0}.Instrumentation|Mixed Platforms.ActiveCfg = Release|Any CPU {7FB3F581-742D-4E12-A36A-BE172C574AB0}.Instrumentation|Mixed Platforms.Build.0 = Release|Any CPU {7FB3F581-742D-4E12-A36A-BE172C574AB0}.Instrumentation|Win32.ActiveCfg = Release|Any CPU {7FB3F581-742D-4E12-A36A-BE172C574AB0}.Instrumentation|Win32.Build.0 = Release|Any CPU {7FB3F581-742D-4E12-A36A-BE172C574AB0}.Instrumentation|x64.ActiveCfg = Release|Any CPU {7FB3F581-742D-4E12-A36A-BE172C574AB0}.Instrumentation|x64.Build.0 = Release|Any CPU {7FB3F581-742D-4E12-A36A-BE172C574AB0}.Release|Any CPU.ActiveCfg = Release|Any CPU {7FB3F581-742D-4E12-A36A-BE172C574AB0}.Release|Any CPU.Build.0 = Release|Any CPU {7FB3F581-742D-4E12-A36A-BE172C574AB0}.Release|ARM.ActiveCfg = Release|Any CPU {7FB3F581-742D-4E12-A36A-BE172C574AB0}.Release|ARM.Build.0 = Release|Any CPU {7FB3F581-742D-4E12-A36A-BE172C574AB0}.Release|Mixed Platforms.ActiveCfg = Release|Any CPU {7FB3F581-742D-4E12-A36A-BE172C574AB0}.Release|Mixed Platforms.Build.0 = Release|Any CPU {7FB3F581-742D-4E12-A36A-BE172C574AB0}.Release|Win32.ActiveCfg = Release|Any CPU {7FB3F581-742D-4E12-A36A-BE172C574AB0}.Release|Win32.Build.0 = Release|Any CPU {7FB3F581-742D-4E12-A36A-BE172C574AB0}.Release|x64.ActiveCfg = Release|Any CPU {7FB3F581-742D-4E12-A36A-BE172C574AB0}.Release|x64.Build.0 = Release|Any CPU {65C8EDA6-AC24-4E18-A5B5-216E0F2C3906}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {65C8EDA6-AC24-4E18-A5B5-216E0F2C3906}.Debug|Any CPU.Build.0 = Debug|Any CPU {65C8EDA6-AC24-4E18-A5B5-216E0F2C3906}.Debug|ARM.ActiveCfg = Debug|Any CPU {65C8EDA6-AC24-4E18-A5B5-216E0F2C3906}.Debug|ARM.Build.0 = Debug|Any CPU {65C8EDA6-AC24-4E18-A5B5-216E0F2C3906}.Debug|Mixed Platforms.ActiveCfg = Debug|Any CPU {65C8EDA6-AC24-4E18-A5B5-216E0F2C3906}.Debug|Mixed Platforms.Build.0 = Debug|Any CPU {65C8EDA6-AC24-4E18-A5B5-216E0F2C3906}.Debug|Win32.ActiveCfg = Debug|Any CPU {65C8EDA6-AC24-4E18-A5B5-216E0F2C3906}.Debug|Win32.Build.0 = Debug|Any CPU {65C8EDA6-AC24-4E18-A5B5-216E0F2C3906}.Debug|x64.ActiveCfg = Debug|Any CPU {65C8EDA6-AC24-4E18-A5B5-216E0F2C3906}.Debug|x64.Build.0 = Debug|Any CPU {65C8EDA6-AC24-4E18-A5B5-216E0F2C3906}.Instrumentation|Any CPU.ActiveCfg = Release|Any CPU {65C8EDA6-AC24-4E18-A5B5-216E0F2C3906}.Instrumentation|Any CPU.Build.0 = Release|Any CPU {65C8EDA6-AC24-4E18-A5B5-216E0F2C3906}.Instrumentation|ARM.ActiveCfg = Release|Any CPU {65C8EDA6-AC24-4E18-A5B5-216E0F2C3906}.Instrumentation|ARM.Build.0 = Release|Any CPU {65C8EDA6-AC24-4E18-A5B5-216E0F2C3906}.Instrumentation|Mixed Platforms.ActiveCfg = Release|Any CPU {65C8EDA6-AC24-4E18-A5B5-216E0F2C3906}.Instrumentation|Mixed Platforms.Build.0 = Release|Any CPU {65C8EDA6-AC24-4E18-A5B5-216E0F2C3906}.Instrumentation|Win32.ActiveCfg = Release|Any CPU {65C8EDA6-AC24-4E18-A5B5-216E0F2C3906}.Instrumentation|Win32.Build.0 = Release|Any CPU {65C8EDA6-AC24-4E18-A5B5-216E0F2C3906}.Instrumentation|x64.ActiveCfg = Release|Any CPU {65C8EDA6-AC24-4E18-A5B5-216E0F2C3906}.Instrumentation|x64.Build.0 = Release|Any CPU {65C8EDA6-AC24-4E18-A5B5-216E0F2C3906}.Release|Any CPU.ActiveCfg = Release|Any CPU {65C8EDA6-AC24-4E18-A5B5-216E0F2C3906}.Release|Any CPU.Build.0 = Release|Any CPU {65C8EDA6-AC24-4E18-A5B5-216E0F2C3906}.Release|ARM.ActiveCfg = Release|Any CPU {65C8EDA6-AC24-4E18-A5B5-216E0F2C3906}.Release|ARM.Build.0 = Release|Any CPU {65C8EDA6-AC24-4E18-A5B5-216E0F2C3906}.Release|Mixed Platforms.ActiveCfg = Release|Any CPU {65C8EDA6-AC24-4E18-A5B5-216E0F2C3906}.Release|Mixed Platforms.Build.0 = Release|Any CPU {65C8EDA6-AC24-4E18-A5B5-216E0F2C3906}.Release|Win32.ActiveCfg = Release|Any CPU {65C8EDA6-AC24-4E18-A5B5-216E0F2C3906}.Release|Win32.Build.0 = Release|Any CPU {65C8EDA6-AC24-4E18-A5B5-216E0F2C3906}.Release|x64.ActiveCfg = Release|Any CPU {65C8EDA6-AC24-4E18-A5B5-216E0F2C3906}.Release|x64.Build.0 = Release|Any CPU {CA8A6D38-528B-4FAA-89B6-8FA9178DE55D}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {CA8A6D38-528B-4FAA-89B6-8FA9178DE55D}.Debug|Any CPU.Build.0 = Debug|Any CPU {CA8A6D38-528B-4FAA-89B6-8FA9178DE55D}.Debug|ARM.ActiveCfg = Debug|Any CPU {CA8A6D38-528B-4FAA-89B6-8FA9178DE55D}.Debug|ARM.Build.0 = Debug|Any CPU {CA8A6D38-528B-4FAA-89B6-8FA9178DE55D}.Debug|Mixed Platforms.ActiveCfg = Debug|Any CPU {CA8A6D38-528B-4FAA-89B6-8FA9178DE55D}.Debug|Mixed Platforms.Build.0 = Debug|Any CPU {CA8A6D38-528B-4FAA-89B6-8FA9178DE55D}.Debug|Win32.ActiveCfg = Debug|Any CPU {CA8A6D38-528B-4FAA-89B6-8FA9178DE55D}.Debug|Win32.Build.0 = Debug|Any CPU {CA8A6D38-528B-4FAA-89B6-8FA9178DE55D}.Debug|x64.ActiveCfg = Debug|Any CPU {CA8A6D38-528B-4FAA-89B6-8FA9178DE55D}.Debug|x64.Build.0 = Debug|Any CPU {CA8A6D38-528B-4FAA-89B6-8FA9178DE55D}.Instrumentation|Any CPU.ActiveCfg = Instrumentation|Any CPU {CA8A6D38-528B-4FAA-89B6-8FA9178DE55D}.Instrumentation|Any CPU.Build.0 = Instrumentation|Any CPU {CA8A6D38-528B-4FAA-89B6-8FA9178DE55D}.Instrumentation|ARM.ActiveCfg = Instrumentation|Any CPU {CA8A6D38-528B-4FAA-89B6-8FA9178DE55D}.Instrumentation|ARM.Build.0 = Instrumentation|Any CPU {CA8A6D38-528B-4FAA-89B6-8FA9178DE55D}.Instrumentation|Mixed Platforms.ActiveCfg = Instrumentation|Any CPU {CA8A6D38-528B-4FAA-89B6-8FA9178DE55D}.Instrumentation|Mixed Platforms.Build.0 = Instrumentation|Any CPU {CA8A6D38-528B-4FAA-89B6-8FA9178DE55D}.Instrumentation|Win32.ActiveCfg = Instrumentation|Any CPU {CA8A6D38-528B-4FAA-89B6-8FA9178DE55D}.Instrumentation|Win32.Build.0 = Instrumentation|Any CPU {CA8A6D38-528B-4FAA-89B6-8FA9178DE55D}.Instrumentation|x64.ActiveCfg = Instrumentation|Any CPU {CA8A6D38-528B-4FAA-89B6-8FA9178DE55D}.Instrumentation|x64.Build.0 = Instrumentation|Any CPU {CA8A6D38-528B-4FAA-89B6-8FA9178DE55D}.Release|Any CPU.ActiveCfg = Release|Any CPU {CA8A6D38-528B-4FAA-89B6-8FA9178DE55D}.Release|Any CPU.Build.0 = Release|Any CPU {CA8A6D38-528B-4FAA-89B6-8FA9178DE55D}.Release|ARM.ActiveCfg = Release|Any CPU {CA8A6D38-528B-4FAA-89B6-8FA9178DE55D}.Release|ARM.Build.0 = Release|Any CPU {CA8A6D38-528B-4FAA-89B6-8FA9178DE55D}.Release|Mixed Platforms.ActiveCfg = Release|Any CPU {CA8A6D38-528B-4FAA-89B6-8FA9178DE55D}.Release|Mixed Platforms.Build.0 = Release|Any CPU {CA8A6D38-528B-4FAA-89B6-8FA9178DE55D}.Release|Win32.ActiveCfg = Release|Any CPU {CA8A6D38-528B-4FAA-89B6-8FA9178DE55D}.Release|Win32.Build.0 = Release|Any CPU {CA8A6D38-528B-4FAA-89B6-8FA9178DE55D}.Release|x64.ActiveCfg = Release|Any CPU {CA8A6D38-528B-4FAA-89B6-8FA9178DE55D}.Release|x64.Build.0 = Release|Any CPU {D68EE51B-A898-4A77-97D8-C61254CAC122}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {D68EE51B-A898-4A77-97D8-C61254CAC122}.Debug|Any CPU.Build.0 = Debug|Any CPU {D68EE51B-A898-4A77-97D8-C61254CAC122}.Debug|ARM.ActiveCfg = Debug|Any CPU {D68EE51B-A898-4A77-97D8-C61254CAC122}.Debug|ARM.Build.0 = Debug|Any CPU {D68EE51B-A898-4A77-97D8-C61254CAC122}.Debug|Mixed Platforms.ActiveCfg = Debug|Any CPU {D68EE51B-A898-4A77-97D8-C61254CAC122}.Debug|Mixed Platforms.Build.0 = Debug|Any CPU {D68EE51B-A898-4A77-97D8-C61254CAC122}.Debug|Win32.ActiveCfg = Debug|Any CPU {D68EE51B-A898-4A77-97D8-C61254CAC122}.Debug|Win32.Build.0 = Debug|Any CPU {D68EE51B-A898-4A77-97D8-C61254CAC122}.Debug|x64.ActiveCfg = Debug|Any CPU {D68EE51B-A898-4A77-97D8-C61254CAC122}.Debug|x64.Build.0 = Debug|Any CPU {D68EE51B-A898-4A77-97D8-C61254CAC122}.Instrumentation|Any CPU.ActiveCfg = Release|Any CPU {D68EE51B-A898-4A77-97D8-C61254CAC122}.Instrumentation|Any CPU.Build.0 = Release|Any CPU {D68EE51B-A898-4A77-97D8-C61254CAC122}.Instrumentation|ARM.ActiveCfg = Release|Any CPU {D68EE51B-A898-4A77-97D8-C61254CAC122}.Instrumentation|ARM.Build.0 = Release|Any CPU {D68EE51B-A898-4A77-97D8-C61254CAC122}.Instrumentation|Mixed Platforms.ActiveCfg = Release|Any CPU {D68EE51B-A898-4A77-97D8-C61254CAC122}.Instrumentation|Mixed Platforms.Build.0 = Release|Any CPU {D68EE51B-A898-4A77-97D8-C61254CAC122}.Instrumentation|Win32.ActiveCfg = Release|Any CPU {D68EE51B-A898-4A77-97D8-C61254CAC122}.Instrumentation|Win32.Build.0 = Release|Any CPU {D68EE51B-A898-4A77-97D8-C61254CAC122}.Instrumentation|x64.ActiveCfg = Release|Any CPU {D68EE51B-A898-4A77-97D8-C61254CAC122}.Instrumentation|x64.Build.0 = Release|Any CPU {D68EE51B-A898-4A77-97D8-C61254CAC122}.Release|Any CPU.ActiveCfg = Release|Any CPU {D68EE51B-A898-4A77-97D8-C61254CAC122}.Release|Any CPU.Build.0 = Release|Any CPU {D68EE51B-A898-4A77-97D8-C61254CAC122}.Release|ARM.ActiveCfg = Release|Any CPU {D68EE51B-A898-4A77-97D8-C61254CAC122}.Release|ARM.Build.0 = Release|Any CPU {D68EE51B-A898-4A77-97D8-C61254CAC122}.Release|Mixed Platforms.ActiveCfg = Release|Any CPU {D68EE51B-A898-4A77-97D8-C61254CAC122}.Release|Mixed Platforms.Build.0 = Release|Any CPU {D68EE51B-A898-4A77-97D8-C61254CAC122}.Release|Win32.ActiveCfg = Release|Any CPU {D68EE51B-A898-4A77-97D8-C61254CAC122}.Release|Win32.Build.0 = Release|Any CPU {D68EE51B-A898-4A77-97D8-C61254CAC122}.Release|x64.ActiveCfg = Release|Any CPU {D68EE51B-A898-4A77-97D8-C61254CAC122}.Release|x64.Build.0 = Release|Any CPU {1705887B-E636-4FA3-AE40-2D431AF1511C}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {1705887B-E636-4FA3-AE40-2D431AF1511C}.Debug|Any CPU.Build.0 = Debug|Any CPU {1705887B-E636-4FA3-AE40-2D431AF1511C}.Debug|ARM.ActiveCfg = Debug|Any CPU {1705887B-E636-4FA3-AE40-2D431AF1511C}.Debug|ARM.Build.0 = Debug|Any CPU {1705887B-E636-4FA3-AE40-2D431AF1511C}.Debug|Mixed Platforms.ActiveCfg = Debug|Any CPU {1705887B-E636-4FA3-AE40-2D431AF1511C}.Debug|Mixed Platforms.Build.0 = Debug|Any CPU {1705887B-E636-4FA3-AE40-2D431AF1511C}.Debug|Win32.ActiveCfg = Debug|Any CPU {1705887B-E636-4FA3-AE40-2D431AF1511C}.Debug|Win32.Build.0 = Debug|Any CPU {1705887B-E636-4FA3-AE40-2D431AF1511C}.Debug|x64.ActiveCfg = Debug|Any CPU {1705887B-E636-4FA3-AE40-2D431AF1511C}.Debug|x64.Build.0 = Debug|Any CPU {1705887B-E636-4FA3-AE40-2D431AF1511C}.Instrumentation|Any CPU.ActiveCfg = Release|Any CPU {1705887B-E636-4FA3-AE40-2D431AF1511C}.Instrumentation|Any CPU.Build.0 = Release|Any CPU {1705887B-E636-4FA3-AE40-2D431AF1511C}.Instrumentation|ARM.ActiveCfg = Release|Any CPU {1705887B-E636-4FA3-AE40-2D431AF1511C}.Instrumentation|ARM.Build.0 = Release|Any CPU {1705887B-E636-4FA3-AE40-2D431AF1511C}.Instrumentation|Mixed Platforms.ActiveCfg = Release|Any CPU {1705887B-E636-4FA3-AE40-2D431AF1511C}.Instrumentation|Mixed Platforms.Build.0 = Release|Any CPU {1705887B-E636-4FA3-AE40-2D431AF1511C}.Instrumentation|Win32.ActiveCfg = Release|Any CPU {1705887B-E636-4FA3-AE40-2D431AF1511C}.Instrumentation|Win32.Build.0 = Release|Any CPU {1705887B-E636-4FA3-AE40-2D431AF1511C}.Instrumentation|x64.ActiveCfg = Release|Any CPU {1705887B-E636-4FA3-AE40-2D431AF1511C}.Instrumentation|x64.Build.0 = Release|Any CPU {1705887B-E636-4FA3-AE40-2D431AF1511C}.Release|Any CPU.ActiveCfg = Release|Any CPU {1705887B-E636-4FA3-AE40-2D431AF1511C}.Release|Any CPU.Build.0 = Release|Any CPU {1705887B-E636-4FA3-AE40-2D431AF1511C}.Release|ARM.ActiveCfg = Release|Any CPU {1705887B-E636-4FA3-AE40-2D431AF1511C}.Release|ARM.Build.0 = Release|Any CPU {1705887B-E636-4FA3-AE40-2D431AF1511C}.Release|Mixed Platforms.ActiveCfg = Release|Any CPU {1705887B-E636-4FA3-AE40-2D431AF1511C}.Release|Mixed Platforms.Build.0 = Release|Any CPU {1705887B-E636-4FA3-AE40-2D431AF1511C}.Release|Win32.ActiveCfg = Release|Any CPU {1705887B-E636-4FA3-AE40-2D431AF1511C}.Release|Win32.Build.0 = Release|Any CPU {1705887B-E636-4FA3-AE40-2D431AF1511C}.Release|x64.ActiveCfg = Release|Any CPU {1705887B-E636-4FA3-AE40-2D431AF1511C}.Release|x64.Build.0 = Release|Any CPU {CEE4D575-4B4B-42B0-B2F1-CC7198CB7306}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {CEE4D575-4B4B-42B0-B2F1-CC7198CB7306}.Debug|Any CPU.Build.0 = Debug|Any CPU {CEE4D575-4B4B-42B0-B2F1-CC7198CB7306}.Debug|ARM.ActiveCfg = Debug|Any CPU {CEE4D575-4B4B-42B0-B2F1-CC7198CB7306}.Debug|ARM.Build.0 = Debug|Any CPU {CEE4D575-4B4B-42B0-B2F1-CC7198CB7306}.Debug|Mixed Platforms.ActiveCfg = Debug|Any CPU {CEE4D575-4B4B-42B0-B2F1-CC7198CB7306}.Debug|Mixed Platforms.Build.0 = Debug|Any CPU {CEE4D575-4B4B-42B0-B2F1-CC7198CB7306}.Debug|Win32.ActiveCfg = Debug|Any CPU {CEE4D575-4B4B-42B0-B2F1-CC7198CB7306}.Debug|Win32.Build.0 = Debug|Any CPU {CEE4D575-4B4B-42B0-B2F1-CC7198CB7306}.Debug|x64.ActiveCfg = Debug|Any CPU {CEE4D575-4B4B-42B0-B2F1-CC7198CB7306}.Debug|x64.Build.0 = Debug|Any CPU {CEE4D575-4B4B-42B0-B2F1-CC7198CB7306}.Instrumentation|Any CPU.ActiveCfg = Release|Any CPU {CEE4D575-4B4B-42B0-B2F1-CC7198CB7306}.Instrumentation|Any CPU.Build.0 = Release|Any CPU {CEE4D575-4B4B-42B0-B2F1-CC7198CB7306}.Instrumentation|ARM.ActiveCfg = Release|Any CPU {CEE4D575-4B4B-42B0-B2F1-CC7198CB7306}.Instrumentation|ARM.Build.0 = Release|Any CPU {CEE4D575-4B4B-42B0-B2F1-CC7198CB7306}.Instrumentation|Mixed Platforms.ActiveCfg = Release|Any CPU {CEE4D575-4B4B-42B0-B2F1-CC7198CB7306}.Instrumentation|Mixed Platforms.Build.0 = Release|Any CPU {CEE4D575-4B4B-42B0-B2F1-CC7198CB7306}.Instrumentation|Win32.ActiveCfg = Release|Any CPU {CEE4D575-4B4B-42B0-B2F1-CC7198CB7306}.Instrumentation|Win32.Build.0 = Release|Any CPU {CEE4D575-4B4B-42B0-B2F1-CC7198CB7306}.Instrumentation|x64.ActiveCfg = Release|Any CPU {CEE4D575-4B4B-42B0-B2F1-CC7198CB7306}.Instrumentation|x64.Build.0 = Release|Any CPU {CEE4D575-4B4B-42B0-B2F1-CC7198CB7306}.Release|Any CPU.ActiveCfg = Release|Any CPU {CEE4D575-4B4B-42B0-B2F1-CC7198CB7306}.Release|Any CPU.Build.0 = Release|Any CPU {CEE4D575-4B4B-42B0-B2F1-CC7198CB7306}.Release|ARM.ActiveCfg = Release|Any CPU {CEE4D575-4B4B-42B0-B2F1-CC7198CB7306}.Release|ARM.Build.0 = Release|Any CPU {CEE4D575-4B4B-42B0-B2F1-CC7198CB7306}.Release|Mixed Platforms.ActiveCfg = Release|Any CPU {CEE4D575-4B4B-42B0-B2F1-CC7198CB7306}.Release|Mixed Platforms.Build.0 = Release|Any CPU {CEE4D575-4B4B-42B0-B2F1-CC7198CB7306}.Release|Win32.ActiveCfg = Release|Any CPU {CEE4D575-4B4B-42B0-B2F1-CC7198CB7306}.Release|Win32.Build.0 = Release|Any CPU {CEE4D575-4B4B-42B0-B2F1-CC7198CB7306}.Release|x64.ActiveCfg = Release|Any CPU {CEE4D575-4B4B-42B0-B2F1-CC7198CB7306}.Release|x64.Build.0 = Release|Any CPU {4D364D69-06AF-4277-8828-3B4313533A5B}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {4D364D69-06AF-4277-8828-3B4313533A5B}.Debug|Any CPU.Build.0 = Debug|Any CPU {4D364D69-06AF-4277-8828-3B4313533A5B}.Debug|ARM.ActiveCfg = Debug|Any CPU {4D364D69-06AF-4277-8828-3B4313533A5B}.Debug|ARM.Build.0 = Debug|Any CPU {4D364D69-06AF-4277-8828-3B4313533A5B}.Debug|Mixed Platforms.ActiveCfg = Debug|Any CPU {4D364D69-06AF-4277-8828-3B4313533A5B}.Debug|Mixed Platforms.Build.0 = Debug|Any CPU {4D364D69-06AF-4277-8828-3B4313533A5B}.Debug|Win32.ActiveCfg = Debug|Any CPU {4D364D69-06AF-4277-8828-3B4313533A5B}.Debug|Win32.Build.0 = Debug|Any CPU {4D364D69-06AF-4277-8828-3B4313533A5B}.Debug|x64.ActiveCfg = Debug|Any CPU {4D364D69-06AF-4277-8828-3B4313533A5B}.Debug|x64.Build.0 = Debug|Any CPU {4D364D69-06AF-4277-8828-3B4313533A5B}.Instrumentation|Any CPU.ActiveCfg = Release|Any CPU {4D364D69-06AF-4277-8828-3B4313533A5B}.Instrumentation|Any CPU.Build.0 = Release|Any CPU {4D364D69-06AF-4277-8828-3B4313533A5B}.Instrumentation|ARM.ActiveCfg = Release|Any CPU {4D364D69-06AF-4277-8828-3B4313533A5B}.Instrumentation|ARM.Build.0 = Release|Any CPU {4D364D69-06AF-4277-8828-3B4313533A5B}.Instrumentation|Mixed Platforms.ActiveCfg = Release|Any CPU {4D364D69-06AF-4277-8828-3B4313533A5B}.Instrumentation|Mixed Platforms.Build.0 = Release|Any CPU {4D364D69-06AF-4277-8828-3B4313533A5B}.Instrumentation|Win32.ActiveCfg = Release|Any CPU {4D364D69-06AF-4277-8828-3B4313533A5B}.Instrumentation|Win32.Build.0 = Release|Any CPU {4D364D69-06AF-4277-8828-3B4313533A5B}.Instrumentation|x64.ActiveCfg = Release|Any CPU {4D364D69-06AF-4277-8828-3B4313533A5B}.Instrumentation|x64.Build.0 = Release|Any CPU {4D364D69-06AF-4277-8828-3B4313533A5B}.Release|Any CPU.ActiveCfg = Release|Any CPU {4D364D69-06AF-4277-8828-3B4313533A5B}.Release|Any CPU.Build.0 = Release|Any CPU {4D364D69-06AF-4277-8828-3B4313533A5B}.Release|ARM.ActiveCfg = Release|Any CPU {4D364D69-06AF-4277-8828-3B4313533A5B}.Release|ARM.Build.0 = Release|Any CPU {4D364D69-06AF-4277-8828-3B4313533A5B}.Release|Mixed Platforms.ActiveCfg = Release|Any CPU {4D364D69-06AF-4277-8828-3B4313533A5B}.Release|Mixed Platforms.Build.0 = Release|Any CPU {4D364D69-06AF-4277-8828-3B4313533A5B}.Release|Win32.ActiveCfg = Release|Any CPU {4D364D69-06AF-4277-8828-3B4313533A5B}.Release|Win32.Build.0 = Release|Any CPU {4D364D69-06AF-4277-8828-3B4313533A5B}.Release|x64.ActiveCfg = Release|Any CPU {4D364D69-06AF-4277-8828-3B4313533A5B}.Release|x64.Build.0 = Release|Any CPU {E149B569-516B-4C88-A7B1-EBD02E12DD1E}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {E149B569-516B-4C88-A7B1-EBD02E12DD1E}.Debug|Any CPU.Build.0 = Debug|Any CPU {E149B569-516B-4C88-A7B1-EBD02E12DD1E}.Debug|ARM.ActiveCfg = Debug|Any CPU {E149B569-516B-4C88-A7B1-EBD02E12DD1E}.Debug|ARM.Build.0 = Debug|Any CPU {E149B569-516B-4C88-A7B1-EBD02E12DD1E}.Debug|Mixed Platforms.ActiveCfg = Debug|Any CPU {E149B569-516B-4C88-A7B1-EBD02E12DD1E}.Debug|Mixed Platforms.Build.0 = Debug|Any CPU {E149B569-516B-4C88-A7B1-EBD02E12DD1E}.Debug|Win32.ActiveCfg = Debug|Any CPU {E149B569-516B-4C88-A7B1-EBD02E12DD1E}.Debug|Win32.Build.0 = Debug|Any CPU {E149B569-516B-4C88-A7B1-EBD02E12DD1E}.Debug|x64.ActiveCfg = Debug|Any CPU {E149B569-516B-4C88-A7B1-EBD02E12DD1E}.Debug|x64.Build.0 = Debug|Any CPU {E149B569-516B-4C88-A7B1-EBD02E12DD1E}.Instrumentation|Any CPU.ActiveCfg = Release|Any CPU {E149B569-516B-4C88-A7B1-EBD02E12DD1E}.Instrumentation|Any CPU.Build.0 = Release|Any CPU {E149B569-516B-4C88-A7B1-EBD02E12DD1E}.Instrumentation|ARM.ActiveCfg = Release|Any CPU {E149B569-516B-4C88-A7B1-EBD02E12DD1E}.Instrumentation|ARM.Build.0 = Release|Any CPU {E149B569-516B-4C88-A7B1-EBD02E12DD1E}.Instrumentation|Mixed Platforms.ActiveCfg = Release|Any CPU {E149B569-516B-4C88-A7B1-EBD02E12DD1E}.Instrumentation|Mixed Platforms.Build.0 = Release|Any CPU {E149B569-516B-4C88-A7B1-EBD02E12DD1E}.Instrumentation|Win32.ActiveCfg = Release|Any CPU {E149B569-516B-4C88-A7B1-EBD02E12DD1E}.Instrumentation|Win32.Build.0 = Release|Any CPU {E149B569-516B-4C88-A7B1-EBD02E12DD1E}.Instrumentation|x64.ActiveCfg = Release|Any CPU {E149B569-516B-4C88-A7B1-EBD02E12DD1E}.Instrumentation|x64.Build.0 = Release|Any CPU {E149B569-516B-4C88-A7B1-EBD02E12DD1E}.Release|Any CPU.ActiveCfg = Release|Any CPU {E149B569-516B-4C88-A7B1-EBD02E12DD1E}.Release|Any CPU.Build.0 = Release|Any CPU {E149B569-516B-4C88-A7B1-EBD02E12DD1E}.Release|ARM.ActiveCfg = Release|Any CPU {E149B569-516B-4C88-A7B1-EBD02E12DD1E}.Release|ARM.Build.0 = Release|Any CPU {E149B569-516B-4C88-A7B1-EBD02E12DD1E}.Release|Mixed Platforms.ActiveCfg = Release|Any CPU {E149B569-516B-4C88-A7B1-EBD02E12DD1E}.Release|Mixed Platforms.Build.0 = Release|Any CPU {E149B569-516B-4C88-A7B1-EBD02E12DD1E}.Release|Win32.ActiveCfg = Release|Any CPU {E149B569-516B-4C88-A7B1-EBD02E12DD1E}.Release|Win32.Build.0 = Release|Any CPU {E149B569-516B-4C88-A7B1-EBD02E12DD1E}.Release|x64.ActiveCfg = Release|Any CPU {E149B569-516B-4C88-A7B1-EBD02E12DD1E}.Release|x64.Build.0 = Release|Any CPU {B649B569-516B-4C88-A7B1-EBD02E12DD99}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {B649B569-516B-4C88-A7B1-EBD02E12DD99}.Debug|Any CPU.Build.0 = Debug|Any CPU {B649B569-516B-4C88-A7B1-EBD02E12DD99}.Debug|ARM.ActiveCfg = Debug|Any CPU {B649B569-516B-4C88-A7B1-EBD02E12DD99}.Debug|ARM.Build.0 = Debug|Any CPU {B649B569-516B-4C88-A7B1-EBD02E12DD99}.Debug|Mixed Platforms.ActiveCfg = Debug|Any CPU {B649B569-516B-4C88-A7B1-EBD02E12DD99}.Debug|Mixed Platforms.Build.0 = Debug|Any CPU {B649B569-516B-4C88-A7B1-EBD02E12DD99}.Debug|Win32.ActiveCfg = Debug|Any CPU {B649B569-516B-4C88-A7B1-EBD02E12DD99}.Debug|Win32.Build.0 = Debug|Any CPU {B649B569-516B-4C88-A7B1-EBD02E12DD99}.Debug|x64.ActiveCfg = Debug|Any CPU {B649B569-516B-4C88-A7B1-EBD02E12DD99}.Debug|x64.Build.0 = Debug|Any CPU {B649B569-516B-4C88-A7B1-EBD02E12DD99}.Instrumentation|Any CPU.ActiveCfg = Release|Any CPU {B649B569-516B-4C88-A7B1-EBD02E12DD99}.Instrumentation|Any CPU.Build.0 = Release|Any CPU {B649B569-516B-4C88-A7B1-EBD02E12DD99}.Instrumentation|ARM.ActiveCfg = Release|Any CPU {B649B569-516B-4C88-A7B1-EBD02E12DD99}.Instrumentation|ARM.Build.0 = Release|Any CPU {B649B569-516B-4C88-A7B1-EBD02E12DD99}.Instrumentation|Mixed Platforms.ActiveCfg = Release|Any CPU {B649B569-516B-4C88-A7B1-EBD02E12DD99}.Instrumentation|Mixed Platforms.Build.0 = Release|Any CPU {B649B569-516B-4C88-A7B1-EBD02E12DD99}.Instrumentation|Win32.ActiveCfg = Release|Any CPU {B649B569-516B-4C88-A7B1-EBD02E12DD99}.Instrumentation|Win32.Build.0 = Release|Any CPU {B649B569-516B-4C88-A7B1-EBD02E12DD99}.Instrumentation|x64.ActiveCfg = Release|Any CPU {B649B569-516B-4C88-A7B1-EBD02E12DD99}.Instrumentation|x64.Build.0 = Release|Any CPU {B649B569-516B-4C88-A7B1-EBD02E12DD99}.Release|Any CPU.ActiveCfg = Release|Any CPU {B649B569-516B-4C88-A7B1-EBD02E12DD99}.Release|Any CPU.Build.0 = Release|Any CPU {B649B569-516B-4C88-A7B1-EBD02E12DD99}.Release|ARM.ActiveCfg = Release|Any CPU {B649B569-516B-4C88-A7B1-EBD02E12DD99}.Release|ARM.Build.0 = Release|Any CPU {B649B569-516B-4C88-A7B1-EBD02E12DD99}.Release|Mixed Platforms.ActiveCfg = Release|Any CPU {B649B569-516B-4C88-A7B1-EBD02E12DD99}.Release|Mixed Platforms.Build.0 = Release|Any CPU {B649B569-516B-4C88-A7B1-EBD02E12DD99}.Release|Win32.ActiveCfg = Release|Any CPU {B649B569-516B-4C88-A7B1-EBD02E12DD99}.Release|Win32.Build.0 = Release|Any CPU {B649B569-516B-4C88-A7B1-EBD02E12DD99}.Release|x64.ActiveCfg = Release|Any CPU {B649B569-516B-4C88-A7B1-EBD02E12DD99}.Release|x64.Build.0 = Release|Any CPU {A8C7CEC1-FF02-4ECA-967B-72825F4940AE}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {A8C7CEC1-FF02-4ECA-967B-72825F4940AE}.Debug|Any CPU.Build.0 = Debug|Any CPU {A8C7CEC1-FF02-4ECA-967B-72825F4940AE}.Debug|ARM.ActiveCfg = Debug|Any CPU {A8C7CEC1-FF02-4ECA-967B-72825F4940AE}.Debug|ARM.Build.0 = Debug|Any CPU {A8C7CEC1-FF02-4ECA-967B-72825F4940AE}.Debug|Mixed Platforms.ActiveCfg = Debug|Any CPU {A8C7CEC1-FF02-4ECA-967B-72825F4940AE}.Debug|Mixed Platforms.Build.0 = Debug|Any CPU {A8C7CEC1-FF02-4ECA-967B-72825F4940AE}.Debug|Win32.ActiveCfg = Debug|Any CPU {A8C7CEC1-FF02-4ECA-967B-72825F4940AE}.Debug|Win32.Build.0 = Debug|Any CPU {A8C7CEC1-FF02-4ECA-967B-72825F4940AE}.Debug|x64.ActiveCfg = Debug|Any CPU {A8C7CEC1-FF02-4ECA-967B-72825F4940AE}.Debug|x64.Build.0 = Debug|Any CPU {A8C7CEC1-FF02-4ECA-967B-72825F4940AE}.Instrumentation|Any CPU.ActiveCfg = Release|Any CPU {A8C7CEC1-FF02-4ECA-967B-72825F4940AE}.Instrumentation|Any CPU.Build.0 = Release|Any CPU {A8C7CEC1-FF02-4ECA-967B-72825F4940AE}.Instrumentation|ARM.ActiveCfg = Release|Any CPU {A8C7CEC1-FF02-4ECA-967B-72825F4940AE}.Instrumentation|ARM.Build.0 = Release|Any CPU {A8C7CEC1-FF02-4ECA-967B-72825F4940AE}.Instrumentation|Mixed Platforms.ActiveCfg = Release|Any CPU {A8C7CEC1-FF02-4ECA-967B-72825F4940AE}.Instrumentation|Mixed Platforms.Build.0 = Release|Any CPU {A8C7CEC1-FF02-4ECA-967B-72825F4940AE}.Instrumentation|Win32.ActiveCfg = Release|Any CPU {A8C7CEC1-FF02-4ECA-967B-72825F4940AE}.Instrumentation|Win32.Build.0 = Release|Any CPU {A8C7CEC1-FF02-4ECA-967B-72825F4940AE}.Instrumentation|x64.ActiveCfg = Release|Any CPU {A8C7CEC1-FF02-4ECA-967B-72825F4940AE}.Instrumentation|x64.Build.0 = Release|Any CPU {A8C7CEC1-FF02-4ECA-967B-72825F4940AE}.Release|Any CPU.ActiveCfg = Release|Any CPU {A8C7CEC1-FF02-4ECA-967B-72825F4940AE}.Release|Any CPU.Build.0 = Release|Any CPU {A8C7CEC1-FF02-4ECA-967B-72825F4940AE}.Release|ARM.ActiveCfg = Release|Any CPU {A8C7CEC1-FF02-4ECA-967B-72825F4940AE}.Release|ARM.Build.0 = Release|Any CPU {A8C7CEC1-FF02-4ECA-967B-72825F4940AE}.Release|Mixed Platforms.ActiveCfg = Release|Any CPU {A8C7CEC1-FF02-4ECA-967B-72825F4940AE}.Release|Mixed Platforms.Build.0 = Release|Any CPU {A8C7CEC1-FF02-4ECA-967B-72825F4940AE}.Release|Win32.ActiveCfg = Release|Any CPU {A8C7CEC1-FF02-4ECA-967B-72825F4940AE}.Release|Win32.Build.0 = Release|Any CPU {A8C7CEC1-FF02-4ECA-967B-72825F4940AE}.Release|x64.ActiveCfg = Release|Any CPU {A8C7CEC1-FF02-4ECA-967B-72825F4940AE}.Release|x64.Build.0 = Release|Any CPU {9863D039-AB21-4710-960E-7303919552C6}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {9863D039-AB21-4710-960E-7303919552C6}.Debug|Any CPU.Build.0 = Debug|Any CPU {9863D039-AB21-4710-960E-7303919552C6}.Debug|ARM.ActiveCfg = Debug|Any CPU {9863D039-AB21-4710-960E-7303919552C6}.Debug|ARM.Build.0 = Debug|Any CPU {9863D039-AB21-4710-960E-7303919552C6}.Debug|Mixed Platforms.ActiveCfg = Debug|Any CPU {9863D039-AB21-4710-960E-7303919552C6}.Debug|Mixed Platforms.Build.0 = Debug|Any CPU {9863D039-AB21-4710-960E-7303919552C6}.Debug|Win32.ActiveCfg = Debug|Any CPU {9863D039-AB21-4710-960E-7303919552C6}.Debug|Win32.Build.0 = Debug|Any CPU {9863D039-AB21-4710-960E-7303919552C6}.Debug|x64.ActiveCfg = Debug|Any CPU {9863D039-AB21-4710-960E-7303919552C6}.Debug|x64.Build.0 = Debug|Any CPU {9863D039-AB21-4710-960E-7303919552C6}.Instrumentation|Any CPU.ActiveCfg = Release|Any CPU {9863D039-AB21-4710-960E-7303919552C6}.Instrumentation|Any CPU.Build.0 = Release|Any CPU {9863D039-AB21-4710-960E-7303919552C6}.Instrumentation|ARM.ActiveCfg = Release|Any CPU {9863D039-AB21-4710-960E-7303919552C6}.Instrumentation|ARM.Build.0 = Release|Any CPU {9863D039-AB21-4710-960E-7303919552C6}.Instrumentation|Mixed Platforms.ActiveCfg = Release|Any CPU {9863D039-AB21-4710-960E-7303919552C6}.Instrumentation|Mixed Platforms.Build.0 = Release|Any CPU {9863D039-AB21-4710-960E-7303919552C6}.Instrumentation|Win32.ActiveCfg = Release|Any CPU {9863D039-AB21-4710-960E-7303919552C6}.Instrumentation|Win32.Build.0 = Release|Any CPU {9863D039-AB21-4710-960E-7303919552C6}.Instrumentation|x64.ActiveCfg = Release|Any CPU {9863D039-AB21-4710-960E-7303919552C6}.Instrumentation|x64.Build.0 = Release|Any CPU {9863D039-AB21-4710-960E-7303919552C6}.Release|Any CPU.ActiveCfg = Release|Any CPU {9863D039-AB21-4710-960E-7303919552C6}.Release|Any CPU.Build.0 = Release|Any CPU {9863D039-AB21-4710-960E-7303919552C6}.Release|ARM.ActiveCfg = Release|Any CPU {9863D039-AB21-4710-960E-7303919552C6}.Release|ARM.Build.0 = Release|Any CPU {9863D039-AB21-4710-960E-7303919552C6}.Release|Mixed Platforms.ActiveCfg = Release|Any CPU {9863D039-AB21-4710-960E-7303919552C6}.Release|Mixed Platforms.Build.0 = Release|Any CPU {9863D039-AB21-4710-960E-7303919552C6}.Release|Win32.ActiveCfg = Release|Any CPU {9863D039-AB21-4710-960E-7303919552C6}.Release|Win32.Build.0 = Release|Any CPU {9863D039-AB21-4710-960E-7303919552C6}.Release|x64.ActiveCfg = Release|Any CPU {9863D039-AB21-4710-960E-7303919552C6}.Release|x64.Build.0 = Release|Any CPU {C17E59D0-2D64-4012-8A98-D184D0CF8A49}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {C17E59D0-2D64-4012-8A98-D184D0CF8A49}.Debug|Any CPU.Build.0 = Debug|Any CPU {C17E59D0-2D64-4012-8A98-D184D0CF8A49}.Debug|ARM.ActiveCfg = Debug|Any CPU {C17E59D0-2D64-4012-8A98-D184D0CF8A49}.Debug|ARM.Build.0 = Debug|Any CPU {C17E59D0-2D64-4012-8A98-D184D0CF8A49}.Debug|Mixed Platforms.ActiveCfg = Debug|Any CPU {C17E59D0-2D64-4012-8A98-D184D0CF8A49}.Debug|Mixed Platforms.Build.0 = Debug|Any CPU {C17E59D0-2D64-4012-8A98-D184D0CF8A49}.Debug|Win32.ActiveCfg = Debug|Any CPU {C17E59D0-2D64-4012-8A98-D184D0CF8A49}.Debug|Win32.Build.0 = Debug|Any CPU {C17E59D0-2D64-4012-8A98-D184D0CF8A49}.Debug|x64.ActiveCfg = Debug|Any CPU {C17E59D0-2D64-4012-8A98-D184D0CF8A49}.Debug|x64.Build.0 = Debug|Any CPU {C17E59D0-2D64-4012-8A98-D184D0CF8A49}.Instrumentation|Any CPU.ActiveCfg = Release|Any CPU {C17E59D0-2D64-4012-8A98-D184D0CF8A49}.Instrumentation|Any CPU.Build.0 = Release|Any CPU {C17E59D0-2D64-4012-8A98-D184D0CF8A49}.Instrumentation|ARM.ActiveCfg = Release|Any CPU {C17E59D0-2D64-4012-8A98-D184D0CF8A49}.Instrumentation|ARM.Build.0 = Release|Any CPU {C17E59D0-2D64-4012-8A98-D184D0CF8A49}.Instrumentation|Mixed Platforms.ActiveCfg = Release|Any CPU {C17E59D0-2D64-4012-8A98-D184D0CF8A49}.Instrumentation|Mixed Platforms.Build.0 = Release|Any CPU {C17E59D0-2D64-4012-8A98-D184D0CF8A49}.Instrumentation|Win32.ActiveCfg = Release|Any CPU {C17E59D0-2D64-4012-8A98-D184D0CF8A49}.Instrumentation|Win32.Build.0 = Release|Any CPU {C17E59D0-2D64-4012-8A98-D184D0CF8A49}.Instrumentation|x64.ActiveCfg = Release|Any CPU {C17E59D0-2D64-4012-8A98-D184D0CF8A49}.Instrumentation|x64.Build.0 = Release|Any CPU {C17E59D0-2D64-4012-8A98-D184D0CF8A49}.Release|Any CPU.ActiveCfg = Release|Any CPU {C17E59D0-2D64-4012-8A98-D184D0CF8A49}.Release|Any CPU.Build.0 = Release|Any CPU {C17E59D0-2D64-4012-8A98-D184D0CF8A49}.Release|ARM.ActiveCfg = Release|Any CPU {C17E59D0-2D64-4012-8A98-D184D0CF8A49}.Release|ARM.Build.0 = Release|Any CPU {C17E59D0-2D64-4012-8A98-D184D0CF8A49}.Release|Mixed Platforms.ActiveCfg = Release|Any CPU {C17E59D0-2D64-4012-8A98-D184D0CF8A49}.Release|Mixed Platforms.Build.0 = Release|Any CPU {C17E59D0-2D64-4012-8A98-D184D0CF8A49}.Release|Win32.ActiveCfg = Release|Any CPU {C17E59D0-2D64-4012-8A98-D184D0CF8A49}.Release|Win32.Build.0 = Release|Any CPU {C17E59D0-2D64-4012-8A98-D184D0CF8A49}.Release|x64.ActiveCfg = Release|Any CPU {C17E59D0-2D64-4012-8A98-D184D0CF8A49}.Release|x64.Build.0 = Release|Any CPU {DC8C38D7-780B-4B13-8ACE-9050E39CC51C}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {DC8C38D7-780B-4B13-8ACE-9050E39CC51C}.Debug|Any CPU.Build.0 = Debug|Any CPU {DC8C38D7-780B-4B13-8ACE-9050E39CC51C}.Debug|ARM.ActiveCfg = Debug|Any CPU {DC8C38D7-780B-4B13-8ACE-9050E39CC51C}.Debug|ARM.Build.0 = Debug|Any CPU {DC8C38D7-780B-4B13-8ACE-9050E39CC51C}.Debug|Mixed Platforms.ActiveCfg = Debug|Any CPU {DC8C38D7-780B-4B13-8ACE-9050E39CC51C}.Debug|Mixed Platforms.Build.0 = Debug|Any CPU {DC8C38D7-780B-4B13-8ACE-9050E39CC51C}.Debug|Win32.ActiveCfg = Debug|Any CPU {DC8C38D7-780B-4B13-8ACE-9050E39CC51C}.Debug|Win32.Build.0 = Debug|Any CPU {DC8C38D7-780B-4B13-8ACE-9050E39CC51C}.Debug|x64.ActiveCfg = Debug|Any CPU {DC8C38D7-780B-4B13-8ACE-9050E39CC51C}.Debug|x64.Build.0 = Debug|Any CPU {DC8C38D7-780B-4B13-8ACE-9050E39CC51C}.Instrumentation|Any CPU.ActiveCfg = Instrumentation|Any CPU {DC8C38D7-780B-4B13-8ACE-9050E39CC51C}.Instrumentation|Any CPU.Build.0 = Instrumentation|Any CPU {DC8C38D7-780B-4B13-8ACE-9050E39CC51C}.Instrumentation|ARM.ActiveCfg = Instrumentation|Any CPU {DC8C38D7-780B-4B13-8ACE-9050E39CC51C}.Instrumentation|ARM.Build.0 = Instrumentation|Any CPU {DC8C38D7-780B-4B13-8ACE-9050E39CC51C}.Instrumentation|Mixed Platforms.ActiveCfg = Instrumentation|Any CPU {DC8C38D7-780B-4B13-8ACE-9050E39CC51C}.Instrumentation|Mixed Platforms.Build.0 = Instrumentation|Any CPU {DC8C38D7-780B-4B13-8ACE-9050E39CC51C}.Instrumentation|Win32.ActiveCfg = Instrumentation|Any CPU {DC8C38D7-780B-4B13-8ACE-9050E39CC51C}.Instrumentation|Win32.Build.0 = Instrumentation|Any CPU {DC8C38D7-780B-4B13-8ACE-9050E39CC51C}.Instrumentation|x64.ActiveCfg = Instrumentation|Any CPU {DC8C38D7-780B-4B13-8ACE-9050E39CC51C}.Instrumentation|x64.Build.0 = Instrumentation|Any CPU {DC8C38D7-780B-4B13-8ACE-9050E39CC51C}.Release|Any CPU.ActiveCfg = Release|Any CPU {DC8C38D7-780B-4B13-8ACE-9050E39CC51C}.Release|Any CPU.Build.0 = Release|Any CPU {DC8C38D7-780B-4B13-8ACE-9050E39CC51C}.Release|ARM.ActiveCfg = Release|Any CPU {DC8C38D7-780B-4B13-8ACE-9050E39CC51C}.Release|ARM.Build.0 = Release|Any CPU {DC8C38D7-780B-4B13-8ACE-9050E39CC51C}.Release|Mixed Platforms.ActiveCfg = Release|Any CPU {DC8C38D7-780B-4B13-8ACE-9050E39CC51C}.Release|Mixed Platforms.Build.0 = Release|Any CPU {DC8C38D7-780B-4B13-8ACE-9050E39CC51C}.Release|Win32.ActiveCfg = Release|Any CPU {DC8C38D7-780B-4B13-8ACE-9050E39CC51C}.Release|Win32.Build.0 = Release|Any CPU {DC8C38D7-780B-4B13-8ACE-9050E39CC51C}.Release|x64.ActiveCfg = Release|Any CPU {DC8C38D7-780B-4B13-8ACE-9050E39CC51C}.Release|x64.Build.0 = Release|Any CPU {20DC2CF5-8EED-4231-9743-6BAB96BE465C}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {20DC2CF5-8EED-4231-9743-6BAB96BE465C}.Debug|Any CPU.Build.0 = Debug|Any CPU {20DC2CF5-8EED-4231-9743-6BAB96BE465C}.Debug|ARM.ActiveCfg = Debug|Any CPU {20DC2CF5-8EED-4231-9743-6BAB96BE465C}.Debug|ARM.Build.0 = Debug|Any CPU {20DC2CF5-8EED-4231-9743-6BAB96BE465C}.Debug|Mixed Platforms.ActiveCfg = Debug|Any CPU {20DC2CF5-8EED-4231-9743-6BAB96BE465C}.Debug|Mixed Platforms.Build.0 = Debug|Any CPU {20DC2CF5-8EED-4231-9743-6BAB96BE465C}.Debug|Win32.ActiveCfg = Debug|Any CPU {20DC2CF5-8EED-4231-9743-6BAB96BE465C}.Debug|Win32.Build.0 = Debug|Any CPU {20DC2CF5-8EED-4231-9743-6BAB96BE465C}.Debug|x64.ActiveCfg = Debug|Any CPU {20DC2CF5-8EED-4231-9743-6BAB96BE465C}.Debug|x64.Build.0 = Debug|Any CPU {20DC2CF5-8EED-4231-9743-6BAB96BE465C}.Instrumentation|Any CPU.ActiveCfg = Instrumentation|Any CPU {20DC2CF5-8EED-4231-9743-6BAB96BE465C}.Instrumentation|Any CPU.Build.0 = Instrumentation|Any CPU {20DC2CF5-8EED-4231-9743-6BAB96BE465C}.Instrumentation|ARM.ActiveCfg = Instrumentation|Any CPU {20DC2CF5-8EED-4231-9743-6BAB96BE465C}.Instrumentation|ARM.Build.0 = Instrumentation|Any CPU {20DC2CF5-8EED-4231-9743-6BAB96BE465C}.Instrumentation|Mixed Platforms.ActiveCfg = Instrumentation|Any CPU {20DC2CF5-8EED-4231-9743-6BAB96BE465C}.Instrumentation|Mixed Platforms.Build.0 = Instrumentation|Any CPU {20DC2CF5-8EED-4231-9743-6BAB96BE465C}.Instrumentation|Win32.ActiveCfg = Instrumentation|Any CPU {20DC2CF5-8EED-4231-9743-6BAB96BE465C}.Instrumentation|Win32.Build.0 = Instrumentation|Any CPU {20DC2CF5-8EED-4231-9743-6BAB96BE465C}.Instrumentation|x64.ActiveCfg = Instrumentation|Any CPU {20DC2CF5-8EED-4231-9743-6BAB96BE465C}.Instrumentation|x64.Build.0 = Instrumentation|Any CPU {20DC2CF5-8EED-4231-9743-6BAB96BE465C}.Release|Any CPU.ActiveCfg = Release|Any CPU {20DC2CF5-8EED-4231-9743-6BAB96BE465C}.Release|Any CPU.Build.0 = Release|Any CPU {20DC2CF5-8EED-4231-9743-6BAB96BE465C}.Release|ARM.ActiveCfg = Release|Any CPU {20DC2CF5-8EED-4231-9743-6BAB96BE465C}.Release|ARM.Build.0 = Release|Any CPU {20DC2CF5-8EED-4231-9743-6BAB96BE465C}.Release|Mixed Platforms.ActiveCfg = Release|Any CPU {20DC2CF5-8EED-4231-9743-6BAB96BE465C}.Release|Mixed Platforms.Build.0 = Release|Any CPU {20DC2CF5-8EED-4231-9743-6BAB96BE465C}.Release|Win32.ActiveCfg = Release|Any CPU {20DC2CF5-8EED-4231-9743-6BAB96BE465C}.Release|Win32.Build.0 = Release|Any CPU {20DC2CF5-8EED-4231-9743-6BAB96BE465C}.Release|x64.ActiveCfg = Release|Any CPU {20DC2CF5-8EED-4231-9743-6BAB96BE465C}.Release|x64.Build.0 = Release|Any CPU {2832CE7B-8065-4473-A3C7-B8B069920A9C}.Debug|Any CPU.ActiveCfg = Debug|ARM {2832CE7B-8065-4473-A3C7-B8B069920A9C}.Debug|ARM.ActiveCfg = Debug|ARM {2832CE7B-8065-4473-A3C7-B8B069920A9C}.Debug|ARM.Build.0 = Debug|ARM {2832CE7B-8065-4473-A3C7-B8B069920A9C}.Debug|Mixed Platforms.ActiveCfg = Debug|ARM {2832CE7B-8065-4473-A3C7-B8B069920A9C}.Debug|Win32.ActiveCfg = Debug|ARM {2832CE7B-8065-4473-A3C7-B8B069920A9C}.Debug|x64.ActiveCfg = Debug|ARM {2832CE7B-8065-4473-A3C7-B8B069920A9C}.Instrumentation|Any CPU.ActiveCfg = Release|ARM {2832CE7B-8065-4473-A3C7-B8B069920A9C}.Instrumentation|ARM.ActiveCfg = Release|ARM {2832CE7B-8065-4473-A3C7-B8B069920A9C}.Instrumentation|ARM.Build.0 = Release|ARM {2832CE7B-8065-4473-A3C7-B8B069920A9C}.Instrumentation|Mixed Platforms.ActiveCfg = Release|ARM {2832CE7B-8065-4473-A3C7-B8B069920A9C}.Instrumentation|Win32.ActiveCfg = Release|ARM {2832CE7B-8065-4473-A3C7-B8B069920A9C}.Instrumentation|Win32.Build.0 = Release|ARM {2832CE7B-8065-4473-A3C7-B8B069920A9C}.Instrumentation|Win32.Deploy.0 = Release|ARM {2832CE7B-8065-4473-A3C7-B8B069920A9C}.Instrumentation|x64.ActiveCfg = Release|ARM {2832CE7B-8065-4473-A3C7-B8B069920A9C}.Instrumentation|x64.Build.0 = Release|ARM {2832CE7B-8065-4473-A3C7-B8B069920A9C}.Instrumentation|x64.Deploy.0 = Release|ARM {2832CE7B-8065-4473-A3C7-B8B069920A9C}.Release|Any CPU.ActiveCfg = Release|ARM {2832CE7B-8065-4473-A3C7-B8B069920A9C}.Release|ARM.ActiveCfg = Release|ARM {2832CE7B-8065-4473-A3C7-B8B069920A9C}.Release|ARM.Build.0 = Release|ARM {2832CE7B-8065-4473-A3C7-B8B069920A9C}.Release|Mixed Platforms.ActiveCfg = Release|ARM {2832CE7B-8065-4473-A3C7-B8B069920A9C}.Release|Win32.ActiveCfg = Release|ARM {2832CE7B-8065-4473-A3C7-B8B069920A9C}.Release|x64.ActiveCfg = Release|ARM {E77AC86E-58AB-47B6-BC6D-3C1B4545CDFD}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {E77AC86E-58AB-47B6-BC6D-3C1B4545CDFD}.Debug|Any CPU.Build.0 = Debug|Any CPU {E77AC86E-58AB-47B6-BC6D-3C1B4545CDFD}.Debug|ARM.ActiveCfg = Debug|Any CPU {E77AC86E-58AB-47B6-BC6D-3C1B4545CDFD}.Debug|ARM.Build.0 = Debug|Any CPU {E77AC86E-58AB-47B6-BC6D-3C1B4545CDFD}.Debug|Mixed Platforms.ActiveCfg = Debug|Any CPU {E77AC86E-58AB-47B6-BC6D-3C1B4545CDFD}.Debug|Mixed Platforms.Build.0 = Debug|Any CPU {E77AC86E-58AB-47B6-BC6D-3C1B4545CDFD}.Debug|Win32.ActiveCfg = Debug|Any CPU {E77AC86E-58AB-47B6-BC6D-3C1B4545CDFD}.Debug|Win32.Build.0 = Debug|Any CPU {E77AC86E-58AB-47B6-BC6D-3C1B4545CDFD}.Debug|x64.ActiveCfg = Debug|Any CPU {E77AC86E-58AB-47B6-BC6D-3C1B4545CDFD}.Debug|x64.Build.0 = Debug|Any CPU {E77AC86E-58AB-47B6-BC6D-3C1B4545CDFD}.Instrumentation|Any CPU.ActiveCfg = Instrumentation|Any CPU {E77AC86E-58AB-47B6-BC6D-3C1B4545CDFD}.Instrumentation|Any CPU.Build.0 = Instrumentation|Any CPU {E77AC86E-58AB-47B6-BC6D-3C1B4545CDFD}.Instrumentation|ARM.ActiveCfg = Instrumentation|Any CPU {E77AC86E-58AB-47B6-BC6D-3C1B4545CDFD}.Instrumentation|ARM.Build.0 = Instrumentation|Any CPU {E77AC86E-58AB-47B6-BC6D-3C1B4545CDFD}.Instrumentation|Mixed Platforms.ActiveCfg = Instrumentation|Any CPU {E77AC86E-58AB-47B6-BC6D-3C1B4545CDFD}.Instrumentation|Mixed Platforms.Build.0 = Instrumentation|Any CPU {E77AC86E-58AB-47B6-BC6D-3C1B4545CDFD}.Instrumentation|Win32.ActiveCfg = Instrumentation|Any CPU {E77AC86E-58AB-47B6-BC6D-3C1B4545CDFD}.Instrumentation|Win32.Build.0 = Instrumentation|Any CPU {E77AC86E-58AB-47B6-BC6D-3C1B4545CDFD}.Instrumentation|x64.ActiveCfg = Instrumentation|Any CPU {E77AC86E-58AB-47B6-BC6D-3C1B4545CDFD}.Instrumentation|x64.Build.0 = Instrumentation|Any CPU {E77AC86E-58AB-47B6-BC6D-3C1B4545CDFD}.Release|Any CPU.ActiveCfg = Release|Any CPU {E77AC86E-58AB-47B6-BC6D-3C1B4545CDFD}.Release|Any CPU.Build.0 = Release|Any CPU {E77AC86E-58AB-47B6-BC6D-3C1B4545CDFD}.Release|ARM.ActiveCfg = Release|Any CPU {E77AC86E-58AB-47B6-BC6D-3C1B4545CDFD}.Release|ARM.Build.0 = Release|Any CPU {E77AC86E-58AB-47B6-BC6D-3C1B4545CDFD}.Release|Mixed Platforms.ActiveCfg = Release|Any CPU {E77AC86E-58AB-47B6-BC6D-3C1B4545CDFD}.Release|Mixed Platforms.Build.0 = Release|Any CPU {E77AC86E-58AB-47B6-BC6D-3C1B4545CDFD}.Release|Win32.ActiveCfg = Release|Any CPU {E77AC86E-58AB-47B6-BC6D-3C1B4545CDFD}.Release|Win32.Build.0 = Release|Any CPU {E77AC86E-58AB-47B6-BC6D-3C1B4545CDFD}.Release|x64.ActiveCfg = Release|Any CPU {E77AC86E-58AB-47B6-BC6D-3C1B4545CDFD}.Release|x64.Build.0 = Release|Any CPU {40710089-C1C3-49D9-93B6-07A25219E5E8}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {40710089-C1C3-49D9-93B6-07A25219E5E8}.Debug|Any CPU.Build.0 = Debug|Any CPU {40710089-C1C3-49D9-93B6-07A25219E5E8}.Debug|ARM.ActiveCfg = Debug|Any CPU {40710089-C1C3-49D9-93B6-07A25219E5E8}.Debug|ARM.Build.0 = Debug|Any CPU {40710089-C1C3-49D9-93B6-07A25219E5E8}.Debug|Mixed Platforms.ActiveCfg = Debug|Any CPU {40710089-C1C3-49D9-93B6-07A25219E5E8}.Debug|Mixed Platforms.Build.0 = Debug|Any CPU {40710089-C1C3-49D9-93B6-07A25219E5E8}.Debug|Win32.ActiveCfg = Debug|Any CPU {40710089-C1C3-49D9-93B6-07A25219E5E8}.Debug|Win32.Build.0 = Debug|Any CPU {40710089-C1C3-49D9-93B6-07A25219E5E8}.Debug|x64.ActiveCfg = Debug|Any CPU {40710089-C1C3-49D9-93B6-07A25219E5E8}.Debug|x64.Build.0 = Debug|Any CPU {40710089-C1C3-49D9-93B6-07A25219E5E8}.Instrumentation|Any CPU.ActiveCfg = Release|Any CPU {40710089-C1C3-49D9-93B6-07A25219E5E8}.Instrumentation|Any CPU.Build.0 = Release|Any CPU {40710089-C1C3-49D9-93B6-07A25219E5E8}.Instrumentation|ARM.ActiveCfg = Release|Any CPU {40710089-C1C3-49D9-93B6-07A25219E5E8}.Instrumentation|ARM.Build.0 = Release|Any CPU {40710089-C1C3-49D9-93B6-07A25219E5E8}.Instrumentation|Mixed Platforms.ActiveCfg = Release|Any CPU {40710089-C1C3-49D9-93B6-07A25219E5E8}.Instrumentation|Mixed Platforms.Build.0 = Release|Any CPU {40710089-C1C3-49D9-93B6-07A25219E5E8}.Instrumentation|Win32.ActiveCfg = Release|Any CPU {40710089-C1C3-49D9-93B6-07A25219E5E8}.Instrumentation|Win32.Build.0 = Release|Any CPU {40710089-C1C3-49D9-93B6-07A25219E5E8}.Instrumentation|x64.ActiveCfg = Release|Any CPU {40710089-C1C3-49D9-93B6-07A25219E5E8}.Instrumentation|x64.Build.0 = Release|Any CPU {40710089-C1C3-49D9-93B6-07A25219E5E8}.Release|Any CPU.ActiveCfg = Release|Any CPU {40710089-C1C3-49D9-93B6-07A25219E5E8}.Release|Any CPU.Build.0 = Release|Any CPU {40710089-C1C3-49D9-93B6-07A25219E5E8}.Release|ARM.ActiveCfg = Release|Any CPU {40710089-C1C3-49D9-93B6-07A25219E5E8}.Release|ARM.Build.0 = Release|Any CPU {40710089-C1C3-49D9-93B6-07A25219E5E8}.Release|Mixed Platforms.ActiveCfg = Release|Any CPU {40710089-C1C3-49D9-93B6-07A25219E5E8}.Release|Mixed Platforms.Build.0 = Release|Any CPU {40710089-C1C3-49D9-93B6-07A25219E5E8}.Release|Win32.ActiveCfg = Release|Any CPU {40710089-C1C3-49D9-93B6-07A25219E5E8}.Release|Win32.Build.0 = Release|Any CPU {40710089-C1C3-49D9-93B6-07A25219E5E8}.Release|x64.ActiveCfg = Release|Any CPU {40710089-C1C3-49D9-93B6-07A25219E5E8}.Release|x64.Build.0 = Release|Any CPU {769F9326-B779-4F35-BC49-87E15CDF2A8C}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {769F9326-B779-4F35-BC49-87E15CDF2A8C}.Debug|Any CPU.Build.0 = Debug|Any CPU {769F9326-B779-4F35-BC49-87E15CDF2A8C}.Debug|ARM.ActiveCfg = Debug|Any CPU {769F9326-B779-4F35-BC49-87E15CDF2A8C}.Debug|ARM.Build.0 = Debug|Any CPU {769F9326-B779-4F35-BC49-87E15CDF2A8C}.Debug|Mixed Platforms.ActiveCfg = Debug|Any CPU {769F9326-B779-4F35-BC49-87E15CDF2A8C}.Debug|Mixed Platforms.Build.0 = Debug|Any CPU {769F9326-B779-4F35-BC49-87E15CDF2A8C}.Debug|Win32.ActiveCfg = Debug|Any CPU {769F9326-B779-4F35-BC49-87E15CDF2A8C}.Debug|Win32.Build.0 = Debug|Any CPU {769F9326-B779-4F35-BC49-87E15CDF2A8C}.Debug|x64.ActiveCfg = Debug|Any CPU {769F9326-B779-4F35-BC49-87E15CDF2A8C}.Debug|x64.Build.0 = Debug|Any CPU {769F9326-B779-4F35-BC49-87E15CDF2A8C}.Instrumentation|Any CPU.ActiveCfg = Release|Any CPU {769F9326-B779-4F35-BC49-87E15CDF2A8C}.Instrumentation|Any CPU.Build.0 = Release|Any CPU {769F9326-B779-4F35-BC49-87E15CDF2A8C}.Instrumentation|ARM.ActiveCfg = Release|Any CPU {769F9326-B779-4F35-BC49-87E15CDF2A8C}.Instrumentation|ARM.Build.0 = Release|Any CPU {769F9326-B779-4F35-BC49-87E15CDF2A8C}.Instrumentation|Mixed Platforms.ActiveCfg = Release|Any CPU {769F9326-B779-4F35-BC49-87E15CDF2A8C}.Instrumentation|Mixed Platforms.Build.0 = Release|Any CPU {769F9326-B779-4F35-BC49-87E15CDF2A8C}.Instrumentation|Win32.ActiveCfg = Release|Any CPU {769F9326-B779-4F35-BC49-87E15CDF2A8C}.Instrumentation|Win32.Build.0 = Release|Any CPU {769F9326-B779-4F35-BC49-87E15CDF2A8C}.Instrumentation|x64.ActiveCfg = Release|Any CPU {769F9326-B779-4F35-BC49-87E15CDF2A8C}.Instrumentation|x64.Build.0 = Release|Any CPU {769F9326-B779-4F35-BC49-87E15CDF2A8C}.Release|Any CPU.ActiveCfg = Release|Any CPU {769F9326-B779-4F35-BC49-87E15CDF2A8C}.Release|Any CPU.Build.0 = Release|Any CPU {769F9326-B779-4F35-BC49-87E15CDF2A8C}.Release|ARM.ActiveCfg = Release|Any CPU {769F9326-B779-4F35-BC49-87E15CDF2A8C}.Release|ARM.Build.0 = Release|Any CPU {769F9326-B779-4F35-BC49-87E15CDF2A8C}.Release|Mixed Platforms.ActiveCfg = Release|Any CPU {769F9326-B779-4F35-BC49-87E15CDF2A8C}.Release|Mixed Platforms.Build.0 = Release|Any CPU {769F9326-B779-4F35-BC49-87E15CDF2A8C}.Release|Win32.ActiveCfg = Release|Any CPU {769F9326-B779-4F35-BC49-87E15CDF2A8C}.Release|Win32.Build.0 = Release|Any CPU {769F9326-B779-4F35-BC49-87E15CDF2A8C}.Release|x64.ActiveCfg = Release|Any CPU {769F9326-B779-4F35-BC49-87E15CDF2A8C}.Release|x64.Build.0 = Release|Any CPU {DD4371DE-85A8-49AA-B939-10E03B7ED3C9}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {DD4371DE-85A8-49AA-B939-10E03B7ED3C9}.Debug|Any CPU.Build.0 = Debug|Any CPU {DD4371DE-85A8-49AA-B939-10E03B7ED3C9}.Debug|ARM.ActiveCfg = Debug|Any CPU {DD4371DE-85A8-49AA-B939-10E03B7ED3C9}.Debug|ARM.Build.0 = Debug|Any CPU {DD4371DE-85A8-49AA-B939-10E03B7ED3C9}.Debug|Mixed Platforms.ActiveCfg = Debug|Any CPU {DD4371DE-85A8-49AA-B939-10E03B7ED3C9}.Debug|Mixed Platforms.Build.0 = Debug|Any CPU {DD4371DE-85A8-49AA-B939-10E03B7ED3C9}.Debug|Win32.ActiveCfg = Debug|Any CPU {DD4371DE-85A8-49AA-B939-10E03B7ED3C9}.Debug|Win32.Build.0 = Debug|Any CPU {DD4371DE-85A8-49AA-B939-10E03B7ED3C9}.Debug|x64.ActiveCfg = Debug|Any CPU {DD4371DE-85A8-49AA-B939-10E03B7ED3C9}.Debug|x64.Build.0 = Debug|Any CPU {DD4371DE-85A8-49AA-B939-10E03B7ED3C9}.Instrumentation|Any CPU.ActiveCfg = Release|Any CPU {DD4371DE-85A8-49AA-B939-10E03B7ED3C9}.Instrumentation|Any CPU.Build.0 = Release|Any CPU {DD4371DE-85A8-49AA-B939-10E03B7ED3C9}.Instrumentation|ARM.ActiveCfg = Release|Any CPU {DD4371DE-85A8-49AA-B939-10E03B7ED3C9}.Instrumentation|ARM.Build.0 = Release|Any CPU {DD4371DE-85A8-49AA-B939-10E03B7ED3C9}.Instrumentation|Mixed Platforms.ActiveCfg = Release|Any CPU {DD4371DE-85A8-49AA-B939-10E03B7ED3C9}.Instrumentation|Mixed Platforms.Build.0 = Release|Any CPU {DD4371DE-85A8-49AA-B939-10E03B7ED3C9}.Instrumentation|Win32.ActiveCfg = Release|Any CPU {DD4371DE-85A8-49AA-B939-10E03B7ED3C9}.Instrumentation|Win32.Build.0 = Release|Any CPU {DD4371DE-85A8-49AA-B939-10E03B7ED3C9}.Instrumentation|x64.ActiveCfg = Release|Any CPU {DD4371DE-85A8-49AA-B939-10E03B7ED3C9}.Instrumentation|x64.Build.0 = Release|Any CPU {DD4371DE-85A8-49AA-B939-10E03B7ED3C9}.Release|Any CPU.ActiveCfg = Release|Any CPU {DD4371DE-85A8-49AA-B939-10E03B7ED3C9}.Release|Any CPU.Build.0 = Release|Any CPU {DD4371DE-85A8-49AA-B939-10E03B7ED3C9}.Release|ARM.ActiveCfg = Release|Any CPU {DD4371DE-85A8-49AA-B939-10E03B7ED3C9}.Release|ARM.Build.0 = Release|Any CPU {DD4371DE-85A8-49AA-B939-10E03B7ED3C9}.Release|Mixed Platforms.ActiveCfg = Release|Any CPU {DD4371DE-85A8-49AA-B939-10E03B7ED3C9}.Release|Mixed Platforms.Build.0 = Release|Any CPU {DD4371DE-85A8-49AA-B939-10E03B7ED3C9}.Release|Win32.ActiveCfg = Release|Any CPU {DD4371DE-85A8-49AA-B939-10E03B7ED3C9}.Release|Win32.Build.0 = Release|Any CPU {DD4371DE-85A8-49AA-B939-10E03B7ED3C9}.Release|x64.ActiveCfg = Release|Any CPU {DD4371DE-85A8-49AA-B939-10E03B7ED3C9}.Release|x64.Build.0 = Release|Any CPU {9B0EDB62-1E62-492D-B807-A8501EEE8400}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {9B0EDB62-1E62-492D-B807-A8501EEE8400}.Debug|Any CPU.Build.0 = Debug|Any CPU {9B0EDB62-1E62-492D-B807-A8501EEE8400}.Debug|ARM.ActiveCfg = Debug|Any CPU {9B0EDB62-1E62-492D-B807-A8501EEE8400}.Debug|ARM.Build.0 = Debug|Any CPU {9B0EDB62-1E62-492D-B807-A8501EEE8400}.Debug|Mixed Platforms.ActiveCfg = Debug|Any CPU {9B0EDB62-1E62-492D-B807-A8501EEE8400}.Debug|Mixed Platforms.Build.0 = Debug|Any CPU {9B0EDB62-1E62-492D-B807-A8501EEE8400}.Debug|Win32.ActiveCfg = Debug|Any CPU {9B0EDB62-1E62-492D-B807-A8501EEE8400}.Debug|Win32.Build.0 = Debug|Any CPU {9B0EDB62-1E62-492D-B807-A8501EEE8400}.Debug|x64.ActiveCfg = Debug|Any CPU {9B0EDB62-1E62-492D-B807-A8501EEE8400}.Debug|x64.Build.0 = Debug|Any CPU {9B0EDB62-1E62-492D-B807-A8501EEE8400}.Instrumentation|Any CPU.ActiveCfg = Release|Any CPU {9B0EDB62-1E62-492D-B807-A8501EEE8400}.Instrumentation|Any CPU.Build.0 = Release|Any CPU {9B0EDB62-1E62-492D-B807-A8501EEE8400}.Instrumentation|ARM.ActiveCfg = Release|Any CPU {9B0EDB62-1E62-492D-B807-A8501EEE8400}.Instrumentation|ARM.Build.0 = Release|Any CPU {9B0EDB62-1E62-492D-B807-A8501EEE8400}.Instrumentation|Mixed Platforms.ActiveCfg = Release|Any CPU {9B0EDB62-1E62-492D-B807-A8501EEE8400}.Instrumentation|Mixed Platforms.Build.0 = Release|Any CPU {9B0EDB62-1E62-492D-B807-A8501EEE8400}.Instrumentation|Win32.ActiveCfg = Release|Any CPU {9B0EDB62-1E62-492D-B807-A8501EEE8400}.Instrumentation|Win32.Build.0 = Release|Any CPU {9B0EDB62-1E62-492D-B807-A8501EEE8400}.Instrumentation|x64.ActiveCfg = Release|Any CPU {9B0EDB62-1E62-492D-B807-A8501EEE8400}.Instrumentation|x64.Build.0 = Release|Any CPU {9B0EDB62-1E62-492D-B807-A8501EEE8400}.Release|Any CPU.ActiveCfg = Release|Any CPU {9B0EDB62-1E62-492D-B807-A8501EEE8400}.Release|Any CPU.Build.0 = Release|Any CPU {9B0EDB62-1E62-492D-B807-A8501EEE8400}.Release|ARM.ActiveCfg = Release|Any CPU {9B0EDB62-1E62-492D-B807-A8501EEE8400}.Release|ARM.Build.0 = Release|Any CPU {9B0EDB62-1E62-492D-B807-A8501EEE8400}.Release|Mixed Platforms.ActiveCfg = Release|Any CPU {9B0EDB62-1E62-492D-B807-A8501EEE8400}.Release|Mixed Platforms.Build.0 = Release|Any CPU {9B0EDB62-1E62-492D-B807-A8501EEE8400}.Release|Win32.ActiveCfg = Release|Any CPU {9B0EDB62-1E62-492D-B807-A8501EEE8400}.Release|Win32.Build.0 = Release|Any CPU {9B0EDB62-1E62-492D-B807-A8501EEE8400}.Release|x64.ActiveCfg = Release|Any CPU {9B0EDB62-1E62-492D-B807-A8501EEE8400}.Release|x64.Build.0 = Release|Any CPU {93219A45-914C-44B7-A6CB-66849879C8B1}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {93219A45-914C-44B7-A6CB-66849879C8B1}.Debug|Any CPU.Build.0 = Debug|Any CPU {93219A45-914C-44B7-A6CB-66849879C8B1}.Debug|ARM.ActiveCfg = Debug|Any CPU {93219A45-914C-44B7-A6CB-66849879C8B1}.Debug|ARM.Build.0 = Debug|Any CPU {93219A45-914C-44B7-A6CB-66849879C8B1}.Debug|Mixed Platforms.ActiveCfg = Debug|Any CPU {93219A45-914C-44B7-A6CB-66849879C8B1}.Debug|Mixed Platforms.Build.0 = Debug|Any CPU {93219A45-914C-44B7-A6CB-66849879C8B1}.Debug|Win32.ActiveCfg = Debug|Any CPU {93219A45-914C-44B7-A6CB-66849879C8B1}.Debug|Win32.Build.0 = Debug|Any CPU {93219A45-914C-44B7-A6CB-66849879C8B1}.Debug|x64.ActiveCfg = Debug|Any CPU {93219A45-914C-44B7-A6CB-66849879C8B1}.Debug|x64.Build.0 = Debug|Any CPU {93219A45-914C-44B7-A6CB-66849879C8B1}.Instrumentation|Any CPU.ActiveCfg = Instrumentation|Any CPU {93219A45-914C-44B7-A6CB-66849879C8B1}.Instrumentation|Any CPU.Build.0 = Instrumentation|Any CPU {93219A45-914C-44B7-A6CB-66849879C8B1}.Instrumentation|ARM.ActiveCfg = Instrumentation|Any CPU {93219A45-914C-44B7-A6CB-66849879C8B1}.Instrumentation|ARM.Build.0 = Instrumentation|Any CPU {93219A45-914C-44B7-A6CB-66849879C8B1}.Instrumentation|Mixed Platforms.ActiveCfg = Instrumentation|Any CPU {93219A45-914C-44B7-A6CB-66849879C8B1}.Instrumentation|Mixed Platforms.Build.0 = Instrumentation|Any CPU {93219A45-914C-44B7-A6CB-66849879C8B1}.Instrumentation|Win32.ActiveCfg = Instrumentation|Any CPU {93219A45-914C-44B7-A6CB-66849879C8B1}.Instrumentation|Win32.Build.0 = Instrumentation|Any CPU {93219A45-914C-44B7-A6CB-66849879C8B1}.Instrumentation|x64.ActiveCfg = Instrumentation|Any CPU {93219A45-914C-44B7-A6CB-66849879C8B1}.Instrumentation|x64.Build.0 = Instrumentation|Any CPU {93219A45-914C-44B7-A6CB-66849879C8B1}.Release|Any CPU.ActiveCfg = Release|Any CPU {93219A45-914C-44B7-A6CB-66849879C8B1}.Release|Any CPU.Build.0 = Release|Any CPU {93219A45-914C-44B7-A6CB-66849879C8B1}.Release|ARM.ActiveCfg = Release|Any CPU {93219A45-914C-44B7-A6CB-66849879C8B1}.Release|ARM.Build.0 = Release|Any CPU {93219A45-914C-44B7-A6CB-66849879C8B1}.Release|Mixed Platforms.ActiveCfg = Release|Any CPU {93219A45-914C-44B7-A6CB-66849879C8B1}.Release|Mixed Platforms.Build.0 = Release|Any CPU {93219A45-914C-44B7-A6CB-66849879C8B1}.Release|Win32.ActiveCfg = Release|Any CPU {93219A45-914C-44B7-A6CB-66849879C8B1}.Release|Win32.Build.0 = Release|Any CPU {93219A45-914C-44B7-A6CB-66849879C8B1}.Release|x64.ActiveCfg = Release|Any CPU {93219A45-914C-44B7-A6CB-66849879C8B1}.Release|x64.Build.0 = Release|Any CPU {2D6185A8-A5FE-4FDF-874A-96037C37BD41}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {2D6185A8-A5FE-4FDF-874A-96037C37BD41}.Debug|Any CPU.Build.0 = Debug|Any CPU {2D6185A8-A5FE-4FDF-874A-96037C37BD41}.Debug|ARM.ActiveCfg = Debug|Any CPU {2D6185A8-A5FE-4FDF-874A-96037C37BD41}.Debug|ARM.Build.0 = Debug|Any CPU {2D6185A8-A5FE-4FDF-874A-96037C37BD41}.Debug|Mixed Platforms.ActiveCfg = Debug|Any CPU {2D6185A8-A5FE-4FDF-874A-96037C37BD41}.Debug|Mixed Platforms.Build.0 = Debug|Any CPU {2D6185A8-A5FE-4FDF-874A-96037C37BD41}.Debug|Win32.ActiveCfg = Debug|Any CPU {2D6185A8-A5FE-4FDF-874A-96037C37BD41}.Debug|Win32.Build.0 = Debug|Any CPU {2D6185A8-A5FE-4FDF-874A-96037C37BD41}.Debug|x64.ActiveCfg = Debug|Any CPU {2D6185A8-A5FE-4FDF-874A-96037C37BD41}.Debug|x64.Build.0 = Debug|Any CPU {2D6185A8-A5FE-4FDF-874A-96037C37BD41}.Instrumentation|Any CPU.ActiveCfg = Release|Any CPU {2D6185A8-A5FE-4FDF-874A-96037C37BD41}.Instrumentation|Any CPU.Build.0 = Release|Any CPU {2D6185A8-A5FE-4FDF-874A-96037C37BD41}.Instrumentation|ARM.ActiveCfg = Release|Any CPU {2D6185A8-A5FE-4FDF-874A-96037C37BD41}.Instrumentation|ARM.Build.0 = Release|Any CPU {2D6185A8-A5FE-4FDF-874A-96037C37BD41}.Instrumentation|Mixed Platforms.ActiveCfg = Release|Any CPU {2D6185A8-A5FE-4FDF-874A-96037C37BD41}.Instrumentation|Mixed Platforms.Build.0 = Release|Any CPU {2D6185A8-A5FE-4FDF-874A-96037C37BD41}.Instrumentation|Win32.ActiveCfg = Release|Any CPU {2D6185A8-A5FE-4FDF-874A-96037C37BD41}.Instrumentation|Win32.Build.0 = Release|Any CPU {2D6185A8-A5FE-4FDF-874A-96037C37BD41}.Instrumentation|x64.ActiveCfg = Release|Any CPU {2D6185A8-A5FE-4FDF-874A-96037C37BD41}.Instrumentation|x64.Build.0 = Release|Any CPU {2D6185A8-A5FE-4FDF-874A-96037C37BD41}.Release|Any CPU.ActiveCfg = Release|Any CPU {2D6185A8-A5FE-4FDF-874A-96037C37BD41}.Release|Any CPU.Build.0 = Release|Any CPU {2D6185A8-A5FE-4FDF-874A-96037C37BD41}.Release|ARM.ActiveCfg = Release|Any CPU {2D6185A8-A5FE-4FDF-874A-96037C37BD41}.Release|ARM.Build.0 = Release|Any CPU {2D6185A8-A5FE-4FDF-874A-96037C37BD41}.Release|Mixed Platforms.ActiveCfg = Release|Any CPU {2D6185A8-A5FE-4FDF-874A-96037C37BD41}.Release|Mixed Platforms.Build.0 = Release|Any CPU {2D6185A8-A5FE-4FDF-874A-96037C37BD41}.Release|Win32.ActiveCfg = Release|Any CPU {2D6185A8-A5FE-4FDF-874A-96037C37BD41}.Release|Win32.Build.0 = Release|Any CPU {2D6185A8-A5FE-4FDF-874A-96037C37BD41}.Release|x64.ActiveCfg = Release|Any CPU {2D6185A8-A5FE-4FDF-874A-96037C37BD41}.Release|x64.Build.0 = Release|Any CPU {54125FC8-5C6D-4F4B-92B8-3377FE1D92E1}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {54125FC8-5C6D-4F4B-92B8-3377FE1D92E1}.Debug|Any CPU.Build.0 = Debug|Any CPU {54125FC8-5C6D-4F4B-92B8-3377FE1D92E1}.Debug|ARM.ActiveCfg = Debug|Any CPU {54125FC8-5C6D-4F4B-92B8-3377FE1D92E1}.Debug|ARM.Build.0 = Debug|Any CPU {54125FC8-5C6D-4F4B-92B8-3377FE1D92E1}.Debug|Mixed Platforms.ActiveCfg = Debug|Any CPU {54125FC8-5C6D-4F4B-92B8-3377FE1D92E1}.Debug|Mixed Platforms.Build.0 = Debug|Any CPU {54125FC8-5C6D-4F4B-92B8-3377FE1D92E1}.Debug|Win32.ActiveCfg = Debug|Any CPU {54125FC8-5C6D-4F4B-92B8-3377FE1D92E1}.Debug|Win32.Build.0 = Debug|Any CPU {54125FC8-5C6D-4F4B-92B8-3377FE1D92E1}.Debug|x64.ActiveCfg = Debug|Any CPU {54125FC8-5C6D-4F4B-92B8-3377FE1D92E1}.Debug|x64.Build.0 = Debug|Any CPU {54125FC8-5C6D-4F4B-92B8-3377FE1D92E1}.Instrumentation|Any CPU.ActiveCfg = Release|Any CPU {54125FC8-5C6D-4F4B-92B8-3377FE1D92E1}.Instrumentation|Any CPU.Build.0 = Release|Any CPU {54125FC8-5C6D-4F4B-92B8-3377FE1D92E1}.Instrumentation|ARM.ActiveCfg = Release|Any CPU {54125FC8-5C6D-4F4B-92B8-3377FE1D92E1}.Instrumentation|ARM.Build.0 = Release|Any CPU {54125FC8-5C6D-4F4B-92B8-3377FE1D92E1}.Instrumentation|Mixed Platforms.ActiveCfg = Release|Any CPU {54125FC8-5C6D-4F4B-92B8-3377FE1D92E1}.Instrumentation|Mixed Platforms.Build.0 = Release|Any CPU {54125FC8-5C6D-4F4B-92B8-3377FE1D92E1}.Instrumentation|Win32.ActiveCfg = Release|Any CPU {54125FC8-5C6D-4F4B-92B8-3377FE1D92E1}.Instrumentation|Win32.Build.0 = Release|Any CPU {54125FC8-5C6D-4F4B-92B8-3377FE1D92E1}.Instrumentation|x64.ActiveCfg = Release|Any CPU {54125FC8-5C6D-4F4B-92B8-3377FE1D92E1}.Instrumentation|x64.Build.0 = Release|Any CPU {54125FC8-5C6D-4F4B-92B8-3377FE1D92E1}.Release|Any CPU.ActiveCfg = Release|Any CPU {54125FC8-5C6D-4F4B-92B8-3377FE1D92E1}.Release|Any CPU.Build.0 = Release|Any CPU {54125FC8-5C6D-4F4B-92B8-3377FE1D92E1}.Release|ARM.ActiveCfg = Release|Any CPU {54125FC8-5C6D-4F4B-92B8-3377FE1D92E1}.Release|ARM.Build.0 = Release|Any CPU {54125FC8-5C6D-4F4B-92B8-3377FE1D92E1}.Release|Mixed Platforms.ActiveCfg = Release|Any CPU {54125FC8-5C6D-4F4B-92B8-3377FE1D92E1}.Release|Mixed Platforms.Build.0 = Release|Any CPU {54125FC8-5C6D-4F4B-92B8-3377FE1D92E1}.Release|Win32.ActiveCfg = Release|Any CPU {54125FC8-5C6D-4F4B-92B8-3377FE1D92E1}.Release|Win32.Build.0 = Release|Any CPU {54125FC8-5C6D-4F4B-92B8-3377FE1D92E1}.Release|x64.ActiveCfg = Release|Any CPU {54125FC8-5C6D-4F4B-92B8-3377FE1D92E1}.Release|x64.Build.0 = Release|Any CPU {A4CB8DA8-AB1A-4977-B1C5-9AE27EBB6FC7}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {A4CB8DA8-AB1A-4977-B1C5-9AE27EBB6FC7}.Debug|Any CPU.Build.0 = Debug|Any CPU {A4CB8DA8-AB1A-4977-B1C5-9AE27EBB6FC7}.Debug|ARM.ActiveCfg = Debug|Any CPU {A4CB8DA8-AB1A-4977-B1C5-9AE27EBB6FC7}.Debug|ARM.Build.0 = Debug|Any CPU {A4CB8DA8-AB1A-4977-B1C5-9AE27EBB6FC7}.Debug|Mixed Platforms.ActiveCfg = Debug|Any CPU {A4CB8DA8-AB1A-4977-B1C5-9AE27EBB6FC7}.Debug|Mixed Platforms.Build.0 = Debug|Any CPU {A4CB8DA8-AB1A-4977-B1C5-9AE27EBB6FC7}.Debug|Win32.ActiveCfg = Debug|Any CPU {A4CB8DA8-AB1A-4977-B1C5-9AE27EBB6FC7}.Debug|Win32.Build.0 = Debug|Any CPU {A4CB8DA8-AB1A-4977-B1C5-9AE27EBB6FC7}.Debug|x64.ActiveCfg = Debug|Any CPU {A4CB8DA8-AB1A-4977-B1C5-9AE27EBB6FC7}.Debug|x64.Build.0 = Debug|Any CPU {A4CB8DA8-AB1A-4977-B1C5-9AE27EBB6FC7}.Instrumentation|Any CPU.ActiveCfg = Instrumentation|Any CPU {A4CB8DA8-AB1A-4977-B1C5-9AE27EBB6FC7}.Instrumentation|Any CPU.Build.0 = Instrumentation|Any CPU {A4CB8DA8-AB1A-4977-B1C5-9AE27EBB6FC7}.Instrumentation|ARM.ActiveCfg = Instrumentation|Any CPU {A4CB8DA8-AB1A-4977-B1C5-9AE27EBB6FC7}.Instrumentation|ARM.Build.0 = Instrumentation|Any CPU {A4CB8DA8-AB1A-4977-B1C5-9AE27EBB6FC7}.Instrumentation|Mixed Platforms.ActiveCfg = Instrumentation|Any CPU {A4CB8DA8-AB1A-4977-B1C5-9AE27EBB6FC7}.Instrumentation|Mixed Platforms.Build.0 = Instrumentation|Any CPU {A4CB8DA8-AB1A-4977-B1C5-9AE27EBB6FC7}.Instrumentation|Win32.ActiveCfg = Instrumentation|Any CPU {A4CB8DA8-AB1A-4977-B1C5-9AE27EBB6FC7}.Instrumentation|Win32.Build.0 = Instrumentation|Any CPU {A4CB8DA8-AB1A-4977-B1C5-9AE27EBB6FC7}.Instrumentation|x64.ActiveCfg = Instrumentation|Any CPU {A4CB8DA8-AB1A-4977-B1C5-9AE27EBB6FC7}.Instrumentation|x64.Build.0 = Instrumentation|Any CPU {A4CB8DA8-AB1A-4977-B1C5-9AE27EBB6FC7}.Release|Any CPU.ActiveCfg = Release|Any CPU {A4CB8DA8-AB1A-4977-B1C5-9AE27EBB6FC7}.Release|Any CPU.Build.0 = Release|Any CPU {A4CB8DA8-AB1A-4977-B1C5-9AE27EBB6FC7}.Release|ARM.ActiveCfg = Release|Any CPU {A4CB8DA8-AB1A-4977-B1C5-9AE27EBB6FC7}.Release|ARM.Build.0 = Release|Any CPU {A4CB8DA8-AB1A-4977-B1C5-9AE27EBB6FC7}.Release|Mixed Platforms.ActiveCfg = Release|Any CPU {A4CB8DA8-AB1A-4977-B1C5-9AE27EBB6FC7}.Release|Mixed Platforms.Build.0 = Release|Any CPU {A4CB8DA8-AB1A-4977-B1C5-9AE27EBB6FC7}.Release|Win32.ActiveCfg = Release|Any CPU {A4CB8DA8-AB1A-4977-B1C5-9AE27EBB6FC7}.Release|Win32.Build.0 = Release|Any CPU {A4CB8DA8-AB1A-4977-B1C5-9AE27EBB6FC7}.Release|x64.ActiveCfg = Release|Any CPU {A4CB8DA8-AB1A-4977-B1C5-9AE27EBB6FC7}.Release|x64.Build.0 = Release|Any CPU {37193A86-BA04-4A3E-9DF8-656DF455E952}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {37193A86-BA04-4A3E-9DF8-656DF455E952}.Debug|Any CPU.Build.0 = Debug|Any CPU {37193A86-BA04-4A3E-9DF8-656DF455E952}.Debug|ARM.ActiveCfg = Debug|Any CPU {37193A86-BA04-4A3E-9DF8-656DF455E952}.Debug|ARM.Build.0 = Debug|Any CPU {37193A86-BA04-4A3E-9DF8-656DF455E952}.Debug|Mixed Platforms.ActiveCfg = Debug|Any CPU {37193A86-BA04-4A3E-9DF8-656DF455E952}.Debug|Mixed Platforms.Build.0 = Debug|Any CPU {37193A86-BA04-4A3E-9DF8-656DF455E952}.Debug|Win32.ActiveCfg = Debug|Any CPU {37193A86-BA04-4A3E-9DF8-656DF455E952}.Debug|Win32.Build.0 = Debug|Any CPU {37193A86-BA04-4A3E-9DF8-656DF455E952}.Debug|x64.ActiveCfg = Debug|Any CPU {37193A86-BA04-4A3E-9DF8-656DF455E952}.Debug|x64.Build.0 = Debug|Any CPU {37193A86-BA04-4A3E-9DF8-656DF455E952}.Instrumentation|Any CPU.ActiveCfg = Instrumentation|Any CPU {37193A86-BA04-4A3E-9DF8-656DF455E952}.Instrumentation|Any CPU.Build.0 = Instrumentation|Any CPU {37193A86-BA04-4A3E-9DF8-656DF455E952}.Instrumentation|ARM.ActiveCfg = Instrumentation|Any CPU {37193A86-BA04-4A3E-9DF8-656DF455E952}.Instrumentation|ARM.Build.0 = Instrumentation|Any CPU {37193A86-BA04-4A3E-9DF8-656DF455E952}.Instrumentation|Mixed Platforms.ActiveCfg = Instrumentation|Any CPU {37193A86-BA04-4A3E-9DF8-656DF455E952}.Instrumentation|Mixed Platforms.Build.0 = Instrumentation|Any CPU {37193A86-BA04-4A3E-9DF8-656DF455E952}.Instrumentation|Win32.ActiveCfg = Instrumentation|Any CPU {37193A86-BA04-4A3E-9DF8-656DF455E952}.Instrumentation|Win32.Build.0 = Instrumentation|Any CPU {37193A86-BA04-4A3E-9DF8-656DF455E952}.Instrumentation|x64.ActiveCfg = Instrumentation|Any CPU {37193A86-BA04-4A3E-9DF8-656DF455E952}.Instrumentation|x64.Build.0 = Instrumentation|Any CPU {37193A86-BA04-4A3E-9DF8-656DF455E952}.Release|Any CPU.ActiveCfg = Release|Any CPU {37193A86-BA04-4A3E-9DF8-656DF455E952}.Release|Any CPU.Build.0 = Release|Any CPU {37193A86-BA04-4A3E-9DF8-656DF455E952}.Release|ARM.ActiveCfg = Release|Any CPU {37193A86-BA04-4A3E-9DF8-656DF455E952}.Release|ARM.Build.0 = Release|Any CPU {37193A86-BA04-4A3E-9DF8-656DF455E952}.Release|Mixed Platforms.ActiveCfg = Release|Any CPU {37193A86-BA04-4A3E-9DF8-656DF455E952}.Release|Mixed Platforms.Build.0 = Release|Any CPU {37193A86-BA04-4A3E-9DF8-656DF455E952}.Release|Win32.ActiveCfg = Release|Any CPU {37193A86-BA04-4A3E-9DF8-656DF455E952}.Release|Win32.Build.0 = Release|Any CPU {37193A86-BA04-4A3E-9DF8-656DF455E952}.Release|x64.ActiveCfg = Release|Any CPU {37193A86-BA04-4A3E-9DF8-656DF455E952}.Release|x64.Build.0 = Release|Any CPU {0F0DC8C5-349B-453D-94F2-123205E3EADD}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {0F0DC8C5-349B-453D-94F2-123205E3EADD}.Debug|Any CPU.Build.0 = Debug|Any CPU {0F0DC8C5-349B-453D-94F2-123205E3EADD}.Debug|ARM.ActiveCfg = Debug|Any CPU {0F0DC8C5-349B-453D-94F2-123205E3EADD}.Debug|ARM.Build.0 = Debug|Any CPU {0F0DC8C5-349B-453D-94F2-123205E3EADD}.Debug|Mixed Platforms.ActiveCfg = Debug|Any CPU {0F0DC8C5-349B-453D-94F2-123205E3EADD}.Debug|Mixed Platforms.Build.0 = Debug|Any CPU {0F0DC8C5-349B-453D-94F2-123205E3EADD}.Debug|Win32.ActiveCfg = Debug|Any CPU {0F0DC8C5-349B-453D-94F2-123205E3EADD}.Debug|Win32.Build.0 = Debug|Any CPU {0F0DC8C5-349B-453D-94F2-123205E3EADD}.Debug|x64.ActiveCfg = Debug|Any CPU {0F0DC8C5-349B-453D-94F2-123205E3EADD}.Debug|x64.Build.0 = Debug|Any CPU {0F0DC8C5-349B-453D-94F2-123205E3EADD}.Instrumentation|Any CPU.ActiveCfg = Release|Any CPU {0F0DC8C5-349B-453D-94F2-123205E3EADD}.Instrumentation|Any CPU.Build.0 = Release|Any CPU {0F0DC8C5-349B-453D-94F2-123205E3EADD}.Instrumentation|ARM.ActiveCfg = Release|Any CPU {0F0DC8C5-349B-453D-94F2-123205E3EADD}.Instrumentation|ARM.Build.0 = Release|Any CPU {0F0DC8C5-349B-453D-94F2-123205E3EADD}.Instrumentation|Mixed Platforms.ActiveCfg = Release|Any CPU {0F0DC8C5-349B-453D-94F2-123205E3EADD}.Instrumentation|Mixed Platforms.Build.0 = Release|Any CPU {0F0DC8C5-349B-453D-94F2-123205E3EADD}.Instrumentation|Win32.ActiveCfg = Release|Any CPU {0F0DC8C5-349B-453D-94F2-123205E3EADD}.Instrumentation|Win32.Build.0 = Release|Any CPU {0F0DC8C5-349B-453D-94F2-123205E3EADD}.Instrumentation|x64.ActiveCfg = Release|Any CPU {0F0DC8C5-349B-453D-94F2-123205E3EADD}.Instrumentation|x64.Build.0 = Release|Any CPU {0F0DC8C5-349B-453D-94F2-123205E3EADD}.Release|Any CPU.ActiveCfg = Release|Any CPU {0F0DC8C5-349B-453D-94F2-123205E3EADD}.Release|Any CPU.Build.0 = Release|Any CPU {0F0DC8C5-349B-453D-94F2-123205E3EADD}.Release|ARM.ActiveCfg = Release|Any CPU {0F0DC8C5-349B-453D-94F2-123205E3EADD}.Release|ARM.Build.0 = Release|Any CPU {0F0DC8C5-349B-453D-94F2-123205E3EADD}.Release|Mixed Platforms.ActiveCfg = Release|Any CPU {0F0DC8C5-349B-453D-94F2-123205E3EADD}.Release|Mixed Platforms.Build.0 = Release|Any CPU {0F0DC8C5-349B-453D-94F2-123205E3EADD}.Release|Win32.ActiveCfg = Release|Any CPU {0F0DC8C5-349B-453D-94F2-123205E3EADD}.Release|Win32.Build.0 = Release|Any CPU {0F0DC8C5-349B-453D-94F2-123205E3EADD}.Release|x64.ActiveCfg = Release|Any CPU {0F0DC8C5-349B-453D-94F2-123205E3EADD}.Release|x64.Build.0 = Release|Any CPU {6194144A-F8B1-4525-829F-061DF4A5645A}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {6194144A-F8B1-4525-829F-061DF4A5645A}.Debug|Any CPU.Build.0 = Debug|Any CPU {6194144A-F8B1-4525-829F-061DF4A5645A}.Debug|ARM.ActiveCfg = Debug|Any CPU {6194144A-F8B1-4525-829F-061DF4A5645A}.Debug|ARM.Build.0 = Debug|Any CPU {6194144A-F8B1-4525-829F-061DF4A5645A}.Debug|Mixed Platforms.ActiveCfg = Debug|Any CPU {6194144A-F8B1-4525-829F-061DF4A5645A}.Debug|Mixed Platforms.Build.0 = Debug|Any CPU {6194144A-F8B1-4525-829F-061DF4A5645A}.Debug|Win32.ActiveCfg = Debug|Any CPU {6194144A-F8B1-4525-829F-061DF4A5645A}.Debug|Win32.Build.0 = Debug|Any CPU {6194144A-F8B1-4525-829F-061DF4A5645A}.Debug|x64.ActiveCfg = Debug|Any CPU {6194144A-F8B1-4525-829F-061DF4A5645A}.Debug|x64.Build.0 = Debug|Any CPU {6194144A-F8B1-4525-829F-061DF4A5645A}.Instrumentation|Any CPU.ActiveCfg = Release|Any CPU {6194144A-F8B1-4525-829F-061DF4A5645A}.Instrumentation|Any CPU.Build.0 = Release|Any CPU {6194144A-F8B1-4525-829F-061DF4A5645A}.Instrumentation|ARM.ActiveCfg = Release|Any CPU {6194144A-F8B1-4525-829F-061DF4A5645A}.Instrumentation|ARM.Build.0 = Release|Any CPU {6194144A-F8B1-4525-829F-061DF4A5645A}.Instrumentation|Mixed Platforms.ActiveCfg = Release|Any CPU {6194144A-F8B1-4525-829F-061DF4A5645A}.Instrumentation|Mixed Platforms.Build.0 = Release|Any CPU {6194144A-F8B1-4525-829F-061DF4A5645A}.Instrumentation|Win32.ActiveCfg = Release|Any CPU {6194144A-F8B1-4525-829F-061DF4A5645A}.Instrumentation|Win32.Build.0 = Release|Any CPU {6194144A-F8B1-4525-829F-061DF4A5645A}.Instrumentation|x64.ActiveCfg = Release|Any CPU {6194144A-F8B1-4525-829F-061DF4A5645A}.Instrumentation|x64.Build.0 = Release|Any CPU {6194144A-F8B1-4525-829F-061DF4A5645A}.Release|Any CPU.ActiveCfg = Release|Any CPU {6194144A-F8B1-4525-829F-061DF4A5645A}.Release|Any CPU.Build.0 = Release|Any CPU {6194144A-F8B1-4525-829F-061DF4A5645A}.Release|ARM.ActiveCfg = Release|Any CPU {6194144A-F8B1-4525-829F-061DF4A5645A}.Release|ARM.Build.0 = Release|Any CPU {6194144A-F8B1-4525-829F-061DF4A5645A}.Release|Mixed Platforms.ActiveCfg = Release|Any CPU {6194144A-F8B1-4525-829F-061DF4A5645A}.Release|Mixed Platforms.Build.0 = Release|Any CPU {6194144A-F8B1-4525-829F-061DF4A5645A}.Release|Win32.ActiveCfg = Release|Any CPU {6194144A-F8B1-4525-829F-061DF4A5645A}.Release|Win32.Build.0 = Release|Any CPU {6194144A-F8B1-4525-829F-061DF4A5645A}.Release|x64.ActiveCfg = Release|Any CPU {6194144A-F8B1-4525-829F-061DF4A5645A}.Release|x64.Build.0 = Release|Any CPU {7F600371-17AB-41F2-96AB-39C8AA2389E1}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {7F600371-17AB-41F2-96AB-39C8AA2389E1}.Debug|Any CPU.Build.0 = Debug|Any CPU {7F600371-17AB-41F2-96AB-39C8AA2389E1}.Debug|ARM.ActiveCfg = Debug|Any CPU {7F600371-17AB-41F2-96AB-39C8AA2389E1}.Debug|ARM.Build.0 = Debug|Any CPU {7F600371-17AB-41F2-96AB-39C8AA2389E1}.Debug|Mixed Platforms.ActiveCfg = Debug|Any CPU {7F600371-17AB-41F2-96AB-39C8AA2389E1}.Debug|Mixed Platforms.Build.0 = Debug|Any CPU {7F600371-17AB-41F2-96AB-39C8AA2389E1}.Debug|Win32.ActiveCfg = Debug|Any CPU {7F600371-17AB-41F2-96AB-39C8AA2389E1}.Debug|Win32.Build.0 = Debug|Any CPU {7F600371-17AB-41F2-96AB-39C8AA2389E1}.Debug|x64.ActiveCfg = Debug|Any CPU {7F600371-17AB-41F2-96AB-39C8AA2389E1}.Debug|x64.Build.0 = Debug|Any CPU {7F600371-17AB-41F2-96AB-39C8AA2389E1}.Instrumentation|Any CPU.ActiveCfg = Release|Any CPU {7F600371-17AB-41F2-96AB-39C8AA2389E1}.Instrumentation|Any CPU.Build.0 = Release|Any CPU {7F600371-17AB-41F2-96AB-39C8AA2389E1}.Instrumentation|ARM.ActiveCfg = Release|Any CPU {7F600371-17AB-41F2-96AB-39C8AA2389E1}.Instrumentation|ARM.Build.0 = Release|Any CPU {7F600371-17AB-41F2-96AB-39C8AA2389E1}.Instrumentation|Mixed Platforms.ActiveCfg = Release|Any CPU {7F600371-17AB-41F2-96AB-39C8AA2389E1}.Instrumentation|Mixed Platforms.Build.0 = Release|Any CPU {7F600371-17AB-41F2-96AB-39C8AA2389E1}.Instrumentation|Win32.ActiveCfg = Release|Any CPU {7F600371-17AB-41F2-96AB-39C8AA2389E1}.Instrumentation|Win32.Build.0 = Release|Any CPU {7F600371-17AB-41F2-96AB-39C8AA2389E1}.Instrumentation|x64.ActiveCfg = Release|Any CPU {7F600371-17AB-41F2-96AB-39C8AA2389E1}.Instrumentation|x64.Build.0 = Release|Any CPU {7F600371-17AB-41F2-96AB-39C8AA2389E1}.Release|Any CPU.ActiveCfg = Release|Any CPU {7F600371-17AB-41F2-96AB-39C8AA2389E1}.Release|Any CPU.Build.0 = Release|Any CPU {7F600371-17AB-41F2-96AB-39C8AA2389E1}.Release|ARM.ActiveCfg = Release|Any CPU {7F600371-17AB-41F2-96AB-39C8AA2389E1}.Release|ARM.Build.0 = Release|Any CPU {7F600371-17AB-41F2-96AB-39C8AA2389E1}.Release|Mixed Platforms.ActiveCfg = Release|Any CPU {7F600371-17AB-41F2-96AB-39C8AA2389E1}.Release|Mixed Platforms.Build.0 = Release|Any CPU {7F600371-17AB-41F2-96AB-39C8AA2389E1}.Release|Win32.ActiveCfg = Release|Any CPU {7F600371-17AB-41F2-96AB-39C8AA2389E1}.Release|Win32.Build.0 = Release|Any CPU {7F600371-17AB-41F2-96AB-39C8AA2389E1}.Release|x64.ActiveCfg = Release|Any CPU {7F600371-17AB-41F2-96AB-39C8AA2389E1}.Release|x64.Build.0 = Release|Any CPU {65E36DF8-5CB8-4582-851E-F5381AE4A1A7}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {65E36DF8-5CB8-4582-851E-F5381AE4A1A7}.Debug|Any CPU.Build.0 = Debug|Any CPU {65E36DF8-5CB8-4582-851E-F5381AE4A1A7}.Debug|ARM.ActiveCfg = Debug|Any CPU {65E36DF8-5CB8-4582-851E-F5381AE4A1A7}.Debug|ARM.Build.0 = Debug|Any CPU {65E36DF8-5CB8-4582-851E-F5381AE4A1A7}.Debug|Mixed Platforms.ActiveCfg = Debug|Any CPU {65E36DF8-5CB8-4582-851E-F5381AE4A1A7}.Debug|Mixed Platforms.Build.0 = Debug|Any CPU {65E36DF8-5CB8-4582-851E-F5381AE4A1A7}.Debug|Win32.ActiveCfg = Debug|Any CPU {65E36DF8-5CB8-4582-851E-F5381AE4A1A7}.Debug|Win32.Build.0 = Debug|Any CPU {65E36DF8-5CB8-4582-851E-F5381AE4A1A7}.Debug|x64.ActiveCfg = Debug|Any CPU {65E36DF8-5CB8-4582-851E-F5381AE4A1A7}.Debug|x64.Build.0 = Debug|Any CPU {65E36DF8-5CB8-4582-851E-F5381AE4A1A7}.Instrumentation|Any CPU.ActiveCfg = Release|Any CPU {65E36DF8-5CB8-4582-851E-F5381AE4A1A7}.Instrumentation|Any CPU.Build.0 = Release|Any CPU {65E36DF8-5CB8-4582-851E-F5381AE4A1A7}.Instrumentation|ARM.ActiveCfg = Release|Any CPU {65E36DF8-5CB8-4582-851E-F5381AE4A1A7}.Instrumentation|ARM.Build.0 = Release|Any CPU {65E36DF8-5CB8-4582-851E-F5381AE4A1A7}.Instrumentation|Mixed Platforms.ActiveCfg = Release|Any CPU {65E36DF8-5CB8-4582-851E-F5381AE4A1A7}.Instrumentation|Mixed Platforms.Build.0 = Release|Any CPU {65E36DF8-5CB8-4582-851E-F5381AE4A1A7}.Instrumentation|Win32.ActiveCfg = Release|Any CPU {65E36DF8-5CB8-4582-851E-F5381AE4A1A7}.Instrumentation|Win32.Build.0 = Release|Any CPU {65E36DF8-5CB8-4582-851E-F5381AE4A1A7}.Instrumentation|x64.ActiveCfg = Release|Any CPU {65E36DF8-5CB8-4582-851E-F5381AE4A1A7}.Instrumentation|x64.Build.0 = Release|Any CPU {65E36DF8-5CB8-4582-851E-F5381AE4A1A7}.Release|Any CPU.ActiveCfg = Release|Any CPU {65E36DF8-5CB8-4582-851E-F5381AE4A1A7}.Release|Any CPU.Build.0 = Release|Any CPU {65E36DF8-5CB8-4582-851E-F5381AE4A1A7}.Release|ARM.ActiveCfg = Release|Any CPU {65E36DF8-5CB8-4582-851E-F5381AE4A1A7}.Release|ARM.Build.0 = Release|Any CPU {65E36DF8-5CB8-4582-851E-F5381AE4A1A7}.Release|Mixed Platforms.ActiveCfg = Release|Any CPU {65E36DF8-5CB8-4582-851E-F5381AE4A1A7}.Release|Mixed Platforms.Build.0 = Release|Any CPU {65E36DF8-5CB8-4582-851E-F5381AE4A1A7}.Release|Win32.ActiveCfg = Release|Any CPU {65E36DF8-5CB8-4582-851E-F5381AE4A1A7}.Release|Win32.Build.0 = Release|Any CPU {65E36DF8-5CB8-4582-851E-F5381AE4A1A7}.Release|x64.ActiveCfg = Release|Any CPU {65E36DF8-5CB8-4582-851E-F5381AE4A1A7}.Release|x64.Build.0 = Release|Any CPU {C183991C-1F27-4665-A884-FD977D2AD359}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {C183991C-1F27-4665-A884-FD977D2AD359}.Debug|Any CPU.Build.0 = Debug|Any CPU {C183991C-1F27-4665-A884-FD977D2AD359}.Debug|ARM.ActiveCfg = Debug|Any CPU {C183991C-1F27-4665-A884-FD977D2AD359}.Debug|ARM.Build.0 = Debug|Any CPU {C183991C-1F27-4665-A884-FD977D2AD359}.Debug|Mixed Platforms.ActiveCfg = Debug|Any CPU {C183991C-1F27-4665-A884-FD977D2AD359}.Debug|Mixed Platforms.Build.0 = Debug|Any CPU {C183991C-1F27-4665-A884-FD977D2AD359}.Debug|Win32.ActiveCfg = Debug|Any CPU {C183991C-1F27-4665-A884-FD977D2AD359}.Debug|Win32.Build.0 = Debug|Any CPU {C183991C-1F27-4665-A884-FD977D2AD359}.Debug|x64.ActiveCfg = Debug|Any CPU {C183991C-1F27-4665-A884-FD977D2AD359}.Debug|x64.Build.0 = Debug|Any CPU {C183991C-1F27-4665-A884-FD977D2AD359}.Instrumentation|Any CPU.ActiveCfg = Release|Any CPU {C183991C-1F27-4665-A884-FD977D2AD359}.Instrumentation|Any CPU.Build.0 = Release|Any CPU {C183991C-1F27-4665-A884-FD977D2AD359}.Instrumentation|ARM.ActiveCfg = Release|Any CPU {C183991C-1F27-4665-A884-FD977D2AD359}.Instrumentation|ARM.Build.0 = Release|Any CPU {C183991C-1F27-4665-A884-FD977D2AD359}.Instrumentation|Mixed Platforms.ActiveCfg = Release|Any CPU {C183991C-1F27-4665-A884-FD977D2AD359}.Instrumentation|Mixed Platforms.Build.0 = Release|Any CPU {C183991C-1F27-4665-A884-FD977D2AD359}.Instrumentation|Win32.ActiveCfg = Release|Any CPU {C183991C-1F27-4665-A884-FD977D2AD359}.Instrumentation|Win32.Build.0 = Release|Any CPU {C183991C-1F27-4665-A884-FD977D2AD359}.Instrumentation|x64.ActiveCfg = Release|Any CPU {C183991C-1F27-4665-A884-FD977D2AD359}.Instrumentation|x64.Build.0 = Release|Any CPU {C183991C-1F27-4665-A884-FD977D2AD359}.Release|Any CPU.ActiveCfg = Release|Any CPU {C183991C-1F27-4665-A884-FD977D2AD359}.Release|Any CPU.Build.0 = Release|Any CPU {C183991C-1F27-4665-A884-FD977D2AD359}.Release|ARM.ActiveCfg = Release|Any CPU {C183991C-1F27-4665-A884-FD977D2AD359}.Release|ARM.Build.0 = Release|Any CPU {C183991C-1F27-4665-A884-FD977D2AD359}.Release|Mixed Platforms.ActiveCfg = Release|Any CPU {C183991C-1F27-4665-A884-FD977D2AD359}.Release|Mixed Platforms.Build.0 = Release|Any CPU {C183991C-1F27-4665-A884-FD977D2AD359}.Release|Win32.ActiveCfg = Release|Any CPU {C183991C-1F27-4665-A884-FD977D2AD359}.Release|Win32.Build.0 = Release|Any CPU {C183991C-1F27-4665-A884-FD977D2AD359}.Release|x64.ActiveCfg = Release|Any CPU {C183991C-1F27-4665-A884-FD977D2AD359}.Release|x64.Build.0 = Release|Any CPU {E4C618AF-1785-472E-A070-8068E20582EB}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {E4C618AF-1785-472E-A070-8068E20582EB}.Debug|Any CPU.Build.0 = Debug|Any CPU {E4C618AF-1785-472E-A070-8068E20582EB}.Debug|ARM.ActiveCfg = Debug|Any CPU {E4C618AF-1785-472E-A070-8068E20582EB}.Debug|ARM.Build.0 = Debug|Any CPU {E4C618AF-1785-472E-A070-8068E20582EB}.Debug|Mixed Platforms.ActiveCfg = Debug|Any CPU {E4C618AF-1785-472E-A070-8068E20582EB}.Debug|Mixed Platforms.Build.0 = Debug|Any CPU {E4C618AF-1785-472E-A070-8068E20582EB}.Debug|Win32.ActiveCfg = Debug|Any CPU {E4C618AF-1785-472E-A070-8068E20582EB}.Debug|Win32.Build.0 = Debug|Any CPU {E4C618AF-1785-472E-A070-8068E20582EB}.Debug|x64.ActiveCfg = Debug|Any CPU {E4C618AF-1785-472E-A070-8068E20582EB}.Debug|x64.Build.0 = Debug|Any CPU {E4C618AF-1785-472E-A070-8068E20582EB}.Instrumentation|Any CPU.ActiveCfg = Instrumentation|Any CPU {E4C618AF-1785-472E-A070-8068E20582EB}.Instrumentation|Any CPU.Build.0 = Instrumentation|Any CPU {E4C618AF-1785-472E-A070-8068E20582EB}.Instrumentation|ARM.ActiveCfg = Instrumentation|Any CPU {E4C618AF-1785-472E-A070-8068E20582EB}.Instrumentation|ARM.Build.0 = Instrumentation|Any CPU {E4C618AF-1785-472E-A070-8068E20582EB}.Instrumentation|Mixed Platforms.ActiveCfg = Instrumentation|Any CPU {E4C618AF-1785-472E-A070-8068E20582EB}.Instrumentation|Mixed Platforms.Build.0 = Instrumentation|Any CPU {E4C618AF-1785-472E-A070-8068E20582EB}.Instrumentation|Win32.ActiveCfg = Instrumentation|Any CPU {E4C618AF-1785-472E-A070-8068E20582EB}.Instrumentation|Win32.Build.0 = Instrumentation|Any CPU {E4C618AF-1785-472E-A070-8068E20582EB}.Instrumentation|x64.ActiveCfg = Instrumentation|Any CPU {E4C618AF-1785-472E-A070-8068E20582EB}.Instrumentation|x64.Build.0 = Instrumentation|Any CPU {E4C618AF-1785-472E-A070-8068E20582EB}.Release|Any CPU.ActiveCfg = Release|Any CPU {E4C618AF-1785-472E-A070-8068E20582EB}.Release|Any CPU.Build.0 = Release|Any CPU {E4C618AF-1785-472E-A070-8068E20582EB}.Release|ARM.ActiveCfg = Release|Any CPU {E4C618AF-1785-472E-A070-8068E20582EB}.Release|ARM.Build.0 = Release|Any CPU {E4C618AF-1785-472E-A070-8068E20582EB}.Release|Mixed Platforms.ActiveCfg = Release|Any CPU {E4C618AF-1785-472E-A070-8068E20582EB}.Release|Mixed Platforms.Build.0 = Release|Any CPU {E4C618AF-1785-472E-A070-8068E20582EB}.Release|Win32.ActiveCfg = Release|Any CPU {E4C618AF-1785-472E-A070-8068E20582EB}.Release|Win32.Build.0 = Release|Any CPU {E4C618AF-1785-472E-A070-8068E20582EB}.Release|x64.ActiveCfg = Release|Any CPU {E4C618AF-1785-472E-A070-8068E20582EB}.Release|x64.Build.0 = Release|Any CPU {C3BFAFAD-A6C6-471D-A059-B3CB7E57A4AB}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {C3BFAFAD-A6C6-471D-A059-B3CB7E57A4AB}.Debug|Any CPU.Build.0 = Debug|Any CPU {C3BFAFAD-A6C6-471D-A059-B3CB7E57A4AB}.Debug|ARM.ActiveCfg = Debug|Any CPU {C3BFAFAD-A6C6-471D-A059-B3CB7E57A4AB}.Debug|ARM.Build.0 = Debug|Any CPU {C3BFAFAD-A6C6-471D-A059-B3CB7E57A4AB}.Debug|Mixed Platforms.ActiveCfg = Debug|Any CPU {C3BFAFAD-A6C6-471D-A059-B3CB7E57A4AB}.Debug|Mixed Platforms.Build.0 = Debug|Any CPU {C3BFAFAD-A6C6-471D-A059-B3CB7E57A4AB}.Debug|Win32.ActiveCfg = Debug|Any CPU {C3BFAFAD-A6C6-471D-A059-B3CB7E57A4AB}.Debug|Win32.Build.0 = Debug|Any CPU {C3BFAFAD-A6C6-471D-A059-B3CB7E57A4AB}.Debug|x64.ActiveCfg = Debug|Any CPU {C3BFAFAD-A6C6-471D-A059-B3CB7E57A4AB}.Debug|x64.Build.0 = Debug|Any CPU {C3BFAFAD-A6C6-471D-A059-B3CB7E57A4AB}.Instrumentation|Any CPU.ActiveCfg = Instrumentation|Any CPU {C3BFAFAD-A6C6-471D-A059-B3CB7E57A4AB}.Instrumentation|Any CPU.Build.0 = Instrumentation|Any CPU {C3BFAFAD-A6C6-471D-A059-B3CB7E57A4AB}.Instrumentation|ARM.ActiveCfg = Instrumentation|Any CPU {C3BFAFAD-A6C6-471D-A059-B3CB7E57A4AB}.Instrumentation|ARM.Build.0 = Instrumentation|Any CPU {C3BFAFAD-A6C6-471D-A059-B3CB7E57A4AB}.Instrumentation|Mixed Platforms.ActiveCfg = Instrumentation|Any CPU {C3BFAFAD-A6C6-471D-A059-B3CB7E57A4AB}.Instrumentation|Mixed Platforms.Build.0 = Instrumentation|Any CPU {C3BFAFAD-A6C6-471D-A059-B3CB7E57A4AB}.Instrumentation|Win32.ActiveCfg = Instrumentation|Any CPU {C3BFAFAD-A6C6-471D-A059-B3CB7E57A4AB}.Instrumentation|Win32.Build.0 = Instrumentation|Any CPU {C3BFAFAD-A6C6-471D-A059-B3CB7E57A4AB}.Instrumentation|x64.ActiveCfg = Instrumentation|Any CPU {C3BFAFAD-A6C6-471D-A059-B3CB7E57A4AB}.Instrumentation|x64.Build.0 = Instrumentation|Any CPU {C3BFAFAD-A6C6-471D-A059-B3CB7E57A4AB}.Release|Any CPU.ActiveCfg = Release|Any CPU {C3BFAFAD-A6C6-471D-A059-B3CB7E57A4AB}.Release|Any CPU.Build.0 = Release|Any CPU {C3BFAFAD-A6C6-471D-A059-B3CB7E57A4AB}.Release|ARM.ActiveCfg = Release|Any CPU {C3BFAFAD-A6C6-471D-A059-B3CB7E57A4AB}.Release|ARM.Build.0 = Release|Any CPU {C3BFAFAD-A6C6-471D-A059-B3CB7E57A4AB}.Release|Mixed Platforms.ActiveCfg = Release|Any CPU {C3BFAFAD-A6C6-471D-A059-B3CB7E57A4AB}.Release|Mixed Platforms.Build.0 = Release|Any CPU {C3BFAFAD-A6C6-471D-A059-B3CB7E57A4AB}.Release|Win32.ActiveCfg = Release|Any CPU {C3BFAFAD-A6C6-471D-A059-B3CB7E57A4AB}.Release|Win32.Build.0 = Release|Any CPU {C3BFAFAD-A6C6-471D-A059-B3CB7E57A4AB}.Release|x64.ActiveCfg = Release|Any CPU {C3BFAFAD-A6C6-471D-A059-B3CB7E57A4AB}.Release|x64.Build.0 = Release|Any CPU {B8FE271A-CD41-435E-8766-4DB7609C1007}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {B8FE271A-CD41-435E-8766-4DB7609C1007}.Debug|Any CPU.Build.0 = Debug|Any CPU {B8FE271A-CD41-435E-8766-4DB7609C1007}.Debug|ARM.ActiveCfg = Debug|Any CPU {B8FE271A-CD41-435E-8766-4DB7609C1007}.Debug|ARM.Build.0 = Debug|Any CPU {B8FE271A-CD41-435E-8766-4DB7609C1007}.Debug|Mixed Platforms.ActiveCfg = Debug|Any CPU {B8FE271A-CD41-435E-8766-4DB7609C1007}.Debug|Mixed Platforms.Build.0 = Debug|Any CPU {B8FE271A-CD41-435E-8766-4DB7609C1007}.Debug|Win32.ActiveCfg = Debug|Any CPU {B8FE271A-CD41-435E-8766-4DB7609C1007}.Debug|Win32.Build.0 = Debug|Any CPU {B8FE271A-CD41-435E-8766-4DB7609C1007}.Debug|x64.ActiveCfg = Debug|Any CPU {B8FE271A-CD41-435E-8766-4DB7609C1007}.Debug|x64.Build.0 = Debug|Any CPU {B8FE271A-CD41-435E-8766-4DB7609C1007}.Instrumentation|Any CPU.ActiveCfg = Release|Any CPU {B8FE271A-CD41-435E-8766-4DB7609C1007}.Instrumentation|Any CPU.Build.0 = Release|Any CPU {B8FE271A-CD41-435E-8766-4DB7609C1007}.Instrumentation|ARM.ActiveCfg = Release|Any CPU {B8FE271A-CD41-435E-8766-4DB7609C1007}.Instrumentation|ARM.Build.0 = Release|Any CPU {B8FE271A-CD41-435E-8766-4DB7609C1007}.Instrumentation|Mixed Platforms.ActiveCfg = Release|Any CPU {B8FE271A-CD41-435E-8766-4DB7609C1007}.Instrumentation|Mixed Platforms.Build.0 = Release|Any CPU {B8FE271A-CD41-435E-8766-4DB7609C1007}.Instrumentation|Win32.ActiveCfg = Release|Any CPU {B8FE271A-CD41-435E-8766-4DB7609C1007}.Instrumentation|Win32.Build.0 = Release|Any CPU {B8FE271A-CD41-435E-8766-4DB7609C1007}.Instrumentation|x64.ActiveCfg = Release|Any CPU {B8FE271A-CD41-435E-8766-4DB7609C1007}.Instrumentation|x64.Build.0 = Release|Any CPU {B8FE271A-CD41-435E-8766-4DB7609C1007}.Release|Any CPU.ActiveCfg = Release|Any CPU {B8FE271A-CD41-435E-8766-4DB7609C1007}.Release|Any CPU.Build.0 = Release|Any CPU {B8FE271A-CD41-435E-8766-4DB7609C1007}.Release|ARM.ActiveCfg = Release|Any CPU {B8FE271A-CD41-435E-8766-4DB7609C1007}.Release|ARM.Build.0 = Release|Any CPU {B8FE271A-CD41-435E-8766-4DB7609C1007}.Release|Mixed Platforms.ActiveCfg = Release|Any CPU {B8FE271A-CD41-435E-8766-4DB7609C1007}.Release|Mixed Platforms.Build.0 = Release|Any CPU {B8FE271A-CD41-435E-8766-4DB7609C1007}.Release|Win32.ActiveCfg = Release|Any CPU {B8FE271A-CD41-435E-8766-4DB7609C1007}.Release|Win32.Build.0 = Release|Any CPU {B8FE271A-CD41-435E-8766-4DB7609C1007}.Release|x64.ActiveCfg = Release|Any CPU {B8FE271A-CD41-435E-8766-4DB7609C1007}.Release|x64.Build.0 = Release|Any CPU {89EBDBB0-C81F-4611-B719-B385DF215F8D}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {89EBDBB0-C81F-4611-B719-B385DF215F8D}.Debug|Any CPU.Build.0 = Debug|Any CPU {89EBDBB0-C81F-4611-B719-B385DF215F8D}.Debug|ARM.ActiveCfg = Debug|Any CPU {89EBDBB0-C81F-4611-B719-B385DF215F8D}.Debug|ARM.Build.0 = Debug|Any CPU {89EBDBB0-C81F-4611-B719-B385DF215F8D}.Debug|Mixed Platforms.ActiveCfg = Debug|Any CPU {89EBDBB0-C81F-4611-B719-B385DF215F8D}.Debug|Mixed Platforms.Build.0 = Debug|Any CPU {89EBDBB0-C81F-4611-B719-B385DF215F8D}.Debug|Win32.ActiveCfg = Debug|Any CPU {89EBDBB0-C81F-4611-B719-B385DF215F8D}.Debug|Win32.Build.0 = Debug|Any CPU {89EBDBB0-C81F-4611-B719-B385DF215F8D}.Debug|x64.ActiveCfg = Debug|Any CPU {89EBDBB0-C81F-4611-B719-B385DF215F8D}.Debug|x64.Build.0 = Debug|Any CPU {89EBDBB0-C81F-4611-B719-B385DF215F8D}.Instrumentation|Any CPU.ActiveCfg = Release|Any CPU {89EBDBB0-C81F-4611-B719-B385DF215F8D}.Instrumentation|Any CPU.Build.0 = Release|Any CPU {89EBDBB0-C81F-4611-B719-B385DF215F8D}.Instrumentation|ARM.ActiveCfg = Release|Any CPU {89EBDBB0-C81F-4611-B719-B385DF215F8D}.Instrumentation|ARM.Build.0 = Release|Any CPU {89EBDBB0-C81F-4611-B719-B385DF215F8D}.Instrumentation|Mixed Platforms.ActiveCfg = Release|Any CPU {89EBDBB0-C81F-4611-B719-B385DF215F8D}.Instrumentation|Mixed Platforms.Build.0 = Release|Any CPU {89EBDBB0-C81F-4611-B719-B385DF215F8D}.Instrumentation|Win32.ActiveCfg = Release|Any CPU {89EBDBB0-C81F-4611-B719-B385DF215F8D}.Instrumentation|Win32.Build.0 = Release|Any CPU {89EBDBB0-C81F-4611-B719-B385DF215F8D}.Instrumentation|x64.ActiveCfg = Release|Any CPU {89EBDBB0-C81F-4611-B719-B385DF215F8D}.Instrumentation|x64.Build.0 = Release|Any CPU {89EBDBB0-C81F-4611-B719-B385DF215F8D}.Release|Any CPU.ActiveCfg = Release|Any CPU {89EBDBB0-C81F-4611-B719-B385DF215F8D}.Release|Any CPU.Build.0 = Release|Any CPU {89EBDBB0-C81F-4611-B719-B385DF215F8D}.Release|ARM.ActiveCfg = Release|Any CPU {89EBDBB0-C81F-4611-B719-B385DF215F8D}.Release|ARM.Build.0 = Release|Any CPU {89EBDBB0-C81F-4611-B719-B385DF215F8D}.Release|Mixed Platforms.ActiveCfg = Release|Any CPU {89EBDBB0-C81F-4611-B719-B385DF215F8D}.Release|Mixed Platforms.Build.0 = Release|Any CPU {89EBDBB0-C81F-4611-B719-B385DF215F8D}.Release|Win32.ActiveCfg = Release|Any CPU {89EBDBB0-C81F-4611-B719-B385DF215F8D}.Release|Win32.Build.0 = Release|Any CPU {89EBDBB0-C81F-4611-B719-B385DF215F8D}.Release|x64.ActiveCfg = Release|Any CPU {89EBDBB0-C81F-4611-B719-B385DF215F8D}.Release|x64.Build.0 = Release|Any CPU {F84C2434-C768-4295-955B-E032E3A18FC3}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {F84C2434-C768-4295-955B-E032E3A18FC3}.Debug|Any CPU.Build.0 = Debug|Any CPU {F84C2434-C768-4295-955B-E032E3A18FC3}.Debug|ARM.ActiveCfg = Debug|Any CPU {F84C2434-C768-4295-955B-E032E3A18FC3}.Debug|ARM.Build.0 = Debug|Any CPU {F84C2434-C768-4295-955B-E032E3A18FC3}.Debug|Mixed Platforms.ActiveCfg = Debug|Any CPU {F84C2434-C768-4295-955B-E032E3A18FC3}.Debug|Mixed Platforms.Build.0 = Debug|Any CPU {F84C2434-C768-4295-955B-E032E3A18FC3}.Debug|Win32.ActiveCfg = Debug|Any CPU {F84C2434-C768-4295-955B-E032E3A18FC3}.Debug|Win32.Build.0 = Debug|Any CPU {F84C2434-C768-4295-955B-E032E3A18FC3}.Debug|x64.ActiveCfg = Debug|Any CPU {F84C2434-C768-4295-955B-E032E3A18FC3}.Debug|x64.Build.0 = Debug|Any CPU {F84C2434-C768-4295-955B-E032E3A18FC3}.Instrumentation|Any CPU.ActiveCfg = Release|Any CPU {F84C2434-C768-4295-955B-E032E3A18FC3}.Instrumentation|Any CPU.Build.0 = Release|Any CPU {F84C2434-C768-4295-955B-E032E3A18FC3}.Instrumentation|ARM.ActiveCfg = Release|Any CPU {F84C2434-C768-4295-955B-E032E3A18FC3}.Instrumentation|ARM.Build.0 = Release|Any CPU {F84C2434-C768-4295-955B-E032E3A18FC3}.Instrumentation|Mixed Platforms.ActiveCfg = Release|Any CPU {F84C2434-C768-4295-955B-E032E3A18FC3}.Instrumentation|Mixed Platforms.Build.0 = Release|Any CPU {F84C2434-C768-4295-955B-E032E3A18FC3}.Instrumentation|Win32.ActiveCfg = Release|Any CPU {F84C2434-C768-4295-955B-E032E3A18FC3}.Instrumentation|Win32.Build.0 = Release|Any CPU {F84C2434-C768-4295-955B-E032E3A18FC3}.Instrumentation|x64.ActiveCfg = Release|Any CPU {F84C2434-C768-4295-955B-E032E3A18FC3}.Instrumentation|x64.Build.0 = Release|Any CPU {F84C2434-C768-4295-955B-E032E3A18FC3}.Release|Any CPU.ActiveCfg = Release|Any CPU {F84C2434-C768-4295-955B-E032E3A18FC3}.Release|Any CPU.Build.0 = Release|Any CPU {F84C2434-C768-4295-955B-E032E3A18FC3}.Release|ARM.ActiveCfg = Release|Any CPU {F84C2434-C768-4295-955B-E032E3A18FC3}.Release|ARM.Build.0 = Release|Any CPU {F84C2434-C768-4295-955B-E032E3A18FC3}.Release|Mixed Platforms.ActiveCfg = Release|Any CPU {F84C2434-C768-4295-955B-E032E3A18FC3}.Release|Mixed Platforms.Build.0 = Release|Any CPU {F84C2434-C768-4295-955B-E032E3A18FC3}.Release|Win32.ActiveCfg = Release|Any CPU {F84C2434-C768-4295-955B-E032E3A18FC3}.Release|Win32.Build.0 = Release|Any CPU {F84C2434-C768-4295-955B-E032E3A18FC3}.Release|x64.ActiveCfg = Release|Any CPU {F84C2434-C768-4295-955B-E032E3A18FC3}.Release|x64.Build.0 = Release|Any CPU {B157F660-AED5-49A2-99DB-FE60855DC5F4}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {B157F660-AED5-49A2-99DB-FE60855DC5F4}.Debug|Any CPU.Build.0 = Debug|Any CPU {B157F660-AED5-49A2-99DB-FE60855DC5F4}.Debug|ARM.ActiveCfg = Debug|Any CPU {B157F660-AED5-49A2-99DB-FE60855DC5F4}.Debug|ARM.Build.0 = Debug|Any CPU {B157F660-AED5-49A2-99DB-FE60855DC5F4}.Debug|Mixed Platforms.ActiveCfg = Debug|Any CPU {B157F660-AED5-49A2-99DB-FE60855DC5F4}.Debug|Mixed Platforms.Build.0 = Debug|Any CPU {B157F660-AED5-49A2-99DB-FE60855DC5F4}.Debug|Win32.ActiveCfg = Debug|Any CPU {B157F660-AED5-49A2-99DB-FE60855DC5F4}.Debug|Win32.Build.0 = Debug|Any CPU {B157F660-AED5-49A2-99DB-FE60855DC5F4}.Debug|x64.ActiveCfg = Debug|Any CPU {B157F660-AED5-49A2-99DB-FE60855DC5F4}.Debug|x64.Build.0 = Debug|Any CPU {B157F660-AED5-49A2-99DB-FE60855DC5F4}.Instrumentation|Any CPU.ActiveCfg = Instrumentation|Any CPU {B157F660-AED5-49A2-99DB-FE60855DC5F4}.Instrumentation|Any CPU.Build.0 = Instrumentation|Any CPU {B157F660-AED5-49A2-99DB-FE60855DC5F4}.Instrumentation|ARM.ActiveCfg = Instrumentation|Any CPU {B157F660-AED5-49A2-99DB-FE60855DC5F4}.Instrumentation|ARM.Build.0 = Instrumentation|Any CPU {B157F660-AED5-49A2-99DB-FE60855DC5F4}.Instrumentation|Mixed Platforms.ActiveCfg = Instrumentation|Any CPU {B157F660-AED5-49A2-99DB-FE60855DC5F4}.Instrumentation|Mixed Platforms.Build.0 = Instrumentation|Any CPU {B157F660-AED5-49A2-99DB-FE60855DC5F4}.Instrumentation|Win32.ActiveCfg = Instrumentation|Any CPU {B157F660-AED5-49A2-99DB-FE60855DC5F4}.Instrumentation|Win32.Build.0 = Instrumentation|Any CPU {B157F660-AED5-49A2-99DB-FE60855DC5F4}.Instrumentation|x64.ActiveCfg = Instrumentation|Any CPU {B157F660-AED5-49A2-99DB-FE60855DC5F4}.Instrumentation|x64.Build.0 = Instrumentation|Any CPU {B157F660-AED5-49A2-99DB-FE60855DC5F4}.Release|Any CPU.ActiveCfg = Release|Any CPU {B157F660-AED5-49A2-99DB-FE60855DC5F4}.Release|Any CPU.Build.0 = Release|Any CPU {B157F660-AED5-49A2-99DB-FE60855DC5F4}.Release|ARM.ActiveCfg = Release|Any CPU {B157F660-AED5-49A2-99DB-FE60855DC5F4}.Release|ARM.Build.0 = Release|Any CPU {B157F660-AED5-49A2-99DB-FE60855DC5F4}.Release|Mixed Platforms.ActiveCfg = Release|Any CPU {B157F660-AED5-49A2-99DB-FE60855DC5F4}.Release|Mixed Platforms.Build.0 = Release|Any CPU {B157F660-AED5-49A2-99DB-FE60855DC5F4}.Release|Win32.ActiveCfg = Release|Any CPU {B157F660-AED5-49A2-99DB-FE60855DC5F4}.Release|Win32.Build.0 = Release|Any CPU {B157F660-AED5-49A2-99DB-FE60855DC5F4}.Release|x64.ActiveCfg = Release|Any CPU {B157F660-AED5-49A2-99DB-FE60855DC5F4}.Release|x64.Build.0 = Release|Any CPU {46478CA2-8163-47A0-8C65-3ACFC21CE57F}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {46478CA2-8163-47A0-8C65-3ACFC21CE57F}.Debug|Any CPU.Build.0 = Debug|Any CPU {46478CA2-8163-47A0-8C65-3ACFC21CE57F}.Debug|ARM.ActiveCfg = Debug|Any CPU {46478CA2-8163-47A0-8C65-3ACFC21CE57F}.Debug|ARM.Build.0 = Debug|Any CPU {46478CA2-8163-47A0-8C65-3ACFC21CE57F}.Debug|Mixed Platforms.ActiveCfg = Debug|Any CPU {46478CA2-8163-47A0-8C65-3ACFC21CE57F}.Debug|Mixed Platforms.Build.0 = Debug|Any CPU {46478CA2-8163-47A0-8C65-3ACFC21CE57F}.Debug|Win32.ActiveCfg = Debug|Any CPU {46478CA2-8163-47A0-8C65-3ACFC21CE57F}.Debug|Win32.Build.0 = Debug|Any CPU {46478CA2-8163-47A0-8C65-3ACFC21CE57F}.Debug|x64.ActiveCfg = Debug|Any CPU {46478CA2-8163-47A0-8C65-3ACFC21CE57F}.Debug|x64.Build.0 = Debug|Any CPU {46478CA2-8163-47A0-8C65-3ACFC21CE57F}.Instrumentation|Any CPU.ActiveCfg = Instrumentation|Any CPU {46478CA2-8163-47A0-8C65-3ACFC21CE57F}.Instrumentation|Any CPU.Build.0 = Instrumentation|Any CPU {46478CA2-8163-47A0-8C65-3ACFC21CE57F}.Instrumentation|ARM.ActiveCfg = Instrumentation|Any CPU {46478CA2-8163-47A0-8C65-3ACFC21CE57F}.Instrumentation|ARM.Build.0 = Instrumentation|Any CPU {46478CA2-8163-47A0-8C65-3ACFC21CE57F}.Instrumentation|Mixed Platforms.ActiveCfg = Instrumentation|Any CPU {46478CA2-8163-47A0-8C65-3ACFC21CE57F}.Instrumentation|Mixed Platforms.Build.0 = Instrumentation|Any CPU {46478CA2-8163-47A0-8C65-3ACFC21CE57F}.Instrumentation|Win32.ActiveCfg = Instrumentation|Any CPU {46478CA2-8163-47A0-8C65-3ACFC21CE57F}.Instrumentation|Win32.Build.0 = Instrumentation|Any CPU {46478CA2-8163-47A0-8C65-3ACFC21CE57F}.Instrumentation|x64.ActiveCfg = Instrumentation|Any CPU {46478CA2-8163-47A0-8C65-3ACFC21CE57F}.Instrumentation|x64.Build.0 = Instrumentation|Any CPU {46478CA2-8163-47A0-8C65-3ACFC21CE57F}.Release|Any CPU.ActiveCfg = Release|Any CPU {46478CA2-8163-47A0-8C65-3ACFC21CE57F}.Release|Any CPU.Build.0 = Release|Any CPU {46478CA2-8163-47A0-8C65-3ACFC21CE57F}.Release|ARM.ActiveCfg = Release|Any CPU {46478CA2-8163-47A0-8C65-3ACFC21CE57F}.Release|ARM.Build.0 = Release|Any CPU {46478CA2-8163-47A0-8C65-3ACFC21CE57F}.Release|Mixed Platforms.ActiveCfg = Release|Any CPU {46478CA2-8163-47A0-8C65-3ACFC21CE57F}.Release|Mixed Platforms.Build.0 = Release|Any CPU {46478CA2-8163-47A0-8C65-3ACFC21CE57F}.Release|Win32.ActiveCfg = Release|Any CPU {46478CA2-8163-47A0-8C65-3ACFC21CE57F}.Release|Win32.Build.0 = Release|Any CPU {46478CA2-8163-47A0-8C65-3ACFC21CE57F}.Release|x64.ActiveCfg = Release|Any CPU {46478CA2-8163-47A0-8C65-3ACFC21CE57F}.Release|x64.Build.0 = Release|Any CPU {09CD4F6F-17D7-4A56-A8FD-797EBF2543DF}.Debug|Any CPU.ActiveCfg = Debug|Win32 {09CD4F6F-17D7-4A56-A8FD-797EBF2543DF}.Debug|ARM.ActiveCfg = Debug|Win32 {09CD4F6F-17D7-4A56-A8FD-797EBF2543DF}.Debug|Mixed Platforms.ActiveCfg = Debug|Win32 {09CD4F6F-17D7-4A56-A8FD-797EBF2543DF}.Debug|Win32.ActiveCfg = Debug|Win32 {09CD4F6F-17D7-4A56-A8FD-797EBF2543DF}.Debug|Win32.Build.0 = Debug|Win32 {09CD4F6F-17D7-4A56-A8FD-797EBF2543DF}.Debug|x64.ActiveCfg = Debug|Win32 {09CD4F6F-17D7-4A56-A8FD-797EBF2543DF}.Instrumentation|Any CPU.ActiveCfg = Release|Win32 {09CD4F6F-17D7-4A56-A8FD-797EBF2543DF}.Instrumentation|Any CPU.Build.0 = Release|Win32 {09CD4F6F-17D7-4A56-A8FD-797EBF2543DF}.Instrumentation|ARM.ActiveCfg = Release|Win32 {09CD4F6F-17D7-4A56-A8FD-797EBF2543DF}.Instrumentation|ARM.Build.0 = Release|Win32 {09CD4F6F-17D7-4A56-A8FD-797EBF2543DF}.Instrumentation|Mixed Platforms.ActiveCfg = Release|Win32 {09CD4F6F-17D7-4A56-A8FD-797EBF2543DF}.Instrumentation|Win32.ActiveCfg = Release|Win32 {09CD4F6F-17D7-4A56-A8FD-797EBF2543DF}.Instrumentation|Win32.Build.0 = Release|Win32 {09CD4F6F-17D7-4A56-A8FD-797EBF2543DF}.Instrumentation|x64.ActiveCfg = Release|Win32 {09CD4F6F-17D7-4A56-A8FD-797EBF2543DF}.Instrumentation|x64.Build.0 = Release|Win32 {09CD4F6F-17D7-4A56-A8FD-797EBF2543DF}.Release|Any CPU.ActiveCfg = Release|Win32 {09CD4F6F-17D7-4A56-A8FD-797EBF2543DF}.Release|ARM.ActiveCfg = Release|Win32 {09CD4F6F-17D7-4A56-A8FD-797EBF2543DF}.Release|Mixed Platforms.ActiveCfg = Release|Win32 {09CD4F6F-17D7-4A56-A8FD-797EBF2543DF}.Release|Win32.ActiveCfg = Release|Win32 {09CD4F6F-17D7-4A56-A8FD-797EBF2543DF}.Release|Win32.Build.0 = Release|Win32 {09CD4F6F-17D7-4A56-A8FD-797EBF2543DF}.Release|x64.ActiveCfg = Release|Win32 {E18A0A2A-60AF-4819-9F64-FD347E222144}.Debug|Any CPU.ActiveCfg = Debug|Win32 {E18A0A2A-60AF-4819-9F64-FD347E222144}.Debug|ARM.ActiveCfg = Debug|Win32 {E18A0A2A-60AF-4819-9F64-FD347E222144}.Debug|Mixed Platforms.ActiveCfg = Debug|Win32 {E18A0A2A-60AF-4819-9F64-FD347E222144}.Debug|Win32.ActiveCfg = Debug|Win32 {E18A0A2A-60AF-4819-9F64-FD347E222144}.Debug|Win32.Build.0 = Debug|Win32 {E18A0A2A-60AF-4819-9F64-FD347E222144}.Debug|x64.ActiveCfg = Debug|Win32 {E18A0A2A-60AF-4819-9F64-FD347E222144}.Instrumentation|Any CPU.ActiveCfg = Release|Win32 {E18A0A2A-60AF-4819-9F64-FD347E222144}.Instrumentation|Any CPU.Build.0 = Release|Win32 {E18A0A2A-60AF-4819-9F64-FD347E222144}.Instrumentation|ARM.ActiveCfg = Release|Win32 {E18A0A2A-60AF-4819-9F64-FD347E222144}.Instrumentation|ARM.Build.0 = Release|Win32 {E18A0A2A-60AF-4819-9F64-FD347E222144}.Instrumentation|Mixed Platforms.ActiveCfg = Release|Win32 {E18A0A2A-60AF-4819-9F64-FD347E222144}.Instrumentation|Win32.ActiveCfg = Release|Win32 {E18A0A2A-60AF-4819-9F64-FD347E222144}.Instrumentation|Win32.Build.0 = Release|Win32 {E18A0A2A-60AF-4819-9F64-FD347E222144}.Instrumentation|x64.ActiveCfg = Release|Win32 {E18A0A2A-60AF-4819-9F64-FD347E222144}.Instrumentation|x64.Build.0 = Release|Win32 {E18A0A2A-60AF-4819-9F64-FD347E222144}.Release|Any CPU.ActiveCfg = Release|Win32 {E18A0A2A-60AF-4819-9F64-FD347E222144}.Release|ARM.ActiveCfg = Release|Win32 {E18A0A2A-60AF-4819-9F64-FD347E222144}.Release|Mixed Platforms.ActiveCfg = Release|Win32 {E18A0A2A-60AF-4819-9F64-FD347E222144}.Release|Win32.ActiveCfg = Release|Win32 {E18A0A2A-60AF-4819-9F64-FD347E222144}.Release|Win32.Build.0 = Release|Win32 {E18A0A2A-60AF-4819-9F64-FD347E222144}.Release|x64.ActiveCfg = Release|Win32 {F0229144-F7C4-4456-8442-5E816C6E8FBC}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {F0229144-F7C4-4456-8442-5E816C6E8FBC}.Debug|Any CPU.Build.0 = Debug|Any CPU {F0229144-F7C4-4456-8442-5E816C6E8FBC}.Debug|ARM.ActiveCfg = Debug|Any CPU {F0229144-F7C4-4456-8442-5E816C6E8FBC}.Debug|ARM.Build.0 = Debug|Any CPU {F0229144-F7C4-4456-8442-5E816C6E8FBC}.Debug|Mixed Platforms.ActiveCfg = Debug|Any CPU {F0229144-F7C4-4456-8442-5E816C6E8FBC}.Debug|Mixed Platforms.Build.0 = Debug|Any CPU {F0229144-F7C4-4456-8442-5E816C6E8FBC}.Debug|Win32.ActiveCfg = Debug|Any CPU {F0229144-F7C4-4456-8442-5E816C6E8FBC}.Debug|Win32.Build.0 = Debug|Any CPU {F0229144-F7C4-4456-8442-5E816C6E8FBC}.Debug|x64.ActiveCfg = Debug|Any CPU {F0229144-F7C4-4456-8442-5E816C6E8FBC}.Debug|x64.Build.0 = Debug|Any CPU {F0229144-F7C4-4456-8442-5E816C6E8FBC}.Instrumentation|Any CPU.ActiveCfg = Release|Any CPU {F0229144-F7C4-4456-8442-5E816C6E8FBC}.Instrumentation|Any CPU.Build.0 = Release|Any CPU {F0229144-F7C4-4456-8442-5E816C6E8FBC}.Instrumentation|ARM.ActiveCfg = Release|Any CPU {F0229144-F7C4-4456-8442-5E816C6E8FBC}.Instrumentation|ARM.Build.0 = Release|Any CPU {F0229144-F7C4-4456-8442-5E816C6E8FBC}.Instrumentation|Mixed Platforms.ActiveCfg = Release|Any CPU {F0229144-F7C4-4456-8442-5E816C6E8FBC}.Instrumentation|Mixed Platforms.Build.0 = Release|Any CPU {F0229144-F7C4-4456-8442-5E816C6E8FBC}.Instrumentation|Win32.ActiveCfg = Release|Any CPU {F0229144-F7C4-4456-8442-5E816C6E8FBC}.Instrumentation|Win32.Build.0 = Release|Any CPU {F0229144-F7C4-4456-8442-5E816C6E8FBC}.Instrumentation|x64.ActiveCfg = Release|Any CPU {F0229144-F7C4-4456-8442-5E816C6E8FBC}.Instrumentation|x64.Build.0 = Release|Any CPU {F0229144-F7C4-4456-8442-5E816C6E8FBC}.Release|Any CPU.ActiveCfg = Release|Any CPU {F0229144-F7C4-4456-8442-5E816C6E8FBC}.Release|Any CPU.Build.0 = Release|Any CPU {F0229144-F7C4-4456-8442-5E816C6E8FBC}.Release|ARM.ActiveCfg = Release|Any CPU {F0229144-F7C4-4456-8442-5E816C6E8FBC}.Release|ARM.Build.0 = Release|Any CPU {F0229144-F7C4-4456-8442-5E816C6E8FBC}.Release|Mixed Platforms.ActiveCfg = Release|Any CPU {F0229144-F7C4-4456-8442-5E816C6E8FBC}.Release|Mixed Platforms.Build.0 = Release|Any CPU {F0229144-F7C4-4456-8442-5E816C6E8FBC}.Release|Win32.ActiveCfg = Release|Any CPU {F0229144-F7C4-4456-8442-5E816C6E8FBC}.Release|Win32.Build.0 = Release|Any CPU {F0229144-F7C4-4456-8442-5E816C6E8FBC}.Release|x64.ActiveCfg = Release|Any CPU {F0229144-F7C4-4456-8442-5E816C6E8FBC}.Release|x64.Build.0 = Release|Any CPU {F222E0D3-0FFF-41F4-91EE-400C4E4E043D}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {F222E0D3-0FFF-41F4-91EE-400C4E4E043D}.Debug|Any CPU.Build.0 = Debug|Any CPU {F222E0D3-0FFF-41F4-91EE-400C4E4E043D}.Debug|ARM.ActiveCfg = Debug|Any CPU {F222E0D3-0FFF-41F4-91EE-400C4E4E043D}.Debug|ARM.Build.0 = Debug|Any CPU {F222E0D3-0FFF-41F4-91EE-400C4E4E043D}.Debug|Mixed Platforms.ActiveCfg = Debug|Any CPU {F222E0D3-0FFF-41F4-91EE-400C4E4E043D}.Debug|Mixed Platforms.Build.0 = Debug|Any CPU {F222E0D3-0FFF-41F4-91EE-400C4E4E043D}.Debug|Win32.ActiveCfg = Debug|Any CPU {F222E0D3-0FFF-41F4-91EE-400C4E4E043D}.Debug|Win32.Build.0 = Debug|Any CPU {F222E0D3-0FFF-41F4-91EE-400C4E4E043D}.Debug|x64.ActiveCfg = Debug|Any CPU {F222E0D3-0FFF-41F4-91EE-400C4E4E043D}.Debug|x64.Build.0 = Debug|Any CPU {F222E0D3-0FFF-41F4-91EE-400C4E4E043D}.Instrumentation|Any CPU.ActiveCfg = Release|Any CPU {F222E0D3-0FFF-41F4-91EE-400C4E4E043D}.Instrumentation|Any CPU.Build.0 = Release|Any CPU {F222E0D3-0FFF-41F4-91EE-400C4E4E043D}.Instrumentation|ARM.ActiveCfg = Release|Any CPU {F222E0D3-0FFF-41F4-91EE-400C4E4E043D}.Instrumentation|ARM.Build.0 = Release|Any CPU {F222E0D3-0FFF-41F4-91EE-400C4E4E043D}.Instrumentation|Mixed Platforms.ActiveCfg = Release|Any CPU {F222E0D3-0FFF-41F4-91EE-400C4E4E043D}.Instrumentation|Mixed Platforms.Build.0 = Release|Any CPU {F222E0D3-0FFF-41F4-91EE-400C4E4E043D}.Instrumentation|Win32.ActiveCfg = Release|Any CPU {F222E0D3-0FFF-41F4-91EE-400C4E4E043D}.Instrumentation|Win32.Build.0 = Release|Any CPU {F222E0D3-0FFF-41F4-91EE-400C4E4E043D}.Instrumentation|x64.ActiveCfg = Release|Any CPU {F222E0D3-0FFF-41F4-91EE-400C4E4E043D}.Instrumentation|x64.Build.0 = Release|Any CPU {F222E0D3-0FFF-41F4-91EE-400C4E4E043D}.Release|Any CPU.ActiveCfg = Release|Any CPU {F222E0D3-0FFF-41F4-91EE-400C4E4E043D}.Release|Any CPU.Build.0 = Release|Any CPU {F222E0D3-0FFF-41F4-91EE-400C4E4E043D}.Release|ARM.ActiveCfg = Release|Any CPU {F222E0D3-0FFF-41F4-91EE-400C4E4E043D}.Release|ARM.Build.0 = Release|Any CPU {F222E0D3-0FFF-41F4-91EE-400C4E4E043D}.Release|Mixed Platforms.ActiveCfg = Release|Any CPU {F222E0D3-0FFF-41F4-91EE-400C4E4E043D}.Release|Mixed Platforms.Build.0 = Release|Any CPU {F222E0D3-0FFF-41F4-91EE-400C4E4E043D}.Release|Win32.ActiveCfg = Release|Any CPU {F222E0D3-0FFF-41F4-91EE-400C4E4E043D}.Release|Win32.Build.0 = Release|Any CPU {F222E0D3-0FFF-41F4-91EE-400C4E4E043D}.Release|x64.ActiveCfg = Release|Any CPU {F222E0D3-0FFF-41F4-91EE-400C4E4E043D}.Release|x64.Build.0 = Release|Any CPU EndGlobalSection GlobalSection(SolutionProperties) = preSolution HideSolutionNode = FALSE EndGlobalSection GlobalSection(NestedProjects) = preSolution {7F3A2DA3-7D2A-4F59-AEE2-3DBF75C80FFE} = {AEF34496-481F-47EC-B246-92F7E87339C0} {6956D60A-260F-4B83-ABC6-EDABC5E17C84} = {AEF34496-481F-47EC-B246-92F7E87339C0} {B005F882-B6AB-4CEA-9434-8BFF1876686B} = {AEF34496-481F-47EC-B246-92F7E87339C0} {A1D7BA88-298C-440A-B626-E061EDCE4045} = {993EE84F-7CEA-40E0-BE5C-B1F38D1BA562} {AA94AD05-A42A-4190-8585-A82439976872} = {993EE84F-7CEA-40E0-BE5C-B1F38D1BA562} {5354D2AA-713A-4F47-BE76-2CCC57DE6EC4} = {993EE84F-7CEA-40E0-BE5C-B1F38D1BA562} {DC90A338-0E12-4668-8FFF-2A0BDEBC3597} = {AEF34496-481F-47EC-B246-92F7E87339C0} {186F31A3-EF89-4A25-B2D5-20060404AA01} = {7F3A2DA3-7D2A-4F59-AEE2-3DBF75C80FFE} {186F31A3-EF89-4A25-B2D5-20060606AA02} = {7F3A2DA3-7D2A-4F59-AEE2-3DBF75C80FFE} {186F31A3-EF89-4A25-B2D5-20060501AA01} = {AA94AD05-A42A-4190-8585-A82439976872} {186F31A3-EF89-4A25-B2D5-20060509AA02} = {AA94AD05-A42A-4190-8585-A82439976872} {186F31A3-EF89-4A25-B2D5-20060509AA01} = {5354D2AA-713A-4F47-BE76-2CCC57DE6EC4} {186F31A3-EF89-4A25-B2D5-20060510AA01} = {7F3A2DA3-7D2A-4F59-AEE2-3DBF75C80FFE} {186F31A3-EF89-4A25-B2D5-20060603AA01} = {6956D60A-260F-4B83-ABC6-EDABC5E17C84} {186F31A3-EF89-4A25-B2D5-20060606AA01} = {6956D60A-260F-4B83-ABC6-EDABC5E17C84} {186F31A3-EF89-4A25-B2D5-20060704AA01} = {B2AEC590-045A-4623-8DFD-357A5B54C424} {186F31A3-EF89-4A25-B2D5-20060720AA01} = {5354D2AA-713A-4F47-BE76-2CCC57DE6EC4} {186F31A3-EF89-4A25-B2D5-20060721AA01} = {6956D60A-260F-4B83-ABC6-EDABC5E17C84} {186F31A3-EF89-4A25-B2D5-20061218AA01} = {5354D2AA-713A-4F47-BE76-2CCC57DE6EC4} {186F31A3-EF89-4A25-B2D5-20070211AA01} = {B005F882-B6AB-4CEA-9434-8BFF1876686B} {186F31A3-EF89-4A25-B2D5-20070222AA01} = {6956D60A-260F-4B83-ABC6-EDABC5E17C84} {186F31A3-EF89-4A25-B2D5-20070430AA01} = {B2AEC590-045A-4623-8DFD-357A5B54C424} {186F31A3-EF89-4A25-B2D5-20070519AA01} = {DC90A338-0E12-4668-8FFF-2A0BDEBC3597} {186F31A3-EF89-4A25-B2D5-20070601AA01} = {5354D2AA-713A-4F47-BE76-2CCC57DE6EC4} {186F31A3-EF89-4A25-B2D5-20070605AA02} = {6956D60A-260F-4B83-ABC6-EDABC5E17C84} {186F31A3-EF89-4A25-B2D5-20070606AA01} = {DC90A338-0E12-4668-8FFF-2A0BDEBC3597} {186F31A3-EF89-4A25-B2D5-20070702AA01} = {AA94AD05-A42A-4190-8585-A82439976872} {186F31A3-EF89-4A25-B2D5-20070911AA01} = {6BBE2750-648C-4CC6-A08C-6454CB98812B} {186F31A3-EF89-4A25-B2D5-20070724AA02} = {6BBE2750-648C-4CC6-A08C-6454CB98812B} {186F31A3-EF89-4A25-B2D5-20080519AA01} = {6BBE2750-648C-4CC6-A08C-6454CB98812B} {186F31A3-EF89-4A25-B2D5-20070725AA01} = {6BBE2750-648C-4CC6-A08C-6454CB98812B} {186F31A3-EF89-4A25-B2D5-20070726AA01} = {6BBE2750-648C-4CC6-A08C-6454CB98812B} {186F31A3-EF89-4A25-B2D5-20070803AA01} = {6BBE2750-648C-4CC6-A08C-6454CB98812B} {186F31A3-EF89-4A25-B2D5-20070912AA01} = {6BBE2750-648C-4CC6-A08C-6454CB98812B} {186F31A3-EF89-4A25-B2D5-20071018AA01} = {6BBE2750-648C-4CC6-A08C-6454CB98812B} {186F31A3-EF89-4A25-B2D5-20071208AA01} = {6BBE2750-648C-4CC6-A08C-6454CB98812B} {96BF0234-1D60-4401-A6B9-99839187234E} = {B005F882-B6AB-4CEA-9434-8BFF1876686B} {186F31A3-EF89-4A25-B2D5-20090606AA01} = {6BBE2750-648C-4CC6-A08C-6454CB98812B} {186F31A3-EF89-4A25-B2D5-20080606AA02} = {6BBE2750-648C-4CC6-A08C-6454CB98812B} {186F31A3-EF89-4A25-B2D5-20080628AA01} = {AA94AD05-A42A-4190-8585-A82439976872} {186F31A3-EF89-4A25-B2D5-20080630AA01} = {6BBE2750-648C-4CC6-A08C-6454CB98812B} {ACE86CB1-7796-4B5F-96AF-B51595944B66} = {700EC40D-81C7-45CC-8CB6-F92803BBB204} {F1829F0B-1A0E-4844-BF44-106F3ADDF157} = {B2AEC590-045A-4623-8DFD-357A5B54C424} {C165CC46-A458-478B-9167-F073EED35EB2} = {700EC40D-81C7-45CC-8CB6-F92803BBB204} {FA6F295F-6DEB-4095-86F2-DEC2D2D9A038} = {700EC40D-81C7-45CC-8CB6-F92803BBB204} {242A3A91-4622-4463-8A89-608908C7C540} = {700EC40D-81C7-45CC-8CB6-F92803BBB204} {30BA8CEE-868B-4C53-85C5-DFF6FA39D035} = {700EC40D-81C7-45CC-8CB6-F92803BBB204} {22248085-CA53-485F-9A71-968A7AC42B04} = {700EC40D-81C7-45CC-8CB6-F92803BBB204} {64874F12-60A0-4B5B-ACC6-616C530F430E} = {700EC40D-81C7-45CC-8CB6-F92803BBB204} {79F07A26-A95A-45AB-B6B6-325A63AF1065} = {3E953D4D-61BB-48CA-B996-90A5736BFA58} {77D71AF4-11C3-409B-A211-51FA19E5C1AA} = {F5824561-14E4-4E5E-83A4-CFE95F128829} {6C77A7DE-D464-430F-96A9-A64768763B5F} = {6956D60A-260F-4B83-ABC6-EDABC5E17C84} {0162C8CE-6641-4922-8664-F8A44356FBF7} = {6956D60A-260F-4B83-ABC6-EDABC5E17C84} {D7F2BC4E-1406-47AA-90E1-07BC4CE9410F} = {8988313A-FAC7-4CF9-B373-C4034FC01EFA} {7FC1F0E6-A46C-4A0C-AA6F-233EEFEB33D3} = {A1D7BA88-298C-440A-B626-E061EDCE4045} {6BBE2750-648C-4CC6-A08C-6454CB98812B} = {A1D7BA88-298C-440A-B626-E061EDCE4045} {700EC40D-81C7-45CC-8CB6-F92803BBB204} = {A1D7BA88-298C-440A-B626-E061EDCE4045} {8988313A-FAC7-4CF9-B373-C4034FC01EFA} = {7FC1F0E6-A46C-4A0C-AA6F-233EEFEB33D3} {6367CACE-0511-485D-9AE5-698F7E600839} = {F5824561-14E4-4E5E-83A4-CFE95F128829} {EE8431BB-2720-4F75-AD08-1E3307F68BE4} = {7FC1F0E6-A46C-4A0C-AA6F-233EEFEB33D3} {DFC4F889-3803-4B12-B792-30504AD8C85A} = {999FF4E4-118C-4705-839C-3ECF28854C8F} {016691CA-A31F-4273-A4D2-C5F6E4B3662D} = {AA94AD05-A42A-4190-8585-A82439976872} {6C581F6A-34F8-4380-9BE0-279F709D13CB} = {35A43865-50F4-423A-ACF6-B3AEC2511716} {D3FA04AF-4285-477D-A756-6C51E9A56E7A} = {35A43865-50F4-423A-ACF6-B3AEC2511716} {35A43865-50F4-423A-ACF6-B3AEC2511716} = {79F07A26-A95A-45AB-B6B6-325A63AF1065} {F5824561-14E4-4E5E-83A4-CFE95F128829} = {79F07A26-A95A-45AB-B6B6-325A63AF1065} {CF168235-325F-448A-B455-3382C2B9DA48} = {7FC1F0E6-A46C-4A0C-AA6F-233EEFEB33D3} {CF4FC546-608D-4BE4-8A67-1E8C9F3526A3} = {7FC1F0E6-A46C-4A0C-AA6F-233EEFEB33D3} {0B37E5BA-4839-4EC4-9E36-A96BCBEA2400} = {CF168235-325F-448A-B455-3382C2B9DA48} {0C522C6A-0F77-4AF8-AD78-5B2415C98C51} = {CF168235-325F-448A-B455-3382C2B9DA48} {A30EB003-94F8-4A85-8DA1-006F6810A7A4} = {CF168235-325F-448A-B455-3382C2B9DA48} {7FB3F581-742D-4E12-A36A-BE172C574AB0} = {CF4FC546-608D-4BE4-8A67-1E8C9F3526A3} {65C8EDA6-AC24-4E18-A5B5-216E0F2C3906} = {CF4FC546-608D-4BE4-8A67-1E8C9F3526A3} {CA8A6D38-528B-4FAA-89B6-8FA9178DE55D} = {CF4FC546-608D-4BE4-8A67-1E8C9F3526A3} {D68EE51B-A898-4A77-97D8-C61254CAC122} = {AA94AD05-A42A-4190-8585-A82439976872} {1705887B-E636-4FA3-AE40-2D431AF1511C} = {EE8431BB-2720-4F75-AD08-1E3307F68BE4} {CEE4D575-4B4B-42B0-B2F1-CC7198CB7306} = {EE8431BB-2720-4F75-AD08-1E3307F68BE4} {999FF4E4-118C-4705-839C-3ECF28854C8F} = {3E953D4D-61BB-48CA-B996-90A5736BFA58} {4D364D69-06AF-4277-8828-3B4313533A5B} = {DFC4F889-3803-4B12-B792-30504AD8C85A} {9AC4A5AB-04B5-46C2-9020-AC70D8E2DF8D} = {999FF4E4-118C-4705-839C-3ECF28854C8F} {0FCFB940-AFD7-450C-9A58-936A5349CD59} = {9AC4A5AB-04B5-46C2-9020-AC70D8E2DF8D} {8BD964E3-ADBC-497C-B6CB-16C762771797} = {0FCFB940-AFD7-450C-9A58-936A5349CD59} {E149B569-516B-4C88-A7B1-EBD02E12DD1E} = {8BD964E3-ADBC-497C-B6CB-16C762771797} {B649B569-516B-4C88-A7B1-EBD02E12DD99} = {999FF4E4-118C-4705-839C-3ECF28854C8F} {A8C7CEC1-FF02-4ECA-967B-72825F4940AE} = {999FF4E4-118C-4705-839C-3ECF28854C8F} {9863D039-AB21-4710-960E-7303919552C6} = {DC90A338-0E12-4668-8FFF-2A0BDEBC3597} {C17E59D0-2D64-4012-8A98-D184D0CF8A49} = {DC90A338-0E12-4668-8FFF-2A0BDEBC3597} {DC8C38D7-780B-4B13-8ACE-9050E39CC51C} = {AA94AD05-A42A-4190-8585-A82439976872} {110E8B86-4F26-458A-97C3-55F2BA1E60DE} = {993EE84F-7CEA-40E0-BE5C-B1F38D1BA562} {3ECE9965-D0E8-493E-848C-A43D96E26F16} = {110E8B86-4F26-458A-97C3-55F2BA1E60DE} {20DC2CF5-8EED-4231-9743-6BAB96BE465C} = {110E8B86-4F26-458A-97C3-55F2BA1E60DE} {2832CE7B-8065-4473-A3C7-B8B069920A9C} = {3ECE9965-D0E8-493E-848C-A43D96E26F16} {89BAA5C6-B788-4B69-AD54-E78A52E1AF33} = {7FC1F0E6-A46C-4A0C-AA6F-233EEFEB33D3} {E77AC86E-58AB-47B6-BC6D-3C1B4545CDFD} = {89BAA5C6-B788-4B69-AD54-E78A52E1AF33} {40710089-C1C3-49D9-93B6-07A25219E5E8} = {F5824561-14E4-4E5E-83A4-CFE95F128829} {A15E99D7-3C46-406C-8850-4674CD3FE97C} = {999FF4E4-118C-4705-839C-3ECF28854C8F} {F761A686-A69C-4081-BD23-AFD45670DD69} = {A15E99D7-3C46-406C-8850-4674CD3FE97C} {769F9326-B779-4F35-BC49-87E15CDF2A8C} = {F761A686-A69C-4081-BD23-AFD45670DD69} {DD4371DE-85A8-49AA-B939-10E03B7ED3C9} = {EE8431BB-2720-4F75-AD08-1E3307F68BE4} {9B0EDB62-1E62-492D-B807-A8501EEE8400} = {DC90A338-0E12-4668-8FFF-2A0BDEBC3597} {93219A45-914C-44B7-A6CB-66849879C8B1} = {110E8B86-4F26-458A-97C3-55F2BA1E60DE} {2D6185A8-A5FE-4FDF-874A-96037C37BD41} = {F5824561-14E4-4E5E-83A4-CFE95F128829} {9164B9A3-F6F0-49F0-845B-880534BE7D41} = {0FCFB940-AFD7-450C-9A58-936A5349CD59} {54125FC8-5C6D-4F4B-92B8-3377FE1D92E1} = {9164B9A3-F6F0-49F0-845B-880534BE7D41} {8B9C17E7-DA84-4C8E-8F1B-0E57C4B699D4} = {B2AEC590-045A-4623-8DFD-357A5B54C424} {A4CB8DA8-AB1A-4977-B1C5-9AE27EBB6FC7} = {8B9C17E7-DA84-4C8E-8F1B-0E57C4B699D4} {37193A86-BA04-4A3E-9DF8-656DF455E952} = {8B9C17E7-DA84-4C8E-8F1B-0E57C4B699D4} {19DD0BB4-AB2C-4B06-9D83-0FEE635566BD} = {A1D7BA88-298C-440A-B626-E061EDCE4045} {0F0DC8C5-349B-453D-94F2-123205E3EADD} = {F761A686-A69C-4081-BD23-AFD45670DD69} {6194144A-F8B1-4525-829F-061DF4A5645A} = {EE8431BB-2720-4F75-AD08-1E3307F68BE4} {7F600371-17AB-41F2-96AB-39C8AA2389E1} = {DC90A338-0E12-4668-8FFF-2A0BDEBC3597} {65E36DF8-5CB8-4582-851E-F5381AE4A1A7} = {EE8431BB-2720-4F75-AD08-1E3307F68BE4} {C183991C-1F27-4665-A884-FD977D2AD359} = {DC90A338-0E12-4668-8FFF-2A0BDEBC3597} {DFD09237-A74B-46A4-AA30-F711EEDA4AF7} = {7FC1F0E6-A46C-4A0C-AA6F-233EEFEB33D3} {910EC8B6-B1B8-4800-AEF6-0BD45471FAFB} = {7FC1F0E6-A46C-4A0C-AA6F-233EEFEB33D3} {E4C618AF-1785-472E-A070-8068E20582EB} = {910EC8B6-B1B8-4800-AEF6-0BD45471FAFB} {C3BFAFAD-A6C6-471D-A059-B3CB7E57A4AB} = {DFD09237-A74B-46A4-AA30-F711EEDA4AF7} {B8FE271A-CD41-435E-8766-4DB7609C1007} = {DFD09237-A74B-46A4-AA30-F711EEDA4AF7} {89EBDBB0-C81F-4611-B719-B385DF215F8D} = {DFD09237-A74B-46A4-AA30-F711EEDA4AF7} {F84C2434-C768-4295-955B-E032E3A18FC3} = {DC90A338-0E12-4668-8FFF-2A0BDEBC3597} {B157F660-AED5-49A2-99DB-FE60855DC5F4} = {19DD0BB4-AB2C-4B06-9D83-0FEE635566BD} {46478CA2-8163-47A0-8C65-3ACFC21CE57F} = {DC90A338-0E12-4668-8FFF-2A0BDEBC3597} {52C76D47-FE0A-4D7C-B11F-64B057D96523} = {9AC4A5AB-04B5-46C2-9020-AC70D8E2DF8D} {09CD4F6F-17D7-4A56-A8FD-797EBF2543DF} = {52C76D47-FE0A-4D7C-B11F-64B057D96523} {E18A0A2A-60AF-4819-9F64-FD347E222144} = {3ECE9965-D0E8-493E-848C-A43D96E26F16} {F0229144-F7C4-4456-8442-5E816C6E8FBC} = {EE8431BB-2720-4F75-AD08-1E3307F68BE4} {F222E0D3-0FFF-41F4-91EE-400C4E4E043D} = {DC90A338-0E12-4668-8FFF-2A0BDEBC3597} EndGlobalSection EndGlobal ================================================ FILE: Zelig/Zelig/setenv.cmd ================================================ @echo off echo. echo Welcome to Zelig! echo. if "%DEPOTROOT%" equ "" ( pushd %~dp0\.. FOR /F "usebackq delims==" %%i IN (`cd`) DO @set DEPOTROOT=%%i popd ) path %ProgramFiles%\Microsoft SDKs\Windows\v6.0A\bin;%PATH% path %DEPOTROOT%\Zelig\Scripts;%PATH% path %DEPOTROOT%\..\bin;%DEPOTROOT%\..\..\bin;%PATH% call "%VS100COMNTOOLS%\vsvars32.bat" rem prompt $_$+Dir: $P$_$_Cmd$G prompt $_$+---$G $P$_$+ $G$_Cmd$G ================================================ FILE: Zelig/ZeligInterop/Sample/ExternalLinking_tester/dotNetMF.proj ================================================  zelig_interop zelig_interop.$(LIB_EXT) $(SPOCLIENT)\Zelig_interop\dotNetMF.proj True ZeligSample Library ================================================ FILE: Zelig/ZeligInterop/Sample/ExternalLinking_tester/zelig_interop.cpp ================================================ //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // Copyright (c) Microsoft Corporation. All rights reserved. //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// #include "zelig_interop.h" int g_GlobalValue = 1; int g_GlobalValue2 = 2; static int s_StaticValue = 3; static int s_StaticValue2 = 4; int Foo::otherMethod(int arg1, int arg2) { m_private = s_StaticValue++; // m_private = 3, 4 return arg1 + arg2 + m_private + g_GlobalValue2++; // g_globalValue2 = 2, 3 } INTEROP_INTERFACE g_InteropInterface = { &FP_INTEROP_Driver::FP_Method }; int FP_INTEROP_Driver::FP_Method( int cVal, const char* name, unsigned int* outParam ) { *outParam = (int)cVal; return cVal*cVal; } FP_INTEROP_INTERFACES g_AvailableInterfaces[] = { { &g_InteropInterface }, }; extern "C" { int ImportedExternalFunction(int a, int b) { int r = 1, p; Foo f; unsigned int outVal = 0; p = g_AvailableInterfaces[0].interopIface->FPInterop( 3, "Hello World", &outVal ); s_StaticValue2++; // s_StaticValue2 = 5 b = f.otherMethod(a, b) + g_GlobalValue; // b = (3 + 7 + 3 + 2) + 1 = 16 r = a + b + s_StaticValue2; // r = 3 + 16 + 5 = 24 return f.otherMethod(r, b); // ret = 24 + 16 + 4 + 3 = 47 } } //--// -a c:\sporoot\current\client_v4_2_dev\BuildOutput\ARM\RVDS4.0\le\FLASH\debug\iMXS_net_open\lib\zelig_interop.lib ================================================ FILE: Zelig/ZeligInterop/Sample/ExternalLinking_tester/zelig_interop.h ================================================ //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // Copyright (c) Microsoft Corporation. All rights reserved. //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// extern "C" long long ExportedInternalFunction( long long arg1 ); extern int g_GlobalValue; extern int g_GlobalValue2; typedef int (*FP_INTEROP)( int /*cVal*/, const char*/*name*/, unsigned int* /*outParam*/ ); struct INTEROP_INTERFACE { FP_INTEROP FPInterop; }; struct FP_INTEROP_Driver { static int FP_Method( int cVal, const char* name, unsigned int* outParam ); }; struct FP_INTEROP_INTERFACES { INTEROP_INTERFACE* interopIface; }; struct Foo { private: int m_private; public: int otherMethod(int arg1, int arg2); }; typedef unsigned short WORD; struct SYSTEMTIME { WORD wYear; WORD wMonth; WORD wDayOfWeek; WORD wDay; WORD wHour; WORD wMinute; WORD wSecond; WORD wMilliseconds; }; extern "C" int ExportedStructInt64( long long time, SYSTEMTIME* sysTime ); ================================================ FILE: Zelig/ZeligInterop/Sample/ExternalLinking_tester/zelig_interop2.cpp ================================================ //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // Copyright (c) Microsoft Corporation. All rights reserved. //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// #include "zelig_interop.h" int s_StaticValue = 5; typedef long long (*FP )(long long); typedef unsigned char byte; static FP s_exportedFuncPtr = ExportedInternalFunction; struct MyStruct { public: int a; double b; char c; }; extern "C" { int MyExternalFunction(int a) // a = 47 { int r = 1, b = 0; double d = 3.33; Foo f; long long time = 3; SYSTEMTIME sysTime; sysTime.wYear = 1; sysTime.wMonth = 2; sysTime.wDayOfWeek = 3; sysTime.wDay = 4; sysTime.wHour = 5; sysTime.wMinute = 6; sysTime.wSecond = 7; sysTime.wMilliseconds = 8; s_StaticValue++; // s_StaticValue = 6 b = f.otherMethod(a, r) + g_GlobalValue; // b = 47 + 1 + 5 + 4 + 1 = 58 r = a + b + s_StaticValue; // r = 47 + 58 + 6 = 111 r = f.otherMethod(r, b); // r = 111 + 58 + 6 + 5 = 180 r = (int)s_exportedFuncPtr( r ); // r = 180 + 180 = 360 r /= 43; // r = 8 r = (int)(r * d); // r = 26 r += ExportedStructInt64( time, &sysTime ); // r = 27 r += sysTime.wSecond; // r = 27 + 3 = 30 return r; } double Multiply(double a, double b) { double c = a * b; return c; } void PassStringArgument( wchar_t* pChar, int len ) { int half = len / 2; len--; for(int i=0; ia = 123; pStruct->b = 3.4775; pStruct->c = 'Z'; } int StringLength( const wchar_t* pChar ) { int len = 0; while(*pChar++ != L'\0') { len++; } return len; } } //--// ================================================ FILE: Zelig/ZeligInterop/Sample/FileSystemSampleLPC/BlockStorageFileSystem.cpp ================================================ //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // Copyright (c) Microsoft Corporation. All rights reserved. //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// #include #include #include "BlockStorageFileSystem.h" //--// extern FILESYSTEM_DRIVER_INTERFACE g_FAT32_FILE_SYSTEM_DriverInterface; extern STREAM_DRIVER_INTERFACE g_FAT32_STREAM_DriverInterface; //#pragma pack(1) //static UINT32 s_RamBuffer[(5*1024*1024 + 512)/sizeof(UINT32)]; #define FS_SIZE (1 * 8 * 1024 * 1024) #define FS_BASE_ADDR (0x80000000 + FS_SIZE) #define FS_BLOCK_SIZE 0x20000 static const BlockRange s_BlockRanges[] = { { BlockRange::BLOCKTYPE_FILESYSTEM, 0, FS_SIZE / FS_BLOCK_SIZE - 2, //sizeof(s_RamBuffer) / 512 - 2, }, { BlockRange::BLOCKTYPE_CONFIG, FS_SIZE / FS_BLOCK_SIZE - 1, FS_SIZE / FS_BLOCK_SIZE - 1, //sizeof(s_RamBuffer) / 512 - 1, //sizeof(s_RamBuffer) / 512 - 1, } }; static const BlockRegionInfo s_RamRegionInfo = { //0xA0000000, FS_BASE_ADDR, //sizeof(s_RamBuffer)/512, FS_SIZE / FS_BLOCK_SIZE, FS_BLOCK_SIZE, 2, s_BlockRanges, }; static const BlockDeviceInfo s_RamDeviceInfo = { {FALSE, TRUE, FALSE, FALSE, TRUE}, 100, 500, 4, //sizeof(s_RamBuffer), FS_SIZE, 1, &s_RamRegionInfo, }; struct IBlockStorageDevice g_ZeligRAM_BS_DeviceTable = { &ZeligRAM_BS_Driver::ChipInitialize, &ZeligRAM_BS_Driver::ChipUnInitialize, &ZeligRAM_BS_Driver::GetDeviceInfo, &ZeligRAM_BS_Driver::Read, &ZeligRAM_BS_Driver::Write, &ZeligRAM_BS_Driver::Memset, &ZeligRAM_BS_Driver::GetSectorMetadata, &ZeligRAM_BS_Driver::SetSectorMetadata, &ZeligRAM_BS_Driver::IsBlockErased, &ZeligRAM_BS_Driver::EraseBlock, &ZeligRAM_BS_Driver::SetPowerState, &ZeligRAM_BS_Driver::MaxSectorWrite_uSec, &ZeligRAM_BS_Driver::MaxBlockErase_uSec, }; FILESYSTEM_INTERFACES g_AvailableFSInterfaces[] = { { &g_FAT32_FILE_SYSTEM_DriverInterface , &g_FAT32_STREAM_DriverInterface }, }; const size_t g_InstalledFSCount = 1; static FileSystemVolume* s_volumes[10]; static int s_volumeIdx = 0; static UINT32 s_MallocBytes[1024*1024/sizeof(UINT32)]; //static int s_MallocIndex = 0; struct FreeList { FreeList* pNext; UINT32* pData; UINT32 size; }; static FreeList s_freeList = {NULL, NULL, 0}; BlockStorageDevice g_RamBlockStorageDevice; FileSystemVolume g_RamFileSysVolume; //#pragma unpack extern "C" { void* private_malloc( size_t len ) { FreeList* ptr; FreeList* ptrPrev = NULL; while(len & 0x3) { len++; } len += 4; if(len < sizeof(FreeList)) { len = sizeof(FreeList); } if(s_freeList.pData == NULL) { s_freeList.pData = &s_MallocBytes[0]; s_freeList.size = sizeof(s_MallocBytes); s_freeList.pNext = NULL; } ptr = &s_freeList; while(ptr->size < len) { if(ptr->pNext == NULL) { while(true); } ptrPrev = ptr; ptr = ptr->pNext; } ptr->pData[0] = len; void* ret = (void*)&ptr->pData[1]; if(ptrPrev == NULL) { s_freeList.pData = (UINT32*)&ptr->pData[len]; s_freeList.size -= len; } else { ptrPrev->pNext = ptr->pNext; } return ret; } void private_free( void* ptrFree ) { FreeList* ptr = &s_freeList; FreeList* ptrPrev = NULL; UINT32 size = ((UINT32*)ptrFree)[-1]; while(ptr != NULL && ptr->pData < ptrFree) { ptrPrev = ptr; ptr = ptr->pNext; } if(ptrPrev->size + (UINT32)ptrPrev->pData == (UINT32)ptrFree - 4) { ptrPrev->size += size; } else { ptr = (FreeList*)&((UINT32*)ptrFree)[-1]; ptr->pNext = ptrPrev->pNext; ptrPrev->pNext = ptr; ptr->size = size; ptr->pData = (UINT32*)ptr; } } void* private_realloc( void * ptr, size_t len ) { UINT32 size = ((UINT32*)ptr)[-1]; void* ret; if(len < size) { return ptr; } ret = private_malloc(len); memcpy(ret, ptr, size); private_free(ptr); return ret; } void debug_printf( const char* format, ... ) { } } BOOL ZeligRAM_BS_Driver::ChipInitialize( void* context ) { return TRUE; } BOOL ZeligRAM_BS_Driver::ChipUnInitialize( void* context ) { return TRUE; } const BlockDeviceInfo* ZeligRAM_BS_Driver::GetDeviceInfo( void* context ) { return (BlockDeviceInfo*)context; } BOOL ZeligRAM_BS_Driver::ChipReadOnly( void* context, BOOL On, UINT32 ProtectionKey ) { return TRUE; } BOOL ZeligRAM_BS_Driver::Read( void* context, ByteAddress StartSector, UINT32 NumBytes, BYTE * pSectorBuff) { if(StartSector < FS_BASE_ADDR || (StartSector + NumBytes) > (FS_BASE_ADDR + FS_SIZE)) return FALSE; return 1 == Extern__Storage_Read( StartSector, pSectorBuff, 0, NumBytes ); } BOOL ZeligRAM_BS_Driver::Write(void* context, ByteAddress Address, UINT32 NumBytes, BYTE * pSectorBuff, BOOL ReadModifyWrite) { if(Address < FS_BASE_ADDR || (Address + NumBytes) > (FS_BASE_ADDR + FS_SIZE)) return FALSE; return 1 == Extern__Storage_Write( Address, pSectorBuff, 0, NumBytes ); } BOOL ZeligRAM_BS_Driver::Memset(void* context, ByteAddress Address, UINT8 Data, UINT32 NumBytes) { if(Address < FS_BASE_ADDR || (Address + NumBytes) > (FS_BASE_ADDR + FS_SIZE)) return FALSE; return 1 == Extern__Storage_Memset( Address, Data, NumBytes ); } BOOL ZeligRAM_BS_Driver::GetSectorMetadata(void* context, ByteAddress SectorStart, SectorMetadata* pSectorMetadata) { return FALSE; } BOOL ZeligRAM_BS_Driver::SetSectorMetadata(void* context, ByteAddress SectorStart, SectorMetadata* pSectorMetadata) { return FALSE; } BOOL ZeligRAM_BS_Driver::IsBlockErased( void* context, ByteAddress BlockStart, UINT32 BlockLength ) { if(BlockStart < FS_BASE_ADDR || (BlockStart + BlockLength) > (FS_BASE_ADDR + FS_SIZE)) return FALSE; return 1 == Extern__Storage_IsErased( BlockStart, FS_BLOCK_SIZE ); } BOOL ZeligRAM_BS_Driver::EraseBlock( void* context, ByteAddress Sector ) { if(Sector < FS_BASE_ADDR || (Sector + FS_BLOCK_SIZE) > (FS_BASE_ADDR + FS_SIZE)) return FALSE; return 1 == Extern__Storage_EraseBlock( Sector, FS_BLOCK_SIZE ); } void ZeligRAM_BS_Driver::SetPowerState( void* context, UINT32 State ) { return ; } UINT32 ZeligRAM_BS_Driver::MaxSectorWrite_uSec( void* context ) { return 100; } UINT32 ZeligRAM_BS_Driver::MaxBlockErase_uSec( void* context ) { return 500; } //--// extern "C" { void AddRamBlockStorageFileStream() { FileSystemVolume* pFSVolume; FAT_LogicDisk* pLogicDisk; BlockStorageList::Initialize(); BlockStorageList::AddDevice( &g_RamBlockStorageDevice, &g_ZeligRAM_BS_DeviceTable, (void*)&s_RamDeviceInfo, TRUE ); //BlockStorageList::InitializeDevices(); FS_Initialize(); FileSystemVolumeList::Initialize(); FileSystemVolumeList::AddVolume( &g_RamFileSysVolume, "ROOT", 0, 0, &g_FAT32_STREAM_DriverInterface, &g_FAT32_FILE_SYSTEM_DriverInterface, &g_RamBlockStorageDevice, 0, FALSE ); pFSVolume = FileSystemVolumeList::FindVolume("ROOT", 4); if (pFSVolume) { pLogicDisk = FAT_LogicDisk::Initialize(&(pFSVolume->m_volumeId)); if (pLogicDisk == NULL) { pFSVolume->Format("", FORMAT_PARAMETER_FORCE_FAT16); pLogicDisk = FAT_LogicDisk::Initialize(&(pFSVolume->m_volumeId)); } else { pLogicDisk->Uninitialize(); } } //FileSystemVolumeList::InitializeVolumes(); } struct FileInfo { UINT32 Attributes; INT64 CreationTime; INT64 LastAccessTime; INT64 LastWriteTime; INT64 Size; }; HRESULT Format ( UINT32 volumeHandle, LPCWSTR volumeLabel, UINT32 parameters ) { char lbl[128]; int idx = 0; const WCHAR* src = (const WCHAR*)volumeLabel; HRESULT hr; if(volumeHandle >= s_volumeIdx) return CLR_E_FILE_IO; FileSystemVolume* pVol = s_volumes[volumeHandle]; while(*src != L'\0' && idx < 127) { lbl[idx++] = (char)*src++; } lbl[idx] = '\0'; pVol->UninitializeVolume(); hr = pVol->Format( lbl, parameters ); if(SUCCEEDED(hr)) { pVol->InitializeVolume(); } return hr; } HRESULT FindOpen ( UINT32 volumeHandle, LPCWSTR path, UINT32* findHandle ) { FileSystemVolume* pVol; if(volumeHandle >= s_volumeIdx) return CLR_E_FILE_IO; pVol = s_volumes[volumeHandle]; return pVol->FindOpen(path, findHandle); } HRESULT FindNext ( UINT32 volumeHandle, UINT32 findHandle, FileInfo* findData, LPWSTR fileName, INT32* fileLen, BOOL* found ) { FS_FILEINFO fi; FileSystemVolume* pVol; HRESULT hr; INT32 len; UINT16 fileNameBuf[256]; if(volumeHandle >= s_volumeIdx) return CLR_E_FILE_IO; fi.FileName = fileNameBuf; fi.FileNameSize = ARRAYSIZE(fileNameBuf); pVol = s_volumes[volumeHandle]; hr = pVol->FindNext(findHandle, &fi, found ); len = *fileLen; *fileLen = 0; if(SUCCEEDED(hr)&& *found) { WCHAR* src = (WCHAR*)fi.FileName; WCHAR* dst = fileName; findData->Attributes = fi.Attributes; findData->CreationTime = fi.CreationTime; findData->LastAccessTime = fi.LastAccessTime; findData->LastWriteTime = fi.LastWriteTime; if(fi.FileNameSize/sizeof(WCHAR) < len) { len = fi.FileNameSize/sizeof(WCHAR); } while(*src != L'\0' && len-->1) { *dst++ = *src++; fileLen[0] += 1; } *dst = L'\0'; } return hr; } HRESULT FindClose ( UINT32 volumeHandle, UINT32 findHandle ) { FileSystemVolume* pVol; HRESULT hr; if(volumeHandle >= s_volumeIdx) return CLR_E_FILE_IO; pVol = s_volumes[volumeHandle]; hr = pVol->FindClose(findHandle); return hr; } HRESULT GetFileInfo ( UINT32 volumeHandle, LPCWSTR path, FileInfo* fileInfo, BOOL* found ) { FS_FILEINFO fi; FileSystemVolume* pVol; HRESULT hr; if(volumeHandle >= s_volumeIdx) return CLR_E_FILE_IO; pVol = s_volumes[volumeHandle]; memset(&fi, 0, sizeof(fi)); hr = pVol->GetFileInfo(path, &fi, found); if(SUCCEEDED(hr)&& *found) { fileInfo->Attributes = fi.Attributes; fileInfo->CreationTime = fi.CreationTime; fileInfo->LastAccessTime = fi.LastAccessTime; fileInfo->LastWriteTime = fi.LastWriteTime; fileInfo->Size = fi.Size; } return hr; } HRESULT CreateDirectory ( UINT32 volumeHandle, LPCWSTR path ) { FileSystemVolume* pVol; HRESULT hr; if(volumeHandle >= s_volumeIdx) return CLR_E_FILE_IO; pVol = s_volumes[volumeHandle]; hr = pVol->CreateDirectory( path ); return hr; } HRESULT Move ( UINT32 volumeHandle, LPCWSTR oldPath, LPCWSTR newPath ) { FileSystemVolume* pVol; HRESULT hr; if(volumeHandle >= s_volumeIdx) return CLR_E_FILE_IO; pVol = s_volumes[volumeHandle]; hr = pVol->Move( oldPath, newPath ); return hr; } HRESULT Delete ( UINT32 volumeHandle, LPCWSTR path ) { FileSystemVolume* pVol; HRESULT hr; if(volumeHandle >= s_volumeIdx) return CLR_E_FILE_IO; pVol = s_volumes[volumeHandle]; hr = pVol->Delete( path ); return hr; } HRESULT GetAttributes ( UINT32 volumeHandle, LPCWSTR path, UINT32* attributes ) { FileSystemVolume* pVol; HRESULT hr; if(volumeHandle >= s_volumeIdx) return CLR_E_FILE_IO; pVol = s_volumes[volumeHandle]; hr = pVol->GetAttributes( path, attributes ); return hr; } HRESULT SetAttributes ( UINT32 volumeHandle, LPCWSTR path, UINT32 attributes ) { FileSystemVolume* pVol; HRESULT hr; if(volumeHandle >= s_volumeIdx) return CLR_E_FILE_IO; pVol = s_volumes[volumeHandle]; hr = pVol->SetAttributes( path, attributes ); return hr; } HRESULT GetDriverDetails ( UINT32 volumeHandle, UINT32 handle, STREAM_DRIVER_DETAILS* details ) { FileSystemVolume* pVol; if(volumeHandle >= s_volumeIdx) return CLR_E_FILE_IO; pVol = s_volumes[volumeHandle]; *details = *pVol->DriverDetails(); return S_OK; } HRESULT Open ( UINT32 volumeHandle, LPCWSTR path, UINT32* handle ) { FileSystemVolume* pVol; HRESULT hr; if(volumeHandle >= s_volumeIdx) return CLR_E_FILE_IO; pVol = s_volumes[volumeHandle]; hr = pVol->Open( path, handle ); return hr; } HRESULT Close ( UINT32 volumeHandle, UINT32 handle ) { FileSystemVolume* pVol = s_volumes[volumeHandle]; HRESULT hr = pVol->Close( handle ); return hr; } HRESULT Read ( UINT32 volumeHandle, UINT32 handle, BYTE* buffer, int offset, int count, int* bytesRead ) { FileSystemVolume* pVol; HRESULT hr; if(volumeHandle >= s_volumeIdx) return CLR_E_FILE_IO; pVol = s_volumes[volumeHandle]; hr = pVol->Read( handle, &buffer[offset], count, bytesRead ); if(*bytesRead < 0) { *bytesRead = 0; } return hr; } HRESULT Write ( UINT32 volumeHandle, UINT32 handle, BYTE* buffer, int offset, int count, int* bytesWritten ) { FileSystemVolume* pVol; HRESULT hr; if(volumeHandle >= s_volumeIdx) return CLR_E_FILE_IO; pVol = s_volumes[volumeHandle]; hr = pVol->Write( handle, &buffer[offset], count, bytesWritten ); if(*bytesWritten < 0) { *bytesWritten = 0; hr = CLR_E_FILE_IO; } return hr; } HRESULT Flush ( UINT32 volumeHandle, UINT32 handle ) { FileSystemVolume* pVol; HRESULT hr; if(volumeHandle >= s_volumeIdx) return CLR_E_FILE_IO; pVol = s_volumes[volumeHandle]; hr = pVol->Flush( handle ); return hr; } HRESULT Seek ( UINT32 volumeHandle, UINT32 handle, INT64 offset, UINT32 origin, INT64* position ) { FileSystemVolume* pVol; HRESULT hr; if(volumeHandle >= s_volumeIdx) return CLR_E_FILE_IO; pVol = s_volumes[volumeHandle]; hr = pVol->Seek( handle, offset, origin, position ); return hr; } HRESULT GetLength ( UINT32 volumeHandle, UINT32 handle, INT64* length ) { FileSystemVolume* pVol; HRESULT hr; if(volumeHandle >= s_volumeIdx) return CLR_E_FILE_IO; pVol = s_volumes[volumeHandle]; hr = pVol->GetLength( handle, length ); return hr; } HRESULT SetLength( UINT32 volumeHandle, UINT32 handle, INT64 length ) { FileSystemVolume* pVol; HRESULT hr; if(volumeHandle >= s_volumeIdx) return CLR_E_FILE_IO; pVol = s_volumes[volumeHandle]; hr = pVol->SetLength( handle, length ); return hr; } HRESULT GetVolumes( UINT32* volume, INT32* volumeCount ) { INT32 cnt; if(volumeCount == NULL) return CLR_E_FILE_IO; if(volume == NULL) { *volumeCount = s_volumeIdx; return S_OK; } cnt = *volumeCount; if(cnt > s_volumeIdx) { cnt = s_volumeIdx; *volumeCount = cnt; } for(int i=0; i 0) { for(int x=0; xm_nameSpace, lbl )) { return x; } } } { FileSystemVolume* pVol = FileSystemVolumeList::FindVolume( lbl, i ); if(pVol != NULL) { idx = s_volumeIdx++; s_volumes[idx] = pVol; } } return idx; } HRESULT GetName( UINT32 volumeHandle, wchar_t* name, INT32* nameLen ) { char* pName; int idx = 0; int len = *nameLen; if(volumeHandle >= s_volumeIdx) { return CLR_E_FILE_IO; } pName = s_volumes[volumeHandle]->m_nameSpace; while(pName[idx] != '\0' && len-- > 0) { name[idx] = pName[idx]; idx++; } *nameLen = idx; return S_OK; } HRESULT GetLabel( UINT32 volumeHandle, wchar_t* label, INT32* labelLen ) { int idx = 0; int len = *labelLen; FileSystemVolume *pVol; char szLabel[16]; HRESULT hr = S_OK; if(volumeHandle >= s_volumeIdx) { return CLR_E_FILE_IO; } pVol = s_volumes[volumeHandle]; hr = g_FAT32_FILE_SYSTEM_DriverInterface.GetVolumeLabel( &pVol->m_volumeId, (LPSTR)szLabel, ARRAYSIZE(szLabel) ); if(SUCCEEDED(hr)) { if(len > ARRAYSIZE(szLabel)-1) { len = ARRAYSIZE(szLabel) - 1; } while(szLabel[idx] != '\0' && len-- > 0) { label[idx] = szLabel[idx]; idx++; } label[idx] = L'\0'; *labelLen = idx; } return S_OK; } HRESULT GetFileSystem( UINT32 volumeHandle, wchar_t* fileSystem, INT32* fileSystemLen ) { const char* pName; int idx = 0; int len = *fileSystemLen; if(volumeHandle >= s_volumeIdx) { return CLR_E_FILE_IO; } pName = s_volumes[volumeHandle]->m_fsDriver->Name; while(pName[idx] != '\0' && len-- > 0) { fileSystem[idx] = pName[idx]; idx++; } *fileSystemLen = idx; return S_OK; } HRESULT GetSize( UINT32 volumeHandle, INT64* totalFreeSpace, INT64* totalSize ) { if(volumeHandle >= s_volumeIdx) { return CLR_E_FILE_IO; } return s_volumes[volumeHandle]->GetSizeInfo(totalSize, totalFreeSpace); } } ================================================ FILE: Zelig/ZeligInterop/Sample/FileSystemSampleLPC/BlockStorageFileSystem.h ================================================ //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // Copyright (c) Microsoft Corporation. All rights reserved. ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////#include #include //--// #ifndef _ZeligRAM_BS_Driver #define _ZeligRAM_BS_Driver 1 extern "C" { UINT32 Extern__Storage_Write( UINT32 address, UINT8* buffer, UINT32 offset, UINT32 len ); UINT32 Extern__Storage_Read( UINT32 address, UINT8* buffer, UINT32 offset, UINT32 len ); UINT32 Extern__Storage_Memset( UINT32 address, UINT8 data, UINT32 len ); UINT32 Extern__Storage_IsErased( UINT32 address, UINT32 len ); UINT32 Extern__Storage_EraseBlock( UINT32 address, UINT32 len ); } //--// struct ZeligRAM_BS_Driver { static BOOL ChipInitialize( void* context ); static BOOL ChipUnInitialize( void* context ); static const BlockDeviceInfo* GetDeviceInfo( void* context ); static BOOL Read( void* context, ByteAddress Address, UINT32 NumBytes, BYTE * pSectorBuff ); static BOOL Write( void* context, ByteAddress Address, UINT32 NumBytes, BYTE * pSectorBuff, BOOL ReadModifyWrite ); static BOOL Memset( void* context, ByteAddress Address, UINT8 Data, UINT32 NumBytes ); static BOOL GetSectorMetadata(void* context, ByteAddress SectorStart, SectorMetadata* pSectorMetadata); static BOOL SetSectorMetadata(void* context, ByteAddress SectorStart, SectorMetadata* pSectorMetadata); static BOOL IsBlockErased( void* context, ByteAddress BlockStart, UINT32 BlockLength ); static BOOL EraseBlock( void* context, ByteAddress Address ); static void SetPowerState( void* context, UINT32 State ); static UINT32 MaxSectorWrite_uSec( void* context ); static UINT32 MaxBlockErase_uSec( void* context ); //--// static BOOL ChipReadOnly( void* context, BOOL On, UINT32 ProtectionKey ); static BOOL ReadProductID( void* context, FLASH_WORD& ManufacturerCode, FLASH_WORD& DeviceCode ); }; //--// #endif // _ZeligRAM_BS_Driver ================================================ FILE: Zelig/ZeligInterop/Sample/FileSystemSampleLPC/build.cmd ================================================ msbuild /p:platform=SAM9261_EK;DEVICE_TYPE=ARM926EJ-S;FLOATING_POINT_FLAG="--fpu vfpv2 " dotnetmf.proj ================================================ FILE: Zelig/ZeligInterop/Sample/FileSystemSampleLPC/dotnetmf.proj ================================================  $(SPOCLIENT)\..\client_zelig_v0_9\ZeligInterop\Sample\FileSystemSampleLPC\dotNetMF.proj {22764cf0-2780-4d79-b4d1-54c72543408A} BlockStorageFileSystem False ZeligInterop\Sample\FileSystemSampleLPC Library false 4.0.0.0 ================================================ FILE: Zelig/ZeligInterop/Sample/FileSystemTest/BlockStorageFileSystem.cpp ================================================ //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // Copyright (c) Microsoft Corporation. All rights reserved. //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// #include #include #include "BlockStorageFileSystem.h" //--// extern FILESYSTEM_DRIVER_INTERFACE g_FAT32_FILE_SYSTEM_DriverInterface; extern STREAM_DRIVER_INTERFACE g_FAT32_STREAM_DriverInterface; //#pragma pack(1) //static UINT32 s_RamBuffer[(5*1024*1024 + 512)/sizeof(UINT32)]; #define FS_SIZE (2 * 8 * 1024 * 1024) #define FS_BASE_ADDR (0xA0000000 + FS_SIZE) #define FS_BLOCK_SIZE 0x20000 static const BlockRange s_BlockRanges[] = { { BlockRange::BLOCKTYPE_FILESYSTEM, 0, FS_SIZE / FS_BLOCK_SIZE - 2, //sizeof(s_RamBuffer) / 512 - 2, }, { BlockRange::BLOCKTYPE_CONFIG, FS_SIZE / FS_BLOCK_SIZE - 1, FS_SIZE / FS_BLOCK_SIZE - 1, //sizeof(s_RamBuffer) / 512 - 1, //sizeof(s_RamBuffer) / 512 - 1, } }; static const BlockRegionInfo s_RamRegionInfo = { //0xA0000000, FS_BASE_ADDR, //sizeof(s_RamBuffer)/512, FS_SIZE / FS_BLOCK_SIZE, FS_BLOCK_SIZE, 2, s_BlockRanges, }; static const BlockDeviceInfo s_RamDeviceInfo = { {FALSE, TRUE, FALSE, FALSE, TRUE}, 100, 500, 4, //sizeof(s_RamBuffer), FS_SIZE, 1, &s_RamRegionInfo, }; struct IBlockStorageDevice g_ZeligRAM_BS_DeviceTable = { &ZeligRAM_BS_Driver::ChipInitialize, &ZeligRAM_BS_Driver::ChipUnInitialize, &ZeligRAM_BS_Driver::GetDeviceInfo, &ZeligRAM_BS_Driver::Read, &ZeligRAM_BS_Driver::Write, &ZeligRAM_BS_Driver::Memset, &ZeligRAM_BS_Driver::GetSectorMetadata, &ZeligRAM_BS_Driver::SetSectorMetadata, &ZeligRAM_BS_Driver::IsBlockErased, &ZeligRAM_BS_Driver::EraseBlock, &ZeligRAM_BS_Driver::SetPowerState, &ZeligRAM_BS_Driver::MaxSectorWrite_uSec, &ZeligRAM_BS_Driver::MaxBlockErase_uSec, }; FILESYSTEM_INTERFACES g_AvailableFSInterfaces[] = { { &g_FAT32_FILE_SYSTEM_DriverInterface , &g_FAT32_STREAM_DriverInterface }, }; const size_t g_InstalledFSCount = 1; static FileSystemVolume* s_volumes[10]; static int s_volumeIdx = 0; static UINT32 s_MallocBytes[1024*1024/sizeof(UINT32)]; //static int s_MallocIndex = 0; struct FreeList { FreeList* pNext; UINT32* pData; UINT32 size; }; static FreeList s_freeList = {NULL, NULL, 0}; BlockStorageDevice g_RamBlockStorageDevice; FileSystemVolume g_RamFileSysVolume; //#pragma unpack extern "C" { void* private_malloc( size_t len ) { FreeList* ptr; FreeList* ptrPrev = NULL; while(len & 0x3) { len++; } len += 4; if(len < sizeof(FreeList)) { len = sizeof(FreeList); } if(s_freeList.pData == NULL) { s_freeList.pData = &s_MallocBytes[0]; s_freeList.size = sizeof(s_MallocBytes); s_freeList.pNext = NULL; } ptr = &s_freeList; while(ptr->size < len) { if(ptr->pNext == NULL) { while(true); } ptrPrev = ptr; ptr = ptr->pNext; } ptr->pData[0] = len; void* ret = (void*)&ptr->pData[1]; if(ptrPrev == NULL) { s_freeList.pData = (UINT32*)&ptr->pData[len]; s_freeList.size -= len; } else { ptrPrev->pNext = ptr->pNext; } return ret; } void private_free( void* ptrFree ) { FreeList* ptr = &s_freeList; FreeList* ptrPrev = NULL; UINT32 size = ((UINT32*)ptrFree)[-1]; while(ptr != NULL && ptr->pData < ptrFree) { ptrPrev = ptr; ptr = ptr->pNext; } if(ptrPrev->size + (UINT32)ptrPrev->pData == (UINT32)ptrFree - 4) { ptrPrev->size += size; } else { ptr = (FreeList*)&((UINT32*)ptrFree)[-1]; ptr->pNext = ptrPrev->pNext; ptrPrev->pNext = ptr; ptr->size = size; ptr->pData = (UINT32*)ptr; } } void* private_realloc( void * ptr, size_t len ) { UINT32 size = ((UINT32*)ptr)[-1]; void* ret; if(len < size) { return ptr; } ret = private_malloc(len); memcpy(ret, ptr, size); private_free(ptr); return ret; } void debug_printf( const char* format, ... ) { } } BOOL ZeligRAM_BS_Driver::ChipInitialize( void* context ) { return TRUE; } BOOL ZeligRAM_BS_Driver::ChipUnInitialize( void* context ) { return TRUE; } const BlockDeviceInfo* ZeligRAM_BS_Driver::GetDeviceInfo( void* context ) { return (BlockDeviceInfo*)context; } BOOL ZeligRAM_BS_Driver::ChipReadOnly( void* context, BOOL On, UINT32 ProtectionKey ) { return TRUE; } BOOL ZeligRAM_BS_Driver::Read( void* context, ByteAddress StartSector, UINT32 NumBytes, BYTE * pSectorBuff) { if(StartSector < FS_BASE_ADDR || (StartSector + NumBytes) > (FS_BASE_ADDR + FS_SIZE)) return FALSE; return 1 == Extern__Storage_Read( StartSector, pSectorBuff, 0, NumBytes ); } BOOL ZeligRAM_BS_Driver::Write(void* context, ByteAddress Address, UINT32 NumBytes, BYTE * pSectorBuff, BOOL ReadModifyWrite) { if(Address < FS_BASE_ADDR || (Address + NumBytes) > (FS_BASE_ADDR + FS_SIZE)) return FALSE; return 1 == Extern__Storage_Write( Address, pSectorBuff, 0, NumBytes ); } BOOL ZeligRAM_BS_Driver::Memset(void* context, ByteAddress Address, UINT8 Data, UINT32 NumBytes) { if(Address < FS_BASE_ADDR || (Address + NumBytes) > (FS_BASE_ADDR + FS_SIZE)) return FALSE; return 1 == Extern__Storage_Memset( Address, Data, NumBytes ); } BOOL ZeligRAM_BS_Driver::GetSectorMetadata(void* context, ByteAddress SectorStart, SectorMetadata* pSectorMetadata) { return FALSE; } BOOL ZeligRAM_BS_Driver::SetSectorMetadata(void* context, ByteAddress SectorStart, SectorMetadata* pSectorMetadata) { return FALSE; } BOOL ZeligRAM_BS_Driver::IsBlockErased( void* context, ByteAddress BlockStart, UINT32 BlockLength ) { if(BlockStart < FS_BASE_ADDR || (BlockStart + BlockLength) > (FS_BASE_ADDR + FS_SIZE)) return FALSE; return 1 == Extern__Storage_IsErased( BlockStart, FS_BLOCK_SIZE ); } BOOL ZeligRAM_BS_Driver::EraseBlock( void* context, ByteAddress Sector ) { if(Sector < FS_BASE_ADDR || (Sector + FS_BLOCK_SIZE) > (FS_BASE_ADDR + FS_SIZE)) return FALSE; return 1 == Extern__Storage_EraseBlock( Sector, FS_BLOCK_SIZE ); } void ZeligRAM_BS_Driver::SetPowerState( void* context, UINT32 State ) { return ; } UINT32 ZeligRAM_BS_Driver::MaxSectorWrite_uSec( void* context ) { return 100; } UINT32 ZeligRAM_BS_Driver::MaxBlockErase_uSec( void* context ) { return 500; } //--// extern "C" { void AddRamBlockStorageFileStream() { FileSystemVolume* pFSVolume; FAT_LogicDisk* pLogicDisk; BlockStorageList::Initialize(); BlockStorageList::AddDevice( &g_RamBlockStorageDevice, &g_ZeligRAM_BS_DeviceTable, (void*)&s_RamDeviceInfo, TRUE ); //BlockStorageList::InitializeDevices(); FS_Initialize(); FileSystemVolumeList::Initialize(); FileSystemVolumeList::AddVolume( &g_RamFileSysVolume, "ROOT", 0, 0, &g_FAT32_STREAM_DriverInterface, &g_FAT32_FILE_SYSTEM_DriverInterface, &g_RamBlockStorageDevice, 0, FALSE ); pFSVolume = FileSystemVolumeList::FindVolume("ROOT", 4); if (pFSVolume) { pLogicDisk = FAT_LogicDisk::Initialize(&(pFSVolume->m_volumeId)); if (pLogicDisk == NULL) { pFSVolume->Format("", FORMAT_PARAMETER_FORCE_FAT16); pLogicDisk = FAT_LogicDisk::Initialize(&(pFSVolume->m_volumeId)); } else { pLogicDisk->Uninitialize(); } } //FileSystemVolumeList::InitializeVolumes(); } struct FileInfo { UINT32 Attributes; INT64 CreationTime; INT64 LastAccessTime; INT64 LastWriteTime; INT64 Size; }; HRESULT Format ( UINT32 volumeHandle, LPCWSTR volumeLabel, UINT32 parameters ) { char lbl[128]; int idx = 0; const WCHAR* src = (const WCHAR*)volumeLabel; HRESULT hr; if(volumeHandle >= s_volumeIdx) return CLR_E_FILE_IO; FileSystemVolume* pVol = s_volumes[volumeHandle]; while(*src != L'\0' && idx < 127) { lbl[idx++] = (char)*src++; } lbl[idx] = '\0'; pVol->UninitializeVolume(); hr = pVol->Format( lbl, parameters ); if(SUCCEEDED(hr)) { pVol->InitializeVolume(); } return hr; } HRESULT FindOpen ( UINT32 volumeHandle, LPCWSTR path, UINT32* findHandle ) { FileSystemVolume* pVol; if(volumeHandle >= s_volumeIdx) return CLR_E_FILE_IO; pVol = s_volumes[volumeHandle]; return pVol->FindOpen(path, findHandle); } HRESULT FindNext ( UINT32 volumeHandle, UINT32 findHandle, FileInfo* findData, LPWSTR fileName, INT32* fileLen, BOOL* found ) { FS_FILEINFO fi; FileSystemVolume* pVol; HRESULT hr; INT32 len; UINT16 fileNameBuf[256]; if(volumeHandle >= s_volumeIdx) return CLR_E_FILE_IO; fi.FileName = fileNameBuf; fi.FileNameSize = ARRAYSIZE(fileNameBuf); pVol = s_volumes[volumeHandle]; hr = pVol->FindNext(findHandle, &fi, found ); len = *fileLen; *fileLen = 0; if(SUCCEEDED(hr)&& *found) { WCHAR* src = (WCHAR*)fi.FileName; WCHAR* dst = fileName; findData->Attributes = fi.Attributes; findData->CreationTime = fi.CreationTime; findData->LastAccessTime = fi.LastAccessTime; findData->LastWriteTime = fi.LastWriteTime; if(fi.FileNameSize/sizeof(WCHAR) < len) { len = fi.FileNameSize/sizeof(WCHAR); } while(*src != L'\0' && len-->1) { *dst++ = *src++; fileLen[0] += 1; } *dst = L'\0'; } return hr; } HRESULT FindClose ( UINT32 volumeHandle, UINT32 findHandle ) { FileSystemVolume* pVol; HRESULT hr; if(volumeHandle >= s_volumeIdx) return CLR_E_FILE_IO; pVol = s_volumes[volumeHandle]; hr = pVol->FindClose(findHandle); return hr; } HRESULT GetFileInfo ( UINT32 volumeHandle, LPCWSTR path, FileInfo* fileInfo, BOOL* found ) { FS_FILEINFO fi; FileSystemVolume* pVol; HRESULT hr; if(volumeHandle >= s_volumeIdx) return CLR_E_FILE_IO; pVol = s_volumes[volumeHandle]; memset(&fi, 0, sizeof(fi)); hr = pVol->GetFileInfo(path, &fi, found); if(SUCCEEDED(hr)&& *found) { fileInfo->Attributes = fi.Attributes; fileInfo->CreationTime = fi.CreationTime; fileInfo->LastAccessTime = fi.LastAccessTime; fileInfo->LastWriteTime = fi.LastWriteTime; fileInfo->Size = fi.Size; } return hr; } HRESULT CreateDirectory ( UINT32 volumeHandle, LPCWSTR path ) { FileSystemVolume* pVol; HRESULT hr; if(volumeHandle >= s_volumeIdx) return CLR_E_FILE_IO; pVol = s_volumes[volumeHandle]; hr = pVol->CreateDirectory( path ); return hr; } HRESULT Move ( UINT32 volumeHandle, LPCWSTR oldPath, LPCWSTR newPath ) { FileSystemVolume* pVol; HRESULT hr; if(volumeHandle >= s_volumeIdx) return CLR_E_FILE_IO; pVol = s_volumes[volumeHandle]; hr = pVol->Move( oldPath, newPath ); return hr; } HRESULT Delete ( UINT32 volumeHandle, LPCWSTR path ) { FileSystemVolume* pVol; HRESULT hr; if(volumeHandle >= s_volumeIdx) return CLR_E_FILE_IO; pVol = s_volumes[volumeHandle]; hr = pVol->Delete( path ); return hr; } HRESULT GetAttributes ( UINT32 volumeHandle, LPCWSTR path, UINT32* attributes ) { FileSystemVolume* pVol; HRESULT hr; if(volumeHandle >= s_volumeIdx) return CLR_E_FILE_IO; pVol = s_volumes[volumeHandle]; hr = pVol->GetAttributes( path, attributes ); return hr; } HRESULT SetAttributes ( UINT32 volumeHandle, LPCWSTR path, UINT32 attributes ) { FileSystemVolume* pVol; HRESULT hr; if(volumeHandle >= s_volumeIdx) return CLR_E_FILE_IO; pVol = s_volumes[volumeHandle]; hr = pVol->SetAttributes( path, attributes ); return hr; } HRESULT GetDriverDetails ( UINT32 volumeHandle, UINT32 handle, STREAM_DRIVER_DETAILS* details ) { FileSystemVolume* pVol; if(volumeHandle >= s_volumeIdx) return CLR_E_FILE_IO; pVol = s_volumes[volumeHandle]; *details = *pVol->DriverDetails(); return S_OK; } HRESULT Open ( UINT32 volumeHandle, LPCWSTR path, UINT32* handle ) { FileSystemVolume* pVol; HRESULT hr; if(volumeHandle >= s_volumeIdx) return CLR_E_FILE_IO; pVol = s_volumes[volumeHandle]; hr = pVol->Open( path, handle ); return hr; } HRESULT Close ( UINT32 volumeHandle, UINT32 handle ) { FileSystemVolume* pVol = s_volumes[volumeHandle]; HRESULT hr = pVol->Close( handle ); return hr; } HRESULT Read ( UINT32 volumeHandle, UINT32 handle, BYTE* buffer, int offset, int count, int* bytesRead ) { FileSystemVolume* pVol; HRESULT hr; if(volumeHandle >= s_volumeIdx) return CLR_E_FILE_IO; pVol = s_volumes[volumeHandle]; hr = pVol->Read( handle, &buffer[offset], count, bytesRead ); if(*bytesRead < 0) { *bytesRead = 0; } return hr; } HRESULT Write ( UINT32 volumeHandle, UINT32 handle, BYTE* buffer, int offset, int count, int* bytesWritten ) { FileSystemVolume* pVol; HRESULT hr; if(volumeHandle >= s_volumeIdx) return CLR_E_FILE_IO; pVol = s_volumes[volumeHandle]; hr = pVol->Write( handle, &buffer[offset], count, bytesWritten ); if(*bytesWritten < 0) { *bytesWritten = 0; hr = CLR_E_FILE_IO; } return hr; } HRESULT Flush ( UINT32 volumeHandle, UINT32 handle ) { FileSystemVolume* pVol; HRESULT hr; if(volumeHandle >= s_volumeIdx) return CLR_E_FILE_IO; pVol = s_volumes[volumeHandle]; hr = pVol->Flush( handle ); return hr; } HRESULT Seek ( UINT32 volumeHandle, UINT32 handle, INT64 offset, UINT32 origin, INT64* position ) { FileSystemVolume* pVol; HRESULT hr; if(volumeHandle >= s_volumeIdx) return CLR_E_FILE_IO; pVol = s_volumes[volumeHandle]; hr = pVol->Seek( handle, offset, origin, position ); return hr; } HRESULT GetLength ( UINT32 volumeHandle, UINT32 handle, INT64* length ) { FileSystemVolume* pVol; HRESULT hr; if(volumeHandle >= s_volumeIdx) return CLR_E_FILE_IO; pVol = s_volumes[volumeHandle]; hr = pVol->GetLength( handle, length ); return hr; } HRESULT SetLength( UINT32 volumeHandle, UINT32 handle, INT64 length ) { FileSystemVolume* pVol; HRESULT hr; if(volumeHandle >= s_volumeIdx) return CLR_E_FILE_IO; pVol = s_volumes[volumeHandle]; hr = pVol->SetLength( handle, length ); return hr; } HRESULT GetVolumes( UINT32* volume, INT32* volumeCount ) { INT32 cnt; if(volumeCount == NULL) return CLR_E_FILE_IO; if(volume == NULL) { *volumeCount = s_volumeIdx; return S_OK; } cnt = *volumeCount; if(cnt > s_volumeIdx) { cnt = s_volumeIdx; *volumeCount = cnt; } for(int i=0; i 0) { for(int x=0; xm_nameSpace, lbl )) { return x; } } } { FileSystemVolume* pVol = FileSystemVolumeList::FindVolume( lbl, i ); if(pVol != NULL) { idx = s_volumeIdx++; s_volumes[idx] = pVol; } } return idx; } HRESULT GetName( UINT32 volumeHandle, wchar_t* name, INT32* nameLen ) { char* pName; int idx = 0; int len = *nameLen; if(volumeHandle >= s_volumeIdx) { return CLR_E_FILE_IO; } pName = s_volumes[volumeHandle]->m_nameSpace; while(pName[idx] != '\0' && len-- > 0) { name[idx] = pName[idx]; idx++; } *nameLen = idx; return S_OK; } HRESULT GetLabel( UINT32 volumeHandle, wchar_t* label, INT32* labelLen ) { int idx = 0; int len = *labelLen; FileSystemVolume *pVol; char szLabel[16]; HRESULT hr = S_OK; if(volumeHandle >= s_volumeIdx) { return CLR_E_FILE_IO; } pVol = s_volumes[volumeHandle]; hr = g_FAT32_FILE_SYSTEM_DriverInterface.GetVolumeLabel( &pVol->m_volumeId, (LPSTR)szLabel, ARRAYSIZE(szLabel) ); if(SUCCEEDED(hr)) { if(len > ARRAYSIZE(szLabel)-1) { len = ARRAYSIZE(szLabel) - 1; } while(szLabel[idx] != '\0' && len-- > 0) { label[idx] = szLabel[idx]; idx++; } label[idx] = L'\0'; *labelLen = idx; } return S_OK; } HRESULT GetFileSystem( UINT32 volumeHandle, wchar_t* fileSystem, INT32* fileSystemLen ) { const char* pName; int idx = 0; int len = *fileSystemLen; if(volumeHandle >= s_volumeIdx) { return CLR_E_FILE_IO; } pName = s_volumes[volumeHandle]->m_fsDriver->Name; while(pName[idx] != '\0' && len-- > 0) { fileSystem[idx] = pName[idx]; idx++; } *fileSystemLen = idx; return S_OK; } HRESULT GetSize( UINT32 volumeHandle, INT64* totalFreeSpace, INT64* totalSize ) { if(volumeHandle >= s_volumeIdx) { return CLR_E_FILE_IO; } return s_volumes[volumeHandle]->GetSizeInfo(totalSize, totalFreeSpace); } } ================================================ FILE: Zelig/ZeligInterop/Sample/FileSystemTest/BlockStorageFileSystem.h ================================================ //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // Copyright (c) Microsoft Corporation. All rights reserved. ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////#include #include //--// #ifndef _ZeligRAM_BS_Driver #define _ZeligRAM_BS_Driver 1 extern "C" { UINT32 Extern__Storage_Write( UINT32 address, UINT8* buffer, UINT32 offset, UINT32 len ); UINT32 Extern__Storage_Read( UINT32 address, UINT8* buffer, UINT32 offset, UINT32 len ); UINT32 Extern__Storage_Memset( UINT32 address, UINT8 data, UINT32 len ); UINT32 Extern__Storage_IsErased( UINT32 address, UINT32 len ); UINT32 Extern__Storage_EraseBlock( UINT32 address, UINT32 len ); } //--// struct ZeligRAM_BS_Driver { static BOOL ChipInitialize( void* context ); static BOOL ChipUnInitialize( void* context ); static const BlockDeviceInfo* GetDeviceInfo( void* context ); static BOOL Read( void* context, ByteAddress Address, UINT32 NumBytes, BYTE * pSectorBuff ); static BOOL Write( void* context, ByteAddress Address, UINT32 NumBytes, BYTE * pSectorBuff, BOOL ReadModifyWrite ); static BOOL Memset( void* context, ByteAddress Address, UINT8 Data, UINT32 NumBytes ); static BOOL GetSectorMetadata(void* context, ByteAddress SectorStart, SectorMetadata* pSectorMetadata); static BOOL SetSectorMetadata(void* context, ByteAddress SectorStart, SectorMetadata* pSectorMetadata); static BOOL IsBlockErased( void* context, ByteAddress BlockStart, UINT32 BlockLength ); static BOOL EraseBlock( void* context, ByteAddress Address ); static void SetPowerState( void* context, UINT32 State ); static UINT32 MaxSectorWrite_uSec( void* context ); static UINT32 MaxBlockErase_uSec( void* context ); //--// static BOOL ChipReadOnly( void* context, BOOL On, UINT32 ProtectionKey ); static BOOL ReadProductID( void* context, FLASH_WORD& ManufacturerCode, FLASH_WORD& DeviceCode ); }; //--// #endif // _ZeligRAM_BS_Driver ================================================ FILE: Zelig/ZeligInterop/Sample/FileSystemTest/build.cmd ================================================ msbuild /p:platform=MOTE2 dotnetmf.proj ================================================ FILE: Zelig/ZeligInterop/Sample/FileSystemTest/dotnetmf.proj ================================================  $(SPOCLIENT)\..\client_zelig_v0_9\ZeligInterop\Sample\FileSystemTest\dotNetMF.proj {22764cf0-2780-4d79-b4d1-54c72543408B} BlockStorageFileSystem False ZeligInterop\Sample\FileSystemTest Library false 4.0.0.0 ================================================ FILE: Zelig/ext-tools/binutils/binutils.sln ================================================  Microsoft Visual Studio Solution File, Format Version 11.00 # Visual Studio 2010 Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "readelf", "readelf\readelf.csproj", "{A4CB8DA8-AB1A-4977-B1C5-9AE27EBB6FC7}" EndProject Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "elflib", "elflib\elflib.csproj", "{37193A86-BA04-4A3E-9DF8-656DF455E952}" EndProject Global GlobalSection(SolutionConfigurationPlatforms) = preSolution Debug|Any CPU = Debug|Any CPU Instrumentation|Any CPU = Instrumentation|Any CPU Release|Any CPU = Release|Any CPU EndGlobalSection GlobalSection(ProjectConfigurationPlatforms) = postSolution {A4CB8DA8-AB1A-4977-B1C5-9AE27EBB6FC7}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {A4CB8DA8-AB1A-4977-B1C5-9AE27EBB6FC7}.Debug|Any CPU.Build.0 = Debug|Any CPU {A4CB8DA8-AB1A-4977-B1C5-9AE27EBB6FC7}.Instrumentation|Any CPU.ActiveCfg = Instrumentation|Any CPU {A4CB8DA8-AB1A-4977-B1C5-9AE27EBB6FC7}.Instrumentation|Any CPU.Build.0 = Instrumentation|Any CPU {A4CB8DA8-AB1A-4977-B1C5-9AE27EBB6FC7}.Release|Any CPU.ActiveCfg = Release|Any CPU {A4CB8DA8-AB1A-4977-B1C5-9AE27EBB6FC7}.Release|Any CPU.Build.0 = Release|Any CPU {37193A86-BA04-4A3E-9DF8-656DF455E952}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {37193A86-BA04-4A3E-9DF8-656DF455E952}.Debug|Any CPU.Build.0 = Debug|Any CPU {37193A86-BA04-4A3E-9DF8-656DF455E952}.Instrumentation|Any CPU.ActiveCfg = Instrumentation|Any CPU {37193A86-BA04-4A3E-9DF8-656DF455E952}.Instrumentation|Any CPU.Build.0 = Instrumentation|Any CPU {37193A86-BA04-4A3E-9DF8-656DF455E952}.Release|Any CPU.ActiveCfg = Release|Any CPU {37193A86-BA04-4A3E-9DF8-656DF455E952}.Release|Any CPU.Build.0 = Release|Any CPU EndGlobalSection GlobalSection(SolutionProperties) = preSolution HideSolutionNode = FALSE EndGlobalSection EndGlobal ================================================ FILE: Zelig/lwip/lwip/include/ipv4/lwip/autoip.h ================================================ /** * @file * * AutoIP Automatic LinkLocal IP Configuration */ /* * * Copyright (c) 2007 Dominik Spies * All rights reserved. * * Redistribution and use in source and binary forms, with or without modification, * are permitted provided that the following conditions are met: * * 1. Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * 3. The name of the author may not be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT * SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT * OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING * IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY * OF SUCH DAMAGE. * * Author: Dominik Spies * * This is a AutoIP implementation for the lwIP TCP/IP stack. It aims to conform * with RFC 3927. * * * Please coordinate changes and requests with Dominik Spies * */ #ifndef __LWIP_AUTOIP_H__ #define __LWIP_AUTOIP_H__ #include "lwip/opt.h" #if LWIP_AUTOIP /* don't build if not configured for use in lwipopts.h */ #include "lwip/netif.h" #include "lwip/udp.h" #include "netif/etharp.h" #ifdef __cplusplus extern "C" { #endif /* AutoIP Timing */ #define AUTOIP_TMR_INTERVAL 100 #define AUTOIP_TICKS_PER_SECOND (1000 / AUTOIP_TMR_INTERVAL) /* RFC 3927 Constants */ #define PROBE_WAIT 1 /* second (initial random delay) */ #define PROBE_MIN 1 /* second (minimum delay till repeated probe) */ #define PROBE_MAX 2 /* seconds (maximum delay till repeated probe) */ #define PROBE_NUM 3 /* (number of probe packets) */ #define ANNOUNCE_NUM 2 /* (number of announcement packets) */ #define ANNOUNCE_INTERVAL 2 /* seconds (time between announcement packets) */ #define ANNOUNCE_WAIT 2 /* seconds (delay before announcing) */ #define MAX_CONFLICTS 10 /* (max conflicts before rate limiting) */ #define RATE_LIMIT_INTERVAL 60 /* seconds (delay between successive attempts) */ #define DEFEND_INTERVAL 10 /* seconds (min. wait between defensive ARPs) */ /* AutoIP client states */ #define AUTOIP_STATE_OFF 0 #define AUTOIP_STATE_PROBING 1 #define AUTOIP_STATE_ANNOUNCING 2 #define AUTOIP_STATE_BOUND 3 struct autoip { ip_addr_t llipaddr; /* the currently selected, probed, announced or used LL IP-Address */ u8_t state; /* current AutoIP state machine state */ u8_t sent_num; /* sent number of probes or announces, dependent on state */ u16_t ttw; /* ticks to wait, tick is AUTOIP_TMR_INTERVAL long */ u8_t lastconflict; /* ticks until a conflict can be solved by defending */ u8_t tried_llipaddr; /* total number of probed/used Link Local IP-Addresses */ }; /** Init srand, has to be called before entering mainloop */ void autoip_init(void); /** Set a struct autoip allocated by the application to work with */ void autoip_set_struct(struct netif *netif, struct autoip *autoip); /** Start AutoIP client */ err_t autoip_start(struct netif *netif); /** Stop AutoIP client */ err_t autoip_stop(struct netif *netif); /** Handles every incoming ARP Packet, called by etharp_arp_input */ void autoip_arp_reply(struct netif *netif, struct etharp_hdr *hdr); /** Has to be called in loop every AUTOIP_TMR_INTERVAL milliseconds */ void autoip_tmr(void); /** Handle a possible change in the network configuration */ void autoip_network_changed(struct netif *netif); #ifdef __cplusplus } #endif #endif /* LWIP_AUTOIP */ #endif /* __LWIP_AUTOIP_H__ */ ================================================ FILE: Zelig/lwip/lwip/include/ipv4/lwip/icmp.h ================================================ /* * Copyright (c) 2001-2004 Swedish Institute of Computer Science. * All rights reserved. * * Redistribution and use in source and binary forms, with or without modification, * are permitted provided that the following conditions are met: * * 1. Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * 3. The name of the author may not be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT * SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT * OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING * IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY * OF SUCH DAMAGE. * * This file is part of the lwIP TCP/IP stack. * * Author: Adam Dunkels * */ #ifndef __LWIP_ICMP_H__ #define __LWIP_ICMP_H__ #include "lwip/opt.h" #include "lwip/pbuf.h" #include "lwip/ip_addr.h" #include "lwip/netif.h" #ifdef __cplusplus extern "C" { #endif #define ICMP_ER 0 /* echo reply */ #define ICMP_DUR 3 /* destination unreachable */ #define ICMP_SQ 4 /* source quench */ #define ICMP_RD 5 /* redirect */ #define ICMP_ECHO 8 /* echo */ #define ICMP_TE 11 /* time exceeded */ #define ICMP_PP 12 /* parameter problem */ #define ICMP_TS 13 /* timestamp */ #define ICMP_TSR 14 /* timestamp reply */ #define ICMP_IRQ 15 /* information request */ #define ICMP_IR 16 /* information reply */ enum icmp_dur_type { ICMP_DUR_NET = 0, /* net unreachable */ ICMP_DUR_HOST = 1, /* host unreachable */ ICMP_DUR_PROTO = 2, /* protocol unreachable */ ICMP_DUR_PORT = 3, /* port unreachable */ ICMP_DUR_FRAG = 4, /* fragmentation needed and DF set */ ICMP_DUR_SR = 5 /* source route failed */ }; enum icmp_te_type { ICMP_TE_TTL = 0, /* time to live exceeded in transit */ ICMP_TE_FRAG = 1 /* fragment reassembly time exceeded */ }; #ifdef PACK_STRUCT_USE_INCLUDES # include "arch/bpstruct.h" #endif /** This is the standard ICMP header only that the u32_t data * is splitted to two u16_t like ICMP echo needs it. * This header is also used for other ICMP types that do not * use the data part. */ PACK_STRUCT_BEGIN struct icmp_echo_hdr { PACK_STRUCT_FIELD(u8_t type); PACK_STRUCT_FIELD(u8_t code); PACK_STRUCT_FIELD(u16_t chksum); PACK_STRUCT_FIELD(u16_t id); PACK_STRUCT_FIELD(u16_t seqno); } PACK_STRUCT_STRUCT; PACK_STRUCT_END #ifdef PACK_STRUCT_USE_INCLUDES # include "arch/epstruct.h" #endif #define ICMPH_TYPE(hdr) ((hdr)->type) #define ICMPH_CODE(hdr) ((hdr)->code) /** Combines type and code to an u16_t */ #define ICMPH_TYPE_SET(hdr, t) ((hdr)->type = (t)) #define ICMPH_CODE_SET(hdr, c) ((hdr)->code = (c)) #if LWIP_ICMP /* don't build if not configured for use in lwipopts.h */ void icmp_input(struct pbuf *p, struct netif *inp); void icmp_dest_unreach(struct pbuf *p, enum icmp_dur_type t); void icmp_time_exceeded(struct pbuf *p, enum icmp_te_type t); #endif /* LWIP_ICMP */ #ifdef __cplusplus } #endif #endif /* __LWIP_ICMP_H__ */ ================================================ FILE: Zelig/lwip/lwip/include/ipv4/lwip/igmp.h ================================================ /* * Copyright (c) 2002 CITEL Technologies Ltd. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * 3. Neither the name of CITEL Technologies Ltd 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 CITEL TECHNOLOGIES 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 CITEL TECHNOLOGIES OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. * * This file is a contribution to the lwIP TCP/IP stack. * The Swedish Institute of Computer Science and Adam Dunkels * are specifically granted permission to redistribute this * source code. */ #ifndef __LWIP_IGMP_H__ #define __LWIP_IGMP_H__ #include "lwip/opt.h" #include "lwip/ip_addr.h" #include "lwip/netif.h" #include "lwip/pbuf.h" #if LWIP_IGMP /* don't build if not configured for use in lwipopts.h */ #ifdef __cplusplus extern "C" { #endif /* IGMP timer */ #define IGMP_TMR_INTERVAL 100 /* Milliseconds */ #define IGMP_V1_DELAYING_MEMBER_TMR (1000/IGMP_TMR_INTERVAL) #define IGMP_JOIN_DELAYING_MEMBER_TMR (500 /IGMP_TMR_INTERVAL) /* MAC Filter Actions, these are passed to a netif's * igmp_mac_filter callback function. */ #define IGMP_DEL_MAC_FILTER 0 #define IGMP_ADD_MAC_FILTER 1 /** * igmp group structure - there is * a list of groups for each interface * these should really be linked from the interface, but * if we keep them separate we will not affect the lwip original code * too much * * There will be a group for the all systems group address but this * will not run the state machine as it is used to kick off reports * from all the other groups */ struct igmp_group { /** next link */ struct igmp_group *next; /** interface on which the group is active */ struct netif *netif; /** multicast address */ ip_addr_t group_address; /** signifies we were the last person to report */ u8_t last_reporter_flag; /** current state of the group */ u8_t group_state; /** timer for reporting, negative is OFF */ u16_t timer; /** counter of simultaneous uses */ u8_t use; }; /* Prototypes */ void igmp_init(void); err_t igmp_start(struct netif *netif); err_t igmp_stop(struct netif *netif); void igmp_report_groups(struct netif *netif); struct igmp_group *igmp_lookfor_group(struct netif *ifp, ip_addr_t *addr); void igmp_input(struct pbuf *p, struct netif *inp, ip_addr_t *dest); err_t igmp_joingroup(ip_addr_t *ifaddr, ip_addr_t *groupaddr); err_t igmp_leavegroup(ip_addr_t *ifaddr, ip_addr_t *groupaddr); void igmp_tmr(void); #ifdef __cplusplus } #endif #endif /* LWIP_IGMP */ #endif /* __LWIP_IGMP_H__ */ ================================================ FILE: Zelig/lwip/lwip/include/ipv4/lwip/inet.h ================================================ /* * Copyright (c) 2001-2004 Swedish Institute of Computer Science. * All rights reserved. * * Redistribution and use in source and binary forms, with or without modification, * are permitted provided that the following conditions are met: * * 1. Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * 3. The name of the author may not be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT * SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT * OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING * IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY * OF SUCH DAMAGE. * * This file is part of the lwIP TCP/IP stack. * * Author: Adam Dunkels * */ #ifndef __LWIP_INET_H__ #define __LWIP_INET_H__ #include "lwip/opt.h" #include "lwip/def.h" #include "lwip/ip_addr.h" #ifdef __cplusplus extern "C" { #endif /** For compatibility with BSD code */ struct in_addr { u32_t s_addr; }; /** 255.255.255.255 */ #define INADDR_NONE IPADDR_NONE /** 127.0.0.1 */ #define INADDR_LOOPBACK IPADDR_LOOPBACK /** 0.0.0.0 */ #define INADDR_ANY IPADDR_ANY /** 255.255.255.255 */ #define INADDR_BROADCAST IPADDR_BROADCAST /* Definitions of the bits in an Internet address integer. On subnets, host and network parts are found according to the subnet mask, not these masks. */ #define IN_CLASSA(a) IP_CLASSA(a) #define IN_CLASSA_NET IP_CLASSA_NET #define IN_CLASSA_NSHIFT IP_CLASSA_NSHIFT #define IN_CLASSA_HOST IP_CLASSA_HOST #define IN_CLASSA_MAX IP_CLASSA_MAX #define IN_CLASSB(b) IP_CLASSB(b) #define IN_CLASSB_NET IP_CLASSB_NET #define IN_CLASSB_NSHIFT IP_CLASSB_NSHIFT #define IN_CLASSB_HOST IP_CLASSB_HOST #define IN_CLASSB_MAX IP_CLASSB_MAX #define IN_CLASSC(c) IP_CLASSC(c) #define IN_CLASSC_NET IP_CLASSC_NET #define IN_CLASSC_NSHIFT IP_CLASSC_NSHIFT #define IN_CLASSC_HOST IP_CLASSC_HOST #define IN_CLASSC_MAX IP_CLASSC_MAX #define IN_CLASSD(d) IP_CLASSD(d) #define IN_CLASSD_NET IP_CLASSD_NET /* These ones aren't really */ #define IN_CLASSD_NSHIFT IP_CLASSD_NSHIFT /* net and host fields, but */ #define IN_CLASSD_HOST IP_CLASSD_HOST /* routing needn't know. */ #define IN_CLASSD_MAX IP_CLASSD_MAX #define IN_MULTICAST(a) IP_MULTICAST(a) #define IN_EXPERIMENTAL(a) IP_EXPERIMENTAL(a) #define IN_BADCLASS(a) IP_BADCLASS(a) #define IN_LOOPBACKNET IP_LOOPBACKNET #define inet_addr_from_ipaddr(target_inaddr, source_ipaddr) ((target_inaddr)->s_addr = ip4_addr_get_u32(source_ipaddr)) #define inet_addr_to_ipaddr(target_ipaddr, source_inaddr) (ip4_addr_set_u32(target_ipaddr, (source_inaddr)->s_addr)) /* ATTENTION: the next define only works because both s_addr and ip_addr_t are an u32_t effectively! */ #define inet_addr_to_ipaddr_p(target_ipaddr_p, source_inaddr) ((target_ipaddr_p) = (ip_addr_t*)&((source_inaddr)->s_addr)) /* directly map this to the lwip internal functions */ #define inet_addr(cp) ipaddr_addr(cp) #define inet_aton(cp, addr) ipaddr_aton(cp, (ip_addr_t*)addr) #define inet_ntoa(addr) ipaddr_ntoa((ip_addr_t*)&(addr)) #define inet_ntoa_r(addr, buf, buflen) ipaddr_ntoa_r((ip_addr_t*)&(addr), buf, buflen) #ifdef __cplusplus } #endif #endif /* __LWIP_INET_H__ */ ================================================ FILE: Zelig/lwip/lwip/include/ipv4/lwip/inet_chksum.h ================================================ /* * Copyright (c) 2001-2004 Swedish Institute of Computer Science. * All rights reserved. * * Redistribution and use in source and binary forms, with or without modification, * are permitted provided that the following conditions are met: * * 1. Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * 3. The name of the author may not be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT * SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT * OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING * IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY * OF SUCH DAMAGE. * * This file is part of the lwIP TCP/IP stack. * * Author: Adam Dunkels * */ #ifndef __LWIP_INET_CHKSUM_H__ #define __LWIP_INET_CHKSUM_H__ #include "lwip/opt.h" #include "lwip/pbuf.h" #include "lwip/ip_addr.h" /** Swap the bytes in an u16_t: much like htons() for little-endian */ #ifndef SWAP_BYTES_IN_WORD #if LWIP_PLATFORM_BYTESWAP && (BYTE_ORDER == LITTLE_ENDIAN) /* little endian and PLATFORM_BYTESWAP defined */ #define SWAP_BYTES_IN_WORD(w) LWIP_PLATFORM_HTONS(w) #else /* LWIP_PLATFORM_BYTESWAP && (BYTE_ORDER == LITTLE_ENDIAN) */ /* can't use htons on big endian (or PLATFORM_BYTESWAP not defined)... */ #define SWAP_BYTES_IN_WORD(w) (((w) & 0xff) << 8) | (((w) & 0xff00) >> 8) #endif /* LWIP_PLATFORM_BYTESWAP && (BYTE_ORDER == LITTLE_ENDIAN)*/ #endif /* SWAP_BYTES_IN_WORD */ /** Split an u32_t in two u16_ts and add them up */ #ifndef FOLD_U32T #define FOLD_U32T(u) (((u) >> 16) + ((u) & 0x0000ffffUL)) #endif #if LWIP_CHECKSUM_ON_COPY /** Function-like macro: same as MEMCPY but returns the checksum of copied data as u16_t */ #ifndef LWIP_CHKSUM_COPY #define LWIP_CHKSUM_COPY(dst, src, len) lwip_chksum_copy(dst, src, len) #ifndef LWIP_CHKSUM_COPY_ALGORITHM #define LWIP_CHKSUM_COPY_ALGORITHM 1 #endif /* LWIP_CHKSUM_COPY_ALGORITHM */ #endif /* LWIP_CHKSUM_COPY */ #else /* LWIP_CHECKSUM_ON_COPY */ #define LWIP_CHKSUM_COPY_ALGORITHM 0 #endif /* LWIP_CHECKSUM_ON_COPY */ #ifdef __cplusplus extern "C" { #endif u16_t inet_chksum(void *dataptr, u16_t len); u16_t inet_chksum_pbuf(struct pbuf *p); u16_t inet_chksum_pseudo(struct pbuf *p, ip_addr_t *src, ip_addr_t *dest, u8_t proto, u16_t proto_len); u16_t inet_chksum_pseudo_partial(struct pbuf *p, ip_addr_t *src, ip_addr_t *dest, u8_t proto, u16_t proto_len, u16_t chksum_len); #if LWIP_CHKSUM_COPY_ALGORITHM u16_t lwip_chksum_copy(void *dst, const void *src, u16_t len); #endif /* LWIP_CHKSUM_COPY_ALGORITHM */ #ifdef __cplusplus } #endif #endif /* __LWIP_INET_H__ */ ================================================ FILE: Zelig/lwip/lwip/include/ipv4/lwip/ip.h ================================================ /* * Copyright (c) 2001-2004 Swedish Institute of Computer Science. * All rights reserved. * * Redistribution and use in source and binary forms, with or without modification, * are permitted provided that the following conditions are met: * * 1. Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * 3. The name of the author may not be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT * SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT * OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING * IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY * OF SUCH DAMAGE. * * This file is part of the lwIP TCP/IP stack. * * Author: Adam Dunkels * */ #ifndef __LWIP_IP_H__ #define __LWIP_IP_H__ #include "lwip/opt.h" #include "lwip/def.h" #include "lwip/pbuf.h" #include "lwip/ip_addr.h" #include "lwip/err.h" #include "lwip/netif.h" #ifdef __cplusplus extern "C" { #endif /** Currently, the function ip_output_if_opt() is only used with IGMP */ #define IP_OPTIONS_SEND LWIP_IGMP #define IP_HLEN 20 #define IP_PROTO_ICMP 1 #define IP_PROTO_IGMP 2 #define IP_PROTO_UDP 17 #define IP_PROTO_UDPLITE 136 #define IP_PROTO_TCP 6 /* This is passed as the destination address to ip_output_if (not to ip_output), meaning that an IP header already is constructed in the pbuf. This is used when TCP retransmits. */ #ifdef IP_HDRINCL #undef IP_HDRINCL #endif /* IP_HDRINCL */ #define IP_HDRINCL NULL #if LWIP_NETIF_HWADDRHINT #define IP_PCB_ADDRHINT ;u8_t addr_hint #else #define IP_PCB_ADDRHINT #endif /* LWIP_NETIF_HWADDRHINT */ /* This is the common part of all PCB types. It needs to be at the beginning of a PCB type definition. It is located here so that changes to this common part are made in one location instead of having to change all PCB structs. */ #define IP_PCB \ /* ip addresses in network byte order */ \ ip_addr_t local_ip; \ ip_addr_t remote_ip; \ /* Socket options */ \ u8_t so_options; \ /* Type Of Service */ \ u8_t tos; \ /* Time To Live */ \ u8_t ttl \ /* link layer address resolution hint */ \ IP_PCB_ADDRHINT struct ip_pcb { /* Common members of all PCB types */ IP_PCB; }; /* * Option flags per-socket. These are the same like SO_XXX. */ /*#define SOF_DEBUG (u8_t)0x01U Unimplemented: turn on debugging info recording */ #define SOF_ACCEPTCONN (u8_t)0x02U /* socket has had listen() */ #define SOF_REUSEADDR (u8_t)0x04U /* allow local address reuse */ #define SOF_KEEPALIVE (u8_t)0x08U /* keep connections alive */ /*#define SOF_DONTROUTE (u8_t)0x10U Unimplemented: just use interface addresses */ #define SOF_BROADCAST (u8_t)0x20U /* permit to send and to receive broadcast messages (see IP_SOF_BROADCAST option) */ /*#define SOF_USELOOPBACK (u8_t)0x40U Unimplemented: bypass hardware when possible */ #define SOF_LINGER (u8_t)0x80U /* linger on close if data present */ /*#define SOF_OOBINLINE (u16_t)0x0100U Unimplemented: leave received OOB data in line */ /*#define SOF_REUSEPORT (u16_t)0x0200U Unimplemented: allow local address & port reuse */ /* These flags are inherited (e.g. from a listen-pcb to a connection-pcb): */ #define SOF_INHERITED (SOF_REUSEADDR|SOF_KEEPALIVE|SOF_LINGER/*|SOF_DEBUG|SOF_DONTROUTE|SOF_OOBINLINE*/) #ifdef PACK_STRUCT_USE_INCLUDES # include "arch/bpstruct.h" #endif PACK_STRUCT_BEGIN struct ip_hdr { /* version / header length / type of service */ PACK_STRUCT_FIELD(u16_t _v_hl_tos); /* total length */ PACK_STRUCT_FIELD(u16_t _len); /* identification */ PACK_STRUCT_FIELD(u16_t _id); /* fragment offset field */ PACK_STRUCT_FIELD(u16_t _offset); #define IP_RF 0x8000U /* reserved fragment flag */ #define IP_DF 0x4000U /* dont fragment flag */ #define IP_MF 0x2000U /* more fragments flag */ #define IP_OFFMASK 0x1fffU /* mask for fragmenting bits */ /* time to live */ PACK_STRUCT_FIELD(u8_t _ttl); /* protocol*/ PACK_STRUCT_FIELD(u8_t _proto); /* checksum */ PACK_STRUCT_FIELD(u16_t _chksum); /* source and destination IP addresses */ PACK_STRUCT_FIELD(ip_addr_p_t src); PACK_STRUCT_FIELD(ip_addr_p_t dest); } PACK_STRUCT_STRUCT; PACK_STRUCT_END #ifdef PACK_STRUCT_USE_INCLUDES # include "arch/epstruct.h" #endif #define IPH_V(hdr) (ntohs((hdr)->_v_hl_tos) >> 12) #define IPH_HL(hdr) ((ntohs((hdr)->_v_hl_tos) >> 8) & 0x0f) #define IPH_TOS(hdr) (ntohs((hdr)->_v_hl_tos) & 0xff) #define IPH_LEN(hdr) ((hdr)->_len) #define IPH_ID(hdr) ((hdr)->_id) #define IPH_OFFSET(hdr) ((hdr)->_offset) #define IPH_TTL(hdr) ((hdr)->_ttl) #define IPH_PROTO(hdr) ((hdr)->_proto) #define IPH_CHKSUM(hdr) ((hdr)->_chksum) #define IPH_VHLTOS_SET(hdr, v, hl, tos) (hdr)->_v_hl_tos = (htons(((v) << 12) | ((hl) << 8) | (tos))) #define IPH_LEN_SET(hdr, len) (hdr)->_len = (len) #define IPH_ID_SET(hdr, id) (hdr)->_id = (id) #define IPH_OFFSET_SET(hdr, off) (hdr)->_offset = (off) #define IPH_TTL_SET(hdr, ttl) (hdr)->_ttl = (u8_t)(ttl) #define IPH_PROTO_SET(hdr, proto) (hdr)->_proto = (u8_t)(proto) #define IPH_CHKSUM_SET(hdr, chksum) (hdr)->_chksum = (chksum) /** The interface that provided the packet for the current callback invocation. */ extern struct netif *current_netif; /** Header of the input packet currently being processed. */ extern const struct ip_hdr *current_header; /** Source IP address of current_header */ extern ip_addr_t current_iphdr_src; /** Destination IP address of current_header */ extern ip_addr_t current_iphdr_dest; #define ip_init() /* Compatibility define, not init needed. */ struct netif *ip_route(ip_addr_t *dest); err_t ip_input(struct pbuf *p, struct netif *inp); err_t ip_output(struct pbuf *p, ip_addr_t *src, ip_addr_t *dest, u8_t ttl, u8_t tos, u8_t proto); err_t ip_output_if(struct pbuf *p, ip_addr_t *src, ip_addr_t *dest, u8_t ttl, u8_t tos, u8_t proto, struct netif *netif); #if LWIP_NETIF_HWADDRHINT err_t ip_output_hinted(struct pbuf *p, ip_addr_t *src, ip_addr_t *dest, u8_t ttl, u8_t tos, u8_t proto, u8_t *addr_hint); #endif /* LWIP_NETIF_HWADDRHINT */ #if IP_OPTIONS_SEND err_t ip_output_if_opt(struct pbuf *p, ip_addr_t *src, ip_addr_t *dest, u8_t ttl, u8_t tos, u8_t proto, struct netif *netif, void *ip_options, u16_t optlen); #endif /* IP_OPTIONS_SEND */ /** Get the interface that received the current packet. * This function must only be called from a receive callback (udp_recv, * raw_recv, tcp_accept). It will return NULL otherwise. */ #define ip_current_netif() (current_netif) /** Get the IP header of the current packet. * This function must only be called from a receive callback (udp_recv, * raw_recv, tcp_accept). It will return NULL otherwise. */ #define ip_current_header() (current_header) /** Source IP address of current_header */ #define ip_current_src_addr() (¤t_iphdr_src) /** Destination IP address of current_header */ #define ip_current_dest_addr() (¤t_iphdr_dest) #if IP_DEBUG void ip_debug_print(struct pbuf *p); #else #define ip_debug_print(p) #endif /* IP_DEBUG */ #ifdef __cplusplus } #endif #endif /* __LWIP_IP_H__ */ ================================================ FILE: Zelig/lwip/lwip/include/ipv4/lwip/ip_addr.h ================================================ /* * Copyright (c) 2001-2004 Swedish Institute of Computer Science. * All rights reserved. * * Redistribution and use in source and binary forms, with or without modification, * are permitted provided that the following conditions are met: * * 1. Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * 3. The name of the author may not be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT * SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT * OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING * IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY * OF SUCH DAMAGE. * * This file is part of the lwIP TCP/IP stack. * * Author: Adam Dunkels * */ #ifndef __LWIP_IP_ADDR_H__ #define __LWIP_IP_ADDR_H__ #include "lwip/opt.h" #include "lwip/def.h" #ifdef __cplusplus extern "C" { #endif /* This is the aligned version of ip_addr_t, used as local variable, on the stack, etc. */ struct ip_addr { u32_t addr; }; /* This is the packed version of ip_addr_t, used in network headers that are itself packed */ #ifdef PACK_STRUCT_USE_INCLUDES # include "arch/bpstruct.h" #endif PACK_STRUCT_BEGIN struct ip_addr_packed { PACK_STRUCT_FIELD(u32_t addr); } PACK_STRUCT_STRUCT; PACK_STRUCT_END #ifdef PACK_STRUCT_USE_INCLUDES # include "arch/epstruct.h" #endif /** ip_addr_t uses a struct for convenience only, so that the same defines can * operate both on ip_addr_t as well as on ip_addr_p_t. */ typedef struct ip_addr ip_addr_t; typedef struct ip_addr_packed ip_addr_p_t; /* * struct ipaddr2 is used in the definition of the ARP packet format in * order to support compilers that don't have structure packing. */ #ifdef PACK_STRUCT_USE_INCLUDES # include "arch/bpstruct.h" #endif PACK_STRUCT_BEGIN struct ip_addr2 { PACK_STRUCT_FIELD(u16_t addrw[2]); } PACK_STRUCT_STRUCT; PACK_STRUCT_END #ifdef PACK_STRUCT_USE_INCLUDES # include "arch/epstruct.h" #endif /* Forward declaration to not include netif.h */ struct netif; extern const ip_addr_t ip_addr_any; extern const ip_addr_t ip_addr_broadcast; /** IP_ADDR_ can be used as a fixed IP address * for the wildcard and the broadcast address */ #define IP_ADDR_ANY ((ip_addr_t *)&ip_addr_any) #define IP_ADDR_BROADCAST ((ip_addr_t *)&ip_addr_broadcast) /** 255.255.255.255 */ #define IPADDR_NONE ((u32_t)0xffffffffUL) /** 127.0.0.1 */ #define IPADDR_LOOPBACK ((u32_t)0x7f000001UL) /** 0.0.0.0 */ #define IPADDR_ANY ((u32_t)0x00000000UL) /** 255.255.255.255 */ #define IPADDR_BROADCAST ((u32_t)0xffffffffUL) /* Definitions of the bits in an Internet address integer. On subnets, host and network parts are found according to the subnet mask, not these masks. */ #define IP_CLASSA(a) ((((u32_t)(a)) & 0x80000000UL) == 0) #define IP_CLASSA_NET 0xff000000 #define IP_CLASSA_NSHIFT 24 #define IP_CLASSA_HOST (0xffffffff & ~IP_CLASSA_NET) #define IP_CLASSA_MAX 128 #define IP_CLASSB(a) ((((u32_t)(a)) & 0xc0000000UL) == 0x80000000UL) #define IP_CLASSB_NET 0xffff0000 #define IP_CLASSB_NSHIFT 16 #define IP_CLASSB_HOST (0xffffffff & ~IP_CLASSB_NET) #define IP_CLASSB_MAX 65536 #define IP_CLASSC(a) ((((u32_t)(a)) & 0xe0000000UL) == 0xc0000000UL) #define IP_CLASSC_NET 0xffffff00 #define IP_CLASSC_NSHIFT 8 #define IP_CLASSC_HOST (0xffffffff & ~IP_CLASSC_NET) #define IP_CLASSD(a) (((u32_t)(a) & 0xf0000000UL) == 0xe0000000UL) #define IP_CLASSD_NET 0xf0000000 /* These ones aren't really */ #define IP_CLASSD_NSHIFT 28 /* net and host fields, but */ #define IP_CLASSD_HOST 0x0fffffff /* routing needn't know. */ #define IP_MULTICAST(a) IP_CLASSD(a) #define IP_EXPERIMENTAL(a) (((u32_t)(a) & 0xf0000000UL) == 0xf0000000UL) #define IP_BADCLASS(a) (((u32_t)(a) & 0xf0000000UL) == 0xf0000000UL) #define IP_LOOPBACKNET 127 /* official! */ #if BYTE_ORDER == BIG_ENDIAN /** Set an IP address given by the four byte-parts */ #define IP4_ADDR(ipaddr, a,b,c,d) \ (ipaddr)->addr = ((u32_t)((a) & 0xff) << 24) | \ ((u32_t)((b) & 0xff) << 16) | \ ((u32_t)((c) & 0xff) << 8) | \ (u32_t)((d) & 0xff) #else /** Set an IP address given by the four byte-parts. Little-endian version that prevents the use of htonl. */ #define IP4_ADDR(ipaddr, a,b,c,d) \ (ipaddr)->addr = ((u32_t)((d) & 0xff) << 24) | \ ((u32_t)((c) & 0xff) << 16) | \ ((u32_t)((b) & 0xff) << 8) | \ (u32_t)((a) & 0xff) #endif /** MEMCPY-like copying of IP addresses where addresses are known to be * 16-bit-aligned if the port is correctly configured (so a port could define * this to copying 2 u16_t's) - no NULL-pointer-checking needed. */ #ifndef IPADDR2_COPY #define IPADDR2_COPY(dest, src) SMEMCPY(dest, src, sizeof(ip_addr_t)) #endif /** Copy IP address - faster than ip_addr_set: no NULL check */ #define ip_addr_copy(dest, src) ((dest).addr = (src).addr) /** Safely copy one IP address to another (src may be NULL) */ #define ip_addr_set(dest, src) ((dest)->addr = \ ((src) == NULL ? 0 : \ (src)->addr)) /** Set complete address to zero */ #define ip_addr_set_zero(ipaddr) ((ipaddr)->addr = 0) /** Set address to IPADDR_ANY (no need for htonl()) */ #define ip_addr_set_any(ipaddr) ((ipaddr)->addr = IPADDR_ANY) /** Set address to loopback address */ #define ip_addr_set_loopback(ipaddr) ((ipaddr)->addr = PP_HTONL(IPADDR_LOOPBACK)) /** Safely copy one IP address to another and change byte order * from host- to network-order. */ #define ip_addr_set_hton(dest, src) ((dest)->addr = \ ((src) == NULL ? 0:\ htonl((src)->addr))) /** IPv4 only: set the IP address given as an u32_t */ #define ip4_addr_set_u32(dest_ipaddr, src_u32) ((dest_ipaddr)->addr = (src_u32)) /** IPv4 only: get the IP address as an u32_t */ #define ip4_addr_get_u32(src_ipaddr) ((src_ipaddr)->addr) /** Get the network address by combining host address with netmask */ #define ip_addr_get_network(target, host, netmask) ((target)->addr = ((host)->addr) & ((netmask)->addr)) /** * Determine if two address are on the same network. * * @arg addr1 IP address 1 * @arg addr2 IP address 2 * @arg mask network identifier mask * @return !0 if the network identifiers of both address match */ #define ip_addr_netcmp(addr1, addr2, mask) (((addr1)->addr & \ (mask)->addr) == \ ((addr2)->addr & \ (mask)->addr)) #define ip_addr_cmp(addr1, addr2) ((addr1)->addr == (addr2)->addr) #define ip_addr_isany(addr1) ((addr1) == NULL || (addr1)->addr == IPADDR_ANY) #define ip_addr_isbroadcast(ipaddr, netif) ip4_addr_isbroadcast((ipaddr)->addr, (netif)) u8_t ip4_addr_isbroadcast(u32_t addr, const struct netif *netif); #define ip_addr_netmask_valid(netmask) ip4_addr_netmask_valid((netmask)->addr) u8_t ip4_addr_netmask_valid(u32_t netmask); #define ip_addr_ismulticast(addr1) (((addr1)->addr & PP_HTONL(0xf0000000UL)) == PP_HTONL(0xe0000000UL)) #define ip_addr_islinklocal(addr1) (((addr1)->addr & PP_HTONL(0xffff0000UL)) == PP_HTONL(0xa9fe0000UL)) #define ip_addr_debug_print(debug, ipaddr) \ LWIP_DEBUGF(debug, ("%"U16_F".%"U16_F".%"U16_F".%"U16_F, \ ipaddr != NULL ? ip4_addr1_16(ipaddr) : 0, \ ipaddr != NULL ? ip4_addr2_16(ipaddr) : 0, \ ipaddr != NULL ? ip4_addr3_16(ipaddr) : 0, \ ipaddr != NULL ? ip4_addr4_16(ipaddr) : 0)) /* Get one byte from the 4-byte address */ #define ip4_addr1(ipaddr) (((u8_t*)(ipaddr))[0]) #define ip4_addr2(ipaddr) (((u8_t*)(ipaddr))[1]) #define ip4_addr3(ipaddr) (((u8_t*)(ipaddr))[2]) #define ip4_addr4(ipaddr) (((u8_t*)(ipaddr))[3]) /* These are cast to u16_t, with the intent that they are often arguments * to printf using the U16_F format from cc.h. */ #define ip4_addr1_16(ipaddr) ((u16_t)ip4_addr1(ipaddr)) #define ip4_addr2_16(ipaddr) ((u16_t)ip4_addr2(ipaddr)) #define ip4_addr3_16(ipaddr) ((u16_t)ip4_addr3(ipaddr)) #define ip4_addr4_16(ipaddr) ((u16_t)ip4_addr4(ipaddr)) /** For backwards compatibility */ #define ip_ntoa(ipaddr) ipaddr_ntoa(ipaddr) u32_t ipaddr_addr(const char *cp); int ipaddr_aton(const char *cp, ip_addr_t *addr); /** returns ptr to static buffer; not reentrant! */ char *ipaddr_ntoa(const ip_addr_t *addr); char *ipaddr_ntoa_r(const ip_addr_t *addr, char *buf, int buflen); #ifdef __cplusplus } #endif #endif /* __LWIP_IP_ADDR_H__ */ ================================================ FILE: Zelig/lwip/lwip/include/ipv4/lwip/ip_frag.h ================================================ /* * Copyright (c) 2001-2004 Swedish Institute of Computer Science. * All rights reserved. * * Redistribution and use in source and binary forms, with or without modification, * are permitted provided that the following conditions are met: * * 1. Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * 3. The name of the author may not be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT * SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT * OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING * IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY * OF SUCH DAMAGE. * * This file is part of the lwIP TCP/IP stack. * * Author: Jani Monoses * */ #ifndef __LWIP_IP_FRAG_H__ #define __LWIP_IP_FRAG_H__ #include "lwip/opt.h" #include "lwip/err.h" #include "lwip/pbuf.h" #include "lwip/netif.h" #include "lwip/ip_addr.h" #include "lwip/ip.h" #ifdef __cplusplus extern "C" { #endif #if IP_REASSEMBLY /* The IP reassembly timer interval in milliseconds. */ #define IP_TMR_INTERVAL 1000 /* IP reassembly helper struct. * This is exported because memp needs to know the size. */ struct ip_reassdata { struct ip_reassdata *next; struct pbuf *p; struct ip_hdr iphdr; u16_t datagram_len; u8_t flags; u8_t timer; }; void ip_reass_init(void); void ip_reass_tmr(void); struct pbuf * ip_reass(struct pbuf *p); #endif /* IP_REASSEMBLY */ #if IP_FRAG #if !IP_FRAG_USES_STATIC_BUF && !LWIP_NETIF_TX_SINGLE_PBUF /** A custom pbuf that holds a reference to another pbuf, which is freed * when this custom pbuf is freed. This is used to create a custom PBUF_REF * that points into the original pbuf. */ struct pbuf_custom_ref { /** 'base class' */ struct pbuf_custom pc; /** pointer to the original pbuf that is referenced */ struct pbuf *original; }; #endif /* !IP_FRAG_USES_STATIC_BUF && !LWIP_NETIF_TX_SINGLE_PBUF */ err_t ip_frag(struct pbuf *p, struct netif *netif, ip_addr_t *dest); #endif /* IP_FRAG */ #ifdef __cplusplus } #endif #endif /* __LWIP_IP_FRAG_H__ */ ================================================ FILE: Zelig/lwip/lwip/include/lwip/api.h ================================================ /* * Copyright (c) 2001-2004 Swedish Institute of Computer Science. * All rights reserved. * * Redistribution and use in source and binary forms, with or without modification, * are permitted provided that the following conditions are met: * * 1. Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * 3. The name of the author may not be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT * SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT * OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING * IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY * OF SUCH DAMAGE. * * This file is part of the lwIP TCP/IP stack. * * Author: Adam Dunkels * */ #ifndef __LWIP_API_H__ #define __LWIP_API_H__ #include "lwip/opt.h" #if LWIP_NETCONN /* don't build if not configured for use in lwipopts.h */ #include /* for size_t */ #include "lwip/netbuf.h" #include "lwip/sys.h" #include "lwip/ip_addr.h" #include "lwip/err.h" #ifdef __cplusplus extern "C" { #endif /* Throughout this file, IP addresses and port numbers are expected to be in * the same byte order as in the corresponding pcb. */ /* Flags for netconn_write (u8_t) */ #define NETCONN_NOFLAG 0x00 #define NETCONN_NOCOPY 0x00 /* Only for source code compatibility */ #define NETCONN_COPY 0x01 #define NETCONN_MORE 0x02 #define NETCONN_DONTBLOCK 0x04 /* Flags for struct netconn.flags (u8_t) */ /** TCP: when data passed to netconn_write doesn't fit into the send buffer, this temporarily stores whether to wake up the original application task if data couldn't be sent in the first try. */ #define NETCONN_FLAG_WRITE_DELAYED 0x01 /** Should this netconn avoid blocking? */ #define NETCONN_FLAG_NON_BLOCKING 0x02 /** Was the last connect action a non-blocking one? */ #define NETCONN_FLAG_IN_NONBLOCKING_CONNECT 0x04 /** If this is set, a TCP netconn must call netconn_recved() to update the TCP receive window (done automatically if not set). */ #define NETCONN_FLAG_NO_AUTO_RECVED 0x08 /** If a nonblocking write has been rejected before, poll_tcp needs to check if the netconn is writable again */ #define NETCONN_FLAG_CHECK_WRITESPACE 0x10 /* Helpers to process several netconn_types by the same code */ #define NETCONNTYPE_GROUP(t) (t&0xF0) #define NETCONNTYPE_DATAGRAM(t) (t&0xE0) /** Protocol family and type of the netconn */ enum netconn_type { NETCONN_INVALID = 0, /* NETCONN_TCP Group */ NETCONN_TCP = 0x10, /* NETCONN_UDP Group */ NETCONN_UDP = 0x20, NETCONN_UDPLITE = 0x21, NETCONN_UDPNOCHKSUM= 0x22, /* NETCONN_RAW Group */ NETCONN_RAW = 0x40 }; /** Current state of the netconn. Non-TCP netconns are always * in state NETCONN_NONE! */ enum netconn_state { NETCONN_NONE, NETCONN_WRITE, NETCONN_LISTEN, NETCONN_CONNECT, NETCONN_CLOSE }; /** Use to inform the callback function about changes */ enum netconn_evt { NETCONN_EVT_RCVPLUS, NETCONN_EVT_RCVMINUS, NETCONN_EVT_SENDPLUS, NETCONN_EVT_SENDMINUS, NETCONN_EVT_ERROR }; #if LWIP_IGMP /** Used for netconn_join_leave_group() */ enum netconn_igmp { NETCONN_JOIN, NETCONN_LEAVE }; #endif /* LWIP_IGMP */ /* forward-declare some structs to avoid to include their headers */ struct ip_pcb; struct tcp_pcb; struct udp_pcb; struct raw_pcb; struct netconn; struct api_msg_msg; /** A callback prototype to inform about events for a netconn */ typedef void (* netconn_callback)(struct netconn *, enum netconn_evt, u16_t len); /** A netconn descriptor */ struct netconn { /** type of the netconn (TCP, UDP or RAW) */ enum netconn_type type; /** current state of the netconn */ enum netconn_state state; /** the lwIP internal protocol control block */ union { struct ip_pcb *ip; struct tcp_pcb *tcp; struct udp_pcb *udp; struct raw_pcb *raw; } pcb; /** the last error this netconn had */ err_t last_err; /** sem that is used to synchroneously execute functions in the core context */ sys_sem_t op_completed; /** mbox where received packets are stored until they are fetched by the netconn application thread (can grow quite big) */ sys_mbox_t recvmbox; #if LWIP_TCP /** mbox where new connections are stored until processed by the application thread */ sys_mbox_t acceptmbox; #endif /* LWIP_TCP */ /** only used for socket layer */ #if LWIP_SOCKET int socket; #endif /* LWIP_SOCKET */ #if LWIP_SO_RCVTIMEO /** timeout to wait for new data to be received (or connections to arrive for listening netconns) */ int recv_timeout; #endif /* LWIP_SO_RCVTIMEO */ #if LWIP_SO_RCVBUF /** maximum amount of bytes queued in recvmbox not used for TCP: adjust TCP_WND instead! */ int recv_bufsize; /** number of bytes currently in recvmbox to be received, tested against recv_bufsize to limit bytes on recvmbox for UDP and RAW, used for FIONREAD */ s16_t recv_avail; #endif /* LWIP_SO_RCVBUF */ /** flags holding more netconn-internal state, see NETCONN_FLAG_* defines */ u8_t flags; #if LWIP_TCP /** TCP: when data passed to netconn_write doesn't fit into the send buffer, this temporarily stores how much is already sent. */ size_t write_offset; /** TCP: when data passed to netconn_write doesn't fit into the send buffer, this temporarily stores the message. Also used during connect and close. */ struct api_msg_msg *current_msg; #endif /* LWIP_TCP */ /** A callback function that is informed about events for this netconn */ netconn_callback callback; }; /** Register an Network connection event */ #define API_EVENT(c,e,l) if (c->callback) { \ (*c->callback)(c, e, l); \ } /** Set conn->last_err to err but don't overwrite fatal errors */ #define NETCONN_SET_SAFE_ERR(conn, err) do { \ SYS_ARCH_DECL_PROTECT(lev); \ SYS_ARCH_PROTECT(lev); \ if (!ERR_IS_FATAL((conn)->last_err)) { \ (conn)->last_err = err; \ } \ SYS_ARCH_UNPROTECT(lev); \ } while(0); /* Network connection functions: */ #define netconn_new(t) netconn_new_with_proto_and_callback(t, 0, NULL) #define netconn_new_with_callback(t, c) netconn_new_with_proto_and_callback(t, 0, c) struct netconn *netconn_new_with_proto_and_callback(enum netconn_type t, u8_t proto, netconn_callback callback); err_t netconn_delete(struct netconn *conn); /** Get the type of a netconn (as enum netconn_type). */ #define netconn_type(conn) (conn->type) err_t netconn_getaddr(struct netconn *conn, ip_addr_t *addr, u16_t *port, u8_t local); #define netconn_peer(c,i,p) netconn_getaddr(c,i,p,0) #define netconn_addr(c,i,p) netconn_getaddr(c,i,p,1) err_t netconn_bind(struct netconn *conn, ip_addr_t *addr, u16_t port); err_t netconn_connect(struct netconn *conn, ip_addr_t *addr, u16_t port); err_t netconn_disconnect (struct netconn *conn); err_t netconn_listen_with_backlog(struct netconn *conn, u8_t backlog); #define netconn_listen(conn) netconn_listen_with_backlog(conn, TCP_DEFAULT_LISTEN_BACKLOG) err_t netconn_accept(struct netconn *conn, struct netconn **new_conn); err_t netconn_recv(struct netconn *conn, struct netbuf **new_buf); err_t netconn_recv_tcp_pbuf(struct netconn *conn, struct pbuf **new_buf); void netconn_recved(struct netconn *conn, u32_t length); err_t netconn_sendto(struct netconn *conn, struct netbuf *buf, ip_addr_t *addr, u16_t port); err_t netconn_send(struct netconn *conn, struct netbuf *buf); err_t netconn_write(struct netconn *conn, const void *dataptr, size_t size, u8_t apiflags); err_t netconn_close(struct netconn *conn); err_t netconn_shutdown(struct netconn *conn, u8_t shut_rx, u8_t shut_tx); #if LWIP_IGMP err_t netconn_join_leave_group(struct netconn *conn, ip_addr_t *multiaddr, ip_addr_t *netif_addr, enum netconn_igmp join_or_leave); #endif /* LWIP_IGMP */ #if LWIP_DNS err_t netconn_gethostbyname(const char *name, ip_addr_t *addr); #endif /* LWIP_DNS */ #define netconn_err(conn) ((conn)->last_err) #define netconn_recv_bufsize(conn) ((conn)->recv_bufsize) /** Set the blocking status of netconn calls (@todo: write/send is missing) */ #define netconn_set_nonblocking(conn, val) do { if(val) { \ (conn)->flags |= NETCONN_FLAG_NON_BLOCKING; \ } else { \ (conn)->flags &= ~ NETCONN_FLAG_NON_BLOCKING; }} while(0) /** Get the blocking status of netconn calls (@todo: write/send is missing) */ #define netconn_is_nonblocking(conn) (((conn)->flags & NETCONN_FLAG_NON_BLOCKING) != 0) /** TCP: Set the no-auto-recved status of netconn calls (see NETCONN_FLAG_NO_AUTO_RECVED) */ #define netconn_set_noautorecved(conn, val) do { if(val) { \ (conn)->flags |= NETCONN_FLAG_NO_AUTO_RECVED; \ } else { \ (conn)->flags &= ~ NETCONN_FLAG_NO_AUTO_RECVED; }} while(0) /** TCP: Get the no-auto-recved status of netconn calls (see NETCONN_FLAG_NO_AUTO_RECVED) */ #define netconn_get_noautorecved(conn) (((conn)->flags & NETCONN_FLAG_NO_AUTO_RECVED) != 0) #if LWIP_SO_RCVTIMEO /** Set the receive timeout in milliseconds */ #define netconn_set_recvtimeout(conn, timeout) ((conn)->recv_timeout = (timeout)) /** Get the receive timeout in milliseconds */ #define netconn_get_recvtimeout(conn) ((conn)->recv_timeout) #endif /* LWIP_SO_RCVTIMEO */ #if LWIP_SO_RCVBUF /** Set the receive buffer in bytes */ #define netconn_set_recvbufsize(conn, recvbufsize) ((conn)->recv_bufsize = (recvbufsize)) /** Get the receive buffer in bytes */ #define netconn_get_recvbufsize(conn) ((conn)->recv_bufsize) #endif /* LWIP_SO_RCVBUF*/ #ifdef __cplusplus } #endif #endif /* LWIP_NETCONN */ #endif /* __LWIP_API_H__ */ ================================================ FILE: Zelig/lwip/lwip/include/lwip/api_msg.h ================================================ /* * Copyright (c) 2001-2004 Swedish Institute of Computer Science. * All rights reserved. * * Redistribution and use in source and binary forms, with or without modification, * are permitted provided that the following conditions are met: * * 1. Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * 3. The name of the author may not be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT * SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT * OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING * IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY * OF SUCH DAMAGE. * * This file is part of the lwIP TCP/IP stack. * * Author: Adam Dunkels * */ #ifndef __LWIP_API_MSG_H__ #define __LWIP_API_MSG_H__ #include "lwip/opt.h" #if LWIP_NETCONN /* don't build if not configured for use in lwipopts.h */ #include /* for size_t */ #include "lwip/ip_addr.h" #include "lwip/err.h" #include "lwip/sys.h" #include "lwip/igmp.h" #include "lwip/api.h" #ifdef __cplusplus extern "C" { #endif /* For the netconn API, these values are use as a bitmask! */ #define NETCONN_SHUT_RD 1 #define NETCONN_SHUT_WR 2 #define NETCONN_SHUT_RDWR (NETCONN_SHUT_RD | NETCONN_SHUT_WR) /* IP addresses and port numbers are expected to be in * the same byte order as in the corresponding pcb. */ /** This struct includes everything that is necessary to execute a function for a netconn in another thread context (mainly used to process netconns in the tcpip_thread context to be thread safe). */ struct api_msg_msg { /** The netconn which to process - always needed: it includes the semaphore which is used to block the application thread until the function finished. */ struct netconn *conn; /** The return value of the function executed in tcpip_thread. */ err_t err; /** Depending on the executed function, one of these union members is used */ union { /** used for do_send */ struct netbuf *b; /** used for do_newconn */ struct { u8_t proto; } n; /** used for do_bind and do_connect */ struct { ip_addr_t *ipaddr; u16_t port; } bc; /** used for do_getaddr */ struct { ip_addr_t *ipaddr; u16_t *port; u8_t local; } ad; /** used for do_write */ struct { const void *dataptr; size_t len; u8_t apiflags; } w; /** used for do_recv */ struct { u32_t len; } r; /** used for do_close (/shutdown) */ struct { u8_t shut; } sd; #if LWIP_IGMP /** used for do_join_leave_group */ struct { ip_addr_t *multiaddr; ip_addr_t *netif_addr; enum netconn_igmp join_or_leave; } jl; #endif /* LWIP_IGMP */ #if TCP_LISTEN_BACKLOG struct { u8_t backlog; } lb; #endif /* TCP_LISTEN_BACKLOG */ } msg; }; /** This struct contains a function to execute in another thread context and a struct api_msg_msg that serves as an argument for this function. This is passed to tcpip_apimsg to execute functions in tcpip_thread context. */ struct api_msg { /** function to execute in tcpip_thread context */ void (* function)(struct api_msg_msg *msg); /** arguments for this function */ struct api_msg_msg msg; }; #if LWIP_DNS /** As do_gethostbyname requires more arguments but doesn't require a netconn, it has its own struct (to avoid struct api_msg getting bigger than necessary). do_gethostbyname must be called using tcpip_callback instead of tcpip_apimsg (see netconn_gethostbyname). */ struct dns_api_msg { /** Hostname to query or dotted IP address string */ const char *name; /** Rhe resolved address is stored here */ ip_addr_t *addr; /** This semaphore is posted when the name is resolved, the application thread should wait on it. */ sys_sem_t *sem; /** Errors are given back here */ err_t *err; }; #endif /* LWIP_DNS */ void do_newconn ( struct api_msg_msg *msg); void do_delconn ( struct api_msg_msg *msg); void do_bind ( struct api_msg_msg *msg); void do_connect ( struct api_msg_msg *msg); void do_disconnect ( struct api_msg_msg *msg); void do_listen ( struct api_msg_msg *msg); void do_send ( struct api_msg_msg *msg); void do_recv ( struct api_msg_msg *msg); void do_write ( struct api_msg_msg *msg); void do_getaddr ( struct api_msg_msg *msg); void do_close ( struct api_msg_msg *msg); void do_shutdown ( struct api_msg_msg *msg); #if LWIP_IGMP void do_join_leave_group( struct api_msg_msg *msg); #endif /* LWIP_IGMP */ #if LWIP_DNS void do_gethostbyname(void *arg); #endif /* LWIP_DNS */ struct netconn* netconn_alloc(enum netconn_type t, netconn_callback callback); void netconn_free(struct netconn *conn); #ifdef __cplusplus } #endif #endif /* LWIP_NETCONN */ #endif /* __LWIP_API_MSG_H__ */ ================================================ FILE: Zelig/lwip/lwip/include/lwip/arch.h ================================================ /* * Copyright (c) 2001-2004 Swedish Institute of Computer Science. * All rights reserved. * * Redistribution and use in source and binary forms, with or without modification, * are permitted provided that the following conditions are met: * * 1. Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * 3. The name of the author may not be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT * SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT * OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING * IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY * OF SUCH DAMAGE. * * This file is part of the lwIP TCP/IP stack. * * Author: Adam Dunkels * */ #ifndef __LWIP_ARCH_H__ #define __LWIP_ARCH_H__ #ifndef LITTLE_ENDIAN #define LITTLE_ENDIAN 1234 #endif #ifndef BIG_ENDIAN #define BIG_ENDIAN 4321 #endif #include "arch/cc.h" /** Temporary: define format string for size_t if not defined in cc.h */ #ifndef SZT_F #define SZT_F U32_F #endif /* SZT_F */ /** Temporary upgrade helper: define format string for u8_t as hex if not defined in cc.h */ #ifndef X8_F #define X8_F "02x" #endif /* X8_F */ #ifdef __cplusplus extern "C" { #endif #ifndef PACK_STRUCT_BEGIN #define PACK_STRUCT_BEGIN #endif /* PACK_STRUCT_BEGIN */ #ifndef PACK_STRUCT_END #define PACK_STRUCT_END #endif /* PACK_STRUCT_END */ #ifndef PACK_STRUCT_FIELD #define PACK_STRUCT_FIELD(x) x #endif /* PACK_STRUCT_FIELD */ #ifndef LWIP_UNUSED_ARG #define LWIP_UNUSED_ARG(x) (void)x #endif /* LWIP_UNUSED_ARG */ #ifdef LWIP_PROVIDE_ERRNO #define EPERM 1 /* Operation not permitted */ #define ENOENT 2 /* No such file or directory */ #define ESRCH 3 /* No such process */ #define EINTR 4 /* Interrupted system call */ #define EIO 5 /* I/O error */ #define ENXIO 6 /* No such device or address */ #define E2BIG 7 /* Arg list too long */ #define ENOEXEC 8 /* Exec format error */ #define EBADF 9 /* Bad file number */ #define ECHILD 10 /* No child processes */ #define EAGAIN 11 /* Try again */ #define ENOMEM 12 /* Out of memory */ #define EACCES 13 /* Permission denied */ #define EFAULT 14 /* Bad address */ #define ENOTBLK 15 /* Block device required */ #define EBUSY 16 /* Device or resource busy */ #define EEXIST 17 /* File exists */ #define EXDEV 18 /* Cross-device link */ #define ENODEV 19 /* No such device */ #define ENOTDIR 20 /* Not a directory */ #define EISDIR 21 /* Is a directory */ #define EINVAL 22 /* Invalid argument */ #define ENFILE 23 /* File table overflow */ #define EMFILE 24 /* Too many open files */ #define ENOTTY 25 /* Not a typewriter */ #define ETXTBSY 26 /* Text file busy */ #define EFBIG 27 /* File too large */ #define ENOSPC 28 /* No space left on device */ #define ESPIPE 29 /* Illegal seek */ #define EROFS 30 /* Read-only file system */ #define EMLINK 31 /* Too many links */ #define EPIPE 32 /* Broken pipe */ #define EDOM 33 /* Math argument out of domain of func */ #define ERANGE 34 /* Math result not representable */ #define EDEADLK 35 /* Resource deadlock would occur */ #define ENAMETOOLONG 36 /* File name too long */ #define ENOLCK 37 /* No record locks available */ #define ENOSYS 38 /* Function not implemented */ #define ENOTEMPTY 39 /* Directory not empty */ #define ELOOP 40 /* Too many symbolic links encountered */ #define EWOULDBLOCK EAGAIN /* Operation would block */ #define ENOMSG 42 /* No message of desired type */ #define EIDRM 43 /* Identifier removed */ #define ECHRNG 44 /* Channel number out of range */ #define EL2NSYNC 45 /* Level 2 not synchronized */ #define EL3HLT 46 /* Level 3 halted */ #define EL3RST 47 /* Level 3 reset */ #define ELNRNG 48 /* Link number out of range */ #define EUNATCH 49 /* Protocol driver not attached */ #define ENOCSI 50 /* No CSI structure available */ #define EL2HLT 51 /* Level 2 halted */ #define EBADE 52 /* Invalid exchange */ #define EBADR 53 /* Invalid request descriptor */ #define EXFULL 54 /* Exchange full */ #define ENOANO 55 /* No anode */ #define EBADRQC 56 /* Invalid request code */ #define EBADSLT 57 /* Invalid slot */ #define EDEADLOCK EDEADLK #define EBFONT 59 /* Bad font file format */ #define ENOSTR 60 /* Device not a stream */ #define ENODATA 61 /* No data available */ #define ETIME 62 /* Timer expired */ #define ENOSR 63 /* Out of streams resources */ #define ENONET 64 /* Machine is not on the network */ #define ENOPKG 65 /* Package not installed */ #define EREMOTE 66 /* Object is remote */ #define ENOLINK 67 /* Link has been severed */ #define EADV 68 /* Advertise error */ #define ESRMNT 69 /* Srmount error */ #define ECOMM 70 /* Communication error on send */ #define EPROTO 71 /* Protocol error */ #define EMULTIHOP 72 /* Multihop attempted */ #define EDOTDOT 73 /* RFS specific error */ #define EBADMSG 74 /* Not a data message */ #define EOVERFLOW 75 /* Value too large for defined data type */ #define ENOTUNIQ 76 /* Name not unique on network */ #define EBADFD 77 /* File descriptor in bad state */ #define EREMCHG 78 /* Remote address changed */ #define ELIBACC 79 /* Can not access a needed shared library */ #define ELIBBAD 80 /* Accessing a corrupted shared library */ #define ELIBSCN 81 /* .lib section in a.out corrupted */ #define ELIBMAX 82 /* Attempting to link in too many shared libraries */ #define ELIBEXEC 83 /* Cannot exec a shared library directly */ #define EILSEQ 84 /* Illegal byte sequence */ #define ERESTART 85 /* Interrupted system call should be restarted */ #define ESTRPIPE 86 /* Streams pipe error */ #define EUSERS 87 /* Too many users */ #define ENOTSOCK 88 /* Socket operation on non-socket */ #define EDESTADDRREQ 89 /* Destination address required */ #define EMSGSIZE 90 /* Message too long */ #define EPROTOTYPE 91 /* Protocol wrong type for socket */ #define ENOPROTOOPT 92 /* Protocol not available */ #define EPROTONOSUPPORT 93 /* Protocol not supported */ #define ESOCKTNOSUPPORT 94 /* Socket type not supported */ #define EOPNOTSUPP 95 /* Operation not supported on transport endpoint */ #define EPFNOSUPPORT 96 /* Protocol family not supported */ #define EAFNOSUPPORT 97 /* Address family not supported by protocol */ #define EADDRINUSE 98 /* Address already in use */ #define EADDRNOTAVAIL 99 /* Cannot assign requested address */ #define ENETDOWN 100 /* Network is down */ #define ENETUNREACH 101 /* Network is unreachable */ #define ENETRESET 102 /* Network dropped connection because of reset */ #define ECONNABORTED 103 /* Software caused connection abort */ #define ECONNRESET 104 /* Connection reset by peer */ #define ENOBUFS 105 /* No buffer space available */ #define EISCONN 106 /* Transport endpoint is already connected */ #define ENOTCONN 107 /* Transport endpoint is not connected */ #define ESHUTDOWN 108 /* Cannot send after transport endpoint shutdown */ #define ETOOMANYREFS 109 /* Too many references: cannot splice */ #define ETIMEDOUT 110 /* Connection timed out */ #define ECONNREFUSED 111 /* Connection refused */ #define EHOSTDOWN 112 /* Host is down */ #define EHOSTUNREACH 113 /* No route to host */ #define EALREADY 114 /* Operation already in progress */ #define EINPROGRESS 115 /* Operation now in progress */ #define ESTALE 116 /* Stale NFS file handle */ #define EUCLEAN 117 /* Structure needs cleaning */ #define ENOTNAM 118 /* Not a XENIX named type file */ #define ENAVAIL 119 /* No XENIX semaphores available */ #define EISNAM 120 /* Is a named type file */ #define EREMOTEIO 121 /* Remote I/O error */ #define EDQUOT 122 /* Quota exceeded */ #define ENOMEDIUM 123 /* No medium found */ #define EMEDIUMTYPE 124 /* Wrong medium type */ #define ENSROK 0 /* DNS server returned answer with no data */ #define ENSRNODATA 160 /* DNS server returned answer with no data */ #define ENSRFORMERR 161 /* DNS server claims query was misformatted */ #define ENSRSERVFAIL 162 /* DNS server returned general failure */ #define ENSRNOTFOUND 163 /* Domain name not found */ #define ENSRNOTIMP 164 /* DNS server does not implement requested operation */ #define ENSRREFUSED 165 /* DNS server refused query */ #define ENSRBADQUERY 166 /* Misformatted DNS query */ #define ENSRBADNAME 167 /* Misformatted domain name */ #define ENSRBADFAMILY 168 /* Unsupported address family */ #define ENSRBADRESP 169 /* Misformatted DNS reply */ #define ENSRCONNREFUSED 170 /* Could not contact DNS servers */ #define ENSRTIMEOUT 171 /* Timeout while contacting DNS servers */ #define ENSROF 172 /* End of file */ #define ENSRFILE 173 /* Error reading file */ #define ENSRNOMEM 174 /* Out of memory */ #define ENSRDESTRUCTION 175 /* Application terminated lookup */ #define ENSRQUERYDOMAINTOOLONG 176 /* Domain name is too long */ #define ENSRCNAMELOOP 177 /* Domain name is too long */ #ifndef errno extern int errno; #endif #endif /* LWIP_PROVIDE_ERRNO */ #ifdef __cplusplus } #endif #endif /* __LWIP_ARCH_H__ */ ================================================ FILE: Zelig/lwip/lwip/include/lwip/debug.h ================================================ /* * Copyright (c) 2001-2004 Swedish Institute of Computer Science. * All rights reserved. * * Redistribution and use in source and binary forms, with or without modification, * are permitted provided that the following conditions are met: * * 1. Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * 3. The name of the author may not be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT * SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT * OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING * IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY * OF SUCH DAMAGE. * * This file is part of the lwIP TCP/IP stack. * * Author: Adam Dunkels * */ #ifndef __LWIP_DEBUG_H__ #define __LWIP_DEBUG_H__ #include "lwip/arch.h" /** lower two bits indicate debug level * - 0 all * - 1 warning * - 2 serious * - 3 severe */ #define LWIP_DBG_LEVEL_ALL 0x00 #define LWIP_DBG_LEVEL_OFF LWIP_DBG_LEVEL_ALL /* compatibility define only */ #define LWIP_DBG_LEVEL_WARNING 0x01 /* bad checksums, dropped packets, ... */ #define LWIP_DBG_LEVEL_SERIOUS 0x02 /* memory allocation failures, ... */ #define LWIP_DBG_LEVEL_SEVERE 0x03 #define LWIP_DBG_MASK_LEVEL 0x03 /** flag for LWIP_DEBUGF to enable that debug message */ #define LWIP_DBG_ON 0x80U /** flag for LWIP_DEBUGF to disable that debug message */ #define LWIP_DBG_OFF 0x00U /** flag for LWIP_DEBUGF indicating a tracing message (to follow program flow) */ #define LWIP_DBG_TRACE 0x40U /** flag for LWIP_DEBUGF indicating a state debug message (to follow module states) */ #define LWIP_DBG_STATE 0x20U /** flag for LWIP_DEBUGF indicating newly added code, not thoroughly tested yet */ #define LWIP_DBG_FRESH 0x10U /** flag for LWIP_DEBUGF to halt after printing this debug message */ #define LWIP_DBG_HALT 0x08U #ifndef LWIP_NOASSERT #define LWIP_ASSERT(message, assertion) do { if(!(assertion)) \ LWIP_PLATFORM_ASSERT(message); } while(0) #else /* LWIP_NOASSERT */ #define LWIP_ASSERT(message, assertion) #endif /* LWIP_NOASSERT */ /** if "expression" isn't true, then print "message" and execute "handler" expression */ #ifndef LWIP_ERROR #define LWIP_ERROR(message, expression, handler) do { if (!(expression)) { \ LWIP_PLATFORM_ASSERT(message); handler;}} while(0) #endif /* LWIP_ERROR */ #ifdef LWIP_DEBUG /** print debug message only if debug message type is enabled... * AND is of correct type AND is at least LWIP_DBG_LEVEL */ #define LWIP_DEBUGF(debug, message) do { \ if ( \ ((debug) & LWIP_DBG_ON) && \ ((debug) & LWIP_DBG_TYPES_ON) && \ ((s16_t)((debug) & LWIP_DBG_MASK_LEVEL) >= LWIP_DBG_MIN_LEVEL)) { \ LWIP_PLATFORM_DIAG(message); \ if ((debug) & LWIP_DBG_HALT) { \ while(1); \ } \ } \ } while(0) #else /* LWIP_DEBUG */ #define LWIP_DEBUGF(debug, message) #endif /* LWIP_DEBUG */ #endif /* __LWIP_DEBUG_H__ */ ================================================ FILE: Zelig/lwip/lwip/include/lwip/def.h ================================================ /* * Copyright (c) 2001-2004 Swedish Institute of Computer Science. * All rights reserved. * * Redistribution and use in source and binary forms, with or without modification, * are permitted provided that the following conditions are met: * * 1. Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * 3. The name of the author may not be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT * SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT * OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING * IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY * OF SUCH DAMAGE. * * This file is part of the lwIP TCP/IP stack. * * Author: Adam Dunkels * */ #ifndef __LWIP_DEF_H__ #define __LWIP_DEF_H__ /* arch.h might define NULL already */ #include "lwip/arch.h" #include "lwip/opt.h" #ifdef __cplusplus extern "C" { #endif #define LWIP_MAX(x , y) (((x) > (y)) ? (x) : (y)) #define LWIP_MIN(x , y) (((x) < (y)) ? (x) : (y)) #ifndef NULL #define NULL ((void *)0) #endif /** Get the absolute difference between 2 u32_t values (correcting overflows) * 'a' is expected to be 'higher' (without overflow) than 'b'. */ #define LWIP_U32_DIFF(a, b) (((a) >= (b)) ? ((a) - (b)) : (((a) + ((b) ^ 0xFFFFFFFF) + 1))) /* Endianess-optimized shifting of two u8_t to create one u16_t */ #if BYTE_ORDER == LITTLE_ENDIAN #define LWIP_MAKE_U16(a, b) ((a << 8) | b) #else #define LWIP_MAKE_U16(a, b) ((b << 8) | a) #endif #ifndef LWIP_PLATFORM_BYTESWAP #define LWIP_PLATFORM_BYTESWAP 0 #endif #ifndef LWIP_PREFIX_BYTEORDER_FUNCS /* workaround for naming collisions on some platforms */ #ifdef htons #undef htons #endif /* htons */ #ifdef htonl #undef htonl #endif /* htonl */ #ifdef ntohs #undef ntohs #endif /* ntohs */ #ifdef ntohl #undef ntohl #endif /* ntohl */ #define htons(x) lwip_htons(x) #define ntohs(x) lwip_ntohs(x) #define htonl(x) lwip_htonl(x) #define ntohl(x) lwip_ntohl(x) #endif /* LWIP_PREFIX_BYTEORDER_FUNCS */ #if BYTE_ORDER == BIG_ENDIAN #define lwip_htons(x) (x) #define lwip_ntohs(x) (x) #define lwip_htonl(x) (x) #define lwip_ntohl(x) (x) #define PP_HTONS(x) (x) #define PP_NTOHS(x) (x) #define PP_HTONL(x) (x) #define PP_NTOHL(x) (x) #else /* BYTE_ORDER != BIG_ENDIAN */ #if LWIP_PLATFORM_BYTESWAP #define lwip_htons(x) LWIP_PLATFORM_HTONS(x) #define lwip_ntohs(x) LWIP_PLATFORM_HTONS(x) #define lwip_htonl(x) LWIP_PLATFORM_HTONL(x) #define lwip_ntohl(x) LWIP_PLATFORM_HTONL(x) #else /* LWIP_PLATFORM_BYTESWAP */ u16_t lwip_htons(u16_t x); u16_t lwip_ntohs(u16_t x); u32_t lwip_htonl(u32_t x); u32_t lwip_ntohl(u32_t x); #endif /* LWIP_PLATFORM_BYTESWAP */ /* These macros should be calculated by the preprocessor and are used with compile-time constants only (so that there is no little-endian overhead at runtime). */ #define PP_HTONS(x) ((((x) & 0xff) << 8) | (((x) & 0xff00) >> 8)) #define PP_NTOHS(x) PP_HTONS(x) #define PP_HTONL(x) ((((x) & 0xff) << 24) | \ (((x) & 0xff00) << 8) | \ (((x) & 0xff0000UL) >> 8) | \ (((x) & 0xff000000UL) >> 24)) #define PP_NTOHL(x) PP_HTONL(x) #endif /* BYTE_ORDER == BIG_ENDIAN */ #ifdef __cplusplus } #endif #endif /* __LWIP_DEF_H__ */ ================================================ FILE: Zelig/lwip/lwip/include/lwip/dhcp.h ================================================ /** @file */ #ifndef __LWIP_DHCP_H__ #define __LWIP_DHCP_H__ #include "lwip/opt.h" #if LWIP_DHCP /* don't build if not configured for use in lwipopts.h */ #include "lwip/netif.h" #include "lwip/udp.h" #ifdef __cplusplus extern "C" { #endif /** period (in seconds) of the application calling dhcp_coarse_tmr() */ #define DHCP_COARSE_TIMER_SECS 60 /** period (in milliseconds) of the application calling dhcp_coarse_tmr() */ #define DHCP_COARSE_TIMER_MSECS (DHCP_COARSE_TIMER_SECS * 1000UL) /** period (in milliseconds) of the application calling dhcp_fine_tmr() */ #define DHCP_FINE_TIMER_MSECS 500 #define DHCP_CHADDR_LEN 16U #define DHCP_SNAME_LEN 64U #define DHCP_FILE_LEN 128U struct dhcp { /** transaction identifier of last sent request */ u32_t xid; /** our connection to the DHCP server */ struct udp_pcb *pcb; /** incoming msg */ struct dhcp_msg *msg_in; /** current DHCP state machine state */ u8_t state; /** retries of current request */ u8_t tries; #if LWIP_DHCP_AUTOIP_COOP u8_t autoip_coop_state; #endif u8_t subnet_mask_given; struct pbuf *p_out; /* pbuf of outcoming msg */ struct dhcp_msg *msg_out; /* outgoing msg */ u16_t options_out_len; /* outgoing msg options length */ u16_t request_timeout; /* #ticks with period DHCP_FINE_TIMER_SECS for request timeout */ u16_t t1_timeout; /* #ticks with period DHCP_COARSE_TIMER_SECS for renewal time */ u16_t t2_timeout; /* #ticks with period DHCP_COARSE_TIMER_SECS for rebind time */ ip_addr_t server_ip_addr; /* dhcp server address that offered this lease */ ip_addr_t offered_ip_addr; ip_addr_t offered_sn_mask; ip_addr_t offered_gw_addr; u32_t offered_t0_lease; /* lease period (in seconds) */ u32_t offered_t1_renew; /* recommended renew time (usually 50% of lease period) */ u32_t offered_t2_rebind; /* recommended rebind time (usually 66% of lease period) */ /* @todo: LWIP_DHCP_BOOTP_FILE configuration option? integrate with possible TFTP-client for booting? */ #if LWIP_DHCP_BOOTP_FILE ip_addr_t offered_si_addr; char boot_file_name[DHCP_FILE_LEN]; #endif /* LWIP_DHCP_BOOTPFILE */ }; /* MUST be compiled with "pack structs" or equivalent! */ #ifdef PACK_STRUCT_USE_INCLUDES # include "arch/bpstruct.h" #endif PACK_STRUCT_BEGIN /** minimum set of fields of any DHCP message */ struct dhcp_msg { PACK_STRUCT_FIELD(u8_t op); PACK_STRUCT_FIELD(u8_t htype); PACK_STRUCT_FIELD(u8_t hlen); PACK_STRUCT_FIELD(u8_t hops); PACK_STRUCT_FIELD(u32_t xid); PACK_STRUCT_FIELD(u16_t secs); PACK_STRUCT_FIELD(u16_t flags); PACK_STRUCT_FIELD(ip_addr_p_t ciaddr); PACK_STRUCT_FIELD(ip_addr_p_t yiaddr); PACK_STRUCT_FIELD(ip_addr_p_t siaddr); PACK_STRUCT_FIELD(ip_addr_p_t giaddr); PACK_STRUCT_FIELD(u8_t chaddr[DHCP_CHADDR_LEN]); PACK_STRUCT_FIELD(u8_t sname[DHCP_SNAME_LEN]); PACK_STRUCT_FIELD(u8_t file[DHCP_FILE_LEN]); PACK_STRUCT_FIELD(u32_t cookie); #define DHCP_MIN_OPTIONS_LEN 68U /** make sure user does not configure this too small */ #if ((defined(DHCP_OPTIONS_LEN)) && (DHCP_OPTIONS_LEN < DHCP_MIN_OPTIONS_LEN)) # undef DHCP_OPTIONS_LEN #endif /** allow this to be configured in lwipopts.h, but not too small */ #if (!defined(DHCP_OPTIONS_LEN)) /** set this to be sufficient for your options in outgoing DHCP msgs */ # define DHCP_OPTIONS_LEN DHCP_MIN_OPTIONS_LEN #endif PACK_STRUCT_FIELD(u8_t options[DHCP_OPTIONS_LEN]); } PACK_STRUCT_STRUCT; PACK_STRUCT_END #ifdef PACK_STRUCT_USE_INCLUDES # include "arch/epstruct.h" #endif void dhcp_set_struct(struct netif *netif, struct dhcp *dhcp); /** Remove a struct dhcp previously set to the netif using dhcp_set_struct() */ #define dhcp_remove_struct(netif) do { (netif)->dhcp = NULL; } while(0) void dhcp_cleanup(struct netif *netif); /** start DHCP configuration */ err_t dhcp_start(struct netif *netif); /** enforce early lease renewal (not needed normally)*/ err_t dhcp_renew(struct netif *netif); /** release the DHCP lease, usually called before dhcp_stop()*/ err_t dhcp_release(struct netif *netif); /** stop DHCP configuration */ void dhcp_stop(struct netif *netif); /** inform server of our manual IP address */ void dhcp_inform(struct netif *netif); /** Handle a possible change in the network configuration */ void dhcp_network_changed(struct netif *netif); /** if enabled, check whether the offered IP address is not in use, using ARP */ #if DHCP_DOES_ARP_CHECK void dhcp_arp_reply(struct netif *netif, ip_addr_t *addr); #endif /** to be called every minute */ void dhcp_coarse_tmr(void); /** to be called every half second */ void dhcp_fine_tmr(void); /** DHCP message item offsets and length */ #define DHCP_OP_OFS 0 #define DHCP_HTYPE_OFS 1 #define DHCP_HLEN_OFS 2 #define DHCP_HOPS_OFS 3 #define DHCP_XID_OFS 4 #define DHCP_SECS_OFS 8 #define DHCP_FLAGS_OFS 10 #define DHCP_CIADDR_OFS 12 #define DHCP_YIADDR_OFS 16 #define DHCP_SIADDR_OFS 20 #define DHCP_GIADDR_OFS 24 #define DHCP_CHADDR_OFS 28 #define DHCP_SNAME_OFS 44 #define DHCP_FILE_OFS 108 #define DHCP_MSG_LEN 236 #define DHCP_COOKIE_OFS DHCP_MSG_LEN #define DHCP_OPTIONS_OFS (DHCP_MSG_LEN + 4) #define DHCP_CLIENT_PORT 68 #define DHCP_SERVER_PORT 67 /** DHCP client states */ #define DHCP_OFF 0 #define DHCP_REQUESTING 1 #define DHCP_INIT 2 #define DHCP_REBOOTING 3 #define DHCP_REBINDING 4 #define DHCP_RENEWING 5 #define DHCP_SELECTING 6 #define DHCP_INFORMING 7 #define DHCP_CHECKING 8 #define DHCP_PERMANENT 9 #define DHCP_BOUND 10 /** not yet implemented #define DHCP_RELEASING 11 */ #define DHCP_BACKING_OFF 12 /** AUTOIP cooperatation flags */ #define DHCP_AUTOIP_COOP_STATE_OFF 0 #define DHCP_AUTOIP_COOP_STATE_ON 1 #define DHCP_BOOTREQUEST 1 #define DHCP_BOOTREPLY 2 /** DHCP message types */ #define DHCP_DISCOVER 1 #define DHCP_OFFER 2 #define DHCP_REQUEST 3 #define DHCP_DECLINE 4 #define DHCP_ACK 5 #define DHCP_NAK 6 #define DHCP_RELEASE 7 #define DHCP_INFORM 8 /** DHCP hardware type, currently only ethernet is supported */ #define DHCP_HTYPE_ETH 1 #define DHCP_MAGIC_COOKIE 0x63825363UL /* This is a list of options for BOOTP and DHCP, see RFC 2132 for descriptions */ /** BootP options */ #define DHCP_OPTION_PAD 0 #define DHCP_OPTION_SUBNET_MASK 1 /* RFC 2132 3.3 */ #define DHCP_OPTION_ROUTER 3 #define DHCP_OPTION_DNS_SERVER 6 #define DHCP_OPTION_HOSTNAME 12 #define DHCP_OPTION_IP_TTL 23 #define DHCP_OPTION_MTU 26 #define DHCP_OPTION_BROADCAST 28 #define DHCP_OPTION_TCP_TTL 37 #define DHCP_OPTION_END 255 /** DHCP options */ #define DHCP_OPTION_REQUESTED_IP 50 /* RFC 2132 9.1, requested IP address */ #define DHCP_OPTION_LEASE_TIME 51 /* RFC 2132 9.2, time in seconds, in 4 bytes */ #define DHCP_OPTION_OVERLOAD 52 /* RFC2132 9.3, use file and/or sname field for options */ #define DHCP_OPTION_MESSAGE_TYPE 53 /* RFC 2132 9.6, important for DHCP */ #define DHCP_OPTION_MESSAGE_TYPE_LEN 1 #define DHCP_OPTION_SERVER_ID 54 /* RFC 2132 9.7, server IP address */ #define DHCP_OPTION_PARAMETER_REQUEST_LIST 55 /* RFC 2132 9.8, requested option types */ #define DHCP_OPTION_MAX_MSG_SIZE 57 /* RFC 2132 9.10, message size accepted >= 576 */ #define DHCP_OPTION_MAX_MSG_SIZE_LEN 2 #define DHCP_OPTION_T1 58 /* T1 renewal time */ #define DHCP_OPTION_T2 59 /* T2 rebinding time */ #define DHCP_OPTION_US 60 #define DHCP_OPTION_CLIENT_ID 61 #define DHCP_OPTION_TFTP_SERVERNAME 66 #define DHCP_OPTION_BOOTFILE 67 /** possible combinations of overloading the file and sname fields with options */ #define DHCP_OVERLOAD_NONE 0 #define DHCP_OVERLOAD_FILE 1 #define DHCP_OVERLOAD_SNAME 2 #define DHCP_OVERLOAD_SNAME_FILE 3 #ifdef __cplusplus } #endif #endif /* LWIP_DHCP */ #endif /*__LWIP_DHCP_H__*/ ================================================ FILE: Zelig/lwip/lwip/include/lwip/dns.h ================================================ /** * lwip DNS resolver header file. * Author: Jim Pettinato * April 2007 * ported from uIP resolv.c Copyright (c) 2002-2003, Adam Dunkels. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * 3. The name of the author may not be used to endorse or promote * products derived from this software without specific prior * written permission. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS * OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE * GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #ifndef __LWIP_DNS_H__ #define __LWIP_DNS_H__ #include "lwip/opt.h" #if LWIP_DNS /* don't build if not configured for use in lwipopts.h */ #ifdef __cplusplus extern "C" { #endif /** DNS timer period */ #define DNS_TMR_INTERVAL 1000 /** DNS field TYPE used for "Resource Records" */ #define DNS_RRTYPE_A 1 /* a host address */ #define DNS_RRTYPE_NS 2 /* an authoritative name server */ #define DNS_RRTYPE_MD 3 /* a mail destination (Obsolete - use MX) */ #define DNS_RRTYPE_MF 4 /* a mail forwarder (Obsolete - use MX) */ #define DNS_RRTYPE_CNAME 5 /* the canonical name for an alias */ #define DNS_RRTYPE_SOA 6 /* marks the start of a zone of authority */ #define DNS_RRTYPE_MB 7 /* a mailbox domain name (EXPERIMENTAL) */ #define DNS_RRTYPE_MG 8 /* a mail group member (EXPERIMENTAL) */ #define DNS_RRTYPE_MR 9 /* a mail rename domain name (EXPERIMENTAL) */ #define DNS_RRTYPE_NULL 10 /* a null RR (EXPERIMENTAL) */ #define DNS_RRTYPE_WKS 11 /* a well known service description */ #define DNS_RRTYPE_PTR 12 /* a domain name pointer */ #define DNS_RRTYPE_HINFO 13 /* host information */ #define DNS_RRTYPE_MINFO 14 /* mailbox or mail list information */ #define DNS_RRTYPE_MX 15 /* mail exchange */ #define DNS_RRTYPE_TXT 16 /* text strings */ /** DNS field CLASS used for "Resource Records" */ #define DNS_RRCLASS_IN 1 /* the Internet */ #define DNS_RRCLASS_CS 2 /* the CSNET class (Obsolete - used only for examples in some obsolete RFCs) */ #define DNS_RRCLASS_CH 3 /* the CHAOS class */ #define DNS_RRCLASS_HS 4 /* Hesiod [Dyer 87] */ #define DNS_RRCLASS_FLUSH 0x800 /* Flush bit */ /* The size used for the next line is rather a hack, but it prevents including socket.h in all files that include memp.h, and that would possibly break portability (since socket.h defines some types and constants possibly already define by the OS). Calculation rule: sizeof(struct addrinfo) + sizeof(struct sockaddr_in) + DNS_MAX_NAME_LENGTH + 1 byte zero-termination */ #define NETDB_ELEM_SIZE (32 + 16 + DNS_MAX_NAME_LENGTH + 1) #if DNS_LOCAL_HOSTLIST /** struct used for local host-list */ struct local_hostlist_entry { /** static hostname */ const char *name; /** static host address in network byteorder */ ip_addr_t addr; struct local_hostlist_entry *next; }; #if DNS_LOCAL_HOSTLIST_IS_DYNAMIC #ifndef DNS_LOCAL_HOSTLIST_MAX_NAMELEN #define DNS_LOCAL_HOSTLIST_MAX_NAMELEN DNS_MAX_NAME_LENGTH #endif #define LOCALHOSTLIST_ELEM_SIZE ((sizeof(struct local_hostlist_entry) + DNS_LOCAL_HOSTLIST_MAX_NAMELEN + 1)) #endif /* DNS_LOCAL_HOSTLIST_IS_DYNAMIC */ #endif /* DNS_LOCAL_HOSTLIST */ /** Callback which is invoked when a hostname is found. * A function of this type must be implemented by the application using the DNS resolver. * @param name pointer to the name that was looked up. * @param ipaddr pointer to an ip_addr_t containing the IP address of the hostname, * or NULL if the name could not be found (or on any other error). * @param callback_arg a user-specified callback argument passed to dns_gethostbyname */ typedef void (*dns_found_callback)(const char *name, ip_addr_t *ipaddr, void *callback_arg); void dns_init(void); void dns_tmr(void); void dns_setserver(u8_t numdns, ip_addr_t *dnsserver); ip_addr_t dns_getserver(u8_t numdns); err_t dns_gethostbyname(const char *hostname, ip_addr_t *addr, dns_found_callback found, void *callback_arg); #if DNS_LOCAL_HOSTLIST && DNS_LOCAL_HOSTLIST_IS_DYNAMIC int dns_local_removehost(const char *hostname, const ip_addr_t *addr); err_t dns_local_addhost(const char *hostname, const ip_addr_t *addr); #endif /* DNS_LOCAL_HOSTLIST && DNS_LOCAL_HOSTLIST_IS_DYNAMIC */ #ifdef __cplusplus } #endif #endif /* LWIP_DNS */ #endif /* __LWIP_DNS_H__ */ ================================================ FILE: Zelig/lwip/lwip/include/lwip/err.h ================================================ /* * Copyright (c) 2001-2004 Swedish Institute of Computer Science. * All rights reserved. * * Redistribution and use in source and binary forms, with or without modification, * are permitted provided that the following conditions are met: * * 1. Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * 3. The name of the author may not be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT * SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT * OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING * IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY * OF SUCH DAMAGE. * * This file is part of the lwIP TCP/IP stack. * * Author: Adam Dunkels * */ #ifndef __LWIP_ERR_H__ #define __LWIP_ERR_H__ #include "lwip/opt.h" #include "lwip/arch.h" #ifdef __cplusplus extern "C" { #endif /** Define LWIP_ERR_T in cc.h if you want to use * a different type for your platform (must be signed). */ #ifdef LWIP_ERR_T typedef LWIP_ERR_T err_t; #else /* LWIP_ERR_T */ typedef s8_t err_t; #endif /* LWIP_ERR_T*/ /* Definitions for error constants. */ #define ERR_OK 0 /* No error, everything OK. */ #define ERR_MEM -1 /* Out of memory error. */ #define ERR_BUF -2 /* Buffer error. */ #define ERR_TIMEOUT -3 /* Timeout. */ #define ERR_RTE -4 /* Routing problem. */ #define ERR_INPROGRESS -5 /* Operation in progress */ #define ERR_VAL -6 /* Illegal value. */ #define ERR_WOULDBLOCK -7 /* Operation would block. */ #define ERR_USE -8 /* Address in use. */ #define ERR_ISCONN -9 /* Already connected. */ #define ERR_IS_FATAL(e) ((e) < ERR_ISCONN) #define ERR_ABRT -10 /* Connection aborted. */ #define ERR_RST -11 /* Connection reset. */ #define ERR_CLSD -12 /* Connection closed. */ #define ERR_CONN -13 /* Not connected. */ #define ERR_ARG -14 /* Illegal argument. */ #define ERR_IF -15 /* Low-level netif error */ #ifdef LWIP_DEBUG extern const char *lwip_strerr(err_t err); #else #define lwip_strerr(x) "" #endif /* LWIP_DEBUG */ #ifdef __cplusplus } #endif #endif /* __LWIP_ERR_H__ */ ================================================ FILE: Zelig/lwip/lwip/include/lwip/init.h ================================================ /* * Copyright (c) 2001-2004 Swedish Institute of Computer Science. * All rights reserved. * * Redistribution and use in source and binary forms, with or without modification, * are permitted provided that the following conditions are met: * * 1. Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * 3. The name of the author may not be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT * SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT * OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING * IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY * OF SUCH DAMAGE. * * This file is part of the lwIP TCP/IP stack. * * Author: Adam Dunkels * */ #ifndef __LWIP_INIT_H__ #define __LWIP_INIT_H__ #include "lwip/opt.h" #ifdef __cplusplus extern "C" { #endif /** X.x.x: Major version of the stack */ #define LWIP_VERSION_MAJOR 1U /** x.X.x: Minor version of the stack */ #define LWIP_VERSION_MINOR 4U /** x.x.X: Revision of the stack */ #define LWIP_VERSION_REVISION 0U /** For release candidates, this is set to 1..254 * For official releases, this is set to 255 (LWIP_RC_RELEASE) * For development versions (CVS), this is set to 0 (LWIP_RC_DEVELOPMENT) */ #define LWIP_VERSION_RC 255U /** LWIP_VERSION_RC is set to LWIP_RC_RELEASE for official releases */ #define LWIP_RC_RELEASE 255U /** LWIP_VERSION_RC is set to LWIP_RC_DEVELOPMENT for CVS versions */ #define LWIP_RC_DEVELOPMENT 0U #define LWIP_VERSION_IS_RELEASE (LWIP_VERSION_RC == LWIP_RC_RELEASE) #define LWIP_VERSION_IS_DEVELOPMENT (LWIP_VERSION_RC == LWIP_RC_DEVELOPMENT) #define LWIP_VERSION_IS_RC ((LWIP_VERSION_RC != LWIP_RC_RELEASE) && (LWIP_VERSION_RC != LWIP_RC_DEVELOPMENT)) /** Provides the version of the stack */ #define LWIP_VERSION (LWIP_VERSION_MAJOR << 24 | LWIP_VERSION_MINOR << 16 | \ LWIP_VERSION_REVISION << 8 | LWIP_VERSION_RC) /* Modules initialization */ void lwip_init(void); #ifdef __cplusplus } #endif #endif /* __LWIP_INIT_H__ */ ================================================ FILE: Zelig/lwip/lwip/include/lwip/mem.h ================================================ /* * Copyright (c) 2001-2004 Swedish Institute of Computer Science. * All rights reserved. * * Redistribution and use in source and binary forms, with or without modification, * are permitted provided that the following conditions are met: * * 1. Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * 3. The name of the author may not be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT * SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT * OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING * IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY * OF SUCH DAMAGE. * * This file is part of the lwIP TCP/IP stack. * * Author: Adam Dunkels * */ #ifndef __LWIP_MEM_H__ #define __LWIP_MEM_H__ #include "lwip/opt.h" #ifdef __cplusplus extern "C" { #endif #if MEM_LIBC_MALLOC #include /* for size_t */ typedef size_t mem_size_t; /* aliases for C library malloc() */ #define mem_init() /* in case C library malloc() needs extra protection, * allow these defines to be overridden. */ #ifndef mem_free #define mem_free free #endif #ifndef mem_malloc #define mem_malloc malloc #endif #ifndef mem_calloc #define mem_calloc calloc #endif /* Since there is no C library allocation function to shrink memory without moving it, define this to nothing. */ #ifndef mem_trim #define mem_trim(mem, size) (mem) #endif #else /* MEM_LIBC_MALLOC */ /* MEM_SIZE would have to be aligned, but using 64000 here instead of * 65535 leaves some room for alignment... */ #if MEM_SIZE > 64000L typedef u32_t mem_size_t; #define MEM_SIZE_F U32_F #else typedef u16_t mem_size_t; #define MEM_SIZE_F U16_F #endif /* MEM_SIZE > 64000 */ #if MEM_USE_POOLS /** mem_init is not used when using pools instead of a heap */ #define mem_init() /** mem_trim is not used when using pools instead of a heap: we can't free part of a pool element and don't want to copy the rest */ #define mem_trim(mem, size) (mem) #else /* MEM_USE_POOLS */ /* lwIP alternative malloc */ void mem_init(void); void *mem_trim(void *mem, mem_size_t size); #endif /* MEM_USE_POOLS */ void *mem_malloc(mem_size_t size); void *mem_calloc(mem_size_t count, mem_size_t size); void mem_free(void *mem); #endif /* MEM_LIBC_MALLOC */ /** Calculate memory size for an aligned buffer - returns the next highest * multiple of MEM_ALIGNMENT (e.g. LWIP_MEM_ALIGN_SIZE(3) and * LWIP_MEM_ALIGN_SIZE(4) will both yield 4 for MEM_ALIGNMENT == 4). */ #ifndef LWIP_MEM_ALIGN_SIZE #define LWIP_MEM_ALIGN_SIZE(size) (((size) + MEM_ALIGNMENT - 1) & ~(MEM_ALIGNMENT-1)) #endif /** Calculate safe memory size for an aligned buffer when using an unaligned * type as storage. This includes a safety-margin on (MEM_ALIGNMENT - 1) at the * start (e.g. if buffer is u8_t[] and actual data will be u32_t*) */ #ifndef LWIP_MEM_ALIGN_BUFFER #define LWIP_MEM_ALIGN_BUFFER(size) (((size) + MEM_ALIGNMENT - 1)) #endif /** Align a memory pointer to the alignment defined by MEM_ALIGNMENT * so that ADDR % MEM_ALIGNMENT == 0 */ #ifndef LWIP_MEM_ALIGN #define LWIP_MEM_ALIGN(addr) ((void *)(((mem_ptr_t)(addr) + MEM_ALIGNMENT - 1) & ~(mem_ptr_t)(MEM_ALIGNMENT-1))) #endif #ifdef __cplusplus } #endif #endif /* __LWIP_MEM_H__ */ ================================================ FILE: Zelig/lwip/lwip/include/lwip/memp.h ================================================ /* * Copyright (c) 2001-2004 Swedish Institute of Computer Science. * All rights reserved. * * Redistribution and use in source and binary forms, with or without modification, * are permitted provided that the following conditions are met: * * 1. Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * 3. The name of the author may not be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT * SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT * OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING * IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY * OF SUCH DAMAGE. * * This file is part of the lwIP TCP/IP stack. * * Author: Adam Dunkels * */ #ifndef __LWIP_MEMP_H__ #define __LWIP_MEMP_H__ #include "lwip/opt.h" #ifdef __cplusplus extern "C" { #endif /* Create the list of all memory pools managed by memp. MEMP_MAX represents a NULL pool at the end */ typedef enum { #define LWIP_MEMPOOL(name,num,size,desc) MEMP_##name, #include "lwip/memp_std.h" MEMP_MAX } memp_t; #if MEM_USE_POOLS /* Use a helper type to get the start and end of the user "memory pools" for mem_malloc */ typedef enum { /* Get the first (via: MEMP_POOL_HELPER_START = ((u8_t) 1*MEMP_POOL_A + 0*MEMP_POOL_B + 0*MEMP_POOL_C + 0)*/ MEMP_POOL_HELPER_FIRST = ((u8_t) #define LWIP_MEMPOOL(name,num,size,desc) #define LWIP_MALLOC_MEMPOOL_START 1 #define LWIP_MALLOC_MEMPOOL(num, size) * MEMP_POOL_##size + 0 #define LWIP_MALLOC_MEMPOOL_END #include "lwip/memp_std.h" ) , /* Get the last (via: MEMP_POOL_HELPER_END = ((u8_t) 0 + MEMP_POOL_A*0 + MEMP_POOL_B*0 + MEMP_POOL_C*1) */ MEMP_POOL_HELPER_LAST = ((u8_t) #define LWIP_MEMPOOL(name,num,size,desc) #define LWIP_MALLOC_MEMPOOL_START #define LWIP_MALLOC_MEMPOOL(num, size) 0 + MEMP_POOL_##size * #define LWIP_MALLOC_MEMPOOL_END 1 #include "lwip/memp_std.h" ) } memp_pool_helper_t; /* The actual start and stop values are here (cast them over) We use this helper type and these defines so we can avoid using const memp_t values */ #define MEMP_POOL_FIRST ((memp_t) MEMP_POOL_HELPER_FIRST) #define MEMP_POOL_LAST ((memp_t) MEMP_POOL_HELPER_LAST) #endif /* MEM_USE_POOLS */ #if MEMP_MEM_MALLOC || MEM_USE_POOLS extern const u16_t memp_sizes[MEMP_MAX]; #endif /* MEMP_MEM_MALLOC || MEM_USE_POOLS */ #if MEMP_MEM_MALLOC #include "mem.h" #define memp_init() #define memp_malloc(type) mem_malloc(memp_sizes[type]) #define memp_free(type, mem) mem_free(mem) #else /* MEMP_MEM_MALLOC */ #if MEM_USE_POOLS /** This structure is used to save the pool one element came from. */ struct memp_malloc_helper { memp_t poolnr; }; #endif /* MEM_USE_POOLS */ void memp_init(void); #if MEMP_OVERFLOW_CHECK void *memp_malloc_fn(memp_t type, const char* file, const int line); #define memp_malloc(t) memp_malloc_fn((t), __FILE__, __LINE__) #else void *memp_malloc(memp_t type); #endif void memp_free(memp_t type, void *mem); #endif /* MEMP_MEM_MALLOC */ #ifdef __cplusplus } #endif #endif /* __LWIP_MEMP_H__ */ ================================================ FILE: Zelig/lwip/lwip/include/lwip/memp_std.h ================================================ /* * SETUP: Make sure we define everything we will need. * * We have create three types of pools: * 1) MEMPOOL - standard pools * 2) MALLOC_MEMPOOL - to be used by mem_malloc in mem.c * 3) PBUF_MEMPOOL - a mempool of pbuf's, so include space for the pbuf struct * * If the include'r doesn't require any special treatment of each of the types * above, then will declare #2 & #3 to be just standard mempools. */ #ifndef LWIP_MALLOC_MEMPOOL /* This treats "malloc pools" just like any other pool. The pools are a little bigger to provide 'size' as the amount of user data. */ #define LWIP_MALLOC_MEMPOOL(num, size) LWIP_MEMPOOL(POOL_##size, num, (size + sizeof(struct memp_malloc_helper)), "MALLOC_"#size) #define LWIP_MALLOC_MEMPOOL_START #define LWIP_MALLOC_MEMPOOL_END #endif /* LWIP_MALLOC_MEMPOOL */ #ifndef LWIP_PBUF_MEMPOOL /* This treats "pbuf pools" just like any other pool. * Allocates buffers for a pbuf struct AND a payload size */ #define LWIP_PBUF_MEMPOOL(name, num, payload, desc) LWIP_MEMPOOL(name, num, (MEMP_ALIGN_SIZE(sizeof(struct pbuf)) + MEMP_ALIGN_SIZE(payload)), desc) #endif /* LWIP_PBUF_MEMPOOL */ /* * A list of internal pools used by LWIP. * * LWIP_MEMPOOL(pool_name, number_elements, element_size, pool_description) * creates a pool name MEMP_pool_name. description is used in stats.c */ #if LWIP_RAW LWIP_MEMPOOL(RAW_PCB, MEMP_NUM_RAW_PCB, sizeof(struct raw_pcb), "RAW_PCB") #endif /* LWIP_RAW */ #if LWIP_UDP LWIP_MEMPOOL(UDP_PCB, MEMP_NUM_UDP_PCB, sizeof(struct udp_pcb), "UDP_PCB") #endif /* LWIP_UDP */ #if LWIP_TCP LWIP_MEMPOOL(TCP_PCB, MEMP_NUM_TCP_PCB, sizeof(struct tcp_pcb), "TCP_PCB") LWIP_MEMPOOL(TCP_PCB_LISTEN, MEMP_NUM_TCP_PCB_LISTEN, sizeof(struct tcp_pcb_listen), "TCP_PCB_LISTEN") LWIP_MEMPOOL(TCP_SEG, MEMP_NUM_TCP_SEG, sizeof(struct tcp_seg), "TCP_SEG") #endif /* LWIP_TCP */ #if IP_REASSEMBLY LWIP_MEMPOOL(REASSDATA, MEMP_NUM_REASSDATA, sizeof(struct ip_reassdata), "REASSDATA") #endif /* IP_REASSEMBLY */ #if IP_FRAG && !IP_FRAG_USES_STATIC_BUF && !LWIP_NETIF_TX_SINGLE_PBUF LWIP_MEMPOOL(FRAG_PBUF, MEMP_NUM_FRAG_PBUF, sizeof(struct pbuf_custom_ref),"FRAG_PBUF") #endif /* IP_FRAG && !IP_FRAG_USES_STATIC_BUF && !LWIP_NETIF_TX_SINGLE_PBUF */ #if LWIP_NETCONN LWIP_MEMPOOL(NETBUF, MEMP_NUM_NETBUF, sizeof(struct netbuf), "NETBUF") LWIP_MEMPOOL(NETCONN, MEMP_NUM_NETCONN, sizeof(struct netconn), "NETCONN") #endif /* LWIP_NETCONN */ #if NO_SYS==0 LWIP_MEMPOOL(TCPIP_MSG_API, MEMP_NUM_TCPIP_MSG_API, sizeof(struct tcpip_msg), "TCPIP_MSG_API") #if !LWIP_TCPIP_CORE_LOCKING_INPUT LWIP_MEMPOOL(TCPIP_MSG_INPKT,MEMP_NUM_TCPIP_MSG_INPKT, sizeof(struct tcpip_msg), "TCPIP_MSG_INPKT") #endif /* !LWIP_TCPIP_CORE_LOCKING_INPUT */ #endif /* NO_SYS==0 */ #if ARP_QUEUEING LWIP_MEMPOOL(ARP_QUEUE, MEMP_NUM_ARP_QUEUE, sizeof(struct etharp_q_entry), "ARP_QUEUE") #endif /* ARP_QUEUEING */ #if LWIP_IGMP LWIP_MEMPOOL(IGMP_GROUP, MEMP_NUM_IGMP_GROUP, sizeof(struct igmp_group), "IGMP_GROUP") #endif /* LWIP_IGMP */ #if (!NO_SYS || (NO_SYS && !NO_SYS_NO_TIMERS)) /* LWIP_TIMERS */ LWIP_MEMPOOL(SYS_TIMEOUT, MEMP_NUM_SYS_TIMEOUT, sizeof(struct sys_timeo), "SYS_TIMEOUT") #endif /* LWIP_TIMERS */ #if LWIP_SNMP LWIP_MEMPOOL(SNMP_ROOTNODE, MEMP_NUM_SNMP_ROOTNODE, sizeof(struct mib_list_rootnode), "SNMP_ROOTNODE") LWIP_MEMPOOL(SNMP_NODE, MEMP_NUM_SNMP_NODE, sizeof(struct mib_list_node), "SNMP_NODE") LWIP_MEMPOOL(SNMP_VARBIND, MEMP_NUM_SNMP_VARBIND, sizeof(struct snmp_varbind), "SNMP_VARBIND") LWIP_MEMPOOL(SNMP_VALUE, MEMP_NUM_SNMP_VALUE, SNMP_MAX_VALUE_SIZE, "SNMP_VALUE") #endif /* LWIP_SNMP */ #if LWIP_DNS && LWIP_SOCKET LWIP_MEMPOOL(NETDB, MEMP_NUM_NETDB, NETDB_ELEM_SIZE, "NETDB") #endif /* LWIP_DNS && LWIP_SOCKET */ #if LWIP_DNS && DNS_LOCAL_HOSTLIST && DNS_LOCAL_HOSTLIST_IS_DYNAMIC LWIP_MEMPOOL(LOCALHOSTLIST, MEMP_NUM_LOCALHOSTLIST, LOCALHOSTLIST_ELEM_SIZE, "LOCALHOSTLIST") #endif /* LWIP_DNS && DNS_LOCAL_HOSTLIST && DNS_LOCAL_HOSTLIST_IS_DYNAMIC */ #if PPP_SUPPORT && PPPOE_SUPPORT LWIP_MEMPOOL(PPPOE_IF, MEMP_NUM_PPPOE_INTERFACES, sizeof(struct pppoe_softc), "PPPOE_IF") #endif /* PPP_SUPPORT && PPPOE_SUPPORT */ /* * A list of pools of pbuf's used by LWIP. * * LWIP_PBUF_MEMPOOL(pool_name, number_elements, pbuf_payload_size, pool_description) * creates a pool name MEMP_pool_name. description is used in stats.c * This allocates enough space for the pbuf struct and a payload. * (Example: pbuf_payload_size=0 allocates only size for the struct) */ LWIP_PBUF_MEMPOOL(PBUF, MEMP_NUM_PBUF, 0, "PBUF_REF/ROM") LWIP_PBUF_MEMPOOL(PBUF_POOL, PBUF_POOL_SIZE, PBUF_POOL_BUFSIZE, "PBUF_POOL") /* * Allow for user-defined pools; this must be explicitly set in lwipopts.h * since the default is to NOT look for lwippools.h */ #if MEMP_USE_CUSTOM_POOLS #include "lwippools.h" #endif /* MEMP_USE_CUSTOM_POOLS */ /* * REQUIRED CLEANUP: Clear up so we don't get "multiply defined" error later * (#undef is ignored for something that is not defined) */ #undef LWIP_MEMPOOL #undef LWIP_MALLOC_MEMPOOL #undef LWIP_MALLOC_MEMPOOL_START #undef LWIP_MALLOC_MEMPOOL_END #undef LWIP_PBUF_MEMPOOL ================================================ FILE: Zelig/lwip/lwip/include/lwip/netbuf.h ================================================ /* * Copyright (c) 2001-2004 Swedish Institute of Computer Science. * All rights reserved. * * Redistribution and use in source and binary forms, with or without modification, * are permitted provided that the following conditions are met: * * 1. Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * 3. The name of the author may not be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT * SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT * OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING * IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY * OF SUCH DAMAGE. * * This file is part of the lwIP TCP/IP stack. * * Author: Adam Dunkels * */ #ifndef __LWIP_NETBUF_H__ #define __LWIP_NETBUF_H__ #include "lwip/opt.h" #include "lwip/pbuf.h" #include "lwip/ip_addr.h" #ifdef __cplusplus extern "C" { #endif /** This netbuf has dest-addr/port set */ #define NETBUF_FLAG_DESTADDR 0x01 /** This netbuf includes a checksum */ #define NETBUF_FLAG_CHKSUM 0x02 struct netbuf { struct pbuf *p, *ptr; ip_addr_t addr; u16_t port; #if LWIP_NETBUF_RECVINFO || LWIP_CHECKSUM_ON_COPY #if LWIP_CHECKSUM_ON_COPY u8_t flags; #endif /* LWIP_CHECKSUM_ON_COPY */ u16_t toport_chksum; #if LWIP_NETBUF_RECVINFO ip_addr_t toaddr; #endif /* LWIP_NETBUF_RECVINFO */ #endif /* LWIP_NETBUF_RECVINFO || LWIP_CHECKSUM_ON_COPY */ }; /* Network buffer functions: */ struct netbuf * netbuf_new (void); void netbuf_delete (struct netbuf *buf); void * netbuf_alloc (struct netbuf *buf, u16_t size); void netbuf_free (struct netbuf *buf); err_t netbuf_ref (struct netbuf *buf, const void *dataptr, u16_t size); void netbuf_chain (struct netbuf *head, struct netbuf *tail); err_t netbuf_data (struct netbuf *buf, void **dataptr, u16_t *len); s8_t netbuf_next (struct netbuf *buf); void netbuf_first (struct netbuf *buf); #define netbuf_copy_partial(buf, dataptr, len, offset) \ pbuf_copy_partial((buf)->p, (dataptr), (len), (offset)) #define netbuf_copy(buf,dataptr,len) netbuf_copy_partial(buf, dataptr, len, 0) #define netbuf_take(buf, dataptr, len) pbuf_take((buf)->p, dataptr, len) #define netbuf_len(buf) ((buf)->p->tot_len) #define netbuf_fromaddr(buf) (&((buf)->addr)) #define netbuf_set_fromaddr(buf, fromaddr) ip_addr_set((&(buf)->addr), fromaddr) #define netbuf_fromport(buf) ((buf)->port) #if LWIP_NETBUF_RECVINFO #define netbuf_destaddr(buf) (&((buf)->toaddr)) #define netbuf_set_destaddr(buf, destaddr) ip_addr_set((&(buf)->addr), destaddr) #define netbuf_destport(buf) (((buf)->flags & NETBUF_FLAG_DESTADDR) ? (buf)->toport_chksum : 0) #endif /* LWIP_NETBUF_RECVINFO */ #if LWIP_CHECKSUM_ON_COPY #define netbuf_set_chksum(buf, chksum) do { (buf)->flags = NETBUF_FLAG_CHKSUM; \ (buf)->toport_chksum = chksum; } while(0) #endif /* LWIP_CHECKSUM_ON_COPY */ #ifdef __cplusplus } #endif #endif /* __LWIP_NETBUF_H__ */ ================================================ FILE: Zelig/lwip/lwip/include/lwip/netdb.h ================================================ /* * Redistribution and use in source and binary forms, with or without modification, * are permitted provided that the following conditions are met: * * 1. Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * 3. The name of the author may not be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT * SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT * OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING * IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY * OF SUCH DAMAGE. * * This file is part of the lwIP TCP/IP stack. * * Author: Simon Goldschmidt * */ #ifndef __LWIP_NETDB_H__ #define __LWIP_NETDB_H__ #include "lwip/opt.h" #if LWIP_DNS && LWIP_SOCKET #include /* for size_t */ #include "lwip/inet.h" #include "lwip/sockets.h" #ifdef __cplusplus extern "C" { #endif /* some rarely used options */ #ifndef LWIP_DNS_API_DECLARE_H_ERRNO #define LWIP_DNS_API_DECLARE_H_ERRNO 1 #endif #ifndef LWIP_DNS_API_DEFINE_ERRORS #define LWIP_DNS_API_DEFINE_ERRORS 1 #endif #ifndef LWIP_DNS_API_DECLARE_STRUCTS #define LWIP_DNS_API_DECLARE_STRUCTS 1 #endif #if LWIP_DNS_API_DEFINE_ERRORS /** Errors used by the DNS API functions, h_errno can be one of them */ #define EAI_NONAME 200 #define EAI_SERVICE 201 #define EAI_FAIL 202 #define EAI_MEMORY 203 #define HOST_NOT_FOUND 210 #define NO_DATA 211 #define NO_RECOVERY 212 #define TRY_AGAIN 213 #endif /* LWIP_DNS_API_DEFINE_ERRORS */ #if LWIP_DNS_API_DECLARE_STRUCTS struct hostent { char *h_name; /* Official name of the host. */ char **h_aliases; /* A pointer to an array of pointers to alternative host names, terminated by a null pointer. */ int h_addrtype; /* Address type. */ int h_length; /* The length, in bytes, of the address. */ char **h_addr_list; /* A pointer to an array of pointers to network addresses (in network byte order) for the host, terminated by a null pointer. */ #define h_addr h_addr_list[0] /* for backward compatibility */ }; struct addrinfo { int ai_flags; /* Input flags. */ int ai_family; /* Address family of socket. */ int ai_socktype; /* Socket type. */ int ai_protocol; /* Protocol of socket. */ socklen_t ai_addrlen; /* Length of socket address. */ struct sockaddr *ai_addr; /* Socket address of socket. */ char *ai_canonname; /* Canonical name of service location. */ struct addrinfo *ai_next; /* Pointer to next in list. */ }; #endif /* LWIP_DNS_API_DECLARE_STRUCTS */ #if LWIP_DNS_API_DECLARE_H_ERRNO /* application accessable error code set by the DNS API functions */ extern int h_errno; #endif /* LWIP_DNS_API_DECLARE_H_ERRNO*/ struct hostent *lwip_gethostbyname(const char *name); int lwip_gethostbyname_r(const char *name, struct hostent *ret, char *buf, size_t buflen, struct hostent **result, int *h_errnop); void lwip_freeaddrinfo(struct addrinfo *ai); int lwip_getaddrinfo(const char *nodename, const char *servname, const struct addrinfo *hints, struct addrinfo **res); #if LWIP_COMPAT_SOCKETS #define gethostbyname(name) lwip_gethostbyname(name) #define gethostbyname_r(name, ret, buf, buflen, result, h_errnop) \ lwip_gethostbyname_r(name, ret, buf, buflen, result, h_errnop) #define freeaddrinfo(addrinfo) lwip_freeaddrinfo(addrinfo) #define getaddrinfo(nodname, servname, hints, res) \ lwip_getaddrinfo(nodname, servname, hints, res) #endif /* LWIP_COMPAT_SOCKETS */ #ifdef __cplusplus } #endif #endif /* LWIP_DNS && LWIP_SOCKET */ #endif /* __LWIP_NETDB_H__ */ ================================================ FILE: Zelig/lwip/lwip/include/lwip/netif.h ================================================ /* * Copyright (c) 2001-2004 Swedish Institute of Computer Science. * All rights reserved. * * Redistribution and use in source and binary forms, with or without modification, * are permitted provided that the following conditions are met: * * 1. Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * 3. The name of the author may not be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT * SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT * OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING * IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY * OF SUCH DAMAGE. * * This file is part of the lwIP TCP/IP stack. * * Author: Adam Dunkels * */ #ifndef __LWIP_NETIF_H__ #define __LWIP_NETIF_H__ #include "lwip/opt.h" #define ENABLE_LOOPBACK (LWIP_NETIF_LOOPBACK || LWIP_HAVE_LOOPIF) #include "lwip/err.h" #include "lwip/ip_addr.h" #include "lwip/def.h" #include "lwip/pbuf.h" #if LWIP_DHCP struct dhcp; #endif #if LWIP_AUTOIP struct autoip; #endif #ifdef __cplusplus extern "C" { #endif /* Throughout this file, IP addresses are expected to be in * the same byte order as in IP_PCB. */ /** must be the maximum of all used hardware address lengths across all types of interfaces in use */ #define NETIF_MAX_HWADDR_LEN 6U /** Whether the network interface is 'up'. This is * a software flag used to control whether this network * interface is enabled and processes traffic. * It is set by the startup code (for static IP configuration) or * by dhcp/autoip when an address has been assigned. */ #define NETIF_FLAG_UP 0x01U /** If set, the netif has broadcast capability. * Set by the netif driver in its init function. */ #define NETIF_FLAG_BROADCAST 0x02U /** If set, the netif is one end of a point-to-point connection. * Set by the netif driver in its init function. */ #define NETIF_FLAG_POINTTOPOINT 0x04U /** If set, the interface is configured using DHCP. * Set by the DHCP code when starting or stopping DHCP. */ #define NETIF_FLAG_DHCP 0x08U /** If set, the interface has an active link * (set by the network interface driver). * Either set by the netif driver in its init function (if the link * is up at that time) or at a later point once the link comes up * (if link detection is supported by the hardware). */ #define NETIF_FLAG_LINK_UP 0x10U /** If set, the netif is an ethernet device using ARP. * Set by the netif driver in its init function. * Used to check input packet types and use of DHCP. */ #define NETIF_FLAG_ETHARP 0x20U /** If set, the netif is an ethernet device. It might not use * ARP or TCP/IP if it is used for PPPoE only. */ #define NETIF_FLAG_ETHERNET 0x40U /** If set, the netif has IGMP capability. * Set by the netif driver in its init function. */ #define NETIF_FLAG_IGMP 0x80U /** Function prototype for netif init functions. Set up flags and output/linkoutput * callback functions in this function. * * @param netif The netif to initialize */ typedef err_t (*netif_init_fn)(struct netif *netif); /** Function prototype for netif->input functions. This function is saved as 'input' * callback function in the netif struct. Call it when a packet has been received. * * @param p The received packet, copied into a pbuf * @param inp The netif which received the packet */ typedef err_t (*netif_input_fn)(struct pbuf *p, struct netif *inp); /** Function prototype for netif->output functions. Called by lwIP when a packet * shall be sent. For ethernet netif, set this to 'etharp_output' and set * 'linkoutput'. * * @param netif The netif which shall send a packet * @param p The packet to send (p->payload points to IP header) * @param ipaddr The IP address to which the packet shall be sent */ typedef err_t (*netif_output_fn)(struct netif *netif, struct pbuf *p, ip_addr_t *ipaddr); /** Function prototype for netif->linkoutput functions. Only used for ethernet * netifs. This function is called by ARP when a packet shall be sent. * * @param netif The netif which shall send a packet * @param p The packet to send (raw ethernet packet) */ typedef err_t (*netif_linkoutput_fn)(struct netif *netif, struct pbuf *p); /** Function prototype for netif status- or link-callback functions. */ typedef void (*netif_status_callback_fn)(struct netif *netif); /** Function prototype for netif igmp_mac_filter functions */ typedef err_t (*netif_igmp_mac_filter_fn)(struct netif *netif, ip_addr_t *group, u8_t action); /** Generic data structure used for all lwIP network interfaces. * The following fields should be filled in by the initialization * function for the device driver: hwaddr_len, hwaddr[], mtu, flags */ struct netif { /** pointer to next in linked list */ struct netif *next; /** IP address configuration in network byte order */ ip_addr_t ip_addr; ip_addr_t netmask; ip_addr_t gw; /** This function is called by the network device driver * to pass a packet up the TCP/IP stack. */ netif_input_fn input; /** This function is called by the IP module when it wants * to send a packet on the interface. This function typically * first resolves the hardware address, then sends the packet. */ netif_output_fn output; /** This function is called by the ARP module when it wants * to send a packet on the interface. This function outputs * the pbuf as-is on the link medium. */ netif_linkoutput_fn linkoutput; #if LWIP_NETIF_STATUS_CALLBACK /** This function is called when the netif state is set to up or down */ netif_status_callback_fn status_callback; #endif /* LWIP_NETIF_STATUS_CALLBACK */ #if LWIP_NETIF_LINK_CALLBACK /** This function is called when the netif link is set to up or down */ netif_status_callback_fn link_callback; #endif /* LWIP_NETIF_LINK_CALLBACK */ /** This field can be set by the device driver and could point * to state information for the device. */ void *state; #if LWIP_DHCP /** the DHCP client state information for this netif */ struct dhcp *dhcp; #endif /* LWIP_DHCP */ #if LWIP_AUTOIP /** the AutoIP client state information for this netif */ struct autoip *autoip; #endif #if LWIP_NETIF_HOSTNAME /* the hostname for this netif, NULL is a valid value */ char* hostname; #endif /* LWIP_NETIF_HOSTNAME */ /** maximum transfer unit (in bytes) */ u16_t mtu; /** number of bytes used in hwaddr */ u8_t hwaddr_len; /** link level hardware address of this interface */ u8_t hwaddr[NETIF_MAX_HWADDR_LEN]; /** flags (see NETIF_FLAG_ above) */ u8_t flags; /** descriptive abbreviation */ char name[2]; /** number of this interface */ u8_t num; #if LWIP_SNMP /** link type (from "snmp_ifType" enum from snmp.h) */ u8_t link_type; /** (estimate) link speed */ u32_t link_speed; /** timestamp at last change made (up/down) */ u32_t ts; /** counters */ u32_t ifinoctets; u32_t ifinucastpkts; u32_t ifinnucastpkts; u32_t ifindiscards; u32_t ifoutoctets; u32_t ifoutucastpkts; u32_t ifoutnucastpkts; u32_t ifoutdiscards; #endif /* LWIP_SNMP */ #if LWIP_IGMP /** This function could be called to add or delete a entry in the multicast filter table of the ethernet MAC.*/ netif_igmp_mac_filter_fn igmp_mac_filter; #endif /* LWIP_IGMP */ #if LWIP_NETIF_HWADDRHINT u8_t *addr_hint; #endif /* LWIP_NETIF_HWADDRHINT */ #if ENABLE_LOOPBACK /* List of packets to be queued for ourselves. */ struct pbuf *loop_first; struct pbuf *loop_last; #if LWIP_LOOPBACK_MAX_PBUFS u16_t loop_cnt_current; #endif /* LWIP_LOOPBACK_MAX_PBUFS */ #endif /* ENABLE_LOOPBACK */ }; #if LWIP_SNMP #define NETIF_INIT_SNMP(netif, type, speed) \ /* use "snmp_ifType" enum from snmp.h for "type", snmp_ifType_ethernet_csmacd by example */ \ (netif)->link_type = (type); \ /* your link speed here (units: bits per second) */ \ (netif)->link_speed = (speed); \ (netif)->ts = 0; \ (netif)->ifinoctets = 0; \ (netif)->ifinucastpkts = 0; \ (netif)->ifinnucastpkts = 0; \ (netif)->ifindiscards = 0; \ (netif)->ifoutoctets = 0; \ (netif)->ifoutucastpkts = 0; \ (netif)->ifoutnucastpkts = 0; \ (netif)->ifoutdiscards = 0 #else /* LWIP_SNMP */ #define NETIF_INIT_SNMP(netif, type, speed) #endif /* LWIP_SNMP */ /** The list of network interfaces. */ extern struct netif *netif_list; /** The default network interface. */ extern struct netif *netif_default; void netif_init(void); struct netif *netif_add(struct netif *netif, ip_addr_t *ipaddr, ip_addr_t *netmask, ip_addr_t *gw, void *state, netif_init_fn init, netif_input_fn input); void netif_set_addr(struct netif *netif, ip_addr_t *ipaddr, ip_addr_t *netmask, ip_addr_t *gw); void netif_remove(struct netif * netif); /* Returns a network interface given its name. The name is of the form "et0", where the first two letters are the "name" field in the netif structure, and the digit is in the num field in the same structure. */ struct netif *netif_find(char *name); void netif_set_default(struct netif *netif); void netif_set_ipaddr(struct netif *netif, ip_addr_t *ipaddr); void netif_set_netmask(struct netif *netif, ip_addr_t *netmask); void netif_set_gw(struct netif *netif, ip_addr_t *gw); void netif_set_up(struct netif *netif); void netif_set_down(struct netif *netif); /** Ask if an interface is up */ #define netif_is_up(netif) (((netif)->flags & NETIF_FLAG_UP) ? (u8_t)1 : (u8_t)0) #if LWIP_NETIF_STATUS_CALLBACK void netif_set_status_callback(struct netif *netif, netif_status_callback_fn status_callback); #endif /* LWIP_NETIF_STATUS_CALLBACK */ void netif_set_link_up(struct netif *netif); void netif_set_link_down(struct netif *netif); /** Ask if a link is up */ #define netif_is_link_up(netif) (((netif)->flags & NETIF_FLAG_LINK_UP) ? (u8_t)1 : (u8_t)0) #if LWIP_NETIF_LINK_CALLBACK void netif_set_link_callback(struct netif *netif, netif_status_callback_fn link_callback); #endif /* LWIP_NETIF_LINK_CALLBACK */ #if LWIP_NETIF_HOSTNAME #define netif_set_hostname(netif, name) do { if((netif) != NULL) { (netif)->hostname = name; }}while(0) #define netif_get_hostname(netif) (((netif) != NULL) ? ((netif)->hostname) : NULL) #endif /* LWIP_NETIF_HOSTNAME */ #if LWIP_IGMP #define netif_set_igmp_mac_filter(netif, function) do { if((netif) != NULL) { (netif)->igmp_mac_filter = function; }}while(0) #define netif_get_igmp_mac_filter(netif) (((netif) != NULL) ? ((netif)->igmp_mac_filter) : NULL) #endif /* LWIP_IGMP */ #if ENABLE_LOOPBACK err_t netif_loop_output(struct netif *netif, struct pbuf *p, ip_addr_t *dest_ip); void netif_poll(struct netif *netif); #if !LWIP_NETIF_LOOPBACK_MULTITHREADING void netif_poll_all(void); #endif /* !LWIP_NETIF_LOOPBACK_MULTITHREADING */ #endif /* ENABLE_LOOPBACK */ #ifdef __cplusplus } #endif #endif /* __LWIP_NETIF_H__ */ ================================================ FILE: Zelig/lwip/lwip/include/lwip/netifapi.h ================================================ /* * Redistribution and use in source and binary forms, with or without modification, * are permitted provided that the following conditions are met: * * 1. Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * 3. The name of the author may not be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT * SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT * OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING * IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY * OF SUCH DAMAGE. * * This file is part of the lwIP TCP/IP stack. * */ #ifndef __LWIP_NETIFAPI_H__ #define __LWIP_NETIFAPI_H__ #include "lwip/opt.h" #if LWIP_NETIF_API /* don't build if not configured for use in lwipopts.h */ #include "lwip/sys.h" #include "lwip/netif.h" #include "lwip/dhcp.h" #include "lwip/autoip.h" #ifdef __cplusplus extern "C" { #endif typedef void (*netifapi_void_fn)(struct netif *netif); typedef err_t (*netifapi_errt_fn)(struct netif *netif); struct netifapi_msg_msg { #if !LWIP_TCPIP_CORE_LOCKING sys_sem_t sem; #endif /* !LWIP_TCPIP_CORE_LOCKING */ err_t err; struct netif *netif; union { struct { ip_addr_t *ipaddr; ip_addr_t *netmask; ip_addr_t *gw; void *state; netif_init_fn init; netif_input_fn input; } add; struct { netifapi_void_fn voidfunc; netifapi_errt_fn errtfunc; } common; } msg; }; struct netifapi_msg { void (* function)(struct netifapi_msg_msg *msg); struct netifapi_msg_msg msg; }; /* API for application */ err_t netifapi_netif_add ( struct netif *netif, ip_addr_t *ipaddr, ip_addr_t *netmask, ip_addr_t *gw, void *state, netif_init_fn init, netif_input_fn input); err_t netifapi_netif_set_addr ( struct netif *netif, ip_addr_t *ipaddr, ip_addr_t *netmask, ip_addr_t *gw ); err_t netifapi_netif_common ( struct netif *netif, netifapi_void_fn voidfunc, netifapi_errt_fn errtfunc); #define netifapi_netif_remove(n) netifapi_netif_common(n, netif_remove, NULL) #define netifapi_netif_set_up(n) netifapi_netif_common(n, netif_set_up, NULL) #define netifapi_netif_set_down(n) netifapi_netif_common(n, netif_set_down, NULL) #define netifapi_netif_set_default(n) netifapi_netif_common(n, netif_set_default, NULL) #define netifapi_dhcp_start(n) netifapi_netif_common(n, NULL, dhcp_start) #define netifapi_dhcp_stop(n) netifapi_netif_common(n, dhcp_stop, NULL) #define netifapi_autoip_start(n) netifapi_netif_common(n, NULL, autoip_start) #define netifapi_autoip_stop(n) netifapi_netif_common(n, NULL, autoip_stop) #ifdef __cplusplus } #endif #endif /* LWIP_NETIF_API */ #endif /* __LWIP_NETIFAPI_H__ */ ================================================ FILE: Zelig/lwip/lwip/include/lwip/opt.h ================================================ /** * @file * * lwIP Options Configuration */ /* * Copyright (c) 2001-2004 Swedish Institute of Computer Science. * All rights reserved. * * Redistribution and use in source and binary forms, with or without modification, * are permitted provided that the following conditions are met: * * 1. Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * 3. The name of the author may not be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT * SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT * OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING * IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY * OF SUCH DAMAGE. * * This file is part of the lwIP TCP/IP stack. * * Author: Adam Dunkels * */ #ifndef __LWIP_OPT_H__ #define __LWIP_OPT_H__ /* * Include user defined options first. Anything not defined in these files * will be set to standard values. Override anything you dont like! */ #include "lwipopts.h" #include "lwip/debug.h" /* ----------------------------------------------- ---------- Platform specific locking ---------- ----------------------------------------------- */ /** * SYS_LIGHTWEIGHT_PROT==1: if you want inter-task protection for certain * critical regions during buffer allocation, deallocation and memory * allocation and deallocation. */ #ifndef SYS_LIGHTWEIGHT_PROT #define SYS_LIGHTWEIGHT_PROT 0 #endif /** * NO_SYS==1: Provides VERY minimal functionality. Otherwise, * use lwIP facilities. */ #ifndef NO_SYS #define NO_SYS 0 #endif /** * NO_SYS_NO_TIMERS==1: Drop support for sys_timeout when NO_SYS==1 * Mainly for compatibility to old versions. */ #ifndef NO_SYS_NO_TIMERS #define NO_SYS_NO_TIMERS 0 #endif /** * MEMCPY: override this if you have a faster implementation at hand than the * one included in your C library */ #ifndef MEMCPY #define MEMCPY(dst,src,len) memcpy(dst,src,len) #endif /** * SMEMCPY: override this with care! Some compilers (e.g. gcc) can inline a * call to memcpy() if the length is known at compile time and is small. */ #ifndef SMEMCPY #define SMEMCPY(dst,src,len) memcpy(dst,src,len) #endif /* ------------------------------------ ---------- Memory options ---------- ------------------------------------ */ /** * MEM_LIBC_MALLOC==1: Use malloc/free/realloc provided by your C-library * instead of the lwip internal allocator. Can save code size if you * already use it. */ #ifndef MEM_LIBC_MALLOC #define MEM_LIBC_MALLOC 0 #endif /** * MEMP_MEM_MALLOC==1: Use mem_malloc/mem_free instead of the lwip pool allocator. * Especially useful with MEM_LIBC_MALLOC but handle with care regarding execution * speed and usage from interrupts! */ #ifndef MEMP_MEM_MALLOC #define MEMP_MEM_MALLOC 0 #endif /** * MEM_ALIGNMENT: should be set to the alignment of the CPU * 4 byte alignment -> #define MEM_ALIGNMENT 4 * 2 byte alignment -> #define MEM_ALIGNMENT 2 */ #ifndef MEM_ALIGNMENT #define MEM_ALIGNMENT 1 #endif /** * MEM_SIZE: the size of the heap memory. If the application will send * a lot of data that needs to be copied, this should be set high. */ #ifndef MEM_SIZE #define MEM_SIZE 1600 #endif /** * MEMP_SEPARATE_POOLS: if defined to 1, each pool is placed in its own array. * This can be used to individually change the location of each pool. * Default is one big array for all pools */ #ifndef MEMP_SEPARATE_POOLS #define MEMP_SEPARATE_POOLS 0 #endif /** * MEMP_OVERFLOW_CHECK: memp overflow protection reserves a configurable * amount of bytes before and after each memp element in every pool and fills * it with a prominent default value. * MEMP_OVERFLOW_CHECK == 0 no checking * MEMP_OVERFLOW_CHECK == 1 checks each element when it is freed * MEMP_OVERFLOW_CHECK >= 2 checks each element in every pool every time * memp_malloc() or memp_free() is called (useful but slow!) */ #ifndef MEMP_OVERFLOW_CHECK #define MEMP_OVERFLOW_CHECK 0 #endif /** * MEMP_SANITY_CHECK==1: run a sanity check after each memp_free() to make * sure that there are no cycles in the linked lists. */ #ifndef MEMP_SANITY_CHECK #define MEMP_SANITY_CHECK 0 #endif /** * MEM_USE_POOLS==1: Use an alternative to malloc() by allocating from a set * of memory pools of various sizes. When mem_malloc is called, an element of * the smallest pool that can provide the length needed is returned. * To use this, MEMP_USE_CUSTOM_POOLS also has to be enabled. */ #ifndef MEM_USE_POOLS #define MEM_USE_POOLS 0 #endif /** * MEM_USE_POOLS_TRY_BIGGER_POOL==1: if one malloc-pool is empty, try the next * bigger pool - WARNING: THIS MIGHT WASTE MEMORY but it can make a system more * reliable. */ #ifndef MEM_USE_POOLS_TRY_BIGGER_POOL #define MEM_USE_POOLS_TRY_BIGGER_POOL 0 #endif /** * MEMP_USE_CUSTOM_POOLS==1: whether to include a user file lwippools.h * that defines additional pools beyond the "standard" ones required * by lwIP. If you set this to 1, you must have lwippools.h in your * inlude path somewhere. */ #ifndef MEMP_USE_CUSTOM_POOLS #define MEMP_USE_CUSTOM_POOLS 0 #endif /** * Set this to 1 if you want to free PBUF_RAM pbufs (or call mem_free()) from * interrupt context (or another context that doesn't allow waiting for a * semaphore). * If set to 1, mem_malloc will be protected by a semaphore and SYS_ARCH_PROTECT, * while mem_free will only use SYS_ARCH_PROTECT. mem_malloc SYS_ARCH_UNPROTECTs * with each loop so that mem_free can run. * * ATTENTION: As you can see from the above description, this leads to dis-/ * enabling interrupts often, which can be slow! Also, on low memory, mem_malloc * can need longer. * * If you don't want that, at least for NO_SYS=0, you can still use the following * functions to enqueue a deallocation call which then runs in the tcpip_thread * context: * - pbuf_free_callback(p); * - mem_free_callback(m); */ #ifndef LWIP_ALLOW_MEM_FREE_FROM_OTHER_CONTEXT #define LWIP_ALLOW_MEM_FREE_FROM_OTHER_CONTEXT 0 #endif /* ------------------------------------------------ ---------- Internal Memory Pool Sizes ---------- ------------------------------------------------ */ /** * MEMP_NUM_PBUF: the number of memp struct pbufs (used for PBUF_ROM and PBUF_REF). * If the application sends a lot of data out of ROM (or other static memory), * this should be set high. */ #ifndef MEMP_NUM_PBUF #define MEMP_NUM_PBUF 16 #endif /** * MEMP_NUM_RAW_PCB: Number of raw connection PCBs * (requires the LWIP_RAW option) */ #ifndef MEMP_NUM_RAW_PCB #define MEMP_NUM_RAW_PCB 4 #endif /** * MEMP_NUM_UDP_PCB: the number of UDP protocol control blocks. One * per active UDP "connection". * (requires the LWIP_UDP option) */ #ifndef MEMP_NUM_UDP_PCB #define MEMP_NUM_UDP_PCB 4 #endif /** * MEMP_NUM_TCP_PCB: the number of simulatenously active TCP connections. * (requires the LWIP_TCP option) */ #ifndef MEMP_NUM_TCP_PCB #define MEMP_NUM_TCP_PCB 5 #endif /** * MEMP_NUM_TCP_PCB_LISTEN: the number of listening TCP connections. * (requires the LWIP_TCP option) */ #ifndef MEMP_NUM_TCP_PCB_LISTEN #define MEMP_NUM_TCP_PCB_LISTEN 8 #endif /** * MEMP_NUM_TCP_SEG: the number of simultaneously queued TCP segments. * (requires the LWIP_TCP option) */ #ifndef MEMP_NUM_TCP_SEG #define MEMP_NUM_TCP_SEG 16 #endif /** * MEMP_NUM_REASSDATA: the number of IP packets simultaneously queued for * reassembly (whole packets, not fragments!) */ #ifndef MEMP_NUM_REASSDATA #define MEMP_NUM_REASSDATA 5 #endif /** * MEMP_NUM_FRAG_PBUF: the number of IP fragments simultaneously sent * (fragments, not whole packets!). * This is only used with IP_FRAG_USES_STATIC_BUF==0 and * LWIP_NETIF_TX_SINGLE_PBUF==0 and only has to be > 1 with DMA-enabled MACs * where the packet is not yet sent when netif->output returns. */ #ifndef MEMP_NUM_FRAG_PBUF #define MEMP_NUM_FRAG_PBUF 15 #endif /** * MEMP_NUM_ARP_QUEUE: the number of simulateously queued outgoing * packets (pbufs) that are waiting for an ARP request (to resolve * their destination address) to finish. * (requires the ARP_QUEUEING option) */ #ifndef MEMP_NUM_ARP_QUEUE #define MEMP_NUM_ARP_QUEUE 30 #endif /** * MEMP_NUM_IGMP_GROUP: The number of multicast groups whose network interfaces * can be members et the same time (one per netif - allsystems group -, plus one * per netif membership). * (requires the LWIP_IGMP option) */ #ifndef MEMP_NUM_IGMP_GROUP #define MEMP_NUM_IGMP_GROUP 8 #endif /** * MEMP_NUM_SYS_TIMEOUT: the number of simulateously active timeouts. * (requires NO_SYS==0) */ #ifndef MEMP_NUM_SYS_TIMEOUT #define MEMP_NUM_SYS_TIMEOUT 3 #endif /** * MEMP_NUM_NETBUF: the number of struct netbufs. * (only needed if you use the sequential API, like api_lib.c) */ #ifndef MEMP_NUM_NETBUF #define MEMP_NUM_NETBUF 2 #endif /** * MEMP_NUM_NETCONN: the number of struct netconns. * (only needed if you use the sequential API, like api_lib.c) */ #ifndef MEMP_NUM_NETCONN #define MEMP_NUM_NETCONN 4 #endif /** * MEMP_NUM_TCPIP_MSG_API: the number of struct tcpip_msg, which are used * for callback/timeout API communication. * (only needed if you use tcpip.c) */ #ifndef MEMP_NUM_TCPIP_MSG_API #define MEMP_NUM_TCPIP_MSG_API 8 #endif /** * MEMP_NUM_TCPIP_MSG_INPKT: the number of struct tcpip_msg, which are used * for incoming packets. * (only needed if you use tcpip.c) */ #ifndef MEMP_NUM_TCPIP_MSG_INPKT #define MEMP_NUM_TCPIP_MSG_INPKT 8 #endif /** * MEMP_NUM_SNMP_NODE: the number of leafs in the SNMP tree. */ #ifndef MEMP_NUM_SNMP_NODE #define MEMP_NUM_SNMP_NODE 50 #endif /** * MEMP_NUM_SNMP_ROOTNODE: the number of branches in the SNMP tree. * Every branch has one leaf (MEMP_NUM_SNMP_NODE) at least! */ #ifndef MEMP_NUM_SNMP_ROOTNODE #define MEMP_NUM_SNMP_ROOTNODE 30 #endif /** * MEMP_NUM_SNMP_VARBIND: the number of concurrent requests (does not have to * be changed normally) - 2 of these are used per request (1 for input, * 1 for output) */ #ifndef MEMP_NUM_SNMP_VARBIND #define MEMP_NUM_SNMP_VARBIND 2 #endif /** * MEMP_NUM_SNMP_VALUE: the number of OID or values concurrently used * (does not have to be changed normally) - 3 of these are used per request * (1 for the value read and 2 for OIDs - input and output) */ #ifndef MEMP_NUM_SNMP_VALUE #define MEMP_NUM_SNMP_VALUE 3 #endif /** * MEMP_NUM_NETDB: the number of concurrently running lwip_addrinfo() calls * (before freeing the corresponding memory using lwip_freeaddrinfo()). */ #ifndef MEMP_NUM_NETDB #define MEMP_NUM_NETDB 1 #endif /** * MEMP_NUM_LOCALHOSTLIST: the number of host entries in the local host list * if DNS_LOCAL_HOSTLIST_IS_DYNAMIC==1. */ #ifndef MEMP_NUM_LOCALHOSTLIST #define MEMP_NUM_LOCALHOSTLIST 1 #endif /** * MEMP_NUM_PPPOE_INTERFACES: the number of concurrently active PPPoE * interfaces (only used with PPPOE_SUPPORT==1) */ #ifndef MEMP_NUM_PPPOE_INTERFACES #define MEMP_NUM_PPPOE_INTERFACES 1 #endif /** * PBUF_POOL_SIZE: the number of buffers in the pbuf pool. */ #ifndef PBUF_POOL_SIZE #define PBUF_POOL_SIZE 16 #endif /* --------------------------------- ---------- ARP options ---------- --------------------------------- */ /** * LWIP_ARP==1: Enable ARP functionality. */ #ifndef LWIP_ARP #define LWIP_ARP 1 #endif /** * ARP_TABLE_SIZE: Number of active MAC-IP address pairs cached. */ #ifndef ARP_TABLE_SIZE #define ARP_TABLE_SIZE 10 #endif /** * ARP_QUEUEING==1: Multiple outgoing packets are queued during hardware address * resolution. By default, only the most recent packet is queued per IP address. * This is sufficient for most protocols and mainly reduces TCP connection * startup time. Set this to 1 if you know your application sends more than one * packet in a row to an IP address that is not in the ARP cache. */ #ifndef ARP_QUEUEING #define ARP_QUEUEING 0 #endif /** * ETHARP_TRUST_IP_MAC==1: Incoming IP packets cause the ARP table to be * updated with the source MAC and IP addresses supplied in the packet. * You may want to disable this if you do not trust LAN peers to have the * correct addresses, or as a limited approach to attempt to handle * spoofing. If disabled, lwIP will need to make a new ARP request if * the peer is not already in the ARP table, adding a little latency. * The peer *is* in the ARP table if it requested our address before. * Also notice that this slows down input processing of every IP packet! */ #ifndef ETHARP_TRUST_IP_MAC #define ETHARP_TRUST_IP_MAC 0 #endif /** * ETHARP_SUPPORT_VLAN==1: support receiving ethernet packets with VLAN header. * Additionally, you can define ETHARP_VLAN_CHECK to an u16_t VLAN ID to check. * If ETHARP_VLAN_CHECK is defined, only VLAN-traffic for this VLAN is accepted. * If ETHARP_VLAN_CHECK is not defined, all traffic is accepted. */ #ifndef ETHARP_SUPPORT_VLAN #define ETHARP_SUPPORT_VLAN 0 #endif /** LWIP_ETHERNET==1: enable ethernet support for PPPoE even though ARP * might be disabled */ #ifndef LWIP_ETHERNET #define LWIP_ETHERNET (LWIP_ARP || PPPOE_SUPPORT) #endif /** ETH_PAD_SIZE: number of bytes added before the ethernet header to ensure * alignment of payload after that header. Since the header is 14 bytes long, * without this padding e.g. addresses in the IP header will not be aligned * on a 32-bit boundary, so setting this to 2 can speed up 32-bit-platforms. */ #ifndef ETH_PAD_SIZE #define ETH_PAD_SIZE 0 #endif /** ETHARP_SUPPORT_STATIC_ENTRIES==1: enable code to support static ARP table * entries (using etharp_add_static_entry/etharp_remove_static_entry). */ #ifndef ETHARP_SUPPORT_STATIC_ENTRIES #define ETHARP_SUPPORT_STATIC_ENTRIES 0 #endif /* -------------------------------- ---------- IP options ---------- -------------------------------- */ /** * IP_FORWARD==1: Enables the ability to forward IP packets across network * interfaces. If you are going to run lwIP on a device with only one network * interface, define this to 0. */ #ifndef IP_FORWARD #define IP_FORWARD 0 #endif /** * IP_OPTIONS_ALLOWED: Defines the behavior for IP options. * IP_OPTIONS_ALLOWED==0: All packets with IP options are dropped. * IP_OPTIONS_ALLOWED==1: IP options are allowed (but not parsed). */ #ifndef IP_OPTIONS_ALLOWED #define IP_OPTIONS_ALLOWED 1 #endif /** * IP_REASSEMBLY==1: Reassemble incoming fragmented IP packets. Note that * this option does not affect outgoing packet sizes, which can be controlled * via IP_FRAG. */ #ifndef IP_REASSEMBLY #define IP_REASSEMBLY 1 #endif /** * IP_FRAG==1: Fragment outgoing IP packets if their size exceeds MTU. Note * that this option does not affect incoming packet sizes, which can be * controlled via IP_REASSEMBLY. */ #ifndef IP_FRAG #define IP_FRAG 1 #endif /** * IP_REASS_MAXAGE: Maximum time (in multiples of IP_TMR_INTERVAL - so seconds, normally) * a fragmented IP packet waits for all fragments to arrive. If not all fragments arrived * in this time, the whole packet is discarded. */ #ifndef IP_REASS_MAXAGE #define IP_REASS_MAXAGE 3 #endif /** * IP_REASS_MAX_PBUFS: Total maximum amount of pbufs waiting to be reassembled. * Since the received pbufs are enqueued, be sure to configure * PBUF_POOL_SIZE > IP_REASS_MAX_PBUFS so that the stack is still able to receive * packets even if the maximum amount of fragments is enqueued for reassembly! */ #ifndef IP_REASS_MAX_PBUFS #define IP_REASS_MAX_PBUFS 10 #endif /** * IP_FRAG_USES_STATIC_BUF==1: Use a static MTU-sized buffer for IP * fragmentation. Otherwise pbufs are allocated and reference the original * packet data to be fragmented (or with LWIP_NETIF_TX_SINGLE_PBUF==1, * new PBUF_RAM pbufs are used for fragments). * ATTENTION: IP_FRAG_USES_STATIC_BUF==1 may not be used for DMA-enabled MACs! */ #ifndef IP_FRAG_USES_STATIC_BUF #define IP_FRAG_USES_STATIC_BUF 0 #endif /** * IP_FRAG_MAX_MTU: Assumed max MTU on any interface for IP frag buffer * (requires IP_FRAG_USES_STATIC_BUF==1) */ #if IP_FRAG_USES_STATIC_BUF && !defined(IP_FRAG_MAX_MTU) #define IP_FRAG_MAX_MTU 1500 #endif /** * IP_DEFAULT_TTL: Default value for Time-To-Live used by transport layers. */ #ifndef IP_DEFAULT_TTL #define IP_DEFAULT_TTL 255 #endif /** * IP_SOF_BROADCAST=1: Use the SOF_BROADCAST field to enable broadcast * filter per pcb on udp and raw send operations. To enable broadcast filter * on recv operations, you also have to set IP_SOF_BROADCAST_RECV=1. */ #ifndef IP_SOF_BROADCAST #define IP_SOF_BROADCAST 0 #endif /** * IP_SOF_BROADCAST_RECV (requires IP_SOF_BROADCAST=1) enable the broadcast * filter on recv operations. */ #ifndef IP_SOF_BROADCAST_RECV #define IP_SOF_BROADCAST_RECV 0 #endif /* ---------------------------------- ---------- ICMP options ---------- ---------------------------------- */ /** * LWIP_ICMP==1: Enable ICMP module inside the IP stack. * Be careful, disable that make your product non-compliant to RFC1122 */ #ifndef LWIP_ICMP #define LWIP_ICMP 1 #endif /** * ICMP_TTL: Default value for Time-To-Live used by ICMP packets. */ #ifndef ICMP_TTL #define ICMP_TTL (IP_DEFAULT_TTL) #endif /** * LWIP_BROADCAST_PING==1: respond to broadcast pings (default is unicast only) */ #ifndef LWIP_BROADCAST_PING #define LWIP_BROADCAST_PING 0 #endif /** * LWIP_MULTICAST_PING==1: respond to multicast pings (default is unicast only) */ #ifndef LWIP_MULTICAST_PING #define LWIP_MULTICAST_PING 0 #endif /* --------------------------------- ---------- RAW options ---------- --------------------------------- */ /** * LWIP_RAW==1: Enable application layer to hook into the IP layer itself. */ #ifndef LWIP_RAW #define LWIP_RAW 1 #endif /** * LWIP_RAW==1: Enable application layer to hook into the IP layer itself. */ #ifndef RAW_TTL #define RAW_TTL (IP_DEFAULT_TTL) #endif /* ---------------------------------- ---------- DHCP options ---------- ---------------------------------- */ /** * LWIP_DHCP==1: Enable DHCP module. */ #ifndef LWIP_DHCP #define LWIP_DHCP 0 #endif /** * DHCP_DOES_ARP_CHECK==1: Do an ARP check on the offered address. */ #ifndef DHCP_DOES_ARP_CHECK #define DHCP_DOES_ARP_CHECK ((LWIP_DHCP) && (LWIP_ARP)) #endif /* ------------------------------------ ---------- AUTOIP options ---------- ------------------------------------ */ /** * LWIP_AUTOIP==1: Enable AUTOIP module. */ #ifndef LWIP_AUTOIP #define LWIP_AUTOIP 0 #endif /** * LWIP_DHCP_AUTOIP_COOP==1: Allow DHCP and AUTOIP to be both enabled on * the same interface at the same time. */ #ifndef LWIP_DHCP_AUTOIP_COOP #define LWIP_DHCP_AUTOIP_COOP 0 #endif /** * LWIP_DHCP_AUTOIP_COOP_TRIES: Set to the number of DHCP DISCOVER probes * that should be sent before falling back on AUTOIP. This can be set * as low as 1 to get an AutoIP address very quickly, but you should * be prepared to handle a changing IP address when DHCP overrides * AutoIP. */ #ifndef LWIP_DHCP_AUTOIP_COOP_TRIES #define LWIP_DHCP_AUTOIP_COOP_TRIES 9 #endif /* ---------------------------------- ---------- SNMP options ---------- ---------------------------------- */ /** * LWIP_SNMP==1: Turn on SNMP module. UDP must be available for SNMP * transport. */ #ifndef LWIP_SNMP #define LWIP_SNMP 0 #endif /** * SNMP_CONCURRENT_REQUESTS: Number of concurrent requests the module will * allow. At least one request buffer is required. * Does not have to be changed unless external MIBs answer request asynchronously */ #ifndef SNMP_CONCURRENT_REQUESTS #define SNMP_CONCURRENT_REQUESTS 1 #endif /** * SNMP_TRAP_DESTINATIONS: Number of trap destinations. At least one trap * destination is required */ #ifndef SNMP_TRAP_DESTINATIONS #define SNMP_TRAP_DESTINATIONS 1 #endif /** * SNMP_PRIVATE_MIB: * When using a private MIB, you have to create a file 'private_mib.h' that contains * a 'struct mib_array_node mib_private' which contains your MIB. */ #ifndef SNMP_PRIVATE_MIB #define SNMP_PRIVATE_MIB 0 #endif /** * Only allow SNMP write actions that are 'safe' (e.g. disabeling netifs is not * a safe action and disabled when SNMP_SAFE_REQUESTS = 1). * Unsafe requests are disabled by default! */ #ifndef SNMP_SAFE_REQUESTS #define SNMP_SAFE_REQUESTS 1 #endif /** * The maximum length of strings used. This affects the size of * MEMP_SNMP_VALUE elements. */ #ifndef SNMP_MAX_OCTET_STRING_LEN #define SNMP_MAX_OCTET_STRING_LEN 127 #endif /** * The maximum depth of the SNMP tree. * With private MIBs enabled, this depends on your MIB! * This affects the size of MEMP_SNMP_VALUE elements. */ #ifndef SNMP_MAX_TREE_DEPTH #define SNMP_MAX_TREE_DEPTH 15 #endif /** * The size of the MEMP_SNMP_VALUE elements, normally calculated from * SNMP_MAX_OCTET_STRING_LEN and SNMP_MAX_TREE_DEPTH. */ #ifndef SNMP_MAX_VALUE_SIZE #define SNMP_MAX_VALUE_SIZE LWIP_MAX((SNMP_MAX_OCTET_STRING_LEN)+1, sizeof(s32_t)*(SNMP_MAX_TREE_DEPTH)) #endif /* ---------------------------------- ---------- IGMP options ---------- ---------------------------------- */ /** * LWIP_IGMP==1: Turn on IGMP module. */ #ifndef LWIP_IGMP #define LWIP_IGMP 0 #endif /* ---------------------------------- ---------- DNS options ----------- ---------------------------------- */ /** * LWIP_DNS==1: Turn on DNS module. UDP must be available for DNS * transport. */ #ifndef LWIP_DNS #define LWIP_DNS 0 #endif /** DNS maximum number of entries to maintain locally. */ #ifndef DNS_TABLE_SIZE #define DNS_TABLE_SIZE 4 #endif /** DNS maximum host name length supported in the name table. */ #ifndef DNS_MAX_NAME_LENGTH #define DNS_MAX_NAME_LENGTH 256 #endif /** The maximum of DNS servers */ #ifndef DNS_MAX_SERVERS #define DNS_MAX_SERVERS 2 #endif /** DNS do a name checking between the query and the response. */ #ifndef DNS_DOES_NAME_CHECK #define DNS_DOES_NAME_CHECK 1 #endif /** DNS message max. size. Default value is RFC compliant. */ #ifndef DNS_MSG_SIZE #define DNS_MSG_SIZE 512 #endif /** DNS_LOCAL_HOSTLIST: Implements a local host-to-address list. If enabled, * you have to define * #define DNS_LOCAL_HOSTLIST_INIT {{"host1", 0x123}, {"host2", 0x234}} * (an array of structs name/address, where address is an u32_t in network * byte order). * * Instead, you can also use an external function: * #define DNS_LOOKUP_LOCAL_EXTERN(x) extern u32_t my_lookup_function(const char *name) * that returns the IP address or INADDR_NONE if not found. */ #ifndef DNS_LOCAL_HOSTLIST #define DNS_LOCAL_HOSTLIST 0 #endif /* DNS_LOCAL_HOSTLIST */ /** If this is turned on, the local host-list can be dynamically changed * at runtime. */ #ifndef DNS_LOCAL_HOSTLIST_IS_DYNAMIC #define DNS_LOCAL_HOSTLIST_IS_DYNAMIC 0 #endif /* DNS_LOCAL_HOSTLIST_IS_DYNAMIC */ /* --------------------------------- ---------- UDP options ---------- --------------------------------- */ /** * LWIP_UDP==1: Turn on UDP. */ #ifndef LWIP_UDP #define LWIP_UDP 1 #endif /** * LWIP_UDPLITE==1: Turn on UDP-Lite. (Requires LWIP_UDP) */ #ifndef LWIP_UDPLITE #define LWIP_UDPLITE 0 #endif /** * UDP_TTL: Default Time-To-Live value. */ #ifndef UDP_TTL #define UDP_TTL (IP_DEFAULT_TTL) #endif /** * LWIP_NETBUF_RECVINFO==1: append destination addr and port to every netbuf. */ #ifndef LWIP_NETBUF_RECVINFO #define LWIP_NETBUF_RECVINFO 0 #endif /* --------------------------------- ---------- TCP options ---------- --------------------------------- */ /** * LWIP_TCP==1: Turn on TCP. */ #ifndef LWIP_TCP #define LWIP_TCP 1 #endif /** * TCP_TTL: Default Time-To-Live value. */ #ifndef TCP_TTL #define TCP_TTL (IP_DEFAULT_TTL) #endif /** * TCP_WND: The size of a TCP window. This must be at least * (2 * TCP_MSS) for things to work well */ #ifndef TCP_WND #define TCP_WND (4 * TCP_MSS) #endif /** * TCP_MAXRTX: Maximum number of retransmissions of data segments. */ #ifndef TCP_MAXRTX #define TCP_MAXRTX 12 #endif /** * TCP_SYNMAXRTX: Maximum number of retransmissions of SYN segments. */ #ifndef TCP_SYNMAXRTX #define TCP_SYNMAXRTX 6 #endif /** * TCP_QUEUE_OOSEQ==1: TCP will queue segments that arrive out of order. * Define to 0 if your device is low on memory. */ #ifndef TCP_QUEUE_OOSEQ #define TCP_QUEUE_OOSEQ (LWIP_TCP) #endif /** * TCP_MSS: TCP Maximum segment size. (default is 536, a conservative default, * you might want to increase this.) * For the receive side, this MSS is advertised to the remote side * when opening a connection. For the transmit size, this MSS sets * an upper limit on the MSS advertised by the remote host. */ #ifndef TCP_MSS #define TCP_MSS 536 #endif /** * TCP_CALCULATE_EFF_SEND_MSS: "The maximum size of a segment that TCP really * sends, the 'effective send MSS,' MUST be the smaller of the send MSS (which * reflects the available reassembly buffer size at the remote host) and the * largest size permitted by the IP layer" (RFC 1122) * Setting this to 1 enables code that checks TCP_MSS against the MTU of the * netif used for a connection and limits the MSS if it would be too big otherwise. */ #ifndef TCP_CALCULATE_EFF_SEND_MSS #define TCP_CALCULATE_EFF_SEND_MSS 1 #endif /** * TCP_SND_BUF: TCP sender buffer space (bytes). */ #ifndef TCP_SND_BUF #define TCP_SND_BUF 256 #endif /** * TCP_SND_QUEUELEN: TCP sender buffer space (pbufs). This must be at least * as much as (2 * TCP_SND_BUF/TCP_MSS) for things to work. */ #ifndef TCP_SND_QUEUELEN #define TCP_SND_QUEUELEN ((4 * (TCP_SND_BUF) + (TCP_MSS - 1))/(TCP_MSS)) #endif /** * TCP_SNDLOWAT: TCP writable space (bytes). This must be less than * TCP_SND_BUF. It is the amount of space which must be available in the * TCP snd_buf for select to return writable (combined with TCP_SNDQUEUELOWAT). */ #ifndef TCP_SNDLOWAT #define TCP_SNDLOWAT ((TCP_SND_BUF)/2) #endif /** * TCP_SNDQUEUELOWAT: TCP writable bufs (pbuf count). This must be grater * than TCP_SND_QUEUELEN. If the number of pbufs queued on a pcb drops below * this number, select returns writable (combined with TCP_SNDLOWAT). */ #ifndef TCP_SNDQUEUELOWAT #define TCP_SNDQUEUELOWAT ((TCP_SND_QUEUELEN)/2) #endif /** * TCP_LISTEN_BACKLOG: Enable the backlog option for tcp listen pcb. */ #ifndef TCP_LISTEN_BACKLOG #define TCP_LISTEN_BACKLOG 0 #endif /** * The maximum allowed backlog for TCP listen netconns. * This backlog is used unless another is explicitly specified. * 0xff is the maximum (u8_t). */ #ifndef TCP_DEFAULT_LISTEN_BACKLOG #define TCP_DEFAULT_LISTEN_BACKLOG 0xff #endif /** * TCP_OVERSIZE: The maximum number of bytes that tcp_write may * allocate ahead of time in an attempt to create shorter pbuf chains * for transmission. The meaningful range is 0 to TCP_MSS. Some * suggested values are: * * 0: Disable oversized allocation. Each tcp_write() allocates a new pbuf (old behaviour). * 1: Allocate size-aligned pbufs with minimal excess. Use this if your * scatter-gather DMA requires aligned fragments. * 128: Limit the pbuf/memory overhead to 20%. * TCP_MSS: Try to create unfragmented TCP packets. * TCP_MSS/4: Try to create 4 fragments or less per TCP packet. */ #ifndef TCP_OVERSIZE #define TCP_OVERSIZE TCP_MSS #endif /** * LWIP_TCP_TIMESTAMPS==1: support the TCP timestamp option. */ #ifndef LWIP_TCP_TIMESTAMPS #define LWIP_TCP_TIMESTAMPS 0 #endif /** * TCP_WND_UPDATE_THRESHOLD: difference in window to trigger an * explicit window update */ #ifndef TCP_WND_UPDATE_THRESHOLD #define TCP_WND_UPDATE_THRESHOLD (TCP_WND / 4) #endif /** * LWIP_EVENT_API and LWIP_CALLBACK_API: Only one of these should be set to 1. * LWIP_EVENT_API==1: The user defines lwip_tcp_event() to receive all * events (accept, sent, etc) that happen in the system. * LWIP_CALLBACK_API==1: The PCB callback function is called directly * for the event. */ #ifndef LWIP_EVENT_API #define LWIP_EVENT_API 0 #define LWIP_CALLBACK_API 1 #else #define LWIP_EVENT_API 1 #define LWIP_CALLBACK_API 0 #endif /* ---------------------------------- ---------- Pbuf options ---------- ---------------------------------- */ /** * PBUF_LINK_HLEN: the number of bytes that should be allocated for a * link level header. The default is 14, the standard value for * Ethernet. */ #ifndef PBUF_LINK_HLEN #define PBUF_LINK_HLEN (14 + ETH_PAD_SIZE) #endif /** * PBUF_POOL_BUFSIZE: the size of each pbuf in the pbuf pool. The default is * designed to accomodate single full size TCP frame in one pbuf, including * TCP_MSS, IP header, and link header. */ #ifndef PBUF_POOL_BUFSIZE #define PBUF_POOL_BUFSIZE LWIP_MEM_ALIGN_SIZE(TCP_MSS+40+PBUF_LINK_HLEN) #endif /* ------------------------------------------------ ---------- Network Interfaces options ---------- ------------------------------------------------ */ /** * LWIP_NETIF_HOSTNAME==1: use DHCP_OPTION_HOSTNAME with netif's hostname * field. */ #ifndef LWIP_NETIF_HOSTNAME #define LWIP_NETIF_HOSTNAME 0 #endif /** * LWIP_NETIF_API==1: Support netif api (in netifapi.c) */ #ifndef LWIP_NETIF_API #define LWIP_NETIF_API 0 #endif /** * LWIP_NETIF_STATUS_CALLBACK==1: Support a callback function whenever an interface * changes its up/down status (i.e., due to DHCP IP acquistion) */ #ifndef LWIP_NETIF_STATUS_CALLBACK #define LWIP_NETIF_STATUS_CALLBACK 0 #endif /** * LWIP_NETIF_LINK_CALLBACK==1: Support a callback function from an interface * whenever the link changes (i.e., link down) */ #ifndef LWIP_NETIF_LINK_CALLBACK #define LWIP_NETIF_LINK_CALLBACK 0 #endif /** * LWIP_NETIF_HWADDRHINT==1: Cache link-layer-address hints (e.g. table * indices) in struct netif. TCP and UDP can make use of this to prevent * scanning the ARP table for every sent packet. While this is faster for big * ARP tables or many concurrent connections, it might be counterproductive * if you have a tiny ARP table or if there never are concurrent connections. */ #ifndef LWIP_NETIF_HWADDRHINT #define LWIP_NETIF_HWADDRHINT 0 #endif /** * LWIP_NETIF_LOOPBACK==1: Support sending packets with a destination IP * address equal to the netif IP address, looping them back up the stack. */ #ifndef LWIP_NETIF_LOOPBACK #define LWIP_NETIF_LOOPBACK 0 #endif /** * LWIP_LOOPBACK_MAX_PBUFS: Maximum number of pbufs on queue for loopback * sending for each netif (0 = disabled) */ #ifndef LWIP_LOOPBACK_MAX_PBUFS #define LWIP_LOOPBACK_MAX_PBUFS 0 #endif /** * LWIP_NETIF_LOOPBACK_MULTITHREADING: Indicates whether threading is enabled in * the system, as netifs must change how they behave depending on this setting * for the LWIP_NETIF_LOOPBACK option to work. * Setting this is needed to avoid reentering non-reentrant functions like * tcp_input(). * LWIP_NETIF_LOOPBACK_MULTITHREADING==1: Indicates that the user is using a * multithreaded environment like tcpip.c. In this case, netif->input() * is called directly. * LWIP_NETIF_LOOPBACK_MULTITHREADING==0: Indicates a polling (or NO_SYS) setup. * The packets are put on a list and netif_poll() must be called in * the main application loop. */ #ifndef LWIP_NETIF_LOOPBACK_MULTITHREADING #define LWIP_NETIF_LOOPBACK_MULTITHREADING (!NO_SYS) #endif /** * LWIP_NETIF_TX_SINGLE_PBUF: if this is set to 1, lwIP tries to put all data * to be sent into one single pbuf. This is for compatibility with DMA-enabled * MACs that do not support scatter-gather. * Beware that this might involve CPU-memcpy before transmitting that would not * be needed without this flag! Use this only if you need to! * * @todo: TCP and IP-frag do not work with this, yet: */ #ifndef LWIP_NETIF_TX_SINGLE_PBUF #define LWIP_NETIF_TX_SINGLE_PBUF 0 #endif /* LWIP_NETIF_TX_SINGLE_PBUF */ /* ------------------------------------ ---------- LOOPIF options ---------- ------------------------------------ */ /** * LWIP_HAVE_LOOPIF==1: Support loop interface (127.0.0.1) and loopif.c */ #ifndef LWIP_HAVE_LOOPIF #define LWIP_HAVE_LOOPIF 0 #endif /* ------------------------------------ ---------- SLIPIF options ---------- ------------------------------------ */ /** * LWIP_HAVE_SLIPIF==1: Support slip interface and slipif.c */ #ifndef LWIP_HAVE_SLIPIF #define LWIP_HAVE_SLIPIF 0 #endif /* ------------------------------------ ---------- Thread options ---------- ------------------------------------ */ /** * TCPIP_THREAD_NAME: The name assigned to the main tcpip thread. */ #ifndef TCPIP_THREAD_NAME #define TCPIP_THREAD_NAME "tcpip_thread" #endif /** * TCPIP_THREAD_STACKSIZE: The stack size used by the main tcpip thread. * The stack size value itself is platform-dependent, but is passed to * sys_thread_new() when the thread is created. */ #ifndef TCPIP_THREAD_STACKSIZE #define TCPIP_THREAD_STACKSIZE 0 #endif /** * TCPIP_THREAD_PRIO: The priority assigned to the main tcpip thread. * The priority value itself is platform-dependent, but is passed to * sys_thread_new() when the thread is created. */ #ifndef TCPIP_THREAD_PRIO #define TCPIP_THREAD_PRIO 1 #endif /** * TCPIP_MBOX_SIZE: The mailbox size for the tcpip thread messages * The queue size value itself is platform-dependent, but is passed to * sys_mbox_new() when tcpip_init is called. */ #ifndef TCPIP_MBOX_SIZE #define TCPIP_MBOX_SIZE 0 #endif /** * SLIPIF_THREAD_NAME: The name assigned to the slipif_loop thread. */ #ifndef SLIPIF_THREAD_NAME #define SLIPIF_THREAD_NAME "slipif_loop" #endif /** * SLIP_THREAD_STACKSIZE: The stack size used by the slipif_loop thread. * The stack size value itself is platform-dependent, but is passed to * sys_thread_new() when the thread is created. */ #ifndef SLIPIF_THREAD_STACKSIZE #define SLIPIF_THREAD_STACKSIZE 0 #endif /** * SLIPIF_THREAD_PRIO: The priority assigned to the slipif_loop thread. * The priority value itself is platform-dependent, but is passed to * sys_thread_new() when the thread is created. */ #ifndef SLIPIF_THREAD_PRIO #define SLIPIF_THREAD_PRIO 1 #endif /** * PPP_THREAD_NAME: The name assigned to the pppInputThread. */ #ifndef PPP_THREAD_NAME #define PPP_THREAD_NAME "pppInputThread" #endif /** * PPP_THREAD_STACKSIZE: The stack size used by the pppInputThread. * The stack size value itself is platform-dependent, but is passed to * sys_thread_new() when the thread is created. */ #ifndef PPP_THREAD_STACKSIZE #define PPP_THREAD_STACKSIZE 0 #endif /** * PPP_THREAD_PRIO: The priority assigned to the pppInputThread. * The priority value itself is platform-dependent, but is passed to * sys_thread_new() when the thread is created. */ #ifndef PPP_THREAD_PRIO #define PPP_THREAD_PRIO 1 #endif /** * DEFAULT_THREAD_NAME: The name assigned to any other lwIP thread. */ #ifndef DEFAULT_THREAD_NAME #define DEFAULT_THREAD_NAME "lwIP" #endif /** * DEFAULT_THREAD_STACKSIZE: The stack size used by any other lwIP thread. * The stack size value itself is platform-dependent, but is passed to * sys_thread_new() when the thread is created. */ #ifndef DEFAULT_THREAD_STACKSIZE #define DEFAULT_THREAD_STACKSIZE 0 #endif /** * DEFAULT_THREAD_PRIO: The priority assigned to any other lwIP thread. * The priority value itself is platform-dependent, but is passed to * sys_thread_new() when the thread is created. */ #ifndef DEFAULT_THREAD_PRIO #define DEFAULT_THREAD_PRIO 1 #endif /** * DEFAULT_RAW_RECVMBOX_SIZE: The mailbox size for the incoming packets on a * NETCONN_RAW. The queue size value itself is platform-dependent, but is passed * to sys_mbox_new() when the recvmbox is created. */ #ifndef DEFAULT_RAW_RECVMBOX_SIZE #define DEFAULT_RAW_RECVMBOX_SIZE 0 #endif /** * DEFAULT_UDP_RECVMBOX_SIZE: The mailbox size for the incoming packets on a * NETCONN_UDP. The queue size value itself is platform-dependent, but is passed * to sys_mbox_new() when the recvmbox is created. */ #ifndef DEFAULT_UDP_RECVMBOX_SIZE #define DEFAULT_UDP_RECVMBOX_SIZE 0 #endif /** * DEFAULT_TCP_RECVMBOX_SIZE: The mailbox size for the incoming packets on a * NETCONN_TCP. The queue size value itself is platform-dependent, but is passed * to sys_mbox_new() when the recvmbox is created. */ #ifndef DEFAULT_TCP_RECVMBOX_SIZE #define DEFAULT_TCP_RECVMBOX_SIZE 0 #endif /** * DEFAULT_ACCEPTMBOX_SIZE: The mailbox size for the incoming connections. * The queue size value itself is platform-dependent, but is passed to * sys_mbox_new() when the acceptmbox is created. */ #ifndef DEFAULT_ACCEPTMBOX_SIZE #define DEFAULT_ACCEPTMBOX_SIZE 0 #endif /* ---------------------------------------------- ---------- Sequential layer options ---------- ---------------------------------------------- */ /** * LWIP_TCPIP_CORE_LOCKING: (EXPERIMENTAL!) * Don't use it if you're not an active lwIP project member */ #ifndef LWIP_TCPIP_CORE_LOCKING #define LWIP_TCPIP_CORE_LOCKING 0 #endif /** * LWIP_TCPIP_CORE_LOCKING_INPUT: (EXPERIMENTAL!) * Don't use it if you're not an active lwIP project member */ #ifndef LWIP_TCPIP_CORE_LOCKING_INPUT #define LWIP_TCPIP_CORE_LOCKING_INPUT 0 #endif /** * LWIP_NETCONN==1: Enable Netconn API (require to use api_lib.c) */ #ifndef LWIP_NETCONN #define LWIP_NETCONN 1 #endif /** LWIP_TCPIP_TIMEOUT==1: Enable tcpip_timeout/tcpip_untimeout tod create * timers running in tcpip_thread from another thread. */ #ifndef LWIP_TCPIP_TIMEOUT #define LWIP_TCPIP_TIMEOUT 1 #endif /* ------------------------------------ ---------- Socket options ---------- ------------------------------------ */ /** * LWIP_SOCKET==1: Enable Socket API (require to use sockets.c) */ #ifndef LWIP_SOCKET #define LWIP_SOCKET 1 #endif /** * LWIP_COMPAT_SOCKETS==1: Enable BSD-style sockets functions names. * (only used if you use sockets.c) */ #ifndef LWIP_COMPAT_SOCKETS #define LWIP_COMPAT_SOCKETS 0 #endif /** * LWIP_POSIX_SOCKETS_IO_NAMES==1: Enable POSIX-style sockets functions names. * Disable this option if you use a POSIX operating system that uses the same * names (read, write & close). (only used if you use sockets.c) */ #ifndef LWIP_POSIX_SOCKETS_IO_NAMES #define LWIP_POSIX_SOCKETS_IO_NAMES 1 #endif /** * LWIP_TCP_KEEPALIVE==1: Enable TCP_KEEPIDLE, TCP_KEEPINTVL and TCP_KEEPCNT * options processing. Note that TCP_KEEPIDLE and TCP_KEEPINTVL have to be set * in seconds. (does not require sockets.c, and will affect tcp.c) */ #ifndef LWIP_TCP_KEEPALIVE #define LWIP_TCP_KEEPALIVE 0 #endif /** * LWIP_SO_RCVTIMEO==1: Enable SO_RCVTIMEO processing. */ #ifndef LWIP_SO_RCVTIMEO #define LWIP_SO_RCVTIMEO 0 #endif /** * LWIP_SO_RCVBUF==1: Enable SO_RCVBUF processing. */ #ifndef LWIP_SO_RCVBUF #define LWIP_SO_RCVBUF 0 #endif /** * If LWIP_SO_RCVBUF is used, this is the default value for recv_bufsize. */ #ifndef RECV_BUFSIZE_DEFAULT #define RECV_BUFSIZE_DEFAULT INT_MAX #endif /** * SO_REUSE==1: Enable SO_REUSEADDR option. */ #ifndef SO_REUSE #define SO_REUSE 0 #endif /** * SO_REUSE_RXTOALL==1: Pass a copy of incoming broadcast/multicast packets * to all local matches if SO_REUSEADDR is turned on. * WARNING: Adds a memcpy for every packet if passing to more than one pcb! */ #ifndef SO_REUSE_RXTOALL #define SO_REUSE_RXTOALL 0 #endif /* ---------------------------------------- ---------- Statistics options ---------- ---------------------------------------- */ /** * LWIP_STATS==1: Enable statistics collection in lwip_stats. */ #ifndef LWIP_STATS #define LWIP_STATS 1 #endif #if LWIP_STATS /** * LWIP_STATS_DISPLAY==1: Compile in the statistics output functions. */ #ifndef LWIP_STATS_DISPLAY #define LWIP_STATS_DISPLAY 0 #endif /** * LINK_STATS==1: Enable link stats. */ #ifndef LINK_STATS #define LINK_STATS 1 #endif /** * ETHARP_STATS==1: Enable etharp stats. */ #ifndef ETHARP_STATS #define ETHARP_STATS (LWIP_ARP) #endif /** * IP_STATS==1: Enable IP stats. */ #ifndef IP_STATS #define IP_STATS 1 #endif /** * IPFRAG_STATS==1: Enable IP fragmentation stats. Default is * on if using either frag or reass. */ #ifndef IPFRAG_STATS #define IPFRAG_STATS (IP_REASSEMBLY || IP_FRAG) #endif /** * ICMP_STATS==1: Enable ICMP stats. */ #ifndef ICMP_STATS #define ICMP_STATS 1 #endif /** * IGMP_STATS==1: Enable IGMP stats. */ #ifndef IGMP_STATS #define IGMP_STATS (LWIP_IGMP) #endif /** * UDP_STATS==1: Enable UDP stats. Default is on if * UDP enabled, otherwise off. */ #ifndef UDP_STATS #define UDP_STATS (LWIP_UDP) #endif /** * TCP_STATS==1: Enable TCP stats. Default is on if TCP * enabled, otherwise off. */ #ifndef TCP_STATS #define TCP_STATS (LWIP_TCP) #endif /** * MEM_STATS==1: Enable mem.c stats. */ #ifndef MEM_STATS #define MEM_STATS ((MEM_LIBC_MALLOC == 0) && (MEM_USE_POOLS == 0)) #endif /** * MEMP_STATS==1: Enable memp.c pool stats. */ #ifndef MEMP_STATS #define MEMP_STATS (MEMP_MEM_MALLOC == 0) #endif /** * SYS_STATS==1: Enable system stats (sem and mbox counts, etc). */ #ifndef SYS_STATS #define SYS_STATS (NO_SYS == 0) #endif #else #define LINK_STATS 0 #define IP_STATS 0 #define IPFRAG_STATS 0 #define ICMP_STATS 0 #define IGMP_STATS 0 #define UDP_STATS 0 #define TCP_STATS 0 #define MEM_STATS 0 #define MEMP_STATS 0 #define SYS_STATS 0 #define LWIP_STATS_DISPLAY 0 #endif /* LWIP_STATS */ /* --------------------------------- ---------- PPP options ---------- --------------------------------- */ /** * PPP_SUPPORT==1: Enable PPP. */ #ifndef PPP_SUPPORT #define PPP_SUPPORT 0 #endif /** * PPPOE_SUPPORT==1: Enable PPP Over Ethernet */ #ifndef PPPOE_SUPPORT #define PPPOE_SUPPORT 0 #endif /** * PPPOS_SUPPORT==1: Enable PPP Over Serial */ #ifndef PPPOS_SUPPORT #define PPPOS_SUPPORT PPP_SUPPORT #endif #if PPP_SUPPORT /** * NUM_PPP: Max PPP sessions. */ #ifndef NUM_PPP #define NUM_PPP 1 #endif /** * PAP_SUPPORT==1: Support PAP. */ #ifndef PAP_SUPPORT #define PAP_SUPPORT 0 #endif /** * CHAP_SUPPORT==1: Support CHAP. */ #ifndef CHAP_SUPPORT #define CHAP_SUPPORT 0 #endif /** * MSCHAP_SUPPORT==1: Support MSCHAP. CURRENTLY NOT SUPPORTED! DO NOT SET! */ #ifndef MSCHAP_SUPPORT #define MSCHAP_SUPPORT 0 #endif /** * CBCP_SUPPORT==1: Support CBCP. CURRENTLY NOT SUPPORTED! DO NOT SET! */ #ifndef CBCP_SUPPORT #define CBCP_SUPPORT 0 #endif /** * CCP_SUPPORT==1: Support CCP. CURRENTLY NOT SUPPORTED! DO NOT SET! */ #ifndef CCP_SUPPORT #define CCP_SUPPORT 0 #endif /** * VJ_SUPPORT==1: Support VJ header compression. */ #ifndef VJ_SUPPORT #define VJ_SUPPORT 0 #endif /** * MD5_SUPPORT==1: Support MD5 (see also CHAP). */ #ifndef MD5_SUPPORT #define MD5_SUPPORT 0 #endif /* * Timeouts */ #ifndef FSM_DEFTIMEOUT #define FSM_DEFTIMEOUT 6 /* Timeout time in seconds */ #endif #ifndef FSM_DEFMAXTERMREQS #define FSM_DEFMAXTERMREQS 2 /* Maximum Terminate-Request transmissions */ #endif #ifndef FSM_DEFMAXCONFREQS #define FSM_DEFMAXCONFREQS 10 /* Maximum Configure-Request transmissions */ #endif #ifndef FSM_DEFMAXNAKLOOPS #define FSM_DEFMAXNAKLOOPS 5 /* Maximum number of nak loops */ #endif #ifndef UPAP_DEFTIMEOUT #define UPAP_DEFTIMEOUT 6 /* Timeout (seconds) for retransmitting req */ #endif #ifndef UPAP_DEFREQTIME #define UPAP_DEFREQTIME 30 /* Time to wait for auth-req from peer */ #endif #ifndef CHAP_DEFTIMEOUT #define CHAP_DEFTIMEOUT 6 /* Timeout time in seconds */ #endif #ifndef CHAP_DEFTRANSMITS #define CHAP_DEFTRANSMITS 10 /* max # times to send challenge */ #endif /* Interval in seconds between keepalive echo requests, 0 to disable. */ #ifndef LCP_ECHOINTERVAL #define LCP_ECHOINTERVAL 0 #endif /* Number of unanswered echo requests before failure. */ #ifndef LCP_MAXECHOFAILS #define LCP_MAXECHOFAILS 3 #endif /* Max Xmit idle time (in jiffies) before resend flag char. */ #ifndef PPP_MAXIDLEFLAG #define PPP_MAXIDLEFLAG 100 #endif /* * Packet sizes * * Note - lcp shouldn't be allowed to negotiate stuff outside these * limits. See lcp.h in the pppd directory. * (XXX - these constants should simply be shared by lcp.c instead * of living in lcp.h) */ #define PPP_MTU 1500 /* Default MTU (size of Info field) */ #ifndef PPP_MAXMTU /* #define PPP_MAXMTU 65535 - (PPP_HDRLEN + PPP_FCSLEN) */ #define PPP_MAXMTU 1500 /* Largest MTU we allow */ #endif #define PPP_MINMTU 64 #define PPP_MRU 1500 /* default MRU = max length of info field */ #define PPP_MAXMRU 1500 /* Largest MRU we allow */ #ifndef PPP_DEFMRU #define PPP_DEFMRU 296 /* Try for this */ #endif #define PPP_MINMRU 128 /* No MRUs below this */ #ifndef MAXNAMELEN #define MAXNAMELEN 256 /* max length of hostname or name for auth */ #endif #ifndef MAXSECRETLEN #define MAXSECRETLEN 256 /* max length of password or secret */ #endif #endif /* PPP_SUPPORT */ /* -------------------------------------- ---------- Checksum options ---------- -------------------------------------- */ /** * CHECKSUM_GEN_IP==1: Generate checksums in software for outgoing IP packets. */ #ifndef CHECKSUM_GEN_IP #define CHECKSUM_GEN_IP 1 #endif /** * CHECKSUM_GEN_UDP==1: Generate checksums in software for outgoing UDP packets. */ #ifndef CHECKSUM_GEN_UDP #define CHECKSUM_GEN_UDP 1 #endif /** * CHECKSUM_GEN_TCP==1: Generate checksums in software for outgoing TCP packets. */ #ifndef CHECKSUM_GEN_TCP #define CHECKSUM_GEN_TCP 1 #endif /** * CHECKSUM_CHECK_IP==1: Check checksums in software for incoming IP packets. */ #ifndef CHECKSUM_CHECK_IP #define CHECKSUM_CHECK_IP 1 #endif /** * CHECKSUM_CHECK_UDP==1: Check checksums in software for incoming UDP packets. */ #ifndef CHECKSUM_CHECK_UDP #define CHECKSUM_CHECK_UDP 1 #endif /** * CHECKSUM_CHECK_TCP==1: Check checksums in software for incoming TCP packets. */ #ifndef CHECKSUM_CHECK_TCP #define CHECKSUM_CHECK_TCP 1 #endif /** * LWIP_CHECKSUM_ON_COPY==1: Calculate checksum when copying data from * application buffers to pbufs. */ #ifndef LWIP_CHECKSUM_ON_COPY #define LWIP_CHECKSUM_ON_COPY 0 #endif /* --------------------------------------- ---------- Debugging options ---------- --------------------------------------- */ /** * LWIP_DBG_MIN_LEVEL: After masking, the value of the debug is * compared against this value. If it is smaller, then debugging * messages are written. */ #ifndef LWIP_DBG_MIN_LEVEL #define LWIP_DBG_MIN_LEVEL LWIP_DBG_LEVEL_ALL #endif /** * LWIP_DBG_TYPES_ON: A mask that can be used to globally enable/disable * debug messages of certain types. */ #ifndef LWIP_DBG_TYPES_ON #define LWIP_DBG_TYPES_ON LWIP_DBG_ON #endif /** * ETHARP_DEBUG: Enable debugging in etharp.c. */ #ifndef ETHARP_DEBUG #define ETHARP_DEBUG LWIP_DBG_OFF #endif /** * NETIF_DEBUG: Enable debugging in netif.c. */ #ifndef NETIF_DEBUG #define NETIF_DEBUG LWIP_DBG_OFF #endif /** * PBUF_DEBUG: Enable debugging in pbuf.c. */ #ifndef PBUF_DEBUG #define PBUF_DEBUG LWIP_DBG_OFF #endif /** * API_LIB_DEBUG: Enable debugging in api_lib.c. */ #ifndef API_LIB_DEBUG #define API_LIB_DEBUG LWIP_DBG_OFF #endif /** * API_MSG_DEBUG: Enable debugging in api_msg.c. */ #ifndef API_MSG_DEBUG #define API_MSG_DEBUG LWIP_DBG_OFF #endif /** * SOCKETS_DEBUG: Enable debugging in sockets.c. */ #ifndef SOCKETS_DEBUG #define SOCKETS_DEBUG LWIP_DBG_OFF #endif /** * ICMP_DEBUG: Enable debugging in icmp.c. */ #ifndef ICMP_DEBUG #define ICMP_DEBUG LWIP_DBG_OFF #endif /** * IGMP_DEBUG: Enable debugging in igmp.c. */ #ifndef IGMP_DEBUG #define IGMP_DEBUG LWIP_DBG_OFF #endif /** * INET_DEBUG: Enable debugging in inet.c. */ #ifndef INET_DEBUG #define INET_DEBUG LWIP_DBG_OFF #endif /** * IP_DEBUG: Enable debugging for IP. */ #ifndef IP_DEBUG #define IP_DEBUG LWIP_DBG_OFF #endif /** * IP_REASS_DEBUG: Enable debugging in ip_frag.c for both frag & reass. */ #ifndef IP_REASS_DEBUG #define IP_REASS_DEBUG LWIP_DBG_OFF #endif /** * RAW_DEBUG: Enable debugging in raw.c. */ #ifndef RAW_DEBUG #define RAW_DEBUG LWIP_DBG_OFF #endif /** * MEM_DEBUG: Enable debugging in mem.c. */ #ifndef MEM_DEBUG #define MEM_DEBUG LWIP_DBG_OFF #endif /** * MEMP_DEBUG: Enable debugging in memp.c. */ #ifndef MEMP_DEBUG #define MEMP_DEBUG LWIP_DBG_OFF #endif /** * SYS_DEBUG: Enable debugging in sys.c. */ #ifndef SYS_DEBUG #define SYS_DEBUG LWIP_DBG_OFF #endif /** * TIMERS_DEBUG: Enable debugging in timers.c. */ #ifndef TIMERS_DEBUG #define TIMERS_DEBUG LWIP_DBG_OFF #endif /** * TCP_DEBUG: Enable debugging for TCP. */ #ifndef TCP_DEBUG #define TCP_DEBUG LWIP_DBG_OFF #endif /** * TCP_INPUT_DEBUG: Enable debugging in tcp_in.c for incoming debug. */ #ifndef TCP_INPUT_DEBUG #define TCP_INPUT_DEBUG LWIP_DBG_OFF #endif /** * TCP_FR_DEBUG: Enable debugging in tcp_in.c for fast retransmit. */ #ifndef TCP_FR_DEBUG #define TCP_FR_DEBUG LWIP_DBG_OFF #endif /** * TCP_RTO_DEBUG: Enable debugging in TCP for retransmit * timeout. */ #ifndef TCP_RTO_DEBUG #define TCP_RTO_DEBUG LWIP_DBG_OFF #endif /** * TCP_CWND_DEBUG: Enable debugging for TCP congestion window. */ #ifndef TCP_CWND_DEBUG #define TCP_CWND_DEBUG LWIP_DBG_OFF #endif /** * TCP_WND_DEBUG: Enable debugging in tcp_in.c for window updating. */ #ifndef TCP_WND_DEBUG #define TCP_WND_DEBUG LWIP_DBG_OFF #endif /** * TCP_OUTPUT_DEBUG: Enable debugging in tcp_out.c output functions. */ #ifndef TCP_OUTPUT_DEBUG #define TCP_OUTPUT_DEBUG LWIP_DBG_OFF #endif /** * TCP_RST_DEBUG: Enable debugging for TCP with the RST message. */ #ifndef TCP_RST_DEBUG #define TCP_RST_DEBUG LWIP_DBG_OFF #endif /** * TCP_QLEN_DEBUG: Enable debugging for TCP queue lengths. */ #ifndef TCP_QLEN_DEBUG #define TCP_QLEN_DEBUG LWIP_DBG_OFF #endif /** * UDP_DEBUG: Enable debugging in UDP. */ #ifndef UDP_DEBUG #define UDP_DEBUG LWIP_DBG_OFF #endif /** * TCPIP_DEBUG: Enable debugging in tcpip.c. */ #ifndef TCPIP_DEBUG #define TCPIP_DEBUG LWIP_DBG_OFF #endif /** * PPP_DEBUG: Enable debugging for PPP. */ #ifndef PPP_DEBUG #define PPP_DEBUG LWIP_DBG_OFF #endif /** * SLIP_DEBUG: Enable debugging in slipif.c. */ #ifndef SLIP_DEBUG #define SLIP_DEBUG LWIP_DBG_OFF #endif /** * DHCP_DEBUG: Enable debugging in dhcp.c. */ #ifndef DHCP_DEBUG #define DHCP_DEBUG LWIP_DBG_OFF #endif /** * AUTOIP_DEBUG: Enable debugging in autoip.c. */ #ifndef AUTOIP_DEBUG #define AUTOIP_DEBUG LWIP_DBG_OFF #endif /** * SNMP_MSG_DEBUG: Enable debugging for SNMP messages. */ #ifndef SNMP_MSG_DEBUG #define SNMP_MSG_DEBUG LWIP_DBG_OFF #endif /** * SNMP_MIB_DEBUG: Enable debugging for SNMP MIBs. */ #ifndef SNMP_MIB_DEBUG #define SNMP_MIB_DEBUG LWIP_DBG_OFF #endif /** * DNS_DEBUG: Enable debugging for DNS. */ #ifndef DNS_DEBUG #define DNS_DEBUG LWIP_DBG_OFF #endif #endif /* __LWIP_OPT_H__ */ ================================================ FILE: Zelig/lwip/lwip/include/lwip/pbuf.h ================================================ /* * Copyright (c) 2001-2004 Swedish Institute of Computer Science. * All rights reserved. * * Redistribution and use in source and binary forms, with or without modification, * are permitted provided that the following conditions are met: * * 1. Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * 3. The name of the author may not be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT * SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT * OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING * IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY * OF SUCH DAMAGE. * * This file is part of the lwIP TCP/IP stack. * * Author: Adam Dunkels * */ #ifndef __LWIP_PBUF_H__ #define __LWIP_PBUF_H__ #include "lwip/opt.h" #include "lwip/err.h" #ifdef __cplusplus extern "C" { #endif /** Currently, the pbuf_custom code is only needed for one specific configuration * of IP_FRAG */ #define LWIP_SUPPORT_CUSTOM_PBUF (IP_FRAG && !IP_FRAG_USES_STATIC_BUF && !LWIP_NETIF_TX_SINGLE_PBUF) #define PBUF_TRANSPORT_HLEN 20 #define PBUF_IP_HLEN 20 typedef enum { PBUF_TRANSPORT, PBUF_IP, PBUF_LINK, PBUF_RAW } pbuf_layer; typedef enum { PBUF_RAM, /* pbuf data is stored in RAM */ PBUF_ROM, /* pbuf data is stored in ROM */ PBUF_REF, /* pbuf comes from the pbuf pool */ PBUF_POOL /* pbuf payload refers to RAM */ } pbuf_type; /** indicates this packet's data should be immediately passed to the application */ #define PBUF_FLAG_PUSH 0x01U /** indicates this is a custom pbuf: pbuf_free and pbuf_header handle such a a pbuf differently */ #define PBUF_FLAG_IS_CUSTOM 0x02U /** indicates this pbuf is UDP multicast to be looped back */ #define PBUF_FLAG_MCASTLOOP 0x04U struct pbuf { /** next pbuf in singly linked pbuf chain */ struct pbuf *next; /** pointer to the actual data in the buffer */ void *payload; /** * total length of this buffer and all next buffers in chain * belonging to the same packet. * * For non-queue packet chains this is the invariant: * p->tot_len == p->len + (p->next? p->next->tot_len: 0) */ u16_t tot_len; /** length of this buffer */ u16_t len; /** pbuf_type as u8_t instead of enum to save space */ u8_t /*pbuf_type*/ type; /** misc flags */ u8_t flags; /** * the reference count always equals the number of pointers * that refer to this pbuf. This can be pointers from an application, * the stack itself, or pbuf->next pointers from a chain. */ u16_t ref; }; #if LWIP_SUPPORT_CUSTOM_PBUF /** Prototype for a function to free a custom pbuf */ typedef void (*pbuf_free_custom_fn)(struct pbuf *p); /** A custom pbuf: like a pbuf, but following a function pointer to free it. */ struct pbuf_custom { /** The actual pbuf */ struct pbuf pbuf; /** This function is called when pbuf_free deallocates this pbuf(_custom) */ pbuf_free_custom_fn custom_free_function; }; #endif /* LWIP_SUPPORT_CUSTOM_PBUF */ /* Initializes the pbuf module. This call is empty for now, but may not be in future. */ #define pbuf_init() struct pbuf *pbuf_alloc(pbuf_layer l, u16_t length, pbuf_type type); #if LWIP_SUPPORT_CUSTOM_PBUF struct pbuf *pbuf_alloced_custom(pbuf_layer l, u16_t length, pbuf_type type, struct pbuf_custom *p, void *payload_mem, u16_t payload_mem_len); #endif /* LWIP_SUPPORT_CUSTOM_PBUF */ void pbuf_realloc(struct pbuf *p, u16_t size); u8_t pbuf_header(struct pbuf *p, s16_t header_size); void pbuf_ref(struct pbuf *p); u8_t pbuf_free(struct pbuf *p); u8_t pbuf_clen(struct pbuf *p); void pbuf_cat(struct pbuf *head, struct pbuf *tail); void pbuf_chain(struct pbuf *head, struct pbuf *tail); struct pbuf *pbuf_dechain(struct pbuf *p); err_t pbuf_copy(struct pbuf *p_to, struct pbuf *p_from); u16_t pbuf_copy_partial(struct pbuf *p, void *dataptr, u16_t len, u16_t offset); err_t pbuf_take(struct pbuf *buf, const void *dataptr, u16_t len); struct pbuf *pbuf_coalesce(struct pbuf *p, pbuf_layer layer); #if LWIP_CHECKSUM_ON_COPY err_t pbuf_fill_chksum(struct pbuf *p, u16_t start_offset, const void *dataptr, u16_t len, u16_t *chksum); #endif /* LWIP_CHECKSUM_ON_COPY */ u8_t pbuf_get_at(struct pbuf* p, u16_t offset); u16_t pbuf_memcmp(struct pbuf* p, u16_t offset, const void* s2, u16_t n); u16_t pbuf_memfind(struct pbuf* p, const void* mem, u16_t mem_len, u16_t start_offset); u16_t pbuf_strstr(struct pbuf* p, const char* substr); #ifdef __cplusplus } #endif #endif /* __LWIP_PBUF_H__ */ ================================================ FILE: Zelig/lwip/lwip/include/lwip/raw.h ================================================ /* * Copyright (c) 2001-2004 Swedish Institute of Computer Science. * All rights reserved. * * Redistribution and use in source and binary forms, with or without modification, * are permitted provided that the following conditions are met: * * 1. Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * 3. The name of the author may not be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT * SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT * OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING * IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY * OF SUCH DAMAGE. * * This file is part of the lwIP TCP/IP stack. * * Author: Adam Dunkels * */ #ifndef __LWIP_RAW_H__ #define __LWIP_RAW_H__ #include "lwip/opt.h" #if LWIP_RAW /* don't build if not configured for use in lwipopts.h */ #include "lwip/pbuf.h" #include "lwip/def.h" #include "lwip/ip.h" #include "lwip/ip_addr.h" #ifdef __cplusplus extern "C" { #endif struct raw_pcb; /** Function prototype for raw pcb receive callback functions. * @param arg user supplied argument (raw_pcb.recv_arg) * @param pcb the raw_pcb which received data * @param p the packet buffer that was received * @param addr the remote IP address from which the packet was received * @return 1 if the packet was 'eaten' (aka. deleted), * 0 if the packet lives on * If returning 1, the callback is responsible for freeing the pbuf * if it's not used any more. */ typedef u8_t (*raw_recv_fn)(void *arg, struct raw_pcb *pcb, struct pbuf *p, ip_addr_t *addr); struct raw_pcb { /* Common members of all PCB types */ IP_PCB; struct raw_pcb *next; u8_t protocol; /** receive callback function */ raw_recv_fn recv; /* user-supplied argument for the recv callback */ void *recv_arg; }; /* The following functions is the application layer interface to the RAW code. */ struct raw_pcb * raw_new (u8_t proto); void raw_remove (struct raw_pcb *pcb); err_t raw_bind (struct raw_pcb *pcb, ip_addr_t *ipaddr); err_t raw_connect (struct raw_pcb *pcb, ip_addr_t *ipaddr); void raw_recv (struct raw_pcb *pcb, raw_recv_fn recv, void *recv_arg); err_t raw_sendto (struct raw_pcb *pcb, struct pbuf *p, ip_addr_t *ipaddr); err_t raw_send (struct raw_pcb *pcb, struct pbuf *p); /* The following functions are the lower layer interface to RAW. */ u8_t raw_input (struct pbuf *p, struct netif *inp); #define raw_init() /* Compatibility define, not init needed. */ #ifdef __cplusplus } #endif #endif /* LWIP_RAW */ #endif /* __LWIP_RAW_H__ */ ================================================ FILE: Zelig/lwip/lwip/include/lwip/sio.h ================================================ /* * Copyright (c) 2001-2004 Swedish Institute of Computer Science. * All rights reserved. * * Redistribution and use in source and binary forms, with or without modification, * are permitted provided that the following conditions are met: * * 1. Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * 3. The name of the author may not be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT * SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT * OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING * IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY * OF SUCH DAMAGE. * * This file is part of the lwIP TCP/IP stack. */ /* * This is the interface to the platform specific serial IO module * It needs to be implemented by those platforms which need SLIP or PPP */ #ifndef __SIO_H__ #define __SIO_H__ #include "lwip/arch.h" #ifdef __cplusplus extern "C" { #endif /* If you want to define sio_fd_t elsewhere or differently, define this in your cc.h file. */ #ifndef __sio_fd_t_defined typedef void * sio_fd_t; #endif /* The following functions can be defined to something else in your cc.h file or be implemented in your custom sio.c file. */ #ifndef sio_open /** * Opens a serial device for communication. * * @param devnum device number * @return handle to serial device if successful, NULL otherwise */ sio_fd_t sio_open(u8_t devnum); #endif #ifndef sio_send /** * Sends a single character to the serial device. * * @param c character to send * @param fd serial device handle * * @note This function will block until the character can be sent. */ void sio_send(u8_t c, sio_fd_t fd); #endif #ifndef sio_recv /** * Receives a single character from the serial device. * * @param fd serial device handle * * @note This function will block until a character is received. */ u8_t sio_recv(sio_fd_t fd); #endif #ifndef sio_read /** * Reads from the serial device. * * @param fd serial device handle * @param data pointer to data buffer for receiving * @param len maximum length (in bytes) of data to receive * @return number of bytes actually received - may be 0 if aborted by sio_read_abort * * @note This function will block until data can be received. The blocking * can be cancelled by calling sio_read_abort(). */ u32_t sio_read(sio_fd_t fd, u8_t *data, u32_t len); #endif #ifndef sio_tryread /** * Tries to read from the serial device. Same as sio_read but returns * immediately if no data is available and never blocks. * * @param fd serial device handle * @param data pointer to data buffer for receiving * @param len maximum length (in bytes) of data to receive * @return number of bytes actually received */ u32_t sio_tryread(sio_fd_t fd, u8_t *data, u32_t len); #endif #ifndef sio_write /** * Writes to the serial device. * * @param fd serial device handle * @param data pointer to data to send * @param len length (in bytes) of data to send * @return number of bytes actually sent * * @note This function will block until all data can be sent. */ u32_t sio_write(sio_fd_t fd, u8_t *data, u32_t len); #endif #ifndef sio_read_abort /** * Aborts a blocking sio_read() call. * * @param fd serial device handle */ void sio_read_abort(sio_fd_t fd); #endif #ifdef __cplusplus } #endif #endif /* __SIO_H__ */ ================================================ FILE: Zelig/lwip/lwip/include/lwip/snmp.h ================================================ /* * Copyright (c) 2001, 2002 Leon Woestenberg * Copyright (c) 2001, 2002 Axon Digital Design B.V., The Netherlands. * All rights reserved. * * Redistribution and use in source and binary forms, with or without modification, * are permitted provided that the following conditions are met: * * 1. Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * 3. The name of the author may not be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT * SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT * OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING * IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY * OF SUCH DAMAGE. * * This file is part of the lwIP TCP/IP stack. * * Author: Leon Woestenberg * */ #ifndef __LWIP_SNMP_H__ #define __LWIP_SNMP_H__ #include "lwip/opt.h" #ifdef __cplusplus extern "C" { #endif #include "lwip/ip_addr.h" struct udp_pcb; struct netif; /** * @see RFC1213, "MIB-II, 6. Definitions" */ enum snmp_ifType { snmp_ifType_other=1, /* none of the following */ snmp_ifType_regular1822, snmp_ifType_hdh1822, snmp_ifType_ddn_x25, snmp_ifType_rfc877_x25, snmp_ifType_ethernet_csmacd, snmp_ifType_iso88023_csmacd, snmp_ifType_iso88024_tokenBus, snmp_ifType_iso88025_tokenRing, snmp_ifType_iso88026_man, snmp_ifType_starLan, snmp_ifType_proteon_10Mbit, snmp_ifType_proteon_80Mbit, snmp_ifType_hyperchannel, snmp_ifType_fddi, snmp_ifType_lapb, snmp_ifType_sdlc, snmp_ifType_ds1, /* T-1 */ snmp_ifType_e1, /* european equiv. of T-1 */ snmp_ifType_basicISDN, snmp_ifType_primaryISDN, /* proprietary serial */ snmp_ifType_propPointToPointSerial, snmp_ifType_ppp, snmp_ifType_softwareLoopback, snmp_ifType_eon, /* CLNP over IP [11] */ snmp_ifType_ethernet_3Mbit, snmp_ifType_nsip, /* XNS over IP */ snmp_ifType_slip, /* generic SLIP */ snmp_ifType_ultra, /* ULTRA technologies */ snmp_ifType_ds3, /* T-3 */ snmp_ifType_sip, /* SMDS */ snmp_ifType_frame_relay }; #if LWIP_SNMP /* don't build if not configured for use in lwipopts.h */ /** SNMP "sysuptime" Interval */ #define SNMP_SYSUPTIME_INTERVAL 10 /** fixed maximum length for object identifier type */ #define LWIP_SNMP_OBJ_ID_LEN 32 /** internal object identifier representation */ struct snmp_obj_id { u8_t len; s32_t id[LWIP_SNMP_OBJ_ID_LEN]; }; /* system */ void snmp_set_sysdesr(u8_t* str, u8_t* len); void snmp_set_sysobjid(struct snmp_obj_id *oid); void snmp_get_sysobjid_ptr(struct snmp_obj_id **oid); void snmp_inc_sysuptime(void); void snmp_add_sysuptime(u32_t value); void snmp_get_sysuptime(u32_t *value); void snmp_set_syscontact(u8_t *ocstr, u8_t *ocstrlen); void snmp_set_sysname(u8_t *ocstr, u8_t *ocstrlen); void snmp_set_syslocation(u8_t *ocstr, u8_t *ocstrlen); /* network interface */ void snmp_add_ifinoctets(struct netif *ni, u32_t value); void snmp_inc_ifinucastpkts(struct netif *ni); void snmp_inc_ifinnucastpkts(struct netif *ni); void snmp_inc_ifindiscards(struct netif *ni); void snmp_add_ifoutoctets(struct netif *ni, u32_t value); void snmp_inc_ifoutucastpkts(struct netif *ni); void snmp_inc_ifoutnucastpkts(struct netif *ni); void snmp_inc_ifoutdiscards(struct netif *ni); void snmp_inc_iflist(void); void snmp_dec_iflist(void); /* ARP (for atTable and ipNetToMediaTable) */ void snmp_insert_arpidx_tree(struct netif *ni, ip_addr_t *ip); void snmp_delete_arpidx_tree(struct netif *ni, ip_addr_t *ip); /* IP */ void snmp_inc_ipinreceives(void); void snmp_inc_ipinhdrerrors(void); void snmp_inc_ipinaddrerrors(void); void snmp_inc_ipforwdatagrams(void); void snmp_inc_ipinunknownprotos(void); void snmp_inc_ipindiscards(void); void snmp_inc_ipindelivers(void); void snmp_inc_ipoutrequests(void); void snmp_inc_ipoutdiscards(void); void snmp_inc_ipoutnoroutes(void); void snmp_inc_ipreasmreqds(void); void snmp_inc_ipreasmoks(void); void snmp_inc_ipreasmfails(void); void snmp_inc_ipfragoks(void); void snmp_inc_ipfragfails(void); void snmp_inc_ipfragcreates(void); void snmp_inc_iproutingdiscards(void); void snmp_insert_ipaddridx_tree(struct netif *ni); void snmp_delete_ipaddridx_tree(struct netif *ni); void snmp_insert_iprteidx_tree(u8_t dflt, struct netif *ni); void snmp_delete_iprteidx_tree(u8_t dflt, struct netif *ni); /* ICMP */ void snmp_inc_icmpinmsgs(void); void snmp_inc_icmpinerrors(void); void snmp_inc_icmpindestunreachs(void); void snmp_inc_icmpintimeexcds(void); void snmp_inc_icmpinparmprobs(void); void snmp_inc_icmpinsrcquenchs(void); void snmp_inc_icmpinredirects(void); void snmp_inc_icmpinechos(void); void snmp_inc_icmpinechoreps(void); void snmp_inc_icmpintimestamps(void); void snmp_inc_icmpintimestampreps(void); void snmp_inc_icmpinaddrmasks(void); void snmp_inc_icmpinaddrmaskreps(void); void snmp_inc_icmpoutmsgs(void); void snmp_inc_icmpouterrors(void); void snmp_inc_icmpoutdestunreachs(void); void snmp_inc_icmpouttimeexcds(void); void snmp_inc_icmpoutparmprobs(void); void snmp_inc_icmpoutsrcquenchs(void); void snmp_inc_icmpoutredirects(void); void snmp_inc_icmpoutechos(void); void snmp_inc_icmpoutechoreps(void); void snmp_inc_icmpouttimestamps(void); void snmp_inc_icmpouttimestampreps(void); void snmp_inc_icmpoutaddrmasks(void); void snmp_inc_icmpoutaddrmaskreps(void); /* TCP */ void snmp_inc_tcpactiveopens(void); void snmp_inc_tcppassiveopens(void); void snmp_inc_tcpattemptfails(void); void snmp_inc_tcpestabresets(void); void snmp_inc_tcpinsegs(void); void snmp_inc_tcpoutsegs(void); void snmp_inc_tcpretranssegs(void); void snmp_inc_tcpinerrs(void); void snmp_inc_tcpoutrsts(void); /* UDP */ void snmp_inc_udpindatagrams(void); void snmp_inc_udpnoports(void); void snmp_inc_udpinerrors(void); void snmp_inc_udpoutdatagrams(void); void snmp_insert_udpidx_tree(struct udp_pcb *pcb); void snmp_delete_udpidx_tree(struct udp_pcb *pcb); /* SNMP */ void snmp_inc_snmpinpkts(void); void snmp_inc_snmpoutpkts(void); void snmp_inc_snmpinbadversions(void); void snmp_inc_snmpinbadcommunitynames(void); void snmp_inc_snmpinbadcommunityuses(void); void snmp_inc_snmpinasnparseerrs(void); void snmp_inc_snmpintoobigs(void); void snmp_inc_snmpinnosuchnames(void); void snmp_inc_snmpinbadvalues(void); void snmp_inc_snmpinreadonlys(void); void snmp_inc_snmpingenerrs(void); void snmp_add_snmpintotalreqvars(u8_t value); void snmp_add_snmpintotalsetvars(u8_t value); void snmp_inc_snmpingetrequests(void); void snmp_inc_snmpingetnexts(void); void snmp_inc_snmpinsetrequests(void); void snmp_inc_snmpingetresponses(void); void snmp_inc_snmpintraps(void); void snmp_inc_snmpouttoobigs(void); void snmp_inc_snmpoutnosuchnames(void); void snmp_inc_snmpoutbadvalues(void); void snmp_inc_snmpoutgenerrs(void); void snmp_inc_snmpoutgetrequests(void); void snmp_inc_snmpoutgetnexts(void); void snmp_inc_snmpoutsetrequests(void); void snmp_inc_snmpoutgetresponses(void); void snmp_inc_snmpouttraps(void); void snmp_get_snmpgrpid_ptr(struct snmp_obj_id **oid); void snmp_set_snmpenableauthentraps(u8_t *value); void snmp_get_snmpenableauthentraps(u8_t *value); /* LWIP_SNMP support not available */ /* define everything to be empty */ #else /* system */ #define snmp_set_sysdesr(str, len) #define snmp_set_sysobjid(oid); #define snmp_get_sysobjid_ptr(oid) #define snmp_inc_sysuptime() #define snmp_add_sysuptime(value) #define snmp_get_sysuptime(value) #define snmp_set_syscontact(ocstr, ocstrlen); #define snmp_set_sysname(ocstr, ocstrlen); #define snmp_set_syslocation(ocstr, ocstrlen); /* network interface */ #define snmp_add_ifinoctets(ni,value) #define snmp_inc_ifinucastpkts(ni) #define snmp_inc_ifinnucastpkts(ni) #define snmp_inc_ifindiscards(ni) #define snmp_add_ifoutoctets(ni,value) #define snmp_inc_ifoutucastpkts(ni) #define snmp_inc_ifoutnucastpkts(ni) #define snmp_inc_ifoutdiscards(ni) #define snmp_inc_iflist() #define snmp_dec_iflist() /* ARP */ #define snmp_insert_arpidx_tree(ni,ip) #define snmp_delete_arpidx_tree(ni,ip) /* IP */ #define snmp_inc_ipinreceives() #define snmp_inc_ipinhdrerrors() #define snmp_inc_ipinaddrerrors() #define snmp_inc_ipforwdatagrams() #define snmp_inc_ipinunknownprotos() #define snmp_inc_ipindiscards() #define snmp_inc_ipindelivers() #define snmp_inc_ipoutrequests() #define snmp_inc_ipoutdiscards() #define snmp_inc_ipoutnoroutes() #define snmp_inc_ipreasmreqds() #define snmp_inc_ipreasmoks() #define snmp_inc_ipreasmfails() #define snmp_inc_ipfragoks() #define snmp_inc_ipfragfails() #define snmp_inc_ipfragcreates() #define snmp_inc_iproutingdiscards() #define snmp_insert_ipaddridx_tree(ni) #define snmp_delete_ipaddridx_tree(ni) #define snmp_insert_iprteidx_tree(dflt, ni) #define snmp_delete_iprteidx_tree(dflt, ni) /* ICMP */ #define snmp_inc_icmpinmsgs() #define snmp_inc_icmpinerrors() #define snmp_inc_icmpindestunreachs() #define snmp_inc_icmpintimeexcds() #define snmp_inc_icmpinparmprobs() #define snmp_inc_icmpinsrcquenchs() #define snmp_inc_icmpinredirects() #define snmp_inc_icmpinechos() #define snmp_inc_icmpinechoreps() #define snmp_inc_icmpintimestamps() #define snmp_inc_icmpintimestampreps() #define snmp_inc_icmpinaddrmasks() #define snmp_inc_icmpinaddrmaskreps() #define snmp_inc_icmpoutmsgs() #define snmp_inc_icmpouterrors() #define snmp_inc_icmpoutdestunreachs() #define snmp_inc_icmpouttimeexcds() #define snmp_inc_icmpoutparmprobs() #define snmp_inc_icmpoutsrcquenchs() #define snmp_inc_icmpoutredirects() #define snmp_inc_icmpoutechos() #define snmp_inc_icmpoutechoreps() #define snmp_inc_icmpouttimestamps() #define snmp_inc_icmpouttimestampreps() #define snmp_inc_icmpoutaddrmasks() #define snmp_inc_icmpoutaddrmaskreps() /* TCP */ #define snmp_inc_tcpactiveopens() #define snmp_inc_tcppassiveopens() #define snmp_inc_tcpattemptfails() #define snmp_inc_tcpestabresets() #define snmp_inc_tcpinsegs() #define snmp_inc_tcpoutsegs() #define snmp_inc_tcpretranssegs() #define snmp_inc_tcpinerrs() #define snmp_inc_tcpoutrsts() /* UDP */ #define snmp_inc_udpindatagrams() #define snmp_inc_udpnoports() #define snmp_inc_udpinerrors() #define snmp_inc_udpoutdatagrams() #define snmp_insert_udpidx_tree(pcb) #define snmp_delete_udpidx_tree(pcb) /* SNMP */ #define snmp_inc_snmpinpkts() #define snmp_inc_snmpoutpkts() #define snmp_inc_snmpinbadversions() #define snmp_inc_snmpinbadcommunitynames() #define snmp_inc_snmpinbadcommunityuses() #define snmp_inc_snmpinasnparseerrs() #define snmp_inc_snmpintoobigs() #define snmp_inc_snmpinnosuchnames() #define snmp_inc_snmpinbadvalues() #define snmp_inc_snmpinreadonlys() #define snmp_inc_snmpingenerrs() #define snmp_add_snmpintotalreqvars(value) #define snmp_add_snmpintotalsetvars(value) #define snmp_inc_snmpingetrequests() #define snmp_inc_snmpingetnexts() #define snmp_inc_snmpinsetrequests() #define snmp_inc_snmpingetresponses() #define snmp_inc_snmpintraps() #define snmp_inc_snmpouttoobigs() #define snmp_inc_snmpoutnosuchnames() #define snmp_inc_snmpoutbadvalues() #define snmp_inc_snmpoutgenerrs() #define snmp_inc_snmpoutgetrequests() #define snmp_inc_snmpoutgetnexts() #define snmp_inc_snmpoutsetrequests() #define snmp_inc_snmpoutgetresponses() #define snmp_inc_snmpouttraps() #define snmp_get_snmpgrpid_ptr(oid) #define snmp_set_snmpenableauthentraps(value) #define snmp_get_snmpenableauthentraps(value) #endif /* LWIP_SNMP */ #ifdef __cplusplus } #endif #endif /* __LWIP_SNMP_H__ */ ================================================ FILE: Zelig/lwip/lwip/include/lwip/snmp_asn1.h ================================================ /** * @file * Abstract Syntax Notation One (ISO 8824, 8825) codec. */ /* * Copyright (c) 2006 Axon Digital Design B.V., The Netherlands. * All rights reserved. * * Redistribution and use in source and binary forms, with or without modification, * are permitted provided that the following conditions are met: * * 1. Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * 3. The name of the author may not be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT * SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT * OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING * IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY * OF SUCH DAMAGE. * * Author: Christiaan Simons */ #ifndef __LWIP_SNMP_ASN1_H__ #define __LWIP_SNMP_ASN1_H__ #include "lwip/opt.h" #include "lwip/err.h" #include "lwip/pbuf.h" #include "lwip/snmp.h" #if LWIP_SNMP #ifdef __cplusplus extern "C" { #endif #define SNMP_ASN1_UNIV (0) /* (!0x80 | !0x40) */ #define SNMP_ASN1_APPLIC (0x40) /* (!0x80 | 0x40) */ #define SNMP_ASN1_CONTXT (0x80) /* ( 0x80 | !0x40) */ #define SNMP_ASN1_CONSTR (0x20) /* ( 0x20) */ #define SNMP_ASN1_PRIMIT (0) /* (!0x20) */ /* universal tags */ #define SNMP_ASN1_INTEG 2 #define SNMP_ASN1_OC_STR 4 #define SNMP_ASN1_NUL 5 #define SNMP_ASN1_OBJ_ID 6 #define SNMP_ASN1_SEQ 16 /* application specific (SNMP) tags */ #define SNMP_ASN1_IPADDR 0 /* octet string size(4) */ #define SNMP_ASN1_COUNTER 1 /* u32_t */ #define SNMP_ASN1_GAUGE 2 /* u32_t */ #define SNMP_ASN1_TIMETICKS 3 /* u32_t */ #define SNMP_ASN1_OPAQUE 4 /* octet string */ /* context specific (SNMP) tags */ #define SNMP_ASN1_PDU_GET_REQ 0 #define SNMP_ASN1_PDU_GET_NEXT_REQ 1 #define SNMP_ASN1_PDU_GET_RESP 2 #define SNMP_ASN1_PDU_SET_REQ 3 #define SNMP_ASN1_PDU_TRAP 4 err_t snmp_asn1_dec_type(struct pbuf *p, u16_t ofs, u8_t *type); err_t snmp_asn1_dec_length(struct pbuf *p, u16_t ofs, u8_t *octets_used, u16_t *length); err_t snmp_asn1_dec_u32t(struct pbuf *p, u16_t ofs, u16_t len, u32_t *value); err_t snmp_asn1_dec_s32t(struct pbuf *p, u16_t ofs, u16_t len, s32_t *value); err_t snmp_asn1_dec_oid(struct pbuf *p, u16_t ofs, u16_t len, struct snmp_obj_id *oid); err_t snmp_asn1_dec_raw(struct pbuf *p, u16_t ofs, u16_t len, u16_t raw_len, u8_t *raw); void snmp_asn1_enc_length_cnt(u16_t length, u8_t *octets_needed); void snmp_asn1_enc_u32t_cnt(u32_t value, u16_t *octets_needed); void snmp_asn1_enc_s32t_cnt(s32_t value, u16_t *octets_needed); void snmp_asn1_enc_oid_cnt(u8_t ident_len, s32_t *ident, u16_t *octets_needed); err_t snmp_asn1_enc_type(struct pbuf *p, u16_t ofs, u8_t type); err_t snmp_asn1_enc_length(struct pbuf *p, u16_t ofs, u16_t length); err_t snmp_asn1_enc_u32t(struct pbuf *p, u16_t ofs, u16_t octets_needed, u32_t value); err_t snmp_asn1_enc_s32t(struct pbuf *p, u16_t ofs, u16_t octets_needed, s32_t value); err_t snmp_asn1_enc_oid(struct pbuf *p, u16_t ofs, u8_t ident_len, s32_t *ident); err_t snmp_asn1_enc_raw(struct pbuf *p, u16_t ofs, u16_t raw_len, u8_t *raw); #ifdef __cplusplus } #endif #endif /* LWIP_SNMP */ #endif /* __LWIP_SNMP_ASN1_H__ */ ================================================ FILE: Zelig/lwip/lwip/include/lwip/snmp_msg.h ================================================ /** * @file * SNMP Agent message handling structures. */ /* * Copyright (c) 2006 Axon Digital Design B.V., The Netherlands. * All rights reserved. * * Redistribution and use in source and binary forms, with or without modification, * are permitted provided that the following conditions are met: * * 1. Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * 3. The name of the author may not be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT * SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT * OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING * IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY * OF SUCH DAMAGE. * * Author: Christiaan Simons */ #ifndef __LWIP_SNMP_MSG_H__ #define __LWIP_SNMP_MSG_H__ #include "lwip/opt.h" #include "lwip/snmp.h" #include "lwip/snmp_structs.h" #include "lwip/ip_addr.h" #include "lwip/err.h" #if LWIP_SNMP #if SNMP_PRIVATE_MIB /* When using a private MIB, you have to create a file 'private_mib.h' that contains * a 'struct mib_array_node mib_private' which contains your MIB. */ #include "private_mib.h" #endif #ifdef __cplusplus extern "C" { #endif /* The listen port of the SNMP agent. Clients have to make their requests to this port. Most standard clients won't work if you change this! */ #ifndef SNMP_IN_PORT #define SNMP_IN_PORT 161 #endif /* The remote port the SNMP agent sends traps to. Most standard trap sinks won't work if you change this! */ #ifndef SNMP_TRAP_PORT #define SNMP_TRAP_PORT 162 #endif #define SNMP_ES_NOERROR 0 #define SNMP_ES_TOOBIG 1 #define SNMP_ES_NOSUCHNAME 2 #define SNMP_ES_BADVALUE 3 #define SNMP_ES_READONLY 4 #define SNMP_ES_GENERROR 5 #define SNMP_GENTRAP_COLDSTART 0 #define SNMP_GENTRAP_WARMSTART 1 #define SNMP_GENTRAP_AUTHFAIL 4 #define SNMP_GENTRAP_ENTERPRISESPC 6 struct snmp_varbind { /* next pointer, NULL for last in list */ struct snmp_varbind *next; /* previous pointer, NULL for first in list */ struct snmp_varbind *prev; /* object identifier length (in s32_t) */ u8_t ident_len; /* object identifier array */ s32_t *ident; /* object value ASN1 type */ u8_t value_type; /* object value length (in u8_t) */ u8_t value_len; /* object value */ void *value; /* encoding varbind seq length length */ u8_t seqlenlen; /* encoding object identifier length length */ u8_t olenlen; /* encoding object value length length */ u8_t vlenlen; /* encoding varbind seq length */ u16_t seqlen; /* encoding object identifier length */ u16_t olen; /* encoding object value length */ u16_t vlen; }; struct snmp_varbind_root { struct snmp_varbind *head; struct snmp_varbind *tail; /* number of variable bindings in list */ u8_t count; /* encoding varbind-list seq length length */ u8_t seqlenlen; /* encoding varbind-list seq length */ u16_t seqlen; }; /** output response message header length fields */ struct snmp_resp_header_lengths { /* encoding error-index length length */ u8_t erridxlenlen; /* encoding error-status length length */ u8_t errstatlenlen; /* encoding request id length length */ u8_t ridlenlen; /* encoding pdu length length */ u8_t pdulenlen; /* encoding community length length */ u8_t comlenlen; /* encoding version length length */ u8_t verlenlen; /* encoding sequence length length */ u8_t seqlenlen; /* encoding error-index length */ u16_t erridxlen; /* encoding error-status length */ u16_t errstatlen; /* encoding request id length */ u16_t ridlen; /* encoding pdu length */ u16_t pdulen; /* encoding community length */ u16_t comlen; /* encoding version length */ u16_t verlen; /* encoding sequence length */ u16_t seqlen; }; /** output response message header length fields */ struct snmp_trap_header_lengths { /* encoding timestamp length length */ u8_t tslenlen; /* encoding specific-trap length length */ u8_t strplenlen; /* encoding generic-trap length length */ u8_t gtrplenlen; /* encoding agent-addr length length */ u8_t aaddrlenlen; /* encoding enterprise-id length length */ u8_t eidlenlen; /* encoding pdu length length */ u8_t pdulenlen; /* encoding community length length */ u8_t comlenlen; /* encoding version length length */ u8_t verlenlen; /* encoding sequence length length */ u8_t seqlenlen; /* encoding timestamp length */ u16_t tslen; /* encoding specific-trap length */ u16_t strplen; /* encoding generic-trap length */ u16_t gtrplen; /* encoding agent-addr length */ u16_t aaddrlen; /* encoding enterprise-id length */ u16_t eidlen; /* encoding pdu length */ u16_t pdulen; /* encoding community length */ u16_t comlen; /* encoding version length */ u16_t verlen; /* encoding sequence length */ u16_t seqlen; }; /* Accepting new SNMP messages. */ #define SNMP_MSG_EMPTY 0 /* Search for matching object for variable binding. */ #define SNMP_MSG_SEARCH_OBJ 1 /* Perform SNMP operation on in-memory object. Pass-through states, for symmetry only. */ #define SNMP_MSG_INTERNAL_GET_OBJDEF 2 #define SNMP_MSG_INTERNAL_GET_VALUE 3 #define SNMP_MSG_INTERNAL_SET_TEST 4 #define SNMP_MSG_INTERNAL_GET_OBJDEF_S 5 #define SNMP_MSG_INTERNAL_SET_VALUE 6 /* Perform SNMP operation on object located externally. In theory this could be used for building a proxy agent. Practical use is for an enterprise spc. app. gateway. */ #define SNMP_MSG_EXTERNAL_GET_OBJDEF 7 #define SNMP_MSG_EXTERNAL_GET_VALUE 8 #define SNMP_MSG_EXTERNAL_SET_TEST 9 #define SNMP_MSG_EXTERNAL_GET_OBJDEF_S 10 #define SNMP_MSG_EXTERNAL_SET_VALUE 11 #define SNMP_COMMUNITY_STR_LEN 64 struct snmp_msg_pstat { /* lwIP local port (161) binding */ struct udp_pcb *pcb; /* source IP address */ ip_addr_t sip; /* source UDP port */ u16_t sp; /* request type */ u8_t rt; /* request ID */ s32_t rid; /* error status */ s32_t error_status; /* error index */ s32_t error_index; /* community name (zero terminated) */ u8_t community[SNMP_COMMUNITY_STR_LEN + 1]; /* community string length (exclusive zero term) */ u8_t com_strlen; /* one out of MSG_EMPTY, MSG_DEMUX, MSG_INTERNAL, MSG_EXTERNAL_x */ u8_t state; /* saved arguments for MSG_EXTERNAL_x */ struct mib_external_node *ext_mib_node; struct snmp_name_ptr ext_name_ptr; struct obj_def ext_object_def; struct snmp_obj_id ext_oid; /* index into input variable binding list */ u8_t vb_idx; /* ptr into input variable binding list */ struct snmp_varbind *vb_ptr; /* list of variable bindings from input */ struct snmp_varbind_root invb; /* list of variable bindings to output */ struct snmp_varbind_root outvb; /* output response lengths used in ASN encoding */ struct snmp_resp_header_lengths rhl; }; struct snmp_msg_trap { /* lwIP local port (161) binding */ struct udp_pcb *pcb; /* destination IP address in network order */ ip_addr_t dip; /* source enterprise ID (sysObjectID) */ struct snmp_obj_id *enterprise; /* source IP address, raw network order format */ u8_t sip_raw[4]; /* generic trap code */ u32_t gen_trap; /* specific trap code */ u32_t spc_trap; /* timestamp */ u32_t ts; /* list of variable bindings to output */ struct snmp_varbind_root outvb; /* output trap lengths used in ASN encoding */ struct snmp_trap_header_lengths thl; }; /** Agent Version constant, 0 = v1 oddity */ extern const s32_t snmp_version; /** Agent default "public" community string */ extern const char snmp_publiccommunity[7]; extern struct snmp_msg_trap trap_msg; /** Agent setup, start listening to port 161. */ void snmp_init(void); void snmp_trap_dst_enable(u8_t dst_idx, u8_t enable); void snmp_trap_dst_ip_set(u8_t dst_idx, ip_addr_t *dst); /** Varbind-list functions. */ struct snmp_varbind* snmp_varbind_alloc(struct snmp_obj_id *oid, u8_t type, u8_t len); void snmp_varbind_free(struct snmp_varbind *vb); void snmp_varbind_list_free(struct snmp_varbind_root *root); void snmp_varbind_tail_add(struct snmp_varbind_root *root, struct snmp_varbind *vb); struct snmp_varbind* snmp_varbind_tail_remove(struct snmp_varbind_root *root); /** Handle an internal (recv) or external (private response) event. */ void snmp_msg_event(u8_t request_id); err_t snmp_send_response(struct snmp_msg_pstat *m_stat); err_t snmp_send_trap(s8_t generic_trap, struct snmp_obj_id *eoid, s32_t specific_trap); void snmp_coldstart_trap(void); void snmp_authfail_trap(void); #ifdef __cplusplus } #endif #endif /* LWIP_SNMP */ #endif /* __LWIP_SNMP_MSG_H__ */ ================================================ FILE: Zelig/lwip/lwip/include/lwip/snmp_structs.h ================================================ /** * @file * Generic MIB tree structures. * * @todo namespace prefixes */ /* * Copyright (c) 2006 Axon Digital Design B.V., The Netherlands. * All rights reserved. * * Redistribution and use in source and binary forms, with or without modification, * are permitted provided that the following conditions are met: * * 1. Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * 3. The name of the author may not be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT * SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT * OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING * IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY * OF SUCH DAMAGE. * * Author: Christiaan Simons */ #ifndef __LWIP_SNMP_STRUCTS_H__ #define __LWIP_SNMP_STRUCTS_H__ #include "lwip/opt.h" #if LWIP_SNMP /* don't build if not configured for use in lwipopts.h */ #include "lwip/snmp.h" #if SNMP_PRIVATE_MIB /* When using a private MIB, you have to create a file 'private_mib.h' that contains * a 'struct mib_array_node mib_private' which contains your MIB. */ #include "private_mib.h" #endif #ifdef __cplusplus extern "C" { #endif /* MIB object instance */ #define MIB_OBJECT_NONE 0 #define MIB_OBJECT_SCALAR 1 #define MIB_OBJECT_TAB 2 /* MIB access types */ #define MIB_ACCESS_READ 1 #define MIB_ACCESS_WRITE 2 /* MIB object access */ #define MIB_OBJECT_READ_ONLY MIB_ACCESS_READ #define MIB_OBJECT_READ_WRITE (MIB_ACCESS_READ | MIB_ACCESS_WRITE) #define MIB_OBJECT_WRITE_ONLY MIB_ACCESS_WRITE #define MIB_OBJECT_NOT_ACCESSIBLE 0 /** object definition returned by (get_object_def)() */ struct obj_def { /* MIB_OBJECT_NONE (0), MIB_OBJECT_SCALAR (1), MIB_OBJECT_TAB (2) */ u8_t instance; /* 0 read-only, 1 read-write, 2 write-only, 3 not-accessible */ u8_t access; /* ASN type for this object */ u8_t asn_type; /* value length (host length) */ u16_t v_len; /* length of instance part of supplied object identifier */ u8_t id_inst_len; /* instance part of supplied object identifier */ s32_t *id_inst_ptr; }; struct snmp_name_ptr { u8_t ident_len; s32_t *ident; }; /** MIB const scalar (.0) node */ #define MIB_NODE_SC 0x01 /** MIB const array node */ #define MIB_NODE_AR 0x02 /** MIB array node (mem_malloced from RAM) */ #define MIB_NODE_RA 0x03 /** MIB list root node (mem_malloced from RAM) */ #define MIB_NODE_LR 0x04 /** MIB node for external objects */ #define MIB_NODE_EX 0x05 /** node "base class" layout, the mandatory fields for a node */ struct mib_node { /** returns struct obj_def for the given object identifier */ void (*get_object_def)(u8_t ident_len, s32_t *ident, struct obj_def *od); /** returns object value for the given object identifier, @note the caller must allocate at least len bytes for the value */ void (*get_value)(struct obj_def *od, u16_t len, void *value); /** tests length and/or range BEFORE setting */ u8_t (*set_test)(struct obj_def *od, u16_t len, void *value); /** sets object value, only to be called when set_test() */ void (*set_value)(struct obj_def *od, u16_t len, void *value); /** One out of MIB_NODE_AR, MIB_NODE_LR or MIB_NODE_EX */ u8_t node_type; /* array or max list length */ u16_t maxlength; }; /** derived node for scalars .0 index */ typedef struct mib_node mib_scalar_node; /** derived node, points to a fixed size const array of sub-identifiers plus a 'child' pointer */ struct mib_array_node { /* inherited "base class" members */ void (*get_object_def)(u8_t ident_len, s32_t *ident, struct obj_def *od); void (*get_value)(struct obj_def *od, u16_t len, void *value); u8_t (*set_test)(struct obj_def *od, u16_t len, void *value); void (*set_value)(struct obj_def *od, u16_t len, void *value); u8_t node_type; u16_t maxlength; /* additional struct members */ const s32_t *objid; struct mib_node* const *nptr; }; /** derived node, points to a fixed size mem_malloced array of sub-identifiers plus a 'child' pointer */ struct mib_ram_array_node { /* inherited "base class" members */ void (*get_object_def)(u8_t ident_len, s32_t *ident, struct obj_def *od); void (*get_value)(struct obj_def *od, u16_t len, void *value); u8_t (*set_test)(struct obj_def *od, u16_t len, void *value); void (*set_value)(struct obj_def *od, u16_t len, void *value); u8_t node_type; u16_t maxlength; /* aditional struct members */ s32_t *objid; struct mib_node **nptr; }; struct mib_list_node { struct mib_list_node *prev; struct mib_list_node *next; s32_t objid; struct mib_node *nptr; }; /** derived node, points to a doubly linked list of sub-identifiers plus a 'child' pointer */ struct mib_list_rootnode { /* inherited "base class" members */ void (*get_object_def)(u8_t ident_len, s32_t *ident, struct obj_def *od); void (*get_value)(struct obj_def *od, u16_t len, void *value); u8_t (*set_test)(struct obj_def *od, u16_t len, void *value); void (*set_value)(struct obj_def *od, u16_t len, void *value); u8_t node_type; u16_t maxlength; /* additional struct members */ struct mib_list_node *head; struct mib_list_node *tail; /* counts list nodes in list */ u16_t count; }; /** derived node, has access functions for mib object in external memory or device using 'tree_level' and 'idx', with a range 0 .. (level_length() - 1) */ struct mib_external_node { /* inherited "base class" members */ void (*get_object_def)(u8_t ident_len, s32_t *ident, struct obj_def *od); void (*get_value)(struct obj_def *od, u16_t len, void *value); u8_t (*set_test)(struct obj_def *od, u16_t len, void *value); void (*set_value)(struct obj_def *od, u16_t len, void *value); u8_t node_type; u16_t maxlength; /* additional struct members */ /** points to an external (in memory) record of some sort of addressing information, passed to and interpreted by the funtions below */ void* addr_inf; /** tree levels under this node */ u8_t tree_levels; /** number of objects at this level */ u16_t (*level_length)(void* addr_inf, u8_t level); /** compares object sub identifier with external id return zero when equal, nonzero when unequal */ s32_t (*ident_cmp)(void* addr_inf, u8_t level, u16_t idx, s32_t sub_id); void (*get_objid)(void* addr_inf, u8_t level, u16_t idx, s32_t *sub_id); /** async Questions */ void (*get_object_def_q)(void* addr_inf, u8_t rid, u8_t ident_len, s32_t *ident); void (*get_value_q)(u8_t rid, struct obj_def *od); void (*set_test_q)(u8_t rid, struct obj_def *od); void (*set_value_q)(u8_t rid, struct obj_def *od, u16_t len, void *value); /** async Answers */ void (*get_object_def_a)(u8_t rid, u8_t ident_len, s32_t *ident, struct obj_def *od); void (*get_value_a)(u8_t rid, struct obj_def *od, u16_t len, void *value); u8_t (*set_test_a)(u8_t rid, struct obj_def *od, u16_t len, void *value); void (*set_value_a)(u8_t rid, struct obj_def *od, u16_t len, void *value); /** async Panic Close (agent returns error reply, e.g. used for external transaction cleanup) */ void (*get_object_def_pc)(u8_t rid, u8_t ident_len, s32_t *ident); void (*get_value_pc)(u8_t rid, struct obj_def *od); void (*set_test_pc)(u8_t rid, struct obj_def *od); void (*set_value_pc)(u8_t rid, struct obj_def *od); }; /** export MIB tree from mib2.c */ extern const struct mib_array_node internet; /** dummy function pointers for non-leaf MIB nodes from mib2.c */ void noleafs_get_object_def(u8_t ident_len, s32_t *ident, struct obj_def *od); void noleafs_get_value(struct obj_def *od, u16_t len, void *value); u8_t noleafs_set_test(struct obj_def *od, u16_t len, void *value); void noleafs_set_value(struct obj_def *od, u16_t len, void *value); void snmp_oidtoip(s32_t *ident, ip_addr_t *ip); void snmp_iptooid(ip_addr_t *ip, s32_t *ident); void snmp_ifindextonetif(s32_t ifindex, struct netif **netif); void snmp_netiftoifindex(struct netif *netif, s32_t *ifidx); struct mib_list_node* snmp_mib_ln_alloc(s32_t id); void snmp_mib_ln_free(struct mib_list_node *ln); struct mib_list_rootnode* snmp_mib_lrn_alloc(void); void snmp_mib_lrn_free(struct mib_list_rootnode *lrn); s8_t snmp_mib_node_insert(struct mib_list_rootnode *rn, s32_t objid, struct mib_list_node **insn); s8_t snmp_mib_node_find(struct mib_list_rootnode *rn, s32_t objid, struct mib_list_node **fn); struct mib_list_rootnode *snmp_mib_node_delete(struct mib_list_rootnode *rn, struct mib_list_node *n); struct mib_node* snmp_search_tree(struct mib_node *node, u8_t ident_len, s32_t *ident, struct snmp_name_ptr *np); struct mib_node* snmp_expand_tree(struct mib_node *node, u8_t ident_len, s32_t *ident, struct snmp_obj_id *oidret); u8_t snmp_iso_prefix_tst(u8_t ident_len, s32_t *ident); u8_t snmp_iso_prefix_expand(u8_t ident_len, s32_t *ident, struct snmp_obj_id *oidret); #ifdef __cplusplus } #endif #endif /* LWIP_SNMP */ #endif /* __LWIP_SNMP_STRUCTS_H__ */ ================================================ FILE: Zelig/lwip/lwip/include/lwip/sockets.h ================================================ /* * Copyright (c) 2001-2004 Swedish Institute of Computer Science. * All rights reserved. * * Redistribution and use in source and binary forms, with or without modification, * are permitted provided that the following conditions are met: * * 1. Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * 3. The name of the author may not be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT * SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT * OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING * IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY * OF SUCH DAMAGE. * * This file is part of the lwIP TCP/IP stack. * * Author: Adam Dunkels * */ #ifndef __LWIP_SOCKETS_H__ #define __LWIP_SOCKETS_H__ #include "lwip/opt.h" #if LWIP_SOCKET /* don't build if not configured for use in lwipopts.h */ #include /* for size_t */ #include "lwip/ip_addr.h" #include "lwip/inet.h" #ifdef __cplusplus extern "C" { #endif /* members are in network byte order */ struct sockaddr_in { u8_t sin_len; u8_t sin_family; u16_t sin_port; struct in_addr sin_addr; char sin_zero[8]; }; struct sockaddr { u8_t sa_len; u8_t sa_family; char sa_data[14]; }; #ifndef socklen_t # define socklen_t u32_t #endif /* Socket protocol types (TCP/UDP/RAW) */ #define SOCK_STREAM 1 #define SOCK_DGRAM 2 #define SOCK_RAW 3 /* * Option flags per-socket. These must match the SOF_ flags in ip.h (checked in init.c) */ #define SO_DEBUG 0x0001 /* Unimplemented: turn on debugging info recording */ #define SO_ACCEPTCONN 0x0002 /* socket has had listen() */ #define SO_REUSEADDR 0x0004 /* Allow local address reuse */ #define SO_KEEPALIVE 0x0008 /* keep connections alive */ #define SO_DONTROUTE 0x0010 /* Unimplemented: just use interface addresses */ #define SO_BROADCAST 0x0020 /* permit to send and to receive broadcast messages (see IP_SOF_BROADCAST option) */ #define SO_USELOOPBACK 0x0040 /* Unimplemented: bypass hardware when possible */ #define SO_LINGER 0x0080 /* linger on close if data present */ #define SO_OOBINLINE 0x0100 /* Unimplemented: leave received OOB data in line */ #define SO_REUSEPORT 0x0200 /* Unimplemented: allow local address & port reuse */ #define SO_DONTLINGER ((int)(~SO_LINGER)) /* * Additional options, not kept in so_options. */ #define SO_SNDBUF 0x1001 /* Unimplemented: send buffer size */ #define SO_RCVBUF 0x1002 /* receive buffer size */ #define SO_SNDLOWAT 0x1003 /* Unimplemented: send low-water mark */ #define SO_RCVLOWAT 0x1004 /* Unimplemented: receive low-water mark */ #define SO_SNDTIMEO 0x1005 /* Unimplemented: send timeout */ #define SO_RCVTIMEO 0x1006 /* receive timeout */ #define SO_ERROR 0x1007 /* get error status and clear */ #define SO_TYPE 0x1008 /* get socket type */ #define SO_CONTIMEO 0x1009 /* Unimplemented: connect timeout */ #define SO_NO_CHECK 0x100a /* don't create UDP checksum */ /* * Structure used for manipulating linger option. */ struct linger { int l_onoff; /* option on/off */ int l_linger; /* linger time */ }; /* * Level number for (get/set)sockopt() to apply to socket itself. */ #define SOL_SOCKET 0xfff /* options for socket level */ #define AF_UNSPEC 0 #define AF_INET 2 #define PF_INET AF_INET #define PF_UNSPEC AF_UNSPEC #define IPPROTO_IP 0 #define IPPROTO_TCP 6 #define IPPROTO_UDP 17 #define IPPROTO_UDPLITE 136 /* Flags we can use with send and recv. */ #define MSG_PEEK 0x01 /* Peeks at an incoming message */ #define MSG_WAITALL 0x02 /* Unimplemented: Requests that the function block until the full amount of data requested can be returned */ #define MSG_OOB 0x04 /* Unimplemented: Requests out-of-band data. The significance and semantics of out-of-band data are protocol-specific */ #define MSG_DONTWAIT 0x08 /* Nonblocking i/o for this operation only */ #define MSG_MORE 0x10 /* Sender will send more */ /* * Options for level IPPROTO_IP */ #define IP_TOS 1 #define IP_TTL 2 #if LWIP_TCP /* * Options for level IPPROTO_TCP */ #define TCP_NODELAY 0x01 /* don't delay send to coalesce packets */ #define TCP_KEEPALIVE 0x02 /* send KEEPALIVE probes when idle for pcb->keep_idle milliseconds */ #define TCP_KEEPIDLE 0x03 /* set pcb->keep_idle - Same as TCP_KEEPALIVE, but use seconds for get/setsockopt */ #define TCP_KEEPINTVL 0x04 /* set pcb->keep_intvl - Use seconds for get/setsockopt */ #define TCP_KEEPCNT 0x05 /* set pcb->keep_cnt - Use number of probes sent for get/setsockopt */ #endif /* LWIP_TCP */ #if LWIP_UDP && LWIP_UDPLITE /* * Options for level IPPROTO_UDPLITE */ #define UDPLITE_SEND_CSCOV 0x01 /* sender checksum coverage */ #define UDPLITE_RECV_CSCOV 0x02 /* minimal receiver checksum coverage */ #endif /* LWIP_UDP && LWIP_UDPLITE*/ #if LWIP_IGMP /* * Options and types for UDP multicast traffic handling */ #define IP_ADD_MEMBERSHIP 3 #define IP_DROP_MEMBERSHIP 4 #define IP_MULTICAST_TTL 5 #define IP_MULTICAST_IF 6 #define IP_MULTICAST_LOOP 7 typedef struct ip_mreq { struct in_addr imr_multiaddr; /* IP multicast address of group */ struct in_addr imr_interface; /* local IP address of interface */ } ip_mreq; #endif /* LWIP_IGMP */ /* * The Type of Service provides an indication of the abstract * parameters of the quality of service desired. These parameters are * to be used to guide the selection of the actual service parameters * when transmitting a datagram through a particular network. Several * networks offer service precedence, which somehow treats high * precedence traffic as more important than other traffic (generally * by accepting only traffic above a certain precedence at time of high * load). The major choice is a three way tradeoff between low-delay, * high-reliability, and high-throughput. * The use of the Delay, Throughput, and Reliability indications may * increase the cost (in some sense) of the service. In many networks * better performance for one of these parameters is coupled with worse * performance on another. Except for very unusual cases at most two * of these three indications should be set. */ #define IPTOS_TOS_MASK 0x1E #define IPTOS_TOS(tos) ((tos) & IPTOS_TOS_MASK) #define IPTOS_LOWDELAY 0x10 #define IPTOS_THROUGHPUT 0x08 #define IPTOS_RELIABILITY 0x04 #define IPTOS_LOWCOST 0x02 #define IPTOS_MINCOST IPTOS_LOWCOST /* * The Network Control precedence designation is intended to be used * within a network only. The actual use and control of that * designation is up to each network. The Internetwork Control * designation is intended for use by gateway control originators only. * If the actual use of these precedence designations is of concern to * a particular network, it is the responsibility of that network to * control the access to, and use of, those precedence designations. */ #define IPTOS_PREC_MASK 0xe0 #define IPTOS_PREC(tos) ((tos) & IPTOS_PREC_MASK) #define IPTOS_PREC_NETCONTROL 0xe0 #define IPTOS_PREC_INTERNETCONTROL 0xc0 #define IPTOS_PREC_CRITIC_ECP 0xa0 #define IPTOS_PREC_FLASHOVERRIDE 0x80 #define IPTOS_PREC_FLASH 0x60 #define IPTOS_PREC_IMMEDIATE 0x40 #define IPTOS_PREC_PRIORITY 0x20 #define IPTOS_PREC_ROUTINE 0x00 /* * Commands for ioctlsocket(), taken from the BSD file fcntl.h. * lwip_ioctl only supports FIONREAD and FIONBIO, for now * * Ioctl's have the command encoded in the lower word, * and the size of any in or out parameters in the upper * word. The high 2 bits of the upper word are used * to encode the in/out status of the parameter; for now * we restrict parameters to at most 128 bytes. */ #if !defined(FIONREAD) || !defined(FIONBIO) #define IOCPARM_MASK 0x7fU /* parameters must be < 128 bytes */ #define IOC_VOID 0x20000000UL /* no parameters */ #define IOC_OUT 0x40000000UL /* copy out parameters */ #define IOC_IN 0x80000000UL /* copy in parameters */ #define IOC_INOUT (IOC_IN|IOC_OUT) /* 0x20000000 distinguishes new & old ioctl's */ #define _IO(x,y) (IOC_VOID|((x)<<8)|(y)) #define _IOR(x,y,t) (IOC_OUT|(((long)sizeof(t)&IOCPARM_MASK)<<16)|((x)<<8)|(y)) #define _IOW(x,y,t) (IOC_IN|(((long)sizeof(t)&IOCPARM_MASK)<<16)|((x)<<8)|(y)) #endif /* !defined(FIONREAD) || !defined(FIONBIO) */ #ifndef FIONREAD #define FIONREAD _IOR('f', 127, unsigned long) /* get # bytes to read */ #endif #ifndef FIONBIO #define FIONBIO _IOW('f', 126, unsigned long) /* set/clear non-blocking i/o */ #endif /* Socket I/O Controls: unimplemented */ #ifndef SIOCSHIWAT #define SIOCSHIWAT _IOW('s', 0, unsigned long) /* set high watermark */ #define SIOCGHIWAT _IOR('s', 1, unsigned long) /* get high watermark */ #define SIOCSLOWAT _IOW('s', 2, unsigned long) /* set low watermark */ #define SIOCGLOWAT _IOR('s', 3, unsigned long) /* get low watermark */ #define SIOCATMARK _IOR('s', 7, unsigned long) /* at oob mark? */ #endif /* commands for fnctl */ #ifndef F_GETFL #define F_GETFL 3 #endif #ifndef F_SETFL #define F_SETFL 4 #endif /* File status flags and file access modes for fnctl, these are bits in an int. */ #ifndef O_NONBLOCK #define O_NONBLOCK 1 /* nonblocking I/O */ #endif #ifndef O_NDELAY #define O_NDELAY 1 /* same as O_NONBLOCK, for compatibility */ #endif #ifndef SHUT_RD #define SHUT_RD 0 #define SHUT_WR 1 #define SHUT_RDWR 2 #endif /* FD_SET used for lwip_select */ #ifndef FD_SET #undef FD_SETSIZE /* Make FD_SETSIZE match NUM_SOCKETS in socket.c */ #define FD_SETSIZE MEMP_NUM_NETCONN #define FD_SET(n, p) ((p)->fd_bits[(n)/8] |= (1 << ((n) & 7))) #define FD_CLR(n, p) ((p)->fd_bits[(n)/8] &= ~(1 << ((n) & 7))) #define FD_ISSET(n,p) ((p)->fd_bits[(n)/8] & (1 << ((n) & 7))) #define FD_ZERO(p) memset((void*)(p),0,sizeof(*(p))) typedef struct fd_set { unsigned char fd_bits [(FD_SETSIZE+7)/8]; } fd_set; #endif /* FD_SET */ /** LWIP_TIMEVAL_PRIVATE: if you want to use the struct timeval provided * by your system, set this to 0 and include in cc.h */ #ifndef LWIP_TIMEVAL_PRIVATE #define LWIP_TIMEVAL_PRIVATE 0 #endif #if LWIP_TIMEVAL_PRIVATE struct timeval { long tv_sec; /* seconds */ long tv_usec; /* and microseconds */ }; #endif /* LWIP_TIMEVAL_PRIVATE */ void lwip_socket_init(void); int lwip_accept(int s, struct sockaddr *addr, socklen_t *addrlen); int lwip_bind(int s, const struct sockaddr *name, socklen_t namelen); int lwip_shutdown(int s, int how); int lwip_getpeername (int s, struct sockaddr *name, socklen_t *namelen); int lwip_getsockname (int s, struct sockaddr *name, socklen_t *namelen); int lwip_getsockopt (int s, int level, int optname, void *optval, socklen_t *optlen); int lwip_setsockopt (int s, int level, int optname, const void *optval, socklen_t optlen); int lwip_close(int s); int lwip_connect(int s, const struct sockaddr *name, socklen_t namelen); int lwip_listen(int s, int backlog); int lwip_recv(int s, void *mem, size_t len, int flags); int lwip_read(int s, void *mem, size_t len); int lwip_recvfrom(int s, void *mem, size_t len, int flags, struct sockaddr *from, socklen_t *fromlen); int lwip_send(int s, const void *dataptr, size_t size, int flags); int lwip_sendto(int s, const void *dataptr, size_t size, int flags, const struct sockaddr *to, socklen_t tolen); int lwip_socket(int domain, int type, int protocol); int lwip_write(int s, const void *dataptr, size_t size); int lwip_select(int maxfdp1, fd_set *readset, fd_set *writeset, fd_set *exceptset, struct timeval *timeout); int lwip_ioctl(int s, long cmd, void *argp); int lwip_fcntl(int s, int cmd, int val); #if LWIP_COMPAT_SOCKETS #define accept(a,b,c) lwip_accept(a,b,c) #define bind(a,b,c) lwip_bind(a,b,c) #define shutdown(a,b) lwip_shutdown(a,b) #define closesocket(s) lwip_close(s) #define connect(a,b,c) lwip_connect(a,b,c) #define getsockname(a,b,c) lwip_getsockname(a,b,c) #define getpeername(a,b,c) lwip_getpeername(a,b,c) #define setsockopt(a,b,c,d,e) lwip_setsockopt(a,b,c,d,e) #define getsockopt(a,b,c,d,e) lwip_getsockopt(a,b,c,d,e) #define listen(a,b) lwip_listen(a,b) #define recv(a,b,c,d) lwip_recv(a,b,c,d) #define recvfrom(a,b,c,d,e,f) lwip_recvfrom(a,b,c,d,e,f) #define send(a,b,c,d) lwip_send(a,b,c,d) #define sendto(a,b,c,d,e,f) lwip_sendto(a,b,c,d,e,f) #define socket(a,b,c) lwip_socket(a,b,c) #define select(a,b,c,d,e) lwip_select(a,b,c,d,e) #define ioctlsocket(a,b,c) lwip_ioctl(a,b,c) #if LWIP_POSIX_SOCKETS_IO_NAMES #define read(a,b,c) lwip_read(a,b,c) #define write(a,b,c) lwip_write(a,b,c) #define close(s) lwip_close(s) #endif /* LWIP_POSIX_SOCKETS_IO_NAMES */ #endif /* LWIP_COMPAT_SOCKETS */ #ifdef __cplusplus } #endif #endif /* LWIP_SOCKET */ #endif /* __LWIP_SOCKETS_H__ */ ================================================ FILE: Zelig/lwip/lwip/include/lwip/stats.h ================================================ /* * Copyright (c) 2001-2004 Swedish Institute of Computer Science. * All rights reserved. * * Redistribution and use in source and binary forms, with or without modification, * are permitted provided that the following conditions are met: * * 1. Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * 3. The name of the author may not be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT * SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT * OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING * IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY * OF SUCH DAMAGE. * * This file is part of the lwIP TCP/IP stack. * * Author: Adam Dunkels * */ #ifndef __LWIP_STATS_H__ #define __LWIP_STATS_H__ #include "lwip/opt.h" #include "lwip/mem.h" #include "lwip/memp.h" #ifdef __cplusplus extern "C" { #endif #if LWIP_STATS #ifndef LWIP_STATS_LARGE #define LWIP_STATS_LARGE 0 #endif #if LWIP_STATS_LARGE #define STAT_COUNTER u32_t #define STAT_COUNTER_F U32_F #else #define STAT_COUNTER u16_t #define STAT_COUNTER_F U16_F #endif struct stats_proto { STAT_COUNTER xmit; /* Transmitted packets. */ STAT_COUNTER recv; /* Received packets. */ STAT_COUNTER fw; /* Forwarded packets. */ STAT_COUNTER drop; /* Dropped packets. */ STAT_COUNTER chkerr; /* Checksum error. */ STAT_COUNTER lenerr; /* Invalid length error. */ STAT_COUNTER memerr; /* Out of memory error. */ STAT_COUNTER rterr; /* Routing error. */ STAT_COUNTER proterr; /* Protocol error. */ STAT_COUNTER opterr; /* Error in options. */ STAT_COUNTER err; /* Misc error. */ STAT_COUNTER cachehit; }; struct stats_igmp { STAT_COUNTER xmit; /* Transmitted packets. */ STAT_COUNTER recv; /* Received packets. */ STAT_COUNTER drop; /* Dropped packets. */ STAT_COUNTER chkerr; /* Checksum error. */ STAT_COUNTER lenerr; /* Invalid length error. */ STAT_COUNTER memerr; /* Out of memory error. */ STAT_COUNTER proterr; /* Protocol error. */ STAT_COUNTER rx_v1; /* Received v1 frames. */ STAT_COUNTER rx_group; /* Received group-specific queries. */ STAT_COUNTER rx_general; /* Received general queries. */ STAT_COUNTER rx_report; /* Received reports. */ STAT_COUNTER tx_join; /* Sent joins. */ STAT_COUNTER tx_leave; /* Sent leaves. */ STAT_COUNTER tx_report; /* Sent reports. */ }; struct stats_mem { #ifdef LWIP_DEBUG const char *name; #endif /* LWIP_DEBUG */ mem_size_t avail; mem_size_t used; mem_size_t max; STAT_COUNTER err; STAT_COUNTER illegal; }; struct stats_syselem { STAT_COUNTER used; STAT_COUNTER max; STAT_COUNTER err; }; struct stats_sys { struct stats_syselem sem; struct stats_syselem mutex; struct stats_syselem mbox; }; struct stats_ { #if LINK_STATS struct stats_proto link; #endif #if ETHARP_STATS struct stats_proto etharp; #endif #if IPFRAG_STATS struct stats_proto ip_frag; #endif #if IP_STATS struct stats_proto ip; #endif #if ICMP_STATS struct stats_proto icmp; #endif #if IGMP_STATS struct stats_igmp igmp; #endif #if UDP_STATS struct stats_proto udp; #endif #if TCP_STATS struct stats_proto tcp; #endif #if MEM_STATS struct stats_mem mem; #endif #if MEMP_STATS struct stats_mem memp[MEMP_MAX]; #endif #if SYS_STATS struct stats_sys sys; #endif }; extern struct stats_ lwip_stats; void stats_init(void); #define STATS_INC(x) ++lwip_stats.x #define STATS_DEC(x) --lwip_stats.x #define STATS_INC_USED(x, y) do { lwip_stats.x.used += y; \ if (lwip_stats.x.max < lwip_stats.x.used) { \ lwip_stats.x.max = lwip_stats.x.used; \ } \ } while(0) #else /* LWIP_STATS */ #define stats_init() #define STATS_INC(x) #define STATS_DEC(x) #define STATS_INC_USED(x) #endif /* LWIP_STATS */ #if TCP_STATS #define TCP_STATS_INC(x) STATS_INC(x) #define TCP_STATS_DISPLAY() stats_display_proto(&lwip_stats.tcp, "TCP") #else #define TCP_STATS_INC(x) #define TCP_STATS_DISPLAY() #endif #if UDP_STATS #define UDP_STATS_INC(x) STATS_INC(x) #define UDP_STATS_DISPLAY() stats_display_proto(&lwip_stats.udp, "UDP") #else #define UDP_STATS_INC(x) #define UDP_STATS_DISPLAY() #endif #if ICMP_STATS #define ICMP_STATS_INC(x) STATS_INC(x) #define ICMP_STATS_DISPLAY() stats_display_proto(&lwip_stats.icmp, "ICMP") #else #define ICMP_STATS_INC(x) #define ICMP_STATS_DISPLAY() #endif #if IGMP_STATS #define IGMP_STATS_INC(x) STATS_INC(x) #define IGMP_STATS_DISPLAY() stats_display_igmp(&lwip_stats.igmp) #else #define IGMP_STATS_INC(x) #define IGMP_STATS_DISPLAY() #endif #if IP_STATS #define IP_STATS_INC(x) STATS_INC(x) #define IP_STATS_DISPLAY() stats_display_proto(&lwip_stats.ip, "IP") #else #define IP_STATS_INC(x) #define IP_STATS_DISPLAY() #endif #if IPFRAG_STATS #define IPFRAG_STATS_INC(x) STATS_INC(x) #define IPFRAG_STATS_DISPLAY() stats_display_proto(&lwip_stats.ip_frag, "IP_FRAG") #else #define IPFRAG_STATS_INC(x) #define IPFRAG_STATS_DISPLAY() #endif #if ETHARP_STATS #define ETHARP_STATS_INC(x) STATS_INC(x) #define ETHARP_STATS_DISPLAY() stats_display_proto(&lwip_stats.etharp, "ETHARP") #else #define ETHARP_STATS_INC(x) #define ETHARP_STATS_DISPLAY() #endif #if LINK_STATS #define LINK_STATS_INC(x) STATS_INC(x) #define LINK_STATS_DISPLAY() stats_display_proto(&lwip_stats.link, "LINK") #else #define LINK_STATS_INC(x) #define LINK_STATS_DISPLAY() #endif #if MEM_STATS #define MEM_STATS_AVAIL(x, y) lwip_stats.mem.x = y #define MEM_STATS_INC(x) STATS_INC(mem.x) #define MEM_STATS_INC_USED(x, y) STATS_INC_USED(mem, y) #define MEM_STATS_DEC_USED(x, y) lwip_stats.mem.x -= y #define MEM_STATS_DISPLAY() stats_display_mem(&lwip_stats.mem, "HEAP") #else #define MEM_STATS_AVAIL(x, y) #define MEM_STATS_INC(x) #define MEM_STATS_INC_USED(x, y) #define MEM_STATS_DEC_USED(x, y) #define MEM_STATS_DISPLAY() #endif #if MEMP_STATS #define MEMP_STATS_AVAIL(x, i, y) lwip_stats.memp[i].x = y #define MEMP_STATS_INC(x, i) STATS_INC(memp[i].x) #define MEMP_STATS_DEC(x, i) STATS_DEC(memp[i].x) #define MEMP_STATS_INC_USED(x, i) STATS_INC_USED(memp[i], 1) #define MEMP_STATS_DISPLAY(i) stats_display_memp(&lwip_stats.memp[i], i) #else #define MEMP_STATS_AVAIL(x, i, y) #define MEMP_STATS_INC(x, i) #define MEMP_STATS_DEC(x, i) #define MEMP_STATS_INC_USED(x, i) #define MEMP_STATS_DISPLAY(i) #endif #if SYS_STATS #define SYS_STATS_INC(x) STATS_INC(sys.x) #define SYS_STATS_DEC(x) STATS_DEC(sys.x) #define SYS_STATS_INC_USED(x) STATS_INC_USED(sys.x, 1) #define SYS_STATS_DISPLAY() stats_display_sys(&lwip_stats.sys) #else #define SYS_STATS_INC(x) #define SYS_STATS_DEC(x) #define SYS_STATS_INC_USED(x) #define SYS_STATS_DISPLAY() #endif /* Display of statistics */ #if LWIP_STATS_DISPLAY void stats_display(void); void stats_display_proto(struct stats_proto *proto, char *name); void stats_display_igmp(struct stats_igmp *igmp); void stats_display_mem(struct stats_mem *mem, char *name); void stats_display_memp(struct stats_mem *mem, int index); void stats_display_sys(struct stats_sys *sys); #else /* LWIP_STATS_DISPLAY */ #define stats_display() #define stats_display_proto(proto, name) #define stats_display_igmp(igmp) #define stats_display_mem(mem, name) #define stats_display_memp(mem, index) #define stats_display_sys(sys) #endif /* LWIP_STATS_DISPLAY */ #ifdef __cplusplus } #endif #endif /* __LWIP_STATS_H__ */ ================================================ FILE: Zelig/lwip/lwip/include/lwip/sys.h ================================================ /* * Copyright (c) 2001-2004 Swedish Institute of Computer Science. * All rights reserved. * * Redistribution and use in source and binary forms, with or without modification, * are permitted provided that the following conditions are met: * * 1. Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * 3. The name of the author may not be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT * SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT * OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING * IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY * OF SUCH DAMAGE. * * This file is part of the lwIP TCP/IP stack. * * Author: Adam Dunkels * */ #ifndef __LWIP_SYS_H__ #define __LWIP_SYS_H__ #include "lwip/opt.h" #ifdef __cplusplus extern "C" { #endif #if NO_SYS /* For a totally minimal and standalone system, we provide null definitions of the sys_ functions. */ typedef u8_t sys_sem_t; typedef u8_t sys_mutex_t; typedef u8_t sys_mbox_t; #define sys_sem_new(s, c) ERR_OK #define sys_sem_signal(s) #define sys_sem_wait(s) #define sys_arch_sem_wait(s,t) #define sys_sem_free(s) #define sys_mutex_new(mu) ERR_OK #define sys_mutex_lock(mu) #define sys_mutex_unlock(mu) #define sys_mutex_free(mu) #define sys_mbox_new(m, s) ERR_OK #define sys_mbox_fetch(m,d) #define sys_mbox_tryfetch(m,d) #define sys_mbox_post(m,d) #define sys_mbox_trypost(m,d) #define sys_mbox_free(m) #define sys_thread_new(n,t,a,s,p) #define sys_msleep(t) #else /* NO_SYS */ /** Return code for timeouts from sys_arch_mbox_fetch and sys_arch_sem_wait */ #define SYS_ARCH_TIMEOUT 0xffffffffUL /** sys_mbox_tryfetch() returns SYS_MBOX_EMPTY if appropriate. * For now we use the same magic value, but we allow this to change in future. */ #define SYS_MBOX_EMPTY SYS_ARCH_TIMEOUT #include "lwip/err.h" #include "arch/sys_arch.h" /** Function prototype for thread functions */ typedef void (*lwip_thread_fn)(void *arg); /* Function prototypes for functions to be implemented by platform ports (in sys_arch.c) */ /* Mutex functions: */ /** Define LWIP_COMPAT_MUTEX if the port has no mutexes and binary semaphores should be used instead */ #if LWIP_COMPAT_MUTEX /* for old ports that don't have mutexes: define them to binary semaphores */ #define sys_mutex_t sys_sem_t #define sys_mutex_new(mutex) sys_sem_new(mutex, 1) #define sys_mutex_lock(mutex) sys_sem_wait(mutex) #define sys_mutex_unlock(mutex) sys_sem_signal(mutex) #define sys_mutex_free(mutex) sys_sem_free(mutex) #define sys_mutex_valid(mutex) sys_sem_valid(mutex) #define sys_mutex_set_invalid(mutex) sys_sem_set_invalid(mutex) #else /* LWIP_COMPAT_MUTEX */ /** Create a new mutex * @param mutex pointer to the mutex to create * @return a new mutex */ err_t sys_mutex_new(sys_mutex_t *mutex); /** Lock a mutex * @param mutex the mutex to lock */ void sys_mutex_lock(sys_mutex_t *mutex); /** Unlock a mutex * @param mutex the mutex to unlock */ void sys_mutex_unlock(sys_mutex_t *mutex); /** Delete a semaphore * @param mutex the mutex to delete */ void sys_mutex_free(sys_mutex_t *mutex); #ifndef sys_mutex_valid /** Check if a mutex is valid/allocated: return 1 for valid, 0 for invalid */ int sys_mutex_valid(sys_mutex_t *mutex); #endif #ifndef sys_mutex_set_invalid /** Set a mutex invalid so that sys_mutex_valid returns 0 */ void sys_mutex_set_invalid(sys_mutex_t *mutex); #endif #endif /* LWIP_COMPAT_MUTEX */ /* Semaphore functions: */ /** Create a new semaphore * @param sem pointer to the semaphore to create * @param count initial count of the semaphore * @return ERR_OK if successful, another err_t otherwise */ err_t sys_sem_new(sys_sem_t *sem, u8_t count); /** Signals a semaphore * @param sem the semaphore to signal */ void sys_sem_signal(sys_sem_t *sem); /** Wait for a semaphore for the specified timeout * @param sem the semaphore to wait for * @param timeout timeout in milliseconds to wait (0 = wait forever) * @return time (in milliseconds) waited for the semaphore * or SYS_ARCH_TIMEOUT on timeout */ u32_t sys_arch_sem_wait(sys_sem_t *sem, u32_t timeout); /** Delete a semaphore * @param sem semaphore to delete */ void sys_sem_free(sys_sem_t *sem); /** Wait for a semaphore - forever/no timeout */ #define sys_sem_wait(sem) sys_arch_sem_wait(sem, 0) #ifndef sys_sem_valid /** Check if a sempahore is valid/allocated: return 1 for valid, 0 for invalid */ int sys_sem_valid(sys_sem_t *sem); #endif #ifndef sys_sem_set_invalid /** Set a semaphore invalid so that sys_sem_valid returns 0 */ void sys_sem_set_invalid(sys_sem_t *sem); #endif /* Time functions. */ #ifndef sys_msleep void sys_msleep(u32_t ms); /* only has a (close to) 1 jiffy resolution. */ #endif /* Mailbox functions. */ /** Create a new mbox of specified size * @param mbox pointer to the mbox to create * @param size (miminum) number of messages in this mbox * @return ERR_OK if successful, another err_t otherwise */ err_t sys_mbox_new(sys_mbox_t *mbox, int size); /** Post a message to an mbox - may not fail * -> blocks if full, only used from tasks not from ISR * @param mbox mbox to posts the message * @param msg message to post (ATTENTION: can be NULL) */ void sys_mbox_post(sys_mbox_t *mbox, void *msg); /** Try to post a message to an mbox - may fail if full or ISR * @param mbox mbox to posts the message * @param msg message to post (ATTENTION: can be NULL) */ err_t sys_mbox_trypost(sys_mbox_t *mbox, void *msg); /** Wait for a new message to arrive in the mbox * @param mbox mbox to get a message from * @param msg pointer where the message is stored * @param timeout maximum time (in milliseconds) to wait for a message * @return time (in milliseconds) waited for a message, may be 0 if not waited or SYS_ARCH_TIMEOUT on timeout * The returned time has to be accurate to prevent timer jitter! */ u32_t sys_arch_mbox_fetch(sys_mbox_t *mbox, void **msg, u32_t timeout); /* Allow port to override with a macro, e.g. special timout for sys_arch_mbox_fetch() */ #ifndef sys_arch_mbox_tryfetch /** Wait for a new message to arrive in the mbox * @param mbox mbox to get a message from * @param msg pointer where the message is stored * @param timeout maximum time (in milliseconds) to wait for a message * @return 0 (milliseconds) if a message has been received * or SYS_MBOX_EMPTY if the mailbox is empty */ u32_t sys_arch_mbox_tryfetch(sys_mbox_t *mbox, void **msg); #endif /** For now, we map straight to sys_arch implementation. */ #define sys_mbox_tryfetch(mbox, msg) sys_arch_mbox_tryfetch(mbox, msg) /** Delete an mbox * @param mbox mbox to delete */ void sys_mbox_free(sys_mbox_t *mbox); #define sys_mbox_fetch(mbox, msg) sys_arch_mbox_fetch(mbox, msg, 0) #ifndef sys_mbox_valid /** Check if an mbox is valid/allocated: return 1 for valid, 0 for invalid */ int sys_mbox_valid(sys_mbox_t *mbox); #endif #ifndef sys_mbox_set_invalid /** Set an mbox invalid so that sys_mbox_valid returns 0 */ void sys_mbox_set_invalid(sys_mbox_t *mbox); #endif /** The only thread function: * Creates a new thread * @param name human-readable name for the thread (used for debugging purposes) * @param thread thread-function * @param arg parameter passed to 'thread' * @param stacksize stack size in bytes for the new thread (may be ignored by ports) * @param prio priority of the new thread (may be ignored by ports) */ sys_thread_t sys_thread_new(const char *name, lwip_thread_fn thread, void *arg, int stacksize, int prio); #endif /* NO_SYS */ /* sys_init() must be called before anthing else. */ void sys_init(void); #ifndef sys_jiffies /** Ticks/jiffies since power up. */ u32_t sys_jiffies(void); #endif /** Returns the current time in milliseconds, * may be the same as sys_jiffies or at least based on it. */ u32_t sys_now(void); /* Critical Region Protection */ /* These functions must be implemented in the sys_arch.c file. In some implementations they can provide a more light-weight protection mechanism than using semaphores. Otherwise semaphores can be used for implementation */ #ifndef SYS_ARCH_PROTECT /** SYS_LIGHTWEIGHT_PROT * define SYS_LIGHTWEIGHT_PROT in lwipopts.h if you want inter-task protection * for certain critical regions during buffer allocation, deallocation and memory * allocation and deallocation. */ #if SYS_LIGHTWEIGHT_PROT /** SYS_ARCH_DECL_PROTECT * declare a protection variable. This macro will default to defining a variable of * type sys_prot_t. If a particular port needs a different implementation, then * this macro may be defined in sys_arch.h. */ #define SYS_ARCH_DECL_PROTECT(lev) sys_prot_t lev /** SYS_ARCH_PROTECT * Perform a "fast" protect. This could be implemented by * disabling interrupts for an embedded system or by using a semaphore or * mutex. The implementation should allow calling SYS_ARCH_PROTECT when * already protected. The old protection level is returned in the variable * "lev". This macro will default to calling the sys_arch_protect() function * which should be implemented in sys_arch.c. If a particular port needs a * different implementation, then this macro may be defined in sys_arch.h */ #define SYS_ARCH_PROTECT(lev) lev = sys_arch_protect() /** SYS_ARCH_UNPROTECT * Perform a "fast" set of the protection level to "lev". This could be * implemented by setting the interrupt level to "lev" within the MACRO or by * using a semaphore or mutex. This macro will default to calling the * sys_arch_unprotect() function which should be implemented in * sys_arch.c. If a particular port needs a different implementation, then * this macro may be defined in sys_arch.h */ #define SYS_ARCH_UNPROTECT(lev) sys_arch_unprotect(lev) sys_prot_t sys_arch_protect(void); void sys_arch_unprotect(sys_prot_t pval); #else #define SYS_ARCH_DECL_PROTECT(lev) #define SYS_ARCH_PROTECT(lev) #define SYS_ARCH_UNPROTECT(lev) #endif /* SYS_LIGHTWEIGHT_PROT */ #endif /* SYS_ARCH_PROTECT */ /* * Macros to set/get and increase/decrease variables in a thread-safe way. * Use these for accessing variable that are used from more than one thread. */ #ifndef SYS_ARCH_INC #define SYS_ARCH_INC(var, val) do { \ SYS_ARCH_DECL_PROTECT(old_level); \ SYS_ARCH_PROTECT(old_level); \ var += val; \ SYS_ARCH_UNPROTECT(old_level); \ } while(0) #endif /* SYS_ARCH_INC */ #ifndef SYS_ARCH_DEC #define SYS_ARCH_DEC(var, val) do { \ SYS_ARCH_DECL_PROTECT(old_level); \ SYS_ARCH_PROTECT(old_level); \ var -= val; \ SYS_ARCH_UNPROTECT(old_level); \ } while(0) #endif /* SYS_ARCH_DEC */ #ifndef SYS_ARCH_GET #define SYS_ARCH_GET(var, ret) do { \ SYS_ARCH_DECL_PROTECT(old_level); \ SYS_ARCH_PROTECT(old_level); \ ret = var; \ SYS_ARCH_UNPROTECT(old_level); \ } while(0) #endif /* SYS_ARCH_GET */ #ifndef SYS_ARCH_SET #define SYS_ARCH_SET(var, val) do { \ SYS_ARCH_DECL_PROTECT(old_level); \ SYS_ARCH_PROTECT(old_level); \ var = val; \ SYS_ARCH_UNPROTECT(old_level); \ } while(0) #endif /* SYS_ARCH_SET */ #ifdef __cplusplus } #endif #endif /* __LWIP_SYS_H__ */ ================================================ FILE: Zelig/lwip/lwip/include/lwip/tcp.h ================================================ /* * Copyright (c) 2001-2004 Swedish Institute of Computer Science. * All rights reserved. * * Redistribution and use in source and binary forms, with or without modification, * are permitted provided that the following conditions are met: * * 1. Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * 3. The name of the author may not be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT * SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT * OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING * IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY * OF SUCH DAMAGE. * * This file is part of the lwIP TCP/IP stack. * * Author: Adam Dunkels * */ #ifndef __LWIP_TCP_H__ #define __LWIP_TCP_H__ #include "lwip/opt.h" #if LWIP_TCP /* don't build if not configured for use in lwipopts.h */ #include "lwip/sys.h" #include "lwip/mem.h" #include "lwip/pbuf.h" #include "lwip/ip.h" #include "lwip/icmp.h" #include "lwip/err.h" #ifdef __cplusplus extern "C" { #endif struct tcp_pcb; /** Function prototype for tcp accept callback functions. Called when a new * connection can be accepted on a listening pcb. * * @param arg Additional argument to pass to the callback function (@see tcp_arg()) * @param newpcb The new connection pcb * @param err An error code if there has been an error accepting. * Only return ERR_ABRT if you have called tcp_abort from within the * callback function! */ typedef err_t (*tcp_accept_fn)(void *arg, struct tcp_pcb *newpcb, err_t err); /** Function prototype for tcp receive callback functions. Called when data has * been received. * * @param arg Additional argument to pass to the callback function (@see tcp_arg()) * @param tpcb The connection pcb which received data * @param p The received data (or NULL when the connection has been closed!) * @param err An error code if there has been an error receiving * Only return ERR_ABRT if you have called tcp_abort from within the * callback function! */ typedef err_t (*tcp_recv_fn)(void *arg, struct tcp_pcb *tpcb, struct pbuf *p, err_t err); /** Function prototype for tcp sent callback functions. Called when sent data has * been acknowledged by the remote side. Use it to free corresponding resources. * This also means that the pcb has now space available to send new data. * * @param arg Additional argument to pass to the callback function (@see tcp_arg()) * @param tpcb The connection pcb for which data has been acknowledged * @param len The amount of bytes acknowledged * @return ERR_OK: try to send some data by calling tcp_output * Only return ERR_ABRT if you have called tcp_abort from within the * callback function! */ typedef err_t (*tcp_sent_fn)(void *arg, struct tcp_pcb *tpcb, u16_t len); /** Function prototype for tcp poll callback functions. Called periodically as * specified by @see tcp_poll. * * @param arg Additional argument to pass to the callback function (@see tcp_arg()) * @param tpcb tcp pcb * @return ERR_OK: try to send some data by calling tcp_output * Only return ERR_ABRT if you have called tcp_abort from within the * callback function! */ typedef err_t (*tcp_poll_fn)(void *arg, struct tcp_pcb *tpcb); /** Function prototype for tcp error callback functions. Called when the pcb * receives a RST or is unexpectedly closed for any other reason. * * @note The corresponding pcb is already freed when this callback is called! * * @param arg Additional argument to pass to the callback function (@see tcp_arg()) * @param err Error code to indicate why the pcb has been closed * ERR_ABRT: aborted through tcp_abort or by a TCP timer * ERR_RST: the connection was reset by the remote host */ typedef void (*tcp_err_fn)(void *arg, err_t err); /** Function prototype for tcp connected callback functions. Called when a pcb * is connected to the remote side after initiating a connection attempt by * calling tcp_connect(). * * @param arg Additional argument to pass to the callback function (@see tcp_arg()) * @param tpcb The connection pcb which is connected * @param err An unused error code, always ERR_OK currently ;-) TODO! * Only return ERR_ABRT if you have called tcp_abort from within the * callback function! * * @note When a connection attempt fails, the error callback is currently called! */ typedef err_t (*tcp_connected_fn)(void *arg, struct tcp_pcb *tpcb, err_t err); enum tcp_state { CLOSED = 0, LISTEN = 1, SYN_SENT = 2, SYN_RCVD = 3, ESTABLISHED = 4, FIN_WAIT_1 = 5, FIN_WAIT_2 = 6, CLOSE_WAIT = 7, CLOSING = 8, LAST_ACK = 9, TIME_WAIT = 10 }; #if LWIP_CALLBACK_API /* Function to call when a listener has been connected. * @param arg user-supplied argument (tcp_pcb.callback_arg) * @param pcb a new tcp_pcb that now is connected * @param err an error argument (TODO: that is current always ERR_OK?) * @return ERR_OK: accept the new connection, * any other err_t abortsthe new connection */ #define DEF_ACCEPT_CALLBACK tcp_accept_fn accept; #else /* LWIP_CALLBACK_API */ #define DEF_ACCEPT_CALLBACK #endif /* LWIP_CALLBACK_API */ /** * members common to struct tcp_pcb and struct tcp_listen_pcb */ #define TCP_PCB_COMMON(type) \ type *next; /* for the linked list */ \ enum tcp_state state; /* TCP state */ \ u8_t prio; \ void *callback_arg; \ /* the accept callback for listen- and normal pcbs, if LWIP_CALLBACK_API */ \ DEF_ACCEPT_CALLBACK \ /* ports are in host byte order */ \ u16_t local_port /* the TCP protocol control block */ struct tcp_pcb { /** common PCB members */ IP_PCB; /** protocol specific PCB members */ TCP_PCB_COMMON(struct tcp_pcb); /* ports are in host byte order */ u16_t remote_port; u8_t flags; #define TF_ACK_DELAY ((u8_t)0x01U) /* Delayed ACK. */ #define TF_ACK_NOW ((u8_t)0x02U) /* Immediate ACK. */ #define TF_INFR ((u8_t)0x04U) /* In fast recovery. */ #define TF_TIMESTAMP ((u8_t)0x08U) /* Timestamp option enabled */ #define TF_RXCLOSED ((u8_t)0x10U) /* rx closed by tcp_shutdown */ #define TF_FIN ((u8_t)0x20U) /* Connection was closed locally (FIN segment enqueued). */ #define TF_NODELAY ((u8_t)0x40U) /* Disable Nagle algorithm */ #define TF_NAGLEMEMERR ((u8_t)0x80U) /* nagle enabled, memerr, try to output to prevent delayed ACK to happen */ /* the rest of the fields are in host byte order as we have to do some math with them */ /* receiver variables */ u32_t rcv_nxt; /* next seqno expected */ u16_t rcv_wnd; /* receiver window available */ u16_t rcv_ann_wnd; /* receiver window to announce */ u32_t rcv_ann_right_edge; /* announced right edge of window */ /* Timers */ u32_t tmr; u8_t polltmr, pollinterval; /* Retransmission timer. */ s16_t rtime; u16_t mss; /* maximum segment size */ /* RTT (round trip time) estimation variables */ u32_t rttest; /* RTT estimate in 500ms ticks */ u32_t rtseq; /* sequence number being timed */ s16_t sa, sv; /* @todo document this */ s16_t rto; /* retransmission time-out */ u8_t nrtx; /* number of retransmissions */ /* fast retransmit/recovery */ u32_t lastack; /* Highest acknowledged seqno. */ u8_t dupacks; /* congestion avoidance/control variables */ u16_t cwnd; u16_t ssthresh; /* sender variables */ u32_t snd_nxt; /* next new seqno to be sent */ u16_t snd_wnd; /* sender window */ u32_t snd_wl1, snd_wl2; /* Sequence and acknowledgement numbers of last window update. */ u32_t snd_lbb; /* Sequence number of next byte to be buffered. */ u16_t acked; u16_t snd_buf; /* Available buffer space for sending (in bytes). */ #define TCP_SNDQUEUELEN_OVERFLOW (0xffffU-3) u16_t snd_queuelen; /* Available buffer space for sending (in tcp_segs). */ #if TCP_OVERSIZE /* Extra bytes available at the end of the last pbuf in unsent. */ u16_t unsent_oversize; #endif /* TCP_OVERSIZE */ /* These are ordered by sequence number: */ struct tcp_seg *unsent; /* Unsent (queued) segments. */ struct tcp_seg *unacked; /* Sent but unacknowledged segments. */ #if TCP_QUEUE_OOSEQ struct tcp_seg *ooseq; /* Received out of sequence segments. */ #endif /* TCP_QUEUE_OOSEQ */ struct pbuf *refused_data; /* Data previously received but not yet taken by upper layer */ #if LWIP_CALLBACK_API /* Function to be called when more send buffer space is available. */ tcp_sent_fn sent; /* Function to be called when (in-sequence) data has arrived. */ tcp_recv_fn recv; /* Function to be called when a connection has been set up. */ tcp_connected_fn connected; /* Function which is called periodically. */ tcp_poll_fn poll; /* Function to be called whenever a fatal error occurs. */ tcp_err_fn errf; #endif /* LWIP_CALLBACK_API */ #if LWIP_TCP_TIMESTAMPS u32_t ts_lastacksent; u32_t ts_recent; #endif /* LWIP_TCP_TIMESTAMPS */ /* idle time before KEEPALIVE is sent */ u32_t keep_idle; #if LWIP_TCP_KEEPALIVE u32_t keep_intvl; u32_t keep_cnt; #endif /* LWIP_TCP_KEEPALIVE */ /* Persist timer counter */ u32_t persist_cnt; /* Persist timer back-off */ u8_t persist_backoff; /* KEEPALIVE counter */ u8_t keep_cnt_sent; }; struct tcp_pcb_listen { /* Common members of all PCB types */ IP_PCB; /* Protocol specific PCB members */ TCP_PCB_COMMON(struct tcp_pcb_listen); #if TCP_LISTEN_BACKLOG u8_t backlog; u8_t accepts_pending; #endif /* TCP_LISTEN_BACKLOG */ }; #if LWIP_EVENT_API enum lwip_event { LWIP_EVENT_ACCEPT, LWIP_EVENT_SENT, LWIP_EVENT_RECV, LWIP_EVENT_CONNECTED, LWIP_EVENT_POLL, LWIP_EVENT_ERR }; err_t lwip_tcp_event(void *arg, struct tcp_pcb *pcb, enum lwip_event, struct pbuf *p, u16_t size, err_t err); #endif /* LWIP_EVENT_API */ /* Application program's interface: */ struct tcp_pcb * tcp_new (void); void tcp_arg (struct tcp_pcb *pcb, void *arg); void tcp_accept (struct tcp_pcb *pcb, tcp_accept_fn accept); void tcp_recv (struct tcp_pcb *pcb, tcp_recv_fn recv); void tcp_sent (struct tcp_pcb *pcb, tcp_sent_fn sent); void tcp_poll (struct tcp_pcb *pcb, tcp_poll_fn poll, u8_t interval); void tcp_err (struct tcp_pcb *pcb, tcp_err_fn err); #define tcp_mss(pcb) (((pcb)->flags & TF_TIMESTAMP) ? ((pcb)->mss - 12) : (pcb)->mss) #define tcp_sndbuf(pcb) ((pcb)->snd_buf) #define tcp_sndqueuelen(pcb) ((pcb)->snd_queuelen) #define tcp_nagle_disable(pcb) ((pcb)->flags |= TF_NODELAY) #define tcp_nagle_enable(pcb) ((pcb)->flags &= ~TF_NODELAY) #define tcp_nagle_disabled(pcb) (((pcb)->flags & TF_NODELAY) != 0) #if TCP_LISTEN_BACKLOG #define tcp_accepted(pcb) do { \ LWIP_ASSERT("pcb->state == LISTEN (called for wrong pcb?)", pcb->state == LISTEN); \ (((struct tcp_pcb_listen *)(pcb))->accepts_pending--); } while(0) #else /* TCP_LISTEN_BACKLOG */ #define tcp_accepted(pcb) LWIP_ASSERT("pcb->state == LISTEN (called for wrong pcb?)", \ pcb->state == LISTEN) #endif /* TCP_LISTEN_BACKLOG */ void tcp_recved (struct tcp_pcb *pcb, u16_t len); err_t tcp_bind (struct tcp_pcb *pcb, ip_addr_t *ipaddr, u16_t port); err_t tcp_connect (struct tcp_pcb *pcb, ip_addr_t *ipaddr, u16_t port, tcp_connected_fn connected); struct tcp_pcb * tcp_listen_with_backlog(struct tcp_pcb *pcb, u8_t backlog); #define tcp_listen(pcb) tcp_listen_with_backlog(pcb, TCP_DEFAULT_LISTEN_BACKLOG) void tcp_abort (struct tcp_pcb *pcb); err_t tcp_close (struct tcp_pcb *pcb); err_t tcp_shutdown(struct tcp_pcb *pcb, int shut_rx, int shut_tx); /* Flags for "apiflags" parameter in tcp_write */ #define TCP_WRITE_FLAG_COPY 0x01 #define TCP_WRITE_FLAG_MORE 0x02 err_t tcp_write (struct tcp_pcb *pcb, const void *dataptr, u16_t len, u8_t apiflags); void tcp_setprio (struct tcp_pcb *pcb, u8_t prio); #define TCP_PRIO_MIN 1 #define TCP_PRIO_NORMAL 64 #define TCP_PRIO_MAX 127 err_t tcp_output (struct tcp_pcb *pcb); const char* tcp_debug_state_str(enum tcp_state s); #ifdef __cplusplus } #endif #endif /* LWIP_TCP */ #endif /* __LWIP_TCP_H__ */ ================================================ FILE: Zelig/lwip/lwip/include/lwip/tcp_impl.h ================================================ /* * Copyright (c) 2001-2004 Swedish Institute of Computer Science. * All rights reserved. * * Redistribution and use in source and binary forms, with or without modification, * are permitted provided that the following conditions are met: * * 1. Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * 3. The name of the author may not be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT * SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT * OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING * IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY * OF SUCH DAMAGE. * * This file is part of the lwIP TCP/IP stack. * * Author: Adam Dunkels * */ #ifndef __LWIP_TCP_IMPL_H__ #define __LWIP_TCP_IMPL_H__ #include "lwip/opt.h" #if LWIP_TCP /* don't build if not configured for use in lwipopts.h */ #include "lwip/tcp.h" #include "lwip/sys.h" #include "lwip/mem.h" #include "lwip/pbuf.h" #include "lwip/ip.h" #include "lwip/icmp.h" #include "lwip/err.h" #ifdef __cplusplus extern "C" { #endif /* Functions for interfacing with TCP: */ /* Lower layer interface to TCP: */ #define tcp_init() /* Compatibility define, no init needed. */ void tcp_tmr (void); /* Must be called every TCP_TMR_INTERVAL ms. (Typically 250 ms). */ /* It is also possible to call these two functions at the right intervals (instead of calling tcp_tmr()). */ void tcp_slowtmr (void); void tcp_fasttmr (void); /* Only used by IP to pass a TCP segment to TCP: */ void tcp_input (struct pbuf *p, struct netif *inp); /* Used within the TCP code only: */ struct tcp_pcb * tcp_alloc (u8_t prio); void tcp_abandon (struct tcp_pcb *pcb, int reset); err_t tcp_send_empty_ack(struct tcp_pcb *pcb); void tcp_rexmit (struct tcp_pcb *pcb); void tcp_rexmit_rto (struct tcp_pcb *pcb); void tcp_rexmit_fast (struct tcp_pcb *pcb); u32_t tcp_update_rcv_ann_wnd(struct tcp_pcb *pcb); /** * This is the Nagle algorithm: try to combine user data to send as few TCP * segments as possible. Only send if * - no previously transmitted data on the connection remains unacknowledged or * - the TF_NODELAY flag is set (nagle algorithm turned off for this pcb) or * - the only unsent segment is at least pcb->mss bytes long (or there is more * than one unsent segment - with lwIP, this can happen although unsent->len < mss) * - or if we are in fast-retransmit (TF_INFR) */ #define tcp_do_output_nagle(tpcb) ((((tpcb)->unacked == NULL) || \ ((tpcb)->flags & (TF_NODELAY | TF_INFR)) || \ (((tpcb)->unsent != NULL) && (((tpcb)->unsent->next != NULL) || \ ((tpcb)->unsent->len >= (tpcb)->mss))) \ ) ? 1 : 0) #define tcp_output_nagle(tpcb) (tcp_do_output_nagle(tpcb) ? tcp_output(tpcb) : ERR_OK) #define TCP_SEQ_LT(a,b) ((s32_t)((a)-(b)) < 0) #define TCP_SEQ_LEQ(a,b) ((s32_t)((a)-(b)) <= 0) #define TCP_SEQ_GT(a,b) ((s32_t)((a)-(b)) > 0) #define TCP_SEQ_GEQ(a,b) ((s32_t)((a)-(b)) >= 0) /* is b<=a<=c? */ #if 0 /* see bug #10548 */ #define TCP_SEQ_BETWEEN(a,b,c) ((c)-(b) >= (a)-(b)) #endif #define TCP_SEQ_BETWEEN(a,b,c) (TCP_SEQ_GEQ(a,b) && TCP_SEQ_LEQ(a,c)) #define TCP_FIN 0x01U #define TCP_SYN 0x02U #define TCP_RST 0x04U #define TCP_PSH 0x08U #define TCP_ACK 0x10U #define TCP_URG 0x20U #define TCP_ECE 0x40U #define TCP_CWR 0x80U #define TCP_FLAGS 0x3fU /* Length of the TCP header, excluding options. */ #define TCP_HLEN 20 #ifndef TCP_TMR_INTERVAL #define TCP_TMR_INTERVAL 250 /* The TCP timer interval in milliseconds. */ #endif /* TCP_TMR_INTERVAL */ #ifndef TCP_FAST_INTERVAL #define TCP_FAST_INTERVAL TCP_TMR_INTERVAL /* the fine grained timeout in milliseconds */ #endif /* TCP_FAST_INTERVAL */ #ifndef TCP_SLOW_INTERVAL #define TCP_SLOW_INTERVAL (2*TCP_TMR_INTERVAL) /* the coarse grained timeout in milliseconds */ #endif /* TCP_SLOW_INTERVAL */ #define TCP_FIN_WAIT_TIMEOUT 20000 /* milliseconds */ #define TCP_SYN_RCVD_TIMEOUT 20000 /* milliseconds */ #define TCP_OOSEQ_TIMEOUT 6U /* x RTO */ #ifndef TCP_MSL #define TCP_MSL 60000UL /* The maximum segment lifetime in milliseconds */ #endif /* Keepalive values, compliant with RFC 1122. Don't change this unless you know what you're doing */ #ifndef TCP_KEEPIDLE_DEFAULT #define TCP_KEEPIDLE_DEFAULT 7200000UL /* Default KEEPALIVE timer in milliseconds */ #endif #ifndef TCP_KEEPINTVL_DEFAULT #define TCP_KEEPINTVL_DEFAULT 75000UL /* Default Time between KEEPALIVE probes in milliseconds */ #endif #ifndef TCP_KEEPCNT_DEFAULT #define TCP_KEEPCNT_DEFAULT 9U /* Default Counter for KEEPALIVE probes */ #endif #define TCP_MAXIDLE TCP_KEEPCNT_DEFAULT * TCP_KEEPINTVL_DEFAULT /* Maximum KEEPALIVE probe time */ /* Fields are (of course) in network byte order. * Some fields are converted to host byte order in tcp_input(). */ #ifdef PACK_STRUCT_USE_INCLUDES # include "arch/bpstruct.h" #endif PACK_STRUCT_BEGIN struct tcp_hdr { PACK_STRUCT_FIELD(u16_t src); PACK_STRUCT_FIELD(u16_t dest); PACK_STRUCT_FIELD(u32_t seqno); PACK_STRUCT_FIELD(u32_t ackno); PACK_STRUCT_FIELD(u16_t _hdrlen_rsvd_flags); PACK_STRUCT_FIELD(u16_t wnd); PACK_STRUCT_FIELD(u16_t chksum); PACK_STRUCT_FIELD(u16_t urgp); } PACK_STRUCT_STRUCT; PACK_STRUCT_END #ifdef PACK_STRUCT_USE_INCLUDES # include "arch/epstruct.h" #endif #define TCPH_OFFSET(phdr) (ntohs((phdr)->_hdrlen_rsvd_flags) >> 8) #define TCPH_HDRLEN(phdr) (ntohs((phdr)->_hdrlen_rsvd_flags) >> 12) #define TCPH_FLAGS(phdr) (ntohs((phdr)->_hdrlen_rsvd_flags) & TCP_FLAGS) #define TCPH_OFFSET_SET(phdr, offset) (phdr)->_hdrlen_rsvd_flags = htons(((offset) << 8) | TCPH_FLAGS(phdr)) #define TCPH_HDRLEN_SET(phdr, len) (phdr)->_hdrlen_rsvd_flags = htons(((len) << 12) | TCPH_FLAGS(phdr)) #define TCPH_FLAGS_SET(phdr, flags) (phdr)->_hdrlen_rsvd_flags = (((phdr)->_hdrlen_rsvd_flags & PP_HTONS((u16_t)(~(u16_t)(TCP_FLAGS)))) | htons(flags)) #define TCPH_HDRLEN_FLAGS_SET(phdr, len, flags) (phdr)->_hdrlen_rsvd_flags = htons(((len) << 12) | (flags)) #define TCPH_SET_FLAG(phdr, flags ) (phdr)->_hdrlen_rsvd_flags = ((phdr)->_hdrlen_rsvd_flags | htons(flags)) #define TCPH_UNSET_FLAG(phdr, flags) (phdr)->_hdrlen_rsvd_flags = htons(ntohs((phdr)->_hdrlen_rsvd_flags) | (TCPH_FLAGS(phdr) & ~(flags)) ) #define TCP_TCPLEN(seg) ((seg)->len + ((TCPH_FLAGS((seg)->tcphdr) & (TCP_FIN | TCP_SYN)) != 0)) /** Flags used on input processing, not on pcb->flags */ #define TF_RESET (u8_t)0x08U /* Connection was reset. */ #define TF_CLOSED (u8_t)0x10U /* Connection was sucessfully closed. */ #define TF_GOT_FIN (u8_t)0x20U /* Connection was closed by the remote end. */ #if LWIP_EVENT_API #define TCP_EVENT_ACCEPT(pcb,err,ret) ret = lwip_tcp_event((pcb)->callback_arg, (pcb),\ LWIP_EVENT_ACCEPT, NULL, 0, err) #define TCP_EVENT_SENT(pcb,space,ret) ret = lwip_tcp_event((pcb)->callback_arg, (pcb),\ LWIP_EVENT_SENT, NULL, space, ERR_OK) #define TCP_EVENT_RECV(pcb,p,err,ret) ret = lwip_tcp_event((pcb)->callback_arg, (pcb),\ LWIP_EVENT_RECV, (p), 0, (err)) #define TCP_EVENT_CLOSED(pcb,ret) ret = lwip_tcp_event((pcb)->callback_arg, (pcb),\ LWIP_EVENT_RECV, NULL, 0, ERR_OK) #define TCP_EVENT_CONNECTED(pcb,err,ret) ret = lwip_tcp_event((pcb)->callback_arg, (pcb),\ LWIP_EVENT_CONNECTED, NULL, 0, (err)) #define TCP_EVENT_POLL(pcb,ret) ret = lwip_tcp_event((pcb)->callback_arg, (pcb),\ LWIP_EVENT_POLL, NULL, 0, ERR_OK) #define TCP_EVENT_ERR(errf,arg,err) lwip_tcp_event((arg), NULL, \ LWIP_EVENT_ERR, NULL, 0, (err)) #else /* LWIP_EVENT_API */ #define TCP_EVENT_ACCEPT(pcb,err,ret) \ do { \ if((pcb)->accept != NULL) \ (ret) = (pcb)->accept((pcb)->callback_arg,(pcb),(err)); \ else (ret) = ERR_ARG; \ } while (0) #define TCP_EVENT_SENT(pcb,space,ret) \ do { \ if((pcb)->sent != NULL) \ (ret) = (pcb)->sent((pcb)->callback_arg,(pcb),(space)); \ else (ret) = ERR_OK; \ } while (0) #define TCP_EVENT_RECV(pcb,p,err,ret) \ do { \ if((pcb)->recv != NULL) { \ (ret) = (pcb)->recv((pcb)->callback_arg,(pcb),(p),(err));\ } else { \ (ret) = tcp_recv_null(NULL, (pcb), (p), (err)); \ } \ } while (0) #define TCP_EVENT_CLOSED(pcb,ret) \ do { \ if(((pcb)->recv != NULL)) { \ (ret) = (pcb)->recv((pcb)->callback_arg,(pcb),NULL,ERR_OK);\ } else { \ (ret) = ERR_OK; \ } \ } while (0) #define TCP_EVENT_CONNECTED(pcb,err,ret) \ do { \ if((pcb)->connected != NULL) \ (ret) = (pcb)->connected((pcb)->callback_arg,(pcb),(err)); \ else (ret) = ERR_OK; \ } while (0) #define TCP_EVENT_POLL(pcb,ret) \ do { \ if((pcb)->poll != NULL) \ (ret) = (pcb)->poll((pcb)->callback_arg,(pcb)); \ else (ret) = ERR_OK; \ } while (0) #define TCP_EVENT_ERR(errf,arg,err) \ do { \ if((errf) != NULL) \ (errf)((arg),(err)); \ } while (0) #endif /* LWIP_EVENT_API */ /** Enabled extra-check for TCP_OVERSIZE if LWIP_DEBUG is enabled */ #if TCP_OVERSIZE && defined(LWIP_DEBUG) #define TCP_OVERSIZE_DBGCHECK 1 #else #define TCP_OVERSIZE_DBGCHECK 0 #endif /** Don't generate checksum on copy if CHECKSUM_GEN_TCP is disabled */ #define TCP_CHECKSUM_ON_COPY (LWIP_CHECKSUM_ON_COPY && CHECKSUM_GEN_TCP) /* This structure represents a TCP segment on the unsent, unacked and ooseq queues */ struct tcp_seg { struct tcp_seg *next; /* used when putting segements on a queue */ struct pbuf *p; /* buffer containing data + TCP header */ u16_t len; /* the TCP length of this segment */ #if TCP_OVERSIZE_DBGCHECK u16_t oversize_left; /* Extra bytes available at the end of the last pbuf in unsent (used for asserting vs. tcp_pcb.unsent_oversized only) */ #endif /* TCP_OVERSIZE_DBGCHECK */ #if TCP_CHECKSUM_ON_COPY u16_t chksum; u8_t chksum_swapped; #endif /* TCP_CHECKSUM_ON_COPY */ u8_t flags; #define TF_SEG_OPTS_MSS (u8_t)0x01U /* Include MSS option. */ #define TF_SEG_OPTS_TS (u8_t)0x02U /* Include timestamp option. */ #define TF_SEG_DATA_CHECKSUMMED (u8_t)0x04U /* ALL data (not the header) is checksummed into 'chksum' */ struct tcp_hdr *tcphdr; /* the TCP header */ }; #define LWIP_TCP_OPT_LENGTH(flags) \ (flags & TF_SEG_OPTS_MSS ? 4 : 0) + \ (flags & TF_SEG_OPTS_TS ? 12 : 0) /** This returns a TCP header option for MSS in an u32_t */ #define TCP_BUILD_MSS_OPTION(x) (x) = PP_HTONL(((u32_t)2 << 24) | \ ((u32_t)4 << 16) | \ (((u32_t)TCP_MSS / 256) << 8) | \ (TCP_MSS & 255)) /* Global variables: */ extern struct tcp_pcb *tcp_input_pcb; extern u32_t tcp_ticks; /* The TCP PCB lists. */ union tcp_listen_pcbs_t { /* List of all TCP PCBs in LISTEN state. */ struct tcp_pcb_listen *listen_pcbs; struct tcp_pcb *pcbs; }; extern struct tcp_pcb *tcp_bound_pcbs; extern union tcp_listen_pcbs_t tcp_listen_pcbs; extern struct tcp_pcb *tcp_active_pcbs; /* List of all TCP PCBs that are in a state in which they accept or send data. */ extern struct tcp_pcb *tcp_tw_pcbs; /* List of all TCP PCBs in TIME-WAIT. */ extern struct tcp_pcb *tcp_tmp_pcb; /* Only used for temporary storage. */ /* Axioms about the above lists: 1) Every TCP PCB that is not CLOSED is in one of the lists. 2) A PCB is only in one of the lists. 3) All PCBs in the tcp_listen_pcbs list is in LISTEN state. 4) All PCBs in the tcp_tw_pcbs list is in TIME-WAIT state. */ /* Define two macros, TCP_REG and TCP_RMV that registers a TCP PCB with a PCB list or removes a PCB from a list, respectively. */ #ifndef TCP_DEBUG_PCB_LISTS #define TCP_DEBUG_PCB_LISTS 0 #endif #if TCP_DEBUG_PCB_LISTS #define TCP_REG(pcbs, npcb) do {\ LWIP_DEBUGF(TCP_DEBUG, ("TCP_REG %p local port %d\n", (npcb), (npcb)->local_port)); \ for(tcp_tmp_pcb = *(pcbs); \ tcp_tmp_pcb != NULL; \ tcp_tmp_pcb = tcp_tmp_pcb->next) { \ LWIP_ASSERT("TCP_REG: already registered\n", tcp_tmp_pcb != (npcb)); \ } \ LWIP_ASSERT("TCP_REG: pcb->state != CLOSED", ((pcbs) == &tcp_bound_pcbs) || ((npcb)->state != CLOSED)); \ (npcb)->next = *(pcbs); \ LWIP_ASSERT("TCP_REG: npcb->next != npcb", (npcb)->next != (npcb)); \ *(pcbs) = (npcb); \ LWIP_ASSERT("TCP_RMV: tcp_pcbs sane", tcp_pcbs_sane()); \ tcp_timer_needed(); \ } while(0) #define TCP_RMV(pcbs, npcb) do { \ LWIP_ASSERT("TCP_RMV: pcbs != NULL", *(pcbs) != NULL); \ LWIP_DEBUGF(TCP_DEBUG, ("TCP_RMV: removing %p from %p\n", (npcb), *(pcbs))); \ if(*(pcbs) == (npcb)) { \ *(pcbs) = (*pcbs)->next; \ } else for(tcp_tmp_pcb = *(pcbs); tcp_tmp_pcb != NULL; tcp_tmp_pcb = tcp_tmp_pcb->next) { \ if(tcp_tmp_pcb->next == (npcb)) { \ tcp_tmp_pcb->next = (npcb)->next; \ break; \ } \ } \ (npcb)->next = NULL; \ LWIP_ASSERT("TCP_RMV: tcp_pcbs sane", tcp_pcbs_sane()); \ LWIP_DEBUGF(TCP_DEBUG, ("TCP_RMV: removed %p from %p\n", (npcb), *(pcbs))); \ } while(0) #else /* LWIP_DEBUG */ #define TCP_REG(pcbs, npcb) \ do { \ (npcb)->next = *pcbs; \ *(pcbs) = (npcb); \ tcp_timer_needed(); \ } while (0) #define TCP_RMV(pcbs, npcb) \ do { \ if(*(pcbs) == (npcb)) { \ (*(pcbs)) = (*pcbs)->next; \ } \ else { \ for(tcp_tmp_pcb = *pcbs; \ tcp_tmp_pcb != NULL; \ tcp_tmp_pcb = tcp_tmp_pcb->next) { \ if(tcp_tmp_pcb->next == (npcb)) { \ tcp_tmp_pcb->next = (npcb)->next; \ break; \ } \ } \ } \ (npcb)->next = NULL; \ } while(0) #endif /* LWIP_DEBUG */ /* Internal functions: */ struct tcp_pcb *tcp_pcb_copy(struct tcp_pcb *pcb); void tcp_pcb_purge(struct tcp_pcb *pcb); void tcp_pcb_remove(struct tcp_pcb **pcblist, struct tcp_pcb *pcb); void tcp_segs_free(struct tcp_seg *seg); void tcp_seg_free(struct tcp_seg *seg); struct tcp_seg *tcp_seg_copy(struct tcp_seg *seg); #define tcp_ack(pcb) \ do { \ if((pcb)->flags & TF_ACK_DELAY) { \ (pcb)->flags &= ~TF_ACK_DELAY; \ (pcb)->flags |= TF_ACK_NOW; \ } \ else { \ (pcb)->flags |= TF_ACK_DELAY; \ } \ } while (0) #define tcp_ack_now(pcb) \ do { \ (pcb)->flags |= TF_ACK_NOW; \ } while (0) err_t tcp_send_fin(struct tcp_pcb *pcb); err_t tcp_enqueue_flags(struct tcp_pcb *pcb, u8_t flags); void tcp_rexmit_seg(struct tcp_pcb *pcb, struct tcp_seg *seg); void tcp_rst(u32_t seqno, u32_t ackno, ip_addr_t *local_ip, ip_addr_t *remote_ip, u16_t local_port, u16_t remote_port); u32_t tcp_next_iss(void); void tcp_keepalive(struct tcp_pcb *pcb); void tcp_zero_window_probe(struct tcp_pcb *pcb); #if TCP_CALCULATE_EFF_SEND_MSS u16_t tcp_eff_send_mss(u16_t sendmss, ip_addr_t *addr); #endif /* TCP_CALCULATE_EFF_SEND_MSS */ #if LWIP_CALLBACK_API err_t tcp_recv_null(void *arg, struct tcp_pcb *pcb, struct pbuf *p, err_t err); #endif /* LWIP_CALLBACK_API */ #if TCP_DEBUG || TCP_INPUT_DEBUG || TCP_OUTPUT_DEBUG void tcp_debug_print(struct tcp_hdr *tcphdr); void tcp_debug_print_flags(u8_t flags); void tcp_debug_print_state(enum tcp_state s); void tcp_debug_print_pcbs(void); s16_t tcp_pcbs_sane(void); #else # define tcp_debug_print(tcphdr) # define tcp_debug_print_flags(flags) # define tcp_debug_print_state(s) # define tcp_debug_print_pcbs() # define tcp_pcbs_sane() 1 #endif /* TCP_DEBUG */ /** External function (implemented in timers.c), called when TCP detects * that a timer is needed (i.e. active- or time-wait-pcb found). */ void tcp_timer_needed(void); #ifdef __cplusplus } #endif #endif /* LWIP_TCP */ #endif /* __LWIP_TCP_H__ */ ================================================ FILE: Zelig/lwip/lwip/include/lwip/tcpip.h ================================================ /* * Copyright (c) 2001-2004 Swedish Institute of Computer Science. * All rights reserved. * * Redistribution and use in source and binary forms, with or without modification, * are permitted provided that the following conditions are met: * * 1. Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * 3. The name of the author may not be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT * SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT * OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING * IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY * OF SUCH DAMAGE. * * This file is part of the lwIP TCP/IP stack. * * Author: Adam Dunkels * */ #ifndef __LWIP_TCPIP_H__ #define __LWIP_TCPIP_H__ #include "lwip/opt.h" #if !NO_SYS /* don't build if not configured for use in lwipopts.h */ #include "lwip/api_msg.h" #include "lwip/netifapi.h" #include "lwip/pbuf.h" #include "lwip/api.h" #include "lwip/sys.h" #include "lwip/timers.h" #include "lwip/netif.h" #ifdef __cplusplus extern "C" { #endif /** Define this to something that triggers a watchdog. This is called from * tcpip_thread after processing a message. */ #ifndef LWIP_TCPIP_THREAD_ALIVE #define LWIP_TCPIP_THREAD_ALIVE() #endif #if LWIP_TCPIP_CORE_LOCKING /** The global semaphore to lock the stack. */ extern sys_mutex_t lock_tcpip_core; #define LOCK_TCPIP_CORE() sys_mutex_lock(&lock_tcpip_core) #define UNLOCK_TCPIP_CORE() sys_mutex_unlock(&lock_tcpip_core) #define TCPIP_APIMSG(m) tcpip_apimsg_lock(m) #define TCPIP_APIMSG_ACK(m) #define TCPIP_NETIFAPI(m) tcpip_netifapi_lock(m) #define TCPIP_NETIFAPI_ACK(m) #else /* LWIP_TCPIP_CORE_LOCKING */ #define LOCK_TCPIP_CORE() #define UNLOCK_TCPIP_CORE() #define TCPIP_APIMSG(m) tcpip_apimsg(m) #define TCPIP_APIMSG_ACK(m) sys_sem_signal(&m->conn->op_completed) #define TCPIP_NETIFAPI(m) tcpip_netifapi(m) #define TCPIP_NETIFAPI_ACK(m) sys_sem_signal(&m->sem) #endif /* LWIP_TCPIP_CORE_LOCKING */ /** Function prototype for the init_done function passed to tcpip_init */ typedef void (*tcpip_init_done_fn)(void *arg); /** Function prototype for functions passed to tcpip_callback() */ typedef void (*tcpip_callback_fn)(void *ctx); void tcpip_init(tcpip_init_done_fn tcpip_init_done, void *arg); #if LWIP_NETCONN err_t tcpip_apimsg(struct api_msg *apimsg); #if LWIP_TCPIP_CORE_LOCKING err_t tcpip_apimsg_lock(struct api_msg *apimsg); #endif /* LWIP_TCPIP_CORE_LOCKING */ #endif /* LWIP_NETCONN */ err_t tcpip_input(struct pbuf *p, struct netif *inp); #if LWIP_NETIF_API err_t tcpip_netifapi(struct netifapi_msg *netifapimsg); #if LWIP_TCPIP_CORE_LOCKING err_t tcpip_netifapi_lock(struct netifapi_msg *netifapimsg); #endif /* LWIP_TCPIP_CORE_LOCKING */ #endif /* LWIP_NETIF_API */ err_t tcpip_callback_with_block(tcpip_callback_fn function, void *ctx, u8_t block); #define tcpip_callback(f, ctx) tcpip_callback_with_block(f, ctx, 1) /* free pbufs or heap memory from another context without blocking */ err_t pbuf_free_callback(struct pbuf *p); err_t mem_free_callback(void *m); #if LWIP_TCPIP_TIMEOUT err_t tcpip_timeout(u32_t msecs, sys_timeout_handler h, void *arg); err_t tcpip_untimeout(sys_timeout_handler h, void *arg); #endif /* LWIP_TCPIP_TIMEOUT */ enum tcpip_msg_type { #if LWIP_NETCONN TCPIP_MSG_API, #endif /* LWIP_NETCONN */ TCPIP_MSG_INPKT, #if LWIP_NETIF_API TCPIP_MSG_NETIFAPI, #endif /* LWIP_NETIF_API */ #if LWIP_TCPIP_TIMEOUT TCPIP_MSG_TIMEOUT, TCPIP_MSG_UNTIMEOUT, #endif /* LWIP_TCPIP_TIMEOUT */ TCPIP_MSG_CALLBACK }; struct tcpip_msg { enum tcpip_msg_type type; sys_sem_t *sem; union { #if LWIP_NETCONN struct api_msg *apimsg; #endif /* LWIP_NETCONN */ #if LWIP_NETIF_API struct netifapi_msg *netifapimsg; #endif /* LWIP_NETIF_API */ struct { struct pbuf *p; struct netif *netif; } inp; struct { tcpip_callback_fn function; void *ctx; } cb; #if LWIP_TCPIP_TIMEOUT struct { u32_t msecs; sys_timeout_handler h; void *arg; } tmo; #endif /* LWIP_TCPIP_TIMEOUT */ } msg; }; #ifdef __cplusplus } #endif #endif /* !NO_SYS */ #endif /* __LWIP_TCPIP_H__ */ ================================================ FILE: Zelig/lwip/lwip/include/lwip/timers.h ================================================ /* * Copyright (c) 2001-2004 Swedish Institute of Computer Science. * All rights reserved. * * Redistribution and use in source and binary forms, with or without modification, * are permitted provided that the following conditions are met: * * 1. Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * 3. The name of the author may not be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT * SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT * OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING * IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY * OF SUCH DAMAGE. * * This file is part of the lwIP TCP/IP stack. * * Author: Adam Dunkels * Simon Goldschmidt * */ #ifndef __LWIP_TIMERS_H__ #define __LWIP_TIMERS_H__ #include "lwip/opt.h" /* Timers are not supported when NO_SYS==1 and NO_SYS_NO_TIMERS==1 */ #define LWIP_TIMERS (!NO_SYS || (NO_SYS && !NO_SYS_NO_TIMERS)) #if LWIP_TIMERS #include "lwip/err.h" #include "lwip/sys.h" #ifdef __cplusplus extern "C" { #endif #ifndef LWIP_DEBUG_TIMERNAMES #ifdef LWIP_DEBUG #define LWIP_DEBUG_TIMERNAMES SYS_DEBUG #else /* LWIP_DEBUG */ #define LWIP_DEBUG_TIMERNAMES 0 #endif /* LWIP_DEBUG*/ #endif /** Function prototype for a timeout callback function. Register such a function * using sys_timeout(). * * @param arg Additional argument to pass to the function - set up by sys_timeout() */ typedef void (* sys_timeout_handler)(void *arg); struct sys_timeo { struct sys_timeo *next; u32_t time; sys_timeout_handler h; void *arg; #if LWIP_DEBUG_TIMERNAMES const char* handler_name; #endif /* LWIP_DEBUG_TIMERNAMES */ }; void sys_timeouts_init(void); #if LWIP_DEBUG_TIMERNAMES void sys_timeout_debug(u32_t msecs, sys_timeout_handler handler, void *arg, const char* handler_name); #define sys_timeout(msecs, handler, arg) sys_timeout_debug(msecs, handler, arg, #handler) #else /* LWIP_DEBUG_TIMERNAMES */ void sys_timeout(u32_t msecs, sys_timeout_handler handler, void *arg); #endif /* LWIP_DEBUG_TIMERNAMES */ void sys_untimeout(sys_timeout_handler handler, void *arg); #if NO_SYS void sys_check_timeouts(void); void sys_restart_timeouts(void); #else /* NO_SYS */ void sys_timeouts_mbox_fetch(sys_mbox_t *mbox, void **msg); #endif /* NO_SYS */ #ifdef __cplusplus } #endif #endif /* LWIP_TIMERS */ #endif /* __LWIP_TIMERS_H__ */ ================================================ FILE: Zelig/lwip/lwip/include/lwip/udp.h ================================================ /* * Copyright (c) 2001-2004 Swedish Institute of Computer Science. * All rights reserved. * * Redistribution and use in source and binary forms, with or without modification, * are permitted provided that the following conditions are met: * * 1. Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * 3. The name of the author may not be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT * SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT * OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING * IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY * OF SUCH DAMAGE. * * This file is part of the lwIP TCP/IP stack. * * Author: Adam Dunkels * */ #ifndef __LWIP_UDP_H__ #define __LWIP_UDP_H__ #include "lwip/opt.h" #if LWIP_UDP /* don't build if not configured for use in lwipopts.h */ #include "lwip/pbuf.h" #include "lwip/netif.h" #include "lwip/ip_addr.h" #include "lwip/ip.h" #ifdef __cplusplus extern "C" { #endif #define UDP_HLEN 8 /* Fields are (of course) in network byte order. */ #ifdef PACK_STRUCT_USE_INCLUDES # include "arch/bpstruct.h" #endif PACK_STRUCT_BEGIN struct udp_hdr { PACK_STRUCT_FIELD(u16_t src); PACK_STRUCT_FIELD(u16_t dest); /* src/dest UDP ports */ PACK_STRUCT_FIELD(u16_t len); PACK_STRUCT_FIELD(u16_t chksum); } PACK_STRUCT_STRUCT; PACK_STRUCT_END #ifdef PACK_STRUCT_USE_INCLUDES # include "arch/epstruct.h" #endif #define UDP_FLAGS_NOCHKSUM 0x01U #define UDP_FLAGS_UDPLITE 0x02U #define UDP_FLAGS_CONNECTED 0x04U #define UDP_FLAGS_MULTICAST_LOOP 0x08U struct udp_pcb; /** Function prototype for udp pcb receive callback functions * addr and port are in same byte order as in the pcb * The callback is responsible for freeing the pbuf * if it's not used any more. * * ATTENTION: Be aware that 'addr' points into the pbuf 'p' so freeing this pbuf * makes 'addr' invalid, too. * * @param arg user supplied argument (udp_pcb.recv_arg) * @param pcb the udp_pcb which received data * @param p the packet buffer that was received * @param addr the remote IP address from which the packet was received * @param port the remote port from which the packet was received */ typedef void (*udp_recv_fn)(void *arg, struct udp_pcb *pcb, struct pbuf *p, ip_addr_t *addr, u16_t port); struct udp_pcb { /* Common members of all PCB types */ IP_PCB; /* Protocol specific PCB members */ struct udp_pcb *next; u8_t flags; /** ports are in host byte order */ u16_t local_port, remote_port; #if LWIP_IGMP /** outgoing network interface for multicast packets */ ip_addr_t multicast_ip; #endif /* LWIP_IGMP */ #if LWIP_UDPLITE /** used for UDP_LITE only */ u16_t chksum_len_rx, chksum_len_tx; #endif /* LWIP_UDPLITE */ /** receive callback function */ udp_recv_fn recv; /** user-supplied argument for the recv callback */ void *recv_arg; }; /* udp_pcbs export for exernal reference (e.g. SNMP agent) */ extern struct udp_pcb *udp_pcbs; /* The following functions is the application layer interface to the UDP code. */ struct udp_pcb * udp_new (void); void udp_remove (struct udp_pcb *pcb); err_t udp_bind (struct udp_pcb *pcb, ip_addr_t *ipaddr, u16_t port); err_t udp_connect (struct udp_pcb *pcb, ip_addr_t *ipaddr, u16_t port); void udp_disconnect (struct udp_pcb *pcb); void udp_recv (struct udp_pcb *pcb, udp_recv_fn recv, void *recv_arg); err_t udp_sendto_if (struct udp_pcb *pcb, struct pbuf *p, ip_addr_t *dst_ip, u16_t dst_port, struct netif *netif); err_t udp_sendto (struct udp_pcb *pcb, struct pbuf *p, ip_addr_t *dst_ip, u16_t dst_port); err_t udp_send (struct udp_pcb *pcb, struct pbuf *p); #if LWIP_CHECKSUM_ON_COPY err_t udp_sendto_if_chksum(struct udp_pcb *pcb, struct pbuf *p, ip_addr_t *dst_ip, u16_t dst_port, struct netif *netif, u8_t have_chksum, u16_t chksum); err_t udp_sendto_chksum(struct udp_pcb *pcb, struct pbuf *p, ip_addr_t *dst_ip, u16_t dst_port, u8_t have_chksum, u16_t chksum); err_t udp_send_chksum(struct udp_pcb *pcb, struct pbuf *p, u8_t have_chksum, u16_t chksum); #endif /* LWIP_CHECKSUM_ON_COPY */ #define udp_flags(pcb) ((pcb)->flags) #define udp_setflags(pcb, f) ((pcb)->flags = (f)) /* The following functions are the lower layer interface to UDP. */ void udp_input (struct pbuf *p, struct netif *inp); #define udp_init() /* Compatibility define, not init needed. */ #if UDP_DEBUG void udp_debug_print(struct udp_hdr *udphdr); #else #define udp_debug_print(udphdr) #endif #ifdef __cplusplus } #endif #endif /* LWIP_UDP */ #endif /* __LWIP_UDP_H__ */ ================================================ FILE: Zelig/lwip/lwip/include/netif/etharp.h ================================================ /* * Copyright (c) 2001-2003 Swedish Institute of Computer Science. * Copyright (c) 2003-2004 Leon Woestenberg * Copyright (c) 2003-2004 Axon Digital Design B.V., The Netherlands. * All rights reserved. * * Redistribution and use in source and binary forms, with or without modification, * are permitted provided that the following conditions are met: * * 1. Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * 3. The name of the author may not be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT * SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT * OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING * IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY * OF SUCH DAMAGE. * * This file is part of the lwIP TCP/IP stack. * * Author: Adam Dunkels * */ #ifndef __NETIF_ETHARP_H__ #define __NETIF_ETHARP_H__ #include "lwip/opt.h" #if LWIP_ARP || LWIP_ETHERNET /* don't build if not configured for use in lwipopts.h */ #include "lwip/pbuf.h" #include "lwip/ip_addr.h" #include "lwip/netif.h" #include "lwip/ip.h" #ifdef __cplusplus extern "C" { #endif #ifndef ETHARP_HWADDR_LEN #define ETHARP_HWADDR_LEN 6 #endif #ifdef PACK_STRUCT_USE_INCLUDES # include "arch/bpstruct.h" #endif PACK_STRUCT_BEGIN struct eth_addr { PACK_STRUCT_FIELD(u8_t addr[ETHARP_HWADDR_LEN]); } PACK_STRUCT_STRUCT; PACK_STRUCT_END #ifdef PACK_STRUCT_USE_INCLUDES # include "arch/epstruct.h" #endif #ifdef PACK_STRUCT_USE_INCLUDES # include "arch/bpstruct.h" #endif PACK_STRUCT_BEGIN /** Ethernet header */ struct eth_hdr { #if ETH_PAD_SIZE PACK_STRUCT_FIELD(u8_t padding[ETH_PAD_SIZE]); #endif PACK_STRUCT_FIELD(struct eth_addr dest); PACK_STRUCT_FIELD(struct eth_addr src); PACK_STRUCT_FIELD(u16_t type); } PACK_STRUCT_STRUCT; PACK_STRUCT_END #ifdef PACK_STRUCT_USE_INCLUDES # include "arch/epstruct.h" #endif #define SIZEOF_ETH_HDR (14 + ETH_PAD_SIZE) #if ETHARP_SUPPORT_VLAN #ifdef PACK_STRUCT_USE_INCLUDES # include "arch/bpstruct.h" #endif PACK_STRUCT_BEGIN /** VLAN header inserted between ethernet header and payload * if 'type' in ethernet header is ETHTYPE_VLAN. * See IEEE802.Q */ struct eth_vlan_hdr { PACK_STRUCT_FIELD(u16_t prio_vid); PACK_STRUCT_FIELD(u16_t tpid); } PACK_STRUCT_STRUCT; PACK_STRUCT_END #ifdef PACK_STRUCT_USE_INCLUDES # include "arch/epstruct.h" #endif #define SIZEOF_VLAN_HDR 4 #define VLAN_ID(vlan_hdr) (htons((vlan_hdr)->prio_vid) & 0xFFF) #endif /* ETHARP_SUPPORT_VLAN */ #ifdef PACK_STRUCT_USE_INCLUDES # include "arch/bpstruct.h" #endif PACK_STRUCT_BEGIN /** the ARP message, see RFC 826 ("Packet format") */ struct etharp_hdr { PACK_STRUCT_FIELD(u16_t hwtype); PACK_STRUCT_FIELD(u16_t proto); PACK_STRUCT_FIELD(u8_t hwlen); PACK_STRUCT_FIELD(u8_t protolen); PACK_STRUCT_FIELD(u16_t opcode); PACK_STRUCT_FIELD(struct eth_addr shwaddr); PACK_STRUCT_FIELD(struct ip_addr2 sipaddr); PACK_STRUCT_FIELD(struct eth_addr dhwaddr); PACK_STRUCT_FIELD(struct ip_addr2 dipaddr); } PACK_STRUCT_STRUCT; PACK_STRUCT_END #ifdef PACK_STRUCT_USE_INCLUDES # include "arch/epstruct.h" #endif #define SIZEOF_ETHARP_HDR 28 #define SIZEOF_ETHARP_PACKET (SIZEOF_ETH_HDR + SIZEOF_ETHARP_HDR) /** 5 seconds period */ #define ARP_TMR_INTERVAL 5000 #define ETHTYPE_ARP 0x0806U #define ETHTYPE_IP 0x0800U #define ETHTYPE_VLAN 0x8100U #define ETHTYPE_PPPOEDISC 0x8863U /* PPP Over Ethernet Discovery Stage */ #define ETHTYPE_PPPOE 0x8864U /* PPP Over Ethernet Session Stage */ /** MEMCPY-like macro to copy to/from struct eth_addr's that are local variables * or known to be 32-bit aligned within the protocol header. */ #ifndef ETHADDR32_COPY #define ETHADDR32_COPY(src, dst) SMEMCPY(src, dst, ETHARP_HWADDR_LEN) #endif /** MEMCPY-like macro to copy to/from struct eth_addr's that are no local * variables and known to be 16-bit aligned within the protocol header. */ #ifndef ETHADDR16_COPY #define ETHADDR16_COPY(src, dst) SMEMCPY(src, dst, ETHARP_HWADDR_LEN) #endif #if LWIP_ARP /* don't build if not configured for use in lwipopts.h */ /** ARP message types (opcodes) */ #define ARP_REQUEST 1 #define ARP_REPLY 2 /** Define this to 1 and define LWIP_ARP_FILTER_NETIF_FN(pbuf, netif, type) * to a filter function that returns the correct netif when using multiple * netifs on one hardware interface where the netif's low-level receive * routine cannot decide for the correct netif (e.g. when mapping multiple * IP addresses to one hardware interface). */ #ifndef LWIP_ARP_FILTER_NETIF #define LWIP_ARP_FILTER_NETIF 0 #endif #if ARP_QUEUEING /** struct for queueing outgoing packets for unknown address * defined here to be accessed by memp.h */ struct etharp_q_entry { struct etharp_q_entry *next; struct pbuf *p; }; #endif /* ARP_QUEUEING */ #define etharp_init() /* Compatibility define, not init needed. */ void etharp_tmr(void); s8_t etharp_find_addr(struct netif *netif, ip_addr_t *ipaddr, struct eth_addr **eth_ret, ip_addr_t **ip_ret); err_t etharp_output(struct netif *netif, struct pbuf *q, ip_addr_t *ipaddr); err_t etharp_query(struct netif *netif, ip_addr_t *ipaddr, struct pbuf *q); err_t etharp_request(struct netif *netif, ip_addr_t *ipaddr); /** For Ethernet network interfaces, we might want to send "gratuitous ARP"; * this is an ARP packet sent by a node in order to spontaneously cause other * nodes to update an entry in their ARP cache. * From RFC 3220 "IP Mobility Support for IPv4" section 4.6. */ #define etharp_gratuitous(netif) etharp_request((netif), &(netif)->ip_addr) #if ETHARP_SUPPORT_STATIC_ENTRIES err_t etharp_add_static_entry(ip_addr_t *ipaddr, struct eth_addr *ethaddr); err_t etharp_remove_static_entry(ip_addr_t *ipaddr); #endif /* ETHARP_SUPPORT_STATIC_ENTRIES */ #if LWIP_AUTOIP err_t etharp_raw(struct netif *netif, const struct eth_addr *ethsrc_addr, const struct eth_addr *ethdst_addr, const struct eth_addr *hwsrc_addr, const ip_addr_t *ipsrc_addr, const struct eth_addr *hwdst_addr, const ip_addr_t *ipdst_addr, const u16_t opcode); #endif /* LWIP_AUTOIP */ #endif /* LWIP_ARP */ err_t ethernet_input(struct pbuf *p, struct netif *netif); #define eth_addr_cmp(addr1, addr2) (memcmp((addr1)->addr, (addr2)->addr, ETHARP_HWADDR_LEN) == 0) extern const struct eth_addr ethbroadcast, ethzero; #ifdef __cplusplus } #endif #endif /* LWIP_ARP || LWIP_ETHERNET */ #endif /* __NETIF_ARP_H__ */ ================================================ FILE: Zelig/lwip/lwip/include/netif/ppp_oe.h ================================================ /***************************************************************************** * ppp_oe.h - PPP Over Ethernet implementation for lwIP. * * Copyright (c) 2006 by Marc Boucher, Services Informatiques (MBSI) inc. * * The authors hereby grant permission to use, copy, modify, distribute, * and license this software and its documentation for any purpose, provided * that existing copyright notices are retained in all copies and that this * notice and the following disclaimer are included verbatim in any * distributions. No written agreement, license, or royalty fee is required * for any of the authorized uses. * * THIS SOFTWARE IS PROVIDED BY THE 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 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. * ****************************************************************************** * REVISION HISTORY * * 06-01-01 Marc Boucher * Ported to lwIP. *****************************************************************************/ /* based on NetBSD: if_pppoe.c,v 1.64 2006/01/31 23:50:15 martin Exp */ /*- * Copyright (c) 2002 The NetBSD Foundation, Inc. * All rights reserved. * * This code is derived from software contributed to The NetBSD Foundation * by Martin Husemann . * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * 3. All advertising materials mentioning features or use of this software * must display the following acknowledgement: * This product includes software developed by the NetBSD * Foundation, Inc. and its contributors. * 4. Neither the name of The NetBSD Foundation nor the names of its * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE NETBSD FOUNDATION, INC. AND CONTRIBUTORS * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE FOUNDATION OR CONTRIBUTORS * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. */ #ifndef PPP_OE_H #define PPP_OE_H #include "lwip/opt.h" #if PPPOE_SUPPORT > 0 #include "netif/etharp.h" #ifdef PACK_STRUCT_USE_INCLUDES # include "arch/bpstruct.h" #endif PACK_STRUCT_BEGIN struct pppoehdr { PACK_STRUCT_FIELD(u8_t vertype); PACK_STRUCT_FIELD(u8_t code); PACK_STRUCT_FIELD(u16_t session); PACK_STRUCT_FIELD(u16_t plen); } PACK_STRUCT_STRUCT; PACK_STRUCT_END #ifdef PACK_STRUCT_USE_INCLUDES # include "arch/epstruct.h" #endif #ifdef PACK_STRUCT_USE_INCLUDES # include "arch/bpstruct.h" #endif PACK_STRUCT_BEGIN struct pppoetag { PACK_STRUCT_FIELD(u16_t tag); PACK_STRUCT_FIELD(u16_t len); } PACK_STRUCT_STRUCT; PACK_STRUCT_END #ifdef PACK_STRUCT_USE_INCLUDES # include "arch/epstruct.h" #endif #define PPPOE_STATE_INITIAL 0 #define PPPOE_STATE_PADI_SENT 1 #define PPPOE_STATE_PADR_SENT 2 #define PPPOE_STATE_SESSION 3 #define PPPOE_STATE_CLOSING 4 /* passive */ #define PPPOE_STATE_PADO_SENT 1 #define PPPOE_HEADERLEN sizeof(struct pppoehdr) #define PPPOE_VERTYPE 0x11 /* VER=1, TYPE = 1 */ #define PPPOE_TAG_EOL 0x0000 /* end of list */ #define PPPOE_TAG_SNAME 0x0101 /* service name */ #define PPPOE_TAG_ACNAME 0x0102 /* access concentrator name */ #define PPPOE_TAG_HUNIQUE 0x0103 /* host unique */ #define PPPOE_TAG_ACCOOKIE 0x0104 /* AC cookie */ #define PPPOE_TAG_VENDOR 0x0105 /* vendor specific */ #define PPPOE_TAG_RELAYSID 0x0110 /* relay session id */ #define PPPOE_TAG_SNAME_ERR 0x0201 /* service name error */ #define PPPOE_TAG_ACSYS_ERR 0x0202 /* AC system error */ #define PPPOE_TAG_GENERIC_ERR 0x0203 /* gerneric error */ #define PPPOE_CODE_PADI 0x09 /* Active Discovery Initiation */ #define PPPOE_CODE_PADO 0x07 /* Active Discovery Offer */ #define PPPOE_CODE_PADR 0x19 /* Active Discovery Request */ #define PPPOE_CODE_PADS 0x65 /* Active Discovery Session confirmation */ #define PPPOE_CODE_PADT 0xA7 /* Active Discovery Terminate */ #ifndef ETHERMTU #define ETHERMTU 1500 #endif /* two byte PPP protocol discriminator, then IP data */ #define PPPOE_MAXMTU (ETHERMTU-PPPOE_HEADERLEN-2) #ifndef PPPOE_MAX_AC_COOKIE_LEN #define PPPOE_MAX_AC_COOKIE_LEN 64 #endif struct pppoe_softc { struct pppoe_softc *next; struct netif *sc_ethif; /* ethernet interface we are using */ int sc_pd; /* ppp unit number */ void (*sc_linkStatusCB)(int pd, int up); int sc_state; /* discovery phase or session connected */ struct eth_addr sc_dest; /* hardware address of concentrator */ u16_t sc_session; /* PPPoE session id */ #ifdef PPPOE_TODO char *sc_service_name; /* if != NULL: requested name of service */ char *sc_concentrator_name; /* if != NULL: requested concentrator id */ #endif /* PPPOE_TODO */ u8_t sc_ac_cookie[PPPOE_MAX_AC_COOKIE_LEN]; /* content of AC cookie we must echo back */ size_t sc_ac_cookie_len; /* length of cookie data */ #ifdef PPPOE_SERVER u8_t *sc_hunique; /* content of host unique we must echo back */ size_t sc_hunique_len; /* length of host unique */ #endif int sc_padi_retried; /* number of PADI retries already done */ int sc_padr_retried; /* number of PADR retries already done */ }; #define pppoe_init() /* compatibility define, no initialization needed */ err_t pppoe_create(struct netif *ethif, int pd, void (*linkStatusCB)(int pd, int up), struct pppoe_softc **scptr); err_t pppoe_destroy(struct netif *ifp); int pppoe_connect(struct pppoe_softc *sc); void pppoe_disconnect(struct pppoe_softc *sc); void pppoe_disc_input(struct netif *netif, struct pbuf *p); void pppoe_data_input(struct netif *netif, struct pbuf *p); err_t pppoe_xmit(struct pppoe_softc *sc, struct pbuf *pb); /** used in ppp.c */ #define PPPOE_HDRLEN (sizeof(struct eth_hdr) + PPPOE_HEADERLEN) #endif /* PPPOE_SUPPORT */ #endif /* PPP_OE_H */ ================================================ FILE: Zelig/lwip/lwip/include/netif/slipif.h ================================================ /* * Copyright (c) 2001, Swedish Institute of Computer Science. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * 3. Neither the name of the Institute nor the names of its contributors * may be used to endorse or promote products derived from this software * without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. * * This file is part of the lwIP TCP/IP stack. * * Author: Adam Dunkels * */ #ifndef __NETIF_SLIPIF_H__ #define __NETIF_SLIPIF_H__ #include "lwip/netif.h" #ifdef __cplusplus extern "C" { #endif err_t slipif_init(struct netif * netif); void slipif_poll(struct netif *netif); #ifdef __cplusplus } #endif #endif ================================================ FILE: Zelig/lwip/lwip/lwipopts.h ================================================ /* Copyright (C) 2012 mbed.org, MIT License * * Permission is hereby granted, free of charge, to any person obtaining a copy of this software * and associated documentation files (the "Software"), to deal in the Software without restriction, * including without limitation the rights to use, copy, modify, merge, publish, distribute, * sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all copies or * substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING * BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, * DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ #ifndef LWIPOPTS_H #define LWIPOPTS_H #include "lwipopts_conf.h" // Operating System #define NO_SYS 0 #if NO_SYS == 0 #include "cmsis_os.h" #define SYS_LIGHTWEIGHT_PROT 1 #define LWIP_RAW 0 #define TCPIP_MBOX_SIZE 8 #define DEFAULT_TCP_RECVMBOX_SIZE 8 #define DEFAULT_UDP_RECVMBOX_SIZE 8 #define DEFAULT_RAW_RECVMBOX_SIZE 8 #define DEFAULT_ACCEPTMBOX_SIZE 8 #define TCPIP_THREAD_STACKSIZE 1024 #define TCPIP_THREAD_PRIO (osPriorityNormal) #define DEFAULT_THREAD_STACKSIZE 512 #define MEMP_NUM_SYS_TIMEOUT 16 #endif // 32-bit alignment #define MEM_ALIGNMENT 4 #define PBUF_POOL_SIZE 5 #define MEMP_NUM_TCP_PCB_LISTEN 4 #define MEMP_NUM_TCP_PCB 4 #define MEMP_NUM_PBUF 8 #define TCP_QUEUE_OOSEQ 0 #define TCP_OVERSIZE 0 #define LWIP_DHCP 1 #define LWIP_DNS 1 // Support Multicast #include "stdlib.h" #define LWIP_IGMP 1 #define LWIP_RAND() rand() #define LWIP_COMPAT_SOCKETS 0 #define LWIP_POSIX_SOCKETS_IO_NAMES 0 #define LWIP_SO_RCVTIMEO 1 #define LWIP_TCP_KEEPALIVE 1 // Debug Options // #define LWIP_DEBUG #define UDP_LPC_EMAC LWIP_DBG_OFF #define SYS_DEBUG LWIP_DBG_OFF #define PPP_DEBUG LWIP_DBG_OFF #define IP_DEBUG LWIP_DBG_OFF #define MEM_DEBUG LWIP_DBG_OFF #define MEMP_DEBUG LWIP_DBG_OFF #define PBUF_DEBUG LWIP_DBG_OFF #define API_LIB_DEBUG LWIP_DBG_OFF #define API_MSG_DEBUG LWIP_DBG_OFF #define TCPIP_DEBUG LWIP_DBG_OFF #define SOCKETS_DEBUG LWIP_DBG_OFF #define TCP_DEBUG LWIP_DBG_OFF #define TCP_INPUT_DEBUG LWIP_DBG_OFF #define TCP_FR_DEBUG LWIP_DBG_OFF #define TCP_RTO_DEBUG LWIP_DBG_OFF #define TCP_CWND_DEBUG LWIP_DBG_OFF #define TCP_WND_DEBUG LWIP_DBG_OFF #define TCP_OUTPUT_DEBUG LWIP_DBG_OFF #define TCP_RST_DEBUG LWIP_DBG_OFF #define TCP_QLEN_DEBUG LWIP_DBG_OFF #define ETHARP_DEBUG LWIP_DBG_OFF #define NETIF_DEBUG LWIP_DBG_OFF #define DHCP_DEBUG LWIP_DBG_OFF #ifdef LWIP_DEBUG #define MEMP_OVERFLOW_CHECK 1 #define MEMP_SANITY_CHECK 1 #else #define LWIP_NOASSERT 1 #define LWIP_STATS 0 #endif #define LWIP_PLATFORM_BYTESWAP 1 #if LWIP_TRANSPORT_ETHERNET /* MSS should match the hardware packet size */ #define TCP_MSS 1460 #define TCP_SND_BUF (2 * TCP_MSS) #define TCP_WND (2 * TCP_MSS) #define TCP_SND_QUEUELEN (2 * TCP_SND_BUF/TCP_MSS) // Broadcast #define IP_SOF_BROADCAST 1 #define IP_SOF_BROADCAST_RECV 1 #define LWIP_BROADCAST_PING 1 #define LWIP_CHECKSUM_ON_COPY 1 #define LWIP_NETIF_HOSTNAME 1 #define LWIP_NETIF_STATUS_CALLBACK 1 #define LWIP_NETIF_LINK_CALLBACK 1 #elif LWIP_TRANSPORT_PPP #define TCP_SND_BUF (3 * 536) #define TCP_WND (2 * 536) #define LWIP_ARP 0 #define PPP_SUPPORT 1 #define CHAP_SUPPORT 1 #define PAP_SUPPORT 1 #define PPP_THREAD_STACKSIZE 4*192 #define PPP_THREAD_PRIO 0 #define MAXNAMELEN 64 /* max length of hostname or name for auth */ #define MAXSECRETLEN 64 #else #error A transport mechanism (Ethernet or PPP) must be defined #endif #endif /* LWIPOPTS_H_ */ ================================================ FILE: Zelig/lwip/lwip-eth/arch/TARGET_Freescale/k64f_emac_config.h ================================================ /* * Copyright (c) 2013 - 2014, Freescale Semiconductor, Inc. * All rights reserved. * * Redistribution and use in source and binary forms, with or without modification, * are permitted provided that the following conditions are met: * * o Redistributions of source code must retain the above copyright notice, this list * of conditions and the following disclaimer. * * o Redistributions in binary form must reproduce the above copyright notice, this * list of conditions and the following disclaimer in the documentation and/or * other materials provided with the distribution. * * o Neither the name of Freescale Semiconductor, Inc. nor the names of its * contributors may be used to endorse or promote products derived from this * software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT 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. */ #ifndef K64F_EMAC_CONFIG_H__ #define K64F_EMAC_CONFIG_H__ #define ENET_RX_RING_LEN (16) #define ENET_TX_RING_LEN (8) #define ENET_RX_LARGE_BUFFER_NUM (0) #define ENET_RX_BUFFER_ALIGNMENT (16) #define ENET_TX_BUFFER_ALIGNMENT (16) #define ENET_BD_ALIGNMENT (16) #define ENET_MII_CLOCK (2500000L) #define RX_BUF_ALIGNMENT (16) #define TX_BUF_ALIGNMENT (8) #define BOARD_DEBUG_ENET_INSTANCE (0) #define BOARD_DEBUG_ENET_INSTANCE_ADDR (ENET_BASE) #define ENET_ETH_MAX_FLEN (1522) // recommended size for a VLAN frame #if defined(__cplusplus) extern "C" { #endif int phy_link_status(void); #if defined(__cplusplus) } #endif #endif // #define K64F_EMAC_CONFIG_H__ ================================================ FILE: Zelig/lwip/lwip-eth/arch/TARGET_Freescale/lwipopts_conf.h ================================================ /* Copyright (C) 2012 mbed.org, MIT License * * Permission is hereby granted, free of charge, to any person obtaining a copy of this software * and associated documentation files (the "Software"), to deal in the Software without restriction, * including without limitation the rights to use, copy, modify, merge, publish, distribute, * sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all copies or * substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING * BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, * DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ #ifndef LWIPOPTS_CONF_H #define LWIPOPTS_CONF_H #include "k64f_emac_config.h" #define LWIP_TRANSPORT_ETHERNET 1 #define ETH_PAD_SIZE 2 #define MEM_SIZE (ENET_RX_RING_LEN * (ENET_ETH_MAX_FLEN + RX_BUF_ALIGNMENT) + ENET_TX_RING_LEN * ENET_ETH_MAX_FLEN) #endif ================================================ FILE: Zelig/lwip/lwip-eth/arch/TARGET_NXP/lpc17_emac.c ================================================ /********************************************************************** * $Id$ lpc17_emac.c 2011-11-20 *//** * @file lpc17_emac.c * @brief LPC17 ethernet driver for LWIP * @version 1.0 * @date 20. Nov. 2011 * @author NXP MCU SW Application Team * * Copyright(C) 2011, NXP Semiconductor * All rights reserved. * *********************************************************************** * Software that is described herein is for illustrative purposes only * which provides customers with programming information regarding the * products. This software is supplied "AS IS" without any warranties. * NXP Semiconductors assumes no responsibility or liability for the * use of the software, conveys no license or title under any patent, * copyright, or mask work right to the product. NXP Semiconductors * reserves the right to make changes in the software without * notification. NXP Semiconductors also make no representation or * warranty that such application will be suitable for the specified * use without further testing or modification. **********************************************************************/ #include "lwip/opt.h" #include "lwip/sys.h" #include "lwip/def.h" #include "lwip/mem.h" #include "lwip/pbuf.h" #include "lwip/stats.h" #include "lwip/snmp.h" #include "netif/etharp.h" #include "netif/ppp_oe.h" #include "lpc17xx_emac.h" #include "eth_arch.h" #include "lpc_emac_config.h" #include "lpc_phy.h" #include "sys_arch.h" #include "mbed_interface.h" #include #ifndef LPC_EMAC_RMII #error LPC_EMAC_RMII is not defined! #endif #if LPC_NUM_BUFF_TXDESCS < 2 #error LPC_NUM_BUFF_TXDESCS must be at least 2 #endif #if LPC_NUM_BUFF_RXDESCS < 3 #error LPC_NUM_BUFF_RXDESCS must be at least 3 #endif /** @defgroup lwip17xx_emac_DRIVER lpc17 EMAC driver for LWIP * @ingroup lwip_emac * * @{ */ #if NO_SYS == 0 /** \brief Driver transmit and receive thread priorities * * Thread priorities for receive thread and TX cleanup thread. Alter * to prioritize receive or transmit bandwidth. In a heavily loaded * system or with LEIP_DEBUG enabled, the priorities might be better * the same. */ #define RX_PRIORITY (osPriorityNormal) #define TX_PRIORITY (osPriorityNormal) /** \brief Debug output formatter lock define * * When using FreeRTOS and with LWIP_DEBUG enabled, enabling this * define will allow RX debug messages to not interleave with the * TX messages (so they are actually readable). Not enabling this * define when the system is under load will cause the output to * be unreadable. There is a small tradeoff in performance for this * so use it only for debug. */ //#define LOCK_RX_THREAD /** \brief Receive group interrupts */ #define RXINTGROUP (EMAC_INT_RX_OVERRUN | EMAC_INT_RX_ERR | EMAC_INT_RX_DONE) /** \brief Transmit group interrupts */ #define TXINTGROUP (EMAC_INT_TX_UNDERRUN | EMAC_INT_TX_ERR | EMAC_INT_TX_DONE) /** \brief Signal used for ethernet ISR to signal packet_rx() thread. */ #define RX_SIGNAL 1 #else #define RXINTGROUP 0 #define TXINTGROUP 0 #endif /** \brief Structure of a TX/RX descriptor */ typedef struct { volatile u32_t packet; /**< Pointer to buffer */ volatile u32_t control; /**< Control word */ } LPC_TXRX_DESC_T; /** \brief Structure of a RX status entry */ typedef struct { volatile u32_t statusinfo; /**< RX status word */ volatile u32_t statushashcrc; /**< RX hash CRC */ } LPC_TXRX_STATUS_T; /* LPC EMAC driver data structure */ struct lpc_enetdata { /* prxs must be 8 byte aligned! */ LPC_TXRX_STATUS_T prxs[LPC_NUM_BUFF_RXDESCS]; /**< Pointer to RX statuses */ struct netif *netif; /**< Reference back to LWIP parent netif */ LPC_TXRX_DESC_T ptxd[LPC_NUM_BUFF_TXDESCS]; /**< Pointer to TX descriptor list */ LPC_TXRX_STATUS_T ptxs[LPC_NUM_BUFF_TXDESCS]; /**< Pointer to TX statuses */ LPC_TXRX_DESC_T prxd[LPC_NUM_BUFF_RXDESCS]; /**< Pointer to RX descriptor list */ struct pbuf *rxb[LPC_NUM_BUFF_RXDESCS]; /**< RX pbuf pointer list, zero-copy mode */ u32_t rx_fill_desc_index; /**< RX descriptor next available index */ volatile u32_t rx_free_descs; /**< Count of free RX descriptors */ struct pbuf *txb[LPC_NUM_BUFF_TXDESCS]; /**< TX pbuf pointer list, zero-copy mode */ u32_t lpc_last_tx_idx; /**< TX last descriptor index, zero-copy mode */ #if NO_SYS == 0 sys_thread_t RxThread; /**< RX receive thread data object pointer */ sys_sem_t TxCleanSem; /**< TX cleanup thread wakeup semaphore */ sys_mutex_t TXLockMutex; /**< TX critical section mutex */ sys_sem_t xTXDCountSem; /**< TX free buffer counting semaphore */ #endif }; #if defined(TARGET_LPC4088) || defined(TARGET_LPC4088_DM) # if defined (__ICCARM__) # define ETHMEM_SECTION # elif defined(TOOLCHAIN_GCC_CR) # define ETHMEM_SECTION __attribute__((section(".data.$RamPeriph32"), aligned)) # else # define ETHMEM_SECTION __attribute__((section("AHBSRAM1"),aligned)) # endif #elif defined(TARGET_LPC1768) # if defined(TOOLCHAIN_GCC_ARM) # define ETHMEM_SECTION __attribute__((section("AHBSRAM1"),aligned)) # endif #endif #ifndef ETHMEM_SECTION #define ETHMEM_SECTION ALIGNED(8) #endif /** \brief LPC EMAC driver work data */ ETHMEM_SECTION struct lpc_enetdata lpc_enetdata; /** \brief Queues a pbuf into the RX descriptor list * * \param[in] lpc_enetif Pointer to the drvier data structure * \param[in] p Pointer to pbuf to queue */ static void lpc_rxqueue_pbuf(struct lpc_enetdata *lpc_enetif, struct pbuf *p) { u32_t idx; /* Get next free descriptor index */ idx = lpc_enetif->rx_fill_desc_index; /* Setup descriptor and clear statuses */ lpc_enetif->prxd[idx].control = EMAC_RCTRL_INT | ((u32_t) (p->len - 1)); lpc_enetif->prxd[idx].packet = (u32_t) p->payload; lpc_enetif->prxs[idx].statusinfo = 0xFFFFFFFF; lpc_enetif->prxs[idx].statushashcrc = 0xFFFFFFFF; /* Save pbuf pointer for push to network layer later */ lpc_enetif->rxb[idx] = p; /* Wrap at end of descriptor list */ idx++; if (idx >= LPC_NUM_BUFF_RXDESCS) idx = 0; /* Queue descriptor(s) */ lpc_enetif->rx_free_descs -= 1; lpc_enetif->rx_fill_desc_index = idx; LPC_EMAC->RxConsumeIndex = idx; LWIP_DEBUGF(UDP_LPC_EMAC | LWIP_DBG_TRACE, ("lpc_rxqueue_pbuf: pbuf packet queued: %p (free desc=%d)\n", p, lpc_enetif->rx_free_descs)); } /** \brief Attempt to allocate and requeue a new pbuf for RX * * \param[in] netif Pointer to the netif structure * \returns 1 if a packet was allocated and requeued, otherwise 0 */ s32_t lpc_rx_queue(struct netif *netif) { struct lpc_enetdata *lpc_enetif = netif->state; struct pbuf *p; s32_t queued = 0; /* Attempt to requeue as many packets as possible */ while (lpc_enetif->rx_free_descs > 0) { /* Allocate a pbuf from the pool. We need to allocate at the maximum size as we don't know the size of the yet to be received packet. */ p = pbuf_alloc(PBUF_RAW, (u16_t) EMAC_ETH_MAX_FLEN, PBUF_RAM); if (p == NULL) { LWIP_DEBUGF(UDP_LPC_EMAC | LWIP_DBG_TRACE, ("lpc_rx_queue: could not allocate RX pbuf (free desc=%d)\n", lpc_enetif->rx_free_descs)); return queued; } /* pbufs allocated from the RAM pool should be non-chained. */ LWIP_ASSERT("lpc_rx_queue: pbuf is not contiguous (chained)", pbuf_clen(p) <= 1); /* Queue packet */ lpc_rxqueue_pbuf(lpc_enetif, p); /* Update queued count */ queued++; } return queued; } /** \brief Sets up the RX descriptor ring buffers. * * This function sets up the descriptor list used for receive packets. * * \param[in] lpc_enetif Pointer to driver data structure * \returns Always returns ERR_OK */ static err_t lpc_rx_setup(struct lpc_enetdata *lpc_enetif) { /* Setup pointers to RX structures */ LPC_EMAC->RxDescriptor = (u32_t) &lpc_enetif->prxd[0]; LPC_EMAC->RxStatus = (u32_t) &lpc_enetif->prxs[0]; LPC_EMAC->RxDescriptorNumber = LPC_NUM_BUFF_RXDESCS - 1; lpc_enetif->rx_free_descs = LPC_NUM_BUFF_RXDESCS; lpc_enetif->rx_fill_desc_index = 0; /* Build RX buffer and descriptors */ lpc_rx_queue(lpc_enetif->netif); return ERR_OK; } /** \brief Allocates a pbuf and returns the data from the incoming packet. * * \param[in] netif the lwip network interface structure for this lpc_enetif * \return a pbuf filled with the received packet (including MAC header) * NULL on memory error */ static struct pbuf *lpc_low_level_input(struct netif *netif) { struct lpc_enetdata *lpc_enetif = netif->state; struct pbuf *p = NULL; u32_t idx, length; u16_t origLength; #ifdef LOCK_RX_THREAD #if NO_SYS == 0 /* Get exclusive access */ sys_mutex_lock(&lpc_enetif->TXLockMutex); #endif #endif /* Monitor RX overrun status. This should never happen unless (possibly) the internal bus is behing held up by something. Unless your system is running at a very low clock speed or there are possibilities that the internal buses may be held up for a long time, this can probably safely be removed. */ if (LPC_EMAC->IntStatus & EMAC_INT_RX_OVERRUN) { LINK_STATS_INC(link.err); LINK_STATS_INC(link.drop); /* Temporarily disable RX */ LPC_EMAC->MAC1 &= ~EMAC_MAC1_REC_EN; /* Reset the RX side */ LPC_EMAC->MAC1 |= EMAC_MAC1_RES_RX; LPC_EMAC->IntClear = EMAC_INT_RX_OVERRUN; /* De-allocate all queued RX pbufs */ for (idx = 0; idx < LPC_NUM_BUFF_RXDESCS; idx++) { if (lpc_enetif->rxb[idx] != NULL) { pbuf_free(lpc_enetif->rxb[idx]); lpc_enetif->rxb[idx] = NULL; } } /* Start RX side again */ lpc_rx_setup(lpc_enetif); /* Re-enable RX */ LPC_EMAC->MAC1 |= EMAC_MAC1_REC_EN; #ifdef LOCK_RX_THREAD #if NO_SYS == 0 sys_mutex_unlock(&lpc_enetif->TXLockMutex); #endif #endif return NULL; } /* Determine if a frame has been received */ length = 0; idx = LPC_EMAC->RxConsumeIndex; if (LPC_EMAC->RxProduceIndex != idx) { /* Handle errors */ if (lpc_enetif->prxs[idx].statusinfo & (EMAC_RINFO_CRC_ERR | EMAC_RINFO_SYM_ERR | EMAC_RINFO_ALIGN_ERR | EMAC_RINFO_LEN_ERR)) { #if LINK_STATS if (lpc_enetif->prxs[idx].statusinfo & (EMAC_RINFO_CRC_ERR | EMAC_RINFO_SYM_ERR | EMAC_RINFO_ALIGN_ERR)) LINK_STATS_INC(link.chkerr); if (lpc_enetif->prxs[idx].statusinfo & EMAC_RINFO_LEN_ERR) LINK_STATS_INC(link.lenerr); #endif /* Drop the frame */ LINK_STATS_INC(link.drop); /* Re-queue the pbuf for receive */ lpc_enetif->rx_free_descs++; p = lpc_enetif->rxb[idx]; lpc_enetif->rxb[idx] = NULL; lpc_rxqueue_pbuf(lpc_enetif, p); LWIP_DEBUGF(UDP_LPC_EMAC | LWIP_DBG_TRACE, ("lpc_low_level_input: Packet dropped with errors (0x%x)\n", lpc_enetif->prxs[idx].statusinfo)); p = NULL; } else { /* A packet is waiting, get length */ length = (lpc_enetif->prxs[idx].statusinfo & 0x7FF) + 1; /* Zero-copy */ p = lpc_enetif->rxb[idx]; origLength = p->len; p->len = (u16_t) length; /* Free pbuf from descriptor */ lpc_enetif->rxb[idx] = NULL; lpc_enetif->rx_free_descs++; /* Attempt to queue new buffer(s) */ if (lpc_rx_queue(lpc_enetif->netif) == 0) { /* Drop the frame due to OOM. */ LINK_STATS_INC(link.drop); /* Re-queue the pbuf for receive */ p->len = origLength; lpc_rxqueue_pbuf(lpc_enetif, p); LWIP_DEBUGF(UDP_LPC_EMAC | LWIP_DBG_TRACE, ("lpc_low_level_input: Packet index %d dropped for OOM\n", idx)); #ifdef LOCK_RX_THREAD #if NO_SYS == 0 sys_mutex_unlock(&lpc_enetif->TXLockMutex); #endif #endif return NULL; } LWIP_DEBUGF(UDP_LPC_EMAC | LWIP_DBG_TRACE, ("lpc_low_level_input: Packet received: %p, size %d (index=%d)\n", p, length, idx)); /* Save size */ p->tot_len = (u16_t) length; LINK_STATS_INC(link.recv); } } #ifdef LOCK_RX_THREAD #if NO_SYS == 0 sys_mutex_unlock(&lpc_enetif->TXLockMutex); #endif #endif return p; } /** \brief Attempt to read a packet from the EMAC interface. * * \param[in] netif the lwip network interface structure for this lpc_enetif */ void lpc_enetif_input(struct netif *netif) { struct eth_hdr *ethhdr; struct pbuf *p; /* move received packet into a new pbuf */ p = lpc_low_level_input(netif); if (p == NULL) return; /* points to packet payload, which starts with an Ethernet header */ ethhdr = p->payload; switch (htons(ethhdr->type)) { case ETHTYPE_IP: case ETHTYPE_ARP: #if PPPOE_SUPPORT case ETHTYPE_PPPOEDISC: case ETHTYPE_PPPOE: #endif /* PPPOE_SUPPORT */ /* full packet send to tcpip_thread to process */ if (netif->input(p, netif) != ERR_OK) { LWIP_DEBUGF(NETIF_DEBUG, ("lpc_enetif_input: IP input error\n")); /* Free buffer */ pbuf_free(p); } break; default: /* Return buffer */ pbuf_free(p); break; } } /** \brief Determine if the passed address is usable for the ethernet * DMA controller. * * \param[in] addr Address of packet to check for DMA safe operation * \return 1 if the packet address is not safe, otherwise 0 */ static s32_t lpc_packet_addr_notsafe(void *addr) { /* Check for legal address ranges */ #if defined(TARGET_LPC1768) if ((((u32_t) addr >= 0x2007C000) && ((u32_t) addr < 0x20083FFF))) { #elif defined(TARGET_LPC4088) || defined(TARGET_LPC4088_DM) if ((((u32_t) addr >= 0x20000000) && ((u32_t) addr < 0x20007FFF))) { #endif return 0; } return 1; } /** \brief Sets up the TX descriptor ring buffers. * * This function sets up the descriptor list used for transmit packets. * * \param[in] lpc_enetif Pointer to driver data structure */ static err_t lpc_tx_setup(struct lpc_enetdata *lpc_enetif) { s32_t idx; /* Build TX descriptors for local buffers */ for (idx = 0; idx < LPC_NUM_BUFF_TXDESCS; idx++) { lpc_enetif->ptxd[idx].control = 0; lpc_enetif->ptxs[idx].statusinfo = 0xFFFFFFFF; } /* Setup pointers to TX structures */ LPC_EMAC->TxDescriptor = (u32_t) &lpc_enetif->ptxd[0]; LPC_EMAC->TxStatus = (u32_t) &lpc_enetif->ptxs[0]; LPC_EMAC->TxDescriptorNumber = LPC_NUM_BUFF_TXDESCS - 1; lpc_enetif->lpc_last_tx_idx = 0; return ERR_OK; } /** \brief Free TX buffers that are complete * * \param[in] lpc_enetif Pointer to driver data structure * \param[in] cidx EMAC current descriptor comsumer index */ static void lpc_tx_reclaim_st(struct lpc_enetdata *lpc_enetif, u32_t cidx) { #if NO_SYS == 0 /* Get exclusive access */ sys_mutex_lock(&lpc_enetif->TXLockMutex); #endif while (cidx != lpc_enetif->lpc_last_tx_idx) { if (lpc_enetif->txb[lpc_enetif->lpc_last_tx_idx] != NULL) { LWIP_DEBUGF(UDP_LPC_EMAC | LWIP_DBG_TRACE, ("lpc_tx_reclaim_st: Freeing packet %p (index %d)\n", lpc_enetif->txb[lpc_enetif->lpc_last_tx_idx], lpc_enetif->lpc_last_tx_idx)); pbuf_free(lpc_enetif->txb[lpc_enetif->lpc_last_tx_idx]); lpc_enetif->txb[lpc_enetif->lpc_last_tx_idx] = NULL; } #if NO_SYS == 0 osSemaphoreRelease(lpc_enetif->xTXDCountSem.id); #endif lpc_enetif->lpc_last_tx_idx++; if (lpc_enetif->lpc_last_tx_idx >= LPC_NUM_BUFF_TXDESCS) lpc_enetif->lpc_last_tx_idx = 0; } #if NO_SYS == 0 /* Restore access */ sys_mutex_unlock(&lpc_enetif->TXLockMutex); #endif } /** \brief User call for freeingTX buffers that are complete * * \param[in] netif the lwip network interface structure for this lpc_enetif */ void lpc_tx_reclaim(struct netif *netif) { lpc_tx_reclaim_st((struct lpc_enetdata *) netif->state, LPC_EMAC->TxConsumeIndex); } /** \brief Polls if an available TX descriptor is ready. Can be used to * determine if the low level transmit function will block. * * \param[in] netif the lwip network interface structure for this lpc_enetif * \return 0 if no descriptors are read, or >0 */ s32_t lpc_tx_ready(struct netif *netif) { s32_t fb; u32_t idx, cidx; cidx = LPC_EMAC->TxConsumeIndex; idx = LPC_EMAC->TxProduceIndex; /* Determine number of free buffers */ if (idx == cidx) fb = LPC_NUM_BUFF_TXDESCS; else if (cidx > idx) fb = (LPC_NUM_BUFF_TXDESCS - 1) - ((idx + LPC_NUM_BUFF_TXDESCS) - cidx); else fb = (LPC_NUM_BUFF_TXDESCS - 1) - (cidx - idx); return fb; } /** \brief Low level output of a packet. Never call this from an * interrupt context, as it may block until TX descriptors * become available. * * \param[in] netif the lwip network interface structure for this lpc_enetif * \param[in] p the MAC packet to send (e.g. IP packet including MAC addresses and type) * \return ERR_OK if the packet could be sent or an err_t value if the packet couldn't be sent */ static err_t lpc_low_level_output(struct netif *netif, struct pbuf *p) { struct lpc_enetdata *lpc_enetif = netif->state; struct pbuf *q; u8_t *dst; u32_t idx, notdmasafe = 0; struct pbuf *np; s32_t dn; /* Zero-copy TX buffers may be fragmented across mutliple payload chains. Determine the number of descriptors needed for the transfer. The pbuf chaining can be a mess! */ dn = (s32_t) pbuf_clen(p); /* Test to make sure packet addresses are DMA safe. A DMA safe address is once that uses external memory or periphheral RAM. IRAM and FLASH are not safe! */ for (q = p; q != NULL; q = q->next) notdmasafe += lpc_packet_addr_notsafe(q->payload); #if LPC_TX_PBUF_BOUNCE_EN==1 /* If the pbuf is not DMA safe, a new bounce buffer (pbuf) will be created that will be used instead. This requires an copy from the non-safe DMA region to the new pbuf */ if (notdmasafe) { /* Allocate a pbuf in DMA memory */ np = pbuf_alloc(PBUF_RAW, p->tot_len, PBUF_RAM); if (np == NULL) return ERR_MEM; /* This buffer better be contiguous! */ LWIP_ASSERT("lpc_low_level_output: New transmit pbuf is chained", (pbuf_clen(np) == 1)); /* Copy to DMA safe pbuf */ dst = (u8_t *) np->payload; for(q = p; q != NULL; q = q->next) { /* Copy the buffer to the descriptor's buffer */ MEMCPY(dst, (u8_t *) q->payload, q->len); dst += q->len; } np->len = p->tot_len; LWIP_DEBUGF(UDP_LPC_EMAC | LWIP_DBG_TRACE, ("lpc_low_level_output: Switched to DMA safe buffer, old=%p, new=%p\n", q, np)); /* use the new buffer for descrptor queueing. The original pbuf will be de-allocated outsuide this driver. */ p = np; dn = 1; } #else if (notdmasafe) LWIP_ASSERT("lpc_low_level_output: Not a DMA safe pbuf", (notdmasafe == 0)); #endif /* Wait until enough descriptors are available for the transfer. */ /* THIS WILL BLOCK UNTIL THERE ARE ENOUGH DESCRIPTORS AVAILABLE */ while (dn > lpc_tx_ready(netif)) #if NO_SYS == 0 osSemaphoreWait(lpc_enetif->xTXDCountSem.id, osWaitForever); #else osDelay(1); #endif /* Get free TX buffer index */ idx = LPC_EMAC->TxProduceIndex; #if NO_SYS == 0 /* Get exclusive access */ sys_mutex_lock(&lpc_enetif->TXLockMutex); #endif /* Prevent LWIP from de-allocating this pbuf. The driver will free it once it's been transmitted. */ if (!notdmasafe) pbuf_ref(p); /* Setup transfers */ q = p; while (dn > 0) { dn--; /* Only save pointer to free on last descriptor */ if (dn == 0) { /* Save size of packet and signal it's ready */ lpc_enetif->ptxd[idx].control = (q->len - 1) | EMAC_TCTRL_INT | EMAC_TCTRL_LAST; lpc_enetif->txb[idx] = p; } else { /* Save size of packet, descriptor is not last */ lpc_enetif->ptxd[idx].control = (q->len - 1) | EMAC_TCTRL_INT; lpc_enetif->txb[idx] = NULL; } LWIP_DEBUGF(UDP_LPC_EMAC | LWIP_DBG_TRACE, ("lpc_low_level_output: pbuf packet(%p) sent, chain#=%d," " size = %d (index=%d)\n", q->payload, dn, q->len, idx)); lpc_enetif->ptxd[idx].packet = (u32_t) q->payload; q = q->next; idx++; if (idx >= LPC_NUM_BUFF_TXDESCS) idx = 0; } LPC_EMAC->TxProduceIndex = idx; LINK_STATS_INC(link.xmit); #if NO_SYS == 0 /* Restore access */ sys_mutex_unlock(&lpc_enetif->TXLockMutex); #endif return ERR_OK; } /** \brief LPC EMAC interrupt handler. * * This function handles the transmit, receive, and error interrupt of * the LPC177x_8x. This is meant to be used when NO_SYS=0. */ void ENET_IRQHandler(void) { #if NO_SYS == 1 /* Interrupts are not used without an RTOS */ NVIC_DisableIRQ(ENET_IRQn); #else uint32_t ints; /* Interrupts are of 2 groups - transmit or receive. Based on the interrupt, kick off the receive or transmit (cleanup) task */ /* Get pending interrupts */ ints = LPC_EMAC->IntStatus; if (ints & RXINTGROUP) { /* RX group interrupt(s): Give signal to wakeup RX receive task.*/ osSignalSet(lpc_enetdata.RxThread->id, RX_SIGNAL); } if (ints & TXINTGROUP) { /* TX group interrupt(s): Give semaphore to wakeup TX cleanup task. */ sys_sem_signal(&lpc_enetdata.TxCleanSem); } /* Clear pending interrupts */ LPC_EMAC->IntClear = ints; #endif } #if NO_SYS == 0 /** \brief Packet reception task * * This task is called when a packet is received. It will * pass the packet to the LWIP core. * * \param[in] pvParameters Not used yet */ static void packet_rx(void* pvParameters) { struct lpc_enetdata *lpc_enetif = pvParameters; while (1) { /* Wait for receive task to wakeup */ osSignalWait(RX_SIGNAL, osWaitForever); /* Process packets until all empty */ while (LPC_EMAC->RxConsumeIndex != LPC_EMAC->RxProduceIndex) lpc_enetif_input(lpc_enetif->netif); } } /** \brief Transmit cleanup task * * This task is called when a transmit interrupt occurs and * reclaims the pbuf and descriptor used for the packet once * the packet has been transferred. * * \param[in] pvParameters Not used yet */ static void packet_tx(void* pvParameters) { struct lpc_enetdata *lpc_enetif = pvParameters; s32_t idx; while (1) { /* Wait for transmit cleanup task to wakeup */ sys_arch_sem_wait(&lpc_enetif->TxCleanSem, 0); /* Error handling for TX underruns. This should never happen unless something is holding the bus or the clocks are going too slow. It can probably be safely removed. */ if (LPC_EMAC->IntStatus & EMAC_INT_TX_UNDERRUN) { LINK_STATS_INC(link.err); LINK_STATS_INC(link.drop); #if NO_SYS == 0 /* Get exclusive access */ sys_mutex_lock(&lpc_enetif->TXLockMutex); #endif /* Reset the TX side */ LPC_EMAC->MAC1 |= EMAC_MAC1_RES_TX; LPC_EMAC->IntClear = EMAC_INT_TX_UNDERRUN; /* De-allocate all queued TX pbufs */ for (idx = 0; idx < LPC_NUM_BUFF_TXDESCS; idx++) { if (lpc_enetif->txb[idx] != NULL) { pbuf_free(lpc_enetif->txb[idx]); lpc_enetif->txb[idx] = NULL; } } #if NO_SYS == 0 /* Restore access */ sys_mutex_unlock(&lpc_enetif->TXLockMutex); #endif /* Start TX side again */ lpc_tx_setup(lpc_enetif); } else { /* Free TX buffers that are done sending */ lpc_tx_reclaim(lpc_enetdata.netif); } } } #endif /** \brief Low level init of the MAC and PHY. * * \param[in] netif Pointer to LWIP netif structure */ static err_t low_level_init(struct netif *netif) { struct lpc_enetdata *lpc_enetif = netif->state; err_t err = ERR_OK; /* Enable MII clocking */ LPC_SC->PCONP |= CLKPWR_PCONP_PCENET; #if defined(TARGET_LPC1768) LPC_PINCON->PINSEL2 = 0x50150105; /* Enable P1 Ethernet Pins. */ LPC_PINCON->PINSEL3 = (LPC_PINCON->PINSEL3 & ~0x0000000F) | 0x00000005; #elif defined(TARGET_LPC4088) || defined(TARGET_LPC4088_DM) LPC_IOCON->P1_0 &= ~0x07; /* ENET I/O config */ LPC_IOCON->P1_0 |= 0x01; /* ENET_TXD0 */ LPC_IOCON->P1_1 &= ~0x07; LPC_IOCON->P1_1 |= 0x01; /* ENET_TXD1 */ LPC_IOCON->P1_4 &= ~0x07; LPC_IOCON->P1_4 |= 0x01; /* ENET_TXEN */ LPC_IOCON->P1_8 &= ~0x07; LPC_IOCON->P1_8 |= 0x01; /* ENET_CRS */ LPC_IOCON->P1_9 &= ~0x07; LPC_IOCON->P1_9 |= 0x01; /* ENET_RXD0 */ LPC_IOCON->P1_10 &= ~0x07; LPC_IOCON->P1_10 |= 0x01; /* ENET_RXD1 */ LPC_IOCON->P1_14 &= ~0x07; LPC_IOCON->P1_14 |= 0x01; /* ENET_RX_ER */ LPC_IOCON->P1_15 &= ~0x07; LPC_IOCON->P1_15 |= 0x01; /* ENET_REF_CLK */ LPC_IOCON->P1_16 &= ~0x07; /* ENET/PHY I/O config */ LPC_IOCON->P1_16 |= 0x01; /* ENET_MDC */ LPC_IOCON->P1_17 &= ~0x07; LPC_IOCON->P1_17 |= 0x01; /* ENET_MDIO */ #endif /* Reset all MAC logic */ LPC_EMAC->MAC1 = EMAC_MAC1_RES_TX | EMAC_MAC1_RES_MCS_TX | EMAC_MAC1_RES_RX | EMAC_MAC1_RES_MCS_RX | EMAC_MAC1_SIM_RES | EMAC_MAC1_SOFT_RES; LPC_EMAC->Command = EMAC_CR_REG_RES | EMAC_CR_TX_RES | EMAC_CR_RX_RES | EMAC_CR_PASS_RUNT_FRM; osDelay(10); /* Initial MAC initialization */ LPC_EMAC->MAC1 = EMAC_MAC1_PASS_ALL; LPC_EMAC->MAC2 = EMAC_MAC2_CRC_EN | EMAC_MAC2_PAD_EN | EMAC_MAC2_VLAN_PAD_EN; LPC_EMAC->MAXF = EMAC_ETH_MAX_FLEN; /* Set RMII management clock rate to lowest speed */ LPC_EMAC->MCFG = EMAC_MCFG_CLK_SEL(11) | EMAC_MCFG_RES_MII; LPC_EMAC->MCFG &= ~EMAC_MCFG_RES_MII; /* Maximum number of retries, 0x37 collision window, gap */ LPC_EMAC->CLRT = EMAC_CLRT_DEF; LPC_EMAC->IPGR = EMAC_IPGR_P1_DEF | EMAC_IPGR_P2_DEF; #if LPC_EMAC_RMII /* RMII setup */ LPC_EMAC->Command = EMAC_CR_PASS_RUNT_FRM | EMAC_CR_RMII; #else /* MII setup */ LPC_EMAC->CR = EMAC_CR_PASS_RUNT_FRM; #endif /* Initialize the PHY and reset */ err = lpc_phy_init(netif, LPC_EMAC_RMII); if (err != ERR_OK) return err; /* Save station address */ LPC_EMAC->SA2 = (u32_t) netif->hwaddr[0] | (((u32_t) netif->hwaddr[1]) << 8); LPC_EMAC->SA1 = (u32_t) netif->hwaddr[2] | (((u32_t) netif->hwaddr[3]) << 8); LPC_EMAC->SA0 = (u32_t) netif->hwaddr[4] | (((u32_t) netif->hwaddr[5]) << 8); /* Setup transmit and receive descriptors */ if (lpc_tx_setup(lpc_enetif) != ERR_OK) return ERR_BUF; if (lpc_rx_setup(lpc_enetif) != ERR_OK) return ERR_BUF; /* Enable packet reception */ #if IP_SOF_BROADCAST_RECV LPC_EMAC->RxFilterCtrl = EMAC_RFC_PERFECT_EN | EMAC_RFC_BCAST_EN | EMAC_RFC_MCAST_EN; #else LPC_EMAC->RxFilterCtrl = EMAC_RFC_PERFECT_EN; #endif /* Clear and enable rx/tx interrupts */ LPC_EMAC->IntClear = 0xFFFF; LPC_EMAC->IntEnable = RXINTGROUP | TXINTGROUP; /* Enable RX and TX */ LPC_EMAC->Command |= EMAC_CR_RX_EN | EMAC_CR_TX_EN; LPC_EMAC->MAC1 |= EMAC_MAC1_REC_EN; return err; } /* This function provides a method for the PHY to setup the EMAC for the PHY negotiated duplex mode */ void lpc_emac_set_duplex(int full_duplex) { if (full_duplex) { LPC_EMAC->MAC2 |= EMAC_MAC2_FULL_DUP; LPC_EMAC->Command |= EMAC_CR_FULL_DUP; LPC_EMAC->IPGT = EMAC_IPGT_FULL_DUP; } else { LPC_EMAC->MAC2 &= ~EMAC_MAC2_FULL_DUP; LPC_EMAC->Command &= ~EMAC_CR_FULL_DUP; LPC_EMAC->IPGT = EMAC_IPGT_HALF_DUP; } } /* This function provides a method for the PHY to setup the EMAC for the PHY negotiated bit rate */ void lpc_emac_set_speed(int mbs_100) { if (mbs_100) LPC_EMAC->SUPP = EMAC_SUPP_SPEED; else LPC_EMAC->SUPP = 0; } /** * This function is the ethernet packet send function. It calls * etharp_output after checking link status. * * \param[in] netif the lwip network interface structure for this lpc_enetif * \param[in] q Pointer to pbug to send * \param[in] ipaddr IP address * \return ERR_OK or error code */ err_t lpc_etharp_output(struct netif *netif, struct pbuf *q, ip_addr_t *ipaddr) { /* Only send packet is link is up */ if (netif->flags & NETIF_FLAG_LINK_UP) return etharp_output(netif, q, ipaddr); return ERR_CONN; } #if NO_SYS == 0 /* periodic PHY status update */ void phy_update(void const *nif) { lpc_phy_sts_sm((struct netif*)nif); } osTimerDef(phy_update, phy_update); #endif /** * Should be called at the beginning of the program to set up the * network interface. * * This function should be passed as a parameter to netif_add(). * * @param[in] netif the lwip network interface structure for this lpc_enetif * @return ERR_OK if the loopif is initialized * ERR_MEM if private data couldn't be allocated * any other err_t on error */ err_t eth_arch_enetif_init(struct netif *netif) { err_t err; LWIP_ASSERT("netif != NULL", (netif != NULL)); lpc_enetdata.netif = netif; /* set MAC hardware address */ #if (MBED_MAC_ADDRESS_SUM != MBED_MAC_ADDR_INTERFACE) netif->hwaddr[0] = MBED_MAC_ADDR_0; netif->hwaddr[1] = MBED_MAC_ADDR_1; netif->hwaddr[2] = MBED_MAC_ADDR_2; netif->hwaddr[3] = MBED_MAC_ADDR_3; netif->hwaddr[4] = MBED_MAC_ADDR_4; netif->hwaddr[5] = MBED_MAC_ADDR_5; #else mbed_mac_address((char *)netif->hwaddr); #endif netif->hwaddr_len = ETHARP_HWADDR_LEN; /* maximum transfer unit */ netif->mtu = 1500; /* device capabilities */ netif->flags = NETIF_FLAG_BROADCAST | NETIF_FLAG_ETHARP | NETIF_FLAG_ETHERNET | NETIF_FLAG_IGMP; /* Initialize the hardware */ netif->state = &lpc_enetdata; err = low_level_init(netif); if (err != ERR_OK) return err; #if LWIP_NETIF_HOSTNAME /* Initialize interface hostname */ netif->hostname = "lwiplpc"; #endif /* LWIP_NETIF_HOSTNAME */ netif->name[0] = 'e'; netif->name[1] = 'n'; netif->output = lpc_etharp_output; netif->linkoutput = lpc_low_level_output; /* CMSIS-RTOS, start tasks */ #if NO_SYS == 0 #ifdef CMSIS_OS_RTX memset(lpc_enetdata.xTXDCountSem.data, 0, sizeof(lpc_enetdata.xTXDCountSem.data)); lpc_enetdata.xTXDCountSem.def.semaphore = lpc_enetdata.xTXDCountSem.data; #endif lpc_enetdata.xTXDCountSem.id = osSemaphoreCreate(&lpc_enetdata.xTXDCountSem.def, LPC_NUM_BUFF_TXDESCS); LWIP_ASSERT("xTXDCountSem creation error", (lpc_enetdata.xTXDCountSem.id != NULL)); err = sys_mutex_new(&lpc_enetdata.TXLockMutex); LWIP_ASSERT("TXLockMutex creation error", (err == ERR_OK)); /* Packet receive task */ lpc_enetdata.RxThread = sys_thread_new("receive_thread", packet_rx, netif->state, DEFAULT_THREAD_STACKSIZE, RX_PRIORITY); LWIP_ASSERT("RxThread creation error", (lpc_enetdata.RxThread)); /* Transmit cleanup task */ err = sys_sem_new(&lpc_enetdata.TxCleanSem, 0); LWIP_ASSERT("TxCleanSem creation error", (err == ERR_OK)); sys_thread_new("txclean_thread", packet_tx, netif->state, DEFAULT_THREAD_STACKSIZE, TX_PRIORITY); /* periodic PHY status update */ osTimerId phy_timer = osTimerCreate(osTimer(phy_update), osTimerPeriodic, (void *)netif); osTimerStart(phy_timer, 250); #endif return ERR_OK; } void eth_arch_enable_interrupts(void) { NVIC_SetPriority(ENET_IRQn, ((0x01 << 3) | 0x01)); NVIC_EnableIRQ(ENET_IRQn); } void eth_arch_disable_interrupts(void) { NVIC_DisableIRQ(ENET_IRQn); } /** * @} */ /* --------------------------------- End Of File ------------------------------ */ ================================================ FILE: Zelig/lwip/lwip-eth/arch/TARGET_NXP/lpc17xx_emac.h ================================================ /********************************************************************** * $Id$ lpc17xx_emac.h 2010-05-21 *//** * @file lpc17xx_emac.h * @brief Contains all macro definitions and function prototypes * support for Ethernet MAC firmware library on LPC17xx * @version 2.0 * @date 21. May. 2010 * @author NXP MCU SW Application Team * * Copyright(C) 2010, NXP Semiconductor * All rights reserved. * *********************************************************************** * Software that is described herein is for illustrative purposes only * which provides customers with programming information regarding the * products. This software is supplied "AS IS" without any warranties. * NXP Semiconductors assumes no responsibility or liability for the * use of the software, conveys no license or title under any patent, * copyright, or mask work right to the product. NXP Semiconductors * reserves the right to make changes in the software without * notification. NXP Semiconductors also make no representation or * warranty that such application will be suitable for the specified * use without further testing or modification. **********************************************************************/ /* Peripheral group ----------------------------------------------------------- */ /** @defgroup EMAC EMAC (Ethernet Media Access Controller) * @ingroup LPC1700CMSIS_FwLib_Drivers * @{ */ #ifndef LPC17XX_EMAC_H_ #define LPC17XX_EMAC_H_ /* Includes ------------------------------------------------------------------- */ #include "cmsis.h" #ifdef __cplusplus extern "C" { #endif #define MCB_LPC_1768 //#define IAR_LPC_1768 /* Public Macros -------------------------------------------------------------- */ /** @defgroup EMAC_Public_Macros EMAC Public Macros * @{ */ /* EMAC PHY status type definitions */ #define EMAC_PHY_STAT_LINK (0) /**< Link Status */ #define EMAC_PHY_STAT_SPEED (1) /**< Speed Status */ #define EMAC_PHY_STAT_DUP (2) /**< Duplex Status */ /* EMAC PHY device Speed definitions */ #define EMAC_MODE_AUTO (0) /**< Auto-negotiation mode */ #define EMAC_MODE_10M_FULL (1) /**< 10Mbps FullDuplex mode */ #define EMAC_MODE_10M_HALF (2) /**< 10Mbps HalfDuplex mode */ #define EMAC_MODE_100M_FULL (3) /**< 100Mbps FullDuplex mode */ #define EMAC_MODE_100M_HALF (4) /**< 100Mbps HalfDuplex mode */ /** * @} */ /* Private Macros ------------------------------------------------------------- */ /** @defgroup EMAC_Private_Macros EMAC Private Macros * @{ */ /* EMAC Memory Buffer configuration for 16K Ethernet RAM */ #define EMAC_NUM_RX_FRAG 4 /**< Num.of RX Fragments 4*1536= 6.0kB */ #define EMAC_NUM_TX_FRAG 3 /**< Num.of TX Fragments 3*1536= 4.6kB */ #define EMAC_ETH_MAX_FLEN 1536 /**< Max. Ethernet Frame Size */ #define EMAC_TX_FRAME_TOUT 0x00100000 /**< Frame Transmit timeout count */ /* --------------------- BIT DEFINITIONS -------------------------------------- */ /*********************************************************************//** * Macro defines for MAC Configuration Register 1 **********************************************************************/ #define EMAC_MAC1_REC_EN 0x00000001 /**< Receive Enable */ #define EMAC_MAC1_PASS_ALL 0x00000002 /**< Pass All Receive Frames */ #define EMAC_MAC1_RX_FLOWC 0x00000004 /**< RX Flow Control */ #define EMAC_MAC1_TX_FLOWC 0x00000008 /**< TX Flow Control */ #define EMAC_MAC1_LOOPB 0x00000010 /**< Loop Back Mode */ #define EMAC_MAC1_RES_TX 0x00000100 /**< Reset TX Logic */ #define EMAC_MAC1_RES_MCS_TX 0x00000200 /**< Reset MAC TX Control Sublayer */ #define EMAC_MAC1_RES_RX 0x00000400 /**< Reset RX Logic */ #define EMAC_MAC1_RES_MCS_RX 0x00000800 /**< Reset MAC RX Control Sublayer */ #define EMAC_MAC1_SIM_RES 0x00004000 /**< Simulation Reset */ #define EMAC_MAC1_SOFT_RES 0x00008000 /**< Soft Reset MAC */ /*********************************************************************//** * Macro defines for MAC Configuration Register 2 **********************************************************************/ #define EMAC_MAC2_FULL_DUP 0x00000001 /**< Full-Duplex Mode */ #define EMAC_MAC2_FRM_LEN_CHK 0x00000002 /**< Frame Length Checking */ #define EMAC_MAC2_HUGE_FRM_EN 0x00000004 /**< Huge Frame Enable */ #define EMAC_MAC2_DLY_CRC 0x00000008 /**< Delayed CRC Mode */ #define EMAC_MAC2_CRC_EN 0x00000010 /**< Append CRC to every Frame */ #define EMAC_MAC2_PAD_EN 0x00000020 /**< Pad all Short Frames */ #define EMAC_MAC2_VLAN_PAD_EN 0x00000040 /**< VLAN Pad Enable */ #define EMAC_MAC2_ADET_PAD_EN 0x00000080 /**< Auto Detect Pad Enable */ #define EMAC_MAC2_PPREAM_ENF 0x00000100 /**< Pure Preamble Enforcement */ #define EMAC_MAC2_LPREAM_ENF 0x00000200 /**< Long Preamble Enforcement */ #define EMAC_MAC2_NO_BACKOFF 0x00001000 /**< No Backoff Algorithm */ #define EMAC_MAC2_BACK_PRESSURE 0x00002000 /**< Backoff Presurre / No Backoff */ #define EMAC_MAC2_EXCESS_DEF 0x00004000 /**< Excess Defer */ /*********************************************************************//** * Macro defines for Back-to-Back Inter-Packet-Gap Register **********************************************************************/ /** Programmable field representing the nibble time offset of the minimum possible period * between the end of any transmitted packet to the beginning of the next */ #define EMAC_IPGT_BBIPG(n) (n&0x7F) /** Recommended value for Full Duplex of Programmable field representing the nibble time * offset of the minimum possible period between the end of any transmitted packet to the * beginning of the next */ #define EMAC_IPGT_FULL_DUP (EMAC_IPGT_BBIPG(0x15)) /** Recommended value for Half Duplex of Programmable field representing the nibble time * offset of the minimum possible period between the end of any transmitted packet to the * beginning of the next */ #define EMAC_IPGT_HALF_DUP (EMAC_IPGT_BBIPG(0x12)) /*********************************************************************//** * Macro defines for Non Back-to-Back Inter-Packet-Gap Register **********************************************************************/ /** Programmable field representing the Non-Back-to-Back Inter-Packet-Gap */ #define EMAC_IPGR_NBBIPG_P2(n) (n&0x7F) /** Recommended value for Programmable field representing the Non-Back-to-Back Inter-Packet-Gap Part 1 */ #define EMAC_IPGR_P2_DEF (EMAC_IPGR_NBBIPG_P2(0x12)) /** Programmable field representing the optional carrierSense window referenced in * IEEE 802.3/4.2.3.2.1 'Carrier Deference' */ #define EMAC_IPGR_NBBIPG_P1(n) ((n&0x7F)<<8) /** Recommended value for Programmable field representing the Non-Back-to-Back Inter-Packet-Gap Part 2 */ #define EMAC_IPGR_P1_DEF EMAC_IPGR_NBBIPG_P1(0x0C) /*********************************************************************//** * Macro defines for Collision Window/Retry Register **********************************************************************/ /** Programmable field specifying the number of retransmission attempts following a collision before * aborting the packet due to excessive collisions */ #define EMAC_CLRT_MAX_RETX(n) (n&0x0F) /** Programmable field representing the slot time or collision window during which collisions occur * in properly configured networks */ #define EMAC_CLRT_COLL(n) ((n&0x3F)<<8) /** Default value for Collision Window / Retry register */ #define EMAC_CLRT_DEF ((EMAC_CLRT_MAX_RETX(0x0F))|(EMAC_CLRT_COLL(0x37))) /*********************************************************************//** * Macro defines for Maximum Frame Register **********************************************************************/ /** Represents a maximum receive frame of 1536 octets */ #define EMAC_MAXF_MAXFRMLEN(n) (n&0xFFFF) /*********************************************************************//** * Macro defines for PHY Support Register **********************************************************************/ #define EMAC_SUPP_SPEED 0x00000100 /**< Reduced MII Logic Current Speed */ #define EMAC_SUPP_RES_RMII 0x00000800 /**< Reset Reduced MII Logic */ /*********************************************************************//** * Macro defines for Test Register **********************************************************************/ #define EMAC_TEST_SHCUT_PQUANTA 0x00000001 /**< Shortcut Pause Quanta */ #define EMAC_TEST_TST_PAUSE 0x00000002 /**< Test Pause */ #define EMAC_TEST_TST_BACKP 0x00000004 /**< Test Back Pressure */ /*********************************************************************//** * Macro defines for MII Management Configuration Register **********************************************************************/ #define EMAC_MCFG_SCAN_INC 0x00000001 /**< Scan Increment PHY Address */ #define EMAC_MCFG_SUPP_PREAM 0x00000002 /**< Suppress Preamble */ #define EMAC_MCFG_CLK_SEL(n) ((n&0x0F)<<2) /**< Clock Select Field */ #define EMAC_MCFG_RES_MII 0x00008000 /**< Reset MII Management Hardware */ #define EMAC_MCFG_MII_MAXCLK 2500000UL /**< MII Clock max */ /*********************************************************************//** * Macro defines for MII Management Command Register **********************************************************************/ #define EMAC_MCMD_READ 0x00000001 /**< MII Read */ #define EMAC_MCMD_SCAN 0x00000002 /**< MII Scan continuously */ #define EMAC_MII_WR_TOUT 0x00050000 /**< MII Write timeout count */ #define EMAC_MII_RD_TOUT 0x00050000 /**< MII Read timeout count */ /*********************************************************************//** * Macro defines for MII Management Address Register **********************************************************************/ #define EMAC_MADR_REG_ADR(n) (n&0x1F) /**< MII Register Address field */ #define EMAC_MADR_PHY_ADR(n) ((n&0x1F)<<8) /**< PHY Address Field */ /*********************************************************************//** * Macro defines for MII Management Write Data Register **********************************************************************/ #define EMAC_MWTD_DATA(n) (n&0xFFFF) /**< Data field for MMI Management Write Data register */ /*********************************************************************//** * Macro defines for MII Management Read Data Register **********************************************************************/ #define EMAC_MRDD_DATA(n) (n&0xFFFF) /**< Data field for MMI Management Read Data register */ /*********************************************************************//** * Macro defines for MII Management Indicators Register **********************************************************************/ #define EMAC_MIND_BUSY 0x00000001 /**< MII is Busy */ #define EMAC_MIND_SCAN 0x00000002 /**< MII Scanning in Progress */ #define EMAC_MIND_NOT_VAL 0x00000004 /**< MII Read Data not valid */ #define EMAC_MIND_MII_LINK_FAIL 0x00000008 /**< MII Link Failed */ /* Station Address 0 Register */ /* Station Address 1 Register */ /* Station Address 2 Register */ /* Control register definitions --------------------------------------------------------------------------- */ /*********************************************************************//** * Macro defines for Command Register **********************************************************************/ #define EMAC_CR_RX_EN 0x00000001 /**< Enable Receive */ #define EMAC_CR_TX_EN 0x00000002 /**< Enable Transmit */ #define EMAC_CR_REG_RES 0x00000008 /**< Reset Host Registers */ #define EMAC_CR_TX_RES 0x00000010 /**< Reset Transmit Datapath */ #define EMAC_CR_RX_RES 0x00000020 /**< Reset Receive Datapath */ #define EMAC_CR_PASS_RUNT_FRM 0x00000040 /**< Pass Runt Frames */ #define EMAC_CR_PASS_RX_FILT 0x00000080 /**< Pass RX Filter */ #define EMAC_CR_TX_FLOW_CTRL 0x00000100 /**< TX Flow Control */ #define EMAC_CR_RMII 0x00000200 /**< Reduced MII Interface */ #define EMAC_CR_FULL_DUP 0x00000400 /**< Full Duplex */ /*********************************************************************//** * Macro defines for Status Register **********************************************************************/ #define EMAC_SR_RX_EN 0x00000001 /**< Enable Receive */ #define EMAC_SR_TX_EN 0x00000002 /**< Enable Transmit */ /*********************************************************************//** * Macro defines for Transmit Status Vector 0 Register **********************************************************************/ #define EMAC_TSV0_CRC_ERR 0x00000001 /**< CRC error */ #define EMAC_TSV0_LEN_CHKERR 0x00000002 /**< Length Check Error */ #define EMAC_TSV0_LEN_OUTRNG 0x00000004 /**< Length Out of Range */ #define EMAC_TSV0_DONE 0x00000008 /**< Tramsmission Completed */ #define EMAC_TSV0_MCAST 0x00000010 /**< Multicast Destination */ #define EMAC_TSV0_BCAST 0x00000020 /**< Broadcast Destination */ #define EMAC_TSV0_PKT_DEFER 0x00000040 /**< Packet Deferred */ #define EMAC_TSV0_EXC_DEFER 0x00000080 /**< Excessive Packet Deferral */ #define EMAC_TSV0_EXC_COLL 0x00000100 /**< Excessive Collision */ #define EMAC_TSV0_LATE_COLL 0x00000200 /**< Late Collision Occured */ #define EMAC_TSV0_GIANT 0x00000400 /**< Giant Frame */ #define EMAC_TSV0_UNDERRUN 0x00000800 /**< Buffer Underrun */ #define EMAC_TSV0_BYTES 0x0FFFF000 /**< Total Bytes Transferred */ #define EMAC_TSV0_CTRL_FRAME 0x10000000 /**< Control Frame */ #define EMAC_TSV0_PAUSE 0x20000000 /**< Pause Frame */ #define EMAC_TSV0_BACK_PRESS 0x40000000 /**< Backpressure Method Applied */ #define EMAC_TSV0_VLAN 0x80000000 /**< VLAN Frame */ /*********************************************************************//** * Macro defines for Transmit Status Vector 1 Register **********************************************************************/ #define EMAC_TSV1_BYTE_CNT 0x0000FFFF /**< Transmit Byte Count */ #define EMAC_TSV1_COLL_CNT 0x000F0000 /**< Transmit Collision Count */ /*********************************************************************//** * Macro defines for Receive Status Vector Register **********************************************************************/ #define EMAC_RSV_BYTE_CNT 0x0000FFFF /**< Receive Byte Count */ #define EMAC_RSV_PKT_IGNORED 0x00010000 /**< Packet Previously Ignored */ #define EMAC_RSV_RXDV_SEEN 0x00020000 /**< RXDV Event Previously Seen */ #define EMAC_RSV_CARR_SEEN 0x00040000 /**< Carrier Event Previously Seen */ #define EMAC_RSV_REC_CODEV 0x00080000 /**< Receive Code Violation */ #define EMAC_RSV_CRC_ERR 0x00100000 /**< CRC Error */ #define EMAC_RSV_LEN_CHKERR 0x00200000 /**< Length Check Error */ #define EMAC_RSV_LEN_OUTRNG 0x00400000 /**< Length Out of Range */ #define EMAC_RSV_REC_OK 0x00800000 /**< Frame Received OK */ #define EMAC_RSV_MCAST 0x01000000 /**< Multicast Frame */ #define EMAC_RSV_BCAST 0x02000000 /**< Broadcast Frame */ #define EMAC_RSV_DRIB_NIBB 0x04000000 /**< Dribble Nibble */ #define EMAC_RSV_CTRL_FRAME 0x08000000 /**< Control Frame */ #define EMAC_RSV_PAUSE 0x10000000 /**< Pause Frame */ #define EMAC_RSV_UNSUPP_OPC 0x20000000 /**< Unsupported Opcode */ #define EMAC_RSV_VLAN 0x40000000 /**< VLAN Frame */ /*********************************************************************//** * Macro defines for Flow Control Counter Register **********************************************************************/ #define EMAC_FCC_MIRR_CNT(n) (n&0xFFFF) /**< Mirror Counter */ #define EMAC_FCC_PAUSE_TIM(n) ((n&0xFFFF)<<16) /**< Pause Timer */ /*********************************************************************//** * Macro defines for Flow Control Status Register **********************************************************************/ #define EMAC_FCS_MIRR_CNT(n) (n&0xFFFF) /**< Mirror Counter Current */ /* Receive filter register definitions -------------------------------------------------------- */ /*********************************************************************//** * Macro defines for Receive Filter Control Register **********************************************************************/ #define EMAC_RFC_UCAST_EN 0x00000001 /**< Accept Unicast Frames Enable */ #define EMAC_RFC_BCAST_EN 0x00000002 /**< Accept Broadcast Frames Enable */ #define EMAC_RFC_MCAST_EN 0x00000004 /**< Accept Multicast Frames Enable */ #define EMAC_RFC_UCAST_HASH_EN 0x00000008 /**< Accept Unicast Hash Filter Frames */ #define EMAC_RFC_MCAST_HASH_EN 0x00000010 /**< Accept Multicast Hash Filter Fram.*/ #define EMAC_RFC_PERFECT_EN 0x00000020 /**< Accept Perfect Match Enable */ #define EMAC_RFC_MAGP_WOL_EN 0x00001000 /**< Magic Packet Filter WoL Enable */ #define EMAC_RFC_PFILT_WOL_EN 0x00002000 /**< Perfect Filter WoL Enable */ /*********************************************************************//** * Macro defines for Receive Filter WoL Status/Clear Registers **********************************************************************/ #define EMAC_WOL_UCAST 0x00000001 /**< Unicast Frame caused WoL */ #define EMAC_WOL_BCAST 0x00000002 /**< Broadcast Frame caused WoL */ #define EMAC_WOL_MCAST 0x00000004 /**< Multicast Frame caused WoL */ #define EMAC_WOL_UCAST_HASH 0x00000008 /**< Unicast Hash Filter Frame WoL */ #define EMAC_WOL_MCAST_HASH 0x00000010 /**< Multicast Hash Filter Frame WoL */ #define EMAC_WOL_PERFECT 0x00000020 /**< Perfect Filter WoL */ #define EMAC_WOL_RX_FILTER 0x00000080 /**< RX Filter caused WoL */ #define EMAC_WOL_MAG_PACKET 0x00000100 /**< Magic Packet Filter caused WoL */ #define EMAC_WOL_BITMASK 0x01BF /**< Receive Filter WoL Status/Clear bitmasl value */ /* Module control register definitions ---------------------------------------------------- */ /*********************************************************************//** * Macro defines for Interrupt Status/Enable/Clear/Set Registers **********************************************************************/ #define EMAC_INT_RX_OVERRUN 0x00000001 /**< Overrun Error in RX Queue */ #define EMAC_INT_RX_ERR 0x00000002 /**< Receive Error */ #define EMAC_INT_RX_FIN 0x00000004 /**< RX Finished Process Descriptors */ #define EMAC_INT_RX_DONE 0x00000008 /**< Receive Done */ #define EMAC_INT_TX_UNDERRUN 0x00000010 /**< Transmit Underrun */ #define EMAC_INT_TX_ERR 0x00000020 /**< Transmit Error */ #define EMAC_INT_TX_FIN 0x00000040 /**< TX Finished Process Descriptors */ #define EMAC_INT_TX_DONE 0x00000080 /**< Transmit Done */ #define EMAC_INT_SOFT_INT 0x00001000 /**< Software Triggered Interrupt */ #define EMAC_INT_WAKEUP 0x00002000 /**< Wakeup Event Interrupt */ /*********************************************************************//** * Macro defines for Power Down Register **********************************************************************/ #define EMAC_PD_POWER_DOWN 0x80000000 /**< Power Down MAC */ /* Descriptor and status formats ---------------------------------------------------- */ /*********************************************************************//** * Macro defines for RX Descriptor Control Word **********************************************************************/ #define EMAC_RCTRL_SIZE(n) (n&0x7FF) /**< Buffer size field */ #define EMAC_RCTRL_INT 0x80000000 /**< Generate RxDone Interrupt */ /*********************************************************************//** * Macro defines for RX Status Hash CRC Word **********************************************************************/ #define EMAC_RHASH_SA 0x000001FF /**< Hash CRC for Source Address */ #define EMAC_RHASH_DA 0x001FF000 /**< Hash CRC for Destination Address */ /*********************************************************************//** * Macro defines for RX Status Information Word **********************************************************************/ #define EMAC_RINFO_SIZE 0x000007FF /**< Data size in bytes */ #define EMAC_RINFO_CTRL_FRAME 0x00040000 /**< Control Frame */ #define EMAC_RINFO_VLAN 0x00080000 /**< VLAN Frame */ #define EMAC_RINFO_FAIL_FILT 0x00100000 /**< RX Filter Failed */ #define EMAC_RINFO_MCAST 0x00200000 /**< Multicast Frame */ #define EMAC_RINFO_BCAST 0x00400000 /**< Broadcast Frame */ #define EMAC_RINFO_CRC_ERR 0x00800000 /**< CRC Error in Frame */ #define EMAC_RINFO_SYM_ERR 0x01000000 /**< Symbol Error from PHY */ #define EMAC_RINFO_LEN_ERR 0x02000000 /**< Length Error */ #define EMAC_RINFO_RANGE_ERR 0x04000000 /**< Range Error (exceeded max. size) */ #define EMAC_RINFO_ALIGN_ERR 0x08000000 /**< Alignment Error */ #define EMAC_RINFO_OVERRUN 0x10000000 /**< Receive overrun */ #define EMAC_RINFO_NO_DESCR 0x20000000 /**< No new Descriptor available */ #define EMAC_RINFO_LAST_FLAG 0x40000000 /**< Last Fragment in Frame */ #define EMAC_RINFO_ERR 0x80000000 /**< Error Occured (OR of all errors) */ #define EMAC_RINFO_ERR_MASK (EMAC_RINFO_FAIL_FILT | EMAC_RINFO_CRC_ERR | EMAC_RINFO_SYM_ERR | \ EMAC_RINFO_LEN_ERR | EMAC_RINFO_ALIGN_ERR | EMAC_RINFO_OVERRUN) /*********************************************************************//** * Macro defines for TX Descriptor Control Word **********************************************************************/ #define EMAC_TCTRL_SIZE 0x000007FF /**< Size of data buffer in bytes */ #define EMAC_TCTRL_OVERRIDE 0x04000000 /**< Override Default MAC Registers */ #define EMAC_TCTRL_HUGE 0x08000000 /**< Enable Huge Frame */ #define EMAC_TCTRL_PAD 0x10000000 /**< Pad short Frames to 64 bytes */ #define EMAC_TCTRL_CRC 0x20000000 /**< Append a hardware CRC to Frame */ #define EMAC_TCTRL_LAST 0x40000000 /**< Last Descriptor for TX Frame */ #define EMAC_TCTRL_INT 0x80000000 /**< Generate TxDone Interrupt */ /*********************************************************************//** * Macro defines for TX Status Information Word **********************************************************************/ #define EMAC_TINFO_COL_CNT 0x01E00000 /**< Collision Count */ #define EMAC_TINFO_DEFER 0x02000000 /**< Packet Deferred (not an error) */ #define EMAC_TINFO_EXCESS_DEF 0x04000000 /**< Excessive Deferral */ #define EMAC_TINFO_EXCESS_COL 0x08000000 /**< Excessive Collision */ #define EMAC_TINFO_LATE_COL 0x10000000 /**< Late Collision Occured */ #define EMAC_TINFO_UNDERRUN 0x20000000 /**< Transmit Underrun */ #define EMAC_TINFO_NO_DESCR 0x40000000 /**< No new Descriptor available */ #define EMAC_TINFO_ERR 0x80000000 /**< Error Occured (OR of all errors) */ #ifdef MCB_LPC_1768 /* DP83848C PHY definition ------------------------------------------------------------ */ /** PHY device reset time out definition */ #define EMAC_PHY_RESP_TOUT 0x100000UL /* ENET Device Revision ID */ #define EMAC_OLD_EMAC_MODULE_ID 0x39022000 /**< Rev. ID for first rev '-' */ /*********************************************************************//** * Macro defines for DP83848C PHY Registers **********************************************************************/ #define EMAC_PHY_REG_BMCR 0x00 /**< Basic Mode Control Register */ #define EMAC_PHY_REG_BMSR 0x01 /**< Basic Mode Status Register */ #define EMAC_PHY_REG_IDR1 0x02 /**< PHY Identifier 1 */ #define EMAC_PHY_REG_IDR2 0x03 /**< PHY Identifier 2 */ #define EMAC_PHY_REG_ANAR 0x04 /**< Auto-Negotiation Advertisement */ #define EMAC_PHY_REG_ANLPAR 0x05 /**< Auto-Neg. Link Partner Abitily */ #define EMAC_PHY_REG_ANER 0x06 /**< Auto-Neg. Expansion Register */ #define EMAC_PHY_REG_ANNPTR 0x07 /**< Auto-Neg. Next Page TX */ #define EMAC_PHY_REG_LPNPA 0x08 /*********************************************************************//** * Macro defines for PHY Extended Registers **********************************************************************/ #define EMAC_PHY_REG_STS 0x10 /**< Status Register */ #define EMAC_PHY_REG_MICR 0x11 /**< MII Interrupt Control Register */ #define EMAC_PHY_REG_MISR 0x12 /**< MII Interrupt Status Register */ #define EMAC_PHY_REG_FCSCR 0x14 /**< False Carrier Sense Counter */ #define EMAC_PHY_REG_RECR 0x15 /**< Receive Error Counter */ #define EMAC_PHY_REG_PCSR 0x16 /**< PCS Sublayer Config. and Status */ #define EMAC_PHY_REG_RBR 0x17 /**< RMII and Bypass Register */ #define EMAC_PHY_REG_LEDCR 0x18 /**< LED Direct Control Register */ #define EMAC_PHY_REG_PHYCR 0x19 /**< PHY Control Register */ #define EMAC_PHY_REG_10BTSCR 0x1A /**< 10Base-T Status/Control Register */ #define EMAC_PHY_REG_CDCTRL1 0x1B /**< CD Test Control and BIST Extens. */ #define EMAC_PHY_REG_EDCR 0x1D /**< Energy Detect Control Register */ /*********************************************************************//** * Macro defines for PHY Basic Mode Control Register **********************************************************************/ #define EMAC_PHY_BMCR_RESET (1<<15) /**< Reset bit */ #define EMAC_PHY_BMCR_LOOPBACK (1<<14) /**< Loop back */ #define EMAC_PHY_BMCR_SPEED_SEL (1<<13) /**< Speed selection */ #define EMAC_PHY_BMCR_AN (1<<12) /**< Auto Negotiation */ #define EMAC_PHY_BMCR_POWERDOWN (1<<11) /**< Power down mode */ #define EMAC_PHY_BMCR_ISOLATE (1<<10) /**< Isolate */ #define EMAC_PHY_BMCR_RE_AN (1<<9) /**< Restart auto negotiation */ #define EMAC_PHY_BMCR_DUPLEX (1<<8) /**< Duplex mode */ /*********************************************************************//** * Macro defines for PHY Basic Mode Status Status Register **********************************************************************/ #define EMAC_PHY_BMSR_100BE_T4 (1<<15) /**< 100 base T4 */ #define EMAC_PHY_BMSR_100TX_FULL (1<<14) /**< 100 base full duplex */ #define EMAC_PHY_BMSR_100TX_HALF (1<<13) /**< 100 base half duplex */ #define EMAC_PHY_BMSR_10BE_FULL (1<<12) /**< 10 base T full duplex */ #define EMAC_PHY_BMSR_10BE_HALF (1<<11) /**< 10 base T half duplex */ #define EMAC_PHY_BMSR_NOPREAM (1<<6) /**< MF Preamable Supress */ #define EMAC_PHY_BMSR_AUTO_DONE (1<<5) /**< Auto negotiation complete */ #define EMAC_PHY_BMSR_REMOTE_FAULT (1<<4) /**< Remote fault */ #define EMAC_PHY_BMSR_NO_AUTO (1<<3) /**< Auto Negotiation ability */ #define EMAC_PHY_BMSR_LINK_ESTABLISHED (1<<2) /**< Link status */ /*********************************************************************//** * Macro defines for PHY Status Register **********************************************************************/ #define EMAC_PHY_SR_REMOTE_FAULT (1<<6) /**< Remote Fault */ #define EMAC_PHY_SR_JABBER (1<<5) /**< Jabber detect */ #define EMAC_PHY_SR_AUTO_DONE (1<<4) /**< Auto Negotiation complete */ #define EMAC_PHY_SR_LOOPBACK (1<<3) /**< Loop back status */ #define EMAC_PHY_SR_DUP (1<<2) /**< Duplex status */ #define EMAC_PHY_SR_SPEED (1<<1) /**< Speed status */ #define EMAC_PHY_SR_LINK (1<<0) /**< Link Status */ #define EMAC_PHY_FULLD_100M 0x2100 /**< Full Duplex 100Mbit */ #define EMAC_PHY_HALFD_100M 0x2000 /**< Half Duplex 100Mbit */ #define EMAC_PHY_FULLD_10M 0x0100 /**< Full Duplex 10Mbit */ #define EMAC_PHY_HALFD_10M 0x0000 /**< Half Duplex 10MBit */ #define EMAC_PHY_AUTO_NEG 0x3000 /**< Select Auto Negotiation */ #define EMAC_DEF_ADR 0x0100 /**< Default PHY device address */ #define EMAC_DP83848C_ID 0x20005C90 /**< PHY Identifier */ #define EMAC_PHY_SR_100_SPEED ((1<<14)|(1<<13)) #define EMAC_PHY_SR_FULL_DUP ((1<<14)|(1<<12)) #define EMAC_PHY_BMSR_LINK_STATUS (1<<2) /**< Link status */ #elif defined(IAR_LPC_1768) /* KSZ8721BL PHY definition ------------------------------------------------------------ */ /** PHY device reset time out definition */ #define EMAC_PHY_RESP_TOUT 0x100000UL /* ENET Device Revision ID */ #define EMAC_OLD_EMAC_MODULE_ID 0x39022000 /**< Rev. ID for first rev '-' */ /*********************************************************************//** * Macro defines for KSZ8721BL PHY Registers **********************************************************************/ #define EMAC_PHY_REG_BMCR 0x00 /**< Basic Mode Control Register */ #define EMAC_PHY_REG_BMSR 0x01 /**< Basic Mode Status Register */ #define EMAC_PHY_REG_IDR1 0x02 /**< PHY Identifier 1 */ #define EMAC_PHY_REG_IDR2 0x03 /**< PHY Identifier 2 */ #define EMAC_PHY_REG_ANAR 0x04 /**< Auto-Negotiation Advertisement */ #define EMAC_PHY_REG_ANLPAR 0x05 /**< Auto-Neg. Link Partner Abitily */ #define EMAC_PHY_REG_ANER 0x06 /**< Auto-Neg. Expansion Register */ #define EMAC_PHY_REG_ANNPTR 0x07 /**< Auto-Neg. Next Page TX */ #define EMAC_PHY_REG_LPNPA 0x08 /**< Link Partner Next Page Ability */ #define EMAC_PHY_REG_REC 0x15 /**< RXError Counter Register */ #define EMAC_PHY_REG_ISC 0x1b /**< Interrupt Control/Status Register */ #define EMAC_PHY_REG_100BASE 0x1f /**< 100BASE-TX PHY Control Register */ /*********************************************************************//** * Macro defines for PHY Basic Mode Control Register **********************************************************************/ #define EMAC_PHY_BMCR_RESET (1<<15) /**< Reset bit */ #define EMAC_PHY_BMCR_LOOPBACK (1<<14) /**< Loop back */ #define EMAC_PHY_BMCR_SPEED_SEL (1<<13) /**< Speed selection */ #define EMAC_PHY_BMCR_AN (1<<12) /**< Auto Negotiation */ #define EMAC_PHY_BMCR_POWERDOWN (1<<11) /**< Power down mode */ #define EMAC_PHY_BMCR_ISOLATE (1<<10) /**< Isolate */ #define EMAC_PHY_BMCR_RE_AN (1<<9) /**< Restart auto negotiation */ #define EMAC_PHY_BMCR_DUPLEX (1<<8) /**< Duplex mode */ #define EMAC_PHY_BMCR_COLLISION (1<<7) /**< Collision test */ #define EMAC_PHY_BMCR_TXDIS (1<<0) /**< Disable transmit */ /*********************************************************************//** * Macro defines for PHY Basic Mode Status Register **********************************************************************/ #define EMAC_PHY_BMSR_100BE_T4 (1<<15) /**< 100 base T4 */ #define EMAC_PHY_BMSR_100TX_FULL (1<<14) /**< 100 base full duplex */ #define EMAC_PHY_BMSR_100TX_HALF (1<<13) /**< 100 base half duplex */ #define EMAC_PHY_BMSR_10BE_FULL (1<<12) /**< 10 base T full duplex */ #define EMAC_PHY_BMSR_10BE_HALF (1<<11) /**< 10 base T half duplex */ #define EMAC_PHY_BMSR_NOPREAM (1<<6) /**< MF Preamable Supress */ #define EMAC_PHY_BMSR_AUTO_DONE (1<<5) /**< Auto negotiation complete */ #define EMAC_PHY_BMSR_REMOTE_FAULT (1<<4) /**< Remote fault */ #define EMAC_PHY_BMSR_NO_AUTO (1<<3) /**< Auto Negotiation ability */ #define EMAC_PHY_BMSR_LINK_STATUS (1<<2) /**< Link status */ #define EMAC_PHY_BMSR_JABBER_DETECT (1<<1) /**< Jabber detect */ #define EMAC_PHY_BMSR_EXTEND (1<<0) /**< Extended support */ /*********************************************************************//** * Macro defines for PHY Identifier **********************************************************************/ /* PHY Identifier 1 bitmap definitions */ #define EMAC_PHY_IDR1(n) (n & 0xFFFF) /**< PHY ID1 Number */ /* PHY Identifier 2 bitmap definitions */ #define EMAC_PHY_IDR2(n) (n & 0xFFFF) /**< PHY ID2 Number */ /*********************************************************************//** * Macro defines for Auto-Negotiation Advertisement **********************************************************************/ #define EMAC_PHY_AN_NEXTPAGE (1<<15) /**< Next page capable */ #define EMAC_PHY_AN_REMOTE_FAULT (1<<13) /**< Remote Fault support */ #define EMAC_PHY_AN_PAUSE (1<<10) /**< Pause support */ #define EMAC_PHY_AN_100BASE_T4 (1<<9) /**< T4 capable */ #define EMAC_PHY_AN_100BASE_TX_FD (1<<8) /**< TX with Full-duplex capable */ #define EMAC_PHY_AN_100BASE_TX (1<<7) /**< TX capable */ #define EMAC_PHY_AN_10BASE_T_FD (1<<6) /**< 10Mbps with full-duplex capable */ #define EMAC_PHY_AN_10BASE_T (1<<5) /**< 10Mbps capable */ #define EMAC_PHY_AN_FIELD(n) (n & 0x1F) /**< Selector Field */ #define EMAC_PHY_FULLD_100M 0x2100 /**< Full Duplex 100Mbit */ #define EMAC_PHY_HALFD_100M 0x2000 /**< Half Duplex 100Mbit */ #define EMAC_PHY_FULLD_10M 0x0100 /**< Full Duplex 10Mbit */ #define EMAC_PHY_HALFD_10M 0x0000 /**< Half Duplex 10MBit */ #define EMAC_PHY_AUTO_NEG 0x3000 /**< Select Auto Negotiation */ #define EMAC_PHY_SR_100_SPEED ((1<<14)|(1<<13)) #define EMAC_PHY_SR_FULL_DUP ((1<<14)|(1<<12)) #define EMAC_DEF_ADR (0x01<<8) /**< Default PHY device address */ #define EMAC_KSZ8721BL_ID ((0x22 << 16) | 0x1619 ) /**< PHY Identifier */ #endif /** * @} */ /* Public Types --------------------------------------------------------------- */ /** @defgroup EMAC_Public_Types EMAC Public Types * @{ */ /* Descriptor and status formats ---------------------------------------------- */ /** * @brief RX Descriptor structure type definition */ typedef struct { uint32_t Packet; /**< Receive Packet Descriptor */ uint32_t Ctrl; /**< Receive Control Descriptor */ } RX_Desc; /** * @brief RX Status structure type definition */ typedef struct { uint32_t Info; /**< Receive Information Status */ uint32_t HashCRC; /**< Receive Hash CRC Status */ } RX_Stat; /** * @brief TX Descriptor structure type definition */ typedef struct { uint32_t Packet; /**< Transmit Packet Descriptor */ uint32_t Ctrl; /**< Transmit Control Descriptor */ } TX_Desc; /** * @brief TX Status structure type definition */ typedef struct { uint32_t Info; /**< Transmit Information Status */ } TX_Stat; /** * @brief TX Data Buffer structure definition */ typedef struct { uint32_t ulDataLen; /**< Data length */ uint32_t *pbDataBuf; /**< A word-align data pointer to data buffer */ } EMAC_PACKETBUF_Type; /** * @brief EMAC configuration structure definition */ typedef struct { uint32_t Mode; /**< Supported EMAC PHY device speed, should be one of the following: - EMAC_MODE_AUTO - EMAC_MODE_10M_FULL - EMAC_MODE_10M_HALF - EMAC_MODE_100M_FULL - EMAC_MODE_100M_HALF */ uint8_t *pbEMAC_Addr; /**< Pointer to EMAC Station address that contains 6-bytes of MAC address, it must be sorted in order (bEMAC_Addr[0]..[5]) */ } EMAC_CFG_Type; /** Ethernet block power/clock control bit*/ #define CLKPWR_PCONP_PCENET ((uint32_t)(1<<30)) #ifdef __cplusplus } #endif #endif /* LPC17XX_EMAC_H_ */ /** * @} */ /* --------------------------------- End Of File ------------------------------ */ ================================================ FILE: Zelig/lwip/lwip-eth/arch/TARGET_NXP/lpc_emac_config.h ================================================ /********************************************************************** * $Id$ lpc_emac_config.h 2011-11-20 *//** * @file lpc_emac_config.h * @brief PHY and EMAC configuration file * @version 1.0 * @date 20 Nov. 2011 * @author NXP MCU SW Application Team * * Copyright(C) 2011, NXP Semiconductor * All rights reserved. * *********************************************************************** * Software that is described herein is for illustrative purposes only * which provides customers with programming information regarding the * products. This software is supplied "AS IS" without any warranties. * NXP Semiconductors assumes no responsibility or liability for the * use of the software, conveys no license or title under any patent, * copyright, or mask work right to the product. NXP Semiconductors * reserves the right to make changes in the software without * notification. NXP Semiconductors also make no representation or * warranty that such application will be suitable for the specified * use without further testing or modification. **********************************************************************/ #ifndef __LPC_EMAC_CONFIG_H #define __LPC_EMAC_CONFIG_H #include "lwip/opt.h" #ifdef __cplusplus extern "C" { #endif /** @defgroup lwip_phy_config LWIP PHY configuration * @ingroup lwip_phy * * Configuration options for the PHY connected to the LPC EMAC. * @{ */ /** \brief The PHY address connected the to MII/RMII */ #define LPC_PHYDEF_PHYADDR 1 /**< The PHY address on the PHY device. */ /** \brief Enable autonegotiation mode. * If this is enabled, the PHY will attempt to auto-negotiate the * best link mode if the PHY supports it. If this is not enabled, * the PHY_USE_FULL_DUPLEX and PHY_USE_100MBS defines will be * used to select the link mode. Note that auto-negotiation may * take a few seconds to complete. */ #define PHY_USE_AUTONEG 1 /**< Enables auto-negotiation mode. */ /** \brief Sets up the PHY interface to either full duplex operation or * half duplex operation if PHY_USE_AUTONEG is not enabled. */ #define PHY_USE_FULL_DUPLEX 1 /**< Sets duplex mode to full. */ /** \brief Sets up the PHY interface to either 100MBS operation or 10MBS * operation if PHY_USE_AUTONEG is not enabled. */ #define PHY_USE_100MBS 1 /**< Sets data rate to 100Mbps. */ /** * @} */ /** @defgroup lwip_emac_config LWIP EMAC configuration * @ingroup lwip_emac * * Configuration options for the LPC EMAC. * @{ */ /** \brief Selects RMII or MII connection type in the EMAC peripheral */ #define LPC_EMAC_RMII 1 /**< Use the RMII or MII driver variant .*/ /** \brief Defines the number of descriptors used for RX. This * must be a minimum value of 2. */ #define LPC_NUM_BUFF_RXDESCS 3 /** \brief Defines the number of descriptors used for TX. Must * be a minimum value of 2. */ #define LPC_NUM_BUFF_TXDESCS (TCP_SND_QUEUELEN + 1) /** \brief Set this define to 1 to enable bounce buffers for transmit pbufs * that cannot be sent via the zero-copy method. Some chained pbufs * may have a payload address that links to an area of memory that * cannot be used for transmit DMA operations. If this define is * set to 1, an extra check will be made with the pbufs. If a buffer * is determined to be non-usable for zero-copy, a temporary bounce * buffer will be created and used instead. */ #define LPC_TX_PBUF_BOUNCE_EN 1 /** * @} */ #ifdef __cplusplus } #endif #endif /* __LPC_EMAC_CONFIG_H */ /* --------------------------------- End Of File ------------------------------ */ ================================================ FILE: Zelig/lwip/lwip-eth/arch/TARGET_NXP/lpc_phy.h ================================================ /********************************************************************** * $Id$ lpc_phy.h 2011-11-20 *//** * @file lpc_phy.h * @brief Common PHY definitions used with all PHYs * @version 1.0 * @date 20 Nov. 2011 * @author NXP MCU SW Application Team * * Copyright(C) 2011, NXP Semiconductor * All rights reserved. * *********************************************************************** * Software that is described herein is for illustrative purposes only * which provides customers with programming information regarding the * products. This software is supplied "AS IS" without any warranties. * NXP Semiconductors assumes no responsibility or liability for the * use of the software, conveys no license or title under any patent, * copyright, or mask work right to the product. NXP Semiconductors * reserves the right to make changes in the software without * notification. NXP Semiconductors also make no representation or * warranty that such application will be suitable for the specified * use without further testing or modification. **********************************************************************/ #ifndef __LPC_PHY_H_ #define __LPC_PHY_H_ #include "lwip/opt.h" #include "lwip/err.h" #include "lwip/netif.h" #ifdef __cplusplus extern "C" { #endif /* These PHY functions are usually part of the EMAC driver */ /** \brief Phy status update state machine * * This function provides a state machine for maintaining the PHY * status without blocking. It must be occasionally called for the * PHY status to be maintained. * * \param[in] netif NETIF structure */ s32_t lpc_phy_sts_sm(struct netif *netif); /** \brief Initialize the PHY * * This function initializes the PHY. It will block until complete. * This function is called as part of the EMAC driver * initialization. Configuration of the PHY at startup is * controlled by setting up configuration defines in lpc_phy.h. * * \param[in] netif NETIF structure * \param[in] rmii If set, configures the PHY for RMII mode * \return ERR_OK if the setup was successful, otherwise ERR_TIMEOUT */ err_t lpc_phy_init(struct netif *netif, int rmii); /** \brief Write a value via the MII link (non-blocking) * * This function will write a value on the MII link interface to a PHY * or a connected device. The function will return immediately without * a status. Status needs to be polled later to determine if the write * was successful. * * \param[in] PhyReg PHY register to write to * \param[in] Value Value to write */ void lpc_mii_write_noblock(u32_t PhyReg, u32_t Value); /** \brief Write a value via the MII link (blocking) * * This function will write a value on the MII link interface to a PHY * or a connected device. The function will block until complete. * * \param[in] PhyReg PHY register to write to * \param[in] Value Value to write * \returns 0 if the write was successful, otherwise !0 */ err_t lpc_mii_write(u32_t PhyReg, u32_t Value); /** \brief Reads current MII link busy status * * This function will return the current MII link busy status and is meant to * be used with non-blocking functions for monitor PHY status such as * connection state. * * \returns !0 if the MII link is busy, otherwise 0 */ u32_t lpc_mii_is_busy(void); /** \brief Starts a read operation via the MII link (non-blocking) * * This function returns the current value in the MII data register. It is * meant to be used with the non-blocking oeprations. This value should * only be read after a non-block read command has been issued and the * MII status has been determined to be good. * * \returns The current value in the MII value register */ u32_t lpc_mii_read_data(void); /** \brief Starts a read operation via the MII link (non-blocking) * * This function will start a read operation on the MII link interface * from a PHY or a connected device. The function will not block and * the status mist be polled until complete. Once complete, the data * can be read. * * \param[in] PhyReg PHY register to read from */ err_t lpc_mii_read(u32_t PhyReg, u32_t *data); /** \brief Read a value via the MII link (blocking) * * This function will read a value on the MII link interface from a PHY * or a connected device. The function will block until complete. * * \param[in] PhyReg PHY register to read from * \param[in] data Pointer to where to save data read via MII * \returns 0 if the read was successful, otherwise !0 */ void lpc_mii_read_noblock(u32_t PhyReg); /** * This function provides a method for the PHY to setup the EMAC * for the PHY negotiated duplex mode. * * @param[in] full_duplex 0 = half duplex, 1 = full duplex */ void lpc_emac_set_duplex(int full_duplex); /** * This function provides a method for the PHY to setup the EMAC * for the PHY negotiated bit rate. * * @param[in] mbs_100 0 = 10mbs mode, 1 = 100mbs mode */ void lpc_emac_set_speed(int mbs_100); #ifdef __cplusplus } #endif #endif /* __LPC_PHY_H_ */ /* --------------------------------- End Of File ------------------------------ */ ================================================ FILE: Zelig/lwip/lwip-eth/arch/TARGET_NXP/lpc_phy_dp83848.c ================================================ /********************************************************************** * $Id$ lpc_phy_dp83848.c 2011-11-20 *//** * @file lpc_phy_dp83848.c * @brief DP83848C PHY status and control. * @version 1.0 * @date 20 Nov. 2011 * @author NXP MCU SW Application Team * * Copyright(C) 2011, NXP Semiconductor * All rights reserved. * *********************************************************************** * Software that is described herein is for illustrative purposes only * which provides customers with programming information regarding the * products. This software is supplied "AS IS" without any warranties. * NXP Semiconductors assumes no responsibility or liability for the * use of the software, conveys no license or title under any patent, * copyright, or mask work right to the product. NXP Semiconductors * reserves the right to make changes in the software without * notification. NXP Semiconductors also make no representation or * warranty that such application will be suitable for the specified * use without further testing or modification. **********************************************************************/ #include "lwip/opt.h" #include "lwip/err.h" #include "lwip/tcpip.h" #include "lwip/snmp.h" #include "lpc_emac_config.h" #include "lpc_phy.h" #include "lpc17xx_emac.h" /** @defgroup dp83848_phy PHY status and control for the DP83848. * @ingroup lwip_phy * * Various functions for controlling and monitoring the status of the * DP83848 PHY. In polled (standalone) systems, the PHY state must be * monitored as part of the application. In a threaded (RTOS) system, * the PHY state is monitored by the PHY handler thread. The MAC * driver will not transmit unless the PHY link is active. * @{ */ /** \brief DP83848 PHY register offsets */ #define DP8_BMCR_REG 0x0 /**< Basic Mode Control Register */ #define DP8_BMSR_REG 0x1 /**< Basic Mode Status Reg */ #define DP8_IDR1_REG 0x2 /**< Basic Mode Status Reg */ #define DP8_IDR2_REG 0x3 /**< Basic Mode Status Reg */ #define DP8_ANADV_REG 0x4 /**< Auto_Neg Advt Reg */ #define DP8_ANLPA_REG 0x5 /**< Auto_neg Link Partner Ability Reg */ #define DP8_ANEEXP_REG 0x6 /**< Auto-neg Expansion Reg */ #define DP8_PHY_STAT_REG 0x10 /**< PHY Status Register */ #define DP8_PHY_INT_CTL_REG 0x11 /**< PHY Interrupt Control Register */ #define DP8_PHY_RBR_REG 0x17 /**< PHY RMII and Bypass Register */ #define DP8_PHY_STS_REG 0x19 /**< PHY Status Register */ #define DP8_PHY_SCSR_REG 0x1f /**< PHY Special Control/Status Register (LAN8720) */ /** \brief DP83848 Control register definitions */ #define DP8_RESET (1 << 15) /**< 1= S/W Reset */ #define DP8_LOOPBACK (1 << 14) /**< 1=loopback Enabled */ #define DP8_SPEED_SELECT (1 << 13) /**< 1=Select 100MBps */ #define DP8_AUTONEG (1 << 12) /**< 1=Enable auto-negotiation */ #define DP8_POWER_DOWN (1 << 11) /**< 1=Power down PHY */ #define DP8_ISOLATE (1 << 10) /**< 1=Isolate PHY */ #define DP8_RESTART_AUTONEG (1 << 9) /**< 1=Restart auto-negoatiation */ #define DP8_DUPLEX_MODE (1 << 8) /**< 1=Full duplex mode */ #define DP8_COLLISION_TEST (1 << 7) /**< 1=Perform collsion test */ /** \brief DP83848 Status register definitions */ #define DP8_100BASE_T4 (1 << 15) /**< T4 mode */ #define DP8_100BASE_TX_FD (1 << 14) /**< 100MBps full duplex */ #define DP8_100BASE_TX_HD (1 << 13) /**< 100MBps half duplex */ #define DP8_10BASE_T_FD (1 << 12) /**< 100Bps full duplex */ #define DP8_10BASE_T_HD (1 << 11) /**< 10MBps half duplex */ #define DP8_MF_PREAMB_SUPPR (1 << 6) /**< Preamble suppress */ #define DP8_AUTONEG_COMP (1 << 5) /**< Auto-negotation complete */ #define DP8_RMT_FAULT (1 << 4) /**< Fault */ #define DP8_AUTONEG_ABILITY (1 << 3) /**< Auto-negotation supported */ #define DP8_LINK_STATUS (1 << 2) /**< 1=Link active */ #define DP8_JABBER_DETECT (1 << 1) /**< Jabber detect */ #define DP8_EXTEND_CAPAB (1 << 0) /**< Supports extended capabilities */ /** \brief DP83848 PHY RBR MII dode definitions */ #define DP8_RBR_RMII_MODE (1 << 5) /**< Use RMII mode */ /** \brief DP83848 PHY status definitions */ #define DP8_REMOTEFAULT (1 << 6) /**< Remote fault */ #define DP8_FULLDUPLEX (1 << 2) /**< 1=full duplex */ #define DP8_SPEED10MBPS (1 << 1) /**< 1=10MBps speed */ #define DP8_VALID_LINK (1 << 0) /**< 1=Link active */ /** \brief DP83848 PHY ID register definitions */ #define DP8_PHYID1_OUI 0x2000 /**< Expected PHY ID1 */ #define DP8_PHYID2_OUI 0x5c90 /**< Expected PHY ID2 */ /** \brief LAN8720 PHY Special Control/Status Register */ #define PHY_SCSR_100MBIT 0x0008 /**< Speed: 1=100 MBit, 0=10Mbit */ #define PHY_SCSR_DUPLEX 0x0010 /**< PHY Duplex Mask */ /** \brief Link status bits */ #define LNK_STAT_VALID 0x01 #define LNK_STAT_FULLDUPLEX 0x02 #define LNK_STAT_SPEED10MPS 0x04 /** \brief PHY ID definitions */ #define DP83848C_ID 0x20005C90 /**< PHY Identifier - DP83848C */ #define LAN8720_ID 0x0007C0F0 /**< PHY Identifier - LAN8720 */ /** \brief PHY status structure used to indicate current status of PHY. */ typedef struct { u32_t phy_speed_100mbs:1; /**< 10/100 MBS connection speed flag. */ u32_t phy_full_duplex:1; /**< Half/full duplex connection speed flag. */ u32_t phy_link_active:1; /**< Phy link active flag. */ } PHY_STATUS_TYPE; /** \brief PHY update flags */ static PHY_STATUS_TYPE physts; /** \brief Last PHY update flags, used for determing if something has changed */ static PHY_STATUS_TYPE olddphysts; /** \brief PHY update counter for state machine */ static s32_t phyustate; /** \brief Holds the PHY ID */ static u32_t phy_id; /** \brief Temporary holder of link status for LAN7420 */ static u32_t phy_lan7420_sts_tmp; /* Write a value via the MII link (non-blocking) */ void lpc_mii_write_noblock(u32_t PhyReg, u32_t Value) { /* Write value at PHY address and register */ LPC_EMAC->MADR = (LPC_PHYDEF_PHYADDR << 8) | PhyReg; LPC_EMAC->MWTD = Value; } /* Write a value via the MII link (blocking) */ err_t lpc_mii_write(u32_t PhyReg, u32_t Value) { u32_t mst = 250; err_t sts = ERR_OK; /* Write value at PHY address and register */ lpc_mii_write_noblock(PhyReg, Value); /* Wait for unbusy status */ while (mst > 0) { sts = LPC_EMAC->MIND; if ((sts & EMAC_MIND_BUSY) == 0) mst = 0; else { mst--; osDelay(1); } } if (sts != 0) sts = ERR_TIMEOUT; return sts; } /* Reads current MII link busy status */ u32_t lpc_mii_is_busy(void) { return (u32_t) (LPC_EMAC->MIND & EMAC_MIND_BUSY); } /* Starts a read operation via the MII link (non-blocking) */ u32_t lpc_mii_read_data(void) { u32_t data = LPC_EMAC->MRDD; LPC_EMAC->MCMD = 0; return data; } /* Starts a read operation via the MII link (non-blocking) */ void lpc_mii_read_noblock(u32_t PhyReg) { /* Read value at PHY address and register */ LPC_EMAC->MADR = (LPC_PHYDEF_PHYADDR << 8) | PhyReg; LPC_EMAC->MCMD = EMAC_MCMD_READ; } /* Read a value via the MII link (blocking) */ err_t lpc_mii_read(u32_t PhyReg, u32_t *data) { u32_t mst = 250; err_t sts = ERR_OK; /* Read value at PHY address and register */ lpc_mii_read_noblock(PhyReg); /* Wait for unbusy status */ while (mst > 0) { sts = LPC_EMAC->MIND & ~EMAC_MIND_MII_LINK_FAIL; if ((sts & EMAC_MIND_BUSY) == 0) { mst = 0; *data = LPC_EMAC->MRDD; } else { mst--; osDelay(1); } } LPC_EMAC->MCMD = 0; if (sts != 0) sts = ERR_TIMEOUT; return sts; } /** \brief Update PHY status from passed value * * This function updates the current PHY status based on the * passed PHY status word. The PHY status indicate if the link * is active, the connection speed, and duplex. * * \param[in] netif NETIF structure * \param[in] linksts Status word from PHY * \return 1 if the status has changed, otherwise 0 */ static s32_t lpc_update_phy_sts(struct netif *netif, u32_t linksts) { s32_t changed = 0; /* Update link active status */ if (linksts & LNK_STAT_VALID) physts.phy_link_active = 1; else physts.phy_link_active = 0; /* Full or half duplex */ if (linksts & LNK_STAT_FULLDUPLEX) physts.phy_full_duplex = 1; else physts.phy_full_duplex = 0; /* Configure 100MBit/10MBit mode. */ if (linksts & LNK_STAT_SPEED10MPS) physts.phy_speed_100mbs = 0; else physts.phy_speed_100mbs = 1; if (physts.phy_speed_100mbs != olddphysts.phy_speed_100mbs) { changed = 1; if (physts.phy_speed_100mbs) { /* 100MBit mode. */ lpc_emac_set_speed(1); NETIF_INIT_SNMP(netif, snmp_ifType_ethernet_csmacd, 100000000); } else { /* 10MBit mode. */ lpc_emac_set_speed(0); NETIF_INIT_SNMP(netif, snmp_ifType_ethernet_csmacd, 10000000); } olddphysts.phy_speed_100mbs = physts.phy_speed_100mbs; } if (physts.phy_full_duplex != olddphysts.phy_full_duplex) { changed = 1; if (physts.phy_full_duplex) lpc_emac_set_duplex(1); else lpc_emac_set_duplex(0); olddphysts.phy_full_duplex = physts.phy_full_duplex; } if (physts.phy_link_active != olddphysts.phy_link_active) { changed = 1; #if NO_SYS == 1 if (physts.phy_link_active) netif_set_link_up(netif); else netif_set_link_down(netif); #else if (physts.phy_link_active) tcpip_callback_with_block((tcpip_callback_fn) netif_set_link_up, (void*) netif, 1); else tcpip_callback_with_block((tcpip_callback_fn) netif_set_link_down, (void*) netif, 1); #endif olddphysts.phy_link_active = physts.phy_link_active; } return changed; } /** \brief Initialize the DP83848 PHY. * * This function initializes the DP83848 PHY. It will block until * complete. This function is called as part of the EMAC driver * initialization. Configuration of the PHY at startup is * controlled by setting up configuration defines in lpc_phy.h. * * \param[in] netif NETIF structure * \param[in] rmii If set, configures the PHY for RMII mode * \return ERR_OK if the setup was successful, otherwise ERR_TIMEOUT */ err_t lpc_phy_init(struct netif *netif, int rmii) { u32_t tmp; s32_t i; physts.phy_speed_100mbs = olddphysts.phy_speed_100mbs = 0; physts.phy_full_duplex = olddphysts.phy_full_duplex = 0; physts.phy_link_active = olddphysts.phy_link_active = 0; phyustate = 0; /* Only first read and write are checked for failure */ /* Put the DP83848C in reset mode and wait for completion */ if (lpc_mii_write(DP8_BMCR_REG, DP8_RESET) != 0) return ERR_TIMEOUT; i = 400; while (i > 0) { osDelay(1); /* 1 ms */ if (lpc_mii_read(DP8_BMCR_REG, &tmp) != 0) return ERR_TIMEOUT; if (!(tmp & (DP8_RESET | DP8_POWER_DOWN))) i = -1; else i--; } /* Timeout? */ if (i == 0) return ERR_TIMEOUT; // read PHY ID lpc_mii_read(DP8_IDR1_REG, &tmp); phy_id = (tmp << 16); lpc_mii_read(DP8_IDR2_REG, &tmp); phy_id |= (tmp & 0XFFF0); /* Setup link based on configuration options */ #if PHY_USE_AUTONEG==1 tmp = DP8_AUTONEG; #else tmp = 0; #endif #if PHY_USE_100MBS==1 tmp |= DP8_SPEED_SELECT; #endif #if PHY_USE_FULL_DUPLEX==1 tmp |= DP8_DUPLEX_MODE; #endif lpc_mii_write(DP8_BMCR_REG, tmp); /* Enable RMII mode for PHY */ if (rmii) lpc_mii_write(DP8_PHY_RBR_REG, DP8_RBR_RMII_MODE); /* The link is not set active at this point, but will be detected later */ return ERR_OK; } /* Phy status update state machine */ s32_t lpc_phy_sts_sm(struct netif *netif) { s32_t changed = 0; u32_t data = 0; u32_t tmp; switch (phyustate) { default: case 0: if (phy_id == DP83848C_ID) { lpc_mii_read_noblock(DP8_PHY_STAT_REG); phyustate = 2; } else if (phy_id == LAN8720_ID) { lpc_mii_read_noblock(DP8_PHY_SCSR_REG); phyustate = 1; } break; case 1: if (phy_id == LAN8720_ID) { tmp = lpc_mii_read_data(); // we get speed and duplex here. phy_lan7420_sts_tmp = (tmp & PHY_SCSR_DUPLEX) ? LNK_STAT_FULLDUPLEX : 0; phy_lan7420_sts_tmp |= (tmp & PHY_SCSR_100MBIT) ? 0 : LNK_STAT_SPEED10MPS; //read the status register to get link status lpc_mii_read_noblock(DP8_BMSR_REG); phyustate = 2; } break; case 2: /* Wait for read status state */ if (!lpc_mii_is_busy()) { /* Update PHY status */ tmp = lpc_mii_read_data(); if (phy_id == DP83848C_ID) { // STS register contains all needed status bits data = (tmp & DP8_VALID_LINK) ? LNK_STAT_VALID : 0; data |= (tmp & DP8_FULLDUPLEX) ? LNK_STAT_FULLDUPLEX : 0; data |= (tmp & DP8_SPEED10MBPS) ? LNK_STAT_SPEED10MPS : 0; } else if (phy_id == LAN8720_ID) { // we only get the link status here. phy_lan7420_sts_tmp |= (tmp & DP8_LINK_STATUS) ? LNK_STAT_VALID : 0; data = phy_lan7420_sts_tmp; } changed = lpc_update_phy_sts(netif, data); phyustate = 0; } break; } return changed; } /** * @} */ /* --------------------------------- End Of File ------------------------------ */ ================================================ FILE: Zelig/lwip/lwip-eth/arch/TARGET_NXP/lwipopts_conf.h ================================================ /* Copyright (C) 2012 mbed.org, MIT License * * Permission is hereby granted, free of charge, to any person obtaining a copy of this software * and associated documentation files (the "Software"), to deal in the Software without restriction, * including without limitation the rights to use, copy, modify, merge, publish, distribute, * sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all copies or * substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING * BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, * DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ #ifndef LWIPOPTS_CONF_H #define LWIPOPTS_CONF_H #define LWIP_TRANSPORT_ETHERNET 1 #if defined(TARGET_LPC4088) || defined(TARGET_LPC4088_DM) #define MEM_SIZE 15360 #elif defined(TARGET_LPC1768) #define MEM_SIZE 16362 #endif #endif ================================================ FILE: Zelig/lwip/lwip-eth/arch/TARGET_RZ_A1H/lwipopts_conf.h ================================================ /* Copyright (C) 2012 mbed.org, MIT License * * Permission is hereby granted, free of charge, to any person obtaining a copy of this software * and associated documentation files (the "Software"), to deal in the Software without restriction, * including without limitation the rights to use, copy, modify, merge, publish, distribute, * sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all copies or * substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING * BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, * DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ #ifndef LWIPOPTS_CONF_H #define LWIPOPTS_CONF_H #define LWIP_TRANSPORT_ETHERNET 1 #define MEM_SIZE (1600 * 16) #endif ================================================ FILE: Zelig/lwip/lwip-eth/arch/TARGET_RZ_A1H/rza1_emac.c ================================================ #include "lwip/opt.h" #include "lwip/tcpip.h" #include "netif/etharp.h" #include "mbed_interface.h" #include "ethernet_api.h" #include "ethernetext_api.h" #define RECV_TASK_PRI (osPriorityNormal) #define PHY_TASK_PRI (osPriorityNormal) #define PHY_TASK_WAIT (200) /* memory */ static sys_sem_t recv_ready_sem; /* receive ready semaphore */ /* function */ static void rza1_recv_task(void *arg); static void rza1_phy_task(void *arg); static err_t rza1_etharp_output(struct netif *netif, struct pbuf *q, ip_addr_t *ipaddr); static err_t rza1_low_level_output(struct netif *netif, struct pbuf *p); static void rza1_recv_callback(void); static void rza1_recv_task(void *arg) { struct netif *netif = (struct netif*)arg; struct eth_hdr *ethhdr; u16_t recv_size; struct pbuf *p; int cnt; while (1) { sys_arch_sem_wait(&recv_ready_sem, 0); for (cnt = 0; cnt < 16; cnt++) { recv_size = ethernet_receive(); if (recv_size != 0) { p = pbuf_alloc(PBUF_RAW, recv_size, PBUF_RAM); if (p != NULL) { (void)ethernet_read((char *)p->payload, p->len); ethhdr = p->payload; switch (htons(ethhdr->type)) { case ETHTYPE_IP: case ETHTYPE_ARP: #if PPPOE_SUPPORT case ETHTYPE_PPPOEDISC: case ETHTYPE_PPPOE: #endif /* PPPOE_SUPPORT */ /* full packet send to tcpip_thread to process */ if (netif->input(p, netif) != ERR_OK) { /* Free buffer */ pbuf_free(p); } break; default: /* Return buffer */ pbuf_free(p); break; } } } else { break; } } } } static void rza1_phy_task(void *arg) { struct netif *netif = (struct netif*)arg; s32_t connect_sts = 0; /* 0: disconnect, 1:connect */ s32_t link_sts; s32_t link_mode_new = NEGO_FAIL; s32_t link_mode_old = NEGO_FAIL; while (1) { link_sts = ethernet_link(); if (link_sts == 1) { link_mode_new = ethernetext_chk_link_mode(); if (link_mode_new != link_mode_old) { if (connect_sts == 1) { tcpip_callback_with_block((tcpip_callback_fn)netif_set_link_down, (void*) netif, 1); } if (link_mode_new != NEGO_FAIL) { ethernetext_set_link_mode(link_mode_new); tcpip_callback_with_block((tcpip_callback_fn)netif_set_link_up, (void*) netif, 1); connect_sts = 1; } } } else { if (connect_sts != 0) { tcpip_callback_with_block((tcpip_callback_fn)netif_set_link_down, (void*) netif, 1); link_mode_new = NEGO_FAIL; connect_sts = 0; } } link_mode_old = link_mode_new; osDelay(PHY_TASK_WAIT); } } static err_t rza1_etharp_output(struct netif *netif, struct pbuf *q, ip_addr_t *ipaddr) { /* Only send packet is link is up */ if (netif->flags & NETIF_FLAG_LINK_UP) { return etharp_output(netif, q, ipaddr); } return ERR_CONN; } static err_t rza1_low_level_output(struct netif *netif, struct pbuf *p) { struct pbuf *q; s32_t cnt; err_t err = ERR_MEM; s32_t write_size = 0; if ((p->payload != NULL) && (p->len != 0)) { /* If the first data can't be written, transmit descriptor is full. */ for (cnt = 0; cnt < 100; cnt++) { write_size = ethernet_write((char *)p->payload, p->len); if (write_size != 0) { break; } osDelay(1); } if (write_size != 0) { for (q = p->next; q != NULL; q = q->next) { (void)ethernet_write((char *)q->payload, q->len); } if (ethernet_send() == 1) { err = ERR_OK; } } } return err; } static void rza1_recv_callback(void) { sys_sem_signal(&recv_ready_sem); } err_t eth_arch_enetif_init(struct netif *netif) { ethernet_cfg_t ethcfg; /* set MAC hardware address */ #if (MBED_MAC_ADDRESS_SUM != MBED_MAC_ADDR_INTERFACE) netif->hwaddr[0] = MBED_MAC_ADDR_0; netif->hwaddr[1] = MBED_MAC_ADDR_1; netif->hwaddr[2] = MBED_MAC_ADDR_2; netif->hwaddr[3] = MBED_MAC_ADDR_3; netif->hwaddr[4] = MBED_MAC_ADDR_4; netif->hwaddr[5] = MBED_MAC_ADDR_5; #else mbed_mac_address((char *)netif->hwaddr); #endif netif->hwaddr_len = ETHARP_HWADDR_LEN; /* maximum transfer unit */ netif->mtu = 1500; /* device capabilities */ netif->flags = NETIF_FLAG_BROADCAST | NETIF_FLAG_ETHARP | NETIF_FLAG_ETHERNET | NETIF_FLAG_IGMP; #if LWIP_NETIF_HOSTNAME /* Initialize interface hostname */ netif->hostname = "lwiprza1"; #endif /* LWIP_NETIF_HOSTNAME */ netif->name[0] = 'e'; netif->name[1] = 'n'; netif->output = rza1_etharp_output; netif->linkoutput = rza1_low_level_output; /* Initialize the hardware */ ethcfg.int_priority = 6; ethcfg.recv_cb = &rza1_recv_callback; ethcfg.ether_mac = (char *)netif->hwaddr; ethernetext_init(ðcfg); /* semaphore */ sys_sem_new(&recv_ready_sem, 0); /* task */ sys_thread_new("rza1_recv_task", rza1_recv_task, netif, DEFAULT_THREAD_STACKSIZE, RECV_TASK_PRI); sys_thread_new("rza1_phy_task", rza1_phy_task, netif, DEFAULT_THREAD_STACKSIZE, PHY_TASK_PRI); return ERR_OK; } void eth_arch_enable_interrupts(void) { ethernetext_start_stop(1); } void eth_arch_disable_interrupts(void) { ethernetext_start_stop(0); } ================================================ FILE: Zelig/lwip/lwip-eth/arch/TARGET_STM/lwipopts_conf.h ================================================ /* Copyright (C) 2015 mbed.org, MIT License * * Permission is hereby granted, free of charge, to any person obtaining a copy of this software * and associated documentation files (the "Software"), to deal in the Software without restriction, * including without limitation the rights to use, copy, modify, merge, publish, distribute, * sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all copies or * substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING * BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, * DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ #ifndef LWIPOPTS_CONF_H #define LWIPOPTS_CONF_H #define LWIP_TRANSPORT_ETHERNET 1 #define MEM_SIZE (1600 * 16) #endif ================================================ FILE: Zelig/lwip/lwip-eth/arch/TARGET_STM/stm32f4_emac.c ================================================ #include "stm32f4xx_hal.h" #include "lwip/opt.h" #include "lwip/timers.h" #include "netif/etharp.h" #include "lwip/tcpip.h" #include #include "cmsis_os.h" #include "mbed_interface.h" /** @defgroup lwipstm32f4xx_emac_DRIVER stm32f4 EMAC driver for LWIP * @ingroup lwip_emac * * @{ */ #define RECV_TASK_PRI (osPriorityHigh) #define PHY_TASK_PRI (osPriorityLow) #define PHY_TASK_WAIT (200) #if defined (__ICCARM__) /*!< IAR Compiler */ #pragma data_alignment=4 #endif __ALIGN_BEGIN ETH_DMADescTypeDef DMARxDscrTab[ETH_RXBUFNB] __ALIGN_END; /* Ethernet Rx MA Descriptor */ #if defined (__ICCARM__) /*!< IAR Compiler */ #pragma data_alignment=4 #endif __ALIGN_BEGIN ETH_DMADescTypeDef DMATxDscrTab[ETH_TXBUFNB] __ALIGN_END; /* Ethernet Tx DMA Descriptor */ #if defined (__ICCARM__) /*!< IAR Compiler */ #pragma data_alignment=4 #endif __ALIGN_BEGIN uint8_t Rx_Buff[ETH_RXBUFNB][ETH_RX_BUF_SIZE] __ALIGN_END; /* Ethernet Receive Buffer */ #if defined (__ICCARM__) /*!< IAR Compiler */ #pragma data_alignment=4 #endif __ALIGN_BEGIN uint8_t Tx_Buff[ETH_TXBUFNB][ETH_TX_BUF_SIZE] __ALIGN_END; /* Ethernet Transmit Buffer */ ETH_HandleTypeDef heth; static sys_sem_t rx_ready_sem; /* receive ready semaphore */ static sys_mutex_t tx_lock_mutex; /* function */ static void stm32f4_rx_task(void *arg); static void stm32f4_phy_task(void *arg); static err_t stm32f4_etharp_output(struct netif *netif, struct pbuf *q, ip_addr_t *ipaddr); static err_t stm32f4_low_level_output(struct netif *netif, struct pbuf *p); /** * Override HAL Eth Init function */ void HAL_ETH_MspInit(ETH_HandleTypeDef* heth) { GPIO_InitTypeDef GPIO_InitStruct; if (heth->Instance == ETH) { /* Peripheral clock enable */ __ETH_CLK_ENABLE(); __GPIOA_CLK_ENABLE(); __GPIOB_CLK_ENABLE(); __GPIOC_CLK_ENABLE(); /**ETH GPIO Configuration PC1 ------> ETH_MDC PA1 ------> ETH_REF_CLK PA2 ------> ETH_MDIO PA7 ------> ETH_CRS_DV PC4 ------> ETH_RXD0 PC5 ------> ETH_RXD1 PB11 ------> ETH_TX_EN PB12 ------> ETH_TXD0 PB13 ------> ETH_TXD1 */ GPIO_InitStruct.Pin = GPIO_PIN_1 | GPIO_PIN_4 | GPIO_PIN_5; GPIO_InitStruct.Mode = GPIO_MODE_AF_PP; GPIO_InitStruct.Pull = GPIO_NOPULL; GPIO_InitStruct.Speed = GPIO_SPEED_HIGH; GPIO_InitStruct.Alternate = GPIO_AF11_ETH; HAL_GPIO_Init(GPIOC, &GPIO_InitStruct); GPIO_InitStruct.Pin = GPIO_PIN_1 | GPIO_PIN_2 | GPIO_PIN_7; GPIO_InitStruct.Mode = GPIO_MODE_AF_PP; GPIO_InitStruct.Pull = GPIO_NOPULL; GPIO_InitStruct.Speed = GPIO_SPEED_HIGH; GPIO_InitStruct.Alternate = GPIO_AF11_ETH; HAL_GPIO_Init(GPIOA, &GPIO_InitStruct); GPIO_InitStruct.Pin = GPIO_PIN_11 | GPIO_PIN_12 | GPIO_PIN_13; GPIO_InitStruct.Mode = GPIO_MODE_AF_PP; GPIO_InitStruct.Pull = GPIO_NOPULL; GPIO_InitStruct.Speed = GPIO_SPEED_HIGH; GPIO_InitStruct.Alternate = GPIO_AF11_ETH; HAL_GPIO_Init(GPIOB, &GPIO_InitStruct); /* Peripheral interrupt init*/ /* Sets the priority grouping field */ HAL_NVIC_SetPriorityGrouping(NVIC_PRIORITYGROUP_4); HAL_NVIC_SetPriority(ETH_IRQn, 0, 0); HAL_NVIC_EnableIRQ(ETH_IRQn); } } /** * Override HAL Eth DeInit function */ void HAL_ETH_MspDeInit(ETH_HandleTypeDef* heth) { if (heth->Instance == ETH) { /* Peripheral clock disable */ __ETH_CLK_DISABLE(); /**ETH GPIO Configuration PC1 ------> ETH_MDC PA1 ------> ETH_REF_CLK PA2 ------> ETH_MDIO PA7 ------> ETH_CRS_DV PC4 ------> ETH_RXD0 PC5 ------> ETH_RXD1 PB11 ------> ETH_TX_EN PB12 ------> ETH_TXD0 PB13 ------> ETH_TXD1 */ HAL_GPIO_DeInit(GPIOC, GPIO_PIN_1 | GPIO_PIN_4 | GPIO_PIN_5); HAL_GPIO_DeInit(GPIOA, GPIO_PIN_1 | GPIO_PIN_2 | GPIO_PIN_7); HAL_GPIO_DeInit(GPIOB, GPIO_PIN_11 | GPIO_PIN_12 | GPIO_PIN_13); /* Peripheral interrupt Deinit*/ HAL_NVIC_DisableIRQ(ETH_IRQn); } } /** * Ethernet Rx Transfer completed callback * * @param heth: ETH handle * @retval None */ void HAL_ETH_RxCpltCallback(ETH_HandleTypeDef *heth) { sys_sem_signal(&rx_ready_sem); } /** * Ethernet IRQ Handler * * @param None * @retval None */ void ETH_IRQHandler(void) { HAL_ETH_IRQHandler(&heth); } /** * In this function, the hardware should be initialized. * Called from eth_arch_enetif_init(). * * @param netif the already initialized lwip network interface structure * for this ethernetif */ static void stm32f4_low_level_init(struct netif *netif) { uint32_t regvalue = 0; HAL_StatusTypeDef hal_eth_init_status; /* Init ETH */ uint8_t MACAddr[6]; heth.Instance = ETH; heth.Init.AutoNegotiation = ETH_AUTONEGOTIATION_ENABLE; heth.Init.Speed = ETH_SPEED_10M; heth.Init.DuplexMode = ETH_MODE_FULLDUPLEX; heth.Init.PhyAddress = 1; #if (MBED_MAC_ADDRESS_SUM != MBED_MAC_ADDR_INTERFACE) MACAddr[0] = MBED_MAC_ADDR_0; MACAddr[1] = MBED_MAC_ADDR_1; MACAddr[2] = MBED_MAC_ADDR_2; MACAddr[3] = MBED_MAC_ADDR_3; MACAddr[4] = MBED_MAC_ADDR_4; MACAddr[5] = MBED_MAC_ADDR_5; #else mbed_mac_address((char *)MACAddr); #endif heth.Init.MACAddr = &MACAddr[0]; heth.Init.RxMode = ETH_RXINTERRUPT_MODE; heth.Init.ChecksumMode = ETH_CHECKSUM_BY_HARDWARE; heth.Init.MediaInterface = ETH_MEDIA_INTERFACE_RMII; hal_eth_init_status = HAL_ETH_Init(&heth); if (hal_eth_init_status == HAL_OK) { /* Set netif link flag */ netif->flags |= NETIF_FLAG_LINK_UP; } /* Initialize Tx Descriptors list: Chain Mode */ HAL_ETH_DMATxDescListInit(&heth, DMATxDscrTab, &Tx_Buff[0][0], ETH_TXBUFNB); /* Initialize Rx Descriptors list: Chain Mode */ HAL_ETH_DMARxDescListInit(&heth, DMARxDscrTab, &Rx_Buff[0][0], ETH_RXBUFNB); #if LWIP_ARP || LWIP_ETHERNET /* set MAC hardware address length */ netif->hwaddr_len = ETHARP_HWADDR_LEN; /* set MAC hardware address */ netif->hwaddr[0] = heth.Init.MACAddr[0]; netif->hwaddr[1] = heth.Init.MACAddr[1]; netif->hwaddr[2] = heth.Init.MACAddr[2]; netif->hwaddr[3] = heth.Init.MACAddr[3]; netif->hwaddr[4] = heth.Init.MACAddr[4]; netif->hwaddr[5] = heth.Init.MACAddr[5]; /* maximum transfer unit */ netif->mtu = 1500; /* device capabilities */ /* don't set NETIF_FLAG_ETHARP if this device is not an ethernet one */ netif->flags |= NETIF_FLAG_BROADCAST | NETIF_FLAG_ETHARP; /* Enable MAC and DMA transmission and reception */ HAL_ETH_Start(&heth); /**** Configure PHY to generate an interrupt when Eth Link state changes ****/ /* Read Register Configuration */ HAL_ETH_ReadPHYRegister(&heth, PHY_MICR, ®value); regvalue |= (PHY_MICR_INT_EN | PHY_MICR_INT_OE); /* Enable Interrupts */ HAL_ETH_WritePHYRegister(&heth, PHY_MICR, regvalue); /* Read Register Configuration */ HAL_ETH_ReadPHYRegister(&heth, PHY_MISR, ®value); regvalue |= PHY_MISR_LINK_INT_EN; /* Enable Interrupt on change of link status */ HAL_ETH_WritePHYRegister(&heth, PHY_MISR, regvalue); #endif } /** * This function should do the actual transmission of the packet. The packet is * contained in the pbuf that is passed to the function. This pbuf * might be chained. * * @param netif the lwip network interface structure for this ethernetif * @param p the MAC packet to send (e.g. IP packet including MAC addresses and type) * @return ERR_OK if the packet could be sent * an err_t value if the packet couldn't be sent * * @note Returning ERR_MEM here if a DMA queue of your MAC is full can lead to * strange results. You might consider waiting for space in the DMA queue * to become availale since the stack doesn't retry to send a packet * dropped because of memory failure (except for the TCP timers). */ static err_t stm32f4_low_level_output(struct netif *netif, struct pbuf *p) { err_t errval; struct pbuf *q; uint8_t *buffer = (uint8_t*)(heth.TxDesc->Buffer1Addr); __IO ETH_DMADescTypeDef *DmaTxDesc; uint32_t framelength = 0; uint32_t bufferoffset = 0; uint32_t byteslefttocopy = 0; uint32_t payloadoffset = 0; DmaTxDesc = heth.TxDesc; bufferoffset = 0; sys_mutex_lock(&tx_lock_mutex); /* copy frame from pbufs to driver buffers */ for (q = p; q != NULL; q = q->next) { /* Is this buffer available? If not, goto error */ if ((DmaTxDesc->Status & ETH_DMATXDESC_OWN) != (uint32_t)RESET) { errval = ERR_USE; goto error; } /* Get bytes in current lwIP buffer */ byteslefttocopy = q->len; payloadoffset = 0; /* Check if the length of data to copy is bigger than Tx buffer size*/ while ((byteslefttocopy + bufferoffset) > ETH_TX_BUF_SIZE) { /* Copy data to Tx buffer*/ memcpy((uint8_t*)((uint8_t*)buffer + bufferoffset), (uint8_t*)((uint8_t*)q->payload + payloadoffset), (ETH_TX_BUF_SIZE - bufferoffset)); /* Point to next descriptor */ DmaTxDesc = (ETH_DMADescTypeDef*)(DmaTxDesc->Buffer2NextDescAddr); /* Check if the buffer is available */ if ((DmaTxDesc->Status & ETH_DMATXDESC_OWN) != (uint32_t)RESET) { errval = ERR_USE; goto error; } buffer = (uint8_t*)(DmaTxDesc->Buffer1Addr); byteslefttocopy = byteslefttocopy - (ETH_TX_BUF_SIZE - bufferoffset); payloadoffset = payloadoffset + (ETH_TX_BUF_SIZE - bufferoffset); framelength = framelength + (ETH_TX_BUF_SIZE - bufferoffset); bufferoffset = 0; } /* Copy the remaining bytes */ memcpy((uint8_t*)((uint8_t*)buffer + bufferoffset), (uint8_t*)((uint8_t*)q->payload + payloadoffset), byteslefttocopy); bufferoffset = bufferoffset + byteslefttocopy; framelength = framelength + byteslefttocopy; } /* Prepare transmit descriptors to give to DMA */ HAL_ETH_TransmitFrame(&heth, framelength); errval = ERR_OK; error: /* When Transmit Underflow flag is set, clear it and issue a Transmit Poll Demand to resume transmission */ if ((heth.Instance->DMASR & ETH_DMASR_TUS) != (uint32_t)RESET) { /* Clear TUS ETHERNET DMA flag */ heth.Instance->DMASR = ETH_DMASR_TUS; /* Resume DMA transmission*/ heth.Instance->DMATPDR = 0; } sys_mutex_unlock(&tx_lock_mutex); return errval; } /** * Should allocate a pbuf and transfer the bytes of the incoming * packet from the interface into the pbuf. * * @param netif the lwip network interface structure for this ethernetif * @return a pbuf filled with the received packet (including MAC header) * NULL on memory error */ static struct pbuf * stm32f4_low_level_input(struct netif *netif) { struct pbuf *p = NULL; struct pbuf *q; uint16_t len = 0; uint8_t *buffer; __IO ETH_DMADescTypeDef *dmarxdesc; uint32_t bufferoffset = 0; uint32_t payloadoffset = 0; uint32_t byteslefttocopy = 0; uint32_t i = 0; /* get received frame */ if (HAL_ETH_GetReceivedFrame(&heth) != HAL_OK) return NULL; /* Obtain the size of the packet and put it into the "len" variable. */ len = heth.RxFrameInfos.length; buffer = (uint8_t*)heth.RxFrameInfos.buffer; if (len > 0) { /* We allocate a pbuf chain of pbufs from the Lwip buffer pool */ p = pbuf_alloc(PBUF_RAW, len, PBUF_POOL); } if (p != NULL) { dmarxdesc = heth.RxFrameInfos.FSRxDesc; bufferoffset = 0; for (q = p; q != NULL; q = q->next) { byteslefttocopy = q->len; payloadoffset = 0; /* Check if the length of bytes to copy in current pbuf is bigger than Rx buffer size*/ while ((byteslefttocopy + bufferoffset) > ETH_RX_BUF_SIZE) { /* Copy data to pbuf */ memcpy((uint8_t*)((uint8_t*)q->payload + payloadoffset), (uint8_t*)((uint8_t*)buffer + bufferoffset), (ETH_RX_BUF_SIZE - bufferoffset)); /* Point to next descriptor */ dmarxdesc = (ETH_DMADescTypeDef*)(dmarxdesc->Buffer2NextDescAddr); buffer = (uint8_t*)(dmarxdesc->Buffer1Addr); byteslefttocopy = byteslefttocopy - (ETH_RX_BUF_SIZE - bufferoffset); payloadoffset = payloadoffset + (ETH_RX_BUF_SIZE - bufferoffset); bufferoffset = 0; } /* Copy remaining data in pbuf */ memcpy((uint8_t*)((uint8_t*)q->payload + payloadoffset), (uint8_t*)((uint8_t*)buffer + bufferoffset), byteslefttocopy); bufferoffset = bufferoffset + byteslefttocopy; } /* Release descriptors to DMA */ /* Point to first descriptor */ dmarxdesc = heth.RxFrameInfos.FSRxDesc; /* Set Own bit in Rx descriptors: gives the buffers back to DMA */ for (i = 0; i < heth.RxFrameInfos.SegCount; i++) { dmarxdesc->Status |= ETH_DMARXDESC_OWN; dmarxdesc = (ETH_DMADescTypeDef*)(dmarxdesc->Buffer2NextDescAddr); } /* Clear Segment_Count */ heth.RxFrameInfos.SegCount = 0; } /* When Rx Buffer unavailable flag is set: clear it and resume reception */ if ((heth.Instance->DMASR & ETH_DMASR_RBUS) != (uint32_t)RESET) { /* Clear RBUS ETHERNET DMA flag */ heth.Instance->DMASR = ETH_DMASR_RBUS; /* Resume DMA reception */ heth.Instance->DMARPDR = 0; } return p; } /** * This task receives input data * * \param[in] netif the lwip network interface structure */ static void stm32f4_rx_task(void *arg) { struct netif *netif = (struct netif*)arg; struct pbuf *p; while (1) { sys_arch_sem_wait(&rx_ready_sem, 0); p = stm32f4_low_level_input(netif); if (p != NULL) { if (netif->input(p, netif) != ERR_OK) { pbuf_free(p); p = NULL; } } } } /** * This task checks phy link status and updates net status * * \param[in] netif the lwip network interface structure */ static void stm32f4_phy_task(void *arg) { struct netif *netif = (struct netif*)arg; uint32_t phy_status = 0; while (1) { uint32_t status; if (HAL_ETH_ReadPHYRegister(&heth, PHY_SR, &status) == HAL_OK) { if ((status & PHY_LINK_STATUS) && !(phy_status & PHY_LINK_STATUS)) { tcpip_callback_with_block((tcpip_callback_fn)netif_set_link_up, (void*) netif, 1); } else if (!(status & PHY_LINK_STATUS) && (phy_status & PHY_LINK_STATUS)) { tcpip_callback_with_block((tcpip_callback_fn)netif_set_link_down, (void*) netif, 1); } phy_status = status; } osDelay(PHY_TASK_WAIT); } } /** * This function is the ethernet packet send function. It calls * etharp_output after checking link status. * * \param[in] netif the lwip network interface structure for this lpc_enetif * \param[in] q Pointer to pbug to send * \param[in] ipaddr IP address * \return ERR_OK or error code */ static err_t stm32f4_etharp_output(struct netif *netif, struct pbuf *q, ip_addr_t *ipaddr) { /* Only send packet is link is up */ if (netif->flags & NETIF_FLAG_LINK_UP) { return etharp_output(netif, q, ipaddr); } return ERR_CONN; } /** * Should be called at the beginning of the program to set up the * network interface. * * This function should be passed as a parameter to netif_add(). * * @param[in] netif the lwip network interface structure for this lpc_enetif * @return ERR_OK if the loopif is initialized * ERR_MEM if private data couldn't be allocated * any other err_t on error */ err_t eth_arch_enetif_init(struct netif *netif) { /* set MAC hardware address */ netif->hwaddr_len = ETHARP_HWADDR_LEN; /* maximum transfer unit */ netif->mtu = 1500; /* device capabilities */ netif->flags = NETIF_FLAG_BROADCAST | NETIF_FLAG_ETHARP | NETIF_FLAG_ETHERNET | NETIF_FLAG_IGMP; #if LWIP_NETIF_HOSTNAME /* Initialize interface hostname */ netif->hostname = "lwipstm32f4"; #endif /* LWIP_NETIF_HOSTNAME */ netif->name[0] = 'e'; netif->name[1] = 'n'; netif->output = stm32f4_etharp_output; netif->linkoutput = stm32f4_low_level_output; /* semaphore */ sys_sem_new(&rx_ready_sem, 0); sys_mutex_new(&tx_lock_mutex); /* task */ sys_thread_new("stm32f4_recv_task", stm32f4_rx_task, netif, DEFAULT_THREAD_STACKSIZE, RECV_TASK_PRI); sys_thread_new("stm32f4_phy_task", stm32f4_phy_task, netif, DEFAULT_THREAD_STACKSIZE, PHY_TASK_PRI); /* initialize the hardware */ stm32f4_low_level_init(netif); return ERR_OK; } void eth_arch_enable_interrupts(void) { HAL_NVIC_SetPriorityGrouping(NVIC_PRIORITYGROUP_4); HAL_NVIC_SetPriority(ETH_IRQn, 0, 0); HAL_NVIC_EnableIRQ(ETH_IRQn); } void eth_arch_disable_interrupts(void) { NVIC_DisableIRQ(ETH_IRQn); } /** * @} */ /* --------------------------------- End Of File ------------------------------ */ ================================================ FILE: Zelig/lwip/lwip-sys/arch/cc.h ================================================ /* * Copyright (c) 2001-2003 Swedish Institute of Computer Science. * All rights reserved. * * Redistribution and use in source and binary forms, with or without modification, * are permitted provided that the following conditions are met: * * 1. Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * 3. The name of the author may not be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT * SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT * OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING * IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY * OF SUCH DAMAGE. * * This file is part of the lwIP TCP/IP stack. * * Author: Adam Dunkels * */ #ifndef __CC_H__ #define __CC_H__ #include /* Types based on stdint.h */ typedef uint8_t u8_t; typedef int8_t s8_t; typedef uint16_t u16_t; typedef int16_t s16_t; typedef uint32_t u32_t; typedef int32_t s32_t; typedef uintptr_t mem_ptr_t; /* Define (sn)printf formatters for these lwIP types */ #define U16_F "hu" #define S16_F "hd" #define X16_F "hx" #define U32_F "lu" #define S32_F "ld" #define X32_F "lx" #define SZT_F "uz" /* ARM/LPC17xx is little endian only */ #define BYTE_ORDER LITTLE_ENDIAN /* Use LWIP error codes */ #define LWIP_PROVIDE_ERRNO #if defined(__arm__) && defined(__ARMCC_VERSION) /* Keil uVision4 tools */ #define PACK_STRUCT_BEGIN __packed #define PACK_STRUCT_STRUCT #define PACK_STRUCT_END #define PACK_STRUCT_FIELD(fld) fld #define ALIGNED(n) __align(n) #elif defined (__IAR_SYSTEMS_ICC__) /* IAR Embedded Workbench tools */ #define PACK_STRUCT_BEGIN __packed #define PACK_STRUCT_STRUCT #define PACK_STRUCT_END #define PACK_STRUCT_FIELD(fld) fld #define IAR_STR(a) #a #define ALIGNED(n) _Pragma(IAR_STR(data_alignment= ## n ##)) #else /* GCC tools (CodeSourcery) */ #define PACK_STRUCT_BEGIN #define PACK_STRUCT_STRUCT __attribute__ ((__packed__)) #define PACK_STRUCT_END #define PACK_STRUCT_FIELD(fld) fld #define ALIGNED(n) __attribute__((aligned (n))) #endif /* Provide Thumb-2 routines for GCC to improve performance */ #if defined(TOOLCHAIN_GCC) && defined(__thumb2__) #define MEMCPY(dst,src,len) thumb2_memcpy(dst,src,len) #define LWIP_CHKSUM thumb2_checksum /* Set algorithm to 0 so that unused lwip_standard_chksum function doesn't generate compiler warning */ #define LWIP_CHKSUM_ALGORITHM 0 void* thumb2_memcpy(void* pDest, const void* pSource, size_t length); u16_t thumb2_checksum(void* pData, int length); #else /* Used with IP headers only */ #define LWIP_CHKSUM_ALGORITHM 1 #endif #ifdef LWIP_DEBUG #include "stdio.h" void assert_printf(char *msg, int line, char *file); /* Plaform specific diagnostic output */ #define LWIP_PLATFORM_DIAG(vars) printf vars #define LWIP_PLATFORM_ASSERT(flag) { assert_printf((flag), __LINE__, __FILE__); } #else #define LWIP_PLATFORM_DIAG(msg) { ; } #define LWIP_PLATFORM_ASSERT(flag) { ; } #endif #include "cmsis.h" #define LWIP_PLATFORM_HTONS(x) __REV16(x) #define LWIP_PLATFORM_HTONL(x) __REV(x) #endif /* __CC_H__ */ ================================================ FILE: Zelig/lwip/lwip-sys/arch/checksum.c ================================================ /* Copyright (C) 2013 - Adam Green (https://github.com/adamgreen) 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. */ #if defined(TOOLCHAIN_GCC) && defined(__thumb2__) /* This is a hand written Thumb-2 assembly language version of the algorithm 3 version of lwip_standard_chksum in lwIP's inet_chksum.c. It performs the checksumming 32-bits at a time and even unrolls the loop to perform two of these 32-bit adds per loop iteration. Returns: 16-bit 1's complement summation (not inversed). NOTE: This function does return a uint16_t from the assembly language code but is marked as void so that GCC doesn't issue warning because it doesn't know about this low level return. */ __attribute__((naked)) void /*uint16_t*/ thumb2_checksum(const void* pData, int length) { __asm ( ".syntax unified\n" ".thumb\n" // Push non-volatile registers we use on stack. Push link register too to // keep stack 8-byte aligned and allow single pop to restore and return. " push {r4, lr}\n" // Initialize sum, r2, to 0. " movs r2, #0\n" // Remember whether pData was at odd address in r3. This is used later to // know if it needs to swap the result since the summation will be done at // an offset of 1, rather than 0. " ands r3, r0, #1\n" // Need to 2-byte align? If not skip ahead. " beq 1$\n" // We can return if there are no bytes to sum. " cbz r1, 9$\n" // 2-byte align. // Place the first data byte in odd summation location since it needs to be // swapped later. It's ok to overwrite r2 here as it only had a value of 0 // up until now. Advance r0 pointer and decrement r1 length as we go. " ldrb r2, [r0], #1\n" " lsls r2, r2, #8\n" " subs r1, r1, #1\n" // Need to 4-byte align? If not skip ahead. "1$:\n" " ands r4, r0, #3\n" " beq 2$\n" // Have more than 1 byte left to align? If not skip ahead to take care of // trailing byte. " cmp r1, #2\n" " blt 7$\n" // 4-byte align. " ldrh r4, [r0], #2\n" " adds r2, r2, r4\n" " subs r1, r1, #2\n" // Main summing loop which sums up data 2 words at a time. // Make sure that we have more than 7 bytes left to sum. "2$:\n" " cmp r1, #8\n" " blt 3$\n" // Sum next two words. Applying previous upper 16-bit carry to // lower 16-bits. " ldr r4, [r0], #4\n" " adds r2, r4\n" " adc r2, r2, #0\n" " ldr r4, [r0], #4\n" " adds r2, r4\n" " adc r2, r2, #0\n" " subs r1, r1, #8\n" " b 2$\n" // Sum up any remaining half-words. "3$:\n" // Make sure that we have more than 1 byte left to sum. " cmp r1, #2\n" " blt 7$\n" // Sum up next half word, continue to apply carry. " ldrh r4, [r0], #2\n" " adds r2, r4\n" " adc r2, r2, #0\n" " subs r1, r1, #2\n" " b 3$\n" // Handle trailing byte, if it exists "7$:\n" " cbz r1, 8$\n" " ldrb r4, [r0]\n" " adds r2, r4\n" " adc r2, r2, #0\n" // Fold 32-bit checksum into 16-bit checksum. "8$:\n" " ubfx r4, r2, #16, #16\n" " ubfx r2, r2, #0, #16\n" " adds r2, r4\n" " ubfx r4, r2, #16, #16\n" " ubfx r2, r2, #0, #16\n" " adds r2, r4\n" // Swap bytes if started at odd address " cbz r3, 9$\n" " rev16 r2, r2\n" // Return final sum. "9$: mov r0, r2\n" " pop {r4, pc}\n" ); } #endif ================================================ FILE: Zelig/lwip/lwip-sys/arch/memcpy.c ================================================ /* Copyright (C) 2013 - Adam Green (https://github.com/adamgreen) 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. */ #if defined(TOOLCHAIN_GCC) && defined(__thumb2__) #include /* This is a hand written Thumb-2 assembly language version of the standard C memcpy() function that can be used by the lwIP networking stack to improve its performance. It copies 4 bytes at a time and unrolls the loop to perform 4 of these copies per loop iteration. */ __attribute__((naked)) void thumb2_memcpy(void* pDest, const void* pSource, size_t length) { __asm ( ".syntax unified\n" ".thumb\n" // Copy 16 bytes at a time first. " lsrs r3, r2, #4\n" " beq.n 2$\n" "1$: ldr r12, [r1], #4\n" " str r12, [r0], #4\n" " ldr r12, [r1], #4\n" " str r12, [r0], #4\n" " ldr r12, [r1], #4\n" " str r12, [r0], #4\n" " ldr r12, [r1], #4\n" " str r12, [r0], #4\n" " subs r3, #1\n" " bne 1$\n" // Copy byte by byte for what is left. "2$:\n" " ands r3, r2, #0xf\n" " beq.n 4$\n" "3$: ldrb r12, [r1], #1\n" " strb r12, [r0], #1\n" " subs r3, #1\n" " bne 3$\n" // Return to caller. "4$: bx lr\n" ); } #endif ================================================ FILE: Zelig/lwip/lwip-sys/arch/perf.h ================================================ /* * Copyright (c) 2001-2003 Swedish Institute of Computer Science. * All rights reserved. * * Redistribution and use in source and binary forms, with or without modification, * are permitted provided that the following conditions are met: * * 1. Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * 3. The name of the author may not be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT * SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT * OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING * IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY * OF SUCH DAMAGE. * * This file is part of the lwIP TCP/IP stack. * * Author: Adam Dunkels * */ #ifndef __PERF_H__ #define __PERF_H__ #define PERF_START /* null definition */ #define PERF_STOP(x) /* null definition */ #endif /* __PERF_H__ */ ================================================ FILE: Zelig/lwip/lwip-sys/arch/sys_arch.c ================================================ /* Copyright (C) 2012 mbed.org, MIT License * * Permission is hereby granted, free of charge, to any person obtaining a copy of this software * and associated documentation files (the "Software"), to deal in the Software without restriction, * including without limitation the rights to use, copy, modify, merge, publish, distribute, * sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all copies or * substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING * BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, * DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ #include /* mbed includes */ #include "mbed_error.h" #include "mbed_interface.h" #include "us_ticker_api.h" /* lwIP includes. */ #include "lwip/opt.h" #include "lwip/debug.h" #include "lwip/def.h" #include "lwip/sys.h" #include "lwip/mem.h" #if NO_SYS==1 #include "cmsis.h" /* Saved total time in ms since timer was enabled */ static volatile u32_t systick_timems; /* Enable systick rate and interrupt */ void SysTick_Init(void) { if (SysTick_Config(SystemCoreClock / 1000)) { while (1); /* Capture error */ } } /** \brief SysTick IRQ handler and timebase management * * This function keeps a timebase for the sysTick that can be * used for other functions. It also calls an external function * (SysTick_User) that must be defined outside this handler. */ void SysTick_Handler(void) { systick_timems++; } /* Delay for the specified number of milliSeconds */ void osDelay(uint32_t ms) { uint32_t to = ms + systick_timems; while (to > systick_timems); } /* Returns the current time in mS. This is needed for the LWIP timers */ u32_t sys_now(void) { return (u32_t) systick_timems; } #else #define CMSIS_OS_LLILUM //-// #include "cmsis_os.h" /* CMSIS-RTOS implementation of the lwip operating system abstraction */ #include "arch/sys_arch.h" ////#include "sys_arch.h" ////#include "sys.h" #include "llos_system_timer.h" #include "llos_clock.h" #include "llos_error.h" uint32_t sys_uSeconds() { uint64_t frequency = LLOS_SYSTEM_TIMER_GetTimerFrequency( NULL ); uint64_t ticks = LLOS_SYSTEM_TIMER_GetTicks(NULL); return (uint32_t)((ticks * 1000000) / frequency); } /*---------------------------------------------------------------------------* * Routine: sys_mbox_new *---------------------------------------------------------------------------* * Description: * Creates a new mailbox * Inputs: * sys_mbox_t mbox -- Handle of mailbox * int queue_sz -- Size of elements in the mailbox * Outputs: * err_t -- ERR_OK if message posted, else ERR_MEM *---------------------------------------------------------------------------*/ err_t sys_mbox_new(sys_mbox_t *mbox, int queue_sz) { if (queue_sz > MB_SIZE) error("sys_mbox_new size error\n"); #ifdef CMSIS_OS_LLILUM //memset(mbox->queue, 0, sizeof(mbox->queue)); //mbox->def.pool = mbox->queue; mbox->def.queue_sz = queue_sz; #endif mbox->id = osMessageCreate(&mbox->def, NULL); return (mbox->id == NULL) ? (ERR_MEM) : (ERR_OK); } /*---------------------------------------------------------------------------* * Routine: sys_mbox_free *---------------------------------------------------------------------------* * Description: * Deallocates a mailbox. If there are messages still present in the * mailbox when the mailbox is deallocated, it is an indication of a * programming error in lwIP and the developer should be notified. * Inputs: * sys_mbox_t *mbox -- Handle of mailbox *---------------------------------------------------------------------------*/ void sys_mbox_free(sys_mbox_t *mbox) { osEvent event = osMessageGet(mbox->id, 0); if (event.status == osEventMessage) error("sys_mbox_free error\n"); // // The lwIP port for K64F seems to never delete the message queue and // CMSIS-RTOS does not definte any way to delete a Message Queue either // We will add one of our own. // osMessageDelete(mbox->id); } /*---------------------------------------------------------------------------* * Routine: sys_mbox_post *---------------------------------------------------------------------------* * Description: * Post the "msg" to the mailbox. * Inputs: * sys_mbox_t mbox -- Handle of mailbox * void *msg -- Pointer to data to post *---------------------------------------------------------------------------*/ void sys_mbox_post(sys_mbox_t *mbox, void *msg) { if (osMessagePut(mbox->id, (uint32_t)msg, osWaitForever) != osOK) error("sys_mbox_post error\n"); } /*---------------------------------------------------------------------------* * Routine: sys_mbox_trypost *---------------------------------------------------------------------------* * Description: * Try to post the "msg" to the mailbox. Returns immediately with * error if cannot. * Inputs: * sys_mbox_t mbox -- Handle of mailbox * void *msg -- Pointer to data to post * Outputs: * err_t -- ERR_OK if message posted, else ERR_MEM * if not. *---------------------------------------------------------------------------*/ err_t sys_mbox_trypost(sys_mbox_t *mbox, void *msg) { osStatus status = osMessagePut(mbox->id, (uint32_t)msg, 0); return (status == osOK) ? (ERR_OK) : (ERR_MEM); } /*---------------------------------------------------------------------------* * Routine: sys_arch_mbox_fetch *---------------------------------------------------------------------------* * Description: * Blocks the thread until a message arrives in the mailbox, but does * not block the thread longer than "timeout" milliseconds (similar to * the sys_arch_sem_wait() function). The "msg" argument is a result * parameter that is set by the function (i.e., by doing "*msg = * ptr"). The "msg" parameter maybe NULL to indicate that the message * should be dropped. * * The return values are the same as for the sys_arch_sem_wait() function: * Number of milliseconds spent waiting or SYS_ARCH_TIMEOUT if there was a * timeout. * * Note that a function with a similar name, sys_mbox_fetch(), is * implemented by lwIP. * Inputs: * sys_mbox_t mbox -- Handle of mailbox * void **msg -- Pointer to pointer to msg received * u32_t timeout -- Number of milliseconds until timeout * Outputs: * u32_t -- SYS_ARCH_TIMEOUT if timeout, else number * of milliseconds until received. *---------------------------------------------------------------------------*/ u32_t sys_arch_mbox_fetch(sys_mbox_t *mbox, void **msg, u32_t timeout) { u32_t start = (u32_t)sys_uSeconds(); osEvent event = osMessageGet(mbox->id, (timeout != 0)?(timeout):(osWaitForever)); if (event.status != osEventMessage) return SYS_ARCH_TIMEOUT; *msg = (void *)event.value.v; return ((u32_t)sys_uSeconds() - start) / 1000; } /*---------------------------------------------------------------------------* * Routine: sys_arch_mbox_tryfetch *---------------------------------------------------------------------------* * Description: * Similar to sys_arch_mbox_fetch, but if message is not ready * immediately, we'll return with SYS_MBOX_EMPTY. On success, 0 is * returned. * Inputs: * sys_mbox_t mbox -- Handle of mailbox * void **msg -- Pointer to pointer to msg received * Outputs: * u32_t -- SYS_MBOX_EMPTY if no messages. Otherwise, * return ERR_OK. *---------------------------------------------------------------------------*/ u32_t sys_arch_mbox_tryfetch(sys_mbox_t *mbox, void **msg) { osEvent event = osMessageGet(mbox->id, 0); if (event.status != osEventMessage) return SYS_MBOX_EMPTY; *msg = (void *)event.value.v; return ERR_OK; } /*---------------------------------------------------------------------------* * Routine: sys_sem_new *---------------------------------------------------------------------------* * Description: * Creates and returns a new semaphore. The "ucCount" argument specifies * the initial state of the semaphore. * NOTE: Currently this routine only creates counts of 1 or 0 * Inputs: * sys_sem_t sem -- Handle of semaphore * u8_t count -- Initial count of semaphore * Outputs: * err_t -- ERR_OK if semaphore created *---------------------------------------------------------------------------*/ err_t sys_sem_new(sys_sem_t *sem, u8_t count) { #ifdef CMSIS_OS_LLILUM //memset(sem->data, 0, sizeof(uint32_t)*2); //sem->def.semaphore = sem->data; #endif sem->id = osSemaphoreCreate(&sem->def, count); if (sem->id == NULL) error("sys_sem_new create error\n"); return ERR_OK; } /*---------------------------------------------------------------------------* * Routine: sys_arch_sem_wait *---------------------------------------------------------------------------* * Description: * Blocks the thread while waiting for the semaphore to be * signaled. If the "timeout" argument is non-zero, the thread should * only be blocked for the specified time (measured in * milliseconds). * * If the timeout argument is non-zero, the return value is the number of * milliseconds spent waiting for the semaphore to be signaled. If the * semaphore wasn't signaled within the specified time, the return value is * SYS_ARCH_TIMEOUT. If the thread didn't have to wait for the semaphore * (i.e., it was already signaled), the function may return zero. * * Notice that lwIP implements a function with a similar name, * sys_sem_wait(), that uses the sys_arch_sem_wait() function. * Inputs: * sys_sem_t sem -- Semaphore to wait on * u32_t timeout -- Number of milliseconds until timeout * Outputs: * u32_t -- Time elapsed or SYS_ARCH_TIMEOUT. *---------------------------------------------------------------------------*/ u32_t sys_arch_sem_wait(sys_sem_t *sem, u32_t timeout) { u32_t start = (u32_t)sys_uSeconds(); if (osSemaphoreWait(sem->id, (timeout != 0)?(timeout):(osWaitForever)) < 1) return SYS_ARCH_TIMEOUT; return ((u32_t)sys_uSeconds() - start) / 1000; } /*---------------------------------------------------------------------------* * Routine: sys_sem_signal *---------------------------------------------------------------------------* * Description: * Signals (releases) a semaphore * Inputs: * sys_sem_t sem -- Semaphore to signal *---------------------------------------------------------------------------*/ void sys_sem_signal(sys_sem_t *data) { if (osSemaphoreRelease(data->id) != osOK) LLOS_Die(); /* Can be called by ISR do not use printf */ } /*---------------------------------------------------------------------------* * Routine: sys_sem_free *---------------------------------------------------------------------------* * Description: * Deallocates a semaphore * Inputs: * sys_sem_t sem -- Semaphore to free *---------------------------------------------------------------------------*/ void sys_sem_free(sys_sem_t *sem) { osSemaphoreDelete(sem->id); } /** Create a new mutex * @param mutex pointer to the mutex to create * @return a new mutex */ err_t sys_mutex_new(sys_mutex_t *mutex) { #ifdef CMSIS_OS_LLILUM #ifdef __MBED_CMSIS_RTOS_CA9 memset(mutex->data, 0, sizeof(int32_t)*4); #else //memset(mutex->data, 0, sizeof(int32_t)*3); #endif //mutex->def.mutex = mutex->data; #endif mutex->id = osMutexCreate(&mutex->def); if (mutex->id == NULL) return ERR_MEM; return ERR_OK; } /** Lock a mutex * @param mutex the mutex to lock */ void sys_mutex_lock(sys_mutex_t *mutex) { if (osMutexWait(mutex->id, osWaitForever) != osOK) error("sys_mutex_lock error\n"); } /** Unlock a mutex * @param mutex the mutex to unlock */ void sys_mutex_unlock(sys_mutex_t *mutex) { if (osMutexRelease(mutex->id) != osOK) error("sys_mutex_unlock error\n"); } /** Delete a mutex * @param mutex the mutex to delete */ void sys_mutex_free(sys_mutex_t *mutex) {} /*---------------------------------------------------------------------------* * Routine: sys_init *---------------------------------------------------------------------------* * Description: * Initialize sys arch *---------------------------------------------------------------------------*/ osMutexId lwip_sys_mutex; osMutexDef(lwip_sys_mutex); void sys_init(void) { lwip_sys_mutex = osMutexCreate(osMutex(lwip_sys_mutex)); if (lwip_sys_mutex == NULL) error("sys_init error\n"); } /*---------------------------------------------------------------------------* * Routine: sys_jiffies *---------------------------------------------------------------------------* * Description: * Used by PPP as a timestamp-ish value *---------------------------------------------------------------------------*/ u32_t sys_jiffies(void) { static u32_t jiffies = 0; // Modified to use sys_now jiffies += 1 + (sys_now() / 10); return jiffies; } /*---------------------------------------------------------------------------* * Routine: sys_arch_protect *---------------------------------------------------------------------------* * Description: * This optional function does a "fast" critical region protection and * returns the previous protection level. This function is only called * during very short critical regions. An embedded system which supports * ISR-based drivers might want to implement this function by disabling * interrupts. Task-based systems might want to implement this by using * a mutex or disabling tasking. This function should support recursive * calls from the same task or interrupt. In other words, * sys_arch_protect() could be called while already protected. In * that case the return value indicates that it is already protected. * * sys_arch_protect() is only required if your port is supporting an * operating system. * Outputs: * sys_prot_t -- Previous protection level (not used here) *---------------------------------------------------------------------------*/ sys_prot_t sys_arch_protect(void) { if (osMutexWait(lwip_sys_mutex, osWaitForever) != osOK) error("sys_arch_protect error\n"); return (sys_prot_t)1; } /*---------------------------------------------------------------------------* * Routine: sys_arch_unprotect *---------------------------------------------------------------------------* * Description: * This optional function does a "fast" set of critical region * protection to the value specified by pval. See the documentation for * sys_arch_protect() for more information. This function is only * required if your port is supporting an operating system. * Inputs: * sys_prot_t -- Previous protection level (not used here) *---------------------------------------------------------------------------*/ void sys_arch_unprotect(sys_prot_t p) { if (osMutexRelease(lwip_sys_mutex) != osOK) error("sys_arch_unprotect error\n"); } u32_t sys_now(void) { return sys_uSeconds() / 1000; } void sys_msleep(u32_t ms) { osDelay(ms); } // Keep a pool of thread structures static int thread_pool_index = 0; static sys_thread_data_t thread_pool[SYS_THREAD_POOL_N]; /*---------------------------------------------------------------------------* * Routine: sys_thread_new *---------------------------------------------------------------------------* * Description: * Starts a new thread with priority "prio" that will begin its * execution in the function "thread()". The "arg" argument will be * passed as an argument to the thread() function. The id of the new * thread is returned. Both the id and the priority are system * dependent. * Inputs: * char *name -- Name of thread * void (*thread)(void *arg) -- Pointer to function to run. * void *arg -- Argument passed into function * int stacksize -- Required stack amount in bytes * int priority -- Thread priority * Outputs: * sys_thread_t -- Pointer to thread handle. *---------------------------------------------------------------------------*/ sys_thread_t sys_thread_new(const char *pcName, void (*thread)(void *arg), void *arg, int stacksize, int priority) { LWIP_DEBUGF(SYS_DEBUG, ("New Thread: %s\n", pcName)); if (thread_pool_index >= SYS_THREAD_POOL_N) error("sys_thread_new number error\n"); sys_thread_t t = (sys_thread_t)&thread_pool[thread_pool_index]; thread_pool_index++; #ifdef CMSIS_OS_LLILUM t->def.pthread = (os_pthread)thread; t->def.tpriority = (osPriority)priority; t->def.stacksize = stacksize; //t->def.stack_pointer = (uint32_t*)malloc(stacksize); // if (t->def.stack_pointer == NULL) { // error("Error allocating the stack memory"); // } #endif t->id = osThreadCreate(&t->def, arg); if (t->id == NULL) error("sys_thread_new create error\n"); return t; } #undef CMSIS_OS_LLILUM #endif void LLOS_lwIPTaskRun( void* codePtr, void* arg ) { os_pthread func = (os_pthread)codePtr; func( arg ); } osEvent osWait(uint32_t millisec) { osEvent ev; osWaitEx(millisec, &ev); return ev; } osEvent osMessageGet(osMessageQId queue_id, uint32_t millisec) { osEvent ev; osMessageGetEx(queue_id, millisec, &ev); return ev; } int32_t osSemaphoreWait(osSemaphoreId semaphore_id, uint32_t millisec) { return osSemaphoreWaitEx(semaphore_id, millisec) + 1; } #ifdef LWIP_DEBUG /** \brief Displays an error message on assertion This function will display an error message on an assertion to the debug output. \param[in] msg Error message to display \param[in] line Line number in file with error \param[in] file Filename with error */ void assert_printf(char *msg, int line, char *file) { if (msg) error("%s:%d in file %s\n", msg, line, file); else error("LWIP ASSERT\n"); } #else void assert_printf(char *msg, int line, char *file) { // do nothing } #endif /* LWIP_DEBUG */ ================================================ FILE: Zelig/lwip/lwip-sys/arch/sys_arch.h ================================================ /* Copyright (C) 2012 mbed.org, MIT License * * Permission is hereby granted, free of charge, to any person obtaining a copy of this software * and associated documentation files (the "Software"), to deal in the Software without restriction, * including without limitation the rights to use, copy, modify, merge, publish, distribute, * sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all copies or * substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING * BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, * DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ #ifndef __ARCH_SYS_ARCH_H__ #define __ARCH_SYS_ARCH_H__ #include "lwip/opt.h" #if NO_SYS == 0 #ifdef __cplusplus extern "C" { #endif // === SEMAPHORE === typedef struct { osSemaphoreId id; osSemaphoreDef_t def; #ifdef CMSIS_OS_RTX uint32_t data[2]; #endif } sys_sem_t; #ifdef __cplusplus } #endif #define osPriorityNormal (0) #include "cmsis_os.h" #define sys_sem_valid(x) (((*x).id == NULL) ? 0 : 1) #define sys_sem_set_invalid(x) ( (*x).id = NULL) // === MUTEX === typedef struct { osMutexId id; osMutexDef_t def; #ifdef CMSIS_OS_RTX #ifdef __MBED_CMSIS_RTOS_CA9 int32_t data[4]; #else int32_t data[3]; #endif #endif } sys_mutex_t; // === MAIL BOX === #define MB_SIZE 8 typedef struct { osMessageQId id; osMessageQDef_t def; #ifdef CMSIS_OS_RTX uint32_t queue[4+MB_SIZE]; /* The +4 is required for RTX OS_MCB overhead. */ #endif } sys_mbox_t; #define SYS_MBOX_NULL ((uint32_t) NULL) #define sys_mbox_valid(x) (((*x).id == NULL) ? 0 : 1 ) #define sys_mbox_set_invalid(x) ( (*x).id = NULL ) #if ((DEFAULT_RAW_RECVMBOX_SIZE) > (MB_SIZE)) || \ ((DEFAULT_UDP_RECVMBOX_SIZE) > (MB_SIZE)) || \ ((DEFAULT_TCP_RECVMBOX_SIZE) > (MB_SIZE)) || \ ((DEFAULT_ACCEPTMBOX_SIZE) > (MB_SIZE)) || \ ((TCPIP_MBOX_SIZE) > (MB_SIZE)) # error Mailbox size not supported #endif // === THREAD === typedef struct { osThreadId id; osThreadDef_t def; } sys_thread_data_t; typedef sys_thread_data_t* sys_thread_t; #define SYS_THREAD_POOL_N 6 #define SYS_DEFAULT_THREAD_STACK_DEPTH DEFAULT_STACK_SIZE // === PROTECTION === typedef int sys_prot_t; #else #ifdef __cplusplus extern "C" { #endif /** \brief Init systick to 1ms rate * * This init the systick to 1ms rate. This function is only used in standalone * systems. */ void SysTick_Init(void); /** \brief Get the current systick time in milliSeconds * * Returns the current systick time in milliSeconds. This function is only * used in standalone systems. * * /returns current systick time in milliSeconds */ uint32_t SysTick_GetMS(void); /** \brief Delay for the specified number of milliSeconds * * For standalone systems. This function will block for the specified * number of milliSconds. For RTOS based systems, this function will delay * the task by the specified number of milliSeconds. * * \param[in] ms Time in milliSeconds to delay */ #ifdef __cplusplus } #endif #endif #endif /* __ARCH_SYS_ARCH_H__ */ ================================================ FILE: Zelig/mbed/AnalogIn.h ================================================ /* mbed Microcontroller Library * Copyright (c) 2006-2013 ARM Limited * * 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 MBED_ANALOGIN_H #define MBED_ANALOGIN_H #include "platform.h" #if DEVICE_ANALOGIN #include "analogin_api.h" namespace mbed { /** An analog input, used for reading the voltage on a pin * * Example: * @code * // Print messages when the AnalogIn is greater than 50% * * #include "mbed.h" * * AnalogIn temperature(p20); * * int main() { * while(1) { * if(temperature > 0.5) { * printf("Too hot! (%f)", temperature.read()); * } * } * } * @endcode */ class AnalogIn { public: /** Create an AnalogIn, connected to the specified pin * * @param pin AnalogIn pin to connect to * @param name (optional) A string to identify the object */ AnalogIn(PinName pin) { analogin_init(&_adc, pin); } /** Read the input voltage, represented as a float in the range [0.0, 1.0] * * @returns A floating-point value representing the current input voltage, measured as a percentage */ float read() { return analogin_read(&_adc); } /** Read the input voltage, represented as an unsigned short in the range [0x0, 0xFFFF] * * @returns * 16-bit unsigned short representing the current input voltage, normalised to a 16-bit value */ unsigned short read_u16() { return analogin_read_u16(&_adc); } #ifdef MBED_OPERATORS /** An operator shorthand for read() * * The float() operator can be used as a shorthand for read() to simplify common code sequences * * Example: * @code * float x = volume.read(); * float x = volume; * * if(volume.read() > 0.25) { ... } * if(volume > 0.25) { ... } * @endcode */ operator float() { return read(); } #endif protected: analogin_t _adc; }; } // namespace mbed #endif #endif ================================================ FILE: Zelig/mbed/AnalogOut.h ================================================ /* mbed Microcontroller Library * Copyright (c) 2006-2013 ARM Limited * * 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 MBED_ANALOGOUT_H #define MBED_ANALOGOUT_H #include "platform.h" #if DEVICE_ANALOGOUT #include "analogout_api.h" namespace mbed { /** An analog output, used for setting the voltage on a pin * * Example: * @code * // Make a sawtooth output * * #include "mbed.h" * * AnalogOut tri(p18); * int main() { * while(1) { * tri = tri + 0.01; * wait_us(1); * if(tri == 1) { * tri = 0; * } * } * } * @endcode */ class AnalogOut { public: /** Create an AnalogOut connected to the specified pin * * @param AnalogOut pin to connect to (18) */ AnalogOut(PinName pin) { analogout_init(&_dac, pin); } /** Set the output voltage, specified as a percentage (float) * * @param value A floating-point value representing the output voltage, * specified as a percentage. The value should lie between * 0.0f (representing 0v / 0%) and 1.0f (representing 3.3v / 100%). * Values outside this range will be saturated to 0.0f or 1.0f. */ void write(float value) { analogout_write(&_dac, value); } /** Set the output voltage, represented as an unsigned short in the range [0x0, 0xFFFF] * * @param value 16-bit unsigned short representing the output voltage, * normalised to a 16-bit value (0x0000 = 0v, 0xFFFF = 3.3v) */ void write_u16(unsigned short value) { analogout_write_u16(&_dac, value); } /** Return the current output voltage setting, measured as a percentage (float) * * @returns * A floating-point value representing the current voltage being output on the pin, * measured as a percentage. The returned value will lie between * 0.0f (representing 0v / 0%) and 1.0f (representing 3.3v / 100%). * * @note * This value may not match exactly the value set by a previous write(). */ float read() { return analogout_read(&_dac); } #ifdef MBED_OPERATORS /** An operator shorthand for write() */ AnalogOut& operator= (float percent) { write(percent); return *this; } AnalogOut& operator= (AnalogOut& rhs) { write(rhs.read()); return *this; } /** An operator shorthand for read() */ operator float() { return read(); } #endif protected: dac_t _dac; }; } // namespace mbed #endif #endif ================================================ FILE: Zelig/mbed/BusIn.h ================================================ /* mbed Microcontroller Library * Copyright (c) 2006-2013 ARM Limited * * 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 MBED_BUSIN_H #define MBED_BUSIN_H #include "platform.h" #include "DigitalIn.h" namespace mbed { /** A digital input bus, used for reading the state of a collection of pins */ class BusIn { public: /* Group: Configuration Methods */ /** Create an BusIn, connected to the specified pins * * @param DigitalIn pin to connect to bus bit (p5-p30, NC) * * @note * It is only required to specify as many pin variables as is required * for the bus; the rest will default to NC (not connected) */ BusIn(PinName p0, PinName p1 = NC, PinName p2 = NC, PinName p3 = NC, PinName p4 = NC, PinName p5 = NC, PinName p6 = NC, PinName p7 = NC, PinName p8 = NC, PinName p9 = NC, PinName p10 = NC, PinName p11 = NC, PinName p12 = NC, PinName p13 = NC, PinName p14 = NC, PinName p15 = NC); BusIn(PinName pins[16]); virtual ~BusIn(); /** Read the value of the input bus * * @returns * An integer with each bit corresponding to the value read from the associated DigitalIn pin */ int read(); /** Set the input pin mode * * @param mode PullUp, PullDown, PullNone */ void mode(PinMode pull); /** Binary mask of bus pins connected to actual pins (not NC pins) * If bus pin is in NC state make corresponding bit will be cleared (set to 0), else bit will be set to 1 * * @returns * Binary mask of connected pins */ int mask() { return _nc_mask; } #ifdef MBED_OPERATORS /** A shorthand for read() */ operator int(); /** Access to particular bit in random-iterator fashion */ DigitalIn & operator[] (int index); #endif protected: DigitalIn* _pin[16]; /** Mask of bus's NC pins * If bit[n] is set to 1 - pin is connected * if bit[n] is cleared - pin is not connected (NC) */ int _nc_mask; /* disallow copy constructor and assignment operators */ private: BusIn(const BusIn&); BusIn & operator = (const BusIn&); }; } // namespace mbed #endif ================================================ FILE: Zelig/mbed/BusInOut.h ================================================ /* mbed Microcontroller Library * Copyright (c) 2006-2013 ARM Limited * * 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 MBED_BUSINOUT_H #define MBED_BUSINOUT_H #include "DigitalInOut.h" namespace mbed { /** A digital input output bus, used for setting the state of a collection of pins */ class BusInOut { public: /** Create an BusInOut, connected to the specified pins * * @param p DigitalInOut pin to connect to bus bit p (p5-p30, NC) * * @note * It is only required to specify as many pin variables as is required * for the bus; the rest will default to NC (not connected) */ BusInOut(PinName p0, PinName p1 = NC, PinName p2 = NC, PinName p3 = NC, PinName p4 = NC, PinName p5 = NC, PinName p6 = NC, PinName p7 = NC, PinName p8 = NC, PinName p9 = NC, PinName p10 = NC, PinName p11 = NC, PinName p12 = NC, PinName p13 = NC, PinName p14 = NC, PinName p15 = NC); BusInOut(PinName pins[16]); virtual ~BusInOut(); /* Group: Access Methods */ /** Write the value to the output bus * * @param value An integer specifying a bit to write for every corresponding DigitalInOut pin */ void write(int value); /** Read the value currently output on the bus * * @returns * An integer with each bit corresponding to associated DigitalInOut pin setting */ int read(); /** Set as an output */ void output(); /** Set as an input */ void input(); /** Set the input pin mode * * @param mode PullUp, PullDown, PullNone */ void mode(PinMode pull); /** Binary mask of bus pins connected to actual pins (not NC pins) * If bus pin is in NC state make corresponding bit will be cleared (set to 0), else bit will be set to 1 * * @returns * Binary mask of connected pins */ int mask() { return _nc_mask; } #ifdef MBED_OPERATORS /** A shorthand for write() */ BusInOut& operator= (int v); BusInOut& operator= (BusInOut& rhs); /** Access to particular bit in random-iterator fashion */ DigitalInOut& operator[] (int index); /** A shorthand for read() */ operator int(); #endif protected: DigitalInOut* _pin[16]; /** Mask of bus's NC pins * If bit[n] is set to 1 - pin is connected * if bit[n] is cleared - pin is not connected (NC) */ int _nc_mask; /* disallow copy constructor and assignment operators */ private: BusInOut(const BusInOut&); BusInOut & operator = (const BusInOut&); }; } // namespace mbed #endif ================================================ FILE: Zelig/mbed/BusOut.h ================================================ /* mbed Microcontroller Library * Copyright (c) 2006-2013 ARM Limited * * 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 MBED_BUSOUT_H #define MBED_BUSOUT_H #include "DigitalOut.h" namespace mbed { /** A digital output bus, used for setting the state of a collection of pins */ class BusOut { public: /** Create an BusOut, connected to the specified pins * * @param p DigitalOut pin to connect to bus bit (p5-p30, NC) * * @note * It is only required to specify as many pin variables as is required * for the bus; the rest will default to NC (not connected) */ BusOut(PinName p0, PinName p1 = NC, PinName p2 = NC, PinName p3 = NC, PinName p4 = NC, PinName p5 = NC, PinName p6 = NC, PinName p7 = NC, PinName p8 = NC, PinName p9 = NC, PinName p10 = NC, PinName p11 = NC, PinName p12 = NC, PinName p13 = NC, PinName p14 = NC, PinName p15 = NC); BusOut(PinName pins[16]); virtual ~BusOut(); /** Write the value to the output bus * * @param value An integer specifying a bit to write for every corresponding DigitalOut pin */ void write(int value); /** Read the value currently output on the bus * * @returns * An integer with each bit corresponding to associated DigitalOut pin setting */ int read(); /** Binary mask of bus pins connected to actual pins (not NC pins) * If bus pin is in NC state make corresponding bit will be cleared (set to 0), else bit will be set to 1 * * @returns * Binary mask of connected pins */ int mask() { return _nc_mask; } #ifdef MBED_OPERATORS /** A shorthand for write() */ BusOut& operator= (int v); BusOut& operator= (BusOut& rhs); /** Access to particular bit in random-iterator fashion */ DigitalOut& operator[] (int index); /** A shorthand for read() */ operator int(); #endif protected: DigitalOut* _pin[16]; /** Mask of bus's NC pins * If bit[n] is set to 1 - pin is connected * if bit[n] is cleared - pin is not connected (NC) */ int _nc_mask; /* disallow copy constructor and assignment operators */ private: BusOut(const BusOut&); BusOut & operator = (const BusOut&); }; } // namespace mbed #endif ================================================ FILE: Zelig/mbed/CAN.h ================================================ /* mbed Microcontroller Library * Copyright (c) 2006-2013 ARM Limited * * 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 MBED_CAN_H #define MBED_CAN_H #include "platform.h" #if DEVICE_CAN #include "can_api.h" #include "can_helper.h" #include "FunctionPointer.h" namespace mbed { /** CANMessage class */ class CANMessage : public CAN_Message { public: /** Creates empty CAN message. */ CANMessage() : CAN_Message() { len = 8; type = CANData; format = CANStandard; id = 0; memset(data, 0, 8); } /** Creates CAN message with specific content. */ CANMessage(int _id, const char *_data, char _len = 8, CANType _type = CANData, CANFormat _format = CANStandard) { len = _len & 0xF; type = _type; format = _format; id = _id; memcpy(data, _data, _len); } /** Creates CAN remote message. */ CANMessage(int _id, CANFormat _format = CANStandard) { len = 0; type = CANRemote; format = _format; id = _id; memset(data, 0, 8); } }; /** A can bus client, used for communicating with can devices */ class CAN { public: /** Creates an CAN interface connected to specific pins. * * @param rd read from transmitter * @param td transmit to transmitter * * Example: * @code * #include "mbed.h" * * Ticker ticker; * DigitalOut led1(LED1); * DigitalOut led2(LED2); * CAN can1(p9, p10); * CAN can2(p30, p29); * * char counter = 0; * * void send() { * if(can1.write(CANMessage(1337, &counter, 1))) { * printf("Message sent: %d\n", counter); * counter++; * } * led1 = !led1; * } * * int main() { * ticker.attach(&send, 1); * CANMessage msg; * while(1) { * if(can2.read(msg)) { * printf("Message received: %d\n\n", msg.data[0]); * led2 = !led2; * } * wait(0.2); * } * } * @endcode */ CAN(PinName rd, PinName td); virtual ~CAN(); /** Set the frequency of the CAN interface * * @param hz The bus frequency in hertz * * @returns * 1 if successful, * 0 otherwise */ int frequency(int hz); /** Write a CANMessage to the bus. * * @param msg The CANMessage to write. * * @returns * 0 if write failed, * 1 if write was successful */ int write(CANMessage msg); /** Read a CANMessage from the bus. * * @param msg A CANMessage to read to. * @param handle message filter handle (0 for any message) * * @returns * 0 if no message arrived, * 1 if message arrived */ int read(CANMessage &msg, int handle = 0); /** Reset CAN interface. * * To use after error overflow. */ void reset(); /** Puts or removes the CAN interface into silent monitoring mode * * @param silent boolean indicating whether to go into silent mode or not */ void monitor(bool silent); enum Mode { Reset = 0, Normal, Silent, LocalTest, GlobalTest, SilentTest }; /** Change CAN operation to the specified mode * * @param mode The new operation mode (CAN::Normal, CAN::Silent, CAN::LocalTest, CAN::GlobalTest, CAN::SilentTest) * * @returns * 0 if mode change failed or unsupported, * 1 if mode change was successful */ int mode(Mode mode); /** Filter out incomming messages * * @param id the id to filter on * @param mask the mask applied to the id * @param format format to filter on (Default CANAny) * @param handle message filter handle (Optional) * * @returns * 0 if filter change failed or unsupported, * new filter handle if successful */ int filter(unsigned int id, unsigned int mask, CANFormat format = CANAny, int handle = 0); /** Returns number of read errors to detect read overflow errors. */ unsigned char rderror(); /** Returns number of write errors to detect write overflow errors. */ unsigned char tderror(); enum IrqType { RxIrq = 0, TxIrq, EwIrq, DoIrq, WuIrq, EpIrq, AlIrq, BeIrq, IdIrq }; /** Attach a function to call whenever a CAN frame received interrupt is * generated. * * @param fptr A pointer to a void function, or 0 to set as none * @param event Which CAN interrupt to attach the member function to (CAN::RxIrq for message received, CAN::TxIrq for transmitted or aborted, CAN::EwIrq for error warning, CAN::DoIrq for data overrun, CAN::WuIrq for wake-up, CAN::EpIrq for error passive, CAN::AlIrq for arbitration lost, CAN::BeIrq for bus error) */ void attach(void (*fptr)(void), IrqType type=RxIrq); /** Attach a member function to call whenever a CAN frame received interrupt * is generated. * * @param tptr pointer to the object to call the member function on * @param mptr pointer to the member function to be called * @param event Which CAN interrupt to attach the member function to (CAN::RxIrq for message received, TxIrq for transmitted or aborted, EwIrq for error warning, DoIrq for data overrun, WuIrq for wake-up, EpIrq for error passive, AlIrq for arbitration lost, BeIrq for bus error) */ template void attach(T* tptr, void (T::*mptr)(void), IrqType type=RxIrq) { if((mptr != NULL) && (tptr != NULL)) { _irq[type].attach(tptr, mptr); can_irq_set(&_can, (CanIrqType)type, 1); } else { can_irq_set(&_can, (CanIrqType)type, 0); } } static void _irq_handler(uint32_t id, CanIrqType type); protected: can_t _can; FunctionPointer _irq[9]; }; } // namespace mbed #endif #endif // MBED_CAN_H ================================================ FILE: Zelig/mbed/CThunk.h ================================================ /* General C++ Object Thunking class * * - allows direct callbacks to non-static C++ class functions * - keeps track for the corresponding class instance * - supports an optional context parameter for the called function * - ideally suited for class object receiving interrupts (NVIC_SetVector) * * Copyright (c) 2014-2015 ARM Limited * * 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 __CTHUNK_H__ #define __CTHUNK_H__ #define CTHUNK_ADDRESS 1 #if defined(__CORTEX_M3) || defined(__CORTEX_M4) || defined(__thumb2__) #define CTHUNK_VARIABLES volatile uint32_t code[1] /** * CTHUNK disassembly for Cortex-M3/M4 (thumb2): * * ldm.w pc,{r0,r1,r2,pc} * * This instruction loads the arguments for the static thunking function to r0-r2, and * branches to that function by loading its address into PC. * * This is safe for both regular calling and interrupt calling, since it only touches scratch registers * which should be saved by the caller, and are automatically saved as part of the IRQ context switch. */ #define CTHUNK_ASSIGMENT m_thunk.code[0] = 0x8007E89F #elif defined(__CORTEX_M0PLUS) || defined(__CORTEX_M0) /* * CTHUNK disassembly for Cortex M0 (thumb): * * push {r0,r1,r2,r3,r4,lr} save touched registers and return address * * movs r4,#4 set up address to load arguments from (immediately following this code block) (1) * * add r4,pc set up address to load arguments from (immediately following this code block) (2) * * ldm r4!,{r0,r1,r2,r3} load arguments for static thunk function * * blx r3 call static thunk function * * pop {r0,r1,r2,r3,r4,pc} restore scratch registers and return from function */ #define CTHUNK_VARIABLES volatile uint32_t code[3] #define CTHUNK_ASSIGMENT do { \ m_thunk.code[0] = 0x2404B51F; \ m_thunk.code[1] = 0xCC0F447C; \ m_thunk.code[2] = 0xBD1F4798; \ } while (0) #else #error "Target is not currently suported." #endif /* IRQ/Exception compatible thunk entry function */ typedef void (*CThunkEntry)(void); template class CThunk { public: typedef void (T::*CCallbackSimple)(void); typedef void (T::*CCallback)(void* context); inline CThunk(T *instance) { init(instance, NULL, NULL); } inline CThunk(T *instance, CCallback callback) { init(instance, callback, NULL); } ~CThunk() { } inline CThunk(T *instance, CCallbackSimple callback) { init(instance, (CCallback)callback, NULL); } inline CThunk(T &instance, CCallback callback) { init(instance, callback, NULL); } inline CThunk(T &instance, CCallbackSimple callback) { init(instance, (CCallback)callback, NULL); } inline CThunk(T &instance, CCallback callback, void* context) { init(instance, callback, context); } inline void callback(CCallback callback) { m_callback = callback; } inline void callback(CCallbackSimple callback) { m_callback = (CCallback)callback; } inline void context(void* context) { m_thunk.context = (uint32_t)context; } inline void context(uint32_t context) { m_thunk.context = context; } inline uint32_t entry(void) { return (((uint32_t)&m_thunk)|CTHUNK_ADDRESS); } /* get thunk entry point for connecting rhunk to an IRQ table */ inline operator CThunkEntry(void) { return (CThunkEntry)entry(); } /* get thunk entry point for connecting rhunk to an IRQ table */ inline operator uint32_t(void) { return entry(); } /* simple test function */ inline void call(void) { (((CThunkEntry)(entry()))()); } private: T* m_instance; volatile CCallback m_callback; // TODO: this needs proper fix, to refactor toolchain header file and all its use // PACKED there is not defined properly for IAR #if defined (__ICCARM__) typedef __packed struct { CTHUNK_VARIABLES; volatile uint32_t instance; volatile uint32_t context; volatile uint32_t callback; volatile uint32_t trampoline; } CThunkTrampoline; #else typedef struct { CTHUNK_VARIABLES; volatile uint32_t instance; volatile uint32_t context; volatile uint32_t callback; volatile uint32_t trampoline; } __attribute__((__packed__)) CThunkTrampoline; #endif static void trampoline(T* instance, void* context, CCallback* callback) { if(instance && *callback) { (static_cast(instance)->**callback)(context); } } volatile CThunkTrampoline m_thunk; inline void init(T *instance, CCallback callback, void* context) { /* remember callback - need to add this level of redirection as pointer size for member functions differs between platforms */ m_callback = callback; /* populate thunking trampoline */ CTHUNK_ASSIGMENT; m_thunk.context = (uint32_t)context; m_thunk.instance = (uint32_t)instance; m_thunk.callback = (uint32_t)&m_callback; m_thunk.trampoline = (uint32_t)&trampoline; __ISB(); __DSB(); } }; #endif/*__CTHUNK_H__*/ ================================================ FILE: Zelig/mbed/CallChain.h ================================================ /* mbed Microcontroller Library * Copyright (c) 2006-2013 ARM Limited * * 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 MBED_CALLCHAIN_H #define MBED_CALLCHAIN_H #include "FunctionPointer.h" #include namespace mbed { /** Group one or more functions in an instance of a CallChain, then call them in * sequence using CallChain::call(). Used mostly by the interrupt chaining code, * but can be used for other purposes. * * Example: * @code * #include "mbed.h" * * CallChain chain; * * void first(void) { * printf("'first' function.\n"); * } * * void second(void) { * printf("'second' function.\n"); * } * * class Test { * public: * void f(void) { * printf("A::f (class member).\n"); * } * }; * * int main() { * Test test; * * chain.add(second); * chain.add_front(first); * chain.add(&test, &Test::f); * chain.call(); * } * @endcode */ typedef FunctionPointer* pFunctionPointer_t; class CallChain { public: /** Create an empty chain * * @param size (optional) Initial size of the chain */ CallChain(int size = 4); virtual ~CallChain(); /** Add a function at the end of the chain * * @param function A pointer to a void function * * @returns * The function object created for 'function' */ pFunctionPointer_t add(void (*function)(void)); /** Add a function at the end of the chain * * @param tptr pointer to the object to call the member function on * @param mptr pointer to the member function to be called * * @returns * The function object created for 'tptr' and 'mptr' */ template pFunctionPointer_t add(T *tptr, void (T::*mptr)(void)) { return common_add(new FunctionPointer(tptr, mptr)); } /** Add a function at the beginning of the chain * * @param function A pointer to a void function * * @returns * The function object created for 'function' */ pFunctionPointer_t add_front(void (*function)(void)); /** Add a function at the beginning of the chain * * @param tptr pointer to the object to call the member function on * @param mptr pointer to the member function to be called * * @returns * The function object created for 'tptr' and 'mptr' */ template pFunctionPointer_t add_front(T *tptr, void (T::*mptr)(void)) { return common_add_front(new FunctionPointer(tptr, mptr)); } /** Get the number of functions in the chain */ int size() const; /** Get a function object from the chain * * @param i function object index * * @returns * The function object at position 'i' in the chain */ pFunctionPointer_t get(int i) const; /** Look for a function object in the call chain * * @param f the function object to search * * @returns * The index of the function object if found, -1 otherwise. */ int find(pFunctionPointer_t f) const; /** Clear the call chain (remove all functions in the chain). */ void clear(); /** Remove a function object from the chain * * @arg f the function object to remove * * @returns * true if the function object was found and removed, false otherwise. */ bool remove(pFunctionPointer_t f); /** Call all the functions in the chain in sequence */ void call(); #ifdef MBED_OPERATORS void operator ()(void) { call(); } pFunctionPointer_t operator [](int i) const { return get(i); } #endif private: void _check_size(); pFunctionPointer_t common_add(pFunctionPointer_t pf); pFunctionPointer_t common_add_front(pFunctionPointer_t pf); pFunctionPointer_t* _chain; int _size; int _elements; /* disallow copy constructor and assignment operators */ private: CallChain(const CallChain&); CallChain & operator = (const CallChain&); }; } // namespace mbed #endif ================================================ FILE: Zelig/mbed/CircularBuffer.h ================================================ /* mbed Microcontroller Library * Copyright (c) 2015 ARM Limited * * 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 MBED_CIRCULARBUFFER_H #define MBED_CIRCULARBUFFER_H namespace mbed { /** Templated Circular buffer class */ template class CircularBuffer { public: CircularBuffer() : _head(0), _tail(0), _full(false) { } ~CircularBuffer() { } /** Push the transaction to the buffer. This overwrites the buffer if it's * full * * @param data Data to be pushed to the buffer */ void push(const T& data) { if (full()) { _tail++; _tail %= BufferSize; } _pool[_head++] = data; _head %= BufferSize; if (_head == _tail) { _full = true; } } /** Pop the transaction from the buffer * * @param data Data to be pushed to the buffer * @return True if the buffer is not empty and data contains a transaction, false otherwise */ bool pop(T& data) { if (!empty()) { data = _pool[_tail++]; _tail %= BufferSize; _full = false; return true; } return false; } /** Check if the buffer is empty * * @return True if the buffer is empty, false if not */ bool empty() { return (_head == _tail) && !_full; } /** Check if the buffer is full * * @return True if the buffer is full, false if not */ bool full() { return _full; } /** Reset the buffer * */ void reset() { _head = 0; _tail = 0; _full = false; } private: T _pool[BufferSize]; volatile CounterType _head; volatile CounterType _tail; volatile bool _full; }; } #endif ================================================ FILE: Zelig/mbed/DigitalIn.h ================================================ /* mbed Microcontroller Library * Copyright (c) 2006-2013 ARM Limited * * 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 MBED_DIGITALIN_H #define MBED_DIGITALIN_H #include "platform.h" #include "gpio_api.h" namespace mbed { /** A digital input, used for reading the state of a pin * * Example: * @code * // Flash an LED while a DigitalIn is true * * #include "mbed.h" * * DigitalIn enable(p5); * DigitalOut led(LED1); * * int main() { * while(1) { * if(enable) { * led = !led; * } * wait(0.25); * } * } * @endcode */ class DigitalIn { public: /** Create a DigitalIn connected to the specified pin * * @param pin DigitalIn pin to connect to */ DigitalIn(PinName pin) : gpio() { gpio_init_in(&gpio, pin); } /** Create a DigitalIn connected to the specified pin * * @param pin DigitalIn pin to connect to * @param mode the initial mode of the pin */ DigitalIn(PinName pin, PinMode mode) : gpio() { gpio_init_in_ex(&gpio, pin, mode); } /** Read the input, represented as 0 or 1 (int) * * @returns * An integer representing the state of the input pin, * 0 for logical 0, 1 for logical 1 */ int read() { return gpio_read(&gpio); } /** Set the input pin mode * * @param mode PullUp, PullDown, PullNone, OpenDrain */ void mode(PinMode pull) { gpio_mode(&gpio, pull); } /** Return the output setting, represented as 0 or 1 (int) * * @returns * Non zero value if pin is connected to uc GPIO * 0 if gpio object was initialized with NC */ int is_connected() { return gpio_is_connected(&gpio); } #ifdef MBED_OPERATORS /** An operator shorthand for read() */ operator int() { return read(); } #endif protected: gpio_t gpio; }; } // namespace mbed #endif ================================================ FILE: Zelig/mbed/DigitalInOut.h ================================================ /* mbed Microcontroller Library * Copyright (c) 2006-2013 ARM Limited * * 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 MBED_DIGITALINOUT_H #define MBED_DIGITALINOUT_H #include "platform.h" #include "gpio_api.h" namespace mbed { /** A digital input/output, used for setting or reading a bi-directional pin */ class DigitalInOut { public: /** Create a DigitalInOut connected to the specified pin * * @param pin DigitalInOut pin to connect to */ DigitalInOut(PinName pin) : gpio() { gpio_init_in(&gpio, pin); } /** Create a DigitalInOut connected to the specified pin * * @param pin DigitalInOut pin to connect to * @param direction the initial direction of the pin * @param mode the initial mode of the pin * @param value the initial value of the pin if is an output */ DigitalInOut(PinName pin, PinDirection direction, PinMode mode, int value) : gpio() { gpio_init_inout(&gpio, pin, direction, mode, value); } /** Set the output, specified as 0 or 1 (int) * * @param value An integer specifying the pin output value, * 0 for logical 0, 1 (or any other non-zero value) for logical 1 */ void write(int value) { gpio_write(&gpio, value); } /** Return the output setting, represented as 0 or 1 (int) * * @returns * an integer representing the output setting of the pin if it is an output, * or read the input if set as an input */ int read() { return gpio_read(&gpio); } /** Set as an output */ void output() { gpio_dir(&gpio, PIN_OUTPUT); } /** Set as an input */ void input() { gpio_dir(&gpio, PIN_INPUT); } /** Set the input pin mode * * @param mode PullUp, PullDown, PullNone, OpenDrain */ void mode(PinMode pull) { gpio_mode(&gpio, pull); } /** Return the output setting, represented as 0 or 1 (int) * * @returns * Non zero value if pin is connected to uc GPIO * 0 if gpio object was initialized with NC */ int is_connected() { return gpio_is_connected(&gpio); } #ifdef MBED_OPERATORS /** A shorthand for write() */ DigitalInOut& operator= (int value) { write(value); return *this; } DigitalInOut& operator= (DigitalInOut& rhs) { write(rhs.read()); return *this; } /** A shorthand for read() */ operator int() { return read(); } #endif protected: gpio_t gpio; }; } // namespace mbed #endif ================================================ FILE: Zelig/mbed/DigitalOut.h ================================================ /* mbed Microcontroller Library * Copyright (c) 2006-2013 ARM Limited * * 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 MBED_DIGITALOUT_H #define MBED_DIGITALOUT_H #include "platform.h" #include "gpio_api.h" namespace mbed { /** A digital output, used for setting the state of a pin * * Example: * @code * // Toggle a LED * #include "mbed.h" * * DigitalOut led(LED1); * * int main() { * while(1) { * led = !led; * wait(0.2); * } * } * @endcode */ class DigitalOut { public: /** Create a DigitalOut connected to the specified pin * * @param pin DigitalOut pin to connect to */ DigitalOut(PinName pin) : gpio() { gpio_init_out(&gpio, pin); } /** Create a DigitalOut connected to the specified pin * * @param pin DigitalOut pin to connect to * @param value the initial pin value */ DigitalOut(PinName pin, int value) : gpio() { gpio_init_out_ex(&gpio, pin, value); } /** Set the output, specified as 0 or 1 (int) * * @param value An integer specifying the pin output value, * 0 for logical 0, 1 (or any other non-zero value) for logical 1 */ void write(int value) { gpio_write(&gpio, value); } /** Return the output setting, represented as 0 or 1 (int) * * @returns * an integer representing the output setting of the pin, * 0 for logical 0, 1 for logical 1 */ int read() { return gpio_read(&gpio); } /** Return the output setting, represented as 0 or 1 (int) * * @returns * Non zero value if pin is connected to uc GPIO * 0 if gpio object was initialized with NC */ int is_connected() { return gpio_is_connected(&gpio); } #ifdef MBED_OPERATORS /** A shorthand for write() */ DigitalOut& operator= (int value) { write(value); return *this; } DigitalOut& operator= (DigitalOut& rhs) { write(rhs.read()); return *this; } /** A shorthand for read() */ operator int() { return read(); } #endif protected: gpio_t gpio; }; } // namespace mbed #endif ================================================ FILE: Zelig/mbed/DirHandle.h ================================================ /* mbed Microcontroller Library * Copyright (c) 2006-2013 ARM Limited * * 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 MBED_DIRHANDLE_H #define MBED_DIRHANDLE_H #if defined(__ARMCC_VERSION) || defined(__ICCARM__) # define NAME_MAX 255 typedef int mode_t; #else # include #endif #include "FileHandle.h" struct dirent { char d_name[NAME_MAX+1]; }; namespace mbed { /** Represents a directory stream. Objects of this type are returned * by a FileSystemLike's opendir method. Implementations must define * at least closedir, readdir and rewinddir. * * If a FileSystemLike class defines the opendir method, then the * directories of an object of that type can be accessed by * DIR *d = opendir("/example/directory") (or opendir("/example") * to open the root of the filesystem), and then using readdir(d) etc. * * The root directory is considered to contain all FileLike and * FileSystemLike objects, so the DIR* returned by opendir("/") will * reflect this. */ class DirHandle { public: /** Closes the directory. * * @returns * 0 on success, * -1 on error. */ virtual int closedir()=0; /** Return the directory entry at the current position, and * advances the position to the next entry. * * @returns * A pointer to a dirent structure representing the * directory entry at the current position, or NULL on reaching * end of directory or error. */ virtual struct dirent *readdir()=0; /** Resets the position to the beginning of the directory. */ virtual void rewinddir()=0; /** Returns the current position of the DirHandle. * * @returns * the current position, * -1 on error. */ virtual off_t telldir() { return -1; } /** Sets the position of the DirHandle. * * @param location The location to seek to. Must be a value returned by telldir. */ virtual void seekdir(off_t location) { } virtual ~DirHandle() {} }; } // namespace mbed typedef mbed::DirHandle DIR; extern "C" { DIR *opendir(const char*); struct dirent *readdir(DIR *); int closedir(DIR*); void rewinddir(DIR*); long telldir(DIR*); void seekdir(DIR*, long); int mkdir(const char *name, mode_t n); }; #endif /* MBED_DIRHANDLE_H */ ================================================ FILE: Zelig/mbed/Ethernet.h ================================================ /* mbed Microcontroller Library * Copyright (c) 2006-2013 ARM Limited * * 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 MBED_ETHERNET_H #define MBED_ETHERNET_H #include "platform.h" #if DEVICE_ETHERNET namespace mbed { /** An ethernet interface, to use with the ethernet pins. * * Example: * @code * // Read destination and source from every ethernet packet * * #include "mbed.h" * * Ethernet eth; * * int main() { * char buf[0x600]; * * while(1) { * int size = eth.receive(); * if(size > 0) { * eth.read(buf, size); * printf("Destination: %02X:%02X:%02X:%02X:%02X:%02X\n", * buf[0], buf[1], buf[2], buf[3], buf[4], buf[5]); * printf("Source: %02X:%02X:%02X:%02X:%02X:%02X\n", * buf[6], buf[7], buf[8], buf[9], buf[10], buf[11]); * } * * wait(1); * } * } * @endcode */ class Ethernet { public: /** Initialise the ethernet interface. */ Ethernet(); /** Powers the hardware down. */ virtual ~Ethernet(); enum Mode { AutoNegotiate, HalfDuplex10, FullDuplex10, HalfDuplex100, FullDuplex100 }; /** Writes into an outgoing ethernet packet. * * It will append size bytes of data to the previously written bytes. * * @param data An array to write. * @param size The size of data. * * @returns * The number of written bytes. */ int write(const char *data, int size); /** Send an outgoing ethernet packet. * * After filling in the data in an ethernet packet it must be send. * Send will provide a new packet to write to. * * @returns * 0 if the sending was failed, * or the size of the packet successfully sent. */ int send(); /** Recevies an arrived ethernet packet. * * Receiving an ethernet packet will drop the last received ethernet packet * and make a new ethernet packet ready to read. * If no ethernet packet is arrived it will return 0. * * @returns * 0 if no ethernet packet is arrived, * or the size of the arrived packet. */ int receive(); /** Read from an recevied ethernet packet. * * After receive returnd a number bigger than 0it is * possible to read bytes from this packet. * Read will write up to size bytes into data. * * It is possible to use read multible times. * Each time read will start reading after the last read byte before. * * @returns * The number of byte read. */ int read(char *data, int size); /** Gives the ethernet address of the mbed. * * @param mac Must be a pointer to a 6 byte char array to copy the ethernet address in. */ void address(char *mac); /** Returns if an ethernet link is pressent or not. It takes a wile after Ethernet initializion to show up. * * @returns * 0 if no ethernet link is pressent, * 1 if an ethernet link is pressent. * * Example: * @code * // Using the Ethernet link function * #include "mbed.h" * * Ethernet eth; * * int main() { * wait(1); // Needed after startup. * if (eth.link()) { * printf("online\n"); * } else { * printf("offline\n"); * } * } * @endcode */ int link(); /** Sets the speed and duplex parameters of an ethernet link * * - AutoNegotiate Auto negotiate speed and duplex * - HalfDuplex10 10 Mbit, half duplex * - FullDuplex10 10 Mbit, full duplex * - HalfDuplex100 100 Mbit, half duplex * - FullDuplex100 100 Mbit, full duplex * * @param mode the speed and duplex mode to set the link to: */ void set_link(Mode mode); }; } // namespace mbed #endif #endif ================================================ FILE: Zelig/mbed/EthernetInterface/EthernetInterface.cpp ================================================ /* EthernetInterface.cpp */ /* Copyright (C) 2012 mbed.org, MIT License * * Permission is hereby granted, free of charge, to any person obtaining a copy of this software * and associated documentation files (the "Software"), to deal in the Software without restriction, * including without limitation the rights to use, copy, modify, merge, publish, distribute, * sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all copies or * substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING * BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, * DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ #include "EthernetInterface.h" #include "lwip/inet.h" #include "lwip/netif.h" #include "netif/etharp.h" #include "lwip/dhcp.h" #include "eth_arch.h" #include "lwip/tcpip.h" #include "mbed.h" /* TCP/IP and Network Interface Initialisation */ static struct netif netif; static char mac_addr[19]; static char ip_addr[17] = "\0"; static char gateway[17] = "\0"; static char networkmask[17] = "\0"; static bool use_dhcp = false; static Semaphore tcpip_inited(0); static Semaphore netif_linked(0); static Semaphore netif_up(0); static void tcpip_init_done(void *arg) { tcpip_inited.release(); } static void netif_link_callback(struct netif *netif) { if (netif_is_link_up(netif)) { netif_linked.release(); } } static void netif_status_callback(struct netif *netif) { if (netif_is_up(netif)) { strcpy(ip_addr, inet_ntoa(netif->ip_addr)); strcpy(gateway, inet_ntoa(netif->gw)); strcpy(networkmask, inet_ntoa(netif->netmask)); netif_up.release(); } } static void init_netif(ip_addr_t *ipaddr, ip_addr_t *netmask, ip_addr_t *gw) { tcpip_init(tcpip_init_done, NULL); tcpip_inited.wait(); memset((void*) &netif, 0, sizeof(netif)); netif_add(&netif, ipaddr, netmask, gw, NULL, eth_arch_enetif_init, tcpip_input); netif_set_default(&netif); netif_set_link_callback (&netif, netif_link_callback); netif_set_status_callback(&netif, netif_status_callback); } static void set_mac_address(void) { #if (MBED_MAC_ADDRESS_SUM != MBED_MAC_ADDR_INTERFACE) snprintf(mac_addr, 19, "%02x:%02x:%02x:%02x:%02x:%02x", MBED_MAC_ADDR_0, MBED_MAC_ADDR_1, MBED_MAC_ADDR_2, MBED_MAC_ADDR_3, MBED_MAC_ADDR_4, MBED_MAC_ADDR_5); #else char mac[6]; mbed_mac_address(mac); snprintf(mac_addr, 19, "%02x:%02x:%02x:%02x:%02x:%02x", mac[0], mac[1], mac[2], mac[3], mac[4], mac[5]); #endif } int EthernetInterface::init() { tcpip_inited.init(); netif_linked.init(); netif_up.init(); use_dhcp = true; set_mac_address(); init_netif(NULL, NULL, NULL); return 0; } int EthernetInterface::init(const char* ip, const char* mask, const char* gateway) { tcpip_inited.init(); netif_linked.init(); netif_up.init(); use_dhcp = false; set_mac_address(); strcpy(ip_addr, ip); ip_addr_t ip_n, mask_n, gateway_n; inet_aton(ip, &ip_n); inet_aton(mask, &mask_n); inet_aton(gateway, &gateway_n); init_netif(&ip_n, &mask_n, &gateway_n); return 0; } int EthernetInterface::connect(unsigned int timeout_ms) { eth_arch_enable_interrupts(); int inited; if (use_dhcp) { dhcp_start(&netif); // Wait for an IP Address // -1: error, 0: timeout inited = netif_up.wait(timeout_ms); } else { netif_set_up(&netif); // Wait for the link up inited = netif_linked.wait(timeout_ms); } return (inited > 0) ? (0) : (-1); } int EthernetInterface::disconnect() { if (use_dhcp) { dhcp_release(&netif); dhcp_stop(&netif); } else { netif_set_down(&netif); } eth_arch_disable_interrupts(); return 0; } char* EthernetInterface::getMACAddress() { return mac_addr; } char* EthernetInterface::getIPAddress() { return ip_addr; } char* EthernetInterface::getGateway() { return gateway; } char* EthernetInterface::getNetworkMask() { return networkmask; } ================================================ FILE: Zelig/mbed/EthernetInterface/EthernetInterface.h ================================================ /* EthernetInterface.h */ /* Copyright (C) 2012 mbed.org, MIT License * * Permission is hereby granted, free of charge, to any person obtaining a copy of this software * and associated documentation files (the "Software"), to deal in the Software without restriction, * including without limitation the rights to use, copy, modify, merge, publish, distribute, * sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all copies or * substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING * BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, * DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ #ifndef ETHERNETINTERFACE_H_ #define ETHERNETINTERFACE_H_ #if !defined(TARGET_LPC1768) && !defined(TARGET_LPC4088) && !defined(TARGET_LPC4088_DM) && !defined(TARGET_K64F) && !defined(TARGET_RZ_A1H) && !defined(TARGET_STM32F4) //#error The Ethernet Interface library is not supported on this target #endif //#include "rtos.h" #include "lwip/netif.h" /** Interface using Ethernet to connect to an IP-based network * */ class EthernetInterface { public: /** Initialize the interface with DHCP. * Initialize the interface and configure it to use DHCP (no connection at this point). * \return 0 on success, a negative number on failure */ static int init(); //With DHCP /** Initialize the interface with a static IP address. * Initialize the interface and configure it with the following static configuration (no connection at this point). * \param ip the IP address to use * \param mask the IP address mask * \param gateway the gateway to use * \return 0 on success, a negative number on failure */ static int init(const char* ip, const char* mask, const char* gateway); /** Connect * Bring the interface up, start DHCP if needed. * \param timeout_ms timeout in ms (default: (15)s). * \return 0 on success, a negative number on failure */ static int connect(unsigned int timeout_ms=15000); /** Disconnect * Bring the interface down * \return 0 on success, a negative number on failure */ static int disconnect(); /** Get the MAC address of your Ethernet interface * \return a pointer to a string containing the MAC address */ static char* getMACAddress(); /** Get the IP address of your Ethernet interface * \return a pointer to a string containing the IP address */ static char* getIPAddress(); /** Get the Gateway address of your Ethernet interface * \return a pointer to a string containing the Gateway address */ static char* getGateway(); /** Get the Network mask of your Ethernet interface * \return a pointer to a string containing the Network mask */ static char* getNetworkMask(); }; //#include "TCPSocketConnection.h" //#include "TCPSocketServer.h" // //#include "Endpoint.h" //#include "UDPSocket.h" #endif /* ETHERNETINTERFACE_H_ */ ================================================ FILE: Zelig/mbed/EthernetInterface/README.txt ================================================ In order to create the mbedeth lib, these files need to be compiled. They were modified due to an issue with using static constructors in C++ that call into the Llilum runtime. The only change made was adding an init method to Semaphore, and calling that method from the EthernetInterface init methods. The following command creates the lib: \bin\arm-none-eabi-ar.exe --target=elf32-little -v -q libmbedeth.a Semaphore.o EthernetInterface.o This lib needs to be placed into the ARM_GCC_TOOLCHAIN folder for every board The files in this folder are found in \mbed\libraries\net\eth\EthernetInterface AND \mbed\libraries\rtos\rtos (for Semaphore) Steps: 1. Export a sample application (for GCC) from mBed that uses EthernetInterface 2. Find Samephore.h and add the method header "void init(void);" 3. Open Semaphore.cpp and comment out this line in the constructor: "_osSemaphoreId = osSemaphoreCreate(&_osSemaphoreDef, count);" 4. Add a method in Semaphore.cpp that looks like the following: void Semaphore::init(void) { _osSemaphoreId = osSemaphoreCreate(&_osSemaphoreDef, _count); } 5. Replace EthernetInterface.cpp and EthernetInterface.h with the ones from \llilum\Zelig\mbed\EthernetInterface 6. Run make in the sample directory 7. Copy Semaphore.o and EthernetInterface.o into one folder 8. Run \bin\arm-none-eabi-ar.exe --target=elf32-little -v -q libmbedeth.a Semaphore.o EthernetInterface.o ================================================ FILE: Zelig/mbed/EthernetInterface/eth_arch.h ================================================ /* EthernetInterface.h */ /* Copyright (C) 2012 mbed.org, MIT License * * Permission is hereby granted, free of charge, to any person obtaining a copy of this software * and associated documentation files (the "Software"), to deal in the Software without restriction, * including without limitation the rights to use, copy, modify, merge, publish, distribute, * sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all copies or * substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING * BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, * DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ // Architecture specific Ethernet interface // Must be implemented by each target #ifndef ETHARCH_H_ #define ETHARCH_H_ #include "lwip/netif.h" #ifdef __cplusplus extern "C" { #endif void eth_arch_enable_interrupts(void); void eth_arch_disable_interrupts(void); err_t eth_arch_enetif_init(struct netif *netif); #ifdef __cplusplus } #endif #endif // #ifndef ETHARCHINTERFACE_H_ ================================================ FILE: Zelig/mbed/FileBase.h ================================================ /* mbed Microcontroller Library * Copyright (c) 2006-2013 ARM Limited * * 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 MBED_FILEBASE_H #define MBED_FILEBASE_H typedef int FILEHANDLE; #include #if defined(__ARMCC_VERSION) || defined(__ICCARM__) # define O_RDONLY 0 # define O_WRONLY 1 # define O_RDWR 2 # define O_CREAT 0x0200 # define O_TRUNC 0x0400 # define O_APPEND 0x0008 # define NAME_MAX 255 typedef int mode_t; typedef int ssize_t; typedef long off_t; #else # include # include # include #endif #include "platform.h" namespace mbed { typedef enum { FilePathType, FileSystemPathType } PathType; class FileBase { public: FileBase(const char *name, PathType t); virtual ~FileBase(); const char* getName(void); PathType getPathType(void); static FileBase *lookup(const char *name, unsigned int len); static FileBase *get(int n); protected: static FileBase *_head; FileBase *_next; const char *_name; PathType _path_type; /* disallow copy constructor and assignment operators */ private: FileBase(const FileBase&); FileBase & operator = (const FileBase&); }; } // namespace mbed #endif ================================================ FILE: Zelig/mbed/FileHandle.h ================================================ /* mbed Microcontroller Library * Copyright (c) 2006-2013 ARM Limited * * 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 MBED_FILEHANDLE_H #define MBED_FILEHANDLE_H typedef int FILEHANDLE; #include #if defined(__ARMCC_VERSION) || defined(__ICCARM__) typedef int ssize_t; typedef long off_t; #else # include #endif namespace mbed { /** An OO equivalent of the internal FILEHANDLE variable * and associated _sys_* functions. * * FileHandle is an abstract class, needing at least sys_write and * sys_read to be implmented for a simple interactive device. * * No one ever directly tals to/instanciates a FileHandle - it gets * created by FileSystem, and wrapped up by stdio. */ class FileHandle { public: /** Write the contents of a buffer to the file * * @param buffer the buffer to write from * @param length the number of characters to write * * @returns * The number of characters written (possibly 0) on success, -1 on error. */ virtual ssize_t write(const void* buffer, size_t length) = 0; /** Close the file * * @returns * Zero on success, -1 on error. */ virtual int close() = 0; /** Function read * Reads the contents of the file into a buffer * * @param buffer the buffer to read in to * @param length the number of characters to read * * @returns * The number of characters read (zero at end of file) on success, -1 on error. */ virtual ssize_t read(void* buffer, size_t length) = 0; /** Check if the handle is for a interactive terminal device. * If so, line buffered behaviour is used by default * * @returns * 1 if it is a terminal, * 0 otherwise */ virtual int isatty() = 0; /** Move the file position to a given offset from a given location. * * @param offset The offset from whence to move to * @param whence SEEK_SET for the start of the file, SEEK_CUR for the * current file position, or SEEK_END for the end of the file. * * @returns * new file position on success, * -1 on failure or unsupported */ virtual off_t lseek(off_t offset, int whence) = 0; /** Flush any buffers associated with the FileHandle, ensuring it * is up to date on disk * * @returns * 0 on success or un-needed, * -1 on error */ virtual int fsync() = 0; virtual off_t flen() { /* remember our current position */ off_t pos = lseek(0, SEEK_CUR); if(pos == -1) return -1; /* seek to the end to get the file length */ off_t res = lseek(0, SEEK_END); /* return to our old position */ lseek(pos, SEEK_SET); return res; } virtual ~FileHandle(); }; } // namespace mbed #endif ================================================ FILE: Zelig/mbed/FileLike.h ================================================ /* mbed Microcontroller Library * Copyright (c) 2006-2013 ARM Limited * * 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 MBED_FILELIKE_H #define MBED_FILELIKE_H #include "FileBase.h" #include "FileHandle.h" namespace mbed { /* Class FileLike * A file-like object is one that can be opened with fopen by * fopen("/name", mode). It is intersection of the classes Base and * FileHandle. */ class FileLike : public FileHandle, public FileBase { public: /* Constructor FileLike * * Variables * name - The name to use to open the file. */ FileLike(const char *name); virtual ~FileLike(); }; } // namespace mbed #endif ================================================ FILE: Zelig/mbed/FilePath.h ================================================ /* mbed Microcontroller Library * Copyright (c) 2006-2013 ARM Limited * * 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 MBED_FILEPATH_H #define MBED_FILEPATH_H #include "platform.h" #include "FileSystemLike.h" #include "FileLike.h" namespace mbed { class FilePath { public: FilePath(const char* file_path); const char* fileName(void); bool isFileSystem(void); FileSystemLike* fileSystem(void); bool isFile(void); FileLike* file(void); bool exists(void); private: const char* file_name; FileBase* fb; }; } // namespace mbed #endif ================================================ FILE: Zelig/mbed/FileSystemLike.h ================================================ /* mbed Microcontroller Library * Copyright (c) 2006-2013 ARM Limited * * 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 MBED_FILESYSTEMLIKE_H #define MBED_FILESYSTEMLIKE_H #include "platform.h" #include "FileBase.h" #include "FileHandle.h" #include "DirHandle.h" namespace mbed { /** A filesystem-like object is one that can be used to open files * though it by fopen("/name/filename", mode) * * Implementations must define at least open (the default definitions * of the rest of the functions just return error values). */ class FileSystemLike : public FileBase { public: /** FileSystemLike constructor * * @param name The name to use for the filesystem. */ FileSystemLike(const char *name); virtual ~FileSystemLike(); static DirHandle *opendir(); friend class BaseDirHandle; /** Opens a file from the filesystem * * @param filename The name of the file to open. * @param flags One of O_RDONLY, O_WRONLY, or O_RDWR, OR'd with * zero or more of O_CREAT, O_TRUNC, or O_APPEND. * * @returns * A pointer to a FileHandle object representing the * file on success, or NULL on failure. */ virtual FileHandle *open(const char *filename, int flags) = 0; /** Remove a file from the filesystem. * * @param filename the name of the file to remove. * @param returns 0 on success, -1 on failure. */ virtual int remove(const char *filename) { return -1; }; /** Rename a file in the filesystem. * * @param oldname the name of the file to rename. * @param newname the name to rename it to. * * @returns * 0 on success, * -1 on failure. */ virtual int rename(const char *oldname, const char *newname) { return -1; }; /** Opens a directory in the filesystem and returns a DirHandle * representing the directory stream. * * @param name The name of the directory to open. * * @returns * A DirHandle representing the directory stream, or * NULL on failure. */ virtual DirHandle *opendir(const char *name) { return NULL; }; /** Creates a directory in the filesystem. * * @param name The name of the directory to create. * @param mode The permissions to create the directory with. * * @returns * 0 on success, * -1 on failure. */ virtual int mkdir(const char *name, mode_t mode) { return -1; } // TODO other filesystem functions (mkdir, rm, rn, ls etc) }; } // namespace mbed #endif ================================================ FILE: Zelig/mbed/FunctionPointer.h ================================================ /* mbed Microcontroller Library * Copyright (c) 2006-2015 ARM Limited * * 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 MBED_FUNCTIONPOINTER_H #define MBED_FUNCTIONPOINTER_H #include #include namespace mbed { /* If we had variaditic templates, this wouldn't be a problem, but until C++11 is enabled, we are stuck with multiple classes... */ /** A class for storing and calling a pointer to a static or member function */ template class FunctionPointerArg1{ public: /** Create a FunctionPointer, attaching a static function * * @param function The static function to attach (default is none) */ FunctionPointerArg1(R (*function)(A1) = 0) { attach(function); } /** Create a FunctionPointer, attaching a member function * * @param object The object pointer to invoke the member function on (i.e. the this pointer) * @param function The address of the member function to attach */ template FunctionPointerArg1(T *object, R (T::*member)(A1)) { attach(object, member); } /** Attach a static function * * @param function The static function to attach (default is none) */ void attach(R (*function)(A1)) { _p.function = function; _membercaller = 0; } /** Attach a member function * * @param object The object pointer to invoke the member function on (i.e. the this pointer) * @param function The address of the member function to attach */ template void attach(T *object, R (T::*member)(A1)) { _p.object = static_cast(object); *reinterpret_cast(_member) = member; _membercaller = &FunctionPointerArg1::membercaller; } /** Call the attached static or member function */ R call(A1 a) { if (_membercaller == 0 && _p.function) { return _p.function(a); } else if (_membercaller && _p.object) { return _membercaller(_p.object, _member, a); } return (R)0; } /** Get registered static function */ R(*get_function(A1))() { return _membercaller ? (R(*)(A1))0 : (R(*)(A1))_p.function; } #ifdef MBED_OPERATORS R operator ()(A1 a) { return call(a); } operator bool(void) const { return (_membercaller != NULL ? _p.object : (void*)_p.function) != NULL; } #endif private: template static R membercaller(void *object, uintptr_t *member, A1 a) { T* o = static_cast(object); R (T::**m)(A1) = reinterpret_cast(member); return (o->**m)(a); } union { R (*function)(A1); // static function pointer void *object; // object this pointer } _p; uintptr_t _member[4]; // aligned raw member function pointer storage - converted back by registered _membercaller R (*_membercaller)(void*, uintptr_t*, A1); // registered membercaller function to convert back and call _m.member on _object }; /** A class for storing and calling a pointer to a static or member function (R ()(void)) */ template class FunctionPointerArg1{ public: /** Create a FunctionPointer, attaching a static function * * @param function The static function to attach (default is none) */ FunctionPointerArg1(R (*function)(void) = 0) { attach(function); } /** Create a FunctionPointer, attaching a member function * * @param object The object pointer to invoke the member function on (i.e. the this pointer) * @param function The address of the void member function to attach */ template FunctionPointerArg1(T *object, R (T::*member)(void)) { attach(object, member); } /** Attach a static function * * @param function The void static function to attach (default is none) */ void attach(R (*function)(void)) { _p.function = function; _membercaller = 0; } /** Attach a member function * * @param object The object pointer to invoke the member function on (i.e. the this pointer) * @param function The address of the void member function to attach */ template void attach(T *object, R (T::*member)(void)) { _p.object = static_cast(object); *reinterpret_cast(_member) = member; _membercaller = &FunctionPointerArg1::membercaller; } /** Call the attached static or member function */ R call(){ if (_membercaller == 0 && _p.function) { return _p.function(); } else if (_membercaller && _p.object) { return _membercaller(_p.object, _member); } return (R)0; } /** Get registered static function */ R(*get_function())() { return _membercaller ? (R(*)())0 : (R(*)())_p.function; } #ifdef MBED_OPERATORS R operator ()(void) { return call(); } operator bool(void) const { return (_membercaller != NULL ? _p.object : (void*)_p.function) != NULL; } #endif private: template static R membercaller(void *object, uintptr_t *member) { T* o = static_cast(object); R (T::**m)(void) = reinterpret_cast(member); return (o->**m)(); } union { R (*function)(void); // static function pointer void *object; // object this pointer } _p; uintptr_t _member[4]; // aligned raw member function pointer storage - converted back by registered _membercaller R (*_membercaller)(void*, uintptr_t*); // registered membercaller function to convert back and call _m.member on _object }; typedef FunctionPointerArg1 FunctionPointer; typedef FunctionPointerArg1 event_callback_t; } // namespace mbed #endif ================================================ FILE: Zelig/mbed/I2C.h ================================================ /* mbed Microcontroller Library * Copyright (c) 2006-2015 ARM Limited * * 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 MBED_I2C_H #define MBED_I2C_H #include "platform.h" #if DEVICE_I2C #include "i2c_api.h" #if DEVICE_I2C_ASYNCH #include "CThunk.h" #include "dma_api.h" #include "FunctionPointer.h" #endif namespace mbed { /** An I2C Master, used for communicating with I2C slave devices * * Example: * @code * // Read from I2C slave at address 0x62 * * #include "mbed.h" * * I2C i2c(p28, p27); * * int main() { * int address = 0x62; * char data[2]; * i2c.read(address, data, 2); * } * @endcode */ class I2C { public: enum RxStatus { NoData, MasterGeneralCall, MasterWrite, MasterRead }; enum Acknowledge { NoACK = 0, ACK = 1 }; /** Create an I2C Master interface, connected to the specified pins * * @param sda I2C data line pin * @param scl I2C clock line pin */ I2C(PinName sda, PinName scl); /** Set the frequency of the I2C interface * * @param hz The bus frequency in hertz */ void frequency(int hz); /** Read from an I2C slave * * Performs a complete read transaction. The bottom bit of * the address is forced to 1 to indicate a read. * * @param address 8-bit I2C slave address [ addr | 1 ] * @param data Pointer to the byte-array to read data in to * @param length Number of bytes to read * @param repeated Repeated start, true - don't send stop at end * * @returns * 0 on success (ack), * non-0 on failure (nack) */ int read(int address, char *data, int length, bool repeated = false); /** Read a single byte from the I2C bus * * @param ack indicates if the byte is to be acknowledged (1 = acknowledge) * * @returns * the byte read */ int read(int ack); /** Write to an I2C slave * * Performs a complete write transaction. The bottom bit of * the address is forced to 0 to indicate a write. * * @param address 8-bit I2C slave address [ addr | 0 ] * @param data Pointer to the byte-array data to send * @param length Number of bytes to send * @param repeated Repeated start, true - do not send stop at end * * @returns * 0 on success (ack), * non-0 on failure (nack) */ int write(int address, const char *data, int length, bool repeated = false); /** Write single byte out on the I2C bus * * @param data data to write out on bus * * @returns * '1' if an ACK was received, * '0' otherwise */ int write(int data); /** Creates a start condition on the I2C bus */ void start(void); /** Creates a stop condition on the I2C bus */ void stop(void); #if DEVICE_I2C_ASYNCH /** Start non-blocking I2C transfer. * * @param address 8/10 bit I2c slave address * @param tx_buffer The TX buffer with data to be transfered * @param tx_length The length of TX buffer in bytes * @param rx_buffer The RX buffer which is used for received data * @param rx_length The length of RX buffer in bytes * @param event The logical OR of events to modify * @param callback The event callback function * @param repeated Repeated start, true - do not send stop at end * @return Zero if the transfer has started, or -1 if I2C peripheral is busy */ int transfer(int address, const char *tx_buffer, int tx_length, char *rx_buffer, int rx_length, const event_callback_t& callback, int event = I2C_EVENT_TRANSFER_COMPLETE, bool repeated = false); /** Abort the on-going I2C transfer */ void abort_transfer(); protected: void irq_handler_asynch(void); event_callback_t _callback; CThunk _irq; DMAUsage _usage; #endif protected: void aquire(); i2c_t _i2c; static I2C *_owner; int _hz; }; } // namespace mbed #endif #endif ================================================ FILE: Zelig/mbed/I2CSlave.h ================================================ /* mbed Microcontroller Library * Copyright (c) 2006-2013 ARM Limited * * 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 MBED_I2C_SLAVE_H #define MBED_I2C_SLAVE_H #include "platform.h" #if DEVICE_I2CSLAVE #include "i2c_api.h" namespace mbed { /** An I2C Slave, used for communicating with an I2C Master device * * Example: * @code * // Simple I2C responder * #include * * I2CSlave slave(p9, p10); * * int main() { * char buf[10]; * char msg[] = "Slave!"; * * slave.address(0xA0); * while (1) { * int i = slave.receive(); * switch (i) { * case I2CSlave::ReadAddressed: * slave.write(msg, strlen(msg) + 1); // Includes null char * break; * case I2CSlave::WriteGeneral: * slave.read(buf, 10); * printf("Read G: %s\n", buf); * break; * case I2CSlave::WriteAddressed: * slave.read(buf, 10); * printf("Read A: %s\n", buf); * break; * } * for(int i = 0; i < 10; i++) buf[i] = 0; // Clear buffer * } * } * @endcode */ class I2CSlave { public: enum RxStatus { NoData = 0, ReadAddressed = 1, WriteGeneral = 2, WriteAddressed = 3 }; /** Create an I2C Slave interface, connected to the specified pins. * * @param sda I2C data line pin * @param scl I2C clock line pin */ I2CSlave(PinName sda, PinName scl); /** Set the frequency of the I2C interface * * @param hz The bus frequency in hertz */ void frequency(int hz); /** Checks to see if this I2C Slave has been addressed. * * @returns * A status indicating if the device has been addressed, and how * - NoData - the slave has not been addressed * - ReadAddressed - the master has requested a read from this slave * - WriteAddressed - the master is writing to this slave * - WriteGeneral - the master is writing to all slave */ int receive(void); /** Read from an I2C master. * * @param data pointer to the byte array to read data in to * @param length maximum number of bytes to read * * @returns * 0 on success, * non-0 otherwise */ int read(char *data, int length); /** Read a single byte from an I2C master. * * @returns * the byte read */ int read(void); /** Write to an I2C master. * * @param data pointer to the byte array to be transmitted * @param length the number of bytes to transmite * * @returns * 0 on success, * non-0 otherwise */ int write(const char *data, int length); /** Write a single byte to an I2C master. * * @data the byte to write * * @returns * '1' if an ACK was received, * '0' otherwise */ int write(int data); /** Sets the I2C slave address. * * @param address The address to set for the slave (ignoring the least * signifcant bit). If set to 0, the slave will only respond to the * general call address. */ void address(int address); /** Reset the I2C slave back into the known ready receiving state. */ void stop(void); protected: i2c_t _i2c; }; } // namespace mbed #endif #endif ================================================ FILE: Zelig/mbed/InterruptIn.h ================================================ /* mbed Microcontroller Library * Copyright (c) 2006-2013 ARM Limited * * 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 MBED_INTERRUPTIN_H #define MBED_INTERRUPTIN_H #include "platform.h" #if DEVICE_INTERRUPTIN #include "gpio_api.h" #include "gpio_irq_api.h" #include "FunctionPointer.h" namespace mbed { /** A digital interrupt input, used to call a function on a rising or falling edge * * Example: * @code * // Flash an LED while waiting for events * * #include "mbed.h" * * InterruptIn event(p16); * DigitalOut led(LED1); * * void trigger() { * printf("triggered!\n"); * } * * int main() { * event.rise(&trigger); * while(1) { * led = !led; * wait(0.25); * } * } * @endcode */ class InterruptIn { public: /** Create an InterruptIn connected to the specified pin * * @param pin InterruptIn pin to connect to * @param name (optional) A string to identify the object */ InterruptIn(PinName pin); virtual ~InterruptIn(); int read(); #ifdef MBED_OPERATORS operator int(); #endif /** Attach a function to call when a rising edge occurs on the input * * @param fptr A pointer to a void function, or 0 to set as none */ void rise(void (*fptr)(void)); /** Attach a member function to call when a rising edge occurs on the input * * @param tptr pointer to the object to call the member function on * @param mptr pointer to the member function to be called */ template void rise(T* tptr, void (T::*mptr)(void)) { _rise.attach(tptr, mptr); gpio_irq_set(&gpio_irq, IRQ_RISE, 1); } /** Attach a function to call when a falling edge occurs on the input * * @param fptr A pointer to a void function, or 0 to set as none */ void fall(void (*fptr)(void)); /** Attach a member function to call when a falling edge occurs on the input * * @param tptr pointer to the object to call the member function on * @param mptr pointer to the member function to be called */ template void fall(T* tptr, void (T::*mptr)(void)) { _fall.attach(tptr, mptr); gpio_irq_set(&gpio_irq, IRQ_FALL, 1); } /** Set the input pin mode * * @param mode PullUp, PullDown, PullNone */ void mode(PinMode pull); /** Enable IRQ. This method depends on hw implementation, might enable one * port interrupts. For further information, check gpio_irq_enable(). */ void enable_irq(); /** Disable IRQ. This method depends on hw implementation, might disable one * port interrupts. For further information, check gpio_irq_disable(). */ void disable_irq(); static void _irq_handler(uint32_t id, gpio_irq_event event); protected: gpio_t gpio; gpio_irq_t gpio_irq; FunctionPointer _rise; FunctionPointer _fall; }; } // namespace mbed #endif #endif ================================================ FILE: Zelig/mbed/InterruptManager.h ================================================ #ifndef MBED_INTERRUPTMANAGER_H #define MBED_INTERRUPTMANAGER_H #include "cmsis.h" #include "CallChain.h" #include namespace mbed { /** Use this singleton if you need to chain interrupt handlers. * * Example (for LPC1768): * @code * #include "InterruptManager.h" * #include "mbed.h" * * Ticker flipper; * DigitalOut led1(LED1); * DigitalOut led2(LED2); * * void flip(void) { * led1 = !led1; * } * * void handler(void) { * led2 = !led1; * } * * int main() { * led1 = led2 = 0; * flipper.attach(&flip, 1.0); * InterruptManager::get()->add_handler(handler, TIMER3_IRQn); * } * @endcode */ class InterruptManager { public: /** Return the only instance of this class */ static InterruptManager* get(); /** Destroy the current instance of the interrupt manager */ static void destroy(); /** Add a handler for an interrupt at the end of the handler list * * @param function the handler to add * @param irq interrupt number * * @returns * The function object created for 'function' */ pFunctionPointer_t add_handler(void (*function)(void), IRQn_Type irq) { return add_common(function, irq); } /** Add a handler for an interrupt at the beginning of the handler list * * @param function the handler to add * @param irq interrupt number * * @returns * The function object created for 'function' */ pFunctionPointer_t add_handler_front(void (*function)(void), IRQn_Type irq) { return add_common(function, irq, true); } /** Add a handler for an interrupt at the end of the handler list * * @param tptr pointer to the object that has the handler function * @param mptr pointer to the actual handler function * @param irq interrupt number * * @returns * The function object created for 'tptr' and 'mptr' */ template pFunctionPointer_t add_handler(T* tptr, void (T::*mptr)(void), IRQn_Type irq) { return add_common(tptr, mptr, irq); } /** Add a handler for an interrupt at the beginning of the handler list * * @param tptr pointer to the object that has the handler function * @param mptr pointer to the actual handler function * @param irq interrupt number * * @returns * The function object created for 'tptr' and 'mptr' */ template pFunctionPointer_t add_handler_front(T* tptr, void (T::*mptr)(void), IRQn_Type irq) { return add_common(tptr, mptr, irq, true); } /** Remove a handler from an interrupt * * @param handler the function object for the handler to remove * @param irq the interrupt number * * @returns * true if the handler was found and removed, false otherwise */ bool remove_handler(pFunctionPointer_t handler, IRQn_Type irq); private: InterruptManager(); ~InterruptManager(); // We declare the copy contructor and the assignment operator, but we don't // implement them. This way, if someone tries to copy/assign our instance, // he will get an error at compile time. InterruptManager(const InterruptManager&); InterruptManager& operator =(const InterruptManager&); template pFunctionPointer_t add_common(T *tptr, void (T::*mptr)(void), IRQn_Type irq, bool front=false) { int irq_pos = get_irq_index(irq); bool change = must_replace_vector(irq); pFunctionPointer_t pf = front ? _chains[irq_pos]->add_front(tptr, mptr) : _chains[irq_pos]->add(tptr, mptr); if (change) NVIC_SetVector(irq, (uint32_t)&InterruptManager::static_irq_helper); return pf; } pFunctionPointer_t add_common(void (*function)(void), IRQn_Type irq, bool front=false); bool must_replace_vector(IRQn_Type irq); int get_irq_index(IRQn_Type irq); void irq_helper(); void add_helper(void (*function)(void), IRQn_Type irq, bool front=false); static void static_irq_helper(); CallChain* _chains[NVIC_NUM_VECTORS]; static InterruptManager* _instance; }; } // namespace mbed #endif ================================================ FILE: Zelig/mbed/LocalFileSystem.h ================================================ /* mbed Microcontroller Library * Copyright (c) 2006-2013 ARM Limited * * 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 MBED_LOCALFILESYSTEM_H #define MBED_LOCALFILESYSTEM_H #include "platform.h" #if DEVICE_LOCALFILESYSTEM #include "FileSystemLike.h" namespace mbed { FILEHANDLE local_file_open(const char* name, int flags); class LocalFileHandle : public FileHandle { public: LocalFileHandle(FILEHANDLE fh); virtual int close(); virtual ssize_t write(const void *buffer, size_t length); virtual ssize_t read(void *buffer, size_t length); virtual int isatty(); virtual off_t lseek(off_t position, int whence); virtual int fsync(); virtual off_t flen(); protected: FILEHANDLE _fh; int pos; }; /** A filesystem for accessing the local mbed Microcontroller USB disk drive * * This allows programs to read and write files on the same disk drive that is used to program the * mbed Microcontroller. Once created, the standard C file access functions are used to open, * read and write files. * * Example: * @code * #include "mbed.h" * * LocalFileSystem local("local"); // Create the local filesystem under the name "local" * * int main() { * FILE *fp = fopen("/local/out.txt", "w"); // Open "out.txt" on the local file system for writing * fprintf(fp, "Hello World!"); * fclose(fp); * remove("/local/out.txt"); // Removes the file "out.txt" from the local file system * * DIR *d = opendir("/local"); // Opens the root directory of the local file system * struct dirent *p; * while((p = readdir(d)) != NULL) { // Print the names of the files in the local file system * printf("%s\n", p->d_name); // to stdout. * } * closedir(d); * } * @endcode * * @note * If the microcontroller program makes an access to the local drive, it will be marked as "removed" * on the Host computer. This means it is no longer accessible from the Host Computer. * * The drive will only re-appear when the microcontroller program exists. Note that if the program does * not exit, you will need to hold down reset on the mbed Microcontroller to be able to see the drive again! */ class LocalFileSystem : public FileSystemLike { public: LocalFileSystem(const char* n) : FileSystemLike(n) { } virtual FileHandle *open(const char* name, int flags); virtual int remove(const char *filename); virtual DirHandle *opendir(const char *name); }; } // namespace mbed #endif #endif ================================================ FILE: Zelig/mbed/LowPowerTicker.h ================================================ /* mbed Microcontroller Library * Copyright (c) 2015 ARM Limited * * 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 MBED_LOWPOWERTICKER_H #define MBED_LOWPOWERTICKER_H #include "platform.h" #include "Ticker.h" #if DEVICE_LOWPOWERTIMER #include "lp_ticker_api.h" namespace mbed { /** Low Power Ticker */ class LowPowerTicker : public Ticker { public: LowPowerTicker() : Ticker(get_lp_ticker_data()) { } virtual ~LowPowerTicker() { } }; } // namespace mbed #endif #endif ================================================ FILE: Zelig/mbed/LowPowerTimeout.h ================================================ /* mbed Microcontroller Library * Copyright (c) 2015 ARM Limited * * 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 MBED_LOWPOWERTIMEOUT_H #define MBED_LOWPOWERTIMEOUT_H #include "platform.h" #if DEVICE_LOWPOWERTIMER #include "lp_ticker_api.h" #include "LowPowerTicker.h" namespace mbed { /** Low Power Timout */ class LowPowerTimeout : public LowPowerTicker { private: virtual void handler(void) { _function.call(); } }; } #endif #endif ================================================ FILE: Zelig/mbed/LowPowerTimer.h ================================================ /* mbed Microcontroller Library * Copyright (c) 2015 ARM Limited * * 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 MBED_LOWPOWERTIMER_H #define MBED_LOWPOWERTIMER_H #include "platform.h" #include "Timer.h" #if DEVICE_LOWPOWERTIMER #include "lp_ticker_api.h" namespace mbed { /** Low power timer */ class LowPowerTimer : public Timer { public: LowPowerTimer() : Timer(get_lp_ticker_data()) { } }; } // namespace mbed #endif #endif ================================================ FILE: Zelig/mbed/PortIn.h ================================================ /* mbed Microcontroller Library * Copyright (c) 2006-2013 ARM Limited * * 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 MBED_PORTIN_H #define MBED_PORTIN_H #include "platform.h" #if DEVICE_PORTIN #include "port_api.h" namespace mbed { /** A multiple pin digital input * * Example: * @code * // Switch on an LED if any of mbed pins 21-26 is high * * #include "mbed.h" * * PortIn p(Port2, 0x0000003F); // p21-p26 * DigitalOut ind(LED4); * * int main() { * while(1) { * int pins = p.read(); * if(pins) { * ind = 1; * } else { * ind = 0; * } * } * } * @endcode */ class PortIn { public: /** Create an PortIn, connected to the specified port * * @param port Port to connect to (Port0-Port5) * @param mask A bitmask to identify which bits in the port should be included (0 - ignore) */ PortIn(PortName port, int mask = 0xFFFFFFFF) { port_init(&_port, port, mask, PIN_INPUT); } /** Read the value currently output on the port * * @returns * An integer with each bit corresponding to associated port pin setting */ int read() { return port_read(&_port); } /** Set the input pin mode * * @param mode PullUp, PullDown, PullNone, OpenDrain */ void mode(PinMode mode) { port_mode(&_port, mode); } /** A shorthand for read() */ operator int() { return read(); } private: port_t _port; }; } // namespace mbed #endif #endif ================================================ FILE: Zelig/mbed/PortInOut.h ================================================ /* mbed Microcontroller Library * Copyright (c) 2006-2013 ARM Limited * * 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 MBED_PORTINOUT_H #define MBED_PORTINOUT_H #include "platform.h" #if DEVICE_PORTINOUT #include "port_api.h" namespace mbed { /** A multiple pin digital in/out used to set/read multiple bi-directional pins */ class PortInOut { public: /** Create an PortInOut, connected to the specified port * * @param port Port to connect to (Port0-Port5) * @param mask A bitmask to identify which bits in the port should be included (0 - ignore) */ PortInOut(PortName port, int mask = 0xFFFFFFFF) { port_init(&_port, port, mask, PIN_INPUT); } /** Write the value to the output port * * @param value An integer specifying a bit to write for every corresponding port pin */ void write(int value) { port_write(&_port, value); } /** Read the value currently output on the port * * @returns * An integer with each bit corresponding to associated port pin setting */ int read() { return port_read(&_port); } /** Set as an output */ void output() { port_dir(&_port, PIN_OUTPUT); } /** Set as an input */ void input() { port_dir(&_port, PIN_INPUT); } /** Set the input pin mode * * @param mode PullUp, PullDown, PullNone, OpenDrain */ void mode(PinMode mode) { port_mode(&_port, mode); } /** A shorthand for write() */ PortInOut& operator= (int value) { write(value); return *this; } PortInOut& operator= (PortInOut& rhs) { write(rhs.read()); return *this; } /** A shorthand for read() */ operator int() { return read(); } private: port_t _port; }; } // namespace mbed #endif #endif ================================================ FILE: Zelig/mbed/PortOut.h ================================================ /* mbed Microcontroller Library * Copyright (c) 2006-2013 ARM Limited * * 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 MBED_PORTOUT_H #define MBED_PORTOUT_H #include "platform.h" #if DEVICE_PORTOUT #include "port_api.h" namespace mbed { /** A multiple pin digital out * * Example: * @code * // Toggle all four LEDs * * #include "mbed.h" * * // LED1 = P1.18 LED2 = P1.20 LED3 = P1.21 LED4 = P1.23 * #define LED_MASK 0x00B40000 * * PortOut ledport(Port1, LED_MASK); * * int main() { * while(1) { * ledport = LED_MASK; * wait(1); * ledport = 0; * wait(1); * } * } * @endcode */ class PortOut { public: /** Create an PortOut, connected to the specified port * * @param port Port to connect to (Port0-Port5) * @param mask A bitmask to identify which bits in the port should be included (0 - ignore) */ PortOut(PortName port, int mask = 0xFFFFFFFF) { port_init(&_port, port, mask, PIN_OUTPUT); } /** Write the value to the output port * * @param value An integer specifying a bit to write for every corresponding PortOut pin */ void write(int value) { port_write(&_port, value); } /** Read the value currently output on the port * * @returns * An integer with each bit corresponding to associated PortOut pin setting */ int read() { return port_read(&_port); } /** A shorthand for write() */ PortOut& operator= (int value) { write(value); return *this; } PortOut& operator= (PortOut& rhs) { write(rhs.read()); return *this; } /** A shorthand for read() */ operator int() { return read(); } private: port_t _port; }; } // namespace mbed #endif #endif ================================================ FILE: Zelig/mbed/PwmOut.h ================================================ /* mbed Microcontroller Library * Copyright (c) 2006-2013 ARM Limited * * 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 MBED_PWMOUT_H #define MBED_PWMOUT_H #include "platform.h" #if DEVICE_PWMOUT #include "pwmout_api.h" namespace mbed { /** A pulse-width modulation digital output * * Example * @code * // Fade a led on. * #include "mbed.h" * * PwmOut led(LED1); * * int main() { * while(1) { * led = led + 0.01; * wait(0.2); * if(led == 1.0) { * led = 0; * } * } * } * @endcode * * @note * On the LPC1768 and LPC2368, the PWMs all share the same * period - if you change the period for one, you change it for all. * Although routines that change the period maintain the duty cycle * for its PWM, all other PWMs will require their duty cycle to be * refreshed. */ class PwmOut { public: /** Create a PwmOut connected to the specified pin * * @param pin PwmOut pin to connect to */ PwmOut(PinName pin) { pwmout_init(&_pwm, pin); } /** Set the ouput duty-cycle, specified as a percentage (float) * * @param value A floating-point value representing the output duty-cycle, * specified as a percentage. The value should lie between * 0.0f (representing on 0%) and 1.0f (representing on 100%). * Values outside this range will be saturated to 0.0f or 1.0f. */ void write(float value) { pwmout_write(&_pwm, value); } /** Return the current output duty-cycle setting, measured as a percentage (float) * * @returns * A floating-point value representing the current duty-cycle being output on the pin, * measured as a percentage. The returned value will lie between * 0.0f (representing on 0%) and 1.0f (representing on 100%). * * @note * This value may not match exactly the value set by a previous . */ float read() { return pwmout_read(&_pwm); } /** Set the PWM period, specified in seconds (float), keeping the duty cycle the same. * * @note * The resolution is currently in microseconds; periods smaller than this * will be set to zero. */ void period(float seconds) { pwmout_period(&_pwm, seconds); } /** Set the PWM period, specified in milli-seconds (int), keeping the duty cycle the same. */ void period_ms(int ms) { pwmout_period_ms(&_pwm, ms); } /** Set the PWM period, specified in micro-seconds (int), keeping the duty cycle the same. */ void period_us(int us) { pwmout_period_us(&_pwm, us); } /** Set the PWM pulsewidth, specified in seconds (float), keeping the period the same. */ void pulsewidth(float seconds) { pwmout_pulsewidth(&_pwm, seconds); } /** Set the PWM pulsewidth, specified in milli-seconds (int), keeping the period the same. */ void pulsewidth_ms(int ms) { pwmout_pulsewidth_ms(&_pwm, ms); } /** Set the PWM pulsewidth, specified in micro-seconds (int), keeping the period the same. */ void pulsewidth_us(int us) { pwmout_pulsewidth_us(&_pwm, us); } #ifdef MBED_OPERATORS /** A operator shorthand for write() */ PwmOut& operator= (float value) { write(value); return *this; } PwmOut& operator= (PwmOut& rhs) { write(rhs.read()); return *this; } /** An operator shorthand for read() */ operator float() { return read(); } #endif protected: pwmout_t _pwm; }; } // namespace mbed #endif #endif ================================================ FILE: Zelig/mbed/RawSerial.h ================================================ /* mbed Microcontroller Library * Copyright (c) 2006-2013 ARM Limited * * 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 MBED_RAW_SERIAL_H #define MBED_RAW_SERIAL_H #include "platform.h" #if DEVICE_SERIAL #include "SerialBase.h" #include "serial_api.h" namespace mbed { /** A serial port (UART) for communication with other serial devices * This is a variation of the Serial class that doesn't use streams, * thus making it safe to use in interrupt handlers with the RTOS. * * Can be used for Full Duplex communication, or Simplex by specifying * one pin as NC (Not Connected) * * Example: * @code * // Send a char to the PC * * #include "mbed.h" * * RawSerial pc(USBTX, USBRX); * * int main() { * pc.putc('A'); * } * @endcode */ class RawSerial: public SerialBase { public: /** Create a RawSerial port, connected to the specified transmit and receive pins * * @param tx Transmit pin * @param rx Receive pin * * @note * Either tx or rx may be specified as NC if unused */ RawSerial(PinName tx, PinName rx); /** Write a char to the serial port * * @param c The char to write * * @returns The written char or -1 if an error occured */ int putc(int c); /** Read a char from the serial port * * @returns The char read from the serial port */ int getc(); /** Write a string to the serial port * * @param str The string to write * * @returns 0 if the write succeeds, EOF for error */ int puts(const char *str); int printf(const char *format, ...); }; } // namespace mbed #endif #endif ================================================ FILE: Zelig/mbed/SPI.h ================================================ /* mbed Microcontroller Library * Copyright (c) 2006-2015 ARM Limited * * 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 MBED_SPI_H #define MBED_SPI_H #include "platform.h" #if DEVICE_SPI #include "spi_api.h" #if DEVICE_SPI_ASYNCH #include "CThunk.h" #include "dma_api.h" #include "CircularBuffer.h" #include "FunctionPointer.h" #include "Transaction.h" #endif namespace mbed { /** A SPI Master, used for communicating with SPI slave devices * * The default format is set to 8-bits, mode 0, and a clock frequency of 1MHz * * Most SPI devices will also require Chip Select and Reset signals. These * can be controlled using pins * * Example: * @code * // Send a byte to a SPI slave, and record the response * * #include "mbed.h" * * // hardware ssel (where applicable) * //SPI device(p5, p6, p7, p8); // mosi, miso, sclk, ssel * * // software ssel * SPI device(p5, p6, p7); // mosi, miso, sclk * DigitalOut cs(p8); // ssel * * int main() { * // hardware ssel (where applicable) * //int response = device.write(0xFF); * * // software ssel * cs = 0; * int response = device.write(0xFF); * cs = 1; * } * @endcode */ class SPI { public: /** Create a SPI master connected to the specified pins * * mosi or miso can be specfied as NC if not used * * @param mosi SPI Master Out, Slave In pin * @param miso SPI Master In, Slave Out pin * @param sclk SPI Clock pin * @param ssel SPI chip select pin */ SPI(PinName mosi, PinName miso, PinName sclk, PinName ssel=NC); /** Configure the data transmission format * * @param bits Number of bits per SPI frame (4 - 16) * @param mode Clock polarity and phase mode (0 - 3) * * @code * mode | POL PHA * -----+-------- * 0 | 0 0 * 1 | 0 1 * 2 | 1 0 * 3 | 1 1 * @endcode */ void format(int bits, int mode = 0); /** Set the spi bus clock frequency * * @param hz SCLK frequency in hz (default = 1MHz) */ void frequency(int hz = 1000000); /** Write to the SPI Slave and return the response * * @param value Data to be sent to the SPI slave * * @returns * Response from the SPI slave */ virtual int write(int value); #if DEVICE_SPI_ASYNCH /** Start non-blocking SPI transfer using 8bit buffers. * * @param tx_buffer The TX buffer with data to be transfered. If NULL is passed, * the default SPI value is sent * @param tx_length The length of TX buffer in bytes * @param rx_buffer The RX buffer which is used for received data. If NULL is passed, * received data are ignored * @param rx_length The length of RX buffer in bytes * @param callback The event callback function * @param event The logical OR of events to modify. Look at spi hal header file for SPI events. * @return Zero if the transfer has started, or -1 if SPI peripheral is busy */ template int transfer(const Type *tx_buffer, int tx_length, Type *rx_buffer, int rx_length, const event_callback_t& callback, int event = SPI_EVENT_COMPLETE) { if (spi_active(&_spi)) { return queue_transfer(tx_buffer, tx_length, rx_buffer, rx_length, sizeof(Type)*8, callback, event); } start_transfer(tx_buffer, tx_length, rx_buffer, rx_length, sizeof(Type)*8, callback, event); return 0; } /** Abort the on-going SPI transfer, and continue with transfer's in the queue if any. */ void abort_transfer(); /** Clear the transaction buffer */ void clear_transfer_buffer(); /** Clear the transaction buffer and abort on-going transfer. */ void abort_all_transfers(); /** Configure DMA usage suggestion for non-blocking transfers * * @param usage The usage DMA hint for peripheral * @return Zero if the usage was set, -1 if a transaction is on-going */ int set_dma_usage(DMAUsage usage); protected: /** SPI IRQ handler * */ void irq_handler_asynch(void); /** Common transfer method * * @param tx_buffer The TX buffer with data to be transfered. If NULL is passed, * the default SPI value is sent * @param tx_length The length of TX buffer in bytes * @param rx_buffer The RX buffer which is used for received data. If NULL is passed, * received data are ignored * @param rx_length The length of RX buffer in bytes * @param bit_width The buffers element width * @param callback The event callback function * @param event The logical OR of events to modify * @return Zero if the transfer has started or was added to the queue, or -1 if SPI peripheral is busy/buffer is full */ int transfer(const void *tx_buffer, int tx_length, void *rx_buffer, int rx_length, unsigned char bit_width, const event_callback_t& callback, int event); /** * * @param tx_buffer The TX buffer with data to be transfered. If NULL is passed, * the default SPI value is sent * @param tx_length The length of TX buffer in bytes * @param rx_buffer The RX buffer which is used for received data. If NULL is passed, * received data are ignored * @param rx_length The length of RX buffer in bytes * @param bit_width The buffers element width * @param callback The event callback function * @param event The logical OR of events to modify * @return Zero if a transfer was added to the queue, or -1 if the queue is full */ int queue_transfer(const void *tx_buffer, int tx_length, void *rx_buffer, int rx_length, unsigned char bit_width, const event_callback_t& callback, int event); /** Configures a callback, spi peripheral and initiate a new transfer * * @param tx_buffer The TX buffer with data to be transfered. If NULL is passed, * the default SPI value is sent * @param tx_length The length of TX buffer in bytes * @param rx_buffer The RX buffer which is used for received data. If NULL is passed, * received data are ignored * @param rx_length The length of RX buffer in bytes * @param bit_width The buffers element width * @param callback The event callback function * @param event The logical OR of events to modify */ void start_transfer(const void *tx_buffer, int tx_length, void *rx_buffer, int rx_length, unsigned char bit_width, const event_callback_t& callback, int event); #if TRANSACTION_QUEUE_SIZE_SPI /** Start a new transaction * * @param data Transaction data */ void start_transaction(transaction_t *data); /** Dequeue a transaction * */ void dequeue_transaction(); static CircularBuffer, TRANSACTION_QUEUE_SIZE_SPI> _transaction_buffer; #endif #endif public: virtual ~SPI() { } protected: spi_t _spi; #if DEVICE_SPI_ASYNCH CThunk _irq; event_callback_t _callback; DMAUsage _usage; #endif void aquire(void); static SPI *_owner; int _bits; int _mode; int _hz; }; } // namespace mbed #endif #endif ================================================ FILE: Zelig/mbed/SPISlave.h ================================================ /* mbed Microcontroller Library * Copyright (c) 2006-2013 ARM Limited * * 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 MBED_SPISLAVE_H #define MBED_SPISLAVE_H #include "platform.h" #if DEVICE_SPISLAVE #include "spi_api.h" namespace mbed { /** A SPI slave, used for communicating with a SPI Master device * * The default format is set to 8-bits, mode 0, and a clock frequency of 1MHz * * Example: * @code * // Reply to a SPI master as slave * * #include "mbed.h" * * SPISlave device(p5, p6, p7, p8); // mosi, miso, sclk, ssel * * int main() { * device.reply(0x00); // Prime SPI with first reply * while(1) { * if(device.receive()) { * int v = device.read(); // Read byte from master * v = (v + 1) % 0x100; // Add one to it, modulo 256 * device.reply(v); // Make this the next reply * } * } * } * @endcode */ class SPISlave { public: /** Create a SPI slave connected to the specified pins * * Pin Options: * (5, 6, 7i, 8) or (11, 12, 13, 14) * * mosi or miso can be specfied as NC if not used * * @param mosi SPI Master Out, Slave In pin * @param miso SPI Master In, Slave Out pin * @param sclk SPI Clock pin * @param ssel SPI chip select pin * @param name (optional) A string to identify the object */ SPISlave(PinName mosi, PinName miso, PinName sclk, PinName ssel); /** Configure the data transmission format * * @param bits Number of bits per SPI frame (4 - 16) * @param mode Clock polarity and phase mode (0 - 3) * * @code * mode | POL PHA * -----+-------- * 0 | 0 0 * 1 | 0 1 * 2 | 1 0 * 3 | 1 1 * @endcode */ void format(int bits, int mode = 0); /** Set the spi bus clock frequency * * @param hz SCLK frequency in hz (default = 1MHz) */ void frequency(int hz = 1000000); /** Polls the SPI to see if data has been received * * @returns * 0 if no data, * 1 otherwise */ int receive(void); /** Retrieve data from receive buffer as slave * * @returns * the data in the receive buffer */ int read(void); /** Fill the transmission buffer with the value to be written out * as slave on the next received message from the master. * * @param value the data to be transmitted next */ void reply(int value); protected: spi_t _spi; int _bits; int _mode; int _hz; }; } // namespace mbed #endif #endif ================================================ FILE: Zelig/mbed/Serial.h ================================================ /* mbed Microcontroller Library * Copyright (c) 2006-2013 ARM Limited * * 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 MBED_SERIAL_H #define MBED_SERIAL_H #include "platform.h" #if DEVICE_SERIAL #include "Stream.h" #include "SerialBase.h" #include "serial_api.h" namespace mbed { /** A serial port (UART) for communication with other serial devices * * Can be used for Full Duplex communication, or Simplex by specifying * one pin as NC (Not Connected) * * Example: * @code * // Print "Hello World" to the PC * * #include "mbed.h" * * Serial pc(USBTX, USBRX); * * int main() { * pc.printf("Hello World\n"); * } * @endcode */ class Serial : public SerialBase, public Stream { public: #if DEVICE_SERIAL_ASYNCH using SerialBase::read; using SerialBase::write; #endif /** Create a Serial port, connected to the specified transmit and receive pins * * @param tx Transmit pin * @param rx Receive pin * * @note * Either tx or rx may be specified as NC if unused */ Serial(PinName tx, PinName rx, const char *name=NULL); protected: virtual int _getc(); virtual int _putc(int c); }; } // namespace mbed #endif #endif ================================================ FILE: Zelig/mbed/SerialBase.h ================================================ /* mbed Microcontroller Library * Copyright (c) 2006-2013 ARM Limited * * 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 MBED_SERIALBASE_H #define MBED_SERIALBASE_H #include "platform.h" #if DEVICE_SERIAL #include "Stream.h" #include "FunctionPointer.h" #include "serial_api.h" #if DEVICE_SERIAL_ASYNCH #include "CThunk.h" #include "dma_api.h" #endif namespace mbed { /** A base class for serial port implementations * Can't be instantiated directly (use Serial or RawSerial) */ class SerialBase { public: /** Set the baud rate of the serial port * * @param baudrate The baudrate of the serial port (default = 9600). */ void baud(int baudrate); enum Parity { None = 0, Odd, Even, Forced1, Forced0 }; enum IrqType { RxIrq = 0, TxIrq }; enum Flow { Disabled = 0, RTS, CTS, RTSCTS }; /** Set the transmission format used by the serial port * * @param bits The number of bits in a word (5-8; default = 8) * @param parity The parity used (SerialBase::None, SerialBase::Odd, SerialBase::Even, SerialBase::Forced1, SerialBase::Forced0; default = SerialBase::None) * @param stop The number of stop bits (1 or 2; default = 1) */ void format(int bits=8, Parity parity=SerialBase::None, int stop_bits=1); /** Determine if there is a character available to read * * @returns * 1 if there is a character available to read, * 0 otherwise */ int readable(); /** Determine if there is space available to write a character * * @returns * 1 if there is space to write a character, * 0 otherwise */ int writeable(); /** Attach a function to call whenever a serial interrupt is generated * * @param fptr A pointer to a void function, or 0 to set as none * @param type Which serial interrupt to attach the member function to (Seriall::RxIrq for receive, TxIrq for transmit buffer empty) */ void attach(void (*fptr)(void), IrqType type=RxIrq); /** Attach a member function to call whenever a serial interrupt is generated * * @param tptr pointer to the object to call the member function on * @param mptr pointer to the member function to be called * @param type Which serial interrupt to attach the member function to (Seriall::RxIrq for receive, TxIrq for transmit buffer empty) */ template void attach(T* tptr, void (T::*mptr)(void), IrqType type=RxIrq) { if((mptr != NULL) && (tptr != NULL)) { _irq[type].attach(tptr, mptr); serial_irq_set(&_serial, (SerialIrq)type, 1); } else { serial_irq_set(&_serial, (SerialIrq)type, 0); } } /** Generate a break condition on the serial line */ void send_break(); #if DEVICE_SERIAL_FC /** Set the flow control type on the serial port * * @param type the flow control type (Disabled, RTS, CTS, RTSCTS) * @param flow1 the first flow control pin (RTS for RTS or RTSCTS, CTS for CTS) * @param flow2 the second flow control pin (CTS for RTSCTS) */ void set_flow_control(Flow type, PinName flow1=NC, PinName flow2=NC); #endif static void _irq_handler(uint32_t id, SerialIrq irq_type); #if DEVICE_SERIAL_ASYNCH /** Begin asynchronous write using 8bit buffer. The completition invokes registered TX event callback * * @param buffer The buffer where received data will be stored * @param length The buffer length in bytes * @param callback The event callback function * @param event The logical OR of TX events */ int write(const uint8_t *buffer, int length, const event_callback_t& callback, int event = SERIAL_EVENT_TX_COMPLETE); /** Begin asynchronous write using 16bit buffer. The completition invokes registered TX event callback * * @param buffer The buffer where received data will be stored * @param length The buffer length in bytes * @param callback The event callback function * @param event The logical OR of TX events */ int write(const uint16_t *buffer, int length, const event_callback_t& callback, int event = SERIAL_EVENT_TX_COMPLETE); /** Abort the on-going write transfer */ void abort_write(); /** Begin asynchronous reading using 8bit buffer. The completition invokes registred RX event callback. * * @param buffer The buffer where received data will be stored * @param length The buffer length in bytes * @param callback The event callback function * @param event The logical OR of RX events * @param char_match The matching character */ int read(uint8_t *buffer, int length, const event_callback_t& callback, int event = SERIAL_EVENT_RX_COMPLETE, unsigned char char_match = SERIAL_RESERVED_CHAR_MATCH); /** Begin asynchronous reading using 16bit buffer. The completition invokes registred RX event callback. * * @param buffer The buffer where received data will be stored * @param length The buffer length in bytes * @param callback The event callback function * @param event The logical OR of RX events * @param char_match The matching character */ int read(uint16_t *buffer, int length, const event_callback_t& callback, int event = SERIAL_EVENT_RX_COMPLETE, unsigned char char_match = SERIAL_RESERVED_CHAR_MATCH); /** Abort the on-going read transfer */ void abort_read(); /** Configure DMA usage suggestion for non-blocking TX transfers * * @param usage The usage DMA hint for peripheral * @return Zero if the usage was set, -1 if a transaction is on-going */ int set_dma_usage_tx(DMAUsage usage); /** Configure DMA usage suggestion for non-blocking RX transfers * * @param usage The usage DMA hint for peripheral * @return Zero if the usage was set, -1 if a transaction is on-going */ int set_dma_usage_rx(DMAUsage usage); protected: void start_read(void *buffer, int buffer_size, char buffer_width, const event_callback_t& callback, int event, unsigned char char_match); void start_write(const void *buffer, int buffer_size, char buffer_width, const event_callback_t& callback, int event); void interrupt_handler_asynch(void); #endif protected: SerialBase(PinName tx, PinName rx); virtual ~SerialBase() { } int _base_getc(); int _base_putc(int c); #if DEVICE_SERIAL_ASYNCH CThunk _thunk_irq; event_callback_t _tx_callback; event_callback_t _rx_callback; DMAUsage _tx_usage; DMAUsage _rx_usage; #endif serial_t _serial; FunctionPointer _irq[2]; int _baud; }; } // namespace mbed #endif #endif ================================================ FILE: Zelig/mbed/Stream.h ================================================ /* mbed Microcontroller Library * Copyright (c) 2006-2013 ARM Limited * * 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 MBED_STREAM_H #define MBED_STREAM_H #include "platform.h" #include "FileLike.h" namespace mbed { extern void mbed_set_unbuffered_stream(FILE *_file); extern int mbed_getc(FILE *_file); extern char* mbed_gets(char *s, int size, FILE *_file); class Stream : public FileLike { public: Stream(const char *name=NULL); virtual ~Stream(); int putc(int c); int puts(const char *s); int getc(); char *gets(char *s, int size); int printf(const char* format, ...); int scanf(const char* format, ...); operator std::FILE*() {return _file;} protected: virtual int close(); virtual ssize_t write(const void* buffer, size_t length); virtual ssize_t read(void* buffer, size_t length); virtual off_t lseek(off_t offset, int whence); virtual int isatty(); virtual int fsync(); virtual off_t flen(); virtual int _putc(int c) = 0; virtual int _getc() = 0; std::FILE *_file; /* disallow copy constructor and assignment operators */ private: Stream(const Stream&); Stream & operator = (const Stream&); }; } // namespace mbed #endif ================================================ FILE: Zelig/mbed/TARGET_K64F/MK64F12.h ================================================ /* ** ################################################################### ** Processors: MK64FN1M0VDC12 ** MK64FN1M0VLL12 ** MK64FN1M0VLQ12 ** MK64FN1M0VMD12 ** ** Compilers: Keil ARM C/C++ Compiler ** Freescale C/C++ for Embedded ARM ** GNU C Compiler ** GNU C Compiler - CodeSourcery Sourcery G++ ** IAR ANSI C/C++ Compiler for ARM ** ** Reference manual: K64P144M120SF5RM, Rev.2, January 2014 ** Version: rev. 2.5, 2014-02-10 ** Build: b140604 ** ** Abstract: ** CMSIS Peripheral Access Layer for MK64F12 ** ** Copyright (c) 1997 - 2014 Freescale Semiconductor, Inc. ** All rights reserved. ** ** Redistribution and use in source and binary forms, with or without modification, ** are permitted provided that the following conditions are met: ** ** o Redistributions of source code must retain the above copyright notice, this list ** of conditions and the following disclaimer. ** ** o Redistributions in binary form must reproduce the above copyright notice, this ** list of conditions and the following disclaimer in the documentation and/or ** other materials provided with the distribution. ** ** o Neither the name of Freescale Semiconductor, Inc. nor the names of its ** contributors may be used to endorse or promote products derived from this ** software without specific prior written permission. ** ** THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ** ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED ** WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE ** DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT 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. ** ** http: www.freescale.com ** mail: support@freescale.com ** ** Revisions: ** - rev. 1.0 (2013-08-12) ** Initial version. ** - rev. 2.0 (2013-10-29) ** Register accessor macros added to the memory map. ** Symbols for Processor Expert memory map compatibility added to the memory map. ** Startup file for gcc has been updated according to CMSIS 3.2. ** System initialization updated. ** MCG - registers updated. ** PORTA, PORTB, PORTC, PORTE - registers for digital filter removed. ** - rev. 2.1 (2013-10-30) ** Definition of BITBAND macros updated to support peripherals with 32-bit acces disabled. ** - rev. 2.2 (2013-12-09) ** DMA - EARS register removed. ** AIPS0, AIPS1 - MPRA register updated. ** - rev. 2.3 (2014-01-24) ** Update according to reference manual rev. 2 ** ENET, MCG, MCM, SIM, USB - registers updated ** - rev. 2.4 (2014-02-10) ** The declaration of clock configurations has been moved to separate header file system_MK64F12.h ** Update of SystemInit() and SystemCoreClockUpdate() functions. ** - rev. 2.5 (2014-02-10) ** The declaration of clock configurations has been moved to separate header file system_MK64F12.h ** Update of SystemInit() and SystemCoreClockUpdate() functions. ** Module access macro module_BASES replaced by module_BASE_PTRS. ** ** ################################################################### */ /*! * @file MK64F12.h * @version 2.5 * @date 2014-02-10 * @brief CMSIS Peripheral Access Layer for MK64F12 * * CMSIS Peripheral Access Layer for MK64F12 */ /* ---------------------------------------------------------------------------- -- MCU activation ---------------------------------------------------------------------------- */ /* Prevention from multiple including the same memory map */ #if !defined(MK64F12_H_) /* Check if memory map has not been already included */ #define MK64F12_H_ #define MCU_MK64F12 /* Check if another memory map has not been also included */ #if (defined(MCU_ACTIVE)) #error MK64F12 memory map: There is already included another memory map. Only one memory map can be included. #endif /* (defined(MCU_ACTIVE)) */ #define MCU_ACTIVE #include /** Memory map major version (memory maps with equal major version number are * compatible) */ #define MCU_MEM_MAP_VERSION 0x0200u /** Memory map minor version */ #define MCU_MEM_MAP_VERSION_MINOR 0x0005u /** * @brief Macro to calculate address of an aliased word in the peripheral * bitband area for a peripheral register and bit (bit band region 0x40000000 to * 0x400FFFFF). * @param Reg Register to access. * @param Bit Bit number to access. * @return Address of the aliased word in the peripheral bitband area. */ #define BITBAND_REGADDR(Reg,Bit) (0x42000000u + (32u*((uint32_t)&(Reg) - (uint32_t)0x40000000u)) + (4u*((uint32_t)(Bit)))) /** * @brief Macro to access a single bit of a peripheral register (bit band region * 0x40000000 to 0x400FFFFF) using the bit-band alias region access. Can * be used for peripherals with 32bit access allowed. * @param Reg Register to access. * @param Bit Bit number to access. * @return Value of the targeted bit in the bit band region. */ #define BITBAND_REG32(Reg,Bit) (*((uint32_t volatile*)(BITBAND_REGADDR(Reg,Bit)))) #define BITBAND_REG(Reg,Bit) (BITBAND_REG32(Reg,Bit)) /** * @brief Macro to access a single bit of a peripheral register (bit band region * 0x40000000 to 0x400FFFFF) using the bit-band alias region access. Can * be used for peripherals with 16bit access allowed. * @param Reg Register to access. * @param Bit Bit number to access. * @return Value of the targeted bit in the bit band region. */ #define BITBAND_REG16(Reg,Bit) (*((uint16_t volatile*)(BITBAND_REGADDR(Reg,Bit)))) /** * @brief Macro to access a single bit of a peripheral register (bit band region * 0x40000000 to 0x400FFFFF) using the bit-band alias region access. Can * be used for peripherals with 8bit access allowed. * @param Reg Register to access. * @param Bit Bit number to access. * @return Value of the targeted bit in the bit band region. */ #define BITBAND_REG8(Reg,Bit) (*((uint8_t volatile*)(BITBAND_REGADDR(Reg,Bit)))) /* ---------------------------------------------------------------------------- -- Interrupt vector numbers ---------------------------------------------------------------------------- */ /*! * @addtogroup Interrupt_vector_numbers Interrupt vector numbers * @{ */ /** Interrupt Number Definitions */ #define NUMBER_OF_INT_VECTORS 102 /**< Number of interrupts in the Vector table */ typedef enum IRQn { /* Core interrupts */ NonMaskableInt_IRQn = -14, /**< Non Maskable Interrupt */ HardFault_IRQn = -13, /**< Cortex-M4 SV Hard Fault Interrupt */ MemoryManagement_IRQn = -12, /**< Cortex-M4 Memory Management Interrupt */ BusFault_IRQn = -11, /**< Cortex-M4 Bus Fault Interrupt */ UsageFault_IRQn = -10, /**< Cortex-M4 Usage Fault Interrupt */ SVCall_IRQn = -5, /**< Cortex-M4 SV Call Interrupt */ DebugMonitor_IRQn = -4, /**< Cortex-M4 Debug Monitor Interrupt */ PendSV_IRQn = -2, /**< Cortex-M4 Pend SV Interrupt */ SysTick_IRQn = -1, /**< Cortex-M4 System Tick Interrupt */ /* Device specific interrupts */ DMA0_IRQn = 0, /**< DMA Channel 0 Transfer Complete */ DMA1_IRQn = 1, /**< DMA Channel 1 Transfer Complete */ DMA2_IRQn = 2, /**< DMA Channel 2 Transfer Complete */ DMA3_IRQn = 3, /**< DMA Channel 3 Transfer Complete */ DMA4_IRQn = 4, /**< DMA Channel 4 Transfer Complete */ DMA5_IRQn = 5, /**< DMA Channel 5 Transfer Complete */ DMA6_IRQn = 6, /**< DMA Channel 6 Transfer Complete */ DMA7_IRQn = 7, /**< DMA Channel 7 Transfer Complete */ DMA8_IRQn = 8, /**< DMA Channel 8 Transfer Complete */ DMA9_IRQn = 9, /**< DMA Channel 9 Transfer Complete */ DMA10_IRQn = 10, /**< DMA Channel 10 Transfer Complete */ DMA11_IRQn = 11, /**< DMA Channel 11 Transfer Complete */ DMA12_IRQn = 12, /**< DMA Channel 12 Transfer Complete */ DMA13_IRQn = 13, /**< DMA Channel 13 Transfer Complete */ DMA14_IRQn = 14, /**< DMA Channel 14 Transfer Complete */ DMA15_IRQn = 15, /**< DMA Channel 15 Transfer Complete */ DMA_Error_IRQn = 16, /**< DMA Error Interrupt */ MCM_IRQn = 17, /**< Normal Interrupt */ FTFE_IRQn = 18, /**< FTFE Command complete interrupt */ Read_Collision_IRQn = 19, /**< Read Collision Interrupt */ LVD_LVW_IRQn = 20, /**< Low Voltage Detect, Low Voltage Warning */ LLW_IRQn = 21, /**< Low Leakage Wakeup */ Watchdog_IRQn = 22, /**< WDOG Interrupt */ RNG_IRQn = 23, /**< RNG Interrupt */ I2C0_IRQn = 24, /**< I2C0 interrupt */ I2C1_IRQn = 25, /**< I2C1 interrupt */ SPI0_IRQn = 26, /**< SPI0 Interrupt */ SPI1_IRQn = 27, /**< SPI1 Interrupt */ I2S0_Tx_IRQn = 28, /**< I2S0 transmit interrupt */ I2S0_Rx_IRQn = 29, /**< I2S0 receive interrupt */ UART0_LON_IRQn = 30, /**< UART0 LON interrupt */ UART0_RX_TX_IRQn = 31, /**< UART0 Receive/Transmit interrupt */ UART0_ERR_IRQn = 32, /**< UART0 Error interrupt */ UART1_RX_TX_IRQn = 33, /**< UART1 Receive/Transmit interrupt */ UART1_ERR_IRQn = 34, /**< UART1 Error interrupt */ UART2_RX_TX_IRQn = 35, /**< UART2 Receive/Transmit interrupt */ UART2_ERR_IRQn = 36, /**< UART2 Error interrupt */ UART3_RX_TX_IRQn = 37, /**< UART3 Receive/Transmit interrupt */ UART3_ERR_IRQn = 38, /**< UART3 Error interrupt */ ADC0_IRQn = 39, /**< ADC0 interrupt */ CMP0_IRQn = 40, /**< CMP0 interrupt */ CMP1_IRQn = 41, /**< CMP1 interrupt */ FTM0_IRQn = 42, /**< FTM0 fault, overflow and channels interrupt */ FTM1_IRQn = 43, /**< FTM1 fault, overflow and channels interrupt */ FTM2_IRQn = 44, /**< FTM2 fault, overflow and channels interrupt */ CMT_IRQn = 45, /**< CMT interrupt */ RTC_IRQn = 46, /**< RTC interrupt */ RTC_Seconds_IRQn = 47, /**< RTC seconds interrupt */ PIT0_IRQn = 48, /**< PIT timer channel 0 interrupt */ PIT1_IRQn = 49, /**< PIT timer channel 1 interrupt */ PIT2_IRQn = 50, /**< PIT timer channel 2 interrupt */ PIT3_IRQn = 51, /**< PIT timer channel 3 interrupt */ PDB0_IRQn = 52, /**< PDB0 Interrupt */ USB0_IRQn = 53, /**< USB0 interrupt */ USBDCD_IRQn = 54, /**< USBDCD Interrupt */ Reserved71_IRQn = 55, /**< Reserved interrupt 71 */ DAC0_IRQn = 56, /**< DAC0 interrupt */ MCG_IRQn = 57, /**< MCG Interrupt */ LPTimer_IRQn = 58, /**< LPTimer interrupt */ PORTA_IRQn = 59, /**< Port A interrupt */ PORTB_IRQn = 60, /**< Port B interrupt */ PORTC_IRQn = 61, /**< Port C interrupt */ PORTD_IRQn = 62, /**< Port D interrupt */ PORTE_IRQn = 63, /**< Port E interrupt */ SWI_IRQn = 64, /**< Software interrupt */ SPI2_IRQn = 65, /**< SPI2 Interrupt */ UART4_RX_TX_IRQn = 66, /**< UART4 Receive/Transmit interrupt */ UART4_ERR_IRQn = 67, /**< UART4 Error interrupt */ UART5_RX_TX_IRQn = 68, /**< UART5 Receive/Transmit interrupt */ UART5_ERR_IRQn = 69, /**< UART5 Error interrupt */ CMP2_IRQn = 70, /**< CMP2 interrupt */ FTM3_IRQn = 71, /**< FTM3 fault, overflow and channels interrupt */ DAC1_IRQn = 72, /**< DAC1 interrupt */ ADC1_IRQn = 73, /**< ADC1 interrupt */ I2C2_IRQn = 74, /**< I2C2 interrupt */ CAN0_ORed_Message_buffer_IRQn = 75, /**< CAN0 OR'd message buffers interrupt */ CAN0_Bus_Off_IRQn = 76, /**< CAN0 bus off interrupt */ CAN0_Error_IRQn = 77, /**< CAN0 error interrupt */ CAN0_Tx_Warning_IRQn = 78, /**< CAN0 Tx warning interrupt */ CAN0_Rx_Warning_IRQn = 79, /**< CAN0 Rx warning interrupt */ CAN0_Wake_Up_IRQn = 80, /**< CAN0 wake up interrupt */ SDHC_IRQn = 81, /**< SDHC interrupt */ ENET_1588_Timer_IRQn = 82, /**< Ethernet MAC IEEE 1588 Timer Interrupt */ ENET_Transmit_IRQn = 83, /**< Ethernet MAC Transmit Interrupt */ ENET_Receive_IRQn = 84, /**< Ethernet MAC Receive Interrupt */ ENET_Error_IRQn = 85 /**< Ethernet MAC Error and miscelaneous Interrupt */ } IRQn_Type; /*! * @} */ /* end of group Interrupt_vector_numbers */ /* ---------------------------------------------------------------------------- -- Cortex M4 Core Configuration ---------------------------------------------------------------------------- */ /*! * @addtogroup Cortex_Core_Configuration Cortex M4 Core Configuration * @{ */ #define __MPU_PRESENT 0 /**< Defines if an MPU is present or not */ #define __NVIC_PRIO_BITS 4 /**< Number of priority bits implemented in the NVIC */ #define __Vendor_SysTickConfig 0 /**< Vendor specific implementation of SysTickConfig is defined */ #define __FPU_PRESENT 1 /**< Defines if an FPU is present or not */ #include "core_cm4.h" /* Core Peripheral Access Layer */ #include "system_MK64F12.h" /* Device specific configuration file */ /*! * @} */ /* end of group Cortex_Core_Configuration */ /* ---------------------------------------------------------------------------- -- Device Peripheral Access Layer ---------------------------------------------------------------------------- */ /*! * @addtogroup Peripheral_access_layer Device Peripheral Access Layer * @{ */ /* ** Start of section using anonymous unions */ #if defined(__ARMCC_VERSION) #pragma push #pragma anon_unions #elif defined(__CWCC__) #pragma push #pragma cpp_extensions on #elif defined(__GNUC__) /* anonymous unions are enabled by default */ #elif defined(__IAR_SYSTEMS_ICC__) #pragma language=extended #else #error Not supported compiler type #endif /* ---------------------------------------------------------------------------- -- ADC Peripheral Access Layer ---------------------------------------------------------------------------- */ /*! * @addtogroup ADC_Peripheral_Access_Layer ADC Peripheral Access Layer * @{ */ /** ADC - Register Layout Typedef */ typedef struct { __IO uint32_t SC1[2]; /**< ADC Status and Control Registers 1, array offset: 0x0, array step: 0x4 */ __IO uint32_t CFG1; /**< ADC Configuration Register 1, offset: 0x8 */ __IO uint32_t CFG2; /**< ADC Configuration Register 2, offset: 0xC */ __I uint32_t R[2]; /**< ADC Data Result Register, array offset: 0x10, array step: 0x4 */ __IO uint32_t CV1; /**< Compare Value Registers, offset: 0x18 */ __IO uint32_t CV2; /**< Compare Value Registers, offset: 0x1C */ __IO uint32_t SC2; /**< Status and Control Register 2, offset: 0x20 */ __IO uint32_t SC3; /**< Status and Control Register 3, offset: 0x24 */ __IO uint32_t OFS; /**< ADC Offset Correction Register, offset: 0x28 */ __IO uint32_t PG; /**< ADC Plus-Side Gain Register, offset: 0x2C */ __IO uint32_t MG; /**< ADC Minus-Side Gain Register, offset: 0x30 */ __IO uint32_t CLPD; /**< ADC Plus-Side General Calibration Value Register, offset: 0x34 */ __IO uint32_t CLPS; /**< ADC Plus-Side General Calibration Value Register, offset: 0x38 */ __IO uint32_t CLP4; /**< ADC Plus-Side General Calibration Value Register, offset: 0x3C */ __IO uint32_t CLP3; /**< ADC Plus-Side General Calibration Value Register, offset: 0x40 */ __IO uint32_t CLP2; /**< ADC Plus-Side General Calibration Value Register, offset: 0x44 */ __IO uint32_t CLP1; /**< ADC Plus-Side General Calibration Value Register, offset: 0x48 */ __IO uint32_t CLP0; /**< ADC Plus-Side General Calibration Value Register, offset: 0x4C */ uint8_t RESERVED_0[4]; __IO uint32_t CLMD; /**< ADC Minus-Side General Calibration Value Register, offset: 0x54 */ __IO uint32_t CLMS; /**< ADC Minus-Side General Calibration Value Register, offset: 0x58 */ __IO uint32_t CLM4; /**< ADC Minus-Side General Calibration Value Register, offset: 0x5C */ __IO uint32_t CLM3; /**< ADC Minus-Side General Calibration Value Register, offset: 0x60 */ __IO uint32_t CLM2; /**< ADC Minus-Side General Calibration Value Register, offset: 0x64 */ __IO uint32_t CLM1; /**< ADC Minus-Side General Calibration Value Register, offset: 0x68 */ __IO uint32_t CLM0; /**< ADC Minus-Side General Calibration Value Register, offset: 0x6C */ } ADC_Type, *ADC_MemMapPtr; /* ---------------------------------------------------------------------------- -- ADC - Register accessor macros ---------------------------------------------------------------------------- */ /*! * @addtogroup ADC_Register_Accessor_Macros ADC - Register accessor macros * @{ */ /* ADC - Register accessors */ #define ADC_SC1_REG(base,index) ((base)->SC1[index]) #define ADC_CFG1_REG(base) ((base)->CFG1) #define ADC_CFG2_REG(base) ((base)->CFG2) #define ADC_R_REG(base,index) ((base)->R[index]) #define ADC_CV1_REG(base) ((base)->CV1) #define ADC_CV2_REG(base) ((base)->CV2) #define ADC_SC2_REG(base) ((base)->SC2) #define ADC_SC3_REG(base) ((base)->SC3) #define ADC_OFS_REG(base) ((base)->OFS) #define ADC_PG_REG(base) ((base)->PG) #define ADC_MG_REG(base) ((base)->MG) #define ADC_CLPD_REG(base) ((base)->CLPD) #define ADC_CLPS_REG(base) ((base)->CLPS) #define ADC_CLP4_REG(base) ((base)->CLP4) #define ADC_CLP3_REG(base) ((base)->CLP3) #define ADC_CLP2_REG(base) ((base)->CLP2) #define ADC_CLP1_REG(base) ((base)->CLP1) #define ADC_CLP0_REG(base) ((base)->CLP0) #define ADC_CLMD_REG(base) ((base)->CLMD) #define ADC_CLMS_REG(base) ((base)->CLMS) #define ADC_CLM4_REG(base) ((base)->CLM4) #define ADC_CLM3_REG(base) ((base)->CLM3) #define ADC_CLM2_REG(base) ((base)->CLM2) #define ADC_CLM1_REG(base) ((base)->CLM1) #define ADC_CLM0_REG(base) ((base)->CLM0) /*! * @} */ /* end of group ADC_Register_Accessor_Macros */ /* ---------------------------------------------------------------------------- -- ADC Register Masks ---------------------------------------------------------------------------- */ /*! * @addtogroup ADC_Register_Masks ADC Register Masks * @{ */ /* SC1 Bit Fields */ #define ADC_SC1_ADCH_MASK 0x1Fu #define ADC_SC1_ADCH_SHIFT 0 #define ADC_SC1_ADCH(x) (((uint32_t)(((uint32_t)(x))<MPRA) #define AIPS_PACRA_REG(base) ((base)->PACRA) #define AIPS_PACRB_REG(base) ((base)->PACRB) #define AIPS_PACRC_REG(base) ((base)->PACRC) #define AIPS_PACRD_REG(base) ((base)->PACRD) #define AIPS_PACRE_REG(base) ((base)->PACRE) #define AIPS_PACRF_REG(base) ((base)->PACRF) #define AIPS_PACRG_REG(base) ((base)->PACRG) #define AIPS_PACRH_REG(base) ((base)->PACRH) #define AIPS_PACRI_REG(base) ((base)->PACRI) #define AIPS_PACRJ_REG(base) ((base)->PACRJ) #define AIPS_PACRK_REG(base) ((base)->PACRK) #define AIPS_PACRL_REG(base) ((base)->PACRL) #define AIPS_PACRM_REG(base) ((base)->PACRM) #define AIPS_PACRN_REG(base) ((base)->PACRN) #define AIPS_PACRO_REG(base) ((base)->PACRO) #define AIPS_PACRP_REG(base) ((base)->PACRP) #define AIPS_PACRU_REG(base) ((base)->PACRU) /*! * @} */ /* end of group AIPS_Register_Accessor_Macros */ /* ---------------------------------------------------------------------------- -- AIPS Register Masks ---------------------------------------------------------------------------- */ /*! * @addtogroup AIPS_Register_Masks AIPS Register Masks * @{ */ /* MPRA Bit Fields */ #define AIPS_MPRA_MPL5_MASK 0x100u #define AIPS_MPRA_MPL5_SHIFT 8 #define AIPS_MPRA_MTW5_MASK 0x200u #define AIPS_MPRA_MTW5_SHIFT 9 #define AIPS_MPRA_MTR5_MASK 0x400u #define AIPS_MPRA_MTR5_SHIFT 10 #define AIPS_MPRA_MPL4_MASK 0x1000u #define AIPS_MPRA_MPL4_SHIFT 12 #define AIPS_MPRA_MTW4_MASK 0x2000u #define AIPS_MPRA_MTW4_SHIFT 13 #define AIPS_MPRA_MTR4_MASK 0x4000u #define AIPS_MPRA_MTR4_SHIFT 14 #define AIPS_MPRA_MPL3_MASK 0x10000u #define AIPS_MPRA_MPL3_SHIFT 16 #define AIPS_MPRA_MTW3_MASK 0x20000u #define AIPS_MPRA_MTW3_SHIFT 17 #define AIPS_MPRA_MTR3_MASK 0x40000u #define AIPS_MPRA_MTR3_SHIFT 18 #define AIPS_MPRA_MPL2_MASK 0x100000u #define AIPS_MPRA_MPL2_SHIFT 20 #define AIPS_MPRA_MTW2_MASK 0x200000u #define AIPS_MPRA_MTW2_SHIFT 21 #define AIPS_MPRA_MTR2_MASK 0x400000u #define AIPS_MPRA_MTR2_SHIFT 22 #define AIPS_MPRA_MPL1_MASK 0x1000000u #define AIPS_MPRA_MPL1_SHIFT 24 #define AIPS_MPRA_MTW1_MASK 0x2000000u #define AIPS_MPRA_MTW1_SHIFT 25 #define AIPS_MPRA_MTR1_MASK 0x4000000u #define AIPS_MPRA_MTR1_SHIFT 26 #define AIPS_MPRA_MPL0_MASK 0x10000000u #define AIPS_MPRA_MPL0_SHIFT 28 #define AIPS_MPRA_MTW0_MASK 0x20000000u #define AIPS_MPRA_MTW0_SHIFT 29 #define AIPS_MPRA_MTR0_MASK 0x40000000u #define AIPS_MPRA_MTR0_SHIFT 30 /* PACRA Bit Fields */ #define AIPS_PACRA_TP7_MASK 0x1u #define AIPS_PACRA_TP7_SHIFT 0 #define AIPS_PACRA_WP7_MASK 0x2u #define AIPS_PACRA_WP7_SHIFT 1 #define AIPS_PACRA_SP7_MASK 0x4u #define AIPS_PACRA_SP7_SHIFT 2 #define AIPS_PACRA_TP6_MASK 0x10u #define AIPS_PACRA_TP6_SHIFT 4 #define AIPS_PACRA_WP6_MASK 0x20u #define AIPS_PACRA_WP6_SHIFT 5 #define AIPS_PACRA_SP6_MASK 0x40u #define AIPS_PACRA_SP6_SHIFT 6 #define AIPS_PACRA_TP5_MASK 0x100u #define AIPS_PACRA_TP5_SHIFT 8 #define AIPS_PACRA_WP5_MASK 0x200u #define AIPS_PACRA_WP5_SHIFT 9 #define AIPS_PACRA_SP5_MASK 0x400u #define AIPS_PACRA_SP5_SHIFT 10 #define AIPS_PACRA_TP4_MASK 0x1000u #define AIPS_PACRA_TP4_SHIFT 12 #define AIPS_PACRA_WP4_MASK 0x2000u #define AIPS_PACRA_WP4_SHIFT 13 #define AIPS_PACRA_SP4_MASK 0x4000u #define AIPS_PACRA_SP4_SHIFT 14 #define AIPS_PACRA_TP3_MASK 0x10000u #define AIPS_PACRA_TP3_SHIFT 16 #define AIPS_PACRA_WP3_MASK 0x20000u #define AIPS_PACRA_WP3_SHIFT 17 #define AIPS_PACRA_SP3_MASK 0x40000u #define AIPS_PACRA_SP3_SHIFT 18 #define AIPS_PACRA_TP2_MASK 0x100000u #define AIPS_PACRA_TP2_SHIFT 20 #define AIPS_PACRA_WP2_MASK 0x200000u #define AIPS_PACRA_WP2_SHIFT 21 #define AIPS_PACRA_SP2_MASK 0x400000u #define AIPS_PACRA_SP2_SHIFT 22 #define AIPS_PACRA_TP1_MASK 0x1000000u #define AIPS_PACRA_TP1_SHIFT 24 #define AIPS_PACRA_WP1_MASK 0x2000000u #define AIPS_PACRA_WP1_SHIFT 25 #define AIPS_PACRA_SP1_MASK 0x4000000u #define AIPS_PACRA_SP1_SHIFT 26 #define AIPS_PACRA_TP0_MASK 0x10000000u #define AIPS_PACRA_TP0_SHIFT 28 #define AIPS_PACRA_WP0_MASK 0x20000000u #define AIPS_PACRA_WP0_SHIFT 29 #define AIPS_PACRA_SP0_MASK 0x40000000u #define AIPS_PACRA_SP0_SHIFT 30 /* PACRB Bit Fields */ #define AIPS_PACRB_TP7_MASK 0x1u #define AIPS_PACRB_TP7_SHIFT 0 #define AIPS_PACRB_WP7_MASK 0x2u #define AIPS_PACRB_WP7_SHIFT 1 #define AIPS_PACRB_SP7_MASK 0x4u #define AIPS_PACRB_SP7_SHIFT 2 #define AIPS_PACRB_TP6_MASK 0x10u #define AIPS_PACRB_TP6_SHIFT 4 #define AIPS_PACRB_WP6_MASK 0x20u #define AIPS_PACRB_WP6_SHIFT 5 #define AIPS_PACRB_SP6_MASK 0x40u #define AIPS_PACRB_SP6_SHIFT 6 #define AIPS_PACRB_TP5_MASK 0x100u #define AIPS_PACRB_TP5_SHIFT 8 #define AIPS_PACRB_WP5_MASK 0x200u #define AIPS_PACRB_WP5_SHIFT 9 #define AIPS_PACRB_SP5_MASK 0x400u #define AIPS_PACRB_SP5_SHIFT 10 #define AIPS_PACRB_TP4_MASK 0x1000u #define AIPS_PACRB_TP4_SHIFT 12 #define AIPS_PACRB_WP4_MASK 0x2000u #define AIPS_PACRB_WP4_SHIFT 13 #define AIPS_PACRB_SP4_MASK 0x4000u #define AIPS_PACRB_SP4_SHIFT 14 #define AIPS_PACRB_TP3_MASK 0x10000u #define AIPS_PACRB_TP3_SHIFT 16 #define AIPS_PACRB_WP3_MASK 0x20000u #define AIPS_PACRB_WP3_SHIFT 17 #define AIPS_PACRB_SP3_MASK 0x40000u #define AIPS_PACRB_SP3_SHIFT 18 #define AIPS_PACRB_TP2_MASK 0x100000u #define AIPS_PACRB_TP2_SHIFT 20 #define AIPS_PACRB_WP2_MASK 0x200000u #define AIPS_PACRB_WP2_SHIFT 21 #define AIPS_PACRB_SP2_MASK 0x400000u #define AIPS_PACRB_SP2_SHIFT 22 #define AIPS_PACRB_TP1_MASK 0x1000000u #define AIPS_PACRB_TP1_SHIFT 24 #define AIPS_PACRB_WP1_MASK 0x2000000u #define AIPS_PACRB_WP1_SHIFT 25 #define AIPS_PACRB_SP1_MASK 0x4000000u #define AIPS_PACRB_SP1_SHIFT 26 #define AIPS_PACRB_TP0_MASK 0x10000000u #define AIPS_PACRB_TP0_SHIFT 28 #define AIPS_PACRB_WP0_MASK 0x20000000u #define AIPS_PACRB_WP0_SHIFT 29 #define AIPS_PACRB_SP0_MASK 0x40000000u #define AIPS_PACRB_SP0_SHIFT 30 /* PACRC Bit Fields */ #define AIPS_PACRC_TP7_MASK 0x1u #define AIPS_PACRC_TP7_SHIFT 0 #define AIPS_PACRC_WP7_MASK 0x2u #define AIPS_PACRC_WP7_SHIFT 1 #define AIPS_PACRC_SP7_MASK 0x4u #define AIPS_PACRC_SP7_SHIFT 2 #define AIPS_PACRC_TP6_MASK 0x10u #define AIPS_PACRC_TP6_SHIFT 4 #define AIPS_PACRC_WP6_MASK 0x20u #define AIPS_PACRC_WP6_SHIFT 5 #define AIPS_PACRC_SP6_MASK 0x40u #define AIPS_PACRC_SP6_SHIFT 6 #define AIPS_PACRC_TP5_MASK 0x100u #define AIPS_PACRC_TP5_SHIFT 8 #define AIPS_PACRC_WP5_MASK 0x200u #define AIPS_PACRC_WP5_SHIFT 9 #define AIPS_PACRC_SP5_MASK 0x400u #define AIPS_PACRC_SP5_SHIFT 10 #define AIPS_PACRC_TP4_MASK 0x1000u #define AIPS_PACRC_TP4_SHIFT 12 #define AIPS_PACRC_WP4_MASK 0x2000u #define AIPS_PACRC_WP4_SHIFT 13 #define AIPS_PACRC_SP4_MASK 0x4000u #define AIPS_PACRC_SP4_SHIFT 14 #define AIPS_PACRC_TP3_MASK 0x10000u #define AIPS_PACRC_TP3_SHIFT 16 #define AIPS_PACRC_WP3_MASK 0x20000u #define AIPS_PACRC_WP3_SHIFT 17 #define AIPS_PACRC_SP3_MASK 0x40000u #define AIPS_PACRC_SP3_SHIFT 18 #define AIPS_PACRC_TP2_MASK 0x100000u #define AIPS_PACRC_TP2_SHIFT 20 #define AIPS_PACRC_WP2_MASK 0x200000u #define AIPS_PACRC_WP2_SHIFT 21 #define AIPS_PACRC_SP2_MASK 0x400000u #define AIPS_PACRC_SP2_SHIFT 22 #define AIPS_PACRC_TP1_MASK 0x1000000u #define AIPS_PACRC_TP1_SHIFT 24 #define AIPS_PACRC_WP1_MASK 0x2000000u #define AIPS_PACRC_WP1_SHIFT 25 #define AIPS_PACRC_SP1_MASK 0x4000000u #define AIPS_PACRC_SP1_SHIFT 26 #define AIPS_PACRC_TP0_MASK 0x10000000u #define AIPS_PACRC_TP0_SHIFT 28 #define AIPS_PACRC_WP0_MASK 0x20000000u #define AIPS_PACRC_WP0_SHIFT 29 #define AIPS_PACRC_SP0_MASK 0x40000000u #define AIPS_PACRC_SP0_SHIFT 30 /* PACRD Bit Fields */ #define AIPS_PACRD_TP7_MASK 0x1u #define AIPS_PACRD_TP7_SHIFT 0 #define AIPS_PACRD_WP7_MASK 0x2u #define AIPS_PACRD_WP7_SHIFT 1 #define AIPS_PACRD_SP7_MASK 0x4u #define AIPS_PACRD_SP7_SHIFT 2 #define AIPS_PACRD_TP6_MASK 0x10u #define AIPS_PACRD_TP6_SHIFT 4 #define AIPS_PACRD_WP6_MASK 0x20u #define AIPS_PACRD_WP6_SHIFT 5 #define AIPS_PACRD_SP6_MASK 0x40u #define AIPS_PACRD_SP6_SHIFT 6 #define AIPS_PACRD_TP5_MASK 0x100u #define AIPS_PACRD_TP5_SHIFT 8 #define AIPS_PACRD_WP5_MASK 0x200u #define AIPS_PACRD_WP5_SHIFT 9 #define AIPS_PACRD_SP5_MASK 0x400u #define AIPS_PACRD_SP5_SHIFT 10 #define AIPS_PACRD_TP4_MASK 0x1000u #define AIPS_PACRD_TP4_SHIFT 12 #define AIPS_PACRD_WP4_MASK 0x2000u #define AIPS_PACRD_WP4_SHIFT 13 #define AIPS_PACRD_SP4_MASK 0x4000u #define AIPS_PACRD_SP4_SHIFT 14 #define AIPS_PACRD_TP3_MASK 0x10000u #define AIPS_PACRD_TP3_SHIFT 16 #define AIPS_PACRD_WP3_MASK 0x20000u #define AIPS_PACRD_WP3_SHIFT 17 #define AIPS_PACRD_SP3_MASK 0x40000u #define AIPS_PACRD_SP3_SHIFT 18 #define AIPS_PACRD_TP2_MASK 0x100000u #define AIPS_PACRD_TP2_SHIFT 20 #define AIPS_PACRD_WP2_MASK 0x200000u #define AIPS_PACRD_WP2_SHIFT 21 #define AIPS_PACRD_SP2_MASK 0x400000u #define AIPS_PACRD_SP2_SHIFT 22 #define AIPS_PACRD_TP1_MASK 0x1000000u #define AIPS_PACRD_TP1_SHIFT 24 #define AIPS_PACRD_WP1_MASK 0x2000000u #define AIPS_PACRD_WP1_SHIFT 25 #define AIPS_PACRD_SP1_MASK 0x4000000u #define AIPS_PACRD_SP1_SHIFT 26 #define AIPS_PACRD_TP0_MASK 0x10000000u #define AIPS_PACRD_TP0_SHIFT 28 #define AIPS_PACRD_WP0_MASK 0x20000000u #define AIPS_PACRD_WP0_SHIFT 29 #define AIPS_PACRD_SP0_MASK 0x40000000u #define AIPS_PACRD_SP0_SHIFT 30 /* PACRE Bit Fields */ #define AIPS_PACRE_TP7_MASK 0x1u #define AIPS_PACRE_TP7_SHIFT 0 #define AIPS_PACRE_WP7_MASK 0x2u #define AIPS_PACRE_WP7_SHIFT 1 #define AIPS_PACRE_SP7_MASK 0x4u #define AIPS_PACRE_SP7_SHIFT 2 #define AIPS_PACRE_TP6_MASK 0x10u #define AIPS_PACRE_TP6_SHIFT 4 #define AIPS_PACRE_WP6_MASK 0x20u #define AIPS_PACRE_WP6_SHIFT 5 #define AIPS_PACRE_SP6_MASK 0x40u #define AIPS_PACRE_SP6_SHIFT 6 #define AIPS_PACRE_TP5_MASK 0x100u #define AIPS_PACRE_TP5_SHIFT 8 #define AIPS_PACRE_WP5_MASK 0x200u #define AIPS_PACRE_WP5_SHIFT 9 #define AIPS_PACRE_SP5_MASK 0x400u #define AIPS_PACRE_SP5_SHIFT 10 #define AIPS_PACRE_TP4_MASK 0x1000u #define AIPS_PACRE_TP4_SHIFT 12 #define AIPS_PACRE_WP4_MASK 0x2000u #define AIPS_PACRE_WP4_SHIFT 13 #define AIPS_PACRE_SP4_MASK 0x4000u #define AIPS_PACRE_SP4_SHIFT 14 #define AIPS_PACRE_TP3_MASK 0x10000u #define AIPS_PACRE_TP3_SHIFT 16 #define AIPS_PACRE_WP3_MASK 0x20000u #define AIPS_PACRE_WP3_SHIFT 17 #define AIPS_PACRE_SP3_MASK 0x40000u #define AIPS_PACRE_SP3_SHIFT 18 #define AIPS_PACRE_TP2_MASK 0x100000u #define AIPS_PACRE_TP2_SHIFT 20 #define AIPS_PACRE_WP2_MASK 0x200000u #define AIPS_PACRE_WP2_SHIFT 21 #define AIPS_PACRE_SP2_MASK 0x400000u #define AIPS_PACRE_SP2_SHIFT 22 #define AIPS_PACRE_TP1_MASK 0x1000000u #define AIPS_PACRE_TP1_SHIFT 24 #define AIPS_PACRE_WP1_MASK 0x2000000u #define AIPS_PACRE_WP1_SHIFT 25 #define AIPS_PACRE_SP1_MASK 0x4000000u #define AIPS_PACRE_SP1_SHIFT 26 #define AIPS_PACRE_TP0_MASK 0x10000000u #define AIPS_PACRE_TP0_SHIFT 28 #define AIPS_PACRE_WP0_MASK 0x20000000u #define AIPS_PACRE_WP0_SHIFT 29 #define AIPS_PACRE_SP0_MASK 0x40000000u #define AIPS_PACRE_SP0_SHIFT 30 /* PACRF Bit Fields */ #define AIPS_PACRF_TP7_MASK 0x1u #define AIPS_PACRF_TP7_SHIFT 0 #define AIPS_PACRF_WP7_MASK 0x2u #define AIPS_PACRF_WP7_SHIFT 1 #define AIPS_PACRF_SP7_MASK 0x4u #define AIPS_PACRF_SP7_SHIFT 2 #define AIPS_PACRF_TP6_MASK 0x10u #define AIPS_PACRF_TP6_SHIFT 4 #define AIPS_PACRF_WP6_MASK 0x20u #define AIPS_PACRF_WP6_SHIFT 5 #define AIPS_PACRF_SP6_MASK 0x40u #define AIPS_PACRF_SP6_SHIFT 6 #define AIPS_PACRF_TP5_MASK 0x100u #define AIPS_PACRF_TP5_SHIFT 8 #define AIPS_PACRF_WP5_MASK 0x200u #define AIPS_PACRF_WP5_SHIFT 9 #define AIPS_PACRF_SP5_MASK 0x400u #define AIPS_PACRF_SP5_SHIFT 10 #define AIPS_PACRF_TP4_MASK 0x1000u #define AIPS_PACRF_TP4_SHIFT 12 #define AIPS_PACRF_WP4_MASK 0x2000u #define AIPS_PACRF_WP4_SHIFT 13 #define AIPS_PACRF_SP4_MASK 0x4000u #define AIPS_PACRF_SP4_SHIFT 14 #define AIPS_PACRF_TP3_MASK 0x10000u #define AIPS_PACRF_TP3_SHIFT 16 #define AIPS_PACRF_WP3_MASK 0x20000u #define AIPS_PACRF_WP3_SHIFT 17 #define AIPS_PACRF_SP3_MASK 0x40000u #define AIPS_PACRF_SP3_SHIFT 18 #define AIPS_PACRF_TP2_MASK 0x100000u #define AIPS_PACRF_TP2_SHIFT 20 #define AIPS_PACRF_WP2_MASK 0x200000u #define AIPS_PACRF_WP2_SHIFT 21 #define AIPS_PACRF_SP2_MASK 0x400000u #define AIPS_PACRF_SP2_SHIFT 22 #define AIPS_PACRF_TP1_MASK 0x1000000u #define AIPS_PACRF_TP1_SHIFT 24 #define AIPS_PACRF_WP1_MASK 0x2000000u #define AIPS_PACRF_WP1_SHIFT 25 #define AIPS_PACRF_SP1_MASK 0x4000000u #define AIPS_PACRF_SP1_SHIFT 26 #define AIPS_PACRF_TP0_MASK 0x10000000u #define AIPS_PACRF_TP0_SHIFT 28 #define AIPS_PACRF_WP0_MASK 0x20000000u #define AIPS_PACRF_WP0_SHIFT 29 #define AIPS_PACRF_SP0_MASK 0x40000000u #define AIPS_PACRF_SP0_SHIFT 30 /* PACRG Bit Fields */ #define AIPS_PACRG_TP7_MASK 0x1u #define AIPS_PACRG_TP7_SHIFT 0 #define AIPS_PACRG_WP7_MASK 0x2u #define AIPS_PACRG_WP7_SHIFT 1 #define AIPS_PACRG_SP7_MASK 0x4u #define AIPS_PACRG_SP7_SHIFT 2 #define AIPS_PACRG_TP6_MASK 0x10u #define AIPS_PACRG_TP6_SHIFT 4 #define AIPS_PACRG_WP6_MASK 0x20u #define AIPS_PACRG_WP6_SHIFT 5 #define AIPS_PACRG_SP6_MASK 0x40u #define AIPS_PACRG_SP6_SHIFT 6 #define AIPS_PACRG_TP5_MASK 0x100u #define AIPS_PACRG_TP5_SHIFT 8 #define AIPS_PACRG_WP5_MASK 0x200u #define AIPS_PACRG_WP5_SHIFT 9 #define AIPS_PACRG_SP5_MASK 0x400u #define AIPS_PACRG_SP5_SHIFT 10 #define AIPS_PACRG_TP4_MASK 0x1000u #define AIPS_PACRG_TP4_SHIFT 12 #define AIPS_PACRG_WP4_MASK 0x2000u #define AIPS_PACRG_WP4_SHIFT 13 #define AIPS_PACRG_SP4_MASK 0x4000u #define AIPS_PACRG_SP4_SHIFT 14 #define AIPS_PACRG_TP3_MASK 0x10000u #define AIPS_PACRG_TP3_SHIFT 16 #define AIPS_PACRG_WP3_MASK 0x20000u #define AIPS_PACRG_WP3_SHIFT 17 #define AIPS_PACRG_SP3_MASK 0x40000u #define AIPS_PACRG_SP3_SHIFT 18 #define AIPS_PACRG_TP2_MASK 0x100000u #define AIPS_PACRG_TP2_SHIFT 20 #define AIPS_PACRG_WP2_MASK 0x200000u #define AIPS_PACRG_WP2_SHIFT 21 #define AIPS_PACRG_SP2_MASK 0x400000u #define AIPS_PACRG_SP2_SHIFT 22 #define AIPS_PACRG_TP1_MASK 0x1000000u #define AIPS_PACRG_TP1_SHIFT 24 #define AIPS_PACRG_WP1_MASK 0x2000000u #define AIPS_PACRG_WP1_SHIFT 25 #define AIPS_PACRG_SP1_MASK 0x4000000u #define AIPS_PACRG_SP1_SHIFT 26 #define AIPS_PACRG_TP0_MASK 0x10000000u #define AIPS_PACRG_TP0_SHIFT 28 #define AIPS_PACRG_WP0_MASK 0x20000000u #define AIPS_PACRG_WP0_SHIFT 29 #define AIPS_PACRG_SP0_MASK 0x40000000u #define AIPS_PACRG_SP0_SHIFT 30 /* PACRH Bit Fields */ #define AIPS_PACRH_TP7_MASK 0x1u #define AIPS_PACRH_TP7_SHIFT 0 #define AIPS_PACRH_WP7_MASK 0x2u #define AIPS_PACRH_WP7_SHIFT 1 #define AIPS_PACRH_SP7_MASK 0x4u #define AIPS_PACRH_SP7_SHIFT 2 #define AIPS_PACRH_TP6_MASK 0x10u #define AIPS_PACRH_TP6_SHIFT 4 #define AIPS_PACRH_WP6_MASK 0x20u #define AIPS_PACRH_WP6_SHIFT 5 #define AIPS_PACRH_SP6_MASK 0x40u #define AIPS_PACRH_SP6_SHIFT 6 #define AIPS_PACRH_TP5_MASK 0x100u #define AIPS_PACRH_TP5_SHIFT 8 #define AIPS_PACRH_WP5_MASK 0x200u #define AIPS_PACRH_WP5_SHIFT 9 #define AIPS_PACRH_SP5_MASK 0x400u #define AIPS_PACRH_SP5_SHIFT 10 #define AIPS_PACRH_TP4_MASK 0x1000u #define AIPS_PACRH_TP4_SHIFT 12 #define AIPS_PACRH_WP4_MASK 0x2000u #define AIPS_PACRH_WP4_SHIFT 13 #define AIPS_PACRH_SP4_MASK 0x4000u #define AIPS_PACRH_SP4_SHIFT 14 #define AIPS_PACRH_TP3_MASK 0x10000u #define AIPS_PACRH_TP3_SHIFT 16 #define AIPS_PACRH_WP3_MASK 0x20000u #define AIPS_PACRH_WP3_SHIFT 17 #define AIPS_PACRH_SP3_MASK 0x40000u #define AIPS_PACRH_SP3_SHIFT 18 #define AIPS_PACRH_TP2_MASK 0x100000u #define AIPS_PACRH_TP2_SHIFT 20 #define AIPS_PACRH_WP2_MASK 0x200000u #define AIPS_PACRH_WP2_SHIFT 21 #define AIPS_PACRH_SP2_MASK 0x400000u #define AIPS_PACRH_SP2_SHIFT 22 #define AIPS_PACRH_TP1_MASK 0x1000000u #define AIPS_PACRH_TP1_SHIFT 24 #define AIPS_PACRH_WP1_MASK 0x2000000u #define AIPS_PACRH_WP1_SHIFT 25 #define AIPS_PACRH_SP1_MASK 0x4000000u #define AIPS_PACRH_SP1_SHIFT 26 #define AIPS_PACRH_TP0_MASK 0x10000000u #define AIPS_PACRH_TP0_SHIFT 28 #define AIPS_PACRH_WP0_MASK 0x20000000u #define AIPS_PACRH_WP0_SHIFT 29 #define AIPS_PACRH_SP0_MASK 0x40000000u #define AIPS_PACRH_SP0_SHIFT 30 /* PACRI Bit Fields */ #define AIPS_PACRI_TP7_MASK 0x1u #define AIPS_PACRI_TP7_SHIFT 0 #define AIPS_PACRI_WP7_MASK 0x2u #define AIPS_PACRI_WP7_SHIFT 1 #define AIPS_PACRI_SP7_MASK 0x4u #define AIPS_PACRI_SP7_SHIFT 2 #define AIPS_PACRI_TP6_MASK 0x10u #define AIPS_PACRI_TP6_SHIFT 4 #define AIPS_PACRI_WP6_MASK 0x20u #define AIPS_PACRI_WP6_SHIFT 5 #define AIPS_PACRI_SP6_MASK 0x40u #define AIPS_PACRI_SP6_SHIFT 6 #define AIPS_PACRI_TP5_MASK 0x100u #define AIPS_PACRI_TP5_SHIFT 8 #define AIPS_PACRI_WP5_MASK 0x200u #define AIPS_PACRI_WP5_SHIFT 9 #define AIPS_PACRI_SP5_MASK 0x400u #define AIPS_PACRI_SP5_SHIFT 10 #define AIPS_PACRI_TP4_MASK 0x1000u #define AIPS_PACRI_TP4_SHIFT 12 #define AIPS_PACRI_WP4_MASK 0x2000u #define AIPS_PACRI_WP4_SHIFT 13 #define AIPS_PACRI_SP4_MASK 0x4000u #define AIPS_PACRI_SP4_SHIFT 14 #define AIPS_PACRI_TP3_MASK 0x10000u #define AIPS_PACRI_TP3_SHIFT 16 #define AIPS_PACRI_WP3_MASK 0x20000u #define AIPS_PACRI_WP3_SHIFT 17 #define AIPS_PACRI_SP3_MASK 0x40000u #define AIPS_PACRI_SP3_SHIFT 18 #define AIPS_PACRI_TP2_MASK 0x100000u #define AIPS_PACRI_TP2_SHIFT 20 #define AIPS_PACRI_WP2_MASK 0x200000u #define AIPS_PACRI_WP2_SHIFT 21 #define AIPS_PACRI_SP2_MASK 0x400000u #define AIPS_PACRI_SP2_SHIFT 22 #define AIPS_PACRI_TP1_MASK 0x1000000u #define AIPS_PACRI_TP1_SHIFT 24 #define AIPS_PACRI_WP1_MASK 0x2000000u #define AIPS_PACRI_WP1_SHIFT 25 #define AIPS_PACRI_SP1_MASK 0x4000000u #define AIPS_PACRI_SP1_SHIFT 26 #define AIPS_PACRI_TP0_MASK 0x10000000u #define AIPS_PACRI_TP0_SHIFT 28 #define AIPS_PACRI_WP0_MASK 0x20000000u #define AIPS_PACRI_WP0_SHIFT 29 #define AIPS_PACRI_SP0_MASK 0x40000000u #define AIPS_PACRI_SP0_SHIFT 30 /* PACRJ Bit Fields */ #define AIPS_PACRJ_TP7_MASK 0x1u #define AIPS_PACRJ_TP7_SHIFT 0 #define AIPS_PACRJ_WP7_MASK 0x2u #define AIPS_PACRJ_WP7_SHIFT 1 #define AIPS_PACRJ_SP7_MASK 0x4u #define AIPS_PACRJ_SP7_SHIFT 2 #define AIPS_PACRJ_TP6_MASK 0x10u #define AIPS_PACRJ_TP6_SHIFT 4 #define AIPS_PACRJ_WP6_MASK 0x20u #define AIPS_PACRJ_WP6_SHIFT 5 #define AIPS_PACRJ_SP6_MASK 0x40u #define AIPS_PACRJ_SP6_SHIFT 6 #define AIPS_PACRJ_TP5_MASK 0x100u #define AIPS_PACRJ_TP5_SHIFT 8 #define AIPS_PACRJ_WP5_MASK 0x200u #define AIPS_PACRJ_WP5_SHIFT 9 #define AIPS_PACRJ_SP5_MASK 0x400u #define AIPS_PACRJ_SP5_SHIFT 10 #define AIPS_PACRJ_TP4_MASK 0x1000u #define AIPS_PACRJ_TP4_SHIFT 12 #define AIPS_PACRJ_WP4_MASK 0x2000u #define AIPS_PACRJ_WP4_SHIFT 13 #define AIPS_PACRJ_SP4_MASK 0x4000u #define AIPS_PACRJ_SP4_SHIFT 14 #define AIPS_PACRJ_TP3_MASK 0x10000u #define AIPS_PACRJ_TP3_SHIFT 16 #define AIPS_PACRJ_WP3_MASK 0x20000u #define AIPS_PACRJ_WP3_SHIFT 17 #define AIPS_PACRJ_SP3_MASK 0x40000u #define AIPS_PACRJ_SP3_SHIFT 18 #define AIPS_PACRJ_TP2_MASK 0x100000u #define AIPS_PACRJ_TP2_SHIFT 20 #define AIPS_PACRJ_WP2_MASK 0x200000u #define AIPS_PACRJ_WP2_SHIFT 21 #define AIPS_PACRJ_SP2_MASK 0x400000u #define AIPS_PACRJ_SP2_SHIFT 22 #define AIPS_PACRJ_TP1_MASK 0x1000000u #define AIPS_PACRJ_TP1_SHIFT 24 #define AIPS_PACRJ_WP1_MASK 0x2000000u #define AIPS_PACRJ_WP1_SHIFT 25 #define AIPS_PACRJ_SP1_MASK 0x4000000u #define AIPS_PACRJ_SP1_SHIFT 26 #define AIPS_PACRJ_TP0_MASK 0x10000000u #define AIPS_PACRJ_TP0_SHIFT 28 #define AIPS_PACRJ_WP0_MASK 0x20000000u #define AIPS_PACRJ_WP0_SHIFT 29 #define AIPS_PACRJ_SP0_MASK 0x40000000u #define AIPS_PACRJ_SP0_SHIFT 30 /* PACRK Bit Fields */ #define AIPS_PACRK_TP7_MASK 0x1u #define AIPS_PACRK_TP7_SHIFT 0 #define AIPS_PACRK_WP7_MASK 0x2u #define AIPS_PACRK_WP7_SHIFT 1 #define AIPS_PACRK_SP7_MASK 0x4u #define AIPS_PACRK_SP7_SHIFT 2 #define AIPS_PACRK_TP6_MASK 0x10u #define AIPS_PACRK_TP6_SHIFT 4 #define AIPS_PACRK_WP6_MASK 0x20u #define AIPS_PACRK_WP6_SHIFT 5 #define AIPS_PACRK_SP6_MASK 0x40u #define AIPS_PACRK_SP6_SHIFT 6 #define AIPS_PACRK_TP5_MASK 0x100u #define AIPS_PACRK_TP5_SHIFT 8 #define AIPS_PACRK_WP5_MASK 0x200u #define AIPS_PACRK_WP5_SHIFT 9 #define AIPS_PACRK_SP5_MASK 0x400u #define AIPS_PACRK_SP5_SHIFT 10 #define AIPS_PACRK_TP4_MASK 0x1000u #define AIPS_PACRK_TP4_SHIFT 12 #define AIPS_PACRK_WP4_MASK 0x2000u #define AIPS_PACRK_WP4_SHIFT 13 #define AIPS_PACRK_SP4_MASK 0x4000u #define AIPS_PACRK_SP4_SHIFT 14 #define AIPS_PACRK_TP3_MASK 0x10000u #define AIPS_PACRK_TP3_SHIFT 16 #define AIPS_PACRK_WP3_MASK 0x20000u #define AIPS_PACRK_WP3_SHIFT 17 #define AIPS_PACRK_SP3_MASK 0x40000u #define AIPS_PACRK_SP3_SHIFT 18 #define AIPS_PACRK_TP2_MASK 0x100000u #define AIPS_PACRK_TP2_SHIFT 20 #define AIPS_PACRK_WP2_MASK 0x200000u #define AIPS_PACRK_WP2_SHIFT 21 #define AIPS_PACRK_SP2_MASK 0x400000u #define AIPS_PACRK_SP2_SHIFT 22 #define AIPS_PACRK_TP1_MASK 0x1000000u #define AIPS_PACRK_TP1_SHIFT 24 #define AIPS_PACRK_WP1_MASK 0x2000000u #define AIPS_PACRK_WP1_SHIFT 25 #define AIPS_PACRK_SP1_MASK 0x4000000u #define AIPS_PACRK_SP1_SHIFT 26 #define AIPS_PACRK_TP0_MASK 0x10000000u #define AIPS_PACRK_TP0_SHIFT 28 #define AIPS_PACRK_WP0_MASK 0x20000000u #define AIPS_PACRK_WP0_SHIFT 29 #define AIPS_PACRK_SP0_MASK 0x40000000u #define AIPS_PACRK_SP0_SHIFT 30 /* PACRL Bit Fields */ #define AIPS_PACRL_TP7_MASK 0x1u #define AIPS_PACRL_TP7_SHIFT 0 #define AIPS_PACRL_WP7_MASK 0x2u #define AIPS_PACRL_WP7_SHIFT 1 #define AIPS_PACRL_SP7_MASK 0x4u #define AIPS_PACRL_SP7_SHIFT 2 #define AIPS_PACRL_TP6_MASK 0x10u #define AIPS_PACRL_TP6_SHIFT 4 #define AIPS_PACRL_WP6_MASK 0x20u #define AIPS_PACRL_WP6_SHIFT 5 #define AIPS_PACRL_SP6_MASK 0x40u #define AIPS_PACRL_SP6_SHIFT 6 #define AIPS_PACRL_TP5_MASK 0x100u #define AIPS_PACRL_TP5_SHIFT 8 #define AIPS_PACRL_WP5_MASK 0x200u #define AIPS_PACRL_WP5_SHIFT 9 #define AIPS_PACRL_SP5_MASK 0x400u #define AIPS_PACRL_SP5_SHIFT 10 #define AIPS_PACRL_TP4_MASK 0x1000u #define AIPS_PACRL_TP4_SHIFT 12 #define AIPS_PACRL_WP4_MASK 0x2000u #define AIPS_PACRL_WP4_SHIFT 13 #define AIPS_PACRL_SP4_MASK 0x4000u #define AIPS_PACRL_SP4_SHIFT 14 #define AIPS_PACRL_TP3_MASK 0x10000u #define AIPS_PACRL_TP3_SHIFT 16 #define AIPS_PACRL_WP3_MASK 0x20000u #define AIPS_PACRL_WP3_SHIFT 17 #define AIPS_PACRL_SP3_MASK 0x40000u #define AIPS_PACRL_SP3_SHIFT 18 #define AIPS_PACRL_TP2_MASK 0x100000u #define AIPS_PACRL_TP2_SHIFT 20 #define AIPS_PACRL_WP2_MASK 0x200000u #define AIPS_PACRL_WP2_SHIFT 21 #define AIPS_PACRL_SP2_MASK 0x400000u #define AIPS_PACRL_SP2_SHIFT 22 #define AIPS_PACRL_TP1_MASK 0x1000000u #define AIPS_PACRL_TP1_SHIFT 24 #define AIPS_PACRL_WP1_MASK 0x2000000u #define AIPS_PACRL_WP1_SHIFT 25 #define AIPS_PACRL_SP1_MASK 0x4000000u #define AIPS_PACRL_SP1_SHIFT 26 #define AIPS_PACRL_TP0_MASK 0x10000000u #define AIPS_PACRL_TP0_SHIFT 28 #define AIPS_PACRL_WP0_MASK 0x20000000u #define AIPS_PACRL_WP0_SHIFT 29 #define AIPS_PACRL_SP0_MASK 0x40000000u #define AIPS_PACRL_SP0_SHIFT 30 /* PACRM Bit Fields */ #define AIPS_PACRM_TP7_MASK 0x1u #define AIPS_PACRM_TP7_SHIFT 0 #define AIPS_PACRM_WP7_MASK 0x2u #define AIPS_PACRM_WP7_SHIFT 1 #define AIPS_PACRM_SP7_MASK 0x4u #define AIPS_PACRM_SP7_SHIFT 2 #define AIPS_PACRM_TP6_MASK 0x10u #define AIPS_PACRM_TP6_SHIFT 4 #define AIPS_PACRM_WP6_MASK 0x20u #define AIPS_PACRM_WP6_SHIFT 5 #define AIPS_PACRM_SP6_MASK 0x40u #define AIPS_PACRM_SP6_SHIFT 6 #define AIPS_PACRM_TP5_MASK 0x100u #define AIPS_PACRM_TP5_SHIFT 8 #define AIPS_PACRM_WP5_MASK 0x200u #define AIPS_PACRM_WP5_SHIFT 9 #define AIPS_PACRM_SP5_MASK 0x400u #define AIPS_PACRM_SP5_SHIFT 10 #define AIPS_PACRM_TP4_MASK 0x1000u #define AIPS_PACRM_TP4_SHIFT 12 #define AIPS_PACRM_WP4_MASK 0x2000u #define AIPS_PACRM_WP4_SHIFT 13 #define AIPS_PACRM_SP4_MASK 0x4000u #define AIPS_PACRM_SP4_SHIFT 14 #define AIPS_PACRM_TP3_MASK 0x10000u #define AIPS_PACRM_TP3_SHIFT 16 #define AIPS_PACRM_WP3_MASK 0x20000u #define AIPS_PACRM_WP3_SHIFT 17 #define AIPS_PACRM_SP3_MASK 0x40000u #define AIPS_PACRM_SP3_SHIFT 18 #define AIPS_PACRM_TP2_MASK 0x100000u #define AIPS_PACRM_TP2_SHIFT 20 #define AIPS_PACRM_WP2_MASK 0x200000u #define AIPS_PACRM_WP2_SHIFT 21 #define AIPS_PACRM_SP2_MASK 0x400000u #define AIPS_PACRM_SP2_SHIFT 22 #define AIPS_PACRM_TP1_MASK 0x1000000u #define AIPS_PACRM_TP1_SHIFT 24 #define AIPS_PACRM_WP1_MASK 0x2000000u #define AIPS_PACRM_WP1_SHIFT 25 #define AIPS_PACRM_SP1_MASK 0x4000000u #define AIPS_PACRM_SP1_SHIFT 26 #define AIPS_PACRM_TP0_MASK 0x10000000u #define AIPS_PACRM_TP0_SHIFT 28 #define AIPS_PACRM_WP0_MASK 0x20000000u #define AIPS_PACRM_WP0_SHIFT 29 #define AIPS_PACRM_SP0_MASK 0x40000000u #define AIPS_PACRM_SP0_SHIFT 30 /* PACRN Bit Fields */ #define AIPS_PACRN_TP7_MASK 0x1u #define AIPS_PACRN_TP7_SHIFT 0 #define AIPS_PACRN_WP7_MASK 0x2u #define AIPS_PACRN_WP7_SHIFT 1 #define AIPS_PACRN_SP7_MASK 0x4u #define AIPS_PACRN_SP7_SHIFT 2 #define AIPS_PACRN_TP6_MASK 0x10u #define AIPS_PACRN_TP6_SHIFT 4 #define AIPS_PACRN_WP6_MASK 0x20u #define AIPS_PACRN_WP6_SHIFT 5 #define AIPS_PACRN_SP6_MASK 0x40u #define AIPS_PACRN_SP6_SHIFT 6 #define AIPS_PACRN_TP5_MASK 0x100u #define AIPS_PACRN_TP5_SHIFT 8 #define AIPS_PACRN_WP5_MASK 0x200u #define AIPS_PACRN_WP5_SHIFT 9 #define AIPS_PACRN_SP5_MASK 0x400u #define AIPS_PACRN_SP5_SHIFT 10 #define AIPS_PACRN_TP4_MASK 0x1000u #define AIPS_PACRN_TP4_SHIFT 12 #define AIPS_PACRN_WP4_MASK 0x2000u #define AIPS_PACRN_WP4_SHIFT 13 #define AIPS_PACRN_SP4_MASK 0x4000u #define AIPS_PACRN_SP4_SHIFT 14 #define AIPS_PACRN_TP3_MASK 0x10000u #define AIPS_PACRN_TP3_SHIFT 16 #define AIPS_PACRN_WP3_MASK 0x20000u #define AIPS_PACRN_WP3_SHIFT 17 #define AIPS_PACRN_SP3_MASK 0x40000u #define AIPS_PACRN_SP3_SHIFT 18 #define AIPS_PACRN_TP2_MASK 0x100000u #define AIPS_PACRN_TP2_SHIFT 20 #define AIPS_PACRN_WP2_MASK 0x200000u #define AIPS_PACRN_WP2_SHIFT 21 #define AIPS_PACRN_SP2_MASK 0x400000u #define AIPS_PACRN_SP2_SHIFT 22 #define AIPS_PACRN_TP1_MASK 0x1000000u #define AIPS_PACRN_TP1_SHIFT 24 #define AIPS_PACRN_WP1_MASK 0x2000000u #define AIPS_PACRN_WP1_SHIFT 25 #define AIPS_PACRN_SP1_MASK 0x4000000u #define AIPS_PACRN_SP1_SHIFT 26 #define AIPS_PACRN_TP0_MASK 0x10000000u #define AIPS_PACRN_TP0_SHIFT 28 #define AIPS_PACRN_WP0_MASK 0x20000000u #define AIPS_PACRN_WP0_SHIFT 29 #define AIPS_PACRN_SP0_MASK 0x40000000u #define AIPS_PACRN_SP0_SHIFT 30 /* PACRO Bit Fields */ #define AIPS_PACRO_TP7_MASK 0x1u #define AIPS_PACRO_TP7_SHIFT 0 #define AIPS_PACRO_WP7_MASK 0x2u #define AIPS_PACRO_WP7_SHIFT 1 #define AIPS_PACRO_SP7_MASK 0x4u #define AIPS_PACRO_SP7_SHIFT 2 #define AIPS_PACRO_TP6_MASK 0x10u #define AIPS_PACRO_TP6_SHIFT 4 #define AIPS_PACRO_WP6_MASK 0x20u #define AIPS_PACRO_WP6_SHIFT 5 #define AIPS_PACRO_SP6_MASK 0x40u #define AIPS_PACRO_SP6_SHIFT 6 #define AIPS_PACRO_TP5_MASK 0x100u #define AIPS_PACRO_TP5_SHIFT 8 #define AIPS_PACRO_WP5_MASK 0x200u #define AIPS_PACRO_WP5_SHIFT 9 #define AIPS_PACRO_SP5_MASK 0x400u #define AIPS_PACRO_SP5_SHIFT 10 #define AIPS_PACRO_TP4_MASK 0x1000u #define AIPS_PACRO_TP4_SHIFT 12 #define AIPS_PACRO_WP4_MASK 0x2000u #define AIPS_PACRO_WP4_SHIFT 13 #define AIPS_PACRO_SP4_MASK 0x4000u #define AIPS_PACRO_SP4_SHIFT 14 #define AIPS_PACRO_TP3_MASK 0x10000u #define AIPS_PACRO_TP3_SHIFT 16 #define AIPS_PACRO_WP3_MASK 0x20000u #define AIPS_PACRO_WP3_SHIFT 17 #define AIPS_PACRO_SP3_MASK 0x40000u #define AIPS_PACRO_SP3_SHIFT 18 #define AIPS_PACRO_TP2_MASK 0x100000u #define AIPS_PACRO_TP2_SHIFT 20 #define AIPS_PACRO_WP2_MASK 0x200000u #define AIPS_PACRO_WP2_SHIFT 21 #define AIPS_PACRO_SP2_MASK 0x400000u #define AIPS_PACRO_SP2_SHIFT 22 #define AIPS_PACRO_TP1_MASK 0x1000000u #define AIPS_PACRO_TP1_SHIFT 24 #define AIPS_PACRO_WP1_MASK 0x2000000u #define AIPS_PACRO_WP1_SHIFT 25 #define AIPS_PACRO_SP1_MASK 0x4000000u #define AIPS_PACRO_SP1_SHIFT 26 #define AIPS_PACRO_TP0_MASK 0x10000000u #define AIPS_PACRO_TP0_SHIFT 28 #define AIPS_PACRO_WP0_MASK 0x20000000u #define AIPS_PACRO_WP0_SHIFT 29 #define AIPS_PACRO_SP0_MASK 0x40000000u #define AIPS_PACRO_SP0_SHIFT 30 /* PACRP Bit Fields */ #define AIPS_PACRP_TP7_MASK 0x1u #define AIPS_PACRP_TP7_SHIFT 0 #define AIPS_PACRP_WP7_MASK 0x2u #define AIPS_PACRP_WP7_SHIFT 1 #define AIPS_PACRP_SP7_MASK 0x4u #define AIPS_PACRP_SP7_SHIFT 2 #define AIPS_PACRP_TP6_MASK 0x10u #define AIPS_PACRP_TP6_SHIFT 4 #define AIPS_PACRP_WP6_MASK 0x20u #define AIPS_PACRP_WP6_SHIFT 5 #define AIPS_PACRP_SP6_MASK 0x40u #define AIPS_PACRP_SP6_SHIFT 6 #define AIPS_PACRP_TP5_MASK 0x100u #define AIPS_PACRP_TP5_SHIFT 8 #define AIPS_PACRP_WP5_MASK 0x200u #define AIPS_PACRP_WP5_SHIFT 9 #define AIPS_PACRP_SP5_MASK 0x400u #define AIPS_PACRP_SP5_SHIFT 10 #define AIPS_PACRP_TP4_MASK 0x1000u #define AIPS_PACRP_TP4_SHIFT 12 #define AIPS_PACRP_WP4_MASK 0x2000u #define AIPS_PACRP_WP4_SHIFT 13 #define AIPS_PACRP_SP4_MASK 0x4000u #define AIPS_PACRP_SP4_SHIFT 14 #define AIPS_PACRP_TP3_MASK 0x10000u #define AIPS_PACRP_TP3_SHIFT 16 #define AIPS_PACRP_WP3_MASK 0x20000u #define AIPS_PACRP_WP3_SHIFT 17 #define AIPS_PACRP_SP3_MASK 0x40000u #define AIPS_PACRP_SP3_SHIFT 18 #define AIPS_PACRP_TP2_MASK 0x100000u #define AIPS_PACRP_TP2_SHIFT 20 #define AIPS_PACRP_WP2_MASK 0x200000u #define AIPS_PACRP_WP2_SHIFT 21 #define AIPS_PACRP_SP2_MASK 0x400000u #define AIPS_PACRP_SP2_SHIFT 22 #define AIPS_PACRP_TP1_MASK 0x1000000u #define AIPS_PACRP_TP1_SHIFT 24 #define AIPS_PACRP_WP1_MASK 0x2000000u #define AIPS_PACRP_WP1_SHIFT 25 #define AIPS_PACRP_SP1_MASK 0x4000000u #define AIPS_PACRP_SP1_SHIFT 26 #define AIPS_PACRP_TP0_MASK 0x10000000u #define AIPS_PACRP_TP0_SHIFT 28 #define AIPS_PACRP_WP0_MASK 0x20000000u #define AIPS_PACRP_WP0_SHIFT 29 #define AIPS_PACRP_SP0_MASK 0x40000000u #define AIPS_PACRP_SP0_SHIFT 30 /* PACRU Bit Fields */ #define AIPS_PACRU_TP1_MASK 0x1000000u #define AIPS_PACRU_TP1_SHIFT 24 #define AIPS_PACRU_WP1_MASK 0x2000000u #define AIPS_PACRU_WP1_SHIFT 25 #define AIPS_PACRU_SP1_MASK 0x4000000u #define AIPS_PACRU_SP1_SHIFT 26 #define AIPS_PACRU_TP0_MASK 0x10000000u #define AIPS_PACRU_TP0_SHIFT 28 #define AIPS_PACRU_WP0_MASK 0x20000000u #define AIPS_PACRU_WP0_SHIFT 29 #define AIPS_PACRU_SP0_MASK 0x40000000u #define AIPS_PACRU_SP0_SHIFT 30 /*! * @} */ /* end of group AIPS_Register_Masks */ /* AIPS - Peripheral instance base addresses */ /** Peripheral AIPS0 base address */ #define AIPS0_BASE (0x40000000u) /** Peripheral AIPS0 base pointer */ #define AIPS0 ((AIPS_Type *)AIPS0_BASE) #define AIPS0_BASE_PTR (AIPS0) /** Peripheral AIPS1 base address */ #define AIPS1_BASE (0x40080000u) /** Peripheral AIPS1 base pointer */ #define AIPS1 ((AIPS_Type *)AIPS1_BASE) #define AIPS1_BASE_PTR (AIPS1) /** Array initializer of AIPS peripheral base addresses */ #define AIPS_BASE_ADDRS { AIPS0_BASE, AIPS1_BASE } /** Array initializer of AIPS peripheral base pointers */ #define AIPS_BASE_PTRS { AIPS0, AIPS1 } /* ---------------------------------------------------------------------------- -- AIPS - Register accessor macros ---------------------------------------------------------------------------- */ /*! * @addtogroup AIPS_Register_Accessor_Macros AIPS - Register accessor macros * @{ */ /* AIPS - Register instance definitions */ /* AIPS0 */ #define AIPS0_MPRA AIPS_MPRA_REG(AIPS0) #define AIPS0_PACRA AIPS_PACRA_REG(AIPS0) #define AIPS0_PACRB AIPS_PACRB_REG(AIPS0) #define AIPS0_PACRC AIPS_PACRC_REG(AIPS0) #define AIPS0_PACRD AIPS_PACRD_REG(AIPS0) #define AIPS0_PACRE AIPS_PACRE_REG(AIPS0) #define AIPS0_PACRF AIPS_PACRF_REG(AIPS0) #define AIPS0_PACRG AIPS_PACRG_REG(AIPS0) #define AIPS0_PACRH AIPS_PACRH_REG(AIPS0) #define AIPS0_PACRI AIPS_PACRI_REG(AIPS0) #define AIPS0_PACRJ AIPS_PACRJ_REG(AIPS0) #define AIPS0_PACRK AIPS_PACRK_REG(AIPS0) #define AIPS0_PACRL AIPS_PACRL_REG(AIPS0) #define AIPS0_PACRM AIPS_PACRM_REG(AIPS0) #define AIPS0_PACRN AIPS_PACRN_REG(AIPS0) #define AIPS0_PACRO AIPS_PACRO_REG(AIPS0) #define AIPS0_PACRP AIPS_PACRP_REG(AIPS0) #define AIPS0_PACRU AIPS_PACRU_REG(AIPS0) /* AIPS1 */ #define AIPS1_MPRA AIPS_MPRA_REG(AIPS1) #define AIPS1_PACRA AIPS_PACRA_REG(AIPS1) #define AIPS1_PACRB AIPS_PACRB_REG(AIPS1) #define AIPS1_PACRC AIPS_PACRC_REG(AIPS1) #define AIPS1_PACRD AIPS_PACRD_REG(AIPS1) #define AIPS1_PACRE AIPS_PACRE_REG(AIPS1) #define AIPS1_PACRF AIPS_PACRF_REG(AIPS1) #define AIPS1_PACRG AIPS_PACRG_REG(AIPS1) #define AIPS1_PACRH AIPS_PACRH_REG(AIPS1) #define AIPS1_PACRI AIPS_PACRI_REG(AIPS1) #define AIPS1_PACRJ AIPS_PACRJ_REG(AIPS1) #define AIPS1_PACRK AIPS_PACRK_REG(AIPS1) #define AIPS1_PACRL AIPS_PACRL_REG(AIPS1) #define AIPS1_PACRM AIPS_PACRM_REG(AIPS1) #define AIPS1_PACRN AIPS_PACRN_REG(AIPS1) #define AIPS1_PACRO AIPS_PACRO_REG(AIPS1) #define AIPS1_PACRP AIPS_PACRP_REG(AIPS1) #define AIPS1_PACRU AIPS_PACRU_REG(AIPS1) /*! * @} */ /* end of group AIPS_Register_Accessor_Macros */ /*! * @} */ /* end of group AIPS_Peripheral_Access_Layer */ /* ---------------------------------------------------------------------------- -- AXBS Peripheral Access Layer ---------------------------------------------------------------------------- */ /*! * @addtogroup AXBS_Peripheral_Access_Layer AXBS Peripheral Access Layer * @{ */ /** AXBS - Register Layout Typedef */ typedef struct { struct { /* offset: 0x0, array step: 0x100 */ __IO uint32_t PRS; /**< Priority Registers Slave, array offset: 0x0, array step: 0x100 */ uint8_t RESERVED_0[12]; __IO uint32_t CRS; /**< Control Register, array offset: 0x10, array step: 0x100 */ uint8_t RESERVED_1[236]; } SLAVE[5]; uint8_t RESERVED_0[768]; __IO uint32_t MGPCR0; /**< Master General Purpose Control Register, offset: 0x800 */ uint8_t RESERVED_1[252]; __IO uint32_t MGPCR1; /**< Master General Purpose Control Register, offset: 0x900 */ uint8_t RESERVED_2[252]; __IO uint32_t MGPCR2; /**< Master General Purpose Control Register, offset: 0xA00 */ uint8_t RESERVED_3[252]; __IO uint32_t MGPCR3; /**< Master General Purpose Control Register, offset: 0xB00 */ uint8_t RESERVED_4[252]; __IO uint32_t MGPCR4; /**< Master General Purpose Control Register, offset: 0xC00 */ uint8_t RESERVED_5[252]; __IO uint32_t MGPCR5; /**< Master General Purpose Control Register, offset: 0xD00 */ } AXBS_Type, *AXBS_MemMapPtr; /* ---------------------------------------------------------------------------- -- AXBS - Register accessor macros ---------------------------------------------------------------------------- */ /*! * @addtogroup AXBS_Register_Accessor_Macros AXBS - Register accessor macros * @{ */ /* AXBS - Register accessors */ #define AXBS_PRS_REG(base,index) ((base)->SLAVE[index].PRS) #define AXBS_CRS_REG(base,index) ((base)->SLAVE[index].CRS) #define AXBS_MGPCR0_REG(base) ((base)->MGPCR0) #define AXBS_MGPCR1_REG(base) ((base)->MGPCR1) #define AXBS_MGPCR2_REG(base) ((base)->MGPCR2) #define AXBS_MGPCR3_REG(base) ((base)->MGPCR3) #define AXBS_MGPCR4_REG(base) ((base)->MGPCR4) #define AXBS_MGPCR5_REG(base) ((base)->MGPCR5) /*! * @} */ /* end of group AXBS_Register_Accessor_Macros */ /* ---------------------------------------------------------------------------- -- AXBS Register Masks ---------------------------------------------------------------------------- */ /*! * @addtogroup AXBS_Register_Masks AXBS Register Masks * @{ */ /* PRS Bit Fields */ #define AXBS_PRS_M0_MASK 0x7u #define AXBS_PRS_M0_SHIFT 0 #define AXBS_PRS_M0(x) (((uint32_t)(((uint32_t)(x))<MCR) #define CAN_CTRL1_REG(base) ((base)->CTRL1) #define CAN_TIMER_REG(base) ((base)->TIMER) #define CAN_RXMGMASK_REG(base) ((base)->RXMGMASK) #define CAN_RX14MASK_REG(base) ((base)->RX14MASK) #define CAN_RX15MASK_REG(base) ((base)->RX15MASK) #define CAN_ECR_REG(base) ((base)->ECR) #define CAN_ESR1_REG(base) ((base)->ESR1) #define CAN_IMASK1_REG(base) ((base)->IMASK1) #define CAN_IFLAG1_REG(base) ((base)->IFLAG1) #define CAN_CTRL2_REG(base) ((base)->CTRL2) #define CAN_ESR2_REG(base) ((base)->ESR2) #define CAN_CRCR_REG(base) ((base)->CRCR) #define CAN_RXFGMASK_REG(base) ((base)->RXFGMASK) #define CAN_RXFIR_REG(base) ((base)->RXFIR) #define CAN_CS_REG(base,index) ((base)->MB[index].CS) #define CAN_ID_REG(base,index) ((base)->MB[index].ID) #define CAN_WORD0_REG(base,index) ((base)->MB[index].WORD0) #define CAN_WORD1_REG(base,index) ((base)->MB[index].WORD1) #define CAN_RXIMR_REG(base,index) ((base)->RXIMR[index]) /*! * @} */ /* end of group CAN_Register_Accessor_Macros */ /* ---------------------------------------------------------------------------- -- CAN Register Masks ---------------------------------------------------------------------------- */ /*! * @addtogroup CAN_Register_Masks CAN Register Masks * @{ */ /* MCR Bit Fields */ #define CAN_MCR_MAXMB_MASK 0x7Fu #define CAN_MCR_MAXMB_SHIFT 0 #define CAN_MCR_MAXMB(x) (((uint32_t)(((uint32_t)(x))<DIRECT[index]) #define CAU_LDR_CASR_REG(base) ((base)->LDR_CASR) #define CAU_LDR_CAA_REG(base) ((base)->LDR_CAA) #define CAU_LDR_CA_REG(base,index) ((base)->LDR_CA[index]) #define CAU_STR_CASR_REG(base) ((base)->STR_CASR) #define CAU_STR_CAA_REG(base) ((base)->STR_CAA) #define CAU_STR_CA_REG(base,index) ((base)->STR_CA[index]) #define CAU_ADR_CASR_REG(base) ((base)->ADR_CASR) #define CAU_ADR_CAA_REG(base) ((base)->ADR_CAA) #define CAU_ADR_CA_REG(base,index) ((base)->ADR_CA[index]) #define CAU_RADR_CASR_REG(base) ((base)->RADR_CASR) #define CAU_RADR_CAA_REG(base) ((base)->RADR_CAA) #define CAU_RADR_CA_REG(base,index) ((base)->RADR_CA[index]) #define CAU_XOR_CASR_REG(base) ((base)->XOR_CASR) #define CAU_XOR_CAA_REG(base) ((base)->XOR_CAA) #define CAU_XOR_CA_REG(base,index) ((base)->XOR_CA[index]) #define CAU_ROTL_CASR_REG(base) ((base)->ROTL_CASR) #define CAU_ROTL_CAA_REG(base) ((base)->ROTL_CAA) #define CAU_ROTL_CA_REG(base,index) ((base)->ROTL_CA[index]) #define CAU_AESC_CASR_REG(base) ((base)->AESC_CASR) #define CAU_AESC_CAA_REG(base) ((base)->AESC_CAA) #define CAU_AESC_CA_REG(base,index) ((base)->AESC_CA[index]) #define CAU_AESIC_CASR_REG(base) ((base)->AESIC_CASR) #define CAU_AESIC_CAA_REG(base) ((base)->AESIC_CAA) #define CAU_AESIC_CA_REG(base,index) ((base)->AESIC_CA[index]) /*! * @} */ /* end of group CAU_Register_Accessor_Macros */ /* ---------------------------------------------------------------------------- -- CAU Register Masks ---------------------------------------------------------------------------- */ /*! * @addtogroup CAU_Register_Masks CAU Register Masks * @{ */ /* DIRECT Bit Fields */ #define CAU_DIRECT_CAU_DIRECT0_MASK 0xFFFFFFFFu #define CAU_DIRECT_CAU_DIRECT0_SHIFT 0 #define CAU_DIRECT_CAU_DIRECT0(x) (((uint32_t)(((uint32_t)(x))<CR0) #define CMP_CR1_REG(base) ((base)->CR1) #define CMP_FPR_REG(base) ((base)->FPR) #define CMP_SCR_REG(base) ((base)->SCR) #define CMP_DACCR_REG(base) ((base)->DACCR) #define CMP_MUXCR_REG(base) ((base)->MUXCR) /*! * @} */ /* end of group CMP_Register_Accessor_Macros */ /* ---------------------------------------------------------------------------- -- CMP Register Masks ---------------------------------------------------------------------------- */ /*! * @addtogroup CMP_Register_Masks CMP Register Masks * @{ */ /* CR0 Bit Fields */ #define CMP_CR0_HYSTCTR_MASK 0x3u #define CMP_CR0_HYSTCTR_SHIFT 0 #define CMP_CR0_HYSTCTR(x) (((uint8_t)(((uint8_t)(x))<CGH1) #define CMT_CGL1_REG(base) ((base)->CGL1) #define CMT_CGH2_REG(base) ((base)->CGH2) #define CMT_CGL2_REG(base) ((base)->CGL2) #define CMT_OC_REG(base) ((base)->OC) #define CMT_MSC_REG(base) ((base)->MSC) #define CMT_CMD1_REG(base) ((base)->CMD1) #define CMT_CMD2_REG(base) ((base)->CMD2) #define CMT_CMD3_REG(base) ((base)->CMD3) #define CMT_CMD4_REG(base) ((base)->CMD4) #define CMT_PPS_REG(base) ((base)->PPS) #define CMT_DMA_REG(base) ((base)->DMA) /*! * @} */ /* end of group CMT_Register_Accessor_Macros */ /* ---------------------------------------------------------------------------- -- CMT Register Masks ---------------------------------------------------------------------------- */ /*! * @addtogroup CMT_Register_Masks CMT Register Masks * @{ */ /* CGH1 Bit Fields */ #define CMT_CGH1_PH_MASK 0xFFu #define CMT_CGH1_PH_SHIFT 0 #define CMT_CGH1_PH(x) (((uint8_t)(((uint8_t)(x))<ACCESS16BIT.DATAL) #define CRC_DATAH_REG(base) ((base)->ACCESS16BIT.DATAH) #define CRC_DATA_REG(base) ((base)->DATA) #define CRC_DATALL_REG(base) ((base)->ACCESS8BIT.DATALL) #define CRC_DATALU_REG(base) ((base)->ACCESS8BIT.DATALU) #define CRC_DATAHL_REG(base) ((base)->ACCESS8BIT.DATAHL) #define CRC_DATAHU_REG(base) ((base)->ACCESS8BIT.DATAHU) #define CRC_GPOLYL_REG(base) ((base)->GPOLY_ACCESS16BIT.GPOLYL) #define CRC_GPOLYH_REG(base) ((base)->GPOLY_ACCESS16BIT.GPOLYH) #define CRC_GPOLY_REG(base) ((base)->GPOLY) #define CRC_GPOLYLL_REG(base) ((base)->GPOLY_ACCESS8BIT.GPOLYLL) #define CRC_GPOLYLU_REG(base) ((base)->GPOLY_ACCESS8BIT.GPOLYLU) #define CRC_GPOLYHL_REG(base) ((base)->GPOLY_ACCESS8BIT.GPOLYHL) #define CRC_GPOLYHU_REG(base) ((base)->GPOLY_ACCESS8BIT.GPOLYHU) #define CRC_CTRL_REG(base) ((base)->CTRL) #define CRC_CTRLHU_REG(base) ((base)->CTRL_ACCESS8BIT.CTRLHU) /*! * @} */ /* end of group CRC_Register_Accessor_Macros */ /* ---------------------------------------------------------------------------- -- CRC Register Masks ---------------------------------------------------------------------------- */ /*! * @addtogroup CRC_Register_Masks CRC Register Masks * @{ */ /* DATAL Bit Fields */ #define CRC_DATAL_DATAL_MASK 0xFFFFu #define CRC_DATAL_DATAL_SHIFT 0 #define CRC_DATAL_DATAL(x) (((uint16_t)(((uint16_t)(x))<DAT[index].DATL) #define DAC_DATH_REG(base,index) ((base)->DAT[index].DATH) #define DAC_SR_REG(base) ((base)->SR) #define DAC_C0_REG(base) ((base)->C0) #define DAC_C1_REG(base) ((base)->C1) #define DAC_C2_REG(base) ((base)->C2) /*! * @} */ /* end of group DAC_Register_Accessor_Macros */ /* ---------------------------------------------------------------------------- -- DAC Register Masks ---------------------------------------------------------------------------- */ /*! * @addtogroup DAC_Register_Masks DAC Register Masks * @{ */ /* DATL Bit Fields */ #define DAC_DATL_DATA0_MASK 0xFFu #define DAC_DATL_DATA0_SHIFT 0 #define DAC_DATL_DATA0(x) (((uint8_t)(((uint8_t)(x))<CR) #define DMA_ES_REG(base) ((base)->ES) #define DMA_ERQ_REG(base) ((base)->ERQ) #define DMA_EEI_REG(base) ((base)->EEI) #define DMA_CEEI_REG(base) ((base)->CEEI) #define DMA_SEEI_REG(base) ((base)->SEEI) #define DMA_CERQ_REG(base) ((base)->CERQ) #define DMA_SERQ_REG(base) ((base)->SERQ) #define DMA_CDNE_REG(base) ((base)->CDNE) #define DMA_SSRT_REG(base) ((base)->SSRT) #define DMA_CERR_REG(base) ((base)->CERR) #define DMA_CINT_REG(base) ((base)->CINT) #define DMA_INT_REG(base) ((base)->INT) #define DMA_ERR_REG(base) ((base)->ERR) #define DMA_HRS_REG(base) ((base)->HRS) #define DMA_DCHPRI3_REG(base) ((base)->DCHPRI3) #define DMA_DCHPRI2_REG(base) ((base)->DCHPRI2) #define DMA_DCHPRI1_REG(base) ((base)->DCHPRI1) #define DMA_DCHPRI0_REG(base) ((base)->DCHPRI0) #define DMA_DCHPRI7_REG(base) ((base)->DCHPRI7) #define DMA_DCHPRI6_REG(base) ((base)->DCHPRI6) #define DMA_DCHPRI5_REG(base) ((base)->DCHPRI5) #define DMA_DCHPRI4_REG(base) ((base)->DCHPRI4) #define DMA_DCHPRI11_REG(base) ((base)->DCHPRI11) #define DMA_DCHPRI10_REG(base) ((base)->DCHPRI10) #define DMA_DCHPRI9_REG(base) ((base)->DCHPRI9) #define DMA_DCHPRI8_REG(base) ((base)->DCHPRI8) #define DMA_DCHPRI15_REG(base) ((base)->DCHPRI15) #define DMA_DCHPRI14_REG(base) ((base)->DCHPRI14) #define DMA_DCHPRI13_REG(base) ((base)->DCHPRI13) #define DMA_DCHPRI12_REG(base) ((base)->DCHPRI12) #define DMA_SADDR_REG(base,index) ((base)->TCD[index].SADDR) #define DMA_SOFF_REG(base,index) ((base)->TCD[index].SOFF) #define DMA_ATTR_REG(base,index) ((base)->TCD[index].ATTR) #define DMA_NBYTES_MLNO_REG(base,index) ((base)->TCD[index].NBYTES_MLNO) #define DMA_NBYTES_MLOFFNO_REG(base,index) ((base)->TCD[index].NBYTES_MLOFFNO) #define DMA_NBYTES_MLOFFYES_REG(base,index) ((base)->TCD[index].NBYTES_MLOFFYES) #define DMA_SLAST_REG(base,index) ((base)->TCD[index].SLAST) #define DMA_DADDR_REG(base,index) ((base)->TCD[index].DADDR) #define DMA_DOFF_REG(base,index) ((base)->TCD[index].DOFF) #define DMA_CITER_ELINKNO_REG(base,index) ((base)->TCD[index].CITER_ELINKNO) #define DMA_CITER_ELINKYES_REG(base,index) ((base)->TCD[index].CITER_ELINKYES) #define DMA_DLAST_SGA_REG(base,index) ((base)->TCD[index].DLAST_SGA) #define DMA_CSR_REG(base,index) ((base)->TCD[index].CSR) #define DMA_BITER_ELINKNO_REG(base,index) ((base)->TCD[index].BITER_ELINKNO) #define DMA_BITER_ELINKYES_REG(base,index) ((base)->TCD[index].BITER_ELINKYES) /*! * @} */ /* end of group DMA_Register_Accessor_Macros */ /* ---------------------------------------------------------------------------- -- DMA Register Masks ---------------------------------------------------------------------------- */ /*! * @addtogroup DMA_Register_Masks DMA Register Masks * @{ */ /* CR Bit Fields */ #define DMA_CR_EDBG_MASK 0x2u #define DMA_CR_EDBG_SHIFT 1 #define DMA_CR_ERCA_MASK 0x4u #define DMA_CR_ERCA_SHIFT 2 #define DMA_CR_HOE_MASK 0x10u #define DMA_CR_HOE_SHIFT 4 #define DMA_CR_HALT_MASK 0x20u #define DMA_CR_HALT_SHIFT 5 #define DMA_CR_CLM_MASK 0x40u #define DMA_CR_CLM_SHIFT 6 #define DMA_CR_EMLM_MASK 0x80u #define DMA_CR_EMLM_SHIFT 7 #define DMA_CR_ECX_MASK 0x10000u #define DMA_CR_ECX_SHIFT 16 #define DMA_CR_CX_MASK 0x20000u #define DMA_CR_CX_SHIFT 17 /* ES Bit Fields */ #define DMA_ES_DBE_MASK 0x1u #define DMA_ES_DBE_SHIFT 0 #define DMA_ES_SBE_MASK 0x2u #define DMA_ES_SBE_SHIFT 1 #define DMA_ES_SGE_MASK 0x4u #define DMA_ES_SGE_SHIFT 2 #define DMA_ES_NCE_MASK 0x8u #define DMA_ES_NCE_SHIFT 3 #define DMA_ES_DOE_MASK 0x10u #define DMA_ES_DOE_SHIFT 4 #define DMA_ES_DAE_MASK 0x20u #define DMA_ES_DAE_SHIFT 5 #define DMA_ES_SOE_MASK 0x40u #define DMA_ES_SOE_SHIFT 6 #define DMA_ES_SAE_MASK 0x80u #define DMA_ES_SAE_SHIFT 7 #define DMA_ES_ERRCHN_MASK 0xF00u #define DMA_ES_ERRCHN_SHIFT 8 #define DMA_ES_ERRCHN(x) (((uint32_t)(((uint32_t)(x))<CHCFG[index]) /*! * @} */ /* end of group DMAMUX_Register_Accessor_Macros */ /* ---------------------------------------------------------------------------- -- DMAMUX Register Masks ---------------------------------------------------------------------------- */ /*! * @addtogroup DMAMUX_Register_Masks DMAMUX Register Masks * @{ */ /* CHCFG Bit Fields */ #define DMAMUX_CHCFG_SOURCE_MASK 0x3Fu #define DMAMUX_CHCFG_SOURCE_SHIFT 0 #define DMAMUX_CHCFG_SOURCE(x) (((uint8_t)(((uint8_t)(x))<EIR) #define ENET_EIMR_REG(base) ((base)->EIMR) #define ENET_RDAR_REG(base) ((base)->RDAR) #define ENET_TDAR_REG(base) ((base)->TDAR) #define ENET_ECR_REG(base) ((base)->ECR) #define ENET_MMFR_REG(base) ((base)->MMFR) #define ENET_MSCR_REG(base) ((base)->MSCR) #define ENET_MIBC_REG(base) ((base)->MIBC) #define ENET_RCR_REG(base) ((base)->RCR) #define ENET_TCR_REG(base) ((base)->TCR) #define ENET_PALR_REG(base) ((base)->PALR) #define ENET_PAUR_REG(base) ((base)->PAUR) #define ENET_OPD_REG(base) ((base)->OPD) #define ENET_IAUR_REG(base) ((base)->IAUR) #define ENET_IALR_REG(base) ((base)->IALR) #define ENET_GAUR_REG(base) ((base)->GAUR) #define ENET_GALR_REG(base) ((base)->GALR) #define ENET_TFWR_REG(base) ((base)->TFWR) #define ENET_RDSR_REG(base) ((base)->RDSR) #define ENET_TDSR_REG(base) ((base)->TDSR) #define ENET_MRBR_REG(base) ((base)->MRBR) #define ENET_RSFL_REG(base) ((base)->RSFL) #define ENET_RSEM_REG(base) ((base)->RSEM) #define ENET_RAEM_REG(base) ((base)->RAEM) #define ENET_RAFL_REG(base) ((base)->RAFL) #define ENET_TSEM_REG(base) ((base)->TSEM) #define ENET_TAEM_REG(base) ((base)->TAEM) #define ENET_TAFL_REG(base) ((base)->TAFL) #define ENET_TIPG_REG(base) ((base)->TIPG) #define ENET_FTRL_REG(base) ((base)->FTRL) #define ENET_TACC_REG(base) ((base)->TACC) #define ENET_RACC_REG(base) ((base)->RACC) #define ENET_RMON_T_PACKETS_REG(base) ((base)->RMON_T_PACKETS) #define ENET_RMON_T_BC_PKT_REG(base) ((base)->RMON_T_BC_PKT) #define ENET_RMON_T_MC_PKT_REG(base) ((base)->RMON_T_MC_PKT) #define ENET_RMON_T_CRC_ALIGN_REG(base) ((base)->RMON_T_CRC_ALIGN) #define ENET_RMON_T_UNDERSIZE_REG(base) ((base)->RMON_T_UNDERSIZE) #define ENET_RMON_T_OVERSIZE_REG(base) ((base)->RMON_T_OVERSIZE) #define ENET_RMON_T_FRAG_REG(base) ((base)->RMON_T_FRAG) #define ENET_RMON_T_JAB_REG(base) ((base)->RMON_T_JAB) #define ENET_RMON_T_COL_REG(base) ((base)->RMON_T_COL) #define ENET_RMON_T_P64_REG(base) ((base)->RMON_T_P64) #define ENET_RMON_T_P65TO127_REG(base) ((base)->RMON_T_P65TO127) #define ENET_RMON_T_P128TO255_REG(base) ((base)->RMON_T_P128TO255) #define ENET_RMON_T_P256TO511_REG(base) ((base)->RMON_T_P256TO511) #define ENET_RMON_T_P512TO1023_REG(base) ((base)->RMON_T_P512TO1023) #define ENET_RMON_T_P1024TO2047_REG(base) ((base)->RMON_T_P1024TO2047) #define ENET_RMON_T_P_GTE2048_REG(base) ((base)->RMON_T_P_GTE2048) #define ENET_RMON_T_OCTETS_REG(base) ((base)->RMON_T_OCTETS) #define ENET_IEEE_T_FRAME_OK_REG(base) ((base)->IEEE_T_FRAME_OK) #define ENET_IEEE_T_1COL_REG(base) ((base)->IEEE_T_1COL) #define ENET_IEEE_T_MCOL_REG(base) ((base)->IEEE_T_MCOL) #define ENET_IEEE_T_DEF_REG(base) ((base)->IEEE_T_DEF) #define ENET_IEEE_T_LCOL_REG(base) ((base)->IEEE_T_LCOL) #define ENET_IEEE_T_EXCOL_REG(base) ((base)->IEEE_T_EXCOL) #define ENET_IEEE_T_MACERR_REG(base) ((base)->IEEE_T_MACERR) #define ENET_IEEE_T_CSERR_REG(base) ((base)->IEEE_T_CSERR) #define ENET_IEEE_T_FDXFC_REG(base) ((base)->IEEE_T_FDXFC) #define ENET_IEEE_T_OCTETS_OK_REG(base) ((base)->IEEE_T_OCTETS_OK) #define ENET_RMON_R_PACKETS_REG(base) ((base)->RMON_R_PACKETS) #define ENET_RMON_R_BC_PKT_REG(base) ((base)->RMON_R_BC_PKT) #define ENET_RMON_R_MC_PKT_REG(base) ((base)->RMON_R_MC_PKT) #define ENET_RMON_R_CRC_ALIGN_REG(base) ((base)->RMON_R_CRC_ALIGN) #define ENET_RMON_R_UNDERSIZE_REG(base) ((base)->RMON_R_UNDERSIZE) #define ENET_RMON_R_OVERSIZE_REG(base) ((base)->RMON_R_OVERSIZE) #define ENET_RMON_R_FRAG_REG(base) ((base)->RMON_R_FRAG) #define ENET_RMON_R_JAB_REG(base) ((base)->RMON_R_JAB) #define ENET_RMON_R_P64_REG(base) ((base)->RMON_R_P64) #define ENET_RMON_R_P65TO127_REG(base) ((base)->RMON_R_P65TO127) #define ENET_RMON_R_P128TO255_REG(base) ((base)->RMON_R_P128TO255) #define ENET_RMON_R_P256TO511_REG(base) ((base)->RMON_R_P256TO511) #define ENET_RMON_R_P512TO1023_REG(base) ((base)->RMON_R_P512TO1023) #define ENET_RMON_R_P1024TO2047_REG(base) ((base)->RMON_R_P1024TO2047) #define ENET_RMON_R_P_GTE2048_REG(base) ((base)->RMON_R_P_GTE2048) #define ENET_RMON_R_OCTETS_REG(base) ((base)->RMON_R_OCTETS) #define ENET_IEEE_R_DROP_REG(base) ((base)->IEEE_R_DROP) #define ENET_IEEE_R_FRAME_OK_REG(base) ((base)->IEEE_R_FRAME_OK) #define ENET_IEEE_R_CRC_REG(base) ((base)->IEEE_R_CRC) #define ENET_IEEE_R_ALIGN_REG(base) ((base)->IEEE_R_ALIGN) #define ENET_IEEE_R_MACERR_REG(base) ((base)->IEEE_R_MACERR) #define ENET_IEEE_R_FDXFC_REG(base) ((base)->IEEE_R_FDXFC) #define ENET_IEEE_R_OCTETS_OK_REG(base) ((base)->IEEE_R_OCTETS_OK) #define ENET_ATCR_REG(base) ((base)->ATCR) #define ENET_ATVR_REG(base) ((base)->ATVR) #define ENET_ATOFF_REG(base) ((base)->ATOFF) #define ENET_ATPER_REG(base) ((base)->ATPER) #define ENET_ATCOR_REG(base) ((base)->ATCOR) #define ENET_ATINC_REG(base) ((base)->ATINC) #define ENET_ATSTMP_REG(base) ((base)->ATSTMP) #define ENET_TGSR_REG(base) ((base)->TGSR) #define ENET_TCSR_REG(base,index) ((base)->CHANNEL[index].TCSR) #define ENET_TCCR_REG(base,index) ((base)->CHANNEL[index].TCCR) /*! * @} */ /* end of group ENET_Register_Accessor_Macros */ /* ---------------------------------------------------------------------------- -- ENET Register Masks ---------------------------------------------------------------------------- */ /*! * @addtogroup ENET_Register_Masks ENET Register Masks * @{ */ /* EIR Bit Fields */ #define ENET_EIR_TS_TIMER_MASK 0x8000u #define ENET_EIR_TS_TIMER_SHIFT 15 #define ENET_EIR_TS_AVAIL_MASK 0x10000u #define ENET_EIR_TS_AVAIL_SHIFT 16 #define ENET_EIR_WAKEUP_MASK 0x20000u #define ENET_EIR_WAKEUP_SHIFT 17 #define ENET_EIR_PLR_MASK 0x40000u #define ENET_EIR_PLR_SHIFT 18 #define ENET_EIR_UN_MASK 0x80000u #define ENET_EIR_UN_SHIFT 19 #define ENET_EIR_RL_MASK 0x100000u #define ENET_EIR_RL_SHIFT 20 #define ENET_EIR_LC_MASK 0x200000u #define ENET_EIR_LC_SHIFT 21 #define ENET_EIR_EBERR_MASK 0x400000u #define ENET_EIR_EBERR_SHIFT 22 #define ENET_EIR_MII_MASK 0x800000u #define ENET_EIR_MII_SHIFT 23 #define ENET_EIR_RXB_MASK 0x1000000u #define ENET_EIR_RXB_SHIFT 24 #define ENET_EIR_RXF_MASK 0x2000000u #define ENET_EIR_RXF_SHIFT 25 #define ENET_EIR_TXB_MASK 0x4000000u #define ENET_EIR_TXB_SHIFT 26 #define ENET_EIR_TXF_MASK 0x8000000u #define ENET_EIR_TXF_SHIFT 27 #define ENET_EIR_GRA_MASK 0x10000000u #define ENET_EIR_GRA_SHIFT 28 #define ENET_EIR_BABT_MASK 0x20000000u #define ENET_EIR_BABT_SHIFT 29 #define ENET_EIR_BABR_MASK 0x40000000u #define ENET_EIR_BABR_SHIFT 30 /* EIMR Bit Fields */ #define ENET_EIMR_TS_TIMER_MASK 0x8000u #define ENET_EIMR_TS_TIMER_SHIFT 15 #define ENET_EIMR_TS_AVAIL_MASK 0x10000u #define ENET_EIMR_TS_AVAIL_SHIFT 16 #define ENET_EIMR_WAKEUP_MASK 0x20000u #define ENET_EIMR_WAKEUP_SHIFT 17 #define ENET_EIMR_PLR_MASK 0x40000u #define ENET_EIMR_PLR_SHIFT 18 #define ENET_EIMR_UN_MASK 0x80000u #define ENET_EIMR_UN_SHIFT 19 #define ENET_EIMR_RL_MASK 0x100000u #define ENET_EIMR_RL_SHIFT 20 #define ENET_EIMR_LC_MASK 0x200000u #define ENET_EIMR_LC_SHIFT 21 #define ENET_EIMR_EBERR_MASK 0x400000u #define ENET_EIMR_EBERR_SHIFT 22 #define ENET_EIMR_MII_MASK 0x800000u #define ENET_EIMR_MII_SHIFT 23 #define ENET_EIMR_RXB_MASK 0x1000000u #define ENET_EIMR_RXB_SHIFT 24 #define ENET_EIMR_RXF_MASK 0x2000000u #define ENET_EIMR_RXF_SHIFT 25 #define ENET_EIMR_TXB_MASK 0x4000000u #define ENET_EIMR_TXB_SHIFT 26 #define ENET_EIMR_TXF_MASK 0x8000000u #define ENET_EIMR_TXF_SHIFT 27 #define ENET_EIMR_GRA_MASK 0x10000000u #define ENET_EIMR_GRA_SHIFT 28 #define ENET_EIMR_BABT_MASK 0x20000000u #define ENET_EIMR_BABT_SHIFT 29 #define ENET_EIMR_BABR_MASK 0x40000000u #define ENET_EIMR_BABR_SHIFT 30 /* RDAR Bit Fields */ #define ENET_RDAR_RDAR_MASK 0x1000000u #define ENET_RDAR_RDAR_SHIFT 24 /* TDAR Bit Fields */ #define ENET_TDAR_TDAR_MASK 0x1000000u #define ENET_TDAR_TDAR_SHIFT 24 /* ECR Bit Fields */ #define ENET_ECR_RESET_MASK 0x1u #define ENET_ECR_RESET_SHIFT 0 #define ENET_ECR_ETHEREN_MASK 0x2u #define ENET_ECR_ETHEREN_SHIFT 1 #define ENET_ECR_MAGICEN_MASK 0x4u #define ENET_ECR_MAGICEN_SHIFT 2 #define ENET_ECR_SLEEP_MASK 0x8u #define ENET_ECR_SLEEP_SHIFT 3 #define ENET_ECR_EN1588_MASK 0x10u #define ENET_ECR_EN1588_SHIFT 4 #define ENET_ECR_DBGEN_MASK 0x40u #define ENET_ECR_DBGEN_SHIFT 6 #define ENET_ECR_STOPEN_MASK 0x80u #define ENET_ECR_STOPEN_SHIFT 7 #define ENET_ECR_DBSWP_MASK 0x100u #define ENET_ECR_DBSWP_SHIFT 8 /* MMFR Bit Fields */ #define ENET_MMFR_DATA_MASK 0xFFFFu #define ENET_MMFR_DATA_SHIFT 0 #define ENET_MMFR_DATA(x) (((uint32_t)(((uint32_t)(x))<CTRL) #define EWM_SERV_REG(base) ((base)->SERV) #define EWM_CMPL_REG(base) ((base)->CMPL) #define EWM_CMPH_REG(base) ((base)->CMPH) /*! * @} */ /* end of group EWM_Register_Accessor_Macros */ /* ---------------------------------------------------------------------------- -- EWM Register Masks ---------------------------------------------------------------------------- */ /*! * @addtogroup EWM_Register_Masks EWM Register Masks * @{ */ /* CTRL Bit Fields */ #define EWM_CTRL_EWMEN_MASK 0x1u #define EWM_CTRL_EWMEN_SHIFT 0 #define EWM_CTRL_ASSIN_MASK 0x2u #define EWM_CTRL_ASSIN_SHIFT 1 #define EWM_CTRL_INEN_MASK 0x4u #define EWM_CTRL_INEN_SHIFT 2 #define EWM_CTRL_INTEN_MASK 0x8u #define EWM_CTRL_INTEN_SHIFT 3 /* SERV Bit Fields */ #define EWM_SERV_SERVICE_MASK 0xFFu #define EWM_SERV_SERVICE_SHIFT 0 #define EWM_SERV_SERVICE(x) (((uint8_t)(((uint8_t)(x))<CS[index].CSAR) #define FB_CSMR_REG(base,index) ((base)->CS[index].CSMR) #define FB_CSCR_REG(base,index) ((base)->CS[index].CSCR) #define FB_CSPMCR_REG(base) ((base)->CSPMCR) /*! * @} */ /* end of group FB_Register_Accessor_Macros */ /* ---------------------------------------------------------------------------- -- FB Register Masks ---------------------------------------------------------------------------- */ /*! * @addtogroup FB_Register_Masks FB Register Masks * @{ */ /* CSAR Bit Fields */ #define FB_CSAR_BA_MASK 0xFFFF0000u #define FB_CSAR_BA_SHIFT 16 #define FB_CSAR_BA(x) (((uint32_t)(((uint32_t)(x))<PFAPR) #define FMC_PFB0CR_REG(base) ((base)->PFB0CR) #define FMC_PFB1CR_REG(base) ((base)->PFB1CR) #define FMC_TAGVDW0S_REG(base,index) ((base)->TAGVDW0S[index]) #define FMC_TAGVDW1S_REG(base,index) ((base)->TAGVDW1S[index]) #define FMC_TAGVDW2S_REG(base,index) ((base)->TAGVDW2S[index]) #define FMC_TAGVDW3S_REG(base,index) ((base)->TAGVDW3S[index]) #define FMC_DATA_U_REG(base,index,index2) ((base)->SET[index][index2].DATA_U) #define FMC_DATA_L_REG(base,index,index2) ((base)->SET[index][index2].DATA_L) /*! * @} */ /* end of group FMC_Register_Accessor_Macros */ /* ---------------------------------------------------------------------------- -- FMC Register Masks ---------------------------------------------------------------------------- */ /*! * @addtogroup FMC_Register_Masks FMC Register Masks * @{ */ /* PFAPR Bit Fields */ #define FMC_PFAPR_M0AP_MASK 0x3u #define FMC_PFAPR_M0AP_SHIFT 0 #define FMC_PFAPR_M0AP(x) (((uint32_t)(((uint32_t)(x))<FSTAT) #define FTFE_FCNFG_REG(base) ((base)->FCNFG) #define FTFE_FSEC_REG(base) ((base)->FSEC) #define FTFE_FOPT_REG(base) ((base)->FOPT) #define FTFE_FCCOB3_REG(base) ((base)->FCCOB3) #define FTFE_FCCOB2_REG(base) ((base)->FCCOB2) #define FTFE_FCCOB1_REG(base) ((base)->FCCOB1) #define FTFE_FCCOB0_REG(base) ((base)->FCCOB0) #define FTFE_FCCOB7_REG(base) ((base)->FCCOB7) #define FTFE_FCCOB6_REG(base) ((base)->FCCOB6) #define FTFE_FCCOB5_REG(base) ((base)->FCCOB5) #define FTFE_FCCOB4_REG(base) ((base)->FCCOB4) #define FTFE_FCCOBB_REG(base) ((base)->FCCOBB) #define FTFE_FCCOBA_REG(base) ((base)->FCCOBA) #define FTFE_FCCOB9_REG(base) ((base)->FCCOB9) #define FTFE_FCCOB8_REG(base) ((base)->FCCOB8) #define FTFE_FPROT3_REG(base) ((base)->FPROT3) #define FTFE_FPROT2_REG(base) ((base)->FPROT2) #define FTFE_FPROT1_REG(base) ((base)->FPROT1) #define FTFE_FPROT0_REG(base) ((base)->FPROT0) #define FTFE_FEPROT_REG(base) ((base)->FEPROT) #define FTFE_FDPROT_REG(base) ((base)->FDPROT) /*! * @} */ /* end of group FTFE_Register_Accessor_Macros */ /* ---------------------------------------------------------------------------- -- FTFE Register Masks ---------------------------------------------------------------------------- */ /*! * @addtogroup FTFE_Register_Masks FTFE Register Masks * @{ */ /* FSTAT Bit Fields */ #define FTFE_FSTAT_MGSTAT0_MASK 0x1u #define FTFE_FSTAT_MGSTAT0_SHIFT 0 #define FTFE_FSTAT_FPVIOL_MASK 0x10u #define FTFE_FSTAT_FPVIOL_SHIFT 4 #define FTFE_FSTAT_ACCERR_MASK 0x20u #define FTFE_FSTAT_ACCERR_SHIFT 5 #define FTFE_FSTAT_RDCOLERR_MASK 0x40u #define FTFE_FSTAT_RDCOLERR_SHIFT 6 #define FTFE_FSTAT_CCIF_MASK 0x80u #define FTFE_FSTAT_CCIF_SHIFT 7 /* FCNFG Bit Fields */ #define FTFE_FCNFG_EEERDY_MASK 0x1u #define FTFE_FCNFG_EEERDY_SHIFT 0 #define FTFE_FCNFG_RAMRDY_MASK 0x2u #define FTFE_FCNFG_RAMRDY_SHIFT 1 #define FTFE_FCNFG_PFLSH_MASK 0x4u #define FTFE_FCNFG_PFLSH_SHIFT 2 #define FTFE_FCNFG_SWAP_MASK 0x8u #define FTFE_FCNFG_SWAP_SHIFT 3 #define FTFE_FCNFG_ERSSUSP_MASK 0x10u #define FTFE_FCNFG_ERSSUSP_SHIFT 4 #define FTFE_FCNFG_ERSAREQ_MASK 0x20u #define FTFE_FCNFG_ERSAREQ_SHIFT 5 #define FTFE_FCNFG_RDCOLLIE_MASK 0x40u #define FTFE_FCNFG_RDCOLLIE_SHIFT 6 #define FTFE_FCNFG_CCIE_MASK 0x80u #define FTFE_FCNFG_CCIE_SHIFT 7 /* FSEC Bit Fields */ #define FTFE_FSEC_SEC_MASK 0x3u #define FTFE_FSEC_SEC_SHIFT 0 #define FTFE_FSEC_SEC(x) (((uint8_t)(((uint8_t)(x))<SC) #define FTM_CNT_REG(base) ((base)->CNT) #define FTM_MOD_REG(base) ((base)->MOD) #define FTM_CnSC_REG(base,index) ((base)->CONTROLS[index].CnSC) #define FTM_CnV_REG(base,index) ((base)->CONTROLS[index].CnV) #define FTM_CNTIN_REG(base) ((base)->CNTIN) #define FTM_STATUS_REG(base) ((base)->STATUS) #define FTM_MODE_REG(base) ((base)->MODE) #define FTM_SYNC_REG(base) ((base)->SYNC) #define FTM_OUTINIT_REG(base) ((base)->OUTINIT) #define FTM_OUTMASK_REG(base) ((base)->OUTMASK) #define FTM_COMBINE_REG(base) ((base)->COMBINE) #define FTM_DEADTIME_REG(base) ((base)->DEADTIME) #define FTM_EXTTRIG_REG(base) ((base)->EXTTRIG) #define FTM_POL_REG(base) ((base)->POL) #define FTM_FMS_REG(base) ((base)->FMS) #define FTM_FILTER_REG(base) ((base)->FILTER) #define FTM_FLTCTRL_REG(base) ((base)->FLTCTRL) #define FTM_QDCTRL_REG(base) ((base)->QDCTRL) #define FTM_CONF_REG(base) ((base)->CONF) #define FTM_FLTPOL_REG(base) ((base)->FLTPOL) #define FTM_SYNCONF_REG(base) ((base)->SYNCONF) #define FTM_INVCTRL_REG(base) ((base)->INVCTRL) #define FTM_SWOCTRL_REG(base) ((base)->SWOCTRL) #define FTM_PWMLOAD_REG(base) ((base)->PWMLOAD) /*! * @} */ /* end of group FTM_Register_Accessor_Macros */ /* ---------------------------------------------------------------------------- -- FTM Register Masks ---------------------------------------------------------------------------- */ /*! * @addtogroup FTM_Register_Masks FTM Register Masks * @{ */ /* SC Bit Fields */ #define FTM_SC_PS_MASK 0x7u #define FTM_SC_PS_SHIFT 0 #define FTM_SC_PS(x) (((uint32_t)(((uint32_t)(x))<PDOR) #define GPIO_PSOR_REG(base) ((base)->PSOR) #define GPIO_PCOR_REG(base) ((base)->PCOR) #define GPIO_PTOR_REG(base) ((base)->PTOR) #define GPIO_PDIR_REG(base) ((base)->PDIR) #define GPIO_PDDR_REG(base) ((base)->PDDR) /*! * @} */ /* end of group GPIO_Register_Accessor_Macros */ /* ---------------------------------------------------------------------------- -- GPIO Register Masks ---------------------------------------------------------------------------- */ /*! * @addtogroup GPIO_Register_Masks GPIO Register Masks * @{ */ /* PDOR Bit Fields */ #define GPIO_PDOR_PDO_MASK 0xFFFFFFFFu #define GPIO_PDOR_PDO_SHIFT 0 #define GPIO_PDOR_PDO(x) (((uint32_t)(((uint32_t)(x))<A1) #define I2C_F_REG(base) ((base)->F) #define I2C_C1_REG(base) ((base)->C1) #define I2C_S_REG(base) ((base)->S) #define I2C_D_REG(base) ((base)->D) #define I2C_C2_REG(base) ((base)->C2) #define I2C_FLT_REG(base) ((base)->FLT) #define I2C_RA_REG(base) ((base)->RA) #define I2C_SMB_REG(base) ((base)->SMB) #define I2C_A2_REG(base) ((base)->A2) #define I2C_SLTH_REG(base) ((base)->SLTH) #define I2C_SLTL_REG(base) ((base)->SLTL) /*! * @} */ /* end of group I2C_Register_Accessor_Macros */ /* ---------------------------------------------------------------------------- -- I2C Register Masks ---------------------------------------------------------------------------- */ /*! * @addtogroup I2C_Register_Masks I2C Register Masks * @{ */ /* A1 Bit Fields */ #define I2C_A1_AD_MASK 0xFEu #define I2C_A1_AD_SHIFT 1 #define I2C_A1_AD(x) (((uint8_t)(((uint8_t)(x))<TCSR) #define I2S_TCR1_REG(base) ((base)->TCR1) #define I2S_TCR2_REG(base) ((base)->TCR2) #define I2S_TCR3_REG(base) ((base)->TCR3) #define I2S_TCR4_REG(base) ((base)->TCR4) #define I2S_TCR5_REG(base) ((base)->TCR5) #define I2S_TDR_REG(base,index) ((base)->TDR[index]) #define I2S_TFR_REG(base,index) ((base)->TFR[index]) #define I2S_TMR_REG(base) ((base)->TMR) #define I2S_RCSR_REG(base) ((base)->RCSR) #define I2S_RCR1_REG(base) ((base)->RCR1) #define I2S_RCR2_REG(base) ((base)->RCR2) #define I2S_RCR3_REG(base) ((base)->RCR3) #define I2S_RCR4_REG(base) ((base)->RCR4) #define I2S_RCR5_REG(base) ((base)->RCR5) #define I2S_RDR_REG(base,index) ((base)->RDR[index]) #define I2S_RFR_REG(base,index) ((base)->RFR[index]) #define I2S_RMR_REG(base) ((base)->RMR) #define I2S_MCR_REG(base) ((base)->MCR) #define I2S_MDR_REG(base) ((base)->MDR) /*! * @} */ /* end of group I2S_Register_Accessor_Macros */ /* ---------------------------------------------------------------------------- -- I2S Register Masks ---------------------------------------------------------------------------- */ /*! * @addtogroup I2S_Register_Masks I2S Register Masks * @{ */ /* TCSR Bit Fields */ #define I2S_TCSR_FRDE_MASK 0x1u #define I2S_TCSR_FRDE_SHIFT 0 #define I2S_TCSR_FWDE_MASK 0x2u #define I2S_TCSR_FWDE_SHIFT 1 #define I2S_TCSR_FRIE_MASK 0x100u #define I2S_TCSR_FRIE_SHIFT 8 #define I2S_TCSR_FWIE_MASK 0x200u #define I2S_TCSR_FWIE_SHIFT 9 #define I2S_TCSR_FEIE_MASK 0x400u #define I2S_TCSR_FEIE_SHIFT 10 #define I2S_TCSR_SEIE_MASK 0x800u #define I2S_TCSR_SEIE_SHIFT 11 #define I2S_TCSR_WSIE_MASK 0x1000u #define I2S_TCSR_WSIE_SHIFT 12 #define I2S_TCSR_FRF_MASK 0x10000u #define I2S_TCSR_FRF_SHIFT 16 #define I2S_TCSR_FWF_MASK 0x20000u #define I2S_TCSR_FWF_SHIFT 17 #define I2S_TCSR_FEF_MASK 0x40000u #define I2S_TCSR_FEF_SHIFT 18 #define I2S_TCSR_SEF_MASK 0x80000u #define I2S_TCSR_SEF_SHIFT 19 #define I2S_TCSR_WSF_MASK 0x100000u #define I2S_TCSR_WSF_SHIFT 20 #define I2S_TCSR_SR_MASK 0x1000000u #define I2S_TCSR_SR_SHIFT 24 #define I2S_TCSR_FR_MASK 0x2000000u #define I2S_TCSR_FR_SHIFT 25 #define I2S_TCSR_BCE_MASK 0x10000000u #define I2S_TCSR_BCE_SHIFT 28 #define I2S_TCSR_DBGE_MASK 0x20000000u #define I2S_TCSR_DBGE_SHIFT 29 #define I2S_TCSR_STOPE_MASK 0x40000000u #define I2S_TCSR_STOPE_SHIFT 30 #define I2S_TCSR_TE_MASK 0x80000000u #define I2S_TCSR_TE_SHIFT 31 /* TCR1 Bit Fields */ #define I2S_TCR1_TFW_MASK 0x7u #define I2S_TCR1_TFW_SHIFT 0 #define I2S_TCR1_TFW(x) (((uint32_t)(((uint32_t)(x))<PE1) #define LLWU_PE2_REG(base) ((base)->PE2) #define LLWU_PE3_REG(base) ((base)->PE3) #define LLWU_PE4_REG(base) ((base)->PE4) #define LLWU_ME_REG(base) ((base)->ME) #define LLWU_F1_REG(base) ((base)->F1) #define LLWU_F2_REG(base) ((base)->F2) #define LLWU_F3_REG(base) ((base)->F3) #define LLWU_FILT1_REG(base) ((base)->FILT1) #define LLWU_FILT2_REG(base) ((base)->FILT2) #define LLWU_RST_REG(base) ((base)->RST) /*! * @} */ /* end of group LLWU_Register_Accessor_Macros */ /* ---------------------------------------------------------------------------- -- LLWU Register Masks ---------------------------------------------------------------------------- */ /*! * @addtogroup LLWU_Register_Masks LLWU Register Masks * @{ */ /* PE1 Bit Fields */ #define LLWU_PE1_WUPE0_MASK 0x3u #define LLWU_PE1_WUPE0_SHIFT 0 #define LLWU_PE1_WUPE0(x) (((uint8_t)(((uint8_t)(x))<CSR) #define LPTMR_PSR_REG(base) ((base)->PSR) #define LPTMR_CMR_REG(base) ((base)->CMR) #define LPTMR_CNR_REG(base) ((base)->CNR) /*! * @} */ /* end of group LPTMR_Register_Accessor_Macros */ /* ---------------------------------------------------------------------------- -- LPTMR Register Masks ---------------------------------------------------------------------------- */ /*! * @addtogroup LPTMR_Register_Masks LPTMR Register Masks * @{ */ /* CSR Bit Fields */ #define LPTMR_CSR_TEN_MASK 0x1u #define LPTMR_CSR_TEN_SHIFT 0 #define LPTMR_CSR_TMS_MASK 0x2u #define LPTMR_CSR_TMS_SHIFT 1 #define LPTMR_CSR_TFC_MASK 0x4u #define LPTMR_CSR_TFC_SHIFT 2 #define LPTMR_CSR_TPP_MASK 0x8u #define LPTMR_CSR_TPP_SHIFT 3 #define LPTMR_CSR_TPS_MASK 0x30u #define LPTMR_CSR_TPS_SHIFT 4 #define LPTMR_CSR_TPS(x) (((uint32_t)(((uint32_t)(x))<C1) #define MCG_C2_REG(base) ((base)->C2) #define MCG_C3_REG(base) ((base)->C3) #define MCG_C4_REG(base) ((base)->C4) #define MCG_C5_REG(base) ((base)->C5) #define MCG_C6_REG(base) ((base)->C6) #define MCG_S_REG(base) ((base)->S) #define MCG_SC_REG(base) ((base)->SC) #define MCG_ATCVH_REG(base) ((base)->ATCVH) #define MCG_ATCVL_REG(base) ((base)->ATCVL) #define MCG_C7_REG(base) ((base)->C7) #define MCG_C8_REG(base) ((base)->C8) /*! * @} */ /* end of group MCG_Register_Accessor_Macros */ /* ---------------------------------------------------------------------------- -- MCG Register Masks ---------------------------------------------------------------------------- */ /*! * @addtogroup MCG_Register_Masks MCG Register Masks * @{ */ /* C1 Bit Fields */ #define MCG_C1_IREFSTEN_MASK 0x1u #define MCG_C1_IREFSTEN_SHIFT 0 #define MCG_C1_IRCLKEN_MASK 0x2u #define MCG_C1_IRCLKEN_SHIFT 1 #define MCG_C1_IREFS_MASK 0x4u #define MCG_C1_IREFS_SHIFT 2 #define MCG_C1_FRDIV_MASK 0x38u #define MCG_C1_FRDIV_SHIFT 3 #define MCG_C1_FRDIV(x) (((uint8_t)(((uint8_t)(x))<PLASC) #define MCM_PLAMC_REG(base) ((base)->PLAMC) #define MCM_CR_REG(base) ((base)->CR) #define MCM_ISCR_REG(base) ((base)->ISCR) #define MCM_ETBCC_REG(base) ((base)->ETBCC) #define MCM_ETBRL_REG(base) ((base)->ETBRL) #define MCM_ETBCNT_REG(base) ((base)->ETBCNT) #define MCM_PID_REG(base) ((base)->PID) /*! * @} */ /* end of group MCM_Register_Accessor_Macros */ /* ---------------------------------------------------------------------------- -- MCM Register Masks ---------------------------------------------------------------------------- */ /*! * @addtogroup MCM_Register_Masks MCM Register Masks * @{ */ /* PLASC Bit Fields */ #define MCM_PLASC_ASC_MASK 0xFFu #define MCM_PLASC_ASC_SHIFT 0 #define MCM_PLASC_ASC(x) (((uint16_t)(((uint16_t)(x))<CESR) #define MPU_EAR_REG(base,index) ((base)->SP[index].EAR) #define MPU_EDR_REG(base,index) ((base)->SP[index].EDR) #define MPU_WORD_REG(base,index,index2) ((base)->WORD[index][index2]) #define MPU_RGDAAC_REG(base,index) ((base)->RGDAAC[index]) /*! * @} */ /* end of group MPU_Register_Accessor_Macros */ /* ---------------------------------------------------------------------------- -- MPU Register Masks ---------------------------------------------------------------------------- */ /*! * @addtogroup MPU_Register_Masks MPU Register Masks * @{ */ /* CESR Bit Fields */ #define MPU_CESR_VLD_MASK 0x1u #define MPU_CESR_VLD_SHIFT 0 #define MPU_CESR_NRGD_MASK 0xF00u #define MPU_CESR_NRGD_SHIFT 8 #define MPU_CESR_NRGD(x) (((uint32_t)(((uint32_t)(x))<BACKKEY3) #define NV_BACKKEY2_REG(base) ((base)->BACKKEY2) #define NV_BACKKEY1_REG(base) ((base)->BACKKEY1) #define NV_BACKKEY0_REG(base) ((base)->BACKKEY0) #define NV_BACKKEY7_REG(base) ((base)->BACKKEY7) #define NV_BACKKEY6_REG(base) ((base)->BACKKEY6) #define NV_BACKKEY5_REG(base) ((base)->BACKKEY5) #define NV_BACKKEY4_REG(base) ((base)->BACKKEY4) #define NV_FPROT3_REG(base) ((base)->FPROT3) #define NV_FPROT2_REG(base) ((base)->FPROT2) #define NV_FPROT1_REG(base) ((base)->FPROT1) #define NV_FPROT0_REG(base) ((base)->FPROT0) #define NV_FSEC_REG(base) ((base)->FSEC) #define NV_FOPT_REG(base) ((base)->FOPT) #define NV_FEPROT_REG(base) ((base)->FEPROT) #define NV_FDPROT_REG(base) ((base)->FDPROT) /*! * @} */ /* end of group NV_Register_Accessor_Macros */ /* ---------------------------------------------------------------------------- -- NV Register Masks ---------------------------------------------------------------------------- */ /*! * @addtogroup NV_Register_Masks NV Register Masks * @{ */ /* BACKKEY3 Bit Fields */ #define NV_BACKKEY3_KEY_MASK 0xFFu #define NV_BACKKEY3_KEY_SHIFT 0 #define NV_BACKKEY3_KEY(x) (((uint8_t)(((uint8_t)(x))<CR) /*! * @} */ /* end of group OSC_Register_Accessor_Macros */ /* ---------------------------------------------------------------------------- -- OSC Register Masks ---------------------------------------------------------------------------- */ /*! * @addtogroup OSC_Register_Masks OSC Register Masks * @{ */ /* CR Bit Fields */ #define OSC_CR_SC16P_MASK 0x1u #define OSC_CR_SC16P_SHIFT 0 #define OSC_CR_SC8P_MASK 0x2u #define OSC_CR_SC8P_SHIFT 1 #define OSC_CR_SC4P_MASK 0x4u #define OSC_CR_SC4P_SHIFT 2 #define OSC_CR_SC2P_MASK 0x8u #define OSC_CR_SC2P_SHIFT 3 #define OSC_CR_EREFSTEN_MASK 0x20u #define OSC_CR_EREFSTEN_SHIFT 5 #define OSC_CR_ERCLKEN_MASK 0x80u #define OSC_CR_ERCLKEN_SHIFT 7 /*! * @} */ /* end of group OSC_Register_Masks */ /* OSC - Peripheral instance base addresses */ /** Peripheral OSC base address */ #define OSC_BASE (0x40065000u) /** Peripheral OSC base pointer */ #define OSC ((OSC_Type *)OSC_BASE) #define OSC_BASE_PTR (OSC) /** Array initializer of OSC peripheral base addresses */ #define OSC_BASE_ADDRS { OSC_BASE } /** Array initializer of OSC peripheral base pointers */ #define OSC_BASE_PTRS { OSC } /* ---------------------------------------------------------------------------- -- OSC - Register accessor macros ---------------------------------------------------------------------------- */ /*! * @addtogroup OSC_Register_Accessor_Macros OSC - Register accessor macros * @{ */ /* OSC - Register instance definitions */ /* OSC */ #define OSC_CR OSC_CR_REG(OSC) /*! * @} */ /* end of group OSC_Register_Accessor_Macros */ /*! * @} */ /* end of group OSC_Peripheral_Access_Layer */ /* ---------------------------------------------------------------------------- -- PDB Peripheral Access Layer ---------------------------------------------------------------------------- */ /*! * @addtogroup PDB_Peripheral_Access_Layer PDB Peripheral Access Layer * @{ */ /** PDB - Register Layout Typedef */ typedef struct { __IO uint32_t SC; /**< Status and Control register, offset: 0x0 */ __IO uint32_t MOD; /**< Modulus register, offset: 0x4 */ __I uint32_t CNT; /**< Counter register, offset: 0x8 */ __IO uint32_t IDLY; /**< Interrupt Delay register, offset: 0xC */ struct { /* offset: 0x10, array step: 0x28 */ __IO uint32_t C1; /**< Channel n Control register 1, array offset: 0x10, array step: 0x28 */ __IO uint32_t S; /**< Channel n Status register, array offset: 0x14, array step: 0x28 */ __IO uint32_t DLY[2]; /**< Channel n Delay 0 register..Channel n Delay 1 register, array offset: 0x18, array step: index*0x28, index2*0x4 */ uint8_t RESERVED_0[24]; } CH[2]; uint8_t RESERVED_0[240]; struct { /* offset: 0x150, array step: 0x8 */ __IO uint32_t INTC; /**< DAC Interval Trigger n Control register, array offset: 0x150, array step: 0x8 */ __IO uint32_t INT; /**< DAC Interval n register, array offset: 0x154, array step: 0x8 */ } DAC[2]; uint8_t RESERVED_1[48]; __IO uint32_t POEN; /**< Pulse-Out n Enable register, offset: 0x190 */ __IO uint32_t PODLY[3]; /**< Pulse-Out n Delay register, array offset: 0x194, array step: 0x4 */ } PDB_Type, *PDB_MemMapPtr; /* ---------------------------------------------------------------------------- -- PDB - Register accessor macros ---------------------------------------------------------------------------- */ /*! * @addtogroup PDB_Register_Accessor_Macros PDB - Register accessor macros * @{ */ /* PDB - Register accessors */ #define PDB_SC_REG(base) ((base)->SC) #define PDB_MOD_REG(base) ((base)->MOD) #define PDB_CNT_REG(base) ((base)->CNT) #define PDB_IDLY_REG(base) ((base)->IDLY) #define PDB_C1_REG(base,index) ((base)->CH[index].C1) #define PDB_S_REG(base,index) ((base)->CH[index].S) #define PDB_DLY_REG(base,index,index2) ((base)->CH[index].DLY[index2]) #define PDB_INTC_REG(base,index) ((base)->DAC[index].INTC) #define PDB_INT_REG(base,index) ((base)->DAC[index].INT) #define PDB_POEN_REG(base) ((base)->POEN) #define PDB_PODLY_REG(base,index) ((base)->PODLY[index]) /*! * @} */ /* end of group PDB_Register_Accessor_Macros */ /* ---------------------------------------------------------------------------- -- PDB Register Masks ---------------------------------------------------------------------------- */ /*! * @addtogroup PDB_Register_Masks PDB Register Masks * @{ */ /* SC Bit Fields */ #define PDB_SC_LDOK_MASK 0x1u #define PDB_SC_LDOK_SHIFT 0 #define PDB_SC_CONT_MASK 0x2u #define PDB_SC_CONT_SHIFT 1 #define PDB_SC_MULT_MASK 0xCu #define PDB_SC_MULT_SHIFT 2 #define PDB_SC_MULT(x) (((uint32_t)(((uint32_t)(x))<MCR) #define PIT_LDVAL_REG(base,index) ((base)->CHANNEL[index].LDVAL) #define PIT_CVAL_REG(base,index) ((base)->CHANNEL[index].CVAL) #define PIT_TCTRL_REG(base,index) ((base)->CHANNEL[index].TCTRL) #define PIT_TFLG_REG(base,index) ((base)->CHANNEL[index].TFLG) /*! * @} */ /* end of group PIT_Register_Accessor_Macros */ /* ---------------------------------------------------------------------------- -- PIT Register Masks ---------------------------------------------------------------------------- */ /*! * @addtogroup PIT_Register_Masks PIT Register Masks * @{ */ /* MCR Bit Fields */ #define PIT_MCR_FRZ_MASK 0x1u #define PIT_MCR_FRZ_SHIFT 0 #define PIT_MCR_MDIS_MASK 0x2u #define PIT_MCR_MDIS_SHIFT 1 /* LDVAL Bit Fields */ #define PIT_LDVAL_TSV_MASK 0xFFFFFFFFu #define PIT_LDVAL_TSV_SHIFT 0 #define PIT_LDVAL_TSV(x) (((uint32_t)(((uint32_t)(x))<LVDSC1) #define PMC_LVDSC2_REG(base) ((base)->LVDSC2) #define PMC_REGSC_REG(base) ((base)->REGSC) /*! * @} */ /* end of group PMC_Register_Accessor_Macros */ /* ---------------------------------------------------------------------------- -- PMC Register Masks ---------------------------------------------------------------------------- */ /*! * @addtogroup PMC_Register_Masks PMC Register Masks * @{ */ /* LVDSC1 Bit Fields */ #define PMC_LVDSC1_LVDV_MASK 0x3u #define PMC_LVDSC1_LVDV_SHIFT 0 #define PMC_LVDSC1_LVDV(x) (((uint8_t)(((uint8_t)(x))<PCR[index]) #define PORT_GPCLR_REG(base) ((base)->GPCLR) #define PORT_GPCHR_REG(base) ((base)->GPCHR) #define PORT_ISFR_REG(base) ((base)->ISFR) #define PORT_DFER_REG(base) ((base)->DFER) #define PORT_DFCR_REG(base) ((base)->DFCR) #define PORT_DFWR_REG(base) ((base)->DFWR) /*! * @} */ /* end of group PORT_Register_Accessor_Macros */ /* ---------------------------------------------------------------------------- -- PORT Register Masks ---------------------------------------------------------------------------- */ /*! * @addtogroup PORT_Register_Masks PORT Register Masks * @{ */ /* PCR Bit Fields */ #define PORT_PCR_PS_MASK 0x1u #define PORT_PCR_PS_SHIFT 0 #define PORT_PCR_PE_MASK 0x2u #define PORT_PCR_PE_SHIFT 1 #define PORT_PCR_SRE_MASK 0x4u #define PORT_PCR_SRE_SHIFT 2 #define PORT_PCR_PFE_MASK 0x10u #define PORT_PCR_PFE_SHIFT 4 #define PORT_PCR_ODE_MASK 0x20u #define PORT_PCR_ODE_SHIFT 5 #define PORT_PCR_DSE_MASK 0x40u #define PORT_PCR_DSE_SHIFT 6 #define PORT_PCR_MUX_MASK 0x700u #define PORT_PCR_MUX_SHIFT 8 #define PORT_PCR_MUX(x) (((uint32_t)(((uint32_t)(x))<SRS0) #define RCM_SRS1_REG(base) ((base)->SRS1) #define RCM_RPFC_REG(base) ((base)->RPFC) #define RCM_RPFW_REG(base) ((base)->RPFW) #define RCM_MR_REG(base) ((base)->MR) /*! * @} */ /* end of group RCM_Register_Accessor_Macros */ /* ---------------------------------------------------------------------------- -- RCM Register Masks ---------------------------------------------------------------------------- */ /*! * @addtogroup RCM_Register_Masks RCM Register Masks * @{ */ /* SRS0 Bit Fields */ #define RCM_SRS0_WAKEUP_MASK 0x1u #define RCM_SRS0_WAKEUP_SHIFT 0 #define RCM_SRS0_LVD_MASK 0x2u #define RCM_SRS0_LVD_SHIFT 1 #define RCM_SRS0_LOC_MASK 0x4u #define RCM_SRS0_LOC_SHIFT 2 #define RCM_SRS0_LOL_MASK 0x8u #define RCM_SRS0_LOL_SHIFT 3 #define RCM_SRS0_WDOG_MASK 0x20u #define RCM_SRS0_WDOG_SHIFT 5 #define RCM_SRS0_PIN_MASK 0x40u #define RCM_SRS0_PIN_SHIFT 6 #define RCM_SRS0_POR_MASK 0x80u #define RCM_SRS0_POR_SHIFT 7 /* SRS1 Bit Fields */ #define RCM_SRS1_JTAG_MASK 0x1u #define RCM_SRS1_JTAG_SHIFT 0 #define RCM_SRS1_LOCKUP_MASK 0x2u #define RCM_SRS1_LOCKUP_SHIFT 1 #define RCM_SRS1_SW_MASK 0x4u #define RCM_SRS1_SW_SHIFT 2 #define RCM_SRS1_MDM_AP_MASK 0x8u #define RCM_SRS1_MDM_AP_SHIFT 3 #define RCM_SRS1_EZPT_MASK 0x10u #define RCM_SRS1_EZPT_SHIFT 4 #define RCM_SRS1_SACKERR_MASK 0x20u #define RCM_SRS1_SACKERR_SHIFT 5 /* RPFC Bit Fields */ #define RCM_RPFC_RSTFLTSRW_MASK 0x3u #define RCM_RPFC_RSTFLTSRW_SHIFT 0 #define RCM_RPFC_RSTFLTSRW(x) (((uint8_t)(((uint8_t)(x))<REG[index]) /*! * @} */ /* end of group RFSYS_Register_Accessor_Macros */ /* ---------------------------------------------------------------------------- -- RFSYS Register Masks ---------------------------------------------------------------------------- */ /*! * @addtogroup RFSYS_Register_Masks RFSYS Register Masks * @{ */ /* REG Bit Fields */ #define RFSYS_REG_LL_MASK 0xFFu #define RFSYS_REG_LL_SHIFT 0 #define RFSYS_REG_LL(x) (((uint32_t)(((uint32_t)(x))<REG[index]) /*! * @} */ /* end of group RFVBAT_Register_Accessor_Macros */ /* ---------------------------------------------------------------------------- -- RFVBAT Register Masks ---------------------------------------------------------------------------- */ /*! * @addtogroup RFVBAT_Register_Masks RFVBAT Register Masks * @{ */ /* REG Bit Fields */ #define RFVBAT_REG_LL_MASK 0xFFu #define RFVBAT_REG_LL_SHIFT 0 #define RFVBAT_REG_LL(x) (((uint32_t)(((uint32_t)(x))<CR) #define RNG_SR_REG(base) ((base)->SR) #define RNG_ER_REG(base) ((base)->ER) #define RNG_OR_REG(base) ((base)->OR) /*! * @} */ /* end of group RNG_Register_Accessor_Macros */ /* ---------------------------------------------------------------------------- -- RNG Register Masks ---------------------------------------------------------------------------- */ /*! * @addtogroup RNG_Register_Masks RNG Register Masks * @{ */ /* CR Bit Fields */ #define RNG_CR_GO_MASK 0x1u #define RNG_CR_GO_SHIFT 0 #define RNG_CR_HA_MASK 0x2u #define RNG_CR_HA_SHIFT 1 #define RNG_CR_INTM_MASK 0x4u #define RNG_CR_INTM_SHIFT 2 #define RNG_CR_CLRI_MASK 0x8u #define RNG_CR_CLRI_SHIFT 3 #define RNG_CR_SLP_MASK 0x10u #define RNG_CR_SLP_SHIFT 4 /* SR Bit Fields */ #define RNG_SR_SECV_MASK 0x1u #define RNG_SR_SECV_SHIFT 0 #define RNG_SR_LRS_MASK 0x2u #define RNG_SR_LRS_SHIFT 1 #define RNG_SR_ORU_MASK 0x4u #define RNG_SR_ORU_SHIFT 2 #define RNG_SR_ERRI_MASK 0x8u #define RNG_SR_ERRI_SHIFT 3 #define RNG_SR_SLP_MASK 0x10u #define RNG_SR_SLP_SHIFT 4 #define RNG_SR_OREG_LVL_MASK 0xFF00u #define RNG_SR_OREG_LVL_SHIFT 8 #define RNG_SR_OREG_LVL(x) (((uint32_t)(((uint32_t)(x))<TSR) #define RTC_TPR_REG(base) ((base)->TPR) #define RTC_TAR_REG(base) ((base)->TAR) #define RTC_TCR_REG(base) ((base)->TCR) #define RTC_CR_REG(base) ((base)->CR) #define RTC_SR_REG(base) ((base)->SR) #define RTC_LR_REG(base) ((base)->LR) #define RTC_IER_REG(base) ((base)->IER) #define RTC_WAR_REG(base) ((base)->WAR) #define RTC_RAR_REG(base) ((base)->RAR) /*! * @} */ /* end of group RTC_Register_Accessor_Macros */ /* ---------------------------------------------------------------------------- -- RTC Register Masks ---------------------------------------------------------------------------- */ /*! * @addtogroup RTC_Register_Masks RTC Register Masks * @{ */ /* TSR Bit Fields */ #define RTC_TSR_TSR_MASK 0xFFFFFFFFu #define RTC_TSR_TSR_SHIFT 0 #define RTC_TSR_TSR(x) (((uint32_t)(((uint32_t)(x))<DSADDR) #define SDHC_BLKATTR_REG(base) ((base)->BLKATTR) #define SDHC_CMDARG_REG(base) ((base)->CMDARG) #define SDHC_XFERTYP_REG(base) ((base)->XFERTYP) #define SDHC_CMDRSP_REG(base,index) ((base)->CMDRSP[index]) #define SDHC_DATPORT_REG(base) ((base)->DATPORT) #define SDHC_PRSSTAT_REG(base) ((base)->PRSSTAT) #define SDHC_PROCTL_REG(base) ((base)->PROCTL) #define SDHC_SYSCTL_REG(base) ((base)->SYSCTL) #define SDHC_IRQSTAT_REG(base) ((base)->IRQSTAT) #define SDHC_IRQSTATEN_REG(base) ((base)->IRQSTATEN) #define SDHC_IRQSIGEN_REG(base) ((base)->IRQSIGEN) #define SDHC_AC12ERR_REG(base) ((base)->AC12ERR) #define SDHC_HTCAPBLT_REG(base) ((base)->HTCAPBLT) #define SDHC_WML_REG(base) ((base)->WML) #define SDHC_FEVT_REG(base) ((base)->FEVT) #define SDHC_ADMAES_REG(base) ((base)->ADMAES) #define SDHC_ADSADDR_REG(base) ((base)->ADSADDR) #define SDHC_VENDOR_REG(base) ((base)->VENDOR) #define SDHC_MMCBOOT_REG(base) ((base)->MMCBOOT) #define SDHC_HOSTVER_REG(base) ((base)->HOSTVER) /*! * @} */ /* end of group SDHC_Register_Accessor_Macros */ /* ---------------------------------------------------------------------------- -- SDHC Register Masks ---------------------------------------------------------------------------- */ /*! * @addtogroup SDHC_Register_Masks SDHC Register Masks * @{ */ /* DSADDR Bit Fields */ #define SDHC_DSADDR_DSADDR_MASK 0xFFFFFFFCu #define SDHC_DSADDR_DSADDR_SHIFT 2 #define SDHC_DSADDR_DSADDR(x) (((uint32_t)(((uint32_t)(x))<SOPT1) #define SIM_SOPT1CFG_REG(base) ((base)->SOPT1CFG) #define SIM_SOPT2_REG(base) ((base)->SOPT2) #define SIM_SOPT4_REG(base) ((base)->SOPT4) #define SIM_SOPT5_REG(base) ((base)->SOPT5) #define SIM_SOPT7_REG(base) ((base)->SOPT7) #define SIM_SDID_REG(base) ((base)->SDID) #define SIM_SCGC1_REG(base) ((base)->SCGC1) #define SIM_SCGC2_REG(base) ((base)->SCGC2) #define SIM_SCGC3_REG(base) ((base)->SCGC3) #define SIM_SCGC4_REG(base) ((base)->SCGC4) #define SIM_SCGC5_REG(base) ((base)->SCGC5) #define SIM_SCGC6_REG(base) ((base)->SCGC6) #define SIM_SCGC7_REG(base) ((base)->SCGC7) #define SIM_CLKDIV1_REG(base) ((base)->CLKDIV1) #define SIM_CLKDIV2_REG(base) ((base)->CLKDIV2) #define SIM_FCFG1_REG(base) ((base)->FCFG1) #define SIM_FCFG2_REG(base) ((base)->FCFG2) #define SIM_UIDH_REG(base) ((base)->UIDH) #define SIM_UIDMH_REG(base) ((base)->UIDMH) #define SIM_UIDML_REG(base) ((base)->UIDML) #define SIM_UIDL_REG(base) ((base)->UIDL) /*! * @} */ /* end of group SIM_Register_Accessor_Macros */ /* ---------------------------------------------------------------------------- -- SIM Register Masks ---------------------------------------------------------------------------- */ /*! * @addtogroup SIM_Register_Masks SIM Register Masks * @{ */ /* SOPT1 Bit Fields */ #define SIM_SOPT1_RAMSIZE_MASK 0xF000u #define SIM_SOPT1_RAMSIZE_SHIFT 12 #define SIM_SOPT1_RAMSIZE(x) (((uint32_t)(((uint32_t)(x))<PMPROT) #define SMC_PMCTRL_REG(base) ((base)->PMCTRL) #define SMC_VLLSCTRL_REG(base) ((base)->VLLSCTRL) #define SMC_PMSTAT_REG(base) ((base)->PMSTAT) /*! * @} */ /* end of group SMC_Register_Accessor_Macros */ /* ---------------------------------------------------------------------------- -- SMC Register Masks ---------------------------------------------------------------------------- */ /*! * @addtogroup SMC_Register_Masks SMC Register Masks * @{ */ /* PMPROT Bit Fields */ #define SMC_PMPROT_AVLLS_MASK 0x2u #define SMC_PMPROT_AVLLS_SHIFT 1 #define SMC_PMPROT_ALLS_MASK 0x8u #define SMC_PMPROT_ALLS_SHIFT 3 #define SMC_PMPROT_AVLP_MASK 0x20u #define SMC_PMPROT_AVLP_SHIFT 5 /* PMCTRL Bit Fields */ #define SMC_PMCTRL_STOPM_MASK 0x7u #define SMC_PMCTRL_STOPM_SHIFT 0 #define SMC_PMCTRL_STOPM(x) (((uint8_t)(((uint8_t)(x))<MCR) #define SPI_TCR_REG(base) ((base)->TCR) #define SPI_CTAR_REG(base,index2) ((base)->CTAR[index2]) #define SPI_CTAR_SLAVE_REG(base,index2) ((base)->CTAR_SLAVE[index2]) #define SPI_SR_REG(base) ((base)->SR) #define SPI_RSER_REG(base) ((base)->RSER) #define SPI_PUSHR_REG(base) ((base)->PUSHR) #define SPI_PUSHR_SLAVE_REG(base) ((base)->PUSHR_SLAVE) #define SPI_POPR_REG(base) ((base)->POPR) #define SPI_TXFR0_REG(base) ((base)->TXFR0) #define SPI_TXFR1_REG(base) ((base)->TXFR1) #define SPI_TXFR2_REG(base) ((base)->TXFR2) #define SPI_TXFR3_REG(base) ((base)->TXFR3) #define SPI_RXFR0_REG(base) ((base)->RXFR0) #define SPI_RXFR1_REG(base) ((base)->RXFR1) #define SPI_RXFR2_REG(base) ((base)->RXFR2) #define SPI_RXFR3_REG(base) ((base)->RXFR3) /*! * @} */ /* end of group SPI_Register_Accessor_Macros */ /* ---------------------------------------------------------------------------- -- SPI Register Masks ---------------------------------------------------------------------------- */ /*! * @addtogroup SPI_Register_Masks SPI Register Masks * @{ */ /* MCR Bit Fields */ #define SPI_MCR_HALT_MASK 0x1u #define SPI_MCR_HALT_SHIFT 0 #define SPI_MCR_SMPL_PT_MASK 0x300u #define SPI_MCR_SMPL_PT_SHIFT 8 #define SPI_MCR_SMPL_PT(x) (((uint32_t)(((uint32_t)(x))<BDH) #define UART_BDL_REG(base) ((base)->BDL) #define UART_C1_REG(base) ((base)->C1) #define UART_C2_REG(base) ((base)->C2) #define UART_S1_REG(base) ((base)->S1) #define UART_S2_REG(base) ((base)->S2) #define UART_C3_REG(base) ((base)->C3) #define UART_D_REG(base) ((base)->D) #define UART_MA1_REG(base) ((base)->MA1) #define UART_MA2_REG(base) ((base)->MA2) #define UART_C4_REG(base) ((base)->C4) #define UART_C5_REG(base) ((base)->C5) #define UART_ED_REG(base) ((base)->ED) #define UART_MODEM_REG(base) ((base)->MODEM) #define UART_IR_REG(base) ((base)->IR) #define UART_PFIFO_REG(base) ((base)->PFIFO) #define UART_CFIFO_REG(base) ((base)->CFIFO) #define UART_SFIFO_REG(base) ((base)->SFIFO) #define UART_TWFIFO_REG(base) ((base)->TWFIFO) #define UART_TCFIFO_REG(base) ((base)->TCFIFO) #define UART_RWFIFO_REG(base) ((base)->RWFIFO) #define UART_RCFIFO_REG(base) ((base)->RCFIFO) #define UART_C7816_REG(base) ((base)->C7816) #define UART_IE7816_REG(base) ((base)->IE7816) #define UART_IS7816_REG(base) ((base)->IS7816) #define UART_WP7816T0_REG(base) ((base)->WP7816T0) #define UART_WP7816T1_REG(base) ((base)->WP7816T1) #define UART_WN7816_REG(base) ((base)->WN7816) #define UART_WF7816_REG(base) ((base)->WF7816) #define UART_ET7816_REG(base) ((base)->ET7816) #define UART_TL7816_REG(base) ((base)->TL7816) /*! * @} */ /* end of group UART_Register_Accessor_Macros */ /* ---------------------------------------------------------------------------- -- UART Register Masks ---------------------------------------------------------------------------- */ /*! * @addtogroup UART_Register_Masks UART Register Masks * @{ */ /* BDH Bit Fields */ #define UART_BDH_SBR_MASK 0x1Fu #define UART_BDH_SBR_SHIFT 0 #define UART_BDH_SBR(x) (((uint8_t)(((uint8_t)(x))<PERID) #define USB_IDCOMP_REG(base) ((base)->IDCOMP) #define USB_REV_REG(base) ((base)->REV) #define USB_ADDINFO_REG(base) ((base)->ADDINFO) #define USB_OTGISTAT_REG(base) ((base)->OTGISTAT) #define USB_OTGICR_REG(base) ((base)->OTGICR) #define USB_OTGSTAT_REG(base) ((base)->OTGSTAT) #define USB_OTGCTL_REG(base) ((base)->OTGCTL) #define USB_ISTAT_REG(base) ((base)->ISTAT) #define USB_INTEN_REG(base) ((base)->INTEN) #define USB_ERRSTAT_REG(base) ((base)->ERRSTAT) #define USB_ERREN_REG(base) ((base)->ERREN) #define USB_STAT_REG(base) ((base)->STAT) #define USB_CTL_REG(base) ((base)->CTL) #define USB_ADDR_REG(base) ((base)->ADDR) #define USB_BDTPAGE1_REG(base) ((base)->BDTPAGE1) #define USB_FRMNUML_REG(base) ((base)->FRMNUML) #define USB_FRMNUMH_REG(base) ((base)->FRMNUMH) #define USB_TOKEN_REG(base) ((base)->TOKEN) #define USB_SOFTHLD_REG(base) ((base)->SOFTHLD) #define USB_BDTPAGE2_REG(base) ((base)->BDTPAGE2) #define USB_BDTPAGE3_REG(base) ((base)->BDTPAGE3) #define USB_ENDPT_REG(base,index) ((base)->ENDPOINT[index].ENDPT) #define USB_USBCTRL_REG(base) ((base)->USBCTRL) #define USB_OBSERVE_REG(base) ((base)->OBSERVE) #define USB_CONTROL_REG(base) ((base)->CONTROL) #define USB_USBTRC0_REG(base) ((base)->USBTRC0) #define USB_USBFRMADJUST_REG(base) ((base)->USBFRMADJUST) #define USB_CLK_RECOVER_CTRL_REG(base) ((base)->CLK_RECOVER_CTRL) #define USB_CLK_RECOVER_IRC_EN_REG(base) ((base)->CLK_RECOVER_IRC_EN) #define USB_CLK_RECOVER_INT_STATUS_REG(base) ((base)->CLK_RECOVER_INT_STATUS) /*! * @} */ /* end of group USB_Register_Accessor_Macros */ /* ---------------------------------------------------------------------------- -- USB Register Masks ---------------------------------------------------------------------------- */ /*! * @addtogroup USB_Register_Masks USB Register Masks * @{ */ /* PERID Bit Fields */ #define USB_PERID_ID_MASK 0x3Fu #define USB_PERID_ID_SHIFT 0 #define USB_PERID_ID(x) (((uint8_t)(((uint8_t)(x))<CONTROL) #define USBDCD_CLOCK_REG(base) ((base)->CLOCK) #define USBDCD_STATUS_REG(base) ((base)->STATUS) #define USBDCD_TIMER0_REG(base) ((base)->TIMER0) #define USBDCD_TIMER1_REG(base) ((base)->TIMER1) #define USBDCD_TIMER2_BC11_REG(base) ((base)->TIMER2_BC11) #define USBDCD_TIMER2_BC12_REG(base) ((base)->TIMER2_BC12) /*! * @} */ /* end of group USBDCD_Register_Accessor_Macros */ /* ---------------------------------------------------------------------------- -- USBDCD Register Masks ---------------------------------------------------------------------------- */ /*! * @addtogroup USBDCD_Register_Masks USBDCD Register Masks * @{ */ /* CONTROL Bit Fields */ #define USBDCD_CONTROL_IACK_MASK 0x1u #define USBDCD_CONTROL_IACK_SHIFT 0 #define USBDCD_CONTROL_IF_MASK 0x100u #define USBDCD_CONTROL_IF_SHIFT 8 #define USBDCD_CONTROL_IE_MASK 0x10000u #define USBDCD_CONTROL_IE_SHIFT 16 #define USBDCD_CONTROL_BC12_MASK 0x20000u #define USBDCD_CONTROL_BC12_SHIFT 17 #define USBDCD_CONTROL_START_MASK 0x1000000u #define USBDCD_CONTROL_START_SHIFT 24 #define USBDCD_CONTROL_SR_MASK 0x2000000u #define USBDCD_CONTROL_SR_SHIFT 25 /* CLOCK Bit Fields */ #define USBDCD_CLOCK_CLOCK_UNIT_MASK 0x1u #define USBDCD_CLOCK_CLOCK_UNIT_SHIFT 0 #define USBDCD_CLOCK_CLOCK_SPEED_MASK 0xFFCu #define USBDCD_CLOCK_CLOCK_SPEED_SHIFT 2 #define USBDCD_CLOCK_CLOCK_SPEED(x) (((uint32_t)(((uint32_t)(x))<TRM) #define VREF_SC_REG(base) ((base)->SC) /*! * @} */ /* end of group VREF_Register_Accessor_Macros */ /* ---------------------------------------------------------------------------- -- VREF Register Masks ---------------------------------------------------------------------------- */ /*! * @addtogroup VREF_Register_Masks VREF Register Masks * @{ */ /* TRM Bit Fields */ #define VREF_TRM_TRIM_MASK 0x3Fu #define VREF_TRM_TRIM_SHIFT 0 #define VREF_TRM_TRIM(x) (((uint8_t)(((uint8_t)(x))<STCTRLH) #define WDOG_STCTRLL_REG(base) ((base)->STCTRLL) #define WDOG_TOVALH_REG(base) ((base)->TOVALH) #define WDOG_TOVALL_REG(base) ((base)->TOVALL) #define WDOG_WINH_REG(base) ((base)->WINH) #define WDOG_WINL_REG(base) ((base)->WINL) #define WDOG_REFRESH_REG(base) ((base)->REFRESH) #define WDOG_UNLOCK_REG(base) ((base)->UNLOCK) #define WDOG_TMROUTH_REG(base) ((base)->TMROUTH) #define WDOG_TMROUTL_REG(base) ((base)->TMROUTL) #define WDOG_RSTCNT_REG(base) ((base)->RSTCNT) #define WDOG_PRESC_REG(base) ((base)->PRESC) /*! * @} */ /* end of group WDOG_Register_Accessor_Macros */ /* ---------------------------------------------------------------------------- -- WDOG Register Masks ---------------------------------------------------------------------------- */ /*! * @addtogroup WDOG_Register_Masks WDOG Register Masks * @{ */ /* STCTRLH Bit Fields */ #define WDOG_STCTRLH_WDOGEN_MASK 0x1u #define WDOG_STCTRLH_WDOGEN_SHIFT 0 #define WDOG_STCTRLH_CLKSRC_MASK 0x2u #define WDOG_STCTRLH_CLKSRC_SHIFT 1 #define WDOG_STCTRLH_IRQRSTEN_MASK 0x4u #define WDOG_STCTRLH_IRQRSTEN_SHIFT 2 #define WDOG_STCTRLH_WINEN_MASK 0x8u #define WDOG_STCTRLH_WINEN_SHIFT 3 #define WDOG_STCTRLH_ALLOWUPDATE_MASK 0x10u #define WDOG_STCTRLH_ALLOWUPDATE_SHIFT 4 #define WDOG_STCTRLH_DBGEN_MASK 0x20u #define WDOG_STCTRLH_DBGEN_SHIFT 5 #define WDOG_STCTRLH_STOPEN_MASK 0x40u #define WDOG_STCTRLH_STOPEN_SHIFT 6 #define WDOG_STCTRLH_WAITEN_MASK 0x80u #define WDOG_STCTRLH_WAITEN_SHIFT 7 #define WDOG_STCTRLH_TESTWDOG_MASK 0x400u #define WDOG_STCTRLH_TESTWDOG_SHIFT 10 #define WDOG_STCTRLH_TESTSEL_MASK 0x800u #define WDOG_STCTRLH_TESTSEL_SHIFT 11 #define WDOG_STCTRLH_BYTESEL_MASK 0x3000u #define WDOG_STCTRLH_BYTESEL_SHIFT 12 #define WDOG_STCTRLH_BYTESEL(x) (((uint16_t)(((uint16_t)(x))< #include #include "fsl_enet_driver.h" #ifndef MBED_NO_ENET /*! * @addtogroup phy_driver * @{ */ /*! @file*/ /******************************************************************************* * Definitions ******************************************************************************/ /*! @brief Defines the PHY return status. */ typedef enum _phy_status { kStatus_PHY_Success = 0, /*!< Success*/ kStatus_PHY_InvaildInput = 1, /*!< Invalid PHY input parameter*/ kStatus_PHY_TimeOut = 2, /*!< PHY timeout*/ kStatus_PHY_Fail = 3 /*!< PHY fail*/ } phy_status_t; /*! @brief Defines the ENET timeout.*/ typedef enum _phy_timeout { kPhyTimeout = 0x10000, /*!< ENET resets timeout.*/ } phy_timeout_t; /*! @brief Defines the PHY register.*/ typedef enum _enet_phy_register { kEnetPhyCR = 0, /*!< PHY control register */ kEnetPhySR = 1, /*!< PHY status register*/ kEnetPhyId1 = 2, /*!< PHY identification register 1*/ kEnetPhyId2 = 3, /*!< PHY identification register 2*/ kEnetPhyCt2 = 0x1e /*!< PHY control2 register*/ } enet_phy_register_t; /*! @brief Defines the control flag.*/ typedef enum _enet_phy_control { kEnetPhyAutoNeg = 0x1000,/*!< ENET PHY auto negotiation control*/ kEnetPhySpeed = 0x2000, /*! ENET PHY speed control*/ kEnetPhyLoop = 0x4000, /*!< ENET PHY loop control*/ kEnetPhyReset = 0x8000, /*!< ENET PHY reset control*/ kEnetPhy10HalfDuplex = 0x01, /*!< ENET PHY 10 M half duplex*/ kEnetPhy100HalfDuplex = 0x02,/*!< ENET PHY 100 M half duplex*/ kEnetPhy10FullDuplex = 0x05,/*!< ENET PHY 10 M full duplex*/ kEnetPhy100FullDuplex = 0x06/*!< ENET PHY 100 M full duplex*/ } enet_phy_control_t; /*! @brief Defines the PHY link speed. */ typedef enum _enet_phy_speed { kEnetSpeed10M = 0, /*!< ENET PHY 10 M speed*/ kEnetSpeed100M = 1 /*!< ENET PHY 100 M speed*/ } enet_phy_speed_t; /*! @brief Defines the PHY link duplex.*/ typedef enum _enet_phy_duplex { kEnetHalfDuplex = 0, /*!< ENET PHY half duplex*/ kEnetFullDuplex = 1 /*!< ENET PHY full duplex*/ } enet_phy_duplex_t; /*! @brief Defines the PHY status.*/ typedef enum _enet_phy_status { kEnetPhyLinkStatus = 0x4, /*!< ENET PHY link status bit*/ kEnetPhyAutoNegAble = 0x08, /*!< ENET PHY auto negotiation ability*/ kEnetPhyAutoNegComplete = 0x20, /*!< ENET PHY auto negotiation complete*/ kEnetPhySpeedDulpexMask = 0x07 /*!< ENET PHY speed mask on status register 2*/ } enet_phy_status_t; /*! @brief Defines the basic PHY application.*/ typedef struct ENETPhyApi { uint32_t (* phy_auto_discover)(enet_dev_if_t * enetIfPtr);/*!< PHY auto discover*/ uint32_t (* phy_init)(enet_dev_if_t * enetIfPtr);/*!< PHY initialize*/ uint32_t (* phy_get_link_speed)(enet_dev_if_t * enetIfPtr, enet_phy_speed_t *speed);/*!< Get PHY speed*/ uint32_t (* phy_get_link_status)(enet_dev_if_t * enetIfPtr, bool *status);/*! Get PHY link status*/ uint32_t (* phy_get_link_duplex)(enet_dev_if_t * enetIfPtr, enet_phy_duplex_t *duplex);/*!< Get PHY link duplex*/ } enet_phy_api_t; /******************************************************************************* * Global variables ******************************************************************************/ extern const enet_phy_api_t g_enetPhyApi; /******************************************************************************* * API ******************************************************************************/ #if defined(__cplusplus) extern "C" { #endif /*! * @name PHY Driver * @{ */ /*! * @brief Initializes PHY. * * @param enetIfPtr The ENET context structure. * @return The execution status. */ uint32_t phy_init(enet_dev_if_t * enetIfPtr); /*! * @brief PHY address auto discover. * * @param enetIfPtr The ENET context structure. * @return The execution status. */ uint32_t phy_auto_discover(enet_dev_if_t * enetIfPtr); /*! * @brief Gets the PHY link speed. * * @param enetIfPtr The ENET context structure. * @param status The link speed of PHY. * @return The execution status. */ uint32_t phy_get_link_speed(enet_dev_if_t * enetIfPtr, enet_phy_speed_t *status); /*! * @brief Gets the PHY link status. * * @param enetIfPtr The ENET context structure. * @param status The link on or down status of the PHY. * @return The execution status. */ uint32_t phy_get_link_status(enet_dev_if_t * enetIfPtr, bool *status); /*! * @brief Gets the PHY link duplex. * * @param enetIfPtr The ENET context structure. * @param status The link duplex status of PHY. * @return The execution status. */ uint32_t phy_get_link_duplex(enet_dev_if_t * enetIfPtr, enet_phy_duplex_t *status); /* @} */ #if defined(__cplusplus) } #endif #endif /*! @}*/ #endif /* __FSL_PHY_DRIVER_H__ */ /******************************************************************************* * EOF ******************************************************************************/ ================================================ FILE: Zelig/mbed/TARGET_K64F/TARGET_Freescale/TARGET_KPSDK_MCUS/TARGET_KPSDK_CODE/drivers/clock/fsl_clock_manager.h ================================================ /* * Copyright (c) 2013 - 2014, Freescale Semiconductor, Inc. * All rights reserved. * * Redistribution and use in source and binary forms, with or without modification, * are permitted provided that the following conditions are met: * * o Redistributions of source code must retain the above copyright notice, this list * of conditions and the following disclaimer. * * o Redistributions in binary form must reproduce the above copyright notice, this * list of conditions and the following disclaimer in the documentation and/or * other materials provided with the distribution. * * o Neither the name of Freescale Semiconductor, Inc. nor the names of its * contributors may be used to endorse or promote products derived from this * software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT 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. */ #if !defined(__FSL_CLOCK_MANAGER_H__) #define __FSL_CLOCK_MANAGER_H__ #include #include #include #include "fsl_mcg_hal.h" #include "fsl_sim_hal.h" /*! @addtogroup clock_manager*/ /*! @{*/ /*! @file*/ /******************************************************************************* * Definitions ******************************************************************************/ /* system clocks definition (should be moved to other proper place) */ #define CPU_XTAL1hz_CLK_HZ 1 #define CPU_LPO_CLK_HZ 1000 /* external clock definition (should be moved to other proper place) */ #define SDHC0_CLKIN 0 /* kSimSDHC0_CLKIN */ #define ENET_1588_CLKIN 0 /* kSimENET_1588_CLKIN */ #define EXTAL_Clock 0 /* kSimEXTAL_Clock */ #define EXTAL1_Clock 0 /* kSimEXTAL1_Clock */ #define USB_CLKIN 0 /* kSimUSB_CLKIN */ /* Table of base addresses for instances. */ extern const uint32_t g_simBaseAddr[]; extern const uint32_t g_mcgBaseAddr[]; /*! * @brief Error code definition for the clock manager APIs */ typedef enum _clock_manager_error_code { kClockManagerSuccess, /*!< success */ kClockManagerNoSuchClockName, /*!< cannot find the clock name */ kClockManagerNoSuchClockModule, /*!< cannot find the clock module name */ kClockManagerNoSuchClockSource, /*!< cannot find the clock source name */ kClockManagerNoSuchDivider, /*!< cannot find the divider name */ kClockManagerUnknown /*!< unknown error*/ } clock_manager_error_code_t; /******************************************************************************* * API ******************************************************************************/ #if defined(__cplusplus) extern "C" { #endif /* __cplusplus*/ /*! @name Clock Frequencies*/ /*@{*/ /*! * @brief Gets the clock frequency for a specific clock name. * * This function checks the current clock configurations and then calculates * the clock frequency for a specific clock name defined in clock_names_t. * The MCG must be properly configured before using this function. See * the reference manual for supported clock names for different chip families. * The returned value is in Hertz. If it cannot find the clock name * or the name is not supported for a specific chip family, it returns an * error. * * @param clockName Clock names defined in clock_names_t * @param frequency Returned clock frequency value in Hertz * @return status Error code defined in clock_manager_error_code_t */ clock_manager_error_code_t CLOCK_SYS_GetFreq(clock_names_t clockName, uint32_t *frequency); /*! * @brief Sets the clock source setting. * * This function sets the settings for a specified clock source. Each clock * source has its own clock selection settings. See the chip reference manual for * clock source detailed settings and the sim_clock_source_names_t * for clock sources. * * @param clockSource Clock source name defined in sim_clock_source_names_t * @param setting Setting value * @return status If the clock source doesn't exist, it returns an error. */ clock_manager_error_code_t CLOCK_SYS_SetSource(clock_source_names_t clockSource, uint8_t setting); /*! * @brief Gets the clock source setting. * * This function gets the settings for a specified clock source. Each clock * source has its own clock selection settings. See the reference manual for * clock source detailed settings and the sim_clock_source_names_t * for clock sources. * * @param clockSource Clock source name * @param setting Current setting for the clock source * @return status If the clock source doesn't exist, it returns an error. */ clock_manager_error_code_t CLOCK_SYS_GetSource(clock_source_names_t clockSource, uint8_t *setting); /*! * @brief Sets the clock divider setting. * * This function sets the setting for a specified clock divider. See the * reference manual for a supported clock divider and value range and the * sim_clock_divider_names_t for dividers. * * @param clockDivider Clock divider name * @param divider Divider setting * @return status If the clock divider doesn't exist, it returns an error. */ clock_manager_error_code_t CLOCK_SYS_SetDivider(clock_divider_names_t clockDivider, uint32_t setting); /*! * @brief Gets the clock divider setting. * * This function gets the setting for a specified clock divider. See the * reference manual for a supported clock divider and value range and the * clock_divider_names_t for dividers. * * @param clockDivider Clock divider name * @param divider Divider value pointer * @return status If the clock divider doesn't exist, it returns an error. */ clock_manager_error_code_t CLOCK_SYS_GetDivider(clock_divider_names_t clockDivider, uint32_t *setting); /*! * @brief Sets the clock out dividers setting. * * This function sets the setting for all clock out dividers at the same time. * See the reference manual for a supported clock divider and value range and the * clock_divider_names_t for clock out dividers. * * @param outdiv1 Outdivider1 setting * @param outdiv2 Outdivider2 setting * @param outdiv3 Outdivider3 setting * @param outdiv4 Outdivider4 setting */ static inline void CLOCK_SYS_SetOutDividers(uint32_t outdiv1, uint32_t outdiv2, uint32_t outdiv3, uint32_t outdiv4) { CLOCK_HAL_SetOutDividers(g_simBaseAddr[0], outdiv1, outdiv2, outdiv3, outdiv4); } #if defined(__cplusplus) } #endif /* __cplusplus*/ /*! @}*/ /* * Include the cpu specific clock API header files. */ #if (defined(CPU_MK02FN128VFM10) || defined(CPU_MK02FN64VFM10) || defined(CPU_MK02FN128VLF10) || \ defined(CPU_MK02FN64VLF10) || defined(CPU_MK02FN128VLH10) || defined(CPU_MK02FN64VLH10)) #define K02F12810_SERIES #elif (defined(CPU_MK20DX128VMP5) || defined(CPU_MK20DN128VMP5) || defined(CPU_MK20DX64VMP5) || \ defined(CPU_MK20DN64VMP5) || defined(CPU_MK20DX32VMP5) || defined(CPU_MK20DN32VMP5) || \ defined(CPU_MK20DX128VLH5) || defined(CPU_MK20DN128VLH5) || defined(CPU_MK20DX64VLH5) || \ defined(CPU_MK20DN64VLH5) || defined(CPU_MK20DX32VLH5) || defined(CPU_MK20DN32VLH5) || \ defined(CPU_MK20DX128VFM5) || defined(CPU_MK20DN128VFM5) || defined(CPU_MK20DX64VFM5) || \ defined(CPU_MK20DN64VFM5) || defined(CPU_MK20DX32VFM5) || defined(CPU_MK20DN32VFM5) || \ defined(CPU_MK20DX128VFT5) || defined(CPU_MK20DN128VFT5) || defined(CPU_MK20DX64VFT5) || \ defined(CPU_MK20DN64VFT5) || defined(CPU_MK20DX32VFT5) || defined(CPU_MK20DN32VFT5) || \ defined(CPU_MK20DX128VLF5) || defined(CPU_MK20DN128VLF5) || defined(CPU_MK20DX64VLF5) || \ defined(CPU_MK20DN64VLF5) || defined(CPU_MK20DX32VLF5) || defined(CPU_MK20DN32VLF5)) #define K20D5_SERIES #elif (defined(CPU_MK22FN128VDC10) || defined(CPU_MK22FN128VLH10) || defined(CPU_MK22FN128VLL10) || \ defined(CPU_MK22FN128VMP10)) #define K22F12810_SERIES /* Clock System Level API header file */ #include "MK22F12810/fsl_clock_K22F12810.h" #elif (defined(CPU_MK22FN256VDC12) || defined(CPU_MK22FN256VLH12) || defined(CPU_MK22FN256VLL12) || \ defined(CPU_MK22FN256VMP12)) #define K22F25612_SERIES /* Clock System Level API header file */ #include "MK22F25612/fsl_clock_K22F25612.h" #elif (defined(CPU_MK22FN512VDC12) || defined(CPU_MK22FN512VLH12) || defined(CPU_MK22FN512VLL12)) #define K22F51212_SERIES /* Clock System Level API header file */ #include "MK22F51212/fsl_clock_K22F51212.h" #elif (defined(CPU_MK24FN1M0VDC12) || defined(CPU_MK24FN1M0VLQ12)) #define K24F12_SERIES /* Clock System Level API header file */ #include "MK24F12/fsl_clock_K24F12.h" #elif (defined(CPU_MK24FN256VDC12)) #define K24F25612_SERIES #elif (defined(CPU_MK63FN1M0VLQ12) || defined(CPU_MK63FN1M0VMD12)) #define K63F12_SERIES /* Clock System Level API header file */ #include "MK63F12/fsl_clock_K63F12.h" #elif (defined(CPU_MK64FX512VDC12) || defined(CPU_MK64FN1M0VDC12) || defined(CPU_MK64FX512VLL12) || \ defined(CPU_MK64FN1M0VLL12) || defined(CPU_MK64FX512VLQ12) || defined(CPU_MK64FN1M0VLQ12) || \ defined(CPU_MK64FX512VMD12) || defined(CPU_MK64FN1M0VMD12)) #define K64F12_SERIES /* Clock System Level API header file */ #include "MK64F12/fsl_clock_K64F12.h" #elif (defined(CPU_MK65FN2M0CAC18) || defined(CPU_MK65FX1M0CAC18) || defined(CPU_MK65FN2M0VMI18) || \ defined(CPU_MK65FX1M0VMI18)) #define K65F18_SERIES #elif (defined(CPU_MK66FN2M0VLQ18) || defined(CPU_MK66FX1M0VLQ18) || defined(CPU_MK66FN2M0VMD18) || \ defined(CPU_MK66FX1M0VMD18)) #define K66F18_SERIES #elif (defined(CPU_MK70FN1M0VMF12) || defined(CPU_MK70FX512VMF12) || defined(CPU_MK70FN1M0VMF15) || \ defined(CPU_MK70FX512VMF15) || defined(CPU_MK70FN1M0VMJ12) || defined(CPU_MK70FX512VMJ12) || \ defined(CPU_MK70FN1M0VMJ15) || defined(CPU_MK70FX512VMJ15)) #define K70F12_SERIES #elif (defined(CPU_MK70FN1M0VMF12) || defined(CPU_MK70FX512VMF12) || defined(CPU_MK70FN1M0VMF15) || \ defined(CPU_MK70FX512VMF15) || defined(CPU_MK70FN1M0VMJ12) || defined(CPU_MK70FX512VMJ12) || \ defined(CPU_MK70FN1M0VMJ15) || defined(CPU_MK70FX512VMJ15)) #define K70F15_SERIES #elif (defined(CPU_MKL02Z32CAF4) || defined(CPU_MKL02Z8VFG4) || defined(CPU_MKL02Z16VFG4) || \ defined(CPU_MKL02Z32VFG4) || defined(CPU_MKL02Z16VFK4) || defined(CPU_MKL02Z32VFK4) || \ defined(CPU_MKL02Z16VFM4) || defined(CPU_MKL02Z32VFM4)) #define KL02Z4_SERIES #elif (defined(CPU_MKL03Z32CAF4) || defined(CPU_MKL03Z8VFG4) || defined(CPU_MKL03Z16VFG4) || \ defined(CPU_MKL03Z32VFG4) || defined(CPU_MKL03Z8VFK4) || defined(CPU_MKL03Z16VFK4) || \ defined(CPU_MKL03Z32VFK4)) #define KL03Z4_SERIES #elif (defined(CPU_MKL05Z8VFK4) || defined(CPU_MKL05Z16VFK4) || defined(CPU_MKL05Z32VFK4) || \ defined(CPU_MKL05Z8VLC4) || defined(CPU_MKL05Z16VLC4) || defined(CPU_MKL05Z32VLC4) || \ defined(CPU_MKL05Z8VFM4) || defined(CPU_MKL05Z16VFM4) || defined(CPU_MKL05Z32VFM4) || \ defined(CPU_MKL05Z16VLF4) || defined(CPU_MKL05Z32VLF4)) #define KL05Z4_SERIES #elif (defined(CPU_MKL13Z64VFM4) || defined(CPU_MKL13Z128VFM4) || defined(CPU_MKL13Z256VFM4) || \ defined(CPU_MKL13Z64VFT4) || defined(CPU_MKL13Z128VFT4) || defined(CPU_MKL13Z256VFT4) || \ defined(CPU_MKL13Z64VLH4) || defined(CPU_MKL13Z128VLH4) || defined(CPU_MKL13Z256VLH4) || \ defined(CPU_MKL13Z64VMP4) || defined(CPU_MKL13Z128VMP4) || defined(CPU_MKL13Z256VMP4)) #define KL13Z4_SERIES #elif (defined(CPU_MKL23Z64VFM4) || defined(CPU_MKL23Z128VFM4) || defined(CPU_MKL23Z256VFM4) || \ defined(CPU_MKL23Z64VFT4) || defined(CPU_MKL23Z128VFT4) || defined(CPU_MKL23Z256VFT4) || \ defined(CPU_MKL23Z64VLH4) || defined(CPU_MKL23Z128VLH4) || defined(CPU_MKL23Z256VLH4) || \ defined(CPU_MKL23Z64VMP4) || defined(CPU_MKL23Z128VMP4) || defined(CPU_MKL23Z256VMP4)) #define KL23Z4_SERIES #elif (defined(CPU_MKL25Z32VFM4) || defined(CPU_MKL25Z64VFM4) || defined(CPU_MKL25Z128VFM4) || \ defined(CPU_MKL25Z32VFT4) || defined(CPU_MKL25Z64VFT4) || defined(CPU_MKL25Z128VFT4) || \ defined(CPU_MKL25Z32VLH4) || defined(CPU_MKL25Z64VLH4) || defined(CPU_MKL25Z128VLH4) || \ defined(CPU_MKL25Z32VLK4) || defined(CPU_MKL25Z64VLK4) || defined(CPU_MKL25Z128VLK4)) #define KL25Z4_SERIES /* Clock System Level API header file */ #include "MKL25Z4/fsl_clock_KL25Z4.h" #elif (defined(CPU_MKL26Z32VFM4) || defined(CPU_MKL26Z64VFM4) || defined(CPU_MKL26Z128VFM4) || \ defined(CPU_MKL26Z32VFT4) || defined(CPU_MKL26Z64VFT4) || defined(CPU_MKL26Z128VFT4) || \ defined(CPU_MKL26Z32VLH4) || defined(CPU_MKL26Z64VLH4) || defined(CPU_MKL26Z128VLH4) || \ defined(CPU_MKL26Z256VLH4) || defined(CPU_MKL26Z256VLK4) || defined(CPU_MKL26Z128VLL4) || \ defined(CPU_MKL26Z256VLL4) || defined(CPU_MKL26Z128VMC4) || defined(CPU_MKL26Z256VMC4)) #define KL26Z4_SERIES #elif (defined(CPU_MKL33Z128VLH4) || defined(CPU_MKL33Z256VLH4) || defined(CPU_MKL33Z128VMP4) || \ defined(CPU_MKL33Z256VMP4)) #define KL33Z4_SERIES #elif (defined(CPU_MKL43Z64VLH4) || defined(CPU_MKL43Z128VLH4) || defined(CPU_MKL43Z256VLH4) || \ defined(CPU_MKL43Z64VMP4) || defined(CPU_MKL43Z128VMP4) || defined(CPU_MKL43Z256VMP4)) #define KL43Z4_SERIES #elif (defined(CPU_MKL46Z128VLH4) || defined(CPU_MKL46Z256VLH4) || defined(CPU_MKL46Z128VLL4) || \ defined(CPU_MKL46Z256VLL4) || defined(CPU_MKL46Z128VMC4) || defined(CPU_MKL46Z256VMC4)) #define KL46Z4_SERIES #elif (defined(CPU_MKV30F128VFM10) || defined(CPU_MKV30F64VFM10) || defined(CPU_MKV30F128VLF10) || \ defined(CPU_MKV30F64VLF10) || defined(CPU_MKV30F128VLH10) || defined(CPU_MKV30F64VLH10)) #define KV30F12810_SERIES #elif (defined(CPU_MKV31F128VLH10) || defined(CPU_MKV31F128VLL10)) #define KV31F12810_SERIES /* Clock System Level API header file */ #include "MKV31F12810/fsl_clock_KV31F12810.h" #elif (defined(CPU_MKV31F256VLH12) || defined(CPU_MKV31F256VLL12)) #define KV31F25612_SERIES /* Clock System Level API header file */ #include "MKV31F25612/fsl_clock_KV31F25612.h" #elif (defined(CPU_MKV31F512VLH12) || defined(CPU_MKV31F512VLL12)) #define KV31F51212_SERIES /* Clock System Level API header file */ #include "MKV31F51212/fsl_clock_KV31F51212.h" #elif (defined(CPU_MKV40F128VLH15) || defined(CPU_MKV40F128VLL15) || defined(CPU_MKV40F256VLH15) || \ defined(CPU_MKV40F256VLL15) || defined(CPU_MKV40F64VLH15)) #define KV40F15_SERIES #elif (defined(CPU_MKV43F128VLH15) || defined(CPU_MKV43F128VLL15) || defined(CPU_MKV43F64VLH15)) #define KV43F15_SERIES #elif (defined(CPU_MKV44F128VLH15) || defined(CPU_MKV44F128VLL15) || defined(CPU_MKV44F64VLH15)) #define KV44F15_SERIES #elif (defined(CPU_MKV45F128VLH15) || defined(CPU_MKV45F128VLL15) || defined(CPU_MKV45F256VLH15) || \ defined(CPU_MKV45F256VLL15)) #define KV45F15_SERIES #elif (defined(CPU_MKV46F128VLH15) || defined(CPU_MKV46F128VLL15) || defined(CPU_MKV46F256VLH15) || \ defined(CPU_MKV46F256VLL15)) #define KV46F15_SERIES #else #error "No valid CPU defined!" #endif #endif /* __FSL_CLOCK_MANAGER_H__*/ /******************************************************************************* * EOF ******************************************************************************/ ================================================ FILE: Zelig/mbed/TARGET_K64F/TARGET_Freescale/TARGET_KPSDK_MCUS/TARGET_KPSDK_CODE/drivers/enet/fsl_enet_driver.h ================================================ /* * Copyright (c) 2013 - 2014, Freescale Semiconductor, Inc. * All rights reserved. * * Redistribution and use in source and binary forms, with or without modification, * are permitted provided that the following conditions are met: * * o Redistributions of source code must retain the above copyright notice, this list * of conditions and the following disclaimer. * * o Redistributions in binary form must reproduce the above copyright notice, this * list of conditions and the following disclaimer in the documentation and/or * other materials provided with the distribution. * * o Neither the name of Freescale Semiconductor, Inc. nor the names of its * contributors may be used to endorse or promote products derived from this * software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT 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. */ #ifndef __FSL_ENET_DRIVER_H__ #define __FSL_ENET_DRIVER_H__ #include #include #include "fsl_enet_hal.h" #include "fsl_os_abstraction.h" #ifndef MBED_NO_ENET /*! * @addtogroup enet_driver * @{ */ /******************************************************************************* * Definitions ******************************************************************************/ /*! @brief Defines the approach: ENET interrupt handler do receive */ #define ENET_RECEIVE_ALL_INTERRUPT 0 /*! @brief Defines the statistic enable macro.*/ #define ENET_ENABLE_DETAIL_STATS 0 /*! @brief Defines the alignment operation.*/ #define ENET_ALIGN(x,align) ((unsigned int)((x) + ((align)-1)) & (unsigned int)(~(unsigned int)((align)- 1))) #if FSL_FEATURE_ENET_SUPPORT_PTP /*! @brief Defines the PTP IOCTL macro.*/ typedef enum _enet_ptp_ioctl { kEnetPtpGetRxTimestamp = 0, /*!< ENET PTP gets receive timestamp*/ kEnetPtpGetTxTimestamp, /*!< ENET PTP gets transmit timestamp*/ kEnetPtpGetCurrentTime, /*!< ENET PTP gets current time*/ kEnetPtpSetCurrentTime, /*!< ENET PTP sets current time*/ kEnetPtpFlushTimestamp, /*!< ENET PTP flushes timestamp*/ kEnetPtpCorrectTime, /*!< ENET PTP time correction*/ kEnetPtpSendEthernetPtpV2, /*!< ENET PTPv2 sends Ethernet frame*/ kEnetPtpReceiveEthernetPtpV2 /*!< ENET PTPv2 receives with Ethernet frame*/ } enet_ptp_ioctl_t; /*! @brief Defines the PTP message buffer number.*/ typedef enum _enet_ptp_buffer_number { kEnetPtpL2bufferNumber = 10, /*!< PTP layer2 frame buffer number*/ kEnetPtpRingNumber = 25 /*!< PTP Ring buffer number*/ } enet_ptp_buffer_number_t; /*! @brief Defines the ENET PTP message related constant.*/ typedef enum _enet_ptp_event_type { kEnetPtpSourcePortIdLen = 10, /*!< PTP message sequence id length*/ kEnetPtpEventMsgType = 3, /*!< PTP event message type*/ kEnetPtpEventPort = 319, /*!< PTP event port number*/ kEnetPtpGnrlPort = 320 /*!< PTP general port number*/ } enet_ptp_event_type_t; /*! @brief Defines all ENET PTP content offsets in the IPv4 PTP UDP/IP multicast message.*/ typedef enum _enet_ipv4_ptp_content_offset { kEnetPtpIpVersionOffset = 0xe, /*!< IPv4 PTP message IP version offset*/ kEnetPtpUdpProtocolOffset = 0x17,/*!< IPv4 PTP message UDP protocol offset*/ kEnetPtpUdpPortOffset = 0x24, /*!< IPv4 PTP message UDP port offset*/ kEnetPtpUdpMsgTypeOffset = 0x2a, /*!< IPv4 PTP message UDP message type offset*/ kEnetPtpUdpVersionoffset = 0x2b, /*!< IPv4 PTP message UDP version offset*/ kEnetPtpUdpClockIdOffset = 0x3e, /*!< IPv4 PTP message UDP clock id offset*/ kEnetPtpUdpSequenIdOffset = 0x48,/*!< IPv4 PTP message UDP sequence id offset*/ kEnetPtpUdpCtlOffset = 0x4a /*!< IPv4 PTP message UDP control offset*/ } enet_ipv4_ptp_content_offset_t; /*! @brief Defines all ENET PTP content offset in THE IPv6 PTP UDP/IP multicast message.*/ typedef enum _enet_ipv6_ptp_content_offset { kEnetPtpIpv6UdpProtocolOffset = 0x14, /*!< IPv6 PTP message UDP protocol offset*/ kEnetPtpIpv6UdpPortOffset = 0x38, /*!< IPv6 PTP message UDP port offset*/ kEnetPtpIpv6UdpMsgTypeOffset = 0x3e, /*!< IPv6 PTP message UDP message type offset*/ kEnetPtpIpv6UdpVersionOffset = 0x3f, /*!< IPv6 PTP message UDP version offset*/ kEnetPtpIpv6UdpClockIdOffset = 0x52, /*!< IPv6 PTP message UDP clock id offset*/ kEnetPtpIpv6UdpSequenceIdOffset = 0x5c,/*!< IPv6 PTP message UDP sequence id offset*/ kEnetPtpIpv6UdpCtlOffset = 0x5e /*!< IPv6 PTP message UDP control offset*/ } enet_ipv6_ptp_content_offset_t; /*! @brief Defines all ENET PTP content offset in the PTP Layer2 Ethernet message.*/ typedef enum _enet_ethernet_ptp_content_offset { kEnetPtpEtherPktTypeOffset = 0x0c, /*!< PTPv2 message Ethernet packet type offset*/ kEnetPtpEtherMsgTypeOffset = 0x0e, /*!< PTPv2 message Ethernet message type offset*/ kEnetPtpEtherVersionOffset = 0x0f, /*!< PTPv2 message Ethernet version type offset*/ kEnetPtpEtherClockIdOffset = 0x22, /*!< PTPv2 message Ethernet clock id offset*/ kEnetPtpEtherSequenceIdOffset = 0x2c,/*!< PTPv2 message Ethernet sequence id offset*/ kEnetPtpEtherCtlOffset = 0x2e /*!< PTPv2 message Ethernet control offset*/ } enet_ethernet_ptp_content_offset_t; /*! @brief Defines the 1588 timer parameters.*/ typedef enum _enet_ptp_timer_wrap_period { kEnetPtpAtperVaule = 1000000000, /*!< PTP timer wrap around one second */ kEnetBaseIncreaseUnit = 2 /*!< PTP timer adjusts clock and increases value to 2*/ } enet_ptp_timer_wrap_period_t; #endif /*! @brief Defines the interrupt source index for the interrupt vector change table.*/ typedef enum _enet_interrupt_number { kEnetTstimerInt = 0, /*!< Timestamp interrupt*/ kEnetTsAvailInt, /*!< TS-avail interrupt*/ kEnetWakeUpInt, /*!< Wakeup interrupt*/ kEnetPlrInt, /*!< Plr interrupt*/ kEnetUnInt, /*!< Un interrupt*/ kEnetRlInt, /*!< RL interrupt*/ kEnetLcInt, /*!< LC interrupt*/ kEnetEberrInt, /*!< Eberr interrupt*/ kEnetMiiInt, /*!< MII interrupt*/ kEnetRxbInt , /*!< Receive byte interrupt*/ kEnetRxfInt, /*!< Receive frame interrupt*/ kEnetTxbInt, /*!< Transmit byte interrupt*/ kEnetTxfInt, /*!< Transmit frame interrupt*/ kEnetGraInt, /*!< Gra interrupt*/ kEnetBabtInt, /*!< Babt interrupt*/ kEnetBabrInt, /*!< Babr interrupt*/ kEnetIntNum /*!< Interrupt number*/ } enet_interrupt_number_t; /*! @brief Defines the ENET main constant.*/ typedef enum _enet_frame_max { kEnetMaxTimeout = 0x10000, /*!< Maximum timeout*/ kEnetMaxFrameSize = 1518, /*!< Maximum frame size*/ kEnetMaxFrameVlanSize = 1522, /*!< Maximum VLAN frame size*/ kEnetMaxFrameDateSize = 1500, /*!< Maximum frame data size*/ kEnetMaxFrameBdNumbers = 7, /*!< Maximum buffer descriptor numbers of a frame*/ kEnetFrameFcsLen = 4, /*!< FCS length*/ kEnetEthernetHeadLen = 14 /*!< Ethernet Frame header length*/ } enet_frame_max_t; /*! @brief Defines the CRC data for a hash value calculation.*/ typedef enum _enet_crc_parameter { kEnetCrcData = 0xFFFFFFFFU, /*!< CRC-32 maximum data */ kEnetCrcOffset = 8, /*!< CRC-32 offset2*/ kEnetCrcMask1 = 0x3F /*!< CRC-32 mask*/ } enet_crc_parameter_t; /*! @brief Defines the ENET protocol type and main parameters.*/ typedef enum _enet_protocol_type { kEnetProtocolIeee8023 = 0x88F7, /*!< Packet type Ethernet ieee802.3*/ kEnetProtocolIpv4 = 0x0800, /*!< Packet type IPv4*/ kEnetProtocolIpv6 = 0x86dd, /*!< Packet type IPv6*/ kEnetProtocol8021QVlan = 0x8100, /*!< Packet type VLAN*/ kEnetPacketUdpVersion = 0x11, /*!< UDP protocol type*/ kEnetPacketIpv4Version = 0x4, /*!< Packet IP version IPv4*/ kEnetPacketIpv6Version = 0x6 /*!< Packet IP version IPv6*/ } enet_protocol_type_t; /*! @brief Defines the ENET MAC control Configure*/ typedef enum _enet_mac_control_flag { kEnetSleepModeEnable = 0x1, /*!< ENET control sleep mode Enable*/ kEnetPayloadlenCheckEnable = 0x2, /*!< ENET receive payload length check Enable*/ kEnetRxFlowControlEnable = 0x4, /*!< ENET flow control, receiver detects PAUSE frames and stops transmitting data when a PAUSE frame is detected*/ kEnetRxCrcFwdEnable = 0x8, /*!< Received frame crc is stripped from the frame*/ kEnetRxPauseFwdEnable = 0x10,/*!< Pause frames are forwarded to the user application*/ kEnetRxPadRemoveEnable = 0x20, /*!< Padding is removed from received frames*/ kEnetRxBcRejectEnable = 0x40, /*!< Broadcast frame reject*/ kEnetRxPromiscuousEnable = 0x80, /*!< Promiscuous mode enabled*/ kEnetRxMiiLoopback = 0x100, /*!< MAC MII loopback mode*/ } enet_mac_control_flag_t; /*! @brief Defines the multicast group structure for the ENET device. */ typedef struct ENETMulticastGroup { enetMacAddr groupAdddr; /*!< Multicast group address*/ uint32_t hash; /*!< Hash value of the multicast group address*/ struct ENETMulticastGroup *next; /*!< Pointer of the next group structure*/ struct ENETMulticastGroup *prv; /*!< Pointer of the previous structure*/ } enet_multicast_group_t; /*! @brief Defines the receive buffer descriptor configure structure.*/ typedef struct ENETRxBdConfig { uint8_t *rxBdPtrAlign; /*!< Aligned receive buffer descriptor pointer */ uint8_t *rxBufferAlign; /*!< Aligned receive data buffer pointer */ uint8_t *rxLargeBufferAlign; /*!< Aligned receive large data buffer pointer*/ uint8_t rxBdNum; /*!< Aligned receive buffer descriptor pointer*/ uint8_t rxBufferNum; /*!< Receive buffer number*/ uint8_t rxLargeBufferNum; /*!< Large receive buffer number*/ uint32_t rxLargeBufferSizeAlign; /*!< Aligned large receive buffer size*/ }enet_rxbd_config_t; /*! @brief Defines the transmit buffer descriptor configure structure.*/ typedef struct ENETTxBdConfig { uint8_t *txBdPtrAlign; /*!< Aligned transmit buffer descriptor pointer*/ uint8_t *txBufferAlign; /*!< Aligned transmit buffer descriptor pointer*/ uint8_t txBufferNum; /*!< Transmit buffer number*/ uint32_t txBufferSizeAlign; /*!< Aligned transmit buffer size*/ }enet_txbd_config_t; /*! @brief Defines the basic configuration structure for the ENET device.*/ typedef struct ENETMacConfig { uint16_t rxBufferSize; /*!< Receive buffer size*/ uint16_t rxLargeBufferNumber; /*!< Receive large buffer number; Needed only when the BD size is smaller than the maximum frame length.*/ uint16_t rxBdNumber; /*!< Receive buffer descriptor number*/ uint16_t txBdNumber; /*!< Transmit buffer descriptor number*/ enetMacAddr macAddr; /*!< MAC hardware address*/ enet_config_rmii_t rmiiCfgMode;/*!< RMII configure mode*/ enet_config_speed_t speed; /*!< Speed configuration*/ enet_config_duplex_t duplex; /*!< Duplex configuration*/ /*!< Mac control configure, it is recommended to use enet_mac_control_flag_t it is special control set for loop mode, sleep mode, crc forward/terminate etc*/ uint32_t macCtlConfigure; bool isTxAccelEnabled;/*!< Switcher to enable transmit accelerator*/ bool isRxAccelEnabled;/*!< Switcher to enable receive accelerator*/ bool isStoreAndFwEnabled; /*!< Switcher to enable store and forward*/ enet_config_rx_accelerator_t rxAcceler; /*!< Receive accelerator configure*/ enet_config_tx_accelerator_t txAcceler; /*!< Transmit accelerator configure*/ bool isVlanEnabled; /*!< Switcher to enable VLAN frame*/ bool isPhyAutoDiscover;/*!< Switcher to use PHY auto discover*/ uint32_t miiClock; /*!< MII speed*/ #if FSL_FEATURE_ENET_SUPPORT_PTP uint16_t ptpRingBufferNumber; /*!< PTP ring buffer number*/ bool isSlaveModeEnabled; /*!< PTP timer configuration*/ #endif } enet_mac_config_t; /*! @brief Defines the basic configuration for PHY.*/ typedef struct ENETPhyConfig { uint8_t phyAddr; /*!< PHY address*/ bool isLoopEnabled; /*!< Switcher to enable the HY loop mode*/ } enet_phy_config_t; #if FSL_FEATURE_ENET_SUPPORT_PTP /*! @brief Defines the ENET Mac PTP timestamp structure.*/ typedef struct ENETMacPtpTime { uint64_t second; /*!< Second*/ uint32_t nanosecond; /*!< Nanosecond*/ } enet_mac_ptp_time_t; /*! @brief Defines the ENET PTP timer drift structure.*/ typedef struct ENETPtpDrift { int32_t drift; /*!< Drift for the PTP timer to adjust*/ } enet_ptp_drift_t; /*! @brief Defines the ENET MAC PTP time parameter.*/ typedef struct ENETPtpMasterTimeData { uint8_t masterPtpInstance;/*!< PTP master timer instance*/ uint64_t second; /*!< PTP master timer second */ } enet_ptp_master_time_data_t; /*! @brief Defines the structure for the ENET PTP message data and timestamp data.*/ typedef struct ENETMacPtpTsData { uint8_t version; /*!< PTP version*/ uint8_t sourcePortId[kEnetPtpSourcePortIdLen];/*!< PTP source port ID*/ uint16_t sequenceId; /*!< PTP sequence ID*/ uint8_t messageType; /*!< PTP message type*/ enet_mac_ptp_time_t timeStamp;/*!< PTP timestamp*/ } enet_mac_ptp_ts_data_t; /*! @brief Defines the ENET PTP ring buffer structure for the PTP message timestamp store.*/ typedef struct ENETMacPtpTsRing { uint32_t front; /*!< The first index of the ring*/ uint32_t end; /*!< The end index of the ring*/ uint32_t size; /*!< The size of the ring*/ enet_mac_ptp_ts_data_t *ptpTsDataPtr;/*!< PTP message data structure*/ } enet_mac_ptp_ts_ring_t; /*! @brief Defines the ENET packet for the PTP version2 message using the layer2 Ethernet frame.*/ typedef struct ENETPtpL2packet { uint8_t packet[kEnetMaxFrameDateSize]; /*!< Buffer for ptpv2 message*/ uint16_t length; /*!< PTP message length*/ } enet_ptp_l2packet_t; /*! @brief Defines the ENET PTPv2 packet queue using the layer2 Ethernet frame.*/ typedef struct ENETPtpL2queue { enet_ptp_l2packet_t l2Packet[kEnetPtpL2bufferNumber]; /*!< PTP layer2 packet*/ uint16_t writeIdex; /*!< Queue write index*/ uint16_t readIdx; /*!< Queue read index*/ } enet_ptp_l2queue_t; /*! @brief Defines the ENET PTP layer2 Ethernet frame structure.*/ typedef struct ENETPtpL2Ethernet { uint8_t *ptpMsg; /*!< PTP message*/ uint16_t length; /*!< Length of the PTP message*/ enetMacAddr hwAddr; /*!< Destination hardware address*/ } enet_ptp_l2_ethernet_t; /*! @brief Defines the ENET PTP buffer structure for all 1588 data.*/ typedef struct ENETPrivatePtpBuffer { enet_mac_ptp_ts_ring_t rxTimeStamp;/*!< Data structure for receive message*/ enet_mac_ptp_ts_ring_t txTimeStamp;/*!< Data structure for transmit timestamp*/ enet_ptp_l2queue_t *l2QueuePtr; /*!< Data structure for layer2 Ethernet queue*/ uint64_t masterSecond; /*!< PTP time second when it's master time*/ } enet_private_ptp_buffer_t; #endif /*! @brief Defines the ENET header structure. */ typedef struct ENETEthernetHeader { enetMacAddr destAddr; /*!< Destination address */ enetMacAddr sourceAddr;/*!< Source address*/ uint16_t type; /*!< Protocol type*/ } enet_ethernet_header_t; /*! @brief Defines the ENET VLAN frame header structure. */ typedef struct ENET8021vlanHeader { enetMacAddr destAddr; /*!< Destination address */ enetMacAddr sourceAddr;/*!< Source address*/ uint16_t tpidtag; /*!< ENET 8021tag header tag region*/ uint16_t othertag; /*!< ENET 8021tag header type region*/ uint16_t type; /*!< Protocol type*/ } enet_8021vlan_header_t; /*! @brief Defines the ENET MAC context structure for the buffer address, buffer descriptor address, etc.*/ typedef struct ENETMacContext { uint8_t *rxBufferPtr; /*!< Receive buffer pointer*/ uint8_t *rxLargeBufferPtr; /*!< Receive large buffer descriptor*/ uint8_t *txBufferPtr; /*!< Transmit buffer pointer*/ uint8_t *rxBdBasePtr; /*!< Receive buffer descriptor base address pointer*/ uint8_t *rxBdCurPtr; /*!< Current receive buffer descriptor pointer*/ uint8_t *rxBdDirtyPtr; /*!< Receive dirty buffer descriptor*/ uint8_t *txBdBasePtr; /*!< Transmit buffer descriptor base address pointer*/ uint8_t *txBdCurPtr; /*!< Current transmit buffer descriptor pointer*/ uint8_t *txBdDirtyPtr; /*!< Last cleaned transmit buffer descriptor pointer*/ bool isTxFull; /*!< Transmit buffer descriptor full*/ bool isRxFull; /*!< Receive buffer descriptor full*/ uint32_t bufferdescSize; /*!< ENET buffer descriptor size*/ uint16_t rxBufferSizeAligned; /*!< Receive buffer alignment size*/ #if FSL_FEATURE_ENET_SUPPORT_PTP enet_private_ptp_buffer_t privatePtp;/*!< PTP private buffer*/ #endif } enet_mac_context_t; /*! @brief Defines the ENET packets statistic structure.*/ typedef struct ENETMacStats { uint32_t statsRxTotal; /*!< Total number of receive packets*/ uint32_t statsRxMissed; /*!< Total number of receive packets*/ uint32_t statsRxDiscard; /*!< Receive discarded with error */ uint32_t statsRxError; /*!< Receive discarded with error packets*/ uint32_t statsTxTotal; /*!< Total number of transmit packets*/ uint32_t statsTxMissed; /*!< Transmit missed*/ uint32_t statsTxDiscard; /*!< Transmit discarded with error */ uint32_t statsTxError; /*!< Transmit error*/ uint32_t statsRxAlign; /*!< Receive non-octet alignment*/ uint32_t statsRxFcs; /*!< Receive CRC error*/ uint32_t statsRxTruncate;/*!< Receive truncate*/ uint32_t statsRxLengthGreater; /*!< Receive length greater than RCR[MAX_FL] */ uint32_t statsRxCollision; /*!< Receive collision*/ uint32_t statsRxOverRun; /*!< Receive over run*/ uint32_t statsTxOverFlow; /*!< Transmit overflow*/ uint32_t statsTxLateCollision; /*!< Transmit late collision*/ uint32_t statsTxExcessCollision;/*!< Transmit excess collision*/ uint32_t statsTxUnderFlow; /*!< Transmit under flow*/ uint32_t statsTxLarge; /*!< Transmit large packet*/ uint32_t statsTxSmall; /*!< Transmit small packet*/ } enet_stats_t; /*! @brief Defines the ENET MAC packet buffer structure.*/ typedef struct ENETMacPacketBuffer { uint8_t *data; uint16_t length; } enet_mac_packet_buffer_t; #if ENET_RECEIVE_ALL_INTERRUPT typedef uint32_t (* enet_netif_callback_t)(void *enetPtr, enet_mac_packet_buffer_t *packetBuffer); #endif /*! @brief Defines the ENET device data structure for the ENET.*/ typedef struct ENETDevIf { struct ENETDevIf *next; /*!< Next device structure address*/ void *netIfPtr; /*!< Store the connected upper layer in the structure*/ #if ENET_RECEIVE_ALL_INTERRUPT void *enetNetifService; /*!< Service function*/ #endif enet_multicast_group_t *multiGroupPtr; /*!< Multicast group chain*/ uint32_t deviceNumber; /*!< Device number*/ bool isInitialized; /*!< Device initialized*/ uint16_t maxFrameSize; /*!< MAC maximum frame size*/ enet_mac_config_t *macCfgPtr;/*!< MAC configuration structure*/ enet_phy_config_t *phyCfgPtr;/*!< PHY configuration structure*/ const struct ENETMacApi *macApiPtr; /*!< MAC application interface structure*/ void *phyApiPtr; /*!< PHY application interface structure*/ enet_mac_context_t *macContextPtr; /*!< MAC context pointer*/ #if ENET_ENABLE_DETAIL_STATS enet_stats_t stats; /*!< Packets statistic*/ #endif #if ENET_RECEIVE_ALL_INTERRUPT enet_netif_callback_t enetNetifcall; /*!< Receive callback function to the upper layer*/ #else event_object_t enetReceiveSync; /*!< Receive sync signal*/ #endif lock_object_t enetContextSync; /*!< Sync signal*/ } enet_dev_if_t; /*! @brief Defines the basic application for the ENET device.*/ typedef struct ENETMacApi { uint32_t (* enet_mac_init)(enet_dev_if_t * enetIfPtr, enet_rxbd_config_t *rxbdCfg, enet_txbd_config_t *txbdCfg);/*!< MAC initialize interface*/ uint32_t (* enet_mac_deinit)(enet_dev_if_t * enetIfPtr);/*!< MAC close interface*/ uint32_t (* enet_mac_send)(enet_dev_if_t * enetIfPtr, uint8_t *packet, uint32_t size);/*!< MAC send packets*/ #if !ENET_RECEIVE_ALL_INTERRUPT uint32_t (* enet_mac_receive)(enet_dev_if_t * enetIfPtr, enet_mac_packet_buffer_t *packBuffer);/*!< MAC receive interface*/ #endif uint32_t (* enet_mii_read)(uint32_t instance, uint32_t phyAddr, uint32_t phyReg, uint32_t *dataPtr);/*!< MII reads PHY*/ uint32_t (* enet_mii_write)(uint32_t instance, uint32_t phyAddr, uint32_t phyReg, uint32_t data);/*!< MII writes PHY*/ uint32_t (* enet_add_multicast_group)(uint32_t instance, enet_multicast_group_t *multiGroupPtr, uint8_t *groupAddr);/*!< Add multicast group*/ uint32_t (* enet_leave_multicast_group)(uint32_t instance, enet_multicast_group_t *multiGroupPtr, uint8_t *groupAddr);/*!< Leave multicast group*/ } enet_mac_api_t; /******************************************************************* * Global variables ***********************************************************************/ extern const enet_mac_api_t g_enetMacApi; /******************************************************************************* * API ******************************************************************************/ #if defined(__cplusplus) extern "C" { #endif /*! * @name ENET Driver * @{ */ #if FSL_FEATURE_ENET_SUPPORT_PTP /*! * @brief Initializes the ENET PTP context structure with the basic configuration. * * @param macContextPtr The pointer to the ENET MAC macContext structure. * @return The execution status. */ uint32_t enet_ptp_init(enet_private_ptp_buffer_t *privatePtpPtr, uint32_t ptpRxBufferNum, enet_mac_ptp_ts_data_t *ptpTsRxDataPtr, uint32_t ptpTxBufferNum, enet_mac_ptp_ts_data_t *ptpTsTxDataPtr); /*! * @brief Initializes the ENET PTP timer with the basic configuration. * * After the PTP starts, the 1588 timer also starts running. If the user wants the 1588 timer * as the slave, enable the isSlaveEnabled flag. * * @param instance The ENET instance number. * @param ptpCfgPtr The pointer to the basic PTP timer configuration structure. * @return The execution status. */ uint32_t enet_ptp_start(uint32_t instance, bool isSlaveEnabled); /*! * @brief Parses the ENET packet. * * Parses the ENET message and checks if it is a PTP message. If it is a PTP message, * the message is stored in the PTP information structure. Message parsing * decides whether timestamp processing is done after that. * * @param packet The ENET packet. * @param ptpTsPtr The pointer to the PTP data structure. * @param isPtpMsg The PTP message flag. * @param isFastEnabled The fast operation flag. If set, only check if it is a ptp message * and doesn't store any ptp message. * @return The execution status. */ uint32_t enet_ptp_parse(uint8_t *packet, enet_mac_ptp_ts_data_t *ptpTsPtr, bool *isPtpMsg, bool isFastEnabled); /*! * @brief Gets the current value of the ENET PTP time. * * @param ptpTimerPtr The PTP timer structure. * @return The execution status. */ uint32_t enet_ptp_get_time(enet_mac_ptp_time_t *ptpTimerPtr); /*! * @brief Sets the current value of the ENET PTP time. * * @param ptpTimerPtr The PTP timer structure. * @return The execution status. */ uint32_t enet_ptp_set_time(enet_mac_ptp_time_t *ptpTimerPtr); /*! * @brief Adjusts the ENET PTP time. * * @param instance The ENET instance number. * @param drift The PTP timer drift value. * @return The execution status. */ uint32_t enet_ptp_correction_time(uint32_t instance, int32_t drift); /*! * @brief Stores the transmit timestamp. * * @param ptpBuffer The PTP buffer pointer. * @param bdPtr The current transmit buffer descriptor. * @return The execution status. */ uint32_t enet_ptp_store_tx_timestamp(enet_private_ptp_buffer_t *ptpBuffer,void *bdPtr); /*! * @brief Stores receive timestamp. * * @param ptpBuffer The PTP buffer pointer. * @param packet The current receive packet. * @param bdPtr The current receive buffer descriptor. * @return The execution status. */ uint32_t enet_ptp_store_rx_timestamp(enet_private_ptp_buffer_t *ptpBuffer, uint8_t *packet, void *bdPtr); /*! * @brief Initializes the buffer queue for the PTP layer2 Ethernet packets. * * @param ptpBuffer The PTP buffer pointer. * @return The execution status. */ uint32_t enet_ptp_l2queue_init(enet_private_ptp_buffer_t *ptpBuffer, enet_ptp_l2queue_t *ptpL2QuePtr); /*! * @brief Adds the PTP layer2 Ethernet packet to the PTP Ethernet packet queue. * * @param ptpQuePtr The ENET private ptp layer2 buffer queue structure pointer. * @param packet The packet buffer pointer. * @param length The packet length. * @return The execution status. */ uint32_t enet_ptp_service_l2packet(enet_ptp_l2queue_t * ptpQuePtr, uint8_t *packet, uint16_t length); /*! * @brief Sends the PTP layer2 Ethernet packet to the Net. * * @param enetIfPtr The ENET context structure. * @param paramPtr The buffer from upper layer. * @return The execution status. */ uint32_t enet_ptp_send_l2packet(enet_dev_if_t * enetIfPtr, void *paramPtr); /*! * @brief Receives the PTP layer2 Ethernet packet from the Net. * * @param enetIfPtr The ENET context structure. * @param paramPtr The buffer receive from net and will send to upper layer. * @return The execution status. */ uint32_t enet_ptp_receive_l2packet(enet_dev_if_t * enetIfPtr,void *paramPtr); /*! * @brief Provides the handler for the 1588 stack to do PTP IOCTL. * * @param enetIfPtr The ENET context structure. * @param commandId The command id. * @param inOutPtr The data buffer. * @return The execution status. */ uint32_t enet_ptp_ioctl(enet_dev_if_t * enetIfPtr, uint32_t commandId, void *inOutPtr); /*! * @brief Stops the ENET PTP timer. * * @param instance The ENET instance number. * @return The execution status. */ uint32_t enet_ptp_stop(uint32_t instance); /*! * @brief Checks whether the PTP ring buffer is full. * * @param ptpTsRingPtr The ENET PTP timestamp ring. * @return True if the PTP ring buffer is full. Otherwise, false. */ bool enet_ptp_ring_is_full(enet_mac_ptp_ts_ring_t *ptpTsRingPtr); /*! * @brief Updates the latest ring buffers. * * Adds the PTP message data to the PTP ring buffers and increases the * PTP ring buffer index. * * @param ptpTsRingPtr The ENET PTP timestamp ring. * @param data The PTP data buffer. * @return The execution status. */ uint32_t enet_ptp_ring_update(enet_mac_ptp_ts_ring_t *ptpTsRingPtr, enet_mac_ptp_ts_data_t *data); /*! * @brief Searches the element in ring buffers with the message ID and Clock ID. * * @param ptpTsRingPtr The ENET PTP timestamp ring. * @param data The PTP data buffer. * @return The execution status. */ uint32_t enet_ptp_ring_search(enet_mac_ptp_ts_ring_t *ptpTsRingPtr, enet_mac_ptp_ts_data_t *data); /*! * @brief Calculates the ENET PTP ring buffer index. * * @param size The ring size. * @param curIdx The current ring index. * @param offset The offset index. * @return The execution status. */ static inline uint32_t enet_ptp_ring_index(uint32_t size, uint32_t curIdx, uint32_t offset) { return ((curIdx + offset) % size); } /*! * @brief Frees all ring buffers. * * @param enetContextPtr The ENET MAC context buffer. * @return The execution status. */ uint32_t enet_ptp_deinit(enet_mac_context_t *enetContextPtr); /*! * @brief The ENET PTP time interrupt handler. * * @param enetIfPtr The ENET context structure pointer. */ void enet_mac_ts_isr(void *enetIfPtr); #endif /*! * @brief(R)MII Read function. * * @param instance The ENET instance number. * @param phyAddr The PHY address. * @param phyReg The PHY register. * @param dataPtr The data read from MII. * @return The execution status. */ uint32_t enet_mii_read(uint32_t instance, uint32_t phyAddr, uint32_t phyReg, uint32_t *dataPtr); /*! * @brief(R)MII Read function. * * @param instance The ENET instance number. * @param phyAddr The PHY address. * @param phyReg The PHY register. * @param data The data write to MII. * @return The execution status. */ uint32_t enet_mii_write(uint32_t instance, uint32_t phyAddr, uint32_t phyReg, uint32_t data); /*! * @brief Initializes ENET buffer descriptors. * * @param enetIfPtr The ENET context structure. * @return The execution status. */ uint32_t enet_mac_bd_init(enet_dev_if_t * enetIfPtr); /*! * @brief Initializes the ENET MAC MII(MDC/MDIO) interface. * * @param enetIfPtr The ENET context structure. * @return The execution status. */ uint32_t enet_mac_mii_init(enet_dev_if_t * enetIfPtr); /*! * @brief Initialize the ENET receive buffer descriptors. * * If you open ENET_RECEIVE_ALL_INTERRUPT to do receive * data buffer numbers can be the same as the receive descriptor numbers. * But if you close ENET_RECEIVE_ALL_INTERRUPT and choose polling receive * frames please make sure the receive data buffers are more than * buffer descriptor numbers to guarantee a good performance. * * @param enetIfPtr The ENET context structure. * @param rxbdCfg The receive buffer descriptor configuration. * @return The execution status. */ uint32_t enet_mac_rxbd_init(enet_dev_if_t * enetIfPtr, enet_rxbd_config_t *rxbdCfg); /*! * @brief Deinitialize the ENET receive buffer descriptors. * * Deinitialize the ENET receive buffer descriptors. * * @param enetIfPtr The ENET context structure. * @return The execution status. */ uint32_t enet_mac_rxbd_deinit(enet_dev_if_t * enetIfPtr); /*! * @brief Initialize the ENET transmit buffer descriptors. * * @param enetIfPtr The ENET context structure. * @param txbdCfg The transmit buffer descriptor configuration. * @return The execution status. */ uint32_t enet_mac_txbd_init(enet_dev_if_t * enetIfPtr, enet_txbd_config_t *txbdCfg); /*! * @brief Deinitialize the ENET transmit buffer descriptors. * * Deinitialize the ENET transmit buffer descriptors. * * @param enetIfPtr The ENET context structure. * @return The execution status. */ uint32_t enet_mac_txbd_deinit(enet_dev_if_t * enetIfPtr); /*! * @brief Initializes ENET MAC FIFO and accelerator with the basic configuration. * * @param enetIfPtr The ENET context structure. * @return The execution status. */ uint32_t enet_mac_configure_fifo_accel(enet_dev_if_t * enetIfPtr); /*! * @brief the ENET controller with the basic configuration. * * @param enetIfPtr The ENET context structure. * @return The execution status. */ uint32_t enet_mac_configure_controller(enet_dev_if_t * enetIfPtr); /*! * @brief Deinit the ENET device. * * @param enetIfPtr The ENET context structure. * @return The execution status. */ uint32_t enet_mac_deinit(enet_dev_if_t * enetIfPtr); #if !ENET_RECEIVE_ALL_INTERRUPT /*! * @brief Updates the receive buffer descriptor. * * This updates the used receive buffer descriptor ring to * ensure that the used BDS is correctly used again. It cleans * the status region and sets the control region of the used receive buffer * descriptor. If the isBufferUpdate flag is set, the data buffer in the * buffer descriptor is updated. * * @param enetIfPtr The ENET context structure. * @param isBufferUpdate The data buffer update flag. * @return The execution status. */ uint32_t enet_mac_update_rxbd(enet_dev_if_t * enetIfPtr, bool isBufferUpdate); #else /*! * @brief Updates the receive buffer descriptor. * * Clears the status region and sets the control region of the current receive buffer * descriptor to ensure that it is used correctly again. It increases the buffer * descriptor index to the next buffer descriptor. * * @param enetIfPtr The ENET context structure. * @return The execution status. */ uint32_t enet_mac_update_rxbd(enet_dev_if_t * enetIfPtr); #endif /*! * @brief Processes the ENET receive frame error statistics. * * This interface gets the error statistics of the received frame. * Because the error information is in the last BD of a frame, this interface * should be called when processing the last BD of a frame. * * @param enetIfPtr The ENET context structure. * @param data The current control and status data of the buffer descriptor. * @return The frame error status. * - True if the frame has an error. * - False if the frame does not have an error. */ bool enet_mac_rx_error_stats(enet_dev_if_t * enetIfPtr, uint32_t data); /*! * @brief Processes the ENET transmit frame statistics. * * This interface gets the error statistics of the transmit frame. * Because the error information is in the last BD of a frame, this interface * should be called when processing the last BD of a frame. * * @param enetIfPtr The ENET context structure. * @param curBd The current buffer descriptor. */ void enet_mac_tx_error_stats(enet_dev_if_t * enetIfPtr,void *curBd); /*! * @brief ENET transmit buffer descriptor cleanup. * * First, store the transmit frame error statistic and PTP timestamp of the transmitted packets. * Second, clean up the used transmit buffer descriptors. * If the PTP 1588 feature is open, this interface captures the 1588 timestamp. * It is called by the transmit interrupt handler. * * @param enetIfPtr The ENET context structure. * @return The execution status. */ uint32_t enet_mac_tx_cleanup(enet_dev_if_t * enetIfPtr); #if !ENET_RECEIVE_ALL_INTERRUPT /*! * @brief Receives ENET packets. * * @param enetIfPtr The ENET context structure. * @param packBuffer The received data buffer. * @return The execution status. */ uint32_t enet_mac_receive(enet_dev_if_t * enetIfPtr, enet_mac_packet_buffer_t *packBuffer); #else /*! * @brief Receives ENET packets. * * @param enetIfPtr The ENET context structure. * @return The execution status. */ uint32_t enet_mac_receive(enet_dev_if_t * enetIfPtr); #endif /*! * @brief Transmits ENET packets. * * @param enetIfPtr The ENET context structure. * @param packet The frame to be transmitted. * @param size The frame size. * @return The execution status. */ uint32_t enet_mac_send(enet_dev_if_t * enetIfPtr, uint8_t *packet, uint32_t size); /*! * @brief The ENET receive interrupt handler. * * @param enetIfPtr The ENET context structure pointer. */ void enet_mac_rx_isr(void *enetIfPtr); /*! * @brief The ENET transmit interrupt handler. * * @param enetIfPtr The ENET context structure pointer. */ void enet_mac_tx_isr(void *enetIfPtr); /*! * @brief Calculates the CRC hash value. * * @param address The ENET MAC hardware address. * @param crcVlaue The calculated CRC value of the Mac address. */ void enet_mac_calculate_crc32(enetMacAddr address, uint32_t *crcValue); /*! * @brief Adds the ENET device to a multicast group. * * @param instance The ENET instance number. * @param multiGroupPtr The ENET multicast group structure. * @param address The ENET MAC hardware address. * @return The execution status. */ uint32_t enet_mac_add_multicast_group(uint32_t instance, enet_multicast_group_t *multiGroupPtr, enetMacAddr address); /*! * @brief Moves the ENET device from a multicast group. * * @param instance The ENET instance number. * @param multiGroupPtr The ENET multicast group structure. * @param address The ENET MAC hardware address. * @return The execution status. */ uint32_t enet_mac_leave_multicast_group(uint32_t instance, enet_multicast_group_t *multiGroupPtr, enetMacAddr address); /*! * @brief Initializes the ENET with the basic configuration. * * @param enetIfPtr The pointer to the basic configuration structure. * @return The execution status. */ uint32_t enet_mac_init(enet_dev_if_t * enetIfPtr, enet_rxbd_config_t *rxbdCfg, enet_txbd_config_t *txbdCfg); /*! * @brief Enqueues a data buffer to the buffer queue. * * @param queue The buffer queue. * @param buffer The buffer to add to the buffer queue. */ void enet_mac_enqueue_buffer( void **queue, void *buffer); /*! * @brief Dequeues a buffer from the buffer queue. * * @param queue The buffer queue. * @return The dequeued data buffer. */ void *enet_mac_dequeue_buffer( void **queue); /* @} */ #if defined(__cplusplus) } #endif #endif /*! @}*/ #endif /* __FSL_ENET_DRIVER_H__ */ /******************************************************************************* * EOF ******************************************************************************/ ================================================ FILE: Zelig/mbed/TARGET_K64F/TARGET_Freescale/TARGET_KPSDK_MCUS/TARGET_KPSDK_CODE/drivers/enet/fsl_enet_rtcs_adapter.h ================================================ /* * Copyright (c) 2013 - 2014, Freescale Semiconductor, Inc. * All rights reserved. * * Redistribution and use in source and binary forms, with or without modification, * are permitted provided that the following conditions are met: * * o Redistributions of source code must retain the above copyright notice, this list * of conditions and the following disclaimer. * * o Redistributions in binary form must reproduce the above copyright notice, this * list of conditions and the following disclaimer in the documentation and/or * other materials provided with the distribution. * * o Neither the name of Freescale Semiconductor, Inc. nor the names of its * contributors may be used to endorse or promote products derived from this * software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT 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. */ #ifndef __FSL_ENET_RTCS_ADAPTOR_H__ #define __FSL_ENET_RTCS_ADAPTOR_H__ #include "fsl_enet_hal.h" #ifndef MBED_NO_ENET #ifdef FSL_RTOS_MQX #include "rtcs.h" #include "pcb.h" #endif /*! * @addtogroup enet_rtcs_adaptor * @{ */ /******************************************************************************* * Definitions ******************************************************************************/ /*! @brief Definitions of the task parameter*/ #ifndef FSL_RTOS_MQX extern unsigned long _RTCSTASK_priority; #endif #define ENET_RECEIVE_TASK_PRIO (1) #define ENET_TASK_STACK_SIZE (800) #define ENET_PCB_NUM (16) /*! @brief Definitions of the configuration parameter*/ #define ENET_RXBD_NUM (8) #define ENET_TXBD_NUM (4) #define ENET_EXTRXBD_NUM (4) #define ENET_RXBuff_SIZE (kEnetMaxFrameSize) #define ENET_TXBuff_SIZE (kEnetMaxFrameSize) #define ENET_RXRTCSBUFF_NUM (8) #define ENET_RX_BUFFER_ALIGNMENT (16) #define ENET_TX_BUFFER_ALIGNMENT (16) #define ENET_BD_ALIGNMENT (16) #define ENET_RXBuffSizeAlign(n) ENET_ALIGN(n, ENET_RX_BUFFER_ALIGNMENT) #define ENET_TXBuffSizeAlign(n) ENET_ALIGN(n, ENET_TX_BUFFER_ALIGNMENT) #define ENET_MII_CLOCK (2500000L) #if FSL_FEATURE_ENET_SUPPORT_PTP #define ENET_PTP_TXTS_RING_LEN (25) #define ENET_PTP_RXTS_RING_LEN (25) #endif /*! @brief Definitions of the error codes */ #define ENET_OK (0) #define ENET_ERROR (0xff) /* General ENET error */ #define ENETERR_INVALID_DEVICE (kStatus_ENET_InvalidDevice) /* Device number out of range */ #define ENETERR_INIT_DEVICE (kStatus_ENET_Initialized) /* Device already initialized */ /*! @brief Definitions of the ENET protocol parameter*/ #define ENETPROT_IP 0x0800 #define ENETPROT_ARP 0x0806 #define ENETPROT_8021Q 0x8100 #define ENETPROT_IP6 0x86DD #define ENETPROT_ETHERNET 0x88F7 #define ENET_OPT_8023 0x0001 #define ENET_OPT_8021QTAG 0x0002 #define ENET_SETOPT_8021QPRIO(p) (ENET_OPT_8021QTAG | (((uint_32)(p) & 0x7) << 2)) #define ENET_GETOPT_8021QPRIO(f) ((((unsigned int)f) >> 2) & 0x7) /*! @brief Definitions of the ENET option macro*/ #define ENET_OPTION_HW_TX_IP_CHECKSUM 0x00001000 #define ENET_OPTION_HW_TX_PROTOCOL_CHECKSUM 0x00002000 #define ENET_OPTION_HW_RX_IP_CHECKSUM 0x00004000 #define ENET_OPTION_HW_RX_PROTOCOL_CHECKSUM 0x00008000 #define ENET_OPTION_HW_RX_MAC_ERR 0x00010000 /*! @brief Definitions of the ENET default Mac*/ #define ENET_DEFAULT_MAC_ADD { 0x00, 0x00, 0x5E, 0, 0, 0 } #define PCB_MINIMUM_SIZE (sizeof(PCB2)) #define PCB_free(pcb_ptr) ((pcb_ptr)->FREE(pcb_ptr)) /*! @brief Definitions of the macro for byte-swap*/ #if SYSTEM_LITTLE_ENDIAN #define RTCS_HTONS(n) BSWAP_16(n) #define RTCS_HTONL(n) BSWAP_32(n) #define RTCS_NTOHS(n) BSWAP_16(n) #define RTCS_NTOHL(n) BSWAP_32(n) #else #define RTCS_HTONS(n) (n) #define RTCS_HTONL(n) (n) #define RTCS_NTOHS(n) (n) #define RTCS_NTOHL(n) (n) #endif #ifndef FSL_RTOS_MQX #define htonl(p,x) (((uint_8_ptr)(p))[0] = ((x) >> 24) & 0xFF, \ ((uint_8_ptr)(p))[1] = ((x) >> 16) & 0xFF, \ ((uint_8_ptr)(p))[2] = ((x) >> 8) & 0xFF, \ ((uint_8_ptr)(p))[3] = (x) & 0xFF, \ (x)) #define htons(p,x) (((uint_8_ptr)(p))[0] = ((x) >> 8) & 0xFF, \ ((uint_8_ptr)(p))[1] = (x) & 0xFF, \ (x)) #define htonc(p,x) (((uint_8_ptr)(p))[0] = (x) & 0xFF, \ (x)) #define ntohl(p) (\ (((uint_32)(((uint_8_ptr)(p))[0])) << 24) | \ (((uint_32)(((uint_8_ptr)(p))[1])) << 16) | \ (((uint_32)(((uint_8_ptr)(p))[2])) << 8) | \ ( (uint_32)(((uint_8_ptr)(p))[3])) \ ) #define ntohs(p) (\ (((uint_16)(((uint_8_ptr)(p))[0])) << 8) | \ ( (uint_16)(((uint_8_ptr)(p))[1])) \ ) #define ntohc(p) ((uint_8)(((uint_8_ptr)(p))[0])) #endif #define htone(p,x) ((p)[0] = (x)[0], \ (p)[1] = (x)[1], \ (p)[2] = (x)[2], \ (p)[3] = (x)[3], \ (p)[4] = (x)[4], \ (p)[5] = (x)[5] \ ) #define ntohe(p,x) ((x)[0] = (p)[0] & 0xFF, \ (x)[1] = (p)[1] & 0xFF, \ (x)[2] = (p)[2] & 0xFF, \ (x)[3] = (p)[3] & 0xFF, \ (x)[4] = (p)[4] & 0xFF, \ (x)[5] = (p)[5] & 0xFF \ ) /*! @brief Definitions of the add to queue*/ #define QUEUEADD(head,tail,pcb) \ if ((head) == NULL) { \ (head) = (pcb); \ } else { \ (tail)->PRIVATE = (pcb); \ } \ (tail) = (pcb); \ (pcb)->PRIVATE = NULL /*! @brief Definitions of the get from queue*/ #define QUEUEGET(head,tail,pcb) \ (pcb) = (head); \ if (head) { \ (head) = (head)->PRIVATE; \ if ((head) == NULL) { \ (tail) = NULL; \ } \ } /*! @brief Definition for ENET six-byte Mac type*/ typedef unsigned char _enet_address[6]; /*! @brief Definition of the IPCFG structure*/ typedef void * _enet_handle; #ifndef FSL_RTOS_MQX struct pcb; typedef void (* PCB_FREE_FPTR)(struct pcb *); #endif /*! @brief Definition of the Ethernet packet header structure*/ typedef struct enet_header { _enet_address DEST; /*!< destination Mac address*/ _enet_address SOURCE; /*!< source Mac address*/ unsigned char TYPE[2]; /*!< protocol type*/ } ENET_HEADER, * ENET_HEADER_PTR; #ifndef FSL_RTOS_MQX /*! @brief Definition of the fragment PCB structure*/ typedef struct pcb_fragment { uint32_t LENGTH; /*!< Packet fragment length*/ unsigned char *FRAGMENT; /*!< brief Pointer to fragment*/ } PCB_FRAGMENT, * PCB_FRAGMENT_PTR; /*! @brief Definition of the PCB structure for the RTCS adaptor*/ typedef struct pcb { PCB_FREE_FPTR FREE; /*!< Function that frees PCB*/ void *PRIVATE; /*!< Private PCB information*/ PCB_FRAGMENT FRAG[1]; /*!< Pointer to PCB fragment*/ } PCB, * PCB_PTR; /*! @brief Definition of the two fragment PCB structure*/ typedef struct pcb2 { PCB_FREE_FPTR FREE; /*!< Function that frees PCB*/ void *PRIVATE; /*!< Private PCB information*/ PCB_FRAGMENT FRAG[2]; /*!< Pointers to two PCB fragments*/ } PCB2, *PCB2_PTR; #endif /*! @brief Definition of the two fragment PCB structure*/ typedef struct pcb_queue { PCB *pcbHead; /*!< PCB buffer head*/ PCB *pcbTail; /*!< PCB buffer tail*/ }pcb_queue; /*! @brief Definition of the ECB structure, which contains the protocol type and it's related service function*/ typedef struct ENETEcbStruct { uint16_t TYPE; void (* SERVICE)(PCB_PTR, void *); void *PRIVATE; struct ENETEcbStruct *NEXT; } enet_ecb_struct_t; /*! @brief Definition of the 8022 header*/ typedef struct enet_8022_header { uint8_t dsap[1]; /*!< DSAP region*/ uint8_t ssap[1]; /*!< SSAP region*/ uint8_t command[1]; /*!< Command region*/ uint8_t oui[3]; /*!< OUI region*/ uint16_t type; /*!< type region*/ }enet_8022_header_t, *enet_8022_header_ptr; /*! @brief Definition of the common status structure*/ typedef struct enet_commom_stats_struct { uint32_t ST_RX_TOTAL; /*!< Total number of received packets*/ uint32_t ST_RX_MISSED; /*!< Number of missed packets*/ uint32_t ST_RX_DISCARDED; /*!< Discarded a protocol that was not recognized*/ uint32_t ST_RX_ERRORS; /*!< Discarded error during reception*/ uint32_t ST_TX_TOTAL; /*!< Total number of transmitted packets*/ uint32_t ST_TX_MISSED; /*!< Discarded transmit ring full*/ uint32_t ST_TX_DISCARDED; /*!< Discarded bad packet*/ uint32_t ST_TX_ERRORS; /*!< Error during transmission*/ } ENET_COMMON_STATS_STRUCT, * ENET_COMMON_STATS_STRUCT_PTR; typedef struct enet_stats { ENET_COMMON_STATS_STRUCT COMMON; /*!< Common status structure*/ uint32_t ST_RX_ALIGN; /*!< Frame Alignment error*/ uint32_t ST_RX_FCS; /*!< CRC error */ uint32_t ST_RX_RUNT; /*!< Runt packet received */ uint32_t ST_RX_GIANT; /*!< Giant packet received*/ uint32_t ST_RX_LATECOLL; /*!< Late collision */ uint32_t ST_RX_OVERRUN; /*!< DMA overrun*/ uint32_t ST_TX_SQE; /*!< Heartbeat lost*/ uint32_t ST_TX_DEFERRED; /*!< Transmission deferred*/ uint32_t ST_TX_LATECOLL; /*!< Late collision*/ uint32_t ST_TX_EXCESSCOLL; /*!< Excessive collisions*/ uint32_t ST_TX_CARRIER; /*!< Carrier sense lost*/ uint32_t ST_TX_UNDERRUN; /*!< DMA underrun*/ /* Following stats are collected by the Ethernet driver */ uint32_t ST_RX_COPY_SMALL; /*!< Driver had to copy packet */ uint32_t ST_RX_COPY_LARGE; /*!< Driver had to copy packet */ uint32_t ST_TX_COPY_SMALL; /*!< Driver had to copy packet */ uint32_t ST_TX_COPY_LARGE; /*!< Driver had to copy packet */ uint32_t RX_FRAGS_EXCEEDED; uint32_t RX_PCBS_EXHAUSTED; uint32_t RX_LARGE_BUFFERS_EXHAUSTED; uint32_t TX_ALIGNED; uint32_t TX_ALL_ALIGNED; #if BSPCFG_ENABLE_ENET_HISTOGRAM uint32_t RX_HISTOGRAM[ENET_HISTOGRAM_ENTRIES]; uint32_t TX_HISTOGRAM[ENET_HISTOGRAM_ENTRIES]; #endif } ENET_STATS, * ENET_STATS_PTR; /******************************************************************************* * API ******************************************************************************/ #if defined(__cplusplus) extern "C" { #endif /*! * @name ENET RTCS ADAPTOR * @{ */ /*! * @brief Initializes the ENET device. * * @param device The ENET device number. * @param address The hardware address. * @param flag The flag for upper layer. * @param handle The address pointer for ENET device structure. * @return The execution status. */ uint32_t ENET_initialize(uint32_t device, _enet_address address,uint32_t flag, _enet_handle *handle); /*! * @brief Opens the ENET device. * * @param handle The address pointer for ENET device structure. * @param type The ENET protocol type. * @param service The service function for type. * @param private The private data for ENET device. * @return The execution status. */ uint32_t ENET_open(_enet_handle handle, uint16_t type, void (* service)(PCB_PTR, void *), void *private); /*! * @brief Shuts down the ENET device. * * @param handle The address pointer for ENET device structure. * @return The execution status. */ uint32_t ENET_shutdown(_enet_handle handle); #if !ENET_RECEIVE_ALL_INTERRUPT /*! * @brief ENET frame receive. * * @param enetIfPtr The address pointer for ENET device structure. */ static void ENET_receive(task_param_t param); #endif /*! * @brief ENET frame transmit. * * @param handle The address pointer for ENET device structure. * @param packet The ENET packet buffer. * @param type The ENET protocol type. * @param dest The destination hardware address. * @param flag The flag for upper layer. * @return The execution status. */ uint32_t ENET_send(_enet_handle handle, PCB_PTR packet, uint32_t type, _enet_address dest, uint32_t flags) ; /*! * @brief The ENET gets the address with the initialized device. * * @param handle The address pointer for ENET device structure. * @param address The destination hardware address. * @return The execution status. */ uint32_t ENET_get_address(_enet_handle handle, _enet_address address); /*! * @brief The ENET gets the address with an uninitialized device. * * @param handle The address pointer for ENET device structure. * @param value The value to change the last three bytes of hardware. * @param address The destination hardware address. * @return True if the execution status is success else false. */ uint32_t ENET_get_mac_address(uint32_t device, uint32_t value, _enet_address address); /*! * @brief The ENET joins a multicast group address. * * @param handle The address pointer for ENET device structure. * @param type The ENET protocol type. * @param address The destination hardware address. * @return The execution status. */ uint32_t ENET_join(_enet_handle handle, uint16_t type, _enet_address address); /*! * @brief The ENET leaves a multicast group address. * * @param handle The address pointer for ENET device structure. * @param type The ENET protocol type. * @param address The destination hardware address. * @return The execution status. */ uint32_t ENET_leave(_enet_handle handle, uint16_t type, _enet_address address); #if BSPCFG_ENABLE_ENET_STATS /*! * @brief The ENET gets the packet statistic. * * @param handle The address pointer for ENET device structure. * @return The statistic. */ ENET_STATS_PTR ENET_get_stats(_enet_handle handle); #endif /*! * @brief The ENET gets the link status. * * @param handle The address pointer for ENET device structure. * @return The link status. */ bool ENET_link_status(_enet_handle handle); /*! * @brief The ENET gets the link speed. * * @param handle The address pointer for ENET device structure. * @return The link speed. */ uint32_t ENET_get_speed(_enet_handle handle); /*! * @brief The ENET gets the MTU. * * @param handle The address pointer for ENET device structure. * @return The link MTU */ uint32_t ENET_get_MTU(_enet_handle handle); /*! * @brief Gets the ENET PHY registers. * * @param handle The address pointer for ENET device structure. * @param numRegs The number of registers. * @param regPtr The buffer for data read from PHY registers. * @return True if all numRegs registers are read succeed else false. */ bool ENET_phy_registers(_enet_handle handle, uint32_t numRegs, uint32_t *regPtr); /*! * @brief Gets ENET options. * * @param handle The address pointer for ENET device structure. * @return ENET options. */ uint32_t ENET_get_options(_enet_handle handle); /*! * @brief Unregisters a protocol type on an Ethernet channel. * * @param handle The address pointer for ENET device structure. * @return ENET options. */ uint32_t ENET_close(_enet_handle handle, uint16_t type); /*! * @brief ENET mediactl. * * @param handle The address pointer for ENET device structure. * @param The command ID. * @param The buffer for input or output parameters. * @return ENET options. */ uint32_t ENET_mediactl(_enet_handle handle, uint32_t commandId, void *inOutParam); /*! * @brief Gets the next ENET device handle address. * * @param handle The address pointer for ENET device structure. * @return The address of next ENET device handle. */ _enet_handle ENET_get_next_device_handle(_enet_handle handle); /*! * @brief ENET free. * * @param packet The buffer address. */ void ENET_free(PCB_PTR packet); /*! * @brief ENET error description. * * @param error The ENET error code. * @return The error string. */ const char * ENET_strerror(uint32_t error); /* @} */ #if defined(__cplusplus) } #endif /*! @}*/ #endif /* MBED_NO_ENET */ #endif /* __FSL_ENET_RTCS_ADAPTOR_H__ */ /******************************************************************************* * EOF ******************************************************************************/ ================================================ FILE: Zelig/mbed/TARGET_K64F/TARGET_Freescale/TARGET_KPSDK_MCUS/TARGET_KPSDK_CODE/drivers/interrupt/fsl_interrupt_features.h ================================================ /* ** ################################################################### ** Version: rev. 1.0, 2014-05-14 ** Build: b140526 ** ** Abstract: ** Chip specific module features. ** ** Copyright: 2014 Freescale Semiconductor, Inc. ** All rights reserved. ** ** Redistribution and use in source and binary forms, with or without modification, ** are permitted provided that the following conditions are met: ** ** o Redistributions of source code must retain the above copyright notice, this list ** of conditions and the following disclaimer. ** ** o Redistributions in binary form must reproduce the above copyright notice, this ** list of conditions and the following disclaimer in the documentation and/or ** other materials provided with the distribution. ** ** o Neither the name of Freescale Semiconductor, Inc. nor the names of its ** contributors may be used to endorse or promote products derived from this ** software without specific prior written permission. ** ** THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ** ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED ** WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE ** DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT 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. ** ** http: www.freescale.com ** mail: support@freescale.com ** ** Revisions: ** - rev. 1.0 (2014-05-14) ** Customer release. ** ** ################################################################### */ #if !defined(__FSL_INTERRUPT_FEATURES_H__) #define __FSL_INTERRUPT_FEATURES_H__ #if defined(CPU_MK02FN128VFM10) || defined(CPU_MK02FN64VFM10) || defined(CPU_MK02FN128VLF10) || defined(CPU_MK02FN64VLF10) || \ defined(CPU_MK02FN128VLH10) || defined(CPU_MK02FN64VLH10) || defined(CPU_MKV30F128VFM10) || defined(CPU_MKV30F64VFM10) || \ defined(CPU_MKV30F128VLF10) || defined(CPU_MKV30F64VLF10) || defined(CPU_MKV30F128VLH10) || defined(CPU_MKV30F64VLH10) /* @brief Lowest interrupt request number. */ #define FSL_FEATURE_INTERRUPT_IRQ_MIN (-14) /* @brief Highest interrupt request number. */ #define FSL_FEATURE_INTERRUPT_IRQ_MAX (73) #elif defined(CPU_MK20DX128VMP5) || defined(CPU_MK20DN128VMP5) || defined(CPU_MK20DX64VMP5) || defined(CPU_MK20DN64VMP5) || \ defined(CPU_MK20DX32VMP5) || defined(CPU_MK20DN32VMP5) || defined(CPU_MK20DX128VLH5) || defined(CPU_MK20DN128VLH5) || \ defined(CPU_MK20DX64VLH5) || defined(CPU_MK20DN64VLH5) || defined(CPU_MK20DX32VLH5) || defined(CPU_MK20DN32VLH5) || \ defined(CPU_MK20DX128VFM5) || defined(CPU_MK20DN128VFM5) || defined(CPU_MK20DX64VFM5) || defined(CPU_MK20DN64VFM5) || \ defined(CPU_MK20DX32VFM5) || defined(CPU_MK20DN32VFM5) || defined(CPU_MK20DX128VFT5) || defined(CPU_MK20DN128VFT5) || \ defined(CPU_MK20DX64VFT5) || defined(CPU_MK20DN64VFT5) || defined(CPU_MK20DX32VFT5) || defined(CPU_MK20DN32VFT5) || \ defined(CPU_MK20DX128VLF5) || defined(CPU_MK20DN128VLF5) || defined(CPU_MK20DX64VLF5) || defined(CPU_MK20DN64VLF5) || \ defined(CPU_MK20DX32VLF5) || defined(CPU_MK20DN32VLF5) || defined(CPU_MK70FN1M0VMF12) || defined(CPU_MK70FX512VMF12) || \ defined(CPU_MK70FN1M0VMF15) || defined(CPU_MK70FX512VMF15) || defined(CPU_MK70FN1M0VMJ12) || defined(CPU_MK70FX512VMJ12) || \ defined(CPU_MK70FN1M0VMJ15) || defined(CPU_MK70FX512VMJ15) /* @brief Lowest interrupt request number. */ #define FSL_FEATURE_INTERRUPT_IRQ_MIN (-14) /* @brief Highest interrupt request number. */ #define FSL_FEATURE_INTERRUPT_IRQ_MAX (105) #elif defined(CPU_MK22FN128VDC10) || defined(CPU_MK22FN128VLH10) || defined(CPU_MK22FN128VLL10) || defined(CPU_MK22FN128VMP10) || \ defined(CPU_MK22FN256VDC12) || defined(CPU_MK22FN256VLH12) || defined(CPU_MK22FN256VLL12) || defined(CPU_MK22FN256VMP12) || \ defined(CPU_MK22FN512VDC12) || defined(CPU_MK22FN512VLH12) || defined(CPU_MK22FN512VLL12) || defined(CPU_MK24FN1M0VDC12) || \ defined(CPU_MK24FN1M0VLL12) || defined(CPU_MK24FN1M0VLQ12) || defined(CPU_MK24FN256VDC12) || defined(CPU_MK63FN1M0VLQ12) || \ defined(CPU_MK63FN1M0VMD12) || defined(CPU_MK64FX512VDC12) || defined(CPU_MK64FN1M0VDC12) || defined(CPU_MK64FX512VLL12) || \ defined(CPU_MK64FN1M0VLL12) || defined(CPU_MK64FX512VLQ12) || defined(CPU_MK64FN1M0VLQ12) || defined(CPU_MK64FX512VMD12) || \ defined(CPU_MK64FN1M0VMD12) || defined(CPU_MKV31F128VLH10) || defined(CPU_MKV31F128VLL10) || defined(CPU_MKV31F256VLH12) || \ defined(CPU_MKV31F256VLL12) || defined(CPU_MKV31F512VLH12) || defined(CPU_MKV31F512VLL12) /* @brief Lowest interrupt request number. */ #define FSL_FEATURE_INTERRUPT_IRQ_MIN (-14) /* @brief Highest interrupt request number. */ #define FSL_FEATURE_INTERRUPT_IRQ_MAX (85) #elif defined(CPU_MK65FN2M0CAC18) || defined(CPU_MK65FX1M0CAC18) || defined(CPU_MK65FN2M0VMI18) || defined(CPU_MK65FX1M0VMI18) || \ defined(CPU_MK66FN2M0VLQ18) || defined(CPU_MK66FX1M0VLQ18) || defined(CPU_MK66FN2M0VMD18) || defined(CPU_MK66FX1M0VMD18) || \ defined(CPU_MKV40F128VLL15) || defined(CPU_MKV40F256VLL15) || defined(CPU_MKV43F128VLL15) || defined(CPU_MKV45F128VLL15) || \ defined(CPU_MKV45F256VLL15) || defined(CPU_MKV46F128VLH15) || defined(CPU_MKV46F128VLL15) || defined(CPU_MKV46F256VLH15) || \ defined(CPU_MKV46F256VLL15) /* @brief Lowest interrupt request number. */ #define FSL_FEATURE_INTERRUPT_IRQ_MIN (-14) /* @brief Highest interrupt request number. */ #define FSL_FEATURE_INTERRUPT_IRQ_MAX (99) #elif defined(CPU_MKL03Z32CAF4) || defined(CPU_MKL03Z8VFG4) || defined(CPU_MKL03Z16VFG4) || defined(CPU_MKL03Z32VFG4) || \ defined(CPU_MKL03Z8VFK4) || defined(CPU_MKL03Z16VFK4) || defined(CPU_MKL03Z32VFK4) || defined(CPU_MKL05Z8VFK4) || \ defined(CPU_MKL05Z16VFK4) || defined(CPU_MKL05Z32VFK4) || defined(CPU_MKL05Z8VLC4) || defined(CPU_MKL05Z16VLC4) || \ defined(CPU_MKL05Z32VLC4) || defined(CPU_MKL05Z8VFM4) || defined(CPU_MKL05Z16VFM4) || defined(CPU_MKL05Z32VFM4) || \ defined(CPU_MKL05Z16VLF4) || defined(CPU_MKL05Z32VLF4) || defined(CPU_MKL17Z128VFM4) || defined(CPU_MKL17Z256VFM4) || \ defined(CPU_MKL17Z128VFT4) || defined(CPU_MKL17Z256VFT4) || defined(CPU_MKL17Z128VMP4) || defined(CPU_MKL17Z256VMP4) || \ defined(CPU_MKL25Z32VFM4) || defined(CPU_MKL25Z64VFM4) || defined(CPU_MKL25Z128VFM4) || defined(CPU_MKL25Z32VFT4) || \ defined(CPU_MKL25Z64VFT4) || defined(CPU_MKL25Z128VFT4) || defined(CPU_MKL25Z32VLH4) || defined(CPU_MKL25Z64VLH4) || \ defined(CPU_MKL25Z128VLH4) || defined(CPU_MKL25Z32VLK4) || defined(CPU_MKL25Z64VLK4) || defined(CPU_MKL25Z128VLK4) || \ defined(CPU_MKL26Z256VLK4) || defined(CPU_MKL26Z128VLL4) || defined(CPU_MKL26Z256VLL4) || defined(CPU_MKL26Z128VMC4) || \ defined(CPU_MKL26Z256VMC4) || defined(CPU_MKL27Z128VFM4) || defined(CPU_MKL27Z256VFM4) || defined(CPU_MKL33Z128VLH4) || \ defined(CPU_MKL33Z256VLH4) || defined(CPU_MKL33Z128VMP4) || defined(CPU_MKL33Z256VMP4) || defined(CPU_MKL43Z64VLH4) || \ defined(CPU_MKL43Z128VLH4) || defined(CPU_MKL43Z256VLH4) || defined(CPU_MKL43Z64VMP4) || defined(CPU_MKL43Z128VMP4) || \ defined(CPU_MKL43Z256VMP4) || defined(CPU_MKL46Z128VLH4) || defined(CPU_MKL46Z256VLH4) || defined(CPU_MKL46Z128VLL4) || \ defined(CPU_MKL46Z256VLL4) || defined(CPU_MKL46Z128VMC4) || defined(CPU_MKL46Z256VMC4) /* @brief Lowest interrupt request number. */ #define FSL_FEATURE_INTERRUPT_IRQ_MIN (-14) /* @brief Highest interrupt request number. */ #define FSL_FEATURE_INTERRUPT_IRQ_MAX (31) #elif defined(CPU_MKV40F128VLH15) || defined(CPU_MKV40F256VLH15) || defined(CPU_MKV40F64VLH15) || defined(CPU_MKV43F128VLH15) || \ defined(CPU_MKV43F64VLH15) || defined(CPU_MKV44F128VLH15) || defined(CPU_MKV44F128VLL15) || defined(CPU_MKV44F64VLH15) || \ defined(CPU_MKV45F128VLH15) || defined(CPU_MKV45F256VLH15) /* @brief Lowest interrupt request number. */ #define FSL_FEATURE_INTERRUPT_IRQ_MIN (-14) /* @brief Highest interrupt request number. */ #define FSL_FEATURE_INTERRUPT_IRQ_MAX (92) #else #error "No valid CPU defined!" #endif #endif /* __FSL_INTERRUPT_FEATURES_H__ */ /******************************************************************************* * EOF ******************************************************************************/ ================================================ FILE: Zelig/mbed/TARGET_K64F/TARGET_Freescale/TARGET_KPSDK_MCUS/TARGET_KPSDK_CODE/drivers/interrupt/fsl_interrupt_manager.h ================================================ /* * Copyright (c) 2013 - 2014, Freescale Semiconductor, Inc. * All rights reserved. * * Redistribution and use in source and binary forms, with or without modification, * are permitted provided that the following conditions are met: * * o Redistributions of source code must retain the above copyright notice, this list * of conditions and the following disclaimer. * * o Redistributions in binary form must reproduce the above copyright notice, this * list of conditions and the following disclaimer in the documentation and/or * other materials provided with the distribution. * * o Neither the name of Freescale Semiconductor, Inc. nor the names of its * contributors may be used to endorse or promote products derived from this * software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT 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. */ #if !defined(__FSL_INTERRUPT_MANAGER_H__) #define __FSL_INTERRUPT_MANAGER_H__ #include #include #include #include "fsl_interrupt_features.h" #include "device/fsl_device_registers.h" /*! @addtogroup interrupt_manager*/ /*! @{*/ /*! @file*/ /******************************************************************************* * Definitions ******************************************************************************/ /******************************************************************************* * API ******************************************************************************/ #if defined(__cplusplus) extern "C" { #endif /* __cplusplus*/ /*! @name interrupt_manager APIs*/ /*@{*/ /*! * @brief Installs an interrupt handler routine for a given IRQ number. * * This function lets the application register/replace the interrupt * handler for a specified IRQ number. The IRQ number is different than the vector * number. IRQ 0 starts from the vector 16 address. See a chip-specific reference * manual for details and the startup_MKxxxx.s file for each chip * family to find out the default interrupt handler for each device. This * function converts the IRQ number to the vector number by adding 16 to * it. * * @param irqNumber IRQ number * @param handler Interrupt handler routine address pointer */ void INT_SYS_InstallHandler(IRQn_Type irqNumber, void (*handler)(void)); /*! * @brief Enables an interrupt for a given IRQ number. * * This function enables the individual interrupt for a specified IRQ * number. It calls the system NVIC API to access the interrupt control * register. The input IRQ number does not include the core interrupt, only * the peripheral interrupt, from 0 to a maximum supported IRQ. * * @param irqNumber IRQ number */ static inline void INT_SYS_EnableIRQ(IRQn_Type irqNumber) { /* check IRQ number */ assert(0 <= irqNumber); assert(irqNumber <= FSL_FEATURE_INTERRUPT_IRQ_MAX); /* call core API to enable the IRQ*/ NVIC_EnableIRQ(irqNumber); } /*! * @brief Disables an interrupt for a given IRQ number. * * This function enables the individual interrupt for a specified IRQ * number. It calls the system NVIC API to access the interrupt control * register. * * @param irqNumber IRQ number */ static inline void INT_SYS_DisableIRQ(IRQn_Type irqNumber) { /* check IRQ number */ assert(0 <= irqNumber); assert(irqNumber <= FSL_FEATURE_INTERRUPT_IRQ_MAX); /* call core API to disable the IRQ*/ NVIC_DisableIRQ(irqNumber); } /*! * @brief Enables system interrupt. * * This function enables the global interrupt by calling the core API. * */ void INT_SYS_EnableIRQGlobal(void); /*! * @brief Disable system interrupt. * * This function disables the global interrupt by calling the core API. * */ void INT_SYS_DisableIRQGlobal(void); /*@}*/ #if defined(__cplusplus) } #endif /* __cplusplus*/ /*! @}*/ #endif /* __FSL_INTERRUPT_MANAGER_H__*/ /******************************************************************************* * EOF ******************************************************************************/ ================================================ FILE: Zelig/mbed/TARGET_K64F/TARGET_Freescale/TARGET_KPSDK_MCUS/TARGET_KPSDK_CODE/drivers/pit/common/fsl_pit_common.h ================================================ /* * Copyright (c) 2013 - 2014, Freescale Semiconductor, Inc. * All rights reserved. * * Redistribution and use in source and binary forms, with or without modification, * are permitted provided that the following conditions are met: * * o Redistributions of source code must retain the above copyright notice, this list * of conditions and the following disclaimer. * * o Redistributions in binary form must reproduce the above copyright notice, this * list of conditions and the following disclaimer in the documentation and/or * other materials provided with the distribution. * * o Neither the name of Freescale Semiconductor, Inc. nor the names of its * contributors may be used to endorse or promote products derived from this * software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT 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. */ #if !defined(__FSL_PIT_COMMON_H__) #define __FSL_PIT_COMMON_H__ #include #include "fsl_device_registers.h" /******************************************************************************* * Definitions ******************************************************************************/ /*! @brief Table of base addresses for pit instances. */ extern const uint32_t g_pitBaseAddr[]; /*! @brief Table to save pit IRQ enum numbers defined in CMSIS header file. */ extern const IRQn_Type g_pitIrqId[]; #endif /* __FSL_PIT_COMMON_H__*/ /******************************************************************************* * EOF ******************************************************************************/ ================================================ FILE: Zelig/mbed/TARGET_K64F/TARGET_Freescale/TARGET_KPSDK_MCUS/TARGET_KPSDK_CODE/drivers/pit/fsl_pit_driver.h ================================================ /* * Copyright (c) 2013 - 2014, Freescale Semiconductor, Inc. * All rights reserved. * * Redistribution and use in source and binary forms, with or without modification, * are permitted provided that the following conditions are met: * * o Redistributions of source code must retain the above copyright notice, this list * of conditions and the following disclaimer. * * o Redistributions in binary form must reproduce the above copyright notice, this * list of conditions and the following disclaimer in the documentation and/or * other materials provided with the distribution. * * o Neither the name of Freescale Semiconductor, Inc. nor the names of its * contributors may be used to endorse or promote products derived from this * software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT 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. */ #ifndef __FSL_PIT_DRIVER_H__ #define __FSL_PIT_DRIVER_H__ #include #include #include "fsl_pit_hal.h" /*! * @addtogroup pit_driver * @{ */ /******************************************************************************* * Definitions ******************************************************************************/ /*! * @brief PIT timer configuration structure * * Define structure PitConfig and use the PIT_DRV_InitChannel() function to make necessary * initializations. You may also use the remaining functions for PIT configuration. * * @note The timer chain feature is not valid in all devices. Check the * fsl_pit_features.h for accurate settings. If it's not valid, the value set here * will be bypassed inside the PIT_DRV_InitChannel() function. */ typedef struct PitUserConfig { bool isInterruptEnabled; /*!< Timer interrupt 0-disable/1-enable*/ bool isTimerChained; /*!< Chained with previous timer, 0-not/1-chained*/ uint32_t periodUs; /*!< Timer period in unit of microseconds*/ } pit_user_config_t; /*! @brief PIT ISR callback function typedef */ typedef void (*pit_isr_callback_t)(void); /******************************************************************************* * API ******************************************************************************/ #if defined(__cplusplus) extern "C" { #endif /*! * @name Initialize and Shutdown * @{ */ /*! * @brief Initializes the PIT module. * * This function must be called before calling all the other PIT driver functions. * This function un-gates the PIT clock and enables the PIT module. The isRunInDebug * passed into function affects all timer channels. * * @param instance PIT module instance number. * @param isRunInDebug Timers run or stop in debug mode. * - true: Timers continue to run in debug mode. * - false: Timers stop in debug mode. */ void PIT_DRV_Init(uint32_t instance, bool isRunInDebug); /*! * @brief Disables the PIT module and gate control. * * This function disables all PIT interrupts and PIT clock. It then gates the * PIT clock control. PIT_DRV_Init must be called if you want to use PIT again. * * @param instance PIT module instance number. */ void PIT_DRV_Deinit(uint32_t instance); /*! * @brief Initializes the PIT channel. * * This function initializes the PIT timers by using a channel. Pass in the timer number and its * configuration structure. Timers do not start counting by default after calling this * function. The function PIT_DRV_StartTimer must be called to start the timer counting. * Call the PIT_DRV_SetTimerPeriodByUs to re-set the period. * * This is an example demonstrating how to define a PIT channel configuration structure: @code pit_user_config_t pitTestInit = { .isInterruptEnabled = true, // Only takes effect when chain feature is available. // Otherwise, pass in arbitrary value(true/false). .isTimerChained = false, // In unit of microseconds. .periodUs = 1000, }; @endcode * * @param instance PIT module instance number. * @param channel Timer channel number. * @param config PIT channel configuration structure. */ void PIT_DRV_InitChannel(uint32_t instance, uint32_t channel, const pit_user_config_t * config); /* @} */ /*! * @name Timer Start and Stop * @{ */ /*! * @brief Starts the timer counting. * * After calling this function, timers load period value, count down to 0 and * then load the respective start value again. Each time a timer reaches 0, * it generates a trigger pulse and sets the timeout interrupt flag. * * @param instance PIT module instance number. * @param channel Timer channel number. */ void PIT_DRV_StartTimer(uint32_t instance, uint32_t channel); /*! * @brief Stops the timer counting. * * This function stops every timer counting. Timers reload their periods * respectively after the next time they call the PIT_DRV_StartTimer. * * @param instance PIT module instance number. * @param channel Timer channel number. */ void PIT_DRV_StopTimer(uint32_t instance, uint32_t channel); /* @} */ /*! * @name Timer Period * @{ */ /*! * @brief Sets the timer period in microseconds. * * The period range depends on the frequency of the PIT source clock. If the required period * is out of range, use the lifetime timer. * * @param instance PIT module instance number. * @param channel Timer channel number. * @param us Timer period in microseconds. */ void PIT_DRV_SetTimerPeriodByUs(uint32_t instance, uint32_t channel, uint32_t us); /*! * @brief Reads the current timer value in microseconds. * * This function returns an absolute time stamp in microseconds. * One common use of this function is to measure the running time of a part of * code. Call this function at both the beginning and end of code. The time * difference between these two time stamps is the running time. Make sure the * running time does not exceed the timer period. The time stamp returned is * up-counting. * * @param instance PIT module instance number. * @param channel Timer channel number. * @return Current timer value in microseconds. */ uint32_t PIT_DRV_ReadTimerUs(uint32_t instance, uint32_t channel); #if FSL_FEATURE_PIT_HAS_LIFETIME_TIMER /*! * @brief Sets the lifetime timer period. * * Timer 1 must be chained with timer 0 before using the lifetime timer. The period * range is restricted by "period * pitSourceClock < max of an uint64_t integer", * or it may cause an overflow and be unable to set the correct period. * * @param instance PIT module instance number. * @param period Lifetime timer period in microseconds. */ void PIT_DRV_SetLifetimeTimerPeriodByUs(uint32_t instance, uint64_t us); /*! * @brief Reads the current lifetime value in microseconds. * * This feature returns an absolute time stamp in microseconds. The time stamp * value does not exceed the timer period. The timer is up-counting. * * @param instance PIT module instance number. * @return Current lifetime timer value in microseconds. */ uint64_t PIT_DRV_ReadLifetimeTimerUs(uint32_t instance); #endif /*FSL_FEATURE_PIT_HAS_LIFETIME_TIMER*/ /* @} */ /*! * @name ISR Callback Function * @{ */ /*! * @brief Registers the PIT ISR callback function. * * System default ISR interfaces are already defined in the fsl_pit_irq.c. Users * can either edit these ISRs or use this function to register a callback * function. The default ISR runs the callback function if there is one * installed. * * @param instance PIT module instance number. * @param channel Timer channel number. * @param function Pointer to pit ISR callback function. */ void PIT_DRV_InstallCallback(uint32_t instance, uint32_t channel, pit_isr_callback_t function); /* @} */ #if defined(__cplusplus) } #endif /*! @}*/ #endif /* __FSL_PIT_DRIVER_H__*/ /******************************************************************************* * EOF ******************************************************************************/ ================================================ FILE: Zelig/mbed/TARGET_K64F/TARGET_Freescale/TARGET_KPSDK_MCUS/TARGET_KPSDK_CODE/hal/adc/fsl_adc_features.h ================================================ /* ** ################################################################### ** Version: rev. 1.0, 2014-05-14 ** Build: b140515 ** ** Abstract: ** Chip specific module features. ** ** Copyright: 2014 Freescale Semiconductor, Inc. ** All rights reserved. ** ** Redistribution and use in source and binary forms, with or without modification, ** are permitted provided that the following conditions are met: ** ** o Redistributions of source code must retain the above copyright notice, this list ** of conditions and the following disclaimer. ** ** o Redistributions in binary form must reproduce the above copyright notice, this ** list of conditions and the following disclaimer in the documentation and/or ** other materials provided with the distribution. ** ** o Neither the name of Freescale Semiconductor, Inc. nor the names of its ** contributors may be used to endorse or promote products derived from this ** software without specific prior written permission. ** ** THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ** ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED ** WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE ** DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT 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. ** ** http: www.freescale.com ** mail: support@freescale.com ** ** Revisions: ** - rev. 1.0 (2014-05-14) ** Customer release. ** ** ################################################################### */ #if !defined(__FSL_ADC_FEATURES_H__) #define __FSL_ADC_FEATURES_H__ #if defined(CPU_MK02FN128VFM10) || defined(CPU_MK02FN64VFM10) || defined(CPU_MK02FN128VLF10) || defined(CPU_MK02FN64VLF10) || \ defined(CPU_MK02FN128VLH10) || defined(CPU_MK02FN64VLH10) || defined(CPU_MK20DX128VMP5) || defined(CPU_MK20DN128VMP5) || \ defined(CPU_MK20DX64VMP5) || defined(CPU_MK20DN64VMP5) || defined(CPU_MK20DX32VMP5) || defined(CPU_MK20DN32VMP5) || \ defined(CPU_MK20DX128VLH5) || defined(CPU_MK20DN128VLH5) || defined(CPU_MK20DX64VLH5) || defined(CPU_MK20DN64VLH5) || \ defined(CPU_MK20DX32VLH5) || defined(CPU_MK20DN32VLH5) || defined(CPU_MK20DX128VFT5) || defined(CPU_MK20DN128VFT5) || \ defined(CPU_MK20DX64VFT5) || defined(CPU_MK20DN64VFT5) || defined(CPU_MK20DX32VFT5) || defined(CPU_MK20DN32VFT5) || \ defined(CPU_MK20DX128VLF5) || defined(CPU_MK20DN128VLF5) || defined(CPU_MK20DX64VLF5) || defined(CPU_MK20DN64VLF5) || \ defined(CPU_MK20DX32VLF5) || defined(CPU_MK20DN32VLF5) || defined(CPU_MK22FN128VDC10) || defined(CPU_MK22FN128VLH10) || \ defined(CPU_MK22FN128VLL10) || defined(CPU_MK22FN128VMP10) || defined(CPU_MK22FN256VDC12) || defined(CPU_MK22FN256VLH12) || \ defined(CPU_MK22FN256VLL12) || defined(CPU_MK22FN256VMP12) || defined(CPU_MK22FN512VDC12) || defined(CPU_MK22FN512VLH12) || \ defined(CPU_MK22FN512VLL12) || defined(CPU_MK24FN1M0VDC12) || defined(CPU_MK24FN1M0VLL12) || defined(CPU_MK24FN1M0VLQ12) || \ defined(CPU_MK24FN256VDC12) || defined(CPU_MK63FN1M0VLQ12) || defined(CPU_MK63FN1M0VMD12) || defined(CPU_MK64FX512VDC12) || \ defined(CPU_MK64FN1M0VDC12) || defined(CPU_MK64FX512VLL12) || defined(CPU_MK64FN1M0VLL12) || defined(CPU_MK64FX512VLQ12) || \ defined(CPU_MK64FN1M0VLQ12) || defined(CPU_MK64FX512VMD12) || defined(CPU_MK64FN1M0VMD12) || defined(CPU_MK65FN2M0CAC18) || \ defined(CPU_MK65FX1M0CAC18) || defined(CPU_MK65FN2M0VMI18) || defined(CPU_MK65FX1M0VMI18) || defined(CPU_MK66FN2M0VLQ18) || \ defined(CPU_MK66FX1M0VLQ18) || defined(CPU_MK66FN2M0VMD18) || defined(CPU_MK66FX1M0VMD18) || defined(CPU_MKL13Z64VFM4) || \ defined(CPU_MKL13Z128VFM4) || defined(CPU_MKL13Z256VFM4) || defined(CPU_MKL13Z64VFT4) || defined(CPU_MKL13Z128VFT4) || \ defined(CPU_MKL13Z256VFT4) || defined(CPU_MKL13Z64VLH4) || defined(CPU_MKL13Z128VLH4) || defined(CPU_MKL13Z256VLH4) || \ defined(CPU_MKL13Z64VMP4) || defined(CPU_MKL13Z128VMP4) || defined(CPU_MKL13Z256VMP4) || defined(CPU_MKL23Z64VFM4) || \ defined(CPU_MKL23Z128VFM4) || defined(CPU_MKL23Z256VFM4) || defined(CPU_MKL23Z64VFT4) || defined(CPU_MKL23Z128VFT4) || \ defined(CPU_MKL23Z256VFT4) || defined(CPU_MKL23Z64VLH4) || defined(CPU_MKL23Z128VLH4) || defined(CPU_MKL23Z256VLH4) || \ defined(CPU_MKL23Z64VMP4) || defined(CPU_MKL23Z128VMP4) || defined(CPU_MKL23Z256VMP4) || defined(CPU_MKL25Z32VFM4) || \ defined(CPU_MKL25Z64VFM4) || defined(CPU_MKL25Z128VFM4) || defined(CPU_MKL25Z32VFT4) || defined(CPU_MKL25Z64VFT4) || \ defined(CPU_MKL25Z128VFT4) || defined(CPU_MKL25Z32VLH4) || defined(CPU_MKL25Z64VLH4) || defined(CPU_MKL25Z128VLH4) || \ defined(CPU_MKL25Z32VLK4) || defined(CPU_MKL25Z64VLK4) || defined(CPU_MKL25Z128VLK4) || defined(CPU_MKL26Z256VLK4) || \ defined(CPU_MKL26Z128VLL4) || defined(CPU_MKL26Z256VLL4) || defined(CPU_MKL26Z128VMC4) || defined(CPU_MKL26Z256VMC4) || \ defined(CPU_MKL33Z128VLH4) || defined(CPU_MKL33Z256VLH4) || defined(CPU_MKL33Z128VMP4) || defined(CPU_MKL33Z256VMP4) || \ defined(CPU_MKL43Z64VLH4) || defined(CPU_MKL43Z128VLH4) || defined(CPU_MKL43Z256VLH4) || defined(CPU_MKL43Z64VMP4) || \ defined(CPU_MKL43Z128VMP4) || defined(CPU_MKL43Z256VMP4) || defined(CPU_MKL46Z128VLH4) || defined(CPU_MKL46Z256VLH4) || \ defined(CPU_MKL46Z128VLL4) || defined(CPU_MKL46Z256VLL4) || defined(CPU_MKL46Z128VMC4) || defined(CPU_MKL46Z256VMC4) || \ defined(CPU_MKV30F128VFM10) || defined(CPU_MKV30F64VFM10) || defined(CPU_MKV30F128VLF10) || defined(CPU_MKV30F64VLF10) || \ defined(CPU_MKV30F128VLH10) || defined(CPU_MKV30F64VLH10) || defined(CPU_MKV31F128VLH10) || defined(CPU_MKV31F128VLL10) || \ defined(CPU_MKV31F256VLH12) || defined(CPU_MKV31F256VLL12) || defined(CPU_MKV31F512VLH12) || defined(CPU_MKV31F512VLL12) /* @brief Has Programmable Gain Amplifier (PGA) in ADC (register PGA). */ #define FSL_FEATURE_ADC_HAS_PGA (0) /* @brief Has DMA support (bit SC2[DMAEN] or SC4[DMAEN]). */ #define FSL_FEATURE_ADC_HAS_DMA (1) /* @brief Has differential mode (bitfield SC1x[DIFF]). */ #define FSL_FEATURE_ADC_HAS_DIFF_MODE (1) /* @brief Has FIFO (bit SC4[AFDEP]). */ #define FSL_FEATURE_ADC_HAS_FIFO (0) /* @brief FIFO size if available (bitfield SC4[AFDEP]). */ #define FSL_FEATURE_ADC_FIFO_SIZE (0) /* @brief Has channel set a/b multiplexor (bitfield CFG2[MUXSEL]). */ #define FSL_FEATURE_ADC_HAS_MUX_SELECT (1) /* @brief Has HW trigger masking (bitfield SC5[HTRGMASKE]. */ #define FSL_FEATURE_ADC_HAS_HW_TRIGGER_MASK (0) /* @brief Has calibration feature (bit SC3[CAL] and registers CLPx, CLMx). */ #define FSL_FEATURE_ADC_HAS_CALIBRATION (1) /* @brief Has HW averaging (bit SC3[AVGE]). */ #define FSL_FEATURE_ADC_HAS_HW_AVERAGE (1) /* @brief Has offset correction (register OFS). */ #define FSL_FEATURE_ADC_HAS_OFFSET_CORRECTION (1) /* @brief Maximum ADC resolution. */ #define FSL_FEATURE_ADC_MAX_RESOLUTION (16) /* @brief Number of SC1x and Rx register pairs (conversion control and result registers). */ #define FSL_FEATURE_ADC_CONVERSION_CONTROL_COUNT (2) #elif defined(CPU_MK20DX128VFM5) || defined(CPU_MK20DN128VFM5) || defined(CPU_MK20DX64VFM5) || defined(CPU_MK20DN64VFM5) || \ defined(CPU_MK20DX32VFM5) || defined(CPU_MK20DN32VFM5) /* @brief Has Programmable Gain Amplifier (PGA) in ADC (register PGA). */ #define FSL_FEATURE_ADC_HAS_PGA (0) /* @brief Has DMA support (bit SC2[DMAEN] or SC4[DMAEN]). */ #define FSL_FEATURE_ADC_HAS_DMA (1) /* @brief Has differential mode (bitfield SC1x[DIFF]). */ #define FSL_FEATURE_ADC_HAS_DIFF_MODE (0) /* @brief Has FIFO (bit SC4[AFDEP]). */ #define FSL_FEATURE_ADC_HAS_FIFO (0) /* @brief FIFO size if available (bitfield SC4[AFDEP]). */ #define FSL_FEATURE_ADC_FIFO_SIZE (0) /* @brief Has channel set a/b multiplexor (bitfield CFG2[MUXSEL]). */ #define FSL_FEATURE_ADC_HAS_MUX_SELECT (1) /* @brief Has HW trigger masking (bitfield SC5[HTRGMASKE]. */ #define FSL_FEATURE_ADC_HAS_HW_TRIGGER_MASK (0) /* @brief Has calibration feature (bit SC3[CAL] and registers CLPx, CLMx). */ #define FSL_FEATURE_ADC_HAS_CALIBRATION (1) /* @brief Has HW averaging (bit SC3[AVGE]). */ #define FSL_FEATURE_ADC_HAS_HW_AVERAGE (1) /* @brief Has offset correction (register OFS). */ #define FSL_FEATURE_ADC_HAS_OFFSET_CORRECTION (1) /* @brief Maximum ADC resolution. */ #define FSL_FEATURE_ADC_MAX_RESOLUTION (16) /* @brief Number of SC1x and Rx register pairs (conversion control and result registers). */ #define FSL_FEATURE_ADC_CONVERSION_CONTROL_COUNT (2) #elif defined(CPU_MK70FN1M0VMF12) || defined(CPU_MK70FX512VMF12) || defined(CPU_MK70FN1M0VMF15) || defined(CPU_MK70FX512VMF15) || \ defined(CPU_MK70FN1M0VMJ12) || defined(CPU_MK70FX512VMJ12) || defined(CPU_MK70FN1M0VMJ15) || defined(CPU_MK70FX512VMJ15) /* @brief Has Programmable Gain Amplifier (PGA) in ADC (register PGA). */ #define FSL_FEATURE_ADC_HAS_PGA (1) /* @brief Has DMA support (bit SC2[DMAEN] or SC4[DMAEN]). */ #define FSL_FEATURE_ADC_HAS_DMA (1) /* @brief Has differential mode (bitfield SC1x[DIFF]). */ #define FSL_FEATURE_ADC_HAS_DIFF_MODE (1) /* @brief Has FIFO (bit SC4[AFDEP]). */ #define FSL_FEATURE_ADC_HAS_FIFO (0) /* @brief FIFO size if available (bitfield SC4[AFDEP]). */ #define FSL_FEATURE_ADC_FIFO_SIZE (0) /* @brief Has channel set a/b multiplexor (bitfield CFG2[MUXSEL]). */ #define FSL_FEATURE_ADC_HAS_MUX_SELECT (1) /* @brief Has HW trigger masking (bitfield SC5[HTRGMASKE]. */ #define FSL_FEATURE_ADC_HAS_HW_TRIGGER_MASK (0) /* @brief Has calibration feature (bit SC3[CAL] and registers CLPx, CLMx). */ #define FSL_FEATURE_ADC_HAS_CALIBRATION (1) /* @brief Has HW averaging (bit SC3[AVGE]). */ #define FSL_FEATURE_ADC_HAS_HW_AVERAGE (1) /* @brief Has offset correction (register OFS). */ #define FSL_FEATURE_ADC_HAS_OFFSET_CORRECTION (1) /* @brief Maximum ADC resolution. */ #define FSL_FEATURE_ADC_MAX_RESOLUTION (16) /* @brief Number of SC1x and Rx register pairs (conversion control and result registers). */ #define FSL_FEATURE_ADC_CONVERSION_CONTROL_COUNT (2) #elif defined(CPU_MKL03Z32CAF4) || defined(CPU_MKL03Z8VFG4) || defined(CPU_MKL03Z16VFG4) || defined(CPU_MKL03Z32VFG4) || \ defined(CPU_MKL03Z8VFK4) || defined(CPU_MKL03Z16VFK4) || defined(CPU_MKL03Z32VFK4) /* @brief Has Programmable Gain Amplifier (PGA) in ADC (register PGA). */ #define FSL_FEATURE_ADC_HAS_PGA (0) /* @brief Has DMA support (bit SC2[DMAEN] or SC4[DMAEN]). */ #define FSL_FEATURE_ADC_HAS_DMA (0) /* @brief Has differential mode (bitfield SC1x[DIFF]). */ #define FSL_FEATURE_ADC_HAS_DIFF_MODE (0) /* @brief Has FIFO (bit SC4[AFDEP]). */ #define FSL_FEATURE_ADC_HAS_FIFO (0) /* @brief FIFO size if available (bitfield SC4[AFDEP]). */ #define FSL_FEATURE_ADC_FIFO_SIZE (0) /* @brief Has channel set a/b multiplexor (bitfield CFG2[MUXSEL]). */ #define FSL_FEATURE_ADC_HAS_MUX_SELECT (1) /* @brief Has HW trigger masking (bitfield SC5[HTRGMASKE]. */ #define FSL_FEATURE_ADC_HAS_HW_TRIGGER_MASK (0) /* @brief Has calibration feature (bit SC3[CAL] and registers CLPx, CLMx). */ #define FSL_FEATURE_ADC_HAS_CALIBRATION (1) /* @brief Has HW averaging (bit SC3[AVGE]). */ #define FSL_FEATURE_ADC_HAS_HW_AVERAGE (1) /* @brief Has offset correction (register OFS). */ #define FSL_FEATURE_ADC_HAS_OFFSET_CORRECTION (1) /* @brief Maximum ADC resolution. */ #define FSL_FEATURE_ADC_MAX_RESOLUTION (12) /* @brief Number of SC1x and Rx register pairs (conversion control and result registers). */ #define FSL_FEATURE_ADC_CONVERSION_CONTROL_COUNT (2) #elif defined(CPU_MKL05Z8VFK4) || defined(CPU_MKL05Z16VFK4) || defined(CPU_MKL05Z32VFK4) || defined(CPU_MKL05Z8VLC4) || \ defined(CPU_MKL05Z16VLC4) || defined(CPU_MKL05Z32VLC4) || defined(CPU_MKL05Z8VFM4) || defined(CPU_MKL05Z16VFM4) || \ defined(CPU_MKL05Z32VFM4) || defined(CPU_MKL05Z16VLF4) || defined(CPU_MKL05Z32VLF4) /* @brief Has Programmable Gain Amplifier (PGA) in ADC (register PGA). */ #define FSL_FEATURE_ADC_HAS_PGA (0) /* @brief Has DMA support (bit SC2[DMAEN] or SC4[DMAEN]). */ #define FSL_FEATURE_ADC_HAS_DMA (1) /* @brief Has differential mode (bitfield SC1x[DIFF]). */ #define FSL_FEATURE_ADC_HAS_DIFF_MODE (0) /* @brief Has FIFO (bit SC4[AFDEP]). */ #define FSL_FEATURE_ADC_HAS_FIFO (0) /* @brief FIFO size if available (bitfield SC4[AFDEP]). */ #define FSL_FEATURE_ADC_FIFO_SIZE (0) /* @brief Has channel set a/b multiplexor (bitfield CFG2[MUXSEL]). */ #define FSL_FEATURE_ADC_HAS_MUX_SELECT (1) /* @brief Has HW trigger masking (bitfield SC5[HTRGMASKE]. */ #define FSL_FEATURE_ADC_HAS_HW_TRIGGER_MASK (0) /* @brief Has calibration feature (bit SC3[CAL] and registers CLPx, CLMx). */ #define FSL_FEATURE_ADC_HAS_CALIBRATION (1) /* @brief Has HW averaging (bit SC3[AVGE]). */ #define FSL_FEATURE_ADC_HAS_HW_AVERAGE (1) /* @brief Has offset correction (register OFS). */ #define FSL_FEATURE_ADC_HAS_OFFSET_CORRECTION (1) /* @brief Maximum ADC resolution. */ #define FSL_FEATURE_ADC_MAX_RESOLUTION (12) /* @brief Number of SC1x and Rx register pairs (conversion control and result registers). */ #define FSL_FEATURE_ADC_CONVERSION_CONTROL_COUNT (2) #else #error "No valid CPU defined!" #endif #endif /* __FSL_ADC_FEATURES_H__ */ /******************************************************************************* * EOF ******************************************************************************/ ================================================ FILE: Zelig/mbed/TARGET_K64F/TARGET_Freescale/TARGET_KPSDK_MCUS/TARGET_KPSDK_CODE/hal/adc/fsl_adc_hal.h ================================================ /* * Copyright (c) 2013 - 2014, Freescale Semiconductor, Inc. * All rights reserved. * * Redistribution and use in source and binary forms, with or without modification, * are permitted provided that the following conditions are met: * * o Redistributions of source code must retain the above copyright notice, this list * of conditions and the following disclaimer. * * o Redistributions in binary form must reproduce the above copyright notice, this * list of conditions and the following disclaimer in the documentation and/or * other materials provided with the distribution. * * o Neither the name of Freescale Semiconductor, Inc. nor the names of its * contributors may be used to endorse or promote products derived from this * software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT 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. */ #ifndef __FSL_ADC_HAL_H__ #define __FSL_ADC_HAL_H__ #include #include #include #include "fsl_device_registers.h" #include "fsl_adc_features.h" /*! * @addtogroup adc_hal * @{ */ /****************************************************************************** * Definitions *****************************************************************************/ /*! * @brief ADC status return codes. */ typedef enum _adc_status { kStatus_ADC_Success = 0U, /*!< Success. */ kStatus_ADC_InvalidArgument = 1U, /*!< Invalid argument existed. */ kStatus_ADC_Failed = 2U /*!< Execution failed. */ } adc_status_t; #if FSL_FEATURE_ADC_HAS_MUX_SELECT /*! * @brief Defines the type of the enumerating channel multiplexer mode for each channel. * * For some ADC channels, there are two selections for the channel multiplexer. For * example, ADC0_SE4a and ADC0_SE4b are the different channels but share the same * channel number. */ typedef enum _adc_chn_mux_mode { kAdcChnMuxOfA = 0U, /*!< For channel with channel mux a. */ kAdcChnMuxOfB = 1U, /*!< For channel with channel mux b. */ kAdcChnMuxOfDefault = kAdcChnMuxOfA /*!< For channel without any channel mux identifier. */ } adc_chn_mux_mode_t; #endif /* FSL_FEATURE_ADC_HAS_MUX_SELECT */ /*! * @brief Defines the type of the enumerating divider for the converter. */ typedef enum _adc_clk_divider_mode { kAdcClkDividerInputOf1 = 0U, /*!< For divider 1 from the input clock to ADC. */ kAdcClkDividerInputOf2 = 1U, /*!< For divider 2 from the input clock to ADC. */ kAdcClkDividerInputOf4 = 2U, /*!< For divider 4 from the input clock to ADC. */ kAdcClkDividerInputOf8 = 3U /*!< For divider 8 from the input clock to ADC. */ } adc_clk_divider_mode_t; /*! *@brief Defines the type of the enumerating resolution for the converter. */ typedef enum _adc_resolution_mode { kAdcResolutionBitOf8or9 = 0U, /*!< 8-bit for single end sample, or 9-bit for differential sample. */ kAdcResolutionBitOfSingleEndAs8 = kAdcResolutionBitOf8or9, /*!< 8-bit for single end sample. */ kAdcResolutionBitOfDiffModeAs9 = kAdcResolutionBitOf8or9, /*!< 9-bit for differential sample. */ kAdcResolutionBitOf12or13 = 1U, /*!< 12-bit for single end sample, or 13-bit for differential sample. */ kAdcResolutionBitOfSingleEndAs12 = kAdcResolutionBitOf12or13, /*!< 12-bit for single end sample. */ kAdcResolutionBitOfDiffModeAs13 = kAdcResolutionBitOf12or13, /*!< 13-bit for differential sample. */ kAdcResolutionBitOf10or11 = 2U, /*!< 10-bit for single end sample, or 11-bit for differential sample. */ kAdcResolutionBitOfSingleEndAs10 = kAdcResolutionBitOf10or11, /*!< 10-bit for single end sample. */ kAdcResolutionBitOfDiffModeAs11 = kAdcResolutionBitOf10or11 /*!< 11-bit for differential sample. */ #if (FSL_FEATURE_ADC_MAX_RESOLUTION>=16) , kAdcResolutionBitOf16 = 3U, /*!< 16-bit for both single end sample and differential sample. */ kAdcResolutionBitOfSingleEndAs16 = kAdcResolutionBitOf16, /*!< 16-bit for single end sample. */ kAdcResolutionBitOfDiffModeAs16 = kAdcResolutionBitOf16 /*!< 16-bit for differential sample. */ #endif /* FSL_FEATURE_ADC_MAX_RESOLUTION */ } adc_resolution_mode_t; /*! * @brief Defines the type of the enumerating source of the input clock. */ typedef enum _adc_clk_src_mode { kAdcClkSrcOfBusClk = 0U, /*!< For input as bus clock. */ kAdcClkSrcOfBusOrAltClk2 = 1U, /*!< For input as bus clock /2 or AltClk2. */ kAdcClkSrcOfAltClk = 2U, /*!< For input as alternate clock (ALTCLK). */ kAdcClkSrcOfAsynClk = 3U /*!< For input as asynchronous clock (ADACK). */ } adc_clk_src_mode_t; /* * @brief Defines the type of the enumerating long sample cycles. */ typedef enum _adc_long_sample_cycle_mode { kAdcLongSampleCycleOf24 = 0U, /*!< 20 extra ADCK cycles, 24 ADCK cycles total. */ kAdcLongSampleCycleOf16 = 1U, /*!< 12 extra ADCK cycles, 16 ADCK cycles total. */ kAdcLongSampleCycleOf10 = 2U, /*!< 6 extra ADCK cycles, 10 ADCK cycles total. */ kAdcLongSampleCycleOf4 = 3U /*!< 2 extra ADCK cycles, 6 ADCK cycles total. */ } adc_long_sample_cycle_mode_t; /* * @brief Defines the type of the enumerating reference voltage source. */ typedef enum _adc_ref_volt_src_mode { kAdcRefVoltSrcOfVref = 0U, /*!< For external pins pair of VrefH and VrefL. */ kAdcRefVoltSrcOfValt = 1U /*!< For alternate reference pair of ValtH and ValtL.*/ } adc_ref_volt_src_mode_t; #if FSL_FEATURE_ADC_HAS_HW_AVERAGE /* * @brief Defines the type of the enumerating hardware average mode. */ typedef enum _adc_hw_average_count_mode { kAdcHwAverageCountOf4 = 0U, /*!< For hardware average with 4 samples. */ kAdcHwAverageCountOf8 = 1U, /*!< For hardware average with 8 samples. */ kAdcHwAverageCountOf16 = 2U, /*!< For hardware average with 16 samples. */ kAdcHwAverageCountOf32 = 3U /*!< For hardware average with 32 samples. */ } adc_hw_average_count_mode_t; #endif /* FSL_FEATURE_ADC_HAS_HW_AVERAGE */ /*! * @brief Defines the type of the enumerating asserted range in the hardware compare. * * When the internal CMP is enabled, the COCO flag, which represents the complement * of the conversion, is not asserted if the sample value is not in the indicated * range. Eventually, the data of conversion result is not kept in the result * data register. The two values, cmpValue1 and cmpValue2, mark * the thresholds with the comparator feature. * kAdcHwCmpRangeModeOf1: * Both greater than and in range switchers are disabled. * The available range is "< cmpValue1". * kAdcHwCmpRangeModeOf2: * Greater than switcher is enabled while the in range switcher is disabled. * The available range is " > cmpValue1". * kAdcHwCmpRangeModeOf3: * Greater than switcher is disabled while in range switcher is enabled. * The available range is "< cmpValue1" or "> cmpValue2" when * cmpValue1 <= cmpValue2, or "< cmpValue1" and "> cmpValue2" when * cmpValue1 >= cmpValue2. * kAdcHwCmpRangeModeOf4: * Both greater than and in range switchers are enabled. * The available range is "> cmpValue1" and "< cmpValue2" when * cmpValue1 <= cmpValue2, or "> cmpValue1" or "< cmpValue2" when * cmpValue1 < cmpValue2. */ typedef enum _adc_hw_cmp_range_mode { kAdcHwCmpRangeModeOf1 = 0U, /*!< For selection mode 1. */ kAdcHwCmpRangeModeOf2 = 1U, /*!< For selection mode 2. */ kAdcHwCmpRangeModeOf3 = 2U, /*!< For selection mode 3. */ kAdcHwCmpRangeModeOf4 = 3U /*!< For selection mode 4. */ } adc_hw_cmp_range_mode_t; #if FSL_FEATURE_ADC_HAS_PGA /*! * @brief Defines the type of enumerating PGA's Gain mode. */ typedef enum _adc_pga_gain_mode { kAdcPgaGainValueOf1 = 0U, /*!< For amplifier gain of 1.*/ kAdcPgaGainValueOf2 = 1U, /*!< For amplifier gain of 2.*/ kAdcPgaGainValueOf4 = 2U, /*!< For amplifier gain of 4.*/ kAdcPgaGainValueOf8 = 3U, /*!< For amplifier gain of 8.*/ kAdcPgaGainValueOf16 = 4U, /*!< For amplifier gain of 16.*/ kAdcPgaGainValueOf32 = 5U, /*!< For amplifier gain of 32.*/ kAdcPgaGainValueOf64 = 6U /*!< For amplifier gain of 64.*/ } adc_pga_gain_mode_t; #endif /* FSL_FEATURE_ADC_HAS_PGA */ #if defined(__cplusplus) extern "C" { #endif /******************************************************************************* * API ******************************************************************************/ /*! * @brief Resets all registers into a known state for the ADC module. * * This function resets all registers into a known state for the ADC * module. This known state is the reset value indicated by the Reference * manual. It is strongly recommended to call this API before any other operation * when initializing the ADC module. * * @param baseAddr Register base address for the module. */ void ADC_HAL_Init(uint32_t baseAddr); /*! * @brief Configures the conversion channel for the ADC module. * * This function configures the channel for the ADC module. At any point, * only one of the configuration groups takes effect. The other channel mux of * the first group (group A, 0) is only for the hardware trigger. Both software and * hardware trigger can be used to the first group. When in software trigger * mode, once the available channel is set, the conversion begins to execute. * * @param baseAddr Register base address for the module. * @param chnGroup Channel configuration group ID. * @param intEnable Switcher to enable interrupt when conversion is completed. * @param diffEnable Switcher to enable differential channel mode. * @param chnNum ADC channel for next conversion. */ static inline void ADC_HAL_ConfigChn(uint32_t baseAddr, uint32_t chnGroup, bool intEnable, bool diffEnable, uint8_t chnNum) { assert(chnGroup < FSL_FEATURE_ADC_CONVERSION_CONTROL_COUNT); #if FSL_FEATURE_ADC_HAS_DIFF_MODE HW_ADC_SC1n_WR(baseAddr, chnGroup, \ ( (intEnable ? BM_ADC_SC1n_AIEN : 0U) \ | ( (diffEnable)? BM_ADC_SC1n_DIFF : 0U) \ | BF_ADC_SC1n_ADCH(chnNum) \ ) ); #else HW_ADC_SC1n_WR(baseAddr, chnGroup, \ ( (intEnable ? BM_ADC_SC1n_AIEN : 0U) \ | BF_ADC_SC1n_ADCH(chnNum) \ ) ); #endif /* FSL_FEATURE_ADC_HAS_DIFF_MODE */ } #if FSL_FEATURE_ADC_HAS_DIFF_MODE /*! * @brief Checks whether the channel differential mode is enabled. * * This function checks whether the channel differential mode for * is enabled. * * @param baseAddr Register base address for the module. * @param chnGroup Channel configuration group ID. * @return Assertion of enabling differential mode. */ static inline bool ADC_HAL_GetChnDiffCmd(uint32_t baseAddr, uint32_t chnGroup) { assert(chnGroup < FSL_FEATURE_ADC_CONVERSION_CONTROL_COUNT); return (1U == BR_ADC_SC1n_DIFF(baseAddr, chnGroup)); } #endif /* FSL_FEATURE_ADC_HAS_DIFF_MODE */ /*! * @brief Checks whether the channel conversion is completed. * * This function checks whether the channel conversion for the ADC * module is completed. * * @param baseAddr Register base address for the module. * @param chnGroup Channel configuration group ID. * @return Assertion of completed conversion mode. */ static inline bool ADC_HAL_GetChnConvCompletedCmd(uint32_t baseAddr, uint32_t chnGroup) { assert(chnGroup < FSL_FEATURE_ADC_CONVERSION_CONTROL_COUNT); return (1U == BR_ADC_SC1n_COCO(baseAddr, chnGroup) ); } /*! * @brief Switches to enable the low power mode for ADC module. * * This function switches to enable the low power mode for ADC module. * * @param baseAddr Register base address for the module. * @param enable Switcher to asserted the feature. */ static inline void ADC_HAL_SetLowPowerCmd(uint32_t baseAddr, bool enable) { BW_ADC_CFG1_ADLPC(baseAddr, (enable ? 1U : 0U) ); } /*! * @brief Selects the clock divider mode for the ADC module. * * This function selects the clock divider mode for the ADC module. * * @param baseAddr Register base address for the module. * @param mode Selection of mode enumeration. See to "adc_clk_divider_mode_t". */ static inline void ADC_HAL_SetClkDividerMode(uint32_t baseAddr, adc_clk_divider_mode_t mode) { BW_ADC_CFG1_ADIV(baseAddr, (uint32_t)mode ); } /*! * @brief Switches to enable the long sample mode for the ADC module. * * This function switches to enable the long sample mode for the ADC module. * This function adjusts the sample period to allow the higher impedance inputs to * be accurately sampled or to maximize the conversion speed for the lower impedance * inputs. Longer sample times can also be used to lower overall power * consumption if the continuous conversions are enabled and the high conversion rates * are not required. If the long sample mode is enabled, more configuration * is set by calling the "ADC_HAL_SetLongSampleCycleMode()" function. * * @param baseAddr Register base address for the module. * @param enable Switcher to asserted the feature. */ static inline void ADC_HAL_SetLongSampleCmd(uint32_t baseAddr, bool enable) { BW_ADC_CFG1_ADLSMP(baseAddr, (enable ? 1U : 0U) ); } /*! * @brief Selects the conversion resolution mode for ADC module. * * This function selects the conversion resolution mode for the ADC module. * * @param baseAddr Register base address for the module. * @param mode Selection of mode enumeration. See to "adc_resolution_mode_t". */ static inline void ADC_HAL_SetResolutionMode(uint32_t baseAddr, adc_resolution_mode_t mode) { BW_ADC_CFG1_MODE(baseAddr, (uint32_t)mode ); } /*! * @brief Gets the conversion resolution mode for ADC module. * * This function gets the conversion resolution mode for the ADC module. * It is specially used when processing the conversion result of RAW format. * * @param baseAddr Register base address for the module. * @return Current conversion resolution mode. */ static inline adc_resolution_mode_t ADC_HAL_GetResolutionMode(uint32_t baseAddr) { return (adc_resolution_mode_t)( BR_ADC_CFG1_MODE(baseAddr) ); } /*! * @brief Selects the input clock source for the ADC module. * * This function selects the input clock source for the ADC module. * * @param baseAddr Register base address for the module. * @param mode Selection of mode enumeration. See to "adc_clk_src_mode_t". */ static inline void ADC_HAL_SetClkSrcMode(uint32_t baseAddr, adc_clk_src_mode_t mode) { BW_ADC_CFG1_ADICLK(baseAddr, (uint32_t)mode ); } #if FSL_FEATURE_ADC_HAS_MUX_SELECT /*! * @brief Selects the channel mux mode for the ADC module. * * This function selects the channel mux mode for the ADC module. * * @param baseAddr Register base address for the module. * @param mode Selection of mode enumeration. See to "adc_chn_mux_mode_t". */ static inline void ADC_HAL_SetChnMuxMode(uint32_t baseAddr, adc_chn_mux_mode_t mode) { BW_ADC_CFG2_MUXSEL(baseAddr, ((kAdcChnMuxOfA == mode) ? 0U : 1U) ); } /*! * @brief Gets the current channel mux mode for the ADC module. * * This function selects the channel mux mode for the ADC module. * * @param baseAddr Register base address for the module. * @return Selection of mode enumeration. See to "adc_chn_mux_mode_t". */ static inline adc_chn_mux_mode_t ADC_HAL_GetChnMuxMode(uint32_t baseAddr) { return (adc_chn_mux_mode_t)(BR_ADC_CFG2_MUXSEL(baseAddr) ); } #endif /* FSL_FEATURE_ADC_HAS_MUX_SELECT */ /*! * @brief Switches to enable the asynchronous clock for the ADC module. * * This function switches to enable the asynchronous clock for the ADC module. * It enables the ADC's asynchronous clock source and the clock source * output regardless of the conversion and the input clock select status of the * ADC. Asserting this function allows the clock to be used even while the ADC * is idle or operating from a different clock source. Also, latency of * initiating a single or first-continuous conversion with the asynchronous * clock selected is reduced since the ADC internal clock has been already * operational. * * @param baseAddr Register base address for the module. * @param enable Switcher to asserted the feature. */ static inline void ADC_HAL_SetAsyncClkCmd(uint32_t baseAddr, bool enable) { BW_ADC_CFG2_ADACKEN(baseAddr, (enable ? 1U : 0U) ); } /*! * @brief Switches to enable the high speed mode for the ADC module. * * This function switches to enable the high speed mode for the ADC module. * * @param baseAddr Register base address for the module. * @param enable Switcher to asserted the feature. */ static inline void ADC_HAL_SetHighSpeedCmd(uint32_t baseAddr, bool enable) { BW_ADC_CFG2_ADHSC(baseAddr, (enable ? 1U : 0U) ); } /*! * @brief Selects the long sample cycle mode for the ADC module. * * This function selects the long sample cycle mode for the ADC module. * This function should be called along with "ADC_HAL_SetLongSampleCmd()". * * @param baseAddr Register base address for the module. * @param mode Selection of long sample cycle mode. See the "adc_long_sample_cycle_mode_t". */ static inline void ADC_HAL_SetLongSampleCycleMode(uint32_t baseAddr, adc_long_sample_cycle_mode_t mode) { BW_ADC_CFG2_ADLSTS(baseAddr, (uint32_t)mode ); } /*! * @brief Gets the raw result data of channel conversion for the ADC module. * * This function gets the result data of conversion for the ADC module. * The return value is raw data that is not processed. The unavailable bits would be * filled with "0" in single-ended mode and sign bit in differential mode. * * @param baseAddr Register base address for the module. * @param chnGroup Channel configuration group ID. * @return Conversion value of RAW. */ static inline uint16_t ADC_HAL_GetChnConvValueRAW(uint32_t baseAddr, uint32_t chnGroup ) { assert(chnGroup < FSL_FEATURE_ADC_CONVERSION_CONTROL_COUNT); return (uint16_t)(BR_ADC_Rn_D(baseAddr, chnGroup) ); } /*! * @brief Sets the compare value of the lower limitation for the ADC module. * * This function sets the compare value of the lower limitation for the ADC module. * * @param baseAddr Register base address for the module. * @param value Setting value. */ static inline void ADC_HAL_SetHwCmpValue1(uint32_t baseAddr, uint16_t value) { BW_ADC_CV1_CV(baseAddr,value); } /*! * @brief Sets the compare value of the higher limitation for the ADC module. * * This function sets the compare value of the higher limitation for the ADC module. * * @param baseAddr Register base address for the module. * @param value Setting value. */ static inline void ADC_HAL_SetHwCmpValue2(uint32_t baseAddr, uint16_t value) { BW_ADC_CV2_CV(baseAddr,value); } /*! * @brief Checks whether the converter is active for the ADC module. * * This function checks whether the converter is active for the ADC * module. If it is dis-asserted when the conversion is completed, one of the * completed flag is asserted for the indicated group mux. See the * "ADC_HAL_GetChnConvCompletedCmd()". * * @param baseAddr Register base address for the module. * @return Assertion of that the converter is active. */ static inline bool ADC_HAL_GetConvActiveCmd(uint32_t baseAddr) { return (1U == BR_ADC_SC2_ADACT(baseAddr) ); } /*! * @brief Switches to enable the hardware trigger mode for the ADC module. * * This function switches to enable the hardware trigger mode for the ADC * module. * * @param baseAddr Register base address for the module. * @param enable Switcher to asserted the feature. */ static inline void ADC_HAL_SetHwTriggerCmd(uint32_t baseAddr, bool enable) { BW_ADC_SC2_ADTRG(baseAddr,(enable ? 1U : 0U) ); } /*! * @brief Switches to enable the hardware comparator for the ADC module. * * This function switches to enable the hardware comparator for the ADC module. * * @param baseAddr Register base address for the module. * @param enable Switcher to asserted the feature. */ static inline void ADC_HAL_SetHwCmpCmd(uint32_t baseAddr, bool enable) { BW_ADC_SC2_ACFE(baseAddr, (enable ? 1U : 0U) ); } /*! * @brief Switches to enable the setting that is greater than the hardware comparator. * * This function switches to enable the setting that is greater than the * hardware comparator. * * @param baseAddr Register base address for the module. * @param enable Switcher to asserted the feature. */ static inline void ADC_HAL_SetHwCmpGreaterCmd(uint32_t baseAddr, bool enable) { BW_ADC_SC2_ACFGT(baseAddr, (enable ? 1U : 0U) ); } /*! * @brief Switches to enable the setting of the range for hardware comparator. * * This function switches to enable the setting of range for the hardware * comparator. * * @param baseAddr Register base address for the module. * @param enable Switcher to asserted the feature. */ static inline void ADC_HAL_SetHwCmpRangeCmd(uint32_t baseAddr, bool enable) { BW_ADC_SC2_ACREN(baseAddr, (enable ? 1U : 0U) ); } /*! * @brief Configures the asserted range of the hardware comparator for the ADC module. * * This function configures the asserted range of the hardware comparator for the * ADC module. * * @param baseAddr Register base address for the module. * @param mode Selection of range mode, see to "adc_hw_cmp_range_mode_t". */ void ADC_HAL_SetHwCmpMode(uint32_t baseAddr, adc_hw_cmp_range_mode_t mode); #if FSL_FEATURE_ADC_HAS_DMA /*! * @brief Switches to enable the DMA for the ADC module. * * This function switches to enable the DMA for the ADC module. When enabled, the * DMA request is asserted during the ADC conversion complete event, which is noted * by the assertion of any of the ADC channel completed flags. * * @param baseAddr Register base address for the module. * @param enable Switcher to asserted the feature. */ static inline void ADC_HAL_SetDmaCmd(uint32_t baseAddr, bool enable) { BW_ADC_SC2_DMAEN(baseAddr, (enable ? 1U : 0U) ); } #endif /* FSL_FEATURE_ADC_HAS_DMA */ /*! * @brief Selects the reference voltage source for the ADC module. * * This function selects the reference voltage source for the ADC module. * * @param baseAddr Register base address for the module. * @param mode Selection of asserted the feature. */ static inline void ADC_HAL_SetRefVoltSrcMode(uint32_t baseAddr, adc_ref_volt_src_mode_t mode) { BW_ADC_SC2_REFSEL(baseAddr, (uint32_t)mode ); } #if FSL_FEATURE_ADC_HAS_CALIBRATION /*! * @brief Switches to enable the hardware calibration for the ADC module. * * This function launches the hardware calibration for the ADC module. * * @param baseAddr Register base address for the module. * @param enable Switcher to asserted the feature. */ static inline void ADC_HAL_SetAutoCalibrationCmd(uint32_t baseAddr, bool enable) { BW_ADC_SC3_CAL(baseAddr, (enable ? 1U : 0U) ); } /*! * @brief Gets the hardware calibration status for the ADC module. * * This function gets the status whether the hardware calibration is active * for the ADC module. The return value holds on as asserted during the hardware * calibration. Then, it is cleared and dis-asserted after the * calibration. * * @param baseAddr Register base address for the module. */ static inline bool ADC_HAL_GetAutoCalibrationActiveCmd(uint32_t baseAddr) { return (1U == BR_ADC_SC3_CAL(baseAddr) ); } /*! * @brief Gets the hardware calibration status for the ADC module. * * This function gets the status whether the hardware calibration has failed * for the ADC module. The return value is asserted if there is anything wrong * with the hardware calibration. * * @param baseAddr Register base address for the module. */ static inline bool ADC_HAL_GetAutoCalibrationFailedCmd(uint32_t baseAddr) { return (1U == BR_ADC_SC3_CALF(baseAddr) ); } /*! * @brief Gets and calculates the plus side calibration parameter from the auto calibration. * * This function gets the values of CLP0 - CLP4 and CLPS internally, * accumulates them, and returns the value that can be used to be set in the PG * register directly. Note that this API should be called after the process of * auto calibration is complete. * * @param baseAddr Register base address for the module. * @return value that can be set into PG directly. */ uint16_t ADC_HAL_GetAutoPlusSideGainValue(uint32_t baseAddr); /*! * @brief Sets the plus side gain calibration value for the ADC module. * * This function sets the plus side gain calibration value for the ADC module. * * @param baseAddr Register base address for the module. * @param value Setting value for plus side gain. */ static inline void ADC_HAL_SetPlusSideGainValue(uint32_t baseAddr, uint16_t value) { BW_ADC_PG_PG(baseAddr, value); } #if FSL_FEATURE_ADC_HAS_DIFF_MODE /*! * @brief Gets and calculates the minus side calibration parameter from the auto calibration. * * This function gets the values of CLM0 - CLM4 and CLMS internally, * accumulates them, and returns the value that can be used to be set in the MG * register directly. Note that this API should be called after the process of * auto calibration is complete. * * @param baseAddr Register base address for the module. * @return value that can be set into MG directly. */ uint16_t ADC_HAL_GetAutoMinusSideGainValue(uint32_t baseAddr); /*! * @brief Sets the minus side gain calibration value for the ADC module. * * This function sets the minus side gain calibration value for the ADC module. * * @param baseAddr Register base address for the module. * @param value Setting value for minus side gain. */ static inline void ADC_HAL_SetMinusSideGainValue(uint32_t baseAddr, uint16_t value) { BW_ADC_MG_MG(baseAddr, value); } #endif /* FSL_FEATURE_ADC_HAS_DIFF_MODE */ #endif /* FSL_FEATURE_ADC_HAS_CALIBRATION */ #if FSL_FEATURE_ADC_HAS_OFFSET_CORRECTION /*! * @brief Gets the offset correction value for the ADC module. * * This function gets the offset correction value for the ADC module. * When auto calibration is executed, the OFS register holds the new value * generated by the calibration. It can be left as default or modified * according to the use case. * * @param baseAddr Register base address for the module. * @return current value for OFS. */ static inline uint16_t ADC_HAL_GetOffsetValue(uint32_t baseAddr) { return (uint16_t)(BR_ADC_OFS_OFS(baseAddr) ); } /*! * @brief Sets the offset correction value for the ADC module. * * This function sets the offset correction value for the ADC module. The ADC * offset correction register (OFS) contains the user-selected or calibration-generated * offset error correction value. The value in the offset correction * registers (OFS) is subtracted from the conversion and the result is * transferred into the result registers (Rn). If the result is above the * maximum or below the minimum result value, it is forced to the appropriate * limit for the current mode of operation. * * @param baseAddr Register base address for the module. * @param value Setting value for OFS. */ static inline void ADC_HAL_SetOffsetValue(uint32_t baseAddr, uint16_t value) { BW_ADC_OFS_OFS(baseAddr, value); } #endif /* FSL_FEATURE_ADC_HAS_OFFSET_CORRECTION */ /*! * @brief Switches to enable the continuous conversion mode for the ADC module. * * This function switches to enable the continuous conversion mode for the ADC * module. Once enabled, continuous conversions, or sets of conversions if the * hardware average function, is enabled after initiating a conversion. * * @param baseAddr Register base address for the module. * @param enable Switcher to asserted the feature. */ static inline void ADC_HAL_SetContinuousConvCmd(uint32_t baseAddr, bool enable) { BW_ADC_SC3_ADCO(baseAddr, (enable ? 1U : 0U) ); } #if FSL_FEATURE_ADC_HAS_HW_AVERAGE /*! * @brief Switches to enable the hardware average for the ADC module. * * This function switches to enable the hardware average for the ADC module. * Once enabled, the conversion does not stop before the average * count has been reached. * * @param baseAddr Register base address for the module. * @param enable Switcher to asserted the feature. */ static inline void ADC_HAL_SetHwAverageCmd(uint32_t baseAddr, bool enable) { BW_ADC_SC3_AVGE(baseAddr, (enable ? 1U : 0U) ); } /*! * @brief Selects the hardware average mode for the ADC module. * * This function switches to select the hardware average mode for the ADC * module. * * @param baseAddr Register base address for the module. * @param mode Selection of hardware average count mode, see to "adc_hw_average_count_mode_t". */ static inline void ADC_HAL_SetHwAverageMode(uint32_t baseAddr, adc_hw_average_count_mode_t mode) { BW_ADC_SC3_AVGS(baseAddr, (uint32_t)mode ); } #endif /* FSL_FEATURE_ADC_HAS_HW_AVERAGE */ #if FSL_FEATURE_ADC_HAS_PGA /*! * @brief Switches to enable the Programmable Gain Amplifier for ADC module. * * This function enables the PGA for the ADC module. The Programmable Gain * Amplifier (PGA) is designed to increase the dynamic range by amplifying the * low-amplitude signals before they are fed to the 16 bit SAR ADC. * * @param baseAddr Register base address for the module. * @param enable Switcher to asserted feature. */ static inline void ADC_HAL_SetPgaCmd(uint32_t baseAddr, bool enable) { BW_ADC_PGA_PGAEN(baseAddr, (enable ? 1U : 0U) ); } /*! * @brief Switches to enable the PGA chopping mode for the ADC module. * * This function switches to enable the PGA chopping mode for the ADC module. * The PGA employs chopping to remove/reduce offset and 1/f noise and offers an * offset measurement configuration that aids the offset calibration. * * @param baseAddr Register base address for the module. * @param enable Switcher to asserted feature. */ static inline void ADC_HAL_SetPgaChoppingCmd(uint32_t baseAddr, bool enable) { BW_ADC_PGA_PGACHPb(baseAddr, (enable ? 0U : 1U) ); } /*! * @brief Switches to enable the PGA working in low power mode for the ADC module. * * This function switches to enable the PGA working in low power mode for * ADC module. * * @param baseAddr Register base address for the module. * @param enable Switcher to asserted feature. */ static inline void ADC_HAL_SetPgaLowPowerCmd(uint32_t baseAddr, bool enable) { BW_ADC_PGA_PGALPb(baseAddr, (enable ? 0U : 1U) ); } /*! * @brief Selects the amplifier mode for the PGA. * * This function selects the amplifier mode for the PGA. * * @param baseAddr Register base address for the module. * @param mode Selection of asserted feature. See to "adc_pga_gain_mode_t". */ static inline void ADC_HAL_SetPgaGainMode(uint32_t baseAddr, adc_pga_gain_mode_t mode) { BW_ADC_PGA_PGAG(baseAddr, (uint32_t)mode ); } /*! * @brief Switches to enable the offset measurement mode for the ADC module. * * This function switches to enable the offset measurement mode for the ADC * module. When asserted, the PGA disconnects from the external inputs and * auto-configures into offset measurement mode. With this function asserted, * run the ADC in recommended settings and enable maximum hardware averaging * to get the PGA offset number. The output is the (PGA offset * (64+1)) * for a given setting. * * @param baseAddr Register base address for the module. * @param enable Switcher to asserted feature. */ static inline void ADC_HAL_SetPgaOffsetMeasurementCmd(uint32_t baseAddr, bool enable) { BW_ADC_PGA_PGAOFSM(baseAddr, (enable ? 1U : 0U) ); } #endif /* FSL_FEATURE_ADC_HAS_PGA */ #if defined(__cplusplus) } #endif /*! * @} */ #endif /* __FSL_ADC_HAL_H__ */ /****************************************************************************** * EOF *****************************************************************************/ ================================================ FILE: Zelig/mbed/TARGET_K64F/TARGET_Freescale/TARGET_KPSDK_MCUS/TARGET_KPSDK_CODE/hal/can/fsl_flexcan_features.h ================================================ /* ** ################################################################### ** Version: rev. 1.0, 2014-05-14 ** Build: b140516 ** ** Abstract: ** Chip specific module features. ** ** Copyright: 2014 Freescale Semiconductor, Inc. ** All rights reserved. ** ** Redistribution and use in source and binary forms, with or without modification, ** are permitted provided that the following conditions are met: ** ** o Redistributions of source code must retain the above copyright notice, this list ** of conditions and the following disclaimer. ** ** o Redistributions in binary form must reproduce the above copyright notice, this ** list of conditions and the following disclaimer in the documentation and/or ** other materials provided with the distribution. ** ** o Neither the name of Freescale Semiconductor, Inc. nor the names of its ** contributors may be used to endorse or promote products derived from this ** software without specific prior written permission. ** ** THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ** ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED ** WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE ** DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT 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. ** ** http: www.freescale.com ** mail: support@freescale.com ** ** Revisions: ** - rev. 1.0 (2014-05-14) ** Customer release. ** ** ################################################################### */ #if !defined(__FSL_FLEXCAN_FEATURES_H__) #define __FSL_FLEXCAN_FEATURES_H__ #if defined(CPU_MK24FN1M0VDC12) || defined(CPU_MK24FN1M0VLL12) || defined(CPU_MK24FN1M0VLQ12) || defined(CPU_MK63FN1M0VLQ12) || \ defined(CPU_MK63FN1M0VMD12) || defined(CPU_MK64FX512VDC12) || defined(CPU_MK64FN1M0VDC12) || defined(CPU_MK64FX512VLL12) || \ defined(CPU_MK64FN1M0VLL12) || defined(CPU_MK64FX512VLQ12) || defined(CPU_MK64FN1M0VLQ12) || defined(CPU_MK64FX512VMD12) || \ defined(CPU_MK64FN1M0VMD12) || defined(CPU_MK65FN2M0CAC18) || defined(CPU_MK65FX1M0CAC18) || defined(CPU_MK65FN2M0VMI18) || \ defined(CPU_MK65FX1M0VMI18) || defined(CPU_MK66FN2M0VLQ18) || defined(CPU_MK66FX1M0VLQ18) || defined(CPU_MK66FN2M0VMD18) || \ defined(CPU_MK66FX1M0VMD18) /* @brief Message buffer size */ #define FSL_FEATURE_FLEXCAN_HAS_MESSAGE_BUFFER_MAX_NUMBER (16) /* @brief Has doze mode support (register bit field MCR[DOZE]). */ #define FSL_FEATURE_FLEXCAN_HAS_DOZE_MODE_SUPPORT (0) /* @brief Has a glitch filter on the receive pin (register bit field MCR[WAKSRC]). */ #define FSL_FEATURE_FLEXCAN_HAS_GLITCH_FILTER (1) /* @brief Has extended interrupt mask and flag register (register IMASK2, IFLAG2). */ #define FSL_FEATURE_FLEXCAN_HAS_EXTENDED_FLAG_REGISTER (0) /* @brief Has extended bit timing register (register CBT). */ #define FSL_FEATURE_FLEXCAN_HAS_EXTENDED_TIMING_REGISTER (0) /* @brief Has a receive FIFO DMA feature (register bit field MCR[DMA]). */ #define FSL_FEATURE_FLEXCAN_HAS_RX_FIFO_DMA (0) /* @brief Has separate message buffer 0 interrupt flag (register bit field IFLAG1[BUF0I]). */ #define FSL_FEATURE_FLEXCAN_HAS_SEPARATE_BUFFER_0_FLAG (1) /* @brief Number of interrupt vectors. */ #define FSL_FEATURE_FLEXCAN_INTERRUPT_COUNT (6) #elif defined(CPU_MK70FN1M0VMF12) || defined(CPU_MK70FX512VMF12) || defined(CPU_MK70FN1M0VMF15) || defined(CPU_MK70FX512VMF15) || \ defined(CPU_MK70FN1M0VMJ12) || defined(CPU_MK70FX512VMJ12) || defined(CPU_MK70FN1M0VMJ15) || defined(CPU_MK70FX512VMJ15) /* @brief Message buffer size */ #define FSL_FEATURE_FLEXCAN_HAS_MESSAGE_BUFFER_MAX_NUMBER (16) /* @brief Has doze mode support (register bit field MCR[DOZE]). */ #define FSL_FEATURE_FLEXCAN_HAS_DOZE_MODE_SUPPORT (0) /* @brief Has a glitch filter on the receive pin (register bit field MCR[WAKSRC]). */ #define FSL_FEATURE_FLEXCAN_HAS_GLITCH_FILTER (0) /* @brief Has extended interrupt mask and flag register (register IMASK2, IFLAG2). */ #define FSL_FEATURE_FLEXCAN_HAS_EXTENDED_FLAG_REGISTER (1) /* @brief Has extended bit timing register (register CBT). */ #define FSL_FEATURE_FLEXCAN_HAS_EXTENDED_TIMING_REGISTER (0) /* @brief Has a receive FIFO DMA feature (register bit field MCR[DMA]). */ #define FSL_FEATURE_FLEXCAN_HAS_RX_FIFO_DMA (0) /* @brief Has separate message buffer 0 interrupt flag (register bit field IFLAG1[BUF0I]). */ #define FSL_FEATURE_FLEXCAN_HAS_SEPARATE_BUFFER_0_FLAG (0) /* @brief Number of interrupt vectors. */ #define FSL_FEATURE_FLEXCAN_INTERRUPT_COUNT (6) #elif defined(CPU_MKV40F128VLH15) || defined(CPU_MKV40F128VLL15) || defined(CPU_MKV40F256VLH15) || defined(CPU_MKV40F256VLL15) || \ defined(CPU_MKV40F64VLH15) || defined(CPU_MKV43F128VLH15) || defined(CPU_MKV43F128VLL15) || defined(CPU_MKV43F64VLH15) || \ defined(CPU_MKV44F128VLH15) || defined(CPU_MKV44F128VLL15) || defined(CPU_MKV44F64VLH15) || defined(CPU_MKV45F128VLH15) || \ defined(CPU_MKV45F128VLL15) || defined(CPU_MKV45F256VLH15) || defined(CPU_MKV45F256VLL15) || defined(CPU_MKV46F128VLH15) || \ defined(CPU_MKV46F128VLL15) || defined(CPU_MKV46F256VLH15) || defined(CPU_MKV46F256VLL15) /* @brief Message buffer size */ #define FSL_FEATURE_FLEXCAN_HAS_MESSAGE_BUFFER_MAX_NUMBER (16) /* @brief Has doze mode support (register bit field MCR[DOZE]). */ #define FSL_FEATURE_FLEXCAN_HAS_DOZE_MODE_SUPPORT (1) /* @brief Has a glitch filter on the receive pin (register bit field MCR[WAKSRC]). */ #define FSL_FEATURE_FLEXCAN_HAS_GLITCH_FILTER (1) /* @brief Has extended interrupt mask and flag register (register IMASK2, IFLAG2). */ #define FSL_FEATURE_FLEXCAN_HAS_EXTENDED_FLAG_REGISTER (0) /* @brief Has extended bit timing register (register CBT). */ #define FSL_FEATURE_FLEXCAN_HAS_EXTENDED_TIMING_REGISTER (1) /* @brief Has a receive FIFO DMA feature (register bit field MCR[DMA]). */ #define FSL_FEATURE_FLEXCAN_HAS_RX_FIFO_DMA (1) /* @brief Has separate message buffer 0 interrupt flag (register bit field IFLAG1[BUF0I]). */ #define FSL_FEATURE_FLEXCAN_HAS_SEPARATE_BUFFER_0_FLAG (1) /* @brief Number of interrupt vectors. */ #define FSL_FEATURE_FLEXCAN_INTERRUPT_COUNT (6) #else #define MBED_NO_FLEXCAN #endif #endif /* __FSL_FLEXCAN_FEATURES_H__ */ /******************************************************************************* * EOF ******************************************************************************/ ================================================ FILE: Zelig/mbed/TARGET_K64F/TARGET_Freescale/TARGET_KPSDK_MCUS/TARGET_KPSDK_CODE/hal/can/fsl_flexcan_hal.h ================================================ /* * Copyright (c) 2013 - 2014, Freescale Semiconductor, Inc. * All rights reserved. * * Redistribution and use in source and binary forms, with or without modification, * are permitted provided that the following conditions are met: * * o Redistributions of source code must retain the above copyright notice, this list * of conditions and the following disclaimer. * * o Redistributions in binary form must reproduce the above copyright notice, this * list of conditions and the following disclaimer in the documentation and/or * other materials provided with the distribution. * * o Neither the name of Freescale Semiconductor, Inc. nor the names of its * contributors may be used to endorse or promote products derived from this * software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT 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. */ #ifndef __FSL_FLEXCAN_HAL_H__ #define __FSL_FLEXCAN_HAL_H__ #include #include #include #include "fsl_flexcan_features.h" #include "fsl_device_registers.h" #ifndef MBED_NO_FLEXCAN /*! * @addtogroup flexcan_hal * @{ */ /******************************************************************************* * Definitions ******************************************************************************/ /*! @brief FlexCAN constants*/ enum _flexcan_constants { kFlexCanMessageSize = 8, /*!< FlexCAN message buffer data size in bytes*/ }; /*! @brief The Status enum is used to report current status of the FlexCAN interface.*/ enum _flexcan_err_status { kFlexCan_RxWrn = 0x0080, /*!< Reached warning level for RX errors*/ kFlexCan_TxWrn = 0x0100, /*!< Reached warning level for TX errors*/ kFlexCan_StfErr = 0x0200, /*!< Stuffing Error*/ kFlexCan_FrmErr = 0x0400, /*!< Form Error*/ kFlexCan_CrcErr = 0x0800, /*!< Cyclic Redundancy Check Error*/ kFlexCan_AckErr = 0x1000, /*!< Received no ACK on transmission*/ kFlexCan_Bit0Err = 0x2000, /*!< Unable to send dominant bit*/ kFlexCan_Bit1Err = 0x4000, /*!< Unable to send recessive bit*/ }; /*! @brief FlexCAN status return codes*/ typedef enum _flexcan_status { kStatus_FLEXCAN_Success = 0, kStatus_FLEXCAN_OutOfRange, kStatus_FLEXCAN_UnknownProperty, kStatus_FLEXCAN_InvalidArgument, kStatus_FLEXCAN_Fail, kStatus_FLEXCAN_TimeOut, } flexcan_status_t; /*! @brief FlexCAN operation modes*/ typedef enum _flexcan_operation_modes { kFlexCanNormalMode, /*!< Normal mode or user mode*/ kFlexCanListenOnlyMode, /*!< Listen-only mode*/ kFlexCanLoopBackMode, /*!< Loop-back mode*/ kFlexCanFreezeMode, /*!< Freeze mode*/ kFlexCanDisableMode, /*!< Module disable mode*/ } flexcan_operation_modes_t; /*! @brief FlexCAN message buffer CODE for Rx buffers*/ typedef enum _flexcan_mb_code_rx { kFlexCanRX_Inactive = 0x0, /*!< MB is not active.*/ kFlexCanRX_Full = 0x2, /*!< MB is full.*/ kFlexCanRX_Empty = 0x4, /*!< MB is active and empty.*/ kFlexCanRX_Overrun = 0x6, /*!< MB is overwritten into a full buffer.*/ kFlexCanRX_Busy = 0x8, /*!< FlexCAN is updating the contents of the MB.*/ /*! The CPU must not access the MB.*/ kFlexCanRX_Ranswer = 0xA, /*!< A frame was configured to recognize a Remote Request Frame*/ /*! and transmit a Response Frame in return.*/ kFlexCanRX_NotUsed = 0xF, /*!< Not used*/ } flexcan_mb_code_rx_t; /*! @brief FlexCAN message buffer CODE FOR Tx buffers*/ typedef enum _flexcan_mb_code_tx { kFlexCanTX_Inactive = 0x08, /*!< MB is not active.*/ kFlexCanTX_Abort = 0x09, /*!< MB is aborted.*/ kFlexCanTX_Data = 0x0C, /*!< MB is a TX Data Frame(MB RTR must be 0).*/ kFlexCanTX_Remote = 0x1C, /*!< MB is a TX Remote Request Frame (MB RTR must be 1).*/ kFlexCanTX_Tanswer = 0x0E, /*!< MB is a TX Response Request Frame from.*/ /*! an incoming Remote Request Frame.*/ kFlexCanTX_NotUsed = 0xF, /*!< Not used*/ } flexcan_mb_code_tx_t; /*! @brief FlexCAN message buffer transmission types*/ typedef enum _flexcan_mb_transmission_type { kFlexCanMBStatusType_TX, /*!< Transmit MB*/ kFlexCanMBStatusType_TXRemote, /*!< Transmit remote request MB*/ kFlexCanMBStatusType_RX, /*!< Receive MB*/ kFlexCanMBStatusType_RXRemote, /*!< Receive remote request MB*/ kFlexCanMBStatusType_RXTXRemote, /*!< FlexCAN remote frame receives remote request and*/ /*! transmits MB.*/ } flexcan_mb_transmission_type_t; typedef enum _flexcan_rx_fifo_id_element_format { kFlexCanRxFifoIdElementFormat_A, /*!< One full ID (standard and extended) per ID Filter Table*/ /*! element.*/ kFlexCanRxFifoIdElementFormat_B, /*!< Two full standard IDs or two partial 14-bit (standard and*/ /*! extended) IDs per ID Filter Table element.*/ kFlexCanRxFifoIdElementFormat_C, /*!< Four partial 8-bit Standard IDs per ID Filter Table*/ /*! element.*/ kFlexCanRxFifoIdElementFormat_D, /*!< All frames rejected.*/ } flexcan_rx_fifo_id_element_format_t; /*! @brief FlexCAN Rx FIFO filters number*/ typedef enum _flexcan_rx_fifo_id_filter_number { kFlexCanRxFifoIDFilters_8 = 0x0, /*!< 8 Rx FIFO Filters*/ kFlexCanRxFifoIDFilters_16 = 0x1, /*!< 16 Rx FIFO Filters*/ kFlexCanRxFifoIDFilters_24 = 0x2, /*!< 24 Rx FIFO Filters*/ kFlexCanRxFifoIDFilters_32 = 0x3, /*!< 32 Rx FIFO Filters*/ kFlexCanRxFifoIDFilters_40 = 0x4, /*!< 40 Rx FIFO Filters*/ kFlexCanRxFifoIDFilters_48 = 0x5, /*!< 48 Rx FIFO Filters*/ kFlexCanRxFifoIDFilters_56 = 0x6, /*!< 56 Rx FIFO Filters*/ kFlexCanRxFifoIDFilters_64 = 0x7, /*!< 64 Rx FIFO Filters*/ kFlexCanRxFifoIDFilters_72 = 0x8, /*!< 72 Rx FIFO Filters*/ kFlexCanRxFifoIDFilters_80 = 0x9, /*!< 80 Rx FIFO Filters*/ kFlexCanRxFifoIDFilters_88 = 0xA, /*!< 88 Rx FIFO Filters*/ kFlexCanRxFifoIDFilters_96 = 0xB, /*!< 96 Rx FIFO Filters*/ kFlexCanRxFifoIDFilters_104 = 0xC, /*!< 104 Rx FIFO Filters*/ kFlexCanRxFifoIDFilters_112 = 0xD, /*!< 112 Rx FIFO Filters*/ kFlexCanRxFifoIDFilters_120 = 0xE, /*!< 120 Rx FIFO Filters*/ kFlexCanRxFifoIDFilters_128 = 0xF /*!< 128 Rx FIFO Filters*/ } flexcan_rx_fifo_id_filter_num_t; /*! @brief FlexCAN RX FIFO ID filter table structure*/ typedef struct FLEXCANIdTable { bool is_remote_mb; /*!< Remote frame*/ bool is_extended_mb; /*!< Extended frame*/ uint32_t *id_filter; /*!< Rx FIFO ID filter elements*/ } flexcan_id_table_t; /*! @brief FlexCAN RX mask type.*/ typedef enum _flexcan_rx_mask_type { kFlexCanRxMask_Global, /*!< Rx global mask*/ kFlexCanRxMask_Individual, /*!< Rx individual mask*/ } flexcan_rx_mask_type_t; /*! @brief FlexCAN MB ID type*/ typedef enum _flexcan_mb_id_type { kFlexCanMbId_Std, /*!< Standard ID*/ kFlexCanMbId_Ext, /*!< Extended ID*/ } flexcan_mb_id_type_t; /*! @brief FlexCAN clock source*/ typedef enum _flexcan_clk_source { kFlexCanClkSource_Osc, /*!< Oscillator clock*/ kFlexCanClkSource_Ipbus, /*!< Peripheral clock*/ } flexcan_clk_source_t; /*! @brief FlexCAN error interrupt types*/ typedef enum _flexcan_int_type { kFlexCanInt_Buf, /*!< OR'd message buffers interrupt*/ kFlexCanInt_Err, /*!< Error interrupt*/ kFlexCanInt_Boff, /*!< Bus off interrupt*/ kFlexCanInt_Wakeup, /*!< Wakeup interrupt*/ kFlexCanInt_Txwarning, /*!< TX warning interrupt*/ kFlexCanInt_Rxwarning, /*!< RX warning interrupt*/ } flexcan_int_type_t; /*! @brief FlexCAN bus error counters*/ typedef struct FLEXCANBerrCounter { uint16_t txerr; /*!< Transmit error counter*/ uint16_t rxerr; /*!< Receive error counter*/ } flexcan_berr_counter_t; /*! @brief FlexCAN MB code and status for transmit and receive */ typedef struct FLEXCANMbCodeStatus { uint32_t code; /*!< MB code for TX or RX buffers. Defined by flexcan_mb_code_rx_t and flexcan_mb_code_tx_t */ flexcan_mb_id_type_t msg_id_type; /*!< Type of message ID (standard or extended)*/ uint32_t data_length; /*!< Length of Data in Bytes*/ } flexcan_mb_code_status_t; /*! @brief FlexCAN message buffer structure*/ typedef struct FLEXCANMb { uint32_t cs; /*!< Code and Status*/ uint32_t msg_id; /*!< Message Buffer ID*/ uint8_t data[kFlexCanMessageSize]; /*!< Bytes of the FlexCAN message*/ } flexcan_mb_t; /*! @brief FlexCAN configuration*/ typedef struct FLEXCANUserConfig { uint32_t max_num_mb; /*!< The maximum number of Message Buffers*/ flexcan_rx_fifo_id_filter_num_t num_id_filters; /*!< The number of Rx FIFO ID filters needed*/ bool is_rx_fifo_needed; /*!< 1 if needed; 0 if not*/ } flexcan_user_config_t; /*! @brief FlexCAN timing related structures*/ typedef struct FLEXCANTimeSegment { uint32_t propseg; /*!< Propagation segment*/ uint32_t pseg1; /*!< Phase segment 1*/ uint32_t pseg2; /*!< Phase segment 2*/ uint32_t pre_divider; /*!< Clock pre divider*/ uint32_t rjw; /*!< Resync jump width*/ } flexcan_time_segment_t; /******************************************************************************* * API ******************************************************************************/ #if defined(__cplusplus) extern "C" { #endif /*! * @name Configuration * @{ */ /*! * @brief Enables FlexCAN controller. * * @param canBaseAddr The FlexCAN base address * @return 0 if successful; non-zero failed */ flexcan_status_t FLEXCAN_HAL_Enable(uint32_t canBaseAddr); /*! * @brief Disables FlexCAN controller. * * @param canBaseAddr The FlexCAN base address * @return 0 if successful; non-zero failed */ flexcan_status_t FLEXCAN_HAL_Disable(uint32_t canBaseAddr); /*! * @brief Checks whether the FlexCAN is enabled or disabled. * * @param canBaseAddr The FlexCAN base address * @return State of FlexCAN enable(0)/disable(1) */ static inline bool FLEXCAN_HAL_IsEnabled(uint32_t canBaseAddr) { return BR_CAN_MCR_MDIS(canBaseAddr); } /*! * @brief Selects the clock source for FlexCAN. * * @param canBaseAddr The FlexCAN base address * @param clk The FlexCAN clock source * @return 0 if successful; non-zero failed */ flexcan_status_t FLEXCAN_HAL_SelectClock(uint32_t canBaseAddr, flexcan_clk_source_t clk); /*! * @brief Initializes the FlexCAN controller. * * @param canBaseAddr The FlexCAN base address * @param data The FlexCAN platform data. * @return 0 if successful; non-zero failed */ flexcan_status_t FLEXCAN_HAL_Init(uint32_t canBaseAddr, const flexcan_user_config_t *data); /*! * @brief Sets the FlexCAN time segments for setting up bit rate. * * @param canBaseAddr The FlexCAN base address * @param time_seg FlexCAN time segments, which need to be set for the bit rate. * @return 0 if successful; non-zero failed */ void FLEXCAN_HAL_SetTimeSegments(uint32_t canBaseAddr, flexcan_time_segment_t *time_seg); /*! * @brief Gets the FlexCAN time segments to calculate the bit rate. * * @param canBaseAddr The FlexCAN base address * @param time_seg FlexCAN time segments read for bit rate * @return 0 if successful; non-zero failed */ void FLEXCAN_HAL_GetTimeSegments(uint32_t canBaseAddr, flexcan_time_segment_t *time_seg); /*! * @brief Un freezes the FlexCAN module. * * @param canBaseAddr The FlexCAN base address * @return 0 if successful; non-zero failed. */ void FLEXCAN_HAL_ExitFreezeMode(uint32_t canBaseAddr); /*! * @brief Freezes the FlexCAN module. * * @param canBaseAddr The FlexCAN base address */ void FLEXCAN_HAL_EnterFreezeMode(uint32_t canBaseAddr); /*! * @brief Enables operation mode. * * @param canBaseAddr The FlexCAN base address * @param mode An operation mode to be enabled * @return 0 if successful; non-zero failed. */ flexcan_status_t FLEXCAN_HAL_EnableOperationMode( uint32_t canBaseAddr, flexcan_operation_modes_t mode); /*! * @brief Disables operation mode. * * @param canBaseAddr The FlexCAN base address * @param mode An operation mode to be disabled * @return 0 if successful; non-zero failed. */ flexcan_status_t FLEXCAN_HAL_DisableOperationMode( uint32_t canBaseAddr, flexcan_operation_modes_t mode); /*@}*/ /*! * @name Data transfer * @{ */ /*! * @brief Sets the FlexCAN message buffer fields for transmitting. * * @param canBaseAddr The FlexCAN base address * @param data The FlexCAN platform data * @param mb_idx Index of the message buffer * @param cs CODE/status values (TX) * @param msg_id ID of the message to transmit * @param mb_data Bytes of the FlexCAN message * @return 0 if successful; non-zero failed */ flexcan_status_t FLEXCAN_HAL_SetMbTx( uint32_t canBaseAddr, const flexcan_user_config_t *data, uint32_t mb_idx, flexcan_mb_code_status_t *cs, uint32_t msg_id, uint8_t *mb_data); /*! * @brief Sets the FlexCAN message buffer fields for receiving. * * @param canBaseAddr The FlexCAN base address * @param data The FlexCAN platform data * @param mb_idx Index of the message buffer * @param cs CODE/status values (RX) * @param msg_id ID of the message to receive * @return 0 if successful; non-zero failed */ flexcan_status_t FLEXCAN_HAL_SetMbRx( uint32_t canBaseAddr, const flexcan_user_config_t *data, uint32_t mb_idx, flexcan_mb_code_status_t *cs, uint32_t msg_id); /*! * @brief Gets the FlexCAN message buffer fields. * * @param canBaseAddr The FlexCAN base address * @param data The FlexCAN platform data * @param mb_idx Index of the message buffer * @param mb The fields of the message buffer * @return 0 if successful; non-zero failed */ flexcan_status_t FLEXCAN_HAL_GetMb( uint32_t canBaseAddr, const flexcan_user_config_t *data, uint32_t mb_idx, flexcan_mb_t *mb); /*! * @brief Locks the FlexCAN Rx message buffer. * * @param canBaseAddr The FlexCAN base address * @param data The FlexCAN platform data * @param mb_idx Index of the message buffer * @return 0 if successful; non-zero failed */ flexcan_status_t FLEXCAN_HAL_LockRxMb( uint32_t canBaseAddr, const flexcan_user_config_t *data, uint32_t mb_idx); /*! * @brief Unlocks the FlexCAN Rx message buffer. * * @param canBaseAddr The FlexCAN base address * @return 0 if successful; non-zero failed */ static inline void FLEXCAN_HAL_UnlockRxMb(uint32_t canBaseAddr) { /* Unlock the mailbox */ HW_CAN_TIMER_RD(canBaseAddr); } /*! * @brief Enables the Rx FIFO. * * @param canBaseAddr The FlexCAN base address */ void FLEXCAN_HAL_EnableRxFifo(uint32_t canBaseAddr); /*! * @brief Disables the Rx FIFO. * * @param canBaseAddr The FlexCAN base address */ void FLEXCAN_HAL_DisableRxFifo(uint32_t canBaseAddr); /*! * @brief Sets the number of the Rx FIFO filters. * * @param canBaseAddr The FlexCAN base address * @param number The number of Rx FIFO filters */ void FLEXCAN_HAL_SetRxFifoFiltersNumber(uint32_t canBaseAddr, uint32_t number); /*! * @brief Sets the maximum number of Message Buffers. * * @param canBaseAddr The FlexCAN base address * @param data The FlexCAN platform data */ void FLEXCAN_HAL_SetMaxMbNumber( uint32_t canBaseAddr, const flexcan_user_config_t *data); /*! * @brief Sets the Rx FIFO ID filter table elements. * * @param canBaseAddr The FlexCAN base address * @param data The FlexCAN platform data * @param id_format The format of the Rx FIFO ID Filter Table Elements * @param id_filter_table The ID filter table elements which contain if RTR bit, * IDE bit and RX message ID need to be set. * @return 0 if successful; non-zero failed. */ flexcan_status_t FLEXCAN_HAL_SetIdFilterTableElements( uint32_t canBaseAddr, const flexcan_user_config_t *data, flexcan_rx_fifo_id_element_format_t id_format, flexcan_id_table_t *id_filter_table); /*! * @brief Sets the FlexCAN Rx FIFO fields. * * @param canBaseAddr The FlexCAN base address * @param data The FlexCAN platform data * @param id_format The format of the Rx FIFO ID Filter Table Elements * @param id_filter_table The ID filter table elements which contain RTR bit, IDE bit, * and RX message ID. * @return 0 if successful; non-zero failed. */ flexcan_status_t FLEXCAN_HAL_SetRxFifo( uint32_t canBaseAddr, const flexcan_user_config_t *data, flexcan_rx_fifo_id_element_format_t id_format, flexcan_id_table_t *id_filter_table); /*! * @brief Gets the FlexCAN Rx FIFO data. * * @param canBaseAddr The FlexCAN base address * @param rx_fifo The FlexCAN receive FIFO data * @return 0 if successful; non-zero failed. */ flexcan_status_t FLEXCAN_HAL_ReadFifo( uint32_t canBaseAddr, flexcan_mb_t *rx_fifo); /*@}*/ /*! * @name Interrupts * @{ */ /*! * @brief Enables the FlexCAN Message Buffer interrupt. * * @param canBaseAddr The FlexCAN base address * @param data The FlexCAN platform data * @param mb_idx Index of the message buffer * @return 0 if successful; non-zero failed */ flexcan_status_t FLEXCAN_HAL_EnableMbInt( uint32_t canBaseAddr, const flexcan_user_config_t *data, uint32_t mb_idx); /*! * @brief Disables the FlexCAN Message Buffer interrupt. * * @param canBaseAddr The FlexCAN base address * @param data The FlexCAN platform data * @param mb_idx Index of the message buffer * @return 0 if successful; non-zero failed */ flexcan_status_t FLEXCAN_HAL_DisableMbInt( uint32_t canBaseAddr, const flexcan_user_config_t *data, uint32_t mb_idx); /*! * @brief Enables error interrupt of the FlexCAN module. * @param canBaseAddr The FlexCAN base address */ void FLEXCAN_HAL_EnableErrInt(uint32_t canBaseAddr); /*! * @brief Disables error interrupt of the FlexCAN module. * * @param canBaseAddr The FlexCAN base address */ void FLEXCAN_HAL_DisableErrInt(uint32_t canBaseAddr); /*! * @brief Enables Bus off interrupt of the FlexCAN module. * * @param canBaseAddr The FlexCAN base address */ void FLEXCAN_HAL_EnableBusOffInt(uint32_t canBaseAddr); /*! * @brief Disables Bus off interrupt of the FlexCAN module. * * @param canBaseAddr The FlexCAN base address */ void FLEXCAN_HAL_DisableBusOffInt(uint32_t canBaseAddr); /*! * @brief Enables Wakeup interrupt of the FlexCAN module. * * @param canBaseAddr The FlexCAN base address */ void FLEXCAN_HAL_EnableWakeupInt(uint32_t canBaseAddr); /*! * @brief Disables Wakeup interrupt of the FlexCAN module. * * @param canBaseAddr The FlexCAN base address */ void FLEXCAN_HAL_DisableWakeupInt(uint32_t canBaseAddr); /*! * @brief Enables TX warning interrupt of the FlexCAN module * * @param canBaseAddr The FlexCAN base address */ void FLEXCAN_HAL_EnableTxWarningInt(uint32_t canBaseAddr); /*! * @brief Disables TX warning interrupt of the FlexCAN module. * * @param canBaseAddr The FlexCAN base address */ void FLEXCAN_HAL_DisableTxWarningInt(uint32_t canBaseAddr); /*! * @brief Enables RX warning interrupt of the FlexCAN module. * * @param canBaseAddr The FlexCAN base address */ void FLEXCAN_HAL_EnableRxWarningInt(uint32_t canBaseAddr); /*! * @brief Disables RX warning interrupt of the FlexCAN module. * * @param canBaseAddr The FlexCAN base address */ void FLEXCAN_HAL_DisableRxWarningInt(uint32_t canBaseAddr); /*@}*/ /*! * @name Status * @{ */ /*! * @brief Gets the value of FlexCAN freeze ACK. * * @param canBaseAddr The FlexCAN base address * @return freeze ACK state (1-freeze mode, 0-not in freeze mode). */ static inline uint32_t FLEXCAN_HAL_GetFreezeAck(uint32_t canBaseAddr) { return HW_CAN_MCR(canBaseAddr).B.FRZACK; } /*! * @brief Gets the individual FlexCAN MB interrupt flag. * * @param canBaseAddr The FlexCAN base address * @param data The FlexCAN platform data * @param mb_idx Index of the message buffer * @return the individual MB interrupt flag (0 and 1 are the flag value) */ uint8_t FLEXCAN_HAL_GetMbIntFlag( uint32_t canBaseAddr, const flexcan_user_config_t *data, uint32_t mb_idx); /*! * @brief Gets all FlexCAN MB interrupt flags. * * @param canBaseAddr The FlexCAN base address * @return all MB interrupt flags */ static inline uint32_t FLEXCAN_HAL_GetAllMbIntFlags(uint32_t canBaseAddr) { return HW_CAN_IFLAG1_RD(canBaseAddr); } /*! * @brief Clears the interrupt flag of the message buffers. * * @param canBaseAddr The FlexCAN base address * @param reg_val The value to be written to the interrupt flag1 register. */ /* See fsl_flexcan_hal.h for documentation of this function.*/ static inline void FLEXCAN_HAL_ClearMbIntFlag( uint32_t canBaseAddr, uint32_t reg_val) { /* Clear the corresponding message buffer interrupt flag*/ HW_CAN_IFLAG1_SET(canBaseAddr, reg_val); } /*! * @brief Gets the transmit error counter and receives the error counter. * * @param canBaseAddr The FlexCAN base address * @param err_cnt Transmit error counter and receive error counter */ void FLEXCAN_HAL_GetErrCounter( uint32_t canBaseAddr, flexcan_berr_counter_t *err_cnt); /*! * @brief Gets error and status. * * @param canBaseAddr The FlexCAN base address * @return The current error and status */ static inline uint32_t FLEXCAN_HAL_GetErrStatus(uint32_t canBaseAddr) { return HW_CAN_ESR1_RD(canBaseAddr); } /*! * @brief Clears all other interrupts in ERRSTAT register (Error, Busoff, Wakeup). * * @param canBaseAddr The FlexCAN base address */ void FLEXCAN_HAL_ClearErrIntStatus(uint32_t canBaseAddr); /*@}*/ /*! * @name Mask * @{ */ /*! * @brief Sets the Rx masking type. * * @param canBaseAddr The FlexCAN base address * @param type The FlexCAN Rx mask type */ void FLEXCAN_HAL_SetMaskType(uint32_t canBaseAddr, flexcan_rx_mask_type_t type); /*! * @brief Sets the FlexCAN RX FIFO global standard mask. * * @param canBaseAddr The FlexCAN base address * @param std_mask Standard mask */ void FLEXCAN_HAL_SetRxFifoGlobalStdMask( uint32_t canBaseAddr, uint32_t std_mask); /*! * @brief Sets the FlexCAN Rx FIFO global extended mask. * * @param canBaseAddr The FlexCAN base address * @param ext_mask Extended mask */ void FLEXCAN_HAL_SetRxFifoGlobalExtMask( uint32_t canBaseAddr, uint32_t ext_mask); /*! * @brief Sets the FlexCAN Rx individual standard mask for ID filtering in the Rx MBs and the Rx FIFO. * * @param canBaseAddr The FlexCAN base address * @param data The FlexCAN platform data * @param mb_idx Index of the message buffer * @param std_mask Individual standard mask * @return 0 if successful; non-zero failed */ flexcan_status_t FLEXCAN_HAL_SetRxIndividualStdMask( uint32_t canBaseAddr, const flexcan_user_config_t * data, uint32_t mb_idx, uint32_t std_mask); /*! * @brief Sets the FlexCAN Rx individual extended mask for ID filtering in the Rx MBs and the Rx FIFO. * * @param canBaseAddr The FlexCAN base address * @param data The FlexCAN platform data * @param mb_idx Index of the message buffer * @param ext_mask Individual extended mask * @return 0 if successful; non-zero failed */ flexcan_status_t FLEXCAN_HAL_SetRxIndividualExtMask( uint32_t canBaseAddr, const flexcan_user_config_t * data, uint32_t mb_idx, uint32_t ext_mask); /*! * @brief Sets the FlexCAN Rx MB global standard mask. * * @param canBaseAddr The FlexCAN base address * @param std_mask Standard mask */ void FLEXCAN_HAL_SetRxMbGlobalStdMask( uint32_t canBaseAddr, uint32_t std_mask); /*! * @brief Sets the FlexCAN RX MB BUF14 standard mask. * * @param canBaseAddr The FlexCAN base address * @param std_mask Standard mask */ void FLEXCAN_HAL_SetRxMbBuf14StdMask( uint32_t canBaseAddr, uint32_t std_mask); /*! * @brief Sets the FlexCAN Rx MB BUF15 standard mask. * * @param canBaseAddr The FlexCAN base address * @param std_mask Standard mask * @return 0 if successful; non-zero failed */ void FLEXCAN_HAL_SetRxMbBuf15StdMask( uint32_t canBaseAddr, uint32_t std_mask); /*! * @brief Sets the FlexCAN RX MB global extended mask. * * @param canBaseAddr The FlexCAN base address * @param ext_mask Extended mask */ void FLEXCAN_HAL_SetRxMbGlobalExtMask( uint32_t canBaseAddr, uint32_t ext_mask); /*! * @brief Sets the FlexCAN RX MB BUF14 extended mask. * * @param canBaseAddr The FlexCAN base address * @param ext_mask Extended mask */ void FLEXCAN_HAL_SetRxMbBuf14ExtMask( uint32_t canBaseAddr, uint32_t ext_mask); /*! * @brief Sets the FlexCAN RX MB BUF15 extended mask. * * @param canBaseAddr The FlexCAN base address * @param ext_mask Extended mask */ void FLEXCAN_HAL_SetRxMbBuf15ExtMask( uint32_t canBaseAddr, uint32_t ext_mask); /*! * @brief Gets the FlexCAN ID acceptance filter hit indicator on Rx FIFO. * * @param canBaseAddr The FlexCAN base address * @return RX FIFO information */ static inline uint32_t FLEXCAN_HAL_GetIdAcceptanceFilterRxFifo(uint32_t canBaseAddr) { return BR_CAN_RXFIR_IDHIT(canBaseAddr); } /*@}*/ #if defined(__cplusplus) } #endif /*! @}*/ #endif /* MBED_NO_FLEXCAN */ #endif /* __FSL_FLEXCAN_HAL_H__*/ /******************************************************************************* * EOF ******************************************************************************/ ================================================ FILE: Zelig/mbed/TARGET_K64F/TARGET_Freescale/TARGET_KPSDK_MCUS/TARGET_KPSDK_CODE/hal/dac/fsl_dac_features.h ================================================ /* ** ################################################################### ** Version: rev. 1.0, 2014-05-14 ** Build: b140515 ** ** Abstract: ** Chip specific module features. ** ** Copyright: 2014 Freescale Semiconductor, Inc. ** All rights reserved. ** ** Redistribution and use in source and binary forms, with or without modification, ** are permitted provided that the following conditions are met: ** ** o Redistributions of source code must retain the above copyright notice, this list ** of conditions and the following disclaimer. ** ** o Redistributions in binary form must reproduce the above copyright notice, this ** list of conditions and the following disclaimer in the documentation and/or ** other materials provided with the distribution. ** ** o Neither the name of Freescale Semiconductor, Inc. nor the names of its ** contributors may be used to endorse or promote products derived from this ** software without specific prior written permission. ** ** THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ** ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED ** WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE ** DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT 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. ** ** http: www.freescale.com ** mail: support@freescale.com ** ** Revisions: ** - rev. 1.0 (2014-05-14) ** Customer release. ** ** ################################################################### */ #if !defined(__FSL_DAC_FEATURES_H__) #define __FSL_DAC_FEATURES_H__ #if defined(CPU_MK02FN128VFM10) || defined(CPU_MK02FN64VFM10) || defined(CPU_MK02FN128VLF10) || defined(CPU_MK02FN64VLF10) || \ defined(CPU_MK02FN128VLH10) || defined(CPU_MK02FN64VLH10) || defined(CPU_MK22FN128VDC10) || defined(CPU_MK22FN128VLH10) || \ defined(CPU_MK22FN128VLL10) || defined(CPU_MK22FN128VMP10) || defined(CPU_MK22FN256VDC12) || defined(CPU_MK22FN256VLH12) || \ defined(CPU_MK22FN256VLL12) || defined(CPU_MK22FN256VMP12) || defined(CPU_MK22FN512VDC12) || defined(CPU_MK22FN512VLH12) || \ defined(CPU_MK22FN512VLL12) || defined(CPU_MK24FN1M0VDC12) || defined(CPU_MK24FN1M0VLL12) || defined(CPU_MK24FN1M0VLQ12) || \ defined(CPU_MK24FN256VDC12) || defined(CPU_MK63FN1M0VLQ12) || defined(CPU_MK63FN1M0VMD12) || defined(CPU_MK64FX512VDC12) || \ defined(CPU_MK64FN1M0VDC12) || defined(CPU_MK64FX512VLL12) || defined(CPU_MK64FN1M0VLL12) || defined(CPU_MK64FX512VLQ12) || \ defined(CPU_MK64FN1M0VLQ12) || defined(CPU_MK64FX512VMD12) || defined(CPU_MK64FN1M0VMD12) || defined(CPU_MK65FN2M0CAC18) || \ defined(CPU_MK65FX1M0CAC18) || defined(CPU_MK65FN2M0VMI18) || defined(CPU_MK65FX1M0VMI18) || defined(CPU_MK66FN2M0VLQ18) || \ defined(CPU_MK66FX1M0VLQ18) || defined(CPU_MK66FN2M0VMD18) || defined(CPU_MK66FX1M0VMD18) || defined(CPU_MK70FN1M0VMF12) || \ defined(CPU_MK70FX512VMF12) || defined(CPU_MK70FN1M0VMF15) || defined(CPU_MK70FX512VMF15) || defined(CPU_MK70FN1M0VMJ12) || \ defined(CPU_MK70FX512VMJ12) || defined(CPU_MK70FN1M0VMJ15) || defined(CPU_MK70FX512VMJ15) || defined(CPU_MKV30F128VFM10) || \ defined(CPU_MKV30F64VFM10) || defined(CPU_MKV30F128VLF10) || defined(CPU_MKV30F64VLF10) || defined(CPU_MKV30F128VLH10) || \ defined(CPU_MKV30F64VLH10) || defined(CPU_MKV31F128VLH10) || defined(CPU_MKV31F128VLL10) || defined(CPU_MKV31F256VLH12) || \ defined(CPU_MKV31F256VLL12) || defined(CPU_MKV31F512VLH12) || defined(CPU_MKV31F512VLL12) || defined(CPU_MKV44F128VLH15) || \ defined(CPU_MKV44F128VLL15) || defined(CPU_MKV44F64VLH15) || defined(CPU_MKV46F128VLH15) || defined(CPU_MKV46F128VLL15) || \ defined(CPU_MKV46F256VLH15) || defined(CPU_MKV46F256VLL15) /* @brief Define the size of hardware buffer */ #define FSL_FEATURE_DAC_BUFFER_SIZE (16) /* @brief Define has watermark event detection or not. */ #define FSL_FEATURE_DAC_HAS_WATERMARK_DETECTION (1) #elif defined(CPU_MKL05Z8VFK4) || defined(CPU_MKL05Z16VFK4) || defined(CPU_MKL05Z32VFK4) || defined(CPU_MKL05Z8VLC4) || \ defined(CPU_MKL05Z16VLC4) || defined(CPU_MKL05Z32VLC4) || defined(CPU_MKL05Z8VFM4) || defined(CPU_MKL05Z16VFM4) || \ defined(CPU_MKL05Z32VFM4) || defined(CPU_MKL05Z16VLF4) || defined(CPU_MKL05Z32VLF4) || defined(CPU_MKL13Z64VFM4) || \ defined(CPU_MKL13Z128VFM4) || defined(CPU_MKL13Z256VFM4) || defined(CPU_MKL13Z64VFT4) || defined(CPU_MKL13Z128VFT4) || \ defined(CPU_MKL13Z256VFT4) || defined(CPU_MKL13Z64VLH4) || defined(CPU_MKL13Z128VLH4) || defined(CPU_MKL13Z256VLH4) || \ defined(CPU_MKL13Z64VMP4) || defined(CPU_MKL13Z128VMP4) || defined(CPU_MKL13Z256VMP4) || defined(CPU_MKL23Z64VFM4) || \ defined(CPU_MKL23Z128VFM4) || defined(CPU_MKL23Z256VFM4) || defined(CPU_MKL23Z64VFT4) || defined(CPU_MKL23Z128VFT4) || \ defined(CPU_MKL23Z256VFT4) || defined(CPU_MKL23Z64VLH4) || defined(CPU_MKL23Z128VLH4) || defined(CPU_MKL23Z256VLH4) || \ defined(CPU_MKL23Z64VMP4) || defined(CPU_MKL23Z128VMP4) || defined(CPU_MKL23Z256VMP4) || defined(CPU_MKL25Z32VFM4) || \ defined(CPU_MKL25Z64VFM4) || defined(CPU_MKL25Z128VFM4) || defined(CPU_MKL25Z32VFT4) || defined(CPU_MKL25Z64VFT4) || \ defined(CPU_MKL25Z128VFT4) || defined(CPU_MKL25Z32VLH4) || defined(CPU_MKL25Z64VLH4) || defined(CPU_MKL25Z128VLH4) || \ defined(CPU_MKL25Z32VLK4) || defined(CPU_MKL25Z64VLK4) || defined(CPU_MKL25Z128VLK4) || defined(CPU_MKL26Z256VLK4) || \ defined(CPU_MKL26Z128VLL4) || defined(CPU_MKL26Z256VLL4) || defined(CPU_MKL26Z128VMC4) || defined(CPU_MKL26Z256VMC4) || \ defined(CPU_MKL33Z128VLH4) || defined(CPU_MKL33Z256VLH4) || defined(CPU_MKL33Z128VMP4) || defined(CPU_MKL33Z256VMP4) || \ defined(CPU_MKL43Z64VLH4) || defined(CPU_MKL43Z128VLH4) || defined(CPU_MKL43Z256VLH4) || defined(CPU_MKL43Z64VMP4) || \ defined(CPU_MKL43Z128VMP4) || defined(CPU_MKL43Z256VMP4) || defined(CPU_MKL46Z128VLH4) || defined(CPU_MKL46Z256VLH4) || \ defined(CPU_MKL46Z128VLL4) || defined(CPU_MKL46Z256VLL4) || defined(CPU_MKL46Z128VMC4) || defined(CPU_MKL46Z256VMC4) /* @brief Define the size of hardware buffer */ #define FSL_FEATURE_DAC_BUFFER_SIZE (2) /* @brief Define has watermark event detection or not. */ #define FSL_FEATURE_DAC_HAS_WATERMARK_DETECTION (0) #else #error "No valid CPU defined!" #endif #endif /* __FSL_DAC_FEATURES_H__ */ /******************************************************************************* * EOF ******************************************************************************/ ================================================ FILE: Zelig/mbed/TARGET_K64F/TARGET_Freescale/TARGET_KPSDK_MCUS/TARGET_KPSDK_CODE/hal/dac/fsl_dac_hal.h ================================================ /* * Copyright (c) 2013 - 2014, Freescale Semiconductor, Inc. * All rights reserved. * * Redistribution and use in source and binary forms, with or without modification, * are permitted provided that the following conditions are met: * * o Redistributions of source code must retain the above copyright notice, this list * of conditions and the following disclaimer. * * o Redistributions in binary form must reproduce the above copyright notice, this * list of conditions and the following disclaimer in the documentation and/or * other materials provided with the distribution. * * o Neither the name of Freescale Semiconductor, Inc. nor the names of its * contributors may be used to endorse or promote products derived from this * software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT 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. */ #ifndef __FSL_DAC_HAL_H__ #define __FSL_DAC_HAL_H__ #include #include #include #include "fsl_device_registers.h" #include "fsl_dac_features.h" /*! * @addtogroup dac_hal * @{ */ /****************************************************************************** * Definitions *****************************************************************************/ /*! * @brief DAC status return codes. */ typedef enum _dac_status { kStatus_DAC_Success = 0U, /*!< Success. */ kStatus_DAC_InvalidArgument = 1U, /*!< Invalid argument existed. */ kStatus_DAC_Failed = 2U /*!< Execution failed. */ } dac_status_t; /*! * @brief Defines the type of selection for DAC module's reference voltage source. * * See the appropriate SoC Reference Manual for actual connections. */ typedef enum _dac_ref_volt_src_mode { kDacRefVoltSrcOfVref1 = 0U, /*!< Select DACREF_1 as the reference voltage. */ kDacRefVoltSrcOfVref2 = 1U, /*!< Select DACREF_2 as the reference voltage. */ } dac_ref_volt_src_mode_t; /*! * @brief Defines the type of selection for DAC module trigger mode. */ typedef enum _dac_trigger_mode { kDacTriggerByHardware = 0U, /*!< Select hardware trigger. */ kDacTriggerBySoftware = 1U /*!< Select software trigger. */ } dac_trigger_mode_t; /*! * @brief Defines the type of selection for buffer watermark mode. * * If the buffer feature for DAC module is enabled, a watermark event will * occur when the buffer index hits the watermark. */ typedef enum _dac_buff_watermark_mode { kDacBuffWatermarkFromUpperAs1Word = 0U, /*!< Select 1 word away from the upper of buffer. */ kDacBuffWatermarkFromUpperAs2Word = 1U, /*!< Select 2 word away from the upper of buffer. */ kDacBuffWatermarkFromUpperAs3Word = 2U, /*!< Select 3 word away from the upper of buffer. */ kDacBuffWatermarkFromUpperAs4Word = 3U, /*!< Select 4 word away from the upper of buffer. */ } dac_buff_watermark_mode_t; /*! * @brief Defines the type of selection for buffer work mode. * * There are three kinds of work modes when the DAC buffer is enabled. * Normal mode - When the buffer index hits the upper level, it * starts (0) on the next trigger. * Swing mode - When the buffer index hits the upper level, it goes backward to * the start and is reduced one-by-one on the next trigger. When the buffer index * hits the start, it goes backward to the upper level and increases one-by-one * on the next trigger. * One-Time-Scan mode - The buffer index can only be increased on the next trigger. * When the buffer index hits the upper level, it is not updated by the trigger. * FIFO mode */ typedef enum _dac_buff_work_mode { kDacBuffWorkAsNormalMode = 0U, /*!< Buffer works as Normal. */ kDacBuffWorkAsSwingMode = 1U, /*!< Buffer works as swing. */ kDacBuffWorkAsOneTimeScanMode = 2U, /*!< Buffer works as one time scan.*/ kDacBuffWorkAsFIFOMode = 3U /*!< Buffer works as FIFO.*/ } dac_buff_work_mode_t; #if defined(__cplusplus) extern "C" { #endif /******************************************************************************* * API ******************************************************************************/ /*! * @brief Resets all configurable registers to be in the reset state for DAC. * * This function resets all configurable registers to be in the reset state for DAC. * It should be called before configuring the DAC module. * * @param baseAddr The DAC peripheral base address. */ void DAC_HAL_Init(uint32_t baseAddr); /*! * @brief Sets the 12-bit value for the DAC items in the buffer. * * This function sets the value assembled by the low 8 bits and high 4 * bits of 12-bit DAC item in the buffer. * * @param baseAddr The DAC peripheral base address. * @param index Buffer index. * @param value Setting value. */ void DAC_HAL_SetBuffValue(uint32_t baseAddr, uint8_t index, uint16_t value); /*! * @brief Gets the 12-bit value from the DAC item in the buffer. * * This function gets the value assembled by the low 8 bits and high 4 * bits of 12-bit DAC item in the buffer. * * @param baseAddr The DAC peripheral base address. * @param index Buffer index. * @return Current setting value. */ uint16_t DAC_HAL_GetBuffValue(uint32_t baseAddr, uint8_t index); /*! * @brief Clears the flag of the DAC buffer read pointer. * * This function clears the flag of the DAC buffer read pointer when it hits the * bottom position. * * @param baseAddr The DAC peripheral base address. */ static inline void DAC_HAL_ClearBuffIndexUpperFlag(uint32_t baseAddr) { BW_DAC_SR_DACBFRPBF(baseAddr, 0U); } /*! * @brief Gets the flag of DAC buffer read pointer when it hits the bottom position. * * This function gets the flag of DAC buffer read pointer when it hits the * bottom position. * * @param baseAddr The DAC peripheral base address. * @return Assertion of indicated event. */ static inline bool DAC_HAL_GetBuffIndexUpperFlag(uint32_t baseAddr) { return ( 1U == BR_DAC_SR_DACBFRPBF(baseAddr) ); } /*! * @brief Clears the flag of the DAC buffer read pointer when it hits the top position. * * This function clears the flag of the DAC buffer read pointer when it hits the * top position. * * @param baseAddr The DAC peripheral base address. */ static inline void DAC_HAL_ClearBuffIndexStartFlag(uint32_t baseAddr) { BW_DAC_SR_DACBFRPTF(baseAddr, 0U); } /*! * @brief Gets the flag of the DAC buffer read pointer when it hits the top position. * * This function gets the flag of the DAC buffer read pointer when it hits the * top position. * * @param baseAddr The DAC peripheral base address. * @return Assertion of indicated event. */ static inline bool DAC_HAL_GetBuffIndexStartFlag(uint32_t baseAddr) { return ( 1U == BR_DAC_SR_DACBFRPTF(baseAddr) ); } #if FSL_FEATURE_DAC_HAS_WATERMARK_DETECTION /*! * @brief Gets the flag of the DAC buffer read pointer when it hits the watermark position. * * This function gets the flag of the DAC buffer read pointer when it hits the * watermark position. * * @param baseAddr The DAC peripheral base address. * @return Assertion of indicated event. */ static inline bool DAC_HAL_GetBuffIndexWatermarkFlag(uint32_t baseAddr) { return ( 1U == BR_DAC_SR_DACBFWMF(baseAddr) ); } /*! * @brief Clears the flag of the DAC buffer read pointer when it hits the watermark position. * * This function clears the flag of the DAC buffer read pointer when it hits the * watermark position. * * @param baseAddr The DAC peripheral base address. * @return Assertion of indicated event. */ static inline void DAC_HAL_ClearBuffIndexWatermarkFlag(uint32_t baseAddr) { BW_DAC_SR_DACBFWMF(baseAddr, 0U); } #endif /* FSL_FEATURE_DAC_HAS_WATERMARK_DETECTION */ /*! * @brief Enables the Programmable Reference Generator. * * This function enables the Programmable Reference Generator. Then the * DAC system is enabled. * * @param baseAddr The DAC peripheral base address. */ static inline void DAC_HAL_Enable(uint32_t baseAddr) { BW_DAC_C0_DACEN(baseAddr, 1U); } /*! * @brief Disables the Programmable Reference Generator. * * This function disables the Programmable Reference Generator. Then the * DAC system is disabled. * * @param baseAddr The DAC peripheral base address. */ static inline void DAC_HAL_Disable(uint32_t baseAddr) { BW_DAC_C0_DACEN(baseAddr, 0U); } /*! * @brief Sets the reference voltage source mode for the DAC module. * * This function sets the reference voltage source mode for the DAC module. * * @param baseAddr The DAC peripheral base address. * @param mode Selection of enumeration mode. See to "dac_ref_volt_src_mode_t". */ static inline void DAC_HAL_SetRefVoltSrcMode(uint32_t baseAddr, dac_ref_volt_src_mode_t mode) { BW_DAC_C0_DACRFS(baseAddr, ((kDacRefVoltSrcOfVref1==mode)?0U:1U) ); } /*! * @brief Sets the trigger mode for the DAC module. * * This function sets the trigger mode for the DAC module. * * @param baseAddr The DAC peripheral base address. * @param mode Selection of enumeration mode. See to "dac_trigger_mode_t". */ static inline void DAC_HAL_SetTriggerMode(uint32_t baseAddr, dac_trigger_mode_t mode) { BW_DAC_C0_DACTRGSEL(baseAddr, ((kDacTriggerByHardware==mode)?0U:1U) ); } /*! * @brief Triggers the converter with software. * * This function triggers the converter with software. If the DAC software * trigger is selected and buffer enabled, calling this API advances the * buffer read pointer once. * * @param baseAddr The DAC peripheral base address. */ static inline void DAC_HAL_SetSoftTriggerCmd(uint32_t baseAddr) { BW_DAC_C0_DACSWTRG(baseAddr, 1U); } /*! * @brief Switches to enable working in low power mode for the DAC module. * * This function switches to enable working in low power mode for the DAC module. * * @param baseAddr The DAC peripheral base address. * @param enable Switcher to assert the feature. */ static inline void DAC_HAL_SetLowPowerCmd(uint32_t baseAddr, bool enable) { BW_DAC_C0_LPEN(baseAddr, (enable?1U:0U) ); } #if FSL_FEATURE_DAC_HAS_WATERMARK_DETECTION /*! * @brief Switches to enable the interrupt when buffer read pointer hits the watermark position. * * This function switches to enable the interrupt when the buffer read pointer hits * the watermark position. * * @param baseAddr The DAC peripheral base address. * @param enable Switcher to assert the feature. */ static inline void DAC_HAL_SetBuffIndexWatermarkIntCmd(uint32_t baseAddr, bool enable) { BW_DAC_C0_DACBWIEN(baseAddr, (enable?1U:0U) ); } #endif /* FSL_FEATURE_DAC_HAS_WATERMARK_DETECTION */ /*! * @brief Switches to enable the interrupt when the buffer read pointer hits the top position. * * This function switches to enable the interrupt when the buffer read pointer hits * the top position. * * @param baseAddr The DAC peripheral base address. * @param enable Switcher to assert the feature. */ static inline void DAC_HAL_SetBuffIndexStartIntCmd(uint32_t baseAddr, bool enable) { BW_DAC_C0_DACBTIEN(baseAddr, (enable?1U:0U) ); } /*! * @brief Switches to enable the interrupt when the buffer read pointer hits the bottom position. * * This function switches to enable the interrupt when the buffer read pointer hits * the bottom position. * * @param baseAddr The DAC peripheral base address. * @param enable Switcher to assert the feature. */ static inline void DAC_HAL_SetBuffIndexUpperIntCmd(uint32_t baseAddr, bool enable) { BW_DAC_C0_DACBBIEN(baseAddr, (enable?1U:0U) ); } /*! * @brief Switches to enable the DMA for DAC. * * This function switches to enable the DMA for the DAC module. When the DMA is enabled, * DMA request is generated by the original interrupts, which are * not presented on this module at the same time. * * @param baseAddr The DAC peripheral base address. * @param enable Switcher to assert the feature. */ static inline void DAC_HAL_SetDmaCmd(uint32_t baseAddr, bool enable) { BW_DAC_C1_DMAEN(baseAddr, (enable?1U:0U) ); } #if FSL_FEATURE_DAC_HAS_WATERMARK_DETECTION /*! * @brief Sets the watermark mode of the buffer for the DAC module. * * This function sets the watermark mode of the buffer for the DAC module. * * @param baseAddr The DAC peripheral base address. * @param mode Selection of enumeration mode. See to "dac_buff_watermark_mode_t". */ static inline void DAC_HAL_SetBuffWatermarkMode(uint32_t baseAddr, dac_buff_watermark_mode_t mode) { BW_DAC_C1_DACBFWM(baseAddr, (uint8_t)mode); } #endif /* FSL_FEATURE_DAC_HAS_WATERMARK_DETECTION */ /*! * @brief Sets the work mode of the buffer for the DAC module. * * This function sets the work mode of the buffer for the DAC module. * * @param baseAddr The DAC peripheral base address. * @param mode Selection of enumeration mode. See to "dac_buff_work_mode_t". */ static inline void DAC_HAL_SetBuffWorkMode(uint32_t baseAddr, dac_buff_work_mode_t mode) { BW_DAC_C1_DACBFMD(baseAddr, (uint8_t)mode ); } /*! * @brief Switches to enable the buffer for the DAC module. * * This function switches to enable the buffer for the DAC module. * * @param baseAddr The DAC peripheral base address. * @param enable Switcher to assert the feature. */ static inline void DAC_HAL_SetBuffCmd(uint32_t baseAddr, bool enable) { BW_DAC_C1_DACBFEN(baseAddr, (enable?1U:0U) ); } /*! * @brief Gets the buffer index upper limitation for the DAC module. * * This function gets the upper buffer index upper limitation for the DAC module. * * @param baseAddr The DAC peripheral base address. * @return Value of buffer index upper limitation. */ static inline uint8_t DAC_HAL_GetBuffUpperIndex(uint32_t baseAddr) { return BR_DAC_C2_DACBFUP(baseAddr); } /*! * @brief Sets the buffer index upper limitation for the DAC module. * * This function sets the upper buffer index upper limitation for the DAC module. * * @param baseAddr The DAC peripheral base address. * @param index Setting value of upper limitation for buffer index. */ static inline void DAC_HAL_SetBuffUpperIndex(uint32_t baseAddr, uint8_t index) { assert(index < HW_DAC_DATnL_COUNT); BW_DAC_C2_DACBFUP(baseAddr , index); } /*! * @brief Gets the current buffer index upper limitation for the DAC module. * * This function gets the current buffer index for the DAC module. * * @param baseAddr The DAC peripheral base address. * @return Value of current buffer index. */ static inline uint8_t DAC_HAL_GetBuffCurrentIndex(uint32_t baseAddr) { return BR_DAC_C2_DACBFRP(baseAddr); } /*! * @brief Sets the buffer index for the DAC module. * * This function sets the upper buffer index for the DAC module. * * @param baseAddr the DAC peripheral base address. * @param index Setting value for buffer index. */ static inline void DAC_HAL_SetBuffCurrentIndex(uint32_t baseAddr, uint8_t index) { assert(index < HW_DAC_DATnL_COUNT); BW_DAC_C2_DACBFRP(baseAddr, index); } #if defined(__cplusplus) } #endif /*! * @} */ #endif /* __FSL_DAC_HAL_H__ */ /****************************************************************************** * EOF *****************************************************************************/ ================================================ FILE: Zelig/mbed/TARGET_K64F/TARGET_Freescale/TARGET_KPSDK_MCUS/TARGET_KPSDK_CODE/hal/dmamux/fsl_dmamux_features.h ================================================ /* ** ################################################################### ** Version: rev. 1.0, 2014-05-14 ** Build: b140515 ** ** Abstract: ** Chip specific module features. ** ** Copyright: 2014 Freescale Semiconductor, Inc. ** All rights reserved. ** ** Redistribution and use in source and binary forms, with or without modification, ** are permitted provided that the following conditions are met: ** ** o Redistributions of source code must retain the above copyright notice, this list ** of conditions and the following disclaimer. ** ** o Redistributions in binary form must reproduce the above copyright notice, this ** list of conditions and the following disclaimer in the documentation and/or ** other materials provided with the distribution. ** ** o Neither the name of Freescale Semiconductor, Inc. nor the names of its ** contributors may be used to endorse or promote products derived from this ** software without specific prior written permission. ** ** THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ** ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED ** WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE ** DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT 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. ** ** http: www.freescale.com ** mail: support@freescale.com ** ** Revisions: ** - rev. 1.0 (2014-05-14) ** Customer release. ** ** ################################################################### */ #if !defined(__FSL_DMAMUX_FEATURES_H__) #define __FSL_DMAMUX_FEATURES_H__ #if defined(CPU_MK02FN128VFM10) || defined(CPU_MK02FN64VFM10) || defined(CPU_MK02FN128VLF10) || defined(CPU_MK02FN64VLF10) || \ defined(CPU_MK02FN128VLH10) || defined(CPU_MK02FN64VLH10) || defined(CPU_MK20DX128VMP5) || defined(CPU_MK20DN128VMP5) || \ defined(CPU_MK20DX64VMP5) || defined(CPU_MK20DN64VMP5) || defined(CPU_MK20DX32VMP5) || defined(CPU_MK20DN32VMP5) || \ defined(CPU_MK20DX128VLH5) || defined(CPU_MK20DN128VLH5) || defined(CPU_MK20DX64VLH5) || defined(CPU_MK20DN64VLH5) || \ defined(CPU_MK20DX32VLH5) || defined(CPU_MK20DN32VLH5) || defined(CPU_MK20DX128VFM5) || defined(CPU_MK20DN128VFM5) || \ defined(CPU_MK20DX64VFM5) || defined(CPU_MK20DN64VFM5) || defined(CPU_MK20DX32VFM5) || defined(CPU_MK20DN32VFM5) || \ defined(CPU_MK20DX128VFT5) || defined(CPU_MK20DN128VFT5) || defined(CPU_MK20DX64VFT5) || defined(CPU_MK20DN64VFT5) || \ defined(CPU_MK20DX32VFT5) || defined(CPU_MK20DN32VFT5) || defined(CPU_MK20DX128VLF5) || defined(CPU_MK20DN128VLF5) || \ defined(CPU_MK20DX64VLF5) || defined(CPU_MK20DN64VLF5) || defined(CPU_MK20DX32VLF5) || defined(CPU_MK20DN32VLF5) || \ defined(CPU_MK22FN128VDC10) || defined(CPU_MK22FN128VLH10) || defined(CPU_MK22FN128VLL10) || defined(CPU_MK22FN128VMP10) || \ defined(CPU_MKL05Z8VFK4) || defined(CPU_MKL05Z16VFK4) || defined(CPU_MKL05Z32VFK4) || defined(CPU_MKL05Z8VLC4) || \ defined(CPU_MKL05Z16VLC4) || defined(CPU_MKL05Z32VLC4) || defined(CPU_MKL05Z8VFM4) || defined(CPU_MKL05Z16VFM4) || \ defined(CPU_MKL05Z32VFM4) || defined(CPU_MKL05Z16VLF4) || defined(CPU_MKL05Z32VLF4) || defined(CPU_MKL13Z64VFM4) || \ defined(CPU_MKL13Z128VFM4) || defined(CPU_MKL13Z256VFM4) || defined(CPU_MKL13Z64VFT4) || defined(CPU_MKL13Z128VFT4) || \ defined(CPU_MKL13Z256VFT4) || defined(CPU_MKL13Z64VLH4) || defined(CPU_MKL13Z128VLH4) || defined(CPU_MKL13Z256VLH4) || \ defined(CPU_MKL13Z64VMP4) || defined(CPU_MKL13Z128VMP4) || defined(CPU_MKL13Z256VMP4) || defined(CPU_MKL23Z64VFM4) || \ defined(CPU_MKL23Z128VFM4) || defined(CPU_MKL23Z256VFM4) || defined(CPU_MKL23Z64VFT4) || defined(CPU_MKL23Z128VFT4) || \ defined(CPU_MKL23Z256VFT4) || defined(CPU_MKL23Z64VLH4) || defined(CPU_MKL23Z128VLH4) || defined(CPU_MKL23Z256VLH4) || \ defined(CPU_MKL23Z64VMP4) || defined(CPU_MKL23Z128VMP4) || defined(CPU_MKL23Z256VMP4) || defined(CPU_MKL25Z32VFM4) || \ defined(CPU_MKL25Z64VFM4) || defined(CPU_MKL25Z128VFM4) || defined(CPU_MKL25Z32VFT4) || defined(CPU_MKL25Z64VFT4) || \ defined(CPU_MKL25Z128VFT4) || defined(CPU_MKL25Z32VLH4) || defined(CPU_MKL25Z64VLH4) || defined(CPU_MKL25Z128VLH4) || \ defined(CPU_MKL25Z32VLK4) || defined(CPU_MKL25Z64VLK4) || defined(CPU_MKL25Z128VLK4) || defined(CPU_MKL26Z256VLK4) || \ defined(CPU_MKL26Z128VLL4) || defined(CPU_MKL26Z256VLL4) || defined(CPU_MKL26Z128VMC4) || defined(CPU_MKL26Z256VMC4) || \ defined(CPU_MKL33Z128VLH4) || defined(CPU_MKL33Z256VLH4) || defined(CPU_MKL33Z128VMP4) || defined(CPU_MKL33Z256VMP4) || \ defined(CPU_MKL43Z64VLH4) || defined(CPU_MKL43Z128VLH4) || defined(CPU_MKL43Z256VLH4) || defined(CPU_MKL43Z64VMP4) || \ defined(CPU_MKL43Z128VMP4) || defined(CPU_MKL43Z256VMP4) || defined(CPU_MKL46Z128VLH4) || defined(CPU_MKL46Z256VLH4) || \ defined(CPU_MKL46Z128VLL4) || defined(CPU_MKL46Z256VLL4) || defined(CPU_MKL46Z128VMC4) || defined(CPU_MKL46Z256VMC4) || \ defined(CPU_MKV30F128VFM10) || defined(CPU_MKV30F64VFM10) || defined(CPU_MKV30F128VLF10) || defined(CPU_MKV30F64VLF10) || \ defined(CPU_MKV30F128VLH10) || defined(CPU_MKV30F64VLH10) || defined(CPU_MKV31F128VLH10) || defined(CPU_MKV31F128VLL10) /* @brief Number of DMA channels (related to number of register CHCFGn). */ #define FSL_FEATURE_DMAMUX_MODULE_CHANNEL (4) /* @brief Total number of DMA channels on all modules. */ #define FSL_FEATURE_DMAMUX_DMAMUX_CHANNELS (HW_DMAMUX_INSTANCE_COUNT * 4) #elif defined(CPU_MK22FN256VDC12) || defined(CPU_MK22FN256VLH12) || defined(CPU_MK22FN256VLL12) || defined(CPU_MK22FN256VMP12) || \ defined(CPU_MK22FN512VDC12) || defined(CPU_MK22FN512VLH12) || defined(CPU_MK22FN512VLL12) || defined(CPU_MK24FN1M0VDC12) || \ defined(CPU_MK24FN1M0VLL12) || defined(CPU_MK24FN1M0VLQ12) || defined(CPU_MK24FN256VDC12) || defined(CPU_MK63FN1M0VLQ12) || \ defined(CPU_MK63FN1M0VMD12) || defined(CPU_MK64FX512VDC12) || defined(CPU_MK64FN1M0VDC12) || defined(CPU_MK64FX512VLL12) || \ defined(CPU_MK64FN1M0VLL12) || defined(CPU_MK64FX512VLQ12) || defined(CPU_MK64FN1M0VLQ12) || defined(CPU_MK64FX512VMD12) || \ defined(CPU_MK64FN1M0VMD12) || defined(CPU_MK70FN1M0VMF12) || defined(CPU_MK70FX512VMF12) || defined(CPU_MK70FN1M0VMF15) || \ defined(CPU_MK70FX512VMF15) || defined(CPU_MK70FN1M0VMJ12) || defined(CPU_MK70FX512VMJ12) || defined(CPU_MK70FN1M0VMJ15) || \ defined(CPU_MK70FX512VMJ15) || defined(CPU_MKV31F256VLH12) || defined(CPU_MKV31F256VLL12) || defined(CPU_MKV31F512VLH12) || \ defined(CPU_MKV31F512VLL12) || defined(CPU_MKV40F128VLH15) || defined(CPU_MKV40F128VLL15) || defined(CPU_MKV40F256VLH15) || \ defined(CPU_MKV40F256VLL15) || defined(CPU_MKV40F64VLH15) || defined(CPU_MKV43F128VLH15) || defined(CPU_MKV43F128VLL15) || \ defined(CPU_MKV43F64VLH15) || defined(CPU_MKV44F128VLH15) || defined(CPU_MKV44F128VLL15) || defined(CPU_MKV44F64VLH15) || \ defined(CPU_MKV45F128VLH15) || defined(CPU_MKV45F128VLL15) || defined(CPU_MKV45F256VLH15) || defined(CPU_MKV45F256VLL15) || \ defined(CPU_MKV46F128VLH15) || defined(CPU_MKV46F128VLL15) || defined(CPU_MKV46F256VLH15) || defined(CPU_MKV46F256VLL15) /* @brief Number of DMA channels (related to number of register CHCFGn). */ #define FSL_FEATURE_DMAMUX_MODULE_CHANNEL (16) /* @brief Total number of DMA channels on all modules. */ #define FSL_FEATURE_DMAMUX_DMAMUX_CHANNELS (HW_DMAMUX_INSTANCE_COUNT * 16) #elif defined(CPU_MK65FN2M0CAC18) || defined(CPU_MK65FX1M0CAC18) || defined(CPU_MK65FN2M0VMI18) || defined(CPU_MK65FX1M0VMI18) || \ defined(CPU_MK66FN2M0VLQ18) || defined(CPU_MK66FX1M0VLQ18) || defined(CPU_MK66FN2M0VMD18) || defined(CPU_MK66FX1M0VMD18) /* @brief Number of DMA channels (related to number of register CHCFGn). */ #define FSL_FEATURE_DMAMUX_MODULE_CHANNEL (32) /* @brief Total number of DMA channels on all modules. */ #define FSL_FEATURE_DMAMUX_DMAMUX_CHANNELS (HW_DMAMUX_INSTANCE_COUNT * 32) #else #error "No valid CPU defined!" #endif #endif /* __FSL_DMAMUX_FEATURES_H__ */ /******************************************************************************* * EOF ******************************************************************************/ ================================================ FILE: Zelig/mbed/TARGET_K64F/TARGET_Freescale/TARGET_KPSDK_MCUS/TARGET_KPSDK_CODE/hal/dmamux/fsl_dmamux_hal.h ================================================ /* * Copyright (c) 2013 - 2014, Freescale Semiconductor, Inc. * All rights reserved. * * Redistribution and use in source and binary forms, with or without modification, * are permitted provided that the following conditions are met: * * o Redistributions of source code must retain the above copyright notice, this list * of conditions and the following disclaimer. * * o Redistributions in binary form must reproduce the above copyright notice, this * list of conditions and the following disclaimer in the documentation and/or * other materials provided with the distribution. * * o Neither the name of Freescale Semiconductor, Inc. nor the names of its * contributors may be used to endorse or promote products derived from this * software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT 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. */ #ifndef __FSL_DMAMUX_HAL_H__ #define __FSL_DMAMUX_HAL_H__ #include #include #include #include "fsl_dmamux_features.h" #include "fsl_device_registers.h" /*! * @addtogroup dmamux_hal * @{ */ /******************************************************************************* * Definitions ******************************************************************************/ /*! * @brief A constant for the length of the DMA hardware source. This structure is used inside * the DMA driver. */ typedef enum _dmamux_source { kDmamuxDmaRequestSource = 64U /*!< Maximum number of the DMA requests allowed for the DMA mux. */ } dmamux_dma_request_source; /******************************************************************************* * API ******************************************************************************/ #if defined(__cplusplus) extern "C" { #endif /*! * @name DMAMUX HAL function * @{ */ /*! * @brief Initializes the DMAMUX module to the reset state. * * Initializes the DMAMUX module to the reset state. * * @param baseAddr Register base address for DMAMUX module. */ void DMAMUX_HAL_Init(uint32_t baseAddr); /*! * @brief Enables/Disables the DMAMUX channel. * * Enables the hardware request. If enabled, the hardware request is sent to * the corresponding DMA channel. * * @param baseAddr Register base address for DMAMUX module. * @param channel DMAMUX channel number. * @param enable Enables (true) or Disables (false) DMAMUX channel. */ static inline void DMAMUX_HAL_SetChannelCmd(uint32_t baseAddr, uint32_t channel, bool enable) { assert(channel < FSL_FEATURE_DMAMUX_MODULE_CHANNEL); BW_DMAMUX_CHCFGn_ENBL(baseAddr, channel, enable); } /*! * @brief Enables/Disables the period trigger. * * @param baseAddr Register base address for DMAMUX module. * @param channel DMAMUX channel number. * @param enable Enables (true) or Disables (false) period trigger. */ static inline void DMAMUX_HAL_SetPeriodTriggerCmd(uint32_t baseAddr, uint32_t channel, bool enable) { assert(channel < FSL_FEATURE_DMAMUX_MODULE_CHANNEL); BW_DMAMUX_CHCFGn_TRIG(baseAddr, channel, enable); } /*! * @brief Configures the DMA request for the DMAMUX channel. * * Sets the trigger source for the DMA channel. The trigger source is in the file * fsl_dma_request.h. * * @param baseAddr Register base address for DMAMUX module. * @param channel DMAMUX channel number. * @param source DMA request source. */ static inline void DMAMUX_HAL_SetTriggerSource(uint32_t baseAddr, uint32_t channel, uint8_t source) { assert(channel < FSL_FEATURE_DMAMUX_MODULE_CHANNEL); BW_DMAMUX_CHCFGn_SOURCE(baseAddr, channel, source); } /* @} */ #if defined(__cplusplus) } #endif /*! @} */ #endif /* __FSL_DMAMUX_HAL_H__ */ /******************************************************************************* * EOF ******************************************************************************/ ================================================ FILE: Zelig/mbed/TARGET_K64F/TARGET_Freescale/TARGET_KPSDK_MCUS/TARGET_KPSDK_CODE/hal/dspi/fsl_dspi_features.h ================================================ /* ** ################################################################### ** Version: rev. 1.0, 2014-05-14 ** Build: b140515 ** ** Abstract: ** Chip specific module features. ** ** Copyright: 2014 Freescale Semiconductor, Inc. ** All rights reserved. ** ** Redistribution and use in source and binary forms, with or without modification, ** are permitted provided that the following conditions are met: ** ** o Redistributions of source code must retain the above copyright notice, this list ** of conditions and the following disclaimer. ** ** o Redistributions in binary form must reproduce the above copyright notice, this ** list of conditions and the following disclaimer in the documentation and/or ** other materials provided with the distribution. ** ** o Neither the name of Freescale Semiconductor, Inc. nor the names of its ** contributors may be used to endorse or promote products derived from this ** software without specific prior written permission. ** ** THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ** ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED ** WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE ** DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT 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. ** ** http: www.freescale.com ** mail: support@freescale.com ** ** Revisions: ** - rev. 1.0 (2014-05-14) ** Customer release. ** ** ################################################################### */ #if !defined(__FSL_DSPI_FEATURES_H__) #define __FSL_DSPI_FEATURES_H__ #if defined(CPU_MK02FN128VFM10) || defined(CPU_MK02FN64VFM10) || defined(CPU_MK20DX128VFM5) || defined(CPU_MK20DN128VFM5) || \ defined(CPU_MK20DX64VFM5) || defined(CPU_MK20DN64VFM5) || defined(CPU_MK20DX32VFM5) || defined(CPU_MK20DN32VFM5) || \ defined(CPU_MKV30F128VFM10) || defined(CPU_MKV30F64VFM10) /* @brief Receive/transmit FIFO size in number of items. */ #define FSL_FEATURE_DSPI_FIFO_SIZE (4) #define FSL_FEATURE_DSPI_FIFO_SIZEn(x) \ ((x) == 0 ? (4) : (-1)) /* @brief Maximum transfer data width in bits. */ #define FSL_FEATURE_DSPI_MAX_DATA_WIDTH (16) /* @brief Maximum number of chip select pins. (Reflects the width of register bit field PUSHR[PCS].) */ #define FSL_FEATURE_DSPI_MAX_CHIP_SELECT_COUNT (6) /* @brief Number of chip select pins. */ #define FSL_FEATURE_DSPI_CHIP_SELECT_COUNT (4) #define FSL_FEATURE_DSPI_CHIP_SELECT_COUNTn(x) \ ((x) == 0 ? (4) : (-1)) /* @brief Has chip select strobe capability on the PCS5 pin. */ #define FSL_FEATURE_DSPI_HAS_CHIP_SELECT_STROBE (1) /* @brief Has 16-bit data transfer support. */ #define FSL_FEATURE_DSPI_16BIT_TRANSFERS (1) #elif defined(CPU_MK02FN128VLF10) || defined(CPU_MK02FN64VLF10) || defined(CPU_MK02FN128VLH10) || defined(CPU_MK02FN64VLH10) || \ defined(CPU_MK20DX128VMP5) || defined(CPU_MK20DN128VMP5) || defined(CPU_MK20DX64VMP5) || defined(CPU_MK20DN64VMP5) || \ defined(CPU_MK20DX32VMP5) || defined(CPU_MK20DN32VMP5) || defined(CPU_MK20DX128VLH5) || defined(CPU_MK20DN128VLH5) || \ defined(CPU_MK20DX64VLH5) || defined(CPU_MK20DN64VLH5) || defined(CPU_MK20DX32VLH5) || defined(CPU_MK20DN32VLH5) || \ defined(CPU_MK20DX128VFT5) || defined(CPU_MK20DN128VFT5) || defined(CPU_MK20DX64VFT5) || defined(CPU_MK20DN64VFT5) || \ defined(CPU_MK20DX32VFT5) || defined(CPU_MK20DN32VFT5) || defined(CPU_MK20DX128VLF5) || defined(CPU_MK20DN128VLF5) || \ defined(CPU_MK20DX64VLF5) || defined(CPU_MK20DN64VLF5) || defined(CPU_MK20DX32VLF5) || defined(CPU_MK20DN32VLF5) || \ defined(CPU_MKV30F128VLF10) || defined(CPU_MKV30F64VLF10) || defined(CPU_MKV30F128VLH10) || defined(CPU_MKV30F64VLH10) /* @brief Receive/transmit FIFO size in number of items. */ #define FSL_FEATURE_DSPI_FIFO_SIZE (4) #define FSL_FEATURE_DSPI_FIFO_SIZEn(x) \ ((x) == 0 ? (4) : (-1)) /* @brief Maximum transfer data width in bits. */ #define FSL_FEATURE_DSPI_MAX_DATA_WIDTH (16) /* @brief Maximum number of chip select pins. (Reflects the width of register bit field PUSHR[PCS].) */ #define FSL_FEATURE_DSPI_MAX_CHIP_SELECT_COUNT (6) /* @brief Number of chip select pins. */ #define FSL_FEATURE_DSPI_CHIP_SELECT_COUNT (5) #define FSL_FEATURE_DSPI_CHIP_SELECT_COUNTn(x) \ ((x) == 0 ? (5) : (-1)) /* @brief Has chip select strobe capability on the PCS5 pin. */ #define FSL_FEATURE_DSPI_HAS_CHIP_SELECT_STROBE (1) /* @brief Has 16-bit data transfer support. */ #define FSL_FEATURE_DSPI_16BIT_TRANSFERS (1) #elif defined(CPU_MK22FN128VDC10) || defined(CPU_MK22FN128VLL10) || defined(CPU_MK22FN256VDC12) || defined(CPU_MK22FN256VLL12) || \ defined(CPU_MK22FN512VDC12) || defined(CPU_MK22FN512VLL12) || defined(CPU_MKV31F128VLL10) || defined(CPU_MKV31F256VLL12) || \ defined(CPU_MKV31F512VLL12) /* @brief Receive/transmit FIFO size in number of items. */ #define FSL_FEATURE_DSPI_FIFO_SIZE (4) #define FSL_FEATURE_DSPI_FIFO_SIZEn(x) \ ((x) == 0 ? (4) : \ ((x) == 1 ? (1) : (-1))) /* @brief Maximum transfer data width in bits. */ #define FSL_FEATURE_DSPI_MAX_DATA_WIDTH (16) /* @brief Maximum number of chip select pins. (Reflects the width of register bit field PUSHR[PCS].) */ #define FSL_FEATURE_DSPI_MAX_CHIP_SELECT_COUNT (6) /* @brief Number of chip select pins. */ #define FSL_FEATURE_DSPI_CHIP_SELECT_COUNT (6) #define FSL_FEATURE_DSPI_CHIP_SELECT_COUNTn(x) \ ((x) == 0 ? (6) : \ ((x) == 1 ? (4) : (-1))) /* @brief Has chip select strobe capability on the PCS5 pin. */ #define FSL_FEATURE_DSPI_HAS_CHIP_SELECT_STROBE (1) /* @brief Has 16-bit data transfer support. */ #define FSL_FEATURE_DSPI_16BIT_TRANSFERS (1) #elif defined(CPU_MK22FN128VLH10) || defined(CPU_MK22FN128VMP10) || defined(CPU_MK22FN256VLH12) || defined(CPU_MK22FN256VMP12) || \ defined(CPU_MK22FN512VLH12) || defined(CPU_MKV31F128VLH10) || defined(CPU_MKV31F256VLH12) || defined(CPU_MKV31F512VLH12) /* @brief Receive/transmit FIFO size in number of items. */ #define FSL_FEATURE_DSPI_FIFO_SIZE (4) #define FSL_FEATURE_DSPI_FIFO_SIZEn(x) \ ((x) == 0 ? (4) : \ ((x) == 1 ? (1) : (-1))) /* @brief Maximum transfer data width in bits. */ #define FSL_FEATURE_DSPI_MAX_DATA_WIDTH (16) /* @brief Maximum number of chip select pins. (Reflects the width of register bit field PUSHR[PCS].) */ #define FSL_FEATURE_DSPI_MAX_CHIP_SELECT_COUNT (6) /* @brief Number of chip select pins. */ #define FSL_FEATURE_DSPI_CHIP_SELECT_COUNT (5) #define FSL_FEATURE_DSPI_CHIP_SELECT_COUNTn(x) \ ((x) == 0 ? (5) : \ ((x) == 1 ? (2) : (-1))) /* @brief Has chip select strobe capability on the PCS5 pin. */ #define FSL_FEATURE_DSPI_HAS_CHIP_SELECT_STROBE (1) /* @brief Has 16-bit data transfer support. */ #define FSL_FEATURE_DSPI_16BIT_TRANSFERS (1) #elif defined(CPU_MK24FN1M0VDC12) || defined(CPU_MK24FN1M0VLQ12) || defined(CPU_MK24FN256VDC12) || defined(CPU_MK63FN1M0VLQ12) || \ defined(CPU_MK63FN1M0VMD12) || defined(CPU_MK64FX512VDC12) || defined(CPU_MK64FN1M0VDC12) || defined(CPU_MK64FX512VLQ12) || \ defined(CPU_MK64FN1M0VLQ12) || defined(CPU_MK64FX512VMD12) || defined(CPU_MK64FN1M0VMD12) || defined(CPU_MK65FN2M0CAC18) || \ defined(CPU_MK65FX1M0CAC18) || defined(CPU_MK65FN2M0VMI18) || defined(CPU_MK65FX1M0VMI18) || defined(CPU_MK66FN2M0VLQ18) || \ defined(CPU_MK66FX1M0VLQ18) || defined(CPU_MK66FN2M0VMD18) || defined(CPU_MK66FX1M0VMD18) /* @brief Receive/transmit FIFO size in number of items. */ #define FSL_FEATURE_DSPI_FIFO_SIZE (4) #define FSL_FEATURE_DSPI_FIFO_SIZEn(x) \ ((x) == 0 ? (4) : \ ((x) == 1 ? (1) : \ ((x) == 2 ? (1) : (-1)))) /* @brief Maximum transfer data width in bits. */ #define FSL_FEATURE_DSPI_MAX_DATA_WIDTH (16) /* @brief Maximum number of chip select pins. (Reflects the width of register bit field PUSHR[PCS].) */ #define FSL_FEATURE_DSPI_MAX_CHIP_SELECT_COUNT (6) /* @brief Number of chip select pins. */ #define FSL_FEATURE_DSPI_CHIP_SELECT_COUNT (6) #define FSL_FEATURE_DSPI_CHIP_SELECT_COUNTn(x) \ ((x) == 0 ? (6) : \ ((x) == 1 ? (4) : \ ((x) == 2 ? (2) : (-1)))) /* @brief Has chip select strobe capability on the PCS5 pin. */ #define FSL_FEATURE_DSPI_HAS_CHIP_SELECT_STROBE (1) /* @brief Has 16-bit data transfer support. */ #define FSL_FEATURE_DSPI_16BIT_TRANSFERS (1) #elif defined(CPU_MK24FN1M0VLL12) || defined(CPU_MK64FX512VLL12) || defined(CPU_MK64FN1M0VLL12) /* @brief Receive/transmit FIFO size in number of items. */ #define FSL_FEATURE_DSPI_FIFO_SIZE (4) #define FSL_FEATURE_DSPI_FIFO_SIZEn(x) \ ((x) == 0 ? (4) : \ ((x) == 1 ? (1) : \ ((x) == 2 ? (1) : (-1)))) /* @brief Maximum transfer data width in bits. */ #define FSL_FEATURE_DSPI_MAX_DATA_WIDTH (16) /* @brief Maximum number of chip select pins. (Reflects the width of register bit field PUSHR[PCS].) */ #define FSL_FEATURE_DSPI_MAX_CHIP_SELECT_COUNT (6) /* @brief Number of chip select pins. */ #define FSL_FEATURE_DSPI_CHIP_SELECT_COUNT (6) #define FSL_FEATURE_DSPI_CHIP_SELECT_COUNTn(x) \ ((x) == 0 ? (6) : \ ((x) == 1 ? (4) : \ ((x) == 2 ? (1) : (-1)))) /* @brief Has chip select strobe capability on the PCS5 pin. */ #define FSL_FEATURE_DSPI_HAS_CHIP_SELECT_STROBE (1) /* @brief Has 16-bit data transfer support. */ #define FSL_FEATURE_DSPI_16BIT_TRANSFERS (1) #elif defined(CPU_MK70FN1M0VMF12) || defined(CPU_MK70FX512VMF12) || defined(CPU_MK70FN1M0VMF15) || defined(CPU_MK70FX512VMF15) || \ defined(CPU_MK70FN1M0VMJ12) || defined(CPU_MK70FX512VMJ12) || defined(CPU_MK70FN1M0VMJ15) || defined(CPU_MK70FX512VMJ15) /* @brief Receive/transmit FIFO size in number of items. */ #define FSL_FEATURE_DSPI_FIFO_SIZE (4) #define FSL_FEATURE_DSPI_FIFO_SIZEn(x) \ ((x) == 0 ? (4) : \ ((x) == 1 ? (4) : \ ((x) == 2 ? (4) : (-1)))) /* @brief Maximum transfer data width in bits. */ #define FSL_FEATURE_DSPI_MAX_DATA_WIDTH (16) /* @brief Maximum number of chip select pins. (Reflects the width of register bit field PUSHR[PCS].) */ #define FSL_FEATURE_DSPI_MAX_CHIP_SELECT_COUNT (6) /* @brief Number of chip select pins. */ #define FSL_FEATURE_DSPI_CHIP_SELECT_COUNT (6) #define FSL_FEATURE_DSPI_CHIP_SELECT_COUNTn(x) \ ((x) == 0 ? (6) : \ ((x) == 1 ? (4) : \ ((x) == 2 ? (2) : (-1)))) /* @brief Has chip select strobe capability on the PCS5 pin. */ #define FSL_FEATURE_DSPI_HAS_CHIP_SELECT_STROBE (1) /* @brief Has 16-bit data transfer support. */ #define FSL_FEATURE_DSPI_16BIT_TRANSFERS (1) #elif defined(CPU_MKV40F128VLH15) || defined(CPU_MKV40F256VLH15) || defined(CPU_MKV40F64VLH15) || defined(CPU_MKV43F128VLH15) || \ defined(CPU_MKV43F64VLH15) || defined(CPU_MKV44F128VLH15) || defined(CPU_MKV44F64VLH15) || defined(CPU_MKV45F128VLH15) || \ defined(CPU_MKV45F256VLH15) || defined(CPU_MKV46F128VLH15) || defined(CPU_MKV46F256VLH15) /* @brief Receive/transmit FIFO size in number of items. */ #define FSL_FEATURE_DSPI_FIFO_SIZE (4) #define FSL_FEATURE_DSPI_FIFO_SIZEn(x) \ ((x) == 0 ? (4) : (-1)) /* @brief Maximum transfer data width in bits. */ #define FSL_FEATURE_DSPI_MAX_DATA_WIDTH (16) /* @brief Maximum number of chip select pins. (Reflects the width of register bit field PUSHR[PCS].) */ #define FSL_FEATURE_DSPI_MAX_CHIP_SELECT_COUNT (6) /* @brief Number of chip select pins. */ #define FSL_FEATURE_DSPI_CHIP_SELECT_COUNT (5) #define FSL_FEATURE_DSPI_CHIP_SELECT_COUNTn(x) \ ((x) == 0 ? (5) : (-1)) /* @brief Has chip select strobe capability on the PCS5 pin. */ #define FSL_FEATURE_DSPI_HAS_CHIP_SELECT_STROBE (1) /* @brief Has 16-bit data transfer support. */ #define FSL_FEATURE_DSPI_16BIT_TRANSFERS (1) #elif defined(CPU_MKV40F128VLL15) || defined(CPU_MKV40F256VLL15) || defined(CPU_MKV43F128VLL15) || defined(CPU_MKV44F128VLL15) || \ defined(CPU_MKV45F128VLL15) || defined(CPU_MKV45F256VLL15) || defined(CPU_MKV46F128VLL15) || defined(CPU_MKV46F256VLL15) /* @brief Receive/transmit FIFO size in number of items. */ #define FSL_FEATURE_DSPI_FIFO_SIZE (4) #define FSL_FEATURE_DSPI_FIFO_SIZEn(x) \ ((x) == 0 ? (4) : (-1)) /* @brief Maximum transfer data width in bits. */ #define FSL_FEATURE_DSPI_MAX_DATA_WIDTH (16) /* @brief Maximum number of chip select pins. (Reflects the width of register bit field PUSHR[PCS].) */ #define FSL_FEATURE_DSPI_MAX_CHIP_SELECT_COUNT (6) /* @brief Number of chip select pins. */ #define FSL_FEATURE_DSPI_CHIP_SELECT_COUNT (6) #define FSL_FEATURE_DSPI_CHIP_SELECT_COUNTn(x) \ ((x) == 0 ? (6) : (-1)) /* @brief Has chip select strobe capability on the PCS5 pin. */ #define FSL_FEATURE_DSPI_HAS_CHIP_SELECT_STROBE (1) /* @brief Has 16-bit data transfer support. */ #define FSL_FEATURE_DSPI_16BIT_TRANSFERS (1) #else #error "No valid CPU defined!" #endif #endif /* __FSL_DSPI_FEATURES_H__ */ /******************************************************************************* * EOF ******************************************************************************/ ================================================ FILE: Zelig/mbed/TARGET_K64F/TARGET_Freescale/TARGET_KPSDK_MCUS/TARGET_KPSDK_CODE/hal/dspi/fsl_dspi_hal.h ================================================ /* * Copyright (c) 2013 - 2014, Freescale Semiconductor, Inc. * All rights reserved. * * Redistribution and use in source and binary forms, with or without modification, * are permitted provided that the following conditions are met: * * o Redistributions of source code must retain the above copyright notice, this list * of conditions and the following disclaimer. * * o Redistributions in binary form must reproduce the above copyright notice, this * list of conditions and the following disclaimer in the documentation and/or * other materials provided with the distribution. * * o Neither the name of Freescale Semiconductor, Inc. nor the names of its * contributors may be used to endorse or promote products derived from this * software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT 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. */ #if !defined(__FSL_DSPI_HAL_H__) #define __FSL_DSPI_HAL_H__ #include #include #include "fsl_dspi_features.h" #include "fsl_device_registers.h" /*! * @addtogroup dspi_hal * @{ */ /*! @file*/ /******************************************************************************* * Definitions ******************************************************************************/ /* Defines constant value arrays for the baud rate pre-scalar and scalar divider values.*/ static const uint32_t s_baudratePrescaler[] = { 2, 3, 5, 7 }; static const uint32_t s_baudrateScaler[] = { 2, 4, 6, 8, 16, 32, 64, 128, 256, 512, 1024, 2048, 4096, 8192, 16384, 32768 }; static const uint32_t s_delayPrescaler[] = { 1, 3, 5, 7 }; static const uint32_t s_delayScaler[] = { 2, 4, 8, 16, 32, 64, 128, 256, 512, 1024, 2048, 4096, 8192, 16384, 32768, 65536 }; /*! @brief Error codes for the DSPI driver.*/ typedef enum _dspi_status { kStatus_DSPI_Success = 0, kStatus_DSPI_SlaveTxUnderrun, /*!< DSPI Slave Tx Under run error*/ kStatus_DSPI_SlaveRxOverrun, /*!< DSPI Slave Rx Overrun error*/ kStatus_DSPI_Timeout, /*!< DSPI transfer timed out*/ kStatus_DSPI_Busy, /*!< DSPI instance is already busy performing a transfer.*/ kStatus_DSPI_NoTransferInProgress, /*!< Attempt to abort a transfer when no transfer was in progress*/ kStatus_DSPI_InvalidBitCount, /*!< bits-per-frame value not valid*/ kStatus_DSPI_InvalidInstanceNumber, /*!< DSPI instance number does not match current count*/ kStatus_DSPI_OutOfRange /*!< DSPI out-of-range error used in slave callback */ } dspi_status_t; /*! @brief DSPI master or slave configuration*/ typedef enum _dspi_master_slave_mode { kDspiMaster = 1, /*!< DSPI peripheral operates in master mode*/ kDspiSlave = 0 /*!< DSPI peripheral operates in slave mode*/ } dspi_master_slave_mode_t; /*! @brief DSPI clock polarity configuration for a given CTAR*/ typedef enum _dspi_clock_polarity { kDspiClockPolarity_ActiveHigh = 0, /*!< Active-high DSPI clock (idles low)*/ kDspiClockPolarity_ActiveLow = 1 /*!< Active-low DSPI clock (idles high)*/ } dspi_clock_polarity_t; /*! @brief DSPI clock phase configuration for a given CTAR*/ typedef enum _dspi_clock_phase { kDspiClockPhase_FirstEdge = 0, /*!< Data is captured on the leading edge of the SCK and changed on the following edge.*/ kDspiClockPhase_SecondEdge = 1 /*!< Data is changed on the leading edge of the SCK and captured on the following edge.*/ } dspi_clock_phase_t; /*! @brief DSPI data shifter direction options for a given CTAR*/ typedef enum _dspi_shift_direction { kDspiMsbFirst = 0, /*!< Data transfers start with most significant bit.*/ kDspiLsbFirst = 1 /*!< Data transfers start with least significant bit.*/ } dspi_shift_direction_t; /*! @brief DSPI Clock and Transfer Attributes Register (CTAR) selection*/ typedef enum _dspi_ctar_selection { kDspiCtar0 = 0, /*!< CTAR0 selection option for master or slave mode*/ kDspiCtar1 = 1 /*!< CTAR1 selection option for master mode only*/ } dspi_ctar_selection_t; /*! @brief DSPI Peripheral Chip Select (PCS) Polarity configuration.*/ typedef enum _dspi_pcs_polarity_config { kDspiPcs_ActiveHigh = 0, /*!< PCS Active High (idles low)*/ kDspiPcs_ActiveLow = 1 /*!< PCS Active Low (idles high)*/ } dspi_pcs_polarity_config_t; /*! @brief DSPI Peripheral Chip Select (PCS) configuration (which PCS to configure)*/ typedef enum _dspi_which_pcs_config { kDspiPcs0 = 1 << 0, /*!< PCS[0] */ kDspiPcs1 = 1 << 1, /*!< PCS[1] */ kDspiPcs2 = 1 << 2, /*!< PCS[2] */ kDspiPcs3 = 1 << 3, /*!< PCS[3] */ kDspiPcs4 = 1 << 4, /*!< PCS[4] */ kDspiPcs5 = 1 << 5 /*!< PCS[5] */ } dspi_which_pcs_config_t; /*! * @brief DSPI Sample Point: Controls when the DSPI master samples SIN in Modified Transfer * Format. This field is valid only when CPHA bit in CTAR register is 0. */ typedef enum _dspi_master_sample_point { kDspiSckToSin_0Clock = 0, /*!< 0 system clocks between SCK edge and SIN sample*/ kDspiSckToSin_1Clock = 1, /*!< 1 system clock between SCK edge and SIN sample*/ kDspiSckToSin_2Clock = 2 /*!< 2 system clocks between SCK edge and SIN sample*/ } dspi_master_sample_point_t; /*! @brief DSPI FIFO selects*/ typedef enum _dspi_fifo { kDspiTxFifo = 0, /*!< DSPI Tx FIFO*/ kDspiRxFifo = 1 /*!< DSPI Rx FIFO.*/ } dspi_fifo_t; /*! @brief DSPI Tx FIFO Fill and Rx FIFO Drain DMA or Interrupt configuration */ typedef enum _dspi_dma_or_int_mode { kDspiGenerateIntReq = 0, /*!< Desired flag generates an Interrupt request */ kDspiGenerateDmaReq = 1 /*!< Desired flag generates a DMA request */ } dspi_dma_or_int_mode_t; /*! @brief DSPI status flags and interrupt request enable*/ typedef enum _dspi_status_and_interrupt_request { kDspiTxComplete = BP_SPI_RSER_TCF_RE, /*!< TCF status/interrupt enable */ kDspiTxAndRxStatus = BP_SPI_SR_TXRXS, /*!< TXRXS status only, no interrupt*/ kDspiEndOfQueue = BP_SPI_RSER_EOQF_RE, /*!< EOQF status/interrupt enable*/ kDspiTxFifoUnderflow = BP_SPI_RSER_TFUF_RE, /*!< TFUF status/interrupt enable*/ kDspiTxFifoFillRequest = BP_SPI_RSER_TFFF_RE, /*!< TFFF status/interrupt enable*/ kDspiRxFifoOverflow = BP_SPI_RSER_RFOF_RE, /*!< RFOF status/interrupt enable*/ kDspiRxFifoDrainRequest = BP_SPI_RSER_RFDF_RE /*!< RFDF status/interrupt enable*/ } dspi_status_and_interrupt_request_t; /*! @brief DSPI FIFO counter or pointer defines based on bit positions*/ typedef enum _dspi_fifo_counter_pointer { kDspiRxFifoPointer = BP_SPI_SR_POPNXTPTR, /*!< Rx FIFO pointer*/ kDspiRxFifoCounter = BP_SPI_SR_RXCTR, /*!< Rx FIFO counter*/ kDspiTxFifoPointer = BP_SPI_SR_TXNXTPTR, /*!< Tx FIFO pointer*/ kDspiTxFifoCounter = BP_SPI_SR_TXCTR /*!< Tx FIFO counter*/ } dspi_fifo_counter_pointer_t; /*! @brief DSPI delay type selection*/ typedef enum _dspi_delay_type { kDspiPcsToSck = 1, /*!< PCS-to-SCK delay */ kDspiLastSckToPcs = 2, /*!< Last SCK edge to PCS delay */ kDspiAfterTransfer = 3, /*!< Delay between transfers */ } dspi_delay_type_t; /*! * @brief DSPI data format settings configuration structure * * This structure contains the data format settings. These settings apply to a specific * CTARn register, which the user must provide in this structure. */ typedef struct DspiDataFormatConfig { uint32_t bitsPerFrame; /*!< Bits per frame, minimum 4, maximum 16 (master), 32 (slave) */ dspi_clock_polarity_t clkPolarity; /*!< Active high or low clock polarity*/ dspi_clock_phase_t clkPhase; /*!< Clock phase setting to change and capture data*/ dspi_shift_direction_t direction; /*!< MSB or LSB data shift direction This setting relevant only in master mode and can be ignored in slave mode */ } dspi_data_format_config_t; /*! * @brief DSPI hardware configuration settings for slave mode. * * Use an instance of this structure with the DSPI_HAL_SlaveInit() to configure the * most common settings of the DSPI peripheral in slave mode with a single function call. */ typedef struct DspiSlaveConfig { bool isEnabled; /*!< Set to true to enable the DSPI peripheral. */ dspi_data_format_config_t dataConfig; /*!< Data format configuration structure */ bool isTxFifoDisabled; /*!< Disable(1) or Enable(0) Tx FIFO */ bool isRxFifoDisabled; /*!< Disable(1) or Enable(0) Rx FIFO */ } dspi_slave_config_t; /*! * @brief DSPI baud rate divisors settings configuration structure. * * Note: These settings are relevant only in master mode. * This structure contains the baud rate divisor settings, which provides the user with the option * to explicitly set these baud rate divisors. In addition, the user must also set the * CTARn register with the divisor settings. */ typedef struct DspiBaudRateDivisors { bool doubleBaudRate; /*!< Double Baud rate parameter setting */ uint32_t prescaleDivisor; /*!< Baud Rate Pre-scalar parameter setting*/ uint32_t baudRateDivisor; /*!< Baud Rate scaler parameter setting */ } dspi_baud_rate_divisors_t; /*! * @brief DSPI command and data configuration structure * * Note: This structure is used with the PUSHR register, which * provides the means to write to the Tx FIFO. Data written to this register is * transferred to the Tx FIFO. Eight or sixteen-bit write accesses to the PUSHR transfer all * 32 register bits to the Tx FIFO. The register structure is different in master and slave * modes. In master mode, the register provides 16-bit command and 16-bit data to the Tx * FIFO. In slave mode all 32 register bits can be used as data, supporting up to 32-bit SPI * frame operation. */ typedef struct DspiCommandDataConfig { bool isChipSelectContinuous; /*!< Option to enable the continuous assertion of chip select between transfers*/ dspi_ctar_selection_t whichCtar; /*!< The desired Clock and Transfer Attributes Register (CTAR) to use for CTAS*/ dspi_which_pcs_config_t whichPcs; /*!< The desired PCS signal to use for the data transfer*/ bool isEndOfQueue; /*!< Signals that the current transfer is the last in the queue*/ bool clearTransferCount; /*!< Clears SPI_TCNT field; cleared before transmission starts*/ } dspi_command_config_t; /******************************************************************************* * Variables ******************************************************************************/ extern const uint32_t spi_base_addr[]; /******************************************************************************* * API ******************************************************************************/ #if defined(__cplusplus) extern "C" { #endif /*! * @name Configuration * @{ */ /*! * @brief Restores the DSPI to reset the configuration. * * This function basically resets all of the DSPI registers to their default setting including * disabling the module. * * @param baseAddr Module base address */ void DSPI_HAL_Init(uint32_t baseAddr); /*! * @brief Enables the DSPI peripheral and sets the MCR MDIS to 0. * * @param baseAddr Module base address */ static inline void DSPI_HAL_Enable(uint32_t baseAddr) { BW_SPI_MCR_MDIS(baseAddr, 0); } /*! * @brief Disables the DSPI peripheral, sets MCR MDIS to 1. * * @param baseAddr Module base address */ static inline void DSPI_HAL_Disable(uint32_t baseAddr) { BW_SPI_MCR_MDIS(baseAddr, 1); } /*! * @brief Sets the DSPI baud rate in bits per second. * * This function takes in the desired bitsPerSec (baud rate) and calculates the nearest * possible baud rate without exceeding the desired baud rate, and returns the calculated * baud rate in bits-per-second. It requires that the caller also provide the frequency of the * module source clock (in Hertz). * * @param baseAddr Module base address * @param whichCtar The desired Clock and Transfer Attributes Register (CTAR) of the type * dspi_ctar_selection_t * @param bitsPerSec The desired baud rate in bits per second * @param sourceClockInHz Module source input clock in Hertz * @return The actual calculated baud rate */ uint32_t DSPI_HAL_SetBaudRate(uint32_t baseAddr, dspi_ctar_selection_t whichCtar, uint32_t bitsPerSec, uint32_t sourceClockInHz); /*! * @brief Configures the baud rate divisors manually. * * This function allows the caller to manually set the baud rate divisors in the event that * these dividers are known and the caller does not wish to call the DSPI_HAL_SetBaudRate function. * * @param baseAddr Module base address * @param whichCtar The desired Clock and Transfer Attributes Register (CTAR) of type * dspi_ctar_selection_t * @param divisors Pointer to a structure containing the user defined baud rate divisor settings */ void DSPI_HAL_SetBaudDivisors(uint32_t baseAddr, dspi_ctar_selection_t whichCtar, const dspi_baud_rate_divisors_t * divisors); /*! * @brief Configures the DSPI for master or slave. * * @param baseAddr Module base address * @param mode Mode setting (master or slave) of type dspi_master_slave_mode_t */ static inline void DSPI_HAL_SetMasterSlaveMode(uint32_t baseAddr, dspi_master_slave_mode_t mode) { BW_SPI_MCR_MSTR(baseAddr, (uint32_t)mode); } /*! * @brief Returns whether the DSPI module is in master mode. * * @param baseAddr Module base address * @retval true The module is in master mode. * @retval false The module is in slave mode. */ static inline bool DSPI_HAL_IsMaster(uint32_t baseAddr) { return (bool)BR_SPI_MCR_MSTR(baseAddr); } /*! * @brief Configures the DSPI for the continuous SCK operation. * * @param baseAddr Module base address * @param enable Enables (true) or disables(false) continuous SCK operation. */ static inline void DSPI_HAL_SetContinuousSckCmd(uint32_t baseAddr, bool enable) { BW_SPI_MCR_CONT_SCKE(baseAddr, (enable == true)); } /*! * @brief Configures the DSPI to enable modified timing format. * * @param baseAddr Module base address * @param enable Enables (true) or disables(false) modified timing format. */ static inline void DSPI_HAL_SetModifiedTimingFormatCmd(uint32_t baseAddr, bool enable) { BW_SPI_MCR_MTFE(baseAddr, (enable == true)); } /*! * @brief Configures the DSPI peripheral chip select strobe enable. Configures the PCS[5] to be the * active-low PCS Strobe output. * * PCS[5] is a special case that can be configured as an active low PCS strobe or as a Peripheral * Chip Select in master mode. When configured as a strobe, it provides a signal to an external * demultiplexer to decode PCS[0] to PCS[4] signals into as many as 128 glitch-free PCS signals. * * @param baseAddr Module base address * @param enable Enable (true) PCS[5] to operate as the peripheral chip select (PCS) strobe * If disable (false), PCS[5] operates as a peripheral chip select */ static inline void DSPI_HAL_SetPcsStrobeCmd(uint32_t baseAddr, bool enable) { BW_SPI_MCR_PCSSE(baseAddr, (enable == true)); } /*! * @brief Configures the DSPI received FIFO overflow overwrite enable. * * When enabled, this function allows incoming receive data to overwrite the existing data in the * receive shift register when the Rx FIFO is full. Otherwise when disabled, the incoming data * is ignored when the RX FIFO is full. * * @param baseAddr Module base address. * @param enable If enabled (true), allows incoming data to overwrite Rx FIFO contents when full, * else incoming data is ignored. */ static inline void DSPI_HAL_SetRxFifoOverwriteCmd(uint32_t baseAddr, bool enable) { BW_SPI_MCR_ROOE(baseAddr, (enable == true)); } /*! * @brief Configures the DSPI peripheral chip select polarity. * * This function takes in the desired peripheral chip select (PCS) and it's * corresponding desired polarity and configures the PCS signal to operate with the * desired characteristic. * * @param baseAddr Module base address * @param pcs The particular peripheral chip select (parameter value is of type * dspi_which_pcs_config_t) for which we wish to apply the active high or active * low characteristic. * @param activeLowOrHigh The setting for either "active high, inactive low (0)" or * "active low, inactive high(1)" of type dspi_pcs_polarity_config_t. */ void DSPI_HAL_SetPcsPolarityMode(uint32_t baseAddr, dspi_which_pcs_config_t pcs, dspi_pcs_polarity_config_t activeLowOrHigh); /*! * @brief Enables (or disables) the DSPI FIFOs. * * This function allows the caller to disable/enable the Tx and Rx FIFOs (independently). * Note that to disable, the caller must pass in a logic 0 (false) for the particular FIFO * configuration. To enable, the caller must pass in a logic 1 (true). * * @param baseAddr Module instance number * @param enableTxFifo Disables (false) the TX FIFO, else enables (true) the TX FIFO * @param enableRxFifo Disables (false) the RX FIFO, else enables (true) the RX FIFO */ void DSPI_HAL_SetFifoCmd(uint32_t baseAddr, bool enableTxFifo, bool enableRxFifo); /*! * @brief Flushes the DSPI FIFOs. * * @param baseAddr Module base address * @param enableFlushTxFifo Flushes (true) the Tx FIFO, else do not flush (false) the Tx FIFO * @param enableFlushRxFifo Flushes (true) the Rx FIFO, else do not flush (false) the Rx FIFO */ void DSPI_HAL_SetFlushFifoCmd(uint32_t baseAddr, bool enableFlushTxFifo, bool enableFlushRxFifo); /*! * @brief Configures the time when the DSPI master samples SIN in the Modified Transfer Format. * * This function controls when the DSPI master samples SIN (data in) in the Modified Transfer * Format. Note that this is valid only when the CPHA bit in the CTAR register is 0. * * @param baseAddr Module base address * @param samplePnt selects when the data in (SIN) is sampled, of type dspi_master_sample_point_t. * This value selects either 0, 1, or 2 system clocks between the SCK edge * and the SIN (data in) sample. */ static inline void DSPI_HAL_SetDatainSamplepointMode(uint32_t baseAddr, dspi_master_sample_point_t samplePnt) { BW_SPI_MCR_SMPL_PT(baseAddr, samplePnt); } /*! * @brief Starts the DSPI transfers, clears HALT bit in MCR. * * This function call called whenever the module is ready to begin data transfers in either master * or slave mode. * * @param baseAddr Module base address */ static inline void DSPI_HAL_StartTransfer(uint32_t baseAddr) { BW_SPI_MCR_HALT(baseAddr, 0); } /*! * @brief Stops (halts) DSPI transfers, sets HALT bit in MCR. * * This function call stops data transfers in either master or slave mode. * * @param baseAddr Module base address */ static inline void DSPI_HAL_StopTransfer(uint32_t baseAddr) { BW_SPI_MCR_HALT(baseAddr, 1); } /*! * @brief Configures the data format for a particular CTAR. * * This function configures the bits-per-frame, polarity, phase, and shift direction for a * particular CTAR. An example use case is as follows: @code dspi_data_format_config_t dataFormat; dataFormat.bitsPerFrame = 16; dataFormat.clkPolarity = kDspiClockPolarity_ActiveLow; dataFormat.clkPhase = kDspiClockPhase_FirstEdge; dataFormat.direction = kDspiMsbFirst; DSPI_HAL_SetDataFormat(instance, kDspiCtar0, &dataFormat); @endcode * * @param baseAddr Module base address * @param whichCtar The desired Clock and Transfer Attributes Register (CTAR) of type * dspi_ctar_selection_t. * @param config Pointer to structure containing user defined data format configuration settings. * @return An error code or kStatus_DSPI_Success */ dspi_status_t DSPI_HAL_SetDataFormat(uint32_t baseAddr, dspi_ctar_selection_t whichCtar, const dspi_data_format_config_t * config); /*! * @brief Manually configures the delay prescaler and scaler for a particular CTAR. * * This function configures the PCS to SCK delay pre-scalar (PCSSCK) and scalar (CSSCK), * after SCK delay pre-scalar (PASC) and scalar (ASC), and the delay * after transfer pre-scalar (PDT)and scalar (DT). * * These delay names are available in type dspi_delay_type_t. * * The user passes which delay they want to configure along with the prescaler and scaler value. * This allows the user to directly set the prescaler/scaler values if they have * pre-calculated them or if they simply wish to manually increment either value. * * @param baseAddr Module base address * @param whichCtar The desired Clock and Transfer Attributes Register (CTAR) of type * dspi_ctar_selection_t. * @param prescaler The prescaler delay value (can be an integer 0, 1, 2, or 3). * @param prescaler The scaler delay value (can be any integer between 0 to 15). * @param whichDelay The desired delay to configure, must be of type dspi_delay_type_t */ void DSPI_HAL_SetDelay(uint32_t baseAddr, dspi_ctar_selection_t whichCtar, uint32_t prescaler, uint32_t scaler, dspi_delay_type_t whichDelay); /*! * @brief Calculates the delay prescaler and scaler based on the desired delay input in nanoseconds. * * This function calculates the values for: * PCS to SCK delay pre-scalar (PCSSCK) and scalar (CSSCK), or * After SCK delay pre-scalar (PASC) and scalar (ASC), or * Delay after transfer pre-scalar (PDT)and scalar (DT). * * These delay names are available in type dspi_delay_type_t. * * The user passes which delay they want to configure along with the desired delay value in * nano-seconds. The function calculates the values needed for the prescaler and scaler and * returning the actual calculated delay as an exact delay match may not be possible. In this * case, the closest match is calculated without going below the desired delay value input. * It is possible to input a very large delay value that exceeds the capability of the part, in * which case the maximum supported delay will be returned. It is to the higher level * peripheral driver to alert the user of an out of range delay input. * * @param baseAddr Module base address * @param whichCtar The desired Clock and Transfer Attributes Register (CTAR) of type * dspi_ctar_selection_t. * @param whichDelay The desired delay to configure, must be of type dspi_delay_type_t * @param sourceClockInHz Module source input clock in Hertz * @param delayInNanoSec The desired delay value in nano-seconds. * @return The actual calculated delay value. */ uint32_t DSPI_HAL_CalculateDelay(uint32_t baseAddr, dspi_ctar_selection_t whichCtar, dspi_delay_type_t whichDelay, uint32_t sourceClockInHz, uint32_t delayInNanoSec); /*@}*/ /*! * @name Low power * @{ */ /*! * @brief Configures the DSPI operation during doze mode. * * This function provides support for an externally controlled doze mode, power-saving, mechanism. * When disabled, the doze mode has no effect on the DSPI, and when enabled, the Doze mode * disables the DSPI. * * @param baseAddr Module base address * @param enable If disabled (false), the doze mode has no effect on the DSPI, if enabled (true), * the doze mode disables the DSPI. */ static inline void DSPI_HAL_SetDozemodeCmd(uint32_t baseAddr, bool enable) { BW_SPI_MCR_DOZE(baseAddr, (enable == true)); } /*@}*/ /*! * @name Interrupts * @{ */ /*! * @brief Configures the DSPI Tx FIFO fill request to generate DMA or interrupt requests. * * This function configures the DSPI Tx FIFO Fill flag to generate either * an interrupt or DMA request. The user passes in which request they'd like to generate * of type dspi_dma_or_int_mode_t and whether or not they wish to enable this request. * Note, when disabling the request, the request type is don't care. @code DSPI_HAL_SetTxFifoFillDmaIntMode(baseAddr, kDspiGenerateDmaReq, true); <- to enable DMA DSPI_HAL_SetTxFifoFillDmaIntMode(baseAddr, kDspiGenerateIntReq, true); <- to enable Interrupt DSPI_HAL_SetTxFifoFillDmaIntMode(baseAddr, kDspiGenerateIntReq, false); <- to disable @endcode * @param baseAddr Module base address * @param mode Configures the DSPI Tx FIFO Fill to generate an interrupt or DMA request * @param enable Enable (true) or disable (false) the DSPI Tx FIFO Fill flag to generate requests */ void DSPI_HAL_SetTxFifoFillDmaIntMode(uint32_t baseAddr, dspi_dma_or_int_mode_t mode, bool enable); /*! * @brief Configures the DSPI Rx FIFO Drain request to generate DMA or interrupt requests. * * This function configures the DSPI Rx FIFO Drain flag to generate either * an interrupt or a DMA request. The user passes in which request they'd like to generate * of type dspi_dma_or_int_mode_t and whether or not they wish to enable this request. * Note, when disabling the request, the request type is don't care. @code DSPI_HAL_SetRxFifoDrainDmaIntMode(baseAddr, kDspiGenerateDmaReq, true); <- to enable DMA DSPI_HAL_SetRxFifoDrainDmaIntMode(baseAddr, kDspiGenerateIntReq, true); <- to enable Interrupt DSPI_HAL_SetRxFifoDrainDmaIntMode(baseAddr, kDspiGenerateIntReq, false); <- to disable @endcode * @param baseAddr Module base address * @param mode Configures the Rx FIFO Drain to generate an interrupt or DMA request * @param enable Enable (true) or disable (false) the Rx FIFO Drain flag to generate requests */ void DSPI_HAL_SetRxFifoDrainDmaIntMode(uint32_t baseAddr, dspi_dma_or_int_mode_t mode, bool enable); /*! * @brief Configures the DSPI interrupts. * * This function configures the various interrupt sources of the DSPI. The parameters are * baseAddr, interrupt source, and enable/disable setting. * The interrupt source is a typedef enumeration whose value is the bit position of the * interrupt source setting within the RSER register. In the DSPI, all interrupt * configuration settings are in one register. The typedef enum equates each * interrupt source to the bit position defined in the device header file. * The function uses these bit positions in its algorithm to enable/disable the * interrupt source, where interrupt source is the dspi_status_and_interrupt_request_t type. * Note, for Tx FIFO Fill and Rx FIFO Drain requests, use the functions: * DSPI_HAL_SetTxFifoFillDmaIntMode and DSPI_HAL_SetRxFifoDrainDmaIntMode respectively as * these requests can generate either an interrupt or DMA request. @code DSPI_HAL_SetIntMode(baseAddr, kDspiTxComplete, true); <- example use-case @endcode * * @param baseAddr Module base address * @param interruptSrc The interrupt source, of type dspi_status_and_interrupt_request_t * @param enable Enable (true) or disable (false) the interrupt source to generate requests */ void DSPI_HAL_SetIntMode(uint32_t baseAddr, dspi_status_and_interrupt_request_t interruptSrc, bool enable); /*! * @brief Gets DSPI interrupt configuration, returns if interrupt request is enabled or disabled. * * This function returns the requested interrupt source setting (enabled or disabled, of * type bool). The parameters to pass in are baseAddr and interrupt source. It utilizes the * same enumeration definitions for the interrupt sources as described in the "interrupt configuration" * function. The function uses these bit positions in its algorithm to obtain the desired * interrupt source setting. * Note, for Tx FIFO Fill and Rx FIFO Drain requests, this returns whether or not their * requests are enabled. @code getInterruptSetting = DSPI_HAL_GetIntMode(baseAddr, kDspiTxComplete); @endcode * * @param baseAddr Module base address * @param interruptSrc The interrupt source, of type dspi_status_and_interrupt_request_t * @return Configuration of interrupt request: enable (true) or disable (false). */ static inline bool DSPI_HAL_GetIntMode(uint32_t baseAddr, dspi_status_and_interrupt_request_t interruptSrc) { return ((HW_SPI_RSER_RD(baseAddr) >> interruptSrc) & 0x1); } /*@}*/ /*! * @name Status * @{ */ /*! * @brief Gets the DSPI status flag state. * * The status flag is defined in the same enumeration as the interrupt source enable because the bit * position of the interrupt source and corresponding status flag are the same in the RSER and * SR registers. The function uses these bit positions in its algorithm to obtain the desired * flag state, similar to the dspi_get_interrupt_config function. @code getStatus = DSPI_HAL_GetStatusFlag(baseAddr, kDspiTxComplete); @endcode * * @param baseAddr Module base address * @param statusFlag The status flag, of type dspi_status_and_interrupt_request_t * @return State of the status flag: asserted (true) or not-asserted (false) */ static inline bool DSPI_HAL_GetStatusFlag(uint32_t baseAddr, dspi_status_and_interrupt_request_t statusFlag) { return ((HW_SPI_SR_RD(baseAddr) >> statusFlag) & 0x1); } /*! * @brief Clears the DSPI status flag. * * This function clears the desired status bit by using a write-1-to-clear. The user passes in * the baseAddr and the desired status bit to clear. The list of status bits is defined in the * dspi_status_and_interrupt_request_t. The function uses these bit positions in its algorithm * to clear the desired flag state. Example usage: @code DSPI_HAL_ClearStatusFlag(baseAddr, kDspiTxComplete); @endcode * * @param baseAddr Module base address * @param statusFlag The status flag, of type dspi_status_and_interrupt_request_t */ static inline void DSPI_HAL_ClearStatusFlag(uint32_t baseAddr, dspi_status_and_interrupt_request_t statusFlag) { HW_SPI_SR_SET(baseAddr, (0x1U << statusFlag)); } /*! * @brief Gets the DSPI FIFO counter or pointer. * * This function returns the number of entries or the next pointer in the Tx or Rx FIFO. * The parameters to pass in are the baseAddr and either the Tx or Rx FIFO counter or a * pointer. The latter is an enumeration type defined as the bitmask of * those particular bit fields found in the device header file. Example usage: @code DSPI_HAL_GetFifoCountOrPtr(baseAddr, kDspiRxFifoCounter); @endcode * * @param baseAddr Module base address * @param desiredParameter Desired parameter to obtain, of type dspi_fifo_counter_pointer_t */ static inline uint32_t DSPI_HAL_GetFifoCountOrPtr(uint32_t baseAddr, dspi_fifo_counter_pointer_t desiredParameter) { return ((HW_SPI_SR_RD(baseAddr) >> desiredParameter) & 0xFU); } /*@}*/ /*! * @name Data transfer * @{ */ /*! * @brief Reads data from the data buffer. * * @param baseAddr Module base address */ static inline uint32_t DSPI_HAL_ReadData(uint32_t baseAddr) { return HW_SPI_POPR_RD(baseAddr); } /*! * @brief Writes data into the data buffer, slave mode. * * In slave mode, up to 32-bit words may be written. * * @param baseAddr Module base address * @param data The data to send */ static inline void DSPI_HAL_WriteDataSlavemode(uint32_t baseAddr, uint32_t data) { HW_SPI_PUSHR_SLAVE_WR(baseAddr, data); } /*! * @brief Writes data into the data buffer, master mode. * * In master mode, the 16-bit data is appended to the 16-bit command info. The command portion * provides characteristics of the data such as: optional continuous chip select * operation between transfers, the desired Clock and Transfer Attributes register to use for the * associated SPI frame, the desired PCS signal to use for the data transfer, whether the current * transfer is the last in the queue, and whether to clear the transfer count (normally needed when * sending the first frame of a data packet). This is an example: @code dspi_command_config_t commandConfig; commandConfig.isChipSelectContinuous = true; commandConfig.whichCtar = kDspiCtar0; commandConfig.whichPcs = kDspiPcs1; commandConfig.clearTransferCount = false; commandConfig.isEndOfQueue = false; DSPI_HAL_WriteDataMastermode(baseAddr, &commandConfig, dataWord); @endcode * * @param baseAddr Module base address * @param command Pointer to command structure * @param data The data word to be sent */ void DSPI_HAL_WriteDataMastermode(uint32_t baseAddr, dspi_command_config_t * command, uint16_t data); /*! * @brief Writes data into the data buffer, master mode and waits till complete to return. * * In master mode, the 16-bit data is appended to the 16-bit command info. The command portion * provides characteristics of the data such as: optional continuous chip select * operation between transfers, the desired Clock and Transfer Attributes register to use for the * associated SPI frame, the desired PCS signal to use for the data transfer, whether the current * transfer is the last in the queue, and whether to clear the transfer count (normally needed when * sending the first frame of a data packet). This is an example: @code dspi_command_config_t commandConfig; commandConfig.isChipSelectContinuous = true; commandConfig.whichCtar = kDspiCtar0; commandConfig.whichPcs = kDspiPcs1; commandConfig.clearTransferCount = false; commandConfig.isEndOfQueue = false; DSPI_HAL_WriteDataMastermode(baseAddr, &commandConfig, dataWord); @endcode * * Note that this function does not return until after the transmit is complete. Also note that * the DSPI must be enabled and running in order to transmit data (MCR[MDIS] & [HALT] = 0). * Since the SPI is a synchronous protocol, receive data is available when transmit completes. * * @param baseAddr Module base address * @param command Pointer to command structure * @param data The data word to be sent */ void DSPI_HAL_WriteDataMastermodeBlocking(uint32_t baseAddr, dspi_command_config_t * command, uint16_t data); /*! * @brief Gets the transfer count. * * This function returns the current value of the DSPI Transfer Count Register. * * @param baseAddr Module base address * @return The current transfer count */ static inline uint32_t DSPI_HAL_GetTransferCount(uint32_t baseAddr) { return BR_SPI_TCR_SPI_TCNT(baseAddr); } /*! * @brief Pre-sets the transfer count. * * This function allows the caller to pre-set the DSI Transfer Count Register to a desired value up * to 65535; Incrementing past this resets the counter back to 0. * * @param baseAddr Module base address * @param presetValue The desired pre-set value for the transfer counter */ static inline void DSPI_HAL_PresetTransferCount(uint32_t baseAddr, uint16_t presetValue) { BW_SPI_TCR_SPI_TCNT(baseAddr, presetValue); } /*@}*/ /*! * @name Debug * @{ */ /*! * @brief Reads FIFO registers for debug purposes. * * @param baseAddr Module base address * @param whichFifo Selects Tx or Rx FIFO, of type dspi_fifo_t. * @param whichFifoEntry Selects which FIFO entry to read: 0, 1, 2, or 3. * @return The desired FIFO register contents */ uint32_t DSPI_HAL_GetFifoData(uint32_t baseAddr, dspi_fifo_t whichFifo, uint32_t whichFifoEntry); /*! * @brief Configures the DSPI to halt during debug mode. * * @param baseAddr Module base address * @param enable Enables (true) debug mode to halt transfers, else disable to not halt transfer * in debug mode. */ static inline void DSPI_HAL_SetHaltInDebugmodeCmd(uint32_t baseAddr, bool enable) { BW_SPI_MCR_FRZ(baseAddr, (enable == true)); } /* @}*/ #if defined(__cplusplus) } #endif /*! @}*/ #endif /* __FSL_DSPI_HAL_H__*/ /******************************************************************************* * EOF ******************************************************************************/ ================================================ FILE: Zelig/mbed/TARGET_K64F/TARGET_Freescale/TARGET_KPSDK_MCUS/TARGET_KPSDK_CODE/hal/edma/fsl_edma_features.h ================================================ /* ** ################################################################### ** Version: rev. 1.0, 2014-05-14 ** Build: b140515 ** ** Abstract: ** Chip specific module features. ** ** Copyright: 2014 Freescale Semiconductor, Inc. ** All rights reserved. ** ** Redistribution and use in source and binary forms, with or without modification, ** are permitted provided that the following conditions are met: ** ** o Redistributions of source code must retain the above copyright notice, this list ** of conditions and the following disclaimer. ** ** o Redistributions in binary form must reproduce the above copyright notice, this ** list of conditions and the following disclaimer in the documentation and/or ** other materials provided with the distribution. ** ** o Neither the name of Freescale Semiconductor, Inc. nor the names of its ** contributors may be used to endorse or promote products derived from this ** software without specific prior written permission. ** ** THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ** ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED ** WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE ** DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT 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. ** ** http: www.freescale.com ** mail: support@freescale.com ** ** Revisions: ** - rev. 1.0 (2014-05-14) ** Customer release. ** ** ################################################################### */ #if !defined(__FSL_EDMA_FEATURES_H__) #define __FSL_EDMA_FEATURES_H__ #if defined(CPU_MK02FN128VFM10) || defined(CPU_MK02FN64VFM10) || defined(CPU_MK02FN128VLF10) || defined(CPU_MK02FN64VLF10) || \ defined(CPU_MK02FN128VLH10) || defined(CPU_MK02FN64VLH10) || defined(CPU_MK22FN128VDC10) || defined(CPU_MK22FN128VLH10) || \ defined(CPU_MK22FN128VLL10) || defined(CPU_MK22FN128VMP10) || defined(CPU_MKV30F128VFM10) || defined(CPU_MKV30F64VFM10) || \ defined(CPU_MKV30F128VLF10) || defined(CPU_MKV30F64VLF10) || defined(CPU_MKV30F128VLH10) || defined(CPU_MKV30F64VLH10) || \ defined(CPU_MKV31F128VLH10) || defined(CPU_MKV31F128VLL10) /* @brief Number of DMA channels (related to number of registers TCD, DCHPRI, bit fields ERQ[ERQn], EEI[EEIn], INT[INTn], ERR[ERRn], HRS[HRSn] and bit field widths ES[ERRCHN], CEEI[CEEI], SEEI[SEEI], CERQ[CERQ], SERQ[SERQ], CDNE[CDNE], SSRT[SSRT], CERR[CERR], CINT[CINT], TCDn_CITER_ELINKYES[LINKCH], TCDn_CSR[MAJORLINKCH], TCDn_BITER_ELINKYES[LINKCH]). (Valid only for eDMA modules.) */ #define FSL_FEATURE_EDMA_MODULE_CHANNEL (4) /* @brief Total number of DMA channels on all modules. */ #define FSL_FEATURE_EDMA_DMAMUX_CHANNELS (HW_DMA_INSTANCE_COUNT * 4) /* @brief Number of DMA channel groups (register bit fields CR[ERGA], CR[GRPnPRI], ES[GPE], DCHPRIn[GRPPRI]). (Valid only for eDMA modules.) */ #define FSL_FEATURE_EDMA_CHANNEL_GROUP_COUNT (1) /* @brief Number of DMA channels with asynchronous request capability (register EARS). (Valid only for eDMA modules.) */ #define FSL_FEATURE_EDMA_ASYNCHRO_REQUEST_CHANNEL_COUNT (4) #elif defined(CPU_MK20DX128VMP5) || defined(CPU_MK20DN128VMP5) || defined(CPU_MK20DX64VMP5) || defined(CPU_MK20DN64VMP5) || \ defined(CPU_MK20DX32VMP5) || defined(CPU_MK20DN32VMP5) || defined(CPU_MK20DX128VLH5) || defined(CPU_MK20DN128VLH5) || \ defined(CPU_MK20DX64VLH5) || defined(CPU_MK20DN64VLH5) || defined(CPU_MK20DX32VLH5) || defined(CPU_MK20DN32VLH5) || \ defined(CPU_MK20DX128VFM5) || defined(CPU_MK20DN128VFM5) || defined(CPU_MK20DX64VFM5) || defined(CPU_MK20DN64VFM5) || \ defined(CPU_MK20DX32VFM5) || defined(CPU_MK20DN32VFM5) || defined(CPU_MK20DX128VFT5) || defined(CPU_MK20DN128VFT5) || \ defined(CPU_MK20DX64VFT5) || defined(CPU_MK20DN64VFT5) || defined(CPU_MK20DX32VFT5) || defined(CPU_MK20DN32VFT5) || \ defined(CPU_MK20DX128VLF5) || defined(CPU_MK20DN128VLF5) || defined(CPU_MK20DX64VLF5) || defined(CPU_MK20DN64VLF5) || \ defined(CPU_MK20DX32VLF5) || defined(CPU_MK20DN32VLF5) /* @brief Number of DMA channels (related to number of registers TCD, DCHPRI, bit fields ERQ[ERQn], EEI[EEIn], INT[INTn], ERR[ERRn], HRS[HRSn] and bit field widths ES[ERRCHN], CEEI[CEEI], SEEI[SEEI], CERQ[CERQ], SERQ[SERQ], CDNE[CDNE], SSRT[SSRT], CERR[CERR], CINT[CINT], TCDn_CITER_ELINKYES[LINKCH], TCDn_CSR[MAJORLINKCH], TCDn_BITER_ELINKYES[LINKCH]). (Valid only for eDMA modules.) */ #define FSL_FEATURE_EDMA_MODULE_CHANNEL (4) /* @brief Total number of DMA channels on all modules. */ #define FSL_FEATURE_EDMA_DMAMUX_CHANNELS (HW_DMA_INSTANCE_COUNT * 4) /* @brief Number of DMA channel groups (register bit fields CR[ERGA], CR[GRPnPRI], ES[GPE], DCHPRIn[GRPPRI]). (Valid only for eDMA modules.) */ #define FSL_FEATURE_EDMA_CHANNEL_GROUP_COUNT (1) /* @brief Number of DMA channels with asynchronous request capability (register EARS). (Valid only for eDMA modules.) */ #define FSL_FEATURE_EDMA_ASYNCHRO_REQUEST_CHANNEL_COUNT (0) #elif defined(CPU_MK22FN256VDC12) || defined(CPU_MK22FN256VLH12) || defined(CPU_MK22FN256VLL12) || defined(CPU_MK22FN256VMP12) || \ defined(CPU_MK22FN512VDC12) || defined(CPU_MK22FN512VLH12) || defined(CPU_MK22FN512VLL12) || defined(CPU_MKV31F256VLH12) || \ defined(CPU_MKV31F256VLL12) || defined(CPU_MKV31F512VLH12) || defined(CPU_MKV31F512VLL12) || defined(CPU_MKV40F128VLH15) || \ defined(CPU_MKV40F128VLL15) || defined(CPU_MKV40F256VLH15) || defined(CPU_MKV40F256VLL15) || defined(CPU_MKV40F64VLH15) || \ defined(CPU_MKV43F128VLH15) || defined(CPU_MKV43F128VLL15) || defined(CPU_MKV43F64VLH15) || defined(CPU_MKV44F128VLH15) || \ defined(CPU_MKV44F128VLL15) || defined(CPU_MKV44F64VLH15) || defined(CPU_MKV45F128VLH15) || defined(CPU_MKV45F128VLL15) || \ defined(CPU_MKV45F256VLH15) || defined(CPU_MKV45F256VLL15) || defined(CPU_MKV46F128VLH15) || defined(CPU_MKV46F128VLL15) || \ defined(CPU_MKV46F256VLH15) || defined(CPU_MKV46F256VLL15) /* @brief Number of DMA channels (related to number of registers TCD, DCHPRI, bit fields ERQ[ERQn], EEI[EEIn], INT[INTn], ERR[ERRn], HRS[HRSn] and bit field widths ES[ERRCHN], CEEI[CEEI], SEEI[SEEI], CERQ[CERQ], SERQ[SERQ], CDNE[CDNE], SSRT[SSRT], CERR[CERR], CINT[CINT], TCDn_CITER_ELINKYES[LINKCH], TCDn_CSR[MAJORLINKCH], TCDn_BITER_ELINKYES[LINKCH]). (Valid only for eDMA modules.) */ #define FSL_FEATURE_EDMA_MODULE_CHANNEL (16) /* @brief Total number of DMA channels on all modules. */ #define FSL_FEATURE_EDMA_DMAMUX_CHANNELS (HW_DMA_INSTANCE_COUNT * 16) /* @brief Number of DMA channel groups (register bit fields CR[ERGA], CR[GRPnPRI], ES[GPE], DCHPRIn[GRPPRI]). (Valid only for eDMA modules.) */ #define FSL_FEATURE_EDMA_CHANNEL_GROUP_COUNT (1) /* @brief Number of DMA channels with asynchronous request capability (register EARS). (Valid only for eDMA modules.) */ #define FSL_FEATURE_EDMA_ASYNCHRO_REQUEST_CHANNEL_COUNT (16) #elif defined(CPU_MK24FN1M0VDC12) || defined(CPU_MK24FN1M0VLL12) || defined(CPU_MK24FN1M0VLQ12) || defined(CPU_MK24FN256VDC12) || \ defined(CPU_MK63FN1M0VLQ12) || defined(CPU_MK63FN1M0VMD12) || defined(CPU_MK64FX512VDC12) || defined(CPU_MK64FN1M0VDC12) || \ defined(CPU_MK64FX512VLL12) || defined(CPU_MK64FN1M0VLL12) || defined(CPU_MK64FX512VLQ12) || defined(CPU_MK64FN1M0VLQ12) || \ defined(CPU_MK64FX512VMD12) || defined(CPU_MK64FN1M0VMD12) /* @brief Number of DMA channels (related to number of registers TCD, DCHPRI, bit fields ERQ[ERQn], EEI[EEIn], INT[INTn], ERR[ERRn], HRS[HRSn] and bit field widths ES[ERRCHN], CEEI[CEEI], SEEI[SEEI], CERQ[CERQ], SERQ[SERQ], CDNE[CDNE], SSRT[SSRT], CERR[CERR], CINT[CINT], TCDn_CITER_ELINKYES[LINKCH], TCDn_CSR[MAJORLINKCH], TCDn_BITER_ELINKYES[LINKCH]). (Valid only for eDMA modules.) */ #define FSL_FEATURE_EDMA_MODULE_CHANNEL (16) /* @brief Total number of DMA channels on all modules. */ #define FSL_FEATURE_EDMA_DMAMUX_CHANNELS (HW_DMA_INSTANCE_COUNT * 16) /* @brief Number of DMA channel groups (register bit fields CR[ERGA], CR[GRPnPRI], ES[GPE], DCHPRIn[GRPPRI]). (Valid only for eDMA modules.) */ #define FSL_FEATURE_EDMA_CHANNEL_GROUP_COUNT (1) /* @brief Number of DMA channels with asynchronous request capability (register EARS). (Valid only for eDMA modules.) */ #define FSL_FEATURE_EDMA_ASYNCHRO_REQUEST_CHANNEL_COUNT (0) #elif defined(CPU_MK65FN2M0CAC18) || defined(CPU_MK65FX1M0CAC18) || defined(CPU_MK65FN2M0VMI18) || defined(CPU_MK65FX1M0VMI18) || \ defined(CPU_MK66FN2M0VLQ18) || defined(CPU_MK66FX1M0VLQ18) || defined(CPU_MK66FN2M0VMD18) || defined(CPU_MK66FX1M0VMD18) /* @brief Number of DMA channels (related to number of registers TCD, DCHPRI, bit fields ERQ[ERQn], EEI[EEIn], INT[INTn], ERR[ERRn], HRS[HRSn] and bit field widths ES[ERRCHN], CEEI[CEEI], SEEI[SEEI], CERQ[CERQ], SERQ[SERQ], CDNE[CDNE], SSRT[SSRT], CERR[CERR], CINT[CINT], TCDn_CITER_ELINKYES[LINKCH], TCDn_CSR[MAJORLINKCH], TCDn_BITER_ELINKYES[LINKCH]). (Valid only for eDMA modules.) */ #define FSL_FEATURE_EDMA_MODULE_CHANNEL (32) /* @brief Total number of DMA channels on all modules. */ #define FSL_FEATURE_EDMA_DMAMUX_CHANNELS (HW_DMA_INSTANCE_COUNT * 32) /* @brief Number of DMA channel groups (register bit fields CR[ERGA], CR[GRPnPRI], ES[GPE], DCHPRIn[GRPPRI]). (Valid only for eDMA modules.) */ #define FSL_FEATURE_EDMA_CHANNEL_GROUP_COUNT (2) /* @brief Number of DMA channels with asynchronous request capability (register EARS). (Valid only for eDMA modules.) */ #define FSL_FEATURE_EDMA_ASYNCHRO_REQUEST_CHANNEL_COUNT (32) #elif defined(CPU_MK70FN1M0VMF12) || defined(CPU_MK70FX512VMF12) || defined(CPU_MK70FN1M0VMF15) || defined(CPU_MK70FX512VMF15) || \ defined(CPU_MK70FN1M0VMJ12) || defined(CPU_MK70FX512VMJ12) || defined(CPU_MK70FN1M0VMJ15) || defined(CPU_MK70FX512VMJ15) /* @brief Number of DMA channels (related to number of registers TCD, DCHPRI, bit fields ERQ[ERQn], EEI[EEIn], INT[INTn], ERR[ERRn], HRS[HRSn] and bit field widths ES[ERRCHN], CEEI[CEEI], SEEI[SEEI], CERQ[CERQ], SERQ[SERQ], CDNE[CDNE], SSRT[SSRT], CERR[CERR], CINT[CINT], TCDn_CITER_ELINKYES[LINKCH], TCDn_CSR[MAJORLINKCH], TCDn_BITER_ELINKYES[LINKCH]). (Valid only for eDMA modules.) */ #define FSL_FEATURE_EDMA_MODULE_CHANNEL (32) /* @brief Total number of DMA channels on all modules. */ #define FSL_FEATURE_EDMA_DMAMUX_CHANNELS (HW_DMA_INSTANCE_COUNT * 32) /* @brief Number of DMA channel groups (register bit fields CR[ERGA], CR[GRPnPRI], ES[GPE], DCHPRIn[GRPPRI]). (Valid only for eDMA modules.) */ #define FSL_FEATURE_EDMA_CHANNEL_GROUP_COUNT (2) /* @brief Number of DMA channels with asynchronous request capability (register EARS). (Valid only for eDMA modules.) */ #define FSL_FEATURE_EDMA_ASYNCHRO_REQUEST_CHANNEL_COUNT (0) #else #error "No valid CPU defined!" #endif #endif /* __FSL_EDMA_FEATURES_H__ */ /******************************************************************************* * EOF ******************************************************************************/ ================================================ FILE: Zelig/mbed/TARGET_K64F/TARGET_Freescale/TARGET_KPSDK_MCUS/TARGET_KPSDK_CODE/hal/edma/fsl_edma_hal.h ================================================ /* * Copyright (c) 2013 - 2014, Freescale Semiconductor, Inc. * All rights reserved. * * Redistribution and use in source and binary forms, with or without modification, * are permitted provided that the following conditions are met: * * o Redistributions of source code must retain the above copyright notice, this list * of conditions and the following disclaimer. * * o Redistributions in binary form must reproduce the above copyright notice, this * list of conditions and the following disclaimer in the documentation and/or * other materials provided with the distribution. * * o Neither the name of Freescale Semiconductor, Inc. nor the names of its * contributors may be used to endorse or promote products derived from this * software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT 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. */ #ifndef __EDMA_HAL_H__ #define __EDMA_HAL_H__ #include #include #include #include "fsl_edma_features.h" #include "fsl_device_registers.h" /*! * @addtogroup edma_hal * @{ */ /******************************************************************************* * Definitions ******************************************************************************/ /*! @brief Error code for the eDMA Driver. */ typedef enum _edma_status { kStatus_EDMA_Success = 0U, kStatus_EDMA_InvalidArgument = 1U, /*!< Parameter is invalid. */ kStatus_EDMA_Fail = 2U /*!< Failed operation. */ } edma_status_t; /*! @brief eDMA channel arbitration algorithm used for selection among channels. */ typedef enum _edma_channel_arbitration { kEDMAChnArbitrationFixedPriority = 0U, /*!< Fixed Priority arbitration is used for selection among channels. */ kEDMAChnArbitrationRoundrobin /*!< Round-Robin arbitration is used for selection among channels. */ } edma_channel_arbitration_t; /*! @brief eDMA channel priority setting */ typedef enum _edma_chn_priority { kEDMAChnPriority0 = 0U, kEDMAChnPriority1, kEDMAChnPriority2, kEDMAChnPriority3, kEDMAChnPriority4, kEDMAChnPriority5, kEDMAChnPriority6, kEDMAChnPriority7, kEDMAChnPriority8, kEDMAChnPriority9, kEDMAChnPriority10, kEDMAChnPriority11, kEDMAChnPriority12, kEDMAChnPriority13, kEDMAChnPriority14, kEDMAChnPriority15 } edma_channel_priority_t; #if (FSL_FEATURE_EDMA_CHANNEL_GROUP_COUNT > 0x1U) /*! @brief eDMA group arbitration algorithm used for selection among channels. */ typedef enum _edma_group_arbitration { kEDMAGroupArbitrationFixedPriority = 0U, /*!< Fixed Priority arbitration is used for selection among eDMA groups. */ kEDMAGroupArbitrationRoundrobin /*!< Round-Robin arbitration is used for selection among eDMA channels. */ } edma_group_arbitration_t; /*! @brief eDMA group priority setting */ typedef enum _edma_group_priority { kEDMAGroup0PriorityLowGroup1PriorityHigh, /*!< eDMA group 0's priority is lower priority. eDMA group 1's priority is higher priority. */ kEDMAGroup0PriorityHighGroup1PriorityLow /*!< eDMA group 0's priority is higher priority. eDMA group 1's priority is lower priority. */ } edma_group_priority_t; #endif /*! @brief eDMA modulo configuration */ typedef enum _edma_modulo { kEDMAModuloDisable = 0U, kEDMAModulo2bytes, kEDMAModulo4bytes, kEDMAModulo8bytes, kEDMAModulo16bytes, kEDMAModulo32bytes, kEDMAModulo64bytes, kEDMAModulo128bytes, kEDMAModulo256bytes, kEDMAModulo512bytes, kEDMAModulo1Kbytes, kEDMAModulo2Kbytes, kEDMAModulo4Kbytes, kEDMAModulo8Kbytes, kEDMAModulo16Kbytes, kEDMAModulo32Kbytes, kEDMAModulo64Kbytes, kEDMAModulo128Kbytes, kEDMAModulo256Kbytes, kEDMAModulo512Kbytes, kEDMAModulo1Mbytes, kEDMAModulo2Mbytes, kEDMAModulo4Mbytes, kEDMAModulo8Mbytes, kEDMAModulo16Mbytes, kEDMAModulo32Mbytes, kEDMAModulo64Mbytes, kEDMAModulo128Mbytes, kEDMAModulo256Mbytes, kEDMAModulo512Mbytes, kEDMAModulo1Gbytes, kEDMAModulo2Gbytes } edma_modulo_t; /*! @brief eDMA transfer configuration */ typedef enum _edma_transfer_size { kEDMATransferSize_1Bytes = 0x0U, kEDMATransferSize_2Bytes = 0x1U, kEDMATransferSize_4Bytes = 0x2U, kEDMATransferSize_16Bytes = 0x4U, kEDMATransferSize_32Bytes = 0x5U } edma_transfer_size_t; /*! * @brief eDMA transfer size configuration. * * This structure configures the basic source/destination transfer attribute. * This figure shows the eDMA's transfer model: * _________________________________________________ * | Transfer Size | | * Minor Loop |_______________| Major loop Count 1 | * Count | Transfer Size | | * ____________|_______________|____________________|--> Minor loop complete * ____________________________________ * | | | * |_______________| Major Loop Count 2 | * | | | * |_______________|____________________|--> Minor loop Complete * * ---------------------------------------------------------> Major loop complete * */ typedef struct EDMATransferConfig { uint32_t srcAddr; /*!< Memory address pointing to the source data. */ uint32_t destAddr; /*!< Memory address pointing to the destination data. */ edma_transfer_size_t srcTransferSize; /*!< Source data transfer size. */ edma_transfer_size_t destTransferSize; /*!< Destination data transfer size. */ int16_t srcOffset; /*!< Sign-extended offset applied to the current source address to form the next-state value as each source read/write is completed. */ int16_t destOffset; uint32_t srcLastAddrAdjust; /*!< Last source address adjustment. */ uint32_t destLastAddrAdjust; /*!< Last destination address adjustment. Note here it is only valid when scatter/gather feature is not enabled. */ edma_modulo_t srcModulo; /*!< Source address modulo. */ edma_modulo_t destModulo; /*!< Destination address modulo. */ uint32_t minorLoopCount; /*!< Minor bytes transfer count. Number of bytes to be transferred in each service request of the channel. */ uint16_t majorLoopCount; /*!< Major iteration count. */ } edma_transfer_config_t; /*! @brief eDMA channel configuration. */ typedef enum _edma_channel_indicator { kEDMAChannel0 = 0U, /*!< Channel 0. */ kEDMAChannel1 = 1U, kEDMAChannel2 = 2U, kEDMAChannel3 = 3U, #if (FSL_FEATURE_EDMA_MODULE_CHANNEL > 4U) kEDMAChannel4 = 4U, kEDMAChannel5 = 5U, kEDMAChannel6 = 6U, kEDMAChannel7 = 7U, kEDMAChannel8 = 8U, kEDMAChannel9 = 9U, kEDMAChannel10 = 10U, kEDMAChannel11 = 11U, kEDMAChannel12 = 12U, kEDMAChannel13 = 13U, kEDMAChannel14 = 14U, kEDMAChannel15 = 15U, #endif #if (FSL_FEATURE_EDMA_MODULE_CHANNEL == 32U) kEDMAChannel16 = 16U, kEDMAChannel17 = 17U, kEDMAChannel18 = 18U, kEDMAChannel19 = 19U, kEDMAChannel20 = 20U, kEDMAChannel21 = 21U, kEDMAChannel22 = 22U, kEDMAChannel23 = 23U, kEDMAChannel24 = 24U, kEDMAChannel25 = 25U, kEDMAChannel26 = 26U, kEDMAChannel27 = 27U, kEDMAChannel28 = 28U, kEDMAChannel29 = 29U, kEDMAChannel30 = 30U, kEDMAChannel31 = 31U, #endif kEDMAAllChannel = 64U } edma_channel_indicator_t; /*! @brief eDMA TCD Minor loop mapping configuration */ typedef struct EDMAMinorLoopOffsetConfig { bool enableSrcMinorloop; /*!< Enable(true) or Disable(false) source minor loop offset. */ bool enableDestMinorloop; /*!< Enable(true) or Disable(false) destination minor loop offset. */ uint32_t offset; /*!< Offset for minor loop mapping. */ } edma_minorloop_offset_config_t; /*! @brief Error status of the eDMA module */ typedef union EDMAErrorStatusAll { struct { uint32_t destinationBusError : 1; /*!< Bus error on destination address */ uint32_t sourceBusError : 1; /*!< Bus error on the SRC address */ uint32_t scatterOrGatherConfigurationError : 1; /*!< Error on the Scatter/Gather address */ uint32_t nbyteOrCiterConfigurationError : 1; /*!< NBYTES/CITER configuration error */ uint32_t destinationOffsetError : 1; /*!< Destination offset error */ uint32_t destinationAddressError : 1; /*!< Destination address error */ uint32_t sourceOffsetError : 1; /*!< Source offset error */ uint32_t sourceAddressError : 1; /*!< Source address error */ uint32_t errorChannel : 5; /*!< Error channel number of the cancelled channel number */ uint32_t _reserved1 : 1; uint32_t channelPriorityError : 1; /*!< Channel priority error */ uint32_t groupPriorityError : 1; /*!< Group priority error */ uint32_t transferCancelledError : 1; /*!< Transfer cancelled */ uint32_t _reserved0 : 14; uint32_t orOfAllError : 1; /*!< Logical OR all ERR status bits */ } U; uint32_t B; } edma_error_status_all_t; /*! @brief Bandwidth control configuration */ typedef enum _edma_bandwidth_config { kEDMABandwidthStallNone = 0U, /*!< No eDMA engine stalls. */ kEDMABandwidthStall4Cycle = 2U, /*!< eDMA engine stalls for 4 cycles after each read/write. */ kEDMABandwidthStall8Cycle = 3U /*!< eDMA engine stalls for 8 cycles after each read/write. */ } edma_bandwidth_config_t; /*! @brief eDMA TCD */ typedef struct EDMASoftwareTcd { uint32_t SADDR; uint16_t SOFF; uint16_t ATTR; union { uint32_t MLNO; uint32_t MLOFFNO; uint32_t MLOFFYES; } NBYTES; uint32_t SLAST; uint32_t DADDR; uint16_t DOFF; union { uint16_t ELINKNO; uint16_t ELINKYES; } CITER; uint32_t DLAST_SGA; uint16_t CSR; union { uint16_t ELINKNO; uint16_t ELINKYES; } BITER; } edma_software_tcd_t; /******************************************************************************* * API ******************************************************************************/ #if defined(__cplusplus) extern "C" { #endif /*! * @name eDMA HAL driver module level operation * @{ */ /*! * @brief Initializes eDMA module to known state. * * @param baseAddr Register base address for eDMA module. */ void EDMA_HAL_Init(uint32_t baseAddr); /*! * @brief Cancels the remaining data transfer. * * This function stops the executing channel and forces the minor loop * to finish. The cancellation takes effect after the last write of the * current read/write sequence. The CX clears itself after the cancel has * been honored. This cancel retires the channel normally as if the minor * loop had completed. * * @param baseAddr Register base address for eDMA module. */ void EDMA_HAL_CancelTransfer(uint32_t baseAddr); /*! * @brief Cancels the remaining data transfer and treats it as an error condition. * * This function stops the executing channel and forces the minor loop * to finish. The cancellation takes effect after the last write of the * current read/write sequence. The CX clears itself after the cancel has * been honored. This cancel retires the channel normally as if the minor * loop had completed. Additional thing is to treat this operation as an error * condition. * * @param baseAddr Register base address for eDMA module. */ void EDMA_HAL_ErrorCancelTransfer(uint32_t baseAddr); /*! * @brief Halts/Un-halts the DMA Operations. * * This function stalls/un-stalls the start of any new channels. Executing channels are allowed * to be completed. * * @param baseAddr Register base address for eDMA module. * @param halt Halts (true) or un-halts (false) eDMA transfer. */ static inline void EDMA_HAL_SetHaltCmd(uint32_t baseAddr, bool halt) { BW_DMA_CR_HALT(baseAddr, halt); } /*! * @brief Halts or does not halt the eDMA module when an error occurs. * * An error causes the HALT bit to be set. Subsequently, all service requests are ignored until the * HALT bit is cleared. * * @param baseAddr Register base address for eDMA module. * @param haltOnError Halts (true) or not halt (false) eDMA module when an error occurs. */ static inline void EDMA_HAL_SetHaltOnErrorCmd(uint32_t baseAddr, bool haltOnError) { BW_DMA_CR_HOE(baseAddr, haltOnError); } /*! * @brief Enables/Disables the eDMA DEBUG mode. * * This function enables/disables the eDMA Debug mode. * When in debug mode, the DMA stalls the start of a new * channel. Executing channels are allowed to complete. Channel execution resumes * either when the system exits debug mode or when the EDBG bit is cleared. * * @param baseAddr Register base address for eDMA module. * @param enable Enables (true) or Disable (false) eDMA module debug mode. */ static inline void EDMA_HAL_SetDebugCmd(uint32_t baseAddr, bool enable) { BW_DMA_CR_EDBG(baseAddr, enable); } /* @} */ /*! * @name eDMA HAL driver channel priority and arbitration configuration. * @{ */ /*! * @brief Sets the preempt and preemption feature for the eDMA channel. * * This function sets the preempt and preemption features. * * @param baseAddr Register base address for eDMA module. * @param channel eDMA channel number. * @param preempt eDMA channel can't suspend a lower priority channel (true). eDMA channel can * suspend a lower priority channel (false). * @param preemption eDMA channel can be temporarily suspended by the service request of a higher * priority channel (true). eDMA channel can't be suspended by a higher priority channel (false). */ static inline void EDMA_HAL_SetChannelPreemptMode( uint32_t baseAddr, uint32_t channel, bool preempt, bool preemption) { assert(channel < FSL_FEATURE_EDMA_MODULE_CHANNEL); BW_DMA_DCHPRIn_DPA(baseAddr, HW_DMA_DCHPRIn_CHANNEL(channel), preempt); BW_DMA_DCHPRIn_ECP(baseAddr, HW_DMA_DCHPRIn_CHANNEL(channel), preemption); } /*! * @brief Sets the eDMA channel priority. * * @param baseAddr Register base address for eDMA module. * @param channel eDMA channel number. * @param priority Priority of the DMA channel. Different channels should have different priority * setting inside a group. */ static inline void EDMA_HAL_SetChannelPriority( uint32_t baseAddr, uint32_t channel, edma_channel_priority_t priority) { assert(channel < FSL_FEATURE_EDMA_MODULE_CHANNEL); BW_DMA_DCHPRIn_CHPRI(baseAddr, HW_DMA_DCHPRIn_CHANNEL(channel), priority); } /*! * @brief Sets the channel arbitration algorithm. * * @param baseAddr Register base address for eDMA module. * @param channelArbitration Round-Robin way for fixed priority way. */ static inline void EDMA_HAL_SetChannelArbitrationMode( uint32_t baseAddr, edma_channel_arbitration_t channelArbitration) { BW_DMA_CR_ERCA(baseAddr, channelArbitration); } #if (FSL_FEATURE_EDMA_CHANNEL_GROUP_COUNT > 0x1U) /*! * @brief Configures the group priority. * * This function configures the priority for group 0 and group 1. * * @param baseAddr Register base address for eDMA module. * @param groupPriority Group priority configuration. Note that each group get its own * group priority. */ void EDMA_HAL_SetGroupPriority(uint32_t baseAddr, edma_group_priority_t groupPriority); /*! * @brief Sets the eDMA group arbitration algorithm. * * @param baseAddr Register base address for eDMA module. * @param groupArbitration Group arbitration way. Fixed-Priority way or Round-Robin way. */ static inline void EDMA_HAL_SetGroupArbitrationMode( uint32_t baseAddr, edma_group_arbitration_t groupArbitration) { BW_DMA_CR_ERGA(baseAddr, groupArbitration); } #endif /* @} */ /*! * @name eDMA HAL driver configuration and operation. * @{ */ /*! * @brief Enables/Disables the minor loop mapping. * * This function enables/disables the minor loop mapping feature. * If enabled, the NBYTES is redefined to include the individual enable fields and the NBYTES field. The * individual enable fields allow the minor loop offset to be applied to the source address, the * destination address, or both. The NBYTES field is reduced when either offset is enabled. * * @param baseAddr Register base address for eDMA module. * @param enable Enables (true) or Disable (false) minor loop mapping. */ static inline void EDMA_HAL_SetMinorLoopMappingCmd(uint32_t baseAddr, bool enable) { BW_DMA_CR_EMLM(baseAddr, enable); } /*! * @brief Enables or disables the continuous transfer mode. * * This function enables or disables the continuous transfer. If set, a minor loop channel link * does not go through the channel arbitration before being activated again. Upon minor loop * completion, the channel activates again if that channel has a minor loop channel link enabled and * the link channel is itself. * * @param baseAddr Register base address for eDMA module. * @param continuous Enables (true) or Disable (false) continuous transfer mode. */ static inline void EDMA_HAL_SetContinuousLinkCmd(uint32_t baseAddr, bool continuous) { BW_DMA_CR_CLM(baseAddr, continuous); } /*! * @brief Gets the error status of the eDMA module. * * @param baseAddr Register base address for eDMA module. * @return Detailed information of the error type in the eDMA module. */ static inline uint32_t EDMA_HAL_GetErrorStatus(uint32_t baseAddr) { return HW_DMA_ES_RD(baseAddr); } /*! * @brief Enables/Disables the error interrupt for channels. * * @param baseAddr Register base address for eDMA module. * @param enable Enable(true) or Disable (false) error interrupt. * @param channel Channel indicator. If kEDMAAllChannel is selected, all channels' error interrupt * will be enabled/disabled. */ void EDMA_HAL_SetErrorIntCmd(uint32_t baseAddr, bool enable, edma_channel_indicator_t channel); /*! * @brief Checks whether the eDMA channel error interrupt is enabled or disabled. * * @param baseAddr Register base address for eDMA module. * @param channel eDMA channel number. * @return Error interrupt is enabled (true) or disabled (false). */ bool EDMA_HAL_GetErrorIntCmd(uint32_t baseAddr, uint32_t channel); /*! * @brief Gets the eDMA error interrupt status. * * @param baseAddr Register base address for eDMA module. * @param channel eDMA channel number. * @return 32 bit variable indicating error channels. If error happens on eDMA channel n, the bit n * of this variable is '1'. If not, the bit n of this variable is '0'. */ static inline uint32_t EDMA_HAL_GetErrorIntStatusFlag(uint32_t baseAddr) { return HW_DMA_ERR_RD(baseAddr); } /*! * @brief Clears the error interrupt status for the eDMA channel or channels. * * @param baseAddr Register base address for eDMA module. * @param enable Enable(true) or Disable (false) error interrupt. * @param channel Channel indicator. If kEDMAAllChannel is selected, all channels' error interrupt * status will be cleared. */ static inline void EDMA_HAL_ClearErrorIntStatusFlag( uint32_t baseAddr, edma_channel_indicator_t channel) { HW_DMA_CERR_WR(baseAddr, channel); } /*! * @brief Enables/Disables the DMA request for the channel or all channels. * * @param baseAddr Register base address for eDMA module. * @param enable Enable(true) or Disable (false) DMA request. * @param channel Channel indicator. If kEDMAAllChannel is selected, all channels DMA request * are enabled/disabled. */ void EDMA_HAL_SetDmaRequestCmd(uint32_t baseAddr, edma_channel_indicator_t channel,bool enable); /*! * @brief Checks whether the eDMA channel DMA request is enabled or disabled. * * @param baseAddr Register base address for eDMA module. * @param channel eDMA channel number. * @return DMA request is enabled (true) or disabled (false). */ static inline bool EDMA_HAL_GetDmaRequestCmd(uint32_t baseAddr, uint32_t channel) { assert(channel < FSL_FEATURE_EDMA_MODULE_CHANNEL); return ((HW_DMA_ERQ_RD(baseAddr) >> channel) & 1U); } /*! * @brief Gets the eDMA channel DMA request status. * * @param baseAddr Register base address for eDMA module. * @param channel eDMA channel number. * @return Hardware request is triggered in this eDMA channel (true) or not be triggered in this * channel (false). */ static inline bool EDMA_HAL_GetDmaRequestStatusFlag(uint32_t baseAddr, uint32_t channel) { assert(channel < FSL_FEATURE_EDMA_MODULE_CHANNEL); return (((uint32_t)HW_DMA_HRS_RD(baseAddr) >> channel) & 1U); } /*! * @brief Clears the done status for a channel or all channels. * * @param baseAddr Register base address for eDMA module. * @param channel Channel indicator. If kEDMAAllChannel is selected, all channels' done status will * be cleared. */ static inline void EDMA_HAL_ClearDoneStatusFlag(uint32_t baseAddr, edma_channel_indicator_t channel) { HW_DMA_CDNE_WR(baseAddr, channel); } /*! * @brief Triggers the eDMA channel. * * @param baseAddr Register base address for eDMA module. * @param channel Channel indicator. If kEDMAAllChannel is selected, all channels are tirggere. */ static inline void EDMA_HAL_TriggerChannelStart(uint32_t baseAddr, edma_channel_indicator_t channel) { HW_DMA_SSRT_WR(baseAddr, channel); } /*! * @brief Gets the eDMA channel interrupt request status. * * @param baseAddr Register base address for eDMA module. * @param channel eDMA channel number. * @return Interrupt request happens in this eDMA channel (true) or not happen in this * channel (false). */ static inline bool EDMA_HAL_GetIntStatusFlag(uint32_t baseAddr, uint32_t channel) { assert(channel < FSL_FEATURE_EDMA_MODULE_CHANNEL); return (((uint32_t)HW_DMA_INT_RD(baseAddr) >> channel) & 1U); } /*! * @brief Gets the eDMA all channel's interrupt request status. * * @param baseAddr Register base address for eDMA module. * @param channel eDMA channel number. * @return Interrupt status flag of all channels. */ static inline uint32_t EDMA_HAL_GetAllIntStatusFlag(uint32_t baseAddr) { return (uint32_t)HW_DMA_INT_RD(baseAddr); } /*! * @brief Clears the interrupt status for the eDMA channel or all channels. * * @param baseAddr Register base address for eDMA module. * @param enable Enable(true) or Disable (false) error interrupt. * @param channel Channel indicator. If kEDMAAllChannel is selected, all channels' interrupt * status will be cleared. */ static inline void EDMA_HAL_ClearIntStatusFlag( uint32_t baseAddr, edma_channel_indicator_t channel) { HW_DMA_CINT_WR(baseAddr, channel); } #if (FSL_FEATURE_EDMA_ASYNCHRO_REQUEST_CHANNEL_COUNT > 0x0U) /*! * @brief Enables/Disables an asynchronous request in stop mode. * * @param baseAddr Register base address for eDMA module. * @param channel eDMA channel number. * @param enable Enable (true) or Disable (false) async DMA request. */ void EDMA_HAL_SetAsyncRequestInStopModeCmd(uint32_t baseAddr, uint32_t channel, bool enable); #endif /* @} */ /*! * @name eDMA HAL driver hardware TCD configuration functions. * @{ */ /*! * @brief Clears all registers to 0 for the hardware TCD. * * @param baseAddr Register base address for eDMA module. * @param channel eDMA channel number. */ void EDMA_HAL_HTCDClearReg(uint32_t baseAddr, uint32_t channel); /*! * @brief Configures the source address for the hardware TCD. * * @param baseAddr Register base address for eDMA module. * @param channel eDMA channel number. * @param address The pointer to the source memory address. */ static inline void EDMA_HAL_HTCDSetSrcAddr(uint32_t baseAddr, uint32_t channel, uint32_t address) { assert(channel < FSL_FEATURE_EDMA_MODULE_CHANNEL); BW_DMA_TCDn_SADDR_SADDR(baseAddr, channel, address); } /*! * @brief Configures the source address signed offset for the hardware TCD. * * Sign-extended offset applied to the current source address to form the next-state value as each * source read is complete. * * @param baseAddr Register base address for eDMA module. * @param channel eDMA channel number. * @param offset signed-offset for source address. */ static inline void EDMA_HAL_HTCDSetSrcOffset(uint32_t baseAddr, uint32_t channel, int16_t offset) { assert(channel < FSL_FEATURE_EDMA_MODULE_CHANNEL); BW_DMA_TCDn_SOFF_SOFF(baseAddr, channel, offset); } /*! * @brief Configures the transfer attribute for the eDMA channel. * * @param baseAddr Register base address for eDMA module. * @param channel eDMA channel number. * @param srcModulo enumeration type for an allowed source modulo. The value defines a specific address range * specified as the value after the SADDR + SOFF calculation is performed on the original register * value. Setting this field provides the ability to implement a circular data. For data queues * requiring power-of-2 size bytes, the queue should start at a 0-modulo-size address and the SMOD * field should be set to the appropriate value for the queue, freezing the desired number of upper * address bits. The value programmed into this field specifies the number of the lower address bits * allowed to change. For a circular queue application, the SOFF is typically set to the transfer * size to implement post-increment addressing with SMOD function restricting the addresses to a * 0-modulo-size range. * @param destModulo Enum type for an allowed destination modulo. * @param srcTransferSize Enum type for source transfer size. * @param destTransferSize Enum type for destination transfer size. */ void EDMA_HAL_HTCDSetAttribute( uint32_t baseAddr, uint32_t channel, edma_modulo_t srcModulo, edma_modulo_t destModulo, edma_transfer_size_t srcTransferSize, edma_transfer_size_t destTransferSize); /*! * @brief Configures the nbytes for the eDMA channel. * * Note here that user need firstly configure the minor loop mapping feature and then call this * function. * * @param baseAddr Register base address for eDMA module. * @param channel eDMA channel number. * @param nbytes Number of bytes to be transferred in each service request of the channel */ void EDMA_HAL_HTCDSetNbytes(uint32_t baseAddr, uint32_t channel, uint32_t nbytes); /*! * @brief Gets the nbytes configuration data for the hardware TCD. * * This function decides whether the minor loop mapping is enabled or whether the source/dest * minor loop mapping is enabled. Then, the nbytes are returned accordingly. * * @param baseAddr Register base address for eDMA module. * @param channel eDMA channel number. * @return nbytes configuration according to minor loop setting. */ uint32_t EDMA_HAL_HTCDGetNbytes(uint32_t baseAddr, uint32_t channel); /*! * @brief Configures the minor loop offset for the hardware TCD. * * Configures both the enable bits and the offset value. If neither source nor destination offset is enabled, * offset is not configured. Note here if source or destination offset is required, the eDMA module * EMLM bit will be set in this function. User need to know this side effect. * * @param baseAddr Register base address for eDMA module. * @param channel eDMA channel number. * @param config Configuration data structure for the minor loop offset */ void EDMA_HAL_HTCDSetMinorLoopOffset( uint32_t baseAddr, uint32_t channel, edma_minorloop_offset_config_t *config); /*! * @brief Configures the last source address adjustment for the hardware TCD. * * Adjustment value added to the source address at the completion of the major iteration count. This * value can be applied to restore the source address to the initial value, or adjust the address to * reference the next data structure. * * @param baseAddr Register base address for eDMA module. * @param channel eDMA channel number. * @param size adjustment value */ static inline void EDMA_HAL_HTCDSetSrcLastAdjust(uint32_t baseAddr, uint32_t channel, int32_t size) { assert(channel < FSL_FEATURE_EDMA_MODULE_CHANNEL); BW_DMA_TCDn_SLAST_SLAST(baseAddr, channel, size); } /*! * @brief Configures the destination address for the hardware TCD. * * @param baseAddr Register base address for eDMA module. * @param channel eDMA channel number. * @param address The pointer to the destination address. */ static inline void EDMA_HAL_HTCDSetDestAddr(uint32_t baseAddr, uint32_t channel, uint32_t address) { assert(channel < FSL_FEATURE_EDMA_MODULE_CHANNEL); BW_DMA_TCDn_DADDR_DADDR(baseAddr, channel, address); } /*! * @brief Configures the destination address signed offset for the hardware TCD. * * Sign-extended offset applied to the current source address to form the next-state value as each * destination write is complete. * * @param baseAddr Register base address for eDMA module. * @param channel eDMA channel number. * @param offset signed-offset */ static inline void EDMA_HAL_HTCDSetDestOffset(uint32_t baseAddr, uint32_t channel, int16_t offset) { assert(channel < FSL_FEATURE_EDMA_MODULE_CHANNEL); BW_DMA_TCDn_DOFF_DOFF(baseAddr, channel, offset); } /*! * @brief Configures the last source address adjustment. * * This function adds an adjustment value added to the source address at the completion of the major * iteration count. This value can be applied to restore the source address to the initial value, or * adjust the address to reference the next data structure. * * @param baseAddr Register base address for eDMA module. * @param channel eDMA channel number. * @param adjust adjustment value */ static inline void EDMA_HAL_HTCDSetDestLastAdjust( uint32_t baseAddr, uint32_t channel, uint32_t adjust) { assert(channel < FSL_FEATURE_EDMA_MODULE_CHANNEL); BW_DMA_TCDn_DLASTSGA_DLASTSGA(baseAddr, channel, adjust); } /*! * @brief Configures the memory address for the next transfer TCD for the hardware TCD. * * * This function enables the scatter/gather feature for the hardware TCD and configures the next * TCD's address. This address points to the beginning of a 0-modulo-32 byte region containing * the next transfer TCD to be loaded into this channel. The channel reload is performed as the * major iteration count completes. The scatter/gather address must be 0-modulo-32-byte. Otherwise, * a configuration error is reported. * * @param baseAddr Register base address for eDMA module. * @param channel eDMA channel number. * @param stcd The pointer to the TCD to be linked to this hardware TCD. */ void EDMA_HAL_HTCDSetScatterGatherLink( uint32_t baseAddr, uint32_t channel, edma_software_tcd_t *stcd); /*! * @brief Configures the bandwidth for the hardware TCD. * * Throttles the amount of bus bandwidth consumed by the eDMA. In general, as the eDMA processes the * minor loop, it continuously generates read/write sequences until the minor count is exhausted. * This field forces the eDMA to stall after the completion of each read/write access to control the * bus request bandwidth seen by the crossbar switch. * * @param baseAddr Register base address for eDMA module. * @param channel eDMA channel number. * @param bandwidth enum type for bandwidth control */ static inline void EDMA_HAL_HTCDSetBandwidth( uint32_t baseAddr, uint32_t channel, edma_bandwidth_config_t bandwidth) { assert(channel < FSL_FEATURE_EDMA_MODULE_CHANNEL); BW_DMA_TCDn_CSR_BWC(baseAddr, channel, bandwidth); } /*! * @brief Configures the major channel link the hardware TCD. * * If the major link is enabled, after the major loop counter is exhausted, the eDMA engine initiates a * channel service request at the channel defined by these six bits by setting that channel start * bits. * * @param baseAddr Register base address for eDMA module. * @param channel eDMA channel number. * @param majorChannel channel number for major link * @param enable Enables (true) or Disables (false) channel major link. */ static inline void EDMA_HAL_HTCDSetChannelMajorLink( uint32_t baseAddr, uint32_t channel, uint32_t majorChannel, bool enable) { assert(channel < FSL_FEATURE_EDMA_MODULE_CHANNEL); BW_DMA_TCDn_CSR_MAJORLINKCH(baseAddr, channel, majorChannel); BW_DMA_TCDn_CSR_MAJORELINK(baseAddr, channel, enable); } /*! * @brief Gets the major link channel for the hardware TCD. * * @param baseAddr Register base address for eDMA module. * @param channel eDMA channel number. * @return major link channel number */ static inline uint32_t EDMA_HAL_HTCDGetMajorLinkChannel(uint32_t baseAddr, uint32_t channel) { assert(channel < FSL_FEATURE_EDMA_MODULE_CHANNEL); return BR_DMA_TCDn_CSR_MAJORLINKCH(baseAddr, channel); } /*! * @brief Enables/Disables the scatter/gather feature for the hardware TCD. * * @param baseAddr Register base address for eDMA module. * @param channel eDMA channel number. * @param enable Enables (true) /Disables (false) scatter/gather feature. */ static inline void EDMA_HAL_HTCDSetScatterGatherCmd( uint32_t baseAddr, uint32_t channel, bool enable) { assert(channel < FSL_FEATURE_EDMA_MODULE_CHANNEL); BW_DMA_TCDn_CSR_ESG(baseAddr, channel, enable); } /*! * @brief Checks whether the scatter/gather feature is enabled for the hardware TCD. * * @param baseAddr Register base address for eDMA module. * @param channel eDMA channel number. * @return True stand for enabled. False stands for disabled. */ static inline bool EDMA_HAL_HTCDGetScatterGatherCmd(uint32_t baseAddr, uint32_t channel) { assert(channel < FSL_FEATURE_EDMA_MODULE_CHANNEL); return BR_DMA_TCDn_CSR_ESG(baseAddr, channel); } /*! * @brief Disables/Enables the DMA request after the major loop completes for the hardware TCD. * * If disabled, the eDMA hardware automatically clears the corresponding DMA request when the * current major iteration count reaches zero. * * @param baseAddr Register base address for eDMA module. * @param channel eDMA channel number. * @param disable Disable (true)/Enable (true) DMA request after TCD complete. */ static inline void EDMA_HAL_HTCDSetDisableDmaRequestAfterTCDDoneCmd( uint32_t baseAddr, uint32_t channel, bool disable) { assert(channel < FSL_FEATURE_EDMA_MODULE_CHANNEL); BW_DMA_TCDn_CSR_DREQ(baseAddr, channel, disable); } /*! * @brief Enables/Disables the half complete interrupt for the hardware TCD. * * If set, the channel generates an interrupt request by setting the appropriate bit in the * interrupt register when the current major iteration count reaches the halfway point. Specifically, * the comparison performed by the eDMA engine is (CITER == (BITER >> 1)). This half-way point * interrupt request is provided to support the double-buffered schemes or other types of data movement * where the processor needs an early indication of the transfer's process. * * @param baseAddr Register base address for eDMA module. * @param channel eDMA channel number. * @param enable Enable (true) /Disable (false) half complete interrupt. */ static inline void EDMA_HAL_HTCDSetHalfCompleteIntCmd( uint32_t baseAddr, uint32_t channel, bool enable) { assert(channel < FSL_FEATURE_EDMA_MODULE_CHANNEL); BW_DMA_TCDn_CSR_INTHALF(baseAddr, channel, enable); } /*! * @brief Enables/Disables the interrupt after the major loop completes for the hardware TCD. * * If enabled, the channel generates an interrupt request by setting the appropriate bit in the * interrupt register when the current major iteration count reaches zero. * * @param baseAddr Register base address for eDMA module. * @param channel eDMA channel number. * @param enable Enable (true) /Disable (false) interrupt after TCD done. */ static inline void EDMA_HAL_HTCDSetIntCmd( uint32_t baseAddr, uint32_t channel, bool enable) { assert(channel < FSL_FEATURE_EDMA_MODULE_CHANNEL); BW_DMA_TCDn_CSR_INTMAJOR(baseAddr, channel, enable); } /*! * @brief Triggers the start bits for the hardware TCD. * * The eDMA hardware automatically clears this flag after the channel begins execution. * * @param baseAddr Register base address for eDMA module. * @param channel eDMA channel number. */ static inline void EDMA_HAL_HTCDTriggerChannelStart(uint32_t baseAddr, uint32_t channel) { assert(channel < FSL_FEATURE_EDMA_MODULE_CHANNEL); BW_DMA_TCDn_CSR_START(baseAddr, channel, true); } /*! * @brief Checks whether the channel is running for the hardware TCD. * * @param baseAddr Register base address for eDMA module. * @param channel eDMA channel number. * @return True stands for running. False stands for not. */ static inline bool EDMA_HAL_HTCDGetChannelActiveStatus(uint32_t baseAddr, uint32_t channel) { assert(channel < FSL_FEATURE_EDMA_MODULE_CHANNEL); return BR_DMA_TCDn_CSR_ACTIVE(baseAddr, channel); } /*! * @brief Sets the channel minor link for the hardware TCD. * * @param baseAddr Register base address for eDMA module. * @param channel eDMA channel number. * @param linkChannel Channel to be linked on minor loop complete. * @param enable Enable (true)/Disable (false) channel minor link. */ void EDMA_HAL_HTCDSetChannelMinorLink( uint32_t baseAddr, uint32_t channel, uint32_t linkChannel, bool enable); /*! * @brief Sets the major iteration count according to minor loop channel link setting. * * Note here that user need to first set the minor loop channel link and then call this function. * The execute flow inside this function is dependent on the minor loop channel link setting. * * @param baseAddr Register base address for eDMA module. * @param channel eDMA channel number. * @param count major loop count */ void EDMA_HAL_HTCDSetMajorCount(uint32_t baseAddr, uint32_t channel, uint32_t count); /*! * @brief Gets the number of beginning major counts for the hardware TCD. * * @param baseAddr Register base address for eDMA module. * @param channel eDMA channel number. * @return Begin major counts. */ uint32_t EDMA_HAL_HTCDGetBeginMajorCount(uint32_t baseAddr, uint32_t channel); /*! * @brief Gets the number of current major counts for the hardware TCD. * * @param baseAddr Register base address for eDMA module. * @param channel eDMA channel number. * @return Current major counts. */ uint32_t EDMA_HAL_HTCDGetCurrentMajorCount(uint32_t baseAddr, uint32_t channel); /*! * @brief Gets the number of bytes already transferred for the hardware TCD. * * @param baseAddr Register base address for eDMA module. * @param channel eDMA channel number. * @return data bytes already transferred */ uint32_t EDMA_HAL_HTCDGetFinishedBytes(uint32_t baseAddr, uint32_t channel); /*! * @brief Gets the number of bytes haven't transferred for the hardware TCD. * * @param baseAddr Register base address for eDMA module. * @param channel eDMA channel number. * @return data bytes already transferred */ uint32_t EDMA_HAL_HTCDGetUnfinishedBytes(uint32_t baseAddr, uint32_t channel); /*! * @brief Gets the channel done status. * * @param baseAddr Register base address for eDMA module. * @param channel eDMA channel number. * @return If channel done. */ static inline bool EDMA_HAL_HTCDGetDoneStatusFlag(uint32_t baseAddr, uint32_t channel) { return BR_DMA_TCDn_CSR_DONE(baseAddr,channel); } /* @} */ /*! * @name EDMA HAL driver software TCD configuration functions. * @{ */ /*! * @brief Configures the source address for the software TCD. * * @param stcd The pointer to the software TCD. * @param channel eDMA channel number. * @param address The pointer to the source memory address. */ static inline void EDMA_HAL_STCDSetSrcAddr(edma_software_tcd_t *stcd, uint32_t address) { assert(stcd); stcd->SADDR = DMA_SADDR_SADDR(address); } /*! * @brief Configures the source address signed offset for the software TCD. * * Sign-extended offset applied to the current source address to form the next-state value as each * source read is complete. * * @param stcd The pointer to the software TCD. * @param offset signed-offset for source address. */ static inline void EDMA_HAL_STCDSetSrcOffset(edma_software_tcd_t *stcd, int16_t offset) { assert(stcd); stcd->SOFF = DMA_SOFF_SOFF(offset); } /*! * @brief Configures the transfer attribute for software TCD. * * @param stcd The pointer to the software TCD. * @param srcModulo enum type for an allowed source modulo. The value defines a specific address range * specified as the value after the SADDR + SOFF calculation is performed on the original register * value. Setting this field provides the ability to implement a circular data. For data queues * requiring power-of-2 size bytes, the queue should start at a 0-modulo-size address and the SMOD * field should be set to the appropriate value for the queue, freezing the desired number of upper * address bits. The value programmed into this field specifies the number of the lower address bits * allowed to change. For a circular queue application, the SOFF is typically set to the transfer * size to implement post-increment addressing with SMOD function restricting the addresses to a * 0-modulo-size range. * @param destModulo Enum type for an allowed destination modulo. * @param srcTransferSize Enum type for source transfer size. * @param destTransferSize Enum type for destinatio transfer size. */ void EDMA_HAL_STCDSetAttribute( edma_software_tcd_t *stcd, edma_modulo_t srcModulo, edma_modulo_t destModulo, edma_transfer_size_t srcTransferSize, edma_transfer_size_t destTransferSize); /*! * @brief Configures the nbytes for software TCD. * * Note here that user need firstly configure the minor loop mapping feature and then call this * function. * * @param baseAddr Register base address for eDMA module. * @param stcd The pointer to the software TCD. * @param nbytes Number of bytes to be transferred in each service request of the channel */ void EDMA_HAL_STCDSetNbytes(uint32_t baseAddr, edma_software_tcd_t *stcd, uint32_t nbytes); /*! * @brief Configures the minorloop offset for the software TCD. * * Configures both the enable bits and the offset value. If neither source nor dest offset is enabled, * offset is not configured. Note here if source or destination offset is requred, the eDMA module * EMLM bit will be set in this function. User need to know this side effect. * * @param baseAddr Register base address for eDMA module. * @param stcd The pointer to the software TCD. * @param config Configuration data structure for the minorloop offset */ void EDMA_HAL_STCDSetMinorLoopOffset( uint32_t baseAddr, edma_software_tcd_t *stcd, edma_minorloop_offset_config_t *config); /*! * @brief Configures the last source address adjustment for the software TCD. * * Adjustment value added to the source address at the completion of the major iteration count. This * value can be applied to restore the source address to the initial value, or adjust the address to * reference the next data structure. * * @param stcd The pointer to the software TCD. * @param size adjustment value */ static inline void EDMA_HAL_STCDSetSrcLastAdjust(edma_software_tcd_t *stcd, int32_t size) { assert(stcd); stcd->SLAST = (stcd->SLAST & ~DMA_SLAST_SLAST_MASK) | DMA_SLAST_SLAST(size); } /*! * @brief Configures the destination address for the software TCD. * * @param stcd The pointer to the software TCD. * @param address The pointer to the destination addresss. */ static inline void EDMA_HAL_STCDSetDestAddr(edma_software_tcd_t *stcd, uint32_t address) { assert(stcd); stcd->DADDR = DMA_DADDR_DADDR(address); } /*! * @brief Configures the destination address signed offset for the software TCD. * * Sign-extended offset applied to the current source address to form the next-state value as each * destination write is complete. * * @param stcd The pointer to the software TCD. * @param offset signed-offset */ static inline void EDMA_HAL_STCDSetDestOffset(edma_software_tcd_t *stcd, int16_t offset) { assert(stcd); stcd->DOFF = DMA_DOFF_DOFF(offset); } /*! * @brief Configures the last source address adjustment. * * This function add an adjustment value added to the source address at the completion of the major * iteration count. This value can be applied to restore the source address to the initial value, or * adjust the address to reference the next data structure. * * @param stcd The pointer to the software TCD. * @param adjust adjustment value */ static inline void EDMA_HAL_STCDSetDestLastAdjust( edma_software_tcd_t *stcd, uint32_t adjust) { assert(stcd); stcd->DLAST_SGA = DMA_DLAST_SGA_DLASTSGA(adjust); } /*! * @brief Configures the memory address for the next transfer TCD for the software TCD. * * * This function enable the scatter/gather feature for the software TCD and configure the next * TCD's address.This address points to the beginning of a 0-modulo-32 byte region containing * the next transfer TCD to be loaded into this channel. The channel reload is performed as the * major iteration count completes. The scatter/gather address must be 0-modulo-32-byte. Otherwise, * a configuration error is reported. * * @param stcd The pointer to the software TCD. * @param nextStcd The pointer to the TCD to be linked to this software TCD. */ void EDMA_HAL_STCDSetScatterGatherLink( edma_software_tcd_t *stcd, edma_software_tcd_t *nextStcd); /*! * @brief Configures the bandwidth for the software TCD. * * Throttles the amount of bus bandwidth consumed by the eDMA. In general, as the eDMA processes the * minor loop, it continuously generates read/write sequences until the minor count is exhausted. * This field forces the eDMA to stall after the completion of each read/write access to control the * bus request bandwidth seen by the crossbar switch. * * @param stcd The pointer to the software TCD. * @param bandwidth enum type for bandwidth control */ static inline void EDMA_HAL_STCDSetBandwidth( edma_software_tcd_t *stcd, edma_bandwidth_config_t bandwidth) { assert(stcd); stcd->CSR = (stcd->CSR & ~DMA_CSR_BWC_MASK) | DMA_CSR_BWC(bandwidth); } /*! * @brief Configures the major channel link the software TCD. * * If the majorlink is enabled, after the major loop counter is exhausted, the eDMA engine initiates a * channel service request at the channel defined by these six bits by setting that channel start * bits. * * @param stcd The pointer to the software TCD. * @param majorChannel channel number for major link * @param enable Enables (true) or Disables (false) channel major link. */ static inline void EDMA_HAL_STCDSetChannelMajorLink( edma_software_tcd_t *stcd, uint32_t majorChannel, bool enable) { assert(stcd); stcd->CSR = (stcd->CSR & ~DMA_CSR_MAJORLINKCH_MASK) | DMA_CSR_MAJORLINKCH(majorChannel); stcd->CSR = (stcd->CSR & ~DMA_CSR_MAJORELINK_MASK) | ((uint32_t)enable << DMA_CSR_MAJORELINK_SHIFT); } /*! * @brief Enables/Disables the scatter/gather feature for the software TCD. * * @param stcd The pointer to the software TCD. * @param enable Enables (true) /Disables (false) scatter/gather feature. */ static inline void EDMA_HAL_STCDSetScatterGatherCmd( edma_software_tcd_t *stcd, bool enable) { assert(stcd); stcd->CSR = (stcd->CSR & ~DMA_CSR_ESG_MASK) | ((uint32_t)enable << DMA_CSR_ESG_SHIFT); } /*! * @brief Disables/Enables the DMA request after the major loop completes for the software TCD. * * If disabled, the eDMA hardware automatically clears the corresponding DMA request when the * current major iteration count reaches zero. * * @param stcd The pointer to the software TCD. * @param disable Disable (true)/Enable (true) dma request after TCD complete. */ static inline void EDMA_HAL_STCDSetDisableDmaRequestAfterTCDDoneCmd( edma_software_tcd_t *stcd, bool disable) { assert(stcd); stcd->CSR = (stcd->CSR & ~DMA_CSR_DREQ_MASK) | ((uint32_t)disable << DMA_CSR_DREQ_SHIFT); } /*! * @brief Enables/Disables the half complete interrupt for the software TCD. * * If set, the channel generates an interrupt request by setting the appropriate bit in the * interrupt register when the current major iteration count reaches the halfway point. Specifically, * the comparison performed by the eDMA engine is (CITER == (BITER >> 1)). This half-way point * interrupt request is provided to support the double-buffered schemes or other types of data movement * where the processor needs an early indication of the transfer's process. * * @param stcd The pointer to the software TCD. * @param enable Enable (true) /Disable (false) half complete interrupt. */ static inline void EDMA_HAL_STCDSetHalfCompleteIntCmd( edma_software_tcd_t *stcd, bool enable) { assert(stcd); stcd->CSR = (stcd->CSR & ~DMA_CSR_INTHALF_MASK) | ((uint32_t)enable << DMA_CSR_INTHALF_SHIFT); } /*! * @brief Enables/Disables the interrupt after the major loop completes for the software TCD. * * If enabled, the channel generates an interrupt request by setting the appropriate bit in the * interrupt register when the current major iteration count reaches zero. * * @param stcd The pointer to the software TCD. * @param enable Enable (true) /Disable (false) interrupt after TCD done. */ static inline void EDMA_HAL_STCDSetIntCmd(edma_software_tcd_t *stcd, bool enable) { assert(stcd); stcd->CSR = (stcd->CSR & ~DMA_CSR_INTMAJOR_MASK) | ((uint32_t)enable << DMA_CSR_INTMAJOR_SHIFT); } /*! * @brief Triggers the start bits for the software TCD. * * The eDMA hardware automatically clears this flag after the channel begins execution. * * @param stcd The pointer to the software TCD. */ static inline void EDMA_HAL_STCDTriggerChannelStart(edma_software_tcd_t *stcd) { assert(stcd); stcd->CSR |= DMA_CSR_START_MASK; } /*! * @brief Set Channel minor link for software TCD. * * @param stcd The pointer to the software TCD. * @param linkChannel Channel to be linked on minor loop complete. * @param enable Enable (true)/Disable (false) channel minor link. */ void EDMA_HAL_STCDSetChannelMinorLink( edma_software_tcd_t *stcd, uint32_t linkChannel, bool enable); /*! * @brief Sets the major iteration count according to minor loop channel link setting. * * Note here that user need to first set the minor loop channel link and then call this function. * The execute flow inside this function is dependent on the minor loop channel link setting. * * @param stcd The pointer to the software TCD. * @param count major loop count */ void EDMA_HAL_STCDSetMajorCount(edma_software_tcd_t *stcd, uint32_t count); /*! * @brief Copy the software TCD configuration to the hardware TCD. * * @param baseAddr Register base address for eDMA module. * @param channel eDMA channel number. * @param stcd The pointer to the software TCD. */ void EDMA_HAL_PushSTCDToHTCD(uint32_t baseAddr, uint32_t channel, edma_software_tcd_t *stcd); /*! * @brief Set the basic transfer for software TCD. * * This function is used to setup the basic transfer for software TCD. The minor loop setting is not * involved here cause minor loop's configuration will lay a impact on the global eDMA setting. And * the source minor loop offset is relevant to the dest minor loop offset. For these reasons, minor * loop offset configuration is treated as an advanced configuration. User can call the * EDMA_HAL_STCDSetMinorLoopOffset() to configure the minor loop offset feature. * * @param baseAddr Register base address for eDMA module. * @param stcd The pointer to the software TCD. * @param config The pointer to the transfer configuration structure. * @param enableInt Enables (true) or Disables (false) interrupt on TCD complete. * @param disableDmaRequest Disables (true) or Enable (false) dma request on TCD complete. */ edma_status_t EDMA_HAL_STCDSetBasicTransfer( uint32_t baseAddr, edma_software_tcd_t *stcd, edma_transfer_config_t *config, bool enableInt, bool disableDmaRequest); /* @} */ #if defined(__cplusplus) } #endif /*! @} */ #endif /* __EDMA_HAL_H__ */ /******************************************************************************* * EOF ******************************************************************************/ ================================================ FILE: Zelig/mbed/TARGET_K64F/TARGET_Freescale/TARGET_KPSDK_MCUS/TARGET_KPSDK_CODE/hal/enet/fsl_enet_features.h ================================================ /* * Copyright (c) 2013 - 2014, Freescale Semiconductor, Inc. * All rights reserved. * * Redistribution and use in source and binary forms, with or without modification, * are permitted provided that the following conditions are met: * * o Redistributions of source code must retain the above copyright notice, this list * of conditions and the following disclaimer. * * o Redistributions in binary form must reproduce the above copyright notice, this * list of conditions and the following disclaimer in the documentation and/or * other materials provided with the distribution. * * o Neither the name of Freescale Semiconductor, Inc. nor the names of its * contributors may be used to endorse or promote products derived from this * software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT 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. */ #if !defined(__FSL_ENET_FEATURES_H__) #define __FSL_ENET_FEATURES_H__ #if defined(CPU_MK63FN1M0VMD12) || defined(CPU_MK63FN1M0VMD12WS) #define FSL_FEATURE_ENET_DMA_BIG_ENDIAN_ONLY (1) #define FSL_FEATURE_ENET_SUPPORT_PTP (0) #define FSL_FEATURE_ENET_INTERRUPT_COUNT (4) #define FSL_FEATURE_ENET_PTP_TIMER_CHANNEL_INTERRUPT (0) #elif defined(CPU_MK64FN1M0VMD12) || defined(CPU_MK64FX512VMD12) #define FSL_FEATURE_ENET_DMA_BIG_ENDIAN_ONLY (0) #define FSL_FEATURE_ENET_SUPPORT_PTP (0) #define FSL_FEATURE_ENET_INTERRUPT_COUNT (4) #define FSL_FEATURE_ENET_PTP_TIMER_CHANNEL_INTERRUPT (0) #elif defined(CPU_MK70FN1M0VMJ12) #define FSL_FEATURE_ENET_DMA_BIG_ENDIAN_ONLY (1) #define FSL_FEATURE_ENET_SUPPORT_PTP (0) #define FSL_FEATURE_ENET_INTERRUPT_COUNT (4) #else #define MBED_NO_ENET #endif #endif /* __FSL_ENET_FEATURES_H__*/ /******************************************************************************* * EOF ******************************************************************************/ ================================================ FILE: Zelig/mbed/TARGET_K64F/TARGET_Freescale/TARGET_KPSDK_MCUS/TARGET_KPSDK_CODE/hal/enet/fsl_enet_hal.h ================================================ /* * Copyright (c) 2013 - 2014, Freescale Semiconductor, Inc. * All rights reserved. * * Redistribution and use in source and binary forms, with or without modification, * are permitted provided that the following conditions are met: * * o Redistributions of source code must retain the above copyright notice, this list * of conditions and the following disclaimer. * * o Redistributions in binary form must reproduce the above copyright notice, this * list of conditions and the following disclaimer in the documentation and/or * other materials provided with the distribution. * * o Neither the name of Freescale Semiconductor, Inc. nor the names of its * contributors may be used to endorse or promote products derived from this * software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT 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. */ #ifndef __FSL_ENET_HAL_H__ #define __FSL_ENET_HAL_H__ #include #include #include "fsl_device_registers.h" #include "fsl_enet_features.h" #include #ifndef MBED_NO_ENET /*! * @addtogroup enet_hal * @{ */ /******************************************************************************* * Definitions ******************************************************************************/ /*! @brief Defines the system endian type.*/ #define SYSTEM_LITTLE_ENDIAN (1) /*! @brief Define macro to do the endianness swap*/ #define BSWAP_16(x) (uint16_t)((uint16_t)(((uint16_t)(x) & (uint16_t)0xFF00) >> 0x8) | (uint16_t)(((uint16_t)(x) & (uint16_t)0xFF) << 0x8)) #define BSWAP_32(x) (uint32_t)((((uint32_t)(x) & 0x00FFU) << 24) | (((uint32_t)(x) & 0x00FF00U) << 8) | (((uint32_t)(x) & 0xFF0000U) >> 8) | (((uint32_t)(x) & 0xFF000000U) >> 24)) #if SYSTEM_LITTLE_ENDIAN && FSL_FEATURE_ENET_DMA_BIG_ENDIAN_ONLY #define HTONS(n) BSWAP_16(n) #define HTONL(n) BSWAP_32(n) #define NTOHS(n) BSWAP_16(n) #define NTOHL(n) BSWAP_32(n) #else #define HTONS(n) (n) #define HTONL(n) (n) #define NTOHS(n) (n) #define NTOHL(n) (n) #endif /*! @brief Defines the Status return codes.*/ typedef enum _enet_status { kStatus_ENET_Success = 0, kStatus_ENET_InvalidInput, /*!< Invalid ENET input parameter */ kStatus_ENET_MemoryAllocateFail, /*!< Memory allocate failure*/ kStatus_ENET_GetClockFreqFail, /*!< Get clock frequency failure*/ kStatus_ENET_Initialized, /*!< ENET device already initialized*/ kStatus_ENET_Layer2QueueNull, /*!< NULL L2 PTP buffer queue pointer*/ kStatus_ENET_Layer2OverLarge, /*!< Layer2 packet length over large*/ kStatus_ENET_Layer2BufferFull, /*!< Layer2 packet buffer full*/ kStatus_ENET_PtpringBufferFull, /*!< PTP ring buffer full*/ kStatus_ENET_PtpringBufferEmpty, /*!< PTP ring buffer empty*/ kStatus_ENET_Miiuninitialized, /*!< MII uninitialized*/ kStatus_ENET_RxbdInvalid, /*!< Receive buffer descriptor invalid*/ kStatus_ENET_RxbdEmpty, /*!< Receive buffer descriptor empty*/ kStatus_ENET_RxbdTrunc, /*!< Receive buffer descriptor truncate*/ kStatus_ENET_RxbdError, /*!< Receive buffer descriptor error*/ kStatus_ENET_RxBdFull, /*!< Receive buffer descriptor full*/ kStatus_ENET_SmallBdSize, /*!< Small receive buffer size*/ kStatus_ENET_LargeBufferFull, /*!< Receive large buffer full*/ kStatus_ENET_TxbdFull, /*!< Transmit buffer descriptor full*/ kStatus_ENET_TxbdNull, /*!< Transmit buffer descriptor Null*/ kStatus_ENET_TxBufferNull, /*!< Transmit data buffer Null*/ kStatus_ENET_NoRxBufferLeft, /*!< No more receive buffer left*/ kStatus_ENET_UnknownCommand, /*!< Invalid ENET PTP IOCTL command*/ kStatus_ENET_TimeOut, /*!< ENET Timeout*/ kStatus_ENET_MulticastPointerNull, /*!< Null multicast group pointer*/ kStatus_ENET_AlreadyAddedMulticast /*!< Have Already added to multicast group*/ } enet_status_t; #if FSL_FEATURE_ENET_DMA_BIG_ENDIAN_ONLY && SYSTEM_LITTLE_ENDIAN /*! @brief Defines the control and status regions of the receive buffer descriptor.*/ typedef enum _enet_rx_bd_control_status { kEnetRxBdBroadCast = 0x8000, /*!< Broadcast */ kEnetRxBdMultiCast = 0x4000, /*!< Multicast*/ kEnetRxBdLengthViolation = 0x2000, /*!< Receive length violation*/ kEnetRxBdNoOctet = 0x1000, /*!< Receive non-octet aligned frame*/ kEnetRxBdCrc = 0x0400, /*!< Receive CRC error*/ kEnetRxBdOverRun = 0x0200, /*!< Receive FIFO overrun*/ kEnetRxBdTrunc = 0x0100, /*!< Frame is truncated */ kEnetRxBdEmpty = 0x0080, /*!< Empty bit*/ kEnetRxBdRxSoftOwner1 = 0x0040, /*!< Receive software owner*/ kEnetRxBdWrap = 0x0020, /*!< Update buffer descriptor*/ kEnetRxBdRxSoftOwner2 = 0x0010, /*!< Receive software owner*/ kEnetRxBdLast = 0x0008, /*!< Last BD in the frame*/ kEnetRxBdMiss = 0x0001 /*!< Receive for promiscuous mode*/ } enet_rx_bd_control_status_t; /*! @brief Defines the control extended regions of the receive buffer descriptor.*/ typedef enum _enet_rx_bd_control_extend { kEnetRxBdUnicast = 0x0001, /*!< Unicast frame*/ kEnetRxBdCollision = 0x0002, /*!< BD collision*/ kEnetRxBdPhyErr = 0x0004, /*!< PHY error*/ kEnetRxBdMacErr = 0x0080, /*!< Mac error*/ kEnetRxBdIpv4 = 0x0100, /*!< Ipv4 frame*/ kEnetRxBdIpv6 = 0x0200, /*!< Ipv6 frame*/ kEnetRxBdVlan = 0x0400, /*!< VLAN*/ kEnetRxBdProtocolChecksumErr = 0x1000, /*!< Protocol checksum error*/ kEnetRxBdIpHeaderChecksumErr = 0x2000, /*!< IP header checksum error*/ kEnetRxBdIntrrupt = 0x8000 /*!< BD interrupt*/ } enet_rx_bd_control_extend_t; /*! @brief Defines the control status region of the transmit buffer descriptor.*/ typedef enum _enet_tx_bd_control_status { kEnetTxBdReady = 0x0080, /*!< Ready bit*/ kEnetTxBdTxSoftOwner1 = 0x0040, /*!< Transmit software owner*/ kEnetTxBdWrap = 0x0020, /*!< Wrap buffer descriptor*/ kEnetTxBdTxSoftOwner2 = 0x0010, /*!< Transmit software owner*/ kEnetTxBdLast = 0x0008, /*!< Last BD in the frame*/ kEnetTxBdTransmitCrc = 0x0004 /*!< Receive for transmit CRC*/ } enet_tx_bd_control_status_t; /*! @brief Defines the control extended region of the transmit buffer descriptor.*/ typedef enum _enet_tx_bd_control_extend { kEnetTxBdTxErr = 0x0080, /*!< Transmit error*/ kEnetTxBdTxUnderFlowErr = 0x0020, /*!< Underflow error*/ kEnetTxBdExcessCollisionErr = 0x0010, /*!< Excess collision error*/ kEnetTxBdTxFrameErr = 0x0008, /*!< Frame error*/ kEnetTxBdLatecollisionErr = 0x0004, /*!< Late collision error*/ kEnetTxBdOverFlowErr = 0x0002, /*!< Overflow error*/ kEnetTxTimestampErr = 0x0001 /*!< Timestamp error*/ } enet_tx_bd_control_extend_t; /*! @brief Defines the control extended2 region of the transmit buffer descriptor.*/ typedef enum _enet_tx_bd_control_extend2 { kEnetTxBdTxInterrupt = 0x0040, /*!< Transmit interrupt*/ kEnetTxBdTimeStamp = 0x0020 /*!< Transmit timestamp flag */ } enet_tx_bd_control_extend2_t; #else /*! @brief Defines the control and status region of the receive buffer descriptor.*/ typedef enum _enet_rx_bd_control_status { kEnetRxBdEmpty = 0x8000, /*!< Empty bit*/ kEnetRxBdRxSoftOwner1 = 0x4000, /*!< Receive software owner*/ kEnetRxBdWrap = 0x2000, /*!< Update buffer descriptor*/ kEnetRxBdRxSoftOwner2 = 0x1000, /*!< Receive software owner*/ kEnetRxBdLast = 0x0800, /*!< Last BD in the frame*/ kEnetRxBdMiss = 0x0100, /*!< Receive for promiscuous mode*/ kEnetRxBdBroadCast = 0x0080, /*!< Broadcast */ kEnetRxBdMultiCast = 0x0040, /*!< Multicast*/ kEnetRxBdLengthViolation = 0x0020, /*!< Receive length violation*/ kEnetRxBdNoOctet = 0x0010, /*!< Receive non-octet aligned frame*/ kEnetRxBdCrc = 0x0004, /*!< Receive CRC error*/ kEnetRxBdOverRun = 0x0002, /*!< Receive FIFO overrun*/ kEnetRxBdTrunc = 0x0001 /*!< Frame is truncated */ } enet_rx_bd_control_status_t; /*! @brief Defines the control extended region of the receive buffer descriptor.*/ typedef enum _enet_rx_bd_control_extend { kEnetRxBdIpv4 = 0x0001, /*!< Ipv4 frame*/ kEnetRxBdIpv6 = 0x0002, /*!< Ipv6 frame*/ kEnetRxBdVlan = 0x0004, /*!< VLAN*/ kEnetRxBdProtocolChecksumErr = 0x0010, /*!< Protocol checksum error*/ kEnetRxBdIpHeaderChecksumErr = 0x0020, /*!< IP header checksum error*/ kEnetRxBdIntrrupt = 0x0080, /*!< BD interrupt*/ kEnetRxBdUnicast = 0x0100, /*!< Unicast frame*/ kEnetRxBdCollision = 0x0200, /*!< BD collision*/ kEnetRxBdPhyErr = 0x0400, /*!< PHY error*/ kEnetRxBdMacErr = 0x8000 /*!< Mac error */ } enet_rx_bd_control_extend_t; /*! @brief Defines the control status of the transmit buffer descriptor.*/ typedef enum _enet_tx_bd_control_status { kEnetTxBdReady = 0x8000, /*!< Ready bit*/ kEnetTxBdTxSoftOwner1 = 0x4000, /*!< Transmit software owner*/ kEnetTxBdWrap = 0x2000, /*!< Wrap buffer descriptor*/ kEnetTxBdTxSoftOwner2 = 0x1000, /*!< Transmit software owner*/ kEnetTxBdLast = 0x0800, /*!< Last BD in the frame*/ kEnetTxBdTransmitCrc = 0x0400 /*!< Receive for transmit CRC */ } enet_tx_bd_control_status_t; /*! @brief Defines the control extended of the transmit buffer descriptor.*/ typedef enum _enet_tx_bd_control_extend { kEnetTxBdTxErr = 0x8000, /*!< Transmit error*/ kEnetTxBdTxUnderFlowErr = 0x2000, /*!< Underflow error*/ kEnetTxBdExcessCollisionErr = 0x1000, /*!< Excess collision error*/ kEnetTxBdTxFrameErr = 0x0800, /*!< Frame error*/ kEnetTxBdLatecollisionErr = 0x0400, /*!< Late collision error*/ kEnetTxBdOverFlowErr = 0x0200, /*!< Overflow error*/ kEnetTxTimestampErr = 0x0100 /*!< Timestamp error*/ } enet_tx_bd_control_extend_t; /*! @brief Defines the control extended2 of the transmit buffer descriptor.*/ typedef enum _enet_tx_bd_control_extend2 { kEnetTxBdTxInterrupt = 0x4000, /*!< Transmit interrupt*/ kEnetTxBdTimeStamp = 0x2000 /*!< Transmit timestamp flag */ } enet_tx_bd_control_extend2_t; #endif /*! @brief Defines the macro to the different ENET constant value.*/ typedef enum _enet_constant_parameter { kEnetMacAddrLen = 6, /*!< ENET mac address length*/ kEnetHashValMask = 0x1f, /*!< ENET hash value mask*/ kEnetRxBdCtlJudge1 = 0x0080,/*!< ENET receive buffer descriptor control judge value1*/ kEnetRxBdCtlJudge2 = 0x8000 /*!< ENET receive buffer descriptor control judge value2*/ } enet_constant_parameter_t; /*! @brief Defines the RMII or MII mode for data interface between the MAC and the PHY.*/ typedef enum _enet_config_rmii { kEnetCfgMii = 0, /*!< MII mode for data interface*/ kEnetCfgRmii = 1 /*!< RMII mode for data interface*/ } enet_config_rmii_t; /*! @brief Defines the 10 Mbps or 100 Mbps speed mode for the data transfer.*/ typedef enum _enet_config_speed { kEnetCfgSpeed100M = 0, /*!< Speed 100 M mode*/ kEnetCfgSpeed10M = 1 /*!< Speed 10 M mode*/ } enet_config_speed_t; /*! @brief Defines the half or full duplex mode for the data transfer.*/ typedef enum _enet_config_duplex { kEnetCfgHalfDuplex = 0, /*!< Half duplex mode*/ kEnetCfgFullDuplex = 1 /*!< Full duplex mode*/ } enet_config_duplex_t; /*! @brief Defines the write/read operation for the MII.*/ typedef enum _enet_mii_operation { kEnetWriteNoCompliant = 0, /*!< Write frame operation, but not MII compliant.*/ kEnetWriteValidFrame = 1, /*!< Write frame operation for a valid MII management frame*/ kEnetReadValidFrame = 2, /*!< Read frame operation for a valid MII management frame.*/ kEnetReadNoCompliant = 3 /*!< Read frame operation, but not MII compliant*/ }enet_mii_operation_t; /*! @brief Define holdon time on MDIO output*/ typedef enum _enet_mdio_holdon_clkcycle { kEnetMdioHoldOneClkCycle = 0, /*!< MDIO output hold on one clock cycle*/ kEnetMdioHoldTwoClkCycle = 1, /*!< MDIO output hold on two clock cycles*/ kEnetMdioHoldThreeClkCycle = 2, /*!< MDIO output hold on three clock cycles*/ kEnetMdioHoldFourClkCycle = 3, /*!< MDIO output hold on four clock cycles*/ kEnetMdioHoldFiveClkCycle = 4, /*!< MDIO output hold on five clock cycles*/ kEnetMdioHoldSixClkCycle = 5, /*!< MDIO output hold on six clock cycles*/ kEnetMdioHoldSevenClkCycle = 6, /*!< MDIO output hold seven two clock cycles*/ kEnetMdioHoldEightClkCycle = 7, /*!< MDIO output hold on eight clock cycles*/ }enet_mdio_holdon_clkcycle_t; /*! @brief Defines the initialization, enables or disables the operation for a special address filter */ typedef enum _enet_special_address_filter { kEnetSpecialAddressInit= 0, /*!< Initializes the special address filter.*/ kEnetSpecialAddressEnable = 1, /*!< Enables the special address filter.*/ kEnetSpecialAddressDisable = 2 /*!< Disables the special address filter.*/ } enet_special_address_filter_t; /*! @brief Defines the capture or compare mode for 1588 timer channels.*/ typedef enum _enet_timer_channel_mode { kEnetChannelDisable = 0, /*!< Disable timer channel*/ kEnetChannelRisingCapture = 1, /*!< Input capture on rising edge*/ kEnetChannelFallingCapture = 2, /*!< Input capture on falling edge*/ kEnetChannelBothCapture = 3, /*!< Input capture on both edges*/ kEnetChannelSoftCompare = 4, /*!< Output compare software only*/ kEnetChannelToggleCompare = 5, /*!< Toggle output on compare*/ kEnetChannelClearCompare = 6, /*!< Clear output on compare*/ kEnetChannelSetCompare = 7, /*!< Set output on compare*/ kEnetChannelClearCompareSetOverflow = 10, /*!< Clear output on compare, set output on overflow*/ kEnetChannelSetCompareClearOverflow = 11, /*!< Set output on compare, clear output on overflow*/ kEnetChannelPulseLowonCompare = 14, /*!< Pulse output low on compare for one 1588 clock cycle*/ kEnetChannelPulseHighonCompare = 15 /*!< Pulse output high on compare for one 1588 clock cycle*/ } enet_timer_channel_mode_t; /*! @brief Defines the RXFRAME/RXBYTE/TXFRAME/TXBYTE/MII/TSTIMER/TSAVAIL interrupt source for ENET.*/ typedef enum _enet_interrupt_request { kEnetBabrInterrupt = 0x40000000, /*!< BABR interrupt source*/ kEnetBabtInterrupt = 0x20000000, /*!< BABT interrupt source*/ kEnetGraInterrupt = 0x10000000, /*!< GRA interrupt source*/ kEnetTxFrameInterrupt = 0x8000000, /*!< TXFRAME interrupt source */ kEnetTxByteInterrupt = 0x4000000, /*!< TXBYTE interrupt source*/ kEnetRxFrameInterrupt = 0x2000000, /*!< RXFRAME interrupt source */ kEnetRxByteInterrupt = 0x1000000, /*!< RXBYTE interrupt source */ kEnetMiiInterrupt = 0x0800000, /*!< MII interrupt source*/ kEnetEBERInterrupt = 0x0400000, /*!< EBERR interrupt source*/ kEnetLcInterrupt = 0x0200000, /*!< LC interrupt source*/ kEnetRlInterrupt = 0x0100000, /*!< RL interrupt source*/ kEnetUnInterrupt = 0x0080000, /*!< UN interrupt source*/ kEnetPlrInterrupt = 0x0040000, /*!< PLR interrupt source*/ kEnetWakeupInterrupt = 0x0020000, /*!< WAKEUP interrupt source*/ kEnetTsAvailInterrupt = 0x0010000, /*!< TS AVAIL interrupt source*/ kEnetTsTimerInterrupt = 0x0008000, /*!< TS WRAP interrupt source*/ kEnetAllInterrupt = 0x7FFFFFFF /*!< All interrupt*/ } enet_interrupt_request_t; /*! @brief Defines the six-byte Mac address type.*/ typedef uint8_t enetMacAddr[kEnetMacAddrLen]; #if (!FSL_FEATURE_ENET_DMA_BIG_ENDIAN_ONLY) && SYSTEM_LITTLE_ENDIAN /*! @brief Defines the buffer descriptor structure for the little-Endian system and endianness configurable IP.*/ typedef struct ENETBdStruct { uint16_t length; /*!< Buffer descriptor data length*/ uint16_t control; /*!< Buffer descriptor control*/ uint8_t *buffer; /*!< Data buffer pointer*/ uint16_t controlExtend0; /*!< Extend buffer descriptor control0*/ uint16_t controlExtend1; /*!< Extend buffer descriptor control1*/ uint16_t payloadCheckSum; /*!< Internal payload checksum*/ uint8_t headerLength; /*!< Header length*/ uint8_t protocalTyte; /*!< Protocol type*/ uint16_t reserved0; uint16_t controlExtend2; /*!< Extend buffer descriptor control2*/ uint32_t timestamp; /*!< Timestamp */ uint16_t reserved1; uint16_t reserved2; uint16_t reserved3; uint16_t reserved4; } enet_bd_struct_t; #define TX_DESC_UPDATED_MASK (0x8000) #else /*! @brief Defines the buffer descriptors structure for the Big-Endian system.*/ typedef struct ENETBdStruct { uint16_t control; /*!< Buffer descriptor control */ uint16_t length; /*!< Buffer descriptor data length*/ uint8_t *buffer; /*!< Data buffer pointer*/ uint16_t controlExtend1; /*!< Extend buffer descriptor control1*/ uint16_t controlExtend0; /*!< Extend buffer descriptor control0*/ uint8_t headerLength; /*!< Header length*/ uint8_t protocalTyte; /*!< Protocol type*/ uint16_t payloadCheckSum; /*!< Internal payload checksum*/ uint16_t controlExtend2; /*!< Extend buffer descriptor control2*/ uint16_t reserved0; uint32_t timestamp; /*!< Timestamp pointer*/ uint16_t reserved1; uint16_t reserved2; uint16_t reserved3; uint16_t reserved4; } enet_bd_struct_t; #define TX_DESC_UPDATED_MASK (0x0080) #endif /*! @brief Defines the configuration structure for the 1588 PTP timer.*/ typedef struct ENETConfigPtpTimer { bool isSlaveEnabled; /*!< Master or slave PTP timer*/ uint32_t clockIncease; /*!< Timer increase value each clock period*/ uint32_t period; /*!< Timer period for generate interrupt event */ } enet_config_ptp_timer_t; /*! @brief Defines the transmit accelerator configuration.*/ typedef struct ENETConfigTxAccelerator { bool isIpCheckEnabled; /*!< Insert IP header checksum */ bool isProtocolCheckEnabled; /*!< Insert protocol checksum*/ bool isShift16Enabled; /*!< Tx FIFO shift-16*/ } enet_config_tx_accelerator_t; /*! @brief Defines the receive accelerator configuration.*/ typedef struct ENETConfigRxAccelerator { bool isIpcheckEnabled; /*!< Discard with wrong IP header checksum */ bool isProtocolCheckEnabled; /*!< Discard with wrong protocol checksum*/ bool isMacCheckEnabled; /*!< Discard with Mac layer errors*/ bool isPadRemoveEnabled; /*!< Padding removal for short IP frames*/ bool isShift16Enabled; /*!< Rx FIFO shift-16*/ } enet_config_rx_accelerator_t; /*! @brief Defines the transmit FIFO configuration.*/ typedef struct ENETConfigTxFifo { bool isStoreForwardEnabled; /*!< Transmit FIFO store and forward */ uint8_t txFifoWrite; /*!< Transmit FIFO write */ uint8_t txEmpty; /*!< Transmit FIFO section empty threshold*/ uint8_t txAlmostEmpty; /*!< Transmit FIFO section almost empty threshold*/ uint8_t txAlmostFull; /*!< Transmit FIFO section almost full threshold*/ } enet_config_tx_fifo_t; /*! @brief Defines the receive FIFO configuration.*/ typedef struct ENETConfigRxFifo { uint8_t rxFull; /*!< Receive FIFO section full threshold*/ uint8_t rxAlmostFull; /*!< Receive FIFO section almost full threshold*/ uint8_t rxEmpty; /*!< Receive FIFO section empty threshold*/ uint8_t rxAlmostEmpty; /*!< Receive FIFO section almost empty threshold*/ } enet_config_rx_fifo_t; /******************************************************************************* * API ******************************************************************************/ #if defined(__cplusplus) extern "C" { #endif /*! * @brief Resets the ENET module. * * @param instance The ENET instance number */ static inline void enet_hal_reset_ethernet(uint32_t instance) { // assert(instance < HW_ENET_INSTANCE_COUNT); HW_ENET_ECR_SET(instance, BM_ENET_ECR_RESET); } /*! * @brief Gets the ENET status to check whether the reset has completed. * * @param instance The ENET instance number * @return Current status of the reset operation * - true if ENET reset completed. * - false if ENET reset has not completed. */ static inline bool enet_hal_is_reset_completed(uint32_t instance) { // assert(instance < HW_ENET_INSTANCE_COUNT); return (BR_ENET_ECR_RESET(instance) == 0); } /*! * @brief Enable or disable stop mode. * * Enable stop mode will control device behavior in doze mode. * In doze mode, if this filed is set then all clock of the enet assemably are * disabled, except the RMII/MII clock. * * @param instance The ENET instance number. * @param isEnabled The switch to enable/disable stop mode. * - true to enabale the stop mode. * - false to disable the stop mode. */ static inline void enet_hal_enable_stop(uint32_t instance, bool isEnabled) { // assert(instance < HW_ENET_INSTANCE_COUNT); BW_ENET_ECR_STOPEN(instance, isEnabled); } /*! * @brief Enable or disable sleep mode. * * Enable sleep mode will disable normal operating mode. When enable the sleep * mode, the magic packet detection is also enabled so that a remote agent can * wakeup the node. * * @param instance The ENET instance number. * @param isEnabled The switch to enable/disable the sleep mode. * - true to enabale the sleep mode. * - false to disable the sleep mode. */ static inline void enet_hal_enable_sleep(uint32_t instance, bool isEnabled) { // assert(instance < HW_ENET_INSTANCE_COUNT); BW_ENET_ECR_SLEEP(instance, isEnabled); BW_ENET_ECR_MAGICEN(instance, isEnabled); } /*! * @brief Sets the Mac address. * * This interface sets the six-byte Mac address of the ENET interface. * * @param instance The ENET instance number * @param hwAddr The mac address pointer store for six bytes Mac address */ void enet_hal_set_mac_address(uint32_t instance, enetMacAddr hwAddr); /*! * @brief Sets the hardware addressing filtering to a multicast group address. * * This interface is used to add the ENET device to a multicast group address. * After joining the group, Mac receives all frames with the group Mac address. * * @param instance The ENET instance number * @param crcValue The CRC value of the special address * @param mode The operation for init/enable/disable the specified hardware address */ void enet_hal_set_group_hashtable(uint32_t instance, uint32_t crcValue, enet_special_address_filter_t mode); /*! * @brief Sets the hardware addressing filtering to an individual address. * * This interface is used to add an individual address to the hardware address * filter. Mac receives all frames with the individual address as a destination address. * * @param instance The ENET instance number * @param crcValue The CRC value of the special address * @param mode The operation for init/enable/disable the specified hardware address */ void enet_hal_set_individual_hashtable(uint32_t instance, uint32_t crcValue, enet_special_address_filter_t mode); /*! * @brief Enable/disable payload length check. * * If the length/type is less than 0x600,When enable payload length check * the core checks the fame's payload length. If the length/type is greater * than or equal to 0x600. The MAC interprets the field as a type and no * payload length check is performanced. * * @param instance The ENET instance number * @param isEnabled The switch to enable/disable payload length check * - True to enabale payload length check. * - False to disable payload legnth check. */ static inline void enet_hal_enable_payloadcheck(uint32_t instance, bool isEnabled) { // assert(instance < HW_ENET_INSTANCE_COUNT); BW_ENET_RCR_NLC(instance, isEnabled); } /*! * @brief Enable/disable append CRC to transmitted frames. * * If transmit CRC forward is enabled, the transmit buffer descriptor controls * whether the frame has a CRC from the application. If transmit CRC forward is disabled, * transmitter does not append any CRC to transmitted frames. * * @param instance The ENET instance number * @param isEnabled The switch to enable/disable transmit the receive CRC * - True the transmitter control CRC through transmit buffer descriptor. * - False the transmitter does not append any CRC to transmitted frames. */ static inline void enet_hal_enable_txcrcforward(uint32_t instance, bool isEnabled) { // assert(instance < HW_ENET_INSTANCE_COUNT); BW_ENET_TCR_CRCFWD(instance, !isEnabled); } /*! * @brief Enable/disable forward the CRC filed of the received frame. * * This is used to deceide whether the CRC field of received frame is transmitted * or stripped. Enable this feature to strip CRC field from the frame. * If padding remove is enabled, this feature will be ignored and * the CRC field is checked and always terminated and removed. * * @param instance The ENET instance number * @param isEnabled The switch to enable/disable transmit the receive CRC * - True to transmit the received CRC. * - False to strip the received CRC. */ static inline void enet_hal_enable_rxcrcforward(uint32_t instance, bool isEnabled) { // assert(instance < HW_ENET_INSTANCE_COUNT); BW_ENET_RCR_CRCFWD(instance, !isEnabled); } /*! * @brief Enable/disable forward PAUSE frames. * * This is used to deceide whether PAUSE frames is forwarded or discarded. * * @param instance The ENET instance number * @param isEnabled The switch to enable/disable forward PAUSE frames * - True to forward PAUSE frames. * - False to terminate and discard PAUSE frames. */ static inline void enet_hal_enable_pauseforward(uint32_t instance, bool isEnabled) { // assert(instance < HW_ENET_INSTANCE_COUNT); BW_ENET_RCR_PAUFWD(instance, isEnabled); } /*! * @brief Enable/disable frame padding remove on receive. * * Enable frame padding remove will remove the padding from the received frames. * * @param instance The ENET instance number * @param isEnabled The switch to enable/disable remove padding * - True to remove padding from frames. * - False to disable padding remove. */ static inline void enet_hal_enable_padremove(uint32_t instance, bool isEnabled) { // assert(instance < HW_ENET_INSTANCE_COUNT); BW_ENET_RCR_PADEN(instance, isEnabled); } /*! * @brief Enable/disable flow control. * * If flow control is enabled, the receive detects PAUSE frames. * Upon PAUSE frame detection, the transmitter stops transmitting * data frames for a given duration. * * @param instance The ENET instance number * @param isEnabled The switch to enable/disable flow control * - True to enable the flow control. * - False to disable the flow control. */ static inline void enet_hal_enable_flowcontrol(uint32_t instance, bool isEnabled) { // assert(instance < HW_ENET_INSTANCE_COUNT); BW_ENET_RCR_CFEN(instance, isEnabled); BW_ENET_RCR_FCE(instance, isEnabled); } /*! * @brief Enable/disable broadcast frame reject. * * If broadcast frame reject is enabled, frames with destination address * equal to 0xffff_ffff_ffff are rejected unless the promiscuous mode is open. * * @param instance The ENET instance number * @param isEnabled The switch to enable/disable reject broadcast frames * - True to reject broadcast frames. * - False to accept broadcast frames. */ static inline void enet_hal_enable_broadcastreject(uint32_t instance, bool isEnabled) { // assert(instance < HW_ENET_INSTANCE_COUNT); BW_ENET_RCR_BC_REJ(instance, isEnabled); } /*! * @brief Sets PAUSE duration for a PAUSE frame. * * This function is used to set the pause duraion used in transmission * of a PAUSE frame. When another node detects a PAUSE frame, that node * pauses transmission for the pause duration. * * @param instance The ENET instance number * @param pauseDuration The PAUSE duration for the transmitted PAUSE frame * the maximum pause duration is 0xFFFF. */ static inline void enet_hal_set_pauseduration(uint32_t instance, uint32_t pauseDuration) { // assert(instance < HW_ENET_INSTANCE_COUNT); assert(pauseDuration <= BM_ENET_OPD_PAUSE_DUR); BW_ENET_OPD_PAUSE_DUR(instance, pauseDuration); } /*! * @brief Gets receive PAUSE frame status. * * This function is used to get the received PAUSE frame status. * * @param instance The ENET instance number * @return The status of the received flow control frames * true if the flow control pause frame is received. * false if there is no flow control frame received or the pause duration is complete. */ static inline bool enet_hal_get_rxpause_status(uint32_t instance) { // assert(instance < HW_ENET_INSTANCE_COUNT); return BR_ENET_TCR_RFC_PAUSE(instance); } /*! * @brief Enables transmit frame control PAUSE. * * This function enables pauses frame transmission. * When this is set, with transmission of data frames stopped, the MAC * transmits a MAC control PAUSE frame. NEXT, the MAC clear the * and resumes transmitting data frames. * * @param instance The ENET instance number * @param isEnabled The switch to enable/disable PAUSE control frame transmission * - True enable PAUSE control frame transmission. * - Flase disable PAUSE control frame transmission. */ static inline void enet_hal_enable_txpause(uint32_t instance, bool isEnabled) { // assert(instance < HW_ENET_INSTANCE_COUNT); BW_ENET_TCR_TFC_PAUSE(instance, isEnabled); } /*! * @brief Sets transmit PAUSE frame. * * This function Sets ENET transmit controller with pause duration. * And set the transmit control to do PAUSE frame transmission * This should be called when a PAUSE frame is dynamically wanted. * * @param instance The ENET instance number */ void enet_hal_set_txpause(uint32_t instance, uint32_t pauseDuration); /*! * @brief Sets the transmit inter-packet gap. * * This function indicates the IPG, in bytes, between transmitted frames. * Valid values range from 8 to 27. If value is less than 8, the IPG is 8. * If value is greater than 27, the IPG is 27. * * @param instance The ENET instance number * @param ipgValue The IPG for transmitted frames * The default value is 12, the maximum value set to ipg is 0x1F. * */ static inline void enet_hal_set_txipg(uint32_t instance, uint32_t ipgValue) { // assert(instance < HW_ENET_INSTANCE_COUNT); assert(ipgValue <= BM_ENET_TIPG_IPG); BW_ENET_TIPG_IPG(instance, ipgValue); } /*! * @brief Sets the receive frame truncation length. * * This function indicates the value a receive frame is truncated, * if it is greater than this value. The frame truncation length must be greater * than or equal to the receive maximum frame length. * * @param instance The ENET instance number * @param length The truncation length. The maximum value is 0x3FFF * The default truncation length is 2047(0x7FF). * */ static inline void enet_hal_set_truncationlen(uint32_t instance, uint32_t length) { // assert(instance < HW_ENET_INSTANCE_COUNT); assert(length <= BM_ENET_FTRL_TRUNC_FL); BW_ENET_FTRL_TRUNC_FL(instance, length); } /*! * @brief Sets the maximum receive buffer size and the maximum frame size. * * @param instance The ENET instance number * @param maxBufferSize The maximum receive buffer size, which should not be smaller than 256 * It should be evenly divisible by 16 and the maximum receive size should not be larger than 0x3ff0. * @param maxFrameSize The maximum receive frame size, the reset value is 1518 or 1522 if the VLAN tags are * supported. The length is measured starting at DA and including the CRC. */ static inline void enet_hal_set_rx_max_size(uint32_t instance, uint32_t maxBufferSize, uint32_t maxFrameSize) { // assert(instance < HW_ENET_INSTANCE_COUNT); /* max buffer size must larger than 256 to minimize bus usage*/ assert(maxBufferSize >= 256); assert(maxFrameSize <= (BM_ENET_RCR_MAX_FL >> BP_ENET_RCR_MAX_FL)); BW_ENET_RCR_MAX_FL(instance, maxFrameSize); HW_ENET_MRBR_WR(instance, (maxBufferSize & BM_ENET_MRBR_R_BUF_SIZE)); } /*! * @brief Configures the ENET transmit FIFO. * * @param instance The ENET instance number * @param thresholdCfg The FIFO threshold configuration */ void enet_hal_config_tx_fifo(uint32_t instance, enet_config_tx_fifo_t *thresholdCfg); /*! * @brief Configures the ENET receive FIFO. * * @param instance The ENET instance number * @param thresholdCfg The FIFO threshold configuration */ void enet_hal_config_rx_fifo(uint32_t instance, enet_config_rx_fifo_t *thresholdCfg); /*! * @brief Sets the start address for ENET receive buffer descriptors. * * This interface provides the beginning of the receive * and receive buffer descriptor queue in the external memory. The * txbdAddr is recommended to be 128-bit aligned, must be evenly divisible by 16. * * @param instance The ENET instance number * @param rxBdAddr The start address of receive buffer descriptors */ static inline void enet_hal_set_rxbd_address(uint32_t instance, uint32_t rxBdAddr) { // assert(instance < HW_ENET_INSTANCE_COUNT); HW_ENET_RDSR_WR(instance,rxBdAddr); /* Initialize receive buffer descriptor start address*/ } /*! * @brief Sets the start address for ENET transmit buffer descriptors. * * This interface provides the beginning of the receive * and transmit buffer descriptor queue in the external memory. The * txbdAddr is recommended to be 128-bit aligned, must be evenly divisible by 16. * * @param instance The ENET instance number * @param txBdAddr The start address of transmit buffer descriptors */ static inline void enet_hal_set_txbd_address(uint32_t instance, uint32_t txBdAddr) { // assert(instance < HW_ENET_INSTANCE_COUNT); HW_ENET_TDSR_WR(instance,txBdAddr); /* Initialize transmit buffer descriptor start address*/ } /*! * @brief Initializes the receive buffer descriptors. * * To make sure the uDMA will do the right data transfer after you activate * with wrap flag and all the buffer descriptors should be initialized with an empty bit. * * @param rxBds The current receive buffer descriptor * @param buffer The data buffer on buffer descriptor * @param isLastBd The flag to indicate the last receive buffer descriptor */ void enet_hal_init_rxbds(void *rxBds, uint8_t *buffer, bool isLastBd); /*! * @brief Initializes the transmit buffer descriptors. * * To make sure the uDMA will do the right data transfer after you active * with wrap flag. * * @param txBds The current transmit buffer descriptor. * @param isLastBd The last transmit buffer descriptor flag. */ void enet_hal_init_txbds(void *txBds, bool isLastBd); /*! * @brief Updates the receive buffer descriptors. * * This interface mainly clears the status region and updates the received * buffer descriptor to ensure that the BD is correctly used. * * @param rxBds The current receive buffer descriptor * @param data The data buffer address * @param isbufferUpdate The data buffer update flag. When you want to update * the data buffer of the buffer descriptor ensure that this flag * is set. */ void enet_hal_update_rxbds(void *rxBds, uint8_t *data, bool isbufferUpdate); /*! * @brief Initializes the transmit buffer descriptors. * * Ensures that the uDMA transfer data correctly after the user activates * with the wrap flag. * * @param txBds The current transmit buffer descriptor * @param isLastBd The last transmit buffer descriptor flag */ void enet_hal_init_txbds(void *txBds, bool isLastBd); /*! * @brief Updates the transmit buffer descriptors. * * This interface mainly clears the status region and updates the transmit * buffer descriptor to ensure tat this BD is correctly used again. * You should set the isTxtsCfged when the transmit timestamp feature is required. * * @param txBds The current transmit buffer descriptor * @param buffer The data buffer on buffer descriptor * @param length The data length on buffer descriptor * @param isTxtsCfged The timestamp configure flag. The timestamp is * added to the transmit buffer descriptor when this flag is set. */ void enet_hal_update_txbds(void *txBds,uint8_t *buffer, uint16_t length, bool isTxtsCfged); /*! * @brief Clears the context in the transmit buffer descriptors. * * Clears the data, length, control, and status region of the transmit buffer descriptor. * * @param curBd The current buffer descriptor */ static inline void enet_hal_clear_txbds(void *curBd) { assert(curBd); volatile enet_bd_struct_t *bdPtr = (enet_bd_struct_t *)curBd; bdPtr->length = 0; /* Set data length*/ bdPtr->buffer = (uint8_t *)(NULL);/* Set data buffer*/ bdPtr->control &= (kEnetTxBdWrap);/* Set control */ } /*! * @brief Gets the control and the status region of the receive buffer descriptors. * * This interface can get the whole control and status region of the * receive buffer descriptor. The enet_rx_bd_control_status_t enum type * definition should be used if you want to get each status bit of * the control and status region. * * @param curBd The current receive buffer descriptor * @return The control and status data on buffer descriptors */ uint16_t enet_hal_get_rxbd_control(void *curBd); /*! * @brief Gets the control and the status region of the transmit buffer descriptors. * * This interface can get the whole control and status region of the * transmit buffer descriptor. The enet_tx_bd_control_status_t enum type * definition should be used if you want to get each status bit of * the control and status region. * * @param curBd The current transmit buffer descriptor * @return The extended control region of transmit buffer descriptor */ uint16_t enet_hal_get_txbd_control(void *curBd); /*! * @brief Gets the extended control region of the receive buffer descriptors. * * This interface can get the whole control and status region of the * receive buffer descriptor. The enet_rx_bd_control_extend_t enum type * definition should be used if you want to get each status bit of * the control and status region. * * @param curBd The current receive buffer descriptor * @param controlRegion The different control region * @return The extended control region data of receive buffer descriptor * - true when the control region is set * - false when the control region is not set */ bool enet_hal_get_rxbd_control_extend(void *curBd,enet_rx_bd_control_extend_t controlRegion); /*! * @brief Gets the extended control region of the transmit buffer descriptors. * * This interface can get the whole control and status region of the * transmit buffer descriptor. The enet_tx_bd_control_extend_t enum type * definition should be used if you want to get each status bit of * the control and status region. * * @param curBd The current transmit buffer descriptor * @return The extended control data */ uint16_t enet_hal_get_txbd_control_extend(void *curBd); /*! * @brief Gets the data length of the buffer descriptors. * * @param curBd The current buffer descriptor * @return The data length of the buffer descriptor */ uint16_t enet_hal_get_bd_length(void *curBd); /*! * @brief Gets the buffer address of the buffer descriptors. * * @param curBd The current buffer descriptor * @return The buffer address of the buffer descriptor */ uint8_t* enet_hal_get_bd_buffer(void *curBd); /*! * @brief Gets the timestamp of the buffer descriptors. * * @param curBd The current buffer descriptor * @return The time stamp of the frame in the buffer descriptor. * Notice that the frame timestamp is only set in the last * buffer descriptor of the frame. */ uint32_t enet_hal_get_bd_timestamp(void *curBd); /*! * @brief Activates the receive buffer descriptor. * * The buffer descriptor activation * should be done after the ENET module is enabled. Otherwise, the activation fails. * * @param instance The ENET instance number */ static inline void enet_hal_active_rxbd(uint32_t instance) { // assert(instance < HW_ENET_INSTANCE_COUNT); HW_ENET_RDAR_SET(instance, BM_ENET_RDAR_RDAR); } /*! * @brief Activates the transmit buffer descriptor. * * The buffer descriptor activation should be done after the ENET module is * enabled. Otherwise, the activation fails. * * @param instance The ENET instance number */ static inline void enet_hal_active_txbd(uint32_t instance) { // assert(instance < HW_ENET_INSTANCE_COUNT); HW_ENET_TDAR_SET(instance, BM_ENET_TDAR_TDAR); } /*! * @brief Configures the (R)MII of ENET. * * @param instance The ENET instance number * @param mode The RMII or MII mode * @param speed The speed of RMII * @param duplex The full or half duplex mode * @param isRxOnTxDisabled The Receive on transmit disable flag * @param isLoopEnabled The loop enable flag */ void enet_hal_config_rmii(uint32_t instance, enet_config_rmii_t mode, enet_config_speed_t speed, enet_config_duplex_t duplex, bool isRxOnTxDisabled, bool isLoopEnabled); /*! * @brief Configures the MII of ENET. * * Sets the MII interface between Mac and PHY. The miiSpeed is * a value that controls the frequency of the MDC, relative to the internal module clock(InterClockSrc). * A value of zero in this parameter turns the MDC off and leaves it in the low voltage state. * Any non-zero value results in the MDC frequency MDC = InterClockSrc/((miiSpeed + 1)*2). * So miiSpeed = InterClockSrc/(2*MDC) - 1. * The Maximum MDC clock is 2.5MHZ(maximum). We should round up and plus one to simlplify: * miiSpeed = InterClockSrc/(2*2.5MHZ). * * @param instance The ENET instance number * @param miiSpeed The MII speed and it is ranged from 0~0x3F * @param time The holdon clock cycles for MDIO output * @param isPreambleDisabled The preamble disabled flag */ static inline void enet_hal_config_mii(uint32_t instance, uint32_t miiSpeed, enet_mdio_holdon_clkcycle_t clkCycle, bool isPreambleDisabled) { // assert(instance < HW_ENET_INSTANCE_COUNT); BW_ENET_MSCR_MII_SPEED(instance, miiSpeed); /* MII speed set*/ BW_ENET_MSCR_DIS_PRE(instance, isPreambleDisabled); /* Preamble is disabled*/ BW_ENET_MSCR_HOLDTIME(instance, clkCycle); /* hold on clock cycles for MDIO output*/ } /*! * @brief Gets the MII configuration status. * * This interface is usually called to check the MII interface before * the Mac writes or reads the PHY registers. * * @param instance The ENET instance number * @return The MII configuration status * - true if the MII has been configured. * - false if the MII has not been configured. */ static inline bool enet_hal_is_mii_enabled(uint32_t instance) { // assert(instance < HW_ENET_INSTANCE_COUNT); return (HW_ENET_MSCR_RD(instance) & 0x7E)!= 0; } /*! * @brief Reads data from PHY. * * @param instance The ENET instance number * @return The data read from PHY */ static inline uint32_t enet_hal_get_mii_data(uint32_t instance) { // assert(instance < HW_ENET_INSTANCE_COUNT); return (uint32_t)BR_ENET_MMFR_DATA(instance); } /*! * @brief Sets the MII command. * * @param instance The ENET instance number * @param phyAddr The PHY address * @param phyReg The PHY register * @param operation The read or write operation * @param data The data written to PHY */ void enet_hal_set_mii_command(uint32_t instance, uint32_t phyAddr, uint32_t phyReg, enet_mii_operation_t operation, uint32_t data); /*! * @brief Enables/Disables the ENET module. * * @param instance The ENET instance number * @param isEnhanced The enhanced 1588 feature switch * @param isEnabled The ENET module enable switch */ void enet_hal_config_ethernet(uint32_t instance, bool isEnhanced, bool isEnabled); /*! * @brief Enables/Disables the ENET interrupt. * * @param instance The ENET instance number * @param source The interrupt sources. enet_interrupt_request_t enum types * is recommended as the interrupt source. * @param isEnabled The interrupt enable switch */ void enet_hal_config_interrupt(uint32_t instance, uint32_t source, bool isEnabled); /*! * @brief Clears ENET interrupt events. * * @param instance The ENET instance number * @param source The interrupt source to be cleared. enet_interrupt_request_t * enum types is recommended as the interrupt source. */ static inline void enet_hal_clear_interrupt(uint32_t instance, uint32_t source) { // assert(instance < HW_ENET_INSTANCE_COUNT); HW_ENET_EIR_WR(instance,source); } /*! * @brief Gets the ENET interrupt status. * * @param instance The ENET instance number * @param source The interrupt sources. enet_interrupt_request_t * enum types is recommended as the interrupt source. * @return The event status of the interrupt source * - true if the interrupt event happened. * - false if the interrupt event has not happened. */ static inline bool enet_hal_get_interrupt_status(uint32_t instance, uint32_t source) { // assert(instance < HW_ENET_INSTANCE_COUNT); return ((HW_ENET_EIR_RD(instance) & source) != 0); } /* * @brief Enables/disables the ENET promiscuous mode. * * @param instance The ENET instance number * @param isEnabled The enable switch */ static inline void enet_hal_config_promiscuous(uint32_t instance, bool isEnabled) { // assert(instance < HW_ENET_INSTANCE_COUNT); BW_ENET_RCR_PROM(instance,isEnabled); } /*! * @brief Enables/disables the clear MIB counter. * * @param instance The ENET instance number * @param isEnabled The enable switch */ static inline void enet_hal_clear_mib(uint32_t instance, bool isEnabled) { // assert(instance < HW_ENET_INSTANCE_COUNT); BW_ENET_MIBC_MIB_CLEAR(instance, isEnabled); } /*! * @brief Sets the enable/disable of the MIB block. * * @param instance The ENET instance number * @param isEnabled The enable flag * - True to enabale MIB block. * - False to disable MIB block. */ static inline void enet_hal_enable_mib(uint32_t instance, bool isEnabled) { // assert(instance < HW_ENET_INSTANCE_COUNT); BW_ENET_MIBC_MIB_DIS(instance,!isEnabled); } /*! * @brief Gets the MIB idle status. * * @param instance The ENET instance number * @return true if in MIB idle and MIB is not updating else false. */ static inline bool enet_hal_get_mib_status(uint32_t instance) { // assert(instance < HW_ENET_INSTANCE_COUNT); return BR_ENET_MIBC_MIB_IDLE(instance); } /*! * @brief Sets the transmit accelerator. * * @param instance The ENET instance number * @param txCfgPtr The transmit accelerator configuration */ void enet_hal_config_tx_accelerator(uint32_t instance, enet_config_tx_accelerator_t *txCfgPtr); /*! * @brief Sets the receive accelerator. * * @param instance The ENET instance number * @param rxCfgPtr The receive accelerator configuration */ void enet_hal_config_rx_accelerator(uint32_t instance, enet_config_rx_accelerator_t *rxCfgPtr); /*! * @brief Initializes the 1588 timer. * * This interface initializes the 1588 context structure. * Initialize 1588 parameters according to the user configuration structure. * * @param instance The ENET instance number * @param ptpCfg The 1588 timer configuration */ void enet_hal_init_ptp_timer(uint32_t instance, enet_config_ptp_timer_t *ptpCfgPtr); /*! * @brief Enables or disables the 1588 timer. * * Enable the PTP timer will starts the timer. Disable the timer will stop timer * at the current value. * * @param instance The ENET instance number. * @param isEnabled The 1588 timer Enable switch * - True enbaled the 1588 PTP timer. * - False disable or stop the 1588 PTP timer. */ static inline void enet_hal_enable_ptp_timer(uint32_t instance, uint32_t isEnabled) { // assert(instance < HW_ENET_INSTANCE_COUNT); BW_ENET_ATCR_EN(instance,isEnabled); } /*! * @brief Restarts the 1588 timer. * * Restarting the PTP timer clears all PTP-timer counters to zero. * * @param instance The ENET instance number */ static inline void enet_hal_restart_ptp_timer(uint32_t instance) { // assert(instance < HW_ENET_INSTANCE_COUNT); BW_ENET_ATCR_RESTART(instance,1); } /*! * @brief Adjusts the 1588 timer. * * Adjust the 1588 timer according to the increase and correction period of the configured correction. * * @param instance The ENET instance number * @param inceaseCorrection The increase correction for 1588 timer * @param periodCorrection The period correction for 1588 timer */ static inline void enet_hal_adjust_ptp_timer(uint32_t instance, uint32_t increaseCorrection, uint32_t periodCorrection) { // assert(instance < HW_ENET_INSTANCE_COUNT); HW_ENET_ATINC_SET(instance,((increaseCorrection << ENET_ATINC_INC_CORR_SHIFT) & ENET_ATINC_INC_CORR_MASK)); /* set correction for ptp timer increase*/ /* set correction for ptp timer period*/ HW_ENET_ATCOR_SET(instance, (BM_ENET_ATCOR_COR & periodCorrection)); } /*! * @brief Initializes the 1588 timer channel. * * @param instance The ENET instance number * @Param channel The 1588 timer channel number * @param mode Compare or capture mode for the 1588 timer channel */ static inline void enet_hal_init_timer_channel(uint32_t instance, uint32_t channel, enet_timer_channel_mode_t mode) { // assert(instance < HW_ENET_INSTANCE_COUNT); assert(channel < HW_ENET_TCSRn_COUNT); HW_ENET_TCSRn_SET(instance, channel, (BM_ENET_TCSRn_TMODE &(mode << BP_ENET_TCSRn_TMODE))); HW_ENET_TCSRn_SET(instance, channel, BM_ENET_TCSRn_TIE); } /*! * @brief Sets the compare value for the 1588 timer channel. * * @param instance The ENET instance number * @Param channel The 1588 timer channel number * @param compareValue Compare value for 1588 timer channel */ static inline void enet_hal_set_timer_channel_compare(uint32_t instance, uint32_t channel, uint32_t compareValue) { assert(instance < HW_ENET_INSTANCE_COUNT); assert(channel < HW_ENET_TCSRn_COUNT); HW_ENET_TCCRn_WR(instance,channel, compareValue); } /*! * @brief Gets the 1588 timer channel status. * * @param instance The ENET instance number * @param channel The 1588 timer channel number * @return Compare or capture operation status * - True if the compare or capture has occurred. * - False if the compare or capture has not occurred. */ static inline bool enet_hal_get_timer_channel_status(uint32_t instance, uint32_t channel) { // assert(instance < HW_ENET_INSTANCE_COUNT); assert(channel < HW_ENET_TCSRn_COUNT); return BR_ENET_TCSRn_TF(instance,channel); } /*! * @brief Clears the 1588 timer channel flag. * * @param instance The ENET instance number * @param channel The 1588 timer channel number */ static inline void enet_hal_clear_timer_channel_flag(uint32_t instance, uint32_t channel) { // assert(instance < HW_ENET_INSTANCE_COUNT); assert(channel < HW_ENET_TCSRn_COUNT); HW_ENET_TCSRn_SET(instance, channel, BM_ENET_TCSRn_TF);/* clear interrupt flag*/ HW_ENET_TGSR_WR(instance,(1U << channel)); /* clear channel flag*/ } /*! * @brief Sets the capture command to the 1588 timer. * * This is used before reading the current time register. * After set timer capture, please wait for about 1us before read * the captured timer. * * @param instance The ENET instance number */ static inline void enet_hal_set_timer_capture(uint32_t instance) { assert(instance < HW_ENET_INSTANCE_COUNT); HW_ENET_ATCR_SET(instance, BM_ENET_ATCR_CAPTURE); } /*! * @brief Sets the 1588 timer. * * @param instance The ENET instance number * @param nanSecond The nanosecond set to 1588 timer */ static inline void enet_hal_set_current_time(uint32_t instance, uint32_t nanSecond) { // assert(instance < HW_ENET_INSTANCE_COUNT); HW_ENET_ATVR_WR(instance,nanSecond); } /*! * @brief Gets the time from the 1588 timer. * * @param instance The ENET instance number * @return the current time from 1588 timer */ static inline uint32_t enet_hal_get_current_time(uint32_t instance) { // assert(instance < HW_ENET_INSTANCE_COUNT); return HW_ENET_ATVR_RD(instance); } /*! * @brief Gets the transmit timestamp. * * @param instance The ENET instance number * @return The timestamp of the last transmitted frame */ static inline uint32_t enet_hal_get_tx_timestamp(uint32_t instance) { // assert(instance < HW_ENET_INSTANCE_COUNT); return HW_ENET_ATSTMP_RD(instance); } /*! * @brief Gets the transmit buffer descriptor timestamp flag. * * @param curBd The ENET transmit buffer descriptor * @return true if timestamp region is set else false. */ bool enet_hal_get_txbd_timestamp_flag(void *curBd); /*! * @brief Gets the buffer descriptor timestamp. * * @param null * @return The the size of the buffer descriptor */ static inline uint32_t enet_hal_get_bd_size(void) { return sizeof(enet_bd_struct_t); } /* @} */ #if defined(__cplusplus) } #endif #endif /*! @}*/ #endif /*!< __FSL_ENET_HAL_H__*/ /******************************************************************************* * EOF ******************************************************************************/ ================================================ FILE: Zelig/mbed/TARGET_K64F/TARGET_Freescale/TARGET_KPSDK_MCUS/TARGET_KPSDK_CODE/hal/flextimer/fsl_ftm_features.h ================================================ /* ** ################################################################### ** Version: rev. 1.0, 2014-05-14 ** Build: b140515 ** ** Abstract: ** Chip specific module features. ** ** Copyright: 2014 Freescale Semiconductor, Inc. ** All rights reserved. ** ** Redistribution and use in source and binary forms, with or without modification, ** are permitted provided that the following conditions are met: ** ** o Redistributions of source code must retain the above copyright notice, this list ** of conditions and the following disclaimer. ** ** o Redistributions in binary form must reproduce the above copyright notice, this ** list of conditions and the following disclaimer in the documentation and/or ** other materials provided with the distribution. ** ** o Neither the name of Freescale Semiconductor, Inc. nor the names of its ** contributors may be used to endorse or promote products derived from this ** software without specific prior written permission. ** ** THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ** ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED ** WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE ** DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT 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. ** ** http: www.freescale.com ** mail: support@freescale.com ** ** Revisions: ** - rev. 1.0 (2014-05-14) ** Customer release. ** ** ################################################################### */ #if !defined(__FSL_FTM_FEATURES_H__) #define __FSL_FTM_FEATURES_H__ #if defined(CPU_MK02FN128VFM10) || defined(CPU_MK02FN64VFM10) || defined(CPU_MK02FN128VLF10) || defined(CPU_MK02FN64VLF10) || \ defined(CPU_MK02FN128VLH10) || defined(CPU_MK02FN64VLH10) || defined(CPU_MKV30F128VFM10) || defined(CPU_MKV30F64VFM10) || \ defined(CPU_MKV30F128VLF10) || defined(CPU_MKV30F64VLF10) || defined(CPU_MKV30F128VLH10) || defined(CPU_MKV30F64VLH10) /* @brief Bus clock is the source clock for the module. */ #define FSL_FEATURE_FTM_BUS_CLOCK (1) /* @brief Number of channels. */ #define FSL_FEATURE_FTM_CHANNEL_COUNT (6) #define FSL_FEATURE_FTM_CHANNEL_COUNTn(x) \ ((x) == 0 ? (6) : \ ((x) == 1 ? (2) : \ ((x) == 2 ? (2) : (-1)))) /* @brief Has counter reset by the selected input capture event (register bits C0SC[ICRST], C1SC[ICRST], ...). */ #define FSL_FEATURE_FTM_HAS_COUNTER_RESET_BY_CAPTURE_EVENT (1) #elif defined(CPU_MK20DX128VMP5) || defined(CPU_MK20DN128VMP5) || defined(CPU_MK20DX64VMP5) || defined(CPU_MK20DN64VMP5) || \ defined(CPU_MK20DX32VMP5) || defined(CPU_MK20DN32VMP5) || defined(CPU_MK20DX128VLH5) || defined(CPU_MK20DN128VLH5) || \ defined(CPU_MK20DX64VLH5) || defined(CPU_MK20DN64VLH5) || defined(CPU_MK20DX32VLH5) || defined(CPU_MK20DN32VLH5) || \ defined(CPU_MK20DX128VFM5) || defined(CPU_MK20DN128VFM5) || defined(CPU_MK20DX64VFM5) || defined(CPU_MK20DN64VFM5) || \ defined(CPU_MK20DX32VFM5) || defined(CPU_MK20DN32VFM5) || defined(CPU_MK20DX128VFT5) || defined(CPU_MK20DN128VFT5) || \ defined(CPU_MK20DX64VFT5) || defined(CPU_MK20DN64VFT5) || defined(CPU_MK20DX32VFT5) || defined(CPU_MK20DN32VFT5) || \ defined(CPU_MK20DX128VLF5) || defined(CPU_MK20DN128VLF5) || defined(CPU_MK20DX64VLF5) || defined(CPU_MK20DN64VLF5) || \ defined(CPU_MK20DX32VLF5) || defined(CPU_MK20DN32VLF5) /* @brief Bus clock is the source clock for the module. */ #define FSL_FEATURE_FTM_BUS_CLOCK (1) /* @brief Number of channels. */ #define FSL_FEATURE_FTM_CHANNEL_COUNT (8) #define FSL_FEATURE_FTM_CHANNEL_COUNTn(x) \ ((x) == 0 ? (8) : \ ((x) == 1 ? (2) : (-1))) /* @brief Has counter reset by the selected input capture event (register bits C0SC[ICRST], C1SC[ICRST], ...). */ #define FSL_FEATURE_FTM_HAS_COUNTER_RESET_BY_CAPTURE_EVENT (0) #elif defined(CPU_MK22FN128VDC10) || defined(CPU_MK22FN128VLH10) || defined(CPU_MK22FN128VLL10) || defined(CPU_MK22FN128VMP10) || \ defined(CPU_MK22FN256VDC12) || defined(CPU_MK22FN256VLH12) || defined(CPU_MK22FN256VLL12) || defined(CPU_MK22FN256VMP12) || \ defined(CPU_MKV31F128VLH10) || defined(CPU_MKV31F128VLL10) || defined(CPU_MKV31F256VLH12) || defined(CPU_MKV31F256VLL12) /* @brief Bus clock is the source clock for the module. */ #define FSL_FEATURE_FTM_BUS_CLOCK (1) /* @brief Number of channels. */ #define FSL_FEATURE_FTM_CHANNEL_COUNT (8) #define FSL_FEATURE_FTM_CHANNEL_COUNTn(x) \ ((x) == 0 ? (8) : \ ((x) == 1 ? (2) : \ ((x) == 2 ? (2) : (-1)))) /* @brief Has counter reset by the selected input capture event (register bits C0SC[ICRST], C1SC[ICRST], ...). */ #define FSL_FEATURE_FTM_HAS_COUNTER_RESET_BY_CAPTURE_EVENT (1) #elif defined(CPU_MK22FN512VDC12) || defined(CPU_MK22FN512VLH12) || defined(CPU_MK22FN512VLL12) || defined(CPU_MKV31F512VLH12) || \ defined(CPU_MKV31F512VLL12) /* @brief Bus clock is the source clock for the module. */ #define FSL_FEATURE_FTM_BUS_CLOCK (1) /* @brief Number of channels. */ #define FSL_FEATURE_FTM_CHANNEL_COUNT (8) #define FSL_FEATURE_FTM_CHANNEL_COUNTn(x) \ ((x) == 0 ? (8) : \ ((x) == 1 ? (2) : \ ((x) == 2 ? (2) : \ ((x) == 3 ? (8) : (-1))))) /* @brief Has counter reset by the selected input capture event (register bits C0SC[ICRST], C1SC[ICRST], ...). */ #define FSL_FEATURE_FTM_HAS_COUNTER_RESET_BY_CAPTURE_EVENT (1) #elif defined(CPU_MK24FN1M0VDC12) || defined(CPU_MK24FN1M0VLL12) || defined(CPU_MK24FN1M0VLQ12) || defined(CPU_MK24FN256VDC12) || \ defined(CPU_MK63FN1M0VLQ12) || defined(CPU_MK63FN1M0VMD12) || defined(CPU_MK64FX512VDC12) || defined(CPU_MK64FN1M0VDC12) || \ defined(CPU_MK64FX512VLL12) || defined(CPU_MK64FN1M0VLL12) || defined(CPU_MK64FX512VLQ12) || defined(CPU_MK64FN1M0VLQ12) || \ defined(CPU_MK64FX512VMD12) || defined(CPU_MK64FN1M0VMD12) || defined(CPU_MK65FN2M0CAC18) || defined(CPU_MK65FX1M0CAC18) || \ defined(CPU_MK65FN2M0VMI18) || defined(CPU_MK65FX1M0VMI18) || defined(CPU_MK66FN2M0VLQ18) || defined(CPU_MK66FX1M0VLQ18) || \ defined(CPU_MK66FN2M0VMD18) || defined(CPU_MK66FX1M0VMD18) || defined(CPU_MK70FN1M0VMF12) || defined(CPU_MK70FX512VMF12) || \ defined(CPU_MK70FN1M0VMF15) || defined(CPU_MK70FX512VMF15) || defined(CPU_MK70FN1M0VMJ12) || defined(CPU_MK70FX512VMJ12) || \ defined(CPU_MK70FN1M0VMJ15) || defined(CPU_MK70FX512VMJ15) /* @brief Bus clock is the source clock for the module. */ #define FSL_FEATURE_FTM_BUS_CLOCK (1) /* @brief Number of channels. */ #define FSL_FEATURE_FTM_CHANNEL_COUNT (8) #define FSL_FEATURE_FTM_CHANNEL_COUNTn(x) \ ((x) == 0 ? (8) : \ ((x) == 1 ? (2) : \ ((x) == 2 ? (2) : \ ((x) == 3 ? (8) : (-1))))) /* @brief Has counter reset by the selected input capture event (register bits C0SC[ICRST], C1SC[ICRST], ...). */ #define FSL_FEATURE_FTM_HAS_COUNTER_RESET_BY_CAPTURE_EVENT (0) #elif defined(CPU_MKV40F128VLH15) || defined(CPU_MKV40F256VLH15) || defined(CPU_MKV40F64VLH15) || defined(CPU_MKV45F128VLH15) || \ defined(CPU_MKV45F256VLH15) || defined(CPU_MKV46F128VLH15) || defined(CPU_MKV46F256VLH15) /* @brief Bus clock is the source clock for the module. */ #define FSL_FEATURE_FTM_BUS_CLOCK (1) /* @brief Number of channels. */ #define FSL_FEATURE_FTM_CHANNEL_COUNT (8) #define FSL_FEATURE_FTM_CHANNEL_COUNTn(x) \ ((x) == 0 ? (8) : \ ((x) == 1 ? (2) : (-1))) /* @brief Has counter reset by the selected input capture event (register bits C0SC[ICRST], C1SC[ICRST], ...). */ #define FSL_FEATURE_FTM_HAS_COUNTER_RESET_BY_CAPTURE_EVENT (1) #elif defined(CPU_MKV40F128VLL15) || defined(CPU_MKV40F256VLL15) || defined(CPU_MKV45F128VLL15) || defined(CPU_MKV45F256VLL15) || \ defined(CPU_MKV46F128VLL15) || defined(CPU_MKV46F256VLL15) /* @brief Bus clock is the source clock for the module. */ #define FSL_FEATURE_FTM_BUS_CLOCK (1) /* @brief Number of channels. */ #define FSL_FEATURE_FTM_CHANNEL_COUNT (8) #define FSL_FEATURE_FTM_CHANNEL_COUNTn(x) \ ((x) == 0 ? (8) : \ ((x) == 1 ? (2) : \ ((x) == 2 ? (8) : (-1)))) /* @brief Has counter reset by the selected input capture event (register bits C0SC[ICRST], C1SC[ICRST], ...). */ #define FSL_FEATURE_FTM_HAS_COUNTER_RESET_BY_CAPTURE_EVENT (1) #else #error "No valid CPU defined!" #endif #endif /* __FSL_FTM_FEATURES_H__ */ /******************************************************************************* * EOF ******************************************************************************/ ================================================ FILE: Zelig/mbed/TARGET_K64F/TARGET_Freescale/TARGET_KPSDK_MCUS/TARGET_KPSDK_CODE/hal/flextimer/fsl_ftm_hal.h ================================================ /* * Copyright (c) 2013 - 2014, Freescale Semiconductor, Inc. * All rights reserved. * * Redistribution and use in source and binary forms, with or without modification, * are permitted provided that the following conditions are met: * * o Redistributions of source code must retain the above copyright notice, this list * of conditions and the following disclaimer. * * o Redistributions in binary form must reproduce the above copyright notice, this * list of conditions and the following disclaimer in the documentation and/or * other materials provided with the distribution. * * o Neither the name of Freescale Semiconductor, Inc. nor the names of its * contributors may be used to endorse or promote products derived from this * software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT 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. */ #if !defined(__FSL_FTM_HAL_H__) #define __FSL_FTM_HAL_H__ #include "fsl_device_registers.h" #include "fsl_ftm_features.h" #include #include /*! * @addtogroup ftm_hal * @{ */ /******************************************************************************* * Definitions ******************************************************************************/ #define HW_CHAN0 (0U) /*!< Channel number for CHAN0.*/ #define HW_CHAN1 (1U) /*!< Channel number for CHAN1.*/ #define HW_CHAN2 (2U) /*!< Channel number for CHAN2.*/ #define HW_CHAN3 (3U) /*!< Channel number for CHAN3.*/ #define HW_CHAN4 (4U) /*!< Channel number for CHAN4.*/ #define HW_CHAN5 (5U) /*!< Channel number for CHAN5.*/ #define HW_CHAN6 (6U) /*!< Channel number for CHAN6.*/ #define HW_CHAN7 (7U) /*!< Channel number for CHAN7.*/ #define FTM_COMBINE_CHAN_CTRL_WIDTH (8U) /*! @brief FlexTimer clock source selection*/ typedef enum _ftm_clock_source { kClock_source_FTM_None = 0, kClock_source_FTM_SystemClk, kClock_source_FTM_FixedClk, kClock_source_FTM_ExternalClk }ftm_clock_source_t; /*! @brief FlexTimer counting mode selection */ typedef enum _ftm_counting_mode { kCounting_FTM_UP = 0, kCounting_FTM_UpDown }ftm_counting_mode_t; /*! @brief FlexTimer pre-scaler factor selection for the clock source*/ typedef enum _ftm_clock_ps { kFtmDividedBy1 = 0, kFtmDividedBy2 , kFtmDividedBy4 , kFtmDividedBy8, kFtmDividedBy16, kFtmDividedBy32, kFtmDividedBy64, kFtmDividedBy128 }ftm_clock_ps_t; /*! @brief FlexTimer pre-scaler factor for the deadtime insertion*/ typedef enum _ftm_deadtime_ps { kFtmDivided1 = 1, kFtmDivided4 = 2, kFtmDivided16 = 3, }ftm_deadtime_ps_t; /*! @brief FlexTimer operation mode, capture, output, dual */ typedef enum _ftm_config_mode_t { kFtmInputCapture, kFtmOutputCompare, kFtmEdgeAlignedPWM, kFtmCenterAlignedPWM, kFtmCombinedPWM, kFtmDualEdgeCapture }ftm_config_mode_t; /*! @brief FlexTimer input capture edge mode, rising edge, or falling edge */ typedef enum _ftm_input_capture_edge_mode_t { kFtmRisingEdge = 0, kFtmFallingEdge, kFtmRisingAndFalling }ftm_input_capture_edge_mode_t; /*! @brief FlexTimer output compare edge mode. Toggle, clear or set.*/ typedef enum _ftm_output_compare_edge_mode_t { kFtmToggleOnMatch = 0, kFtmClearOnMatch, kFtmSetOnMatch }ftm_output_compare_edge_mode_t; /*! @brief FlexTimer PWM output pulse mode, high-true or low-true on match up */ typedef enum _ftm_pwm_edge_mode_t { kFtmHighTrue = 0, kFtmLowTrue }ftm_pwm_edge_mode_t; /*! @brief FlexTimer dual capture edge mode, one shot or continuous */ typedef enum _ftm_dual_capture_edge_mode_t { kFtmOneShout = 0, kFtmContinuous }ftm_dual_capture_edge_mode_t; /*! @brief FlexTimer quadrature decode modes, phase encode or count and direction mode */ typedef enum _ftm_quad_decode_mode_t { kFtmQuadPhaseEncode = 0, kFtmQuadCountAndDir }ftm_quad_decode_mode_t; /*! @brief FlexTimer quadrature phase polarities, normal or inverted polarity */ typedef enum _ftm_quad_phase_polarity_t { kFtmQuadPhaseNormal = 0, kFtmQuadPhaseInvert }ftm_quad_phase_polarity_t; /*! @brief FlexTimer edge mode*/ typedef union _ftm_edge_mode_t { ftm_input_capture_edge_mode_t input_capture_edge_mode; ftm_output_compare_edge_mode_t output_compare_edge_mode; ftm_pwm_edge_mode_t ftm_pwm_edge_mode; ftm_dual_capture_edge_mode_t ftm_dual_capture_edge_mode; }ftm_edge_mode_t; /*! * @brief FlexTimer driver PWM parameter * */ typedef struct FtmPwmParam { ftm_config_mode_t mode; /*!< FlexTimer PWM operation mode */ ftm_pwm_edge_mode_t edgeMode; /*!< PWM output mode */ uint32_t uFrequencyHZ; /*!< PWM period in Hz */ uint32_t uDutyCyclePercent; /*!< PWM pulse width, value should be between 0 to 100 0=inactive signal(0% duty cycle)... 100=active signal (100% duty cycle). */ uint16_t uFirstEdgeDelayPercent; /*!< Used only in combined PWM mode to generate asymmetrical PWM. Specifies the delay to the first edge in a PWM period. If unsure please leave as 0, should be specified as percentage of the PWM period*/ }ftm_pwm_param_t; /*! @brief FlexTimer quadrature decode phase parameters */ typedef struct FtmPhaseParam { bool kFtmPhaseInputFilter; /*!< false: disable phase filter, true: enable phase filter */ uint32_t kFtmPhaseFilterVal; /*!< Filter value, used only if phase input filter is enabled */ ftm_quad_phase_polarity_t kFtmPhasePolarity; /*!< kFtmQuadPhaseNormal or kFtmQuadPhaseInvert */ }ftm_phase_params_t; /*FTM timer control*/ /*! * @brief Sets the FTM clock source. * * @param ftmBaseAddr The FTM base address * @param clock The FTM peripheral clock selection\n * bits - 00: No clock 01: system clock 10: fixed clock 11: External clock */ static inline void FTM_HAL_SetClockSource(uint32_t ftmBaseAddr, ftm_clock_source_t clock) { BW_FTM_SC_CLKS(ftmBaseAddr, clock); } /*! * @brief Reads the FTM clock source. * * @param ftmBaseAddr The FTM base address * * @return The FTM clock source selection\n * bits - 00: No clock 01: system clock 10: fixed clock 11:External clock */ static inline uint8_t FTM_HAL_GetClockSource(uint32_t ftmBaseAddr) { return BR_FTM_SC_CLKS(ftmBaseAddr); } /*! * @brief Sets the FTM clock divider. * * @param ftmBaseAddr The FTM base address * @param ps The FTM peripheral clock pre-scale divider */ static inline void FTM_HAL_SetClockPs(uint32_t ftmBaseAddr, ftm_clock_ps_t ps) { BW_FTM_SC_PS(ftmBaseAddr, ps); } /*! * @brief Reads the FTM clock divider. * * @param ftmBaseAddr The FTM base address * * @return The FTM clock pre-scale divider */ static inline uint8_t FTM_HAL_GetClockPs(uint32_t ftmBaseAddr) { return BR_FTM_SC_PS(ftmBaseAddr); } /*! * @brief Enables the FTM peripheral timer overflow interrupt. * * @param ftmBaseAddr The FTM base address */ static inline void FTM_HAL_EnableTimerOverflowInt(uint32_t ftmBaseAddr) { HW_FTM_SC_SET(ftmBaseAddr, BM_FTM_SC_TOIE); } /*! * @brief Disables the FTM peripheral timer overflow interrupt. * * @param ftmBaseAddr The FTM base address */ static inline void FTM_HAL_DisableTimerOverflowInt(uint32_t ftmBaseAddr) { HW_FTM_SC_CLR(ftmBaseAddr, BM_FTM_SC_TOIE); } /*! * @brief Reads the bit that controls enabling the FTM timer overflow interrupt. * * @param baseAddr FTM module base address. * @retval true if overflow interrupt is enabled, false if not */ static inline bool FTM_HAL_IsOverflowIntEnabled(uint32_t baseAddr) { return (bool)(BR_FTM_SC_TOIE(baseAddr)); } /*! * @brief Clears the timer overflow interrupt flag. * * @param ftmBaseAddr The FTM base address */ static inline void FTM_HAL_ClearTimerOverflow(uint32_t ftmBaseAddr) { BW_FTM_SC_TOF(ftmBaseAddr, 0); } /*! * @brief Returns the FTM peripheral timer overflow interrupt flag. * * @param ftmBaseAddr The FTM base address * @retval true if overflow, false if not */ static inline bool FTM_HAL_HasTimerOverflowed(uint32_t ftmBaseAddr) { return BR_FTM_SC_TOF(ftmBaseAddr); } /*! * @brief Sets the FTM center-aligned PWM select. * * @param ftmBaseAddr The FTM base address * @param mode 1:upcounting mode 0:up_down counting mode */ static inline void FTM_HAL_SetCpwms(uint32_t ftmBaseAddr, uint8_t mode) { assert(mode < 2); BW_FTM_SC_CPWMS(ftmBaseAddr, mode); } /*! * @brief Sets the FTM peripheral current counter value. * * @param ftmBaseAddr The FTM base address * @param val FTM timer counter value to be set */ static inline void FTM_HAL_SetCounter(uint32_t ftmBaseAddr,uint16_t val) { BW_FTM_CNT_COUNT(ftmBaseAddr, val); } /*! * @brief Returns the FTM peripheral current counter value. * * @param ftmBaseAddr The FTM base address * @retval current FTM timer counter value */ static inline uint16_t FTM_HAL_GetCounter(uint32_t ftmBaseAddr) { return BR_FTM_CNT_COUNT(ftmBaseAddr); } /*! * @brief Sets the FTM peripheral timer modulo value. * * @param ftmBaseAddr The FTM base address * @param val The value to be set to the timer modulo */ static inline void FTM_HAL_SetMod(uint32_t ftmBaseAddr, uint16_t val) { BW_FTM_MOD_MOD(ftmBaseAddr, val); } /*! * @brief Returns the FTM peripheral counter modulo value. * * @param ftmBaseAddr The FTM base address * @retval FTM timer modulo value */ static inline uint16_t FTM_HAL_GetMod(uint32_t ftmBaseAddr) { return BR_FTM_MOD_MOD(ftmBaseAddr); } /*! * @brief Sets the FTM peripheral timer counter initial value. * * @param ftmBaseAddr The FTM base address * @param val initial value to be set */ static inline void FTM_HAL_SetCounterInitVal(uint32_t ftmBaseAddr, uint16_t val) { BW_FTM_CNTIN_INIT(ftmBaseAddr, val & BM_FTM_CNTIN_INIT); } /*! * @brief Returns the FTM peripheral counter initial value. * * @param ftmBaseAddr The FTM base address * @retval FTM timer counter initial value */ static inline uint16_t FTM_HAL_GetCounterInitVal(uint32_t ftmBaseAddr) { return BR_FTM_CNTIN_INIT(ftmBaseAddr); } /*FTM channel operating mode (Mode, edge and level selection) for capture, output, PWM, combine, dual */ /*! * @brief Sets the FTM peripheral timer channel mode. * * @param ftmBaseAddr The FTM base address * @param channel The FTM peripheral channel number * @param selection The mode to be set valid value MSnB:MSnA :00,01, 10, 11 */ static inline void FTM_HAL_SetChnMSnBAMode(uint32_t ftmBaseAddr, uint8_t channel, uint8_t selection) { assert(channel < FSL_FEATURE_FTM_CHANNEL_COUNT); BW_FTM_CnSC_MSA(ftmBaseAddr, channel, selection & 1); BW_FTM_CnSC_MSB(ftmBaseAddr, channel, selection & 2 ? 1 : 0); } /*! * @brief Sets the FTM peripheral timer channel edge level. * * @param ftmBaseAddr The FTM base address * @param channel The FTM peripheral channel number * @param level The rising or falling edge to be set, valid value ELSnB:ELSnA :00,01, 10, 11 */ static inline void FTM_HAL_SetChnEdgeLevel(uint32_t ftmBaseAddr, uint8_t channel, uint8_t level) { assert(channel < FSL_FEATURE_FTM_CHANNEL_COUNT); BW_FTM_CnSC_ELSA(ftmBaseAddr, channel, level & 1 ? 1 : 0); BW_FTM_CnSC_ELSB(ftmBaseAddr, channel, level & 2 ? 1 : 0); } /*! * @brief Gets the FTM peripheral timer channel mode. * * @param ftmBaseAddr The FTM base address * @param channel The FTM peripheral channel number * @retval The MSnB:MSnA mode value, will be 00,01, 10, 11 */ static inline uint8_t FTM_HAL_GetChnMode(uint32_t ftmBaseAddr, uint8_t channel) { assert(channel < FSL_FEATURE_FTM_CHANNEL_COUNT); return (BR_FTM_CnSC_MSA(ftmBaseAddr, channel)|| (BR_FTM_CnSC_MSB(ftmBaseAddr, channel) << 1)); } /*! * @brief Gets the FTM peripheral timer channel edge level. * * @param ftmBaseAddr The FTM base address * @param channel The FTM peripheral channel number * @retval The ELSnB:ELSnA mode value, will be 00,01, 10, 11 */ static inline uint8_t FTM_HAL_GetChnEdgeLevel(uint32_t ftmBaseAddr, uint8_t channel) { assert(channel < FSL_FEATURE_FTM_CHANNEL_COUNT); return (BR_FTM_CnSC_ELSA(ftmBaseAddr, channel)|| (BR_FTM_CnSC_ELSB(ftmBaseAddr, channel) << 1)); } /*! * @brief Enables or disables the FTM peripheral timer channel DMA. * * @param ftmBaseAddr The FTM base address * @param channel The FTM peripheral channel number * @param val enable or disable */ static inline void FTM_HAL_SetChnDmaCmd(uint32_t ftmBaseAddr, uint8_t channel, bool val) { assert(channel < FSL_FEATURE_FTM_CHANNEL_COUNT); BW_FTM_CnSC_DMA(ftmBaseAddr, channel,(val? 1 : 0)); } /*! * @brief Returns whether the FTM peripheral timer channel DMA is enabled. * * @param ftmBaseAddr The FTM base address * @param channel The FTM peripheral channel number * @retval true if enabled, false if disabled */ static inline bool FTM_HAL_IsChnDma(uint32_t ftmBaseAddr, uint8_t channel) { assert(channel < FSL_FEATURE_FTM_CHANNEL_COUNT); return (BR_FTM_CnSC_DMA(ftmBaseAddr, channel) ? true : false); } /*! * @brief Enables the FTM peripheral timer channel(n) interrupt. * * @param ftmBaseAddr The FTM base address * @param channel The FTM peripheral channel number */ static inline void FTM_HAL_EnableChnInt(uint32_t ftmBaseAddr, uint8_t channel) { assert(channel < FSL_FEATURE_FTM_CHANNEL_COUNT); BW_FTM_CnSC_CHIE(ftmBaseAddr, channel, 1); } /*! * @brief Disables the FTM peripheral timer channel(n) interrupt. * * @param ftmBaseAddr The FTM base address * @param channel The FTM peripheral channel number */ static inline void FTM_HAL_DisableChnInt(uint32_t ftmBaseAddr, uint8_t channel) { assert(channel < FSL_FEATURE_FTM_CHANNEL_COUNT); BW_FTM_CnSC_CHIE(ftmBaseAddr, channel, 0); } /*! * @brief Returns whether any event for the FTM peripheral timer channel has occurred. * * @param ftmBaseAddr The FTM base address * @param channel The FTM peripheral channel number * @retval true if event occurred, false otherwise. */ static inline bool FTM_HAL_HasChnEventOccurred(uint32_t ftmBaseAddr, uint8_t channel) { assert(channel < FSL_FEATURE_FTM_CHANNEL_COUNT); return (BR_FTM_CnSC_CHF(ftmBaseAddr, channel)) ? true : false; } /*FTM channel control*/ /*! * @brief Sets the FTM peripheral timer channel counter value. * * @param ftmBaseAddr The FTM base address * @param channel The FTM peripheral channel number * @param val counter value to be set */ static inline void FTM_HAL_SetChnCountVal(uint32_t ftmBaseAddr, uint8_t channel, uint16_t val) { assert(channel < FSL_FEATURE_FTM_CHANNEL_COUNT); HW_FTM_CnV_WR(ftmBaseAddr, channel, val); } /*! * @brief Gets the FTM peripheral timer channel counter value. * * @param ftmBaseAddr The FTM base address * @param channel The FTM peripheral channel number * @retval val return current channel counter value */ static inline uint16_t FTM_HAL_GetChnCountVal(uint32_t ftmBaseAddr, uint8_t channel, uint16_t val) { assert(channel < FSL_FEATURE_FTM_CHANNEL_COUNT); return BR_FTM_CnV_VAL(ftmBaseAddr, channel); } /*! * @brief Gets the FTM peripheral timer channel event status. * * @param ftmBaseAddr The FTM base address * @param channel The FTM peripheral channel number * @retval val return current channel event status value */ static inline uint32_t FTM_HAL_GetChnEventStatus(uint32_t ftmBaseAddr, uint8_t channel) { assert(channel < FSL_FEATURE_FTM_CHANNEL_COUNT); return (HW_FTM_STATUS_RD(ftmBaseAddr)&(1U << channel)) ? true : false; /*return BR_FTM_STATUS(ftmBaseAddr, channel);*/ } /*! * @brief Clears the FTM peripheral timer all channel event status. * * @param ftmBaseAddr The FTM base address * @param channel The FTM peripheral channel number * @retval val return current channel counter value */ static inline void FTM_HAL_ClearChnEventStatus(uint32_t ftmBaseAddr, uint8_t channel) { assert(channel < FSL_FEATURE_FTM_CHANNEL_COUNT); HW_FTM_STATUS_CLR(ftmBaseAddr, 1U << channel); } /*! * @brief Sets the FTM peripheral timer channel output mask. * * @param ftmBaseAddr The FTM base address * @param channel The FTM peripheral channel number * @param mask mask to be set 0 or 1, unmasked or masked */ static inline void FTM_HAL_SetChnOutputMask(uint32_t ftmBaseAddr, uint8_t channel, bool mask) { assert(channel < FSL_FEATURE_FTM_CHANNEL_COUNT); mask? HW_FTM_OUTMASK_SET(ftmBaseAddr, 1U << channel) : HW_FTM_OUTMASK_CLR(ftmBaseAddr, 1U << channel); /* BW_FTM_OUTMASK_CHnOM(ftmBaseAddr, channel,mask); */ } /*! * @brief Sets the FTM peripheral timer channel output initial state 0 or 1. * * @param ftmBaseAddr The FTM base address * @param channel The FTM peripheral channel number * @param state counter value to be set 0 or 1 */ static inline void FTM_HAL_SetChnOutputInitState(uint32_t ftmBaseAddr, uint8_t channel, uint8_t state) { assert(channel < FSL_FEATURE_FTM_CHANNEL_COUNT); HW_FTM_OUTINIT_CLR(ftmBaseAddr, 1U << channel); HW_FTM_OUTINIT_SET(ftmBaseAddr, (uint8_t)(state << channel)); } /*! * @brief Sets the FTM peripheral timer channel output polarity. * * @param ftmBaseAddr The FTM base address * @param channel The FTM peripheral channel number * @param pol polarity to be set 0 or 1 */ static inline void FTM_HAL_SetChnOutputPolarity(uint32_t ftmBaseAddr, uint8_t channel, uint8_t pol) { assert(channel < FSL_FEATURE_FTM_CHANNEL_COUNT); HW_FTM_POL_CLR(ftmBaseAddr, 1U << channel); HW_FTM_POL_SET(ftmBaseAddr, (uint8_t)(pol << channel)); } /*! * @brief Sets the FTM peripheral timer channel input polarity. * * @param ftmBaseAddr The FTM base address * @param channel The FTM peripheral channel number * @param pol polarity to be set, 0: active high, 1:active low */ static inline void FTM_HAL_SetChnFaultInputPolarity(uint32_t ftmBaseAddr, uint8_t channel, uint8_t pol) { assert(channel < FSL_FEATURE_FTM_CHANNEL_COUNT); HW_FTM_FLTPOL_CLR(ftmBaseAddr, 1U << channel); HW_FTM_FLTPOL_SET(ftmBaseAddr, (uint8_t)(pol< #include #include #include "fsl_gpio_features.h" #include "fsl_device_registers.h" /*! * @addtogroup gpio_hal * @{ */ /*! * @file fsl_gpio_hal.h * * @brief GPIO hardware driver configuration. Use these functions to set the GPIO input/output, * set output logic or get input logic. Check the GPIO header file for base address. Each * GPIO instance has 32 pins with numbers from 0 to 31. */ /******************************************************************************* * Definitions ******************************************************************************/ /*! @brief GPIO direction definition*/ typedef enum _gpio_pin_direction { kGpioDigitalInput = 0, /*!< Set current pin as digital input*/ kGpioDigitalOutput = 1 /*!< Set current pin as digital output*/ } gpio_pin_direction_t; /******************************************************************************* * API ******************************************************************************/ #if defined(__cplusplus) extern "C" { #endif /*! * @name Configuration * @{ */ /*! * @brief Sets the individual GPIO pin to general input or output. * * @param baseAddr GPIO base address(HW_GPIOA, HW_GPIOB, HW_GPIOC, etc.) * @param pin GPIO port pin number * @param direction GPIO directions * - kGpioDigitalInput: set to input * - kGpioDigitalOutput: set to output */ void GPIO_HAL_SetPinDir(uint32_t baseAddr, uint32_t pin, gpio_pin_direction_t direction); /*! * @brief Sets the GPIO port pins to general input or output. * * This function operates all 32 port pins. * * @param baseAddr GPIO base address (HW_GPIOA, HW_GPIOB, HW_GPIOC, etc.) * @param direction GPIO directions * - 0: set to input * - 1: set to output * - LSB: pin 0 * - MSB: pin 31 */ static inline void GPIO_HAL_SetPortDir(uint32_t baseAddr, uint32_t direction) { HW_GPIO_PDDR_WR(baseAddr, direction); } /* @} */ /*! * @name Status * @{ */ /*! * @brief Gets the current direction of the individual GPIO pin. * * @param baseAddr GPIO base address(HW_GPIOA, HW_GPIOB, HW_GPIOC, etc.) * @param pin GPIO port pin number * @return GPIO directions * - kGpioDigitalInput: corresponding pin is set to input. * - kGpioDigitalOutput: corresponding pin is set to output. */ static inline gpio_pin_direction_t GPIO_HAL_GetPinDir(uint32_t baseAddr, uint32_t pin) { assert(pin < 32); return (gpio_pin_direction_t)((HW_GPIO_PDDR_RD(baseAddr) >> pin) & 1U); } /*! * @brief Gets the GPIO port pins direction. * * This function gets all 32-pin directions as a 32-bit integer. * * @param baseAddr GPIO base address (HW_GPIOA, HW_GPIOB, HW_GPIOC, etc.) * @return GPIO directions. Each bit represents one pin. For each bit: * - 0: corresponding pin is set to input * - 1: corresponding pin is set to output * - LSB: pin 0 * - MSB: pin 31 */ static inline uint32_t GPIO_HAL_GetPortDir(uint32_t baseAddr) { return HW_GPIO_PDDR_RD(baseAddr); } /* @} */ /*! * @name Output Operation * @{ */ /*! * @brief Sets the output level of the individual GPIO pin to logic 1 or 0. * * @param baseAddr GPIO base address(HW_GPIOA, HW_GPIOB, HW_GPIOC, etc.) * @param pin GPIO port pin number * @param output pin output logic level */ void GPIO_HAL_WritePinOutput(uint32_t baseAddr, uint32_t pin, uint32_t output); /*! * @brief Reads the current pin output. * * @param baseAddr GPIO base address (HW_GPIOA, HW_GPIOB, HW_GPIOC, etc.) * @param pin GPIO port pin number * @return current pin output status. 0 - Low logic, 1 - High logic */ static inline uint32_t GPIO_HAL_ReadPinOutput(uint32_t baseAddr, uint32_t pin) { assert(pin < 32); return ((HW_GPIO_PDOR_RD(baseAddr) >> pin) & 0x1U); } /*! * @brief Sets the output level of the individual GPIO pin to logic 1. * * @param baseAddr GPIO base address(HW_GPIOA, HW_GPIOB, HW_GPIOC, etc.) * @param pin GPIO port pin number */ static inline void GPIO_HAL_SetPinOutput(uint32_t baseAddr, uint32_t pin) { assert(pin < 32); HW_GPIO_PSOR_WR(baseAddr, 1U << pin); } /*! * @brief Clears the output level of the individual GPIO pin to logic 0. * * @param baseAddr GPIO base address(HW_GPIOA, HW_GPIOB, HW_GPIOC, etc.) * @param pin GPIO port pin number */ static inline void GPIO_HAL_ClearPinOutput(uint32_t baseAddr, uint32_t pin) { assert(pin < 32); HW_GPIO_PCOR_WR(baseAddr, 1U << pin); } /*! * @brief Reverses the current output logic of the individual GPIO pin. * * @param baseAddr GPIO base address(HW_GPIOA, HW_GPIOB, HW_GPIOC, etc.) * @param pin GPIO port pin number */ static inline void GPIO_HAL_TogglePinOutput(uint32_t baseAddr, uint32_t pin) { assert(pin < 32); HW_GPIO_PTOR_WR(baseAddr, 1U << pin); } /*! * @brief Sets the output of the GPIO port to a specific logic value. * * This function operates all 32 port pins. * * @param baseAddr GPIO base address (HW_GPIOA, HW_GPIOB, HW_GPIOC, etc.) * @param portOutput data to configure the GPIO output. Each bit represents one pin. For each bit: * - 0: set logic level 0 to pin * - 1: set logic level 1 to pin * - LSB: pin 0 * - MSB: pin 31 */ static inline void GPIO_HAL_WritePortOutput(uint32_t baseAddr, uint32_t portOutput) { HW_GPIO_PDOR_WR(baseAddr, portOutput); } /*! * @brief Reads out all pin output status of the current port. * * This function operates all 32 port pins. * * @param baseAddr GPIO base address (HW_GPIOA, HW_GPIOB, HW_GPIOC, etc.) * @return current port output status. Each bit represents one pin. For each bit: * - 0: corresponding pin is outputting logic level 0 * - 1: corresponding pin is outputting logic level 1 * - LSB: pin 0 * - MSB: pin 31 */ static inline uint32_t GPIO_HAL_ReadPortOutput(uint32_t baseAddr) { return HW_GPIO_PDOR_RD(baseAddr); } /* @} */ /*! * @name Input Operation * @{ */ /*! * @brief Reads the current input value of the individual GPIO pin. * * @param baseAddr GPIO base address(HW_GPIOA, HW_GPIOB, HW_GPIOC, etc.) * @param pin GPIO port pin number * @return GPIO port input value * - 0: Pin logic level is 0, or is not configured for use by digital function. * - 1: Pin logic level is 1 */ static inline uint32_t GPIO_HAL_ReadPinInput(uint32_t baseAddr, uint32_t pin) { assert(pin < 32); return (HW_GPIO_PDIR_RD(baseAddr) >> pin) & 1U; } /*! * @brief Reads the current input value of a specific GPIO port. * * This function gets all 32-pin input as a 32-bit integer. * * @param baseAddr GPIO base address(HW_GPIOA, HW_GPIOB, HW_GPIOC, etc.) * @return GPIO port input data. Each bit represents one pin. For each bit: * - 0: Pin logic level is 0, or is not configured for use by digital function. * - 1: Pin logic level is 1. * - LSB: pin 0 * - MSB: pin 31 */ static inline uint32_t GPIO_HAL_ReadPortInput(uint32_t baseAddr) { return HW_GPIO_PDIR_RD(baseAddr); } /* @} */ /*! * @name FGPIO Operation * * @note FGPIO (Fast GPIO) is only available in a few MCUs. FGPIO and GPIO share the same * peripheral but use different registers. FGPIO is closer to the core than the regular GPIO * and it's faster to read and write. * @{ */ #if FSL_FEATURE_GPIO_HAS_FAST_GPIO /*! * @name Output Operation * @{ */ /*! * @brief Sets the output level of an individual FGPIO pin to logic 1. * * @param baseAddr GPIO base address(HW_FPTA, HW_FPTB, HW_FPTC, etc.) * @param pin FGPIO port pin number */ static inline void FGPIO_HAL_SetPinOutput(uint32_t baseAddr, uint32_t pin) { assert(pin < 32); HW_FGPIO_PSOR_WR(baseAddr, 1U << pin); } /*! * @brief Clears the output level of an individual FGPIO pin to logic 0. * * @param baseAddr GPIO base address(HW_FPTA, HW_FPTB, HW_FPTC, etc.) * @param pin FGPIO port pin number */ static inline void FGPIO_HAL_ClearPinOutput(uint32_t baseAddr, uint32_t pin) { assert(pin < 32); HW_FGPIO_PCOR_WR(baseAddr, 1U << pin); } /*! * @brief Reverses the current output logic of an individual FGPIO pin. * * @param baseAddr GPIO base address(HW_FPTA, HW_FPTB, HW_FPTC, etc.) * @param pin FGPIO port pin number */ static inline void FGPIO_HAL_TogglePinOutput(uint32_t baseAddr, uint32_t pin) { assert(pin < 32); HW_FGPIO_PTOR_WR(baseAddr, 1U << pin); } /*! * @brief Sets the output of the FGPIO port to a specific logic value. * * This function affects all 32 port pins. * * @param baseAddr GPIO base address(HW_FPTA, HW_FPTB, HW_FPTC, etc.) * @param portOutput data to configure the GPIO output. Each bit represents one pin. For each bit: * - 0: set logic level 0 to pin. * - 1: set logic level 1 to pin. * - LSB: pin 0 * - MSB: pin 31 */ static inline void FGPIO_HAL_WritePortOutput(uint32_t baseAddr, uint32_t portOutput) { HW_FGPIO_PDOR_WR(baseAddr, portOutput); } /* @} */ /*! * @name Input Operation * @{ */ /*! * @brief Gets the current input value of an individual FGPIO pin. * * @param baseAddr GPIO base address(HW_FPTA, HW_FPTB, HW_FPTC, etc.) * @param pin FGPIO port pin number * @return FGPIO port input data * - 0: Pin logic level is 0, or is not configured for use by digital function. * - 1: Pin logic level is 1. */ static inline uint32_t FGPIO_HAL_ReadPinInput(uint32_t baseAddr, uint32_t pin) { assert(pin < 32); return (HW_FGPIO_PDIR_RD(baseAddr) >> pin) & 1U; } /*! * @brief Gets the current input value of a specific FGPIO port. * * This function gets all 32-pin input as a 32-bit integer. * * @param baseAddr GPIO base address(HW_FPTA, HW_FPTB, HW_FPTC, etc.). * @return FGPIO port input data. Each bit represents one pin. For each bit: * - 0: Pin logic level is 0, or is not configured for use by digital function. * - 1: Pin logic level is 1. * - LSB: pin 0 * - MSB: pin 31 */ static inline uint32_t FGPIO_HAL_ReadPortInput(uint32_t baseAddr) { return HW_FGPIO_PDIR_RD(baseAddr); } /* @} */ #endif /* FSL_FEATURE_GPIO_HAS_FAST_GPIO*/ #if defined(__cplusplus) } #endif /*! @} */ #endif /* __FSL_GPIO_HAL_H__*/ /******************************************************************************* * EOF ******************************************************************************/ ================================================ FILE: Zelig/mbed/TARGET_K64F/TARGET_Freescale/TARGET_KPSDK_MCUS/TARGET_KPSDK_CODE/hal/i2c/fsl_i2c_features.h ================================================ /* ** ################################################################### ** Version: rev. 1.0, 2014-05-14 ** Build: b140515 ** ** Abstract: ** Chip specific module features. ** ** Copyright: 2014 Freescale Semiconductor, Inc. ** All rights reserved. ** ** Redistribution and use in source and binary forms, with or without modification, ** are permitted provided that the following conditions are met: ** ** o Redistributions of source code must retain the above copyright notice, this list ** of conditions and the following disclaimer. ** ** o Redistributions in binary form must reproduce the above copyright notice, this ** list of conditions and the following disclaimer in the documentation and/or ** other materials provided with the distribution. ** ** o Neither the name of Freescale Semiconductor, Inc. nor the names of its ** contributors may be used to endorse or promote products derived from this ** software without specific prior written permission. ** ** THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ** ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED ** WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE ** DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT 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. ** ** http: www.freescale.com ** mail: support@freescale.com ** ** Revisions: ** - rev. 1.0 (2014-05-14) ** Customer release. ** ** ################################################################### */ #if !defined(__FSL_I2C_FEATURES_H__) #define __FSL_I2C_FEATURES_H__ #if defined(CPU_MK02FN128VFM10) || defined(CPU_MK02FN64VFM10) || defined(CPU_MK02FN128VLF10) || defined(CPU_MK02FN64VLF10) || \ defined(CPU_MK02FN128VLH10) || defined(CPU_MK02FN64VLH10) || defined(CPU_MK22FN128VDC10) || defined(CPU_MK22FN128VLH10) || \ defined(CPU_MK22FN128VLL10) || defined(CPU_MK22FN128VMP10) || defined(CPU_MK22FN256VDC12) || defined(CPU_MK22FN256VLH12) || \ defined(CPU_MK22FN256VLL12) || defined(CPU_MK22FN256VMP12) || defined(CPU_MK22FN512VDC12) || defined(CPU_MK22FN512VLH12) || \ defined(CPU_MK22FN512VLL12) || defined(CPU_MK24FN1M0VDC12) || defined(CPU_MK24FN1M0VLL12) || defined(CPU_MK24FN1M0VLQ12) || \ defined(CPU_MK63FN1M0VLQ12) || defined(CPU_MK63FN1M0VMD12) || defined(CPU_MK64FX512VDC12) || defined(CPU_MK64FN1M0VDC12) || \ defined(CPU_MK64FX512VLL12) || defined(CPU_MK64FN1M0VLL12) || defined(CPU_MK64FX512VLQ12) || defined(CPU_MK64FN1M0VLQ12) || \ defined(CPU_MK64FX512VMD12) || defined(CPU_MK64FN1M0VMD12) || defined(CPU_MK65FN2M0CAC18) || defined(CPU_MK65FX1M0CAC18) || \ defined(CPU_MK65FN2M0VMI18) || defined(CPU_MK65FX1M0VMI18) || defined(CPU_MK66FN2M0VLQ18) || defined(CPU_MK66FX1M0VLQ18) || \ defined(CPU_MK66FN2M0VMD18) || defined(CPU_MK66FX1M0VMD18) || defined(CPU_MKV30F128VFM10) || defined(CPU_MKV30F64VFM10) || \ defined(CPU_MKV30F128VLF10) || defined(CPU_MKV30F64VLF10) || defined(CPU_MKV30F128VLH10) || defined(CPU_MKV30F64VLH10) || \ defined(CPU_MKV31F128VLH10) || defined(CPU_MKV31F128VLL10) || defined(CPU_MKV31F256VLH12) || defined(CPU_MKV31F256VLL12) || \ defined(CPU_MKV31F512VLH12) || defined(CPU_MKV31F512VLL12) /* @brief Has I2C bus stop detection (register bit FLT[STOPF]). */ #define FSL_FEATURE_I2C_HAS_STOP_DETECT (1) /* @brief Has System Management Bus support (registers SMB, A2, SLTL and SLTH). */ #define FSL_FEATURE_I2C_HAS_SMBUS (1) /* @brief Maximum supported baud rate in kilobit per second. */ #define FSL_FEATURE_I2C_MAX_BAUD_KBPS (400) /* @brief Is affected by errata with ID 6070 (repeat start cannot be generated if the F[MULT] bit field is set to a non-zero value). */ #define FSL_FEATURE_I2C_HAS_ERRATA_6070 (0) /* @brief Has DMA support (register bit C1[DMAEN]). */ #define FSL_FEATURE_I2C_HAS_DMA_SUPPORT (1) /* @brief Has I2C bus start detection (register bits FLT[STARTF] and FLT[SSIE]). */ #define FSL_FEATURE_I2C_HAS_START_DETECT (1) /* @brief Has I2C bus stop detection interrupt (register bit FLT[STOPIE]). */ #define FSL_FEATURE_I2C_HAS_STOP_DETECT_INTERRUPT (0) /* @brief Has I2C bus stop hold off (register bit FLT[SHEN]). */ #define FSL_FEATURE_I2C_HAS_STOP_HOLD_OFF (1) /* @brief Maximum width of the glitch filter in number of bus clocks. */ #define FSL_FEATURE_I2C_MAX_GLITCH_FILTER_WIDTH (15) /* @brief Has control of the drive capability of the I2C pins. */ #define FSL_FEATURE_I2C_HAS_HIGH_DRIVE_SELECTION (1) /* @brief Has double buffering support (register S2). */ #define FSL_FEATURE_I2C_HAS_DOUBLE_BUFFERING (0) #elif defined(CPU_MK20DX128VMP5) || defined(CPU_MK20DN128VMP5) || defined(CPU_MK20DX64VMP5) || defined(CPU_MK20DN64VMP5) || \ defined(CPU_MK20DX32VMP5) || defined(CPU_MK20DN32VMP5) || defined(CPU_MK20DX128VLH5) || defined(CPU_MK20DN128VLH5) || \ defined(CPU_MK20DX64VLH5) || defined(CPU_MK20DN64VLH5) || defined(CPU_MK20DX32VLH5) || defined(CPU_MK20DN32VLH5) || \ defined(CPU_MK20DX128VFM5) || defined(CPU_MK20DN128VFM5) || defined(CPU_MK20DX64VFM5) || defined(CPU_MK20DN64VFM5) || \ defined(CPU_MK20DX32VFM5) || defined(CPU_MK20DN32VFM5) || defined(CPU_MK20DX128VFT5) || defined(CPU_MK20DN128VFT5) || \ defined(CPU_MK20DX64VFT5) || defined(CPU_MK20DN64VFT5) || defined(CPU_MK20DX32VFT5) || defined(CPU_MK20DN32VFT5) || \ defined(CPU_MK20DX128VLF5) || defined(CPU_MK20DN128VLF5) || defined(CPU_MK20DX64VLF5) || defined(CPU_MK20DN64VLF5) || \ defined(CPU_MK20DX32VLF5) || defined(CPU_MK20DN32VLF5) || defined(CPU_MK70FN1M0VMF12) || defined(CPU_MK70FX512VMF12) || \ defined(CPU_MK70FN1M0VMF15) || defined(CPU_MK70FX512VMF15) || defined(CPU_MK70FN1M0VMJ12) || defined(CPU_MK70FX512VMJ12) || \ defined(CPU_MK70FN1M0VMJ15) || defined(CPU_MK70FX512VMJ15) /* @brief Has I2C bus stop detection (register bit FLT[STOPF]). */ #define FSL_FEATURE_I2C_HAS_STOP_DETECT (0) /* @brief Has System Management Bus support (registers SMB, A2, SLTL and SLTH). */ #define FSL_FEATURE_I2C_HAS_SMBUS (1) /* @brief Maximum supported baud rate in kilobit per second. */ #define FSL_FEATURE_I2C_MAX_BAUD_KBPS (400) /* @brief Is affected by errata with ID 6070 (repeat start cannot be generated if the F[MULT] bit field is set to a non-zero value). */ #define FSL_FEATURE_I2C_HAS_ERRATA_6070 (0) /* @brief Has DMA support (register bit C1[DMAEN]). */ #define FSL_FEATURE_I2C_HAS_DMA_SUPPORT (1) /* @brief Has I2C bus start detection (register bits FLT[STARTF] and FLT[SSIE]). */ #define FSL_FEATURE_I2C_HAS_START_DETECT (0) /* @brief Has I2C bus stop detection interrupt (register bit FLT[STOPIE]). */ #define FSL_FEATURE_I2C_HAS_STOP_DETECT_INTERRUPT (0) /* @brief Has I2C bus stop hold off (register bit FLT[SHEN]). */ #define FSL_FEATURE_I2C_HAS_STOP_HOLD_OFF (0) /* @brief Maximum width of the glitch filter in number of bus clocks. */ #define FSL_FEATURE_I2C_MAX_GLITCH_FILTER_WIDTH (31) /* @brief Has control of the drive capability of the I2C pins. */ #define FSL_FEATURE_I2C_HAS_HIGH_DRIVE_SELECTION (1) /* @brief Has double buffering support (register S2). */ #define FSL_FEATURE_I2C_HAS_DOUBLE_BUFFERING (0) #elif defined(CPU_MK24FN256VDC12) /* @brief Has I2C bus stop detection (register bit FLT[STOPF]). */ #define FSL_FEATURE_I2C_HAS_STOP_DETECT (1) /* @brief Has System Management Bus support (registers SMB, A2, SLTL and SLTH). */ #define FSL_FEATURE_I2C_HAS_SMBUS (1) /* @brief Maximum supported baud rate in kilobit per second. */ #define FSL_FEATURE_I2C_MAX_BAUD_KBPS (100) /* @brief Is affected by errata with ID 6070 (repeat start cannot be generated if the F[MULT] bit field is set to a non-zero value). */ #define FSL_FEATURE_I2C_HAS_ERRATA_6070 (0) /* @brief Has DMA support (register bit C1[DMAEN]). */ #define FSL_FEATURE_I2C_HAS_DMA_SUPPORT (1) /* @brief Has I2C bus start detection (register bits FLT[STARTF] and FLT[SSIE]). */ #define FSL_FEATURE_I2C_HAS_START_DETECT (1) /* @brief Has I2C bus stop detection interrupt (register bit FLT[STOPIE]). */ #define FSL_FEATURE_I2C_HAS_STOP_DETECT_INTERRUPT (0) /* @brief Has I2C bus stop hold off (register bit FLT[SHEN]). */ #define FSL_FEATURE_I2C_HAS_STOP_HOLD_OFF (1) /* @brief Maximum width of the glitch filter in number of bus clocks. */ #define FSL_FEATURE_I2C_MAX_GLITCH_FILTER_WIDTH (15) /* @brief Has control of the drive capability of the I2C pins. */ #define FSL_FEATURE_I2C_HAS_HIGH_DRIVE_SELECTION (1) /* @brief Has double buffering support (register S2). */ #define FSL_FEATURE_I2C_HAS_DOUBLE_BUFFERING (0) #elif defined(CPU_MKL03Z32CAF4) || defined(CPU_MKL03Z8VFG4) || defined(CPU_MKL03Z16VFG4) || defined(CPU_MKL03Z32VFG4) || \ defined(CPU_MKL03Z8VFK4) || defined(CPU_MKL03Z16VFK4) || defined(CPU_MKL03Z32VFK4) /* @brief Has I2C bus stop detection (register bit FLT[STOPF]). */ #define FSL_FEATURE_I2C_HAS_STOP_DETECT (1) /* @brief Has System Management Bus support (registers SMB, A2, SLTL and SLTH). */ #define FSL_FEATURE_I2C_HAS_SMBUS (1) /* @brief Maximum supported baud rate in kilobit per second. */ #define FSL_FEATURE_I2C_MAX_BAUD_KBPS (400) /* @brief Is affected by errata with ID 6070 (repeat start cannot be generated if the F[MULT] bit field is set to a non-zero value). */ #define FSL_FEATURE_I2C_HAS_ERRATA_6070 (0) /* @brief Has DMA support (register bit C1[DMAEN]). */ #define FSL_FEATURE_I2C_HAS_DMA_SUPPORT (0) /* @brief Has I2C bus start detection (register bits FLT[STARTF] and FLT[SSIE]). */ #define FSL_FEATURE_I2C_HAS_START_DETECT (1) /* @brief Has I2C bus stop detection interrupt (register bit FLT[STOPIE]). */ #define FSL_FEATURE_I2C_HAS_STOP_DETECT_INTERRUPT (0) /* @brief Has I2C bus stop hold off (register bit FLT[SHEN]). */ #define FSL_FEATURE_I2C_HAS_STOP_HOLD_OFF (1) /* @brief Maximum width of the glitch filter in number of bus clocks. */ #define FSL_FEATURE_I2C_MAX_GLITCH_FILTER_WIDTH (15) /* @brief Has control of the drive capability of the I2C pins. */ #define FSL_FEATURE_I2C_HAS_HIGH_DRIVE_SELECTION (0) /* @brief Has double buffering support (register S2). */ #define FSL_FEATURE_I2C_HAS_DOUBLE_BUFFERING (1) #elif defined(CPU_MKL05Z8VFK4) || defined(CPU_MKL05Z16VFK4) || defined(CPU_MKL05Z32VFK4) || defined(CPU_MKL05Z8VLC4) || \ defined(CPU_MKL05Z16VLC4) || defined(CPU_MKL05Z32VLC4) || defined(CPU_MKL05Z8VFM4) || defined(CPU_MKL05Z16VFM4) || \ defined(CPU_MKL05Z32VFM4) || defined(CPU_MKL05Z16VLF4) || defined(CPU_MKL05Z32VLF4) || defined(CPU_MKL25Z32VFM4) || \ defined(CPU_MKL25Z64VFM4) || defined(CPU_MKL25Z128VFM4) || defined(CPU_MKL25Z32VFT4) || defined(CPU_MKL25Z64VFT4) || \ defined(CPU_MKL25Z128VFT4) || defined(CPU_MKL25Z32VLH4) || defined(CPU_MKL25Z64VLH4) || defined(CPU_MKL25Z128VLH4) || \ defined(CPU_MKL25Z32VLK4) || defined(CPU_MKL25Z64VLK4) || defined(CPU_MKL25Z128VLK4) /* @brief Has I2C bus stop detection (register bit FLT[STOPF]). */ #define FSL_FEATURE_I2C_HAS_STOP_DETECT (1) /* @brief Has System Management Bus support (registers SMB, A2, SLTL and SLTH). */ #define FSL_FEATURE_I2C_HAS_SMBUS (1) /* @brief Maximum supported baud rate in kilobit per second. */ #define FSL_FEATURE_I2C_MAX_BAUD_KBPS (400) /* @brief Is affected by errata with ID 6070 (repeat start cannot be generated if the F[MULT] bit field is set to a non-zero value). */ #define FSL_FEATURE_I2C_HAS_ERRATA_6070 (1) /* @brief Has DMA support (register bit C1[DMAEN]). */ #define FSL_FEATURE_I2C_HAS_DMA_SUPPORT (1) /* @brief Has I2C bus start detection (register bits FLT[STARTF] and FLT[SSIE]). */ #define FSL_FEATURE_I2C_HAS_START_DETECT (0) /* @brief Has I2C bus stop detection interrupt (register bit FLT[STOPIE]). */ #define FSL_FEATURE_I2C_HAS_STOP_DETECT_INTERRUPT (1) /* @brief Has I2C bus stop hold off (register bit FLT[SHEN]). */ #define FSL_FEATURE_I2C_HAS_STOP_HOLD_OFF (1) /* @brief Maximum width of the glitch filter in number of bus clocks. */ #define FSL_FEATURE_I2C_MAX_GLITCH_FILTER_WIDTH (31) /* @brief Has control of the drive capability of the I2C pins. */ #define FSL_FEATURE_I2C_HAS_HIGH_DRIVE_SELECTION (1) /* @brief Has double buffering support (register S2). */ #define FSL_FEATURE_I2C_HAS_DOUBLE_BUFFERING (0) #elif defined(CPU_MKL13Z64VFM4) || defined(CPU_MKL13Z128VFM4) || defined(CPU_MKL13Z256VFM4) || defined(CPU_MKL13Z64VFT4) || \ defined(CPU_MKL13Z128VFT4) || defined(CPU_MKL13Z256VFT4) || defined(CPU_MKL13Z64VLH4) || defined(CPU_MKL13Z128VLH4) || \ defined(CPU_MKL13Z256VLH4) || defined(CPU_MKL13Z64VMP4) || defined(CPU_MKL13Z128VMP4) || defined(CPU_MKL13Z256VMP4) || \ defined(CPU_MKL23Z64VFM4) || defined(CPU_MKL23Z128VFM4) || defined(CPU_MKL23Z256VFM4) || defined(CPU_MKL23Z64VFT4) || \ defined(CPU_MKL23Z128VFT4) || defined(CPU_MKL23Z256VFT4) || defined(CPU_MKL23Z64VLH4) || defined(CPU_MKL23Z128VLH4) || \ defined(CPU_MKL23Z256VLH4) || defined(CPU_MKL23Z64VMP4) || defined(CPU_MKL23Z128VMP4) || defined(CPU_MKL23Z256VMP4) || \ defined(CPU_MKL33Z128VLH4) || defined(CPU_MKL33Z256VLH4) || defined(CPU_MKL33Z128VMP4) || defined(CPU_MKL33Z256VMP4) || \ defined(CPU_MKL43Z64VLH4) || defined(CPU_MKL43Z128VLH4) || defined(CPU_MKL43Z256VLH4) || defined(CPU_MKL43Z64VMP4) || \ defined(CPU_MKL43Z128VMP4) || defined(CPU_MKL43Z256VMP4) /* @brief Has I2C bus stop detection (register bit FLT[STOPF]). */ #define FSL_FEATURE_I2C_HAS_STOP_DETECT (1) /* @brief Has System Management Bus support (registers SMB, A2, SLTL and SLTH). */ #define FSL_FEATURE_I2C_HAS_SMBUS (1) /* @brief Maximum supported baud rate in kilobit per second. */ #define FSL_FEATURE_I2C_MAX_BAUD_KBPS (400) /* @brief Is affected by errata with ID 6070 (repeat start cannot be generated if the F[MULT] bit field is set to a non-zero value). */ #define FSL_FEATURE_I2C_HAS_ERRATA_6070 (1) /* @brief Has DMA support (register bit C1[DMAEN]). */ #define FSL_FEATURE_I2C_HAS_DMA_SUPPORT (1) /* @brief Has I2C bus start detection (register bits FLT[STARTF] and FLT[SSIE]). */ #define FSL_FEATURE_I2C_HAS_START_DETECT (1) /* @brief Has I2C bus stop detection interrupt (register bit FLT[STOPIE]). */ #define FSL_FEATURE_I2C_HAS_STOP_DETECT_INTERRUPT (0) /* @brief Has I2C bus stop hold off (register bit FLT[SHEN]). */ #define FSL_FEATURE_I2C_HAS_STOP_HOLD_OFF (1) /* @brief Maximum width of the glitch filter in number of bus clocks. */ #define FSL_FEATURE_I2C_MAX_GLITCH_FILTER_WIDTH (15) /* @brief Has control of the drive capability of the I2C pins. */ #define FSL_FEATURE_I2C_HAS_HIGH_DRIVE_SELECTION (1) /* @brief Has double buffering support (register S2). */ #define FSL_FEATURE_I2C_HAS_DOUBLE_BUFFERING (1) #elif defined(CPU_MKL26Z256VLK4) || defined(CPU_MKL26Z128VLL4) || defined(CPU_MKL26Z256VLL4) || defined(CPU_MKL26Z128VMC4) || \ defined(CPU_MKL26Z256VMC4) || defined(CPU_MKL46Z128VLH4) || defined(CPU_MKL46Z256VLH4) || defined(CPU_MKL46Z128VLL4) || \ defined(CPU_MKL46Z256VLL4) || defined(CPU_MKL46Z128VMC4) || defined(CPU_MKL46Z256VMC4) /* @brief Has I2C bus stop detection (register bit FLT[STOPF]). */ #define FSL_FEATURE_I2C_HAS_STOP_DETECT (1) /* @brief Has System Management Bus support (registers SMB, A2, SLTL and SLTH). */ #define FSL_FEATURE_I2C_HAS_SMBUS (1) /* @brief Maximum supported baud rate in kilobit per second. */ #define FSL_FEATURE_I2C_MAX_BAUD_KBPS (100) /* @brief Is affected by errata with ID 6070 (repeat start cannot be generated if the F[MULT] bit field is set to a non-zero value). */ #define FSL_FEATURE_I2C_HAS_ERRATA_6070 (1) /* @brief Has DMA support (register bit C1[DMAEN]). */ #define FSL_FEATURE_I2C_HAS_DMA_SUPPORT (1) /* @brief Has I2C bus start detection (register bits FLT[STARTF] and FLT[SSIE]). */ #define FSL_FEATURE_I2C_HAS_START_DETECT (0) /* @brief Has I2C bus stop detection interrupt (register bit FLT[STOPIE]). */ #define FSL_FEATURE_I2C_HAS_STOP_DETECT_INTERRUPT (1) /* @brief Has I2C bus stop hold off (register bit FLT[SHEN]). */ #define FSL_FEATURE_I2C_HAS_STOP_HOLD_OFF (1) /* @brief Maximum width of the glitch filter in number of bus clocks. */ #define FSL_FEATURE_I2C_MAX_GLITCH_FILTER_WIDTH (31) /* @brief Has control of the drive capability of the I2C pins. */ #define FSL_FEATURE_I2C_HAS_HIGH_DRIVE_SELECTION (1) /* @brief Has double buffering support (register S2). */ #define FSL_FEATURE_I2C_HAS_DOUBLE_BUFFERING (0) #elif defined(CPU_MKV40F128VLH15) || defined(CPU_MKV40F128VLL15) || defined(CPU_MKV40F256VLH15) || defined(CPU_MKV40F256VLL15) || \ defined(CPU_MKV40F64VLH15) || defined(CPU_MKV43F128VLH15) || defined(CPU_MKV43F128VLL15) || defined(CPU_MKV43F64VLH15) || \ defined(CPU_MKV44F128VLH15) || defined(CPU_MKV44F128VLL15) || defined(CPU_MKV44F64VLH15) || defined(CPU_MKV45F128VLH15) || \ defined(CPU_MKV45F128VLL15) || defined(CPU_MKV45F256VLH15) || defined(CPU_MKV45F256VLL15) || defined(CPU_MKV46F128VLH15) || \ defined(CPU_MKV46F128VLL15) || defined(CPU_MKV46F256VLH15) || defined(CPU_MKV46F256VLL15) /* @brief Has I2C bus stop detection (register bit FLT[STOPF]). */ #define FSL_FEATURE_I2C_HAS_STOP_DETECT (1) /* @brief Has System Management Bus support (registers SMB, A2, SLTL and SLTH). */ #define FSL_FEATURE_I2C_HAS_SMBUS (1) /* @brief Maximum supported baud rate in kilobit per second. */ #define FSL_FEATURE_I2C_MAX_BAUD_KBPS (100) /* @brief Is affected by errata with ID 6070 (repeat start cannot be generated if the F[MULT] bit field is set to a non-zero value). */ #define FSL_FEATURE_I2C_HAS_ERRATA_6070 (0) /* @brief Has DMA support (register bit C1[DMAEN]). */ #define FSL_FEATURE_I2C_HAS_DMA_SUPPORT (1) /* @brief Has I2C bus start detection (register bits FLT[STARTF] and FLT[SSIE]). */ #define FSL_FEATURE_I2C_HAS_START_DETECT (0) /* @brief Has I2C bus stop detection interrupt (register bit FLT[STOPIE]). */ #define FSL_FEATURE_I2C_HAS_STOP_DETECT_INTERRUPT (1) /* @brief Has I2C bus stop hold off (register bit FLT[SHEN]). */ #define FSL_FEATURE_I2C_HAS_STOP_HOLD_OFF (1) /* @brief Maximum width of the glitch filter in number of bus clocks. */ #define FSL_FEATURE_I2C_MAX_GLITCH_FILTER_WIDTH (31) /* @brief Has control of the drive capability of the I2C pins. */ #define FSL_FEATURE_I2C_HAS_HIGH_DRIVE_SELECTION (1) /* @brief Has double buffering support (register S2). */ #define FSL_FEATURE_I2C_HAS_DOUBLE_BUFFERING (0) #else #error "No valid CPU defined!" #endif #endif /* __FSL_I2C_FEATURES_H__ */ /******************************************************************************* * EOF ******************************************************************************/ ================================================ FILE: Zelig/mbed/TARGET_K64F/TARGET_Freescale/TARGET_KPSDK_MCUS/TARGET_KPSDK_CODE/hal/i2c/fsl_i2c_hal.h ================================================ /* * Copyright (c) 2013 - 2014, Freescale Semiconductor, Inc. * All rights reserved. * * Redistribution and use in source and binary forms, with or without modification, * are permitted provided that the following conditions are met: * * o Redistributions of source code must retain the above copyright notice, this list * of conditions and the following disclaimer. * * o Redistributions in binary form must reproduce the above copyright notice, this * list of conditions and the following disclaimer in the documentation and/or * other materials provided with the distribution. * * o Neither the name of Freescale Semiconductor, Inc. nor the names of its * contributors may be used to endorse or promote products derived from this * software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT 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. */ #if !defined(__FSL_I2C_HAL_H__) #define __FSL_I2C_HAL_H__ #include #include #include "fsl_i2c_features.h" #include "fsl_device_registers.h" /*! * @addtogroup i2c_hal * @{ */ /******************************************************************************* * Definitions ******************************************************************************/ /*! @brief I2C status return codes.*/ typedef enum _i2c_status { kStatus_I2C_Success = 0x0U, kStatus_I2C_OutOfRange = 0x1U, kStatus_I2C_Fail = 0x2U, kStatus_I2C_Busy = 0x3U, /*!< The master is already performing a transfer.*/ kStatus_I2C_Timeout = 0x4U, /*!< The transfer timed out.*/ kStatus_I2C_ReceivedNak = 0x5U, /*!< The slave device sent a NAK in response to a byte.*/ kStatus_I2C_SlaveTxUnderrun = 0x6U, /*!< I2C Slave TX Underrun error.*/ kStatus_I2C_SlaveRxOverrun = 0x7U, /*!< I2C Slave RX Overrun error.*/ kStatus_I2C_AribtrationLost = 0x8U, /*!< I2C Arbitration Lost error.*/ } i2c_status_t; /*! @brief I2C status flags. */ typedef enum _i2c_status_flag { kI2CTransferComplete = BP_I2C_S_TCF, kI2CAddressAsSlave = BP_I2C_S_IAAS, kI2CBusBusy = BP_I2C_S_BUSY, kI2CArbitrationLost = BP_I2C_S_ARBL, kI2CAddressMatch = BP_I2C_S_RAM, kI2CSlaveTransmit = BP_I2C_S_SRW, kI2CInterruptPending = BP_I2C_S_IICIF, kI2CReceivedNak = BP_I2C_S_RXAK } i2c_status_flag_t; /*! @brief Direction of master and slave transfers.*/ typedef enum _i2c_direction { kI2CReceive = 0U, /*!< Master and slave receive.*/ kI2CSend = 1U /*!< Master and slave transmit.*/ } i2c_direction_t; /******************************************************************************* * API ******************************************************************************/ #if defined(__cplusplus) extern "C" { #endif /*! * @name Module controls * @{ */ /*! * @brief Restores the I2C peripheral to reset state. * * @param baseAddr The I2C peripheral base address */ void I2C_HAL_Init(uint32_t baseAddr); /*! * @brief Enables the I2C module operation. * * @param baseAddr The I2C peripheral base address */ static inline void I2C_HAL_Enable(uint32_t baseAddr) { BW_I2C_C1_IICEN(baseAddr, 0x1U); } /*! * @brief Disables the I2C module operation. * * @param baseAddr The I2C peripheral base address */ static inline void I2C_HAL_Disable(uint32_t baseAddr) { BW_I2C_C1_IICEN(baseAddr, 0x0U); } /*@}*/ /*! * @name DMA * @{ */ /*! * @brief Enables or disables the DMA support. * * @param baseAddr The I2C peripheral base address * @param enable Pass true to enable DMA transfer signalling */ static inline void I2C_HAL_SetDmaCmd(uint32_t baseAddr, bool enable) { BW_I2C_C1_DMAEN(baseAddr, (uint8_t)enable); } /*! * @brief Returns whether I2C DMA support is enabled. * * @param baseAddr The I2C peripheral base address. * @retval true I2C DMA is enabled. * @retval false I2C DMA is disabled. */ static inline bool I2C_HAL_GetDmaCmd(uint32_t baseAddr) { return BR_I2C_C1_DMAEN(baseAddr); } /*@}*/ /*! * @name Pin functions * @{ */ /*! * @brief Controls the drive capability of the I2C pads. * * @param baseAddr The I2C peripheral base address * @param enable Passing true will enable high drive mode of the I2C pads. False sets normal * drive mode. */ static inline void I2C_HAL_SetHighDriveCmd(uint32_t baseAddr, bool enable) { BW_I2C_C2_HDRS(baseAddr, (uint8_t)enable); } /*! * @brief Controls the width of the programmable glitch filter. * * Controls the width of the glitch, in terms of bus clock cycles, that the filter must absorb. * The filter does not allow any glitch whose size is less than or equal to this width setting, * to pass. * * @param baseAddr The I2C peripheral base address * @param glitchWidth Maximum width in bus clock cycles of the glitches that is filtered. * Pass zero to disable the glitch filter. */ static inline void I2C_HAL_SetGlitchWidth(uint32_t baseAddr, uint8_t glitchWidth) { BW_I2C_FLT_FLT(baseAddr, glitchWidth); } /*@}*/ /*! * @name Low power * @{ */ /*! * @brief Controls the I2C wakeup enable. * * The I2C module can wake the MCU from low power mode with no peripheral bus running when * slave address matching occurs. * * @param baseAddr The I2C peripheral base address. * @param enable true - Enables the wakeup function in low power mode.
* false - Normal operation. No interrupt is generated when address matching in * low power mode. */ static inline void I2C_HAL_SetWakeupCmd(uint32_t baseAddr, bool enable) { BW_I2C_C1_WUEN(baseAddr, (uint8_t)enable); } #if FSL_FEATURE_I2C_HAS_STOP_HOLD_OFF /*! * @brief Controls the stop mode hold off. * * This function lets you enable the hold off entry to low power stop mode when any data transmission * or reception is occurring. * * @param baseAddr The I2C peripheral base address * @param enable false - Stop hold off is disabled. The MCU's entry to stop mode is not gated.
* true - Stop hold off is enabled. */ static inline void I2C_HAL_SetStopHoldoffCmd(uint32_t baseAddr, bool enable) { BW_I2C_FLT_SHEN(baseAddr, (uint8_t)enable); } #endif /* FSL_FEATURE_I2C_HAS_STOP_HOLD_OFF*/ /*@}*/ /*! * @name Baud rate * @{ */ /*! * @brief Sets the I2C bus frequency for master transactions. * * @param baseAddr The I2C peripheral base address * @param sourceClockInHz I2C source input clock in Hertz * @param kbps Requested bus frequency in kilohertz. Common values are either 100 or 400. * @param absoluteError_Hz If this parameter is not NULL, it is filled in with the * difference in Hertz between the requested bus frequency and the closest frequency * possible given available divider values. * * @retval kStatus_Success The baud rate was changed successfully. However, there is no * guarantee on the minimum error. If you want to ensure that the baud was set to within * a certain error, then use the @a absoluteError_Hz parameter. * @retval kStatus_OutOfRange The requested baud rate was not within the range of rates * supported by the peripheral. */ i2c_status_t I2C_HAL_SetBaudRate(uint32_t baseAddr, uint32_t sourceClockInHz, uint32_t kbps, uint32_t * absoluteError_Hz); /*! * @brief Sets the I2C baud rate multiplier and table entry. * * Use this function to set the I2C bus frequency register values directly, if they are * known in advance. * * @param baseAddr The I2C peripheral base address * @param mult Value of the MULT bitfield, ranging from 0-2. * @param icr The ICR bitfield value, which is the index into an internal table in the I2C * hardware that selects the baud rate divisor and SCL hold time. */ static inline void I2C_HAL_SetFreqDiv(uint32_t baseAddr, uint8_t mult, uint8_t icr) { HW_I2C_F_WR(baseAddr, BF_I2C_F_MULT(mult) | BF_I2C_F_ICR(icr)); } /*! * @brief Slave baud rate control * * Enables an independent slave mode baud rate at the maximum frequency. This forces clock stretching * on the SCL in very fast I2C modes. * * @param baseAddr The I2C peripheral base address * @param enable true - Slave baud rate is independent of the master baud rate;
* false - The slave baud rate follows the master baud rate and clock stretching may occur. */ static inline void I2C_HAL_SetSlaveBaudCtrlCmd(uint32_t baseAddr, bool enable) { BW_I2C_C2_SBRC(baseAddr, (uint8_t)enable); } /*@}*/ /*! * @name Bus operations * @{ */ /*! * @brief Sends a START or a Repeated START signal on the I2C bus. * * This function is used to initiate a new master mode transfer by sending the START signal. It * is also used to send a Repeated START signal when a transfer is already in progress. * * @param baseAddr The I2C peripheral base address */ void I2C_HAL_SendStart(uint32_t baseAddr); /*! * @brief Sends a STOP signal on the I2C bus. * * This function changes the direction to receive. * * @param baseAddr The I2C peripheral base address */ static inline void I2C_HAL_SendStop(uint32_t baseAddr) { assert(BR_I2C_C1_MST(baseAddr) == 1); HW_I2C_C1_CLR(baseAddr, BM_I2C_C1_MST | BM_I2C_C1_TX); } /*! * @brief Causes an ACK to be sent on the bus. * * This function specifies that an ACK signal is sent in response to the next received byte. * * Note that the behavior of this function is changed when the I2C peripheral is placed in * Fast ACK mode. In this case, this function causes an ACK signal to be sent in * response to the current byte, rather than the next received byte. * * @param baseAddr The I2C peripheral base address */ static inline void I2C_HAL_SendAck(uint32_t baseAddr) { BW_I2C_C1_TXAK(baseAddr, 0x0U); } /*! * @brief Causes a NAK to be sent on the bus. * * This function specifies that a NAK signal is sent in response to the next received byte. * * Note that the behavior of this function is changed when the I2C peripheral is placed in the * Fast ACK mode. In this case, this function causes an NAK signal to be sent in * response to the current byte, rather than the next received byte. * * @param baseAddr The I2C peripheral base address */ static inline void I2C_HAL_SendNak(uint32_t baseAddr) { BW_I2C_C1_TXAK(baseAddr, 0x1U); } /*! * @brief Selects either transmit or receive mode. * * @param baseAddr The I2C peripheral base address. * @param direction Specifies either transmit mode or receive mode. The valid values are: * - #kI2CTransmit * - #kI2CReceive */ static inline void I2C_HAL_SetDirMode(uint32_t baseAddr, i2c_direction_t direction) { BW_I2C_C1_TX(baseAddr, (uint8_t)direction); } /*! * @brief Returns the currently selected transmit or receive mode. * * @param baseAddr The I2C peripheral base address. * @retval #kI2CTransmit I2C is configured for master or slave transmit mode. * @retval #kI2CReceive I2C is configured for master or slave receive mode. */ static inline i2c_direction_t I2C_HAL_GetDirMode(uint32_t baseAddr) { return (i2c_direction_t)BR_I2C_C1_TX(baseAddr); } /*@}*/ /*! * @name Data transfer * @{ */ /*! * @brief Returns the last byte of data read from the bus and initiate another read. * * In a master receive mode, calling this function initiates receiving the next byte of data. * * @param baseAddr The I2C peripheral base address * @return This function returns the last byte received while the I2C module is configured in master * receive or slave receive mode. */ static inline uint8_t I2C_HAL_ReadByte(uint32_t baseAddr) { return HW_I2C_D_RD(baseAddr); } /*! * @brief Writes one byte of data to the I2C bus. * * When this function is called in the master transmit mode, a data transfer is initiated. In slave * mode, the same function is available after an address match occurs. * * In a master transmit mode, the first byte of data written following the start bit or repeated * start bit is used for the address transfer and must consist of the slave address (in bits 7-1) * concatenated with the required R/\#W bit (in position bit 0). * * @param baseAddr The I2C peripheral base address. * @param byte The byte of data to transmit. */ static inline void I2C_HAL_WriteByte(uint32_t baseAddr, uint8_t byte) { HW_I2C_D_WR(baseAddr, byte); } /*@}*/ /*! * @name Slave address * @{ */ /*! * @brief Sets the primary 7-bit slave address. * * @param baseAddr The I2C peripheral base address * @param address The slave address in the upper 7 bits. Bit 0 of this value must be 0. */ void I2C_HAL_SetAddress7bit(uint32_t baseAddr, uint8_t address); /*! * @brief Sets the primary slave address and enables 10-bit address mode. * * @param baseAddr The I2C peripheral base address * @param address The 10-bit slave address, in bits [10:1] of the value. Bit 0 must be 0. */ void I2C_HAL_SetAddress10bit(uint32_t baseAddr, uint16_t address); /*! * @brief Enables or disables the extension address (10-bit). * * @param baseAddr The I2C peripheral base address * @param enable true: 10-bit address is enabled. * false: 10-bit address is not enabled. */ static inline void I2C_HAL_SetExtensionAddrCmd(uint32_t baseAddr, bool enable) { BW_I2C_C2_ADEXT(baseAddr, (uint8_t)enable); } /*! * @brief Returns whether the extension address is enabled or not. * * @param baseAddr The I2C peripheral base address * @return true: 10-bit address is enabled. * false: 10-bit address is not enabled. */ static inline bool I2C_HAL_GetExtensionAddrCmd(uint32_t baseAddr) { return BR_I2C_C2_ADEXT(baseAddr); } /*! * @brief Controls whether the general call address is recognized. * * @param baseAddr The I2C peripheral base address * @param enable Whether to enable the general call address. */ static inline void I2C_HAL_SetGeneralCallCmd(uint32_t baseAddr, bool enable) { BW_I2C_C2_GCAEN(baseAddr, (uint8_t)enable); } /*! * @brief Enables or disables the slave address range matching. * * @param baseAddr The I2C peripheral base address. * @param enable Pass true to enable range address matching. You must also call * I2C_HAL_SetUpperAddress7bit() to set the upper address. */ static inline void I2C_HAL_SetRangeMatchCmd(uint32_t baseAddr, bool enable) { BW_I2C_C2_RMEN(baseAddr, (uint8_t)enable); } /*! * @brief Sets the upper slave address. * * This slave address is used as a secondary slave address. If range address * matching is enabled, this slave address acts as the upper bound on the slave address * range. * * This function sets only a 7-bit slave address. If 10-bit addressing was enabled by calling * I2C_HAL_SetAddress10bit(), then the top 3 bits set with that function are also used * with the address set with this function to form a 10-bit address. * * Passing 0 for the @a address parameter disables matching the upper slave address. * * @param baseAddr The I2C peripheral base address * @param address The upper slave address in the upper 7 bits. Bit 0 of this value must be 0. * In addition, this address must be greater than the primary slave address that is set by * calling I2C_HAL_SetAddress7bit(). */ static inline void I2C_HAL_SetUpperAddress7bit(uint32_t baseAddr, uint8_t address) { assert((address & 1) == 0); assert((address == 0) || (address > HW_I2C_A1_RD(baseAddr))); HW_I2C_RA_WR(baseAddr, address); } /*@}*/ /*! * @name Status * @{ */ /*! * @brief Gets the I2C status flag state. * * @param baseAddr The I2C peripheral base address. * @param statusFlag The status flag, defined in type i2c_status_flag_t. * @return State of the status flag: asserted (true) or not-asserted (false). * - true: related status flag is being set. * - false: related status flag is not set. */ static inline bool I2C_HAL_GetStatusFlag(uint32_t baseAddr, i2c_status_flag_t statusFlag) { return (bool)((HW_I2C_S_RD(baseAddr) >> statusFlag) & 0x1U); } /*! * @brief Returns whether the I2C module is in master mode. * * @param baseAddr The I2C peripheral base address. * @retval true The module is in master mode, which implies it is also performing a transfer. * @retval false The module is in slave mode. */ static inline bool I2C_HAL_IsMaster(uint32_t baseAddr) { return (bool)BR_I2C_C1_MST(baseAddr); } /*! * @brief Clears the arbitration lost flag. * * @param baseAddr The I2C peripheral base address */ static inline void I2C_HAL_ClearArbitrationLost(uint32_t baseAddr) { BW_I2C_S_ARBL(baseAddr, 0x1U); } /*@}*/ /*! * @name Interrupt * @{ */ /*! * @brief Enables or disables I2C interrupt requests. * * @param baseAddr The I2C peripheral base address * @param enable Pass true to enable interrupt, flase to disable. */ static inline void I2C_HAL_SetIntCmd(uint32_t baseAddr, bool enable) { BW_I2C_C1_IICIE(baseAddr, (uint8_t)enable); } /*! * @brief Returns whether the I2C interrupts are enabled. * * @param baseAddr The I2C peripheral base address * @retval true I2C interrupts are enabled. * @retval false I2C interrupts are disabled. */ static inline bool I2C_HAL_GetIntCmd(uint32_t baseAddr) { return (bool)BR_I2C_C1_IICIE(baseAddr); } /*! * @brief Returns the current I2C interrupt flag. * * @param baseAddr The I2C peripheral base address * @retval true An interrupt is pending. * @retval false No interrupt is pending. */ static inline bool I2C_HAL_IsIntPending(uint32_t baseAddr) { return (bool)BR_I2C_S_IICIF(baseAddr); } /*! * @brief Clears the I2C interrupt if set. * * @param baseAddr The I2C peripheral base address */ static inline void I2C_HAL_ClearInt(uint32_t baseAddr) { BW_I2C_S_IICIF(baseAddr, 0x1U); } /*@}*/ #if FSL_FEATURE_I2C_HAS_STOP_DETECT /*! * @name Bus stop detection status * @{ */ /*! * @brief Gets the flag indicating a STOP signal was detected on the I2C bus. * * @param baseAddr The I2C peripheral base address * @retval true STOP signal detected on bus. * @retval false No STOP signal was detected on the bus. */ static inline bool I2C_HAL_GetStopFlag(uint32_t baseAddr) { return (bool)BR_I2C_FLT_STOPF(baseAddr); } /*! * @brief Clears the bus STOP signal detected flag. * * @param baseAddr The I2C peripheral base address */ static inline void I2C_HAL_ClearStopFlag(uint32_t baseAddr) { BW_I2C_FLT_STOPF(baseAddr, 0x1U); } /*@}*/ #if FSL_FEATURE_I2C_HAS_START_DETECT /*! * @name Bus stop detection interrupt * @{ */ /*! * @brief Enables the I2C bus stop detection interrupt. * * @param baseAddr The I2C peripheral base address * @param enable Pass true to enable interrupt, flase to disable. */ static inline void I2C_HAL_SetStopIntCmd(uint32_t baseAddr, bool enable) { BW_I2C_FLT_SSIE(baseAddr, enable); } /*! * @brief Returns whether the I2C bus stop detection interrupts are enabled. * * @param baseAddr The I2C peripheral base address * @retval true Stop detect interrupts are enabled. * @retval false Stop detect interrupts are disabled. */ static inline bool I2C_HAL_GetStopIntCmd(uint32_t baseAddr) { return (bool)BR_I2C_FLT_SSIE(baseAddr); } #else /*! @name Bus stop detection interrupt*/ /*@{*/ /*! * @brief Enables the I2C bus stop detection interrupt. * * @param baseAddr The I2C peripheral base address */ static inline void I2C_HAL_SetStopIntCmd(uint32_t baseAddr, bool enable) { BW_I2C_FLT_STOPIE(baseAddr, enable); } /*! * @brief Returns whether the I2C bus stop detection interrupts are enabled. * * @param baseAddr The I2C peripheral base address * @retval true Stop detect interrupts are enabled. * @retval false Stop detect interrupts are disabled. */ static inline bool I2C_HAL_GetStopIntCmd(uint32_t baseAddr) { return (bool)BR_I2C_FLT_STOPIE(baseAddr); } #endif /* FSL_FEATURE_I2C_HAS_START_DETECT*/ /*@}*/ #endif /* FSL_FEATURE_I2C_HAS_STOP_DETECT*/ #if defined(__cplusplus) } #endif /*! @} */ #endif /* __FSL_I2C_HAL_H__*/ /******************************************************************************* * EOF ******************************************************************************/ ================================================ FILE: Zelig/mbed/TARGET_K64F/TARGET_Freescale/TARGET_KPSDK_MCUS/TARGET_KPSDK_CODE/hal/llwu/fsl_llwu_features.h ================================================ /* ** ################################################################### ** Version: rev. 1.0, 2014-05-14 ** Build: b140515 ** ** Abstract: ** Chip specific module features. ** ** Copyright: 2014 Freescale Semiconductor, Inc. ** All rights reserved. ** ** Redistribution and use in source and binary forms, with or without modification, ** are permitted provided that the following conditions are met: ** ** o Redistributions of source code must retain the above copyright notice, this list ** of conditions and the following disclaimer. ** ** o Redistributions in binary form must reproduce the above copyright notice, this ** list of conditions and the following disclaimer in the documentation and/or ** other materials provided with the distribution. ** ** o Neither the name of Freescale Semiconductor, Inc. nor the names of its ** contributors may be used to endorse or promote products derived from this ** software without specific prior written permission. ** ** THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ** ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED ** WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE ** DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT 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. ** ** http: www.freescale.com ** mail: support@freescale.com ** ** Revisions: ** - rev. 1.0 (2014-05-14) ** Customer release. ** ** ################################################################### */ #if !defined(__FSL_LLWU_FEATURES_H__) #define __FSL_LLWU_FEATURES_H__ #if defined(CPU_MK02FN128VFM10) || defined(CPU_MK02FN64VFM10) || defined(CPU_MK02FN128VLF10) || defined(CPU_MK02FN64VLF10) || \ defined(CPU_MK02FN128VLH10) || defined(CPU_MK02FN64VLH10) || defined(CPU_MKV30F128VFM10) || defined(CPU_MKV30F64VFM10) || \ defined(CPU_MKV30F128VLF10) || defined(CPU_MKV30F64VLF10) || defined(CPU_MKV30F128VLH10) || defined(CPU_MKV30F64VLH10) || \ defined(CPU_MKV31F128VLH10) || defined(CPU_MKV31F128VLL10) || defined(CPU_MKV31F256VLH12) || defined(CPU_MKV31F256VLL12) || \ defined(CPU_MKV31F512VLH12) || defined(CPU_MKV31F512VLL12) /* @brief Maximum number of pins connected to LLWU device. */ #define FSL_FEATURE_LLWU_HAS_EXTERNAL_PIN (16) /* @brief Maximum number of internal modules connected to LLWU device. */ #define FSL_FEATURE_LLWU_HAS_INTERNAL_MODULE (3) /* @brief Number of digital filters. */ #define FSL_FEATURE_LLWU_HAS_PIN_FILTER (2) /* @brief Has possibility to enable reset in low leakage power mode and enable digital filter for RESET pin (register LLWU_RST). */ #define FSL_FEATURE_LLWU_HAS_RESET_ENABLE (0) #elif defined(CPU_MK20DX128VMP5) || defined(CPU_MK20DN128VMP5) || defined(CPU_MK20DX64VMP5) || defined(CPU_MK20DN64VMP5) || \ defined(CPU_MK20DX32VMP5) || defined(CPU_MK20DN32VMP5) || defined(CPU_MK20DX128VLH5) || defined(CPU_MK20DN128VLH5) || \ defined(CPU_MK20DX64VLH5) || defined(CPU_MK20DN64VLH5) || defined(CPU_MK20DX32VLH5) || defined(CPU_MK20DN32VLH5) || \ defined(CPU_MK20DX128VFM5) || defined(CPU_MK20DN128VFM5) || defined(CPU_MK20DX64VFM5) || defined(CPU_MK20DN64VFM5) || \ defined(CPU_MK20DX32VFM5) || defined(CPU_MK20DN32VFM5) || defined(CPU_MK20DX128VFT5) || defined(CPU_MK20DN128VFT5) || \ defined(CPU_MK20DX64VFT5) || defined(CPU_MK20DN64VFT5) || defined(CPU_MK20DX32VFT5) || defined(CPU_MK20DN32VFT5) || \ defined(CPU_MK20DX128VLF5) || defined(CPU_MK20DN128VLF5) || defined(CPU_MK20DX64VLF5) || defined(CPU_MK20DN64VLF5) || \ defined(CPU_MK20DX32VLF5) || defined(CPU_MK20DN32VLF5) || defined(CPU_MK24FN1M0VDC12) || defined(CPU_MK24FN1M0VLL12) || \ defined(CPU_MK24FN1M0VLQ12) || defined(CPU_MK24FN256VDC12) || defined(CPU_MK63FN1M0VLQ12) || defined(CPU_MK63FN1M0VMD12) || \ defined(CPU_MK64FX512VDC12) || defined(CPU_MK64FN1M0VDC12) || defined(CPU_MK64FX512VLL12) || defined(CPU_MK64FN1M0VLL12) || \ defined(CPU_MK64FX512VLQ12) || defined(CPU_MK64FN1M0VLQ12) || defined(CPU_MK64FX512VMD12) || defined(CPU_MK64FN1M0VMD12) || \ defined(CPU_MK70FN1M0VMF12) || defined(CPU_MK70FX512VMF12) || defined(CPU_MK70FN1M0VMF15) || defined(CPU_MK70FX512VMF15) || \ defined(CPU_MK70FN1M0VMJ12) || defined(CPU_MK70FX512VMJ12) || defined(CPU_MK70FN1M0VMJ15) || defined(CPU_MK70FX512VMJ15) /* @brief Maximum number of pins connected to LLWU device. */ #define FSL_FEATURE_LLWU_HAS_EXTERNAL_PIN (16) /* @brief Maximum number of internal modules connected to LLWU device. */ #define FSL_FEATURE_LLWU_HAS_INTERNAL_MODULE (8) /* @brief Number of digital filters. */ #define FSL_FEATURE_LLWU_HAS_PIN_FILTER (2) /* @brief Has possibility to enable reset in low leakage power mode and enable digital filter for RESET pin (register LLWU_RST). */ #define FSL_FEATURE_LLWU_HAS_RESET_ENABLE (1) #elif defined(CPU_MK22FN128VDC10) || defined(CPU_MK22FN128VLH10) || defined(CPU_MK22FN128VLL10) || defined(CPU_MK22FN128VMP10) || \ defined(CPU_MK22FN256VDC12) || defined(CPU_MK22FN256VLH12) || defined(CPU_MK22FN256VLL12) || defined(CPU_MK22FN256VMP12) || \ defined(CPU_MK22FN512VDC12) || defined(CPU_MK22FN512VLH12) || defined(CPU_MK22FN512VLL12) || defined(CPU_MK65FN2M0CAC18) || \ defined(CPU_MK65FX1M0CAC18) || defined(CPU_MK65FN2M0VMI18) || defined(CPU_MK65FX1M0VMI18) || defined(CPU_MK66FN2M0VLQ18) || \ defined(CPU_MK66FX1M0VLQ18) || defined(CPU_MK66FN2M0VMD18) || defined(CPU_MK66FX1M0VMD18) || defined(CPU_MKL13Z64VFM4) || \ defined(CPU_MKL13Z128VFM4) || defined(CPU_MKL13Z256VFM4) || defined(CPU_MKL13Z64VFT4) || defined(CPU_MKL13Z128VFT4) || \ defined(CPU_MKL13Z256VFT4) || defined(CPU_MKL13Z64VLH4) || defined(CPU_MKL13Z128VLH4) || defined(CPU_MKL13Z256VLH4) || \ defined(CPU_MKL13Z64VMP4) || defined(CPU_MKL13Z128VMP4) || defined(CPU_MKL13Z256VMP4) || defined(CPU_MKL23Z64VFM4) || \ defined(CPU_MKL23Z128VFM4) || defined(CPU_MKL23Z256VFM4) || defined(CPU_MKL23Z64VFT4) || defined(CPU_MKL23Z128VFT4) || \ defined(CPU_MKL23Z256VFT4) || defined(CPU_MKL23Z64VLH4) || defined(CPU_MKL23Z128VLH4) || defined(CPU_MKL23Z256VLH4) || \ defined(CPU_MKL23Z64VMP4) || defined(CPU_MKL23Z128VMP4) || defined(CPU_MKL23Z256VMP4) || defined(CPU_MKL25Z32VFM4) || \ defined(CPU_MKL25Z64VFM4) || defined(CPU_MKL25Z128VFM4) || defined(CPU_MKL25Z32VFT4) || defined(CPU_MKL25Z64VFT4) || \ defined(CPU_MKL25Z128VFT4) || defined(CPU_MKL25Z32VLH4) || defined(CPU_MKL25Z64VLH4) || defined(CPU_MKL25Z128VLH4) || \ defined(CPU_MKL25Z32VLK4) || defined(CPU_MKL25Z64VLK4) || defined(CPU_MKL25Z128VLK4) || defined(CPU_MKL26Z256VLK4) || \ defined(CPU_MKL26Z128VLL4) || defined(CPU_MKL26Z256VLL4) || defined(CPU_MKL26Z128VMC4) || defined(CPU_MKL26Z256VMC4) || \ defined(CPU_MKL33Z128VLH4) || defined(CPU_MKL33Z256VLH4) || defined(CPU_MKL33Z128VMP4) || defined(CPU_MKL33Z256VMP4) || \ defined(CPU_MKL43Z64VLH4) || defined(CPU_MKL43Z128VLH4) || defined(CPU_MKL43Z256VLH4) || defined(CPU_MKL43Z64VMP4) || \ defined(CPU_MKL43Z128VMP4) || defined(CPU_MKL43Z256VMP4) || defined(CPU_MKL46Z128VLH4) || defined(CPU_MKL46Z256VLH4) || \ defined(CPU_MKL46Z128VLL4) || defined(CPU_MKL46Z256VLL4) || defined(CPU_MKL46Z128VMC4) || defined(CPU_MKL46Z256VMC4) /* @brief Maximum number of pins connected to LLWU device. */ #define FSL_FEATURE_LLWU_HAS_EXTERNAL_PIN (16) /* @brief Maximum number of internal modules connected to LLWU device. */ #define FSL_FEATURE_LLWU_HAS_INTERNAL_MODULE (8) /* @brief Number of digital filters. */ #define FSL_FEATURE_LLWU_HAS_PIN_FILTER (2) /* @brief Has possibility to enable reset in low leakage power mode and enable digital filter for RESET pin (register LLWU_RST). */ #define FSL_FEATURE_LLWU_HAS_RESET_ENABLE (0) #elif defined(CPU_MKL03Z32CAF4) || defined(CPU_MKL03Z8VFG4) || defined(CPU_MKL03Z16VFG4) || defined(CPU_MKL03Z32VFG4) || \ defined(CPU_MKL03Z8VFK4) || defined(CPU_MKL03Z16VFK4) || defined(CPU_MKL03Z32VFK4) /* @brief Maximum number of pins connected to LLWU device. */ #define FSL_FEATURE_LLWU_HAS_EXTERNAL_PIN (8) /* @brief Maximum number of internal modules connected to LLWU device. */ #define FSL_FEATURE_LLWU_HAS_INTERNAL_MODULE (0) /* @brief Number of digital filters. */ #define FSL_FEATURE_LLWU_HAS_PIN_FILTER (1) /* @brief Has possibility to enable reset in low leakage power mode and enable digital filter for RESET pin (register LLWU_RST). */ #define FSL_FEATURE_LLWU_HAS_RESET_ENABLE (0) #elif defined(CPU_MKL05Z8VFK4) || defined(CPU_MKL05Z16VFK4) || defined(CPU_MKL05Z32VFK4) || defined(CPU_MKL05Z8VLC4) || \ defined(CPU_MKL05Z16VLC4) || defined(CPU_MKL05Z32VLC4) || defined(CPU_MKL05Z8VFM4) || defined(CPU_MKL05Z16VFM4) || \ defined(CPU_MKL05Z32VFM4) || defined(CPU_MKL05Z16VLF4) || defined(CPU_MKL05Z32VLF4) /* @brief Maximum number of pins connected to LLWU device. */ #define FSL_FEATURE_LLWU_HAS_EXTERNAL_PIN (8) /* @brief Maximum number of internal modules connected to LLWU device. */ #define FSL_FEATURE_LLWU_HAS_INTERNAL_MODULE (8) /* @brief Number of digital filters. */ #define FSL_FEATURE_LLWU_HAS_PIN_FILTER (2) /* @brief Has possibility to enable reset in low leakage power mode and enable digital filter for RESET pin (register LLWU_RST). */ #define FSL_FEATURE_LLWU_HAS_RESET_ENABLE (0) #elif defined(CPU_MKV40F128VLH15) || defined(CPU_MKV40F128VLL15) || defined(CPU_MKV40F256VLH15) || defined(CPU_MKV40F256VLL15) || \ defined(CPU_MKV40F64VLH15) || defined(CPU_MKV43F128VLH15) || defined(CPU_MKV43F128VLL15) || defined(CPU_MKV43F64VLH15) || \ defined(CPU_MKV44F128VLH15) || defined(CPU_MKV44F128VLL15) || defined(CPU_MKV44F64VLH15) || defined(CPU_MKV45F128VLH15) || \ defined(CPU_MKV45F128VLL15) || defined(CPU_MKV45F256VLH15) || defined(CPU_MKV45F256VLL15) || defined(CPU_MKV46F128VLH15) || \ defined(CPU_MKV46F128VLL15) || defined(CPU_MKV46F256VLH15) || defined(CPU_MKV46F256VLL15) /* @brief Maximum number of pins connected to LLWU device. */ #define FSL_FEATURE_LLWU_HAS_EXTERNAL_PIN (16) /* @brief Maximum number of internal modules connected to LLWU device. */ #define FSL_FEATURE_LLWU_HAS_INTERNAL_MODULE (4) /* @brief Number of digital filters. */ #define FSL_FEATURE_LLWU_HAS_PIN_FILTER (2) /* @brief Has possibility to enable reset in low leakage power mode and enable digital filter for RESET pin (register LLWU_RST). */ #define FSL_FEATURE_LLWU_HAS_RESET_ENABLE (0) #else #error "No valid CPU defined!" #endif #endif /* __FSL_LLWU_FEATURES_H__ */ /******************************************************************************* * EOF ******************************************************************************/ ================================================ FILE: Zelig/mbed/TARGET_K64F/TARGET_Freescale/TARGET_KPSDK_MCUS/TARGET_KPSDK_CODE/hal/llwu/fsl_llwu_hal.h ================================================ /* * Copyright (c) 2013 - 2014, Freescale Semiconductor, Inc. * All rights reserved. * * Redistribution and use in source and binary forms, with or without modification, * are permitted provided that the following conditions are met: * * o Redistributions of source code must retain the above copyright notice, this list * of conditions and the following disclaimer. * * o Redistributions in binary form must reproduce the above copyright notice, this * list of conditions and the following disclaimer in the documentation and/or * other materials provided with the distribution. * * o Neither the name of Freescale Semiconductor, Inc. nor the names of its * contributors may be used to endorse or promote products derived from this * software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT 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. */ #if !defined(__FSL_LLWU_HAL_H__) #define __FSL_LLWU_HAL_H__ #include #include #include #include "fsl_device_registers.h" #include "fsl_llwu_features.h" /*! @addtogroup llwu_hal*/ /*! @{*/ /*! @file fsl_llwu_hal.h */ /******************************************************************************* * Definitions ******************************************************************************/ /*! @brief External input pin control modes */ typedef enum _llwu_external_pin_modes { kLlwuExternalPinDisabled, /* pin disabled as wakeup input */ kLlwuExternalPinRisingEdge, /* pin enabled with rising edge detection */ kLlwuExternalPinFallingEdge, /* pin enabled with falling edge detection */ kLlwuExternalPinChangeDetect /* pin enabled with any change detection */ } llwu_external_pin_modes_t; /*! @brief Digital filter control modes */ typedef enum _llwu_filter_modes { kLlwuFilterDisabled, /* filter disabled */ kLlwuFilterPosEdgeDetect, /* filter positive edge detection */ kLlwuFilterNegEdgeDetect, /* filter negative edge detection */ kLlwuFilterAnyEdgeDetect /* filter any edge detection */ } llwu_filter_modes_t; /*! @brief External input pin filter control structure */ typedef struct _llwu_external_pin_filter_mode { llwu_filter_modes_t filterMode; /* filter mode */ uint32_t pinNumber; /* pin number */ } llwu_external_pin_filter_mode_t; /*! @brief Reset enable control structure */ typedef struct _llwu_reset_enable_mode { bool lowLeakageMode; /* reset for Low-leakage mode */ bool digitalFilterMode; /* reset for digital filter mode */ } llwu_reset_enable_mode_t; /******************************************************************************* * API ******************************************************************************/ /*! * @brief Sets the external input pin source mode. * * This function sets the external input pin source mode that is used * as a wake up source. * * @param baseAddr Register base address of LLWU * @param pinMode pin configuration mode defined in llwu_external_pin_modes_t * @param pinNumber pin number specified */ void LLWU_HAL_SetExternalInputPinMode(uint32_t baseAddr, llwu_external_pin_modes_t pinMode, uint32_t pinNumber); /*! * @brief Gets the external input pin source mode. * * This function gets the external input pin source mode that is used * as wake up source. * * @param baseAddr Register base address of LLWU * @param pinNumber pin number specified * @return pinMode pin mode defined in llwu_external_pin_modes_t */ llwu_external_pin_modes_t LLWU_HAL_GetExternalInputPinMode(uint32_t baseAddr, uint32_t pinNumber); /*! * @brief Enables/disables the internal module source. * * This function enables/disables the internal module source mode that is used * as a wake up source. * * @param baseAddr Register base address of LLWU * @param moduleNumber module number specified * @param enable enable or disable setting */ void LLWU_HAL_SetInternalModuleCmd(uint32_t baseAddr, uint32_t moduleNumber, bool enable); /*! * @brief Gets the internal module source enable setting. * * This function gets the internal module source enable setting that is used * as a wake up source. * * @param baseAddr Register base address of LLWU * @param moduleNumber module number specified * @return enable enable or disable setting */ bool LLWU_HAL_GetInternalModuleCmd(uint32_t baseAddr, uint32_t moduleNumber); /*! * @brief Gets the external wakeup source flag. * * This function gets the external wakeup source flag for a specific pin. * * @param baseAddr Register base address of LLWU * @param pinNumber pin number specified * @return flag true if wakeup source flag set */ bool LLWU_HAL_GetExternalPinWakeupFlag(uint32_t baseAddr, uint32_t pinNumber); /*! * @brief Clears the external wakeup source flag. * * This function clears the external wakeup source flag for a specific pin. * * @param baseAddr Register base address of LLWU * @param pinNumber pin number specified */ void LLWU_HAL_ClearExternalPinWakeupFlag(uint32_t baseAddr, uint32_t pinNumber); /*! * @brief Gets the internal module wakeup source flag. * * This function gets the internal module wakeup source flag for a specific module. * * @param baseAddr Register base address of LLWU * @param moduleNumber module number specified * @return flag true if wakeup flag set */ bool LLWU_HAL_GetInternalModuleWakeupFlag(uint32_t baseAddr, uint32_t moduleNumber); /*! * @brief Sets the pin filter configuration. * * This function sets the pin filter configuration. * * @param baseAddr Register base address of LLWU * @param filterNumber filter number specified * @param pinFilterMode filter mode configuration */ void LLWU_HAL_SetPinFilterMode(uint32_t baseAddr, uint32_t filterNumber, llwu_external_pin_filter_mode_t pinFilterMode); /*! * @brief Gets the pin filter configuration. * * This function gets the pin filter configuration. * * @param baseAddr Register base address of LLWU * @param filterNumber filter number specified * @param pinFilterMode filter mode configuration */ void LLWU_HAL_GetPinFilterMode(uint32_t baseAddr, uint32_t filterNumber, llwu_external_pin_filter_mode_t *pinFilterMode); /*! * @brief Gets the filter detect flag. * * This function will get the filter detect flag. * * @param baseAddr Register base address of LLWU * @param filterNumber filter number specified * @return flag true if the filter was a wakeup source */ bool LLWU_HAL_GetFilterDetectFlag(uint32_t baseAddr, uint32_t filterNumber); /*! * @brief Clears the filter detect flag. * * This function will clear the filter detect flag. * * @param baseAddr Register base address of LLWU * @param filterNumber filter number specified */ void LLWU_HAL_ClearFilterDetectFlag(uint32_t baseAddr, uint32_t filterNumber); #if FSL_FEATURE_LLWU_HAS_RESET_ENABLE /*! * @brief Sets the reset enable mode. * * This function will set the reset enable mode. * * @param baseAddr Register base address of LLWU * @param resetEnableMode reset enable mode defined in llwu_reset_enable_mode_t */ void LLWU_HAL_SetResetEnableMode(uint32_t baseAddr, llwu_reset_enable_mode_t resetEnableMode); /*! * @brief Gets the reset enable mode. * * This function gets the reset enable mode. * * @param baseAddr Register base address of LLWU * @param resetEnableMode reset enable mode defined in llwu_reset_enable_mode_t */ void LLWU_HAL_GetResetEnableMode(uint32_t baseAddr, llwu_reset_enable_mode_t *resetEnableMode); #endif #if defined(__cplusplus) extern "C" { #endif /* __cplusplus*/ /*! @name Low-Leakage Wakeup Unit Control APIs*/ /*@{*/ /*@}*/ #if defined(__cplusplus) } #endif /* __cplusplus*/ /*! @}*/ #endif /* __FSL_LLWU_HAL_H__*/ /******************************************************************************* * EOF ******************************************************************************/ ================================================ FILE: Zelig/mbed/TARGET_K64F/TARGET_Freescale/TARGET_KPSDK_MCUS/TARGET_KPSDK_CODE/hal/lptmr/fsl_lptmr_features.h ================================================ /* ** ################################################################### ** Version: rev. 1.0, 2014-05-14 ** Build: b140515 ** ** Abstract: ** Chip specific module features. ** ** Copyright: 2014 Freescale Semiconductor, Inc. ** All rights reserved. ** ** Redistribution and use in source and binary forms, with or without modification, ** are permitted provided that the following conditions are met: ** ** o Redistributions of source code must retain the above copyright notice, this list ** of conditions and the following disclaimer. ** ** o Redistributions in binary form must reproduce the above copyright notice, this ** list of conditions and the following disclaimer in the documentation and/or ** other materials provided with the distribution. ** ** o Neither the name of Freescale Semiconductor, Inc. nor the names of its ** contributors may be used to endorse or promote products derived from this ** software without specific prior written permission. ** ** THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ** ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED ** WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE ** DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT 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. ** ** http: www.freescale.com ** mail: support@freescale.com ** ** Revisions: ** - rev. 1.0 (2014-05-14) ** Customer release. ** ** ################################################################### */ #if !defined(__FSL_LPTMR_FEATURES_H__) #define __FSL_LPTMR_FEATURES_H__ #if defined(CPU_MK02FN128VFM10) || defined(CPU_MK02FN64VFM10) || defined(CPU_MK02FN128VLF10) || defined(CPU_MK02FN64VLF10) || \ defined(CPU_MK02FN128VLH10) || defined(CPU_MK02FN64VLH10) || defined(CPU_MK22FN128VDC10) || defined(CPU_MK22FN128VLH10) || \ defined(CPU_MK22FN128VLL10) || defined(CPU_MK22FN128VMP10) || defined(CPU_MK22FN256VDC12) || defined(CPU_MK22FN256VLH12) || \ defined(CPU_MK22FN256VLL12) || defined(CPU_MK22FN256VMP12) || defined(CPU_MK22FN512VDC12) || defined(CPU_MK22FN512VLH12) || \ defined(CPU_MK22FN512VLL12) || defined(CPU_MK24FN1M0VDC12) || defined(CPU_MK24FN1M0VLL12) || defined(CPU_MK24FN1M0VLQ12) || \ defined(CPU_MK24FN256VDC12) || defined(CPU_MK63FN1M0VLQ12) || defined(CPU_MK63FN1M0VMD12) || defined(CPU_MK64FX512VDC12) || \ defined(CPU_MK64FN1M0VDC12) || defined(CPU_MK64FX512VLL12) || defined(CPU_MK64FN1M0VLL12) || defined(CPU_MK64FX512VLQ12) || \ defined(CPU_MK64FN1M0VLQ12) || defined(CPU_MK64FX512VMD12) || defined(CPU_MK64FN1M0VMD12) || defined(CPU_MK65FN2M0CAC18) || \ defined(CPU_MK65FX1M0CAC18) || defined(CPU_MK65FN2M0VMI18) || defined(CPU_MK65FX1M0VMI18) || defined(CPU_MK66FN2M0VLQ18) || \ defined(CPU_MK66FX1M0VLQ18) || defined(CPU_MK66FN2M0VMD18) || defined(CPU_MK66FX1M0VMD18) || defined(CPU_MKL03Z32CAF4) || \ defined(CPU_MKL03Z8VFG4) || defined(CPU_MKL03Z16VFG4) || defined(CPU_MKL03Z32VFG4) || defined(CPU_MKL03Z8VFK4) || \ defined(CPU_MKL03Z16VFK4) || defined(CPU_MKL03Z32VFK4) || defined(CPU_MKL13Z64VFM4) || defined(CPU_MKL13Z128VFM4) || \ defined(CPU_MKL13Z256VFM4) || defined(CPU_MKL13Z64VFT4) || defined(CPU_MKL13Z128VFT4) || defined(CPU_MKL13Z256VFT4) || \ defined(CPU_MKL13Z64VLH4) || defined(CPU_MKL13Z128VLH4) || defined(CPU_MKL13Z256VLH4) || defined(CPU_MKL13Z64VMP4) || \ defined(CPU_MKL13Z128VMP4) || defined(CPU_MKL13Z256VMP4) || defined(CPU_MKL23Z64VFM4) || defined(CPU_MKL23Z128VFM4) || \ defined(CPU_MKL23Z256VFM4) || defined(CPU_MKL23Z64VFT4) || defined(CPU_MKL23Z128VFT4) || defined(CPU_MKL23Z256VFT4) || \ defined(CPU_MKL23Z64VLH4) || defined(CPU_MKL23Z128VLH4) || defined(CPU_MKL23Z256VLH4) || defined(CPU_MKL23Z64VMP4) || \ defined(CPU_MKL23Z128VMP4) || defined(CPU_MKL23Z256VMP4) || defined(CPU_MKL33Z128VLH4) || defined(CPU_MKL33Z256VLH4) || \ defined(CPU_MKL33Z128VMP4) || defined(CPU_MKL33Z256VMP4) || defined(CPU_MKL43Z64VLH4) || defined(CPU_MKL43Z128VLH4) || \ defined(CPU_MKL43Z256VLH4) || defined(CPU_MKL43Z64VMP4) || defined(CPU_MKL43Z128VMP4) || defined(CPU_MKL43Z256VMP4) || \ defined(CPU_MKV30F128VFM10) || defined(CPU_MKV30F64VFM10) || defined(CPU_MKV30F128VLF10) || defined(CPU_MKV30F64VLF10) || \ defined(CPU_MKV30F128VLH10) || defined(CPU_MKV30F64VLH10) || defined(CPU_MKV31F128VLH10) || defined(CPU_MKV31F128VLL10) || \ defined(CPU_MKV31F256VLH12) || defined(CPU_MKV31F256VLL12) || defined(CPU_MKV31F512VLH12) || defined(CPU_MKV31F512VLL12) || \ defined(CPU_MKV40F128VLH15) || defined(CPU_MKV40F128VLL15) || defined(CPU_MKV40F256VLH15) || defined(CPU_MKV40F256VLL15) || \ defined(CPU_MKV40F64VLH15) || defined(CPU_MKV43F128VLH15) || defined(CPU_MKV43F128VLL15) || defined(CPU_MKV43F64VLH15) || \ defined(CPU_MKV44F128VLH15) || defined(CPU_MKV44F128VLL15) || defined(CPU_MKV44F64VLH15) || defined(CPU_MKV45F128VLH15) || \ defined(CPU_MKV45F128VLL15) || defined(CPU_MKV45F256VLH15) || defined(CPU_MKV45F256VLL15) || defined(CPU_MKV46F128VLH15) || \ defined(CPU_MKV46F128VLL15) || defined(CPU_MKV46F256VLH15) || defined(CPU_MKV46F256VLL15) || defined(CPU_MKL25Z128VLK4) #else #error "No valid CPU defined!" #endif #endif /* __FSL_LPTMR_FEATURES_H__ */ /******************************************************************************* * EOF ******************************************************************************/ ================================================ FILE: Zelig/mbed/TARGET_K64F/TARGET_Freescale/TARGET_KPSDK_MCUS/TARGET_KPSDK_CODE/hal/lptmr/fsl_lptmr_hal.h ================================================ /* * Copyright (c) 2013 - 2014, Freescale Semiconductor, Inc. * All rights reserved. * * Redistribution and use in source and binary forms, with or without modification, * are permitted provided that the following conditions are met: * * o Redistributions of source code must retain the above copyright notice, this list * of conditions and the following disclaimer. * * o Redistributions in binary form must reproduce the above copyright notice, this * list of conditions and the following disclaimer in the documentation and/or * other materials provided with the distribution. * * o Neither the name of Freescale Semiconductor, Inc. nor the names of its * contributors may be used to endorse or promote products derived from this * software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT 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. */ #ifndef __FSL_LPTMR_HAL_H__ #define __FSL_LPTMR_HAL_H__ #include #include #include #include "fsl_lptmr_features.h" #include "fsl_device_registers.h" /*! * @addtogroup lptmr_hal * @{ */ /******************************************************************************* * Definitions *******************************************************************************/ /*! @brief LPTMR pin selection.*/ typedef enum _lptmr_pin_select{ kLptmrPinSelectCmpOut = 0x0U, /*!< Lptmr Pin is CMP0 output pin.*/ kLptmrPinSelectLptmrAlt1 = 0x1U, /*!< Lptmr Pin is LPTMR_ALT1 pin.*/ kLptmrPinSelectLptmrAlt2 = 0x2U, /*!< Lptmr Pin is LPTMR_ALT2 pin.*/ kLptmrPinSelectLptmrAlt3 = 0x3U /*!< Lptmr Pin is LPTMR_ALT3 pin.*/ } lptmr_pin_select_t; /*! @brief LPTMR pin polarity, used while in pluse counter mode.*/ typedef enum _lptmr_pin_polarity{ kLptmrPinPolarityActiveHigh = 0x0U, /*!< Pulse Counter input source is active-high.*/ kLptmrPinPolarityActiveLow = 0x1U /*!< Pulse Counter input source is active-low.*/ } lptmr_pin_polarity_t; /*! @brief LPTMR timer mode selection.*/ typedef enum _lptmr_timer_mode{ kLptmrTimerModeTimeCounter = 0x0U, /*!< Time Counter mode.*/ kLptmrTimerModePluseCounter = 0x1U /*!< Pulse Counter mode.*/ } lptmr_timer_mode_t; /*! @brief LPTMR proscaler value.*/ typedef enum _lptmr_prescaler_value{ kLptmrPrescalerDivide2 = 0x0U, /*!< Prescaler divide 2, glitch filter invalid.*/ kLptmrPrescalerDivide4GlichFiltch2 = 0x1U, /*!< Prescaler divide 4, glitch filter 2.*/ kLptmrPrescalerDivide8GlichFiltch4 = 0x2U, /*!< Prescaler divide 8, glitch filter 4.*/ kLptmrPrescalerDivide16GlichFiltch8 = 0x3U, /*!< Prescaler divide 16, glitch filter 8.*/ kLptmrPrescalerDivide32GlichFiltch16 = 0x4U, /*!< Prescaler divide 32, glitch filter 16.*/ kLptmrPrescalerDivide64GlichFiltch32 = 0x5U, /*!< Prescaler divide 64, glitch filter 32.*/ kLptmrPrescalerDivide128GlichFiltch64 = 0x6U, /*!< Prescaler divide 128, glitch filter 64.*/ kLptmrPrescalerDivide256GlichFiltch128 = 0x7U, /*!< Prescaler divide 256, glitch filter 128.*/ kLptmrPrescalerDivide512GlichFiltch256 = 0x8U, /*!< Prescaler divide 512, glitch filter 256.*/ kLptmrPrescalerDivide1024GlichFiltch512 = 0x9U, /*!< Prescaler divide 1024, glitch filter 512.*/ kLptmrPrescalerDivide2048lichFiltch1024 = 0xAU, /*!< Prescaler divide 2048 glitch filter 1024.*/ kLptmrPrescalerDivide4096GlichFiltch2048 = 0xBU, /*!< Prescaler divide 4096, glitch filter 2048.*/ kLptmrPrescalerDivide8192GlichFiltch4096 = 0xCU, /*!< Prescaler divide 8192, glitch filter 4096.*/ kLptmrPrescalerDivide16384GlichFiltch8192 = 0xDU, /*!< Prescaler divide 16384, glitch filter 8192.*/ kLptmrPrescalerDivide32768GlichFiltch16384 = 0xEU, /*!< Prescaler divide 32768, glitch filter 16384.*/ kLptmrPrescalerDivide65535GlichFiltch32768 = 0xFU /*!< Prescaler divide 65535, glitch filter 32768.*/ } lptmr_prescaler_value_t; /*! @brief LPTMR clock source selection.*/ typedef enum _lptmr_prescaler_clock_source{ kLptmrPrescalerClockSourceMcgIrcClk = 0x0U, /*!< Clock source is MCGIRCLK.*/ kLptmrPrescalerClockSourceLpo = 0x1U, /*!< Clock source is LPO.*/ kLptmrPrescalerClockSourceErClk32K = 0x2U, /*!< Clock source is ERCLK32K.*/ kLptmrPrescalerClockSourceOscErClk = 0x3U /*!< Clock source is OSCERCLK.*/ } lptmr_prescaler_clock_source_t; /*! @brief LPTMR status return codes.*/ typedef enum _lptmr_status { kStatus_LPTMR_Success = 0x0U, /*!< Succeed. */ kStatus_LPTMR_NotInitlialized = 0x1U, /*!< LPTMR is not initialized yet. */ kStatus_LPTMR_NullArgument = 0x2U, /*!< Argument is NULL.*/ kStatus_LPTMR_InvalidPrescalerValue = 0x3U, /*!< Value 0 is not valid in pulse counter mode. */ kStatus_LPTMR_InvalidInTimeCounterMode = 0x4U, /*!< Function can not called in time counter mode. */ kStatus_LPTMR_InvalidInPluseCounterMode = 0x5U, /*!< Function can not called in pulse counter mode. */ kStatus_LPTMR_InvalidPlusePeriodCount = 0x6U, /*!< Pulse period count must be integer multiples of the glitch filter divider. */ kStatus_LPTMR_TcfNotSet = 0x7U, /*!< If LPTMR is enabled, compare register can only altered when TCF is set. */ kStatus_LPTMR_TimerPeriodUsTooSmall = 0x8U, /*!< Timer period time is too small for current clock source. */ kStatus_LPTMR_TimerPeriodUsTooLarge = 0x9U /*!< Timer period time is too large for current clock source. */ } lptmr_status_t; /******************************************************************************* ** Variables *******************************************************************************/ /******************************************************************************* * API *******************************************************************************/ #if defined(__cplusplus) extern "C" { #endif /*! * @name LPTMR HAL. * @{ */ /*! * @brief Enables the LPTMR module operation. * * @param baseAddr The LPTMR peripheral base address. */ static inline void LPTMR_HAL_Enable(uint32_t baseAddr) { BW_LPTMR_CSR_TEN(baseAddr, (uint8_t)true); } /*! * @brief Disables the LPTMR module operation. * * @param baseAddr The LPTMR peripheral base address. */ static inline void LPTMR_HAL_Disable(uint32_t baseAddr) { BW_LPTMR_CSR_TEN(baseAddr, (uint8_t)false); } /*! * @brief Checks whether the LPTMR module is enabled. * * @param baseAddr The LPTMR peripheral base address. * @retval true LPTMR module is enabled. * @retval false LPTMR module is disabled. */ static inline bool LPTMR_HAL_IsEnabled(uint32_t baseAddr) { return (bool)BR_LPTMR_CSR_TEN(baseAddr); } /*! * @brief Clears the LPTMR interrupt flag if set. * * @param baseAddr The LPTMR peripheral base address. */ static inline void LPTMR_HAL_ClearIntFlag(uint32_t baseAddr) { BW_LPTMR_CSR_TCF(baseAddr, 1); } /*! * @brief Returns the current LPTMR interrupt flag. * * @param baseAddr The LPTMR peripheral base address * @retval true An interrupt is pending. * @retval false No interrupt is pending. */ static inline bool LPTMR_HAL_IsIntPending(uint32_t baseAddr) { return ((bool)BR_LPTMR_CSR_TCF(baseAddr)); } /*! * @brief Enables or disables the LPTMR interrupt. * * @param baseAddr The LPTMR peripheral base address * @param enable Pass true to enable LPTMR interrupt */ static inline void LPTMR_HAL_SetIntCmd(uint32_t baseAddr, bool enable) { BW_LPTMR_CSR_TIE(baseAddr, (uint8_t)enable); } /*! * @brief Returns whether the LPTMR interrupt is enabled. * * @param baseAddr The LPTMR peripheral base address. * @retval true LPTMR interrupt is enabled. * @retval false LPTMR interrupt is disabled. */ static inline bool LPTMR_HAL_GetIntCmd(uint32_t baseAddr) { return ((bool)BR_LPTMR_CSR_TIE(baseAddr)); } /*! * @brief Selects the LPTMR pulse input pin select. * * @param baseAddr The LPTMR peripheral base address. * @param pinSelect Specifies LPTMR pulse input pin select, see #lptmr_pin_select_t */ static inline void LPTMR_HAL_SetPinSelectMode(uint32_t baseAddr, lptmr_pin_select_t pinSelect) { BW_LPTMR_CSR_TPS(baseAddr, (uint8_t)pinSelect); } /*! * @brief Returns the LPTMR pulse input pin select. * * @param baseAddr The LPTMR peripheral base address. * @return LPTMR pulse input pin select, see #lptmr_pin_select_t */ static inline lptmr_pin_select_t LPTMR_HAL_GetPinSelectMode(uint32_t baseAddr) { return (lptmr_pin_select_t)BR_LPTMR_CSR_TPS(baseAddr); } /*! * @brief Selects the LPTMR pulse input pin polarity. * * @param baseAddr The LPTMR peripheral base address. * @param pinPolarity Specifies LPTMR pulse input pin polarity, see #lptmr_pin_polarity_t */ static inline void LPTMR_HAL_SetPinPolarityMode(uint32_t baseAddr, lptmr_pin_polarity_t pinPolarity) { BW_LPTMR_CSR_TPP(baseAddr, (uint8_t)pinPolarity); } /*! * @brief Returns the LPTMR pulse input pin polarity. * * @param baseAddr The LPTMR peripheral base address. * @return LPTMR pulse input pin polarity, see #lptmr_pin_polarity_t */ static inline lptmr_pin_polarity_t LPTMR_HAL_GetPinPolarityMode(uint32_t baseAddr) { return (lptmr_pin_polarity_t)BR_LPTMR_CSR_TPP(baseAddr); } /*! * @brief Enables or disables the LPTMR free running. * * @param baseAddr The LPTMR peripheral base address * @param enable Pass true to enable LPTMR free running */ static inline void LPTMR_HAL_SetFreeRunningCmd(uint32_t baseAddr, bool enable) { BW_LPTMR_CSR_TFC(baseAddr, (uint8_t)enable); } /*! * @brief Returns whether the LPTMR free running is enabled. * * @param baseAddr The LPTMR peripheral base address. * @retval true LPTMR free running is enabled. * @retval false LPTMR free running is disabled. */ static inline bool LPTMR_HAL_GetFreeRunningCmd(uint32_t baseAddr) { return ((bool)BR_LPTMR_CSR_TFC(baseAddr)); } /*! * @brief Selects the LPTMR working mode. * * @param baseAddr The LPTMR peripheral base address. * @param timerMode Specifies LPTMR working mode, see #lptmr_timer_mode_t */ static inline void LPTMR_HAL_SetTimerModeMode(uint32_t baseAddr, lptmr_timer_mode_t timerMode) { BW_LPTMR_CSR_TMS(baseAddr, (uint8_t)timerMode); } /*! * @brief Returns the LPTMR working mode. * * @param baseAddr The LPTMR peripheral base address. * @return LPTMR working mode, see #lptmr_timer_mode_t */ static inline lptmr_timer_mode_t LPTMR_HAL_GetTimerModeMode(uint32_t baseAddr) { return (lptmr_timer_mode_t)BR_LPTMR_CSR_TMS(baseAddr); } /*! * @brief Selects the LPTMR prescaler value. * * @param baseAddr The LPTMR peripheral base address. * @param prescaleValue Specifies LPTMR prescaler value, see #lptmr_prescaler_value_t */ static inline void LPTMR_HAL_SetPrescalerValueMode(uint32_t baseAddr, lptmr_prescaler_value_t prescaleValue) { BW_LPTMR_PSR_PRESCALE(baseAddr, (uint8_t)prescaleValue); } /*! * @brief Returns the LPTMR prescaler value. * * @param baseAddr The LPTMR peripheral base address. * @return LPTMR prescaler value, see #lptmr_prescaler_value_t */ static inline lptmr_prescaler_value_t LPTMR_HAL_GetPrescalerValueMode(uint32_t baseAddr) { return (lptmr_prescaler_value_t)BR_LPTMR_PSR_PRESCALE(baseAddr); } /*! * @brief Enables or disables the LPTMR prescaler. * * @param baseAddr The LPTMR peripheral base address * @param enable Pass true to enable LPTMR free running */ static inline void LPTMR_HAL_SetPrescalerCmd(uint32_t baseAddr, bool enable) { BW_LPTMR_PSR_PBYP(baseAddr, (uint8_t)(enable == false)); /* 1 means disable prelsaler , 0 means enalbe prescaler */ } /*! * @brief Returns whether the LPTMR prescaler is enabled. * * @param baseAddr The LPTMR peripheral base address. * @retval true LPTMR prescaler is enabled. * @retval false LPTMR prescaler is disabled. */ static inline bool LPTMR_HAL_GetPrescalerCmd(uint32_t baseAddr) { return (bool)(0 == BR_LPTMR_PSR_PBYP(baseAddr)); /* 1 means prelsaler is disabled, 0 means prescaler is enalbed*/ } /*! * @brief Selects the LPTMR clock source. * * @param baseAddr The LPTMR peripheral base address. * @param prescalerClockSource Specifies LPTMR clock source, see #lptmr_prescaler_clock_source_t */ static inline void LPTMR_HAL_SetPrescalerClockSourceMode(uint32_t baseAddr, lptmr_prescaler_clock_source_t prescalerClockSource) { BW_LPTMR_PSR_PCS(baseAddr, (uint8_t)prescalerClockSource); } /*! * @brief Gets the LPTMR clock source. * * @param baseAddr The LPTMR peripheral base address. * @return LPTMR clock source, see #lptmr_prescaler_clock_source_t */ static inline lptmr_prescaler_clock_source_t LPTMR_HAL_GetPrescalerClockSourceMode(uint32_t baseAddr) { return (lptmr_prescaler_clock_source_t)BR_LPTMR_PSR_PCS(baseAddr); } /*! * @brief Sets the LPTMR compare value. * * @param baseAddr The LPTMR peripheral base address. * @param compareValue Specifies LPTMR compare value, less than 0xFFFFU */ static inline void LPTMR_HAL_SetCompareValue(uint32_t baseAddr, uint32_t compareValue) { BW_LPTMR_CMR_COMPARE(baseAddr, compareValue & 0xFFFFU); } /*! * @brief Gets the LPTMR compare value. * * @param baseAddr The LPTMR peripheral base address. * @return Current LPTMR compare value */ static inline uint32_t LPTMR_HAL_GetCompareValue(uint32_t baseAddr) { return (uint32_t)(BR_LPTMR_CMR_COMPARE(baseAddr) & 0xFFFFU); } /*! * @brief Gets the LPTMR counter value. * * @param baseAddr The LPTMR peripheral base address. * @return Current LPTMR counter value */ static inline uint32_t LPTMR_HAL_GetCounterValue(uint32_t baseAddr) { BW_LPTMR_CNR_COUNTER(baseAddr, 0); /* Must first write to the CNR with any value */ return (uint32_t)(BR_LPTMR_CNR_COUNTER(baseAddr) & 0xFFFFU); } /*! * @brief Restores the LPTMR module to reset state. * * @param baseAddr The LPTMR peripheral base address */ void LPTMR_HAL_Init(uint32_t baseAddr); /*@}*/ #if defined(__cplusplus) } #endif /*! @}*/ #endif /* __FSL_LPTMR_HAL_H__*/ /******************************************************************************* * EOF *******************************************************************************/ ================================================ FILE: Zelig/mbed/TARGET_K64F/TARGET_Freescale/TARGET_KPSDK_MCUS/TARGET_KPSDK_CODE/hal/lpuart/fsl_lpuart_features.h ================================================ /* ** ################################################################### ** Version: rev. 1.0, 2014-05-14 ** Build: b140515 ** ** Abstract: ** Chip specific module features. ** ** Copyright: 2014 Freescale Semiconductor, Inc. ** All rights reserved. ** ** Redistribution and use in source and binary forms, with or without modification, ** are permitted provided that the following conditions are met: ** ** o Redistributions of source code must retain the above copyright notice, this list ** of conditions and the following disclaimer. ** ** o Redistributions in binary form must reproduce the above copyright notice, this ** list of conditions and the following disclaimer in the documentation and/or ** other materials provided with the distribution. ** ** o Neither the name of Freescale Semiconductor, Inc. nor the names of its ** contributors may be used to endorse or promote products derived from this ** software without specific prior written permission. ** ** THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ** ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED ** WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE ** DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT 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. ** ** http: www.freescale.com ** mail: support@freescale.com ** ** Revisions: ** - rev. 1.0 (2014-05-14) ** Customer release. ** ** ################################################################### */ #if !defined(__FSL_LPUART_FEATURES_H__) #define __FSL_LPUART_FEATURES_H__ #if defined(CPU_MK22FN128VDC10) || defined(CPU_MK22FN128VLH10) || defined(CPU_MK22FN128VLL10) || defined(CPU_MK22FN128VMP10) || \ defined(CPU_MK22FN256VDC12) || defined(CPU_MK22FN256VLH12) || defined(CPU_MK22FN256VLL12) || defined(CPU_MK22FN256VMP12) || \ defined(CPU_MK22FN512VDC12) || defined(CPU_MK22FN512VLH12) || defined(CPU_MK22FN512VLL12) || defined(CPU_MK65FN2M0CAC18) || \ defined(CPU_MK65FX1M0CAC18) || defined(CPU_MK65FN2M0VMI18) || defined(CPU_MK65FX1M0VMI18) || defined(CPU_MK66FN2M0VLQ18) || \ defined(CPU_MK66FX1M0VLQ18) || defined(CPU_MK66FN2M0VMD18) || defined(CPU_MK66FX1M0VMD18) || defined(CPU_MKV31F128VLH10) || \ defined(CPU_MKV31F128VLL10) || defined(CPU_MKV31F256VLH12) || defined(CPU_MKV31F256VLL12) || defined(CPU_MKV31F512VLH12) || \ defined(CPU_MKV31F512VLL12) /* @brief Has receive FIFO overflow detection (bit field CFIFO[RXOFE]). */ #define FSL_FEATURE_LPUART_HAS_IRQ_EXTENDED_FUNCTIONS (1) /* @brief Has low power features (can be enabled in wait mode via register bit C1[DOZEEN] or CTRL[DOZEEN] if the registers are 32-bit wide). */ #define FSL_FEATURE_LPUART_HAS_LOW_POWER_UART_SUPPORT (1) /* @brief Has extended data register ED (or extra flags in the DATA register if the registers are 32-bit wide). */ #define FSL_FEATURE_LPUART_HAS_EXTENDED_DATA_REGISTER_FLAGS (1) /* @brief Capacity (number of entries) of the transmit/receive FIFO (or zero if no FIFO is available). */ #define FSL_FEATURE_LPUART_HAS_FIFO (0) /* @brief Hardware flow control (RTS, CTS) is supported. */ #define FSL_FEATURE_LPUART_HAS_MODEM_SUPPORT (1) /* @brief Infrared (modulation) is supported. */ #define FSL_FEATURE_LPUART_HAS_IR_SUPPORT (1) /* @brief 2 bits long stop bit is available. */ #define FSL_FEATURE_LPUART_HAS_STOP_BIT_CONFIG_SUPPORT (1) /* @brief Maximal data width without parity bit. */ #define FSL_FEATURE_LPUART_HAS_10BIT_DATA_SUPPORT (1) /* @brief Baud rate fine adjustment is available. */ #define FSL_FEATURE_LPUART_HAS_BAUD_RATE_FINE_ADJUST_SUPPORT (0) /* @brief Baud rate oversampling is available (has bit fields C4[OSR], C5[BOTHEDGE], C5[RESYNCDIS] or BAUD[OSR], BAUD[BOTHEDGE], BAUD[RESYNCDIS] if the registers are 32-bit wide). */ #define FSL_FEATURE_LPUART_HAS_BAUD_RATE_OVER_SAMPLING_SUPPORT (1) /* @brief Baud rate oversampling is available. */ #define FSL_FEATURE_LPUART_HAS_RX_RESYNC_SUPPORT (1) /* @brief Baud rate oversampling is available. */ #define FSL_FEATURE_LPUART_HAS_BOTH_EDGE_SAMPLING_SUPPORT (1) /* @brief Peripheral type. */ #define FSL_FEATURE_LPUART_IS_SCI (1) /* @brief Capacity (number of entries) of the transmit/receive FIFO (or zero if no FIFO is available). */ #define FSL_FEATURE_LPUART_FIFO_SIZE (0) /* @brief Maximal data width without parity bit. */ #define FSL_FEATURE_LPUART_MAX_DATA_WIDTH_WITH_NO_PARITY (10) /* @brief Maximal data width with parity bit. */ #define FSL_FEATURE_LPUART_MAX_DATA_WIDTH_WITH_PARITY (9) /* @brief Supports two match addresses to filter incoming frames. */ #define FSL_FEATURE_LPUART_HAS_ADDRESS_MATCHING (1) /* @brief Has transmitter/receiver DMA enable bits C5[TDMAE]/C5[RDMAE] (or BAUD[TDMAE]/BAUD[RDMAE] if the registers are 32-bit wide). */ #define FSL_FEATURE_LPUART_HAS_DMA_ENABLE (1) /* @brief Has transmitter/receiver DMA select bits C4[TDMAS]/C4[RDMAS], resp. C5[TDMAS]/C5[RDMAS] if IS_SCI = 0. */ #define FSL_FEATURE_LPUART_HAS_DMA_SELECT (0) /* @brief Data character bit order selection is supported (bit field S2[MSBF] or STAT[MSBF] if the registers are 32-bit wide). */ #define FSL_FEATURE_LPUART_HAS_BIT_ORDER_SELECT (1) /* @brief Has smart card (ISO7816 protocol) support and no improved smart card support. */ #define FSL_FEATURE_LPUART_HAS_SMART_CARD_SUPPORT (0) /* @brief Has improved smart card (ISO7816 protocol) support. */ #define FSL_FEATURE_LPUART_HAS_IMPROVED_SMART_CARD_SUPPORT (0) /* @brief Has local operation network (CEA709.1-B protocol) support. */ #define FSL_FEATURE_LPUART_HAS_LOCAL_OPERATION_NETWORK_SUPPORT (0) /* @brief Has 32-bit registers (BAUD, STAT, CTRL, DATA, MATCH, MODIR) instead of 8-bit (BDH, BDL, C1, S1, D, etc.). */ #define FSL_FEATURE_LPUART_HAS_32BIT_REGISTERS (1) #elif defined(CPU_MKL03Z32CAF4) || defined(CPU_MKL03Z8VFG4) || defined(CPU_MKL03Z16VFG4) || defined(CPU_MKL03Z32VFG4) || \ defined(CPU_MKL03Z8VFK4) || defined(CPU_MKL03Z16VFK4) || defined(CPU_MKL03Z32VFK4) /* @brief Has receive FIFO overflow detection (bit field CFIFO[RXOFE]). */ #define FSL_FEATURE_LPUART_HAS_IRQ_EXTENDED_FUNCTIONS (1) /* @brief Has low power features (can be enabled in wait mode via register bit C1[DOZEEN] or CTRL[DOZEEN] if the registers are 32-bit wide). */ #define FSL_FEATURE_LPUART_HAS_LOW_POWER_UART_SUPPORT (1) /* @brief Has extended data register ED (or extra flags in the DATA register if the registers are 32-bit wide). */ #define FSL_FEATURE_LPUART_HAS_EXTENDED_DATA_REGISTER_FLAGS (1) /* @brief Capacity (number of entries) of the transmit/receive FIFO (or zero if no FIFO is available). */ #define FSL_FEATURE_LPUART_HAS_FIFO (0) /* @brief Hardware flow control (RTS, CTS) is supported. */ #define FSL_FEATURE_LPUART_HAS_MODEM_SUPPORT (0) /* @brief Infrared (modulation) is supported. */ #define FSL_FEATURE_LPUART_HAS_IR_SUPPORT (0) /* @brief 2 bits long stop bit is available. */ #define FSL_FEATURE_LPUART_HAS_STOP_BIT_CONFIG_SUPPORT (1) /* @brief Maximal data width without parity bit. */ #define FSL_FEATURE_LPUART_HAS_10BIT_DATA_SUPPORT (1) /* @brief Baud rate fine adjustment is available. */ #define FSL_FEATURE_LPUART_HAS_BAUD_RATE_FINE_ADJUST_SUPPORT (0) /* @brief Baud rate oversampling is available (has bit fields C4[OSR], C5[BOTHEDGE], C5[RESYNCDIS] or BAUD[OSR], BAUD[BOTHEDGE], BAUD[RESYNCDIS] if the registers are 32-bit wide). */ #define FSL_FEATURE_LPUART_HAS_BAUD_RATE_OVER_SAMPLING_SUPPORT (1) /* @brief Baud rate oversampling is available. */ #define FSL_FEATURE_LPUART_HAS_RX_RESYNC_SUPPORT (1) /* @brief Baud rate oversampling is available. */ #define FSL_FEATURE_LPUART_HAS_BOTH_EDGE_SAMPLING_SUPPORT (1) /* @brief Peripheral type. */ #define FSL_FEATURE_LPUART_IS_SCI (1) /* @brief Capacity (number of entries) of the transmit/receive FIFO (or zero if no FIFO is available). */ #define FSL_FEATURE_LPUART_FIFO_SIZE (0) /* @brief Maximal data width without parity bit. */ #define FSL_FEATURE_LPUART_MAX_DATA_WIDTH_WITH_NO_PARITY (10) /* @brief Maximal data width with parity bit. */ #define FSL_FEATURE_LPUART_MAX_DATA_WIDTH_WITH_PARITY (9) /* @brief Supports two match addresses to filter incoming frames. */ #define FSL_FEATURE_LPUART_HAS_ADDRESS_MATCHING (1) /* @brief Has transmitter/receiver DMA enable bits C5[TDMAE]/C5[RDMAE] (or BAUD[TDMAE]/BAUD[RDMAE] if the registers are 32-bit wide). */ #define FSL_FEATURE_LPUART_HAS_DMA_ENABLE (0) /* @brief Has transmitter/receiver DMA select bits C4[TDMAS]/C4[RDMAS], resp. C5[TDMAS]/C5[RDMAS] if IS_SCI = 0. */ #define FSL_FEATURE_LPUART_HAS_DMA_SELECT (0) /* @brief Data character bit order selection is supported (bit field S2[MSBF] or STAT[MSBF] if the registers are 32-bit wide). */ #define FSL_FEATURE_LPUART_HAS_BIT_ORDER_SELECT (1) /* @brief Has smart card (ISO7816 protocol) support and no improved smart card support. */ #define FSL_FEATURE_LPUART_HAS_SMART_CARD_SUPPORT (0) /* @brief Has improved smart card (ISO7816 protocol) support. */ #define FSL_FEATURE_LPUART_HAS_IMPROVED_SMART_CARD_SUPPORT (0) /* @brief Has local operation network (CEA709.1-B protocol) support. */ #define FSL_FEATURE_LPUART_HAS_LOCAL_OPERATION_NETWORK_SUPPORT (0) /* @brief Has 32-bit registers (BAUD, STAT, CTRL, DATA, MATCH, MODIR) instead of 8-bit (BDH, BDL, C1, S1, D, etc.). */ #define FSL_FEATURE_LPUART_HAS_32BIT_REGISTERS (1) #elif defined(CPU_MKL13Z64VFM4) || defined(CPU_MKL13Z128VFM4) || defined(CPU_MKL13Z256VFM4) || defined(CPU_MKL13Z64VFT4) || \ defined(CPU_MKL13Z128VFT4) || defined(CPU_MKL13Z256VFT4) || defined(CPU_MKL13Z64VLH4) || defined(CPU_MKL13Z128VLH4) || \ defined(CPU_MKL13Z256VLH4) || defined(CPU_MKL13Z64VMP4) || defined(CPU_MKL13Z128VMP4) || defined(CPU_MKL13Z256VMP4) || \ defined(CPU_MKL23Z64VFM4) || defined(CPU_MKL23Z128VFM4) || defined(CPU_MKL23Z256VFM4) || defined(CPU_MKL23Z64VFT4) || \ defined(CPU_MKL23Z128VFT4) || defined(CPU_MKL23Z256VFT4) || defined(CPU_MKL23Z64VLH4) || defined(CPU_MKL23Z128VLH4) || \ defined(CPU_MKL23Z256VLH4) || defined(CPU_MKL23Z64VMP4) || defined(CPU_MKL23Z128VMP4) || defined(CPU_MKL23Z256VMP4) || \ defined(CPU_MKL33Z128VLH4) || defined(CPU_MKL33Z256VLH4) || defined(CPU_MKL33Z128VMP4) || defined(CPU_MKL33Z256VMP4) || \ defined(CPU_MKL43Z64VLH4) || defined(CPU_MKL43Z128VLH4) || defined(CPU_MKL43Z256VLH4) || defined(CPU_MKL43Z64VMP4) || \ defined(CPU_MKL43Z128VMP4) || defined(CPU_MKL43Z256VMP4) /* @brief Has receive FIFO overflow detection (bit field CFIFO[RXOFE]). */ #define FSL_FEATURE_LPUART_HAS_IRQ_EXTENDED_FUNCTIONS (1) /* @brief Has low power features (can be enabled in wait mode via register bit C1[DOZEEN] or CTRL[DOZEEN] if the registers are 32-bit wide). */ #define FSL_FEATURE_LPUART_HAS_LOW_POWER_UART_SUPPORT (1) /* @brief Has extended data register ED (or extra flags in the DATA register if the registers are 32-bit wide). */ #define FSL_FEATURE_LPUART_HAS_EXTENDED_DATA_REGISTER_FLAGS (1) /* @brief Capacity (number of entries) of the transmit/receive FIFO (or zero if no FIFO is available). */ #define FSL_FEATURE_LPUART_HAS_FIFO (0) /* @brief Hardware flow control (RTS, CTS) is supported. */ #define FSL_FEATURE_LPUART_HAS_MODEM_SUPPORT (0) /* @brief Infrared (modulation) is supported. */ #define FSL_FEATURE_LPUART_HAS_IR_SUPPORT (0) /* @brief 2 bits long stop bit is available. */ #define FSL_FEATURE_LPUART_HAS_STOP_BIT_CONFIG_SUPPORT (1) /* @brief Maximal data width without parity bit. */ #define FSL_FEATURE_LPUART_HAS_10BIT_DATA_SUPPORT (1) /* @brief Baud rate fine adjustment is available. */ #define FSL_FEATURE_LPUART_HAS_BAUD_RATE_FINE_ADJUST_SUPPORT (0) /* @brief Baud rate oversampling is available (has bit fields C4[OSR], C5[BOTHEDGE], C5[RESYNCDIS] or BAUD[OSR], BAUD[BOTHEDGE], BAUD[RESYNCDIS] if the registers are 32-bit wide). */ #define FSL_FEATURE_LPUART_HAS_BAUD_RATE_OVER_SAMPLING_SUPPORT (1) /* @brief Baud rate oversampling is available. */ #define FSL_FEATURE_LPUART_HAS_RX_RESYNC_SUPPORT (1) /* @brief Baud rate oversampling is available. */ #define FSL_FEATURE_LPUART_HAS_BOTH_EDGE_SAMPLING_SUPPORT (1) /* @brief Peripheral type. */ #define FSL_FEATURE_LPUART_IS_SCI (1) /* @brief Capacity (number of entries) of the transmit/receive FIFO (or zero if no FIFO is available). */ #define FSL_FEATURE_LPUART_FIFO_SIZE (0) /* @brief Maximal data width without parity bit. */ #define FSL_FEATURE_LPUART_MAX_DATA_WIDTH_WITH_NO_PARITY (10) /* @brief Maximal data width with parity bit. */ #define FSL_FEATURE_LPUART_MAX_DATA_WIDTH_WITH_PARITY (9) /* @brief Supports two match addresses to filter incoming frames. */ #define FSL_FEATURE_LPUART_HAS_ADDRESS_MATCHING (1) /* @brief Has transmitter/receiver DMA enable bits C5[TDMAE]/C5[RDMAE] (or BAUD[TDMAE]/BAUD[RDMAE] if the registers are 32-bit wide). */ #define FSL_FEATURE_LPUART_HAS_DMA_ENABLE (1) /* @brief Has transmitter/receiver DMA select bits C4[TDMAS]/C4[RDMAS], resp. C5[TDMAS]/C5[RDMAS] if IS_SCI = 0. */ #define FSL_FEATURE_LPUART_HAS_DMA_SELECT (0) /* @brief Data character bit order selection is supported (bit field S2[MSBF] or STAT[MSBF] if the registers are 32-bit wide). */ #define FSL_FEATURE_LPUART_HAS_BIT_ORDER_SELECT (1) /* @brief Has smart card (ISO7816 protocol) support and no improved smart card support. */ #define FSL_FEATURE_LPUART_HAS_SMART_CARD_SUPPORT (0) /* @brief Has improved smart card (ISO7816 protocol) support. */ #define FSL_FEATURE_LPUART_HAS_IMPROVED_SMART_CARD_SUPPORT (0) /* @brief Has local operation network (CEA709.1-B protocol) support. */ #define FSL_FEATURE_LPUART_HAS_LOCAL_OPERATION_NETWORK_SUPPORT (0) /* @brief Has 32-bit registers (BAUD, STAT, CTRL, DATA, MATCH, MODIR) instead of 8-bit (BDH, BDL, C1, S1, D, etc.). */ #define FSL_FEATURE_LPUART_HAS_32BIT_REGISTERS (1) #else #define MBED_NO_LPUART #endif #endif /* __FSL_LPUART_FEATURES_H__ */ /******************************************************************************* * EOF ******************************************************************************/ ================================================ FILE: Zelig/mbed/TARGET_K64F/TARGET_Freescale/TARGET_KPSDK_MCUS/TARGET_KPSDK_CODE/hal/lpuart/fsl_lpuart_hal.h ================================================ /* * Copyright (c) 2013 - 2014, Freescale Semiconductor, Inc. * All rights reserved. * * Redistribution and use in source and binary forms, with or without modification, * are permitted provided that the following conditions are met: * * o Redistributions of source code must retain the above copyright notice, this list * of conditions and the following disclaimer. * * o Redistributions in binary form must reproduce the above copyright notice, this * list of conditions and the following disclaimer in the documentation and/or * other materials provided with the distribution. * * o Neither the name of Freescale Semiconductor, Inc. nor the names of its * contributors may be used to endorse or promote products derived from this * software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT 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. */ #ifndef __FSL_LPUART_HAL_H__ #define __FSL_LPUART_HAL_H__ #include #include #include #include "fsl_lpuart_features.h" #include "fsl_device_registers.h" #ifndef MBED_NO_LPUART /*! * @addtogroup lpuart_hal * @{ */ /******************************************************************************* * Definitions ******************************************************************************/ #define LPUART_SHIFT (16U) #define LPUART_BAUD_REG_ID (0U) #define LPUART_STAT_REG_ID (1U) #define LPUART_CTRL_REG_ID (2U) #define LPUART_DATA_REG_ID (3U) #define LPUART_MATCH_REG_ID (4U) #define LPUART_MODIR_REG_ID (5U) /*! @brief Error codes for the LPUART driver.*/ typedef enum _lpuart_status { kStatus_LPUART_Success, kStatus_LPUART_BaudRateCalculationError , /*!< LPUART Baud Rate calculation error out of range. */ kStatus_LPUART_BaudRatePercentDiffExceeded, /*!< LPUART Baud Rate exceeds percentage difference*/ kStatus_LPUART_BitCountNotSupported, /*!< LPUART bit count configuration not supported.*/ kStatus_LPUART_StopBitCountNotSupported, /*!< LPUART stop bit count configuration not supported.*/ kStatus_LPUART_RxStandbyModeError, /*!< LPUART unable to place receiver in standby mode.*/ kStatus_LPUART_ClearStatusFlagError, /*!< LPUART clear status flag error.*/ kStatus_LPUART_MSBFirstNotSupported, /*!< LPUART MSB first feature not supported.*/ kStatus_LPUART_Resync_NotSupported, /*!< LPUART resync disable operation not supported.*/ kStatus_LPUART_TxNotDisabled, /*!< LPUART Transmitter not disabled before enabling feature*/ kStatus_LPUART_RxNotDisabled, /*!< LPUART Receiver not disabled before enabling feature*/ kStatus_LPUART_TxOrRxNotDisabled, /*!< LPUART Transmitter or Receiver not disabled*/ kStatus_LPUART_TxBusy, /*!< LPUART transmit still in progress.*/ kStatus_LPUART_RxBusy, /*!< LPUART receive still in progress.*/ kStatus_LPUART_NoTransmitInProgress, /*!< LPUART no transmit in progress.*/ kStatus_LPUART_NoReceiveInProgress, /*!< LPUART no receive in progress.*/ kStatus_LPUART_InvalidInstanceNumber, /*!< Invalid LPUART base address */ kStatus_LPUART_InvalidBitSetting, /*!< Invalid setting for desired LPUART register bit field */ kStatus_LPUART_OverSamplingNotSupported, /*!< LPUART oversampling not supported.*/ kStatus_LPUART_BothEdgeNotSupported, /*!< LPUART both edge sampling not supported. */ kStatus_LPUART_Timeout, /*!< LPUART transfer timed out.*/ kStatus_LPUART_Initialized, } lpuart_status_t; /*! @brief LPUART number of stop bits*/ typedef enum _lpuart_stop_bit_count { kLpuartOneStopBit = 0, /*!< one stop bit*/ kLpuartTwoStopBit = 1, /*!< two stop bits*/ } lpuart_stop_bit_count_t; /*! @brief LPUART parity mode*/ typedef enum _lpuart_parity_mode { kLpuartParityDisabled = 0x0, /*!< parity disabled*/ kLpuartParityEven = 0x2, /*!< parity enabled, type even, bit setting: PE|PT = 10*/ kLpuartParityOdd = 0x3, /*!< parity enabled, type odd, bit setting: PE|PT = 11*/ } lpuart_parity_mode_t; /*! @brief LPUART number of bits in a character*/ typedef enum _lpuart_bit_count_per_char { kLpuart8BitsPerChar = 0, /*!< 8-bit data characters*/ kLpuart9BitsPerChar = 1, /*!< 9-bit data characters*/ kLpuart10BitsPerChar = 2, /*!< 10-bit data characters*/ } lpuart_bit_count_per_char_t; /*! @brief LPUART operation configuration constants*/ typedef enum _lpuart_operation_config { kLpuartOperates = 0,/*!< LPUART continues to operate normally.*/ kLpuartStops = 1, /*!< LPUART stops operation. */ } lpuart_operation_config_t; /*! @brief LPUART wakeup from standby method constants*/ typedef enum _lpuart_wakeup_method { kLpuartIdleLineWake = 0, /*!< Idle-line wakes the LPUART receiver from standby. */ kLpuartAddrMarkWake = 1, /*!< Addr-mark wakes LPUART receiver from standby.*/ } lpuart_wakeup_method_t; /*! @brief LPUART idle line detect selection types*/ typedef enum _lpuart_idle_line_select { kLpuartIdleLineAfterStartBit = 0, /*!< LPUART idle character bit count start after start bit */ kLpuartIdleLineAfterStopBit = 1, /*!< LPUART idle character bit count start after stop bit */ } lpuart_idle_line_select_t; /*! * @brief LPUART break character length settings for transmit/detect. * * The actual maximum bit times may vary depending on the LPUART instance. */ typedef enum _lpuart_break_char_length { kLpuartBreakChar10BitMinimum = 0, /*!< LPUART break char length 10 bit times (if M = 0, SBNS = 0) or 11 (if M = 1, SBNS = 0 or M = 0, SBNS = 1) or 12 (if M = 1, SBNS = 1 or M10 = 1, SNBS = 0) or 13 (if M10 = 1, SNBS = 1 .*/ kLpuartBreakChar13BitMinimum = 1, /*!< LPUART break char length 13 bit times (if M = 0, SBNS = 0) or 14 (if M = 1, SBNS = 0 or M = 0, SBNS = 1) or 15 (if M = 1, SBNS = 1 or M10 = 1, SNBS = 0) or 16 (if M10 = 1, SNBS = 1)*/ } lpuart_break_char_length_t; /*! @brief LPUART single-wire mode TX direction*/ typedef enum _lpuart_singlewire_txdir { kLpuartSinglewireTxdirIn = 0, /*!< LPUART Single Wire mode TXDIR input*/ kLpuartSinglewireTxdirOut = 1, /*!< LPUART Single Wire mode TXDIR output*/ } lpuart_singlewire_txdir_t; /*! @brief LPUART Configures the match addressing mode used.*/ typedef enum _lpuart_match_config { kLpuartAddressMatchWakeup = 0, /*!< LPUART Address Match Wakeup*/ kLpuartIdleMatchWakeup = 1, /*!< LPUART Idle Match Wakeup*/ kLpuartMatchOnAndMatchOff = 2, /*!< LPUART Match On and Match Off*/ kLpuartEnablesRwuOnDataMatch = 3, /*!< LPUART Enables RWU on Data Match and Match On/Off for transmitter CTS input*/ } lpuart_match_config_t; /*! @brief LPUART infra-red transmitter pulse width options*/ typedef enum _lpuart_ir_tx_pulsewidth { kLpuartIrThreeSixteenthsWidth = 0, /*!< 3/16 pulse*/ kLpuartIrOneSixteenthWidth = 1, /*!< 1/16 pulse*/ kLpuartIrOneThirtysecondsWidth = 2, /*!< 1/32 pulse*/ kLpuartIrOneFourthWidth = 3, /*!< 1/4 pulse*/ } lpuart_ir_tx_pulsewidth_t; /*! @brief LPUART Configures the number of idle characters that must be received before the IDLE flag is set. */ typedef enum _lpuart_idle_config { kLpuart_1_IdleChar = 0, /*!< 1 idle character*/ kLpuart_2_IdleChar = 1, /*!< 2 idle character*/ kLpuart_4_IdleChar = 2, /*!< 4 idle character*/ kLpuart_8_IdleChar = 3, /*!< 8 idle character*/ kLpuart_16_IdleChar = 4, /*!< 16 idle character*/ kLpuart_32_IdleChar = 5, /*!< 32 idle character*/ kLpuart_64_IdleChar = 6, /*!< 64 idle character*/ kLpuart_128_IdleChar = 7, /*!< 128 idle character*/ } lpuart_idle_config_t; /*! @brief LPUART Transmits the CTS Configuration. Configures the source of the CTS input.*/ typedef enum _lpuart_cts_source { kLpuartCtsSourcePin = 0, /*!< LPUART CTS input is the LPUART_CTS pin.*/ kLpuartCtsSourceInvertedReceiverMatch = 1, /*!< LPUART CTS input is the inverted Receiver Match result.*/ } lpuart_cts_source_t; /*! @brief LPUART Transmits CTS Source.Configures if the CTS state is checked at the start of each character or only when the transmitter is idle.*/ typedef enum _lpuart_cts_config { kLpuartCtsSampledOnEachCharacter = 0, /*!< LPUART CTS input is sampled at the start of each character.*/ kLpuartCtsSampledOnIdle = 1, /*!< LPUART CTS input is sampled when the transmitter is idle.*/ } lpuart_cts_config_t; /*! @brief Structure for idle line configuration settings*/ typedef struct LpuartIdleLineConfig { unsigned idleLineType : 1; /*!< ILT, Idle bit count start: 0 - after start bit (default),*/ /*! 1 - after stop bit */ unsigned rxWakeIdleDetect : 1; /*!< RWUID, Receiver Wake Up Idle Detect. IDLE status bit */ /*! operation during receive standbyControls whether idle */ /*! character that wakes up receiver will also set */ /*! IDLE status bit 0 - IDLE status bit doesn't */ /*! get set (default), 1 - IDLE status bit gets set*/ } lpuart_idle_line_config_t; /*! * @brief LPUART status flags. * * This provides constants for the LPUART status flags for use in the UART functions. */ typedef enum _lpuart_status_flag { kLpuartTxDataRegEmpty = LPUART_STAT_REG_ID << LPUART_SHIFT | BP_LPUART_STAT_TDRE, /*!< Tx data register empty flag, sets when Tx buffer is empty */ kLpuartTxComplete = LPUART_STAT_REG_ID << LPUART_SHIFT | BP_LPUART_STAT_TC, /*!< Transmission complete flag, sets when transmission activity complete */ kLpuartRxDataRegFull = LPUART_STAT_REG_ID << LPUART_SHIFT | BP_LPUART_STAT_RDRF, /*!< Rx data register full flag, sets when the receive data buffer is full */ kLpuartIdleLineDetect = LPUART_STAT_REG_ID << LPUART_SHIFT | BP_LPUART_STAT_IDLE, /*!< Idle line detect flag, sets when idle line detected */ kLpuartRxOverrun = LPUART_STAT_REG_ID << LPUART_SHIFT | BP_LPUART_STAT_OR, /*!< Rxr Overrun, sets when new data is received before data is read from receive register */ kLpuartNoiseDetect = LPUART_STAT_REG_ID << LPUART_SHIFT | BP_LPUART_STAT_NF, /*!< Rxr takes 3 samples of each received bit. If any of these samples differ, noise flag sets */ kLpuartFrameErr = LPUART_STAT_REG_ID << LPUART_SHIFT | BP_LPUART_STAT_FE, /*!< Frame error flag, sets if logic 0 was detected where stop bit expected */ kLpuartParityErr = LPUART_STAT_REG_ID << LPUART_SHIFT | BP_LPUART_STAT_PF, /*!< If parity enabled, sets upon parity error detection */ kLpuartLineBreakDetect = LPUART_STAT_REG_ID << LPUART_SHIFT | BP_LPUART_STAT_LBKDE, /*!< LIN break detect interrupt flag, sets when LIN break char detected and LIN circuit enabled */ kLpuartRxActiveEdgeDetect = LPUART_STAT_REG_ID << LPUART_SHIFT | BP_LPUART_STAT_RXEDGIF, /*!< Rx pin active edge interrupt flag, sets when active edge detected */ kLpuartRxActive = LPUART_STAT_REG_ID << LPUART_SHIFT | BP_LPUART_STAT_RAF, /*!< Receiver Active Flag (RAF), sets at beginning of valid start bit */ #if FSL_FEATURE_LPUART_HAS_EXTENDED_DATA_REGISTER_FLAGS kLpuartNoiseInCurrentWord = LPUART_DATA_REG_ID << LPUART_SHIFT | BP_LPUART_DATA_NOISY, /*!< NOISY bit, sets if noise detected in current data word */ kLpuartParityErrInCurrentWord = LPUART_DATA_REG_ID << LPUART_SHIFT | BP_LPUART_DATA_PARITYE, /*!< PARITYE bit, sets if noise detected in current data word */ #endif #if FSL_FEATURE_LPUART_HAS_ADDRESS_MATCHING kLpuartMatchAddrOne = LPUART_STAT_REG_ID << LPUART_SHIFT | BP_LPUART_STAT_MA1F, /*!< Address one match flag */ kLpuartMatchAddrTwo = LPUART_STAT_REG_ID << LPUART_SHIFT | BP_LPUART_STAT_MA2F, /*!< Address two match flag */ #endif } lpuart_status_flag_t; /*! @brief LPUART interrupt configuration structure, default settings are 0 (disabled)*/ typedef enum _lpuart_interrupt { kLpuartIntLinBreakDetect = LPUART_BAUD_REG_ID << LPUART_SHIFT | BP_LPUART_BAUD_LBKDIE, /*!< LIN break detect. */ kLpuartIntRxActiveEdge = LPUART_BAUD_REG_ID << LPUART_SHIFT | BP_LPUART_BAUD_RXEDGIE, /*!< RX Active Edge. */ kLpuartIntTxDataRegEmpty = LPUART_CTRL_REG_ID << LPUART_SHIFT | BP_LPUART_CTRL_TIE, /*!< Transmit data register empty. */ kLpuartIntTxComplete = LPUART_CTRL_REG_ID << LPUART_SHIFT | BP_LPUART_CTRL_TCIE, /*!< Transmission complete. */ kLpuartIntRxDataRegFull = LPUART_CTRL_REG_ID << LPUART_SHIFT | BP_LPUART_CTRL_RIE, /*!< Receiver data register full. */ kLpuartIntIdleLine = LPUART_CTRL_REG_ID << LPUART_SHIFT | BP_LPUART_CTRL_ILIE, /*!< Idle line. */ kLpuartIntRxOverrun = LPUART_CTRL_REG_ID << LPUART_SHIFT | BP_LPUART_CTRL_ORIE, /*!< Receiver Overrun. */ kLpuartIntNoiseErrFlag = LPUART_CTRL_REG_ID << LPUART_SHIFT | BP_LPUART_CTRL_NEIE, /*!< Noise error flag. */ kLpuartIntFrameErrFlag = LPUART_CTRL_REG_ID << LPUART_SHIFT | BP_LPUART_CTRL_FEIE, /*!< Framing error flag. */ kLpuartIntParityErrFlag = LPUART_CTRL_REG_ID << LPUART_SHIFT | BP_LPUART_CTRL_PEIE, /*!< Parity error flag. */ #if FSL_FEATURE_LPUART_HAS_ADDRESS_MATCHING kLpuartIntMatchAddrOne = LPUART_CTRL_REG_ID << LPUART_SHIFT | BP_LPUART_CTRL_MA1IE, /*!< Match address one flag. */ kLpuartIntMatchAddrTwo = LPUART_CTRL_REG_ID << LPUART_SHIFT | BP_LPUART_CTRL_MA2IE, /*!< Match address two flag. */ #endif } lpuart_interrupt_t; /******************************************************************************* * API ******************************************************************************/ #if defined(__cplusplus) extern "C" { #endif /*! * @name LPUART Common Configurations * @{ */ /*! * @brief Initializes the LPUART controller to known state. * * @param baseAddr LPUART base address. */ void LPUART_HAL_Init(uint32_t baseAddr); /*! * @brief Enables the LPUART transmitter. * * @param baseAddr LPUART base address. */ void LPUART_HAL_EnableTransmitter(uint32_t baseAddr); /*! * @brief Disables the LPUART transmitter. * * @param baseAddr LPUART base address */ static inline void LPUART_HAL_DisableTransmitter(uint32_t baseAddr) { BW_LPUART_CTRL_TE(baseAddr, 0); } /*! * @brief Gets the LPUART transmitter enabled/disabled configuration. * * @param baseAddr LPUART base address * @return State of LPUART transmitter enable(1)/disable(0) */ static inline bool LPUART_HAL_IsTransmitterEnabled(uint32_t baseAddr) { return BR_LPUART_CTRL_TE(baseAddr); } /*! * @brief Enables the LPUART receiver. * * @param baseAddr LPUART base address */ static inline void LPUART_HAL_EnableReceiver(uint32_t baseAddr) { BW_LPUART_CTRL_RE(baseAddr, 1); } /*! * @brief Disables the LPUART receiver. * * @param baseAddr LPUART base address */ static inline void LPUART_HAL_DisableReceiver(uint32_t baseAddr) { BW_LPUART_CTRL_RE(baseAddr, 0); } /*! * @brief Gets the LPUART receiver enabled/disabled configuration. * * @param baseAddr LPUART base address * @return State of LPUART receiver enable(1)/disable(0) */ static inline bool LPUART_HAL_IsReceiverEnabled(uint32_t baseAddr) { return BR_LPUART_CTRL_RE(baseAddr); } /*! * @brief Configures the LPUART baud rate. * * In some LPUART instances the user must disable the transmitter/receiver * before calling this function. * Generally, this may be applied to all LPUARTs to ensure safe operation. * * @param baseAddr LPUART base address. * @param sourceClockInHz LPUART source input clock in Hz. * @param desiredBaudRate LPUART desired baud rate. * @return An error code or kStatus_Success */ lpuart_status_t LPUART_HAL_SetBaudRate(uint32_t baseAddr, uint32_t sourceClockInHz, uint32_t desiredBaudRate); /*! * @brief Sets the LPUART baud rate modulo divisor. * * @param baseAddr LPUART base address. * @param baudRateDivisor The baud rate modulo division "SBR" */ static inline void LPUART_HAL_SetBaudRateDivisor(uint32_t baseAddr, uint32_t baudRateDivisor) { assert ((baudRateDivisor < 0x1FFF) && (baudRateDivisor > 1)); BW_LPUART_BAUD_SBR(baseAddr, baudRateDivisor); } #if FSL_FEATURE_LPUART_HAS_BAUD_RATE_OVER_SAMPLING_SUPPORT /*! * @brief Sets the LPUART baud rate oversampling ratio (Note: Feature available on select * LPUART instances used together with baud rate programming) * The oversampling ratio should be set between 4x (00011) and 32x (11111). Writing * an invalid oversampling ratio results in an error and is set to a default * 16x (01111) oversampling ratio. * IDisable the transmitter/receiver before calling * this function. * * @param baseAddr LPUART base address. * @param overSamplingRatio The oversampling ratio "OSR" */ static inline void LPUART_HAL_SetOversamplingRatio(uint32_t baseAddr, uint32_t overSamplingRatio) { assert(overSamplingRatio < 0x1F); BW_LPUART_BAUD_OSR(baseAddr, overSamplingRatio); } #endif #if FSL_FEATURE_LPUART_HAS_BOTH_EDGE_SAMPLING_SUPPORT /*! * @brief Configures the LPUART baud rate both edge sampling (Note: Feature available on select * LPUART instances used with baud rate programming) * When enabled, the received data is sampled on both edges of the baud rate clock. * This must be set when the oversampling ratio is between 4x and 7x. * This function should only be called when the receiver is disabled. * * @param baseAddr LPUART base address. * @param enableBothEdgeSampling Enable (1) or Disable (0) Both Edge Sampling * @return An error code or kStatus_Success */ static inline void LPUART_HAL_SetBothEdgeSamplingCmd(uint32_t baseAddr, bool enableBothEdgeSampling) { BW_LPUART_BAUD_BOTHEDGE(baseAddr, enableBothEdgeSampling); } #endif /*! * @brief Configures the number of bits per character in the LPUART controller. * * In some LPUART instances, the user should disable the transmitter/receiver * before calling this function. * Generally, this may be applied to all LPUARTs to ensure safe operation. * * @param baseAddr LPUART base address. * @param bitCountPerChar Number of bits per char (8, 9, or * 10, depending on the LPUART instance) */ void LPUART_HAL_SetBitCountPerChar(uint32_t baseAddr, lpuart_bit_count_per_char_t bitCountPerChar); /*! * @brief Configures parity mode in the LPUART controller. * * In some LPUART instances, the user should disable the transmitter/receiver * before calling this function. * Generally, this may be applied to all LPUARTs to ensure safe operation. * * @param baseAddr LPUART base address. * @param parityModeType Parity mode (enabled, disable, odd, even - see parity_mode_t struct) */ void LPUART_HAL_SetParityMode(uint32_t baseAddr, lpuart_parity_mode_t parityModeType); /*! * @brief Configures the number of stop bits in the LPUART controller. * In some LPUART instances, the user should disable the transmitter/receiver * before calling this function. * Generally, this may be applied to all LPUARTs to ensure safe operation. * * @param baseAddr LPUART base address. * @param stopBitCount Number of stop bits (1 or 2 - see lpuart_stop_bit_count_t struct) * @return An error code (an unsupported setting in some LPUARTs) or kStatus_Success */ static inline void LPUART_HAL_SetStopBitCount(uint32_t baseAddr, lpuart_stop_bit_count_t stopBitCount) { /* configure the number of stop bits */ BW_LPUART_BAUD_SBNS(baseAddr, stopBitCount); } /*! * @brief Configures the transmit and receive inversion control in the LPUART controller. * * This function should only be called when the LPUART is between transmit and receive packets. * * @param baseAddr LPUART base address. * @param rxInvert Enable (1) or disable (0) receive inversion * @param txInvert Enable (1) or disable (0) transmit inversion */ void LPUART_HAL_SetTxRxInversionCmd(uint32_t baseAddr, uint32_t rxInvert, uint32_t txInvert); /*@}*/ /*! * @name LPUART Interrupts and DMA * @{ */ /*! * @brief Configures the LPUART module interrupts to enable/disable various interrupt sources. * * @param baseAddr LPUART module base address. * @param interrupt LPUART interrupt configuration data. * @param enable true: enable, false: disable. */ void LPUART_HAL_SetIntMode(uint32_t baseAddr, lpuart_interrupt_t interrupt, bool enable); /*! * @brief Returns whether the LPUART module interrupts is enabled/disabled. * * @param baseAddr LPUART module base address. * @param interrupt LPUART interrupt configuration data. * @return true: enable, false: disable. */ bool LPUART_HAL_GetIntMode(uint32_t baseAddr, lpuart_interrupt_t interrupt); /*! * @brief Enable/Disable the transmission_complete_interrupt. * * @param baseAddr LPUART base address * @param enable true: enable, false: disable. */ static inline void LPUART_HAL_SetTxDataRegEmptyIntCmd(uint32_t baseAddr, bool enable) { BW_LPUART_CTRL_TIE(baseAddr, enable); } /*! * @brief Gets the configuration of the transmission_data_register_empty_interrupt enable setting. * * @param baseAddr LPUART base address * @return Bit setting of the interrupt enable bit */ static inline bool LPUART_HAL_GetTxDataRegEmptyIntCmd(uint32_t baseAddr) { return BR_LPUART_CTRL_TIE(baseAddr); } /*! * @brief Enables the rx_data_register_full_interrupt. * * @param baseAddr LPUART base address * @param enable true: enable, false: disable. */ static inline void LPUART_HAL_SetRxDataRegFullIntCmd(uint32_t baseAddr, bool enable) { BW_LPUART_CTRL_RIE(baseAddr, enable); } /*! * @brief Gets the configuration of the rx_data_register_full_interrupt enable. * * @param baseAddr LPUART base address * @return Bit setting of the interrupt enable bit */ static inline bool LPUART_HAL_GetRxDataRegFullIntCmd(uint32_t baseAddr) { return BR_LPUART_CTRL_RIE(baseAddr); } #if FSL_FEATURE_LPUART_HAS_DMA_ENABLE /*! * @brief LPUART configures DMA requests for Transmitter and Receiver. * * @param baseAddr LPUART base address * @param txDmaConfig Transmit DMA request configuration (enable:1 /disable: 0) * @param rxDmaConfig Receive DMA request configuration (enable: 1/disable: 0) */ void LPUART_HAL_ConfigureDma(uint32_t baseAddr, bool txDmaConfig, bool rxDmaConfig); /*! * @brief Gets the LPUART Transmit DMA request configuration. * * @param baseAddr LPUART base address * @return Transmit DMA request configuration (enable: 1/disable: 0) */ static inline bool LPUART_HAL_IsTxDmaEnabled(uint32_t baseAddr) { /* TDMAE configures the transmit data register empty flag, S1[TDRE], to */ /* generate a DMA request. */ return BR_LPUART_BAUD_TDMAE(baseAddr); } /*! * @brief Gets the LPUART receive DMA request configuration. * * @param baseAddr LPUART base address * @return Receives the DMA request configuration (enable: 1/disable: 0). */ static inline bool LPUART_HAL_IsRxDmaEnabled(uint32_t baseAddr) { /* RDMAE configures the receive data register fell flag, S1[RDRF], to */ /* generate a DMA request. */ return BR_LPUART_BAUD_RDMAE(baseAddr); } #endif /*@}*/ /*! * @name LPUART Transfer Functions * @{ */ /*! * @brief Sends the LPUART 8-bit character. * * @param baseAddr LPUART Instance * @param data data to send (8-bit) */ static inline void LPUART_HAL_Putchar(uint32_t baseAddr, uint8_t data) { /* put 8-bit data into the lpuart data register */ HW_LPUART_DATA_WR(baseAddr, data); } /*! * @brief Sends the LPUART 9-bit character. * * @param baseAddr LPUART Instance * @param data data to send (9-bit) */ void LPUART_HAL_Putchar9(uint32_t baseAddr, uint16_t data); /*! * @brief Sends the LPUART 10-bit character (Note: Feature available on select LPUART instances). * * @param baseAddr LPUART Instance * @param data data to send (10-bit) * @return An error code or kStatus_Success */ lpuart_status_t LPUART_HAL_Putchar10(uint32_t baseAddr, uint16_t data); /*! * @brief Gets the LPUART 8-bit character. * * @param baseAddr LPUART base address * @param readData data read from receive (8-bit) */ void LPUART_HAL_Getchar(uint32_t baseAddr, uint8_t *readData); /*! * @brief Gets the LPUART 9-bit character. * * @param baseAddr LPUART base address * @param readData data read from receive (9-bit) */ void LPUART_HAL_Getchar9(uint32_t baseAddr, uint16_t *readData); /*! * @brief Gets the LPUART 10-bit character. * * @param baseAddr LPUART base address * @param readData data read from receive (10-bit) * @return An error code or kStatus_Success */ lpuart_status_t LPUART_HAL_Getchar10(uint32_t baseAddr, uint16_t *readData); /*! * @brief Configures the number of idle characters that must be received before the IDLE flag is set. * * @param baseAddr LPUART base address * @param idle_config idle characters configuration */ static inline void LPUART_HAL_IdleConfig(uint32_t baseAddr, lpuart_idle_config_t idleConfig) { BW_LPUART_CTRL_IDLECFG(baseAddr, idleConfig); } /*! * @brief Gets the configuration of the number of idle characters that must be received before the IDLE flag is set. * * @param baseAddr LPUART base address * @return idle characters configuration */ static inline lpuart_idle_config_t LPUART_HAL_GetIdleconfig(uint32_t baseAddr) { /* get the receiver idle character config based on the LPUART baseAddr */ return (lpuart_idle_config_t)BR_LPUART_CTRL_IDLECFG(baseAddr); } #if FSL_FEATURE_LPUART_HAS_EXTENDED_DATA_REGISTER_FLAGS /*! * @brief Configures bit10 (if enabled) or bit9 (if disabled) as the parity bit in the serial * transmission. * This sets LPUARTx_C4[M10] - it is also required to set LPUARTx_C1[M] and LPUARTx_C1[PE] * * @param baseAddr LPUART base address * @param enable Enable (1) to configure bit10 as the parity bit, disable (0) to * configure bit 9 as the parity bit in the serial transmission */ static inline void LPUART_HAL_ConfigureBit10AsParityBitOperation(uint32_t baseAddr, bool enable) { /* to enable the parity bit as the tenth data bit, along with enabling LPUARTx_C4[M10] */ /* need to also enable parity and set LPUARTx_CTRL[M] bit */ /* assumed that the user has already set the appropriate bits */ BW_LPUART_BAUD_M10(baseAddr, enable); } /*! * @brief Gets the configuration of bit10 (if enabled) or bit9 (if disabled) as the * parity bit in the serial transmission. * * @param baseAddr LPUART base address * @return Configuration of bit10 (enabled (1)), or bit 9 (disabled (0)) as the * parity bit in the serial transmission */ static inline bool LPUART_HAL_IsBit10SetAsParityBit(uint32_t baseAddr) { /* to see if the parity bit is set as the tenth data bit, */ /* return value of LPUARTx_BAUD[M10] */ return BR_LPUART_BAUD_M10(baseAddr); } /*! * @brief Checks whether the current data word was received with noise. * * @param baseAddr LPUART base address. * @return The status of the NOISY bit in the LPUART extended data register */ static inline bool LPUART_HAL_IsCurrentDatawordReceivedWithNoise(uint32_t baseAddr) { /* to see if the current dataword was received with noise, */ /* return value of LPUARTx_DATA[NOISY] */ return BR_LPUART_DATA_NOISY(baseAddr); } /*! * @brief Checks whether the receive buffer is empty. * * @param baseAddr LPUART base address * @return TRUE if the receive-buffer is empty. */ static inline bool LPUART_HAL_IsReceiveBufferEmpty(uint32_t baseAddr) { /* to see if the current state of data buffer is empty, */ /* return value of LPUARTx_DATA[RXEMPT] */ return BR_LPUART_DATA_RXEMPT(baseAddr); } /*! * @brief Checks whether the previous BUS state was idle before this byte is received. * * @param baseAddr LPUART base address * @return TRUE if the previous BUS state was IDLE. */ static inline bool LPUART_HAL_ItWasPreviousBusStateIdle(uint32_t baseAddr) { /* to see if the current dataword was received with parity error, */ /* return value of LPUARTx_DATA[PARITYE] */ return BR_LPUART_DATA_IDLINE(baseAddr); } /*! * @brief Checks whether the current data word was received with parity error. * * @param baseAddr LPUART base address * @return The status of the PARITYE bit in the LPUART extended data register */ static inline bool LPUART_HAL_IsCurrentDatawordReceivedWithParityError(uint32_t baseAddr) { /* to see if the current dataword was received with parity error, */ /* return value of LPUARTx_DATA[PARITYE] */ return BR_LPUART_DATA_PARITYE(baseAddr); } #endif /* FSL_FEATURE_LPUART_HAS_EXTENDED_DATA_REGISTER_FLAGS */ /*@}*/ /*! * @name LPUART Special Feature Configurations * @{ */ /*! * @brief Configures the LPUART operation in wait mode (operates or stops operations in wait mode). * In some LPUART instances, the user should disable the transmitter/receiver * before calling this function. * Generally, this may be applied to all LPUARTs to ensure safe operation. * * @param baseAddr LPUART base address * @param mode LPUART wait mode operation - operates or stops to operate in wait mode. */ static inline void LPUART_HAL_SetWaitModeOperation(uint32_t baseAddr, lpuart_operation_config_t mode) { /* configure lpuart operation in wait mode */ /* In CPU wait mode: 0 - lpuart clocks continue to run; 1 - lpuart clocks freeze */ BW_LPUART_CTRL_DOZEEN(baseAddr, mode); } /*! * @brief Gets the LPUART operation in wait mode (operates or stops operations in wait mode). * * @param baseAddr LPUART base address * @return LPUART wait mode operation configuration - kLpuartOperates or KLpuartStops in wait mode */ lpuart_operation_config_t LPUART_HAL_GetWaitModeOperationConfig(uint32_t baseAddr); /*! * @brief Configures the LPUART loopback operation (enable/disable loopback operation) * * In some LPUART instances, the user should disable the transmitter/receiver * before calling this function. * Generally, this may be applied to all LPUARTs to ensure safe operation. * * @param baseAddr LPUART base address * @param enable LPUART loopback mode - disabled (0) or enabled (1) */ void LPUART_HAL_SedLoopbackCmd(uint32_t baseAddr, bool enable); /*! * @brief Configures the LPUART single-wire operation (enable/disable single-wire mode) * * In some LPUART instances, the user should disable the transmitter/receiver * before calling this function. * Generally, this may be applied to all LPUARTs to ensure safe operation. * * @param baseAddr LPUART base address * @param enable LPUART loopback mode - disabled (0) or enabled (1) */ void LPUART_HAL_SetSingleWireCmd(uint32_t baseAddr, bool enable); /*! * @brief Configures the LPUART transmit direction while in single-wire mode. * * @param baseAddr LPUART base address * @param direction LPUART single-wire transmit direction - input or output */ static inline void LPUART_HAL_ConfigureTxdirInSinglewireMode(uint32_t baseAddr, lpuart_singlewire_txdir_t direction) { /* configure LPUART transmit direction (input or output) when in single-wire mode */ /* it is assumed LPUART is in single-wire mode */ BW_LPUART_CTRL_TXDIR(baseAddr, direction); } /*! * @brief Places the LPUART receiver in standby mode. * * In some LPUART instances, * before placing LPUART in standby mode, first determine whether the receiver is set to * wake on idle or whether it is already in idle state. * NOTE that the RWU should only be set with C1[WAKE] = 0 (wakeup on idle) if the channel is currently * not idle. * This can be determined by the S2[RAF] flag. If it is set to wake up an IDLE event and the channel is * already idle, it is possible that the LPUART will discard data since data must be received * (or a LIN break detect) after an IDLE is detected and before IDLE is allowed to reasserted. * * @param baseAddr LPUART base address * @return Error code or kStatus_Success */ lpuart_status_t LPUART_HAL_PutReceiverInStandbyMode(uint32_t baseAddr); /*! * @brief Places the LPUART receiver in a normal mode (disable standby mode operation). * * @param baseAddr LPUART base address */ static inline void LPUART_HAL_PutReceiverInNormalMode(uint32_t baseAddr) { /* clear the RWU bit to place receiver into normal mode (disable standby mode) */ BW_LPUART_CTRL_RWU(baseAddr, 0); } /*! * @brief Checks whether the LPUART receiver is in a standby mode. * * @param baseAddr LPUART base address * @return LPUART in normal more (0) or standby (1) */ static inline bool LPUART_HAL_IsReceiverInStandby(uint32_t baseAddr) { /* return the RWU bit setting (0 - normal more, 1 - standby) */ return BR_LPUART_CTRL_RWU(baseAddr); } /*! * @brief LPUART receiver wakeup method (idle line or addr-mark) from standby mode * * @param baseAddr LPUART base address * @param method LPUART wakeup method: 0 - Idle-line wake (default), 1 - addr-mark wake */ static inline void LPUART_HAL_SelectReceiverWakeupMethod(uint32_t baseAddr, lpuart_wakeup_method_t method) { /* configure the WAKE bit for idle line wake or address mark wake */ BW_LPUART_CTRL_WAKE(baseAddr, method); } /*! * @brief Gets the LPUART receiver wakeup method (idle line or addr-mark) from standby mode. * * @param baseAddr LPUART base address * @return LPUART wakeup method: kLpuartIdleLineWake: 0 - Idle-line wake (default), * kLpuartAddrMarkWake: 1 - addr-mark wake */ lpuart_wakeup_method_t LPUART_HAL_GetReceiverWakeupMethod(uint32_t baseAddr); /*! * @brief LPUART idle-line detect operation configuration (idle line bit-count start and wake * up affect on IDLE status bit). * * In some LPUART instances, the user should disable the transmitter/receiver * before calling this function. * Generally, this may be applied to all LPUARTs to ensure safe operation. * * @param baseAddr LPUART base address * @param config LPUART configuration data for idle line detect operation */ void LPUART_HAL_ConfigureIdleLineDetect(uint32_t baseAddr, const lpuart_idle_line_config_t *config); /*! * @brief LPUART break character transmit length configuration * In some LPUART instances, the user should disable the transmitter before calling * this function. Generally, this may be applied to all LPUARTs to ensure safe operation. * * @param baseAddr LPUART base address * @param length LPUART break character length setting: 0 - minimum 10-bit times (default), * 1 - minimum 13-bit times */ static inline void LPUART_HAL_SetBreakCharTransmitLength(uint32_t baseAddr, lpuart_break_char_length_t length) { /* Configure BRK13 - Break Character transmit length configuration */ /* LPUART break character length setting: */ /* 0 - minimum 10-bit times (default), */ /* 1 - minimum 13-bit times */ BW_LPUART_STAT_BRK13(baseAddr, length); } /*! * @brief LPUART break character detect length configuration * * @param baseAddr LPUART base address * @param length LPUART break character length setting: 0 - minimum 10-bit times (default), * 1 - minimum 13-bit times */ static inline void LPUART_HAL_SetBreakCharDetectLength(uint32_t baseAddr, lpuart_break_char_length_t length) { /* Configure LBKDE - Break Character detect length configuration */ /* LPUART break character length setting: */ /* 0 - minimum 10-bit times (default), */ /* 1 - minimum 13-bit times */ BW_LPUART_STAT_LBKDE(baseAddr, length); } /*! * @brief LPUART transmit sends break character configuration. * * @param baseAddr LPUART base address * @param enable LPUART normal/queue break char - disabled (normal mode, default: 0) or * enabled (queue break char: 1) */ static inline void LPUART_HAL_QueueBreakCharToSend(uint32_t baseAddr, bool enable) { /* Configure SBK - Send Break */ /* LPUART send break character setting: */ /* 0 - normal transmitter operation, */ /* 1 - Queue break character(s) to be sent */ BW_LPUART_CTRL_SBK(baseAddr, enable); } /*! * @brief LPUART configures match address mode control (Note: Feature available on * select LPUART instances) * * @param baseAddr LPUART base address * @param matchAddrMode1 MAEN1: match address mode1 enable (1)/disable (0) * @param matchAddrMode2 MAEN2: match address mode2 enable (1)/disable (0) * @param matchAddrValue1 MA: match address value to program into match address register 1 * @param matchAddrValue2 MA: match address value to program into match address register 2 * @param config MATCFG: Configures the match addressing mode used. * @return An error code or kStatus_Success */ lpuart_status_t LPUART_HAL_SetMatchAddressOperation(uint32_t baseAddr, bool matchAddrMode1, bool matchAddrMode2, uint8_t matchAddrValue1, uint8_t matchAddrValue2, lpuart_match_config_t config); /*! * @brief LPUART sends the MSB first configuration (Note: Feature available on select LPUART instances) * In some LPUART instances, the user should disable the transmitter/receiver * before calling this function. * Generally, this may be applied to all LPUARTs to ensure safe operation. * * @param baseAddr LPUART base address * @param enable MSB first mode configuration, MSBF: 0 - LSB (default, feature disabled), * 1 - MSB (feature enabled) */ static inline void LPUART_HAL_ConfigureSendMsbFirstOperation(uint32_t baseAddr, bool enable) { BW_LPUART_STAT_MSBF(baseAddr, enable); } /*! * @brief LPUART disables re-sync of received data configuration (Note: Feature available on * select LPUART instances). * * @param baseAddr LPUART base address * @param enable disable re-sync of received data word configuration, RESYNCDIS: * 0 - re-sync of received data word (default, feature disabled), * 1 - disable the re-sync (feature enabled) */ static inline void LPUART_HAL_ConfigureReceiveResyncDisableOperation(uint32_t baseAddr, bool enable) { /* When set, disables the resynchronization of the received data word when a data */ /* one followed by data zero transition is detected. This bit should only be changed */ /* when the receiver is disabled. */ BW_LPUART_BAUD_RESYNCDIS(baseAddr, enable); } #if FSL_FEATURE_LPUART_HAS_MODEM_SUPPORT /*! * @brief Transmits the CTS source configuration. * * @param baseAddr LPUART base address * @param source LPUART CTS source */ static inline void LPUART_HAL_SelectSourceCts(uint32_t baseAddr, lpuart_cts_source_t source) { /* Set TXCTSSRC */ BW_LPUART_MODIR_TXCTSSRC(baseAddr, source); } /*! * @brief Transmits the CTS configuration. * Note: configures if the CTS state is checked at the start of each character or only when the transmitter is idle. * * @param baseAddr LPUART base address * @param config LPUART CTS configuration */ static inline void LPUART_HAL_ConfigureCts(uint32_t baseAddr, lpuart_cts_config_t config) { /* Set TXCTSC */ BW_LPUART_MODIR_TXCTSC(baseAddr, config); } /*! * @brief Enables the receiver request-to-send. * Note: do not enable both Receiver RTS (RXRTSE) and Transmit RTS (TXRTSE). * * @param baseAddr LPUART base address * @param enable disable(0)/enable(1) receiver RTS. */ static inline void LPUART_HAL_SetReceiverRts(uint32_t baseAddr, bool enable) { BW_LPUART_MODIR_RXRTSE(baseAddr, enable); } /*! * @brief Enables the transmitter request-to-send. * Note: do not enable both Receiver RTS (RXRTSE) and Transmit RTS (TXRTSE). * * @param baseAddr LPUART base address * @param enable disable(0)/enable(1) transmitter RTS. */ static inline void LPUART_HAL_SetTransmitterRtsCmd(uint32_t baseAddr, bool enable) { BW_LPUART_MODIR_TXRTSE(baseAddr, enable); } /*! * @brief Configures the transmitter RTS polarity: 0=active low, 1=active high. * * @param baseAddr LPUART base address * @param polarity Settings to choose RTS polarity. */ static inline void LPUART_HAL_SetTransmitterRtsPolarityMode(uint32_t baseAddr, bool polarity) { /* Configure the transmitter rts polarity: 0=active low, 1=active high */ BW_LPUART_MODIR_TXRTSPOL(baseAddr, polarity); } /*! * @brief Enables the transmitter clear-to-send. * * @param baseAddr LPUART base address * @param enable disable(0)/enable(1) transmitter CTS. */ static inline void LPUART_HAL_SetTransmitterCtsCmd(uint32_t baseAddr, bool enable) { BW_LPUART_MODIR_TXCTSE(baseAddr, enable); } #endif /* FSL_FEATURE_LPUART_HAS_MODEM_SUPPORT */ #if FSL_FEATURE_LPUART_HAS_IR_SUPPORT /*! * @brief Configures the LPUART infrared operation. * * @param baseAddr LPUART base address * @param enable Enable (1) or disable (0) the infrared operation * @param pulseWidth The transmit narrow pulse width of type lpuart_ir_tx_pulsewidth_t */ void LPUART_HAL_SetInfraredOperation(uint32_t baseAddr, bool enable, lpuart_ir_tx_pulsewidth_t pulseWidth); #endif /* FSL_FEATURE_LPUART_HAS_IR_SUPPORT */ /*@}*/ /*! * @name LPUART Status Flags * @{ */ /*! * @brief LPUART get status flag * * @param baseAddr LPUART base address * @param statusFlag The status flag to query */ bool LPUART_HAL_GetStatusFlag(uint32_t baseAddr, lpuart_status_flag_t statusFlag); /*! * @brief Gets the LPUART Transmit data register empty flag. * * This function returns the state of the LPUART Transmit data register empty flag. * * @param baseAddr LPUART module base address. * @return The status of Transmit data register empty flag, which is set when transmit buffer * is empty. */ static inline bool LPUART_HAL_IsTxDataRegEmpty(uint32_t baseAddr) { /* return status condition of TDRE flag */ return BR_LPUART_STAT_TDRE(baseAddr); } /*! * @brief Gets the LPUART receive data register full flag. * * @param baseAddr LPUART base address * @return Status of the receive data register full flag, sets when the receive data buffer is full. */ static inline bool LPUART_HAL_IsRxDataRegFull(uint32_t baseAddr) { /* return status condition of RDRF flag */ return BR_LPUART_STAT_RDRF(baseAddr); } /*! * @brief Gets the LPUART transmission complete flag. * * @param baseAddr LPUART base address * @return Status of Transmission complete flag, sets when transmitter is idle * (transmission activity complete) */ static inline bool LPUART_HAL_IsTxComplete(uint32_t baseAddr) { /* return status condition of TC flag */ return BR_LPUART_STAT_TC(baseAddr); } /*! * @brief LPUART clears an individual status flag (see lpuart_status_flag_t for list of status bits). * * @param baseAddr LPUART base address * @param statusFlag Desired LPUART status flag to clear * @return An error code or kStatus_Success */ lpuart_status_t LPUART_HAL_ClearStatusFlag(uint32_t baseAddr, lpuart_status_flag_t statusFlag); /*! * @brief LPUART clears ALL status flags. * * @param baseAddr LPUART base address */ void LPUART_HAL_ClearAllNonAutoclearStatusFlags(uint32_t baseAddr); /*@}*/ #if defined(__cplusplus) } #endif /*! @}*/ #endif /* MBED_NO_LPUART */ #endif /* __FSL_LPUART_HAL_H__ */ /******************************************************************************* * EOF ******************************************************************************/ ================================================ FILE: Zelig/mbed/TARGET_K64F/TARGET_Freescale/TARGET_KPSDK_MCUS/TARGET_KPSDK_CODE/hal/mcg/fsl_mcg_features.h ================================================ /* ** ################################################################### ** Version: rev. 1.0, 2014-05-14 ** Build: b140515 ** ** Abstract: ** Chip specific module features. ** ** Copyright: 2014 Freescale Semiconductor, Inc. ** All rights reserved. ** ** Redistribution and use in source and binary forms, with or without modification, ** are permitted provided that the following conditions are met: ** ** o Redistributions of source code must retain the above copyright notice, this list ** of conditions and the following disclaimer. ** ** o Redistributions in binary form must reproduce the above copyright notice, this ** list of conditions and the following disclaimer in the documentation and/or ** other materials provided with the distribution. ** ** o Neither the name of Freescale Semiconductor, Inc. nor the names of its ** contributors may be used to endorse or promote products derived from this ** software without specific prior written permission. ** ** THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ** ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED ** WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE ** DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT 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. ** ** http: www.freescale.com ** mail: support@freescale.com ** ** Revisions: ** - rev. 1.0 (2014-05-14) ** Customer release. ** ** ################################################################### */ #if !defined(__FSL_MCG_FEATURES_H__) #define __FSL_MCG_FEATURES_H__ #if defined(CPU_MK02FN128VFM10) || defined(CPU_MK02FN64VFM10) || defined(CPU_MK02FN128VLF10) || defined(CPU_MK02FN64VLF10) || \ defined(CPU_MK02FN128VLH10) || defined(CPU_MK02FN64VLH10) || defined(CPU_MKV30F128VFM10) || defined(CPU_MKV30F64VFM10) || \ defined(CPU_MKV30F128VLF10) || defined(CPU_MKV30F64VLF10) || defined(CPU_MKV30F128VLH10) || defined(CPU_MKV30F64VLH10) || \ defined(CPU_MKV31F128VLH10) || defined(CPU_MKV31F128VLL10) /* @brief Maximum PLL external reference divider value (max. value of register bit field C5[PRVDIV] increased by one). */ #define FSL_FEATURE_MCG_PLL_PRDIV_MAX (0) /* @brief VCO divider base value (multiply factor of register bit field C6[VDIV] zero value). */ #define FSL_FEATURE_MCG_PLL_VDIV_BASE (0) /* @brief Is PLL clock divided by 2 before MCG PLL/FLL clock selection in the SIM module. */ #define FSL_FEATURE_MCG_HAS_PLL_EXTRA_DIV (0) /* @brief Has 32kHz RTC external reference clock (register bits C8[LOCS1], C8[CME1] and C8[LOCRE1]). */ #define FSL_FEATURE_MCG_HAS_RTC_32K (0) /* @brief Has PLL1 external reference clock (registers C10, C11, C12, S2). */ #define FSL_FEATURE_MCG_HAS_PLL1 (0) /* @brief Has 48MHz internal oscillator. */ #define FSL_FEATURE_MCG_HAS_IRC_48M (1) /* @brief Has OSC1 external oscillator (registers C10, C11, C12, S2). */ #define FSL_FEATURE_MCG_HAS_OSC1 (0) /* @brief Has fast internal reference clock fine trim (register bit C2[FCFTRIM]). */ #define FSL_FEATURE_MCG_HAS_FCFTRIM (1) /* @brief Has PLL loss of lock reset (register bit C8[LOLRE]). */ #define FSL_FEATURE_MCG_HAS_LOLRE (0) /* @brief Has MCG OSC clock selection (register bit C7[OSCSEL]). */ #define FSL_FEATURE_MCG_USE_OSCSEL (1) /* @brief Has PLL external reference selection (register bits C5[PLLREFSEL0] and C11[PLLREFSEL1]). */ #define FSL_FEATURE_MCG_USE_PLLREFSEL (0) /* @brief TBD */ #define FSL_FEATURE_MCG_USE_SYSTEM_CLOCK (0) /* @brief Has phase-locked loop (PLL) (register C5 and bits C6[VDIV], C6[PLLS], C6[LOLIE0], S[PLLST], S[LOCK0], S[LOLS]). */ #define FSL_FEATURE_MCG_HAS_PLL (0) /* @brief PLL/OSC related register bit fields have PLL/OSC index in their name. */ #define FSL_FEATURE_MCG_HAS_PLL_OSC_INDEX (0) /* @brief Has frequency-locked loop (FLL) (register ATCVH, ATCVL and bits C1[IREFS], C1[FRDIV]). */ #define FSL_FEATURE_MCG_HAS_FLL (1) /* @brief Has PLL external to MCG (register C9). */ #define FSL_FEATURE_MCG_HAS_EXTERNAL_PLL (0) /* @brief Has crystal oscillator or external reference clock low power controls (register bits C2[HGO], C2[RANGE]). */ #define FSL_FEATURE_MCG_HAS_EXT_REF_LOW_POWER_CONTROL (1) /* @brief Has PLL/FLL selection as MCG output (register bit C6[PLLS]). */ #define FSL_FEATURE_MCG_HAS_PLL_FLL_SELECTION (0) /* @brief Has PLL output selection (PLL0/PLL1, PLL/external PLL) (register bit C11[PLLCS]). */ #define FSL_FEATURE_MCG_HAS_PLL_OUTPUT_SELECTION (0) /* @brief Has automatic trim machine (registers ATCVH, ATCVL and bits SC[ATMF], SC[ATMS], SC[ATME]). */ #define FSL_FEATURE_MCG_HAS_AUTO_TRIM_MACHINE (1) /* @brief Has external clock monitor (register bit C6[CME]). */ #define FSL_FEATURE_MCG_HAS_EXTERNAL_CLOCK_MONITOR (1) /* @brief Has low frequency internal reference clock (IRC) (registers LTRIMRNG, LFRIM, LSTRIM and bit MC[LIRC_DIV2]). */ #define FSL_FEATURE_MCG_HAS_LOW_FREQ_IRC (0) /* @brief Has high frequency internal reference clock (IRC) (registers HCTRIM, HTTRIM, HFTRIM and bit MC[HIRCEN]). */ #define FSL_FEATURE_MCG_HAS_HIGH_FREQ_IRC (0) #elif defined(CPU_MK20DX128VMP5) || defined(CPU_MK20DN128VMP5) || defined(CPU_MK20DX64VMP5) || defined(CPU_MK20DN64VMP5) || \ defined(CPU_MK20DX32VMP5) || defined(CPU_MK20DN32VMP5) || defined(CPU_MK20DX128VLH5) || defined(CPU_MK20DN128VLH5) || \ defined(CPU_MK20DX64VLH5) || defined(CPU_MK20DN64VLH5) || defined(CPU_MK20DX32VLH5) || defined(CPU_MK20DN32VLH5) || \ defined(CPU_MK20DX128VFM5) || defined(CPU_MK20DN128VFM5) || defined(CPU_MK20DX64VFM5) || defined(CPU_MK20DN64VFM5) || \ defined(CPU_MK20DX32VFM5) || defined(CPU_MK20DN32VFM5) || defined(CPU_MK20DX128VFT5) || defined(CPU_MK20DN128VFT5) || \ defined(CPU_MK20DX64VFT5) || defined(CPU_MK20DN64VFT5) || defined(CPU_MK20DX32VFT5) || defined(CPU_MK20DN32VFT5) || \ defined(CPU_MK20DX128VLF5) || defined(CPU_MK20DN128VLF5) || defined(CPU_MK20DX64VLF5) || defined(CPU_MK20DN64VLF5) || \ defined(CPU_MK20DX32VLF5) || defined(CPU_MK20DN32VLF5) /* @brief Maximum PLL external reference divider value (max. value of register bit field C5[PRVDIV] increased by one). */ #define FSL_FEATURE_MCG_PLL_PRDIV_MAX (25) /* @brief VCO divider base value (multiply factor of register bit field C6[VDIV] zero value). */ #define FSL_FEATURE_MCG_PLL_VDIV_BASE (24) /* @brief Is PLL clock divided by 2 before MCG PLL/FLL clock selection in the SIM module. */ #define FSL_FEATURE_MCG_HAS_PLL_EXTRA_DIV (0) /* @brief Has 32kHz RTC external reference clock (register bits C8[LOCS1], C8[CME1] and C8[LOCRE1]). */ #define FSL_FEATURE_MCG_HAS_RTC_32K (1) /* @brief Has PLL1 external reference clock (registers C10, C11, C12, S2). */ #define FSL_FEATURE_MCG_HAS_PLL1 (0) /* @brief Has 48MHz internal oscillator. */ #define FSL_FEATURE_MCG_HAS_IRC_48M (0) /* @brief Has OSC1 external oscillator (registers C10, C11, C12, S2). */ #define FSL_FEATURE_MCG_HAS_OSC1 (0) /* @brief Has fast internal reference clock fine trim (register bit C2[FCFTRIM]). */ #define FSL_FEATURE_MCG_HAS_FCFTRIM (0) /* @brief Has PLL loss of lock reset (register bit C8[LOLRE]). */ #define FSL_FEATURE_MCG_HAS_LOLRE (1) /* @brief Has MCG OSC clock selection (register bit C7[OSCSEL]). */ #define FSL_FEATURE_MCG_USE_OSCSEL (1) /* @brief Has PLL external reference selection (register bits C5[PLLREFSEL0] and C11[PLLREFSEL1]). */ #define FSL_FEATURE_MCG_USE_PLLREFSEL (0) /* @brief TBD */ #define FSL_FEATURE_MCG_USE_SYSTEM_CLOCK (0) /* @brief Has phase-locked loop (PLL) (register C5 and bits C6[VDIV], C6[PLLS], C6[LOLIE0], S[PLLST], S[LOCK0], S[LOLS]). */ #define FSL_FEATURE_MCG_HAS_PLL (1) /* @brief PLL/OSC related register bit fields have PLL/OSC index in their name. */ #define FSL_FEATURE_MCG_HAS_PLL_OSC_INDEX (1) /* @brief Has frequency-locked loop (FLL) (register ATCVH, ATCVL and bits C1[IREFS], C1[FRDIV]). */ #define FSL_FEATURE_MCG_HAS_FLL (1) /* @brief Has PLL external to MCG (register C9). */ #define FSL_FEATURE_MCG_HAS_EXTERNAL_PLL (0) /* @brief Has crystal oscillator or external reference clock low power controls (register bits C2[HGO], C2[RANGE]). */ #define FSL_FEATURE_MCG_HAS_EXT_REF_LOW_POWER_CONTROL (1) /* @brief Has PLL/FLL selection as MCG output (register bit C6[PLLS]). */ #define FSL_FEATURE_MCG_HAS_PLL_FLL_SELECTION (1) /* @brief Has PLL output selection (PLL0/PLL1, PLL/external PLL) (register bit C11[PLLCS]). */ #define FSL_FEATURE_MCG_HAS_PLL_OUTPUT_SELECTION (0) /* @brief Has automatic trim machine (registers ATCVH, ATCVL and bits SC[ATMF], SC[ATMS], SC[ATME]). */ #define FSL_FEATURE_MCG_HAS_AUTO_TRIM_MACHINE (1) /* @brief Has external clock monitor (register bit C6[CME]). */ #define FSL_FEATURE_MCG_HAS_EXTERNAL_CLOCK_MONITOR (1) /* @brief Has low frequency internal reference clock (IRC) (registers LTRIMRNG, LFRIM, LSTRIM and bit MC[LIRC_DIV2]). */ #define FSL_FEATURE_MCG_HAS_LOW_FREQ_IRC (0) /* @brief Has high frequency internal reference clock (IRC) (registers HCTRIM, HTTRIM, HFTRIM and bit MC[HIRCEN]). */ #define FSL_FEATURE_MCG_HAS_HIGH_FREQ_IRC (0) #elif defined(CPU_MK22FN128VDC10) || defined(CPU_MK22FN128VLH10) || defined(CPU_MK22FN128VLL10) || defined(CPU_MK22FN128VMP10) /* @brief Maximum PLL external reference divider value (max. value of register bit field C5[PRVDIV] increased by one). */ #define FSL_FEATURE_MCG_PLL_PRDIV_MAX (0) /* @brief VCO divider base value (multiply factor of register bit field C6[VDIV] zero value). */ #define FSL_FEATURE_MCG_PLL_VDIV_BASE (0) /* @brief Is PLL clock divided by 2 before MCG PLL/FLL clock selection in the SIM module. */ #define FSL_FEATURE_MCG_HAS_PLL_EXTRA_DIV (0) /* @brief Has 32kHz RTC external reference clock (register bits C8[LOCS1], C8[CME1] and C8[LOCRE1]). */ #define FSL_FEATURE_MCG_HAS_RTC_32K (1) /* @brief Has PLL1 external reference clock (registers C10, C11, C12, S2). */ #define FSL_FEATURE_MCG_HAS_PLL1 (0) /* @brief Has 48MHz internal oscillator. */ #define FSL_FEATURE_MCG_HAS_IRC_48M (1) /* @brief Has OSC1 external oscillator (registers C10, C11, C12, S2). */ #define FSL_FEATURE_MCG_HAS_OSC1 (0) /* @brief Has fast internal reference clock fine trim (register bit C2[FCFTRIM]). */ #define FSL_FEATURE_MCG_HAS_FCFTRIM (1) /* @brief Has PLL loss of lock reset (register bit C8[LOLRE]). */ #define FSL_FEATURE_MCG_HAS_LOLRE (0) /* @brief Has MCG OSC clock selection (register bit C7[OSCSEL]). */ #define FSL_FEATURE_MCG_USE_OSCSEL (1) /* @brief Has PLL external reference selection (register bits C5[PLLREFSEL0] and C11[PLLREFSEL1]). */ #define FSL_FEATURE_MCG_USE_PLLREFSEL (0) /* @brief TBD */ #define FSL_FEATURE_MCG_USE_SYSTEM_CLOCK (0) /* @brief Has phase-locked loop (PLL) (register C5 and bits C6[VDIV], C6[PLLS], C6[LOLIE0], S[PLLST], S[LOCK0], S[LOLS]). */ #define FSL_FEATURE_MCG_HAS_PLL (0) /* @brief PLL/OSC related register bit fields have PLL/OSC index in their name. */ #define FSL_FEATURE_MCG_HAS_PLL_OSC_INDEX (0) /* @brief Has frequency-locked loop (FLL) (register ATCVH, ATCVL and bits C1[IREFS], C1[FRDIV]). */ #define FSL_FEATURE_MCG_HAS_FLL (1) /* @brief Has PLL external to MCG (register C9). */ #define FSL_FEATURE_MCG_HAS_EXTERNAL_PLL (0) /* @brief Has crystal oscillator or external reference clock low power controls (register bits C2[HGO], C2[RANGE]). */ #define FSL_FEATURE_MCG_HAS_EXT_REF_LOW_POWER_CONTROL (1) /* @brief Has PLL/FLL selection as MCG output (register bit C6[PLLS]). */ #define FSL_FEATURE_MCG_HAS_PLL_FLL_SELECTION (0) /* @brief Has PLL output selection (PLL0/PLL1, PLL/external PLL) (register bit C11[PLLCS]). */ #define FSL_FEATURE_MCG_HAS_PLL_OUTPUT_SELECTION (0) /* @brief Has automatic trim machine (registers ATCVH, ATCVL and bits SC[ATMF], SC[ATMS], SC[ATME]). */ #define FSL_FEATURE_MCG_HAS_AUTO_TRIM_MACHINE (1) /* @brief Has external clock monitor (register bit C6[CME]). */ #define FSL_FEATURE_MCG_HAS_EXTERNAL_CLOCK_MONITOR (1) /* @brief Has low frequency internal reference clock (IRC) (registers LTRIMRNG, LFRIM, LSTRIM and bit MC[LIRC_DIV2]). */ #define FSL_FEATURE_MCG_HAS_LOW_FREQ_IRC (0) /* @brief Has high frequency internal reference clock (IRC) (registers HCTRIM, HTTRIM, HFTRIM and bit MC[HIRCEN]). */ #define FSL_FEATURE_MCG_HAS_HIGH_FREQ_IRC (0) #elif defined(CPU_MK22FN256VDC12) || defined(CPU_MK22FN256VLH12) || defined(CPU_MK22FN256VLL12) || defined(CPU_MK22FN256VMP12) || \ defined(CPU_MK22FN512VDC12) || defined(CPU_MK22FN512VLH12) || defined(CPU_MK22FN512VLL12) || defined(CPU_MK24FN1M0VDC12) || \ defined(CPU_MK24FN1M0VLL12) || defined(CPU_MK24FN1M0VLQ12) || defined(CPU_MK24FN256VDC12) || defined(CPU_MK63FN1M0VLQ12) || \ defined(CPU_MK63FN1M0VMD12) || defined(CPU_MK64FX512VDC12) || defined(CPU_MK64FN1M0VDC12) || defined(CPU_MK64FX512VLL12) || \ defined(CPU_MK64FN1M0VLL12) || defined(CPU_MK64FX512VLQ12) || defined(CPU_MK64FN1M0VLQ12) || defined(CPU_MK64FX512VMD12) || \ defined(CPU_MK64FN1M0VMD12) /* @brief Maximum PLL external reference divider value (max. value of register bit field C5[PRVDIV] increased by one). */ #define FSL_FEATURE_MCG_PLL_PRDIV_MAX (25) /* @brief VCO divider base value (multiply factor of register bit field C6[VDIV] zero value). */ #define FSL_FEATURE_MCG_PLL_VDIV_BASE (24) /* @brief Is PLL clock divided by 2 before MCG PLL/FLL clock selection in the SIM module. */ #define FSL_FEATURE_MCG_HAS_PLL_EXTRA_DIV (0) /* @brief Has 32kHz RTC external reference clock (register bits C8[LOCS1], C8[CME1] and C8[LOCRE1]). */ #define FSL_FEATURE_MCG_HAS_RTC_32K (1) /* @brief Has PLL1 external reference clock (registers C10, C11, C12, S2). */ #define FSL_FEATURE_MCG_HAS_PLL1 (0) /* @brief Has 48MHz internal oscillator. */ #define FSL_FEATURE_MCG_HAS_IRC_48M (1) /* @brief Has OSC1 external oscillator (registers C10, C11, C12, S2). */ #define FSL_FEATURE_MCG_HAS_OSC1 (0) /* @brief Has fast internal reference clock fine trim (register bit C2[FCFTRIM]). */ #define FSL_FEATURE_MCG_HAS_FCFTRIM (1) /* @brief Has PLL loss of lock reset (register bit C8[LOLRE]). */ #define FSL_FEATURE_MCG_HAS_LOLRE (1) /* @brief Has MCG OSC clock selection (register bit C7[OSCSEL]). */ #define FSL_FEATURE_MCG_USE_OSCSEL (1) /* @brief Has PLL external reference selection (register bits C5[PLLREFSEL0] and C11[PLLREFSEL1]). */ #define FSL_FEATURE_MCG_USE_PLLREFSEL (0) /* @brief TBD */ #define FSL_FEATURE_MCG_USE_SYSTEM_CLOCK (0) /* @brief Has phase-locked loop (PLL) (register C5 and bits C6[VDIV], C6[PLLS], C6[LOLIE0], S[PLLST], S[LOCK0], S[LOLS]). */ #define FSL_FEATURE_MCG_HAS_PLL (1) /* @brief PLL/OSC related register bit fields have PLL/OSC index in their name. */ #define FSL_FEATURE_MCG_HAS_PLL_OSC_INDEX (0) /* @brief Has frequency-locked loop (FLL) (register ATCVH, ATCVL and bits C1[IREFS], C1[FRDIV]). */ #define FSL_FEATURE_MCG_HAS_FLL (1) /* @brief Has PLL external to MCG (register C9). */ #define FSL_FEATURE_MCG_HAS_EXTERNAL_PLL (0) /* @brief Has crystal oscillator or external reference clock low power controls (register bits C2[HGO], C2[RANGE]). */ #define FSL_FEATURE_MCG_HAS_EXT_REF_LOW_POWER_CONTROL (1) /* @brief Has PLL/FLL selection as MCG output (register bit C6[PLLS]). */ #define FSL_FEATURE_MCG_HAS_PLL_FLL_SELECTION (1) /* @brief Has PLL output selection (PLL0/PLL1, PLL/external PLL) (register bit C11[PLLCS]). */ #define FSL_FEATURE_MCG_HAS_PLL_OUTPUT_SELECTION (0) /* @brief Has automatic trim machine (registers ATCVH, ATCVL and bits SC[ATMF], SC[ATMS], SC[ATME]). */ #define FSL_FEATURE_MCG_HAS_AUTO_TRIM_MACHINE (1) /* @brief Has external clock monitor (register bit C6[CME]). */ #define FSL_FEATURE_MCG_HAS_EXTERNAL_CLOCK_MONITOR (1) /* @brief Has low frequency internal reference clock (IRC) (registers LTRIMRNG, LFRIM, LSTRIM and bit MC[LIRC_DIV2]). */ #define FSL_FEATURE_MCG_HAS_LOW_FREQ_IRC (0) /* @brief Has high frequency internal reference clock (IRC) (registers HCTRIM, HTTRIM, HFTRIM and bit MC[HIRCEN]). */ #define FSL_FEATURE_MCG_HAS_HIGH_FREQ_IRC (0) #elif defined(CPU_MK65FN2M0CAC18) || defined(CPU_MK65FX1M0CAC18) || defined(CPU_MK65FN2M0VMI18) || defined(CPU_MK65FX1M0VMI18) || \ defined(CPU_MK66FN2M0VLQ18) || defined(CPU_MK66FX1M0VLQ18) || defined(CPU_MK66FN2M0VMD18) || defined(CPU_MK66FX1M0VMD18) /* @brief Maximum PLL external reference divider value (max. value of register bit field C5[PRVDIV] increased by one). */ #define FSL_FEATURE_MCG_PLL_PRDIV_MAX (8) /* @brief VCO divider base value (multiply factor of register bit field C6[VDIV] zero value). */ #define FSL_FEATURE_MCG_PLL_VDIV_BASE (24) /* @brief Is PLL clock divided by 2 before MCG PLL/FLL clock selection in the SIM module. */ #define FSL_FEATURE_MCG_HAS_PLL_EXTRA_DIV (0) /* @brief Has 32kHz RTC external reference clock (register bits C8[LOCS1], C8[CME1] and C8[LOCRE1]). */ #define FSL_FEATURE_MCG_HAS_RTC_32K (1) /* @brief Has PLL1 external reference clock (registers C10, C11, C12, S2). */ #define FSL_FEATURE_MCG_HAS_PLL1 (0) /* @brief Has 48MHz internal oscillator. */ #define FSL_FEATURE_MCG_HAS_IRC_48M (1) /* @brief Has OSC1 external oscillator (registers C10, C11, C12, S2). */ #define FSL_FEATURE_MCG_HAS_OSC1 (0) /* @brief Has fast internal reference clock fine trim (register bit C2[FCFTRIM]). */ #define FSL_FEATURE_MCG_HAS_FCFTRIM (1) /* @brief Has PLL loss of lock reset (register bit C8[LOLRE]). */ #define FSL_FEATURE_MCG_HAS_LOLRE (1) /* @brief Has MCG OSC clock selection (register bit C7[OSCSEL]). */ #define FSL_FEATURE_MCG_USE_OSCSEL (1) /* @brief Has PLL external reference selection (register bits C5[PLLREFSEL0] and C11[PLLREFSEL1]). */ #define FSL_FEATURE_MCG_USE_PLLREFSEL (0) /* @brief TBD */ #define FSL_FEATURE_MCG_USE_SYSTEM_CLOCK (0) /* @brief Has phase-locked loop (PLL) (register C5 and bits C6[VDIV], C6[PLLS], C6[LOLIE0], S[PLLST], S[LOCK0], S[LOLS]). */ #define FSL_FEATURE_MCG_HAS_PLL (1) /* @brief PLL/OSC related register bit fields have PLL/OSC index in their name. */ #define FSL_FEATURE_MCG_HAS_PLL_OSC_INDEX (0) /* @brief Has frequency-locked loop (FLL) (register ATCVH, ATCVL and bits C1[IREFS], C1[FRDIV]). */ #define FSL_FEATURE_MCG_HAS_FLL (1) /* @brief Has PLL external to MCG (register C9). */ #define FSL_FEATURE_MCG_HAS_EXTERNAL_PLL (1) /* @brief Has crystal oscillator or external reference clock low power controls (register bits C2[HGO], C2[RANGE]). */ #define FSL_FEATURE_MCG_HAS_EXT_REF_LOW_POWER_CONTROL (1) /* @brief Has PLL/FLL selection as MCG output (register bit C6[PLLS]). */ #define FSL_FEATURE_MCG_HAS_PLL_FLL_SELECTION (1) /* @brief Has PLL output selection (PLL0/PLL1, PLL/external PLL) (register bit C11[PLLCS]). */ #define FSL_FEATURE_MCG_HAS_PLL_OUTPUT_SELECTION (1) /* @brief Has automatic trim machine (registers ATCVH, ATCVL and bits SC[ATMF], SC[ATMS], SC[ATME]). */ #define FSL_FEATURE_MCG_HAS_AUTO_TRIM_MACHINE (1) /* @brief Has external clock monitor (register bit C6[CME]). */ #define FSL_FEATURE_MCG_HAS_EXTERNAL_CLOCK_MONITOR (1) /* @brief Has low frequency internal reference clock (IRC) (registers LTRIMRNG, LFRIM, LSTRIM and bit MC[LIRC_DIV2]). */ #define FSL_FEATURE_MCG_HAS_LOW_FREQ_IRC (0) /* @brief Has high frequency internal reference clock (IRC) (registers HCTRIM, HTTRIM, HFTRIM and bit MC[HIRCEN]). */ #define FSL_FEATURE_MCG_HAS_HIGH_FREQ_IRC (0) #elif defined(CPU_MK70FN1M0VMF12) || defined(CPU_MK70FX512VMF12) || defined(CPU_MK70FN1M0VMF15) || defined(CPU_MK70FX512VMF15) || \ defined(CPU_MK70FN1M0VMJ12) || defined(CPU_MK70FX512VMJ12) || defined(CPU_MK70FN1M0VMJ15) || defined(CPU_MK70FX512VMJ15) /* @brief Maximum PLL external reference divider value (max. value of register bit field C5[PRVDIV] increased by one). */ #define FSL_FEATURE_MCG_PLL_PRDIV_MAX (8) /* @brief VCO divider base value (multiply factor of register bit field C6[VDIV] zero value). */ #define FSL_FEATURE_MCG_PLL_VDIV_BASE (16) /* @brief Is PLL clock divided by 2 before MCG PLL/FLL clock selection in the SIM module. */ #define FSL_FEATURE_MCG_HAS_PLL_EXTRA_DIV (0) /* @brief Has 32kHz RTC external reference clock (register bits C8[LOCS1], C8[CME1] and C8[LOCRE1]). */ #define FSL_FEATURE_MCG_HAS_RTC_32K (1) /* @brief Has PLL1 external reference clock (registers C10, C11, C12, S2). */ #define FSL_FEATURE_MCG_HAS_PLL1 (1) /* @brief Has 48MHz internal oscillator. */ #define FSL_FEATURE_MCG_HAS_IRC_48M (0) /* @brief Has OSC1 external oscillator (registers C10, C11, C12, S2). */ #define FSL_FEATURE_MCG_HAS_OSC1 (1) /* @brief Has fast internal reference clock fine trim (register bit C2[FCFTRIM]). */ #define FSL_FEATURE_MCG_HAS_FCFTRIM (0) /* @brief Has PLL loss of lock reset (register bit C8[LOLRE]). */ #define FSL_FEATURE_MCG_HAS_LOLRE (0) /* @brief Has MCG OSC clock selection (register bit C7[OSCSEL]). */ #define FSL_FEATURE_MCG_USE_OSCSEL (1) /* @brief Has PLL external reference selection (register bits C5[PLLREFSEL0] and C11[PLLREFSEL1]). */ #define FSL_FEATURE_MCG_USE_PLLREFSEL (1) /* @brief TBD */ #define FSL_FEATURE_MCG_USE_SYSTEM_CLOCK (0) /* @brief Has phase-locked loop (PLL) (register C5 and bits C6[VDIV], C6[PLLS], C6[LOLIE0], S[PLLST], S[LOCK0], S[LOLS]). */ #define FSL_FEATURE_MCG_HAS_PLL (1) /* @brief PLL/OSC related register bit fields have PLL/OSC index in their name. */ #define FSL_FEATURE_MCG_HAS_PLL_OSC_INDEX (1) /* @brief Has frequency-locked loop (FLL) (register ATCVH, ATCVL and bits C1[IREFS], C1[FRDIV]). */ #define FSL_FEATURE_MCG_HAS_FLL (1) /* @brief Has PLL external to MCG (register C9). */ #define FSL_FEATURE_MCG_HAS_EXTERNAL_PLL (0) /* @brief Has crystal oscillator or external reference clock low power controls (register bits C2[HGO], C2[RANGE]). */ #define FSL_FEATURE_MCG_HAS_EXT_REF_LOW_POWER_CONTROL (1) /* @brief Has PLL/FLL selection as MCG output (register bit C6[PLLS]). */ #define FSL_FEATURE_MCG_HAS_PLL_FLL_SELECTION (1) /* @brief Has PLL output selection (PLL0/PLL1, PLL/external PLL) (register bit C11[PLLCS]). */ #define FSL_FEATURE_MCG_HAS_PLL_OUTPUT_SELECTION (1) /* @brief Has automatic trim machine (registers ATCVH, ATCVL and bits SC[ATMF], SC[ATMS], SC[ATME]). */ #define FSL_FEATURE_MCG_HAS_AUTO_TRIM_MACHINE (1) /* @brief Has external clock monitor (register bit C6[CME]). */ #define FSL_FEATURE_MCG_HAS_EXTERNAL_CLOCK_MONITOR (1) /* @brief Has low frequency internal reference clock (IRC) (registers LTRIMRNG, LFRIM, LSTRIM and bit MC[LIRC_DIV2]). */ #define FSL_FEATURE_MCG_HAS_LOW_FREQ_IRC (0) /* @brief Has high frequency internal reference clock (IRC) (registers HCTRIM, HTTRIM, HFTRIM and bit MC[HIRCEN]). */ #define FSL_FEATURE_MCG_HAS_HIGH_FREQ_IRC (0) #elif defined(CPU_MKL03Z32CAF4) || defined(CPU_MKL03Z8VFG4) || defined(CPU_MKL03Z16VFG4) || defined(CPU_MKL03Z32VFG4) || \ defined(CPU_MKL03Z8VFK4) || defined(CPU_MKL03Z16VFK4) || defined(CPU_MKL03Z32VFK4) /* @brief Maximum PLL external reference divider value (max. value of register bit field C5[PRVDIV] increased by one). */ #define FSL_FEATURE_MCG_PLL_PRDIV_MAX (0) /* @brief VCO divider base value (multiply factor of register bit field C6[VDIV] zero value). */ #define FSL_FEATURE_MCG_PLL_VDIV_BASE (0) /* @brief Is PLL clock divided by 2 before MCG PLL/FLL clock selection in the SIM module. */ #define FSL_FEATURE_MCG_HAS_PLL_EXTRA_DIV (1) /* @brief Has 32kHz RTC external reference clock (register bits C8[LOCS1], C8[CME1] and C8[LOCRE1]). */ #define FSL_FEATURE_MCG_HAS_RTC_32K (0) /* @brief Has PLL1 external reference clock (registers C10, C11, C12, S2). */ #define FSL_FEATURE_MCG_HAS_PLL1 (0) /* @brief Has 48MHz internal oscillator. */ #define FSL_FEATURE_MCG_HAS_IRC_48M (0) /* @brief Has OSC1 external oscillator (registers C10, C11, C12, S2). */ #define FSL_FEATURE_MCG_HAS_OSC1 (0) /* @brief Has fast internal reference clock fine trim (register bit C2[FCFTRIM]). */ #define FSL_FEATURE_MCG_HAS_FCFTRIM (0) /* @brief Has PLL loss of lock reset (register bit C8[LOLRE]). */ #define FSL_FEATURE_MCG_HAS_LOLRE (0) /* @brief Has MCG OSC clock selection (register bit C7[OSCSEL]). */ #define FSL_FEATURE_MCG_USE_OSCSEL (0) /* @brief Has PLL external reference selection (register bits C5[PLLREFSEL0] and C11[PLLREFSEL1]). */ #define FSL_FEATURE_MCG_USE_PLLREFSEL (0) /* @brief TBD */ #define FSL_FEATURE_MCG_USE_SYSTEM_CLOCK (0) /* @brief Has phase-locked loop (PLL) (register C5 and bits C6[VDIV], C6[PLLS], C6[LOLIE0], S[PLLST], S[LOCK0], S[LOLS]). */ #define FSL_FEATURE_MCG_HAS_PLL (0) /* @brief PLL/OSC related register bit fields have PLL/OSC index in their name. */ #define FSL_FEATURE_MCG_HAS_PLL_OSC_INDEX (0) /* @brief Has frequency-locked loop (FLL) (register ATCVH, ATCVL and bits C1[IREFS], C1[FRDIV]). */ #define FSL_FEATURE_MCG_HAS_FLL (0) /* @brief Has PLL external to MCG (register C9). */ #define FSL_FEATURE_MCG_HAS_EXTERNAL_PLL (0) /* @brief Has crystal oscillator or external reference clock low power controls (register bits C2[HGO], C2[RANGE]). */ #define FSL_FEATURE_MCG_HAS_EXT_REF_LOW_POWER_CONTROL (0) /* @brief Has PLL/FLL selection as MCG output (register bit C6[PLLS]). */ #define FSL_FEATURE_MCG_HAS_PLL_FLL_SELECTION (0) /* @brief Has PLL output selection (PLL0/PLL1, PLL/external PLL) (register bit C11[PLLCS]). */ #define FSL_FEATURE_MCG_HAS_PLL_OUTPUT_SELECTION (0) /* @brief Has automatic trim machine (registers ATCVH, ATCVL and bits SC[ATMF], SC[ATMS], SC[ATME]). */ #define FSL_FEATURE_MCG_HAS_AUTO_TRIM_MACHINE (0) /* @brief Has external clock monitor (register bit C6[CME]). */ #define FSL_FEATURE_MCG_HAS_EXTERNAL_CLOCK_MONITOR (0) /* @brief Has low frequency internal reference clock (IRC) (registers LTRIMRNG, LFRIM, LSTRIM and bit MC[LIRC_DIV2]). */ #define FSL_FEATURE_MCG_HAS_LOW_FREQ_IRC (1) /* @brief Has high frequency internal reference clock (IRC) (registers HCTRIM, HTTRIM, HFTRIM and bit MC[HIRCEN]). */ #define FSL_FEATURE_MCG_HAS_HIGH_FREQ_IRC (1) #elif defined(CPU_MKL05Z8VFK4) || defined(CPU_MKL05Z16VFK4) || defined(CPU_MKL05Z32VFK4) || defined(CPU_MKL05Z8VLC4) || \ defined(CPU_MKL05Z16VLC4) || defined(CPU_MKL05Z32VLC4) || defined(CPU_MKL05Z8VFM4) || defined(CPU_MKL05Z16VFM4) || \ defined(CPU_MKL05Z32VFM4) || defined(CPU_MKL05Z16VLF4) || defined(CPU_MKL05Z32VLF4) /* @brief Maximum PLL external reference divider value (max. value of register bit field C5[PRVDIV] increased by one). */ #define FSL_FEATURE_MCG_PLL_PRDIV_MAX (0) /* @brief VCO divider base value (multiply factor of register bit field C6[VDIV] zero value). */ #define FSL_FEATURE_MCG_PLL_VDIV_BASE (0) /* @brief Is PLL clock divided by 2 before MCG PLL/FLL clock selection in the SIM module. */ #define FSL_FEATURE_MCG_HAS_PLL_EXTRA_DIV (1) /* @brief Has 32kHz RTC external reference clock (register bits C8[LOCS1], C8[CME1] and C8[LOCRE1]). */ #define FSL_FEATURE_MCG_HAS_RTC_32K (0) /* @brief Has PLL1 external reference clock (registers C10, C11, C12, S2). */ #define FSL_FEATURE_MCG_HAS_PLL1 (0) /* @brief Has 48MHz internal oscillator. */ #define FSL_FEATURE_MCG_HAS_IRC_48M (0) /* @brief Has OSC1 external oscillator (registers C10, C11, C12, S2). */ #define FSL_FEATURE_MCG_HAS_OSC1 (0) /* @brief Has fast internal reference clock fine trim (register bit C2[FCFTRIM]). */ #define FSL_FEATURE_MCG_HAS_FCFTRIM (0) /* @brief Has PLL loss of lock reset (register bit C8[LOLRE]). */ #define FSL_FEATURE_MCG_HAS_LOLRE (0) /* @brief Has MCG OSC clock selection (register bit C7[OSCSEL]). */ #define FSL_FEATURE_MCG_USE_OSCSEL (0) /* @brief Has PLL external reference selection (register bits C5[PLLREFSEL0] and C11[PLLREFSEL1]). */ #define FSL_FEATURE_MCG_USE_PLLREFSEL (0) /* @brief TBD */ #define FSL_FEATURE_MCG_USE_SYSTEM_CLOCK (0) /* @brief Has phase-locked loop (PLL) (register C5 and bits C6[VDIV], C6[PLLS], C6[LOLIE0], S[PLLST], S[LOCK0], S[LOLS]). */ #define FSL_FEATURE_MCG_HAS_PLL (0) /* @brief PLL/OSC related register bit fields have PLL/OSC index in their name. */ #define FSL_FEATURE_MCG_HAS_PLL_OSC_INDEX (1) /* @brief Has frequency-locked loop (FLL) (register ATCVH, ATCVL and bits C1[IREFS], C1[FRDIV]). */ #define FSL_FEATURE_MCG_HAS_FLL (1) /* @brief Has PLL external to MCG (register C9). */ #define FSL_FEATURE_MCG_HAS_EXTERNAL_PLL (0) /* @brief Has crystal oscillator or external reference clock low power controls (register bits C2[HGO], C2[RANGE]). */ #define FSL_FEATURE_MCG_HAS_EXT_REF_LOW_POWER_CONTROL (1) /* @brief Has PLL/FLL selection as MCG output (register bit C6[PLLS]). */ #define FSL_FEATURE_MCG_HAS_PLL_FLL_SELECTION (0) /* @brief Has PLL output selection (PLL0/PLL1, PLL/external PLL) (register bit C11[PLLCS]). */ #define FSL_FEATURE_MCG_HAS_PLL_OUTPUT_SELECTION (0) /* @brief Has automatic trim machine (registers ATCVH, ATCVL and bits SC[ATMF], SC[ATMS], SC[ATME]). */ #define FSL_FEATURE_MCG_HAS_AUTO_TRIM_MACHINE (1) /* @brief Has external clock monitor (register bit C6[CME]). */ #define FSL_FEATURE_MCG_HAS_EXTERNAL_CLOCK_MONITOR (1) /* @brief Has low frequency internal reference clock (IRC) (registers LTRIMRNG, LFRIM, LSTRIM and bit MC[LIRC_DIV2]). */ #define FSL_FEATURE_MCG_HAS_LOW_FREQ_IRC (0) /* @brief Has high frequency internal reference clock (IRC) (registers HCTRIM, HTTRIM, HFTRIM and bit MC[HIRCEN]). */ #define FSL_FEATURE_MCG_HAS_HIGH_FREQ_IRC (0) #elif defined(CPU_MKL13Z64VFM4) || defined(CPU_MKL13Z128VFM4) || defined(CPU_MKL13Z256VFM4) || defined(CPU_MKL13Z64VFT4) || \ defined(CPU_MKL13Z128VFT4) || defined(CPU_MKL13Z256VFT4) || defined(CPU_MKL13Z64VLH4) || defined(CPU_MKL13Z128VLH4) || \ defined(CPU_MKL13Z256VLH4) || defined(CPU_MKL13Z64VMP4) || defined(CPU_MKL13Z128VMP4) || defined(CPU_MKL13Z256VMP4) || \ defined(CPU_MKL23Z64VFM4) || defined(CPU_MKL23Z128VFM4) || defined(CPU_MKL23Z256VFM4) || defined(CPU_MKL23Z64VFT4) || \ defined(CPU_MKL23Z128VFT4) || defined(CPU_MKL23Z256VFT4) || defined(CPU_MKL23Z64VLH4) || defined(CPU_MKL23Z128VLH4) || \ defined(CPU_MKL23Z256VLH4) || defined(CPU_MKL23Z64VMP4) || defined(CPU_MKL23Z128VMP4) || defined(CPU_MKL23Z256VMP4) || \ defined(CPU_MKL33Z128VLH4) || defined(CPU_MKL33Z256VLH4) || defined(CPU_MKL33Z128VMP4) || defined(CPU_MKL33Z256VMP4) || \ defined(CPU_MKL43Z64VLH4) || defined(CPU_MKL43Z128VLH4) || defined(CPU_MKL43Z256VLH4) || defined(CPU_MKL43Z64VMP4) || \ defined(CPU_MKL43Z128VMP4) || defined(CPU_MKL43Z256VMP4) /* @brief Maximum PLL external reference divider value (max. value of register bit field C5[PRVDIV] increased by one). */ #define FSL_FEATURE_MCG_PLL_PRDIV_MAX (0) /* @brief VCO divider base value (multiply factor of register bit field C6[VDIV] zero value). */ #define FSL_FEATURE_MCG_PLL_VDIV_BASE (0) /* @brief Is PLL clock divided by 2 before MCG PLL/FLL clock selection in the SIM module. */ #define FSL_FEATURE_MCG_HAS_PLL_EXTRA_DIV (1) /* @brief Has 32kHz RTC external reference clock (register bits C8[LOCS1], C8[CME1] and C8[LOCRE1]). */ #define FSL_FEATURE_MCG_HAS_RTC_32K (0) /* @brief Has PLL1 external reference clock (registers C10, C11, C12, S2). */ #define FSL_FEATURE_MCG_HAS_PLL1 (0) /* @brief Has 48MHz internal oscillator. */ #define FSL_FEATURE_MCG_HAS_IRC_48M (0) /* @brief Has OSC1 external oscillator (registers C10, C11, C12, S2). */ #define FSL_FEATURE_MCG_HAS_OSC1 (0) /* @brief Has fast internal reference clock fine trim (register bit C2[FCFTRIM]). */ #define FSL_FEATURE_MCG_HAS_FCFTRIM (0) /* @brief Has PLL loss of lock reset (register bit C8[LOLRE]). */ #define FSL_FEATURE_MCG_HAS_LOLRE (0) /* @brief Has MCG OSC clock selection (register bit C7[OSCSEL]). */ #define FSL_FEATURE_MCG_USE_OSCSEL (0) /* @brief Has PLL external reference selection (register bits C5[PLLREFSEL0] and C11[PLLREFSEL1]). */ #define FSL_FEATURE_MCG_USE_PLLREFSEL (0) /* @brief TBD */ #define FSL_FEATURE_MCG_USE_SYSTEM_CLOCK (0) /* @brief Has phase-locked loop (PLL) (register C5 and bits C6[VDIV], C6[PLLS], C6[LOLIE0], S[PLLST], S[LOCK0], S[LOLS]). */ #define FSL_FEATURE_MCG_HAS_PLL (0) /* @brief PLL/OSC related register bit fields have PLL/OSC index in their name. */ #define FSL_FEATURE_MCG_HAS_PLL_OSC_INDEX (1) /* @brief Has frequency-locked loop (FLL) (register ATCVH, ATCVL and bits C1[IREFS], C1[FRDIV]). */ #define FSL_FEATURE_MCG_HAS_FLL (0) /* @brief Has PLL external to MCG (register C9). */ #define FSL_FEATURE_MCG_HAS_EXTERNAL_PLL (0) /* @brief Has crystal oscillator or external reference clock low power controls (register bits C2[HGO], C2[RANGE]). */ #define FSL_FEATURE_MCG_HAS_EXT_REF_LOW_POWER_CONTROL (1) /* @brief Has PLL/FLL selection as MCG output (register bit C6[PLLS]). */ #define FSL_FEATURE_MCG_HAS_PLL_FLL_SELECTION (0) /* @brief Has PLL output selection (PLL0/PLL1, PLL/external PLL) (register bit C11[PLLCS]). */ #define FSL_FEATURE_MCG_HAS_PLL_OUTPUT_SELECTION (0) /* @brief Has automatic trim machine (registers ATCVH, ATCVL and bits SC[ATMF], SC[ATMS], SC[ATME]). */ #define FSL_FEATURE_MCG_HAS_AUTO_TRIM_MACHINE (0) /* @brief Has external clock monitor (register bit C6[CME]). */ #define FSL_FEATURE_MCG_HAS_EXTERNAL_CLOCK_MONITOR (0) /* @brief Has low frequency internal reference clock (IRC) (registers LTRIMRNG, LFRIM, LSTRIM and bit MC[LIRC_DIV2]). */ #define FSL_FEATURE_MCG_HAS_LOW_FREQ_IRC (1) /* @brief Has high frequency internal reference clock (IRC) (registers HCTRIM, HTTRIM, HFTRIM and bit MC[HIRCEN]). */ #define FSL_FEATURE_MCG_HAS_HIGH_FREQ_IRC (1) #elif defined(CPU_MKL25Z32VFM4) || defined(CPU_MKL25Z64VFM4) || defined(CPU_MKL25Z128VFM4) || defined(CPU_MKL25Z32VFT4) || \ defined(CPU_MKL25Z64VFT4) || defined(CPU_MKL25Z128VFT4) || defined(CPU_MKL25Z32VLH4) || defined(CPU_MKL25Z64VLH4) || \ defined(CPU_MKL25Z128VLH4) || defined(CPU_MKL25Z32VLK4) || defined(CPU_MKL25Z64VLK4) || defined(CPU_MKL25Z128VLK4) /* @brief Maximum PLL external reference divider value (max. value of register bit field C5[PRVDIV] increased by one). */ #define FSL_FEATURE_MCG_PLL_PRDIV_MAX (25) /* @brief VCO divider base value (multiply factor of register bit field C6[VDIV] zero value). */ #define FSL_FEATURE_MCG_PLL_VDIV_BASE (24) /* @brief Is PLL clock divided by 2 before MCG PLL/FLL clock selection in the SIM module. */ #define FSL_FEATURE_MCG_HAS_PLL_EXTRA_DIV (1) /* @brief Has 32kHz RTC external reference clock (register bits C8[LOCS1], C8[CME1] and C8[LOCRE1]). */ #define FSL_FEATURE_MCG_HAS_RTC_32K (0) /* @brief Has PLL1 external reference clock (registers C10, C11, C12, S2). */ #define FSL_FEATURE_MCG_HAS_PLL1 (0) /* @brief Has 48MHz internal oscillator. */ #define FSL_FEATURE_MCG_HAS_IRC_48M (0) /* @brief Has OSC1 external oscillator (registers C10, C11, C12, S2). */ #define FSL_FEATURE_MCG_HAS_OSC1 (0) /* @brief Has fast internal reference clock fine trim (register bit C2[FCFTRIM]). */ #define FSL_FEATURE_MCG_HAS_FCFTRIM (0) /* @brief Has PLL loss of lock reset (register bit C8[LOLRE]). */ #define FSL_FEATURE_MCG_HAS_LOLRE (1) /* @brief Has MCG OSC clock selection (register bit C7[OSCSEL]). */ #define FSL_FEATURE_MCG_USE_OSCSEL (0) /* @brief Has PLL external reference selection (register bits C5[PLLREFSEL0] and C11[PLLREFSEL1]). */ #define FSL_FEATURE_MCG_USE_PLLREFSEL (0) /* @brief TBD */ #define FSL_FEATURE_MCG_USE_SYSTEM_CLOCK (0) /* @brief Has phase-locked loop (PLL) (register C5 and bits C6[VDIV], C6[PLLS], C6[LOLIE0], S[PLLST], S[LOCK0], S[LOLS]). */ #define FSL_FEATURE_MCG_HAS_PLL (1) /* @brief PLL/OSC related register bit fields have PLL/OSC index in their name. */ #define FSL_FEATURE_MCG_HAS_PLL_OSC_INDEX (1) /* @brief Has frequency-locked loop (FLL) (register ATCVH, ATCVL and bits C1[IREFS], C1[FRDIV]). */ #define FSL_FEATURE_MCG_HAS_FLL (1) /* @brief Has PLL external to MCG (register C9). */ #define FSL_FEATURE_MCG_HAS_EXTERNAL_PLL (1) /* @brief Has crystal oscillator or external reference clock low power controls (register bits C2[HGO], C2[RANGE]). */ #define FSL_FEATURE_MCG_HAS_EXT_REF_LOW_POWER_CONTROL (1) /* @brief Has PLL/FLL selection as MCG output (register bit C6[PLLS]). */ #define FSL_FEATURE_MCG_HAS_PLL_FLL_SELECTION (1) /* @brief Has PLL output selection (PLL0/PLL1, PLL/external PLL) (register bit C11[PLLCS]). */ #define FSL_FEATURE_MCG_HAS_PLL_OUTPUT_SELECTION (0) /* @brief Has automatic trim machine (registers ATCVH, ATCVL and bits SC[ATMF], SC[ATMS], SC[ATME]). */ #define FSL_FEATURE_MCG_HAS_AUTO_TRIM_MACHINE (1) /* @brief Has external clock monitor (register bit C6[CME]). */ #define FSL_FEATURE_MCG_HAS_EXTERNAL_CLOCK_MONITOR (1) /* @brief Has low frequency internal reference clock (IRC) (registers LTRIMRNG, LFRIM, LSTRIM and bit MC[LIRC_DIV2]). */ #define FSL_FEATURE_MCG_HAS_LOW_FREQ_IRC (0) /* @brief Has high frequency internal reference clock (IRC) (registers HCTRIM, HTTRIM, HFTRIM and bit MC[HIRCEN]). */ #define FSL_FEATURE_MCG_HAS_HIGH_FREQ_IRC (0) #elif defined(CPU_MKL26Z256VLK4) || defined(CPU_MKL26Z128VLL4) || defined(CPU_MKL26Z256VLL4) || defined(CPU_MKL26Z128VMC4) || \ defined(CPU_MKL26Z256VMC4) || defined(CPU_MKL46Z128VLH4) || defined(CPU_MKL46Z256VLH4) || defined(CPU_MKL46Z128VLL4) || \ defined(CPU_MKL46Z256VLL4) || defined(CPU_MKL46Z128VMC4) || defined(CPU_MKL46Z256VMC4) /* @brief Maximum PLL external reference divider value (max. value of register bit field C5[PRVDIV] increased by one). */ #define FSL_FEATURE_MCG_PLL_PRDIV_MAX (25) /* @brief VCO divider base value (multiply factor of register bit field C6[VDIV] zero value). */ #define FSL_FEATURE_MCG_PLL_VDIV_BASE (24) /* @brief Is PLL clock divided by 2 before MCG PLL/FLL clock selection in the SIM module. */ #define FSL_FEATURE_MCG_HAS_PLL_EXTRA_DIV (1) /* @brief Has 32kHz RTC external reference clock (register bits C8[LOCS1], C8[CME1] and C8[LOCRE1]). */ #define FSL_FEATURE_MCG_HAS_RTC_32K (0) /* @brief Has PLL1 external reference clock (registers C10, C11, C12, S2). */ #define FSL_FEATURE_MCG_HAS_PLL1 (0) /* @brief Has 48MHz internal oscillator. */ #define FSL_FEATURE_MCG_HAS_IRC_48M (0) /* @brief Has OSC1 external oscillator (registers C10, C11, C12, S2). */ #define FSL_FEATURE_MCG_HAS_OSC1 (0) /* @brief Has fast internal reference clock fine trim (register bit C2[FCFTRIM]). */ #define FSL_FEATURE_MCG_HAS_FCFTRIM (1) /* @brief Has PLL loss of lock reset (register bit C8[LOLRE]). */ #define FSL_FEATURE_MCG_HAS_LOLRE (1) /* @brief Has MCG OSC clock selection (register bit C7[OSCSEL]). */ #define FSL_FEATURE_MCG_USE_OSCSEL (0) /* @brief Has PLL external reference selection (register bits C5[PLLREFSEL0] and C11[PLLREFSEL1]). */ #define FSL_FEATURE_MCG_USE_PLLREFSEL (0) /* @brief TBD */ #define FSL_FEATURE_MCG_USE_SYSTEM_CLOCK (0) /* @brief Has phase-locked loop (PLL) (register C5 and bits C6[VDIV], C6[PLLS], C6[LOLIE0], S[PLLST], S[LOCK0], S[LOLS]). */ #define FSL_FEATURE_MCG_HAS_PLL (1) /* @brief PLL/OSC related register bit fields have PLL/OSC index in their name. */ #define FSL_FEATURE_MCG_HAS_PLL_OSC_INDEX (1) /* @brief Has frequency-locked loop (FLL) (register ATCVH, ATCVL and bits C1[IREFS], C1[FRDIV]). */ #define FSL_FEATURE_MCG_HAS_FLL (1) /* @brief Has PLL external to MCG (register C9). */ #define FSL_FEATURE_MCG_HAS_EXTERNAL_PLL (1) /* @brief Has crystal oscillator or external reference clock low power controls (register bits C2[HGO], C2[RANGE]). */ #define FSL_FEATURE_MCG_HAS_EXT_REF_LOW_POWER_CONTROL (1) /* @brief Has PLL/FLL selection as MCG output (register bit C6[PLLS]). */ #define FSL_FEATURE_MCG_HAS_PLL_FLL_SELECTION (1) /* @brief Has PLL output selection (PLL0/PLL1, PLL/external PLL) (register bit C11[PLLCS]). */ #define FSL_FEATURE_MCG_HAS_PLL_OUTPUT_SELECTION (0) /* @brief Has automatic trim machine (registers ATCVH, ATCVL and bits SC[ATMF], SC[ATMS], SC[ATME]). */ #define FSL_FEATURE_MCG_HAS_AUTO_TRIM_MACHINE (1) /* @brief Has external clock monitor (register bit C6[CME]). */ #define FSL_FEATURE_MCG_HAS_EXTERNAL_CLOCK_MONITOR (1) /* @brief Has low frequency internal reference clock (IRC) (registers LTRIMRNG, LFRIM, LSTRIM and bit MC[LIRC_DIV2]). */ #define FSL_FEATURE_MCG_HAS_LOW_FREQ_IRC (0) /* @brief Has high frequency internal reference clock (IRC) (registers HCTRIM, HTTRIM, HFTRIM and bit MC[HIRCEN]). */ #define FSL_FEATURE_MCG_HAS_HIGH_FREQ_IRC (0) #elif defined(CPU_MKV31F256VLH12) || defined(CPU_MKV31F256VLL12) || defined(CPU_MKV31F512VLH12) || defined(CPU_MKV31F512VLL12) /* @brief Maximum PLL external reference divider value (max. value of register bit field C5[PRVDIV] increased by one). */ #define FSL_FEATURE_MCG_PLL_PRDIV_MAX (25) /* @brief VCO divider base value (multiply factor of register bit field C6[VDIV] zero value). */ #define FSL_FEATURE_MCG_PLL_VDIV_BASE (24) /* @brief Is PLL clock divided by 2 before MCG PLL/FLL clock selection in the SIM module. */ #define FSL_FEATURE_MCG_HAS_PLL_EXTRA_DIV (0) /* @brief Has 32kHz RTC external reference clock (register bits C8[LOCS1], C8[CME1] and C8[LOCRE1]). */ #define FSL_FEATURE_MCG_HAS_RTC_32K (0) /* @brief Has PLL1 external reference clock (registers C10, C11, C12, S2). */ #define FSL_FEATURE_MCG_HAS_PLL1 (0) /* @brief Has 48MHz internal oscillator. */ #define FSL_FEATURE_MCG_HAS_IRC_48M (1) /* @brief Has OSC1 external oscillator (registers C10, C11, C12, S2). */ #define FSL_FEATURE_MCG_HAS_OSC1 (0) /* @brief Has fast internal reference clock fine trim (register bit C2[FCFTRIM]). */ #define FSL_FEATURE_MCG_HAS_FCFTRIM (1) /* @brief Has PLL loss of lock reset (register bit C8[LOLRE]). */ #define FSL_FEATURE_MCG_HAS_LOLRE (1) /* @brief Has MCG OSC clock selection (register bit C7[OSCSEL]). */ #define FSL_FEATURE_MCG_USE_OSCSEL (1) /* @brief Has PLL external reference selection (register bits C5[PLLREFSEL0] and C11[PLLREFSEL1]). */ #define FSL_FEATURE_MCG_USE_PLLREFSEL (0) /* @brief TBD */ #define FSL_FEATURE_MCG_USE_SYSTEM_CLOCK (0) /* @brief Has phase-locked loop (PLL) (register C5 and bits C6[VDIV], C6[PLLS], C6[LOLIE0], S[PLLST], S[LOCK0], S[LOLS]). */ #define FSL_FEATURE_MCG_HAS_PLL (1) /* @brief PLL/OSC related register bit fields have PLL/OSC index in their name. */ #define FSL_FEATURE_MCG_HAS_PLL_OSC_INDEX (0) /* @brief Has frequency-locked loop (FLL) (register ATCVH, ATCVL and bits C1[IREFS], C1[FRDIV]). */ #define FSL_FEATURE_MCG_HAS_FLL (1) /* @brief Has PLL external to MCG (register C9). */ #define FSL_FEATURE_MCG_HAS_EXTERNAL_PLL (0) /* @brief Has crystal oscillator or external reference clock low power controls (register bits C2[HGO], C2[RANGE]). */ #define FSL_FEATURE_MCG_HAS_EXT_REF_LOW_POWER_CONTROL (1) /* @brief Has PLL/FLL selection as MCG output (register bit C6[PLLS]). */ #define FSL_FEATURE_MCG_HAS_PLL_FLL_SELECTION (1) /* @brief Has PLL output selection (PLL0/PLL1, PLL/external PLL) (register bit C11[PLLCS]). */ #define FSL_FEATURE_MCG_HAS_PLL_OUTPUT_SELECTION (0) /* @brief Has automatic trim machine (registers ATCVH, ATCVL and bits SC[ATMF], SC[ATMS], SC[ATME]). */ #define FSL_FEATURE_MCG_HAS_AUTO_TRIM_MACHINE (1) /* @brief Has external clock monitor (register bit C6[CME]). */ #define FSL_FEATURE_MCG_HAS_EXTERNAL_CLOCK_MONITOR (1) /* @brief Has low frequency internal reference clock (IRC) (registers LTRIMRNG, LFRIM, LSTRIM and bit MC[LIRC_DIV2]). */ #define FSL_FEATURE_MCG_HAS_LOW_FREQ_IRC (0) /* @brief Has high frequency internal reference clock (IRC) (registers HCTRIM, HTTRIM, HFTRIM and bit MC[HIRCEN]). */ #define FSL_FEATURE_MCG_HAS_HIGH_FREQ_IRC (0) #elif defined(CPU_MKV40F128VLH15) || defined(CPU_MKV40F128VLL15) || defined(CPU_MKV40F256VLH15) || defined(CPU_MKV40F256VLL15) || \ defined(CPU_MKV40F64VLH15) || defined(CPU_MKV43F128VLH15) || defined(CPU_MKV43F128VLL15) || defined(CPU_MKV43F64VLH15) || \ defined(CPU_MKV44F128VLH15) || defined(CPU_MKV44F128VLL15) || defined(CPU_MKV44F64VLH15) || defined(CPU_MKV45F128VLH15) || \ defined(CPU_MKV45F128VLL15) || defined(CPU_MKV45F256VLH15) || defined(CPU_MKV45F256VLL15) || defined(CPU_MKV46F128VLH15) || \ defined(CPU_MKV46F128VLL15) || defined(CPU_MKV46F256VLH15) || defined(CPU_MKV46F256VLL15) /* @brief Maximum PLL external reference divider value (max. value of register bit field C5[PRVDIV] increased by one). */ #define FSL_FEATURE_MCG_PLL_PRDIV_MAX (8) /* @brief VCO divider base value (multiply factor of register bit field C6[VDIV] zero value). */ #define FSL_FEATURE_MCG_PLL_VDIV_BASE (16) /* @brief Is PLL clock divided by 2 before MCG PLL/FLL clock selection in the SIM module. */ #define FSL_FEATURE_MCG_HAS_PLL_EXTRA_DIV (1) /* @brief Has 32kHz RTC external reference clock (register bits C8[LOCS1], C8[CME1] and C8[LOCRE1]). */ #define FSL_FEATURE_MCG_HAS_RTC_32K (0) /* @brief Has PLL1 external reference clock (registers C10, C11, C12, S2). */ #define FSL_FEATURE_MCG_HAS_PLL1 (0) /* @brief Has 48MHz internal oscillator. */ #define FSL_FEATURE_MCG_HAS_IRC_48M (0) /* @brief Has OSC1 external oscillator (registers C10, C11, C12, S2). */ #define FSL_FEATURE_MCG_HAS_OSC1 (0) /* @brief Has fast internal reference clock fine trim (register bit C2[FCFTRIM]). */ #define FSL_FEATURE_MCG_HAS_FCFTRIM (1) /* @brief Has PLL loss of lock reset (register bit C8[LOLRE]). */ #define FSL_FEATURE_MCG_HAS_LOLRE (1) /* @brief Has MCG OSC clock selection (register bit C7[OSCSEL]). */ #define FSL_FEATURE_MCG_USE_OSCSEL (0) /* @brief Has PLL external reference selection (register bits C5[PLLREFSEL0] and C11[PLLREFSEL1]). */ #define FSL_FEATURE_MCG_USE_PLLREFSEL (0) /* @brief TBD */ #define FSL_FEATURE_MCG_USE_SYSTEM_CLOCK (0) /* @brief Has phase-locked loop (PLL) (register C5 and bits C6[VDIV], C6[PLLS], C6[LOLIE0], S[PLLST], S[LOCK0], S[LOLS]). */ #define FSL_FEATURE_MCG_HAS_PLL (1) /* @brief PLL/OSC related register bit fields have PLL/OSC index in their name. */ #define FSL_FEATURE_MCG_HAS_PLL_OSC_INDEX (0) /* @brief Has frequency-locked loop (FLL) (register ATCVH, ATCVL and bits C1[IREFS], C1[FRDIV]). */ #define FSL_FEATURE_MCG_HAS_FLL (1) /* @brief Has PLL external to MCG (register C9). */ #define FSL_FEATURE_MCG_HAS_EXTERNAL_PLL (0) /* @brief Has crystal oscillator or external reference clock low power controls (register bits C2[HGO], C2[RANGE]). */ #define FSL_FEATURE_MCG_HAS_EXT_REF_LOW_POWER_CONTROL (1) /* @brief Has PLL/FLL selection as MCG output (register bit C6[PLLS]). */ #define FSL_FEATURE_MCG_HAS_PLL_FLL_SELECTION (1) /* @brief Has PLL output selection (PLL0/PLL1, PLL/external PLL) (register bit C11[PLLCS]). */ #define FSL_FEATURE_MCG_HAS_PLL_OUTPUT_SELECTION (0) /* @brief Has automatic trim machine (registers ATCVH, ATCVL and bits SC[ATMF], SC[ATMS], SC[ATME]). */ #define FSL_FEATURE_MCG_HAS_AUTO_TRIM_MACHINE (1) /* @brief Has external clock monitor (register bit C6[CME]). */ #define FSL_FEATURE_MCG_HAS_EXTERNAL_CLOCK_MONITOR (1) /* @brief Has low frequency internal reference clock (IRC) (registers LTRIMRNG, LFRIM, LSTRIM and bit MC[LIRC_DIV2]). */ #define FSL_FEATURE_MCG_HAS_LOW_FREQ_IRC (0) /* @brief Has high frequency internal reference clock (IRC) (registers HCTRIM, HTTRIM, HFTRIM and bit MC[HIRCEN]). */ #define FSL_FEATURE_MCG_HAS_HIGH_FREQ_IRC (0) #else #error "No valid CPU defined!" #endif #endif /* __FSL_MCG_FEATURES_H__ */ /******************************************************************************* * EOF ******************************************************************************/ ================================================ FILE: Zelig/mbed/TARGET_K64F/TARGET_Freescale/TARGET_KPSDK_MCUS/TARGET_KPSDK_CODE/hal/mcg/fsl_mcg_hal.h ================================================ /* * Copyright (c) 2013 - 2014, Freescale Semiconductor, Inc. * All rights reserved. * * Redistribution and use in source and binary forms, with or without modification, * are permitted provided that the following conditions are met: * * o Redistributions of source code must retain the above copyright notice, this list * of conditions and the following disclaimer. * * o Redistributions in binary form must reproduce the above copyright notice, this * list of conditions and the following disclaimer in the documentation and/or * other materials provided with the distribution. * * o Neither the name of Freescale Semiconductor, Inc. nor the names of its * contributors may be used to endorse or promote products derived from this * software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT 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. */ #if !defined(__FSL_MCG_HAL_H__) #define __FSL_MCG_HAL_H__ #include #include #include #include "fsl_device_registers.h" #include "fsl_mcg_features.h" /*! @addtogroup mcg_hal*/ /*! @{*/ /*! @file fsl_mcg_hal.h */ /******************************************************************************* * Definitions ******************************************************************************/ /*! @brief MCG constant definitions*/ enum _mcg_constant { kMcgConstant0 = (0u), kMcgConstant1 = (1u), kMcgConstant2 = (2u), kMcgConstant3 = (3u), kMcgConstant4 = (4u), kMcgConstant5 = (5u), kMcgConstant32 = (32u), kMcgConstant640 = (640u), kMcgConstant1280 = (1280u), kMcgConstant1920 = (1920u), kMcgConstant2560 = (2560u), kMcgConstant732 = (732u), kMcgConstant1464 = (1464u), kMcgConstant2197 = (2197u), kMcgConstant2929 = (2929u), kMcgConstantHex20 = (0x20u), kMcgConstantHex40 = (0x40u), kMcgConstantHex60 = (0x60u), kMcgConstantHex80 = (0x80u), kMcgConstantHexA0 = (0xA0u), kMcgConstantHexC0 = (0xC0u), kMcgConstantHexE0 = (0xE0u), kMcgConstant2000 = (2000u), kMcgConstant3000 = (3000u), kMcgConstant4000 = (4000u), kMcgConstant10000 = (10000u), kMcgConstant30000 = (30000u), kMcgConstant31250 = (31250u), kMcgConstant39063 = (39063u), kMcgConstant40000 = (40000u), kMcgConstant1250000 = (1250000u), kMcgConstant2500000 = (2500000u), kMcgConstant3000000 = (3000000u), kMcgConstant5000000 = (5000000u), kMcgConstant8000000 = (8000000u), kMcgConstant10000000 = (10000000u), kMcgConstant20000000 = (20000000u), kMcgConstant25000000 = (25000000u), kMcgConstant32000000 = (32000000u), kMcgConstant40000000 = (40000000u), kMcgConstant50000000 = (50000000u), kMcgConstant60000000 = (60000000u), kMcgConstant75000000 = (75000000u), kMcgConstant80000000 = (80000000u), kMcgConstant100000000 = (100000000u), kMcgConstant180000000 = (180000000u), kMcgConstant360000000 = (360000000u) }; /*! @brief MCG clock source select */ typedef enum _mcg_clock_select { kMcgClkSelOut, /* Output of FLL or PLLCS is selected(depends on PLLS bit) */ kMcgClkSelInternal, /* Internal reference clock is selected */ kMcgClkSelExternal, /* External reference clock is selected */ kMcgClkSelReserved } mcg_clock_select_t; /*! @brief MCG internal reference clock source select */ typedef enum _mcg_internal_ref_clock_source { kMcgInternalRefClkSrcExternal, /* External reference clock is selected */ kMcgInternalRefClkSrcSlow /* The slow internal reference clock is selected */ } mcg_internal_ref_clock_source_t; /*! @brief MCG frequency range select */ typedef enum _mcg_freq_range_select { kMcgFreqRangeSelLow, /* Low frequency range selected for the crystal OSC */ kMcgFreqRangeSelHigh, /* High frequency range selected for the crystal OSC */ kMcgFreqRangeSelVeryHigh, /* Very High frequency range selected for the crystal OSC */ kMcgFreqRangeSelVeryHigh1 /* Very High frequency range selected for the crystal OSC */ } mcg_freq_range_select_t; /*! @brief MCG high gain oscillator select */ typedef enum _mcg_high_gain_osc_select { kMcgHighGainOscSelLow, /* Configure crystal oscillator for low-power operation */ kMcgHighGainOscSelHigh /* Configure crystal oscillator for high-gain operation */ } mcg_high_gain_osc_select_t; /*! @brief MCG high gain oscillator select */ typedef enum _mcg_external_ref_clock_select { kMcgExternalRefClkSelExternal, /* External reference clock requested */ kMcgExternalRefClkSelOsc /* Oscillator requested */ } mcg_external_ref_clock_select_t; /*! @brief MCG low power select */ typedef enum _mcg_low_power_select { kMcgLowPowerSelNormal, /* FLL (or PLL) is not disabled in bypass modes */ kMcgLowPowerSelLowPower /* FLL (or PLL) is disabled in bypass modes (lower power) */ } mcg_low_power_select_t; /*! @brief MCG internal reference clock select */ typedef enum _mcg_internal_ref_clock_select { kMcgInternalRefClkSelSlow, /* Slow internal reference clock selected */ kMcgInternalRefClkSelFast /* Fast internal reference clock selected */ } mcg_internal_ref_clock_select_t; /*! @brief MCG DCO Maximum Frequency with 32.768 kHz Reference */ typedef enum _mcg_dmx32_select { kMcgDmx32Default, /* DCO has a default range of 25% */ kMcgDmx32Fine /* DCO is fine-tuned for maximum frequency with 32.768 kHz reference */ } mcg_dmx32_select_t; /*! @brief MCG DCO range select */ typedef enum _mcg_digital_controlled_osc_range_select { kMcgDigitalControlledOscRangeSelLow, /* Low frequency range */ kMcgDigitalControlledOscRangeSelMid, /* Mid frequency range*/ kMcgDigitalControlledOscRangeSelMidHigh, /* Mid-High frequency range */ kMcgDigitalControlledOscRangeSelHigh /* High frequency range */ } mcg_digital_controlled_osc_range_select_t; /*! @brief MCG PLL external reference clock select */ typedef enum _mcg_pll_external_ref_clk_select { kMcgPllExternalRefClkSelOsc0, /* Selects OSC0 clock source as its external reference clock */ kMcgPllExternalRefClkSelOsc1 /* Selects OSC1 clock source as its external reference clock */ } mcg_pll_external_ref_clk_select_t; /*! @brief MCG PLL select */ typedef enum _mcg_pll_select { kMcgPllSelFll, /* FLL is selected */ kMcgPllSelPllClkSel /* PLLCS output clock is selected */ } mcg_pll_select_t; /*! @brief MCG loss of lock status */ typedef enum _mcg_loss_of_lock_status { kMcgLossOfLockNotLost, /* PLL has not lost lock since LOLS 0 was last cleared */ kMcgLossOfLockLost /* PLL has lost lock since LOLS 0 was last cleared */ } mcg_loss_of_lock_status_t; /*! @brief MCG lock status */ typedef enum _mcg_lock_status { kMcgLockUnlocked, /* PLL is currently unlocked */ kMcgLockLocked /* PLL is currently locked */ } mcg_lock_status_t; /*! @brief MCG clock status */ typedef enum _mcg_pll_stat_status { kMcgPllStatFll, /* Source of PLLS clock is FLL clock */ kMcgPllStatPllClkSel /* Source of PLLS clock is PLLCS output clock */ } mcg_pll_stat_status_t; /*! @brief MCG iref status */ typedef enum _mcg_internal_ref_status { kMcgInternalRefStatExternal, /* FLL reference clock is the external reference clock */ kMcgInternalRefStatInternal /* FLL reference clock is the internal reference clock */ } mcg_internal_ref_status_t; /*! @brief MCG clock mode status */ typedef enum _mcg_clk_stat_status { kMcgClkStatFll, /* Output of the FLL is selected (reset default) */ kMcgClkStatInternalRef, /* Internal reference clock is selected */ kMcgClkStatExternalRef, /* External reference clock is selected */ kMcgClkStatPll /* Output of the PLL is selected */ } mcg_clk_stat_status_t; /*! @brief MCG ircst status */ typedef enum _mcg_internal_ref_clk_status { kMcgInternalRefClkStatSlow, /* internal reference clock is the slow clock (32 kHz IRC) */ kMcgInternalRefClkStatFast /* internal reference clock is the fast clock (2 MHz IRC) */ } mcg_internal_ref_clk_status_t; /*! @brief MCG auto trim fail status */ typedef enum _mcg_auto_trim_machine_fail_status { kMcgAutoTrimMachineNormal, /* Automatic Trim Machine completed normally */ kMcgAutoTrimMachineFail /* Automatic Trim Machine failed */ } mcg_auto_trim_machine_fail_status_t; /*! @brief MCG loss of clock status */ typedef enum _mcg_locs0_status { kMcgLocs0NotOccured, /* Loss of OSC0 has not occurred */ kMcgLocs0Occured /* Loss of OSC0 has occurred */ } mcg_locs0_status_t; /*! @brief MCG Automatic Trim Machine Select */ typedef enum _mcg_auto_trim_machine_select { kMcgAutoTrimMachineSel32k, /* 32 kHz Internal Reference Clock selected */ kMcgAutoTrimMachineSel4m /* 4 MHz Internal Reference Clock selected */ } mcg_auto_trim_machine_select_t; /*! @brief MCG OSC Clock Select */ typedef enum _mcg_oscsel_select { kMcgOscselOsc, /* Selects System Oscillator (OSCCLK) */ kMcgOscselRtc, /* Selects 32 kHz RTC Oscillator */ #if FSL_FEATURE_MCG_HAS_IRC_48M kMcgOscselIrc /* Selects 48 MHz IRC Oscillator */ #endif } mcg_oscsel_select_t; /*! @brief MCG loss of clock status */ typedef enum _mcg_loss_of_clk1_status { kMcgLossOfClk1NotOccured, /* Loss of RTC has not occurred */ kMcgLossOfClk1Occured /* Loss of RTC has occurred */ } mcg_loss_of_clk1_status_t; /*! @brief MCG PLLCS select */ typedef enum _mcg_pll_clk_select { kMcgPllClkSelPll0, /* PLL0 output clock is selected */ kMcgPllClkSelPll1, /* PLL1 output clock is selected */ } mcg_pll_clk_select_t; /*! @brief MCG loss of clock status */ typedef enum _mcg_locs2_status { kMcgLocs2NotOccured, /* Loss of OSC1 has not occurred */ kMcgLocs2Occured /* Loss of OSC1 has occurred */ } mcg_locs2_status_t; /******************************************************************************* * API ******************************************************************************/ #if defined(__cplusplus) extern "C" { #endif /* __cplusplus*/ /*! @name MCG out clock access API*/ /*@{*/ /*! * @brief Gets the current MCG FLL clock. * * This function returns the mcgfllclk value in frequency(Hertz) based on the * current MCG configurations and settings. FLL should be properly configured * in order to get the valid value. * * @param baseAddr Base address for current MCG instance. * @return value Frequency value in Hertz of the mcgpllclk. */ uint32_t CLOCK_HAL_GetFllRefClk(uint32_t baseAddr); /*! * @brief Gets the current MCG FLL clock. * * This function returns the mcgfllclk value in frequency(Hertz) based on the * current MCG configurations and settings. FLL should be properly configured * in order to get the valid value. * * @param baseAddr Base address for current MCG instance. * @return value Frequency value in Hertz of the mcgpllclk. */ uint32_t CLOCK_HAL_GetFllClk(uint32_t baseAddr); /*! * @brief Gets the current MCG PLL/PLL0 clock. * * This function returns the mcgpllclk/mcgpll0 value in frequency(Hertz) based * on the current MCG configurations and settings. PLL/PLL0 should be properly * configured in order to get the valid value. * * @param baseAddr Base address for current MCG instance. * @return value Frequency value in Hertz of the mcgpllclk or the mcgpll0clk. */ uint32_t CLOCK_HAL_GetPll0Clk(uint32_t baseAddr); #if FSL_FEATURE_MCG_HAS_PLL1 /*! * @brief Gets the current MCG PLL1 clock. * * This function returns the mcgpll1clk value in frequency (Hertz) based * on the current MCG configurations and settings. PLL1 should be properly configured * in order to get the valid value. * * @param baseAddr Base address for current MCG instance. * @return value Frequency value in Hertz of mcgpll1clk. */ uint32_t CLOCK_HAL_GetPll1Clk(uint32_t baseAddr); #endif /*! * @brief Gets the current MCG IR clock. * * This function returns the mcgirclk value in frequency (Hertz) based * on the current MCG configurations and settings. It does not check if the * mcgirclk is enabled or not, just calculate and return the value. * * @param baseAddr Base address for current MCG instance. * @return value Frequency value in Hertz of the mcgirclk. */ uint32_t CLOCK_HAL_GetInternalRefClk(uint32_t baseAddr); /*! * @brief Gets the current MCG out clock. * * This function returns the mcgoutclk value in frequency (Hertz) based on the * current MCG configurations and settings. The configuration should be * properly done in order to get the valid value. * * @param baseAddr Base address for current MCG instance. * @return value Frequency value in Hertz of mcgoutclk. */ uint32_t CLOCK_HAL_GetOutClk(uint32_t baseAddr); /*@}*/ /*! @name MCG control register access API*/ /*@{*/ /*! * @brief Sets the Clock Source Select * * This function selects the clock source for the MCGOUTCLK. * * @param baseAddr Base address for current MCG instance. * @param select Clock source selection * - 00: Output of FLL or PLLCS is selected(depends on PLLS control bit) * - 01: Internal reference clock is selected. * - 10: External reference clock is selected. * - 11: Reserved. */ static inline void CLOCK_HAL_SetClkSrcMode(uint32_t baseAddr, mcg_clock_select_t select) { BW_MCG_C1_CLKS(baseAddr, select); } /*! * @brief Gets the Clock Source Select. * * This function gets the select of the clock source for the MCGOUTCLK. * * @param baseAddr Base address for current MCG instance. * @return select Clock source selection */ static inline mcg_clock_select_t CLOCK_HAL_GetClkSrcMode(uint32_t baseAddr) { return (mcg_clock_select_t)BR_MCG_C1_CLKS(baseAddr); } /*! * @brief Sets the FLL External Reference Divider. * * This function sets the FLL External Reference Divider. * * @param baseAddr Base address for current MCG instance. * @param setting Divider setting */ static inline void CLOCK_HAL_SetFllExternalRefDivider(uint32_t baseAddr, uint8_t setting) { BW_MCG_C1_FRDIV(baseAddr, setting); } /*! * @brief Gets the FLL External Reference Divider. * * This function gets the FLL External Reference Divider. * * @param baseAddr Base address for current MCG instance. * @return setting Divider setting */ static inline uint8_t CLOCK_HAL_GetFllExternalRefDivider(uint32_t baseAddr) { return BR_MCG_C1_FRDIV(baseAddr); } /*! * @brief Sets the Internal Reference Select. * * This function selects the reference clock source for the FLL. * * @param baseAddr Base address for current MCG instance. * @param select Clock source select * - 0: External reference clock is selected * - 1: The slow internal reference clock is selected */ static inline void CLOCK_HAL_SetInternalRefSelMode(uint32_t baseAddr, mcg_internal_ref_clock_source_t select) { BW_MCG_C1_IREFS(baseAddr, select); } /*! * @brief Gets the Internal Reference Select * * This function gets the reference clock source for the FLL. * * @param baseAddr Base address for current MCG instance. * @return select Clock source select */ static inline mcg_internal_ref_clock_source_t CLOCK_HAL_GetInternalRefSelMode(uint32_t baseAddr) { return (mcg_internal_ref_clock_source_t)BR_MCG_C1_IREFS(baseAddr); } /*! * @brief Sets the CLKS, FRDIV and IREFS at the same time. * * This function sets the CLKS, FRDIV, and IREFS settings at the same time * in order keep the integrity of the clock switching. * * @param baseAddr Base address for current MCG instance. * @param clks Clock source select * @param frdiv FLL external reference divider select * @param irefs Internal reference select */ static inline void CLOCK_HAL_SetClksFrdivInternalRefSelect(uint32_t baseAddr, mcg_clock_select_t clks, uint8_t frdiv, mcg_internal_ref_clock_source_t irefs) { /* Set the required CLKS , FRDIV and IREFS values */ HW_MCG_C1_WR(baseAddr, (HW_MCG_C1_RD(baseAddr) & ~(BM_MCG_C1_CLKS | BM_MCG_C1_FRDIV | BM_MCG_C1_IREFS)) | (BF_MCG_C1_CLKS(clks) | BF_MCG_C1_FRDIV(frdiv) | BF_MCG_C1_IREFS(irefs))); } /*! * @brief Sets the Enable Internal Reference Clock setting. * * This function enables/disables the internal reference clock to use as the MCGIRCLK. * * @param baseAddr Base address for current MCG instance. * @params enable Enable or disable internal reference clock. * - true: MCGIRCLK active * - false: MCGIRCLK inactive */ static inline void CLOCK_HAL_SetInternalClkCmd(uint32_t baseAddr, bool enable) { BW_MCG_C1_IRCLKEN(baseAddr, enable ? 1 : 0); } /*! * @brief Gets the enable Internal Reference Clock setting. * * This function gets the reference clock enable setting. * * @param baseAddr Base address for current MCG instance. * @return enabled True if the internal reference clock is enabled. */ static inline bool CLOCK_HAL_GetInternalClkCmd(uint32_t baseAddr) { return BR_MCG_C1_IRCLKEN(baseAddr); } /*! * @brief Sets the Internal Reference Clock Stop Enable setting. * * This function controls whether or not the internal reference clock remains * enabled when the MCG enters Stop mode. * * @param baseAddr Base address for current MCG instance. * @params enable Enable or disable the internal reference clock stop setting. * - true: Internal reference clock is enabled in Stop mode if IRCLKEN is set * or if MCG is in FEI, FBI, or BLPI modes before entering Stop mode. * - false: Internal reference clock is disabled in Stop mode */ static inline void CLOCK_HAL_SetInternalRefStopCmd(uint32_t baseAddr, bool enable) { BW_MCG_C1_IREFSTEN(baseAddr, enable ? 1 : 0); } /*! * @brief Gets the Enable Internal Reference Clock setting. * * This function gets the Internal Reference Clock Stop Enable setting. * * @param baseAddr Base address for current MCG instance. * @return enabled True if internal reference clock stop is enabled. */ static inline bool CLOCK_HAL_GetInternalRefStopCmd(uint32_t baseAddr) { return BR_MCG_C1_IREFSTEN(baseAddr); } /*! * @brief Sets the Loss of Clock Reset Enable setting. * * This function determines whether an interrupt or a reset request is made following a loss * of the OSC0 external reference clock. The LOCRE0 only has an affect when CME0 is set. * * @param baseAddr Base address for current MCG instance. * @params enable Loss of Clock Reset Enable setting * - true: Generate a reset request on a loss of OSC0 external reference clock * - false: Interrupt request is generated on a loss of OSC0 external reference clock */ static inline void CLOCK_HAL_SetLossOfClkReset0Cmd(uint32_t baseAddr, bool enable) { BW_MCG_C2_LOCRE0(baseAddr, enable ? 1 : 0); } /*! * @brief Gets the Loss of Clock Reset Enable setting. * * This function gets the Loss of Clock Reset Enable setting. * * @param baseAddr Base address for current MCG instance. * @return enabled True if Loss of Clock Reset is enabled. */ static inline bool CLOCK_HAL_GetLossOfClkReset0Cmd(uint32_t baseAddr) { return BR_MCG_C2_LOCRE0(baseAddr); } #if FSL_FEATURE_MCG_HAS_FCFTRIM /*! * @brief Sets the Fast Internal Reference Clock Fine Trim setting. * * This function sets the Fast Internal Reference Clock Fine Trim setting. FCFTRIM * controls the smallest adjustment of the fast internal reference clock frequency. * Setting the FCFTRIM increases the period and clearing FCFTRIM decreases the period * by the smallest amount possible. If an FCFTRIM value is stored and non-volatile * memory is to be used, it is the user's responsibility to copy that value from the * non-volatile memory location to this bit. * * @param baseAddr Base address for current MCG instance. * @params setting Fast Internal Reference Clock Fine Trim setting */ static inline void CLOCK_HAL_SetFastInternalRefClkFineTrim(uint32_t baseAddr, uint8_t setting) { BW_MCG_C2_FCFTRIM(baseAddr, setting); } /*! * @brief Gets the Fast Internal Reference Clock Fine Trim setting. * * This function gets the Fast Internal Reference Clock Fine Trim setting. * * @param baseAddr Base address for current MCG instance. * @return setting Fast Internal Reference Clock Fine Trim setting */ static inline uint8_t CLOCK_HAL_GetFastInternalRefClkFineTrim(uint32_t baseAddr) { return BR_MCG_C2_FCFTRIM(baseAddr); } #endif /* FSL_FEATURE_MCG_HAS_FCFTRIM */ /*! * @brief Sets the Frequency Range Select. * * This function selects the frequency range for the crystal oscillator or an external * clock source. See the Oscillator (OSC) chapter for more details and the device * data sheet for the frequency ranges used. * * @param baseAddr Base address for current MCG instance. * @params select Frequency Range Select * - 00: Low frequency range selected for the crystal oscillator * - 01: High frequency range selected for the crystal oscillator * - 1X: Very high frequency range selected for the crystal oscillator */ static inline void CLOCK_HAL_SetRange0Mode(uint32_t baseAddr, mcg_freq_range_select_t select) { BW_MCG_C2_RANGE(baseAddr, select); } /*! * @brief Gets the Frequency Range Select. * * This function gets the Frequency Range Select. * * @param baseAddr Base address for current MCG instance. * @return select Frequency Range Select */ static inline mcg_freq_range_select_t CLOCK_HAL_GetRange0Mode(uint32_t baseAddr) { return (mcg_freq_range_select_t)BR_MCG_C2_RANGE(baseAddr); } /*! * @brief Sets the High Gain Oscillator Select. * * This function controls the crystal oscillator mode of operation. See the * Oscillator (OSC) chapter for more details. * * @param baseAddr Base address for current MCG instance. * @params select High Gain Oscillator Select. * - 0: Configure crystal oscillator for low-power operation * - 1: Configure crystal oscillator for high-gain operation */ static inline void CLOCK_HAL_SetHighGainOsc0Mode(uint32_t baseAddr, mcg_high_gain_osc_select_t select) { BW_MCG_C2_HGO(baseAddr, select); } /*! * @brief Gets the High Gain Oscillator Select. * * This function gets the High Gain Oscillator Select. * * @param baseAddr Base address for current MCG instance. * @return select High Gain Oscillator Select */ static inline mcg_high_gain_osc_select_t CLOCK_HAL_GetHighGainOsc0Mode(uint32_t baseAddr) { return (mcg_high_gain_osc_select_t)BR_MCG_C2_HGO(baseAddr); } /*! * @brief Sets the External Reference Select. * * This function selects the source for the external reference clock. * See the Oscillator (OSC) chapter for more details. * * @param baseAddr Base address for current MCG instance. * @params select External Reference Select * - 0: External reference clock requested * - 1: Oscillator requested */ static inline void CLOCK_HAL_SetExternalRefSel0Mode(uint32_t baseAddr, mcg_external_ref_clock_select_t select) { BW_MCG_C2_EREFS(baseAddr, select); } /*! * @brief Gets the External Reference Select. * * This function gets the External Reference Select. * * @param baseAddr Base address for current MCG instance. * @return select External Reference Select */ static inline mcg_external_ref_clock_select_t CLOCK_HAL_GetExternalRefSel0Mode(uint32_t baseAddr) { return (mcg_external_ref_clock_select_t)BR_MCG_C2_EREFS(baseAddr); } /*! * @brief Sets the Low Power Select. * * This function controls whether the FLL (or PLL) is disabled in the BLPI and the * BLPE modes. In the FBE or the PBE modes, setting this bit to 1 transitions the MCG * into the BLPE mode; in the FBI mode, setting this bit to 1 transitions the MCG into * the BLPI mode. In any other MCG mode, the LP bit has no affect.. * * @param baseAddr Base address for current MCG instance. * @params select Low Power Select * - 0: FLL (or PLL) is not disabled in bypass modes * - 1: FLL (or PLL) is disabled in bypass modes (lower power) */ static inline void CLOCK_HAL_SetLowPowerMode(uint32_t baseAddr, mcg_low_power_select_t select) { BW_MCG_C2_LP(baseAddr, select); } /*! * @brief Gets the Low Power Select. * * This function gets the Low Power Select. * * @param baseAddr Base address for current MCG instance. * @return select Low Power Select */ static inline mcg_low_power_select_t CLOCK_HAL_GetLowPowerMode(uint32_t baseAddr) { return (mcg_low_power_select_t)BR_MCG_C2_LP(baseAddr); } /*! * @brief Sets the Internal Reference Clock Select. * * This function selects between the fast or slow internal reference clock source. * * @param baseAddr Base address for current MCG instance. * @params select Low Power Select * - 0: Slow internal reference clock selected. * - 1: Fast internal reference clock selected. */ static inline void CLOCK_HAL_SetInternalRefClkSelMode(uint32_t baseAddr, mcg_internal_ref_clock_select_t select) { BW_MCG_C2_IRCS(baseAddr, select); } /*! * @brief Gets the Internal Reference Clock Select. * * This function gets the Internal Reference Clock Select. * * @param baseAddr Base address for current MCG instance. * @return select Internal Reference Clock Select */ static inline mcg_internal_ref_clock_select_t CLOCK_HAL_GetInternalRefClkSelMode(uint32_t baseAddr) { return (mcg_internal_ref_clock_select_t)BR_MCG_C2_IRCS(baseAddr); } /*! * @brief Sets the Slow Internal Reference Clock Trim Setting. * * This function controls the slow internal reference clock frequency by * controlling the slow internal reference clock period. The SCTRIM bits are * binary weighted (that is, bit 1 adjusts twice as much as bit 0). * Increasing the binary value increases the period, and decreasing the value * decreases the period. * An additional fine trim bit is available in the C4 register as the SCFTRIM bit. * Upon reset, this value is loaded with a factory trim value. * If an SCTRIM value stored in non-volatile memory is to be used, it is the user's * responsibility to copy that value from the non-volatile memory location to * this register. * * @param baseAddr Base address for current MCG instance. * @params setting Slow Internal Reference Clock Trim Setting */ static inline void CLOCK_HAL_SetSlowInternalRefClkTrim(uint32_t baseAddr, uint8_t setting) { BW_MCG_C3_SCTRIM(baseAddr, setting); } /*! * @brief Gets the Slow Internal Reference Clock Trim Setting. * * This function gets the Slow Internal Reference Clock Trim Setting. * * @param baseAddr Base address for current MCG instance. * @return setting Slow Internal Reference Clock Trim Setting */ static inline uint8_t CLOCK_HAL_GetSlowInternalRefClkTrim(uint32_t baseAddr) { return BR_MCG_C3_SCTRIM(baseAddr); } /*! * @brief Sets the DCO Maximum Frequency with 32.768 kHz Reference. * * This function controls whether or not the DCO frequency range * is narrowed to its maximum frequency with a 32.768 kHz reference. * * @param baseAddr Base address for current MCG instance. * @params setting DCO Maximum Frequency with 32.768 kHz Reference Setting * - 0: DCO has a default range of 25%. * - 1: DCO is fine-tuned for maximum frequency with 32.768 kHz reference. */ static inline void CLOCK_HAL_SetDmx32(uint32_t baseAddr, mcg_dmx32_select_t setting) { BW_MCG_C4_DMX32(baseAddr, setting); } /*! * @brief Gets the DCO Maximum Frequency with the 32.768 kHz Reference Setting. * * This function gets the DCO Maximum Frequency with 32.768 kHz Reference Setting. * * @param baseAddr Base address for current MCG instance. * @return setting DCO Maximum Frequency with 32.768 kHz Reference Setting */ static inline mcg_dmx32_select_t CLOCK_HAL_GetDmx32(uint32_t baseAddr) { return (mcg_dmx32_select_t)BR_MCG_C4_DMX32(baseAddr); } /*! * @brief Sets the DCO Range Select. * * This function selects the frequency range for the FLL output, DCOOUT. * When the LP bit is set, the writes to the DRS bits are ignored. The DRST read * field indicates the current frequency range for the DCOOUT. The DRST field does * not update immediately after a write to the DRS field due to internal * synchronization between the clock domains. See the DCO Frequency Range table * for more details. * * @param baseAddr Base address for current MCG instance. * @params setting DCO Range Select Setting * - 00: Low range (reset default). * - 01: Mid range. * - 10: Mid-high range. * - 11: High range. */ static inline void CLOCK_HAL_SetDigitalControlledOscRangeMode(uint32_t baseAddr, mcg_digital_controlled_osc_range_select_t setting) { BW_MCG_C4_DRST_DRS(baseAddr, setting); } /*! * @brief Gets the DCO Range Select Setting. * * This function gets the DCO Range Select Setting. * * @param baseAddr Base address for current MCG instance. * @return setting DCO Range Select Setting */ static inline mcg_digital_controlled_osc_range_select_t CLOCK_HAL_GetDigitalControlledOscRangeMode(uint32_t baseAddr) { return (mcg_digital_controlled_osc_range_select_t)BR_MCG_C4_DRST_DRS(baseAddr); } /*! * @brief Sets the Fast Internal Reference Clock Trim Setting. * * This function controls the fast internal reference clock frequency * by controlling the fast internal reference clock period. The FCTRIM * bits are binary weighted (that is, bit 1 adjusts twice as much as bit 0). * Increasing the binary value increases the period, and decreasing the * value decreases the period. * If an FCTRIM[3:0] value stored in non-volatile memory is to be used, it is * the user's responsibility to copy that value from the non-volatile memory location * to this register. * * @param baseAddr Base address for current MCG instance. * @params setting Fast Internal Reference Clock Trim Setting. */ static inline void CLOCK_HAL_SetFastInternalRefClkTrim(uint32_t baseAddr, uint8_t setting) { BW_MCG_C4_FCTRIM(baseAddr, setting); } /*! * @brief Gets the Fast Internal Reference Clock Trim Setting. * * This function gets the Fast Internal Reference Clock Trim Setting. * * @param baseAddr Base address for current MCG instance. * @return setting Fast Internal Reference Clock Trim Setting */ static inline uint8_t CLOCK_HAL_GetFastInternalRefClkTrim(uint32_t baseAddr) { return BR_MCG_C4_FCTRIM(baseAddr); } /*! * @brief Sets the Slow Internal Reference Clock Fine Trim Setting. * * This function controls the smallest adjustment of the slow internal * reference clock frequency. Setting the SCFTRIM increases the period and * clearing the SCFTRIM decreases the period by the smallest amount possible. * If an SCFTRIM value, stored in non-volatile memory, is to be used, it is * the user's responsibility to copy that value from the non-volatile memory * location to this bit. * * @param baseAddr Base address for current MCG instance. * @params setting Slow Internal Reference Clock Fine Trim Setting */ static inline void CLOCK_HAL_SetSlowInternalRefClkFineTrim(uint32_t baseAddr, uint8_t setting) { BW_MCG_C4_SCFTRIM(baseAddr, setting); } /*! * @brief Gets the Slow Internal Reference Clock Fine Trim Setting. * * This function gets the Slow Internal Reference Clock Fine Trim Setting. * * @param baseAddr Base address for current MCG instance. * @return setting Slow Internal Reference Clock Fine Trim Setting */ static inline uint8_t CLOCK_HAL_GetSlowInternalRefClkFineTrim(uint32_t baseAddr) { return BR_MCG_C4_SCFTRIM(baseAddr); } #if FSL_FEATURE_MCG_USE_PLLREFSEL /*! * @brief Sets the PLL0 External Reference Select Setting. * * This function selects the PLL0 external reference clock source. * * @param baseAddr Base address for current MCG instance. * @params setting PLL0 External Reference Select Setting * - 0: Selects OSC0 clock source as its external reference clock * - 1: Selects OSC1 clock source as its external reference clock */ static inline void CLOCK_HAL_SetPllRefSel0Mode(uint32_t baseAddr, mcg_pll_external_ref_clk_select_t setting) { BW_MCG_C5_PLLREFSEL0(baseAddr, setting); } /*! * @brief Gets the PLL0 External Reference Select Setting. * * This function gets the PLL0 External Reference Select Setting. * * @param baseAddr Base address for current MCG instance. * @return setting PLL0 External Reference Select Setting */ static inline mcg_pll_external_ref_clk_select_t CLOCK_HAL_GetPllRefSel0Mode(uint32_t baseAddr) { return (mcg_pll_external_ref_clk_select_t)BR_MCG_C5_PLLREFSEL0(baseAddr); } #endif /* FSL_FEATURE_MCG_USE_PLLREFSEL */ #if FSL_FEATURE_MCG_HAS_EXTERNAL_CLOCK_MONITOR /*! * @brief Sets the Clock Monitor Enable Setting. * * This function enables/disables the loss of clock monitoring circuit for * the OSC0 external reference mux select. The LOCRE0 bit determines whether an * interrupt or a reset request is generated following a loss of the OSC0 indication. * The CME0 bit should only be set to a logic 1 when the MCG is in an operational * mode that uses the external clock (FEE, FBE, PEE, PBE, or BLPE). Whenever the * CME0 bit is set to a logic 1, the value of the RANGE0 bits in the C2 register * should not be changed. CME0 bit should be set to a logic 0 before the MCG * enters any Stop mode. Otherwise, a reset request may occur while in Stop mode. * CME0 should also be set to a logic 0 before entering VLPR or VLPW power modes * if the MCG is in BLPE mode. * * @param baseAddr Base address for current MCG instance. * @params enable Clock Monitor Enable Setting * - true: External clock monitor is enabled for OSC0. * - false: External clock monitor is disabled for OSC0. */ static inline void CLOCK_HAL_SetClkMonitor0Cmd(uint32_t baseAddr, bool enable) { #if FSL_FEATURE_MCG_HAS_PLL BW_MCG_C6_CME0(baseAddr, enable ? 1 : 0); #else BW_MCG_C6_CME(baseAddr, enable ? 1 : 0); #endif } /*! * @brief Gets the Clock Monitor Enable Setting. * * This function gets the Clock Monitor Enable Setting. * * @param baseAddr Base address for current MCG instance. * @return enabled True if Clock Monitor is enabled */ static inline bool CLOCK_HAL_GetClkMonitor0Cmd(uint32_t baseAddr) { #if FSL_FEATURE_MCG_HAS_PLL return BR_MCG_C6_CME0(baseAddr); #else return BR_MCG_C6_CME(baseAddr); #endif } #endif #if FSL_FEATURE_MCG_HAS_PLL /*! * @brief Sets the PLL Clock Enable Setting. * * This function enables/disables the PLL0 independent of the PLLS and enables the PLL0 * clock to use as the MCGPLL0CLK and the MCGPLL0CLK2X. (PRDIV0 needs to be programmed to * the correct divider to generate a PLL1 reference clock in a valid reference range * prior to setting the PLLCLKEN0 bit). Setting PLLCLKEN0 enables the external * oscillator selected by REFSEL if not already enabled. Whenever the PLL0 is being * enabled with the PLLCLKEN0 bit, and the external oscillator is being used * as the reference clock, the OSCINIT 0 bit should be checked to make sure it is set. * * @param baseAddr Base address for current MCG instance. * @params enable PLL Clock Enable Setting * - true: MCGPLL0CLK and MCGPLL0CLK2X are active * - false: MCGPLL0CLK and MCGPLL0CLK2X are inactive */ static inline void CLOCK_HAL_SetPllClk0Cmd(uint32_t baseAddr, bool enable) { BW_MCG_C5_PLLCLKEN0(baseAddr, enable ? 1 : 0); } /*! * @brief Gets the PLL Clock Enable Setting. * * This function gets the PLL Clock Enable Setting. * * @param baseAddr Base address for current MCG instance. * @return enabled True if PLL0 PLL Clock is enabled. */ static inline bool CLOCK_HAL_GetPllClk0Cmd(uint32_t baseAddr) { return BR_MCG_C5_PLLCLKEN0(baseAddr); } /*! * @brief Sets the PLL0 Stop Enable Setting. * * This function enables/disables the PLL0 Clock during a Normal Stop (In Low * Power Stop mode, the PLL0 clock gets disabled even if PLLSTEN0=1). In all other * power modes, the PLLSTEN0 bit has no affect and does not enable the PLL0 Clock * to run if it is written to 1. * * @param baseAddr Base address for current MCG instance. * @params enable PLL0 Stop Enable Setting * - true: MCGPLL0CLK and MCGPLL0CLK2X are enabled if system is in * Normal Stop mode. * - false: MCGPLL0CLK and MCGPLL0CLK2X are disabled in any of the * Stop modes. */ static inline void CLOCK_HAL_SetPllStat0Cmd(uint32_t baseAddr, bool enable) { BW_MCG_C5_PLLSTEN0(baseAddr, enable ? 1 : 0); } /*! * @brief Gets the PLL0 Stop Enable Setting. * * This function gets the PLL0 Stop Enable Setting. * * @param baseAddr Base address for current MCG instance. * @return enabled True if the PLL0 Stop is enabled. */ static inline bool CLOCK_HAL_GetPllStat0Cmd(uint32_t baseAddr) { return BR_MCG_C5_PLLSTEN0(baseAddr); } /*! * @brief Sets the PLL0 External Reference Divider Setting. * * This function selects the amount to divide down the external reference * clock for the PLL0. The resulting frequency must be in a valid reference * range. After the PLL0 is enabled, (by setting either PLLCLKEN0 or PLLS), the * PRDIV0 value must not be changed when LOCK0 is zero. * * @param baseAddr Base address for current MCG instance. * @params setting PLL0 External Reference Divider Setting */ static inline void CLOCK_HAL_SetPllExternalRefDivider0(uint32_t baseAddr, uint8_t setting) { BW_MCG_C5_PRDIV0(baseAddr, setting); } /*! * @brief Gets the PLL0 External Reference Divider Setting. * * This function gets the PLL0 External Reference Divider Setting. * * @param baseAddr Base address for current MCG instance. * @return setting PLL0 External Reference Divider Setting */ static inline uint8_t CLOCK_HAL_GetPllExternalRefDivider0(uint32_t baseAddr) { return BR_MCG_C5_PRDIV0(baseAddr); } /*! * @brief Sets the Loss of Lock Interrupt Enable Setting. * * This function determine whether an interrupt request is made following a loss * of lock indication. This bit only has an effect when LOLS 0 is set. * * @param baseAddr Base address for current MCG instance. * @params enable Loss of Lock Interrupt Enable Setting * - true: Generate an interrupt request on loss of lock. * - false: No interrupt request is generated on loss of lock. */ static inline void CLOCK_HAL_SetLossOfClkInt0Cmd(uint32_t baseAddr, bool enable) { BW_MCG_C6_LOLIE0(baseAddr, enable ? 1 : 0); } /*! * @brief Gets the Loss of the Lock Interrupt Enable Setting. * * This function gets the Loss of the Lock Interrupt Enable Setting. * * @param baseAddr Base address for current MCG instance. * @return enabled True if the Loss of Lock Interrupt is enabled. */ static inline bool CLOCK_HAL_GetLossOfClkInt0Cmd(uint32_t baseAddr) { return BR_MCG_C6_LOLIE0(baseAddr); } /*! * @brief Sets the PLL Select Setting. * * This function controls whether the PLLCS or FLL output is selected as the * MCG source when CLKS[1:0]=00. If the PLLS bit is cleared and PLLCLKEN0 and * PLLCLKEN1 is not set, the PLLCS output clock is disabled in all modes. If the * PLLS is set, the FLL is disabled in all modes. * * @param baseAddr Base address for current MCG instance. * @params setting PLL Select Setting * - 0: FLL is selected. * - 1: PLLCS output clock is selected (PRDIV0 bits of PLL in * control need to be programmed to the correct divider to * generate a PLL reference clock in the range of 1 - 32 MHz * prior to setting the PLLS bit). */ static inline void CLOCK_HAL_SetPllSelMode(uint32_t baseAddr, mcg_pll_select_t setting) { BW_MCG_C6_PLLS(baseAddr, setting); } /*! * @brief Gets the PLL Select Setting. * * This function gets the PLL Select Setting. * * @param baseAddr Base address for current MCG instance. * @return setting PLL Select Setting */ static inline mcg_pll_select_t CLOCK_HAL_GetPllSelMode(uint32_t baseAddr) { return (mcg_pll_select_t)BR_MCG_C6_PLLS(baseAddr); } /*! * @brief Sets the VCO0 Divider Setting. * * This function selects the amount to divide the VCO output of the PLL0. * The VDIV0 bits establish the multiplication factor (M) applied to the * reference clock frequency. After the PLL0 is enabled (by setting either * PLLCLKEN0 or PLLS), the VDIV0 value must not be changed when LOCK0 is zero. * * @param baseAddr Base address for current MCG instance. * @params setting VCO0 Divider Setting */ static inline void CLOCK_HAL_SetVoltCtrlOscDivider0(uint32_t baseAddr, uint8_t setting) { BW_MCG_C6_VDIV0(baseAddr, setting); } /*! * @brief Gets the VCO0 Divider Setting. * * This function gets the VCO0 Divider Setting. * * @param baseAddr Base address for current MCG instance. * @return setting VCO0 Divider Setting */ static inline uint8_t CLOCK_HAL_GetVoltCtrlOscDivider0(uint32_t baseAddr) { return BR_MCG_C6_VDIV0(baseAddr); } /*! * @brief Gets the Loss of the Lock Status. * * This function gets the Loss of Lock Status. This bit is a sticky bit indicating * the lock status for the PLL. LOLS 0 is set if after acquiring lock, the PLL * output frequency has fallen outside the lock exit frequency tolerance, D unl . * LOLIE 0 determines whether an interrupt request is made when LOLS 0 is set. * This bit is cleared by reset or by writing a logic 1 to it when set. Writing a * logic 0 to this bit has no effect. * * @param baseAddr Base address for current MCG instance. * @return status Loss of Lock Status * - 0: PLL has not lost lock since LOLS 0 was last cleared * - 1: PLL has lost lock since LOLS 0 was last cleared */ static inline mcg_loss_of_lock_status_t CLOCK_HAL_GetLossOfLock0Mode(uint32_t baseAddr) { return (mcg_loss_of_lock_status_t)BR_MCG_S_LOLS0(baseAddr); } /*! * @brief Gets the Lock Status. * * This function gets the Lock Status. This bit indicates whether the PLL0 has * acquired the lock. Lock detection is disabled when not operating in either the PBE or the * PEE mode unless PLLCLKEN0=1 and the MCG is not configured in the BLPI or the BLPE mode. * While the PLL0 clock is locking to the desired frequency, MCGPLL0CLK and * MCGPLL0CLK2X are gated off until the LOCK0 bit gets asserted. If the lock * status bit is set, changing the value of the PRDIV0[2:0] bits in the C5 register * or the VDIV0[4:0] bits in the C6 register causes the lock status bit to clear * and stay cleared until the PLL0 has reacquired the lock. The loss of the PLL0 reference * clock also causes the LOCK0 bit to clear until the PLL0 has an entry into the LLS, * VLPS, or a regular Stop with PLLSTEN0=0 also causes the lock status bit to clear * and stay cleared until the stop mode is exited and the PLL0 has reacquired the lock. * Any time the PLL0 is enabled and the LOCK0 bit is cleared, the MCGPLL0CLK and * MCGPLL0CLK2X are gated off until the LOCK0 bit is reasserted. * * @param baseAddr Base address for current MCG instance. * @return status Lock Status * - 0: PLL is currently unlocked * - 1: PLL is currently locked */ static inline mcg_lock_status_t CLOCK_HAL_GetLock0Mode(uint32_t baseAddr) { return (mcg_lock_status_t)BR_MCG_S_LOCK0(baseAddr); } /*! * @brief Gets the PLL Select Status. * * This function gets the PLL Select Status. This bit indicates the clock source * selected by PLLS . The PLLST bit does not update immediately after a write to * the PLLS bit due to the internal synchronization between the clock domains. * * @param baseAddr Base address for current MCG instance. * @return status PLL Select Status * - 0: Source of PLLS clock is FLL clock. * - 1: Source of PLLS clock is PLLCS output clock. */ static inline mcg_pll_stat_status_t CLOCK_HAL_GetPllStatMode(uint32_t baseAddr) { return (mcg_pll_stat_status_t)BR_MCG_S_PLLST(baseAddr); } #endif /*! * @brief Gets the Internal Reference Status. * * This function gets the Internal Reference Status. This bit indicates the current * source for the FLL reference clock. The IREFST bit does not update immediately * after a write to the IREFS bit due to internal synchronization between the clock * domains. * * @param baseAddr Base address for current MCG instance. * @return status Internal Reference Status * - 0: Source of FLL reference clock is the external reference clock. * - 1: Source of FLL reference clock is the internal reference clock. */ static inline mcg_internal_ref_status_t CLOCK_HAL_GetInternalRefStatMode(uint32_t baseAddr) { return (mcg_internal_ref_status_t)BR_MCG_S_IREFST(baseAddr); } /*! * @brief Gets the Clock Mode Status. * * This function gets the Clock Mode Status. These bits indicate the current clock mode. * The CLKST bits do not update immediately after a write to the CLKS bits due to * internal synchronization between clock domains. * * @param baseAddr Base address for current MCG instance. * @return status Clock Mode Status * - 00: Output of the FLL is selected (reset default). * - 01: Internal reference clock is selected. * - 10: External reference clock is selected. * - 11: Output of the PLL is selected. */ static inline mcg_clk_stat_status_t CLOCK_HAL_GetClkStatMode(uint32_t baseAddr) { return (mcg_clk_stat_status_t)BR_MCG_S_CLKST(baseAddr); } /*! * @brief Gets the OSC Initialization Status. * * This function gets the OSC Initialization Status. This bit, which resets to 0, is set * to 1 after the initialization cycles of the crystal oscillator clock have completed. * After being set, the bit is cleared to 0 if the OSC is subsequently disabled. See the * OSC module's detailed description for more information. * * @param baseAddr Base address for current MCG instance. * @return status OSC Initialization Status */ static inline uint8_t CLOCK_HAL_GetOscInit0(uint32_t baseAddr) { return BR_MCG_S_OSCINIT0(baseAddr); } /*! * @brief Gets the Internal Reference Clock Status. * * This function gets the Internal Reference Clock Status. The IRCST bit indicates the * current source for the internal reference clock select clock (IRCSCLK). The IRCST bit * does not update immediately after a write to the IRCS bit due to the internal * synchronization between clock domains. The IRCST bit is only updated if the * internal reference clock is enabled, either by the MCG being in a mode that uses the * IRC or by setting the C1[IRCLKEN] bit. * * @param baseAddr Base address for current MCG instance. * @return status Internal Reference Clock Status * - 0: Source of internal reference clock is the slow clock (32 kHz IRC). * - 1: Source of internal reference clock is the fast clock (2 MHz IRC). */ static inline mcg_internal_ref_clk_status_t CLOCK_HAL_GetInternalRefClkStatMode(uint32_t baseAddr) { return (mcg_internal_ref_clk_status_t)BR_MCG_S_IRCST(baseAddr); } /*! * @brief Gets the Automatic Trim machine Fail Flag. * * This function gets the Automatic Trim machine Fail Flag. This Fail flag for the * Automatic Trim Machine (ATM). This bit asserts when the Automatic Trim Machine is * enabled (ATME=1) and a write to the C1, C3, C4, and SC registers is detected or the MCG * enters into any Stop mode. A write to ATMF clears the flag. * * @param baseAddr Base address for current MCG instance. * @return flag Automatic Trim machine Fail Flag * - 0: Automatic Trim Machine completed normally. * - 1: Automatic Trim Machine failed. */ static inline mcg_auto_trim_machine_fail_status_t CLOCK_HAL_GetAutoTrimMachineFailMode(uint32_t baseAddr) { return (mcg_auto_trim_machine_fail_status_t)BR_MCG_SC_ATMF(baseAddr); } /*! * @brief Sets the Automatic Trim machine Fail Flag. * * This function clears the ATMF flag. * * @param baseAddr Base address for current MCG instance. */ static inline void CLOCK_HAL_SetAutoTrimMachineFail(uint32_t baseAddr) { BW_MCG_SC_ATMF(baseAddr, 1); } /*! * @brief Gets the OSC0 Loss of Clock Status. * * This function gets the OSC0 Loss of Clock Status. The LOCS0 indicates when a loss of * OSC0 reference clock has occurred. The LOCS0 bit only has an effect when CME0 is set. * This bit is cleared by writing a logic 1 to it when set. * * @param baseAddr Base address for current MCG instance. * @return status OSC0 Loss of Clock Status * - 0: Loss of OSC0 has not occurred. * - 1: Loss of OSC0 has occurred. */ static inline mcg_locs0_status_t CLOCK_HAL_GetLocs0Mode(uint32_t baseAddr) { return (mcg_locs0_status_t)BR_MCG_SC_LOCS0(baseAddr); } /*! * @brief Sets the Automatic Trim Machine Enable Setting. * * This function enables/disables the Auto Trim Machine to start automatically * trimming the selected Internal Reference Clock. * ATME de-asserts after the Auto Trim Machine has completed trimming all trim bits * of the IRCS clock selected by the ATMS bit. * Writing to C1, C3, C4, and SC registers or entering Stop mode aborts the auto * trim operation and clears this bit. * * @param baseAddr Base address for current MCG instance. * @params enable Automatic Trim Machine Enable Setting * - true: Auto Trim Machine enabled * - false: Auto Trim Machine disabled */ static inline void CLOCK_HAL_SetAutoTrimMachineCmd(uint32_t baseAddr, bool enable) { BW_MCG_SC_ATME(baseAddr, enable ? 1 : 0); } /*! * @brief Gets the Automatic Trim Machine Enable Setting. * * This function gets the Automatic Trim Machine Enable Setting. * * @param baseAddr Base address for current MCG instance. * @return enabled True if Automatic Trim Machine is enabled */ static inline bool CLOCK_HAL_GetAutoTrimMachineCmd(uint32_t baseAddr) { return BR_MCG_SC_ATME(baseAddr); } /*! * @brief Sets the Automatic Trim Machine Select Setting. * * This function selects the IRCS clock for Auto Trim Test. * * @param baseAddr Base address for current MCG instance. * @params setting Automatic Trim Machine Select Setting * - 0: 32 kHz Internal Reference Clock selected * - 1: 4 MHz Internal Reference Clock selected */ static inline void CLOCK_HAL_SetAutoTrimMachineSelMode(uint32_t baseAddr, mcg_auto_trim_machine_select_t setting) { BW_MCG_SC_ATMS(baseAddr, setting); } /*! * @brief Gets the Automatic Trim Machine Select Setting. * * This function gets the Automatic Trim Machine Select Setting. * * @param baseAddr Base address for current MCG instance. * @return setting Automatic Trim Machine Select Setting */ static inline mcg_auto_trim_machine_select_t CLOCK_HAL_GetAutoTrimMachineSelMode(uint32_t baseAddr) { return (mcg_auto_trim_machine_select_t)BR_MCG_SC_ATMS(baseAddr); } /*! * @brief Sets the FLL Filter Preserve Enable Setting. * * This function sets the FLL Filter Preserve Enable. This bit prevents the * FLL filter values from resetting allowing the FLL output frequency to remain the * same during the clock mode changes where the FLL/DCO output is still valid. * (Note: This requires that the FLL reference frequency remain the same as * the value prior to the new clock mode switch. Otherwise, the FLL filter and the frequency * values change.) * * @param baseAddr Base address for current MCG instance. * @params enable FLL Filter Preserve Enable Setting * - true: FLL filter and FLL frequency retain their previous values * during new clock mode change * - false: FLL filter and FLL frequency will reset on changes to correct * clock mode */ static inline void CLOCK_HAL_SetFllFilterPreserveCmd(uint32_t baseAddr, bool enable) { BW_MCG_SC_FLTPRSRV(baseAddr, enable ? 1 : 0); } /*! * @brief Gets the FLL Filter Preserve Enable Setting. * * This function gets the FLL Filter Preserve Enable Setting. * * @param baseAddr Base address for current MCG instance. * @return enabled True if FLL Filter Preserve is enabled. */ static inline bool CLOCK_HAL_GetFllFilterPreserveCmd(uint32_t baseAddr) { return BR_MCG_SC_FLTPRSRV(baseAddr); } /*! * @brief Sets the Fast Clock Internal Reference Divider Setting. * * This function selects the amount to divide down the fast internal reference * clock. The resulting frequency is in the range 31.25 kHz to 4 MHz. * (Note: Changing the divider when the Fast IRC is enabled is not supported). * * @param baseAddr Base address for current MCG instance. * @params setting Fast Clock Internal Reference Divider Setting */ static inline void CLOCK_HAL_SetFastClkInternalRefDivider(uint32_t baseAddr, uint8_t setting) { BW_MCG_SC_FCRDIV(baseAddr, setting); } /*! * @brief Gets the Fast Clock Internal Reference Divider Setting. * * This function gets the Fast Clock Internal Reference Divider Setting. * * @param baseAddr Base address for current MCG instance. * @return setting Fast Clock Internal Reference Divider Setting */ static inline uint8_t CLOCK_HAL_GetFastClkInternalRefDivider(uint32_t baseAddr) { return BR_MCG_SC_FCRDIV(baseAddr); } /*! * @brief Sets the ATM Compare Value High Setting. * * This function sets the ATM compare value high setting. The values are used by the * Auto Trim Machine to compare and adjust the Internal Reference trim values during the ATM * SAR conversion. * * @param baseAddr Base address for current MCG instance. * @params setting ATM Compare Value High Setting */ static inline void CLOCK_HAL_SetAutoTrimMachineCompValHigh(uint32_t baseAddr, uint8_t setting) { BW_MCG_ATCVH_ATCVH(baseAddr, setting); } /*! * @brief Gets the ATM Compare Value High Setting. * * This function gets the ATM Compare Value High Setting. * * @param baseAddr Base address for current MCG instance. * @return setting ATM Compare Value High Setting */ static inline uint8_t CLOCK_HAL_GetAutoTrimMachineCompValHigh(uint32_t baseAddr) { return BR_MCG_ATCVH_ATCVH(baseAddr); } /*! * @brief Sets the ATM Compare Value Low Setting. * * This function sets the ATM compare value low setting. The values are used by the * Auto Trim Machine to compare and adjust Internal Reference trim values during the ATM * SAR conversion. * * @param baseAddr Base address for current MCG instance. * @params setting ATM Compare Value Low Setting */ static inline void CLOCK_HAL_SetAutoTrimMachineCompValLow(uint32_t baseAddr, uint8_t setting) { BW_MCG_ATCVL_ATCVL(baseAddr, setting); } /*! * @brief Gets the ATM Compare Value Low Setting. * * This function gets the ATM Compare Value Low Setting. * * @param baseAddr Base address for current MCG instance. * @return setting ATM Compare Value Low Setting */ static inline uint8_t CLOCK_HAL_GetAutoTrimMachineCompValLow(uint32_t baseAddr) { return BR_MCG_ATCVL_ATCVL(baseAddr); } #if FSL_FEATURE_MCG_USE_OSCSEL /*! * @brief Sets the MCG OSC Clock Select Setting. * * This function selects the MCG FLL external reference clock. * * @param baseAddr Base address for current MCG instance. * @params setting MCG OSC Clock Select Setting * - 0: Selects System Oscillator (OSCCLK). * - 1: Selects 32 kHz RTC Oscillator. */ static inline void CLOCK_HAL_SetOscselMode(uint32_t baseAddr, mcg_oscsel_select_t setting) { BW_MCG_C7_OSCSEL(baseAddr, setting); } /*! * @brief Gets the MCG OSC Clock Select Setting. * * This function gets the MCG OSC Clock Select Setting. * * @param baseAddr Base address for current MCG instance. * @return setting MCG OSC Clock Select Setting */ static inline mcg_oscsel_select_t CLOCK_HAL_GetOscselMode(uint32_t baseAddr) { return (mcg_oscsel_select_t)BR_MCG_C7_OSCSEL(baseAddr); } #endif /* FSL_FEATURE_MCG_USE_OSCSEL */ #if FSL_FEATURE_MCG_HAS_LOLRE /*! * @brief Sets the PLL Loss of Lock Reset Enable Setting. * * This function determines whether an interrupt or a reset request is made * following a PLL loss of lock. * * @param baseAddr Base address for current MCG instance. * @params enable PLL Loss of Lock Reset Enable Setting * - true: Generate a reset request on a PLL loss of lock indication. * - false: Interrupt request is generated on a PLL loss of lock * indication. The PLL loss of lock interrupt enable bit * must also be set to generate the interrupt request. */ static inline void CLOCK_HAL_SetLossOfClkResetCmd(uint32_t baseAddr, bool enable) { BW_MCG_C8_LOLRE(baseAddr, enable ? 1 : 0); } /*! * @brief Gets the PLL Loss of Lock Reset Enable Setting. * * This function gets the PLL Loss of Lock Reset Enable Setting. * * @param baseAddr Base address for current MCG instance. * @return enabled True if the PLL Loss of Lock Reset is enabled. */ static inline bool CLOCK_HAL_GetLossOfClkResetCmd(uint32_t baseAddr) { return BR_MCG_C8_LOLRE(baseAddr); } #endif /* FSL_FEATURE_MCG_HAS_LOLRE */ #if FSL_FEATURE_MCG_HAS_RTC_32K /*! * @brief Sets the Loss of Clock Reset Enable Setting. * * This function determines whether an interrupt or a reset request is made following * a loss of the RTC external reference clock. The LOCRE1 only has an affect when CME1 * is set. * * @param baseAddr Base address for current MCG instance. * @params enable Loss of Clock Reset Enable Setting * - true: Generate a reset request on a loss of RTC external reference clock. * - false: Interrupt request is generated on a loss of RTC external * reference clock. */ static inline void CLOCK_HAL_SetLossClkReset1Cmd(uint32_t baseAddr, bool enable) { BW_MCG_C8_LOCRE1(baseAddr, enable ? 1 : 0); } /*! * @brief Gets the Loss of Clock Reset Enable Setting. * * This function gets the Loss of Clock Reset Enable Setting. * * @param baseAddr Base address for current MCG instance. * @return enabled True if Loss of Clock Reset is enabled. */ static inline bool CLOCK_HAL_GetLossClkReset1Cmd(uint32_t baseAddr) { return BR_MCG_C8_LOCRE1(baseAddr); } /*! * @brief Sets the Clock Monitor Enable1 Setting. * * This function enables/disables the loss of the clock monitoring circuit for the * output of the RTC external reference clock. The LOCRE1 bit determines whether an * interrupt or a reset request is generated following a loss of the RTC clock indication. * The CME1 bit should only be set to a logic 1 when the MCG is in an operational mode * that uses the external clock (FEE, FBE, PEE, PBE, or BLPE). CME1 bit must be set to * a logic 0 before the MCG enters any Stop mode. Otherwise, a reset request may occur * while in Stop mode. CME1 should also be set to a logic 0 before entering VLPR or * VLPW power modes if the MCG is in BLPE mode. * * @param baseAddr Base address for current MCG instance. * @params enable Clock Monitor Enable1 Setting * - true: External clock monitor is enabled for RTC clock. * - false: External clock monitor is disabled for RTC clock. */ static inline void CLOCK_HAL_SetClkMonitor1Cmd(uint32_t baseAddr, bool enable) { BW_MCG_C8_CME1(baseAddr, enable ? 1 : 0); } /*! * @brief Gets the Clock Monitor Enable1 Setting. * * This function gets the Clock Monitor Enable1 Setting. * * @param baseAddr Base address for current MCG instance. * @return enabled True if Clock Monitor Enable1 is enabled */ static inline bool CLOCK_HAL_GetClkMonitor1Cmd(uint32_t baseAddr) { return BR_MCG_C8_CME1(baseAddr); } /*! * @brief Gets the RTC Loss of Clock Status. * * This function gets the RTC Loss of Clock Status. This bit indicates when a loss * of clock has occurred. This bit is cleared by writing a logic 1 to it when set. * * @param baseAddr Base address for current MCG instance. * @return status RTC Loss of Clock Status * - 0: Loss of RTC has not occurred * - 1: Loss of RTC has occurred */ static inline mcg_loss_of_clk1_status_t CLOCK_HAL_GetLossOfClk1Mode(uint32_t baseAddr) { return (mcg_loss_of_clk1_status_t)BR_MCG_C8_LOCS1(baseAddr); } #endif /* FSL_FEATURE_MCG_HAS_RTC_32K */ #if FSL_FEATURE_MCG_USE_PLLREFSEL /*! * @brief Sets the OSC1 Loss of Clock Reset Enable Setting. * * This function determines whether an interrupt or reset request is made following * a loss of OSC1 external reference clock. The LOCRE2 only has an affect when * LOCS2 is set. * * @param baseAddr Base address for current MCG instance. * @params enable OSC1 Loss of Clock Reset Enable Setting * - true: Reset request is generated on a loss of OSC1 external * reference clock.. * - false: Interrupt request is generated on a loss of OSC1 external * reference clock. */ static inline void CLOCK_HAL_SetLossClkReset2Cmd(uint32_t baseAddr, bool enable) { BW_MCG_C10_LOCRE2(baseAddr, enable ? 1 : 0); } /*! * @brief Gets the OSC1 Loss of the Clock Reset Enable Setting. * * This function gets the OSC1 Loss of Clock Reset Enable Setting. * * @param baseAddr Base address for current MCG instance. * @return enabled True if OSC1 Loss of Clock Reset is enabled. */ static inline bool CLOCK_HAL_GetLossClkReset2Cmd(uint32_t baseAddr) { return BR_MCG_C10_LOCRE2(baseAddr); } /*! * @brief Sets the Frequency Range1 Select Setting. * * This function selects the frequency range for the OSC1 crystal oscillator * or an external clock source. See the Oscillator chapter for more details and * the device data sheet for the frequency ranges used. * * @param baseAddr Base address for current MCG instance. * @params setting Frequency Range1 Select Setting * - 00: Low frequency range selected for the crystal oscillator. * - 01: High frequency range selected for the crystal oscillator. * - 1X: Very high frequency range selected for the crystal oscillator. */ static inline void CLOCK_HAL_SetRange1Mode(uint32_t baseAddr, mcg_freq_range_select_t setting) { BW_MCG_C10_RANGE1(baseAddr, setting); } /*! * @brief Gets the Frequency Range1 Select Setting. * * This function gets the Frequency Range1 Select Setting. * * @param baseAddr Base address for current MCG instance. * @return setting Frequency Range1 Select Setting */ static inline mcg_freq_range_select_t CLOCK_HAL_GetRange1Mode(uint32_t baseAddr) { return (mcg_freq_range_select_t)BR_MCG_C10_RANGE1(baseAddr); } /*! * @brief Sets the High Gain Oscillator1 Select Setting. * * This function controls the OSC1 crystal oscillator mode of operation. * See the Oscillator chapter for more details. * * @param baseAddr Base address for current MCG instance. * @params setting High Gain Oscillator1 Select Setting * - 0: Configure crystal oscillator for low-power operation. * - 1: Configure crystal oscillator for high-gain operation. */ static inline void CLOCK_HAL_SetHighGainOsc1Mode(uint32_t baseAddr, mcg_high_gain_osc_select_t setting) { BW_MCG_C10_HGO1(baseAddr, setting); } /*! * @brief Gets the High Gain Oscillator1 Select Setting. * * This function gets the High Gain Oscillator1 Select Setting. * * @param baseAddr Base address for current MCG instance. * @return setting High Gain Oscillator1 Select Setting */ static inline mcg_high_gain_osc_select_t CLOCK_HAL_GetHighGainOsc1Mode(uint32_t baseAddr) { return (mcg_high_gain_osc_select_t)BR_MCG_C10_HGO1(baseAddr); } /*! * @brief Sets the External Reference Select Setting. * * This function selects the source for the OSC1 external reference clock. * See the Oscillator chapter for more details. * * @param baseAddr Base address for current MCG instance. * @params setting External Reference Select Setting * - 0: External reference clock requested. * - 1: Oscillator requested. */ static inline void CLOCK_HAL_SetExternalRefSel1Mode(uint32_t baseAddr, mcg_external_ref_clock_select_t setting) { BW_MCG_C10_EREFS1(baseAddr, setting); } /*! * @brief Gets the External Reference Select Setting. * * This function gets the External Reference Select Setting. * * @param baseAddr Base address for current MCG instance. * @return setting External Reference Select Setting */ static inline mcg_external_ref_clock_select_t CLOCK_HAL_GetExternalRefSel1Mode(uint32_t baseAddr) { return (mcg_external_ref_clock_select_t)BR_MCG_C10_EREFS1(baseAddr); } /*! * @brief Sets the PLL1 External Reference Select Setting. * * This function selects the PLL1 external reference clock source. * * @param baseAddr Base address for current MCG instance. * @params setting PLL1 External Reference Select Setting * - 0: Selects OSC0 clock source as its external reference clock. * - 1: Selects OSC1 clock source as its external reference clock. */ static inline void CLOCK_HAL_SetPllRefSel1Mode(uint32_t baseAddr, mcg_pll_external_ref_clk_select_t setting) { BW_MCG_C11_PLLREFSEL1(baseAddr, setting); } /*! * @brief Gets the PLL1 External Reference Select Setting. * * This function gets the PLL1 External Reference Select Setting. * * @param baseAddr Base address for current MCG instance. * @return setting PLL1 External Reference Select Setting */ static inline mcg_pll_external_ref_clk_select_t CLOCK_HAL_GetPllRefSel1Mode(uint32_t baseAddr) { return (mcg_pll_external_ref_clk_select_t)BR_MCG_C11_PLLREFSEL1(baseAddr); } /*! * @brief Sets the PLL1 Clock Enable Setting. * * This function enables/disables the PLL1 independent of PLLS and enables the * PLL clocks for use as MCGPLL1CLK, MCGPLL1CLK2X, and MCGDDRCLK2X. (PRDIV1 needs * to be programmed to the correct divider to generate a PLL1 reference clock in a * valid reference range prior to setting the PLLCLKEN1 bit.) Setting PLLCLKEN1 * enables the PLL1 selected external oscillator if not already enabled. * Whenever the PLL1 is enabled with the PLLCLKEN1 bit, and the * external oscillator is used as the reference clock, the OSCINIT1 bit should * be checked to make sure it is set. * * @param baseAddr Base address for current MCG instance. * @params enable PLL1 Clock Enable Setting * - true: MCGPLL1CLK, MCGPLL1CLK2X, and MCGDDRCLK2X are active unless * MCG is in a bypass mode with LP=1 (BLPI or BLPE). * - false: MCGPLL1CLK, MCGPLL1CLK2X, and MCGDDRCLK2X are inactive. */ static inline void CLOCK_HAL_SetPllClk1Cmd(uint32_t baseAddr, bool enable) { BW_MCG_C11_PLLCLKEN1(baseAddr, enable ? 1 : 0); } /*! * @brief Gets the PLL1 Clock Enable Setting. * * This function gets the PLL1 Clock Enable Setting. * * @param baseAddr Base address for current MCG instance. * @return enabled True if the PLL1 Clock is enabled. */ static inline bool CLOCK_HAL_GetPllClk1Cmd(uint32_t baseAddr) { return BR_MCG_C11_PLLCLKEN1(baseAddr); } /*! * @brief Sets the PLL1 Stop Enable Setting. * * This function enables/disables the PLL1 Clock during the Normal Stop (In Low * Power Stop modes, the PLL1 clock gets disabled even if PLLSTEN1=1. In all other * power modes, PLLSTEN1 bit has no affect and does not enable the PLL1 Clock to * run if it is written to 1. * * @param baseAddr Base address for current MCG instance. * @params enable PLL1 Stop Enable Setting * - true: PLL1 and its clocks (MCGPLL1CLK, MCGPLL1CLK2X, and * MCGDDRCLK2X) are enabled if system is in Normal Stop mode. * - false: PLL1 clocks (MCGPLL1CLK, MCGPLL1CLK2X, and MCGDDRCLK2X) * are disabled in any of the Stop modes. */ static inline void CLOCK_HAL_SetPllStop1Cmd(uint32_t baseAddr, bool enable) { BW_MCG_C11_PLLSTEN1(baseAddr, enable ? 1 : 0); } /*! * @brief Gets the PLL1 Stop Enable Setting. * * This function gets the PLL1 Stop Enable Setting. * * @param baseAddr Base address for current MCG instance. * @return enabled True if PLL1 Stop is enabled. */ static inline bool CLOCK_HAL_GetPllStop1Cmd(uint32_t baseAddr) { return BR_MCG_C11_PLLSTEN1(baseAddr); } /*! * @brief Sets the PLL Clock Select Setting. * * This function controls whether the PLL0 or PLL1 output is selected as the * MCG source when CLKS are programmed in PLL Engaged External (PEE) mode * (CLKS[1:0]=00 and IREFS=0 and PLLS=1). * * @param baseAddr Base address for current MCG instance. * @params setting PLL Clock Select Setting * - 0: PLL0 output clock is selected. * - 1: PLL1 output clock is selected. */ static inline void CLOCK_HAL_SetPllClkSelMode(uint32_t baseAddr, mcg_pll_clk_select_t setting) { BW_MCG_C11_PLLCS(baseAddr, setting); } /*! * @brief Gets the PLL Clock Select Setting. * * This function gets the PLL Clock Select Setting. * * @param baseAddr Base address for current MCG instance. * @return setting PLL Clock Select Setting */ static inline mcg_pll_clk_select_t CLOCK_HAL_GetPllClkSelMode(uint32_t baseAddr) { return (mcg_pll_clk_select_t)BR_MCG_C11_PLLCS(baseAddr); } /*! * @brief Sets the PLL1 External Reference Divider Setting. * * This function selects the amount to divide down the external reference * clock selected by REFSEL2 for PLL1. The resulting frequency must be in a valid * reference range. After the PLL1 is enabled (by setting either PLLCLKEN1 or PLLS), * the PRDIV1 value must not be changed when LOCK1 is zero. * * @param baseAddr Base address for current MCG instance. * @params setting PLL1 External Reference Divider Setting */ static inline void CLOCK_HAL_SetPllExternalRefDivider1(uint32_t baseAddr, uint8_t setting) { BW_MCG_C11_PRDIV1(baseAddr, setting); } /*! * @brief Gets the PLL1 External Reference Divider Setting. * * This function gets the PLL1 External Reference Divider Setting. * * @param baseAddr Base address for current MCG instance. * @return setting PLL1 External Reference Divider Setting */ static inline uint8_t CLOCK_HAL_GetPllExternalRefDivider1(uint32_t baseAddr) { return BR_MCG_C11_PRDIV1(baseAddr); } /*! * @brief Sets the PLL1 Loss of Lock Interrupt Enable Setting. * * This function determines whether an interrupt request is made following a * loss of lock indication for PLL1. This bit only has an affect when LOLS1 is set. * * @param baseAddr Base address for current MCG instance. * @params enable PLL1 Loss of Lock Interrupt Enable Setting * - true: Generate an interrupt request on loss of lock on PLL1. * - false: No interrupt request is generated on loss of lock on PLL1. */ static inline void CLOCK_HAL_SetLossOfLock1Cmd(uint32_t baseAddr, bool enable) { BW_MCG_C12_LOLIE1(baseAddr, enable ? 1 : 0); } /*! * @brief Gets the PLL1 Loss of Lock Interrupt Enable Setting. * * This function gets the PLL1 Loss of Lock Interrupt Enable Setting. * * @param baseAddr Base address for current MCG instance. * @return enabled true if PLL1 Loss of Lock Interrupt is enabled. */ static inline bool CLOCK_HAL_GetLossOfLock1Cmd(uint32_t baseAddr) { return BR_MCG_C12_LOLIE1(baseAddr); } /*! * @brief Sets the Clock Monitor Enable2 Setting * * This function enables/disables the loss of the clock monitor for the OSC1 external * reference clock. LOCRE2 determines whether a reset or interrupt request is generated * following a loss of OSC1 external reference clock. The CME2 bit should only be set * to a logic 1 when the MCG is in an operational mode that uses the external clock * (PEE or PBE) . Whenever the CME2 bit is set to a logic 1, the value of the RANGE1 * bits in the C10 register should not be changed. CME2 bit should be set to a logic 0 * before the MCG enters any Stop mode. Otherwise, a reset request may occur while in * Stop mode. * * @param baseAddr Base address for current MCG instance. * @params enable Clock Monitor Enable2 Setting * - true: Generate a reset request on loss of external clock on OSC1. * - false: External clock monitor for OSC1 is disabled. */ static inline void CLOCK_HAL_SetClkMonitor2Cmd(uint32_t baseAddr, bool enable) { BW_MCG_C12_CME2(baseAddr, enable ? 1 : 0); } /*! * @brief Gets the Clock Monitor Enable2 Setting. * * This function gets the Clock Monitor Enable2 Setting. * * @param baseAddr Base address for current MCG instance. * @return enabled True if Clock Monitor Enable2 is enabled. */ static inline bool CLOCK_HAL_GetClkMonitor2Cmd(uint32_t baseAddr) { return BR_MCG_C12_CME2(baseAddr); } /*! * @brief Sets the VCO1 Divider Setting. * * This function selects the amount to divide the VCO output of the PLL1. * The VDIV1 bits establishes the multiplication factor (M) applied to the reference * clock frequency. After the PLL1 is enabled (by setting either PLLCLKEN1 or * PLLS), the VDIV1 value must not be changed when LOCK1 is zero. * * @param baseAddr Base address for current MCG instance. * @params setting VCO1 Divider Setting */ static inline void CLOCK_HAL_SetVoltCtrlOscDivider1(uint32_t baseAddr, uint8_t setting) { BW_MCG_C12_VDIV1(baseAddr, setting); } /*! * @brief Gets the VCO1 Divider Setting. * * This function gets the VCO1 Divider Setting. * * @param baseAddr Base address for current MCG instance. * @return setting VCO1 Divider Setting */ static inline uint8_t CLOCK_HAL_GetVoltCtrlOscDivider1(uint32_t baseAddr) { return BR_MCG_C12_VDIV1(baseAddr); } /*! * @brief Gets the Loss of the Lock2 Status. * * This function gets the Loss of the Lock2 Status. This bit is a sticky bit indicating * the lock status for the PLL1. LOLS1 is set if after acquiring lock, the PLL1 * output frequency has fallen outside the lock exit frequency tolerance, D unl. * LOLIE1 determines whether an interrupt request is made when LOLS1 is set. This * bit is cleared by reset or by writing a logic 1 to it when set. Writing a logic 0 * to this bit has no effect. * * @param baseAddr Base address for current MCG instance. * @return status Loss of Lock2 Status * - 0: PLL1 has not lost lock since LOLS1 was last cleared. * - 1: PLL1 has lost lock since LOLS1 was last cleared. */ static inline mcg_loss_of_lock_status_t CLOCK_HAL_GetLossOfLock1Mode(uint32_t baseAddr) { return (mcg_loss_of_lock_status_t)BR_MCG_S2_LOLS1(baseAddr); } /*! * @brief Gets the Lock1 Status. * * This function gets the Lock1 Status. This bit indicates whether PLL1 has * acquired the lock. PLL1 Lock detection is disabled when not operating in either * PBE or PEE mode unless the PLLCLKEN1=1 and the the MCG is not configured in the BLPI or the * BLPE mode. While the PLL1 clock is locking to the desired frequency, MCGPLL1CLK, * MCGPLL1CLK2X, and MCGDDRCLK2X are gated off until the LOCK1 bit gets * asserted. If the lock status bit is set, changing the value of the PRDIV1[2:0] * bits in the C8 register or the VDIV2[4:0] bits in the C9 register causes the * lock status bit to clear and stay cleared until the PLL1 has reacquired lock. * Loss of PLL1 reference clock will also causes the LOCK1 bit to clear until the PLL1 * has reacquired lock. Entry into the LLS, VLPS, or a regular Stop with the PLLSTEN1=0 also * causes the lock status bit to clear and stay cleared until the Stop mode is exited * and the PLL1 has reacquired the lock. Any time the PLL1 is enabled and the LOCK1 bit * is cleared, the MCGPLL1CLK, MCGPLL1CLK2X, and MCGDDRCLK2X are gated off * until the LOCK1 bit is asserted again. * * @param baseAddr Base address for current MCG instance. * @return status Lock1 Status * - 0: PLL1 is currently unlocked. * - 1: PLL1 is currently locked. */ static inline mcg_lock_status_t CLOCK_HAL_GetLock1Mode(uint32_t baseAddr) { return (mcg_lock_status_t)BR_MCG_S2_LOCK1(baseAddr); } /*! * @brief Gets the PLL Clock Select Status. * * This function gets the PLL Clock Select Status. The PLLCST indicates the PLL * clock selected by PLLCS. The PLLCST bit is not updated immediately after a * write to the PLLCS bit due internal synchronization between clock domains. * * @param baseAddr Base address for current MCG instance. * @return status PLL Clock Select Status * - 0: Source of PLLCS is PLL0 clock. * - 1: Source of PLLCS is PLL1 clock. */ static inline mcg_pll_clk_select_t CLOCK_HAL_GetPllClkSelStatMode(uint32_t baseAddr) { return (mcg_pll_clk_select_t)BR_MCG_S2_PLLCST(baseAddr); } /*! * @brief Gets the OSC1 Initialization Status. * * This function gets the OSC1 Initialization Status. This bit is set after the * initialization cycles of the 2nd crystal oscillator clock have completed. See * the Oscillator block guide for more details. * * @param baseAddr Base address for current MCG instance. * @return status OSC1 Initialization Status */ static inline uint8_t CLOCK_HAL_GetOscInit1(uint32_t baseAddr) { return BR_MCG_S2_OSCINIT1(baseAddr); } /*! * @brief Gets the OSC1 Loss of Clock Status. * * This function gets the OSC1 Loss of Clock Status. This bit indicates when a loss * of the OSC1 external reference clock has occurred. LOCRE2 determines if a reset or * interrupt is generated when LOCS2 is set. This bit is cleared by writing a * logic 1 to it when set. * * @param baseAddr Base address for current MCG instance. * @return status OSC1 Loss of Clock Status * - 0: No loss of OSC1 external reference clock has occurred. * - 1: Loss of OSC1 external reference clock has occurred. */ static inline mcg_locs2_status_t CLOCK_HAL_GetLocs2Mode(uint32_t baseAddr) { return (mcg_locs2_status_t)BR_MCG_S2_LOCS2(baseAddr); } #endif /* FSL_FEATURE_MCG_USE_PLLREFSEL */ /*@}*/ #if defined(__cplusplus) } #endif /* __cplusplus*/ /*! @}*/ #endif /* __FSL_MCG_HAL_H__*/ /******************************************************************************* * EOF ******************************************************************************/ ================================================ FILE: Zelig/mbed/TARGET_K64F/TARGET_Freescale/TARGET_KPSDK_MCUS/TARGET_KPSDK_CODE/hal/mcg/fsl_mcg_hal_modes.h ================================================ /* * Copyright (c) 2013, Freescale Semiconductor, Inc. * All rights reserved. * * Redistribution and use in source and binary forms, with or without modification, * are permitted provided that the following conditions are met: * * o Redistributions of source code must retain the above copyright notice, this list * of conditions and the following disclaimer. * * o Redistributions in binary form must reproduce the above copyright notice, this * list of conditions and the following disclaimer in the documentation and/or * other materials provided with the distribution. * * o Neither the name of Freescale Semiconductor, Inc. nor the names of its * contributors may be used to endorse or promote products derived from this * software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT 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. */ #if !defined(__FSL_MCG_HAL_MODES_H__) #define __FSL_MCG_HAL_MODES_H__ #include #include #include #include "fsl_mcg_features.h" #include "fsl_mcg_hal.h" //! @addtogroup mcg_hal //! @{ //////////////////////////////////////////////////////////////////////////////// // Definitions //////////////////////////////////////////////////////////////////////////////// /*! @brief MCG mode definitions */ typedef enum _mcg_modes { kMcgModeFEI, /* FEI - FLL Engaged Internal */ kMcgModeFEE, /* FEE - FLL Engaged External */ kMcgModeFBI, /* FBI - FLL Bypassed Internal */ kMcgModeFBE, /* FBE - FLL Bypassed External */ kMcgModePEE, /* PEE - PLL Engaged External */ kMcgModePBE, /* PBE - PLL Bypassed Enternal */ kMcgModeBLPI, /* BLPI - Bypassed Low Power Internal */ kMcgModeBLPE, /* BLPE - Bypassed Low Power External */ kMcgModeSTOP, /* STOP - Stop */ kMcgModeError /* Unknown mode */ } mcg_modes_t; /*! @brief MCG mode transition API error code definitions */ typedef enum McgModeErrorCode { /* MCG mode error codes */ kMcgErrNotInFeiMode = 0x01, /* - Not in FEI mode */ kMcgErrNotInFeeMode = 0x02, /* - Not in FEE mode */ kMcgErrNotInFbiMode = 0x03, /* - Not in FBI mode */ kMcgErrNotInFbeMode = 0x04, /* - Not in FBE mode */ kMcgErrNotInBlpiMode = 0x05, /* - Not in BLPI mode */ kMcgErrNotInBlpeMode = 0x06, /* - Not in BLPE mode */ kMcgErrNotInPbeMode = 0x07, /* - Not in PBE mode */ kMcgErrNotInPeeMode = 0x08, /* - Not in PEE mode */ /* CLock MUX switching error codes */ kMcgErrIrefstClearTimeOut = 0x11, /* - IREFST did not clear within allowed time, FLL reference did not switch over from internal to external clock */ kMcgErrIrefstSetTimeout = 0x12, /* - IREFST did not set within allowed time, the FLL reference did not switch over from external to internal clock(NEED TO CHECK IN MOVES TO FBI MODE) */ kMcgErrIrcstClearTimeout = 0x13, /* - IRCST did not clear within allowed time, slow IRC is not selected */ kMcgErrIrefstSetTimeout1 = 0x14, /* - IREFST did not set within allowed time, fast IRC is not selected */ kMcgErrPllstClearTimeout = 0x15, /* - PLLST did not clear, PLLST did not switch to FLL output, FLL is not running */ kMcgErrPllstSetTimeout = 0x16, /* - PLLST did not set, PLLST did not switch to PLL ouptut, PLL is not running */ kMcgErrPllcst = 0x17, /* - PLLCST did not switch to the correct state, the correct PLL is not selected as PLLS clock source */ kMcgErrClkst0 = 0x18, /* - CLKST != 0, MCG did not switch to FLL output */ kMcgErrClkst1 = 0x19, /* - CLKST != 1, MCG did not switch to internal reference clock source */ kMcgErrClkst2 = 0x1A, /* - CLKST != 2, MCG did not switch to external clock */ kMcgErrClkst3 = 0x1B, /* - CLKST != 3, MCG did not switch to PLL */ /* Oscillator error codes */ kMcgErrOscEtalRange = 0x21, /* - external frequency is bigger than max frequency */ kMcgErrOscXtalRange = 0x22, /* - crystal frequency outside allowed range */ kMcgErrOscSetTimeout = 0x23, /* - OSCINIT/OSCINIT2 did not set within allowed time */ /* IRC and FLL error codes */ kMcgErrIrcSlowRange = 0x31, /* - slow IRC is outside allowed range */ kMcgErrIrcFastRange = 0x32, /* - fast IRC is outside allowed range */ kMcgErrFllRange0Min = 0x33, /* - FLL frequency is below minimum value for range 0 */ kMcgErrFllRange0Max = 0x34, /* - FLL frequency is above maximum value for range 0 */ kMcgErrFllRange1Min = 0x35, /* - FLL frequency is below minimum value for range 1 */ kMcgErrFllRange1Max = 0x36, /* - FLL frequency is above maximum value for range 1 */ kMcgErrFllRange2Min = 0x37, /* - FLL frequency is below minimum value for range 2 */ kMcgErrFllRange2Max = 0x38, /* - FLL frequency is above maximum value for range 2 */ kMcgErrFllRange3Min = 0x39, /* - FLL frequency is below minimum value for range 3 */ kMcgErrFllRange3Max = 0x3A, /* - FLL frequency is above maximum value for range 3 */ kMcgErrFllDrstDrsRange = 0x3B, /* - DRS is out of range */ kMcgErrFllFreqency = 0x3C, /* PLL error codes */ kMcgErrPllPrdidRange = 0x41, /* - PRDIV outside allowed range */ kMcgErrPllVdivRange = 0x42, /* - VDIV outside allowed range */ kMcgErrPllRefClkRange = 0x43, /* - PLL reference clock frequency, out of allowed range */ kMcgErrPllLockBit = 0x44, /* - LOCK or LOCK2 bit did not set */ kMcgErrPllOutClkRange = 0x45, /* - PLL output frequency is outside allowed range (NEED TO ADD THIS CHECK TO fbe_pbe and blpe_pbe) only in fei-pee at this time */ kMcgErrMax = 0x1000 } mcg_mode_error_code_t; //////////////////////////////////////////////////////////////////////////////// // API //////////////////////////////////////////////////////////////////////////////// #if defined(__cplusplus) extern "C" { #endif // __cplusplus /*! * @brief Gets the current MCG mode. * * This is an internal function that checks the MCG registers and determine * the current MCG mode * * @param baseAddr Base address for current MCG instance. * @return mcgMode Current MCG mode or error code mcg_modes_t */ mcg_modes_t CLOCK_HAL_GetMcgMode(uint32_t baseAddr); /*! * @brief Checks the FLL frequency integrity. * * This function calculates and checks the FLL frequency value based on input value. * * @param baseAddr Base address for current MCG instance. * @param fllRef - FLL reference clock in Hz. * * @return value FLL output frequency (Hz) or error code */ uint32_t CLOCK_HAL_GetFllFrequency(uint32_t baseAddr, int32_t fllRef); /*! * @brief Mode transition FEI to FEE mode * * This function transitions the MCG from FEI mode to FEE mode. * * @param baseAddr Base address for current MCG instance. * @param oscselVal - oscillator selection value * 0 - OSC 0, 1 - RTC 32k, 2 - IRC 48M * @param crystalVal - external clock frequency in Hz * oscselVal - 0 * erefsVal - 0: osc0 external clock frequency * erefsVal - 1: osc0 crystal clock frequency * oscselVal - 1: RTC 32Khz clock source frequency * oscselVal - 2: IRC 48Mhz clock source frequency * @param hgoVal - selects whether low power or high gain mode is selected * for the crystal oscillator. This value is only valid when * oscselVal is 0 and erefsVal is 1. * @param erefsVal - selects external clock (=0) or crystal OSC (=1) * * @return value MCGCLKOUT frequency (Hz) or error code */ uint32_t CLOCK_HAL_SetFeiToFeeMode(uint32_t baseAddr, mcg_oscsel_select_t oscselVal, uint32_t crystalVal, mcg_high_gain_osc_select_t hgoVal, mcg_external_ref_clock_select_t erefsVal); /*! * @brief Mode transition FEI to FBI mode * * This function transitions the MCG from FEI mode to FBI mode. * * @param baseAddr Base address for current MCG instance. * @param ircFreq - internal reference clock frequency value * @param ircSelect - slow or fast clock selection * 0: slow, 1: fast * @return value MCGCLKOUT frequency (Hz) or error code */ uint32_t CLOCK_HAL_SetFeiToFbiMode(uint32_t baseAddr, uint32_t ircFreq, mcg_internal_ref_clock_select_t ircSelect); /*! * @brief Mode transition FEI to FBE mode * * This function transitions the MCG from FEI mode to FBE mode. * * @param baseAddr Base address for current MCG instance. * @param oscselVal - oscillator selection value * 0 - OSC 0, 1 - RTC 32k, 2 - IRC 48M * @param crystalVal - external clock frequency in Hz * oscselVal - 0 * erefsVal - 0: osc0 external clock frequency * erefsVal - 1: osc0 crystal clock frequency * oscselVal - 1: RTC 32Khz clock source frequency * oscselVal - 2: IRC 48Mhz clock source frequency * @param hgoVal - selects whether low power or high gain mode is selected * for the crystal oscillator. This value is only valid when * oscselVal is 0 and erefsVal is 1. * @param erefsVal - selects external clock (=0) or crystal OSC (=1) * * @return value MCGCLKOUT frequency (Hz) or error code */ uint32_t CLOCK_HAL_SetFeiToFbeMode(uint32_t baseAddr, mcg_oscsel_select_t oscselVal, uint32_t crystalVal, mcg_high_gain_osc_select_t hgoVal, mcg_external_ref_clock_select_t erefsVal); /*! * @brief Mode transition FEE to FEI mode * * This function transitions the MCG from FEE mode to FEI mode. * * @param baseAddr Base address for current MCG instance. * @param ircFreq - internal reference clock frequency value (slow) * * @return value MCGCLKOUT frequency (Hz) or error code */ uint32_t CLOCK_HAL_SetFeeToFeiMode(uint32_t baseAddr, uint32_t ircFreq); /*! * @brief Mode transition FEE to FBI mode * * This function transitions the MCG from FEE mode to FBI mode. * * @param baseAddr Base address for current MCG instance. * @param ircFreq - internal reference clock frequency value * @param ircSelect - slow or fast clock selection * 0: slow, 1: fast * * @return value MCGCLKOUT frequency (Hz) or error code */ uint32_t CLOCK_HAL_SetFeeToFbiMode(uint32_t baseAddr, uint32_t ircFreq, mcg_internal_ref_clock_select_t ircSelect); /*! * @brief Mode transition FEE to FBE mode * * This function transitions the MCG from FEE mode to FBE mode. * * @param baseAddr Base address for current MCG instance. * @param crystalVal - external reference clock frequency value * * @return value MCGCLKOUT frequency (Hz) or error code */ uint32_t CLOCK_HAL_SetFeeToFbeMode(uint32_t baseAddr, uint32_t crystalVal); /*! * @brief Mode transition FBI to FEI mode * * This function transitions the MCG from FBI mode to FEI mode. * * @param baseAddr Base address for current MCG instance. * @param ircFreq - internal reference clock frequency value (slow) * * @return value MCGCLKOUT frequency (Hz) or error code */ uint32_t CLOCK_HAL_SetFbiToFeiMode(uint32_t baseAddr, uint32_t ircFreq); /*! * @brief Mode transition FBI to FEE mode * * This function transitions the MCG from FBI mode to FEE mode. * * @param baseAddr Base address for current MCG instance. * @param oscselVal - oscillator selection value * 0 - OSC 0, 1 - RTC 32k, 2 - IRC 48M * @param crystalVal - external clock frequency in Hz * oscselVal - 0 * erefsVal - 0: osc0 external clock frequency * erefsVal - 1: osc0 crystal clock frequency * oscselVal - 1: RTC 32Khz clock source frequency * oscselVal - 2: IRC 48Mhz clock source frequency * @param hgoVal - selects whether low power or high gain mode is selected * for the crystal oscillator. This value is only valid when * oscselVal is 0 and erefsVal is 1. * @param erefsVal - selects external clock (=0) or crystal OSC (=1) * * @return value MCGCLKOUT frequency (Hz) or error code */ uint32_t CLOCK_HAL_SetFbiToFeeMode(uint32_t baseAddr, mcg_oscsel_select_t oscselVal, uint32_t crystalVal, mcg_high_gain_osc_select_t hgoVal, mcg_external_ref_clock_select_t erefsVal); /*! * @brief Mode transition FBI to FBE mode * * This function transitions the MCG from FBI mode to FBE mode. * * @param baseAddr Base address for current MCG instance. * @param oscselVal - oscillator selection value * 0 - OSC 0, 1 - RTC 32k, 2 - IRC 48M * @param crystalVal - external clock frequency in Hz * oscselVal - 0 * erefsVal - 0: osc0 external clock frequency * erefsVal - 1: osc0 crystal clock frequency * oscselVal - 1: RTC 32Khz clock source frequency * oscselVal - 2: IRC 48Mhz clock source frequency * @param hgoVal - selects whether low power or high gain mode is selected * for the crystal oscillator. This value is only valid when * oscselVal is 0 and erefsVal is 1. * @param erefsVal - selects external clock (=0) or crystal OSC (=1) * * @return value MCGCLKOUT frequency (Hz) or error code */ uint32_t CLOCK_HAL_SetFbiToFbeMode(uint32_t baseAddr, mcg_oscsel_select_t oscselVal, uint32_t crystalVal, mcg_high_gain_osc_select_t hgoVal, mcg_external_ref_clock_select_t erefsVal); /*! * @brief Mode transition FBI to BLPI mode * * This function transitions the MCG from FBI mode to BLPI mode.This is * achieved by setting the MCG_C2[LP] bit. * * @param baseAddr Base address for current MCG instance. * @param ircFreq - internal reference clock frequency value * @param ircSelect - slow or fast clock selection * 0: slow, 1: fast * * @return value MCGCLKOUT frequency (Hz) or error code */ uint32_t CLOCK_HAL_SetFbiToBlpiMode(uint32_t baseAddr, uint32_t ircFreq, mcg_internal_ref_clock_select_t ircSelect); /*! * @brief Mode transition BLPI to FBI mode * * This function transitions the MCG from BLPI mode to FBI mode.This is * achieved by clearing the MCG_C2[LP] bit. * * @param baseAddr Base address for current MCG instance. * @param ircFreq - internal reference clock frequency value * @param ircSelect - slow or fast clock selection * 0: slow, 1: fast * * @return value MCGCLKOUT frequency (Hz) or error code */ uint32_t CLOCK_HAL_SetBlpiToFbiMode(uint32_t baseAddr, uint32_t ircFreq, uint8_t ircSelect); /*! * @brief Mode transition FBE to FEE mode * * This function transitions the MCG from FBE mode to FEE mode. * * @param baseAddr Base address for current MCG instance. * @param crystalVal - external reference clock frequency value * * @return value MCGCLKOUT frequency (Hz) or error code */ uint32_t CLOCK_HAL_SetFbeToFeeMode(uint32_t baseAddr, uint32_t crystalVal); /*! * @brief Mode transition FBE to FEI mode * * This function transitions the MCG from FBE mode to FEI mode. * * @param baseAddr Base address for current MCG instance. * @param ircFreq - internal reference clock frequency value (slow) * * @return value MCGCLKOUT frequency (Hz) or error code *END***********************************************************************************/ uint32_t CLOCK_HAL_SetFbeToFeiMode(uint32_t baseAddr, uint32_t ircFreq); /*! * @brief Mode transition FBE to FBI mode * * This function transitions the MCG from FBE mode to FBI mode. * * @param baseAddr Base address for current MCG instance. * @param ircFreq - internal reference clock frequency value * @param ircSelect - slow or fast clock selection * 0: slow, 1: fast * * @return value MCGCLKOUT frequency (Hz) or error code *END***********************************************************************************/ uint32_t CLOCK_HAL_SetFbeToFbiMode(uint32_t baseAddr, uint32_t ircFreq, mcg_internal_ref_clock_select_t ircSelect); /*! * @brief Mode transition FBE to PBE mode * * This function transitions the MCG from FBE mode to PBE mode. * The function requires the desired OSC and PLL be passed in to it for compatibility * with the future support of OSC/PLL selection * (This function presently only supports OSC0 as PLL source) * * @param baseAddr Base address for current MCG instance. * @param crystalVal - external clock frequency in Hz * @param pllcsSelect - 0 to select PLL0, non-zero to select PLL1. * @param prdivVal - value to divide the external clock source by to create * the desired PLL reference clock frequency * @param vdivVal - value to multiply the PLL reference clock frequency by * * @return value MCGCLKOUT frequency (Hz) or error code */ uint32_t CLOCK_HAL_SetFbeToPbeMode(uint32_t baseAddr, uint32_t crystalVal, mcg_pll_clk_select_t pllcsSelect, uint8_t prdivVal, uint8_t vdivVal); /*! * @brief Mode transition FBE to BLPE mode * * This function transitions the MCG from FBE mode to BLPE mode. * * @param baseAddr Base address for current MCG instance. * @param crystalVal - external clock frequency in Hz * * @return value MCGCLKOUT frequency (Hz) or error code */ uint32_t CLOCK_HAL_SetFbeToBlpeMode(uint32_t baseAddr, uint32_t crystalVal); /*! * @brief Mode transition PBE to FBE mode * * This function transitions the MCG from PBE mode to FBE mode. * * @param baseAddr Base address for current MCG instance. * @param crystalVal - external clock frequency in Hz * * @return value MCGCLKOUT frequency (Hz) or error code */ uint32_t CLOCK_HAL_SetPbeToFbeMode(uint32_t baseAddr, uint32_t crystalVal); /*! * @brief Mode transition PBE to PEE mode * * This function transitions the MCG from PBE mode to PEE mode. * * @param baseAddr Base address for current MCG instance. * @param crystalVal - external clock frequency in Hz * @param pllcsSelect - PLLCS select setting * mcg_pll_clk_select_t is defined in fsl_mcg_hal.h * 0: kMcgPllcsSelectPll0 PLL0 output clock is selected * 1: kMcgPllcsSelectPll1 PLL1 output clock is selected * * @return value MCGCLKOUT frequency (Hz) or error code */ uint32_t CLOCK_HAL_SetPbeToPeeMode(uint32_t baseAddr, uint32_t crystalVal, mcg_pll_clk_select_t pllcsSelect); /*! * @brief Mode transition PBE to BLPE mode * * This function transitions the MCG from PBE mode to BLPE mode. * * @param baseAddr Base address for current MCG instance. * @param crystalVal - external clock frequency in Hz * * @return value MCGCLKOUT frequency (Hz) or error code */ uint32_t CLOCK_HAL_SetPbeToBlpeMode(uint32_t baseAddr, uint32_t crystalVal); /*! * @brief Mode transition PEE to PBE mode * * This function transitions the MCG from PEE mode to PBE mode. * * @param baseAddr Base address for current MCG instance. * @param crystalVal - external clock frequency in Hz * * @return value MCGCLKOUT frequency (Hz) or error code */ uint32_t CLOCK_HAL_SetPeeToPbeMode(uint32_t baseAddr, uint32_t crystalVal); /*! * @brief Mode transition BLPE to PBE mode * * This function transitions the MCG from BLPE mode to PBE mode. * The function requires the desired OSC and PLL be passed in to it for compatibility * with the future support of OSC/PLL selection * (This function presently only supports OSC0 as PLL source) * * @param baseAddr Base address for current MCG instance. * @param crystalVal - external clock frequency in Hz * @param pllcsSelect - 0 to select PLL0, non-zero to select PLL1. * @param prdivVal - value to divide the external clock source by to create * the desired PLL reference clock frequency * @param vdivVal - value to multiply the PLL reference clock frequency by * * @return value MCGCLKOUT frequency (Hz) or error code */ uint32_t CLOCK_HAL_SetBlpeToPbeMode(uint32_t baseAddr, uint32_t crystalVal, mcg_pll_clk_select_t pllcsSelect, uint8_t prdivVal, uint8_t vdivVal); /*! * @brief Mode transition BLPE to FBE mode * * This function transitions the MCG from BLPE mode to FBE mode. * * @param baseAddr Base address for current MCG instance. * @param crystalVal - external reference clock frequency value * * @return value MCGCLKOUT frequency (Hz) or error code */ uint32_t CLOCK_HAL_SetBlpeToFbeMode(uint32_t baseAddr, uint32_t crystalVal); #if defined(__cplusplus) } #endif // __cplusplus //! @} #endif // __FSL_MCG_HAL_MODES_H__ //////////////////////////////////////////////////////////////////////////////// // EOF //////////////////////////////////////////////////////////////////////////////// ================================================ FILE: Zelig/mbed/TARGET_K64F/TARGET_Freescale/TARGET_KPSDK_MCUS/TARGET_KPSDK_CODE/hal/mpu/fsl_mpu_features.h ================================================ /* ** ################################################################### ** Version: rev. 1.0, 2014-05-14 ** Build: b140515 ** ** Abstract: ** Chip specific module features. ** ** Copyright: 2014 Freescale Semiconductor, Inc. ** All rights reserved. ** ** Redistribution and use in source and binary forms, with or without modification, ** are permitted provided that the following conditions are met: ** ** o Redistributions of source code must retain the above copyright notice, this list ** of conditions and the following disclaimer. ** ** o Redistributions in binary form must reproduce the above copyright notice, this ** list of conditions and the following disclaimer in the documentation and/or ** other materials provided with the distribution. ** ** o Neither the name of Freescale Semiconductor, Inc. nor the names of its ** contributors may be used to endorse or promote products derived from this ** software without specific prior written permission. ** ** THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ** ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED ** WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE ** DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT 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. ** ** http: www.freescale.com ** mail: support@freescale.com ** ** Revisions: ** - rev. 1.0 (2014-05-14) ** Customer release. ** ** ################################################################### */ #if !defined(__FSL_MPU_FEATURES_H__) #define __FSL_MPU_FEATURES_H__ #if defined(CPU_MK24FN1M0VDC12) || defined(CPU_MK24FN1M0VLL12) || defined(CPU_MK24FN1M0VLQ12) /* @brief Specifies number of descriptors available. */ #define FSL_FEATURE_MPU_DESCRIPTOR_COUNT (12) /* @brief Has process identifier support. */ #define FSL_FEATURE_MPU_HAS_PROCESS_IDENTIFIER (1) /* @brief Has master 0. */ #define FSL_FEATURE_MPU_HAS_MASTER0 (1) /* @brief Has master 1. */ #define FSL_FEATURE_MPU_HAS_MASTER1 (1) /* @brief Has master 2. */ #define FSL_FEATURE_MPU_HAS_MASTER2 (1) /* @brief Has master 3. */ #define FSL_FEATURE_MPU_HAS_MASTER3 (0) /* @brief Has master 4. */ #define FSL_FEATURE_MPU_HAS_MASTER4 (1) /* @brief Has master 5. */ #define FSL_FEATURE_MPU_HAS_MASTER5 (1) /* @brief Has master 6. */ #define FSL_FEATURE_MPU_HAS_MASTER6 (0) /* @brief Has master 7. */ #define FSL_FEATURE_MPU_HAS_MASTER7 (0) #elif defined(CPU_MK63FN1M0VLQ12) || defined(CPU_MK63FN1M0VMD12) || defined(CPU_MK64FX512VDC12) || defined(CPU_MK64FN1M0VDC12) || \ defined(CPU_MK64FX512VLL12) || defined(CPU_MK64FN1M0VLL12) || defined(CPU_MK64FX512VLQ12) || defined(CPU_MK64FN1M0VLQ12) || \ defined(CPU_MK64FX512VMD12) || defined(CPU_MK64FN1M0VMD12) /* @brief Specifies number of descriptors available. */ #define FSL_FEATURE_MPU_DESCRIPTOR_COUNT (12) /* @brief Has process identifier support. */ #define FSL_FEATURE_MPU_HAS_PROCESS_IDENTIFIER (1) /* @brief Has master 0. */ #define FSL_FEATURE_MPU_HAS_MASTER0 (1) /* @brief Has master 1. */ #define FSL_FEATURE_MPU_HAS_MASTER1 (1) /* @brief Has master 2. */ #define FSL_FEATURE_MPU_HAS_MASTER2 (1) /* @brief Has master 3. */ #define FSL_FEATURE_MPU_HAS_MASTER3 (1) /* @brief Has master 4. */ #define FSL_FEATURE_MPU_HAS_MASTER4 (1) /* @brief Has master 5. */ #define FSL_FEATURE_MPU_HAS_MASTER5 (1) /* @brief Has master 6. */ #define FSL_FEATURE_MPU_HAS_MASTER6 (0) /* @brief Has master 7. */ #define FSL_FEATURE_MPU_HAS_MASTER7 (0) #elif defined(CPU_MK65FN2M0CAC18) || defined(CPU_MK65FX1M0CAC18) || defined(CPU_MK65FN2M0VMI18) || defined(CPU_MK65FX1M0VMI18) || \ defined(CPU_MK66FN2M0VLQ18) || defined(CPU_MK66FX1M0VLQ18) || defined(CPU_MK66FN2M0VMD18) || defined(CPU_MK66FX1M0VMD18) /* @brief Specifies number of descriptors available. */ #define FSL_FEATURE_MPU_DESCRIPTOR_COUNT (12) /* @brief Has process identifier support. */ #define FSL_FEATURE_MPU_HAS_PROCESS_IDENTIFIER (1) /* @brief Has master 0. */ #define FSL_FEATURE_MPU_HAS_MASTER0 (1) /* @brief Has master 1. */ #define FSL_FEATURE_MPU_HAS_MASTER1 (1) /* @brief Has master 2. */ #define FSL_FEATURE_MPU_HAS_MASTER2 (1) /* @brief Has master 3. */ #define FSL_FEATURE_MPU_HAS_MASTER3 (1) /* @brief Has master 4. */ #define FSL_FEATURE_MPU_HAS_MASTER4 (1) /* @brief Has master 5. */ #define FSL_FEATURE_MPU_HAS_MASTER5 (1) /* @brief Has master 6. */ #define FSL_FEATURE_MPU_HAS_MASTER6 (1) /* @brief Has master 7. */ #define FSL_FEATURE_MPU_HAS_MASTER7 (0) #elif defined(CPU_MK70FN1M0VMF12) || defined(CPU_MK70FX512VMF12) || defined(CPU_MK70FN1M0VMF15) || defined(CPU_MK70FX512VMF15) || \ defined(CPU_MK70FN1M0VMJ12) || defined(CPU_MK70FX512VMJ12) || defined(CPU_MK70FN1M0VMJ15) || defined(CPU_MK70FX512VMJ15) /* @brief Specifies number of descriptors available. */ #define FSL_FEATURE_MPU_DESCRIPTOR_COUNT (16) /* @brief Has process identifier support. */ #define FSL_FEATURE_MPU_HAS_PROCESS_IDENTIFIER (1) /* @brief Has master 0. */ #define FSL_FEATURE_MPU_HAS_MASTER0 (1) /* @brief Has master 1. */ #define FSL_FEATURE_MPU_HAS_MASTER1 (1) /* @brief Has master 2. */ #define FSL_FEATURE_MPU_HAS_MASTER2 (1) /* @brief Has master 3. */ #define FSL_FEATURE_MPU_HAS_MASTER3 (1) /* @brief Has master 4. */ #define FSL_FEATURE_MPU_HAS_MASTER4 (1) /* @brief Has master 5. */ #define FSL_FEATURE_MPU_HAS_MASTER5 (1) /* @brief Has master 6. */ #define FSL_FEATURE_MPU_HAS_MASTER6 (0) /* @brief Has master 7. */ #define FSL_FEATURE_MPU_HAS_MASTER7 (0) #else #define MBED_NO_MPU #endif #endif /* __FSL_MPU_FEATURES_H__ */ /******************************************************************************* * EOF ******************************************************************************/ ================================================ FILE: Zelig/mbed/TARGET_K64F/TARGET_Freescale/TARGET_KPSDK_MCUS/TARGET_KPSDK_CODE/hal/mpu/fsl_mpu_hal.h ================================================ /* * Copyright (c) 2013 - 2014, Freescale Semiconductor, Inc. * All rights reserved. * * Redistribution and use in source and binary forms, with or without modification, * are permitted provided that the following conditions are met: * * o Redistributions of source code must retain the above copyright notice, this list * of conditions and the following disclaimer. * * o Redistributions in binary form must reproduce the above copyright notice, this * list of conditions and the following disclaimer in the documentation and/or * other materials provided with the distribution. * * o Neither the name of Freescale Semiconductor, Inc. nor the names of its * contributors may be used to endorse or promote products derived from this * software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT 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. */ #ifndef __FSL_MPU_HAL_H__ #define __FSL_MPU_HAL_H__ #include #include #include #include "fsl_mpu_features.h" #include "fsl_device_registers.h" #ifndef MBED_NO_MPU #define MPU_REGION_NUMBER 12 /*! * @addtogroup mpu_hal * @{ */ /******************************************************************************* * Definitions *******************************************************************************/ /*! @brief MPU region number region0~region11. */ typedef enum _mpu_region_num{ kMPURegionNum00 = 0U, /*!< MPU region number 0*/ kMPURegionNum01 = 1U, /*!< MPU region number 1*/ kMPURegionNum02 = 2U, /*!< MPU region number 2*/ kMPURegionNum03 = 3U, /*!< MPU region number 3*/ kMPURegionNum04 = 4U, /*!< MPU region number 4*/ kMPURegionNum05 = 5U, /*!< MPU region number 5*/ kMPURegionNum06 = 6U, /*!< MPU region number 6*/ kMPURegionNum07 = 7U, /*!< MPU region number 7*/ kMPURegionNum08 = 8U, /*!< MPU region number 8*/ kMPURegionNum09 = 9U, /*!< MPU region number 9*/ kMPURegionNum10 = 10U, /*!< MPU region number 10*/ kMPURegionNum11 = 11U, /*!< MPU region number 11*/ #if defined(CPU_MK70FN1M0VMF12) || defined(CPU_MK70FX512VMF12) || defined(CPU_MK70FN1M0VMF15) || defined(CPU_MK70FX512VMF15) || \ defined(CPU_MK70FN1M0VMJ12) || defined(CPU_MK70FX512VMJ12) || defined(CPU_MK70FN1M0VMJ15) || defined(CPU_MK70FX512VMJ15) kMPURegionNum11 = 12U, /*!< MPU region number 12*/ kMPURegionNum11 = 13U, /*!< MPU region number 13*/ kMPURegionNum11 = 14U, /*!< MPU region number 14*/ kMPURegionNum11 = 15U, /*!< MPU region number 15*/ #endif }mpu_region_num; /*! @brief MPU error address register0~4. */ typedef enum _mpu_error_addr_reg{ kMPUErrorAddrReg00 = 0U, /*!< MPU error address register 0*/ kMPUErrorAddrReg01 = 1U, /*!< MPU error address register 1*/ kMPUErrorAddrReg02 = 2U, /*!< MPU error address register 2*/ kMPUErrorAddrReg03 = 3U, /*!< MPU error address register 3*/ kMPUErrorAddrReg04 = 4U /*!< MPU error address register 4*/ }mpu_error_addr_reg; /*! @brief MPU error detail register0~4. */ typedef enum _mpu_error_detail_reg{ kMPUErrorDetailReg00 = 0U, /*!< MPU error detail register 0*/ kMPUErrorDetailReg01 = 1U, /*!< MPU error detail register 1*/ kMPUErrorDetailReg02 = 2U, /*!< MPU error detail register 2*/ kMPUErrorDetailReg03 = 3U, /*!< MPU error detail register 3*/ kMPUErrorDetailReg04 = 4U /*!< MPU error detail register 4*/ }mpu_error_detail_reg; /*! @brief MPU access error. */ typedef enum _mpu_error_access_type{ kMPUReadErrorType = 0U, /*!< MPU error type---read*/ kMPUWriteErrorType = 1U /*!< MPU error type---write*/ }mpu_error_access_type; /*! @brief MPU access error attributes.*/ typedef enum _mpu_error_attributes{ kMPUUserModeInstructionAccess = 0U, /*!< access instruction error in user mode*/ kMPUUserModeDataAccess = 1U, /*!< access data error in user mode*/ kMPUSupervisorModeInstructionAccess = 2U, /*!< access instruction error in supervisor mode*/ kMPUSupervisorModeDataAccess = 3U /*!< access data error in supervisor mode*/ }mpu_error_attributes; /*! @brief access MPU in which mode. */ typedef enum _mpu_access_mode{ kMPUAccessInUserMode = 0U, /*!< access data or instruction in user mode*/ kMPUAccessInSupervisorMode = 1U /*!< access data or instruction in supervisor mode*/ }mpu_access_mode; /*! @brief MPU master number. */ typedef enum _mpu_master_num{ kMPUMaster00 = 0U, /*!< Core.*/ kMPUMaster01 = 1U, /*!< Debugger.*/ kMPUMaster02 = 2U, /*!< DMA.*/ kMPUMaster03 = 3U, /*!< ENET.*/ kMPUMaster04 = 4U, /*!< USB.*/ kMPUMaster05 = 5U, /*!< SDHC.*/ kMPUMaster06 = 6U, /*!< undefined.*/ kMPUMaster07 = 7U /*!< undefined.*/ }mpu_master_num; /*! @brief MPU error access control detail. */ typedef enum _mpu_error_access_control{ kMPUNoRegionHitError = 0U, /*!< no region hit error*/ kMPUNoneOverlappRegionError = 1U, /*!< access single region error*/ kMPUOverlappRegionError = 2U /*!< access overlapping region error*/ }mpu_error_access_control; /*! @brief MPU access rights in supervisor mode for master0~master3. */ typedef enum _mpu_supervisor_access_rights{ kMPUSupervisorReadWriteExecute = 0U, /*!< R W E allowed in supervisor mode*/ kMPUSupervisorReadExecute = 1U, /*!< R E allowed in supervisor mode*/ kMPUSupervisorReadWrite = 2U, /*!< R W allowed in supervisor mode*/ kMPUSupervisorEqualToUsermode = 3U /*!< access permission equal to user mode*/ }mpu_supervisor_access_rights; /*! @brief MPU access rights in user mode for master0~master3. */ typedef enum _mpu_user_access_rights{ kMPUUserNoAccessRights = 0U, /*!< no access allowed in user mode*/ kMPUUserExecute = 1U, /*!< E allowed in user mode*/ kMPUUserWrite = 2U, /*!< W allowed in user mode*/ kMPUUserWriteExecute = 3U, /*!< W E allowed in user mode*/ kMPUUserRead = 4U, /*!< R allowed in user mode*/ kMPUUserReadExecute = 5U, /*!< R E allowed in user mode*/ kMPUUserReadWrite = 6U, /*!< R W allowed in user mode*/ kMPUUserReadWriteExecute = 7U /*!< R W E allowed in user mode*/ }mpu_user_access_rights; /*! @brief MPU process identifier. */ typedef enum _mpu_process_identifier_value{ kMPUIdentifierDisable = 0U, /*!< processor identifier disable*/ kMPUIdentifierEnable = 1U /*!< processor identifier enable*/ }mpu_process_identifier_value; /*! @brief MPU access control for master4~master7. */ typedef enum _mpu_access_control{ kMPUAccessDisable = 0U, /*!< Read or Write not allowed*/ kMPUAccessEnable = 1U /*!< Read or Write allowed*/ }mpu_access_control; /*! @brief MPU access type for master4~master7. */ typedef enum _mpu_access_type{ kMPUAccessRead = 0U, /*!< Access type is read*/ kMPUAccessWrite = 1U /*!< Access type is write*/ }mpu_access_type; /*! @brief MPU access region valid. */ typedef enum _mpu_region_valid{ kMPURegionInvalid = 0U, /*!< region invalid*/ kMPURegionValid = 1U /*!< region valid*/ }mpu_region_valid; /*! @brief MPU status return codes.*/ typedef enum _MPU_status { kStatus_MPU_Success = 0x0U, /*!< Succeed. */ kStatus_MPU_NotInitlialized = 0x1U, /*!< MPU is not initialized yet. */ kStatus_MPU_NullArgument = 0x2U, /*!< Argument is NULL.*/ } mpu_status_t; /******************************************************************************* ** Variables *******************************************************************************/ /******************************************************************************* * API *******************************************************************************/ #if defined(__cplusplus) extern "C" { #endif /*! * @name MPU HAL. * @{ */ /*! * @brief Enables the MPU module operation * * @param baseAddr The MPU peripheral base address */ static inline void MPU_HAL_Enable(uint32_t baseAddr) { BW_MPU_CESR_VLD(baseAddr, (uint8_t)true); } /*! * @brief Disables the MPU module operation * * @param baseAddr The MPU peripheral base address */ static inline void MPU_HAL_Disable(uint32_t baseAddr) { BW_MPU_CESR_VLD(baseAddr, (uint8_t)false); } /*! * @brief Checks whether the MPU module is enabled * * @param baseAddr The MPU peripheral base address * @retval true MPU module is enabled * @retval false MPU module is disabled */ static inline bool MPU_HAL_IsEnabled(uint32_t baseAddr) { return BR_MPU_CESR_VLD(baseAddr); } /*! * @brief Returns the total region number * * @param baseAddr The MPU peripheral base address * @retval the number of regions */ static inline uint32_t MPU_HAL_GetNumberOfRegions(uint32_t baseAddr) { return (BR_MPU_CESR_NRGD(baseAddr)); } /*! * @brief Returns MPU slave sports * * @param baseAddr The MPU peripheral base address * @retval the number of slaves */ static inline uint32_t MPU_HAL_GetNumberOfSlaves(uint32_t baseAddr) { return (BR_MPU_CESR_NSP(baseAddr)); } /*! * @brief Returns hardware level info * * @param baseAddr The MPU peripheral base address * @retval hardware revision level */ static inline uint32_t MPU_HAL_GetHardwareRevisionLevel(uint32_t baseAddr) { return (BR_MPU_CESR_HRL(baseAddr)); } /*! * @brief Returns hardware level info * * @param baseAddr The MPU peripheral base address * @param regNum Error address register number * @retval error access address */ static inline uint32_t MPU_HAL_GetErrorAccessAddr(uint32_t baseAddr, mpu_error_addr_reg regNum) { assert(regNum < HW_MPU_EARn_COUNT); return (BR_MPU_EARn_EADDR(baseAddr, regNum)); } /*! * @brief Returns error access slaves sports * * @param baseAddr The MPU peripheral base address * @retval error slave sports */ static inline uint8_t MPU_HAL_GetErrorSlaveSports(uint32_t baseAddr) { return (BR_MPU_CESR_SPERR(baseAddr)); } /*! * @brief Returns error access address * * @param baseAddr The MPU peripheral base address * @param errorDetailRegNum Error detail register number * @retval error access type */ static inline mpu_error_access_type MPU_HAL_GetErrorAccessType(uint32_t baseAddr, mpu_error_detail_reg errorDetailRegNum) { assert(errorDetailRegNum < HW_MPU_EDRn_COUNT); return (mpu_error_access_type)(BR_MPU_EDRn_ERW(baseAddr, errorDetailRegNum)); } /*! * @brief Returns error access attributes * * @param baseAddr The MPU peripheral base address * @param errorDetailRegNum Detail error register number * @retval error access attributes */ static inline mpu_error_attributes MPU_HAL_GetErrorAttributes(uint32_t baseAddr, mpu_error_detail_reg errorDetailRegNum) { assert(errorDetailRegNum < HW_MPU_EDRn_COUNT); return (mpu_error_attributes)(BR_MPU_EDRn_EATTR(baseAddr, errorDetailRegNum)); } /*! * @brief Returns error access master number * * @param baseAddr The MPU peripheral base address * @param errorDetailRegNum Error register number * @retval error master number */ static inline mpu_master_num MPU_HAL_GetErrorMasterNum(uint32_t baseAddr, mpu_error_detail_reg errorDetailRegNum) { assert(errorDetailRegNum < HW_MPU_EDRn_COUNT); return (mpu_master_num)(BR_MPU_EDRn_EMN(baseAddr, errorDetailRegNum)); } /*! * @brief Returns error process identifier * * @param baseAddr The MPU peripheral base address * @param errorDetailRegNum Error register number * @retval error process identifier */ static inline uint32_t MPU_HAL_GetErrorProcessIdentifier(uint32_t baseAddr, mpu_error_detail_reg errorDetailRegNum) { assert(errorDetailRegNum < HW_MPU_EDRn_COUNT); return(BR_MPU_EDRn_EPID(baseAddr, errorDetailRegNum)); } /*! * @brief Returns error access control * * @param baseAddr The MPU peripheral base address * @param errorDetailRegNum Error register number * @retval error access control */ static inline mpu_error_access_control MPU_HAL_GetErrorAccessControl(uint32_t baseAddr, mpu_error_detail_reg errorDetailRegNum) { assert(errorDetailRegNum < HW_MPU_EDRn_COUNT); uint32_t i = BR_MPU_EDRn_EACD(baseAddr, errorDetailRegNum); if(0 == i) { return (kMPUNoRegionHitError); } else if(!(i&(i-1))) { return (kMPUNoneOverlappRegionError); } else { return (kMPUOverlappRegionError); } } /*! * @brief Returns the region start address * * @param baseAddr The MPU peripheral base address * @param regionNum MPU region number * @retval region start address */ static inline uint32_t MPU_HAL_GetRegionStartAddr(uint32_t baseAddr, mpu_region_num regionNum) { assert(regionNum < HW_MPU_RGDn_WORD0_COUNT); return (BR_MPU_RGDn_WORD0_SRTADDR(baseAddr, regionNum)<>= BP_MPU_RGDn_WORD0_SRTADDR; BW_MPU_RGDn_WORD0_SRTADDR(baseAddr, regionNum, startAddr); } /*! * @brief Returns region end address * * @param baseAddr The MPU peripheral base address * @param regionNum MPU region number * @retval region end address */ static inline uint32_t MPU_HAL_GetRegionEndAddr(uint32_t baseAddr, mpu_region_num regionNum) { assert(regionNum < HW_MPU_RGDn_WORD1_COUNT); return (BR_MPU_RGDn_WORD1_ENDADDR(baseAddr, regionNum)<>= BP_MPU_RGDn_WORD0_SRTADDR; BW_MPU_RGDn_WORD1_ENDADDR(baseAddr, regionNum, endAddr); } /*! * @brief Returns all masters access permission for a specific region * * @param baseAddr The MPU peripheral base address * @param regionNum MPU region number * @retval all masters access permission */ static inline uint32_t MPU_HAL_GetAllMastersAccessRights(uint32_t baseAddr, mpu_region_num regionNum) { assert(regionNum < HW_MPU_RGDn_WORD2_COUNT); return (HW_MPU_RGDn_WORD2_RD(baseAddr, regionNum)); } /*! * @brief Sets all masters access permission for a specific region * * @param baseAddr The MPU peripheral base address * @param regionNum MPU region number * @param accessRights All masters access rights */ static inline void MPU_HAL_SetAllMastersAccessRights(uint32_t baseAddr, mpu_region_num regionNum, uint32_t accessRights) { assert(regionNum < HW_MPU_RGDn_WORD2_COUNT); HW_MPU_RGDn_WORD2_WR(baseAddr, regionNum, accessRights); } /*! * @brief Gets M0 access permission in supervisor mode * * @param baseAddr The MPU peripheral base address * @param regionNum MPU region number * @retval Master0 access permission */ static inline mpu_supervisor_access_rights MPU_HAL_GetM0SupervisorAccessRights(uint32_t baseAddr, mpu_region_num regionNum) { assert(regionNum < HW_MPU_RGDn_WORD2_COUNT); return (mpu_supervisor_access_rights)(BR_MPU_RGDn_WORD2_M0SM(baseAddr, regionNum)); } /*! * @brief Gets M0 access permission in user mode * * @param baseAddr The MPU peripheral base address * @param regionNum MPU region number * @retval Master0 access permission */ static inline mpu_user_access_rights MPU_HAL_GetM0UserAccessRights(uint32_t baseAddr, mpu_region_num regionNum) { assert(regionNum < HW_MPU_RGDn_WORD2_COUNT); return (mpu_user_access_rights)(BR_MPU_RGDn_WORD2_M0UM(baseAddr, regionNum)); } /*! * @brief Sets M0 access permission in supervisor mode * * @param baseAddr The MPU peripheral base address * @param regionNum MPU region number * @param accessRights Master0 access permission */ static inline void MPU_HAL_SetM0SupervisorAccessRights(uint32_t baseAddr, mpu_region_num regionNum, mpu_supervisor_access_rights accessRights) { assert(regionNum < HW_MPU_RGDn_WORD2_COUNT); BW_MPU_RGDn_WORD2_M0SM(baseAddr, regionNum, accessRights); } /*! * @brief Sets M0 access permission in user mode * * @param baseAddr The MPU peripheral base address * @param regionNum MPU region number * @param accessRights Master0 access permission */ static inline void MPU_HAL_SetM0UserAccessRights(uint32_t baseAddr, mpu_region_num regionNum, mpu_user_access_rights accessRights) { assert(regionNum < HW_MPU_RGDn_WORD2_COUNT); BW_MPU_RGDn_WORD2_M0UM(baseAddr, regionNum, accessRights); } /*! * @brief Checks whether the M0 process identifier is enabled in region hit evaluation * * @param baseAddr The MPU peripheral base address * @param regionNum MPU region number * @retval true m0 process identifier is enabled * @retval false m0 process identifier is disabled */ static inline bool MPU_HAL_IsM0ProcessIdentifierEnabled(uint32_t baseAddr, mpu_region_num regionNum) { assert(regionNum < HW_MPU_RGDn_WORD2_COUNT); return (1 == BR_MPU_RGDn_WORD2_M0PE(baseAddr, regionNum)); } /*! * @brief Sets the M0 process identifier value--- 1 enable process identifier in region hit evaluation and 0 disable * * @param baseAddr The MPU peripheral base address * @param regionNum MPU region number * @param identifierValue Process identifier value */ static inline void MPU_HAL_SetM0ProcessIdentifierValue(uint32_t baseAddr, mpu_region_num regionNum, mpu_process_identifier_value identifierValue) { assert(regionNum < HW_MPU_RGDn_WORD2_COUNT); BW_MPU_RGDn_WORD2_M0PE(baseAddr, regionNum, identifierValue); } /*! * @brief Gets M1 access permission in supervisor mode * * @param baseAddr The MPU peripheral base address * @param regionNum MPU region number * @retval Master1 access permission */ static inline mpu_supervisor_access_rights MPU_HAL_GetM1SupervisorAccessRights(uint32_t baseAddr, mpu_region_num regionNum) { assert(regionNum < HW_MPU_RGDn_WORD2_COUNT); return (mpu_supervisor_access_rights)(BR_MPU_RGDn_WORD2_M1SM(baseAddr, regionNum)); } /*! * @brief Gets M1 access permission in user mode * * @param baseAddr The MPU peripheral base address * @param regionNum MPU region number * @retval Master1 access permission */ static inline mpu_user_access_rights MPU_HAL_GetM1UserAccessRights(uint32_t baseAddr, mpu_region_num regionNum) { assert(regionNum < HW_MPU_RGDn_WORD2_COUNT); return (mpu_user_access_rights)(BR_MPU_RGDn_WORD2_M1UM(baseAddr, regionNum)); } /*! * @brief Sets M1 access permission in supervisor mode * * @param baseAddr The MPU peripheral base address * @param regionNum MPU region number * @param accessRights Master1 access permission */ static inline void MPU_HAL_SetM1SupervisorAccessRights(uint32_t baseAddr, mpu_region_num regionNum, mpu_supervisor_access_rights accessRights) { assert(regionNum < HW_MPU_RGDn_WORD2_COUNT); BW_MPU_RGDn_WORD2_M1SM(baseAddr, regionNum, accessRights); } /*! * @brief Sets M1 access permission in user mode * * @param baseAddr The MPU peripheral base address * @param regionNum MPU region number * @param accessRights Master1 access permission */ static inline void MPU_HAL_SetM1UserAccessRights(uint32_t baseAddr, mpu_region_num regionNum, mpu_user_access_rights accessRights) { assert(regionNum < HW_MPU_RGDn_WORD2_COUNT); BW_MPU_RGDn_WORD2_M1UM(baseAddr, regionNum, accessRights); } /*! * @brief Checks whether M1 process identifier enabled in region hit evaluation * * @param baseAddr The MPU peripheral base address * @param regionNum MPU region number * @retval true m1 process identifier is enabled * @retval false m1 process identifier is disabled */ static inline bool MPU_HAL_IsM1ProcessIdentifierEnabled(uint32_t baseAddr, mpu_region_num regionNum) { assert(regionNum < HW_MPU_RGDn_WORD2_COUNT); return (1 == BR_MPU_RGDn_WORD2_M1PE(baseAddr, regionNum)); } /*! * @brief Sets the M1 process identifier value--- 1 enable process identifier in region hit evaluation and 0 disable * * @param baseAddr The MPU peripheral base address * @param regionNum MPU region number * @param identifierValue Process identifier value */ static inline void MPU_HAL_SetM1ProcessIdentifierValue(uint32_t baseAddr, mpu_region_num regionNum, mpu_process_identifier_value identifierValue) { assert(regionNum < HW_MPU_RGDn_WORD2_COUNT); BW_MPU_RGDn_WORD2_M1PE(baseAddr, regionNum, identifierValue); } /*! * @brief Gets M2 access permission in supervisor mode * * @param baseAddr The MPU peripheral base address * @param regionNum MPU region number * @retval Master2 access permission */ static inline mpu_supervisor_access_rights MPU_HAL_GetM2SupervisorAccessRights(uint32_t baseAddr, mpu_region_num regionNum) { assert(regionNum < HW_MPU_RGDn_WORD2_COUNT); return (mpu_supervisor_access_rights)(BR_MPU_RGDn_WORD2_M2SM(baseAddr, regionNum)); } /*! * @brief Gets M2 access permission in user mode * * @param baseAddr The MPU peripheral base address * @param regionNum MPU region number * @retval Master2 access permission */ static inline mpu_user_access_rights MPU_HAL_GetM2UserAccessRights(uint32_t baseAddr, mpu_region_num regionNum) { assert(regionNum < HW_MPU_RGDn_WORD2_COUNT); return (mpu_user_access_rights)(BR_MPU_RGDn_WORD2_M2UM(baseAddr, regionNum)); } /*! * @brief Sets M2 access permission in supervisor mode * * @param baseAddr The MPU peripheral base address * @param regionNum MPU region number * @param accessRights Master2 access permission */ static inline void MPU_HAL_SetM2SupervisorAccessRights(uint32_t baseAddr, mpu_region_num regionNum, mpu_supervisor_access_rights accessRights) { assert(regionNum < HW_MPU_RGDn_WORD2_COUNT); BW_MPU_RGDn_WORD2_M2SM(baseAddr, regionNum, accessRights); } /*! * @brief Sets M2 access permission in user mode * * @param baseAddr The MPU peripheral base address * @param regionNum MPU region number * @param accessRights Master2 access permission */ static inline void MPU_HAL_SetM2UserAccessRights(uint32_t baseAddr, mpu_region_num regionNum, mpu_user_access_rights accessRights) { assert(regionNum < HW_MPU_RGDn_WORD2_COUNT); BW_MPU_RGDn_WORD2_M2UM(baseAddr, regionNum, accessRights); } /*! * @brief Checks whether the M2 process identifier enabled in region hit evaluation * * @param baseAddr The MPU peripheral base address * @param regionNum MPU region number * @retval true m2 process identifier is enabled * @retval false m2 process identifier is disabled */ static inline bool MPU_HAL_IsM2ProcessIdentifierEnabled(uint32_t baseAddr, mpu_region_num regionNum) { assert(regionNum < HW_MPU_RGDn_WORD2_COUNT); return (1 == BR_MPU_RGDn_WORD2_M2PE(baseAddr, regionNum)); } /*! * @brief Sets the M2 process identifier value--- 1 enable process identifier in region hit evaluation and 0 disable. * * @param baseAddr The MPU peripheral base address. * @param regionNum MPU region number. * @param identifierValue Process identifier value. */ static inline void MPU_HAL_SetM2ProcessIdentifierValue(uint32_t baseAddr, mpu_region_num regionNum, mpu_process_identifier_value identifierValue) { assert(regionNum < HW_MPU_RGDn_WORD2_COUNT); BW_MPU_RGDn_WORD2_M2PE(baseAddr, regionNum, identifierValue); } /*! * @brief Gets M3 access permission in supervisor mode * * @param baseAddr The MPU peripheral base address * @param regionNum MPU region number * @retval Master3 access permission */ static inline mpu_supervisor_access_rights MPU_HAL_GetM3SupervisorAccessRights(uint32_t baseAddr, mpu_region_num regionNum) { assert(regionNum < HW_MPU_RGDn_WORD2_COUNT); return (mpu_supervisor_access_rights)(BR_MPU_RGDn_WORD2_M3SM(baseAddr, regionNum)); } /*! * @brief Gets M3 access permission in user mode * * @param baseAddr The MPU peripheral base address * @param regionNum MPU region number * @retval Master3 access permission */ static inline mpu_user_access_rights MPU_HAL_GetM3UserAccessRights(uint32_t baseAddr, mpu_region_num regionNum) { assert(regionNum < HW_MPU_RGDn_WORD2_COUNT); return (mpu_user_access_rights)(BR_MPU_RGDn_WORD2_M3UM(baseAddr, regionNum)); } /*! * @brief Sets M3 access permission in supervisor mode. * * @param baseAddr The MPU peripheral base address. * @param regionNum MPU region number. * @param accessRights Master3 access permission. */ static inline void MPU_HAL_SetM3SupervisorAccessRights(uint32_t baseAddr, mpu_region_num regionNum, mpu_supervisor_access_rights accessRights) { assert(regionNum < HW_MPU_RGDn_WORD2_COUNT); BW_MPU_RGDn_WORD2_M3SM(baseAddr, regionNum, accessRights); } /*! * @brief Sets M3 access permission in user mode * * @param baseAddr The MPU peripheral base address * @param regionNum MPU region number * @param accessRights Master3 access permission */ static inline void MPU_HAL_SetM3UserAccessRights(uint32_t baseAddr, mpu_region_num regionNum, mpu_user_access_rights accessRights) { assert(regionNum < HW_MPU_RGDn_WORD2_COUNT); BW_MPU_RGDn_WORD2_M3UM(baseAddr, regionNum, accessRights); } /*! * @brief Checks whether the M3 process identifier enabled in region hit evaluation * * @param baseAddr The MPU peripheral base address * @param regionNum MPU region number * @retval true m3 process identifier is enabled * @retval false m3 process identifier is disabled */ static inline bool MPU_HAL_IsM3ProcessIdentifierEnabled(uint32_t baseAddr, mpu_region_num regionNum) { assert(regionNum < HW_MPU_RGDn_WORD2_COUNT); return (1 == BR_MPU_RGDn_WORD2_M3PE(baseAddr, regionNum)); } /*! * @brief Sets M3 process identifier value--- 1 enable process identifier in region hit evaluation and 0 disable * * @param baseAddr The MPU peripheral base address * @param regionNum MPU region number * @param identifierValue Process identifier value */ static inline void MPU_HAL_SetM3ProcessIdentifierValue(uint32_t baseAddr, mpu_region_num regionNum, mpu_process_identifier_value identifierValue) { assert(regionNum < HW_MPU_RGDn_WORD2_COUNT); BW_MPU_RGDn_WORD2_M3PE(baseAddr, regionNum, identifierValue); } /*! * @brief Gets the M4 access permission. * * @param baseAddr The MPU peripheral base address * @param regionNum MPU region number * @param accessType Access type Read/Write * @retval read or write permission */ static inline mpu_access_control MPU_HAL_GetM4AccessControl(uint32_t baseAddr, mpu_region_num regionNum, mpu_access_type accessType) { assert(regionNum < HW_MPU_RGDn_WORD2_COUNT); if(kMPUAccessRead == accessType) { return (mpu_access_control)(BR_MPU_RGDn_WORD2_M4RE(baseAddr, regionNum)); } else { return (mpu_access_control)(BR_MPU_RGDn_WORD2_M4WE(baseAddr, regionNum)); } } /*! * @brief Sets the M4 access permission * * @param baseAddr The MPU peripheral base address * @param regionNum MPU region number * @param accessType Access type Read/Write * @param accessControl Access permission */ static inline void MPU_HAL_SetM4AccessControl(uint32_t baseAddr, mpu_region_num regionNum, mpu_access_type accessType, mpu_access_control accessControl) { assert(regionNum < HW_MPU_RGDn_WORD2_COUNT); if(kMPUAccessRead == accessType) { BW_MPU_RGDn_WORD2_M4RE(baseAddr, regionNum, accessControl); } else { BW_MPU_RGDn_WORD2_M4WE(baseAddr, regionNum, accessControl); } } /*! * @brief Gets the M5 access permission * * @param baseAddr The MPU peripheral base address * @param regionNum MPU region number * @param accessType Access type Read/Write * @retval read or write permission */ static inline mpu_access_control MPU_HAL_GetM5AccessControl(uint32_t baseAddr, mpu_region_num regionNum, mpu_access_type accessType) { assert(regionNum < HW_MPU_RGDn_WORD2_COUNT); if(kMPUAccessRead == accessType) { return (mpu_access_control)(BR_MPU_RGDn_WORD2_M5RE(baseAddr, regionNum)); } else { return (mpu_access_control)(BR_MPU_RGDn_WORD2_M5WE(baseAddr, regionNum)); } } /*! * @brief Sets the M5 access permission * * @param baseAddr The MPU peripheral base address * @param regionNum MPU region number * @param accessType Access type Read/Write * @param accessControl Access permission */ static inline void MPU_HAL_SetM5AccessControl(uint32_t baseAddr, mpu_region_num regionNum, mpu_access_type accessType, mpu_access_control accessControl) { assert(regionNum < HW_MPU_RGDn_WORD2_COUNT); if(kMPUAccessRead == accessType) { BW_MPU_RGDn_WORD2_M5RE(baseAddr, regionNum, accessControl); } else { BW_MPU_RGDn_WORD2_M5WE(baseAddr, regionNum, accessControl); } } /*! * @brief Gets the M6 access permission * * @param baseAddr The MPU peripheral base address * @param regionNum MPU region number * @param accessType access type Read/Write * @retval read or write permission */ static inline mpu_access_control MPU_HAL_GetM6AccessControl(uint32_t baseAddr, mpu_region_num regionNum, mpu_access_type accessType) { assert(regionNum < HW_MPU_RGDn_WORD2_COUNT); if(kMPUAccessRead == accessType) { return (mpu_access_control)(BR_MPU_RGDn_WORD2_M6RE(baseAddr, regionNum)); } else { return (mpu_access_control)(BR_MPU_RGDn_WORD2_M6WE(baseAddr, regionNum)); } } /*! * @brief Sets the M6 access permission * * @param baseAddr The MPU peripheral base address * @param regionNum MPU region number * @param accessType Access type Read/Write * @param accessControl Access permission */ static inline void MPU_HAL_SetM6AccessControl(uint32_t baseAddr, mpu_region_num regionNum, mpu_access_type accessType, mpu_access_control accessControl) { assert(regionNum < HW_MPU_RGDn_WORD2_COUNT); if(kMPUAccessRead == accessType) { BW_MPU_RGDn_WORD2_M6RE(baseAddr, regionNum, accessControl); } else { BW_MPU_RGDn_WORD2_M6WE(baseAddr, regionNum, accessControl); } } /*! * @brief Gets the M7 access permission * * @param baseAddr The MPU peripheral base address * @param regionNum MPU region number * @param accessType Access type Read/Write * @retval read or write permission */ static inline mpu_access_control MPU_HAL_GetM7AccessControl(uint32_t baseAddr, mpu_region_num regionNum, mpu_access_type accessType) { assert(regionNum < HW_MPU_RGDn_WORD2_COUNT); if(kMPUAccessRead == accessType) { return (mpu_access_control)(BR_MPU_RGDn_WORD2_M7RE(baseAddr, regionNum)); } else { return (mpu_access_control)(BR_MPU_RGDn_WORD2_M7WE(baseAddr, regionNum)); } } /*! * @brief Sets the M7 access permission * * @param baseAddr The MPU peripheral base address * @param regionNum MPU region number * @param accessType Access type Read/Write * @param accessControl Access permission */ static inline void MPU_HAL_SetM7AccessControl(uint32_t baseAddr, mpu_region_num regionNum, mpu_access_type accessType, mpu_access_control accessControl) { assert(regionNum < HW_MPU_RGDn_WORD2_COUNT); if(kMPUAccessRead == accessType) { BW_MPU_RGDn_WORD2_M7RE(baseAddr, regionNum, accessControl); } else { BW_MPU_RGDn_WORD2_M7WE(baseAddr, regionNum, accessControl); } } /*! * @brief Checks whether region is valid * * @param baseAddr The MPU peripheral base address * @param regionNum MPU region number * @retval true region is valid * @retval false region is invalid */ static inline bool MPU_HAL_IsRegionValid(uint32_t baseAddr, mpu_region_num regionNum) { assert(regionNum < HW_MPU_RGDn_WORD3_COUNT); return (1 == BR_MPU_RGDn_WORD3_VLD(baseAddr, regionNum)); } /*! * @brief Sets the region valid value * * @param baseAddr The MPU peripheral base address * @param regionNum MPU region number * @param validValue Region valid value */ static inline void MPU_HAL_SetRegionValidValue(uint32_t baseAddr, mpu_region_num regionNum, mpu_region_valid validValue) { assert(regionNum < HW_MPU_RGDn_WORD3_COUNT); BW_MPU_RGDn_WORD3_VLD(baseAddr, regionNum, validValue); } /*! * @brief Gets the process identifier mask * * @param baseAddr The MPU peripheral base address * @param regionNum MPU region number * @retval region process identifier mask */ static inline uint8_t MPU_HAL_GetProcessIdentifierMask(uint32_t baseAddr, mpu_region_num regionNum) { assert(regionNum < HW_MPU_RGDn_WORD3_COUNT); return (BR_MPU_RGDn_WORD3_PIDMASK(baseAddr, regionNum)); } /*! * @brief Sets the process identifier mask * * @param baseAddr The MPU peripheral base address * @param regionNum MPU region number * @param processIdentifierMask Process identifier mask value */ static inline void MPU_HAL_SetPIDMASK(uint32_t baseAddr, mpu_region_num regionNum, uint8_t processIdentifierMask) { assert(regionNum < HW_MPU_RGDn_WORD3_COUNT); BW_MPU_RGDn_WORD3_PIDMASK(baseAddr, regionNum, processIdentifierMask); } /*! * @brief Gets the process identifier * * @param baseAddr The MPU peripheral base address * @param regionNum MPU region number * @retval process identifier */ static inline uint8_t MPU_HAL_GetProcessIdentifier(uint32_t baseAddr, mpu_region_num regionNum) { assert(regionNum < HW_MPU_RGDn_WORD3_COUNT); return (BR_MPU_RGDn_WORD3_PID(baseAddr, regionNum)); } /*! * @brief Sets the process identifier * * @param baseAddr The MPU peripheral base address * @param regionNum MPU region number * @param processIdentifier Process identifier */ static inline void MPU_HAL_SetProcessIdentifier(uint32_t baseAddr, mpu_region_num regionNum, uint8_t processIdentifier) { assert(regionNum < HW_MPU_RGDn_WORD3_COUNT); BW_MPU_RGDn_WORD3_PID(baseAddr, regionNum, processIdentifier); } /*! * @brief Gets all masters access permission from alternative register * * @param baseAddr The MPU peripheral base address * @param regionNum MPU region number * @retval all masters access permission */ static inline uint32_t MPU_HAL_GetAllMastersAlternateAcessRights(uint32_t baseAddr, mpu_region_num regionNum) { assert(regionNum < HW_MPU_RGDAACn_COUNT); return (HW_MPU_RGDAACn_RD(baseAddr, regionNum)); } /*! * @brief Sets all masters access permission through alternative register * * @param baseAddr The MPU peripheral base address * @param regionNum MPU region number * @param accessRights All masters access permission */ static inline void MPU_HAL_SetAllMastersAlternateAccessRights(uint32_t baseAddr, mpu_region_num regionNum, uint32_t accessRights) { assert(regionNum < HW_MPU_RGDAACn_COUNT); HW_MPU_RGDAACn_WR(baseAddr, regionNum, accessRights); } /*! * @brief Gets the M0 access rights in supervisor mode * * @param baseAddr The MPU peripheral base address * @param regionNum MPU region number * @retval Master0 access permission */ static inline mpu_supervisor_access_rights MPU_HAL_GetM0AlternateSupervisorAccessRights(uint32_t baseAddr, mpu_region_num regionNum) { assert(regionNum < HW_MPU_RGDAACn_COUNT); return (mpu_supervisor_access_rights)(BR_MPU_RGDAACn_M0SM(baseAddr, regionNum)); } /*! * @brief Gets the M0 access rights in user mode * * @param baseAddr The MPU peripheral base address * @param regionNum MPU region number * @retval Master0 access permission */ static inline mpu_user_access_rights MPU_HAL_GetM0AlternateUserAccessRights(uint32_t baseAddr, mpu_region_num regionNum) { assert(regionNum < HW_MPU_RGDAACn_COUNT); return (mpu_user_access_rights)(BR_MPU_RGDAACn_M0UM(baseAddr, regionNum)); } /*! * @brief Sets the M0 access rights in supervisor mode * * @param baseAddr The MPU peripheral base address * @param regionNum MPU region number * @param accessRights Master0 access permission */ static inline void MPU_HAL_SetM0AlternateSupervisorAccessRights(uint32_t baseAddr, mpu_region_num regionNum, mpu_supervisor_access_rights accessRights) { assert(regionNum < HW_MPU_RGDAACn_COUNT); BW_MPU_RGDAACn_M0SM(baseAddr, regionNum, accessRights); } /*! * @brief Sets the M0 access rights in user mode * * @param baseAddr The MPU peripheral base address * @param regionNum MPU region number * @param accessRights Master0 access permission */ static inline void MPU_HAL_SetM0AlternateUserAccessRights(uint32_t baseAddr, mpu_region_num regionNum, mpu_user_access_rights accessRights) { assert(regionNum < HW_MPU_RGDAACn_COUNT); BW_MPU_RGDAACn_M0UM(baseAddr, regionNum, accessRights); } /*! * @brief Checks whether the M0 process identifier works in region hit evaluation * * @param baseAddr The MPU peripheral base address * @param regionNum MPU region number * @retval true m0 process identifier is enabled * @retval false m0 process identifier is disabled */ static inline bool MPU_HAL_IsM0AlternateProcessIdentifierEnabled(uint32_t baseAddr, mpu_region_num regionNum) { assert(regionNum < HW_MPU_RGDn_WORD2_COUNT); return (1 == BR_MPU_RGDAACn_M0PE(baseAddr, regionNum)); } /*! * @brief @brief Sets the M0 process identifier value--- 1 enable process identifier in region hit evaluation and 0 disable * * @param baseAddr The MPU peripheral base address * @param regionNum MPU region number * @param identifierValue Process identifier value */ static inline void MPU_HAL_SetM0AlternateProcessIdentifierValue(uint32_t baseAddr, mpu_region_num regionNum, mpu_process_identifier_value identifierValue) { assert(regionNum < HW_MPU_RGDn_WORD2_COUNT); BW_MPU_RGDAACn_M0PE(baseAddr, regionNum, identifierValue); } /*! * @brief Gets M1 access rights in supervisor mode * * @param baseAddr The MPU peripheral base address * @param regionNum MPU region number * @retval Master1 access permission */ static inline mpu_supervisor_access_rights MPU_HAL_GetM1AlternateSupervisorAccessRights(uint32_t baseAddr, mpu_region_num regionNum) { assert(regionNum < HW_MPU_RGDAACn_COUNT); return (mpu_supervisor_access_rights)(BR_MPU_RGDAACn_M1SM(baseAddr, regionNum)); } /*! * @brief Gets M1 access rights in user mode * * @param baseAddr The MPU peripheral base address * @param regionNum MPU region number * @retval Master1 access permission */ static inline mpu_user_access_rights MPU_HAL_GetM1AlternateUserAccessRights(uint32_t baseAddr, mpu_region_num regionNum) { assert(regionNum < HW_MPU_RGDAACn_COUNT); return (mpu_user_access_rights)(BR_MPU_RGDAACn_M1UM(baseAddr, regionNum)); } /*! * @brief Sets M1 access rights in supervisor mode * * @param baseAddr The MPU peripheral base address * @param regionNum MPU region number * @param accessRights Master1 access permission */ static inline void MPU_HAL_SetM1AlternateSupervisorAccessRights(uint32_t baseAddr, mpu_region_num regionNum, mpu_supervisor_access_rights accessRights) { assert(regionNum < HW_MPU_RGDAACn_COUNT); BW_MPU_RGDAACn_M1SM(baseAddr, regionNum, accessRights); } /*! * @brief Sets M1 access rights in user mode * * @param baseAddr The MPU peripheral base address * @param regionNum MPU region number * @param accessRights Master1 access permission */ static inline void MPU_HAL_SetM1AlternateUserAccessRights(uint32_t baseAddr, mpu_region_num regionNum, mpu_user_access_rights accessRights) { assert(regionNum < HW_MPU_RGDAACn_COUNT); BW_MPU_RGDAACn_M1UM(baseAddr, regionNum, accessRights); } /*! * @brief Checks whether the M1 process identifier works in region hit evaluation * * @param baseAddr The MPU peripheral base address * @param regionNum MPU region number * @retval true m1 process identifier is enabled * @retval false m1 process identifier is disabled */ static inline bool MPU_HAL_IsM1AlternateProcessIdentifierEnabled(uint32_t baseAddr, mpu_region_num regionNum) { assert(regionNum < HW_MPU_RGDn_WORD2_COUNT); return (1 == BR_MPU_RGDAACn_M1PE(baseAddr, regionNum)); } /*! * @brief @brief Sets M1 process identifier value--- 1 enable process identifier in region hit evaluation and 0 disable * * @param baseAddr The MPU peripheral base address * @param regionNum MPU region number * @param identifierValue process identifier value */ static inline void MPU_HAL_SetM1AlternateProcessIdentifierValue(uint32_t baseAddr, mpu_region_num regionNum, mpu_process_identifier_value identifierValue) { assert(regionNum < HW_MPU_RGDn_WORD2_COUNT); BW_MPU_RGDAACn_M1PE(baseAddr, regionNum, identifierValue); } /*! * @brief Gets M2 access rights in supervisor mode * * @param baseAddr The MPU peripheral base address * @param regionNum MPU region number * @retval M2 access permission */ static inline mpu_supervisor_access_rights MPU_HAL_GetM2AlternateSupervisorAccessRights(uint32_t baseAddr, mpu_region_num regionNum) { assert(regionNum < HW_MPU_RGDAACn_COUNT); return (mpu_supervisor_access_rights)(BR_MPU_RGDAACn_M2SM(baseAddr, regionNum)); } /*! * @brief Gets the M2 access rights in user mode * * @param baseAddr The MPU peripheral base address * @param regionNum MPU region number * @retval M2 access permission */ static inline mpu_user_access_rights MPU_HAL_GetM2AlternateUserAccessRights(uint32_t baseAddr, mpu_region_num regionNum) { assert(regionNum < HW_MPU_RGDAACn_COUNT); return (mpu_user_access_rights)(BR_MPU_RGDAACn_M2UM(baseAddr, regionNum)); } /*! * @brief Sets M2 access rights in supervisor mode * * @param baseAddr The MPU peripheral base address * @param regionNum MPU region number * @param accessRights M2 access permission */ static inline void MPU_HAL_SetM2AlternateSupervisorAccessRights(uint32_t baseAddr, mpu_region_num regionNum, mpu_supervisor_access_rights accessRights) { assert(regionNum < HW_MPU_RGDAACn_COUNT); BW_MPU_RGDAACn_M2SM(baseAddr, regionNum, accessRights); } /*! * @brief Sets M2 access rights in user mode * * @param baseAddr The MPU peripheral base address * @param regionNum MPU region number * @param accessRights M2 access permission */ static inline void MPU_HAL_SetM2AlternateUserAccessRights(uint32_t baseAddr, mpu_region_num regionNum, mpu_user_access_rights accessRights) { assert(regionNum < HW_MPU_RGDAACn_COUNT); BW_MPU_RGDAACn_M2UM(baseAddr, regionNum, accessRights); } /*! * @brief Checks whether the M2 process identifier works in region hit evaluation * * @param baseAddr The MPU peripheral base address * @param regionNum MPU region number * @retval true m2 process identifier is enabled * @retval false m2 process identifier is disabled */ static inline bool MPU_HAL_IsM2AlternateProcessIdentifierEnabled(uint32_t baseAddr, mpu_region_num regionNum) { assert(regionNum < HW_MPU_RGDn_WORD2_COUNT); return (1 == BR_MPU_RGDAACn_M2PE(baseAddr, regionNum)); } /*! * @brief Sets M2 process identifier value--- 1 enable process identifier in region hit evaluation and 0 disable * * @param baseAddr The MPU peripheral base address * @param regionNum MPU region number * @param identifierValue process identifier value */ static inline void MPU_HAL_SetM2AlternateProcessIdentifierValue(uint32_t baseAddr, mpu_region_num regionNum, mpu_process_identifier_value identifierValue) { assert(regionNum < HW_MPU_RGDn_WORD2_COUNT); BW_MPU_RGDAACn_M2PE(baseAddr, regionNum, identifierValue); } /*! * @brief Gets M3 access rights in supervisor mode * * @param baseAddr The MPU peripheral base address * @param regionNum MPU region number * @retval M3 access permission */ static inline mpu_supervisor_access_rights MPU_HAL_GetM3AlternateSupervisorAccessRights(uint32_t baseAddr, mpu_region_num regionNum) { assert(regionNum < HW_MPU_RGDAACn_COUNT); return (mpu_supervisor_access_rights)(BR_MPU_RGDAACn_M3SM(baseAddr, regionNum)); } /*! * @brief Gets M3 access rights in user mode * * @param baseAddr The MPU peripheral base address * @param regionNum MPU region number * @retval M3 access permission */ static inline mpu_user_access_rights MPU_HAL_GetM3AlternateUserAccessRights(uint32_t baseAddr, mpu_region_num regionNum) { assert(regionNum < HW_MPU_RGDAACn_COUNT); return (mpu_user_access_rights)(BR_MPU_RGDAACn_M3UM(baseAddr, regionNum)); } /*! * @brief Sets M3 access rights in supervisor mode * * @param baseAddr The MPU peripheral base address * @param regionNum MPU region number * @param accessRights Master3 access permission */ static inline void MPU_HAL_SetM3AlternateSupervisorAccessRights(uint32_t baseAddr, mpu_region_num regionNum, mpu_supervisor_access_rights accessRights) { assert(regionNum < HW_MPU_RGDAACn_COUNT); BW_MPU_RGDAACn_M3SM(baseAddr, regionNum, accessRights); } /*! * @brief Sets M3 access rights in user mode * * @param baseAddr The MPU peripheral base address * @param regionNum MPU region number * @param accessRights Master3 access permission */ static inline void MPU_HAL_SetM3AlternateUserAccessRights(uint32_t baseAddr, mpu_region_num regionNum, mpu_user_access_rights accessRights) { assert(regionNum < HW_MPU_RGDAACn_COUNT); BW_MPU_RGDAACn_M3UM(baseAddr, regionNum, accessRights); } /*! * @brief Checks whether the M3 process identifier works in region hit evaluation. * * @param baseAddr The MPU peripheral base address. * @param regionNum MPU region number. * @retval true m3 process identifier is enabled. * @retval false m3 process identifier is disabled. */ static inline bool MPU_HAL_IsM3AlternateProcessIdentifierEnabled(uint32_t baseAddr, mpu_region_num regionNum) { assert(regionNum < HW_MPU_RGDn_WORD2_COUNT); return (1 == BR_MPU_RGDAACn_M3PE(baseAddr, regionNum)); } /*! * @brief Sets M3 process identifier value--- 1 enable process identifier in region hit evaluation and 0 disable. * * @param baseAddr The MPU peripheral base address. * @param regionNum MPU region number. * @param identifierValue process identifier value. */ static inline void MPU_HAL_SetM3AlternateProcessIdentifierValue(uint32_t baseAddr, mpu_region_num regionNum, mpu_process_identifier_value identifierValue) { assert(regionNum < HW_MPU_RGDn_WORD2_COUNT); BW_MPU_RGDAACn_M3PE(baseAddr, regionNum, identifierValue); } /*! * @brief Gets M4 access permission from alternate register. * * @param baseAddr The MPU peripheral base address. * @param regionNum MPU region number. * @param accessType Access type Read/Write. * @retval read or write permission. */ static inline mpu_access_control MPU_HAL_GetM4AlternateAccessRights(uint32_t baseAddr, mpu_region_num regionNum, mpu_access_type accessType) { assert(regionNum < HW_MPU_RGDAACn_COUNT); if(kMPUAccessRead == accessType) { return (mpu_access_control)(BR_MPU_RGDAACn_M4RE(baseAddr, regionNum)); } else { return (mpu_access_control)(BR_MPU_RGDAACn_M4WE(baseAddr, regionNum)); } } /*! * @brief Sets M4 access permission through alternate register. * * @param baseAddr The MPU peripheral base address. * @param regionNum MPU region number. * @param accessType Access type Read/Write. * @param accessControl Access permission. */ static inline void MPU_HAL_SetM4AlternateAccessRights(uint32_t baseAddr, mpu_region_num regionNum, mpu_access_type accessType, mpu_access_control accessControl) { assert(regionNum < HW_MPU_RGDAACn_COUNT); if(kMPUAccessRead == accessType) { BW_MPU_RGDAACn_M4RE(baseAddr, regionNum, accessControl); } else { BW_MPU_RGDAACn_M4WE(baseAddr, regionNum, accessControl); } } /*! * @brief Gets M5 access permission from alternate register. * * @param baseAddr The MPU peripheral base address. * @param regionNum MPU region number. * @param accessType Access type Read/Write. * @retval read or write permission. */ static inline mpu_access_control MPU_HAL_GetM5AlternateAccessRights(uint32_t baseAddr, mpu_region_num regionNum, mpu_access_type accessType) { assert(regionNum < HW_MPU_RGDAACn_COUNT); if(kMPUAccessRead == accessType) { return (mpu_access_control)(BR_MPU_RGDAACn_M5RE(baseAddr, regionNum)); } else { return (mpu_access_control)(BR_MPU_RGDAACn_M5WE(baseAddr, regionNum)); } } /*! * @brief Sets M5 access permission through alternate register. * * @param baseAddr The MPU peripheral base address. * @param regionNum MPU region number. * @param accessType Access type Read/Write. * @param accessControl Master5 Access permission. */ static inline void MPU_HAL_SetM5AlternateAccessRights(uint32_t baseAddr, mpu_region_num regionNum, mpu_access_type accessType, mpu_access_control accessControl) { assert(regionNum < HW_MPU_RGDAACn_COUNT); if(kMPUAccessRead == accessType) { BW_MPU_RGDAACn_M5RE(baseAddr, regionNum, accessControl); } else { BW_MPU_RGDAACn_M5WE(baseAddr, regionNum, accessControl); } } /*! * @brief Gets M6 access permission from alternate register. * * @param baseAddr The MPU peripheral base address. * @param regionNum MPU region number. * @param accessType Access type Read/Write. * @retval read or write permission. */ static inline mpu_access_control MPU_HAL_GetM6AlternateAccessRights(uint32_t baseAddr, mpu_region_num regionNum, mpu_access_type accessType) { assert(regionNum < HW_MPU_RGDAACn_COUNT); if(kMPUAccessRead == accessType) { return (mpu_access_control)(BR_MPU_RGDAACn_M6RE(baseAddr, regionNum)); } else { return (mpu_access_control)(BR_MPU_RGDAACn_M6WE(baseAddr, regionNum)); } } /*! * @brief Sets M6 access permission through alternate register. * * @param baseAddr The MPU peripheral base address. * @param regionNum MPU region number. * @param accessType Access type Read/Write. * @param accessControl Master6 access permission. */ static inline void MPU_HAL_SetM6AlternateAccessRights(uint32_t baseAddr, mpu_region_num regionNum, mpu_access_type accessType, mpu_access_control accessControl) { assert(regionNum < HW_MPU_RGDAACn_COUNT); if(kMPUAccessRead == accessType) { BW_MPU_RGDAACn_M6RE(baseAddr, regionNum, accessControl); } else { BW_MPU_RGDAACn_M6WE(baseAddr, regionNum, accessControl); } } /*! * @brief Gets M7 access permission from alternate register. * * @param baseAddr The MPU peripheral base address. * @param regionNum MPU region number. * @param accessType Access type Read/Write. * @retval read or write permission. */ static inline mpu_access_control MPU_HAL_GetM7AlternateAccessRights(uint32_t baseAddr, mpu_region_num regionNum, mpu_access_type accessType) { assert(regionNum < HW_MPU_RGDAACn_COUNT); if(kMPUAccessRead == accessType) { return (mpu_access_control)(BR_MPU_RGDAACn_M7RE(baseAddr, regionNum)); } else { return (mpu_access_control)(BR_MPU_RGDAACn_M7WE(baseAddr, regionNum)); } } /*! * @brief Sets M7 access permission through alternate register. * * @param baseAddr The MPU peripheral base address. * @param regionNum MPU region number. * @param accessType Access type Read/Write. * @param accessControl Master7 access permission. */ static inline void MPU_HAL_SetM7AlternateAccessRights(uint32_t baseAddr, mpu_region_num regionNum, mpu_access_type accessType, mpu_access_control accessControl) { assert(regionNum < HW_MPU_RGDAACn_COUNT); if(kMPUAccessRead == accessType) { BW_MPU_RGDAACn_M7RE(baseAddr, regionNum, accessControl); } else { BW_MPU_RGDAACn_M7WE(baseAddr, regionNum, accessControl); } } /*! * @brief Initializes the MPU module. * * @param baseAddr The MPU peripheral base address. */ void MPU_HAL_Init(uint32_t baseAddr); /*@}*/ #if defined(__cplusplus) } #endif /*! @}*/ #endif /* MBED_NO_MPU */ #endif /* __FSL_MPU_HAL_H__*/ /******************************************************************************* * EOF *******************************************************************************/ ================================================ FILE: Zelig/mbed/TARGET_K64F/TARGET_Freescale/TARGET_KPSDK_MCUS/TARGET_KPSDK_CODE/hal/osc/fsl_osc_features.h ================================================ /* ** ################################################################### ** Version: rev. 1.0, 2014-05-14 ** Build: b140515 ** ** Abstract: ** Chip specific module features. ** ** Copyright: 2014 Freescale Semiconductor, Inc. ** All rights reserved. ** ** Redistribution and use in source and binary forms, with or without modification, ** are permitted provided that the following conditions are met: ** ** o Redistributions of source code must retain the above copyright notice, this list ** of conditions and the following disclaimer. ** ** o Redistributions in binary form must reproduce the above copyright notice, this ** list of conditions and the following disclaimer in the documentation and/or ** other materials provided with the distribution. ** ** o Neither the name of Freescale Semiconductor, Inc. nor the names of its ** contributors may be used to endorse or promote products derived from this ** software without specific prior written permission. ** ** THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ** ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED ** WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE ** DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT 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. ** ** http: www.freescale.com ** mail: support@freescale.com ** ** Revisions: ** - rev. 1.0 (2014-05-14) ** Customer release. ** ** ################################################################### */ #if !defined(__FSL_OSC_FEATURES_H__) #define __FSL_OSC_FEATURES_H__ #if defined(CPU_MK02FN128VFM10) || defined(CPU_MK02FN64VFM10) || defined(CPU_MK02FN128VLF10) || defined(CPU_MK02FN64VLF10) || \ defined(CPU_MK02FN128VLH10) || defined(CPU_MK02FN64VLH10) || defined(CPU_MK22FN128VDC10) || defined(CPU_MK22FN128VLH10) || \ defined(CPU_MK22FN128VLL10) || defined(CPU_MK22FN128VMP10) || defined(CPU_MK22FN256VDC12) || defined(CPU_MK22FN256VLH12) || \ defined(CPU_MK22FN256VLL12) || defined(CPU_MK22FN256VMP12) || defined(CPU_MK22FN512VDC12) || defined(CPU_MK22FN512VLH12) || \ defined(CPU_MK22FN512VLL12) || defined(CPU_MK65FN2M0CAC18) || defined(CPU_MK65FX1M0CAC18) || defined(CPU_MK65FN2M0VMI18) || \ defined(CPU_MK65FX1M0VMI18) || defined(CPU_MK66FN2M0VLQ18) || defined(CPU_MK66FX1M0VLQ18) || defined(CPU_MK66FN2M0VMD18) || \ defined(CPU_MK66FX1M0VMD18) || defined(CPU_MKV30F128VFM10) || defined(CPU_MKV30F64VFM10) || defined(CPU_MKV30F128VLF10) || \ defined(CPU_MKV30F64VLF10) || defined(CPU_MKV30F128VLH10) || defined(CPU_MKV30F64VLH10) || defined(CPU_MKV31F128VLH10) || \ defined(CPU_MKV31F128VLL10) || defined(CPU_MKV31F256VLH12) || defined(CPU_MKV31F256VLL12) || defined(CPU_MKV31F512VLH12) || \ defined(CPU_MKV31F512VLL12) /* @brief Has OSC1 external oscillator. */ #define FSL_FEATURE_OSC_HAS_OSC1 (0) /* @brief Has OSC0 external oscillator. */ #define FSL_FEATURE_OSC_HAS_OSC0 (0) /* @brief Has OSC external oscillator (without index). */ #define FSL_FEATURE_OSC_HAS_OSC (1) /* @brief Number of OSC external oscillators. */ #define FSL_FEATURE_OSC_OSC_COUNT (1) /* @brief Has external reference clock divider (register bit field DIV[ERPS]). */ #define FSL_FEATURE_OSC_HAS_EXT_REF_CLOCK_DIVIDER (1) #elif defined(CPU_MK20DX128VMP5) || defined(CPU_MK20DN128VMP5) || defined(CPU_MK20DX64VMP5) || defined(CPU_MK20DN64VMP5) || \ defined(CPU_MK20DX32VMP5) || defined(CPU_MK20DN32VMP5) || defined(CPU_MK20DX128VLH5) || defined(CPU_MK20DN128VLH5) || \ defined(CPU_MK20DX64VLH5) || defined(CPU_MK20DN64VLH5) || defined(CPU_MK20DX32VLH5) || defined(CPU_MK20DN32VLH5) || \ defined(CPU_MK20DX128VFM5) || defined(CPU_MK20DN128VFM5) || defined(CPU_MK20DX64VFM5) || defined(CPU_MK20DN64VFM5) || \ defined(CPU_MK20DX32VFM5) || defined(CPU_MK20DN32VFM5) || defined(CPU_MK20DX128VFT5) || defined(CPU_MK20DN128VFT5) || \ defined(CPU_MK20DX64VFT5) || defined(CPU_MK20DN64VFT5) || defined(CPU_MK20DX32VFT5) || defined(CPU_MK20DN32VFT5) || \ defined(CPU_MK20DX128VLF5) || defined(CPU_MK20DN128VLF5) || defined(CPU_MK20DX64VLF5) || defined(CPU_MK20DN64VLF5) || \ defined(CPU_MK20DX32VLF5) || defined(CPU_MK20DN32VLF5) || defined(CPU_MKL05Z8VFK4) || defined(CPU_MKL05Z16VFK4) || \ defined(CPU_MKL05Z32VFK4) || defined(CPU_MKL05Z8VLC4) || defined(CPU_MKL05Z16VLC4) || defined(CPU_MKL05Z32VLC4) || \ defined(CPU_MKL05Z8VFM4) || defined(CPU_MKL05Z16VFM4) || defined(CPU_MKL05Z32VFM4) || defined(CPU_MKL05Z16VLF4) || \ defined(CPU_MKL05Z32VLF4) || defined(CPU_MKL13Z64VFM4) || defined(CPU_MKL13Z128VFM4) || defined(CPU_MKL13Z256VFM4) || \ defined(CPU_MKL13Z64VFT4) || defined(CPU_MKL13Z128VFT4) || defined(CPU_MKL13Z256VFT4) || defined(CPU_MKL13Z64VLH4) || \ defined(CPU_MKL13Z128VLH4) || defined(CPU_MKL13Z256VLH4) || defined(CPU_MKL13Z64VMP4) || defined(CPU_MKL13Z128VMP4) || \ defined(CPU_MKL13Z256VMP4) || defined(CPU_MKL23Z64VFM4) || defined(CPU_MKL23Z128VFM4) || defined(CPU_MKL23Z256VFM4) || \ defined(CPU_MKL23Z64VFT4) || defined(CPU_MKL23Z128VFT4) || defined(CPU_MKL23Z256VFT4) || defined(CPU_MKL23Z64VLH4) || \ defined(CPU_MKL23Z128VLH4) || defined(CPU_MKL23Z256VLH4) || defined(CPU_MKL23Z64VMP4) || defined(CPU_MKL23Z128VMP4) || \ defined(CPU_MKL23Z256VMP4) || defined(CPU_MKL25Z32VFM4) || defined(CPU_MKL25Z64VFM4) || defined(CPU_MKL25Z128VFM4) || \ defined(CPU_MKL25Z32VFT4) || defined(CPU_MKL25Z64VFT4) || defined(CPU_MKL25Z128VFT4) || defined(CPU_MKL25Z32VLH4) || \ defined(CPU_MKL25Z64VLH4) || defined(CPU_MKL25Z128VLH4) || defined(CPU_MKL25Z32VLK4) || defined(CPU_MKL25Z64VLK4) || \ defined(CPU_MKL25Z128VLK4) || defined(CPU_MKL26Z256VLK4) || defined(CPU_MKL26Z128VLL4) || defined(CPU_MKL26Z256VLL4) || \ defined(CPU_MKL26Z128VMC4) || defined(CPU_MKL26Z256VMC4) || defined(CPU_MKL33Z128VLH4) || defined(CPU_MKL33Z256VLH4) || \ defined(CPU_MKL33Z128VMP4) || defined(CPU_MKL33Z256VMP4) || defined(CPU_MKL43Z64VLH4) || defined(CPU_MKL43Z128VLH4) || \ defined(CPU_MKL43Z256VLH4) || defined(CPU_MKL43Z64VMP4) || defined(CPU_MKL43Z128VMP4) || defined(CPU_MKL43Z256VMP4) || \ defined(CPU_MKL46Z128VLH4) || defined(CPU_MKL46Z256VLH4) || defined(CPU_MKL46Z128VLL4) || defined(CPU_MKL46Z256VLL4) || \ defined(CPU_MKL46Z128VMC4) || defined(CPU_MKL46Z256VMC4) /* @brief Has OSC1 external oscillator. */ #define FSL_FEATURE_OSC_HAS_OSC1 (0) /* @brief Has OSC0 external oscillator. */ #define FSL_FEATURE_OSC_HAS_OSC0 (1) /* @brief Has OSC external oscillator (without index). */ #define FSL_FEATURE_OSC_HAS_OSC (0) /* @brief Number of OSC external oscillators. */ #define FSL_FEATURE_OSC_OSC_COUNT (1) /* @brief Has external reference clock divider (register bit field DIV[ERPS]). */ #define FSL_FEATURE_OSC_HAS_EXT_REF_CLOCK_DIVIDER (0) #elif defined(CPU_MK24FN1M0VDC12) || defined(CPU_MK24FN1M0VLL12) || defined(CPU_MK24FN1M0VLQ12) || defined(CPU_MK24FN256VDC12) || \ defined(CPU_MK63FN1M0VLQ12) || defined(CPU_MK63FN1M0VMD12) || defined(CPU_MK64FX512VDC12) || defined(CPU_MK64FN1M0VDC12) || \ defined(CPU_MK64FX512VLL12) || defined(CPU_MK64FN1M0VLL12) || defined(CPU_MK64FX512VLQ12) || defined(CPU_MK64FN1M0VLQ12) || \ defined(CPU_MK64FX512VMD12) || defined(CPU_MK64FN1M0VMD12) /* @brief Has OSC1 external oscillator. */ #define FSL_FEATURE_OSC_HAS_OSC1 (0) /* @brief Has OSC0 external oscillator. */ #define FSL_FEATURE_OSC_HAS_OSC0 (0) /* @brief Has OSC external oscillator (without index). */ #define FSL_FEATURE_OSC_HAS_OSC (1) /* @brief Number of OSC external oscillators. */ #define FSL_FEATURE_OSC_OSC_COUNT (1) /* @brief Has external reference clock divider (register bit field DIV[ERPS]). */ #define FSL_FEATURE_OSC_HAS_EXT_REF_CLOCK_DIVIDER (0) #elif defined(CPU_MK70FN1M0VMF12) || defined(CPU_MK70FX512VMF12) || defined(CPU_MK70FN1M0VMF15) || defined(CPU_MK70FX512VMF15) || \ defined(CPU_MK70FN1M0VMJ12) || defined(CPU_MK70FX512VMJ12) || defined(CPU_MK70FN1M0VMJ15) || defined(CPU_MK70FX512VMJ15) /* @brief Has OSC1 external oscillator. */ #define FSL_FEATURE_OSC_HAS_OSC1 (1) /* @brief Has OSC0 external oscillator. */ #define FSL_FEATURE_OSC_HAS_OSC0 (1) /* @brief Has OSC external oscillator (without index). */ #define FSL_FEATURE_OSC_HAS_OSC (0) /* @brief Number of OSC external oscillators. */ #define FSL_FEATURE_OSC_OSC_COUNT (2) /* @brief Has external reference clock divider (register bit field DIV[ERPS]). */ #define FSL_FEATURE_OSC_HAS_EXT_REF_CLOCK_DIVIDER (0) #elif defined(CPU_MKL03Z32CAF4) || defined(CPU_MKL03Z8VFG4) || defined(CPU_MKL03Z16VFG4) || defined(CPU_MKL03Z32VFG4) || \ defined(CPU_MKL03Z8VFK4) || defined(CPU_MKL03Z16VFK4) || defined(CPU_MKL03Z32VFK4) /* @brief Has OSC1 external oscillator. */ #define FSL_FEATURE_OSC_HAS_OSC1 (0) /* @brief Has OSC0 external oscillator. */ #define FSL_FEATURE_OSC_HAS_OSC0 (0) /* @brief Has OSC external oscillator (without index). */ #define FSL_FEATURE_OSC_HAS_OSC (0) /* @brief Number of OSC external oscillators. */ #define FSL_FEATURE_OSC_OSC_COUNT (0) /* @brief Has external reference clock divider (register bit field DIV[ERPS]). */ #define FSL_FEATURE_OSC_HAS_EXT_REF_CLOCK_DIVIDER (0) #elif defined(CPU_MKV40F128VLH15) || defined(CPU_MKV40F128VLL15) || defined(CPU_MKV40F256VLH15) || defined(CPU_MKV40F256VLL15) || \ defined(CPU_MKV40F64VLH15) || defined(CPU_MKV43F128VLH15) || defined(CPU_MKV43F128VLL15) || defined(CPU_MKV43F64VLH15) || \ defined(CPU_MKV44F128VLH15) || defined(CPU_MKV44F128VLL15) || defined(CPU_MKV44F64VLH15) || defined(CPU_MKV45F128VLH15) || \ defined(CPU_MKV45F128VLL15) || defined(CPU_MKV45F256VLH15) || defined(CPU_MKV45F256VLL15) || defined(CPU_MKV46F128VLH15) || \ defined(CPU_MKV46F128VLL15) || defined(CPU_MKV46F256VLH15) || defined(CPU_MKV46F256VLL15) /* @brief Has OSC1 external oscillator. */ #define FSL_FEATURE_OSC_HAS_OSC1 (0) /* @brief Has OSC0 external oscillator. */ #define FSL_FEATURE_OSC_HAS_OSC0 (0) /* @brief Has OSC external oscillator (without index). */ #define FSL_FEATURE_OSC_HAS_OSC (0) /* @brief Number of OSC external oscillators. */ #define FSL_FEATURE_OSC_OSC_COUNT (0) /* @brief Has external reference clock divider (register bit field DIV[ERPS]). */ #define FSL_FEATURE_OSC_HAS_EXT_REF_CLOCK_DIVIDER (1) #else #error "No valid CPU defined!" #endif #endif /* __FSL_OSC_FEATURES_H__ */ /******************************************************************************* * EOF ******************************************************************************/ ================================================ FILE: Zelig/mbed/TARGET_K64F/TARGET_Freescale/TARGET_KPSDK_MCUS/TARGET_KPSDK_CODE/hal/osc/fsl_osc_hal.h ================================================ /* * Copyright (c) 2013 - 2014, Freescale Semiconductor, Inc. * All rights reserved. * * Redistribution and use in source and binary forms, with or without modification, * are permitted provided that the following conditions are met: * * o Redistributions of source code must retain the above copyright notice, this list * of conditions and the following disclaimer. * * o Redistributions in binary form must reproduce the above copyright notice, this * list of conditions and the following disclaimer in the documentation and/or * other materials provided with the distribution. * * o Neither the name of Freescale Semiconductor, Inc. nor the names of its * contributors may be used to endorse or promote products derived from this * software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT 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. */ #if !defined(__FSL_OSC_HAL_H__) #define __FSL_OSC_HAL_H__ #include #include #include #include "fsl_device_registers.h" #include "fsl_osc_features.h" /*! @addtogroup osc_hal*/ /*! @{*/ /*! @file fsl_osc_hal.h */ /******************************************************************************* * Definitions ******************************************************************************/ /*! @brief Oscillator capacitor load configurations.*/ typedef enum _osc_capacitor_config { kOscCapacitor2p = OSC_CR_SC2P_MASK, /*!< 2 pF capacitor load */ kOscCapacitor4p = OSC_CR_SC4P_MASK, /*!< 4 pF capacitor load */ kOscCapacitor8p = OSC_CR_SC8P_MASK, /*!< 8 pF capacitor load */ kOscCapacitor16p = OSC_CR_SC16P_MASK /*!< 16 pF capacitor load */ } osc_capacitor_config_t; /******************************************************************************* * API ******************************************************************************/ #if defined(__cplusplus) extern "C" { #endif /* __cplusplus*/ /*! @name oscillator control APIs*/ /*@{*/ /*! * @brief Enables the external reference clock for the oscillator. * * This function enables the external reference clock output * for the oscillator, OSCERCLK. This clock is used * by many peripherals. It should be enabled at an early system initialization * stage to ensure the peripherals can select and use it. * * @param baseAddr Oscillator register base address * @param enable enable/disable the clock */ void OSC_HAL_SetExternalRefClkCmd(uint32_t baseAddr, bool enable); /*! * @brief Gets the external reference clock enable setting for the oscillator. * * This function gets the external reference clock output enable setting * for the oscillator , OSCERCLK. This clock is used * by many peripherals. It should be enabled at an early system initialization * stage to ensure the peripherals could select and use it. * * @param baseAddr Oscillator register base address * @return enable clock enable/disable setting */ bool OSC_HAL_GetExternalRefClkCmd(uint32_t baseAddr); /*! * @brief Enables/disables the external reference clock in stop mode. * * This function enables/disables the external reference clock (OSCERCLK) when an * MCU enters the stop mode. * * @param baseAddr Oscillator register base address * @param enable enable/disable setting */ void OSC_HAL_SetExternalRefClkInStopModeCmd(uint32_t baseAddr, bool enable); /*! * @brief Gets the external reference clock enable setting in stop mode. * * This function gets the external reference clock (OSCERCLK) enable setting when an * MCU enters stop mode. * * @param baseAddr Oscillator register base address */ bool OSC_HAL_GetExternalRefClkInStopModeCmd(uint32_t baseAddr); /*! * @brief Enables the capacitor configuration for the oscillator. * * This function enables the specified capacitors configuration for the * oscillator. This should be done in the early system level initialization function call * based on the system configuration. * * @param baseAddr Oscillator register base address * @param capacitorConfig Capacitor configuration. (2p, 4p, 8p, 16p) * @param enable enable/disable the Capacitor configuration */ void OSC_HAL_SetCapacitorCmd(uint32_t baseAddr, osc_capacitor_config_t capacitorConfig, bool enable); /*! * @brief Gets the capacitor configuration for a specific oscillator. * * This function gets the specified capacitors configuration for an * oscillator. * * @param baseAddr Oscillator register base address * @param capacitorConfig Capacitor configuration. * @return enable enable/disable setting */ bool OSC_HAL_GetCapacitorCmd(uint32_t baseAddr, osc_capacitor_config_t capacitorConfig); #if FSL_FEATURE_OSC_HAS_EXT_REF_CLOCK_DIVIDER /*! * @brief Sets the external reference clock divider. * * This function sets the divider for the external reference clock. * * @param baseAddr Oscillator register base address * @param divider divider settings */ void OSC_HAL_SetExternalRefClkDivCmd(uint32_t baseAddr, uint32_t divider); /*! * @brief Gets the external reference clock divider. * * This function gets the divider for the external reference clock. * * @param baseAddr Oscillator register base address * @return divider divider settings */ uint32_t OSC_HAL_GetExternalRefClkDivCmd(uint32_t baseAddr); #endif /*@}*/ #if defined(__cplusplus) } #endif /* __cplusplus*/ /*! @}*/ #endif /* __FSL_OSC_HAL_H__*/ /******************************************************************************* * EOF ******************************************************************************/ ================================================ FILE: Zelig/mbed/TARGET_K64F/TARGET_Freescale/TARGET_KPSDK_MCUS/TARGET_KPSDK_CODE/hal/pdb/fsl_pdb_features.h ================================================ /* ** ################################################################### ** Version: rev. 1.0, 2014-05-14 ** Build: b140515 ** ** Abstract: ** Chip specific module features. ** ** Copyright: 2014 Freescale Semiconductor, Inc. ** All rights reserved. ** ** Redistribution and use in source and binary forms, with or without modification, ** are permitted provided that the following conditions are met: ** ** o Redistributions of source code must retain the above copyright notice, this list ** of conditions and the following disclaimer. ** ** o Redistributions in binary form must reproduce the above copyright notice, this ** list of conditions and the following disclaimer in the documentation and/or ** other materials provided with the distribution. ** ** o Neither the name of Freescale Semiconductor, Inc. nor the names of its ** contributors may be used to endorse or promote products derived from this ** software without specific prior written permission. ** ** THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ** ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED ** WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE ** DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT 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. ** ** http: www.freescale.com ** mail: support@freescale.com ** ** Revisions: ** - rev. 1.0 (2014-05-14) ** Customer release. ** ** ################################################################### */ #if !defined(__FSL_PDB_FEATURES_H__) #define __FSL_PDB_FEATURES_H__ #if defined(CPU_MK02FN128VFM10) || defined(CPU_MK02FN64VFM10) || defined(CPU_MK02FN128VLF10) || defined(CPU_MK02FN64VLF10) || \ defined(CPU_MK02FN128VLH10) || defined(CPU_MK02FN64VLH10) || defined(CPU_MK20DX128VMP5) || defined(CPU_MK20DN128VMP5) || \ defined(CPU_MK20DX64VMP5) || defined(CPU_MK20DN64VMP5) || defined(CPU_MK20DX32VMP5) || defined(CPU_MK20DN32VMP5) || \ defined(CPU_MK20DX128VLH5) || defined(CPU_MK20DN128VLH5) || defined(CPU_MK20DX64VLH5) || defined(CPU_MK20DN64VLH5) || \ defined(CPU_MK20DX32VLH5) || defined(CPU_MK20DN32VLH5) || defined(CPU_MK20DX128VFM5) || defined(CPU_MK20DN128VFM5) || \ defined(CPU_MK20DX64VFM5) || defined(CPU_MK20DN64VFM5) || defined(CPU_MK20DX32VFM5) || defined(CPU_MK20DN32VFM5) || \ defined(CPU_MK20DX128VFT5) || defined(CPU_MK20DN128VFT5) || defined(CPU_MK20DX64VFT5) || defined(CPU_MK20DN64VFT5) || \ defined(CPU_MK20DX32VFT5) || defined(CPU_MK20DN32VFT5) || defined(CPU_MK20DX128VLF5) || defined(CPU_MK20DN128VLF5) || \ defined(CPU_MK20DX64VLF5) || defined(CPU_MK20DN64VLF5) || defined(CPU_MK20DX32VLF5) || defined(CPU_MK20DN32VLF5) || \ defined(CPU_MK22FN128VDC10) || defined(CPU_MK22FN128VLH10) || defined(CPU_MK22FN128VLL10) || defined(CPU_MK22FN128VMP10) || \ defined(CPU_MK22FN256VDC12) || defined(CPU_MK22FN256VLH12) || defined(CPU_MK22FN256VLL12) || defined(CPU_MK22FN256VMP12) || \ defined(CPU_MK22FN512VDC12) || defined(CPU_MK22FN512VLH12) || defined(CPU_MK22FN512VLL12) || defined(CPU_MK24FN1M0VDC12) || \ defined(CPU_MK24FN1M0VLL12) || defined(CPU_MK24FN1M0VLQ12) || defined(CPU_MK24FN256VDC12) || defined(CPU_MK63FN1M0VLQ12) || \ defined(CPU_MK63FN1M0VMD12) || defined(CPU_MK64FX512VDC12) || defined(CPU_MK64FN1M0VDC12) || defined(CPU_MK64FX512VLL12) || \ defined(CPU_MK64FN1M0VLL12) || defined(CPU_MK64FX512VLQ12) || defined(CPU_MK64FN1M0VLQ12) || defined(CPU_MK64FX512VMD12) || \ defined(CPU_MK64FN1M0VMD12) || defined(CPU_MK65FN2M0CAC18) || defined(CPU_MK65FX1M0CAC18) || defined(CPU_MK65FN2M0VMI18) || \ defined(CPU_MK65FX1M0VMI18) || defined(CPU_MK66FN2M0VLQ18) || defined(CPU_MK66FX1M0VLQ18) || defined(CPU_MK66FN2M0VMD18) || \ defined(CPU_MK66FX1M0VMD18) || defined(CPU_MK70FN1M0VMF12) || defined(CPU_MK70FX512VMF12) || defined(CPU_MK70FN1M0VMF15) || \ defined(CPU_MK70FX512VMF15) || defined(CPU_MK70FN1M0VMJ12) || defined(CPU_MK70FX512VMJ12) || defined(CPU_MK70FN1M0VMJ15) || \ defined(CPU_MK70FX512VMJ15) || defined(CPU_MKV30F128VFM10) || defined(CPU_MKV30F64VFM10) || defined(CPU_MKV30F128VLF10) || \ defined(CPU_MKV30F64VLF10) || defined(CPU_MKV30F128VLH10) || defined(CPU_MKV30F64VLH10) || defined(CPU_MKV31F128VLH10) || \ defined(CPU_MKV31F128VLL10) || defined(CPU_MKV31F256VLH12) || defined(CPU_MKV31F256VLL12) || defined(CPU_MKV31F512VLH12) || \ defined(CPU_MKV31F512VLL12) || defined(CPU_MKV40F128VLH15) || defined(CPU_MKV40F128VLL15) || defined(CPU_MKV40F256VLH15) || \ defined(CPU_MKV40F256VLL15) || defined(CPU_MKV40F64VLH15) || defined(CPU_MKV43F128VLH15) || defined(CPU_MKV43F128VLL15) || \ defined(CPU_MKV43F64VLH15) || defined(CPU_MKV44F128VLH15) || defined(CPU_MKV44F128VLL15) || defined(CPU_MKV44F64VLH15) || \ defined(CPU_MKV45F128VLH15) || defined(CPU_MKV45F128VLL15) || defined(CPU_MKV45F256VLH15) || defined(CPU_MKV45F256VLL15) || \ defined(CPU_MKV46F128VLH15) || defined(CPU_MKV46F128VLL15) || defined(CPU_MKV46F256VLH15) || defined(CPU_MKV46F256VLL15) /* @brief Define the count of supporting ADC pre-trigger for each channel. */ #define FSL_FEATURE_PDB_ADC_PRE_CHANNEL_COUNT (2) #else #error "No valid CPU defined!" #endif #endif /* __FSL_PDB_FEATURES_H__ */ /******************************************************************************* * EOF ******************************************************************************/ ================================================ FILE: Zelig/mbed/TARGET_K64F/TARGET_Freescale/TARGET_KPSDK_MCUS/TARGET_KPSDK_CODE/hal/pdb/fsl_pdb_hal.h ================================================ /* * Copyright (c) 2014, Freescale Semiconductor, Inc. * All rights reserved. * * Redistribution and use in source and binary forms, with or without modification, * are permitted provided that the following conditions are met: * * o Redistributions of source code must retain the above copyright notice, this list * of conditions and the following disclaimer. * * o Redistributions in binary form must reproduce the above copyright notice, this * list of conditions and the following disclaimer in the documentation and/or * other materials provided with the distribution. * * o Neither the name of Freescale Semiconductor, Inc. nor the names of its * contributors may be used to endorse or promote products derived from this * software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT 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. */ #ifndef __FSL_PDB_HAL_H__ #define __FSL_PDB_HAL_H__ #include #include #include #include "fsl_device_registers.h" #include "fsl_pdb_features.h" /*! * @addtogroup pdb_hal * @{ */ /****************************************************************************** * Definitions *****************************************************************************/ /*! * @brief PDB status return codes. */ typedef enum _pdb_status { kStatus_PDB_Success = 0U, /*!< Success. */ kStatus_PDB_InvalidArgument = 1U, /*!< Invalid argument existed. */ kStatus_PDB_Failed = 2U /*!< Execution failed. */ } pdb_status_t; /*! * @brief Defines the type of value load mode for the PDB module. * * Some timing related registers, such as the MOD, IDLY, CHnDLYm, INTx and POyDLY, * buffer the setting values. Only the load operation is triggered. * The setting value is loaded from a buffer and takes effect. There are * four loading modes to fit different applications. */ typedef enum _pdb_load_mode { kPdbLoadImmediately = 0U, /*!< Loaded immediately after load operation. */ kPdbLoadAtModuloCounter = 1U, /*!< Loaded when counter hits the modulo after load operation. */ kPdbLoadAtNextTrigger = 2U, /*!< Loaded when detecting an input trigger after load operation. */ kPdbLoadAtModuloCounterOrNextTrigger = 3U /*!< Loaded when counter hits the modulo or detecting an input trigger after load operation. */ } pdb_load_mode_t; /*! * @brief Defines the type of prescaler divider for the PDB counter clock. */ typedef enum _pdb_clk_prescaler_div_mode { kPdbClkPreDivBy1 = 0U, /*!< Counting divided by multiplication factor selected by MULT. */ kPdbClkPreDivBy2 = 1U, /*!< Counting divided by multiplication factor selected by 2 times ofMULT. */ kPdbClkPreDivBy4 = 2U, /*!< Counting divided by multiplication factor selected by 4 times ofMULT. */ kPdbClkPreDivBy8 = 3U, /*!< Counting divided by multiplication factor selected by 8 times ofMULT. */ kPdbClkPreDivBy16 = 4U, /*!< Counting divided by multiplication factor selected by 16 times ofMULT. */ kPdbClkPreDivBy32 = 5U, /*!< Counting divided by multiplication factor selected by 32 times ofMULT. */ kPdbClkPreDivBy64 = 6U, /*!< Counting divided by multiplication factor selected by 64 times ofMULT. */ kPdbClkPreDivBy128 = 7U, /*!< Counting divided by multiplication factor selected by 128 times ofMULT. */ } pdb_clk_prescaler_div_mode_t; /*! * @brief Defines the type of trigger source mode for the PDB. * * Selects the trigger input source for the PDB. The trigger input source can * be internal or external (EXTRG pin), or the software trigger. */ typedef enum _pdb_trigger_src_mode { kPdbTrigger0 = 0U, /*!< Select trigger-In 0. */ kPdbTrigger1 = 1U, /*!< Select trigger-In 1. */ kPdbTrigger2 = 2U, /*!< Select trigger-In 2. */ kPdbTrigger3 = 3U, /*!< Select trigger-In 3. */ kPdbTrigger4 = 4U, /*!< Select trigger-In 4. */ kPdbTrigger5 = 5U, /*!< Select trigger-In 5. */ kPdbTrigger6 = 6U, /*!< Select trigger-In 6. */ kPdbTrigger7 = 7U, /*!< Select trigger-In 7. */ kPdbTrigger8 = 8U, /*!< Select trigger-In 8. */ kPdbTrigger9 = 9U, /*!< Select trigger-In 8. */ kPdbTrigger10 = 10U, /*!< Select trigger-In 10. */ kPdbTrigger11 = 11U, /*!< Select trigger-In 11. */ kPdbTrigger12 = 12U, /*!< Select trigger-In 12. */ kPdbTrigger13 = 13U, /*!< Select trigger-In 13. */ kPdbTrigger14 = 14U, /*!< Select trigger-In 14. */ kPdbSoftTrigger = 15U, /*!< Select software trigger. */ } pdb_trigger_src_mode_t; /*! * @brief Defines the type of the multiplication source mode for PDB. * * Selects the multiplication factor of the prescaler divider for the PDB counter clock. */ typedef enum _pdb_mult_factor_mode { kPdbMultFactorAs1 = 0U, /*!< Multiplication factor is 1. */ kPdbMultFactorAs10 = 1U, /*!< Multiplication factor is 10. */ kPdbMultFactorAs20 = 2U, /*!< Multiplication factor is 20. */ kPdbMultFactorAs40 = 3U /*!< Multiplication factor is 40. */ } pdb_mult_factor_mode_t; #if defined(__cplusplus) extern "C" { #endif /******************************************************************************* * API ******************************************************************************/ /*! * @brief Resets the PDB registers to a known state. * * This function resets the PDB registers to a known state. This state is * defined in a reference manual and is power on reset value. * * @param baseAddr Register base address for the module. */ void PDB_HAL_Init(uint32_t baseAddr); /*! * @brief Sets the load mode for timing registers. * * This function sets the load mode for some timing registers including * MOD, IDLY, CHnDLYm, INTx and POyDLY. * * @param baseAddr Register base address for the module. * @param mode Selection of mode, see to "pdb_load_mode_t". */ static inline void PDB_HAL_SetLoadMode(uint32_t baseAddr, pdb_load_mode_t mode) { BW_PDB_SC_LDMOD(baseAddr, (uint32_t)mode); } /*! * @brief Switches to enable the PDB sequence error interrupt. * * This function switches to enable the PDB sequence error interrupt. * * @param baseAddr Register base address for the module. * @param enable The switcher to assert the feature. */ static inline void PDB_HAL_SetSeqErrIntCmd(uint32_t baseAddr, bool enabled) { BW_PDB_SC_PDBEIE(baseAddr, (enabled ? 1U : 0U) ); } /*! * @brief Triggers the DAC by software if enabled. * * If enabled, this function triggers the DAC by using software. * * @param baseAddr Register base address for the module. */ static inline void PDB_HAL_SetSoftTriggerCmd(uint32_t baseAddr) { BW_PDB_SC_SWTRIG(baseAddr, 1U); } /*! * @brief Switches to enable the PDB DMA support. * * This function switches to enable the PDB DMA support. * * @param baseAddr Register base address for the module. * @param enable The switcher to assert the feature. */ static inline void PDB_HAL_SetDmaCmd(uint32_t baseAddr, bool enable) { BW_PDB_SC_DMAEN(baseAddr, (enable ? 1U : 0U) ); } /*! * @brief Sets the prescaler divider from the peripheral bus clock for the PDB. * * This function sets the prescaler divider from the peripheral bus clock for the PDB. * * @param baseAddr Register base address for the module. * @param mode Selection of mode, see to "pdb_clk_prescaler_div_mode_t". */ static inline void PDB_HAL_SetPreDivMode(uint32_t baseAddr, pdb_clk_prescaler_div_mode_t mode) { BW_PDB_SC_PRESCALER(baseAddr, (uint32_t)mode); } /*! * @brief Sets the trigger source mode for the PDB module. * * This function sets the trigger source mode for the PDB module. * * @param baseAddr Register base address for the module. * @param mode Selection of mode, see to "pdb_trigger_src_mode_t". */ static inline void PDB_HAL_SetTriggerSrcMode(uint32_t baseAddr, pdb_trigger_src_mode_t mode) { BW_PDB_SC_TRGSEL(baseAddr, (uint32_t)mode); } /*! * @brief Switches on to enable the PDB module. * * This function switches on to enable the PDB module. * * @param baseAddr Register base address for the module. */ static inline void PDB_HAL_Enable(uint32_t baseAddr) { BW_PDB_SC_PDBEN(baseAddr, 1U); } /*! * @brief Switches off to enable the PDB module. * * This function switches off to enable the PDB module. * * @param baseAddr Register base address for the module. */ static inline void PDB_HAL_Disable(uint32_t baseAddr) { BW_PDB_SC_PDBEN(baseAddr, 0U); } /*! * @brief Gets the PDB delay interrupt flag. * * This function gets the PDB delay interrupt flag. * * @param baseAddr Register base address for the module. * @return Flat status, true if the flag is set. */ static inline bool PDB_HAL_GetIntFlag(uint32_t baseAddr) { return (1U == BR_PDB_SC_PDBIF(baseAddr)); } /*! * @brief Clears the PDB delay interrupt flag. * * This function clears PDB delay interrupt flag. * * @param baseAddr Register base address for the module. * @return Flat status, true if the flag is set. */ static inline void PDB_HAL_ClearIntFlag(uint32_t baseAddr) { BW_PDB_SC_PDBIF(baseAddr, 0U); } /*! * @brief Switches to enable the PDB interrupt. * * This function switches to enable the PDB interrupt. * * @param baseAddr Register base address for the module. * @param enable The switcher to assert the feature. */ static inline void PDB_HAL_SetIntCmd(uint32_t baseAddr, bool enable) { BW_PDB_SC_PDBIE(baseAddr, (enable ? 1U : 0U) ); } /*! * @brief Sets the PDB prescaler multiplication factor. * * This function sets the PDB prescaler multiplication factor. * * @param baseAddr Register base address for the module. * @param mode Selection of mode, see to "pdb_mult_factor_mode_t". */ static inline void PDB_HAL_SetPreMultFactorMode(uint32_t baseAddr, pdb_mult_factor_mode_t mode) { BW_PDB_SC_MULT(baseAddr, (uint32_t)mode); } /*! * @brief Switches to enable the PDB continuous mode. * * This function switches to enable the PDB continuous mode. * * @param baseAddr Register base address for the module. * @param enable The switcher to assert the feature. */ static inline void PDB_HAL_SetContinuousModeCmd(uint32_t baseAddr, bool enable) { BW_PDB_SC_CONT(baseAddr, (enable ? 1U : 0U) ); } /*! * @brief Loads the delay registers value for the PDB module. * * This function sets the LDOK bit and loads the delay registers value. * Writing one to this bit updates the internal registers MOD, IDLY, CHnDLYm, * DACINTx, and POyDLY with the values written to their buffers. The MOD, IDLY, * CHnDLYm, DACINTx, and POyDLY take effect according to the load mode settings. * * After one is written to the LDOK bit, the values in the buffers of above mentioned registers * are not effective and cannot be written until the values in the * buffers are loaded into their internal registers. * The LDOK can be written only when the the PDB is enabled or as alone with it. It is * automatically cleared either when the values in the buffers are loaded into the * internal registers or when the PDB is disabled. * * @param baseAddr Register base address for the module. */ static inline void PDB_HAL_SetLoadRegsCmd(uint32_t baseAddr) { BW_PDB_SC_LDOK(baseAddr, 1U); } /*! * @brief Sets the modulus value for the PDB module. * * This function sets the modulus value for the PDB module. * When the counter reaches the setting value, it is automatically reset to zero. * When in continuous mode, the counter begins to increase * again. * * @param baseAddr Register base address for the module. * @param value The setting value of upper limit for PDB counter. */ static inline void PDB_HAL_SetModulusValue(uint32_t baseAddr, uint32_t value) { BW_PDB_MOD_MOD(baseAddr, value); } /*! * @brief Gets the modulus value for the PDB module. * * This function gets the modulus value for the PDB module. * * @param baseAddr Register base address for the module. * @return The current value of upper limit for counter. */ static inline uint32_t PDB_HAL_GetModulusValue(uint32_t baseAddr) { return BR_PDB_MOD_MOD(baseAddr); } /*! * @brief Gets the PDB counter value. * * This function gets the PDB counter value. * * @param baseAddr Register base address for the module. * @return The current counter value. */ static inline uint32_t PDB_HAL_GetCounterValue(uint32_t baseAddr) { return BR_PDB_CNT_CNT(baseAddr); } /*! * @brief Sets the interrupt delay milestone of the PDB counter. * * This function sets the interrupt delay milestone of the PDB counter. * If enabled, a PDB interrupt is generated when the counter is equal to the * setting value. * * @param baseAddr Register base address for the module. * @param value The setting value for interrupt delay milestone of PDB counter. */ static inline void PDB_HAL_SetIntDelayValue(uint32_t baseAddr, uint32_t value) { BW_PDB_IDLY_IDLY(baseAddr, value); } /*! * @brief Gets the current interrupt delay milestone of the PDB counter. * * This function gets the current interrupt delay milestone of the PDB counter. * * @param baseAddr Register base address for the module. * @return The current setting value for interrupt delay milestone of PDB counter. */ static inline uint32_t PDB_HAL_GetIntDelayValue(uint32_t baseAddr) { return BR_PDB_IDLY_IDLY(baseAddr); } /*! * @brief Switches to enable the pre-trigger back-to-back mode. * * This function switches to enable the pre-trigger back-to-back mode. * * @param baseAddr Register base address for the module. * @param chn ADC instance index for trigger. * @param preChn ADC channel group index for trigger. * @param enable Switcher to assert the feature. */ void PDB_HAL_SetPreTriggerBackToBackCmd(uint32_t baseAddr, uint32_t chn, uint32_t preChn, bool enable); /*! * @brief Switches to enable the pre-trigger output. * * This function switches to enable pre-trigger output. * * @param baseAddr Register base address for the module. * @param chn ADC instance index for trigger. * @param preChn ADC channel group index for trigger. * @param enable Switcher to assert the feature. */ void PDB_HAL_SetPreTriggerOutputCmd(uint32_t baseAddr, uint32_t chn, uint32_t preChn, bool enable); /*! * @brief Switches to enable the pre-trigger. * * This function switches to enable the pre-trigger. * * @param baseAddr Register base address for the module. * @param chn ADC instance index for trigger. * @param preChn ADC channel group index for trigger. * @param enable Switcher to assert the feature. */ void PDB_HAL_SetPreTriggerCmd(uint32_t baseAddr, uint32_t chn, uint32_t preChn, bool enable); /*! * @brief Gets the flag which indicates whether the PDB counter has reached the pre-trigger delay value. * * This function gets the flag which indicates the PDB counter has reached the * pre-trigger delay value. * * @param baseAddr Register base address for the module. * @param chn ADC instance index for trigger. * @param preChn ADC channel group index for trigger. * @return Flag status. True if the event is asserted. */ static inline bool PDB_HAL_GetPreTriggerFlag(uint32_t baseAddr, uint32_t chn, uint32_t preChn) { assert(chn < HW_PDB_CHnC1_COUNT); assert(preChn < FSL_FEATURE_PDB_ADC_PRE_CHANNEL_COUNT); return ( ((1U<< preChn) & BR_PDB_CHnS_CF(baseAddr, chn))? true: false); } /*! * @brief Clears the flag which indicates that the PDB counter has reached the pre-trigger delay value. * * This function clears the flag which indicates that the PDB counter has reached the * pre-trigger delay value. * * @param baseAddr Register base address for the module. * @param chn ADC instance index for trigger. * @param preChn ADC channel group index for trigger. */ void PDB_HAL_ClearPreTriggerFlag(uint32_t baseAddr, uint32_t chn, uint32_t preChn); /*! * @brief Gets the flag which indicates whether a sequence error is detected. * * This function gets the flag which indicates whether a sequence error is detected. * * @param baseAddr Register base address for the module. * @param chn ADC instance index for trigger. * @param preChn ADC channel group index for trigger. * @return Flag status. True if the event is asserted. */ static inline bool PDB_HAL_GetPreTriggerSeqErrFlag(uint32_t baseAddr, uint32_t chn, uint32_t preChn) { assert(chn < HW_PDB_CHnC1_COUNT); assert(preChn < FSL_FEATURE_PDB_ADC_PRE_CHANNEL_COUNT); return ( ((1U<< preChn) & BR_PDB_CHnS_ERR(baseAddr, chn))? true: false); } /*! * @brief Clears the flag which indicates that a sequence error has been detected. * * This function clears the flag which indicates that the sequence error has been detected. * * @param baseAddr Register base address for the module. * @param chn ADC instance index for trigger. * @param preChn ADC channel group index for trigger. */ void PDB_HAL_ClearPreTriggerSeqErrFlag(uint32_t baseAddr, uint32_t chn, uint32_t preChn); /*! * @brief Sets the pre-trigger delay value. * * This function sets the pre-trigger delay value. * * @param baseAddr Register base address for the module. * @param chn ADC instance index for trigger. * @param preChn ADC channel group index for trigger. * @param value Setting value for pre-trigger's delay value. */ void PDB_HAL_SetPreTriggerDelayCount(uint32_t baseAddr, uint32_t chn, uint32_t preChn, uint32_t value); /*! * @brief Switches to enable the DAC external trigger input. * * This function switches to enable the DAC external trigger input. * * @param baseAddr Register base address for the module. * @param dacChn DAC instance index for trigger. * @param value Setting value for pre-trigger's delay value. */ static inline void PDB_HAL_SetDacExtTriggerInputCmd(uint32_t baseAddr, uint32_t dacChn, bool enable) { assert(dacChn < HW_PDB_DACINTCn_COUNT); BW_PDB_DACINTCn_EXT(baseAddr, dacChn, (enable ? 1U: 0U) ); } /*! * @brief Switches to enable the DAC external trigger input. * * This function switches to enable the DAC external trigger input. * * @param baseAddr Register base address for the module. * @param dacChn DAC instance index for trigger. * @param enable Switcher to assert the feature. */ static inline void PDB_HAL_SetDacIntervalTriggerCmd(uint32_t baseAddr, uint32_t dacChn, bool enable) { assert(dacChn < HW_PDB_DACINTCn_COUNT); BW_PDB_DACINTCn_TOE(baseAddr, dacChn, (enable ? 1U: 0U) ); } /*! * @brief Sets the interval value for the DAC trigger. * * This function sets the interval value for the DAC trigger. * * @param baseAddr Register base address for the module. * @param dacChn DAC instance index for trigger. * @param value Setting value for DAC trigger interval. */ static inline void PDB_HAL_SetDacIntervalValue(uint32_t baseAddr, uint32_t dacChn, uint32_t value) { assert(dacChn < HW_PDB_DACINTn_COUNT); BW_PDB_DACINTn_INT(baseAddr, dacChn, value); } /*! * @brief Gets the interval value for the DAC trigger. * * This function gets the interval value for the DAC trigger. * * @param baseAddr Register base address for the module. * @param dacChn DAC instance index for trigger. * @return The current setting value for DAC trigger interval. */ static inline uint32_t PDB_HAL_GetDacIntervalValue(uint32_t baseAddr, uint32_t dacChn) { assert(dacChn < HW_PDB_DACINTn_COUNT); return BR_PDB_DACINTn_INT(baseAddr, dacChn); } /*! * @brief Switches to enable the pulse-out trigger. * * This function switches to enable the pulse-out trigger. * * @param baseAddr Register base address for the module. * @param pulseChn Pulse-out channle index for trigger. * @param enable Switcher to assert the feature. */ void PDB_HAL_SetPulseOutCmd(uint32_t baseAddr, uint32_t pulseChn, bool enable); /*! * @brief Sets the counter delay value for the pulse-out goes high. * * This function sets the counter delay value for the pulse-out goes high. * * @param baseAddr Register base address for the module. * @param pulseChn Pulse-out channel index for trigger. * @param value Setting value for PDB delay . */ static inline void PDB_HAL_SetPulseOutDelayForHigh(uint32_t baseAddr, uint32_t pulseChn, uint32_t value) { assert(pulseChn < HW_PDB_POnDLY_COUNT); BW_PDB_POnDLY_DLY1(baseAddr, pulseChn, value); } /*! * @brief Sets the counter delay value for the pulse-out goes low. * * This function sets the counter delay value for the pulse-out goes low. * * @param baseAddr Register base address for the module. * @param pulseChn Pulse-out channel index for trigger. * @param value Setting value for PDB delay . */ static inline void PDB_HAL_SetPulseOutDelayForLow(uint32_t baseAddr, uint32_t pulseChn, uint32_t value) { assert(pulseChn < HW_PDB_POnDLY_COUNT); BW_PDB_POnDLY_DLY2(baseAddr, pulseChn, value); } #if defined(__cplusplus) } #endif /*! * @} */ #endif /* __FSL_PDB_HAL_H__ */ /****************************************************************************** * EOF *****************************************************************************/ ================================================ FILE: Zelig/mbed/TARGET_K64F/TARGET_Freescale/TARGET_KPSDK_MCUS/TARGET_KPSDK_CODE/hal/pit/fsl_pit_features.h ================================================ /* ** ################################################################### ** Version: rev. 1.0, 2014-05-14 ** Build: b140515 ** ** Abstract: ** Chip specific module features. ** ** Copyright: 2014 Freescale Semiconductor, Inc. ** All rights reserved. ** ** Redistribution and use in source and binary forms, with or without modification, ** are permitted provided that the following conditions are met: ** ** o Redistributions of source code must retain the above copyright notice, this list ** of conditions and the following disclaimer. ** ** o Redistributions in binary form must reproduce the above copyright notice, this ** list of conditions and the following disclaimer in the documentation and/or ** other materials provided with the distribution. ** ** o Neither the name of Freescale Semiconductor, Inc. nor the names of its ** contributors may be used to endorse or promote products derived from this ** software without specific prior written permission. ** ** THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ** ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED ** WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE ** DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT 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. ** ** http: www.freescale.com ** mail: support@freescale.com ** ** Revisions: ** - rev. 1.0 (2014-05-14) ** Customer release. ** ** ################################################################### */ #if !defined(__FSL_PIT_FEATURES_H__) #define __FSL_PIT_FEATURES_H__ #if defined(CPU_MK02FN128VFM10) || defined(CPU_MK02FN64VFM10) || defined(CPU_MK02FN128VLF10) || defined(CPU_MK02FN64VLF10) || \ defined(CPU_MK02FN128VLH10) || defined(CPU_MK02FN64VLH10) || defined(CPU_MK22FN128VDC10) || defined(CPU_MK22FN128VLH10) || \ defined(CPU_MK22FN128VLL10) || defined(CPU_MK22FN128VMP10) || defined(CPU_MK22FN256VDC12) || defined(CPU_MK22FN256VLH12) || \ defined(CPU_MK22FN256VLL12) || defined(CPU_MK22FN256VMP12) || defined(CPU_MK22FN512VDC12) || defined(CPU_MK22FN512VLH12) || \ defined(CPU_MK22FN512VLL12) || defined(CPU_MK24FN1M0VDC12) || defined(CPU_MK24FN1M0VLL12) || defined(CPU_MK24FN1M0VLQ12) || \ defined(CPU_MK24FN256VDC12) || defined(CPU_MK63FN1M0VLQ12) || defined(CPU_MK63FN1M0VMD12) || defined(CPU_MK64FX512VDC12) || \ defined(CPU_MK64FN1M0VDC12) || defined(CPU_MK64FX512VLL12) || defined(CPU_MK64FN1M0VLL12) || defined(CPU_MK64FX512VLQ12) || \ defined(CPU_MK64FN1M0VLQ12) || defined(CPU_MK64FX512VMD12) || defined(CPU_MK64FN1M0VMD12) || defined(CPU_MKV30F128VFM10) || \ defined(CPU_MKV30F64VFM10) || defined(CPU_MKV30F128VLF10) || defined(CPU_MKV30F64VLF10) || defined(CPU_MKV30F128VLH10) || \ defined(CPU_MKV30F64VLH10) || defined(CPU_MKV31F128VLH10) || defined(CPU_MKV31F128VLL10) || defined(CPU_MKV31F256VLH12) || \ defined(CPU_MKV31F256VLL12) || defined(CPU_MKV31F512VLH12) || defined(CPU_MKV31F512VLL12) || defined(CPU_MKV40F128VLH15) || \ defined(CPU_MKV40F128VLL15) || defined(CPU_MKV40F256VLH15) || defined(CPU_MKV40F256VLL15) || defined(CPU_MKV40F64VLH15) || \ defined(CPU_MKV43F128VLH15) || defined(CPU_MKV43F128VLL15) || defined(CPU_MKV43F64VLH15) || defined(CPU_MKV44F128VLH15) || \ defined(CPU_MKV44F128VLL15) || defined(CPU_MKV44F64VLH15) || defined(CPU_MKV45F128VLH15) || defined(CPU_MKV45F128VLL15) || \ defined(CPU_MKV45F256VLH15) || defined(CPU_MKV45F256VLL15) || defined(CPU_MKV46F128VLH15) || defined(CPU_MKV46F128VLL15) || \ defined(CPU_MKV46F256VLH15) || defined(CPU_MKV46F256VLL15) /* @brief Number of channels (related to number of registers LDVALn, CVALn, TCTRLn, TFLGn). */ #define FSL_FEATURE_PIT_TIMER_COUNT (4) /* @brief Has lifetime timer (related to existence of registers LTMR64L and LTMR64H). */ #define FSL_FEATURE_PIT_HAS_LIFETIME_TIMER (0) /* @brief Has chain mode (related to existence of register bit field TCTRLn[CHN]). */ #define FSL_FEATURE_PIT_HAS_CHAIN_MODE (1) #elif defined(CPU_MK20DX128VMP5) || defined(CPU_MK20DN128VMP5) || defined(CPU_MK20DX64VMP5) || defined(CPU_MK20DN64VMP5) || \ defined(CPU_MK20DX32VMP5) || defined(CPU_MK20DN32VMP5) || defined(CPU_MK20DX128VLH5) || defined(CPU_MK20DN128VLH5) || \ defined(CPU_MK20DX64VLH5) || defined(CPU_MK20DN64VLH5) || defined(CPU_MK20DX32VLH5) || defined(CPU_MK20DN32VLH5) || \ defined(CPU_MK20DX128VFM5) || defined(CPU_MK20DN128VFM5) || defined(CPU_MK20DX64VFM5) || defined(CPU_MK20DN64VFM5) || \ defined(CPU_MK20DX32VFM5) || defined(CPU_MK20DN32VFM5) || defined(CPU_MK20DX128VFT5) || defined(CPU_MK20DN128VFT5) || \ defined(CPU_MK20DX64VFT5) || defined(CPU_MK20DN64VFT5) || defined(CPU_MK20DX32VFT5) || defined(CPU_MK20DN32VFT5) || \ defined(CPU_MK20DX128VLF5) || defined(CPU_MK20DN128VLF5) || defined(CPU_MK20DX64VLF5) || defined(CPU_MK20DN64VLF5) || \ defined(CPU_MK20DX32VLF5) || defined(CPU_MK20DN32VLF5) || defined(CPU_MK70FN1M0VMF12) || defined(CPU_MK70FX512VMF12) || \ defined(CPU_MK70FN1M0VMF15) || defined(CPU_MK70FX512VMF15) || defined(CPU_MK70FN1M0VMJ12) || defined(CPU_MK70FX512VMJ12) || \ defined(CPU_MK70FN1M0VMJ15) || defined(CPU_MK70FX512VMJ15) /* @brief Number of channels (related to number of registers LDVALn, CVALn, TCTRLn, TFLGn). */ #define FSL_FEATURE_PIT_TIMER_COUNT (4) /* @brief Has lifetime timer (related to existence of registers LTMR64L and LTMR64H). */ #define FSL_FEATURE_PIT_HAS_LIFETIME_TIMER (0) /* @brief Has chain mode (related to existence of register bit field TCTRLn[CHN]). */ #define FSL_FEATURE_PIT_HAS_CHAIN_MODE (0) #elif defined(CPU_MK65FN2M0CAC18) || defined(CPU_MK65FX1M0CAC18) || defined(CPU_MK65FN2M0VMI18) || defined(CPU_MK65FX1M0VMI18) || \ defined(CPU_MK66FN2M0VLQ18) || defined(CPU_MK66FX1M0VLQ18) || defined(CPU_MK66FN2M0VMD18) || defined(CPU_MK66FX1M0VMD18) /* @brief Number of channels (related to number of registers LDVALn, CVALn, TCTRLn, TFLGn). */ #define FSL_FEATURE_PIT_TIMER_COUNT (4) /* @brief Has lifetime timer (related to existence of registers LTMR64L and LTMR64H). */ #define FSL_FEATURE_PIT_HAS_LIFETIME_TIMER (1) /* @brief Has chain mode (related to existence of register bit field TCTRLn[CHN]). */ #define FSL_FEATURE_PIT_HAS_CHAIN_MODE (1) #elif defined(CPU_MKL05Z8VFK4) || defined(CPU_MKL05Z16VFK4) || defined(CPU_MKL05Z32VFK4) || defined(CPU_MKL05Z8VLC4) || \ defined(CPU_MKL05Z16VLC4) || defined(CPU_MKL05Z32VLC4) || defined(CPU_MKL05Z8VFM4) || defined(CPU_MKL05Z16VFM4) || \ defined(CPU_MKL05Z32VFM4) || defined(CPU_MKL05Z16VLF4) || defined(CPU_MKL05Z32VLF4) || defined(CPU_MKL13Z64VFM4) || \ defined(CPU_MKL13Z128VFM4) || defined(CPU_MKL13Z256VFM4) || defined(CPU_MKL13Z64VFT4) || defined(CPU_MKL13Z128VFT4) || \ defined(CPU_MKL13Z256VFT4) || defined(CPU_MKL13Z64VLH4) || defined(CPU_MKL13Z128VLH4) || defined(CPU_MKL13Z256VLH4) || \ defined(CPU_MKL13Z64VMP4) || defined(CPU_MKL13Z128VMP4) || defined(CPU_MKL13Z256VMP4) || defined(CPU_MKL23Z64VFM4) || \ defined(CPU_MKL23Z128VFM4) || defined(CPU_MKL23Z256VFM4) || defined(CPU_MKL23Z64VFT4) || defined(CPU_MKL23Z128VFT4) || \ defined(CPU_MKL23Z256VFT4) || defined(CPU_MKL23Z64VLH4) || defined(CPU_MKL23Z128VLH4) || defined(CPU_MKL23Z256VLH4) || \ defined(CPU_MKL23Z64VMP4) || defined(CPU_MKL23Z128VMP4) || defined(CPU_MKL23Z256VMP4) || defined(CPU_MKL25Z32VFM4) || \ defined(CPU_MKL25Z64VFM4) || defined(CPU_MKL25Z128VFM4) || defined(CPU_MKL25Z32VFT4) || defined(CPU_MKL25Z64VFT4) || \ defined(CPU_MKL25Z128VFT4) || defined(CPU_MKL25Z32VLH4) || defined(CPU_MKL25Z64VLH4) || defined(CPU_MKL25Z128VLH4) || \ defined(CPU_MKL25Z32VLK4) || defined(CPU_MKL25Z64VLK4) || defined(CPU_MKL25Z128VLK4) || defined(CPU_MKL26Z256VLK4) || \ defined(CPU_MKL26Z128VLL4) || defined(CPU_MKL26Z256VLL4) || defined(CPU_MKL26Z128VMC4) || defined(CPU_MKL26Z256VMC4) || \ defined(CPU_MKL33Z128VLH4) || defined(CPU_MKL33Z256VLH4) || defined(CPU_MKL33Z128VMP4) || defined(CPU_MKL33Z256VMP4) || \ defined(CPU_MKL43Z64VLH4) || defined(CPU_MKL43Z128VLH4) || defined(CPU_MKL43Z256VLH4) || defined(CPU_MKL43Z64VMP4) || \ defined(CPU_MKL43Z128VMP4) || defined(CPU_MKL43Z256VMP4) || defined(CPU_MKL46Z128VLH4) || defined(CPU_MKL46Z256VLH4) || \ defined(CPU_MKL46Z128VLL4) || defined(CPU_MKL46Z256VLL4) || defined(CPU_MKL46Z128VMC4) || defined(CPU_MKL46Z256VMC4) /* @brief Number of channels (related to number of registers LDVALn, CVALn, TCTRLn, TFLGn). */ #define FSL_FEATURE_PIT_TIMER_COUNT (2) /* @brief Has lifetime timer (related to existence of registers LTMR64L and LTMR64H). */ #define FSL_FEATURE_PIT_HAS_LIFETIME_TIMER (1) /* @brief Has chain mode (related to existence of register bit field TCTRLn[CHN]). */ #define FSL_FEATURE_PIT_HAS_CHAIN_MODE (1) #else #error "No valid CPU defined!" #endif #endif /* __FSL_PIT_FEATURES_H__ */ /******************************************************************************* * EOF ******************************************************************************/ ================================================ FILE: Zelig/mbed/TARGET_K64F/TARGET_Freescale/TARGET_KPSDK_MCUS/TARGET_KPSDK_CODE/hal/pit/fsl_pit_hal.h ================================================ /* * Copyright (c) 2013 - 2014, Freescale Semiconductor, Inc. * All rights reserved. * * Redistribution and use in source and binary forms, with or without modification, * are permitted provided that the following conditions are met: * * o Redistributions of source code must retain the above copyright notice, this list * of conditions and the following disclaimer. * * o Redistributions in binary form must reproduce the above copyright notice, this * list of conditions and the following disclaimer in the documentation and/or * other materials provided with the distribution. * * o Neither the name of Freescale Semiconductor, Inc. nor the names of its * contributors may be used to endorse or promote products derived from this * software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT 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. */ #ifndef __FSL_PIT_HAL_H__ #define __FSL_PIT_HAL_H__ #include #include #include #include "fsl_pit_features.h" #include "fsl_device_registers.h" /*! * @addtogroup pit_hal * @{ */ /******************************************************************************* * API ******************************************************************************/ #if defined(__cplusplus) extern "C" { #endif /*! * @name Initialization * @{ */ /*! * @brief Enables the PIT module. * * This function enables the PIT timer clock (Note: this function does not un-gate * the system clock gating control). It should be called before any other timer * related setup. * * @param baseAddr Base address for current PIT instance. */ static inline void PIT_HAL_Enable(uint32_t baseAddr) { BW_PIT_MCR_MDIS(baseAddr, 0U); } /*! * @brief Disables the PIT module. * * This function disables all PIT timer clocks(Note: it does not affect the * SIM clock gating control). * * @param baseAddr Base address for current PIT instance. */ static inline void PIT_HAL_Disable(uint32_t baseAddr) { BW_PIT_MCR_MDIS(baseAddr, 1U); } /*! * @brief Configures the timers to continue running or to stop in debug mode. * * In debug mode, the timers may or may not be frozen, based on the configuration of * this function. This is intended to aid software development, allowing the developer * to halt the processor, investigate the current state of the system (for example, * the timer values), and continue the operation. * * @param baseAddr Base address for current PIT instance. * @param timerRun Timers run or stop in debug mode. * - true: Timers continue to run in debug mode. * - false: Timers stop in debug mode. */ static inline void PIT_HAL_SetTimerRunInDebugCmd(uint32_t baseAddr, bool timerRun) { BW_PIT_MCR_FRZ(baseAddr, !timerRun); } #if FSL_FEATURE_PIT_HAS_CHAIN_MODE /*! * @brief Enables or disables the timer chain with the previous timer. * * When a timer has a chain mode enabled, it only counts after the previous * timer has expired. If the timer n-1 has counted down to 0, counter n * decrements the value by one. This allows the developers to chain timers together * and form a longer timer. The first timer (timer 0) cannot be chained to any * other timer. * * @param baseAddr Base address for current PIT instance. * @param channel Timer channel number which is chained with the previous timer. * @param enable Enable or disable chain. * - true: Current timer is chained with the previous timer. * - false: Timer doesn't chain with other timers. */ static inline void PIT_HAL_SetTimerChainCmd(uint32_t baseAddr, uint32_t channel, bool enable) { assert(channel < FSL_FEATURE_PIT_TIMER_COUNT); BW_PIT_TCTRLn_CHN(baseAddr, channel, enable); } #endif /* FSL_FEATURE_PIT_HAS_CHAIN_MODE*/ /* @} */ /*! * @name Timer Start and Stop * @{ */ /*! * @brief Starts the timer counting. * * After calling this function, timers load the start value as specified by the function * PIT_HAL_SetTimerPeriodByCount(uint32_t baseAddr, uint32_t channel, uint32_t count), count down to * 0, and load the respective start value again. Each time a timer reaches 0, * it generates a trigger pulse and sets the time-out interrupt flag. * * @param baseAddr Base address for current PIT instance. * @param channel Timer channel number */ static inline void PIT_HAL_StartTimer(uint32_t baseAddr, uint32_t channel) { assert(channel < FSL_FEATURE_PIT_TIMER_COUNT); BW_PIT_TCTRLn_TEN(baseAddr, channel, 1U); } /*! * @brief Stops the timer from counting. * * This function stops every timer from counting. Timers reload their periods * respectively after they call the PIT_HAL_StartTimer the next time. * * @param baseAddr Base address for current PIT instance. * @param channel Timer channel number */ static inline void PIT_HAL_StopTimer(uint32_t baseAddr, uint32_t channel) { assert(channel < FSL_FEATURE_PIT_TIMER_COUNT); BW_PIT_TCTRLn_TEN(baseAddr, channel, 0U); } /*! * @brief Checks to see whether the current timer is started or not. * * @param baseAddr Base address for current PIT instance. * @param channel Timer channel number * @return Current timer running status * -true: Current timer is running. * -false: Current timer has stopped. */ static inline bool PIT_HAL_IsTimerRunning(uint32_t baseAddr, uint32_t channel) { assert(channel < FSL_FEATURE_PIT_TIMER_COUNT); return BR_PIT_TCTRLn_TEN(baseAddr, channel); } /* @} */ /*! * @name Timer Period * @{ */ /*! * @brief Sets the timer period in units of count. * * Timers begin counting from the value set by this function. * The counter period of a running timer can be modified by first stopping * the timer, setting a new load value, and starting the timer again. If * timers are not restarted, the new value is loaded after the next trigger * event. * * @param baseAddr Base address for current PIT instance. * @param channel Timer channel number * @param count Timer period in units of count */ static inline void PIT_HAL_SetTimerPeriodByCount(uint32_t baseAddr, uint32_t channel, uint32_t count) { assert(channel < FSL_FEATURE_PIT_TIMER_COUNT); HW_PIT_LDVALn_WR(baseAddr, channel, count); } /*! * @brief Returns the current timer period in units of count. * * @param baseAddr Base address for current PIT instance. * @param channel Timer channel number * @return Timer period in units of count */ static inline uint32_t PIT_HAL_GetTimerPeriodByCount(uint32_t baseAddr, uint32_t channel) { assert(channel < FSL_FEATURE_PIT_TIMER_COUNT); return HW_PIT_LDVALn_RD(baseAddr, channel); } /*! * @brief Reads the current timer counting value. * * This function returns the real-time timer counting value, in a range from 0 to a * timer period. * * @param baseAddr Base address for current PIT instance. * @param channel Timer channel number * @return Current timer counting value */ static inline uint32_t PIT_HAL_ReadTimerCount(uint32_t baseAddr, uint32_t channel) { assert(channel < FSL_FEATURE_PIT_TIMER_COUNT); return HW_PIT_CVALn_RD(baseAddr, channel); } #if FSL_FEATURE_PIT_HAS_LIFETIME_TIMER /*! * @brief Reads the current lifetime counter value. * * The lifetime timer is a 64-bit timer which chains timer 0 and timer 1 together. * Timer 0 and 1 are chained by calling the PIT_HAL_SetTimerChainCmd * before using this timer. The period of lifetime timer is equal to the "period of * timer 0 * period of timer 1". For the 64-bit value, the higher 32-bit has * the value of timer 1, and the lower 32-bit has the value of timer 0. * * @param baseAddr Base address for current PIT instance. * @return Current lifetime timer value */ uint64_t PIT_HAL_ReadLifetimeTimerCount(uint32_t baseAddr); #endif /*FSL_FEATURE_PIT_HAS_LIFETIME_TIMER*/ /* @} */ /*! * @name Interrupt * @{ */ /*! * @brief Enables or disables the timer interrupt. * * If enabled, an interrupt happens when a timeout event occurs * (Note: NVIC should be called to enable pit interrupt in system level). * * @param baseAddr Base address for current PIT instance. * @param channel Timer channel number * @param enable Enable or disable interrupt. * - true: Generate interrupt when timer counts to 0. * - false: No interrupt is generated. */ static inline void PIT_HAL_SetIntCmd(uint32_t baseAddr, uint32_t channel, bool enable) { assert(channel < FSL_FEATURE_PIT_TIMER_COUNT); BW_PIT_TCTRLn_TIE(baseAddr, channel, enable); } /*! * @brief Checks whether the timer interrupt is enabled or not. * * @param baseAddr Base address for current PIT instance. * @param channel Timer channel number * @return Status of enabled or disabled interrupt * - true: Interrupt is enabled. * - false: Interrupt is disabled. */ static inline bool PIT_HAL_GetIntCmd(uint32_t baseAddr, uint32_t channel) { assert(channel < FSL_FEATURE_PIT_TIMER_COUNT); return BR_PIT_TCTRLn_TIE(baseAddr, channel); } /*! * @brief Clears the timer interrupt flag. * * This function clears the timer interrupt flag after a timeout event * occurs. * * @param baseAddr Base address for current PIT instance. * @param channel Timer channel number */ static inline void PIT_HAL_ClearIntFlag(uint32_t baseAddr, uint32_t channel) { assert(channel < FSL_FEATURE_PIT_TIMER_COUNT); /* Write 1 will clear the flag. */ HW_PIT_TFLGn_WR(baseAddr, channel, 1U); } /*! * @brief Reads the current timer timeout flag. * * Every time the timer counts to 0, this flag is set. * * @param baseAddr Base address for current PIT instance. * @param channel Timer channel number * @return Current status of the timeout flag * - true: Timeout has occurred. * - false: Timeout has not yet occurred. */ static inline bool PIT_HAL_IsIntPending(uint32_t baseAddr, uint32_t channel) { assert(channel < FSL_FEATURE_PIT_TIMER_COUNT); return HW_PIT_TFLGn_RD(baseAddr, channel); } /* @} */ #if defined(__cplusplus) } #endif /*! @}*/ #endif /* __FSL_PIT_HAL_H__*/ /******************************************************************************* * EOF *******************************************************************************/ ================================================ FILE: Zelig/mbed/TARGET_K64F/TARGET_Freescale/TARGET_KPSDK_MCUS/TARGET_KPSDK_CODE/hal/pmc/fsl_pmc_features.h ================================================ /* ** ################################################################### ** Version: rev. 1.0, 2014-05-14 ** Build: b140515 ** ** Abstract: ** Chip specific module features. ** ** Copyright: 2014 Freescale Semiconductor, Inc. ** All rights reserved. ** ** Redistribution and use in source and binary forms, with or without modification, ** are permitted provided that the following conditions are met: ** ** o Redistributions of source code must retain the above copyright notice, this list ** of conditions and the following disclaimer. ** ** o Redistributions in binary form must reproduce the above copyright notice, this ** list of conditions and the following disclaimer in the documentation and/or ** other materials provided with the distribution. ** ** o Neither the name of Freescale Semiconductor, Inc. nor the names of its ** contributors may be used to endorse or promote products derived from this ** software without specific prior written permission. ** ** THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ** ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED ** WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE ** DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT 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. ** ** http: www.freescale.com ** mail: support@freescale.com ** ** Revisions: ** - rev. 1.0 (2014-05-14) ** Customer release. ** ** ################################################################### */ #if !defined(__FSL_PMC_FEATURES_H__) #define __FSL_PMC_FEATURES_H__ #if defined(CPU_MK02FN128VFM10) || defined(CPU_MK02FN64VFM10) || defined(CPU_MK02FN128VLF10) || defined(CPU_MK02FN64VLF10) || \ defined(CPU_MK02FN128VLH10) || defined(CPU_MK02FN64VLH10) || defined(CPU_MK22FN128VDC10) || defined(CPU_MK22FN128VLH10) || \ defined(CPU_MK22FN128VLL10) || defined(CPU_MK22FN128VMP10) || defined(CPU_MK22FN256VDC12) || defined(CPU_MK22FN256VLH12) || \ defined(CPU_MK22FN256VLL12) || defined(CPU_MK22FN256VMP12) || defined(CPU_MK22FN512VDC12) || defined(CPU_MK22FN512VLH12) || \ defined(CPU_MK22FN512VLL12) || defined(CPU_MK24FN1M0VDC12) || defined(CPU_MK24FN1M0VLL12) || defined(CPU_MK24FN1M0VLQ12) || \ defined(CPU_MK24FN256VDC12) || defined(CPU_MK63FN1M0VLQ12) || defined(CPU_MK63FN1M0VMD12) || defined(CPU_MK64FX512VDC12) || \ defined(CPU_MK64FN1M0VDC12) || defined(CPU_MK64FX512VLL12) || defined(CPU_MK64FN1M0VLL12) || defined(CPU_MK64FX512VLQ12) || \ defined(CPU_MK64FN1M0VLQ12) || defined(CPU_MK64FX512VMD12) || defined(CPU_MK64FN1M0VMD12) || defined(CPU_MK65FN2M0CAC18) || \ defined(CPU_MK65FX1M0CAC18) || defined(CPU_MK65FN2M0VMI18) || defined(CPU_MK65FX1M0VMI18) || defined(CPU_MK66FN2M0VLQ18) || \ defined(CPU_MK66FX1M0VLQ18) || defined(CPU_MK66FN2M0VMD18) || defined(CPU_MK66FX1M0VMD18) || defined(CPU_MKL03Z32CAF4) || \ defined(CPU_MKL03Z8VFG4) || defined(CPU_MKL03Z16VFG4) || defined(CPU_MKL03Z32VFG4) || defined(CPU_MKL03Z8VFK4) || \ defined(CPU_MKL03Z16VFK4) || defined(CPU_MKL03Z32VFK4) || defined(CPU_MKL05Z8VFK4) || defined(CPU_MKL05Z16VFK4) || \ defined(CPU_MKL05Z32VFK4) || defined(CPU_MKL05Z8VLC4) || defined(CPU_MKL05Z16VLC4) || defined(CPU_MKL05Z32VLC4) || \ defined(CPU_MKL05Z8VFM4) || defined(CPU_MKL05Z16VFM4) || defined(CPU_MKL05Z32VFM4) || defined(CPU_MKL05Z16VLF4) || \ defined(CPU_MKL05Z32VLF4) || defined(CPU_MKL13Z64VFM4) || defined(CPU_MKL13Z128VFM4) || defined(CPU_MKL13Z256VFM4) || \ defined(CPU_MKL13Z64VFT4) || defined(CPU_MKL13Z128VFT4) || defined(CPU_MKL13Z256VFT4) || defined(CPU_MKL13Z64VLH4) || \ defined(CPU_MKL13Z128VLH4) || defined(CPU_MKL13Z256VLH4) || defined(CPU_MKL13Z64VMP4) || defined(CPU_MKL13Z128VMP4) || \ defined(CPU_MKL13Z256VMP4) || defined(CPU_MKL23Z64VFM4) || defined(CPU_MKL23Z128VFM4) || defined(CPU_MKL23Z256VFM4) || \ defined(CPU_MKL23Z64VFT4) || defined(CPU_MKL23Z128VFT4) || defined(CPU_MKL23Z256VFT4) || defined(CPU_MKL23Z64VLH4) || \ defined(CPU_MKL23Z128VLH4) || defined(CPU_MKL23Z256VLH4) || defined(CPU_MKL23Z64VMP4) || defined(CPU_MKL23Z128VMP4) || \ defined(CPU_MKL23Z256VMP4) || defined(CPU_MKL25Z32VFM4) || defined(CPU_MKL25Z64VFM4) || defined(CPU_MKL25Z128VFM4) || \ defined(CPU_MKL25Z32VFT4) || defined(CPU_MKL25Z64VFT4) || defined(CPU_MKL25Z128VFT4) || defined(CPU_MKL25Z32VLH4) || \ defined(CPU_MKL25Z64VLH4) || defined(CPU_MKL25Z128VLH4) || defined(CPU_MKL25Z32VLK4) || defined(CPU_MKL25Z64VLK4) || \ defined(CPU_MKL25Z128VLK4) || defined(CPU_MKL26Z256VLK4) || defined(CPU_MKL26Z128VLL4) || defined(CPU_MKL26Z256VLL4) || \ defined(CPU_MKL26Z128VMC4) || defined(CPU_MKL26Z256VMC4) || defined(CPU_MKL33Z128VLH4) || defined(CPU_MKL33Z256VLH4) || \ defined(CPU_MKL33Z128VMP4) || defined(CPU_MKL33Z256VMP4) || defined(CPU_MKL43Z64VLH4) || defined(CPU_MKL43Z128VLH4) || \ defined(CPU_MKL43Z256VLH4) || defined(CPU_MKL43Z64VMP4) || defined(CPU_MKL43Z128VMP4) || defined(CPU_MKL43Z256VMP4) || \ defined(CPU_MKL46Z128VLH4) || defined(CPU_MKL46Z256VLH4) || defined(CPU_MKL46Z128VLL4) || defined(CPU_MKL46Z256VLL4) || \ defined(CPU_MKL46Z128VMC4) || defined(CPU_MKL46Z256VMC4) || defined(CPU_MKV30F128VFM10) || defined(CPU_MKV30F64VFM10) || \ defined(CPU_MKV30F128VLF10) || defined(CPU_MKV30F64VLF10) || defined(CPU_MKV30F128VLH10) || defined(CPU_MKV30F64VLH10) || \ defined(CPU_MKV31F128VLH10) || defined(CPU_MKV31F128VLL10) || defined(CPU_MKV31F256VLH12) || defined(CPU_MKV31F256VLL12) || \ defined(CPU_MKV31F512VLH12) || defined(CPU_MKV31F512VLL12) || defined(CPU_MKV40F128VLH15) || defined(CPU_MKV40F128VLL15) || \ defined(CPU_MKV40F256VLH15) || defined(CPU_MKV40F256VLL15) || defined(CPU_MKV40F64VLH15) || defined(CPU_MKV43F128VLH15) || \ defined(CPU_MKV43F128VLL15) || defined(CPU_MKV43F64VLH15) || defined(CPU_MKV44F128VLH15) || defined(CPU_MKV44F128VLL15) || \ defined(CPU_MKV44F64VLH15) || defined(CPU_MKV45F128VLH15) || defined(CPU_MKV45F128VLL15) || defined(CPU_MKV45F256VLH15) || \ defined(CPU_MKV45F256VLL15) || defined(CPU_MKV46F128VLH15) || defined(CPU_MKV46F128VLL15) || defined(CPU_MKV46F256VLH15) || \ defined(CPU_MKV46F256VLL15) /* @brief Has Bandgap Enable In VLPx Operation support. */ #define FSL_FEATURE_PMC_HAS_BGEN (1) #elif defined(CPU_MK20DX128VMP5) || defined(CPU_MK20DN128VMP5) || defined(CPU_MK20DX64VMP5) || defined(CPU_MK20DN64VMP5) || \ defined(CPU_MK20DX32VMP5) || defined(CPU_MK20DN32VMP5) || defined(CPU_MK20DX128VLH5) || defined(CPU_MK20DN128VLH5) || \ defined(CPU_MK20DX64VLH5) || defined(CPU_MK20DN64VLH5) || defined(CPU_MK20DX32VLH5) || defined(CPU_MK20DN32VLH5) || \ defined(CPU_MK20DX128VFM5) || defined(CPU_MK20DN128VFM5) || defined(CPU_MK20DX64VFM5) || defined(CPU_MK20DN64VFM5) || \ defined(CPU_MK20DX32VFM5) || defined(CPU_MK20DN32VFM5) || defined(CPU_MK20DX128VFT5) || defined(CPU_MK20DN128VFT5) || \ defined(CPU_MK20DX64VFT5) || defined(CPU_MK20DN64VFT5) || defined(CPU_MK20DX32VFT5) || defined(CPU_MK20DN32VFT5) || \ defined(CPU_MK20DX128VLF5) || defined(CPU_MK20DN128VLF5) || defined(CPU_MK20DX64VLF5) || defined(CPU_MK20DN64VLF5) || \ defined(CPU_MK20DX32VLF5) || defined(CPU_MK20DN32VLF5) || defined(CPU_MK70FN1M0VMF12) || defined(CPU_MK70FX512VMF12) || \ defined(CPU_MK70FN1M0VMF15) || defined(CPU_MK70FX512VMF15) || defined(CPU_MK70FN1M0VMJ12) || defined(CPU_MK70FX512VMJ12) || \ defined(CPU_MK70FN1M0VMJ15) || defined(CPU_MK70FX512VMJ15) /* @brief Has Bandgap Enable In VLPx Operation support. */ #define FSL_FEATURE_PMC_HAS_BGEN (0) #else #error "No valid CPU defined!" #endif #endif /* __FSL_PMC_FEATURES_H__ */ /******************************************************************************* * EOF ******************************************************************************/ ================================================ FILE: Zelig/mbed/TARGET_K64F/TARGET_Freescale/TARGET_KPSDK_MCUS/TARGET_KPSDK_CODE/hal/pmc/fsl_pmc_hal.h ================================================ /* * Copyright (c) 2013 - 2014, Freescale Semiconductor, Inc. * All rights reserved. * * Redistribution and use in source and binary forms, with or without modification, * are permitted provided that the following conditions are met: * * o Redistributions of source code must retain the above copyright notice, this list * of conditions and the following disclaimer. * * o Redistributions in binary form must reproduce the above copyright notice, this * list of conditions and the following disclaimer in the documentation and/or * other materials provided with the distribution. * * o Neither the name of Freescale Semiconductor, Inc. nor the names of its * contributors may be used to endorse or promote products derived from this * software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT 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. */ #if !defined(__FSL_PMC_HAL_H__) #define __FSL_PMC_HAL_H__ #include #include #include #include "fsl_device_registers.h" #include "fsl_pmc_features.h" /*! @addtogroup pmc_hal*/ /*! @{*/ /*! @file fsl_pmc_hal.h */ /******************************************************************************* * Definitions ******************************************************************************/ /*! @brief Low-Voltage Warning Voltage Select*/ typedef enum _pmc_low_volt_warn_volt_select { kPmcLowVoltWarnVoltLowTrip, /*!< Low trip point selected (VLVW = VLVW1)*/ kPmcLowVoltWarnVoltMid1Trip, /*!< Mid 1 trip point selected (VLVW = VLVW2)*/ kPmcLowVoltWarnVoltMid2Trip, /*!< Mid 2 trip point selected (VLVW = VLVW3)*/ kPmcLowVoltWarnVoltHighTrip /*!< High trip point selected (VLVW = VLVW4)*/ } pmc_low_volt_warn_volt_select_t; /*! @brief Low-Voltage Detect Voltage Select*/ typedef enum _pmc_low_volt_detect_volt_select { kPmcLowVoltDetectVoltLowTrip, /*!< Low trip point selected (V LVD = V LVDL )*/ kPmcLowVoltDetectVoltHighTrip, /*!< High trip point selected (V LVD = V LVDH )*/ } pmc_low_volt_detect_volt_select_t; /*! @brief interrupt control*/ typedef enum _pmc_int_select { kPmcIntLowVoltDetect, /*!< Low Voltage Detect Interrupt */ kPmcIntLowVoltWarn, /*!< Low Voltage Warning Interrupt */ } pmc_int_select_t; /******************************************************************************* * API ******************************************************************************/ #if defined(__cplusplus) extern "C" { #endif /* __cplusplus*/ /*! @name Power Management Controller Control APIs*/ /*@{*/ /*! * @brief Enables/Disables low voltage-related interrupts. * * This function enables the interrupt for the low voltage detection, warning, * etc. When enabled, if the LVDF (Low Voltage Detect Flag) is set, a hardware * interrupt occurs. * * @param baseAddr Base address for current PMC instance. * @param intSelect interrut select * @param enable enable/disable the interrupt */ void PMC_HAL_SetLowVoltIntCmd(uint32_t baseAddr, pmc_int_select_t intSelect, bool enable); /*! * @brief Low-Voltage Detect Hardware Reset Enable/Disable (write once) * * This function enables/disables the hardware reset for the low voltage * detection. When enabled, if the LVDF (Low Voltage Detect Flag) is set, a * hardware reset occurs. This setting is a write-once-only. Any additional writes * are ignored. * * @param baseAddr Base address for current PMC instance. * @param enable enable/disable the LVD hardware reset */ static inline void PMC_HAL_SetLowVoltDetectResetCmd(uint32_t baseAddr, bool enable) { BW_PMC_LVDSC1_LVDRE(baseAddr, (uint8_t)enable); } /*! * @brief Low-Voltage Detect Acknowledge * * This function acknowledges the low voltage detection errors (write 1 to * clear LVDF). * * @param baseAddr Base address for current PMC instance. */ static inline void PMC_HAL_SetLowVoltDetectAck(uint32_t baseAddr) { BW_PMC_LVDSC1_LVDACK(baseAddr, 1); } /*! * @brief Low-Voltage Detect Flag Read * * This function reads the current LVDF status. If it returns 1, a low * voltage event is detected. * * @param baseAddr Base address for current PMC instance. * @return status Current low voltage detect flag * - true: Low-Voltage detected * - false: Low-Voltage not detected */ static inline bool PMC_HAL_GetLowVoltDetectFlag(uint32_t baseAddr) { return BR_PMC_LVDSC1_LVDF(baseAddr); } /*! * @brief Sets the Low-Voltage Detect Voltage Mode * * This function sets the low voltage detect voltage select. It sets * the low voltage detect trip point voltage (Vlvd). An application can select * either a low-trip or a high-trip point. See a chip reference manual for details. * * @param baseAddr Base address for current PMC instance. * @param select Voltage select setting defined in pmc_lvdv_select_t */ static inline void PMC_HAL_SetLowVoltDetectVoltMode(uint32_t baseAddr, pmc_low_volt_detect_volt_select_t select) { BW_PMC_LVDSC1_LVDV(baseAddr, select); } /*! * @brief Gets the Low-Voltage Detect Voltage Mode * * This function gets the low voltage detect voltage select. It gets * the low voltage detect trip point voltage (Vlvd). An application can select * either a low-trip or a high-trip point. See a chip reference manual for details. * * @param baseAddr Base address for current PMC instance. * @return select Current voltage select setting */ static inline pmc_low_volt_detect_volt_select_t PMC_HAL_GetLowVoltDetectVoltMode(uint32_t baseAddr) { return (pmc_low_volt_detect_volt_select_t)BR_PMC_LVDSC1_LVDV(baseAddr); } /*! * @brief Low-Voltage Warning Acknowledge * * This function acknowledges the low voltage warning errors (write 1 to * clear LVWF). * * @param baseAddr Base address for current PMC instance. */ static inline void PMC_HAL_SetLowVoltWarnAck(uint32_t baseAddr) { BW_PMC_LVDSC2_LVWACK(baseAddr, 1); } /*! * @brief Low-Voltage Warning Flag Read * * This function polls the current LVWF status. When 1 is returned, it * indicates a low-voltage warning event. LVWF is set when V Supply transitions * below the trip point or after reset and V Supply is already below the V LVW. * * @param baseAddr Base address for current PMC instance. * @return status Current LVWF status * - true: Low-Voltage Warning Flag is set. * - false: the Low-Voltage Warning does not happen. */ static inline bool PMC_HAL_GetLowVoltWarnFlag(uint32_t baseAddr) { return BR_PMC_LVDSC2_LVWF(baseAddr); } /*! * @brief Sets the Low-Voltage Warning Voltage Mode. * * This function sets the low voltage warning voltage select. It sets * the low voltage warning trip point voltage (Vlvw). An application can select * either a low, mid1, mid2 and a high-trip point. See a chip reference manual for * details and the pmc_lvwv_select_t for supported settings. * * @param baseAddr Base address for current PMC instance. * @param select Low voltage warning select setting */ static inline void PMC_HAL_SetLowVoltWarnVoltMode(uint32_t baseAddr, pmc_low_volt_warn_volt_select_t select) { BW_PMC_LVDSC2_LVWV(baseAddr, select); } /*! * @brief Gets the Low-Voltage Warning Voltage Mode. * * This function gets the low voltage warning voltage select. It gets * the low voltage warning trip point voltage (Vlvw). See the pmc_lvwv_select_t * for supported settings. * * @param baseAddr Base address for current PMC instance. * @return select Current low voltage warning select setting */ static inline pmc_low_volt_warn_volt_select_t PMC_HAL_GetLowVoltWarnVoltMode(uint32_t baseAddr) { return (pmc_low_volt_warn_volt_select_t)BR_PMC_LVDSC2_LVWV(baseAddr); } #if FSL_FEATURE_PMC_HAS_BGEN /*! * @brief Enables the Bandgap in the VLPx Operation. * * This function enables/disables the bandgap in lower power modes * (VLPx, * LLS, and VLLSx). When on-chip peripherals require the bandgap voltage * reference in low power modes, set the BGEN to continue to enable * the bandgap operation. * * @param baseAddr Base address for current PMC instance. * @param enable enable/disable the Bangap. */ static inline void PMC_HAL_SetBandgapInLowPowerModeCmd(uint32_t baseAddr, bool enable) { BW_PMC_REGSC_BGEN(baseAddr, enable); } #endif /*! * @brief Enables/Disables the Bandgap Buffer. * * This function enables/disables the Bandgap buffer. * * @param baseAddr Base address for current PMC instance. * @param enable enable/disable the Bangap Buffer. */ static inline void PMC_HAL_SetBandgapBufferCmd(uint32_t baseAddr, bool enable) { BW_PMC_REGSC_BGBE(baseAddr, enable); } /*! * @brief Gets the acknowledge isolation value. * * This function reads the Acknowledge Isolation setting that indicates * whether certain peripherals and the I/O pads are in a latched state as * a result of having been in the VLLS mode. * * @param baseAddr Base address for current PMC instance. * @return value ACK isolation * 0 - Peripherals and I/O pads are in a normal run state. * 1 - Certain peripherals and I/O pads are in an isolated and * latched state. */ static inline uint8_t PMC_HAL_GetAckIsolation(uint32_t baseAddr) { return BR_PMC_REGSC_ACKISO(baseAddr); } /*! * @brief Clears an acknowledge isolation. * * This function clears the ACK Isolation flag. Writing one to this setting * when it is set releases the I/O pads and certain peripherals to their normal * run mode state. * * @param baseAddr Base address for current PMC instance. */ static inline void PMC_HAL_SetClearAckIsolation(uint32_t baseAddr) { BW_PMC_REGSC_ACKISO(baseAddr, 1); } /*! * @brief Gets the Regulator regulation status. * * This function returns the regulator to a run regulation status. It provides * the current status of the internal voltage regulator. * * @param baseAddr Base address for current PMC instance. * @return value Regulation status * 0 - Regulator is in a stop regulation or in transition to/from it. * 1 - Regulator is in a run regulation. * */ static inline uint8_t PMC_HAL_GetRegulatorStatus(uint32_t baseAddr) { return BR_PMC_REGSC_REGONS(baseAddr); } /*@}*/ #if defined(__cplusplus) } #endif /* __cplusplus*/ /*! @}*/ #endif /* __FSL_PMC_HAL_H__*/ /******************************************************************************* * EOF ******************************************************************************/ ================================================ FILE: Zelig/mbed/TARGET_K64F/TARGET_Freescale/TARGET_KPSDK_MCUS/TARGET_KPSDK_CODE/hal/port/fsl_port_features.h ================================================ /* ** ################################################################### ** Version: rev. 1.0, 2014-05-14 ** Build: b140515 ** ** Abstract: ** Chip specific module features. ** ** Copyright: 2014 Freescale Semiconductor, Inc. ** All rights reserved. ** ** Redistribution and use in source and binary forms, with or without modification, ** are permitted provided that the following conditions are met: ** ** o Redistributions of source code must retain the above copyright notice, this list ** of conditions and the following disclaimer. ** ** o Redistributions in binary form must reproduce the above copyright notice, this ** list of conditions and the following disclaimer in the documentation and/or ** other materials provided with the distribution. ** ** o Neither the name of Freescale Semiconductor, Inc. nor the names of its ** contributors may be used to endorse or promote products derived from this ** software without specific prior written permission. ** ** THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ** ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED ** WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE ** DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT 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. ** ** http: www.freescale.com ** mail: support@freescale.com ** ** Revisions: ** - rev. 1.0 (2014-05-14) ** Customer release. ** ** ################################################################### */ #if !defined(__FSL_PORT_FEATURES_H__) #define __FSL_PORT_FEATURES_H__ #if defined(CPU_MK02FN128VFM10) || defined(CPU_MK02FN64VFM10) || defined(CPU_MK02FN128VLF10) || defined(CPU_MK02FN64VLF10) || \ defined(CPU_MK02FN128VLH10) || defined(CPU_MK02FN64VLH10) || defined(CPU_MK20DX128VMP5) || defined(CPU_MK20DN128VMP5) || \ defined(CPU_MK20DX64VMP5) || defined(CPU_MK20DN64VMP5) || defined(CPU_MK20DX32VMP5) || defined(CPU_MK20DN32VMP5) || \ defined(CPU_MK20DX128VLH5) || defined(CPU_MK20DN128VLH5) || defined(CPU_MK20DX64VLH5) || defined(CPU_MK20DN64VLH5) || \ defined(CPU_MK20DX32VLH5) || defined(CPU_MK20DN32VLH5) || defined(CPU_MK20DX128VFM5) || defined(CPU_MK20DN128VFM5) || \ defined(CPU_MK20DX64VFM5) || defined(CPU_MK20DN64VFM5) || defined(CPU_MK20DX32VFM5) || defined(CPU_MK20DN32VFM5) || \ defined(CPU_MK20DX128VFT5) || defined(CPU_MK20DN128VFT5) || defined(CPU_MK20DX64VFT5) || defined(CPU_MK20DN64VFT5) || \ defined(CPU_MK20DX32VFT5) || defined(CPU_MK20DN32VFT5) || defined(CPU_MK20DX128VLF5) || defined(CPU_MK20DN128VLF5) || \ defined(CPU_MK20DX64VLF5) || defined(CPU_MK20DN64VLF5) || defined(CPU_MK20DX32VLF5) || defined(CPU_MK20DN32VLF5) || \ defined(CPU_MK22FN128VDC10) || defined(CPU_MK22FN128VLH10) || defined(CPU_MK22FN128VLL10) || defined(CPU_MK22FN128VMP10) || \ defined(CPU_MK22FN256VDC12) || defined(CPU_MK22FN256VLH12) || defined(CPU_MK22FN256VLL12) || defined(CPU_MK22FN256VMP12) || \ defined(CPU_MK22FN512VDC12) || defined(CPU_MK22FN512VLH12) || defined(CPU_MK22FN512VLL12) || defined(CPU_MK24FN1M0VDC12) || \ defined(CPU_MK24FN1M0VLL12) || defined(CPU_MK24FN1M0VLQ12) || defined(CPU_MK24FN256VDC12) || defined(CPU_MK63FN1M0VLQ12) || \ defined(CPU_MK63FN1M0VMD12) || defined(CPU_MK64FX512VDC12) || defined(CPU_MK64FN1M0VDC12) || defined(CPU_MK64FX512VLL12) || \ defined(CPU_MK64FN1M0VLL12) || defined(CPU_MK64FX512VLQ12) || defined(CPU_MK64FN1M0VLQ12) || defined(CPU_MK64FX512VMD12) || \ defined(CPU_MK64FN1M0VMD12) || defined(CPU_MK65FN2M0CAC18) || defined(CPU_MK65FX1M0CAC18) || defined(CPU_MK65FN2M0VMI18) || \ defined(CPU_MK65FX1M0VMI18) || defined(CPU_MK66FN2M0VLQ18) || defined(CPU_MK66FX1M0VLQ18) || defined(CPU_MK66FN2M0VMD18) || \ defined(CPU_MK66FX1M0VMD18) || defined(CPU_MKV30F128VFM10) || defined(CPU_MKV30F64VFM10) || defined(CPU_MKV30F128VLF10) || \ defined(CPU_MKV30F64VLF10) || defined(CPU_MKV30F128VLH10) || defined(CPU_MKV30F64VLH10) || defined(CPU_MKV31F128VLH10) || \ defined(CPU_MKV31F128VLL10) || defined(CPU_MKV31F256VLH12) || defined(CPU_MKV31F256VLL12) || defined(CPU_MKV31F512VLH12) || \ defined(CPU_MKV31F512VLL12) || defined(CPU_MKV40F128VLH15) || defined(CPU_MKV40F128VLL15) || defined(CPU_MKV40F256VLH15) || \ defined(CPU_MKV40F256VLL15) || defined(CPU_MKV40F64VLH15) || defined(CPU_MKV43F128VLH15) || defined(CPU_MKV43F128VLL15) || \ defined(CPU_MKV43F64VLH15) || defined(CPU_MKV44F128VLH15) || defined(CPU_MKV44F128VLL15) || defined(CPU_MKV44F64VLH15) || \ defined(CPU_MKV45F128VLH15) || defined(CPU_MKV45F128VLL15) || defined(CPU_MKV45F256VLH15) || defined(CPU_MKV45F256VLL15) || \ defined(CPU_MKV46F128VLH15) || defined(CPU_MKV46F128VLL15) || defined(CPU_MKV46F256VLH15) || defined(CPU_MKV46F256VLL15) /* @brief Has control lock (register bit PCR[LK]). */ #define FSL_FEATURE_PORT_HAS_PIN_CONTROL_LOCK (1) /* @brief Has open drain control (register bit PCR[ODE]). */ #define FSL_FEATURE_PORT_HAS_OPEN_DRAIN (1) /* @brief Has digital filter (registers DFER, DFCR and DFWR). */ #define FSL_FEATURE_PORT_HAS_DIGITAL_FILTER (1) #define FSL_FEATURE_PORT_HAS_DIGITAL_FILTERn(x) \ ((x) == 0 ? (0) : \ ((x) == 1 ? (0) : \ ((x) == 2 ? (0) : \ ((x) == 3 ? (1) : \ ((x) == 4 ? (0) : (-1)))))) /* @brief Has DMA request (register bit field PCR[IRQC] values). */ #define FSL_FEATURE_PORT_HAS_DMA_REQUEST (1) /* @brief Has pull resistor selection (register bit PCR[PS]). */ #define FSL_FEATURE_PORT_HAS_PULL_SELECTION (1) /* @brief Has separate pull resistor enable registers (PUEL and PUEH). */ #define FSL_FEATURE_PORT_HAS_PULL_ENABLE_REGISTER (0) /* @brief Has slew rate control (register bit PCR[SRE]). */ #define FSL_FEATURE_PORT_HAS_SLEW_RATE (1) /* @brief Has passive filter (register bit field PCR[PFE]). */ #define FSL_FEATURE_PORT_HAS_PASSIVE_FILTER (1) #define FSL_FEATURE_PORT_HAS_PASSIVE_FILTERn(x) \ ((x) == 0 ? (1) : \ ((x) == 1 ? (1) : \ ((x) == 2 ? (1) : \ ((x) == 3 ? (1) : \ ((x) == 4 ? (1) : (-1)))))) /* @brief Has drive strength control (register bit PCR[DSE]). */ #define FSL_FEATURE_PORT_HAS_DRIVE_STRENGTH (1) /* @brief Has separate drive strength register (HDRVE). */ #define FSL_FEATURE_PORT_HAS_DRIVE_STRENGTH_REGISTER (0) /* @brief Has glitch filter (register IOFLT). */ #define FSL_FEATURE_PORT_HAS_GLITCH_FILTER (0) #elif defined(CPU_MK70FN1M0VMF12) || defined(CPU_MK70FX512VMF12) || defined(CPU_MK70FN1M0VMF15) || defined(CPU_MK70FX512VMF15) || \ defined(CPU_MK70FN1M0VMJ12) || defined(CPU_MK70FX512VMJ12) || defined(CPU_MK70FN1M0VMJ15) || defined(CPU_MK70FX512VMJ15) /* @brief Has control lock (register bit PCR[LK]). */ #define FSL_FEATURE_PORT_HAS_PIN_CONTROL_LOCK (1) /* @brief Has open drain control (register bit PCR[ODE]). */ #define FSL_FEATURE_PORT_HAS_OPEN_DRAIN (1) /* @brief Has digital filter (registers DFER, DFCR and DFWR). */ #define FSL_FEATURE_PORT_HAS_DIGITAL_FILTER (1) #define FSL_FEATURE_PORT_HAS_DIGITAL_FILTERn(x) \ ((x) == 0 ? (1) : \ ((x) == 1 ? (1) : \ ((x) == 2 ? (1) : \ ((x) == 3 ? (1) : \ ((x) == 4 ? (1) : \ ((x) == 5 ? (1) : (-1))))))) /* @brief Has DMA request (register bit field PCR[IRQC] values). */ #define FSL_FEATURE_PORT_HAS_DMA_REQUEST (1) /* @brief Has pull resistor selection (register bit PCR[PS]). */ #define FSL_FEATURE_PORT_HAS_PULL_SELECTION (1) /* @brief Has separate pull resistor enable registers (PUEL and PUEH). */ #define FSL_FEATURE_PORT_HAS_PULL_ENABLE_REGISTER (0) /* @brief Has slew rate control (register bit PCR[SRE]). */ #define FSL_FEATURE_PORT_HAS_SLEW_RATE (1) /* @brief Has passive filter (register bit field PCR[PFE]). */ #define FSL_FEATURE_PORT_HAS_PASSIVE_FILTER (1) #define FSL_FEATURE_PORT_HAS_PASSIVE_FILTERn(x) \ ((x) == 0 ? (1) : \ ((x) == 1 ? (1) : \ ((x) == 2 ? (1) : \ ((x) == 3 ? (1) : \ ((x) == 4 ? (1) : \ ((x) == 5 ? (1) : (-1))))))) /* @brief Has drive strength control (register bit PCR[DSE]). */ #define FSL_FEATURE_PORT_HAS_DRIVE_STRENGTH (1) /* @brief Has separate drive strength register (HDRVE). */ #define FSL_FEATURE_PORT_HAS_DRIVE_STRENGTH_REGISTER (0) /* @brief Has glitch filter (register IOFLT). */ #define FSL_FEATURE_PORT_HAS_GLITCH_FILTER (0) #elif defined(CPU_MKL03Z32CAF4) || defined(CPU_MKL03Z8VFG4) || defined(CPU_MKL03Z16VFG4) || defined(CPU_MKL03Z32VFG4) || \ defined(CPU_MKL03Z8VFK4) || defined(CPU_MKL03Z16VFK4) || defined(CPU_MKL03Z32VFK4) /* @brief Has control lock (register bit PCR[LK]). */ #define FSL_FEATURE_PORT_HAS_PIN_CONTROL_LOCK (0) /* @brief Has open drain control (register bit PCR[ODE]). */ #define FSL_FEATURE_PORT_HAS_OPEN_DRAIN (0) /* @brief Has digital filter (registers DFER, DFCR and DFWR). */ #define FSL_FEATURE_PORT_HAS_DIGITAL_FILTER (0) #define FSL_FEATURE_PORT_HAS_DIGITAL_FILTERn(x) \ ((x) == 0 ? (0) : \ ((x) == 1 ? (0) : (-1))) /* @brief Has DMA request (register bit field PCR[IRQC] values). */ #define FSL_FEATURE_PORT_HAS_DMA_REQUEST (0) /* @brief Has pull resistor selection (register bit PCR[PS]). */ #define FSL_FEATURE_PORT_HAS_PULL_SELECTION (1) /* @brief Has separate pull resistor enable registers (PUEL and PUEH). */ #define FSL_FEATURE_PORT_HAS_PULL_ENABLE_REGISTER (0) /* @brief Has slew rate control (register bit PCR[SRE]). */ #define FSL_FEATURE_PORT_HAS_SLEW_RATE (1) /* @brief Has passive filter (register bit field PCR[PFE]). */ #define FSL_FEATURE_PORT_HAS_PASSIVE_FILTER (1) #define FSL_FEATURE_PORT_HAS_PASSIVE_FILTERn(x) \ ((x) == 0 ? (1) : \ ((x) == 1 ? (1) : (-1))) /* @brief Has drive strength control (register bit PCR[DSE]). */ #define FSL_FEATURE_PORT_HAS_DRIVE_STRENGTH (1) /* @brief Has separate drive strength register (HDRVE). */ #define FSL_FEATURE_PORT_HAS_DRIVE_STRENGTH_REGISTER (0) /* @brief Has glitch filter (register IOFLT). */ #define FSL_FEATURE_PORT_HAS_GLITCH_FILTER (0) #elif defined(CPU_MKL05Z8VFK4) || defined(CPU_MKL05Z16VFK4) || defined(CPU_MKL05Z32VFK4) || defined(CPU_MKL05Z8VLC4) || \ defined(CPU_MKL05Z16VLC4) || defined(CPU_MKL05Z32VLC4) || defined(CPU_MKL05Z8VFM4) || defined(CPU_MKL05Z16VFM4) || \ defined(CPU_MKL05Z32VFM4) || defined(CPU_MKL05Z16VLF4) || defined(CPU_MKL05Z32VLF4) /* @brief Has control lock (register bit PCR[LK]). */ #define FSL_FEATURE_PORT_HAS_PIN_CONTROL_LOCK (0) /* @brief Has open drain control (register bit PCR[ODE]). */ #define FSL_FEATURE_PORT_HAS_OPEN_DRAIN (0) /* @brief Has digital filter (registers DFER, DFCR and DFWR). */ #define FSL_FEATURE_PORT_HAS_DIGITAL_FILTER (0) #define FSL_FEATURE_PORT_HAS_DIGITAL_FILTERn(x) \ ((x) == 0 ? (0) : \ ((x) == 1 ? (0) : (-1))) /* @brief Has DMA request (register bit field PCR[IRQC] values). */ #define FSL_FEATURE_PORT_HAS_DMA_REQUEST (1) /* @brief Has pull resistor selection (register bit PCR[PS]). */ #define FSL_FEATURE_PORT_HAS_PULL_SELECTION (1) /* @brief Has separate pull resistor enable registers (PUEL and PUEH). */ #define FSL_FEATURE_PORT_HAS_PULL_ENABLE_REGISTER (0) /* @brief Has slew rate control (register bit PCR[SRE]). */ #define FSL_FEATURE_PORT_HAS_SLEW_RATE (1) /* @brief Has passive filter (register bit field PCR[PFE]). */ #define FSL_FEATURE_PORT_HAS_PASSIVE_FILTER (1) #define FSL_FEATURE_PORT_HAS_PASSIVE_FILTERn(x) \ ((x) == 0 ? (1) : \ ((x) == 1 ? (1) : (-1))) /* @brief Has drive strength control (register bit PCR[DSE]). */ #define FSL_FEATURE_PORT_HAS_DRIVE_STRENGTH (1) /* @brief Has separate drive strength register (HDRVE). */ #define FSL_FEATURE_PORT_HAS_DRIVE_STRENGTH_REGISTER (0) /* @brief Has glitch filter (register IOFLT). */ #define FSL_FEATURE_PORT_HAS_GLITCH_FILTER (0) #elif defined(CPU_MKL13Z64VFM4) || defined(CPU_MKL13Z128VFM4) || defined(CPU_MKL13Z256VFM4) || defined(CPU_MKL13Z64VFT4) || \ defined(CPU_MKL13Z128VFT4) || defined(CPU_MKL13Z256VFT4) || defined(CPU_MKL13Z64VLH4) || defined(CPU_MKL13Z128VLH4) || \ defined(CPU_MKL13Z256VLH4) || defined(CPU_MKL13Z64VMP4) || defined(CPU_MKL13Z128VMP4) || defined(CPU_MKL13Z256VMP4) || \ defined(CPU_MKL23Z64VFM4) || defined(CPU_MKL23Z128VFM4) || defined(CPU_MKL23Z256VFM4) || defined(CPU_MKL23Z64VFT4) || \ defined(CPU_MKL23Z128VFT4) || defined(CPU_MKL23Z256VFT4) || defined(CPU_MKL23Z64VLH4) || defined(CPU_MKL23Z128VLH4) || \ defined(CPU_MKL23Z256VLH4) || defined(CPU_MKL23Z64VMP4) || defined(CPU_MKL23Z128VMP4) || defined(CPU_MKL23Z256VMP4) || \ defined(CPU_MKL33Z128VLH4) || defined(CPU_MKL33Z256VLH4) || defined(CPU_MKL33Z128VMP4) || defined(CPU_MKL33Z256VMP4) || \ defined(CPU_MKL43Z64VLH4) || defined(CPU_MKL43Z128VLH4) || defined(CPU_MKL43Z256VLH4) || defined(CPU_MKL43Z64VMP4) || \ defined(CPU_MKL43Z128VMP4) || defined(CPU_MKL43Z256VMP4) /* @brief Has control lock (register bit PCR[LK]). */ #define FSL_FEATURE_PORT_HAS_PIN_CONTROL_LOCK (0) /* @brief Has open drain control (register bit PCR[ODE]). */ #define FSL_FEATURE_PORT_HAS_OPEN_DRAIN (0) /* @brief Has digital filter (registers DFER, DFCR and DFWR). */ #define FSL_FEATURE_PORT_HAS_DIGITAL_FILTER (0) #define FSL_FEATURE_PORT_HAS_DIGITAL_FILTERn(x) \ ((x) == 0 ? (0) : \ ((x) == 1 ? (0) : \ ((x) == 2 ? (0) : \ ((x) == 3 ? (0) : \ ((x) == 4 ? (0) : (-1)))))) /* @brief Has DMA request (register bit field PCR[IRQC] values). */ #define FSL_FEATURE_PORT_HAS_DMA_REQUEST (1) /* @brief Has pull resistor selection (register bit PCR[PS]). */ #define FSL_FEATURE_PORT_HAS_PULL_SELECTION (1) /* @brief Has separate pull resistor enable registers (PUEL and PUEH). */ #define FSL_FEATURE_PORT_HAS_PULL_ENABLE_REGISTER (0) /* @brief Has slew rate control (register bit PCR[SRE]). */ #define FSL_FEATURE_PORT_HAS_SLEW_RATE (1) /* @brief Has passive filter (register bit field PCR[PFE]). */ #define FSL_FEATURE_PORT_HAS_PASSIVE_FILTER (1) #define FSL_FEATURE_PORT_HAS_PASSIVE_FILTERn(x) \ ((x) == 0 ? (1) : \ ((x) == 1 ? (1) : \ ((x) == 2 ? (1) : \ ((x) == 3 ? (1) : \ ((x) == 4 ? (1) : (-1)))))) /* @brief Has drive strength control (register bit PCR[DSE]). */ #define FSL_FEATURE_PORT_HAS_DRIVE_STRENGTH (1) /* @brief Has separate drive strength register (HDRVE). */ #define FSL_FEATURE_PORT_HAS_DRIVE_STRENGTH_REGISTER (0) /* @brief Has glitch filter (register IOFLT). */ #define FSL_FEATURE_PORT_HAS_GLITCH_FILTER (0) #elif defined(CPU_MKL25Z32VFM4) || defined(CPU_MKL25Z64VFM4) || defined(CPU_MKL25Z128VFM4) || defined(CPU_MKL25Z32VFT4) || \ defined(CPU_MKL25Z64VFT4) || defined(CPU_MKL25Z128VFT4) || defined(CPU_MKL25Z32VLH4) || defined(CPU_MKL25Z64VLH4) || \ defined(CPU_MKL25Z128VLH4) || defined(CPU_MKL25Z32VLK4) || defined(CPU_MKL25Z64VLK4) || defined(CPU_MKL25Z128VLK4) /* @brief Has control lock (register bit PCR[LK]). */ #define FSL_FEATURE_PORT_HAS_PIN_CONTROL_LOCK (0) /* @brief Has open drain control (register bit PCR[ODE]). */ #define FSL_FEATURE_PORT_HAS_OPEN_DRAIN (0) /* @brief Has digital filter (registers DFER, DFCR and DFWR). */ #define FSL_FEATURE_PORT_HAS_DIGITAL_FILTER (0) #define FSL_FEATURE_PORT_HAS_DIGITAL_FILTERn(x) \ ((x) == 0 ? (0) : \ ((x) == 1 ? (0) : \ ((x) == 2 ? (0) : \ ((x) == 3 ? (0) : \ ((x) == 4 ? (0) : (-1)))))) /* @brief Has DMA request (register bit field PCR[IRQC] values). */ #define FSL_FEATURE_PORT_HAS_DMA_REQUEST (1) /* @brief Has pull resistor selection (register bit PCR[PS]). */ #define FSL_FEATURE_PORT_HAS_PULL_SELECTION (0) /* @brief Has separate pull resistor enable registers (PUEL and PUEH). */ #define FSL_FEATURE_PORT_HAS_PULL_ENABLE_REGISTER (0) /* @brief Has slew rate control (register bit PCR[SRE]). */ #define FSL_FEATURE_PORT_HAS_SLEW_RATE (1) /* @brief Has passive filter (register bit field PCR[PFE]). */ #define FSL_FEATURE_PORT_HAS_PASSIVE_FILTER (1) #define FSL_FEATURE_PORT_HAS_PASSIVE_FILTERn(x) \ ((x) == 0 ? (1) : \ ((x) == 1 ? (0) : \ ((x) == 2 ? (0) : \ ((x) == 3 ? (0) : \ ((x) == 4 ? (0) : (-1)))))) /* @brief Has drive strength control (register bit PCR[DSE]). */ #define FSL_FEATURE_PORT_HAS_DRIVE_STRENGTH (1) /* @brief Has separate drive strength register (HDRVE). */ #define FSL_FEATURE_PORT_HAS_DRIVE_STRENGTH_REGISTER (0) /* @brief Has glitch filter (register IOFLT). */ #define FSL_FEATURE_PORT_HAS_GLITCH_FILTER (0) #elif defined(CPU_MKL26Z256VLK4) || defined(CPU_MKL26Z128VLL4) || defined(CPU_MKL26Z256VLL4) || defined(CPU_MKL26Z128VMC4) || \ defined(CPU_MKL26Z256VMC4) || defined(CPU_MKL46Z128VLH4) || defined(CPU_MKL46Z256VLH4) || defined(CPU_MKL46Z128VLL4) || \ defined(CPU_MKL46Z256VLL4) || defined(CPU_MKL46Z128VMC4) || defined(CPU_MKL46Z256VMC4) /* @brief Has control lock (register bit PCR[LK]). */ #define FSL_FEATURE_PORT_HAS_PIN_CONTROL_LOCK (0) /* @brief Has open drain control (register bit PCR[ODE]). */ #define FSL_FEATURE_PORT_HAS_OPEN_DRAIN (0) /* @brief Has digital filter (registers DFER, DFCR and DFWR). */ #define FSL_FEATURE_PORT_HAS_DIGITAL_FILTER (0) #define FSL_FEATURE_PORT_HAS_DIGITAL_FILTERn(x) \ ((x) == 0 ? (0) : \ ((x) == 1 ? (0) : \ ((x) == 2 ? (0) : \ ((x) == 3 ? (0) : \ ((x) == 4 ? (0) : (-1)))))) /* @brief Has DMA request (register bit field PCR[IRQC] values). */ #define FSL_FEATURE_PORT_HAS_DMA_REQUEST (1) /* @brief Has pull resistor selection (register bit PCR[PS]). */ #define FSL_FEATURE_PORT_HAS_PULL_SELECTION (1) /* @brief Has separate pull resistor enable registers (PUEL and PUEH). */ #define FSL_FEATURE_PORT_HAS_PULL_ENABLE_REGISTER (0) /* @brief Has slew rate control (register bit PCR[SRE]). */ #define FSL_FEATURE_PORT_HAS_SLEW_RATE (1) /* @brief Has passive filter (register bit field PCR[PFE]). */ #define FSL_FEATURE_PORT_HAS_PASSIVE_FILTER (1) #define FSL_FEATURE_PORT_HAS_PASSIVE_FILTERn(x) \ ((x) == 0 ? (1) : \ ((x) == 1 ? (0) : \ ((x) == 2 ? (0) : \ ((x) == 3 ? (0) : \ ((x) == 4 ? (0) : (-1)))))) /* @brief Has drive strength control (register bit PCR[DSE]). */ #define FSL_FEATURE_PORT_HAS_DRIVE_STRENGTH (1) /* @brief Has separate drive strength register (HDRVE). */ #define FSL_FEATURE_PORT_HAS_DRIVE_STRENGTH_REGISTER (0) /* @brief Has glitch filter (register IOFLT). */ #define FSL_FEATURE_PORT_HAS_GLITCH_FILTER (0) #else #error "No valid CPU defined!" #endif #endif /* __FSL_PORT_FEATURES_H__ */ /******************************************************************************* * EOF ******************************************************************************/ ================================================ FILE: Zelig/mbed/TARGET_K64F/TARGET_Freescale/TARGET_KPSDK_MCUS/TARGET_KPSDK_CODE/hal/port/fsl_port_hal.h ================================================ /* * Copyright (c) 2013 - 2014, Freescale Semiconductor, Inc. * All rights reserved. * * Redistribution and use in source and binary forms, with or without modification, * are permitted provided that the following conditions are met: * * o Redistributions of source code must retain the above copyright notice, this list * of conditions and the following disclaimer. * * o Redistributions in binary form must reproduce the above copyright notice, this * list of conditions and the following disclaimer in the documentation and/or * other materials provided with the distribution. * * o Neither the name of Freescale Semiconductor, Inc. nor the names of its * contributors may be used to endorse or promote products derived from this * software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT 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. */ #ifndef __FSL_PORT_HAL_H__ #define __FSL_PORT_HAL_H__ #include #include #include #include "fsl_port_features.h" #include "fsl_device_registers.h" /*! * @addtogroup port_hal * @{ */ /******************************************************************************* * Definitions ******************************************************************************/ /*! @brief Internal resistor pull feature selection*/ typedef enum _port_pull { kPortPullDown = 0U, /*!< internal pull-down resistor is enabled.*/ kPortPullUp = 1U /*!< internal pull-up resistor is enabled.*/ } port_pull_t; /*! @brief Slew rate selection*/ typedef enum _port_slew_rate { kPortFastSlewRate = 0U, /*!< fast slew rate is configured.*/ kPortSlowSlewRate = 1U /*!< slow slew rate is configured.*/ } port_slew_rate_t; /*! @brief Configures the drive strength.*/ typedef enum _port_drive_strength { kPortLowDriveStrength = 0U, /*!< low drive strength is configured.*/ kPortHighDriveStrength = 1U /*!< high drive strength is configured.*/ } port_drive_strength_t; /*! @brief Pin mux selection*/ typedef enum _port_mux { kPortPinDisabled = 0U, /*!< corresponding pin is disabled as analog.*/ kPortMuxAsGpio = 1U, /*!< corresponding pin is configured as GPIO.*/ kPortMuxAlt2 = 2U, /*!< chip-specific*/ kPortMuxAlt3 = 3U, /*!< chip-specific*/ kPortMuxAlt4 = 4U, /*!< chip-specific*/ kPortMuxAlt5 = 5U, /*!< chip-specific*/ kPortMuxAlt6 = 6U, /*!< chip-specific*/ kPortMuxAlt7 = 7U /*!< chip-specific*/ } port_mux_t; /*! @brief Digital filter clock source selection*/ #if FSL_FEATURE_PORT_HAS_DIGITAL_FILTER typedef enum _port_digital_filter_clock_source { kPortBusClock = 0U, /*!< Digital filters are clocked by the bus clock.*/ kPortLPOClock = 1U /*!< Digital filters are clocked by the 1 kHz LPO clock.*/ } port_digital_filter_clock_source_t; #endif /*! @brief Configures the interrupt generation condition.*/ typedef enum _port_interrupt_config { kPortIntDisabled = 0x0U, /*!< Interrupt/DMA request is disabled.*/ kPortDmaRisingEdge = 0x1U, /*!< DMA request on rising edge.*/ kPortDmaFallingEdge = 0x2U, /*!< DMA request on falling edge.*/ kPortDmaEitherEdge = 0x3U, /*!< DMA request on either edge.*/ kPortIntLogicZero = 0x8U, /*!< Interrupt when logic zero. */ kPortIntRisingEdge = 0x9U, /*!< Interrupt on rising edge. */ kPortIntFallingEdge = 0xAU, /*!< Interrupt on falling edge. */ kPortIntEitherEdge = 0xBU, /*!< Interrupt on either edge. */ kPortIntLogicOne = 0xCU /*!< Interrupt when logic one. */ } port_interrupt_config_t; /******************************************************************************* * API ******************************************************************************/ #if defined(__cplusplus) extern "C" { #endif /*! * @name Configuration * @{ */ /*! * @brief Selects the internal resistor as pull-down or pull-up. * * Pull configuration is valid in all digital pin muxing modes. * * @param baseAddr port base address. * @param pin port pin number * @param pullSelect internal resistor pull feature selection * - kPortPullDown: internal pull-down resistor is enabled. * - kPortPullUp : internal pull-up resistor is enabled. */ static inline void PORT_HAL_SetPullMode(uint32_t baseAddr, uint32_t pin, port_pull_t pullSelect) { assert(pin < 32U); BW_PORT_PCRn_PS(baseAddr, pin, pullSelect); } /*! * @brief Enables or disables the internal pull resistor. * * @param baseAddr port base address * @param pin port pin number * @param isPullEnabled internal pull resistor enable or disable * - true : internal pull resistor is enabled. * - false: internal pull resistor is disabled. */ static inline void PORT_HAL_SetPullCmd(uint32_t baseAddr, uint32_t pin, bool isPullEnabled) { assert(pin < 32U); BW_PORT_PCRn_PE(baseAddr, pin, isPullEnabled); } /*! * @brief Configures the fast/slow slew rate if the pin is used as a digital output. * * @param baseAddr port base address * @param pin port pin number * @param rateSelect slew rate selection * - kPortFastSlewRate: fast slew rate is configured. * - kPortSlowSlewRate: slow slew rate is configured. */ static inline void PORT_HAL_SetSlewRateMode(uint32_t baseAddr, uint32_t pin, port_slew_rate_t rateSelect) { assert(pin < 32U); BW_PORT_PCRn_SRE(baseAddr, pin, rateSelect); } /*! * @brief Configures the passive filter if the pin is used as a digital input. * * If enabled, a low pass filter (10 MHz to 30 MHz bandwidth) is enabled * on the digital input path. Disable the Passive Input Filter when supporting * high speed interfaces (> 2 MHz) on the pin. * * @param baseAddr port base address * @param pin port pin number * @param isPassiveFilterEnabled passive filter configuration * - false: passive filter is disabled. * - true : passive filter is enabled. */ static inline void PORT_HAL_SetPassiveFilterCmd(uint32_t baseAddr, uint32_t pin, bool isPassiveFilterEnabled) { assert(pin < 32U); BW_PORT_PCRn_PFE(baseAddr, pin, isPassiveFilterEnabled); } #if FSL_FEATURE_PORT_HAS_OPEN_DRAIN /*! * @brief Enables or disables the open drain. * * @param baseAddr port base address * @param pin port pin number * @param isOpenDrainEnabled enable open drain or not * - false: Open Drain output is disabled on the corresponding pin. * - true : Open Drain output is disabled on the corresponding pin. */ static inline void PORT_HAL_SetOpenDrainCmd(uint32_t baseAddr, uint32_t pin, bool isOpenDrainEnabled) { assert(pin < 32U); BW_PORT_PCRn_ODE(baseAddr, pin, isOpenDrainEnabled); } #endif /*FSL_FEATURE_PORT_HAS_OPEN_DRAIN*/ /*! * @brief Configures the drive strength if the pin is used as a digital output. * * @param baseAddr port base address * @param pin port pin number * @param driveSelect drive strength selection * - kLowDriveStrength : low drive strength is configured. * - kHighDriveStrength: high drive strength is configured. */ static inline void PORT_HAL_SetDriveStrengthMode(uint32_t baseAddr, uint32_t pin, port_drive_strength_t driveSelect) { assert(pin < 32U); BW_PORT_PCRn_DSE(baseAddr, pin, driveSelect); } /*! * @brief Configures the pin muxing. * * @param baseAddr port base address * @param pin port pin number * @param mux pin muxing slot selection * - kPinDisabled: Pin disabled. * - kMuxAsGpio : Set as GPIO. * - others : chip-specific. */ static inline void PORT_HAL_SetMuxMode(uint32_t baseAddr, uint32_t pin, port_mux_t mux) { assert(pin < 32U); BW_PORT_PCRn_MUX(baseAddr, pin, mux); } #if FSL_FEATURE_PORT_HAS_PIN_CONTROL_LOCK /*! * @brief Locks or unlocks the pin control register bits[15:0]. * * @param baseAddr port base address * @param pin port pin number * @param isPinLockEnabled lock pin control register or not * - false: pin control register bit[15:0] are not locked. * - true : pin control register bit[15:0] are locked, cannot be updated till system reset. */ static inline void PORT_HAL_SetPinCtrlLockCmd(uint32_t baseAddr, uint32_t pin, bool isPinLockEnabled) { assert(pin < 32U); BW_PORT_PCRn_LK(baseAddr, pin, isPinLockEnabled); } #endif /* FSL_FEATURE_PORT_HAS_PIN_CONTROL_LOCK*/ #if FSL_FEATURE_PORT_HAS_DIGITAL_FILTER /*! * @brief Enables or disables the digital filter in one single port. * Each bit of the 32-bit register represents one pin. * * @param baseAddr port base address * @param pin port pin number * @param isDigitalFilterEnabled digital filter enable/disable * - false: digital filter is disabled on the corresponding pin. * - true : digital filter is enabled on the corresponding pin. */ static inline void PORT_HAL_SetDigitalFilterCmd(uint32_t baseAddr, uint32_t pin, bool isDigitalFilterEnabled) { assert(pin < 32U); HW_PORT_DFER_SET(baseAddr, (uint32_t)isDigitalFilterEnabled << pin); } /*! * @brief Configures the clock source for the digital input filters. Changing the filter clock source should * only be done after disabling all enabled filters. Every pin in one port uses the same * clock source. * * @param baseAddr port base address * @param clockSource chose which clock source to use for current port * - kBusClock: digital filters are clocked by the bus clock. * - kLPOClock: digital filters are clocked by the 1 kHz LPO clock. */ static inline void PORT_HAL_SetDigitalFilterClock(uint32_t baseAddr, port_digital_filter_clock_source_t clockSource) { HW_PORT_DFCR_WR(baseAddr, clockSource); } /*! * @brief Configures the maximum size of the glitches (in clock cycles) that the digital filter absorbs * for enabled digital filters. Glitches that are longer than this register setting * (in clock cycles) pass through the digital filter, while glitches that are equal * to or less than this register setting (in clock cycles) are filtered. Changing the * filter length should only be done after disabling all enabled filters. * * @param baseAddr port base address * @param width configure digital filter width (should be less than 5 bits). */ static inline void PORT_HAL_SetDigitalFilterWidth(uint32_t baseAddr, uint8_t width) { HW_PORT_DFWR_WR(baseAddr, width); } #endif /* FSL_FEATURE_PORT_HAS_DIGITAL_FILTER*/ /*! * @brief Configures the low half of the pin control register for the same settings. * This function operates pin 0 -15 of one specific port. * * @param baseAddr port base address * @param lowPinSelect update corresponding pin control register or not. For a specific bit: * - 0: corresponding low half of pin control register won't be updated according to configuration. * - 1: corresponding low half of pin control register will be updated according to configuration. * @param config value is written to a low half port control register bits[15:0]. */ void PORT_HAL_SetLowGlobalPinCtrl(uint32_t baseAddr, uint16_t lowPinSelect, uint16_t config); /*! * @brief Configures the high half of pin control register for the same settings. * This function operates pin 16 -31 of one specific port. * * @param baseAddr port base address * @param highPinSelect update corresponding pin control register or not. For a specific bit: * - 0: corresponding high half of pin control register won't be updated according to configuration. * - 1: corresponding high half of pin control register will be updated according to configuration. * @param config value is written to a high half port control register bits[15:0]. */ void PORT_HAL_SetHighGlobalPinCtrl(uint32_t baseAddr, uint16_t highPinSelect, uint16_t config); /*@}*/ /*! * @name Interrupt * @{ */ /*! * @brief Configures the port pin interrupt/DMA request. * * @param baseAddr port base address. * @param pin port pin number * @param intConfig interrupt configuration * - kIntDisabled : Interrupt/DMA request disabled. * - kDmaRisingEdge : DMA request on rising edge. * - kDmaFallingEdge: DMA request on falling edge. * - kDmaEitherEdge : DMA request on either edge. * - KIntLogicZero : Interrupt when logic zero. * - KIntRisingEdge : Interrupt on rising edge. * - KIntFallingEdge: Interrupt on falling edge. * - KIntEitherEdge : Interrupt on either edge. * - KIntLogicOne : Interrupt when logic one. */ static inline void PORT_HAL_SetPinIntMode(uint32_t baseAddr, uint32_t pin, port_interrupt_config_t intConfig) { assert(pin < 32U); BW_PORT_PCRn_IRQC(baseAddr, pin, intConfig); } /*! * @brief Gets the current port pin interrupt/DMA request configuration. * * @param baseAddr port base address * @param pin port pin number * @return interrupt configuration * - kIntDisabled : Interrupt/DMA request disabled. * - kDmaRisingEdge : DMA request on rising edge. * - kDmaFallingEdge: DMA request on falling edge. * - kDmaEitherEdge : DMA request on either edge. * - KIntLogicZero : Interrupt when logic zero. * - KIntRisingEdge : Interrupt on rising edge. * - KIntFallingEdge: Interrupt on falling edge. * - KIntEitherEdge : Interrupt on either edge. * - KIntLogicOne : Interrupt when logic one. */ static inline port_interrupt_config_t PORT_HAL_GetPinIntMode(uint32_t baseAddr, uint32_t pin) { assert(pin < 32U); return (port_interrupt_config_t)BR_PORT_PCRn_IRQC(baseAddr, pin); } /*! * @brief Reads the individual pin-interrupt status flag. * * If a pin is configured to generate the DMA request, the corresponding flag * is cleared automatically at the completion of the requested DMA transfer. * Otherwise, the flag remains set until a logic one is written to that flag. * If configured for a level sensitive interrupt that remains asserted, the flag * is set again immediately. * * @param baseAddr port base address * @param pin port pin number * @return current pin interrupt status flag * - 0: interrupt is not detected. * - 1: interrupt is detected. */ static inline bool PORT_HAL_IsPinIntPending(uint32_t baseAddr, uint32_t pin) { assert(pin < 32U); return BR_PORT_PCRn_ISF(baseAddr, pin); } /*! * @brief Clears the individual pin-interrupt status flag. * * @param baseAddr port base address * @param pin port pin number */ static inline void PORT_HAL_ClearPinIntFlag(uint32_t baseAddr, uint32_t pin) { assert(pin < 32U); BW_PORT_PCRn_ISF(baseAddr, pin, 1U); } /*! * @brief Reads the entire port interrupt status flag. * * @param baseAddr port base address * @return all 32 pin interrupt status flags. For specific bit: * - 0: interrupt is not detected. * - 1: interrupt is detected. */ static inline uint32_t PORT_HAL_GetPortIntFlag(uint32_t baseAddr) { return HW_PORT_ISFR_RD(baseAddr); } /*! * @brief Clears the entire port interrupt status flag. * * @param baseAddr port base address */ static inline void PORT_HAL_ClearPortIntFlag(uint32_t baseAddr) { HW_PORT_ISFR_WR(baseAddr, ~0U); } /*@}*/ #if defined(__cplusplus) } #endif /*! @}*/ #endif /* __FSL_PORT_HAL_H__*/ /******************************************************************************* * EOF ******************************************************************************/ ================================================ FILE: Zelig/mbed/TARGET_K64F/TARGET_Freescale/TARGET_KPSDK_MCUS/TARGET_KPSDK_CODE/hal/rcm/fsl_rcm_features.h ================================================ /* ** ################################################################### ** Version: rev. 1.0, 2014-05-14 ** Build: b140516 ** ** Abstract: ** Chip specific module features. ** ** Copyright: 2014 Freescale Semiconductor, Inc. ** All rights reserved. ** ** Redistribution and use in source and binary forms, with or without modification, ** are permitted provided that the following conditions are met: ** ** o Redistributions of source code must retain the above copyright notice, this list ** of conditions and the following disclaimer. ** ** o Redistributions in binary form must reproduce the above copyright notice, this ** list of conditions and the following disclaimer in the documentation and/or ** other materials provided with the distribution. ** ** o Neither the name of Freescale Semiconductor, Inc. nor the names of its ** contributors may be used to endorse or promote products derived from this ** software without specific prior written permission. ** ** THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ** ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED ** WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE ** DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT 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. ** ** http: www.freescale.com ** mail: support@freescale.com ** ** Revisions: ** - rev. 1.0 (2014-05-14) ** Customer release. ** ** ################################################################### */ #if !defined(__FSL_RCM_FEATURES_H__) #define __FSL_RCM_FEATURES_H__ #if defined(CPU_MK02FN128VFM10) || defined(CPU_MK02FN64VFM10) || defined(CPU_MK02FN128VLF10) || defined(CPU_MK02FN64VLF10) || \ defined(CPU_MK02FN128VLH10) || defined(CPU_MK02FN64VLH10) || defined(CPU_MK22FN128VDC10) || defined(CPU_MK22FN128VLH10) || \ defined(CPU_MK22FN128VLL10) || defined(CPU_MK22FN128VMP10) || defined(CPU_MK70FN1M0VMF12) || defined(CPU_MK70FX512VMF12) || \ defined(CPU_MK70FN1M0VMF15) || defined(CPU_MK70FX512VMF15) || defined(CPU_MK70FN1M0VMJ12) || defined(CPU_MK70FX512VMJ12) || \ defined(CPU_MK70FN1M0VMJ15) || defined(CPU_MK70FX512VMJ15) || defined(CPU_MKL03Z32CAF4) || defined(CPU_MKL03Z8VFG4) || \ defined(CPU_MKL03Z16VFG4) || defined(CPU_MKL03Z32VFG4) || defined(CPU_MKL03Z8VFK4) || defined(CPU_MKL03Z16VFK4) || \ defined(CPU_MKL03Z32VFK4) || defined(CPU_MKL05Z8VFK4) || defined(CPU_MKL05Z16VFK4) || defined(CPU_MKL05Z32VFK4) || \ defined(CPU_MKL05Z8VLC4) || defined(CPU_MKL05Z16VLC4) || defined(CPU_MKL05Z32VLC4) || defined(CPU_MKL05Z8VFM4) || \ defined(CPU_MKL05Z16VFM4) || defined(CPU_MKL05Z32VFM4) || defined(CPU_MKL05Z16VLF4) || defined(CPU_MKL05Z32VLF4) || \ defined(CPU_MKL13Z64VFM4) || defined(CPU_MKL13Z128VFM4) || defined(CPU_MKL13Z256VFM4) || defined(CPU_MKL13Z64VFT4) || \ defined(CPU_MKL13Z128VFT4) || defined(CPU_MKL13Z256VFT4) || defined(CPU_MKL13Z64VLH4) || defined(CPU_MKL13Z128VLH4) || \ defined(CPU_MKL13Z256VLH4) || defined(CPU_MKL13Z64VMP4) || defined(CPU_MKL13Z128VMP4) || defined(CPU_MKL13Z256VMP4) || \ defined(CPU_MKL23Z64VFM4) || defined(CPU_MKL23Z128VFM4) || defined(CPU_MKL23Z256VFM4) || defined(CPU_MKL23Z64VFT4) || \ defined(CPU_MKL23Z128VFT4) || defined(CPU_MKL23Z256VFT4) || defined(CPU_MKL23Z64VLH4) || defined(CPU_MKL23Z128VLH4) || \ defined(CPU_MKL23Z256VLH4) || defined(CPU_MKL23Z64VMP4) || defined(CPU_MKL23Z128VMP4) || defined(CPU_MKL23Z256VMP4) || \ defined(CPU_MKL33Z128VLH4) || defined(CPU_MKL33Z256VLH4) || defined(CPU_MKL33Z128VMP4) || defined(CPU_MKL33Z256VMP4) || \ defined(CPU_MKL43Z64VLH4) || defined(CPU_MKL43Z128VLH4) || defined(CPU_MKL43Z256VLH4) || defined(CPU_MKL43Z64VMP4) || \ defined(CPU_MKL43Z128VMP4) || defined(CPU_MKL43Z256VMP4) || defined(CPU_MKV30F128VFM10) || defined(CPU_MKV30F64VFM10) || \ defined(CPU_MKV30F128VLF10) || defined(CPU_MKV30F64VLF10) || defined(CPU_MKV30F128VLH10) || defined(CPU_MKV30F64VLH10) || \ defined(CPU_MKV31F128VLH10) || defined(CPU_MKV31F128VLL10) /* @brief Has Loss-of-Lock Reset support. */ #define FSL_FEATURE_RCM_HAS_LOL (0) #elif defined(CPU_MK20DX128VMP5) || defined(CPU_MK20DN128VMP5) || defined(CPU_MK20DX64VMP5) || defined(CPU_MK20DN64VMP5) || \ defined(CPU_MK20DX32VMP5) || defined(CPU_MK20DN32VMP5) || defined(CPU_MK20DX128VLH5) || defined(CPU_MK20DN128VLH5) || \ defined(CPU_MK20DX64VLH5) || defined(CPU_MK20DN64VLH5) || defined(CPU_MK20DX32VLH5) || defined(CPU_MK20DN32VLH5) || \ defined(CPU_MK20DX128VFM5) || defined(CPU_MK20DN128VFM5) || defined(CPU_MK20DX64VFM5) || defined(CPU_MK20DN64VFM5) || \ defined(CPU_MK20DX32VFM5) || defined(CPU_MK20DN32VFM5) || defined(CPU_MK20DX128VFT5) || defined(CPU_MK20DN128VFT5) || \ defined(CPU_MK20DX64VFT5) || defined(CPU_MK20DN64VFT5) || defined(CPU_MK20DX32VFT5) || defined(CPU_MK20DN32VFT5) || \ defined(CPU_MK20DX128VLF5) || defined(CPU_MK20DN128VLF5) || defined(CPU_MK20DX64VLF5) || defined(CPU_MK20DN64VLF5) || \ defined(CPU_MK20DX32VLF5) || defined(CPU_MK20DN32VLF5) || defined(CPU_MK22FN256VDC12) || defined(CPU_MK22FN256VLH12) || \ defined(CPU_MK22FN256VLL12) || defined(CPU_MK22FN256VMP12) || defined(CPU_MK22FN512VDC12) || defined(CPU_MK22FN512VLH12) || \ defined(CPU_MK22FN512VLL12) || defined(CPU_MK24FN1M0VDC12) || defined(CPU_MK24FN1M0VLL12) || defined(CPU_MK24FN1M0VLQ12) || \ defined(CPU_MK24FN256VDC12) || defined(CPU_MK63FN1M0VLQ12) || defined(CPU_MK63FN1M0VMD12) || defined(CPU_MK64FX512VDC12) || \ defined(CPU_MK64FN1M0VDC12) || defined(CPU_MK64FX512VLL12) || defined(CPU_MK64FN1M0VLL12) || defined(CPU_MK64FX512VLQ12) || \ defined(CPU_MK64FN1M0VLQ12) || defined(CPU_MK64FX512VMD12) || defined(CPU_MK64FN1M0VMD12) || defined(CPU_MK65FN2M0CAC18) || \ defined(CPU_MK65FX1M0CAC18) || defined(CPU_MK65FN2M0VMI18) || defined(CPU_MK65FX1M0VMI18) || defined(CPU_MK66FN2M0VLQ18) || \ defined(CPU_MK66FX1M0VLQ18) || defined(CPU_MK66FN2M0VMD18) || defined(CPU_MK66FX1M0VMD18) || defined(CPU_MKL25Z32VFM4) || \ defined(CPU_MKL25Z64VFM4) || defined(CPU_MKL25Z128VFM4) || defined(CPU_MKL25Z32VFT4) || defined(CPU_MKL25Z64VFT4) || \ defined(CPU_MKL25Z128VFT4) || defined(CPU_MKL25Z32VLH4) || defined(CPU_MKL25Z64VLH4) || defined(CPU_MKL25Z128VLH4) || \ defined(CPU_MKL25Z32VLK4) || defined(CPU_MKL25Z64VLK4) || defined(CPU_MKL25Z128VLK4) || defined(CPU_MKL26Z256VLK4) || \ defined(CPU_MKL26Z128VLL4) || defined(CPU_MKL26Z256VLL4) || defined(CPU_MKL26Z128VMC4) || defined(CPU_MKL26Z256VMC4) || \ defined(CPU_MKL46Z128VLH4) || defined(CPU_MKL46Z256VLH4) || defined(CPU_MKL46Z128VLL4) || defined(CPU_MKL46Z256VLL4) || \ defined(CPU_MKL46Z128VMC4) || defined(CPU_MKL46Z256VMC4) || defined(CPU_MKV31F256VLH12) || defined(CPU_MKV31F256VLL12) || \ defined(CPU_MKV31F512VLH12) || defined(CPU_MKV31F512VLL12) || defined(CPU_MKV40F128VLH15) || defined(CPU_MKV40F128VLL15) || \ defined(CPU_MKV40F256VLH15) || defined(CPU_MKV40F256VLL15) || defined(CPU_MKV40F64VLH15) || defined(CPU_MKV43F128VLH15) || \ defined(CPU_MKV43F128VLL15) || defined(CPU_MKV43F64VLH15) || defined(CPU_MKV44F128VLH15) || defined(CPU_MKV44F128VLL15) || \ defined(CPU_MKV44F64VLH15) || defined(CPU_MKV45F128VLH15) || defined(CPU_MKV45F128VLL15) || defined(CPU_MKV45F256VLH15) || \ defined(CPU_MKV45F256VLL15) || defined(CPU_MKV46F128VLH15) || defined(CPU_MKV46F128VLL15) || defined(CPU_MKV46F256VLH15) || \ defined(CPU_MKV46F256VLL15) /* @brief Has Loss-of-Lock Reset support. */ #define FSL_FEATURE_RCM_HAS_LOL (1) #else #error "No valid CPU defined!" #endif #endif /* __FSL_RCM_FEATURES_H__ */ /******************************************************************************* * EOF ******************************************************************************/ ================================================ FILE: Zelig/mbed/TARGET_K64F/TARGET_Freescale/TARGET_KPSDK_MCUS/TARGET_KPSDK_CODE/hal/rcm/fsl_rcm_hal.h ================================================ /* * Copyright (c) 2013 - 2014, Freescale Semiconductor, Inc. * All rights reserved. * * Redistribution and use in source and binary forms, with or without modification, * are permitted provided that the following conditions are met: * * o Redistributions of source code must retain the above copyright notice, this list * of conditions and the following disclaimer. * * o Redistributions in binary form must reproduce the above copyright notice, this * list of conditions and the following disclaimer in the documentation and/or * other materials provided with the distribution. * * o Neither the name of Freescale Semiconductor, Inc. nor the names of its * contributors may be used to endorse or promote products derived from this * software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT 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. */ #if !defined(__FSL_RCM_HAL_H__) #define __FSL_RCM_HAL_H__ #include #include #include #include "fsl_device_registers.h" #include "fsl_rcm_features.h" /*! @addtogroup rcm_hal*/ /*! @{*/ /*! @file fsl_rcm_hal.h */ /******************************************************************************* * Definitions ******************************************************************************/ /*! @brief System Reset Source Name definitions */ typedef enum _rcm_source_names { kRcmWakeup, /* low-leakage wakeup reset */ kRcmLowVoltDetect, /* low voltage detect reset */ kRcmLossOfClk, /* loss of clock reset */ kRcmLossOfLock, /* loss of lock reset */ kRcmWatchDog, /* watch dog reset */ kRcmExternalPin, /* external pin reset */ kRcmPowerOn, /* power on reset */ kRcmJtag, /* JTAG generated reset */ kRcmCoreLockup, /* core lockup reset */ kRcmSoftware, /* software reset */ kRcmSystem, /* system reset request bit set reset */ kRcmEzport, /* EzPort reset */ kRcmStopModeAckErr, /* stop mode ack error reset */ kRcmSrcNameMax } rcm_source_names_t; /*! @brief Reset pin filter select in Run and Wait modes */ typedef enum _rcm_filter_run_wait_modes { kRcmFilterDisabled, /* all filtering disabled */ kRcmFilterBusClk, /* Bus clock filter enabled */ kRcmFilterLpoClk, /* LPO clock filter enabled */ kRcmFilterReserverd /* reserved setting */ } rcm_filter_run_wait_modes_t; /******************************************************************************* * API ******************************************************************************/ /*! * @brief Gets the reset source status. * * This function gets the current reset source status for a specified source. * * @param baseAddr Register base address of RCM * @param srcName reset source name * @return status true or false for specified reset source */ bool RCM_HAL_GetSrcStatusCmd(uint32_t baseAddr, rcm_source_names_t srcName); /*! * @brief Sets the reset pin filter in stop mode. * * This function sets the reset pin filter enable setting in stop mode. * * @param baseAddr Register base address of RCM * @param enable enable or disable the filter in stop mode */ static inline void RCM_HAL_SetFilterStopModeCmd(uint32_t baseAddr, bool enable) { BW_RCM_RPFC_RSTFLTSS(baseAddr, enable); } /*! * @brief Gets the reset pin filter in stop mode. * * This function gets the reset pin filter enable setting in stop mode. * * @param baseAddr Register base address of RCM * @return enable true/false to enable or disable the filter in stop mode */ static inline bool RCM_HAL_GetFilterStopModeCmd(uint32_t baseAddr) { return (bool)BR_RCM_RPFC_RSTFLTSS(baseAddr); } /*! * @brief Sets the reset pin filter in run and wait mode. * * This function sets the reset pin filter enable setting in run/wait mode. * * @param baseAddr Register base address of RCM * @param mode to be set for reset filter in run/wait mode */ static inline void RCM_HAL_SetFilterRunWaitMode(uint32_t baseAddr, rcm_filter_run_wait_modes_t mode) { BW_RCM_RPFC_RSTFLTSRW(baseAddr, mode); } /*! * @brief Gets the reset pin filter for stop mode. * * This function gets the reset pin filter enable setting for stop mode. * * @param baseAddr Register base address of RCM * @return mode for reset filter in run/wait mode */ static inline rcm_filter_run_wait_modes_t RCM_HAL_GetFilterRunWaitMode(uint32_t baseAddr) { return (rcm_filter_run_wait_modes_t)BR_RCM_RPFC_RSTFLTSRW(baseAddr); } /*! * @brief Sets the reset pin filter width. * * This function sets the reset pin filter width. * * @param baseAddr Register base address of RCM * @param width to be set for reset filter width */ static inline void RCM_HAL_SetFilterWidth(uint32_t baseAddr, uint32_t width) { BW_RCM_RPFW_RSTFLTSEL(baseAddr, width); } /*! * @brief Gets the reset pin filter for stop mode. * * This function gets the reset pin filter width. * * @param baseAddr Register base address of RCM * @return width reset filter width */ static inline uint32_t RCM_HAL_GetFilterWidth(uint32_t baseAddr) { return (uint32_t)BR_RCM_RPFW_RSTFLTSEL(baseAddr); } /*! * @brief Gets the EZP_MS_B pin assert status. * * This function gets the easy port mode status (EZP_MS_B) pin assert status. * * @param baseAddr Register base address of RCM * @return status true - asserted, false - reasserted */ static inline bool RCM_HAL_GetEasyPortModeStatusCmd(uint32_t baseAddr) { return (bool)BR_RCM_MR_EZP_MS(baseAddr); } #if defined(__cplusplus) extern "C" { #endif /* __cplusplus*/ /*! @name Reset Control Module APIs*/ /*@{*/ /*@}*/ #if defined(__cplusplus) } #endif /* __cplusplus*/ /*! @}*/ #endif /* __FSL_RCM_HAL_H__*/ /******************************************************************************* * EOF ******************************************************************************/ ================================================ FILE: Zelig/mbed/TARGET_K64F/TARGET_Freescale/TARGET_KPSDK_MCUS/TARGET_KPSDK_CODE/hal/rtc/fsl_rtc_features.h ================================================ /* ** ################################################################### ** Version: rev. 1.0, 2014-05-14 ** Build: b140515 ** ** Abstract: ** Chip specific module features. ** ** Copyright: 2014 Freescale Semiconductor, Inc. ** All rights reserved. ** ** Redistribution and use in source and binary forms, with or without modification, ** are permitted provided that the following conditions are met: ** ** o Redistributions of source code must retain the above copyright notice, this list ** of conditions and the following disclaimer. ** ** o Redistributions in binary form must reproduce the above copyright notice, this ** list of conditions and the following disclaimer in the documentation and/or ** other materials provided with the distribution. ** ** o Neither the name of Freescale Semiconductor, Inc. nor the names of its ** contributors may be used to endorse or promote products derived from this ** software without specific prior written permission. ** ** THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ** ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED ** WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE ** DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT 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. ** ** http: www.freescale.com ** mail: support@freescale.com ** ** Revisions: ** - rev. 1.0 (2014-05-14) ** Customer release. ** ** ################################################################### */ #if !defined(__FSL_RTC_FEATURES_H__) #define __FSL_RTC_FEATURES_H__ #if defined(CPU_MK20DX128VMP5) || defined(CPU_MK20DN128VMP5) || defined(CPU_MK20DX64VMP5) || defined(CPU_MK20DN64VMP5) || \ defined(CPU_MK20DX32VMP5) || defined(CPU_MK20DN32VMP5) || defined(CPU_MK20DX128VLH5) || defined(CPU_MK20DN128VLH5) || \ defined(CPU_MK20DX64VLH5) || defined(CPU_MK20DN64VLH5) || defined(CPU_MK20DX32VLH5) || defined(CPU_MK20DN32VLH5) || \ defined(CPU_MK20DX128VFM5) || defined(CPU_MK20DN128VFM5) || defined(CPU_MK20DX64VFM5) || defined(CPU_MK20DN64VFM5) || \ defined(CPU_MK20DX32VFM5) || defined(CPU_MK20DN32VFM5) || defined(CPU_MK20DX128VFT5) || defined(CPU_MK20DN128VFT5) || \ defined(CPU_MK20DX64VFT5) || defined(CPU_MK20DN64VFT5) || defined(CPU_MK20DX32VFT5) || defined(CPU_MK20DN32VFT5) || \ defined(CPU_MK20DX128VLF5) || defined(CPU_MK20DN128VLF5) || defined(CPU_MK20DX64VLF5) || defined(CPU_MK20DN64VLF5) || \ defined(CPU_MK20DX32VLF5) || defined(CPU_MK20DN32VLF5) /* @brief Has wakeup pin (bit field CR[WPS]). */ #define FSL_FEATURE_RTC_HAS_WAKEUP_PIN (0) /* @brief Has low power features (registers MER, MCLR and MCHR). */ #define FSL_FEATURE_RTC_HAS_MONOTONIC (0) /* @brief Has read/write access control (registers WAR and RAR). */ #define FSL_FEATURE_RTC_HAS_ACCESS_CONTROL (1) /* @brief Has security features (registers TTSR, MER, MCLR and MCHR). */ #define FSL_FEATURE_RTC_HAS_SECURITY (0) #elif defined(CPU_MK22FN128VDC10) || defined(CPU_MK22FN128VLH10) || defined(CPU_MK22FN128VLL10) || defined(CPU_MK22FN128VMP10) || \ defined(CPU_MK22FN256VDC12) || defined(CPU_MK22FN256VLH12) || defined(CPU_MK22FN256VLL12) || defined(CPU_MK22FN256VMP12) || \ defined(CPU_MK22FN512VDC12) || defined(CPU_MK22FN512VLH12) || defined(CPU_MK22FN512VLL12) || defined(CPU_MK63FN1M0VLQ12) || \ defined(CPU_MK63FN1M0VMD12) || defined(CPU_MK64FX512VDC12) || defined(CPU_MK64FN1M0VDC12) || defined(CPU_MK64FX512VLL12) || \ defined(CPU_MK64FN1M0VLL12) || defined(CPU_MK64FX512VLQ12) || defined(CPU_MK64FN1M0VLQ12) /* @brief Has wakeup pin (bit field CR[WPS]). */ #define FSL_FEATURE_RTC_HAS_WAKEUP_PIN (1) /* @brief Has low power features (registers MER, MCLR and MCHR). */ #define FSL_FEATURE_RTC_HAS_MONOTONIC (0) /* @brief Has read/write access control (registers WAR and RAR). */ #define FSL_FEATURE_RTC_HAS_ACCESS_CONTROL (1) /* @brief Has security features (registers TTSR, MER, MCLR and MCHR). */ #define FSL_FEATURE_RTC_HAS_SECURITY (1) #elif defined(CPU_MK24FN1M0VDC12) || defined(CPU_MK24FN1M0VLL12) || defined(CPU_MK24FN1M0VLQ12) || defined(CPU_MK24FN256VDC12) || \ defined(CPU_MK64FX512VMD12) || defined(CPU_MK64FN1M0VMD12) /* @brief Has wakeup pin (bit field CR[WPS]). */ #define FSL_FEATURE_RTC_HAS_WAKEUP_PIN (1) /* @brief Has low power features (registers MER, MCLR and MCHR). */ #define FSL_FEATURE_RTC_HAS_MONOTONIC (0) /* @brief Has read/write access control (registers WAR and RAR). */ #define FSL_FEATURE_RTC_HAS_ACCESS_CONTROL (1) /* @brief Has security features (registers TTSR, MER, MCLR and MCHR). */ #define FSL_FEATURE_RTC_HAS_SECURITY (0) #elif defined(CPU_MK65FN2M0CAC18) || defined(CPU_MK65FX1M0CAC18) || defined(CPU_MK65FN2M0VMI18) || defined(CPU_MK65FX1M0VMI18) || \ defined(CPU_MK66FN2M0VLQ18) || defined(CPU_MK66FX1M0VLQ18) || defined(CPU_MK66FN2M0VMD18) || defined(CPU_MK66FX1M0VMD18) /* @brief Has wakeup pin (bit field CR[WPS]). */ #define FSL_FEATURE_RTC_HAS_WAKEUP_PIN (1) /* @brief Has low power features (registers MER, MCLR and MCHR). */ #define FSL_FEATURE_RTC_HAS_MONOTONIC (1) /* @brief Has read/write access control (registers WAR and RAR). */ #define FSL_FEATURE_RTC_HAS_ACCESS_CONTROL (1) /* @brief Has security features (registers TTSR, MER, MCLR and MCHR). */ #define FSL_FEATURE_RTC_HAS_SECURITY (1) #elif defined(CPU_MK70FN1M0VMF12) || defined(CPU_MK70FX512VMF12) || defined(CPU_MK70FN1M0VMF15) || defined(CPU_MK70FX512VMF15) || \ defined(CPU_MK70FN1M0VMJ12) || defined(CPU_MK70FX512VMJ12) || defined(CPU_MK70FN1M0VMJ15) || defined(CPU_MK70FX512VMJ15) /* @brief Has wakeup pin (bit field CR[WPS]). */ #define FSL_FEATURE_RTC_HAS_WAKEUP_PIN (0) /* @brief Has low power features (registers MER, MCLR and MCHR). */ #define FSL_FEATURE_RTC_HAS_MONOTONIC (1) /* @brief Has read/write access control (registers WAR and RAR). */ #define FSL_FEATURE_RTC_HAS_ACCESS_CONTROL (1) /* @brief Has security features (registers TTSR, MER, MCLR and MCHR). */ #define FSL_FEATURE_RTC_HAS_SECURITY (1) #elif defined(CPU_MKL03Z32CAF4) || defined(CPU_MKL03Z8VFG4) || defined(CPU_MKL03Z16VFG4) || defined(CPU_MKL03Z32VFG4) || \ defined(CPU_MKL03Z8VFK4) || defined(CPU_MKL03Z16VFK4) || defined(CPU_MKL03Z32VFK4) || defined(CPU_MKL05Z8VFK4) || \ defined(CPU_MKL05Z16VFK4) || defined(CPU_MKL05Z32VFK4) || defined(CPU_MKL05Z8VLC4) || defined(CPU_MKL05Z16VLC4) || \ defined(CPU_MKL05Z32VLC4) || defined(CPU_MKL05Z8VFM4) || defined(CPU_MKL05Z16VFM4) || defined(CPU_MKL05Z32VFM4) || \ defined(CPU_MKL05Z16VLF4) || defined(CPU_MKL05Z32VLF4) || defined(CPU_MKL13Z64VFM4) || defined(CPU_MKL13Z128VFM4) || \ defined(CPU_MKL13Z256VFM4) || defined(CPU_MKL13Z64VFT4) || defined(CPU_MKL13Z128VFT4) || defined(CPU_MKL13Z256VFT4) || \ defined(CPU_MKL13Z64VLH4) || defined(CPU_MKL13Z128VLH4) || defined(CPU_MKL13Z256VLH4) || defined(CPU_MKL13Z64VMP4) || \ defined(CPU_MKL13Z128VMP4) || defined(CPU_MKL13Z256VMP4) || defined(CPU_MKL23Z64VFM4) || defined(CPU_MKL23Z128VFM4) || \ defined(CPU_MKL23Z256VFM4) || defined(CPU_MKL23Z64VFT4) || defined(CPU_MKL23Z128VFT4) || defined(CPU_MKL23Z256VFT4) || \ defined(CPU_MKL23Z64VLH4) || defined(CPU_MKL23Z128VLH4) || defined(CPU_MKL23Z256VLH4) || defined(CPU_MKL23Z64VMP4) || \ defined(CPU_MKL23Z128VMP4) || defined(CPU_MKL23Z256VMP4) || defined(CPU_MKL25Z32VFM4) || defined(CPU_MKL25Z64VFM4) || \ defined(CPU_MKL25Z128VFM4) || defined(CPU_MKL25Z32VFT4) || defined(CPU_MKL25Z64VFT4) || defined(CPU_MKL25Z128VFT4) || \ defined(CPU_MKL25Z32VLH4) || defined(CPU_MKL25Z64VLH4) || defined(CPU_MKL25Z128VLH4) || defined(CPU_MKL25Z32VLK4) || \ defined(CPU_MKL25Z64VLK4) || defined(CPU_MKL25Z128VLK4) || defined(CPU_MKL26Z256VLK4) || defined(CPU_MKL26Z128VLL4) || \ defined(CPU_MKL26Z256VLL4) || defined(CPU_MKL26Z128VMC4) || defined(CPU_MKL26Z256VMC4) || defined(CPU_MKL33Z128VLH4) || \ defined(CPU_MKL33Z256VLH4) || defined(CPU_MKL33Z128VMP4) || defined(CPU_MKL33Z256VMP4) || defined(CPU_MKL43Z64VLH4) || \ defined(CPU_MKL43Z128VLH4) || defined(CPU_MKL43Z256VLH4) || defined(CPU_MKL43Z64VMP4) || defined(CPU_MKL43Z128VMP4) || \ defined(CPU_MKL43Z256VMP4) || defined(CPU_MKL46Z128VLH4) || defined(CPU_MKL46Z256VLH4) || defined(CPU_MKL46Z128VLL4) || \ defined(CPU_MKL46Z256VLL4) || defined(CPU_MKL46Z128VMC4) || defined(CPU_MKL46Z256VMC4) /* @brief Has wakeup pin (bit field CR[WPS]). */ #define FSL_FEATURE_RTC_HAS_WAKEUP_PIN (1) /* @brief Has low power features (registers MER, MCLR and MCHR). */ #define FSL_FEATURE_RTC_HAS_MONOTONIC (0) /* @brief Has read/write access control (registers WAR and RAR). */ #define FSL_FEATURE_RTC_HAS_ACCESS_CONTROL (0) /* @brief Has security features (registers TTSR, MER, MCLR and MCHR). */ #define FSL_FEATURE_RTC_HAS_SECURITY (0) #else #error "No valid CPU defined!" #endif #endif /* __FSL_RTC_FEATURES_H__ */ /******************************************************************************* * EOF ******************************************************************************/ ================================================ FILE: Zelig/mbed/TARGET_K64F/TARGET_Freescale/TARGET_KPSDK_MCUS/TARGET_KPSDK_CODE/hal/rtc/fsl_rtc_hal.h ================================================ /* * Copyright (c) 2013 - 2014, Freescale Semiconductor, Inc. * All rights reserved. * * Redistribution and use in source and binary forms, with or without modification, * are permitted provided that the following conditions are met: * * o Redistributions of source code must retain the above copyright notice, this list * of conditions and the following disclaimer. * * o Redistributions in binary form must reproduce the above copyright notice, this * list of conditions and the following disclaimer in the documentation and/or * other materials provided with the distribution. * * o Neither the name of Freescale Semiconductor, Inc. nor the names of its * contributors may be used to endorse or promote products derived from this * software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT 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. */ #if !defined(__FSL_RTC_HAL_H__) #define __FSL_RTC_HAL_H__ #include #include #include #include "fsl_rtc_features.h" #include "fsl_device_registers.h" /*! * @addtogroup rtc_hal * @{ */ /******************************************************************************* * Definitions ******************************************************************************/ /*! * @brief Structure is used to hold the time in a simple "date" format. */ typedef struct RtcDatetime { uint16_t year; /*!< Range from 1970 to 2099.*/ uint16_t month; /*!< Range from 1 to 12.*/ uint16_t day; /*!< Range from 1 to 31 (depending on month).*/ uint16_t hour; /*!< Range from 0 to 23.*/ uint16_t minute; /*!< Range from 0 to 59.*/ uint8_t second; /*!< Range from 0 to 59.*/ } rtc_datetime_t; /******************************************************************************* * API ******************************************************************************/ #if defined(__cplusplus) extern "C" { #endif /*! * @name RTC HAL API Functions * @{ */ /*! * @brief Initializes the RTC module. * * This function enables the RTC oscillator. * * @param rtcBaseAddr The RTC base address. */ void RTC_HAL_Enable(uint32_t rtcBaseAddr); /*! * @brief Disables the RTC module. * * This function disablesS the RTC counter and oscillator. * * @param rtcBaseAddr The RTC base address. */ void RTC_HAL_Disable(uint32_t rtcBaseAddr); /*! * @brief Resets the RTC module. * * This function initiates a soft-reset of the RTC module to reset * the RTC registers. * * @param rtcBaseAddr The RTC base address.. */ void RTC_HAL_Init(uint32_t rtcBaseAddr); /*! * @brief Converts seconds to date time format data structure. * * @param seconds holds the date and time information in seconds * @param datetime holds the converted information from seconds in date and time format */ void RTC_HAL_ConvertSecsToDatetime(const uint32_t * seconds, rtc_datetime_t * datetime); /*! * @brief Checks whether the date time structure elements have the information that is within the range. * * @param datetime holds the date and time information that needs to be converted to seconds */ bool RTC_HAL_IsDatetimeCorrectFormat(const rtc_datetime_t * datetime); /*! * @brief Converts the date time format data structure to seconds. * * @param datetime holds the date and time information that needs to be converted to seconds * @param seconds holds the converted date and time in seconds */ void RTC_HAL_ConvertDatetimeToSecs(const rtc_datetime_t * datetime, uint32_t * seconds); /*! * @brief Sets the RTC date and time according to the given time structure. * * The function converts the data from the time structure to seconds and writes the seconds * value to the RTC register. The RTC counter is started after setting the time. * * @param rtcBaseAddr The RTC base address * @param datetime [in] Pointer to structure where the date and time * details to set are stored. */ void RTC_HAL_SetDatetime(uint32_t rtcBaseAddr, const rtc_datetime_t * datetime); /*! * @brief Sets the RTC date and time according to the given time provided in seconds. * * The RTC counter is started after setting the time. * * @param rtcBaseAddr The RTC base address * @param seconds [in] Time in seconds */ void RTC_HAL_SetDatetimeInsecs(uint32_t rtcBaseAddr, const uint32_t seconds); /*! * @brief Gets the RTC time and stores it in the given time structure. * * The function reads the value in seconds from the RTC register. It then converts to the * time structure which provides the time in date, hour, minutes and seconds. * * @param rtcBaseAddr The RTC base address * @param datetime [out] pointer to a structure where the date and time details are * stored. */ void RTC_HAL_GetDatetime(uint32_t rtcBaseAddr, rtc_datetime_t * datetime); /*! * @brief Gets the RTC time and returns it in seconds. * * @param rtcBaseAddr The RTC base address * @param datetime [out] pointer to variable where the RTC time is stored in seconds */ void RTC_HAL_GetDatetimeInSecs(uint32_t rtcBaseAddr, uint32_t * seconds); /*! * @brief Reads the value of the time alarm. * * @param rtcBaseAddr The RTC base address * @param date [out] pointer to a variable where the alarm date and time * details are stored. */ void RTC_HAL_GetAlarm(uint32_t rtcBaseAddr, rtc_datetime_t * date); /*! * @brief Sets the RTC alarm time and enables the alarm interrupt. * * The function checks whether the specified alarm time is greater than the present * time. If not, the function does not set the alarm and returns an error. * * @param rtcBaseAddr The RTC base address.. * @param date [in] pointer to structure where the alarm date and time * details will be stored at. * @return true: success in setting the RTC alarm\n * false: error in setting the RTC alarm. */ bool RTC_HAL_SetAlarm(uint32_t rtcBaseAddr, const rtc_datetime_t * date); #if FSL_FEATURE_RTC_HAS_MONOTONIC /*-------------------------------------------------------------------------------------------*/ /* RTC Monotonic Counter*/ /*-------------------------------------------------------------------------------------------*/ /*! * @brief Reads the values of the Monotonic Counter High and Monotonic Counter Low and returns * them as a single value. * * @param rtcBaseAddr The RTC base address * @param counter [out] pointer to variable where the value is stored. */ void RTC_HAL_GetMonotonicCounter(uint32_t rtcBaseAddr, uint64_t * counter); /*! * @brief Writes values Monotonic Counter High and Monotonic Counter Low by decomposing * the given single value. * * @param rtcBaseAddr The RTC base address * @param counter [in] pointer to variable where the value is stored. */ void RTC_HAL_SetMonotonicCounter(uint32_t rtcBaseAddr, const uint64_t * counter); /*! * @brief Increments the Monotonic Counter by one. * * Increments the Monotonic Counter (registers RTC_MCLR and RTC_MCHR accordingly) by setting * the monotonic counter enable (MER[MCE]) and then writing to the RTC_MCLR register. A write to the * monotonic counter low that causes it to overflow also increments the monotonic counter high. * * @param rtcBaseAddr The RTC base address * * @return true: success\n * false: error occurred, either time invalid or monotonic overflow flag was found */ bool RTC_HAL_IncrementMonotonicCounter(uint32_t rtcBaseAddr); #endif /*! @}*/ /*! * @name RTC register access functions * @{ */ /*! * @brief Reads the value of the time seconds counter. * * The time counter reads as zero if either the SR[TOF] or the SR[TIF] is set. * * @param rtcBaseAddr The RTC base address.. * * @return contents of the seconds register. */ static inline uint32_t RTC_HAL_GetSecsReg(uint32_t rtcBaseAddr) { return BR_RTC_TSR_TSR(rtcBaseAddr); } /*! * @brief Writes to the time seconds counter. * * When the time counter is enabled, the TSR is read only and increments * once every second provided the SR[TOF] or SR[TIF] is not set. When the time counter * is disabled, the TSR can be read or written. Writing to the TSR when the * time counter is disabled clears the SR[TOF] and/or the SR[TIF]. Writing * to the TSR register with zero is supported, but not recommended, since the TSR * reads as zero when either the SR[TIF] or the SR[TOF] is set (indicating the time is * invalid). * * @param rtcBaseAddr The RTC base address.. * @param seconds [in] seconds value. * */ static inline void RTC_HAL_SetSecsReg(uint32_t rtcBaseAddr, const uint32_t seconds) { HW_RTC_TPR_WR(rtcBaseAddr, (uint32_t)0x00000000U); BW_RTC_TSR_TSR(rtcBaseAddr, seconds); } /*! * @brief Sets the time alarm and clears the time alarm flag. * * When the time counter is enabled, the SR[TAF] is set whenever the TAR[TAR] * equals the TSR[TSR] and the TSR[TSR] increments. Writing to the TAR * clears the SR[TAF]. * * @param rtcBaseAddr The RTC base address.. * @param seconds [in] alarm value in seconds. */ static inline void RTC_HAL_SetAlarmReg(uint32_t rtcBaseAddr, const uint32_t seconds) { BW_RTC_TAR_TAR(rtcBaseAddr, seconds); } /*! * @brief Gets the time alarm register contents. * * @param rtcBaseAddr The RTC base address * * @return contents of the alarm register. */ static inline uint32_t RTC_HAL_GetAlarmReg(uint32_t rtcBaseAddr) { return BR_RTC_TAR_TAR(rtcBaseAddr); } /*! * @brief Reads the value of the time prescaler. * * The time counter reads as zero when either the SR[TOF] or the SR[TIF] is set. * * @param rtcBaseAddr The RTC base address * * @return contents of the time prescaler register. */ static inline uint16_t RTC_HAL_GetPrescaler(uint32_t rtcBaseAddr) { return BR_RTC_TPR_TPR(rtcBaseAddr); } /*! * @brief Sets the time prescaler. * * When the time counter is enabled, the TPR is read only and increments * every 32.768 kHz clock cycle. When the time counter is disabled, the TPR * can be read or written. The TSR[TSR] increments when bit 14 of the TPR * transitions from a logic one to a logic zero. * * @param rtcBaseAddr The RTC base address * @param prescale Prescaler value */ static inline void RTC_HAL_SetPrescaler(uint32_t rtcBaseAddr, const uint16_t prescale) { BW_RTC_TPR_TPR(rtcBaseAddr, prescale); } /*-------------------------------------------------------------------------------------------*/ /* RTC Time Compensation*/ /*-------------------------------------------------------------------------------------------*/ /*! * @brief Reads the time compensation register contents. * * @param rtcBaseAddr The RTC base address * * @return time compensation register contents. */ static inline uint32_t RTC_HAL_GetCompensationReg(uint32_t rtcBaseAddr) { return HW_RTC_TCR_RD(rtcBaseAddr); } /*! * @brief Writes the value to the RTC TCR register. * * @param rtcBaseAddr The RTC base address * @param compValue value to be written to the compensation register. */ static inline void RTC_HAL_SetCompensationReg(uint32_t rtcBaseAddr, const uint32_t compValue) { HW_RTC_TCR_WR(rtcBaseAddr, compValue); } /*! * @brief Reads the current value of the compensation interval counter, which is the field CIC in the RTC TCR register. * * @param rtcBaseAddr The RTC base address.. * * @return compensation interval value. */ static inline uint8_t RTC_HAL_GetCompensationIntervalCounter(uint32_t rtcBaseAddr) { return BR_RTC_TCR_CIC(rtcBaseAddr); } /*! * @brief Reads the current value used by the compensation logic for the present second interval. * * @param rtcBaseAddr The RTC base address * * @return time compensation value */ static inline uint8_t RTC_HAL_GetTimeCompensationValue(uint32_t rtcBaseAddr) { return BR_RTC_TCR_TCV(rtcBaseAddr); } /*! * @brief Reads the compensation interval register. * The value is the configured compensation interval in seconds from 1 to 256 to control * how frequently the time compensation register should adjust the * number of 32.768 kHz cycles in each second. The value is one * less than the number of seconds (for example, zero means a * configuration for a compensation interval of one second). * * @param rtcBaseAddr The RTC base address.. * * @return compensation interval in seconds. */ static inline uint8_t RTC_HAL_GetCompensationIntervalRegister(uint32_t rtcBaseAddr) { return BR_RTC_TCR_CIR(rtcBaseAddr); } /*! * @brief Writes the compensation interval. * * This configures the compensation interval in seconds from 1 to 256 to control * how frequently the TCR should adjust the number of 32.768 kHz * cycles in each second. The value written should be one less than * the number of seconds (for example, write zero to configure for * a compensation interval of one second). This register is double * buffered and writes do not take affect until the end of the * current compensation interval. * * @param rtcBaseAddr The RTC base address.. * @param value the compensation interval value. */ static inline void RTC_HAL_SetCompensationIntervalRegister(uint32_t rtcBaseAddr, const uint8_t value) { BW_RTC_TCR_CIR(rtcBaseAddr, value); } /*! * @brief Reads the time compensation value which is the configured number * of 32.768 kHz clock cycles in each second. * * @param rtcBaseAddr The RTC base address * * @return time compensation value. */ static inline uint8_t RTC_HAL_GetTimeCompensationRegister(uint32_t rtcBaseAddr) { return BR_RTC_TCR_TCR(rtcBaseAddr); } /*! * @brief Writes to the field Time Compensation Register (TCR) of the RTC Time Compensation Register (RTC_TCR). * * Configures the number of 32.768 kHz clock cycles in each second. This register is double * buffered and writes do not take affect until the end of the * current compensation interval. * 80h Time prescaler register overflows every 32896 clock cycles. * .. ...\n * FFh Time prescaler register overflows every 32769 clock cycles.\n * 00h Time prescaler register overflows every 32768 clock cycles.\n * 01h Time prescaler register overflows every 32767 clock cycles.\n * ... ...\n * 7Fh Time prescaler register overflows every 32641 clock cycles.\n * * @param rtcBaseAddr The RTC base address * @param comp_value value of the time compensation. */ static inline void RTC_HAL_SetTimeCompensationRegister(uint32_t rtcBaseAddr, const uint8_t compValue) { BW_RTC_TCR_TCR(rtcBaseAddr, compValue); } /*-------------------------------------------------------------------------------------------*/ /* RTC Control*/ /*-------------------------------------------------------------------------------------------*/ /*! * @brief Enables/disables the oscillator configuration for the 2pF load. * * @param rtcBaseAddr The RTC base address * @param enable can be true or false\n * true: enables load\n * false: disables load. */ static inline void RTC_HAL_SetOsc2pfLoadCmd(uint32_t rtcBaseAddr, bool enable) { BW_RTC_CR_SC2P(rtcBaseAddr, enable); } /*! * @brief Reads the oscillator 2pF load configure bit. * * @param rtcBaseAddr The RTC base address * * @return true: 2pF additional load enabled.\n * false: 2pF additional load disabled. */ static inline bool RTC_HAL_GetOsc2pfLoad(uint32_t rtcBaseAddr) { return (bool)BR_RTC_CR_SC2P(rtcBaseAddr); } /*! * @brief Enables/disables the oscillator configuration for the 4pF load. * * @param rtcBaseAddr The RTC base address * @param enable can be true or false\n * true: enables load.\n * false: disables load */ static inline void RTC_HAL_SetOsc4pfLoadCmd(uint32_t rtcBaseAddr, bool enable) { BW_RTC_CR_SC4P(rtcBaseAddr, enable); } /*! * @brief Reads the oscillator 4pF load configure bit. * * @param rtcBaseAddr The RTC base address * * @return true: 4pF additional load enabled.\n * false: 4pF additional load disabled. */ static inline bool RTC_HAL_GetOsc4pfLoad(uint32_t rtcBaseAddr) { return (bool)BR_RTC_CR_SC4P(rtcBaseAddr); } /*! * @brief Enables/disables the oscillator configuration for the 8pF load. * * @param rtcBaseAddr The RTC base address * @param enable can be true or false\n * true: enables load.\n * false: disables load. */ static inline void RTC_HAL_SetOsc8pfLoadCmd(uint32_t rtcBaseAddr, bool enable) { BW_RTC_CR_SC8P(rtcBaseAddr, enable); } /*! * @brief Reads the oscillator 8pF load configure bit. * * @param rtcBaseAddr The RTC base address * * @return true: 8pF additional load enabled.\n * false: 8pF additional load disabled. */ static inline bool RTC_HAL_GetOsc8pfLoad(uint32_t rtcBaseAddr) { return (bool)BR_RTC_CR_SC8P(rtcBaseAddr); } /*! * @brief Enables/disables the oscillator configuration for the 16pF load. * * @param rtcBaseAddr The RTC base address * @param enable can be true or false\n * true: enables load.\n * false: disables load. */ static inline void RTC_HAL_SetOsc16pfLoadCmd(uint32_t rtcBaseAddr, bool enable) { BW_RTC_CR_SC16P(rtcBaseAddr, enable); } /*! * @brief Reads the oscillator 16pF load configure bit. * * @param rtcBaseAddr The RTC base address * * @return true: 16pF additional load enabled.\n * false: 16pF additional load disabled. */ static inline bool RTC_HAL_GetOsc16pfLoad(uint32_t rtcBaseAddr) { return (bool)BR_RTC_CR_SC16P(rtcBaseAddr); } /*! * @brief Enables/disables the 32 kHz clock output to other peripherals. * * @param rtcBaseAddr The RTC base address * @param enable can be true or false\n * true: enables clock out.\n * false: disables clock out. */ static inline void RTC_HAL_SetClockOutCmd(uint32_t rtcBaseAddr, bool enable) { BW_RTC_CR_CLKO(rtcBaseAddr, !enable); } /*! * @brief Reads the RTC_CR CLKO bit. * * @param rtcBaseAddr The RTC base address * * @return true: 32 kHz clock is not output to other peripherals.\n * false: 32 kHz clock is output to other peripherals. */ static inline bool RTC_HAL_GetClockOutCmd(uint32_t rtcBaseAddr) { return (bool)BR_RTC_CR_CLKO(rtcBaseAddr); } /*! * @brief Enables/disables the oscillator. * * After enabling, waits for the oscillator startup time before enabling the * time counter to allow the 32.768 kHz clock time to stabilize. * * @param rtcBaseAddr The RTC base address * @param enable can be true or false\n * true: enables oscillator.\n * false: disables oscillator. */ static inline void RTC_HAL_SetOscillatorCmd(uint32_t rtcBaseAddr, bool enable) { BW_RTC_CR_OSCE(rtcBaseAddr, enable); /* TODO: Wait for oscillator startup period if enabling the oscillator if (enable) */ } /*! * @brief Reads the RTC_CR OSCE bit. * * @param rtcBaseAddr The RTC base address * * @return true: 32.768 kHz oscillator is enabled * false: 32.768 kHz oscillator is disabled. */ static inline bool RTC_HAL_IsOscillatorEnabled(uint32_t rtcBaseAddr) { return (bool)BR_RTC_CR_OSCE(rtcBaseAddr); } /*! * @brief Enables/disables the update mode. * * This mode allows the time counter enable bit in the SR to be written * even when the status register is locked. * When set, the time counter enable, can always be written if the * TIF (Time Invalid Flag) or TOF (Time Overflow Flag) are set or * if the time counter enable is clear. For devices with the * monotonic counter it allows the monotonic enable to be written * when it is locked. When set, the monotonic enable can always be * written if the TIF (Time Invalid Flag) or TOF (Time Overflow Flag) * are set or if the montonic counter enable is clear. * For devices with tamper detect it allows the it to be written * when it is locked. When set, the tamper detect can always be * written if the TIF (Time Invalid Flag) is clear. * Note: Tamper and Monotonic features are not available in all MCUs. * * @param rtcBaseAddr The RTC base address * @param lock can be true or false\n * true: registers can be written when locked under limited conditions\n * false: registers cannot be written when locked */ static inline void RTC_HAL_SetUpdateModeCmd(uint32_t rtcBaseAddr, bool lock) { BW_RTC_CR_UM(rtcBaseAddr, lock); } /*! * @brief Reads the RTC_CR update mode bit. * * @param rtcBaseAddr The RTC base address * * @return true: Registers can be written when locked under limited conditions. * false: Registers cannot be written when locked. */ static inline bool RTC_HAL_GetUpdateMode(uint32_t rtcBaseAddr) { return (bool)BR_RTC_CR_UM(rtcBaseAddr); } /*! * @brief Enables/disables the supervisor access. * * This configures non-supervisor mode write access to all RTC registers and * non-supervisor mode read access to RTC tamper/monotonic registers. * Note: Tamper and Monotonic features are NOT available in all MCUs. * * @param rtcBaseAddr The RTC base address.. * @param enableRegWrite can be true or false\n * true: non-supervisor mode write accesses are supported.\n * false: non-supervisor mode write accesses are not supported and generate a bus error. */ static inline void RTC_HAL_SetSupervisorAccessCmd(uint32_t rtcBaseAddr, bool enableRegWrite) { BW_RTC_CR_SUP(rtcBaseAddr, enableRegWrite); } /*! * @brief Reads the RTC_CR SUP bit. * * @param rtcBaseAddr The RTC base address * * @return true: Non-supervisor mode write accesses are supported * false: Non-supervisor mode write accesses are not supported. */ static inline bool RTC_HAL_GetSupervisorAccess(uint32_t rtcBaseAddr) { return (bool)BR_RTC_CR_SUP(rtcBaseAddr); } #if FSL_FEATURE_RTC_HAS_WAKEUP_PIN /*! * @brief Enables/disables the wakeup pin. * * Note: The wakeup pin is optional and not available on all devices. * * @param rtcBaseAddr The RTC base address * @param enable_wp can be true or false\n * true: enables wakeup-pin, wakeup pin asserts if the * RTC interrupt asserts and the chip is powered down.\n * false: disables wakeup-pin. */ static inline void RTC_HAL_SetWakeupPinCmd(uint32_t rtcBaseAddr, bool enableWp) { BW_RTC_CR_WPE(rtcBaseAddr, enableWp); } /*! * @brief Reads the RTC_CR WPE bit. * * @param rtcBaseAddr The RTC base address * * @return true: Wakeup pin is enabled. * false: Wakeup pin is disabled. */ static inline bool RTC_HAL_GetWakeupPin(uint32_t rtcBaseAddr) { return (bool)BR_RTC_CR_WPE(rtcBaseAddr); } #endif /*! * @brief Performs a software reset on the RTC module. * * This resets all RTC registers except for the SWR bit and the RTC_WAR and RTC_RAR * registers. The SWR bit is cleared after VBAT POR and by software * explicitly clearing it. * Note: access control features (RTC_WAR and RTC_RAR registers) * are not available in all MCUs. * * @param rtcBaseAddr The RTC base address */ static inline void RTC_HAL_SoftwareReset(uint32_t rtcBaseAddr) { BW_RTC_CR_SWR(rtcBaseAddr, 1u); } /*! * @brief Clears the software reset flag. * * @param rtcBaseAddr The RTC base address */ static inline void RTC_HAL_SoftwareResetFlagClear(uint32_t rtcBaseAddr) { BW_RTC_CR_SWR(rtcBaseAddr, 0u); } /*! * @brief Reads the RTC_CR SWR bit. * * @param rtcBaseAddr The RTC base address * * @return true: SWR is set. * false: SWR is cleared. */ static inline bool RTC_HAL_ReadSoftwareResetStatus(uint32_t rtcBaseAddr) { return (bool)BR_RTC_CR_SWR(rtcBaseAddr); } /*-------------------------------------------------------------------------------------------*/ /* RTC Status*/ /*-------------------------------------------------------------------------------------------*/ /*! * @brief Reads the time counter status (enabled/disabled). * * @param rtcBaseAddr The RTC base address * * @return true: time counter is enabled, time seconds register and time * prescaler register are not writeable, but increment.\n * false: time counter is disabled, time seconds register and * time prescaler register are writeable, but do not increment. */ static inline bool RTC_HAL_IsCounterEnabled(uint32_t rtcBaseAddr) { return (bool)BR_RTC_SR_TCE(rtcBaseAddr); } /*! * @brief Changes the time counter status. * * @param rtcBaseAddr The RTC base address * @param enable can be true or false\n * true: enables the time counter\n * false: disables the time counter. */ static inline void RTC_HAL_EnableCounter(uint32_t rtcBaseAddr, bool enable) { BW_RTC_SR_TCE(rtcBaseAddr, enable); } #if FSL_FEATURE_RTC_HAS_MONOTONIC /*! * @brief Reads the value of the Monotonic Overflow Flag (MOF). * * This flag is set when the monotonic counter is enabled and the monotonic * counter high overflows. The monotonic counter does not increment and * reads as zero when this bit is set. This bit is cleared by writing the monotonic * counter high register when the monotonic counter is disabled. * * @param rtcBaseAddr The RTC base address.. * * @return true: monotonic counter overflow has occurred and monotonic * counter is read as zero.\n * false: No monotonic counter overflow has occurred. */ static inline bool RTC_HAL_IsMonotonicCounterOverflow(uint32_t rtcBaseAddr) { return (bool)BR_RTC_SR_MOF(rtcBaseAddr); } #endif /*! * @brief Checks whether the configured time alarm has occurred. * * Reads time alarm flag (TAF). This flag is set when the time * alarm register (TAR) equals the time seconds register (TSR) and * the TSR increments. This flag is cleared by writing the TAR register. * * @param rtcBaseAddr The RTC base address.. * * @return true: time alarm has occurred.\n * false: no time alarm occurred. */ static inline bool RTC_HAL_HasAlarmOccured(uint32_t rtcBaseAddr) { return (bool)BR_RTC_SR_TAF(rtcBaseAddr); } /*! * @brief Checks whether a counter overflow has occurred. * * Reads the value of RTC Status Register (RTC_SR), field Time * Overflow Flag (TOF). This flag is set when the time counter is * enabled and overflows. The TSR and TPR do not increment and read * as zero when this bit is set. This flag is cleared by writing the * TSR register when the time counter is disabled. * * @param rtcBaseAddr The RTC base address.. * * @return true: time overflow occurred and time counter is zero.\n * false: no time overflow occurred. */ static inline bool RTC_HAL_HasCounterOverflowed(uint32_t rtcBaseAddr) { return (bool)BR_RTC_SR_TOF(rtcBaseAddr); } /*! * @brief Checks whether the time has been marked as invalid. * * Reads the value of RTC Status Register (RTC_SR), field Time * Invalid Flag (TIF). This flag is set on VBAT POR or software * reset. The TSR and TPR do not increment and read as zero when * this bit is set. This flag is cleared by writing the TSR * register when the time counter is disabled. * * @param rtcBaseAddr The RTC base address.. * * @return true: time is INVALID and time counter is zero.\n * false: time is valid. */ static inline bool RTC_HAL_IsTimeInvalid(uint32_t rtcBaseAddr) { return (bool)BR_RTC_SR_TIF(rtcBaseAddr); } /*-------------------------------------------------------------------------------------------*/ /* RTC Lock*/ /*-------------------------------------------------------------------------------------------*/ /*! * @brief Configures the register lock to other module fields. * * @param rtcBaseAddr The RTC base address.. * @param bitfields [in] configuration flags:\n * Valid bitfields:\n * LRL: Lock Register Lock \n * SRL: Status Register Lock \n * CRL: Control Register Lock \n * TCL: Time Compensation Lock \n * * For MCUs that have the Tamper Detect only: \n * TIL: Tamper Interrupt Lock \n * TTL: Tamper Trim Lock \n * TDL: Tamper Detect Lock \n * TEL: Tamper Enable Lock \n * TTSL: Tamper Time Seconds Lock \n * * For MCUs that have the Monotonic Counter only: \n * MCHL: Monotonic Counter High Lock \n * MCLL: Monotonic Counter Low Lock \n * MEL: Monotonic Enable Lock \n */ static inline void RTC_HAL_SetLockRegistersCmd(uint32_t rtcBaseAddr, hw_rtc_lr_t bitfields) { uint32_t valid_flags = 0; valid_flags |= (BM_RTC_LR_LRL | BM_RTC_LR_SRL | BM_RTC_LR_CRL | BM_RTC_LR_TCL); #if FSL_FEATURE_RTC_HAS_MONOTONIC valid_flags |= (BM_RTC_LR_MCHL | BM_RTC_LR_MCLL | BM_RTC_LR_MEL); #endif HW_RTC_LR_WR(rtcBaseAddr, (bitfields.U) & valid_flags); } /*! * @brief Obtains the lock status of the lock register. * * Reads the value of the field Lock Register Lock (LRL) of the RTC Lock Register (RTC_LR). * * @param rtcBaseAddr The RTC base address * * @return true: lock register is not locked and writes complete as normal.\n * false: lock register is locked and writes are ignored. */ static inline bool RTC_HAL_GetLockRegLock(uint32_t rtcBaseAddr) { return (bool)BR_RTC_LR_LRL(rtcBaseAddr); } /*! * @brief Changes the lock status of the lock register. * * Writes to the field Lock Register Lock (LRL) of the RTC Lock Register (RTC_LR). * Once cleared, this can only be set by VBAT POR or software reset. * * @param rtcBaseAddr The RTC base address * @param lock can be true or false\n * true: Lock register is not locked and writes complete as normal.\n * false: Lock register is locked and writes are ignored. */ static inline void RTC_HAL_SetLockRegLock(uint32_t rtcBaseAddr, bool lock) { BW_RTC_LR_LRL(rtcBaseAddr, (uint32_t) lock); } /*! * @brief Obtains the state of the status register lock. * * Reads the value of field Status Register Lock (SRL) of the RTC Lock Register (RTC_LR), which is the field Status Register. * * @param rtcBaseAddr The RTC base address * * @return true: Status register is not locked and writes complete as * normal.\n * false: Status register is locked and writes are ignored. */ static inline bool RTC_HAL_GetStatusRegLock(uint32_t rtcBaseAddr) { return (bool)BR_RTC_LR_SRL(rtcBaseAddr); } /*! * @brief Changes the state of the status register lock. * * Writes to the field Status Register Lock (SRL) of the RTC Lock Register (RTC_LR). * Once cleared, this can only be set by VBAT POR or software reset. * * @param rtcBaseAddr The RTC base address * @param lock can be true or false\n * true: Status register is not locked and writes complete as * normal.\n * false: Status register is locked and writes are ignored. */ static inline void RTC_HAL_SetStatusRegLock(uint32_t rtcBaseAddr, bool lock) { BW_RTC_LR_SRL(rtcBaseAddr, (uint32_t) lock); } /*! * @brief Obtains the state of the control register lock. * * Reads the field Control Register Lock (CRL)value of the RTC Lock Register (RTC_LR). * * @param rtcBaseAddr The RTC base address * * @return true: Control register is not locked and writes complete as * normal.\n * false: Control register is locked and writes are ignored. */ static inline bool RTC_HAL_GetControlRegLock(uint32_t rtcBaseAddr) { return (bool)BR_RTC_LR_CRL(rtcBaseAddr); } /*! * @brief Changes the state of the control register lock. * * Writes to the field Control Register Lock (CRL) of the RTC Lock Register (RTC_LR). * Once cleared, this can only be set by VBAT POR or software reset. * * @param rtcBaseAddr The RTC base address * @param lock can be true or false\n * true: Control register is not locked and writes complete * as normal.\n * false: Control register is locked and writes are ignored. */ static inline void RTC_HAL_SetControlRegLock(uint32_t rtcBaseAddr, bool lock) { BW_RTC_LR_CRL(rtcBaseAddr, (uint32_t) lock); } /*! * @brief Obtains the state of the time compensation lock. * * Reads the field Time Compensation Lock (TCL) value of the RTC Lock Register (RTC_LR). * * @param rtcBaseAddr The RTC base address * * @return true: Time compensation register is not locked and writes * complete as normal.\n * false: Time compensation register is locked and writes are * ignored. */ static inline bool RTC_HAL_GetTimeCompLock(uint32_t rtcBaseAddr) { return (bool)BR_RTC_LR_TCL(rtcBaseAddr); } /*! * @brief Changes the state of the time compensation lock. * * Writes to the field Time Compensation Lock (TCL) of the RTC Lock Register (RTC_LR). * Once cleared, this can only be set by VBAT POR or software reset. * * @param rtcBaseAddr The RTC base address * @param lock can be true or false\n * true: Time compensation register is not locked and writes * complete as normal.\n * false: Time compensation register is locked and writes are * ignored. */ static inline void RTC_HAL_SetTimeCompLock(uint32_t rtcBaseAddr, bool lock) { BW_RTC_LR_TCL(rtcBaseAddr, (uint32_t) lock); } #if FSL_FEATURE_RTC_HAS_MONOTONIC /*! * @brief Reads the value of the Monotonic Counter High Lock. * * @param rtcBaseAddr The RTC base address * * @return true: Monotonic counter high register is not locked and writes * complete as normal.\n * false: Monotonic counter high register is locked and writes are * ignored. */ static inline bool RTC_HAL_ReadMonotonicHcounterLock(uint32_t rtcBaseAddr) { return (bool)BR_RTC_LR_MCHL(rtcBaseAddr); } /*! * @brief Writes 0 to the field Monotonic Counter High Lock (MCHL) of the RTC Lock Register (RTC_LR). * * Once done, this flag can only be set by VBAT POR or software reset. * * @param rtcBaseAddr The RTC base address */ static inline void RTC_HAL_ClearMonotonicHcounterLock(uint32_t rtcBaseAddr) { BW_RTC_LR_MCHL(rtcBaseAddr, 0U); } /*! * @brief Reads the value of the Monotonic Counter Low Lock. * * @param rtcBaseAddr The RTC base address * * @return true: Monotonic counter low register is not locked and writes * complete as normal.\n * false: Monotonic counter low register is locked and writes are * ignored. */ static inline bool RTC_HAL_ReadMonotonicLcounterLock(uint32_t rtcBaseAddr) { return (bool)BR_RTC_LR_MCLL(rtcBaseAddr); } /*! * @brief Writes 0 to the field Monotonic Counter Low Lock (MCLL) of the RTC Lock Register (RTC_LR). * * Once done, this flag can only be set by VBAT POR or software reset. * * @param rtcBaseAddr The RTC base address */ static inline void RTC_HAL_ClearMonotonicLcounterLock(uint32_t rtcBaseAddr) { BW_RTC_LR_MCLL(rtcBaseAddr, 0U); } /*! * @brief Reads the value of the Monotonic Enable Lock. * * @param rtcBaseAddr The RTC base address * * @return true: Monotonic enable register is not locked and writes * complete as normal.\n * false: Monotonic enable register is locked and writes are * ignored. */ static inline bool RTC_HAL_ReadMonotonicEnableLock(uint32_t rtcBaseAddr) { return (bool)BR_RTC_LR_MEL(rtcBaseAddr); } /*! * @brief Writes 0 to the Monotonic Enable Lock field of the RTC Lock Register (RTC_LR). * * Once done, this flag can only be set by VBAT POR or software reset. * * @param rtcBaseAddr The RTC base address */ static inline void RTC_HAL_ClearMonotonicEnableLock(uint32_t rtcBaseAddr) { BW_RTC_LR_MEL(rtcBaseAddr, 0U); } #endif /*-------------------------------------------------------------------------------------------*/ /* RTC Interrupt Enable*/ /*-------------------------------------------------------------------------------------------*/ /*! * @brief Checks whether the Time Seconds Interrupt is enabled/disabled. * * Reads the value of field Time Seconds Interrupt Enable (TSIE)of the RTC Interrupt Enable Register (RTC_IER). * The seconds interrupt is an edge-sensitive * interrupt with a dedicated interrupt vector. It is generated once a second * and requires no software overhead (there is no corresponding status flag to * clear). * * @param rtcBaseAddr The RTC base address * * @return true: Seconds interrupt is enabled.\n * false: Seconds interrupt is disabled. */ static inline bool RTC_HAL_IsSecsIntEnabled(uint32_t rtcBaseAddr) { return (bool)BR_RTC_IER_TSIE(rtcBaseAddr); } /*! * @brief Enables/disables the Time Seconds Interrupt. * * Writes to the field Time Seconds * Interrupt Enable (TSIE) of the RTC Interrupt Enable Register (RTC_IER). * Note: The seconds interrupt is an edge-sensitive interrupt with a * dedicated interrupt vector. It is generated once a second and * requires no software overhead (there is no corresponding status * flag to clear). * * @param rtcBaseAddr The RTC base address * @param enable can be true or false\n * true: Seconds interrupt is enabled.\n * false: Seconds interrupt is disabled. */ static inline void RTC_HAL_SetSecsIntCmd(uint32_t rtcBaseAddr, bool enable) { BW_RTC_IER_TSIE(rtcBaseAddr, (uint32_t) enable); } #if FSL_FEATURE_RTC_HAS_MONOTONIC /*! * @brief Checks whether the Monotonic Overflow Interrupt is enabled/disabled. * * Reads the value of the RTC Interrupt Enable Register (RTC_IER), field * Monotonic Overflow Interrupt Enable (MOIE). * * @param rtcBaseAddr The RTC base address * * @return true: Monotonic overflow flag does generate an interrupt.\n * false: Monotonic overflow flag does not generate an interrupt. */ static inline bool RTC_HAL_ReadMonotonicOverflowInt(uint32_t rtcBaseAddr) { return (bool)BR_RTC_IER_MOIE(rtcBaseAddr); } /*! * @brief Enables/disables the Monotonic Overflow Interrupt Enable. * * @param rtcBaseAddr The RTC base address * @param enable can be true or false\n * true: Monotonic overflow flag does generate an interrupt.\n * false: Monotonic overflow flag does not generate an interrupt. */ static inline void RTC_HAL_SetMonotonicOverflowIntCmd(uint32_t rtcBaseAddr, bool enable) { BW_RTC_IER_MOIE(rtcBaseAddr, (uint32_t)enable); } #endif /*! * @brief Checks whether the Time Alarm Interrupt is enabled/disabled. * * Reads the field Time Alarm Interrupt Enable (TAIE) value of the RTC Interrupt Enable Register (RTC_IER). * * @param rtcBaseAddr The RTC base address * * @return true: Time alarm flag does generate an interrupt.\n * false: Time alarm flag does not generate an interrupt. */ static inline bool RTC_HAL_ReadAlarmInt(uint32_t rtcBaseAddr) { return (bool)BR_RTC_IER_TAIE(rtcBaseAddr); } /*! * @brief Enables/disables the Time Alarm Interrupt. * * Writes to the field Time Alarm * Interrupt Enable (TAIE) of the RTC Interrupt Enable Register (RTC_IER). * * @param rtcBaseAddr The RTC base address * @param enable can be true or false\n * true: Time alarm flag does generate an interrupt.\n * false: Time alarm flag does not generate an interrupt. */ static inline void RTC_HAL_SetAlarmIntCmd(uint32_t rtcBaseAddr, bool enable) { BW_RTC_IER_TAIE(rtcBaseAddr, (uint32_t) enable); } /*! * @brief Checks whether the Time Overflow Interrupt is enabled/disabled. * * Reads the field * Time Overflow Interrupt Enable (TOIE) of the value of the RTC Interrupt Enable Register (RTC_IER). * * @param rtcBaseAddr The RTC base address.. * * @return true: Time overflow flag does generate an interrupt.\n * false: Time overflow flag does not generate an interrupt. */ static inline bool RTC_HAL_ReadTimeOverflowInt(uint32_t rtcBaseAddr) { return (bool)BR_RTC_IER_TOIE(rtcBaseAddr); } /*! * @brief Enables/disables the Time Overflow Interrupt. * * Writes to the field Time Overflow Interrupt Enable (TOIE) of the RTC Interrupt Enable Register (RTC_IER). * * @param rtcBaseAddr The RTC base address * @param enable can be true or false\n * true: Time overflow flag does generate an interrupt.\n * false: Time overflow flag does not generate an interrupt. */ static inline void RTC_HAL_SetTimeOverflowIntCmd(uint32_t rtcBaseAddr, bool enable) { BW_RTC_IER_TOIE(rtcBaseAddr, (uint32_t) enable); } /*! * @brief Checks whether the Time Invalid Interrupt is enabled/disabled. * * Reads the value of the field Time * Invalid Interrupt Enable (TIIE)of the RTC Interrupt Enable Register (RTC_IER). * * @param rtcBaseAddr The RTC base address * * @return true: Time invalid flag does generate an interrupt.\n * false: Time invalid flag does not generate an interrupt. */ static inline bool RTC_HAL_ReadTimeInvalidInt(uint32_t rtcBaseAddr) { return (bool)BR_RTC_IER_TIIE(rtcBaseAddr); } /*! * @brief Enables/disables the Time Invalid Interrupt. * * Writes to the field Time Invalid * Interrupt Enable (TIIE) of the RTC Interrupt Enable Register (RTC_IER). * * @param rtcBaseAddr The RTC base address * @param enable can be true or false\n * true: Time invalid flag does generate an interrupt.\n * false: Time invalid flag does not generate an interrupt. */ static inline void RTC_HAL_SetTimeInvalidIntCmd(uint32_t rtcBaseAddr, bool enable) { BW_RTC_IER_TIIE(rtcBaseAddr, (uint32_t) enable); } #if FSL_FEATURE_RTC_HAS_MONOTONIC /*-------------------------------------------------------------------------------------------*/ /* RTC Monotonic Enable*/ /*-------------------------------------------------------------------------------------------*/ /*! * @brief Reads the Monotonic Counter Enable bit. * * @param rtcBaseAddr The RTC base address * * @return true: This means writing to the monotonic counter increments the counter by one and * the value written is ignored.\n * false: This means writing to the monotonic counter loads the counter with the * value written. */ static inline bool RTC_HAL_ReadMonotonicEnable(uint32_t rtcBaseAddr) { /* Reads value of the RTC_MER register, field Monotonic Counter Enable (MCE). */ return (bool)BR_RTC_MER_MCE(rtcBaseAddr); } /*! * @brief Changes the state of Monotonic Counter Enable bit. * * @param rtcBaseAddr The RTC base address * @param enable value to be written to the MER[MCE] bit\n * true: Set the bit to 1 which means writing to the monotonic counter will increment * the counter by one and the value written will be ignored.\n * false: Set the bit to 0 which means writing to the monotonic counter loads the counter * with the value written. */ static inline void RTC_HAL_SetMonotonicEnableCmd(uint32_t rtcBaseAddr, bool enable) { /* Writes to the RTC_MER registers Monotonic Counter Enable (MCE) bit.*/ BW_RTC_MER_MCE(rtcBaseAddr, (uint32_t) enable); } /*! * @brief Reads the values of the Monotonic Counter Low register. * * @param rtcBaseAddr The RTC base address * * @return Monotonic Counter Low value. */ static inline uint32_t RTC_HAL_GetMonotonicCounterLow(uint32_t rtcBaseAddr) { return BR_RTC_MCLR_MCL(rtcBaseAddr); } /*! * @brief Reads the values of the Monotonic Counter High register. * * @param rtcBaseAddr The RTC base address * * @return Monotonic Counter High value. */ static inline uint32_t RTC_HAL_GetMonotonicCounterHigh(uint32_t rtcBaseAddr) { return BR_RTC_MCHR_MCH(rtcBaseAddr); } /*! * @brief Writes values of the Monotonic Counter Low register. * * @param rtcBaseAddr The RTC base address * @param counter [in] Monotonic Counter Low value to be stored. */ static inline void RTC_HAL_SetMonotonicCounterLow(uint32_t rtcBaseAddr, const uint32_t counter) { /* enable writing to the counter*/ BW_RTC_MER_MCE(rtcBaseAddr, 0U); BW_RTC_MCLR_MCL(rtcBaseAddr, counter); } /*! * @brief Writes values of the Monotonic Counter High register. * * @param rtcBaseAddr The RTC base address * @param counter [in] Monotonic Counter High value to be stored. */ static inline void RTC_HAL_SetMonotonicCounterHigh(uint32_t rtcBaseAddr, const uint32_t counter) { /* enable writing to the counter*/ BW_RTC_MER_MCE(rtcBaseAddr, 0U); BW_RTC_MCHR_MCH(rtcBaseAddr, counter); } #endif /* FSL_FEATURE_RTC_HAS_MONOTONIC */ #if FSL_FEATURE_RTC_HAS_ACCESS_CONTROL #if FSL_FEATURE_RTC_HAS_MONOTONIC /*! * @brief Reads the field Monotonic Counter High Write (MCHW) value of the register RTC_WAR. * * @param rtcBaseAddr The RTC base address * * @return true: Writes to the monotonic counter high register will complete as normal.\n * false: Writes to the monotonic counter high register are ignored. */ static inline bool RTC_HAL_GetMonotonicHcountWreg(uint32_t rtcBaseAddr) { return (bool)BR_RTC_WAR_MCHW(rtcBaseAddr); } /*! * @brief Writes 0 to the field Monotonic Counter High Write (MCHW) of the RTC_WAR register. * * Once cleared, this bit is only set by system reset. It is not affected by * VBAT POR or software reset. * * @param rtcBaseAddr The RTC base address */ static inline void RTC_HAL_ClearMonotonicHcountWreg(uint32_t rtcBaseAddr) { BW_RTC_WAR_MCHW(rtcBaseAddr, 0U); } /*! * @brief Reads the field Monotonic Counter Low Write (MCLW) value of the register RTC_WAR. * * @param rtcBaseAddr The RTC base address * * @return true: Writes to the monotonic counter low register will complete as normal.\n * false: Writes to the monotonic counter low register are ignored. */ static inline bool RTC_HAL_GetMonotonicLcountWreg(uint32_t rtcBaseAddr) { return (bool)BR_RTC_WAR_MCLW(rtcBaseAddr); } /*! * @brief Writes 0 to the field Monotonic Counter High Write (MCLW) of the RTC_WAR register. * * Once cleared, this bit is only set by the system reset. It is not affected by * VBAT POR or software reset. * * @param rtcBaseAddr The RTC base address.. */ static inline void RTC_HAL_ClearMonotonicLcountWreg(uint32_t rtcBaseAddr) { BW_RTC_WAR_MCLW(rtcBaseAddr, 0U); } /*! * @brief Reads the field Monotonic Enable Register Write (MERW) value of the register RTC_WAR. * * @param rtcBaseAddr The RTC base address * * @return true: Writes to the monotonic enable register will complete as normal.\n * false: Writes to the monotonic enable register are ignored. */ static inline bool RTC_HAL_GetMonotonicEnableWreg(uint32_t rtcBaseAddr) { return (bool)BR_RTC_WAR_MERW(rtcBaseAddr); } /*! * @brief Writes 0 to the field Monotonic Counter High Write (MERW) of the RTC_WAR register. * * Once cleared, this bit is only set by system reset. It is not affected by * VBAT POR or software reset. * * @param rtcBaseAddr The RTC base address */ static inline void RTC_HAL_ClearMonotonicEnableWreg(uint32_t rtcBaseAddr) { BW_RTC_WAR_MERW(rtcBaseAddr, 0U); } #endif /*! * @brief Reads the field Interrupt Enable Register Write (IERW) value of the register RTC_WAR. * * @param rtcBaseAddr The RTC base address * * @return true: Writes to the interrupt enable register will complete as normal.\n * false: Writes to the interrupt enable register are ignored. */ static inline bool RTC_HAL_GetIntEnableWreg(uint32_t rtcBaseAddr) { return (bool)BR_RTC_WAR_IERW(rtcBaseAddr); } /*! * @brief Writes 0 to the field Interrupt Enable Register Write (IERW) of the RTC_WAR register. * * Once cleared, this bit is only set by system reset. It is not affected by * VBAT POR or software reset. * * @param rtcBaseAddr The RTC base address */ static inline void RTC_HAL_ClearIntEnableWreg(uint32_t rtcBaseAddr) { BW_RTC_WAR_IERW(rtcBaseAddr, 0U); } /*! * @brief Reads the field Lock Register Write (LRW) value of the register RTC_WAR. * * @param rtcBaseAddr The RTC base address * * @return true: Writes to the lock register will complete as normal.\n * false: Writes to the lock register are ignored. */ static inline bool RTC_HAL_GetLockWreg(uint32_t rtcBaseAddr) { return (bool)BR_RTC_WAR_LRW(rtcBaseAddr); } /*! * @brief Writes 0 to the field Lock Register Write (LRW) of the RTC_WAR register. * * Once cleared, this bit is only set by system reset. It is not affected by * VBAT POR or software reset. * * @param rtcBaseAddr The RTC base address */ static inline void RTC_HAL_ClearLockWreg(uint32_t rtcBaseAddr) { BW_RTC_WAR_LRW(rtcBaseAddr, 0U); } /*! * @brief Reads the field Status Register Write (SRW) value of the register RTC_WAR. * * @param rtcBaseAddr The RTC base address * * @return true: Writes to the status register completes as normal.\n * false: Writes to the status register are ignored. */ static inline bool RTC_HAL_GetStatusWreg(uint32_t rtcBaseAddr) { return (bool)BR_RTC_WAR_SRW(rtcBaseAddr); } /*! * @brief Writes 0 to the field Status Register Write (SRW) of the RTC_WAR register. * * Once cleared, this bit is only set by system reset. It is not affected by * VBAT POR or software reset. * * @param rtcBaseAddr The RTC base address */ static inline void RTC_HAL_ClearStatusWreg(uint32_t rtcBaseAddr) { BW_RTC_WAR_SRW(rtcBaseAddr, 0U); } /*! * @brief Reads the field Control Register Write (CRW) value of the register RTC_WAR. * * @param rtcBaseAddr The RTC base address * * @return true: Writes to the control register will complete as normal.\n * false: Writes to the control register are ignored. */ static inline bool RTC_HAL_GetControlWreg(uint32_t rtcBaseAddr) { return (bool)BR_RTC_WAR_CRW(rtcBaseAddr); } /*! * @brief Writes 0 to the field Control Register Write (CRW) of the RTC_WAR register. * * Once cleared, this bit is only set by system reset. It is not affected by * VBAT POR or software reset. * * @param rtcBaseAddr The RTC base address */ static inline void RTC_HAL_ClearControlWreg(uint32_t rtcBaseAddr) { BW_RTC_WAR_CRW(rtcBaseAddr, 0U); } /*! * @brief Reads the field Time Compensation Register Write (TCRW) value of the register RTC_WAR. * * @param rtcBaseAddr The RTC base address * * @return true: Writes to the time compensation register will complete as normal.\n * false: Writes to the time compensation register are ignored. */ static inline bool RTC_HAL_GetCompensationWreg(uint32_t rtcBaseAddr) { return (bool)BR_RTC_WAR_TCRW(rtcBaseAddr); } /*! * @brief Writes 0 to the field Time Compensation Register Write (TCRW) of the RTC_WAR register. * * Once cleared, this bit is only set by system reset. It is not affected by * VBAT POR or software reset. * * @param rtcBaseAddr The RTC base address */ static inline void RTC_HAL_ClearCompensationWreg(uint32_t rtcBaseAddr) { BW_RTC_WAR_TCRW(rtcBaseAddr, 0U); } /*! * @brief Reads the field Time Alarm Register Write (TARW) value of the register RTC_WAR. * * @param rtcBaseAddr The RTC base address * * @return true: Writes to the time alarm register will complete as normal.\n * false: Writes to the time alarm register are ignored. */ static inline bool RTC_HAL_GetAlarmWreg(uint32_t rtcBaseAddr) { return (bool)BR_RTC_WAR_TARW(rtcBaseAddr); } /*! * @brief Writes 0 to the field Time Alarm Register Write (TARW) of the RTC_WAR register. * * Once cleared, this bit is only set by system reset. It is not affected by * VBAT POR or software reset. * * @param rtcBaseAddr The RTC base address */ static inline void RTC_HAL_ClearAlarmWreg(uint32_t rtcBaseAddr) { BW_RTC_WAR_TARW(rtcBaseAddr, 0U); } /*! * @brief Reads the field Time Prescaler Register Write (TPRW) value of the register RTC_WAR. * * @param rtcBaseAddr The RTC base address * * @return true: Writes to the time prescaler register will complete as normal.\n * false: Writes to the time prescaler register are ignored. */ static inline bool RTC_HAL_GetPrescalerWreg(uint32_t rtcBaseAddr) { return (bool)BR_RTC_WAR_TPRW(rtcBaseAddr); } /*! * @brief Writes 0 to the field Time Prescaler Register Write (TPRW) of the RTC_WAR register. * * Once cleared, this bit is only set by system reset. It is not affected by * VBAT POR or software reset. * * @param rtcBaseAddr The RTC base address */ static inline void RTC_HAL_ClearPrescalerWreg(uint32_t rtcBaseAddr) { BW_RTC_WAR_TPRW(rtcBaseAddr, 0U); } /*! * @brief Reads the field Time Seconds Register Write (TSRW) value of the register RTC_WAR. * * @param rtcBaseAddr The RTC base address * * @return true: Writes to the time seconds register will complete as normal.\n * false: Writes to the time seconds register are ignored. */ static inline bool RTC_HAL_GetSecsWreg(uint32_t rtcBaseAddr) { return (bool)BR_RTC_WAR_TSRW(rtcBaseAddr); } /*! * @brief Writes 0 to the field Time Seconds Register Write (TSRW) of the RTC_WAR register. * * Once cleared, this bit is only set by system reset. It is not affected by * VBAT POR or software reset. * * @param rtcBaseAddr The RTC base address */ static inline void RTC_HAL_ClearSecsWreg(uint32_t rtcBaseAddr) { BW_RTC_WAR_TSRW(rtcBaseAddr, 0U); } #if FSL_FEATURE_RTC_HAS_MONOTONIC /*! * @brief Reads the field Monotonic Counter High Read (MCHR) value of the register RTC_RAR. * * @param rtcBaseAddr The RTC base address * * @return true: Reads to the monotonic counter high register completes as normal.\n * false: Reads to the monotonic counter high register are ignored. */ static inline bool RTC_HAL_GetMonotonicHcountRreg(uint32_t rtcBaseAddr) { return (bool)BR_RTC_RAR_MCHR(rtcBaseAddr); } /*! * @brief Writes 0 to the field Monotonic Counter High Read (MCHR) of the RTC_RAR register. * * Once cleared, this bit is only set by system reset. It is not affected by * VBAT POR or software reset. * * @param rtcBaseAddr The RTC base address */ static inline void RTC_HAL_ClearMonotonicHcountRreg(uint32_t rtcBaseAddr) { BW_RTC_RAR_MCHR(rtcBaseAddr, 0U); } /*! * @brief Reads the field Monotonic Counter Low Read (MCLR) value of the register RTC_RAR. * * @param rtcBaseAddr The RTC base address * * @return true: Reads to the monotonic counter low register will complete as normal.\n * false: Reads to the monotonic counter low register are ignored. */ static inline bool RTC_HAL_GetMonotonicLcountRreg(uint32_t rtcBaseAddr) { return (bool)BR_RTC_RAR_MCLR(rtcBaseAddr); } /*! * @brief Writes 0 to the field Monotonic Counter Low Read (MCLR) of the RTC_RAR register. * * Once cleared, this bit is only set by system reset. It is not affected by * VBAT POR or software reset. * * @param rtcBaseAddr The RTC base address */ static inline void RTC_HAL_ClearMonotonicLcountRreg(uint32_t rtcBaseAddr) { BW_RTC_RAR_MCLR(rtcBaseAddr, 0U); } /*! * @brief Reads the field Monotonic Enable Register Read (MERR) value of the register RTC_RAR. * * @param rtcBaseAddr The RTC base address * * @return true: Reads to the monotonic enable register completes as normal.\n * false: Reads to the monotonic enable register are ignored. */ static inline bool RTC_HAL_GetMonotonicEnableRreg(uint32_t rtcBaseAddr) { return (bool)BR_RTC_RAR_MERR(rtcBaseAddr); } /*! * @brief Writes 0 to the field Monotonic Enable Register Read (MERR) of the RTC_RAR register. * * Once cleared, this bit is only set by system reset. It is not affected by * VBAT POR or software reset. * * @param rtcBaseAddr The RTC base address */ static inline void RTC_HAL_ClearMonotonicEnableRreg(uint32_t rtcBaseAddr) { BW_RTC_RAR_MERR(rtcBaseAddr, 0U); } #endif /*! * @brief Reads the field Interrupt Enable Register Read (IERR) value of the register RTC_RAR. * * @param rtcBaseAddr The RTC base address * * @return true: Reads to the interrupt enable register completes as normal.\n * false: Reads to the interrupt enable register are ignored. */ static inline bool RTC_HAL_GetIntEnableRreg(uint32_t rtcBaseAddr) { return (bool)BR_RTC_RAR_IERR(rtcBaseAddr); } /*! * @brief Writes 0 to the field Interrupt Enable Register Read (IERR) of the RTC_RAR register. * * Once cleared, this bit is only set by system reset. It is not affected by * VBAT POR or software reset. * * @param rtcBaseAddr The RTC base address */ static inline void RTC_HAL_ClearIntEnableRreg(uint32_t rtcBaseAddr) { BW_RTC_RAR_IERR(rtcBaseAddr, 0U); } /*! * @brief Reads the field Lock Register Read (LRR) value of the RTC_RAR register. * * @param rtcBaseAddr The RTC base address * * @return true: Reads to the lock register will complete as normal.\n * false: Reads to the lock register are ignored. */ static inline bool RTC_HAL_GetLockRreg(uint32_t rtcBaseAddr) { return (bool)BR_RTC_RAR_LRR(rtcBaseAddr); } /*! * @brief Writes 0 to the field Lock Register Read (LRR) of the RTC_RAR register. * * Once cleared, this bit is only set by system reset. It is not affected by * VBAT POR or software reset. * * @param rtcBaseAddr The RTC base address */ static inline void RTC_HAL_ClearLockRreg(uint32_t rtcBaseAddr) { BW_RTC_RAR_LRR(rtcBaseAddr, 0U); } /*! * @brief Reads the field Status Register Read (SRR) value of the RTC_RAR register. * * @param rtcBaseAddr The RTC base address * * @return true: Reads to the status register completes as normal.\n * false: Reads to the status register are ignored. */ static inline bool RTC_HAL_GetStatusRreg(uint32_t rtcBaseAddr) { return (bool)BR_RTC_RAR_SRR(rtcBaseAddr); } /*! * @brief Writes 0 to the field Status Register Read (SRR) of the RTC_RAR register. * * Once cleared, this bit is only set by system reset. It is not affected by * VBAT POR or software reset. * * @param rtcBaseAddr The RTC base address */ static inline void RTC_HAL_ClearStatusRreg(uint32_t rtcBaseAddr) { BW_RTC_RAR_SRR(rtcBaseAddr, 0U); } /*! * @brief Reads the field Control Register Read (CRR) value of the RTC_RAR register. * * @param rtcBaseAddr The RTC base address * * @return true: Reads to the control register completes as normal.\n * false: Reads to the control register are ignored. */ static inline bool RTC_HAL_GetControlRreg(uint32_t rtcBaseAddr) { return (bool)BR_RTC_RAR_CRR(rtcBaseAddr); } /*! * @brief Writes 0 to the field Control Register Read (CRR) of the RTC_RAR register. * * Once cleared, this bit is only set by system reset. It is not affected by * VBAT POR or software reset. * * @param rtcBaseAddr The RTC base address */ static inline void RTC_HAL_ClearControlRreg(uint32_t rtcBaseAddr) { BW_RTC_RAR_CRR(rtcBaseAddr, 0U); } /*! * @brief Reads the field Time Compensation Register Read (TCRR) value of the RTC_RAR register. * * @param rtcBaseAddr The RTC base address * * @return true: Reads to the time compensation register completes as normal.\n * false: Reads to the time compensation register are ignored. */ static inline bool RTC_HAL_GetCompensationRreg(uint32_t rtcBaseAddr) { return (bool)BR_RTC_RAR_TCRR(rtcBaseAddr); } /*! * @brief Writes 0 to the field Time Compensation Register Read (TCRR) of the RTC_RAR register. * * Once cleared, this bit is only set by system reset. It is not affected by * VBAT POR or software reset. * * @param rtcBaseAddr The RTC base address */ static inline void RTC_HAL_ClearCompensationRreg(uint32_t rtcBaseAddr) { BW_RTC_RAR_TCRR(rtcBaseAddr, 0U); } /*! * @brief Reads the field Time Alarm Register Read (TARR) value of the RTC_RAR register. * * @param rtcBaseAddr The RTC base address * * @return true: Reads to the time alarm register completes as normal.\n * false: Reads to the time alarm register are ignored. */ static inline bool RTC_HAL_GetAlarmRreg(uint32_t rtcBaseAddr) { return (bool)BR_RTC_RAR_TARR(rtcBaseAddr); } /*! * @brief Writes 0 to the field Time Alarm Register Read (TARR) of the RTC_RAR register. * * Once cleared, this bit is only set by system reset. It is not affected by * VBAT POR or software reset. * * @param rtcBaseAddr The RTC base address */ static inline void RTC_HAL_ClearAlarmRreg(uint32_t rtcBaseAddr) { BW_RTC_RAR_TARR(rtcBaseAddr, 0U); } /*! * @brief Reads the field Time Prescaler Register Read (TPRR) value of the RTC_RAR register. * * @param rtcBaseAddr The RTC base address * * @return true: Reads to the time prescaler register completes as normal.\n * false: Reads to the time prescaler register are ignored. */ static inline bool RTC_HAL_GetPrescalerRreg(uint32_t rtcBaseAddr) { return (bool)BR_RTC_RAR_TPRR(rtcBaseAddr); } /*! * @brief Writes 0 to the field Time Prescaler Register Read (TPRR) of the RTC_RAR register. * * Once cleared, this bit is only set by system reset. It is not affected by * VBAT POR or software reset. * * @param rtcBaseAddr The RTC base address */ static inline void RTC_HAL_ClearPrescalerRreg(uint32_t rtcBaseAddr) { BW_RTC_RAR_TPRR(rtcBaseAddr, 0U); } /*! * @brief Reads the field Time Seconds Register Read (TSRR) value of the RTC_RAR register. * * @param rtcBaseAddr The RTC base address * * @return true: Reads to the time seconds register completes as normal.\n * false: Reads to the time seconds register are ignored. */ static inline bool RTC_HAL_GetSecsRreg(uint32_t rtcBaseAddr) { return (bool)BR_RTC_RAR_TSRR(rtcBaseAddr); } /*! * @brief Writes 0 to the field Time Seconds Register Read (TSRR) of the RTC_RAR register. * * Once cleared, this bit is only set by system reset. It is not affected by * VBAT POR or software reset. * * @param rtcBaseAddr The RTC base address */ static inline void RTC_HAL_ClearSecsRreg(uint32_t rtcBaseAddr) { BW_RTC_RAR_TSRR(rtcBaseAddr, 0U); } #endif /* FSL_FEATURE_RTC_HAS_ACCESS_CONTROL */ /*! @}*/ #if defined(__cplusplus) } #endif /*! @}*/ #endif /* __FSL_RTC_HAL_H__*/ /******************************************************************************* * EOF ******************************************************************************/ ================================================ FILE: Zelig/mbed/TARGET_K64F/TARGET_Freescale/TARGET_KPSDK_MCUS/TARGET_KPSDK_CODE/hal/sai/fsl_sai_features.h ================================================ /* ** ################################################################### ** Version: rev. 1.0, 2014-05-14 ** Build: b140515 ** ** Abstract: ** Chip specific module features. ** ** Copyright: 2014 Freescale Semiconductor, Inc. ** All rights reserved. ** ** Redistribution and use in source and binary forms, with or without modification, ** are permitted provided that the following conditions are met: ** ** o Redistributions of source code must retain the above copyright notice, this list ** of conditions and the following disclaimer. ** ** o Redistributions in binary form must reproduce the above copyright notice, this ** list of conditions and the following disclaimer in the documentation and/or ** other materials provided with the distribution. ** ** o Neither the name of Freescale Semiconductor, Inc. nor the names of its ** contributors may be used to endorse or promote products derived from this ** software without specific prior written permission. ** ** THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ** ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED ** WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE ** DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT 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. ** ** http: www.freescale.com ** mail: support@freescale.com ** ** Revisions: ** - rev. 1.0 (2014-05-14) ** Customer release. ** ** ################################################################### */ #if !defined(__FSL_SAI_FEATURES_H__) #define __FSL_SAI_FEATURES_H__ #if defined(CPU_MK20DX128VMP5) || defined(CPU_MK20DN128VMP5) || defined(CPU_MK20DX64VMP5) || defined(CPU_MK20DN64VMP5) || \ defined(CPU_MK20DX32VMP5) || defined(CPU_MK20DN32VMP5) || defined(CPU_MK20DX128VLH5) || defined(CPU_MK20DN128VLH5) || \ defined(CPU_MK20DX64VLH5) || defined(CPU_MK20DN64VLH5) || defined(CPU_MK20DX32VLH5) || defined(CPU_MK20DN32VLH5) || \ defined(CPU_MK20DX128VFM5) || defined(CPU_MK20DN128VFM5) || defined(CPU_MK20DX64VFM5) || defined(CPU_MK20DN64VFM5) || \ defined(CPU_MK20DX32VFM5) || defined(CPU_MK20DN32VFM5) || defined(CPU_MK20DX128VFT5) || defined(CPU_MK20DN128VFT5) || \ defined(CPU_MK20DX64VFT5) || defined(CPU_MK20DN64VFT5) || defined(CPU_MK20DX32VFT5) || defined(CPU_MK20DN32VFT5) || \ defined(CPU_MK20DX128VLF5) || defined(CPU_MK20DN128VLF5) || defined(CPU_MK20DX64VLF5) || defined(CPU_MK20DN64VLF5) || \ defined(CPU_MK20DX32VLF5) || defined(CPU_MK20DN32VLF5) || defined(CPU_MK24FN1M0VDC12) || defined(CPU_MK24FN1M0VLL12) || \ defined(CPU_MK24FN1M0VLQ12) || defined(CPU_MK24FN256VDC12) || defined(CPU_MK63FN1M0VLQ12) || defined(CPU_MK63FN1M0VMD12) || \ defined(CPU_MK64FX512VDC12) || defined(CPU_MK64FN1M0VDC12) || defined(CPU_MK64FX512VLL12) || defined(CPU_MK64FN1M0VLL12) || \ defined(CPU_MK64FX512VLQ12) || defined(CPU_MK64FN1M0VLQ12) || defined(CPU_MK64FX512VMD12) || defined(CPU_MK64FN1M0VMD12) || \ defined(CPU_MK70FN1M0VMF12) || defined(CPU_MK70FX512VMF12) || defined(CPU_MK70FN1M0VMF15) || defined(CPU_MK70FX512VMF15) || \ defined(CPU_MK70FN1M0VMJ12) || defined(CPU_MK70FX512VMJ12) || defined(CPU_MK70FN1M0VMJ15) || defined(CPU_MK70FX512VMJ15) /* @brief Receive/transmit FIFO size in item count (register bit fields TCSR[FRDE], TCSR[FRIE], TCSR[FRF], TCR1[TFW], RCSR[FRDE], RCSR[FRIE], RCSR[FRF], RCR1[RFW], registers TFRn, RFRn). */ #define FSL_FEATURE_SAI_FIFO_COUNT (8) /* @brief Receive/transmit channel number (register bit fields TCR3[TCE], RCR3[RCE], registers TDRn and RDRn). */ #define FSL_FEATURE_SAI_CHANNEL_COUNT (2) /* @brief Maximum words per frame (register bit fields TCR3[WDFL], TCR4[FRSZ], TMR[TWM], RCR3[WDFL], RCR4[FRSZ], RMR[RWM]). */ #define FSL_FEATURE_SAI_MAX_WORDS_PER_FRAME (32) /* @brief Has support of combining multiple data channel FIFOs into single channel FIFO (register bit fields TCR3[CFR], TCR4[FCOMB], TFR0[WCP], TFR1[WCP], RCR3[CFR], RCR4[FCOMB], RFR0[RCP], RFR1[RCP]). */ #define FSL_FEATURE_SAI_HAS_FIFO_COMBINE_MODE (0) /* @brief Has packing of 8-bit and 16-bit data into each 32-bit FIFO word (register bit fields TCR4[FPACK], RCR4[FPACK]). */ #define FSL_FEATURE_SAI_HAS_FIFO_PACKING (0) /* @brief Configures when the SAI will continue transmitting after a FIFO error has been detected (register bit fields TCR4[FCONT], RCR4[FCONT]). */ #define FSL_FEATURE_SAI_HAS_FIFO_FUNCTION_AFTER_ERROR (0) /* @brief Configures if the frame sync is generated internally, a frame sync is only generated when the FIFO warning flag is clear or continuously (register bit fields TCR4[ONDEM], RCR4[ONDEM]). */ #define FSL_FEATURE_SAI_HAS_ON_DEMAND_MODE (0) /* @brief Simplified bit clock source and asynchronous/synchronous mode selection (register bit fields TCR2[CLKMODE], RCR2[CLKMODE]), in comparison with the exclusively implemented TCR2[SYNC,BCS,BCI,MSEL], RCR2[SYNC,BCS,BCI,MSEL]. */ #define FSL_FEATURE_SAI_HAS_CLOCKING_MODE (0) #elif defined(CPU_MK22FN128VDC10) || defined(CPU_MK22FN128VLH10) || defined(CPU_MK22FN128VLL10) || defined(CPU_MK22FN128VMP10) || \ defined(CPU_MK22FN256VDC12) || defined(CPU_MK22FN256VLH12) || defined(CPU_MK22FN256VLL12) || defined(CPU_MK22FN256VMP12) || \ defined(CPU_MK22FN512VDC12) || defined(CPU_MK22FN512VLH12) || defined(CPU_MK22FN512VLL12) /* @brief Receive/transmit FIFO size in item count (register bit fields TCSR[FRDE], TCSR[FRIE], TCSR[FRF], TCR1[TFW], RCSR[FRDE], RCSR[FRIE], RCSR[FRF], RCR1[RFW], registers TFRn, RFRn). */ #define FSL_FEATURE_SAI_FIFO_COUNT (8) /* @brief Receive/transmit channel number (register bit fields TCR3[TCE], RCR3[RCE], registers TDRn and RDRn). */ #define FSL_FEATURE_SAI_CHANNEL_COUNT (1) /* @brief Maximum words per frame (register bit fields TCR3[WDFL], TCR4[FRSZ], TMR[TWM], RCR3[WDFL], RCR4[FRSZ], RMR[RWM]). */ #define FSL_FEATURE_SAI_MAX_WORDS_PER_FRAME (16) /* @brief Has support of combining multiple data channel FIFOs into single channel FIFO (register bit fields TCR3[CFR], TCR4[FCOMB], TFR0[WCP], TFR1[WCP], RCR3[CFR], RCR4[FCOMB], RFR0[RCP], RFR1[RCP]). */ #define FSL_FEATURE_SAI_HAS_FIFO_COMBINE_MODE (0) /* @brief Has packing of 8-bit and 16-bit data into each 32-bit FIFO word (register bit fields TCR4[FPACK], RCR4[FPACK]). */ #define FSL_FEATURE_SAI_HAS_FIFO_PACKING (1) /* @brief Configures when the SAI will continue transmitting after a FIFO error has been detected (register bit fields TCR4[FCONT], RCR4[FCONT]). */ #define FSL_FEATURE_SAI_HAS_FIFO_FUNCTION_AFTER_ERROR (1) /* @brief Configures if the frame sync is generated internally, a frame sync is only generated when the FIFO warning flag is clear or continuously (register bit fields TCR4[ONDEM], RCR4[ONDEM]). */ #define FSL_FEATURE_SAI_HAS_ON_DEMAND_MODE (1) /* @brief Simplified bit clock source and asynchronous/synchronous mode selection (register bit fields TCR2[CLKMODE], RCR2[CLKMODE]), in comparison with the exclusively implemented TCR2[SYNC,BCS,BCI,MSEL], RCR2[SYNC,BCS,BCI,MSEL]. */ #define FSL_FEATURE_SAI_HAS_CLOCKING_MODE (0) #elif defined(CPU_MK65FN2M0CAC18) || defined(CPU_MK65FX1M0CAC18) || defined(CPU_MK65FN2M0VMI18) || defined(CPU_MK65FX1M0VMI18) || \ defined(CPU_MK66FN2M0VLQ18) || defined(CPU_MK66FX1M0VLQ18) || defined(CPU_MK66FN2M0VMD18) || defined(CPU_MK66FX1M0VMD18) /* @brief Receive/transmit FIFO size in item count (register bit fields TCSR[FRDE], TCSR[FRIE], TCSR[FRF], TCR1[TFW], RCSR[FRDE], RCSR[FRIE], RCSR[FRF], RCR1[RFW], registers TFRn, RFRn). */ #define FSL_FEATURE_SAI_FIFO_COUNT (8) /* @brief Receive/transmit channel number (register bit fields TCR3[TCE], RCR3[RCE], registers TDRn and RDRn). */ #define FSL_FEATURE_SAI_CHANNEL_COUNT (2) /* @brief Maximum words per frame (register bit fields TCR3[WDFL], TCR4[FRSZ], TMR[TWM], RCR3[WDFL], RCR4[FRSZ], RMR[RWM]). */ #define FSL_FEATURE_SAI_MAX_WORDS_PER_FRAME (32) /* @brief Has support of combining multiple data channel FIFOs into single channel FIFO (register bit fields TCR3[CFR], TCR4[FCOMB], TFR0[WCP], TFR1[WCP], RCR3[CFR], RCR4[FCOMB], RFR0[RCP], RFR1[RCP]). */ #define FSL_FEATURE_SAI_HAS_FIFO_COMBINE_MODE (1) /* @brief Has packing of 8-bit and 16-bit data into each 32-bit FIFO word (register bit fields TCR4[FPACK], RCR4[FPACK]). */ #define FSL_FEATURE_SAI_HAS_FIFO_PACKING (1) /* @brief Configures when the SAI will continue transmitting after a FIFO error has been detected (register bit fields TCR4[FCONT], RCR4[FCONT]). */ #define FSL_FEATURE_SAI_HAS_FIFO_FUNCTION_AFTER_ERROR (1) /* @brief Configures if the frame sync is generated internally, a frame sync is only generated when the FIFO warning flag is clear or continuously (register bit fields TCR4[ONDEM], RCR4[ONDEM]). */ #define FSL_FEATURE_SAI_HAS_ON_DEMAND_MODE (1) /* @brief Simplified bit clock source and asynchronous/synchronous mode selection (register bit fields TCR2[CLKMODE], RCR2[CLKMODE]), in comparison with the exclusively implemented TCR2[SYNC,BCS,BCI,MSEL], RCR2[SYNC,BCS,BCI,MSEL]. */ #define FSL_FEATURE_SAI_HAS_CLOCKING_MODE (0) #elif defined(CPU_MKL13Z64VFM4) || defined(CPU_MKL13Z128VFM4) || defined(CPU_MKL13Z256VFM4) || defined(CPU_MKL13Z64VFT4) || \ defined(CPU_MKL13Z128VFT4) || defined(CPU_MKL13Z256VFT4) || defined(CPU_MKL13Z64VLH4) || defined(CPU_MKL13Z128VLH4) || \ defined(CPU_MKL13Z256VLH4) || defined(CPU_MKL13Z64VMP4) || defined(CPU_MKL13Z128VMP4) || defined(CPU_MKL13Z256VMP4) || \ defined(CPU_MKL23Z64VFM4) || defined(CPU_MKL23Z128VFM4) || defined(CPU_MKL23Z256VFM4) || defined(CPU_MKL23Z64VFT4) || \ defined(CPU_MKL23Z128VFT4) || defined(CPU_MKL23Z256VFT4) || defined(CPU_MKL23Z64VLH4) || defined(CPU_MKL23Z128VLH4) || \ defined(CPU_MKL23Z256VLH4) || defined(CPU_MKL23Z64VMP4) || defined(CPU_MKL23Z128VMP4) || defined(CPU_MKL23Z256VMP4) || \ defined(CPU_MKL33Z128VLH4) || defined(CPU_MKL33Z256VLH4) || defined(CPU_MKL33Z128VMP4) || defined(CPU_MKL33Z256VMP4) || \ defined(CPU_MKL43Z64VLH4) || defined(CPU_MKL43Z128VLH4) || defined(CPU_MKL43Z256VLH4) || defined(CPU_MKL43Z64VMP4) || \ defined(CPU_MKL43Z128VMP4) || defined(CPU_MKL43Z256VMP4) /* @brief Receive/transmit FIFO size in item count (register bit fields TCSR[FRDE], TCSR[FRIE], TCSR[FRF], TCR1[TFW], RCSR[FRDE], RCSR[FRIE], RCSR[FRF], RCR1[RFW], registers TFRn, RFRn). */ #define FSL_FEATURE_SAI_FIFO_COUNT (4) /* @brief Receive/transmit channel number (register bit fields TCR3[TCE], RCR3[RCE], registers TDRn and RDRn). */ #define FSL_FEATURE_SAI_CHANNEL_COUNT (1) /* @brief Maximum words per frame (register bit fields TCR3[WDFL], TCR4[FRSZ], TMR[TWM], RCR3[WDFL], RCR4[FRSZ], RMR[RWM]). */ #define FSL_FEATURE_SAI_MAX_WORDS_PER_FRAME (2) /* @brief Has support of combining multiple data channel FIFOs into single channel FIFO (register bit fields TCR3[CFR], TCR4[FCOMB], TFR0[WCP], TFR1[WCP], RCR3[CFR], RCR4[FCOMB], RFR0[RCP], RFR1[RCP]). */ #define FSL_FEATURE_SAI_HAS_FIFO_COMBINE_MODE (0) /* @brief Has packing of 8-bit and 16-bit data into each 32-bit FIFO word (register bit fields TCR4[FPACK], RCR4[FPACK]). */ #define FSL_FEATURE_SAI_HAS_FIFO_PACKING (1) /* @brief Configures when the SAI will continue transmitting after a FIFO error has been detected (register bit fields TCR4[FCONT], RCR4[FCONT]). */ #define FSL_FEATURE_SAI_HAS_FIFO_FUNCTION_AFTER_ERROR (1) /* @brief Configures if the frame sync is generated internally, a frame sync is only generated when the FIFO warning flag is clear or continuously (register bit fields TCR4[ONDEM], RCR4[ONDEM]). */ #define FSL_FEATURE_SAI_HAS_ON_DEMAND_MODE (1) /* @brief Simplified bit clock source and asynchronous/synchronous mode selection (register bit fields TCR2[CLKMODE], RCR2[CLKMODE]), in comparison with the exclusively implemented TCR2[SYNC,BCS,BCI,MSEL], RCR2[SYNC,BCS,BCI,MSEL]. */ #define FSL_FEATURE_SAI_HAS_CLOCKING_MODE (1) #elif defined(CPU_MKL26Z256VLK4) || defined(CPU_MKL26Z128VLL4) || defined(CPU_MKL26Z256VLL4) || defined(CPU_MKL26Z128VMC4) || \ defined(CPU_MKL26Z256VMC4) || defined(CPU_MKL46Z128VLH4) || defined(CPU_MKL46Z256VLH4) || defined(CPU_MKL46Z128VLL4) || \ defined(CPU_MKL46Z256VLL4) || defined(CPU_MKL46Z128VMC4) || defined(CPU_MKL46Z256VMC4) /* @brief Receive/transmit FIFO size in item count (register bit fields TCSR[FRDE], TCSR[FRIE], TCSR[FRF], TCR1[TFW], RCSR[FRDE], RCSR[FRIE], RCSR[FRF], RCR1[RFW], registers TFRn, RFRn). */ #define FSL_FEATURE_SAI_FIFO_COUNT (1) /* @brief Receive/transmit channel number (register bit fields TCR3[TCE], RCR3[RCE], registers TDRn and RDRn). */ #define FSL_FEATURE_SAI_CHANNEL_COUNT (1) /* @brief Maximum words per frame (register bit fields TCR3[WDFL], TCR4[FRSZ], TMR[TWM], RCR3[WDFL], RCR4[FRSZ], RMR[RWM]). */ #define FSL_FEATURE_SAI_MAX_WORDS_PER_FRAME (2) /* @brief Has support of combining multiple data channel FIFOs into single channel FIFO (register bit fields TCR3[CFR], TCR4[FCOMB], TFR0[WCP], TFR1[WCP], RCR3[CFR], RCR4[FCOMB], RFR0[RCP], RFR1[RCP]). */ #define FSL_FEATURE_SAI_HAS_FIFO_COMBINE_MODE (0) /* @brief Has packing of 8-bit and 16-bit data into each 32-bit FIFO word (register bit fields TCR4[FPACK], RCR4[FPACK]). */ #define FSL_FEATURE_SAI_HAS_FIFO_PACKING (0) /* @brief Configures when the SAI will continue transmitting after a FIFO error has been detected (register bit fields TCR4[FCONT], RCR4[FCONT]). */ #define FSL_FEATURE_SAI_HAS_FIFO_FUNCTION_AFTER_ERROR (0) /* @brief Configures if the frame sync is generated internally, a frame sync is only generated when the FIFO warning flag is clear or continuously (register bit fields TCR4[ONDEM], RCR4[ONDEM]). */ #define FSL_FEATURE_SAI_HAS_ON_DEMAND_MODE (0) /* @brief Simplified bit clock source and asynchronous/synchronous mode selection (register bit fields TCR2[CLKMODE], RCR2[CLKMODE]), in comparison with the exclusively implemented TCR2[SYNC,BCS,BCI,MSEL], RCR2[SYNC,BCS,BCI,MSEL]. */ #define FSL_FEATURE_SAI_HAS_CLOCKING_MODE (0) #else #error "No valid CPU defined!" #endif #endif /* __FSL_SAI_FEATURES_H__ */ /******************************************************************************* * EOF ******************************************************************************/ ================================================ FILE: Zelig/mbed/TARGET_K64F/TARGET_Freescale/TARGET_KPSDK_MCUS/TARGET_KPSDK_CODE/hal/sai/fsl_sai_hal.h ================================================ /* * Copyright (c) 2013 - 2014, Freescale Semiconductor, Inc. * All rights reserved. * * Redistribution and use in source and binary forms, with or without modification, * are permitted provided that the following conditions are met: * * o Redistributions of source code must retain the above copyright notice, this list * of conditions and the following disclaimer. * * o Redistributions in binary form must reproduce the above copyright notice, this * list of conditions and the following disclaimer in the documentation and/or * other materials provided with the distribution. * * o Neither the name of Freescale Semiconductor, Inc. nor the names of its * contributors may be used to endorse or promote products derived from this * software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT 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. */ #ifndef __FSL_SAI_HAL_H__ #define __FSL_SAI_HAL_H__ #include #include #include #include "fsl_device_registers.h" #include "fsl_sai_features.h" /*! * @addtogroup sai_hal * @{ */ /*! @file */ /******************************************************************************* * Definitions ******************************************************************************/ /* Define the bit limits of in a word*/ #define SAI_BIT_MIN 8 #define SAI_BIT_MAX 32 /* Define the max div and fract value for master clock divider. */ #define SAI_FRACT_MAX 256 #define SAI_DIV_MAX 4096 /*! @brief Define the bus type of sai */ typedef enum _sai_protocol { kSaiBusI2SLeft = 0x0, kSaiBusI2SRight = 0x1, kSaiBusI2SType = 0x2, kSaiBusPCMA = 0x3, kSaiBusPCMB = 0x4, kSaiBusAC97 = 0x5 } sai_protocol_t; /*! @brief Master or slave mode */ typedef enum _sai_master_slave { kSaiMaster = 0x0,/*!< Master mode */ kSaiSlave = 0x1/*!< Slave mode */ } sai_master_slave_t; /*! @brief Polarity of SAI clock. */ typedef enum _sai_clk_polarity { kSaiClkPolarityHigh = 0x0, /*!< Clock active high */ kSaiClkPolarityLow = 0x1 /*!< Clock active low */ } sai_clk_polarity_t; /*! @brief Clock generate direction. */ typedef enum _sai_clk_direction { kSaiClkInternal = 0x0, /*!< Clock generated internal. */ kSaiClkExternal = 0x1 /*!< Clock generated external. */ } sai_clk_direction_t; /*! @brief Data transfer polarity, means MSB first of LSB first.*/ typedef enum _sai_data_order { kSaiLSBFirst = 0x0, /*!< Least significant bit transferred first. */ kSaiMSBFirst = 0x1 /*!< Most significant bit transferred first. */ } sai_data_order_t; /*! @brief Synchronous or asynchronous mode */ typedef enum _sai_sync_mode { kSaiModeAsync = 0x0,/*!< Asynchronous mode */ kSaiModeSync = 0x1,/*!< Synchronous mode (with receiver or transmit) */ kSaiModeSyncWithOtherTx = 0x2,/*!< Synchronous with another SAI transmit */ kSaiModeSyncWithOtherRx = 0x3/*!< Synchronous with another SAI receiver */ } sai_sync_mode_t; /*! @brief Mater clock source */ typedef enum _sai_mclk_source { kSaiMclkSourceSysclk = 0x0,/*!< Master clock from the system clock */ kSaiMclkSourceSelect1 = 0x1,/*!< Master clock from source 1 */ kSaiMclkSourceSelect2 = 0x2,/*!< Master clock from source 2 */ kSaiMclkSourceSelect3 = 0x3/*!< Master clock from source 3 */ } sai_mclk_source_t; /*! @brief Bit clock source */ typedef enum _sai_bclk_source { kSaiBclkSourceBusclk = 0x0,/*!< Bit clock using bus clock */ kSaiBclkSourceMclkDiv = 0x1,/*!< Bit clock using master clock divider */ kSaiBclkSourceOtherSai0 = 0x2,/*!< Bit clock from other SAI device */ kSaiBclkSourceOtherSai1 = 0x3/*!< Bit clock from other SAI device */ } sai_bclk_source_t; /*! @brief The SAI state flag. */ typedef enum _sai_interrupt_request { kSaiIntrequestWordStart = 0x0,/*!< Word start flag, means the first word in a frame detected */ kSaiIntrequestSyncError = 0x1,/*!< Sync error flag, means the sync error is detected */ kSaiIntrequestFIFOWarning = 0x2,/*!< FIFO warning flag, means the FIFO is empty */ kSaiIntrequestFIFOError = 0x3,/*!< FIFO error flag */ kSaiIntrequestFIFORequest = 0x4/*!< FIFO request, means reached watermark */ } sai_interrupt_request_t; /*! @brief The DMA request sources */ typedef enum _sai_dma_request { kSaiDmaReqFIFOWarning = 0x0,/*!< FIFO warning caused by the DMA request */ kSaiDmaReqFIFORequest = 0x1/*!< FIFO request caused by the DMA request */ } sai_dma_request_t; /*! @brief The SAI state flag */ typedef enum _sai_state_flag { kSaiStateFlagWordStart = 0x0,/*!< Word start flag, means the first word in a frame detected. */ kSaiStateFlagSyncError = 0x1,/*!< Sync error flag, means the sync error is detected */ kSaiStateFlagFIFOError = 0x2,/*!< FIFO error flag */ kSaiStateFlagFIFORequest = 0x3, kSaiStateFlagFIFOWarning = 0x4, kSaiStateFlagSoftReset = 0x5 /*!< Software reset flag */ } sai_state_flag_t; /*! @brief The reset type */ typedef enum _sai_reset_type { kSaiResetTypeSoftware = 0x0,/*!< Software reset, reset the logic state */ kSaiResetTypeFIFO = 0x1/*!< FIFO reset, reset the FIFO read and write pointer */ } sai_reset_type_t; /* * @brief The SAI running mode * The mode includes normal mode, debug mode, and stop mode. */ typedef enum _sai_running_mode { kSaiRunModeDebug = 0x0,/*!< In debug mode */ kSaiRunModeStop = 0x1/*!< In stop mode */ } sai_run_mode_t; #if FSL_FEATURE_SAI_HAS_FIFO_PACKING /* * @brief The SAI packing mode * The mode includes 8 bit and 16 bit packing. */ typedef enum _sai_fifo_packing { kSaiFifoPackingDisabled = 0x0, /*!< Packing disabled. */ kSaiFifoPacking8bit = 0x2,/*!< 8 bit packing enabled. */ kSaiFifoPacking16bit = 0x3 /*!< 16bit packing enabled. */ } sai_fifo_packing_t; #endif /******************************************************************************* * API ******************************************************************************/ #if defined(__cplusplus) extern "C" { #endif /*! * @name Module control * @{ */ /*! * @brief Initializes the SAI Tx. * * The initialization resets the SAI module by setting the SR bit of TCSR register. * Note that the function writes 0 to every control registers. * @param saiBaseAddr Register base address of SAI module. */ void SAI_HAL_TxInit(uint32_t saiBaseAddr); /*! * @brief Initializes the SAI Rx. * * The initialization resets the SAI module by setting the SR bit of RCSR register. * Note that the function writes 0 to every control registers. * @param saiBaseAddr Register base address of SAI module. */ void SAI_HAL_RxInit(uint32_t saiBaseAddr); /*! * @brief Sets Tx protocol relevant settings. * * The bus mode means which protocol SAI uses. It can be I2S left, right and so on. Each protocol * has a different configuration on bit clock and frame sync. * @param saiBaseAddr Register base address of SAI module. * @param protocol The protocol selection. It can be I2S left aligned, I2S right aligned, etc. */ void SAI_HAL_TxSetProtocol(uint32_t saiBaseAddr, sai_protocol_t protocol); /*! * @brief Sets Rx protocol relevant settings. * * The bus mode means which protocol SAI uses. It can be I2S left, right and so on. Each protocol * has a different configuration on bit clock and frame sync. * @param saiBaseAddr Register base address of SAI module. * @param protocol The protocol selection. It can be I2S left aligned, I2S right aligned, etc. */ void SAI_HAL_RxSetProtocol(uint32_t saiBaseAddr, sai_protocol_t protocol); /*! * @brief Sets master or slave mode. * * The function determines master or slave mode. Master mode provides its * own clock and slave mode uses an external clock. * @param saiBaseAddr Register base address of SAI module. * @param master_slave_mode Mater or slave mode. */ void SAI_HAL_TxSetMasterSlave(uint32_t saiBaseAddr, sai_master_slave_t master_slave_mode); /*! * @brief Sets master or slave mode. * * The function determines master or slave mode. Master mode provides its * own clock and slave mode uses external clock. * @param saiBaseAddr Register base address of SAI module. * @param master_slave_mode Mater or slave mode. */ void SAI_HAL_RxSetMasterSlave(uint32_t saiBaseAddr, sai_master_slave_t master_slave_mode); /*! @}*/ /*! * @name Master clock configuration * @{ */ /*! * @brief Sets the master clock source. * * The source of the clock is different from socs. * This function sets the clock source for SAI master clock source. * Master clock is used to produce the bit clock for the data transfer. * @param saiBaseAddr Register base address of SAI module. * @param source Mater clock source */ static inline void SAI_HAL_SetMclkSrc(uint32_t saiBaseAddr, sai_mclk_source_t source) { BW_I2S_MCR_MICS(saiBaseAddr,source); } /*! * @brief Gets the master clock source. * * The source of the clock is different from socs. * This function gets the clock source for SAI master clock source. * Master clock is used to produce the bit clock for the data transfer. * @param saiBaseAddr Register base address of SAI module. * @return Mater clock source */ static inline uint32_t SAI_HAL_GetMclkSrc(uint32_t saiBaseAddr) { return BR_I2S_MCR_MICS(saiBaseAddr); } /*! * @brief Sets the direction of the SAI master clock. * * This function would decides the direction of bit clock generated. * @param saiBaseAddr Register base address of SAI module. * @param enable True means enable, false means disable. */ static inline void SAI_HAL_SetMclkDividerCmd(uint32_t saiBaseAddr, bool enable) { BW_I2S_MCR_MOE(saiBaseAddr,enable); } /*! * @brief Sets the divider of the master clock. * * Using the divider to get the master clock frequency wanted from the source. * mclk = clk_source * fract/divide. The input is the master clock frequency needed and the source clock frequency. * The master clock is decided by the sample rate and the multi-clock number. * Notice that mclk should less than src_clk, or it would do hang as the HW refuses to write in this situation. * @param saiBaseAddr Register base address of SAI module. * @param mclk Master clock frequency needed. * @param src_clk The source clock frequency. */ void SAI_HAL_SetMclkDiv(uint32_t saiBaseAddr, uint32_t mclk, uint32_t src_clk); /*! * @brief Flag to see if the master clock divider is re-divided. * @param saiBaseAddr Register base address of SAI module. * @return True if the divider updated otherwise false. */ static inline bool SAI_HAL_GetMclkDivUpdatingCmd(uint32_t saiBaseAddr) { return BR_I2S_MCR_DUF(saiBaseAddr); } /*! @}*/ /*! * @name Bit clock configuration * @{ */ /*! * @brief Sets the bit clock source of Tx. It is generated by the master clock, bus clock and other devices. * * The function sets the source of the bit clock. The bit clock can be produced by the master * clock and from the bus clock or other SAI Tx/Rx. Tx and Rx in the SAI module use the same bit * clock either from Tx or Rx. * @param saiBaseAddr Register base address of SAI module. * @param source Bit clock source. */ static inline void SAI_HAL_TxSetBclkSrc(uint32_t saiBaseAddr, sai_bclk_source_t source) { BW_I2S_TCR2_MSEL(saiBaseAddr,source); } /*! * @brief Sets bit clock source of the Rx. It is generated by the master clock, bus clock and other devices. * * The function sets the source of the bit clock. The bit clock can be produced by the master * clock, and from the bus clock or other SAI Tx/Rx. Tx and Rx in the SAI module use the same bit * clock either from Tx or Rx. * @param saiBaseAddr Register base address of SAI module. * @param source Bit clock source. */ static inline void SAI_HAL_RxSetBclkSrc(uint32_t saiBaseAddr, sai_bclk_source_t source) { BW_I2S_RCR2_MSEL(saiBaseAddr,source); } /*! * @brief Gets the bit clock source of Tx. It is generated by the master clock, bus clock and other devices. * * The function gets the source of the bit clock. The bit clock can be produced by the master * clock and from the bus clock or other SAI Tx/Rx. Tx and Rx in the SAI module use the same bit * clock either from Tx or Rx. * @param saiBaseAddr Register base address of SAI module. * @return Bit clock source. */ static inline uint32_t SAI_HAL_TxGetBclkSrc(uint32_t saiBaseAddr) { return BR_I2S_TCR2_MSEL(saiBaseAddr); } /*! * @brief Gets bit clock source of the Rx. It is generated by the master clock, bus clock and other devices. * * The function gets the source of the bit clock. The bit clock can be produced by the master * clock, and from the bus clock or other SAI Tx/Rx. Tx and Rx in the SAI module use the same bit * clock either from Tx or Rx. * @param saiBaseAddr Register base address of SAI module. * @return Bit clock source. */ static inline uint32_t SAI_HAL_RxGetBclkSrc(uint32_t saiBaseAddr) { return BR_I2S_RCR2_MSEL(saiBaseAddr); } /*! * @brief Sets the Tx bit clock divider value. * * bclk = mclk / divider. At the same time, bclk = sample_rate * channel * bits. This means * how much time is needed to transfer one bit. * Notice: The function is called while the bit clock source is the master clock. * @param saiBaseAddr Register base address of SAI module. * @param divider The divide number of bit clock. */ static inline void SAI_HAL_TxSetBclkDiv(uint32_t saiBaseAddr, uint32_t divider) { BW_I2S_TCR2_DIV(saiBaseAddr,divider/2 -1); } /*! * @brief Sets the Rx bit clock divider value. * * bclk = mclk / divider. At the same time, bclk = sample_rate * channel * bits. This means * how much time is needed to transfer one bit. * Notice: The function is called while the bit clock source is the master clock. * @param saiBaseAddr Register base address of SAI module. * @param divider The divide number of bit clock. */ static inline void SAI_HAL_RxSetBclkDiv(uint32_t saiBaseAddr, uint32_t divider) { BW_I2S_RCR2_DIV(saiBaseAddr,divider/2 -1); } /*! * @brief Enables or disables the Tx bit clock. * * @param saiBaseAddr Register base address of SAI module. * @param enable True means enable, false means disable. */ static inline void SAI_HAL_TxSetBclkCmd(uint32_t saiBaseAddr, bool enable) { BW_I2S_TCSR_BCE(saiBaseAddr,enable); } /*! * @brief Enables or disables the Rx bit clock. * * @param saiBaseAddr Register base address of SAI module. * @param enable True means enable, false means disable. */ static inline void SAI_HAL_RxSetBclkCmd(uint32_t saiBaseAddr, bool enable) { BW_I2S_RCSR_BCE(saiBaseAddr, enable); } /*! * @brief Enables or disables the Tx bit clock input bit. * * @param saiBaseAddr Register base address of SAI module. * @param enable True means enable, false means disable. */ static inline void SAI_HAL_TxSetBclkInputCmd(uint32_t saiBaseAddr, bool enable) { BW_I2S_TCR2_BCI(saiBaseAddr,enable); } /*! * @brief Enables or disables the Rx bit clock input bit. * * @param saiBaseAddr Register base address of SAI module. * @param enable True means enable, false means disable. */ static inline void SAI_HAL_RxSetBclkInputCmd(uint32_t saiBaseAddr, bool enable) { BW_I2S_RCR2_BCI(saiBaseAddr,enable); } /*! * @brief Sets the Tx bit clock swap. * * This field swaps the bit clock used by the transmitter. When the transmitter is configured in * asynchronous mode and this bit is set, the transmitter is clocked by the receiver bit clock. * This allows the transmitter and receiver to share the same bit clock, but the transmitter * continues to use the transmit frame sync (SAI_TX_SYNC). * When the transmitter is configured in synchronous mode, the transmitter BCS field and receiver * BCS field must be set to the same value. When both are set, the transmitter and receiver are both * clocked by the transmitter bit clock (SAI_TX_BCLK) but use the receiver frame sync (SAI_RX_SYNC). * @param saiBaseAddr Register base address of SAI module. * @param enable True means swap bit closk, false means no swap. */ static inline void SAI_HAL_TxSetSwapBclkCmd(uint32_t saiBaseAddr, bool enable) { BW_I2S_TCR2_BCS(saiBaseAddr,enable); } /*! * @brief Sets the Rx bit clock swap. * * This field swaps the bit clock used by the receiver. When the receiver is configured in * asynchronous mode and this bit is set, the receiver is clocked by the transmitter bit clock * (SAI_TX_BCLK). This allows the transmitter and receiver to share the same bit clock, but the * receiver continues to use the receiver frame sync (SAI_RX_SYNC). * When the receiver is configured in synchronous mode, the transmitter BCS field and receiver BCS * field must be set to the same value. When both are set, the transmitter and receiver are both * clocked by the receiver bit clock (SAI_RX_BCLK) but use the transmitter frame sync (SAI_TX_SYNC). * @param saiBaseAddr Register base address of SAI module. * @param enable True means swap bit closk, false means no swap. */ static inline void SAI_HAL_RxSetSwapBclkCmd(uint32_t saiBaseAddr, bool enable) { BW_I2S_RCR2_BCS(saiBaseAddr, enable); } /*! * @brief Sets the direction of the Tx SAI bit clock. * * This function sets the direction of the bit clock generated. * @param saiBaseAddr Register base address of SAI module. * @param direction Bit clock generated internal or external. */ static inline void SAI_HAL_TxSetBclkDir(uint32_t saiBaseAddr, sai_clk_direction_t direction) { BW_I2S_TCR2_BCD(saiBaseAddr,direction); } /*! * @brief Sets the direction of the Rx SAI bit clock. * * This function sets the direction of the bit clock generated. * @param saiBaseAddr Register base address of SAI module. * @param direction Bit clock generated internal or external. */ static inline void SAI_HAL_RxSetBclkDir(uint32_t saiBaseAddr, sai_clk_direction_t direction) { BW_I2S_RCR2_BCD(saiBaseAddr,direction); } /*! * @brief Sets the polarity of the Tx SAI bit clock. * * @param saiBaseAddr Register base address of SAI module. * @param pol Polarity of the SAI bit clock, which can be configured to active high or low. */ static inline void SAI_HAL_TxSetBclkPolarity(uint32_t saiBaseAddr, sai_clk_polarity_t pol) { BW_I2S_TCR2_BCP(saiBaseAddr, pol); } /*! * @brief Sets the polarity of the Rx SAI bit clock. * * @param saiBaseAddr Register base address of SAI module. * @param pol Polarity of SAI bit clock, which can be configured to active high or low. */ static inline void SAI_HAL_RxSetBclkPolarity(uint32_t saiBaseAddr, sai_clk_polarity_t pol) { BW_I2S_RCR2_BCP(saiBaseAddr, pol); } /*! @} */ /*! * @name Frame sync configuration * @{ */ /*! * @brief Sets the Tx frame size. * * The frame size means how many words are in a frame. For example 2-channel * audio data, the frame size is 2, which means 2 words in a frame. * @param saiBaseAddr Register base address of SAI module. * @param size Words number in a frame. */ static inline void SAI_HAL_TxSetFrameSize(uint32_t saiBaseAddr, uint32_t size) { BW_I2S_TCR4_FRSZ(saiBaseAddr,size -1); } /*! * @brief Sets the Rx frame size. * * The frame size means how many words are in a frame. For example 2-channel * audio data, the frame size is 2, which means 2 words in a frame. * @param saiBaseAddr Register base address of SAI module. * @param size Words number in a frame. */ static inline void SAI_HAL_RxSetFrameSize(uint32_t saiBaseAddr, uint32_t size) { BW_I2S_RCR4_FRSZ(saiBaseAddr,size - 1); } /*! * @brief Gets the Tx frame size. * * @param saiBaseAddr Register base address of SAI module. */ static inline uint32_t SAI_HAL_TxGetFrameSize(uint32_t saiBaseAddr) { return BR_I2S_TCR4_FRSZ(saiBaseAddr); } /*! * @brief Gets the Tx frame size. * * @param saiBaseAddr Register base address of SAI module. */ static inline uint32_t SAI_HAL_RxGetFrameSize(uint32_t saiBaseAddr) { return BR_I2S_RCR4_FRSZ(saiBaseAddr); } /*! * @brief Sets the Tx sync width. * * A sync is the number of bit clocks of a frame. The sync width cannot be longer than the * length of the first word of the frame. * @param saiBaseAddr Register base address of SAI module. * @param width How many bit clock in a sync. */ static inline void SAI_HAL_TxSetFrameSyncWidth(uint32_t saiBaseAddr, uint32_t width) { BW_I2S_TCR4_SYWD(saiBaseAddr, width -1); } /*! * @brief Sets the Rx sync width. * * A sync is the number of bit clocks of a frame. The sync width cannot be longer than the * length of the first word of the frame. * @param saiBaseAddr Register base address of SAI module. * @param width How many bit clock in a sync. */ static inline void SAI_HAL_RxSetFrameSyncWidth(uint32_t saiBaseAddr, uint32_t width) { BW_I2S_RCR4_SYWD(saiBaseAddr, width -1); } /*! * @brief Sets the polarity of the Tx frame sync. * * @param saiBaseAddr Register base address of SAI module. * @param pol Polarity of sai frame sync, can be configured to active high or low. */ static inline void SAI_HAL_TxSetFrameSyncPolarity(uint32_t saiBaseAddr, sai_clk_polarity_t pol) { BW_I2S_TCR4_FSP(saiBaseAddr,pol); } /*! * @brief Sets the polarity of the Rx frame sync. * * @param saiBaseAddr Register base address of SAI module.. * @param pol Polarity of SAI frame sync, can be configured to active high or low. */ static inline void SAI_HAL_RxSetFrameSyncPolarity(uint32_t saiBaseAddr, sai_clk_polarity_t pol) { BW_I2S_RCR4_FSP(saiBaseAddr,pol); } /*! * @brief Sets the direction of the SAI Tx frame sync. * * This function sets the direction of frame sync. * @param saiBaseAddr Register base address of SAI module. * @param direction Frame sync generated internal or external. */ static inline void SAI_HAL_TxSetFrameSyncDir(uint32_t saiBaseAddr,sai_clk_direction_t direction) { BW_I2S_TCR4_FSD(saiBaseAddr,direction); } /*! * @brief Sets the direction of the SAI Rx frame sync. * * This function sets the direction of frame sync. * @param saiBaseAddr Register base address of SAI module. * @param direction Frame sync generated internal or external. */ static inline void SAI_HAL_RxSetFrameSyncDir(uint32_t saiBaseAddr,sai_clk_direction_t direction) { BW_I2S_RCR4_FSD(saiBaseAddr,direction); } /*! * @brief Sets the Tx data transfer order. * * This function sets the data transfer order. It can be set to MSB first or LSB first. * @param saiBaseAddr Register base address of SAI module. * @param order MSB transmit first or LSB transmit first. */ static inline void SAI_HAL_TxSetBitOrder(uint32_t saiBaseAddr, sai_data_order_t order) { BW_I2S_TCR4_MF(saiBaseAddr,order); } /*! * @brief Sets the Rx data transfer order. * * This function sets the data transfer order. It can be set to MSB first or LSB first. * @param saiBaseAddr Register base address of SAI module. * @param order MSB transmit first or LSB transmit first. */ static inline void SAI_HAL_RxSetBitOrder(uint32_t saiBaseAddr, sai_data_order_t order) { BW_I2S_RCR4_MF(saiBaseAddr,order); } /*! * @brief Tx Frame sync one bit early. * * @param saiBaseAddr Register base address of SAI module. * @param enable True means the frame sync one bit early and false means no early. */ static inline void SAI_HAL_TxSetFrameSyncEarlyCmd(uint32_t saiBaseAddr, bool enable) { BW_I2S_TCR4_FSE(saiBaseAddr,enable); } /*! * @brief Rx Frame sync one bit early. * * @param saiBaseAddr Register base address of SAI module. * @param enable True means the frame sync one bit early and false means no early. */ static inline void SAI_HAL_RxSetFrameSyncEarlyCmd(uint32_t saiBaseAddr, bool enable) { BW_I2S_RCR4_FSE(saiBaseAddr,enable); } /*! @} */ /*! * @name Word configurations * @{ */ /*! * @brief Sets the word size for Tx. * * The word size means the quantization level of audio file. * SAI supports the 8 bit, 16 bit, 24 bit, and 32 bit formats. * @param saiBaseAddr Register base address of SAI module. * @param bits How many bits in a word. */ static inline void SAI_HAL_TxSetWordSize(uint32_t saiBaseAddr,uint32_t bits) { BW_I2S_TCR5_WNW(saiBaseAddr,bits-1); } /*! * @brief Sets the word size for Rx. * * The word size means the quantization level of audio file. * SAI supports 8 bit, 16 bit, 24 bit, and 32 bit formats. * @param saiBaseAddr Register base address of SAI module. * @param bits How many bits in a word. */ static inline void SAI_HAL_RxSetWordSize(uint32_t saiBaseAddr,uint32_t bits) { BW_I2S_RCR5_WNW(saiBaseAddr,bits-1); } /*! * @brief Gets the Tx word size. * @param saiBaseAddr Register base address of SAI module. */ static inline uint32_t SAI_HAL_TxGetWordSize(uint32_t saiBaseAddr) { return BR_I2S_TCR5_WNW(saiBaseAddr); } /*! * @brief Gets the Rx word size. * @param saiBaseAddr Register base address of SAI module. */ static inline uint32_t SAI_HAL_RxGetWordSize(uint32_t saiBaseAddr) { return BR_I2S_RCR5_WNW(saiBaseAddr); } /*! * @brief Sets the size of the first word of the Tx frame . * * In I2S protocol, the size of the first word is the same as the size of other words. In some protocols, * for example, AC'97, the first word is not the same size as others. This function * sets the length of the first word which is, in most situations, the same as others. * @param saiBaseAddr Register base address of SAI module. * @param size The length of frame head word. */ static inline void SAI_HAL_TxSetFirstWordSize(uint32_t saiBaseAddr, uint8_t size) { BW_I2S_TCR5_W0W(saiBaseAddr, size-1); } /*! * @brief Sets the size of the first word of Rx frame . * * In I2S protocol, the size of the first word is the same as the size of other words. In some protocols, * for example, AC'97, the first word is not the same size as others. This function * sets the length of the first word which is, in most situations, the same as others. * @param saiBaseAddr Register base address of SAI module. * @param size The length of frame head word. */ static inline void SAI_HAL_RxSetFirstWordSize(uint32_t saiBaseAddr, uint8_t size) { BW_I2S_RCR5_W0W(saiBaseAddr, size-1); } /*! * @brief Sets the FIFO index for the first bit data. * * The FIFO is 32-bit in SAI. However, not all audio data is 32-bit, but is mostly 16-bit. * In this situation, the codec needs to know which bit of the FIFO marks the valid audio data. * @param saiBaseAddr Register base address of SAI module. * @param index First bit shifted in FIFO. */ static inline void SAI_HAL_TxSetFirstBitShifted(uint32_t saiBaseAddr, uint32_t index) { BW_I2S_TCR5_FBT(saiBaseAddr, index-1); } /*! * @brief Sets the index in FIFO for the first bit data. * * The FIFO is 32-bit in SAI. However, not all audio data is 32-bit, but is mostly 16-bit. * In this situation, the codec needs to know which bit of the FIFO marks the valid audio data. * @param saiBaseAddr Register base address of SAI module. * @param index First bit shifted in FIFO. */ static inline void SAI_HAL_RxSetFirstBitShifted(uint32_t saiBaseAddr, uint32_t index) { BW_I2S_RCR5_FBT(saiBaseAddr, index-1); } /*!@}*/ /*! * @name watermark settings * @{ */ /*! * @brief Sets the Tx watermark value. * * While the value in the FIFO is less or equal to the watermark , it generates an interrupt * request or a DMA request. The watermark value cannot be greater than the depth of FIFO. * @param saiBaseAddr Register base address of SAI module. * @param watermark Watermark value of a FIFO. */ static inline void SAI_HAL_TxSetWatermark(uint32_t saiBaseAddr, uint32_t watermark) { BW_I2S_TCR1_TFW(saiBaseAddr, watermark); } /*! * @brief Sets the Tx watermark value. * * While the value in the FIFO is more or equal to the watermark , it generates an interrupt * request or a DMA request. The watermark value cannot be greater than the depth of FIFO. * @param saiBaseAddr Register base address of SAI module. * @param watermark Watermark value of a FIFO. */ static inline void SAI_HAL_RxSetWatermark(uint32_t saiBaseAddr, uint32_t watermark) { BW_I2S_RCR1_RFW(saiBaseAddr, watermark); } /*! * @brief Gets the Tx watermark value. * * @param saiBaseAddr Register base address of SAI module. */ static inline uint32_t SAI_HAL_TxGetWatermark(uint32_t saiBaseAddr) { return BR_I2S_TCR1_TFW(saiBaseAddr); } /*! * @brief Gets the Rx watermark value. * * @param saiBaseAddr Register base address of SAI module. */ static inline uint32_t SAI_HAL_RxGetWatermark(uint32_t saiBaseAddr) { return BR_I2S_RCR1_RFW(saiBaseAddr); } /*! @}*/ /*! * @brief SAI Tx sync mode setting. * * The mode can be asynchronous mode, synchronous, or synchronous with another SAI device. * When configured for a synchronous mode of operation, the receiver must be configured for the * asynchronous operation. * @param saiBaseAddr Register base address of SAI module. * @param sync_mode Synchronous mode or Asynchronous mode. */ void SAI_HAL_TxSetSyncMode(uint32_t saiBaseAddr, sai_sync_mode_t sync_mode); /*! * @brief SAI Rx sync mode setting. * * The mode can be asynchronous mode, synchronous, or synchronous with another SAI device. * When configured for a synchronous mode of operation, the receiver must be configured for the * asynchronous operation. * @param saiBaseAddr Register base address of SAI module. * @param sync_mode Synchronous mode or Asynchronous mode. */ void SAI_HAL_RxSetSyncMode(uint32_t saiBaseAddr, sai_sync_mode_t sync_mode); /*! * @brief Gets the Tx FIFO read pointer. * * It is used to determine whether the FIFO is full or empty and know how much space there is for FIFO. * If read_ptr == write_ptr, the FIFO is empty. While the bit of the read_ptr and the write_ptr are * equal except for the MSB, the FIFO is full. * @param saiBaseAddr Register base address of SAI module. * @param fifo_channel FIFO channel selected. * @return FIFO read pointer value. */ static inline uint8_t SAI_HAL_TxGetFifoReadPointer(uint32_t saiBaseAddr, uint32_t fifo_channel) { return BR_I2S_TFRn_RFP(saiBaseAddr,fifo_channel); } /*! * @brief Gets the Rx FIFO read pointer. * * It is used to determine whether the FIFO is full or empty and know how much space there is for FIFO. * If read_ptr == write_ptr, the FIFO is empty. While the bit of the read_ptr and the write_ptr are * equal except for the MSB, the FIFO is full. * @param saiBaseAddr Register base address of SAI module. * @param fifo_channel FIFO channel selected. * @return FIFO read pointer value. */ static inline uint8_t SAI_HAL_RxGetFifoReadPointer(uint32_t saiBaseAddr, uint32_t fifo_channel) { return BR_I2S_RFRn_RFP(saiBaseAddr,fifo_channel); } /*! * @brief Gets the Tx FIFO write pointer. * * It is used to determine whether the FIFO is full or empty and know how much space there is for FIFO. * If read_ptr == write_ptr, the FIFO is empty. While the bit of the read_ptr and write_ptr are * equal except for the MSB, the FIFO is full. * @param saiBaseAddr Register base address of SAI module. * @param fifo_channel FIFO channel selected. * @return FIFO read pointer value. */ static inline uint8_t SAI_HAL_TxGetFifoWritePointer(uint32_t saiBaseAddr,uint32_t fifo_channel) { return BR_I2S_TFRn_WFP(saiBaseAddr,fifo_channel); } /*! * @brief Gets the Rx FIFO write pointer. * * It is used to determine whether the FIFO is full or empty and know how much space there is for FIFO. * If read_ptr == write_ptr, the FIFO is empty. While the bit of the read_ptr and write_ptr are * equal except for the MSB, the FIFO is full. * @param saiBaseAddr Register base address of SAI module. * @param fifo_channel FIFO channel selected. * @return FIFO read pointer value. */ static inline uint8_t SAI_HAL_RxGetFifoWritePointer(uint32_t saiBaseAddr,uint32_t fifo_channel) { return BR_I2S_RFRn_WFP(saiBaseAddr,fifo_channel); } /*! * @brief Gets the TDR register address. * * This function determines the dest/src address of the DMA transfer. * @param saiBaseAddr Register base address of SAI module. * @param fifo_channel FIFO channel selected. * @return TDR register or RDR register address */ static inline uint32_t* SAI_HAL_TxGetFifoAddr(uint32_t saiBaseAddr, uint32_t fifo_channel) { return (uint32_t *)HW_I2S_TDRn_ADDR(saiBaseAddr, fifo_channel); } /*! * @brief Gets the RDR register address. * * This function determines the dest/src address of the DMA transfer. * @param saiBaseAddr Register base address of SAI module. * @param fifo_channel FIFO channel selected. * @return TDR register or RDR register address */ static inline uint32_t* SAI_HAL_RxGetFifoAddr(uint32_t saiBaseAddr, uint32_t fifo_channel) { return (uint32_t *)HW_I2S_RDRn_ADDR(saiBaseAddr, fifo_channel); } /*! * @brief Enables the SAI Tx module. * * Enables the Tx. This function enables both the bit clock and the transfer channel. * @param saiBaseAddr Register base address of SAI module. */ static inline void SAI_HAL_TxEnable(uint32_t saiBaseAddr) { BW_I2S_TCSR_BCE(saiBaseAddr,true); BW_I2S_TCSR_TE(saiBaseAddr,true); } /*! * @brief Enables the SAI Rx module. * * Enables the Rx. This function enables both the bit clock and the receive channel. * @param saiBaseAddr Register base address of SAI module. */ static inline void SAI_HAL_RxEnable(uint32_t saiBaseAddr) { BW_I2S_RCSR_BCE(saiBaseAddr,true); BW_I2S_RCSR_RE(saiBaseAddr,true); } /*! * @brief Disables the Tx module. * * Disables the Tx. This function disables both the bit clock and the transfer channel. * @param saiBaseAddr Register base address of SAI module. */ static inline void SAI_HAL_TxDisable(uint32_t saiBaseAddr) { BW_I2S_TCSR_TE(saiBaseAddr,false); BW_I2S_TCSR_BCE(saiBaseAddr,false); } /*! * @brief Disables the Rx module. * * Disables the Rx. This function disables both the bit clock and the receive channel. * @param saiBaseAddr Register base address of SAI module. */ static inline void SAI_HAL_RxDisable(uint32_t saiBaseAddr) { BW_I2S_RCSR_RE(saiBaseAddr,false); BW_I2S_RCSR_BCE(saiBaseAddr,false); } /*! * @brief Enables the Tx interrupt from different interrupt sources. * * The interrupt source can be : Word start flag, Sync error flag, FIFO error flag, FIFO warning flag, FIFO request flag. * This function sets which flag causes an interrupt request. * @param saiBaseAddr Register base address of SAI module. * @param source SAI interrupt request source. * @param enable Enable or disable. */ void SAI_HAL_TxSetIntCmd(uint32_t saiBaseAddr,sai_interrupt_request_t source, bool enable); /*! * @brief Enables the Rx interrupt from different interrupt sources. * * The interrupt source can be : Word start flag, Sync error flag, FIFO error flag, FIFO warning flag, FIFO request flag. * This function sets which flag causes an interrupt request. * @param saiBaseAddr Register base address of SAI module. * @param source SAI interrupt request source. * @param enable Enable or disable. */ void SAI_HAL_RxSetIntCmd(uint32_t saiBaseAddr,sai_interrupt_request_t source, bool enable); /*! * @brief Gets the status as to whether the Tx interrupt source is enabled. * * The interrupt source can be : Word start flag, Sync error flag, FIFO error flag, FIFO warning flag, FIFO request flag. * This function sets which flag causes an interrupt request. * @param saiBaseAddr Register base address of SAI module. * @param source SAI interrupt request source. * @return Enabled or disabled. */ bool SAI_HAL_TxGetIntCmd(uint32_t saiBaseAddr,sai_interrupt_request_t source); /*! * @brief Gets the status as to whether the Rx interrupt source is enabled. * * The interrupt source can be : Word start flag, Sync error flag, FIFO error flag, FIFO warning flag, FIFO request flag. * This function sets which flag causes an interrupt request. * @param saiBaseAddr Register base address of SAI module. * @param source SAI interrupt request source. * @return Enabled or disabled. */ bool SAI_HAL_RxGetIntCmd(uint32_t saiBaseAddr,sai_interrupt_request_t source); /*! * @brief Enables the Tx DMA request from different sources. * * The DMA sources can be: FIFO warning and FIFO request. * This function enables the DMA request from different DMA request sources. * @param saiBaseAddr Register base address of SAI module. * @param source SAI DMA request source. * @param enable Enable or disable. */ void SAI_HAL_TxSetDmaCmd(uint32_t saiBaseAddr, sai_dma_request_t source, bool enable); /*! * @brief Enables the Rx DMA request from different sources. * * The DMA sources can be: FIFO warning and FIFO request. * This function enables the DMA request from different DMA request sources. * @param saiBaseAddr Register base address of SAI module. * @param source SAI DMA request source. * @param enable Enable or disable. */ void SAI_HAL_RxSetDmaCmd(uint32_t saiBaseAddr, sai_dma_request_t source, bool enable); /*! * @brief Gets the status whether the Tx DMA source is enabled. * * The DMA sources can be: FIFO warning and FIFO request. * This function enables the DMA request from different DMA request sources. * @param saiBaseAddr Register base address of SAI module. * @param source SAI DMA request source. * @param Enable or disable. */ bool SAI_HAL_TxGetDmaCmd(uint32_t saiBaseAddr, sai_dma_request_t source); /*! * @brief Gets the status whether the Rx DMA source is enabled. * * The DMA sources can be: FIFO warning and FIFO request. * This function enables the DMA request from different DMA request sources. * @param saiBaseAddr Register base address of SAI module. * @param source SAI DMA request source. * @return Enable or disable. */ bool SAI_HAL_RxGetDmaCmd(uint32_t saiBaseAddr, sai_dma_request_t source); /*! * @brief Clears the Tx state flags. * * The function is used to clear the flags manually. It can clear word start, FIFO warning, FIFO error, * FIFO request flag. * @param saiBaseAddr Register base address of SAI module. * @param flag SAI state flag type. The flag can be word start, sync error, FIFO error/warning. */ void SAI_HAL_TxClearStateFlag(uint32_t saiBaseAddr, sai_state_flag_t flag); /*! * @brief Clears the Rx state flags. * * The function is used to clear the flags manually. It can clear word start, FIFO warning, FIFO error, * FIFO request flag. * @param saiBaseAddr Register base address of SAI module. * @param flag SAI state flag type. The flag can be word start, sync error, FIFO error/warning. */ void SAI_HAL_RxClearStateFlag(uint32_t saiBaseAddr, sai_state_flag_t flag); /*! * @brief Resets the Tx module. * * There are two kinds of resets: Software reset and FIFO reset. * Software reset: resets all transmitter internal logic, including the bit clock generation, * status flags and FIFO pointers. It does not reset the configuration registers. * FIFO reset: synchronizes the FIFO write pointer to the same value as the FIFO read pointer. * This empties the FIFO contents and is to be used after the Transmit FIFO Error Flag is set, * and before the FIFO is re-initialized and the Error Flag is cleared. * @param saiBaseAddr Register base address of SAI module. * @param type SAI reset type. */ void SAI_HAL_TxSetReset(uint32_t saiBaseAddr, sai_reset_type_t type); /*! * @brief Resets the Rx module. * * There are two kinds of resets: Software reset and FIFO reset. * Software reset: resets all transmitter internal logic, including the bit clock generation, * status flags and FIFO pointers. It does not reset the configuration registers. * FIFO reset: synchronizes the FIFO write pointer to the same value as the FIFO read pointer. * This empties the FIFO contents and is to be used after the Transmit FIFO Error Flag is set, * and before the FIFO is re-initialized and the Error Flag is cleared. * @param saiBaseAddr Register base address of SAI module. * @param type SAI reset type. */ void SAI_HAL_RxSetReset(uint32_t saiBaseAddr, sai_reset_type_t type); /*! * @brief Sets the Tx mask word of the frame. * * Each bit number represent the mask word index. For example, 0 represents mask the 0th word, 3 * represents mask 0th and 1st word. The TMR register can be different from frame to frame. If the * user wants a mono audio, set the mask to 0/1. * @param saiBaseAddr Register base address of SAI module. * @param mask Which bits need to be masked in a frame. */ static inline void SAI_HAL_TxSetWordMask(uint32_t saiBaseAddr, uint32_t mask) { BW_I2S_TMR_TWM(saiBaseAddr, mask); } /*! * @brief Sets the Rx mask word of the frame. * * Each bit number represent the mask word index. For example, 0 represents mask the 0th word, 3 * represents mask 0th and 1st word. The TMR register can be different from frame to frame. If the * user wants a mono audio, set the mask to 0/1. * @param saiBaseAddr Register base address of SAI module. * @param mask Which bits need to be masked in a frame. */ static inline void SAI_HAL_RxSetWordMask(uint32_t saiBaseAddr, uint32_t mask) { BW_I2S_RMR_RWM(saiBaseAddr, mask); } /*! * @brief Sets the Tx FIFO channel. * * A SAI saiBaseAddr includes a Tx and an Rx. Each has several channels according to * different platforms. A channel means a path for the audio data input/output. * @param saiBaseAddr Register base address of SAI module. * @param fifo_channel FIFO channel number. */ static inline void SAI_HAL_TxSetDataChn(uint32_t saiBaseAddr, uint8_t fifo_channel) { BW_I2S_TCR3_TCE(saiBaseAddr, 1u << fifo_channel); } /*! * @brief Sets the Rx FIFO channel. * * A SAI saiBaseAddr includes a Tx and a Rx. Each has several channels according to * different platforms. A channel means a path for the audio data input/output. * @param saiBaseAddr Register base address of SAI module. * @param fifo_channel FIFO channel number. */ static inline void SAI_HAL_RxSetDataChn(uint32_t saiBaseAddr, uint8_t fifo_channel) { BW_I2S_RCR3_RCE(saiBaseAddr, 1u << fifo_channel); } /*! * @brief Sets the running mode of the Tx. There is a debug mode, stop mode, and a normal mode. * * This function can set the working mode of the SAI saiBaseAddr. Stop mode is always * used in low power cases, and the debug mode disables the SAI after the current * transmit/receive is completed. * @param saiBaseAddr Register base address of SAI module. * @param run_mode SAI running mode. * @param enable Enable or disable a mode. */ void SAI_HAL_TxSetRunModeCmd(uint32_t saiBaseAddr, sai_run_mode_t run_mode, bool enable); /*! * @brief Sets the running mode of the Rx. There is a debug mode, stop mode, and a normal mode. * * This function can set the working mode of the SAI saiBaseAddr. Stop mode is always * used in low power cases, and the debug mode disables the SAI after the current * transmit/receive is completed. * @param saiBaseAddr Register base address of SAI module. * @param run_mode SAI running mode. * @param enable Enable or disable a mode. */ void SAI_HAL_RxSetRunModeCmd(uint32_t saiBaseAddr, sai_run_mode_t run_mode, bool enable); /*! * @brief Configures at which word the start of word flag is set in the Tx. * * @param saiBaseAddr Register base address of SAI module. * @param index Which word triggers word start flag. */ static inline void SAI_HAL_TxSetWordStartIndex(uint32_t saiBaseAddr,uint32_t index) { assert(index <= FSL_FEATURE_SAI_MAX_WORDS_PER_FRAME); BW_I2S_TCR3_WDFL(saiBaseAddr, index -1); } /*! * @brief Configures at which word the start of word flag is set in the Tx. * * @param saiBaseAddr Register base address of SAI module. * @param index Which word triggers word start flag. */ static inline void SAI_HAL_RxSetWordStartIndex(uint32_t saiBaseAddr,uint32_t index) { assert(index <= FSL_FEATURE_SAI_MAX_WORDS_PER_FRAME); BW_I2S_RCR3_WDFL(saiBaseAddr, index -1); } /*! * @brief Gets the state of the flags in the TCSR. * @param saiBaseAddr Register base address of SAI module. * @param flag State flag type, it can be FIFO error, FIFO warning and so on. * @return True if detect word start otherwise false. */ bool SAI_HAL_TxGetStateFlag(uint32_t saiBaseAddr, sai_state_flag_t flag); /*! * @brief Gets the state of the flags in the RCSR. * @param saiBaseAddr Register base address of SAI module. * @param flag State flag type, it can be FIFO error, FIFO warning and so on. * @return True if detect word start otherwise false. */ bool SAI_HAL_RxGetStateFlag(uint32_t saiBaseAddr, sai_state_flag_t flag); /*! * @brief Receives the data from the FIFO. * @param saiBaseAddr Register base address of SAI module. * @param rx_channel Rx FIFO channel. * @param data Pointer to the address to be written in. */ static inline uint32_t SAI_HAL_ReceiveData(uint32_t saiBaseAddr, uint32_t rx_channel) { assert(rx_channel < FSL_FEATURE_SAI_CHANNEL_COUNT); return HW_I2S_RDRn_RD(saiBaseAddr, rx_channel); } /*! * @brief Transmits data to the FIFO. * @param saiBaseAddr Register base address of SAI module. * @param tx_channel Tx FIFO channel. * @param data Data value which needs to be written into FIFO. */ static inline void SAI_HAL_SendData(uint32_t saiBaseAddr, uint32_t tx_channel, uint32_t data) { assert(tx_channel < FSL_FEATURE_SAI_CHANNEL_COUNT); HW_I2S_TDRn_WR(saiBaseAddr,tx_channel,data); } /*! * @brief Uses blocking to receive data. * @param saiBaseAddr The SAI saiBaseAddr. * @param rx_channel Rx FIFO channel. * @return Received data. */ uint32_t SAI_HAL_ReceiveDataBlocking(uint32_t saiBaseAddr, uint32_t rx_channel); /*! * @brief Uses blocking to send data. * @param saiBaseAddr The SAI saiBaseAddr. * @param tx_channel Tx FIFO channel. * @param data Data value which needs to be written into FIFO. */ void SAI_HAL_SendDataBlocking(uint32_t saiBaseAddr, uint32_t tx_channel, uint32_t data); #if FSL_FEATURE_SAI_HAS_ON_DEMAND_MODE /*! * @brief Tx on-demand mode setting. * * When set, the frame sync is generated internally. A frame sync is only generated when the * FIFO warning flag is clear. * @param saiBaseAddr Register base address of SAI module. * @param enable True means on demand mode enable, false means disable. */ static inline void SAI_HAL_TxSetOndemandCmd(uint32_t saiBaseAddr, bool enable) { BW_I2S_TCR4_ONDEM(saiBaseAddr, enable); } /*! * @brief Rx on-demand mode setting. * * When set, the frame sync is generated internally. A frame sync is only generated when the * FIFO warning flag is clear. * @param saiBaseAddr Register base address of SAI module. * @param enable True means on demand mode enable, false means disable. */ static inline void SAI_HAL_RxSetOndemandCmd(uint32_t saiBaseAddr, bool enable) { BW_I2S_RCR4_ONDEM(saiBaseAddr, enable); } #endif #if FSL_FEATURE_SAI_HAS_FIFO_FUNCTION_AFTER_ERROR /*! * @brief Tx FIFO continues on error. * * Configures when the SAI continues transmitting after a FIFO error has been detected. * @param saiBaseAddr Register base address of SAI module. * @param enable True means on demand mode enable, false means disable. */ static inline void SAI_HAL_TxSetFIFOErrorContinueCmd(uint32_t saiBaseAddr, bool enable) { BW_I2S_TCR4_FCONT(saiBaseAddr, enable); } /*! * @brief Rx FIFO continues on error. * * Configures when the SAI continues transmitting after a FIFO error has been detected. * @param saiBaseAddr Register base address of SAI module. * @param enable True means on demand mode enable, false means disable. */ static inline void SAI_HAL_RxSetFIFOErrorContinueCmd(uint32_t saiBaseAddr, bool enable) { BW_I2S_RCR4_FCONT(saiBaseAddr, enable); } #endif #if FSL_FEATURE_SAI_HAS_FIFO_PACKING /*! * @brief Tx FIFO packing mode setting. * * Enables packing 8-bit data or 16-bit data into each 32-bit FIFO word. If the word size is * greater than 8-bit or 16-bit, only the first 8-bit or 16-bits are loaded from the FIFO. * The first word in each frame always starts with a new 32-bit FIFO word and the first bit shifted * must be configured within the first packed word. When FIFO packing is enabled, the FIFO write * pointer only increments when the full 32-bit FIFO word has been written by software. * @param saiBaseAddr Register base address of SAI module. * @param mode FIFO packing mode. */ static inline void SAI_HAL_TxSetFIFOPackingMode(uint32_t saiBaseAddr, sai_fifo_packing_t mode) { BW_I2S_TCR4_FPACK(saiBaseAddr,mode); } /*! * @brief Rx FIFO packing mode setting. * * Enables packing 8-bit data or 16-bit data into each 32-bit FIFO word. If the word size is * greater than 8-bit or 16-bit, only the first 8-bit or 16-bits are loaded from the FIFO. * The first word in each frame always starts with a new 32-bit FIFO word and the first bit shifted * must be configured within the first packed word. When FIFO packing is enabled, the FIFO write * pointer only increments when the full 32-bit FIFO word has been written by software. * @param saiBaseAddr Register base address of SAI module. * @param mode FIFO packing mode. */ static inline void SAI_HAL_RxSetFIFOPackingMode(uint32_t saiBaseAddr, sai_fifo_packing_t mode) { BW_I2S_RCR4_FPACK(saiBaseAddr,mode); } #endif #if defined(__cplusplus) } #endif /*! @} */ #endif /* __FSL_SAI_HAL_H__ */ /******************************************************************************* * EOF *******************************************************************************/ ================================================ FILE: Zelig/mbed/TARGET_K64F/TARGET_Freescale/TARGET_KPSDK_MCUS/TARGET_KPSDK_CODE/hal/sdhc/fsl_sdhc_features.h ================================================ /* ** ################################################################### ** Version: rev. 1.0, 2014-05-14 ** Build: b140519 ** ** Abstract: ** Chip specific module features. ** ** Copyright: 2014 Freescale Semiconductor, Inc. ** All rights reserved. ** ** Redistribution and use in source and binary forms, with or without modification, ** are permitted provided that the following conditions are met: ** ** o Redistributions of source code must retain the above copyright notice, this list ** of conditions and the following disclaimer. ** ** o Redistributions in binary form must reproduce the above copyright notice, this ** list of conditions and the following disclaimer in the documentation and/or ** other materials provided with the distribution. ** ** o Neither the name of Freescale Semiconductor, Inc. nor the names of its ** contributors may be used to endorse or promote products derived from this ** software without specific prior written permission. ** ** THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ** ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED ** WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE ** DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT 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. ** ** http: www.freescale.com ** mail: support@freescale.com ** ** Revisions: ** - rev. 1.0 (2014-05-14) ** Customer release. ** ** ################################################################### */ #if !defined(__FSL_SDHC_FEATURES_H__) #define __FSL_SDHC_FEATURES_H__ #if defined(CPU_MK24FN1M0VDC12) || defined(CPU_MK24FN1M0VLL12) || defined(CPU_MK24FN1M0VLQ12) || defined(CPU_MK63FN1M0VLQ12) || \ defined(CPU_MK63FN1M0VMD12) || defined(CPU_MK64FX512VDC12) || defined(CPU_MK64FN1M0VDC12) || defined(CPU_MK64FX512VLL12) || \ defined(CPU_MK64FN1M0VLL12) || defined(CPU_MK64FX512VLQ12) || defined(CPU_MK64FN1M0VLQ12) || defined(CPU_MK64FX512VMD12) || \ defined(CPU_MK64FN1M0VMD12) /* @brief Has external DMA support (register bit VENDOR[EXTDMAEN]). */ #define FSL_FEATURE_SDHC_HAS_EXTERNAL_DMA_SUPPORT (1) /* @brief Has support of 3.0V voltage (register bit HTCAPBLT[VS30]). */ #define FSL_FEATURE_SDHC_HAS_V300_SUPPORT (0) /* @brief Has support of 1.8V voltage (register bit HTCAPBLT[VS18]). */ #define FSL_FEATURE_SDHC_HAS_V180_SUPPORT (0) #elif defined(CPU_MK65FN2M0CAC18) || defined(CPU_MK65FX1M0CAC18) || defined(CPU_MK65FN2M0VMI18) || defined(CPU_MK65FX1M0VMI18) || \ defined(CPU_MK66FN2M0VLQ18) || defined(CPU_MK66FX1M0VLQ18) || defined(CPU_MK66FN2M0VMD18) || defined(CPU_MK66FX1M0VMD18) /* @brief Has external DMA support (register bit VENDOR[EXTDMAEN]). */ #define FSL_FEATURE_SDHC_HAS_EXTERNAL_DMA_SUPPORT (0) /* @brief Has support of 3.0V voltage (register bit HTCAPBLT[VS30]). */ #define FSL_FEATURE_SDHC_HAS_V300_SUPPORT (0) /* @brief Has support of 1.8V voltage (register bit HTCAPBLT[VS18]). */ #define FSL_FEATURE_SDHC_HAS_V180_SUPPORT (0) #elif defined(CPU_MK70FN1M0VMF12) || defined(CPU_MK70FX512VMF12) || defined(CPU_MK70FN1M0VMF15) || defined(CPU_MK70FX512VMF15) || \ defined(CPU_MK70FN1M0VMJ12) || defined(CPU_MK70FX512VMJ12) || defined(CPU_MK70FN1M0VMJ15) || defined(CPU_MK70FX512VMJ15) /* @brief Has external DMA support (register bit VENDOR[EXTDMAEN]). */ #define FSL_FEATURE_SDHC_HAS_EXTERNAL_DMA_SUPPORT (1) /* @brief Has support of 3.0V voltage (register bit HTCAPBLT[VS30]). */ #define FSL_FEATURE_SDHC_HAS_V300_SUPPORT (1) /* @brief Has support of 1.8V voltage (register bit HTCAPBLT[VS18]). */ #define FSL_FEATURE_SDHC_HAS_V180_SUPPORT (1) #else #define MBED_NO_SDHC #endif #endif /* __FSL_SDHC_FEATURES_H__ */ /******************************************************************************* * EOF ******************************************************************************/ ================================================ FILE: Zelig/mbed/TARGET_K64F/TARGET_Freescale/TARGET_KPSDK_MCUS/TARGET_KPSDK_CODE/hal/sdhc/fsl_sdhc_hal.h ================================================ /* * Copyright (c) 2013 - 2014, Freescale Semiconductor, Inc. * All rights reserved. * * Redistribution and use in source and binary forms, with or without modification, * are permitted provided that the following conditions are met: * * o Redistributions of source code must retain the above copyright notice, this list * of conditions and the following disclaimer. * * o Redistributions in binary form must reproduce the above copyright notice, this * list of conditions and the following disclaimer in the documentation and/or * other materials provided with the distribution. * * o Neither the name of Freescale Semiconductor, Inc. nor the names of its * contributors may be used to endorse or promote products derived from this * software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT 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. */ #ifndef __FSL_SDHC_HAL_H__ #define __FSL_SDHC_HAL_H__ #include #include #include "fsl_device_registers.h" #include "fsl_sdhc_features.h" #ifndef MBED_NO_SDHC /*! @addtogroup sdhc_hal */ /*! @{ */ /* PRSSTA */ #define SDHC_HAL_DAT0_LEVEL (BM_SDHC_PRSSTAT_DLSL & (1 << 24)) /* XFERTYP */ #define SDHC_HAL_MAX_BLOCK_COUNT ((1 << BS_SDHC_BLKATTR_BLKCNT) - 1) #define SDHC_HAL_ENABLE_DMA BM_SDHC_XFERTYP_DMAEN #define SDHC_HAL_CMD_TYPE_SUSPEND (BF_SDHC_XFERTYP_CMDTYP(1)) #define SDHC_HAL_CMD_TYPE_RESUME (BF_SDHC_XFERTYP_CMDTYP(2)) #define SDHC_HAL_CMD_TYPE_ABORT (BF_SDHC_XFERTYP_CMDTYP(3)) #define SDHC_HAL_ENABLE_BLOCK_COUNT BM_SDHC_XFERTYP_BCEN #define SDHC_HAL_ENABLE_AUTO_CMD12 BM_SDHC_XFERTYP_AC12EN #define SDHC_HAL_ENABLE_DATA_READ BM_SDHC_XFERTYP_DTDSEL #define SDHC_HAL_MULTIPLE_BLOCK BM_SDHC_XFERTYP_MSBSEL #define SDHC_HAL_RESP_LEN_136 ((0x1 << BP_SDHC_XFERTYP_RSPTYP) & BM_SDHC_XFERTYP_RSPTYP) #define SDHC_HAL_RESP_LEN_48 ((0x2 << BP_SDHC_XFERTYP_RSPTYP) & BM_SDHC_XFERTYP_RSPTYP) #define SDHC_HAL_RESP_LEN_48_BC ((0x3 << BP_SDHC_XFERTYP_RSPTYP) & BM_SDHC_XFERTYP_RSPTYP) #define SDHC_HAL_ENABLE_CRC_CHECK BM_SDHC_XFERTYP_CCCEN #define SDHC_HAL_ENABLE_INDEX_CHECK BM_SDHC_XFERTYP_CICEN #define SDHC_HAL_DATA_PRESENT BM_SDHC_XFERTYP_DPSEL /* SYSCTL */ #define SDHC_HAL_MAX_DVS (16U) #define SDHC_HAL_INITIAL_DVS (1U) /* initial value of divisor to calculate clock rate */ #define SDHC_HAL_INITIAL_CLKFS (2U) /* initial value of clock selector to calculate clock rate */ #define SDHC_HAL_NEXT_DVS(x) do { ((x) += 1); } while(0) #define SDHC_HAL_PREV_DVS(x) do { ((x) -= 1); } while(0) #define SDHC_HAL_MAX_CLKFS (256U) #define SDHC_HAL_NEXT_CLKFS(x) do { ((x) <<= 1); } while(0) #define SDHC_HAL_PREV_CLKFS(x) do { ((x) >>= 1); } while(0) /* IRQSTAT */ #define SDHC_HAL_CMD_COMPLETE_INT BM_SDHC_IRQSTAT_CC #define SDHC_HAL_DATA_COMPLETE_INT BM_SDHC_IRQSTAT_TC #define SDHC_HAL_BLOCK_GAP_EVENT_INT BM_SDHC_IRQSTAT_BGE #define SDHC_HAL_DMA_INT BM_SDHC_IRQSTAT_DINT #define SDHC_HAL_DMA_ERR_INT BM_SDHC_IRQSTAT_DMAE #define SDHC_HAL_BUF_WRITE_READY_INT BM_SDHC_IRQSTAT_BWR #define SDHC_HAL_BUF_READ_READY_INT BM_SDHC_IRQSTAT_BRR #define SDHC_HAL_CARD_INSERTION_INT BM_SDHC_IRQSTAT_CINS #define SDHC_HAL_CARD_REMOVAL_INT BM_SDHC_IRQSTAT_CRM #define SDHC_HAL_CARD_INT BM_SDHC_IRQSTAT_CINT #define SDHC_HAL_CMD_TIMEOUT_ERR_INT BM_SDHC_IRQSTAT_CTOE #define SDHC_HAL_CMD_CRC_ERR_INT BM_SDHC_IRQSTAT_CCE #define SDHC_HAL_CMD_END_BIT_ERR_INT BM_SDHC_IRQSTAT_CEBE #define SDHC_HAL_CMD_INDEX_ERR_INT BM_SDHC_IRQSTAT_CIE #define SDHC_HAL_DATA_TIMEOUT_ERR_INT BM_SDHC_IRQSTAT_DTOE #define SDHC_HAL_DATA_CRC_ERR_INT BM_SDHC_IRQSTAT_DCE #define SDHC_HAL_DATA_END_BIT_ERR_INT BM_SDHC_IRQSTAT_DEBE #define SDHC_HAL_AUTO_CMD12_ERR_INT BM_SDHC_IRQSTAT_AC12E #define SDHC_HAL_CMD_ERR_INT ((uint32_t)(SDHC_HAL_CMD_TIMEOUT_ERR_INT | \ SDHC_HAL_CMD_CRC_ERR_INT | \ SDHC_HAL_CMD_END_BIT_ERR_INT | \ SDHC_HAL_CMD_INDEX_ERR_INT)) #define SDHC_HAL_DATA_ERR_INT ((uint32_t)(SDHC_HAL_DATA_TIMEOUT_ERR_INT | \ SDHC_HAL_DATA_CRC_ERR_INT | \ SDHC_HAL_DATA_END_BIT_ERR_INT)) #define SDHC_HAL_DATA_ALL_INT ((uint32_t)(SDHC_HAL_DATA_ERR_INT | \ SDHC_HAL_DATA_COMPLETE_INT | \ SDHC_HAL_BUF_READ_READY_INT | \ SDHC_HAL_BUF_WRITE_READY_INT | \ SDHC_HAL_DMA_ERR_INT | SDHC_HAL_DMA_INT)) #define SDHC_HAL_CMD_ALL_INT ((uint32_t)(SDHC_HAL_CMD_ERR_INT | \ SDHC_HAL_CMD_COMPLETE_INT | \ SDHC_HAL_AUTO_CMD12_ERR_INT)) #define SDHC_HAL_CD_ALL_INT ((uint32_t)(SDHC_HAL_CARD_INSERTION_INT | \ SDHC_HAL_CARD_REMOVAL_INT)) #define SDHC_HAL_ALL_ERR_INT ((uint32_t)(SDHC_HAL_CMD_ERR_INT | \ SDHC_HAL_DATA_ERR_INT | \ SDHC_HAL_AUTO_CMD12_ERR_INT | \ SDHC_HAL_DMA_ERR_INT)) /* AC12ERR */ #define SDHC_HAL_ACMD12_NOT_EXEC_ERR BM_SDHC_AC12ERR_AC12NE #define SDHC_HAL_ACMD12_TIMEOUT_ERR BM_SDHC_AC12ERR_AC12TOE #define SDHC_HAL_ACMD12_END_BIT_ERR BM_SDHC_AC12ERR_AC12EBE #define SDHC_HAL_ACMD12_CRC_ERR BM_SDHC_AC12ERR_AC12CE #define SDHC_HAL_ACMD12_INDEX_ERR BM_SDHC_AC12ERR_AC12IE #define SDHC_HAL_ACMD12_NOT_ISSUE_ERR BM_SDHC_AC12ERR_CNIBAC12E /* HTCAPBLT */ #define SDHC_HAL_SUPPORT_ADMA BM_SDHC_HTCAPBLT_ADMAS #define SDHC_HAL_SUPPORT_HIGHSPEED BM_SDHC_HTCAPBLT_HSS #define SDHC_HAL_SUPPORT_DMA BM_SDHC_HTCAPBLT_DMAS #define SDHC_HAL_SUPPORT_SUSPEND_RESUME BM_SDHC_HTCAPBLT_SRS #define SDHC_HAL_SUPPORT_3_3_V BM_SDHC_HTCAPBLT_VS33 #define SDHC_HAL_SUPPORT_3_0_V BM_SDHC_HTCAPBLT_VS30 #define SDHC_HAL_SUPPORT_1_8_V BM_SDHC_HTCAPBLT_VS18 /* FEVT */ #define SDHC_HAL_ACMD12_NOT_EXEC_ERR_EVENT BM_SDHC_FEVT_AC12NE #define SDHC_HAL_ACMD12_TIMEOUT_ERR_EVENT BM_SDHC_FEVT_AC12TOE #define SDHC_HAL_ACMD12_CRC_ERR_EVENT BM_SDHC_FEVT_AC12CE #define SDHC_HAL_ACMD12_END_BIT_ERR_EVENT BM_SDHC_FEVT_AC12EBE #define SDHC_HAL_ACMD12_INDEX_ERR_EVENT BM_SDHC_FEVT_AC12IE #define SDHC_HAL_ACMD12_NOT_ISSUE_ERR_EVENT BM_SDHC_FEVT_CNIBAC12E #define SDHC_HAL_CMD_TIMEOUT_ERR_EVENT BM_SDHC_FEVT_CTOE #define SDHC_HAL_CMD_CRC_ERR_EVENT BM_SDHC_FEVT_CCE #define SDHC_HAL_CMD_END_BIT_ERR_EVENT BM_SDHC_FEVT_CEBE #define SDHC_HAL_CMD_INDEX_ERR_EVENT BM_SDHC_FEVT_CIE #define SDHC_HAL_DATA_TIMEOUT_ERR_EVENT BM_SDHC_FEVT_DTOE #define SDHC_HAL_DATA_CRC_ERR_EVENT BM_SDHC_FEVT_DCE #define SDHC_HAL_DATA_END_BIT_ERR_EVENT BM_SDHC_FEVT_DEBE #define SDHC_HAL_ACMD12_ERR_EVENT BM_SDHC_FEVT_AC12E #define SDHC_HAL_CARD_INT_EVENT BM_SDHC_FEVT_CINT #define SDHC_HAL_DMA_ERROR_EVENT BM_SDHC_FEVT_DMAE /* MMCBOOT */ typedef enum _sdhc_hal_mmcboot { kSdhcHalMmcbootNormal = 0, kSdhcHalMmcbootAlter = 1, } sdhc_hal_mmcboot_t; /* PROCTL */ typedef enum _sdhc_hal_led { kSdhcHalLedOff = 0, kSdhcHalLedOn = 1, } sdhc_hal_led_t; typedef enum _sdhc_hal_dtw { kSdhcHalDtw1Bit = 0, kSdhcHalDtw4Bit = 1, kSdhcHalDtw8Bit = 2, } sdhc_hal_dtw_t; typedef enum _sdhc_hal_endian { kSdhcHalEndianBig = 0, kSdhcHalEndianHalfWordBig = 1, kSdhcHalEndianLittle = 2, } sdhc_hal_endian_t; typedef enum _sdhc_hal_dma_mode { kSdhcHalDmaSimple = 0, kSdhcHalDmaAdma1 = 1, kSdhcHalDmaAdma2 = 2, } sdhc_hal_dma_mode_t; #define SDHC_HAL_ADMA1_ADDR_ALIGN (4096) #define SDHC_HAL_ADMA1_LEN_ALIGN (4096) #define SDHC_HAL_ADMA2_ADDR_ALIGN (4) #define SDHC_HAL_ADMA2_LEN_ALIGN (4) /* * ADMA1 descriptor table * |------------------------|---------|--------------------------| * | Address/page Field |reserved | Attribute | * |------------------------|---------|--------------------------| * |31 12|11 6|05 |04 |03|02 |01 |00 | * |------------------------|---------|----|----|--|---|---|-----| * | address or data length | 000000 |Act2|Act1| 0|Int|End|Valid| * |------------------------|---------|----|----|--|---|---|-----| * * * |------|------|-----------------|-------|-------------| * | Act2 | Act1 | Comment | 31-28 | 27 - 12 | * |------|------|-----------------|---------------------| * | 0 | 0 | No op | Don't care | * |------|------|-----------------|-------|-------------| * | 0 | 1 | Set data length | 0000 | Data Length | * |------|------|-----------------|-------|-------------| * | 1 | 0 | Transfer data | Data address | * |------|------|-----------------|---------------------| * | 1 | 1 | Link descriptor | Descriptor address | * |------|------|-----------------|---------------------| * */ typedef uint32_t sdhc_hal_adma1_descriptor_t; #define SDHC_HAL_ADMA1_DESC_VALID_MASK (1 << 0) #define SDHC_HAL_ADMA1_DESC_END_MASK (1 << 1) #define SDHC_HAL_ADMA1_DESC_INT_MASK (1 << 2) #define SDHC_HAL_ADMA1_DESC_ACT1_MASK (1 << 4) #define SDHC_HAL_ADMA1_DESC_ACT2_MASK (1 << 5) #define SDHC_HAL_ADMA1_DESC_TYPE_NOP (SDHC_HAL_ADMA1_DESC_VALID_MASK) #define SDHC_HAL_ADMA1_DESC_TYPE_TRAN (SDHC_HAL_ADMA1_DESC_ACT2_MASK | SDHC_HAL_ADMA1_DESC_VALID_MASK) #define SDHC_HAL_ADMA1_DESC_TYPE_LINK (SDHC_HAL_ADMA1_DESC_ACT1_MASK | SDHC_HAL_ADMA1_DESC_ACT2_MASK | SDHC_HAL_ADMA1_DESC_VALID_MASK) #define SDHC_HAL_ADMA1_DESC_TYPE_SET (SDHC_HAL_ADMA1_DESC_ACT1_MASK | SDHC_HAL_ADMA1_DESC_VALID_MASK) #define SDHC_HAL_ADMA1_DESC_ADDRESS_SHIFT (12) #define SDHC_HAL_ADMA1_DESC_ADDRESS_MASK (0xFFFFFU) #define SDHC_HAL_ADMA1_DESC_LEN_SHIFT (12) #define SDHC_HAL_ADMA1_DESC_LEN_MASK (0xFFFFU) #define SDHC_HAL_ADMA1_DESC_MAX_LEN_PER_ENTRY (SDHC_HAL_ADMA1_DESC_LEN_MASK + 1) /* * ADMA2 descriptor table * |----------------|---------------|-------------|--------------------------| * | Address Field | length | reserved | Attribute | * |----------------|---------------|-------------|--------------------------| * |63 32|31 16|15 06|05 |04 |03|02 |01 |00 | * |----------------|---------------|-------------|----|----|--|---|---|-----| * | 32-bit address | 16-bit length | 0000000000 |Act2|Act1| 0|Int|End|Valid| * |----------------|---------------|-------------|----|----|--|---|---|-----| * * * | Act2 | Act1 | Comment | Operation | * |------|------|-----------------|-------------------------------------------------------------------| * | 0 | 0 | No op | Don't care | * |------|------|-----------------|-------------------------------------------------------------------| * | 0 | 1 | Reserved | Read this line and go to next one | * |------|------|-----------------|-------------------------------------------------------------------| * | 1 | 0 | Transfer data | Transfer data with address and length set in this descriptor line | * |------|------|-----------------|-------------------------------------------------------------------| * | 1 | 1 | Link descriptor | Link to another descriptor | * |------|------|-----------------|-------------------------------------------------------------------| * */ typedef struct SdhcHalAdma2Descriptor { uint32_t attribute; uint32_t *address; } sdhc_hal_adma2_descriptor_t; #define SDHC_HAL_ADMA2_DESC_VALID_MASK (1 << 0) #define SDHC_HAL_ADMA2_DESC_END_MASK (1 << 1) #define SDHC_HAL_ADMA2_DESC_INT_MASK (1 << 2) #define SDHC_HAL_ADMA2_DESC_ACT1_MASK (1 << 4) #define SDHC_HAL_ADMA2_DESC_ACT2_MASK (1 << 5) #define SDHC_HAL_ADMA2_DESC_TYPE_NOP (SDHC_HAL_ADMA2_DESC_VALID_MASK) #define SDHC_HAL_ADMA2_DESC_TYPE_RCV (SDHC_HAL_ADMA2_DESC_ACT1_MASK | SDHC_HAL_ADMA2_DESC_VALID_MASK) #define SDHC_HAL_ADMA2_DESC_TYPE_TRAN (SDHC_HAL_ADMA2_DESC_ACT2_MASK | SDHC_HAL_ADMA2_DESC_VALID_MASK) #define SDHC_HAL_ADMA2_DESC_TYPE_LINK (SDHC_HAL_ADMA2_DESC_ACT1_MASK | SDHC_HAL_ADMA2_DESC_ACT2_MASK | SDHC_HAL_ADMA2_DESC_VALID_MASK) #define SDHC_HAL_ADMA2_DESC_LEN_SHIFT (16) #define SDHC_HAL_ADMA2_DESC_LEN_MASK (0xFFFFU) #define SDHC_HAL_ADMA2_DESC_MAX_LEN_PER_ENTRY (SDHC_HAL_ADMA2_DESC_LEN_MASK + 1) #define SDHC_HAL_RST_TYPE_ALL BM_SDHC_SYSCTL_RSTA #define SDHC_HAL_RST_TYPE_CMD BM_SDHC_SYSCTL_RSTC #define SDHC_HAL_RST_TYPE_DATA BM_SDHC_SYSCTL_RSTD #define SDHC_HAL_MAX_BLKLEN_512B (0U) #define SDHC_HAL_MAX_BLKLEN_1024B (1U) #define SDHC_HAL_MAX_BLKLEN_2048B (2U) #define SDHC_HAL_MAX_BLKLEN_4096B (3U) /************************************************************************************************* * API ************************************************************************************************/ #if defined(__cplusplus) extern "C" { #endif /*! @name SDHC HAL FUNCTION */ /*@{ */ /*! * @brief Configures the DMA address. * * @param baseAddr SDHC base address * @param address the DMA address */ static inline void SDHC_HAL_SetDmaAddress(uint32_t baseAddr, uint32_t address) { HW_SDHC_DSADDR_WR(baseAddr, BF_SDHC_DSADDR_DSADDR(address)); } /*! * @brief Gets the DMA address. * * @param baseAddr SDHC base address * @return the DMA address */ static inline uint32_t SDHC_HAL_GetDmaAddress(uint32_t baseAddr) { return HW_SDHC_DSADDR_RD(baseAddr); } /*! * @brief Gets the block size configured. * * @param baseAddr SDHC base address * @return the block size already configured */ static inline uint32_t SDHC_HAL_GetBlockSize(uint32_t baseAddr) { return BR_SDHC_BLKATTR_BLKSIZE(baseAddr); } /*! * @brief Sets the block size. * * @param baseAddr SDHC base address * @param blockSize the block size */ static inline void SDHC_HAL_SetBlockSize(uint32_t baseAddr, uint32_t blockSize) { BW_SDHC_BLKATTR_BLKSIZE(baseAddr, blockSize); } /*! * @brief Sets the block count. * * @param baseAddr SDHC base address * @param blockCount the block count */ static inline void SDHC_HAL_SetBlockCount(uint32_t baseAddr, uint32_t blockCount) { BW_SDHC_BLKATTR_BLKCNT(baseAddr, blockCount); } /*! * @brief Gets the block count configured. * * @param baseAddr SDHC base address * @return the block count already configured */ static inline uint32_t SDHC_HAL_GetBlockCount(uint32_t baseAddr) { return BR_SDHC_BLKATTR_BLKCNT(baseAddr); } /*! * @brief Configures the command argument. * * @param baseAddr SDHC base address * @param arg the command argument */ static inline void SDHC_HAL_SetCmdArgument(uint32_t baseAddr, uint32_t arg) { BW_SDHC_CMDARG_CMDARG(baseAddr, arg); } /*! * @brief Sends a command. * * @param baseAddr SDHC base address * @param index command index * @param flags transfer type flags */ static inline void SDHC_HAL_SendCmd(uint32_t baseAddr, uint32_t index, uint32_t flags) { HW_SDHC_XFERTYP_WR(baseAddr, ((index << BP_SDHC_XFERTYP_CMDINX) & BM_SDHC_XFERTYP_CMDINX) | (flags & ( BM_SDHC_XFERTYP_DMAEN | BM_SDHC_XFERTYP_MSBSEL | BM_SDHC_XFERTYP_DPSEL | BM_SDHC_XFERTYP_CMDTYP | BM_SDHC_XFERTYP_BCEN | BM_SDHC_XFERTYP_CICEN | BM_SDHC_XFERTYP_CCCEN | BM_SDHC_XFERTYP_RSPTYP | BM_SDHC_XFERTYP_DTDSEL | BM_SDHC_XFERTYP_AC12EN))); } /*! * @brief Fills the the data port. * * @param baseAddr SDHC base address * @param data the data about to be sent */ static inline void SDHC_HAL_SetData(uint32_t baseAddr, uint32_t data) { HW_SDHC_DATPORT_WR(baseAddr, data); } /*! * @brief Retrieves the data from the data port. * * @param baseAddr SDHC base address * @return data the data read */ static inline uint32_t SDHC_HAL_GetData(uint32_t baseAddr) { return BR_SDHC_DATPORT_DATCONT(baseAddr); } /*! * @brief Checks whether the command inhibit bit is set or not. * * @param baseAddr SDHC base address * @return 1 if command inhibit, 0 if not. */ static inline uint32_t SDHC_HAL_IsCmdInhibit(uint32_t baseAddr) { return BR_SDHC_PRSSTAT_CIHB(baseAddr); } /*! * @brief Checks whether data inhibit bit is set or not. * * @param baseAddr SDHC base address * @return 1 if data inhibit, 0 if not. */ static inline uint32_t SDHC_HAL_IsDataInhibit(uint32_t baseAddr) { return BR_SDHC_PRSSTAT_CDIHB(baseAddr); } /*! * @brief Checks whether data line is active. * * @param baseAddr SDHC base address * @return 1 if it's active, 0 if not. */ static inline uint32_t SDHC_HAL_IsDataLineActive(uint32_t baseAddr) { return BR_SDHC_PRSSTAT_DLA(baseAddr); } /*! * @brief Checks whether the SD clock is stable or not. * * @param baseAddr SDHC base address * @return 1 if it's stable, 0 if not. */ static inline uint32_t SDHC_HAL_IsSdClockStable(uint32_t baseAddr) { return BR_SDHC_PRSSTAT_SDSTB(baseAddr); } /*! * @brief Checks whether the IPG clock is off or not. * * @param baseAddr SDHC base address * @return 1 if it's off, 0 if not. */ static inline uint32_t SDHC_HAL_IsIpgClockOff(uint32_t baseAddr) { return BR_SDHC_PRSSTAT_IPGOFF(baseAddr); } /*! * @brief Checks whether the system clock is off or not. * * @param baseAddr SDHC base address * @return 1 if it's off, 0 if not. */ static inline uint32_t SDHC_HAL_IsSysClockOff(uint32_t baseAddr) { return BR_SDHC_PRSSTAT_HCKOFF(baseAddr); } /*! * @brief Checks whether the peripheral clock is off or not. * * @param baseAddr SDHC base address. * @return 1 if it's off, 0 if not. */ static inline uint32_t SDHC_HAL_IsPeripheralClockOff(uint32_t baseAddr) { return BR_SDHC_PRSSTAT_PEROFF(baseAddr); } /*! * @brief Checks whether the SD clock is off or not. * * @param baseAddr SDHC base address * @return 1 if it's off, 0 if not. */ static inline uint32_t SDHC_HAL_IsSdClkOff(uint32_t baseAddr) { return BR_SDHC_PRSSTAT_SDOFF(baseAddr); } /*! * @brief Checks whether the write transfer is active or not. * * @param baseAddr SDHC base address * @return 1 if it's active, 0 if not. */ static inline uint32_t SDHC_HAL_IsWriteTransferActive(uint32_t baseAddr) { return BR_SDHC_PRSSTAT_WTA(baseAddr); } /*! * @brief Checks whether the read transfer is active or not. * * @param baseAddr SDHC base address * @return 1 if it's off, 0 if not. */ static inline uint32_t SDHC_HAL_IsReadTransferActive(uint32_t baseAddr) { return BR_SDHC_PRSSTAT_RTA(baseAddr); } /*! * @brief Check whether the buffer write is enabled or not. * * @param baseAddr SDHC base address * @return 1 if it's isEnabledd, 0 if not. */ static inline uint32_t SDHC_HAL_IsBuffWriteEnabled(uint32_t baseAddr) { return BR_SDHC_PRSSTAT_BWEN(baseAddr); } /*! * @brief Checks whether the buffer read is enabled or not. * * @param baseAddr SDHC base address * @return 1 if it's isEnabledd, 0 if not. */ static inline uint32_t SDHC_HAL_IsBuffReadEnabled(uint32_t baseAddr) { return BR_SDHC_PRSSTAT_BREN(baseAddr); } /*! * @brief Checks whether the card is inserted or not. * * @param baseAddr SDHC base address. * @return 1 if it's inserted, 0 if not. */ static inline uint32_t SDHC_HAL_IsCardInserted(uint32_t baseAddr) { return BR_SDHC_PRSSTAT_CINS(baseAddr); } /*! * @brief Checks whether the command line signal is high or not. * * @param baseAddr SDHC base address * @return 1 if it's high, 0 if not. */ static inline uint32_t SDHC_HAL_IsCmdLineLevelHigh(uint32_t baseAddr) { return BR_SDHC_PRSSTAT_CLSL(baseAddr); } /*! * @brief Gets the data line signal level or not. * * @param baseAddr SDHC base address * @return [7:0] data line signal level */ static inline uint32_t SDHC_HAL_GetDataLineLevel(uint32_t baseAddr) { return BR_SDHC_PRSSTAT_DLSL(baseAddr); } /*! * @brief Sets the LED state. * * @param baseAddr SDHC base address * @param state the LED state */ static inline void SDHC_HAL_SetLedState(uint32_t baseAddr, sdhc_hal_led_t state) { BW_SDHC_PROCTL_LCTL(baseAddr, state); } /*! * @brief Sets the data transfer width. * * @param baseAddr SDHC base address * @param dtw data transfer width */ static inline void SDHC_HAL_SetDataTransferWidth(uint32_t baseAddr, sdhc_hal_dtw_t dtw) { BW_SDHC_PROCTL_DTW(baseAddr, dtw); } /*! * @brief Checks whether the DAT3 is taken as card detect pin. * * @param baseAddr SDHC base address * @return if DAT3 as card detect pin is enabled */ static inline bool SDHC_HAL_IsD3cdEnabled(uint32_t baseAddr) { return BR_SDHC_PROCTL_D3CD(baseAddr); } /*! * @brief Enables the DAT3 as a card detect pin. * * @param baseAddr SDHC base address * @param enable to enable DAT3 as card detect pin */ static inline void SDHC_HAL_SetD3cd(uint32_t baseAddr, bool enable) { BW_SDHC_PROCTL_D3CD(baseAddr, enable ? 1 : 0); } /*! * @brief Configures the endian mode. * * @param baseAddr SDHC base address * @param endianMode endian mode */ static inline void SDHC_HAL_SetEndian(uint32_t baseAddr, sdhc_hal_endian_t endianMode) { BW_SDHC_PROCTL_EMODE(baseAddr, endianMode); } /*! * @brief Gets the card detect test level. * * @param baseAddr SDHC base address * @return card detect test level */ static inline uint32_t SDHC_HAL_GetCdTestLevel(uint32_t baseAddr) { return BR_SDHC_PROCTL_CDTL(baseAddr); } /*! * @brief Enables the card detect test. * * @param baseAddr SDHC base address * @param enable to enable card detect signal for test purpose */ static inline void SDHC_HAL_SetCdTest(uint32_t baseAddr, bool enable) { BW_SDHC_PROCTL_CDSS(baseAddr, enable ? 1 : 0); } /*! * @brief Sets the DMA mode. * * @param baseAddr SDHC base address * @param dmaMode the DMA mode */ static inline void SDHC_HAL_SetDmaMode(uint32_t baseAddr, sdhc_hal_dma_mode_t dmaMode) { BW_SDHC_PROCTL_DMAS(baseAddr, dmaMode); } /*! * @brief Enables stop at the block gap. * * @param baseAddr SDHC base address * @param enable to stop at block gap request */ static inline void SDHC_HAL_SetStopAtBlockGap(uint32_t baseAddr, bool enable) { BW_SDHC_PROCTL_SABGREQ(baseAddr, enable ? 1 : 0); } /*! * @brief Restarts a transaction which has stopped at the block gap. * * @param baseAddr SDHC base address */ static inline void SDHC_HAL_SetContinueRequest(uint32_t baseAddr) { BW_SDHC_PROCTL_CREQ(baseAddr, 1); } /*! * @brief Enables the read wait control for the SDIO cards. * * @param baseAddr SDHC base address * @param enable to enable read wait control */ static inline void SDHC_HAL_SetReadWaitCtrl(uint32_t baseAddr, bool enable) { BW_SDHC_PROCTL_RWCTL(baseAddr, enable ? 1 : 0); } /*! * @brief Enables stop at the block gap requests. * * @param baseAddr SDHC base address * @param enable to enable interrupt at block gap */ static inline void SDHC_HAL_SetIntStopAtBlockGap(uint32_t baseAddr, bool enable) { BW_SDHC_PROCTL_IABG(baseAddr, enable ? 1 : 0); } /*! * @brief Enables wakeup event on the card interrupt. * * @param baseAddr SDHC base address * @param enable to enable wakeup event on card interrupt */ static inline void SDHC_HAL_SetWakeupOnCardInt(uint32_t baseAddr, bool enable) { BW_SDHC_PROCTL_WECINT(baseAddr, enable ? 1 : 0); } /*! * @brief Enables wakeup event on the card insertion. * * @param baseAddr SDHC base address * @param enable to enable wakeup event on card insertion */ static inline void SDHC_HAL_SetWakeupOnCardInsertion(uint32_t baseAddr, bool enable) { BW_SDHC_PROCTL_WECINS(baseAddr, enable ? 1 : 0); } /*! * @brief Enables wakeup event on card removal. * * @param baseAddr SDHC base address * @param enable to enable wakeup event on card removal */ static inline void SDHC_HAL_SetWakeupOnCardRemoval(uint32_t baseAddr, bool enable) { BW_SDHC_PROCTL_WECRM(baseAddr, enable ? 1 : 0); } /*! * @brief Enables the IPG clock and no automatic clock gating off. * * @param baseAddr SDHC base address * @param enable to enable IPG clock */ static inline void SDHC_HAL_SetIpgClock(uint32_t baseAddr, bool enable) { BW_SDHC_SYSCTL_IPGEN(baseAddr, enable ? 1 : 0); } /*! * @brief Enables the system clock and no automatic clock gating off. * * @param baseAddr SDHC base address * @param enable to enable SYS clock */ static inline void SDHC_HAL_SetSysClock(uint32_t baseAddr, bool enable) { BW_SDHC_SYSCTL_HCKEN(baseAddr, enable ? 1 : 0); } /*! * @brief Enables the peripheral clock and no automatic clock gating off. * * @param baseAddr SDHC base address * @param enable to enable Peripheral clock */ static inline void SDHC_HAL_SetPeripheralClock(uint32_t baseAddr, bool enable) { BW_SDHC_SYSCTL_PEREN(baseAddr, enable ? 1 : 0); } /*! * @brief Enables the SD clock. It should be disabled before changing the SD clock * frequency. * * @param baseAddr SDHC base address * @param enable to enable SD clock or not */ static inline void SDHC_HAL_SetSdClock(uint32_t baseAddr, bool enable) { BW_SDHC_SYSCTL_SDCLKEN(baseAddr, enable ? 1 : 0); } /*! * @brief Sets the SD clock frequency divisor. * * @param baseAddr SDHC base address * @param divisor the divisor */ static inline void SDHC_HAL_SetClockDivisor(uint32_t baseAddr, uint32_t divisor) { BW_SDHC_SYSCTL_DVS(baseAddr, divisor); } /*! * @brief Sets the SD clock frequency select. * * @param baseAddr SDHC base address * @param frequency the frequency selector */ static inline void SDHC_HAL_SetClockFrequency(uint32_t baseAddr, uint32_t frequency) { BW_SDHC_SYSCTL_SDCLKFS(baseAddr, frequency); } /*! * @brief Sets the data timeout counter value. * * @param baseAddr SDHC base address * @param timeout Data timeout counter value */ static inline void SDHC_HAL_SetDataTimeout(uint32_t baseAddr, uint32_t timeout) { BW_SDHC_SYSCTL_DTOCV(baseAddr, timeout); } /*! * @brief Gets the current interrupt status. * * @param baseAddr SDHC base address * @return current interrupt flags */ static inline uint32_t SDHC_HAL_GetIntFlags(uint32_t baseAddr) { return HW_SDHC_IRQSTAT_RD(baseAddr); } /*! * @brief Clears a specified interrupt status. * * @param baseAddr SDHC base address * @param mask to specify interrupts' flags to be cleared */ static inline void SDHC_HAL_ClearIntFlags(uint32_t baseAddr, uint32_t mask) { HW_SDHC_IRQSTAT_WR(baseAddr, mask); } /*! * @brief Gets the currently enabled interrupt signal. * * @param baseAddr SDHC base address * @return currently enabled interrupt signal */ static inline uint32_t SDHC_HAL_GetIntSignal(uint32_t baseAddr) { return HW_SDHC_IRQSIGEN_RD(baseAddr); } /*! * @brief Gets the currently enabled interrupt state. * * @param baseAddr SDHC base address * @return currently enabled interrupts' state */ static inline uint32_t SDHC_HAL_GetIntState(uint32_t baseAddr) { return HW_SDHC_IRQSTATEN_RD(baseAddr); } /*! * @brief Gets the auto cmd12 error. * * @param baseAddr SDHC base address * @return auto cmd12 error status */ static inline uint32_t SDHC_HAL_GetAc12Error(uint32_t baseAddr) { return HW_SDHC_AC12ERR_RD(baseAddr); } /*! * @brief Gets the maximum block length supported. * * @param baseAddr SDHC base address * @return the maximum block length support */ static inline uint32_t SDHC_HAL_GetMaxBlockLength(uint32_t baseAddr) { return BR_SDHC_HTCAPBLT_MBL(baseAddr); } /*! * @brief Checks whether the ADMA is supported. * * @param baseAddr SDHC base address * @return if ADMA is supported */ static inline uint32_t SDHC_HAL_DoesHostSupportAdma(uint32_t baseAddr) { return BR_SDHC_HTCAPBLT_ADMAS(baseAddr); } /*! * @brief Checks whether the high speed is supported. * * @param baseAddr SDHC base address * @return if high speed is supported */ static inline uint32_t SDHC_HAL_DoesHostSupportHighspeed(uint32_t baseAddr) { return BR_SDHC_HTCAPBLT_HSS(baseAddr); } /*! * @brief Checks whether the DMA is supported. * * @param baseAddr SDHC base address * @return if high speed is supported */ static inline uint32_t SDHC_HAL_DoesHostSupportDma(uint32_t baseAddr) { return BR_SDHC_HTCAPBLT_DMAS(baseAddr); } /*! * @brief Checks whether the suspend/resume is supported. * * @param baseAddr SDHC base address * @return if suspend and resume is supported */ static inline uint32_t SDHC_HAL_DoesHostSupportSuspendResume(uint32_t baseAddr) { return BR_SDHC_HTCAPBLT_SRS(baseAddr); } /*! * @brief Checks whether the voltage 3.3 is supported. * * @param baseAddr SDHC base address * @return if voltage 3.3 is supported */ static inline uint32_t SDHC_HAL_DoesHostSupportV330(uint32_t baseAddr) { return BR_SDHC_HTCAPBLT_VS33(baseAddr); } /*! * @brief Checks whether the voltage 3.0 is supported. * * @param baseAddr SDHC base address * @return if voltage 3.0 is supported */ static inline uint32_t SDHC_HAL_DoesHostSupportV300(uint32_t baseAddr) { #if defined(FSL_FEATURE_SDHC_HAS_V300_SUPPORT) && FSL_FEATURE_SDHC_HAS_V300_SUPPORT return BR_SDHC_HTCAPBLT_VS30(baseAddr); #else return 0; #endif } /*! * @brief Checks whether the voltage 1.8 is supported. * * @param baseAddr SDHC base address * @return if voltage 1.8 is supported */ static inline uint32_t SDHC_HAL_DoesHostSupportV180(uint32_t baseAddr) { #if defined(FSL_FEATURE_SDHC_HAS_V180_SUPPORT) && FSL_FEATURE_SDHC_HAS_V180_SUPPORT return BR_SDHC_HTCAPBLT_VS18(baseAddr); #else return 0; #endif } /*! * @brief Sets the watermark for writing. * * @param baseAddr SDHC base address * @param watermark for writing */ static inline void SDHC_HAL_SetWriteWatermarkLevel(uint32_t baseAddr, uint32_t watermark) { BW_SDHC_WML_WRWML(baseAddr, watermark); } /*! * @brief Sets the watermark for reading. * * @param baseAddr SDHC base address * @param watermark for reading */ static inline void SDHC_HAL_SetReadWatermarkLevel(uint32_t baseAddr, uint32_t watermark) { BW_SDHC_WML_RDWML(baseAddr, watermark); } /*! * @brief Sets the force events according to the given mask. * * @param baseAddr SDHC base address * @param mask to specify the force events' flags to be set */ static inline void SDHC_HAL_SetForceEventFlags(uint32_t baseAddr, uint32_t mask) { HW_SDHC_FEVT_WR(baseAddr, mask); } /*! * @brief Checks whether the ADMA error is length mismatch. * * @param baseAddr SDHC base address * @return if ADMA error is length mismatch */ static inline uint32_t SDHC_HAL_IsAdmaLengthMismatchError(uint32_t baseAddr) { return BR_SDHC_ADMAES_ADMALME(baseAddr); } /*! * @brief Checks the SD clock. * * Checks whether the clock to the SD is enabled. * * @param baseAddr SDHC base address * @return true if enabled */ static inline bool SDHC_HAL_IsSdClockOff(uint32_t baseAddr) { return BR_SDHC_SYSCTL_SDCLKEN(baseAddr); } /*! * @brief Returns the state of the ADMA error. * * @param baseAddr SDHC base address * @return error state */ static inline uint32_t SDHC_HAL_GetAdmaErrorState(uint32_t baseAddr) { return BR_SDHC_ADMAES_ADMAES(baseAddr); } /*! * @brief Checks whether the ADMA error is a descriptor error. * * @param baseAddr SDHC base address * @return if ADMA error is descriptor error */ static inline uint32_t SDHC_HAL_IsAdmaDescriptionError(uint32_t baseAddr) { return BR_SDHC_ADMAES_ADMADCE(baseAddr); } /*! * @brief Sets the ADMA address. * * @param baseAddr SDHC base address * @param address for ADMA transfer */ static inline void SDHC_HAL_SetAdmaAddress(uint32_t baseAddr, uint32_t address) { HW_SDHC_ADSADDR_WR(baseAddr, address); } /*! * @brief Enables the external DMA request. * * @param baseAddr SDHC base address * @param enable to external DMA */ static inline void SDHC_HAL_SetExternalDmaRequest(uint32_t baseAddr, bool enable) { BW_SDHC_VENDOR_EXTDMAEN(baseAddr, enable ? 1 : 0); } /*! * @brief Enables the exact block number for the SDIO CMD53. * * @param baseAddr SDHC base address * @param enable to enable exact block number block read for SDIO CMD53 */ static inline void SDHC_HAL_SetExactBlockNumber(uint32_t baseAddr, bool enable) { BW_SDHC_VENDOR_EXBLKNU(baseAddr, enable ? 1 : 0); } /*! * @brief Sets the timeout value for the boot ACK. * * @param baseAddr SDHC base address * @param timeout boot ack time out counter value */ static inline void SDHC_HAL_SetBootAckTimeout(uint32_t baseAddr, uint32_t timeout) { BW_SDHC_MMCBOOT_DTOCVACK(baseAddr, timeout); } /*! * @brief Enables the boot ACK. * * @param baseAddr SDHC base address * @param enable to enable boot ack mode */ static inline void SDHC_HAL_SetBootAck(uint32_t baseAddr, bool enable) { BW_SDHC_MMCBOOT_BOOTACK(baseAddr, enable ? 1 : 0); } /*! * @brief Configures the boot mode. * * @param baseAddr SDHC base address * @param mode the boot mode */ static inline void SDHC_HAL_SetBootMode(uint32_t baseAddr, sdhc_hal_mmcboot_t mode) { BW_SDHC_MMCBOOT_BOOTMODE(baseAddr, mode); } /*! * @brief Enables the fast boot. * * @param baseAddr SDHC base address * @param enable to enable fast boot */ static inline void SDHC_HAL_SetFastboot(uint32_t baseAddr, bool enable) { BW_SDHC_MMCBOOT_BOOTEN(baseAddr, enable ? 1 : 0); } /*! * @brief Enables the automatic stop at the block gap. * * @param baseAddr SDHC base address * @param enable to enable auto stop at block gap function, when boot. */ static inline void SDHC_HAL_SetAutoStopAtBlockGap(uint32_t baseAddr, bool enable) { BW_SDHC_MMCBOOT_AUTOSABGEN(baseAddr, enable ? 1 : 0); } /*! * @brief Configures the the block count for the boot. * * @param baseAddr SDHC base address * @param blockCount the block count for boot */ static inline void SDHC_HAL_SetBootBlockCount(uint32_t baseAddr, uint32_t blockCount) { BW_SDHC_MMCBOOT_BOOTBLKCNT(baseAddr, blockCount); } /*! * @brief Gets a specification version. * * @param baseAddr SDHC base address * @return specification version */ static inline uint32_t SDHC_HAL_GetSpecificationVersion(uint32_t baseAddr) { return BR_SDHC_HOSTVER_SVN(baseAddr); } /*! * @brief Gets the vendor version. * * @param baseAddr SDHC base address * @return vendor version */ static inline uint32_t SDHC_HAL_GetVendorVersion(uint32_t baseAddr) { return BR_SDHC_HOSTVER_VVN(baseAddr); } /*! * @brief Gets the command response. * * @param baseAddr SDHC base address * @param index of response register, range from 0 to 3 */ uint32_t SDHC_HAL_GetResponse(uint32_t baseAddr, uint32_t index); /*! * @brief Enables the specified interrupts. * * @param baseAddr SDHC base address * @param enable enable or disable * @param mask to specify interrupts to be isEnabledd */ void SDHC_HAL_SetIntSignal(uint32_t baseAddr, bool enable, uint32_t mask); /*! * @brief Enables the specified interrupt state. * * @param baseAddr SDHC base address * @param enable enable or disable * @param mask to specify interrupts' state to be enabled */ void SDHC_HAL_SetIntState(uint32_t baseAddr, bool enable, uint32_t mask); /*! * @brief Performs an SDHC reset. * * @param baseAddr SDHC base address * @param type the type of reset * @param timeout timeout for reset * @return 0 on success, else on error */ uint32_t SDHC_HAL_Reset(uint32_t baseAddr, uint32_t type, uint32_t timeout); /*! * @brief Sends 80 clocks to the card to initialize the card. * * @param baseAddr SDHC base address * @param timeout timeout for initialize card * @return 0 on success, else on error */ uint32_t SDHC_HAL_InitCard(uint32_t baseAddr, uint32_t timeout); /*! * @brief Gets the IRQ ID for a given host controller. * * @param baseAddr SDHC base address * @return IRQ number for specific SDHC instance */ IRQn_Type SDHC_HAL_GetIrqId(uint32_t baseAddr); /*! * @brief Initializes the SDHC HAL. * * @param baseAddr SDHC base address */ void SDHC_HAL_Init(uint32_t baseAddr); /*@} */ #if defined(__cplusplus) } #endif /*! @} */ #endif /* MBED_NO_SDHC */ #endif /************************************************************************************************* * EOF ************************************************************************************************/ ================================================ FILE: Zelig/mbed/TARGET_K64F/TARGET_Freescale/TARGET_KPSDK_MCUS/TARGET_KPSDK_CODE/hal/sim/fsl_sim_features.h ================================================ /* ** ################################################################### ** Version: rev. 1.0, 2014-05-14 ** Build: b140515 ** ** Abstract: ** Chip specific module features. ** ** Copyright: 2014 Freescale Semiconductor, Inc. ** All rights reserved. ** ** Redistribution and use in source and binary forms, with or without modification, ** are permitted provided that the following conditions are met: ** ** o Redistributions of source code must retain the above copyright notice, this list ** of conditions and the following disclaimer. ** ** o Redistributions in binary form must reproduce the above copyright notice, this ** list of conditions and the following disclaimer in the documentation and/or ** other materials provided with the distribution. ** ** o Neither the name of Freescale Semiconductor, Inc. nor the names of its ** contributors may be used to endorse or promote products derived from this ** software without specific prior written permission. ** ** THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ** ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED ** WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE ** DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT 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. ** ** http: www.freescale.com ** mail: support@freescale.com ** ** Revisions: ** - rev. 1.0 (2014-05-14) ** Customer release. ** ** ################################################################### */ #if !defined(__FSL_SIM_FEATURES_H__) #define __FSL_SIM_FEATURES_H__ #if defined(CPU_MK02FN128VFM10) || defined(CPU_MK02FN64VFM10) || defined(CPU_MK02FN128VLF10) || defined(CPU_MK02FN64VLF10) || \ defined(CPU_MK02FN128VLH10) || defined(CPU_MK02FN64VLH10) /* @brief Has USB FS divider. */ #define FSL_FEATURE_SIM_USBFS_USE_SPECIAL_DIVIDER (0) /* @brief Is PLL clock divided by 2 before MCG PLL/FLL clock selection. */ #define FSL_FEATURE_SIM_PLLCLK_USE_SPECIAL_DIVIDER (0) /* @brief Has RAM size specification (register bit field SOPT1[RAMSIZE]). */ #define FSL_FEATURE_SIM_OPT_HAS_RAMSIZE (1) /* @brief Has 32k oscillator clock output (register bit SOPT1[OSC32KOUT]). */ #define FSL_FEATURE_SIM_OPT_HAS_OSC32K_OUT (1) /* @brief Has 32k oscillator clock selection (register bit field SOPT1[OSC32KSEL]). */ #define FSL_FEATURE_SIM_OPT_HAS_OSC32K_SELECTION (1) /* @brief 32k oscillator clock selection width (width of register bit field SOPT1[OSC32KSEL]). */ #define FSL_FEATURE_SIM_OPT_OSC32K_SELECTION_WIDTH (2) /* @brief Has RTC clock output selection (register bit SOPT2[RTCCLKOUTSEL]). */ #define FSL_FEATURE_SIM_OPT_HAS_RTC_CLOCK_OUT_SELECTION (0) /* @brief Has USB voltage regulator (register bits SOPT1[USBVSTBY], SOPT1[USBSSTBY], SOPT1[USBREGEN], SOPT1CFG[URWE], SOPT1CFG[UVSWE], SOPT1CFG[USSWE]). */ #define FSL_FEATURE_SIM_OPT_HAS_USB_VOLTAGE_REGULATOR (0) /* @brief USB has integrated PHY (register bits USBPHYCTL[USBVREGSEL], USBPHYCTL[USBVREGPD], USBPHYCTL[USB3VOUTTRG], USBPHYCTL[USBDISILIM], SOPT2[USBSLSRC], SOPT2[USBREGEN]). */ #define FSL_FEATURE_SIM_OPT_HAS_USB_PHY (0) /* @brief Has PTD7 pad drive strength control (register bit SOPT2[PTD7PAD]). */ #define FSL_FEATURE_SIM_OPT_HAS_PTD7PAD (0) /* @brief Has FlexBus security level selection (register bit SOPT2[FBSL]). */ #define FSL_FEATURE_SIM_OPT_HAS_FBSL (0) /* @brief Has number of FlexBus hold cycle before FlexBus can release bus (register bit SOPT6[PCR]). */ #define FSL_FEATURE_SIM_OPT_HAS_PCR (0) /* @brief Has number of NFC hold cycle in case of FlexBus request (register bit SOPT6[MCC]). */ #define FSL_FEATURE_SIM_OPT_HAS_MCC (0) /* @brief Has UART open drain enable (register bits UARTnODE, where n is a number, in register SOPT5). */ #define FSL_FEATURE_SIM_OPT_HAS_ODE (0) /* @brief Number of UART modules (number of register bits UARTn, where n is a number, in register SCGC4). */ #define FSL_FEATURE_SIM_OPT_UART_COUNT (2) /* @brief Has LPUART0 open drain enable (register bit SOPT5[LPUART0ODE]). */ #define FSL_FEATURE_SIM_OPT_HAS_LPUART0_ODE (0) /* @brief Has LPUART1 open drain enable (register bit SOPT5[LPUART1ODE]). */ #define FSL_FEATURE_SIM_OPT_HAS_LPUART1_ODE (0) /* @brief Has CMT/UART pad drive strength control (register bit SOPT2[CMTUARTPAD]). */ #define FSL_FEATURE_SIM_OPT_HAS_CMTUARTPAD (0) /* @brief Has LPUART0 transmit data source selection (register bit SOPT5[LPUART0TXSRC]). */ #define FSL_FEATURE_SIM_OPT_HAS_LPUART0_TX_SRC (0) /* @brief Has LPUART0 receive data source selection (register bit SOPT5[LPUART0RXSRC]). */ #define FSL_FEATURE_SIM_OPT_HAS_LPUART0_RX_SRC (0) /* @brief Has LPUART1 transmit data source selection (register bit SOPT5[LPUART1TXSRC]). */ #define FSL_FEATURE_SIM_OPT_HAS_LPUART1_TX_SRC (0) /* @brief Has LPUART1 receive data source selection (register bit SOPT5[LPUART1RXSRC]). */ #define FSL_FEATURE_SIM_OPT_HAS_LPUART1_RX_SRC (0) /* @brief Has UART0 transmit data source selection (register bit SOPT5[UART0TXSRC]). */ #define FSL_FEATURE_SIM_OPT_HAS_UART0_TX_SRC (1) /* @brief UART0 transmit data source selection width (width of register bit SOPT5[UART0TXSRC]). */ #define FSL_FEATURE_SIM_OPT_UART0_TX_SRC_WIDTH (2) /* @brief Has UART0 receive data source selection (register bit SOPT5[UART0RXSRC]). */ #define FSL_FEATURE_SIM_OPT_HAS_UART0_RX_SRC (1) /* @brief UART0 receive data source selection width (width of register bit SOPT5[UART0RXSRC]). */ #define FSL_FEATURE_SIM_OPT_UART0_RX_SRC_WIDTH (2) /* @brief Has UART1 transmit data source selection (register bit SOPT5[UART1TXSRC]). */ #define FSL_FEATURE_SIM_OPT_HAS_UART1_TX_SRC (1) /* @brief Has UART1 receive data source selection (register bit SOPT5[UART1RXSRC]). */ #define FSL_FEATURE_SIM_OPT_HAS_UART1_RX_SRC (1) /* @brief UART1 receive data source selection width (width of register bit SOPT5[UART1RXSRC]). */ #define FSL_FEATURE_SIM_OPT_UART1_RX_SRC_WIDTH (2) /* @brief Has FTM module(s) configuration. */ #define FSL_FEATURE_SIM_OPT_HAS_FTM (1) /* @brief Number of FTM modules. */ #define FSL_FEATURE_SIM_OPT_FTM_COUNT (3) /* @brief Number of FTM triggers with selectable source. */ #define FSL_FEATURE_SIM_OPT_FTM_TRIGGER_COUNT (2) /* @brief Has FTM0 triggers source selection (register bits SOPT4[FTM0TRGnSRC], where n is a number). */ #define FSL_FEATURE_SIM_OPT_HAS_FTM0_TRIGGER (1) /* @brief Has FTM3 triggers source selection (register bits SOPT4[FTM3TRGnSRC], where n is a number). */ #define FSL_FEATURE_SIM_OPT_HAS_FTM3_TRIGGER (0) /* @brief Has FTM1 channel 0 input capture source selection (register bit SOPT4[FTM1CH0SRC]). */ #define FSL_FEATURE_SIM_OPT_HAS_FTM1_CHANNELS (1) /* @brief Has FTM2 channel 0 input capture source selection (register bit SOPT4[FTM2CH0SRC]). */ #define FSL_FEATURE_SIM_OPT_HAS_FTM2_CHANNELS (1) /* @brief Has FTM3 channel 0 input capture source selection (register bit SOPT4[FTM3CH0SRC]). */ #define FSL_FEATURE_SIM_OPT_HAS_FTM3_CHANNELS (0) /* @brief Has FTM2 channel 1 input capture source selection (register bit SOPT4[FTM2CH1SRC]). */ #define FSL_FEATURE_SIM_OPT_HAS_FTM2_CHANNEL1 (1) /* @brief Number of configurable FTM0 fault detection input (number of register bits SOPT4[FTM0FLTn], where n is a number starting from zero). */ #define FSL_FEATURE_SIM_OPT_FTM0_FAULT_COUNT (2) /* @brief Number of configurable FTM1 fault detection input (number of register bits SOPT4[FTM1FLTn], where n is a number starting from zero). */ #define FSL_FEATURE_SIM_OPT_FTM1_FAULT_COUNT (1) /* @brief Number of configurable FTM2 fault detection input (number of register bits SOPT4[FTM2FLTn], where n is a number starting from zero). */ #define FSL_FEATURE_SIM_OPT_FTM2_FAULT_COUNT (1) /* @brief Number of configurable FTM3 fault detection input (number of register bits SOPT4[FTM3FLTn], where n is a number starting from zero). */ #define FSL_FEATURE_SIM_OPT_FTM3_FAULT_COUNT (0) /* @brief Has FTM hardware trigger 0 software synchronization (register bit SOPT8[FTMnSYNCBIT], where n is a module instance index). */ #define FSL_FEATURE_SIM_OPT_HAS_FTM_TRIGGER_SYNC (1) /* @brief Has FTM channels output source selection (register bit SOPT8[FTMxOCHnSRC], where x is a module instance index and n is a channel index). */ #define FSL_FEATURE_SIM_OPT_HAS_FTM_CHANNELS_OUTPUT_SRC (1) /* @brief Has TPM module(s) configuration. */ #define FSL_FEATURE_SIM_OPT_HAS_TPM (0) /* @brief The highest TPM module index. */ #define FSL_FEATURE_SIM_OPT_MAX_TPM_INDEX (0) /* @brief Has TPM module with index 0. */ #define FSL_FEATURE_SIM_OPT_HAS_TPM0 (0) /* @brief Is TPM channels configuration in the SOPT4 (not SOPT9) register (register bits TPMnCH0SRC, TPMnCLKSEL, where n is a module instance index). */ #define FSL_FEATURE_SIM_OPT_HAS_TPM_CHANNELS_CONFIG_IN_SOPT4_REG (0) /* @brief Has TPM1 channel 0 input capture source selection (register bit field SOPT4[TPM1CH0SRC] or SOPT9[TPM1CH0SRC]). */ #define FSL_FEATURE_SIM_OPT_HAS_TPM1_CH0_SRC_SELECTION (0) /* @brief TPM1 channel 0 input capture source selection width (width of register bit field SOPT4[TPM1CH0SRC] or SOPT9[TPM1CH0SRC]). */ #define FSL_FEATURE_SIM_OPT_TPM1_CH0_SRC_SELECTION_WIDTH (0) /* @brief Has TPM2 channel 0 input capture source selection (register bit field SOPT4[TPM2CH0SRC]). */ #define FSL_FEATURE_SIM_OPT_HAS_TPM2_CH0_SRC_SELECTION (0) /* @brief Has TPM2 clock selection (register bit field SOPT4[TPM2CLKSEL]). */ #define FSL_FEATURE_SIM_OPT_HAS_TPM2_CLK_SEL (0) /* @brief Has PLL/FLL clock selection (register bit field SOPT2[PLLFLLSEL]). */ #define FSL_FEATURE_SIM_OPT_HAS_PLL_FLL_SELECTION (1) /* @brief PLL/FLL clock selection width (width of register bit field SOPT2[PLLFLLSEL]). */ #define FSL_FEATURE_SIM_OPT_PLL_FLL_SELECTION_WIDTH (1) /* @brief Has NFC clock source selection (register bit SOPT2[NFCSRC]). */ #define FSL_FEATURE_SIM_OPT_HAS_NFCSRC (0) /* @brief Has eSDHC clock source selection (register bit SOPT2[ESDHCSRC]). */ #define FSL_FEATURE_SIM_OPT_HAS_ESDHCSRC (0) /* @brief Has SDHC clock source selection (register bit SOPT2[SDHCSRC]). */ #define FSL_FEATURE_SIM_OPT_HAS_SDHCSRC (0) /* @brief Has LCDC clock source selection (register bits SOPT2[LCDCSRC], SOPT2[LCDC_CLKSEL]). */ #define FSL_FEATURE_SIM_OPT_HAS_LCDCSRC (0) /* @brief Has ENET timestamp clock source selection (register bit SOPT2[TIMESRC]). */ #define FSL_FEATURE_SIM_OPT_HAS_TIMESRC (0) /* @brief Has ENET RMII clock source selection (register bit SOPT2[RMIISRC]). */ #define FSL_FEATURE_SIM_OPT_HAS_RMIISRC (0) /* @brief Has USB clock source selection (register bit SOPT2[USBSRC]). */ #define FSL_FEATURE_SIM_OPT_HAS_USBSRC (0) /* @brief Has USB FS clock source selection (register bit SOPT2[USBFSRC]). */ #define FSL_FEATURE_SIM_OPT_HAS_USBFSRC (0) /* @brief Has USB HS clock source selection (register bit SOPT2[USBHSRC]). */ #define FSL_FEATURE_SIM_OPT_HAS_USBHSRC (0) /* @brief Has LPUART clock source selection (register bit SOPT2[LPUARTSRC]). */ #define FSL_FEATURE_SIM_OPT_HAS_LPUARTSRC (0) /* @brief Has LPUART0 clock source selection (register bit SOPT2[LPUART0SRC]). */ #define FSL_FEATURE_SIM_OPT_HAS_LPUART0SRC (0) /* @brief Has LPUART1 clock source selection (register bit SOPT2[LPUART1SRC]). */ #define FSL_FEATURE_SIM_OPT_HAS_LPUART1SRC (0) /* @brief Has FLEXIOSRC clock source selection (register bit SOPT2[FLEXIOSRC]). */ #define FSL_FEATURE_SIM_OPT_HAS_FLEXIOSRC (0) /* @brief Has UART0 clock source selection (register bit SOPT2[UART0SRC]). */ #define FSL_FEATURE_SIM_OPT_HAS_UART0SRC (0) /* @brief Has TPM clock source selection (register bit SOPT2[TPMSRC]). */ #define FSL_FEATURE_SIM_OPT_HAS_TPMSRC (0) /* @brief Has debug trace clock selection (register bit SOPT2[TRACECLKSEL]). */ #define FSL_FEATURE_SIM_OPT_HAS_TRACE_CLKSEL (1) /* @brief Number of ADC modules (register bits SOPT7[ADCnTRGSEL], SOPT7[ADCnPRETRGSEL], SOPT7[ADCnALTTRGSEL], where n is a module instance index). */ #define FSL_FEATURE_SIM_OPT_ADC_COUNT (1) /* @brief Has clock 2 output divider (register bit field CLKDIV1[OUTDIV2]). */ #define FSL_FEATURE_SIM_DIVIDER_HAS_OUTDIV2 (1) /* @brief Has clock 3 output divider (register bit field CLKDIV1[OUTDIV3]). */ #define FSL_FEATURE_SIM_DIVIDER_HAS_OUTDIV3 (0) /* @brief Has clock 4 output divider (register bit field CLKDIV1[OUTDIV4]). */ #define FSL_FEATURE_SIM_DIVIDER_HAS_OUTDIV4 (1) /* @brief Clock 4 output divider width (width of register bit field CLKDIV1[OUTDIV4]). */ #define FSL_FEATURE_SIM_DIVIDER_OUTDIV4_WIDTH (4) /* @brief Has USB clock divider (register bit field CLKDIV2[USBDIV] and CLKDIV2[USBFRAC]). */ #define FSL_FEATURE_SIM_DIVIDER_HAS_USBDIV (0) /* @brief Has USB FS clock divider (register bit field CLKDIV2[USBFSDIV] and CLKDIV2[USBFSFRAC]). */ #define FSL_FEATURE_SIM_DIVIDER_HAS_USBFSDIV (0) /* @brief Has USB HS clock divider (register bit field CLKDIV2[USBHSDIV] and CLKDIV2[USBHSFRAC]). */ #define FSL_FEATURE_SIM_DIVIDER_HAS_USBHSDIV (0) /* @brief Has PLL/FLL clock divider (register bit field CLKDIV3[PLLFLLDIV] and CLKDIV3[PLLFLLFRAC]). */ #define FSL_FEATURE_SIM_DIVIDER_HAS_PLLFLLDIV (0) /* @brief Has LCDC clock divider (register bit field CLKDIV3[LCDCDIV] and CLKDIV3[LCDCFRAC]). */ #define FSL_FEATURE_SIM_DIVIDER_HAS_LCDCDIV (0) /* @brief Has trace clock divider (register bit field CLKDIV4[TRACEDIV] and CLKDIV4[TRACEFRAC]). */ #define FSL_FEATURE_SIM_DIVIDER_HAS_TRACEDIV (0) /* @brief Has NFC clock divider (register bit field CLKDIV4[NFCDIV] and CLKDIV4[NFCFRAC]). */ #define FSL_FEATURE_SIM_DIVIDER_HAS_NFCDIV (0) /* @brief Has Kinetis family ID (register bit field SDID[FAMILYID]). */ #define FSL_FEATURE_SIM_SDID_HAS_FAMILYID (1) /* @brief Has Kinetis family ID (register bit field SDID[FAMID]). */ #define FSL_FEATURE_SIM_SDID_HAS_FAMID (1) /* @brief Has Kinetis sub-family ID (register bit field SDID[SUBFAMID]). */ #define FSL_FEATURE_SIM_SDID_HAS_SUBFAMID (1) /* @brief Has Kinetis series ID (register bit field SDID[SERIESID]). */ #define FSL_FEATURE_SIM_SDID_HAS_SERIESID (1) /* @brief Has device die ID (register bit field SDID[DIEID]). */ #define FSL_FEATURE_SIM_SDID_HAS_DIEID (1) /* @brief Has system SRAM size specifier (register bit field SDID[SRAMSIZE]). */ #define FSL_FEATURE_SIM_SDID_HAS_SRAMSIZE (0) /* @brief Has flash mode (register bit FCFG1[FLASHDOZE]). */ #define FSL_FEATURE_SIM_FCFG_HAS_FLASHDOZE (1) /* @brief Has flash disable (register bit FCFG1[FLASHDIS]). */ #define FSL_FEATURE_SIM_FCFG_HAS_FLASHDIS (1) /* @brief Has FTFE disable (register bit FCFG1[FTFDIS]). */ #define FSL_FEATURE_SIM_FCFG_HAS_FTFDIS (0) /* @brief Has FlexNVM size specifier (register bit field FCFG1[NVMSIZE]). */ #define FSL_FEATURE_SIM_FCFG_HAS_NVMSIZE (0) /* @brief Has EEPROM size specifier (register bit field FCFG1[EESIZE]). */ #define FSL_FEATURE_SIM_FCFG_HAS_EESIZE (0) /* @brief Has FlexNVM partition (register bit field FCFG1[DEPART]). */ #define FSL_FEATURE_SIM_FCFG_HAS_DEPART (0) /* @brief Maximum flash address block 0 address specifier (register bit field FCFG2[MAXADDR0]). */ #define FSL_FEATURE_SIM_FCFG_HAS_MAXADDR0 (1) /* @brief Maximum flash address block 1 address specifier (register bit field FCFG2[MAXADDR1]). */ #define FSL_FEATURE_SIM_FCFG_HAS_MAXADDR1 (0) /* @brief Maximum flash address block 0 or 1 address specifier (register bit field FCFG2[MAXADDR01]). */ #define FSL_FEATURE_SIM_FCFG_HAS_MAXADDR01 (0) /* @brief Maximum flash address block 2 or 3 address specifier (register bit field FCFG2[MAXADDR23]). */ #define FSL_FEATURE_SIM_FCFG_HAS_MAXADDR23 (0) /* @brief Has program flash availability specifier (register bit FCFG2[PFLSH]). */ #define FSL_FEATURE_SIM_FCFG_HAS_PFLSH (0) /* @brief Has program flash swapping (register bit FCFG2[SWAPPFLSH]). */ #define FSL_FEATURE_SIM_FCFG_HAS_PFLSH_SWAP (0) /* @brief Has miscellanious control register (register MCR). */ #define FSL_FEATURE_SIM_HAS_MISC_CONTROLS (0) /* @brief Has COP watchdog (registers COPC and SRVCOP). */ #define FSL_FEATURE_SIM_HAS_COP_WATCHDOG (0) /* @brief Has COP watchdog stop (register bits COPC[COPSTPEN], COPC[COPDBGEN] and COPC[COPCLKSEL]). */ #define FSL_FEATURE_SIM_HAS_COP_STOP (0) #elif defined(CPU_MK22FN128VDC10) || defined(CPU_MK22FN128VLH10) || defined(CPU_MK22FN128VLL10) || defined(CPU_MK22FN128VMP10) /* @brief Has USB FS divider. */ #define FSL_FEATURE_SIM_USBFS_USE_SPECIAL_DIVIDER (0) /* @brief Is PLL clock divided by 2 before MCG PLL/FLL clock selection. */ #define FSL_FEATURE_SIM_PLLCLK_USE_SPECIAL_DIVIDER (0) /* @brief Has RAM size specification (register bit field SOPT1[RAMSIZE]). */ #define FSL_FEATURE_SIM_OPT_HAS_RAMSIZE (1) /* @brief Has 32k oscillator clock output (register bit SOPT1[OSC32KOUT]). */ #define FSL_FEATURE_SIM_OPT_HAS_OSC32K_OUT (1) /* @brief Has 32k oscillator clock selection (register bit field SOPT1[OSC32KSEL]). */ #define FSL_FEATURE_SIM_OPT_HAS_OSC32K_SELECTION (1) /* @brief 32k oscillator clock selection width (width of register bit field SOPT1[OSC32KSEL]). */ #define FSL_FEATURE_SIM_OPT_OSC32K_SELECTION_WIDTH (2) /* @brief Has RTC clock output selection (register bit SOPT2[RTCCLKOUTSEL]). */ #define FSL_FEATURE_SIM_OPT_HAS_RTC_CLOCK_OUT_SELECTION (1) /* @brief Has USB voltage regulator (register bits SOPT1[USBVSTBY], SOPT1[USBSSTBY], SOPT1[USBREGEN], SOPT1CFG[URWE], SOPT1CFG[UVSWE], SOPT1CFG[USSWE]). */ #define FSL_FEATURE_SIM_OPT_HAS_USB_VOLTAGE_REGULATOR (0) /* @brief USB has integrated PHY (register bits USBPHYCTL[USBVREGSEL], USBPHYCTL[USBVREGPD], USBPHYCTL[USB3VOUTTRG], USBPHYCTL[USBDISILIM], SOPT2[USBSLSRC], SOPT2[USBREGEN]). */ #define FSL_FEATURE_SIM_OPT_HAS_USB_PHY (0) /* @brief Has PTD7 pad drive strength control (register bit SOPT2[PTD7PAD]). */ #define FSL_FEATURE_SIM_OPT_HAS_PTD7PAD (0) /* @brief Has FlexBus security level selection (register bit SOPT2[FBSL]). */ #define FSL_FEATURE_SIM_OPT_HAS_FBSL (0) /* @brief Has number of FlexBus hold cycle before FlexBus can release bus (register bit SOPT6[PCR]). */ #define FSL_FEATURE_SIM_OPT_HAS_PCR (0) /* @brief Has number of NFC hold cycle in case of FlexBus request (register bit SOPT6[MCC]). */ #define FSL_FEATURE_SIM_OPT_HAS_MCC (0) /* @brief Has UART open drain enable (register bits UARTnODE, where n is a number, in register SOPT5). */ #define FSL_FEATURE_SIM_OPT_HAS_ODE (0) /* @brief Number of UART modules (number of register bits UARTn, where n is a number, in register SCGC4). */ #define FSL_FEATURE_SIM_OPT_UART_COUNT (3) /* @brief Has LPUART0 open drain enable (register bit SOPT5[LPUART0ODE]). */ #define FSL_FEATURE_SIM_OPT_HAS_LPUART0_ODE (0) /* @brief Has LPUART1 open drain enable (register bit SOPT5[LPUART1ODE]). */ #define FSL_FEATURE_SIM_OPT_HAS_LPUART1_ODE (0) /* @brief Has CMT/UART pad drive strength control (register bit SOPT2[CMTUARTPAD]). */ #define FSL_FEATURE_SIM_OPT_HAS_CMTUARTPAD (0) /* @brief Has LPUART0 transmit data source selection (register bit SOPT5[LPUART0TXSRC]). */ #define FSL_FEATURE_SIM_OPT_HAS_LPUART0_TX_SRC (0) /* @brief Has LPUART0 receive data source selection (register bit SOPT5[LPUART0RXSRC]). */ #define FSL_FEATURE_SIM_OPT_HAS_LPUART0_RX_SRC (1) /* @brief Has LPUART1 transmit data source selection (register bit SOPT5[LPUART1TXSRC]). */ #define FSL_FEATURE_SIM_OPT_HAS_LPUART1_TX_SRC (0) /* @brief Has LPUART1 receive data source selection (register bit SOPT5[LPUART1RXSRC]). */ #define FSL_FEATURE_SIM_OPT_HAS_LPUART1_RX_SRC (0) /* @brief Has UART0 transmit data source selection (register bit SOPT5[UART0TXSRC]). */ #define FSL_FEATURE_SIM_OPT_HAS_UART0_TX_SRC (1) /* @brief UART0 transmit data source selection width (width of register bit SOPT5[UART0TXSRC]). */ #define FSL_FEATURE_SIM_OPT_UART0_TX_SRC_WIDTH (2) /* @brief Has UART0 receive data source selection (register bit SOPT5[UART0RXSRC]). */ #define FSL_FEATURE_SIM_OPT_HAS_UART0_RX_SRC (1) /* @brief UART0 receive data source selection width (width of register bit SOPT5[UART0RXSRC]). */ #define FSL_FEATURE_SIM_OPT_UART0_RX_SRC_WIDTH (2) /* @brief Has UART1 transmit data source selection (register bit SOPT5[UART1TXSRC]). */ #define FSL_FEATURE_SIM_OPT_HAS_UART1_TX_SRC (1) /* @brief Has UART1 receive data source selection (register bit SOPT5[UART1RXSRC]). */ #define FSL_FEATURE_SIM_OPT_HAS_UART1_RX_SRC (1) /* @brief UART1 receive data source selection width (width of register bit SOPT5[UART1RXSRC]). */ #define FSL_FEATURE_SIM_OPT_UART1_RX_SRC_WIDTH (2) /* @brief Has FTM module(s) configuration. */ #define FSL_FEATURE_SIM_OPT_HAS_FTM (1) /* @brief Number of FTM modules. */ #define FSL_FEATURE_SIM_OPT_FTM_COUNT (3) /* @brief Number of FTM triggers with selectable source. */ #define FSL_FEATURE_SIM_OPT_FTM_TRIGGER_COUNT (2) /* @brief Has FTM0 triggers source selection (register bits SOPT4[FTM0TRGnSRC], where n is a number). */ #define FSL_FEATURE_SIM_OPT_HAS_FTM0_TRIGGER (1) /* @brief Has FTM3 triggers source selection (register bits SOPT4[FTM3TRGnSRC], where n is a number). */ #define FSL_FEATURE_SIM_OPT_HAS_FTM3_TRIGGER (0) /* @brief Has FTM1 channel 0 input capture source selection (register bit SOPT4[FTM1CH0SRC]). */ #define FSL_FEATURE_SIM_OPT_HAS_FTM1_CHANNELS (1) /* @brief Has FTM2 channel 0 input capture source selection (register bit SOPT4[FTM2CH0SRC]). */ #define FSL_FEATURE_SIM_OPT_HAS_FTM2_CHANNELS (1) /* @brief Has FTM3 channel 0 input capture source selection (register bit SOPT4[FTM3CH0SRC]). */ #define FSL_FEATURE_SIM_OPT_HAS_FTM3_CHANNELS (0) /* @brief Has FTM2 channel 1 input capture source selection (register bit SOPT4[FTM2CH1SRC]). */ #define FSL_FEATURE_SIM_OPT_HAS_FTM2_CHANNEL1 (1) /* @brief Number of configurable FTM0 fault detection input (number of register bits SOPT4[FTM0FLTn], where n is a number starting from zero). */ #define FSL_FEATURE_SIM_OPT_FTM0_FAULT_COUNT (2) /* @brief Number of configurable FTM1 fault detection input (number of register bits SOPT4[FTM1FLTn], where n is a number starting from zero). */ #define FSL_FEATURE_SIM_OPT_FTM1_FAULT_COUNT (1) /* @brief Number of configurable FTM2 fault detection input (number of register bits SOPT4[FTM2FLTn], where n is a number starting from zero). */ #define FSL_FEATURE_SIM_OPT_FTM2_FAULT_COUNT (1) /* @brief Number of configurable FTM3 fault detection input (number of register bits SOPT4[FTM3FLTn], where n is a number starting from zero). */ #define FSL_FEATURE_SIM_OPT_FTM3_FAULT_COUNT (0) /* @brief Has FTM hardware trigger 0 software synchronization (register bit SOPT8[FTMnSYNCBIT], where n is a module instance index). */ #define FSL_FEATURE_SIM_OPT_HAS_FTM_TRIGGER_SYNC (1) /* @brief Has FTM channels output source selection (register bit SOPT8[FTMxOCHnSRC], where x is a module instance index and n is a channel index). */ #define FSL_FEATURE_SIM_OPT_HAS_FTM_CHANNELS_OUTPUT_SRC (1) /* @brief Has TPM module(s) configuration. */ #define FSL_FEATURE_SIM_OPT_HAS_TPM (0) /* @brief The highest TPM module index. */ #define FSL_FEATURE_SIM_OPT_MAX_TPM_INDEX (0) /* @brief Has TPM module with index 0. */ #define FSL_FEATURE_SIM_OPT_HAS_TPM0 (0) /* @brief Is TPM channels configuration in the SOPT4 (not SOPT9) register (register bits TPMnCH0SRC, TPMnCLKSEL, where n is a module instance index). */ #define FSL_FEATURE_SIM_OPT_HAS_TPM_CHANNELS_CONFIG_IN_SOPT4_REG (0) /* @brief Has TPM1 channel 0 input capture source selection (register bit field SOPT4[TPM1CH0SRC] or SOPT9[TPM1CH0SRC]). */ #define FSL_FEATURE_SIM_OPT_HAS_TPM1_CH0_SRC_SELECTION (0) /* @brief TPM1 channel 0 input capture source selection width (width of register bit field SOPT4[TPM1CH0SRC] or SOPT9[TPM1CH0SRC]). */ #define FSL_FEATURE_SIM_OPT_TPM1_CH0_SRC_SELECTION_WIDTH (0) /* @brief Has TPM2 channel 0 input capture source selection (register bit field SOPT4[TPM2CH0SRC]). */ #define FSL_FEATURE_SIM_OPT_HAS_TPM2_CH0_SRC_SELECTION (0) /* @brief Has TPM2 clock selection (register bit field SOPT4[TPM2CLKSEL]). */ #define FSL_FEATURE_SIM_OPT_HAS_TPM2_CLK_SEL (0) /* @brief Has PLL/FLL clock selection (register bit field SOPT2[PLLFLLSEL]). */ #define FSL_FEATURE_SIM_OPT_HAS_PLL_FLL_SELECTION (1) /* @brief PLL/FLL clock selection width (width of register bit field SOPT2[PLLFLLSEL]). */ #define FSL_FEATURE_SIM_OPT_PLL_FLL_SELECTION_WIDTH (1) /* @brief Has NFC clock source selection (register bit SOPT2[NFCSRC]). */ #define FSL_FEATURE_SIM_OPT_HAS_NFCSRC (0) /* @brief Has eSDHC clock source selection (register bit SOPT2[ESDHCSRC]). */ #define FSL_FEATURE_SIM_OPT_HAS_ESDHCSRC (0) /* @brief Has SDHC clock source selection (register bit SOPT2[SDHCSRC]). */ #define FSL_FEATURE_SIM_OPT_HAS_SDHCSRC (0) /* @brief Has LCDC clock source selection (register bits SOPT2[LCDCSRC], SOPT2[LCDC_CLKSEL]). */ #define FSL_FEATURE_SIM_OPT_HAS_LCDCSRC (0) /* @brief Has ENET timestamp clock source selection (register bit SOPT2[TIMESRC]). */ #define FSL_FEATURE_SIM_OPT_HAS_TIMESRC (0) /* @brief Has ENET RMII clock source selection (register bit SOPT2[RMIISRC]). */ #define FSL_FEATURE_SIM_OPT_HAS_RMIISRC (0) /* @brief Has USB clock source selection (register bit SOPT2[USBSRC]). */ #define FSL_FEATURE_SIM_OPT_HAS_USBSRC (1) /* @brief Has USB FS clock source selection (register bit SOPT2[USBFSRC]). */ #define FSL_FEATURE_SIM_OPT_HAS_USBFSRC (0) /* @brief Has USB HS clock source selection (register bit SOPT2[USBHSRC]). */ #define FSL_FEATURE_SIM_OPT_HAS_USBHSRC (0) /* @brief Has LPUART clock source selection (register bit SOPT2[LPUARTSRC]). */ #define FSL_FEATURE_SIM_OPT_HAS_LPUARTSRC (1) /* @brief Has LPUART0 clock source selection (register bit SOPT2[LPUART0SRC]). */ #define FSL_FEATURE_SIM_OPT_HAS_LPUART0SRC (0) /* @brief Has LPUART1 clock source selection (register bit SOPT2[LPUART1SRC]). */ #define FSL_FEATURE_SIM_OPT_HAS_LPUART1SRC (0) /* @brief Has FLEXIOSRC clock source selection (register bit SOPT2[FLEXIOSRC]). */ #define FSL_FEATURE_SIM_OPT_HAS_FLEXIOSRC (0) /* @brief Has UART0 clock source selection (register bit SOPT2[UART0SRC]). */ #define FSL_FEATURE_SIM_OPT_HAS_UART0SRC (0) /* @brief Has TPM clock source selection (register bit SOPT2[TPMSRC]). */ #define FSL_FEATURE_SIM_OPT_HAS_TPMSRC (0) /* @brief Has debug trace clock selection (register bit SOPT2[TRACECLKSEL]). */ #define FSL_FEATURE_SIM_OPT_HAS_TRACE_CLKSEL (1) /* @brief Number of ADC modules (register bits SOPT7[ADCnTRGSEL], SOPT7[ADCnPRETRGSEL], SOPT7[ADCnALTTRGSEL], where n is a module instance index). */ #define FSL_FEATURE_SIM_OPT_ADC_COUNT (2) /* @brief Has clock 2 output divider (register bit field CLKDIV1[OUTDIV2]). */ #define FSL_FEATURE_SIM_DIVIDER_HAS_OUTDIV2 (1) /* @brief Has clock 3 output divider (register bit field CLKDIV1[OUTDIV3]). */ #define FSL_FEATURE_SIM_DIVIDER_HAS_OUTDIV3 (0) /* @brief Has clock 4 output divider (register bit field CLKDIV1[OUTDIV4]). */ #define FSL_FEATURE_SIM_DIVIDER_HAS_OUTDIV4 (1) /* @brief Clock 4 output divider width (width of register bit field CLKDIV1[OUTDIV4]). */ #define FSL_FEATURE_SIM_DIVIDER_OUTDIV4_WIDTH (4) /* @brief Has USB clock divider (register bit field CLKDIV2[USBDIV] and CLKDIV2[USBFRAC]). */ #define FSL_FEATURE_SIM_DIVIDER_HAS_USBDIV (1) /* @brief Has USB FS clock divider (register bit field CLKDIV2[USBFSDIV] and CLKDIV2[USBFSFRAC]). */ #define FSL_FEATURE_SIM_DIVIDER_HAS_USBFSDIV (0) /* @brief Has USB HS clock divider (register bit field CLKDIV2[USBHSDIV] and CLKDIV2[USBHSFRAC]). */ #define FSL_FEATURE_SIM_DIVIDER_HAS_USBHSDIV (0) /* @brief Has PLL/FLL clock divider (register bit field CLKDIV3[PLLFLLDIV] and CLKDIV3[PLLFLLFRAC]). */ #define FSL_FEATURE_SIM_DIVIDER_HAS_PLLFLLDIV (0) /* @brief Has LCDC clock divider (register bit field CLKDIV3[LCDCDIV] and CLKDIV3[LCDCFRAC]). */ #define FSL_FEATURE_SIM_DIVIDER_HAS_LCDCDIV (0) /* @brief Has trace clock divider (register bit field CLKDIV4[TRACEDIV] and CLKDIV4[TRACEFRAC]). */ #define FSL_FEATURE_SIM_DIVIDER_HAS_TRACEDIV (0) /* @brief Has NFC clock divider (register bit field CLKDIV4[NFCDIV] and CLKDIV4[NFCFRAC]). */ #define FSL_FEATURE_SIM_DIVIDER_HAS_NFCDIV (0) /* @brief Has Kinetis family ID (register bit field SDID[FAMILYID]). */ #define FSL_FEATURE_SIM_SDID_HAS_FAMILYID (1) /* @brief Has Kinetis family ID (register bit field SDID[FAMID]). */ #define FSL_FEATURE_SIM_SDID_HAS_FAMID (1) /* @brief Has Kinetis sub-family ID (register bit field SDID[SUBFAMID]). */ #define FSL_FEATURE_SIM_SDID_HAS_SUBFAMID (1) /* @brief Has Kinetis series ID (register bit field SDID[SERIESID]). */ #define FSL_FEATURE_SIM_SDID_HAS_SERIESID (1) /* @brief Has device die ID (register bit field SDID[DIEID]). */ #define FSL_FEATURE_SIM_SDID_HAS_DIEID (1) /* @brief Has system SRAM size specifier (register bit field SDID[SRAMSIZE]). */ #define FSL_FEATURE_SIM_SDID_HAS_SRAMSIZE (0) /* @brief Has flash mode (register bit FCFG1[FLASHDOZE]). */ #define FSL_FEATURE_SIM_FCFG_HAS_FLASHDOZE (1) /* @brief Has flash disable (register bit FCFG1[FLASHDIS]). */ #define FSL_FEATURE_SIM_FCFG_HAS_FLASHDIS (1) /* @brief Has FTFE disable (register bit FCFG1[FTFDIS]). */ #define FSL_FEATURE_SIM_FCFG_HAS_FTFDIS (0) /* @brief Has FlexNVM size specifier (register bit field FCFG1[NVMSIZE]). */ #define FSL_FEATURE_SIM_FCFG_HAS_NVMSIZE (0) /* @brief Has EEPROM size specifier (register bit field FCFG1[EESIZE]). */ #define FSL_FEATURE_SIM_FCFG_HAS_EESIZE (0) /* @brief Has FlexNVM partition (register bit field FCFG1[DEPART]). */ #define FSL_FEATURE_SIM_FCFG_HAS_DEPART (0) /* @brief Maximum flash address block 0 address specifier (register bit field FCFG2[MAXADDR0]). */ #define FSL_FEATURE_SIM_FCFG_HAS_MAXADDR0 (1) /* @brief Maximum flash address block 1 address specifier (register bit field FCFG2[MAXADDR1]). */ #define FSL_FEATURE_SIM_FCFG_HAS_MAXADDR1 (1) /* @brief Maximum flash address block 0 or 1 address specifier (register bit field FCFG2[MAXADDR01]). */ #define FSL_FEATURE_SIM_FCFG_HAS_MAXADDR01 (0) /* @brief Maximum flash address block 2 or 3 address specifier (register bit field FCFG2[MAXADDR23]). */ #define FSL_FEATURE_SIM_FCFG_HAS_MAXADDR23 (0) /* @brief Has program flash availability specifier (register bit FCFG2[PFLSH]). */ #define FSL_FEATURE_SIM_FCFG_HAS_PFLSH (0) /* @brief Has program flash swapping (register bit FCFG2[SWAPPFLSH]). */ #define FSL_FEATURE_SIM_FCFG_HAS_PFLSH_SWAP (0) /* @brief Has miscellanious control register (register MCR). */ #define FSL_FEATURE_SIM_HAS_MISC_CONTROLS (0) /* @brief Has COP watchdog (registers COPC and SRVCOP). */ #define FSL_FEATURE_SIM_HAS_COP_WATCHDOG (0) /* @brief Has COP watchdog stop (register bits COPC[COPSTPEN], COPC[COPDBGEN] and COPC[COPCLKSEL]). */ #define FSL_FEATURE_SIM_HAS_COP_STOP (0) #elif defined(CPU_MK22FN256VDC12) || defined(CPU_MK22FN256VLH12) || defined(CPU_MK22FN256VLL12) || defined(CPU_MK22FN256VMP12) /* @brief Has USB FS divider. */ #define FSL_FEATURE_SIM_USBFS_USE_SPECIAL_DIVIDER (0) /* @brief Is PLL clock divided by 2 before MCG PLL/FLL clock selection. */ #define FSL_FEATURE_SIM_PLLCLK_USE_SPECIAL_DIVIDER (0) /* @brief Has RAM size specification (register bit field SOPT1[RAMSIZE]). */ #define FSL_FEATURE_SIM_OPT_HAS_RAMSIZE (1) /* @brief Has 32k oscillator clock output (register bit SOPT1[OSC32KOUT]). */ #define FSL_FEATURE_SIM_OPT_HAS_OSC32K_OUT (1) /* @brief Has 32k oscillator clock selection (register bit field SOPT1[OSC32KSEL]). */ #define FSL_FEATURE_SIM_OPT_HAS_OSC32K_SELECTION (1) /* @brief 32k oscillator clock selection width (width of register bit field SOPT1[OSC32KSEL]). */ #define FSL_FEATURE_SIM_OPT_OSC32K_SELECTION_WIDTH (2) /* @brief Has RTC clock output selection (register bit SOPT2[RTCCLKOUTSEL]). */ #define FSL_FEATURE_SIM_OPT_HAS_RTC_CLOCK_OUT_SELECTION (1) /* @brief Has USB voltage regulator (register bits SOPT1[USBVSTBY], SOPT1[USBSSTBY], SOPT1[USBREGEN], SOPT1CFG[URWE], SOPT1CFG[UVSWE], SOPT1CFG[USSWE]). */ #define FSL_FEATURE_SIM_OPT_HAS_USB_VOLTAGE_REGULATOR (1) /* @brief USB has integrated PHY (register bits USBPHYCTL[USBVREGSEL], USBPHYCTL[USBVREGPD], USBPHYCTL[USB3VOUTTRG], USBPHYCTL[USBDISILIM], SOPT2[USBSLSRC], SOPT2[USBREGEN]). */ #define FSL_FEATURE_SIM_OPT_HAS_USB_PHY (0) /* @brief Has PTD7 pad drive strength control (register bit SOPT2[PTD7PAD]). */ #define FSL_FEATURE_SIM_OPT_HAS_PTD7PAD (0) /* @brief Has FlexBus security level selection (register bit SOPT2[FBSL]). */ #define FSL_FEATURE_SIM_OPT_HAS_FBSL (0) /* @brief Has number of FlexBus hold cycle before FlexBus can release bus (register bit SOPT6[PCR]). */ #define FSL_FEATURE_SIM_OPT_HAS_PCR (0) /* @brief Has number of NFC hold cycle in case of FlexBus request (register bit SOPT6[MCC]). */ #define FSL_FEATURE_SIM_OPT_HAS_MCC (0) /* @brief Has UART open drain enable (register bits UARTnODE, where n is a number, in register SOPT5). */ #define FSL_FEATURE_SIM_OPT_HAS_ODE (0) /* @brief Number of UART modules (number of register bits UARTn, where n is a number, in register SCGC4). */ #define FSL_FEATURE_SIM_OPT_UART_COUNT (3) /* @brief Has LPUART0 open drain enable (register bit SOPT5[LPUART0ODE]). */ #define FSL_FEATURE_SIM_OPT_HAS_LPUART0_ODE (0) /* @brief Has LPUART1 open drain enable (register bit SOPT5[LPUART1ODE]). */ #define FSL_FEATURE_SIM_OPT_HAS_LPUART1_ODE (0) /* @brief Has CMT/UART pad drive strength control (register bit SOPT2[CMTUARTPAD]). */ #define FSL_FEATURE_SIM_OPT_HAS_CMTUARTPAD (0) /* @brief Has LPUART0 transmit data source selection (register bit SOPT5[LPUART0TXSRC]). */ #define FSL_FEATURE_SIM_OPT_HAS_LPUART0_TX_SRC (0) /* @brief Has LPUART0 receive data source selection (register bit SOPT5[LPUART0RXSRC]). */ #define FSL_FEATURE_SIM_OPT_HAS_LPUART0_RX_SRC (1) /* @brief Has LPUART1 transmit data source selection (register bit SOPT5[LPUART1TXSRC]). */ #define FSL_FEATURE_SIM_OPT_HAS_LPUART1_TX_SRC (0) /* @brief Has LPUART1 receive data source selection (register bit SOPT5[LPUART1RXSRC]). */ #define FSL_FEATURE_SIM_OPT_HAS_LPUART1_RX_SRC (0) /* @brief Has UART0 transmit data source selection (register bit SOPT5[UART0TXSRC]). */ #define FSL_FEATURE_SIM_OPT_HAS_UART0_TX_SRC (1) /* @brief UART0 transmit data source selection width (width of register bit SOPT5[UART0TXSRC]). */ #define FSL_FEATURE_SIM_OPT_UART0_TX_SRC_WIDTH (2) /* @brief Has UART0 receive data source selection (register bit SOPT5[UART0RXSRC]). */ #define FSL_FEATURE_SIM_OPT_HAS_UART0_RX_SRC (1) /* @brief UART0 receive data source selection width (width of register bit SOPT5[UART0RXSRC]). */ #define FSL_FEATURE_SIM_OPT_UART0_RX_SRC_WIDTH (2) /* @brief Has UART1 transmit data source selection (register bit SOPT5[UART1TXSRC]). */ #define FSL_FEATURE_SIM_OPT_HAS_UART1_TX_SRC (1) /* @brief Has UART1 receive data source selection (register bit SOPT5[UART1RXSRC]). */ #define FSL_FEATURE_SIM_OPT_HAS_UART1_RX_SRC (1) /* @brief UART1 receive data source selection width (width of register bit SOPT5[UART1RXSRC]). */ #define FSL_FEATURE_SIM_OPT_UART1_RX_SRC_WIDTH (2) /* @brief Has FTM module(s) configuration. */ #define FSL_FEATURE_SIM_OPT_HAS_FTM (1) /* @brief Number of FTM modules. */ #define FSL_FEATURE_SIM_OPT_FTM_COUNT (3) /* @brief Number of FTM triggers with selectable source. */ #define FSL_FEATURE_SIM_OPT_FTM_TRIGGER_COUNT (2) /* @brief Has FTM0 triggers source selection (register bits SOPT4[FTM0TRGnSRC], where n is a number). */ #define FSL_FEATURE_SIM_OPT_HAS_FTM0_TRIGGER (1) /* @brief Has FTM3 triggers source selection (register bits SOPT4[FTM3TRGnSRC], where n is a number). */ #define FSL_FEATURE_SIM_OPT_HAS_FTM3_TRIGGER (0) /* @brief Has FTM1 channel 0 input capture source selection (register bit SOPT4[FTM1CH0SRC]). */ #define FSL_FEATURE_SIM_OPT_HAS_FTM1_CHANNELS (1) /* @brief Has FTM2 channel 0 input capture source selection (register bit SOPT4[FTM2CH0SRC]). */ #define FSL_FEATURE_SIM_OPT_HAS_FTM2_CHANNELS (1) /* @brief Has FTM3 channel 0 input capture source selection (register bit SOPT4[FTM3CH0SRC]). */ #define FSL_FEATURE_SIM_OPT_HAS_FTM3_CHANNELS (0) /* @brief Has FTM2 channel 1 input capture source selection (register bit SOPT4[FTM2CH1SRC]). */ #define FSL_FEATURE_SIM_OPT_HAS_FTM2_CHANNEL1 (1) /* @brief Number of configurable FTM0 fault detection input (number of register bits SOPT4[FTM0FLTn], where n is a number starting from zero). */ #define FSL_FEATURE_SIM_OPT_FTM0_FAULT_COUNT (2) /* @brief Number of configurable FTM1 fault detection input (number of register bits SOPT4[FTM1FLTn], where n is a number starting from zero). */ #define FSL_FEATURE_SIM_OPT_FTM1_FAULT_COUNT (1) /* @brief Number of configurable FTM2 fault detection input (number of register bits SOPT4[FTM2FLTn], where n is a number starting from zero). */ #define FSL_FEATURE_SIM_OPT_FTM2_FAULT_COUNT (1) /* @brief Number of configurable FTM3 fault detection input (number of register bits SOPT4[FTM3FLTn], where n is a number starting from zero). */ #define FSL_FEATURE_SIM_OPT_FTM3_FAULT_COUNT (0) /* @brief Has FTM hardware trigger 0 software synchronization (register bit SOPT8[FTMnSYNCBIT], where n is a module instance index). */ #define FSL_FEATURE_SIM_OPT_HAS_FTM_TRIGGER_SYNC (1) /* @brief Has FTM channels output source selection (register bit SOPT8[FTMxOCHnSRC], where x is a module instance index and n is a channel index). */ #define FSL_FEATURE_SIM_OPT_HAS_FTM_CHANNELS_OUTPUT_SRC (1) /* @brief Has TPM module(s) configuration. */ #define FSL_FEATURE_SIM_OPT_HAS_TPM (0) /* @brief The highest TPM module index. */ #define FSL_FEATURE_SIM_OPT_MAX_TPM_INDEX (0) /* @brief Has TPM module with index 0. */ #define FSL_FEATURE_SIM_OPT_HAS_TPM0 (0) /* @brief Is TPM channels configuration in the SOPT4 (not SOPT9) register (register bits TPMnCH0SRC, TPMnCLKSEL, where n is a module instance index). */ #define FSL_FEATURE_SIM_OPT_HAS_TPM_CHANNELS_CONFIG_IN_SOPT4_REG (0) /* @brief Has TPM1 channel 0 input capture source selection (register bit field SOPT4[TPM1CH0SRC] or SOPT9[TPM1CH0SRC]). */ #define FSL_FEATURE_SIM_OPT_HAS_TPM1_CH0_SRC_SELECTION (0) /* @brief TPM1 channel 0 input capture source selection width (width of register bit field SOPT4[TPM1CH0SRC] or SOPT9[TPM1CH0SRC]). */ #define FSL_FEATURE_SIM_OPT_TPM1_CH0_SRC_SELECTION_WIDTH (0) /* @brief Has TPM2 channel 0 input capture source selection (register bit field SOPT4[TPM2CH0SRC]). */ #define FSL_FEATURE_SIM_OPT_HAS_TPM2_CH0_SRC_SELECTION (0) /* @brief Has TPM2 clock selection (register bit field SOPT4[TPM2CLKSEL]). */ #define FSL_FEATURE_SIM_OPT_HAS_TPM2_CLK_SEL (0) /* @brief Has PLL/FLL clock selection (register bit field SOPT2[PLLFLLSEL]). */ #define FSL_FEATURE_SIM_OPT_HAS_PLL_FLL_SELECTION (1) /* @brief PLL/FLL clock selection width (width of register bit field SOPT2[PLLFLLSEL]). */ #define FSL_FEATURE_SIM_OPT_PLL_FLL_SELECTION_WIDTH (1) /* @brief Has NFC clock source selection (register bit SOPT2[NFCSRC]). */ #define FSL_FEATURE_SIM_OPT_HAS_NFCSRC (0) /* @brief Has eSDHC clock source selection (register bit SOPT2[ESDHCSRC]). */ #define FSL_FEATURE_SIM_OPT_HAS_ESDHCSRC (0) /* @brief Has SDHC clock source selection (register bit SOPT2[SDHCSRC]). */ #define FSL_FEATURE_SIM_OPT_HAS_SDHCSRC (0) /* @brief Has LCDC clock source selection (register bits SOPT2[LCDCSRC], SOPT2[LCDC_CLKSEL]). */ #define FSL_FEATURE_SIM_OPT_HAS_LCDCSRC (0) /* @brief Has ENET timestamp clock source selection (register bit SOPT2[TIMESRC]). */ #define FSL_FEATURE_SIM_OPT_HAS_TIMESRC (0) /* @brief Has ENET RMII clock source selection (register bit SOPT2[RMIISRC]). */ #define FSL_FEATURE_SIM_OPT_HAS_RMIISRC (0) /* @brief Has USB clock source selection (register bit SOPT2[USBSRC]). */ #define FSL_FEATURE_SIM_OPT_HAS_USBSRC (1) /* @brief Has USB FS clock source selection (register bit SOPT2[USBFSRC]). */ #define FSL_FEATURE_SIM_OPT_HAS_USBFSRC (0) /* @brief Has USB HS clock source selection (register bit SOPT2[USBHSRC]). */ #define FSL_FEATURE_SIM_OPT_HAS_USBHSRC (0) /* @brief Has LPUART clock source selection (register bit SOPT2[LPUARTSRC]). */ #define FSL_FEATURE_SIM_OPT_HAS_LPUARTSRC (1) /* @brief Has LPUART0 clock source selection (register bit SOPT2[LPUART0SRC]). */ #define FSL_FEATURE_SIM_OPT_HAS_LPUART0SRC (0) /* @brief Has LPUART1 clock source selection (register bit SOPT2[LPUART1SRC]). */ #define FSL_FEATURE_SIM_OPT_HAS_LPUART1SRC (0) /* @brief Has FLEXIOSRC clock source selection (register bit SOPT2[FLEXIOSRC]). */ #define FSL_FEATURE_SIM_OPT_HAS_FLEXIOSRC (0) /* @brief Has UART0 clock source selection (register bit SOPT2[UART0SRC]). */ #define FSL_FEATURE_SIM_OPT_HAS_UART0SRC (0) /* @brief Has TPM clock source selection (register bit SOPT2[TPMSRC]). */ #define FSL_FEATURE_SIM_OPT_HAS_TPMSRC (0) /* @brief Has debug trace clock selection (register bit SOPT2[TRACECLKSEL]). */ #define FSL_FEATURE_SIM_OPT_HAS_TRACE_CLKSEL (1) /* @brief Number of ADC modules (register bits SOPT7[ADCnTRGSEL], SOPT7[ADCnPRETRGSEL], SOPT7[ADCnALTTRGSEL], where n is a module instance index). */ #define FSL_FEATURE_SIM_OPT_ADC_COUNT (2) /* @brief Has clock 2 output divider (register bit field CLKDIV1[OUTDIV2]). */ #define FSL_FEATURE_SIM_DIVIDER_HAS_OUTDIV2 (1) /* @brief Has clock 3 output divider (register bit field CLKDIV1[OUTDIV3]). */ #define FSL_FEATURE_SIM_DIVIDER_HAS_OUTDIV3 (0) /* @brief Has clock 4 output divider (register bit field CLKDIV1[OUTDIV4]). */ #define FSL_FEATURE_SIM_DIVIDER_HAS_OUTDIV4 (1) /* @brief Clock 4 output divider width (width of register bit field CLKDIV1[OUTDIV4]). */ #define FSL_FEATURE_SIM_DIVIDER_OUTDIV4_WIDTH (4) /* @brief Has USB clock divider (register bit field CLKDIV2[USBDIV] and CLKDIV2[USBFRAC]). */ #define FSL_FEATURE_SIM_DIVIDER_HAS_USBDIV (1) /* @brief Has USB FS clock divider (register bit field CLKDIV2[USBFSDIV] and CLKDIV2[USBFSFRAC]). */ #define FSL_FEATURE_SIM_DIVIDER_HAS_USBFSDIV (0) /* @brief Has USB HS clock divider (register bit field CLKDIV2[USBHSDIV] and CLKDIV2[USBHSFRAC]). */ #define FSL_FEATURE_SIM_DIVIDER_HAS_USBHSDIV (0) /* @brief Has PLL/FLL clock divider (register bit field CLKDIV3[PLLFLLDIV] and CLKDIV3[PLLFLLFRAC]). */ #define FSL_FEATURE_SIM_DIVIDER_HAS_PLLFLLDIV (0) /* @brief Has LCDC clock divider (register bit field CLKDIV3[LCDCDIV] and CLKDIV3[LCDCFRAC]). */ #define FSL_FEATURE_SIM_DIVIDER_HAS_LCDCDIV (0) /* @brief Has trace clock divider (register bit field CLKDIV4[TRACEDIV] and CLKDIV4[TRACEFRAC]). */ #define FSL_FEATURE_SIM_DIVIDER_HAS_TRACEDIV (0) /* @brief Has NFC clock divider (register bit field CLKDIV4[NFCDIV] and CLKDIV4[NFCFRAC]). */ #define FSL_FEATURE_SIM_DIVIDER_HAS_NFCDIV (0) /* @brief Has Kinetis family ID (register bit field SDID[FAMILYID]). */ #define FSL_FEATURE_SIM_SDID_HAS_FAMILYID (1) /* @brief Has Kinetis family ID (register bit field SDID[FAMID]). */ #define FSL_FEATURE_SIM_SDID_HAS_FAMID (1) /* @brief Has Kinetis sub-family ID (register bit field SDID[SUBFAMID]). */ #define FSL_FEATURE_SIM_SDID_HAS_SUBFAMID (1) /* @brief Has Kinetis series ID (register bit field SDID[SERIESID]). */ #define FSL_FEATURE_SIM_SDID_HAS_SERIESID (1) /* @brief Has device die ID (register bit field SDID[DIEID]). */ #define FSL_FEATURE_SIM_SDID_HAS_DIEID (1) /* @brief Has system SRAM size specifier (register bit field SDID[SRAMSIZE]). */ #define FSL_FEATURE_SIM_SDID_HAS_SRAMSIZE (0) /* @brief Has flash mode (register bit FCFG1[FLASHDOZE]). */ #define FSL_FEATURE_SIM_FCFG_HAS_FLASHDOZE (1) /* @brief Has flash disable (register bit FCFG1[FLASHDIS]). */ #define FSL_FEATURE_SIM_FCFG_HAS_FLASHDIS (1) /* @brief Has FTFE disable (register bit FCFG1[FTFDIS]). */ #define FSL_FEATURE_SIM_FCFG_HAS_FTFDIS (0) /* @brief Has FlexNVM size specifier (register bit field FCFG1[NVMSIZE]). */ #define FSL_FEATURE_SIM_FCFG_HAS_NVMSIZE (0) /* @brief Has EEPROM size specifier (register bit field FCFG1[EESIZE]). */ #define FSL_FEATURE_SIM_FCFG_HAS_EESIZE (0) /* @brief Has FlexNVM partition (register bit field FCFG1[DEPART]). */ #define FSL_FEATURE_SIM_FCFG_HAS_DEPART (0) /* @brief Maximum flash address block 0 address specifier (register bit field FCFG2[MAXADDR0]). */ #define FSL_FEATURE_SIM_FCFG_HAS_MAXADDR0 (1) /* @brief Maximum flash address block 1 address specifier (register bit field FCFG2[MAXADDR1]). */ #define FSL_FEATURE_SIM_FCFG_HAS_MAXADDR1 (1) /* @brief Maximum flash address block 0 or 1 address specifier (register bit field FCFG2[MAXADDR01]). */ #define FSL_FEATURE_SIM_FCFG_HAS_MAXADDR01 (0) /* @brief Maximum flash address block 2 or 3 address specifier (register bit field FCFG2[MAXADDR23]). */ #define FSL_FEATURE_SIM_FCFG_HAS_MAXADDR23 (0) /* @brief Has program flash availability specifier (register bit FCFG2[PFLSH]). */ #define FSL_FEATURE_SIM_FCFG_HAS_PFLSH (0) /* @brief Has program flash swapping (register bit FCFG2[SWAPPFLSH]). */ #define FSL_FEATURE_SIM_FCFG_HAS_PFLSH_SWAP (0) /* @brief Has miscellanious control register (register MCR). */ #define FSL_FEATURE_SIM_HAS_MISC_CONTROLS (0) /* @brief Has COP watchdog (registers COPC and SRVCOP). */ #define FSL_FEATURE_SIM_HAS_COP_WATCHDOG (0) /* @brief Has COP watchdog stop (register bits COPC[COPSTPEN], COPC[COPDBGEN] and COPC[COPCLKSEL]). */ #define FSL_FEATURE_SIM_HAS_COP_STOP (0) #elif defined(CPU_MK22FN512VDC12) || defined(CPU_MK22FN512VLH12) || defined(CPU_MK22FN512VLL12) /* @brief Has USB FS divider. */ #define FSL_FEATURE_SIM_USBFS_USE_SPECIAL_DIVIDER (0) /* @brief Is PLL clock divided by 2 before MCG PLL/FLL clock selection. */ #define FSL_FEATURE_SIM_PLLCLK_USE_SPECIAL_DIVIDER (0) /* @brief Has RAM size specification (register bit field SOPT1[RAMSIZE]). */ #define FSL_FEATURE_SIM_OPT_HAS_RAMSIZE (1) /* @brief Has 32k oscillator clock output (register bit SOPT1[OSC32KOUT]). */ #define FSL_FEATURE_SIM_OPT_HAS_OSC32K_OUT (1) /* @brief Has 32k oscillator clock selection (register bit field SOPT1[OSC32KSEL]). */ #define FSL_FEATURE_SIM_OPT_HAS_OSC32K_SELECTION (1) /* @brief 32k oscillator clock selection width (width of register bit field SOPT1[OSC32KSEL]). */ #define FSL_FEATURE_SIM_OPT_OSC32K_SELECTION_WIDTH (2) /* @brief Has RTC clock output selection (register bit SOPT2[RTCCLKOUTSEL]). */ #define FSL_FEATURE_SIM_OPT_HAS_RTC_CLOCK_OUT_SELECTION (1) /* @brief Has USB voltage regulator (register bits SOPT1[USBVSTBY], SOPT1[USBSSTBY], SOPT1[USBREGEN], SOPT1CFG[URWE], SOPT1CFG[UVSWE], SOPT1CFG[USSWE]). */ #define FSL_FEATURE_SIM_OPT_HAS_USB_VOLTAGE_REGULATOR (1) /* @brief USB has integrated PHY (register bits USBPHYCTL[USBVREGSEL], USBPHYCTL[USBVREGPD], USBPHYCTL[USB3VOUTTRG], USBPHYCTL[USBDISILIM], SOPT2[USBSLSRC], SOPT2[USBREGEN]). */ #define FSL_FEATURE_SIM_OPT_HAS_USB_PHY (0) /* @brief Has PTD7 pad drive strength control (register bit SOPT2[PTD7PAD]). */ #define FSL_FEATURE_SIM_OPT_HAS_PTD7PAD (0) /* @brief Has FlexBus security level selection (register bit SOPT2[FBSL]). */ #define FSL_FEATURE_SIM_OPT_HAS_FBSL (1) /* @brief Has number of FlexBus hold cycle before FlexBus can release bus (register bit SOPT6[PCR]). */ #define FSL_FEATURE_SIM_OPT_HAS_PCR (0) /* @brief Has number of NFC hold cycle in case of FlexBus request (register bit SOPT6[MCC]). */ #define FSL_FEATURE_SIM_OPT_HAS_MCC (0) /* @brief Has UART open drain enable (register bits UARTnODE, where n is a number, in register SOPT5). */ #define FSL_FEATURE_SIM_OPT_HAS_ODE (0) /* @brief Number of UART modules (number of register bits UARTn, where n is a number, in register SCGC4). */ #define FSL_FEATURE_SIM_OPT_UART_COUNT (3) /* @brief Has LPUART0 open drain enable (register bit SOPT5[LPUART0ODE]). */ #define FSL_FEATURE_SIM_OPT_HAS_LPUART0_ODE (0) /* @brief Has LPUART1 open drain enable (register bit SOPT5[LPUART1ODE]). */ #define FSL_FEATURE_SIM_OPT_HAS_LPUART1_ODE (0) /* @brief Has CMT/UART pad drive strength control (register bit SOPT2[CMTUARTPAD]). */ #define FSL_FEATURE_SIM_OPT_HAS_CMTUARTPAD (0) /* @brief Has LPUART0 transmit data source selection (register bit SOPT5[LPUART0TXSRC]). */ #define FSL_FEATURE_SIM_OPT_HAS_LPUART0_TX_SRC (0) /* @brief Has LPUART0 receive data source selection (register bit SOPT5[LPUART0RXSRC]). */ #define FSL_FEATURE_SIM_OPT_HAS_LPUART0_RX_SRC (1) /* @brief Has LPUART1 transmit data source selection (register bit SOPT5[LPUART1TXSRC]). */ #define FSL_FEATURE_SIM_OPT_HAS_LPUART1_TX_SRC (0) /* @brief Has LPUART1 receive data source selection (register bit SOPT5[LPUART1RXSRC]). */ #define FSL_FEATURE_SIM_OPT_HAS_LPUART1_RX_SRC (0) /* @brief Has UART0 transmit data source selection (register bit SOPT5[UART0TXSRC]). */ #define FSL_FEATURE_SIM_OPT_HAS_UART0_TX_SRC (1) /* @brief UART0 transmit data source selection width (width of register bit SOPT5[UART0TXSRC]). */ #define FSL_FEATURE_SIM_OPT_UART0_TX_SRC_WIDTH (2) /* @brief Has UART0 receive data source selection (register bit SOPT5[UART0RXSRC]). */ #define FSL_FEATURE_SIM_OPT_HAS_UART0_RX_SRC (1) /* @brief UART0 receive data source selection width (width of register bit SOPT5[UART0RXSRC]). */ #define FSL_FEATURE_SIM_OPT_UART0_RX_SRC_WIDTH (2) /* @brief Has UART1 transmit data source selection (register bit SOPT5[UART1TXSRC]). */ #define FSL_FEATURE_SIM_OPT_HAS_UART1_TX_SRC (1) /* @brief Has UART1 receive data source selection (register bit SOPT5[UART1RXSRC]). */ #define FSL_FEATURE_SIM_OPT_HAS_UART1_RX_SRC (1) /* @brief UART1 receive data source selection width (width of register bit SOPT5[UART1RXSRC]). */ #define FSL_FEATURE_SIM_OPT_UART1_RX_SRC_WIDTH (2) /* @brief Has FTM module(s) configuration. */ #define FSL_FEATURE_SIM_OPT_HAS_FTM (1) /* @brief Number of FTM modules. */ #define FSL_FEATURE_SIM_OPT_FTM_COUNT (4) /* @brief Number of FTM triggers with selectable source. */ #define FSL_FEATURE_SIM_OPT_FTM_TRIGGER_COUNT (2) /* @brief Has FTM0 triggers source selection (register bits SOPT4[FTM0TRGnSRC], where n is a number). */ #define FSL_FEATURE_SIM_OPT_HAS_FTM0_TRIGGER (1) /* @brief Has FTM3 triggers source selection (register bits SOPT4[FTM3TRGnSRC], where n is a number). */ #define FSL_FEATURE_SIM_OPT_HAS_FTM3_TRIGGER (1) /* @brief Has FTM1 channel 0 input capture source selection (register bit SOPT4[FTM1CH0SRC]). */ #define FSL_FEATURE_SIM_OPT_HAS_FTM1_CHANNELS (1) /* @brief Has FTM2 channel 0 input capture source selection (register bit SOPT4[FTM2CH0SRC]). */ #define FSL_FEATURE_SIM_OPT_HAS_FTM2_CHANNELS (1) /* @brief Has FTM3 channel 0 input capture source selection (register bit SOPT4[FTM3CH0SRC]). */ #define FSL_FEATURE_SIM_OPT_HAS_FTM3_CHANNELS (0) /* @brief Has FTM2 channel 1 input capture source selection (register bit SOPT4[FTM2CH1SRC]). */ #define FSL_FEATURE_SIM_OPT_HAS_FTM2_CHANNEL1 (1) /* @brief Number of configurable FTM0 fault detection input (number of register bits SOPT4[FTM0FLTn], where n is a number starting from zero). */ #define FSL_FEATURE_SIM_OPT_FTM0_FAULT_COUNT (2) /* @brief Number of configurable FTM1 fault detection input (number of register bits SOPT4[FTM1FLTn], where n is a number starting from zero). */ #define FSL_FEATURE_SIM_OPT_FTM1_FAULT_COUNT (1) /* @brief Number of configurable FTM2 fault detection input (number of register bits SOPT4[FTM2FLTn], where n is a number starting from zero). */ #define FSL_FEATURE_SIM_OPT_FTM2_FAULT_COUNT (1) /* @brief Number of configurable FTM3 fault detection input (number of register bits SOPT4[FTM3FLTn], where n is a number starting from zero). */ #define FSL_FEATURE_SIM_OPT_FTM3_FAULT_COUNT (1) /* @brief Has FTM hardware trigger 0 software synchronization (register bit SOPT8[FTMnSYNCBIT], where n is a module instance index). */ #define FSL_FEATURE_SIM_OPT_HAS_FTM_TRIGGER_SYNC (1) /* @brief Has FTM channels output source selection (register bit SOPT8[FTMxOCHnSRC], where x is a module instance index and n is a channel index). */ #define FSL_FEATURE_SIM_OPT_HAS_FTM_CHANNELS_OUTPUT_SRC (1) /* @brief Has TPM module(s) configuration. */ #define FSL_FEATURE_SIM_OPT_HAS_TPM (0) /* @brief The highest TPM module index. */ #define FSL_FEATURE_SIM_OPT_MAX_TPM_INDEX (0) /* @brief Has TPM module with index 0. */ #define FSL_FEATURE_SIM_OPT_HAS_TPM0 (0) /* @brief Is TPM channels configuration in the SOPT4 (not SOPT9) register (register bits TPMnCH0SRC, TPMnCLKSEL, where n is a module instance index). */ #define FSL_FEATURE_SIM_OPT_HAS_TPM_CHANNELS_CONFIG_IN_SOPT4_REG (0) /* @brief Has TPM1 channel 0 input capture source selection (register bit field SOPT4[TPM1CH0SRC] or SOPT9[TPM1CH0SRC]). */ #define FSL_FEATURE_SIM_OPT_HAS_TPM1_CH0_SRC_SELECTION (0) /* @brief TPM1 channel 0 input capture source selection width (width of register bit field SOPT4[TPM1CH0SRC] or SOPT9[TPM1CH0SRC]). */ #define FSL_FEATURE_SIM_OPT_TPM1_CH0_SRC_SELECTION_WIDTH (0) /* @brief Has TPM2 channel 0 input capture source selection (register bit field SOPT4[TPM2CH0SRC]). */ #define FSL_FEATURE_SIM_OPT_HAS_TPM2_CH0_SRC_SELECTION (0) /* @brief Has TPM2 clock selection (register bit field SOPT4[TPM2CLKSEL]). */ #define FSL_FEATURE_SIM_OPT_HAS_TPM2_CLK_SEL (0) /* @brief Has PLL/FLL clock selection (register bit field SOPT2[PLLFLLSEL]). */ #define FSL_FEATURE_SIM_OPT_HAS_PLL_FLL_SELECTION (1) /* @brief PLL/FLL clock selection width (width of register bit field SOPT2[PLLFLLSEL]). */ #define FSL_FEATURE_SIM_OPT_PLL_FLL_SELECTION_WIDTH (1) /* @brief Has NFC clock source selection (register bit SOPT2[NFCSRC]). */ #define FSL_FEATURE_SIM_OPT_HAS_NFCSRC (0) /* @brief Has eSDHC clock source selection (register bit SOPT2[ESDHCSRC]). */ #define FSL_FEATURE_SIM_OPT_HAS_ESDHCSRC (0) /* @brief Has SDHC clock source selection (register bit SOPT2[SDHCSRC]). */ #define FSL_FEATURE_SIM_OPT_HAS_SDHCSRC (0) /* @brief Has LCDC clock source selection (register bits SOPT2[LCDCSRC], SOPT2[LCDC_CLKSEL]). */ #define FSL_FEATURE_SIM_OPT_HAS_LCDCSRC (0) /* @brief Has ENET timestamp clock source selection (register bit SOPT2[TIMESRC]). */ #define FSL_FEATURE_SIM_OPT_HAS_TIMESRC (0) /* @brief Has ENET RMII clock source selection (register bit SOPT2[RMIISRC]). */ #define FSL_FEATURE_SIM_OPT_HAS_RMIISRC (0) /* @brief Has USB clock source selection (register bit SOPT2[USBSRC]). */ #define FSL_FEATURE_SIM_OPT_HAS_USBSRC (1) /* @brief Has USB FS clock source selection (register bit SOPT2[USBFSRC]). */ #define FSL_FEATURE_SIM_OPT_HAS_USBFSRC (0) /* @brief Has USB HS clock source selection (register bit SOPT2[USBHSRC]). */ #define FSL_FEATURE_SIM_OPT_HAS_USBHSRC (0) /* @brief Has LPUART clock source selection (register bit SOPT2[LPUARTSRC]). */ #define FSL_FEATURE_SIM_OPT_HAS_LPUARTSRC (1) /* @brief Has LPUART0 clock source selection (register bit SOPT2[LPUART0SRC]). */ #define FSL_FEATURE_SIM_OPT_HAS_LPUART0SRC (0) /* @brief Has LPUART1 clock source selection (register bit SOPT2[LPUART1SRC]). */ #define FSL_FEATURE_SIM_OPT_HAS_LPUART1SRC (0) /* @brief Has FLEXIOSRC clock source selection (register bit SOPT2[FLEXIOSRC]). */ #define FSL_FEATURE_SIM_OPT_HAS_FLEXIOSRC (0) /* @brief Has UART0 clock source selection (register bit SOPT2[UART0SRC]). */ #define FSL_FEATURE_SIM_OPT_HAS_UART0SRC (0) /* @brief Has TPM clock source selection (register bit SOPT2[TPMSRC]). */ #define FSL_FEATURE_SIM_OPT_HAS_TPMSRC (0) /* @brief Has debug trace clock selection (register bit SOPT2[TRACECLKSEL]). */ #define FSL_FEATURE_SIM_OPT_HAS_TRACE_CLKSEL (1) /* @brief Number of ADC modules (register bits SOPT7[ADCnTRGSEL], SOPT7[ADCnPRETRGSEL], SOPT7[ADCnALTTRGSEL], where n is a module instance index). */ #define FSL_FEATURE_SIM_OPT_ADC_COUNT (2) /* @brief Has clock 2 output divider (register bit field CLKDIV1[OUTDIV2]). */ #define FSL_FEATURE_SIM_DIVIDER_HAS_OUTDIV2 (1) /* @brief Has clock 3 output divider (register bit field CLKDIV1[OUTDIV3]). */ #define FSL_FEATURE_SIM_DIVIDER_HAS_OUTDIV3 (1) /* @brief Has clock 4 output divider (register bit field CLKDIV1[OUTDIV4]). */ #define FSL_FEATURE_SIM_DIVIDER_HAS_OUTDIV4 (1) /* @brief Clock 4 output divider width (width of register bit field CLKDIV1[OUTDIV4]). */ #define FSL_FEATURE_SIM_DIVIDER_OUTDIV4_WIDTH (4) /* @brief Has USB clock divider (register bit field CLKDIV2[USBDIV] and CLKDIV2[USBFRAC]). */ #define FSL_FEATURE_SIM_DIVIDER_HAS_USBDIV (1) /* @brief Has USB FS clock divider (register bit field CLKDIV2[USBFSDIV] and CLKDIV2[USBFSFRAC]). */ #define FSL_FEATURE_SIM_DIVIDER_HAS_USBFSDIV (0) /* @brief Has USB HS clock divider (register bit field CLKDIV2[USBHSDIV] and CLKDIV2[USBHSFRAC]). */ #define FSL_FEATURE_SIM_DIVIDER_HAS_USBHSDIV (0) /* @brief Has PLL/FLL clock divider (register bit field CLKDIV3[PLLFLLDIV] and CLKDIV3[PLLFLLFRAC]). */ #define FSL_FEATURE_SIM_DIVIDER_HAS_PLLFLLDIV (0) /* @brief Has LCDC clock divider (register bit field CLKDIV3[LCDCDIV] and CLKDIV3[LCDCFRAC]). */ #define FSL_FEATURE_SIM_DIVIDER_HAS_LCDCDIV (0) /* @brief Has trace clock divider (register bit field CLKDIV4[TRACEDIV] and CLKDIV4[TRACEFRAC]). */ #define FSL_FEATURE_SIM_DIVIDER_HAS_TRACEDIV (0) /* @brief Has NFC clock divider (register bit field CLKDIV4[NFCDIV] and CLKDIV4[NFCFRAC]). */ #define FSL_FEATURE_SIM_DIVIDER_HAS_NFCDIV (0) /* @brief Has Kinetis family ID (register bit field SDID[FAMILYID]). */ #define FSL_FEATURE_SIM_SDID_HAS_FAMILYID (1) /* @brief Has Kinetis family ID (register bit field SDID[FAMID]). */ #define FSL_FEATURE_SIM_SDID_HAS_FAMID (1) /* @brief Has Kinetis sub-family ID (register bit field SDID[SUBFAMID]). */ #define FSL_FEATURE_SIM_SDID_HAS_SUBFAMID (1) /* @brief Has Kinetis series ID (register bit field SDID[SERIESID]). */ #define FSL_FEATURE_SIM_SDID_HAS_SERIESID (1) /* @brief Has device die ID (register bit field SDID[DIEID]). */ #define FSL_FEATURE_SIM_SDID_HAS_DIEID (1) /* @brief Has system SRAM size specifier (register bit field SDID[SRAMSIZE]). */ #define FSL_FEATURE_SIM_SDID_HAS_SRAMSIZE (0) /* @brief Has flash mode (register bit FCFG1[FLASHDOZE]). */ #define FSL_FEATURE_SIM_FCFG_HAS_FLASHDOZE (1) /* @brief Has flash disable (register bit FCFG1[FLASHDIS]). */ #define FSL_FEATURE_SIM_FCFG_HAS_FLASHDIS (1) /* @brief Has FTFE disable (register bit FCFG1[FTFDIS]). */ #define FSL_FEATURE_SIM_FCFG_HAS_FTFDIS (0) /* @brief Has FlexNVM size specifier (register bit field FCFG1[NVMSIZE]). */ #define FSL_FEATURE_SIM_FCFG_HAS_NVMSIZE (0) /* @brief Has EEPROM size specifier (register bit field FCFG1[EESIZE]). */ #define FSL_FEATURE_SIM_FCFG_HAS_EESIZE (0) /* @brief Has FlexNVM partition (register bit field FCFG1[DEPART]). */ #define FSL_FEATURE_SIM_FCFG_HAS_DEPART (0) /* @brief Maximum flash address block 0 address specifier (register bit field FCFG2[MAXADDR0]). */ #define FSL_FEATURE_SIM_FCFG_HAS_MAXADDR0 (1) /* @brief Maximum flash address block 1 address specifier (register bit field FCFG2[MAXADDR1]). */ #define FSL_FEATURE_SIM_FCFG_HAS_MAXADDR1 (1) /* @brief Maximum flash address block 0 or 1 address specifier (register bit field FCFG2[MAXADDR01]). */ #define FSL_FEATURE_SIM_FCFG_HAS_MAXADDR01 (0) /* @brief Maximum flash address block 2 or 3 address specifier (register bit field FCFG2[MAXADDR23]). */ #define FSL_FEATURE_SIM_FCFG_HAS_MAXADDR23 (0) /* @brief Has program flash availability specifier (register bit FCFG2[PFLSH]). */ #define FSL_FEATURE_SIM_FCFG_HAS_PFLSH (0) /* @brief Has program flash swapping (register bit FCFG2[SWAPPFLSH]). */ #define FSL_FEATURE_SIM_FCFG_HAS_PFLSH_SWAP (0) /* @brief Has miscellanious control register (register MCR). */ #define FSL_FEATURE_SIM_HAS_MISC_CONTROLS (0) /* @brief Has COP watchdog (registers COPC and SRVCOP). */ #define FSL_FEATURE_SIM_HAS_COP_WATCHDOG (0) /* @brief Has COP watchdog stop (register bits COPC[COPSTPEN], COPC[COPDBGEN] and COPC[COPCLKSEL]). */ #define FSL_FEATURE_SIM_HAS_COP_STOP (0) #elif defined(CPU_MK24FN1M0VDC12) || defined(CPU_MK24FN1M0VLL12) || defined(CPU_MK24FN1M0VLQ12) /* @brief Has USB FS divider. */ #define FSL_FEATURE_SIM_USBFS_USE_SPECIAL_DIVIDER (0) /* @brief Is PLL clock divided by 2 before MCG PLL/FLL clock selection. */ #define FSL_FEATURE_SIM_PLLCLK_USE_SPECIAL_DIVIDER (0) /* @brief Has RAM size specification (register bit field SOPT1[RAMSIZE]). */ #define FSL_FEATURE_SIM_OPT_HAS_RAMSIZE (1) /* @brief Has 32k oscillator clock output (register bit SOPT1[OSC32KOUT]). */ #define FSL_FEATURE_SIM_OPT_HAS_OSC32K_OUT (0) /* @brief Has 32k oscillator clock selection (register bit field SOPT1[OSC32KSEL]). */ #define FSL_FEATURE_SIM_OPT_HAS_OSC32K_SELECTION (1) /* @brief 32k oscillator clock selection width (width of register bit field SOPT1[OSC32KSEL]). */ #define FSL_FEATURE_SIM_OPT_OSC32K_SELECTION_WIDTH (2) /* @brief Has RTC clock output selection (register bit SOPT2[RTCCLKOUTSEL]). */ #define FSL_FEATURE_SIM_OPT_HAS_RTC_CLOCK_OUT_SELECTION (1) /* @brief Has USB voltage regulator (register bits SOPT1[USBVSTBY], SOPT1[USBSSTBY], SOPT1[USBREGEN], SOPT1CFG[URWE], SOPT1CFG[UVSWE], SOPT1CFG[USSWE]). */ #define FSL_FEATURE_SIM_OPT_HAS_USB_VOLTAGE_REGULATOR (1) /* @brief USB has integrated PHY (register bits USBPHYCTL[USBVREGSEL], USBPHYCTL[USBVREGPD], USBPHYCTL[USB3VOUTTRG], USBPHYCTL[USBDISILIM], SOPT2[USBSLSRC], SOPT2[USBREGEN]). */ #define FSL_FEATURE_SIM_OPT_HAS_USB_PHY (0) /* @brief Has PTD7 pad drive strength control (register bit SOPT2[PTD7PAD]). */ #define FSL_FEATURE_SIM_OPT_HAS_PTD7PAD (1) /* @brief Has FlexBus security level selection (register bit SOPT2[FBSL]). */ #define FSL_FEATURE_SIM_OPT_HAS_FBSL (1) /* @brief Has number of FlexBus hold cycle before FlexBus can release bus (register bit SOPT6[PCR]). */ #define FSL_FEATURE_SIM_OPT_HAS_PCR (0) /* @brief Has number of NFC hold cycle in case of FlexBus request (register bit SOPT6[MCC]). */ #define FSL_FEATURE_SIM_OPT_HAS_MCC (0) /* @brief Has UART open drain enable (register bits UARTnODE, where n is a number, in register SOPT5). */ #define FSL_FEATURE_SIM_OPT_HAS_ODE (0) /* @brief Number of UART modules (number of register bits UARTn, where n is a number, in register SCGC4). */ #define FSL_FEATURE_SIM_OPT_UART_COUNT (4) /* @brief Has LPUART0 open drain enable (register bit SOPT5[LPUART0ODE]). */ #define FSL_FEATURE_SIM_OPT_HAS_LPUART0_ODE (0) /* @brief Has LPUART1 open drain enable (register bit SOPT5[LPUART1ODE]). */ #define FSL_FEATURE_SIM_OPT_HAS_LPUART1_ODE (0) /* @brief Has CMT/UART pad drive strength control (register bit SOPT2[CMTUARTPAD]). */ #define FSL_FEATURE_SIM_OPT_HAS_CMTUARTPAD (0) /* @brief Has LPUART0 transmit data source selection (register bit SOPT5[LPUART0TXSRC]). */ #define FSL_FEATURE_SIM_OPT_HAS_LPUART0_TX_SRC (0) /* @brief Has LPUART0 receive data source selection (register bit SOPT5[LPUART0RXSRC]). */ #define FSL_FEATURE_SIM_OPT_HAS_LPUART0_RX_SRC (0) /* @brief Has LPUART1 transmit data source selection (register bit SOPT5[LPUART1TXSRC]). */ #define FSL_FEATURE_SIM_OPT_HAS_LPUART1_TX_SRC (0) /* @brief Has LPUART1 receive data source selection (register bit SOPT5[LPUART1RXSRC]). */ #define FSL_FEATURE_SIM_OPT_HAS_LPUART1_RX_SRC (0) /* @brief Has UART0 transmit data source selection (register bit SOPT5[UART0TXSRC]). */ #define FSL_FEATURE_SIM_OPT_HAS_UART0_TX_SRC (1) /* @brief UART0 transmit data source selection width (width of register bit SOPT5[UART0TXSRC]). */ #define FSL_FEATURE_SIM_OPT_UART0_TX_SRC_WIDTH (2) /* @brief Has UART0 receive data source selection (register bit SOPT5[UART0RXSRC]). */ #define FSL_FEATURE_SIM_OPT_HAS_UART0_RX_SRC (1) /* @brief UART0 receive data source selection width (width of register bit SOPT5[UART0RXSRC]). */ #define FSL_FEATURE_SIM_OPT_UART0_RX_SRC_WIDTH (2) /* @brief Has UART1 transmit data source selection (register bit SOPT5[UART1TXSRC]). */ #define FSL_FEATURE_SIM_OPT_HAS_UART1_TX_SRC (1) /* @brief Has UART1 receive data source selection (register bit SOPT5[UART1RXSRC]). */ #define FSL_FEATURE_SIM_OPT_HAS_UART1_RX_SRC (1) /* @brief UART1 receive data source selection width (width of register bit SOPT5[UART1RXSRC]). */ #define FSL_FEATURE_SIM_OPT_UART1_RX_SRC_WIDTH (2) /* @brief Has FTM module(s) configuration. */ #define FSL_FEATURE_SIM_OPT_HAS_FTM (1) /* @brief Number of FTM modules. */ #define FSL_FEATURE_SIM_OPT_FTM_COUNT (4) /* @brief Number of FTM triggers with selectable source. */ #define FSL_FEATURE_SIM_OPT_FTM_TRIGGER_COUNT (2) /* @brief Has FTM0 triggers source selection (register bits SOPT4[FTM0TRGnSRC], where n is a number). */ #define FSL_FEATURE_SIM_OPT_HAS_FTM0_TRIGGER (1) /* @brief Has FTM3 triggers source selection (register bits SOPT4[FTM3TRGnSRC], where n is a number). */ #define FSL_FEATURE_SIM_OPT_HAS_FTM3_TRIGGER (1) /* @brief Has FTM1 channel 0 input capture source selection (register bit SOPT4[FTM1CH0SRC]). */ #define FSL_FEATURE_SIM_OPT_HAS_FTM1_CHANNELS (1) /* @brief Has FTM2 channel 0 input capture source selection (register bit SOPT4[FTM2CH0SRC]). */ #define FSL_FEATURE_SIM_OPT_HAS_FTM2_CHANNELS (1) /* @brief Has FTM3 channel 0 input capture source selection (register bit SOPT4[FTM3CH0SRC]). */ #define FSL_FEATURE_SIM_OPT_HAS_FTM3_CHANNELS (0) /* @brief Has FTM2 channel 1 input capture source selection (register bit SOPT4[FTM2CH1SRC]). */ #define FSL_FEATURE_SIM_OPT_HAS_FTM2_CHANNEL1 (0) /* @brief Number of configurable FTM0 fault detection input (number of register bits SOPT4[FTM0FLTn], where n is a number starting from zero). */ #define FSL_FEATURE_SIM_OPT_FTM0_FAULT_COUNT (3) /* @brief Number of configurable FTM1 fault detection input (number of register bits SOPT4[FTM1FLTn], where n is a number starting from zero). */ #define FSL_FEATURE_SIM_OPT_FTM1_FAULT_COUNT (1) /* @brief Number of configurable FTM2 fault detection input (number of register bits SOPT4[FTM2FLTn], where n is a number starting from zero). */ #define FSL_FEATURE_SIM_OPT_FTM2_FAULT_COUNT (1) /* @brief Number of configurable FTM3 fault detection input (number of register bits SOPT4[FTM3FLTn], where n is a number starting from zero). */ #define FSL_FEATURE_SIM_OPT_FTM3_FAULT_COUNT (1) /* @brief Has FTM hardware trigger 0 software synchronization (register bit SOPT8[FTMnSYNCBIT], where n is a module instance index). */ #define FSL_FEATURE_SIM_OPT_HAS_FTM_TRIGGER_SYNC (0) /* @brief Has FTM channels output source selection (register bit SOPT8[FTMxOCHnSRC], where x is a module instance index and n is a channel index). */ #define FSL_FEATURE_SIM_OPT_HAS_FTM_CHANNELS_OUTPUT_SRC (0) /* @brief Has TPM module(s) configuration. */ #define FSL_FEATURE_SIM_OPT_HAS_TPM (0) /* @brief The highest TPM module index. */ #define FSL_FEATURE_SIM_OPT_MAX_TPM_INDEX (0) /* @brief Has TPM module with index 0. */ #define FSL_FEATURE_SIM_OPT_HAS_TPM0 (0) /* @brief Is TPM channels configuration in the SOPT4 (not SOPT9) register (register bits TPMnCH0SRC, TPMnCLKSEL, where n is a module instance index). */ #define FSL_FEATURE_SIM_OPT_HAS_TPM_CHANNELS_CONFIG_IN_SOPT4_REG (0) /* @brief Has TPM1 channel 0 input capture source selection (register bit field SOPT4[TPM1CH0SRC] or SOPT9[TPM1CH0SRC]). */ #define FSL_FEATURE_SIM_OPT_HAS_TPM1_CH0_SRC_SELECTION (0) /* @brief TPM1 channel 0 input capture source selection width (width of register bit field SOPT4[TPM1CH0SRC] or SOPT9[TPM1CH0SRC]). */ #define FSL_FEATURE_SIM_OPT_TPM1_CH0_SRC_SELECTION_WIDTH (0) /* @brief Has TPM2 channel 0 input capture source selection (register bit field SOPT4[TPM2CH0SRC]). */ #define FSL_FEATURE_SIM_OPT_HAS_TPM2_CH0_SRC_SELECTION (0) /* @brief Has TPM2 clock selection (register bit field SOPT4[TPM2CLKSEL]). */ #define FSL_FEATURE_SIM_OPT_HAS_TPM2_CLK_SEL (0) /* @brief Has PLL/FLL clock selection (register bit field SOPT2[PLLFLLSEL]). */ #define FSL_FEATURE_SIM_OPT_HAS_PLL_FLL_SELECTION (1) /* @brief PLL/FLL clock selection width (width of register bit field SOPT2[PLLFLLSEL]). */ #define FSL_FEATURE_SIM_OPT_PLL_FLL_SELECTION_WIDTH (1) /* @brief Has NFC clock source selection (register bit SOPT2[NFCSRC]). */ #define FSL_FEATURE_SIM_OPT_HAS_NFCSRC (0) /* @brief Has eSDHC clock source selection (register bit SOPT2[ESDHCSRC]). */ #define FSL_FEATURE_SIM_OPT_HAS_ESDHCSRC (0) /* @brief Has SDHC clock source selection (register bit SOPT2[SDHCSRC]). */ #define FSL_FEATURE_SIM_OPT_HAS_SDHCSRC (1) /* @brief Has LCDC clock source selection (register bits SOPT2[LCDCSRC], SOPT2[LCDC_CLKSEL]). */ #define FSL_FEATURE_SIM_OPT_HAS_LCDCSRC (0) /* @brief Has ENET timestamp clock source selection (register bit SOPT2[TIMESRC]). */ #define FSL_FEATURE_SIM_OPT_HAS_TIMESRC (0) /* @brief Has ENET RMII clock source selection (register bit SOPT2[RMIISRC]). */ #define FSL_FEATURE_SIM_OPT_HAS_RMIISRC (0) /* @brief Has USB clock source selection (register bit SOPT2[USBSRC]). */ #define FSL_FEATURE_SIM_OPT_HAS_USBSRC (1) /* @brief Has USB FS clock source selection (register bit SOPT2[USBFSRC]). */ #define FSL_FEATURE_SIM_OPT_HAS_USBFSRC (0) /* @brief Has USB HS clock source selection (register bit SOPT2[USBHSRC]). */ #define FSL_FEATURE_SIM_OPT_HAS_USBHSRC (0) /* @brief Has LPUART clock source selection (register bit SOPT2[LPUARTSRC]). */ #define FSL_FEATURE_SIM_OPT_HAS_LPUARTSRC (0) /* @brief Has LPUART0 clock source selection (register bit SOPT2[LPUART0SRC]). */ #define FSL_FEATURE_SIM_OPT_HAS_LPUART0SRC (0) /* @brief Has LPUART1 clock source selection (register bit SOPT2[LPUART1SRC]). */ #define FSL_FEATURE_SIM_OPT_HAS_LPUART1SRC (0) /* @brief Has FLEXIOSRC clock source selection (register bit SOPT2[FLEXIOSRC]). */ #define FSL_FEATURE_SIM_OPT_HAS_FLEXIOSRC (0) /* @brief Has UART0 clock source selection (register bit SOPT2[UART0SRC]). */ #define FSL_FEATURE_SIM_OPT_HAS_UART0SRC (0) /* @brief Has TPM clock source selection (register bit SOPT2[TPMSRC]). */ #define FSL_FEATURE_SIM_OPT_HAS_TPMSRC (0) /* @brief Has debug trace clock selection (register bit SOPT2[TRACECLKSEL]). */ #define FSL_FEATURE_SIM_OPT_HAS_TRACE_CLKSEL (1) /* @brief Number of ADC modules (register bits SOPT7[ADCnTRGSEL], SOPT7[ADCnPRETRGSEL], SOPT7[ADCnALTTRGSEL], where n is a module instance index). */ #define FSL_FEATURE_SIM_OPT_ADC_COUNT (2) /* @brief Has clock 2 output divider (register bit field CLKDIV1[OUTDIV2]). */ #define FSL_FEATURE_SIM_DIVIDER_HAS_OUTDIV2 (1) /* @brief Has clock 3 output divider (register bit field CLKDIV1[OUTDIV3]). */ #define FSL_FEATURE_SIM_DIVIDER_HAS_OUTDIV3 (1) /* @brief Has clock 4 output divider (register bit field CLKDIV1[OUTDIV4]). */ #define FSL_FEATURE_SIM_DIVIDER_HAS_OUTDIV4 (1) /* @brief Clock 4 output divider width (width of register bit field CLKDIV1[OUTDIV4]). */ #define FSL_FEATURE_SIM_DIVIDER_OUTDIV4_WIDTH (4) /* @brief Has USB clock divider (register bit field CLKDIV2[USBDIV] and CLKDIV2[USBFRAC]). */ #define FSL_FEATURE_SIM_DIVIDER_HAS_USBDIV (1) /* @brief Has USB FS clock divider (register bit field CLKDIV2[USBFSDIV] and CLKDIV2[USBFSFRAC]). */ #define FSL_FEATURE_SIM_DIVIDER_HAS_USBFSDIV (0) /* @brief Has USB HS clock divider (register bit field CLKDIV2[USBHSDIV] and CLKDIV2[USBHSFRAC]). */ #define FSL_FEATURE_SIM_DIVIDER_HAS_USBHSDIV (0) /* @brief Has PLL/FLL clock divider (register bit field CLKDIV3[PLLFLLDIV] and CLKDIV3[PLLFLLFRAC]). */ #define FSL_FEATURE_SIM_DIVIDER_HAS_PLLFLLDIV (0) /* @brief Has LCDC clock divider (register bit field CLKDIV3[LCDCDIV] and CLKDIV3[LCDCFRAC]). */ #define FSL_FEATURE_SIM_DIVIDER_HAS_LCDCDIV (0) /* @brief Has trace clock divider (register bit field CLKDIV4[TRACEDIV] and CLKDIV4[TRACEFRAC]). */ #define FSL_FEATURE_SIM_DIVIDER_HAS_TRACEDIV (0) /* @brief Has NFC clock divider (register bit field CLKDIV4[NFCDIV] and CLKDIV4[NFCFRAC]). */ #define FSL_FEATURE_SIM_DIVIDER_HAS_NFCDIV (0) /* @brief Has Kinetis family ID (register bit field SDID[FAMILYID]). */ #define FSL_FEATURE_SIM_SDID_HAS_FAMILYID (1) /* @brief Has Kinetis family ID (register bit field SDID[FAMID]). */ #define FSL_FEATURE_SIM_SDID_HAS_FAMID (1) /* @brief Has Kinetis sub-family ID (register bit field SDID[SUBFAMID]). */ #define FSL_FEATURE_SIM_SDID_HAS_SUBFAMID (1) /* @brief Has Kinetis series ID (register bit field SDID[SERIESID]). */ #define FSL_FEATURE_SIM_SDID_HAS_SERIESID (1) /* @brief Has device die ID (register bit field SDID[DIEID]). */ #define FSL_FEATURE_SIM_SDID_HAS_DIEID (1) /* @brief Has system SRAM size specifier (register bit field SDID[SRAMSIZE]). */ #define FSL_FEATURE_SIM_SDID_HAS_SRAMSIZE (0) /* @brief Has flash mode (register bit FCFG1[FLASHDOZE]). */ #define FSL_FEATURE_SIM_FCFG_HAS_FLASHDOZE (1) /* @brief Has flash disable (register bit FCFG1[FLASHDIS]). */ #define FSL_FEATURE_SIM_FCFG_HAS_FLASHDIS (1) /* @brief Has FTFE disable (register bit FCFG1[FTFDIS]). */ #define FSL_FEATURE_SIM_FCFG_HAS_FTFDIS (0) /* @brief Has FlexNVM size specifier (register bit field FCFG1[NVMSIZE]). */ #define FSL_FEATURE_SIM_FCFG_HAS_NVMSIZE (1) /* @brief Has EEPROM size specifier (register bit field FCFG1[EESIZE]). */ #define FSL_FEATURE_SIM_FCFG_HAS_EESIZE (1) /* @brief Has FlexNVM partition (register bit field FCFG1[DEPART]). */ #define FSL_FEATURE_SIM_FCFG_HAS_DEPART (1) /* @brief Maximum flash address block 0 address specifier (register bit field FCFG2[MAXADDR0]). */ #define FSL_FEATURE_SIM_FCFG_HAS_MAXADDR0 (1) /* @brief Maximum flash address block 1 address specifier (register bit field FCFG2[MAXADDR1]). */ #define FSL_FEATURE_SIM_FCFG_HAS_MAXADDR1 (1) /* @brief Maximum flash address block 0 or 1 address specifier (register bit field FCFG2[MAXADDR01]). */ #define FSL_FEATURE_SIM_FCFG_HAS_MAXADDR01 (0) /* @brief Maximum flash address block 2 or 3 address specifier (register bit field FCFG2[MAXADDR23]). */ #define FSL_FEATURE_SIM_FCFG_HAS_MAXADDR23 (0) /* @brief Has program flash availability specifier (register bit FCFG2[PFLSH]). */ #define FSL_FEATURE_SIM_FCFG_HAS_PFLSH (1) /* @brief Has program flash swapping (register bit FCFG2[SWAPPFLSH]). */ #define FSL_FEATURE_SIM_FCFG_HAS_PFLSH_SWAP (0) /* @brief Has miscellanious control register (register MCR). */ #define FSL_FEATURE_SIM_HAS_MISC_CONTROLS (0) /* @brief Has COP watchdog (registers COPC and SRVCOP). */ #define FSL_FEATURE_SIM_HAS_COP_WATCHDOG (0) /* @brief Has COP watchdog stop (register bits COPC[COPSTPEN], COPC[COPDBGEN] and COPC[COPCLKSEL]). */ #define FSL_FEATURE_SIM_HAS_COP_STOP (0) #elif defined(CPU_MK24FN256VDC12) /* @brief Has USB FS divider. */ #define FSL_FEATURE_SIM_USBFS_USE_SPECIAL_DIVIDER (0) /* @brief Is PLL clock divided by 2 before MCG PLL/FLL clock selection. */ #define FSL_FEATURE_SIM_PLLCLK_USE_SPECIAL_DIVIDER (0) /* @brief Has RAM size specification (register bit field SOPT1[RAMSIZE]). */ #define FSL_FEATURE_SIM_OPT_HAS_RAMSIZE (1) /* @brief Has 32k oscillator clock output (register bit SOPT1[OSC32KOUT]). */ #define FSL_FEATURE_SIM_OPT_HAS_OSC32K_OUT (0) /* @brief Has 32k oscillator clock selection (register bit field SOPT1[OSC32KSEL]). */ #define FSL_FEATURE_SIM_OPT_HAS_OSC32K_SELECTION (1) /* @brief 32k oscillator clock selection width (width of register bit field SOPT1[OSC32KSEL]). */ #define FSL_FEATURE_SIM_OPT_OSC32K_SELECTION_WIDTH (2) /* @brief Has RTC clock output selection (register bit SOPT2[RTCCLKOUTSEL]). */ #define FSL_FEATURE_SIM_OPT_HAS_RTC_CLOCK_OUT_SELECTION (1) /* @brief Has USB voltage regulator (register bits SOPT1[USBVSTBY], SOPT1[USBSSTBY], SOPT1[USBREGEN], SOPT1CFG[URWE], SOPT1CFG[UVSWE], SOPT1CFG[USSWE]). */ #define FSL_FEATURE_SIM_OPT_HAS_USB_VOLTAGE_REGULATOR (1) /* @brief USB has integrated PHY (register bits USBPHYCTL[USBVREGSEL], USBPHYCTL[USBVREGPD], USBPHYCTL[USB3VOUTTRG], USBPHYCTL[USBDISILIM], SOPT2[USBSLSRC], SOPT2[USBREGEN]). */ #define FSL_FEATURE_SIM_OPT_HAS_USB_PHY (0) /* @brief Has PTD7 pad drive strength control (register bit SOPT2[PTD7PAD]). */ #define FSL_FEATURE_SIM_OPT_HAS_PTD7PAD (0) /* @brief Has FlexBus security level selection (register bit SOPT2[FBSL]). */ #define FSL_FEATURE_SIM_OPT_HAS_FBSL (0) /* @brief Has number of FlexBus hold cycle before FlexBus can release bus (register bit SOPT6[PCR]). */ #define FSL_FEATURE_SIM_OPT_HAS_PCR (0) /* @brief Has number of NFC hold cycle in case of FlexBus request (register bit SOPT6[MCC]). */ #define FSL_FEATURE_SIM_OPT_HAS_MCC (0) /* @brief Has UART open drain enable (register bits UARTnODE, where n is a number, in register SOPT5). */ #define FSL_FEATURE_SIM_OPT_HAS_ODE (0) /* @brief Number of UART modules (number of register bits UARTn, where n is a number, in register SCGC4). */ #define FSL_FEATURE_SIM_OPT_UART_COUNT (4) /* @brief Has LPUART0 open drain enable (register bit SOPT5[LPUART0ODE]). */ #define FSL_FEATURE_SIM_OPT_HAS_LPUART0_ODE (0) /* @brief Has LPUART1 open drain enable (register bit SOPT5[LPUART1ODE]). */ #define FSL_FEATURE_SIM_OPT_HAS_LPUART1_ODE (0) /* @brief Has CMT/UART pad drive strength control (register bit SOPT2[CMTUARTPAD]). */ #define FSL_FEATURE_SIM_OPT_HAS_CMTUARTPAD (0) /* @brief Has LPUART0 transmit data source selection (register bit SOPT5[LPUART0TXSRC]). */ #define FSL_FEATURE_SIM_OPT_HAS_LPUART0_TX_SRC (0) /* @brief Has LPUART0 receive data source selection (register bit SOPT5[LPUART0RXSRC]). */ #define FSL_FEATURE_SIM_OPT_HAS_LPUART0_RX_SRC (0) /* @brief Has LPUART1 transmit data source selection (register bit SOPT5[LPUART1TXSRC]). */ #define FSL_FEATURE_SIM_OPT_HAS_LPUART1_TX_SRC (0) /* @brief Has LPUART1 receive data source selection (register bit SOPT5[LPUART1RXSRC]). */ #define FSL_FEATURE_SIM_OPT_HAS_LPUART1_RX_SRC (0) /* @brief Has UART0 transmit data source selection (register bit SOPT5[UART0TXSRC]). */ #define FSL_FEATURE_SIM_OPT_HAS_UART0_TX_SRC (1) /* @brief UART0 transmit data source selection width (width of register bit SOPT5[UART0TXSRC]). */ #define FSL_FEATURE_SIM_OPT_UART0_TX_SRC_WIDTH (2) /* @brief Has UART0 receive data source selection (register bit SOPT5[UART0RXSRC]). */ #define FSL_FEATURE_SIM_OPT_HAS_UART0_RX_SRC (1) /* @brief UART0 receive data source selection width (width of register bit SOPT5[UART0RXSRC]). */ #define FSL_FEATURE_SIM_OPT_UART0_RX_SRC_WIDTH (2) /* @brief Has UART1 transmit data source selection (register bit SOPT5[UART1TXSRC]). */ #define FSL_FEATURE_SIM_OPT_HAS_UART1_TX_SRC (1) /* @brief Has UART1 receive data source selection (register bit SOPT5[UART1RXSRC]). */ #define FSL_FEATURE_SIM_OPT_HAS_UART1_RX_SRC (1) /* @brief UART1 receive data source selection width (width of register bit SOPT5[UART1RXSRC]). */ #define FSL_FEATURE_SIM_OPT_UART1_RX_SRC_WIDTH (2) /* @brief Has FTM module(s) configuration. */ #define FSL_FEATURE_SIM_OPT_HAS_FTM (1) /* @brief Number of FTM modules. */ #define FSL_FEATURE_SIM_OPT_FTM_COUNT (4) /* @brief Number of FTM triggers with selectable source. */ #define FSL_FEATURE_SIM_OPT_FTM_TRIGGER_COUNT (2) /* @brief Has FTM0 triggers source selection (register bits SOPT4[FTM0TRGnSRC], where n is a number). */ #define FSL_FEATURE_SIM_OPT_HAS_FTM0_TRIGGER (1) /* @brief Has FTM3 triggers source selection (register bits SOPT4[FTM3TRGnSRC], where n is a number). */ #define FSL_FEATURE_SIM_OPT_HAS_FTM3_TRIGGER (1) /* @brief Has FTM1 channel 0 input capture source selection (register bit SOPT4[FTM1CH0SRC]). */ #define FSL_FEATURE_SIM_OPT_HAS_FTM1_CHANNELS (1) /* @brief Has FTM2 channel 0 input capture source selection (register bit SOPT4[FTM2CH0SRC]). */ #define FSL_FEATURE_SIM_OPT_HAS_FTM2_CHANNELS (1) /* @brief Has FTM3 channel 0 input capture source selection (register bit SOPT4[FTM3CH0SRC]). */ #define FSL_FEATURE_SIM_OPT_HAS_FTM3_CHANNELS (0) /* @brief Has FTM2 channel 1 input capture source selection (register bit SOPT4[FTM2CH1SRC]). */ #define FSL_FEATURE_SIM_OPT_HAS_FTM2_CHANNEL1 (0) /* @brief Number of configurable FTM0 fault detection input (number of register bits SOPT4[FTM0FLTn], where n is a number starting from zero). */ #define FSL_FEATURE_SIM_OPT_FTM0_FAULT_COUNT (2) /* @brief Number of configurable FTM1 fault detection input (number of register bits SOPT4[FTM1FLTn], where n is a number starting from zero). */ #define FSL_FEATURE_SIM_OPT_FTM1_FAULT_COUNT (1) /* @brief Number of configurable FTM2 fault detection input (number of register bits SOPT4[FTM2FLTn], where n is a number starting from zero). */ #define FSL_FEATURE_SIM_OPT_FTM2_FAULT_COUNT (1) /* @brief Number of configurable FTM3 fault detection input (number of register bits SOPT4[FTM3FLTn], where n is a number starting from zero). */ #define FSL_FEATURE_SIM_OPT_FTM3_FAULT_COUNT (1) /* @brief Has FTM hardware trigger 0 software synchronization (register bit SOPT8[FTMnSYNCBIT], where n is a module instance index). */ #define FSL_FEATURE_SIM_OPT_HAS_FTM_TRIGGER_SYNC (0) /* @brief Has FTM channels output source selection (register bit SOPT8[FTMxOCHnSRC], where x is a module instance index and n is a channel index). */ #define FSL_FEATURE_SIM_OPT_HAS_FTM_CHANNELS_OUTPUT_SRC (0) /* @brief Has TPM module(s) configuration. */ #define FSL_FEATURE_SIM_OPT_HAS_TPM (0) /* @brief The highest TPM module index. */ #define FSL_FEATURE_SIM_OPT_MAX_TPM_INDEX (0) /* @brief Has TPM module with index 0. */ #define FSL_FEATURE_SIM_OPT_HAS_TPM0 (0) /* @brief Is TPM channels configuration in the SOPT4 (not SOPT9) register (register bits TPMnCH0SRC, TPMnCLKSEL, where n is a module instance index). */ #define FSL_FEATURE_SIM_OPT_HAS_TPM_CHANNELS_CONFIG_IN_SOPT4_REG (0) /* @brief Has TPM1 channel 0 input capture source selection (register bit field SOPT4[TPM1CH0SRC] or SOPT9[TPM1CH0SRC]). */ #define FSL_FEATURE_SIM_OPT_HAS_TPM1_CH0_SRC_SELECTION (0) /* @brief TPM1 channel 0 input capture source selection width (width of register bit field SOPT4[TPM1CH0SRC] or SOPT9[TPM1CH0SRC]). */ #define FSL_FEATURE_SIM_OPT_TPM1_CH0_SRC_SELECTION_WIDTH (0) /* @brief Has TPM2 channel 0 input capture source selection (register bit field SOPT4[TPM2CH0SRC]). */ #define FSL_FEATURE_SIM_OPT_HAS_TPM2_CH0_SRC_SELECTION (0) /* @brief Has TPM2 clock selection (register bit field SOPT4[TPM2CLKSEL]). */ #define FSL_FEATURE_SIM_OPT_HAS_TPM2_CLK_SEL (0) /* @brief Has PLL/FLL clock selection (register bit field SOPT2[PLLFLLSEL]). */ #define FSL_FEATURE_SIM_OPT_HAS_PLL_FLL_SELECTION (1) /* @brief PLL/FLL clock selection width (width of register bit field SOPT2[PLLFLLSEL]). */ #define FSL_FEATURE_SIM_OPT_PLL_FLL_SELECTION_WIDTH (1) /* @brief Has NFC clock source selection (register bit SOPT2[NFCSRC]). */ #define FSL_FEATURE_SIM_OPT_HAS_NFCSRC (0) /* @brief Has eSDHC clock source selection (register bit SOPT2[ESDHCSRC]). */ #define FSL_FEATURE_SIM_OPT_HAS_ESDHCSRC (0) /* @brief Has SDHC clock source selection (register bit SOPT2[SDHCSRC]). */ #define FSL_FEATURE_SIM_OPT_HAS_SDHCSRC (0) /* @brief Has LCDC clock source selection (register bits SOPT2[LCDCSRC], SOPT2[LCDC_CLKSEL]). */ #define FSL_FEATURE_SIM_OPT_HAS_LCDCSRC (0) /* @brief Has ENET timestamp clock source selection (register bit SOPT2[TIMESRC]). */ #define FSL_FEATURE_SIM_OPT_HAS_TIMESRC (0) /* @brief Has ENET RMII clock source selection (register bit SOPT2[RMIISRC]). */ #define FSL_FEATURE_SIM_OPT_HAS_RMIISRC (0) /* @brief Has USB clock source selection (register bit SOPT2[USBSRC]). */ #define FSL_FEATURE_SIM_OPT_HAS_USBSRC (1) /* @brief Has USB FS clock source selection (register bit SOPT2[USBFSRC]). */ #define FSL_FEATURE_SIM_OPT_HAS_USBFSRC (0) /* @brief Has USB HS clock source selection (register bit SOPT2[USBHSRC]). */ #define FSL_FEATURE_SIM_OPT_HAS_USBHSRC (0) /* @brief Has LPUART clock source selection (register bit SOPT2[LPUARTSRC]). */ #define FSL_FEATURE_SIM_OPT_HAS_LPUARTSRC (0) /* @brief Has LPUART0 clock source selection (register bit SOPT2[LPUART0SRC]). */ #define FSL_FEATURE_SIM_OPT_HAS_LPUART0SRC (0) /* @brief Has LPUART1 clock source selection (register bit SOPT2[LPUART1SRC]). */ #define FSL_FEATURE_SIM_OPT_HAS_LPUART1SRC (0) /* @brief Has FLEXIOSRC clock source selection (register bit SOPT2[FLEXIOSRC]). */ #define FSL_FEATURE_SIM_OPT_HAS_FLEXIOSRC (0) /* @brief Has UART0 clock source selection (register bit SOPT2[UART0SRC]). */ #define FSL_FEATURE_SIM_OPT_HAS_UART0SRC (0) /* @brief Has TPM clock source selection (register bit SOPT2[TPMSRC]). */ #define FSL_FEATURE_SIM_OPT_HAS_TPMSRC (0) /* @brief Has debug trace clock selection (register bit SOPT2[TRACECLKSEL]). */ #define FSL_FEATURE_SIM_OPT_HAS_TRACE_CLKSEL (1) /* @brief Number of ADC modules (register bits SOPT7[ADCnTRGSEL], SOPT7[ADCnPRETRGSEL], SOPT7[ADCnALTTRGSEL], where n is a module instance index). */ #define FSL_FEATURE_SIM_OPT_ADC_COUNT (2) /* @brief Has clock 2 output divider (register bit field CLKDIV1[OUTDIV2]). */ #define FSL_FEATURE_SIM_DIVIDER_HAS_OUTDIV2 (1) /* @brief Has clock 3 output divider (register bit field CLKDIV1[OUTDIV3]). */ #define FSL_FEATURE_SIM_DIVIDER_HAS_OUTDIV3 (0) /* @brief Has clock 4 output divider (register bit field CLKDIV1[OUTDIV4]). */ #define FSL_FEATURE_SIM_DIVIDER_HAS_OUTDIV4 (1) /* @brief Clock 4 output divider width (width of register bit field CLKDIV1[OUTDIV4]). */ #define FSL_FEATURE_SIM_DIVIDER_OUTDIV4_WIDTH (4) /* @brief Has USB clock divider (register bit field CLKDIV2[USBDIV] and CLKDIV2[USBFRAC]). */ #define FSL_FEATURE_SIM_DIVIDER_HAS_USBDIV (1) /* @brief Has USB FS clock divider (register bit field CLKDIV2[USBFSDIV] and CLKDIV2[USBFSFRAC]). */ #define FSL_FEATURE_SIM_DIVIDER_HAS_USBFSDIV (0) /* @brief Has USB HS clock divider (register bit field CLKDIV2[USBHSDIV] and CLKDIV2[USBHSFRAC]). */ #define FSL_FEATURE_SIM_DIVIDER_HAS_USBHSDIV (0) /* @brief Has PLL/FLL clock divider (register bit field CLKDIV3[PLLFLLDIV] and CLKDIV3[PLLFLLFRAC]). */ #define FSL_FEATURE_SIM_DIVIDER_HAS_PLLFLLDIV (0) /* @brief Has LCDC clock divider (register bit field CLKDIV3[LCDCDIV] and CLKDIV3[LCDCFRAC]). */ #define FSL_FEATURE_SIM_DIVIDER_HAS_LCDCDIV (0) /* @brief Has trace clock divider (register bit field CLKDIV4[TRACEDIV] and CLKDIV4[TRACEFRAC]). */ #define FSL_FEATURE_SIM_DIVIDER_HAS_TRACEDIV (0) /* @brief Has NFC clock divider (register bit field CLKDIV4[NFCDIV] and CLKDIV4[NFCFRAC]). */ #define FSL_FEATURE_SIM_DIVIDER_HAS_NFCDIV (0) /* @brief Has Kinetis family ID (register bit field SDID[FAMILYID]). */ #define FSL_FEATURE_SIM_SDID_HAS_FAMILYID (1) /* @brief Has Kinetis family ID (register bit field SDID[FAMID]). */ #define FSL_FEATURE_SIM_SDID_HAS_FAMID (1) /* @brief Has Kinetis sub-family ID (register bit field SDID[SUBFAMID]). */ #define FSL_FEATURE_SIM_SDID_HAS_SUBFAMID (1) /* @brief Has Kinetis series ID (register bit field SDID[SERIESID]). */ #define FSL_FEATURE_SIM_SDID_HAS_SERIESID (1) /* @brief Has device die ID (register bit field SDID[DIEID]). */ #define FSL_FEATURE_SIM_SDID_HAS_DIEID (1) /* @brief Has system SRAM size specifier (register bit field SDID[SRAMSIZE]). */ #define FSL_FEATURE_SIM_SDID_HAS_SRAMSIZE (0) /* @brief Has flash mode (register bit FCFG1[FLASHDOZE]). */ #define FSL_FEATURE_SIM_FCFG_HAS_FLASHDOZE (1) /* @brief Has flash disable (register bit FCFG1[FLASHDIS]). */ #define FSL_FEATURE_SIM_FCFG_HAS_FLASHDIS (1) /* @brief Has FTFE disable (register bit FCFG1[FTFDIS]). */ #define FSL_FEATURE_SIM_FCFG_HAS_FTFDIS (0) /* @brief Has FlexNVM size specifier (register bit field FCFG1[NVMSIZE]). */ #define FSL_FEATURE_SIM_FCFG_HAS_NVMSIZE (0) /* @brief Has EEPROM size specifier (register bit field FCFG1[EESIZE]). */ #define FSL_FEATURE_SIM_FCFG_HAS_EESIZE (0) /* @brief Has FlexNVM partition (register bit field FCFG1[DEPART]). */ #define FSL_FEATURE_SIM_FCFG_HAS_DEPART (0) /* @brief Maximum flash address block 0 address specifier (register bit field FCFG2[MAXADDR0]). */ #define FSL_FEATURE_SIM_FCFG_HAS_MAXADDR0 (1) /* @brief Maximum flash address block 1 address specifier (register bit field FCFG2[MAXADDR1]). */ #define FSL_FEATURE_SIM_FCFG_HAS_MAXADDR1 (1) /* @brief Maximum flash address block 0 or 1 address specifier (register bit field FCFG2[MAXADDR01]). */ #define FSL_FEATURE_SIM_FCFG_HAS_MAXADDR01 (0) /* @brief Maximum flash address block 2 or 3 address specifier (register bit field FCFG2[MAXADDR23]). */ #define FSL_FEATURE_SIM_FCFG_HAS_MAXADDR23 (0) /* @brief Has program flash availability specifier (register bit FCFG2[PFLSH]). */ #define FSL_FEATURE_SIM_FCFG_HAS_PFLSH (0) /* @brief Has program flash swapping (register bit FCFG2[SWAPPFLSH]). */ #define FSL_FEATURE_SIM_FCFG_HAS_PFLSH_SWAP (0) /* @brief Has miscellanious control register (register MCR). */ #define FSL_FEATURE_SIM_HAS_MISC_CONTROLS (0) /* @brief Has COP watchdog (registers COPC and SRVCOP). */ #define FSL_FEATURE_SIM_HAS_COP_WATCHDOG (0) /* @brief Has COP watchdog stop (register bits COPC[COPSTPEN], COPC[COPDBGEN] and COPC[COPCLKSEL]). */ #define FSL_FEATURE_SIM_HAS_COP_STOP (0) #elif defined(CPU_MK63FN1M0VLQ12) || defined(CPU_MK63FN1M0VMD12) || defined(CPU_MK64FX512VDC12) || defined(CPU_MK64FN1M0VDC12) || \ defined(CPU_MK64FX512VLL12) || defined(CPU_MK64FN1M0VLL12) || defined(CPU_MK64FX512VLQ12) || defined(CPU_MK64FN1M0VLQ12) || \ defined(CPU_MK64FX512VMD12) || defined(CPU_MK64FN1M0VMD12) /* @brief Has USB FS divider. */ #define FSL_FEATURE_SIM_USBFS_USE_SPECIAL_DIVIDER (0) /* @brief Is PLL clock divided by 2 before MCG PLL/FLL clock selection. */ #define FSL_FEATURE_SIM_PLLCLK_USE_SPECIAL_DIVIDER (0) /* @brief Has RAM size specification (register bit field SOPT1[RAMSIZE]). */ #define FSL_FEATURE_SIM_OPT_HAS_RAMSIZE (1) /* @brief Has 32k oscillator clock output (register bit SOPT1[OSC32KOUT]). */ #define FSL_FEATURE_SIM_OPT_HAS_OSC32K_OUT (0) /* @brief Has 32k oscillator clock selection (register bit field SOPT1[OSC32KSEL]). */ #define FSL_FEATURE_SIM_OPT_HAS_OSC32K_SELECTION (1) /* @brief 32k oscillator clock selection width (width of register bit field SOPT1[OSC32KSEL]). */ #define FSL_FEATURE_SIM_OPT_OSC32K_SELECTION_WIDTH (2) /* @brief Has RTC clock output selection (register bit SOPT2[RTCCLKOUTSEL]). */ #define FSL_FEATURE_SIM_OPT_HAS_RTC_CLOCK_OUT_SELECTION (1) /* @brief Has USB voltage regulator (register bits SOPT1[USBVSTBY], SOPT1[USBSSTBY], SOPT1[USBREGEN], SOPT1CFG[URWE], SOPT1CFG[UVSWE], SOPT1CFG[USSWE]). */ #define FSL_FEATURE_SIM_OPT_HAS_USB_VOLTAGE_REGULATOR (1) /* @brief USB has integrated PHY (register bits USBPHYCTL[USBVREGSEL], USBPHYCTL[USBVREGPD], USBPHYCTL[USB3VOUTTRG], USBPHYCTL[USBDISILIM], SOPT2[USBSLSRC], SOPT2[USBREGEN]). */ #define FSL_FEATURE_SIM_OPT_HAS_USB_PHY (0) /* @brief Has PTD7 pad drive strength control (register bit SOPT2[PTD7PAD]). */ #define FSL_FEATURE_SIM_OPT_HAS_PTD7PAD (1) /* @brief Has FlexBus security level selection (register bit SOPT2[FBSL]). */ #define FSL_FEATURE_SIM_OPT_HAS_FBSL (1) /* @brief Has number of FlexBus hold cycle before FlexBus can release bus (register bit SOPT6[PCR]). */ #define FSL_FEATURE_SIM_OPT_HAS_PCR (0) /* @brief Has number of NFC hold cycle in case of FlexBus request (register bit SOPT6[MCC]). */ #define FSL_FEATURE_SIM_OPT_HAS_MCC (0) /* @brief Has UART open drain enable (register bits UARTnODE, where n is a number, in register SOPT5). */ #define FSL_FEATURE_SIM_OPT_HAS_ODE (0) /* @brief Number of UART modules (number of register bits UARTn, where n is a number, in register SCGC4). */ #define FSL_FEATURE_SIM_OPT_UART_COUNT (4) /* @brief Has LPUART0 open drain enable (register bit SOPT5[LPUART0ODE]). */ #define FSL_FEATURE_SIM_OPT_HAS_LPUART0_ODE (0) /* @brief Has LPUART1 open drain enable (register bit SOPT5[LPUART1ODE]). */ #define FSL_FEATURE_SIM_OPT_HAS_LPUART1_ODE (0) /* @brief Has CMT/UART pad drive strength control (register bit SOPT2[CMTUARTPAD]). */ #define FSL_FEATURE_SIM_OPT_HAS_CMTUARTPAD (0) /* @brief Has LPUART0 transmit data source selection (register bit SOPT5[LPUART0TXSRC]). */ #define FSL_FEATURE_SIM_OPT_HAS_LPUART0_TX_SRC (0) /* @brief Has LPUART0 receive data source selection (register bit SOPT5[LPUART0RXSRC]). */ #define FSL_FEATURE_SIM_OPT_HAS_LPUART0_RX_SRC (0) /* @brief Has LPUART1 transmit data source selection (register bit SOPT5[LPUART1TXSRC]). */ #define FSL_FEATURE_SIM_OPT_HAS_LPUART1_TX_SRC (0) /* @brief Has LPUART1 receive data source selection (register bit SOPT5[LPUART1RXSRC]). */ #define FSL_FEATURE_SIM_OPT_HAS_LPUART1_RX_SRC (0) /* @brief Has UART0 transmit data source selection (register bit SOPT5[UART0TXSRC]). */ #define FSL_FEATURE_SIM_OPT_HAS_UART0_TX_SRC (1) /* @brief UART0 transmit data source selection width (width of register bit SOPT5[UART0TXSRC]). */ #define FSL_FEATURE_SIM_OPT_UART0_TX_SRC_WIDTH (2) /* @brief Has UART0 receive data source selection (register bit SOPT5[UART0RXSRC]). */ #define FSL_FEATURE_SIM_OPT_HAS_UART0_RX_SRC (1) /* @brief UART0 receive data source selection width (width of register bit SOPT5[UART0RXSRC]). */ #define FSL_FEATURE_SIM_OPT_UART0_RX_SRC_WIDTH (2) /* @brief Has UART1 transmit data source selection (register bit SOPT5[UART1TXSRC]). */ #define FSL_FEATURE_SIM_OPT_HAS_UART1_TX_SRC (1) /* @brief Has UART1 receive data source selection (register bit SOPT5[UART1RXSRC]). */ #define FSL_FEATURE_SIM_OPT_HAS_UART1_RX_SRC (1) /* @brief UART1 receive data source selection width (width of register bit SOPT5[UART1RXSRC]). */ #define FSL_FEATURE_SIM_OPT_UART1_RX_SRC_WIDTH (2) /* @brief Has FTM module(s) configuration. */ #define FSL_FEATURE_SIM_OPT_HAS_FTM (1) /* @brief Number of FTM modules. */ #define FSL_FEATURE_SIM_OPT_FTM_COUNT (4) /* @brief Number of FTM triggers with selectable source. */ #define FSL_FEATURE_SIM_OPT_FTM_TRIGGER_COUNT (2) /* @brief Has FTM0 triggers source selection (register bits SOPT4[FTM0TRGnSRC], where n is a number). */ #define FSL_FEATURE_SIM_OPT_HAS_FTM0_TRIGGER (1) /* @brief Has FTM3 triggers source selection (register bits SOPT4[FTM3TRGnSRC], where n is a number). */ #define FSL_FEATURE_SIM_OPT_HAS_FTM3_TRIGGER (1) /* @brief Has FTM1 channel 0 input capture source selection (register bit SOPT4[FTM1CH0SRC]). */ #define FSL_FEATURE_SIM_OPT_HAS_FTM1_CHANNELS (1) /* @brief Has FTM2 channel 0 input capture source selection (register bit SOPT4[FTM2CH0SRC]). */ #define FSL_FEATURE_SIM_OPT_HAS_FTM2_CHANNELS (1) /* @brief Has FTM3 channel 0 input capture source selection (register bit SOPT4[FTM3CH0SRC]). */ #define FSL_FEATURE_SIM_OPT_HAS_FTM3_CHANNELS (0) /* @brief Has FTM2 channel 1 input capture source selection (register bit SOPT4[FTM2CH1SRC]). */ #define FSL_FEATURE_SIM_OPT_HAS_FTM2_CHANNEL1 (0) /* @brief Number of configurable FTM0 fault detection input (number of register bits SOPT4[FTM0FLTn], where n is a number starting from zero). */ #define FSL_FEATURE_SIM_OPT_FTM0_FAULT_COUNT (3) /* @brief Number of configurable FTM1 fault detection input (number of register bits SOPT4[FTM1FLTn], where n is a number starting from zero). */ #define FSL_FEATURE_SIM_OPT_FTM1_FAULT_COUNT (1) /* @brief Number of configurable FTM2 fault detection input (number of register bits SOPT4[FTM2FLTn], where n is a number starting from zero). */ #define FSL_FEATURE_SIM_OPT_FTM2_FAULT_COUNT (1) /* @brief Number of configurable FTM3 fault detection input (number of register bits SOPT4[FTM3FLTn], where n is a number starting from zero). */ #define FSL_FEATURE_SIM_OPT_FTM3_FAULT_COUNT (1) /* @brief Has FTM hardware trigger 0 software synchronization (register bit SOPT8[FTMnSYNCBIT], where n is a module instance index). */ #define FSL_FEATURE_SIM_OPT_HAS_FTM_TRIGGER_SYNC (0) /* @brief Has FTM channels output source selection (register bit SOPT8[FTMxOCHnSRC], where x is a module instance index and n is a channel index). */ #define FSL_FEATURE_SIM_OPT_HAS_FTM_CHANNELS_OUTPUT_SRC (0) /* @brief Has TPM module(s) configuration. */ #define FSL_FEATURE_SIM_OPT_HAS_TPM (0) /* @brief The highest TPM module index. */ #define FSL_FEATURE_SIM_OPT_MAX_TPM_INDEX (0) /* @brief Has TPM module with index 0. */ #define FSL_FEATURE_SIM_OPT_HAS_TPM0 (0) /* @brief Is TPM channels configuration in the SOPT4 (not SOPT9) register (register bits TPMnCH0SRC, TPMnCLKSEL, where n is a module instance index). */ #define FSL_FEATURE_SIM_OPT_HAS_TPM_CHANNELS_CONFIG_IN_SOPT4_REG (0) /* @brief Has TPM1 channel 0 input capture source selection (register bit field SOPT4[TPM1CH0SRC] or SOPT9[TPM1CH0SRC]). */ #define FSL_FEATURE_SIM_OPT_HAS_TPM1_CH0_SRC_SELECTION (0) /* @brief TPM1 channel 0 input capture source selection width (width of register bit field SOPT4[TPM1CH0SRC] or SOPT9[TPM1CH0SRC]). */ #define FSL_FEATURE_SIM_OPT_TPM1_CH0_SRC_SELECTION_WIDTH (0) /* @brief Has TPM2 channel 0 input capture source selection (register bit field SOPT4[TPM2CH0SRC]). */ #define FSL_FEATURE_SIM_OPT_HAS_TPM2_CH0_SRC_SELECTION (0) /* @brief Has TPM2 clock selection (register bit field SOPT4[TPM2CLKSEL]). */ #define FSL_FEATURE_SIM_OPT_HAS_TPM2_CLK_SEL (0) /* @brief Has PLL/FLL clock selection (register bit field SOPT2[PLLFLLSEL]). */ #define FSL_FEATURE_SIM_OPT_HAS_PLL_FLL_SELECTION (1) /* @brief PLL/FLL clock selection width (width of register bit field SOPT2[PLLFLLSEL]). */ #define FSL_FEATURE_SIM_OPT_PLL_FLL_SELECTION_WIDTH (1) /* @brief Has NFC clock source selection (register bit SOPT2[NFCSRC]). */ #define FSL_FEATURE_SIM_OPT_HAS_NFCSRC (0) /* @brief Has eSDHC clock source selection (register bit SOPT2[ESDHCSRC]). */ #define FSL_FEATURE_SIM_OPT_HAS_ESDHCSRC (0) /* @brief Has SDHC clock source selection (register bit SOPT2[SDHCSRC]). */ #define FSL_FEATURE_SIM_OPT_HAS_SDHCSRC (1) /* @brief Has LCDC clock source selection (register bits SOPT2[LCDCSRC], SOPT2[LCDC_CLKSEL]). */ #define FSL_FEATURE_SIM_OPT_HAS_LCDCSRC (0) /* @brief Has ENET timestamp clock source selection (register bit SOPT2[TIMESRC]). */ #define FSL_FEATURE_SIM_OPT_HAS_TIMESRC (1) /* @brief Has ENET RMII clock source selection (register bit SOPT2[RMIISRC]). */ #define FSL_FEATURE_SIM_OPT_HAS_RMIISRC (1) /* @brief Has USB clock source selection (register bit SOPT2[USBSRC]). */ #define FSL_FEATURE_SIM_OPT_HAS_USBSRC (1) /* @brief Has USB FS clock source selection (register bit SOPT2[USBFSRC]). */ #define FSL_FEATURE_SIM_OPT_HAS_USBFSRC (0) /* @brief Has USB HS clock source selection (register bit SOPT2[USBHSRC]). */ #define FSL_FEATURE_SIM_OPT_HAS_USBHSRC (0) /* @brief Has LPUART clock source selection (register bit SOPT2[LPUARTSRC]). */ #define FSL_FEATURE_SIM_OPT_HAS_LPUARTSRC (0) /* @brief Has LPUART0 clock source selection (register bit SOPT2[LPUART0SRC]). */ #define FSL_FEATURE_SIM_OPT_HAS_LPUART0SRC (0) /* @brief Has LPUART1 clock source selection (register bit SOPT2[LPUART1SRC]). */ #define FSL_FEATURE_SIM_OPT_HAS_LPUART1SRC (0) /* @brief Has FLEXIOSRC clock source selection (register bit SOPT2[FLEXIOSRC]). */ #define FSL_FEATURE_SIM_OPT_HAS_FLEXIOSRC (0) /* @brief Has UART0 clock source selection (register bit SOPT2[UART0SRC]). */ #define FSL_FEATURE_SIM_OPT_HAS_UART0SRC (0) /* @brief Has TPM clock source selection (register bit SOPT2[TPMSRC]). */ #define FSL_FEATURE_SIM_OPT_HAS_TPMSRC (0) /* @brief Has debug trace clock selection (register bit SOPT2[TRACECLKSEL]). */ #define FSL_FEATURE_SIM_OPT_HAS_TRACE_CLKSEL (1) /* @brief Number of ADC modules (register bits SOPT7[ADCnTRGSEL], SOPT7[ADCnPRETRGSEL], SOPT7[ADCnALTTRGSEL], where n is a module instance index). */ #define FSL_FEATURE_SIM_OPT_ADC_COUNT (2) /* @brief Has clock 2 output divider (register bit field CLKDIV1[OUTDIV2]). */ #define FSL_FEATURE_SIM_DIVIDER_HAS_OUTDIV2 (1) /* @brief Has clock 3 output divider (register bit field CLKDIV1[OUTDIV3]). */ #define FSL_FEATURE_SIM_DIVIDER_HAS_OUTDIV3 (1) /* @brief Has clock 4 output divider (register bit field CLKDIV1[OUTDIV4]). */ #define FSL_FEATURE_SIM_DIVIDER_HAS_OUTDIV4 (1) /* @brief Clock 4 output divider width (width of register bit field CLKDIV1[OUTDIV4]). */ #define FSL_FEATURE_SIM_DIVIDER_OUTDIV4_WIDTH (4) /* @brief Has USB clock divider (register bit field CLKDIV2[USBDIV] and CLKDIV2[USBFRAC]). */ #define FSL_FEATURE_SIM_DIVIDER_HAS_USBDIV (1) /* @brief Has USB FS clock divider (register bit field CLKDIV2[USBFSDIV] and CLKDIV2[USBFSFRAC]). */ #define FSL_FEATURE_SIM_DIVIDER_HAS_USBFSDIV (0) /* @brief Has USB HS clock divider (register bit field CLKDIV2[USBHSDIV] and CLKDIV2[USBHSFRAC]). */ #define FSL_FEATURE_SIM_DIVIDER_HAS_USBHSDIV (0) /* @brief Has PLL/FLL clock divider (register bit field CLKDIV3[PLLFLLDIV] and CLKDIV3[PLLFLLFRAC]). */ #define FSL_FEATURE_SIM_DIVIDER_HAS_PLLFLLDIV (0) /* @brief Has LCDC clock divider (register bit field CLKDIV3[LCDCDIV] and CLKDIV3[LCDCFRAC]). */ #define FSL_FEATURE_SIM_DIVIDER_HAS_LCDCDIV (0) /* @brief Has trace clock divider (register bit field CLKDIV4[TRACEDIV] and CLKDIV4[TRACEFRAC]). */ #define FSL_FEATURE_SIM_DIVIDER_HAS_TRACEDIV (0) /* @brief Has NFC clock divider (register bit field CLKDIV4[NFCDIV] and CLKDIV4[NFCFRAC]). */ #define FSL_FEATURE_SIM_DIVIDER_HAS_NFCDIV (0) /* @brief Has Kinetis family ID (register bit field SDID[FAMILYID]). */ #define FSL_FEATURE_SIM_SDID_HAS_FAMILYID (1) /* @brief Has Kinetis family ID (register bit field SDID[FAMID]). */ #define FSL_FEATURE_SIM_SDID_HAS_FAMID (1) /* @brief Has Kinetis sub-family ID (register bit field SDID[SUBFAMID]). */ #define FSL_FEATURE_SIM_SDID_HAS_SUBFAMID (1) /* @brief Has Kinetis series ID (register bit field SDID[SERIESID]). */ #define FSL_FEATURE_SIM_SDID_HAS_SERIESID (1) /* @brief Has device die ID (register bit field SDID[DIEID]). */ #define FSL_FEATURE_SIM_SDID_HAS_DIEID (1) /* @brief Has system SRAM size specifier (register bit field SDID[SRAMSIZE]). */ #define FSL_FEATURE_SIM_SDID_HAS_SRAMSIZE (0) /* @brief Has flash mode (register bit FCFG1[FLASHDOZE]). */ #define FSL_FEATURE_SIM_FCFG_HAS_FLASHDOZE (1) /* @brief Has flash disable (register bit FCFG1[FLASHDIS]). */ #define FSL_FEATURE_SIM_FCFG_HAS_FLASHDIS (1) /* @brief Has FTFE disable (register bit FCFG1[FTFDIS]). */ #define FSL_FEATURE_SIM_FCFG_HAS_FTFDIS (0) /* @brief Has FlexNVM size specifier (register bit field FCFG1[NVMSIZE]). */ #define FSL_FEATURE_SIM_FCFG_HAS_NVMSIZE (1) /* @brief Has EEPROM size specifier (register bit field FCFG1[EESIZE]). */ #define FSL_FEATURE_SIM_FCFG_HAS_EESIZE (1) /* @brief Has FlexNVM partition (register bit field FCFG1[DEPART]). */ #define FSL_FEATURE_SIM_FCFG_HAS_DEPART (1) /* @brief Maximum flash address block 0 address specifier (register bit field FCFG2[MAXADDR0]). */ #define FSL_FEATURE_SIM_FCFG_HAS_MAXADDR0 (1) /* @brief Maximum flash address block 1 address specifier (register bit field FCFG2[MAXADDR1]). */ #define FSL_FEATURE_SIM_FCFG_HAS_MAXADDR1 (1) /* @brief Maximum flash address block 0 or 1 address specifier (register bit field FCFG2[MAXADDR01]). */ #define FSL_FEATURE_SIM_FCFG_HAS_MAXADDR01 (0) /* @brief Maximum flash address block 2 or 3 address specifier (register bit field FCFG2[MAXADDR23]). */ #define FSL_FEATURE_SIM_FCFG_HAS_MAXADDR23 (0) /* @brief Has program flash availability specifier (register bit FCFG2[PFLSH]). */ #define FSL_FEATURE_SIM_FCFG_HAS_PFLSH (1) /* @brief Has program flash swapping (register bit FCFG2[SWAPPFLSH]). */ #define FSL_FEATURE_SIM_FCFG_HAS_PFLSH_SWAP (0) /* @brief Has miscellanious control register (register MCR). */ #define FSL_FEATURE_SIM_HAS_MISC_CONTROLS (0) /* @brief Has COP watchdog (registers COPC and SRVCOP). */ #define FSL_FEATURE_SIM_HAS_COP_WATCHDOG (0) /* @brief Has COP watchdog stop (register bits COPC[COPSTPEN], COPC[COPDBGEN] and COPC[COPCLKSEL]). */ #define FSL_FEATURE_SIM_HAS_COP_STOP (0) #elif defined(CPU_MK65FN2M0CAC18) || defined(CPU_MK65FX1M0CAC18) || defined(CPU_MK65FN2M0VMI18) || defined(CPU_MK65FX1M0VMI18) || \ defined(CPU_MK66FN2M0VLQ18) || defined(CPU_MK66FX1M0VLQ18) || defined(CPU_MK66FN2M0VMD18) || defined(CPU_MK66FX1M0VMD18) /* @brief Has USB FS divider. */ #define FSL_FEATURE_SIM_USBFS_USE_SPECIAL_DIVIDER (0) /* @brief Is PLL clock divided by 2 before MCG PLL/FLL clock selection. */ #define FSL_FEATURE_SIM_PLLCLK_USE_SPECIAL_DIVIDER (0) /* @brief Has RAM size specification (register bit field SOPT1[RAMSIZE]). */ #define FSL_FEATURE_SIM_OPT_HAS_RAMSIZE (1) /* @brief Has 32k oscillator clock output (register bit SOPT1[OSC32KOUT]). */ #define FSL_FEATURE_SIM_OPT_HAS_OSC32K_OUT (0) /* @brief Has 32k oscillator clock selection (register bit field SOPT1[OSC32KSEL]). */ #define FSL_FEATURE_SIM_OPT_HAS_OSC32K_SELECTION (1) /* @brief 32k oscillator clock selection width (width of register bit field SOPT1[OSC32KSEL]). */ #define FSL_FEATURE_SIM_OPT_OSC32K_SELECTION_WIDTH (2) /* @brief Has RTC clock output selection (register bit SOPT2[RTCCLKOUTSEL]). */ #define FSL_FEATURE_SIM_OPT_HAS_RTC_CLOCK_OUT_SELECTION (1) /* @brief Has USB voltage regulator (register bits SOPT1[USBVSTBY], SOPT1[USBSSTBY], SOPT1[USBREGEN], SOPT1CFG[URWE], SOPT1CFG[UVSWE], SOPT1CFG[USSWE]). */ #define FSL_FEATURE_SIM_OPT_HAS_USB_VOLTAGE_REGULATOR (1) /* @brief USB has integrated PHY (register bits USBPHYCTL[USBVREGSEL], USBPHYCTL[USBVREGPD], USBPHYCTL[USB3VOUTTRG], USBPHYCTL[USBDISILIM], SOPT2[USBSLSRC], SOPT2[USBREGEN]). */ #define FSL_FEATURE_SIM_OPT_HAS_USB_PHY (1) /* @brief Has PTD7 pad drive strength control (register bit SOPT2[PTD7PAD]). */ #define FSL_FEATURE_SIM_OPT_HAS_PTD7PAD (0) /* @brief Has FlexBus security level selection (register bit SOPT2[FBSL]). */ #define FSL_FEATURE_SIM_OPT_HAS_FBSL (1) /* @brief Has number of FlexBus hold cycle before FlexBus can release bus (register bit SOPT6[PCR]). */ #define FSL_FEATURE_SIM_OPT_HAS_PCR (0) /* @brief Has number of NFC hold cycle in case of FlexBus request (register bit SOPT6[MCC]). */ #define FSL_FEATURE_SIM_OPT_HAS_MCC (0) /* @brief Has UART open drain enable (register bits UARTnODE, where n is a number, in register SOPT5). */ #define FSL_FEATURE_SIM_OPT_HAS_ODE (0) /* @brief Number of UART modules (number of register bits UARTn, where n is a number, in register SCGC4). */ #define FSL_FEATURE_SIM_OPT_UART_COUNT (4) /* @brief Has LPUART0 open drain enable (register bit SOPT5[LPUART0ODE]). */ #define FSL_FEATURE_SIM_OPT_HAS_LPUART0_ODE (0) /* @brief Has LPUART1 open drain enable (register bit SOPT5[LPUART1ODE]). */ #define FSL_FEATURE_SIM_OPT_HAS_LPUART1_ODE (0) /* @brief Has CMT/UART pad drive strength control (register bit SOPT2[CMTUARTPAD]). */ #define FSL_FEATURE_SIM_OPT_HAS_CMTUARTPAD (0) /* @brief Has LPUART0 transmit data source selection (register bit SOPT5[LPUART0TXSRC]). */ #define FSL_FEATURE_SIM_OPT_HAS_LPUART0_TX_SRC (1) /* @brief Has LPUART0 receive data source selection (register bit SOPT5[LPUART0RXSRC]). */ #define FSL_FEATURE_SIM_OPT_HAS_LPUART0_RX_SRC (1) /* @brief Has LPUART1 transmit data source selection (register bit SOPT5[LPUART1TXSRC]). */ #define FSL_FEATURE_SIM_OPT_HAS_LPUART1_TX_SRC (0) /* @brief Has LPUART1 receive data source selection (register bit SOPT5[LPUART1RXSRC]). */ #define FSL_FEATURE_SIM_OPT_HAS_LPUART1_RX_SRC (0) /* @brief Has UART0 transmit data source selection (register bit SOPT5[UART0TXSRC]). */ #define FSL_FEATURE_SIM_OPT_HAS_UART0_TX_SRC (1) /* @brief UART0 transmit data source selection width (width of register bit SOPT5[UART0TXSRC]). */ #define FSL_FEATURE_SIM_OPT_UART0_TX_SRC_WIDTH (2) /* @brief Has UART0 receive data source selection (register bit SOPT5[UART0RXSRC]). */ #define FSL_FEATURE_SIM_OPT_HAS_UART0_RX_SRC (1) /* @brief UART0 receive data source selection width (width of register bit SOPT5[UART0RXSRC]). */ #define FSL_FEATURE_SIM_OPT_UART0_RX_SRC_WIDTH (2) /* @brief Has UART1 transmit data source selection (register bit SOPT5[UART1TXSRC]). */ #define FSL_FEATURE_SIM_OPT_HAS_UART1_TX_SRC (1) /* @brief Has UART1 receive data source selection (register bit SOPT5[UART1RXSRC]). */ #define FSL_FEATURE_SIM_OPT_HAS_UART1_RX_SRC (1) /* @brief UART1 receive data source selection width (width of register bit SOPT5[UART1RXSRC]). */ #define FSL_FEATURE_SIM_OPT_UART1_RX_SRC_WIDTH (2) /* @brief Has FTM module(s) configuration. */ #define FSL_FEATURE_SIM_OPT_HAS_FTM (1) /* @brief Number of FTM modules. */ #define FSL_FEATURE_SIM_OPT_FTM_COUNT (4) /* @brief Number of FTM triggers with selectable source. */ #define FSL_FEATURE_SIM_OPT_FTM_TRIGGER_COUNT (2) /* @brief Has FTM0 triggers source selection (register bits SOPT4[FTM0TRGnSRC], where n is a number). */ #define FSL_FEATURE_SIM_OPT_HAS_FTM0_TRIGGER (1) /* @brief Has FTM3 triggers source selection (register bits SOPT4[FTM3TRGnSRC], where n is a number). */ #define FSL_FEATURE_SIM_OPT_HAS_FTM3_TRIGGER (1) /* @brief Has FTM1 channel 0 input capture source selection (register bit SOPT4[FTM1CH0SRC]). */ #define FSL_FEATURE_SIM_OPT_HAS_FTM1_CHANNELS (1) /* @brief Has FTM2 channel 0 input capture source selection (register bit SOPT4[FTM2CH0SRC]). */ #define FSL_FEATURE_SIM_OPT_HAS_FTM2_CHANNELS (1) /* @brief Has FTM3 channel 0 input capture source selection (register bit SOPT4[FTM3CH0SRC]). */ #define FSL_FEATURE_SIM_OPT_HAS_FTM3_CHANNELS (0) /* @brief Has FTM2 channel 1 input capture source selection (register bit SOPT4[FTM2CH1SRC]). */ #define FSL_FEATURE_SIM_OPT_HAS_FTM2_CHANNEL1 (1) /* @brief Number of configurable FTM0 fault detection input (number of register bits SOPT4[FTM0FLTn], where n is a number starting from zero). */ #define FSL_FEATURE_SIM_OPT_FTM0_FAULT_COUNT (4) /* @brief Number of configurable FTM1 fault detection input (number of register bits SOPT4[FTM1FLTn], where n is a number starting from zero). */ #define FSL_FEATURE_SIM_OPT_FTM1_FAULT_COUNT (1) /* @brief Number of configurable FTM2 fault detection input (number of register bits SOPT4[FTM2FLTn], where n is a number starting from zero). */ #define FSL_FEATURE_SIM_OPT_FTM2_FAULT_COUNT (1) /* @brief Number of configurable FTM3 fault detection input (number of register bits SOPT4[FTM3FLTn], where n is a number starting from zero). */ #define FSL_FEATURE_SIM_OPT_FTM3_FAULT_COUNT (1) /* @brief Has FTM hardware trigger 0 software synchronization (register bit SOPT8[FTMnSYNCBIT], where n is a module instance index). */ #define FSL_FEATURE_SIM_OPT_HAS_FTM_TRIGGER_SYNC (1) /* @brief Has FTM channels output source selection (register bit SOPT8[FTMxOCHnSRC], where x is a module instance index and n is a channel index). */ #define FSL_FEATURE_SIM_OPT_HAS_FTM_CHANNELS_OUTPUT_SRC (1) /* @brief Has TPM module(s) configuration. */ #define FSL_FEATURE_SIM_OPT_HAS_TPM (1) /* @brief The highest TPM module index. */ #define FSL_FEATURE_SIM_OPT_MAX_TPM_INDEX (2) /* @brief Has TPM module with index 0. */ #define FSL_FEATURE_SIM_OPT_HAS_TPM0 (0) /* @brief Is TPM channels configuration in the SOPT4 (not SOPT9) register (register bits TPMnCH0SRC, TPMnCLKSEL, where n is a module instance index). */ #define FSL_FEATURE_SIM_OPT_HAS_TPM_CHANNELS_CONFIG_IN_SOPT4_REG (0) /* @brief Has TPM1 channel 0 input capture source selection (register bit field SOPT4[TPM1CH0SRC] or SOPT9[TPM1CH0SRC]). */ #define FSL_FEATURE_SIM_OPT_HAS_TPM1_CH0_SRC_SELECTION (1) /* @brief TPM1 channel 0 input capture source selection width (width of register bit field SOPT4[TPM1CH0SRC] or SOPT9[TPM1CH0SRC]). */ #define FSL_FEATURE_SIM_OPT_TPM1_CH0_SRC_SELECTION_WIDTH (1) /* @brief Has TPM2 channel 0 input capture source selection (register bit field SOPT4[TPM2CH0SRC]). */ #define FSL_FEATURE_SIM_OPT_HAS_TPM2_CH0_SRC_SELECTION (0) /* @brief Has TPM2 clock selection (register bit field SOPT4[TPM2CLKSEL]). */ #define FSL_FEATURE_SIM_OPT_HAS_TPM2_CLK_SEL (0) /* @brief Has PLL/FLL clock selection (register bit field SOPT2[PLLFLLSEL]). */ #define FSL_FEATURE_SIM_OPT_HAS_PLL_FLL_SELECTION (1) /* @brief PLL/FLL clock selection width (width of register bit field SOPT2[PLLFLLSEL]). */ #define FSL_FEATURE_SIM_OPT_PLL_FLL_SELECTION_WIDTH (1) /* @brief Has NFC clock source selection (register bit SOPT2[NFCSRC]). */ #define FSL_FEATURE_SIM_OPT_HAS_NFCSRC (0) /* @brief Has eSDHC clock source selection (register bit SOPT2[ESDHCSRC]). */ #define FSL_FEATURE_SIM_OPT_HAS_ESDHCSRC (0) /* @brief Has SDHC clock source selection (register bit SOPT2[SDHCSRC]). */ #define FSL_FEATURE_SIM_OPT_HAS_SDHCSRC (1) /* @brief Has LCDC clock source selection (register bits SOPT2[LCDCSRC], SOPT2[LCDC_CLKSEL]). */ #define FSL_FEATURE_SIM_OPT_HAS_LCDCSRC (0) /* @brief Has ENET timestamp clock source selection (register bit SOPT2[TIMESRC]). */ #define FSL_FEATURE_SIM_OPT_HAS_TIMESRC (1) /* @brief Has ENET RMII clock source selection (register bit SOPT2[RMIISRC]). */ #define FSL_FEATURE_SIM_OPT_HAS_RMIISRC (1) /* @brief Has USB clock source selection (register bit SOPT2[USBSRC]). */ #define FSL_FEATURE_SIM_OPT_HAS_USBSRC (1) /* @brief Has USB FS clock source selection (register bit SOPT2[USBFSRC]). */ #define FSL_FEATURE_SIM_OPT_HAS_USBFSRC (0) /* @brief Has USB HS clock source selection (register bit SOPT2[USBHSRC]). */ #define FSL_FEATURE_SIM_OPT_HAS_USBHSRC (0) /* @brief Has LPUART clock source selection (register bit SOPT2[LPUARTSRC]). */ #define FSL_FEATURE_SIM_OPT_HAS_LPUARTSRC (1) /* @brief Has LPUART0 clock source selection (register bit SOPT2[LPUART0SRC]). */ #define FSL_FEATURE_SIM_OPT_HAS_LPUART0SRC (0) /* @brief Has LPUART1 clock source selection (register bit SOPT2[LPUART1SRC]). */ #define FSL_FEATURE_SIM_OPT_HAS_LPUART1SRC (0) /* @brief Has FLEXIOSRC clock source selection (register bit SOPT2[FLEXIOSRC]). */ #define FSL_FEATURE_SIM_OPT_HAS_FLEXIOSRC (0) /* @brief Has UART0 clock source selection (register bit SOPT2[UART0SRC]). */ #define FSL_FEATURE_SIM_OPT_HAS_UART0SRC (0) /* @brief Has TPM clock source selection (register bit SOPT2[TPMSRC]). */ #define FSL_FEATURE_SIM_OPT_HAS_TPMSRC (1) /* @brief Has debug trace clock selection (register bit SOPT2[TRACECLKSEL]). */ #define FSL_FEATURE_SIM_OPT_HAS_TRACE_CLKSEL (1) /* @brief Number of ADC modules (register bits SOPT7[ADCnTRGSEL], SOPT7[ADCnPRETRGSEL], SOPT7[ADCnALTTRGSEL], where n is a module instance index). */ #define FSL_FEATURE_SIM_OPT_ADC_COUNT (2) /* @brief Has clock 2 output divider (register bit field CLKDIV1[OUTDIV2]). */ #define FSL_FEATURE_SIM_DIVIDER_HAS_OUTDIV2 (1) /* @brief Has clock 3 output divider (register bit field CLKDIV1[OUTDIV3]). */ #define FSL_FEATURE_SIM_DIVIDER_HAS_OUTDIV3 (1) /* @brief Has clock 4 output divider (register bit field CLKDIV1[OUTDIV4]). */ #define FSL_FEATURE_SIM_DIVIDER_HAS_OUTDIV4 (1) /* @brief Clock 4 output divider width (width of register bit field CLKDIV1[OUTDIV4]). */ #define FSL_FEATURE_SIM_DIVIDER_OUTDIV4_WIDTH (4) /* @brief Has USB clock divider (register bit field CLKDIV2[USBDIV] and CLKDIV2[USBFRAC]). */ #define FSL_FEATURE_SIM_DIVIDER_HAS_USBDIV (1) /* @brief Has USB FS clock divider (register bit field CLKDIV2[USBFSDIV] and CLKDIV2[USBFSFRAC]). */ #define FSL_FEATURE_SIM_DIVIDER_HAS_USBFSDIV (0) /* @brief Has USB HS clock divider (register bit field CLKDIV2[USBHSDIV] and CLKDIV2[USBHSFRAC]). */ #define FSL_FEATURE_SIM_DIVIDER_HAS_USBHSDIV (0) /* @brief Has PLL/FLL clock divider (register bit field CLKDIV3[PLLFLLDIV] and CLKDIV3[PLLFLLFRAC]). */ #define FSL_FEATURE_SIM_DIVIDER_HAS_PLLFLLDIV (1) /* @brief Has LCDC clock divider (register bit field CLKDIV3[LCDCDIV] and CLKDIV3[LCDCFRAC]). */ #define FSL_FEATURE_SIM_DIVIDER_HAS_LCDCDIV (0) /* @brief Has trace clock divider (register bit field CLKDIV4[TRACEDIV] and CLKDIV4[TRACEFRAC]). */ #define FSL_FEATURE_SIM_DIVIDER_HAS_TRACEDIV (1) /* @brief Has NFC clock divider (register bit field CLKDIV4[NFCDIV] and CLKDIV4[NFCFRAC]). */ #define FSL_FEATURE_SIM_DIVIDER_HAS_NFCDIV (0) /* @brief Has Kinetis family ID (register bit field SDID[FAMILYID]). */ #define FSL_FEATURE_SIM_SDID_HAS_FAMILYID (1) /* @brief Has Kinetis family ID (register bit field SDID[FAMID]). */ #define FSL_FEATURE_SIM_SDID_HAS_FAMID (1) /* @brief Has Kinetis sub-family ID (register bit field SDID[SUBFAMID]). */ #define FSL_FEATURE_SIM_SDID_HAS_SUBFAMID (1) /* @brief Has Kinetis series ID (register bit field SDID[SERIESID]). */ #define FSL_FEATURE_SIM_SDID_HAS_SERIESID (1) /* @brief Has device die ID (register bit field SDID[DIEID]). */ #define FSL_FEATURE_SIM_SDID_HAS_DIEID (1) /* @brief Has system SRAM size specifier (register bit field SDID[SRAMSIZE]). */ #define FSL_FEATURE_SIM_SDID_HAS_SRAMSIZE (0) /* @brief Has flash mode (register bit FCFG1[FLASHDOZE]). */ #define FSL_FEATURE_SIM_FCFG_HAS_FLASHDOZE (1) /* @brief Has flash disable (register bit FCFG1[FLASHDIS]). */ #define FSL_FEATURE_SIM_FCFG_HAS_FLASHDIS (1) /* @brief Has FTFE disable (register bit FCFG1[FTFDIS]). */ #define FSL_FEATURE_SIM_FCFG_HAS_FTFDIS (0) /* @brief Has FlexNVM size specifier (register bit field FCFG1[NVMSIZE]). */ #define FSL_FEATURE_SIM_FCFG_HAS_NVMSIZE (1) /* @brief Has EEPROM size specifier (register bit field FCFG1[EESIZE]). */ #define FSL_FEATURE_SIM_FCFG_HAS_EESIZE (1) /* @brief Has FlexNVM partition (register bit field FCFG1[DEPART]). */ #define FSL_FEATURE_SIM_FCFG_HAS_DEPART (1) /* @brief Maximum flash address block 0 address specifier (register bit field FCFG2[MAXADDR0]). */ #define FSL_FEATURE_SIM_FCFG_HAS_MAXADDR0 (1) /* @brief Maximum flash address block 1 address specifier (register bit field FCFG2[MAXADDR1]). */ #define FSL_FEATURE_SIM_FCFG_HAS_MAXADDR1 (1) /* @brief Maximum flash address block 0 or 1 address specifier (register bit field FCFG2[MAXADDR01]). */ #define FSL_FEATURE_SIM_FCFG_HAS_MAXADDR01 (0) /* @brief Maximum flash address block 2 or 3 address specifier (register bit field FCFG2[MAXADDR23]). */ #define FSL_FEATURE_SIM_FCFG_HAS_MAXADDR23 (0) /* @brief Has program flash availability specifier (register bit FCFG2[PFLSH]). */ #define FSL_FEATURE_SIM_FCFG_HAS_PFLSH (1) /* @brief Has program flash swapping (register bit FCFG2[SWAPPFLSH]). */ #define FSL_FEATURE_SIM_FCFG_HAS_PFLSH_SWAP (1) /* @brief Has miscellanious control register (register MCR). */ #define FSL_FEATURE_SIM_HAS_MISC_CONTROLS (0) /* @brief Has COP watchdog (registers COPC and SRVCOP). */ #define FSL_FEATURE_SIM_HAS_COP_WATCHDOG (0) /* @brief Has COP watchdog stop (register bits COPC[COPSTPEN], COPC[COPDBGEN] and COPC[COPCLKSEL]). */ #define FSL_FEATURE_SIM_HAS_COP_STOP (0) #elif defined(CPU_MK70FN1M0VMF12) || defined(CPU_MK70FX512VMF12) || defined(CPU_MK70FN1M0VMF15) || defined(CPU_MK70FX512VMF15) || \ defined(CPU_MK70FN1M0VMJ12) || defined(CPU_MK70FX512VMJ12) || defined(CPU_MK70FN1M0VMJ15) || defined(CPU_MK70FX512VMJ15) /* @brief Has USB FS divider. */ #define FSL_FEATURE_SIM_USBFS_USE_SPECIAL_DIVIDER (0) /* @brief Is PLL clock divided by 2 before MCG PLL/FLL clock selection. */ #define FSL_FEATURE_SIM_PLLCLK_USE_SPECIAL_DIVIDER (0) /* @brief Has RAM size specification (register bit field SOPT1[RAMSIZE]). */ #define FSL_FEATURE_SIM_OPT_HAS_RAMSIZE (1) /* @brief Has 32k oscillator clock output (register bit SOPT1[OSC32KOUT]). */ #define FSL_FEATURE_SIM_OPT_HAS_OSC32K_OUT (0) /* @brief Has 32k oscillator clock selection (register bit field SOPT1[OSC32KSEL]). */ #define FSL_FEATURE_SIM_OPT_HAS_OSC32K_SELECTION (1) /* @brief 32k oscillator clock selection width (width of register bit field SOPT1[OSC32KSEL]). */ #define FSL_FEATURE_SIM_OPT_OSC32K_SELECTION_WIDTH (1) /* @brief Has RTC clock output selection (register bit SOPT2[RTCCLKOUTSEL]). */ #define FSL_FEATURE_SIM_OPT_HAS_RTC_CLOCK_OUT_SELECTION (1) /* @brief Has USB voltage regulator (register bits SOPT1[USBVSTBY], SOPT1[USBSSTBY], SOPT1[USBREGEN], SOPT1CFG[URWE], SOPT1CFG[UVSWE], SOPT1CFG[USSWE]). */ #define FSL_FEATURE_SIM_OPT_HAS_USB_VOLTAGE_REGULATOR (1) /* @brief USB has integrated PHY (register bits USBPHYCTL[USBVREGSEL], USBPHYCTL[USBVREGPD], USBPHYCTL[USB3VOUTTRG], USBPHYCTL[USBDISILIM], SOPT2[USBSLSRC], SOPT2[USBREGEN]). */ #define FSL_FEATURE_SIM_OPT_HAS_USB_PHY (0) /* @brief Has PTD7 pad drive strength control (register bit SOPT2[PTD7PAD]). */ #define FSL_FEATURE_SIM_OPT_HAS_PTD7PAD (0) /* @brief Has FlexBus security level selection (register bit SOPT2[FBSL]). */ #define FSL_FEATURE_SIM_OPT_HAS_FBSL (1) /* @brief Has number of FlexBus hold cycle before FlexBus can release bus (register bit SOPT6[PCR]). */ #define FSL_FEATURE_SIM_OPT_HAS_PCR (1) /* @brief Has number of NFC hold cycle in case of FlexBus request (register bit SOPT6[MCC]). */ #define FSL_FEATURE_SIM_OPT_HAS_MCC (1) /* @brief Has UART open drain enable (register bits UARTnODE, where n is a number, in register SOPT5). */ #define FSL_FEATURE_SIM_OPT_HAS_ODE (0) /* @brief Number of UART modules (number of register bits UARTn, where n is a number, in register SCGC4). */ #define FSL_FEATURE_SIM_OPT_UART_COUNT (4) /* @brief Has LPUART0 open drain enable (register bit SOPT5[LPUART0ODE]). */ #define FSL_FEATURE_SIM_OPT_HAS_LPUART0_ODE (0) /* @brief Has LPUART1 open drain enable (register bit SOPT5[LPUART1ODE]). */ #define FSL_FEATURE_SIM_OPT_HAS_LPUART1_ODE (0) /* @brief Has CMT/UART pad drive strength control (register bit SOPT2[CMTUARTPAD]). */ #define FSL_FEATURE_SIM_OPT_HAS_CMTUARTPAD (1) /* @brief Has LPUART0 transmit data source selection (register bit SOPT5[LPUART0TXSRC]). */ #define FSL_FEATURE_SIM_OPT_HAS_LPUART0_TX_SRC (0) /* @brief Has LPUART0 receive data source selection (register bit SOPT5[LPUART0RXSRC]). */ #define FSL_FEATURE_SIM_OPT_HAS_LPUART0_RX_SRC (0) /* @brief Has LPUART1 transmit data source selection (register bit SOPT5[LPUART1TXSRC]). */ #define FSL_FEATURE_SIM_OPT_HAS_LPUART1_TX_SRC (0) /* @brief Has LPUART1 receive data source selection (register bit SOPT5[LPUART1RXSRC]). */ #define FSL_FEATURE_SIM_OPT_HAS_LPUART1_RX_SRC (0) /* @brief Has UART0 transmit data source selection (register bit SOPT5[UART0TXSRC]). */ #define FSL_FEATURE_SIM_OPT_HAS_UART0_TX_SRC (1) /* @brief UART0 transmit data source selection width (width of register bit SOPT5[UART0TXSRC]). */ #define FSL_FEATURE_SIM_OPT_UART0_TX_SRC_WIDTH (2) /* @brief Has UART0 receive data source selection (register bit SOPT5[UART0RXSRC]). */ #define FSL_FEATURE_SIM_OPT_HAS_UART0_RX_SRC (1) /* @brief UART0 receive data source selection width (width of register bit SOPT5[UART0RXSRC]). */ #define FSL_FEATURE_SIM_OPT_UART0_RX_SRC_WIDTH (2) /* @brief Has UART1 transmit data source selection (register bit SOPT5[UART1TXSRC]). */ #define FSL_FEATURE_SIM_OPT_HAS_UART1_TX_SRC (1) /* @brief Has UART1 receive data source selection (register bit SOPT5[UART1RXSRC]). */ #define FSL_FEATURE_SIM_OPT_HAS_UART1_RX_SRC (1) /* @brief UART1 receive data source selection width (width of register bit SOPT5[UART1RXSRC]). */ #define FSL_FEATURE_SIM_OPT_UART1_RX_SRC_WIDTH (2) /* @brief Has FTM module(s) configuration. */ #define FSL_FEATURE_SIM_OPT_HAS_FTM (1) /* @brief Number of FTM modules. */ #define FSL_FEATURE_SIM_OPT_FTM_COUNT (4) /* @brief Number of FTM triggers with selectable source. */ #define FSL_FEATURE_SIM_OPT_FTM_TRIGGER_COUNT (2) /* @brief Has FTM0 triggers source selection (register bits SOPT4[FTM0TRGnSRC], where n is a number). */ #define FSL_FEATURE_SIM_OPT_HAS_FTM0_TRIGGER (1) /* @brief Has FTM3 triggers source selection (register bits SOPT4[FTM3TRGnSRC], where n is a number). */ #define FSL_FEATURE_SIM_OPT_HAS_FTM3_TRIGGER (1) /* @brief Has FTM1 channel 0 input capture source selection (register bit SOPT4[FTM1CH0SRC]). */ #define FSL_FEATURE_SIM_OPT_HAS_FTM1_CHANNELS (1) /* @brief Has FTM2 channel 0 input capture source selection (register bit SOPT4[FTM2CH0SRC]). */ #define FSL_FEATURE_SIM_OPT_HAS_FTM2_CHANNELS (1) /* @brief Has FTM3 channel 0 input capture source selection (register bit SOPT4[FTM3CH0SRC]). */ #define FSL_FEATURE_SIM_OPT_HAS_FTM3_CHANNELS (0) /* @brief Has FTM2 channel 1 input capture source selection (register bit SOPT4[FTM2CH1SRC]). */ #define FSL_FEATURE_SIM_OPT_HAS_FTM2_CHANNEL1 (0) /* @brief Number of configurable FTM0 fault detection input (number of register bits SOPT4[FTM0FLTn], where n is a number starting from zero). */ #define FSL_FEATURE_SIM_OPT_FTM0_FAULT_COUNT (4) /* @brief Number of configurable FTM1 fault detection input (number of register bits SOPT4[FTM1FLTn], where n is a number starting from zero). */ #define FSL_FEATURE_SIM_OPT_FTM1_FAULT_COUNT (1) /* @brief Number of configurable FTM2 fault detection input (number of register bits SOPT4[FTM2FLTn], where n is a number starting from zero). */ #define FSL_FEATURE_SIM_OPT_FTM2_FAULT_COUNT (1) /* @brief Number of configurable FTM3 fault detection input (number of register bits SOPT4[FTM3FLTn], where n is a number starting from zero). */ #define FSL_FEATURE_SIM_OPT_FTM3_FAULT_COUNT (1) /* @brief Has FTM hardware trigger 0 software synchronization (register bit SOPT8[FTMnSYNCBIT], where n is a module instance index). */ #define FSL_FEATURE_SIM_OPT_HAS_FTM_TRIGGER_SYNC (0) /* @brief Has FTM channels output source selection (register bit SOPT8[FTMxOCHnSRC], where x is a module instance index and n is a channel index). */ #define FSL_FEATURE_SIM_OPT_HAS_FTM_CHANNELS_OUTPUT_SRC (0) /* @brief Has TPM module(s) configuration. */ #define FSL_FEATURE_SIM_OPT_HAS_TPM (0) /* @brief The highest TPM module index. */ #define FSL_FEATURE_SIM_OPT_MAX_TPM_INDEX (0) /* @brief Has TPM module with index 0. */ #define FSL_FEATURE_SIM_OPT_HAS_TPM0 (0) /* @brief Is TPM channels configuration in the SOPT4 (not SOPT9) register (register bits TPMnCH0SRC, TPMnCLKSEL, where n is a module instance index). */ #define FSL_FEATURE_SIM_OPT_HAS_TPM_CHANNELS_CONFIG_IN_SOPT4_REG (0) /* @brief Has TPM1 channel 0 input capture source selection (register bit field SOPT4[TPM1CH0SRC] or SOPT9[TPM1CH0SRC]). */ #define FSL_FEATURE_SIM_OPT_HAS_TPM1_CH0_SRC_SELECTION (0) /* @brief TPM1 channel 0 input capture source selection width (width of register bit field SOPT4[TPM1CH0SRC] or SOPT9[TPM1CH0SRC]). */ #define FSL_FEATURE_SIM_OPT_TPM1_CH0_SRC_SELECTION_WIDTH (0) /* @brief Has TPM2 channel 0 input capture source selection (register bit field SOPT4[TPM2CH0SRC]). */ #define FSL_FEATURE_SIM_OPT_HAS_TPM2_CH0_SRC_SELECTION (0) /* @brief Has TPM2 clock selection (register bit field SOPT4[TPM2CLKSEL]). */ #define FSL_FEATURE_SIM_OPT_HAS_TPM2_CLK_SEL (0) /* @brief Has PLL/FLL clock selection (register bit field SOPT2[PLLFLLSEL]). */ #define FSL_FEATURE_SIM_OPT_HAS_PLL_FLL_SELECTION (1) /* @brief PLL/FLL clock selection width (width of register bit field SOPT2[PLLFLLSEL]). */ #define FSL_FEATURE_SIM_OPT_PLL_FLL_SELECTION_WIDTH (1) /* @brief Has NFC clock source selection (register bit SOPT2[NFCSRC]). */ #define FSL_FEATURE_SIM_OPT_HAS_NFCSRC (1) /* @brief Has eSDHC clock source selection (register bit SOPT2[ESDHCSRC]). */ #define FSL_FEATURE_SIM_OPT_HAS_ESDHCSRC (1) /* @brief Has SDHC clock source selection (register bit SOPT2[SDHCSRC]). */ #define FSL_FEATURE_SIM_OPT_HAS_SDHCSRC (0) /* @brief Has LCDC clock source selection (register bits SOPT2[LCDCSRC], SOPT2[LCDC_CLKSEL]). */ #define FSL_FEATURE_SIM_OPT_HAS_LCDCSRC (1) /* @brief Has ENET timestamp clock source selection (register bit SOPT2[TIMESRC]). */ #define FSL_FEATURE_SIM_OPT_HAS_TIMESRC (1) /* @brief Has ENET RMII clock source selection (register bit SOPT2[RMIISRC]). */ #define FSL_FEATURE_SIM_OPT_HAS_RMIISRC (0) /* @brief Has USB clock source selection (register bit SOPT2[USBSRC]). */ #define FSL_FEATURE_SIM_OPT_HAS_USBSRC (0) /* @brief Has USB FS clock source selection (register bit SOPT2[USBFSRC]). */ #define FSL_FEATURE_SIM_OPT_HAS_USBFSRC (1) /* @brief Has USB HS clock source selection (register bit SOPT2[USBHSRC]). */ #define FSL_FEATURE_SIM_OPT_HAS_USBHSRC (1) /* @brief Has LPUART clock source selection (register bit SOPT2[LPUARTSRC]). */ #define FSL_FEATURE_SIM_OPT_HAS_LPUARTSRC (0) /* @brief Has LPUART0 clock source selection (register bit SOPT2[LPUART0SRC]). */ #define FSL_FEATURE_SIM_OPT_HAS_LPUART0SRC (0) /* @brief Has LPUART1 clock source selection (register bit SOPT2[LPUART1SRC]). */ #define FSL_FEATURE_SIM_OPT_HAS_LPUART1SRC (0) /* @brief Has FLEXIOSRC clock source selection (register bit SOPT2[FLEXIOSRC]). */ #define FSL_FEATURE_SIM_OPT_HAS_FLEXIOSRC (0) /* @brief Has UART0 clock source selection (register bit SOPT2[UART0SRC]). */ #define FSL_FEATURE_SIM_OPT_HAS_UART0SRC (0) /* @brief Has TPM clock source selection (register bit SOPT2[TPMSRC]). */ #define FSL_FEATURE_SIM_OPT_HAS_TPMSRC (0) /* @brief Has debug trace clock selection (register bit SOPT2[TRACECLKSEL]). */ #define FSL_FEATURE_SIM_OPT_HAS_TRACE_CLKSEL (1) /* @brief Number of ADC modules (register bits SOPT7[ADCnTRGSEL], SOPT7[ADCnPRETRGSEL], SOPT7[ADCnALTTRGSEL], where n is a module instance index). */ #define FSL_FEATURE_SIM_OPT_ADC_COUNT (4) /* @brief Has clock 2 output divider (register bit field CLKDIV1[OUTDIV2]). */ #define FSL_FEATURE_SIM_DIVIDER_HAS_OUTDIV2 (1) /* @brief Has clock 3 output divider (register bit field CLKDIV1[OUTDIV3]). */ #define FSL_FEATURE_SIM_DIVIDER_HAS_OUTDIV3 (1) /* @brief Has clock 4 output divider (register bit field CLKDIV1[OUTDIV4]). */ #define FSL_FEATURE_SIM_DIVIDER_HAS_OUTDIV4 (1) /* @brief Clock 4 output divider width (width of register bit field CLKDIV1[OUTDIV4]). */ #define FSL_FEATURE_SIM_DIVIDER_OUTDIV4_WIDTH (4) /* @brief Has USB clock divider (register bit field CLKDIV2[USBDIV] and CLKDIV2[USBFRAC]). */ #define FSL_FEATURE_SIM_DIVIDER_HAS_USBDIV (0) /* @brief Has USB FS clock divider (register bit field CLKDIV2[USBFSDIV] and CLKDIV2[USBFSFRAC]). */ #define FSL_FEATURE_SIM_DIVIDER_HAS_USBFSDIV (1) /* @brief Has USB HS clock divider (register bit field CLKDIV2[USBHSDIV] and CLKDIV2[USBHSFRAC]). */ #define FSL_FEATURE_SIM_DIVIDER_HAS_USBHSDIV (1) /* @brief Has PLL/FLL clock divider (register bit field CLKDIV3[PLLFLLDIV] and CLKDIV3[PLLFLLFRAC]). */ #define FSL_FEATURE_SIM_DIVIDER_HAS_PLLFLLDIV (0) /* @brief Has LCDC clock divider (register bit field CLKDIV3[LCDCDIV] and CLKDIV3[LCDCFRAC]). */ #define FSL_FEATURE_SIM_DIVIDER_HAS_LCDCDIV (1) /* @brief Has trace clock divider (register bit field CLKDIV4[TRACEDIV] and CLKDIV4[TRACEFRAC]). */ #define FSL_FEATURE_SIM_DIVIDER_HAS_TRACEDIV (1) /* @brief Has NFC clock divider (register bit field CLKDIV4[NFCDIV] and CLKDIV4[NFCFRAC]). */ #define FSL_FEATURE_SIM_DIVIDER_HAS_NFCDIV (1) /* @brief Has Kinetis family ID (register bit field SDID[FAMILYID]). */ #define FSL_FEATURE_SIM_SDID_HAS_FAMILYID (0) /* @brief Has Kinetis family ID (register bit field SDID[FAMID]). */ #define FSL_FEATURE_SIM_SDID_HAS_FAMID (1) /* @brief Has Kinetis sub-family ID (register bit field SDID[SUBFAMID]). */ #define FSL_FEATURE_SIM_SDID_HAS_SUBFAMID (0) /* @brief Has Kinetis series ID (register bit field SDID[SERIESID]). */ #define FSL_FEATURE_SIM_SDID_HAS_SERIESID (0) /* @brief Has device die ID (register bit field SDID[DIEID]). */ #define FSL_FEATURE_SIM_SDID_HAS_DIEID (0) /* @brief Has system SRAM size specifier (register bit field SDID[SRAMSIZE]). */ #define FSL_FEATURE_SIM_SDID_HAS_SRAMSIZE (0) /* @brief Has flash mode (register bit FCFG1[FLASHDOZE]). */ #define FSL_FEATURE_SIM_FCFG_HAS_FLASHDOZE (0) /* @brief Has flash disable (register bit FCFG1[FLASHDIS]). */ #define FSL_FEATURE_SIM_FCFG_HAS_FLASHDIS (0) /* @brief Has FTFE disable (register bit FCFG1[FTFDIS]). */ #define FSL_FEATURE_SIM_FCFG_HAS_FTFDIS (1) /* @brief Has FlexNVM size specifier (register bit field FCFG1[NVMSIZE]). */ #define FSL_FEATURE_SIM_FCFG_HAS_NVMSIZE (1) /* @brief Has EEPROM size specifier (register bit field FCFG1[EESIZE]). */ #define FSL_FEATURE_SIM_FCFG_HAS_EESIZE (1) /* @brief Has FlexNVM partition (register bit field FCFG1[DEPART]). */ #define FSL_FEATURE_SIM_FCFG_HAS_DEPART (1) /* @brief Maximum flash address block 0 address specifier (register bit field FCFG2[MAXADDR0]). */ #define FSL_FEATURE_SIM_FCFG_HAS_MAXADDR0 (0) /* @brief Maximum flash address block 1 address specifier (register bit field FCFG2[MAXADDR1]). */ #define FSL_FEATURE_SIM_FCFG_HAS_MAXADDR1 (0) /* @brief Maximum flash address block 0 or 1 address specifier (register bit field FCFG2[MAXADDR01]). */ #define FSL_FEATURE_SIM_FCFG_HAS_MAXADDR01 (1) /* @brief Maximum flash address block 2 or 3 address specifier (register bit field FCFG2[MAXADDR23]). */ #define FSL_FEATURE_SIM_FCFG_HAS_MAXADDR23 (1) /* @brief Has program flash availability specifier (register bit FCFG2[PFLSH]). */ #define FSL_FEATURE_SIM_FCFG_HAS_PFLSH (0) /* @brief Has program flash swapping (register bit FCFG2[SWAPPFLSH]). */ #define FSL_FEATURE_SIM_FCFG_HAS_PFLSH_SWAP (0) /* @brief Has miscellanious control register (register MCR). */ #define FSL_FEATURE_SIM_HAS_MISC_CONTROLS (1) /* @brief Has COP watchdog (registers COPC and SRVCOP). */ #define FSL_FEATURE_SIM_HAS_COP_WATCHDOG (0) /* @brief Has COP watchdog stop (register bits COPC[COPSTPEN], COPC[COPDBGEN] and COPC[COPCLKSEL]). */ #define FSL_FEATURE_SIM_HAS_COP_STOP (0) #elif defined(CPU_MKL03Z32CAF4) || defined(CPU_MKL03Z8VFG4) || defined(CPU_MKL03Z16VFG4) || defined(CPU_MKL03Z32VFG4) || \ defined(CPU_MKL03Z8VFK4) || defined(CPU_MKL03Z16VFK4) || defined(CPU_MKL03Z32VFK4) /* @brief Has USB FS divider. */ #define FSL_FEATURE_SIM_USBFS_USE_SPECIAL_DIVIDER (0) /* @brief Is PLL clock divided by 2 before MCG PLL/FLL clock selection. */ #define FSL_FEATURE_SIM_PLLCLK_USE_SPECIAL_DIVIDER (0) /* @brief Has RAM size specification (register bit field SOPT1[RAMSIZE]). */ #define FSL_FEATURE_SIM_OPT_HAS_RAMSIZE (0) /* @brief Has 32k oscillator clock output (register bit SOPT1[OSC32KOUT]). */ #define FSL_FEATURE_SIM_OPT_HAS_OSC32K_OUT (1) /* @brief Has 32k oscillator clock selection (register bit field SOPT1[OSC32KSEL]). */ #define FSL_FEATURE_SIM_OPT_HAS_OSC32K_SELECTION (1) /* @brief 32k oscillator clock selection width (width of register bit field SOPT1[OSC32KSEL]). */ #define FSL_FEATURE_SIM_OPT_OSC32K_SELECTION_WIDTH (2) /* @brief Has RTC clock output selection (register bit SOPT2[RTCCLKOUTSEL]). */ #define FSL_FEATURE_SIM_OPT_HAS_RTC_CLOCK_OUT_SELECTION (1) /* @brief Has USB voltage regulator (register bits SOPT1[USBVSTBY], SOPT1[USBSSTBY], SOPT1[USBREGEN], SOPT1CFG[URWE], SOPT1CFG[UVSWE], SOPT1CFG[USSWE]). */ #define FSL_FEATURE_SIM_OPT_HAS_USB_VOLTAGE_REGULATOR (0) /* @brief USB has integrated PHY (register bits USBPHYCTL[USBVREGSEL], USBPHYCTL[USBVREGPD], USBPHYCTL[USB3VOUTTRG], USBPHYCTL[USBDISILIM], SOPT2[USBSLSRC], SOPT2[USBREGEN]). */ #define FSL_FEATURE_SIM_OPT_HAS_USB_PHY (0) /* @brief Has PTD7 pad drive strength control (register bit SOPT2[PTD7PAD]). */ #define FSL_FEATURE_SIM_OPT_HAS_PTD7PAD (0) /* @brief Has FlexBus security level selection (register bit SOPT2[FBSL]). */ #define FSL_FEATURE_SIM_OPT_HAS_FBSL (0) /* @brief Has number of FlexBus hold cycle before FlexBus can release bus (register bit SOPT6[PCR]). */ #define FSL_FEATURE_SIM_OPT_HAS_PCR (0) /* @brief Has number of NFC hold cycle in case of FlexBus request (register bit SOPT6[MCC]). */ #define FSL_FEATURE_SIM_OPT_HAS_MCC (0) /* @brief Has UART open drain enable (register bits UARTnODE, where n is a number, in register SOPT5). */ #define FSL_FEATURE_SIM_OPT_HAS_ODE (0) /* @brief Number of UART modules (number of register bits UARTn, where n is a number, in register SCGC4). */ #define FSL_FEATURE_SIM_OPT_UART_COUNT (0) /* @brief Has LPUART0 open drain enable (register bit SOPT5[LPUART0ODE]). */ #define FSL_FEATURE_SIM_OPT_HAS_LPUART0_ODE (1) /* @brief Has LPUART1 open drain enable (register bit SOPT5[LPUART1ODE]). */ #define FSL_FEATURE_SIM_OPT_HAS_LPUART1_ODE (0) /* @brief Has CMT/UART pad drive strength control (register bit SOPT2[CMTUARTPAD]). */ #define FSL_FEATURE_SIM_OPT_HAS_CMTUARTPAD (0) /* @brief Has LPUART0 transmit data source selection (register bit SOPT5[LPUART0TXSRC]). */ #define FSL_FEATURE_SIM_OPT_HAS_LPUART0_TX_SRC (1) /* @brief Has LPUART0 receive data source selection (register bit SOPT5[LPUART0RXSRC]). */ #define FSL_FEATURE_SIM_OPT_HAS_LPUART0_RX_SRC (1) /* @brief Has LPUART1 transmit data source selection (register bit SOPT5[LPUART1TXSRC]). */ #define FSL_FEATURE_SIM_OPT_HAS_LPUART1_TX_SRC (0) /* @brief Has LPUART1 receive data source selection (register bit SOPT5[LPUART1RXSRC]). */ #define FSL_FEATURE_SIM_OPT_HAS_LPUART1_RX_SRC (0) /* @brief Has UART0 transmit data source selection (register bit SOPT5[UART0TXSRC]). */ #define FSL_FEATURE_SIM_OPT_HAS_UART0_TX_SRC (0) /* @brief UART0 transmit data source selection width (width of register bit SOPT5[UART0TXSRC]). */ #define FSL_FEATURE_SIM_OPT_UART0_TX_SRC_WIDTH (0) /* @brief Has UART0 receive data source selection (register bit SOPT5[UART0RXSRC]). */ #define FSL_FEATURE_SIM_OPT_HAS_UART0_RX_SRC (0) /* @brief UART0 receive data source selection width (width of register bit SOPT5[UART0RXSRC]). */ #define FSL_FEATURE_SIM_OPT_UART0_RX_SRC_WIDTH (0) /* @brief Has UART1 transmit data source selection (register bit SOPT5[UART1TXSRC]). */ #define FSL_FEATURE_SIM_OPT_HAS_UART1_TX_SRC (0) /* @brief Has UART1 receive data source selection (register bit SOPT5[UART1RXSRC]). */ #define FSL_FEATURE_SIM_OPT_HAS_UART1_RX_SRC (0) /* @brief UART1 receive data source selection width (width of register bit SOPT5[UART1RXSRC]). */ #define FSL_FEATURE_SIM_OPT_UART1_RX_SRC_WIDTH (0) /* @brief Has FTM module(s) configuration. */ #define FSL_FEATURE_SIM_OPT_HAS_FTM (0) /* @brief Number of FTM modules. */ #define FSL_FEATURE_SIM_OPT_FTM_COUNT (0) /* @brief Number of FTM triggers with selectable source. */ #define FSL_FEATURE_SIM_OPT_FTM_TRIGGER_COUNT (0) /* @brief Has FTM0 triggers source selection (register bits SOPT4[FTM0TRGnSRC], where n is a number). */ #define FSL_FEATURE_SIM_OPT_HAS_FTM0_TRIGGER (0) /* @brief Has FTM3 triggers source selection (register bits SOPT4[FTM3TRGnSRC], where n is a number). */ #define FSL_FEATURE_SIM_OPT_HAS_FTM3_TRIGGER (0) /* @brief Has FTM1 channel 0 input capture source selection (register bit SOPT4[FTM1CH0SRC]). */ #define FSL_FEATURE_SIM_OPT_HAS_FTM1_CHANNELS (0) /* @brief Has FTM2 channel 0 input capture source selection (register bit SOPT4[FTM2CH0SRC]). */ #define FSL_FEATURE_SIM_OPT_HAS_FTM2_CHANNELS (0) /* @brief Has FTM3 channel 0 input capture source selection (register bit SOPT4[FTM3CH0SRC]). */ #define FSL_FEATURE_SIM_OPT_HAS_FTM3_CHANNELS (0) /* @brief Has FTM2 channel 1 input capture source selection (register bit SOPT4[FTM2CH1SRC]). */ #define FSL_FEATURE_SIM_OPT_HAS_FTM2_CHANNEL1 (0) /* @brief Number of configurable FTM0 fault detection input (number of register bits SOPT4[FTM0FLTn], where n is a number starting from zero). */ #define FSL_FEATURE_SIM_OPT_FTM0_FAULT_COUNT (0) /* @brief Number of configurable FTM1 fault detection input (number of register bits SOPT4[FTM1FLTn], where n is a number starting from zero). */ #define FSL_FEATURE_SIM_OPT_FTM1_FAULT_COUNT (0) /* @brief Number of configurable FTM2 fault detection input (number of register bits SOPT4[FTM2FLTn], where n is a number starting from zero). */ #define FSL_FEATURE_SIM_OPT_FTM2_FAULT_COUNT (0) /* @brief Number of configurable FTM3 fault detection input (number of register bits SOPT4[FTM3FLTn], where n is a number starting from zero). */ #define FSL_FEATURE_SIM_OPT_FTM3_FAULT_COUNT (0) /* @brief Has FTM hardware trigger 0 software synchronization (register bit SOPT8[FTMnSYNCBIT], where n is a module instance index). */ #define FSL_FEATURE_SIM_OPT_HAS_FTM_TRIGGER_SYNC (0) /* @brief Has FTM channels output source selection (register bit SOPT8[FTMxOCHnSRC], where x is a module instance index and n is a channel index). */ #define FSL_FEATURE_SIM_OPT_HAS_FTM_CHANNELS_OUTPUT_SRC (0) /* @brief Has TPM module(s) configuration. */ #define FSL_FEATURE_SIM_OPT_HAS_TPM (1) /* @brief The highest TPM module index. */ #define FSL_FEATURE_SIM_OPT_MAX_TPM_INDEX (1) /* @brief Has TPM module with index 0. */ #define FSL_FEATURE_SIM_OPT_HAS_TPM0 (1) /* @brief Is TPM channels configuration in the SOPT4 (not SOPT9) register (register bits TPMnCH0SRC, TPMnCLKSEL, where n is a module instance index). */ #define FSL_FEATURE_SIM_OPT_HAS_TPM_CHANNELS_CONFIG_IN_SOPT4_REG (0) /* @brief Has TPM1 channel 0 input capture source selection (register bit field SOPT4[TPM1CH0SRC] or SOPT9[TPM1CH0SRC]). */ #define FSL_FEATURE_SIM_OPT_HAS_TPM1_CH0_SRC_SELECTION (1) /* @brief TPM1 channel 0 input capture source selection width (width of register bit field SOPT4[TPM1CH0SRC] or SOPT9[TPM1CH0SRC]). */ #define FSL_FEATURE_SIM_OPT_TPM1_CH0_SRC_SELECTION_WIDTH (1) /* @brief Has TPM2 channel 0 input capture source selection (register bit field SOPT4[TPM2CH0SRC]). */ #define FSL_FEATURE_SIM_OPT_HAS_TPM2_CH0_SRC_SELECTION (0) /* @brief Has TPM2 clock selection (register bit field SOPT4[TPM2CLKSEL]). */ #define FSL_FEATURE_SIM_OPT_HAS_TPM2_CLK_SEL (0) /* @brief Has PLL/FLL clock selection (register bit field SOPT2[PLLFLLSEL]). */ #define FSL_FEATURE_SIM_OPT_HAS_PLL_FLL_SELECTION (0) /* @brief PLL/FLL clock selection width (width of register bit field SOPT2[PLLFLLSEL]). */ #define FSL_FEATURE_SIM_OPT_PLL_FLL_SELECTION_WIDTH (0) /* @brief Has NFC clock source selection (register bit SOPT2[NFCSRC]). */ #define FSL_FEATURE_SIM_OPT_HAS_NFCSRC (0) /* @brief Has eSDHC clock source selection (register bit SOPT2[ESDHCSRC]). */ #define FSL_FEATURE_SIM_OPT_HAS_ESDHCSRC (0) /* @brief Has SDHC clock source selection (register bit SOPT2[SDHCSRC]). */ #define FSL_FEATURE_SIM_OPT_HAS_SDHCSRC (0) /* @brief Has LCDC clock source selection (register bits SOPT2[LCDCSRC], SOPT2[LCDC_CLKSEL]). */ #define FSL_FEATURE_SIM_OPT_HAS_LCDCSRC (0) /* @brief Has ENET timestamp clock source selection (register bit SOPT2[TIMESRC]). */ #define FSL_FEATURE_SIM_OPT_HAS_TIMESRC (0) /* @brief Has ENET RMII clock source selection (register bit SOPT2[RMIISRC]). */ #define FSL_FEATURE_SIM_OPT_HAS_RMIISRC (0) /* @brief Has USB clock source selection (register bit SOPT2[USBSRC]). */ #define FSL_FEATURE_SIM_OPT_HAS_USBSRC (0) /* @brief Has USB FS clock source selection (register bit SOPT2[USBFSRC]). */ #define FSL_FEATURE_SIM_OPT_HAS_USBFSRC (0) /* @brief Has USB HS clock source selection (register bit SOPT2[USBHSRC]). */ #define FSL_FEATURE_SIM_OPT_HAS_USBHSRC (0) /* @brief Has LPUART clock source selection (register bit SOPT2[LPUARTSRC]). */ #define FSL_FEATURE_SIM_OPT_HAS_LPUARTSRC (0) /* @brief Has LPUART0 clock source selection (register bit SOPT2[LPUART0SRC]). */ #define FSL_FEATURE_SIM_OPT_HAS_LPUART0SRC (1) /* @brief Has LPUART1 clock source selection (register bit SOPT2[LPUART1SRC]). */ #define FSL_FEATURE_SIM_OPT_HAS_LPUART1SRC (0) /* @brief Has FLEXIOSRC clock source selection (register bit SOPT2[FLEXIOSRC]). */ #define FSL_FEATURE_SIM_OPT_HAS_FLEXIOSRC (0) /* @brief Has UART0 clock source selection (register bit SOPT2[UART0SRC]). */ #define FSL_FEATURE_SIM_OPT_HAS_UART0SRC (0) /* @brief Has TPM clock source selection (register bit SOPT2[TPMSRC]). */ #define FSL_FEATURE_SIM_OPT_HAS_TPMSRC (1) /* @brief Has debug trace clock selection (register bit SOPT2[TRACECLKSEL]). */ #define FSL_FEATURE_SIM_OPT_HAS_TRACE_CLKSEL (0) /* @brief Number of ADC modules (register bits SOPT7[ADCnTRGSEL], SOPT7[ADCnPRETRGSEL], SOPT7[ADCnALTTRGSEL], where n is a module instance index). */ #define FSL_FEATURE_SIM_OPT_ADC_COUNT (1) /* @brief Has clock 2 output divider (register bit field CLKDIV1[OUTDIV2]). */ #define FSL_FEATURE_SIM_DIVIDER_HAS_OUTDIV2 (0) /* @brief Has clock 3 output divider (register bit field CLKDIV1[OUTDIV3]). */ #define FSL_FEATURE_SIM_DIVIDER_HAS_OUTDIV3 (0) /* @brief Has clock 4 output divider (register bit field CLKDIV1[OUTDIV4]). */ #define FSL_FEATURE_SIM_DIVIDER_HAS_OUTDIV4 (1) /* @brief Clock 4 output divider width (width of register bit field CLKDIV1[OUTDIV4]). */ #define FSL_FEATURE_SIM_DIVIDER_OUTDIV4_WIDTH (3) /* @brief Has USB clock divider (register bit field CLKDIV2[USBDIV] and CLKDIV2[USBFRAC]). */ #define FSL_FEATURE_SIM_DIVIDER_HAS_USBDIV (0) /* @brief Has USB FS clock divider (register bit field CLKDIV2[USBFSDIV] and CLKDIV2[USBFSFRAC]). */ #define FSL_FEATURE_SIM_DIVIDER_HAS_USBFSDIV (0) /* @brief Has USB HS clock divider (register bit field CLKDIV2[USBHSDIV] and CLKDIV2[USBHSFRAC]). */ #define FSL_FEATURE_SIM_DIVIDER_HAS_USBHSDIV (0) /* @brief Has PLL/FLL clock divider (register bit field CLKDIV3[PLLFLLDIV] and CLKDIV3[PLLFLLFRAC]). */ #define FSL_FEATURE_SIM_DIVIDER_HAS_PLLFLLDIV (0) /* @brief Has LCDC clock divider (register bit field CLKDIV3[LCDCDIV] and CLKDIV3[LCDCFRAC]). */ #define FSL_FEATURE_SIM_DIVIDER_HAS_LCDCDIV (0) /* @brief Has trace clock divider (register bit field CLKDIV4[TRACEDIV] and CLKDIV4[TRACEFRAC]). */ #define FSL_FEATURE_SIM_DIVIDER_HAS_TRACEDIV (0) /* @brief Has NFC clock divider (register bit field CLKDIV4[NFCDIV] and CLKDIV4[NFCFRAC]). */ #define FSL_FEATURE_SIM_DIVIDER_HAS_NFCDIV (0) /* @brief Has Kinetis family ID (register bit field SDID[FAMILYID]). */ #define FSL_FEATURE_SIM_SDID_HAS_FAMILYID (0) /* @brief Has Kinetis family ID (register bit field SDID[FAMID]). */ #define FSL_FEATURE_SIM_SDID_HAS_FAMID (1) /* @brief Has Kinetis sub-family ID (register bit field SDID[SUBFAMID]). */ #define FSL_FEATURE_SIM_SDID_HAS_SUBFAMID (1) /* @brief Has Kinetis series ID (register bit field SDID[SERIESID]). */ #define FSL_FEATURE_SIM_SDID_HAS_SERIESID (1) /* @brief Has device die ID (register bit field SDID[DIEID]). */ #define FSL_FEATURE_SIM_SDID_HAS_DIEID (1) /* @brief Has system SRAM size specifier (register bit field SDID[SRAMSIZE]). */ #define FSL_FEATURE_SIM_SDID_HAS_SRAMSIZE (1) /* @brief Has flash mode (register bit FCFG1[FLASHDOZE]). */ #define FSL_FEATURE_SIM_FCFG_HAS_FLASHDOZE (1) /* @brief Has flash disable (register bit FCFG1[FLASHDIS]). */ #define FSL_FEATURE_SIM_FCFG_HAS_FLASHDIS (1) /* @brief Has FTFE disable (register bit FCFG1[FTFDIS]). */ #define FSL_FEATURE_SIM_FCFG_HAS_FTFDIS (0) /* @brief Has FlexNVM size specifier (register bit field FCFG1[NVMSIZE]). */ #define FSL_FEATURE_SIM_FCFG_HAS_NVMSIZE (0) /* @brief Has EEPROM size specifier (register bit field FCFG1[EESIZE]). */ #define FSL_FEATURE_SIM_FCFG_HAS_EESIZE (0) /* @brief Has FlexNVM partition (register bit field FCFG1[DEPART]). */ #define FSL_FEATURE_SIM_FCFG_HAS_DEPART (0) /* @brief Maximum flash address block 0 address specifier (register bit field FCFG2[MAXADDR0]). */ #define FSL_FEATURE_SIM_FCFG_HAS_MAXADDR0 (1) /* @brief Maximum flash address block 1 address specifier (register bit field FCFG2[MAXADDR1]). */ #define FSL_FEATURE_SIM_FCFG_HAS_MAXADDR1 (0) /* @brief Maximum flash address block 0 or 1 address specifier (register bit field FCFG2[MAXADDR01]). */ #define FSL_FEATURE_SIM_FCFG_HAS_MAXADDR01 (0) /* @brief Maximum flash address block 2 or 3 address specifier (register bit field FCFG2[MAXADDR23]). */ #define FSL_FEATURE_SIM_FCFG_HAS_MAXADDR23 (0) /* @brief Has program flash availability specifier (register bit FCFG2[PFLSH]). */ #define FSL_FEATURE_SIM_FCFG_HAS_PFLSH (0) /* @brief Has program flash swapping (register bit FCFG2[SWAPPFLSH]). */ #define FSL_FEATURE_SIM_FCFG_HAS_PFLSH_SWAP (0) /* @brief Has miscellanious control register (register MCR). */ #define FSL_FEATURE_SIM_HAS_MISC_CONTROLS (0) /* @brief Has COP watchdog (registers COPC and SRVCOP). */ #define FSL_FEATURE_SIM_HAS_COP_WATCHDOG (1) /* @brief Has COP watchdog stop (register bits COPC[COPSTPEN], COPC[COPDBGEN] and COPC[COPCLKSEL]). */ #define FSL_FEATURE_SIM_HAS_COP_STOP (1) #elif defined(CPU_MKL05Z8VFK4) || defined(CPU_MKL05Z16VFK4) || defined(CPU_MKL05Z32VFK4) || defined(CPU_MKL05Z8VLC4) || \ defined(CPU_MKL05Z16VLC4) || defined(CPU_MKL05Z32VLC4) || defined(CPU_MKL05Z8VFM4) || defined(CPU_MKL05Z16VFM4) || \ defined(CPU_MKL05Z32VFM4) || defined(CPU_MKL05Z16VLF4) || defined(CPU_MKL05Z32VLF4) /* @brief Has USB FS divider. */ #define FSL_FEATURE_SIM_USBFS_USE_SPECIAL_DIVIDER (0) /* @brief Is PLL clock divided by 2 before MCG PLL/FLL clock selection. */ #define FSL_FEATURE_SIM_PLLCLK_USE_SPECIAL_DIVIDER (0) /* @brief Has RAM size specification (register bit field SOPT1[RAMSIZE]). */ #define FSL_FEATURE_SIM_OPT_HAS_RAMSIZE (0) /* @brief Has 32k oscillator clock output (register bit SOPT1[OSC32KOUT]). */ #define FSL_FEATURE_SIM_OPT_HAS_OSC32K_OUT (0) /* @brief Has 32k oscillator clock selection (register bit field SOPT1[OSC32KSEL]). */ #define FSL_FEATURE_SIM_OPT_HAS_OSC32K_SELECTION (1) /* @brief 32k oscillator clock selection width (width of register bit field SOPT1[OSC32KSEL]). */ #define FSL_FEATURE_SIM_OPT_OSC32K_SELECTION_WIDTH (2) /* @brief Has RTC clock output selection (register bit SOPT2[RTCCLKOUTSEL]). */ #define FSL_FEATURE_SIM_OPT_HAS_RTC_CLOCK_OUT_SELECTION (1) /* @brief Has USB voltage regulator (register bits SOPT1[USBVSTBY], SOPT1[USBSSTBY], SOPT1[USBREGEN], SOPT1CFG[URWE], SOPT1CFG[UVSWE], SOPT1CFG[USSWE]). */ #define FSL_FEATURE_SIM_OPT_HAS_USB_VOLTAGE_REGULATOR (0) /* @brief USB has integrated PHY (register bits USBPHYCTL[USBVREGSEL], USBPHYCTL[USBVREGPD], USBPHYCTL[USB3VOUTTRG], USBPHYCTL[USBDISILIM], SOPT2[USBSLSRC], SOPT2[USBREGEN]). */ #define FSL_FEATURE_SIM_OPT_HAS_USB_PHY (0) /* @brief Has PTD7 pad drive strength control (register bit SOPT2[PTD7PAD]). */ #define FSL_FEATURE_SIM_OPT_HAS_PTD7PAD (0) /* @brief Has FlexBus security level selection (register bit SOPT2[FBSL]). */ #define FSL_FEATURE_SIM_OPT_HAS_FBSL (0) /* @brief Has number of FlexBus hold cycle before FlexBus can release bus (register bit SOPT6[PCR]). */ #define FSL_FEATURE_SIM_OPT_HAS_PCR (0) /* @brief Has number of NFC hold cycle in case of FlexBus request (register bit SOPT6[MCC]). */ #define FSL_FEATURE_SIM_OPT_HAS_MCC (0) /* @brief Has UART open drain enable (register bits UARTnODE, where n is a number, in register SOPT5). */ #define FSL_FEATURE_SIM_OPT_HAS_ODE (1) /* @brief Number of UART modules (number of register bits UARTn, where n is a number, in register SCGC4). */ #define FSL_FEATURE_SIM_OPT_UART_COUNT (1) /* @brief Has LPUART0 open drain enable (register bit SOPT5[LPUART0ODE]). */ #define FSL_FEATURE_SIM_OPT_HAS_LPUART0_ODE (0) /* @brief Has LPUART1 open drain enable (register bit SOPT5[LPUART1ODE]). */ #define FSL_FEATURE_SIM_OPT_HAS_LPUART1_ODE (0) /* @brief Has CMT/UART pad drive strength control (register bit SOPT2[CMTUARTPAD]). */ #define FSL_FEATURE_SIM_OPT_HAS_CMTUARTPAD (0) /* @brief Has LPUART0 transmit data source selection (register bit SOPT5[LPUART0TXSRC]). */ #define FSL_FEATURE_SIM_OPT_HAS_LPUART0_TX_SRC (0) /* @brief Has LPUART0 receive data source selection (register bit SOPT5[LPUART0RXSRC]). */ #define FSL_FEATURE_SIM_OPT_HAS_LPUART0_RX_SRC (0) /* @brief Has LPUART1 transmit data source selection (register bit SOPT5[LPUART1TXSRC]). */ #define FSL_FEATURE_SIM_OPT_HAS_LPUART1_TX_SRC (0) /* @brief Has LPUART1 receive data source selection (register bit SOPT5[LPUART1RXSRC]). */ #define FSL_FEATURE_SIM_OPT_HAS_LPUART1_RX_SRC (0) /* @brief Has UART0 transmit data source selection (register bit SOPT5[UART0TXSRC]). */ #define FSL_FEATURE_SIM_OPT_HAS_UART0_TX_SRC (1) /* @brief UART0 transmit data source selection width (width of register bit SOPT5[UART0TXSRC]). */ #define FSL_FEATURE_SIM_OPT_UART0_TX_SRC_WIDTH (1) /* @brief Has UART0 receive data source selection (register bit SOPT5[UART0RXSRC]). */ #define FSL_FEATURE_SIM_OPT_HAS_UART0_RX_SRC (1) /* @brief UART0 receive data source selection width (width of register bit SOPT5[UART0RXSRC]). */ #define FSL_FEATURE_SIM_OPT_UART0_RX_SRC_WIDTH (1) /* @brief Has UART1 transmit data source selection (register bit SOPT5[UART1TXSRC]). */ #define FSL_FEATURE_SIM_OPT_HAS_UART1_TX_SRC (0) /* @brief Has UART1 receive data source selection (register bit SOPT5[UART1RXSRC]). */ #define FSL_FEATURE_SIM_OPT_HAS_UART1_RX_SRC (0) /* @brief UART1 receive data source selection width (width of register bit SOPT5[UART1RXSRC]). */ #define FSL_FEATURE_SIM_OPT_UART1_RX_SRC_WIDTH (0) /* @brief Has FTM module(s) configuration. */ #define FSL_FEATURE_SIM_OPT_HAS_FTM (0) /* @brief Number of FTM modules. */ #define FSL_FEATURE_SIM_OPT_FTM_COUNT (0) /* @brief Number of FTM triggers with selectable source. */ #define FSL_FEATURE_SIM_OPT_FTM_TRIGGER_COUNT (0) /* @brief Has FTM0 triggers source selection (register bits SOPT4[FTM0TRGnSRC], where n is a number). */ #define FSL_FEATURE_SIM_OPT_HAS_FTM0_TRIGGER (0) /* @brief Has FTM3 triggers source selection (register bits SOPT4[FTM3TRGnSRC], where n is a number). */ #define FSL_FEATURE_SIM_OPT_HAS_FTM3_TRIGGER (0) /* @brief Has FTM1 channel 0 input capture source selection (register bit SOPT4[FTM1CH0SRC]). */ #define FSL_FEATURE_SIM_OPT_HAS_FTM1_CHANNELS (0) /* @brief Has FTM2 channel 0 input capture source selection (register bit SOPT4[FTM2CH0SRC]). */ #define FSL_FEATURE_SIM_OPT_HAS_FTM2_CHANNELS (0) /* @brief Has FTM3 channel 0 input capture source selection (register bit SOPT4[FTM3CH0SRC]). */ #define FSL_FEATURE_SIM_OPT_HAS_FTM3_CHANNELS (0) /* @brief Has FTM2 channel 1 input capture source selection (register bit SOPT4[FTM2CH1SRC]). */ #define FSL_FEATURE_SIM_OPT_HAS_FTM2_CHANNEL1 (0) /* @brief Number of configurable FTM0 fault detection input (number of register bits SOPT4[FTM0FLTn], where n is a number starting from zero). */ #define FSL_FEATURE_SIM_OPT_FTM0_FAULT_COUNT (0) /* @brief Number of configurable FTM1 fault detection input (number of register bits SOPT4[FTM1FLTn], where n is a number starting from zero). */ #define FSL_FEATURE_SIM_OPT_FTM1_FAULT_COUNT (0) /* @brief Number of configurable FTM2 fault detection input (number of register bits SOPT4[FTM2FLTn], where n is a number starting from zero). */ #define FSL_FEATURE_SIM_OPT_FTM2_FAULT_COUNT (0) /* @brief Number of configurable FTM3 fault detection input (number of register bits SOPT4[FTM3FLTn], where n is a number starting from zero). */ #define FSL_FEATURE_SIM_OPT_FTM3_FAULT_COUNT (0) /* @brief Has FTM hardware trigger 0 software synchronization (register bit SOPT8[FTMnSYNCBIT], where n is a module instance index). */ #define FSL_FEATURE_SIM_OPT_HAS_FTM_TRIGGER_SYNC (0) /* @brief Has FTM channels output source selection (register bit SOPT8[FTMxOCHnSRC], where x is a module instance index and n is a channel index). */ #define FSL_FEATURE_SIM_OPT_HAS_FTM_CHANNELS_OUTPUT_SRC (0) /* @brief Has TPM module(s) configuration. */ #define FSL_FEATURE_SIM_OPT_HAS_TPM (1) /* @brief The highest TPM module index. */ #define FSL_FEATURE_SIM_OPT_MAX_TPM_INDEX (1) /* @brief Has TPM module with index 0. */ #define FSL_FEATURE_SIM_OPT_HAS_TPM0 (1) /* @brief Is TPM channels configuration in the SOPT4 (not SOPT9) register (register bits TPMnCH0SRC, TPMnCLKSEL, where n is a module instance index). */ #define FSL_FEATURE_SIM_OPT_HAS_TPM_CHANNELS_CONFIG_IN_SOPT4_REG (0) /* @brief Has TPM1 channel 0 input capture source selection (register bit field SOPT4[TPM1CH0SRC] or SOPT9[TPM1CH0SRC]). */ #define FSL_FEATURE_SIM_OPT_HAS_TPM1_CH0_SRC_SELECTION (1) /* @brief TPM1 channel 0 input capture source selection width (width of register bit field SOPT4[TPM1CH0SRC] or SOPT9[TPM1CH0SRC]). */ #define FSL_FEATURE_SIM_OPT_TPM1_CH0_SRC_SELECTION_WIDTH (1) /* @brief Has TPM2 channel 0 input capture source selection (register bit field SOPT4[TPM2CH0SRC]). */ #define FSL_FEATURE_SIM_OPT_HAS_TPM2_CH0_SRC_SELECTION (0) /* @brief Has TPM2 clock selection (register bit field SOPT4[TPM2CLKSEL]). */ #define FSL_FEATURE_SIM_OPT_HAS_TPM2_CLK_SEL (0) /* @brief Has PLL/FLL clock selection (register bit field SOPT2[PLLFLLSEL]). */ #define FSL_FEATURE_SIM_OPT_HAS_PLL_FLL_SELECTION (0) /* @brief PLL/FLL clock selection width (width of register bit field SOPT2[PLLFLLSEL]). */ #define FSL_FEATURE_SIM_OPT_PLL_FLL_SELECTION_WIDTH (0) /* @brief Has NFC clock source selection (register bit SOPT2[NFCSRC]). */ #define FSL_FEATURE_SIM_OPT_HAS_NFCSRC (0) /* @brief Has eSDHC clock source selection (register bit SOPT2[ESDHCSRC]). */ #define FSL_FEATURE_SIM_OPT_HAS_ESDHCSRC (0) /* @brief Has SDHC clock source selection (register bit SOPT2[SDHCSRC]). */ #define FSL_FEATURE_SIM_OPT_HAS_SDHCSRC (0) /* @brief Has LCDC clock source selection (register bits SOPT2[LCDCSRC], SOPT2[LCDC_CLKSEL]). */ #define FSL_FEATURE_SIM_OPT_HAS_LCDCSRC (0) /* @brief Has ENET timestamp clock source selection (register bit SOPT2[TIMESRC]). */ #define FSL_FEATURE_SIM_OPT_HAS_TIMESRC (0) /* @brief Has ENET RMII clock source selection (register bit SOPT2[RMIISRC]). */ #define FSL_FEATURE_SIM_OPT_HAS_RMIISRC (0) /* @brief Has USB clock source selection (register bit SOPT2[USBSRC]). */ #define FSL_FEATURE_SIM_OPT_HAS_USBSRC (0) /* @brief Has USB FS clock source selection (register bit SOPT2[USBFSRC]). */ #define FSL_FEATURE_SIM_OPT_HAS_USBFSRC (0) /* @brief Has USB HS clock source selection (register bit SOPT2[USBHSRC]). */ #define FSL_FEATURE_SIM_OPT_HAS_USBHSRC (0) /* @brief Has LPUART clock source selection (register bit SOPT2[LPUARTSRC]). */ #define FSL_FEATURE_SIM_OPT_HAS_LPUARTSRC (0) /* @brief Has LPUART0 clock source selection (register bit SOPT2[LPUART0SRC]). */ #define FSL_FEATURE_SIM_OPT_HAS_LPUART0SRC (0) /* @brief Has LPUART1 clock source selection (register bit SOPT2[LPUART1SRC]). */ #define FSL_FEATURE_SIM_OPT_HAS_LPUART1SRC (0) /* @brief Has FLEXIOSRC clock source selection (register bit SOPT2[FLEXIOSRC]). */ #define FSL_FEATURE_SIM_OPT_HAS_FLEXIOSRC (0) /* @brief Has UART0 clock source selection (register bit SOPT2[UART0SRC]). */ #define FSL_FEATURE_SIM_OPT_HAS_UART0SRC (1) /* @brief Has TPM clock source selection (register bit SOPT2[TPMSRC]). */ #define FSL_FEATURE_SIM_OPT_HAS_TPMSRC (1) /* @brief Has debug trace clock selection (register bit SOPT2[TRACECLKSEL]). */ #define FSL_FEATURE_SIM_OPT_HAS_TRACE_CLKSEL (0) /* @brief Number of ADC modules (register bits SOPT7[ADCnTRGSEL], SOPT7[ADCnPRETRGSEL], SOPT7[ADCnALTTRGSEL], where n is a module instance index). */ #define FSL_FEATURE_SIM_OPT_ADC_COUNT (1) /* @brief Has clock 2 output divider (register bit field CLKDIV1[OUTDIV2]). */ #define FSL_FEATURE_SIM_DIVIDER_HAS_OUTDIV2 (0) /* @brief Has clock 3 output divider (register bit field CLKDIV1[OUTDIV3]). */ #define FSL_FEATURE_SIM_DIVIDER_HAS_OUTDIV3 (0) /* @brief Has clock 4 output divider (register bit field CLKDIV1[OUTDIV4]). */ #define FSL_FEATURE_SIM_DIVIDER_HAS_OUTDIV4 (1) /* @brief Clock 4 output divider width (width of register bit field CLKDIV1[OUTDIV4]). */ #define FSL_FEATURE_SIM_DIVIDER_OUTDIV4_WIDTH (3) /* @brief Has USB clock divider (register bit field CLKDIV2[USBDIV] and CLKDIV2[USBFRAC]). */ #define FSL_FEATURE_SIM_DIVIDER_HAS_USBDIV (0) /* @brief Has USB FS clock divider (register bit field CLKDIV2[USBFSDIV] and CLKDIV2[USBFSFRAC]). */ #define FSL_FEATURE_SIM_DIVIDER_HAS_USBFSDIV (0) /* @brief Has USB HS clock divider (register bit field CLKDIV2[USBHSDIV] and CLKDIV2[USBHSFRAC]). */ #define FSL_FEATURE_SIM_DIVIDER_HAS_USBHSDIV (0) /* @brief Has PLL/FLL clock divider (register bit field CLKDIV3[PLLFLLDIV] and CLKDIV3[PLLFLLFRAC]). */ #define FSL_FEATURE_SIM_DIVIDER_HAS_PLLFLLDIV (0) /* @brief Has LCDC clock divider (register bit field CLKDIV3[LCDCDIV] and CLKDIV3[LCDCFRAC]). */ #define FSL_FEATURE_SIM_DIVIDER_HAS_LCDCDIV (0) /* @brief Has trace clock divider (register bit field CLKDIV4[TRACEDIV] and CLKDIV4[TRACEFRAC]). */ #define FSL_FEATURE_SIM_DIVIDER_HAS_TRACEDIV (0) /* @brief Has NFC clock divider (register bit field CLKDIV4[NFCDIV] and CLKDIV4[NFCFRAC]). */ #define FSL_FEATURE_SIM_DIVIDER_HAS_NFCDIV (0) /* @brief Has Kinetis family ID (register bit field SDID[FAMILYID]). */ #define FSL_FEATURE_SIM_SDID_HAS_FAMILYID (0) /* @brief Has Kinetis family ID (register bit field SDID[FAMID]). */ #define FSL_FEATURE_SIM_SDID_HAS_FAMID (1) /* @brief Has Kinetis sub-family ID (register bit field SDID[SUBFAMID]). */ #define FSL_FEATURE_SIM_SDID_HAS_SUBFAMID (1) /* @brief Has Kinetis series ID (register bit field SDID[SERIESID]). */ #define FSL_FEATURE_SIM_SDID_HAS_SERIESID (1) /* @brief Has device die ID (register bit field SDID[DIEID]). */ #define FSL_FEATURE_SIM_SDID_HAS_DIEID (1) /* @brief Has system SRAM size specifier (register bit field SDID[SRAMSIZE]). */ #define FSL_FEATURE_SIM_SDID_HAS_SRAMSIZE (1) /* @brief Has flash mode (register bit FCFG1[FLASHDOZE]). */ #define FSL_FEATURE_SIM_FCFG_HAS_FLASHDOZE (1) /* @brief Has flash disable (register bit FCFG1[FLASHDIS]). */ #define FSL_FEATURE_SIM_FCFG_HAS_FLASHDIS (1) /* @brief Has FTFE disable (register bit FCFG1[FTFDIS]). */ #define FSL_FEATURE_SIM_FCFG_HAS_FTFDIS (0) /* @brief Has FlexNVM size specifier (register bit field FCFG1[NVMSIZE]). */ #define FSL_FEATURE_SIM_FCFG_HAS_NVMSIZE (0) /* @brief Has EEPROM size specifier (register bit field FCFG1[EESIZE]). */ #define FSL_FEATURE_SIM_FCFG_HAS_EESIZE (0) /* @brief Has FlexNVM partition (register bit field FCFG1[DEPART]). */ #define FSL_FEATURE_SIM_FCFG_HAS_DEPART (0) /* @brief Maximum flash address block 0 address specifier (register bit field FCFG2[MAXADDR0]). */ #define FSL_FEATURE_SIM_FCFG_HAS_MAXADDR0 (1) /* @brief Maximum flash address block 1 address specifier (register bit field FCFG2[MAXADDR1]). */ #define FSL_FEATURE_SIM_FCFG_HAS_MAXADDR1 (0) /* @brief Maximum flash address block 0 or 1 address specifier (register bit field FCFG2[MAXADDR01]). */ #define FSL_FEATURE_SIM_FCFG_HAS_MAXADDR01 (0) /* @brief Maximum flash address block 2 or 3 address specifier (register bit field FCFG2[MAXADDR23]). */ #define FSL_FEATURE_SIM_FCFG_HAS_MAXADDR23 (0) /* @brief Has program flash availability specifier (register bit FCFG2[PFLSH]). */ #define FSL_FEATURE_SIM_FCFG_HAS_PFLSH (0) /* @brief Has program flash swapping (register bit FCFG2[SWAPPFLSH]). */ #define FSL_FEATURE_SIM_FCFG_HAS_PFLSH_SWAP (0) /* @brief Has miscellanious control register (register MCR). */ #define FSL_FEATURE_SIM_HAS_MISC_CONTROLS (0) /* @brief Has COP watchdog (registers COPC and SRVCOP). */ #define FSL_FEATURE_SIM_HAS_COP_WATCHDOG (1) /* @brief Has COP watchdog stop (register bits COPC[COPSTPEN], COPC[COPDBGEN] and COPC[COPCLKSEL]). */ #define FSL_FEATURE_SIM_HAS_COP_STOP (0) #elif defined(CPU_MKL13Z64VFM4) || defined(CPU_MKL13Z128VFM4) || defined(CPU_MKL13Z256VFM4) || defined(CPU_MKL13Z64VFT4) || \ defined(CPU_MKL13Z128VFT4) || defined(CPU_MKL13Z256VFT4) || defined(CPU_MKL13Z64VLH4) || defined(CPU_MKL13Z128VLH4) || \ defined(CPU_MKL13Z256VLH4) || defined(CPU_MKL13Z64VMP4) || defined(CPU_MKL13Z128VMP4) || defined(CPU_MKL13Z256VMP4) || \ defined(CPU_MKL23Z64VFM4) || defined(CPU_MKL23Z128VFM4) || defined(CPU_MKL23Z256VFM4) || defined(CPU_MKL23Z64VFT4) || \ defined(CPU_MKL23Z128VFT4) || defined(CPU_MKL23Z256VFT4) || defined(CPU_MKL23Z64VLH4) || defined(CPU_MKL23Z128VLH4) || \ defined(CPU_MKL23Z256VLH4) || defined(CPU_MKL23Z64VMP4) || defined(CPU_MKL23Z128VMP4) || defined(CPU_MKL23Z256VMP4) || \ defined(CPU_MKL33Z128VLH4) || defined(CPU_MKL33Z256VLH4) || defined(CPU_MKL33Z128VMP4) || defined(CPU_MKL33Z256VMP4) || \ defined(CPU_MKL43Z64VLH4) || defined(CPU_MKL43Z128VLH4) || defined(CPU_MKL43Z256VLH4) || defined(CPU_MKL43Z64VMP4) || \ defined(CPU_MKL43Z128VMP4) || defined(CPU_MKL43Z256VMP4) /* @brief Has USB FS divider. */ #define FSL_FEATURE_SIM_USBFS_USE_SPECIAL_DIVIDER (0) /* @brief Is PLL clock divided by 2 before MCG PLL/FLL clock selection. */ #define FSL_FEATURE_SIM_PLLCLK_USE_SPECIAL_DIVIDER (0) /* @brief Has RAM size specification (register bit field SOPT1[RAMSIZE]). */ #define FSL_FEATURE_SIM_OPT_HAS_RAMSIZE (0) /* @brief Has 32k oscillator clock output (register bit SOPT1[OSC32KOUT]). */ #define FSL_FEATURE_SIM_OPT_HAS_OSC32K_OUT (1) /* @brief Has 32k oscillator clock selection (register bit field SOPT1[OSC32KSEL]). */ #define FSL_FEATURE_SIM_OPT_HAS_OSC32K_SELECTION (1) /* @brief 32k oscillator clock selection width (width of register bit field SOPT1[OSC32KSEL]). */ #define FSL_FEATURE_SIM_OPT_OSC32K_SELECTION_WIDTH (2) /* @brief Has RTC clock output selection (register bit SOPT2[RTCCLKOUTSEL]). */ #define FSL_FEATURE_SIM_OPT_HAS_RTC_CLOCK_OUT_SELECTION (1) /* @brief Has USB voltage regulator (register bits SOPT1[USBVSTBY], SOPT1[USBSSTBY], SOPT1[USBREGEN], SOPT1CFG[URWE], SOPT1CFG[UVSWE], SOPT1CFG[USSWE]). */ #define FSL_FEATURE_SIM_OPT_HAS_USB_VOLTAGE_REGULATOR (1) /* @brief USB has integrated PHY (register bits USBPHYCTL[USBVREGSEL], USBPHYCTL[USBVREGPD], USBPHYCTL[USB3VOUTTRG], USBPHYCTL[USBDISILIM], SOPT2[USBSLSRC], SOPT2[USBREGEN]). */ #define FSL_FEATURE_SIM_OPT_HAS_USB_PHY (0) /* @brief Has PTD7 pad drive strength control (register bit SOPT2[PTD7PAD]). */ #define FSL_FEATURE_SIM_OPT_HAS_PTD7PAD (0) /* @brief Has FlexBus security level selection (register bit SOPT2[FBSL]). */ #define FSL_FEATURE_SIM_OPT_HAS_FBSL (0) /* @brief Has number of FlexBus hold cycle before FlexBus can release bus (register bit SOPT6[PCR]). */ #define FSL_FEATURE_SIM_OPT_HAS_PCR (0) /* @brief Has number of NFC hold cycle in case of FlexBus request (register bit SOPT6[MCC]). */ #define FSL_FEATURE_SIM_OPT_HAS_MCC (0) /* @brief Has UART open drain enable (register bits UARTnODE, where n is a number, in register SOPT5). */ #define FSL_FEATURE_SIM_OPT_HAS_ODE (1) /* @brief Number of UART modules (number of register bits UARTn, where n is a number, in register SCGC4). */ #define FSL_FEATURE_SIM_OPT_UART_COUNT (1) /* @brief Has LPUART0 open drain enable (register bit SOPT5[LPUART0ODE]). */ #define FSL_FEATURE_SIM_OPT_HAS_LPUART0_ODE (1) /* @brief Has LPUART1 open drain enable (register bit SOPT5[LPUART1ODE]). */ #define FSL_FEATURE_SIM_OPT_HAS_LPUART1_ODE (1) /* @brief Has CMT/UART pad drive strength control (register bit SOPT2[CMTUARTPAD]). */ #define FSL_FEATURE_SIM_OPT_HAS_CMTUARTPAD (0) /* @brief Has LPUART0 transmit data source selection (register bit SOPT5[LPUART0TXSRC]). */ #define FSL_FEATURE_SIM_OPT_HAS_LPUART0_TX_SRC (1) /* @brief Has LPUART0 receive data source selection (register bit SOPT5[LPUART0RXSRC]). */ #define FSL_FEATURE_SIM_OPT_HAS_LPUART0_RX_SRC (1) /* @brief Has LPUART1 transmit data source selection (register bit SOPT5[LPUART1TXSRC]). */ #define FSL_FEATURE_SIM_OPT_HAS_LPUART1_TX_SRC (1) /* @brief Has LPUART1 receive data source selection (register bit SOPT5[LPUART1RXSRC]). */ #define FSL_FEATURE_SIM_OPT_HAS_LPUART1_RX_SRC (1) /* @brief Has UART0 transmit data source selection (register bit SOPT5[UART0TXSRC]). */ #define FSL_FEATURE_SIM_OPT_HAS_UART0_TX_SRC (0) /* @brief UART0 transmit data source selection width (width of register bit SOPT5[UART0TXSRC]). */ #define FSL_FEATURE_SIM_OPT_UART0_TX_SRC_WIDTH (0) /* @brief Has UART0 receive data source selection (register bit SOPT5[UART0RXSRC]). */ #define FSL_FEATURE_SIM_OPT_HAS_UART0_RX_SRC (0) /* @brief UART0 receive data source selection width (width of register bit SOPT5[UART0RXSRC]). */ #define FSL_FEATURE_SIM_OPT_UART0_RX_SRC_WIDTH (0) /* @brief Has UART1 transmit data source selection (register bit SOPT5[UART1TXSRC]). */ #define FSL_FEATURE_SIM_OPT_HAS_UART1_TX_SRC (0) /* @brief Has UART1 receive data source selection (register bit SOPT5[UART1RXSRC]). */ #define FSL_FEATURE_SIM_OPT_HAS_UART1_RX_SRC (0) /* @brief UART1 receive data source selection width (width of register bit SOPT5[UART1RXSRC]). */ #define FSL_FEATURE_SIM_OPT_UART1_RX_SRC_WIDTH (0) /* @brief Has FTM module(s) configuration. */ #define FSL_FEATURE_SIM_OPT_HAS_FTM (0) /* @brief Number of FTM modules. */ #define FSL_FEATURE_SIM_OPT_FTM_COUNT (0) /* @brief Number of FTM triggers with selectable source. */ #define FSL_FEATURE_SIM_OPT_FTM_TRIGGER_COUNT (0) /* @brief Has FTM0 triggers source selection (register bits SOPT4[FTM0TRGnSRC], where n is a number). */ #define FSL_FEATURE_SIM_OPT_HAS_FTM0_TRIGGER (0) /* @brief Has FTM3 triggers source selection (register bits SOPT4[FTM3TRGnSRC], where n is a number). */ #define FSL_FEATURE_SIM_OPT_HAS_FTM3_TRIGGER (0) /* @brief Has FTM1 channel 0 input capture source selection (register bit SOPT4[FTM1CH0SRC]). */ #define FSL_FEATURE_SIM_OPT_HAS_FTM1_CHANNELS (0) /* @brief Has FTM2 channel 0 input capture source selection (register bit SOPT4[FTM2CH0SRC]). */ #define FSL_FEATURE_SIM_OPT_HAS_FTM2_CHANNELS (0) /* @brief Has FTM3 channel 0 input capture source selection (register bit SOPT4[FTM3CH0SRC]). */ #define FSL_FEATURE_SIM_OPT_HAS_FTM3_CHANNELS (0) /* @brief Has FTM2 channel 1 input capture source selection (register bit SOPT4[FTM2CH1SRC]). */ #define FSL_FEATURE_SIM_OPT_HAS_FTM2_CHANNEL1 (0) /* @brief Number of configurable FTM0 fault detection input (number of register bits SOPT4[FTM0FLTn], where n is a number starting from zero). */ #define FSL_FEATURE_SIM_OPT_FTM0_FAULT_COUNT (0) /* @brief Number of configurable FTM1 fault detection input (number of register bits SOPT4[FTM1FLTn], where n is a number starting from zero). */ #define FSL_FEATURE_SIM_OPT_FTM1_FAULT_COUNT (0) /* @brief Number of configurable FTM2 fault detection input (number of register bits SOPT4[FTM2FLTn], where n is a number starting from zero). */ #define FSL_FEATURE_SIM_OPT_FTM2_FAULT_COUNT (0) /* @brief Number of configurable FTM3 fault detection input (number of register bits SOPT4[FTM3FLTn], where n is a number starting from zero). */ #define FSL_FEATURE_SIM_OPT_FTM3_FAULT_COUNT (0) /* @brief Has FTM hardware trigger 0 software synchronization (register bit SOPT8[FTMnSYNCBIT], where n is a module instance index). */ #define FSL_FEATURE_SIM_OPT_HAS_FTM_TRIGGER_SYNC (0) /* @brief Has FTM channels output source selection (register bit SOPT8[FTMxOCHnSRC], where x is a module instance index and n is a channel index). */ #define FSL_FEATURE_SIM_OPT_HAS_FTM_CHANNELS_OUTPUT_SRC (0) /* @brief Has TPM module(s) configuration. */ #define FSL_FEATURE_SIM_OPT_HAS_TPM (1) /* @brief The highest TPM module index. */ #define FSL_FEATURE_SIM_OPT_MAX_TPM_INDEX (2) /* @brief Has TPM module with index 0. */ #define FSL_FEATURE_SIM_OPT_HAS_TPM0 (1) /* @brief Is TPM channels configuration in the SOPT4 (not SOPT9) register (register bits TPMnCH0SRC, TPMnCLKSEL, where n is a module instance index). */ #define FSL_FEATURE_SIM_OPT_HAS_TPM_CHANNELS_CONFIG_IN_SOPT4_REG (0) /* @brief Has TPM1 channel 0 input capture source selection (register bit field SOPT4[TPM1CH0SRC] or SOPT9[TPM1CH0SRC]). */ #define FSL_FEATURE_SIM_OPT_HAS_TPM1_CH0_SRC_SELECTION (1) /* @brief TPM1 channel 0 input capture source selection width (width of register bit field SOPT4[TPM1CH0SRC] or SOPT9[TPM1CH0SRC]). */ #define FSL_FEATURE_SIM_OPT_TPM1_CH0_SRC_SELECTION_WIDTH (2) /* @brief Has TPM2 channel 0 input capture source selection (register bit field SOPT4[TPM2CH0SRC]). */ #define FSL_FEATURE_SIM_OPT_HAS_TPM2_CH0_SRC_SELECTION (1) /* @brief Has TPM2 clock selection (register bit field SOPT4[TPM2CLKSEL]). */ #define FSL_FEATURE_SIM_OPT_HAS_TPM2_CLK_SEL (1) /* @brief Has PLL/FLL clock selection (register bit field SOPT2[PLLFLLSEL]). */ #define FSL_FEATURE_SIM_OPT_HAS_PLL_FLL_SELECTION (0) /* @brief PLL/FLL clock selection width (width of register bit field SOPT2[PLLFLLSEL]). */ #define FSL_FEATURE_SIM_OPT_PLL_FLL_SELECTION_WIDTH (0) /* @brief Has NFC clock source selection (register bit SOPT2[NFCSRC]). */ #define FSL_FEATURE_SIM_OPT_HAS_NFCSRC (0) /* @brief Has eSDHC clock source selection (register bit SOPT2[ESDHCSRC]). */ #define FSL_FEATURE_SIM_OPT_HAS_ESDHCSRC (0) /* @brief Has SDHC clock source selection (register bit SOPT2[SDHCSRC]). */ #define FSL_FEATURE_SIM_OPT_HAS_SDHCSRC (0) /* @brief Has LCDC clock source selection (register bits SOPT2[LCDCSRC], SOPT2[LCDC_CLKSEL]). */ #define FSL_FEATURE_SIM_OPT_HAS_LCDCSRC (0) /* @brief Has ENET timestamp clock source selection (register bit SOPT2[TIMESRC]). */ #define FSL_FEATURE_SIM_OPT_HAS_TIMESRC (0) /* @brief Has ENET RMII clock source selection (register bit SOPT2[RMIISRC]). */ #define FSL_FEATURE_SIM_OPT_HAS_RMIISRC (0) /* @brief Has USB clock source selection (register bit SOPT2[USBSRC]). */ #define FSL_FEATURE_SIM_OPT_HAS_USBSRC (1) /* @brief Has USB FS clock source selection (register bit SOPT2[USBFSRC]). */ #define FSL_FEATURE_SIM_OPT_HAS_USBFSRC (0) /* @brief Has USB HS clock source selection (register bit SOPT2[USBHSRC]). */ #define FSL_FEATURE_SIM_OPT_HAS_USBHSRC (0) /* @brief Has LPUART clock source selection (register bit SOPT2[LPUARTSRC]). */ #define FSL_FEATURE_SIM_OPT_HAS_LPUARTSRC (0) /* @brief Has LPUART0 clock source selection (register bit SOPT2[LPUART0SRC]). */ #define FSL_FEATURE_SIM_OPT_HAS_LPUART0SRC (1) /* @brief Has LPUART1 clock source selection (register bit SOPT2[LPUART1SRC]). */ #define FSL_FEATURE_SIM_OPT_HAS_LPUART1SRC (1) /* @brief Has FLEXIOSRC clock source selection (register bit SOPT2[FLEXIOSRC]). */ #define FSL_FEATURE_SIM_OPT_HAS_FLEXIOSRC (1) /* @brief Has UART0 clock source selection (register bit SOPT2[UART0SRC]). */ #define FSL_FEATURE_SIM_OPT_HAS_UART0SRC (0) /* @brief Has TPM clock source selection (register bit SOPT2[TPMSRC]). */ #define FSL_FEATURE_SIM_OPT_HAS_TPMSRC (1) /* @brief Has debug trace clock selection (register bit SOPT2[TRACECLKSEL]). */ #define FSL_FEATURE_SIM_OPT_HAS_TRACE_CLKSEL (0) /* @brief Number of ADC modules (register bits SOPT7[ADCnTRGSEL], SOPT7[ADCnPRETRGSEL], SOPT7[ADCnALTTRGSEL], where n is a module instance index). */ #define FSL_FEATURE_SIM_OPT_ADC_COUNT (1) /* @brief Has clock 2 output divider (register bit field CLKDIV1[OUTDIV2]). */ #define FSL_FEATURE_SIM_DIVIDER_HAS_OUTDIV2 (0) /* @brief Has clock 3 output divider (register bit field CLKDIV1[OUTDIV3]). */ #define FSL_FEATURE_SIM_DIVIDER_HAS_OUTDIV3 (0) /* @brief Has clock 4 output divider (register bit field CLKDIV1[OUTDIV4]). */ #define FSL_FEATURE_SIM_DIVIDER_HAS_OUTDIV4 (1) /* @brief Clock 4 output divider width (width of register bit field CLKDIV1[OUTDIV4]). */ #define FSL_FEATURE_SIM_DIVIDER_OUTDIV4_WIDTH (3) /* @brief Has USB clock divider (register bit field CLKDIV2[USBDIV] and CLKDIV2[USBFRAC]). */ #define FSL_FEATURE_SIM_DIVIDER_HAS_USBDIV (0) /* @brief Has USB FS clock divider (register bit field CLKDIV2[USBFSDIV] and CLKDIV2[USBFSFRAC]). */ #define FSL_FEATURE_SIM_DIVIDER_HAS_USBFSDIV (0) /* @brief Has USB HS clock divider (register bit field CLKDIV2[USBHSDIV] and CLKDIV2[USBHSFRAC]). */ #define FSL_FEATURE_SIM_DIVIDER_HAS_USBHSDIV (0) /* @brief Has PLL/FLL clock divider (register bit field CLKDIV3[PLLFLLDIV] and CLKDIV3[PLLFLLFRAC]). */ #define FSL_FEATURE_SIM_DIVIDER_HAS_PLLFLLDIV (0) /* @brief Has LCDC clock divider (register bit field CLKDIV3[LCDCDIV] and CLKDIV3[LCDCFRAC]). */ #define FSL_FEATURE_SIM_DIVIDER_HAS_LCDCDIV (0) /* @brief Has trace clock divider (register bit field CLKDIV4[TRACEDIV] and CLKDIV4[TRACEFRAC]). */ #define FSL_FEATURE_SIM_DIVIDER_HAS_TRACEDIV (0) /* @brief Has NFC clock divider (register bit field CLKDIV4[NFCDIV] and CLKDIV4[NFCFRAC]). */ #define FSL_FEATURE_SIM_DIVIDER_HAS_NFCDIV (0) /* @brief Has Kinetis family ID (register bit field SDID[FAMILYID]). */ #define FSL_FEATURE_SIM_SDID_HAS_FAMILYID (0) /* @brief Has Kinetis family ID (register bit field SDID[FAMID]). */ #define FSL_FEATURE_SIM_SDID_HAS_FAMID (1) /* @brief Has Kinetis sub-family ID (register bit field SDID[SUBFAMID]). */ #define FSL_FEATURE_SIM_SDID_HAS_SUBFAMID (1) /* @brief Has Kinetis series ID (register bit field SDID[SERIESID]). */ #define FSL_FEATURE_SIM_SDID_HAS_SERIESID (1) /* @brief Has device die ID (register bit field SDID[DIEID]). */ #define FSL_FEATURE_SIM_SDID_HAS_DIEID (1) /* @brief Has system SRAM size specifier (register bit field SDID[SRAMSIZE]). */ #define FSL_FEATURE_SIM_SDID_HAS_SRAMSIZE (1) /* @brief Has flash mode (register bit FCFG1[FLASHDOZE]). */ #define FSL_FEATURE_SIM_FCFG_HAS_FLASHDOZE (1) /* @brief Has flash disable (register bit FCFG1[FLASHDIS]). */ #define FSL_FEATURE_SIM_FCFG_HAS_FLASHDIS (1) /* @brief Has FTFE disable (register bit FCFG1[FTFDIS]). */ #define FSL_FEATURE_SIM_FCFG_HAS_FTFDIS (0) /* @brief Has FlexNVM size specifier (register bit field FCFG1[NVMSIZE]). */ #define FSL_FEATURE_SIM_FCFG_HAS_NVMSIZE (0) /* @brief Has EEPROM size specifier (register bit field FCFG1[EESIZE]). */ #define FSL_FEATURE_SIM_FCFG_HAS_EESIZE (0) /* @brief Has FlexNVM partition (register bit field FCFG1[DEPART]). */ #define FSL_FEATURE_SIM_FCFG_HAS_DEPART (0) /* @brief Maximum flash address block 0 address specifier (register bit field FCFG2[MAXADDR0]). */ #define FSL_FEATURE_SIM_FCFG_HAS_MAXADDR0 (1) /* @brief Maximum flash address block 1 address specifier (register bit field FCFG2[MAXADDR1]). */ #define FSL_FEATURE_SIM_FCFG_HAS_MAXADDR1 (1) /* @brief Maximum flash address block 0 or 1 address specifier (register bit field FCFG2[MAXADDR01]). */ #define FSL_FEATURE_SIM_FCFG_HAS_MAXADDR01 (0) /* @brief Maximum flash address block 2 or 3 address specifier (register bit field FCFG2[MAXADDR23]). */ #define FSL_FEATURE_SIM_FCFG_HAS_MAXADDR23 (0) /* @brief Has program flash availability specifier (register bit FCFG2[PFLSH]). */ #define FSL_FEATURE_SIM_FCFG_HAS_PFLSH (0) /* @brief Has program flash swapping (register bit FCFG2[SWAPPFLSH]). */ #define FSL_FEATURE_SIM_FCFG_HAS_PFLSH_SWAP (0) /* @brief Has miscellanious control register (register MCR). */ #define FSL_FEATURE_SIM_HAS_MISC_CONTROLS (0) /* @brief Has COP watchdog (registers COPC and SRVCOP). */ #define FSL_FEATURE_SIM_HAS_COP_WATCHDOG (1) /* @brief Has COP watchdog stop (register bits COPC[COPSTPEN], COPC[COPDBGEN] and COPC[COPCLKSEL]). */ #define FSL_FEATURE_SIM_HAS_COP_STOP (1) #elif defined(CPU_MKL25Z32VFM4) || defined(CPU_MKL25Z64VFM4) || defined(CPU_MKL25Z128VFM4) || defined(CPU_MKL25Z32VFT4) || \ defined(CPU_MKL25Z64VFT4) || defined(CPU_MKL25Z128VFT4) || defined(CPU_MKL25Z32VLH4) || defined(CPU_MKL25Z64VLH4) || \ defined(CPU_MKL25Z128VLH4) || defined(CPU_MKL25Z32VLK4) || defined(CPU_MKL25Z64VLK4) || defined(CPU_MKL25Z128VLK4) /* @brief Has USB FS divider. */ #define FSL_FEATURE_SIM_USBFS_USE_SPECIAL_DIVIDER (0) /* @brief Is PLL clock divided by 2 before MCG PLL/FLL clock selection. */ #define FSL_FEATURE_SIM_PLLCLK_USE_SPECIAL_DIVIDER (1) /* @brief Has RAM size specification (register bit field SOPT1[RAMSIZE]). */ #define FSL_FEATURE_SIM_OPT_HAS_RAMSIZE (0) /* @brief Has 32k oscillator clock output (register bit SOPT1[OSC32KOUT]). */ #define FSL_FEATURE_SIM_OPT_HAS_OSC32K_OUT (0) /* @brief Has 32k oscillator clock selection (register bit field SOPT1[OSC32KSEL]). */ #define FSL_FEATURE_SIM_OPT_HAS_OSC32K_SELECTION (1) /* @brief 32k oscillator clock selection width (width of register bit field SOPT1[OSC32KSEL]). */ #define FSL_FEATURE_SIM_OPT_OSC32K_SELECTION_WIDTH (2) /* @brief Has RTC clock output selection (register bit SOPT2[RTCCLKOUTSEL]). */ #define FSL_FEATURE_SIM_OPT_HAS_RTC_CLOCK_OUT_SELECTION (1) /* @brief Has USB voltage regulator (register bits SOPT1[USBVSTBY], SOPT1[USBSSTBY], SOPT1[USBREGEN], SOPT1CFG[URWE], SOPT1CFG[UVSWE], SOPT1CFG[USSWE]). */ #define FSL_FEATURE_SIM_OPT_HAS_USB_VOLTAGE_REGULATOR (1) /* @brief USB has integrated PHY (register bits USBPHYCTL[USBVREGSEL], USBPHYCTL[USBVREGPD], USBPHYCTL[USB3VOUTTRG], USBPHYCTL[USBDISILIM], SOPT2[USBSLSRC], SOPT2[USBREGEN]). */ #define FSL_FEATURE_SIM_OPT_HAS_USB_PHY (0) /* @brief Has PTD7 pad drive strength control (register bit SOPT2[PTD7PAD]). */ #define FSL_FEATURE_SIM_OPT_HAS_PTD7PAD (0) /* @brief Has FlexBus security level selection (register bit SOPT2[FBSL]). */ #define FSL_FEATURE_SIM_OPT_HAS_FBSL (0) /* @brief Has number of FlexBus hold cycle before FlexBus can release bus (register bit SOPT6[PCR]). */ #define FSL_FEATURE_SIM_OPT_HAS_PCR (0) /* @brief Has number of NFC hold cycle in case of FlexBus request (register bit SOPT6[MCC]). */ #define FSL_FEATURE_SIM_OPT_HAS_MCC (0) /* @brief Has UART open drain enable (register bits UARTnODE, where n is a number, in register SOPT5). */ #define FSL_FEATURE_SIM_OPT_HAS_ODE (1) /* @brief Number of UART modules (number of register bits UARTn, where n is a number, in register SCGC4). */ #define FSL_FEATURE_SIM_OPT_UART_COUNT (3) /* @brief Has LPUART0 open drain enable (register bit SOPT5[LPUART0ODE]). */ #define FSL_FEATURE_SIM_OPT_HAS_LPUART0_ODE (0) /* @brief Has LPUART1 open drain enable (register bit SOPT5[LPUART1ODE]). */ #define FSL_FEATURE_SIM_OPT_HAS_LPUART1_ODE (0) /* @brief Has CMT/UART pad drive strength control (register bit SOPT2[CMTUARTPAD]). */ #define FSL_FEATURE_SIM_OPT_HAS_CMTUARTPAD (0) /* @brief Has LPUART0 transmit data source selection (register bit SOPT5[LPUART0TXSRC]). */ #define FSL_FEATURE_SIM_OPT_HAS_LPUART0_TX_SRC (0) /* @brief Has LPUART0 receive data source selection (register bit SOPT5[LPUART0RXSRC]). */ #define FSL_FEATURE_SIM_OPT_HAS_LPUART0_RX_SRC (0) /* @brief Has LPUART1 transmit data source selection (register bit SOPT5[LPUART1TXSRC]). */ #define FSL_FEATURE_SIM_OPT_HAS_LPUART1_TX_SRC (0) /* @brief Has LPUART1 receive data source selection (register bit SOPT5[LPUART1RXSRC]). */ #define FSL_FEATURE_SIM_OPT_HAS_LPUART1_RX_SRC (0) /* @brief Has UART0 transmit data source selection (register bit SOPT5[UART0TXSRC]). */ #define FSL_FEATURE_SIM_OPT_HAS_UART0_TX_SRC (1) /* @brief UART0 transmit data source selection width (width of register bit SOPT5[UART0TXSRC]). */ #define FSL_FEATURE_SIM_OPT_UART0_TX_SRC_WIDTH (2) /* @brief Has UART0 receive data source selection (register bit SOPT5[UART0RXSRC]). */ #define FSL_FEATURE_SIM_OPT_HAS_UART0_RX_SRC (1) /* @brief UART0 receive data source selection width (width of register bit SOPT5[UART0RXSRC]). */ #define FSL_FEATURE_SIM_OPT_UART0_RX_SRC_WIDTH (1) /* @brief Has UART1 transmit data source selection (register bit SOPT5[UART1TXSRC]). */ #define FSL_FEATURE_SIM_OPT_HAS_UART1_TX_SRC (1) /* @brief Has UART1 receive data source selection (register bit SOPT5[UART1RXSRC]). */ #define FSL_FEATURE_SIM_OPT_HAS_UART1_RX_SRC (1) /* @brief UART1 receive data source selection width (width of register bit SOPT5[UART1RXSRC]). */ #define FSL_FEATURE_SIM_OPT_UART1_RX_SRC_WIDTH (1) /* @brief Has FTM module(s) configuration. */ #define FSL_FEATURE_SIM_OPT_HAS_FTM (0) /* @brief Number of FTM modules. */ #define FSL_FEATURE_SIM_OPT_FTM_COUNT (0) /* @brief Number of FTM triggers with selectable source. */ #define FSL_FEATURE_SIM_OPT_FTM_TRIGGER_COUNT (0) /* @brief Has FTM0 triggers source selection (register bits SOPT4[FTM0TRGnSRC], where n is a number). */ #define FSL_FEATURE_SIM_OPT_HAS_FTM0_TRIGGER (0) /* @brief Has FTM3 triggers source selection (register bits SOPT4[FTM3TRGnSRC], where n is a number). */ #define FSL_FEATURE_SIM_OPT_HAS_FTM3_TRIGGER (0) /* @brief Has FTM1 channel 0 input capture source selection (register bit SOPT4[FTM1CH0SRC]). */ #define FSL_FEATURE_SIM_OPT_HAS_FTM1_CHANNELS (0) /* @brief Has FTM2 channel 0 input capture source selection (register bit SOPT4[FTM2CH0SRC]). */ #define FSL_FEATURE_SIM_OPT_HAS_FTM2_CHANNELS (0) /* @brief Has FTM3 channel 0 input capture source selection (register bit SOPT4[FTM3CH0SRC]). */ #define FSL_FEATURE_SIM_OPT_HAS_FTM3_CHANNELS (0) /* @brief Has FTM2 channel 1 input capture source selection (register bit SOPT4[FTM2CH1SRC]). */ #define FSL_FEATURE_SIM_OPT_HAS_FTM2_CHANNEL1 (0) /* @brief Number of configurable FTM0 fault detection input (number of register bits SOPT4[FTM0FLTn], where n is a number starting from zero). */ #define FSL_FEATURE_SIM_OPT_FTM0_FAULT_COUNT (0) /* @brief Number of configurable FTM1 fault detection input (number of register bits SOPT4[FTM1FLTn], where n is a number starting from zero). */ #define FSL_FEATURE_SIM_OPT_FTM1_FAULT_COUNT (0) /* @brief Number of configurable FTM2 fault detection input (number of register bits SOPT4[FTM2FLTn], where n is a number starting from zero). */ #define FSL_FEATURE_SIM_OPT_FTM2_FAULT_COUNT (0) /* @brief Number of configurable FTM3 fault detection input (number of register bits SOPT4[FTM3FLTn], where n is a number starting from zero). */ #define FSL_FEATURE_SIM_OPT_FTM3_FAULT_COUNT (0) /* @brief Has FTM hardware trigger 0 software synchronization (register bit SOPT8[FTMnSYNCBIT], where n is a module instance index). */ #define FSL_FEATURE_SIM_OPT_HAS_FTM_TRIGGER_SYNC (0) /* @brief Has FTM channels output source selection (register bit SOPT8[FTMxOCHnSRC], where x is a module instance index and n is a channel index). */ #define FSL_FEATURE_SIM_OPT_HAS_FTM_CHANNELS_OUTPUT_SRC (0) /* @brief Has TPM module(s) configuration. */ #define FSL_FEATURE_SIM_OPT_HAS_TPM (1) /* @brief The highest TPM module index. */ #define FSL_FEATURE_SIM_OPT_MAX_TPM_INDEX (2) /* @brief Has TPM module with index 0. */ #define FSL_FEATURE_SIM_OPT_HAS_TPM0 (1) /* @brief Is TPM channels configuration in the SOPT4 (not SOPT9) register (register bits TPMnCH0SRC, TPMnCLKSEL, where n is a module instance index). */ #define FSL_FEATURE_SIM_OPT_HAS_TPM_CHANNELS_CONFIG_IN_SOPT4_REG (0) /* @brief Has TPM1 channel 0 input capture source selection (register bit field SOPT4[TPM1CH0SRC] or SOPT9[TPM1CH0SRC]). */ #define FSL_FEATURE_SIM_OPT_HAS_TPM1_CH0_SRC_SELECTION (1) /* @brief TPM1 channel 0 input capture source selection width (width of register bit field SOPT4[TPM1CH0SRC] or SOPT9[TPM1CH0SRC]). */ #define FSL_FEATURE_SIM_OPT_TPM1_CH0_SRC_SELECTION_WIDTH (1) /* @brief Has TPM2 channel 0 input capture source selection (register bit field SOPT4[TPM2CH0SRC]). */ #define FSL_FEATURE_SIM_OPT_HAS_TPM2_CH0_SRC_SELECTION (1) /* @brief Has TPM2 clock selection (register bit field SOPT4[TPM2CLKSEL]). */ #define FSL_FEATURE_SIM_OPT_HAS_TPM2_CLK_SEL (1) /* @brief Has PLL/FLL clock selection (register bit field SOPT2[PLLFLLSEL]). */ #define FSL_FEATURE_SIM_OPT_HAS_PLL_FLL_SELECTION (1) /* @brief PLL/FLL clock selection width (width of register bit field SOPT2[PLLFLLSEL]). */ #define FSL_FEATURE_SIM_OPT_PLL_FLL_SELECTION_WIDTH (1) /* @brief Has NFC clock source selection (register bit SOPT2[NFCSRC]). */ #define FSL_FEATURE_SIM_OPT_HAS_NFCSRC (0) /* @brief Has eSDHC clock source selection (register bit SOPT2[ESDHCSRC]). */ #define FSL_FEATURE_SIM_OPT_HAS_ESDHCSRC (0) /* @brief Has SDHC clock source selection (register bit SOPT2[SDHCSRC]). */ #define FSL_FEATURE_SIM_OPT_HAS_SDHCSRC (0) /* @brief Has LCDC clock source selection (register bits SOPT2[LCDCSRC], SOPT2[LCDC_CLKSEL]). */ #define FSL_FEATURE_SIM_OPT_HAS_LCDCSRC (0) /* @brief Has ENET timestamp clock source selection (register bit SOPT2[TIMESRC]). */ #define FSL_FEATURE_SIM_OPT_HAS_TIMESRC (0) /* @brief Has ENET RMII clock source selection (register bit SOPT2[RMIISRC]). */ #define FSL_FEATURE_SIM_OPT_HAS_RMIISRC (0) /* @brief Has USB clock source selection (register bit SOPT2[USBSRC]). */ #define FSL_FEATURE_SIM_OPT_HAS_USBSRC (1) /* @brief Has USB FS clock source selection (register bit SOPT2[USBFSRC]). */ #define FSL_FEATURE_SIM_OPT_HAS_USBFSRC (0) /* @brief Has USB HS clock source selection (register bit SOPT2[USBHSRC]). */ #define FSL_FEATURE_SIM_OPT_HAS_USBHSRC (0) /* @brief Has LPUART clock source selection (register bit SOPT2[LPUARTSRC]). */ #define FSL_FEATURE_SIM_OPT_HAS_LPUARTSRC (0) /* @brief Has LPUART0 clock source selection (register bit SOPT2[LPUART0SRC]). */ #define FSL_FEATURE_SIM_OPT_HAS_LPUART0SRC (0) /* @brief Has LPUART1 clock source selection (register bit SOPT2[LPUART1SRC]). */ #define FSL_FEATURE_SIM_OPT_HAS_LPUART1SRC (0) /* @brief Has FLEXIOSRC clock source selection (register bit SOPT2[FLEXIOSRC]). */ #define FSL_FEATURE_SIM_OPT_HAS_FLEXIOSRC (0) /* @brief Has UART0 clock source selection (register bit SOPT2[UART0SRC]). */ #define FSL_FEATURE_SIM_OPT_HAS_UART0SRC (1) /* @brief Has TPM clock source selection (register bit SOPT2[TPMSRC]). */ #define FSL_FEATURE_SIM_OPT_HAS_TPMSRC (1) /* @brief Has debug trace clock selection (register bit SOPT2[TRACECLKSEL]). */ #define FSL_FEATURE_SIM_OPT_HAS_TRACE_CLKSEL (0) /* @brief Number of ADC modules (register bits SOPT7[ADCnTRGSEL], SOPT7[ADCnPRETRGSEL], SOPT7[ADCnALTTRGSEL], where n is a module instance index). */ #define FSL_FEATURE_SIM_OPT_ADC_COUNT (1) /* @brief Has clock 2 output divider (register bit field CLKDIV1[OUTDIV2]). */ #define FSL_FEATURE_SIM_DIVIDER_HAS_OUTDIV2 (0) /* @brief Has clock 3 output divider (register bit field CLKDIV1[OUTDIV3]). */ #define FSL_FEATURE_SIM_DIVIDER_HAS_OUTDIV3 (0) /* @brief Has clock 4 output divider (register bit field CLKDIV1[OUTDIV4]). */ #define FSL_FEATURE_SIM_DIVIDER_HAS_OUTDIV4 (1) /* @brief Clock 4 output divider width (width of register bit field CLKDIV1[OUTDIV4]). */ #define FSL_FEATURE_SIM_DIVIDER_OUTDIV4_WIDTH (3) /* @brief Has USB clock divider (register bit field CLKDIV2[USBDIV] and CLKDIV2[USBFRAC]). */ #define FSL_FEATURE_SIM_DIVIDER_HAS_USBDIV (0) /* @brief Has USB FS clock divider (register bit field CLKDIV2[USBFSDIV] and CLKDIV2[USBFSFRAC]). */ #define FSL_FEATURE_SIM_DIVIDER_HAS_USBFSDIV (0) /* @brief Has USB HS clock divider (register bit field CLKDIV2[USBHSDIV] and CLKDIV2[USBHSFRAC]). */ #define FSL_FEATURE_SIM_DIVIDER_HAS_USBHSDIV (0) /* @brief Has PLL/FLL clock divider (register bit field CLKDIV3[PLLFLLDIV] and CLKDIV3[PLLFLLFRAC]). */ #define FSL_FEATURE_SIM_DIVIDER_HAS_PLLFLLDIV (0) /* @brief Has LCDC clock divider (register bit field CLKDIV3[LCDCDIV] and CLKDIV3[LCDCFRAC]). */ #define FSL_FEATURE_SIM_DIVIDER_HAS_LCDCDIV (0) /* @brief Has trace clock divider (register bit field CLKDIV4[TRACEDIV] and CLKDIV4[TRACEFRAC]). */ #define FSL_FEATURE_SIM_DIVIDER_HAS_TRACEDIV (0) /* @brief Has NFC clock divider (register bit field CLKDIV4[NFCDIV] and CLKDIV4[NFCFRAC]). */ #define FSL_FEATURE_SIM_DIVIDER_HAS_NFCDIV (0) /* @brief Has Kinetis family ID (register bit field SDID[FAMILYID]). */ #define FSL_FEATURE_SIM_SDID_HAS_FAMILYID (0) /* @brief Has Kinetis family ID (register bit field SDID[FAMID]). */ #define FSL_FEATURE_SIM_SDID_HAS_FAMID (1) /* @brief Has Kinetis sub-family ID (register bit field SDID[SUBFAMID]). */ #define FSL_FEATURE_SIM_SDID_HAS_SUBFAMID (1) /* @brief Has Kinetis series ID (register bit field SDID[SERIESID]). */ #define FSL_FEATURE_SIM_SDID_HAS_SERIESID (1) /* @brief Has device die ID (register bit field SDID[DIEID]). */ #define FSL_FEATURE_SIM_SDID_HAS_DIEID (1) /* @brief Has system SRAM size specifier (register bit field SDID[SRAMSIZE]). */ #define FSL_FEATURE_SIM_SDID_HAS_SRAMSIZE (1) /* @brief Has flash mode (register bit FCFG1[FLASHDOZE]). */ #define FSL_FEATURE_SIM_FCFG_HAS_FLASHDOZE (1) /* @brief Has flash disable (register bit FCFG1[FLASHDIS]). */ #define FSL_FEATURE_SIM_FCFG_HAS_FLASHDIS (1) /* @brief Has FTFE disable (register bit FCFG1[FTFDIS]). */ #define FSL_FEATURE_SIM_FCFG_HAS_FTFDIS (0) /* @brief Has FlexNVM size specifier (register bit field FCFG1[NVMSIZE]). */ #define FSL_FEATURE_SIM_FCFG_HAS_NVMSIZE (0) /* @brief Has EEPROM size specifier (register bit field FCFG1[EESIZE]). */ #define FSL_FEATURE_SIM_FCFG_HAS_EESIZE (0) /* @brief Has FlexNVM partition (register bit field FCFG1[DEPART]). */ #define FSL_FEATURE_SIM_FCFG_HAS_DEPART (0) /* @brief Maximum flash address block 0 address specifier (register bit field FCFG2[MAXADDR0]). */ #define FSL_FEATURE_SIM_FCFG_HAS_MAXADDR0 (1) /* @brief Maximum flash address block 1 address specifier (register bit field FCFG2[MAXADDR1]). */ #define FSL_FEATURE_SIM_FCFG_HAS_MAXADDR1 (0) /* @brief Maximum flash address block 0 or 1 address specifier (register bit field FCFG2[MAXADDR01]). */ #define FSL_FEATURE_SIM_FCFG_HAS_MAXADDR01 (0) /* @brief Maximum flash address block 2 or 3 address specifier (register bit field FCFG2[MAXADDR23]). */ #define FSL_FEATURE_SIM_FCFG_HAS_MAXADDR23 (0) /* @brief Has program flash availability specifier (register bit FCFG2[PFLSH]). */ #define FSL_FEATURE_SIM_FCFG_HAS_PFLSH (0) /* @brief Has program flash swapping (register bit FCFG2[SWAPPFLSH]). */ #define FSL_FEATURE_SIM_FCFG_HAS_PFLSH_SWAP (0) /* @brief Has miscellanious control register (register MCR). */ #define FSL_FEATURE_SIM_HAS_MISC_CONTROLS (0) /* @brief Has COP watchdog (registers COPC and SRVCOP). */ #define FSL_FEATURE_SIM_HAS_COP_WATCHDOG (1) /* @brief Has COP watchdog stop (register bits COPC[COPSTPEN], COPC[COPDBGEN] and COPC[COPCLKSEL]). */ #define FSL_FEATURE_SIM_HAS_COP_STOP (0) #elif defined(CPU_MKL26Z256VLK4) || defined(CPU_MKL26Z128VLL4) || defined(CPU_MKL26Z256VLL4) || defined(CPU_MKL26Z128VMC4) || \ defined(CPU_MKL26Z256VMC4) || defined(CPU_MKL46Z128VLH4) || defined(CPU_MKL46Z256VLH4) || defined(CPU_MKL46Z128VLL4) || \ defined(CPU_MKL46Z256VLL4) || defined(CPU_MKL46Z128VMC4) || defined(CPU_MKL46Z256VMC4) /* @brief Has USB FS divider. */ #define FSL_FEATURE_SIM_USBFS_USE_SPECIAL_DIVIDER (0) /* @brief Is PLL clock divided by 2 before MCG PLL/FLL clock selection. */ #define FSL_FEATURE_SIM_PLLCLK_USE_SPECIAL_DIVIDER (1) /* @brief Has RAM size specification (register bit field SOPT1[RAMSIZE]). */ #define FSL_FEATURE_SIM_OPT_HAS_RAMSIZE (0) /* @brief Has 32k oscillator clock output (register bit SOPT1[OSC32KOUT]). */ #define FSL_FEATURE_SIM_OPT_HAS_OSC32K_OUT (0) /* @brief Has 32k oscillator clock selection (register bit field SOPT1[OSC32KSEL]). */ #define FSL_FEATURE_SIM_OPT_HAS_OSC32K_SELECTION (1) /* @brief 32k oscillator clock selection width (width of register bit field SOPT1[OSC32KSEL]). */ #define FSL_FEATURE_SIM_OPT_OSC32K_SELECTION_WIDTH (2) /* @brief Has RTC clock output selection (register bit SOPT2[RTCCLKOUTSEL]). */ #define FSL_FEATURE_SIM_OPT_HAS_RTC_CLOCK_OUT_SELECTION (1) /* @brief Has USB voltage regulator (register bits SOPT1[USBVSTBY], SOPT1[USBSSTBY], SOPT1[USBREGEN], SOPT1CFG[URWE], SOPT1CFG[UVSWE], SOPT1CFG[USSWE]). */ #define FSL_FEATURE_SIM_OPT_HAS_USB_VOLTAGE_REGULATOR (1) /* @brief USB has integrated PHY (register bits USBPHYCTL[USBVREGSEL], USBPHYCTL[USBVREGPD], USBPHYCTL[USB3VOUTTRG], USBPHYCTL[USBDISILIM], SOPT2[USBSLSRC], SOPT2[USBREGEN]). */ #define FSL_FEATURE_SIM_OPT_HAS_USB_PHY (0) /* @brief Has PTD7 pad drive strength control (register bit SOPT2[PTD7PAD]). */ #define FSL_FEATURE_SIM_OPT_HAS_PTD7PAD (0) /* @brief Has FlexBus security level selection (register bit SOPT2[FBSL]). */ #define FSL_FEATURE_SIM_OPT_HAS_FBSL (0) /* @brief Has number of FlexBus hold cycle before FlexBus can release bus (register bit SOPT6[PCR]). */ #define FSL_FEATURE_SIM_OPT_HAS_PCR (0) /* @brief Has number of NFC hold cycle in case of FlexBus request (register bit SOPT6[MCC]). */ #define FSL_FEATURE_SIM_OPT_HAS_MCC (0) /* @brief Has UART open drain enable (register bits UARTnODE, where n is a number, in register SOPT5). */ #define FSL_FEATURE_SIM_OPT_HAS_ODE (1) /* @brief Number of UART modules (number of register bits UARTn, where n is a number, in register SCGC4). */ #define FSL_FEATURE_SIM_OPT_UART_COUNT (3) /* @brief Has LPUART0 open drain enable (register bit SOPT5[LPUART0ODE]). */ #define FSL_FEATURE_SIM_OPT_HAS_LPUART0_ODE (0) /* @brief Has LPUART1 open drain enable (register bit SOPT5[LPUART1ODE]). */ #define FSL_FEATURE_SIM_OPT_HAS_LPUART1_ODE (0) /* @brief Has CMT/UART pad drive strength control (register bit SOPT2[CMTUARTPAD]). */ #define FSL_FEATURE_SIM_OPT_HAS_CMTUARTPAD (0) /* @brief Has LPUART0 transmit data source selection (register bit SOPT5[LPUART0TXSRC]). */ #define FSL_FEATURE_SIM_OPT_HAS_LPUART0_TX_SRC (0) /* @brief Has LPUART0 receive data source selection (register bit SOPT5[LPUART0RXSRC]). */ #define FSL_FEATURE_SIM_OPT_HAS_LPUART0_RX_SRC (0) /* @brief Has LPUART1 transmit data source selection (register bit SOPT5[LPUART1TXSRC]). */ #define FSL_FEATURE_SIM_OPT_HAS_LPUART1_TX_SRC (0) /* @brief Has LPUART1 receive data source selection (register bit SOPT5[LPUART1RXSRC]). */ #define FSL_FEATURE_SIM_OPT_HAS_LPUART1_RX_SRC (0) /* @brief Has UART0 transmit data source selection (register bit SOPT5[UART0TXSRC]). */ #define FSL_FEATURE_SIM_OPT_HAS_UART0_TX_SRC (1) /* @brief UART0 transmit data source selection width (width of register bit SOPT5[UART0TXSRC]). */ #define FSL_FEATURE_SIM_OPT_UART0_TX_SRC_WIDTH (2) /* @brief Has UART0 receive data source selection (register bit SOPT5[UART0RXSRC]). */ #define FSL_FEATURE_SIM_OPT_HAS_UART0_RX_SRC (1) /* @brief UART0 receive data source selection width (width of register bit SOPT5[UART0RXSRC]). */ #define FSL_FEATURE_SIM_OPT_UART0_RX_SRC_WIDTH (1) /* @brief Has UART1 transmit data source selection (register bit SOPT5[UART1TXSRC]). */ #define FSL_FEATURE_SIM_OPT_HAS_UART1_TX_SRC (1) /* @brief Has UART1 receive data source selection (register bit SOPT5[UART1RXSRC]). */ #define FSL_FEATURE_SIM_OPT_HAS_UART1_RX_SRC (1) /* @brief UART1 receive data source selection width (width of register bit SOPT5[UART1RXSRC]). */ #define FSL_FEATURE_SIM_OPT_UART1_RX_SRC_WIDTH (1) /* @brief Has FTM module(s) configuration. */ #define FSL_FEATURE_SIM_OPT_HAS_FTM (0) /* @brief Number of FTM modules. */ #define FSL_FEATURE_SIM_OPT_FTM_COUNT (0) /* @brief Number of FTM triggers with selectable source. */ #define FSL_FEATURE_SIM_OPT_FTM_TRIGGER_COUNT (0) /* @brief Has FTM0 triggers source selection (register bits SOPT4[FTM0TRGnSRC], where n is a number). */ #define FSL_FEATURE_SIM_OPT_HAS_FTM0_TRIGGER (0) /* @brief Has FTM3 triggers source selection (register bits SOPT4[FTM3TRGnSRC], where n is a number). */ #define FSL_FEATURE_SIM_OPT_HAS_FTM3_TRIGGER (0) /* @brief Has FTM1 channel 0 input capture source selection (register bit SOPT4[FTM1CH0SRC]). */ #define FSL_FEATURE_SIM_OPT_HAS_FTM1_CHANNELS (0) /* @brief Has FTM2 channel 0 input capture source selection (register bit SOPT4[FTM2CH0SRC]). */ #define FSL_FEATURE_SIM_OPT_HAS_FTM2_CHANNELS (0) /* @brief Has FTM3 channel 0 input capture source selection (register bit SOPT4[FTM3CH0SRC]). */ #define FSL_FEATURE_SIM_OPT_HAS_FTM3_CHANNELS (0) /* @brief Has FTM2 channel 1 input capture source selection (register bit SOPT4[FTM2CH1SRC]). */ #define FSL_FEATURE_SIM_OPT_HAS_FTM2_CHANNEL1 (0) /* @brief Number of configurable FTM0 fault detection input (number of register bits SOPT4[FTM0FLTn], where n is a number starting from zero). */ #define FSL_FEATURE_SIM_OPT_FTM0_FAULT_COUNT (0) /* @brief Number of configurable FTM1 fault detection input (number of register bits SOPT4[FTM1FLTn], where n is a number starting from zero). */ #define FSL_FEATURE_SIM_OPT_FTM1_FAULT_COUNT (0) /* @brief Number of configurable FTM2 fault detection input (number of register bits SOPT4[FTM2FLTn], where n is a number starting from zero). */ #define FSL_FEATURE_SIM_OPT_FTM2_FAULT_COUNT (0) /* @brief Number of configurable FTM3 fault detection input (number of register bits SOPT4[FTM3FLTn], where n is a number starting from zero). */ #define FSL_FEATURE_SIM_OPT_FTM3_FAULT_COUNT (0) /* @brief Has FTM hardware trigger 0 software synchronization (register bit SOPT8[FTMnSYNCBIT], where n is a module instance index). */ #define FSL_FEATURE_SIM_OPT_HAS_FTM_TRIGGER_SYNC (0) /* @brief Has FTM channels output source selection (register bit SOPT8[FTMxOCHnSRC], where x is a module instance index and n is a channel index). */ #define FSL_FEATURE_SIM_OPT_HAS_FTM_CHANNELS_OUTPUT_SRC (0) /* @brief Has TPM module(s) configuration. */ #define FSL_FEATURE_SIM_OPT_HAS_TPM (1) /* @brief The highest TPM module index. */ #define FSL_FEATURE_SIM_OPT_MAX_TPM_INDEX (2) /* @brief Has TPM module with index 0. */ #define FSL_FEATURE_SIM_OPT_HAS_TPM0 (1) /* @brief Is TPM channels configuration in the SOPT4 (not SOPT9) register (register bits TPMnCH0SRC, TPMnCLKSEL, where n is a module instance index). */ #define FSL_FEATURE_SIM_OPT_HAS_TPM_CHANNELS_CONFIG_IN_SOPT4_REG (0) /* @brief Has TPM1 channel 0 input capture source selection (register bit field SOPT4[TPM1CH0SRC] or SOPT9[TPM1CH0SRC]). */ #define FSL_FEATURE_SIM_OPT_HAS_TPM1_CH0_SRC_SELECTION (1) /* @brief TPM1 channel 0 input capture source selection width (width of register bit field SOPT4[TPM1CH0SRC] or SOPT9[TPM1CH0SRC]). */ #define FSL_FEATURE_SIM_OPT_TPM1_CH0_SRC_SELECTION_WIDTH (2) /* @brief Has TPM2 channel 0 input capture source selection (register bit field SOPT4[TPM2CH0SRC]). */ #define FSL_FEATURE_SIM_OPT_HAS_TPM2_CH0_SRC_SELECTION (1) /* @brief Has TPM2 clock selection (register bit field SOPT4[TPM2CLKSEL]). */ #define FSL_FEATURE_SIM_OPT_HAS_TPM2_CLK_SEL (1) /* @brief Has PLL/FLL clock selection (register bit field SOPT2[PLLFLLSEL]). */ #define FSL_FEATURE_SIM_OPT_HAS_PLL_FLL_SELECTION (1) /* @brief PLL/FLL clock selection width (width of register bit field SOPT2[PLLFLLSEL]). */ #define FSL_FEATURE_SIM_OPT_PLL_FLL_SELECTION_WIDTH (1) /* @brief Has NFC clock source selection (register bit SOPT2[NFCSRC]). */ #define FSL_FEATURE_SIM_OPT_HAS_NFCSRC (0) /* @brief Has eSDHC clock source selection (register bit SOPT2[ESDHCSRC]). */ #define FSL_FEATURE_SIM_OPT_HAS_ESDHCSRC (0) /* @brief Has SDHC clock source selection (register bit SOPT2[SDHCSRC]). */ #define FSL_FEATURE_SIM_OPT_HAS_SDHCSRC (0) /* @brief Has LCDC clock source selection (register bits SOPT2[LCDCSRC], SOPT2[LCDC_CLKSEL]). */ #define FSL_FEATURE_SIM_OPT_HAS_LCDCSRC (0) /* @brief Has ENET timestamp clock source selection (register bit SOPT2[TIMESRC]). */ #define FSL_FEATURE_SIM_OPT_HAS_TIMESRC (0) /* @brief Has ENET RMII clock source selection (register bit SOPT2[RMIISRC]). */ #define FSL_FEATURE_SIM_OPT_HAS_RMIISRC (0) /* @brief Has USB clock source selection (register bit SOPT2[USBSRC]). */ #define FSL_FEATURE_SIM_OPT_HAS_USBSRC (1) /* @brief Has USB FS clock source selection (register bit SOPT2[USBFSRC]). */ #define FSL_FEATURE_SIM_OPT_HAS_USBFSRC (0) /* @brief Has USB HS clock source selection (register bit SOPT2[USBHSRC]). */ #define FSL_FEATURE_SIM_OPT_HAS_USBHSRC (0) /* @brief Has LPUART clock source selection (register bit SOPT2[LPUARTSRC]). */ #define FSL_FEATURE_SIM_OPT_HAS_LPUARTSRC (0) /* @brief Has LPUART0 clock source selection (register bit SOPT2[LPUART0SRC]). */ #define FSL_FEATURE_SIM_OPT_HAS_LPUART0SRC (0) /* @brief Has LPUART1 clock source selection (register bit SOPT2[LPUART1SRC]). */ #define FSL_FEATURE_SIM_OPT_HAS_LPUART1SRC (0) /* @brief Has FLEXIOSRC clock source selection (register bit SOPT2[FLEXIOSRC]). */ #define FSL_FEATURE_SIM_OPT_HAS_FLEXIOSRC (0) /* @brief Has UART0 clock source selection (register bit SOPT2[UART0SRC]). */ #define FSL_FEATURE_SIM_OPT_HAS_UART0SRC (1) /* @brief Has TPM clock source selection (register bit SOPT2[TPMSRC]). */ #define FSL_FEATURE_SIM_OPT_HAS_TPMSRC (1) /* @brief Has debug trace clock selection (register bit SOPT2[TRACECLKSEL]). */ #define FSL_FEATURE_SIM_OPT_HAS_TRACE_CLKSEL (0) /* @brief Number of ADC modules (register bits SOPT7[ADCnTRGSEL], SOPT7[ADCnPRETRGSEL], SOPT7[ADCnALTTRGSEL], where n is a module instance index). */ #define FSL_FEATURE_SIM_OPT_ADC_COUNT (1) /* @brief Has clock 2 output divider (register bit field CLKDIV1[OUTDIV2]). */ #define FSL_FEATURE_SIM_DIVIDER_HAS_OUTDIV2 (0) /* @brief Has clock 3 output divider (register bit field CLKDIV1[OUTDIV3]). */ #define FSL_FEATURE_SIM_DIVIDER_HAS_OUTDIV3 (0) /* @brief Has clock 4 output divider (register bit field CLKDIV1[OUTDIV4]). */ #define FSL_FEATURE_SIM_DIVIDER_HAS_OUTDIV4 (1) /* @brief Clock 4 output divider width (width of register bit field CLKDIV1[OUTDIV4]). */ #define FSL_FEATURE_SIM_DIVIDER_OUTDIV4_WIDTH (3) /* @brief Has USB clock divider (register bit field CLKDIV2[USBDIV] and CLKDIV2[USBFRAC]). */ #define FSL_FEATURE_SIM_DIVIDER_HAS_USBDIV (0) /* @brief Has USB FS clock divider (register bit field CLKDIV2[USBFSDIV] and CLKDIV2[USBFSFRAC]). */ #define FSL_FEATURE_SIM_DIVIDER_HAS_USBFSDIV (0) /* @brief Has USB HS clock divider (register bit field CLKDIV2[USBHSDIV] and CLKDIV2[USBHSFRAC]). */ #define FSL_FEATURE_SIM_DIVIDER_HAS_USBHSDIV (0) /* @brief Has PLL/FLL clock divider (register bit field CLKDIV3[PLLFLLDIV] and CLKDIV3[PLLFLLFRAC]). */ #define FSL_FEATURE_SIM_DIVIDER_HAS_PLLFLLDIV (0) /* @brief Has LCDC clock divider (register bit field CLKDIV3[LCDCDIV] and CLKDIV3[LCDCFRAC]). */ #define FSL_FEATURE_SIM_DIVIDER_HAS_LCDCDIV (0) /* @brief Has trace clock divider (register bit field CLKDIV4[TRACEDIV] and CLKDIV4[TRACEFRAC]). */ #define FSL_FEATURE_SIM_DIVIDER_HAS_TRACEDIV (0) /* @brief Has NFC clock divider (register bit field CLKDIV4[NFCDIV] and CLKDIV4[NFCFRAC]). */ #define FSL_FEATURE_SIM_DIVIDER_HAS_NFCDIV (0) /* @brief Has Kinetis family ID (register bit field SDID[FAMILYID]). */ #define FSL_FEATURE_SIM_SDID_HAS_FAMILYID (0) /* @brief Has Kinetis family ID (register bit field SDID[FAMID]). */ #define FSL_FEATURE_SIM_SDID_HAS_FAMID (1) /* @brief Has Kinetis sub-family ID (register bit field SDID[SUBFAMID]). */ #define FSL_FEATURE_SIM_SDID_HAS_SUBFAMID (1) /* @brief Has Kinetis series ID (register bit field SDID[SERIESID]). */ #define FSL_FEATURE_SIM_SDID_HAS_SERIESID (1) /* @brief Has device die ID (register bit field SDID[DIEID]). */ #define FSL_FEATURE_SIM_SDID_HAS_DIEID (1) /* @brief Has system SRAM size specifier (register bit field SDID[SRAMSIZE]). */ #define FSL_FEATURE_SIM_SDID_HAS_SRAMSIZE (1) /* @brief Has flash mode (register bit FCFG1[FLASHDOZE]). */ #define FSL_FEATURE_SIM_FCFG_HAS_FLASHDOZE (1) /* @brief Has flash disable (register bit FCFG1[FLASHDIS]). */ #define FSL_FEATURE_SIM_FCFG_HAS_FLASHDIS (1) /* @brief Has FTFE disable (register bit FCFG1[FTFDIS]). */ #define FSL_FEATURE_SIM_FCFG_HAS_FTFDIS (0) /* @brief Has FlexNVM size specifier (register bit field FCFG1[NVMSIZE]). */ #define FSL_FEATURE_SIM_FCFG_HAS_NVMSIZE (0) /* @brief Has EEPROM size specifier (register bit field FCFG1[EESIZE]). */ #define FSL_FEATURE_SIM_FCFG_HAS_EESIZE (0) /* @brief Has FlexNVM partition (register bit field FCFG1[DEPART]). */ #define FSL_FEATURE_SIM_FCFG_HAS_DEPART (0) /* @brief Maximum flash address block 0 address specifier (register bit field FCFG2[MAXADDR0]). */ #define FSL_FEATURE_SIM_FCFG_HAS_MAXADDR0 (1) /* @brief Maximum flash address block 1 address specifier (register bit field FCFG2[MAXADDR1]). */ #define FSL_FEATURE_SIM_FCFG_HAS_MAXADDR1 (1) /* @brief Maximum flash address block 0 or 1 address specifier (register bit field FCFG2[MAXADDR01]). */ #define FSL_FEATURE_SIM_FCFG_HAS_MAXADDR01 (0) /* @brief Maximum flash address block 2 or 3 address specifier (register bit field FCFG2[MAXADDR23]). */ #define FSL_FEATURE_SIM_FCFG_HAS_MAXADDR23 (0) /* @brief Has program flash availability specifier (register bit FCFG2[PFLSH]). */ #define FSL_FEATURE_SIM_FCFG_HAS_PFLSH (0) /* @brief Has program flash swapping (register bit FCFG2[SWAPPFLSH]). */ #define FSL_FEATURE_SIM_FCFG_HAS_PFLSH_SWAP (0) /* @brief Has miscellanious control register (register MCR). */ #define FSL_FEATURE_SIM_HAS_MISC_CONTROLS (0) /* @brief Has COP watchdog (registers COPC and SRVCOP). */ #define FSL_FEATURE_SIM_HAS_COP_WATCHDOG (1) /* @brief Has COP watchdog stop (register bits COPC[COPSTPEN], COPC[COPDBGEN] and COPC[COPCLKSEL]). */ #define FSL_FEATURE_SIM_HAS_COP_STOP (0) #elif defined(CPU_MKV30F128VFM10) || defined(CPU_MKV30F64VFM10) || defined(CPU_MKV30F128VLF10) || defined(CPU_MKV30F64VLF10) || \ defined(CPU_MKV30F128VLH10) || defined(CPU_MKV30F64VLH10) /* @brief Has USB FS divider. */ #define FSL_FEATURE_SIM_USBFS_USE_SPECIAL_DIVIDER (0) /* @brief Is PLL clock divided by 2 before MCG PLL/FLL clock selection. */ #define FSL_FEATURE_SIM_PLLCLK_USE_SPECIAL_DIVIDER (0) /* @brief Has RAM size specification (register bit field SOPT1[RAMSIZE]). */ #define FSL_FEATURE_SIM_OPT_HAS_RAMSIZE (1) /* @brief Has 32k oscillator clock output (register bit SOPT1[OSC32KOUT]). */ #define FSL_FEATURE_SIM_OPT_HAS_OSC32K_OUT (1) /* @brief Has 32k oscillator clock selection (register bit field SOPT1[OSC32KSEL]). */ #define FSL_FEATURE_SIM_OPT_HAS_OSC32K_SELECTION (1) /* @brief 32k oscillator clock selection width (width of register bit field SOPT1[OSC32KSEL]). */ #define FSL_FEATURE_SIM_OPT_OSC32K_SELECTION_WIDTH (2) /* @brief Has RTC clock output selection (register bit SOPT2[RTCCLKOUTSEL]). */ #define FSL_FEATURE_SIM_OPT_HAS_RTC_CLOCK_OUT_SELECTION (0) /* @brief Has USB voltage regulator (register bits SOPT1[USBVSTBY], SOPT1[USBSSTBY], SOPT1[USBREGEN], SOPT1CFG[URWE], SOPT1CFG[UVSWE], SOPT1CFG[USSWE]). */ #define FSL_FEATURE_SIM_OPT_HAS_USB_VOLTAGE_REGULATOR (0) /* @brief USB has integrated PHY (register bits USBPHYCTL[USBVREGSEL], USBPHYCTL[USBVREGPD], USBPHYCTL[USB3VOUTTRG], USBPHYCTL[USBDISILIM], SOPT2[USBSLSRC], SOPT2[USBREGEN]). */ #define FSL_FEATURE_SIM_OPT_HAS_USB_PHY (0) /* @brief Has PTD7 pad drive strength control (register bit SOPT2[PTD7PAD]). */ #define FSL_FEATURE_SIM_OPT_HAS_PTD7PAD (0) /* @brief Has FlexBus security level selection (register bit SOPT2[FBSL]). */ #define FSL_FEATURE_SIM_OPT_HAS_FBSL (0) /* @brief Has number of FlexBus hold cycle before FlexBus can release bus (register bit SOPT6[PCR]). */ #define FSL_FEATURE_SIM_OPT_HAS_PCR (0) /* @brief Has number of NFC hold cycle in case of FlexBus request (register bit SOPT6[MCC]). */ #define FSL_FEATURE_SIM_OPT_HAS_MCC (0) /* @brief Has UART open drain enable (register bits UARTnODE, where n is a number, in register SOPT5). */ #define FSL_FEATURE_SIM_OPT_HAS_ODE (0) /* @brief Number of UART modules (number of register bits UARTn, where n is a number, in register SCGC4). */ #define FSL_FEATURE_SIM_OPT_UART_COUNT (2) /* @brief Has LPUART0 open drain enable (register bit SOPT5[LPUART0ODE]). */ #define FSL_FEATURE_SIM_OPT_HAS_LPUART0_ODE (0) /* @brief Has LPUART1 open drain enable (register bit SOPT5[LPUART1ODE]). */ #define FSL_FEATURE_SIM_OPT_HAS_LPUART1_ODE (0) /* @brief Has CMT/UART pad drive strength control (register bit SOPT2[CMTUARTPAD]). */ #define FSL_FEATURE_SIM_OPT_HAS_CMTUARTPAD (0) /* @brief Has LPUART0 transmit data source selection (register bit SOPT5[LPUART0TXSRC]). */ #define FSL_FEATURE_SIM_OPT_HAS_LPUART0_TX_SRC (0) /* @brief Has LPUART0 receive data source selection (register bit SOPT5[LPUART0RXSRC]). */ #define FSL_FEATURE_SIM_OPT_HAS_LPUART0_RX_SRC (0) /* @brief Has LPUART1 transmit data source selection (register bit SOPT5[LPUART1TXSRC]). */ #define FSL_FEATURE_SIM_OPT_HAS_LPUART1_TX_SRC (0) /* @brief Has LPUART1 receive data source selection (register bit SOPT5[LPUART1RXSRC]). */ #define FSL_FEATURE_SIM_OPT_HAS_LPUART1_RX_SRC (0) /* @brief Has UART0 transmit data source selection (register bit SOPT5[UART0TXSRC]). */ #define FSL_FEATURE_SIM_OPT_HAS_UART0_TX_SRC (1) /* @brief UART0 transmit data source selection width (width of register bit SOPT5[UART0TXSRC]). */ #define FSL_FEATURE_SIM_OPT_UART0_TX_SRC_WIDTH (2) /* @brief Has UART0 receive data source selection (register bit SOPT5[UART0RXSRC]). */ #define FSL_FEATURE_SIM_OPT_HAS_UART0_RX_SRC (1) /* @brief UART0 receive data source selection width (width of register bit SOPT5[UART0RXSRC]). */ #define FSL_FEATURE_SIM_OPT_UART0_RX_SRC_WIDTH (2) /* @brief Has UART1 transmit data source selection (register bit SOPT5[UART1TXSRC]). */ #define FSL_FEATURE_SIM_OPT_HAS_UART1_TX_SRC (1) /* @brief Has UART1 receive data source selection (register bit SOPT5[UART1RXSRC]). */ #define FSL_FEATURE_SIM_OPT_HAS_UART1_RX_SRC (1) /* @brief UART1 receive data source selection width (width of register bit SOPT5[UART1RXSRC]). */ #define FSL_FEATURE_SIM_OPT_UART1_RX_SRC_WIDTH (2) /* @brief Has FTM module(s) configuration. */ #define FSL_FEATURE_SIM_OPT_HAS_FTM (1) /* @brief Number of FTM modules. */ #define FSL_FEATURE_SIM_OPT_FTM_COUNT (3) /* @brief Number of FTM triggers with selectable source. */ #define FSL_FEATURE_SIM_OPT_FTM_TRIGGER_COUNT (2) /* @brief Has FTM0 triggers source selection (register bits SOPT4[FTM0TRGnSRC], where n is a number). */ #define FSL_FEATURE_SIM_OPT_HAS_FTM0_TRIGGER (1) /* @brief Has FTM3 triggers source selection (register bits SOPT4[FTM3TRGnSRC], where n is a number). */ #define FSL_FEATURE_SIM_OPT_HAS_FTM3_TRIGGER (0) /* @brief Has FTM1 channel 0 input capture source selection (register bit SOPT4[FTM1CH0SRC]). */ #define FSL_FEATURE_SIM_OPT_HAS_FTM1_CHANNELS (1) /* @brief Has FTM2 channel 0 input capture source selection (register bit SOPT4[FTM2CH0SRC]). */ #define FSL_FEATURE_SIM_OPT_HAS_FTM2_CHANNELS (1) /* @brief Has FTM3 channel 0 input capture source selection (register bit SOPT4[FTM3CH0SRC]). */ #define FSL_FEATURE_SIM_OPT_HAS_FTM3_CHANNELS (0) /* @brief Has FTM2 channel 1 input capture source selection (register bit SOPT4[FTM2CH1SRC]). */ #define FSL_FEATURE_SIM_OPT_HAS_FTM2_CHANNEL1 (1) /* @brief Number of configurable FTM0 fault detection input (number of register bits SOPT4[FTM0FLTn], where n is a number starting from zero). */ #define FSL_FEATURE_SIM_OPT_FTM0_FAULT_COUNT (2) /* @brief Number of configurable FTM1 fault detection input (number of register bits SOPT4[FTM1FLTn], where n is a number starting from zero). */ #define FSL_FEATURE_SIM_OPT_FTM1_FAULT_COUNT (1) /* @brief Number of configurable FTM2 fault detection input (number of register bits SOPT4[FTM2FLTn], where n is a number starting from zero). */ #define FSL_FEATURE_SIM_OPT_FTM2_FAULT_COUNT (1) /* @brief Number of configurable FTM3 fault detection input (number of register bits SOPT4[FTM3FLTn], where n is a number starting from zero). */ #define FSL_FEATURE_SIM_OPT_FTM3_FAULT_COUNT (0) /* @brief Has FTM hardware trigger 0 software synchronization (register bit SOPT8[FTMnSYNCBIT], where n is a module instance index). */ #define FSL_FEATURE_SIM_OPT_HAS_FTM_TRIGGER_SYNC (1) /* @brief Has FTM channels output source selection (register bit SOPT8[FTMxOCHnSRC], where x is a module instance index and n is a channel index). */ #define FSL_FEATURE_SIM_OPT_HAS_FTM_CHANNELS_OUTPUT_SRC (1) /* @brief Has TPM module(s) configuration. */ #define FSL_FEATURE_SIM_OPT_HAS_TPM (0) /* @brief The highest TPM module index. */ #define FSL_FEATURE_SIM_OPT_MAX_TPM_INDEX (0) /* @brief Has TPM module with index 0. */ #define FSL_FEATURE_SIM_OPT_HAS_TPM0 (0) /* @brief Is TPM channels configuration in the SOPT4 (not SOPT9) register (register bits TPMnCH0SRC, TPMnCLKSEL, where n is a module instance index). */ #define FSL_FEATURE_SIM_OPT_HAS_TPM_CHANNELS_CONFIG_IN_SOPT4_REG (0) /* @brief Has TPM1 channel 0 input capture source selection (register bit field SOPT4[TPM1CH0SRC] or SOPT9[TPM1CH0SRC]). */ #define FSL_FEATURE_SIM_OPT_HAS_TPM1_CH0_SRC_SELECTION (0) /* @brief TPM1 channel 0 input capture source selection width (width of register bit field SOPT4[TPM1CH0SRC] or SOPT9[TPM1CH0SRC]). */ #define FSL_FEATURE_SIM_OPT_TPM1_CH0_SRC_SELECTION_WIDTH (0) /* @brief Has TPM2 channel 0 input capture source selection (register bit field SOPT4[TPM2CH0SRC]). */ #define FSL_FEATURE_SIM_OPT_HAS_TPM2_CH0_SRC_SELECTION (0) /* @brief Has TPM2 clock selection (register bit field SOPT4[TPM2CLKSEL]). */ #define FSL_FEATURE_SIM_OPT_HAS_TPM2_CLK_SEL (0) /* @brief Has PLL/FLL clock selection (register bit field SOPT2[PLLFLLSEL]). */ #define FSL_FEATURE_SIM_OPT_HAS_PLL_FLL_SELECTION (1) /* @brief PLL/FLL clock selection width (width of register bit field SOPT2[PLLFLLSEL]). */ #define FSL_FEATURE_SIM_OPT_PLL_FLL_SELECTION_WIDTH (1) /* @brief Has NFC clock source selection (register bit SOPT2[NFCSRC]). */ #define FSL_FEATURE_SIM_OPT_HAS_NFCSRC (0) /* @brief Has eSDHC clock source selection (register bit SOPT2[ESDHCSRC]). */ #define FSL_FEATURE_SIM_OPT_HAS_ESDHCSRC (0) /* @brief Has SDHC clock source selection (register bit SOPT2[SDHCSRC]). */ #define FSL_FEATURE_SIM_OPT_HAS_SDHCSRC (0) /* @brief Has LCDC clock source selection (register bits SOPT2[LCDCSRC], SOPT2[LCDC_CLKSEL]). */ #define FSL_FEATURE_SIM_OPT_HAS_LCDCSRC (0) /* @brief Has ENET timestamp clock source selection (register bit SOPT2[TIMESRC]). */ #define FSL_FEATURE_SIM_OPT_HAS_TIMESRC (0) /* @brief Has ENET RMII clock source selection (register bit SOPT2[RMIISRC]). */ #define FSL_FEATURE_SIM_OPT_HAS_RMIISRC (0) /* @brief Has USB clock source selection (register bit SOPT2[USBSRC]). */ #define FSL_FEATURE_SIM_OPT_HAS_USBSRC (0) /* @brief Has USB FS clock source selection (register bit SOPT2[USBFSRC]). */ #define FSL_FEATURE_SIM_OPT_HAS_USBFSRC (0) /* @brief Has USB HS clock source selection (register bit SOPT2[USBHSRC]). */ #define FSL_FEATURE_SIM_OPT_HAS_USBHSRC (0) /* @brief Has LPUART clock source selection (register bit SOPT2[LPUARTSRC]). */ #define FSL_FEATURE_SIM_OPT_HAS_LPUARTSRC (0) /* @brief Has LPUART0 clock source selection (register bit SOPT2[LPUART0SRC]). */ #define FSL_FEATURE_SIM_OPT_HAS_LPUART0SRC (0) /* @brief Has LPUART1 clock source selection (register bit SOPT2[LPUART1SRC]). */ #define FSL_FEATURE_SIM_OPT_HAS_LPUART1SRC (0) /* @brief Has FLEXIOSRC clock source selection (register bit SOPT2[FLEXIOSRC]). */ #define FSL_FEATURE_SIM_OPT_HAS_FLEXIOSRC (0) /* @brief Has UART0 clock source selection (register bit SOPT2[UART0SRC]). */ #define FSL_FEATURE_SIM_OPT_HAS_UART0SRC (0) /* @brief Has TPM clock source selection (register bit SOPT2[TPMSRC]). */ #define FSL_FEATURE_SIM_OPT_HAS_TPMSRC (0) /* @brief Has debug trace clock selection (register bit SOPT2[TRACECLKSEL]). */ #define FSL_FEATURE_SIM_OPT_HAS_TRACE_CLKSEL (1) /* @brief Number of ADC modules (register bits SOPT7[ADCnTRGSEL], SOPT7[ADCnPRETRGSEL], SOPT7[ADCnALTTRGSEL], where n is a module instance index). */ #define FSL_FEATURE_SIM_OPT_ADC_COUNT (2) /* @brief Has clock 2 output divider (register bit field CLKDIV1[OUTDIV2]). */ #define FSL_FEATURE_SIM_DIVIDER_HAS_OUTDIV2 (1) /* @brief Has clock 3 output divider (register bit field CLKDIV1[OUTDIV3]). */ #define FSL_FEATURE_SIM_DIVIDER_HAS_OUTDIV3 (0) /* @brief Has clock 4 output divider (register bit field CLKDIV1[OUTDIV4]). */ #define FSL_FEATURE_SIM_DIVIDER_HAS_OUTDIV4 (1) /* @brief Clock 4 output divider width (width of register bit field CLKDIV1[OUTDIV4]). */ #define FSL_FEATURE_SIM_DIVIDER_OUTDIV4_WIDTH (4) /* @brief Has USB clock divider (register bit field CLKDIV2[USBDIV] and CLKDIV2[USBFRAC]). */ #define FSL_FEATURE_SIM_DIVIDER_HAS_USBDIV (0) /* @brief Has USB FS clock divider (register bit field CLKDIV2[USBFSDIV] and CLKDIV2[USBFSFRAC]). */ #define FSL_FEATURE_SIM_DIVIDER_HAS_USBFSDIV (0) /* @brief Has USB HS clock divider (register bit field CLKDIV2[USBHSDIV] and CLKDIV2[USBHSFRAC]). */ #define FSL_FEATURE_SIM_DIVIDER_HAS_USBHSDIV (0) /* @brief Has PLL/FLL clock divider (register bit field CLKDIV3[PLLFLLDIV] and CLKDIV3[PLLFLLFRAC]). */ #define FSL_FEATURE_SIM_DIVIDER_HAS_PLLFLLDIV (0) /* @brief Has LCDC clock divider (register bit field CLKDIV3[LCDCDIV] and CLKDIV3[LCDCFRAC]). */ #define FSL_FEATURE_SIM_DIVIDER_HAS_LCDCDIV (0) /* @brief Has trace clock divider (register bit field CLKDIV4[TRACEDIV] and CLKDIV4[TRACEFRAC]). */ #define FSL_FEATURE_SIM_DIVIDER_HAS_TRACEDIV (0) /* @brief Has NFC clock divider (register bit field CLKDIV4[NFCDIV] and CLKDIV4[NFCFRAC]). */ #define FSL_FEATURE_SIM_DIVIDER_HAS_NFCDIV (0) /* @brief Has Kinetis family ID (register bit field SDID[FAMILYID]). */ #define FSL_FEATURE_SIM_SDID_HAS_FAMILYID (1) /* @brief Has Kinetis family ID (register bit field SDID[FAMID]). */ #define FSL_FEATURE_SIM_SDID_HAS_FAMID (0) /* @brief Has Kinetis sub-family ID (register bit field SDID[SUBFAMID]). */ #define FSL_FEATURE_SIM_SDID_HAS_SUBFAMID (1) /* @brief Has Kinetis series ID (register bit field SDID[SERIESID]). */ #define FSL_FEATURE_SIM_SDID_HAS_SERIESID (1) /* @brief Has device die ID (register bit field SDID[DIEID]). */ #define FSL_FEATURE_SIM_SDID_HAS_DIEID (1) /* @brief Has system SRAM size specifier (register bit field SDID[SRAMSIZE]). */ #define FSL_FEATURE_SIM_SDID_HAS_SRAMSIZE (0) /* @brief Has flash mode (register bit FCFG1[FLASHDOZE]). */ #define FSL_FEATURE_SIM_FCFG_HAS_FLASHDOZE (1) /* @brief Has flash disable (register bit FCFG1[FLASHDIS]). */ #define FSL_FEATURE_SIM_FCFG_HAS_FLASHDIS (1) /* @brief Has FTFE disable (register bit FCFG1[FTFDIS]). */ #define FSL_FEATURE_SIM_FCFG_HAS_FTFDIS (0) /* @brief Has FlexNVM size specifier (register bit field FCFG1[NVMSIZE]). */ #define FSL_FEATURE_SIM_FCFG_HAS_NVMSIZE (0) /* @brief Has EEPROM size specifier (register bit field FCFG1[EESIZE]). */ #define FSL_FEATURE_SIM_FCFG_HAS_EESIZE (0) /* @brief Has FlexNVM partition (register bit field FCFG1[DEPART]). */ #define FSL_FEATURE_SIM_FCFG_HAS_DEPART (0) /* @brief Maximum flash address block 0 address specifier (register bit field FCFG2[MAXADDR0]). */ #define FSL_FEATURE_SIM_FCFG_HAS_MAXADDR0 (1) /* @brief Maximum flash address block 1 address specifier (register bit field FCFG2[MAXADDR1]). */ #define FSL_FEATURE_SIM_FCFG_HAS_MAXADDR1 (0) /* @brief Maximum flash address block 0 or 1 address specifier (register bit field FCFG2[MAXADDR01]). */ #define FSL_FEATURE_SIM_FCFG_HAS_MAXADDR01 (0) /* @brief Maximum flash address block 2 or 3 address specifier (register bit field FCFG2[MAXADDR23]). */ #define FSL_FEATURE_SIM_FCFG_HAS_MAXADDR23 (0) /* @brief Has program flash availability specifier (register bit FCFG2[PFLSH]). */ #define FSL_FEATURE_SIM_FCFG_HAS_PFLSH (0) /* @brief Has program flash swapping (register bit FCFG2[SWAPPFLSH]). */ #define FSL_FEATURE_SIM_FCFG_HAS_PFLSH_SWAP (0) /* @brief Has miscellanious control register (register MCR). */ #define FSL_FEATURE_SIM_HAS_MISC_CONTROLS (0) /* @brief Has COP watchdog (registers COPC and SRVCOP). */ #define FSL_FEATURE_SIM_HAS_COP_WATCHDOG (0) /* @brief Has COP watchdog stop (register bits COPC[COPSTPEN], COPC[COPDBGEN] and COPC[COPCLKSEL]). */ #define FSL_FEATURE_SIM_HAS_COP_STOP (0) #elif defined(CPU_MKV31F128VLH10) || defined(CPU_MKV31F128VLL10) || defined(CPU_MKV31F256VLH12) || defined(CPU_MKV31F256VLL12) /* @brief Has USB FS divider. */ #define FSL_FEATURE_SIM_USBFS_USE_SPECIAL_DIVIDER (0) /* @brief Is PLL clock divided by 2 before MCG PLL/FLL clock selection. */ #define FSL_FEATURE_SIM_PLLCLK_USE_SPECIAL_DIVIDER (0) /* @brief Has RAM size specification (register bit field SOPT1[RAMSIZE]). */ #define FSL_FEATURE_SIM_OPT_HAS_RAMSIZE (1) /* @brief Has 32k oscillator clock output (register bit SOPT1[OSC32KOUT]). */ #define FSL_FEATURE_SIM_OPT_HAS_OSC32K_OUT (1) /* @brief Has 32k oscillator clock selection (register bit field SOPT1[OSC32KSEL]). */ #define FSL_FEATURE_SIM_OPT_HAS_OSC32K_SELECTION (1) /* @brief 32k oscillator clock selection width (width of register bit field SOPT1[OSC32KSEL]). */ #define FSL_FEATURE_SIM_OPT_OSC32K_SELECTION_WIDTH (2) /* @brief Has RTC clock output selection (register bit SOPT2[RTCCLKOUTSEL]). */ #define FSL_FEATURE_SIM_OPT_HAS_RTC_CLOCK_OUT_SELECTION (0) /* @brief Has USB voltage regulator (register bits SOPT1[USBVSTBY], SOPT1[USBSSTBY], SOPT1[USBREGEN], SOPT1CFG[URWE], SOPT1CFG[UVSWE], SOPT1CFG[USSWE]). */ #define FSL_FEATURE_SIM_OPT_HAS_USB_VOLTAGE_REGULATOR (0) /* @brief USB has integrated PHY (register bits USBPHYCTL[USBVREGSEL], USBPHYCTL[USBVREGPD], USBPHYCTL[USB3VOUTTRG], USBPHYCTL[USBDISILIM], SOPT2[USBSLSRC], SOPT2[USBREGEN]). */ #define FSL_FEATURE_SIM_OPT_HAS_USB_PHY (0) /* @brief Has PTD7 pad drive strength control (register bit SOPT2[PTD7PAD]). */ #define FSL_FEATURE_SIM_OPT_HAS_PTD7PAD (0) /* @brief Has FlexBus security level selection (register bit SOPT2[FBSL]). */ #define FSL_FEATURE_SIM_OPT_HAS_FBSL (0) /* @brief Has number of FlexBus hold cycle before FlexBus can release bus (register bit SOPT6[PCR]). */ #define FSL_FEATURE_SIM_OPT_HAS_PCR (0) /* @brief Has number of NFC hold cycle in case of FlexBus request (register bit SOPT6[MCC]). */ #define FSL_FEATURE_SIM_OPT_HAS_MCC (0) /* @brief Has UART open drain enable (register bits UARTnODE, where n is a number, in register SOPT5). */ #define FSL_FEATURE_SIM_OPT_HAS_ODE (0) /* @brief Number of UART modules (number of register bits UARTn, where n is a number, in register SCGC4). */ #define FSL_FEATURE_SIM_OPT_UART_COUNT (3) /* @brief Has LPUART0 open drain enable (register bit SOPT5[LPUART0ODE]). */ #define FSL_FEATURE_SIM_OPT_HAS_LPUART0_ODE (0) /* @brief Has LPUART1 open drain enable (register bit SOPT5[LPUART1ODE]). */ #define FSL_FEATURE_SIM_OPT_HAS_LPUART1_ODE (0) /* @brief Has CMT/UART pad drive strength control (register bit SOPT2[CMTUARTPAD]). */ #define FSL_FEATURE_SIM_OPT_HAS_CMTUARTPAD (0) /* @brief Has LPUART0 transmit data source selection (register bit SOPT5[LPUART0TXSRC]). */ #define FSL_FEATURE_SIM_OPT_HAS_LPUART0_TX_SRC (0) /* @brief Has LPUART0 receive data source selection (register bit SOPT5[LPUART0RXSRC]). */ #define FSL_FEATURE_SIM_OPT_HAS_LPUART0_RX_SRC (1) /* @brief Has LPUART1 transmit data source selection (register bit SOPT5[LPUART1TXSRC]). */ #define FSL_FEATURE_SIM_OPT_HAS_LPUART1_TX_SRC (0) /* @brief Has LPUART1 receive data source selection (register bit SOPT5[LPUART1RXSRC]). */ #define FSL_FEATURE_SIM_OPT_HAS_LPUART1_RX_SRC (0) /* @brief Has UART0 transmit data source selection (register bit SOPT5[UART0TXSRC]). */ #define FSL_FEATURE_SIM_OPT_HAS_UART0_TX_SRC (1) /* @brief UART0 transmit data source selection width (width of register bit SOPT5[UART0TXSRC]). */ #define FSL_FEATURE_SIM_OPT_UART0_TX_SRC_WIDTH (2) /* @brief Has UART0 receive data source selection (register bit SOPT5[UART0RXSRC]). */ #define FSL_FEATURE_SIM_OPT_HAS_UART0_RX_SRC (1) /* @brief UART0 receive data source selection width (width of register bit SOPT5[UART0RXSRC]). */ #define FSL_FEATURE_SIM_OPT_UART0_RX_SRC_WIDTH (2) /* @brief Has UART1 transmit data source selection (register bit SOPT5[UART1TXSRC]). */ #define FSL_FEATURE_SIM_OPT_HAS_UART1_TX_SRC (1) /* @brief Has UART1 receive data source selection (register bit SOPT5[UART1RXSRC]). */ #define FSL_FEATURE_SIM_OPT_HAS_UART1_RX_SRC (1) /* @brief UART1 receive data source selection width (width of register bit SOPT5[UART1RXSRC]). */ #define FSL_FEATURE_SIM_OPT_UART1_RX_SRC_WIDTH (2) /* @brief Has FTM module(s) configuration. */ #define FSL_FEATURE_SIM_OPT_HAS_FTM (1) /* @brief Number of FTM modules. */ #define FSL_FEATURE_SIM_OPT_FTM_COUNT (3) /* @brief Number of FTM triggers with selectable source. */ #define FSL_FEATURE_SIM_OPT_FTM_TRIGGER_COUNT (2) /* @brief Has FTM0 triggers source selection (register bits SOPT4[FTM0TRGnSRC], where n is a number). */ #define FSL_FEATURE_SIM_OPT_HAS_FTM0_TRIGGER (1) /* @brief Has FTM3 triggers source selection (register bits SOPT4[FTM3TRGnSRC], where n is a number). */ #define FSL_FEATURE_SIM_OPT_HAS_FTM3_TRIGGER (0) /* @brief Has FTM1 channel 0 input capture source selection (register bit SOPT4[FTM1CH0SRC]). */ #define FSL_FEATURE_SIM_OPT_HAS_FTM1_CHANNELS (1) /* @brief Has FTM2 channel 0 input capture source selection (register bit SOPT4[FTM2CH0SRC]). */ #define FSL_FEATURE_SIM_OPT_HAS_FTM2_CHANNELS (1) /* @brief Has FTM3 channel 0 input capture source selection (register bit SOPT4[FTM3CH0SRC]). */ #define FSL_FEATURE_SIM_OPT_HAS_FTM3_CHANNELS (0) /* @brief Has FTM2 channel 1 input capture source selection (register bit SOPT4[FTM2CH1SRC]). */ #define FSL_FEATURE_SIM_OPT_HAS_FTM2_CHANNEL1 (1) /* @brief Number of configurable FTM0 fault detection input (number of register bits SOPT4[FTM0FLTn], where n is a number starting from zero). */ #define FSL_FEATURE_SIM_OPT_FTM0_FAULT_COUNT (2) /* @brief Number of configurable FTM1 fault detection input (number of register bits SOPT4[FTM1FLTn], where n is a number starting from zero). */ #define FSL_FEATURE_SIM_OPT_FTM1_FAULT_COUNT (1) /* @brief Number of configurable FTM2 fault detection input (number of register bits SOPT4[FTM2FLTn], where n is a number starting from zero). */ #define FSL_FEATURE_SIM_OPT_FTM2_FAULT_COUNT (1) /* @brief Number of configurable FTM3 fault detection input (number of register bits SOPT4[FTM3FLTn], where n is a number starting from zero). */ #define FSL_FEATURE_SIM_OPT_FTM3_FAULT_COUNT (0) /* @brief Has FTM hardware trigger 0 software synchronization (register bit SOPT8[FTMnSYNCBIT], where n is a module instance index). */ #define FSL_FEATURE_SIM_OPT_HAS_FTM_TRIGGER_SYNC (1) /* @brief Has FTM channels output source selection (register bit SOPT8[FTMxOCHnSRC], where x is a module instance index and n is a channel index). */ #define FSL_FEATURE_SIM_OPT_HAS_FTM_CHANNELS_OUTPUT_SRC (1) /* @brief Has TPM module(s) configuration. */ #define FSL_FEATURE_SIM_OPT_HAS_TPM (0) /* @brief The highest TPM module index. */ #define FSL_FEATURE_SIM_OPT_MAX_TPM_INDEX (0) /* @brief Has TPM module with index 0. */ #define FSL_FEATURE_SIM_OPT_HAS_TPM0 (0) /* @brief Is TPM channels configuration in the SOPT4 (not SOPT9) register (register bits TPMnCH0SRC, TPMnCLKSEL, where n is a module instance index). */ #define FSL_FEATURE_SIM_OPT_HAS_TPM_CHANNELS_CONFIG_IN_SOPT4_REG (0) /* @brief Has TPM1 channel 0 input capture source selection (register bit field SOPT4[TPM1CH0SRC] or SOPT9[TPM1CH0SRC]). */ #define FSL_FEATURE_SIM_OPT_HAS_TPM1_CH0_SRC_SELECTION (0) /* @brief TPM1 channel 0 input capture source selection width (width of register bit field SOPT4[TPM1CH0SRC] or SOPT9[TPM1CH0SRC]). */ #define FSL_FEATURE_SIM_OPT_TPM1_CH0_SRC_SELECTION_WIDTH (0) /* @brief Has TPM2 channel 0 input capture source selection (register bit field SOPT4[TPM2CH0SRC]). */ #define FSL_FEATURE_SIM_OPT_HAS_TPM2_CH0_SRC_SELECTION (0) /* @brief Has TPM2 clock selection (register bit field SOPT4[TPM2CLKSEL]). */ #define FSL_FEATURE_SIM_OPT_HAS_TPM2_CLK_SEL (0) /* @brief Has PLL/FLL clock selection (register bit field SOPT2[PLLFLLSEL]). */ #define FSL_FEATURE_SIM_OPT_HAS_PLL_FLL_SELECTION (1) /* @brief PLL/FLL clock selection width (width of register bit field SOPT2[PLLFLLSEL]). */ #define FSL_FEATURE_SIM_OPT_PLL_FLL_SELECTION_WIDTH (1) /* @brief Has NFC clock source selection (register bit SOPT2[NFCSRC]). */ #define FSL_FEATURE_SIM_OPT_HAS_NFCSRC (0) /* @brief Has eSDHC clock source selection (register bit SOPT2[ESDHCSRC]). */ #define FSL_FEATURE_SIM_OPT_HAS_ESDHCSRC (0) /* @brief Has SDHC clock source selection (register bit SOPT2[SDHCSRC]). */ #define FSL_FEATURE_SIM_OPT_HAS_SDHCSRC (0) /* @brief Has LCDC clock source selection (register bits SOPT2[LCDCSRC], SOPT2[LCDC_CLKSEL]). */ #define FSL_FEATURE_SIM_OPT_HAS_LCDCSRC (0) /* @brief Has ENET timestamp clock source selection (register bit SOPT2[TIMESRC]). */ #define FSL_FEATURE_SIM_OPT_HAS_TIMESRC (0) /* @brief Has ENET RMII clock source selection (register bit SOPT2[RMIISRC]). */ #define FSL_FEATURE_SIM_OPT_HAS_RMIISRC (0) /* @brief Has USB clock source selection (register bit SOPT2[USBSRC]). */ #define FSL_FEATURE_SIM_OPT_HAS_USBSRC (0) /* @brief Has USB FS clock source selection (register bit SOPT2[USBFSRC]). */ #define FSL_FEATURE_SIM_OPT_HAS_USBFSRC (0) /* @brief Has USB HS clock source selection (register bit SOPT2[USBHSRC]). */ #define FSL_FEATURE_SIM_OPT_HAS_USBHSRC (0) /* @brief Has LPUART clock source selection (register bit SOPT2[LPUARTSRC]). */ #define FSL_FEATURE_SIM_OPT_HAS_LPUARTSRC (1) /* @brief Has LPUART0 clock source selection (register bit SOPT2[LPUART0SRC]). */ #define FSL_FEATURE_SIM_OPT_HAS_LPUART0SRC (0) /* @brief Has LPUART1 clock source selection (register bit SOPT2[LPUART1SRC]). */ #define FSL_FEATURE_SIM_OPT_HAS_LPUART1SRC (0) /* @brief Has FLEXIOSRC clock source selection (register bit SOPT2[FLEXIOSRC]). */ #define FSL_FEATURE_SIM_OPT_HAS_FLEXIOSRC (0) /* @brief Has UART0 clock source selection (register bit SOPT2[UART0SRC]). */ #define FSL_FEATURE_SIM_OPT_HAS_UART0SRC (0) /* @brief Has TPM clock source selection (register bit SOPT2[TPMSRC]). */ #define FSL_FEATURE_SIM_OPT_HAS_TPMSRC (0) /* @brief Has debug trace clock selection (register bit SOPT2[TRACECLKSEL]). */ #define FSL_FEATURE_SIM_OPT_HAS_TRACE_CLKSEL (1) /* @brief Number of ADC modules (register bits SOPT7[ADCnTRGSEL], SOPT7[ADCnPRETRGSEL], SOPT7[ADCnALTTRGSEL], where n is a module instance index). */ #define FSL_FEATURE_SIM_OPT_ADC_COUNT (2) /* @brief Has clock 2 output divider (register bit field CLKDIV1[OUTDIV2]). */ #define FSL_FEATURE_SIM_DIVIDER_HAS_OUTDIV2 (1) /* @brief Has clock 3 output divider (register bit field CLKDIV1[OUTDIV3]). */ #define FSL_FEATURE_SIM_DIVIDER_HAS_OUTDIV3 (0) /* @brief Has clock 4 output divider (register bit field CLKDIV1[OUTDIV4]). */ #define FSL_FEATURE_SIM_DIVIDER_HAS_OUTDIV4 (1) /* @brief Clock 4 output divider width (width of register bit field CLKDIV1[OUTDIV4]). */ #define FSL_FEATURE_SIM_DIVIDER_OUTDIV4_WIDTH (4) /* @brief Has USB clock divider (register bit field CLKDIV2[USBDIV] and CLKDIV2[USBFRAC]). */ #define FSL_FEATURE_SIM_DIVIDER_HAS_USBDIV (0) /* @brief Has USB FS clock divider (register bit field CLKDIV2[USBFSDIV] and CLKDIV2[USBFSFRAC]). */ #define FSL_FEATURE_SIM_DIVIDER_HAS_USBFSDIV (0) /* @brief Has USB HS clock divider (register bit field CLKDIV2[USBHSDIV] and CLKDIV2[USBHSFRAC]). */ #define FSL_FEATURE_SIM_DIVIDER_HAS_USBHSDIV (0) /* @brief Has PLL/FLL clock divider (register bit field CLKDIV3[PLLFLLDIV] and CLKDIV3[PLLFLLFRAC]). */ #define FSL_FEATURE_SIM_DIVIDER_HAS_PLLFLLDIV (0) /* @brief Has LCDC clock divider (register bit field CLKDIV3[LCDCDIV] and CLKDIV3[LCDCFRAC]). */ #define FSL_FEATURE_SIM_DIVIDER_HAS_LCDCDIV (0) /* @brief Has trace clock divider (register bit field CLKDIV4[TRACEDIV] and CLKDIV4[TRACEFRAC]). */ #define FSL_FEATURE_SIM_DIVIDER_HAS_TRACEDIV (0) /* @brief Has NFC clock divider (register bit field CLKDIV4[NFCDIV] and CLKDIV4[NFCFRAC]). */ #define FSL_FEATURE_SIM_DIVIDER_HAS_NFCDIV (0) /* @brief Has Kinetis family ID (register bit field SDID[FAMILYID]). */ #define FSL_FEATURE_SIM_SDID_HAS_FAMILYID (1) /* @brief Has Kinetis family ID (register bit field SDID[FAMID]). */ #define FSL_FEATURE_SIM_SDID_HAS_FAMID (0) /* @brief Has Kinetis sub-family ID (register bit field SDID[SUBFAMID]). */ #define FSL_FEATURE_SIM_SDID_HAS_SUBFAMID (1) /* @brief Has Kinetis series ID (register bit field SDID[SERIESID]). */ #define FSL_FEATURE_SIM_SDID_HAS_SERIESID (1) /* @brief Has device die ID (register bit field SDID[DIEID]). */ #define FSL_FEATURE_SIM_SDID_HAS_DIEID (1) /* @brief Has system SRAM size specifier (register bit field SDID[SRAMSIZE]). */ #define FSL_FEATURE_SIM_SDID_HAS_SRAMSIZE (0) /* @brief Has flash mode (register bit FCFG1[FLASHDOZE]). */ #define FSL_FEATURE_SIM_FCFG_HAS_FLASHDOZE (1) /* @brief Has flash disable (register bit FCFG1[FLASHDIS]). */ #define FSL_FEATURE_SIM_FCFG_HAS_FLASHDIS (1) /* @brief Has FTFE disable (register bit FCFG1[FTFDIS]). */ #define FSL_FEATURE_SIM_FCFG_HAS_FTFDIS (0) /* @brief Has FlexNVM size specifier (register bit field FCFG1[NVMSIZE]). */ #define FSL_FEATURE_SIM_FCFG_HAS_NVMSIZE (0) /* @brief Has EEPROM size specifier (register bit field FCFG1[EESIZE]). */ #define FSL_FEATURE_SIM_FCFG_HAS_EESIZE (0) /* @brief Has FlexNVM partition (register bit field FCFG1[DEPART]). */ #define FSL_FEATURE_SIM_FCFG_HAS_DEPART (0) /* @brief Maximum flash address block 0 address specifier (register bit field FCFG2[MAXADDR0]). */ #define FSL_FEATURE_SIM_FCFG_HAS_MAXADDR0 (1) /* @brief Maximum flash address block 1 address specifier (register bit field FCFG2[MAXADDR1]). */ #define FSL_FEATURE_SIM_FCFG_HAS_MAXADDR1 (1) /* @brief Maximum flash address block 0 or 1 address specifier (register bit field FCFG2[MAXADDR01]). */ #define FSL_FEATURE_SIM_FCFG_HAS_MAXADDR01 (0) /* @brief Maximum flash address block 2 or 3 address specifier (register bit field FCFG2[MAXADDR23]). */ #define FSL_FEATURE_SIM_FCFG_HAS_MAXADDR23 (0) /* @brief Has program flash availability specifier (register bit FCFG2[PFLSH]). */ #define FSL_FEATURE_SIM_FCFG_HAS_PFLSH (0) /* @brief Has program flash swapping (register bit FCFG2[SWAPPFLSH]). */ #define FSL_FEATURE_SIM_FCFG_HAS_PFLSH_SWAP (0) /* @brief Has miscellanious control register (register MCR). */ #define FSL_FEATURE_SIM_HAS_MISC_CONTROLS (0) /* @brief Has COP watchdog (registers COPC and SRVCOP). */ #define FSL_FEATURE_SIM_HAS_COP_WATCHDOG (0) /* @brief Has COP watchdog stop (register bits COPC[COPSTPEN], COPC[COPDBGEN] and COPC[COPCLKSEL]). */ #define FSL_FEATURE_SIM_HAS_COP_STOP (0) #elif defined(CPU_MKV31F512VLH12) || defined(CPU_MKV31F512VLL12) /* @brief Has USB FS divider. */ #define FSL_FEATURE_SIM_USBFS_USE_SPECIAL_DIVIDER (0) /* @brief Is PLL clock divided by 2 before MCG PLL/FLL clock selection. */ #define FSL_FEATURE_SIM_PLLCLK_USE_SPECIAL_DIVIDER (0) /* @brief Has RAM size specification (register bit field SOPT1[RAMSIZE]). */ #define FSL_FEATURE_SIM_OPT_HAS_RAMSIZE (1) /* @brief Has 32k oscillator clock output (register bit SOPT1[OSC32KOUT]). */ #define FSL_FEATURE_SIM_OPT_HAS_OSC32K_OUT (1) /* @brief Has 32k oscillator clock selection (register bit field SOPT1[OSC32KSEL]). */ #define FSL_FEATURE_SIM_OPT_HAS_OSC32K_SELECTION (1) /* @brief 32k oscillator clock selection width (width of register bit field SOPT1[OSC32KSEL]). */ #define FSL_FEATURE_SIM_OPT_OSC32K_SELECTION_WIDTH (2) /* @brief Has RTC clock output selection (register bit SOPT2[RTCCLKOUTSEL]). */ #define FSL_FEATURE_SIM_OPT_HAS_RTC_CLOCK_OUT_SELECTION (0) /* @brief Has USB voltage regulator (register bits SOPT1[USBVSTBY], SOPT1[USBSSTBY], SOPT1[USBREGEN], SOPT1CFG[URWE], SOPT1CFG[UVSWE], SOPT1CFG[USSWE]). */ #define FSL_FEATURE_SIM_OPT_HAS_USB_VOLTAGE_REGULATOR (0) /* @brief USB has integrated PHY (register bits USBPHYCTL[USBVREGSEL], USBPHYCTL[USBVREGPD], USBPHYCTL[USB3VOUTTRG], USBPHYCTL[USBDISILIM], SOPT2[USBSLSRC], SOPT2[USBREGEN]). */ #define FSL_FEATURE_SIM_OPT_HAS_USB_PHY (0) /* @brief Has PTD7 pad drive strength control (register bit SOPT2[PTD7PAD]). */ #define FSL_FEATURE_SIM_OPT_HAS_PTD7PAD (0) /* @brief Has FlexBus security level selection (register bit SOPT2[FBSL]). */ #define FSL_FEATURE_SIM_OPT_HAS_FBSL (1) /* @brief Has number of FlexBus hold cycle before FlexBus can release bus (register bit SOPT6[PCR]). */ #define FSL_FEATURE_SIM_OPT_HAS_PCR (0) /* @brief Has number of NFC hold cycle in case of FlexBus request (register bit SOPT6[MCC]). */ #define FSL_FEATURE_SIM_OPT_HAS_MCC (0) /* @brief Has UART open drain enable (register bits UARTnODE, where n is a number, in register SOPT5). */ #define FSL_FEATURE_SIM_OPT_HAS_ODE (0) /* @brief Number of UART modules (number of register bits UARTn, where n is a number, in register SCGC4). */ #define FSL_FEATURE_SIM_OPT_UART_COUNT (3) /* @brief Has LPUART0 open drain enable (register bit SOPT5[LPUART0ODE]). */ #define FSL_FEATURE_SIM_OPT_HAS_LPUART0_ODE (0) /* @brief Has LPUART1 open drain enable (register bit SOPT5[LPUART1ODE]). */ #define FSL_FEATURE_SIM_OPT_HAS_LPUART1_ODE (0) /* @brief Has CMT/UART pad drive strength control (register bit SOPT2[CMTUARTPAD]). */ #define FSL_FEATURE_SIM_OPT_HAS_CMTUARTPAD (0) /* @brief Has LPUART0 transmit data source selection (register bit SOPT5[LPUART0TXSRC]). */ #define FSL_FEATURE_SIM_OPT_HAS_LPUART0_TX_SRC (0) /* @brief Has LPUART0 receive data source selection (register bit SOPT5[LPUART0RXSRC]). */ #define FSL_FEATURE_SIM_OPT_HAS_LPUART0_RX_SRC (1) /* @brief Has LPUART1 transmit data source selection (register bit SOPT5[LPUART1TXSRC]). */ #define FSL_FEATURE_SIM_OPT_HAS_LPUART1_TX_SRC (0) /* @brief Has LPUART1 receive data source selection (register bit SOPT5[LPUART1RXSRC]). */ #define FSL_FEATURE_SIM_OPT_HAS_LPUART1_RX_SRC (0) /* @brief Has UART0 transmit data source selection (register bit SOPT5[UART0TXSRC]). */ #define FSL_FEATURE_SIM_OPT_HAS_UART0_TX_SRC (1) /* @brief UART0 transmit data source selection width (width of register bit SOPT5[UART0TXSRC]). */ #define FSL_FEATURE_SIM_OPT_UART0_TX_SRC_WIDTH (2) /* @brief Has UART0 receive data source selection (register bit SOPT5[UART0RXSRC]). */ #define FSL_FEATURE_SIM_OPT_HAS_UART0_RX_SRC (1) /* @brief UART0 receive data source selection width (width of register bit SOPT5[UART0RXSRC]). */ #define FSL_FEATURE_SIM_OPT_UART0_RX_SRC_WIDTH (2) /* @brief Has UART1 transmit data source selection (register bit SOPT5[UART1TXSRC]). */ #define FSL_FEATURE_SIM_OPT_HAS_UART1_TX_SRC (1) /* @brief Has UART1 receive data source selection (register bit SOPT5[UART1RXSRC]). */ #define FSL_FEATURE_SIM_OPT_HAS_UART1_RX_SRC (1) /* @brief UART1 receive data source selection width (width of register bit SOPT5[UART1RXSRC]). */ #define FSL_FEATURE_SIM_OPT_UART1_RX_SRC_WIDTH (2) /* @brief Has FTM module(s) configuration. */ #define FSL_FEATURE_SIM_OPT_HAS_FTM (1) /* @brief Number of FTM modules. */ #define FSL_FEATURE_SIM_OPT_FTM_COUNT (4) /* @brief Number of FTM triggers with selectable source. */ #define FSL_FEATURE_SIM_OPT_FTM_TRIGGER_COUNT (2) /* @brief Has FTM0 triggers source selection (register bits SOPT4[FTM0TRGnSRC], where n is a number). */ #define FSL_FEATURE_SIM_OPT_HAS_FTM0_TRIGGER (1) /* @brief Has FTM3 triggers source selection (register bits SOPT4[FTM3TRGnSRC], where n is a number). */ #define FSL_FEATURE_SIM_OPT_HAS_FTM3_TRIGGER (1) /* @brief Has FTM1 channel 0 input capture source selection (register bit SOPT4[FTM1CH0SRC]). */ #define FSL_FEATURE_SIM_OPT_HAS_FTM1_CHANNELS (1) /* @brief Has FTM2 channel 0 input capture source selection (register bit SOPT4[FTM2CH0SRC]). */ #define FSL_FEATURE_SIM_OPT_HAS_FTM2_CHANNELS (1) /* @brief Has FTM3 channel 0 input capture source selection (register bit SOPT4[FTM3CH0SRC]). */ #define FSL_FEATURE_SIM_OPT_HAS_FTM3_CHANNELS (0) /* @brief Has FTM2 channel 1 input capture source selection (register bit SOPT4[FTM2CH1SRC]). */ #define FSL_FEATURE_SIM_OPT_HAS_FTM2_CHANNEL1 (1) /* @brief Number of configurable FTM0 fault detection input (number of register bits SOPT4[FTM0FLTn], where n is a number starting from zero). */ #define FSL_FEATURE_SIM_OPT_FTM0_FAULT_COUNT (2) /* @brief Number of configurable FTM1 fault detection input (number of register bits SOPT4[FTM1FLTn], where n is a number starting from zero). */ #define FSL_FEATURE_SIM_OPT_FTM1_FAULT_COUNT (1) /* @brief Number of configurable FTM2 fault detection input (number of register bits SOPT4[FTM2FLTn], where n is a number starting from zero). */ #define FSL_FEATURE_SIM_OPT_FTM2_FAULT_COUNT (1) /* @brief Number of configurable FTM3 fault detection input (number of register bits SOPT4[FTM3FLTn], where n is a number starting from zero). */ #define FSL_FEATURE_SIM_OPT_FTM3_FAULT_COUNT (1) /* @brief Has FTM hardware trigger 0 software synchronization (register bit SOPT8[FTMnSYNCBIT], where n is a module instance index). */ #define FSL_FEATURE_SIM_OPT_HAS_FTM_TRIGGER_SYNC (1) /* @brief Has FTM channels output source selection (register bit SOPT8[FTMxOCHnSRC], where x is a module instance index and n is a channel index). */ #define FSL_FEATURE_SIM_OPT_HAS_FTM_CHANNELS_OUTPUT_SRC (1) /* @brief Has TPM module(s) configuration. */ #define FSL_FEATURE_SIM_OPT_HAS_TPM (0) /* @brief The highest TPM module index. */ #define FSL_FEATURE_SIM_OPT_MAX_TPM_INDEX (0) /* @brief Has TPM module with index 0. */ #define FSL_FEATURE_SIM_OPT_HAS_TPM0 (0) /* @brief Is TPM channels configuration in the SOPT4 (not SOPT9) register (register bits TPMnCH0SRC, TPMnCLKSEL, where n is a module instance index). */ #define FSL_FEATURE_SIM_OPT_HAS_TPM_CHANNELS_CONFIG_IN_SOPT4_REG (0) /* @brief Has TPM1 channel 0 input capture source selection (register bit field SOPT4[TPM1CH0SRC] or SOPT9[TPM1CH0SRC]). */ #define FSL_FEATURE_SIM_OPT_HAS_TPM1_CH0_SRC_SELECTION (0) /* @brief TPM1 channel 0 input capture source selection width (width of register bit field SOPT4[TPM1CH0SRC] or SOPT9[TPM1CH0SRC]). */ #define FSL_FEATURE_SIM_OPT_TPM1_CH0_SRC_SELECTION_WIDTH (0) /* @brief Has TPM2 channel 0 input capture source selection (register bit field SOPT4[TPM2CH0SRC]). */ #define FSL_FEATURE_SIM_OPT_HAS_TPM2_CH0_SRC_SELECTION (0) /* @brief Has TPM2 clock selection (register bit field SOPT4[TPM2CLKSEL]). */ #define FSL_FEATURE_SIM_OPT_HAS_TPM2_CLK_SEL (0) /* @brief Has PLL/FLL clock selection (register bit field SOPT2[PLLFLLSEL]). */ #define FSL_FEATURE_SIM_OPT_HAS_PLL_FLL_SELECTION (1) /* @brief PLL/FLL clock selection width (width of register bit field SOPT2[PLLFLLSEL]). */ #define FSL_FEATURE_SIM_OPT_PLL_FLL_SELECTION_WIDTH (1) /* @brief Has NFC clock source selection (register bit SOPT2[NFCSRC]). */ #define FSL_FEATURE_SIM_OPT_HAS_NFCSRC (0) /* @brief Has eSDHC clock source selection (register bit SOPT2[ESDHCSRC]). */ #define FSL_FEATURE_SIM_OPT_HAS_ESDHCSRC (0) /* @brief Has SDHC clock source selection (register bit SOPT2[SDHCSRC]). */ #define FSL_FEATURE_SIM_OPT_HAS_SDHCSRC (0) /* @brief Has LCDC clock source selection (register bits SOPT2[LCDCSRC], SOPT2[LCDC_CLKSEL]). */ #define FSL_FEATURE_SIM_OPT_HAS_LCDCSRC (0) /* @brief Has ENET timestamp clock source selection (register bit SOPT2[TIMESRC]). */ #define FSL_FEATURE_SIM_OPT_HAS_TIMESRC (0) /* @brief Has ENET RMII clock source selection (register bit SOPT2[RMIISRC]). */ #define FSL_FEATURE_SIM_OPT_HAS_RMIISRC (0) /* @brief Has USB clock source selection (register bit SOPT2[USBSRC]). */ #define FSL_FEATURE_SIM_OPT_HAS_USBSRC (0) /* @brief Has USB FS clock source selection (register bit SOPT2[USBFSRC]). */ #define FSL_FEATURE_SIM_OPT_HAS_USBFSRC (0) /* @brief Has USB HS clock source selection (register bit SOPT2[USBHSRC]). */ #define FSL_FEATURE_SIM_OPT_HAS_USBHSRC (0) /* @brief Has LPUART clock source selection (register bit SOPT2[LPUARTSRC]). */ #define FSL_FEATURE_SIM_OPT_HAS_LPUARTSRC (1) /* @brief Has LPUART0 clock source selection (register bit SOPT2[LPUART0SRC]). */ #define FSL_FEATURE_SIM_OPT_HAS_LPUART0SRC (0) /* @brief Has LPUART1 clock source selection (register bit SOPT2[LPUART1SRC]). */ #define FSL_FEATURE_SIM_OPT_HAS_LPUART1SRC (0) /* @brief Has FLEXIOSRC clock source selection (register bit SOPT2[FLEXIOSRC]). */ #define FSL_FEATURE_SIM_OPT_HAS_FLEXIOSRC (0) /* @brief Has UART0 clock source selection (register bit SOPT2[UART0SRC]). */ #define FSL_FEATURE_SIM_OPT_HAS_UART0SRC (0) /* @brief Has TPM clock source selection (register bit SOPT2[TPMSRC]). */ #define FSL_FEATURE_SIM_OPT_HAS_TPMSRC (0) /* @brief Has debug trace clock selection (register bit SOPT2[TRACECLKSEL]). */ #define FSL_FEATURE_SIM_OPT_HAS_TRACE_CLKSEL (1) /* @brief Number of ADC modules (register bits SOPT7[ADCnTRGSEL], SOPT7[ADCnPRETRGSEL], SOPT7[ADCnALTTRGSEL], where n is a module instance index). */ #define FSL_FEATURE_SIM_OPT_ADC_COUNT (2) /* @brief Has clock 2 output divider (register bit field CLKDIV1[OUTDIV2]). */ #define FSL_FEATURE_SIM_DIVIDER_HAS_OUTDIV2 (1) /* @brief Has clock 3 output divider (register bit field CLKDIV1[OUTDIV3]). */ #define FSL_FEATURE_SIM_DIVIDER_HAS_OUTDIV3 (1) /* @brief Has clock 4 output divider (register bit field CLKDIV1[OUTDIV4]). */ #define FSL_FEATURE_SIM_DIVIDER_HAS_OUTDIV4 (1) /* @brief Clock 4 output divider width (width of register bit field CLKDIV1[OUTDIV4]). */ #define FSL_FEATURE_SIM_DIVIDER_OUTDIV4_WIDTH (4) /* @brief Has USB clock divider (register bit field CLKDIV2[USBDIV] and CLKDIV2[USBFRAC]). */ #define FSL_FEATURE_SIM_DIVIDER_HAS_USBDIV (0) /* @brief Has USB FS clock divider (register bit field CLKDIV2[USBFSDIV] and CLKDIV2[USBFSFRAC]). */ #define FSL_FEATURE_SIM_DIVIDER_HAS_USBFSDIV (0) /* @brief Has USB HS clock divider (register bit field CLKDIV2[USBHSDIV] and CLKDIV2[USBHSFRAC]). */ #define FSL_FEATURE_SIM_DIVIDER_HAS_USBHSDIV (0) /* @brief Has PLL/FLL clock divider (register bit field CLKDIV3[PLLFLLDIV] and CLKDIV3[PLLFLLFRAC]). */ #define FSL_FEATURE_SIM_DIVIDER_HAS_PLLFLLDIV (0) /* @brief Has LCDC clock divider (register bit field CLKDIV3[LCDCDIV] and CLKDIV3[LCDCFRAC]). */ #define FSL_FEATURE_SIM_DIVIDER_HAS_LCDCDIV (0) /* @brief Has trace clock divider (register bit field CLKDIV4[TRACEDIV] and CLKDIV4[TRACEFRAC]). */ #define FSL_FEATURE_SIM_DIVIDER_HAS_TRACEDIV (0) /* @brief Has NFC clock divider (register bit field CLKDIV4[NFCDIV] and CLKDIV4[NFCFRAC]). */ #define FSL_FEATURE_SIM_DIVIDER_HAS_NFCDIV (0) /* @brief Has Kinetis family ID (register bit field SDID[FAMILYID]). */ #define FSL_FEATURE_SIM_SDID_HAS_FAMILYID (1) /* @brief Has Kinetis family ID (register bit field SDID[FAMID]). */ #define FSL_FEATURE_SIM_SDID_HAS_FAMID (0) /* @brief Has Kinetis sub-family ID (register bit field SDID[SUBFAMID]). */ #define FSL_FEATURE_SIM_SDID_HAS_SUBFAMID (1) /* @brief Has Kinetis series ID (register bit field SDID[SERIESID]). */ #define FSL_FEATURE_SIM_SDID_HAS_SERIESID (1) /* @brief Has device die ID (register bit field SDID[DIEID]). */ #define FSL_FEATURE_SIM_SDID_HAS_DIEID (1) /* @brief Has system SRAM size specifier (register bit field SDID[SRAMSIZE]). */ #define FSL_FEATURE_SIM_SDID_HAS_SRAMSIZE (0) /* @brief Has flash mode (register bit FCFG1[FLASHDOZE]). */ #define FSL_FEATURE_SIM_FCFG_HAS_FLASHDOZE (1) /* @brief Has flash disable (register bit FCFG1[FLASHDIS]). */ #define FSL_FEATURE_SIM_FCFG_HAS_FLASHDIS (1) /* @brief Has FTFE disable (register bit FCFG1[FTFDIS]). */ #define FSL_FEATURE_SIM_FCFG_HAS_FTFDIS (0) /* @brief Has FlexNVM size specifier (register bit field FCFG1[NVMSIZE]). */ #define FSL_FEATURE_SIM_FCFG_HAS_NVMSIZE (0) /* @brief Has EEPROM size specifier (register bit field FCFG1[EESIZE]). */ #define FSL_FEATURE_SIM_FCFG_HAS_EESIZE (0) /* @brief Has FlexNVM partition (register bit field FCFG1[DEPART]). */ #define FSL_FEATURE_SIM_FCFG_HAS_DEPART (0) /* @brief Maximum flash address block 0 address specifier (register bit field FCFG2[MAXADDR0]). */ #define FSL_FEATURE_SIM_FCFG_HAS_MAXADDR0 (1) /* @brief Maximum flash address block 1 address specifier (register bit field FCFG2[MAXADDR1]). */ #define FSL_FEATURE_SIM_FCFG_HAS_MAXADDR1 (1) /* @brief Maximum flash address block 0 or 1 address specifier (register bit field FCFG2[MAXADDR01]). */ #define FSL_FEATURE_SIM_FCFG_HAS_MAXADDR01 (0) /* @brief Maximum flash address block 2 or 3 address specifier (register bit field FCFG2[MAXADDR23]). */ #define FSL_FEATURE_SIM_FCFG_HAS_MAXADDR23 (0) /* @brief Has program flash availability specifier (register bit FCFG2[PFLSH]). */ #define FSL_FEATURE_SIM_FCFG_HAS_PFLSH (0) /* @brief Has program flash swapping (register bit FCFG2[SWAPPFLSH]). */ #define FSL_FEATURE_SIM_FCFG_HAS_PFLSH_SWAP (0) /* @brief Has miscellanious control register (register MCR). */ #define FSL_FEATURE_SIM_HAS_MISC_CONTROLS (0) /* @brief Has COP watchdog (registers COPC and SRVCOP). */ #define FSL_FEATURE_SIM_HAS_COP_WATCHDOG (0) /* @brief Has COP watchdog stop (register bits COPC[COPSTPEN], COPC[COPDBGEN] and COPC[COPCLKSEL]). */ #define FSL_FEATURE_SIM_HAS_COP_STOP (0) #elif defined(CPU_MKV40F128VLH15) || defined(CPU_MKV40F256VLH15) || defined(CPU_MKV40F64VLH15) || defined(CPU_MKV45F128VLH15) || \ defined(CPU_MKV45F256VLH15) || defined(CPU_MKV46F128VLH15) || defined(CPU_MKV46F256VLH15) /* @brief Has USB FS divider. */ #define FSL_FEATURE_SIM_USBFS_USE_SPECIAL_DIVIDER (0) /* @brief Is PLL clock divided by 2 before MCG PLL/FLL clock selection. */ #define FSL_FEATURE_SIM_PLLCLK_USE_SPECIAL_DIVIDER (0) /* @brief Has RAM size specification (register bit field SOPT1[RAMSIZE]). */ #define FSL_FEATURE_SIM_OPT_HAS_RAMSIZE (1) /* @brief Has 32k oscillator clock output (register bit SOPT1[OSC32KOUT]). */ #define FSL_FEATURE_SIM_OPT_HAS_OSC32K_OUT (0) /* @brief Has 32k oscillator clock selection (register bit field SOPT1[OSC32KSEL]). */ #define FSL_FEATURE_SIM_OPT_HAS_OSC32K_SELECTION (1) /* @brief 32k oscillator clock selection width (width of register bit field SOPT1[OSC32KSEL]). */ #define FSL_FEATURE_SIM_OPT_OSC32K_SELECTION_WIDTH (2) /* @brief Has RTC clock output selection (register bit SOPT2[RTCCLKOUTSEL]). */ #define FSL_FEATURE_SIM_OPT_HAS_RTC_CLOCK_OUT_SELECTION (0) /* @brief Has USB voltage regulator (register bits SOPT1[USBVSTBY], SOPT1[USBSSTBY], SOPT1[USBREGEN], SOPT1CFG[URWE], SOPT1CFG[UVSWE], SOPT1CFG[USSWE]). */ #define FSL_FEATURE_SIM_OPT_HAS_USB_VOLTAGE_REGULATOR (0) /* @brief USB has integrated PHY (register bits USBPHYCTL[USBVREGSEL], USBPHYCTL[USBVREGPD], USBPHYCTL[USB3VOUTTRG], USBPHYCTL[USBDISILIM], SOPT2[USBSLSRC], SOPT2[USBREGEN]). */ #define FSL_FEATURE_SIM_OPT_HAS_USB_PHY (0) /* @brief Has PTD7 pad drive strength control (register bit SOPT2[PTD7PAD]). */ #define FSL_FEATURE_SIM_OPT_HAS_PTD7PAD (0) /* @brief Has FlexBus security level selection (register bit SOPT2[FBSL]). */ #define FSL_FEATURE_SIM_OPT_HAS_FBSL (0) /* @brief Has number of FlexBus hold cycle before FlexBus can release bus (register bit SOPT6[PCR]). */ #define FSL_FEATURE_SIM_OPT_HAS_PCR (0) /* @brief Has number of NFC hold cycle in case of FlexBus request (register bit SOPT6[MCC]). */ #define FSL_FEATURE_SIM_OPT_HAS_MCC (0) /* @brief Has UART open drain enable (register bits UARTnODE, where n is a number, in register SOPT5). */ #define FSL_FEATURE_SIM_OPT_HAS_ODE (0) /* @brief Number of UART modules (number of register bits UARTn, where n is a number, in register SCGC4). */ #define FSL_FEATURE_SIM_OPT_UART_COUNT (2) /* @brief Has LPUART0 open drain enable (register bit SOPT5[LPUART0ODE]). */ #define FSL_FEATURE_SIM_OPT_HAS_LPUART0_ODE (0) /* @brief Has LPUART1 open drain enable (register bit SOPT5[LPUART1ODE]). */ #define FSL_FEATURE_SIM_OPT_HAS_LPUART1_ODE (0) /* @brief Has CMT/UART pad drive strength control (register bit SOPT2[CMTUARTPAD]). */ #define FSL_FEATURE_SIM_OPT_HAS_CMTUARTPAD (0) /* @brief Has LPUART0 transmit data source selection (register bit SOPT5[LPUART0TXSRC]). */ #define FSL_FEATURE_SIM_OPT_HAS_LPUART0_TX_SRC (0) /* @brief Has LPUART0 receive data source selection (register bit SOPT5[LPUART0RXSRC]). */ #define FSL_FEATURE_SIM_OPT_HAS_LPUART0_RX_SRC (0) /* @brief Has LPUART1 transmit data source selection (register bit SOPT5[LPUART1TXSRC]). */ #define FSL_FEATURE_SIM_OPT_HAS_LPUART1_TX_SRC (0) /* @brief Has LPUART1 receive data source selection (register bit SOPT5[LPUART1RXSRC]). */ #define FSL_FEATURE_SIM_OPT_HAS_LPUART1_RX_SRC (0) /* @brief Has UART0 transmit data source selection (register bit SOPT5[UART0TXSRC]). */ #define FSL_FEATURE_SIM_OPT_HAS_UART0_TX_SRC (1) /* @brief UART0 transmit data source selection width (width of register bit SOPT5[UART0TXSRC]). */ #define FSL_FEATURE_SIM_OPT_UART0_TX_SRC_WIDTH (1) /* @brief Has UART0 receive data source selection (register bit SOPT5[UART0RXSRC]). */ #define FSL_FEATURE_SIM_OPT_HAS_UART0_RX_SRC (1) /* @brief UART0 receive data source selection width (width of register bit SOPT5[UART0RXSRC]). */ #define FSL_FEATURE_SIM_OPT_UART0_RX_SRC_WIDTH (2) /* @brief Has UART1 transmit data source selection (register bit SOPT5[UART1TXSRC]). */ #define FSL_FEATURE_SIM_OPT_HAS_UART1_TX_SRC (1) /* @brief Has UART1 receive data source selection (register bit SOPT5[UART1RXSRC]). */ #define FSL_FEATURE_SIM_OPT_HAS_UART1_RX_SRC (1) /* @brief UART1 receive data source selection width (width of register bit SOPT5[UART1RXSRC]). */ #define FSL_FEATURE_SIM_OPT_UART1_RX_SRC_WIDTH (2) /* @brief Has FTM module(s) configuration. */ #define FSL_FEATURE_SIM_OPT_HAS_FTM (1) /* @brief Number of FTM modules. */ #define FSL_FEATURE_SIM_OPT_FTM_COUNT (2) /* @brief Number of FTM triggers with selectable source. */ #define FSL_FEATURE_SIM_OPT_FTM_TRIGGER_COUNT (2) /* @brief Has FTM0 triggers source selection (register bits SOPT4[FTM0TRGnSRC], where n is a number). */ #define FSL_FEATURE_SIM_OPT_HAS_FTM0_TRIGGER (1) /* @brief Has FTM3 triggers source selection (register bits SOPT4[FTM3TRGnSRC], where n is a number). */ #define FSL_FEATURE_SIM_OPT_HAS_FTM3_TRIGGER (1) /* @brief Has FTM1 channel 0 input capture source selection (register bit SOPT4[FTM1CH0SRC]). */ #define FSL_FEATURE_SIM_OPT_HAS_FTM1_CHANNELS (0) /* @brief Has FTM2 channel 0 input capture source selection (register bit SOPT4[FTM2CH0SRC]). */ #define FSL_FEATURE_SIM_OPT_HAS_FTM2_CHANNELS (0) /* @brief Has FTM3 channel 0 input capture source selection (register bit SOPT4[FTM3CH0SRC]). */ #define FSL_FEATURE_SIM_OPT_HAS_FTM3_CHANNELS (0) /* @brief Has FTM2 channel 1 input capture source selection (register bit SOPT4[FTM2CH1SRC]). */ #define FSL_FEATURE_SIM_OPT_HAS_FTM2_CHANNEL1 (0) /* @brief Number of configurable FTM0 fault detection input (number of register bits SOPT4[FTM0FLTn], where n is a number starting from zero). */ #define FSL_FEATURE_SIM_OPT_FTM0_FAULT_COUNT (4) /* @brief Number of configurable FTM1 fault detection input (number of register bits SOPT4[FTM1FLTn], where n is a number starting from zero). */ #define FSL_FEATURE_SIM_OPT_FTM1_FAULT_COUNT (1) /* @brief Number of configurable FTM2 fault detection input (number of register bits SOPT4[FTM2FLTn], where n is a number starting from zero). */ #define FSL_FEATURE_SIM_OPT_FTM2_FAULT_COUNT (0) /* @brief Number of configurable FTM3 fault detection input (number of register bits SOPT4[FTM3FLTn], where n is a number starting from zero). */ #define FSL_FEATURE_SIM_OPT_FTM3_FAULT_COUNT (1) /* @brief Has FTM hardware trigger 0 software synchronization (register bit SOPT8[FTMnSYNCBIT], where n is a module instance index). */ #define FSL_FEATURE_SIM_OPT_HAS_FTM_TRIGGER_SYNC (1) /* @brief Has FTM channels output source selection (register bit SOPT8[FTMxOCHnSRC], where x is a module instance index and n is a channel index). */ #define FSL_FEATURE_SIM_OPT_HAS_FTM_CHANNELS_OUTPUT_SRC (1) /* @brief Has TPM module(s) configuration. */ #define FSL_FEATURE_SIM_OPT_HAS_TPM (0) /* @brief The highest TPM module index. */ #define FSL_FEATURE_SIM_OPT_MAX_TPM_INDEX (0) /* @brief Has TPM module with index 0. */ #define FSL_FEATURE_SIM_OPT_HAS_TPM0 (0) /* @brief Is TPM channels configuration in the SOPT4 (not SOPT9) register (register bits TPMnCH0SRC, TPMnCLKSEL, where n is a module instance index). */ #define FSL_FEATURE_SIM_OPT_HAS_TPM_CHANNELS_CONFIG_IN_SOPT4_REG (0) /* @brief Has TPM1 channel 0 input capture source selection (register bit field SOPT4[TPM1CH0SRC] or SOPT9[TPM1CH0SRC]). */ #define FSL_FEATURE_SIM_OPT_HAS_TPM1_CH0_SRC_SELECTION (0) /* @brief TPM1 channel 0 input capture source selection width (width of register bit field SOPT4[TPM1CH0SRC] or SOPT9[TPM1CH0SRC]). */ #define FSL_FEATURE_SIM_OPT_TPM1_CH0_SRC_SELECTION_WIDTH (0) /* @brief Has TPM2 channel 0 input capture source selection (register bit field SOPT4[TPM2CH0SRC]). */ #define FSL_FEATURE_SIM_OPT_HAS_TPM2_CH0_SRC_SELECTION (0) /* @brief Has TPM2 clock selection (register bit field SOPT4[TPM2CLKSEL]). */ #define FSL_FEATURE_SIM_OPT_HAS_TPM2_CLK_SEL (0) /* @brief Has PLL/FLL clock selection (register bit field SOPT2[PLLFLLSEL]). */ #define FSL_FEATURE_SIM_OPT_HAS_PLL_FLL_SELECTION (0) /* @brief PLL/FLL clock selection width (width of register bit field SOPT2[PLLFLLSEL]). */ #define FSL_FEATURE_SIM_OPT_PLL_FLL_SELECTION_WIDTH (0) /* @brief Has NFC clock source selection (register bit SOPT2[NFCSRC]). */ #define FSL_FEATURE_SIM_OPT_HAS_NFCSRC (0) /* @brief Has eSDHC clock source selection (register bit SOPT2[ESDHCSRC]). */ #define FSL_FEATURE_SIM_OPT_HAS_ESDHCSRC (0) /* @brief Has SDHC clock source selection (register bit SOPT2[SDHCSRC]). */ #define FSL_FEATURE_SIM_OPT_HAS_SDHCSRC (0) /* @brief Has LCDC clock source selection (register bits SOPT2[LCDCSRC], SOPT2[LCDC_CLKSEL]). */ #define FSL_FEATURE_SIM_OPT_HAS_LCDCSRC (0) /* @brief Has ENET timestamp clock source selection (register bit SOPT2[TIMESRC]). */ #define FSL_FEATURE_SIM_OPT_HAS_TIMESRC (0) /* @brief Has ENET RMII clock source selection (register bit SOPT2[RMIISRC]). */ #define FSL_FEATURE_SIM_OPT_HAS_RMIISRC (0) /* @brief Has USB clock source selection (register bit SOPT2[USBSRC]). */ #define FSL_FEATURE_SIM_OPT_HAS_USBSRC (0) /* @brief Has USB FS clock source selection (register bit SOPT2[USBFSRC]). */ #define FSL_FEATURE_SIM_OPT_HAS_USBFSRC (0) /* @brief Has USB HS clock source selection (register bit SOPT2[USBHSRC]). */ #define FSL_FEATURE_SIM_OPT_HAS_USBHSRC (0) /* @brief Has LPUART clock source selection (register bit SOPT2[LPUARTSRC]). */ #define FSL_FEATURE_SIM_OPT_HAS_LPUARTSRC (0) /* @brief Has LPUART0 clock source selection (register bit SOPT2[LPUART0SRC]). */ #define FSL_FEATURE_SIM_OPT_HAS_LPUART0SRC (0) /* @brief Has LPUART1 clock source selection (register bit SOPT2[LPUART1SRC]). */ #define FSL_FEATURE_SIM_OPT_HAS_LPUART1SRC (0) /* @brief Has FLEXIOSRC clock source selection (register bit SOPT2[FLEXIOSRC]). */ #define FSL_FEATURE_SIM_OPT_HAS_FLEXIOSRC (0) /* @brief Has UART0 clock source selection (register bit SOPT2[UART0SRC]). */ #define FSL_FEATURE_SIM_OPT_HAS_UART0SRC (0) /* @brief Has TPM clock source selection (register bit SOPT2[TPMSRC]). */ #define FSL_FEATURE_SIM_OPT_HAS_TPMSRC (0) /* @brief Has debug trace clock selection (register bit SOPT2[TRACECLKSEL]). */ #define FSL_FEATURE_SIM_OPT_HAS_TRACE_CLKSEL (1) /* @brief Number of ADC modules (register bits SOPT7[ADCnTRGSEL], SOPT7[ADCnPRETRGSEL], SOPT7[ADCnALTTRGSEL], where n is a module instance index). */ #define FSL_FEATURE_SIM_OPT_ADC_COUNT (1) /* @brief Has clock 2 output divider (register bit field CLKDIV1[OUTDIV2]). */ #define FSL_FEATURE_SIM_DIVIDER_HAS_OUTDIV2 (1) /* @brief Has clock 3 output divider (register bit field CLKDIV1[OUTDIV3]). */ #define FSL_FEATURE_SIM_DIVIDER_HAS_OUTDIV3 (0) /* @brief Has clock 4 output divider (register bit field CLKDIV1[OUTDIV4]). */ #define FSL_FEATURE_SIM_DIVIDER_HAS_OUTDIV4 (1) /* @brief Clock 4 output divider width (width of register bit field CLKDIV1[OUTDIV4]). */ #define FSL_FEATURE_SIM_DIVIDER_OUTDIV4_WIDTH (4) /* @brief Has USB clock divider (register bit field CLKDIV2[USBDIV] and CLKDIV2[USBFRAC]). */ #define FSL_FEATURE_SIM_DIVIDER_HAS_USBDIV (0) /* @brief Has USB FS clock divider (register bit field CLKDIV2[USBFSDIV] and CLKDIV2[USBFSFRAC]). */ #define FSL_FEATURE_SIM_DIVIDER_HAS_USBFSDIV (0) /* @brief Has USB HS clock divider (register bit field CLKDIV2[USBHSDIV] and CLKDIV2[USBHSFRAC]). */ #define FSL_FEATURE_SIM_DIVIDER_HAS_USBHSDIV (0) /* @brief Has PLL/FLL clock divider (register bit field CLKDIV3[PLLFLLDIV] and CLKDIV3[PLLFLLFRAC]). */ #define FSL_FEATURE_SIM_DIVIDER_HAS_PLLFLLDIV (0) /* @brief Has LCDC clock divider (register bit field CLKDIV3[LCDCDIV] and CLKDIV3[LCDCFRAC]). */ #define FSL_FEATURE_SIM_DIVIDER_HAS_LCDCDIV (0) /* @brief Has trace clock divider (register bit field CLKDIV4[TRACEDIV] and CLKDIV4[TRACEFRAC]). */ #define FSL_FEATURE_SIM_DIVIDER_HAS_TRACEDIV (1) /* @brief Has NFC clock divider (register bit field CLKDIV4[NFCDIV] and CLKDIV4[NFCFRAC]). */ #define FSL_FEATURE_SIM_DIVIDER_HAS_NFCDIV (0) /* @brief Has Kinetis family ID (register bit field SDID[FAMILYID]). */ #define FSL_FEATURE_SIM_SDID_HAS_FAMILYID (1) /* @brief Has Kinetis family ID (register bit field SDID[FAMID]). */ #define FSL_FEATURE_SIM_SDID_HAS_FAMID (0) /* @brief Has Kinetis sub-family ID (register bit field SDID[SUBFAMID]). */ #define FSL_FEATURE_SIM_SDID_HAS_SUBFAMID (1) /* @brief Has Kinetis series ID (register bit field SDID[SERIESID]). */ #define FSL_FEATURE_SIM_SDID_HAS_SERIESID (1) /* @brief Has device die ID (register bit field SDID[DIEID]). */ #define FSL_FEATURE_SIM_SDID_HAS_DIEID (1) /* @brief Has system SRAM size specifier (register bit field SDID[SRAMSIZE]). */ #define FSL_FEATURE_SIM_SDID_HAS_SRAMSIZE (0) /* @brief Has flash mode (register bit FCFG1[FLASHDOZE]). */ #define FSL_FEATURE_SIM_FCFG_HAS_FLASHDOZE (1) /* @brief Has flash disable (register bit FCFG1[FLASHDIS]). */ #define FSL_FEATURE_SIM_FCFG_HAS_FLASHDIS (1) /* @brief Has FTFE disable (register bit FCFG1[FTFDIS]). */ #define FSL_FEATURE_SIM_FCFG_HAS_FTFDIS (0) /* @brief Has FlexNVM size specifier (register bit field FCFG1[NVMSIZE]). */ #define FSL_FEATURE_SIM_FCFG_HAS_NVMSIZE (0) /* @brief Has EEPROM size specifier (register bit field FCFG1[EESIZE]). */ #define FSL_FEATURE_SIM_FCFG_HAS_EESIZE (0) /* @brief Has FlexNVM partition (register bit field FCFG1[DEPART]). */ #define FSL_FEATURE_SIM_FCFG_HAS_DEPART (0) /* @brief Maximum flash address block 0 address specifier (register bit field FCFG2[MAXADDR0]). */ #define FSL_FEATURE_SIM_FCFG_HAS_MAXADDR0 (1) /* @brief Maximum flash address block 1 address specifier (register bit field FCFG2[MAXADDR1]). */ #define FSL_FEATURE_SIM_FCFG_HAS_MAXADDR1 (0) /* @brief Maximum flash address block 0 or 1 address specifier (register bit field FCFG2[MAXADDR01]). */ #define FSL_FEATURE_SIM_FCFG_HAS_MAXADDR01 (0) /* @brief Maximum flash address block 2 or 3 address specifier (register bit field FCFG2[MAXADDR23]). */ #define FSL_FEATURE_SIM_FCFG_HAS_MAXADDR23 (0) /* @brief Has program flash availability specifier (register bit FCFG2[PFLSH]). */ #define FSL_FEATURE_SIM_FCFG_HAS_PFLSH (0) /* @brief Has program flash swapping (register bit FCFG2[SWAPPFLSH]). */ #define FSL_FEATURE_SIM_FCFG_HAS_PFLSH_SWAP (0) /* @brief Has miscellanious control register (register MCR). */ #define FSL_FEATURE_SIM_HAS_MISC_CONTROLS (0) /* @brief Has COP watchdog (registers COPC and SRVCOP). */ #define FSL_FEATURE_SIM_HAS_COP_WATCHDOG (0) /* @brief Has COP watchdog stop (register bits COPC[COPSTPEN], COPC[COPDBGEN] and COPC[COPCLKSEL]). */ #define FSL_FEATURE_SIM_HAS_COP_STOP (0) #elif defined(CPU_MKV40F128VLL15) || defined(CPU_MKV40F256VLL15) || defined(CPU_MKV45F128VLL15) || defined(CPU_MKV45F256VLL15) || \ defined(CPU_MKV46F128VLL15) || defined(CPU_MKV46F256VLL15) /* @brief Has USB FS divider. */ #define FSL_FEATURE_SIM_USBFS_USE_SPECIAL_DIVIDER (0) /* @brief Is PLL clock divided by 2 before MCG PLL/FLL clock selection. */ #define FSL_FEATURE_SIM_PLLCLK_USE_SPECIAL_DIVIDER (0) /* @brief Has RAM size specification (register bit field SOPT1[RAMSIZE]). */ #define FSL_FEATURE_SIM_OPT_HAS_RAMSIZE (1) /* @brief Has 32k oscillator clock output (register bit SOPT1[OSC32KOUT]). */ #define FSL_FEATURE_SIM_OPT_HAS_OSC32K_OUT (0) /* @brief Has 32k oscillator clock selection (register bit field SOPT1[OSC32KSEL]). */ #define FSL_FEATURE_SIM_OPT_HAS_OSC32K_SELECTION (1) /* @brief 32k oscillator clock selection width (width of register bit field SOPT1[OSC32KSEL]). */ #define FSL_FEATURE_SIM_OPT_OSC32K_SELECTION_WIDTH (2) /* @brief Has RTC clock output selection (register bit SOPT2[RTCCLKOUTSEL]). */ #define FSL_FEATURE_SIM_OPT_HAS_RTC_CLOCK_OUT_SELECTION (0) /* @brief Has USB voltage regulator (register bits SOPT1[USBVSTBY], SOPT1[USBSSTBY], SOPT1[USBREGEN], SOPT1CFG[URWE], SOPT1CFG[UVSWE], SOPT1CFG[USSWE]). */ #define FSL_FEATURE_SIM_OPT_HAS_USB_VOLTAGE_REGULATOR (0) /* @brief USB has integrated PHY (register bits USBPHYCTL[USBVREGSEL], USBPHYCTL[USBVREGPD], USBPHYCTL[USB3VOUTTRG], USBPHYCTL[USBDISILIM], SOPT2[USBSLSRC], SOPT2[USBREGEN]). */ #define FSL_FEATURE_SIM_OPT_HAS_USB_PHY (0) /* @brief Has PTD7 pad drive strength control (register bit SOPT2[PTD7PAD]). */ #define FSL_FEATURE_SIM_OPT_HAS_PTD7PAD (0) /* @brief Has FlexBus security level selection (register bit SOPT2[FBSL]). */ #define FSL_FEATURE_SIM_OPT_HAS_FBSL (0) /* @brief Has number of FlexBus hold cycle before FlexBus can release bus (register bit SOPT6[PCR]). */ #define FSL_FEATURE_SIM_OPT_HAS_PCR (0) /* @brief Has number of NFC hold cycle in case of FlexBus request (register bit SOPT6[MCC]). */ #define FSL_FEATURE_SIM_OPT_HAS_MCC (0) /* @brief Has UART open drain enable (register bits UARTnODE, where n is a number, in register SOPT5). */ #define FSL_FEATURE_SIM_OPT_HAS_ODE (0) /* @brief Number of UART modules (number of register bits UARTn, where n is a number, in register SCGC4). */ #define FSL_FEATURE_SIM_OPT_UART_COUNT (2) /* @brief Has LPUART0 open drain enable (register bit SOPT5[LPUART0ODE]). */ #define FSL_FEATURE_SIM_OPT_HAS_LPUART0_ODE (0) /* @brief Has LPUART1 open drain enable (register bit SOPT5[LPUART1ODE]). */ #define FSL_FEATURE_SIM_OPT_HAS_LPUART1_ODE (0) /* @brief Has CMT/UART pad drive strength control (register bit SOPT2[CMTUARTPAD]). */ #define FSL_FEATURE_SIM_OPT_HAS_CMTUARTPAD (0) /* @brief Has LPUART0 transmit data source selection (register bit SOPT5[LPUART0TXSRC]). */ #define FSL_FEATURE_SIM_OPT_HAS_LPUART0_TX_SRC (0) /* @brief Has LPUART0 receive data source selection (register bit SOPT5[LPUART0RXSRC]). */ #define FSL_FEATURE_SIM_OPT_HAS_LPUART0_RX_SRC (0) /* @brief Has LPUART1 transmit data source selection (register bit SOPT5[LPUART1TXSRC]). */ #define FSL_FEATURE_SIM_OPT_HAS_LPUART1_TX_SRC (0) /* @brief Has LPUART1 receive data source selection (register bit SOPT5[LPUART1RXSRC]). */ #define FSL_FEATURE_SIM_OPT_HAS_LPUART1_RX_SRC (0) /* @brief Has UART0 transmit data source selection (register bit SOPT5[UART0TXSRC]). */ #define FSL_FEATURE_SIM_OPT_HAS_UART0_TX_SRC (1) /* @brief UART0 transmit data source selection width (width of register bit SOPT5[UART0TXSRC]). */ #define FSL_FEATURE_SIM_OPT_UART0_TX_SRC_WIDTH (1) /* @brief Has UART0 receive data source selection (register bit SOPT5[UART0RXSRC]). */ #define FSL_FEATURE_SIM_OPT_HAS_UART0_RX_SRC (1) /* @brief UART0 receive data source selection width (width of register bit SOPT5[UART0RXSRC]). */ #define FSL_FEATURE_SIM_OPT_UART0_RX_SRC_WIDTH (2) /* @brief Has UART1 transmit data source selection (register bit SOPT5[UART1TXSRC]). */ #define FSL_FEATURE_SIM_OPT_HAS_UART1_TX_SRC (1) /* @brief Has UART1 receive data source selection (register bit SOPT5[UART1RXSRC]). */ #define FSL_FEATURE_SIM_OPT_HAS_UART1_RX_SRC (1) /* @brief UART1 receive data source selection width (width of register bit SOPT5[UART1RXSRC]). */ #define FSL_FEATURE_SIM_OPT_UART1_RX_SRC_WIDTH (2) /* @brief Has FTM module(s) configuration. */ #define FSL_FEATURE_SIM_OPT_HAS_FTM (1) /* @brief Number of FTM modules. */ #define FSL_FEATURE_SIM_OPT_FTM_COUNT (3) /* @brief Number of FTM triggers with selectable source. */ #define FSL_FEATURE_SIM_OPT_FTM_TRIGGER_COUNT (2) /* @brief Has FTM0 triggers source selection (register bits SOPT4[FTM0TRGnSRC], where n is a number). */ #define FSL_FEATURE_SIM_OPT_HAS_FTM0_TRIGGER (1) /* @brief Has FTM3 triggers source selection (register bits SOPT4[FTM3TRGnSRC], where n is a number). */ #define FSL_FEATURE_SIM_OPT_HAS_FTM3_TRIGGER (1) /* @brief Has FTM1 channel 0 input capture source selection (register bit SOPT4[FTM1CH0SRC]). */ #define FSL_FEATURE_SIM_OPT_HAS_FTM1_CHANNELS (0) /* @brief Has FTM2 channel 0 input capture source selection (register bit SOPT4[FTM2CH0SRC]). */ #define FSL_FEATURE_SIM_OPT_HAS_FTM2_CHANNELS (0) /* @brief Has FTM3 channel 0 input capture source selection (register bit SOPT4[FTM3CH0SRC]). */ #define FSL_FEATURE_SIM_OPT_HAS_FTM3_CHANNELS (0) /* @brief Has FTM2 channel 1 input capture source selection (register bit SOPT4[FTM2CH1SRC]). */ #define FSL_FEATURE_SIM_OPT_HAS_FTM2_CHANNEL1 (0) /* @brief Number of configurable FTM0 fault detection input (number of register bits SOPT4[FTM0FLTn], where n is a number starting from zero). */ #define FSL_FEATURE_SIM_OPT_FTM0_FAULT_COUNT (4) /* @brief Number of configurable FTM1 fault detection input (number of register bits SOPT4[FTM1FLTn], where n is a number starting from zero). */ #define FSL_FEATURE_SIM_OPT_FTM1_FAULT_COUNT (1) /* @brief Number of configurable FTM2 fault detection input (number of register bits SOPT4[FTM2FLTn], where n is a number starting from zero). */ #define FSL_FEATURE_SIM_OPT_FTM2_FAULT_COUNT (0) /* @brief Number of configurable FTM3 fault detection input (number of register bits SOPT4[FTM3FLTn], where n is a number starting from zero). */ #define FSL_FEATURE_SIM_OPT_FTM3_FAULT_COUNT (1) /* @brief Has FTM hardware trigger 0 software synchronization (register bit SOPT8[FTMnSYNCBIT], where n is a module instance index). */ #define FSL_FEATURE_SIM_OPT_HAS_FTM_TRIGGER_SYNC (1) /* @brief Has FTM channels output source selection (register bit SOPT8[FTMxOCHnSRC], where x is a module instance index and n is a channel index). */ #define FSL_FEATURE_SIM_OPT_HAS_FTM_CHANNELS_OUTPUT_SRC (1) /* @brief Has TPM module(s) configuration. */ #define FSL_FEATURE_SIM_OPT_HAS_TPM (0) /* @brief The highest TPM module index. */ #define FSL_FEATURE_SIM_OPT_MAX_TPM_INDEX (0) /* @brief Has TPM module with index 0. */ #define FSL_FEATURE_SIM_OPT_HAS_TPM0 (0) /* @brief Is TPM channels configuration in the SOPT4 (not SOPT9) register (register bits TPMnCH0SRC, TPMnCLKSEL, where n is a module instance index). */ #define FSL_FEATURE_SIM_OPT_HAS_TPM_CHANNELS_CONFIG_IN_SOPT4_REG (0) /* @brief Has TPM1 channel 0 input capture source selection (register bit field SOPT4[TPM1CH0SRC] or SOPT9[TPM1CH0SRC]). */ #define FSL_FEATURE_SIM_OPT_HAS_TPM1_CH0_SRC_SELECTION (0) /* @brief TPM1 channel 0 input capture source selection width (width of register bit field SOPT4[TPM1CH0SRC] or SOPT9[TPM1CH0SRC]). */ #define FSL_FEATURE_SIM_OPT_TPM1_CH0_SRC_SELECTION_WIDTH (0) /* @brief Has TPM2 channel 0 input capture source selection (register bit field SOPT4[TPM2CH0SRC]). */ #define FSL_FEATURE_SIM_OPT_HAS_TPM2_CH0_SRC_SELECTION (0) /* @brief Has TPM2 clock selection (register bit field SOPT4[TPM2CLKSEL]). */ #define FSL_FEATURE_SIM_OPT_HAS_TPM2_CLK_SEL (0) /* @brief Has PLL/FLL clock selection (register bit field SOPT2[PLLFLLSEL]). */ #define FSL_FEATURE_SIM_OPT_HAS_PLL_FLL_SELECTION (0) /* @brief PLL/FLL clock selection width (width of register bit field SOPT2[PLLFLLSEL]). */ #define FSL_FEATURE_SIM_OPT_PLL_FLL_SELECTION_WIDTH (0) /* @brief Has NFC clock source selection (register bit SOPT2[NFCSRC]). */ #define FSL_FEATURE_SIM_OPT_HAS_NFCSRC (0) /* @brief Has eSDHC clock source selection (register bit SOPT2[ESDHCSRC]). */ #define FSL_FEATURE_SIM_OPT_HAS_ESDHCSRC (0) /* @brief Has SDHC clock source selection (register bit SOPT2[SDHCSRC]). */ #define FSL_FEATURE_SIM_OPT_HAS_SDHCSRC (0) /* @brief Has LCDC clock source selection (register bits SOPT2[LCDCSRC], SOPT2[LCDC_CLKSEL]). */ #define FSL_FEATURE_SIM_OPT_HAS_LCDCSRC (0) /* @brief Has ENET timestamp clock source selection (register bit SOPT2[TIMESRC]). */ #define FSL_FEATURE_SIM_OPT_HAS_TIMESRC (0) /* @brief Has ENET RMII clock source selection (register bit SOPT2[RMIISRC]). */ #define FSL_FEATURE_SIM_OPT_HAS_RMIISRC (0) /* @brief Has USB clock source selection (register bit SOPT2[USBSRC]). */ #define FSL_FEATURE_SIM_OPT_HAS_USBSRC (0) /* @brief Has USB FS clock source selection (register bit SOPT2[USBFSRC]). */ #define FSL_FEATURE_SIM_OPT_HAS_USBFSRC (0) /* @brief Has USB HS clock source selection (register bit SOPT2[USBHSRC]). */ #define FSL_FEATURE_SIM_OPT_HAS_USBHSRC (0) /* @brief Has LPUART clock source selection (register bit SOPT2[LPUARTSRC]). */ #define FSL_FEATURE_SIM_OPT_HAS_LPUARTSRC (0) /* @brief Has LPUART0 clock source selection (register bit SOPT2[LPUART0SRC]). */ #define FSL_FEATURE_SIM_OPT_HAS_LPUART0SRC (0) /* @brief Has LPUART1 clock source selection (register bit SOPT2[LPUART1SRC]). */ #define FSL_FEATURE_SIM_OPT_HAS_LPUART1SRC (0) /* @brief Has FLEXIOSRC clock source selection (register bit SOPT2[FLEXIOSRC]). */ #define FSL_FEATURE_SIM_OPT_HAS_FLEXIOSRC (0) /* @brief Has UART0 clock source selection (register bit SOPT2[UART0SRC]). */ #define FSL_FEATURE_SIM_OPT_HAS_UART0SRC (0) /* @brief Has TPM clock source selection (register bit SOPT2[TPMSRC]). */ #define FSL_FEATURE_SIM_OPT_HAS_TPMSRC (0) /* @brief Has debug trace clock selection (register bit SOPT2[TRACECLKSEL]). */ #define FSL_FEATURE_SIM_OPT_HAS_TRACE_CLKSEL (1) /* @brief Number of ADC modules (register bits SOPT7[ADCnTRGSEL], SOPT7[ADCnPRETRGSEL], SOPT7[ADCnALTTRGSEL], where n is a module instance index). */ #define FSL_FEATURE_SIM_OPT_ADC_COUNT (1) /* @brief Has clock 2 output divider (register bit field CLKDIV1[OUTDIV2]). */ #define FSL_FEATURE_SIM_DIVIDER_HAS_OUTDIV2 (1) /* @brief Has clock 3 output divider (register bit field CLKDIV1[OUTDIV3]). */ #define FSL_FEATURE_SIM_DIVIDER_HAS_OUTDIV3 (0) /* @brief Has clock 4 output divider (register bit field CLKDIV1[OUTDIV4]). */ #define FSL_FEATURE_SIM_DIVIDER_HAS_OUTDIV4 (1) /* @brief Clock 4 output divider width (width of register bit field CLKDIV1[OUTDIV4]). */ #define FSL_FEATURE_SIM_DIVIDER_OUTDIV4_WIDTH (4) /* @brief Has USB clock divider (register bit field CLKDIV2[USBDIV] and CLKDIV2[USBFRAC]). */ #define FSL_FEATURE_SIM_DIVIDER_HAS_USBDIV (0) /* @brief Has USB FS clock divider (register bit field CLKDIV2[USBFSDIV] and CLKDIV2[USBFSFRAC]). */ #define FSL_FEATURE_SIM_DIVIDER_HAS_USBFSDIV (0) /* @brief Has USB HS clock divider (register bit field CLKDIV2[USBHSDIV] and CLKDIV2[USBHSFRAC]). */ #define FSL_FEATURE_SIM_DIVIDER_HAS_USBHSDIV (0) /* @brief Has PLL/FLL clock divider (register bit field CLKDIV3[PLLFLLDIV] and CLKDIV3[PLLFLLFRAC]). */ #define FSL_FEATURE_SIM_DIVIDER_HAS_PLLFLLDIV (0) /* @brief Has LCDC clock divider (register bit field CLKDIV3[LCDCDIV] and CLKDIV3[LCDCFRAC]). */ #define FSL_FEATURE_SIM_DIVIDER_HAS_LCDCDIV (0) /* @brief Has trace clock divider (register bit field CLKDIV4[TRACEDIV] and CLKDIV4[TRACEFRAC]). */ #define FSL_FEATURE_SIM_DIVIDER_HAS_TRACEDIV (1) /* @brief Has NFC clock divider (register bit field CLKDIV4[NFCDIV] and CLKDIV4[NFCFRAC]). */ #define FSL_FEATURE_SIM_DIVIDER_HAS_NFCDIV (0) /* @brief Has Kinetis family ID (register bit field SDID[FAMILYID]). */ #define FSL_FEATURE_SIM_SDID_HAS_FAMILYID (1) /* @brief Has Kinetis family ID (register bit field SDID[FAMID]). */ #define FSL_FEATURE_SIM_SDID_HAS_FAMID (0) /* @brief Has Kinetis sub-family ID (register bit field SDID[SUBFAMID]). */ #define FSL_FEATURE_SIM_SDID_HAS_SUBFAMID (1) /* @brief Has Kinetis series ID (register bit field SDID[SERIESID]). */ #define FSL_FEATURE_SIM_SDID_HAS_SERIESID (1) /* @brief Has device die ID (register bit field SDID[DIEID]). */ #define FSL_FEATURE_SIM_SDID_HAS_DIEID (1) /* @brief Has system SRAM size specifier (register bit field SDID[SRAMSIZE]). */ #define FSL_FEATURE_SIM_SDID_HAS_SRAMSIZE (0) /* @brief Has flash mode (register bit FCFG1[FLASHDOZE]). */ #define FSL_FEATURE_SIM_FCFG_HAS_FLASHDOZE (1) /* @brief Has flash disable (register bit FCFG1[FLASHDIS]). */ #define FSL_FEATURE_SIM_FCFG_HAS_FLASHDIS (1) /* @brief Has FTFE disable (register bit FCFG1[FTFDIS]). */ #define FSL_FEATURE_SIM_FCFG_HAS_FTFDIS (0) /* @brief Has FlexNVM size specifier (register bit field FCFG1[NVMSIZE]). */ #define FSL_FEATURE_SIM_FCFG_HAS_NVMSIZE (0) /* @brief Has EEPROM size specifier (register bit field FCFG1[EESIZE]). */ #define FSL_FEATURE_SIM_FCFG_HAS_EESIZE (0) /* @brief Has FlexNVM partition (register bit field FCFG1[DEPART]). */ #define FSL_FEATURE_SIM_FCFG_HAS_DEPART (0) /* @brief Maximum flash address block 0 address specifier (register bit field FCFG2[MAXADDR0]). */ #define FSL_FEATURE_SIM_FCFG_HAS_MAXADDR0 (1) /* @brief Maximum flash address block 1 address specifier (register bit field FCFG2[MAXADDR1]). */ #define FSL_FEATURE_SIM_FCFG_HAS_MAXADDR1 (0) /* @brief Maximum flash address block 0 or 1 address specifier (register bit field FCFG2[MAXADDR01]). */ #define FSL_FEATURE_SIM_FCFG_HAS_MAXADDR01 (0) /* @brief Maximum flash address block 2 or 3 address specifier (register bit field FCFG2[MAXADDR23]). */ #define FSL_FEATURE_SIM_FCFG_HAS_MAXADDR23 (0) /* @brief Has program flash availability specifier (register bit FCFG2[PFLSH]). */ #define FSL_FEATURE_SIM_FCFG_HAS_PFLSH (0) /* @brief Has program flash swapping (register bit FCFG2[SWAPPFLSH]). */ #define FSL_FEATURE_SIM_FCFG_HAS_PFLSH_SWAP (0) /* @brief Has miscellanious control register (register MCR). */ #define FSL_FEATURE_SIM_HAS_MISC_CONTROLS (0) /* @brief Has COP watchdog (registers COPC and SRVCOP). */ #define FSL_FEATURE_SIM_HAS_COP_WATCHDOG (0) /* @brief Has COP watchdog stop (register bits COPC[COPSTPEN], COPC[COPDBGEN] and COPC[COPCLKSEL]). */ #define FSL_FEATURE_SIM_HAS_COP_STOP (0) #elif defined(CPU_MKV43F128VLH15) || defined(CPU_MKV43F128VLL15) || defined(CPU_MKV43F64VLH15) || defined(CPU_MKV44F128VLH15) || \ defined(CPU_MKV44F128VLL15) || defined(CPU_MKV44F64VLH15) /* @brief Has USB FS divider. */ #define FSL_FEATURE_SIM_USBFS_USE_SPECIAL_DIVIDER (0) /* @brief Is PLL clock divided by 2 before MCG PLL/FLL clock selection. */ #define FSL_FEATURE_SIM_PLLCLK_USE_SPECIAL_DIVIDER (0) /* @brief Has RAM size specification (register bit field SOPT1[RAMSIZE]). */ #define FSL_FEATURE_SIM_OPT_HAS_RAMSIZE (1) /* @brief Has 32k oscillator clock output (register bit SOPT1[OSC32KOUT]). */ #define FSL_FEATURE_SIM_OPT_HAS_OSC32K_OUT (0) /* @brief Has 32k oscillator clock selection (register bit field SOPT1[OSC32KSEL]). */ #define FSL_FEATURE_SIM_OPT_HAS_OSC32K_SELECTION (1) /* @brief 32k oscillator clock selection width (width of register bit field SOPT1[OSC32KSEL]). */ #define FSL_FEATURE_SIM_OPT_OSC32K_SELECTION_WIDTH (2) /* @brief Has RTC clock output selection (register bit SOPT2[RTCCLKOUTSEL]). */ #define FSL_FEATURE_SIM_OPT_HAS_RTC_CLOCK_OUT_SELECTION (0) /* @brief Has USB voltage regulator (register bits SOPT1[USBVSTBY], SOPT1[USBSSTBY], SOPT1[USBREGEN], SOPT1CFG[URWE], SOPT1CFG[UVSWE], SOPT1CFG[USSWE]). */ #define FSL_FEATURE_SIM_OPT_HAS_USB_VOLTAGE_REGULATOR (0) /* @brief USB has integrated PHY (register bits USBPHYCTL[USBVREGSEL], USBPHYCTL[USBVREGPD], USBPHYCTL[USB3VOUTTRG], USBPHYCTL[USBDISILIM], SOPT2[USBSLSRC], SOPT2[USBREGEN]). */ #define FSL_FEATURE_SIM_OPT_HAS_USB_PHY (0) /* @brief Has PTD7 pad drive strength control (register bit SOPT2[PTD7PAD]). */ #define FSL_FEATURE_SIM_OPT_HAS_PTD7PAD (0) /* @brief Has FlexBus security level selection (register bit SOPT2[FBSL]). */ #define FSL_FEATURE_SIM_OPT_HAS_FBSL (0) /* @brief Has number of FlexBus hold cycle before FlexBus can release bus (register bit SOPT6[PCR]). */ #define FSL_FEATURE_SIM_OPT_HAS_PCR (0) /* @brief Has number of NFC hold cycle in case of FlexBus request (register bit SOPT6[MCC]). */ #define FSL_FEATURE_SIM_OPT_HAS_MCC (0) /* @brief Has UART open drain enable (register bits UARTnODE, where n is a number, in register SOPT5). */ #define FSL_FEATURE_SIM_OPT_HAS_ODE (0) /* @brief Number of UART modules (number of register bits UARTn, where n is a number, in register SCGC4). */ #define FSL_FEATURE_SIM_OPT_UART_COUNT (2) /* @brief Has LPUART0 open drain enable (register bit SOPT5[LPUART0ODE]). */ #define FSL_FEATURE_SIM_OPT_HAS_LPUART0_ODE (0) /* @brief Has LPUART1 open drain enable (register bit SOPT5[LPUART1ODE]). */ #define FSL_FEATURE_SIM_OPT_HAS_LPUART1_ODE (0) /* @brief Has CMT/UART pad drive strength control (register bit SOPT2[CMTUARTPAD]). */ #define FSL_FEATURE_SIM_OPT_HAS_CMTUARTPAD (0) /* @brief Has LPUART0 transmit data source selection (register bit SOPT5[LPUART0TXSRC]). */ #define FSL_FEATURE_SIM_OPT_HAS_LPUART0_TX_SRC (0) /* @brief Has LPUART0 receive data source selection (register bit SOPT5[LPUART0RXSRC]). */ #define FSL_FEATURE_SIM_OPT_HAS_LPUART0_RX_SRC (0) /* @brief Has LPUART1 transmit data source selection (register bit SOPT5[LPUART1TXSRC]). */ #define FSL_FEATURE_SIM_OPT_HAS_LPUART1_TX_SRC (0) /* @brief Has LPUART1 receive data source selection (register bit SOPT5[LPUART1RXSRC]). */ #define FSL_FEATURE_SIM_OPT_HAS_LPUART1_RX_SRC (0) /* @brief Has UART0 transmit data source selection (register bit SOPT5[UART0TXSRC]). */ #define FSL_FEATURE_SIM_OPT_HAS_UART0_TX_SRC (1) /* @brief UART0 transmit data source selection width (width of register bit SOPT5[UART0TXSRC]). */ #define FSL_FEATURE_SIM_OPT_UART0_TX_SRC_WIDTH (1) /* @brief Has UART0 receive data source selection (register bit SOPT5[UART0RXSRC]). */ #define FSL_FEATURE_SIM_OPT_HAS_UART0_RX_SRC (1) /* @brief UART0 receive data source selection width (width of register bit SOPT5[UART0RXSRC]). */ #define FSL_FEATURE_SIM_OPT_UART0_RX_SRC_WIDTH (2) /* @brief Has UART1 transmit data source selection (register bit SOPT5[UART1TXSRC]). */ #define FSL_FEATURE_SIM_OPT_HAS_UART1_TX_SRC (1) /* @brief Has UART1 receive data source selection (register bit SOPT5[UART1RXSRC]). */ #define FSL_FEATURE_SIM_OPT_HAS_UART1_RX_SRC (1) /* @brief UART1 receive data source selection width (width of register bit SOPT5[UART1RXSRC]). */ #define FSL_FEATURE_SIM_OPT_UART1_RX_SRC_WIDTH (2) /* @brief Has FTM module(s) configuration. */ #define FSL_FEATURE_SIM_OPT_HAS_FTM (1) /* @brief Number of FTM modules. */ #define FSL_FEATURE_SIM_OPT_FTM_COUNT (0) /* @brief Number of FTM triggers with selectable source. */ #define FSL_FEATURE_SIM_OPT_FTM_TRIGGER_COUNT (2) /* @brief Has FTM0 triggers source selection (register bits SOPT4[FTM0TRGnSRC], where n is a number). */ #define FSL_FEATURE_SIM_OPT_HAS_FTM0_TRIGGER (1) /* @brief Has FTM3 triggers source selection (register bits SOPT4[FTM3TRGnSRC], where n is a number). */ #define FSL_FEATURE_SIM_OPT_HAS_FTM3_TRIGGER (1) /* @brief Has FTM1 channel 0 input capture source selection (register bit SOPT4[FTM1CH0SRC]). */ #define FSL_FEATURE_SIM_OPT_HAS_FTM1_CHANNELS (0) /* @brief Has FTM2 channel 0 input capture source selection (register bit SOPT4[FTM2CH0SRC]). */ #define FSL_FEATURE_SIM_OPT_HAS_FTM2_CHANNELS (0) /* @brief Has FTM3 channel 0 input capture source selection (register bit SOPT4[FTM3CH0SRC]). */ #define FSL_FEATURE_SIM_OPT_HAS_FTM3_CHANNELS (0) /* @brief Has FTM2 channel 1 input capture source selection (register bit SOPT4[FTM2CH1SRC]). */ #define FSL_FEATURE_SIM_OPT_HAS_FTM2_CHANNEL1 (0) /* @brief Number of configurable FTM0 fault detection input (number of register bits SOPT4[FTM0FLTn], where n is a number starting from zero). */ #define FSL_FEATURE_SIM_OPT_FTM0_FAULT_COUNT (4) /* @brief Number of configurable FTM1 fault detection input (number of register bits SOPT4[FTM1FLTn], where n is a number starting from zero). */ #define FSL_FEATURE_SIM_OPT_FTM1_FAULT_COUNT (1) /* @brief Number of configurable FTM2 fault detection input (number of register bits SOPT4[FTM2FLTn], where n is a number starting from zero). */ #define FSL_FEATURE_SIM_OPT_FTM2_FAULT_COUNT (0) /* @brief Number of configurable FTM3 fault detection input (number of register bits SOPT4[FTM3FLTn], where n is a number starting from zero). */ #define FSL_FEATURE_SIM_OPT_FTM3_FAULT_COUNT (1) /* @brief Has FTM hardware trigger 0 software synchronization (register bit SOPT8[FTMnSYNCBIT], where n is a module instance index). */ #define FSL_FEATURE_SIM_OPT_HAS_FTM_TRIGGER_SYNC (1) /* @brief Has FTM channels output source selection (register bit SOPT8[FTMxOCHnSRC], where x is a module instance index and n is a channel index). */ #define FSL_FEATURE_SIM_OPT_HAS_FTM_CHANNELS_OUTPUT_SRC (1) /* @brief Has TPM module(s) configuration. */ #define FSL_FEATURE_SIM_OPT_HAS_TPM (0) /* @brief The highest TPM module index. */ #define FSL_FEATURE_SIM_OPT_MAX_TPM_INDEX (0) /* @brief Has TPM module with index 0. */ #define FSL_FEATURE_SIM_OPT_HAS_TPM0 (0) /* @brief Is TPM channels configuration in the SOPT4 (not SOPT9) register (register bits TPMnCH0SRC, TPMnCLKSEL, where n is a module instance index). */ #define FSL_FEATURE_SIM_OPT_HAS_TPM_CHANNELS_CONFIG_IN_SOPT4_REG (0) /* @brief Has TPM1 channel 0 input capture source selection (register bit field SOPT4[TPM1CH0SRC] or SOPT9[TPM1CH0SRC]). */ #define FSL_FEATURE_SIM_OPT_HAS_TPM1_CH0_SRC_SELECTION (0) /* @brief TPM1 channel 0 input capture source selection width (width of register bit field SOPT4[TPM1CH0SRC] or SOPT9[TPM1CH0SRC]). */ #define FSL_FEATURE_SIM_OPT_TPM1_CH0_SRC_SELECTION_WIDTH (0) /* @brief Has TPM2 channel 0 input capture source selection (register bit field SOPT4[TPM2CH0SRC]). */ #define FSL_FEATURE_SIM_OPT_HAS_TPM2_CH0_SRC_SELECTION (0) /* @brief Has TPM2 clock selection (register bit field SOPT4[TPM2CLKSEL]). */ #define FSL_FEATURE_SIM_OPT_HAS_TPM2_CLK_SEL (0) /* @brief Has PLL/FLL clock selection (register bit field SOPT2[PLLFLLSEL]). */ #define FSL_FEATURE_SIM_OPT_HAS_PLL_FLL_SELECTION (0) /* @brief PLL/FLL clock selection width (width of register bit field SOPT2[PLLFLLSEL]). */ #define FSL_FEATURE_SIM_OPT_PLL_FLL_SELECTION_WIDTH (0) /* @brief Has NFC clock source selection (register bit SOPT2[NFCSRC]). */ #define FSL_FEATURE_SIM_OPT_HAS_NFCSRC (0) /* @brief Has eSDHC clock source selection (register bit SOPT2[ESDHCSRC]). */ #define FSL_FEATURE_SIM_OPT_HAS_ESDHCSRC (0) /* @brief Has SDHC clock source selection (register bit SOPT2[SDHCSRC]). */ #define FSL_FEATURE_SIM_OPT_HAS_SDHCSRC (0) /* @brief Has LCDC clock source selection (register bits SOPT2[LCDCSRC], SOPT2[LCDC_CLKSEL]). */ #define FSL_FEATURE_SIM_OPT_HAS_LCDCSRC (0) /* @brief Has ENET timestamp clock source selection (register bit SOPT2[TIMESRC]). */ #define FSL_FEATURE_SIM_OPT_HAS_TIMESRC (0) /* @brief Has ENET RMII clock source selection (register bit SOPT2[RMIISRC]). */ #define FSL_FEATURE_SIM_OPT_HAS_RMIISRC (0) /* @brief Has USB clock source selection (register bit SOPT2[USBSRC]). */ #define FSL_FEATURE_SIM_OPT_HAS_USBSRC (0) /* @brief Has USB FS clock source selection (register bit SOPT2[USBFSRC]). */ #define FSL_FEATURE_SIM_OPT_HAS_USBFSRC (0) /* @brief Has USB HS clock source selection (register bit SOPT2[USBHSRC]). */ #define FSL_FEATURE_SIM_OPT_HAS_USBHSRC (0) /* @brief Has LPUART clock source selection (register bit SOPT2[LPUARTSRC]). */ #define FSL_FEATURE_SIM_OPT_HAS_LPUARTSRC (0) /* @brief Has LPUART0 clock source selection (register bit SOPT2[LPUART0SRC]). */ #define FSL_FEATURE_SIM_OPT_HAS_LPUART0SRC (0) /* @brief Has LPUART1 clock source selection (register bit SOPT2[LPUART1SRC]). */ #define FSL_FEATURE_SIM_OPT_HAS_LPUART1SRC (0) /* @brief Has FLEXIOSRC clock source selection (register bit SOPT2[FLEXIOSRC]). */ #define FSL_FEATURE_SIM_OPT_HAS_FLEXIOSRC (0) /* @brief Has UART0 clock source selection (register bit SOPT2[UART0SRC]). */ #define FSL_FEATURE_SIM_OPT_HAS_UART0SRC (0) /* @brief Has TPM clock source selection (register bit SOPT2[TPMSRC]). */ #define FSL_FEATURE_SIM_OPT_HAS_TPMSRC (0) /* @brief Has debug trace clock selection (register bit SOPT2[TRACECLKSEL]). */ #define FSL_FEATURE_SIM_OPT_HAS_TRACE_CLKSEL (1) /* @brief Number of ADC modules (register bits SOPT7[ADCnTRGSEL], SOPT7[ADCnPRETRGSEL], SOPT7[ADCnALTTRGSEL], where n is a module instance index). */ #define FSL_FEATURE_SIM_OPT_ADC_COUNT (1) /* @brief Has clock 2 output divider (register bit field CLKDIV1[OUTDIV2]). */ #define FSL_FEATURE_SIM_DIVIDER_HAS_OUTDIV2 (1) /* @brief Has clock 3 output divider (register bit field CLKDIV1[OUTDIV3]). */ #define FSL_FEATURE_SIM_DIVIDER_HAS_OUTDIV3 (0) /* @brief Has clock 4 output divider (register bit field CLKDIV1[OUTDIV4]). */ #define FSL_FEATURE_SIM_DIVIDER_HAS_OUTDIV4 (1) /* @brief Clock 4 output divider width (width of register bit field CLKDIV1[OUTDIV4]). */ #define FSL_FEATURE_SIM_DIVIDER_OUTDIV4_WIDTH (4) /* @brief Has USB clock divider (register bit field CLKDIV2[USBDIV] and CLKDIV2[USBFRAC]). */ #define FSL_FEATURE_SIM_DIVIDER_HAS_USBDIV (0) /* @brief Has USB FS clock divider (register bit field CLKDIV2[USBFSDIV] and CLKDIV2[USBFSFRAC]). */ #define FSL_FEATURE_SIM_DIVIDER_HAS_USBFSDIV (0) /* @brief Has USB HS clock divider (register bit field CLKDIV2[USBHSDIV] and CLKDIV2[USBHSFRAC]). */ #define FSL_FEATURE_SIM_DIVIDER_HAS_USBHSDIV (0) /* @brief Has PLL/FLL clock divider (register bit field CLKDIV3[PLLFLLDIV] and CLKDIV3[PLLFLLFRAC]). */ #define FSL_FEATURE_SIM_DIVIDER_HAS_PLLFLLDIV (0) /* @brief Has LCDC clock divider (register bit field CLKDIV3[LCDCDIV] and CLKDIV3[LCDCFRAC]). */ #define FSL_FEATURE_SIM_DIVIDER_HAS_LCDCDIV (0) /* @brief Has trace clock divider (register bit field CLKDIV4[TRACEDIV] and CLKDIV4[TRACEFRAC]). */ #define FSL_FEATURE_SIM_DIVIDER_HAS_TRACEDIV (1) /* @brief Has NFC clock divider (register bit field CLKDIV4[NFCDIV] and CLKDIV4[NFCFRAC]). */ #define FSL_FEATURE_SIM_DIVIDER_HAS_NFCDIV (0) /* @brief Has Kinetis family ID (register bit field SDID[FAMILYID]). */ #define FSL_FEATURE_SIM_SDID_HAS_FAMILYID (1) /* @brief Has Kinetis family ID (register bit field SDID[FAMID]). */ #define FSL_FEATURE_SIM_SDID_HAS_FAMID (0) /* @brief Has Kinetis sub-family ID (register bit field SDID[SUBFAMID]). */ #define FSL_FEATURE_SIM_SDID_HAS_SUBFAMID (1) /* @brief Has Kinetis series ID (register bit field SDID[SERIESID]). */ #define FSL_FEATURE_SIM_SDID_HAS_SERIESID (1) /* @brief Has device die ID (register bit field SDID[DIEID]). */ #define FSL_FEATURE_SIM_SDID_HAS_DIEID (1) /* @brief Has system SRAM size specifier (register bit field SDID[SRAMSIZE]). */ #define FSL_FEATURE_SIM_SDID_HAS_SRAMSIZE (0) /* @brief Has flash mode (register bit FCFG1[FLASHDOZE]). */ #define FSL_FEATURE_SIM_FCFG_HAS_FLASHDOZE (1) /* @brief Has flash disable (register bit FCFG1[FLASHDIS]). */ #define FSL_FEATURE_SIM_FCFG_HAS_FLASHDIS (1) /* @brief Has FTFE disable (register bit FCFG1[FTFDIS]). */ #define FSL_FEATURE_SIM_FCFG_HAS_FTFDIS (0) /* @brief Has FlexNVM size specifier (register bit field FCFG1[NVMSIZE]). */ #define FSL_FEATURE_SIM_FCFG_HAS_NVMSIZE (0) /* @brief Has EEPROM size specifier (register bit field FCFG1[EESIZE]). */ #define FSL_FEATURE_SIM_FCFG_HAS_EESIZE (0) /* @brief Has FlexNVM partition (register bit field FCFG1[DEPART]). */ #define FSL_FEATURE_SIM_FCFG_HAS_DEPART (0) /* @brief Maximum flash address block 0 address specifier (register bit field FCFG2[MAXADDR0]). */ #define FSL_FEATURE_SIM_FCFG_HAS_MAXADDR0 (1) /* @brief Maximum flash address block 1 address specifier (register bit field FCFG2[MAXADDR1]). */ #define FSL_FEATURE_SIM_FCFG_HAS_MAXADDR1 (0) /* @brief Maximum flash address block 0 or 1 address specifier (register bit field FCFG2[MAXADDR01]). */ #define FSL_FEATURE_SIM_FCFG_HAS_MAXADDR01 (0) /* @brief Maximum flash address block 2 or 3 address specifier (register bit field FCFG2[MAXADDR23]). */ #define FSL_FEATURE_SIM_FCFG_HAS_MAXADDR23 (0) /* @brief Has program flash availability specifier (register bit FCFG2[PFLSH]). */ #define FSL_FEATURE_SIM_FCFG_HAS_PFLSH (0) /* @brief Has program flash swapping (register bit FCFG2[SWAPPFLSH]). */ #define FSL_FEATURE_SIM_FCFG_HAS_PFLSH_SWAP (0) /* @brief Has miscellanious control register (register MCR). */ #define FSL_FEATURE_SIM_HAS_MISC_CONTROLS (0) /* @brief Has COP watchdog (registers COPC and SRVCOP). */ #define FSL_FEATURE_SIM_HAS_COP_WATCHDOG (0) /* @brief Has COP watchdog stop (register bits COPC[COPSTPEN], COPC[COPDBGEN] and COPC[COPCLKSEL]). */ #define FSL_FEATURE_SIM_HAS_COP_STOP (0) #else #error "No valid CPU defined!" #endif #endif /* __FSL_SIM_FEATURES_H__ */ /******************************************************************************* * EOF ******************************************************************************/ ================================================ FILE: Zelig/mbed/TARGET_K64F/TARGET_Freescale/TARGET_KPSDK_MCUS/TARGET_KPSDK_CODE/hal/sim/fsl_sim_hal.h ================================================ /* * Copyright (c) 2013 - 2014, Freescale Semiconductor, Inc. * All rights reserved. * * Redistribution and use in source and binary forms, with or without modification, * are permitted provided that the following conditions are met: * * o Redistributions of source code must retain the above copyright notice, this list * of conditions and the following disclaimer. * * o Redistributions in binary form must reproduce the above copyright notice, this * list of conditions and the following disclaimer in the documentation and/or * other materials provided with the distribution. * * o Neither the name of Freescale Semiconductor, Inc. nor the names of its * contributors may be used to endorse or promote products derived from this * software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT 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. */ #if !defined(__FSL_SIM_HAL_H__) #define __FSL_SIM_HAL_H__ #include #include #include #include "fsl_device_registers.h" #include "fsl_sim_features.h" /*! @addtogroup sim_hal*/ /*! @{*/ /*! @file*/ /******************************************************************************* * Definitions ******************************************************************************/ typedef enum _clock_names { /* default clocks*/ kCoreClock, /**/ kSystemClock, /**/ kPlatformClock, /**/ kBusClock, /**/ kFlexBusClock, /**/ kFlashClock, /**/ /* other internal clocks used by peripherals*/ /* osc clock*/ kOsc32kClock, kOsc0ErClock, kOsc1ErClock, /* irc 48Mhz clock */ kIrc48mClock, /* rtc clock*/ kRtc32kClock, kRtc1hzClock, /* lpo clcok*/ kLpoClock, /* mcg clocks*/ kMcgFfClock, kMcgFllClock, kMcgPll0Clock, kMcgPll1Clock, kMcgOutClock, kMcgIrClock, /* constant clocks (provided in other header files?)*/ kSDHC0_CLKIN, kENET_1588_CLKIN, kEXTAL_Clock, kEXTAL1_Clock, kUSB_CLKIN, /* reserved value*/ kReserved, kClockNameCount } clock_names_t; /*! @brief Clock source and sel names */ typedef enum _clock_source_names { kClockNfcSrc, /* NFCSRC*/ kClockEsdhcSrc, /* ESDHCSRC K70*/ kClockSdhcSrc, /* SDHCSRC K64*/ kClockLcdcSrc, /* LCDCSRC*/ kClockTimeSrc, /* TIMESRC*/ kClockRmiiSrc, /* RMIISRC*/ kClockUsbfSrc, /* USBFSRC K70*/ kClockUsbSrc, /* USBSRC K64, KL25, KV31, and K22*/ kClockUsbhSrc, /* USBHSRC*/ kClockUart0Src, /* UART0SRC*/ kClockLpuartSrc, /* LPUARTSRC K22, KV31 */ kClockTpmSrc, /* TPMSRC*/ kClockOsc32kSel, /* OSC32KSEL*/ kClockUsbfSel, /* USBF_CLKSEL*/ kClockPllfllSel, /* PLLFLLSEL*/ kClockNfcSel, /* NFC_CLKSEL*/ kClockLcdcSel, /* LCDC_CLKSEL*/ kClockTraceSel, /* TRACE_CLKSEL*/ kClockClkoutSel, /* CLKOUTSEL*/ kClockRtcClkoutSel, /* RTCCLKOUTSEL */ kClockSourceMax } clock_source_names_t; /*! @brief Clock Divider names*/ typedef enum _clock_divider_names { kClockDividerOutdiv1, /* OUTDIV1*/ kClockDividerOutdiv2, /* OUTDIV2*/ kClockDividerOutdiv3, /* OUTDIV3*/ kClockDividerOutdiv4, /* OUTDIV4*/ kClockDividerUsbFrac, /* (USBFRAC + 1) / (USBDIV + 1)*/ kClockDividerUsbDiv, kClockDividerUsbfsFrac, /* (USBFSFRAC + 1) / (USBFSDIV) + 1)*/ kClockDividerUsbfsDiv, kClockDividerUsbhsFrac, /* (USBHSFRAC + 1) / (USBHSDIV + 1)*/ kClockDividerUsbhsDiv, kClockDividerLcdcFrac, /* (LCDCFRAC + 1) / (LCDCDIV + 1)*/ kClockDividerLcdcDiv, kClockDividerNfcFrac, /* (NFCFRAC + 1) / (NFCDIV + 1)*/ kClockDividerNfcDiv, kClockDividerSpecial1, /* special divider 1*/ kClockDividerMax } clock_divider_names_t; /*! @brief SIM USB voltage regulator in standby mode setting during stop modes */ typedef enum _sim_usbsstby_stop { kSimUsbsstbyNoRegulator, /* regulator not in standby during Stop modes */ kSimUsbsstbyWithRegulator /* regulator in standby during Stop modes */ } sim_usbsstby_stop_t; /*! @brief SIM USB voltage regulator in standby mode setting during VLPR and VLPW modes */ typedef enum _sim_usbvstby_stop { kSimUsbvstbyNoRegulator, /* regulator not in standby during VLPR and VLPW modes */ kSimUsbvstbyWithRegulator /* regulator in standby during VLPR and VLPW modes */ } sim_usbvstby_stop_t; /*! @brief SIM CMT/UART pad drive strength */ typedef enum _sim_cmtuartpad_strengh { kSimCmtuartSinglePad, /* Single-pad drive strength for CMT IRO or UART0_TXD */ kSimCmtuartDualPad /* Dual-pad drive strength for CMT IRO or UART0_TXD */ } sim_cmtuartpad_strengh_t; /*! @brief SIM PTD7 pad drive strength */ typedef enum _sim_ptd7pad_strengh { kSimPtd7padSinglePad, /* Single-pad drive strength for PTD7 */ kSimPtd7padDualPad /* Dual-pad drive strength for PTD7 */ } sim_ptd7pad_strengh_t; /*! @brief SIM FlexBus security level */ typedef enum _sim_flexbus_security_level { kSimFbslLevel0, /* All off-chip accesses (op code and data) via the FlexBus */ /* and DDR controller are disallowed */ kSimFbslLevel1, /* Undefined */ kSimFbslLevel2, /* Off-chip op code accesses are disallowed. Data accesses */ /* are allowed */ kSimFbslLevel3 /* Off-chip op code accesses and data accesses are allowed */ } sim_flexbus_security_level_t; /*! @brief SIM ADCx pre-trigger select */ typedef enum _sim_pretrgsel { kSimAdcPretrgselA, /* Pre-trigger A selected for ADCx */ kSimAdcPretrgselB /* Pre-trigger B selected for ADCx */ } sim_pretrgsel_t; /*! @brief SIM ADCx trigger select */ typedef enum _sim_trgsel { kSimAdcTrgselExt, /* External trigger */ kSimAdcTrgSelHighSpeedComp0, /* High speed comparator 0 asynchronous interrupt */ kSimAdcTrgSelHighSpeedComp1, /* High speed comparator 1 asynchronous interrupt */ kSimAdcTrgSelHighSpeedComp2, /* High speed comparator 2 asynchronous interrupt */ kSimAdcTrgSelPit0, /* PIT trigger 0 */ kSimAdcTrgSelPit1, /* PIT trigger 1 */ kSimAdcTrgSelPit2, /* PIT trigger 2 */ kSimAdcTrgSelPit3, /* PIT trigger 3 */ kSimAdcTrgSelFtm0, /* FTM0 trigger */ kSimAdcTrgSelFtm1, /* FTM1 trigger */ kSimAdcTrgSelFtm2, /* FTM2 trigger */ kSimAdcTrgSelFtm3, /* FTM3 trigger */ kSimAdcTrgSelRtcAlarm, /* RTC alarm */ kSimAdcTrgSelRtcSec, /* RTC seconds */ kSimAdcTrgSelLptimer, /* Low-power timer trigger */ kSimAdcTrgSelHigSpeedComp3 /* High speed comparator 3 asynchronous interrupt */ } sim_trgsel_t; /*! @brief SIM receive data source select */ typedef enum _sim_uart_rxsrc { kSimUartRxsrcPin, /* UARTx_RX Pin */ kSimUartRxsrcCmp0, /* CMP0 */ kSimUartRxsrcCmp1, /* CMP1 */ kSimUartRxsrcReserved /* Reserved */ } sim_uart_rxsrc_t; /*! @brief SIM transmit data source select */ typedef enum _sim_uart_txsrc { kSimUartTxsrcPin, /* UARTx_TX Pin */ kSimUartTxsrcCmp0, /* UARTx_TX pin modulated with FTM1 channel 0 output */ kSimUartTxsrcCmp1, /* UARTx_TX pin modulated with FTM2 channel 0 output */ kSimUartTxsrcReserved /* Reserved */ } sim_uart_txsrc_t; /*! @brief SIM FlexTimer x trigger y select */ typedef enum _sim_ftm_trg_src { kSimFtmTrgSrc0, /* FlexTimer x trigger y select 0 */ kSimFtmTrgSrc1 /* FlexTimer x trigger y select 1 */ } sim_ftm_trg_src_t; /*! @brief SIM FlexTimer external clock select */ typedef enum _sim_ftm_clk_sel { kSimFtmClkSel0, /* FTM CLKIN0 pin. */ kSimFtmClkSel1 /* FTM CLKIN1 pin. */ } sim_ftm_clk_sel_t; /*! @brief SIM FlexTimer x channel y input capture source select */ typedef enum _sim_ftm_ch_src { kSimFtmChSrc0, /* See RM for details of each selection for each channel */ kSimFtmChSrc1, /* See RM for details of each selection for each channel */ kSimFtmChSrc2, /* See RM for details of each selection for each channel */ kSimFtmChSrc3 /* See RM for details of each selection for each channel */ } sim_ftm_ch_src_t; /*! @brief SIM FlexTimer x Fault y select */ typedef enum _sim_ftm_flt_sel { kSimFtmFltSel0, /* FlexTimer x fault y select 0 */ kSimFtmFltSel1 /* FlexTimer x fault y select 1 */ } sim_ftm_flt_sel_t; /*! @brief SIM Timer/PWM external clock select */ typedef enum _sim_tpm_clk_sel { kSimTpmClkSel0, /* Timer/PWM TPM_CLKIN0 pin. */ kSimTpmClkSel1 /* Timer/PWM TPM_CLKIN1 pin. */ } sim_tpm_clk_sel_t; /*! @brief SIM Timer/PWM x channel y input capture source select */ typedef enum _sim_tpm_ch_src { kSimTpmChSrc0, /* TPMx_CH0 signal */ kSimTpmChSrc1 /* CMP0 output */ } sim_tpm_ch_src_t; /*! @brief SIM HAL API return status*/ typedef enum _sim_hal_status { kSimHalSuccess, kSimHalFail, kSimHalNoSuchModule, kSimHalNoSuchClockSrc, kSimHalNoSuchDivider } sim_hal_status_t; /*! @brief Clock name configuration table structure*/ typedef struct ClockNameConfig { bool useOtherRefClock; /*!< if it uses the other ref clock*/ clock_names_t otherRefClockName; /*!< other ref clock name*/ clock_divider_names_t dividerName; /*!< clock divider name*/ } clock_name_config_t; /*! @brief clock name configuration table for specified CPU defined in fsl_clock_module_names_Kxxx.h*/ extern const clock_name_config_t kClockNameConfigTable[]; /******************************************************************************* * API ******************************************************************************/ #if defined(__cplusplus) extern "C" { #endif /* __cplusplus*/ /*! @name clock-related feature APIs*/ /*@{*/ /*! * @brief Sets the clock source setting. * * This function sets the settings for a specified clock source. Each clock * source has its own clock selection settings. See the chip reference manual for * clock source detailed settings and the clock_source_names_t * for clock sources. * * @param baseAddr Base address for current SIM instance. * @param clockSource Clock source name defined in sim_clock_source_names_t * @param setting Setting value * @return status If the clock source doesn't exist, it returns an error. */ sim_hal_status_t CLOCK_HAL_SetSource(uint32_t baseAddr, clock_source_names_t clockSource, uint8_t setting); /*! * @brief Gets the clock source setting. * * This function gets the settings for a specified clock source. Each clock * source has its own clock selection settings. See the reference manual for * clock source detailed settings and the clock_source_names_t * for clock sources. * * @param baseAddr Base address for current SIM instance. * @param clockSource Clock source name * @param setting Current setting pointer for the clock source * @return status If the clock source doesn't exist, it returns an error. */ sim_hal_status_t CLOCK_HAL_GetSource(uint32_t baseAddr, clock_source_names_t clockSource, uint8_t *setting); /*! * @brief Sets the clock divider setting. * * This function sets the setting for a specified clock divider. See the * reference manual for a supported clock divider and value range and the * clock_divider_names_t for dividers. * * @param baseAddr Base address for current SIM instance. * @param clockDivider Clock divider name * @param setting Divider setting * @return status If the clock divider doesn't exist, it returns an error. */ sim_hal_status_t CLOCK_HAL_SetDivider(uint32_t baseAddr, clock_divider_names_t clockDivider, uint32_t setting); /*! * @brief Sets the clock out dividers setting. * * This function sets the setting for all clock out dividers at the same time. * See the reference manual for a supported clock divider and value range and the * clock_divider_names_t for clock out dividers. * * @param baseAddr Base address for current SIM instance. * @param outdiv1 Outdivider1 setting * @param outdiv2 Outdivider2 setting * @param outdiv3 Outdivider3 setting * @param outdiv4 Outdivider4 setting */ void CLOCK_HAL_SetOutDividers(uint32_t baseAddr, uint32_t outdiv1, uint32_t outdiv2, uint32_t outdiv3, uint32_t outdiv4); /*! * @brief Gets the clock divider setting. * * This function gets the setting for a specified clock divider. See the * reference manual for a supported clock divider and value range and the * clock_divider_names_t for dividers. * * @param baseAddr Base address for current SIM instance. * @param clockDivider Clock divider name * @param setting Divider value pointer * @return status If the clock divider doesn't exist, it returns an error. */ sim_hal_status_t CLOCK_HAL_GetDivider(uint32_t baseAddr, clock_divider_names_t clockDivider, uint32_t *setting); /*@}*/ /*! @name individual field access APIs*/ /*@{*/ #if FSL_FEATURE_SIM_OPT_HAS_RAMSIZE /*! * @brief Gets RAM size. * * This function gets the RAM size. The field specifies the amount of system RAM * available on the device. * * @param baseAddr Base address for current SIM instance. * @return size RAM size on the device */ static inline uint32_t SIM_HAL_GetRamSize(uint32_t baseAddr) { return BR_SIM_SOPT1_RAMSIZE(baseAddr); } #endif /* FSL_FEATURE_SIM_OPT_HAS_RAMSIZE */ #if FSL_FEATURE_SIM_OPT_HAS_USB_VOLTAGE_REGULATOR /*! * @brief Sets the USB voltage regulator enabled setting. * * This function controls whether the USB voltage regulator is enabled. This bit * can only be written when the SOPT1CFG[URWE] bit is set. * * @param baseAddr Base address for current SIM instance. * @param enable USB voltage regulator enable setting * - true: USB voltage regulator is enabled. * - false: USB voltage regulator is disabled. */ static inline void SIM_HAL_SetUsbVoltRegulatorCmd(uint32_t baseAddr, bool enable) { BW_SIM_SOPT1_USBREGEN(baseAddr, enable ? 1 : 0); } /*! * @brief Gets the USB voltage regulator enabled setting. * * This function gets the USB voltage regulator enabled setting. * * @param baseAddr Base address for current SIM instance. * @return enabled True if the USB voltage regulator is enabled. */ static inline bool SIM_HAL_GetUsbVoltRegulatorCmd(uint32_t baseAddr) { return BR_SIM_SOPT1_USBREGEN(baseAddr); } /*! * @brief Sets the USB voltage regulator in a standby mode setting during Stop, VLPS, LLS, and VLLS. * * This function controls whether the USB voltage regulator is placed in a standby * mode during Stop, VLPS, LLS, and VLLS modes. This bit can only be written when the * SOPT1CFG[USSWE] bit is set. * * @param baseAddr Base address for current SIM instance. * @param setting USB voltage regulator in standby mode setting * - 0: USB voltage regulator not in standby during Stop, VLPS, LLS and * VLLS modes. * - 1: USB voltage regulator in standby during Stop, VLPS, LLS and VLLS * modes. */ static inline void SIM_HAL_SetUsbVoltRegulatorInStdbyDuringStopMode(uint32_t baseAddr, sim_usbsstby_stop_t setting) { BW_SIM_SOPT1_USBSSTBY(baseAddr, setting); } /*! * @brief Gets the USB voltage regulator in a standby mode setting. * * This function gets the USB voltage regulator in a standby mode setting. * * @param baseAddr Base address for current SIM instance. * @return setting USB voltage regulator in a standby mode setting */ static inline sim_usbsstby_stop_t SIM_HAL_GetUsbVoltRegulatorInStdbyDuringStopMode(uint32_t baseAddr) { return (sim_usbsstby_stop_t)BR_SIM_SOPT1_USBSSTBY(baseAddr); } /*! * @brief Sets the USB voltage regulator in a standby mode during the VLPR or the VLPW. * * This function controls whether the USB voltage regulator is placed in a standby * mode during the VLPR and the VLPW modes. This bit can only be written when the * SOPT1CFG[UVSWE] bit is set. * * @param baseAddr Base address for current SIM instance. * @param setting USB voltage regulator in standby mode setting * - 0: USB voltage regulator not in standby during VLPR and VLPW modes. * - 1: USB voltage regulator in standby during VLPR and VLPW modes. */ static inline void SIM_HAL_SetUsbVoltRegulatorInStdbyDuringVlprwMode(uint32_t baseAddr, sim_usbvstby_stop_t setting) { BW_SIM_SOPT1_USBVSTBY(baseAddr, setting); } /*! * @brief Gets the USB voltage regulator in a standby mode during the VLPR or the VLPW. * * This function gets the USB voltage regulator in a standby mode during the VLPR or the VLPW. * * @param baseAddr Base address for current SIM instance. * @return setting USB voltage regulator in a standby mode during the VLPR or the VLPW */ static inline sim_usbvstby_stop_t SIM_HAL_GetUsbVoltRegulatorInStdbyDuringVlprwMode(uint32_t baseAddr) { return (sim_usbvstby_stop_t)BR_SIM_SOPT1_USBVSTBY(baseAddr); } /*! * @brief Sets the USB voltage regulator stop standby write enable setting. * * This function controls whether the USB voltage regulator stop standby write * feature is enabled. Writing one to this bit allows the SOPT1[USBSSTBY] bit to be written. This * register bit clears after a write to SOPT1[USBSSTBY]. * * @param baseAddr Base address for current SIM instance. * @param enable USB voltage regulator stop standby write enable setting * - true: SOPT1[USBSSTBY] can be written. * - false: SOPT1[USBSSTBY] cannot be written. */ static inline void SIM_HAL_SetUsbVoltRegulatorInStdbyDuringStopCmd(uint32_t baseAddr, bool enable) { BW_SIM_SOPT1CFG_USSWE(baseAddr, enable ? 1 : 0); } /*! * @brief Gets the USB voltage regulator stop standby write enable setting. * * This function gets the USB voltage regulator stop standby write enable setting. * * @param baseAddr Base address for current SIM instance. * @return enabled True if the USB voltage regulator stop standby write is enabled. */ static inline bool SIM_HAL_GetUsbVoltRegulatorInStdbyDuringStopCmd(uint32_t baseAddr) { return BR_SIM_SOPT1CFG_USSWE(baseAddr); } /*! * @brief Sets the USB voltage regulator VLP standby write enable setting. * * This function controls whether USB voltage regulator VLP standby write * feature is enabled. Writing one to this bit allows the SOPT1[USBVSTBY] bit to be written. This * register bit clears after a write to SOPT1[USBVSTBY]. * * @param baseAddr Base address for current SIM instance. * @param enable USB voltage regulator VLP standby write enable setting * - true: SOPT1[USBSSTBY] can be written. * - false: SOPT1[USBSSTBY] cannot be written. */ static inline void SIM_HAL_SetUsbVoltRegulatorInStdbyDuringVlprwCmd(uint32_t baseAddr, bool enable) { BW_SIM_SOPT1CFG_UVSWE(baseAddr, enable ? 1 : 0); } /*! * @brief Gets the USB voltage regulator VLP standby write enable setting. * * This function gets the USB voltage regulator VLP standby write enable setting. * * @param baseAddr Base address for current SIM instance. * @return enabled True if the USB voltage regulator VLP standby write is enabled. */ static inline bool SIM_HAL_GetUsbVoltRegulatorInStdbyDuringVlprwCmd(uint32_t baseAddr) { return BR_SIM_SOPT1CFG_UVSWE(baseAddr); } /*! * @brief Sets the USB voltage regulator enable write enable setting. * * This function controls whether the USB voltage regulator write enable * feature is enabled. Writing one to this bit allows the SOPT1[USBREGEN] bit to be written. * This register bit clears after a write to SOPT1[USBREGEN]. * * @param baseAddr Base address for current SIM instance. * @param enable USB voltage regulator enable write enable setting * - true: SOPT1[USBSSTBY] can be written. * - false: SOPT1[USBSSTBY] cannot be written. */ static inline void SIM_HAL_SetUsbVoltRegulatorWriteCmd(uint32_t baseAddr, bool enable) { BW_SIM_SOPT1CFG_URWE(baseAddr, enable ? 1 : 0); } /*! * @brief Gets the USB voltage regulator enable write enable setting. * * This function gets the USB voltage regulator enable write enable setting. * * @param baseAddr Base address for current SIM instance. * @return enabled True if USB voltage regulator enable write is enabled. */ static inline bool SIM_HAL_GetUsbVoltRegulatorWriteCmd(uint32_t baseAddr) { return BR_SIM_SOPT1CFG_URWE(baseAddr); } #endif #if FSL_FEATURE_SIM_OPT_HAS_CMTUARTPAD /*! * @brief Sets the CMT/UART pad drive strength setting. * * This function controls the output drive strength of the CMT IRO signal or * UART0_TXD signal on PTD7 pin by selecting either one or two pads to drive it. * * @param baseAddr Base address for current SIM instance. * @param setting CMT/UART pad drive strength setting * - 0: Single-pad drive strength for CMT IRO or UART0_TXD. * - 1: Dual-pad drive strength for CMT IRO or UART0_TXD. */ static inline void SIM_HAL_SetCmtUartPadDriveStrengthMode(uint32_t baseAddr, sim_cmtuartpad_strengh_t setting) { BW_SIM_SOPT2_CMTUARTPAD(baseAddr, setting); } /*! * @brief Gets the CMT/UART pad drive strength setting. * * This function gets the CMT/UART pad drive strength setting. * * @param baseAddr Base address for current SIM instance. * @return setting CMT/UART pad drive strength setting */ static inline sim_cmtuartpad_strengh_t SIM_HAL_GetCmtUartPadDriveStrengthMode(uint32_t baseAddr) { return (sim_cmtuartpad_strengh_t)BR_SIM_SOPT2_CMTUARTPAD(baseAddr); } #endif /* FSL_FEATURE_SIM_OPT_HAS_CMTUARTPAD */ #if FSL_FEATURE_SIM_OPT_HAS_PTD7PAD /*! * @brief Sets the PTD7 pad drive strength setting. * * This function controls the output drive strength of the PTD7 pin by selecting * either one or two pads to drive it. * * @param baseAddr Base address for current SIM instance. * @param setting PTD7 pad drive strength setting * - 0: Single-pad drive strength for PTD7. * - 1: Double pad drive strength for PTD7. */ static inline void SIM_HAL_SetPtd7PadDriveStrengthMode(uint32_t baseAddr, sim_ptd7pad_strengh_t setting) { BW_SIM_SOPT2_PTD7PAD(baseAddr, setting); } /*! * @brief Gets the PTD7 pad drive strength setting. * * This function gets the PTD7 pad drive strength setting. * * @param baseAddr Base address for current SIM instance. * @return setting PTD7 pad drive strength setting */ static inline sim_ptd7pad_strengh_t SIM_HAL_GetPtd7PadDriveStrengthMode(uint32_t baseAddr) { return (sim_ptd7pad_strengh_t)BR_SIM_SOPT2_PTD7PAD(baseAddr); } #endif /* FSL_FEATURE_SIM_OPT_HAS_PTD7PAD */ #if FSL_FEATURE_SIM_OPT_HAS_FBSL /*! * @brief Sets the FlexBus security level setting. * * This function sets the FlexBus security level setting. If the security is enabled, * this field affects which CPU operations can access the off-chip via the FlexBus * and DDR controller interfaces. This field has no effect if the security is not enabled. * * @param baseAddr Base address for current SIM instance. * @param setting FlexBus security level setting * - 00: All off-chip accesses (op code and data) via the FlexBus and * DDR controller are disallowed. * - 10: Off-chip op code accesses are disallowed. Data accesses are * allowed. * - 11: Off-chip op code accesses and data accesses are allowed. */ static inline void SIM_HAL_SetFlexbusSecurityLevelMode(uint32_t baseAddr, sim_flexbus_security_level_t setting) { BW_SIM_SOPT2_FBSL(baseAddr, setting); } /*! * @brief Gets the FlexBus security level setting. * * This function gets the FlexBus security level setting. * * @param baseAddr Base address for current SIM instance. * @return setting FlexBus security level setting */ static inline sim_flexbus_security_level_t SIM_HAL_GetFlexbusSecurityLevelMode(uint32_t baseAddr) { return (sim_flexbus_security_level_t)BR_SIM_SOPT2_FBSL(baseAddr); } #endif /* FSL_FEATURE_SIM_OPT_HAS_FBSL */ #if FSL_FEATURE_SIM_OPT_HAS_PCR /*! * @brief Sets the PCR setting. * * This function sets the PCR setting. This is the FlexBus hold cycles before * FlexBus can release bus to NFC or to IDLE. * * @param baseAddr Base address for current SIM instance. * @param setting PCR setting */ static inline void SIM_HAL_SetFlexbusHoldCycles(uint32_t baseAddr, uint32_t setting) { BW_SIM_SOPT6_PCR(baseAddr, setting); } /*! * @brief Gets the PCR setting. * * This function gets the PCR setting. * * @param baseAddr Base address for current SIM instance. * @return setting PCR setting */ static inline uint32_t SIM_HAL_GetFlexbusHoldCycles(uint32_t baseAddr) { return BR_SIM_SOPT6_PCR(baseAddr); } #endif /* FSL_FEATURE_SIM_OPT_HAS_PCR */ #if FSL_FEATURE_SIM_OPT_HAS_MCC /*! * @brief Sets the MCC setting. * * This function sets the MCC setting. This is the NFC hold cycle in case the * FlexBus request during NFC is granted. * * @param baseAddr Base address for current SIM instance. * @param setting MCC setting */ static inline void SIM_HAL_SetNandFlashControllerHoldCycles(uint32_t baseAddr, uint32_t setting) { BW_SIM_SOPT6_MCC(baseAddr, setting); } /*! * @brief Gets the MCC setting. * * This function gets the MCC setting. * * @param baseAddr Base address for current SIM instance. * @return setting MCC setting */ static inline uint32_t SIM_HAL_GetNandFlashControllerHoldCycles(uint32_t baseAddr) { return BR_SIM_SOPT6_MCC(baseAddr); } #endif /* FSL_FEATURE_SIM_OPT_HAS_MCC */ /*! * @brief Sets the ADCx alternate trigger enable setting. * * This function enables/disables the alternative conversion triggers for ADCx. * * @param baseAddr Base address for current SIM instance. * @param instance device instance. * @param enable Enable alternative conversion triggers for ADCx * - true: Select alternative conversion trigger. * - false: Select PDB trigger. */ void SIM_HAL_SetAdcAlternativeTriggerCmd(uint32_t baseAddr, uint8_t instance, bool enable); /*! * @brief Gets the ADCx alternate trigger enable setting. * * This function gets the ADCx alternate trigger enable setting. * * @param baseAddr Base address for current SIM instance. * @param instance device instance. * @return enabled True if ADCx alternate trigger is enabled */ bool SIM_HAL_GetAdcAlternativeTriggerCmd(uint32_t baseAddr, uint8_t instance); /*! * @brief Sets the ADCx pre-trigger select setting. * * This function selects the ADCx pre-trigger source when the alternative triggers * are enabled through ADCxALTTRGEN. * * @param baseAddr Base address for current SIM instance. * @param instance device instance. * @param select pre-trigger select setting for ADCx * - 0: Pre-trigger A selected for ADCx. * - 1: Pre-trigger B selected for ADCx. */ void SIM_HAL_SetAdcPreTriggerMode(uint32_t baseAddr, uint8_t instance, sim_pretrgsel_t select); /*! * @brief Gets the ADCx pre-trigger select setting. * * This function gets the ADCx pre-trigger select setting. * * @param baseAddr Base address for current SIM instance. * @param instance device instance. * @return select ADCx pre-trigger select setting */ sim_pretrgsel_t SIM_HAL_GetAdcPreTriggerMode(uint32_t baseAddr, uint8_t instance); /*! * @brief Sets the ADCx trigger select setting. * * This function selects the ADCx trigger source when alternative triggers * are enabled through ADCxALTTRGEN. * * @param baseAddr Base address for current SIM instance. * @param instance device instance. * @param select trigger select setting for ADCx * - 0000: External trigger * - 0001: High speed comparator 0 asynchronous interrupt * - 0010: High speed comparator 1 asynchronous interrupt * - 0011: High speed comparator 2 asynchronous interrupt * - 0100: PIT trigger 0 * - 0101: PIT trigger 1 * - 0110: PIT trigger 2 * - 0111: PIT trigger 3 * - 1000: FTM0 trigger * - 1001: FTM1 trigger * - 1010: FTM2 trigger * - 1011: FTM3 trigger * - 1100: RTC alarm * - 1101: RTC seconds * - 1110: Low-power timer trigger * - 1111: High speed comparator 3 asynchronous interrupt */ void SIM_HAL_SetAdcTriggerMode(uint32_t baseAddr, uint8_t instance, sim_trgsel_t select); /*! * @brief Gets the ADCx trigger select setting. * * This function gets the ADCx trigger select setting. * * @param baseAddr Base address for current SIM instance. * @param instance device instance. * @return select ADCx trigger select setting */ sim_pretrgsel_t SIM_HAL_GetAdcTriggerMode(uint32_t baseAddr, uint8_t instance); /*! * @brief Sets the UARTx receive data source select setting. * * This function selects the source for the UARTx receive data. * * @param baseAddr Base address for current SIM instance. * @param instance device instance. * @param select the source for the UARTx receive data * - 00: UARTx_RX pin. * - 01: CMP0. * - 10: CMP1. * - 11: Reserved. */ void SIM_HAL_SetUartRxSrcMode(uint32_t baseAddr, uint8_t instance, sim_uart_rxsrc_t select); /*! * @brief Gets the UARTx receive data source select setting. * * This function gets the UARTx receive data source select setting. * * @param baseAddr Base address for current SIM instance. * @param instance device instance. * @return select UARTx receive data source select setting */ sim_uart_rxsrc_t SIM_HAL_GetUartRxSrcMode(uint32_t baseAddr, uint8_t instance); /*! * @brief Sets the UARTx transmit data source select setting. * * This function selects the source for the UARTx transmit data. * * @param baseAddr Base address for current SIM instance. * @param instance device instance. * @param select the source for the UARTx transmit data * - 00: UARTx_TX pin. * - 01: UARTx_TX pin modulated with FTM1 channel 0 output. * - 10: UARTx_TX pin modulated with FTM2 channel 0 output. * - 11: Reserved. */ void SIM_HAL_SetUartTxSrcMode(uint32_t baseAddr, uint8_t instance, sim_uart_txsrc_t select); /*! * @brief Gets the UARTx transmit data source select setting. * * This function gets the UARTx transmit data source select setting. * * @param baseAddr Base address for current SIM instance. * @param instance device instance. * @return select UARTx transmit data source select setting */ sim_uart_txsrc_t SIM_HAL_GetUartTxSrcMode(uint32_t baseAddr, uint8_t instance); #if FSL_FEATURE_SIM_OPT_HAS_ODE /*! * @brief Sets the UARTx Open Drain Enable setting. * * This function enables/disables the UARTx Open Drain. * * @param baseAddr Base address for current SIM instance. * @param instance device instance. * @param enable Enable/disable UARTx Open Drain * - True: Enable UARTx Open Drain * - False: Disable UARTx Open Drain */ void SIM_HAL_SetUartOpenDrainCmd(uint32_t baseAddr, uint8_t instance, bool enable); /*! * @brief Gets the UARTx Open Drain Enable setting. * * This function gets the UARTx Open Drain Enable setting. * * @param baseAddr Base address for current SIM instance. * @param instance device instance. * @return enabled True if UARTx Open Drain is enabled. */ bool SIM_HAL_GetUartOpenDrainCmd(uint32_t baseAddr, uint8_t instance); #endif #if FSL_FEATURE_SIM_OPT_HAS_FTM /*! * @brief Sets the FlexTimer x hardware trigger y source select setting. * * This function selects the source of FTMx hardware trigger y. * * @param baseAddr Base address for current SIM instance. * @param instance device instance. * @param trigger hardware trigger y * @param select FlexTimer x hardware trigger y * - 0: Pre-trigger A selected for ADCx. * - 1: Pre-trigger B selected for ADCx. */ void SIM_HAL_SetFtmTriggerSrcMode(uint32_t baseAddr, uint8_t instance, uint8_t trigger, sim_ftm_trg_src_t select); /*! * @brief Gets the FlexTimer x hardware trigger y source select setting. * * This function gets the FlexTimer x hardware trigger y source select setting. * * @param baseAddr Base address for current SIM instance. * @param instance device instance. * @param trigger hardware trigger y * @return select FlexTimer x hardware trigger y source select setting */ sim_ftm_trg_src_t SIM_HAL_GetFtmTriggerSrcMode(uint32_t baseAddr, uint8_t instance, uint8_t trigger); /*! * @brief Sets the FlexTimer x external clock pin select setting. * * This function selects the source of FTMx external clock pin select. * * @param baseAddr Base address for current SIM instance. * @param instance device instance. * @param select FTMx external clock pin select * - 0: FTMx external clock driven by FTM CLKIN0 pin. * - 1: FTMx external clock driven by FTM CLKIN1 pin. */ void SIM_HAL_SetFtmExternalClkPinMode(uint32_t baseAddr, uint8_t instance, sim_ftm_clk_sel_t select); /*! * @brief Gets the FlexTimer x external clock pin select setting. * * This function gets the FlexTimer x external clock pin select setting. * * @param baseAddr Base address for current SIM instance. * @param instance device instance. * @return select FlexTimer x external clock pin select setting */ sim_ftm_clk_sel_t SIM_HAL_GetFtmExternalClkPinMode(uint32_t baseAddr, uint8_t instance); /*! * @brief Sets the FlexTimer x channel y input capture source select setting. * * This function selects the FlexTimer x channel y input capture source. * * @param baseAddr Base address for current SIM instance. * @param instance device instance. * @param channel FlexTimer channel y * @param select FlexTimer x channel y input capture source * See the reference manual for detailed definition for each channel and selection. */ void SIM_HAL_SetFtmChSrcMode(uint32_t baseAddr, uint8_t instance, uint8_t channel, sim_ftm_ch_src_t select); /*! * @brief Gets the FlexTimer x channel y input capture source select setting. * * This function gets the FlexTimer x channel y input capture source select setting. * * @param baseAddr Base address for current SIM instance. * @param instance device instance. * @param channel FlexTimer channel y * @return select FlexTimer x channel y input capture source select setting */ sim_ftm_ch_src_t SIM_HAL_GetFtmChSrcMode(uint32_t baseAddr, uint8_t instance, uint8_t channel); /*! * @brief Sets the FlexTimer x fault y select setting. * * This function sets the FlexTimer x fault y select setting. * * @param baseAddr Base address for current SIM instance. * @param instance device instance. * @param fault fault y * @param select FlexTimer x fault y select setting * - 0: FlexTimer x fault y select 0. * - 1: FlexTimer x fault y select 1. */ void SIM_HAL_SetFtmFaultSelMode(uint32_t baseAddr, uint8_t instance, uint8_t fault, sim_ftm_flt_sel_t select); /*! * @brief Gets the FlexTimer x fault y select setting. * * This function gets the FlexTimer x fault y select setting. * * @param baseAddr Base address for current SIM instance. * @param instance device instance. * @param fault fault y * @return select FlexTimer x fault y select setting */ sim_ftm_flt_sel_t SIM_HAL_GetFtmFaultSelMode(uint32_t baseAddr, uint8_t instance, uint8_t fault); #endif #if FSL_FEATURE_SIM_OPT_HAS_TPM /*! * @brief Sets the Timer/PWM x external clock pin select setting. * * This function selects the source of the Timer/PWM x external clock pin select. * * @param baseAddr Base address for current SIM instance. * @param instance device instance. * @param select Timer/PWM x external clock pin select * - 0: Timer/PWM x external clock driven by the TPM_CLKIN0 pin. * - 1: Timer/PWM x external clock driven by the TPM_CLKIN1 pin. */ void SIM_HAL_SetTpmExternalClkPinSelMode(uint32_t baseAddr, uint8_t instance, sim_tpm_clk_sel_t select); /*! * @brief Gets the Timer/PWM x external clock pin select setting. * * This function gets the Timer/PWM x external clock pin select setting. * * @param baseAddr Base address for current SIM instance. * @param instance device instance. * @return select Timer/PWM x external clock pin select setting */ sim_tpm_clk_sel_t SIM_HAL_GetTpmExternalClkPinSelMode(uint32_t baseAddr, uint8_t instance); /*! * @brief Sets the Timer/PWM x channel y input capture source select setting. * * This function selects the Timer/PWM x channel y input capture source. * * @param baseAddr Base address for current SIM instance. * @param instance device instance. * @param channel TPM channel y * @param select Timer/PWM x channel y input capture source * - 0: TPMx_CH0 signal * - 1: CMP0 output */ void SIM_HAL_SetTpmChSrcMode(uint32_t baseAddr, uint8_t instance, uint8_t channel, sim_tpm_ch_src_t select); /*! * @brief Gets the Timer/PWM x channel y input capture source select setting. * * This function gets the Timer/PWM x channel y input capture source select setting. * * @param baseAddr Base address for current SIM instance. * @param instance device instance. * @param channel Tpm channel y * @return select Timer/PWM x channel y input capture source select setting */ sim_tpm_ch_src_t SIM_HAL_GetTpmChSrcMode(uint32_t baseAddr, uint8_t instance, uint8_t channel); #endif #if FSL_FEATURE_SIM_SDID_HAS_FAMILYID /*! * @brief Gets the Kinetis Family ID in the System Device ID register (SIM_SDID). * * This function gets the Kinetis Family ID in the System Device ID register. * * @param baseAddr Base address for current SIM instance. * @return id Kinetis Family ID */ static inline uint32_t SIM_HAL_GetFamilyId(uint32_t baseAddr) { return BR_SIM_SDID_FAMILYID(baseAddr); } #endif #if FSL_FEATURE_SIM_SDID_HAS_SUBFAMID /*! * @brief Gets the Kinetis Sub-Family ID in the System Device ID register (SIM_SDID). * * This function gets the Kinetis Sub-Family ID in System Device ID register. * * @param baseAddr Base address for current SIM instance. * @return id Kinetis Sub-Family ID */ static inline uint32_t SIM_HAL_GetSubFamilyId(uint32_t baseAddr) { return BR_SIM_SDID_SUBFAMID(baseAddr); } #endif #if FSL_FEATURE_SIM_SDID_HAS_SERIESID /*! * @brief Gets the Kinetis SeriesID in the System Device ID register (SIM_SDID). * * This function gets the Kinetis Series ID in System Device ID register. * * @param baseAddr Base address for current SIM instance. * @return id Kinetis Series ID */ static inline uint32_t SIM_HAL_GetSeriesId(uint32_t baseAddr) { return BR_SIM_SDID_SERIESID(baseAddr); } #endif #if FSL_FEATURE_SIM_SDID_HAS_FAMID /*! * @brief Gets the Kinetis Fam ID in System Device ID register (SIM_SDID). * * This function gets the Kinetis Fam ID in System Device ID register. * * @param baseAddr Base address for current SIM instance. * @return id Kinetis Fam ID */ static inline uint32_t SIM_HAL_GetFamId(uint32_t baseAddr) { return BR_SIM_SDID_FAMID(baseAddr); } #endif /*! * @brief Gets the Kinetis Pincount ID in System Device ID register (SIM_SDID). * * This function gets the Kinetis Pincount ID in System Device ID register. * * @param baseAddr Base address for current SIM instance. * @return id Kinetis Pincount ID */ static inline uint32_t SIM_HAL_GetPinCntId(uint32_t baseAddr) { return BR_SIM_SDID_PINID(baseAddr); } /*! * @brief Gets the Kinetis Revision ID in the System Device ID register (SIM_SDID). * * This function gets the Kinetis Revision ID in System Device ID register. * * @param baseAddr Base address for current SIM instance. * @return id Kinetis Revision ID */ static inline uint32_t SIM_HAL_GetRevId(uint32_t baseAddr) { return BR_SIM_SDID_REVID(baseAddr); } #if FSL_FEATURE_SIM_SDID_HAS_DIEID /*! * @brief Gets the Kinetis Die ID in the System Device ID register (SIM_SDID). * * This function gets the Kinetis Die ID in System Device ID register. * * @param baseAddr Base address for current SIM instance. * @return id Kinetis Die ID */ static inline uint32_t SIM_HAL_GetDieId(uint32_t baseAddr) { return BR_SIM_SDID_DIEID(baseAddr); } #endif #if FSL_FEATURE_SIM_SDID_HAS_SRAMSIZE /*! * @brief Gets the Kinetis SRAM size in the System Device ID register (SIM_SDID). * * This function gets the Kinetis SRAM Size in System Device ID register. * * @param baseAddr Base address for current SIM instance. * @return id Kinetis SRAM Size */ static inline uint32_t SIM_HAL_GetSramSize(uint32_t baseAddr) { return BR_SIM_SDID_SRAMSIZE(baseAddr); } #endif #if FSL_FEATURE_SIM_FCFG_HAS_NVMSIZE /*! * @brief Gets the FlexNVM size in the Flash Configuration Register 1 (SIM_FCFG). * * This function gets the FlexNVM size in the Flash Configuration Register 1. * * @param baseAddr Base address for current SIM instance. * @return size FlexNVM Size */ static inline uint32_t SIM_HAL_GetFlexnvmSize(uint32_t baseAddr) { return BR_SIM_FCFG1_NVMSIZE(baseAddr); } #endif /*! * @brief Gets the program flash size in the Flash Configuration Register 1 (SIM_FCFG). * * This function gets the program flash size in the Flash Configuration Register 1. * * @param baseAddr Base address for current SIM instance. * @return size Program flash Size */ static inline uint32_t SIM_HAL_GetProgramFlashSize(uint32_t baseAddr) { return BR_SIM_FCFG1_PFSIZE(baseAddr); } #if FSL_FEATURE_SIM_FCFG_HAS_EESIZE /*! * @brief Gets the EEProm size in the Flash Configuration Register 1 (SIM_FCFG). * * This function gets the EEProm size in the Flash Configuration Register 1. * * @param baseAddr Base address for current SIM instance. * @return size EEProm Size */ static inline uint32_t SIM_HAL_GetEepromSize(uint32_t baseAddr) { return BR_SIM_FCFG1_EESIZE(baseAddr); } #endif #if FSL_FEATURE_SIM_FCFG_HAS_DEPART /*! * @brief Gets the FlexNVM partition in the Flash Configuration Register 1 (SIM_FCFG). * * This function gets the FlexNVM partition in the Flash Configuration Register 1 * * @param baseAddr Base address for current SIM instance. * @return setting FlexNVM partition setting */ static inline uint32_t SIM_HAL_GetFlexnvmPartition(uint32_t baseAddr) { return BR_SIM_FCFG1_DEPART(baseAddr); } #endif #if FSL_FEATURE_SIM_FCFG_HAS_FLASHDOZE /*! * @brief Sets the Flash Doze in the Flash Configuration Register 1 (SIM_FCFG). * * This function sets the Flash Doze in the Flash Configuration Register 1. * * @param baseAddr Base address for current SIM instance. * @param setting Flash Doze setting */ static inline void SIM_HAL_SetFlashDoze(uint32_t baseAddr, uint32_t setting) { BW_SIM_FCFG1_FLASHDOZE(baseAddr, setting); } /*! * @brief Gets the Flash Doze in the Flash Configuration Register 1 (SIM_FCFG). * * This function gets the Flash Doze in the Flash Configuration Register 1. * * @param baseAddr Base address for current SIM instance. * @return setting Flash Doze setting */ static inline uint32_t SIM_HAL_GetFlashDoze(uint32_t baseAddr) { return BR_SIM_FCFG1_FLASHDOZE(baseAddr); } #endif #if FSL_FEATURE_SIM_FCFG_HAS_FLASHDIS /*! * @brief Sets the Flash disable setting in the Flash Configuration Register 1 (SIM_FCFG). * * This function sets the Flash disable setting in the Flash Configuration Register 1. * * @param baseAddr Base address for current SIM instance. * @param disable Flash disable setting */ static inline void SIM_HAL_SetFlashDisableCmd(uint32_t baseAddr, bool disable) { BW_SIM_FCFG1_FLASHDIS(baseAddr, disable); } /*! * @brief Gets the Flash disable setting in the Flash Configuration Register 1 (SIM_FCFG). * * This function gets the Flash disable setting in the Flash Configuration Register 1. * * @param baseAddr Base address for current SIM instance. * @return setting Flash disable setting */ static inline bool SIM_HAL_GetFlashDisableCmd(uint32_t baseAddr) { return (bool)BR_SIM_FCFG1_FLASHDIS(baseAddr); } #endif #if FSL_FEATURE_SIM_FCFG_HAS_MAXADDR0 /*! * @brief Gets the Flash maximum address block 0 in the Flash Configuration Register 1 (SIM_FCFG). * * This function gets the Flash maximum block 0 in Flash Configuration Register 2. * * @param baseAddr Base address for current SIM instance. * @return address Flash maximum block 0 address */ static inline uint32_t SIM_HAL_GetFlashMaxAddrBlock0(uint32_t baseAddr) { return BR_SIM_FCFG2_MAXADDR0(baseAddr); } #endif #if FSL_FEATURE_SIM_FCFG_HAS_MAXADDR1 /*! * @brief Gets the Flash maximum address block 1 in Flash Configuration Register 2. * * This function gets the Flash maximum block 1 in Flash Configuration Register 1. * * @param baseAddr Base address for current SIM instance. * @return address Flash maximum block 0 address */ static inline uint32_t SIM_HAL_GetFlashMaxAddrBlock1(uint32_t baseAddr) { return BR_SIM_FCFG2_MAXADDR1(baseAddr); } #endif #if FSL_FEATURE_SIM_FCFG_HAS_MAXADDR01 /*! * @brief Gets the Flash maximum address block 0 in the Flash Configuration Register 1 (SIM_FCFG). * * This function gets the Flash maximum block 0 in Flash Configuration Register 2. * * @param baseAddr Base address for current SIM instance. * @return address Flash maximum block 0 address */ static inline uint32_t SIM_HAL_GetFlashMaxAddrBlock01(uint32_t baseAddr) { return BR_SIM_FCFG2_MAXADDR01(baseAddr); } #endif #if FSL_FEATURE_SIM_FCFG_HAS_MAXADDR23 /*! * @brief Gets the Flash maximum address block 1 in the Flash Configuration Register 2. * * This function gets the Flash maximum block 1 in Flash Configuration Register 1. * * @param baseAddr Base address for current SIM instance. * @return address Flash maximum block 0 address */ static inline uint32_t SIM_HAL_GetFlashMaxAddrBlock23(uint32_t baseAddr) { return BR_SIM_FCFG2_MAXADDR23(baseAddr); } #endif #if FSL_FEATURE_SIM_FCFG_HAS_PFLSH /*! * @brief Gets the program flash in the Flash Configuration Register 2. * * This function gets the program flash maximum block 0 in Flash Configuration Register 1. * * @param baseAddr Base address for current SIM instance. * @return status program flash status */ static inline uint32_t SIM_HAL_GetProgramFlashCmd(uint32_t baseAddr) { return BR_SIM_FCFG2_PFLSH(baseAddr); } #endif /*@}*/ #if defined(__cplusplus) } #endif /* __cplusplus*/ /*! @}*/ /* * Include the CPU-specific clock API header files. */ #if (defined(CPU_MK02FN128VFM10) || defined(CPU_MK02FN64VFM10) || defined(CPU_MK02FN128VLF10) || \ defined(CPU_MK02FN64VLF10) || defined(CPU_MK02FN128VLH10) || defined(CPU_MK02FN64VLH10)) #define K02F12810_SERIES #elif (defined(CPU_MK20DX128VMP5) || defined(CPU_MK20DN128VMP5) || defined(CPU_MK20DX64VMP5) || \ defined(CPU_MK20DN64VMP5) || defined(CPU_MK20DX32VMP5) || defined(CPU_MK20DN32VMP5) || \ defined(CPU_MK20DX128VLH5) || defined(CPU_MK20DN128VLH5) || defined(CPU_MK20DX64VLH5) || \ defined(CPU_MK20DN64VLH5) || defined(CPU_MK20DX32VLH5) || defined(CPU_MK20DN32VLH5) || \ defined(CPU_MK20DX128VFM5) || defined(CPU_MK20DN128VFM5) || defined(CPU_MK20DX64VFM5) || \ defined(CPU_MK20DN64VFM5) || defined(CPU_MK20DX32VFM5) || defined(CPU_MK20DN32VFM5) || \ defined(CPU_MK20DX128VFT5) || defined(CPU_MK20DN128VFT5) || defined(CPU_MK20DX64VFT5) || \ defined(CPU_MK20DN64VFT5) || defined(CPU_MK20DX32VFT5) || defined(CPU_MK20DN32VFT5) || \ defined(CPU_MK20DX128VLF5) || defined(CPU_MK20DN128VLF5) || defined(CPU_MK20DX64VLF5) || \ defined(CPU_MK20DN64VLF5) || defined(CPU_MK20DX32VLF5) || defined(CPU_MK20DN32VLF5)) #define K20D5_SERIES #elif (defined(CPU_MK22FN128VDC10) || defined(CPU_MK22FN128VLH10) || defined(CPU_MK22FN128VLL10) || \ defined(CPU_MK22FN128VMP10)) #define K22F12810_SERIES /* Clock System Level API header file */ #include "MK22F12810/fsl_sim_hal_K22F12810.h" #elif (defined(CPU_MK22FN256VDC12) || defined(CPU_MK22FN256VLH12) || defined(CPU_MK22FN256VLL12) || \ defined(CPU_MK22FN256VMP12)) #define K22F25612_SERIES /* Clock System Level API header file */ #include "MK22F25612/fsl_sim_hal_K22F25612.h" #elif (defined(CPU_MK22FN512VDC12) || defined(CPU_MK22FN512VLH12) || defined(CPU_MK22FN512VLL12)) #define K22F51212_SERIES /* Clock System Level API header file */ #include "MK22F51212/fsl_sim_hal_K22F51212.h" #elif (defined(CPU_MK24FN1M0VDC12) || defined(CPU_MK24FN1M0VLQ12)) #define K24F12_SERIES /* Clock System Level API header file */ #include "MK24F12/fsl_sim_hal_K24F12.h" #elif (defined(CPU_MK24FN256VDC12)) #define K24F25612_SERIES #elif (defined(CPU_MK63FN1M0VLQ12) || defined(CPU_MK63FN1M0VMD12)) #define K63F12_SERIES /* Clock System Level API header file */ #include "MK63F12/fsl_sim_hal_K63F12.h" #elif (defined(CPU_MK64FX512VDC12) || defined(CPU_MK64FN1M0VDC12) || defined(CPU_MK64FX512VLL12) || \ defined(CPU_MK64FN1M0VLL12) || defined(CPU_MK64FX512VLQ12) || defined(CPU_MK64FN1M0VLQ12) || \ defined(CPU_MK64FX512VMD12) || defined(CPU_MK64FN1M0VMD12)) #define K64F12_SERIES /* Clock System Level API header file */ #include "MK64F12/fsl_sim_hal_K64F12.h" #elif (defined(CPU_MK65FN2M0CAC18) || defined(CPU_MK65FX1M0CAC18) || defined(CPU_MK65FN2M0VMI18) || \ defined(CPU_MK65FX1M0VMI18)) #define K65F18_SERIES #elif (defined(CPU_MK66FN2M0VLQ18) || defined(CPU_MK66FX1M0VLQ18) || defined(CPU_MK66FN2M0VMD18) || \ defined(CPU_MK66FX1M0VMD18)) #define K66F18_SERIES #elif (defined(CPU_MK70FN1M0VMF12) || defined(CPU_MK70FX512VMF12) || defined(CPU_MK70FN1M0VMF15) || \ defined(CPU_MK70FX512VMF15) || defined(CPU_MK70FN1M0VMJ12) || defined(CPU_MK70FX512VMJ12) || \ defined(CPU_MK70FN1M0VMJ15) || defined(CPU_MK70FX512VMJ15)) #define K70F12_SERIES #elif (defined(CPU_MK70FN1M0VMF12) || defined(CPU_MK70FX512VMF12) || defined(CPU_MK70FN1M0VMF15) || \ defined(CPU_MK70FX512VMF15) || defined(CPU_MK70FN1M0VMJ12) || defined(CPU_MK70FX512VMJ12) || \ defined(CPU_MK70FN1M0VMJ15) || defined(CPU_MK70FX512VMJ15)) #define K70F15_SERIES #elif (defined(CPU_MKL02Z32CAF4) || defined(CPU_MKL02Z8VFG4) || defined(CPU_MKL02Z16VFG4) || \ defined(CPU_MKL02Z32VFG4) || defined(CPU_MKL02Z16VFK4) || defined(CPU_MKL02Z32VFK4) || \ defined(CPU_MKL02Z16VFM4) || defined(CPU_MKL02Z32VFM4)) #define KL02Z4_SERIES #elif (defined(CPU_MKL03Z32CAF4) || defined(CPU_MKL03Z8VFG4) || defined(CPU_MKL03Z16VFG4) || \ defined(CPU_MKL03Z32VFG4) || defined(CPU_MKL03Z8VFK4) || defined(CPU_MKL03Z16VFK4) || \ defined(CPU_MKL03Z32VFK4)) #define KL03Z4_SERIES #elif (defined(CPU_MKL05Z8VFK4) || defined(CPU_MKL05Z16VFK4) || defined(CPU_MKL05Z32VFK4) || \ defined(CPU_MKL05Z8VLC4) || defined(CPU_MKL05Z16VLC4) || defined(CPU_MKL05Z32VLC4) || \ defined(CPU_MKL05Z8VFM4) || defined(CPU_MKL05Z16VFM4) || defined(CPU_MKL05Z32VFM4) || \ defined(CPU_MKL05Z16VLF4) || defined(CPU_MKL05Z32VLF4)) #define KL05Z4_SERIES #elif (defined(CPU_MKL13Z64VFM4) || defined(CPU_MKL13Z128VFM4) || defined(CPU_MKL13Z256VFM4) || \ defined(CPU_MKL13Z64VFT4) || defined(CPU_MKL13Z128VFT4) || defined(CPU_MKL13Z256VFT4) || \ defined(CPU_MKL13Z64VLH4) || defined(CPU_MKL13Z128VLH4) || defined(CPU_MKL13Z256VLH4) || \ defined(CPU_MKL13Z64VMP4) || defined(CPU_MKL13Z128VMP4) || defined(CPU_MKL13Z256VMP4)) #define KL13Z4_SERIES #elif (defined(CPU_MKL23Z64VFM4) || defined(CPU_MKL23Z128VFM4) || defined(CPU_MKL23Z256VFM4) || \ defined(CPU_MKL23Z64VFT4) || defined(CPU_MKL23Z128VFT4) || defined(CPU_MKL23Z256VFT4) || \ defined(CPU_MKL23Z64VLH4) || defined(CPU_MKL23Z128VLH4) || defined(CPU_MKL23Z256VLH4) || \ defined(CPU_MKL23Z64VMP4) || defined(CPU_MKL23Z128VMP4) || defined(CPU_MKL23Z256VMP4)) #define KL23Z4_SERIES #elif (defined(CPU_MKL25Z32VFM4) || defined(CPU_MKL25Z64VFM4) || defined(CPU_MKL25Z128VFM4) || \ defined(CPU_MKL25Z32VFT4) || defined(CPU_MKL25Z64VFT4) || defined(CPU_MKL25Z128VFT4) || \ defined(CPU_MKL25Z32VLH4) || defined(CPU_MKL25Z64VLH4) || defined(CPU_MKL25Z128VLH4) || \ defined(CPU_MKL25Z32VLK4) || defined(CPU_MKL25Z64VLK4) || defined(CPU_MKL25Z128VLK4)) #define KL25Z4_SERIES /* Clock System Level API header file */ #include "MKL25Z4/fsl_sim_hal_KL25Z4.h" #elif (defined(CPU_MKL26Z32VFM4) || defined(CPU_MKL26Z64VFM4) || defined(CPU_MKL26Z128VFM4) || \ defined(CPU_MKL26Z32VFT4) || defined(CPU_MKL26Z64VFT4) || defined(CPU_MKL26Z128VFT4) || \ defined(CPU_MKL26Z32VLH4) || defined(CPU_MKL26Z64VLH4) || defined(CPU_MKL26Z128VLH4) || \ defined(CPU_MKL26Z256VLH4) || defined(CPU_MKL26Z256VLK4) || defined(CPU_MKL26Z128VLL4) || \ defined(CPU_MKL26Z256VLL4) || defined(CPU_MKL26Z128VMC4) || defined(CPU_MKL26Z256VMC4)) #define KL26Z4_SERIES #elif (defined(CPU_MKL33Z128VLH4) || defined(CPU_MKL33Z256VLH4) || defined(CPU_MKL33Z128VMP4) || \ defined(CPU_MKL33Z256VMP4)) #define KL33Z4_SERIES #elif (defined(CPU_MKL43Z64VLH4) || defined(CPU_MKL43Z128VLH4) || defined(CPU_MKL43Z256VLH4) || \ defined(CPU_MKL43Z64VMP4) || defined(CPU_MKL43Z128VMP4) || defined(CPU_MKL43Z256VMP4)) #define KL43Z4_SERIES #elif (defined(CPU_MKL46Z128VLH4) || defined(CPU_MKL46Z256VLH4) || defined(CPU_MKL46Z128VLL4) || \ defined(CPU_MKL46Z256VLL4) || defined(CPU_MKL46Z128VMC4) || defined(CPU_MKL46Z256VMC4)) #define KL46Z4_SERIES #elif (defined(CPU_MKV30F128VFM10) || defined(CPU_MKV30F64VFM10) || defined(CPU_MKV30F128VLF10) || \ defined(CPU_MKV30F64VLF10) || defined(CPU_MKV30F128VLH10) || defined(CPU_MKV30F64VLH10)) #define KV30F12810_SERIES #elif (defined(CPU_MKV31F128VLH10) || defined(CPU_MKV31F128VLL10)) #define KV31F12810_SERIES /* Clock System Level API header file */ #include "MKV31F12810/fsl_sim_hal_KV31F12810.h" #elif (defined(CPU_MKV31F256VLH12) || defined(CPU_MKV31F256VLL12)) #define KV31F25612_SERIES /* Clock System Level API header file */ #include "MKV31F25612/fsl_sim_hal_KV31F25612.h" #elif (defined(CPU_MKV31F512VLH12) || defined(CPU_MKV31F512VLL12)) #define KV31F51212_SERIES /* Clock System Level API header file */ #include "MKV31F51212/fsl_sim_hal_KV31F51212.h" #elif (defined(CPU_MKV40F128VLH15) || defined(CPU_MKV40F128VLL15) || defined(CPU_MKV40F256VLH15) || \ defined(CPU_MKV40F256VLL15) || defined(CPU_MKV40F64VLH15)) #define KV40F15_SERIES #elif (defined(CPU_MKV43F128VLH15) || defined(CPU_MKV43F128VLL15) || defined(CPU_MKV43F64VLH15)) #define KV43F15_SERIES #elif (defined(CPU_MKV44F128VLH15) || defined(CPU_MKV44F128VLL15) || defined(CPU_MKV44F64VLH15)) #define KV44F15_SERIES #elif (defined(CPU_MKV45F128VLH15) || defined(CPU_MKV45F128VLL15) || defined(CPU_MKV45F256VLH15) || \ defined(CPU_MKV45F256VLL15)) #define KV45F15_SERIES #elif (defined(CPU_MKV46F128VLH15) || defined(CPU_MKV46F128VLL15) || defined(CPU_MKV46F256VLH15) || \ defined(CPU_MKV46F256VLL15)) #define KV46F15_SERIES #else #error "No valid CPU defined!" #endif #endif /* __FSL_SIM_HAL_H__*/ /******************************************************************************* * EOF ******************************************************************************/ ================================================ FILE: Zelig/mbed/TARGET_K64F/TARGET_Freescale/TARGET_KPSDK_MCUS/TARGET_KPSDK_CODE/hal/smc/fsl_smc_features.h ================================================ /* ** ################################################################### ** Version: rev. 1.0, 2014-05-14 ** Build: b140515 ** ** Abstract: ** Chip specific module features. ** ** Copyright: 2014 Freescale Semiconductor, Inc. ** All rights reserved. ** ** Redistribution and use in source and binary forms, with or without modification, ** are permitted provided that the following conditions are met: ** ** o Redistributions of source code must retain the above copyright notice, this list ** of conditions and the following disclaimer. ** ** o Redistributions in binary form must reproduce the above copyright notice, this ** list of conditions and the following disclaimer in the documentation and/or ** other materials provided with the distribution. ** ** o Neither the name of Freescale Semiconductor, Inc. nor the names of its ** contributors may be used to endorse or promote products derived from this ** software without specific prior written permission. ** ** THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ** ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED ** WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE ** DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT 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. ** ** http: www.freescale.com ** mail: support@freescale.com ** ** Revisions: ** - rev. 1.0 (2014-05-14) ** Customer release. ** ** ################################################################### */ #if !defined(__FSL_SMC_FEATURES_H__) #define __FSL_SMC_FEATURES_H__ #if defined(CPU_MK02FN128VFM10) || defined(CPU_MK02FN64VFM10) || defined(CPU_MK02FN128VLF10) || defined(CPU_MK02FN64VLF10) || \ defined(CPU_MK02FN128VLH10) || defined(CPU_MK02FN64VLH10) || defined(CPU_MK22FN128VDC10) || defined(CPU_MK22FN128VLH10) || \ defined(CPU_MK22FN128VLL10) || defined(CPU_MK22FN128VMP10) || defined(CPU_MK22FN256VDC12) || defined(CPU_MK22FN256VLH12) || \ defined(CPU_MK22FN256VLL12) || defined(CPU_MK22FN256VMP12) || defined(CPU_MK22FN512VDC12) || defined(CPU_MK22FN512VLH12) || \ defined(CPU_MK22FN512VLL12) || defined(CPU_MKV30F128VFM10) || defined(CPU_MKV30F64VFM10) || defined(CPU_MKV30F128VLF10) || \ defined(CPU_MKV30F64VLF10) || defined(CPU_MKV30F128VLH10) || defined(CPU_MKV30F64VLH10) || defined(CPU_MKV31F128VLH10) || \ defined(CPU_MKV31F128VLL10) || defined(CPU_MKV31F256VLH12) || defined(CPU_MKV31F256VLL12) || defined(CPU_MKV31F512VLH12) || \ defined(CPU_MKV31F512VLL12) /* @brief Has partial stop option (register bit STOPCTRL[PSTOPO]). */ #define FSL_FEATURE_SMC_HAS_PSTOPO (1) /* @brief Has LPO power option (register bit STOPCTRL[LPOPO]). */ #define FSL_FEATURE_SMC_HAS_LPOPO (0) /* @brief Has POR power option (register bit STOPCTRL[PORPO] or VLLSCTRL[PORPO]). */ #define FSL_FEATURE_SMC_HAS_PORPO (1) /* @brief Has low power wakeup on interrupt (register bit PMCTRL[LPWUI]). */ #define FSL_FEATURE_SMC_HAS_LPWUI (0) /* @brief Has LLS or VLLS mode control (register bit STOPCTRL[LLSM]). */ #define FSL_FEATURE_SMC_HAS_LLS_SUBMODE (1) /* @brief Has VLLS mode control (register bit VLLSCTRL[VLLSM]). */ #define FSL_FEATURE_SMC_USE_VLLSCTRL_REG (0) /* @brief Has VLLS mode control (register bit STOPCTRL[VLLSM]). */ #define FSL_FEATURE_SMC_USE_STOPCTRL_VLLSM (0) /* @brief Has RAM partition 2 power option (register bit STOPCTRL[RAM2PO]). */ #define FSL_FEATURE_SMC_HAS_RAM2_POWER_OPTION (0) /* @brief Has high speed run mode (register bit PMPROT[AHSRUN]). */ #define FSL_FEATURE_SMC_HAS_HIGH_SPEED_RUN_MODE (1) /* @brief Has low leakage stop mode (register bit PMPROT[ALLS]). */ #define FSL_FEATURE_SMC_HAS_LOW_LEAKAGE_STOP_MODE (1) #elif defined(CPU_MK20DX128VMP5) || defined(CPU_MK20DN128VMP5) || defined(CPU_MK20DX64VMP5) || defined(CPU_MK20DN64VMP5) || \ defined(CPU_MK20DX32VMP5) || defined(CPU_MK20DN32VMP5) || defined(CPU_MK20DX128VLH5) || defined(CPU_MK20DN128VLH5) || \ defined(CPU_MK20DX64VLH5) || defined(CPU_MK20DN64VLH5) || defined(CPU_MK20DX32VLH5) || defined(CPU_MK20DN32VLH5) || \ defined(CPU_MK20DX128VFM5) || defined(CPU_MK20DN128VFM5) || defined(CPU_MK20DX64VFM5) || defined(CPU_MK20DN64VFM5) || \ defined(CPU_MK20DX32VFM5) || defined(CPU_MK20DN32VFM5) || defined(CPU_MK20DX128VFT5) || defined(CPU_MK20DN128VFT5) || \ defined(CPU_MK20DX64VFT5) || defined(CPU_MK20DN64VFT5) || defined(CPU_MK20DX32VFT5) || defined(CPU_MK20DN32VFT5) || \ defined(CPU_MK20DX128VLF5) || defined(CPU_MK20DN128VLF5) || defined(CPU_MK20DX64VLF5) || defined(CPU_MK20DN64VLF5) || \ defined(CPU_MK20DX32VLF5) || defined(CPU_MK20DN32VLF5) || defined(CPU_MK24FN1M0VDC12) || defined(CPU_MK24FN1M0VLL12) || \ defined(CPU_MK24FN1M0VLQ12) || defined(CPU_MK24FN256VDC12) || defined(CPU_MK63FN1M0VLQ12) || defined(CPU_MK63FN1M0VMD12) || \ defined(CPU_MK64FX512VDC12) || defined(CPU_MK64FN1M0VDC12) || defined(CPU_MK64FX512VLL12) || defined(CPU_MK64FN1M0VLL12) || \ defined(CPU_MK64FX512VLQ12) || defined(CPU_MK64FN1M0VLQ12) || defined(CPU_MK64FX512VMD12) || defined(CPU_MK64FN1M0VMD12) /* @brief Has partial stop option (register bit STOPCTRL[PSTOPO]). */ #define FSL_FEATURE_SMC_HAS_PSTOPO (0) /* @brief Has LPO power option (register bit STOPCTRL[LPOPO]). */ #define FSL_FEATURE_SMC_HAS_LPOPO (0) /* @brief Has POR power option (register bit STOPCTRL[PORPO] or VLLSCTRL[PORPO]). */ #define FSL_FEATURE_SMC_HAS_PORPO (1) /* @brief Has low power wakeup on interrupt (register bit PMCTRL[LPWUI]). */ #define FSL_FEATURE_SMC_HAS_LPWUI (1) /* @brief Has LLS or VLLS mode control (register bit STOPCTRL[LLSM]). */ #define FSL_FEATURE_SMC_HAS_LLS_SUBMODE (0) /* @brief Has VLLS mode control (register bit VLLSCTRL[VLLSM]). */ #define FSL_FEATURE_SMC_USE_VLLSCTRL_REG (1) /* @brief Has VLLS mode control (register bit STOPCTRL[VLLSM]). */ #define FSL_FEATURE_SMC_USE_STOPCTRL_VLLSM (0) /* @brief Has RAM partition 2 power option (register bit STOPCTRL[RAM2PO]). */ #define FSL_FEATURE_SMC_HAS_RAM2_POWER_OPTION (0) /* @brief Has high speed run mode (register bit PMPROT[AHSRUN]). */ #define FSL_FEATURE_SMC_HAS_HIGH_SPEED_RUN_MODE (0) /* @brief Has low leakage stop mode (register bit PMPROT[ALLS]). */ #define FSL_FEATURE_SMC_HAS_LOW_LEAKAGE_STOP_MODE (1) #elif defined(CPU_MK65FN2M0CAC18) || defined(CPU_MK65FX1M0CAC18) || defined(CPU_MK65FN2M0VMI18) || defined(CPU_MK65FX1M0VMI18) || \ defined(CPU_MK66FN2M0VLQ18) || defined(CPU_MK66FX1M0VLQ18) || defined(CPU_MK66FN2M0VMD18) || defined(CPU_MK66FX1M0VMD18) /* @brief Has partial stop option (register bit STOPCTRL[PSTOPO]). */ #define FSL_FEATURE_SMC_HAS_PSTOPO (1) /* @brief Has LPO power option (register bit STOPCTRL[LPOPO]). */ #define FSL_FEATURE_SMC_HAS_LPOPO (0) /* @brief Has POR power option (register bit STOPCTRL[PORPO] or VLLSCTRL[PORPO]). */ #define FSL_FEATURE_SMC_HAS_PORPO (1) /* @brief Has low power wakeup on interrupt (register bit PMCTRL[LPWUI]). */ #define FSL_FEATURE_SMC_HAS_LPWUI (0) /* @brief Has LLS or VLLS mode control (register bit STOPCTRL[LLSM]). */ #define FSL_FEATURE_SMC_HAS_LLS_SUBMODE (1) /* @brief Has VLLS mode control (register bit VLLSCTRL[VLLSM]). */ #define FSL_FEATURE_SMC_USE_VLLSCTRL_REG (0) /* @brief Has VLLS mode control (register bit STOPCTRL[VLLSM]). */ #define FSL_FEATURE_SMC_USE_STOPCTRL_VLLSM (0) /* @brief Has RAM partition 2 power option (register bit STOPCTRL[RAM2PO]). */ #define FSL_FEATURE_SMC_HAS_RAM2_POWER_OPTION (1) /* @brief Has high speed run mode (register bit PMPROT[AHSRUN]). */ #define FSL_FEATURE_SMC_HAS_HIGH_SPEED_RUN_MODE (1) /* @brief Has low leakage stop mode (register bit PMPROT[ALLS]). */ #define FSL_FEATURE_SMC_HAS_LOW_LEAKAGE_STOP_MODE (1) #elif defined(CPU_MK70FN1M0VMF12) || defined(CPU_MK70FX512VMF12) || defined(CPU_MK70FN1M0VMF15) || defined(CPU_MK70FX512VMF15) || \ defined(CPU_MK70FN1M0VMJ12) || defined(CPU_MK70FX512VMJ12) || defined(CPU_MK70FN1M0VMJ15) || defined(CPU_MK70FX512VMJ15) /* @brief Has partial stop option (register bit STOPCTRL[PSTOPO]). */ #define FSL_FEATURE_SMC_HAS_PSTOPO (0) /* @brief Has LPO power option (register bit STOPCTRL[LPOPO]). */ #define FSL_FEATURE_SMC_HAS_LPOPO (0) /* @brief Has POR power option (register bit STOPCTRL[PORPO] or VLLSCTRL[PORPO]). */ #define FSL_FEATURE_SMC_HAS_PORPO (0) /* @brief Has low power wakeup on interrupt (register bit PMCTRL[LPWUI]). */ #define FSL_FEATURE_SMC_HAS_LPWUI (1) /* @brief Has LLS or VLLS mode control (register bit STOPCTRL[LLSM]). */ #define FSL_FEATURE_SMC_HAS_LLS_SUBMODE (0) /* @brief Has VLLS mode control (register bit VLLSCTRL[VLLSM]). */ #define FSL_FEATURE_SMC_USE_VLLSCTRL_REG (1) /* @brief Has VLLS mode control (register bit STOPCTRL[VLLSM]). */ #define FSL_FEATURE_SMC_USE_STOPCTRL_VLLSM (0) /* @brief Has RAM partition 2 power option (register bit STOPCTRL[RAM2PO]). */ #define FSL_FEATURE_SMC_HAS_RAM2_POWER_OPTION (0) /* @brief Has high speed run mode (register bit PMPROT[AHSRUN]). */ #define FSL_FEATURE_SMC_HAS_HIGH_SPEED_RUN_MODE (0) /* @brief Has low leakage stop mode (register bit PMPROT[ALLS]). */ #define FSL_FEATURE_SMC_HAS_LOW_LEAKAGE_STOP_MODE (1) #elif defined(CPU_MKL03Z32CAF4) || defined(CPU_MKL03Z8VFG4) || defined(CPU_MKL03Z16VFG4) || defined(CPU_MKL03Z32VFG4) || \ defined(CPU_MKL03Z8VFK4) || defined(CPU_MKL03Z16VFK4) || defined(CPU_MKL03Z32VFK4) /* @brief Has partial stop option (register bit STOPCTRL[PSTOPO]). */ #define FSL_FEATURE_SMC_HAS_PSTOPO (1) /* @brief Has LPO power option (register bit STOPCTRL[LPOPO]). */ #define FSL_FEATURE_SMC_HAS_LPOPO (1) /* @brief Has POR power option (register bit STOPCTRL[PORPO] or VLLSCTRL[PORPO]). */ #define FSL_FEATURE_SMC_HAS_PORPO (1) /* @brief Has low power wakeup on interrupt (register bit PMCTRL[LPWUI]). */ #define FSL_FEATURE_SMC_HAS_LPWUI (0) /* @brief Has LLS or VLLS mode control (register bit STOPCTRL[LLSM]). */ #define FSL_FEATURE_SMC_HAS_LLS_SUBMODE (0) /* @brief Has VLLS mode control (register bit VLLSCTRL[VLLSM]). */ #define FSL_FEATURE_SMC_USE_VLLSCTRL_REG (0) /* @brief Has VLLS mode control (register bit STOPCTRL[VLLSM]). */ #define FSL_FEATURE_SMC_USE_STOPCTRL_VLLSM (1) /* @brief Has RAM partition 2 power option (register bit STOPCTRL[RAM2PO]). */ #define FSL_FEATURE_SMC_HAS_RAM2_POWER_OPTION (0) /* @brief Has high speed run mode (register bit PMPROT[AHSRUN]). */ #define FSL_FEATURE_SMC_HAS_HIGH_SPEED_RUN_MODE (0) /* @brief Has low leakage stop mode (register bit PMPROT[ALLS]). */ #define FSL_FEATURE_SMC_HAS_LOW_LEAKAGE_STOP_MODE (0) #elif defined(CPU_MKL05Z8VFK4) || defined(CPU_MKL05Z16VFK4) || defined(CPU_MKL05Z32VFK4) || defined(CPU_MKL05Z8VLC4) || \ defined(CPU_MKL05Z16VLC4) || defined(CPU_MKL05Z32VLC4) || defined(CPU_MKL05Z8VFM4) || defined(CPU_MKL05Z16VFM4) || \ defined(CPU_MKL05Z32VFM4) || defined(CPU_MKL05Z16VLF4) || defined(CPU_MKL05Z32VLF4) || defined(CPU_MKL13Z64VFM4) || \ defined(CPU_MKL13Z128VFM4) || defined(CPU_MKL13Z256VFM4) || defined(CPU_MKL13Z64VFT4) || defined(CPU_MKL13Z128VFT4) || \ defined(CPU_MKL13Z256VFT4) || defined(CPU_MKL13Z64VLH4) || defined(CPU_MKL13Z128VLH4) || defined(CPU_MKL13Z256VLH4) || \ defined(CPU_MKL13Z64VMP4) || defined(CPU_MKL13Z128VMP4) || defined(CPU_MKL13Z256VMP4) || defined(CPU_MKL23Z64VFM4) || \ defined(CPU_MKL23Z128VFM4) || defined(CPU_MKL23Z256VFM4) || defined(CPU_MKL23Z64VFT4) || defined(CPU_MKL23Z128VFT4) || \ defined(CPU_MKL23Z256VFT4) || defined(CPU_MKL23Z64VLH4) || defined(CPU_MKL23Z128VLH4) || defined(CPU_MKL23Z256VLH4) || \ defined(CPU_MKL23Z64VMP4) || defined(CPU_MKL23Z128VMP4) || defined(CPU_MKL23Z256VMP4) || defined(CPU_MKL25Z32VFM4) || \ defined(CPU_MKL25Z64VFM4) || defined(CPU_MKL25Z128VFM4) || defined(CPU_MKL25Z32VFT4) || defined(CPU_MKL25Z64VFT4) || \ defined(CPU_MKL25Z128VFT4) || defined(CPU_MKL25Z32VLH4) || defined(CPU_MKL25Z64VLH4) || defined(CPU_MKL25Z128VLH4) || \ defined(CPU_MKL25Z32VLK4) || defined(CPU_MKL25Z64VLK4) || defined(CPU_MKL25Z128VLK4) || defined(CPU_MKL26Z256VLK4) || \ defined(CPU_MKL26Z128VLL4) || defined(CPU_MKL26Z256VLL4) || defined(CPU_MKL26Z128VMC4) || defined(CPU_MKL26Z256VMC4) || \ defined(CPU_MKL33Z128VLH4) || defined(CPU_MKL33Z256VLH4) || defined(CPU_MKL33Z128VMP4) || defined(CPU_MKL33Z256VMP4) || \ defined(CPU_MKL43Z64VLH4) || defined(CPU_MKL43Z128VLH4) || defined(CPU_MKL43Z256VLH4) || defined(CPU_MKL43Z64VMP4) || \ defined(CPU_MKL43Z128VMP4) || defined(CPU_MKL43Z256VMP4) || defined(CPU_MKL46Z128VLH4) || defined(CPU_MKL46Z256VLH4) || \ defined(CPU_MKL46Z128VLL4) || defined(CPU_MKL46Z256VLL4) || defined(CPU_MKL46Z128VMC4) || defined(CPU_MKL46Z256VMC4) /* @brief Has partial stop option (register bit STOPCTRL[PSTOPO]). */ #define FSL_FEATURE_SMC_HAS_PSTOPO (1) /* @brief Has LPO power option (register bit STOPCTRL[LPOPO]). */ #define FSL_FEATURE_SMC_HAS_LPOPO (0) /* @brief Has POR power option (register bit STOPCTRL[PORPO] or VLLSCTRL[PORPO]). */ #define FSL_FEATURE_SMC_HAS_PORPO (1) /* @brief Has low power wakeup on interrupt (register bit PMCTRL[LPWUI]). */ #define FSL_FEATURE_SMC_HAS_LPWUI (0) /* @brief Has LLS or VLLS mode control (register bit STOPCTRL[LLSM]). */ #define FSL_FEATURE_SMC_HAS_LLS_SUBMODE (0) /* @brief Has VLLS mode control (register bit VLLSCTRL[VLLSM]). */ #define FSL_FEATURE_SMC_USE_VLLSCTRL_REG (0) /* @brief Has VLLS mode control (register bit STOPCTRL[VLLSM]). */ #define FSL_FEATURE_SMC_USE_STOPCTRL_VLLSM (1) /* @brief Has RAM partition 2 power option (register bit STOPCTRL[RAM2PO]). */ #define FSL_FEATURE_SMC_HAS_RAM2_POWER_OPTION (0) /* @brief Has high speed run mode (register bit PMPROT[AHSRUN]). */ #define FSL_FEATURE_SMC_HAS_HIGH_SPEED_RUN_MODE (0) /* @brief Has low leakage stop mode (register bit PMPROT[ALLS]). */ #define FSL_FEATURE_SMC_HAS_LOW_LEAKAGE_STOP_MODE (1) #elif defined(CPU_MKV40F128VLH15) || defined(CPU_MKV40F128VLL15) || defined(CPU_MKV40F256VLH15) || defined(CPU_MKV40F256VLL15) || \ defined(CPU_MKV40F64VLH15) || defined(CPU_MKV43F128VLH15) || defined(CPU_MKV43F128VLL15) || defined(CPU_MKV43F64VLH15) || \ defined(CPU_MKV44F128VLH15) || defined(CPU_MKV44F128VLL15) || defined(CPU_MKV44F64VLH15) || defined(CPU_MKV45F128VLH15) || \ defined(CPU_MKV45F128VLL15) || defined(CPU_MKV45F256VLH15) || defined(CPU_MKV45F256VLL15) || defined(CPU_MKV46F128VLH15) || \ defined(CPU_MKV46F128VLL15) || defined(CPU_MKV46F256VLH15) || defined(CPU_MKV46F256VLL15) /* @brief Has partial stop option (register bit STOPCTRL[PSTOPO]). */ #define FSL_FEATURE_SMC_HAS_PSTOPO (1) /* @brief Has LPO power option (register bit STOPCTRL[LPOPO]). */ #define FSL_FEATURE_SMC_HAS_LPOPO (1) /* @brief Has POR power option (register bit STOPCTRL[PORPO] or VLLSCTRL[PORPO]). */ #define FSL_FEATURE_SMC_HAS_PORPO (1) /* @brief Has low power wakeup on interrupt (register bit PMCTRL[LPWUI]). */ #define FSL_FEATURE_SMC_HAS_LPWUI (0) /* @brief Has LLS or VLLS mode control (register bit STOPCTRL[LLSM]). */ #define FSL_FEATURE_SMC_HAS_LLS_SUBMODE (0) /* @brief Has VLLS mode control (register bit VLLSCTRL[VLLSM]). */ #define FSL_FEATURE_SMC_USE_VLLSCTRL_REG (0) /* @brief Has VLLS mode control (register bit STOPCTRL[VLLSM]). */ #define FSL_FEATURE_SMC_USE_STOPCTRL_VLLSM (1) /* @brief Has RAM partition 2 power option (register bit STOPCTRL[RAM2PO]). */ #define FSL_FEATURE_SMC_HAS_RAM2_POWER_OPTION (0) /* @brief Has high speed run mode (register bit PMPROT[AHSRUN]). */ #define FSL_FEATURE_SMC_HAS_HIGH_SPEED_RUN_MODE (1) /* @brief Has low leakage stop mode (register bit PMPROT[ALLS]). */ #define FSL_FEATURE_SMC_HAS_LOW_LEAKAGE_STOP_MODE (0) #else #error "No valid CPU defined!" #endif #endif /* __FSL_SMC_FEATURES_H__ */ /******************************************************************************* * EOF ******************************************************************************/ ================================================ FILE: Zelig/mbed/TARGET_K64F/TARGET_Freescale/TARGET_KPSDK_MCUS/TARGET_KPSDK_CODE/hal/smc/fsl_smc_hal.h ================================================ /* * Copyright (c) 2013 - 2014, Freescale Semiconductor, Inc. * All rights reserved. * * Redistribution and use in source and binary forms, with or without modification, * are permitted provided that the following conditions are met: * * o Redistributions of source code must retain the above copyright notice, this list * of conditions and the following disclaimer. * * o Redistributions in binary form must reproduce the above copyright notice, this * list of conditions and the following disclaimer in the documentation and/or * other materials provided with the distribution. * * o Neither the name of Freescale Semiconductor, Inc. nor the names of its * contributors may be used to endorse or promote products derived from this * software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT 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. */ #if !defined(__FSL_SMC_HAL_H__) #define __FSL_SMC_HAL_H__ #include #include #include #include "fsl_device_registers.h" #include "fsl_smc_features.h" /*! @addtogroup smc_hal*/ /*! @{*/ /*! @file fsl_smc_hal.h */ /******************************************************************************* * Definitions ******************************************************************************/ /*! @brief Power Modes */ typedef enum _power_modes { kPowerModeRun, kPowerModeWait, kPowerModeStop, kPowerModeVlpr, kPowerModeVlpw, kPowerModeVlps, kPowerModeLls, kPowerModeVlls, kPowerModeHsrun, kPowerModeMax } power_modes_t; /*! * @brief Error code definition for the system mode controller manager APIs. */ typedef enum _smc_hal_error_code { kSmcHalSuccess, /*!< Success */ kSmcHalNoSuchModeName, /*!< Cannot find the mode name specified*/ kSmcHalAlreadyInTheState, /*!< Already in the required state*/ kSmcHalFailed /*!< Unknown error, operation failed*/ } smc_hal_error_code_t; /*! @brief Power Modes in PMSTAT*/ typedef enum _power_mode_stat { kStatRun = 0x01, /*!< 0000_0001 - Current power mode is RUN*/ kStatStop = 0x02, /*!< 0000_0010 - Current power mode is STOP*/ kStatVlpr = 0x04, /*!< 0000_0100 - Current power mode is VLPR*/ kStatVlpw = 0x08, /*!< 0000_1000 - Current power mode is VLPW*/ kStatVlps = 0x10, /*!< 0001_0000 - Current power mode is VLPS*/ kStatLls = 0x20, /*!< 0010_0000 - Current power mode is LLS*/ kStatVlls = 0x40, /*!< 0100_0000 - Current power mode is VLLS*/ kStatHsrun = 0x80 /*!< 1000_0000 - Current power mode is HSRUN*/ } power_mode_stat_t; /*! @brief Power Modes Protection*/ typedef enum _power_modes_protect { kAllowHsrun, /*!< Allow High Speed Run mode*/ kAllowVlp, /*!< Allow Very-Low-Power Modes*/ kAllowLls, /*!< Allow Low-Leakage Stop Mode*/ kAllowVlls, /*!< Allow Very-Low-Leakage Stop Mode*/ kAllowMax } power_modes_protect_t; /*! * @brief Run mode definition */ typedef enum _smc_run_mode { kSmcRun, /*!< normal RUN mode*/ kSmcReservedRun, kSmcVlpr, /*!< Very-Low-Power RUN mode*/ kSmcHsrun /*!< High Speed Run mode (HSRUN)*/ } smc_run_mode_t; /*! * @brief Stop mode definition */ typedef enum _smc_stop_mode { kSmcStop, /*!< Normal STOP mode*/ kSmcReservedStop1, /*!< Reserved*/ kSmcVlps, /*!< Very-Low-Power STOP mode*/ kSmcLls, /*!< Low-Leakage Stop mode*/ kSmcVlls /*!< Very-Low-Leakage Stop mode*/ } smc_stop_mode_t; /*! * @brief VLLS/LLS stop sub mode definition */ typedef enum _smc_stop_submode { kSmcStopSub0, kSmcStopSub1, kSmcStopSub2, kSmcStopSub3 } smc_stop_submode_t; /*! @brief Low Power Wake Up on Interrupt option*/ typedef enum _smc_lpwui_option { kSmcLpwuiEnabled, /*!< Low Power Wake Up on Interrupt enabled*/ kSmcLpwuiDisabled /*!< Low Power Wake Up on Interrupt disabled*/ } smc_lpwui_option_t; /*! @brief Partial STOP option*/ typedef enum _smc_pstop_option { kSmcPstopStop, /*!< STOP - Normal Stop mode*/ kSmcPstopStop1, /*!< Partial Stop with both system and bus clocks disabled*/ kSmcPstopStop2, /*!< Partial Stop with system clock disabled and bus clock enabled*/ kSmcPstopReserved, } smc_pstop_option_t; /*! @brief POR option*/ typedef enum _smc_por_option { kSmcPorEnabled, /*!< POR detect circuit is enabled in VLLS0*/ kSmcPorDisabled /*!< POR detect circuit is disabled in VLLS0*/ } smc_por_option_t; /*! @brief LPO power option*/ typedef enum _smc_lpo_option { kSmcLpoEnabled, /*!< LPO clock is enabled in LLS/VLLSx*/ kSmcLpoDisabled /*!< LPO clock is disabled in LLS/VLLSx*/ } smc_lpo_option_t; /*! @brief Power mode control options*/ typedef enum _smc_power_options { kSmcOptionLpwui, /*!< Low Power Wake Up on Interrupt*/ kSmcOptionPropo /*!< POR option*/ } smc_power_options_t; /*! @brief Power mode protection configuration*/ typedef struct _smc_power_mode_protection_config { bool vlpProt; /*!< VLP protect*/ bool llsProt; /*!< LLS protect */ bool vllsProt; /*!< VLLS protect*/ #if FSL_FEATURE_SMC_HAS_HIGH_SPEED_RUN_MODE bool hsrunProt; /*!< HSRUN protect */ #endif } smc_power_mode_protection_config_t; /*! @brief Power mode control configuration used for calling the SMC_SYS_SetPowerMode API. */ typedef struct _smc_power_mode_config { power_modes_t powerModeName; /*!< Power mode(enum), see power_modes_t */ smc_stop_submode_t stopSubMode; /*!< Stop submode(enum), see smc_stop_submode_t */ #if FSL_FEATURE_SMC_HAS_LPWUI bool lpwuiOption; /*!< If LPWUI option is needed */ smc_lpwui_option_t lpwuiOptionValue; /*!< LPWUI option(enum), see smc_lpwui_option_t */ #endif #if FSL_FEATURE_SMC_HAS_PORPO bool porOption; /*!< If POR option is needed */ smc_por_option_t porOptionValue; /*!< POR option(enum), see smc_por_option_t */ #endif #if FSL_FEATURE_SMC_HAS_PSTOPO bool pstopOption; /*!< If PSTOPO option is needed */ smc_pstop_option_t pstopOptionValue; /*!< PSTOPO option(enum), see smc_por_option_t */ #endif } smc_power_mode_config_t; /******************************************************************************* * API ******************************************************************************/ #if defined(__cplusplus) extern "C" { #endif /* __cplusplus*/ /*! @name System mode controller APIs*/ /*@{*/ /*! * @brief Configures the power mode. * * This function configures the power mode control for both run, stop, and * stop sub mode if needed. Also it configures the power options for a specific * power mode. An application should follow the proper procedure to configure and * switch power modes between different run and stop modes. For proper procedures * and supported power modes, see an appropriate chip reference * manual. See the smc_power_mode_config_t for required * parameters to configure the power mode and the supported options. Other options * may need to be individually configured through the HAL driver. See the HAL driver * header file for details. * * @param baseAddr Base address for current SMC instance. * @param powerModeConfig Power mode configuration structure smc_power_mode_config_t * @return errorCode SMC error code */ smc_hal_error_code_t SMC_HAL_SetMode(uint32_t baseAddr, const smc_power_mode_config_t *powerModeConfig); /*! * @brief Configures all power mode protection settings. * * This function configures the power mode protection settings for * supported power modes in the specified chip family. The available power modes * are defined in the smc_power_mode_protection_config_t. An application should provide * the protect settings for all supported power modes on the chip. This * should be done at an early system level initialization stage. See the reference manual * for details. This register can only write once after the power reset. If the user has * only a single option to set, * either use this function or use the individual set function. * * * @param baseAddr Base address for current SMC instance. * @param protectConfig Configurations for the supported power mode protect settings * - See smc_power_mode_protection_config_t for details. */ void SMC_HAL_SetProtection(uint32_t baseAddr, smc_power_mode_protection_config_t *protectConfig); /*! * @brief Configures the individual power mode protection settings. * * This function only configures the power mode protection settings for * a specified power mode on the specified chip family. The available power modes * are defined in the smc_power_mode_protection_config_t. See the reference manual * for details. This register can only write once after the power reset. * * @param baseAddr Base address for current SMC instance. * @param protect Power mode to set for protection * @param allow Allow or not allow the power mode protection */ void SMC_HAL_SetProtectionMode(uint32_t baseAddr, power_modes_protect_t protect, bool allow); /*! * @brief Gets the the current power mode protection setting. * * This function gets the current power mode protection settings for * a specified power mode. * * @param baseAddr Base address for current SMC instance. * @param protect Power mode to set for protection * @return state Status of the protection setting * - true: Allowed * - false: Not allowed */ bool SMC_HAL_GetProtectionMode(uint32_t baseAddr, power_modes_protect_t protect); /*! * @brief Configures the the RUN mode control setting. * * This function sets the run mode settings, for example, normal run mode, * very lower power run mode, etc. See the smc_run_mode_t for supported run * mode on the chip family and the reference manual for details about the * run mode. * * @param baseAddr Base address for current SMC instance. * @param runMode Run mode setting defined in smc_run_mode_t */ void SMC_HAL_SetRunMode(uint32_t baseAddr, smc_run_mode_t runMode); /*! * @brief Gets the current RUN mode configuration setting. * * This function gets the run mode settings. See the smc_run_mode_t * for a supported run mode on the chip family and the reference manual for * details about the run mode. * * @param baseAddr Base address for current SMC instance. * @return setting Run mode configuration setting */ smc_run_mode_t SMC_HAL_GetRunMode(uint32_t baseAddr); /*! * @brief Configures the STOP mode control setting. * * This function sets the stop mode settings, for example, normal stop mode, * very lower power stop mode, etc. See the smc_stop_mode_t for supported stop * mode on the chip family and the reference manual for details about the * stop mode. * * @param baseAddr Base address for current SMC instance. * @param stopMode Stop mode defined in smc_stop_mode_t */ void SMC_HAL_SetStopMode(uint32_t baseAddr, smc_stop_mode_t stopMode); /*! * @brief Gets the current STOP mode control settings. * * This function gets the stop mode settings, for example, normal stop mode, * very lower power stop mode, etc. See the smc_stop_mode_t for supported stop * mode on the chip family and the reference manual for details about the * stop mode. * * @param baseAddr Base address for current SMC instance. * @return setting Current stop mode configuration setting */ smc_stop_mode_t SMC_HAL_GetStopMode(uint32_t baseAddr); /*! * @brief Configures the stop sub mode control setting. * * This function sets the stop submode settings. Some of the stop mode * further supports submodes. See the smc_stop_submode_t for supported * stop submodes and the reference manual for details about the submodes * for a specific stop mode. * * @param baseAddr Base address for current SMC instance. * @param stopSubMode Stop submode setting defined in smc_stop_submode_t */ void SMC_HAL_SetStopSubMode(uint32_t baseAddr, smc_stop_submode_t stopSubMode); /*! * @brief Gets the current stop submode configuration settings. * * This function gets the stop submode settings. Some of the stop mode * further support submodes. See the smc_stop_submode_t for supported * stop submodes and the reference manual for details about the submode * for a specific stop mode. * * @param baseAddr Base address for current SMC instance. * @return setting Current stop submode setting */ smc_stop_submode_t SMC_HAL_GetStopSubMode(uint32_t baseAddr); #if FSL_FEATURE_SMC_HAS_PORPO /*! * @brief Configures the POR (power-on-reset) option. * * This function sets the POR power option setting. It controls whether the * POR detect circuit (for brown-out detection) is enabled in a certain stop mode. * The setting either enables or disables the above feature when the POR * occurs. See the reference manual for details. * * @param baseAddr Base address for current SMC instance. * @param option POR option setting refer to smc_por_option_t */ void SMC_HAL_SetPorMode(uint32_t baseAddr, smc_por_option_t option); /*! * @brief Gets the configuration settings for the POR option. * * This function sets the POR power option setting. See the configuration function * header for details. * * @param baseAddr Base address for current SMC instance. * @return option Current POR option setting */ smc_por_option_t SMC_HAL_GetPorMode(uint32_t baseAddr); #endif #if FSL_FEATURE_SMC_HAS_PSTOPO /*! * @brief Configures the PSTOPO (Partial Stop Option). * * This function sets the PSTOPO option. It controls whether a Partial * Stop mode is entered when the STOPM=STOP. When entering a Partial Stop mode from the * RUN mode, the PMC, MCG and Flash remain fully powered allowing the device * to wakeup almost instantaneously at the expense of a higher power consumption. * In PSTOP2, only the system clocks are gated, which allows the peripherals running on bus * clock to remain fully functional. In PSTOP1, both system and bus clocks are * gated. Refer to the smc_pstop_option_t for supported options. See the reference * manual for details. * * @param baseAddr Base address for current SMC instance. * @param option PSTOPO option setting defined in smc_pstop_option_t */ void SMC_HAL_SetPstopMode(uint32_t baseAddr, smc_pstop_option_t option); /*! * @brief Gets the configuration of the PSTOPO option. * * This function gets the current PSTOPO option setting. See the configuration * function for more details. * * @param baseAddr Base address for current SMC instance. * @return option Current PSTOPO option setting */ smc_pstop_option_t SMC_HAL_GetPstopMode(uint32_t baseAddr); #endif #if FSL_FEATURE_SMC_HAS_LPOPO /*! * @brief Configures the LPO option setting. * * This function sets the LPO option setting. It controls whether the 1 kHZ * LPO clock is enabled in a certain lower power stop modes. See the * smc_lpo_option_t for supported options and the reference manual for * details about this option. * * @param baseAddr Base address for current SMC instance. * @param option LPO option setting defined in smc_lpo_option_t */ void SMC_HAL_SetLpoMode(uint32_t baseAddr, smc_lpo_option_t option); /*! * @brief Gets the settings of the LPO option. * * This function gets the current LPO option setting. See the configuration * function for details. * * @param baseAddr Base address for current SMC instance. * @return option Current LPO option setting */ smc_por_option_t SMC_HAL_GetLpoMode(uint32_t baseAddr); #endif #if FSL_FEATURE_SMC_HAS_LPWUI /*! * @brief Configures the LPWUI (Low Power Wake Up on interrupt) option. * * This function sets the LPWUI option and cause the system to exit * to normal RUN mode when any active interrupt occurs while in a specific lower * power mode. See the smc_lpwui_option_t for supported options and the * reference manual for more details about this option. * * @param baseAddr Base address for current SMC instance. * @param option LPWUI option setting defined in smc_lpwui_option_t */ void SMC_HAL_SetLpwuiMode(uint32_t baseAddr, smc_lpwui_option_t option); /*! * @brief Gets the current LPWUI option. * * This function gets the LPWUI option. See the configuration function for more * details. * * @param baseAddr Base address for current SMC instance. * @return setting Current LPWAUI option setting */ smc_lpwui_option_t SMC_HAL_GetLpwuiMode(uint32_t baseAddr); #endif /*! * @brief Gets the current power mode stat. * * This function returns the current power mode stat. Once application * switches the power mode, it should always check the stat to check whether it * runs into the specified mode or not. An application should check * this mode before switching to a different mode. The system requires that * only certain modes can switch to other specific modes. See the * reference manual for details and the _power_mode_stat for information about * the power stat. * * @param baseAddr Base address for current SMC instance. * @return stat Current power mode stat */ uint8_t SMC_HAL_GetStat(uint32_t baseAddr); /*@}*/ #if defined(__cplusplus) } #endif /* __cplusplus*/ /*! @}*/ #endif /* __FSL_SMC_HAL_H__*/ /******************************************************************************* * EOF ******************************************************************************/ ================================================ FILE: Zelig/mbed/TARGET_K64F/TARGET_Freescale/TARGET_KPSDK_MCUS/TARGET_KPSDK_CODE/hal/uart/fsl_uart_features.h ================================================ /* ** ################################################################### ** Version: rev. 1.0, 2014-05-14 ** Build: b140515 ** ** Abstract: ** Chip specific module features. ** ** Copyright: 2014 Freescale Semiconductor, Inc. ** All rights reserved. ** ** Redistribution and use in source and binary forms, with or without modification, ** are permitted provided that the following conditions are met: ** ** o Redistributions of source code must retain the above copyright notice, this list ** of conditions and the following disclaimer. ** ** o Redistributions in binary form must reproduce the above copyright notice, this ** list of conditions and the following disclaimer in the documentation and/or ** other materials provided with the distribution. ** ** o Neither the name of Freescale Semiconductor, Inc. nor the names of its ** contributors may be used to endorse or promote products derived from this ** software without specific prior written permission. ** ** THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ** ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED ** WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE ** DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT 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. ** ** http: www.freescale.com ** mail: support@freescale.com ** ** Revisions: ** - rev. 1.0 (2014-05-14) ** Customer release. ** ** ################################################################### */ #if !defined(__FSL_UART_FEATURES_H__) #define __FSL_UART_FEATURES_H__ #if defined(CPU_MK02FN128VFM10) || defined(CPU_MK02FN64VFM10) || defined(CPU_MK02FN128VLF10) || defined(CPU_MK02FN64VLF10) || \ defined(CPU_MK02FN128VLH10) || defined(CPU_MK02FN64VLH10) || defined(CPU_MKV30F128VFM10) || defined(CPU_MKV30F64VFM10) || \ defined(CPU_MKV30F128VLF10) || defined(CPU_MKV30F64VLF10) || defined(CPU_MKV30F128VLH10) || defined(CPU_MKV30F64VLH10) /* @brief Has receive FIFO overflow detection (bit field CFIFO[RXOFE]). */ #define FSL_FEATURE_UART_HAS_IRQ_EXTENDED_FUNCTIONS (1) /* @brief Has low power features (can be enabled in wait mode via register bit C1[DOZEEN] or CTRL[DOZEEN] if the registers are 32-bit wide). */ #define FSL_FEATURE_UART_HAS_LOW_POWER_UART_SUPPORT (0) #define FSL_FEATURE_UART_HAS_LOW_POWER_UART_SUPPORTn(x) \ ((x) == 0 ? (0) : \ ((x) == 1 ? (0) : (-1))) /* @brief Has extended data register ED (or extra flags in the DATA register if the registers are 32-bit wide). */ #define FSL_FEATURE_UART_HAS_EXTENDED_DATA_REGISTER_FLAGS (1) /* @brief Capacity (number of entries) of the transmit/receive FIFO (or zero if no FIFO is available). */ #define FSL_FEATURE_UART_HAS_FIFO (1) /* @brief Hardware flow control (RTS, CTS) is supported. */ #define FSL_FEATURE_UART_HAS_MODEM_SUPPORT (1) /* @brief Infrared (modulation) is supported. */ #define FSL_FEATURE_UART_HAS_IR_SUPPORT (1) /* @brief 2 bits long stop bit is available. */ #define FSL_FEATURE_UART_HAS_STOP_BIT_CONFIG_SUPPORT (0) /* @brief Maximal data width without parity bit. */ #define FSL_FEATURE_UART_HAS_10BIT_DATA_SUPPORT (0) #define FSL_FEATURE_UART_HAS_10BIT_DATA_SUPPORTn(x) \ ((x) == 0 ? (0) : \ ((x) == 1 ? (0) : (-1))) /* @brief Baud rate fine adjustment is available. */ #define FSL_FEATURE_UART_HAS_BAUD_RATE_FINE_ADJUST_SUPPORT (1) /* @brief Baud rate oversampling is available (has bit fields C4[OSR], C5[BOTHEDGE], C5[RESYNCDIS] or BAUD[OSR], BAUD[BOTHEDGE], BAUD[RESYNCDIS] if the registers are 32-bit wide). */ #define FSL_FEATURE_UART_HAS_BAUD_RATE_OVER_SAMPLING_SUPPORT (0) #define FSL_FEATURE_UART_HAS_BAUD_RATE_OVER_SAMPLING_SUPPORTn(x) \ ((x) == 0 ? (0) : \ ((x) == 1 ? (0) : (-1))) /* @brief Baud rate oversampling is available. */ #define FSL_FEATURE_UART_HAS_RX_RESYNC_SUPPORT (0) /* @brief Baud rate oversampling is available. */ #define FSL_FEATURE_UART_HAS_BOTH_EDGE_SAMPLING_SUPPORT (0) /* @brief Peripheral type. */ #define FSL_FEATURE_UART_IS_SCI (0) /* @brief Capacity (number of entries) of the transmit/receive FIFO (or zero if no FIFO is available). */ #define FSL_FEATURE_UART_FIFO_SIZE (8) #define FSL_FEATURE_UART_FIFO_SIZEn(x) \ ((x) == 0 ? (8) : \ ((x) == 1 ? (1) : (-1))) /* @brief Maximal data width without parity bit. */ #define FSL_FEATURE_UART_MAX_DATA_WIDTH_WITH_NO_PARITY (9) #define FSL_FEATURE_UART_MAX_DATA_WIDTH_WITH_NO_PARITYn(x) \ ((x) == 0 ? (9) : \ ((x) == 1 ? (9) : (-1))) /* @brief Maximal data width with parity bit. */ #define FSL_FEATURE_UART_MAX_DATA_WIDTH_WITH_PARITY (10) #define FSL_FEATURE_UART_MAX_DATA_WIDTH_WITH_PARITYn(x) \ ((x) == 0 ? (10) : \ ((x) == 1 ? (10) : (-1))) /* @brief Supports two match addresses to filter incoming frames. */ #define FSL_FEATURE_UART_HAS_ADDRESS_MATCHING (1) #define FSL_FEATURE_UART_HAS_ADDRESS_MATCHINGn(x) \ ((x) == 0 ? (1) : \ ((x) == 1 ? (1) : (-1))) /* @brief Has transmitter/receiver DMA enable bits C5[TDMAE]/C5[RDMAE] (or BAUD[TDMAE]/BAUD[RDMAE] if the registers are 32-bit wide). */ #define FSL_FEATURE_UART_HAS_DMA_ENABLE (0) #define FSL_FEATURE_UART_HAS_DMA_ENABLEn(x) \ ((x) == 0 ? (0) : \ ((x) == 1 ? (0) : (-1))) /* @brief Has transmitter/receiver DMA select bits C4[TDMAS]/C4[RDMAS], resp. C5[TDMAS]/C5[RDMAS] if IS_SCI = 0. */ #define FSL_FEATURE_UART_HAS_DMA_SELECT (1) #define FSL_FEATURE_UART_HAS_DMA_SELECTn(x) \ ((x) == 0 ? (1) : \ ((x) == 1 ? (1) : (-1))) /* @brief Data character bit order selection is supported (bit field S2[MSBF] or STAT[MSBF] if the registers are 32-bit wide). */ #define FSL_FEATURE_UART_HAS_BIT_ORDER_SELECT (1) #define FSL_FEATURE_UART_HAS_BIT_ORDER_SELECTn(x) \ ((x) == 0 ? (1) : \ ((x) == 1 ? (1) : (-1))) /* @brief Has smart card (ISO7816 protocol) support and no improved smart card support. */ #define FSL_FEATURE_UART_HAS_SMART_CARD_SUPPORT (0) #define FSL_FEATURE_UART_HAS_SMART_CARD_SUPPORTn(x) \ ((x) == 0 ? (0) : \ ((x) == 1 ? (0) : (-1))) /* @brief Has improved smart card (ISO7816 protocol) support. */ #define FSL_FEATURE_UART_HAS_IMPROVED_SMART_CARD_SUPPORT (0) #define FSL_FEATURE_UART_HAS_IMPROVED_SMART_CARD_SUPPORTn(x) \ ((x) == 0 ? (0) : \ ((x) == 1 ? (0) : (-1))) /* @brief Has local operation network (CEA709.1-B protocol) support. */ #define FSL_FEATURE_UART_HAS_LOCAL_OPERATION_NETWORK_SUPPORT (0) #define FSL_FEATURE_UART_HAS_LOCAL_OPERATION_NETWORK_SUPPORTn(x) \ ((x) == 0 ? (0) : \ ((x) == 1 ? (0) : (-1))) /* @brief Has 32-bit registers (BAUD, STAT, CTRL, DATA, MATCH, MODIR) instead of 8-bit (BDH, BDL, C1, S1, D, etc.). */ #define FSL_FEATURE_UART_HAS_32BIT_REGISTERS (0) #elif defined(CPU_MK20DX128VMP5) || defined(CPU_MK20DN128VMP5) || defined(CPU_MK20DX64VMP5) || defined(CPU_MK20DN64VMP5) || \ defined(CPU_MK20DX32VMP5) || defined(CPU_MK20DN32VMP5) || defined(CPU_MK20DX128VLH5) || defined(CPU_MK20DN128VLH5) || \ defined(CPU_MK20DX64VLH5) || defined(CPU_MK20DN64VLH5) || defined(CPU_MK20DX32VLH5) || defined(CPU_MK20DN32VLH5) || \ defined(CPU_MK20DX128VFT5) || defined(CPU_MK20DN128VFT5) || defined(CPU_MK20DX64VFT5) || defined(CPU_MK20DN64VFT5) || \ defined(CPU_MK20DX32VFT5) || defined(CPU_MK20DN32VFT5) || defined(CPU_MK20DX128VLF5) || defined(CPU_MK20DN128VLF5) || \ defined(CPU_MK20DX64VLF5) || defined(CPU_MK20DN64VLF5) || defined(CPU_MK20DX32VLF5) || defined(CPU_MK20DN32VLF5) /* @brief Has receive FIFO overflow detection (bit field CFIFO[RXOFE]). */ #define FSL_FEATURE_UART_HAS_IRQ_EXTENDED_FUNCTIONS (0) /* @brief Has low power features (can be enabled in wait mode via register bit C1[DOZEEN] or CTRL[DOZEEN] if the registers are 32-bit wide). */ #define FSL_FEATURE_UART_HAS_LOW_POWER_UART_SUPPORT (0) #define FSL_FEATURE_UART_HAS_LOW_POWER_UART_SUPPORTn(x) \ ((x) == 0 ? (0) : \ ((x) == 1 ? (0) : \ ((x) == 2 ? (0) : (-1)))) /* @brief Has extended data register ED (or extra flags in the DATA register if the registers are 32-bit wide). */ #define FSL_FEATURE_UART_HAS_EXTENDED_DATA_REGISTER_FLAGS (1) /* @brief Capacity (number of entries) of the transmit/receive FIFO (or zero if no FIFO is available). */ #define FSL_FEATURE_UART_HAS_FIFO (1) /* @brief Hardware flow control (RTS, CTS) is supported. */ #define FSL_FEATURE_UART_HAS_MODEM_SUPPORT (1) /* @brief Infrared (modulation) is supported. */ #define FSL_FEATURE_UART_HAS_IR_SUPPORT (1) /* @brief 2 bits long stop bit is available. */ #define FSL_FEATURE_UART_HAS_STOP_BIT_CONFIG_SUPPORT (0) /* @brief Maximal data width without parity bit. */ #define FSL_FEATURE_UART_HAS_10BIT_DATA_SUPPORT (0) #define FSL_FEATURE_UART_HAS_10BIT_DATA_SUPPORTn(x) \ ((x) == 0 ? (0) : \ ((x) == 1 ? (0) : \ ((x) == 2 ? (0) : (-1)))) /* @brief Baud rate fine adjustment is available. */ #define FSL_FEATURE_UART_HAS_BAUD_RATE_FINE_ADJUST_SUPPORT (1) /* @brief Baud rate oversampling is available (has bit fields C4[OSR], C5[BOTHEDGE], C5[RESYNCDIS] or BAUD[OSR], BAUD[BOTHEDGE], BAUD[RESYNCDIS] if the registers are 32-bit wide). */ #define FSL_FEATURE_UART_HAS_BAUD_RATE_OVER_SAMPLING_SUPPORT (0) #define FSL_FEATURE_UART_HAS_BAUD_RATE_OVER_SAMPLING_SUPPORTn(x) \ ((x) == 0 ? (0) : \ ((x) == 1 ? (0) : \ ((x) == 2 ? (0) : (-1)))) /* @brief Baud rate oversampling is available. */ #define FSL_FEATURE_UART_HAS_RX_RESYNC_SUPPORT (0) /* @brief Baud rate oversampling is available. */ #define FSL_FEATURE_UART_HAS_BOTH_EDGE_SAMPLING_SUPPORT (0) /* @brief Peripheral type. */ #define FSL_FEATURE_UART_IS_SCI (0) /* @brief Capacity (number of entries) of the transmit/receive FIFO (or zero if no FIFO is available). */ #define FSL_FEATURE_UART_FIFO_SIZE (8) #define FSL_FEATURE_UART_FIFO_SIZEn(x) \ ((x) == 0 ? (8) : \ ((x) == 1 ? (1) : \ ((x) == 2 ? (1) : (-1)))) /* @brief Maximal data width without parity bit. */ #define FSL_FEATURE_UART_MAX_DATA_WIDTH_WITH_NO_PARITY (9) #define FSL_FEATURE_UART_MAX_DATA_WIDTH_WITH_NO_PARITYn(x) \ ((x) == 0 ? (9) : \ ((x) == 1 ? (9) : \ ((x) == 2 ? (9) : (-1)))) /* @brief Maximal data width with parity bit. */ #define FSL_FEATURE_UART_MAX_DATA_WIDTH_WITH_PARITY (10) #define FSL_FEATURE_UART_MAX_DATA_WIDTH_WITH_PARITYn(x) \ ((x) == 0 ? (10) : \ ((x) == 1 ? (10) : \ ((x) == 2 ? (10) : (-1)))) /* @brief Supports two match addresses to filter incoming frames. */ #define FSL_FEATURE_UART_HAS_ADDRESS_MATCHING (1) #define FSL_FEATURE_UART_HAS_ADDRESS_MATCHINGn(x) \ ((x) == 0 ? (1) : \ ((x) == 1 ? (1) : \ ((x) == 2 ? (1) : (-1)))) /* @brief Has transmitter/receiver DMA enable bits C5[TDMAE]/C5[RDMAE] (or BAUD[TDMAE]/BAUD[RDMAE] if the registers are 32-bit wide). */ #define FSL_FEATURE_UART_HAS_DMA_ENABLE (0) #define FSL_FEATURE_UART_HAS_DMA_ENABLEn(x) \ ((x) == 0 ? (0) : \ ((x) == 1 ? (0) : \ ((x) == 2 ? (0) : (-1)))) /* @brief Has transmitter/receiver DMA select bits C4[TDMAS]/C4[RDMAS], resp. C5[TDMAS]/C5[RDMAS] if IS_SCI = 0. */ #define FSL_FEATURE_UART_HAS_DMA_SELECT (1) #define FSL_FEATURE_UART_HAS_DMA_SELECTn(x) \ ((x) == 0 ? (1) : \ ((x) == 1 ? (1) : \ ((x) == 2 ? (1) : (-1)))) /* @brief Data character bit order selection is supported (bit field S2[MSBF] or STAT[MSBF] if the registers are 32-bit wide). */ #define FSL_FEATURE_UART_HAS_BIT_ORDER_SELECT (1) #define FSL_FEATURE_UART_HAS_BIT_ORDER_SELECTn(x) \ ((x) == 0 ? (1) : \ ((x) == 1 ? (1) : \ ((x) == 2 ? (1) : (-1)))) /* @brief Has smart card (ISO7816 protocol) support and no improved smart card support. */ #define FSL_FEATURE_UART_HAS_SMART_CARD_SUPPORT (1) #define FSL_FEATURE_UART_HAS_SMART_CARD_SUPPORTn(x) \ ((x) == 0 ? (1) : \ ((x) == 1 ? (0) : \ ((x) == 2 ? (0) : (-1)))) /* @brief Has improved smart card (ISO7816 protocol) support. */ #define FSL_FEATURE_UART_HAS_IMPROVED_SMART_CARD_SUPPORT (0) #define FSL_FEATURE_UART_HAS_IMPROVED_SMART_CARD_SUPPORTn(x) \ ((x) == 0 ? (0) : \ ((x) == 1 ? (0) : \ ((x) == 2 ? (0) : (-1)))) /* @brief Has local operation network (CEA709.1-B protocol) support. */ #define FSL_FEATURE_UART_HAS_LOCAL_OPERATION_NETWORK_SUPPORT (1) #define FSL_FEATURE_UART_HAS_LOCAL_OPERATION_NETWORK_SUPPORTn(x) \ ((x) == 0 ? (1) : \ ((x) == 1 ? (0) : \ ((x) == 2 ? (0) : (-1)))) /* @brief Has 32-bit registers (BAUD, STAT, CTRL, DATA, MATCH, MODIR) instead of 8-bit (BDH, BDL, C1, S1, D, etc.). */ #define FSL_FEATURE_UART_HAS_32BIT_REGISTERS (0) #elif defined(CPU_MK20DX128VFM5) || defined(CPU_MK20DN128VFM5) || defined(CPU_MK20DX64VFM5) || defined(CPU_MK20DN64VFM5) || \ defined(CPU_MK20DX32VFM5) || defined(CPU_MK20DN32VFM5) /* @brief Has receive FIFO overflow detection (bit field CFIFO[RXOFE]). */ #define FSL_FEATURE_UART_HAS_IRQ_EXTENDED_FUNCTIONS (0) /* @brief Has low power features (can be enabled in wait mode via register bit C1[DOZEEN] or CTRL[DOZEEN] if the registers are 32-bit wide). */ #define FSL_FEATURE_UART_HAS_LOW_POWER_UART_SUPPORT (0) #define FSL_FEATURE_UART_HAS_LOW_POWER_UART_SUPPORTn(x) \ ((x) == 0 ? (0) : \ ((x) == 1 ? (0) : (-1))) /* @brief Has extended data register ED (or extra flags in the DATA register if the registers are 32-bit wide). */ #define FSL_FEATURE_UART_HAS_EXTENDED_DATA_REGISTER_FLAGS (1) /* @brief Capacity (number of entries) of the transmit/receive FIFO (or zero if no FIFO is available). */ #define FSL_FEATURE_UART_HAS_FIFO (1) /* @brief Hardware flow control (RTS, CTS) is supported. */ #define FSL_FEATURE_UART_HAS_MODEM_SUPPORT (1) /* @brief Infrared (modulation) is supported. */ #define FSL_FEATURE_UART_HAS_IR_SUPPORT (1) /* @brief 2 bits long stop bit is available. */ #define FSL_FEATURE_UART_HAS_STOP_BIT_CONFIG_SUPPORT (0) /* @brief Maximal data width without parity bit. */ #define FSL_FEATURE_UART_HAS_10BIT_DATA_SUPPORT (0) #define FSL_FEATURE_UART_HAS_10BIT_DATA_SUPPORTn(x) \ ((x) == 0 ? (0) : \ ((x) == 1 ? (0) : (-1))) /* @brief Baud rate fine adjustment is available. */ #define FSL_FEATURE_UART_HAS_BAUD_RATE_FINE_ADJUST_SUPPORT (1) /* @brief Baud rate oversampling is available (has bit fields C4[OSR], C5[BOTHEDGE], C5[RESYNCDIS] or BAUD[OSR], BAUD[BOTHEDGE], BAUD[RESYNCDIS] if the registers are 32-bit wide). */ #define FSL_FEATURE_UART_HAS_BAUD_RATE_OVER_SAMPLING_SUPPORT (0) #define FSL_FEATURE_UART_HAS_BAUD_RATE_OVER_SAMPLING_SUPPORTn(x) \ ((x) == 0 ? (0) : \ ((x) == 1 ? (0) : (-1))) /* @brief Baud rate oversampling is available. */ #define FSL_FEATURE_UART_HAS_RX_RESYNC_SUPPORT (0) /* @brief Baud rate oversampling is available. */ #define FSL_FEATURE_UART_HAS_BOTH_EDGE_SAMPLING_SUPPORT (0) /* @brief Peripheral type. */ #define FSL_FEATURE_UART_IS_SCI (0) /* @brief Capacity (number of entries) of the transmit/receive FIFO (or zero if no FIFO is available). */ #define FSL_FEATURE_UART_FIFO_SIZE (8) #define FSL_FEATURE_UART_FIFO_SIZEn(x) \ ((x) == 0 ? (8) : \ ((x) == 1 ? (1) : (-1))) /* @brief Maximal data width without parity bit. */ #define FSL_FEATURE_UART_MAX_DATA_WIDTH_WITH_NO_PARITY (9) #define FSL_FEATURE_UART_MAX_DATA_WIDTH_WITH_NO_PARITYn(x) \ ((x) == 0 ? (9) : \ ((x) == 1 ? (9) : (-1))) /* @brief Maximal data width with parity bit. */ #define FSL_FEATURE_UART_MAX_DATA_WIDTH_WITH_PARITY (10) #define FSL_FEATURE_UART_MAX_DATA_WIDTH_WITH_PARITYn(x) \ ((x) == 0 ? (10) : \ ((x) == 1 ? (10) : (-1))) /* @brief Supports two match addresses to filter incoming frames. */ #define FSL_FEATURE_UART_HAS_ADDRESS_MATCHING (1) #define FSL_FEATURE_UART_HAS_ADDRESS_MATCHINGn(x) \ ((x) == 0 ? (1) : \ ((x) == 1 ? (1) : (-1))) /* @brief Has transmitter/receiver DMA enable bits C5[TDMAE]/C5[RDMAE] (or BAUD[TDMAE]/BAUD[RDMAE] if the registers are 32-bit wide). */ #define FSL_FEATURE_UART_HAS_DMA_ENABLE (0) #define FSL_FEATURE_UART_HAS_DMA_ENABLEn(x) \ ((x) == 0 ? (0) : \ ((x) == 1 ? (0) : (-1))) /* @brief Has transmitter/receiver DMA select bits C4[TDMAS]/C4[RDMAS], resp. C5[TDMAS]/C5[RDMAS] if IS_SCI = 0. */ #define FSL_FEATURE_UART_HAS_DMA_SELECT (1) #define FSL_FEATURE_UART_HAS_DMA_SELECTn(x) \ ((x) == 0 ? (1) : \ ((x) == 1 ? (1) : (-1))) /* @brief Data character bit order selection is supported (bit field S2[MSBF] or STAT[MSBF] if the registers are 32-bit wide). */ #define FSL_FEATURE_UART_HAS_BIT_ORDER_SELECT (1) #define FSL_FEATURE_UART_HAS_BIT_ORDER_SELECTn(x) \ ((x) == 0 ? (1) : \ ((x) == 1 ? (1) : (-1))) /* @brief Has smart card (ISO7816 protocol) support and no improved smart card support. */ #define FSL_FEATURE_UART_HAS_SMART_CARD_SUPPORT (1) #define FSL_FEATURE_UART_HAS_SMART_CARD_SUPPORTn(x) \ ((x) == 0 ? (1) : \ ((x) == 1 ? (0) : (-1))) /* @brief Has improved smart card (ISO7816 protocol) support. */ #define FSL_FEATURE_UART_HAS_IMPROVED_SMART_CARD_SUPPORT (0) #define FSL_FEATURE_UART_HAS_IMPROVED_SMART_CARD_SUPPORTn(x) \ ((x) == 0 ? (0) : \ ((x) == 1 ? (0) : (-1))) /* @brief Has local operation network (CEA709.1-B protocol) support. */ #define FSL_FEATURE_UART_HAS_LOCAL_OPERATION_NETWORK_SUPPORT (1) #define FSL_FEATURE_UART_HAS_LOCAL_OPERATION_NETWORK_SUPPORTn(x) \ ((x) == 0 ? (1) : \ ((x) == 1 ? (0) : (-1))) /* @brief Has 32-bit registers (BAUD, STAT, CTRL, DATA, MATCH, MODIR) instead of 8-bit (BDH, BDL, C1, S1, D, etc.). */ #define FSL_FEATURE_UART_HAS_32BIT_REGISTERS (0) #elif defined(CPU_MK22FN128VDC10) || defined(CPU_MK22FN128VLH10) || defined(CPU_MK22FN128VLL10) || defined(CPU_MK22FN128VMP10) || \ defined(CPU_MK22FN256VDC12) || defined(CPU_MK22FN256VLH12) || defined(CPU_MK22FN256VLL12) || defined(CPU_MK22FN256VMP12) || \ defined(CPU_MK22FN512VDC12) || defined(CPU_MK22FN512VLH12) || defined(CPU_MK22FN512VLL12) || defined(CPU_MKV31F128VLH10) || \ defined(CPU_MKV31F128VLL10) || defined(CPU_MKV31F256VLH12) || defined(CPU_MKV31F256VLL12) || defined(CPU_MKV31F512VLH12) || \ defined(CPU_MKV31F512VLL12) /* @brief Has receive FIFO overflow detection (bit field CFIFO[RXOFE]). */ #define FSL_FEATURE_UART_HAS_IRQ_EXTENDED_FUNCTIONS (1) /* @brief Has low power features (can be enabled in wait mode via register bit C1[DOZEEN] or CTRL[DOZEEN] if the registers are 32-bit wide). */ #define FSL_FEATURE_UART_HAS_LOW_POWER_UART_SUPPORT (0) #define FSL_FEATURE_UART_HAS_LOW_POWER_UART_SUPPORTn(x) \ ((x) == 0 ? (0) : \ ((x) == 1 ? (0) : \ ((x) == 2 ? (0) : (-1)))) /* @brief Has extended data register ED (or extra flags in the DATA register if the registers are 32-bit wide). */ #define FSL_FEATURE_UART_HAS_EXTENDED_DATA_REGISTER_FLAGS (1) /* @brief Capacity (number of entries) of the transmit/receive FIFO (or zero if no FIFO is available). */ #define FSL_FEATURE_UART_HAS_FIFO (1) /* @brief Hardware flow control (RTS, CTS) is supported. */ #define FSL_FEATURE_UART_HAS_MODEM_SUPPORT (1) /* @brief Infrared (modulation) is supported. */ #define FSL_FEATURE_UART_HAS_IR_SUPPORT (1) /* @brief 2 bits long stop bit is available. */ #define FSL_FEATURE_UART_HAS_STOP_BIT_CONFIG_SUPPORT (0) /* @brief Maximal data width without parity bit. */ #define FSL_FEATURE_UART_HAS_10BIT_DATA_SUPPORT (0) #define FSL_FEATURE_UART_HAS_10BIT_DATA_SUPPORTn(x) \ ((x) == 0 ? (0) : \ ((x) == 1 ? (0) : \ ((x) == 2 ? (0) : (-1)))) /* @brief Baud rate fine adjustment is available. */ #define FSL_FEATURE_UART_HAS_BAUD_RATE_FINE_ADJUST_SUPPORT (1) /* @brief Baud rate oversampling is available (has bit fields C4[OSR], C5[BOTHEDGE], C5[RESYNCDIS] or BAUD[OSR], BAUD[BOTHEDGE], BAUD[RESYNCDIS] if the registers are 32-bit wide). */ #define FSL_FEATURE_UART_HAS_BAUD_RATE_OVER_SAMPLING_SUPPORT (0) #define FSL_FEATURE_UART_HAS_BAUD_RATE_OVER_SAMPLING_SUPPORTn(x) \ ((x) == 0 ? (0) : \ ((x) == 1 ? (0) : \ ((x) == 2 ? (0) : (-1)))) /* @brief Baud rate oversampling is available. */ #define FSL_FEATURE_UART_HAS_RX_RESYNC_SUPPORT (0) /* @brief Baud rate oversampling is available. */ #define FSL_FEATURE_UART_HAS_BOTH_EDGE_SAMPLING_SUPPORT (0) /* @brief Peripheral type. */ #define FSL_FEATURE_UART_IS_SCI (0) /* @brief Capacity (number of entries) of the transmit/receive FIFO (or zero if no FIFO is available). */ #define FSL_FEATURE_UART_FIFO_SIZE (8) #define FSL_FEATURE_UART_FIFO_SIZEn(x) \ ((x) == 0 ? (8) : \ ((x) == 1 ? (1) : \ ((x) == 2 ? (1) : (-1)))) /* @brief Maximal data width without parity bit. */ #define FSL_FEATURE_UART_MAX_DATA_WIDTH_WITH_NO_PARITY (9) #define FSL_FEATURE_UART_MAX_DATA_WIDTH_WITH_NO_PARITYn(x) \ ((x) == 0 ? (9) : \ ((x) == 1 ? (9) : \ ((x) == 2 ? (9) : (-1)))) /* @brief Maximal data width with parity bit. */ #define FSL_FEATURE_UART_MAX_DATA_WIDTH_WITH_PARITY (10) #define FSL_FEATURE_UART_MAX_DATA_WIDTH_WITH_PARITYn(x) \ ((x) == 0 ? (10) : \ ((x) == 1 ? (10) : \ ((x) == 2 ? (10) : (-1)))) /* @brief Supports two match addresses to filter incoming frames. */ #define FSL_FEATURE_UART_HAS_ADDRESS_MATCHING (1) #define FSL_FEATURE_UART_HAS_ADDRESS_MATCHINGn(x) \ ((x) == 0 ? (1) : \ ((x) == 1 ? (1) : \ ((x) == 2 ? (1) : (-1)))) /* @brief Has transmitter/receiver DMA enable bits C5[TDMAE]/C5[RDMAE] (or BAUD[TDMAE]/BAUD[RDMAE] if the registers are 32-bit wide). */ #define FSL_FEATURE_UART_HAS_DMA_ENABLE (0) #define FSL_FEATURE_UART_HAS_DMA_ENABLEn(x) \ ((x) == 0 ? (0) : \ ((x) == 1 ? (0) : \ ((x) == 2 ? (0) : (-1)))) /* @brief Has transmitter/receiver DMA select bits C4[TDMAS]/C4[RDMAS], resp. C5[TDMAS]/C5[RDMAS] if IS_SCI = 0. */ #define FSL_FEATURE_UART_HAS_DMA_SELECT (1) #define FSL_FEATURE_UART_HAS_DMA_SELECTn(x) \ ((x) == 0 ? (1) : \ ((x) == 1 ? (1) : \ ((x) == 2 ? (1) : (-1)))) /* @brief Data character bit order selection is supported (bit field S2[MSBF] or STAT[MSBF] if the registers are 32-bit wide). */ #define FSL_FEATURE_UART_HAS_BIT_ORDER_SELECT (1) #define FSL_FEATURE_UART_HAS_BIT_ORDER_SELECTn(x) \ ((x) == 0 ? (1) : \ ((x) == 1 ? (1) : \ ((x) == 2 ? (1) : (-1)))) /* @brief Has smart card (ISO7816 protocol) support and no improved smart card support. */ #define FSL_FEATURE_UART_HAS_SMART_CARD_SUPPORT (1) #define FSL_FEATURE_UART_HAS_SMART_CARD_SUPPORTn(x) \ ((x) == 0 ? (1) : \ ((x) == 1 ? (0) : \ ((x) == 2 ? (0) : (-1)))) /* @brief Has improved smart card (ISO7816 protocol) support. */ #define FSL_FEATURE_UART_HAS_IMPROVED_SMART_CARD_SUPPORT (1) #define FSL_FEATURE_UART_HAS_IMPROVED_SMART_CARD_SUPPORTn(x) \ ((x) == 0 ? (1) : \ ((x) == 1 ? (0) : \ ((x) == 2 ? (0) : (-1)))) /* @brief Has local operation network (CEA709.1-B protocol) support. */ #define FSL_FEATURE_UART_HAS_LOCAL_OPERATION_NETWORK_SUPPORT (0) #define FSL_FEATURE_UART_HAS_LOCAL_OPERATION_NETWORK_SUPPORTn(x) \ ((x) == 0 ? (0) : \ ((x) == 1 ? (0) : \ ((x) == 2 ? (0) : (-1)))) /* @brief Has 32-bit registers (BAUD, STAT, CTRL, DATA, MATCH, MODIR) instead of 8-bit (BDH, BDL, C1, S1, D, etc.). */ #define FSL_FEATURE_UART_HAS_32BIT_REGISTERS (0) #elif defined(CPU_MK24FN1M0VDC12) || defined(CPU_MK24FN1M0VLL12) || defined(CPU_MK24FN1M0VLQ12) || defined(CPU_MK24FN256VDC12) || \ defined(CPU_MK63FN1M0VLQ12) || defined(CPU_MK63FN1M0VMD12) || defined(CPU_MK64FX512VDC12) || defined(CPU_MK64FN1M0VDC12) || \ defined(CPU_MK64FX512VLL12) || defined(CPU_MK64FN1M0VLL12) || defined(CPU_MK64FX512VLQ12) || defined(CPU_MK64FN1M0VLQ12) || \ defined(CPU_MK64FX512VMD12) || defined(CPU_MK64FN1M0VMD12) /* @brief Has receive FIFO overflow detection (bit field CFIFO[RXOFE]). */ #define FSL_FEATURE_UART_HAS_IRQ_EXTENDED_FUNCTIONS (1) /* @brief Has low power features (can be enabled in wait mode via register bit C1[DOZEEN] or CTRL[DOZEEN] if the registers are 32-bit wide). */ #define FSL_FEATURE_UART_HAS_LOW_POWER_UART_SUPPORT (0) #define FSL_FEATURE_UART_HAS_LOW_POWER_UART_SUPPORTn(x) \ ((x) == 0 ? (0) : \ ((x) == 1 ? (0) : \ ((x) == 2 ? (0) : \ ((x) == 3 ? (0) : \ ((x) == 4 ? (0) : \ ((x) == 5 ? (0) : (-1))))))) /* @brief Has extended data register ED (or extra flags in the DATA register if the registers are 32-bit wide). */ #define FSL_FEATURE_UART_HAS_EXTENDED_DATA_REGISTER_FLAGS (1) /* @brief Capacity (number of entries) of the transmit/receive FIFO (or zero if no FIFO is available). */ #define FSL_FEATURE_UART_HAS_FIFO (1) /* @brief Hardware flow control (RTS, CTS) is supported. */ #define FSL_FEATURE_UART_HAS_MODEM_SUPPORT (1) /* @brief Infrared (modulation) is supported. */ #define FSL_FEATURE_UART_HAS_IR_SUPPORT (1) /* @brief 2 bits long stop bit is available. */ #define FSL_FEATURE_UART_HAS_STOP_BIT_CONFIG_SUPPORT (1) /* @brief Maximal data width without parity bit. */ #define FSL_FEATURE_UART_HAS_10BIT_DATA_SUPPORT (0) #define FSL_FEATURE_UART_HAS_10BIT_DATA_SUPPORTn(x) \ ((x) == 0 ? (0) : \ ((x) == 1 ? (0) : \ ((x) == 2 ? (0) : \ ((x) == 3 ? (0) : \ ((x) == 4 ? (0) : \ ((x) == 5 ? (0) : (-1))))))) /* @brief Baud rate fine adjustment is available. */ #define FSL_FEATURE_UART_HAS_BAUD_RATE_FINE_ADJUST_SUPPORT (1) /* @brief Baud rate oversampling is available (has bit fields C4[OSR], C5[BOTHEDGE], C5[RESYNCDIS] or BAUD[OSR], BAUD[BOTHEDGE], BAUD[RESYNCDIS] if the registers are 32-bit wide). */ #define FSL_FEATURE_UART_HAS_BAUD_RATE_OVER_SAMPLING_SUPPORT (0) #define FSL_FEATURE_UART_HAS_BAUD_RATE_OVER_SAMPLING_SUPPORTn(x) \ ((x) == 0 ? (0) : \ ((x) == 1 ? (0) : \ ((x) == 2 ? (0) : \ ((x) == 3 ? (0) : \ ((x) == 4 ? (0) : \ ((x) == 5 ? (0) : (-1))))))) /* @brief Baud rate oversampling is available. */ #define FSL_FEATURE_UART_HAS_RX_RESYNC_SUPPORT (0) /* @brief Baud rate oversampling is available. */ #define FSL_FEATURE_UART_HAS_BOTH_EDGE_SAMPLING_SUPPORT (0) /* @brief Peripheral type. */ #define FSL_FEATURE_UART_IS_SCI (0) /* @brief Capacity (number of entries) of the transmit/receive FIFO (or zero if no FIFO is available). */ #define FSL_FEATURE_UART_FIFO_SIZE (8) #define FSL_FEATURE_UART_FIFO_SIZEn(x) \ ((x) == 0 ? (8) : \ ((x) == 1 ? (8) : \ ((x) == 2 ? (1) : \ ((x) == 3 ? (1) : \ ((x) == 4 ? (1) : \ ((x) == 5 ? (1) : (-1))))))) /* @brief Maximal data width without parity bit. */ #define FSL_FEATURE_UART_MAX_DATA_WIDTH_WITH_NO_PARITY (9) #define FSL_FEATURE_UART_MAX_DATA_WIDTH_WITH_NO_PARITYn(x) \ ((x) == 0 ? (9) : \ ((x) == 1 ? (9) : \ ((x) == 2 ? (9) : \ ((x) == 3 ? (9) : \ ((x) == 4 ? (9) : \ ((x) == 5 ? (9) : (-1))))))) /* @brief Maximal data width with parity bit. */ #define FSL_FEATURE_UART_MAX_DATA_WIDTH_WITH_PARITY (10) #define FSL_FEATURE_UART_MAX_DATA_WIDTH_WITH_PARITYn(x) \ ((x) == 0 ? (10) : \ ((x) == 1 ? (10) : \ ((x) == 2 ? (10) : \ ((x) == 3 ? (10) : \ ((x) == 4 ? (10) : \ ((x) == 5 ? (10) : (-1))))))) /* @brief Supports two match addresses to filter incoming frames. */ #define FSL_FEATURE_UART_HAS_ADDRESS_MATCHING (1) #define FSL_FEATURE_UART_HAS_ADDRESS_MATCHINGn(x) \ ((x) == 0 ? (1) : \ ((x) == 1 ? (1) : \ ((x) == 2 ? (1) : \ ((x) == 3 ? (1) : \ ((x) == 4 ? (1) : \ ((x) == 5 ? (1) : (-1))))))) /* @brief Has transmitter/receiver DMA enable bits C5[TDMAE]/C5[RDMAE] (or BAUD[TDMAE]/BAUD[RDMAE] if the registers are 32-bit wide). */ #define FSL_FEATURE_UART_HAS_DMA_ENABLE (0) #define FSL_FEATURE_UART_HAS_DMA_ENABLEn(x) \ ((x) == 0 ? (0) : \ ((x) == 1 ? (0) : \ ((x) == 2 ? (0) : \ ((x) == 3 ? (0) : \ ((x) == 4 ? (0) : \ ((x) == 5 ? (0) : (-1))))))) /* @brief Has transmitter/receiver DMA select bits C4[TDMAS]/C4[RDMAS], resp. C5[TDMAS]/C5[RDMAS] if IS_SCI = 0. */ #define FSL_FEATURE_UART_HAS_DMA_SELECT (1) #define FSL_FEATURE_UART_HAS_DMA_SELECTn(x) \ ((x) == 0 ? (1) : \ ((x) == 1 ? (1) : \ ((x) == 2 ? (1) : \ ((x) == 3 ? (1) : \ ((x) == 4 ? (1) : \ ((x) == 5 ? (1) : (-1))))))) /* @brief Data character bit order selection is supported (bit field S2[MSBF] or STAT[MSBF] if the registers are 32-bit wide). */ #define FSL_FEATURE_UART_HAS_BIT_ORDER_SELECT (1) #define FSL_FEATURE_UART_HAS_BIT_ORDER_SELECTn(x) \ ((x) == 0 ? (1) : \ ((x) == 1 ? (1) : \ ((x) == 2 ? (1) : \ ((x) == 3 ? (1) : \ ((x) == 4 ? (1) : \ ((x) == 5 ? (1) : (-1))))))) /* @brief Has smart card (ISO7816 protocol) support and no improved smart card support. */ #define FSL_FEATURE_UART_HAS_SMART_CARD_SUPPORT (1) #define FSL_FEATURE_UART_HAS_SMART_CARD_SUPPORTn(x) \ ((x) == 0 ? (1) : \ ((x) == 1 ? (0) : \ ((x) == 2 ? (0) : \ ((x) == 3 ? (0) : \ ((x) == 4 ? (0) : \ ((x) == 5 ? (0) : (-1))))))) /* @brief Has improved smart card (ISO7816 protocol) support. */ #define FSL_FEATURE_UART_HAS_IMPROVED_SMART_CARD_SUPPORT (0) #define FSL_FEATURE_UART_HAS_IMPROVED_SMART_CARD_SUPPORTn(x) \ ((x) == 0 ? (0) : \ ((x) == 1 ? (0) : \ ((x) == 2 ? (0) : \ ((x) == 3 ? (0) : \ ((x) == 4 ? (0) : \ ((x) == 5 ? (0) : (-1))))))) /* @brief Has local operation network (CEA709.1-B protocol) support. */ #define FSL_FEATURE_UART_HAS_LOCAL_OPERATION_NETWORK_SUPPORT (0) #define FSL_FEATURE_UART_HAS_LOCAL_OPERATION_NETWORK_SUPPORTn(x) \ ((x) == 0 ? (0) : \ ((x) == 1 ? (0) : \ ((x) == 2 ? (0) : \ ((x) == 3 ? (0) : \ ((x) == 4 ? (0) : \ ((x) == 5 ? (0) : (-1))))))) /* @brief Has 32-bit registers (BAUD, STAT, CTRL, DATA, MATCH, MODIR) instead of 8-bit (BDH, BDL, C1, S1, D, etc.). */ #define FSL_FEATURE_UART_HAS_32BIT_REGISTERS (0) #elif defined(CPU_MK65FN2M0CAC18) || defined(CPU_MK65FX1M0CAC18) || defined(CPU_MK65FN2M0VMI18) || defined(CPU_MK65FX1M0VMI18) || \ defined(CPU_MK66FN2M0VLQ18) || defined(CPU_MK66FX1M0VLQ18) || defined(CPU_MK66FN2M0VMD18) || defined(CPU_MK66FX1M0VMD18) /* @brief Has receive FIFO overflow detection (bit field CFIFO[RXOFE]). */ #define FSL_FEATURE_UART_HAS_IRQ_EXTENDED_FUNCTIONS (1) /* @brief Has low power features (can be enabled in wait mode via register bit C1[DOZEEN] or CTRL[DOZEEN] if the registers are 32-bit wide). */ #define FSL_FEATURE_UART_HAS_LOW_POWER_UART_SUPPORT (0) #define FSL_FEATURE_UART_HAS_LOW_POWER_UART_SUPPORTn(x) \ ((x) == 0 ? (0) : \ ((x) == 1 ? (0) : \ ((x) == 2 ? (0) : \ ((x) == 3 ? (0) : \ ((x) == 4 ? (0) : (-1)))))) /* @brief Has extended data register ED (or extra flags in the DATA register if the registers are 32-bit wide). */ #define FSL_FEATURE_UART_HAS_EXTENDED_DATA_REGISTER_FLAGS (1) /* @brief Capacity (number of entries) of the transmit/receive FIFO (or zero if no FIFO is available). */ #define FSL_FEATURE_UART_HAS_FIFO (1) /* @brief Hardware flow control (RTS, CTS) is supported. */ #define FSL_FEATURE_UART_HAS_MODEM_SUPPORT (1) /* @brief Infrared (modulation) is supported. */ #define FSL_FEATURE_UART_HAS_IR_SUPPORT (1) /* @brief 2 bits long stop bit is available. */ #define FSL_FEATURE_UART_HAS_STOP_BIT_CONFIG_SUPPORT (1) /* @brief Maximal data width without parity bit. */ #define FSL_FEATURE_UART_HAS_10BIT_DATA_SUPPORT (0) #define FSL_FEATURE_UART_HAS_10BIT_DATA_SUPPORTn(x) \ ((x) == 0 ? (0) : \ ((x) == 1 ? (0) : \ ((x) == 2 ? (0) : \ ((x) == 3 ? (0) : \ ((x) == 4 ? (0) : (-1)))))) /* @brief Baud rate fine adjustment is available. */ #define FSL_FEATURE_UART_HAS_BAUD_RATE_FINE_ADJUST_SUPPORT (1) /* @brief Baud rate oversampling is available (has bit fields C4[OSR], C5[BOTHEDGE], C5[RESYNCDIS] or BAUD[OSR], BAUD[BOTHEDGE], BAUD[RESYNCDIS] if the registers are 32-bit wide). */ #define FSL_FEATURE_UART_HAS_BAUD_RATE_OVER_SAMPLING_SUPPORT (0) #define FSL_FEATURE_UART_HAS_BAUD_RATE_OVER_SAMPLING_SUPPORTn(x) \ ((x) == 0 ? (0) : \ ((x) == 1 ? (0) : \ ((x) == 2 ? (0) : \ ((x) == 3 ? (0) : \ ((x) == 4 ? (0) : (-1)))))) /* @brief Baud rate oversampling is available. */ #define FSL_FEATURE_UART_HAS_RX_RESYNC_SUPPORT (0) /* @brief Baud rate oversampling is available. */ #define FSL_FEATURE_UART_HAS_BOTH_EDGE_SAMPLING_SUPPORT (0) /* @brief Peripheral type. */ #define FSL_FEATURE_UART_IS_SCI (0) /* @brief Capacity (number of entries) of the transmit/receive FIFO (or zero if no FIFO is available). */ #define FSL_FEATURE_UART_FIFO_SIZE (8) #define FSL_FEATURE_UART_FIFO_SIZEn(x) \ ((x) == 0 ? (8) : \ ((x) == 1 ? (8) : \ ((x) == 2 ? (1) : \ ((x) == 3 ? (1) : \ ((x) == 4 ? (1) : (-1)))))) /* @brief Maximal data width without parity bit. */ #define FSL_FEATURE_UART_MAX_DATA_WIDTH_WITH_NO_PARITY (9) #define FSL_FEATURE_UART_MAX_DATA_WIDTH_WITH_NO_PARITYn(x) \ ((x) == 0 ? (9) : \ ((x) == 1 ? (9) : \ ((x) == 2 ? (9) : \ ((x) == 3 ? (9) : \ ((x) == 4 ? (9) : (-1)))))) /* @brief Maximal data width with parity bit. */ #define FSL_FEATURE_UART_MAX_DATA_WIDTH_WITH_PARITY (10) #define FSL_FEATURE_UART_MAX_DATA_WIDTH_WITH_PARITYn(x) \ ((x) == 0 ? (10) : \ ((x) == 1 ? (10) : \ ((x) == 2 ? (10) : \ ((x) == 3 ? (10) : \ ((x) == 4 ? (10) : (-1)))))) /* @brief Supports two match addresses to filter incoming frames. */ #define FSL_FEATURE_UART_HAS_ADDRESS_MATCHING (1) #define FSL_FEATURE_UART_HAS_ADDRESS_MATCHINGn(x) \ ((x) == 0 ? (1) : \ ((x) == 1 ? (1) : \ ((x) == 2 ? (1) : \ ((x) == 3 ? (1) : \ ((x) == 4 ? (1) : (-1)))))) /* @brief Has transmitter/receiver DMA enable bits C5[TDMAE]/C5[RDMAE] (or BAUD[TDMAE]/BAUD[RDMAE] if the registers are 32-bit wide). */ #define FSL_FEATURE_UART_HAS_DMA_ENABLE (0) #define FSL_FEATURE_UART_HAS_DMA_ENABLEn(x) \ ((x) == 0 ? (0) : \ ((x) == 1 ? (0) : \ ((x) == 2 ? (0) : \ ((x) == 3 ? (0) : \ ((x) == 4 ? (0) : (-1)))))) /* @brief Has transmitter/receiver DMA select bits C4[TDMAS]/C4[RDMAS], resp. C5[TDMAS]/C5[RDMAS] if IS_SCI = 0. */ #define FSL_FEATURE_UART_HAS_DMA_SELECT (1) #define FSL_FEATURE_UART_HAS_DMA_SELECTn(x) \ ((x) == 0 ? (1) : \ ((x) == 1 ? (1) : \ ((x) == 2 ? (1) : \ ((x) == 3 ? (1) : \ ((x) == 4 ? (1) : (-1)))))) /* @brief Data character bit order selection is supported (bit field S2[MSBF] or STAT[MSBF] if the registers are 32-bit wide). */ #define FSL_FEATURE_UART_HAS_BIT_ORDER_SELECT (1) #define FSL_FEATURE_UART_HAS_BIT_ORDER_SELECTn(x) \ ((x) == 0 ? (1) : \ ((x) == 1 ? (1) : \ ((x) == 2 ? (1) : \ ((x) == 3 ? (1) : \ ((x) == 4 ? (1) : (-1)))))) /* @brief Has smart card (ISO7816 protocol) support and no improved smart card support. */ #define FSL_FEATURE_UART_HAS_SMART_CARD_SUPPORT (1) #define FSL_FEATURE_UART_HAS_SMART_CARD_SUPPORTn(x) \ ((x) == 0 ? (1) : \ ((x) == 1 ? (0) : \ ((x) == 2 ? (0) : \ ((x) == 3 ? (0) : \ ((x) == 4 ? (0) : (-1)))))) /* @brief Has improved smart card (ISO7816 protocol) support. */ #define FSL_FEATURE_UART_HAS_IMPROVED_SMART_CARD_SUPPORT (1) #define FSL_FEATURE_UART_HAS_IMPROVED_SMART_CARD_SUPPORTn(x) \ ((x) == 0 ? (1) : \ ((x) == 1 ? (0) : \ ((x) == 2 ? (0) : \ ((x) == 3 ? (0) : \ ((x) == 4 ? (0) : (-1)))))) /* @brief Has local operation network (CEA709.1-B protocol) support. */ #define FSL_FEATURE_UART_HAS_LOCAL_OPERATION_NETWORK_SUPPORT (0) #define FSL_FEATURE_UART_HAS_LOCAL_OPERATION_NETWORK_SUPPORTn(x) \ ((x) == 0 ? (0) : \ ((x) == 1 ? (0) : \ ((x) == 2 ? (0) : \ ((x) == 3 ? (0) : \ ((x) == 4 ? (0) : (-1)))))) /* @brief Has 32-bit registers (BAUD, STAT, CTRL, DATA, MATCH, MODIR) instead of 8-bit (BDH, BDL, C1, S1, D, etc.). */ #define FSL_FEATURE_UART_HAS_32BIT_REGISTERS (0) #elif defined(CPU_MK70FN1M0VMF12) || defined(CPU_MK70FX512VMF12) || defined(CPU_MK70FN1M0VMF15) || defined(CPU_MK70FX512VMF15) || \ defined(CPU_MK70FN1M0VMJ12) || defined(CPU_MK70FX512VMJ12) || defined(CPU_MK70FN1M0VMJ15) || defined(CPU_MK70FX512VMJ15) /* @brief Has receive FIFO overflow detection (bit field CFIFO[RXOFE]). */ #define FSL_FEATURE_UART_HAS_IRQ_EXTENDED_FUNCTIONS (1) /* @brief Has low power features (can be enabled in wait mode via register bit C1[DOZEEN] or CTRL[DOZEEN] if the registers are 32-bit wide). */ #define FSL_FEATURE_UART_HAS_LOW_POWER_UART_SUPPORT (0) #define FSL_FEATURE_UART_HAS_LOW_POWER_UART_SUPPORTn(x) \ ((x) == 0 ? (0) : \ ((x) == 1 ? (0) : \ ((x) == 2 ? (0) : \ ((x) == 3 ? (0) : \ ((x) == 4 ? (0) : \ ((x) == 5 ? (0) : (-1))))))) /* @brief Has extended data register ED (or extra flags in the DATA register if the registers are 32-bit wide). */ #define FSL_FEATURE_UART_HAS_EXTENDED_DATA_REGISTER_FLAGS (1) /* @brief Capacity (number of entries) of the transmit/receive FIFO (or zero if no FIFO is available). */ #define FSL_FEATURE_UART_HAS_FIFO (1) /* @brief Hardware flow control (RTS, CTS) is supported. */ #define FSL_FEATURE_UART_HAS_MODEM_SUPPORT (1) /* @brief Infrared (modulation) is supported. */ #define FSL_FEATURE_UART_HAS_IR_SUPPORT (1) /* @brief 2 bits long stop bit is available. */ #define FSL_FEATURE_UART_HAS_STOP_BIT_CONFIG_SUPPORT (0) /* @brief Maximal data width without parity bit. */ #define FSL_FEATURE_UART_HAS_10BIT_DATA_SUPPORT (0) #define FSL_FEATURE_UART_HAS_10BIT_DATA_SUPPORTn(x) \ ((x) == 0 ? (0) : \ ((x) == 1 ? (0) : \ ((x) == 2 ? (0) : \ ((x) == 3 ? (0) : \ ((x) == 4 ? (0) : \ ((x) == 5 ? (0) : (-1))))))) /* @brief Baud rate fine adjustment is available. */ #define FSL_FEATURE_UART_HAS_BAUD_RATE_FINE_ADJUST_SUPPORT (1) /* @brief Baud rate oversampling is available (has bit fields C4[OSR], C5[BOTHEDGE], C5[RESYNCDIS] or BAUD[OSR], BAUD[BOTHEDGE], BAUD[RESYNCDIS] if the registers are 32-bit wide). */ #define FSL_FEATURE_UART_HAS_BAUD_RATE_OVER_SAMPLING_SUPPORT (0) #define FSL_FEATURE_UART_HAS_BAUD_RATE_OVER_SAMPLING_SUPPORTn(x) \ ((x) == 0 ? (0) : \ ((x) == 1 ? (0) : \ ((x) == 2 ? (0) : \ ((x) == 3 ? (0) : \ ((x) == 4 ? (0) : \ ((x) == 5 ? (0) : (-1))))))) /* @brief Baud rate oversampling is available. */ #define FSL_FEATURE_UART_HAS_RX_RESYNC_SUPPORT (0) /* @brief Baud rate oversampling is available. */ #define FSL_FEATURE_UART_HAS_BOTH_EDGE_SAMPLING_SUPPORT (0) /* @brief Peripheral type. */ #define FSL_FEATURE_UART_IS_SCI (0) /* @brief Capacity (number of entries) of the transmit/receive FIFO (or zero if no FIFO is available). */ #define FSL_FEATURE_UART_FIFO_SIZE (8) #define FSL_FEATURE_UART_FIFO_SIZEn(x) \ ((x) == 0 ? (8) : \ ((x) == 1 ? (8) : \ ((x) == 2 ? (8) : \ ((x) == 3 ? (8) : \ ((x) == 4 ? (8) : \ ((x) == 5 ? (8) : (-1))))))) /* @brief Maximal data width without parity bit. */ #define FSL_FEATURE_UART_MAX_DATA_WIDTH_WITH_NO_PARITY (9) #define FSL_FEATURE_UART_MAX_DATA_WIDTH_WITH_NO_PARITYn(x) \ ((x) == 0 ? (9) : \ ((x) == 1 ? (9) : \ ((x) == 2 ? (9) : \ ((x) == 3 ? (9) : \ ((x) == 4 ? (9) : \ ((x) == 5 ? (9) : (-1))))))) /* @brief Maximal data width with parity bit. */ #define FSL_FEATURE_UART_MAX_DATA_WIDTH_WITH_PARITY (10) #define FSL_FEATURE_UART_MAX_DATA_WIDTH_WITH_PARITYn(x) \ ((x) == 0 ? (10) : \ ((x) == 1 ? (10) : \ ((x) == 2 ? (10) : \ ((x) == 3 ? (10) : \ ((x) == 4 ? (10) : \ ((x) == 5 ? (10) : (-1))))))) /* @brief Supports two match addresses to filter incoming frames. */ #define FSL_FEATURE_UART_HAS_ADDRESS_MATCHING (1) #define FSL_FEATURE_UART_HAS_ADDRESS_MATCHINGn(x) \ ((x) == 0 ? (1) : \ ((x) == 1 ? (1) : \ ((x) == 2 ? (1) : \ ((x) == 3 ? (1) : \ ((x) == 4 ? (1) : \ ((x) == 5 ? (1) : (-1))))))) /* @brief Has transmitter/receiver DMA enable bits C5[TDMAE]/C5[RDMAE] (or BAUD[TDMAE]/BAUD[RDMAE] if the registers are 32-bit wide). */ #define FSL_FEATURE_UART_HAS_DMA_ENABLE (0) #define FSL_FEATURE_UART_HAS_DMA_ENABLEn(x) \ ((x) == 0 ? (0) : \ ((x) == 1 ? (0) : \ ((x) == 2 ? (0) : \ ((x) == 3 ? (0) : \ ((x) == 4 ? (0) : \ ((x) == 5 ? (0) : (-1))))))) /* @brief Has transmitter/receiver DMA select bits C4[TDMAS]/C4[RDMAS], resp. C5[TDMAS]/C5[RDMAS] if IS_SCI = 0. */ #define FSL_FEATURE_UART_HAS_DMA_SELECT (1) #define FSL_FEATURE_UART_HAS_DMA_SELECTn(x) \ ((x) == 0 ? (1) : \ ((x) == 1 ? (1) : \ ((x) == 2 ? (1) : \ ((x) == 3 ? (1) : \ ((x) == 4 ? (1) : \ ((x) == 5 ? (1) : (-1))))))) /* @brief Data character bit order selection is supported (bit field S2[MSBF] or STAT[MSBF] if the registers are 32-bit wide). */ #define FSL_FEATURE_UART_HAS_BIT_ORDER_SELECT (1) #define FSL_FEATURE_UART_HAS_BIT_ORDER_SELECTn(x) \ ((x) == 0 ? (1) : \ ((x) == 1 ? (1) : \ ((x) == 2 ? (1) : \ ((x) == 3 ? (1) : \ ((x) == 4 ? (1) : \ ((x) == 5 ? (1) : (-1))))))) /* @brief Has smart card (ISO7816 protocol) support and no improved smart card support. */ #define FSL_FEATURE_UART_HAS_SMART_CARD_SUPPORT (1) #define FSL_FEATURE_UART_HAS_SMART_CARD_SUPPORTn(x) \ ((x) == 0 ? (1) : \ ((x) == 1 ? (1) : \ ((x) == 2 ? (0) : \ ((x) == 3 ? (0) : \ ((x) == 4 ? (0) : \ ((x) == 5 ? (0) : (-1))))))) /* @brief Has improved smart card (ISO7816 protocol) support. */ #define FSL_FEATURE_UART_HAS_IMPROVED_SMART_CARD_SUPPORT (0) #define FSL_FEATURE_UART_HAS_IMPROVED_SMART_CARD_SUPPORTn(x) \ ((x) == 0 ? (0) : \ ((x) == 1 ? (0) : \ ((x) == 2 ? (0) : \ ((x) == 3 ? (0) : \ ((x) == 4 ? (0) : \ ((x) == 5 ? (0) : (-1))))))) /* @brief Has local operation network (CEA709.1-B protocol) support. */ #define FSL_FEATURE_UART_HAS_LOCAL_OPERATION_NETWORK_SUPPORT (1) #define FSL_FEATURE_UART_HAS_LOCAL_OPERATION_NETWORK_SUPPORTn(x) \ ((x) == 0 ? (1) : \ ((x) == 1 ? (0) : \ ((x) == 2 ? (0) : \ ((x) == 3 ? (0) : \ ((x) == 4 ? (0) : \ ((x) == 5 ? (0) : (-1))))))) /* @brief Has 32-bit registers (BAUD, STAT, CTRL, DATA, MATCH, MODIR) instead of 8-bit (BDH, BDL, C1, S1, D, etc.). */ #define FSL_FEATURE_UART_HAS_32BIT_REGISTERS (0) #elif defined(CPU_MKL05Z8VFK4) || defined(CPU_MKL05Z16VFK4) || defined(CPU_MKL05Z32VFK4) || defined(CPU_MKL05Z8VLC4) || \ defined(CPU_MKL05Z16VLC4) || defined(CPU_MKL05Z32VLC4) || defined(CPU_MKL05Z8VFM4) || defined(CPU_MKL05Z16VFM4) || \ defined(CPU_MKL05Z32VFM4) || defined(CPU_MKL05Z16VLF4) || defined(CPU_MKL05Z32VLF4) /* @brief Has receive FIFO overflow detection (bit field CFIFO[RXOFE]). */ #define FSL_FEATURE_UART_HAS_IRQ_EXTENDED_FUNCTIONS (1) /* @brief Has low power features (can be enabled in wait mode via register bit C1[DOZEEN] or CTRL[DOZEEN] if the registers are 32-bit wide). */ #define FSL_FEATURE_UART_HAS_LOW_POWER_UART_SUPPORT (1) #define FSL_FEATURE_UART_HAS_LOW_POWER_UART_SUPPORTn(x) \ ((x) == 0 ? (1) : (-1)) /* @brief Has extended data register ED (or extra flags in the DATA register if the registers are 32-bit wide). */ #define FSL_FEATURE_UART_HAS_EXTENDED_DATA_REGISTER_FLAGS (0) /* @brief Capacity (number of entries) of the transmit/receive FIFO (or zero if no FIFO is available). */ #define FSL_FEATURE_UART_HAS_FIFO (0) /* @brief Hardware flow control (RTS, CTS) is supported. */ #define FSL_FEATURE_UART_HAS_MODEM_SUPPORT (0) /* @brief Infrared (modulation) is supported. */ #define FSL_FEATURE_UART_HAS_IR_SUPPORT (0) /* @brief 2 bits long stop bit is available. */ #define FSL_FEATURE_UART_HAS_STOP_BIT_CONFIG_SUPPORT (1) /* @brief Maximal data width without parity bit. */ #define FSL_FEATURE_UART_HAS_10BIT_DATA_SUPPORT (1) #define FSL_FEATURE_UART_HAS_10BIT_DATA_SUPPORTn(x) \ ((x) == 0 ? (1) : (-1)) /* @brief Baud rate fine adjustment is available. */ #define FSL_FEATURE_UART_HAS_BAUD_RATE_FINE_ADJUST_SUPPORT (0) /* @brief Baud rate oversampling is available (has bit fields C4[OSR], C5[BOTHEDGE], C5[RESYNCDIS] or BAUD[OSR], BAUD[BOTHEDGE], BAUD[RESYNCDIS] if the registers are 32-bit wide). */ #define FSL_FEATURE_UART_HAS_BAUD_RATE_OVER_SAMPLING_SUPPORT (1) #define FSL_FEATURE_UART_HAS_BAUD_RATE_OVER_SAMPLING_SUPPORTn(x) \ ((x) == 0 ? (1) : (-1)) /* @brief Baud rate oversampling is available. */ #define FSL_FEATURE_UART_HAS_RX_RESYNC_SUPPORT (1) /* @brief Baud rate oversampling is available. */ #define FSL_FEATURE_UART_HAS_BOTH_EDGE_SAMPLING_SUPPORT (1) /* @brief Peripheral type. */ #define FSL_FEATURE_UART_IS_SCI (1) /* @brief Capacity (number of entries) of the transmit/receive FIFO (or zero if no FIFO is available). */ #define FSL_FEATURE_UART_FIFO_SIZE (0) #define FSL_FEATURE_UART_FIFO_SIZEn(x) \ ((x) == 0 ? (0) : (-1)) /* @brief Maximal data width without parity bit. */ #define FSL_FEATURE_UART_MAX_DATA_WIDTH_WITH_NO_PARITY (10) #define FSL_FEATURE_UART_MAX_DATA_WIDTH_WITH_NO_PARITYn(x) \ ((x) == 0 ? (10) : (-1)) /* @brief Maximal data width with parity bit. */ #define FSL_FEATURE_UART_MAX_DATA_WIDTH_WITH_PARITY (9) #define FSL_FEATURE_UART_MAX_DATA_WIDTH_WITH_PARITYn(x) \ ((x) == 0 ? (9) : (-1)) /* @brief Supports two match addresses to filter incoming frames. */ #define FSL_FEATURE_UART_HAS_ADDRESS_MATCHING (1) #define FSL_FEATURE_UART_HAS_ADDRESS_MATCHINGn(x) \ ((x) == 0 ? (1) : (-1)) /* @brief Has transmitter/receiver DMA enable bits C5[TDMAE]/C5[RDMAE] (or BAUD[TDMAE]/BAUD[RDMAE] if the registers are 32-bit wide). */ #define FSL_FEATURE_UART_HAS_DMA_ENABLE (1) #define FSL_FEATURE_UART_HAS_DMA_ENABLEn(x) \ ((x) == 0 ? (1) : (-1)) /* @brief Has transmitter/receiver DMA select bits C4[TDMAS]/C4[RDMAS], resp. C5[TDMAS]/C5[RDMAS] if IS_SCI = 0. */ #define FSL_FEATURE_UART_HAS_DMA_SELECT (0) #define FSL_FEATURE_UART_HAS_DMA_SELECTn(x) \ ((x) == 0 ? (0) : (-1)) /* @brief Data character bit order selection is supported (bit field S2[MSBF] or STAT[MSBF] if the registers are 32-bit wide). */ #define FSL_FEATURE_UART_HAS_BIT_ORDER_SELECT (1) #define FSL_FEATURE_UART_HAS_BIT_ORDER_SELECTn(x) \ ((x) == 0 ? (1) : (-1)) /* @brief Has smart card (ISO7816 protocol) support and no improved smart card support. */ #define FSL_FEATURE_UART_HAS_SMART_CARD_SUPPORT (0) #define FSL_FEATURE_UART_HAS_SMART_CARD_SUPPORTn(x) \ ((x) == 0 ? (0) : (-1)) /* @brief Has improved smart card (ISO7816 protocol) support. */ #define FSL_FEATURE_UART_HAS_IMPROVED_SMART_CARD_SUPPORT (0) #define FSL_FEATURE_UART_HAS_IMPROVED_SMART_CARD_SUPPORTn(x) \ ((x) == 0 ? (0) : (-1)) /* @brief Has local operation network (CEA709.1-B protocol) support. */ #define FSL_FEATURE_UART_HAS_LOCAL_OPERATION_NETWORK_SUPPORT (0) #define FSL_FEATURE_UART_HAS_LOCAL_OPERATION_NETWORK_SUPPORTn(x) \ ((x) == 0 ? (0) : (-1)) /* @brief Has 32-bit registers (BAUD, STAT, CTRL, DATA, MATCH, MODIR) instead of 8-bit (BDH, BDL, C1, S1, D, etc.). */ #define FSL_FEATURE_UART_HAS_32BIT_REGISTERS (0) #elif defined(CPU_MKL13Z64VFM4) || defined(CPU_MKL13Z128VFM4) || defined(CPU_MKL13Z256VFM4) || defined(CPU_MKL13Z64VFT4) || \ defined(CPU_MKL13Z128VFT4) || defined(CPU_MKL13Z256VFT4) || defined(CPU_MKL13Z64VLH4) || defined(CPU_MKL13Z128VLH4) || \ defined(CPU_MKL13Z256VLH4) || defined(CPU_MKL13Z64VMP4) || defined(CPU_MKL13Z128VMP4) || defined(CPU_MKL13Z256VMP4) || \ defined(CPU_MKL23Z64VFM4) || defined(CPU_MKL23Z128VFM4) || defined(CPU_MKL23Z256VFM4) || defined(CPU_MKL23Z64VFT4) || \ defined(CPU_MKL23Z128VFT4) || defined(CPU_MKL23Z256VFT4) || defined(CPU_MKL23Z64VLH4) || defined(CPU_MKL23Z128VLH4) || \ defined(CPU_MKL23Z256VLH4) || defined(CPU_MKL23Z64VMP4) || defined(CPU_MKL23Z128VMP4) || defined(CPU_MKL23Z256VMP4) || \ defined(CPU_MKL33Z128VLH4) || defined(CPU_MKL33Z256VLH4) || defined(CPU_MKL33Z128VMP4) || defined(CPU_MKL33Z256VMP4) || \ defined(CPU_MKL43Z64VLH4) || defined(CPU_MKL43Z128VLH4) || defined(CPU_MKL43Z256VLH4) || defined(CPU_MKL43Z64VMP4) || \ defined(CPU_MKL43Z128VMP4) || defined(CPU_MKL43Z256VMP4) /* @brief Has receive FIFO overflow detection (bit field CFIFO[RXOFE]). */ #define FSL_FEATURE_UART_HAS_IRQ_EXTENDED_FUNCTIONS (1) /* @brief Has low power features (can be enabled in wait mode via register bit C1[DOZEEN] or CTRL[DOZEEN] if the registers are 32-bit wide). */ #define FSL_FEATURE_UART_HAS_LOW_POWER_UART_SUPPORT (0) #define FSL_FEATURE_UART_HAS_LOW_POWER_UART_SUPPORTn(x) \ ((x) == 0 ? (0) : (-1)) /* @brief Has extended data register ED (or extra flags in the DATA register if the registers are 32-bit wide). */ #define FSL_FEATURE_UART_HAS_EXTENDED_DATA_REGISTER_FLAGS (1) /* @brief Capacity (number of entries) of the transmit/receive FIFO (or zero if no FIFO is available). */ #define FSL_FEATURE_UART_HAS_FIFO (1) /* @brief Hardware flow control (RTS, CTS) is supported. */ #define FSL_FEATURE_UART_HAS_MODEM_SUPPORT (1) /* @brief Infrared (modulation) is supported. */ #define FSL_FEATURE_UART_HAS_IR_SUPPORT (1) /* @brief 2 bits long stop bit is available. */ #define FSL_FEATURE_UART_HAS_STOP_BIT_CONFIG_SUPPORT (0) /* @brief Maximal data width without parity bit. */ #define FSL_FEATURE_UART_HAS_10BIT_DATA_SUPPORT (0) #define FSL_FEATURE_UART_HAS_10BIT_DATA_SUPPORTn(x) \ ((x) == 0 ? (0) : (-1)) /* @brief Baud rate fine adjustment is available. */ #define FSL_FEATURE_UART_HAS_BAUD_RATE_FINE_ADJUST_SUPPORT (1) /* @brief Baud rate oversampling is available (has bit fields C4[OSR], C5[BOTHEDGE], C5[RESYNCDIS] or BAUD[OSR], BAUD[BOTHEDGE], BAUD[RESYNCDIS] if the registers are 32-bit wide). */ #define FSL_FEATURE_UART_HAS_BAUD_RATE_OVER_SAMPLING_SUPPORT (0) #define FSL_FEATURE_UART_HAS_BAUD_RATE_OVER_SAMPLING_SUPPORTn(x) \ ((x) == 0 ? (0) : (-1)) /* @brief Baud rate oversampling is available. */ #define FSL_FEATURE_UART_HAS_RX_RESYNC_SUPPORT (0) /* @brief Baud rate oversampling is available. */ #define FSL_FEATURE_UART_HAS_BOTH_EDGE_SAMPLING_SUPPORT (0) /* @brief Peripheral type. */ #define FSL_FEATURE_UART_IS_SCI (0) /* @brief Capacity (number of entries) of the transmit/receive FIFO (or zero if no FIFO is available). */ #define FSL_FEATURE_UART_FIFO_SIZE (8) #define FSL_FEATURE_UART_FIFO_SIZEn(x) \ ((x) == 0 ? (8) : (-1)) /* @brief Maximal data width without parity bit. */ #define FSL_FEATURE_UART_MAX_DATA_WIDTH_WITH_NO_PARITY (9) #define FSL_FEATURE_UART_MAX_DATA_WIDTH_WITH_NO_PARITYn(x) \ ((x) == 0 ? (9) : (-1)) /* @brief Maximal data width with parity bit. */ #define FSL_FEATURE_UART_MAX_DATA_WIDTH_WITH_PARITY (10) #define FSL_FEATURE_UART_MAX_DATA_WIDTH_WITH_PARITYn(x) \ ((x) == 0 ? (10) : (-1)) /* @brief Supports two match addresses to filter incoming frames. */ #define FSL_FEATURE_UART_HAS_ADDRESS_MATCHING (1) #define FSL_FEATURE_UART_HAS_ADDRESS_MATCHINGn(x) \ ((x) == 0 ? (1) : (-1)) /* @brief Has transmitter/receiver DMA enable bits C5[TDMAE]/C5[RDMAE] (or BAUD[TDMAE]/BAUD[RDMAE] if the registers are 32-bit wide). */ #define FSL_FEATURE_UART_HAS_DMA_ENABLE (0) #define FSL_FEATURE_UART_HAS_DMA_ENABLEn(x) \ ((x) == 0 ? (0) : (-1)) /* @brief Has transmitter/receiver DMA select bits C4[TDMAS]/C4[RDMAS], resp. C5[TDMAS]/C5[RDMAS] if IS_SCI = 0. */ #define FSL_FEATURE_UART_HAS_DMA_SELECT (1) #define FSL_FEATURE_UART_HAS_DMA_SELECTn(x) \ ((x) == 0 ? (1) : (-1)) /* @brief Data character bit order selection is supported (bit field S2[MSBF] or STAT[MSBF] if the registers are 32-bit wide). */ #define FSL_FEATURE_UART_HAS_BIT_ORDER_SELECT (1) #define FSL_FEATURE_UART_HAS_BIT_ORDER_SELECTn(x) \ ((x) == 0 ? (1) : (-1)) /* @brief Has smart card (ISO7816 protocol) support and no improved smart card support. */ #define FSL_FEATURE_UART_HAS_SMART_CARD_SUPPORT (1) #define FSL_FEATURE_UART_HAS_SMART_CARD_SUPPORTn(x) \ ((x) == 0 ? (1) : (-1)) /* @brief Has improved smart card (ISO7816 protocol) support. */ #define FSL_FEATURE_UART_HAS_IMPROVED_SMART_CARD_SUPPORT (1) #define FSL_FEATURE_UART_HAS_IMPROVED_SMART_CARD_SUPPORTn(x) \ ((x) == 0 ? (1) : (-1)) /* @brief Has local operation network (CEA709.1-B protocol) support. */ #define FSL_FEATURE_UART_HAS_LOCAL_OPERATION_NETWORK_SUPPORT (0) #define FSL_FEATURE_UART_HAS_LOCAL_OPERATION_NETWORK_SUPPORTn(x) \ ((x) == 0 ? (0) : (-1)) /* @brief Has 32-bit registers (BAUD, STAT, CTRL, DATA, MATCH, MODIR) instead of 8-bit (BDH, BDL, C1, S1, D, etc.). */ #define FSL_FEATURE_UART_HAS_32BIT_REGISTERS (0) #elif defined(CPU_MKL25Z32VFM4) || defined(CPU_MKL25Z64VFM4) || defined(CPU_MKL25Z128VFM4) || defined(CPU_MKL25Z32VFT4) || \ defined(CPU_MKL25Z64VFT4) || defined(CPU_MKL25Z128VFT4) || defined(CPU_MKL25Z32VLH4) || defined(CPU_MKL25Z64VLH4) || \ defined(CPU_MKL25Z128VLH4) || defined(CPU_MKL25Z32VLK4) || defined(CPU_MKL25Z64VLK4) || defined(CPU_MKL25Z128VLK4) || \ defined(CPU_MKL26Z256VLK4) || defined(CPU_MKL26Z128VLL4) || defined(CPU_MKL26Z256VLL4) || defined(CPU_MKL26Z128VMC4) || \ defined(CPU_MKL26Z256VMC4) || defined(CPU_MKL46Z128VLH4) || defined(CPU_MKL46Z256VLH4) || defined(CPU_MKL46Z128VLL4) || \ defined(CPU_MKL46Z256VLL4) || defined(CPU_MKL46Z128VMC4) || defined(CPU_MKL46Z256VMC4) /* @brief Has receive FIFO overflow detection (bit field CFIFO[RXOFE]). */ #define FSL_FEATURE_UART_HAS_IRQ_EXTENDED_FUNCTIONS (1) /* @brief Has low power features (can be enabled in wait mode via register bit C1[DOZEEN] or CTRL[DOZEEN] if the registers are 32-bit wide). */ #define FSL_FEATURE_UART_HAS_LOW_POWER_UART_SUPPORT (1) #define FSL_FEATURE_UART_HAS_LOW_POWER_UART_SUPPORTn(x) \ ((x) == 0 ? (1) : \ ((x) == 1 ? (0) : \ ((x) == 2 ? (0) : (-1)))) /* @brief Has extended data register ED (or extra flags in the DATA register if the registers are 32-bit wide). */ #define FSL_FEATURE_UART_HAS_EXTENDED_DATA_REGISTER_FLAGS (0) /* @brief Capacity (number of entries) of the transmit/receive FIFO (or zero if no FIFO is available). */ #define FSL_FEATURE_UART_HAS_FIFO (0) /* @brief Hardware flow control (RTS, CTS) is supported. */ #define FSL_FEATURE_UART_HAS_MODEM_SUPPORT (0) /* @brief Infrared (modulation) is supported. */ #define FSL_FEATURE_UART_HAS_IR_SUPPORT (0) /* @brief 2 bits long stop bit is available. */ #define FSL_FEATURE_UART_HAS_STOP_BIT_CONFIG_SUPPORT (1) /* @brief Maximal data width without parity bit. */ #define FSL_FEATURE_UART_HAS_10BIT_DATA_SUPPORT (1) #define FSL_FEATURE_UART_HAS_10BIT_DATA_SUPPORTn(x) \ ((x) == 0 ? (1) : \ ((x) == 1 ? (0) : \ ((x) == 2 ? (0) : (-1)))) /* @brief Baud rate fine adjustment is available. */ #define FSL_FEATURE_UART_HAS_BAUD_RATE_FINE_ADJUST_SUPPORT (0) /* @brief Baud rate oversampling is available (has bit fields C4[OSR], C5[BOTHEDGE], C5[RESYNCDIS] or BAUD[OSR], BAUD[BOTHEDGE], BAUD[RESYNCDIS] if the registers are 32-bit wide). */ #define FSL_FEATURE_UART_HAS_BAUD_RATE_OVER_SAMPLING_SUPPORT (1) #define FSL_FEATURE_UART_HAS_BAUD_RATE_OVER_SAMPLING_SUPPORTn(x) \ ((x) == 0 ? (1) : \ ((x) == 1 ? (0) : \ ((x) == 2 ? (0) : (-1)))) /* @brief Baud rate oversampling is available. */ #define FSL_FEATURE_UART_HAS_RX_RESYNC_SUPPORT (1) /* @brief Baud rate oversampling is available. */ #define FSL_FEATURE_UART_HAS_BOTH_EDGE_SAMPLING_SUPPORT (1) /* @brief Peripheral type. */ #define FSL_FEATURE_UART_IS_SCI (1) /* @brief Capacity (number of entries) of the transmit/receive FIFO (or zero if no FIFO is available). */ #define FSL_FEATURE_UART_FIFO_SIZE (0) #define FSL_FEATURE_UART_FIFO_SIZEn(x) \ ((x) == 0 ? (0) : \ ((x) == 1 ? (0) : \ ((x) == 2 ? (0) : (-1)))) /* @brief Maximal data width without parity bit. */ #define FSL_FEATURE_UART_MAX_DATA_WIDTH_WITH_NO_PARITY (10) #define FSL_FEATURE_UART_MAX_DATA_WIDTH_WITH_NO_PARITYn(x) \ ((x) == 0 ? (10) : \ ((x) == 1 ? (9) : \ ((x) == 2 ? (9) : (-1)))) /* @brief Maximal data width with parity bit. */ #define FSL_FEATURE_UART_MAX_DATA_WIDTH_WITH_PARITY (9) #define FSL_FEATURE_UART_MAX_DATA_WIDTH_WITH_PARITYn(x) \ ((x) == 0 ? (9) : \ ((x) == 1 ? (8) : \ ((x) == 2 ? (8) : (-1)))) /* @brief Supports two match addresses to filter incoming frames. */ #define FSL_FEATURE_UART_HAS_ADDRESS_MATCHING (1) #define FSL_FEATURE_UART_HAS_ADDRESS_MATCHINGn(x) \ ((x) == 0 ? (1) : \ ((x) == 1 ? (0) : \ ((x) == 2 ? (0) : (-1)))) /* @brief Has transmitter/receiver DMA enable bits C5[TDMAE]/C5[RDMAE] (or BAUD[TDMAE]/BAUD[RDMAE] if the registers are 32-bit wide). */ #define FSL_FEATURE_UART_HAS_DMA_ENABLE (1) #define FSL_FEATURE_UART_HAS_DMA_ENABLEn(x) \ ((x) == 0 ? (1) : \ ((x) == 1 ? (0) : \ ((x) == 2 ? (0) : (-1)))) /* @brief Has transmitter/receiver DMA select bits C4[TDMAS]/C4[RDMAS], resp. C5[TDMAS]/C5[RDMAS] if IS_SCI = 0. */ #define FSL_FEATURE_UART_HAS_DMA_SELECT (1) #define FSL_FEATURE_UART_HAS_DMA_SELECTn(x) \ ((x) == 0 ? (0) : \ ((x) == 1 ? (1) : \ ((x) == 2 ? (1) : (-1)))) /* @brief Data character bit order selection is supported (bit field S2[MSBF] or STAT[MSBF] if the registers are 32-bit wide). */ #define FSL_FEATURE_UART_HAS_BIT_ORDER_SELECT (1) #define FSL_FEATURE_UART_HAS_BIT_ORDER_SELECTn(x) \ ((x) == 0 ? (1) : \ ((x) == 1 ? (0) : \ ((x) == 2 ? (0) : (-1)))) /* @brief Has smart card (ISO7816 protocol) support and no improved smart card support. */ #define FSL_FEATURE_UART_HAS_SMART_CARD_SUPPORT (0) #define FSL_FEATURE_UART_HAS_SMART_CARD_SUPPORTn(x) \ ((x) == 0 ? (0) : \ ((x) == 1 ? (0) : \ ((x) == 2 ? (0) : (-1)))) /* @brief Has improved smart card (ISO7816 protocol) support. */ #define FSL_FEATURE_UART_HAS_IMPROVED_SMART_CARD_SUPPORT (0) #define FSL_FEATURE_UART_HAS_IMPROVED_SMART_CARD_SUPPORTn(x) \ ((x) == 0 ? (0) : \ ((x) == 1 ? (0) : \ ((x) == 2 ? (0) : (-1)))) /* @brief Has local operation network (CEA709.1-B protocol) support. */ #define FSL_FEATURE_UART_HAS_LOCAL_OPERATION_NETWORK_SUPPORT (0) #define FSL_FEATURE_UART_HAS_LOCAL_OPERATION_NETWORK_SUPPORTn(x) \ ((x) == 0 ? (0) : \ ((x) == 1 ? (0) : \ ((x) == 2 ? (0) : (-1)))) /* @brief Has 32-bit registers (BAUD, STAT, CTRL, DATA, MATCH, MODIR) instead of 8-bit (BDH, BDL, C1, S1, D, etc.). */ #define FSL_FEATURE_UART_HAS_32BIT_REGISTERS (0) #elif defined(CPU_MKV40F128VLH15) || defined(CPU_MKV40F128VLL15) || defined(CPU_MKV40F256VLH15) || defined(CPU_MKV40F256VLL15) || \ defined(CPU_MKV40F64VLH15) || defined(CPU_MKV43F128VLH15) || defined(CPU_MKV43F128VLL15) || defined(CPU_MKV43F64VLH15) || \ defined(CPU_MKV44F128VLH15) || defined(CPU_MKV44F128VLL15) || defined(CPU_MKV44F64VLH15) || defined(CPU_MKV45F128VLH15) || \ defined(CPU_MKV45F128VLL15) || defined(CPU_MKV45F256VLH15) || defined(CPU_MKV45F256VLL15) || defined(CPU_MKV46F128VLH15) || \ defined(CPU_MKV46F128VLL15) || defined(CPU_MKV46F256VLH15) || defined(CPU_MKV46F256VLL15) /* @brief Has receive FIFO overflow detection (bit field CFIFO[RXOFE]). */ #define FSL_FEATURE_UART_HAS_IRQ_EXTENDED_FUNCTIONS (1) /* @brief Has low power features (can be enabled in wait mode via register bit C1[DOZEEN] or CTRL[DOZEEN] if the registers are 32-bit wide). */ #define FSL_FEATURE_UART_HAS_LOW_POWER_UART_SUPPORT (0) #define FSL_FEATURE_UART_HAS_LOW_POWER_UART_SUPPORTn(x) \ ((x) == 0 ? (0) : \ ((x) == 1 ? (0) : (-1))) /* @brief Has extended data register ED (or extra flags in the DATA register if the registers are 32-bit wide). */ #define FSL_FEATURE_UART_HAS_EXTENDED_DATA_REGISTER_FLAGS (1) /* @brief Capacity (number of entries) of the transmit/receive FIFO (or zero if no FIFO is available). */ #define FSL_FEATURE_UART_HAS_FIFO (1) /* @brief Hardware flow control (RTS, CTS) is supported. */ #define FSL_FEATURE_UART_HAS_MODEM_SUPPORT (1) /* @brief Infrared (modulation) is supported. */ #define FSL_FEATURE_UART_HAS_IR_SUPPORT (1) /* @brief 2 bits long stop bit is available. */ #define FSL_FEATURE_UART_HAS_STOP_BIT_CONFIG_SUPPORT (1) /* @brief Maximal data width without parity bit. */ #define FSL_FEATURE_UART_HAS_10BIT_DATA_SUPPORT (0) #define FSL_FEATURE_UART_HAS_10BIT_DATA_SUPPORTn(x) \ ((x) == 0 ? (0) : \ ((x) == 1 ? (0) : (-1))) /* @brief Baud rate fine adjustment is available. */ #define FSL_FEATURE_UART_HAS_BAUD_RATE_FINE_ADJUST_SUPPORT (1) /* @brief Baud rate oversampling is available (has bit fields C4[OSR], C5[BOTHEDGE], C5[RESYNCDIS] or BAUD[OSR], BAUD[BOTHEDGE], BAUD[RESYNCDIS] if the registers are 32-bit wide). */ #define FSL_FEATURE_UART_HAS_BAUD_RATE_OVER_SAMPLING_SUPPORT (0) #define FSL_FEATURE_UART_HAS_BAUD_RATE_OVER_SAMPLING_SUPPORTn(x) \ ((x) == 0 ? (0) : \ ((x) == 1 ? (0) : (-1))) /* @brief Baud rate oversampling is available. */ #define FSL_FEATURE_UART_HAS_RX_RESYNC_SUPPORT (0) /* @brief Baud rate oversampling is available. */ #define FSL_FEATURE_UART_HAS_BOTH_EDGE_SAMPLING_SUPPORT (0) /* @brief Peripheral type. */ #define FSL_FEATURE_UART_IS_SCI (0) /* @brief Capacity (number of entries) of the transmit/receive FIFO (or zero if no FIFO is available). */ #define FSL_FEATURE_UART_FIFO_SIZE (8) #define FSL_FEATURE_UART_FIFO_SIZEn(x) \ ((x) == 0 ? (8) : \ ((x) == 1 ? (8) : (-1))) /* @brief Maximal data width without parity bit. */ #define FSL_FEATURE_UART_MAX_DATA_WIDTH_WITH_NO_PARITY (9) #define FSL_FEATURE_UART_MAX_DATA_WIDTH_WITH_NO_PARITYn(x) \ ((x) == 0 ? (9) : \ ((x) == 1 ? (9) : (-1))) /* @brief Maximal data width with parity bit. */ #define FSL_FEATURE_UART_MAX_DATA_WIDTH_WITH_PARITY (10) #define FSL_FEATURE_UART_MAX_DATA_WIDTH_WITH_PARITYn(x) \ ((x) == 0 ? (10) : \ ((x) == 1 ? (10) : (-1))) /* @brief Supports two match addresses to filter incoming frames. */ #define FSL_FEATURE_UART_HAS_ADDRESS_MATCHING (1) #define FSL_FEATURE_UART_HAS_ADDRESS_MATCHINGn(x) \ ((x) == 0 ? (1) : \ ((x) == 1 ? (1) : (-1))) /* @brief Has transmitter/receiver DMA enable bits C5[TDMAE]/C5[RDMAE] (or BAUD[TDMAE]/BAUD[RDMAE] if the registers are 32-bit wide). */ #define FSL_FEATURE_UART_HAS_DMA_ENABLE (0) #define FSL_FEATURE_UART_HAS_DMA_ENABLEn(x) \ ((x) == 0 ? (0) : \ ((x) == 1 ? (0) : (-1))) /* @brief Has transmitter/receiver DMA select bits C4[TDMAS]/C4[RDMAS], resp. C5[TDMAS]/C5[RDMAS] if IS_SCI = 0. */ #define FSL_FEATURE_UART_HAS_DMA_SELECT (1) #define FSL_FEATURE_UART_HAS_DMA_SELECTn(x) \ ((x) == 0 ? (1) : \ ((x) == 1 ? (1) : (-1))) /* @brief Data character bit order selection is supported (bit field S2[MSBF] or STAT[MSBF] if the registers are 32-bit wide). */ #define FSL_FEATURE_UART_HAS_BIT_ORDER_SELECT (1) #define FSL_FEATURE_UART_HAS_BIT_ORDER_SELECTn(x) \ ((x) == 0 ? (1) : \ ((x) == 1 ? (1) : (-1))) /* @brief Has smart card (ISO7816 protocol) support and no improved smart card support. */ #define FSL_FEATURE_UART_HAS_SMART_CARD_SUPPORT (0) #define FSL_FEATURE_UART_HAS_SMART_CARD_SUPPORTn(x) \ ((x) == 0 ? (0) : \ ((x) == 1 ? (0) : (-1))) /* @brief Has improved smart card (ISO7816 protocol) support. */ #define FSL_FEATURE_UART_HAS_IMPROVED_SMART_CARD_SUPPORT (0) #define FSL_FEATURE_UART_HAS_IMPROVED_SMART_CARD_SUPPORTn(x) \ ((x) == 0 ? (0) : \ ((x) == 1 ? (0) : (-1))) /* @brief Has local operation network (CEA709.1-B protocol) support. */ #define FSL_FEATURE_UART_HAS_LOCAL_OPERATION_NETWORK_SUPPORT (0) #define FSL_FEATURE_UART_HAS_LOCAL_OPERATION_NETWORK_SUPPORTn(x) \ ((x) == 0 ? (0) : \ ((x) == 1 ? (0) : (-1))) /* @brief Has 32-bit registers (BAUD, STAT, CTRL, DATA, MATCH, MODIR) instead of 8-bit (BDH, BDL, C1, S1, D, etc.). */ #define FSL_FEATURE_UART_HAS_32BIT_REGISTERS (0) #else #error "No valid CPU defined!" #endif #endif /* __FSL_UART_FEATURES_H__ */ /******************************************************************************* * EOF ******************************************************************************/ ================================================ FILE: Zelig/mbed/TARGET_K64F/TARGET_Freescale/TARGET_KPSDK_MCUS/TARGET_KPSDK_CODE/hal/uart/fsl_uart_hal.h ================================================ /* * Copyright (c) 2013 - 2014, Freescale Semiconductor, Inc. * All rights reserved. * * Redistribution and use in source and binary forms, with or without modification, * are permitted provided that the following conditions are met: * * o Redistributions of source code must retain the above copyright notice, this list * of conditions and the following disclaimer. * * o Redistributions in binary form must reproduce the above copyright notice, this * list of conditions and the following disclaimer in the documentation and/or * other materials provided with the distribution. * * o Neither the name of Freescale Semiconductor, Inc. nor the names of its * contributors may be used to endorse or promote products derived from this * software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT 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. */ #ifndef __FSL_UART_HAL_H__ #define __FSL_UART_HAL_H__ #include #include #include #include "fsl_uart_features.h" #include "fsl_device_registers.h" /*! * @addtogroup uart_hal * @{ */ /*! @file*/ /******************************************************************************* * Definitions ******************************************************************************/ #define UART_SHIFT (8U) /*! @brief Error codes for the UART driver. */ typedef enum _uart_status { kStatus_UART_Success = 0x0U, kStatus_UART_BaudRateCalculationError = 0x1U, kStatus_UART_RxStandbyModeError = 0x2U, kStatus_UART_ClearStatusFlagError = 0x3U, kStatus_UART_TxNotDisabled = 0x4U, kStatus_UART_RxNotDisabled = 0x5U, kStatus_UART_TxOrRxNotDisabled = 0x6U, kStatus_UART_TxBusy = 0x7U, kStatus_UART_RxBusy = 0x8U, kStatus_UART_NoTransmitInProgress = 0x9U, kStatus_UART_NoReceiveInProgress = 0xAU, kStatus_UART_Timeout = 0xBU, kStatus_UART_Initialized = 0xCU, kStatus_UART_RxCallBackEnd = 0xDU } uart_status_t; /*! * @brief UART number of stop bits. * * These constants define the number of allowable stop bits to configure in a UART baseAddr. */ typedef enum _uart_stop_bit_count { kUartOneStopBit = 0U, /*!< one stop bit */ kUartTwoStopBit = 1U, /*!< two stop bits */ } uart_stop_bit_count_t; /*! * @brief UART parity mode. * * These constants define the UART parity mode options: disabled or enabled of type even or odd. */ typedef enum _uart_parity_mode { kUartParityDisabled = 0x0U, /*!< parity disabled */ kUartParityEven = 0x2U, /*!< parity enabled, type even, bit setting: PE|PT = 10 */ kUartParityOdd = 0x3U, /*!< parity enabled, type odd, bit setting: PE|PT = 11 */ } uart_parity_mode_t; /*! * @brief UART number of bits in a character. * * These constants define the number of allowable data bits per UART character. Note, check the * UART documentation to determine if the desired UART baseAddr supports the desired number * of data bits per UART character. */ typedef enum _uart_bit_count_per_char { kUart8BitsPerChar = 0U, /*!< 8-bit data characters */ kUart9BitsPerChar = 1U, /*!< 9-bit data characters */ } uart_bit_count_per_char_t; /*! * @brief UART operation configuration constants. * * This provides constants for UART operational states: "operates normally" * or "stops/ceases operation" */ typedef enum _uart_operation_config { kUartOperates = 0U, /*!< UART continues to operate normally */ kUartStops = 1U, /*!< UART ceases operation */ } uart_operation_config_t; /*! @brief UART receiver source select mode. */ typedef enum _uart_receiver_source { kUartLoopBack = 0U, /*!< Internal loop back mode. */ kUartSingleWire = 1U,/*!< Single wire mode. */ } uart_receiver_source_t ; /*! * @brief UART wakeup from standby method constants. * * This provides constants for the two UART wakeup methods: idle-line or address-mark. */ typedef enum _uart_wakeup_method { kUartIdleLineWake = 0U, /*!< The idle-line wakes UART receiver from standby */ kUartAddrMarkWake = 1U, /*!< The address-mark wakes UART receiver from standby */ } uart_wakeup_method_t; /*! * @brief UART idle-line detect selection types. * * This provides constants for the UART idle character bit-count start: either after start or * stop bit. */ typedef enum _uart_idle_line_select { kUartIdleLineAfterStartBit = 0U, /*!< UART idle character bit count start after start bit */ kUartIdleLineAfterStopBit = 1U, /*!< UART idle character bit count start after stop bit */ } uart_idle_line_select_t; /*! * @brief UART break character length settings for transmit/detect. * * This provides constants for the UART break character length for both transmission and detection * purposes. Note that the actual maximum bit times may vary depending on the UART baseAddr. */ typedef enum _uart_break_char_length { kUartBreakChar10BitMinimum = 0U, /*!< UART break char length 10 bit times (if M = 0, SBNS = 0) or 11 (if M = 1, SBNS = 0 or M = 0, SBNS = 1) or 12 (if M = 1, SBNS = 1 or M10 = 1, SNBS = 0) or 13 (if M10 = 1, SNBS = 1) */ kUartBreakChar13BitMinimum = 1U, /*!< UART break char length 13 bit times (if M = 0, SBNS = 0) or 14 (if M = 1, SBNS = 0 or M = 0, SBNS = 1) or 15 (if M = 1, SBNS = 1 or M10 = 1, SNBS = 0) or 16 (if M10 = 1, SNBS = 1) */ } uart_break_char_length_t; /*! * @brief UART single-wire mode transmit direction. * * This provides constants for the UART transmit direction when configured for single-wire mode. * The transmit line TXDIR is either an input or output. */ typedef enum _uart_singlewire_txdir { kUartSinglewireTxdirIn = 0U, /*!< UART Single-Wire mode TXDIR input */ kUartSinglewireTxdirOut = 1U, /*!< UART Single-Wire mode TXDIR output */ } uart_singlewire_txdir_t; /*! * @brief UART infrared transmitter pulse width options. * * This provides constants for the UART infrared (IR) pulse widths. Options include 3/16, 1/16 * 1/32, and 1/4 pulse widths. */ typedef enum _uart_ir_tx_pulsewidth { kUartIrThreeSixteenthsWidth = 0U, /*!< 3/16 pulse */ kUartIrOneSixteenthWidth = 1U, /*!< 1/16 pulse */ kUartIrOneThirtysecondsWidth = 2U, /*!< 1/32 pulse */ kUartIrOneFourthWidth = 3U, /*!< 1/4 pulse */ } uart_ir_tx_pulsewidth_t; /*! * @brief UART status flags. * * This provides constants for the UART status flags for use in the UART functions. */ typedef enum _uart_status_flag { kUartTxDataRegEmpty = 0U << UART_SHIFT | BP_UART_S1_TDRE, /*!< Tx data register empty flag, sets when Tx buffer is empty */ kUartTxComplete = 0U << UART_SHIFT | BP_UART_S1_TC, /*!< Transmission complete flag, sets when transmission activity complete */ kUartRxDataRegFull = 0U << UART_SHIFT | BP_UART_S1_RDRF, /*!< Rx data register full flag, sets when the receive data buffer is full */ kUartIdleLineDetect = 0U << UART_SHIFT | BP_UART_S1_IDLE, /*!< Idle line detect flag, sets when idle line detected */ kUartRxOverrun = 0U << UART_SHIFT | BP_UART_S1_OR, /*!< Rxr Overrun, sets when new data is received before data is read from receive register */ kUartNoiseDetect = 0U << UART_SHIFT | BP_UART_S1_NF, /*!< Rxr takes 3 samples of each received bit. If any of these samples differ, noise flag sets */ kUartFrameErr = 0U << UART_SHIFT | BP_UART_S1_FE, /*!< Frame error flag, sets if logic 0 was detected where stop bit expected */ kUartParityErr = 0U << UART_SHIFT | BP_UART_S1_PF, /*!< If parity enabled, sets upon parity error detection */ kUartLineBreakDetect = 1U << UART_SHIFT | BP_UART_S2_LBKDIF, /*!< LIN break detect interrupt flag, sets when LIN break char detected and LIN circuit enabled */ kUartRxActiveEdgeDetect = 1U << UART_SHIFT | BP_UART_S2_RXEDGIF, /*!< Rx pin active edge interrupt flag, sets when active edge detected */ kUartRxActive = 1U << UART_SHIFT | BP_UART_S2_RAF, /*!< Receiver Active Flag (RAF), sets at beginning of valid start bit */ #if FSL_FEATURE_UART_HAS_EXTENDED_DATA_REGISTER_FLAGS kUartNoiseInCurrentWord = 2U << UART_SHIFT | BP_UART_ED_NOISY, /*!< NOISY bit, sets if noise detected in current data word */ kUartParityErrInCurrentWord = 2U << UART_SHIFT | BP_UART_ED_PARITYE, /*!< PARITYE bit, sets if noise detected in current data word */ #endif #if FSL_FEATURE_UART_HAS_FIFO kUartTxBuffEmpty = 3U << UART_SHIFT | BP_UART_SFIFO_TXEMPT, /*!< TXEMPT bit, sets if Tx buffer is empty */ kUartRxBuffEmpty = 3U << UART_SHIFT | BP_UART_SFIFO_RXEMPT, /*!< RXEMPT bit, sets if Rx buffer is empty */ kUartTxBuffOverflow = 3U << UART_SHIFT | BP_UART_SFIFO_TXOF, /*!< TXOF bit, sets if Tx buffer overflow occurred */ kUartRxBuffUnderflow = 3U << UART_SHIFT | BP_UART_SFIFO_RXUF, /*!< RXUF bit, sets if receive buffer underflow occurred */ #endif } uart_status_flag_t; /*! * @brief UART interrupt configuration structure, default settings are 0 (disabled). * * This structure contains the settings for all of the UART interrupt configurations. */ typedef enum _uart_interrupt { kUartIntLinBreakDetect = 0U << UART_SHIFT | BP_UART_BDH_LBKDIE, /*!< LIN break detect. */ kUartIntRxActiveEdge = 0U << UART_SHIFT | BP_UART_BDH_RXEDGIE, /*!< RX Active Edge. */ kUartIntTxDataRegEmpty = 1U << UART_SHIFT | BP_UART_C2_TIE, /*!< Transmit data register empty. */ kUartIntTxComplete = 1U << UART_SHIFT | BP_UART_C2_TCIE, /*!< Transmission complete. */ kUartIntRxDataRegFull = 1U << UART_SHIFT | BP_UART_C2_RIE, /*!< Receiver data register full. */ kUartIntIdleLine = 1U << UART_SHIFT | BP_UART_C2_ILIE, /*!< Idle line. */ kUartIntRxOverrun = 2U << UART_SHIFT | BP_UART_C3_ORIE, /*!< Receiver Overrun. */ kUartIntNoiseErrFlag = 2U << UART_SHIFT | BP_UART_C3_NEIE, /*!< Noise error flag. */ kUartIntFrameErrFlag = 2U << UART_SHIFT | BP_UART_C3_FEIE, /*!< Framing error flag. */ kUartIntParityErrFlag = 2U << UART_SHIFT | BP_UART_C3_PEIE, /*!< Parity error flag. */ #if FSL_FEATURE_UART_HAS_FIFO kUartIntTxFifoOverflow = 3U << UART_SHIFT | BP_UART_CFIFO_TXOFE, /*!< TX FIFO Overflow. */ kUartIntRxFifoUnderflow = 3U << UART_SHIFT | BP_UART_CFIFO_RXUFE, /*!< RX FIFO Underflow. */ #endif } uart_interrupt_t; /******************************************************************************* * API ******************************************************************************/ #if defined(__cplusplus) extern "C" { #endif /*! * @name UART Common Configurations * @{ */ /*! * @brief Initializes the UART controller. * * This function initializes the module to a known state. * * @param baseAddr UART module base address. */ void UART_HAL_Init(uint32_t baseAddr); /*! * @brief Enables the UART transmitter. * * This function allows the user to enable the UART transmitter. * * @param baseAddr UART module base address. */ static inline void UART_HAL_EnableTransmitter(uint32_t baseAddr) { BW_UART_C2_TE(baseAddr, 1U); } /*! * @brief Disables the UART transmitter. * * This function allows the user to disable the UART transmitter. * * @param baseAddr UART module base address. */ static inline void UART_HAL_DisableTransmitter(uint32_t baseAddr) { BW_UART_C2_TE(baseAddr, 0U); } /*! * @brief Gets the UART transmitter enabled/disabled configuration setting. * * This function allows the user to get the setting of the UART transmitter. * * @param baseAddr UART module base address. * @return The state of UART transmitter enable(true)/disable(false) setting. */ static inline bool UART_HAL_IsTransmitterEnabled(uint32_t baseAddr) { return (bool)BR_UART_C2_TE(baseAddr); } /*! * @brief Enables the UART receiver. * * This function allows the user to enable the UART receiver. * * @param baseAddr UART module base address. */ static inline void UART_HAL_EnableReceiver(uint32_t baseAddr) { BW_UART_C2_RE(baseAddr, 1U); } /*! * @brief Disables the UART receiver. * * This function allows the user to disable the UART receiver. * * @param baseAddr UART module base address. */ static inline void UART_HAL_DisableReceiver(uint32_t baseAddr) { BW_UART_C2_RE(baseAddr, 0U); } /*! * @brief Gets the UART receiver enabled/disabled configuration setting. * * This function allows the user to get the setting of the UART receiver. * * @param baseAddr UART module base address. * @return The state of UART receiver enable(true)/disable(false) setting. */ static inline bool UART_HAL_IsReceiverEnabled(uint32_t baseAddr) { return (bool)BR_UART_C2_RE(baseAddr); } /*! * @brief Configures the UART baud rate. * * This function programs the UART baud rate to the desired value passed in by the user. The user * must also pass in the module source clock so that the function can calculate the baud * rate divisors to their appropriate values. * In some UART baseAddrs it is required that the transmitter/receiver be disabled * before calling this function. * Generally this is applied to all UARTs to ensure safe operation. * * @param baseAddr UART module base address. * @param sourceClockInHz UART source input clock in Hz. * @param baudRate UART desired baud rate. * @return An error code or kStatus_UART_Success */ uart_status_t UART_HAL_SetBaudRate(uint32_t baseAddr, uint32_t sourceClockInHz, uint32_t baudRate); /*! * @brief Sets the UART baud rate modulo divisor value. * * This function allows the user to program the baud rate divisor directly in situations * where the divisor value is known. In this case, the user may not want to call the * UART_HAL_SetBaudRate() function, as the divisor is already known. * * @param baseAddr UART module base address. * @param baudRateDivisor The baud rate modulo division "SBR" value. */ void UART_HAL_SetBaudRateDivisor(uint32_t baseAddr, uint16_t baudRateDivisor); #if FSL_FEATURE_UART_HAS_BAUD_RATE_FINE_ADJUST_SUPPORT /*! * @brief Sets the UART baud rate fine adjust. (Note: Feature available on select * UART baseAddrs used in conjunction with baud rate programming) * * This function, which programs the baud rate fine adjust, is used together with * programming the baud rate modulo divisor in situations where these divisors value are known. * In this case, the user may not want to call the UART_HAL_SetBaudRate() function, as the * divisors are already known. * * @param baseAddr UART module base address. * @param baudFineAdjust Value of 5-bit field used to add more timing resolution to average * baud rate frequency is 1/32 increments. */ static inline void UART_HAL_SetBaudRateFineAdjust(uint32_t baseAddr, uint8_t baudFineAdjust) { assert(baudFineAdjust < 0x1F); BW_UART_C4_BRFA(baseAddr, baudFineAdjust); } #endif /*! * @brief Configures the number of bits per character in the UART controller. * * This function allows the user to configure the number of bits per character according to the * typedef uart_bit_count_per_char_t. * * @param baseAddr UART module base address. * @param bitCountPerChar Number of bits per char (8, 9, or 10, depending on the UART baseAddr). */ static inline void UART_HAL_SetBitCountPerChar(uint32_t baseAddr, uart_bit_count_per_char_t bitCountPerChar) { /* config 8- (M=0) or 9-bits (M=1) */ BW_UART_C1_M(baseAddr, bitCountPerChar); } /*! * @brief Configures the parity mode in the UART controller. * * This function allows the user to configure the parity mode of the UART controller to disable * it or enable it for even parity or for odd parity. * * @param baseAddr UART module base address. * @param parityMode Parity mode setting (enabled, disable, odd, even - see * parity_mode_t struct). */ static inline void UART_HAL_SetParityMode(uint32_t baseAddr, uart_parity_mode_t parityMode) { HW_UART_C1_SET(baseAddr, parityMode); } #if FSL_FEATURE_UART_HAS_STOP_BIT_CONFIG_SUPPORT /*! * @brief Configures the number of stop bits in the UART controller. * * This function allows the user to configure the number of stop bits in the UART controller * to be one or two stop bits. * * @param baseAddr UART module base address. * @param stopBitCount Number of stop bits setting (1 or 2 - see uart_stop_bit_count_t struct). * @return An error code (an unsupported setting in some UARTs) or kStatus_UART_Success. */ static inline void UART_HAL_SetStopBitCount(uint32_t baseAddr, uart_stop_bit_count_t stopBitCount) { BW_UART_BDH_SBNS(baseAddr, stopBitCount); } #endif /*! * @brief Configures the transmit and receive inversion control in UART controller. * * This function allows the user to invert the transmit and receive signals, independently. * This function should only be called when the UART is between transmit and receive packets. * * @param baseAddr UART module base address. * @param rxInvert Enable (true) or disable (false) receive inversion. * @param txInvert Enable (true) or disable (false) transmit inversion. */ void UART_HAL_SetTxRxInversionCmd(uint32_t baseAddr, bool rxInvertEnable, bool txInvertEnable); /*@}*/ /*! * @name UART Interrupts and DMA * @{ */ /*! * @brief Configures the UART module interrupts to enable/disable various interrupt sources. * * @param baseAddr UART module base address. * @param interrupt UART interrupt configuration data. * @param enable true: enable, false: disable. */ void UART_HAL_SetIntMode(uint32_t baseAddr, uart_interrupt_t interrupt, bool enable); /*! * @brief Returns whether the UART module interrupts is enabled/disabled. * * @param baseAddr UART module base address. * @param interrupt UART interrupt configuration data. * @return true: enable, false: disable. */ bool UART_HAL_GetIntMode(uint32_t baseAddr, uart_interrupt_t interrupt); /*! * @brief Enables or disables the tx_data_register_empty_interrupt. * * @param baseAddr UART module base address. * @param enable true: enable, false: disable. */ static inline void UART_HAL_SetTxDataRegEmptyIntCmd(uint32_t baseAddr, bool enable) { /* transmit interrupt enable for TDRE (transmit data register empty)*/ BW_UART_C2_TIE(baseAddr, (uint8_t)enable); } /*! * @brief Gets the configuration of the tx_data_register_empty_interrupt enable setting. * * @param baseAddr UART module base address. * @return setting of the interrupt enable bit. */ static inline bool UART_HAL_GetTxDataRegEmptyIntCmd(uint32_t baseAddr) { /* return interrupt enable condition of TIE */ return (bool)BR_UART_C2_TIE(baseAddr); } /*! * @brief Disables the rx_data_register_full_interrupt. * * @param baseAddr UART module base address. * @param enable true: enable, false: disable. */ static inline void UART_HAL_SetRxDataRegFullIntCmd(uint32_t baseAddr, bool enable) { /* receiver interrupt enable for receiver data register full (RDRF)*/ BW_UART_C2_RIE(baseAddr, (uint8_t)enable); } /*! * @brief Gets the configuration of the rx_data_register_full_interrupt enable setting. * * @param baseAddr UART module base address. * @return Bit setting of the interrupt enable bit. */ static inline bool UART_HAL_GetRxDataRegFullIntCmd(uint32_t baseAddr) { /* return interrupt enable condition of RIE */ return (bool)BR_UART_C2_RIE(baseAddr); } /*! * @brief Configures the UART DMA requests for the Transmitter and Receiver. * * This function allows the user to configure the transmit data register empty flag to * generate an interrupt request (default) or a DMA request. Similarly, this function * allows the user to configure the receive data register full flag to generate an interrupt * request (default) or a DMA request. * * @param baseAddr UART module base address. * @param txDmaConfig Transmit DMA request configuration setting (enable: true /disable: false). * @param rxDmaConfig Receive DMA request configuration setting (enable: true/disable: false). */ void UART_HAL_ConfigureDma(uint32_t baseAddr, bool txDmaConfig, bool rxDmaConfig); /*! * @brief Gets the UART Transmit DMA request configuration setting. * * This function returns the configuration setting of the Transmit DMA request. * * @param baseAddr UART module base address. * @return Transmit DMA request configuration setting (enable: true /disable: false). */ bool UART_HAL_IsTxdmaEnabled(uint32_t baseAddr); /*! * @brief Gets the UART Receive DMA request configuration setting. * * This function returns the configuration setting of the Receive DMA request. * * @param baseAddr UART module base address. * @return Receive DMA request configuration setting (enable: true /disable: false). */ bool UART_HAL_IsRxdmaEnabled(uint32_t baseAddr); /*! * @brief Get UART tx/rx data register address. * * This function is used for DMA transfer. * * @return UART tx/rx data register address. */ static inline uint32_t UART_HAL_GetDataRegAddr(uint32_t baseAddr) { return (uint32_t)HW_UART_D_ADDR(baseAddr); } /*@}*/ /*! * @name UART Transfer Functions * @{ */ /*! * @brief This function allows the user to send an 8-bit character from the UART data register. * * @param baseAddr UART module base address. * @param data The data to send of size 8-bit. */ void UART_HAL_Putchar(uint32_t baseAddr, uint8_t data); /*! * @brief This function allows the user to send a 9-bit character from the UART data register. * * @param baseAddr UART module base address. * @param data The data to send of size 9-bit. */ void UART_HAL_Putchar9(uint32_t baseAddr, uint16_t data); /*! * @brief This function gets a received 8-bit character from the UART data register. * * @param baseAddr UART module base address. * @param readData The received data read from data register of size 8-bit. */ void UART_HAL_Getchar(uint32_t baseAddr, uint8_t *readData); /*! * @brief This function gets a received 9-bit character from the UART data register. * * @param baseAddr UART module base address. * @param readData The received data read from data register of size 9-bit. */ void UART_HAL_Getchar9(uint32_t baseAddr, uint16_t *readData); #if FSL_FEATURE_UART_HAS_EXTENDED_DATA_REGISTER_FLAGS /*! * @brief Configures the UART bit 10 (if enabled) or bit 9 (if disabled) as the parity bit in the * serial transmission. * * This function configures bit 10 or bit 9 to be the parity bit. To configure bit 10 as the parity * bit, the function sets UARTx_C4[M10]; it also sets UARTx_C1[M] and UARTx_C1[PE] as required. * * @param baseAddr UART module base address. * @param enable The setting to enable (true), which configures bit 10 as the parity bit or to * disable (false), which configures bit 9 as the parity bit in the serial * transmission. */ static inline void UART_HAL_SetBit10AsParitybit(uint32_t baseAddr, bool enable) { /* to enable the parity bit as the tenth data bit, along with enabling UARTx_C4[M10] * need to also enable parity and set UARTx_C1[M] bit * assumed that the user has already set the appropriate bits */ BW_UART_C4_M10(baseAddr, enable); } /*! * @brief Gets the configuration of the UART bit 10 (if enabled) or bit 9 (if disabled) as the * parity bit in the serial transmission. * * This function returns true if bit 10 is configured as the parity bit, otherwise it returns * false if bit 9 is configured as the parity bit. * * @param baseAddr UART module base address. * @return The configuration setting of bit 10 (true), or bit 9 (false) as the * parity bit in the serial transmission. */ static inline bool UART_HAL_IsBit10SetAsParitybit(uint32_t baseAddr) { /* to see if the parity bit is set as the tenth data bit, * return value of UARTx_C4[M10] */ return BR_UART_C4_M10(baseAddr); } /*! * @brief Determines whether the UART received data word was received with noise. * * This function returns true if the received data word was received with noise. Otherwise, * it returns false indicating no noise was detected. * * @param baseAddr UART module base address. * @return The status of the NOISY bit in the UART extended data register. */ static inline bool UART_HAL_IsCurrentDatawordReceivedWithNoise(uint32_t baseAddr) { /* to see if the current dataword was received with noise, * return value of UARTx_ED[NOISY] */ return BR_UART_ED_NOISY(baseAddr); } /*! * @brief Determines whether the UART received data word was received with a parity error. * * This function returns true if the received data word was received with a parity error. * Otherwise, it returns false indicating no parity error was detected. * * @param baseAddr UART module base address. * @return The status of the PARITYE (parity error) bit in the UART extended data register. */ static inline bool UART_HAL_IsCurrentDatawordReceivedWithParityerror(uint32_t baseAddr) { /* to see if the current dataword was received with parity error, * return value of UARTx_ED[PARITYE] */ return BR_UART_ED_PARITYE(baseAddr); } #endif /* FSL_FEATURE_UART_HAS_EXTENDED_DATA_REGISTER_FLAGS*/ /*@}*/ /*! * @name UART Special Feature Configurations * @{ */ /*! * @brief Configures the UART to either operate or cease to operate in WAIT mode. * * The function configures the UART to either operate or cease to operate when WAIT mode is * entered. * * @param baseAddr UART module base address. * @param mode The UART WAIT mode operation - operates or ceases to operate in WAIT mode. */ static inline void UART_HAL_SetWaitModeOperation(uint32_t baseAddr, uart_operation_config_t mode) { /*In CPU wait mode: 0 - uart is enabled; 1 - uart is disabled */ BW_UART_C1_UARTSWAI(baseAddr, mode); } /*! * @brief Determines if the UART operates or ceases to operate in WAIT mode. * * This function returns kUartOperates if the UART has been configured to operate in WAIT mode. * Else it returns KUartStops if the UART has been configured to cease-to-operate in WAIT mode. * * @param baseAddr UART module base address. * @return The UART WAIT mode operation configuration, returns either kUartOperates or KUartStops. */ static inline uart_operation_config_t UART_HAL_GetWaitModeOperation(uint32_t baseAddr) { /*In CPU wait mode: 0 - uart is enabled; 1 - uart is disabled */ return (uart_operation_config_t)BR_UART_C1_UARTSWAI(baseAddr); } /*! * @brief Configures the UART loopback operation. * * This function enables or disables the UART loopback operation. * * @param baseAddr UART module base address. * @param enable The UART loopback mode configuration, either disabled (false) or enabled (true). */ static inline void UART_HAL_SetLoopCmd(uint32_t baseAddr, bool enable) { BW_UART_C1_LOOPS(baseAddr, enable); } /*! * @brief Configures the UART single-wire operation. * * This function enables or disables the UART single-wire operation. * In some UART baseAddrs it is required that the transmitter/receiver be disabled * before calling this function. * This may be applied to all UARTs to ensure safe operation. * * @param baseAddr UART module base address. * @param enable The UART single-wire mode configuration, either disabled (false) or enabled (true). */ static inline void UART_HAL_SetReceiverSource(uint32_t baseAddr, uart_receiver_source_t source) { BW_UART_C1_RSRC(baseAddr, source); } /*! * @brief Configures the UART transmit direction while in single-wire mode. * * This function configures the transmitter direction when the UART is configured for single-wire * operation. * * @param baseAddr UART module base address. * @param direction The UART single-wire mode transmit direction configuration of type * uart_singlewire_txdir_t (either kUartSinglewireTxdirIn or * kUartSinglewireTxdirOut. */ static inline void UART_HAL_SetTransmitterDir(uint32_t baseAddr, uart_singlewire_txdir_t direction) { /* configure UART transmit direction (input or output) when in single-wire mode * it is assumed UART is in single-wire mode */ BW_UART_C3_TXDIR(baseAddr, direction); } /*! * @brief Places the UART receiver in standby mode. * * This function, when called, places the UART receiver into standby mode. * In some UART baseAddrs, there are conditions that must be met before placing Rx in standby mode. * Before placing UART in standby, determine if receiver is set to * wake on idle, and if receiver is already in idle state. * NOTE: RWU should only be set with C1[WAKE] = 0 (wakeup on idle) if the channel is currently * not idle. * This can be determined by the S2[RAF] flag. If set to wake up FROM an IDLE event and the channel * is already idle, it is possible that the UART will discard data because data must be received * (or a LIN break detect) after an IDLE is detected before IDLE is allowed to be reasserted. * * @param baseAddr UART module base address. * @return Error code or kStatus_UART_Success. */ uart_status_t UART_HAL_PutReceiverInStandbyMode(uint32_t baseAddr); /*! * @brief Places the UART receiver in normal mode (disable standby mode operation). * * This function, when called, places the UART receiver into normal mode and out of * standby mode. * * @param baseAddr UART module base address. */ static inline void UART_HAL_PutReceiverInNormalMode(uint32_t baseAddr) { /* clear the RWU bit to place receiver into normal mode (disable standby mode)*/ HW_UART_C2_CLR(baseAddr, BM_UART_C2_RWU); } /*! * @brief Determines if the UART receiver is currently in standby mode. * * This function determines the state of the UART receiver. If it returns true, this means * that the UART receiver is in standby mode; if it returns false, the UART receiver * is in normal mode. * * @param baseAddr UART module base address. * @return The UART receiver is in normal mode (false) or standby mode (true). */ static inline bool UART_HAL_IsReceiverInStandby(uint32_t baseAddr) { /* return the RWU bit setting (0 - normal more, 1 - standby)*/ return BR_UART_C2_RWU(baseAddr); } /*! * @brief Selects the UART receiver wakeup method (idle-line or address-mark) from standby mode. * * This function configures the wakeup method of the UART receiver from standby mode. The options * are idle-line wake or address-mark wake. * * @param baseAddr UART module base address. * @param method The UART receiver wakeup method options: kUartIdleLineWake - Idle-line wake or * kUartAddrMarkWake - address-mark wake. */ static inline void UART_HAL_SetReceiverWakeupMethod(uint32_t baseAddr, uart_wakeup_method_t method) { /* configure the WAKE bit for idle line wake or address mark wake */ BW_UART_C1_WAKE(baseAddr, method); } /*! * @brief Gets the UART receiver wakeup method (idle-line or address-mark) from standby mode. * * This function returns how the UART receiver is configured to wake from standby mode. The * wake method options that can be returned are kUartIdleLineWake or kUartAddrMarkWake. * * @param baseAddr UART module base address. * @return The UART receiver wakeup from standby method, false: kUartIdleLineWake (idle-line wake) * or true: kUartAddrMarkWake (address-mark wake). */ static inline uart_wakeup_method_t UART_HAL_GetReceiverWakeupMethod(uint32_t baseAddr) { /* get configuration of the WAKE bit for idle line wake or address mark wake */ return (uart_wakeup_method_t)BR_UART_C1_WAKE(baseAddr); } /*! * @brief Configures the operation options of the UART idle line detect. * * This function allows the user to configure the UART idle-line detect operation. There are two * separate operations for the user to configure, the idle line bit-count start and the receive * wake up affect on IDLE status bit. The user will pass in a structure of type * uart_idle_line_config_t. * * @param baseAddr UART module base address. * @param idleLine Idle bit count start: 0 - after start bit (default), 1 - after stop bit * @param rxWakeIdleDetect Receiver Wake Up Idle Detect. IDLE status bit operation during receive * standby. Controls whether idle character that wakes up receiver will also set IDLE status * bit. 0 - IDLE status bit doesn't get set (default), 1 - IDLE status bit gets set */ void UART_HAL_ConfigIdleLineDetect(uint32_t baseAddr, uint8_t idleLine, uint8_t rxWakeIdleDetect); /*! * @brief Configures the UART break character transmit length. * * This function allows the user to configure the UART break character transmit length. Refer to * the typedef uart_break_char_length_t for setting options. * In some UART baseAddrs it is required that the transmitter be disabled before calling * this function. This may be applied to all UARTs to ensure safe operation. * * @param baseAddr UART module base address. * @param length The UART break character length setting of type uart_break_char_length_t, either a * minimum 10-bit times or a minimum 13-bit times. */ static inline void UART_HAL_SetBreakCharTransmitLength(uint32_t baseAddr, uart_break_char_length_t length) { /* Configure BRK13 - Break Character transmit length configuration * UART break character length setting: * 0 - minimum 10-bit times (default), * 1 - minimum 13-bit times */ BW_UART_S2_BRK13(baseAddr, length); } /*! * @brief Configures the UART break character detect length. * * This function allows the user to configure the UART break character detect length. Refer to * the typedef uart_break_char_length_t for setting options. * * @param baseAddr UART module base address. * @param length The UART break character length setting of type uart_break_char_length_t, either a * minimum 10-bit times or a minimum 13-bit times. */ static inline void UART_HAL_SetBreakCharDetectLength(uint32_t baseAddr, uart_break_char_length_t length) { /* Configure LBKDE - Break Character detect length configuration * UART break character length setting: * 0 - minimum 10-bit times (default), * 1 - minimum 13-bit times */ BW_UART_S2_LBKDE(baseAddr, length); } /*! * @brief Configures the UART transmit send break character operation. * * This function allows the user to queue a UART break character to send. If true is passed into * the function, then a break character is queued for transmission. A break character will * continuously be queued until this function is called again when a false is passed into this * function. * * @param baseAddr UART module base address. * @param enable If false, the UART normal/queue break character setting is disabled, which * configures the UART for normal transmitter operation. If true, a break * character is queued for transmission. */ static inline void UART_HAL_SetBreakCharCmd(uint32_t baseAddr, bool enable) { BW_UART_C2_SBK(baseAddr, enable); } /*! * @brief Configures the UART match address mode control operation. (Note: Feature available on * select UART baseAddrs) * * The function allows the user to configure the UART match address control operation. The user * has the option to enable the match address mode and to program the match address value. There * are two match address modes, each with its own enable and programmable match address value. * * @param baseAddr UART module base address. * @param matchAddrMode1 If true, this enables match address mode 1 (MAEN1), where false disables. * @param matchAddrMode2 If true, this enables match address mode 2 (MAEN2), where false disables. * @param matchAddrValue1 The match address value to program for match address mode 1. * @param matchAddrValue2 The match address value to program for match address mode 2. */ void UART_HAL_SetMatchAddress(uint32_t baseAddr, bool matchAddrMode1, bool matchAddrMode2, uint8_t matchAddrValue1, uint8_t matchAddrValue2); #if FSL_FEATURE_UART_HAS_BIT_ORDER_SELECT /*! * @brief Configures the UART to send data MSB first * (Note: Feature available on select UART baseAddrs) * * The function allows the user to configure the UART to send data MSB first or LSB first. * In some UART baseAddrs it is required that the transmitter/receiver be disabled * before calling this function. * This may be applied to all UARTs to ensure safe operation. * * @param baseAddr UART module base address. * @param enable This configures send MSB first mode configuration. If true, the data is sent MSB * first; if false, it is sent LSB first. */ static inline void UART_HAL_SetSendMsbFirstCmd(uint32_t baseAddr, bool enable) { BW_UART_S2_MSBF(baseAddr, enable); } #endif #if FSL_FEATURE_UART_HAS_MODEM_SUPPORT /*! * @brief Enables the UART receiver request-to-send functionality. * * This function allows the user to enable the UART receiver request-to-send (RTS) functionality. * By enabling, it allows the RTS output to control the CTS input of the transmitting device to * prevent receiver overrun. RTS is deasserted if the number of characters in the receiver data * register (FIFO) is equal to or greater than RWFIFO[RXWATER]. RTS is asserted when the * number of characters in the receiver data register (FIFO) is less than RWFIFO[RXWATER]. * Do not set both RXRTSE and TXRTSE. * * @param baseAddr UART module base address. * @param enable Enable or disable receiver rts. */ static inline void UART_HAL_SetReceiverRtsCmd(uint32_t baseAddr, bool enable) { /* Set RXRTSE */ BW_UART_MODEM_RXRTSE(baseAddr, enable); } /*! * @brief Enables the UART transmitter request-to-send functionality. * * This function allows the user to enable the UART transmitter request-to-send (RTS) functionality. * When enabled, it allows the UART to control the RTS assertion before and after a transmission * such that when a character is placed into an empty transmitter data buffer, RTS * asserts one bit time before the start bit is transmitted. RTS deasserts one bit time after all * characters in the transmitter data buffer and shift register are completely sent, including * the last stop bit. * * @param baseAddr UART module base address. * @param enable Enable or disable transmitter RTS. */ static inline void UART_HAL_SetTransmitterRtsCmd(uint32_t baseAddr, bool enable) { /* Set TXRTSE */ BW_UART_MODEM_TXRTSE(baseAddr, enable); } /*! * @brief Configures the UART transmitter RTS polarity. * * This function allows the user configure the transmitter RTS polarity to be either active low * or active high. * * @param baseAddr UART module base address. * @param polarity The UART transmitter RTS polarity setting (false - active low, * true - active high). */ static inline void UART_HAL_SetTransmitterRtsPolarityMode(uint32_t baseAddr, bool polarity) { /* Configure the transmitter rts polarity: 0=active low, 1=active high */ BW_UART_MODEM_TXRTSPOL(baseAddr, polarity); } /*! * @brief Enables the UART transmitter clear-to-send functionality. * * This function allows the user to enable the UART transmitter clear-to-send (CTS) functionality. * When enabled, the transmitter checks the state of CTS each time it is ready to send a character. * If CTS is asserted, the character is sent. If CTS is deasserted, the signal TXD remains in * the mark state and transmission is delayed until CTS is asserted. Changes in CTS as a * character is being sent do not affect its transmission. * * @param baseAddr UART module base address. * @param enable Enable or disable transmitter CTS. */ static inline void UART_HAL_SetTransmitterCtsCmd(uint32_t baseAddr, bool enable) { /* Set TXCTSE */ BW_UART_MODEM_TXCTSE(baseAddr, enable); } #endif /* FSL_FEATURE_UART_HAS_MODEM_SUPPORT*/ #if FSL_FEATURE_UART_HAS_IR_SUPPORT /*! * @brief Configures the UART infrared operation. * * The function allows the user to enable or disable the UART infrared (IR) operation * and to configure the IR pulse width. * * @param baseAddr UART module base address. * @param enable Enable (true) or disable (false) the infrared operation. * @param pulseWidth The UART transmit narrow pulse width setting of type uart_ir_tx_pulsewidth_t. */ void UART_HAL_SetInfraredOperation(uint32_t baseAddr, bool enable, uart_ir_tx_pulsewidth_t pulseWidth); #endif /* FSL_FEATURE_UART_HAS_IR_SUPPORT*/ /*@}*/ /*! * @name UART Status Flags * @{ */ /*! * @brief Gets all UART status flag states. * * @param baseAddr UART module base address. * @param statusFlag Status flag name. */ bool UART_HAL_GetStatusFlag(uint32_t baseAddr, uart_status_flag_t statusFlag); /*! * @brief Gets the UART Transmit data register empty flag. * * This function returns the state of the UART Transmit data register empty flag. * * @param baseAddr UART module base address. * @return The status of Transmit data register empty flag, which is set when transmit buffer * is empty. */ static inline bool UART_HAL_IsTxDataRegEmpty(uint32_t baseAddr) { /* return status condition of TDRE flag */ return BR_UART_S1_TDRE(baseAddr); } /*! * @brief Gets the UART Transmission complete flag. * * This function returns the state of the UART Transmission complete flag. * * @param baseAddr UART module base address. * @return The status of Transmission complete flag, which is set when the transmitter is idle * (transmission activity complete). */ static inline bool UART_HAL_IsTxComplete(uint32_t baseAddr) { /* return status condition of TC flag */ return BR_UART_S1_TC(baseAddr); } /*! * @brief Gets the UART Receive data register full flag. * * This function returns the state of the UART Receive data register full flag. * * @param baseAddr UART module base address. * @return The status of Receive data register full flag, which is set when the receive data buffer * is full. */ static inline bool UART_HAL_IsRxDataRegFull(uint32_t baseAddr) { /* return status condition of RDRF flag */ return BR_UART_S1_RDRF(baseAddr); } /*! * @brief Clears an individual and specific UART status flag. * * This function allows the user to clear an individual and specific UART status flag. Refer to * structure definition uart_status_flag_t for list of status bits. * * @param baseAddr UART module base address. * @param statusFlag The desired UART status flag to clear. * @return An error code or kStatus_UART_Success. */ uart_status_t UART_HAL_ClearStatusFlag(uint32_t baseAddr, uart_status_flag_t statusFlag); /*! * @brief Clears all UART status flags. * * This function tries to clear all of the UART status flags. In some cases, some of the status * flags may not get cleared because the condition that set the flag may still exist. * * @param baseAddr UART module base address. */ void UART_HAL_ClearAllNonAutoclearStatusFlags(uint32_t baseAddr); /*@}*/ /*! * @name UART FIFO Configurations * @{ */ #if FSL_FEATURE_UART_HAS_FIFO /*! * @brief Enables or disable the UART transmit FIFO. * * This function allows the user to enable or disable the UART transmit FIFO. * It is required that the transmitter/receiver be disabled before calling this function * when the FIFO is empty. * Additionally, TXFLUSH and RXFLUSH commands should be issued after calling this function. * * @param baseAddr UART module base address. * @param enable Enable or disable Tx FIFO. * @return Error code if it is detected that the transmitter or receiver is enabled or * kStatus_UART_Success. */ uart_status_t UART_HAL_SetTxFifoCmd(uint32_t baseAddr, bool enable); /*! * @brief Enables or disable the UART receive FIFO. * * This function allows the user to enable or disable the UART receive FIFO. * It is required that the transmitter/receiver be disabled before calling this function * when the FIFO is empty. * Additionally, TXFLUSH and RXFLUSH commands should be issued after calling this function. * * @param baseAddr UART module base address. * @param enable Enable or disable Rx FIFO. * @return Error code if it is detected that the transmitter or receiver is enabled or * kStatus_UART_Success. */ uart_status_t UART_HAL_SetRxFifoCmd(uint32_t baseAddr, bool enable); /*! * @brief Gets the size of the UART transmit FIFO. * * This function returns the size (number of entries) supported in the UART transmit FIFO for * a particular module baseAddr. * * @param baseAddr UART module base address. * @return The UART transmit FIFO size as follows: * 0x0: 1 data word; 0x1: 4 data words; 0x2: 8 data words; 0x3: 16 data words * 0x4: 32 data words; 0x5: 64 data words; 0x6: 128 data words; 0x7: reserved */ static inline uint8_t UART_HAL_GetTxFifoSize(uint32_t baseAddr) { return BR_UART_PFIFO_TXFIFOSIZE(baseAddr); } /*! * @brief Gets the size of the UART receive FIFO. * * This function returns the size (number of entries) supported in the UART receive FIFO for * a particular module baseAddr. * * @param baseAddr UART module base address. * @return The receive FIFO size as follows: * 0x0: 1 data word; 0x1: 4 data words; 0x2: 8 data words; 0x3: 16 data words * 0x4: 32 data words; 0x5: 64 data words; 0x6: 128 data words; 0x7: reserved */ static inline uint8_t UART_HAL_GetRxFifoSize(uint32_t baseAddr) { return BR_UART_PFIFO_RXFIFOSIZE(baseAddr); } /*! * @brief Flushes the UART transmit FIFO. * * This function allows the user to flush the UART transmit FIFO for a particular module baseAddr. * Flushing the FIFO may result in data loss. * It is recommended that the transmitter be disabled before calling this function. * * @param baseAddr UART module base address. * @return Error code if it is detected that the transmitter or receiver is enabled or * kStatus_UART_Success. */ uart_status_t UART_HAL_FlushTxFifo(uint32_t baseAddr); /*! * @brief Flushes the UART receive FIFO. * * This function allows the user to flush the UART receive FIFO for a particular module baseAddr. * Flushing the FIFO may result in data loss. * It is recommended that the receiver be disabled before calling this function. * * @param baseAddr UART module base address. * @return Error code if it is detected that the transmitter or receiver is enabled or * kStatus_UART_Success. */ uart_status_t UART_HAL_FlushRxFifo(uint32_t baseAddr); /*! * @brief Gets the UART transmit FIFO empty status state. * * The function returns the state of the transmit FIFO empty status state, but does not take into * account data in the shift register. * * @param baseAddr UART module base address. * @return The UART transmit FIFO empty status: true=empty; false=not-empty. */ static inline bool UART_HAL_IsTxFifoEmpty(uint32_t baseAddr) { return BR_UART_SFIFO_TXEMPT(baseAddr); } /*! * @brief Gets the UART receive FIFO empty status state. * * The function returns the state of the receive FIFO empty status state, but does not take into * account data in the shift register. * * @param baseAddr UART module base address. * @return The UART receive FIFO empty status: true=empty; false=not-empty. */ static inline bool UART_HAL_IsRxFifoEmpty(uint32_t baseAddr) { return BR_UART_SFIFO_RXEMPT(baseAddr); } /*! * @brief Sets the UART transmit FIFO watermark value. * * Programming the transmit watermark should be done when UART the transmitter is disabled * and the value must be set less than the size obtained from UART_HAL_GetTxFifoSize. * * @param baseAddr UART module base address. * @param watermark The UART transmit watermark value to be programmed. * @return Error code if transmitter is enabled or kStatus_UART_Success. */ uart_status_t UART_HAL_SetTxFifoWatermark(uint32_t baseAddr, uint8_t watermark); /*! * @brief Gets the UART transmit FIFO watermark value. * * @param baseAddr UART module base address. * @return The value currently programmed for the UART transmit watermark. */ static inline uint8_t UART_HAL_GetTxFifoWatermark(uint32_t baseAddr) { /* get watermark*/ return HW_UART_TWFIFO_RD(baseAddr); } /*! * @brief Gets the UART transmit FIFO data word count (number of words in the transmit FIFO). * * The function UART_HAL_GetTxDatawordCountInFifo excludes any data that may * be in the UART transmit shift register * * @param baseAddr UART module base address. * @return The number of data words currently in the UART transmit FIFO. */ static inline uint8_t UART_HAL_GetTxDatawordCountInFifo(uint32_t baseAddr) { /* get the current number of datawords in the FIFO*/ return HW_UART_TCFIFO_RD(baseAddr); } /*! * @brief Sets the UART receive FIFO watermark value. * * Programming the receive watermark should be done when the receiver is disabled * and the value must be set less than the size obtained from UART_HAL_GetRxFifoSize and * greater than zero. * * @param baseAddr UART module base address. * @param watermark The UART receive watermark value to be programmed. * @return Error code if receiver is enabled or kStatus_UART_Success. */ uart_status_t UART_HAL_SetRxFifoWatermark(uint32_t baseAddr, uint8_t watermark); /*! * @brief Gets the UART receive FIFO data word count (number of words in the receive FIFO). * * The function UART_HAL_GetRxDatawordCountInFifo excludes any data that may be * in the receive shift register. * * @param baseAddr UART module base address. * @return The number of data words currently in the UART receive FIFO. */ static inline uint8_t UART_HAL_GetRxDatawordCountInFifo(uint32_t baseAddr) { /* get the current number of datawords in the FIFO*/ return HW_UART_RCFIFO_RD(baseAddr); } /*! * @brief Gets the UART receive FIFO watermark value. * * @param baseAddr UART module base address. * @return The value currently programmed for the UART receive watermark. */ static inline uint8_t UART_HAL_GetRxFifoWatermark(uint32_t baseAddr) { /* get watermark*/ return HW_UART_RWFIFO_RD(baseAddr); } #endif /* FSL_FEATURE_UART_HAS_FIFO*/ /*@}*/ #if defined(__cplusplus) } #endif /*! @}*/ #endif /* __FSL_UART_HAL_H__*/ /******************************************************************************* * EOF ******************************************************************************/ ================================================ FILE: Zelig/mbed/TARGET_K64F/TARGET_Freescale/TARGET_KPSDK_MCUS/TARGET_KPSDK_CODE/hal/wdog/fsl_wdog_features.h ================================================ /* ** ################################################################### ** Version: rev. 1.0, 2014-05-14 ** Build: b140515 ** ** Abstract: ** Chip specific module features. ** ** Copyright: 2014 Freescale Semiconductor, Inc. ** All rights reserved. ** ** Redistribution and use in source and binary forms, with or without modification, ** are permitted provided that the following conditions are met: ** ** o Redistributions of source code must retain the above copyright notice, this list ** of conditions and the following disclaimer. ** ** o Redistributions in binary form must reproduce the above copyright notice, this ** list of conditions and the following disclaimer in the documentation and/or ** other materials provided with the distribution. ** ** o Neither the name of Freescale Semiconductor, Inc. nor the names of its ** contributors may be used to endorse or promote products derived from this ** software without specific prior written permission. ** ** THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ** ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED ** WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE ** DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT 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. ** ** http: www.freescale.com ** mail: support@freescale.com ** ** Revisions: ** - rev. 1.0 (2014-05-14) ** Customer release. ** ** ################################################################### */ #if !defined(__FSL_WDOG_FEATURES_H__) #define __FSL_WDOG_FEATURES_H__ #if defined(CPU_MK02FN128VFM10) || defined(CPU_MK02FN64VFM10) || defined(CPU_MK02FN128VLF10) || defined(CPU_MK02FN64VLF10) || \ defined(CPU_MK02FN128VLH10) || defined(CPU_MK02FN64VLH10) || defined(CPU_MK20DX128VMP5) || defined(CPU_MK20DN128VMP5) || \ defined(CPU_MK20DX64VMP5) || defined(CPU_MK20DN64VMP5) || defined(CPU_MK20DX32VMP5) || defined(CPU_MK20DN32VMP5) || \ defined(CPU_MK20DX128VLH5) || defined(CPU_MK20DN128VLH5) || defined(CPU_MK20DX64VLH5) || defined(CPU_MK20DN64VLH5) || \ defined(CPU_MK20DX32VLH5) || defined(CPU_MK20DN32VLH5) || defined(CPU_MK20DX128VFM5) || defined(CPU_MK20DN128VFM5) || \ defined(CPU_MK20DX64VFM5) || defined(CPU_MK20DN64VFM5) || defined(CPU_MK20DX32VFM5) || defined(CPU_MK20DN32VFM5) || \ defined(CPU_MK20DX128VFT5) || defined(CPU_MK20DN128VFT5) || defined(CPU_MK20DX64VFT5) || defined(CPU_MK20DN64VFT5) || \ defined(CPU_MK20DX32VFT5) || defined(CPU_MK20DN32VFT5) || defined(CPU_MK20DX128VLF5) || defined(CPU_MK20DN128VLF5) || \ defined(CPU_MK20DX64VLF5) || defined(CPU_MK20DN64VLF5) || defined(CPU_MK20DX32VLF5) || defined(CPU_MK20DN32VLF5) || \ defined(CPU_MK22FN128VDC10) || defined(CPU_MK22FN128VLH10) || defined(CPU_MK22FN128VLL10) || defined(CPU_MK22FN128VMP10) || \ defined(CPU_MK22FN256VDC12) || defined(CPU_MK22FN256VLH12) || defined(CPU_MK22FN256VLL12) || defined(CPU_MK22FN256VMP12) || \ defined(CPU_MK22FN512VDC12) || defined(CPU_MK22FN512VLH12) || defined(CPU_MK22FN512VLL12) || defined(CPU_MK24FN1M0VDC12) || \ defined(CPU_MK24FN1M0VLL12) || defined(CPU_MK24FN1M0VLQ12) || defined(CPU_MK24FN256VDC12) || defined(CPU_MK63FN1M0VLQ12) || \ defined(CPU_MK63FN1M0VMD12) || defined(CPU_MK64FX512VDC12) || defined(CPU_MK64FN1M0VDC12) || defined(CPU_MK64FX512VLL12) || \ defined(CPU_MK64FN1M0VLL12) || defined(CPU_MK64FX512VLQ12) || defined(CPU_MK64FN1M0VLQ12) || defined(CPU_MK64FX512VMD12) || \ defined(CPU_MK64FN1M0VMD12) || defined(CPU_MK65FN2M0CAC18) || defined(CPU_MK65FX1M0CAC18) || defined(CPU_MK65FN2M0VMI18) || \ defined(CPU_MK65FX1M0VMI18) || defined(CPU_MK66FN2M0VLQ18) || defined(CPU_MK66FX1M0VLQ18) || defined(CPU_MK66FN2M0VMD18) || \ defined(CPU_MK66FX1M0VMD18) || defined(CPU_MK70FN1M0VMF12) || defined(CPU_MK70FX512VMF12) || defined(CPU_MK70FN1M0VMF15) || \ defined(CPU_MK70FX512VMF15) || defined(CPU_MK70FN1M0VMJ12) || defined(CPU_MK70FX512VMJ12) || defined(CPU_MK70FN1M0VMJ15) || \ defined(CPU_MK70FX512VMJ15) || defined(CPU_MKV30F128VFM10) || defined(CPU_MKV30F64VFM10) || defined(CPU_MKV30F128VLF10) || \ defined(CPU_MKV30F64VLF10) || defined(CPU_MKV30F128VLH10) || defined(CPU_MKV30F64VLH10) || defined(CPU_MKV31F128VLH10) || \ defined(CPU_MKV31F128VLL10) || defined(CPU_MKV31F256VLH12) || defined(CPU_MKV31F256VLL12) || defined(CPU_MKV31F512VLH12) || \ defined(CPU_MKV31F512VLL12) || defined(CPU_MKV40F128VLH15) || defined(CPU_MKV40F128VLL15) || defined(CPU_MKV40F256VLH15) || \ defined(CPU_MKV40F256VLL15) || defined(CPU_MKV40F64VLH15) || defined(CPU_MKV43F128VLH15) || defined(CPU_MKV43F128VLL15) || \ defined(CPU_MKV43F64VLH15) || defined(CPU_MKV44F128VLH15) || defined(CPU_MKV44F128VLL15) || defined(CPU_MKV44F64VLH15) || \ defined(CPU_MKV45F128VLH15) || defined(CPU_MKV45F128VLL15) || defined(CPU_MKV45F256VLH15) || defined(CPU_MKV45F256VLL15) || \ defined(CPU_MKV46F128VLH15) || defined(CPU_MKV46F128VLL15) || defined(CPU_MKV46F256VLH15) || defined(CPU_MKV46F256VLL15) /* @brief Watchdog is available. */ #define FSL_FEATURE_WDOG_HAS_WATCHDOG (1) #else #error "No valid CPU defined!" #endif #endif /* __FSL_WDOG_FEATURES_H__ */ /******************************************************************************* * EOF ******************************************************************************/ ================================================ FILE: Zelig/mbed/TARGET_K64F/TARGET_Freescale/TARGET_KPSDK_MCUS/TARGET_KPSDK_CODE/hal/wdog/fsl_wdog_hal.h ================================================ /* * Copyright (c) 2013 - 2014, Freescale Semiconductor, Inc. * All rights reserved. * * Redistribution and use in source and binary forms, with or without modification, * are permitted provided that the following conditions are met: * * o Redistributions of source code must retain the above copyright notice, this list * of conditions and the following disclaimer. * * o Redistributions in binary form must reproduce the above copyright notice, this * list of conditions and the following disclaimer in the documentation and/or * other materials provided with the distribution. * * o Neither the name of Freescale Semiconductor, Inc. nor the names of its * contributors may be used to endorse or promote products derived from this * software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT 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. */ #ifndef __FSL_WDOG_HAL_H__ #define __FSL_WDOG_HAL_H__ #include #include #include #include "fsl_wdog_features.h" #include "fsl_device_registers.h" /*! * @addtogroup wdog_hal * @{ */ /******************************************************************************* * Definitions *******************************************************************************/ #define WDOG_UNLOCK_VALUE_HIGH (0xC520U) #define WDOG_UNLOCK_VALUE_LOW (0xD928U) #define WDOG_REFRESH_VALUE_HIGH (0xA602U) #define WDOG_REFRESH_VALUE_LOW (0xB480U) /*! @brief Watchdog clock source selection.*/ typedef enum _wdog_clock_source { kWdogClockSourceLpoClock = 0x0U, /*!< Clock source is LPO clock */ kWdogClockSourceBusClock = 0x1U /*!< Clock source is Bus clock */ } wdog_clock_source_t; /*! @brief Define the selection of the clock prescaler*/ typedef enum _wdog_clock_prescaler_value { kWdogClockPrescalerValueDevide1 = 0x0U, /*!< Divided by 1 */ kWdogClockPrescalerValueDevide2 = 0x1U, /*!< Divided by 2 */ kWdogClockPrescalerValueDevide3 = 0x2U, /*!< Divided by 3 */ kWdogClockPrescalerValueDevide4 = 0x3U, /*!< Divided by 4 */ kWdogClockPrescalerValueDevide5 = 0x4U, /*!< Divided by 5 */ kWdogClockPrescalerValueDevide6 = 0x5U, /*!< Divided by 6 */ kWdogClockPrescalerValueDevide7 = 0x6U, /*!< Divided by 7 */ kWdogClockPrescalerValueDevide8 = 0x7U /*!< Divided by 8 */ } wdog_clock_prescaler_value_t; /*! @brief Define the common configure */ typedef union _wdog_common_config { uint32_t U; struct CommonConfig { uint32_t wdogEnable:1; /*!< Enable configure, 1 means enable WDOG */ uint32_t clockSource:1; /*!< Clock source */ uint32_t interruptEnable:1; /*!< WDOG interrupt configure, 1 means enable interrupt */ uint32_t windowModeEnable:1; /*!< Window mode configure, 1 means enable window mode */ uint32_t updateRegisterEnable:1; /*!< 1 means WDOG register can reconfigure by unlock */ uint32_t workInDebugModeEnable:1; /*!< 1 means WDOG works while CPU in Debug mode */ uint32_t workInStopModeEnable:1; /*!< 1 means WDOG works while CPU in Debug mode */ uint32_t workInWaitModeEnable:1; /*!< 1 means WDOG works while CPU in Debug mode */ uint32_t reserved0:1; /*!< Reserved */ uint32_t reserved1:1; /*!< Reserved */ uint32_t testWdog:1; /*!< WDOG enable configure */ uint32_t testSelect:1; /*!< 0 means quick test, 1 means byte test */ uint32_t byteSelect:2; /*!< Test byte select */ uint32_t disableTestWdog:1; /*!< 1 means WDOG test mode is disabled */ uint32_t reserved2:1; /*!< Reserved */ uint32_t reserved3:16; /*!< Reserved */ } commonConfig; } wdog_common_config; /******************************************************************************* * API *******************************************************************************/ #if defined(__cplusplus) extern "C" { #endif /*! * @name Watchdog HAL. * @{ */ /*! * @brief Sets the WDOG common configure. * * This function is used to set the WDOG common configure. * Make sure WDOG registers are unlocked by the WDOG_HAL_Unlock, the WCT window is still open and * the WDOG_STCTRLH register has not been written in this WCT while this function is called. * Make sure that the WDOG_STCTRLH.ALLOWUPDATE is 1 which means that the register update is enabled. * The common configuration is controlled by the WDOG_STCTRLH. This is a write-once register and this interface * is used to set all field of the WDOG_STCTRLH registers at the same time. * If only one field needs to be set, the API can be used. These API write to the WDOG_STCTRLH register: * #WDOG_HAL_Enable,#WDOG_HAL_Disable,#WDOG_HAL_SetIntCmd,#WDOG_HAL_SetClockSourceMode,#WDOG_HAL_SetWindowModeCmd, * #WDOG_HAL_SetRegisterUpdateCmd,#WDOG_HAL_SetWorkInDebugModeCmd,#WDOG_HAL_SetWorkInStopModeCmd, * #WDOG_HAL_SetWorkInWaitModeCmd * * @param baseAddr The WDOG peripheral base address * @param commonConfig The common configure of the WDOG */ static inline void WDOG_HAL_SetCommonConfig(uint32_t baseAddr, wdog_common_config commonConfig) { HW_WDOG_STCTRLH_WR(baseAddr,(uint16_t)commonConfig.U); } /*! * @brief Enables the Watchdog module. * * This function enables the WDOG. * Make sure that the WDOG registers are unlocked by the WDOG_HAL_Unlock, that the WCT window is still open and that * the WDOG_STCTRLH register has not been written in this WCT while this function is called. * * @param baseAddr The WDOG peripheral base address */ static inline void WDOG_HAL_Enable(uint32_t baseAddr) { BW_WDOG_STCTRLH_WDOGEN(baseAddr, (uint8_t)true); } /*! * @brief Disables the Watchdog module. * * This function disables the WDOG. * Make sure that the WDOG registers are unlocked by the WDOG_HAL_Unlock, that the WCT window is still open and that * the WDOG_STCTRLH register has not been written in this WCT while this function is called. * * @param baseAddr The WDOG peripheral base address */ static inline void WDOG_HAL_Disable(uint32_t baseAddr) { BW_WDOG_STCTRLH_WDOGEN(baseAddr, (uint8_t)false); } /*! * @brief Checks whether the WDOG is enabled. * * This function checks whether the WDOG is enabled. * * @param baseAddr The WDOG peripheral base address * @return false means WDOG is disabled, true means WODG is enabled. * */ static inline bool WDOG_HAL_IsEnabled(uint32_t baseAddr) { return (bool)BR_WDOG_STCTRLH_WDOGEN(baseAddr); } /*! * @brief Enables and disables the Watchdog interrupt. * * This function enables or disables the WDOG interrupt. * Make sure that the WDOG registers are unlocked by the WDOG_HAL_Unlock, that the WCT window is still open and that * the WDOG_STCTRLH register has not been written in this WCT while this function is called. * Make sure WDOG_STCTRLH.ALLOWUPDATE is 1 which means register update is enabled. * * @param baseAddr The WDOG peripheral base address * @param enable false means disable watchdog interrupt and true means enable watchdog interrupt. */ static inline void WDOG_HAL_SetIntCmd(uint32_t baseAddr, bool enable) { BW_WDOG_STCTRLH_IRQRSTEN(baseAddr, (uint8_t)enable); } /*! * @brief Checks whether the WDOG interrupt is enabled. * * This function checks whether the WDOG interrupt is enabled. * * @param baseAddr The WDOG peripheral base address * @return false means interrupt is disabled, true means interrupt is enabled. */ static inline bool WDOG_HAL_GetIntCmd(uint32_t baseAddr) { return (bool)BR_WDOG_STCTRLH_IRQRSTEN(baseAddr); } /*! * @brief Sets the Watchdog clock Source. * * This function sets the WDOG clock source. There are two clock sources that can be used: * the LPO clock and the bus clock. * Make sure that the WDOG registers are unlocked by the WDOG_HAL_Unlock, that the WCT window is still open and that * the WDOG_STCTRLH register has not been written in this WCT while this function is called. * Make sure WDOG_STCTRLH.ALLOWUPDATE is 1 which means register update is enabled. * * @param baseAddr The WDOG peripheral base address * @param clockSource watchdog clock source, see #wdog_clock_source_t. */ static inline void WDOG_HAL_SetClockSourceMode(uint32_t baseAddr, wdog_clock_source_t clockSource) { BW_WDOG_STCTRLH_CLKSRC(baseAddr, (uint8_t)clockSource); } /*! * @brief Gets the Watchdog clock Source. * * This function gets the WDOG clock source. There are two clock sources that can be used: * the LPO clock and the bus clock. * A Clock Switching Delay time is about 2 clock A cycles plus 2 * clock B, where clock A and B are the two input clocks to the clock mux. * * @param baseAddr The WDOG peripheral base address * @return watchdog clock source, see #wdog_clock_source_t. */ static inline wdog_clock_source_t WDOG_HAL_GetClockSourceMode(uint32_t baseAddr) { return (wdog_clock_source_t)BR_WDOG_STCTRLH_CLKSRC(baseAddr); } /*! * @brief Enables and disables the Watchdog window mode. * * This function configures the WDOG window mode. * Make sure WDOG registers are unlocked by the WDOG_HAL_Unlock, that the WCT window is still open and that * the WDOG_STCTRLH register has not been written in this WCT while this function is called. * Make sure WDOG_STCTRLH.ALLOWUPDATE is 1 which means register update is enabled. * * @param baseAddr The WDOG peripheral base address * @param enable false means disable watchdog window mode. true means enable watchdog window mode. */ static inline void WDOG_HAL_SetWindowModeCmd(uint32_t baseAddr, bool enable) { BW_WDOG_STCTRLH_WINEN(baseAddr, (uint8_t)enable); } /*! * @brief Checks whether the window mode is enabled. * * This function checks whether the WDOG window mode is enabled. * * @param baseAddr The WDOG peripheral base address * @return false means window mode is disabled, true means window mode is enabled. */ static inline bool WDOG_HAL_GetWindowModeCmd(uint32_t baseAddr) { return (bool)BR_WDOG_STCTRLH_WINEN(baseAddr); } /*! * @brief Enables and disables the Watchdog write-once-only register update. * * This function configures the WDOG register update feature. If disabled, it means that * all WDOG registers is never written again unless Power On Reset. * Make sure WDOG registers are unlocked by the WDOG_HAL_Unlock, that the WCT window is still open and that * the WDOG_STCTRLH register has not been written in this WCT while this function is called. * Make sure WDOG_STCTRLH.ALLOWUPDATE is 1 which means register update is enabled. * * @param baseAddr The WDOG peripheral base address * @param enable false means disable watchdog write-once-only register update. * true means enable watchdog write-once-only register update. */ static inline void WDOG_HAL_SetRegisterUpdateCmd(uint32_t baseAddr, bool enable) { BW_WDOG_STCTRLH_ALLOWUPDATE(baseAddr, (uint8_t)enable); } /*! * @brief Checks whether the register update is enabled. * * This function checks whether the WDOG register update is enabled. * * @param baseAddr The WDOG peripheral base address * @return false means register update is disabled, true means register update is enabled. */ static inline bool WDOG_HAL_GetRegisterUpdateCmd(uint32_t baseAddr) { return (bool)BR_WDOG_STCTRLH_ALLOWUPDATE(baseAddr); } /*! * @brief Sets whether Watchdog is working while the CPU is in debug mode. * * This function configures whether the WDOG is enabled in the CPU debug mode. * Make sure WDOG registers are unlocked by the WDOG_HAL_Unlock, that the WCT window is still open and that * the WDOG_STCTRLH register has not been written in this WCT while this function is called. * Make sure WDOG_STCTRLH.ALLOWUPDATE is 1 which means register update is enabled. * * @param baseAddr The WDOG peripheral base address * @param enable false means watchdog is disabled in CPU debug mode. * true means watchdog is enabled in CPU debug mode. */ static inline void WDOG_HAL_SetWorkInDebugModeCmd(uint32_t baseAddr, bool enable) { BW_WDOG_STCTRLH_DBGEN(baseAddr, (uint8_t)enable); } /*! * @brief Checks whether the WDOG works while in the CPU debug mode. * * This function checks whether the WDOG works in the CPU debug mode. * * @param baseAddr The WDOG peripheral base address * @return false means not work while in CPU debug mode, true means works while in CPU debug mode. */ static inline bool WDOG_HAL_GetWorkInDebugModeCmd(uint32_t baseAddr) { return (bool)BR_WDOG_STCTRLH_DBGEN(baseAddr); } /*! * @brief Sets whether the Watchdog is working while the CPU is in stop mode. * * This function configures whether the WDOG is enabled in the CPU stop mode. * Make sure that the WDOG registers are unlocked by the WDOG_HAL_Unlock, that the WCT window is still open and that * the WDOG_STCTRLH register has not been written in this WCT while this function is called. * Make sure WDOG_STCTRLH.ALLOWUPDATE is 1 which means register update is enabled. * * @param baseAddr The WDOG peripheral base address * @param enable false means watchdog is disabled in CPU stop mode. * true means watchdog is enabled in CPU stop mode. */ static inline void WDOG_HAL_SetWorkInStopModeCmd(uint32_t baseAddr, bool enable) { BW_WDOG_STCTRLH_STOPEN(baseAddr, (uint8_t)enable); } /*! * @brief Checks whether the WDOG works while in CPU stop mode. * * This function checks whether the WDOG works in the CPU stop mode. * Make sure WDOG registers are unlocked by the WDOG_HAL_Unlock, that the WCT window is still open and that * the WDOG_STCTRLH register has not been written in this WCT while this function is called. * Make sure WDOG_STCTRLH.ALLOWUPDATE is 1 which means register update is enabled. * * @param baseAddr The WDOG peripheral base address * @return false means not work while in CPU stop mode, true means works while in CPU stop mode. */ static inline bool WDOG_HAL_GetWorkInStopModeCmd(uint32_t baseAddr) { return (bool)BR_WDOG_STCTRLH_STOPEN(baseAddr); } /*! * @brief Sets whether the Watchdog is working while the CPU is in wait mode. * * This function configures whether the WDOG is enabled in the CPU wait mode. * Make sure WDOG registers are unlocked by the WDOG_HAL_Unlock, that the WCT window is still open and that * the WDOG_STCTRLH register has not been written in this WCT while this function is called. * Make sure WDOG_STCTRLH.ALLOWUPDATE is 1 which means register update is enabled. * * @param baseAddr The WDOG peripheral base address * @param enable false means watchdog is disabled in CPU wait mode. * true means watchdog is enabled in CPU wait mode. */ static inline void WDOG_HAL_SetWorkInWaitModeCmd(uint32_t baseAddr, bool enable) { BW_WDOG_STCTRLH_WAITEN(baseAddr, (uint8_t)enable); } /*! * @brief Checks whether the WDOG works while in the CPU wait mode. * * This function checks whether the WDOG works in the CPU wait mode. * * @param baseAddr The WDOG peripheral base address * @return false means not work while in CPU wait mode, true means works while in CPU wait mode. */ static inline bool WDOG_HAL_GetWorkInWaitModeCmd(uint32_t baseAddr) { return (bool)BR_WDOG_STCTRLH_WAITEN(baseAddr); } /*! * @brief Gets the Watchdog interrupt status. * * This function gets the WDOG interrupt flag. * * @param baseAddr The WDOG peripheral base address * @return Watchdog interrupt status, false means interrupt not asserted, true means interrupt asserted. */ static inline bool WDOG_HAL_IsIntPending(uint32_t baseAddr) { return (bool)BR_WDOG_STCTRLL_INTFLG(baseAddr); } /*! * @brief Clears the Watchdog interrupt flag. * * This function clears the WDOG interrupt flag. * * @param baseAddr The WDOG peripheral base address */ static inline void WDOG_HAL_ClearIntFlag(uint32_t baseAddr) { BW_WDOG_STCTRLL_INTFLG(baseAddr, true); } /*! * @brief Set the Watchdog timeout value. * * This function sets the WDOG_TOVAL value. * It should be ensured that the time-out value for the Watchdog is always greater than * 2xWCT time + 20 bus clock cycles. * Make sure WDOG registers are unlocked by the WDOG_HAL_Unlock , that the WCT window is still open and that * this API has not been called in this WCT while this function is called. * Make sure WDOG_STCTRLH.ALLOWUPDATE is 1 which means register update is enabled. * * @param baseAddr The WDOG peripheral base address * @param timeoutCount watchdog timeout value, count of watchdog clock tick. */ static inline void WDOG_HAL_SetTimeoutValue(uint32_t baseAddr, uint32_t timeoutCount) { HW_WDOG_TOVALH_WR(baseAddr, (uint16_t)((timeoutCount >> 16U) & 0xFFFFU)); HW_WDOG_TOVALL_WR(baseAddr, (uint16_t)((timeoutCount) & 0xFFFFU)); } /*! * @brief Gets the Watchdog timeout value. * * This function gets the WDOG_TOVAL value. * * @param baseAddr The WDOG peripheral base address * @return value of register WDOG_TOVAL. */ static inline uint32_t WDOG_HAL_GetTimeoutValue(uint32_t baseAddr) { return (uint32_t)((((uint32_t)(HW_WDOG_TOVALH_RD(baseAddr))) << 16U) | (HW_WDOG_TOVALL_RD(baseAddr))); } /*! * @brief Gets the Watchdog timer output. * * This function gets the WDOG_TMROUT value. * * @param baseAddr The WDOG peripheral base address * @return Current value of watchdog timer counter. */ static inline uint32_t WDOG_HAL_GetTimerOutputValue(uint32_t baseAddr) { return (uint32_t)((((uint32_t)(HW_WDOG_TMROUTH_RD(baseAddr))) << 16U) | (HW_WDOG_TMROUTL_RD(baseAddr))); } /*! * @brief Sets the Watchdog clock prescaler. * * This function sets the WDOG clock prescaler. * Make sure WDOG registers are unlocked by the WDOG_HAL_Unlock , that the WCT window is still open and that * this API has not been called in this WCT while this function is called. * Make sure WDOG_STCTRLH.ALLOWUPDATE is 1 which means register update is enabled. * * @param baseAddr The WDOG peripheral base address * @param clockPrescaler watchdog clock prescaler, see #wdog_clock_prescaler_value_t. */ static inline void WDOG_HAL_SetClockPrescalerValueMode(uint32_t baseAddr, wdog_clock_prescaler_value_t clockPrescaler) { BW_WDOG_PRESC_PRESCVAL(baseAddr, (uint8_t)clockPrescaler); } /*! * @brief Gets the Watchdog clock prescaler. * * This function gets the WDOG clock prescaler. * * @param baseAddr The WDOG peripheral base address * @return WDOG clock prescaler, see #wdog_clock_prescaler_value_t. */ static inline wdog_clock_prescaler_value_t WDOG_HAL_GetClockPrescalerValueMode(uint32_t baseAddr) { return (wdog_clock_prescaler_value_t)BR_WDOG_PRESC_PRESCVAL(baseAddr); } /*! * @brief Sets the Watchdog window value. * * This function sets the WDOG_WIN value. * Make sure WDOG registers are unlocked by the WDOG_HAL_Unlock , that the WCT window is still open and that * this API has not been called in this WCT while this function is called. * Make sure WDOG_STCTRLH.ALLOWUPDATE is 1 which means register update is enabled. * * @param baseAddr The WDOG peripheral base address * @param windowValue watchdog window value. */ static inline void WDOG_HAL_SetWindowValue(uint32_t baseAddr, uint32_t windowValue) { HW_WDOG_WINH_WR(baseAddr, (uint16_t)((windowValue>>16U) & 0xFFFFU)); HW_WDOG_WINL_WR(baseAddr, (uint16_t)((windowValue) & 0xFFFFU)); } /*! * @brief Gets the Watchdog window value. * * This function gets the WDOG_WIN value. * * @param baseAddr The WDOG peripheral base address * @return watchdog window value. */ static inline uint32_t WDOG_HAL_GetWindowValue(uint32_t baseAddr) { return (uint32_t)((((uint32_t)(HW_WDOG_WINH_RD(baseAddr))) << 16U) | (HW_WDOG_WINL_RD(baseAddr))); } /*! * @brief Unlocks the Watchdog register written. * * This function unlocks the WDOG register written. * This function must be called before any configuration is set because watchdog register * will be locked automatically after a WCT(256 bus cycles). * * @param baseAddr The WDOG peripheral base address */ static inline void WDOG_HAL_Unlock(uint32_t baseAddr) { HW_WDOG_UNLOCK_WR(baseAddr, WDOG_UNLOCK_VALUE_HIGH); HW_WDOG_UNLOCK_WR(baseAddr, WDOG_UNLOCK_VALUE_LOW); } /*! * @brief Refreshes the Watchdog timer. * * This function feeds the WDOG. * This function should be called before watchdog timer is in timeout. Otherwise, a reset is asserted. * * @param baseAddr The WDOG peripheral base address */ static inline void WDOG_HAL_Refresh(uint32_t baseAddr) { HW_WDOG_REFRESH_WR(baseAddr, WDOG_REFRESH_VALUE_HIGH); HW_WDOG_REFRESH_WR(baseAddr, WDOG_REFRESH_VALUE_LOW); } /*! * @brief Resets the chip using the Watchdog. * * This function resets the chip using WDOG. * * @param baseAddr The WDOG peripheral base address */ static inline void WDOG_HAL_ResetSystem(uint32_t baseAddr) { HW_WDOG_REFRESH_WR(baseAddr, WDOG_REFRESH_VALUE_HIGH); HW_WDOG_REFRESH_WR(baseAddr, 0); while(1) { } } /*! * @brief Gets the chip reset count that was reset by Watchdog. * * This function gets the value of the WDOG_RSTCNT. * * @param baseAddr The WDOG peripheral base address * @return Chip reset count that was reset by Watchdog. */ static inline uint32_t WDOG_HAL_GetResetCount(uint32_t baseAddr) { return HW_WDOG_RSTCNT_RD(baseAddr); } /*! * @brief Clears the chip reset count that was reset by Watchdog. * * This function clears the WDOG_RSTCNT. * * @param baseAddr The WDOG peripheral base address */ static inline void WDOG_HAL_ClearResetCount(uint32_t baseAddr) { HW_WDOG_RSTCNT_WR(baseAddr, 0xFFFFU); } /*! * @brief Restores the WDOG module to reset value. * * This function restores the WDOG module to reset value. * * @param baseAddr The WDOG peripheral base address */ void WDOG_HAL_Init(uint32_t baseAddr); /*@}*/ #if defined(__cplusplus) } #endif /*! @}*/ #endif /* __FSL_WDOG_HAL_H__*/ /******************************************************************************* * EOF *******************************************************************************/ ================================================ FILE: Zelig/mbed/TARGET_K64F/TARGET_Freescale/TARGET_KPSDK_MCUS/TARGET_KPSDK_CODE/utilities/fsl_misc_utilities.h ================================================ /* * Copyright (c) 2013 - 2014, Freescale Semiconductor, Inc. * All rights reserved. * * Redistribution and use in source and binary forms, with or without modification, * are permitted provided that the following conditions are met: * * o Redistributions of source code must retain the above copyright notice, this list * of conditions and the following disclaimer. * * o Redistributions in binary form must reproduce the above copyright notice, this * list of conditions and the following disclaimer in the documentation and/or * other materials provided with the distribution. * * o Neither the name of Freescale Semiconductor, Inc. nor the names of its * contributors may be used to endorse or promote products derived from this * software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT 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. */ #ifndef __FSL_MISC_UTILITIES_H__ #define __FSL_MISC_UTILITIES_H__ #include /******************************************************************************* * Definitions ******************************************************************************/ /*! @brief Min/max macros */ #if !defined(MIN) #define MIN(a, b) ((a) < (b) ? (a) : (b)) #endif #if !defined(MAX) #define MAX(a, b) ((a) > (b) ? (a) : (b)) #endif /*! @brief Computes the number of elements in an array.*/ #define ARRAY_SIZE(x) (sizeof(x) / sizeof((x)[0])) /*! @brief Byte swap macros */ #define BSWAP_16(x) (uint16_t)((((x) & 0xFF00) >> 0x8) | (((x) & 0xFF) << 0x8)) #define BSWAP_32(val) (uint32_t)((BSWAP_16((uint32_t)(val) & (uint32_t)0xFFFF) << 0x10) | \ (BSWAP_16((uint32_t)((val) >> 0x10)))) #endif /* __FSL_MISC_UTILITIES_H__ */ /******************************************************************************* * EOF ******************************************************************************/ ================================================ FILE: Zelig/mbed/TARGET_K64F/TARGET_Freescale/TARGET_KPSDK_MCUS/TARGET_KPSDK_CODE/utilities/fsl_os_abstraction.h ================================================ /* * Copyright (c) 2013 - 2014, Freescale Semiconductor, Inc. * All rights reserved. * * Redistribution and use in source and binary forms, with or without modification, * are permitted provided that the following conditions are met: * * o Redistributions of source code must retain the above copyright notice, this list * of conditions and the following disclaimer. * * o Redistributions in binary form must reproduce the above copyright notice, this * list of conditions and the following disclaimer in the documentation and/or * other materials provided with the distribution. * * o Neither the name of Freescale Semiconductor, Inc. nor the names of its * contributors may be used to endorse or promote products derived from this * software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT 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. */ #if !defined(__FSL_OS_ABSTRACTION_H__) #define __FSL_OS_ABSTRACTION_H__ #include #include #include #if defined __CC_ARM #define inline __inline #endif /*! * @addtogroup os_abstraction * @{ */ /*! @brief Status values to be returned by functions. */ typedef enum { kSuccess = 0, /*!< Functions work correctly. */ kError, /*!< Functions work failed. */ kTimeout, /*!< Timeout occurs while waiting for an object. */ kIdle /*!< Can not get the object in non-blocking mode.*/ }fsl_rtos_status; /*! @brief The event flags are set or not.*/ typedef enum { kFlagNotSet = 0, /*!< The flags checked are set. */ kFlagSet /*!< The flags checked are not set. */ }event_status; /*! @brief The event flags are cleared automatically or manually.*/ typedef enum { kEventAutoClr = 0, /*!< The flags of the event will be cleared automatically. */ kEventManualClr /*!< The flags of the event will be cleared manually. */ }event_clear_type; // Temporary "fix", until the proper macros are integrated in the on-line build system #define FSL_RTOS_MBED /* Include required header file based on RTOS selection */ #if defined (FSL_RTOS_MQX) /*! @brief Macro to set message queue copy messages to internal memory or not. */ #define __FSL_RTOS_MSGQ_COPY_MSG__ 1 #include "fsl_os_abstraction_mqx.h" #elif defined (FSL_RTOS_FREE_RTOS) #define __FSL_RTOS_MSGQ_COPY_MSG__ 1 #include "fsl_os_abstraction_free_rtos.h" #elif defined (FSL_RTOS_UCOSII) #define __FSL_RTOS_MSGQ_COPY_MSG__ 1 #include "fsl_os_abstraction_ucosii.h" #elif defined (FSL_RTOS_UCOSIII) #define __FSL_RTOS_MSGQ_COPY_MSG__ 1 #include "fsl_os_abstraction_ucosiii.h" #elif defined (FSL_RTOS_CMSIS) #define __FSL_RTOS_MSGQ_COPY_MSG__ 0 #include "fsl_os_abstraction_cmsis.h" #elif defined (FSL_RTOS_MBED) #define __FSL_RTOS_MSGQ_COPY_MSG__ 1 #include "fsl_os_abstraction_mbed.h" #else #define __FSL_RTOS_MSGQ_COPY_MSG__ 1 #include "fsl_os_abstraction_bm.h" #endif /******************************************************************************* * API ******************************************************************************/ #if defined(__cplusplus) extern "C" { #endif /*! * @name Synchronization * @{ */ /*! * @brief Initialize a synchronization object to a given state. * * @param obj The sync object to initialize. * @param initValue The initial value the object will be set to. * * @retval kSuccess The object was successfully created. * @retval kError Invalid parameter or no more objects can be created. */ fsl_rtos_status sync_create(sync_object_t *obj, uint8_t initValue); /*! * @brief Wait for the synchronization object. * * This function checks the sync object's counting value, if it is * positive, decreases it and returns kSuccess, otherwise, timeout will be * used for wait. * * @param obj Pointer to the synchronization object. * @param timeout The maximum number of milliseconds to wait for the object to be signalled. * Pass the #kSyncWaitForever constant to wait indefinitely for someone to signal the object. * A value of 0 should not be passed to this function. Instead, use sync_poll for * a non blocking check. * * @retval kSuccess The object was signalled. * @retval kTimeout A timeout occurred. * @retval kError An incorrect parameter was passed. * @retval kIdle The object has not been signalled. * * @note There could be only one process waiting for the object at the same time. */ fsl_rtos_status sync_wait(sync_object_t *obj, uint32_t timeout); /*! * @brief Checks a synchronization object's status. * * This function is used to poll a sync object's status. * If the sync object's counting value is positive, decrease it and return * kSuccess. If the object's counting value is 0, the function will * return kIdle immediately * * @param obj The synchronization object. * * @retval kSuccess The object was signalled. * @retval kIdle The object was not signalled. * @retval kError An incorrect parameter was passed. */ fsl_rtos_status sync_poll(sync_object_t *obj); /*! * @brief Signal for someone waiting on the synchronization object to wake up. * * This function should not be called from an ISR. * * @param obj The synchronization object to signal. * * @retval kSuccess The object was successfully signaled. * @retval kError The object can not be signaled or invalid parameter. */ fsl_rtos_status sync_signal(sync_object_t *obj); /*! * @brief Signal for someone waiting on the synchronization object to wake up. * * This function should only be called from an ISR. * * @param obj The synchronization object to signal. * * @retval kSuccess The object was successfully signaled. * @retval kError The object can not be signaled or invalid parameter. */ fsl_rtos_status sync_signal_from_isr(sync_object_t *obj); /*! * @brief Destroy a previously created synchronization object. * * @param obj The synchronization object to destroy. * * @retval kSuccess The object was successfully destroyed. * @retval kError Object destruction failed. */ fsl_rtos_status sync_destroy(sync_object_t *obj); /* @} */ /*! * @name Resource locking * @{ */ /*! * @brief Initialize a locking object. * * @param obj The lock object to initialize. * * @retval kSuccess The lock is created successfully. * @retval kError Tke lock creation failed. */ fsl_rtos_status lock_create(lock_object_t *obj); /*! * @brief Wait for the object to be unlocked and lock it. * * This function will wait for some time or wait forever if could not get the lock. * * @param obj The locking object. * @param timeout The maximum number of milliseconds to wait for the mutex. * Pass the #kSyncWaitForever constant to wait indefinitely for someone to unlock the object. * A value of 0 should not be passed to this function. Instead, use lock_poll for a non * blocking check. * * @retval kSuccess The lock was obtained. * @retval kTimeout A timeout occurred. * @retval kError An incorrect parameter was passed. */ fsl_rtos_status lock_wait(lock_object_t *obj, uint32_t timeout); /*! * @brief Checks if a locking object can be locked and locks it if possible. * * This function returns instantly if could not get the lock. * * @param obj The locking object. * * @retval kSuccess The lock was obtained. * @retval kIdle The lock could not be obtained. * @retval kError An incorrect parameter was passed. * * @note There could be only one process waiting for the object at the same time. * For RTOSes, wait for a lock recursively by one task is not supported. * */ fsl_rtos_status lock_poll(lock_object_t *obj); /*! * @brief Unlock a previously locked object. * * @param obj The locking object to unlock. * * @retval kSuccess The object was successfully unlocked. * @retval kError The object can not be unlocked or invalid parameter. */ fsl_rtos_status lock_release(lock_object_t *obj); /*! * @brief Destroy a previously created locking object. * * @param obj The locking object to destroy. * * @retval kSuccess The object was successfully destroyed. * @retval kError Object destruction failed. */ fsl_rtos_status lock_destroy(lock_object_t *obj); /* @} */ /*! * @name Event signaling * @{ */ /*! * @brief Initializes the event object. * * When the object is created, the flags is 0. * * @param obj Pointer to the event object to initialize. * @param clearType The event is auto-clear or manual-clear. * * @retval kSuccess The object was successfully created. * @retval kError Incorrect parameter or no more objects can be created. */ fsl_rtos_status event_create(event_object_t *obj, event_clear_type clearType); /*! * @brief Wait for any event flags to be set. * * This function will wait for some time or wait forever if no flags are set. Any flags set * will wake up the function. * * @param obj The event object. * @param timeout The maximum number of milliseconds to wait for the event. * Pass the #kSyncWaitForever constant to wait indefinitely. A value of 0 should not be passed * to this function. * @param setFlags Pointer to receive the flags that were set. * * @retval kSuccess An event was set. * @retval kTimeout A timeout occurred. * @retval kError An incorrect parameter was passed. */ fsl_rtos_status event_wait(event_object_t *obj, uint32_t timeout, event_group_t *setFlags); /*! * @brief Set one or more event flags of an event object. * * This function should not be called from an ISR. * * @param obj The event object. * @param flags Event flags to be set. * * @retval kSuccess The flags were successfully set. * @retval kError An incorrect parameter was passed. * * @note There could be only one process waiting for the event. * */ fsl_rtos_status event_set(event_object_t *obj, event_group_t flags); /*! * @brief Set one or more event flags of an event object. * * This function should only be called from an ISR. * * @param obj The event object. * @param flags Event flags to be set. * * @retval kSuccess The flags were successfully set. * @retval kError An incorrect parameter was passed. */ fsl_rtos_status event_set_from_isr(event_object_t *obj, event_group_t flags); /*! * @brief Clear one or more events of an event object. * * This function should not be called from an ISR. * * @param obj The event object. * @param flags Event flags to be clear. * * @retval kSuccess The flags were successfully cleared. * @retval kError An incorrect parameter was passed. */ fsl_rtos_status event_clear(event_object_t *obj, event_group_t flags); /*! * @brief Check the flags are set or not. * * @param obj The event object. * @param flag The flag to check. * * @retval kFlagsSet The flags checked are set. * @retval kFlagsNotSet The flags checked are not set or got an error. */ event_status event_check_flags(event_object_t *obj, event_group_t flag); /*! * @brief Destroy a previously created event object. * * @param obj The event object to destroy. * * @retval kSuccess The object was successfully destroyed. * @retval kError Event destruction failed. */ fsl_rtos_status event_destroy(event_object_t *obj); /* @} */ /*! * @name Thread management * @{ */ /*! * @brief Create a task. * * This function is wrapped by the macro task_create. Generally, this function is for * internal use only, applications must use FSL_RTOS_TASK_DEFINE to define resources for * task statically then use task_create to create task. If applications have prepare * the resouces for task dynamically, they can use this function to create the task. * * @param task The task function. * @param name The name of this task. * @param stackSize The stack size in byte. * @param stackMem Pointer to the stack. For bare metal, MQX and FreeRTOS, this could be NULL. * @param priority Initial priority of the task. * @param param Pointer to be passed to the task when it is created. * @param usesFloat This task will use float register or not. * @param handler Pointer to the task handler. * * @retval kSuccess The task was successfully created. * @retval kError The task could not be created. * * @note Different tasks can not use the same task function. */ fsl_rtos_status __task_create(task_t task, uint8_t *name, uint16_t stackSize, task_stack_t *stackMem, uint16_t priority, void *param, bool usesFloat, task_handler_t *handler); /*! * @brief Destroy a previously created task. * @note Depending on the RTOS, task resources may or may not be automatically freed, * and this function may not return if the current task is destroyed. * * @param handler The handler of the task to destroy. Returned by the task_create function. * * @retval kSuccess The task was successfully destroyed. * @retval kError Task destruction failed or invalid parameter. */ fsl_rtos_status task_destroy(task_handler_t handler); /* @} */ /*! * @name Message queues * @{ */ /*! * @brief Initialize the message queue. * * This function will initialize the message queue that declared previously. * Here is an example demonstrating how to use: @code msg_queue_handler_t handler; MSG_QUEUE_DECLARE(my_message, msg_num, msg_size); handler = msg_queue_create(&my_message, msg_num, msg_size); @endcode * * @param queue The queue declared through the MSG_QUEUE_DECLARE macro. * @param number The number of elements in the queue. * @param size Size of every elements in words. * * @retval Handler to access the queue for put and get operations. If message queue * created failed, return 0. */ msg_queue_handler_t msg_queue_create(msg_queue_t *queue, uint16_t number, uint16_t size); /*! * @brief Introduce an element at the tail of the queue. * * @param handler Queue handler returned by the msg_queue_create function. * @param item Pointer to the element to be introduced in the queue. * * @retval kSuccess Element successfully introduced in the queue. * @retval kError The queue was full or an invalid parameter was passed. */ fsl_rtos_status msg_queue_put(msg_queue_handler_t handler, msg_queue_item_t item); /*! * @brief Read and remove an element at the head of the queue. * * @param handler Queue handler returned by the msg_queue_create function. * @param item Pointer to store a pointer to the element of the queue. * @param timeout In case the queue is empty, the number of milliseconds to * wait for an element to be introduced into the queue. Use 0 to return * immediately or #kSyncWaitForever to wait indefinitely. * * @retval kSuccess Element successfully obtained from the queue. * @retval kTimeout If a timeout was specified, the queue remained empty after timeout. * @retval kError The queue was empty or the handler was invalid. * @retval kIdle The queue was empty and the timeout has not expired. * * @note There should be only one process waiting on the queue. */ fsl_rtos_status msg_queue_get(msg_queue_handler_t handler, msg_queue_item_t *item, uint32_t timeout); /*! * @brief Discards all elements in the queue and leaves the queue empty. * * @param handler Queue handler returned by the msg_queue_create function. * * @retval kSuccess Queue successfully emptied. * @retval kError Emptying queue failed. */ fsl_rtos_status msg_queue_flush(msg_queue_handler_t handler); /*! * @brief Destroy a previously created queue. * * @param handler Queue handler returned by the msg_queue_create function. * * @retval kSuccess The queue was successfully destroyed. * @retval kError Message queue destruction failed. */ fsl_rtos_status msg_queue_destroy(msg_queue_handler_t handler); /* @} */ #ifndef FSL_RTOS_MBED /*! * @name Memory Management * @{ */ /*! * @brief Reserves the requested amount of memory in bytes. * * @param size Amount of bytes to reserve. * * @retval Pointer to the reserved memory. NULL if memory could not be allocated. */ void * mem_allocate(size_t size); /*! * @brief Reserves the requested amount of memory in bytes and initializes it to 0. * * @param size Amount of bytes to reserve. * * @retval Pointer to the reserved memory. NULL if memory could not be allocated. */ void * mem_allocate_zero(size_t size); /*! * @brief Releases the memory previously reserved. * * @param ptr Pointer to the start of the memory block previously reserved. * * @retval kSuccess Memory correctly released. */ fsl_rtos_status mem_free(void *ptr); #endif /* @} */ /*! * @name Time management * @{ */ /*! * @brief Delays execution for a number of milliseconds. * * @param delay The time in milliseconds to wait. */ void time_delay(uint32_t delay); /* @} */ /*! * @name Interrupt management * @{ */ /*! * @brief Install interrupt handler. * * @param irqNumber IRQ number of the interrupt. * @param handler The interrupt handler to install. * * @retval kSuccess Handler is installed successfully. * @retval kSuccess Handler could not be installed. */ fsl_rtos_status interrupt_handler_register(int32_t irqNumber, void (*handler)(void)); /* @} */ #if defined(__cplusplus) } #endif /*! @}*/ #endif /* __FSL_OS_ABSTRACTION_H__ */ /******************************************************************************* * EOF ******************************************************************************/ ================================================ FILE: Zelig/mbed/TARGET_K64F/TARGET_Freescale/TARGET_KPSDK_MCUS/TARGET_KPSDK_CODE/utilities/fsl_os_abstraction_mbed.h ================================================ /* fsl_os_mbed_abstraction.h */ /* Copyright (C) 2012 mbed.org, MIT License * * Permission is hereby granted, free of charge, to any person obtaining a copy of this software * and associated documentation files (the "Software"), to deal in the Software without restriction, * including without limitation the rights to use, copy, modify, merge, publish, distribute, * sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all copies or * substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING * BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, * DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ #ifndef FSL_OS_ABSTRACTION_MBED_H_ #define FSL_OS_ABSTRACTION_MBED_H_ // This is not really an "abstraction", but rather a set of quick&dirty // defines to allow the KSDK to compile. Currently, this is relevant only // in the context of the ENET driver (fsl_enet_driver.c) typedef int event_object_t; typedef int lock_object_t; typedef void sync_object_t; typedef unsigned int event_group_t; typedef int task_t; typedef void task_stack_t; typedef int task_handler_t; typedef int msg_queue_handler_t; typedef void msg_queue_t; typedef int msg_queue_item_t; #endif // #ifdef FSL_OS_ABSTRACTION_MBED_H_ ================================================ FILE: Zelig/mbed/TARGET_K64F/TARGET_Freescale/TARGET_KPSDK_MCUS/TARGET_KPSDK_CODE/utilities/sw_timer.h ================================================ /* * Copyright (c) 2013 - 2014, Freescale Semiconductor, Inc. * All rights reserved. * * Redistribution and use in source and binary forms, with or without modification, * are permitted provided that the following conditions are met: * * o Redistributions of source code must retain the above copyright notice, this list * of conditions and the following disclaimer. * * o Redistributions in binary form must reproduce the above copyright notice, this * list of conditions and the following disclaimer in the documentation and/or * other materials provided with the distribution. * * o Neither the name of Freescale Semiconductor, Inc. nor the names of its * contributors may be used to endorse or promote products derived from this * software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT 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. */ #if !defined(__SW_TIMER_H__) #define __SW_TIMER_H__ #include #include /*! @addtogroup sw_timer Software Timer * @brief This module is used to interface with Abstract Timer HAL to generate periodical timeouts * required through different modules of the AOA protocol. This block will be based on 1ms * ticks for all the timeout calculations. The HAL Interface block used to communicate with * this must have the same 1ms timeout configured. This module can generate different * software timer channels based on the same 1ms. */ /*! @{*/ /*! Definition of the possible status of a software channel timer. */ typedef enum SwTimerChannelStatus { kSwTimerChannelExpired = 0x00, /*!< Indicates the timer channel has counted the given ms*/ kSwTimerChannelStillCounting = 0x01, /*!< Indicates the timeout of the channel has not expired and the timer is still counting.*/ kSwTimerChannelIsDisable = 0x02, /*!< Indicates the timer channel is not reserved. */ kSwTimerChannelNotAvailable = 0xFF /*!< Indicates there are not available channels to reserve or the requested channel is not available.*/ }sw_timer_channel_status_t; /*! List of status and errors. */ enum _sw_timer_errors { kSwTimerStatusSuccess, /*!< The execution was successful.*/ kSwTimerStatusFail, /*!< The execution failed.*/ kSwTimerStatusInvalidChannel /*!< The given channel is not valid. Valid channels are 0 to (SW_TIMER_NUMBER_CHANNELS - 1). */ }; /*! * Data type of the counter of each timer channel. If it is an int8_t the counter will count * up to 127ms, int16_t up to 32767ms and int32_t up to 2147483647ms. */ typedef int32_t time_counter_t; /*! Max timeout value according to size of the time counter */ enum sw_timer_timeouts { kSwTimerMaxTimeout = 2147483647 }; /*! * Data type of the free running counter. This data type should be unsigned and will count up to * 255ms if it is uint8_t, 65535ms for uint16_t and 4294967295ms for uint32_t. */ typedef uint32_t time_free_counter_t; #if defined(__cplusplus) extern "C" { #endif /* __cplusplus*/ /*! * @brief Initializes the software timer module. Prepares variables and HAL layer to provide timer * services. Starts the free running counter which will be available to get its value any * time while the service is running; it is useful whenever a module wants to keep track of * time, but do not wants to reserve a channel. * * @return status_t Returns software timer status after initialization. * @retval kSwTimerStatusSuccess The initialization was successful and the software timer is ready * to provide services. * @retval kSwTimerStatusFail The initialization failed. */ uint32_t sw_timer_init_service(void); /*! * @brief Deinitializes the software timer module. Shutdown HAL layer, so no timer service can be * provided after the execution of this function. * * @return void */ void sw_timer_shutdown_service(void); /*! * @brief Reserves a free timer channel to be used by any module and returns its identifier. * * @return uint8_t Returns the number of the channel that was reserved. * @retval Any value between 0 and SW_TIMER_NUMBER_CHANNELS is a valid channel. It indicates the * channel was reserved and can be used. * @retval kSwTimerChannelNotAvailable If there is not any available channel, because all * channels are already reserved. */ uint8_t sw_timer_reserve_channel(void); /*! * @brief Returns the actual status of the given timer channel. The timer has to be previously * started to return a valid status. * * @param timerChannel [in] Indicates the timer channel which status is going to be returned. * * @return sw_timer_channel_status_t Current status of the given timer channel. * @retval kSwTimerChannelExpired Indicates the timer channel has counted the given ms. * @retval kSwTimerChannelStillCounting Indicates the timeout of the channel has not expired and the timer is still counting. * @retval kSwTimerChannelIsDisable Indicates the timer channel is not reserved. * @retval kSwTimerChannelNotAvailable Indicates the timer channel is invalid. */ sw_timer_channel_status_t sw_timer_get_channel_status(uint8_t timerChannel); /*! * @brief Starts the count down of the given timer channel. The timer channel has to be previously * reserved. * * @param timerChannel [in] Indicates the timer channel that is going to be started. * @param timeout [in] Time in ms that the timer channel will count. The timeout should be a multiple of count unit of the timer, otherwise it will be taken the integer part of the division and the exact count will not be achieved * * @return status_t Reports failures in the execution of the function. * @retval kSwTimerStatusSuccess A channel was started successfully. * @retval kSwTimerStatusInvalidChannel The timer channel is invalid, it does not exist. */ uint32_t sw_timer_start_channel(uint8_t timerChannel, time_counter_t timeout); /*! * @brief Releases the given timer channel, so it can be used by someone else. * * @param timerChannel [in] Identifier of the timer channel. * * @return status_t Reports failures in the execution of the function. * @retval kSwTimerStatusSuccess A channel was released successfully. * @retval kSwTimerStatusInvalidChannel The timer channel is invalid, it does not exist. */ uint32_t sw_timer_release_channel(uint8_t timerChannel); /*! * @brief Gets the current value of the free running counter. Any module can keep track of the time * by reading this counter and calculates time difference. No reservation of timer channel * is needed. Consider for calculations that when the counter overflows it will start from * 0 again. * * @return time_free_counter_t Returns current count of the free running counter. */ time_free_counter_t sw_timer_get_free_counter(void); /*! * @brief This function is called every 1ms by the interruption and update count down values of all * timer channels. * * @return void */ void sw_timer_update_counters(void); #if defined(__cplusplus) } #endif /* __cplusplus*/ /*! @}*/ /*Group sw_timer*/ #endif /* __SW_TIMER_H__ */ /******************************************************************************* * EOF ******************************************************************************/ ================================================ FILE: Zelig/mbed/TARGET_K64F/TARGET_Freescale/TARGET_KPSDK_MCUS/TARGET_MCU_K64F/MK64F12/fsl_clock_K64F12.h ================================================ /* * Copyright (c) 2013 - 2014, Freescale Semiconductor, Inc. * All rights reserved. * * Redistribution and use in source and binary forms, with or without modification, * are permitted provided that the following conditions are met: * * o Redistributions of source code must retain the above copyright notice, this list * of conditions and the following disclaimer. * * o Redistributions in binary form must reproduce the above copyright notice, this * list of conditions and the following disclaimer in the documentation and/or * other materials provided with the distribution. * * o Neither the name of Freescale Semiconductor, Inc. nor the names of its * contributors may be used to endorse or promote products derived from this * software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT 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. */ #if !defined(__FSL_CLOCK_K64F12_H__) #define __FSL_CLOCK_K64F12__H__ /*! @addtogroup clock_manager*/ /*! @{*/ /*! @file*/ /******************************************************************************* * Definitions ******************************************************************************/ /******************************************************************************* * API ******************************************************************************/ #if defined(__cplusplus) extern "C" { #endif /* __cplusplus*/ /*! * @brief Gets the clock frequency for DMA module. * * This function gets the clock frequence for DMA moudle. * @param instance module device instance * @return freq clock frequence for this module */ uint32_t CLOCK_SYS_GetDmaFreq(uint32_t instance); /*! * @brief Gets the clock frequency for DMAMUX module. * * This function gets the clock frequence for DMAMUX moudle. * @param instance module device instance * @return freq clock frequence for this module */ uint32_t CLOCK_SYS_GetDmamuxFreq(uint32_t instance); /*! * @brief Gets the clock frequency for PORT module. * * This function gets the clock frequence for PORT moudle. * @param instance module device instance * @return freq clock frequence for this module */ uint32_t CLOCK_SYS_GetPortFreq(uint32_t instance); /*! * @brief Gets the clock frequency for MPU module. * * This function gets the clock frequence for MPU moudle. * @param instance module device instance * @return freq clock frequence for this module */ uint32_t CLOCK_SYS_GetMpuFreq(uint32_t instance); /*! * @brief Gets the clock frequency for EWM module. * * This function gets the clock frequence for EWM moudle. * @param instance module device instance * @return freq clock frequence for this module */ uint32_t CLOCK_SYS_GetEwmFreq(uint32_t instance); /*! * @brief Gets the clock frequency for FLEXBUS module. * * This function gets the clock frequence for FLEXBUS moudle. * @param instance module device instance * @return freq clock frequence for this module */ uint32_t CLOCK_SYS_GetFlexbusFreq(uint32_t instance); /*! * @brief Gets the clock frequency for FTF module. (Flash Memory) * * This function gets the clock frequence for FTF module. (Flash Memory) * @param instance module device instance * @return freq clock frequence for this module */ uint32_t CLOCK_SYS_GetFtfFreq(uint32_t instance); /*! * @brief Gets the clock frequency for CRC module. * * This function gets the clock frequence for CRC module. * @param instance module device instance * @return freq clock frequence for this module */ uint32_t CLOCK_SYS_GetCrcFreq(uint32_t instance); /*! * @brief Gets the clock frequency for RNGA module. * * This function gets the clock frequence for RNGA module. * @param instance module device instance * @return freq clock frequence for this module */ uint32_t CLOCK_SYS_GetRngaFreq(uint32_t instance); /*! * @brief Gets the clock frequency for ADC module. * * This function gets the clock frequence for ADC module. * @param instance module device instance * @return freq clock frequence for this module */ uint32_t CLOCK_SYS_GetAdcFreq(uint32_t instance); /*! * @brief Gets the clock frequency for CMP module. * * This function gets the clock frequence for CMP module. * @param instance module device instance * @return freq clock frequence for this module */ uint32_t CLOCK_SYS_GetCmpFreq(uint32_t instance); /*! * @brief Gets the clock frequency for VREF module. * * This function gets the clock frequence for VREF module. * @param instance module device instance * @return freq clock frequence for this module */ uint32_t CLOCK_SYS_GetVrefFreq(uint32_t instance); /*! * @brief Gets the clock frequency for PDB module. * * This function gets the clock frequence for PDB module. * @param instance module device instance * @return freq clock frequence for this module */ uint32_t CLOCK_SYS_GetPdbFreq(uint32_t instance); /*! * @brief Gets the clock frequency for FTM module. (FlexTimer) * * This function gets the clock frequence for FTM module. * @param instance module device instance * @return freq clock frequence for this module */ uint32_t CLOCK_SYS_GetFtmFreq(uint32_t instance); /*! * @brief Gets the clock frequency for PIT module. * * This function gets the clock frequence for PIT module. * @param instance module device instance * @return freq clock frequence for this module */ uint32_t CLOCK_SYS_GetPitFreq(uint32_t instance); /*! * @brief Gets the clock frequency for CMT module. * * This function gets the clock frequence for CMT module. * @param instance module device instance * @return freq clock frequence for this module */ uint32_t CLOCK_SYS_GetCmtFreq(uint32_t instance); /*! * @brief Gets the clock frequency for ENET module RMII clock. * * This function gets the clock frequence for ENET module RMII clock.. * @param instance module device instance * @return freq clock frequence for this module */ uint32_t CLOCK_SYS_GetEnetRmiiFreq(uint32_t instance); /*! * @brief Gets the clock frequency for ENET module TIME clock. * * This function gets the clock frequence for ENET module TIME clock.. * @param instance module device instance * @return freq clock frequence for this module */ uint32_t CLOCK_SYS_GetEnetTimeStampFreq(uint32_t instance); /*! * @brief Gets the clock frequency for USB FS OTG module * * This function gets the clock frequence for USB FS OTG module. * @param instance module device instance * @return freq clock frequence for this module */ uint32_t CLOCK_SYS_GetUsbFreq(uint32_t instance); /*! * @brief Gets the clock frequency for USB DCD module * * This function gets the clock frequence for USB DCD module. * @param instance module device instance * @return freq clock frequence for this module */ uint32_t CLOCK_SYS_GetUsbdcdFreq(uint32_t instance); /*! * @brief Gets the clock frequency for SPI module * * This function gets the clock frequence for SPI module. * @param instance module device instance * @return freq clock frequence for this module */ uint32_t CLOCK_SYS_GetSpiFreq(uint32_t instance); /*! * @brief Gets the clock frequency for I2C module * * This function gets the clock frequence for I2C module. * @param instance module device instance * @return freq clock frequence for this module */ uint32_t CLOCK_SYS_GetI2cFreq(uint32_t instance); /*! * @brief Gets the clock frequency for UART module * * This function gets the clock frequence for UART module. * @param instance module device instance * @return freq clock frequence for this module */ uint32_t CLOCK_SYS_GetUartFreq(uint32_t instance); /*! * @brief Gets the clock frequency for SDHC module. * * This function gets the clock frequence for SDHC moudle. * @param instance module device instance * @return freq clock frequence for this module */ uint32_t CLOCK_SYS_GetSdhcFreq(uint32_t instance); /*! * @brief Gets the clock frequency for I2S module. * * This function gets the clock frequence for I2S module. * @param instance module device instance * @return freq clock frequence for this module */ uint32_t CLOCK_SYS_GetSaiFreq(uint32_t instance); /*! * @brief Gets the clock frequency for GPIO module * * This function gets the clock frequence for GPIO module. * @param instance module device instance * @return freq clock frequence for this module */ uint32_t CLOCK_SYS_GetGpioFreq(uint32_t instance); /*! * @brief Enable the clock for DMA module. * * This function enables the clock for DMA moudle. * @param instance module device instance */ static inline void CLOCK_SYS_EnableDmaClock(uint32_t instance) { SIM_HAL_EnableDmaClock(g_simBaseAddr[0], instance); } /*! * @brief Disable the clock for DMA module. * * This function disables the clock for DMA moudle. * @param instance module device instance */ static inline void CLOCK_SYS_DisableDmaClock(uint32_t instance) { SIM_HAL_DisableDmaClock(g_simBaseAddr[0], instance); } /*! * @brief Get the the clock gate state for DMA module. * * This function will get the clock gate state for DMA moudle. * @param instance module device instance * @return state true - ungated(Enabled), false - gated (Disabled) */ static inline bool CLOCK_SYS_GetDmaGateCmd(uint32_t instance) { return SIM_HAL_GetDmaGateCmd(g_simBaseAddr[0], instance); } /*! * @brief Enable the clock for DMAMUX module. * * This function enables the clock for DMAMUX moudle. * @param instance module device instance */ static inline void CLOCK_SYS_EnableDmamuxClock(uint32_t instance) { SIM_HAL_EnableDmamuxClock(g_simBaseAddr[0], instance); } /*! * @brief Disable the clock for DMAMUX module. * * This function disables the clock for DMAMUX moudle. * @param instance module device instance */ static inline void CLOCK_SYS_DisableDmamuxClock(uint32_t instance) { SIM_HAL_DisableDmamuxClock(g_simBaseAddr[0], instance); } /*! * @brief Get the the clock gate state for DMAMUX module. * * This function will get the clock gate state for DMAMUX moudle. * @param instance module device instance * @return state true - ungated(Enabled), false - gated (Disabled) */ static inline bool CLOCK_SYS_GetDmamuxGateCmd(uint32_t instance) { return SIM_HAL_GetDmamuxGateCmd(g_simBaseAddr[0], instance); } /*! * @brief Enable the clock for PORT module. * * This function enables the clock for PORT moudle. * @param instance module device instance */ static inline void CLOCK_SYS_EnablePortClock(uint32_t instance) { SIM_HAL_EnablePortClock(g_simBaseAddr[0], instance); } /*! * @brief Disable the clock for PORT module. * * This function disables the clock for PORT moudle. * @param instance module device instance */ static inline void CLOCK_SYS_DisablePortClock(uint32_t instance) { SIM_HAL_DisablePortClock(g_simBaseAddr[0], instance); } /*! * @brief Get the the clock gate state for PORT module. * * This function will get the clock gate state for PORT moudle. * @param instance module device instance * @return state true - ungated(Enabled), false - gated (Disabled) */ static inline bool CLOCK_SYS_GetPortGateCmd(uint32_t instance) { return SIM_HAL_GetPortGateCmd(g_simBaseAddr[0], instance); } /*! * @brief Enable the clock for MPU module. * * This function enables the clock for MPU moudle. * @param instance module device instance */ static inline void CLOCK_SYS_EnableMpuClock(uint32_t instance) { SIM_HAL_EnableMpuClock(g_simBaseAddr[0], instance); } /*! * @brief Disable the clock for MPU module. * * This function disables the clock for MPU moudle. * @param instance module device instance */ static inline void CLOCK_SYS_DisableMpuClock(uint32_t instance) { SIM_HAL_DisableMpuClock(g_simBaseAddr[0], instance); } /*! * @brief Get the the clock gate state for MPU module. * * This function will get the clock gate state for MPU moudle. * @param instance module device instance * @return state true - ungated(Enabled), false - gated (Disabled) */ static inline bool CLOCK_SYS_GetMpuGateCmd(uint32_t instance) { return SIM_HAL_GetMpuGateCmd(g_simBaseAddr[0], instance); } /*! * @brief Enable the clock for EWM module. * * This function enables the clock for EWM moudle. * @param instance module device instance */ static inline void CLOCK_SYS_EnableEwmClock(uint32_t instance) { SIM_HAL_EnableEwmClock(g_simBaseAddr[0], instance); } /*! * @brief Disable the clock for EWM module. * * This function disables the clock for EWM moudle. * @param instance module device instance */ static inline void CLOCK_SYS_DisableEwmClock(uint32_t instance) { SIM_HAL_DisableEwmClock(g_simBaseAddr[0], instance); } /*! * @brief Get the the clock gate state for EWM module. * * This function will get the clock gate state for EWM moudle. * @param instance module device instance * @return state true - ungated(Enabled), false - gated (Disabled) */ static inline bool CLOCK_SYS_GetEwmGateCmd(uint32_t instance) { return SIM_HAL_GetEwmGateCmd(g_simBaseAddr[0], instance); } /*! * @brief Enable the clock for FLEXBUS module. * * This function enables the clock for FLEXBUS moudle. * @param instance module device instance */ static inline void CLOCK_SYS_EnableFlexbusClock(uint32_t instance) { SIM_HAL_EnableFlexbusClock(g_simBaseAddr[0], instance); } /*! * @brief Disable the clock for FLEXBUS module. * * This function disables the clock for FLEXBUS moudle. * @param instance module device instance */ static inline void CLOCK_SYS_DisableFlexbusClock(uint32_t instance) { SIM_HAL_DisableFlexbusClock(g_simBaseAddr[0], instance); } /*! * @brief Get the the clock gate state for FLEXBUS module. * * This function will get the clock gate state for FLEXBUS moudle. * @param instance module device instance * @return state true - ungated(Enabled), false - gated (Disabled) */ static inline bool CLOCK_SYS_GetFlexbusGateCmd(uint32_t instance) { return SIM_HAL_GetFlexbusGateCmd(g_simBaseAddr[0], instance); } /*! * @brief Enable the clock for FTF module. * * This function enables the clock for FTF moudle. * @param instance module device instance */ static inline void CLOCK_SYS_EnableFtfClock(uint32_t instance) { SIM_HAL_EnableFtfClock(g_simBaseAddr[0], instance); } /*! * @brief Disable the clock for FTF module. * * This function disables the clock for FTF moudle. * @param instance module device instance */ static inline void CLOCK_SYS_DisableFtfClock(uint32_t instance) { SIM_HAL_DisableFtfClock(g_simBaseAddr[0], instance); } /*! * @brief Get the the clock gate state for FTF module. * * This function will get the clock gate state for FTF moudle. * @param instance module device instance * @return state true - ungated(Enabled), false - gated (Disabled) */ static inline bool CLOCK_SYS_GetFtfGateCmd(uint32_t instance) { return SIM_HAL_GetFtfGateCmd(g_simBaseAddr[0], instance); } /*! * @brief Enable the clock for CRC module. * * This function enables the clock for CRC moudle. * @param instance module device instance */ static inline void CLOCK_SYS_EnableCrcClock(uint32_t instance) { SIM_HAL_EnableCrcClock(g_simBaseAddr[0], instance); } /*! * @brief Disable the clock for CRC module. * * This function disables the clock for CRC moudle. * @param instance module device instance */ static inline void CLOCK_SYS_DisableCrcClock(uint32_t instance) { SIM_HAL_DisableCrcClock(g_simBaseAddr[0], instance); } /*! * @brief Get the the clock gate state for CRC module. * * This function will get the clock gate state for CRC moudle. * @param instance module device instance * @return state true - ungated(Enabled), false - gated (Disabled) */ static inline bool CLOCK_SYS_GetCrcGateCmd(uint32_t instance) { return SIM_HAL_GetCrcGateCmd(g_simBaseAddr[0], instance); } /*! * @brief Enable the clock for RNGA module. * * This function enables the clock for RNGA moudle. * @param instance module device instance */ static inline void CLOCK_SYS_EnableRngaClock(uint32_t instance) { SIM_HAL_EnableRngaClock(g_simBaseAddr[0], instance); } /*! * @brief Disable the clock for RNGA module. * * This function disables the clock for RNGA moudle. * @param instance module device instance */ static inline void CLOCK_SYS_DisableRngaClock(uint32_t instance) { SIM_HAL_DisableRngaClock(g_simBaseAddr[0], instance); } /*! * @brief Get the the clock gate state for RNGA module. * * This function will get the clock gate state for RNGA moudle. * @param instance module device instance * @return state true - ungated(Enabled), false - gated (Disabled) */ static inline bool CLOCK_SYS_GetRngaGateCmd(uint32_t instance) { return SIM_HAL_GetRngaGateCmd(g_simBaseAddr[0], instance); } /*! * @brief Enable the clock for ADC module. * * This function enables the clock for ADC moudle. * @param instance module device instance */ static inline void CLOCK_SYS_EnableAdcClock(uint32_t instance) { SIM_HAL_EnableAdcClock(g_simBaseAddr[0], instance); } /*! * @brief Disable the clock for ADC module. * * This function disables the clock for ADC moudle. * @param instance module device instance */ static inline void CLOCK_SYS_DisableAdcClock(uint32_t instance) { SIM_HAL_DisableAdcClock(g_simBaseAddr[0], instance); } /*! * @brief Get the the clock gate state for ADC module. * * This function will get the clock gate state for ADC moudle. * @param instance module device instance * @return state true - ungated(Enabled), false - gated (Disabled) */ static inline bool CLOCK_SYS_GetAdcGateCmd(uint32_t instance) { return SIM_HAL_GetAdcGateCmd(g_simBaseAddr[0], instance); } /*! * @brief Enable the clock for CMP module. * * This function enables the clock for CMP moudle. * @param instance module device instance */ static inline void CLOCK_SYS_EnableCmpClock(uint32_t instance) { SIM_HAL_EnableCmpClock(g_simBaseAddr[0], instance); } /*! * @brief Disable the clock for CMP module. * * This function disables the clock for CMP moudle. * @param instance module device instance */ static inline void CLOCK_SYS_DisableCmpClock(uint32_t instance) { SIM_HAL_DisableCmpClock(g_simBaseAddr[0], instance); } /*! * @brief Get the the clock gate state for CMP module. * * This function will get the clock gate state for CMP moudle. * @param instance module device instance * @return state true - ungated(Enabled), false - gated (Disabled) */ static inline bool CLOCK_SYS_GetCmpGateCmd(uint32_t instance) { return SIM_HAL_GetCmpGateCmd(g_simBaseAddr[0], instance); } /*! * @brief Enable the clock for DAC module. * * This function enables the clock for DAC moudle. * @param instance module device instance */ static inline void CLOCK_SYS_EnableDacClock(uint32_t instance) { SIM_HAL_EnableDacClock(g_simBaseAddr[0], instance); } /*! * @brief Disable the clock for DAC module. * * This function disables the clock for DAC moudle. * @param instance module device instance */ static inline void CLOCK_SYS_DisableDacClock(uint32_t instance) { SIM_HAL_DisableDacClock(g_simBaseAddr[0], instance); } /*! * @brief Get the the clock gate state for DAC module. * * This function will get the clock gate state for DAC moudle. * @param instance module device instance * @return state true - ungated(Enabled), false - gated (Disabled) */ static inline bool CLOCK_SYS_GetDacGateCmd(uint32_t instance) { return SIM_HAL_GetDacGateCmd(g_simBaseAddr[0], instance); } /*! * @brief Enable the clock for VREF module. * * This function enables the clock for VREF moudle. * @param instance module device instance */ static inline void CLOCK_SYS_EnableVrefClock(uint32_t instance) { SIM_HAL_EnableVrefClock(g_simBaseAddr[0], instance); } /*! * @brief Disable the clock for VREF module. * * This function disables the clock for VREF moudle. * @param instance module device instance */ static inline void CLOCK_SYS_DisableVrefClock(uint32_t instance) { SIM_HAL_DisableVrefClock(g_simBaseAddr[0], instance); } /*! * @brief Get the the clock gate state for VREF module. * * This function will get the clock gate state for VREF moudle. * @param instance module device instance * @return state true - ungated(Enabled), false - gated (Disabled) */ static inline bool CLOCK_SYS_GetVrefGateCmd(uint32_t instance) { return SIM_HAL_GetVrefGateCmd(g_simBaseAddr[0], instance); } /*! * @brief Enable the clock for SAI module. * * This function enables the clock for SAI moudle. * @param instance module device instance */ static inline void CLOCK_SYS_EnableSaiClock(uint32_t instance) { SIM_HAL_EnableSaiClock(g_simBaseAddr[0], instance); } /*! * @brief Disable the clock for SAI module. * * This function disables the clock for SAI moudle. * @param instance module device instance */ static inline void CLOCK_SYS_DisableSaiClock(uint32_t instance) { SIM_HAL_DisableSaiClock(g_simBaseAddr[0], instance); } /*! * @brief Get the the clock gate state for SAI module. * * This function will get the clock gate state for SAI moudle. * @param instance module device instance * @return state true - ungated(Enabled), false - gated (Disabled) */ static inline bool CLOCK_SYS_GetSaiGateCmd(uint32_t instance) { return SIM_HAL_GetSaiGateCmd(g_simBaseAddr[0], instance); } /*! * @brief Enable the clock for PDB module. * * This function enables the clock for PDB moudle. * @param instance module device instance */ static inline void CLOCK_SYS_EnablePdbClock(uint32_t instance) { SIM_HAL_EnablePdbClock(g_simBaseAddr[0], instance); } /*! * @brief Disable the clock for PDB module. * * This function disables the clock for PDB moudle. * @param instance module device instance */ static inline void CLOCK_SYS_DisablePdbClock(uint32_t instance) { SIM_HAL_DisablePdbClock(g_simBaseAddr[0], instance); } /*! * @brief Get the the clock gate state for PDB module. * * This function will get the clock gate state for PDB moudle. * @param instance module device instance * @return state true - ungated(Enabled), false - gated (Disabled) */ static inline bool CLOCK_SYS_GetPdbGateCmd(uint32_t instance) { return SIM_HAL_GetPdbGateCmd(g_simBaseAddr[0], instance); } /*! * @brief Enable the clock for FTM module. * * This function enables the clock for FTM moudle. * @param instance module device instance */ static inline void CLOCK_SYS_EnableFtmClock(uint32_t instance) { SIM_HAL_EnableFtmClock(g_simBaseAddr[0], instance); } /*! * @brief Disable the clock for FTM module. * * This function disables the clock for FTM moudle. * @param instance module device instance */ static inline void CLOCK_SYS_DisableFtmClock(uint32_t instance) { SIM_HAL_DisableFtmClock(g_simBaseAddr[0], instance); } /*! * @brief Get the the clock gate state for FTM module. * * This function will get the clock gate state for FTM moudle. * @param instance module device instance * @return state true - ungated(Enabled), false - gated (Disabled) */ static inline bool CLOCK_SYS_GetFtmGateCmd(uint32_t instance) { return SIM_HAL_GetFtmGateCmd(g_simBaseAddr[0], instance); } /*! * @brief Enable the clock for PIT module. * * This function enables the clock for PIT moudle. * @param instance module device instance */ static inline void CLOCK_SYS_EnablePitClock(uint32_t instance) { SIM_HAL_EnablePitClock(g_simBaseAddr[0], instance); } /*! * @brief Disable the clock for PIT module. * * This function disables the clock for PIT moudle. * @param instance module device instance */ static inline void CLOCK_SYS_DisablePitClock(uint32_t instance) { SIM_HAL_DisablePitClock(g_simBaseAddr[0], instance); } /*! * @brief Get the the clock gate state for PIT module. * * This function will get the clock gate state for PIT moudle. * @param instance module device instance * @return state true - ungated(Enabled), false - gated (Disabled) */ static inline bool CLOCK_SYS_GetPitGateCmd(uint32_t instance) { return SIM_HAL_GetPitGateCmd(g_simBaseAddr[0], instance); } /*! * @brief Enable the clock for LPTIMER module. * * This function enables the clock for LPTIMER moudle. * @param instance module device instance */ static inline void CLOCK_SYS_EnableLptimerClock(uint32_t instance) { SIM_HAL_EnableLptimerClock(g_simBaseAddr[0], instance); } /*! * @brief Disable the clock for LPTIMER module. * * This function disables the clock for LPTIMER moudle. * @param instance module device instance */ static inline void CLOCK_SYS_DisableLptimerClock(uint32_t instance) { SIM_HAL_DisableLptimerClock(g_simBaseAddr[0], instance); } /*! * @brief Get the the clock gate state for LPTIMER module. * * This function will get the clock gate state for LPTIMER moudle. * @param instance module device instance * @return state true - ungated(Enabled), false - gated (Disabled) */ static inline bool CLOCK_SYS_GetLptimerGateCmd(uint32_t instance) { return SIM_HAL_GetLptimerGateCmd(g_simBaseAddr[0], instance); } /*! * @brief Enable the clock for CMT module. * * This function enables the clock for CMT moudle. * @param instance module device instance */ static inline void CLOCK_SYS_EnableCmtClock(uint32_t instance) { SIM_HAL_EnableCmtClock(g_simBaseAddr[0], instance); } /*! * @brief Disable the clock for CMT module. * * This function disables the clock for CMT moudle. * @param instance module device instance */ static inline void CLOCK_SYS_DisableCmtClock(uint32_t instance) { SIM_HAL_DisableCmtClock(g_simBaseAddr[0], instance); } /*! * @brief Get the the clock gate state for CMT module. * * This function will get the clock gate state for CMT moudle. * @param instance module device instance * @return state true - ungated(Enabled), false - gated (Disabled) */ static inline bool CLOCK_SYS_GetCmtGateCmd(uint32_t instance) { return SIM_HAL_GetCmtGateCmd(g_simBaseAddr[0], instance); } /*! * @brief Enable the clock for RTC module. * * This function enables the clock for RTC moudle. * @param instance module device instance */ static inline void CLOCK_SYS_EnableRtcClock(uint32_t instance) { SIM_HAL_EnableRtcClock(g_simBaseAddr[0], instance); } /*! * @brief Disable the clock for RTC module. * * This function disables the clock for RTC moudle. * @param instance module device instance */ static inline void CLOCK_SYS_DisableRtcClock(uint32_t instance) { SIM_HAL_DisableRtcClock(g_simBaseAddr[0], instance); } /*! * @brief Get the the clock gate state for RTC module. * * This function will get the clock gate state for RTC moudle. * @param instance module device instance * @return state true - ungated(Enabled), false - gated (Disabled) */ static inline bool CLOCK_SYS_GetRtcGateCmd(uint32_t instance) { return SIM_HAL_GetRtcGateCmd(g_simBaseAddr[0], instance); } /*! * @brief Enable the clock for ENET module. * * This function enables the clock for ENET moudle. * @param instance module device instance */ static inline void CLOCK_SYS_EnableEnetClock(uint32_t instance) { SIM_HAL_EnableEnetClock(g_simBaseAddr[0], instance); } /*! * @brief Disable the clock for ENET module. * * This function disables the clock for ENET moudle. * @param instance module device instance */ static inline void CLOCK_SYS_DisableEnetClock(uint32_t instance) { SIM_HAL_DisableEnetClock(g_simBaseAddr[0], instance); } /*! * @brief Get the the clock gate state for ENET module. * * This function will get the clock gate state for ENET moudle. * @param instance module device instance * @return state true - ungated(Enabled), false - gated (Disabled) */ static inline bool CLOCK_SYS_GetEnetGateCmd(uint32_t instance) { return SIM_HAL_GetEnetGateCmd(g_simBaseAddr[0], instance); } /*! * @brief Enable the clock for USBFS module. * * This function enables the clock for USBFS moudle. * @param instance module device instance */ static inline void CLOCK_SYS_EnableUsbClock(uint32_t instance) { SIM_HAL_EnableUsbClock(g_simBaseAddr[0], instance); } /*! * @brief Disable the clock for USBFS module. * * This function disables the clock for USBFS moudle. * @param instance module device instance */ static inline void CLOCK_SYS_DisableUsbClock(uint32_t instance) { SIM_HAL_DisableUsbClock(g_simBaseAddr[0], instance); } /*! * @brief Get the the clock gate state for USB module. * * This function will get the clock gate state for USB moudle. * @param instance module device instance * @return state true - ungated(Enabled), false - gated (Disabled) */ static inline bool CLOCK_SYS_GetUsbGateCmd(uint32_t instance) { return SIM_HAL_GetUsbGateCmd(g_simBaseAddr[0], instance); } /*! * @brief Enable the clock for USBDCD module. * * This function enables the clock for USBDCD moudle. * @param instance module device instance */ static inline void CLOCK_SYS_EnableUsbdcdClock(uint32_t instance) { SIM_HAL_EnableUsbdcdClock(g_simBaseAddr[0], instance); } /*! * @brief Disable the clock for USBDCD module. * * This function disables the clock for USBDCD moudle. * @param instance module device instance */ static inline void CLOCK_SYS_DisableUsbdcdClock(uint32_t instance) { SIM_HAL_DisableUsbdcdClock(g_simBaseAddr[0], instance); } /*! * @brief Get the the clock gate state for USBDCD module. * * This function will get the clock gate state for USBDCD moudle. * @param instance module device instance * @return state true - ungated(Enabled), false - gated (Disabled) */ static inline bool CLOCK_SYS_GetUsbdcdGateCmd(uint32_t instance) { return SIM_HAL_GetUsbdcdGateCmd(g_simBaseAddr[0], instance); } /*! * @brief Enable the clock for FLEXCAN module. * * This function enables the clock for FLEXCAN moudle. * @param instance module device instance */ static inline void CLOCK_SYS_EnableFlexcanClock(uint32_t instance) { SIM_HAL_EnableFlexcanClock(g_simBaseAddr[0], instance); } /*! * @brief Disable the clock for FLEXCAN module. * * This function disables the clock for FLEXCAN moudle. * @param instance module device instance */ static inline void CLOCK_SYS_DisableFlexcanClock(uint32_t instance) { SIM_HAL_DisableFlexcanClock(g_simBaseAddr[0], instance); } /*! * @brief Get the the clock gate state for FLEXCAN module. * * This function will get the clock gate state for FLEXCAN moudle. * @param instance module device instance * @return state true - ungated(Enabled), false - gated (Disabled) */ static inline bool CLOCK_SYS_GetFlexcanGateCmd(uint32_t instance) { return SIM_HAL_GetFlexcanGateCmd(g_simBaseAddr[0], instance); } /*! * @brief Enable the clock for SPI module. * * This function enables the clock for SPI moudle. * @param instance module device instance */ static inline void CLOCK_SYS_EnableSpiClock(uint32_t instance) { SIM_HAL_EnableSpiClock(g_simBaseAddr[0], instance); } /*! * @brief Disable the clock for SPI module. * * This function disables the clock for SPI moudle. * @param instance module device instance */ static inline void CLOCK_SYS_DisableSpiClock(uint32_t instance) { SIM_HAL_DisableSpiClock(g_simBaseAddr[0], instance); } /*! * @brief Get the the clock gate state for SPI module. * * This function will get the clock gate state for SPI moudle. * @param instance module device instance * @return state true - ungated(Enabled), false - gated (Disabled) */ static inline bool CLOCK_SYS_GetSpiGateCmd(uint32_t instance) { return SIM_HAL_GetSpiGateCmd(g_simBaseAddr[0], instance); } /*! * @brief Enable the clock for I2C module. * * This function enables the clock for I2C moudle. * @param instance module device instance */ static inline void CLOCK_SYS_EnableI2cClock(uint32_t instance) { SIM_HAL_EnableI2cClock(g_simBaseAddr[0], instance); } /*! * @brief Disable the clock for I2C module. * * This function disables the clock for I2C moudle. * @param instance module device instance */ static inline void CLOCK_SYS_DisableI2cClock(uint32_t instance) { SIM_HAL_DisableI2cClock(g_simBaseAddr[0], instance); } /*! * @brief Get the the clock gate state for I2C module. * * This function will get the clock gate state for I2C moudle. * @param instance module device instance * @return state true - ungated(Enabled), false - gated (Disabled) */ static inline bool CLOCK_SYS_GetI2cGateCmd(uint32_t instance) { return SIM_HAL_GetI2cGateCmd(g_simBaseAddr[0], instance); } /*! * @brief Enable the clock for UART module. * * This function enables the clock for UART moudle. * @param instance module device instance */ static inline void CLOCK_SYS_EnableUartClock(uint32_t instance) { SIM_HAL_EnableUartClock(g_simBaseAddr[0], instance); } /*! * @brief Disable the clock for UART module. * * This function disables the clock for UART moudle. * @param instance module device instance */ static inline void CLOCK_SYS_DisableUartClock(uint32_t instance) { SIM_HAL_DisableUartClock(g_simBaseAddr[0], instance); } /*! * @brief Get the the clock gate state for UART module. * * This function will get the clock gate state for UART moudle. * @param instance module device instance * @return state true - ungated(Enabled), false - gated (Disabled) */ static inline bool CLOCK_SYS_GetUartGateCmd(uint32_t instance) { return SIM_HAL_GetUartGateCmd(g_simBaseAddr[0], instance); } /*! * @brief Enable the clock for SDHC module. * * This function enables the clock for SDHC moudle. * @param instance module device instance */ static inline void CLOCK_SYS_EnableSdhcClock(uint32_t instance) { SIM_HAL_EnableSdhcClock(g_simBaseAddr[0], instance); } /*! * @brief Disable the clock for SDHC module. * * This function disables the clock for SDHC moudle. * @param instance module device instance */ static inline void CLOCK_SYS_DisableSdhcClock(uint32_t instance) { SIM_HAL_DisableSdhcClock(g_simBaseAddr[0], instance); } /*! * @brief Get the the clock gate state for SDHC module. * * This function will get the clock gate state for SDHC moudle. * @param instance module device instance * @return state true - ungated(Enabled), false - gated (Disabled) */ static inline bool CLOCK_SYS_GetSdhcGateCmd(uint32_t instance) { return SIM_HAL_GetSdhcGateCmd(g_simBaseAddr[0], instance); } #if defined(__cplusplus) } #endif /* __cplusplus*/ /*! @}*/ #endif /* __FSL_CLOCK_K64F12_H__ */ /******************************************************************************* * EOF ******************************************************************************/ ================================================ FILE: Zelig/mbed/TARGET_K64F/TARGET_Freescale/TARGET_KPSDK_MCUS/TARGET_MCU_K64F/MK64F12/fsl_sim_hal_K64F12.h ================================================ /* * Copyright (c) 2013 - 2014, Freescale Semiconductor, Inc. * All rights reserved. * * Redistribution and use in source and binary forms, with or without modification, * are permitted provided that the following conditions are met: * * o Redistributions of source code must retain the above copyright notice, this list * of conditions and the following disclaimer. * * o Redistributions in binary form must reproduce the above copyright notice, this * list of conditions and the following disclaimer in the documentation and/or * other materials provided with the distribution. * * o Neither the name of Freescale Semiconductor, Inc. nor the names of its * contributors may be used to endorse or promote products derived from this * software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT 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. */ #if !defined(__FSL_SIM_HAL_K64F12_H__) #define __FSL_SIM_HAL_K64F12_H__ /*! @addtogroup sim_hal*/ /*! @{*/ /*! @file*/ /******************************************************************************* * Definitions ******************************************************************************/ /*! @brief SIM SDHC clock source */ typedef enum _sim_sdhc_clock_source { kSimSdhcSrcCoreSysClk, /* Core/system clock */ kSimSdhcSrcPllFllSel, /* clock as selected by SOPT2[PLLFLLSEL]. */ kSimSdhcSrcOscerclk, /* OSCERCLK clock */ kSimSdhcSrcExt /* External bypass clock (SDHC0_CLKIN) */ } sim_sdhc_clock_source_t; /*! @brief SIM TIME clock source */ typedef enum _sim_time_clock_source { kSimTimeSrcCoreSysClk, /* Core/system clock */ kSimTimeSrcPllFllSel, /* clock as selected by SOPT2[PLLFLLSEL]. */ kSimTimeSrcOscerclk, /* OSCERCLK clock */ kSimTimeSrcExt /* ENET 1588 clock in (ENET_1588_CLKIN) */ } sim_time_clock_source_t; /*! @brief SIM RMII clock source */ typedef enum _sim_rmii_clock_source { kSimRmiiSrcExtalClk, /* EXTAL Clock */ kSimRmiiSrcExt /* ENET 1588 clock in (ENET_1588_CLKIN) */ } sim_rmii_clock_source_t; /*! @brief SIM USB clock source */ typedef enum _sim_usb_clock_source { kSimUsbSrcClkIn, /* USB CLKIN Clock */ kSimUsbSrcPllFllSel /* clock as selected by SOPT2[PLLFLLSEL] */ } sim_usb_clock_source_t; /*! @brief SIM PLLFLLSEL clock source select */ typedef enum _sim_pllfll_clock_sel { kSimPllFllSelFll, /* Fll clock */ kSimPllFllSelPll /* Pll0 clock */ } sim_pllfll_clock_sel_t; /*! @brief SIM OSC32KSEL clock source select */ typedef enum _sim_osc32k_clock_sel { kSimOsc32kSelOsc32k, /* OSC 32k clock */ kSimOsc32kSelReserved, /* Reserved */ kSimOsc32kSelRtc32k, /* RTC 32k clock */ kSimOsc32kSelLpo /* LPO clock */ } sim_osc32k_clock_sel_t; /*! @brief SIM TRACESEL clock source select */ typedef enum _sim_trace_clock_sel { kSimTraceMcgoutClk, /* MCG out clock */ kSimTraceCoreClk /* core clock */ } sim_trace_clock_sel_t; /*! @brief SIM CLKOUT_SEL clock source select */ typedef enum _sim_clkout_clock_sel { kSimClkoutFlexbusClk, /* Flexbus clock */ kSimClkoutReserved, /* Reserved */ kSimClkoutFlashClk, /* Flash clock */ kSimClkoutLpoClk, /* LPO clock */ kSimClkoutMcgIrcClk, /* MCG out clock */ kSimClkoutRtc32kClk, /* RTC 32k clock */ kSimClkoutReserved1 } sim_clkout_clock_sel_t; /*! @brief SIM RTCCLKOUTSEL clock source select */ typedef enum _sim_rtcclkout_clock_sel { kSimRtcClkout1hzClk, /* 1Hz clock */ kSimRtcClkout32kClk /* 32KHz clock */ } sim_rtcclkout_clock_sel_t; /******************************************************************************* * API ******************************************************************************/ #if defined(__cplusplus) extern "C" { #endif /* __cplusplus*/ /*! @name IP related clock feature APIs*/ /*@{*/ /*! * @brief Enable the clock for DMA module. * * This function enables the clock for DMA moudle. * * @param baseAddr Base address for current SIM instance. * @param instance module device instance */ void SIM_HAL_EnableDmaClock(uint32_t baseAddr, uint32_t instance); /*! * @brief Disable the clock for DMA module. * * This function disables the clock for DMA moudle. * * @param baseAddr Base address for current SIM instance. * @param instance module device instance */ void SIM_HAL_DisableDmaClock(uint32_t baseAddr, uint32_t instance); /*! * @brief Get the the clock gate state for DMA module. * * This function will get the clock gate state for DMA moudle. * * @param baseAddr Base address for current SIM instance. * @param instance module device instance * @return state true - ungated(Enabled), false - gated (Disabled) */ bool SIM_HAL_GetDmaGateCmd(uint32_t baseAddr, uint32_t instance); /*! * @brief Enable the clock for DMAMUX module. * * This function enables the clock for DMAMUX moudle. * * @param baseAddr Base address for current SIM instance. * @param instance module device instance */ void SIM_HAL_EnableDmamuxClock(uint32_t baseAddr, uint32_t instance); /*! * @brief Disable the clock for DMAMUX module. * * This function disables the clock for DMAMUX moudle. * * @param baseAddr Base address for current SIM instance. * @param instance module device instance */ void SIM_HAL_DisableDmamuxClock(uint32_t baseAddr, uint32_t instance); /*! * @brief Get the the clock gate state for DMAMUX module. * * This function will get the clock gate state for DMAMUX moudle. * * @param baseAddr Base address for current SIM instance. * @param instance module device instance * @return state true - ungated(Enabled), false - gated (Disabled) */ bool SIM_HAL_GetDmamuxGateCmd(uint32_t baseAddr, uint32_t instance); /*! * @brief Enable the clock for PORT module. * * This function enables the clock for PORT moudle. * * @param baseAddr Base address for current SIM instance. * @param instance module device instance */ void SIM_HAL_EnablePortClock(uint32_t baseAddr, uint32_t instance); /*! * @brief Disable the clock for PORT module. * * This function disables the clock for PORT moudle. * * @param baseAddr Base address for current SIM instance. * @param instance module device instance */ void SIM_HAL_DisablePortClock(uint32_t baseAddr, uint32_t instance); /*! * @brief Get the the clock gate state for PORT module. * * This function will get the clock gate state for PORT moudle. * * @param baseAddr Base address for current SIM instance. * @param instance module device instance * @return state true - ungated(Enabled), false - gated (Disabled) */ bool SIM_HAL_GetPortGateCmd(uint32_t baseAddr, uint32_t instance); /*! * @brief Enable the clock for MPU module. * * This function enables the clock for MPU moudle. * * @param baseAddr Base address for current SIM instance. * @param instance module device instance */ void SIM_HAL_EnableMpuClock(uint32_t baseAddr, uint32_t instance); /*! * @brief Disable the clock for MPU module. * * This function disables the clock for MPU moudle. * * @param baseAddr Base address for current SIM instance. * @param instance module device instance */ void SIM_HAL_DisableMpuClock(uint32_t baseAddr, uint32_t instance); /*! * @brief Get the the clock gate state for MPU module. * * This function will get the clock gate state for MPU moudle. * * @param baseAddr Base address for current SIM instance. * @param instance module device instance * @return state true - ungated(Enabled), false - gated (Disabled) */ bool SIM_HAL_GetMpuGateCmd(uint32_t baseAddr, uint32_t instance); /*! * @brief Enable the clock for EWM module. * * This function enables the clock for EWM moudle. * * @param baseAddr Base address for current SIM instance. * @param instance module device instance */ void SIM_HAL_EnableEwmClock(uint32_t baseAddr, uint32_t instance); /*! * @brief Disable the clock for EWM module. * * This function disables the clock for EWM moudle. * * @param baseAddr Base address for current SIM instance. * @param instance module device instance */ void SIM_HAL_DisableEwmClock(uint32_t baseAddr, uint32_t instance); /*! * @brief Get the the clock gate state for EWM module. * * This function will get the clock gate state for EWM moudle. * * @param baseAddr Base address for current SIM instance. * @param instance module device instance * @return state true - ungated(Enabled), false - gated (Disabled) */ bool SIM_HAL_GetEwmGateCmd(uint32_t baseAddr, uint32_t instance); /*! * @brief Enable the clock for FLEXBUS module. * * This function enables the clock for FLEXBUS moudle. * * @param baseAddr Base address for current SIM instance. * @param instance module device instance */ void SIM_HAL_EnableFlexbusClock(uint32_t baseAddr, uint32_t instance); /*! * @brief Disable the clock for FLEXBUS module. * * This function disables the clock for FLEXBUS moudle. * * @param baseAddr Base address for current SIM instance. * @param instance module device instance */ void SIM_HAL_DisableFlexbusClock(uint32_t baseAddr, uint32_t instance); /*! * @brief Get the the clock gate state for FLEXBUS module. * * This function will get the clock gate state for FLEXBUS moudle. * * @param baseAddr Base address for current SIM instance. * @param instance module device instance * @return state true - ungated(Enabled), false - gated (Disabled) */ bool SIM_HAL_GetFlexbusGateCmd(uint32_t baseAddr, uint32_t instance); /*! * @brief Enable the clock for FTF module. * * This function enables the clock for FTF moudle. * * @param baseAddr Base address for current SIM instance. * @param instance module device instance */ void SIM_HAL_EnableFtfClock(uint32_t baseAddr, uint32_t instance); /*! * @brief Disable the clock for FTF module. * * This function disables the clock for FTF moudle. * * @param baseAddr Base address for current SIM instance. * @param instance module device instance */ void SIM_HAL_DisableFtfClock(uint32_t baseAddr, uint32_t instance); /*! * @brief Get the the clock gate state for FTF module. * * This function will get the clock gate state for FTF moudle. * * @param baseAddr Base address for current SIM instance. * @param instance module device instance * @return state true - ungated(Enabled), false - gated (Disabled) */ bool SIM_HAL_GetFtfGateCmd(uint32_t baseAddr, uint32_t instance); /*! * @brief Enable the clock for CRC module. * * This function enables the clock for CRC moudle. * * @param baseAddr Base address for current SIM instance. * @param instance module device instance */ void SIM_HAL_EnableCrcClock(uint32_t baseAddr, uint32_t instance); /*! * @brief Disable the clock for CRC module. * * This function disables the clock for CRC moudle. * * @param baseAddr Base address for current SIM instance. * @param instance module device instance */ void SIM_HAL_DisableCrcClock(uint32_t baseAddr, uint32_t instance); /*! * @brief Get the the clock gate state for CRC module. * * This function will get the clock gate state for CRC moudle. * * @param baseAddr Base address for current SIM instance. * @param instance module device instance * @return state true - ungated(Enabled), false - gated (Disabled) */ bool SIM_HAL_GetCrcGateCmd(uint32_t baseAddr, uint32_t instance); /*! * @brief Enable the clock for RNGA module. * * This function enables the clock for RNGA moudle. * * @param baseAddr Base address for current SIM instance. * @param instance module device instance */ void SIM_HAL_EnableRngaClock(uint32_t baseAddr, uint32_t instance); /*! * @brief Disable the clock for RNGA module. * * This function disables the clock for RNGA moudle. * * @param baseAddr Base address for current SIM instance. * @param instance module device instance */ void SIM_HAL_DisableRngaClock(uint32_t baseAddr, uint32_t instance); /*! * @brief Get the the clock gate state for RNGA module. * * This function will get the clock gate state for RNGA moudle. * * @param baseAddr Base address for current SIM instance. * @param instance module device instance * @return state true - ungated(Enabled), false - gated (Disabled) */ bool SIM_HAL_GetRngaGateCmd(uint32_t baseAddr, uint32_t instance); /*! * @brief Enable the clock for ADC module. * * This function enables the clock for ADC moudle. * * @param baseAddr Base address for current SIM instance. * @param instance module device instance */ void SIM_HAL_EnableAdcClock(uint32_t baseAddr, uint32_t instance); /*! * @brief Disable the clock for ADC module. * * This function disables the clock for ADC moudle. * * @param baseAddr Base address for current SIM instance. * @param instance module device instance */ void SIM_HAL_DisableAdcClock(uint32_t baseAddr, uint32_t instance); /*! * @brief Get the the clock gate state for ADC module. * * This function will get the clock gate state for ADC moudle. * * @param baseAddr Base address for current SIM instance. * @param instance module device instance * @return state true - ungated(Enabled), false - gated (Disabled) */ bool SIM_HAL_GetAdcGateCmd(uint32_t baseAddr, uint32_t instance); /*! * @brief Enable the clock for CMP module. * * This function enables the clock for CMP moudle. * * @param baseAddr Base address for current SIM instance. * @param instance module device instance */ void SIM_HAL_EnableCmpClock(uint32_t baseAddr, uint32_t instance); /*! * @brief Disable the clock for CMP module. * * This function disables the clock for CMP moudle. * * @param baseAddr Base address for current SIM instance. * @param instance module device instance */ void SIM_HAL_DisableCmpClock(uint32_t baseAddr, uint32_t instance); /*! * @brief Get the the clock gate state for CMP module. * * This function will get the clock gate state for CMP moudle. * * @param baseAddr Base address for current SIM instance. * @param instance module device instance * @return state true - ungated(Enabled), false - gated (Disabled) */ bool SIM_HAL_GetCmpGateCmd(uint32_t baseAddr, uint32_t instance); /*! * @brief Enable the clock for DAC module. * * This function enables the clock for DAC moudle. * * @param baseAddr Base address for current SIM instance. * @param instance module device instance */ void SIM_HAL_EnableDacClock(uint32_t baseAddr, uint32_t instance); /*! * @brief Disable the clock for DAC module. * * This function disables the clock for DAC moudle. * * @param baseAddr Base address for current SIM instance. * @param instance module device instance */ void SIM_HAL_DisableDacClock(uint32_t baseAddr, uint32_t instance); /*! * @brief Get the the clock gate state for DAC module. * * This function will get the clock gate state for DAC moudle. * * @param baseAddr Base address for current SIM instance. * @param instance module device instance * @return state true - ungated(Enabled), false - gated (Disabled) */ bool SIM_HAL_GetDacGateCmd(uint32_t baseAddr, uint32_t instance); /*! * @brief Enable the clock for VREF module. * * This function enables the clock for VREF moudle. * * @param baseAddr Base address for current SIM instance. * @param instance module device instance */ void SIM_HAL_EnableVrefClock(uint32_t baseAddr, uint32_t instance); /*! * @brief Disable the clock for VREF module. * * This function disables the clock for VREF moudle. * * @param baseAddr Base address for current SIM instance. * @param instance module device instance */ void SIM_HAL_DisableVrefClock(uint32_t baseAddr, uint32_t instance); /*! * @brief Get the the clock gate state for VREF module. * * This function will get the clock gate state for VREF moudle. * * @param baseAddr Base address for current SIM instance. * @param instance module device instance * @return state true - ungated(Enabled), false - gated (Disabled) */ bool SIM_HAL_GetVrefGateCmd(uint32_t baseAddr, uint32_t instance); /*! * @brief Enable the clock for SAI module. * * This function enables the clock for SAI moudle. * * @param baseAddr Base address for current SIM instance. * @param instance module device instance */ void SIM_HAL_EnableSaiClock(uint32_t baseAddr, uint32_t instance); /*! * @brief Disable the clock for SAI module. * * This function disables the clock for SAI moudle. * * @param baseAddr Base address for current SIM instance. * @param instance module device instance */ void SIM_HAL_DisableSaiClock(uint32_t baseAddr, uint32_t instance); /*! * @brief Get the the clock gate state for SAI module. * * This function will get the clock gate state for SAI moudle. * * @param baseAddr Base address for current SIM instance. * @param instance module device instance * @return state true - ungated(Enabled), false - gated (Disabled) */ bool SIM_HAL_GetSaiGateCmd(uint32_t baseAddr, uint32_t instance); /*! * @brief Enable the clock for PDB module. * * This function enables the clock for PDB moudle. * * @param baseAddr Base address for current SIM instance. * @param instance module device instance */ void SIM_HAL_EnablePdbClock(uint32_t baseAddr, uint32_t instance); /*! * @brief Disable the clock for PDB module. * * This function disables the clock for PDB moudle. * * @param baseAddr Base address for current SIM instance. * @param instance module device instance */ void SIM_HAL_DisablePdbClock(uint32_t baseAddr, uint32_t instance); /*! * @brief Get the the clock gate state for PDB module. * * This function will get the clock gate state for PDB moudle. * * @param baseAddr Base address for current SIM instance. * @param instance module device instance * @return state true - ungated(Enabled), false - gated (Disabled) */ bool SIM_HAL_GetPdbGateCmd(uint32_t baseAddr, uint32_t instance); /*! * @brief Enable the clock for FTM module. * * This function enables the clock for FTM moudle. * * @param baseAddr Base address for current SIM instance. * @param instance module device instance */ void SIM_HAL_EnableFtmClock(uint32_t baseAddr, uint32_t instance); /*! * @brief Disable the clock for FTM module. * * This function disables the clock for FTM moudle. * * @param baseAddr Base address for current SIM instance. * @param instance module device instance */ void SIM_HAL_DisableFtmClock(uint32_t baseAddr, uint32_t instance); /*! * @brief Get the the clock gate state for FTM module. * * This function will get the clock gate state for FTM moudle. * * @param baseAddr Base address for current SIM instance. * @param instance module device instance * @return state true - ungated(Enabled), false - gated (Disabled) */ bool SIM_HAL_GetFtmGateCmd(uint32_t baseAddr, uint32_t instance); /*! * @brief Enable the clock for PIT module. * * This function enables the clock for PIT moudle. * * @param baseAddr Base address for current SIM instance. * @param instance module device instance */ void SIM_HAL_EnablePitClock(uint32_t baseAddr, uint32_t instance); /*! * @brief Disable the clock for PIT module. * * This function disables the clock for PIT moudle. * * @param baseAddr Base address for current SIM instance. * @param instance module device instance */ void SIM_HAL_DisablePitClock(uint32_t baseAddr, uint32_t instance); /*! * @brief Get the the clock gate state for PIT module. * * This function will get the clock gate state for PIT moudle. * * @param baseAddr Base address for current SIM instance. * @param instance module device instance * @return state true - ungated(Enabled), false - gated (Disabled) */ bool SIM_HAL_GetPitGateCmd(uint32_t baseAddr, uint32_t instance); /*! * @brief Enable the clock for LPTIMER module. * * This function enables the clock for LPTIMER moudle. * * @param baseAddr Base address for current SIM instance. * @param instance module device instance */ void SIM_HAL_EnableLptimerClock(uint32_t baseAddr, uint32_t instance); /*! * @brief Disable the clock for LPTIMER module. * * This function disables the clock for LPTIMER moudle. * * @param baseAddr Base address for current SIM instance. * @param instance module device instance */ void SIM_HAL_DisableLptimerClock(uint32_t baseAddr, uint32_t instance); /*! * @brief Get the the clock gate state for LPTIMER module. * * This function will get the clock gate state for LPTIMER moudle. * * @param baseAddr Base address for current SIM instance. * @param instance module device instance * @return state true - ungated(Enabled), false - gated (Disabled) */ bool SIM_HAL_GetLptimerGateCmd(uint32_t baseAddr, uint32_t instance); /*! * @brief Enable the clock for CMT module. * * This function enables the clock for CMT moudle. * * @param baseAddr Base address for current SIM instance. * @param instance module device instance */ void SIM_HAL_EnableCmtClock(uint32_t baseAddr, uint32_t instance); /*! * @brief Disable the clock for CMT module. * * This function disables the clock for CMT moudle. * * @param baseAddr Base address for current SIM instance. * @param instance module device instance */ void SIM_HAL_DisableCmtClock(uint32_t baseAddr, uint32_t instance); /*! * @brief Get the the clock gate state for CMT module. * * This function will get the clock gate state for CMT moudle. * * @param baseAddr Base address for current SIM instance. * @param instance module device instance * @return state true - ungated(Enabled), false - gated (Disabled) */ bool SIM_HAL_GetCmtGateCmd(uint32_t baseAddr, uint32_t instance); /*! * @brief Enable the clock for RTC module. * * This function enables the clock for RTC moudle. * * @param baseAddr Base address for current SIM instance. * @param instance module device instance */ void SIM_HAL_EnableRtcClock(uint32_t baseAddr, uint32_t instance); /*! * @brief Disable the clock for RTC module. * * This function disables the clock for RTC moudle. * * @param baseAddr Base address for current SIM instance. * @param instance module device instance */ void SIM_HAL_DisableRtcClock(uint32_t baseAddr, uint32_t instance); /*! * @brief Get the the clock gate state for RTC module. * * This function will get the clock gate state for RTC moudle. * * @param baseAddr Base address for current SIM instance. * @param instance module device instance * @return state true - ungated(Enabled), false - gated (Disabled) */ bool SIM_HAL_GetRtcGateCmd(uint32_t baseAddr, uint32_t instance); /*! * @brief Enable the clock for ENET module. * * This function enables the clock for ENET moudle. * * @param baseAddr Base address for current SIM instance. * @param instance module device instance */ void SIM_HAL_EnableEnetClock(uint32_t baseAddr, uint32_t instance); /*! * @brief Disable the clock for ENET module. * * This function disables the clock for ENET moudle. * * @param baseAddr Base address for current SIM instance. * @param instance module device instance */ void SIM_HAL_DisableEnetClock(uint32_t baseAddr, uint32_t instance); /*! * @brief Get the the clock gate state for ENET module. * * This function will get the clock gate state for ENET moudle. * * @param baseAddr Base address for current SIM instance. * @param instance module device instance * @return state true - ungated(Enabled), false - gated (Disabled) */ bool SIM_HAL_GetEnetGateCmd(uint32_t baseAddr, uint32_t instance); /*! * @brief Enable the clock for USBFS module. * * This function enables the clock for USBFS moudle. * * @param baseAddr Base address for current SIM instance. * @param instance module device instance */ void SIM_HAL_EnableUsbClock(uint32_t baseAddr, uint32_t instance); /*! * @brief Disable the clock for USBFS module. * * This function disables the clock for USBFS moudle. * * @param baseAddr Base address for current SIM instance. * @param instance module device instance */ void SIM_HAL_DisableUsbClock(uint32_t baseAddr, uint32_t instance); /*! * @brief Get the the clock gate state for USB module. * * This function will get the clock gate state for USB moudle. * * @param baseAddr Base address for current SIM instance. * @param instance module device instance * @return state true - ungated(Enabled), false - gated (Disabled) */ bool SIM_HAL_GetUsbGateCmd(uint32_t baseAddr, uint32_t instance); /*! * @brief Enable the clock for USBDCD module. * * This function enables the clock for USBDCD moudle. * * @param baseAddr Base address for current SIM instance. * @param instance module device instance */ void SIM_HAL_EnableUsbdcdClock(uint32_t baseAddr, uint32_t instance); /*! * @brief Disable the clock for USBDCD module. * * This function disables the clock for USBDCD moudle. * * @param baseAddr Base address for current SIM instance. * @param instance module device instance */ void SIM_HAL_DisableUsbdcdClock(uint32_t baseAddr, uint32_t instance); /*! * @brief Get the the clock gate state for USBDCD module. * * This function will get the clock gate state for USBDCD moudle. * * @param baseAddr Base address for current SIM instance. * @param instance module device instance * @return state true - ungated(Enabled), false - gated (Disabled) */ bool SIM_HAL_GetUsbdcdGateCmd(uint32_t baseAddr, uint32_t instance); /*! * @brief Enable the clock for FLEXCAN module. * * This function enables the clock for FLEXCAN moudle. * * @param baseAddr Base address for current SIM instance. * @param instance module device instance */ void SIM_HAL_EnableFlexcanClock(uint32_t baseAddr, uint32_t instance); /*! * @brief Disable the clock for FLEXCAN module. * * This function disables the clock for FLEXCAN moudle. * * @param baseAddr Base address for current SIM instance. * @param instance module device instance */ void SIM_HAL_DisableFlexcanClock(uint32_t baseAddr, uint32_t instance); /*! * @brief Get the the clock gate state for FLEXCAN module. * * This function will get the clock gate state for FLEXCAN moudle. * * @param baseAddr Base address for current SIM instance. * @param instance module device instance * @return state true - ungated(Enabled), false - gated (Disabled) */ bool SIM_HAL_GetFlexcanGateCmd(uint32_t baseAddr, uint32_t instance); /*! * @brief Enable the clock for SPI module. * * This function enables the clock for SPI moudle. * * @param baseAddr Base address for current SIM instance. * @param instance module device instance */ void SIM_HAL_EnableSpiClock(uint32_t baseAddr, uint32_t instance); /*! * @brief Disable the clock for SPI module. * * This function disables the clock for SPI moudle. * * @param baseAddr Base address for current SIM instance. * @param instance module device instance */ void SIM_HAL_DisableSpiClock(uint32_t baseAddr, uint32_t instance); /*! * @brief Get the the clock gate state for SPI module. * * This function will get the clock gate state for SPI moudle. * * @param baseAddr Base address for current SIM instance. * @param instance module device instance * @return state true - ungated(Enabled), false - gated (Disabled) */ bool SIM_HAL_GetSpiGateCmd(uint32_t baseAddr, uint32_t instance); /*! * @brief Enable the clock for I2C module. * * This function enables the clock for I2C moudle. * * @param baseAddr Base address for current SIM instance. * @param instance module device instance */ void SIM_HAL_EnableI2cClock(uint32_t baseAddr, uint32_t instance); /*! * @brief Disable the clock for I2C module. * * This function disables the clock for I2C moudle. * * @param baseAddr Base address for current SIM instance. * @param instance module device instance */ void SIM_HAL_DisableI2cClock(uint32_t baseAddr, uint32_t instance); /*! * @brief Get the the clock gate state for I2C module. * * This function will get the clock gate state for I2C moudle. * * @param baseAddr Base address for current SIM instance. * @param instance module device instance * @return state true - ungated(Enabled), false - gated (Disabled) */ bool SIM_HAL_GetI2cGateCmd(uint32_t baseAddr, uint32_t instance); /*! * @brief Enable the clock for UART module. * * This function enables the clock for UART moudle. * * @param baseAddr Base address for current SIM instance. * @param instance module device instance */ void SIM_HAL_EnableUartClock(uint32_t baseAddr, uint32_t instance); /*! * @brief Disable the clock for UART module. * * This function disables the clock for UART moudle. * * @param baseAddr Base address for current SIM instance. * @param instance module device instance */ void SIM_HAL_DisableUartClock(uint32_t baseAddr, uint32_t instance); /*! * @brief Get the the clock gate state for UART module. * * This function will get the clock gate state for UART moudle. * * @param baseAddr Base address for current SIM instance. * @param instance module device instance * @return state true - ungated(Enabled), false - gated (Disabled) */ bool SIM_HAL_GetUartGateCmd(uint32_t baseAddr, uint32_t instance); /*! * @brief Enable the clock for SDHC module. * * This function enables the clock for SDHC moudle. * * @param baseAddr Base address for current SIM instance. * @param instance module device instance */ void SIM_HAL_EnableSdhcClock(uint32_t baseAddr, uint32_t instance); /*! * @brief Disable the clock for SDHC module. * * This function disables the clock for SDHC moudle. * * @param baseAddr Base address for current SIM instance. * @param instance module device instance */ void SIM_HAL_DisableSdhcClock(uint32_t baseAddr, uint32_t instance); /*! * @brief Get the the clock gate state for SDHC module. * * This function will get the clock gate state for SDHC moudle. * * @param baseAddr Base address for current SIM instance. * @param instance module device instance * @return state true - ungated(Enabled), false - gated (Disabled) */ bool SIM_HAL_GetSdhcGateCmd(uint32_t baseAddr, uint32_t instance); /*@}*/ #if defined(__cplusplus) } #endif /* __cplusplus*/ /*! @}*/ #endif /* __FSL_SIM_HAL_K64F12_H__*/ /******************************************************************************* * EOF ******************************************************************************/ ================================================ FILE: Zelig/mbed/TARGET_K64F/TARGET_Freescale/TARGET_KPSDK_MCUS/TARGET_MCU_K64F/TARGET_FRDM/PeripheralNames.h ================================================ /* mbed Microcontroller Library * Copyright (c) 2006-2013 ARM Limited * * 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 MBED_PERIPHERALNAMES_H #define MBED_PERIPHERALNAMES_H #include "cmsis.h" #ifdef __cplusplus extern "C" { #endif typedef enum { OSC32KCLK = 0, } RTCName; typedef enum { UART_0 = 0, UART_1 = 1, UART_2 = 2, UART_3 = 3, UART_4 = 4, } UARTName; #define STDIO_UART_TX USBTX #define STDIO_UART_RX USBRX #define STDIO_UART UART_0 typedef enum { I2C_0 = 0, I2C_1 = 1, I2C_2 = 2, } I2CName; #define TPM_SHIFT 8 typedef enum { PWM_1 = (0 << TPM_SHIFT) | (0), // FTM0 CH0 PWM_2 = (0 << TPM_SHIFT) | (1), // FTM0 CH1 PWM_3 = (0 << TPM_SHIFT) | (2), // FTM0 CH2 PWM_4 = (0 << TPM_SHIFT) | (3), // FTM0 CH3 PWM_5 = (0 << TPM_SHIFT) | (4), // FTM0 CH4 PWM_6 = (0 << TPM_SHIFT) | (5), // FTM0 CH5 PWM_7 = (0 << TPM_SHIFT) | (6), // FTM0 CH6 PWM_8 = (0 << TPM_SHIFT) | (7), // FTM0 CH7 PWM_9 = (1 << TPM_SHIFT) | (0), // FTM1 CH0 PWM_10 = (1 << TPM_SHIFT) | (1), // FTM1 CH1 PWM_11 = (1 << TPM_SHIFT) | (2), // FTM1 CH2 PWM_12 = (1 << TPM_SHIFT) | (3), // FTM1 CH3 PWM_13 = (1 << TPM_SHIFT) | (4), // FTM1 CH4 PWM_14 = (1 << TPM_SHIFT) | (5), // FTM1 CH5 PWM_15 = (1 << TPM_SHIFT) | (6), // FTM1 CH6 PWM_16 = (1 << TPM_SHIFT) | (7), // FTM1 CH7 PWM_17 = (2 << TPM_SHIFT) | (0), // FTM2 CH0 PWM_18 = (2 << TPM_SHIFT) | (1), // FTM2 CH1 PWM_19 = (2 << TPM_SHIFT) | (2), // FTM2 CH2 PWM_20 = (2 << TPM_SHIFT) | (3), // FTM2 CH3 PWM_21 = (2 << TPM_SHIFT) | (4), // FTM2 CH4 PWM_22 = (2 << TPM_SHIFT) | (5), // FTM2 CH5 PWM_23 = (2 << TPM_SHIFT) | (6), // FTM2 CH6 PWM_24 = (2 << TPM_SHIFT) | (7), // FTM2 CH7 // could be 4 or could be 3... not sure what register // this is for... too much abstraction PWM_25 = (3 << TPM_SHIFT) | (0), // FTM3 CH0 PWM_26 = (3 << TPM_SHIFT) | (1), // FTM3 CH1 PWM_27 = (3 << TPM_SHIFT) | (2), // FTM3 CH2 PWM_28 = (3 << TPM_SHIFT) | (3), // FTM3 CH3 PWM_29 = (3 << TPM_SHIFT) | (4), // FTM3 CH4 PWM_30 = (3 << TPM_SHIFT) | (5), // FTM3 CH5 PWM_31 = (3 << TPM_SHIFT) | (6), // FTM3 CH6 PWM_32 = (3 << TPM_SHIFT) | (7), // FTM3 CH7 } PWMName; #define ADC_INSTANCE_SHIFT 8 #define ADC_B_CHANNEL_SHIFT 5 typedef enum { ADC0_SE4b = (0 << ADC_INSTANCE_SHIFT) | (1 << ADC_B_CHANNEL_SHIFT) | 4, ADC0_SE5b = (0 << ADC_INSTANCE_SHIFT) | (1 << ADC_B_CHANNEL_SHIFT) | 5, ADC0_SE6b = (0 << ADC_INSTANCE_SHIFT) | (1 << ADC_B_CHANNEL_SHIFT) | 6, ADC0_SE7b = (0 << ADC_INSTANCE_SHIFT) | (1 << ADC_B_CHANNEL_SHIFT) | 7, ADC0_SE8 = (0 << ADC_INSTANCE_SHIFT) | 8, ADC0_SE9 = (0 << ADC_INSTANCE_SHIFT) | 9, ADC0_SE12 = (0 << ADC_INSTANCE_SHIFT) | 12, ADC0_SE13 = (0 << ADC_INSTANCE_SHIFT) | 13, ADC0_SE14 = (0 << ADC_INSTANCE_SHIFT) | 14, ADC0_SE15 = (0 << ADC_INSTANCE_SHIFT) | 15, ADC0_SE16 = (0 << ADC_INSTANCE_SHIFT) | 16, ADC0_SE17 = (0 << ADC_INSTANCE_SHIFT) | 17, ADC0_SE18 = (0 << ADC_INSTANCE_SHIFT) | 18, ADC1_SE4b = (1 << ADC_INSTANCE_SHIFT) | 4, ADC1_SE5b = (1 << ADC_INSTANCE_SHIFT) | 5, ADC1_SE6b = (1 << ADC_INSTANCE_SHIFT) | 6, ADC1_SE7b = (1 << ADC_INSTANCE_SHIFT) | 7, ADC1_SE8 = (1 << ADC_INSTANCE_SHIFT) | 8, ADC1_SE9 = (1 << ADC_INSTANCE_SHIFT) | 9, ADC1_SE12 = (1 << ADC_INSTANCE_SHIFT) | 12, ADC1_SE13 = (1 << ADC_INSTANCE_SHIFT) | 13, ADC1_SE14 = (1 << ADC_INSTANCE_SHIFT) | 14, ADC1_SE15 = (1 << ADC_INSTANCE_SHIFT) | 15, ADC1_SE16 = (1 << ADC_INSTANCE_SHIFT) | 16, ADC1_SE17 = (1 << ADC_INSTANCE_SHIFT) | 17, ADC1_SE18 = (1 << ADC_INSTANCE_SHIFT) | 18, } ADCName; typedef enum { DAC_0 = 0 } DACName; typedef enum { SPI_0 = 0, SPI_1 = 1, SPI_2 = 2, } SPIName; #ifdef __cplusplus } #endif #endif ================================================ FILE: Zelig/mbed/TARGET_K64F/TARGET_Freescale/TARGET_KPSDK_MCUS/TARGET_MCU_K64F/TARGET_FRDM/PinNames.h ================================================ /* mbed Microcontroller Library * Copyright (c) 2006-2013 ARM Limited * * 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 MBED_PINNAMES_H #define MBED_PINNAMES_H #include "cmsis.h" #ifdef __cplusplus extern "C" { #endif typedef enum { PIN_INPUT, PIN_OUTPUT } PinDirection; #define GPIO_PORT_SHIFT 12 typedef enum { PTA0 = (0 << GPIO_PORT_SHIFT | 0 ), PTA1 = (0 << GPIO_PORT_SHIFT | 1 ), PTA2 = (0 << GPIO_PORT_SHIFT | 2 ), PTA3 = (0 << GPIO_PORT_SHIFT | 3 ), PTA4 = (0 << GPIO_PORT_SHIFT | 4 ), PTA5 = (0 << GPIO_PORT_SHIFT | 5 ), PTA6 = (0 << GPIO_PORT_SHIFT | 6 ), PTA7 = (0 << GPIO_PORT_SHIFT | 7 ), PTA8 = (0 << GPIO_PORT_SHIFT | 8 ), PTA9 = (0 << GPIO_PORT_SHIFT | 9 ), PTA10 = (0 << GPIO_PORT_SHIFT | 10), PTA11 = (0 << GPIO_PORT_SHIFT | 11), PTA12 = (0 << GPIO_PORT_SHIFT | 12), PTA13 = (0 << GPIO_PORT_SHIFT | 13), PTA14 = (0 << GPIO_PORT_SHIFT | 14), PTA15 = (0 << GPIO_PORT_SHIFT | 15), PTA16 = (0 << GPIO_PORT_SHIFT | 16), PTA17 = (0 << GPIO_PORT_SHIFT | 17), PTA18 = (0 << GPIO_PORT_SHIFT | 18), PTA19 = (0 << GPIO_PORT_SHIFT | 19), PTA20 = (0 << GPIO_PORT_SHIFT | 20), PTA21 = (0 << GPIO_PORT_SHIFT | 21), PTA22 = (0 << GPIO_PORT_SHIFT | 22), PTA23 = (0 << GPIO_PORT_SHIFT | 23), PTA24 = (0 << GPIO_PORT_SHIFT | 24), PTA25 = (0 << GPIO_PORT_SHIFT | 25), PTA26 = (0 << GPIO_PORT_SHIFT | 26), PTA27 = (0 << GPIO_PORT_SHIFT | 27), PTA28 = (0 << GPIO_PORT_SHIFT | 28), PTA29 = (0 << GPIO_PORT_SHIFT | 29), PTA30 = (0 << GPIO_PORT_SHIFT | 30), PTA31 = (0 << GPIO_PORT_SHIFT | 31), PTB0 = (1 << GPIO_PORT_SHIFT | 0 ), PTB1 = (1 << GPIO_PORT_SHIFT | 1 ), PTB2 = (1 << GPIO_PORT_SHIFT | 2 ), PTB3 = (1 << GPIO_PORT_SHIFT | 3 ), PTB4 = (1 << GPIO_PORT_SHIFT | 4 ), PTB5 = (1 << GPIO_PORT_SHIFT | 5 ), PTB6 = (1 << GPIO_PORT_SHIFT | 6 ), PTB7 = (1 << GPIO_PORT_SHIFT | 7 ), PTB8 = (1 << GPIO_PORT_SHIFT | 8 ), PTB9 = (1 << GPIO_PORT_SHIFT | 9 ), PTB10 = (1 << GPIO_PORT_SHIFT | 10), PTB11 = (1 << GPIO_PORT_SHIFT | 11), PTB12 = (1 << GPIO_PORT_SHIFT | 12), PTB13 = (1 << GPIO_PORT_SHIFT | 13), PTB14 = (1 << GPIO_PORT_SHIFT | 14), PTB15 = (1 << GPIO_PORT_SHIFT | 15), PTB16 = (1 << GPIO_PORT_SHIFT | 16), PTB17 = (1 << GPIO_PORT_SHIFT | 17), PTB18 = (1 << GPIO_PORT_SHIFT | 18), PTB19 = (1 << GPIO_PORT_SHIFT | 19), PTB20 = (1 << GPIO_PORT_SHIFT | 20), PTB21 = (1 << GPIO_PORT_SHIFT | 21), PTB22 = (1 << GPIO_PORT_SHIFT | 22), PTB23 = (1 << GPIO_PORT_SHIFT | 23), PTB24 = (1 << GPIO_PORT_SHIFT | 24), PTB25 = (1 << GPIO_PORT_SHIFT | 25), PTB26 = (1 << GPIO_PORT_SHIFT | 26), PTB27 = (1 << GPIO_PORT_SHIFT | 27), PTB28 = (1 << GPIO_PORT_SHIFT | 28), PTB29 = (1 << GPIO_PORT_SHIFT | 29), PTB30 = (1 << GPIO_PORT_SHIFT | 30), PTB31 = (1 << GPIO_PORT_SHIFT | 31), PTC0 = (2 << GPIO_PORT_SHIFT | 0 ), PTC1 = (2 << GPIO_PORT_SHIFT | 1 ), PTC2 = (2 << GPIO_PORT_SHIFT | 2 ), PTC3 = (2 << GPIO_PORT_SHIFT | 3 ), PTC4 = (2 << GPIO_PORT_SHIFT | 4 ), PTC5 = (2 << GPIO_PORT_SHIFT | 5 ), PTC6 = (2 << GPIO_PORT_SHIFT | 6 ), PTC7 = (2 << GPIO_PORT_SHIFT | 7 ), PTC8 = (2 << GPIO_PORT_SHIFT | 8 ), PTC9 = (2 << GPIO_PORT_SHIFT | 9 ), PTC10 = (2 << GPIO_PORT_SHIFT | 10), PTC11 = (2 << GPIO_PORT_SHIFT | 11), PTC12 = (2 << GPIO_PORT_SHIFT | 12), PTC13 = (2 << GPIO_PORT_SHIFT | 13), PTC14 = (2 << GPIO_PORT_SHIFT | 14), PTC15 = (2 << GPIO_PORT_SHIFT | 15), PTC16 = (2 << GPIO_PORT_SHIFT | 16), PTC17 = (2 << GPIO_PORT_SHIFT | 17), PTC18 = (2 << GPIO_PORT_SHIFT | 18), PTC19 = (2 << GPIO_PORT_SHIFT | 19), PTC20 = (2 << GPIO_PORT_SHIFT | 20), PTC21 = (2 << GPIO_PORT_SHIFT | 21), PTC22 = (2 << GPIO_PORT_SHIFT | 22), PTC23 = (2 << GPIO_PORT_SHIFT | 23), PTC24 = (2 << GPIO_PORT_SHIFT | 24), PTC25 = (2 << GPIO_PORT_SHIFT | 25), PTC26 = (2 << GPIO_PORT_SHIFT | 26), PTC27 = (2 << GPIO_PORT_SHIFT | 27), PTC28 = (2 << GPIO_PORT_SHIFT | 28), PTC29 = (2 << GPIO_PORT_SHIFT | 29), PTC30 = (2 << GPIO_PORT_SHIFT | 30), PTC31 = (2 << GPIO_PORT_SHIFT | 31), PTD0 = (3 << GPIO_PORT_SHIFT | 0 ), PTD1 = (3 << GPIO_PORT_SHIFT | 1 ), PTD2 = (3 << GPIO_PORT_SHIFT | 2 ), PTD3 = (3 << GPIO_PORT_SHIFT | 3 ), PTD4 = (3 << GPIO_PORT_SHIFT | 4 ), PTD5 = (3 << GPIO_PORT_SHIFT | 5 ), PTD6 = (3 << GPIO_PORT_SHIFT | 6 ), PTD7 = (3 << GPIO_PORT_SHIFT | 7 ), PTD8 = (3 << GPIO_PORT_SHIFT | 8 ), PTD9 = (3 << GPIO_PORT_SHIFT | 9 ), PTD10 = (3 << GPIO_PORT_SHIFT | 10), PTD11 = (3 << GPIO_PORT_SHIFT | 11), PTD12 = (3 << GPIO_PORT_SHIFT | 12), PTD13 = (3 << GPIO_PORT_SHIFT | 13), PTD14 = (3 << GPIO_PORT_SHIFT | 14), PTD15 = (3 << GPIO_PORT_SHIFT | 15), PTD16 = (3 << GPIO_PORT_SHIFT | 16), PTD17 = (3 << GPIO_PORT_SHIFT | 17), PTD18 = (3 << GPIO_PORT_SHIFT | 18), PTD19 = (3 << GPIO_PORT_SHIFT | 19), PTD20 = (3 << GPIO_PORT_SHIFT | 20), PTD21 = (3 << GPIO_PORT_SHIFT | 21), PTD22 = (3 << GPIO_PORT_SHIFT | 22), PTD23 = (3 << GPIO_PORT_SHIFT | 23), PTD24 = (3 << GPIO_PORT_SHIFT | 24), PTD25 = (3 << GPIO_PORT_SHIFT | 25), PTD26 = (3 << GPIO_PORT_SHIFT | 26), PTD27 = (3 << GPIO_PORT_SHIFT | 27), PTD28 = (3 << GPIO_PORT_SHIFT | 28), PTD29 = (3 << GPIO_PORT_SHIFT | 29), PTD30 = (3 << GPIO_PORT_SHIFT | 30), PTD31 = (3 << GPIO_PORT_SHIFT | 31), PTE0 = (4 << GPIO_PORT_SHIFT | 0 ), PTE1 = (4 << GPIO_PORT_SHIFT | 1 ), PTE2 = (4 << GPIO_PORT_SHIFT | 2 ), PTE3 = (4 << GPIO_PORT_SHIFT | 3 ), PTE4 = (4 << GPIO_PORT_SHIFT | 4 ), PTE5 = (4 << GPIO_PORT_SHIFT | 5 ), PTE6 = (4 << GPIO_PORT_SHIFT | 6 ), PTE7 = (4 << GPIO_PORT_SHIFT | 7 ), PTE8 = (4 << GPIO_PORT_SHIFT | 8 ), PTE9 = (4 << GPIO_PORT_SHIFT | 9 ), PTE10 = (4 << GPIO_PORT_SHIFT | 10), PTE11 = (4 << GPIO_PORT_SHIFT | 11), PTE12 = (4 << GPIO_PORT_SHIFT | 12), PTE13 = (4 << GPIO_PORT_SHIFT | 13), PTE14 = (4 << GPIO_PORT_SHIFT | 14), PTE15 = (4 << GPIO_PORT_SHIFT | 15), PTE16 = (4 << GPIO_PORT_SHIFT | 16), PTE17 = (4 << GPIO_PORT_SHIFT | 17), PTE18 = (4 << GPIO_PORT_SHIFT | 18), PTE19 = (4 << GPIO_PORT_SHIFT | 19), PTE20 = (4 << GPIO_PORT_SHIFT | 20), PTE21 = (4 << GPIO_PORT_SHIFT | 21), PTE22 = (4 << GPIO_PORT_SHIFT | 22), PTE23 = (4 << GPIO_PORT_SHIFT | 23), PTE24 = (4 << GPIO_PORT_SHIFT | 24), PTE25 = (4 << GPIO_PORT_SHIFT | 25), PTE26 = (4 << GPIO_PORT_SHIFT | 26), PTE27 = (4 << GPIO_PORT_SHIFT | 27), PTE28 = (4 << GPIO_PORT_SHIFT | 28), PTE29 = (4 << GPIO_PORT_SHIFT | 29), PTE30 = (4 << GPIO_PORT_SHIFT | 30), PTE31 = (4 << GPIO_PORT_SHIFT | 31), LED_RED = PTB22, LED_GREEN = PTE26, LED_BLUE = PTB21, // mbed original LED naming LED1 = LED_RED, LED2 = LED_GREEN, LED3 = LED_BLUE, LED4 = LED_RED, //Push buttons SW2 = PTC6, SW3 = PTA4, // USB Pins USBTX = PTB17, USBRX = PTB16, // Arduino Headers D0 = PTC16, D1 = PTC17, D2 = PTB9, D3 = PTA1, D4 = PTB23, D5 = PTA2, D6 = PTC2, D7 = PTC3, D8 = PTA0, D9 = PTC4, D10 = PTD0, D11 = PTD2, D12 = PTD3, D13 = PTD1, D14 = PTE25, D15 = PTE24, I2C_SCL = D15, I2C_SDA = D14, A0 = PTB2, A1 = PTB3, A2 = PTB10, A3 = PTB11, A4 = PTC11, A5 = PTC10, DAC0_OUT = 0xFEFE, /* DAC does not have Pin Name in RM */ // Not connected NC = (int)0xFFFFFFFF } PinName; typedef enum { PullNone = 0, PullDown = 1, PullUp = 2, PullDefault = PullUp } PinMode; #ifdef __cplusplus } #endif #endif ================================================ FILE: Zelig/mbed/TARGET_K64F/TARGET_Freescale/TARGET_KPSDK_MCUS/TARGET_MCU_K64F/TARGET_FRDM/crc.h ================================================ /********************************************************************** * * Filename: crc.h * * Description: A header file describing the various CRC standards. * * Notes: * * * Copyright (c) 2000 by Michael Barr. This software is placed into * the public domain and may be used for any purpose. However, this * notice must not be changed or removed and no warranty is either * expressed or implied by its publication or distribution. **********************************************************************/ #ifndef _crc_h #define _crc_h #define FALSE 0 #define TRUE !FALSE /* * Select the CRC standard from the list that follows. */ #define CRC16 #if defined(CRC_CCITT) typedef unsigned short crc; #define CRC_NAME "CRC-CCITT" #define POLYNOMIAL 0x1021 #define INITIAL_REMAINDER 0xFFFF #define FINAL_XOR_VALUE 0x0000 #define REFLECT_DATA FALSE #define REFLECT_REMAINDER FALSE #define CHECK_VALUE 0x29B1 #elif defined(CRC16) typedef unsigned short crc; #define CRC_NAME "CRC-16" #define POLYNOMIAL 0x8005 #define INITIAL_REMAINDER 0x0000 #define FINAL_XOR_VALUE 0x0000 #define REFLECT_DATA TRUE #define REFLECT_REMAINDER TRUE #define CHECK_VALUE 0xBB3D #elif defined(CRC32) typedef unsigned long crc; #define CRC_NAME "CRC-32" #define POLYNOMIAL 0x04C11DB7 #define INITIAL_REMAINDER 0xFFFFFFFF #define FINAL_XOR_VALUE 0xFFFFFFFF #define REFLECT_DATA TRUE #define REFLECT_REMAINDER TRUE #define CHECK_VALUE 0xCBF43926 #else #error "One of CRC_CCITT, CRC16, or CRC32 must be #define'd." #endif void crcInit(void); crc crcSlow(unsigned char const message[], int nBytes); crc crcFast(unsigned char const message[], int nBytes); #endif /* _crc_h */ ================================================ FILE: Zelig/mbed/TARGET_K64F/TARGET_Freescale/TARGET_KPSDK_MCUS/TARGET_MCU_K64F/TARGET_FRDM/device.h ================================================ /* mbed Microcontroller Library * Copyright (c) 2006-2013 ARM Limited * * 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 MBED_DEVICE_H #define MBED_DEVICE_H #define DEVICE_PORTIN 1 #define DEVICE_PORTOUT 1 #define DEVICE_PORTINOUT 1 #define DEVICE_INTERRUPTIN 1 #define DEVICE_ANALOGIN 1 #define DEVICE_ANALOGOUT 1 #define DEVICE_SERIAL 1 #define DEVICE_I2C 1 #define DEVICE_I2CSLAVE 1 #define DEVICE_SPI 1 #define DEVICE_SPISLAVE 1 #define DEVICE_CAN 0 #define DEVICE_RTC 1 #define DEVICE_ETHERNET 0 #define DEVICE_PWMOUT 1 #define DEVICE_SEMIHOST 0 #define DEVICE_LOCALFILESYSTEM 0 #define DEVICE_ID_LENGTH 24 #define DEVICE_SLEEP 1 #define DEVICE_DEBUG_AWARENESS 0 #define DEVICE_STDIO_MESSAGES 1 #define DEVICE_ERROR_RED 1 #include "objects.h" #endif ================================================ FILE: Zelig/mbed/TARGET_K64F/TARGET_Freescale/TARGET_KPSDK_MCUS/TARGET_MCU_K64F/device/MK64F12/fsl_bitaccess.h ================================================ /* ** ################################################################### ** Version: rev. 2.5, 2014-02-10 ** Build: b140604 ** ** Abstract: ** Register bit field access macros. ** ** Copyright (c) 2014 Freescale Semiconductor, Inc. ** All rights reserved. ** ** Redistribution and use in source and binary forms, with or without modification, ** are permitted provided that the following conditions are met: ** ** o Redistributions of source code must retain the above copyright notice, this list ** of conditions and the following disclaimer. ** ** o Redistributions in binary form must reproduce the above copyright notice, this ** list of conditions and the following disclaimer in the documentation and/or ** other materials provided with the distribution. ** ** o Neither the name of Freescale Semiconductor, Inc. nor the names of its ** contributors may be used to endorse or promote products derived from this ** software without specific prior written permission. ** ** THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ** ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED ** WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE ** DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT 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. ** ** http: www.freescale.com ** mail: support@freescale.com ** ** Revisions: ** - rev. 1.0 (2013-08-12) ** Initial version. ** - rev. 2.0 (2013-10-29) ** Register accessor macros added to the memory map. ** Symbols for Processor Expert memory map compatibility added to the memory map. ** Startup file for gcc has been updated according to CMSIS 3.2. ** System initialization updated. ** MCG - registers updated. ** PORTA, PORTB, PORTC, PORTE - registers for digital filter removed. ** - rev. 2.1 (2013-10-30) ** Definition of BITBAND macros updated to support peripherals with 32-bit acces disabled. ** - rev. 2.2 (2013-12-09) ** DMA - EARS register removed. ** AIPS0, AIPS1 - MPRA register updated. ** - rev. 2.3 (2014-01-24) ** Update according to reference manual rev. 2 ** ENET, MCG, MCM, SIM, USB - registers updated ** - rev. 2.4 (2014-02-10) ** The declaration of clock configurations has been moved to separate header file system_MK64F12.h ** Update of SystemInit() and SystemCoreClockUpdate() functions. ** - rev. 2.5 (2014-02-10) ** The declaration of clock configurations has been moved to separate header file system_MK64F12.h ** Update of SystemInit() and SystemCoreClockUpdate() functions. ** Module access macro module_BASES replaced by module_BASE_PTRS. ** ** ################################################################### */ #ifndef _FSL_BITACCESS_H #define _FSL_BITACCESS_H 1 #include #include /** * @brief Macro to access a single bit of a 32-bit peripheral register (bit band region * 0x40000000 to 0x400FFFFF) using the bit-band alias region access. * @param Reg Register to access. * @param Bit Bit number to access. * @return Value of the targeted bit in the bit band region. */ #define BITBAND_ACCESS32(Reg,Bit) (*((uint32_t volatile*)(0x42000000u + (32u*((uint32_t)(Reg) - (uint32_t)0x40000000u)) + (4u*((uint32_t)(Bit)))))) /** * @brief Macro to access a single bit of a 16-bit peripheral register (bit band region * 0x40000000 to 0x400FFFFF) using the bit-band alias region access. * @param Reg Register to access. * @param Bit Bit number to access. * @return Value of the targeted bit in the bit band region. */ #define BITBAND_ACCESS16(Reg,Bit) (*((uint16_t volatile*)(0x42000000u + (32u*((uint32_t)(Reg) - (uint32_t)0x40000000u)) + (4u*((uint32_t)(Bit)))))) /** * @brief Macro to access a single bit of an 8-bit peripheral register (bit band region * 0x40000000 to 0x400FFFFF) using the bit-band alias region access. * @param Reg Register to access. * @param Bit Bit number to access. * @return Value of the targeted bit in the bit band region. */ #define BITBAND_ACCESS8(Reg,Bit) (*((uint8_t volatile*)(0x42000000u + (32u*((uint32_t)(Reg) - (uint32_t)0x40000000u)) + (4u*((uint32_t)(Bit)))))) /* * Macros for single instance registers */ #define BF_SET(reg, field) HW_##reg##_SET(BM_##reg##_##field) #define BF_CLR(reg, field) HW_##reg##_CLR(BM_##reg##_##field) #define BF_TOG(reg, field) HW_##reg##_TOG(BM_##reg##_##field) #define BF_SETV(reg, field, v) HW_##reg##_SET(BF_##reg##_##field(v)) #define BF_CLRV(reg, field, v) HW_##reg##_CLR(BF_##reg##_##field(v)) #define BF_TOGV(reg, field, v) HW_##reg##_TOG(BF_##reg##_##field(v)) #define BV_FLD(reg, field, sym) BF_##reg##_##field(BV_##reg##_##field##__##sym) #define BV_VAL(reg, field, sym) BV_##reg##_##field##__##sym #define BF_RD(reg, field) HW_##reg.B.field #define BF_WR(reg, field, v) BW_##reg##_##field(v) #define BF_CS1(reg, f1, v1) \ (HW_##reg##_CLR(BM_##reg##_##f1), \ HW_##reg##_SET(BF_##reg##_##f1(v1))) #define BF_CS2(reg, f1, v1, f2, v2) \ (HW_##reg##_CLR(BM_##reg##_##f1 | \ BM_##reg##_##f2), \ HW_##reg##_SET(BF_##reg##_##f1(v1) | \ BF_##reg##_##f2(v2))) #define BF_CS3(reg, f1, v1, f2, v2, f3, v3) \ (HW_##reg##_CLR(BM_##reg##_##f1 | \ BM_##reg##_##f2 | \ BM_##reg##_##f3), \ HW_##reg##_SET(BF_##reg##_##f1(v1) | \ BF_##reg##_##f2(v2) | \ BF_##reg##_##f3(v3))) #define BF_CS4(reg, f1, v1, f2, v2, f3, v3, f4, v4) \ (HW_##reg##_CLR(BM_##reg##_##f1 | \ BM_##reg##_##f2 | \ BM_##reg##_##f3 | \ BM_##reg##_##f4), \ HW_##reg##_SET(BF_##reg##_##f1(v1) | \ BF_##reg##_##f2(v2) | \ BF_##reg##_##f3(v3) | \ BF_##reg##_##f4(v4))) #define BF_CS5(reg, f1, v1, f2, v2, f3, v3, f4, v4, f5, v5) \ (HW_##reg##_CLR(BM_##reg##_##f1 | \ BM_##reg##_##f2 | \ BM_##reg##_##f3 | \ BM_##reg##_##f4 | \ BM_##reg##_##f5), \ HW_##reg##_SET(BF_##reg##_##f1(v1) | \ BF_##reg##_##f2(v2) | \ BF_##reg##_##f3(v3) | \ BF_##reg##_##f4(v4) | \ BF_##reg##_##f5(v5))) #define BF_CS6(reg, f1, v1, f2, v2, f3, v3, f4, v4, f5, v5, f6, v6) \ (HW_##reg##_CLR(BM_##reg##_##f1 | \ BM_##reg##_##f2 | \ BM_##reg##_##f3 | \ BM_##reg##_##f4 | \ BM_##reg##_##f5 | \ BM_##reg##_##f6), \ HW_##reg##_SET(BF_##reg##_##f1(v1) | \ BF_##reg##_##f2(v2) | \ BF_##reg##_##f3(v3) | \ BF_##reg##_##f4(v4) | \ BF_##reg##_##f5(v5) | \ BF_##reg##_##f6(v6))) #define BF_CS7(reg, f1, v1, f2, v2, f3, v3, f4, v4, f5, v5, f6, v6, f7, v7) \ (HW_##reg##_CLR(BM_##reg##_##f1 | \ BM_##reg##_##f2 | \ BM_##reg##_##f3 | \ BM_##reg##_##f4 | \ BM_##reg##_##f5 | \ BM_##reg##_##f6 | \ BM_##reg##_##f7), \ HW_##reg##_SET(BF_##reg##_##f1(v1) | \ BF_##reg##_##f2(v2) | \ BF_##reg##_##f3(v3) | \ BF_##reg##_##f4(v4) | \ BF_##reg##_##f5(v5) | \ BF_##reg##_##f6(v6) | \ BF_##reg##_##f7(v7))) #define BF_CS8(reg, f1, v1, f2, v2, f3, v3, f4, v4, f5, v5, f6, v6, f7, v7, f8, v8) \ (HW_##reg##_CLR(BM_##reg##_##f1 | \ BM_##reg##_##f2 | \ BM_##reg##_##f3 | \ BM_##reg##_##f4 | \ BM_##reg##_##f5 | \ BM_##reg##_##f6 | \ BM_##reg##_##f7 | \ BM_##reg##_##f8), \ HW_##reg##_SET(BF_##reg##_##f1(v1) | \ BF_##reg##_##f2(v2) | \ BF_##reg##_##f3(v3) | \ BF_##reg##_##f4(v4) | \ BF_##reg##_##f5(v5) | \ BF_##reg##_##f6(v6) | \ BF_##reg##_##f7(v7) | \ BF_##reg##_##f8(v8))) /* * Macros for multiple instance registers */ #define BF_SETn(reg, n, field) HW_##reg##_SET(n, BM_##reg##_##field) #define BF_CLRn(reg, n, field) HW_##reg##_CLR(n, BM_##reg##_##field) #define BF_TOGn(reg, n, field) HW_##reg##_TOG(n, BM_##reg##_##field) #define BF_SETVn(reg, n, field, v) HW_##reg##_SET(n, BF_##reg##_##field(v)) #define BF_CLRVn(reg, n, field, v) HW_##reg##_CLR(n, BF_##reg##_##field(v)) #define BF_TOGVn(reg, n, field, v) HW_##reg##_TOG(n, BF_##reg##_##field(v)) #define BV_FLDn(reg, n, field, sym) BF_##reg##_##field(BV_##reg##_##field##__##sym) #define BV_VALn(reg, n, field, sym) BV_##reg##_##field##__##sym #define BF_RDn(reg, n, field) HW_##reg(n).B.field #define BF_WRn(reg, n, field, v) BW_##reg##_##field(n, v) #define BF_CS1n(reg, n, f1, v1) \ (HW_##reg##_CLR(n, (BM_##reg##_##f1)), \ HW_##reg##_SET(n, (BF_##reg##_##f1(v1)))) #define BF_CS2n(reg, n, f1, v1, f2, v2) \ (HW_##reg##_CLR(n, (BM_##reg##_##f1 | \ BM_##reg##_##f2)), \ HW_##reg##_SET(n, (BF_##reg##_##f1(v1) | \ BF_##reg##_##f2(v2)))) #define BF_CS3n(reg, n, f1, v1, f2, v2, f3, v3) \ (HW_##reg##_CLR(n, (BM_##reg##_##f1 | \ BM_##reg##_##f2 | \ BM_##reg##_##f3)), \ HW_##reg##_SET(n, (BF_##reg##_##f1(v1) | \ BF_##reg##_##f2(v2) | \ BF_##reg##_##f3(v3)))) #define BF_CS4n(reg, n, f1, v1, f2, v2, f3, v3, f4, v4) \ (HW_##reg##_CLR(n, (BM_##reg##_##f1 | \ BM_##reg##_##f2 | \ BM_##reg##_##f3 | \ BM_##reg##_##f4)), \ HW_##reg##_SET(n, (BF_##reg##_##f1(v1) | \ BF_##reg##_##f2(v2) | \ BF_##reg##_##f3(v3) | \ BF_##reg##_##f4(v4)))) #define BF_CS5n(reg, n, f1, v1, f2, v2, f3, v3, f4, v4, f5, v5) \ (HW_##reg##_CLR(n, (BM_##reg##_##f1 | \ BM_##reg##_##f2 | \ BM_##reg##_##f3 | \ BM_##reg##_##f4 | \ BM_##reg##_##f5)), \ HW_##reg##_SET(n, (BF_##reg##_##f1(v1) | \ BF_##reg##_##f2(v2) | \ BF_##reg##_##f3(v3) | \ BF_##reg##_##f4(v4) | \ BF_##reg##_##f5(v5)))) #define BF_CS6n(reg, n, f1, v1, f2, v2, f3, v3, f4, v4, f5, v5, f6, v6) \ (HW_##reg##_CLR(n, (BM_##reg##_##f1 | \ BM_##reg##_##f2 | \ BM_##reg##_##f3 | \ BM_##reg##_##f4 | \ BM_##reg##_##f5 | \ BM_##reg##_##f6)), \ HW_##reg##_SET(n, (BF_##reg##_##f1(v1) | \ BF_##reg##_##f2(v2) | \ BF_##reg##_##f3(v3) | \ BF_##reg##_##f4(v4) | \ BF_##reg##_##f5(v5) | \ BF_##reg##_##f6(v6)))) #define BF_CS7n(reg, n, f1, v1, f2, v2, f3, v3, f4, v4, f5, v5, f6, v6, f7, v7) \ (HW_##reg##_CLR(n, (BM_##reg##_##f1 | \ BM_##reg##_##f2 | \ BM_##reg##_##f3 | \ BM_##reg##_##f4 | \ BM_##reg##_##f5 | \ BM_##reg##_##f6 | \ BM_##reg##_##f7)), \ HW_##reg##_SET(n, (BF_##reg##_##f1(v1) | \ BF_##reg##_##f2(v2) | \ BF_##reg##_##f3(v3) | \ BF_##reg##_##f4(v4) | \ BF_##reg##_##f5(v5) | \ BF_##reg##_##f6(v6) | \ BF_##reg##_##f7(v7)))) #define BF_CS8n(reg, n, f1, v1, f2, v2, f3, v3, f4, v4, f5, v5, f6, v6, f7, v7, f8, v8) \ (HW_##reg##_CLR(n, (BM_##reg##_##f1 | \ BM_##reg##_##f2 | \ BM_##reg##_##f3 | \ BM_##reg##_##f4 | \ BM_##reg##_##f5 | \ BM_##reg##_##f6 | \ BM_##reg##_##f7 | \ BM_##reg##_##f8)), \ HW_##reg##_SET(n, (BF_##reg##_##f1(v1) | \ BF_##reg##_##f2(v2) | \ BF_##reg##_##f3(v3) | \ BF_##reg##_##f4(v4) | \ BF_##reg##_##f5(v5) | \ BF_##reg##_##f6(v6) | \ BF_##reg##_##f7(v7) | \ BF_##reg##_##f8(v8)))) /* * Macros for single instance MULTI-BLOCK registers */ #define BFn_SET(reg, blk, field) HW_##reg##_SET(blk, BM_##reg##_##field) #define BFn_CLR(reg, blk, field) HW_##reg##_CLR(blk, BM_##reg##_##field) #define BFn_TOG(reg, blk, field) HW_##reg##_TOG(blk, BM_##reg##_##field) #define BFn_SETV(reg, blk, field, v) HW_##reg##_SET(blk, BF_##reg##_##field(v)) #define BFn_CLRV(reg, blk, field, v) HW_##reg##_CLR(blk, BF_##reg##_##field(v)) #define BFn_TOGV(reg, blk, field, v) HW_##reg##_TOG(blk, BF_##reg##_##field(v)) #define BVn_FLD(reg, field, sym) BF_##reg##_##field(BV_##reg##_##field##__##sym) #define BVn_VAL(reg, field, sym) BV_##reg##_##field##__##sym #define BFn_RD(reg, blk, field) HW_##reg(blk).B.field #define BFn_WR(reg, blk, field, v) BW_##reg##_##field(blk, v) #define BFn_CS1(reg, blk, f1, v1) \ (HW_##reg##_CLR(blk, BM_##reg##_##f1), \ HW_##reg##_SET(blk, BF_##reg##_##f1(v1))) #define BFn_CS2(reg, blk, f1, v1, f2, v2) \ (HW_##reg##_CLR(blk, BM_##reg##_##f1 | \ BM_##reg##_##f2), \ HW_##reg##_SET(blk, BF_##reg##_##f1(v1) | \ BF_##reg##_##f2(v2))) #define BFn_CS3(reg, blk, f1, v1, f2, v2, f3, v3) \ (HW_##reg##_CLR(blk, BM_##reg##_##f1 | \ BM_##reg##_##f2 | \ BM_##reg##_##f3), \ HW_##reg##_SET(blk, BF_##reg##_##f1(v1) | \ BF_##reg##_##f2(v2) | \ BF_##reg##_##f3(v3))) #define BFn_CS4(reg, blk, f1, v1, f2, v2, f3, v3, f4, v4) \ (HW_##reg##_CLR(blk, BM_##reg##_##f1 | \ BM_##reg##_##f2 | \ BM_##reg##_##f3 | \ BM_##reg##_##f4), \ HW_##reg##_SET(blk, BF_##reg##_##f1(v1) | \ BF_##reg##_##f2(v2) | \ BF_##reg##_##f3(v3) | \ BF_##reg##_##f4(v4))) #define BFn_CS5(reg, blk, f1, v1, f2, v2, f3, v3, f4, v4, f5, v5) \ (HW_##reg##_CLR(blk, BM_##reg##_##f1 | \ BM_##reg##_##f2 | \ BM_##reg##_##f3 | \ BM_##reg##_##f4 | \ BM_##reg##_##f5), \ HW_##reg##_SET(blk, BF_##reg##_##f1(v1) | \ BF_##reg##_##f2(v2) | \ BF_##reg##_##f3(v3) | \ BF_##reg##_##f4(v4) | \ BF_##reg##_##f5(v5))) #define BFn_CS6(reg, blk, f1, v1, f2, v2, f3, v3, f4, v4, f5, v5, f6, v6) \ (HW_##reg##_CLR(blk, BM_##reg##_##f1 | \ BM_##reg##_##f2 | \ BM_##reg##_##f3 | \ BM_##reg##_##f4 | \ BM_##reg##_##f5 | \ BM_##reg##_##f6), \ HW_##reg##_SET(blk, BF_##reg##_##f1(v1) | \ BF_##reg##_##f2(v2) | \ BF_##reg##_##f3(v3) | \ BF_##reg##_##f4(v4) | \ BF_##reg##_##f5(v5) | \ BF_##reg##_##f6(v6))) #define BFn_CS7(reg, blk, f1, v1, f2, v2, f3, v3, f4, v4, f5, v5, f6, v6, f7, v7) \ (HW_##reg##_CLR(blk, BM_##reg##_##f1 | \ BM_##reg##_##f2 | \ BM_##reg##_##f3 | \ BM_##reg##_##f4 | \ BM_##reg##_##f5 | \ BM_##reg##_##f6 | \ BM_##reg##_##f7), \ HW_##reg##_SET(blk, BF_##reg##_##f1(v1) | \ BF_##reg##_##f2(v2) | \ BF_##reg##_##f3(v3) | \ BF_##reg##_##f4(v4) | \ BF_##reg##_##f5(v5) | \ BF_##reg##_##f6(v6) | \ BF_##reg##_##f7(v7))) #define BFn_CS8(reg, blk, f1, v1, f2, v2, f3, v3, f4, v4, f5, v5, f6, v6, f7, v7, f8, v8) \ (HW_##reg##_CLR(blk, BM_##reg##_##f1 | \ BM_##reg##_##f2 | \ BM_##reg##_##f3 | \ BM_##reg##_##f4 | \ BM_##reg##_##f5 | \ BM_##reg##_##f6 | \ BM_##reg##_##f7 | \ BM_##reg##_##f8), \ HW_##reg##_SET(blk, BF_##reg##_##f1(v1) | \ BF_##reg##_##f2(v2) | \ BF_##reg##_##f3(v3) | \ BF_##reg##_##f4(v4) | \ BF_##reg##_##f5(v5) | \ BF_##reg##_##f6(v6) | \ BF_##reg##_##f7(v7) | \ BF_##reg##_##f8(v8))) /* * Macros for MULTI-BLOCK multiple instance registers */ #define BFn_SETn(reg, blk, n, field) HW_##reg##_SET(blk, n, BM_##reg##_##field) #define BFn_CLRn(reg, blk, n, field) HW_##reg##_CLR(blk, n, BM_##reg##_##field) #define BFn_TOGn(reg, blk, n, field) HW_##reg##_TOG(blk, n, BM_##reg##_##field) #define BFn_SETVn(reg, blk, n, field, v) HW_##reg##_SET(blk, n, BF_##reg##_##field(v)) #define BFn_CLRVn(reg, blk, n, field, v) HW_##reg##_CLR(blk, n, BF_##reg##_##field(v)) #define BFn_TOGVn(reg, blk, n, field, v) HW_##reg##_TOG(blk, n, BF_##reg##_##field(v)) #define BVn_FLDn(reg, blk, n, field, sym) BF_##reg##_##field(BV_##reg##_##field##__##sym) #define BVn_VALn(reg, blk, n, field, sym) BV_##reg##_##field##__##sym #define BFn_RDn(reg, blk, n, field) HW_##reg(n).B.field #define BFn_WRn(reg, blk, n, field, v) BW_##reg##_##field(n, v) #define BFn_CS1n(reg, blk, n, f1, v1) \ (HW_##reg##_CLR(blk, n, (BM_##reg##_##f1)), \ HW_##reg##_SET(blk, n, (BF_##reg##_##f1(v1)))) #define BFn_CS2n(reg, blk, n, f1, v1, f2, v2) \ (HW_##reg##_CLR(blk, n, (BM_##reg##_##f1 | \ BM_##reg##_##f2)), \ HW_##reg##_SET(blk, n, (BF_##reg##_##f1(v1) | \ BF_##reg##_##f2(v2)))) #define BFn_CS3n(reg, blk, n, f1, v1, f2, v2, f3, v3) \ (HW_##reg##_CLR(blk, n, (BM_##reg##_##f1 | \ BM_##reg##_##f2 | \ BM_##reg##_##f3)), \ HW_##reg##_SET(blk, n, (BF_##reg##_##f1(v1) | \ BF_##reg##_##f2(v2) | \ BF_##reg##_##f3(v3)))) #define BFn_CS4n(reg, blk, n, f1, v1, f2, v2, f3, v3, f4, v4) \ (HW_##reg##_CLR(blk, n, (BM_##reg##_##f1 | \ BM_##reg##_##f2 | \ BM_##reg##_##f3 | \ BM_##reg##_##f4)), \ HW_##reg##_SET(blk, n, (BF_##reg##_##f1(v1) | \ BF_##reg##_##f2(v2) | \ BF_##reg##_##f3(v3) | \ BF_##reg##_##f4(v4)))) #define BFn_CS5n(reg, blk, n, f1, v1, f2, v2, f3, v3, f4, v4, f5, v5) \ (HW_##reg##_CLR(blk, n, (BM_##reg##_##f1 | \ BM_##reg##_##f2 | \ BM_##reg##_##f3 | \ BM_##reg##_##f4 | \ BM_##reg##_##f5)), \ HW_##reg##_SET(blk, n, (BF_##reg##_##f1(v1) | \ BF_##reg##_##f2(v2) | \ BF_##reg##_##f3(v3) | \ BF_##reg##_##f4(v4) | \ BF_##reg##_##f5(v5)))) #define BFn_CS6n(reg, blk, n, f1, v1, f2, v2, f3, v3, f4, v4, f5, v5, f6, v6) \ (HW_##reg##_CLR(blk, n, (BM_##reg##_##f1 | \ BM_##reg##_##f2 | \ BM_##reg##_##f3 | \ BM_##reg##_##f4 | \ BM_##reg##_##f5 | \ BM_##reg##_##f6)), \ HW_##reg##_SET(blk, n, (BF_##reg##_##f1(v1) | \ BF_##reg##_##f2(v2) | \ BF_##reg##_##f3(v3) | \ BF_##reg##_##f4(v4) | \ BF_##reg##_##f5(v5) | \ BF_##reg##_##f6(v6)))) #define BFn_CS7n(reg, blk, n, f1, v1, f2, v2, f3, v3, f4, v4, f5, v5, f6, v6, f7, v7) \ (HW_##reg##_CLR(blk, n, (BM_##reg##_##f1 | \ BM_##reg##_##f2 | \ BM_##reg##_##f3 | \ BM_##reg##_##f4 | \ BM_##reg##_##f5 | \ BM_##reg##_##f6 | \ BM_##reg##_##f7)), \ HW_##reg##_SET(blk, n, (BF_##reg##_##f1(v1) | \ BF_##reg##_##f2(v2) | \ BF_##reg##_##f3(v3) | \ BF_##reg##_##f4(v4) | \ BF_##reg##_##f5(v5) | \ BF_##reg##_##f6(v6) | \ BF_##reg##_##f7(v7)))) #define BFn_CS8n(reg, blk, n, f1, v1, f2, v2, f3, v3, f4, v4, f5, v5, f6, v6, f7, v7, f8, v8) \ (HW_##reg##_CLR(blk, n, (BM_##reg##_##f1 | \ BM_##reg##_##f2 | \ BM_##reg##_##f3 | \ BM_##reg##_##f4 | \ BM_##reg##_##f5 | \ BM_##reg##_##f6 | \ BM_##reg##_##f7 | \ BM_##reg##_##f8)), \ HW_##reg##_SET(blk, n, (BF_##reg##_##f1(v1) | \ BF_##reg##_##f2(v2) | \ BF_##reg##_##f3(v3) | \ BF_##reg##_##f4(v4) | \ BF_##reg##_##f5(v5) | \ BF_##reg##_##f6(v6) | \ BF_##reg##_##f7(v7) | \ BF_##reg##_##f8(v8)))) #endif /* _FSL_BITACCESS_H */ /******************************************************************************/ ================================================ FILE: Zelig/mbed/TARGET_K64F/TARGET_Freescale/TARGET_KPSDK_MCUS/TARGET_MCU_K64F/device/device/MK64F12/MK64F12.h ================================================ /* ** ################################################################### ** Processors: MK64FN1M0VDC12 ** MK64FN1M0VLL12 ** MK64FN1M0VLQ12 ** MK64FN1M0VMD12 ** ** Compilers: Keil ARM C/C++ Compiler ** Freescale C/C++ for Embedded ARM ** GNU C Compiler ** GNU C Compiler - CodeSourcery Sourcery G++ ** IAR ANSI C/C++ Compiler for ARM ** ** Reference manual: K64P144M120SF5RM, Rev.2, January 2014 ** Version: rev. 2.5, 2014-02-10 ** Build: b140604 ** ** Abstract: ** CMSIS Peripheral Access Layer for MK64F12 ** ** Copyright (c) 1997 - 2014 Freescale Semiconductor, Inc. ** All rights reserved. ** ** Redistribution and use in source and binary forms, with or without modification, ** are permitted provided that the following conditions are met: ** ** o Redistributions of source code must retain the above copyright notice, this list ** of conditions and the following disclaimer. ** ** o Redistributions in binary form must reproduce the above copyright notice, this ** list of conditions and the following disclaimer in the documentation and/or ** other materials provided with the distribution. ** ** o Neither the name of Freescale Semiconductor, Inc. nor the names of its ** contributors may be used to endorse or promote products derived from this ** software without specific prior written permission. ** ** THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ** ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED ** WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE ** DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT 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. ** ** http: www.freescale.com ** mail: support@freescale.com ** ** Revisions: ** - rev. 1.0 (2013-08-12) ** Initial version. ** - rev. 2.0 (2013-10-29) ** Register accessor macros added to the memory map. ** Symbols for Processor Expert memory map compatibility added to the memory map. ** Startup file for gcc has been updated according to CMSIS 3.2. ** System initialization updated. ** MCG - registers updated. ** PORTA, PORTB, PORTC, PORTE - registers for digital filter removed. ** - rev. 2.1 (2013-10-30) ** Definition of BITBAND macros updated to support peripherals with 32-bit acces disabled. ** - rev. 2.2 (2013-12-09) ** DMA - EARS register removed. ** AIPS0, AIPS1 - MPRA register updated. ** - rev. 2.3 (2014-01-24) ** Update according to reference manual rev. 2 ** ENET, MCG, MCM, SIM, USB - registers updated ** - rev. 2.4 (2014-02-10) ** The declaration of clock configurations has been moved to separate header file system_MK64F12.h ** Update of SystemInit() and SystemCoreClockUpdate() functions. ** - rev. 2.5 (2014-02-10) ** The declaration of clock configurations has been moved to separate header file system_MK64F12.h ** Update of SystemInit() and SystemCoreClockUpdate() functions. ** Module access macro module_BASES replaced by module_BASE_PTRS. ** ** ################################################################### */ /*! * @file MK64F12.h * @version 2.5 * @date 2014-02-10 * @brief CMSIS Peripheral Access Layer for MK64F12 * * CMSIS Peripheral Access Layer for MK64F12 */ /* ---------------------------------------------------------------------------- -- MCU activation ---------------------------------------------------------------------------- */ /* Prevention from multiple including the same memory map */ #if !defined(MK64F12_H_) /* Check if memory map has not been already included */ #define MK64F12_H_ #define MCU_MK64F12 /* Check if another memory map has not been also included */ #if (defined(MCU_ACTIVE)) #error MK64F12 memory map: There is already included another memory map. Only one memory map can be included. #endif /* (defined(MCU_ACTIVE)) */ #define MCU_ACTIVE #include /** Memory map major version (memory maps with equal major version number are * compatible) */ #define MCU_MEM_MAP_VERSION 0x0200u /** Memory map minor version */ #define MCU_MEM_MAP_VERSION_MINOR 0x0005u /** * @brief Macro to calculate address of an aliased word in the peripheral * bitband area for a peripheral register and bit (bit band region 0x40000000 to * 0x400FFFFF). * @param Reg Register to access. * @param Bit Bit number to access. * @return Address of the aliased word in the peripheral bitband area. */ #define BITBAND_REGADDR(Reg,Bit) (0x42000000u + (32u*((uint32_t)&(Reg) - (uint32_t)0x40000000u)) + (4u*((uint32_t)(Bit)))) /** * @brief Macro to access a single bit of a peripheral register (bit band region * 0x40000000 to 0x400FFFFF) using the bit-band alias region access. Can * be used for peripherals with 32bit access allowed. * @param Reg Register to access. * @param Bit Bit number to access. * @return Value of the targeted bit in the bit band region. */ #define BITBAND_REG32(Reg,Bit) (*((uint32_t volatile*)(BITBAND_REGADDR(Reg,Bit)))) #define BITBAND_REG(Reg,Bit) (BITBAND_REG32(Reg,Bit)) /** * @brief Macro to access a single bit of a peripheral register (bit band region * 0x40000000 to 0x400FFFFF) using the bit-band alias region access. Can * be used for peripherals with 16bit access allowed. * @param Reg Register to access. * @param Bit Bit number to access. * @return Value of the targeted bit in the bit band region. */ #define BITBAND_REG16(Reg,Bit) (*((uint16_t volatile*)(BITBAND_REGADDR(Reg,Bit)))) /** * @brief Macro to access a single bit of a peripheral register (bit band region * 0x40000000 to 0x400FFFFF) using the bit-band alias region access. Can * be used for peripherals with 8bit access allowed. * @param Reg Register to access. * @param Bit Bit number to access. * @return Value of the targeted bit in the bit band region. */ #define BITBAND_REG8(Reg,Bit) (*((uint8_t volatile*)(BITBAND_REGADDR(Reg,Bit)))) /* ---------------------------------------------------------------------------- -- Interrupt vector numbers ---------------------------------------------------------------------------- */ /*! * @addtogroup Interrupt_vector_numbers Interrupt vector numbers * @{ */ /** Interrupt Number Definitions */ #define NUMBER_OF_INT_VECTORS 102 /**< Number of interrupts in the Vector table */ typedef enum IRQn { /* Core interrupts */ NonMaskableInt_IRQn = -14, /**< Non Maskable Interrupt */ HardFault_IRQn = -13, /**< Cortex-M4 SV Hard Fault Interrupt */ MemoryManagement_IRQn = -12, /**< Cortex-M4 Memory Management Interrupt */ BusFault_IRQn = -11, /**< Cortex-M4 Bus Fault Interrupt */ UsageFault_IRQn = -10, /**< Cortex-M4 Usage Fault Interrupt */ SVCall_IRQn = -5, /**< Cortex-M4 SV Call Interrupt */ DebugMonitor_IRQn = -4, /**< Cortex-M4 Debug Monitor Interrupt */ PendSV_IRQn = -2, /**< Cortex-M4 Pend SV Interrupt */ SysTick_IRQn = -1, /**< Cortex-M4 System Tick Interrupt */ /* Device specific interrupts */ DMA0_IRQn = 0, /**< DMA Channel 0 Transfer Complete */ DMA1_IRQn = 1, /**< DMA Channel 1 Transfer Complete */ DMA2_IRQn = 2, /**< DMA Channel 2 Transfer Complete */ DMA3_IRQn = 3, /**< DMA Channel 3 Transfer Complete */ DMA4_IRQn = 4, /**< DMA Channel 4 Transfer Complete */ DMA5_IRQn = 5, /**< DMA Channel 5 Transfer Complete */ DMA6_IRQn = 6, /**< DMA Channel 6 Transfer Complete */ DMA7_IRQn = 7, /**< DMA Channel 7 Transfer Complete */ DMA8_IRQn = 8, /**< DMA Channel 8 Transfer Complete */ DMA9_IRQn = 9, /**< DMA Channel 9 Transfer Complete */ DMA10_IRQn = 10, /**< DMA Channel 10 Transfer Complete */ DMA11_IRQn = 11, /**< DMA Channel 11 Transfer Complete */ DMA12_IRQn = 12, /**< DMA Channel 12 Transfer Complete */ DMA13_IRQn = 13, /**< DMA Channel 13 Transfer Complete */ DMA14_IRQn = 14, /**< DMA Channel 14 Transfer Complete */ DMA15_IRQn = 15, /**< DMA Channel 15 Transfer Complete */ DMA_Error_IRQn = 16, /**< DMA Error Interrupt */ MCM_IRQn = 17, /**< Normal Interrupt */ FTFE_IRQn = 18, /**< FTFE Command complete interrupt */ Read_Collision_IRQn = 19, /**< Read Collision Interrupt */ LVD_LVW_IRQn = 20, /**< Low Voltage Detect, Low Voltage Warning */ LLW_IRQn = 21, /**< Low Leakage Wakeup */ Watchdog_IRQn = 22, /**< WDOG Interrupt */ RNG_IRQn = 23, /**< RNG Interrupt */ I2C0_IRQn = 24, /**< I2C0 interrupt */ I2C1_IRQn = 25, /**< I2C1 interrupt */ SPI0_IRQn = 26, /**< SPI0 Interrupt */ SPI1_IRQn = 27, /**< SPI1 Interrupt */ I2S0_Tx_IRQn = 28, /**< I2S0 transmit interrupt */ I2S0_Rx_IRQn = 29, /**< I2S0 receive interrupt */ UART0_LON_IRQn = 30, /**< UART0 LON interrupt */ UART0_RX_TX_IRQn = 31, /**< UART0 Receive/Transmit interrupt */ UART0_ERR_IRQn = 32, /**< UART0 Error interrupt */ UART1_RX_TX_IRQn = 33, /**< UART1 Receive/Transmit interrupt */ UART1_ERR_IRQn = 34, /**< UART1 Error interrupt */ UART2_RX_TX_IRQn = 35, /**< UART2 Receive/Transmit interrupt */ UART2_ERR_IRQn = 36, /**< UART2 Error interrupt */ UART3_RX_TX_IRQn = 37, /**< UART3 Receive/Transmit interrupt */ UART3_ERR_IRQn = 38, /**< UART3 Error interrupt */ ADC0_IRQn = 39, /**< ADC0 interrupt */ CMP0_IRQn = 40, /**< CMP0 interrupt */ CMP1_IRQn = 41, /**< CMP1 interrupt */ FTM0_IRQn = 42, /**< FTM0 fault, overflow and channels interrupt */ FTM1_IRQn = 43, /**< FTM1 fault, overflow and channels interrupt */ FTM2_IRQn = 44, /**< FTM2 fault, overflow and channels interrupt */ CMT_IRQn = 45, /**< CMT interrupt */ RTC_IRQn = 46, /**< RTC interrupt */ RTC_Seconds_IRQn = 47, /**< RTC seconds interrupt */ PIT0_IRQn = 48, /**< PIT timer channel 0 interrupt */ PIT1_IRQn = 49, /**< PIT timer channel 1 interrupt */ PIT2_IRQn = 50, /**< PIT timer channel 2 interrupt */ PIT3_IRQn = 51, /**< PIT timer channel 3 interrupt */ PDB0_IRQn = 52, /**< PDB0 Interrupt */ USB0_IRQn = 53, /**< USB0 interrupt */ USBDCD_IRQn = 54, /**< USBDCD Interrupt */ Reserved71_IRQn = 55, /**< Reserved interrupt 71 */ DAC0_IRQn = 56, /**< DAC0 interrupt */ MCG_IRQn = 57, /**< MCG Interrupt */ LPTimer_IRQn = 58, /**< LPTimer interrupt */ PORTA_IRQn = 59, /**< Port A interrupt */ PORTB_IRQn = 60, /**< Port B interrupt */ PORTC_IRQn = 61, /**< Port C interrupt */ PORTD_IRQn = 62, /**< Port D interrupt */ PORTE_IRQn = 63, /**< Port E interrupt */ SWI_IRQn = 64, /**< Software interrupt */ SPI2_IRQn = 65, /**< SPI2 Interrupt */ UART4_RX_TX_IRQn = 66, /**< UART4 Receive/Transmit interrupt */ UART4_ERR_IRQn = 67, /**< UART4 Error interrupt */ UART5_RX_TX_IRQn = 68, /**< UART5 Receive/Transmit interrupt */ UART5_ERR_IRQn = 69, /**< UART5 Error interrupt */ CMP2_IRQn = 70, /**< CMP2 interrupt */ FTM3_IRQn = 71, /**< FTM3 fault, overflow and channels interrupt */ DAC1_IRQn = 72, /**< DAC1 interrupt */ ADC1_IRQn = 73, /**< ADC1 interrupt */ I2C2_IRQn = 74, /**< I2C2 interrupt */ CAN0_ORed_Message_buffer_IRQn = 75, /**< CAN0 OR'd message buffers interrupt */ CAN0_Bus_Off_IRQn = 76, /**< CAN0 bus off interrupt */ CAN0_Error_IRQn = 77, /**< CAN0 error interrupt */ CAN0_Tx_Warning_IRQn = 78, /**< CAN0 Tx warning interrupt */ CAN0_Rx_Warning_IRQn = 79, /**< CAN0 Rx warning interrupt */ CAN0_Wake_Up_IRQn = 80, /**< CAN0 wake up interrupt */ SDHC_IRQn = 81, /**< SDHC interrupt */ ENET_1588_Timer_IRQn = 82, /**< Ethernet MAC IEEE 1588 Timer Interrupt */ ENET_Transmit_IRQn = 83, /**< Ethernet MAC Transmit Interrupt */ ENET_Receive_IRQn = 84, /**< Ethernet MAC Receive Interrupt */ ENET_Error_IRQn = 85 /**< Ethernet MAC Error and miscelaneous Interrupt */ } IRQn_Type; /*! * @} */ /* end of group Interrupt_vector_numbers */ /* ---------------------------------------------------------------------------- -- Cortex M4 Core Configuration ---------------------------------------------------------------------------- */ /*! * @addtogroup Cortex_Core_Configuration Cortex M4 Core Configuration * @{ */ #define __MPU_PRESENT 0 /**< Defines if an MPU is present or not */ #define __NVIC_PRIO_BITS 4 /**< Number of priority bits implemented in the NVIC */ #define __Vendor_SysTickConfig 0 /**< Vendor specific implementation of SysTickConfig is defined */ #define __FPU_PRESENT 1 /**< Defines if an FPU is present or not */ #include "core_cm4.h" /* Core Peripheral Access Layer */ #include "system_MK64F12.h" /* Device specific configuration file */ /*! * @} */ /* end of group Cortex_Core_Configuration */ /* ---------------------------------------------------------------------------- -- Device Peripheral Access Layer ---------------------------------------------------------------------------- */ /*! * @addtogroup Peripheral_access_layer Device Peripheral Access Layer * @{ */ /* ** Start of section using anonymous unions */ #if defined(__ARMCC_VERSION) #pragma push #pragma anon_unions #elif defined(__CWCC__) #pragma push #pragma cpp_extensions on #elif defined(__GNUC__) /* anonymous unions are enabled by default */ #elif defined(__IAR_SYSTEMS_ICC__) #pragma language=extended #else #error Not supported compiler type #endif /* ---------------------------------------------------------------------------- -- ADC Peripheral Access Layer ---------------------------------------------------------------------------- */ /*! * @addtogroup ADC_Peripheral_Access_Layer ADC Peripheral Access Layer * @{ */ /** ADC - Register Layout Typedef */ typedef struct { __IO uint32_t SC1[2]; /**< ADC Status and Control Registers 1, array offset: 0x0, array step: 0x4 */ __IO uint32_t CFG1; /**< ADC Configuration Register 1, offset: 0x8 */ __IO uint32_t CFG2; /**< ADC Configuration Register 2, offset: 0xC */ __I uint32_t R[2]; /**< ADC Data Result Register, array offset: 0x10, array step: 0x4 */ __IO uint32_t CV1; /**< Compare Value Registers, offset: 0x18 */ __IO uint32_t CV2; /**< Compare Value Registers, offset: 0x1C */ __IO uint32_t SC2; /**< Status and Control Register 2, offset: 0x20 */ __IO uint32_t SC3; /**< Status and Control Register 3, offset: 0x24 */ __IO uint32_t OFS; /**< ADC Offset Correction Register, offset: 0x28 */ __IO uint32_t PG; /**< ADC Plus-Side Gain Register, offset: 0x2C */ __IO uint32_t MG; /**< ADC Minus-Side Gain Register, offset: 0x30 */ __IO uint32_t CLPD; /**< ADC Plus-Side General Calibration Value Register, offset: 0x34 */ __IO uint32_t CLPS; /**< ADC Plus-Side General Calibration Value Register, offset: 0x38 */ __IO uint32_t CLP4; /**< ADC Plus-Side General Calibration Value Register, offset: 0x3C */ __IO uint32_t CLP3; /**< ADC Plus-Side General Calibration Value Register, offset: 0x40 */ __IO uint32_t CLP2; /**< ADC Plus-Side General Calibration Value Register, offset: 0x44 */ __IO uint32_t CLP1; /**< ADC Plus-Side General Calibration Value Register, offset: 0x48 */ __IO uint32_t CLP0; /**< ADC Plus-Side General Calibration Value Register, offset: 0x4C */ uint8_t RESERVED_0[4]; __IO uint32_t CLMD; /**< ADC Minus-Side General Calibration Value Register, offset: 0x54 */ __IO uint32_t CLMS; /**< ADC Minus-Side General Calibration Value Register, offset: 0x58 */ __IO uint32_t CLM4; /**< ADC Minus-Side General Calibration Value Register, offset: 0x5C */ __IO uint32_t CLM3; /**< ADC Minus-Side General Calibration Value Register, offset: 0x60 */ __IO uint32_t CLM2; /**< ADC Minus-Side General Calibration Value Register, offset: 0x64 */ __IO uint32_t CLM1; /**< ADC Minus-Side General Calibration Value Register, offset: 0x68 */ __IO uint32_t CLM0; /**< ADC Minus-Side General Calibration Value Register, offset: 0x6C */ } ADC_Type, *ADC_MemMapPtr; /* ---------------------------------------------------------------------------- -- ADC - Register accessor macros ---------------------------------------------------------------------------- */ /*! * @addtogroup ADC_Register_Accessor_Macros ADC - Register accessor macros * @{ */ /* ADC - Register accessors */ #define ADC_SC1_REG(base,index) ((base)->SC1[index]) #define ADC_CFG1_REG(base) ((base)->CFG1) #define ADC_CFG2_REG(base) ((base)->CFG2) #define ADC_R_REG(base,index) ((base)->R[index]) #define ADC_CV1_REG(base) ((base)->CV1) #define ADC_CV2_REG(base) ((base)->CV2) #define ADC_SC2_REG(base) ((base)->SC2) #define ADC_SC3_REG(base) ((base)->SC3) #define ADC_OFS_REG(base) ((base)->OFS) #define ADC_PG_REG(base) ((base)->PG) #define ADC_MG_REG(base) ((base)->MG) #define ADC_CLPD_REG(base) ((base)->CLPD) #define ADC_CLPS_REG(base) ((base)->CLPS) #define ADC_CLP4_REG(base) ((base)->CLP4) #define ADC_CLP3_REG(base) ((base)->CLP3) #define ADC_CLP2_REG(base) ((base)->CLP2) #define ADC_CLP1_REG(base) ((base)->CLP1) #define ADC_CLP0_REG(base) ((base)->CLP0) #define ADC_CLMD_REG(base) ((base)->CLMD) #define ADC_CLMS_REG(base) ((base)->CLMS) #define ADC_CLM4_REG(base) ((base)->CLM4) #define ADC_CLM3_REG(base) ((base)->CLM3) #define ADC_CLM2_REG(base) ((base)->CLM2) #define ADC_CLM1_REG(base) ((base)->CLM1) #define ADC_CLM0_REG(base) ((base)->CLM0) /*! * @} */ /* end of group ADC_Register_Accessor_Macros */ /* ---------------------------------------------------------------------------- -- ADC Register Masks ---------------------------------------------------------------------------- */ /*! * @addtogroup ADC_Register_Masks ADC Register Masks * @{ */ /* SC1 Bit Fields */ #define ADC_SC1_ADCH_MASK 0x1Fu #define ADC_SC1_ADCH_SHIFT 0 #define ADC_SC1_ADCH(x) (((uint32_t)(((uint32_t)(x))<MPRA) #define AIPS_PACRA_REG(base) ((base)->PACRA) #define AIPS_PACRB_REG(base) ((base)->PACRB) #define AIPS_PACRC_REG(base) ((base)->PACRC) #define AIPS_PACRD_REG(base) ((base)->PACRD) #define AIPS_PACRE_REG(base) ((base)->PACRE) #define AIPS_PACRF_REG(base) ((base)->PACRF) #define AIPS_PACRG_REG(base) ((base)->PACRG) #define AIPS_PACRH_REG(base) ((base)->PACRH) #define AIPS_PACRI_REG(base) ((base)->PACRI) #define AIPS_PACRJ_REG(base) ((base)->PACRJ) #define AIPS_PACRK_REG(base) ((base)->PACRK) #define AIPS_PACRL_REG(base) ((base)->PACRL) #define AIPS_PACRM_REG(base) ((base)->PACRM) #define AIPS_PACRN_REG(base) ((base)->PACRN) #define AIPS_PACRO_REG(base) ((base)->PACRO) #define AIPS_PACRP_REG(base) ((base)->PACRP) #define AIPS_PACRU_REG(base) ((base)->PACRU) /*! * @} */ /* end of group AIPS_Register_Accessor_Macros */ /* ---------------------------------------------------------------------------- -- AIPS Register Masks ---------------------------------------------------------------------------- */ /*! * @addtogroup AIPS_Register_Masks AIPS Register Masks * @{ */ /* MPRA Bit Fields */ #define AIPS_MPRA_MPL5_MASK 0x100u #define AIPS_MPRA_MPL5_SHIFT 8 #define AIPS_MPRA_MTW5_MASK 0x200u #define AIPS_MPRA_MTW5_SHIFT 9 #define AIPS_MPRA_MTR5_MASK 0x400u #define AIPS_MPRA_MTR5_SHIFT 10 #define AIPS_MPRA_MPL4_MASK 0x1000u #define AIPS_MPRA_MPL4_SHIFT 12 #define AIPS_MPRA_MTW4_MASK 0x2000u #define AIPS_MPRA_MTW4_SHIFT 13 #define AIPS_MPRA_MTR4_MASK 0x4000u #define AIPS_MPRA_MTR4_SHIFT 14 #define AIPS_MPRA_MPL3_MASK 0x10000u #define AIPS_MPRA_MPL3_SHIFT 16 #define AIPS_MPRA_MTW3_MASK 0x20000u #define AIPS_MPRA_MTW3_SHIFT 17 #define AIPS_MPRA_MTR3_MASK 0x40000u #define AIPS_MPRA_MTR3_SHIFT 18 #define AIPS_MPRA_MPL2_MASK 0x100000u #define AIPS_MPRA_MPL2_SHIFT 20 #define AIPS_MPRA_MTW2_MASK 0x200000u #define AIPS_MPRA_MTW2_SHIFT 21 #define AIPS_MPRA_MTR2_MASK 0x400000u #define AIPS_MPRA_MTR2_SHIFT 22 #define AIPS_MPRA_MPL1_MASK 0x1000000u #define AIPS_MPRA_MPL1_SHIFT 24 #define AIPS_MPRA_MTW1_MASK 0x2000000u #define AIPS_MPRA_MTW1_SHIFT 25 #define AIPS_MPRA_MTR1_MASK 0x4000000u #define AIPS_MPRA_MTR1_SHIFT 26 #define AIPS_MPRA_MPL0_MASK 0x10000000u #define AIPS_MPRA_MPL0_SHIFT 28 #define AIPS_MPRA_MTW0_MASK 0x20000000u #define AIPS_MPRA_MTW0_SHIFT 29 #define AIPS_MPRA_MTR0_MASK 0x40000000u #define AIPS_MPRA_MTR0_SHIFT 30 /* PACRA Bit Fields */ #define AIPS_PACRA_TP7_MASK 0x1u #define AIPS_PACRA_TP7_SHIFT 0 #define AIPS_PACRA_WP7_MASK 0x2u #define AIPS_PACRA_WP7_SHIFT 1 #define AIPS_PACRA_SP7_MASK 0x4u #define AIPS_PACRA_SP7_SHIFT 2 #define AIPS_PACRA_TP6_MASK 0x10u #define AIPS_PACRA_TP6_SHIFT 4 #define AIPS_PACRA_WP6_MASK 0x20u #define AIPS_PACRA_WP6_SHIFT 5 #define AIPS_PACRA_SP6_MASK 0x40u #define AIPS_PACRA_SP6_SHIFT 6 #define AIPS_PACRA_TP5_MASK 0x100u #define AIPS_PACRA_TP5_SHIFT 8 #define AIPS_PACRA_WP5_MASK 0x200u #define AIPS_PACRA_WP5_SHIFT 9 #define AIPS_PACRA_SP5_MASK 0x400u #define AIPS_PACRA_SP5_SHIFT 10 #define AIPS_PACRA_TP4_MASK 0x1000u #define AIPS_PACRA_TP4_SHIFT 12 #define AIPS_PACRA_WP4_MASK 0x2000u #define AIPS_PACRA_WP4_SHIFT 13 #define AIPS_PACRA_SP4_MASK 0x4000u #define AIPS_PACRA_SP4_SHIFT 14 #define AIPS_PACRA_TP3_MASK 0x10000u #define AIPS_PACRA_TP3_SHIFT 16 #define AIPS_PACRA_WP3_MASK 0x20000u #define AIPS_PACRA_WP3_SHIFT 17 #define AIPS_PACRA_SP3_MASK 0x40000u #define AIPS_PACRA_SP3_SHIFT 18 #define AIPS_PACRA_TP2_MASK 0x100000u #define AIPS_PACRA_TP2_SHIFT 20 #define AIPS_PACRA_WP2_MASK 0x200000u #define AIPS_PACRA_WP2_SHIFT 21 #define AIPS_PACRA_SP2_MASK 0x400000u #define AIPS_PACRA_SP2_SHIFT 22 #define AIPS_PACRA_TP1_MASK 0x1000000u #define AIPS_PACRA_TP1_SHIFT 24 #define AIPS_PACRA_WP1_MASK 0x2000000u #define AIPS_PACRA_WP1_SHIFT 25 #define AIPS_PACRA_SP1_MASK 0x4000000u #define AIPS_PACRA_SP1_SHIFT 26 #define AIPS_PACRA_TP0_MASK 0x10000000u #define AIPS_PACRA_TP0_SHIFT 28 #define AIPS_PACRA_WP0_MASK 0x20000000u #define AIPS_PACRA_WP0_SHIFT 29 #define AIPS_PACRA_SP0_MASK 0x40000000u #define AIPS_PACRA_SP0_SHIFT 30 /* PACRB Bit Fields */ #define AIPS_PACRB_TP7_MASK 0x1u #define AIPS_PACRB_TP7_SHIFT 0 #define AIPS_PACRB_WP7_MASK 0x2u #define AIPS_PACRB_WP7_SHIFT 1 #define AIPS_PACRB_SP7_MASK 0x4u #define AIPS_PACRB_SP7_SHIFT 2 #define AIPS_PACRB_TP6_MASK 0x10u #define AIPS_PACRB_TP6_SHIFT 4 #define AIPS_PACRB_WP6_MASK 0x20u #define AIPS_PACRB_WP6_SHIFT 5 #define AIPS_PACRB_SP6_MASK 0x40u #define AIPS_PACRB_SP6_SHIFT 6 #define AIPS_PACRB_TP5_MASK 0x100u #define AIPS_PACRB_TP5_SHIFT 8 #define AIPS_PACRB_WP5_MASK 0x200u #define AIPS_PACRB_WP5_SHIFT 9 #define AIPS_PACRB_SP5_MASK 0x400u #define AIPS_PACRB_SP5_SHIFT 10 #define AIPS_PACRB_TP4_MASK 0x1000u #define AIPS_PACRB_TP4_SHIFT 12 #define AIPS_PACRB_WP4_MASK 0x2000u #define AIPS_PACRB_WP4_SHIFT 13 #define AIPS_PACRB_SP4_MASK 0x4000u #define AIPS_PACRB_SP4_SHIFT 14 #define AIPS_PACRB_TP3_MASK 0x10000u #define AIPS_PACRB_TP3_SHIFT 16 #define AIPS_PACRB_WP3_MASK 0x20000u #define AIPS_PACRB_WP3_SHIFT 17 #define AIPS_PACRB_SP3_MASK 0x40000u #define AIPS_PACRB_SP3_SHIFT 18 #define AIPS_PACRB_TP2_MASK 0x100000u #define AIPS_PACRB_TP2_SHIFT 20 #define AIPS_PACRB_WP2_MASK 0x200000u #define AIPS_PACRB_WP2_SHIFT 21 #define AIPS_PACRB_SP2_MASK 0x400000u #define AIPS_PACRB_SP2_SHIFT 22 #define AIPS_PACRB_TP1_MASK 0x1000000u #define AIPS_PACRB_TP1_SHIFT 24 #define AIPS_PACRB_WP1_MASK 0x2000000u #define AIPS_PACRB_WP1_SHIFT 25 #define AIPS_PACRB_SP1_MASK 0x4000000u #define AIPS_PACRB_SP1_SHIFT 26 #define AIPS_PACRB_TP0_MASK 0x10000000u #define AIPS_PACRB_TP0_SHIFT 28 #define AIPS_PACRB_WP0_MASK 0x20000000u #define AIPS_PACRB_WP0_SHIFT 29 #define AIPS_PACRB_SP0_MASK 0x40000000u #define AIPS_PACRB_SP0_SHIFT 30 /* PACRC Bit Fields */ #define AIPS_PACRC_TP7_MASK 0x1u #define AIPS_PACRC_TP7_SHIFT 0 #define AIPS_PACRC_WP7_MASK 0x2u #define AIPS_PACRC_WP7_SHIFT 1 #define AIPS_PACRC_SP7_MASK 0x4u #define AIPS_PACRC_SP7_SHIFT 2 #define AIPS_PACRC_TP6_MASK 0x10u #define AIPS_PACRC_TP6_SHIFT 4 #define AIPS_PACRC_WP6_MASK 0x20u #define AIPS_PACRC_WP6_SHIFT 5 #define AIPS_PACRC_SP6_MASK 0x40u #define AIPS_PACRC_SP6_SHIFT 6 #define AIPS_PACRC_TP5_MASK 0x100u #define AIPS_PACRC_TP5_SHIFT 8 #define AIPS_PACRC_WP5_MASK 0x200u #define AIPS_PACRC_WP5_SHIFT 9 #define AIPS_PACRC_SP5_MASK 0x400u #define AIPS_PACRC_SP5_SHIFT 10 #define AIPS_PACRC_TP4_MASK 0x1000u #define AIPS_PACRC_TP4_SHIFT 12 #define AIPS_PACRC_WP4_MASK 0x2000u #define AIPS_PACRC_WP4_SHIFT 13 #define AIPS_PACRC_SP4_MASK 0x4000u #define AIPS_PACRC_SP4_SHIFT 14 #define AIPS_PACRC_TP3_MASK 0x10000u #define AIPS_PACRC_TP3_SHIFT 16 #define AIPS_PACRC_WP3_MASK 0x20000u #define AIPS_PACRC_WP3_SHIFT 17 #define AIPS_PACRC_SP3_MASK 0x40000u #define AIPS_PACRC_SP3_SHIFT 18 #define AIPS_PACRC_TP2_MASK 0x100000u #define AIPS_PACRC_TP2_SHIFT 20 #define AIPS_PACRC_WP2_MASK 0x200000u #define AIPS_PACRC_WP2_SHIFT 21 #define AIPS_PACRC_SP2_MASK 0x400000u #define AIPS_PACRC_SP2_SHIFT 22 #define AIPS_PACRC_TP1_MASK 0x1000000u #define AIPS_PACRC_TP1_SHIFT 24 #define AIPS_PACRC_WP1_MASK 0x2000000u #define AIPS_PACRC_WP1_SHIFT 25 #define AIPS_PACRC_SP1_MASK 0x4000000u #define AIPS_PACRC_SP1_SHIFT 26 #define AIPS_PACRC_TP0_MASK 0x10000000u #define AIPS_PACRC_TP0_SHIFT 28 #define AIPS_PACRC_WP0_MASK 0x20000000u #define AIPS_PACRC_WP0_SHIFT 29 #define AIPS_PACRC_SP0_MASK 0x40000000u #define AIPS_PACRC_SP0_SHIFT 30 /* PACRD Bit Fields */ #define AIPS_PACRD_TP7_MASK 0x1u #define AIPS_PACRD_TP7_SHIFT 0 #define AIPS_PACRD_WP7_MASK 0x2u #define AIPS_PACRD_WP7_SHIFT 1 #define AIPS_PACRD_SP7_MASK 0x4u #define AIPS_PACRD_SP7_SHIFT 2 #define AIPS_PACRD_TP6_MASK 0x10u #define AIPS_PACRD_TP6_SHIFT 4 #define AIPS_PACRD_WP6_MASK 0x20u #define AIPS_PACRD_WP6_SHIFT 5 #define AIPS_PACRD_SP6_MASK 0x40u #define AIPS_PACRD_SP6_SHIFT 6 #define AIPS_PACRD_TP5_MASK 0x100u #define AIPS_PACRD_TP5_SHIFT 8 #define AIPS_PACRD_WP5_MASK 0x200u #define AIPS_PACRD_WP5_SHIFT 9 #define AIPS_PACRD_SP5_MASK 0x400u #define AIPS_PACRD_SP5_SHIFT 10 #define AIPS_PACRD_TP4_MASK 0x1000u #define AIPS_PACRD_TP4_SHIFT 12 #define AIPS_PACRD_WP4_MASK 0x2000u #define AIPS_PACRD_WP4_SHIFT 13 #define AIPS_PACRD_SP4_MASK 0x4000u #define AIPS_PACRD_SP4_SHIFT 14 #define AIPS_PACRD_TP3_MASK 0x10000u #define AIPS_PACRD_TP3_SHIFT 16 #define AIPS_PACRD_WP3_MASK 0x20000u #define AIPS_PACRD_WP3_SHIFT 17 #define AIPS_PACRD_SP3_MASK 0x40000u #define AIPS_PACRD_SP3_SHIFT 18 #define AIPS_PACRD_TP2_MASK 0x100000u #define AIPS_PACRD_TP2_SHIFT 20 #define AIPS_PACRD_WP2_MASK 0x200000u #define AIPS_PACRD_WP2_SHIFT 21 #define AIPS_PACRD_SP2_MASK 0x400000u #define AIPS_PACRD_SP2_SHIFT 22 #define AIPS_PACRD_TP1_MASK 0x1000000u #define AIPS_PACRD_TP1_SHIFT 24 #define AIPS_PACRD_WP1_MASK 0x2000000u #define AIPS_PACRD_WP1_SHIFT 25 #define AIPS_PACRD_SP1_MASK 0x4000000u #define AIPS_PACRD_SP1_SHIFT 26 #define AIPS_PACRD_TP0_MASK 0x10000000u #define AIPS_PACRD_TP0_SHIFT 28 #define AIPS_PACRD_WP0_MASK 0x20000000u #define AIPS_PACRD_WP0_SHIFT 29 #define AIPS_PACRD_SP0_MASK 0x40000000u #define AIPS_PACRD_SP0_SHIFT 30 /* PACRE Bit Fields */ #define AIPS_PACRE_TP7_MASK 0x1u #define AIPS_PACRE_TP7_SHIFT 0 #define AIPS_PACRE_WP7_MASK 0x2u #define AIPS_PACRE_WP7_SHIFT 1 #define AIPS_PACRE_SP7_MASK 0x4u #define AIPS_PACRE_SP7_SHIFT 2 #define AIPS_PACRE_TP6_MASK 0x10u #define AIPS_PACRE_TP6_SHIFT 4 #define AIPS_PACRE_WP6_MASK 0x20u #define AIPS_PACRE_WP6_SHIFT 5 #define AIPS_PACRE_SP6_MASK 0x40u #define AIPS_PACRE_SP6_SHIFT 6 #define AIPS_PACRE_TP5_MASK 0x100u #define AIPS_PACRE_TP5_SHIFT 8 #define AIPS_PACRE_WP5_MASK 0x200u #define AIPS_PACRE_WP5_SHIFT 9 #define AIPS_PACRE_SP5_MASK 0x400u #define AIPS_PACRE_SP5_SHIFT 10 #define AIPS_PACRE_TP4_MASK 0x1000u #define AIPS_PACRE_TP4_SHIFT 12 #define AIPS_PACRE_WP4_MASK 0x2000u #define AIPS_PACRE_WP4_SHIFT 13 #define AIPS_PACRE_SP4_MASK 0x4000u #define AIPS_PACRE_SP4_SHIFT 14 #define AIPS_PACRE_TP3_MASK 0x10000u #define AIPS_PACRE_TP3_SHIFT 16 #define AIPS_PACRE_WP3_MASK 0x20000u #define AIPS_PACRE_WP3_SHIFT 17 #define AIPS_PACRE_SP3_MASK 0x40000u #define AIPS_PACRE_SP3_SHIFT 18 #define AIPS_PACRE_TP2_MASK 0x100000u #define AIPS_PACRE_TP2_SHIFT 20 #define AIPS_PACRE_WP2_MASK 0x200000u #define AIPS_PACRE_WP2_SHIFT 21 #define AIPS_PACRE_SP2_MASK 0x400000u #define AIPS_PACRE_SP2_SHIFT 22 #define AIPS_PACRE_TP1_MASK 0x1000000u #define AIPS_PACRE_TP1_SHIFT 24 #define AIPS_PACRE_WP1_MASK 0x2000000u #define AIPS_PACRE_WP1_SHIFT 25 #define AIPS_PACRE_SP1_MASK 0x4000000u #define AIPS_PACRE_SP1_SHIFT 26 #define AIPS_PACRE_TP0_MASK 0x10000000u #define AIPS_PACRE_TP0_SHIFT 28 #define AIPS_PACRE_WP0_MASK 0x20000000u #define AIPS_PACRE_WP0_SHIFT 29 #define AIPS_PACRE_SP0_MASK 0x40000000u #define AIPS_PACRE_SP0_SHIFT 30 /* PACRF Bit Fields */ #define AIPS_PACRF_TP7_MASK 0x1u #define AIPS_PACRF_TP7_SHIFT 0 #define AIPS_PACRF_WP7_MASK 0x2u #define AIPS_PACRF_WP7_SHIFT 1 #define AIPS_PACRF_SP7_MASK 0x4u #define AIPS_PACRF_SP7_SHIFT 2 #define AIPS_PACRF_TP6_MASK 0x10u #define AIPS_PACRF_TP6_SHIFT 4 #define AIPS_PACRF_WP6_MASK 0x20u #define AIPS_PACRF_WP6_SHIFT 5 #define AIPS_PACRF_SP6_MASK 0x40u #define AIPS_PACRF_SP6_SHIFT 6 #define AIPS_PACRF_TP5_MASK 0x100u #define AIPS_PACRF_TP5_SHIFT 8 #define AIPS_PACRF_WP5_MASK 0x200u #define AIPS_PACRF_WP5_SHIFT 9 #define AIPS_PACRF_SP5_MASK 0x400u #define AIPS_PACRF_SP5_SHIFT 10 #define AIPS_PACRF_TP4_MASK 0x1000u #define AIPS_PACRF_TP4_SHIFT 12 #define AIPS_PACRF_WP4_MASK 0x2000u #define AIPS_PACRF_WP4_SHIFT 13 #define AIPS_PACRF_SP4_MASK 0x4000u #define AIPS_PACRF_SP4_SHIFT 14 #define AIPS_PACRF_TP3_MASK 0x10000u #define AIPS_PACRF_TP3_SHIFT 16 #define AIPS_PACRF_WP3_MASK 0x20000u #define AIPS_PACRF_WP3_SHIFT 17 #define AIPS_PACRF_SP3_MASK 0x40000u #define AIPS_PACRF_SP3_SHIFT 18 #define AIPS_PACRF_TP2_MASK 0x100000u #define AIPS_PACRF_TP2_SHIFT 20 #define AIPS_PACRF_WP2_MASK 0x200000u #define AIPS_PACRF_WP2_SHIFT 21 #define AIPS_PACRF_SP2_MASK 0x400000u #define AIPS_PACRF_SP2_SHIFT 22 #define AIPS_PACRF_TP1_MASK 0x1000000u #define AIPS_PACRF_TP1_SHIFT 24 #define AIPS_PACRF_WP1_MASK 0x2000000u #define AIPS_PACRF_WP1_SHIFT 25 #define AIPS_PACRF_SP1_MASK 0x4000000u #define AIPS_PACRF_SP1_SHIFT 26 #define AIPS_PACRF_TP0_MASK 0x10000000u #define AIPS_PACRF_TP0_SHIFT 28 #define AIPS_PACRF_WP0_MASK 0x20000000u #define AIPS_PACRF_WP0_SHIFT 29 #define AIPS_PACRF_SP0_MASK 0x40000000u #define AIPS_PACRF_SP0_SHIFT 30 /* PACRG Bit Fields */ #define AIPS_PACRG_TP7_MASK 0x1u #define AIPS_PACRG_TP7_SHIFT 0 #define AIPS_PACRG_WP7_MASK 0x2u #define AIPS_PACRG_WP7_SHIFT 1 #define AIPS_PACRG_SP7_MASK 0x4u #define AIPS_PACRG_SP7_SHIFT 2 #define AIPS_PACRG_TP6_MASK 0x10u #define AIPS_PACRG_TP6_SHIFT 4 #define AIPS_PACRG_WP6_MASK 0x20u #define AIPS_PACRG_WP6_SHIFT 5 #define AIPS_PACRG_SP6_MASK 0x40u #define AIPS_PACRG_SP6_SHIFT 6 #define AIPS_PACRG_TP5_MASK 0x100u #define AIPS_PACRG_TP5_SHIFT 8 #define AIPS_PACRG_WP5_MASK 0x200u #define AIPS_PACRG_WP5_SHIFT 9 #define AIPS_PACRG_SP5_MASK 0x400u #define AIPS_PACRG_SP5_SHIFT 10 #define AIPS_PACRG_TP4_MASK 0x1000u #define AIPS_PACRG_TP4_SHIFT 12 #define AIPS_PACRG_WP4_MASK 0x2000u #define AIPS_PACRG_WP4_SHIFT 13 #define AIPS_PACRG_SP4_MASK 0x4000u #define AIPS_PACRG_SP4_SHIFT 14 #define AIPS_PACRG_TP3_MASK 0x10000u #define AIPS_PACRG_TP3_SHIFT 16 #define AIPS_PACRG_WP3_MASK 0x20000u #define AIPS_PACRG_WP3_SHIFT 17 #define AIPS_PACRG_SP3_MASK 0x40000u #define AIPS_PACRG_SP3_SHIFT 18 #define AIPS_PACRG_TP2_MASK 0x100000u #define AIPS_PACRG_TP2_SHIFT 20 #define AIPS_PACRG_WP2_MASK 0x200000u #define AIPS_PACRG_WP2_SHIFT 21 #define AIPS_PACRG_SP2_MASK 0x400000u #define AIPS_PACRG_SP2_SHIFT 22 #define AIPS_PACRG_TP1_MASK 0x1000000u #define AIPS_PACRG_TP1_SHIFT 24 #define AIPS_PACRG_WP1_MASK 0x2000000u #define AIPS_PACRG_WP1_SHIFT 25 #define AIPS_PACRG_SP1_MASK 0x4000000u #define AIPS_PACRG_SP1_SHIFT 26 #define AIPS_PACRG_TP0_MASK 0x10000000u #define AIPS_PACRG_TP0_SHIFT 28 #define AIPS_PACRG_WP0_MASK 0x20000000u #define AIPS_PACRG_WP0_SHIFT 29 #define AIPS_PACRG_SP0_MASK 0x40000000u #define AIPS_PACRG_SP0_SHIFT 30 /* PACRH Bit Fields */ #define AIPS_PACRH_TP7_MASK 0x1u #define AIPS_PACRH_TP7_SHIFT 0 #define AIPS_PACRH_WP7_MASK 0x2u #define AIPS_PACRH_WP7_SHIFT 1 #define AIPS_PACRH_SP7_MASK 0x4u #define AIPS_PACRH_SP7_SHIFT 2 #define AIPS_PACRH_TP6_MASK 0x10u #define AIPS_PACRH_TP6_SHIFT 4 #define AIPS_PACRH_WP6_MASK 0x20u #define AIPS_PACRH_WP6_SHIFT 5 #define AIPS_PACRH_SP6_MASK 0x40u #define AIPS_PACRH_SP6_SHIFT 6 #define AIPS_PACRH_TP5_MASK 0x100u #define AIPS_PACRH_TP5_SHIFT 8 #define AIPS_PACRH_WP5_MASK 0x200u #define AIPS_PACRH_WP5_SHIFT 9 #define AIPS_PACRH_SP5_MASK 0x400u #define AIPS_PACRH_SP5_SHIFT 10 #define AIPS_PACRH_TP4_MASK 0x1000u #define AIPS_PACRH_TP4_SHIFT 12 #define AIPS_PACRH_WP4_MASK 0x2000u #define AIPS_PACRH_WP4_SHIFT 13 #define AIPS_PACRH_SP4_MASK 0x4000u #define AIPS_PACRH_SP4_SHIFT 14 #define AIPS_PACRH_TP3_MASK 0x10000u #define AIPS_PACRH_TP3_SHIFT 16 #define AIPS_PACRH_WP3_MASK 0x20000u #define AIPS_PACRH_WP3_SHIFT 17 #define AIPS_PACRH_SP3_MASK 0x40000u #define AIPS_PACRH_SP3_SHIFT 18 #define AIPS_PACRH_TP2_MASK 0x100000u #define AIPS_PACRH_TP2_SHIFT 20 #define AIPS_PACRH_WP2_MASK 0x200000u #define AIPS_PACRH_WP2_SHIFT 21 #define AIPS_PACRH_SP2_MASK 0x400000u #define AIPS_PACRH_SP2_SHIFT 22 #define AIPS_PACRH_TP1_MASK 0x1000000u #define AIPS_PACRH_TP1_SHIFT 24 #define AIPS_PACRH_WP1_MASK 0x2000000u #define AIPS_PACRH_WP1_SHIFT 25 #define AIPS_PACRH_SP1_MASK 0x4000000u #define AIPS_PACRH_SP1_SHIFT 26 #define AIPS_PACRH_TP0_MASK 0x10000000u #define AIPS_PACRH_TP0_SHIFT 28 #define AIPS_PACRH_WP0_MASK 0x20000000u #define AIPS_PACRH_WP0_SHIFT 29 #define AIPS_PACRH_SP0_MASK 0x40000000u #define AIPS_PACRH_SP0_SHIFT 30 /* PACRI Bit Fields */ #define AIPS_PACRI_TP7_MASK 0x1u #define AIPS_PACRI_TP7_SHIFT 0 #define AIPS_PACRI_WP7_MASK 0x2u #define AIPS_PACRI_WP7_SHIFT 1 #define AIPS_PACRI_SP7_MASK 0x4u #define AIPS_PACRI_SP7_SHIFT 2 #define AIPS_PACRI_TP6_MASK 0x10u #define AIPS_PACRI_TP6_SHIFT 4 #define AIPS_PACRI_WP6_MASK 0x20u #define AIPS_PACRI_WP6_SHIFT 5 #define AIPS_PACRI_SP6_MASK 0x40u #define AIPS_PACRI_SP6_SHIFT 6 #define AIPS_PACRI_TP5_MASK 0x100u #define AIPS_PACRI_TP5_SHIFT 8 #define AIPS_PACRI_WP5_MASK 0x200u #define AIPS_PACRI_WP5_SHIFT 9 #define AIPS_PACRI_SP5_MASK 0x400u #define AIPS_PACRI_SP5_SHIFT 10 #define AIPS_PACRI_TP4_MASK 0x1000u #define AIPS_PACRI_TP4_SHIFT 12 #define AIPS_PACRI_WP4_MASK 0x2000u #define AIPS_PACRI_WP4_SHIFT 13 #define AIPS_PACRI_SP4_MASK 0x4000u #define AIPS_PACRI_SP4_SHIFT 14 #define AIPS_PACRI_TP3_MASK 0x10000u #define AIPS_PACRI_TP3_SHIFT 16 #define AIPS_PACRI_WP3_MASK 0x20000u #define AIPS_PACRI_WP3_SHIFT 17 #define AIPS_PACRI_SP3_MASK 0x40000u #define AIPS_PACRI_SP3_SHIFT 18 #define AIPS_PACRI_TP2_MASK 0x100000u #define AIPS_PACRI_TP2_SHIFT 20 #define AIPS_PACRI_WP2_MASK 0x200000u #define AIPS_PACRI_WP2_SHIFT 21 #define AIPS_PACRI_SP2_MASK 0x400000u #define AIPS_PACRI_SP2_SHIFT 22 #define AIPS_PACRI_TP1_MASK 0x1000000u #define AIPS_PACRI_TP1_SHIFT 24 #define AIPS_PACRI_WP1_MASK 0x2000000u #define AIPS_PACRI_WP1_SHIFT 25 #define AIPS_PACRI_SP1_MASK 0x4000000u #define AIPS_PACRI_SP1_SHIFT 26 #define AIPS_PACRI_TP0_MASK 0x10000000u #define AIPS_PACRI_TP0_SHIFT 28 #define AIPS_PACRI_WP0_MASK 0x20000000u #define AIPS_PACRI_WP0_SHIFT 29 #define AIPS_PACRI_SP0_MASK 0x40000000u #define AIPS_PACRI_SP0_SHIFT 30 /* PACRJ Bit Fields */ #define AIPS_PACRJ_TP7_MASK 0x1u #define AIPS_PACRJ_TP7_SHIFT 0 #define AIPS_PACRJ_WP7_MASK 0x2u #define AIPS_PACRJ_WP7_SHIFT 1 #define AIPS_PACRJ_SP7_MASK 0x4u #define AIPS_PACRJ_SP7_SHIFT 2 #define AIPS_PACRJ_TP6_MASK 0x10u #define AIPS_PACRJ_TP6_SHIFT 4 #define AIPS_PACRJ_WP6_MASK 0x20u #define AIPS_PACRJ_WP6_SHIFT 5 #define AIPS_PACRJ_SP6_MASK 0x40u #define AIPS_PACRJ_SP6_SHIFT 6 #define AIPS_PACRJ_TP5_MASK 0x100u #define AIPS_PACRJ_TP5_SHIFT 8 #define AIPS_PACRJ_WP5_MASK 0x200u #define AIPS_PACRJ_WP5_SHIFT 9 #define AIPS_PACRJ_SP5_MASK 0x400u #define AIPS_PACRJ_SP5_SHIFT 10 #define AIPS_PACRJ_TP4_MASK 0x1000u #define AIPS_PACRJ_TP4_SHIFT 12 #define AIPS_PACRJ_WP4_MASK 0x2000u #define AIPS_PACRJ_WP4_SHIFT 13 #define AIPS_PACRJ_SP4_MASK 0x4000u #define AIPS_PACRJ_SP4_SHIFT 14 #define AIPS_PACRJ_TP3_MASK 0x10000u #define AIPS_PACRJ_TP3_SHIFT 16 #define AIPS_PACRJ_WP3_MASK 0x20000u #define AIPS_PACRJ_WP3_SHIFT 17 #define AIPS_PACRJ_SP3_MASK 0x40000u #define AIPS_PACRJ_SP3_SHIFT 18 #define AIPS_PACRJ_TP2_MASK 0x100000u #define AIPS_PACRJ_TP2_SHIFT 20 #define AIPS_PACRJ_WP2_MASK 0x200000u #define AIPS_PACRJ_WP2_SHIFT 21 #define AIPS_PACRJ_SP2_MASK 0x400000u #define AIPS_PACRJ_SP2_SHIFT 22 #define AIPS_PACRJ_TP1_MASK 0x1000000u #define AIPS_PACRJ_TP1_SHIFT 24 #define AIPS_PACRJ_WP1_MASK 0x2000000u #define AIPS_PACRJ_WP1_SHIFT 25 #define AIPS_PACRJ_SP1_MASK 0x4000000u #define AIPS_PACRJ_SP1_SHIFT 26 #define AIPS_PACRJ_TP0_MASK 0x10000000u #define AIPS_PACRJ_TP0_SHIFT 28 #define AIPS_PACRJ_WP0_MASK 0x20000000u #define AIPS_PACRJ_WP0_SHIFT 29 #define AIPS_PACRJ_SP0_MASK 0x40000000u #define AIPS_PACRJ_SP0_SHIFT 30 /* PACRK Bit Fields */ #define AIPS_PACRK_TP7_MASK 0x1u #define AIPS_PACRK_TP7_SHIFT 0 #define AIPS_PACRK_WP7_MASK 0x2u #define AIPS_PACRK_WP7_SHIFT 1 #define AIPS_PACRK_SP7_MASK 0x4u #define AIPS_PACRK_SP7_SHIFT 2 #define AIPS_PACRK_TP6_MASK 0x10u #define AIPS_PACRK_TP6_SHIFT 4 #define AIPS_PACRK_WP6_MASK 0x20u #define AIPS_PACRK_WP6_SHIFT 5 #define AIPS_PACRK_SP6_MASK 0x40u #define AIPS_PACRK_SP6_SHIFT 6 #define AIPS_PACRK_TP5_MASK 0x100u #define AIPS_PACRK_TP5_SHIFT 8 #define AIPS_PACRK_WP5_MASK 0x200u #define AIPS_PACRK_WP5_SHIFT 9 #define AIPS_PACRK_SP5_MASK 0x400u #define AIPS_PACRK_SP5_SHIFT 10 #define AIPS_PACRK_TP4_MASK 0x1000u #define AIPS_PACRK_TP4_SHIFT 12 #define AIPS_PACRK_WP4_MASK 0x2000u #define AIPS_PACRK_WP4_SHIFT 13 #define AIPS_PACRK_SP4_MASK 0x4000u #define AIPS_PACRK_SP4_SHIFT 14 #define AIPS_PACRK_TP3_MASK 0x10000u #define AIPS_PACRK_TP3_SHIFT 16 #define AIPS_PACRK_WP3_MASK 0x20000u #define AIPS_PACRK_WP3_SHIFT 17 #define AIPS_PACRK_SP3_MASK 0x40000u #define AIPS_PACRK_SP3_SHIFT 18 #define AIPS_PACRK_TP2_MASK 0x100000u #define AIPS_PACRK_TP2_SHIFT 20 #define AIPS_PACRK_WP2_MASK 0x200000u #define AIPS_PACRK_WP2_SHIFT 21 #define AIPS_PACRK_SP2_MASK 0x400000u #define AIPS_PACRK_SP2_SHIFT 22 #define AIPS_PACRK_TP1_MASK 0x1000000u #define AIPS_PACRK_TP1_SHIFT 24 #define AIPS_PACRK_WP1_MASK 0x2000000u #define AIPS_PACRK_WP1_SHIFT 25 #define AIPS_PACRK_SP1_MASK 0x4000000u #define AIPS_PACRK_SP1_SHIFT 26 #define AIPS_PACRK_TP0_MASK 0x10000000u #define AIPS_PACRK_TP0_SHIFT 28 #define AIPS_PACRK_WP0_MASK 0x20000000u #define AIPS_PACRK_WP0_SHIFT 29 #define AIPS_PACRK_SP0_MASK 0x40000000u #define AIPS_PACRK_SP0_SHIFT 30 /* PACRL Bit Fields */ #define AIPS_PACRL_TP7_MASK 0x1u #define AIPS_PACRL_TP7_SHIFT 0 #define AIPS_PACRL_WP7_MASK 0x2u #define AIPS_PACRL_WP7_SHIFT 1 #define AIPS_PACRL_SP7_MASK 0x4u #define AIPS_PACRL_SP7_SHIFT 2 #define AIPS_PACRL_TP6_MASK 0x10u #define AIPS_PACRL_TP6_SHIFT 4 #define AIPS_PACRL_WP6_MASK 0x20u #define AIPS_PACRL_WP6_SHIFT 5 #define AIPS_PACRL_SP6_MASK 0x40u #define AIPS_PACRL_SP6_SHIFT 6 #define AIPS_PACRL_TP5_MASK 0x100u #define AIPS_PACRL_TP5_SHIFT 8 #define AIPS_PACRL_WP5_MASK 0x200u #define AIPS_PACRL_WP5_SHIFT 9 #define AIPS_PACRL_SP5_MASK 0x400u #define AIPS_PACRL_SP5_SHIFT 10 #define AIPS_PACRL_TP4_MASK 0x1000u #define AIPS_PACRL_TP4_SHIFT 12 #define AIPS_PACRL_WP4_MASK 0x2000u #define AIPS_PACRL_WP4_SHIFT 13 #define AIPS_PACRL_SP4_MASK 0x4000u #define AIPS_PACRL_SP4_SHIFT 14 #define AIPS_PACRL_TP3_MASK 0x10000u #define AIPS_PACRL_TP3_SHIFT 16 #define AIPS_PACRL_WP3_MASK 0x20000u #define AIPS_PACRL_WP3_SHIFT 17 #define AIPS_PACRL_SP3_MASK 0x40000u #define AIPS_PACRL_SP3_SHIFT 18 #define AIPS_PACRL_TP2_MASK 0x100000u #define AIPS_PACRL_TP2_SHIFT 20 #define AIPS_PACRL_WP2_MASK 0x200000u #define AIPS_PACRL_WP2_SHIFT 21 #define AIPS_PACRL_SP2_MASK 0x400000u #define AIPS_PACRL_SP2_SHIFT 22 #define AIPS_PACRL_TP1_MASK 0x1000000u #define AIPS_PACRL_TP1_SHIFT 24 #define AIPS_PACRL_WP1_MASK 0x2000000u #define AIPS_PACRL_WP1_SHIFT 25 #define AIPS_PACRL_SP1_MASK 0x4000000u #define AIPS_PACRL_SP1_SHIFT 26 #define AIPS_PACRL_TP0_MASK 0x10000000u #define AIPS_PACRL_TP0_SHIFT 28 #define AIPS_PACRL_WP0_MASK 0x20000000u #define AIPS_PACRL_WP0_SHIFT 29 #define AIPS_PACRL_SP0_MASK 0x40000000u #define AIPS_PACRL_SP0_SHIFT 30 /* PACRM Bit Fields */ #define AIPS_PACRM_TP7_MASK 0x1u #define AIPS_PACRM_TP7_SHIFT 0 #define AIPS_PACRM_WP7_MASK 0x2u #define AIPS_PACRM_WP7_SHIFT 1 #define AIPS_PACRM_SP7_MASK 0x4u #define AIPS_PACRM_SP7_SHIFT 2 #define AIPS_PACRM_TP6_MASK 0x10u #define AIPS_PACRM_TP6_SHIFT 4 #define AIPS_PACRM_WP6_MASK 0x20u #define AIPS_PACRM_WP6_SHIFT 5 #define AIPS_PACRM_SP6_MASK 0x40u #define AIPS_PACRM_SP6_SHIFT 6 #define AIPS_PACRM_TP5_MASK 0x100u #define AIPS_PACRM_TP5_SHIFT 8 #define AIPS_PACRM_WP5_MASK 0x200u #define AIPS_PACRM_WP5_SHIFT 9 #define AIPS_PACRM_SP5_MASK 0x400u #define AIPS_PACRM_SP5_SHIFT 10 #define AIPS_PACRM_TP4_MASK 0x1000u #define AIPS_PACRM_TP4_SHIFT 12 #define AIPS_PACRM_WP4_MASK 0x2000u #define AIPS_PACRM_WP4_SHIFT 13 #define AIPS_PACRM_SP4_MASK 0x4000u #define AIPS_PACRM_SP4_SHIFT 14 #define AIPS_PACRM_TP3_MASK 0x10000u #define AIPS_PACRM_TP3_SHIFT 16 #define AIPS_PACRM_WP3_MASK 0x20000u #define AIPS_PACRM_WP3_SHIFT 17 #define AIPS_PACRM_SP3_MASK 0x40000u #define AIPS_PACRM_SP3_SHIFT 18 #define AIPS_PACRM_TP2_MASK 0x100000u #define AIPS_PACRM_TP2_SHIFT 20 #define AIPS_PACRM_WP2_MASK 0x200000u #define AIPS_PACRM_WP2_SHIFT 21 #define AIPS_PACRM_SP2_MASK 0x400000u #define AIPS_PACRM_SP2_SHIFT 22 #define AIPS_PACRM_TP1_MASK 0x1000000u #define AIPS_PACRM_TP1_SHIFT 24 #define AIPS_PACRM_WP1_MASK 0x2000000u #define AIPS_PACRM_WP1_SHIFT 25 #define AIPS_PACRM_SP1_MASK 0x4000000u #define AIPS_PACRM_SP1_SHIFT 26 #define AIPS_PACRM_TP0_MASK 0x10000000u #define AIPS_PACRM_TP0_SHIFT 28 #define AIPS_PACRM_WP0_MASK 0x20000000u #define AIPS_PACRM_WP0_SHIFT 29 #define AIPS_PACRM_SP0_MASK 0x40000000u #define AIPS_PACRM_SP0_SHIFT 30 /* PACRN Bit Fields */ #define AIPS_PACRN_TP7_MASK 0x1u #define AIPS_PACRN_TP7_SHIFT 0 #define AIPS_PACRN_WP7_MASK 0x2u #define AIPS_PACRN_WP7_SHIFT 1 #define AIPS_PACRN_SP7_MASK 0x4u #define AIPS_PACRN_SP7_SHIFT 2 #define AIPS_PACRN_TP6_MASK 0x10u #define AIPS_PACRN_TP6_SHIFT 4 #define AIPS_PACRN_WP6_MASK 0x20u #define AIPS_PACRN_WP6_SHIFT 5 #define AIPS_PACRN_SP6_MASK 0x40u #define AIPS_PACRN_SP6_SHIFT 6 #define AIPS_PACRN_TP5_MASK 0x100u #define AIPS_PACRN_TP5_SHIFT 8 #define AIPS_PACRN_WP5_MASK 0x200u #define AIPS_PACRN_WP5_SHIFT 9 #define AIPS_PACRN_SP5_MASK 0x400u #define AIPS_PACRN_SP5_SHIFT 10 #define AIPS_PACRN_TP4_MASK 0x1000u #define AIPS_PACRN_TP4_SHIFT 12 #define AIPS_PACRN_WP4_MASK 0x2000u #define AIPS_PACRN_WP4_SHIFT 13 #define AIPS_PACRN_SP4_MASK 0x4000u #define AIPS_PACRN_SP4_SHIFT 14 #define AIPS_PACRN_TP3_MASK 0x10000u #define AIPS_PACRN_TP3_SHIFT 16 #define AIPS_PACRN_WP3_MASK 0x20000u #define AIPS_PACRN_WP3_SHIFT 17 #define AIPS_PACRN_SP3_MASK 0x40000u #define AIPS_PACRN_SP3_SHIFT 18 #define AIPS_PACRN_TP2_MASK 0x100000u #define AIPS_PACRN_TP2_SHIFT 20 #define AIPS_PACRN_WP2_MASK 0x200000u #define AIPS_PACRN_WP2_SHIFT 21 #define AIPS_PACRN_SP2_MASK 0x400000u #define AIPS_PACRN_SP2_SHIFT 22 #define AIPS_PACRN_TP1_MASK 0x1000000u #define AIPS_PACRN_TP1_SHIFT 24 #define AIPS_PACRN_WP1_MASK 0x2000000u #define AIPS_PACRN_WP1_SHIFT 25 #define AIPS_PACRN_SP1_MASK 0x4000000u #define AIPS_PACRN_SP1_SHIFT 26 #define AIPS_PACRN_TP0_MASK 0x10000000u #define AIPS_PACRN_TP0_SHIFT 28 #define AIPS_PACRN_WP0_MASK 0x20000000u #define AIPS_PACRN_WP0_SHIFT 29 #define AIPS_PACRN_SP0_MASK 0x40000000u #define AIPS_PACRN_SP0_SHIFT 30 /* PACRO Bit Fields */ #define AIPS_PACRO_TP7_MASK 0x1u #define AIPS_PACRO_TP7_SHIFT 0 #define AIPS_PACRO_WP7_MASK 0x2u #define AIPS_PACRO_WP7_SHIFT 1 #define AIPS_PACRO_SP7_MASK 0x4u #define AIPS_PACRO_SP7_SHIFT 2 #define AIPS_PACRO_TP6_MASK 0x10u #define AIPS_PACRO_TP6_SHIFT 4 #define AIPS_PACRO_WP6_MASK 0x20u #define AIPS_PACRO_WP6_SHIFT 5 #define AIPS_PACRO_SP6_MASK 0x40u #define AIPS_PACRO_SP6_SHIFT 6 #define AIPS_PACRO_TP5_MASK 0x100u #define AIPS_PACRO_TP5_SHIFT 8 #define AIPS_PACRO_WP5_MASK 0x200u #define AIPS_PACRO_WP5_SHIFT 9 #define AIPS_PACRO_SP5_MASK 0x400u #define AIPS_PACRO_SP5_SHIFT 10 #define AIPS_PACRO_TP4_MASK 0x1000u #define AIPS_PACRO_TP4_SHIFT 12 #define AIPS_PACRO_WP4_MASK 0x2000u #define AIPS_PACRO_WP4_SHIFT 13 #define AIPS_PACRO_SP4_MASK 0x4000u #define AIPS_PACRO_SP4_SHIFT 14 #define AIPS_PACRO_TP3_MASK 0x10000u #define AIPS_PACRO_TP3_SHIFT 16 #define AIPS_PACRO_WP3_MASK 0x20000u #define AIPS_PACRO_WP3_SHIFT 17 #define AIPS_PACRO_SP3_MASK 0x40000u #define AIPS_PACRO_SP3_SHIFT 18 #define AIPS_PACRO_TP2_MASK 0x100000u #define AIPS_PACRO_TP2_SHIFT 20 #define AIPS_PACRO_WP2_MASK 0x200000u #define AIPS_PACRO_WP2_SHIFT 21 #define AIPS_PACRO_SP2_MASK 0x400000u #define AIPS_PACRO_SP2_SHIFT 22 #define AIPS_PACRO_TP1_MASK 0x1000000u #define AIPS_PACRO_TP1_SHIFT 24 #define AIPS_PACRO_WP1_MASK 0x2000000u #define AIPS_PACRO_WP1_SHIFT 25 #define AIPS_PACRO_SP1_MASK 0x4000000u #define AIPS_PACRO_SP1_SHIFT 26 #define AIPS_PACRO_TP0_MASK 0x10000000u #define AIPS_PACRO_TP0_SHIFT 28 #define AIPS_PACRO_WP0_MASK 0x20000000u #define AIPS_PACRO_WP0_SHIFT 29 #define AIPS_PACRO_SP0_MASK 0x40000000u #define AIPS_PACRO_SP0_SHIFT 30 /* PACRP Bit Fields */ #define AIPS_PACRP_TP7_MASK 0x1u #define AIPS_PACRP_TP7_SHIFT 0 #define AIPS_PACRP_WP7_MASK 0x2u #define AIPS_PACRP_WP7_SHIFT 1 #define AIPS_PACRP_SP7_MASK 0x4u #define AIPS_PACRP_SP7_SHIFT 2 #define AIPS_PACRP_TP6_MASK 0x10u #define AIPS_PACRP_TP6_SHIFT 4 #define AIPS_PACRP_WP6_MASK 0x20u #define AIPS_PACRP_WP6_SHIFT 5 #define AIPS_PACRP_SP6_MASK 0x40u #define AIPS_PACRP_SP6_SHIFT 6 #define AIPS_PACRP_TP5_MASK 0x100u #define AIPS_PACRP_TP5_SHIFT 8 #define AIPS_PACRP_WP5_MASK 0x200u #define AIPS_PACRP_WP5_SHIFT 9 #define AIPS_PACRP_SP5_MASK 0x400u #define AIPS_PACRP_SP5_SHIFT 10 #define AIPS_PACRP_TP4_MASK 0x1000u #define AIPS_PACRP_TP4_SHIFT 12 #define AIPS_PACRP_WP4_MASK 0x2000u #define AIPS_PACRP_WP4_SHIFT 13 #define AIPS_PACRP_SP4_MASK 0x4000u #define AIPS_PACRP_SP4_SHIFT 14 #define AIPS_PACRP_TP3_MASK 0x10000u #define AIPS_PACRP_TP3_SHIFT 16 #define AIPS_PACRP_WP3_MASK 0x20000u #define AIPS_PACRP_WP3_SHIFT 17 #define AIPS_PACRP_SP3_MASK 0x40000u #define AIPS_PACRP_SP3_SHIFT 18 #define AIPS_PACRP_TP2_MASK 0x100000u #define AIPS_PACRP_TP2_SHIFT 20 #define AIPS_PACRP_WP2_MASK 0x200000u #define AIPS_PACRP_WP2_SHIFT 21 #define AIPS_PACRP_SP2_MASK 0x400000u #define AIPS_PACRP_SP2_SHIFT 22 #define AIPS_PACRP_TP1_MASK 0x1000000u #define AIPS_PACRP_TP1_SHIFT 24 #define AIPS_PACRP_WP1_MASK 0x2000000u #define AIPS_PACRP_WP1_SHIFT 25 #define AIPS_PACRP_SP1_MASK 0x4000000u #define AIPS_PACRP_SP1_SHIFT 26 #define AIPS_PACRP_TP0_MASK 0x10000000u #define AIPS_PACRP_TP0_SHIFT 28 #define AIPS_PACRP_WP0_MASK 0x20000000u #define AIPS_PACRP_WP0_SHIFT 29 #define AIPS_PACRP_SP0_MASK 0x40000000u #define AIPS_PACRP_SP0_SHIFT 30 /* PACRU Bit Fields */ #define AIPS_PACRU_TP1_MASK 0x1000000u #define AIPS_PACRU_TP1_SHIFT 24 #define AIPS_PACRU_WP1_MASK 0x2000000u #define AIPS_PACRU_WP1_SHIFT 25 #define AIPS_PACRU_SP1_MASK 0x4000000u #define AIPS_PACRU_SP1_SHIFT 26 #define AIPS_PACRU_TP0_MASK 0x10000000u #define AIPS_PACRU_TP0_SHIFT 28 #define AIPS_PACRU_WP0_MASK 0x20000000u #define AIPS_PACRU_WP0_SHIFT 29 #define AIPS_PACRU_SP0_MASK 0x40000000u #define AIPS_PACRU_SP0_SHIFT 30 /*! * @} */ /* end of group AIPS_Register_Masks */ /* AIPS - Peripheral instance base addresses */ /** Peripheral AIPS0 base address */ #define AIPS0_BASE (0x40000000u) /** Peripheral AIPS0 base pointer */ #define AIPS0 ((AIPS_Type *)AIPS0_BASE) #define AIPS0_BASE_PTR (AIPS0) /** Peripheral AIPS1 base address */ #define AIPS1_BASE (0x40080000u) /** Peripheral AIPS1 base pointer */ #define AIPS1 ((AIPS_Type *)AIPS1_BASE) #define AIPS1_BASE_PTR (AIPS1) /** Array initializer of AIPS peripheral base addresses */ #define AIPS_BASE_ADDRS { AIPS0_BASE, AIPS1_BASE } /** Array initializer of AIPS peripheral base pointers */ #define AIPS_BASE_PTRS { AIPS0, AIPS1 } /* ---------------------------------------------------------------------------- -- AIPS - Register accessor macros ---------------------------------------------------------------------------- */ /*! * @addtogroup AIPS_Register_Accessor_Macros AIPS - Register accessor macros * @{ */ /* AIPS - Register instance definitions */ /* AIPS0 */ #define AIPS0_MPRA AIPS_MPRA_REG(AIPS0) #define AIPS0_PACRA AIPS_PACRA_REG(AIPS0) #define AIPS0_PACRB AIPS_PACRB_REG(AIPS0) #define AIPS0_PACRC AIPS_PACRC_REG(AIPS0) #define AIPS0_PACRD AIPS_PACRD_REG(AIPS0) #define AIPS0_PACRE AIPS_PACRE_REG(AIPS0) #define AIPS0_PACRF AIPS_PACRF_REG(AIPS0) #define AIPS0_PACRG AIPS_PACRG_REG(AIPS0) #define AIPS0_PACRH AIPS_PACRH_REG(AIPS0) #define AIPS0_PACRI AIPS_PACRI_REG(AIPS0) #define AIPS0_PACRJ AIPS_PACRJ_REG(AIPS0) #define AIPS0_PACRK AIPS_PACRK_REG(AIPS0) #define AIPS0_PACRL AIPS_PACRL_REG(AIPS0) #define AIPS0_PACRM AIPS_PACRM_REG(AIPS0) #define AIPS0_PACRN AIPS_PACRN_REG(AIPS0) #define AIPS0_PACRO AIPS_PACRO_REG(AIPS0) #define AIPS0_PACRP AIPS_PACRP_REG(AIPS0) #define AIPS0_PACRU AIPS_PACRU_REG(AIPS0) /* AIPS1 */ #define AIPS1_MPRA AIPS_MPRA_REG(AIPS1) #define AIPS1_PACRA AIPS_PACRA_REG(AIPS1) #define AIPS1_PACRB AIPS_PACRB_REG(AIPS1) #define AIPS1_PACRC AIPS_PACRC_REG(AIPS1) #define AIPS1_PACRD AIPS_PACRD_REG(AIPS1) #define AIPS1_PACRE AIPS_PACRE_REG(AIPS1) #define AIPS1_PACRF AIPS_PACRF_REG(AIPS1) #define AIPS1_PACRG AIPS_PACRG_REG(AIPS1) #define AIPS1_PACRH AIPS_PACRH_REG(AIPS1) #define AIPS1_PACRI AIPS_PACRI_REG(AIPS1) #define AIPS1_PACRJ AIPS_PACRJ_REG(AIPS1) #define AIPS1_PACRK AIPS_PACRK_REG(AIPS1) #define AIPS1_PACRL AIPS_PACRL_REG(AIPS1) #define AIPS1_PACRM AIPS_PACRM_REG(AIPS1) #define AIPS1_PACRN AIPS_PACRN_REG(AIPS1) #define AIPS1_PACRO AIPS_PACRO_REG(AIPS1) #define AIPS1_PACRP AIPS_PACRP_REG(AIPS1) #define AIPS1_PACRU AIPS_PACRU_REG(AIPS1) /*! * @} */ /* end of group AIPS_Register_Accessor_Macros */ /*! * @} */ /* end of group AIPS_Peripheral_Access_Layer */ /* ---------------------------------------------------------------------------- -- AXBS Peripheral Access Layer ---------------------------------------------------------------------------- */ /*! * @addtogroup AXBS_Peripheral_Access_Layer AXBS Peripheral Access Layer * @{ */ /** AXBS - Register Layout Typedef */ typedef struct { struct { /* offset: 0x0, array step: 0x100 */ __IO uint32_t PRS; /**< Priority Registers Slave, array offset: 0x0, array step: 0x100 */ uint8_t RESERVED_0[12]; __IO uint32_t CRS; /**< Control Register, array offset: 0x10, array step: 0x100 */ uint8_t RESERVED_1[236]; } SLAVE[5]; uint8_t RESERVED_0[768]; __IO uint32_t MGPCR0; /**< Master General Purpose Control Register, offset: 0x800 */ uint8_t RESERVED_1[252]; __IO uint32_t MGPCR1; /**< Master General Purpose Control Register, offset: 0x900 */ uint8_t RESERVED_2[252]; __IO uint32_t MGPCR2; /**< Master General Purpose Control Register, offset: 0xA00 */ uint8_t RESERVED_3[252]; __IO uint32_t MGPCR3; /**< Master General Purpose Control Register, offset: 0xB00 */ uint8_t RESERVED_4[252]; __IO uint32_t MGPCR4; /**< Master General Purpose Control Register, offset: 0xC00 */ uint8_t RESERVED_5[252]; __IO uint32_t MGPCR5; /**< Master General Purpose Control Register, offset: 0xD00 */ } AXBS_Type, *AXBS_MemMapPtr; /* ---------------------------------------------------------------------------- -- AXBS - Register accessor macros ---------------------------------------------------------------------------- */ /*! * @addtogroup AXBS_Register_Accessor_Macros AXBS - Register accessor macros * @{ */ /* AXBS - Register accessors */ #define AXBS_PRS_REG(base,index) ((base)->SLAVE[index].PRS) #define AXBS_CRS_REG(base,index) ((base)->SLAVE[index].CRS) #define AXBS_MGPCR0_REG(base) ((base)->MGPCR0) #define AXBS_MGPCR1_REG(base) ((base)->MGPCR1) #define AXBS_MGPCR2_REG(base) ((base)->MGPCR2) #define AXBS_MGPCR3_REG(base) ((base)->MGPCR3) #define AXBS_MGPCR4_REG(base) ((base)->MGPCR4) #define AXBS_MGPCR5_REG(base) ((base)->MGPCR5) /*! * @} */ /* end of group AXBS_Register_Accessor_Macros */ /* ---------------------------------------------------------------------------- -- AXBS Register Masks ---------------------------------------------------------------------------- */ /*! * @addtogroup AXBS_Register_Masks AXBS Register Masks * @{ */ /* PRS Bit Fields */ #define AXBS_PRS_M0_MASK 0x7u #define AXBS_PRS_M0_SHIFT 0 #define AXBS_PRS_M0(x) (((uint32_t)(((uint32_t)(x))<MCR) #define CAN_CTRL1_REG(base) ((base)->CTRL1) #define CAN_TIMER_REG(base) ((base)->TIMER) #define CAN_RXMGMASK_REG(base) ((base)->RXMGMASK) #define CAN_RX14MASK_REG(base) ((base)->RX14MASK) #define CAN_RX15MASK_REG(base) ((base)->RX15MASK) #define CAN_ECR_REG(base) ((base)->ECR) #define CAN_ESR1_REG(base) ((base)->ESR1) #define CAN_IMASK1_REG(base) ((base)->IMASK1) #define CAN_IFLAG1_REG(base) ((base)->IFLAG1) #define CAN_CTRL2_REG(base) ((base)->CTRL2) #define CAN_ESR2_REG(base) ((base)->ESR2) #define CAN_CRCR_REG(base) ((base)->CRCR) #define CAN_RXFGMASK_REG(base) ((base)->RXFGMASK) #define CAN_RXFIR_REG(base) ((base)->RXFIR) #define CAN_CS_REG(base,index) ((base)->MB[index].CS) #define CAN_ID_REG(base,index) ((base)->MB[index].ID) #define CAN_WORD0_REG(base,index) ((base)->MB[index].WORD0) #define CAN_WORD1_REG(base,index) ((base)->MB[index].WORD1) #define CAN_RXIMR_REG(base,index) ((base)->RXIMR[index]) /*! * @} */ /* end of group CAN_Register_Accessor_Macros */ /* ---------------------------------------------------------------------------- -- CAN Register Masks ---------------------------------------------------------------------------- */ /*! * @addtogroup CAN_Register_Masks CAN Register Masks * @{ */ /* MCR Bit Fields */ #define CAN_MCR_MAXMB_MASK 0x7Fu #define CAN_MCR_MAXMB_SHIFT 0 #define CAN_MCR_MAXMB(x) (((uint32_t)(((uint32_t)(x))<DIRECT[index]) #define CAU_LDR_CASR_REG(base) ((base)->LDR_CASR) #define CAU_LDR_CAA_REG(base) ((base)->LDR_CAA) #define CAU_LDR_CA_REG(base,index) ((base)->LDR_CA[index]) #define CAU_STR_CASR_REG(base) ((base)->STR_CASR) #define CAU_STR_CAA_REG(base) ((base)->STR_CAA) #define CAU_STR_CA_REG(base,index) ((base)->STR_CA[index]) #define CAU_ADR_CASR_REG(base) ((base)->ADR_CASR) #define CAU_ADR_CAA_REG(base) ((base)->ADR_CAA) #define CAU_ADR_CA_REG(base,index) ((base)->ADR_CA[index]) #define CAU_RADR_CASR_REG(base) ((base)->RADR_CASR) #define CAU_RADR_CAA_REG(base) ((base)->RADR_CAA) #define CAU_RADR_CA_REG(base,index) ((base)->RADR_CA[index]) #define CAU_XOR_CASR_REG(base) ((base)->XOR_CASR) #define CAU_XOR_CAA_REG(base) ((base)->XOR_CAA) #define CAU_XOR_CA_REG(base,index) ((base)->XOR_CA[index]) #define CAU_ROTL_CASR_REG(base) ((base)->ROTL_CASR) #define CAU_ROTL_CAA_REG(base) ((base)->ROTL_CAA) #define CAU_ROTL_CA_REG(base,index) ((base)->ROTL_CA[index]) #define CAU_AESC_CASR_REG(base) ((base)->AESC_CASR) #define CAU_AESC_CAA_REG(base) ((base)->AESC_CAA) #define CAU_AESC_CA_REG(base,index) ((base)->AESC_CA[index]) #define CAU_AESIC_CASR_REG(base) ((base)->AESIC_CASR) #define CAU_AESIC_CAA_REG(base) ((base)->AESIC_CAA) #define CAU_AESIC_CA_REG(base,index) ((base)->AESIC_CA[index]) /*! * @} */ /* end of group CAU_Register_Accessor_Macros */ /* ---------------------------------------------------------------------------- -- CAU Register Masks ---------------------------------------------------------------------------- */ /*! * @addtogroup CAU_Register_Masks CAU Register Masks * @{ */ /* DIRECT Bit Fields */ #define CAU_DIRECT_CAU_DIRECT0_MASK 0xFFFFFFFFu #define CAU_DIRECT_CAU_DIRECT0_SHIFT 0 #define CAU_DIRECT_CAU_DIRECT0(x) (((uint32_t)(((uint32_t)(x))<CR0) #define CMP_CR1_REG(base) ((base)->CR1) #define CMP_FPR_REG(base) ((base)->FPR) #define CMP_SCR_REG(base) ((base)->SCR) #define CMP_DACCR_REG(base) ((base)->DACCR) #define CMP_MUXCR_REG(base) ((base)->MUXCR) /*! * @} */ /* end of group CMP_Register_Accessor_Macros */ /* ---------------------------------------------------------------------------- -- CMP Register Masks ---------------------------------------------------------------------------- */ /*! * @addtogroup CMP_Register_Masks CMP Register Masks * @{ */ /* CR0 Bit Fields */ #define CMP_CR0_HYSTCTR_MASK 0x3u #define CMP_CR0_HYSTCTR_SHIFT 0 #define CMP_CR0_HYSTCTR(x) (((uint8_t)(((uint8_t)(x))<CGH1) #define CMT_CGL1_REG(base) ((base)->CGL1) #define CMT_CGH2_REG(base) ((base)->CGH2) #define CMT_CGL2_REG(base) ((base)->CGL2) #define CMT_OC_REG(base) ((base)->OC) #define CMT_MSC_REG(base) ((base)->MSC) #define CMT_CMD1_REG(base) ((base)->CMD1) #define CMT_CMD2_REG(base) ((base)->CMD2) #define CMT_CMD3_REG(base) ((base)->CMD3) #define CMT_CMD4_REG(base) ((base)->CMD4) #define CMT_PPS_REG(base) ((base)->PPS) #define CMT_DMA_REG(base) ((base)->DMA) /*! * @} */ /* end of group CMT_Register_Accessor_Macros */ /* ---------------------------------------------------------------------------- -- CMT Register Masks ---------------------------------------------------------------------------- */ /*! * @addtogroup CMT_Register_Masks CMT Register Masks * @{ */ /* CGH1 Bit Fields */ #define CMT_CGH1_PH_MASK 0xFFu #define CMT_CGH1_PH_SHIFT 0 #define CMT_CGH1_PH(x) (((uint8_t)(((uint8_t)(x))<ACCESS16BIT.DATAL) #define CRC_DATAH_REG(base) ((base)->ACCESS16BIT.DATAH) #define CRC_DATA_REG(base) ((base)->DATA) #define CRC_DATALL_REG(base) ((base)->ACCESS8BIT.DATALL) #define CRC_DATALU_REG(base) ((base)->ACCESS8BIT.DATALU) #define CRC_DATAHL_REG(base) ((base)->ACCESS8BIT.DATAHL) #define CRC_DATAHU_REG(base) ((base)->ACCESS8BIT.DATAHU) #define CRC_GPOLYL_REG(base) ((base)->GPOLY_ACCESS16BIT.GPOLYL) #define CRC_GPOLYH_REG(base) ((base)->GPOLY_ACCESS16BIT.GPOLYH) #define CRC_GPOLY_REG(base) ((base)->GPOLY) #define CRC_GPOLYLL_REG(base) ((base)->GPOLY_ACCESS8BIT.GPOLYLL) #define CRC_GPOLYLU_REG(base) ((base)->GPOLY_ACCESS8BIT.GPOLYLU) #define CRC_GPOLYHL_REG(base) ((base)->GPOLY_ACCESS8BIT.GPOLYHL) #define CRC_GPOLYHU_REG(base) ((base)->GPOLY_ACCESS8BIT.GPOLYHU) #define CRC_CTRL_REG(base) ((base)->CTRL) #define CRC_CTRLHU_REG(base) ((base)->CTRL_ACCESS8BIT.CTRLHU) /*! * @} */ /* end of group CRC_Register_Accessor_Macros */ /* ---------------------------------------------------------------------------- -- CRC Register Masks ---------------------------------------------------------------------------- */ /*! * @addtogroup CRC_Register_Masks CRC Register Masks * @{ */ /* DATAL Bit Fields */ #define CRC_DATAL_DATAL_MASK 0xFFFFu #define CRC_DATAL_DATAL_SHIFT 0 #define CRC_DATAL_DATAL(x) (((uint16_t)(((uint16_t)(x))<DAT[index].DATL) #define DAC_DATH_REG(base,index) ((base)->DAT[index].DATH) #define DAC_SR_REG(base) ((base)->SR) #define DAC_C0_REG(base) ((base)->C0) #define DAC_C1_REG(base) ((base)->C1) #define DAC_C2_REG(base) ((base)->C2) /*! * @} */ /* end of group DAC_Register_Accessor_Macros */ /* ---------------------------------------------------------------------------- -- DAC Register Masks ---------------------------------------------------------------------------- */ /*! * @addtogroup DAC_Register_Masks DAC Register Masks * @{ */ /* DATL Bit Fields */ #define DAC_DATL_DATA0_MASK 0xFFu #define DAC_DATL_DATA0_SHIFT 0 #define DAC_DATL_DATA0(x) (((uint8_t)(((uint8_t)(x))<CR) #define DMA_ES_REG(base) ((base)->ES) #define DMA_ERQ_REG(base) ((base)->ERQ) #define DMA_EEI_REG(base) ((base)->EEI) #define DMA_CEEI_REG(base) ((base)->CEEI) #define DMA_SEEI_REG(base) ((base)->SEEI) #define DMA_CERQ_REG(base) ((base)->CERQ) #define DMA_SERQ_REG(base) ((base)->SERQ) #define DMA_CDNE_REG(base) ((base)->CDNE) #define DMA_SSRT_REG(base) ((base)->SSRT) #define DMA_CERR_REG(base) ((base)->CERR) #define DMA_CINT_REG(base) ((base)->CINT) #define DMA_INT_REG(base) ((base)->INT) #define DMA_ERR_REG(base) ((base)->ERR) #define DMA_HRS_REG(base) ((base)->HRS) #define DMA_DCHPRI3_REG(base) ((base)->DCHPRI3) #define DMA_DCHPRI2_REG(base) ((base)->DCHPRI2) #define DMA_DCHPRI1_REG(base) ((base)->DCHPRI1) #define DMA_DCHPRI0_REG(base) ((base)->DCHPRI0) #define DMA_DCHPRI7_REG(base) ((base)->DCHPRI7) #define DMA_DCHPRI6_REG(base) ((base)->DCHPRI6) #define DMA_DCHPRI5_REG(base) ((base)->DCHPRI5) #define DMA_DCHPRI4_REG(base) ((base)->DCHPRI4) #define DMA_DCHPRI11_REG(base) ((base)->DCHPRI11) #define DMA_DCHPRI10_REG(base) ((base)->DCHPRI10) #define DMA_DCHPRI9_REG(base) ((base)->DCHPRI9) #define DMA_DCHPRI8_REG(base) ((base)->DCHPRI8) #define DMA_DCHPRI15_REG(base) ((base)->DCHPRI15) #define DMA_DCHPRI14_REG(base) ((base)->DCHPRI14) #define DMA_DCHPRI13_REG(base) ((base)->DCHPRI13) #define DMA_DCHPRI12_REG(base) ((base)->DCHPRI12) #define DMA_SADDR_REG(base,index) ((base)->TCD[index].SADDR) #define DMA_SOFF_REG(base,index) ((base)->TCD[index].SOFF) #define DMA_ATTR_REG(base,index) ((base)->TCD[index].ATTR) #define DMA_NBYTES_MLNO_REG(base,index) ((base)->TCD[index].NBYTES_MLNO) #define DMA_NBYTES_MLOFFNO_REG(base,index) ((base)->TCD[index].NBYTES_MLOFFNO) #define DMA_NBYTES_MLOFFYES_REG(base,index) ((base)->TCD[index].NBYTES_MLOFFYES) #define DMA_SLAST_REG(base,index) ((base)->TCD[index].SLAST) #define DMA_DADDR_REG(base,index) ((base)->TCD[index].DADDR) #define DMA_DOFF_REG(base,index) ((base)->TCD[index].DOFF) #define DMA_CITER_ELINKNO_REG(base,index) ((base)->TCD[index].CITER_ELINKNO) #define DMA_CITER_ELINKYES_REG(base,index) ((base)->TCD[index].CITER_ELINKYES) #define DMA_DLAST_SGA_REG(base,index) ((base)->TCD[index].DLAST_SGA) #define DMA_CSR_REG(base,index) ((base)->TCD[index].CSR) #define DMA_BITER_ELINKNO_REG(base,index) ((base)->TCD[index].BITER_ELINKNO) #define DMA_BITER_ELINKYES_REG(base,index) ((base)->TCD[index].BITER_ELINKYES) /*! * @} */ /* end of group DMA_Register_Accessor_Macros */ /* ---------------------------------------------------------------------------- -- DMA Register Masks ---------------------------------------------------------------------------- */ /*! * @addtogroup DMA_Register_Masks DMA Register Masks * @{ */ /* CR Bit Fields */ #define DMA_CR_EDBG_MASK 0x2u #define DMA_CR_EDBG_SHIFT 1 #define DMA_CR_ERCA_MASK 0x4u #define DMA_CR_ERCA_SHIFT 2 #define DMA_CR_HOE_MASK 0x10u #define DMA_CR_HOE_SHIFT 4 #define DMA_CR_HALT_MASK 0x20u #define DMA_CR_HALT_SHIFT 5 #define DMA_CR_CLM_MASK 0x40u #define DMA_CR_CLM_SHIFT 6 #define DMA_CR_EMLM_MASK 0x80u #define DMA_CR_EMLM_SHIFT 7 #define DMA_CR_ECX_MASK 0x10000u #define DMA_CR_ECX_SHIFT 16 #define DMA_CR_CX_MASK 0x20000u #define DMA_CR_CX_SHIFT 17 /* ES Bit Fields */ #define DMA_ES_DBE_MASK 0x1u #define DMA_ES_DBE_SHIFT 0 #define DMA_ES_SBE_MASK 0x2u #define DMA_ES_SBE_SHIFT 1 #define DMA_ES_SGE_MASK 0x4u #define DMA_ES_SGE_SHIFT 2 #define DMA_ES_NCE_MASK 0x8u #define DMA_ES_NCE_SHIFT 3 #define DMA_ES_DOE_MASK 0x10u #define DMA_ES_DOE_SHIFT 4 #define DMA_ES_DAE_MASK 0x20u #define DMA_ES_DAE_SHIFT 5 #define DMA_ES_SOE_MASK 0x40u #define DMA_ES_SOE_SHIFT 6 #define DMA_ES_SAE_MASK 0x80u #define DMA_ES_SAE_SHIFT 7 #define DMA_ES_ERRCHN_MASK 0xF00u #define DMA_ES_ERRCHN_SHIFT 8 #define DMA_ES_ERRCHN(x) (((uint32_t)(((uint32_t)(x))<CHCFG[index]) /*! * @} */ /* end of group DMAMUX_Register_Accessor_Macros */ /* ---------------------------------------------------------------------------- -- DMAMUX Register Masks ---------------------------------------------------------------------------- */ /*! * @addtogroup DMAMUX_Register_Masks DMAMUX Register Masks * @{ */ /* CHCFG Bit Fields */ #define DMAMUX_CHCFG_SOURCE_MASK 0x3Fu #define DMAMUX_CHCFG_SOURCE_SHIFT 0 #define DMAMUX_CHCFG_SOURCE(x) (((uint8_t)(((uint8_t)(x))<EIR) #define ENET_EIMR_REG(base) ((base)->EIMR) #define ENET_RDAR_REG(base) ((base)->RDAR) #define ENET_TDAR_REG(base) ((base)->TDAR) #define ENET_ECR_REG(base) ((base)->ECR) #define ENET_MMFR_REG(base) ((base)->MMFR) #define ENET_MSCR_REG(base) ((base)->MSCR) #define ENET_MIBC_REG(base) ((base)->MIBC) #define ENET_RCR_REG(base) ((base)->RCR) #define ENET_TCR_REG(base) ((base)->TCR) #define ENET_PALR_REG(base) ((base)->PALR) #define ENET_PAUR_REG(base) ((base)->PAUR) #define ENET_OPD_REG(base) ((base)->OPD) #define ENET_IAUR_REG(base) ((base)->IAUR) #define ENET_IALR_REG(base) ((base)->IALR) #define ENET_GAUR_REG(base) ((base)->GAUR) #define ENET_GALR_REG(base) ((base)->GALR) #define ENET_TFWR_REG(base) ((base)->TFWR) #define ENET_RDSR_REG(base) ((base)->RDSR) #define ENET_TDSR_REG(base) ((base)->TDSR) #define ENET_MRBR_REG(base) ((base)->MRBR) #define ENET_RSFL_REG(base) ((base)->RSFL) #define ENET_RSEM_REG(base) ((base)->RSEM) #define ENET_RAEM_REG(base) ((base)->RAEM) #define ENET_RAFL_REG(base) ((base)->RAFL) #define ENET_TSEM_REG(base) ((base)->TSEM) #define ENET_TAEM_REG(base) ((base)->TAEM) #define ENET_TAFL_REG(base) ((base)->TAFL) #define ENET_TIPG_REG(base) ((base)->TIPG) #define ENET_FTRL_REG(base) ((base)->FTRL) #define ENET_TACC_REG(base) ((base)->TACC) #define ENET_RACC_REG(base) ((base)->RACC) #define ENET_RMON_T_PACKETS_REG(base) ((base)->RMON_T_PACKETS) #define ENET_RMON_T_BC_PKT_REG(base) ((base)->RMON_T_BC_PKT) #define ENET_RMON_T_MC_PKT_REG(base) ((base)->RMON_T_MC_PKT) #define ENET_RMON_T_CRC_ALIGN_REG(base) ((base)->RMON_T_CRC_ALIGN) #define ENET_RMON_T_UNDERSIZE_REG(base) ((base)->RMON_T_UNDERSIZE) #define ENET_RMON_T_OVERSIZE_REG(base) ((base)->RMON_T_OVERSIZE) #define ENET_RMON_T_FRAG_REG(base) ((base)->RMON_T_FRAG) #define ENET_RMON_T_JAB_REG(base) ((base)->RMON_T_JAB) #define ENET_RMON_T_COL_REG(base) ((base)->RMON_T_COL) #define ENET_RMON_T_P64_REG(base) ((base)->RMON_T_P64) #define ENET_RMON_T_P65TO127_REG(base) ((base)->RMON_T_P65TO127) #define ENET_RMON_T_P128TO255_REG(base) ((base)->RMON_T_P128TO255) #define ENET_RMON_T_P256TO511_REG(base) ((base)->RMON_T_P256TO511) #define ENET_RMON_T_P512TO1023_REG(base) ((base)->RMON_T_P512TO1023) #define ENET_RMON_T_P1024TO2047_REG(base) ((base)->RMON_T_P1024TO2047) #define ENET_RMON_T_P_GTE2048_REG(base) ((base)->RMON_T_P_GTE2048) #define ENET_RMON_T_OCTETS_REG(base) ((base)->RMON_T_OCTETS) #define ENET_IEEE_T_FRAME_OK_REG(base) ((base)->IEEE_T_FRAME_OK) #define ENET_IEEE_T_1COL_REG(base) ((base)->IEEE_T_1COL) #define ENET_IEEE_T_MCOL_REG(base) ((base)->IEEE_T_MCOL) #define ENET_IEEE_T_DEF_REG(base) ((base)->IEEE_T_DEF) #define ENET_IEEE_T_LCOL_REG(base) ((base)->IEEE_T_LCOL) #define ENET_IEEE_T_EXCOL_REG(base) ((base)->IEEE_T_EXCOL) #define ENET_IEEE_T_MACERR_REG(base) ((base)->IEEE_T_MACERR) #define ENET_IEEE_T_CSERR_REG(base) ((base)->IEEE_T_CSERR) #define ENET_IEEE_T_FDXFC_REG(base) ((base)->IEEE_T_FDXFC) #define ENET_IEEE_T_OCTETS_OK_REG(base) ((base)->IEEE_T_OCTETS_OK) #define ENET_RMON_R_PACKETS_REG(base) ((base)->RMON_R_PACKETS) #define ENET_RMON_R_BC_PKT_REG(base) ((base)->RMON_R_BC_PKT) #define ENET_RMON_R_MC_PKT_REG(base) ((base)->RMON_R_MC_PKT) #define ENET_RMON_R_CRC_ALIGN_REG(base) ((base)->RMON_R_CRC_ALIGN) #define ENET_RMON_R_UNDERSIZE_REG(base) ((base)->RMON_R_UNDERSIZE) #define ENET_RMON_R_OVERSIZE_REG(base) ((base)->RMON_R_OVERSIZE) #define ENET_RMON_R_FRAG_REG(base) ((base)->RMON_R_FRAG) #define ENET_RMON_R_JAB_REG(base) ((base)->RMON_R_JAB) #define ENET_RMON_R_P64_REG(base) ((base)->RMON_R_P64) #define ENET_RMON_R_P65TO127_REG(base) ((base)->RMON_R_P65TO127) #define ENET_RMON_R_P128TO255_REG(base) ((base)->RMON_R_P128TO255) #define ENET_RMON_R_P256TO511_REG(base) ((base)->RMON_R_P256TO511) #define ENET_RMON_R_P512TO1023_REG(base) ((base)->RMON_R_P512TO1023) #define ENET_RMON_R_P1024TO2047_REG(base) ((base)->RMON_R_P1024TO2047) #define ENET_RMON_R_P_GTE2048_REG(base) ((base)->RMON_R_P_GTE2048) #define ENET_RMON_R_OCTETS_REG(base) ((base)->RMON_R_OCTETS) #define ENET_IEEE_R_DROP_REG(base) ((base)->IEEE_R_DROP) #define ENET_IEEE_R_FRAME_OK_REG(base) ((base)->IEEE_R_FRAME_OK) #define ENET_IEEE_R_CRC_REG(base) ((base)->IEEE_R_CRC) #define ENET_IEEE_R_ALIGN_REG(base) ((base)->IEEE_R_ALIGN) #define ENET_IEEE_R_MACERR_REG(base) ((base)->IEEE_R_MACERR) #define ENET_IEEE_R_FDXFC_REG(base) ((base)->IEEE_R_FDXFC) #define ENET_IEEE_R_OCTETS_OK_REG(base) ((base)->IEEE_R_OCTETS_OK) #define ENET_ATCR_REG(base) ((base)->ATCR) #define ENET_ATVR_REG(base) ((base)->ATVR) #define ENET_ATOFF_REG(base) ((base)->ATOFF) #define ENET_ATPER_REG(base) ((base)->ATPER) #define ENET_ATCOR_REG(base) ((base)->ATCOR) #define ENET_ATINC_REG(base) ((base)->ATINC) #define ENET_ATSTMP_REG(base) ((base)->ATSTMP) #define ENET_TGSR_REG(base) ((base)->TGSR) #define ENET_TCSR_REG(base,index) ((base)->CHANNEL[index].TCSR) #define ENET_TCCR_REG(base,index) ((base)->CHANNEL[index].TCCR) /*! * @} */ /* end of group ENET_Register_Accessor_Macros */ /* ---------------------------------------------------------------------------- -- ENET Register Masks ---------------------------------------------------------------------------- */ /*! * @addtogroup ENET_Register_Masks ENET Register Masks * @{ */ /* EIR Bit Fields */ #define ENET_EIR_TS_TIMER_MASK 0x8000u #define ENET_EIR_TS_TIMER_SHIFT 15 #define ENET_EIR_TS_AVAIL_MASK 0x10000u #define ENET_EIR_TS_AVAIL_SHIFT 16 #define ENET_EIR_WAKEUP_MASK 0x20000u #define ENET_EIR_WAKEUP_SHIFT 17 #define ENET_EIR_PLR_MASK 0x40000u #define ENET_EIR_PLR_SHIFT 18 #define ENET_EIR_UN_MASK 0x80000u #define ENET_EIR_UN_SHIFT 19 #define ENET_EIR_RL_MASK 0x100000u #define ENET_EIR_RL_SHIFT 20 #define ENET_EIR_LC_MASK 0x200000u #define ENET_EIR_LC_SHIFT 21 #define ENET_EIR_EBERR_MASK 0x400000u #define ENET_EIR_EBERR_SHIFT 22 #define ENET_EIR_MII_MASK 0x800000u #define ENET_EIR_MII_SHIFT 23 #define ENET_EIR_RXB_MASK 0x1000000u #define ENET_EIR_RXB_SHIFT 24 #define ENET_EIR_RXF_MASK 0x2000000u #define ENET_EIR_RXF_SHIFT 25 #define ENET_EIR_TXB_MASK 0x4000000u #define ENET_EIR_TXB_SHIFT 26 #define ENET_EIR_TXF_MASK 0x8000000u #define ENET_EIR_TXF_SHIFT 27 #define ENET_EIR_GRA_MASK 0x10000000u #define ENET_EIR_GRA_SHIFT 28 #define ENET_EIR_BABT_MASK 0x20000000u #define ENET_EIR_BABT_SHIFT 29 #define ENET_EIR_BABR_MASK 0x40000000u #define ENET_EIR_BABR_SHIFT 30 /* EIMR Bit Fields */ #define ENET_EIMR_TS_TIMER_MASK 0x8000u #define ENET_EIMR_TS_TIMER_SHIFT 15 #define ENET_EIMR_TS_AVAIL_MASK 0x10000u #define ENET_EIMR_TS_AVAIL_SHIFT 16 #define ENET_EIMR_WAKEUP_MASK 0x20000u #define ENET_EIMR_WAKEUP_SHIFT 17 #define ENET_EIMR_PLR_MASK 0x40000u #define ENET_EIMR_PLR_SHIFT 18 #define ENET_EIMR_UN_MASK 0x80000u #define ENET_EIMR_UN_SHIFT 19 #define ENET_EIMR_RL_MASK 0x100000u #define ENET_EIMR_RL_SHIFT 20 #define ENET_EIMR_LC_MASK 0x200000u #define ENET_EIMR_LC_SHIFT 21 #define ENET_EIMR_EBERR_MASK 0x400000u #define ENET_EIMR_EBERR_SHIFT 22 #define ENET_EIMR_MII_MASK 0x800000u #define ENET_EIMR_MII_SHIFT 23 #define ENET_EIMR_RXB_MASK 0x1000000u #define ENET_EIMR_RXB_SHIFT 24 #define ENET_EIMR_RXF_MASK 0x2000000u #define ENET_EIMR_RXF_SHIFT 25 #define ENET_EIMR_TXB_MASK 0x4000000u #define ENET_EIMR_TXB_SHIFT 26 #define ENET_EIMR_TXF_MASK 0x8000000u #define ENET_EIMR_TXF_SHIFT 27 #define ENET_EIMR_GRA_MASK 0x10000000u #define ENET_EIMR_GRA_SHIFT 28 #define ENET_EIMR_BABT_MASK 0x20000000u #define ENET_EIMR_BABT_SHIFT 29 #define ENET_EIMR_BABR_MASK 0x40000000u #define ENET_EIMR_BABR_SHIFT 30 /* RDAR Bit Fields */ #define ENET_RDAR_RDAR_MASK 0x1000000u #define ENET_RDAR_RDAR_SHIFT 24 /* TDAR Bit Fields */ #define ENET_TDAR_TDAR_MASK 0x1000000u #define ENET_TDAR_TDAR_SHIFT 24 /* ECR Bit Fields */ #define ENET_ECR_RESET_MASK 0x1u #define ENET_ECR_RESET_SHIFT 0 #define ENET_ECR_ETHEREN_MASK 0x2u #define ENET_ECR_ETHEREN_SHIFT 1 #define ENET_ECR_MAGICEN_MASK 0x4u #define ENET_ECR_MAGICEN_SHIFT 2 #define ENET_ECR_SLEEP_MASK 0x8u #define ENET_ECR_SLEEP_SHIFT 3 #define ENET_ECR_EN1588_MASK 0x10u #define ENET_ECR_EN1588_SHIFT 4 #define ENET_ECR_DBGEN_MASK 0x40u #define ENET_ECR_DBGEN_SHIFT 6 #define ENET_ECR_STOPEN_MASK 0x80u #define ENET_ECR_STOPEN_SHIFT 7 #define ENET_ECR_DBSWP_MASK 0x100u #define ENET_ECR_DBSWP_SHIFT 8 /* MMFR Bit Fields */ #define ENET_MMFR_DATA_MASK 0xFFFFu #define ENET_MMFR_DATA_SHIFT 0 #define ENET_MMFR_DATA(x) (((uint32_t)(((uint32_t)(x))<CTRL) #define EWM_SERV_REG(base) ((base)->SERV) #define EWM_CMPL_REG(base) ((base)->CMPL) #define EWM_CMPH_REG(base) ((base)->CMPH) /*! * @} */ /* end of group EWM_Register_Accessor_Macros */ /* ---------------------------------------------------------------------------- -- EWM Register Masks ---------------------------------------------------------------------------- */ /*! * @addtogroup EWM_Register_Masks EWM Register Masks * @{ */ /* CTRL Bit Fields */ #define EWM_CTRL_EWMEN_MASK 0x1u #define EWM_CTRL_EWMEN_SHIFT 0 #define EWM_CTRL_ASSIN_MASK 0x2u #define EWM_CTRL_ASSIN_SHIFT 1 #define EWM_CTRL_INEN_MASK 0x4u #define EWM_CTRL_INEN_SHIFT 2 #define EWM_CTRL_INTEN_MASK 0x8u #define EWM_CTRL_INTEN_SHIFT 3 /* SERV Bit Fields */ #define EWM_SERV_SERVICE_MASK 0xFFu #define EWM_SERV_SERVICE_SHIFT 0 #define EWM_SERV_SERVICE(x) (((uint8_t)(((uint8_t)(x))<CS[index].CSAR) #define FB_CSMR_REG(base,index) ((base)->CS[index].CSMR) #define FB_CSCR_REG(base,index) ((base)->CS[index].CSCR) #define FB_CSPMCR_REG(base) ((base)->CSPMCR) /*! * @} */ /* end of group FB_Register_Accessor_Macros */ /* ---------------------------------------------------------------------------- -- FB Register Masks ---------------------------------------------------------------------------- */ /*! * @addtogroup FB_Register_Masks FB Register Masks * @{ */ /* CSAR Bit Fields */ #define FB_CSAR_BA_MASK 0xFFFF0000u #define FB_CSAR_BA_SHIFT 16 #define FB_CSAR_BA(x) (((uint32_t)(((uint32_t)(x))<PFAPR) #define FMC_PFB0CR_REG(base) ((base)->PFB0CR) #define FMC_PFB1CR_REG(base) ((base)->PFB1CR) #define FMC_TAGVDW0S_REG(base,index) ((base)->TAGVDW0S[index]) #define FMC_TAGVDW1S_REG(base,index) ((base)->TAGVDW1S[index]) #define FMC_TAGVDW2S_REG(base,index) ((base)->TAGVDW2S[index]) #define FMC_TAGVDW3S_REG(base,index) ((base)->TAGVDW3S[index]) #define FMC_DATA_U_REG(base,index,index2) ((base)->SET[index][index2].DATA_U) #define FMC_DATA_L_REG(base,index,index2) ((base)->SET[index][index2].DATA_L) /*! * @} */ /* end of group FMC_Register_Accessor_Macros */ /* ---------------------------------------------------------------------------- -- FMC Register Masks ---------------------------------------------------------------------------- */ /*! * @addtogroup FMC_Register_Masks FMC Register Masks * @{ */ /* PFAPR Bit Fields */ #define FMC_PFAPR_M0AP_MASK 0x3u #define FMC_PFAPR_M0AP_SHIFT 0 #define FMC_PFAPR_M0AP(x) (((uint32_t)(((uint32_t)(x))<FSTAT) #define FTFE_FCNFG_REG(base) ((base)->FCNFG) #define FTFE_FSEC_REG(base) ((base)->FSEC) #define FTFE_FOPT_REG(base) ((base)->FOPT) #define FTFE_FCCOB3_REG(base) ((base)->FCCOB3) #define FTFE_FCCOB2_REG(base) ((base)->FCCOB2) #define FTFE_FCCOB1_REG(base) ((base)->FCCOB1) #define FTFE_FCCOB0_REG(base) ((base)->FCCOB0) #define FTFE_FCCOB7_REG(base) ((base)->FCCOB7) #define FTFE_FCCOB6_REG(base) ((base)->FCCOB6) #define FTFE_FCCOB5_REG(base) ((base)->FCCOB5) #define FTFE_FCCOB4_REG(base) ((base)->FCCOB4) #define FTFE_FCCOBB_REG(base) ((base)->FCCOBB) #define FTFE_FCCOBA_REG(base) ((base)->FCCOBA) #define FTFE_FCCOB9_REG(base) ((base)->FCCOB9) #define FTFE_FCCOB8_REG(base) ((base)->FCCOB8) #define FTFE_FPROT3_REG(base) ((base)->FPROT3) #define FTFE_FPROT2_REG(base) ((base)->FPROT2) #define FTFE_FPROT1_REG(base) ((base)->FPROT1) #define FTFE_FPROT0_REG(base) ((base)->FPROT0) #define FTFE_FEPROT_REG(base) ((base)->FEPROT) #define FTFE_FDPROT_REG(base) ((base)->FDPROT) /*! * @} */ /* end of group FTFE_Register_Accessor_Macros */ /* ---------------------------------------------------------------------------- -- FTFE Register Masks ---------------------------------------------------------------------------- */ /*! * @addtogroup FTFE_Register_Masks FTFE Register Masks * @{ */ /* FSTAT Bit Fields */ #define FTFE_FSTAT_MGSTAT0_MASK 0x1u #define FTFE_FSTAT_MGSTAT0_SHIFT 0 #define FTFE_FSTAT_FPVIOL_MASK 0x10u #define FTFE_FSTAT_FPVIOL_SHIFT 4 #define FTFE_FSTAT_ACCERR_MASK 0x20u #define FTFE_FSTAT_ACCERR_SHIFT 5 #define FTFE_FSTAT_RDCOLERR_MASK 0x40u #define FTFE_FSTAT_RDCOLERR_SHIFT 6 #define FTFE_FSTAT_CCIF_MASK 0x80u #define FTFE_FSTAT_CCIF_SHIFT 7 /* FCNFG Bit Fields */ #define FTFE_FCNFG_EEERDY_MASK 0x1u #define FTFE_FCNFG_EEERDY_SHIFT 0 #define FTFE_FCNFG_RAMRDY_MASK 0x2u #define FTFE_FCNFG_RAMRDY_SHIFT 1 #define FTFE_FCNFG_PFLSH_MASK 0x4u #define FTFE_FCNFG_PFLSH_SHIFT 2 #define FTFE_FCNFG_SWAP_MASK 0x8u #define FTFE_FCNFG_SWAP_SHIFT 3 #define FTFE_FCNFG_ERSSUSP_MASK 0x10u #define FTFE_FCNFG_ERSSUSP_SHIFT 4 #define FTFE_FCNFG_ERSAREQ_MASK 0x20u #define FTFE_FCNFG_ERSAREQ_SHIFT 5 #define FTFE_FCNFG_RDCOLLIE_MASK 0x40u #define FTFE_FCNFG_RDCOLLIE_SHIFT 6 #define FTFE_FCNFG_CCIE_MASK 0x80u #define FTFE_FCNFG_CCIE_SHIFT 7 /* FSEC Bit Fields */ #define FTFE_FSEC_SEC_MASK 0x3u #define FTFE_FSEC_SEC_SHIFT 0 #define FTFE_FSEC_SEC(x) (((uint8_t)(((uint8_t)(x))<SC) #define FTM_CNT_REG(base) ((base)->CNT) #define FTM_MOD_REG(base) ((base)->MOD) #define FTM_CnSC_REG(base,index) ((base)->CONTROLS[index].CnSC) #define FTM_CnV_REG(base,index) ((base)->CONTROLS[index].CnV) #define FTM_CNTIN_REG(base) ((base)->CNTIN) #define FTM_STATUS_REG(base) ((base)->STATUS) #define FTM_MODE_REG(base) ((base)->MODE) #define FTM_SYNC_REG(base) ((base)->SYNC) #define FTM_OUTINIT_REG(base) ((base)->OUTINIT) #define FTM_OUTMASK_REG(base) ((base)->OUTMASK) #define FTM_COMBINE_REG(base) ((base)->COMBINE) #define FTM_DEADTIME_REG(base) ((base)->DEADTIME) #define FTM_EXTTRIG_REG(base) ((base)->EXTTRIG) #define FTM_POL_REG(base) ((base)->POL) #define FTM_FMS_REG(base) ((base)->FMS) #define FTM_FILTER_REG(base) ((base)->FILTER) #define FTM_FLTCTRL_REG(base) ((base)->FLTCTRL) #define FTM_QDCTRL_REG(base) ((base)->QDCTRL) #define FTM_CONF_REG(base) ((base)->CONF) #define FTM_FLTPOL_REG(base) ((base)->FLTPOL) #define FTM_SYNCONF_REG(base) ((base)->SYNCONF) #define FTM_INVCTRL_REG(base) ((base)->INVCTRL) #define FTM_SWOCTRL_REG(base) ((base)->SWOCTRL) #define FTM_PWMLOAD_REG(base) ((base)->PWMLOAD) /*! * @} */ /* end of group FTM_Register_Accessor_Macros */ /* ---------------------------------------------------------------------------- -- FTM Register Masks ---------------------------------------------------------------------------- */ /*! * @addtogroup FTM_Register_Masks FTM Register Masks * @{ */ /* SC Bit Fields */ #define FTM_SC_PS_MASK 0x7u #define FTM_SC_PS_SHIFT 0 #define FTM_SC_PS(x) (((uint32_t)(((uint32_t)(x))<PDOR) #define GPIO_PSOR_REG(base) ((base)->PSOR) #define GPIO_PCOR_REG(base) ((base)->PCOR) #define GPIO_PTOR_REG(base) ((base)->PTOR) #define GPIO_PDIR_REG(base) ((base)->PDIR) #define GPIO_PDDR_REG(base) ((base)->PDDR) /*! * @} */ /* end of group GPIO_Register_Accessor_Macros */ /* ---------------------------------------------------------------------------- -- GPIO Register Masks ---------------------------------------------------------------------------- */ /*! * @addtogroup GPIO_Register_Masks GPIO Register Masks * @{ */ /* PDOR Bit Fields */ #define GPIO_PDOR_PDO_MASK 0xFFFFFFFFu #define GPIO_PDOR_PDO_SHIFT 0 #define GPIO_PDOR_PDO(x) (((uint32_t)(((uint32_t)(x))<A1) #define I2C_F_REG(base) ((base)->F) #define I2C_C1_REG(base) ((base)->C1) #define I2C_S_REG(base) ((base)->S) #define I2C_D_REG(base) ((base)->D) #define I2C_C2_REG(base) ((base)->C2) #define I2C_FLT_REG(base) ((base)->FLT) #define I2C_RA_REG(base) ((base)->RA) #define I2C_SMB_REG(base) ((base)->SMB) #define I2C_A2_REG(base) ((base)->A2) #define I2C_SLTH_REG(base) ((base)->SLTH) #define I2C_SLTL_REG(base) ((base)->SLTL) /*! * @} */ /* end of group I2C_Register_Accessor_Macros */ /* ---------------------------------------------------------------------------- -- I2C Register Masks ---------------------------------------------------------------------------- */ /*! * @addtogroup I2C_Register_Masks I2C Register Masks * @{ */ /* A1 Bit Fields */ #define I2C_A1_AD_MASK 0xFEu #define I2C_A1_AD_SHIFT 1 #define I2C_A1_AD(x) (((uint8_t)(((uint8_t)(x))<TCSR) #define I2S_TCR1_REG(base) ((base)->TCR1) #define I2S_TCR2_REG(base) ((base)->TCR2) #define I2S_TCR3_REG(base) ((base)->TCR3) #define I2S_TCR4_REG(base) ((base)->TCR4) #define I2S_TCR5_REG(base) ((base)->TCR5) #define I2S_TDR_REG(base,index) ((base)->TDR[index]) #define I2S_TFR_REG(base,index) ((base)->TFR[index]) #define I2S_TMR_REG(base) ((base)->TMR) #define I2S_RCSR_REG(base) ((base)->RCSR) #define I2S_RCR1_REG(base) ((base)->RCR1) #define I2S_RCR2_REG(base) ((base)->RCR2) #define I2S_RCR3_REG(base) ((base)->RCR3) #define I2S_RCR4_REG(base) ((base)->RCR4) #define I2S_RCR5_REG(base) ((base)->RCR5) #define I2S_RDR_REG(base,index) ((base)->RDR[index]) #define I2S_RFR_REG(base,index) ((base)->RFR[index]) #define I2S_RMR_REG(base) ((base)->RMR) #define I2S_MCR_REG(base) ((base)->MCR) #define I2S_MDR_REG(base) ((base)->MDR) /*! * @} */ /* end of group I2S_Register_Accessor_Macros */ /* ---------------------------------------------------------------------------- -- I2S Register Masks ---------------------------------------------------------------------------- */ /*! * @addtogroup I2S_Register_Masks I2S Register Masks * @{ */ /* TCSR Bit Fields */ #define I2S_TCSR_FRDE_MASK 0x1u #define I2S_TCSR_FRDE_SHIFT 0 #define I2S_TCSR_FWDE_MASK 0x2u #define I2S_TCSR_FWDE_SHIFT 1 #define I2S_TCSR_FRIE_MASK 0x100u #define I2S_TCSR_FRIE_SHIFT 8 #define I2S_TCSR_FWIE_MASK 0x200u #define I2S_TCSR_FWIE_SHIFT 9 #define I2S_TCSR_FEIE_MASK 0x400u #define I2S_TCSR_FEIE_SHIFT 10 #define I2S_TCSR_SEIE_MASK 0x800u #define I2S_TCSR_SEIE_SHIFT 11 #define I2S_TCSR_WSIE_MASK 0x1000u #define I2S_TCSR_WSIE_SHIFT 12 #define I2S_TCSR_FRF_MASK 0x10000u #define I2S_TCSR_FRF_SHIFT 16 #define I2S_TCSR_FWF_MASK 0x20000u #define I2S_TCSR_FWF_SHIFT 17 #define I2S_TCSR_FEF_MASK 0x40000u #define I2S_TCSR_FEF_SHIFT 18 #define I2S_TCSR_SEF_MASK 0x80000u #define I2S_TCSR_SEF_SHIFT 19 #define I2S_TCSR_WSF_MASK 0x100000u #define I2S_TCSR_WSF_SHIFT 20 #define I2S_TCSR_SR_MASK 0x1000000u #define I2S_TCSR_SR_SHIFT 24 #define I2S_TCSR_FR_MASK 0x2000000u #define I2S_TCSR_FR_SHIFT 25 #define I2S_TCSR_BCE_MASK 0x10000000u #define I2S_TCSR_BCE_SHIFT 28 #define I2S_TCSR_DBGE_MASK 0x20000000u #define I2S_TCSR_DBGE_SHIFT 29 #define I2S_TCSR_STOPE_MASK 0x40000000u #define I2S_TCSR_STOPE_SHIFT 30 #define I2S_TCSR_TE_MASK 0x80000000u #define I2S_TCSR_TE_SHIFT 31 /* TCR1 Bit Fields */ #define I2S_TCR1_TFW_MASK 0x7u #define I2S_TCR1_TFW_SHIFT 0 #define I2S_TCR1_TFW(x) (((uint32_t)(((uint32_t)(x))<PE1) #define LLWU_PE2_REG(base) ((base)->PE2) #define LLWU_PE3_REG(base) ((base)->PE3) #define LLWU_PE4_REG(base) ((base)->PE4) #define LLWU_ME_REG(base) ((base)->ME) #define LLWU_F1_REG(base) ((base)->F1) #define LLWU_F2_REG(base) ((base)->F2) #define LLWU_F3_REG(base) ((base)->F3) #define LLWU_FILT1_REG(base) ((base)->FILT1) #define LLWU_FILT2_REG(base) ((base)->FILT2) #define LLWU_RST_REG(base) ((base)->RST) /*! * @} */ /* end of group LLWU_Register_Accessor_Macros */ /* ---------------------------------------------------------------------------- -- LLWU Register Masks ---------------------------------------------------------------------------- */ /*! * @addtogroup LLWU_Register_Masks LLWU Register Masks * @{ */ /* PE1 Bit Fields */ #define LLWU_PE1_WUPE0_MASK 0x3u #define LLWU_PE1_WUPE0_SHIFT 0 #define LLWU_PE1_WUPE0(x) (((uint8_t)(((uint8_t)(x))<CSR) #define LPTMR_PSR_REG(base) ((base)->PSR) #define LPTMR_CMR_REG(base) ((base)->CMR) #define LPTMR_CNR_REG(base) ((base)->CNR) /*! * @} */ /* end of group LPTMR_Register_Accessor_Macros */ /* ---------------------------------------------------------------------------- -- LPTMR Register Masks ---------------------------------------------------------------------------- */ /*! * @addtogroup LPTMR_Register_Masks LPTMR Register Masks * @{ */ /* CSR Bit Fields */ #define LPTMR_CSR_TEN_MASK 0x1u #define LPTMR_CSR_TEN_SHIFT 0 #define LPTMR_CSR_TMS_MASK 0x2u #define LPTMR_CSR_TMS_SHIFT 1 #define LPTMR_CSR_TFC_MASK 0x4u #define LPTMR_CSR_TFC_SHIFT 2 #define LPTMR_CSR_TPP_MASK 0x8u #define LPTMR_CSR_TPP_SHIFT 3 #define LPTMR_CSR_TPS_MASK 0x30u #define LPTMR_CSR_TPS_SHIFT 4 #define LPTMR_CSR_TPS(x) (((uint32_t)(((uint32_t)(x))<C1) #define MCG_C2_REG(base) ((base)->C2) #define MCG_C3_REG(base) ((base)->C3) #define MCG_C4_REG(base) ((base)->C4) #define MCG_C5_REG(base) ((base)->C5) #define MCG_C6_REG(base) ((base)->C6) #define MCG_S_REG(base) ((base)->S) #define MCG_SC_REG(base) ((base)->SC) #define MCG_ATCVH_REG(base) ((base)->ATCVH) #define MCG_ATCVL_REG(base) ((base)->ATCVL) #define MCG_C7_REG(base) ((base)->C7) #define MCG_C8_REG(base) ((base)->C8) /*! * @} */ /* end of group MCG_Register_Accessor_Macros */ /* ---------------------------------------------------------------------------- -- MCG Register Masks ---------------------------------------------------------------------------- */ /*! * @addtogroup MCG_Register_Masks MCG Register Masks * @{ */ /* C1 Bit Fields */ #define MCG_C1_IREFSTEN_MASK 0x1u #define MCG_C1_IREFSTEN_SHIFT 0 #define MCG_C1_IRCLKEN_MASK 0x2u #define MCG_C1_IRCLKEN_SHIFT 1 #define MCG_C1_IREFS_MASK 0x4u #define MCG_C1_IREFS_SHIFT 2 #define MCG_C1_FRDIV_MASK 0x38u #define MCG_C1_FRDIV_SHIFT 3 #define MCG_C1_FRDIV(x) (((uint8_t)(((uint8_t)(x))<PLASC) #define MCM_PLAMC_REG(base) ((base)->PLAMC) #define MCM_CR_REG(base) ((base)->CR) #define MCM_ISCR_REG(base) ((base)->ISCR) #define MCM_ETBCC_REG(base) ((base)->ETBCC) #define MCM_ETBRL_REG(base) ((base)->ETBRL) #define MCM_ETBCNT_REG(base) ((base)->ETBCNT) #define MCM_PID_REG(base) ((base)->PID) /*! * @} */ /* end of group MCM_Register_Accessor_Macros */ /* ---------------------------------------------------------------------------- -- MCM Register Masks ---------------------------------------------------------------------------- */ /*! * @addtogroup MCM_Register_Masks MCM Register Masks * @{ */ /* PLASC Bit Fields */ #define MCM_PLASC_ASC_MASK 0xFFu #define MCM_PLASC_ASC_SHIFT 0 #define MCM_PLASC_ASC(x) (((uint16_t)(((uint16_t)(x))<CESR) #define MPU_EAR_REG(base,index) ((base)->SP[index].EAR) #define MPU_EDR_REG(base,index) ((base)->SP[index].EDR) #define MPU_WORD_REG(base,index,index2) ((base)->WORD[index][index2]) #define MPU_RGDAAC_REG(base,index) ((base)->RGDAAC[index]) /*! * @} */ /* end of group MPU_Register_Accessor_Macros */ /* ---------------------------------------------------------------------------- -- MPU Register Masks ---------------------------------------------------------------------------- */ /*! * @addtogroup MPU_Register_Masks MPU Register Masks * @{ */ /* CESR Bit Fields */ #define MPU_CESR_VLD_MASK 0x1u #define MPU_CESR_VLD_SHIFT 0 #define MPU_CESR_NRGD_MASK 0xF00u #define MPU_CESR_NRGD_SHIFT 8 #define MPU_CESR_NRGD(x) (((uint32_t)(((uint32_t)(x))<BACKKEY3) #define NV_BACKKEY2_REG(base) ((base)->BACKKEY2) #define NV_BACKKEY1_REG(base) ((base)->BACKKEY1) #define NV_BACKKEY0_REG(base) ((base)->BACKKEY0) #define NV_BACKKEY7_REG(base) ((base)->BACKKEY7) #define NV_BACKKEY6_REG(base) ((base)->BACKKEY6) #define NV_BACKKEY5_REG(base) ((base)->BACKKEY5) #define NV_BACKKEY4_REG(base) ((base)->BACKKEY4) #define NV_FPROT3_REG(base) ((base)->FPROT3) #define NV_FPROT2_REG(base) ((base)->FPROT2) #define NV_FPROT1_REG(base) ((base)->FPROT1) #define NV_FPROT0_REG(base) ((base)->FPROT0) #define NV_FSEC_REG(base) ((base)->FSEC) #define NV_FOPT_REG(base) ((base)->FOPT) #define NV_FEPROT_REG(base) ((base)->FEPROT) #define NV_FDPROT_REG(base) ((base)->FDPROT) /*! * @} */ /* end of group NV_Register_Accessor_Macros */ /* ---------------------------------------------------------------------------- -- NV Register Masks ---------------------------------------------------------------------------- */ /*! * @addtogroup NV_Register_Masks NV Register Masks * @{ */ /* BACKKEY3 Bit Fields */ #define NV_BACKKEY3_KEY_MASK 0xFFu #define NV_BACKKEY3_KEY_SHIFT 0 #define NV_BACKKEY3_KEY(x) (((uint8_t)(((uint8_t)(x))<CR) /*! * @} */ /* end of group OSC_Register_Accessor_Macros */ /* ---------------------------------------------------------------------------- -- OSC Register Masks ---------------------------------------------------------------------------- */ /*! * @addtogroup OSC_Register_Masks OSC Register Masks * @{ */ /* CR Bit Fields */ #define OSC_CR_SC16P_MASK 0x1u #define OSC_CR_SC16P_SHIFT 0 #define OSC_CR_SC8P_MASK 0x2u #define OSC_CR_SC8P_SHIFT 1 #define OSC_CR_SC4P_MASK 0x4u #define OSC_CR_SC4P_SHIFT 2 #define OSC_CR_SC2P_MASK 0x8u #define OSC_CR_SC2P_SHIFT 3 #define OSC_CR_EREFSTEN_MASK 0x20u #define OSC_CR_EREFSTEN_SHIFT 5 #define OSC_CR_ERCLKEN_MASK 0x80u #define OSC_CR_ERCLKEN_SHIFT 7 /*! * @} */ /* end of group OSC_Register_Masks */ /* OSC - Peripheral instance base addresses */ /** Peripheral OSC base address */ #define OSC_BASE (0x40065000u) /** Peripheral OSC base pointer */ #define OSC ((OSC_Type *)OSC_BASE) #define OSC_BASE_PTR (OSC) /** Array initializer of OSC peripheral base addresses */ #define OSC_BASE_ADDRS { OSC_BASE } /** Array initializer of OSC peripheral base pointers */ #define OSC_BASE_PTRS { OSC } /* ---------------------------------------------------------------------------- -- OSC - Register accessor macros ---------------------------------------------------------------------------- */ /*! * @addtogroup OSC_Register_Accessor_Macros OSC - Register accessor macros * @{ */ /* OSC - Register instance definitions */ /* OSC */ #define OSC_CR OSC_CR_REG(OSC) /*! * @} */ /* end of group OSC_Register_Accessor_Macros */ /*! * @} */ /* end of group OSC_Peripheral_Access_Layer */ /* ---------------------------------------------------------------------------- -- PDB Peripheral Access Layer ---------------------------------------------------------------------------- */ /*! * @addtogroup PDB_Peripheral_Access_Layer PDB Peripheral Access Layer * @{ */ /** PDB - Register Layout Typedef */ typedef struct { __IO uint32_t SC; /**< Status and Control register, offset: 0x0 */ __IO uint32_t MOD; /**< Modulus register, offset: 0x4 */ __I uint32_t CNT; /**< Counter register, offset: 0x8 */ __IO uint32_t IDLY; /**< Interrupt Delay register, offset: 0xC */ struct { /* offset: 0x10, array step: 0x28 */ __IO uint32_t C1; /**< Channel n Control register 1, array offset: 0x10, array step: 0x28 */ __IO uint32_t S; /**< Channel n Status register, array offset: 0x14, array step: 0x28 */ __IO uint32_t DLY[2]; /**< Channel n Delay 0 register..Channel n Delay 1 register, array offset: 0x18, array step: index*0x28, index2*0x4 */ uint8_t RESERVED_0[24]; } CH[2]; uint8_t RESERVED_0[240]; struct { /* offset: 0x150, array step: 0x8 */ __IO uint32_t INTC; /**< DAC Interval Trigger n Control register, array offset: 0x150, array step: 0x8 */ __IO uint32_t INT; /**< DAC Interval n register, array offset: 0x154, array step: 0x8 */ } DAC[2]; uint8_t RESERVED_1[48]; __IO uint32_t POEN; /**< Pulse-Out n Enable register, offset: 0x190 */ __IO uint32_t PODLY[3]; /**< Pulse-Out n Delay register, array offset: 0x194, array step: 0x4 */ } PDB_Type, *PDB_MemMapPtr; /* ---------------------------------------------------------------------------- -- PDB - Register accessor macros ---------------------------------------------------------------------------- */ /*! * @addtogroup PDB_Register_Accessor_Macros PDB - Register accessor macros * @{ */ /* PDB - Register accessors */ #define PDB_SC_REG(base) ((base)->SC) #define PDB_MOD_REG(base) ((base)->MOD) #define PDB_CNT_REG(base) ((base)->CNT) #define PDB_IDLY_REG(base) ((base)->IDLY) #define PDB_C1_REG(base,index) ((base)->CH[index].C1) #define PDB_S_REG(base,index) ((base)->CH[index].S) #define PDB_DLY_REG(base,index,index2) ((base)->CH[index].DLY[index2]) #define PDB_INTC_REG(base,index) ((base)->DAC[index].INTC) #define PDB_INT_REG(base,index) ((base)->DAC[index].INT) #define PDB_POEN_REG(base) ((base)->POEN) #define PDB_PODLY_REG(base,index) ((base)->PODLY[index]) /*! * @} */ /* end of group PDB_Register_Accessor_Macros */ /* ---------------------------------------------------------------------------- -- PDB Register Masks ---------------------------------------------------------------------------- */ /*! * @addtogroup PDB_Register_Masks PDB Register Masks * @{ */ /* SC Bit Fields */ #define PDB_SC_LDOK_MASK 0x1u #define PDB_SC_LDOK_SHIFT 0 #define PDB_SC_CONT_MASK 0x2u #define PDB_SC_CONT_SHIFT 1 #define PDB_SC_MULT_MASK 0xCu #define PDB_SC_MULT_SHIFT 2 #define PDB_SC_MULT(x) (((uint32_t)(((uint32_t)(x))<MCR) #define PIT_LDVAL_REG(base,index) ((base)->CHANNEL[index].LDVAL) #define PIT_CVAL_REG(base,index) ((base)->CHANNEL[index].CVAL) #define PIT_TCTRL_REG(base,index) ((base)->CHANNEL[index].TCTRL) #define PIT_TFLG_REG(base,index) ((base)->CHANNEL[index].TFLG) /*! * @} */ /* end of group PIT_Register_Accessor_Macros */ /* ---------------------------------------------------------------------------- -- PIT Register Masks ---------------------------------------------------------------------------- */ /*! * @addtogroup PIT_Register_Masks PIT Register Masks * @{ */ /* MCR Bit Fields */ #define PIT_MCR_FRZ_MASK 0x1u #define PIT_MCR_FRZ_SHIFT 0 #define PIT_MCR_MDIS_MASK 0x2u #define PIT_MCR_MDIS_SHIFT 1 /* LDVAL Bit Fields */ #define PIT_LDVAL_TSV_MASK 0xFFFFFFFFu #define PIT_LDVAL_TSV_SHIFT 0 #define PIT_LDVAL_TSV(x) (((uint32_t)(((uint32_t)(x))<LVDSC1) #define PMC_LVDSC2_REG(base) ((base)->LVDSC2) #define PMC_REGSC_REG(base) ((base)->REGSC) /*! * @} */ /* end of group PMC_Register_Accessor_Macros */ /* ---------------------------------------------------------------------------- -- PMC Register Masks ---------------------------------------------------------------------------- */ /*! * @addtogroup PMC_Register_Masks PMC Register Masks * @{ */ /* LVDSC1 Bit Fields */ #define PMC_LVDSC1_LVDV_MASK 0x3u #define PMC_LVDSC1_LVDV_SHIFT 0 #define PMC_LVDSC1_LVDV(x) (((uint8_t)(((uint8_t)(x))<PCR[index]) #define PORT_GPCLR_REG(base) ((base)->GPCLR) #define PORT_GPCHR_REG(base) ((base)->GPCHR) #define PORT_ISFR_REG(base) ((base)->ISFR) #define PORT_DFER_REG(base) ((base)->DFER) #define PORT_DFCR_REG(base) ((base)->DFCR) #define PORT_DFWR_REG(base) ((base)->DFWR) /*! * @} */ /* end of group PORT_Register_Accessor_Macros */ /* ---------------------------------------------------------------------------- -- PORT Register Masks ---------------------------------------------------------------------------- */ /*! * @addtogroup PORT_Register_Masks PORT Register Masks * @{ */ /* PCR Bit Fields */ #define PORT_PCR_PS_MASK 0x1u #define PORT_PCR_PS_SHIFT 0 #define PORT_PCR_PE_MASK 0x2u #define PORT_PCR_PE_SHIFT 1 #define PORT_PCR_SRE_MASK 0x4u #define PORT_PCR_SRE_SHIFT 2 #define PORT_PCR_PFE_MASK 0x10u #define PORT_PCR_PFE_SHIFT 4 #define PORT_PCR_ODE_MASK 0x20u #define PORT_PCR_ODE_SHIFT 5 #define PORT_PCR_DSE_MASK 0x40u #define PORT_PCR_DSE_SHIFT 6 #define PORT_PCR_MUX_MASK 0x700u #define PORT_PCR_MUX_SHIFT 8 #define PORT_PCR_MUX(x) (((uint32_t)(((uint32_t)(x))<SRS0) #define RCM_SRS1_REG(base) ((base)->SRS1) #define RCM_RPFC_REG(base) ((base)->RPFC) #define RCM_RPFW_REG(base) ((base)->RPFW) #define RCM_MR_REG(base) ((base)->MR) /*! * @} */ /* end of group RCM_Register_Accessor_Macros */ /* ---------------------------------------------------------------------------- -- RCM Register Masks ---------------------------------------------------------------------------- */ /*! * @addtogroup RCM_Register_Masks RCM Register Masks * @{ */ /* SRS0 Bit Fields */ #define RCM_SRS0_WAKEUP_MASK 0x1u #define RCM_SRS0_WAKEUP_SHIFT 0 #define RCM_SRS0_LVD_MASK 0x2u #define RCM_SRS0_LVD_SHIFT 1 #define RCM_SRS0_LOC_MASK 0x4u #define RCM_SRS0_LOC_SHIFT 2 #define RCM_SRS0_LOL_MASK 0x8u #define RCM_SRS0_LOL_SHIFT 3 #define RCM_SRS0_WDOG_MASK 0x20u #define RCM_SRS0_WDOG_SHIFT 5 #define RCM_SRS0_PIN_MASK 0x40u #define RCM_SRS0_PIN_SHIFT 6 #define RCM_SRS0_POR_MASK 0x80u #define RCM_SRS0_POR_SHIFT 7 /* SRS1 Bit Fields */ #define RCM_SRS1_JTAG_MASK 0x1u #define RCM_SRS1_JTAG_SHIFT 0 #define RCM_SRS1_LOCKUP_MASK 0x2u #define RCM_SRS1_LOCKUP_SHIFT 1 #define RCM_SRS1_SW_MASK 0x4u #define RCM_SRS1_SW_SHIFT 2 #define RCM_SRS1_MDM_AP_MASK 0x8u #define RCM_SRS1_MDM_AP_SHIFT 3 #define RCM_SRS1_EZPT_MASK 0x10u #define RCM_SRS1_EZPT_SHIFT 4 #define RCM_SRS1_SACKERR_MASK 0x20u #define RCM_SRS1_SACKERR_SHIFT 5 /* RPFC Bit Fields */ #define RCM_RPFC_RSTFLTSRW_MASK 0x3u #define RCM_RPFC_RSTFLTSRW_SHIFT 0 #define RCM_RPFC_RSTFLTSRW(x) (((uint8_t)(((uint8_t)(x))<REG[index]) /*! * @} */ /* end of group RFSYS_Register_Accessor_Macros */ /* ---------------------------------------------------------------------------- -- RFSYS Register Masks ---------------------------------------------------------------------------- */ /*! * @addtogroup RFSYS_Register_Masks RFSYS Register Masks * @{ */ /* REG Bit Fields */ #define RFSYS_REG_LL_MASK 0xFFu #define RFSYS_REG_LL_SHIFT 0 #define RFSYS_REG_LL(x) (((uint32_t)(((uint32_t)(x))<REG[index]) /*! * @} */ /* end of group RFVBAT_Register_Accessor_Macros */ /* ---------------------------------------------------------------------------- -- RFVBAT Register Masks ---------------------------------------------------------------------------- */ /*! * @addtogroup RFVBAT_Register_Masks RFVBAT Register Masks * @{ */ /* REG Bit Fields */ #define RFVBAT_REG_LL_MASK 0xFFu #define RFVBAT_REG_LL_SHIFT 0 #define RFVBAT_REG_LL(x) (((uint32_t)(((uint32_t)(x))<CR) #define RNG_SR_REG(base) ((base)->SR) #define RNG_ER_REG(base) ((base)->ER) #define RNG_OR_REG(base) ((base)->OR) /*! * @} */ /* end of group RNG_Register_Accessor_Macros */ /* ---------------------------------------------------------------------------- -- RNG Register Masks ---------------------------------------------------------------------------- */ /*! * @addtogroup RNG_Register_Masks RNG Register Masks * @{ */ /* CR Bit Fields */ #define RNG_CR_GO_MASK 0x1u #define RNG_CR_GO_SHIFT 0 #define RNG_CR_HA_MASK 0x2u #define RNG_CR_HA_SHIFT 1 #define RNG_CR_INTM_MASK 0x4u #define RNG_CR_INTM_SHIFT 2 #define RNG_CR_CLRI_MASK 0x8u #define RNG_CR_CLRI_SHIFT 3 #define RNG_CR_SLP_MASK 0x10u #define RNG_CR_SLP_SHIFT 4 /* SR Bit Fields */ #define RNG_SR_SECV_MASK 0x1u #define RNG_SR_SECV_SHIFT 0 #define RNG_SR_LRS_MASK 0x2u #define RNG_SR_LRS_SHIFT 1 #define RNG_SR_ORU_MASK 0x4u #define RNG_SR_ORU_SHIFT 2 #define RNG_SR_ERRI_MASK 0x8u #define RNG_SR_ERRI_SHIFT 3 #define RNG_SR_SLP_MASK 0x10u #define RNG_SR_SLP_SHIFT 4 #define RNG_SR_OREG_LVL_MASK 0xFF00u #define RNG_SR_OREG_LVL_SHIFT 8 #define RNG_SR_OREG_LVL(x) (((uint32_t)(((uint32_t)(x))<TSR) #define RTC_TPR_REG(base) ((base)->TPR) #define RTC_TAR_REG(base) ((base)->TAR) #define RTC_TCR_REG(base) ((base)->TCR) #define RTC_CR_REG(base) ((base)->CR) #define RTC_SR_REG(base) ((base)->SR) #define RTC_LR_REG(base) ((base)->LR) #define RTC_IER_REG(base) ((base)->IER) #define RTC_WAR_REG(base) ((base)->WAR) #define RTC_RAR_REG(base) ((base)->RAR) /*! * @} */ /* end of group RTC_Register_Accessor_Macros */ /* ---------------------------------------------------------------------------- -- RTC Register Masks ---------------------------------------------------------------------------- */ /*! * @addtogroup RTC_Register_Masks RTC Register Masks * @{ */ /* TSR Bit Fields */ #define RTC_TSR_TSR_MASK 0xFFFFFFFFu #define RTC_TSR_TSR_SHIFT 0 #define RTC_TSR_TSR(x) (((uint32_t)(((uint32_t)(x))<DSADDR) #define SDHC_BLKATTR_REG(base) ((base)->BLKATTR) #define SDHC_CMDARG_REG(base) ((base)->CMDARG) #define SDHC_XFERTYP_REG(base) ((base)->XFERTYP) #define SDHC_CMDRSP_REG(base,index) ((base)->CMDRSP[index]) #define SDHC_DATPORT_REG(base) ((base)->DATPORT) #define SDHC_PRSSTAT_REG(base) ((base)->PRSSTAT) #define SDHC_PROCTL_REG(base) ((base)->PROCTL) #define SDHC_SYSCTL_REG(base) ((base)->SYSCTL) #define SDHC_IRQSTAT_REG(base) ((base)->IRQSTAT) #define SDHC_IRQSTATEN_REG(base) ((base)->IRQSTATEN) #define SDHC_IRQSIGEN_REG(base) ((base)->IRQSIGEN) #define SDHC_AC12ERR_REG(base) ((base)->AC12ERR) #define SDHC_HTCAPBLT_REG(base) ((base)->HTCAPBLT) #define SDHC_WML_REG(base) ((base)->WML) #define SDHC_FEVT_REG(base) ((base)->FEVT) #define SDHC_ADMAES_REG(base) ((base)->ADMAES) #define SDHC_ADSADDR_REG(base) ((base)->ADSADDR) #define SDHC_VENDOR_REG(base) ((base)->VENDOR) #define SDHC_MMCBOOT_REG(base) ((base)->MMCBOOT) #define SDHC_HOSTVER_REG(base) ((base)->HOSTVER) /*! * @} */ /* end of group SDHC_Register_Accessor_Macros */ /* ---------------------------------------------------------------------------- -- SDHC Register Masks ---------------------------------------------------------------------------- */ /*! * @addtogroup SDHC_Register_Masks SDHC Register Masks * @{ */ /* DSADDR Bit Fields */ #define SDHC_DSADDR_DSADDR_MASK 0xFFFFFFFCu #define SDHC_DSADDR_DSADDR_SHIFT 2 #define SDHC_DSADDR_DSADDR(x) (((uint32_t)(((uint32_t)(x))<SOPT1) #define SIM_SOPT1CFG_REG(base) ((base)->SOPT1CFG) #define SIM_SOPT2_REG(base) ((base)->SOPT2) #define SIM_SOPT4_REG(base) ((base)->SOPT4) #define SIM_SOPT5_REG(base) ((base)->SOPT5) #define SIM_SOPT7_REG(base) ((base)->SOPT7) #define SIM_SDID_REG(base) ((base)->SDID) #define SIM_SCGC1_REG(base) ((base)->SCGC1) #define SIM_SCGC2_REG(base) ((base)->SCGC2) #define SIM_SCGC3_REG(base) ((base)->SCGC3) #define SIM_SCGC4_REG(base) ((base)->SCGC4) #define SIM_SCGC5_REG(base) ((base)->SCGC5) #define SIM_SCGC6_REG(base) ((base)->SCGC6) #define SIM_SCGC7_REG(base) ((base)->SCGC7) #define SIM_CLKDIV1_REG(base) ((base)->CLKDIV1) #define SIM_CLKDIV2_REG(base) ((base)->CLKDIV2) #define SIM_FCFG1_REG(base) ((base)->FCFG1) #define SIM_FCFG2_REG(base) ((base)->FCFG2) #define SIM_UIDH_REG(base) ((base)->UIDH) #define SIM_UIDMH_REG(base) ((base)->UIDMH) #define SIM_UIDML_REG(base) ((base)->UIDML) #define SIM_UIDL_REG(base) ((base)->UIDL) /*! * @} */ /* end of group SIM_Register_Accessor_Macros */ /* ---------------------------------------------------------------------------- -- SIM Register Masks ---------------------------------------------------------------------------- */ /*! * @addtogroup SIM_Register_Masks SIM Register Masks * @{ */ /* SOPT1 Bit Fields */ #define SIM_SOPT1_RAMSIZE_MASK 0xF000u #define SIM_SOPT1_RAMSIZE_SHIFT 12 #define SIM_SOPT1_RAMSIZE(x) (((uint32_t)(((uint32_t)(x))<PMPROT) #define SMC_PMCTRL_REG(base) ((base)->PMCTRL) #define SMC_VLLSCTRL_REG(base) ((base)->VLLSCTRL) #define SMC_PMSTAT_REG(base) ((base)->PMSTAT) /*! * @} */ /* end of group SMC_Register_Accessor_Macros */ /* ---------------------------------------------------------------------------- -- SMC Register Masks ---------------------------------------------------------------------------- */ /*! * @addtogroup SMC_Register_Masks SMC Register Masks * @{ */ /* PMPROT Bit Fields */ #define SMC_PMPROT_AVLLS_MASK 0x2u #define SMC_PMPROT_AVLLS_SHIFT 1 #define SMC_PMPROT_ALLS_MASK 0x8u #define SMC_PMPROT_ALLS_SHIFT 3 #define SMC_PMPROT_AVLP_MASK 0x20u #define SMC_PMPROT_AVLP_SHIFT 5 /* PMCTRL Bit Fields */ #define SMC_PMCTRL_STOPM_MASK 0x7u #define SMC_PMCTRL_STOPM_SHIFT 0 #define SMC_PMCTRL_STOPM(x) (((uint8_t)(((uint8_t)(x))<MCR) #define SPI_TCR_REG(base) ((base)->TCR) #define SPI_CTAR_REG(base,index2) ((base)->CTAR[index2]) #define SPI_CTAR_SLAVE_REG(base,index2) ((base)->CTAR_SLAVE[index2]) #define SPI_SR_REG(base) ((base)->SR) #define SPI_RSER_REG(base) ((base)->RSER) #define SPI_PUSHR_REG(base) ((base)->PUSHR) #define SPI_PUSHR_SLAVE_REG(base) ((base)->PUSHR_SLAVE) #define SPI_POPR_REG(base) ((base)->POPR) #define SPI_TXFR0_REG(base) ((base)->TXFR0) #define SPI_TXFR1_REG(base) ((base)->TXFR1) #define SPI_TXFR2_REG(base) ((base)->TXFR2) #define SPI_TXFR3_REG(base) ((base)->TXFR3) #define SPI_RXFR0_REG(base) ((base)->RXFR0) #define SPI_RXFR1_REG(base) ((base)->RXFR1) #define SPI_RXFR2_REG(base) ((base)->RXFR2) #define SPI_RXFR3_REG(base) ((base)->RXFR3) /*! * @} */ /* end of group SPI_Register_Accessor_Macros */ /* ---------------------------------------------------------------------------- -- SPI Register Masks ---------------------------------------------------------------------------- */ /*! * @addtogroup SPI_Register_Masks SPI Register Masks * @{ */ /* MCR Bit Fields */ #define SPI_MCR_HALT_MASK 0x1u #define SPI_MCR_HALT_SHIFT 0 #define SPI_MCR_SMPL_PT_MASK 0x300u #define SPI_MCR_SMPL_PT_SHIFT 8 #define SPI_MCR_SMPL_PT(x) (((uint32_t)(((uint32_t)(x))<BDH) #define UART_BDL_REG(base) ((base)->BDL) #define UART_C1_REG(base) ((base)->C1) #define UART_C2_REG(base) ((base)->C2) #define UART_S1_REG(base) ((base)->S1) #define UART_S2_REG(base) ((base)->S2) #define UART_C3_REG(base) ((base)->C3) #define UART_D_REG(base) ((base)->D) #define UART_MA1_REG(base) ((base)->MA1) #define UART_MA2_REG(base) ((base)->MA2) #define UART_C4_REG(base) ((base)->C4) #define UART_C5_REG(base) ((base)->C5) #define UART_ED_REG(base) ((base)->ED) #define UART_MODEM_REG(base) ((base)->MODEM) #define UART_IR_REG(base) ((base)->IR) #define UART_PFIFO_REG(base) ((base)->PFIFO) #define UART_CFIFO_REG(base) ((base)->CFIFO) #define UART_SFIFO_REG(base) ((base)->SFIFO) #define UART_TWFIFO_REG(base) ((base)->TWFIFO) #define UART_TCFIFO_REG(base) ((base)->TCFIFO) #define UART_RWFIFO_REG(base) ((base)->RWFIFO) #define UART_RCFIFO_REG(base) ((base)->RCFIFO) #define UART_C7816_REG(base) ((base)->C7816) #define UART_IE7816_REG(base) ((base)->IE7816) #define UART_IS7816_REG(base) ((base)->IS7816) #define UART_WP7816T0_REG(base) ((base)->WP7816T0) #define UART_WP7816T1_REG(base) ((base)->WP7816T1) #define UART_WN7816_REG(base) ((base)->WN7816) #define UART_WF7816_REG(base) ((base)->WF7816) #define UART_ET7816_REG(base) ((base)->ET7816) #define UART_TL7816_REG(base) ((base)->TL7816) /*! * @} */ /* end of group UART_Register_Accessor_Macros */ /* ---------------------------------------------------------------------------- -- UART Register Masks ---------------------------------------------------------------------------- */ /*! * @addtogroup UART_Register_Masks UART Register Masks * @{ */ /* BDH Bit Fields */ #define UART_BDH_SBR_MASK 0x1Fu #define UART_BDH_SBR_SHIFT 0 #define UART_BDH_SBR(x) (((uint8_t)(((uint8_t)(x))<PERID) #define USB_IDCOMP_REG(base) ((base)->IDCOMP) #define USB_REV_REG(base) ((base)->REV) #define USB_ADDINFO_REG(base) ((base)->ADDINFO) #define USB_OTGISTAT_REG(base) ((base)->OTGISTAT) #define USB_OTGICR_REG(base) ((base)->OTGICR) #define USB_OTGSTAT_REG(base) ((base)->OTGSTAT) #define USB_OTGCTL_REG(base) ((base)->OTGCTL) #define USB_ISTAT_REG(base) ((base)->ISTAT) #define USB_INTEN_REG(base) ((base)->INTEN) #define USB_ERRSTAT_REG(base) ((base)->ERRSTAT) #define USB_ERREN_REG(base) ((base)->ERREN) #define USB_STAT_REG(base) ((base)->STAT) #define USB_CTL_REG(base) ((base)->CTL) #define USB_ADDR_REG(base) ((base)->ADDR) #define USB_BDTPAGE1_REG(base) ((base)->BDTPAGE1) #define USB_FRMNUML_REG(base) ((base)->FRMNUML) #define USB_FRMNUMH_REG(base) ((base)->FRMNUMH) #define USB_TOKEN_REG(base) ((base)->TOKEN) #define USB_SOFTHLD_REG(base) ((base)->SOFTHLD) #define USB_BDTPAGE2_REG(base) ((base)->BDTPAGE2) #define USB_BDTPAGE3_REG(base) ((base)->BDTPAGE3) #define USB_ENDPT_REG(base,index) ((base)->ENDPOINT[index].ENDPT) #define USB_USBCTRL_REG(base) ((base)->USBCTRL) #define USB_OBSERVE_REG(base) ((base)->OBSERVE) #define USB_CONTROL_REG(base) ((base)->CONTROL) #define USB_USBTRC0_REG(base) ((base)->USBTRC0) #define USB_USBFRMADJUST_REG(base) ((base)->USBFRMADJUST) #define USB_CLK_RECOVER_CTRL_REG(base) ((base)->CLK_RECOVER_CTRL) #define USB_CLK_RECOVER_IRC_EN_REG(base) ((base)->CLK_RECOVER_IRC_EN) #define USB_CLK_RECOVER_INT_STATUS_REG(base) ((base)->CLK_RECOVER_INT_STATUS) /*! * @} */ /* end of group USB_Register_Accessor_Macros */ /* ---------------------------------------------------------------------------- -- USB Register Masks ---------------------------------------------------------------------------- */ /*! * @addtogroup USB_Register_Masks USB Register Masks * @{ */ /* PERID Bit Fields */ #define USB_PERID_ID_MASK 0x3Fu #define USB_PERID_ID_SHIFT 0 #define USB_PERID_ID(x) (((uint8_t)(((uint8_t)(x))<CONTROL) #define USBDCD_CLOCK_REG(base) ((base)->CLOCK) #define USBDCD_STATUS_REG(base) ((base)->STATUS) #define USBDCD_TIMER0_REG(base) ((base)->TIMER0) #define USBDCD_TIMER1_REG(base) ((base)->TIMER1) #define USBDCD_TIMER2_BC11_REG(base) ((base)->TIMER2_BC11) #define USBDCD_TIMER2_BC12_REG(base) ((base)->TIMER2_BC12) /*! * @} */ /* end of group USBDCD_Register_Accessor_Macros */ /* ---------------------------------------------------------------------------- -- USBDCD Register Masks ---------------------------------------------------------------------------- */ /*! * @addtogroup USBDCD_Register_Masks USBDCD Register Masks * @{ */ /* CONTROL Bit Fields */ #define USBDCD_CONTROL_IACK_MASK 0x1u #define USBDCD_CONTROL_IACK_SHIFT 0 #define USBDCD_CONTROL_IF_MASK 0x100u #define USBDCD_CONTROL_IF_SHIFT 8 #define USBDCD_CONTROL_IE_MASK 0x10000u #define USBDCD_CONTROL_IE_SHIFT 16 #define USBDCD_CONTROL_BC12_MASK 0x20000u #define USBDCD_CONTROL_BC12_SHIFT 17 #define USBDCD_CONTROL_START_MASK 0x1000000u #define USBDCD_CONTROL_START_SHIFT 24 #define USBDCD_CONTROL_SR_MASK 0x2000000u #define USBDCD_CONTROL_SR_SHIFT 25 /* CLOCK Bit Fields */ #define USBDCD_CLOCK_CLOCK_UNIT_MASK 0x1u #define USBDCD_CLOCK_CLOCK_UNIT_SHIFT 0 #define USBDCD_CLOCK_CLOCK_SPEED_MASK 0xFFCu #define USBDCD_CLOCK_CLOCK_SPEED_SHIFT 2 #define USBDCD_CLOCK_CLOCK_SPEED(x) (((uint32_t)(((uint32_t)(x))<TRM) #define VREF_SC_REG(base) ((base)->SC) /*! * @} */ /* end of group VREF_Register_Accessor_Macros */ /* ---------------------------------------------------------------------------- -- VREF Register Masks ---------------------------------------------------------------------------- */ /*! * @addtogroup VREF_Register_Masks VREF Register Masks * @{ */ /* TRM Bit Fields */ #define VREF_TRM_TRIM_MASK 0x3Fu #define VREF_TRM_TRIM_SHIFT 0 #define VREF_TRM_TRIM(x) (((uint8_t)(((uint8_t)(x))<STCTRLH) #define WDOG_STCTRLL_REG(base) ((base)->STCTRLL) #define WDOG_TOVALH_REG(base) ((base)->TOVALH) #define WDOG_TOVALL_REG(base) ((base)->TOVALL) #define WDOG_WINH_REG(base) ((base)->WINH) #define WDOG_WINL_REG(base) ((base)->WINL) #define WDOG_REFRESH_REG(base) ((base)->REFRESH) #define WDOG_UNLOCK_REG(base) ((base)->UNLOCK) #define WDOG_TMROUTH_REG(base) ((base)->TMROUTH) #define WDOG_TMROUTL_REG(base) ((base)->TMROUTL) #define WDOG_RSTCNT_REG(base) ((base)->RSTCNT) #define WDOG_PRESC_REG(base) ((base)->PRESC) /*! * @} */ /* end of group WDOG_Register_Accessor_Macros */ /* ---------------------------------------------------------------------------- -- WDOG Register Masks ---------------------------------------------------------------------------- */ /*! * @addtogroup WDOG_Register_Masks WDOG Register Masks * @{ */ /* STCTRLH Bit Fields */ #define WDOG_STCTRLH_WDOGEN_MASK 0x1u #define WDOG_STCTRLH_WDOGEN_SHIFT 0 #define WDOG_STCTRLH_CLKSRC_MASK 0x2u #define WDOG_STCTRLH_CLKSRC_SHIFT 1 #define WDOG_STCTRLH_IRQRSTEN_MASK 0x4u #define WDOG_STCTRLH_IRQRSTEN_SHIFT 2 #define WDOG_STCTRLH_WINEN_MASK 0x8u #define WDOG_STCTRLH_WINEN_SHIFT 3 #define WDOG_STCTRLH_ALLOWUPDATE_MASK 0x10u #define WDOG_STCTRLH_ALLOWUPDATE_SHIFT 4 #define WDOG_STCTRLH_DBGEN_MASK 0x20u #define WDOG_STCTRLH_DBGEN_SHIFT 5 #define WDOG_STCTRLH_STOPEN_MASK 0x40u #define WDOG_STCTRLH_STOPEN_SHIFT 6 #define WDOG_STCTRLH_WAITEN_MASK 0x80u #define WDOG_STCTRLH_WAITEN_SHIFT 7 #define WDOG_STCTRLH_TESTWDOG_MASK 0x400u #define WDOG_STCTRLH_TESTWDOG_SHIFT 10 #define WDOG_STCTRLH_TESTSEL_MASK 0x800u #define WDOG_STCTRLH_TESTSEL_SHIFT 11 #define WDOG_STCTRLH_BYTESEL_MASK 0x3000u #define WDOG_STCTRLH_BYTESEL_SHIFT 12 #define WDOG_STCTRLH_BYTESEL(x) (((uint16_t)(((uint16_t)(x))<&HW_ADC(ADC0_BASE). */ #define HW_ADC(x) (*(hw_adc_t *)(x)) #endif /* __HW_ADC_REGISTERS_H__ */ /* EOF */ ================================================ FILE: Zelig/mbed/TARGET_K64F/TARGET_Freescale/TARGET_KPSDK_MCUS/TARGET_MCU_K64F/device/device/MK64F12/MK64F12_aips.h ================================================ /* ** ################################################################### ** Compilers: Keil ARM C/C++ Compiler ** Freescale C/C++ for Embedded ARM ** GNU C Compiler ** IAR ANSI C/C++ Compiler for ARM ** ** Reference manual: K64P144M120SF5RM, Rev.2, January 2014 ** Version: rev. 2.5, 2014-02-10 ** Build: b140604 ** ** Abstract: ** Extension to the CMSIS register access layer header. ** ** Copyright (c) 2014 Freescale Semiconductor, Inc. ** All rights reserved. ** ** Redistribution and use in source and binary forms, with or without modification, ** are permitted provided that the following conditions are met: ** ** o Redistributions of source code must retain the above copyright notice, this list ** of conditions and the following disclaimer. ** ** o Redistributions in binary form must reproduce the above copyright notice, this ** list of conditions and the following disclaimer in the documentation and/or ** other materials provided with the distribution. ** ** o Neither the name of Freescale Semiconductor, Inc. nor the names of its ** contributors may be used to endorse or promote products derived from this ** software without specific prior written permission. ** ** THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ** ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED ** WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE ** DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT 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. ** ** http: www.freescale.com ** mail: support@freescale.com ** ** Revisions: ** - rev. 1.0 (2013-08-12) ** Initial version. ** - rev. 2.0 (2013-10-29) ** Register accessor macros added to the memory map. ** Symbols for Processor Expert memory map compatibility added to the memory map. ** Startup file for gcc has been updated according to CMSIS 3.2. ** System initialization updated. ** MCG - registers updated. ** PORTA, PORTB, PORTC, PORTE - registers for digital filter removed. ** - rev. 2.1 (2013-10-30) ** Definition of BITBAND macros updated to support peripherals with 32-bit acces disabled. ** - rev. 2.2 (2013-12-09) ** DMA - EARS register removed. ** AIPS0, AIPS1 - MPRA register updated. ** - rev. 2.3 (2014-01-24) ** Update according to reference manual rev. 2 ** ENET, MCG, MCM, SIM, USB - registers updated ** - rev. 2.4 (2014-02-10) ** The declaration of clock configurations has been moved to separate header file system_MK64F12.h ** Update of SystemInit() and SystemCoreClockUpdate() functions. ** - rev. 2.5 (2014-02-10) ** The declaration of clock configurations has been moved to separate header file system_MK64F12.h ** Update of SystemInit() and SystemCoreClockUpdate() functions. ** Module access macro module_BASES replaced by module_BASE_PTRS. ** ** ################################################################### */ /* * WARNING! DO NOT EDIT THIS FILE DIRECTLY! * * This file was generated automatically and any changes may be lost. */ #ifndef __HW_AIPS_REGISTERS_H__ #define __HW_AIPS_REGISTERS_H__ #include "MK64F12.h" #include "fsl_bitaccess.h" /* * MK64F12 AIPS * * AIPS-Lite Bridge * * Registers defined in this header file: * - HW_AIPS_MPRA - Master Privilege Register A * - HW_AIPS_PACRA - Peripheral Access Control Register * - HW_AIPS_PACRB - Peripheral Access Control Register * - HW_AIPS_PACRC - Peripheral Access Control Register * - HW_AIPS_PACRD - Peripheral Access Control Register * - HW_AIPS_PACRE - Peripheral Access Control Register * - HW_AIPS_PACRF - Peripheral Access Control Register * - HW_AIPS_PACRG - Peripheral Access Control Register * - HW_AIPS_PACRH - Peripheral Access Control Register * - HW_AIPS_PACRI - Peripheral Access Control Register * - HW_AIPS_PACRJ - Peripheral Access Control Register * - HW_AIPS_PACRK - Peripheral Access Control Register * - HW_AIPS_PACRL - Peripheral Access Control Register * - HW_AIPS_PACRM - Peripheral Access Control Register * - HW_AIPS_PACRN - Peripheral Access Control Register * - HW_AIPS_PACRO - Peripheral Access Control Register * - HW_AIPS_PACRP - Peripheral Access Control Register * - HW_AIPS_PACRU - Peripheral Access Control Register * * - hw_aips_t - Struct containing all module registers. */ #define HW_AIPS_INSTANCE_COUNT (2U) /*!< Number of instances of the AIPS module. */ #define HW_AIPS0 (0U) /*!< Instance number for AIPS0. */ #define HW_AIPS1 (1U) /*!< Instance number for AIPS1. */ /******************************************************************************* * HW_AIPS_MPRA - Master Privilege Register A ******************************************************************************/ /*! * @brief HW_AIPS_MPRA - Master Privilege Register A (RW) * * Reset value: 0x77700000U * * The MPRA specifies identical 4-bit fields defining the access-privilege level * associated with a bus master to various peripherals on the chip. The register * provides one field per bus master. At reset, the default value loaded into * the MPRA fields is chip-specific. See the chip configuration details for the * value of a particular device. A register field that maps to an unimplemented * master or peripheral behaves as read-only-zero. Each master is assigned a logical * ID from 0 to 15. See the master logical ID assignment table in the * chip-specific AIPS information. */ typedef union _hw_aips_mpra { uint32_t U; struct _hw_aips_mpra_bitfields { uint32_t RESERVED0 : 8; /*!< [7:0] */ uint32_t MPL5 : 1; /*!< [8] Master 5 Privilege Level */ uint32_t MTW5 : 1; /*!< [9] Master 5 Trusted For Writes */ uint32_t MTR5 : 1; /*!< [10] Master 5 Trusted For Read */ uint32_t RESERVED1 : 1; /*!< [11] */ uint32_t MPL4 : 1; /*!< [12] Master 4 Privilege Level */ uint32_t MTW4 : 1; /*!< [13] Master 4 Trusted For Writes */ uint32_t MTR4 : 1; /*!< [14] Master 4 Trusted For Read */ uint32_t RESERVED2 : 1; /*!< [15] */ uint32_t MPL3 : 1; /*!< [16] Master 3 Privilege Level */ uint32_t MTW3 : 1; /*!< [17] Master 3 Trusted For Writes */ uint32_t MTR3 : 1; /*!< [18] Master 3 Trusted For Read */ uint32_t RESERVED3 : 1; /*!< [19] */ uint32_t MPL2 : 1; /*!< [20] Master 2 Privilege Level */ uint32_t MTW2 : 1; /*!< [21] Master 2 Trusted For Writes */ uint32_t MTR2 : 1; /*!< [22] Master 2 Trusted For Read */ uint32_t RESERVED4 : 1; /*!< [23] */ uint32_t MPL1 : 1; /*!< [24] Master 1 Privilege Level */ uint32_t MTW1 : 1; /*!< [25] Master 1 Trusted for Writes */ uint32_t MTR1 : 1; /*!< [26] Master 1 Trusted for Read */ uint32_t RESERVED5 : 1; /*!< [27] */ uint32_t MPL0 : 1; /*!< [28] Master 0 Privilege Level */ uint32_t MTW0 : 1; /*!< [29] Master 0 Trusted For Writes */ uint32_t MTR0 : 1; /*!< [30] Master 0 Trusted For Read */ uint32_t RESERVED6 : 1; /*!< [31] */ } B; } hw_aips_mpra_t; /*! * @name Constants and macros for entire AIPS_MPRA register */ /*@{*/ #define HW_AIPS_MPRA_ADDR(x) ((x) + 0x0U) #define HW_AIPS_MPRA(x) (*(__IO hw_aips_mpra_t *) HW_AIPS_MPRA_ADDR(x)) #define HW_AIPS_MPRA_RD(x) (HW_AIPS_MPRA(x).U) #define HW_AIPS_MPRA_WR(x, v) (HW_AIPS_MPRA(x).U = (v)) #define HW_AIPS_MPRA_SET(x, v) (HW_AIPS_MPRA_WR(x, HW_AIPS_MPRA_RD(x) | (v))) #define HW_AIPS_MPRA_CLR(x, v) (HW_AIPS_MPRA_WR(x, HW_AIPS_MPRA_RD(x) & ~(v))) #define HW_AIPS_MPRA_TOG(x, v) (HW_AIPS_MPRA_WR(x, HW_AIPS_MPRA_RD(x) ^ (v))) /*@}*/ /* * Constants & macros for individual AIPS_MPRA bitfields */ /*! * @name Register AIPS_MPRA, field MPL5[8] (RW) * * Specifies how the privilege level of the master is determined. * * Values: * - 0 - Accesses from this master are forced to user-mode. * - 1 - Accesses from this master are not forced to user-mode. */ /*@{*/ #define BP_AIPS_MPRA_MPL5 (8U) /*!< Bit position for AIPS_MPRA_MPL5. */ #define BM_AIPS_MPRA_MPL5 (0x00000100U) /*!< Bit mask for AIPS_MPRA_MPL5. */ #define BS_AIPS_MPRA_MPL5 (1U) /*!< Bit field size in bits for AIPS_MPRA_MPL5. */ /*! @brief Read current value of the AIPS_MPRA_MPL5 field. */ #define BR_AIPS_MPRA_MPL5(x) (BITBAND_ACCESS32(HW_AIPS_MPRA_ADDR(x), BP_AIPS_MPRA_MPL5)) /*! @brief Format value for bitfield AIPS_MPRA_MPL5. */ #define BF_AIPS_MPRA_MPL5(v) ((uint32_t)((uint32_t)(v) << BP_AIPS_MPRA_MPL5) & BM_AIPS_MPRA_MPL5) /*! @brief Set the MPL5 field to a new value. */ #define BW_AIPS_MPRA_MPL5(x, v) (BITBAND_ACCESS32(HW_AIPS_MPRA_ADDR(x), BP_AIPS_MPRA_MPL5) = (v)) /*@}*/ /*! * @name Register AIPS_MPRA, field MTW5[9] (RW) * * Determines whether the master is trusted for write accesses. * * Values: * - 0 - This master is not trusted for write accesses. * - 1 - This master is trusted for write accesses. */ /*@{*/ #define BP_AIPS_MPRA_MTW5 (9U) /*!< Bit position for AIPS_MPRA_MTW5. */ #define BM_AIPS_MPRA_MTW5 (0x00000200U) /*!< Bit mask for AIPS_MPRA_MTW5. */ #define BS_AIPS_MPRA_MTW5 (1U) /*!< Bit field size in bits for AIPS_MPRA_MTW5. */ /*! @brief Read current value of the AIPS_MPRA_MTW5 field. */ #define BR_AIPS_MPRA_MTW5(x) (BITBAND_ACCESS32(HW_AIPS_MPRA_ADDR(x), BP_AIPS_MPRA_MTW5)) /*! @brief Format value for bitfield AIPS_MPRA_MTW5. */ #define BF_AIPS_MPRA_MTW5(v) ((uint32_t)((uint32_t)(v) << BP_AIPS_MPRA_MTW5) & BM_AIPS_MPRA_MTW5) /*! @brief Set the MTW5 field to a new value. */ #define BW_AIPS_MPRA_MTW5(x, v) (BITBAND_ACCESS32(HW_AIPS_MPRA_ADDR(x), BP_AIPS_MPRA_MTW5) = (v)) /*@}*/ /*! * @name Register AIPS_MPRA, field MTR5[10] (RW) * * Determines whether the master is trusted for read accesses. * * Values: * - 0 - This master is not trusted for read accesses. * - 1 - This master is trusted for read accesses. */ /*@{*/ #define BP_AIPS_MPRA_MTR5 (10U) /*!< Bit position for AIPS_MPRA_MTR5. */ #define BM_AIPS_MPRA_MTR5 (0x00000400U) /*!< Bit mask for AIPS_MPRA_MTR5. */ #define BS_AIPS_MPRA_MTR5 (1U) /*!< Bit field size in bits for AIPS_MPRA_MTR5. */ /*! @brief Read current value of the AIPS_MPRA_MTR5 field. */ #define BR_AIPS_MPRA_MTR5(x) (BITBAND_ACCESS32(HW_AIPS_MPRA_ADDR(x), BP_AIPS_MPRA_MTR5)) /*! @brief Format value for bitfield AIPS_MPRA_MTR5. */ #define BF_AIPS_MPRA_MTR5(v) ((uint32_t)((uint32_t)(v) << BP_AIPS_MPRA_MTR5) & BM_AIPS_MPRA_MTR5) /*! @brief Set the MTR5 field to a new value. */ #define BW_AIPS_MPRA_MTR5(x, v) (BITBAND_ACCESS32(HW_AIPS_MPRA_ADDR(x), BP_AIPS_MPRA_MTR5) = (v)) /*@}*/ /*! * @name Register AIPS_MPRA, field MPL4[12] (RW) * * Specifies how the privilege level of the master is determined. * * Values: * - 0 - Accesses from this master are forced to user-mode. * - 1 - Accesses from this master are not forced to user-mode. */ /*@{*/ #define BP_AIPS_MPRA_MPL4 (12U) /*!< Bit position for AIPS_MPRA_MPL4. */ #define BM_AIPS_MPRA_MPL4 (0x00001000U) /*!< Bit mask for AIPS_MPRA_MPL4. */ #define BS_AIPS_MPRA_MPL4 (1U) /*!< Bit field size in bits for AIPS_MPRA_MPL4. */ /*! @brief Read current value of the AIPS_MPRA_MPL4 field. */ #define BR_AIPS_MPRA_MPL4(x) (BITBAND_ACCESS32(HW_AIPS_MPRA_ADDR(x), BP_AIPS_MPRA_MPL4)) /*! @brief Format value for bitfield AIPS_MPRA_MPL4. */ #define BF_AIPS_MPRA_MPL4(v) ((uint32_t)((uint32_t)(v) << BP_AIPS_MPRA_MPL4) & BM_AIPS_MPRA_MPL4) /*! @brief Set the MPL4 field to a new value. */ #define BW_AIPS_MPRA_MPL4(x, v) (BITBAND_ACCESS32(HW_AIPS_MPRA_ADDR(x), BP_AIPS_MPRA_MPL4) = (v)) /*@}*/ /*! * @name Register AIPS_MPRA, field MTW4[13] (RW) * * Determines whether the master is trusted for write accesses. * * Values: * - 0 - This master is not trusted for write accesses. * - 1 - This master is trusted for write accesses. */ /*@{*/ #define BP_AIPS_MPRA_MTW4 (13U) /*!< Bit position for AIPS_MPRA_MTW4. */ #define BM_AIPS_MPRA_MTW4 (0x00002000U) /*!< Bit mask for AIPS_MPRA_MTW4. */ #define BS_AIPS_MPRA_MTW4 (1U) /*!< Bit field size in bits for AIPS_MPRA_MTW4. */ /*! @brief Read current value of the AIPS_MPRA_MTW4 field. */ #define BR_AIPS_MPRA_MTW4(x) (BITBAND_ACCESS32(HW_AIPS_MPRA_ADDR(x), BP_AIPS_MPRA_MTW4)) /*! @brief Format value for bitfield AIPS_MPRA_MTW4. */ #define BF_AIPS_MPRA_MTW4(v) ((uint32_t)((uint32_t)(v) << BP_AIPS_MPRA_MTW4) & BM_AIPS_MPRA_MTW4) /*! @brief Set the MTW4 field to a new value. */ #define BW_AIPS_MPRA_MTW4(x, v) (BITBAND_ACCESS32(HW_AIPS_MPRA_ADDR(x), BP_AIPS_MPRA_MTW4) = (v)) /*@}*/ /*! * @name Register AIPS_MPRA, field MTR4[14] (RW) * * Determines whether the master is trusted for read accesses. * * Values: * - 0 - This master is not trusted for read accesses. * - 1 - This master is trusted for read accesses. */ /*@{*/ #define BP_AIPS_MPRA_MTR4 (14U) /*!< Bit position for AIPS_MPRA_MTR4. */ #define BM_AIPS_MPRA_MTR4 (0x00004000U) /*!< Bit mask for AIPS_MPRA_MTR4. */ #define BS_AIPS_MPRA_MTR4 (1U) /*!< Bit field size in bits for AIPS_MPRA_MTR4. */ /*! @brief Read current value of the AIPS_MPRA_MTR4 field. */ #define BR_AIPS_MPRA_MTR4(x) (BITBAND_ACCESS32(HW_AIPS_MPRA_ADDR(x), BP_AIPS_MPRA_MTR4)) /*! @brief Format value for bitfield AIPS_MPRA_MTR4. */ #define BF_AIPS_MPRA_MTR4(v) ((uint32_t)((uint32_t)(v) << BP_AIPS_MPRA_MTR4) & BM_AIPS_MPRA_MTR4) /*! @brief Set the MTR4 field to a new value. */ #define BW_AIPS_MPRA_MTR4(x, v) (BITBAND_ACCESS32(HW_AIPS_MPRA_ADDR(x), BP_AIPS_MPRA_MTR4) = (v)) /*@}*/ /*! * @name Register AIPS_MPRA, field MPL3[16] (RW) * * Specifies how the privilege level of the master is determined. * * Values: * - 0 - Accesses from this master are forced to user-mode. * - 1 - Accesses from this master are not forced to user-mode. */ /*@{*/ #define BP_AIPS_MPRA_MPL3 (16U) /*!< Bit position for AIPS_MPRA_MPL3. */ #define BM_AIPS_MPRA_MPL3 (0x00010000U) /*!< Bit mask for AIPS_MPRA_MPL3. */ #define BS_AIPS_MPRA_MPL3 (1U) /*!< Bit field size in bits for AIPS_MPRA_MPL3. */ /*! @brief Read current value of the AIPS_MPRA_MPL3 field. */ #define BR_AIPS_MPRA_MPL3(x) (BITBAND_ACCESS32(HW_AIPS_MPRA_ADDR(x), BP_AIPS_MPRA_MPL3)) /*! @brief Format value for bitfield AIPS_MPRA_MPL3. */ #define BF_AIPS_MPRA_MPL3(v) ((uint32_t)((uint32_t)(v) << BP_AIPS_MPRA_MPL3) & BM_AIPS_MPRA_MPL3) /*! @brief Set the MPL3 field to a new value. */ #define BW_AIPS_MPRA_MPL3(x, v) (BITBAND_ACCESS32(HW_AIPS_MPRA_ADDR(x), BP_AIPS_MPRA_MPL3) = (v)) /*@}*/ /*! * @name Register AIPS_MPRA, field MTW3[17] (RW) * * Determines whether the master is trusted for write accesses. * * Values: * - 0 - This master is not trusted for write accesses. * - 1 - This master is trusted for write accesses. */ /*@{*/ #define BP_AIPS_MPRA_MTW3 (17U) /*!< Bit position for AIPS_MPRA_MTW3. */ #define BM_AIPS_MPRA_MTW3 (0x00020000U) /*!< Bit mask for AIPS_MPRA_MTW3. */ #define BS_AIPS_MPRA_MTW3 (1U) /*!< Bit field size in bits for AIPS_MPRA_MTW3. */ /*! @brief Read current value of the AIPS_MPRA_MTW3 field. */ #define BR_AIPS_MPRA_MTW3(x) (BITBAND_ACCESS32(HW_AIPS_MPRA_ADDR(x), BP_AIPS_MPRA_MTW3)) /*! @brief Format value for bitfield AIPS_MPRA_MTW3. */ #define BF_AIPS_MPRA_MTW3(v) ((uint32_t)((uint32_t)(v) << BP_AIPS_MPRA_MTW3) & BM_AIPS_MPRA_MTW3) /*! @brief Set the MTW3 field to a new value. */ #define BW_AIPS_MPRA_MTW3(x, v) (BITBAND_ACCESS32(HW_AIPS_MPRA_ADDR(x), BP_AIPS_MPRA_MTW3) = (v)) /*@}*/ /*! * @name Register AIPS_MPRA, field MTR3[18] (RW) * * Determines whether the master is trusted for read accesses. * * Values: * - 0 - This master is not trusted for read accesses. * - 1 - This master is trusted for read accesses. */ /*@{*/ #define BP_AIPS_MPRA_MTR3 (18U) /*!< Bit position for AIPS_MPRA_MTR3. */ #define BM_AIPS_MPRA_MTR3 (0x00040000U) /*!< Bit mask for AIPS_MPRA_MTR3. */ #define BS_AIPS_MPRA_MTR3 (1U) /*!< Bit field size in bits for AIPS_MPRA_MTR3. */ /*! @brief Read current value of the AIPS_MPRA_MTR3 field. */ #define BR_AIPS_MPRA_MTR3(x) (BITBAND_ACCESS32(HW_AIPS_MPRA_ADDR(x), BP_AIPS_MPRA_MTR3)) /*! @brief Format value for bitfield AIPS_MPRA_MTR3. */ #define BF_AIPS_MPRA_MTR3(v) ((uint32_t)((uint32_t)(v) << BP_AIPS_MPRA_MTR3) & BM_AIPS_MPRA_MTR3) /*! @brief Set the MTR3 field to a new value. */ #define BW_AIPS_MPRA_MTR3(x, v) (BITBAND_ACCESS32(HW_AIPS_MPRA_ADDR(x), BP_AIPS_MPRA_MTR3) = (v)) /*@}*/ /*! * @name Register AIPS_MPRA, field MPL2[20] (RW) * * Specifies how the privilege level of the master is determined. * * Values: * - 0 - Accesses from this master are forced to user-mode. * - 1 - Accesses from this master are not forced to user-mode. */ /*@{*/ #define BP_AIPS_MPRA_MPL2 (20U) /*!< Bit position for AIPS_MPRA_MPL2. */ #define BM_AIPS_MPRA_MPL2 (0x00100000U) /*!< Bit mask for AIPS_MPRA_MPL2. */ #define BS_AIPS_MPRA_MPL2 (1U) /*!< Bit field size in bits for AIPS_MPRA_MPL2. */ /*! @brief Read current value of the AIPS_MPRA_MPL2 field. */ #define BR_AIPS_MPRA_MPL2(x) (BITBAND_ACCESS32(HW_AIPS_MPRA_ADDR(x), BP_AIPS_MPRA_MPL2)) /*! @brief Format value for bitfield AIPS_MPRA_MPL2. */ #define BF_AIPS_MPRA_MPL2(v) ((uint32_t)((uint32_t)(v) << BP_AIPS_MPRA_MPL2) & BM_AIPS_MPRA_MPL2) /*! @brief Set the MPL2 field to a new value. */ #define BW_AIPS_MPRA_MPL2(x, v) (BITBAND_ACCESS32(HW_AIPS_MPRA_ADDR(x), BP_AIPS_MPRA_MPL2) = (v)) /*@}*/ /*! * @name Register AIPS_MPRA, field MTW2[21] (RW) * * Determines whether the master is trusted for write accesses. * * Values: * - 0 - This master is not trusted for write accesses. * - 1 - This master is trusted for write accesses. */ /*@{*/ #define BP_AIPS_MPRA_MTW2 (21U) /*!< Bit position for AIPS_MPRA_MTW2. */ #define BM_AIPS_MPRA_MTW2 (0x00200000U) /*!< Bit mask for AIPS_MPRA_MTW2. */ #define BS_AIPS_MPRA_MTW2 (1U) /*!< Bit field size in bits for AIPS_MPRA_MTW2. */ /*! @brief Read current value of the AIPS_MPRA_MTW2 field. */ #define BR_AIPS_MPRA_MTW2(x) (BITBAND_ACCESS32(HW_AIPS_MPRA_ADDR(x), BP_AIPS_MPRA_MTW2)) /*! @brief Format value for bitfield AIPS_MPRA_MTW2. */ #define BF_AIPS_MPRA_MTW2(v) ((uint32_t)((uint32_t)(v) << BP_AIPS_MPRA_MTW2) & BM_AIPS_MPRA_MTW2) /*! @brief Set the MTW2 field to a new value. */ #define BW_AIPS_MPRA_MTW2(x, v) (BITBAND_ACCESS32(HW_AIPS_MPRA_ADDR(x), BP_AIPS_MPRA_MTW2) = (v)) /*@}*/ /*! * @name Register AIPS_MPRA, field MTR2[22] (RW) * * Determines whether the master is trusted for read accesses. * * Values: * - 0 - This master is not trusted for read accesses. * - 1 - This master is trusted for read accesses. */ /*@{*/ #define BP_AIPS_MPRA_MTR2 (22U) /*!< Bit position for AIPS_MPRA_MTR2. */ #define BM_AIPS_MPRA_MTR2 (0x00400000U) /*!< Bit mask for AIPS_MPRA_MTR2. */ #define BS_AIPS_MPRA_MTR2 (1U) /*!< Bit field size in bits for AIPS_MPRA_MTR2. */ /*! @brief Read current value of the AIPS_MPRA_MTR2 field. */ #define BR_AIPS_MPRA_MTR2(x) (BITBAND_ACCESS32(HW_AIPS_MPRA_ADDR(x), BP_AIPS_MPRA_MTR2)) /*! @brief Format value for bitfield AIPS_MPRA_MTR2. */ #define BF_AIPS_MPRA_MTR2(v) ((uint32_t)((uint32_t)(v) << BP_AIPS_MPRA_MTR2) & BM_AIPS_MPRA_MTR2) /*! @brief Set the MTR2 field to a new value. */ #define BW_AIPS_MPRA_MTR2(x, v) (BITBAND_ACCESS32(HW_AIPS_MPRA_ADDR(x), BP_AIPS_MPRA_MTR2) = (v)) /*@}*/ /*! * @name Register AIPS_MPRA, field MPL1[24] (RW) * * Specifies how the privilege level of the master is determined. * * Values: * - 0 - Accesses from this master are forced to user-mode. * - 1 - Accesses from this master are not forced to user-mode. */ /*@{*/ #define BP_AIPS_MPRA_MPL1 (24U) /*!< Bit position for AIPS_MPRA_MPL1. */ #define BM_AIPS_MPRA_MPL1 (0x01000000U) /*!< Bit mask for AIPS_MPRA_MPL1. */ #define BS_AIPS_MPRA_MPL1 (1U) /*!< Bit field size in bits for AIPS_MPRA_MPL1. */ /*! @brief Read current value of the AIPS_MPRA_MPL1 field. */ #define BR_AIPS_MPRA_MPL1(x) (BITBAND_ACCESS32(HW_AIPS_MPRA_ADDR(x), BP_AIPS_MPRA_MPL1)) /*! @brief Format value for bitfield AIPS_MPRA_MPL1. */ #define BF_AIPS_MPRA_MPL1(v) ((uint32_t)((uint32_t)(v) << BP_AIPS_MPRA_MPL1) & BM_AIPS_MPRA_MPL1) /*! @brief Set the MPL1 field to a new value. */ #define BW_AIPS_MPRA_MPL1(x, v) (BITBAND_ACCESS32(HW_AIPS_MPRA_ADDR(x), BP_AIPS_MPRA_MPL1) = (v)) /*@}*/ /*! * @name Register AIPS_MPRA, field MTW1[25] (RW) * * Determines whether the master is trusted for write accesses. * * Values: * - 0 - This master is not trusted for write accesses. * - 1 - This master is trusted for write accesses. */ /*@{*/ #define BP_AIPS_MPRA_MTW1 (25U) /*!< Bit position for AIPS_MPRA_MTW1. */ #define BM_AIPS_MPRA_MTW1 (0x02000000U) /*!< Bit mask for AIPS_MPRA_MTW1. */ #define BS_AIPS_MPRA_MTW1 (1U) /*!< Bit field size in bits for AIPS_MPRA_MTW1. */ /*! @brief Read current value of the AIPS_MPRA_MTW1 field. */ #define BR_AIPS_MPRA_MTW1(x) (BITBAND_ACCESS32(HW_AIPS_MPRA_ADDR(x), BP_AIPS_MPRA_MTW1)) /*! @brief Format value for bitfield AIPS_MPRA_MTW1. */ #define BF_AIPS_MPRA_MTW1(v) ((uint32_t)((uint32_t)(v) << BP_AIPS_MPRA_MTW1) & BM_AIPS_MPRA_MTW1) /*! @brief Set the MTW1 field to a new value. */ #define BW_AIPS_MPRA_MTW1(x, v) (BITBAND_ACCESS32(HW_AIPS_MPRA_ADDR(x), BP_AIPS_MPRA_MTW1) = (v)) /*@}*/ /*! * @name Register AIPS_MPRA, field MTR1[26] (RW) * * Determines whether the master is trusted for read accesses. * * Values: * - 0 - This master is not trusted for read accesses. * - 1 - This master is trusted for read accesses. */ /*@{*/ #define BP_AIPS_MPRA_MTR1 (26U) /*!< Bit position for AIPS_MPRA_MTR1. */ #define BM_AIPS_MPRA_MTR1 (0x04000000U) /*!< Bit mask for AIPS_MPRA_MTR1. */ #define BS_AIPS_MPRA_MTR1 (1U) /*!< Bit field size in bits for AIPS_MPRA_MTR1. */ /*! @brief Read current value of the AIPS_MPRA_MTR1 field. */ #define BR_AIPS_MPRA_MTR1(x) (BITBAND_ACCESS32(HW_AIPS_MPRA_ADDR(x), BP_AIPS_MPRA_MTR1)) /*! @brief Format value for bitfield AIPS_MPRA_MTR1. */ #define BF_AIPS_MPRA_MTR1(v) ((uint32_t)((uint32_t)(v) << BP_AIPS_MPRA_MTR1) & BM_AIPS_MPRA_MTR1) /*! @brief Set the MTR1 field to a new value. */ #define BW_AIPS_MPRA_MTR1(x, v) (BITBAND_ACCESS32(HW_AIPS_MPRA_ADDR(x), BP_AIPS_MPRA_MTR1) = (v)) /*@}*/ /*! * @name Register AIPS_MPRA, field MPL0[28] (RW) * * Specifies how the privilege level of the master is determined. * * Values: * - 0 - Accesses from this master are forced to user-mode. * - 1 - Accesses from this master are not forced to user-mode. */ /*@{*/ #define BP_AIPS_MPRA_MPL0 (28U) /*!< Bit position for AIPS_MPRA_MPL0. */ #define BM_AIPS_MPRA_MPL0 (0x10000000U) /*!< Bit mask for AIPS_MPRA_MPL0. */ #define BS_AIPS_MPRA_MPL0 (1U) /*!< Bit field size in bits for AIPS_MPRA_MPL0. */ /*! @brief Read current value of the AIPS_MPRA_MPL0 field. */ #define BR_AIPS_MPRA_MPL0(x) (BITBAND_ACCESS32(HW_AIPS_MPRA_ADDR(x), BP_AIPS_MPRA_MPL0)) /*! @brief Format value for bitfield AIPS_MPRA_MPL0. */ #define BF_AIPS_MPRA_MPL0(v) ((uint32_t)((uint32_t)(v) << BP_AIPS_MPRA_MPL0) & BM_AIPS_MPRA_MPL0) /*! @brief Set the MPL0 field to a new value. */ #define BW_AIPS_MPRA_MPL0(x, v) (BITBAND_ACCESS32(HW_AIPS_MPRA_ADDR(x), BP_AIPS_MPRA_MPL0) = (v)) /*@}*/ /*! * @name Register AIPS_MPRA, field MTW0[29] (RW) * * Determines whether the master is trusted for write accesses. * * Values: * - 0 - This master is not trusted for write accesses. * - 1 - This master is trusted for write accesses. */ /*@{*/ #define BP_AIPS_MPRA_MTW0 (29U) /*!< Bit position for AIPS_MPRA_MTW0. */ #define BM_AIPS_MPRA_MTW0 (0x20000000U) /*!< Bit mask for AIPS_MPRA_MTW0. */ #define BS_AIPS_MPRA_MTW0 (1U) /*!< Bit field size in bits for AIPS_MPRA_MTW0. */ /*! @brief Read current value of the AIPS_MPRA_MTW0 field. */ #define BR_AIPS_MPRA_MTW0(x) (BITBAND_ACCESS32(HW_AIPS_MPRA_ADDR(x), BP_AIPS_MPRA_MTW0)) /*! @brief Format value for bitfield AIPS_MPRA_MTW0. */ #define BF_AIPS_MPRA_MTW0(v) ((uint32_t)((uint32_t)(v) << BP_AIPS_MPRA_MTW0) & BM_AIPS_MPRA_MTW0) /*! @brief Set the MTW0 field to a new value. */ #define BW_AIPS_MPRA_MTW0(x, v) (BITBAND_ACCESS32(HW_AIPS_MPRA_ADDR(x), BP_AIPS_MPRA_MTW0) = (v)) /*@}*/ /*! * @name Register AIPS_MPRA, field MTR0[30] (RW) * * Determines whether the master is trusted for read accesses. * * Values: * - 0 - This master is not trusted for read accesses. * - 1 - This master is trusted for read accesses. */ /*@{*/ #define BP_AIPS_MPRA_MTR0 (30U) /*!< Bit position for AIPS_MPRA_MTR0. */ #define BM_AIPS_MPRA_MTR0 (0x40000000U) /*!< Bit mask for AIPS_MPRA_MTR0. */ #define BS_AIPS_MPRA_MTR0 (1U) /*!< Bit field size in bits for AIPS_MPRA_MTR0. */ /*! @brief Read current value of the AIPS_MPRA_MTR0 field. */ #define BR_AIPS_MPRA_MTR0(x) (BITBAND_ACCESS32(HW_AIPS_MPRA_ADDR(x), BP_AIPS_MPRA_MTR0)) /*! @brief Format value for bitfield AIPS_MPRA_MTR0. */ #define BF_AIPS_MPRA_MTR0(v) ((uint32_t)((uint32_t)(v) << BP_AIPS_MPRA_MTR0) & BM_AIPS_MPRA_MTR0) /*! @brief Set the MTR0 field to a new value. */ #define BW_AIPS_MPRA_MTR0(x, v) (BITBAND_ACCESS32(HW_AIPS_MPRA_ADDR(x), BP_AIPS_MPRA_MTR0) = (v)) /*@}*/ /******************************************************************************* * HW_AIPS_PACRA - Peripheral Access Control Register ******************************************************************************/ /*! * @brief HW_AIPS_PACRA - Peripheral Access Control Register (RW) * * Reset value: 0x50004000U * * Each PACR register consists of eight 4-bit PACR fields. Each PACR field * defines the access levels for a particular peripheral. The mapping between a * peripheral and its PACR field is shown in the table below. The peripheral assignment * to each PACR is defined by the memory map slot that the peripheral is * assigned to. See this chip's memory map for the assignment of a particular * peripheral. The following table shows the location of each peripheral slot's PACR field * in the PACR registers. Offset Register [31:28] [27:24] [23:20] [19:16] [15:12] * [11:8] [7:4] [3:0] 0x20 PACRA PACR0 PACR1 PACR2 PACR3 PACR4 PACR5 PACR6 PACR7 * 0x24 PACRB PACR8 PACR9 PACR10 PACR11 PACR12 PACR13 PACR14 PACR15 0x28 PACRC * PACR16 PACR17 PACR18 PACR19 PACR20 PACR21 PACR22 PACR23 0x2C PACRD PACR24 * PACR25 PACR26 PACR27 PACR28 PACR29 PACR30 PACR31 0x30 Reserved 0x34 Reserved 0x38 * Reserved 0x3C Reserved 0x40 PACRE PACR32 PACR33 PACR34 PACR35 PACR36 PACR37 * PACR38 PACR39 0x44 PACRF PACR40 PACR41 PACR42 PACR43 PACR44 PACR45 PACR46 PACR47 * 0x48 PACRG PACR48 PACR49 PACR50 PACR51 PACR52 PACR53 PACR54 PACR55 0x4C PACRH * PACR56 PACR57 PACR58 PACR59 PACR60 PACR61 PACR62 PACR63 0x50 PACRI PACR64 * PACR65 PACR66 PACR67 PACR68 PACR69 PACR70 PACR71 0x54 PACRJ PACR72 PACR73 PACR74 * PACR75 PACR76 PACR77 PACR78 PACR79 0x58 PACRK PACR80 PACR81 PACR82 PACR83 * PACR84 PACR85 PACR86 PACR87 0x5C PACRL PACR88 PACR89 PACR90 PACR91 PACR92 PACR93 * PACR94 PACR95 0x60 PACRM PACR96 PACR97 PACR98 PACR99 PACR100 PACR101 PACR102 * PACR103 0x64 PACRN PACR104 PACR105 PACR106 PACR107 PACR108 PACR109 PACR110 * PACR111 0x68 PACRO PACR112 PACR113 PACR114 PACR115 PACR116 PACR117 PACR118 PACR119 * 0x6C PACRP PACR120 PACR121 PACR122 PACR123 PACR124 PACR125 PACR126 PACR127 0x80 * PACRU PACR GBL0 PACR GBL1 Reserved The register field descriptions for PACR * A-D, which control peripheral slots 0-31, are shown below. The following * section, PACRPeripheral Access Control Register , shows the register field * descriptions for PACR E-P. All PACR registers are identical. They are divided into two * sections because they occupy two non-contiguous address spaces. */ typedef union _hw_aips_pacra { uint32_t U; struct _hw_aips_pacra_bitfields { uint32_t TP7 : 1; /*!< [0] Trusted Protect */ uint32_t WP7 : 1; /*!< [1] Write Protect */ uint32_t SP7 : 1; /*!< [2] Supervisor Protect */ uint32_t RESERVED0 : 1; /*!< [3] */ uint32_t TP6 : 1; /*!< [4] Trusted Protect */ uint32_t WP6 : 1; /*!< [5] Write Protect */ uint32_t SP6 : 1; /*!< [6] Supervisor Protect */ uint32_t RESERVED1 : 1; /*!< [7] */ uint32_t TP5 : 1; /*!< [8] Trusted Protect */ uint32_t WP5 : 1; /*!< [9] Write Protect */ uint32_t SP5 : 1; /*!< [10] Supervisor Protect */ uint32_t RESERVED2 : 1; /*!< [11] */ uint32_t TP4 : 1; /*!< [12] Trusted Protect */ uint32_t WP4 : 1; /*!< [13] Write Protect */ uint32_t SP4 : 1; /*!< [14] Supervisor Protect */ uint32_t RESERVED3 : 1; /*!< [15] */ uint32_t TP3 : 1; /*!< [16] Trusted Protect */ uint32_t WP3 : 1; /*!< [17] Write Protect */ uint32_t SP3 : 1; /*!< [18] Supervisor Protect */ uint32_t RESERVED4 : 1; /*!< [19] */ uint32_t TP2 : 1; /*!< [20] Trusted Protect */ uint32_t WP2 : 1; /*!< [21] Write Protect */ uint32_t SP2 : 1; /*!< [22] Supervisor Protect */ uint32_t RESERVED5 : 1; /*!< [23] */ uint32_t TP1 : 1; /*!< [24] Trusted Protect */ uint32_t WP1 : 1; /*!< [25] Write Protect */ uint32_t SP1 : 1; /*!< [26] Supervisor Protect */ uint32_t RESERVED6 : 1; /*!< [27] */ uint32_t TP0 : 1; /*!< [28] Trusted Protect */ uint32_t WP0 : 1; /*!< [29] Write Protect */ uint32_t SP0 : 1; /*!< [30] Supervisor Protect */ uint32_t RESERVED7 : 1; /*!< [31] */ } B; } hw_aips_pacra_t; /*! * @name Constants and macros for entire AIPS_PACRA register */ /*@{*/ #define HW_AIPS_PACRA_ADDR(x) ((x) + 0x20U) #define HW_AIPS_PACRA(x) (*(__IO hw_aips_pacra_t *) HW_AIPS_PACRA_ADDR(x)) #define HW_AIPS_PACRA_RD(x) (HW_AIPS_PACRA(x).U) #define HW_AIPS_PACRA_WR(x, v) (HW_AIPS_PACRA(x).U = (v)) #define HW_AIPS_PACRA_SET(x, v) (HW_AIPS_PACRA_WR(x, HW_AIPS_PACRA_RD(x) | (v))) #define HW_AIPS_PACRA_CLR(x, v) (HW_AIPS_PACRA_WR(x, HW_AIPS_PACRA_RD(x) & ~(v))) #define HW_AIPS_PACRA_TOG(x, v) (HW_AIPS_PACRA_WR(x, HW_AIPS_PACRA_RD(x) ^ (v))) /*@}*/ /* * Constants & macros for individual AIPS_PACRA bitfields */ /*! * @name Register AIPS_PACRA, field TP7[0] (RW) * * Determines whether the peripheral allows accesses from an untrusted master. * When this field is set and an access is attempted by an untrusted master, the * access terminates with an error response and no peripheral access initiates. * * Values: * - 0 - Accesses from an untrusted master are allowed. * - 1 - Accesses from an untrusted master are not allowed. */ /*@{*/ #define BP_AIPS_PACRA_TP7 (0U) /*!< Bit position for AIPS_PACRA_TP7. */ #define BM_AIPS_PACRA_TP7 (0x00000001U) /*!< Bit mask for AIPS_PACRA_TP7. */ #define BS_AIPS_PACRA_TP7 (1U) /*!< Bit field size in bits for AIPS_PACRA_TP7. */ /*! @brief Read current value of the AIPS_PACRA_TP7 field. */ #define BR_AIPS_PACRA_TP7(x) (BITBAND_ACCESS32(HW_AIPS_PACRA_ADDR(x), BP_AIPS_PACRA_TP7)) /*! @brief Format value for bitfield AIPS_PACRA_TP7. */ #define BF_AIPS_PACRA_TP7(v) ((uint32_t)((uint32_t)(v) << BP_AIPS_PACRA_TP7) & BM_AIPS_PACRA_TP7) /*! @brief Set the TP7 field to a new value. */ #define BW_AIPS_PACRA_TP7(x, v) (BITBAND_ACCESS32(HW_AIPS_PACRA_ADDR(x), BP_AIPS_PACRA_TP7) = (v)) /*@}*/ /*! * @name Register AIPS_PACRA, field WP7[1] (RW) * * Determines whether the peripheral allows write accesses. When this field is * set and a write access is attempted, access terminates with an error response * and no peripheral access initiates. * * Values: * - 0 - This peripheral allows write accesses. * - 1 - This peripheral is write protected. */ /*@{*/ #define BP_AIPS_PACRA_WP7 (1U) /*!< Bit position for AIPS_PACRA_WP7. */ #define BM_AIPS_PACRA_WP7 (0x00000002U) /*!< Bit mask for AIPS_PACRA_WP7. */ #define BS_AIPS_PACRA_WP7 (1U) /*!< Bit field size in bits for AIPS_PACRA_WP7. */ /*! @brief Read current value of the AIPS_PACRA_WP7 field. */ #define BR_AIPS_PACRA_WP7(x) (BITBAND_ACCESS32(HW_AIPS_PACRA_ADDR(x), BP_AIPS_PACRA_WP7)) /*! @brief Format value for bitfield AIPS_PACRA_WP7. */ #define BF_AIPS_PACRA_WP7(v) ((uint32_t)((uint32_t)(v) << BP_AIPS_PACRA_WP7) & BM_AIPS_PACRA_WP7) /*! @brief Set the WP7 field to a new value. */ #define BW_AIPS_PACRA_WP7(x, v) (BITBAND_ACCESS32(HW_AIPS_PACRA_ADDR(x), BP_AIPS_PACRA_WP7) = (v)) /*@}*/ /*! * @name Register AIPS_PACRA, field SP7[2] (RW) * * Determines whether the peripheral requires supervisor privilege level for * accesses. When this field is set, the master privilege level must indicate the * supervisor access attribute, and the MPRx[MPLn] control field for the master * must be set. If not, access terminates with an error response and no peripheral * access initiates. * * Values: * - 0 - This peripheral does not require supervisor privilege level for * accesses. * - 1 - This peripheral requires supervisor privilege level for accesses. */ /*@{*/ #define BP_AIPS_PACRA_SP7 (2U) /*!< Bit position for AIPS_PACRA_SP7. */ #define BM_AIPS_PACRA_SP7 (0x00000004U) /*!< Bit mask for AIPS_PACRA_SP7. */ #define BS_AIPS_PACRA_SP7 (1U) /*!< Bit field size in bits for AIPS_PACRA_SP7. */ /*! @brief Read current value of the AIPS_PACRA_SP7 field. */ #define BR_AIPS_PACRA_SP7(x) (BITBAND_ACCESS32(HW_AIPS_PACRA_ADDR(x), BP_AIPS_PACRA_SP7)) /*! @brief Format value for bitfield AIPS_PACRA_SP7. */ #define BF_AIPS_PACRA_SP7(v) ((uint32_t)((uint32_t)(v) << BP_AIPS_PACRA_SP7) & BM_AIPS_PACRA_SP7) /*! @brief Set the SP7 field to a new value. */ #define BW_AIPS_PACRA_SP7(x, v) (BITBAND_ACCESS32(HW_AIPS_PACRA_ADDR(x), BP_AIPS_PACRA_SP7) = (v)) /*@}*/ /*! * @name Register AIPS_PACRA, field TP6[4] (RW) * * Determines whether the peripheral allows accesses from an untrusted master. * When this field is set and an access is attempted by an untrusted master, the * access terminates with an error response and no peripheral access initiates. * * Values: * - 0 - Accesses from an untrusted master are allowed. * - 1 - Accesses from an untrusted master are not allowed. */ /*@{*/ #define BP_AIPS_PACRA_TP6 (4U) /*!< Bit position for AIPS_PACRA_TP6. */ #define BM_AIPS_PACRA_TP6 (0x00000010U) /*!< Bit mask for AIPS_PACRA_TP6. */ #define BS_AIPS_PACRA_TP6 (1U) /*!< Bit field size in bits for AIPS_PACRA_TP6. */ /*! @brief Read current value of the AIPS_PACRA_TP6 field. */ #define BR_AIPS_PACRA_TP6(x) (BITBAND_ACCESS32(HW_AIPS_PACRA_ADDR(x), BP_AIPS_PACRA_TP6)) /*! @brief Format value for bitfield AIPS_PACRA_TP6. */ #define BF_AIPS_PACRA_TP6(v) ((uint32_t)((uint32_t)(v) << BP_AIPS_PACRA_TP6) & BM_AIPS_PACRA_TP6) /*! @brief Set the TP6 field to a new value. */ #define BW_AIPS_PACRA_TP6(x, v) (BITBAND_ACCESS32(HW_AIPS_PACRA_ADDR(x), BP_AIPS_PACRA_TP6) = (v)) /*@}*/ /*! * @name Register AIPS_PACRA, field WP6[5] (RW) * * Determines whether the peripheral allows write accesses. When this field is * set and a write access is attempted, access terminates with an error response * and no peripheral access initiates. * * Values: * - 0 - This peripheral allows write accesses. * - 1 - This peripheral is write protected. */ /*@{*/ #define BP_AIPS_PACRA_WP6 (5U) /*!< Bit position for AIPS_PACRA_WP6. */ #define BM_AIPS_PACRA_WP6 (0x00000020U) /*!< Bit mask for AIPS_PACRA_WP6. */ #define BS_AIPS_PACRA_WP6 (1U) /*!< Bit field size in bits for AIPS_PACRA_WP6. */ /*! @brief Read current value of the AIPS_PACRA_WP6 field. */ #define BR_AIPS_PACRA_WP6(x) (BITBAND_ACCESS32(HW_AIPS_PACRA_ADDR(x), BP_AIPS_PACRA_WP6)) /*! @brief Format value for bitfield AIPS_PACRA_WP6. */ #define BF_AIPS_PACRA_WP6(v) ((uint32_t)((uint32_t)(v) << BP_AIPS_PACRA_WP6) & BM_AIPS_PACRA_WP6) /*! @brief Set the WP6 field to a new value. */ #define BW_AIPS_PACRA_WP6(x, v) (BITBAND_ACCESS32(HW_AIPS_PACRA_ADDR(x), BP_AIPS_PACRA_WP6) = (v)) /*@}*/ /*! * @name Register AIPS_PACRA, field SP6[6] (RW) * * Determines whether the peripheral requires supervisor privilege level for * accesses. When this field is set, the master privilege level must indicate the * supervisor access attribute, and the MPRx[MPLn] control field for the master * must be set. If not, access terminates with an error response and no peripheral * access initiates. * * Values: * - 0 - This peripheral does not require supervisor privilege level for * accesses. * - 1 - This peripheral requires supervisor privilege level for accesses. */ /*@{*/ #define BP_AIPS_PACRA_SP6 (6U) /*!< Bit position for AIPS_PACRA_SP6. */ #define BM_AIPS_PACRA_SP6 (0x00000040U) /*!< Bit mask for AIPS_PACRA_SP6. */ #define BS_AIPS_PACRA_SP6 (1U) /*!< Bit field size in bits for AIPS_PACRA_SP6. */ /*! @brief Read current value of the AIPS_PACRA_SP6 field. */ #define BR_AIPS_PACRA_SP6(x) (BITBAND_ACCESS32(HW_AIPS_PACRA_ADDR(x), BP_AIPS_PACRA_SP6)) /*! @brief Format value for bitfield AIPS_PACRA_SP6. */ #define BF_AIPS_PACRA_SP6(v) ((uint32_t)((uint32_t)(v) << BP_AIPS_PACRA_SP6) & BM_AIPS_PACRA_SP6) /*! @brief Set the SP6 field to a new value. */ #define BW_AIPS_PACRA_SP6(x, v) (BITBAND_ACCESS32(HW_AIPS_PACRA_ADDR(x), BP_AIPS_PACRA_SP6) = (v)) /*@}*/ /*! * @name Register AIPS_PACRA, field TP5[8] (RW) * * Determines whether the peripheral allows accesses from an untrusted master. * When this field is set and an access is attempted by an untrusted master, the * access terminates with an error response and no peripheral access initiates. * * Values: * - 0 - Accesses from an untrusted master are allowed. * - 1 - Accesses from an untrusted master are not allowed. */ /*@{*/ #define BP_AIPS_PACRA_TP5 (8U) /*!< Bit position for AIPS_PACRA_TP5. */ #define BM_AIPS_PACRA_TP5 (0x00000100U) /*!< Bit mask for AIPS_PACRA_TP5. */ #define BS_AIPS_PACRA_TP5 (1U) /*!< Bit field size in bits for AIPS_PACRA_TP5. */ /*! @brief Read current value of the AIPS_PACRA_TP5 field. */ #define BR_AIPS_PACRA_TP5(x) (BITBAND_ACCESS32(HW_AIPS_PACRA_ADDR(x), BP_AIPS_PACRA_TP5)) /*! @brief Format value for bitfield AIPS_PACRA_TP5. */ #define BF_AIPS_PACRA_TP5(v) ((uint32_t)((uint32_t)(v) << BP_AIPS_PACRA_TP5) & BM_AIPS_PACRA_TP5) /*! @brief Set the TP5 field to a new value. */ #define BW_AIPS_PACRA_TP5(x, v) (BITBAND_ACCESS32(HW_AIPS_PACRA_ADDR(x), BP_AIPS_PACRA_TP5) = (v)) /*@}*/ /*! * @name Register AIPS_PACRA, field WP5[9] (RW) * * Determines whether the peripheral allows write accesses. When this field is * set and a write access is attempted, access terminates with an error response * and no peripheral access initiates. * * Values: * - 0 - This peripheral allows write accesses. * - 1 - This peripheral is write protected. */ /*@{*/ #define BP_AIPS_PACRA_WP5 (9U) /*!< Bit position for AIPS_PACRA_WP5. */ #define BM_AIPS_PACRA_WP5 (0x00000200U) /*!< Bit mask for AIPS_PACRA_WP5. */ #define BS_AIPS_PACRA_WP5 (1U) /*!< Bit field size in bits for AIPS_PACRA_WP5. */ /*! @brief Read current value of the AIPS_PACRA_WP5 field. */ #define BR_AIPS_PACRA_WP5(x) (BITBAND_ACCESS32(HW_AIPS_PACRA_ADDR(x), BP_AIPS_PACRA_WP5)) /*! @brief Format value for bitfield AIPS_PACRA_WP5. */ #define BF_AIPS_PACRA_WP5(v) ((uint32_t)((uint32_t)(v) << BP_AIPS_PACRA_WP5) & BM_AIPS_PACRA_WP5) /*! @brief Set the WP5 field to a new value. */ #define BW_AIPS_PACRA_WP5(x, v) (BITBAND_ACCESS32(HW_AIPS_PACRA_ADDR(x), BP_AIPS_PACRA_WP5) = (v)) /*@}*/ /*! * @name Register AIPS_PACRA, field SP5[10] (RW) * * Determines whether the peripheral requires supervisor privilege level for * accesses. When this field is set, the master privilege level must indicate the * supervisor access attribute, and the MPRx[MPLn] control field for the master * must be set. If not, access terminates with an error response and no peripheral * access initiates. * * Values: * - 0 - This peripheral does not require supervisor privilege level for * accesses. * - 1 - This peripheral requires supervisor privilege level for accesses. */ /*@{*/ #define BP_AIPS_PACRA_SP5 (10U) /*!< Bit position for AIPS_PACRA_SP5. */ #define BM_AIPS_PACRA_SP5 (0x00000400U) /*!< Bit mask for AIPS_PACRA_SP5. */ #define BS_AIPS_PACRA_SP5 (1U) /*!< Bit field size in bits for AIPS_PACRA_SP5. */ /*! @brief Read current value of the AIPS_PACRA_SP5 field. */ #define BR_AIPS_PACRA_SP5(x) (BITBAND_ACCESS32(HW_AIPS_PACRA_ADDR(x), BP_AIPS_PACRA_SP5)) /*! @brief Format value for bitfield AIPS_PACRA_SP5. */ #define BF_AIPS_PACRA_SP5(v) ((uint32_t)((uint32_t)(v) << BP_AIPS_PACRA_SP5) & BM_AIPS_PACRA_SP5) /*! @brief Set the SP5 field to a new value. */ #define BW_AIPS_PACRA_SP5(x, v) (BITBAND_ACCESS32(HW_AIPS_PACRA_ADDR(x), BP_AIPS_PACRA_SP5) = (v)) /*@}*/ /*! * @name Register AIPS_PACRA, field TP4[12] (RW) * * Determines whether the peripheral allows accesses from an untrusted master. * When this field is set and an access is attempted by an untrusted master, the * access terminates with an error response and no peripheral access initiates. * * Values: * - 0 - Accesses from an untrusted master are allowed. * - 1 - Accesses from an untrusted master are not allowed. */ /*@{*/ #define BP_AIPS_PACRA_TP4 (12U) /*!< Bit position for AIPS_PACRA_TP4. */ #define BM_AIPS_PACRA_TP4 (0x00001000U) /*!< Bit mask for AIPS_PACRA_TP4. */ #define BS_AIPS_PACRA_TP4 (1U) /*!< Bit field size in bits for AIPS_PACRA_TP4. */ /*! @brief Read current value of the AIPS_PACRA_TP4 field. */ #define BR_AIPS_PACRA_TP4(x) (BITBAND_ACCESS32(HW_AIPS_PACRA_ADDR(x), BP_AIPS_PACRA_TP4)) /*! @brief Format value for bitfield AIPS_PACRA_TP4. */ #define BF_AIPS_PACRA_TP4(v) ((uint32_t)((uint32_t)(v) << BP_AIPS_PACRA_TP4) & BM_AIPS_PACRA_TP4) /*! @brief Set the TP4 field to a new value. */ #define BW_AIPS_PACRA_TP4(x, v) (BITBAND_ACCESS32(HW_AIPS_PACRA_ADDR(x), BP_AIPS_PACRA_TP4) = (v)) /*@}*/ /*! * @name Register AIPS_PACRA, field WP4[13] (RW) * * Determines whether the peripheral allows write accesss. When this bit is set * and a write access is attempted, access terminates with an error response and * no peripheral access initiates. * * Values: * - 0 - This peripheral allows write accesses. * - 1 - This peripheral is write protected. */ /*@{*/ #define BP_AIPS_PACRA_WP4 (13U) /*!< Bit position for AIPS_PACRA_WP4. */ #define BM_AIPS_PACRA_WP4 (0x00002000U) /*!< Bit mask for AIPS_PACRA_WP4. */ #define BS_AIPS_PACRA_WP4 (1U) /*!< Bit field size in bits for AIPS_PACRA_WP4. */ /*! @brief Read current value of the AIPS_PACRA_WP4 field. */ #define BR_AIPS_PACRA_WP4(x) (BITBAND_ACCESS32(HW_AIPS_PACRA_ADDR(x), BP_AIPS_PACRA_WP4)) /*! @brief Format value for bitfield AIPS_PACRA_WP4. */ #define BF_AIPS_PACRA_WP4(v) ((uint32_t)((uint32_t)(v) << BP_AIPS_PACRA_WP4) & BM_AIPS_PACRA_WP4) /*! @brief Set the WP4 field to a new value. */ #define BW_AIPS_PACRA_WP4(x, v) (BITBAND_ACCESS32(HW_AIPS_PACRA_ADDR(x), BP_AIPS_PACRA_WP4) = (v)) /*@}*/ /*! * @name Register AIPS_PACRA, field SP4[14] (RW) * * Determines whether the peripheral requires supervisor privilege level for * accesses. When this field is set, the master privilege level must indicate the * supervisor access attribute, and the MPRx[MPLn] control field for the master * must be set. If not, access terminates with an error response and no peripheral * access initiates. * * Values: * - 0 - This peripheral does not require supervisor privilege level for * accesses. * - 1 - This peripheral requires supervisor privilege level for accesses. */ /*@{*/ #define BP_AIPS_PACRA_SP4 (14U) /*!< Bit position for AIPS_PACRA_SP4. */ #define BM_AIPS_PACRA_SP4 (0x00004000U) /*!< Bit mask for AIPS_PACRA_SP4. */ #define BS_AIPS_PACRA_SP4 (1U) /*!< Bit field size in bits for AIPS_PACRA_SP4. */ /*! @brief Read current value of the AIPS_PACRA_SP4 field. */ #define BR_AIPS_PACRA_SP4(x) (BITBAND_ACCESS32(HW_AIPS_PACRA_ADDR(x), BP_AIPS_PACRA_SP4)) /*! @brief Format value for bitfield AIPS_PACRA_SP4. */ #define BF_AIPS_PACRA_SP4(v) ((uint32_t)((uint32_t)(v) << BP_AIPS_PACRA_SP4) & BM_AIPS_PACRA_SP4) /*! @brief Set the SP4 field to a new value. */ #define BW_AIPS_PACRA_SP4(x, v) (BITBAND_ACCESS32(HW_AIPS_PACRA_ADDR(x), BP_AIPS_PACRA_SP4) = (v)) /*@}*/ /*! * @name Register AIPS_PACRA, field TP3[16] (RW) * * Determines whether the peripheral allows accesses from an untrusted master. * When this bit is set and an access is attempted by an untrusted master, the * access terminates with an error response and no peripheral access initiates. * * Values: * - 0 - Accesses from an untrusted master are allowed. * - 1 - Accesses from an untrusted master are not allowed. */ /*@{*/ #define BP_AIPS_PACRA_TP3 (16U) /*!< Bit position for AIPS_PACRA_TP3. */ #define BM_AIPS_PACRA_TP3 (0x00010000U) /*!< Bit mask for AIPS_PACRA_TP3. */ #define BS_AIPS_PACRA_TP3 (1U) /*!< Bit field size in bits for AIPS_PACRA_TP3. */ /*! @brief Read current value of the AIPS_PACRA_TP3 field. */ #define BR_AIPS_PACRA_TP3(x) (BITBAND_ACCESS32(HW_AIPS_PACRA_ADDR(x), BP_AIPS_PACRA_TP3)) /*! @brief Format value for bitfield AIPS_PACRA_TP3. */ #define BF_AIPS_PACRA_TP3(v) ((uint32_t)((uint32_t)(v) << BP_AIPS_PACRA_TP3) & BM_AIPS_PACRA_TP3) /*! @brief Set the TP3 field to a new value. */ #define BW_AIPS_PACRA_TP3(x, v) (BITBAND_ACCESS32(HW_AIPS_PACRA_ADDR(x), BP_AIPS_PACRA_TP3) = (v)) /*@}*/ /*! * @name Register AIPS_PACRA, field WP3[17] (RW) * * Determines whether the peripheral allows write accesses. When this field is * set and a write access is attempted, access terminates with an error response * and no peripheral access initiates. * * Values: * - 0 - This peripheral allows write accesses. * - 1 - This peripheral is write protected. */ /*@{*/ #define BP_AIPS_PACRA_WP3 (17U) /*!< Bit position for AIPS_PACRA_WP3. */ #define BM_AIPS_PACRA_WP3 (0x00020000U) /*!< Bit mask for AIPS_PACRA_WP3. */ #define BS_AIPS_PACRA_WP3 (1U) /*!< Bit field size in bits for AIPS_PACRA_WP3. */ /*! @brief Read current value of the AIPS_PACRA_WP3 field. */ #define BR_AIPS_PACRA_WP3(x) (BITBAND_ACCESS32(HW_AIPS_PACRA_ADDR(x), BP_AIPS_PACRA_WP3)) /*! @brief Format value for bitfield AIPS_PACRA_WP3. */ #define BF_AIPS_PACRA_WP3(v) ((uint32_t)((uint32_t)(v) << BP_AIPS_PACRA_WP3) & BM_AIPS_PACRA_WP3) /*! @brief Set the WP3 field to a new value. */ #define BW_AIPS_PACRA_WP3(x, v) (BITBAND_ACCESS32(HW_AIPS_PACRA_ADDR(x), BP_AIPS_PACRA_WP3) = (v)) /*@}*/ /*! * @name Register AIPS_PACRA, field SP3[18] (RW) * * Determines whether the peripheral requires supervisor privilege level for * access. When this bit is set, the master privilege level must indicate the * supervisor access attribute, and the MPRx[MPLn] control bit for the master must be * set. If not, access terminates with an error response and no peripheral access * initiates. * * Values: * - 0 - This peripheral does not require supervisor privilege level for * accesses. * - 1 - This peripheral requires supervisor privilege level for accesses. */ /*@{*/ #define BP_AIPS_PACRA_SP3 (18U) /*!< Bit position for AIPS_PACRA_SP3. */ #define BM_AIPS_PACRA_SP3 (0x00040000U) /*!< Bit mask for AIPS_PACRA_SP3. */ #define BS_AIPS_PACRA_SP3 (1U) /*!< Bit field size in bits for AIPS_PACRA_SP3. */ /*! @brief Read current value of the AIPS_PACRA_SP3 field. */ #define BR_AIPS_PACRA_SP3(x) (BITBAND_ACCESS32(HW_AIPS_PACRA_ADDR(x), BP_AIPS_PACRA_SP3)) /*! @brief Format value for bitfield AIPS_PACRA_SP3. */ #define BF_AIPS_PACRA_SP3(v) ((uint32_t)((uint32_t)(v) << BP_AIPS_PACRA_SP3) & BM_AIPS_PACRA_SP3) /*! @brief Set the SP3 field to a new value. */ #define BW_AIPS_PACRA_SP3(x, v) (BITBAND_ACCESS32(HW_AIPS_PACRA_ADDR(x), BP_AIPS_PACRA_SP3) = (v)) /*@}*/ /*! * @name Register AIPS_PACRA, field TP2[20] (RW) * * Determines whether the peripheral allows accesses from an untrusted master. * When this field is set and an access is attempted by an untrusted master, the * access terminates with an error response and no peripheral access initiates. * * Values: * - 0 - Accesses from an untrusted master are allowed. * - 1 - Accesses from an untrusted master are not allowed. */ /*@{*/ #define BP_AIPS_PACRA_TP2 (20U) /*!< Bit position for AIPS_PACRA_TP2. */ #define BM_AIPS_PACRA_TP2 (0x00100000U) /*!< Bit mask for AIPS_PACRA_TP2. */ #define BS_AIPS_PACRA_TP2 (1U) /*!< Bit field size in bits for AIPS_PACRA_TP2. */ /*! @brief Read current value of the AIPS_PACRA_TP2 field. */ #define BR_AIPS_PACRA_TP2(x) (BITBAND_ACCESS32(HW_AIPS_PACRA_ADDR(x), BP_AIPS_PACRA_TP2)) /*! @brief Format value for bitfield AIPS_PACRA_TP2. */ #define BF_AIPS_PACRA_TP2(v) ((uint32_t)((uint32_t)(v) << BP_AIPS_PACRA_TP2) & BM_AIPS_PACRA_TP2) /*! @brief Set the TP2 field to a new value. */ #define BW_AIPS_PACRA_TP2(x, v) (BITBAND_ACCESS32(HW_AIPS_PACRA_ADDR(x), BP_AIPS_PACRA_TP2) = (v)) /*@}*/ /*! * @name Register AIPS_PACRA, field WP2[21] (RW) * * Determines whether the peripheral allows write accesss. When this bit is set * and a write access is attempted, access terminates with an error response and * no peripheral access initiates. * * Values: * - 0 - This peripheral allows write accesses. * - 1 - This peripheral is write protected. */ /*@{*/ #define BP_AIPS_PACRA_WP2 (21U) /*!< Bit position for AIPS_PACRA_WP2. */ #define BM_AIPS_PACRA_WP2 (0x00200000U) /*!< Bit mask for AIPS_PACRA_WP2. */ #define BS_AIPS_PACRA_WP2 (1U) /*!< Bit field size in bits for AIPS_PACRA_WP2. */ /*! @brief Read current value of the AIPS_PACRA_WP2 field. */ #define BR_AIPS_PACRA_WP2(x) (BITBAND_ACCESS32(HW_AIPS_PACRA_ADDR(x), BP_AIPS_PACRA_WP2)) /*! @brief Format value for bitfield AIPS_PACRA_WP2. */ #define BF_AIPS_PACRA_WP2(v) ((uint32_t)((uint32_t)(v) << BP_AIPS_PACRA_WP2) & BM_AIPS_PACRA_WP2) /*! @brief Set the WP2 field to a new value. */ #define BW_AIPS_PACRA_WP2(x, v) (BITBAND_ACCESS32(HW_AIPS_PACRA_ADDR(x), BP_AIPS_PACRA_WP2) = (v)) /*@}*/ /*! * @name Register AIPS_PACRA, field SP2[22] (RW) * * Determines whether the peripheral requires supervisor privilege level for * accesses. When this field is set, the master privilege level must indicate the * supervisor access attribute, and the MPRx[MPLn] control field for the master * must be set. If not, access terminates with an error response and no peripheral * access initiates. * * Values: * - 0 - This peripheral does not require supervisor privilege level for * accesses. * - 1 - This peripheral requires supervisor privilege level for accesses. */ /*@{*/ #define BP_AIPS_PACRA_SP2 (22U) /*!< Bit position for AIPS_PACRA_SP2. */ #define BM_AIPS_PACRA_SP2 (0x00400000U) /*!< Bit mask for AIPS_PACRA_SP2. */ #define BS_AIPS_PACRA_SP2 (1U) /*!< Bit field size in bits for AIPS_PACRA_SP2. */ /*! @brief Read current value of the AIPS_PACRA_SP2 field. */ #define BR_AIPS_PACRA_SP2(x) (BITBAND_ACCESS32(HW_AIPS_PACRA_ADDR(x), BP_AIPS_PACRA_SP2)) /*! @brief Format value for bitfield AIPS_PACRA_SP2. */ #define BF_AIPS_PACRA_SP2(v) ((uint32_t)((uint32_t)(v) << BP_AIPS_PACRA_SP2) & BM_AIPS_PACRA_SP2) /*! @brief Set the SP2 field to a new value. */ #define BW_AIPS_PACRA_SP2(x, v) (BITBAND_ACCESS32(HW_AIPS_PACRA_ADDR(x), BP_AIPS_PACRA_SP2) = (v)) /*@}*/ /*! * @name Register AIPS_PACRA, field TP1[24] (RW) * * Determines whether the peripheral allows accesses from an untrusted master. * When this bit is set and an access is attempted by an untrusted master, the * access terminates with an error response and no peripheral access initiates. * * Values: * - 0 - Accesses from an untrusted master are allowed. * - 1 - Accesses from an untrusted master are not allowed. */ /*@{*/ #define BP_AIPS_PACRA_TP1 (24U) /*!< Bit position for AIPS_PACRA_TP1. */ #define BM_AIPS_PACRA_TP1 (0x01000000U) /*!< Bit mask for AIPS_PACRA_TP1. */ #define BS_AIPS_PACRA_TP1 (1U) /*!< Bit field size in bits for AIPS_PACRA_TP1. */ /*! @brief Read current value of the AIPS_PACRA_TP1 field. */ #define BR_AIPS_PACRA_TP1(x) (BITBAND_ACCESS32(HW_AIPS_PACRA_ADDR(x), BP_AIPS_PACRA_TP1)) /*! @brief Format value for bitfield AIPS_PACRA_TP1. */ #define BF_AIPS_PACRA_TP1(v) ((uint32_t)((uint32_t)(v) << BP_AIPS_PACRA_TP1) & BM_AIPS_PACRA_TP1) /*! @brief Set the TP1 field to a new value. */ #define BW_AIPS_PACRA_TP1(x, v) (BITBAND_ACCESS32(HW_AIPS_PACRA_ADDR(x), BP_AIPS_PACRA_TP1) = (v)) /*@}*/ /*! * @name Register AIPS_PACRA, field WP1[25] (RW) * * Determines whether the peripheral allows write accesses. When this field is * set and a write access is attempted, access terminates with an error response * and no peripheral access initiates. * * Values: * - 0 - This peripheral allows write accesses. * - 1 - This peripheral is write protected. */ /*@{*/ #define BP_AIPS_PACRA_WP1 (25U) /*!< Bit position for AIPS_PACRA_WP1. */ #define BM_AIPS_PACRA_WP1 (0x02000000U) /*!< Bit mask for AIPS_PACRA_WP1. */ #define BS_AIPS_PACRA_WP1 (1U) /*!< Bit field size in bits for AIPS_PACRA_WP1. */ /*! @brief Read current value of the AIPS_PACRA_WP1 field. */ #define BR_AIPS_PACRA_WP1(x) (BITBAND_ACCESS32(HW_AIPS_PACRA_ADDR(x), BP_AIPS_PACRA_WP1)) /*! @brief Format value for bitfield AIPS_PACRA_WP1. */ #define BF_AIPS_PACRA_WP1(v) ((uint32_t)((uint32_t)(v) << BP_AIPS_PACRA_WP1) & BM_AIPS_PACRA_WP1) /*! @brief Set the WP1 field to a new value. */ #define BW_AIPS_PACRA_WP1(x, v) (BITBAND_ACCESS32(HW_AIPS_PACRA_ADDR(x), BP_AIPS_PACRA_WP1) = (v)) /*@}*/ /*! * @name Register AIPS_PACRA, field SP1[26] (RW) * * Determines whether the peripheral requires supervisor privilege level for * accesses. When this field is set, the master privilege level must indicate the * supervisor access attribute, and the MPRx[MPLn] control field for the master * must be set. If not, access terminates with an error response and no peripheral * access initiates. * * Values: * - 0 - This peripheral does not require supervisor privilege level for * accesses. * - 1 - This peripheral requires supervisor privilege level for accesses. */ /*@{*/ #define BP_AIPS_PACRA_SP1 (26U) /*!< Bit position for AIPS_PACRA_SP1. */ #define BM_AIPS_PACRA_SP1 (0x04000000U) /*!< Bit mask for AIPS_PACRA_SP1. */ #define BS_AIPS_PACRA_SP1 (1U) /*!< Bit field size in bits for AIPS_PACRA_SP1. */ /*! @brief Read current value of the AIPS_PACRA_SP1 field. */ #define BR_AIPS_PACRA_SP1(x) (BITBAND_ACCESS32(HW_AIPS_PACRA_ADDR(x), BP_AIPS_PACRA_SP1)) /*! @brief Format value for bitfield AIPS_PACRA_SP1. */ #define BF_AIPS_PACRA_SP1(v) ((uint32_t)((uint32_t)(v) << BP_AIPS_PACRA_SP1) & BM_AIPS_PACRA_SP1) /*! @brief Set the SP1 field to a new value. */ #define BW_AIPS_PACRA_SP1(x, v) (BITBAND_ACCESS32(HW_AIPS_PACRA_ADDR(x), BP_AIPS_PACRA_SP1) = (v)) /*@}*/ /*! * @name Register AIPS_PACRA, field TP0[28] (RW) * * Determines whether the peripheral allows accesses from an untrusted master. * When this field is set and an access is attempted by an untrusted master, the * access terminates with an error response and no peripheral access initiates. * * Values: * - 0 - Accesses from an untrusted master are allowed. * - 1 - Accesses from an untrusted master are not allowed. */ /*@{*/ #define BP_AIPS_PACRA_TP0 (28U) /*!< Bit position for AIPS_PACRA_TP0. */ #define BM_AIPS_PACRA_TP0 (0x10000000U) /*!< Bit mask for AIPS_PACRA_TP0. */ #define BS_AIPS_PACRA_TP0 (1U) /*!< Bit field size in bits for AIPS_PACRA_TP0. */ /*! @brief Read current value of the AIPS_PACRA_TP0 field. */ #define BR_AIPS_PACRA_TP0(x) (BITBAND_ACCESS32(HW_AIPS_PACRA_ADDR(x), BP_AIPS_PACRA_TP0)) /*! @brief Format value for bitfield AIPS_PACRA_TP0. */ #define BF_AIPS_PACRA_TP0(v) ((uint32_t)((uint32_t)(v) << BP_AIPS_PACRA_TP0) & BM_AIPS_PACRA_TP0) /*! @brief Set the TP0 field to a new value. */ #define BW_AIPS_PACRA_TP0(x, v) (BITBAND_ACCESS32(HW_AIPS_PACRA_ADDR(x), BP_AIPS_PACRA_TP0) = (v)) /*@}*/ /*! * @name Register AIPS_PACRA, field WP0[29] (RW) * * Determines whether the peripheral allows write accesss. When this bit is set * and a write access is attempted, access terminates with an error response and * no peripheral access initiates. * * Values: * - 0 - This peripheral allows write accesses. * - 1 - This peripheral is write protected. */ /*@{*/ #define BP_AIPS_PACRA_WP0 (29U) /*!< Bit position for AIPS_PACRA_WP0. */ #define BM_AIPS_PACRA_WP0 (0x20000000U) /*!< Bit mask for AIPS_PACRA_WP0. */ #define BS_AIPS_PACRA_WP0 (1U) /*!< Bit field size in bits for AIPS_PACRA_WP0. */ /*! @brief Read current value of the AIPS_PACRA_WP0 field. */ #define BR_AIPS_PACRA_WP0(x) (BITBAND_ACCESS32(HW_AIPS_PACRA_ADDR(x), BP_AIPS_PACRA_WP0)) /*! @brief Format value for bitfield AIPS_PACRA_WP0. */ #define BF_AIPS_PACRA_WP0(v) ((uint32_t)((uint32_t)(v) << BP_AIPS_PACRA_WP0) & BM_AIPS_PACRA_WP0) /*! @brief Set the WP0 field to a new value. */ #define BW_AIPS_PACRA_WP0(x, v) (BITBAND_ACCESS32(HW_AIPS_PACRA_ADDR(x), BP_AIPS_PACRA_WP0) = (v)) /*@}*/ /*! * @name Register AIPS_PACRA, field SP0[30] (RW) * * Determines whether the peripheral requires supervisor privilege level for * accesses. When this field is set, the master privilege level must indicate the * supervisor access attribute, and the MPRx[MPLn] control field for the master * must be set. If not, access terminates with an error response and no peripheral * access initiates. * * Values: * - 0 - This peripheral does not require supervisor privilege level for * accesses. * - 1 - This peripheral requires supervisor privilege level for accesses. */ /*@{*/ #define BP_AIPS_PACRA_SP0 (30U) /*!< Bit position for AIPS_PACRA_SP0. */ #define BM_AIPS_PACRA_SP0 (0x40000000U) /*!< Bit mask for AIPS_PACRA_SP0. */ #define BS_AIPS_PACRA_SP0 (1U) /*!< Bit field size in bits for AIPS_PACRA_SP0. */ /*! @brief Read current value of the AIPS_PACRA_SP0 field. */ #define BR_AIPS_PACRA_SP0(x) (BITBAND_ACCESS32(HW_AIPS_PACRA_ADDR(x), BP_AIPS_PACRA_SP0)) /*! @brief Format value for bitfield AIPS_PACRA_SP0. */ #define BF_AIPS_PACRA_SP0(v) ((uint32_t)((uint32_t)(v) << BP_AIPS_PACRA_SP0) & BM_AIPS_PACRA_SP0) /*! @brief Set the SP0 field to a new value. */ #define BW_AIPS_PACRA_SP0(x, v) (BITBAND_ACCESS32(HW_AIPS_PACRA_ADDR(x), BP_AIPS_PACRA_SP0) = (v)) /*@}*/ /******************************************************************************* * HW_AIPS_PACRB - Peripheral Access Control Register ******************************************************************************/ /*! * @brief HW_AIPS_PACRB - Peripheral Access Control Register (RW) * * Reset value: 0x44004400U * * Each PACR register consists of eight 4-bit PACR fields. Each PACR field * defines the access levels for a particular peripheral. The mapping between a * peripheral and its PACR field is shown in the table below. The peripheral assignment * to each PACR is defined by the memory map slot that the peripheral is * assigned to. See this chip's memory map for the assignment of a particular * peripheral. The following table shows the location of each peripheral slot's PACR field * in the PACR registers. Offset Register [31:28] [27:24] [23:20] [19:16] [15:12] * [11:8] [7:4] [3:0] 0x20 PACRA PACR0 PACR1 PACR2 PACR3 PACR4 PACR5 PACR6 PACR7 * 0x24 PACRB PACR8 PACR9 PACR10 PACR11 PACR12 PACR13 PACR14 PACR15 0x28 PACRC * PACR16 PACR17 PACR18 PACR19 PACR20 PACR21 PACR22 PACR23 0x2C PACRD PACR24 * PACR25 PACR26 PACR27 PACR28 PACR29 PACR30 PACR31 0x30 Reserved 0x34 Reserved 0x38 * Reserved 0x3C Reserved 0x40 PACRE PACR32 PACR33 PACR34 PACR35 PACR36 PACR37 * PACR38 PACR39 0x44 PACRF PACR40 PACR41 PACR42 PACR43 PACR44 PACR45 PACR46 PACR47 * 0x48 PACRG PACR48 PACR49 PACR50 PACR51 PACR52 PACR53 PACR54 PACR55 0x4C PACRH * PACR56 PACR57 PACR58 PACR59 PACR60 PACR61 PACR62 PACR63 0x50 PACRI PACR64 * PACR65 PACR66 PACR67 PACR68 PACR69 PACR70 PACR71 0x54 PACRJ PACR72 PACR73 PACR74 * PACR75 PACR76 PACR77 PACR78 PACR79 0x58 PACRK PACR80 PACR81 PACR82 PACR83 * PACR84 PACR85 PACR86 PACR87 0x5C PACRL PACR88 PACR89 PACR90 PACR91 PACR92 PACR93 * PACR94 PACR95 0x60 PACRM PACR96 PACR97 PACR98 PACR99 PACR100 PACR101 PACR102 * PACR103 0x64 PACRN PACR104 PACR105 PACR106 PACR107 PACR108 PACR109 PACR110 * PACR111 0x68 PACRO PACR112 PACR113 PACR114 PACR115 PACR116 PACR117 PACR118 PACR119 * 0x6C PACRP PACR120 PACR121 PACR122 PACR123 PACR124 PACR125 PACR126 PACR127 0x80 * PACRU PACR GBL0 PACR GBL1 Reserved The register field descriptions for PACR * A-D, which control peripheral slots 0-31, are shown below. The following * section, PACRPeripheral Access Control Register , shows the register field * descriptions for PACR E-P. All PACR registers are identical. They are divided into two * sections because they occupy two non-contiguous address spaces. */ typedef union _hw_aips_pacrb { uint32_t U; struct _hw_aips_pacrb_bitfields { uint32_t TP7 : 1; /*!< [0] Trusted Protect */ uint32_t WP7 : 1; /*!< [1] Write Protect */ uint32_t SP7 : 1; /*!< [2] Supervisor Protect */ uint32_t RESERVED0 : 1; /*!< [3] */ uint32_t TP6 : 1; /*!< [4] Trusted Protect */ uint32_t WP6 : 1; /*!< [5] Write Protect */ uint32_t SP6 : 1; /*!< [6] Supervisor Protect */ uint32_t RESERVED1 : 1; /*!< [7] */ uint32_t TP5 : 1; /*!< [8] Trusted Protect */ uint32_t WP5 : 1; /*!< [9] Write Protect */ uint32_t SP5 : 1; /*!< [10] Supervisor Protect */ uint32_t RESERVED2 : 1; /*!< [11] */ uint32_t TP4 : 1; /*!< [12] Trusted Protect */ uint32_t WP4 : 1; /*!< [13] Write Protect */ uint32_t SP4 : 1; /*!< [14] Supervisor Protect */ uint32_t RESERVED3 : 1; /*!< [15] */ uint32_t TP3 : 1; /*!< [16] Trusted Protect */ uint32_t WP3 : 1; /*!< [17] Write Protect */ uint32_t SP3 : 1; /*!< [18] Supervisor Protect */ uint32_t RESERVED4 : 1; /*!< [19] */ uint32_t TP2 : 1; /*!< [20] Trusted Protect */ uint32_t WP2 : 1; /*!< [21] Write Protect */ uint32_t SP2 : 1; /*!< [22] Supervisor Protect */ uint32_t RESERVED5 : 1; /*!< [23] */ uint32_t TP1 : 1; /*!< [24] Trusted Protect */ uint32_t WP1 : 1; /*!< [25] Write Protect */ uint32_t SP1 : 1; /*!< [26] Supervisor Protect */ uint32_t RESERVED6 : 1; /*!< [27] */ uint32_t TP0 : 1; /*!< [28] Trusted Protect */ uint32_t WP0 : 1; /*!< [29] Write Protect */ uint32_t SP0 : 1; /*!< [30] Supervisor Protect */ uint32_t RESERVED7 : 1; /*!< [31] */ } B; } hw_aips_pacrb_t; /*! * @name Constants and macros for entire AIPS_PACRB register */ /*@{*/ #define HW_AIPS_PACRB_ADDR(x) ((x) + 0x24U) #define HW_AIPS_PACRB(x) (*(__IO hw_aips_pacrb_t *) HW_AIPS_PACRB_ADDR(x)) #define HW_AIPS_PACRB_RD(x) (HW_AIPS_PACRB(x).U) #define HW_AIPS_PACRB_WR(x, v) (HW_AIPS_PACRB(x).U = (v)) #define HW_AIPS_PACRB_SET(x, v) (HW_AIPS_PACRB_WR(x, HW_AIPS_PACRB_RD(x) | (v))) #define HW_AIPS_PACRB_CLR(x, v) (HW_AIPS_PACRB_WR(x, HW_AIPS_PACRB_RD(x) & ~(v))) #define HW_AIPS_PACRB_TOG(x, v) (HW_AIPS_PACRB_WR(x, HW_AIPS_PACRB_RD(x) ^ (v))) /*@}*/ /* * Constants & macros for individual AIPS_PACRB bitfields */ /*! * @name Register AIPS_PACRB, field TP7[0] (RW) * * Determines whether the peripheral allows accesses from an untrusted master. * When this field is set and an access is attempted by an untrusted master, the * access terminates with an error response and no peripheral access initiates. * * Values: * - 0 - Accesses from an untrusted master are allowed. * - 1 - Accesses from an untrusted master are not allowed. */ /*@{*/ #define BP_AIPS_PACRB_TP7 (0U) /*!< Bit position for AIPS_PACRB_TP7. */ #define BM_AIPS_PACRB_TP7 (0x00000001U) /*!< Bit mask for AIPS_PACRB_TP7. */ #define BS_AIPS_PACRB_TP7 (1U) /*!< Bit field size in bits for AIPS_PACRB_TP7. */ /*! @brief Read current value of the AIPS_PACRB_TP7 field. */ #define BR_AIPS_PACRB_TP7(x) (BITBAND_ACCESS32(HW_AIPS_PACRB_ADDR(x), BP_AIPS_PACRB_TP7)) /*! @brief Format value for bitfield AIPS_PACRB_TP7. */ #define BF_AIPS_PACRB_TP7(v) ((uint32_t)((uint32_t)(v) << BP_AIPS_PACRB_TP7) & BM_AIPS_PACRB_TP7) /*! @brief Set the TP7 field to a new value. */ #define BW_AIPS_PACRB_TP7(x, v) (BITBAND_ACCESS32(HW_AIPS_PACRB_ADDR(x), BP_AIPS_PACRB_TP7) = (v)) /*@}*/ /*! * @name Register AIPS_PACRB, field WP7[1] (RW) * * Determines whether the peripheral allows write accesses. When this field is * set and a write access is attempted, access terminates with an error response * and no peripheral access initiates. * * Values: * - 0 - This peripheral allows write accesses. * - 1 - This peripheral is write protected. */ /*@{*/ #define BP_AIPS_PACRB_WP7 (1U) /*!< Bit position for AIPS_PACRB_WP7. */ #define BM_AIPS_PACRB_WP7 (0x00000002U) /*!< Bit mask for AIPS_PACRB_WP7. */ #define BS_AIPS_PACRB_WP7 (1U) /*!< Bit field size in bits for AIPS_PACRB_WP7. */ /*! @brief Read current value of the AIPS_PACRB_WP7 field. */ #define BR_AIPS_PACRB_WP7(x) (BITBAND_ACCESS32(HW_AIPS_PACRB_ADDR(x), BP_AIPS_PACRB_WP7)) /*! @brief Format value for bitfield AIPS_PACRB_WP7. */ #define BF_AIPS_PACRB_WP7(v) ((uint32_t)((uint32_t)(v) << BP_AIPS_PACRB_WP7) & BM_AIPS_PACRB_WP7) /*! @brief Set the WP7 field to a new value. */ #define BW_AIPS_PACRB_WP7(x, v) (BITBAND_ACCESS32(HW_AIPS_PACRB_ADDR(x), BP_AIPS_PACRB_WP7) = (v)) /*@}*/ /*! * @name Register AIPS_PACRB, field SP7[2] (RW) * * Determines whether the peripheral requires supervisor privilege level for * accesses. When this field is set, the master privilege level must indicate the * supervisor access attribute, and the MPRx[MPLn] control field for the master * must be set. If not, access terminates with an error response and no peripheral * access initiates. * * Values: * - 0 - This peripheral does not require supervisor privilege level for * accesses. * - 1 - This peripheral requires supervisor privilege level for accesses. */ /*@{*/ #define BP_AIPS_PACRB_SP7 (2U) /*!< Bit position for AIPS_PACRB_SP7. */ #define BM_AIPS_PACRB_SP7 (0x00000004U) /*!< Bit mask for AIPS_PACRB_SP7. */ #define BS_AIPS_PACRB_SP7 (1U) /*!< Bit field size in bits for AIPS_PACRB_SP7. */ /*! @brief Read current value of the AIPS_PACRB_SP7 field. */ #define BR_AIPS_PACRB_SP7(x) (BITBAND_ACCESS32(HW_AIPS_PACRB_ADDR(x), BP_AIPS_PACRB_SP7)) /*! @brief Format value for bitfield AIPS_PACRB_SP7. */ #define BF_AIPS_PACRB_SP7(v) ((uint32_t)((uint32_t)(v) << BP_AIPS_PACRB_SP7) & BM_AIPS_PACRB_SP7) /*! @brief Set the SP7 field to a new value. */ #define BW_AIPS_PACRB_SP7(x, v) (BITBAND_ACCESS32(HW_AIPS_PACRB_ADDR(x), BP_AIPS_PACRB_SP7) = (v)) /*@}*/ /*! * @name Register AIPS_PACRB, field TP6[4] (RW) * * Determines whether the peripheral allows accesses from an untrusted master. * When this field is set and an access is attempted by an untrusted master, the * access terminates with an error response and no peripheral access initiates. * * Values: * - 0 - Accesses from an untrusted master are allowed. * - 1 - Accesses from an untrusted master are not allowed. */ /*@{*/ #define BP_AIPS_PACRB_TP6 (4U) /*!< Bit position for AIPS_PACRB_TP6. */ #define BM_AIPS_PACRB_TP6 (0x00000010U) /*!< Bit mask for AIPS_PACRB_TP6. */ #define BS_AIPS_PACRB_TP6 (1U) /*!< Bit field size in bits for AIPS_PACRB_TP6. */ /*! @brief Read current value of the AIPS_PACRB_TP6 field. */ #define BR_AIPS_PACRB_TP6(x) (BITBAND_ACCESS32(HW_AIPS_PACRB_ADDR(x), BP_AIPS_PACRB_TP6)) /*! @brief Format value for bitfield AIPS_PACRB_TP6. */ #define BF_AIPS_PACRB_TP6(v) ((uint32_t)((uint32_t)(v) << BP_AIPS_PACRB_TP6) & BM_AIPS_PACRB_TP6) /*! @brief Set the TP6 field to a new value. */ #define BW_AIPS_PACRB_TP6(x, v) (BITBAND_ACCESS32(HW_AIPS_PACRB_ADDR(x), BP_AIPS_PACRB_TP6) = (v)) /*@}*/ /*! * @name Register AIPS_PACRB, field WP6[5] (RW) * * Determines whether the peripheral allows write accesses. When this field is * set and a write access is attempted, access terminates with an error response * and no peripheral access initiates. * * Values: * - 0 - This peripheral allows write accesses. * - 1 - This peripheral is write protected. */ /*@{*/ #define BP_AIPS_PACRB_WP6 (5U) /*!< Bit position for AIPS_PACRB_WP6. */ #define BM_AIPS_PACRB_WP6 (0x00000020U) /*!< Bit mask for AIPS_PACRB_WP6. */ #define BS_AIPS_PACRB_WP6 (1U) /*!< Bit field size in bits for AIPS_PACRB_WP6. */ /*! @brief Read current value of the AIPS_PACRB_WP6 field. */ #define BR_AIPS_PACRB_WP6(x) (BITBAND_ACCESS32(HW_AIPS_PACRB_ADDR(x), BP_AIPS_PACRB_WP6)) /*! @brief Format value for bitfield AIPS_PACRB_WP6. */ #define BF_AIPS_PACRB_WP6(v) ((uint32_t)((uint32_t)(v) << BP_AIPS_PACRB_WP6) & BM_AIPS_PACRB_WP6) /*! @brief Set the WP6 field to a new value. */ #define BW_AIPS_PACRB_WP6(x, v) (BITBAND_ACCESS32(HW_AIPS_PACRB_ADDR(x), BP_AIPS_PACRB_WP6) = (v)) /*@}*/ /*! * @name Register AIPS_PACRB, field SP6[6] (RW) * * Determines whether the peripheral requires supervisor privilege level for * accesses. When this field is set, the master privilege level must indicate the * supervisor access attribute, and the MPRx[MPLn] control field for the master * must be set. If not, access terminates with an error response and no peripheral * access initiates. * * Values: * - 0 - This peripheral does not require supervisor privilege level for * accesses. * - 1 - This peripheral requires supervisor privilege level for accesses. */ /*@{*/ #define BP_AIPS_PACRB_SP6 (6U) /*!< Bit position for AIPS_PACRB_SP6. */ #define BM_AIPS_PACRB_SP6 (0x00000040U) /*!< Bit mask for AIPS_PACRB_SP6. */ #define BS_AIPS_PACRB_SP6 (1U) /*!< Bit field size in bits for AIPS_PACRB_SP6. */ /*! @brief Read current value of the AIPS_PACRB_SP6 field. */ #define BR_AIPS_PACRB_SP6(x) (BITBAND_ACCESS32(HW_AIPS_PACRB_ADDR(x), BP_AIPS_PACRB_SP6)) /*! @brief Format value for bitfield AIPS_PACRB_SP6. */ #define BF_AIPS_PACRB_SP6(v) ((uint32_t)((uint32_t)(v) << BP_AIPS_PACRB_SP6) & BM_AIPS_PACRB_SP6) /*! @brief Set the SP6 field to a new value. */ #define BW_AIPS_PACRB_SP6(x, v) (BITBAND_ACCESS32(HW_AIPS_PACRB_ADDR(x), BP_AIPS_PACRB_SP6) = (v)) /*@}*/ /*! * @name Register AIPS_PACRB, field TP5[8] (RW) * * Determines whether the peripheral allows accesses from an untrusted master. * When this field is set and an access is attempted by an untrusted master, the * access terminates with an error response and no peripheral access initiates. * * Values: * - 0 - Accesses from an untrusted master are allowed. * - 1 - Accesses from an untrusted master are not allowed. */ /*@{*/ #define BP_AIPS_PACRB_TP5 (8U) /*!< Bit position for AIPS_PACRB_TP5. */ #define BM_AIPS_PACRB_TP5 (0x00000100U) /*!< Bit mask for AIPS_PACRB_TP5. */ #define BS_AIPS_PACRB_TP5 (1U) /*!< Bit field size in bits for AIPS_PACRB_TP5. */ /*! @brief Read current value of the AIPS_PACRB_TP5 field. */ #define BR_AIPS_PACRB_TP5(x) (BITBAND_ACCESS32(HW_AIPS_PACRB_ADDR(x), BP_AIPS_PACRB_TP5)) /*! @brief Format value for bitfield AIPS_PACRB_TP5. */ #define BF_AIPS_PACRB_TP5(v) ((uint32_t)((uint32_t)(v) << BP_AIPS_PACRB_TP5) & BM_AIPS_PACRB_TP5) /*! @brief Set the TP5 field to a new value. */ #define BW_AIPS_PACRB_TP5(x, v) (BITBAND_ACCESS32(HW_AIPS_PACRB_ADDR(x), BP_AIPS_PACRB_TP5) = (v)) /*@}*/ /*! * @name Register AIPS_PACRB, field WP5[9] (RW) * * Determines whether the peripheral allows write accesses. When this field is * set and a write access is attempted, access terminates with an error response * and no peripheral access initiates. * * Values: * - 0 - This peripheral allows write accesses. * - 1 - This peripheral is write protected. */ /*@{*/ #define BP_AIPS_PACRB_WP5 (9U) /*!< Bit position for AIPS_PACRB_WP5. */ #define BM_AIPS_PACRB_WP5 (0x00000200U) /*!< Bit mask for AIPS_PACRB_WP5. */ #define BS_AIPS_PACRB_WP5 (1U) /*!< Bit field size in bits for AIPS_PACRB_WP5. */ /*! @brief Read current value of the AIPS_PACRB_WP5 field. */ #define BR_AIPS_PACRB_WP5(x) (BITBAND_ACCESS32(HW_AIPS_PACRB_ADDR(x), BP_AIPS_PACRB_WP5)) /*! @brief Format value for bitfield AIPS_PACRB_WP5. */ #define BF_AIPS_PACRB_WP5(v) ((uint32_t)((uint32_t)(v) << BP_AIPS_PACRB_WP5) & BM_AIPS_PACRB_WP5) /*! @brief Set the WP5 field to a new value. */ #define BW_AIPS_PACRB_WP5(x, v) (BITBAND_ACCESS32(HW_AIPS_PACRB_ADDR(x), BP_AIPS_PACRB_WP5) = (v)) /*@}*/ /*! * @name Register AIPS_PACRB, field SP5[10] (RW) * * Determines whether the peripheral requires supervisor privilege level for * accesses. When this field is set, the master privilege level must indicate the * supervisor access attribute, and the MPRx[MPLn] control field for the master * must be set. If not, access terminates with an error response and no peripheral * access initiates. * * Values: * - 0 - This peripheral does not require supervisor privilege level for * accesses. * - 1 - This peripheral requires supervisor privilege level for accesses. */ /*@{*/ #define BP_AIPS_PACRB_SP5 (10U) /*!< Bit position for AIPS_PACRB_SP5. */ #define BM_AIPS_PACRB_SP5 (0x00000400U) /*!< Bit mask for AIPS_PACRB_SP5. */ #define BS_AIPS_PACRB_SP5 (1U) /*!< Bit field size in bits for AIPS_PACRB_SP5. */ /*! @brief Read current value of the AIPS_PACRB_SP5 field. */ #define BR_AIPS_PACRB_SP5(x) (BITBAND_ACCESS32(HW_AIPS_PACRB_ADDR(x), BP_AIPS_PACRB_SP5)) /*! @brief Format value for bitfield AIPS_PACRB_SP5. */ #define BF_AIPS_PACRB_SP5(v) ((uint32_t)((uint32_t)(v) << BP_AIPS_PACRB_SP5) & BM_AIPS_PACRB_SP5) /*! @brief Set the SP5 field to a new value. */ #define BW_AIPS_PACRB_SP5(x, v) (BITBAND_ACCESS32(HW_AIPS_PACRB_ADDR(x), BP_AIPS_PACRB_SP5) = (v)) /*@}*/ /*! * @name Register AIPS_PACRB, field TP4[12] (RW) * * Determines whether the peripheral allows accesses from an untrusted master. * When this field is set and an access is attempted by an untrusted master, the * access terminates with an error response and no peripheral access initiates. * * Values: * - 0 - Accesses from an untrusted master are allowed. * - 1 - Accesses from an untrusted master are not allowed. */ /*@{*/ #define BP_AIPS_PACRB_TP4 (12U) /*!< Bit position for AIPS_PACRB_TP4. */ #define BM_AIPS_PACRB_TP4 (0x00001000U) /*!< Bit mask for AIPS_PACRB_TP4. */ #define BS_AIPS_PACRB_TP4 (1U) /*!< Bit field size in bits for AIPS_PACRB_TP4. */ /*! @brief Read current value of the AIPS_PACRB_TP4 field. */ #define BR_AIPS_PACRB_TP4(x) (BITBAND_ACCESS32(HW_AIPS_PACRB_ADDR(x), BP_AIPS_PACRB_TP4)) /*! @brief Format value for bitfield AIPS_PACRB_TP4. */ #define BF_AIPS_PACRB_TP4(v) ((uint32_t)((uint32_t)(v) << BP_AIPS_PACRB_TP4) & BM_AIPS_PACRB_TP4) /*! @brief Set the TP4 field to a new value. */ #define BW_AIPS_PACRB_TP4(x, v) (BITBAND_ACCESS32(HW_AIPS_PACRB_ADDR(x), BP_AIPS_PACRB_TP4) = (v)) /*@}*/ /*! * @name Register AIPS_PACRB, field WP4[13] (RW) * * Determines whether the peripheral allows write accesss. When this bit is set * and a write access is attempted, access terminates with an error response and * no peripheral access initiates. * * Values: * - 0 - This peripheral allows write accesses. * - 1 - This peripheral is write protected. */ /*@{*/ #define BP_AIPS_PACRB_WP4 (13U) /*!< Bit position for AIPS_PACRB_WP4. */ #define BM_AIPS_PACRB_WP4 (0x00002000U) /*!< Bit mask for AIPS_PACRB_WP4. */ #define BS_AIPS_PACRB_WP4 (1U) /*!< Bit field size in bits for AIPS_PACRB_WP4. */ /*! @brief Read current value of the AIPS_PACRB_WP4 field. */ #define BR_AIPS_PACRB_WP4(x) (BITBAND_ACCESS32(HW_AIPS_PACRB_ADDR(x), BP_AIPS_PACRB_WP4)) /*! @brief Format value for bitfield AIPS_PACRB_WP4. */ #define BF_AIPS_PACRB_WP4(v) ((uint32_t)((uint32_t)(v) << BP_AIPS_PACRB_WP4) & BM_AIPS_PACRB_WP4) /*! @brief Set the WP4 field to a new value. */ #define BW_AIPS_PACRB_WP4(x, v) (BITBAND_ACCESS32(HW_AIPS_PACRB_ADDR(x), BP_AIPS_PACRB_WP4) = (v)) /*@}*/ /*! * @name Register AIPS_PACRB, field SP4[14] (RW) * * Determines whether the peripheral requires supervisor privilege level for * accesses. When this field is set, the master privilege level must indicate the * supervisor access attribute, and the MPRx[MPLn] control field for the master * must be set. If not, access terminates with an error response and no peripheral * access initiates. * * Values: * - 0 - This peripheral does not require supervisor privilege level for * accesses. * - 1 - This peripheral requires supervisor privilege level for accesses. */ /*@{*/ #define BP_AIPS_PACRB_SP4 (14U) /*!< Bit position for AIPS_PACRB_SP4. */ #define BM_AIPS_PACRB_SP4 (0x00004000U) /*!< Bit mask for AIPS_PACRB_SP4. */ #define BS_AIPS_PACRB_SP4 (1U) /*!< Bit field size in bits for AIPS_PACRB_SP4. */ /*! @brief Read current value of the AIPS_PACRB_SP4 field. */ #define BR_AIPS_PACRB_SP4(x) (BITBAND_ACCESS32(HW_AIPS_PACRB_ADDR(x), BP_AIPS_PACRB_SP4)) /*! @brief Format value for bitfield AIPS_PACRB_SP4. */ #define BF_AIPS_PACRB_SP4(v) ((uint32_t)((uint32_t)(v) << BP_AIPS_PACRB_SP4) & BM_AIPS_PACRB_SP4) /*! @brief Set the SP4 field to a new value. */ #define BW_AIPS_PACRB_SP4(x, v) (BITBAND_ACCESS32(HW_AIPS_PACRB_ADDR(x), BP_AIPS_PACRB_SP4) = (v)) /*@}*/ /*! * @name Register AIPS_PACRB, field TP3[16] (RW) * * Determines whether the peripheral allows accesses from an untrusted master. * When this bit is set and an access is attempted by an untrusted master, the * access terminates with an error response and no peripheral access initiates. * * Values: * - 0 - Accesses from an untrusted master are allowed. * - 1 - Accesses from an untrusted master are not allowed. */ /*@{*/ #define BP_AIPS_PACRB_TP3 (16U) /*!< Bit position for AIPS_PACRB_TP3. */ #define BM_AIPS_PACRB_TP3 (0x00010000U) /*!< Bit mask for AIPS_PACRB_TP3. */ #define BS_AIPS_PACRB_TP3 (1U) /*!< Bit field size in bits for AIPS_PACRB_TP3. */ /*! @brief Read current value of the AIPS_PACRB_TP3 field. */ #define BR_AIPS_PACRB_TP3(x) (BITBAND_ACCESS32(HW_AIPS_PACRB_ADDR(x), BP_AIPS_PACRB_TP3)) /*! @brief Format value for bitfield AIPS_PACRB_TP3. */ #define BF_AIPS_PACRB_TP3(v) ((uint32_t)((uint32_t)(v) << BP_AIPS_PACRB_TP3) & BM_AIPS_PACRB_TP3) /*! @brief Set the TP3 field to a new value. */ #define BW_AIPS_PACRB_TP3(x, v) (BITBAND_ACCESS32(HW_AIPS_PACRB_ADDR(x), BP_AIPS_PACRB_TP3) = (v)) /*@}*/ /*! * @name Register AIPS_PACRB, field WP3[17] (RW) * * Determines whether the peripheral allows write accesses. When this field is * set and a write access is attempted, access terminates with an error response * and no peripheral access initiates. * * Values: * - 0 - This peripheral allows write accesses. * - 1 - This peripheral is write protected. */ /*@{*/ #define BP_AIPS_PACRB_WP3 (17U) /*!< Bit position for AIPS_PACRB_WP3. */ #define BM_AIPS_PACRB_WP3 (0x00020000U) /*!< Bit mask for AIPS_PACRB_WP3. */ #define BS_AIPS_PACRB_WP3 (1U) /*!< Bit field size in bits for AIPS_PACRB_WP3. */ /*! @brief Read current value of the AIPS_PACRB_WP3 field. */ #define BR_AIPS_PACRB_WP3(x) (BITBAND_ACCESS32(HW_AIPS_PACRB_ADDR(x), BP_AIPS_PACRB_WP3)) /*! @brief Format value for bitfield AIPS_PACRB_WP3. */ #define BF_AIPS_PACRB_WP3(v) ((uint32_t)((uint32_t)(v) << BP_AIPS_PACRB_WP3) & BM_AIPS_PACRB_WP3) /*! @brief Set the WP3 field to a new value. */ #define BW_AIPS_PACRB_WP3(x, v) (BITBAND_ACCESS32(HW_AIPS_PACRB_ADDR(x), BP_AIPS_PACRB_WP3) = (v)) /*@}*/ /*! * @name Register AIPS_PACRB, field SP3[18] (RW) * * Determines whether the peripheral requires supervisor privilege level for * access. When this bit is set, the master privilege level must indicate the * supervisor access attribute, and the MPRx[MPLn] control bit for the master must be * set. If not, access terminates with an error response and no peripheral access * initiates. * * Values: * - 0 - This peripheral does not require supervisor privilege level for * accesses. * - 1 - This peripheral requires supervisor privilege level for accesses. */ /*@{*/ #define BP_AIPS_PACRB_SP3 (18U) /*!< Bit position for AIPS_PACRB_SP3. */ #define BM_AIPS_PACRB_SP3 (0x00040000U) /*!< Bit mask for AIPS_PACRB_SP3. */ #define BS_AIPS_PACRB_SP3 (1U) /*!< Bit field size in bits for AIPS_PACRB_SP3. */ /*! @brief Read current value of the AIPS_PACRB_SP3 field. */ #define BR_AIPS_PACRB_SP3(x) (BITBAND_ACCESS32(HW_AIPS_PACRB_ADDR(x), BP_AIPS_PACRB_SP3)) /*! @brief Format value for bitfield AIPS_PACRB_SP3. */ #define BF_AIPS_PACRB_SP3(v) ((uint32_t)((uint32_t)(v) << BP_AIPS_PACRB_SP3) & BM_AIPS_PACRB_SP3) /*! @brief Set the SP3 field to a new value. */ #define BW_AIPS_PACRB_SP3(x, v) (BITBAND_ACCESS32(HW_AIPS_PACRB_ADDR(x), BP_AIPS_PACRB_SP3) = (v)) /*@}*/ /*! * @name Register AIPS_PACRB, field TP2[20] (RW) * * Determines whether the peripheral allows accesses from an untrusted master. * When this field is set and an access is attempted by an untrusted master, the * access terminates with an error response and no peripheral access initiates. * * Values: * - 0 - Accesses from an untrusted master are allowed. * - 1 - Accesses from an untrusted master are not allowed. */ /*@{*/ #define BP_AIPS_PACRB_TP2 (20U) /*!< Bit position for AIPS_PACRB_TP2. */ #define BM_AIPS_PACRB_TP2 (0x00100000U) /*!< Bit mask for AIPS_PACRB_TP2. */ #define BS_AIPS_PACRB_TP2 (1U) /*!< Bit field size in bits for AIPS_PACRB_TP2. */ /*! @brief Read current value of the AIPS_PACRB_TP2 field. */ #define BR_AIPS_PACRB_TP2(x) (BITBAND_ACCESS32(HW_AIPS_PACRB_ADDR(x), BP_AIPS_PACRB_TP2)) /*! @brief Format value for bitfield AIPS_PACRB_TP2. */ #define BF_AIPS_PACRB_TP2(v) ((uint32_t)((uint32_t)(v) << BP_AIPS_PACRB_TP2) & BM_AIPS_PACRB_TP2) /*! @brief Set the TP2 field to a new value. */ #define BW_AIPS_PACRB_TP2(x, v) (BITBAND_ACCESS32(HW_AIPS_PACRB_ADDR(x), BP_AIPS_PACRB_TP2) = (v)) /*@}*/ /*! * @name Register AIPS_PACRB, field WP2[21] (RW) * * Determines whether the peripheral allows write accesss. When this bit is set * and a write access is attempted, access terminates with an error response and * no peripheral access initiates. * * Values: * - 0 - This peripheral allows write accesses. * - 1 - This peripheral is write protected. */ /*@{*/ #define BP_AIPS_PACRB_WP2 (21U) /*!< Bit position for AIPS_PACRB_WP2. */ #define BM_AIPS_PACRB_WP2 (0x00200000U) /*!< Bit mask for AIPS_PACRB_WP2. */ #define BS_AIPS_PACRB_WP2 (1U) /*!< Bit field size in bits for AIPS_PACRB_WP2. */ /*! @brief Read current value of the AIPS_PACRB_WP2 field. */ #define BR_AIPS_PACRB_WP2(x) (BITBAND_ACCESS32(HW_AIPS_PACRB_ADDR(x), BP_AIPS_PACRB_WP2)) /*! @brief Format value for bitfield AIPS_PACRB_WP2. */ #define BF_AIPS_PACRB_WP2(v) ((uint32_t)((uint32_t)(v) << BP_AIPS_PACRB_WP2) & BM_AIPS_PACRB_WP2) /*! @brief Set the WP2 field to a new value. */ #define BW_AIPS_PACRB_WP2(x, v) (BITBAND_ACCESS32(HW_AIPS_PACRB_ADDR(x), BP_AIPS_PACRB_WP2) = (v)) /*@}*/ /*! * @name Register AIPS_PACRB, field SP2[22] (RW) * * Determines whether the peripheral requires supervisor privilege level for * accesses. When this field is set, the master privilege level must indicate the * supervisor access attribute, and the MPRx[MPLn] control field for the master * must be set. If not, access terminates with an error response and no peripheral * access initiates. * * Values: * - 0 - This peripheral does not require supervisor privilege level for * accesses. * - 1 - This peripheral requires supervisor privilege level for accesses. */ /*@{*/ #define BP_AIPS_PACRB_SP2 (22U) /*!< Bit position for AIPS_PACRB_SP2. */ #define BM_AIPS_PACRB_SP2 (0x00400000U) /*!< Bit mask for AIPS_PACRB_SP2. */ #define BS_AIPS_PACRB_SP2 (1U) /*!< Bit field size in bits for AIPS_PACRB_SP2. */ /*! @brief Read current value of the AIPS_PACRB_SP2 field. */ #define BR_AIPS_PACRB_SP2(x) (BITBAND_ACCESS32(HW_AIPS_PACRB_ADDR(x), BP_AIPS_PACRB_SP2)) /*! @brief Format value for bitfield AIPS_PACRB_SP2. */ #define BF_AIPS_PACRB_SP2(v) ((uint32_t)((uint32_t)(v) << BP_AIPS_PACRB_SP2) & BM_AIPS_PACRB_SP2) /*! @brief Set the SP2 field to a new value. */ #define BW_AIPS_PACRB_SP2(x, v) (BITBAND_ACCESS32(HW_AIPS_PACRB_ADDR(x), BP_AIPS_PACRB_SP2) = (v)) /*@}*/ /*! * @name Register AIPS_PACRB, field TP1[24] (RW) * * Determines whether the peripheral allows accesses from an untrusted master. * When this bit is set and an access is attempted by an untrusted master, the * access terminates with an error response and no peripheral access initiates. * * Values: * - 0 - Accesses from an untrusted master are allowed. * - 1 - Accesses from an untrusted master are not allowed. */ /*@{*/ #define BP_AIPS_PACRB_TP1 (24U) /*!< Bit position for AIPS_PACRB_TP1. */ #define BM_AIPS_PACRB_TP1 (0x01000000U) /*!< Bit mask for AIPS_PACRB_TP1. */ #define BS_AIPS_PACRB_TP1 (1U) /*!< Bit field size in bits for AIPS_PACRB_TP1. */ /*! @brief Read current value of the AIPS_PACRB_TP1 field. */ #define BR_AIPS_PACRB_TP1(x) (BITBAND_ACCESS32(HW_AIPS_PACRB_ADDR(x), BP_AIPS_PACRB_TP1)) /*! @brief Format value for bitfield AIPS_PACRB_TP1. */ #define BF_AIPS_PACRB_TP1(v) ((uint32_t)((uint32_t)(v) << BP_AIPS_PACRB_TP1) & BM_AIPS_PACRB_TP1) /*! @brief Set the TP1 field to a new value. */ #define BW_AIPS_PACRB_TP1(x, v) (BITBAND_ACCESS32(HW_AIPS_PACRB_ADDR(x), BP_AIPS_PACRB_TP1) = (v)) /*@}*/ /*! * @name Register AIPS_PACRB, field WP1[25] (RW) * * Determines whether the peripheral allows write accesses. When this field is * set and a write access is attempted, access terminates with an error response * and no peripheral access initiates. * * Values: * - 0 - This peripheral allows write accesses. * - 1 - This peripheral is write protected. */ /*@{*/ #define BP_AIPS_PACRB_WP1 (25U) /*!< Bit position for AIPS_PACRB_WP1. */ #define BM_AIPS_PACRB_WP1 (0x02000000U) /*!< Bit mask for AIPS_PACRB_WP1. */ #define BS_AIPS_PACRB_WP1 (1U) /*!< Bit field size in bits for AIPS_PACRB_WP1. */ /*! @brief Read current value of the AIPS_PACRB_WP1 field. */ #define BR_AIPS_PACRB_WP1(x) (BITBAND_ACCESS32(HW_AIPS_PACRB_ADDR(x), BP_AIPS_PACRB_WP1)) /*! @brief Format value for bitfield AIPS_PACRB_WP1. */ #define BF_AIPS_PACRB_WP1(v) ((uint32_t)((uint32_t)(v) << BP_AIPS_PACRB_WP1) & BM_AIPS_PACRB_WP1) /*! @brief Set the WP1 field to a new value. */ #define BW_AIPS_PACRB_WP1(x, v) (BITBAND_ACCESS32(HW_AIPS_PACRB_ADDR(x), BP_AIPS_PACRB_WP1) = (v)) /*@}*/ /*! * @name Register AIPS_PACRB, field SP1[26] (RW) * * Determines whether the peripheral requires supervisor privilege level for * accesses. When this field is set, the master privilege level must indicate the * supervisor access attribute, and the MPRx[MPLn] control field for the master * must be set. If not, access terminates with an error response and no peripheral * access initiates. * * Values: * - 0 - This peripheral does not require supervisor privilege level for * accesses. * - 1 - This peripheral requires supervisor privilege level for accesses. */ /*@{*/ #define BP_AIPS_PACRB_SP1 (26U) /*!< Bit position for AIPS_PACRB_SP1. */ #define BM_AIPS_PACRB_SP1 (0x04000000U) /*!< Bit mask for AIPS_PACRB_SP1. */ #define BS_AIPS_PACRB_SP1 (1U) /*!< Bit field size in bits for AIPS_PACRB_SP1. */ /*! @brief Read current value of the AIPS_PACRB_SP1 field. */ #define BR_AIPS_PACRB_SP1(x) (BITBAND_ACCESS32(HW_AIPS_PACRB_ADDR(x), BP_AIPS_PACRB_SP1)) /*! @brief Format value for bitfield AIPS_PACRB_SP1. */ #define BF_AIPS_PACRB_SP1(v) ((uint32_t)((uint32_t)(v) << BP_AIPS_PACRB_SP1) & BM_AIPS_PACRB_SP1) /*! @brief Set the SP1 field to a new value. */ #define BW_AIPS_PACRB_SP1(x, v) (BITBAND_ACCESS32(HW_AIPS_PACRB_ADDR(x), BP_AIPS_PACRB_SP1) = (v)) /*@}*/ /*! * @name Register AIPS_PACRB, field TP0[28] (RW) * * Determines whether the peripheral allows accesses from an untrusted master. * When this field is set and an access is attempted by an untrusted master, the * access terminates with an error response and no peripheral access initiates. * * Values: * - 0 - Accesses from an untrusted master are allowed. * - 1 - Accesses from an untrusted master are not allowed. */ /*@{*/ #define BP_AIPS_PACRB_TP0 (28U) /*!< Bit position for AIPS_PACRB_TP0. */ #define BM_AIPS_PACRB_TP0 (0x10000000U) /*!< Bit mask for AIPS_PACRB_TP0. */ #define BS_AIPS_PACRB_TP0 (1U) /*!< Bit field size in bits for AIPS_PACRB_TP0. */ /*! @brief Read current value of the AIPS_PACRB_TP0 field. */ #define BR_AIPS_PACRB_TP0(x) (BITBAND_ACCESS32(HW_AIPS_PACRB_ADDR(x), BP_AIPS_PACRB_TP0)) /*! @brief Format value for bitfield AIPS_PACRB_TP0. */ #define BF_AIPS_PACRB_TP0(v) ((uint32_t)((uint32_t)(v) << BP_AIPS_PACRB_TP0) & BM_AIPS_PACRB_TP0) /*! @brief Set the TP0 field to a new value. */ #define BW_AIPS_PACRB_TP0(x, v) (BITBAND_ACCESS32(HW_AIPS_PACRB_ADDR(x), BP_AIPS_PACRB_TP0) = (v)) /*@}*/ /*! * @name Register AIPS_PACRB, field WP0[29] (RW) * * Determines whether the peripheral allows write accesss. When this bit is set * and a write access is attempted, access terminates with an error response and * no peripheral access initiates. * * Values: * - 0 - This peripheral allows write accesses. * - 1 - This peripheral is write protected. */ /*@{*/ #define BP_AIPS_PACRB_WP0 (29U) /*!< Bit position for AIPS_PACRB_WP0. */ #define BM_AIPS_PACRB_WP0 (0x20000000U) /*!< Bit mask for AIPS_PACRB_WP0. */ #define BS_AIPS_PACRB_WP0 (1U) /*!< Bit field size in bits for AIPS_PACRB_WP0. */ /*! @brief Read current value of the AIPS_PACRB_WP0 field. */ #define BR_AIPS_PACRB_WP0(x) (BITBAND_ACCESS32(HW_AIPS_PACRB_ADDR(x), BP_AIPS_PACRB_WP0)) /*! @brief Format value for bitfield AIPS_PACRB_WP0. */ #define BF_AIPS_PACRB_WP0(v) ((uint32_t)((uint32_t)(v) << BP_AIPS_PACRB_WP0) & BM_AIPS_PACRB_WP0) /*! @brief Set the WP0 field to a new value. */ #define BW_AIPS_PACRB_WP0(x, v) (BITBAND_ACCESS32(HW_AIPS_PACRB_ADDR(x), BP_AIPS_PACRB_WP0) = (v)) /*@}*/ /*! * @name Register AIPS_PACRB, field SP0[30] (RW) * * Determines whether the peripheral requires supervisor privilege level for * accesses. When this field is set, the master privilege level must indicate the * supervisor access attribute, and the MPRx[MPLn] control field for the master * must be set. If not, access terminates with an error response and no peripheral * access initiates. * * Values: * - 0 - This peripheral does not require supervisor privilege level for * accesses. * - 1 - This peripheral requires supervisor privilege level for accesses. */ /*@{*/ #define BP_AIPS_PACRB_SP0 (30U) /*!< Bit position for AIPS_PACRB_SP0. */ #define BM_AIPS_PACRB_SP0 (0x40000000U) /*!< Bit mask for AIPS_PACRB_SP0. */ #define BS_AIPS_PACRB_SP0 (1U) /*!< Bit field size in bits for AIPS_PACRB_SP0. */ /*! @brief Read current value of the AIPS_PACRB_SP0 field. */ #define BR_AIPS_PACRB_SP0(x) (BITBAND_ACCESS32(HW_AIPS_PACRB_ADDR(x), BP_AIPS_PACRB_SP0)) /*! @brief Format value for bitfield AIPS_PACRB_SP0. */ #define BF_AIPS_PACRB_SP0(v) ((uint32_t)((uint32_t)(v) << BP_AIPS_PACRB_SP0) & BM_AIPS_PACRB_SP0) /*! @brief Set the SP0 field to a new value. */ #define BW_AIPS_PACRB_SP0(x, v) (BITBAND_ACCESS32(HW_AIPS_PACRB_ADDR(x), BP_AIPS_PACRB_SP0) = (v)) /*@}*/ /******************************************************************************* * HW_AIPS_PACRC - Peripheral Access Control Register ******************************************************************************/ /*! * @brief HW_AIPS_PACRC - Peripheral Access Control Register (RW) * * Reset value: 0x00000000U * * Each PACR register consists of eight 4-bit PACR fields. Each PACR field * defines the access levels for a particular peripheral. The mapping between a * peripheral and its PACR field is shown in the table below. The peripheral assignment * to each PACR is defined by the memory map slot that the peripheral is * assigned to. See this chip's memory map for the assignment of a particular * peripheral. The following table shows the location of each peripheral slot's PACR field * in the PACR registers. Offset Register [31:28] [27:24] [23:20] [19:16] [15:12] * [11:8] [7:4] [3:0] 0x20 PACRA PACR0 PACR1 PACR2 PACR3 PACR4 PACR5 PACR6 PACR7 * 0x24 PACRB PACR8 PACR9 PACR10 PACR11 PACR12 PACR13 PACR14 PACR15 0x28 PACRC * PACR16 PACR17 PACR18 PACR19 PACR20 PACR21 PACR22 PACR23 0x2C PACRD PACR24 * PACR25 PACR26 PACR27 PACR28 PACR29 PACR30 PACR31 0x30 Reserved 0x34 Reserved 0x38 * Reserved 0x3C Reserved 0x40 PACRE PACR32 PACR33 PACR34 PACR35 PACR36 PACR37 * PACR38 PACR39 0x44 PACRF PACR40 PACR41 PACR42 PACR43 PACR44 PACR45 PACR46 PACR47 * 0x48 PACRG PACR48 PACR49 PACR50 PACR51 PACR52 PACR53 PACR54 PACR55 0x4C PACRH * PACR56 PACR57 PACR58 PACR59 PACR60 PACR61 PACR62 PACR63 0x50 PACRI PACR64 * PACR65 PACR66 PACR67 PACR68 PACR69 PACR70 PACR71 0x54 PACRJ PACR72 PACR73 PACR74 * PACR75 PACR76 PACR77 PACR78 PACR79 0x58 PACRK PACR80 PACR81 PACR82 PACR83 * PACR84 PACR85 PACR86 PACR87 0x5C PACRL PACR88 PACR89 PACR90 PACR91 PACR92 PACR93 * PACR94 PACR95 0x60 PACRM PACR96 PACR97 PACR98 PACR99 PACR100 PACR101 PACR102 * PACR103 0x64 PACRN PACR104 PACR105 PACR106 PACR107 PACR108 PACR109 PACR110 * PACR111 0x68 PACRO PACR112 PACR113 PACR114 PACR115 PACR116 PACR117 PACR118 PACR119 * 0x6C PACRP PACR120 PACR121 PACR122 PACR123 PACR124 PACR125 PACR126 PACR127 0x80 * PACRU PACR GBL0 PACR GBL1 Reserved The register field descriptions for PACR * A-D, which control peripheral slots 0-31, are shown below. The following * section, PACRPeripheral Access Control Register , shows the register field * descriptions for PACR E-P. All PACR registers are identical. They are divided into two * sections because they occupy two non-contiguous address spaces. */ typedef union _hw_aips_pacrc { uint32_t U; struct _hw_aips_pacrc_bitfields { uint32_t TP7 : 1; /*!< [0] Trusted Protect */ uint32_t WP7 : 1; /*!< [1] Write Protect */ uint32_t SP7 : 1; /*!< [2] Supervisor Protect */ uint32_t RESERVED0 : 1; /*!< [3] */ uint32_t TP6 : 1; /*!< [4] Trusted Protect */ uint32_t WP6 : 1; /*!< [5] Write Protect */ uint32_t SP6 : 1; /*!< [6] Supervisor Protect */ uint32_t RESERVED1 : 1; /*!< [7] */ uint32_t TP5 : 1; /*!< [8] Trusted Protect */ uint32_t WP5 : 1; /*!< [9] Write Protect */ uint32_t SP5 : 1; /*!< [10] Supervisor Protect */ uint32_t RESERVED2 : 1; /*!< [11] */ uint32_t TP4 : 1; /*!< [12] Trusted Protect */ uint32_t WP4 : 1; /*!< [13] Write Protect */ uint32_t SP4 : 1; /*!< [14] Supervisor Protect */ uint32_t RESERVED3 : 1; /*!< [15] */ uint32_t TP3 : 1; /*!< [16] Trusted Protect */ uint32_t WP3 : 1; /*!< [17] Write Protect */ uint32_t SP3 : 1; /*!< [18] Supervisor Protect */ uint32_t RESERVED4 : 1; /*!< [19] */ uint32_t TP2 : 1; /*!< [20] Trusted Protect */ uint32_t WP2 : 1; /*!< [21] Write Protect */ uint32_t SP2 : 1; /*!< [22] Supervisor Protect */ uint32_t RESERVED5 : 1; /*!< [23] */ uint32_t TP1 : 1; /*!< [24] Trusted Protect */ uint32_t WP1 : 1; /*!< [25] Write Protect */ uint32_t SP1 : 1; /*!< [26] Supervisor Protect */ uint32_t RESERVED6 : 1; /*!< [27] */ uint32_t TP0 : 1; /*!< [28] Trusted Protect */ uint32_t WP0 : 1; /*!< [29] Write Protect */ uint32_t SP0 : 1; /*!< [30] Supervisor Protect */ uint32_t RESERVED7 : 1; /*!< [31] */ } B; } hw_aips_pacrc_t; /*! * @name Constants and macros for entire AIPS_PACRC register */ /*@{*/ #define HW_AIPS_PACRC_ADDR(x) ((x) + 0x28U) #define HW_AIPS_PACRC(x) (*(__IO hw_aips_pacrc_t *) HW_AIPS_PACRC_ADDR(x)) #define HW_AIPS_PACRC_RD(x) (HW_AIPS_PACRC(x).U) #define HW_AIPS_PACRC_WR(x, v) (HW_AIPS_PACRC(x).U = (v)) #define HW_AIPS_PACRC_SET(x, v) (HW_AIPS_PACRC_WR(x, HW_AIPS_PACRC_RD(x) | (v))) #define HW_AIPS_PACRC_CLR(x, v) (HW_AIPS_PACRC_WR(x, HW_AIPS_PACRC_RD(x) & ~(v))) #define HW_AIPS_PACRC_TOG(x, v) (HW_AIPS_PACRC_WR(x, HW_AIPS_PACRC_RD(x) ^ (v))) /*@}*/ /* * Constants & macros for individual AIPS_PACRC bitfields */ /*! * @name Register AIPS_PACRC, field TP7[0] (RW) * * Determines whether the peripheral allows accesses from an untrusted master. * When this field is set and an access is attempted by an untrusted master, the * access terminates with an error response and no peripheral access initiates. * * Values: * - 0 - Accesses from an untrusted master are allowed. * - 1 - Accesses from an untrusted master are not allowed. */ /*@{*/ #define BP_AIPS_PACRC_TP7 (0U) /*!< Bit position for AIPS_PACRC_TP7. */ #define BM_AIPS_PACRC_TP7 (0x00000001U) /*!< Bit mask for AIPS_PACRC_TP7. */ #define BS_AIPS_PACRC_TP7 (1U) /*!< Bit field size in bits for AIPS_PACRC_TP7. */ /*! @brief Read current value of the AIPS_PACRC_TP7 field. */ #define BR_AIPS_PACRC_TP7(x) (BITBAND_ACCESS32(HW_AIPS_PACRC_ADDR(x), BP_AIPS_PACRC_TP7)) /*! @brief Format value for bitfield AIPS_PACRC_TP7. */ #define BF_AIPS_PACRC_TP7(v) ((uint32_t)((uint32_t)(v) << BP_AIPS_PACRC_TP7) & BM_AIPS_PACRC_TP7) /*! @brief Set the TP7 field to a new value. */ #define BW_AIPS_PACRC_TP7(x, v) (BITBAND_ACCESS32(HW_AIPS_PACRC_ADDR(x), BP_AIPS_PACRC_TP7) = (v)) /*@}*/ /*! * @name Register AIPS_PACRC, field WP7[1] (RW) * * Determines whether the peripheral allows write accesses. When this field is * set and a write access is attempted, access terminates with an error response * and no peripheral access initiates. * * Values: * - 0 - This peripheral allows write accesses. * - 1 - This peripheral is write protected. */ /*@{*/ #define BP_AIPS_PACRC_WP7 (1U) /*!< Bit position for AIPS_PACRC_WP7. */ #define BM_AIPS_PACRC_WP7 (0x00000002U) /*!< Bit mask for AIPS_PACRC_WP7. */ #define BS_AIPS_PACRC_WP7 (1U) /*!< Bit field size in bits for AIPS_PACRC_WP7. */ /*! @brief Read current value of the AIPS_PACRC_WP7 field. */ #define BR_AIPS_PACRC_WP7(x) (BITBAND_ACCESS32(HW_AIPS_PACRC_ADDR(x), BP_AIPS_PACRC_WP7)) /*! @brief Format value for bitfield AIPS_PACRC_WP7. */ #define BF_AIPS_PACRC_WP7(v) ((uint32_t)((uint32_t)(v) << BP_AIPS_PACRC_WP7) & BM_AIPS_PACRC_WP7) /*! @brief Set the WP7 field to a new value. */ #define BW_AIPS_PACRC_WP7(x, v) (BITBAND_ACCESS32(HW_AIPS_PACRC_ADDR(x), BP_AIPS_PACRC_WP7) = (v)) /*@}*/ /*! * @name Register AIPS_PACRC, field SP7[2] (RW) * * Determines whether the peripheral requires supervisor privilege level for * accesses. When this field is set, the master privilege level must indicate the * supervisor access attribute, and the MPRx[MPLn] control field for the master * must be set. If not, access terminates with an error response and no peripheral * access initiates. * * Values: * - 0 - This peripheral does not require supervisor privilege level for * accesses. * - 1 - This peripheral requires supervisor privilege level for accesses. */ /*@{*/ #define BP_AIPS_PACRC_SP7 (2U) /*!< Bit position for AIPS_PACRC_SP7. */ #define BM_AIPS_PACRC_SP7 (0x00000004U) /*!< Bit mask for AIPS_PACRC_SP7. */ #define BS_AIPS_PACRC_SP7 (1U) /*!< Bit field size in bits for AIPS_PACRC_SP7. */ /*! @brief Read current value of the AIPS_PACRC_SP7 field. */ #define BR_AIPS_PACRC_SP7(x) (BITBAND_ACCESS32(HW_AIPS_PACRC_ADDR(x), BP_AIPS_PACRC_SP7)) /*! @brief Format value for bitfield AIPS_PACRC_SP7. */ #define BF_AIPS_PACRC_SP7(v) ((uint32_t)((uint32_t)(v) << BP_AIPS_PACRC_SP7) & BM_AIPS_PACRC_SP7) /*! @brief Set the SP7 field to a new value. */ #define BW_AIPS_PACRC_SP7(x, v) (BITBAND_ACCESS32(HW_AIPS_PACRC_ADDR(x), BP_AIPS_PACRC_SP7) = (v)) /*@}*/ /*! * @name Register AIPS_PACRC, field TP6[4] (RW) * * Determines whether the peripheral allows accesses from an untrusted master. * When this field is set and an access is attempted by an untrusted master, the * access terminates with an error response and no peripheral access initiates. * * Values: * - 0 - Accesses from an untrusted master are allowed. * - 1 - Accesses from an untrusted master are not allowed. */ /*@{*/ #define BP_AIPS_PACRC_TP6 (4U) /*!< Bit position for AIPS_PACRC_TP6. */ #define BM_AIPS_PACRC_TP6 (0x00000010U) /*!< Bit mask for AIPS_PACRC_TP6. */ #define BS_AIPS_PACRC_TP6 (1U) /*!< Bit field size in bits for AIPS_PACRC_TP6. */ /*! @brief Read current value of the AIPS_PACRC_TP6 field. */ #define BR_AIPS_PACRC_TP6(x) (BITBAND_ACCESS32(HW_AIPS_PACRC_ADDR(x), BP_AIPS_PACRC_TP6)) /*! @brief Format value for bitfield AIPS_PACRC_TP6. */ #define BF_AIPS_PACRC_TP6(v) ((uint32_t)((uint32_t)(v) << BP_AIPS_PACRC_TP6) & BM_AIPS_PACRC_TP6) /*! @brief Set the TP6 field to a new value. */ #define BW_AIPS_PACRC_TP6(x, v) (BITBAND_ACCESS32(HW_AIPS_PACRC_ADDR(x), BP_AIPS_PACRC_TP6) = (v)) /*@}*/ /*! * @name Register AIPS_PACRC, field WP6[5] (RW) * * Determines whether the peripheral allows write accesses. When this field is * set and a write access is attempted, access terminates with an error response * and no peripheral access initiates. * * Values: * - 0 - This peripheral allows write accesses. * - 1 - This peripheral is write protected. */ /*@{*/ #define BP_AIPS_PACRC_WP6 (5U) /*!< Bit position for AIPS_PACRC_WP6. */ #define BM_AIPS_PACRC_WP6 (0x00000020U) /*!< Bit mask for AIPS_PACRC_WP6. */ #define BS_AIPS_PACRC_WP6 (1U) /*!< Bit field size in bits for AIPS_PACRC_WP6. */ /*! @brief Read current value of the AIPS_PACRC_WP6 field. */ #define BR_AIPS_PACRC_WP6(x) (BITBAND_ACCESS32(HW_AIPS_PACRC_ADDR(x), BP_AIPS_PACRC_WP6)) /*! @brief Format value for bitfield AIPS_PACRC_WP6. */ #define BF_AIPS_PACRC_WP6(v) ((uint32_t)((uint32_t)(v) << BP_AIPS_PACRC_WP6) & BM_AIPS_PACRC_WP6) /*! @brief Set the WP6 field to a new value. */ #define BW_AIPS_PACRC_WP6(x, v) (BITBAND_ACCESS32(HW_AIPS_PACRC_ADDR(x), BP_AIPS_PACRC_WP6) = (v)) /*@}*/ /*! * @name Register AIPS_PACRC, field SP6[6] (RW) * * Determines whether the peripheral requires supervisor privilege level for * accesses. When this field is set, the master privilege level must indicate the * supervisor access attribute, and the MPRx[MPLn] control field for the master * must be set. If not, access terminates with an error response and no peripheral * access initiates. * * Values: * - 0 - This peripheral does not require supervisor privilege level for * accesses. * - 1 - This peripheral requires supervisor privilege level for accesses. */ /*@{*/ #define BP_AIPS_PACRC_SP6 (6U) /*!< Bit position for AIPS_PACRC_SP6. */ #define BM_AIPS_PACRC_SP6 (0x00000040U) /*!< Bit mask for AIPS_PACRC_SP6. */ #define BS_AIPS_PACRC_SP6 (1U) /*!< Bit field size in bits for AIPS_PACRC_SP6. */ /*! @brief Read current value of the AIPS_PACRC_SP6 field. */ #define BR_AIPS_PACRC_SP6(x) (BITBAND_ACCESS32(HW_AIPS_PACRC_ADDR(x), BP_AIPS_PACRC_SP6)) /*! @brief Format value for bitfield AIPS_PACRC_SP6. */ #define BF_AIPS_PACRC_SP6(v) ((uint32_t)((uint32_t)(v) << BP_AIPS_PACRC_SP6) & BM_AIPS_PACRC_SP6) /*! @brief Set the SP6 field to a new value. */ #define BW_AIPS_PACRC_SP6(x, v) (BITBAND_ACCESS32(HW_AIPS_PACRC_ADDR(x), BP_AIPS_PACRC_SP6) = (v)) /*@}*/ /*! * @name Register AIPS_PACRC, field TP5[8] (RW) * * Determines whether the peripheral allows accesses from an untrusted master. * When this field is set and an access is attempted by an untrusted master, the * access terminates with an error response and no peripheral access initiates. * * Values: * - 0 - Accesses from an untrusted master are allowed. * - 1 - Accesses from an untrusted master are not allowed. */ /*@{*/ #define BP_AIPS_PACRC_TP5 (8U) /*!< Bit position for AIPS_PACRC_TP5. */ #define BM_AIPS_PACRC_TP5 (0x00000100U) /*!< Bit mask for AIPS_PACRC_TP5. */ #define BS_AIPS_PACRC_TP5 (1U) /*!< Bit field size in bits for AIPS_PACRC_TP5. */ /*! @brief Read current value of the AIPS_PACRC_TP5 field. */ #define BR_AIPS_PACRC_TP5(x) (BITBAND_ACCESS32(HW_AIPS_PACRC_ADDR(x), BP_AIPS_PACRC_TP5)) /*! @brief Format value for bitfield AIPS_PACRC_TP5. */ #define BF_AIPS_PACRC_TP5(v) ((uint32_t)((uint32_t)(v) << BP_AIPS_PACRC_TP5) & BM_AIPS_PACRC_TP5) /*! @brief Set the TP5 field to a new value. */ #define BW_AIPS_PACRC_TP5(x, v) (BITBAND_ACCESS32(HW_AIPS_PACRC_ADDR(x), BP_AIPS_PACRC_TP5) = (v)) /*@}*/ /*! * @name Register AIPS_PACRC, field WP5[9] (RW) * * Determines whether the peripheral allows write accesses. When this field is * set and a write access is attempted, access terminates with an error response * and no peripheral access initiates. * * Values: * - 0 - This peripheral allows write accesses. * - 1 - This peripheral is write protected. */ /*@{*/ #define BP_AIPS_PACRC_WP5 (9U) /*!< Bit position for AIPS_PACRC_WP5. */ #define BM_AIPS_PACRC_WP5 (0x00000200U) /*!< Bit mask for AIPS_PACRC_WP5. */ #define BS_AIPS_PACRC_WP5 (1U) /*!< Bit field size in bits for AIPS_PACRC_WP5. */ /*! @brief Read current value of the AIPS_PACRC_WP5 field. */ #define BR_AIPS_PACRC_WP5(x) (BITBAND_ACCESS32(HW_AIPS_PACRC_ADDR(x), BP_AIPS_PACRC_WP5)) /*! @brief Format value for bitfield AIPS_PACRC_WP5. */ #define BF_AIPS_PACRC_WP5(v) ((uint32_t)((uint32_t)(v) << BP_AIPS_PACRC_WP5) & BM_AIPS_PACRC_WP5) /*! @brief Set the WP5 field to a new value. */ #define BW_AIPS_PACRC_WP5(x, v) (BITBAND_ACCESS32(HW_AIPS_PACRC_ADDR(x), BP_AIPS_PACRC_WP5) = (v)) /*@}*/ /*! * @name Register AIPS_PACRC, field SP5[10] (RW) * * Determines whether the peripheral requires supervisor privilege level for * accesses. When this field is set, the master privilege level must indicate the * supervisor access attribute, and the MPRx[MPLn] control field for the master * must be set. If not, access terminates with an error response and no peripheral * access initiates. * * Values: * - 0 - This peripheral does not require supervisor privilege level for * accesses. * - 1 - This peripheral requires supervisor privilege level for accesses. */ /*@{*/ #define BP_AIPS_PACRC_SP5 (10U) /*!< Bit position for AIPS_PACRC_SP5. */ #define BM_AIPS_PACRC_SP5 (0x00000400U) /*!< Bit mask for AIPS_PACRC_SP5. */ #define BS_AIPS_PACRC_SP5 (1U) /*!< Bit field size in bits for AIPS_PACRC_SP5. */ /*! @brief Read current value of the AIPS_PACRC_SP5 field. */ #define BR_AIPS_PACRC_SP5(x) (BITBAND_ACCESS32(HW_AIPS_PACRC_ADDR(x), BP_AIPS_PACRC_SP5)) /*! @brief Format value for bitfield AIPS_PACRC_SP5. */ #define BF_AIPS_PACRC_SP5(v) ((uint32_t)((uint32_t)(v) << BP_AIPS_PACRC_SP5) & BM_AIPS_PACRC_SP5) /*! @brief Set the SP5 field to a new value. */ #define BW_AIPS_PACRC_SP5(x, v) (BITBAND_ACCESS32(HW_AIPS_PACRC_ADDR(x), BP_AIPS_PACRC_SP5) = (v)) /*@}*/ /*! * @name Register AIPS_PACRC, field TP4[12] (RW) * * Determines whether the peripheral allows accesses from an untrusted master. * When this field is set and an access is attempted by an untrusted master, the * access terminates with an error response and no peripheral access initiates. * * Values: * - 0 - Accesses from an untrusted master are allowed. * - 1 - Accesses from an untrusted master are not allowed. */ /*@{*/ #define BP_AIPS_PACRC_TP4 (12U) /*!< Bit position for AIPS_PACRC_TP4. */ #define BM_AIPS_PACRC_TP4 (0x00001000U) /*!< Bit mask for AIPS_PACRC_TP4. */ #define BS_AIPS_PACRC_TP4 (1U) /*!< Bit field size in bits for AIPS_PACRC_TP4. */ /*! @brief Read current value of the AIPS_PACRC_TP4 field. */ #define BR_AIPS_PACRC_TP4(x) (BITBAND_ACCESS32(HW_AIPS_PACRC_ADDR(x), BP_AIPS_PACRC_TP4)) /*! @brief Format value for bitfield AIPS_PACRC_TP4. */ #define BF_AIPS_PACRC_TP4(v) ((uint32_t)((uint32_t)(v) << BP_AIPS_PACRC_TP4) & BM_AIPS_PACRC_TP4) /*! @brief Set the TP4 field to a new value. */ #define BW_AIPS_PACRC_TP4(x, v) (BITBAND_ACCESS32(HW_AIPS_PACRC_ADDR(x), BP_AIPS_PACRC_TP4) = (v)) /*@}*/ /*! * @name Register AIPS_PACRC, field WP4[13] (RW) * * Determines whether the peripheral allows write accesss. When this bit is set * and a write access is attempted, access terminates with an error response and * no peripheral access initiates. * * Values: * - 0 - This peripheral allows write accesses. * - 1 - This peripheral is write protected. */ /*@{*/ #define BP_AIPS_PACRC_WP4 (13U) /*!< Bit position for AIPS_PACRC_WP4. */ #define BM_AIPS_PACRC_WP4 (0x00002000U) /*!< Bit mask for AIPS_PACRC_WP4. */ #define BS_AIPS_PACRC_WP4 (1U) /*!< Bit field size in bits for AIPS_PACRC_WP4. */ /*! @brief Read current value of the AIPS_PACRC_WP4 field. */ #define BR_AIPS_PACRC_WP4(x) (BITBAND_ACCESS32(HW_AIPS_PACRC_ADDR(x), BP_AIPS_PACRC_WP4)) /*! @brief Format value for bitfield AIPS_PACRC_WP4. */ #define BF_AIPS_PACRC_WP4(v) ((uint32_t)((uint32_t)(v) << BP_AIPS_PACRC_WP4) & BM_AIPS_PACRC_WP4) /*! @brief Set the WP4 field to a new value. */ #define BW_AIPS_PACRC_WP4(x, v) (BITBAND_ACCESS32(HW_AIPS_PACRC_ADDR(x), BP_AIPS_PACRC_WP4) = (v)) /*@}*/ /*! * @name Register AIPS_PACRC, field SP4[14] (RW) * * Determines whether the peripheral requires supervisor privilege level for * accesses. When this field is set, the master privilege level must indicate the * supervisor access attribute, and the MPRx[MPLn] control field for the master * must be set. If not, access terminates with an error response and no peripheral * access initiates. * * Values: * - 0 - This peripheral does not require supervisor privilege level for * accesses. * - 1 - This peripheral requires supervisor privilege level for accesses. */ /*@{*/ #define BP_AIPS_PACRC_SP4 (14U) /*!< Bit position for AIPS_PACRC_SP4. */ #define BM_AIPS_PACRC_SP4 (0x00004000U) /*!< Bit mask for AIPS_PACRC_SP4. */ #define BS_AIPS_PACRC_SP4 (1U) /*!< Bit field size in bits for AIPS_PACRC_SP4. */ /*! @brief Read current value of the AIPS_PACRC_SP4 field. */ #define BR_AIPS_PACRC_SP4(x) (BITBAND_ACCESS32(HW_AIPS_PACRC_ADDR(x), BP_AIPS_PACRC_SP4)) /*! @brief Format value for bitfield AIPS_PACRC_SP4. */ #define BF_AIPS_PACRC_SP4(v) ((uint32_t)((uint32_t)(v) << BP_AIPS_PACRC_SP4) & BM_AIPS_PACRC_SP4) /*! @brief Set the SP4 field to a new value. */ #define BW_AIPS_PACRC_SP4(x, v) (BITBAND_ACCESS32(HW_AIPS_PACRC_ADDR(x), BP_AIPS_PACRC_SP4) = (v)) /*@}*/ /*! * @name Register AIPS_PACRC, field TP3[16] (RW) * * Determines whether the peripheral allows accesses from an untrusted master. * When this bit is set and an access is attempted by an untrusted master, the * access terminates with an error response and no peripheral access initiates. * * Values: * - 0 - Accesses from an untrusted master are allowed. * - 1 - Accesses from an untrusted master are not allowed. */ /*@{*/ #define BP_AIPS_PACRC_TP3 (16U) /*!< Bit position for AIPS_PACRC_TP3. */ #define BM_AIPS_PACRC_TP3 (0x00010000U) /*!< Bit mask for AIPS_PACRC_TP3. */ #define BS_AIPS_PACRC_TP3 (1U) /*!< Bit field size in bits for AIPS_PACRC_TP3. */ /*! @brief Read current value of the AIPS_PACRC_TP3 field. */ #define BR_AIPS_PACRC_TP3(x) (BITBAND_ACCESS32(HW_AIPS_PACRC_ADDR(x), BP_AIPS_PACRC_TP3)) /*! @brief Format value for bitfield AIPS_PACRC_TP3. */ #define BF_AIPS_PACRC_TP3(v) ((uint32_t)((uint32_t)(v) << BP_AIPS_PACRC_TP3) & BM_AIPS_PACRC_TP3) /*! @brief Set the TP3 field to a new value. */ #define BW_AIPS_PACRC_TP3(x, v) (BITBAND_ACCESS32(HW_AIPS_PACRC_ADDR(x), BP_AIPS_PACRC_TP3) = (v)) /*@}*/ /*! * @name Register AIPS_PACRC, field WP3[17] (RW) * * Determines whether the peripheral allows write accesses. When this field is * set and a write access is attempted, access terminates with an error response * and no peripheral access initiates. * * Values: * - 0 - This peripheral allows write accesses. * - 1 - This peripheral is write protected. */ /*@{*/ #define BP_AIPS_PACRC_WP3 (17U) /*!< Bit position for AIPS_PACRC_WP3. */ #define BM_AIPS_PACRC_WP3 (0x00020000U) /*!< Bit mask for AIPS_PACRC_WP3. */ #define BS_AIPS_PACRC_WP3 (1U) /*!< Bit field size in bits for AIPS_PACRC_WP3. */ /*! @brief Read current value of the AIPS_PACRC_WP3 field. */ #define BR_AIPS_PACRC_WP3(x) (BITBAND_ACCESS32(HW_AIPS_PACRC_ADDR(x), BP_AIPS_PACRC_WP3)) /*! @brief Format value for bitfield AIPS_PACRC_WP3. */ #define BF_AIPS_PACRC_WP3(v) ((uint32_t)((uint32_t)(v) << BP_AIPS_PACRC_WP3) & BM_AIPS_PACRC_WP3) /*! @brief Set the WP3 field to a new value. */ #define BW_AIPS_PACRC_WP3(x, v) (BITBAND_ACCESS32(HW_AIPS_PACRC_ADDR(x), BP_AIPS_PACRC_WP3) = (v)) /*@}*/ /*! * @name Register AIPS_PACRC, field SP3[18] (RW) * * Determines whether the peripheral requires supervisor privilege level for * access. When this bit is set, the master privilege level must indicate the * supervisor access attribute, and the MPRx[MPLn] control bit for the master must be * set. If not, access terminates with an error response and no peripheral access * initiates. * * Values: * - 0 - This peripheral does not require supervisor privilege level for * accesses. * - 1 - This peripheral requires supervisor privilege level for accesses. */ /*@{*/ #define BP_AIPS_PACRC_SP3 (18U) /*!< Bit position for AIPS_PACRC_SP3. */ #define BM_AIPS_PACRC_SP3 (0x00040000U) /*!< Bit mask for AIPS_PACRC_SP3. */ #define BS_AIPS_PACRC_SP3 (1U) /*!< Bit field size in bits for AIPS_PACRC_SP3. */ /*! @brief Read current value of the AIPS_PACRC_SP3 field. */ #define BR_AIPS_PACRC_SP3(x) (BITBAND_ACCESS32(HW_AIPS_PACRC_ADDR(x), BP_AIPS_PACRC_SP3)) /*! @brief Format value for bitfield AIPS_PACRC_SP3. */ #define BF_AIPS_PACRC_SP3(v) ((uint32_t)((uint32_t)(v) << BP_AIPS_PACRC_SP3) & BM_AIPS_PACRC_SP3) /*! @brief Set the SP3 field to a new value. */ #define BW_AIPS_PACRC_SP3(x, v) (BITBAND_ACCESS32(HW_AIPS_PACRC_ADDR(x), BP_AIPS_PACRC_SP3) = (v)) /*@}*/ /*! * @name Register AIPS_PACRC, field TP2[20] (RW) * * Determines whether the peripheral allows accesses from an untrusted master. * When this field is set and an access is attempted by an untrusted master, the * access terminates with an error response and no peripheral access initiates. * * Values: * - 0 - Accesses from an untrusted master are allowed. * - 1 - Accesses from an untrusted master are not allowed. */ /*@{*/ #define BP_AIPS_PACRC_TP2 (20U) /*!< Bit position for AIPS_PACRC_TP2. */ #define BM_AIPS_PACRC_TP2 (0x00100000U) /*!< Bit mask for AIPS_PACRC_TP2. */ #define BS_AIPS_PACRC_TP2 (1U) /*!< Bit field size in bits for AIPS_PACRC_TP2. */ /*! @brief Read current value of the AIPS_PACRC_TP2 field. */ #define BR_AIPS_PACRC_TP2(x) (BITBAND_ACCESS32(HW_AIPS_PACRC_ADDR(x), BP_AIPS_PACRC_TP2)) /*! @brief Format value for bitfield AIPS_PACRC_TP2. */ #define BF_AIPS_PACRC_TP2(v) ((uint32_t)((uint32_t)(v) << BP_AIPS_PACRC_TP2) & BM_AIPS_PACRC_TP2) /*! @brief Set the TP2 field to a new value. */ #define BW_AIPS_PACRC_TP2(x, v) (BITBAND_ACCESS32(HW_AIPS_PACRC_ADDR(x), BP_AIPS_PACRC_TP2) = (v)) /*@}*/ /*! * @name Register AIPS_PACRC, field WP2[21] (RW) * * Determines whether the peripheral allows write accesss. When this bit is set * and a write access is attempted, access terminates with an error response and * no peripheral access initiates. * * Values: * - 0 - This peripheral allows write accesses. * - 1 - This peripheral is write protected. */ /*@{*/ #define BP_AIPS_PACRC_WP2 (21U) /*!< Bit position for AIPS_PACRC_WP2. */ #define BM_AIPS_PACRC_WP2 (0x00200000U) /*!< Bit mask for AIPS_PACRC_WP2. */ #define BS_AIPS_PACRC_WP2 (1U) /*!< Bit field size in bits for AIPS_PACRC_WP2. */ /*! @brief Read current value of the AIPS_PACRC_WP2 field. */ #define BR_AIPS_PACRC_WP2(x) (BITBAND_ACCESS32(HW_AIPS_PACRC_ADDR(x), BP_AIPS_PACRC_WP2)) /*! @brief Format value for bitfield AIPS_PACRC_WP2. */ #define BF_AIPS_PACRC_WP2(v) ((uint32_t)((uint32_t)(v) << BP_AIPS_PACRC_WP2) & BM_AIPS_PACRC_WP2) /*! @brief Set the WP2 field to a new value. */ #define BW_AIPS_PACRC_WP2(x, v) (BITBAND_ACCESS32(HW_AIPS_PACRC_ADDR(x), BP_AIPS_PACRC_WP2) = (v)) /*@}*/ /*! * @name Register AIPS_PACRC, field SP2[22] (RW) * * Determines whether the peripheral requires supervisor privilege level for * accesses. When this field is set, the master privilege level must indicate the * supervisor access attribute, and the MPRx[MPLn] control field for the master * must be set. If not, access terminates with an error response and no peripheral * access initiates. * * Values: * - 0 - This peripheral does not require supervisor privilege level for * accesses. * - 1 - This peripheral requires supervisor privilege level for accesses. */ /*@{*/ #define BP_AIPS_PACRC_SP2 (22U) /*!< Bit position for AIPS_PACRC_SP2. */ #define BM_AIPS_PACRC_SP2 (0x00400000U) /*!< Bit mask for AIPS_PACRC_SP2. */ #define BS_AIPS_PACRC_SP2 (1U) /*!< Bit field size in bits for AIPS_PACRC_SP2. */ /*! @brief Read current value of the AIPS_PACRC_SP2 field. */ #define BR_AIPS_PACRC_SP2(x) (BITBAND_ACCESS32(HW_AIPS_PACRC_ADDR(x), BP_AIPS_PACRC_SP2)) /*! @brief Format value for bitfield AIPS_PACRC_SP2. */ #define BF_AIPS_PACRC_SP2(v) ((uint32_t)((uint32_t)(v) << BP_AIPS_PACRC_SP2) & BM_AIPS_PACRC_SP2) /*! @brief Set the SP2 field to a new value. */ #define BW_AIPS_PACRC_SP2(x, v) (BITBAND_ACCESS32(HW_AIPS_PACRC_ADDR(x), BP_AIPS_PACRC_SP2) = (v)) /*@}*/ /*! * @name Register AIPS_PACRC, field TP1[24] (RW) * * Determines whether the peripheral allows accesses from an untrusted master. * When this bit is set and an access is attempted by an untrusted master, the * access terminates with an error response and no peripheral access initiates. * * Values: * - 0 - Accesses from an untrusted master are allowed. * - 1 - Accesses from an untrusted master are not allowed. */ /*@{*/ #define BP_AIPS_PACRC_TP1 (24U) /*!< Bit position for AIPS_PACRC_TP1. */ #define BM_AIPS_PACRC_TP1 (0x01000000U) /*!< Bit mask for AIPS_PACRC_TP1. */ #define BS_AIPS_PACRC_TP1 (1U) /*!< Bit field size in bits for AIPS_PACRC_TP1. */ /*! @brief Read current value of the AIPS_PACRC_TP1 field. */ #define BR_AIPS_PACRC_TP1(x) (BITBAND_ACCESS32(HW_AIPS_PACRC_ADDR(x), BP_AIPS_PACRC_TP1)) /*! @brief Format value for bitfield AIPS_PACRC_TP1. */ #define BF_AIPS_PACRC_TP1(v) ((uint32_t)((uint32_t)(v) << BP_AIPS_PACRC_TP1) & BM_AIPS_PACRC_TP1) /*! @brief Set the TP1 field to a new value. */ #define BW_AIPS_PACRC_TP1(x, v) (BITBAND_ACCESS32(HW_AIPS_PACRC_ADDR(x), BP_AIPS_PACRC_TP1) = (v)) /*@}*/ /*! * @name Register AIPS_PACRC, field WP1[25] (RW) * * Determines whether the peripheral allows write accesses. When this field is * set and a write access is attempted, access terminates with an error response * and no peripheral access initiates. * * Values: * - 0 - This peripheral allows write accesses. * - 1 - This peripheral is write protected. */ /*@{*/ #define BP_AIPS_PACRC_WP1 (25U) /*!< Bit position for AIPS_PACRC_WP1. */ #define BM_AIPS_PACRC_WP1 (0x02000000U) /*!< Bit mask for AIPS_PACRC_WP1. */ #define BS_AIPS_PACRC_WP1 (1U) /*!< Bit field size in bits for AIPS_PACRC_WP1. */ /*! @brief Read current value of the AIPS_PACRC_WP1 field. */ #define BR_AIPS_PACRC_WP1(x) (BITBAND_ACCESS32(HW_AIPS_PACRC_ADDR(x), BP_AIPS_PACRC_WP1)) /*! @brief Format value for bitfield AIPS_PACRC_WP1. */ #define BF_AIPS_PACRC_WP1(v) ((uint32_t)((uint32_t)(v) << BP_AIPS_PACRC_WP1) & BM_AIPS_PACRC_WP1) /*! @brief Set the WP1 field to a new value. */ #define BW_AIPS_PACRC_WP1(x, v) (BITBAND_ACCESS32(HW_AIPS_PACRC_ADDR(x), BP_AIPS_PACRC_WP1) = (v)) /*@}*/ /*! * @name Register AIPS_PACRC, field SP1[26] (RW) * * Determines whether the peripheral requires supervisor privilege level for * accesses. When this field is set, the master privilege level must indicate the * supervisor access attribute, and the MPRx[MPLn] control field for the master * must be set. If not, access terminates with an error response and no peripheral * access initiates. * * Values: * - 0 - This peripheral does not require supervisor privilege level for * accesses. * - 1 - This peripheral requires supervisor privilege level for accesses. */ /*@{*/ #define BP_AIPS_PACRC_SP1 (26U) /*!< Bit position for AIPS_PACRC_SP1. */ #define BM_AIPS_PACRC_SP1 (0x04000000U) /*!< Bit mask for AIPS_PACRC_SP1. */ #define BS_AIPS_PACRC_SP1 (1U) /*!< Bit field size in bits for AIPS_PACRC_SP1. */ /*! @brief Read current value of the AIPS_PACRC_SP1 field. */ #define BR_AIPS_PACRC_SP1(x) (BITBAND_ACCESS32(HW_AIPS_PACRC_ADDR(x), BP_AIPS_PACRC_SP1)) /*! @brief Format value for bitfield AIPS_PACRC_SP1. */ #define BF_AIPS_PACRC_SP1(v) ((uint32_t)((uint32_t)(v) << BP_AIPS_PACRC_SP1) & BM_AIPS_PACRC_SP1) /*! @brief Set the SP1 field to a new value. */ #define BW_AIPS_PACRC_SP1(x, v) (BITBAND_ACCESS32(HW_AIPS_PACRC_ADDR(x), BP_AIPS_PACRC_SP1) = (v)) /*@}*/ /*! * @name Register AIPS_PACRC, field TP0[28] (RW) * * Determines whether the peripheral allows accesses from an untrusted master. * When this field is set and an access is attempted by an untrusted master, the * access terminates with an error response and no peripheral access initiates. * * Values: * - 0 - Accesses from an untrusted master are allowed. * - 1 - Accesses from an untrusted master are not allowed. */ /*@{*/ #define BP_AIPS_PACRC_TP0 (28U) /*!< Bit position for AIPS_PACRC_TP0. */ #define BM_AIPS_PACRC_TP0 (0x10000000U) /*!< Bit mask for AIPS_PACRC_TP0. */ #define BS_AIPS_PACRC_TP0 (1U) /*!< Bit field size in bits for AIPS_PACRC_TP0. */ /*! @brief Read current value of the AIPS_PACRC_TP0 field. */ #define BR_AIPS_PACRC_TP0(x) (BITBAND_ACCESS32(HW_AIPS_PACRC_ADDR(x), BP_AIPS_PACRC_TP0)) /*! @brief Format value for bitfield AIPS_PACRC_TP0. */ #define BF_AIPS_PACRC_TP0(v) ((uint32_t)((uint32_t)(v) << BP_AIPS_PACRC_TP0) & BM_AIPS_PACRC_TP0) /*! @brief Set the TP0 field to a new value. */ #define BW_AIPS_PACRC_TP0(x, v) (BITBAND_ACCESS32(HW_AIPS_PACRC_ADDR(x), BP_AIPS_PACRC_TP0) = (v)) /*@}*/ /*! * @name Register AIPS_PACRC, field WP0[29] (RW) * * Determines whether the peripheral allows write accesss. When this bit is set * and a write access is attempted, access terminates with an error response and * no peripheral access initiates. * * Values: * - 0 - This peripheral allows write accesses. * - 1 - This peripheral is write protected. */ /*@{*/ #define BP_AIPS_PACRC_WP0 (29U) /*!< Bit position for AIPS_PACRC_WP0. */ #define BM_AIPS_PACRC_WP0 (0x20000000U) /*!< Bit mask for AIPS_PACRC_WP0. */ #define BS_AIPS_PACRC_WP0 (1U) /*!< Bit field size in bits for AIPS_PACRC_WP0. */ /*! @brief Read current value of the AIPS_PACRC_WP0 field. */ #define BR_AIPS_PACRC_WP0(x) (BITBAND_ACCESS32(HW_AIPS_PACRC_ADDR(x), BP_AIPS_PACRC_WP0)) /*! @brief Format value for bitfield AIPS_PACRC_WP0. */ #define BF_AIPS_PACRC_WP0(v) ((uint32_t)((uint32_t)(v) << BP_AIPS_PACRC_WP0) & BM_AIPS_PACRC_WP0) /*! @brief Set the WP0 field to a new value. */ #define BW_AIPS_PACRC_WP0(x, v) (BITBAND_ACCESS32(HW_AIPS_PACRC_ADDR(x), BP_AIPS_PACRC_WP0) = (v)) /*@}*/ /*! * @name Register AIPS_PACRC, field SP0[30] (RW) * * Determines whether the peripheral requires supervisor privilege level for * accesses. When this field is set, the master privilege level must indicate the * supervisor access attribute, and the MPRx[MPLn] control field for the master * must be set. If not, access terminates with an error response and no peripheral * access initiates. * * Values: * - 0 - This peripheral does not require supervisor privilege level for * accesses. * - 1 - This peripheral requires supervisor privilege level for accesses. */ /*@{*/ #define BP_AIPS_PACRC_SP0 (30U) /*!< Bit position for AIPS_PACRC_SP0. */ #define BM_AIPS_PACRC_SP0 (0x40000000U) /*!< Bit mask for AIPS_PACRC_SP0. */ #define BS_AIPS_PACRC_SP0 (1U) /*!< Bit field size in bits for AIPS_PACRC_SP0. */ /*! @brief Read current value of the AIPS_PACRC_SP0 field. */ #define BR_AIPS_PACRC_SP0(x) (BITBAND_ACCESS32(HW_AIPS_PACRC_ADDR(x), BP_AIPS_PACRC_SP0)) /*! @brief Format value for bitfield AIPS_PACRC_SP0. */ #define BF_AIPS_PACRC_SP0(v) ((uint32_t)((uint32_t)(v) << BP_AIPS_PACRC_SP0) & BM_AIPS_PACRC_SP0) /*! @brief Set the SP0 field to a new value. */ #define BW_AIPS_PACRC_SP0(x, v) (BITBAND_ACCESS32(HW_AIPS_PACRC_ADDR(x), BP_AIPS_PACRC_SP0) = (v)) /*@}*/ /******************************************************************************* * HW_AIPS_PACRD - Peripheral Access Control Register ******************************************************************************/ /*! * @brief HW_AIPS_PACRD - Peripheral Access Control Register (RW) * * Reset value: 0x00000004U * * Each PACR register consists of eight 4-bit PACR fields. Each PACR field * defines the access levels for a particular peripheral. The mapping between a * peripheral and its PACR field is shown in the table below. The peripheral assignment * to each PACR is defined by the memory map slot that the peripheral is * assigned to. See this chip's memory map for the assignment of a particular * peripheral. The following table shows the location of each peripheral slot's PACR field * in the PACR registers. Offset Register [31:28] [27:24] [23:20] [19:16] [15:12] * [11:8] [7:4] [3:0] 0x20 PACRA PACR0 PACR1 PACR2 PACR3 PACR4 PACR5 PACR6 PACR7 * 0x24 PACRB PACR8 PACR9 PACR10 PACR11 PACR12 PACR13 PACR14 PACR15 0x28 PACRC * PACR16 PACR17 PACR18 PACR19 PACR20 PACR21 PACR22 PACR23 0x2C PACRD PACR24 * PACR25 PACR26 PACR27 PACR28 PACR29 PACR30 PACR31 0x30 Reserved 0x34 Reserved 0x38 * Reserved 0x3C Reserved 0x40 PACRE PACR32 PACR33 PACR34 PACR35 PACR36 PACR37 * PACR38 PACR39 0x44 PACRF PACR40 PACR41 PACR42 PACR43 PACR44 PACR45 PACR46 PACR47 * 0x48 PACRG PACR48 PACR49 PACR50 PACR51 PACR52 PACR53 PACR54 PACR55 0x4C PACRH * PACR56 PACR57 PACR58 PACR59 PACR60 PACR61 PACR62 PACR63 0x50 PACRI PACR64 * PACR65 PACR66 PACR67 PACR68 PACR69 PACR70 PACR71 0x54 PACRJ PACR72 PACR73 PACR74 * PACR75 PACR76 PACR77 PACR78 PACR79 0x58 PACRK PACR80 PACR81 PACR82 PACR83 * PACR84 PACR85 PACR86 PACR87 0x5C PACRL PACR88 PACR89 PACR90 PACR91 PACR92 PACR93 * PACR94 PACR95 0x60 PACRM PACR96 PACR97 PACR98 PACR99 PACR100 PACR101 PACR102 * PACR103 0x64 PACRN PACR104 PACR105 PACR106 PACR107 PACR108 PACR109 PACR110 * PACR111 0x68 PACRO PACR112 PACR113 PACR114 PACR115 PACR116 PACR117 PACR118 PACR119 * 0x6C PACRP PACR120 PACR121 PACR122 PACR123 PACR124 PACR125 PACR126 PACR127 0x80 * PACRU PACR GBL0 PACR GBL1 Reserved The register field descriptions for PACR * A-D, which control peripheral slots 0-31, are shown below. The following * section, PACRPeripheral Access Control Register , shows the register field * descriptions for PACR E-P. All PACR registers are identical. They are divided into two * sections because they occupy two non-contiguous address spaces. */ typedef union _hw_aips_pacrd { uint32_t U; struct _hw_aips_pacrd_bitfields { uint32_t TP7 : 1; /*!< [0] Trusted Protect */ uint32_t WP7 : 1; /*!< [1] Write Protect */ uint32_t SP7 : 1; /*!< [2] Supervisor Protect */ uint32_t RESERVED0 : 1; /*!< [3] */ uint32_t TP6 : 1; /*!< [4] Trusted Protect */ uint32_t WP6 : 1; /*!< [5] Write Protect */ uint32_t SP6 : 1; /*!< [6] Supervisor Protect */ uint32_t RESERVED1 : 1; /*!< [7] */ uint32_t TP5 : 1; /*!< [8] Trusted Protect */ uint32_t WP5 : 1; /*!< [9] Write Protect */ uint32_t SP5 : 1; /*!< [10] Supervisor Protect */ uint32_t RESERVED2 : 1; /*!< [11] */ uint32_t TP4 : 1; /*!< [12] Trusted Protect */ uint32_t WP4 : 1; /*!< [13] Write Protect */ uint32_t SP4 : 1; /*!< [14] Supervisor Protect */ uint32_t RESERVED3 : 1; /*!< [15] */ uint32_t TP3 : 1; /*!< [16] Trusted Protect */ uint32_t WP3 : 1; /*!< [17] Write Protect */ uint32_t SP3 : 1; /*!< [18] Supervisor Protect */ uint32_t RESERVED4 : 1; /*!< [19] */ uint32_t TP2 : 1; /*!< [20] Trusted Protect */ uint32_t WP2 : 1; /*!< [21] Write Protect */ uint32_t SP2 : 1; /*!< [22] Supervisor Protect */ uint32_t RESERVED5 : 1; /*!< [23] */ uint32_t TP1 : 1; /*!< [24] Trusted Protect */ uint32_t WP1 : 1; /*!< [25] Write Protect */ uint32_t SP1 : 1; /*!< [26] Supervisor Protect */ uint32_t RESERVED6 : 1; /*!< [27] */ uint32_t TP0 : 1; /*!< [28] Trusted Protect */ uint32_t WP0 : 1; /*!< [29] Write Protect */ uint32_t SP0 : 1; /*!< [30] Supervisor Protect */ uint32_t RESERVED7 : 1; /*!< [31] */ } B; } hw_aips_pacrd_t; /*! * @name Constants and macros for entire AIPS_PACRD register */ /*@{*/ #define HW_AIPS_PACRD_ADDR(x) ((x) + 0x2CU) #define HW_AIPS_PACRD(x) (*(__IO hw_aips_pacrd_t *) HW_AIPS_PACRD_ADDR(x)) #define HW_AIPS_PACRD_RD(x) (HW_AIPS_PACRD(x).U) #define HW_AIPS_PACRD_WR(x, v) (HW_AIPS_PACRD(x).U = (v)) #define HW_AIPS_PACRD_SET(x, v) (HW_AIPS_PACRD_WR(x, HW_AIPS_PACRD_RD(x) | (v))) #define HW_AIPS_PACRD_CLR(x, v) (HW_AIPS_PACRD_WR(x, HW_AIPS_PACRD_RD(x) & ~(v))) #define HW_AIPS_PACRD_TOG(x, v) (HW_AIPS_PACRD_WR(x, HW_AIPS_PACRD_RD(x) ^ (v))) /*@}*/ /* * Constants & macros for individual AIPS_PACRD bitfields */ /*! * @name Register AIPS_PACRD, field TP7[0] (RW) * * Determines whether the peripheral allows accesses from an untrusted master. * When this field is set and an access is attempted by an untrusted master, the * access terminates with an error response and no peripheral access initiates. * * Values: * - 0 - Accesses from an untrusted master are allowed. * - 1 - Accesses from an untrusted master are not allowed. */ /*@{*/ #define BP_AIPS_PACRD_TP7 (0U) /*!< Bit position for AIPS_PACRD_TP7. */ #define BM_AIPS_PACRD_TP7 (0x00000001U) /*!< Bit mask for AIPS_PACRD_TP7. */ #define BS_AIPS_PACRD_TP7 (1U) /*!< Bit field size in bits for AIPS_PACRD_TP7. */ /*! @brief Read current value of the AIPS_PACRD_TP7 field. */ #define BR_AIPS_PACRD_TP7(x) (BITBAND_ACCESS32(HW_AIPS_PACRD_ADDR(x), BP_AIPS_PACRD_TP7)) /*! @brief Format value for bitfield AIPS_PACRD_TP7. */ #define BF_AIPS_PACRD_TP7(v) ((uint32_t)((uint32_t)(v) << BP_AIPS_PACRD_TP7) & BM_AIPS_PACRD_TP7) /*! @brief Set the TP7 field to a new value. */ #define BW_AIPS_PACRD_TP7(x, v) (BITBAND_ACCESS32(HW_AIPS_PACRD_ADDR(x), BP_AIPS_PACRD_TP7) = (v)) /*@}*/ /*! * @name Register AIPS_PACRD, field WP7[1] (RW) * * Determines whether the peripheral allows write accesses. When this field is * set and a write access is attempted, access terminates with an error response * and no peripheral access initiates. * * Values: * - 0 - This peripheral allows write accesses. * - 1 - This peripheral is write protected. */ /*@{*/ #define BP_AIPS_PACRD_WP7 (1U) /*!< Bit position for AIPS_PACRD_WP7. */ #define BM_AIPS_PACRD_WP7 (0x00000002U) /*!< Bit mask for AIPS_PACRD_WP7. */ #define BS_AIPS_PACRD_WP7 (1U) /*!< Bit field size in bits for AIPS_PACRD_WP7. */ /*! @brief Read current value of the AIPS_PACRD_WP7 field. */ #define BR_AIPS_PACRD_WP7(x) (BITBAND_ACCESS32(HW_AIPS_PACRD_ADDR(x), BP_AIPS_PACRD_WP7)) /*! @brief Format value for bitfield AIPS_PACRD_WP7. */ #define BF_AIPS_PACRD_WP7(v) ((uint32_t)((uint32_t)(v) << BP_AIPS_PACRD_WP7) & BM_AIPS_PACRD_WP7) /*! @brief Set the WP7 field to a new value. */ #define BW_AIPS_PACRD_WP7(x, v) (BITBAND_ACCESS32(HW_AIPS_PACRD_ADDR(x), BP_AIPS_PACRD_WP7) = (v)) /*@}*/ /*! * @name Register AIPS_PACRD, field SP7[2] (RW) * * Determines whether the peripheral requires supervisor privilege level for * accesses. When this field is set, the master privilege level must indicate the * supervisor access attribute, and the MPRx[MPLn] control field for the master * must be set. If not, access terminates with an error response and no peripheral * access initiates. * * Values: * - 0 - This peripheral does not require supervisor privilege level for * accesses. * - 1 - This peripheral requires supervisor privilege level for accesses. */ /*@{*/ #define BP_AIPS_PACRD_SP7 (2U) /*!< Bit position for AIPS_PACRD_SP7. */ #define BM_AIPS_PACRD_SP7 (0x00000004U) /*!< Bit mask for AIPS_PACRD_SP7. */ #define BS_AIPS_PACRD_SP7 (1U) /*!< Bit field size in bits for AIPS_PACRD_SP7. */ /*! @brief Read current value of the AIPS_PACRD_SP7 field. */ #define BR_AIPS_PACRD_SP7(x) (BITBAND_ACCESS32(HW_AIPS_PACRD_ADDR(x), BP_AIPS_PACRD_SP7)) /*! @brief Format value for bitfield AIPS_PACRD_SP7. */ #define BF_AIPS_PACRD_SP7(v) ((uint32_t)((uint32_t)(v) << BP_AIPS_PACRD_SP7) & BM_AIPS_PACRD_SP7) /*! @brief Set the SP7 field to a new value. */ #define BW_AIPS_PACRD_SP7(x, v) (BITBAND_ACCESS32(HW_AIPS_PACRD_ADDR(x), BP_AIPS_PACRD_SP7) = (v)) /*@}*/ /*! * @name Register AIPS_PACRD, field TP6[4] (RW) * * Determines whether the peripheral allows accesses from an untrusted master. * When this field is set and an access is attempted by an untrusted master, the * access terminates with an error response and no peripheral access initiates. * * Values: * - 0 - Accesses from an untrusted master are allowed. * - 1 - Accesses from an untrusted master are not allowed. */ /*@{*/ #define BP_AIPS_PACRD_TP6 (4U) /*!< Bit position for AIPS_PACRD_TP6. */ #define BM_AIPS_PACRD_TP6 (0x00000010U) /*!< Bit mask for AIPS_PACRD_TP6. */ #define BS_AIPS_PACRD_TP6 (1U) /*!< Bit field size in bits for AIPS_PACRD_TP6. */ /*! @brief Read current value of the AIPS_PACRD_TP6 field. */ #define BR_AIPS_PACRD_TP6(x) (BITBAND_ACCESS32(HW_AIPS_PACRD_ADDR(x), BP_AIPS_PACRD_TP6)) /*! @brief Format value for bitfield AIPS_PACRD_TP6. */ #define BF_AIPS_PACRD_TP6(v) ((uint32_t)((uint32_t)(v) << BP_AIPS_PACRD_TP6) & BM_AIPS_PACRD_TP6) /*! @brief Set the TP6 field to a new value. */ #define BW_AIPS_PACRD_TP6(x, v) (BITBAND_ACCESS32(HW_AIPS_PACRD_ADDR(x), BP_AIPS_PACRD_TP6) = (v)) /*@}*/ /*! * @name Register AIPS_PACRD, field WP6[5] (RW) * * Determines whether the peripheral allows write accesses. When this field is * set and a write access is attempted, access terminates with an error response * and no peripheral access initiates. * * Values: * - 0 - This peripheral allows write accesses. * - 1 - This peripheral is write protected. */ /*@{*/ #define BP_AIPS_PACRD_WP6 (5U) /*!< Bit position for AIPS_PACRD_WP6. */ #define BM_AIPS_PACRD_WP6 (0x00000020U) /*!< Bit mask for AIPS_PACRD_WP6. */ #define BS_AIPS_PACRD_WP6 (1U) /*!< Bit field size in bits for AIPS_PACRD_WP6. */ /*! @brief Read current value of the AIPS_PACRD_WP6 field. */ #define BR_AIPS_PACRD_WP6(x) (BITBAND_ACCESS32(HW_AIPS_PACRD_ADDR(x), BP_AIPS_PACRD_WP6)) /*! @brief Format value for bitfield AIPS_PACRD_WP6. */ #define BF_AIPS_PACRD_WP6(v) ((uint32_t)((uint32_t)(v) << BP_AIPS_PACRD_WP6) & BM_AIPS_PACRD_WP6) /*! @brief Set the WP6 field to a new value. */ #define BW_AIPS_PACRD_WP6(x, v) (BITBAND_ACCESS32(HW_AIPS_PACRD_ADDR(x), BP_AIPS_PACRD_WP6) = (v)) /*@}*/ /*! * @name Register AIPS_PACRD, field SP6[6] (RW) * * Determines whether the peripheral requires supervisor privilege level for * accesses. When this field is set, the master privilege level must indicate the * supervisor access attribute, and the MPRx[MPLn] control field for the master * must be set. If not, access terminates with an error response and no peripheral * access initiates. * * Values: * - 0 - This peripheral does not require supervisor privilege level for * accesses. * - 1 - This peripheral requires supervisor privilege level for accesses. */ /*@{*/ #define BP_AIPS_PACRD_SP6 (6U) /*!< Bit position for AIPS_PACRD_SP6. */ #define BM_AIPS_PACRD_SP6 (0x00000040U) /*!< Bit mask for AIPS_PACRD_SP6. */ #define BS_AIPS_PACRD_SP6 (1U) /*!< Bit field size in bits for AIPS_PACRD_SP6. */ /*! @brief Read current value of the AIPS_PACRD_SP6 field. */ #define BR_AIPS_PACRD_SP6(x) (BITBAND_ACCESS32(HW_AIPS_PACRD_ADDR(x), BP_AIPS_PACRD_SP6)) /*! @brief Format value for bitfield AIPS_PACRD_SP6. */ #define BF_AIPS_PACRD_SP6(v) ((uint32_t)((uint32_t)(v) << BP_AIPS_PACRD_SP6) & BM_AIPS_PACRD_SP6) /*! @brief Set the SP6 field to a new value. */ #define BW_AIPS_PACRD_SP6(x, v) (BITBAND_ACCESS32(HW_AIPS_PACRD_ADDR(x), BP_AIPS_PACRD_SP6) = (v)) /*@}*/ /*! * @name Register AIPS_PACRD, field TP5[8] (RW) * * Determines whether the peripheral allows accesses from an untrusted master. * When this field is set and an access is attempted by an untrusted master, the * access terminates with an error response and no peripheral access initiates. * * Values: * - 0 - Accesses from an untrusted master are allowed. * - 1 - Accesses from an untrusted master are not allowed. */ /*@{*/ #define BP_AIPS_PACRD_TP5 (8U) /*!< Bit position for AIPS_PACRD_TP5. */ #define BM_AIPS_PACRD_TP5 (0x00000100U) /*!< Bit mask for AIPS_PACRD_TP5. */ #define BS_AIPS_PACRD_TP5 (1U) /*!< Bit field size in bits for AIPS_PACRD_TP5. */ /*! @brief Read current value of the AIPS_PACRD_TP5 field. */ #define BR_AIPS_PACRD_TP5(x) (BITBAND_ACCESS32(HW_AIPS_PACRD_ADDR(x), BP_AIPS_PACRD_TP5)) /*! @brief Format value for bitfield AIPS_PACRD_TP5. */ #define BF_AIPS_PACRD_TP5(v) ((uint32_t)((uint32_t)(v) << BP_AIPS_PACRD_TP5) & BM_AIPS_PACRD_TP5) /*! @brief Set the TP5 field to a new value. */ #define BW_AIPS_PACRD_TP5(x, v) (BITBAND_ACCESS32(HW_AIPS_PACRD_ADDR(x), BP_AIPS_PACRD_TP5) = (v)) /*@}*/ /*! * @name Register AIPS_PACRD, field WP5[9] (RW) * * Determines whether the peripheral allows write accesses. When this field is * set and a write access is attempted, access terminates with an error response * and no peripheral access initiates. * * Values: * - 0 - This peripheral allows write accesses. * - 1 - This peripheral is write protected. */ /*@{*/ #define BP_AIPS_PACRD_WP5 (9U) /*!< Bit position for AIPS_PACRD_WP5. */ #define BM_AIPS_PACRD_WP5 (0x00000200U) /*!< Bit mask for AIPS_PACRD_WP5. */ #define BS_AIPS_PACRD_WP5 (1U) /*!< Bit field size in bits for AIPS_PACRD_WP5. */ /*! @brief Read current value of the AIPS_PACRD_WP5 field. */ #define BR_AIPS_PACRD_WP5(x) (BITBAND_ACCESS32(HW_AIPS_PACRD_ADDR(x), BP_AIPS_PACRD_WP5)) /*! @brief Format value for bitfield AIPS_PACRD_WP5. */ #define BF_AIPS_PACRD_WP5(v) ((uint32_t)((uint32_t)(v) << BP_AIPS_PACRD_WP5) & BM_AIPS_PACRD_WP5) /*! @brief Set the WP5 field to a new value. */ #define BW_AIPS_PACRD_WP5(x, v) (BITBAND_ACCESS32(HW_AIPS_PACRD_ADDR(x), BP_AIPS_PACRD_WP5) = (v)) /*@}*/ /*! * @name Register AIPS_PACRD, field SP5[10] (RW) * * Determines whether the peripheral requires supervisor privilege level for * accesses. When this field is set, the master privilege level must indicate the * supervisor access attribute, and the MPRx[MPLn] control field for the master * must be set. If not, access terminates with an error response and no peripheral * access initiates. * * Values: * - 0 - This peripheral does not require supervisor privilege level for * accesses. * - 1 - This peripheral requires supervisor privilege level for accesses. */ /*@{*/ #define BP_AIPS_PACRD_SP5 (10U) /*!< Bit position for AIPS_PACRD_SP5. */ #define BM_AIPS_PACRD_SP5 (0x00000400U) /*!< Bit mask for AIPS_PACRD_SP5. */ #define BS_AIPS_PACRD_SP5 (1U) /*!< Bit field size in bits for AIPS_PACRD_SP5. */ /*! @brief Read current value of the AIPS_PACRD_SP5 field. */ #define BR_AIPS_PACRD_SP5(x) (BITBAND_ACCESS32(HW_AIPS_PACRD_ADDR(x), BP_AIPS_PACRD_SP5)) /*! @brief Format value for bitfield AIPS_PACRD_SP5. */ #define BF_AIPS_PACRD_SP5(v) ((uint32_t)((uint32_t)(v) << BP_AIPS_PACRD_SP5) & BM_AIPS_PACRD_SP5) /*! @brief Set the SP5 field to a new value. */ #define BW_AIPS_PACRD_SP5(x, v) (BITBAND_ACCESS32(HW_AIPS_PACRD_ADDR(x), BP_AIPS_PACRD_SP5) = (v)) /*@}*/ /*! * @name Register AIPS_PACRD, field TP4[12] (RW) * * Determines whether the peripheral allows accesses from an untrusted master. * When this field is set and an access is attempted by an untrusted master, the * access terminates with an error response and no peripheral access initiates. * * Values: * - 0 - Accesses from an untrusted master are allowed. * - 1 - Accesses from an untrusted master are not allowed. */ /*@{*/ #define BP_AIPS_PACRD_TP4 (12U) /*!< Bit position for AIPS_PACRD_TP4. */ #define BM_AIPS_PACRD_TP4 (0x00001000U) /*!< Bit mask for AIPS_PACRD_TP4. */ #define BS_AIPS_PACRD_TP4 (1U) /*!< Bit field size in bits for AIPS_PACRD_TP4. */ /*! @brief Read current value of the AIPS_PACRD_TP4 field. */ #define BR_AIPS_PACRD_TP4(x) (BITBAND_ACCESS32(HW_AIPS_PACRD_ADDR(x), BP_AIPS_PACRD_TP4)) /*! @brief Format value for bitfield AIPS_PACRD_TP4. */ #define BF_AIPS_PACRD_TP4(v) ((uint32_t)((uint32_t)(v) << BP_AIPS_PACRD_TP4) & BM_AIPS_PACRD_TP4) /*! @brief Set the TP4 field to a new value. */ #define BW_AIPS_PACRD_TP4(x, v) (BITBAND_ACCESS32(HW_AIPS_PACRD_ADDR(x), BP_AIPS_PACRD_TP4) = (v)) /*@}*/ /*! * @name Register AIPS_PACRD, field WP4[13] (RW) * * Determines whether the peripheral allows write accesss. When this bit is set * and a write access is attempted, access terminates with an error response and * no peripheral access initiates. * * Values: * - 0 - This peripheral allows write accesses. * - 1 - This peripheral is write protected. */ /*@{*/ #define BP_AIPS_PACRD_WP4 (13U) /*!< Bit position for AIPS_PACRD_WP4. */ #define BM_AIPS_PACRD_WP4 (0x00002000U) /*!< Bit mask for AIPS_PACRD_WP4. */ #define BS_AIPS_PACRD_WP4 (1U) /*!< Bit field size in bits for AIPS_PACRD_WP4. */ /*! @brief Read current value of the AIPS_PACRD_WP4 field. */ #define BR_AIPS_PACRD_WP4(x) (BITBAND_ACCESS32(HW_AIPS_PACRD_ADDR(x), BP_AIPS_PACRD_WP4)) /*! @brief Format value for bitfield AIPS_PACRD_WP4. */ #define BF_AIPS_PACRD_WP4(v) ((uint32_t)((uint32_t)(v) << BP_AIPS_PACRD_WP4) & BM_AIPS_PACRD_WP4) /*! @brief Set the WP4 field to a new value. */ #define BW_AIPS_PACRD_WP4(x, v) (BITBAND_ACCESS32(HW_AIPS_PACRD_ADDR(x), BP_AIPS_PACRD_WP4) = (v)) /*@}*/ /*! * @name Register AIPS_PACRD, field SP4[14] (RW) * * Determines whether the peripheral requires supervisor privilege level for * accesses. When this field is set, the master privilege level must indicate the * supervisor access attribute, and the MPRx[MPLn] control field for the master * must be set. If not, access terminates with an error response and no peripheral * access initiates. * * Values: * - 0 - This peripheral does not require supervisor privilege level for * accesses. * - 1 - This peripheral requires supervisor privilege level for accesses. */ /*@{*/ #define BP_AIPS_PACRD_SP4 (14U) /*!< Bit position for AIPS_PACRD_SP4. */ #define BM_AIPS_PACRD_SP4 (0x00004000U) /*!< Bit mask for AIPS_PACRD_SP4. */ #define BS_AIPS_PACRD_SP4 (1U) /*!< Bit field size in bits for AIPS_PACRD_SP4. */ /*! @brief Read current value of the AIPS_PACRD_SP4 field. */ #define BR_AIPS_PACRD_SP4(x) (BITBAND_ACCESS32(HW_AIPS_PACRD_ADDR(x), BP_AIPS_PACRD_SP4)) /*! @brief Format value for bitfield AIPS_PACRD_SP4. */ #define BF_AIPS_PACRD_SP4(v) ((uint32_t)((uint32_t)(v) << BP_AIPS_PACRD_SP4) & BM_AIPS_PACRD_SP4) /*! @brief Set the SP4 field to a new value. */ #define BW_AIPS_PACRD_SP4(x, v) (BITBAND_ACCESS32(HW_AIPS_PACRD_ADDR(x), BP_AIPS_PACRD_SP4) = (v)) /*@}*/ /*! * @name Register AIPS_PACRD, field TP3[16] (RW) * * Determines whether the peripheral allows accesses from an untrusted master. * When this bit is set and an access is attempted by an untrusted master, the * access terminates with an error response and no peripheral access initiates. * * Values: * - 0 - Accesses from an untrusted master are allowed. * - 1 - Accesses from an untrusted master are not allowed. */ /*@{*/ #define BP_AIPS_PACRD_TP3 (16U) /*!< Bit position for AIPS_PACRD_TP3. */ #define BM_AIPS_PACRD_TP3 (0x00010000U) /*!< Bit mask for AIPS_PACRD_TP3. */ #define BS_AIPS_PACRD_TP3 (1U) /*!< Bit field size in bits for AIPS_PACRD_TP3. */ /*! @brief Read current value of the AIPS_PACRD_TP3 field. */ #define BR_AIPS_PACRD_TP3(x) (BITBAND_ACCESS32(HW_AIPS_PACRD_ADDR(x), BP_AIPS_PACRD_TP3)) /*! @brief Format value for bitfield AIPS_PACRD_TP3. */ #define BF_AIPS_PACRD_TP3(v) ((uint32_t)((uint32_t)(v) << BP_AIPS_PACRD_TP3) & BM_AIPS_PACRD_TP3) /*! @brief Set the TP3 field to a new value. */ #define BW_AIPS_PACRD_TP3(x, v) (BITBAND_ACCESS32(HW_AIPS_PACRD_ADDR(x), BP_AIPS_PACRD_TP3) = (v)) /*@}*/ /*! * @name Register AIPS_PACRD, field WP3[17] (RW) * * Determines whether the peripheral allows write accesses. When this field is * set and a write access is attempted, access terminates with an error response * and no peripheral access initiates. * * Values: * - 0 - This peripheral allows write accesses. * - 1 - This peripheral is write protected. */ /*@{*/ #define BP_AIPS_PACRD_WP3 (17U) /*!< Bit position for AIPS_PACRD_WP3. */ #define BM_AIPS_PACRD_WP3 (0x00020000U) /*!< Bit mask for AIPS_PACRD_WP3. */ #define BS_AIPS_PACRD_WP3 (1U) /*!< Bit field size in bits for AIPS_PACRD_WP3. */ /*! @brief Read current value of the AIPS_PACRD_WP3 field. */ #define BR_AIPS_PACRD_WP3(x) (BITBAND_ACCESS32(HW_AIPS_PACRD_ADDR(x), BP_AIPS_PACRD_WP3)) /*! @brief Format value for bitfield AIPS_PACRD_WP3. */ #define BF_AIPS_PACRD_WP3(v) ((uint32_t)((uint32_t)(v) << BP_AIPS_PACRD_WP3) & BM_AIPS_PACRD_WP3) /*! @brief Set the WP3 field to a new value. */ #define BW_AIPS_PACRD_WP3(x, v) (BITBAND_ACCESS32(HW_AIPS_PACRD_ADDR(x), BP_AIPS_PACRD_WP3) = (v)) /*@}*/ /*! * @name Register AIPS_PACRD, field SP3[18] (RW) * * Determines whether the peripheral requires supervisor privilege level for * access. When this bit is set, the master privilege level must indicate the * supervisor access attribute, and the MPRx[MPLn] control bit for the master must be * set. If not, access terminates with an error response and no peripheral access * initiates. * * Values: * - 0 - This peripheral does not require supervisor privilege level for * accesses. * - 1 - This peripheral requires supervisor privilege level for accesses. */ /*@{*/ #define BP_AIPS_PACRD_SP3 (18U) /*!< Bit position for AIPS_PACRD_SP3. */ #define BM_AIPS_PACRD_SP3 (0x00040000U) /*!< Bit mask for AIPS_PACRD_SP3. */ #define BS_AIPS_PACRD_SP3 (1U) /*!< Bit field size in bits for AIPS_PACRD_SP3. */ /*! @brief Read current value of the AIPS_PACRD_SP3 field. */ #define BR_AIPS_PACRD_SP3(x) (BITBAND_ACCESS32(HW_AIPS_PACRD_ADDR(x), BP_AIPS_PACRD_SP3)) /*! @brief Format value for bitfield AIPS_PACRD_SP3. */ #define BF_AIPS_PACRD_SP3(v) ((uint32_t)((uint32_t)(v) << BP_AIPS_PACRD_SP3) & BM_AIPS_PACRD_SP3) /*! @brief Set the SP3 field to a new value. */ #define BW_AIPS_PACRD_SP3(x, v) (BITBAND_ACCESS32(HW_AIPS_PACRD_ADDR(x), BP_AIPS_PACRD_SP3) = (v)) /*@}*/ /*! * @name Register AIPS_PACRD, field TP2[20] (RW) * * Determines whether the peripheral allows accesses from an untrusted master. * When this field is set and an access is attempted by an untrusted master, the * access terminates with an error response and no peripheral access initiates. * * Values: * - 0 - Accesses from an untrusted master are allowed. * - 1 - Accesses from an untrusted master are not allowed. */ /*@{*/ #define BP_AIPS_PACRD_TP2 (20U) /*!< Bit position for AIPS_PACRD_TP2. */ #define BM_AIPS_PACRD_TP2 (0x00100000U) /*!< Bit mask for AIPS_PACRD_TP2. */ #define BS_AIPS_PACRD_TP2 (1U) /*!< Bit field size in bits for AIPS_PACRD_TP2. */ /*! @brief Read current value of the AIPS_PACRD_TP2 field. */ #define BR_AIPS_PACRD_TP2(x) (BITBAND_ACCESS32(HW_AIPS_PACRD_ADDR(x), BP_AIPS_PACRD_TP2)) /*! @brief Format value for bitfield AIPS_PACRD_TP2. */ #define BF_AIPS_PACRD_TP2(v) ((uint32_t)((uint32_t)(v) << BP_AIPS_PACRD_TP2) & BM_AIPS_PACRD_TP2) /*! @brief Set the TP2 field to a new value. */ #define BW_AIPS_PACRD_TP2(x, v) (BITBAND_ACCESS32(HW_AIPS_PACRD_ADDR(x), BP_AIPS_PACRD_TP2) = (v)) /*@}*/ /*! * @name Register AIPS_PACRD, field WP2[21] (RW) * * Determines whether the peripheral allows write accesss. When this bit is set * and a write access is attempted, access terminates with an error response and * no peripheral access initiates. * * Values: * - 0 - This peripheral allows write accesses. * - 1 - This peripheral is write protected. */ /*@{*/ #define BP_AIPS_PACRD_WP2 (21U) /*!< Bit position for AIPS_PACRD_WP2. */ #define BM_AIPS_PACRD_WP2 (0x00200000U) /*!< Bit mask for AIPS_PACRD_WP2. */ #define BS_AIPS_PACRD_WP2 (1U) /*!< Bit field size in bits for AIPS_PACRD_WP2. */ /*! @brief Read current value of the AIPS_PACRD_WP2 field. */ #define BR_AIPS_PACRD_WP2(x) (BITBAND_ACCESS32(HW_AIPS_PACRD_ADDR(x), BP_AIPS_PACRD_WP2)) /*! @brief Format value for bitfield AIPS_PACRD_WP2. */ #define BF_AIPS_PACRD_WP2(v) ((uint32_t)((uint32_t)(v) << BP_AIPS_PACRD_WP2) & BM_AIPS_PACRD_WP2) /*! @brief Set the WP2 field to a new value. */ #define BW_AIPS_PACRD_WP2(x, v) (BITBAND_ACCESS32(HW_AIPS_PACRD_ADDR(x), BP_AIPS_PACRD_WP2) = (v)) /*@}*/ /*! * @name Register AIPS_PACRD, field SP2[22] (RW) * * Determines whether the peripheral requires supervisor privilege level for * accesses. When this field is set, the master privilege level must indicate the * supervisor access attribute, and the MPRx[MPLn] control field for the master * must be set. If not, access terminates with an error response and no peripheral * access initiates. * * Values: * - 0 - This peripheral does not require supervisor privilege level for * accesses. * - 1 - This peripheral requires supervisor privilege level for accesses. */ /*@{*/ #define BP_AIPS_PACRD_SP2 (22U) /*!< Bit position for AIPS_PACRD_SP2. */ #define BM_AIPS_PACRD_SP2 (0x00400000U) /*!< Bit mask for AIPS_PACRD_SP2. */ #define BS_AIPS_PACRD_SP2 (1U) /*!< Bit field size in bits for AIPS_PACRD_SP2. */ /*! @brief Read current value of the AIPS_PACRD_SP2 field. */ #define BR_AIPS_PACRD_SP2(x) (BITBAND_ACCESS32(HW_AIPS_PACRD_ADDR(x), BP_AIPS_PACRD_SP2)) /*! @brief Format value for bitfield AIPS_PACRD_SP2. */ #define BF_AIPS_PACRD_SP2(v) ((uint32_t)((uint32_t)(v) << BP_AIPS_PACRD_SP2) & BM_AIPS_PACRD_SP2) /*! @brief Set the SP2 field to a new value. */ #define BW_AIPS_PACRD_SP2(x, v) (BITBAND_ACCESS32(HW_AIPS_PACRD_ADDR(x), BP_AIPS_PACRD_SP2) = (v)) /*@}*/ /*! * @name Register AIPS_PACRD, field TP1[24] (RW) * * Determines whether the peripheral allows accesses from an untrusted master. * When this bit is set and an access is attempted by an untrusted master, the * access terminates with an error response and no peripheral access initiates. * * Values: * - 0 - Accesses from an untrusted master are allowed. * - 1 - Accesses from an untrusted master are not allowed. */ /*@{*/ #define BP_AIPS_PACRD_TP1 (24U) /*!< Bit position for AIPS_PACRD_TP1. */ #define BM_AIPS_PACRD_TP1 (0x01000000U) /*!< Bit mask for AIPS_PACRD_TP1. */ #define BS_AIPS_PACRD_TP1 (1U) /*!< Bit field size in bits for AIPS_PACRD_TP1. */ /*! @brief Read current value of the AIPS_PACRD_TP1 field. */ #define BR_AIPS_PACRD_TP1(x) (BITBAND_ACCESS32(HW_AIPS_PACRD_ADDR(x), BP_AIPS_PACRD_TP1)) /*! @brief Format value for bitfield AIPS_PACRD_TP1. */ #define BF_AIPS_PACRD_TP1(v) ((uint32_t)((uint32_t)(v) << BP_AIPS_PACRD_TP1) & BM_AIPS_PACRD_TP1) /*! @brief Set the TP1 field to a new value. */ #define BW_AIPS_PACRD_TP1(x, v) (BITBAND_ACCESS32(HW_AIPS_PACRD_ADDR(x), BP_AIPS_PACRD_TP1) = (v)) /*@}*/ /*! * @name Register AIPS_PACRD, field WP1[25] (RW) * * Determines whether the peripheral allows write accesses. When this field is * set and a write access is attempted, access terminates with an error response * and no peripheral access initiates. * * Values: * - 0 - This peripheral allows write accesses. * - 1 - This peripheral is write protected. */ /*@{*/ #define BP_AIPS_PACRD_WP1 (25U) /*!< Bit position for AIPS_PACRD_WP1. */ #define BM_AIPS_PACRD_WP1 (0x02000000U) /*!< Bit mask for AIPS_PACRD_WP1. */ #define BS_AIPS_PACRD_WP1 (1U) /*!< Bit field size in bits for AIPS_PACRD_WP1. */ /*! @brief Read current value of the AIPS_PACRD_WP1 field. */ #define BR_AIPS_PACRD_WP1(x) (BITBAND_ACCESS32(HW_AIPS_PACRD_ADDR(x), BP_AIPS_PACRD_WP1)) /*! @brief Format value for bitfield AIPS_PACRD_WP1. */ #define BF_AIPS_PACRD_WP1(v) ((uint32_t)((uint32_t)(v) << BP_AIPS_PACRD_WP1) & BM_AIPS_PACRD_WP1) /*! @brief Set the WP1 field to a new value. */ #define BW_AIPS_PACRD_WP1(x, v) (BITBAND_ACCESS32(HW_AIPS_PACRD_ADDR(x), BP_AIPS_PACRD_WP1) = (v)) /*@}*/ /*! * @name Register AIPS_PACRD, field SP1[26] (RW) * * Determines whether the peripheral requires supervisor privilege level for * accesses. When this field is set, the master privilege level must indicate the * supervisor access attribute, and the MPRx[MPLn] control field for the master * must be set. If not, access terminates with an error response and no peripheral * access initiates. * * Values: * - 0 - This peripheral does not require supervisor privilege level for * accesses. * - 1 - This peripheral requires supervisor privilege level for accesses. */ /*@{*/ #define BP_AIPS_PACRD_SP1 (26U) /*!< Bit position for AIPS_PACRD_SP1. */ #define BM_AIPS_PACRD_SP1 (0x04000000U) /*!< Bit mask for AIPS_PACRD_SP1. */ #define BS_AIPS_PACRD_SP1 (1U) /*!< Bit field size in bits for AIPS_PACRD_SP1. */ /*! @brief Read current value of the AIPS_PACRD_SP1 field. */ #define BR_AIPS_PACRD_SP1(x) (BITBAND_ACCESS32(HW_AIPS_PACRD_ADDR(x), BP_AIPS_PACRD_SP1)) /*! @brief Format value for bitfield AIPS_PACRD_SP1. */ #define BF_AIPS_PACRD_SP1(v) ((uint32_t)((uint32_t)(v) << BP_AIPS_PACRD_SP1) & BM_AIPS_PACRD_SP1) /*! @brief Set the SP1 field to a new value. */ #define BW_AIPS_PACRD_SP1(x, v) (BITBAND_ACCESS32(HW_AIPS_PACRD_ADDR(x), BP_AIPS_PACRD_SP1) = (v)) /*@}*/ /*! * @name Register AIPS_PACRD, field TP0[28] (RW) * * Determines whether the peripheral allows accesses from an untrusted master. * When this field is set and an access is attempted by an untrusted master, the * access terminates with an error response and no peripheral access initiates. * * Values: * - 0 - Accesses from an untrusted master are allowed. * - 1 - Accesses from an untrusted master are not allowed. */ /*@{*/ #define BP_AIPS_PACRD_TP0 (28U) /*!< Bit position for AIPS_PACRD_TP0. */ #define BM_AIPS_PACRD_TP0 (0x10000000U) /*!< Bit mask for AIPS_PACRD_TP0. */ #define BS_AIPS_PACRD_TP0 (1U) /*!< Bit field size in bits for AIPS_PACRD_TP0. */ /*! @brief Read current value of the AIPS_PACRD_TP0 field. */ #define BR_AIPS_PACRD_TP0(x) (BITBAND_ACCESS32(HW_AIPS_PACRD_ADDR(x), BP_AIPS_PACRD_TP0)) /*! @brief Format value for bitfield AIPS_PACRD_TP0. */ #define BF_AIPS_PACRD_TP0(v) ((uint32_t)((uint32_t)(v) << BP_AIPS_PACRD_TP0) & BM_AIPS_PACRD_TP0) /*! @brief Set the TP0 field to a new value. */ #define BW_AIPS_PACRD_TP0(x, v) (BITBAND_ACCESS32(HW_AIPS_PACRD_ADDR(x), BP_AIPS_PACRD_TP0) = (v)) /*@}*/ /*! * @name Register AIPS_PACRD, field WP0[29] (RW) * * Determines whether the peripheral allows write accesss. When this bit is set * and a write access is attempted, access terminates with an error response and * no peripheral access initiates. * * Values: * - 0 - This peripheral allows write accesses. * - 1 - This peripheral is write protected. */ /*@{*/ #define BP_AIPS_PACRD_WP0 (29U) /*!< Bit position for AIPS_PACRD_WP0. */ #define BM_AIPS_PACRD_WP0 (0x20000000U) /*!< Bit mask for AIPS_PACRD_WP0. */ #define BS_AIPS_PACRD_WP0 (1U) /*!< Bit field size in bits for AIPS_PACRD_WP0. */ /*! @brief Read current value of the AIPS_PACRD_WP0 field. */ #define BR_AIPS_PACRD_WP0(x) (BITBAND_ACCESS32(HW_AIPS_PACRD_ADDR(x), BP_AIPS_PACRD_WP0)) /*! @brief Format value for bitfield AIPS_PACRD_WP0. */ #define BF_AIPS_PACRD_WP0(v) ((uint32_t)((uint32_t)(v) << BP_AIPS_PACRD_WP0) & BM_AIPS_PACRD_WP0) /*! @brief Set the WP0 field to a new value. */ #define BW_AIPS_PACRD_WP0(x, v) (BITBAND_ACCESS32(HW_AIPS_PACRD_ADDR(x), BP_AIPS_PACRD_WP0) = (v)) /*@}*/ /*! * @name Register AIPS_PACRD, field SP0[30] (RW) * * Determines whether the peripheral requires supervisor privilege level for * accesses. When this field is set, the master privilege level must indicate the * supervisor access attribute, and the MPRx[MPLn] control field for the master * must be set. If not, access terminates with an error response and no peripheral * access initiates. * * Values: * - 0 - This peripheral does not require supervisor privilege level for * accesses. * - 1 - This peripheral requires supervisor privilege level for accesses. */ /*@{*/ #define BP_AIPS_PACRD_SP0 (30U) /*!< Bit position for AIPS_PACRD_SP0. */ #define BM_AIPS_PACRD_SP0 (0x40000000U) /*!< Bit mask for AIPS_PACRD_SP0. */ #define BS_AIPS_PACRD_SP0 (1U) /*!< Bit field size in bits for AIPS_PACRD_SP0. */ /*! @brief Read current value of the AIPS_PACRD_SP0 field. */ #define BR_AIPS_PACRD_SP0(x) (BITBAND_ACCESS32(HW_AIPS_PACRD_ADDR(x), BP_AIPS_PACRD_SP0)) /*! @brief Format value for bitfield AIPS_PACRD_SP0. */ #define BF_AIPS_PACRD_SP0(v) ((uint32_t)((uint32_t)(v) << BP_AIPS_PACRD_SP0) & BM_AIPS_PACRD_SP0) /*! @brief Set the SP0 field to a new value. */ #define BW_AIPS_PACRD_SP0(x, v) (BITBAND_ACCESS32(HW_AIPS_PACRD_ADDR(x), BP_AIPS_PACRD_SP0) = (v)) /*@}*/ /******************************************************************************* * HW_AIPS_PACRE - Peripheral Access Control Register ******************************************************************************/ /*! * @brief HW_AIPS_PACRE - Peripheral Access Control Register (RW) * * Reset value: 0x44444444U * * This section describes PACR registers E-P, which control peripheral slots * 32-127. See PACRPeripheral Access Control Register for the description of these * registers. */ typedef union _hw_aips_pacre { uint32_t U; struct _hw_aips_pacre_bitfields { uint32_t TP7 : 1; /*!< [0] Trusted Protect */ uint32_t WP7 : 1; /*!< [1] Write Protect */ uint32_t SP7 : 1; /*!< [2] Supervisor Protect */ uint32_t RESERVED0 : 1; /*!< [3] */ uint32_t TP6 : 1; /*!< [4] Trusted Protect */ uint32_t WP6 : 1; /*!< [5] Write Protect */ uint32_t SP6 : 1; /*!< [6] Supervisor Protect */ uint32_t RESERVED1 : 1; /*!< [7] */ uint32_t TP5 : 1; /*!< [8] Trusted Protect */ uint32_t WP5 : 1; /*!< [9] Write Protect */ uint32_t SP5 : 1; /*!< [10] Supervisor Protect */ uint32_t RESERVED2 : 1; /*!< [11] */ uint32_t TP4 : 1; /*!< [12] Trusted Protect */ uint32_t WP4 : 1; /*!< [13] Write Protect */ uint32_t SP4 : 1; /*!< [14] Supervisor Protect */ uint32_t RESERVED3 : 1; /*!< [15] */ uint32_t TP3 : 1; /*!< [16] Trusted Protect */ uint32_t WP3 : 1; /*!< [17] Write Protect */ uint32_t SP3 : 1; /*!< [18] Supervisor Protect */ uint32_t RESERVED4 : 1; /*!< [19] */ uint32_t TP2 : 1; /*!< [20] Trusted Protect */ uint32_t WP2 : 1; /*!< [21] Write Protect */ uint32_t SP2 : 1; /*!< [22] Supervisor Protect */ uint32_t RESERVED5 : 1; /*!< [23] */ uint32_t TP1 : 1; /*!< [24] Trusted Protect */ uint32_t WP1 : 1; /*!< [25] Write Protect */ uint32_t SP1 : 1; /*!< [26] Supervisor Protect */ uint32_t RESERVED6 : 1; /*!< [27] */ uint32_t TP0 : 1; /*!< [28] Trusted Protect */ uint32_t WP0 : 1; /*!< [29] Write Protect */ uint32_t SP0 : 1; /*!< [30] Supervisor Protect */ uint32_t RESERVED7 : 1; /*!< [31] */ } B; } hw_aips_pacre_t; /*! * @name Constants and macros for entire AIPS_PACRE register */ /*@{*/ #define HW_AIPS_PACRE_ADDR(x) ((x) + 0x40U) #define HW_AIPS_PACRE(x) (*(__IO hw_aips_pacre_t *) HW_AIPS_PACRE_ADDR(x)) #define HW_AIPS_PACRE_RD(x) (HW_AIPS_PACRE(x).U) #define HW_AIPS_PACRE_WR(x, v) (HW_AIPS_PACRE(x).U = (v)) #define HW_AIPS_PACRE_SET(x, v) (HW_AIPS_PACRE_WR(x, HW_AIPS_PACRE_RD(x) | (v))) #define HW_AIPS_PACRE_CLR(x, v) (HW_AIPS_PACRE_WR(x, HW_AIPS_PACRE_RD(x) & ~(v))) #define HW_AIPS_PACRE_TOG(x, v) (HW_AIPS_PACRE_WR(x, HW_AIPS_PACRE_RD(x) ^ (v))) /*@}*/ /* * Constants & macros for individual AIPS_PACRE bitfields */ /*! * @name Register AIPS_PACRE, field TP7[0] (RW) * * Determines whether the peripheral allows accesses from an untrusted master. * When this field is set and an access is attempted by an untrusted master, the * access terminates with an error response and no peripheral access initiates. * * Values: * - 0 - Accesses from an untrusted master are allowed. * - 1 - Accesses from an untrusted master are not allowed. */ /*@{*/ #define BP_AIPS_PACRE_TP7 (0U) /*!< Bit position for AIPS_PACRE_TP7. */ #define BM_AIPS_PACRE_TP7 (0x00000001U) /*!< Bit mask for AIPS_PACRE_TP7. */ #define BS_AIPS_PACRE_TP7 (1U) /*!< Bit field size in bits for AIPS_PACRE_TP7. */ /*! @brief Read current value of the AIPS_PACRE_TP7 field. */ #define BR_AIPS_PACRE_TP7(x) (BITBAND_ACCESS32(HW_AIPS_PACRE_ADDR(x), BP_AIPS_PACRE_TP7)) /*! @brief Format value for bitfield AIPS_PACRE_TP7. */ #define BF_AIPS_PACRE_TP7(v) ((uint32_t)((uint32_t)(v) << BP_AIPS_PACRE_TP7) & BM_AIPS_PACRE_TP7) /*! @brief Set the TP7 field to a new value. */ #define BW_AIPS_PACRE_TP7(x, v) (BITBAND_ACCESS32(HW_AIPS_PACRE_ADDR(x), BP_AIPS_PACRE_TP7) = (v)) /*@}*/ /*! * @name Register AIPS_PACRE, field WP7[1] (RW) * * Determines whether the peripheral allows write accesses. When this field is * set and a write access is attempted, access terminates with an error response * and no peripheral access initiates. * * Values: * - 0 - This peripheral allows write accesses. * - 1 - This peripheral is write protected. */ /*@{*/ #define BP_AIPS_PACRE_WP7 (1U) /*!< Bit position for AIPS_PACRE_WP7. */ #define BM_AIPS_PACRE_WP7 (0x00000002U) /*!< Bit mask for AIPS_PACRE_WP7. */ #define BS_AIPS_PACRE_WP7 (1U) /*!< Bit field size in bits for AIPS_PACRE_WP7. */ /*! @brief Read current value of the AIPS_PACRE_WP7 field. */ #define BR_AIPS_PACRE_WP7(x) (BITBAND_ACCESS32(HW_AIPS_PACRE_ADDR(x), BP_AIPS_PACRE_WP7)) /*! @brief Format value for bitfield AIPS_PACRE_WP7. */ #define BF_AIPS_PACRE_WP7(v) ((uint32_t)((uint32_t)(v) << BP_AIPS_PACRE_WP7) & BM_AIPS_PACRE_WP7) /*! @brief Set the WP7 field to a new value. */ #define BW_AIPS_PACRE_WP7(x, v) (BITBAND_ACCESS32(HW_AIPS_PACRE_ADDR(x), BP_AIPS_PACRE_WP7) = (v)) /*@}*/ /*! * @name Register AIPS_PACRE, field SP7[2] (RW) * * Determines whether the peripheral requires supervisor privilege level for * accesses. When this field is set, the master privilege level must indicate the * supervisor access attribute, and the MPRx[MPLn] control field for the master * must be set. If not, access terminates with an error response and no peripheral * access initiates. * * Values: * - 0 - This peripheral does not require supervisor privilege level for * accesses. * - 1 - This peripheral requires supervisor privilege level for accesses. */ /*@{*/ #define BP_AIPS_PACRE_SP7 (2U) /*!< Bit position for AIPS_PACRE_SP7. */ #define BM_AIPS_PACRE_SP7 (0x00000004U) /*!< Bit mask for AIPS_PACRE_SP7. */ #define BS_AIPS_PACRE_SP7 (1U) /*!< Bit field size in bits for AIPS_PACRE_SP7. */ /*! @brief Read current value of the AIPS_PACRE_SP7 field. */ #define BR_AIPS_PACRE_SP7(x) (BITBAND_ACCESS32(HW_AIPS_PACRE_ADDR(x), BP_AIPS_PACRE_SP7)) /*! @brief Format value for bitfield AIPS_PACRE_SP7. */ #define BF_AIPS_PACRE_SP7(v) ((uint32_t)((uint32_t)(v) << BP_AIPS_PACRE_SP7) & BM_AIPS_PACRE_SP7) /*! @brief Set the SP7 field to a new value. */ #define BW_AIPS_PACRE_SP7(x, v) (BITBAND_ACCESS32(HW_AIPS_PACRE_ADDR(x), BP_AIPS_PACRE_SP7) = (v)) /*@}*/ /*! * @name Register AIPS_PACRE, field TP6[4] (RW) * * Determines whether the peripheral allows accesses from an untrusted master. * When this field is set and an access is attempted by an untrusted master, the * access terminates with an error response and no peripheral access initiates. * * Values: * - 0 - Accesses from an untrusted master are allowed. * - 1 - Accesses from an untrusted master are not allowed. */ /*@{*/ #define BP_AIPS_PACRE_TP6 (4U) /*!< Bit position for AIPS_PACRE_TP6. */ #define BM_AIPS_PACRE_TP6 (0x00000010U) /*!< Bit mask for AIPS_PACRE_TP6. */ #define BS_AIPS_PACRE_TP6 (1U) /*!< Bit field size in bits for AIPS_PACRE_TP6. */ /*! @brief Read current value of the AIPS_PACRE_TP6 field. */ #define BR_AIPS_PACRE_TP6(x) (BITBAND_ACCESS32(HW_AIPS_PACRE_ADDR(x), BP_AIPS_PACRE_TP6)) /*! @brief Format value for bitfield AIPS_PACRE_TP6. */ #define BF_AIPS_PACRE_TP6(v) ((uint32_t)((uint32_t)(v) << BP_AIPS_PACRE_TP6) & BM_AIPS_PACRE_TP6) /*! @brief Set the TP6 field to a new value. */ #define BW_AIPS_PACRE_TP6(x, v) (BITBAND_ACCESS32(HW_AIPS_PACRE_ADDR(x), BP_AIPS_PACRE_TP6) = (v)) /*@}*/ /*! * @name Register AIPS_PACRE, field WP6[5] (RW) * * Determines whether the peripheral allows write accesses. When this field is * set and a write access is attempted, access terminates with an error response * and no peripheral access initiates. * * Values: * - 0 - This peripheral allows write accesses. * - 1 - This peripheral is write protected. */ /*@{*/ #define BP_AIPS_PACRE_WP6 (5U) /*!< Bit position for AIPS_PACRE_WP6. */ #define BM_AIPS_PACRE_WP6 (0x00000020U) /*!< Bit mask for AIPS_PACRE_WP6. */ #define BS_AIPS_PACRE_WP6 (1U) /*!< Bit field size in bits for AIPS_PACRE_WP6. */ /*! @brief Read current value of the AIPS_PACRE_WP6 field. */ #define BR_AIPS_PACRE_WP6(x) (BITBAND_ACCESS32(HW_AIPS_PACRE_ADDR(x), BP_AIPS_PACRE_WP6)) /*! @brief Format value for bitfield AIPS_PACRE_WP6. */ #define BF_AIPS_PACRE_WP6(v) ((uint32_t)((uint32_t)(v) << BP_AIPS_PACRE_WP6) & BM_AIPS_PACRE_WP6) /*! @brief Set the WP6 field to a new value. */ #define BW_AIPS_PACRE_WP6(x, v) (BITBAND_ACCESS32(HW_AIPS_PACRE_ADDR(x), BP_AIPS_PACRE_WP6) = (v)) /*@}*/ /*! * @name Register AIPS_PACRE, field SP6[6] (RW) * * Determines whether the peripheral requires supervisor privilege level for * accesses. When this field is set, the master privilege level must indicate the * supervisor access attribute, and the MPRx[MPLn] control field for the master * must be set. If not, access terminates with an error response and no peripheral * access initiates. * * Values: * - 0 - This peripheral does not require supervisor privilege level for * accesses. * - 1 - This peripheral requires supervisor privilege level for accesses. */ /*@{*/ #define BP_AIPS_PACRE_SP6 (6U) /*!< Bit position for AIPS_PACRE_SP6. */ #define BM_AIPS_PACRE_SP6 (0x00000040U) /*!< Bit mask for AIPS_PACRE_SP6. */ #define BS_AIPS_PACRE_SP6 (1U) /*!< Bit field size in bits for AIPS_PACRE_SP6. */ /*! @brief Read current value of the AIPS_PACRE_SP6 field. */ #define BR_AIPS_PACRE_SP6(x) (BITBAND_ACCESS32(HW_AIPS_PACRE_ADDR(x), BP_AIPS_PACRE_SP6)) /*! @brief Format value for bitfield AIPS_PACRE_SP6. */ #define BF_AIPS_PACRE_SP6(v) ((uint32_t)((uint32_t)(v) << BP_AIPS_PACRE_SP6) & BM_AIPS_PACRE_SP6) /*! @brief Set the SP6 field to a new value. */ #define BW_AIPS_PACRE_SP6(x, v) (BITBAND_ACCESS32(HW_AIPS_PACRE_ADDR(x), BP_AIPS_PACRE_SP6) = (v)) /*@}*/ /*! * @name Register AIPS_PACRE, field TP5[8] (RW) * * Determines whether the peripheral allows accesses from an untrusted master. * When this field is set and an access is attempted by an untrusted master, the * access terminates with an error response and no peripheral access initiates. * * Values: * - 0 - Accesses from an untrusted master are allowed. * - 1 - Accesses from an untrusted master are not allowed. */ /*@{*/ #define BP_AIPS_PACRE_TP5 (8U) /*!< Bit position for AIPS_PACRE_TP5. */ #define BM_AIPS_PACRE_TP5 (0x00000100U) /*!< Bit mask for AIPS_PACRE_TP5. */ #define BS_AIPS_PACRE_TP5 (1U) /*!< Bit field size in bits for AIPS_PACRE_TP5. */ /*! @brief Read current value of the AIPS_PACRE_TP5 field. */ #define BR_AIPS_PACRE_TP5(x) (BITBAND_ACCESS32(HW_AIPS_PACRE_ADDR(x), BP_AIPS_PACRE_TP5)) /*! @brief Format value for bitfield AIPS_PACRE_TP5. */ #define BF_AIPS_PACRE_TP5(v) ((uint32_t)((uint32_t)(v) << BP_AIPS_PACRE_TP5) & BM_AIPS_PACRE_TP5) /*! @brief Set the TP5 field to a new value. */ #define BW_AIPS_PACRE_TP5(x, v) (BITBAND_ACCESS32(HW_AIPS_PACRE_ADDR(x), BP_AIPS_PACRE_TP5) = (v)) /*@}*/ /*! * @name Register AIPS_PACRE, field WP5[9] (RW) * * Determines whether the peripheral allows write accesses. When this field is * set and a write access is attempted, access terminates with an error response * and no peripheral access initiates. * * Values: * - 0 - This peripheral allows write accesses. * - 1 - This peripheral is write protected. */ /*@{*/ #define BP_AIPS_PACRE_WP5 (9U) /*!< Bit position for AIPS_PACRE_WP5. */ #define BM_AIPS_PACRE_WP5 (0x00000200U) /*!< Bit mask for AIPS_PACRE_WP5. */ #define BS_AIPS_PACRE_WP5 (1U) /*!< Bit field size in bits for AIPS_PACRE_WP5. */ /*! @brief Read current value of the AIPS_PACRE_WP5 field. */ #define BR_AIPS_PACRE_WP5(x) (BITBAND_ACCESS32(HW_AIPS_PACRE_ADDR(x), BP_AIPS_PACRE_WP5)) /*! @brief Format value for bitfield AIPS_PACRE_WP5. */ #define BF_AIPS_PACRE_WP5(v) ((uint32_t)((uint32_t)(v) << BP_AIPS_PACRE_WP5) & BM_AIPS_PACRE_WP5) /*! @brief Set the WP5 field to a new value. */ #define BW_AIPS_PACRE_WP5(x, v) (BITBAND_ACCESS32(HW_AIPS_PACRE_ADDR(x), BP_AIPS_PACRE_WP5) = (v)) /*@}*/ /*! * @name Register AIPS_PACRE, field SP5[10] (RW) * * Determines whether the peripheral requires supervisor privilege level for * accesses. When this field is set, the master privilege level must indicate the * supervisor access attribute, and the MPRx[MPLn] control field for the master * must be set. If not, access terminates with an error response and no peripheral * access initiates. * * Values: * - 0 - This peripheral does not require supervisor privilege level for * accesses. * - 1 - This peripheral requires supervisor privilege level for accesses. */ /*@{*/ #define BP_AIPS_PACRE_SP5 (10U) /*!< Bit position for AIPS_PACRE_SP5. */ #define BM_AIPS_PACRE_SP5 (0x00000400U) /*!< Bit mask for AIPS_PACRE_SP5. */ #define BS_AIPS_PACRE_SP5 (1U) /*!< Bit field size in bits for AIPS_PACRE_SP5. */ /*! @brief Read current value of the AIPS_PACRE_SP5 field. */ #define BR_AIPS_PACRE_SP5(x) (BITBAND_ACCESS32(HW_AIPS_PACRE_ADDR(x), BP_AIPS_PACRE_SP5)) /*! @brief Format value for bitfield AIPS_PACRE_SP5. */ #define BF_AIPS_PACRE_SP5(v) ((uint32_t)((uint32_t)(v) << BP_AIPS_PACRE_SP5) & BM_AIPS_PACRE_SP5) /*! @brief Set the SP5 field to a new value. */ #define BW_AIPS_PACRE_SP5(x, v) (BITBAND_ACCESS32(HW_AIPS_PACRE_ADDR(x), BP_AIPS_PACRE_SP5) = (v)) /*@}*/ /*! * @name Register AIPS_PACRE, field TP4[12] (RW) * * Determines whether the peripheral allows accesses from an untrusted master. * When this bit is set and an access is attempted by an untrusted master, the * access terminates with an error response and no peripheral access initiates. * * Values: * - 0 - Accesses from an untrusted master are allowed. * - 1 - Accesses from an untrusted master are not allowed. */ /*@{*/ #define BP_AIPS_PACRE_TP4 (12U) /*!< Bit position for AIPS_PACRE_TP4. */ #define BM_AIPS_PACRE_TP4 (0x00001000U) /*!< Bit mask for AIPS_PACRE_TP4. */ #define BS_AIPS_PACRE_TP4 (1U) /*!< Bit field size in bits for AIPS_PACRE_TP4. */ /*! @brief Read current value of the AIPS_PACRE_TP4 field. */ #define BR_AIPS_PACRE_TP4(x) (BITBAND_ACCESS32(HW_AIPS_PACRE_ADDR(x), BP_AIPS_PACRE_TP4)) /*! @brief Format value for bitfield AIPS_PACRE_TP4. */ #define BF_AIPS_PACRE_TP4(v) ((uint32_t)((uint32_t)(v) << BP_AIPS_PACRE_TP4) & BM_AIPS_PACRE_TP4) /*! @brief Set the TP4 field to a new value. */ #define BW_AIPS_PACRE_TP4(x, v) (BITBAND_ACCESS32(HW_AIPS_PACRE_ADDR(x), BP_AIPS_PACRE_TP4) = (v)) /*@}*/ /*! * @name Register AIPS_PACRE, field WP4[13] (RW) * * Determines whether the peripheral allows write accesses. When this field is * set and a write access is attempted, access terminates with an error response * and no peripheral access initiates. * * Values: * - 0 - This peripheral allows write accesses. * - 1 - This peripheral is write protected. */ /*@{*/ #define BP_AIPS_PACRE_WP4 (13U) /*!< Bit position for AIPS_PACRE_WP4. */ #define BM_AIPS_PACRE_WP4 (0x00002000U) /*!< Bit mask for AIPS_PACRE_WP4. */ #define BS_AIPS_PACRE_WP4 (1U) /*!< Bit field size in bits for AIPS_PACRE_WP4. */ /*! @brief Read current value of the AIPS_PACRE_WP4 field. */ #define BR_AIPS_PACRE_WP4(x) (BITBAND_ACCESS32(HW_AIPS_PACRE_ADDR(x), BP_AIPS_PACRE_WP4)) /*! @brief Format value for bitfield AIPS_PACRE_WP4. */ #define BF_AIPS_PACRE_WP4(v) ((uint32_t)((uint32_t)(v) << BP_AIPS_PACRE_WP4) & BM_AIPS_PACRE_WP4) /*! @brief Set the WP4 field to a new value. */ #define BW_AIPS_PACRE_WP4(x, v) (BITBAND_ACCESS32(HW_AIPS_PACRE_ADDR(x), BP_AIPS_PACRE_WP4) = (v)) /*@}*/ /*! * @name Register AIPS_PACRE, field SP4[14] (RW) * * Determines whether the peripheral requires supervisor privilege level for * access. When this bit is set, the master privilege level must indicate the * supervisor access attribute, and the MPRx[MPLn] control bit for the master must be * set. If not, access terminates with an error response and no peripheral access * initiates. * * Values: * - 0 - This peripheral does not require supervisor privilege level for * accesses. * - 1 - This peripheral requires supervisor privilege level for accesses. */ /*@{*/ #define BP_AIPS_PACRE_SP4 (14U) /*!< Bit position for AIPS_PACRE_SP4. */ #define BM_AIPS_PACRE_SP4 (0x00004000U) /*!< Bit mask for AIPS_PACRE_SP4. */ #define BS_AIPS_PACRE_SP4 (1U) /*!< Bit field size in bits for AIPS_PACRE_SP4. */ /*! @brief Read current value of the AIPS_PACRE_SP4 field. */ #define BR_AIPS_PACRE_SP4(x) (BITBAND_ACCESS32(HW_AIPS_PACRE_ADDR(x), BP_AIPS_PACRE_SP4)) /*! @brief Format value for bitfield AIPS_PACRE_SP4. */ #define BF_AIPS_PACRE_SP4(v) ((uint32_t)((uint32_t)(v) << BP_AIPS_PACRE_SP4) & BM_AIPS_PACRE_SP4) /*! @brief Set the SP4 field to a new value. */ #define BW_AIPS_PACRE_SP4(x, v) (BITBAND_ACCESS32(HW_AIPS_PACRE_ADDR(x), BP_AIPS_PACRE_SP4) = (v)) /*@}*/ /*! * @name Register AIPS_PACRE, field TP3[16] (RW) * * Determines whether the peripheral allows accesses from an untrusted master. * When this field is set and an access is attempted by an untrusted master, the * access terminates with an error response and no peripheral access initiates. * * Values: * - 0 - Accesses from an untrusted master are allowed. * - 1 - Accesses from an untrusted master are not allowed. */ /*@{*/ #define BP_AIPS_PACRE_TP3 (16U) /*!< Bit position for AIPS_PACRE_TP3. */ #define BM_AIPS_PACRE_TP3 (0x00010000U) /*!< Bit mask for AIPS_PACRE_TP3. */ #define BS_AIPS_PACRE_TP3 (1U) /*!< Bit field size in bits for AIPS_PACRE_TP3. */ /*! @brief Read current value of the AIPS_PACRE_TP3 field. */ #define BR_AIPS_PACRE_TP3(x) (BITBAND_ACCESS32(HW_AIPS_PACRE_ADDR(x), BP_AIPS_PACRE_TP3)) /*! @brief Format value for bitfield AIPS_PACRE_TP3. */ #define BF_AIPS_PACRE_TP3(v) ((uint32_t)((uint32_t)(v) << BP_AIPS_PACRE_TP3) & BM_AIPS_PACRE_TP3) /*! @brief Set the TP3 field to a new value. */ #define BW_AIPS_PACRE_TP3(x, v) (BITBAND_ACCESS32(HW_AIPS_PACRE_ADDR(x), BP_AIPS_PACRE_TP3) = (v)) /*@}*/ /*! * @name Register AIPS_PACRE, field WP3[17] (RW) * * Determines whether the peripheral allows write accesss. When this bit is set * and a write access is attempted, access terminates with an error response and * no peripheral access initiates. * * Values: * - 0 - This peripheral allows write accesses. * - 1 - This peripheral is write protected. */ /*@{*/ #define BP_AIPS_PACRE_WP3 (17U) /*!< Bit position for AIPS_PACRE_WP3. */ #define BM_AIPS_PACRE_WP3 (0x00020000U) /*!< Bit mask for AIPS_PACRE_WP3. */ #define BS_AIPS_PACRE_WP3 (1U) /*!< Bit field size in bits for AIPS_PACRE_WP3. */ /*! @brief Read current value of the AIPS_PACRE_WP3 field. */ #define BR_AIPS_PACRE_WP3(x) (BITBAND_ACCESS32(HW_AIPS_PACRE_ADDR(x), BP_AIPS_PACRE_WP3)) /*! @brief Format value for bitfield AIPS_PACRE_WP3. */ #define BF_AIPS_PACRE_WP3(v) ((uint32_t)((uint32_t)(v) << BP_AIPS_PACRE_WP3) & BM_AIPS_PACRE_WP3) /*! @brief Set the WP3 field to a new value. */ #define BW_AIPS_PACRE_WP3(x, v) (BITBAND_ACCESS32(HW_AIPS_PACRE_ADDR(x), BP_AIPS_PACRE_WP3) = (v)) /*@}*/ /*! * @name Register AIPS_PACRE, field SP3[18] (RW) * * Determines whether the peripheral requires supervisor privilege level for * accesses. When this field is set, the master privilege level must indicate the * supervisor access attribute, and the MPRx[MPLn] control field for the master * must be set. If not, access terminates with an error response and no peripheral * access initiates. * * Values: * - 0 - This peripheral does not require supervisor privilege level for * accesses. * - 1 - This peripheral requires supervisor privilege level for accesses. */ /*@{*/ #define BP_AIPS_PACRE_SP3 (18U) /*!< Bit position for AIPS_PACRE_SP3. */ #define BM_AIPS_PACRE_SP3 (0x00040000U) /*!< Bit mask for AIPS_PACRE_SP3. */ #define BS_AIPS_PACRE_SP3 (1U) /*!< Bit field size in bits for AIPS_PACRE_SP3. */ /*! @brief Read current value of the AIPS_PACRE_SP3 field. */ #define BR_AIPS_PACRE_SP3(x) (BITBAND_ACCESS32(HW_AIPS_PACRE_ADDR(x), BP_AIPS_PACRE_SP3)) /*! @brief Format value for bitfield AIPS_PACRE_SP3. */ #define BF_AIPS_PACRE_SP3(v) ((uint32_t)((uint32_t)(v) << BP_AIPS_PACRE_SP3) & BM_AIPS_PACRE_SP3) /*! @brief Set the SP3 field to a new value. */ #define BW_AIPS_PACRE_SP3(x, v) (BITBAND_ACCESS32(HW_AIPS_PACRE_ADDR(x), BP_AIPS_PACRE_SP3) = (v)) /*@}*/ /*! * @name Register AIPS_PACRE, field TP2[20] (RW) * * Determines whether the peripheral allows accesses from an untrusted master. * When this bit is set and an access is attempted by an untrusted master, the * access terminates with an error response and no peripheral access initiates. * * Values: * - 0 - Accesses from an untrusted master are allowed. * - 1 - Accesses from an untrusted master are not allowed. */ /*@{*/ #define BP_AIPS_PACRE_TP2 (20U) /*!< Bit position for AIPS_PACRE_TP2. */ #define BM_AIPS_PACRE_TP2 (0x00100000U) /*!< Bit mask for AIPS_PACRE_TP2. */ #define BS_AIPS_PACRE_TP2 (1U) /*!< Bit field size in bits for AIPS_PACRE_TP2. */ /*! @brief Read current value of the AIPS_PACRE_TP2 field. */ #define BR_AIPS_PACRE_TP2(x) (BITBAND_ACCESS32(HW_AIPS_PACRE_ADDR(x), BP_AIPS_PACRE_TP2)) /*! @brief Format value for bitfield AIPS_PACRE_TP2. */ #define BF_AIPS_PACRE_TP2(v) ((uint32_t)((uint32_t)(v) << BP_AIPS_PACRE_TP2) & BM_AIPS_PACRE_TP2) /*! @brief Set the TP2 field to a new value. */ #define BW_AIPS_PACRE_TP2(x, v) (BITBAND_ACCESS32(HW_AIPS_PACRE_ADDR(x), BP_AIPS_PACRE_TP2) = (v)) /*@}*/ /*! * @name Register AIPS_PACRE, field WP2[21] (RW) * * Determines whether the peripheral allows write accesses. When this field is * set and a write access is attempted, access terminates with an error response * and no peripheral access initiates. * * Values: * - 0 - This peripheral allows write accesses. * - 1 - This peripheral is write protected. */ /*@{*/ #define BP_AIPS_PACRE_WP2 (21U) /*!< Bit position for AIPS_PACRE_WP2. */ #define BM_AIPS_PACRE_WP2 (0x00200000U) /*!< Bit mask for AIPS_PACRE_WP2. */ #define BS_AIPS_PACRE_WP2 (1U) /*!< Bit field size in bits for AIPS_PACRE_WP2. */ /*! @brief Read current value of the AIPS_PACRE_WP2 field. */ #define BR_AIPS_PACRE_WP2(x) (BITBAND_ACCESS32(HW_AIPS_PACRE_ADDR(x), BP_AIPS_PACRE_WP2)) /*! @brief Format value for bitfield AIPS_PACRE_WP2. */ #define BF_AIPS_PACRE_WP2(v) ((uint32_t)((uint32_t)(v) << BP_AIPS_PACRE_WP2) & BM_AIPS_PACRE_WP2) /*! @brief Set the WP2 field to a new value. */ #define BW_AIPS_PACRE_WP2(x, v) (BITBAND_ACCESS32(HW_AIPS_PACRE_ADDR(x), BP_AIPS_PACRE_WP2) = (v)) /*@}*/ /*! * @name Register AIPS_PACRE, field SP2[22] (RW) * * Determines whether the peripheral requires supervisor privilege level for * access. When this bit is set, the master privilege level must indicate the * supervisor access attribute, and the MPRx[MPLn] control bit for the master must be * set. If not, access terminates with an error response and no peripheral access * initiates. * * Values: * - 0 - This peripheral does not require supervisor privilege level for * accesses. * - 1 - This peripheral requires supervisor privilege level for accesses. */ /*@{*/ #define BP_AIPS_PACRE_SP2 (22U) /*!< Bit position for AIPS_PACRE_SP2. */ #define BM_AIPS_PACRE_SP2 (0x00400000U) /*!< Bit mask for AIPS_PACRE_SP2. */ #define BS_AIPS_PACRE_SP2 (1U) /*!< Bit field size in bits for AIPS_PACRE_SP2. */ /*! @brief Read current value of the AIPS_PACRE_SP2 field. */ #define BR_AIPS_PACRE_SP2(x) (BITBAND_ACCESS32(HW_AIPS_PACRE_ADDR(x), BP_AIPS_PACRE_SP2)) /*! @brief Format value for bitfield AIPS_PACRE_SP2. */ #define BF_AIPS_PACRE_SP2(v) ((uint32_t)((uint32_t)(v) << BP_AIPS_PACRE_SP2) & BM_AIPS_PACRE_SP2) /*! @brief Set the SP2 field to a new value. */ #define BW_AIPS_PACRE_SP2(x, v) (BITBAND_ACCESS32(HW_AIPS_PACRE_ADDR(x), BP_AIPS_PACRE_SP2) = (v)) /*@}*/ /*! * @name Register AIPS_PACRE, field TP1[24] (RW) * * Determines whether the peripheral allows accesses from an untrusted master. * When this field is set and an access is attempted by an untrusted master, the * access terminates with an error response and no peripheral access initiates. * * Values: * - 0 - Accesses from an untrusted master are allowed. * - 1 - Accesses from an untrusted master are not allowed. */ /*@{*/ #define BP_AIPS_PACRE_TP1 (24U) /*!< Bit position for AIPS_PACRE_TP1. */ #define BM_AIPS_PACRE_TP1 (0x01000000U) /*!< Bit mask for AIPS_PACRE_TP1. */ #define BS_AIPS_PACRE_TP1 (1U) /*!< Bit field size in bits for AIPS_PACRE_TP1. */ /*! @brief Read current value of the AIPS_PACRE_TP1 field. */ #define BR_AIPS_PACRE_TP1(x) (BITBAND_ACCESS32(HW_AIPS_PACRE_ADDR(x), BP_AIPS_PACRE_TP1)) /*! @brief Format value for bitfield AIPS_PACRE_TP1. */ #define BF_AIPS_PACRE_TP1(v) ((uint32_t)((uint32_t)(v) << BP_AIPS_PACRE_TP1) & BM_AIPS_PACRE_TP1) /*! @brief Set the TP1 field to a new value. */ #define BW_AIPS_PACRE_TP1(x, v) (BITBAND_ACCESS32(HW_AIPS_PACRE_ADDR(x), BP_AIPS_PACRE_TP1) = (v)) /*@}*/ /*! * @name Register AIPS_PACRE, field WP1[25] (RW) * * Determines whether the peripheral allows write accesses. When this field is * set and a write access is attempted, access terminates with an error response * and no peripheral access initiates. * * Values: * - 0 - This peripheral allows write accesses. * - 1 - This peripheral is write protected. */ /*@{*/ #define BP_AIPS_PACRE_WP1 (25U) /*!< Bit position for AIPS_PACRE_WP1. */ #define BM_AIPS_PACRE_WP1 (0x02000000U) /*!< Bit mask for AIPS_PACRE_WP1. */ #define BS_AIPS_PACRE_WP1 (1U) /*!< Bit field size in bits for AIPS_PACRE_WP1. */ /*! @brief Read current value of the AIPS_PACRE_WP1 field. */ #define BR_AIPS_PACRE_WP1(x) (BITBAND_ACCESS32(HW_AIPS_PACRE_ADDR(x), BP_AIPS_PACRE_WP1)) /*! @brief Format value for bitfield AIPS_PACRE_WP1. */ #define BF_AIPS_PACRE_WP1(v) ((uint32_t)((uint32_t)(v) << BP_AIPS_PACRE_WP1) & BM_AIPS_PACRE_WP1) /*! @brief Set the WP1 field to a new value. */ #define BW_AIPS_PACRE_WP1(x, v) (BITBAND_ACCESS32(HW_AIPS_PACRE_ADDR(x), BP_AIPS_PACRE_WP1) = (v)) /*@}*/ /*! * @name Register AIPS_PACRE, field SP1[26] (RW) * * Determines whether the peripheral requires supervisor privilege level for * access. When this field is set, the master privilege level must indicate the * supervisor access attribute, and the MPRx[MPLn] control field for the master must * be set. If not, access terminates with an error response and no peripheral * access initiates. * * Values: * - 0 - This peripheral does not require supervisor privilege level for * accesses. * - 1 - This peripheral requires supervisor privilege level for accesses. */ /*@{*/ #define BP_AIPS_PACRE_SP1 (26U) /*!< Bit position for AIPS_PACRE_SP1. */ #define BM_AIPS_PACRE_SP1 (0x04000000U) /*!< Bit mask for AIPS_PACRE_SP1. */ #define BS_AIPS_PACRE_SP1 (1U) /*!< Bit field size in bits for AIPS_PACRE_SP1. */ /*! @brief Read current value of the AIPS_PACRE_SP1 field. */ #define BR_AIPS_PACRE_SP1(x) (BITBAND_ACCESS32(HW_AIPS_PACRE_ADDR(x), BP_AIPS_PACRE_SP1)) /*! @brief Format value for bitfield AIPS_PACRE_SP1. */ #define BF_AIPS_PACRE_SP1(v) ((uint32_t)((uint32_t)(v) << BP_AIPS_PACRE_SP1) & BM_AIPS_PACRE_SP1) /*! @brief Set the SP1 field to a new value. */ #define BW_AIPS_PACRE_SP1(x, v) (BITBAND_ACCESS32(HW_AIPS_PACRE_ADDR(x), BP_AIPS_PACRE_SP1) = (v)) /*@}*/ /*! * @name Register AIPS_PACRE, field TP0[28] (RW) * * Determines whether the peripheral allows accesses from an untrusted master. * When this bit is set and an access is attempted by an untrusted master, the * access terminates with an error response and no peripheral access initiates. * * Values: * - 0 - Accesses from an untrusted master are allowed. * - 1 - Accesses from an untrusted master are not allowed. */ /*@{*/ #define BP_AIPS_PACRE_TP0 (28U) /*!< Bit position for AIPS_PACRE_TP0. */ #define BM_AIPS_PACRE_TP0 (0x10000000U) /*!< Bit mask for AIPS_PACRE_TP0. */ #define BS_AIPS_PACRE_TP0 (1U) /*!< Bit field size in bits for AIPS_PACRE_TP0. */ /*! @brief Read current value of the AIPS_PACRE_TP0 field. */ #define BR_AIPS_PACRE_TP0(x) (BITBAND_ACCESS32(HW_AIPS_PACRE_ADDR(x), BP_AIPS_PACRE_TP0)) /*! @brief Format value for bitfield AIPS_PACRE_TP0. */ #define BF_AIPS_PACRE_TP0(v) ((uint32_t)((uint32_t)(v) << BP_AIPS_PACRE_TP0) & BM_AIPS_PACRE_TP0) /*! @brief Set the TP0 field to a new value. */ #define BW_AIPS_PACRE_TP0(x, v) (BITBAND_ACCESS32(HW_AIPS_PACRE_ADDR(x), BP_AIPS_PACRE_TP0) = (v)) /*@}*/ /*! * @name Register AIPS_PACRE, field WP0[29] (RW) * * Determines whether the peripheral allows write accesses. When this field is * set and a write access is attempted, access terminates with an error response * and no peripheral access initiates. * * Values: * - 0 - This peripheral allows write accesses. * - 1 - This peripheral is write protected. */ /*@{*/ #define BP_AIPS_PACRE_WP0 (29U) /*!< Bit position for AIPS_PACRE_WP0. */ #define BM_AIPS_PACRE_WP0 (0x20000000U) /*!< Bit mask for AIPS_PACRE_WP0. */ #define BS_AIPS_PACRE_WP0 (1U) /*!< Bit field size in bits for AIPS_PACRE_WP0. */ /*! @brief Read current value of the AIPS_PACRE_WP0 field. */ #define BR_AIPS_PACRE_WP0(x) (BITBAND_ACCESS32(HW_AIPS_PACRE_ADDR(x), BP_AIPS_PACRE_WP0)) /*! @brief Format value for bitfield AIPS_PACRE_WP0. */ #define BF_AIPS_PACRE_WP0(v) ((uint32_t)((uint32_t)(v) << BP_AIPS_PACRE_WP0) & BM_AIPS_PACRE_WP0) /*! @brief Set the WP0 field to a new value. */ #define BW_AIPS_PACRE_WP0(x, v) (BITBAND_ACCESS32(HW_AIPS_PACRE_ADDR(x), BP_AIPS_PACRE_WP0) = (v)) /*@}*/ /*! * @name Register AIPS_PACRE, field SP0[30] (RW) * * Determines whether the peripheral requires supervisor privilege level for * accesses. When this field is set, the master privilege level must indicate the * supervisor access attribute, and the MPRx[MPLn] control field for the master * must be set. If not, access terminates with an error response and no peripheral * access initiates. * * Values: * - 0 - This peripheral does not require supervisor privilege level for * accesses. * - 1 - This peripheral requires supervisor privilege level for accesses. */ /*@{*/ #define BP_AIPS_PACRE_SP0 (30U) /*!< Bit position for AIPS_PACRE_SP0. */ #define BM_AIPS_PACRE_SP0 (0x40000000U) /*!< Bit mask for AIPS_PACRE_SP0. */ #define BS_AIPS_PACRE_SP0 (1U) /*!< Bit field size in bits for AIPS_PACRE_SP0. */ /*! @brief Read current value of the AIPS_PACRE_SP0 field. */ #define BR_AIPS_PACRE_SP0(x) (BITBAND_ACCESS32(HW_AIPS_PACRE_ADDR(x), BP_AIPS_PACRE_SP0)) /*! @brief Format value for bitfield AIPS_PACRE_SP0. */ #define BF_AIPS_PACRE_SP0(v) ((uint32_t)((uint32_t)(v) << BP_AIPS_PACRE_SP0) & BM_AIPS_PACRE_SP0) /*! @brief Set the SP0 field to a new value. */ #define BW_AIPS_PACRE_SP0(x, v) (BITBAND_ACCESS32(HW_AIPS_PACRE_ADDR(x), BP_AIPS_PACRE_SP0) = (v)) /*@}*/ /******************************************************************************* * HW_AIPS_PACRF - Peripheral Access Control Register ******************************************************************************/ /*! * @brief HW_AIPS_PACRF - Peripheral Access Control Register (RW) * * Reset value: 0x44444444U * * This section describes PACR registers E-P, which control peripheral slots * 32-127. See PACRPeripheral Access Control Register for the description of these * registers. */ typedef union _hw_aips_pacrf { uint32_t U; struct _hw_aips_pacrf_bitfields { uint32_t TP7 : 1; /*!< [0] Trusted Protect */ uint32_t WP7 : 1; /*!< [1] Write Protect */ uint32_t SP7 : 1; /*!< [2] Supervisor Protect */ uint32_t RESERVED0 : 1; /*!< [3] */ uint32_t TP6 : 1; /*!< [4] Trusted Protect */ uint32_t WP6 : 1; /*!< [5] Write Protect */ uint32_t SP6 : 1; /*!< [6] Supervisor Protect */ uint32_t RESERVED1 : 1; /*!< [7] */ uint32_t TP5 : 1; /*!< [8] Trusted Protect */ uint32_t WP5 : 1; /*!< [9] Write Protect */ uint32_t SP5 : 1; /*!< [10] Supervisor Protect */ uint32_t RESERVED2 : 1; /*!< [11] */ uint32_t TP4 : 1; /*!< [12] Trusted Protect */ uint32_t WP4 : 1; /*!< [13] Write Protect */ uint32_t SP4 : 1; /*!< [14] Supervisor Protect */ uint32_t RESERVED3 : 1; /*!< [15] */ uint32_t TP3 : 1; /*!< [16] Trusted Protect */ uint32_t WP3 : 1; /*!< [17] Write Protect */ uint32_t SP3 : 1; /*!< [18] Supervisor Protect */ uint32_t RESERVED4 : 1; /*!< [19] */ uint32_t TP2 : 1; /*!< [20] Trusted Protect */ uint32_t WP2 : 1; /*!< [21] Write Protect */ uint32_t SP2 : 1; /*!< [22] Supervisor Protect */ uint32_t RESERVED5 : 1; /*!< [23] */ uint32_t TP1 : 1; /*!< [24] Trusted Protect */ uint32_t WP1 : 1; /*!< [25] Write Protect */ uint32_t SP1 : 1; /*!< [26] Supervisor Protect */ uint32_t RESERVED6 : 1; /*!< [27] */ uint32_t TP0 : 1; /*!< [28] Trusted Protect */ uint32_t WP0 : 1; /*!< [29] Write Protect */ uint32_t SP0 : 1; /*!< [30] Supervisor Protect */ uint32_t RESERVED7 : 1; /*!< [31] */ } B; } hw_aips_pacrf_t; /*! * @name Constants and macros for entire AIPS_PACRF register */ /*@{*/ #define HW_AIPS_PACRF_ADDR(x) ((x) + 0x44U) #define HW_AIPS_PACRF(x) (*(__IO hw_aips_pacrf_t *) HW_AIPS_PACRF_ADDR(x)) #define HW_AIPS_PACRF_RD(x) (HW_AIPS_PACRF(x).U) #define HW_AIPS_PACRF_WR(x, v) (HW_AIPS_PACRF(x).U = (v)) #define HW_AIPS_PACRF_SET(x, v) (HW_AIPS_PACRF_WR(x, HW_AIPS_PACRF_RD(x) | (v))) #define HW_AIPS_PACRF_CLR(x, v) (HW_AIPS_PACRF_WR(x, HW_AIPS_PACRF_RD(x) & ~(v))) #define HW_AIPS_PACRF_TOG(x, v) (HW_AIPS_PACRF_WR(x, HW_AIPS_PACRF_RD(x) ^ (v))) /*@}*/ /* * Constants & macros for individual AIPS_PACRF bitfields */ /*! * @name Register AIPS_PACRF, field TP7[0] (RW) * * Determines whether the peripheral allows accesses from an untrusted master. * When this field is set and an access is attempted by an untrusted master, the * access terminates with an error response and no peripheral access initiates. * * Values: * - 0 - Accesses from an untrusted master are allowed. * - 1 - Accesses from an untrusted master are not allowed. */ /*@{*/ #define BP_AIPS_PACRF_TP7 (0U) /*!< Bit position for AIPS_PACRF_TP7. */ #define BM_AIPS_PACRF_TP7 (0x00000001U) /*!< Bit mask for AIPS_PACRF_TP7. */ #define BS_AIPS_PACRF_TP7 (1U) /*!< Bit field size in bits for AIPS_PACRF_TP7. */ /*! @brief Read current value of the AIPS_PACRF_TP7 field. */ #define BR_AIPS_PACRF_TP7(x) (BITBAND_ACCESS32(HW_AIPS_PACRF_ADDR(x), BP_AIPS_PACRF_TP7)) /*! @brief Format value for bitfield AIPS_PACRF_TP7. */ #define BF_AIPS_PACRF_TP7(v) ((uint32_t)((uint32_t)(v) << BP_AIPS_PACRF_TP7) & BM_AIPS_PACRF_TP7) /*! @brief Set the TP7 field to a new value. */ #define BW_AIPS_PACRF_TP7(x, v) (BITBAND_ACCESS32(HW_AIPS_PACRF_ADDR(x), BP_AIPS_PACRF_TP7) = (v)) /*@}*/ /*! * @name Register AIPS_PACRF, field WP7[1] (RW) * * Determines whether the peripheral allows write accesses. When this field is * set and a write access is attempted, access terminates with an error response * and no peripheral access initiates. * * Values: * - 0 - This peripheral allows write accesses. * - 1 - This peripheral is write protected. */ /*@{*/ #define BP_AIPS_PACRF_WP7 (1U) /*!< Bit position for AIPS_PACRF_WP7. */ #define BM_AIPS_PACRF_WP7 (0x00000002U) /*!< Bit mask for AIPS_PACRF_WP7. */ #define BS_AIPS_PACRF_WP7 (1U) /*!< Bit field size in bits for AIPS_PACRF_WP7. */ /*! @brief Read current value of the AIPS_PACRF_WP7 field. */ #define BR_AIPS_PACRF_WP7(x) (BITBAND_ACCESS32(HW_AIPS_PACRF_ADDR(x), BP_AIPS_PACRF_WP7)) /*! @brief Format value for bitfield AIPS_PACRF_WP7. */ #define BF_AIPS_PACRF_WP7(v) ((uint32_t)((uint32_t)(v) << BP_AIPS_PACRF_WP7) & BM_AIPS_PACRF_WP7) /*! @brief Set the WP7 field to a new value. */ #define BW_AIPS_PACRF_WP7(x, v) (BITBAND_ACCESS32(HW_AIPS_PACRF_ADDR(x), BP_AIPS_PACRF_WP7) = (v)) /*@}*/ /*! * @name Register AIPS_PACRF, field SP7[2] (RW) * * Determines whether the peripheral requires supervisor privilege level for * accesses. When this field is set, the master privilege level must indicate the * supervisor access attribute, and the MPRx[MPLn] control field for the master * must be set. If not, access terminates with an error response and no peripheral * access initiates. * * Values: * - 0 - This peripheral does not require supervisor privilege level for * accesses. * - 1 - This peripheral requires supervisor privilege level for accesses. */ /*@{*/ #define BP_AIPS_PACRF_SP7 (2U) /*!< Bit position for AIPS_PACRF_SP7. */ #define BM_AIPS_PACRF_SP7 (0x00000004U) /*!< Bit mask for AIPS_PACRF_SP7. */ #define BS_AIPS_PACRF_SP7 (1U) /*!< Bit field size in bits for AIPS_PACRF_SP7. */ /*! @brief Read current value of the AIPS_PACRF_SP7 field. */ #define BR_AIPS_PACRF_SP7(x) (BITBAND_ACCESS32(HW_AIPS_PACRF_ADDR(x), BP_AIPS_PACRF_SP7)) /*! @brief Format value for bitfield AIPS_PACRF_SP7. */ #define BF_AIPS_PACRF_SP7(v) ((uint32_t)((uint32_t)(v) << BP_AIPS_PACRF_SP7) & BM_AIPS_PACRF_SP7) /*! @brief Set the SP7 field to a new value. */ #define BW_AIPS_PACRF_SP7(x, v) (BITBAND_ACCESS32(HW_AIPS_PACRF_ADDR(x), BP_AIPS_PACRF_SP7) = (v)) /*@}*/ /*! * @name Register AIPS_PACRF, field TP6[4] (RW) * * Determines whether the peripheral allows accesses from an untrusted master. * When this field is set and an access is attempted by an untrusted master, the * access terminates with an error response and no peripheral access initiates. * * Values: * - 0 - Accesses from an untrusted master are allowed. * - 1 - Accesses from an untrusted master are not allowed. */ /*@{*/ #define BP_AIPS_PACRF_TP6 (4U) /*!< Bit position for AIPS_PACRF_TP6. */ #define BM_AIPS_PACRF_TP6 (0x00000010U) /*!< Bit mask for AIPS_PACRF_TP6. */ #define BS_AIPS_PACRF_TP6 (1U) /*!< Bit field size in bits for AIPS_PACRF_TP6. */ /*! @brief Read current value of the AIPS_PACRF_TP6 field. */ #define BR_AIPS_PACRF_TP6(x) (BITBAND_ACCESS32(HW_AIPS_PACRF_ADDR(x), BP_AIPS_PACRF_TP6)) /*! @brief Format value for bitfield AIPS_PACRF_TP6. */ #define BF_AIPS_PACRF_TP6(v) ((uint32_t)((uint32_t)(v) << BP_AIPS_PACRF_TP6) & BM_AIPS_PACRF_TP6) /*! @brief Set the TP6 field to a new value. */ #define BW_AIPS_PACRF_TP6(x, v) (BITBAND_ACCESS32(HW_AIPS_PACRF_ADDR(x), BP_AIPS_PACRF_TP6) = (v)) /*@}*/ /*! * @name Register AIPS_PACRF, field WP6[5] (RW) * * Determines whether the peripheral allows write accesses. When this field is * set and a write access is attempted, access terminates with an error response * and no peripheral access initiates. * * Values: * - 0 - This peripheral allows write accesses. * - 1 - This peripheral is write protected. */ /*@{*/ #define BP_AIPS_PACRF_WP6 (5U) /*!< Bit position for AIPS_PACRF_WP6. */ #define BM_AIPS_PACRF_WP6 (0x00000020U) /*!< Bit mask for AIPS_PACRF_WP6. */ #define BS_AIPS_PACRF_WP6 (1U) /*!< Bit field size in bits for AIPS_PACRF_WP6. */ /*! @brief Read current value of the AIPS_PACRF_WP6 field. */ #define BR_AIPS_PACRF_WP6(x) (BITBAND_ACCESS32(HW_AIPS_PACRF_ADDR(x), BP_AIPS_PACRF_WP6)) /*! @brief Format value for bitfield AIPS_PACRF_WP6. */ #define BF_AIPS_PACRF_WP6(v) ((uint32_t)((uint32_t)(v) << BP_AIPS_PACRF_WP6) & BM_AIPS_PACRF_WP6) /*! @brief Set the WP6 field to a new value. */ #define BW_AIPS_PACRF_WP6(x, v) (BITBAND_ACCESS32(HW_AIPS_PACRF_ADDR(x), BP_AIPS_PACRF_WP6) = (v)) /*@}*/ /*! * @name Register AIPS_PACRF, field SP6[6] (RW) * * Determines whether the peripheral requires supervisor privilege level for * accesses. When this field is set, the master privilege level must indicate the * supervisor access attribute, and the MPRx[MPLn] control field for the master * must be set. If not, access terminates with an error response and no peripheral * access initiates. * * Values: * - 0 - This peripheral does not require supervisor privilege level for * accesses. * - 1 - This peripheral requires supervisor privilege level for accesses. */ /*@{*/ #define BP_AIPS_PACRF_SP6 (6U) /*!< Bit position for AIPS_PACRF_SP6. */ #define BM_AIPS_PACRF_SP6 (0x00000040U) /*!< Bit mask for AIPS_PACRF_SP6. */ #define BS_AIPS_PACRF_SP6 (1U) /*!< Bit field size in bits for AIPS_PACRF_SP6. */ /*! @brief Read current value of the AIPS_PACRF_SP6 field. */ #define BR_AIPS_PACRF_SP6(x) (BITBAND_ACCESS32(HW_AIPS_PACRF_ADDR(x), BP_AIPS_PACRF_SP6)) /*! @brief Format value for bitfield AIPS_PACRF_SP6. */ #define BF_AIPS_PACRF_SP6(v) ((uint32_t)((uint32_t)(v) << BP_AIPS_PACRF_SP6) & BM_AIPS_PACRF_SP6) /*! @brief Set the SP6 field to a new value. */ #define BW_AIPS_PACRF_SP6(x, v) (BITBAND_ACCESS32(HW_AIPS_PACRF_ADDR(x), BP_AIPS_PACRF_SP6) = (v)) /*@}*/ /*! * @name Register AIPS_PACRF, field TP5[8] (RW) * * Determines whether the peripheral allows accesses from an untrusted master. * When this field is set and an access is attempted by an untrusted master, the * access terminates with an error response and no peripheral access initiates. * * Values: * - 0 - Accesses from an untrusted master are allowed. * - 1 - Accesses from an untrusted master are not allowed. */ /*@{*/ #define BP_AIPS_PACRF_TP5 (8U) /*!< Bit position for AIPS_PACRF_TP5. */ #define BM_AIPS_PACRF_TP5 (0x00000100U) /*!< Bit mask for AIPS_PACRF_TP5. */ #define BS_AIPS_PACRF_TP5 (1U) /*!< Bit field size in bits for AIPS_PACRF_TP5. */ /*! @brief Read current value of the AIPS_PACRF_TP5 field. */ #define BR_AIPS_PACRF_TP5(x) (BITBAND_ACCESS32(HW_AIPS_PACRF_ADDR(x), BP_AIPS_PACRF_TP5)) /*! @brief Format value for bitfield AIPS_PACRF_TP5. */ #define BF_AIPS_PACRF_TP5(v) ((uint32_t)((uint32_t)(v) << BP_AIPS_PACRF_TP5) & BM_AIPS_PACRF_TP5) /*! @brief Set the TP5 field to a new value. */ #define BW_AIPS_PACRF_TP5(x, v) (BITBAND_ACCESS32(HW_AIPS_PACRF_ADDR(x), BP_AIPS_PACRF_TP5) = (v)) /*@}*/ /*! * @name Register AIPS_PACRF, field WP5[9] (RW) * * Determines whether the peripheral allows write accesses. When this field is * set and a write access is attempted, access terminates with an error response * and no peripheral access initiates. * * Values: * - 0 - This peripheral allows write accesses. * - 1 - This peripheral is write protected. */ /*@{*/ #define BP_AIPS_PACRF_WP5 (9U) /*!< Bit position for AIPS_PACRF_WP5. */ #define BM_AIPS_PACRF_WP5 (0x00000200U) /*!< Bit mask for AIPS_PACRF_WP5. */ #define BS_AIPS_PACRF_WP5 (1U) /*!< Bit field size in bits for AIPS_PACRF_WP5. */ /*! @brief Read current value of the AIPS_PACRF_WP5 field. */ #define BR_AIPS_PACRF_WP5(x) (BITBAND_ACCESS32(HW_AIPS_PACRF_ADDR(x), BP_AIPS_PACRF_WP5)) /*! @brief Format value for bitfield AIPS_PACRF_WP5. */ #define BF_AIPS_PACRF_WP5(v) ((uint32_t)((uint32_t)(v) << BP_AIPS_PACRF_WP5) & BM_AIPS_PACRF_WP5) /*! @brief Set the WP5 field to a new value. */ #define BW_AIPS_PACRF_WP5(x, v) (BITBAND_ACCESS32(HW_AIPS_PACRF_ADDR(x), BP_AIPS_PACRF_WP5) = (v)) /*@}*/ /*! * @name Register AIPS_PACRF, field SP5[10] (RW) * * Determines whether the peripheral requires supervisor privilege level for * accesses. When this field is set, the master privilege level must indicate the * supervisor access attribute, and the MPRx[MPLn] control field for the master * must be set. If not, access terminates with an error response and no peripheral * access initiates. * * Values: * - 0 - This peripheral does not require supervisor privilege level for * accesses. * - 1 - This peripheral requires supervisor privilege level for accesses. */ /*@{*/ #define BP_AIPS_PACRF_SP5 (10U) /*!< Bit position for AIPS_PACRF_SP5. */ #define BM_AIPS_PACRF_SP5 (0x00000400U) /*!< Bit mask for AIPS_PACRF_SP5. */ #define BS_AIPS_PACRF_SP5 (1U) /*!< Bit field size in bits for AIPS_PACRF_SP5. */ /*! @brief Read current value of the AIPS_PACRF_SP5 field. */ #define BR_AIPS_PACRF_SP5(x) (BITBAND_ACCESS32(HW_AIPS_PACRF_ADDR(x), BP_AIPS_PACRF_SP5)) /*! @brief Format value for bitfield AIPS_PACRF_SP5. */ #define BF_AIPS_PACRF_SP5(v) ((uint32_t)((uint32_t)(v) << BP_AIPS_PACRF_SP5) & BM_AIPS_PACRF_SP5) /*! @brief Set the SP5 field to a new value. */ #define BW_AIPS_PACRF_SP5(x, v) (BITBAND_ACCESS32(HW_AIPS_PACRF_ADDR(x), BP_AIPS_PACRF_SP5) = (v)) /*@}*/ /*! * @name Register AIPS_PACRF, field TP4[12] (RW) * * Determines whether the peripheral allows accesses from an untrusted master. * When this bit is set and an access is attempted by an untrusted master, the * access terminates with an error response and no peripheral access initiates. * * Values: * - 0 - Accesses from an untrusted master are allowed. * - 1 - Accesses from an untrusted master are not allowed. */ /*@{*/ #define BP_AIPS_PACRF_TP4 (12U) /*!< Bit position for AIPS_PACRF_TP4. */ #define BM_AIPS_PACRF_TP4 (0x00001000U) /*!< Bit mask for AIPS_PACRF_TP4. */ #define BS_AIPS_PACRF_TP4 (1U) /*!< Bit field size in bits for AIPS_PACRF_TP4. */ /*! @brief Read current value of the AIPS_PACRF_TP4 field. */ #define BR_AIPS_PACRF_TP4(x) (BITBAND_ACCESS32(HW_AIPS_PACRF_ADDR(x), BP_AIPS_PACRF_TP4)) /*! @brief Format value for bitfield AIPS_PACRF_TP4. */ #define BF_AIPS_PACRF_TP4(v) ((uint32_t)((uint32_t)(v) << BP_AIPS_PACRF_TP4) & BM_AIPS_PACRF_TP4) /*! @brief Set the TP4 field to a new value. */ #define BW_AIPS_PACRF_TP4(x, v) (BITBAND_ACCESS32(HW_AIPS_PACRF_ADDR(x), BP_AIPS_PACRF_TP4) = (v)) /*@}*/ /*! * @name Register AIPS_PACRF, field WP4[13] (RW) * * Determines whether the peripheral allows write accesses. When this field is * set and a write access is attempted, access terminates with an error response * and no peripheral access initiates. * * Values: * - 0 - This peripheral allows write accesses. * - 1 - This peripheral is write protected. */ /*@{*/ #define BP_AIPS_PACRF_WP4 (13U) /*!< Bit position for AIPS_PACRF_WP4. */ #define BM_AIPS_PACRF_WP4 (0x00002000U) /*!< Bit mask for AIPS_PACRF_WP4. */ #define BS_AIPS_PACRF_WP4 (1U) /*!< Bit field size in bits for AIPS_PACRF_WP4. */ /*! @brief Read current value of the AIPS_PACRF_WP4 field. */ #define BR_AIPS_PACRF_WP4(x) (BITBAND_ACCESS32(HW_AIPS_PACRF_ADDR(x), BP_AIPS_PACRF_WP4)) /*! @brief Format value for bitfield AIPS_PACRF_WP4. */ #define BF_AIPS_PACRF_WP4(v) ((uint32_t)((uint32_t)(v) << BP_AIPS_PACRF_WP4) & BM_AIPS_PACRF_WP4) /*! @brief Set the WP4 field to a new value. */ #define BW_AIPS_PACRF_WP4(x, v) (BITBAND_ACCESS32(HW_AIPS_PACRF_ADDR(x), BP_AIPS_PACRF_WP4) = (v)) /*@}*/ /*! * @name Register AIPS_PACRF, field SP4[14] (RW) * * Determines whether the peripheral requires supervisor privilege level for * access. When this bit is set, the master privilege level must indicate the * supervisor access attribute, and the MPRx[MPLn] control bit for the master must be * set. If not, access terminates with an error response and no peripheral access * initiates. * * Values: * - 0 - This peripheral does not require supervisor privilege level for * accesses. * - 1 - This peripheral requires supervisor privilege level for accesses. */ /*@{*/ #define BP_AIPS_PACRF_SP4 (14U) /*!< Bit position for AIPS_PACRF_SP4. */ #define BM_AIPS_PACRF_SP4 (0x00004000U) /*!< Bit mask for AIPS_PACRF_SP4. */ #define BS_AIPS_PACRF_SP4 (1U) /*!< Bit field size in bits for AIPS_PACRF_SP4. */ /*! @brief Read current value of the AIPS_PACRF_SP4 field. */ #define BR_AIPS_PACRF_SP4(x) (BITBAND_ACCESS32(HW_AIPS_PACRF_ADDR(x), BP_AIPS_PACRF_SP4)) /*! @brief Format value for bitfield AIPS_PACRF_SP4. */ #define BF_AIPS_PACRF_SP4(v) ((uint32_t)((uint32_t)(v) << BP_AIPS_PACRF_SP4) & BM_AIPS_PACRF_SP4) /*! @brief Set the SP4 field to a new value. */ #define BW_AIPS_PACRF_SP4(x, v) (BITBAND_ACCESS32(HW_AIPS_PACRF_ADDR(x), BP_AIPS_PACRF_SP4) = (v)) /*@}*/ /*! * @name Register AIPS_PACRF, field TP3[16] (RW) * * Determines whether the peripheral allows accesses from an untrusted master. * When this field is set and an access is attempted by an untrusted master, the * access terminates with an error response and no peripheral access initiates. * * Values: * - 0 - Accesses from an untrusted master are allowed. * - 1 - Accesses from an untrusted master are not allowed. */ /*@{*/ #define BP_AIPS_PACRF_TP3 (16U) /*!< Bit position for AIPS_PACRF_TP3. */ #define BM_AIPS_PACRF_TP3 (0x00010000U) /*!< Bit mask for AIPS_PACRF_TP3. */ #define BS_AIPS_PACRF_TP3 (1U) /*!< Bit field size in bits for AIPS_PACRF_TP3. */ /*! @brief Read current value of the AIPS_PACRF_TP3 field. */ #define BR_AIPS_PACRF_TP3(x) (BITBAND_ACCESS32(HW_AIPS_PACRF_ADDR(x), BP_AIPS_PACRF_TP3)) /*! @brief Format value for bitfield AIPS_PACRF_TP3. */ #define BF_AIPS_PACRF_TP3(v) ((uint32_t)((uint32_t)(v) << BP_AIPS_PACRF_TP3) & BM_AIPS_PACRF_TP3) /*! @brief Set the TP3 field to a new value. */ #define BW_AIPS_PACRF_TP3(x, v) (BITBAND_ACCESS32(HW_AIPS_PACRF_ADDR(x), BP_AIPS_PACRF_TP3) = (v)) /*@}*/ /*! * @name Register AIPS_PACRF, field WP3[17] (RW) * * Determines whether the peripheral allows write accesss. When this bit is set * and a write access is attempted, access terminates with an error response and * no peripheral access initiates. * * Values: * - 0 - This peripheral allows write accesses. * - 1 - This peripheral is write protected. */ /*@{*/ #define BP_AIPS_PACRF_WP3 (17U) /*!< Bit position for AIPS_PACRF_WP3. */ #define BM_AIPS_PACRF_WP3 (0x00020000U) /*!< Bit mask for AIPS_PACRF_WP3. */ #define BS_AIPS_PACRF_WP3 (1U) /*!< Bit field size in bits for AIPS_PACRF_WP3. */ /*! @brief Read current value of the AIPS_PACRF_WP3 field. */ #define BR_AIPS_PACRF_WP3(x) (BITBAND_ACCESS32(HW_AIPS_PACRF_ADDR(x), BP_AIPS_PACRF_WP3)) /*! @brief Format value for bitfield AIPS_PACRF_WP3. */ #define BF_AIPS_PACRF_WP3(v) ((uint32_t)((uint32_t)(v) << BP_AIPS_PACRF_WP3) & BM_AIPS_PACRF_WP3) /*! @brief Set the WP3 field to a new value. */ #define BW_AIPS_PACRF_WP3(x, v) (BITBAND_ACCESS32(HW_AIPS_PACRF_ADDR(x), BP_AIPS_PACRF_WP3) = (v)) /*@}*/ /*! * @name Register AIPS_PACRF, field SP3[18] (RW) * * Determines whether the peripheral requires supervisor privilege level for * accesses. When this field is set, the master privilege level must indicate the * supervisor access attribute, and the MPRx[MPLn] control field for the master * must be set. If not, access terminates with an error response and no peripheral * access initiates. * * Values: * - 0 - This peripheral does not require supervisor privilege level for * accesses. * - 1 - This peripheral requires supervisor privilege level for accesses. */ /*@{*/ #define BP_AIPS_PACRF_SP3 (18U) /*!< Bit position for AIPS_PACRF_SP3. */ #define BM_AIPS_PACRF_SP3 (0x00040000U) /*!< Bit mask for AIPS_PACRF_SP3. */ #define BS_AIPS_PACRF_SP3 (1U) /*!< Bit field size in bits for AIPS_PACRF_SP3. */ /*! @brief Read current value of the AIPS_PACRF_SP3 field. */ #define BR_AIPS_PACRF_SP3(x) (BITBAND_ACCESS32(HW_AIPS_PACRF_ADDR(x), BP_AIPS_PACRF_SP3)) /*! @brief Format value for bitfield AIPS_PACRF_SP3. */ #define BF_AIPS_PACRF_SP3(v) ((uint32_t)((uint32_t)(v) << BP_AIPS_PACRF_SP3) & BM_AIPS_PACRF_SP3) /*! @brief Set the SP3 field to a new value. */ #define BW_AIPS_PACRF_SP3(x, v) (BITBAND_ACCESS32(HW_AIPS_PACRF_ADDR(x), BP_AIPS_PACRF_SP3) = (v)) /*@}*/ /*! * @name Register AIPS_PACRF, field TP2[20] (RW) * * Determines whether the peripheral allows accesses from an untrusted master. * When this bit is set and an access is attempted by an untrusted master, the * access terminates with an error response and no peripheral access initiates. * * Values: * - 0 - Accesses from an untrusted master are allowed. * - 1 - Accesses from an untrusted master are not allowed. */ /*@{*/ #define BP_AIPS_PACRF_TP2 (20U) /*!< Bit position for AIPS_PACRF_TP2. */ #define BM_AIPS_PACRF_TP2 (0x00100000U) /*!< Bit mask for AIPS_PACRF_TP2. */ #define BS_AIPS_PACRF_TP2 (1U) /*!< Bit field size in bits for AIPS_PACRF_TP2. */ /*! @brief Read current value of the AIPS_PACRF_TP2 field. */ #define BR_AIPS_PACRF_TP2(x) (BITBAND_ACCESS32(HW_AIPS_PACRF_ADDR(x), BP_AIPS_PACRF_TP2)) /*! @brief Format value for bitfield AIPS_PACRF_TP2. */ #define BF_AIPS_PACRF_TP2(v) ((uint32_t)((uint32_t)(v) << BP_AIPS_PACRF_TP2) & BM_AIPS_PACRF_TP2) /*! @brief Set the TP2 field to a new value. */ #define BW_AIPS_PACRF_TP2(x, v) (BITBAND_ACCESS32(HW_AIPS_PACRF_ADDR(x), BP_AIPS_PACRF_TP2) = (v)) /*@}*/ /*! * @name Register AIPS_PACRF, field WP2[21] (RW) * * Determines whether the peripheral allows write accesses. When this field is * set and a write access is attempted, access terminates with an error response * and no peripheral access initiates. * * Values: * - 0 - This peripheral allows write accesses. * - 1 - This peripheral is write protected. */ /*@{*/ #define BP_AIPS_PACRF_WP2 (21U) /*!< Bit position for AIPS_PACRF_WP2. */ #define BM_AIPS_PACRF_WP2 (0x00200000U) /*!< Bit mask for AIPS_PACRF_WP2. */ #define BS_AIPS_PACRF_WP2 (1U) /*!< Bit field size in bits for AIPS_PACRF_WP2. */ /*! @brief Read current value of the AIPS_PACRF_WP2 field. */ #define BR_AIPS_PACRF_WP2(x) (BITBAND_ACCESS32(HW_AIPS_PACRF_ADDR(x), BP_AIPS_PACRF_WP2)) /*! @brief Format value for bitfield AIPS_PACRF_WP2. */ #define BF_AIPS_PACRF_WP2(v) ((uint32_t)((uint32_t)(v) << BP_AIPS_PACRF_WP2) & BM_AIPS_PACRF_WP2) /*! @brief Set the WP2 field to a new value. */ #define BW_AIPS_PACRF_WP2(x, v) (BITBAND_ACCESS32(HW_AIPS_PACRF_ADDR(x), BP_AIPS_PACRF_WP2) = (v)) /*@}*/ /*! * @name Register AIPS_PACRF, field SP2[22] (RW) * * Determines whether the peripheral requires supervisor privilege level for * access. When this bit is set, the master privilege level must indicate the * supervisor access attribute, and the MPRx[MPLn] control bit for the master must be * set. If not, access terminates with an error response and no peripheral access * initiates. * * Values: * - 0 - This peripheral does not require supervisor privilege level for * accesses. * - 1 - This peripheral requires supervisor privilege level for accesses. */ /*@{*/ #define BP_AIPS_PACRF_SP2 (22U) /*!< Bit position for AIPS_PACRF_SP2. */ #define BM_AIPS_PACRF_SP2 (0x00400000U) /*!< Bit mask for AIPS_PACRF_SP2. */ #define BS_AIPS_PACRF_SP2 (1U) /*!< Bit field size in bits for AIPS_PACRF_SP2. */ /*! @brief Read current value of the AIPS_PACRF_SP2 field. */ #define BR_AIPS_PACRF_SP2(x) (BITBAND_ACCESS32(HW_AIPS_PACRF_ADDR(x), BP_AIPS_PACRF_SP2)) /*! @brief Format value for bitfield AIPS_PACRF_SP2. */ #define BF_AIPS_PACRF_SP2(v) ((uint32_t)((uint32_t)(v) << BP_AIPS_PACRF_SP2) & BM_AIPS_PACRF_SP2) /*! @brief Set the SP2 field to a new value. */ #define BW_AIPS_PACRF_SP2(x, v) (BITBAND_ACCESS32(HW_AIPS_PACRF_ADDR(x), BP_AIPS_PACRF_SP2) = (v)) /*@}*/ /*! * @name Register AIPS_PACRF, field TP1[24] (RW) * * Determines whether the peripheral allows accesses from an untrusted master. * When this field is set and an access is attempted by an untrusted master, the * access terminates with an error response and no peripheral access initiates. * * Values: * - 0 - Accesses from an untrusted master are allowed. * - 1 - Accesses from an untrusted master are not allowed. */ /*@{*/ #define BP_AIPS_PACRF_TP1 (24U) /*!< Bit position for AIPS_PACRF_TP1. */ #define BM_AIPS_PACRF_TP1 (0x01000000U) /*!< Bit mask for AIPS_PACRF_TP1. */ #define BS_AIPS_PACRF_TP1 (1U) /*!< Bit field size in bits for AIPS_PACRF_TP1. */ /*! @brief Read current value of the AIPS_PACRF_TP1 field. */ #define BR_AIPS_PACRF_TP1(x) (BITBAND_ACCESS32(HW_AIPS_PACRF_ADDR(x), BP_AIPS_PACRF_TP1)) /*! @brief Format value for bitfield AIPS_PACRF_TP1. */ #define BF_AIPS_PACRF_TP1(v) ((uint32_t)((uint32_t)(v) << BP_AIPS_PACRF_TP1) & BM_AIPS_PACRF_TP1) /*! @brief Set the TP1 field to a new value. */ #define BW_AIPS_PACRF_TP1(x, v) (BITBAND_ACCESS32(HW_AIPS_PACRF_ADDR(x), BP_AIPS_PACRF_TP1) = (v)) /*@}*/ /*! * @name Register AIPS_PACRF, field WP1[25] (RW) * * Determines whether the peripheral allows write accesses. When this field is * set and a write access is attempted, access terminates with an error response * and no peripheral access initiates. * * Values: * - 0 - This peripheral allows write accesses. * - 1 - This peripheral is write protected. */ /*@{*/ #define BP_AIPS_PACRF_WP1 (25U) /*!< Bit position for AIPS_PACRF_WP1. */ #define BM_AIPS_PACRF_WP1 (0x02000000U) /*!< Bit mask for AIPS_PACRF_WP1. */ #define BS_AIPS_PACRF_WP1 (1U) /*!< Bit field size in bits for AIPS_PACRF_WP1. */ /*! @brief Read current value of the AIPS_PACRF_WP1 field. */ #define BR_AIPS_PACRF_WP1(x) (BITBAND_ACCESS32(HW_AIPS_PACRF_ADDR(x), BP_AIPS_PACRF_WP1)) /*! @brief Format value for bitfield AIPS_PACRF_WP1. */ #define BF_AIPS_PACRF_WP1(v) ((uint32_t)((uint32_t)(v) << BP_AIPS_PACRF_WP1) & BM_AIPS_PACRF_WP1) /*! @brief Set the WP1 field to a new value. */ #define BW_AIPS_PACRF_WP1(x, v) (BITBAND_ACCESS32(HW_AIPS_PACRF_ADDR(x), BP_AIPS_PACRF_WP1) = (v)) /*@}*/ /*! * @name Register AIPS_PACRF, field SP1[26] (RW) * * Determines whether the peripheral requires supervisor privilege level for * access. When this field is set, the master privilege level must indicate the * supervisor access attribute, and the MPRx[MPLn] control field for the master must * be set. If not, access terminates with an error response and no peripheral * access initiates. * * Values: * - 0 - This peripheral does not require supervisor privilege level for * accesses. * - 1 - This peripheral requires supervisor privilege level for accesses. */ /*@{*/ #define BP_AIPS_PACRF_SP1 (26U) /*!< Bit position for AIPS_PACRF_SP1. */ #define BM_AIPS_PACRF_SP1 (0x04000000U) /*!< Bit mask for AIPS_PACRF_SP1. */ #define BS_AIPS_PACRF_SP1 (1U) /*!< Bit field size in bits for AIPS_PACRF_SP1. */ /*! @brief Read current value of the AIPS_PACRF_SP1 field. */ #define BR_AIPS_PACRF_SP1(x) (BITBAND_ACCESS32(HW_AIPS_PACRF_ADDR(x), BP_AIPS_PACRF_SP1)) /*! @brief Format value for bitfield AIPS_PACRF_SP1. */ #define BF_AIPS_PACRF_SP1(v) ((uint32_t)((uint32_t)(v) << BP_AIPS_PACRF_SP1) & BM_AIPS_PACRF_SP1) /*! @brief Set the SP1 field to a new value. */ #define BW_AIPS_PACRF_SP1(x, v) (BITBAND_ACCESS32(HW_AIPS_PACRF_ADDR(x), BP_AIPS_PACRF_SP1) = (v)) /*@}*/ /*! * @name Register AIPS_PACRF, field TP0[28] (RW) * * Determines whether the peripheral allows accesses from an untrusted master. * When this bit is set and an access is attempted by an untrusted master, the * access terminates with an error response and no peripheral access initiates. * * Values: * - 0 - Accesses from an untrusted master are allowed. * - 1 - Accesses from an untrusted master are not allowed. */ /*@{*/ #define BP_AIPS_PACRF_TP0 (28U) /*!< Bit position for AIPS_PACRF_TP0. */ #define BM_AIPS_PACRF_TP0 (0x10000000U) /*!< Bit mask for AIPS_PACRF_TP0. */ #define BS_AIPS_PACRF_TP0 (1U) /*!< Bit field size in bits for AIPS_PACRF_TP0. */ /*! @brief Read current value of the AIPS_PACRF_TP0 field. */ #define BR_AIPS_PACRF_TP0(x) (BITBAND_ACCESS32(HW_AIPS_PACRF_ADDR(x), BP_AIPS_PACRF_TP0)) /*! @brief Format value for bitfield AIPS_PACRF_TP0. */ #define BF_AIPS_PACRF_TP0(v) ((uint32_t)((uint32_t)(v) << BP_AIPS_PACRF_TP0) & BM_AIPS_PACRF_TP0) /*! @brief Set the TP0 field to a new value. */ #define BW_AIPS_PACRF_TP0(x, v) (BITBAND_ACCESS32(HW_AIPS_PACRF_ADDR(x), BP_AIPS_PACRF_TP0) = (v)) /*@}*/ /*! * @name Register AIPS_PACRF, field WP0[29] (RW) * * Determines whether the peripheral allows write accesses. When this field is * set and a write access is attempted, access terminates with an error response * and no peripheral access initiates. * * Values: * - 0 - This peripheral allows write accesses. * - 1 - This peripheral is write protected. */ /*@{*/ #define BP_AIPS_PACRF_WP0 (29U) /*!< Bit position for AIPS_PACRF_WP0. */ #define BM_AIPS_PACRF_WP0 (0x20000000U) /*!< Bit mask for AIPS_PACRF_WP0. */ #define BS_AIPS_PACRF_WP0 (1U) /*!< Bit field size in bits for AIPS_PACRF_WP0. */ /*! @brief Read current value of the AIPS_PACRF_WP0 field. */ #define BR_AIPS_PACRF_WP0(x) (BITBAND_ACCESS32(HW_AIPS_PACRF_ADDR(x), BP_AIPS_PACRF_WP0)) /*! @brief Format value for bitfield AIPS_PACRF_WP0. */ #define BF_AIPS_PACRF_WP0(v) ((uint32_t)((uint32_t)(v) << BP_AIPS_PACRF_WP0) & BM_AIPS_PACRF_WP0) /*! @brief Set the WP0 field to a new value. */ #define BW_AIPS_PACRF_WP0(x, v) (BITBAND_ACCESS32(HW_AIPS_PACRF_ADDR(x), BP_AIPS_PACRF_WP0) = (v)) /*@}*/ /*! * @name Register AIPS_PACRF, field SP0[30] (RW) * * Determines whether the peripheral requires supervisor privilege level for * accesses. When this field is set, the master privilege level must indicate the * supervisor access attribute, and the MPRx[MPLn] control field for the master * must be set. If not, access terminates with an error response and no peripheral * access initiates. * * Values: * - 0 - This peripheral does not require supervisor privilege level for * accesses. * - 1 - This peripheral requires supervisor privilege level for accesses. */ /*@{*/ #define BP_AIPS_PACRF_SP0 (30U) /*!< Bit position for AIPS_PACRF_SP0. */ #define BM_AIPS_PACRF_SP0 (0x40000000U) /*!< Bit mask for AIPS_PACRF_SP0. */ #define BS_AIPS_PACRF_SP0 (1U) /*!< Bit field size in bits for AIPS_PACRF_SP0. */ /*! @brief Read current value of the AIPS_PACRF_SP0 field. */ #define BR_AIPS_PACRF_SP0(x) (BITBAND_ACCESS32(HW_AIPS_PACRF_ADDR(x), BP_AIPS_PACRF_SP0)) /*! @brief Format value for bitfield AIPS_PACRF_SP0. */ #define BF_AIPS_PACRF_SP0(v) ((uint32_t)((uint32_t)(v) << BP_AIPS_PACRF_SP0) & BM_AIPS_PACRF_SP0) /*! @brief Set the SP0 field to a new value. */ #define BW_AIPS_PACRF_SP0(x, v) (BITBAND_ACCESS32(HW_AIPS_PACRF_ADDR(x), BP_AIPS_PACRF_SP0) = (v)) /*@}*/ /******************************************************************************* * HW_AIPS_PACRG - Peripheral Access Control Register ******************************************************************************/ /*! * @brief HW_AIPS_PACRG - Peripheral Access Control Register (RW) * * Reset value: 0x44444444U * * This section describes PACR registers E-P, which control peripheral slots * 32-127. See PACRPeripheral Access Control Register for the description of these * registers. */ typedef union _hw_aips_pacrg { uint32_t U; struct _hw_aips_pacrg_bitfields { uint32_t TP7 : 1; /*!< [0] Trusted Protect */ uint32_t WP7 : 1; /*!< [1] Write Protect */ uint32_t SP7 : 1; /*!< [2] Supervisor Protect */ uint32_t RESERVED0 : 1; /*!< [3] */ uint32_t TP6 : 1; /*!< [4] Trusted Protect */ uint32_t WP6 : 1; /*!< [5] Write Protect */ uint32_t SP6 : 1; /*!< [6] Supervisor Protect */ uint32_t RESERVED1 : 1; /*!< [7] */ uint32_t TP5 : 1; /*!< [8] Trusted Protect */ uint32_t WP5 : 1; /*!< [9] Write Protect */ uint32_t SP5 : 1; /*!< [10] Supervisor Protect */ uint32_t RESERVED2 : 1; /*!< [11] */ uint32_t TP4 : 1; /*!< [12] Trusted Protect */ uint32_t WP4 : 1; /*!< [13] Write Protect */ uint32_t SP4 : 1; /*!< [14] Supervisor Protect */ uint32_t RESERVED3 : 1; /*!< [15] */ uint32_t TP3 : 1; /*!< [16] Trusted Protect */ uint32_t WP3 : 1; /*!< [17] Write Protect */ uint32_t SP3 : 1; /*!< [18] Supervisor Protect */ uint32_t RESERVED4 : 1; /*!< [19] */ uint32_t TP2 : 1; /*!< [20] Trusted Protect */ uint32_t WP2 : 1; /*!< [21] Write Protect */ uint32_t SP2 : 1; /*!< [22] Supervisor Protect */ uint32_t RESERVED5 : 1; /*!< [23] */ uint32_t TP1 : 1; /*!< [24] Trusted Protect */ uint32_t WP1 : 1; /*!< [25] Write Protect */ uint32_t SP1 : 1; /*!< [26] Supervisor Protect */ uint32_t RESERVED6 : 1; /*!< [27] */ uint32_t TP0 : 1; /*!< [28] Trusted Protect */ uint32_t WP0 : 1; /*!< [29] Write Protect */ uint32_t SP0 : 1; /*!< [30] Supervisor Protect */ uint32_t RESERVED7 : 1; /*!< [31] */ } B; } hw_aips_pacrg_t; /*! * @name Constants and macros for entire AIPS_PACRG register */ /*@{*/ #define HW_AIPS_PACRG_ADDR(x) ((x) + 0x48U) #define HW_AIPS_PACRG(x) (*(__IO hw_aips_pacrg_t *) HW_AIPS_PACRG_ADDR(x)) #define HW_AIPS_PACRG_RD(x) (HW_AIPS_PACRG(x).U) #define HW_AIPS_PACRG_WR(x, v) (HW_AIPS_PACRG(x).U = (v)) #define HW_AIPS_PACRG_SET(x, v) (HW_AIPS_PACRG_WR(x, HW_AIPS_PACRG_RD(x) | (v))) #define HW_AIPS_PACRG_CLR(x, v) (HW_AIPS_PACRG_WR(x, HW_AIPS_PACRG_RD(x) & ~(v))) #define HW_AIPS_PACRG_TOG(x, v) (HW_AIPS_PACRG_WR(x, HW_AIPS_PACRG_RD(x) ^ (v))) /*@}*/ /* * Constants & macros for individual AIPS_PACRG bitfields */ /*! * @name Register AIPS_PACRG, field TP7[0] (RW) * * Determines whether the peripheral allows accesses from an untrusted master. * When this field is set and an access is attempted by an untrusted master, the * access terminates with an error response and no peripheral access initiates. * * Values: * - 0 - Accesses from an untrusted master are allowed. * - 1 - Accesses from an untrusted master are not allowed. */ /*@{*/ #define BP_AIPS_PACRG_TP7 (0U) /*!< Bit position for AIPS_PACRG_TP7. */ #define BM_AIPS_PACRG_TP7 (0x00000001U) /*!< Bit mask for AIPS_PACRG_TP7. */ #define BS_AIPS_PACRG_TP7 (1U) /*!< Bit field size in bits for AIPS_PACRG_TP7. */ /*! @brief Read current value of the AIPS_PACRG_TP7 field. */ #define BR_AIPS_PACRG_TP7(x) (BITBAND_ACCESS32(HW_AIPS_PACRG_ADDR(x), BP_AIPS_PACRG_TP7)) /*! @brief Format value for bitfield AIPS_PACRG_TP7. */ #define BF_AIPS_PACRG_TP7(v) ((uint32_t)((uint32_t)(v) << BP_AIPS_PACRG_TP7) & BM_AIPS_PACRG_TP7) /*! @brief Set the TP7 field to a new value. */ #define BW_AIPS_PACRG_TP7(x, v) (BITBAND_ACCESS32(HW_AIPS_PACRG_ADDR(x), BP_AIPS_PACRG_TP7) = (v)) /*@}*/ /*! * @name Register AIPS_PACRG, field WP7[1] (RW) * * Determines whether the peripheral allows write accesses. When this field is * set and a write access is attempted, access terminates with an error response * and no peripheral access initiates. * * Values: * - 0 - This peripheral allows write accesses. * - 1 - This peripheral is write protected. */ /*@{*/ #define BP_AIPS_PACRG_WP7 (1U) /*!< Bit position for AIPS_PACRG_WP7. */ #define BM_AIPS_PACRG_WP7 (0x00000002U) /*!< Bit mask for AIPS_PACRG_WP7. */ #define BS_AIPS_PACRG_WP7 (1U) /*!< Bit field size in bits for AIPS_PACRG_WP7. */ /*! @brief Read current value of the AIPS_PACRG_WP7 field. */ #define BR_AIPS_PACRG_WP7(x) (BITBAND_ACCESS32(HW_AIPS_PACRG_ADDR(x), BP_AIPS_PACRG_WP7)) /*! @brief Format value for bitfield AIPS_PACRG_WP7. */ #define BF_AIPS_PACRG_WP7(v) ((uint32_t)((uint32_t)(v) << BP_AIPS_PACRG_WP7) & BM_AIPS_PACRG_WP7) /*! @brief Set the WP7 field to a new value. */ #define BW_AIPS_PACRG_WP7(x, v) (BITBAND_ACCESS32(HW_AIPS_PACRG_ADDR(x), BP_AIPS_PACRG_WP7) = (v)) /*@}*/ /*! * @name Register AIPS_PACRG, field SP7[2] (RW) * * Determines whether the peripheral requires supervisor privilege level for * accesses. When this field is set, the master privilege level must indicate the * supervisor access attribute, and the MPRx[MPLn] control field for the master * must be set. If not, access terminates with an error response and no peripheral * access initiates. * * Values: * - 0 - This peripheral does not require supervisor privilege level for * accesses. * - 1 - This peripheral requires supervisor privilege level for accesses. */ /*@{*/ #define BP_AIPS_PACRG_SP7 (2U) /*!< Bit position for AIPS_PACRG_SP7. */ #define BM_AIPS_PACRG_SP7 (0x00000004U) /*!< Bit mask for AIPS_PACRG_SP7. */ #define BS_AIPS_PACRG_SP7 (1U) /*!< Bit field size in bits for AIPS_PACRG_SP7. */ /*! @brief Read current value of the AIPS_PACRG_SP7 field. */ #define BR_AIPS_PACRG_SP7(x) (BITBAND_ACCESS32(HW_AIPS_PACRG_ADDR(x), BP_AIPS_PACRG_SP7)) /*! @brief Format value for bitfield AIPS_PACRG_SP7. */ #define BF_AIPS_PACRG_SP7(v) ((uint32_t)((uint32_t)(v) << BP_AIPS_PACRG_SP7) & BM_AIPS_PACRG_SP7) /*! @brief Set the SP7 field to a new value. */ #define BW_AIPS_PACRG_SP7(x, v) (BITBAND_ACCESS32(HW_AIPS_PACRG_ADDR(x), BP_AIPS_PACRG_SP7) = (v)) /*@}*/ /*! * @name Register AIPS_PACRG, field TP6[4] (RW) * * Determines whether the peripheral allows accesses from an untrusted master. * When this field is set and an access is attempted by an untrusted master, the * access terminates with an error response and no peripheral access initiates. * * Values: * - 0 - Accesses from an untrusted master are allowed. * - 1 - Accesses from an untrusted master are not allowed. */ /*@{*/ #define BP_AIPS_PACRG_TP6 (4U) /*!< Bit position for AIPS_PACRG_TP6. */ #define BM_AIPS_PACRG_TP6 (0x00000010U) /*!< Bit mask for AIPS_PACRG_TP6. */ #define BS_AIPS_PACRG_TP6 (1U) /*!< Bit field size in bits for AIPS_PACRG_TP6. */ /*! @brief Read current value of the AIPS_PACRG_TP6 field. */ #define BR_AIPS_PACRG_TP6(x) (BITBAND_ACCESS32(HW_AIPS_PACRG_ADDR(x), BP_AIPS_PACRG_TP6)) /*! @brief Format value for bitfield AIPS_PACRG_TP6. */ #define BF_AIPS_PACRG_TP6(v) ((uint32_t)((uint32_t)(v) << BP_AIPS_PACRG_TP6) & BM_AIPS_PACRG_TP6) /*! @brief Set the TP6 field to a new value. */ #define BW_AIPS_PACRG_TP6(x, v) (BITBAND_ACCESS32(HW_AIPS_PACRG_ADDR(x), BP_AIPS_PACRG_TP6) = (v)) /*@}*/ /*! * @name Register AIPS_PACRG, field WP6[5] (RW) * * Determines whether the peripheral allows write accesses. When this field is * set and a write access is attempted, access terminates with an error response * and no peripheral access initiates. * * Values: * - 0 - This peripheral allows write accesses. * - 1 - This peripheral is write protected. */ /*@{*/ #define BP_AIPS_PACRG_WP6 (5U) /*!< Bit position for AIPS_PACRG_WP6. */ #define BM_AIPS_PACRG_WP6 (0x00000020U) /*!< Bit mask for AIPS_PACRG_WP6. */ #define BS_AIPS_PACRG_WP6 (1U) /*!< Bit field size in bits for AIPS_PACRG_WP6. */ /*! @brief Read current value of the AIPS_PACRG_WP6 field. */ #define BR_AIPS_PACRG_WP6(x) (BITBAND_ACCESS32(HW_AIPS_PACRG_ADDR(x), BP_AIPS_PACRG_WP6)) /*! @brief Format value for bitfield AIPS_PACRG_WP6. */ #define BF_AIPS_PACRG_WP6(v) ((uint32_t)((uint32_t)(v) << BP_AIPS_PACRG_WP6) & BM_AIPS_PACRG_WP6) /*! @brief Set the WP6 field to a new value. */ #define BW_AIPS_PACRG_WP6(x, v) (BITBAND_ACCESS32(HW_AIPS_PACRG_ADDR(x), BP_AIPS_PACRG_WP6) = (v)) /*@}*/ /*! * @name Register AIPS_PACRG, field SP6[6] (RW) * * Determines whether the peripheral requires supervisor privilege level for * accesses. When this field is set, the master privilege level must indicate the * supervisor access attribute, and the MPRx[MPLn] control field for the master * must be set. If not, access terminates with an error response and no peripheral * access initiates. * * Values: * - 0 - This peripheral does not require supervisor privilege level for * accesses. * - 1 - This peripheral requires supervisor privilege level for accesses. */ /*@{*/ #define BP_AIPS_PACRG_SP6 (6U) /*!< Bit position for AIPS_PACRG_SP6. */ #define BM_AIPS_PACRG_SP6 (0x00000040U) /*!< Bit mask for AIPS_PACRG_SP6. */ #define BS_AIPS_PACRG_SP6 (1U) /*!< Bit field size in bits for AIPS_PACRG_SP6. */ /*! @brief Read current value of the AIPS_PACRG_SP6 field. */ #define BR_AIPS_PACRG_SP6(x) (BITBAND_ACCESS32(HW_AIPS_PACRG_ADDR(x), BP_AIPS_PACRG_SP6)) /*! @brief Format value for bitfield AIPS_PACRG_SP6. */ #define BF_AIPS_PACRG_SP6(v) ((uint32_t)((uint32_t)(v) << BP_AIPS_PACRG_SP6) & BM_AIPS_PACRG_SP6) /*! @brief Set the SP6 field to a new value. */ #define BW_AIPS_PACRG_SP6(x, v) (BITBAND_ACCESS32(HW_AIPS_PACRG_ADDR(x), BP_AIPS_PACRG_SP6) = (v)) /*@}*/ /*! * @name Register AIPS_PACRG, field TP5[8] (RW) * * Determines whether the peripheral allows accesses from an untrusted master. * When this field is set and an access is attempted by an untrusted master, the * access terminates with an error response and no peripheral access initiates. * * Values: * - 0 - Accesses from an untrusted master are allowed. * - 1 - Accesses from an untrusted master are not allowed. */ /*@{*/ #define BP_AIPS_PACRG_TP5 (8U) /*!< Bit position for AIPS_PACRG_TP5. */ #define BM_AIPS_PACRG_TP5 (0x00000100U) /*!< Bit mask for AIPS_PACRG_TP5. */ #define BS_AIPS_PACRG_TP5 (1U) /*!< Bit field size in bits for AIPS_PACRG_TP5. */ /*! @brief Read current value of the AIPS_PACRG_TP5 field. */ #define BR_AIPS_PACRG_TP5(x) (BITBAND_ACCESS32(HW_AIPS_PACRG_ADDR(x), BP_AIPS_PACRG_TP5)) /*! @brief Format value for bitfield AIPS_PACRG_TP5. */ #define BF_AIPS_PACRG_TP5(v) ((uint32_t)((uint32_t)(v) << BP_AIPS_PACRG_TP5) & BM_AIPS_PACRG_TP5) /*! @brief Set the TP5 field to a new value. */ #define BW_AIPS_PACRG_TP5(x, v) (BITBAND_ACCESS32(HW_AIPS_PACRG_ADDR(x), BP_AIPS_PACRG_TP5) = (v)) /*@}*/ /*! * @name Register AIPS_PACRG, field WP5[9] (RW) * * Determines whether the peripheral allows write accesses. When this field is * set and a write access is attempted, access terminates with an error response * and no peripheral access initiates. * * Values: * - 0 - This peripheral allows write accesses. * - 1 - This peripheral is write protected. */ /*@{*/ #define BP_AIPS_PACRG_WP5 (9U) /*!< Bit position for AIPS_PACRG_WP5. */ #define BM_AIPS_PACRG_WP5 (0x00000200U) /*!< Bit mask for AIPS_PACRG_WP5. */ #define BS_AIPS_PACRG_WP5 (1U) /*!< Bit field size in bits for AIPS_PACRG_WP5. */ /*! @brief Read current value of the AIPS_PACRG_WP5 field. */ #define BR_AIPS_PACRG_WP5(x) (BITBAND_ACCESS32(HW_AIPS_PACRG_ADDR(x), BP_AIPS_PACRG_WP5)) /*! @brief Format value for bitfield AIPS_PACRG_WP5. */ #define BF_AIPS_PACRG_WP5(v) ((uint32_t)((uint32_t)(v) << BP_AIPS_PACRG_WP5) & BM_AIPS_PACRG_WP5) /*! @brief Set the WP5 field to a new value. */ #define BW_AIPS_PACRG_WP5(x, v) (BITBAND_ACCESS32(HW_AIPS_PACRG_ADDR(x), BP_AIPS_PACRG_WP5) = (v)) /*@}*/ /*! * @name Register AIPS_PACRG, field SP5[10] (RW) * * Determines whether the peripheral requires supervisor privilege level for * accesses. When this field is set, the master privilege level must indicate the * supervisor access attribute, and the MPRx[MPLn] control field for the master * must be set. If not, access terminates with an error response and no peripheral * access initiates. * * Values: * - 0 - This peripheral does not require supervisor privilege level for * accesses. * - 1 - This peripheral requires supervisor privilege level for accesses. */ /*@{*/ #define BP_AIPS_PACRG_SP5 (10U) /*!< Bit position for AIPS_PACRG_SP5. */ #define BM_AIPS_PACRG_SP5 (0x00000400U) /*!< Bit mask for AIPS_PACRG_SP5. */ #define BS_AIPS_PACRG_SP5 (1U) /*!< Bit field size in bits for AIPS_PACRG_SP5. */ /*! @brief Read current value of the AIPS_PACRG_SP5 field. */ #define BR_AIPS_PACRG_SP5(x) (BITBAND_ACCESS32(HW_AIPS_PACRG_ADDR(x), BP_AIPS_PACRG_SP5)) /*! @brief Format value for bitfield AIPS_PACRG_SP5. */ #define BF_AIPS_PACRG_SP5(v) ((uint32_t)((uint32_t)(v) << BP_AIPS_PACRG_SP5) & BM_AIPS_PACRG_SP5) /*! @brief Set the SP5 field to a new value. */ #define BW_AIPS_PACRG_SP5(x, v) (BITBAND_ACCESS32(HW_AIPS_PACRG_ADDR(x), BP_AIPS_PACRG_SP5) = (v)) /*@}*/ /*! * @name Register AIPS_PACRG, field TP4[12] (RW) * * Determines whether the peripheral allows accesses from an untrusted master. * When this bit is set and an access is attempted by an untrusted master, the * access terminates with an error response and no peripheral access initiates. * * Values: * - 0 - Accesses from an untrusted master are allowed. * - 1 - Accesses from an untrusted master are not allowed. */ /*@{*/ #define BP_AIPS_PACRG_TP4 (12U) /*!< Bit position for AIPS_PACRG_TP4. */ #define BM_AIPS_PACRG_TP4 (0x00001000U) /*!< Bit mask for AIPS_PACRG_TP4. */ #define BS_AIPS_PACRG_TP4 (1U) /*!< Bit field size in bits for AIPS_PACRG_TP4. */ /*! @brief Read current value of the AIPS_PACRG_TP4 field. */ #define BR_AIPS_PACRG_TP4(x) (BITBAND_ACCESS32(HW_AIPS_PACRG_ADDR(x), BP_AIPS_PACRG_TP4)) /*! @brief Format value for bitfield AIPS_PACRG_TP4. */ #define BF_AIPS_PACRG_TP4(v) ((uint32_t)((uint32_t)(v) << BP_AIPS_PACRG_TP4) & BM_AIPS_PACRG_TP4) /*! @brief Set the TP4 field to a new value. */ #define BW_AIPS_PACRG_TP4(x, v) (BITBAND_ACCESS32(HW_AIPS_PACRG_ADDR(x), BP_AIPS_PACRG_TP4) = (v)) /*@}*/ /*! * @name Register AIPS_PACRG, field WP4[13] (RW) * * Determines whether the peripheral allows write accesses. When this field is * set and a write access is attempted, access terminates with an error response * and no peripheral access initiates. * * Values: * - 0 - This peripheral allows write accesses. * - 1 - This peripheral is write protected. */ /*@{*/ #define BP_AIPS_PACRG_WP4 (13U) /*!< Bit position for AIPS_PACRG_WP4. */ #define BM_AIPS_PACRG_WP4 (0x00002000U) /*!< Bit mask for AIPS_PACRG_WP4. */ #define BS_AIPS_PACRG_WP4 (1U) /*!< Bit field size in bits for AIPS_PACRG_WP4. */ /*! @brief Read current value of the AIPS_PACRG_WP4 field. */ #define BR_AIPS_PACRG_WP4(x) (BITBAND_ACCESS32(HW_AIPS_PACRG_ADDR(x), BP_AIPS_PACRG_WP4)) /*! @brief Format value for bitfield AIPS_PACRG_WP4. */ #define BF_AIPS_PACRG_WP4(v) ((uint32_t)((uint32_t)(v) << BP_AIPS_PACRG_WP4) & BM_AIPS_PACRG_WP4) /*! @brief Set the WP4 field to a new value. */ #define BW_AIPS_PACRG_WP4(x, v) (BITBAND_ACCESS32(HW_AIPS_PACRG_ADDR(x), BP_AIPS_PACRG_WP4) = (v)) /*@}*/ /*! * @name Register AIPS_PACRG, field SP4[14] (RW) * * Determines whether the peripheral requires supervisor privilege level for * access. When this bit is set, the master privilege level must indicate the * supervisor access attribute, and the MPRx[MPLn] control bit for the master must be * set. If not, access terminates with an error response and no peripheral access * initiates. * * Values: * - 0 - This peripheral does not require supervisor privilege level for * accesses. * - 1 - This peripheral requires supervisor privilege level for accesses. */ /*@{*/ #define BP_AIPS_PACRG_SP4 (14U) /*!< Bit position for AIPS_PACRG_SP4. */ #define BM_AIPS_PACRG_SP4 (0x00004000U) /*!< Bit mask for AIPS_PACRG_SP4. */ #define BS_AIPS_PACRG_SP4 (1U) /*!< Bit field size in bits for AIPS_PACRG_SP4. */ /*! @brief Read current value of the AIPS_PACRG_SP4 field. */ #define BR_AIPS_PACRG_SP4(x) (BITBAND_ACCESS32(HW_AIPS_PACRG_ADDR(x), BP_AIPS_PACRG_SP4)) /*! @brief Format value for bitfield AIPS_PACRG_SP4. */ #define BF_AIPS_PACRG_SP4(v) ((uint32_t)((uint32_t)(v) << BP_AIPS_PACRG_SP4) & BM_AIPS_PACRG_SP4) /*! @brief Set the SP4 field to a new value. */ #define BW_AIPS_PACRG_SP4(x, v) (BITBAND_ACCESS32(HW_AIPS_PACRG_ADDR(x), BP_AIPS_PACRG_SP4) = (v)) /*@}*/ /*! * @name Register AIPS_PACRG, field TP3[16] (RW) * * Determines whether the peripheral allows accesses from an untrusted master. * When this field is set and an access is attempted by an untrusted master, the * access terminates with an error response and no peripheral access initiates. * * Values: * - 0 - Accesses from an untrusted master are allowed. * - 1 - Accesses from an untrusted master are not allowed. */ /*@{*/ #define BP_AIPS_PACRG_TP3 (16U) /*!< Bit position for AIPS_PACRG_TP3. */ #define BM_AIPS_PACRG_TP3 (0x00010000U) /*!< Bit mask for AIPS_PACRG_TP3. */ #define BS_AIPS_PACRG_TP3 (1U) /*!< Bit field size in bits for AIPS_PACRG_TP3. */ /*! @brief Read current value of the AIPS_PACRG_TP3 field. */ #define BR_AIPS_PACRG_TP3(x) (BITBAND_ACCESS32(HW_AIPS_PACRG_ADDR(x), BP_AIPS_PACRG_TP3)) /*! @brief Format value for bitfield AIPS_PACRG_TP3. */ #define BF_AIPS_PACRG_TP3(v) ((uint32_t)((uint32_t)(v) << BP_AIPS_PACRG_TP3) & BM_AIPS_PACRG_TP3) /*! @brief Set the TP3 field to a new value. */ #define BW_AIPS_PACRG_TP3(x, v) (BITBAND_ACCESS32(HW_AIPS_PACRG_ADDR(x), BP_AIPS_PACRG_TP3) = (v)) /*@}*/ /*! * @name Register AIPS_PACRG, field WP3[17] (RW) * * Determines whether the peripheral allows write accesss. When this bit is set * and a write access is attempted, access terminates with an error response and * no peripheral access initiates. * * Values: * - 0 - This peripheral allows write accesses. * - 1 - This peripheral is write protected. */ /*@{*/ #define BP_AIPS_PACRG_WP3 (17U) /*!< Bit position for AIPS_PACRG_WP3. */ #define BM_AIPS_PACRG_WP3 (0x00020000U) /*!< Bit mask for AIPS_PACRG_WP3. */ #define BS_AIPS_PACRG_WP3 (1U) /*!< Bit field size in bits for AIPS_PACRG_WP3. */ /*! @brief Read current value of the AIPS_PACRG_WP3 field. */ #define BR_AIPS_PACRG_WP3(x) (BITBAND_ACCESS32(HW_AIPS_PACRG_ADDR(x), BP_AIPS_PACRG_WP3)) /*! @brief Format value for bitfield AIPS_PACRG_WP3. */ #define BF_AIPS_PACRG_WP3(v) ((uint32_t)((uint32_t)(v) << BP_AIPS_PACRG_WP3) & BM_AIPS_PACRG_WP3) /*! @brief Set the WP3 field to a new value. */ #define BW_AIPS_PACRG_WP3(x, v) (BITBAND_ACCESS32(HW_AIPS_PACRG_ADDR(x), BP_AIPS_PACRG_WP3) = (v)) /*@}*/ /*! * @name Register AIPS_PACRG, field SP3[18] (RW) * * Determines whether the peripheral requires supervisor privilege level for * accesses. When this field is set, the master privilege level must indicate the * supervisor access attribute, and the MPRx[MPLn] control field for the master * must be set. If not, access terminates with an error response and no peripheral * access initiates. * * Values: * - 0 - This peripheral does not require supervisor privilege level for * accesses. * - 1 - This peripheral requires supervisor privilege level for accesses. */ /*@{*/ #define BP_AIPS_PACRG_SP3 (18U) /*!< Bit position for AIPS_PACRG_SP3. */ #define BM_AIPS_PACRG_SP3 (0x00040000U) /*!< Bit mask for AIPS_PACRG_SP3. */ #define BS_AIPS_PACRG_SP3 (1U) /*!< Bit field size in bits for AIPS_PACRG_SP3. */ /*! @brief Read current value of the AIPS_PACRG_SP3 field. */ #define BR_AIPS_PACRG_SP3(x) (BITBAND_ACCESS32(HW_AIPS_PACRG_ADDR(x), BP_AIPS_PACRG_SP3)) /*! @brief Format value for bitfield AIPS_PACRG_SP3. */ #define BF_AIPS_PACRG_SP3(v) ((uint32_t)((uint32_t)(v) << BP_AIPS_PACRG_SP3) & BM_AIPS_PACRG_SP3) /*! @brief Set the SP3 field to a new value. */ #define BW_AIPS_PACRG_SP3(x, v) (BITBAND_ACCESS32(HW_AIPS_PACRG_ADDR(x), BP_AIPS_PACRG_SP3) = (v)) /*@}*/ /*! * @name Register AIPS_PACRG, field TP2[20] (RW) * * Determines whether the peripheral allows accesses from an untrusted master. * When this bit is set and an access is attempted by an untrusted master, the * access terminates with an error response and no peripheral access initiates. * * Values: * - 0 - Accesses from an untrusted master are allowed. * - 1 - Accesses from an untrusted master are not allowed. */ /*@{*/ #define BP_AIPS_PACRG_TP2 (20U) /*!< Bit position for AIPS_PACRG_TP2. */ #define BM_AIPS_PACRG_TP2 (0x00100000U) /*!< Bit mask for AIPS_PACRG_TP2. */ #define BS_AIPS_PACRG_TP2 (1U) /*!< Bit field size in bits for AIPS_PACRG_TP2. */ /*! @brief Read current value of the AIPS_PACRG_TP2 field. */ #define BR_AIPS_PACRG_TP2(x) (BITBAND_ACCESS32(HW_AIPS_PACRG_ADDR(x), BP_AIPS_PACRG_TP2)) /*! @brief Format value for bitfield AIPS_PACRG_TP2. */ #define BF_AIPS_PACRG_TP2(v) ((uint32_t)((uint32_t)(v) << BP_AIPS_PACRG_TP2) & BM_AIPS_PACRG_TP2) /*! @brief Set the TP2 field to a new value. */ #define BW_AIPS_PACRG_TP2(x, v) (BITBAND_ACCESS32(HW_AIPS_PACRG_ADDR(x), BP_AIPS_PACRG_TP2) = (v)) /*@}*/ /*! * @name Register AIPS_PACRG, field WP2[21] (RW) * * Determines whether the peripheral allows write accesses. When this field is * set and a write access is attempted, access terminates with an error response * and no peripheral access initiates. * * Values: * - 0 - This peripheral allows write accesses. * - 1 - This peripheral is write protected. */ /*@{*/ #define BP_AIPS_PACRG_WP2 (21U) /*!< Bit position for AIPS_PACRG_WP2. */ #define BM_AIPS_PACRG_WP2 (0x00200000U) /*!< Bit mask for AIPS_PACRG_WP2. */ #define BS_AIPS_PACRG_WP2 (1U) /*!< Bit field size in bits for AIPS_PACRG_WP2. */ /*! @brief Read current value of the AIPS_PACRG_WP2 field. */ #define BR_AIPS_PACRG_WP2(x) (BITBAND_ACCESS32(HW_AIPS_PACRG_ADDR(x), BP_AIPS_PACRG_WP2)) /*! @brief Format value for bitfield AIPS_PACRG_WP2. */ #define BF_AIPS_PACRG_WP2(v) ((uint32_t)((uint32_t)(v) << BP_AIPS_PACRG_WP2) & BM_AIPS_PACRG_WP2) /*! @brief Set the WP2 field to a new value. */ #define BW_AIPS_PACRG_WP2(x, v) (BITBAND_ACCESS32(HW_AIPS_PACRG_ADDR(x), BP_AIPS_PACRG_WP2) = (v)) /*@}*/ /*! * @name Register AIPS_PACRG, field SP2[22] (RW) * * Determines whether the peripheral requires supervisor privilege level for * access. When this bit is set, the master privilege level must indicate the * supervisor access attribute, and the MPRx[MPLn] control bit for the master must be * set. If not, access terminates with an error response and no peripheral access * initiates. * * Values: * - 0 - This peripheral does not require supervisor privilege level for * accesses. * - 1 - This peripheral requires supervisor privilege level for accesses. */ /*@{*/ #define BP_AIPS_PACRG_SP2 (22U) /*!< Bit position for AIPS_PACRG_SP2. */ #define BM_AIPS_PACRG_SP2 (0x00400000U) /*!< Bit mask for AIPS_PACRG_SP2. */ #define BS_AIPS_PACRG_SP2 (1U) /*!< Bit field size in bits for AIPS_PACRG_SP2. */ /*! @brief Read current value of the AIPS_PACRG_SP2 field. */ #define BR_AIPS_PACRG_SP2(x) (BITBAND_ACCESS32(HW_AIPS_PACRG_ADDR(x), BP_AIPS_PACRG_SP2)) /*! @brief Format value for bitfield AIPS_PACRG_SP2. */ #define BF_AIPS_PACRG_SP2(v) ((uint32_t)((uint32_t)(v) << BP_AIPS_PACRG_SP2) & BM_AIPS_PACRG_SP2) /*! @brief Set the SP2 field to a new value. */ #define BW_AIPS_PACRG_SP2(x, v) (BITBAND_ACCESS32(HW_AIPS_PACRG_ADDR(x), BP_AIPS_PACRG_SP2) = (v)) /*@}*/ /*! * @name Register AIPS_PACRG, field TP1[24] (RW) * * Determines whether the peripheral allows accesses from an untrusted master. * When this field is set and an access is attempted by an untrusted master, the * access terminates with an error response and no peripheral access initiates. * * Values: * - 0 - Accesses from an untrusted master are allowed. * - 1 - Accesses from an untrusted master are not allowed. */ /*@{*/ #define BP_AIPS_PACRG_TP1 (24U) /*!< Bit position for AIPS_PACRG_TP1. */ #define BM_AIPS_PACRG_TP1 (0x01000000U) /*!< Bit mask for AIPS_PACRG_TP1. */ #define BS_AIPS_PACRG_TP1 (1U) /*!< Bit field size in bits for AIPS_PACRG_TP1. */ /*! @brief Read current value of the AIPS_PACRG_TP1 field. */ #define BR_AIPS_PACRG_TP1(x) (BITBAND_ACCESS32(HW_AIPS_PACRG_ADDR(x), BP_AIPS_PACRG_TP1)) /*! @brief Format value for bitfield AIPS_PACRG_TP1. */ #define BF_AIPS_PACRG_TP1(v) ((uint32_t)((uint32_t)(v) << BP_AIPS_PACRG_TP1) & BM_AIPS_PACRG_TP1) /*! @brief Set the TP1 field to a new value. */ #define BW_AIPS_PACRG_TP1(x, v) (BITBAND_ACCESS32(HW_AIPS_PACRG_ADDR(x), BP_AIPS_PACRG_TP1) = (v)) /*@}*/ /*! * @name Register AIPS_PACRG, field WP1[25] (RW) * * Determines whether the peripheral allows write accesses. When this field is * set and a write access is attempted, access terminates with an error response * and no peripheral access initiates. * * Values: * - 0 - This peripheral allows write accesses. * - 1 - This peripheral is write protected. */ /*@{*/ #define BP_AIPS_PACRG_WP1 (25U) /*!< Bit position for AIPS_PACRG_WP1. */ #define BM_AIPS_PACRG_WP1 (0x02000000U) /*!< Bit mask for AIPS_PACRG_WP1. */ #define BS_AIPS_PACRG_WP1 (1U) /*!< Bit field size in bits for AIPS_PACRG_WP1. */ /*! @brief Read current value of the AIPS_PACRG_WP1 field. */ #define BR_AIPS_PACRG_WP1(x) (BITBAND_ACCESS32(HW_AIPS_PACRG_ADDR(x), BP_AIPS_PACRG_WP1)) /*! @brief Format value for bitfield AIPS_PACRG_WP1. */ #define BF_AIPS_PACRG_WP1(v) ((uint32_t)((uint32_t)(v) << BP_AIPS_PACRG_WP1) & BM_AIPS_PACRG_WP1) /*! @brief Set the WP1 field to a new value. */ #define BW_AIPS_PACRG_WP1(x, v) (BITBAND_ACCESS32(HW_AIPS_PACRG_ADDR(x), BP_AIPS_PACRG_WP1) = (v)) /*@}*/ /*! * @name Register AIPS_PACRG, field SP1[26] (RW) * * Determines whether the peripheral requires supervisor privilege level for * access. When this field is set, the master privilege level must indicate the * supervisor access attribute, and the MPRx[MPLn] control field for the master must * be set. If not, access terminates with an error response and no peripheral * access initiates. * * Values: * - 0 - This peripheral does not require supervisor privilege level for * accesses. * - 1 - This peripheral requires supervisor privilege level for accesses. */ /*@{*/ #define BP_AIPS_PACRG_SP1 (26U) /*!< Bit position for AIPS_PACRG_SP1. */ #define BM_AIPS_PACRG_SP1 (0x04000000U) /*!< Bit mask for AIPS_PACRG_SP1. */ #define BS_AIPS_PACRG_SP1 (1U) /*!< Bit field size in bits for AIPS_PACRG_SP1. */ /*! @brief Read current value of the AIPS_PACRG_SP1 field. */ #define BR_AIPS_PACRG_SP1(x) (BITBAND_ACCESS32(HW_AIPS_PACRG_ADDR(x), BP_AIPS_PACRG_SP1)) /*! @brief Format value for bitfield AIPS_PACRG_SP1. */ #define BF_AIPS_PACRG_SP1(v) ((uint32_t)((uint32_t)(v) << BP_AIPS_PACRG_SP1) & BM_AIPS_PACRG_SP1) /*! @brief Set the SP1 field to a new value. */ #define BW_AIPS_PACRG_SP1(x, v) (BITBAND_ACCESS32(HW_AIPS_PACRG_ADDR(x), BP_AIPS_PACRG_SP1) = (v)) /*@}*/ /*! * @name Register AIPS_PACRG, field TP0[28] (RW) * * Determines whether the peripheral allows accesses from an untrusted master. * When this bit is set and an access is attempted by an untrusted master, the * access terminates with an error response and no peripheral access initiates. * * Values: * - 0 - Accesses from an untrusted master are allowed. * - 1 - Accesses from an untrusted master are not allowed. */ /*@{*/ #define BP_AIPS_PACRG_TP0 (28U) /*!< Bit position for AIPS_PACRG_TP0. */ #define BM_AIPS_PACRG_TP0 (0x10000000U) /*!< Bit mask for AIPS_PACRG_TP0. */ #define BS_AIPS_PACRG_TP0 (1U) /*!< Bit field size in bits for AIPS_PACRG_TP0. */ /*! @brief Read current value of the AIPS_PACRG_TP0 field. */ #define BR_AIPS_PACRG_TP0(x) (BITBAND_ACCESS32(HW_AIPS_PACRG_ADDR(x), BP_AIPS_PACRG_TP0)) /*! @brief Format value for bitfield AIPS_PACRG_TP0. */ #define BF_AIPS_PACRG_TP0(v) ((uint32_t)((uint32_t)(v) << BP_AIPS_PACRG_TP0) & BM_AIPS_PACRG_TP0) /*! @brief Set the TP0 field to a new value. */ #define BW_AIPS_PACRG_TP0(x, v) (BITBAND_ACCESS32(HW_AIPS_PACRG_ADDR(x), BP_AIPS_PACRG_TP0) = (v)) /*@}*/ /*! * @name Register AIPS_PACRG, field WP0[29] (RW) * * Determines whether the peripheral allows write accesses. When this field is * set and a write access is attempted, access terminates with an error response * and no peripheral access initiates. * * Values: * - 0 - This peripheral allows write accesses. * - 1 - This peripheral is write protected. */ /*@{*/ #define BP_AIPS_PACRG_WP0 (29U) /*!< Bit position for AIPS_PACRG_WP0. */ #define BM_AIPS_PACRG_WP0 (0x20000000U) /*!< Bit mask for AIPS_PACRG_WP0. */ #define BS_AIPS_PACRG_WP0 (1U) /*!< Bit field size in bits for AIPS_PACRG_WP0. */ /*! @brief Read current value of the AIPS_PACRG_WP0 field. */ #define BR_AIPS_PACRG_WP0(x) (BITBAND_ACCESS32(HW_AIPS_PACRG_ADDR(x), BP_AIPS_PACRG_WP0)) /*! @brief Format value for bitfield AIPS_PACRG_WP0. */ #define BF_AIPS_PACRG_WP0(v) ((uint32_t)((uint32_t)(v) << BP_AIPS_PACRG_WP0) & BM_AIPS_PACRG_WP0) /*! @brief Set the WP0 field to a new value. */ #define BW_AIPS_PACRG_WP0(x, v) (BITBAND_ACCESS32(HW_AIPS_PACRG_ADDR(x), BP_AIPS_PACRG_WP0) = (v)) /*@}*/ /*! * @name Register AIPS_PACRG, field SP0[30] (RW) * * Determines whether the peripheral requires supervisor privilege level for * accesses. When this field is set, the master privilege level must indicate the * supervisor access attribute, and the MPRx[MPLn] control field for the master * must be set. If not, access terminates with an error response and no peripheral * access initiates. * * Values: * - 0 - This peripheral does not require supervisor privilege level for * accesses. * - 1 - This peripheral requires supervisor privilege level for accesses. */ /*@{*/ #define BP_AIPS_PACRG_SP0 (30U) /*!< Bit position for AIPS_PACRG_SP0. */ #define BM_AIPS_PACRG_SP0 (0x40000000U) /*!< Bit mask for AIPS_PACRG_SP0. */ #define BS_AIPS_PACRG_SP0 (1U) /*!< Bit field size in bits for AIPS_PACRG_SP0. */ /*! @brief Read current value of the AIPS_PACRG_SP0 field. */ #define BR_AIPS_PACRG_SP0(x) (BITBAND_ACCESS32(HW_AIPS_PACRG_ADDR(x), BP_AIPS_PACRG_SP0)) /*! @brief Format value for bitfield AIPS_PACRG_SP0. */ #define BF_AIPS_PACRG_SP0(v) ((uint32_t)((uint32_t)(v) << BP_AIPS_PACRG_SP0) & BM_AIPS_PACRG_SP0) /*! @brief Set the SP0 field to a new value. */ #define BW_AIPS_PACRG_SP0(x, v) (BITBAND_ACCESS32(HW_AIPS_PACRG_ADDR(x), BP_AIPS_PACRG_SP0) = (v)) /*@}*/ /******************************************************************************* * HW_AIPS_PACRH - Peripheral Access Control Register ******************************************************************************/ /*! * @brief HW_AIPS_PACRH - Peripheral Access Control Register (RW) * * Reset value: 0x44444444U * * This section describes PACR registers E-P, which control peripheral slots * 32-127. See PACRPeripheral Access Control Register for the description of these * registers. */ typedef union _hw_aips_pacrh { uint32_t U; struct _hw_aips_pacrh_bitfields { uint32_t TP7 : 1; /*!< [0] Trusted Protect */ uint32_t WP7 : 1; /*!< [1] Write Protect */ uint32_t SP7 : 1; /*!< [2] Supervisor Protect */ uint32_t RESERVED0 : 1; /*!< [3] */ uint32_t TP6 : 1; /*!< [4] Trusted Protect */ uint32_t WP6 : 1; /*!< [5] Write Protect */ uint32_t SP6 : 1; /*!< [6] Supervisor Protect */ uint32_t RESERVED1 : 1; /*!< [7] */ uint32_t TP5 : 1; /*!< [8] Trusted Protect */ uint32_t WP5 : 1; /*!< [9] Write Protect */ uint32_t SP5 : 1; /*!< [10] Supervisor Protect */ uint32_t RESERVED2 : 1; /*!< [11] */ uint32_t TP4 : 1; /*!< [12] Trusted Protect */ uint32_t WP4 : 1; /*!< [13] Write Protect */ uint32_t SP4 : 1; /*!< [14] Supervisor Protect */ uint32_t RESERVED3 : 1; /*!< [15] */ uint32_t TP3 : 1; /*!< [16] Trusted Protect */ uint32_t WP3 : 1; /*!< [17] Write Protect */ uint32_t SP3 : 1; /*!< [18] Supervisor Protect */ uint32_t RESERVED4 : 1; /*!< [19] */ uint32_t TP2 : 1; /*!< [20] Trusted Protect */ uint32_t WP2 : 1; /*!< [21] Write Protect */ uint32_t SP2 : 1; /*!< [22] Supervisor Protect */ uint32_t RESERVED5 : 1; /*!< [23] */ uint32_t TP1 : 1; /*!< [24] Trusted Protect */ uint32_t WP1 : 1; /*!< [25] Write Protect */ uint32_t SP1 : 1; /*!< [26] Supervisor Protect */ uint32_t RESERVED6 : 1; /*!< [27] */ uint32_t TP0 : 1; /*!< [28] Trusted Protect */ uint32_t WP0 : 1; /*!< [29] Write Protect */ uint32_t SP0 : 1; /*!< [30] Supervisor Protect */ uint32_t RESERVED7 : 1; /*!< [31] */ } B; } hw_aips_pacrh_t; /*! * @name Constants and macros for entire AIPS_PACRH register */ /*@{*/ #define HW_AIPS_PACRH_ADDR(x) ((x) + 0x4CU) #define HW_AIPS_PACRH(x) (*(__IO hw_aips_pacrh_t *) HW_AIPS_PACRH_ADDR(x)) #define HW_AIPS_PACRH_RD(x) (HW_AIPS_PACRH(x).U) #define HW_AIPS_PACRH_WR(x, v) (HW_AIPS_PACRH(x).U = (v)) #define HW_AIPS_PACRH_SET(x, v) (HW_AIPS_PACRH_WR(x, HW_AIPS_PACRH_RD(x) | (v))) #define HW_AIPS_PACRH_CLR(x, v) (HW_AIPS_PACRH_WR(x, HW_AIPS_PACRH_RD(x) & ~(v))) #define HW_AIPS_PACRH_TOG(x, v) (HW_AIPS_PACRH_WR(x, HW_AIPS_PACRH_RD(x) ^ (v))) /*@}*/ /* * Constants & macros for individual AIPS_PACRH bitfields */ /*! * @name Register AIPS_PACRH, field TP7[0] (RW) * * Determines whether the peripheral allows accesses from an untrusted master. * When this field is set and an access is attempted by an untrusted master, the * access terminates with an error response and no peripheral access initiates. * * Values: * - 0 - Accesses from an untrusted master are allowed. * - 1 - Accesses from an untrusted master are not allowed. */ /*@{*/ #define BP_AIPS_PACRH_TP7 (0U) /*!< Bit position for AIPS_PACRH_TP7. */ #define BM_AIPS_PACRH_TP7 (0x00000001U) /*!< Bit mask for AIPS_PACRH_TP7. */ #define BS_AIPS_PACRH_TP7 (1U) /*!< Bit field size in bits for AIPS_PACRH_TP7. */ /*! @brief Read current value of the AIPS_PACRH_TP7 field. */ #define BR_AIPS_PACRH_TP7(x) (BITBAND_ACCESS32(HW_AIPS_PACRH_ADDR(x), BP_AIPS_PACRH_TP7)) /*! @brief Format value for bitfield AIPS_PACRH_TP7. */ #define BF_AIPS_PACRH_TP7(v) ((uint32_t)((uint32_t)(v) << BP_AIPS_PACRH_TP7) & BM_AIPS_PACRH_TP7) /*! @brief Set the TP7 field to a new value. */ #define BW_AIPS_PACRH_TP7(x, v) (BITBAND_ACCESS32(HW_AIPS_PACRH_ADDR(x), BP_AIPS_PACRH_TP7) = (v)) /*@}*/ /*! * @name Register AIPS_PACRH, field WP7[1] (RW) * * Determines whether the peripheral allows write accesses. When this field is * set and a write access is attempted, access terminates with an error response * and no peripheral access initiates. * * Values: * - 0 - This peripheral allows write accesses. * - 1 - This peripheral is write protected. */ /*@{*/ #define BP_AIPS_PACRH_WP7 (1U) /*!< Bit position for AIPS_PACRH_WP7. */ #define BM_AIPS_PACRH_WP7 (0x00000002U) /*!< Bit mask for AIPS_PACRH_WP7. */ #define BS_AIPS_PACRH_WP7 (1U) /*!< Bit field size in bits for AIPS_PACRH_WP7. */ /*! @brief Read current value of the AIPS_PACRH_WP7 field. */ #define BR_AIPS_PACRH_WP7(x) (BITBAND_ACCESS32(HW_AIPS_PACRH_ADDR(x), BP_AIPS_PACRH_WP7)) /*! @brief Format value for bitfield AIPS_PACRH_WP7. */ #define BF_AIPS_PACRH_WP7(v) ((uint32_t)((uint32_t)(v) << BP_AIPS_PACRH_WP7) & BM_AIPS_PACRH_WP7) /*! @brief Set the WP7 field to a new value. */ #define BW_AIPS_PACRH_WP7(x, v) (BITBAND_ACCESS32(HW_AIPS_PACRH_ADDR(x), BP_AIPS_PACRH_WP7) = (v)) /*@}*/ /*! * @name Register AIPS_PACRH, field SP7[2] (RW) * * Determines whether the peripheral requires supervisor privilege level for * accesses. When this field is set, the master privilege level must indicate the * supervisor access attribute, and the MPRx[MPLn] control field for the master * must be set. If not, access terminates with an error response and no peripheral * access initiates. * * Values: * - 0 - This peripheral does not require supervisor privilege level for * accesses. * - 1 - This peripheral requires supervisor privilege level for accesses. */ /*@{*/ #define BP_AIPS_PACRH_SP7 (2U) /*!< Bit position for AIPS_PACRH_SP7. */ #define BM_AIPS_PACRH_SP7 (0x00000004U) /*!< Bit mask for AIPS_PACRH_SP7. */ #define BS_AIPS_PACRH_SP7 (1U) /*!< Bit field size in bits for AIPS_PACRH_SP7. */ /*! @brief Read current value of the AIPS_PACRH_SP7 field. */ #define BR_AIPS_PACRH_SP7(x) (BITBAND_ACCESS32(HW_AIPS_PACRH_ADDR(x), BP_AIPS_PACRH_SP7)) /*! @brief Format value for bitfield AIPS_PACRH_SP7. */ #define BF_AIPS_PACRH_SP7(v) ((uint32_t)((uint32_t)(v) << BP_AIPS_PACRH_SP7) & BM_AIPS_PACRH_SP7) /*! @brief Set the SP7 field to a new value. */ #define BW_AIPS_PACRH_SP7(x, v) (BITBAND_ACCESS32(HW_AIPS_PACRH_ADDR(x), BP_AIPS_PACRH_SP7) = (v)) /*@}*/ /*! * @name Register AIPS_PACRH, field TP6[4] (RW) * * Determines whether the peripheral allows accesses from an untrusted master. * When this field is set and an access is attempted by an untrusted master, the * access terminates with an error response and no peripheral access initiates. * * Values: * - 0 - Accesses from an untrusted master are allowed. * - 1 - Accesses from an untrusted master are not allowed. */ /*@{*/ #define BP_AIPS_PACRH_TP6 (4U) /*!< Bit position for AIPS_PACRH_TP6. */ #define BM_AIPS_PACRH_TP6 (0x00000010U) /*!< Bit mask for AIPS_PACRH_TP6. */ #define BS_AIPS_PACRH_TP6 (1U) /*!< Bit field size in bits for AIPS_PACRH_TP6. */ /*! @brief Read current value of the AIPS_PACRH_TP6 field. */ #define BR_AIPS_PACRH_TP6(x) (BITBAND_ACCESS32(HW_AIPS_PACRH_ADDR(x), BP_AIPS_PACRH_TP6)) /*! @brief Format value for bitfield AIPS_PACRH_TP6. */ #define BF_AIPS_PACRH_TP6(v) ((uint32_t)((uint32_t)(v) << BP_AIPS_PACRH_TP6) & BM_AIPS_PACRH_TP6) /*! @brief Set the TP6 field to a new value. */ #define BW_AIPS_PACRH_TP6(x, v) (BITBAND_ACCESS32(HW_AIPS_PACRH_ADDR(x), BP_AIPS_PACRH_TP6) = (v)) /*@}*/ /*! * @name Register AIPS_PACRH, field WP6[5] (RW) * * Determines whether the peripheral allows write accesses. When this field is * set and a write access is attempted, access terminates with an error response * and no peripheral access initiates. * * Values: * - 0 - This peripheral allows write accesses. * - 1 - This peripheral is write protected. */ /*@{*/ #define BP_AIPS_PACRH_WP6 (5U) /*!< Bit position for AIPS_PACRH_WP6. */ #define BM_AIPS_PACRH_WP6 (0x00000020U) /*!< Bit mask for AIPS_PACRH_WP6. */ #define BS_AIPS_PACRH_WP6 (1U) /*!< Bit field size in bits for AIPS_PACRH_WP6. */ /*! @brief Read current value of the AIPS_PACRH_WP6 field. */ #define BR_AIPS_PACRH_WP6(x) (BITBAND_ACCESS32(HW_AIPS_PACRH_ADDR(x), BP_AIPS_PACRH_WP6)) /*! @brief Format value for bitfield AIPS_PACRH_WP6. */ #define BF_AIPS_PACRH_WP6(v) ((uint32_t)((uint32_t)(v) << BP_AIPS_PACRH_WP6) & BM_AIPS_PACRH_WP6) /*! @brief Set the WP6 field to a new value. */ #define BW_AIPS_PACRH_WP6(x, v) (BITBAND_ACCESS32(HW_AIPS_PACRH_ADDR(x), BP_AIPS_PACRH_WP6) = (v)) /*@}*/ /*! * @name Register AIPS_PACRH, field SP6[6] (RW) * * Determines whether the peripheral requires supervisor privilege level for * accesses. When this field is set, the master privilege level must indicate the * supervisor access attribute, and the MPRx[MPLn] control field for the master * must be set. If not, access terminates with an error response and no peripheral * access initiates. * * Values: * - 0 - This peripheral does not require supervisor privilege level for * accesses. * - 1 - This peripheral requires supervisor privilege level for accesses. */ /*@{*/ #define BP_AIPS_PACRH_SP6 (6U) /*!< Bit position for AIPS_PACRH_SP6. */ #define BM_AIPS_PACRH_SP6 (0x00000040U) /*!< Bit mask for AIPS_PACRH_SP6. */ #define BS_AIPS_PACRH_SP6 (1U) /*!< Bit field size in bits for AIPS_PACRH_SP6. */ /*! @brief Read current value of the AIPS_PACRH_SP6 field. */ #define BR_AIPS_PACRH_SP6(x) (BITBAND_ACCESS32(HW_AIPS_PACRH_ADDR(x), BP_AIPS_PACRH_SP6)) /*! @brief Format value for bitfield AIPS_PACRH_SP6. */ #define BF_AIPS_PACRH_SP6(v) ((uint32_t)((uint32_t)(v) << BP_AIPS_PACRH_SP6) & BM_AIPS_PACRH_SP6) /*! @brief Set the SP6 field to a new value. */ #define BW_AIPS_PACRH_SP6(x, v) (BITBAND_ACCESS32(HW_AIPS_PACRH_ADDR(x), BP_AIPS_PACRH_SP6) = (v)) /*@}*/ /*! * @name Register AIPS_PACRH, field TP5[8] (RW) * * Determines whether the peripheral allows accesses from an untrusted master. * When this field is set and an access is attempted by an untrusted master, the * access terminates with an error response and no peripheral access initiates. * * Values: * - 0 - Accesses from an untrusted master are allowed. * - 1 - Accesses from an untrusted master are not allowed. */ /*@{*/ #define BP_AIPS_PACRH_TP5 (8U) /*!< Bit position for AIPS_PACRH_TP5. */ #define BM_AIPS_PACRH_TP5 (0x00000100U) /*!< Bit mask for AIPS_PACRH_TP5. */ #define BS_AIPS_PACRH_TP5 (1U) /*!< Bit field size in bits for AIPS_PACRH_TP5. */ /*! @brief Read current value of the AIPS_PACRH_TP5 field. */ #define BR_AIPS_PACRH_TP5(x) (BITBAND_ACCESS32(HW_AIPS_PACRH_ADDR(x), BP_AIPS_PACRH_TP5)) /*! @brief Format value for bitfield AIPS_PACRH_TP5. */ #define BF_AIPS_PACRH_TP5(v) ((uint32_t)((uint32_t)(v) << BP_AIPS_PACRH_TP5) & BM_AIPS_PACRH_TP5) /*! @brief Set the TP5 field to a new value. */ #define BW_AIPS_PACRH_TP5(x, v) (BITBAND_ACCESS32(HW_AIPS_PACRH_ADDR(x), BP_AIPS_PACRH_TP5) = (v)) /*@}*/ /*! * @name Register AIPS_PACRH, field WP5[9] (RW) * * Determines whether the peripheral allows write accesses. When this field is * set and a write access is attempted, access terminates with an error response * and no peripheral access initiates. * * Values: * - 0 - This peripheral allows write accesses. * - 1 - This peripheral is write protected. */ /*@{*/ #define BP_AIPS_PACRH_WP5 (9U) /*!< Bit position for AIPS_PACRH_WP5. */ #define BM_AIPS_PACRH_WP5 (0x00000200U) /*!< Bit mask for AIPS_PACRH_WP5. */ #define BS_AIPS_PACRH_WP5 (1U) /*!< Bit field size in bits for AIPS_PACRH_WP5. */ /*! @brief Read current value of the AIPS_PACRH_WP5 field. */ #define BR_AIPS_PACRH_WP5(x) (BITBAND_ACCESS32(HW_AIPS_PACRH_ADDR(x), BP_AIPS_PACRH_WP5)) /*! @brief Format value for bitfield AIPS_PACRH_WP5. */ #define BF_AIPS_PACRH_WP5(v) ((uint32_t)((uint32_t)(v) << BP_AIPS_PACRH_WP5) & BM_AIPS_PACRH_WP5) /*! @brief Set the WP5 field to a new value. */ #define BW_AIPS_PACRH_WP5(x, v) (BITBAND_ACCESS32(HW_AIPS_PACRH_ADDR(x), BP_AIPS_PACRH_WP5) = (v)) /*@}*/ /*! * @name Register AIPS_PACRH, field SP5[10] (RW) * * Determines whether the peripheral requires supervisor privilege level for * accesses. When this field is set, the master privilege level must indicate the * supervisor access attribute, and the MPRx[MPLn] control field for the master * must be set. If not, access terminates with an error response and no peripheral * access initiates. * * Values: * - 0 - This peripheral does not require supervisor privilege level for * accesses. * - 1 - This peripheral requires supervisor privilege level for accesses. */ /*@{*/ #define BP_AIPS_PACRH_SP5 (10U) /*!< Bit position for AIPS_PACRH_SP5. */ #define BM_AIPS_PACRH_SP5 (0x00000400U) /*!< Bit mask for AIPS_PACRH_SP5. */ #define BS_AIPS_PACRH_SP5 (1U) /*!< Bit field size in bits for AIPS_PACRH_SP5. */ /*! @brief Read current value of the AIPS_PACRH_SP5 field. */ #define BR_AIPS_PACRH_SP5(x) (BITBAND_ACCESS32(HW_AIPS_PACRH_ADDR(x), BP_AIPS_PACRH_SP5)) /*! @brief Format value for bitfield AIPS_PACRH_SP5. */ #define BF_AIPS_PACRH_SP5(v) ((uint32_t)((uint32_t)(v) << BP_AIPS_PACRH_SP5) & BM_AIPS_PACRH_SP5) /*! @brief Set the SP5 field to a new value. */ #define BW_AIPS_PACRH_SP5(x, v) (BITBAND_ACCESS32(HW_AIPS_PACRH_ADDR(x), BP_AIPS_PACRH_SP5) = (v)) /*@}*/ /*! * @name Register AIPS_PACRH, field TP4[12] (RW) * * Determines whether the peripheral allows accesses from an untrusted master. * When this bit is set and an access is attempted by an untrusted master, the * access terminates with an error response and no peripheral access initiates. * * Values: * - 0 - Accesses from an untrusted master are allowed. * - 1 - Accesses from an untrusted master are not allowed. */ /*@{*/ #define BP_AIPS_PACRH_TP4 (12U) /*!< Bit position for AIPS_PACRH_TP4. */ #define BM_AIPS_PACRH_TP4 (0x00001000U) /*!< Bit mask for AIPS_PACRH_TP4. */ #define BS_AIPS_PACRH_TP4 (1U) /*!< Bit field size in bits for AIPS_PACRH_TP4. */ /*! @brief Read current value of the AIPS_PACRH_TP4 field. */ #define BR_AIPS_PACRH_TP4(x) (BITBAND_ACCESS32(HW_AIPS_PACRH_ADDR(x), BP_AIPS_PACRH_TP4)) /*! @brief Format value for bitfield AIPS_PACRH_TP4. */ #define BF_AIPS_PACRH_TP4(v) ((uint32_t)((uint32_t)(v) << BP_AIPS_PACRH_TP4) & BM_AIPS_PACRH_TP4) /*! @brief Set the TP4 field to a new value. */ #define BW_AIPS_PACRH_TP4(x, v) (BITBAND_ACCESS32(HW_AIPS_PACRH_ADDR(x), BP_AIPS_PACRH_TP4) = (v)) /*@}*/ /*! * @name Register AIPS_PACRH, field WP4[13] (RW) * * Determines whether the peripheral allows write accesses. When this field is * set and a write access is attempted, access terminates with an error response * and no peripheral access initiates. * * Values: * - 0 - This peripheral allows write accesses. * - 1 - This peripheral is write protected. */ /*@{*/ #define BP_AIPS_PACRH_WP4 (13U) /*!< Bit position for AIPS_PACRH_WP4. */ #define BM_AIPS_PACRH_WP4 (0x00002000U) /*!< Bit mask for AIPS_PACRH_WP4. */ #define BS_AIPS_PACRH_WP4 (1U) /*!< Bit field size in bits for AIPS_PACRH_WP4. */ /*! @brief Read current value of the AIPS_PACRH_WP4 field. */ #define BR_AIPS_PACRH_WP4(x) (BITBAND_ACCESS32(HW_AIPS_PACRH_ADDR(x), BP_AIPS_PACRH_WP4)) /*! @brief Format value for bitfield AIPS_PACRH_WP4. */ #define BF_AIPS_PACRH_WP4(v) ((uint32_t)((uint32_t)(v) << BP_AIPS_PACRH_WP4) & BM_AIPS_PACRH_WP4) /*! @brief Set the WP4 field to a new value. */ #define BW_AIPS_PACRH_WP4(x, v) (BITBAND_ACCESS32(HW_AIPS_PACRH_ADDR(x), BP_AIPS_PACRH_WP4) = (v)) /*@}*/ /*! * @name Register AIPS_PACRH, field SP4[14] (RW) * * Determines whether the peripheral requires supervisor privilege level for * access. When this bit is set, the master privilege level must indicate the * supervisor access attribute, and the MPRx[MPLn] control bit for the master must be * set. If not, access terminates with an error response and no peripheral access * initiates. * * Values: * - 0 - This peripheral does not require supervisor privilege level for * accesses. * - 1 - This peripheral requires supervisor privilege level for accesses. */ /*@{*/ #define BP_AIPS_PACRH_SP4 (14U) /*!< Bit position for AIPS_PACRH_SP4. */ #define BM_AIPS_PACRH_SP4 (0x00004000U) /*!< Bit mask for AIPS_PACRH_SP4. */ #define BS_AIPS_PACRH_SP4 (1U) /*!< Bit field size in bits for AIPS_PACRH_SP4. */ /*! @brief Read current value of the AIPS_PACRH_SP4 field. */ #define BR_AIPS_PACRH_SP4(x) (BITBAND_ACCESS32(HW_AIPS_PACRH_ADDR(x), BP_AIPS_PACRH_SP4)) /*! @brief Format value for bitfield AIPS_PACRH_SP4. */ #define BF_AIPS_PACRH_SP4(v) ((uint32_t)((uint32_t)(v) << BP_AIPS_PACRH_SP4) & BM_AIPS_PACRH_SP4) /*! @brief Set the SP4 field to a new value. */ #define BW_AIPS_PACRH_SP4(x, v) (BITBAND_ACCESS32(HW_AIPS_PACRH_ADDR(x), BP_AIPS_PACRH_SP4) = (v)) /*@}*/ /*! * @name Register AIPS_PACRH, field TP3[16] (RW) * * Determines whether the peripheral allows accesses from an untrusted master. * When this field is set and an access is attempted by an untrusted master, the * access terminates with an error response and no peripheral access initiates. * * Values: * - 0 - Accesses from an untrusted master are allowed. * - 1 - Accesses from an untrusted master are not allowed. */ /*@{*/ #define BP_AIPS_PACRH_TP3 (16U) /*!< Bit position for AIPS_PACRH_TP3. */ #define BM_AIPS_PACRH_TP3 (0x00010000U) /*!< Bit mask for AIPS_PACRH_TP3. */ #define BS_AIPS_PACRH_TP3 (1U) /*!< Bit field size in bits for AIPS_PACRH_TP3. */ /*! @brief Read current value of the AIPS_PACRH_TP3 field. */ #define BR_AIPS_PACRH_TP3(x) (BITBAND_ACCESS32(HW_AIPS_PACRH_ADDR(x), BP_AIPS_PACRH_TP3)) /*! @brief Format value for bitfield AIPS_PACRH_TP3. */ #define BF_AIPS_PACRH_TP3(v) ((uint32_t)((uint32_t)(v) << BP_AIPS_PACRH_TP3) & BM_AIPS_PACRH_TP3) /*! @brief Set the TP3 field to a new value. */ #define BW_AIPS_PACRH_TP3(x, v) (BITBAND_ACCESS32(HW_AIPS_PACRH_ADDR(x), BP_AIPS_PACRH_TP3) = (v)) /*@}*/ /*! * @name Register AIPS_PACRH, field WP3[17] (RW) * * Determines whether the peripheral allows write accesss. When this bit is set * and a write access is attempted, access terminates with an error response and * no peripheral access initiates. * * Values: * - 0 - This peripheral allows write accesses. * - 1 - This peripheral is write protected. */ /*@{*/ #define BP_AIPS_PACRH_WP3 (17U) /*!< Bit position for AIPS_PACRH_WP3. */ #define BM_AIPS_PACRH_WP3 (0x00020000U) /*!< Bit mask for AIPS_PACRH_WP3. */ #define BS_AIPS_PACRH_WP3 (1U) /*!< Bit field size in bits for AIPS_PACRH_WP3. */ /*! @brief Read current value of the AIPS_PACRH_WP3 field. */ #define BR_AIPS_PACRH_WP3(x) (BITBAND_ACCESS32(HW_AIPS_PACRH_ADDR(x), BP_AIPS_PACRH_WP3)) /*! @brief Format value for bitfield AIPS_PACRH_WP3. */ #define BF_AIPS_PACRH_WP3(v) ((uint32_t)((uint32_t)(v) << BP_AIPS_PACRH_WP3) & BM_AIPS_PACRH_WP3) /*! @brief Set the WP3 field to a new value. */ #define BW_AIPS_PACRH_WP3(x, v) (BITBAND_ACCESS32(HW_AIPS_PACRH_ADDR(x), BP_AIPS_PACRH_WP3) = (v)) /*@}*/ /*! * @name Register AIPS_PACRH, field SP3[18] (RW) * * Determines whether the peripheral requires supervisor privilege level for * accesses. When this field is set, the master privilege level must indicate the * supervisor access attribute, and the MPRx[MPLn] control field for the master * must be set. If not, access terminates with an error response and no peripheral * access initiates. * * Values: * - 0 - This peripheral does not require supervisor privilege level for * accesses. * - 1 - This peripheral requires supervisor privilege level for accesses. */ /*@{*/ #define BP_AIPS_PACRH_SP3 (18U) /*!< Bit position for AIPS_PACRH_SP3. */ #define BM_AIPS_PACRH_SP3 (0x00040000U) /*!< Bit mask for AIPS_PACRH_SP3. */ #define BS_AIPS_PACRH_SP3 (1U) /*!< Bit field size in bits for AIPS_PACRH_SP3. */ /*! @brief Read current value of the AIPS_PACRH_SP3 field. */ #define BR_AIPS_PACRH_SP3(x) (BITBAND_ACCESS32(HW_AIPS_PACRH_ADDR(x), BP_AIPS_PACRH_SP3)) /*! @brief Format value for bitfield AIPS_PACRH_SP3. */ #define BF_AIPS_PACRH_SP3(v) ((uint32_t)((uint32_t)(v) << BP_AIPS_PACRH_SP3) & BM_AIPS_PACRH_SP3) /*! @brief Set the SP3 field to a new value. */ #define BW_AIPS_PACRH_SP3(x, v) (BITBAND_ACCESS32(HW_AIPS_PACRH_ADDR(x), BP_AIPS_PACRH_SP3) = (v)) /*@}*/ /*! * @name Register AIPS_PACRH, field TP2[20] (RW) * * Determines whether the peripheral allows accesses from an untrusted master. * When this bit is set and an access is attempted by an untrusted master, the * access terminates with an error response and no peripheral access initiates. * * Values: * - 0 - Accesses from an untrusted master are allowed. * - 1 - Accesses from an untrusted master are not allowed. */ /*@{*/ #define BP_AIPS_PACRH_TP2 (20U) /*!< Bit position for AIPS_PACRH_TP2. */ #define BM_AIPS_PACRH_TP2 (0x00100000U) /*!< Bit mask for AIPS_PACRH_TP2. */ #define BS_AIPS_PACRH_TP2 (1U) /*!< Bit field size in bits for AIPS_PACRH_TP2. */ /*! @brief Read current value of the AIPS_PACRH_TP2 field. */ #define BR_AIPS_PACRH_TP2(x) (BITBAND_ACCESS32(HW_AIPS_PACRH_ADDR(x), BP_AIPS_PACRH_TP2)) /*! @brief Format value for bitfield AIPS_PACRH_TP2. */ #define BF_AIPS_PACRH_TP2(v) ((uint32_t)((uint32_t)(v) << BP_AIPS_PACRH_TP2) & BM_AIPS_PACRH_TP2) /*! @brief Set the TP2 field to a new value. */ #define BW_AIPS_PACRH_TP2(x, v) (BITBAND_ACCESS32(HW_AIPS_PACRH_ADDR(x), BP_AIPS_PACRH_TP2) = (v)) /*@}*/ /*! * @name Register AIPS_PACRH, field WP2[21] (RW) * * Determines whether the peripheral allows write accesses. When this field is * set and a write access is attempted, access terminates with an error response * and no peripheral access initiates. * * Values: * - 0 - This peripheral allows write accesses. * - 1 - This peripheral is write protected. */ /*@{*/ #define BP_AIPS_PACRH_WP2 (21U) /*!< Bit position for AIPS_PACRH_WP2. */ #define BM_AIPS_PACRH_WP2 (0x00200000U) /*!< Bit mask for AIPS_PACRH_WP2. */ #define BS_AIPS_PACRH_WP2 (1U) /*!< Bit field size in bits for AIPS_PACRH_WP2. */ /*! @brief Read current value of the AIPS_PACRH_WP2 field. */ #define BR_AIPS_PACRH_WP2(x) (BITBAND_ACCESS32(HW_AIPS_PACRH_ADDR(x), BP_AIPS_PACRH_WP2)) /*! @brief Format value for bitfield AIPS_PACRH_WP2. */ #define BF_AIPS_PACRH_WP2(v) ((uint32_t)((uint32_t)(v) << BP_AIPS_PACRH_WP2) & BM_AIPS_PACRH_WP2) /*! @brief Set the WP2 field to a new value. */ #define BW_AIPS_PACRH_WP2(x, v) (BITBAND_ACCESS32(HW_AIPS_PACRH_ADDR(x), BP_AIPS_PACRH_WP2) = (v)) /*@}*/ /*! * @name Register AIPS_PACRH, field SP2[22] (RW) * * Determines whether the peripheral requires supervisor privilege level for * access. When this bit is set, the master privilege level must indicate the * supervisor access attribute, and the MPRx[MPLn] control bit for the master must be * set. If not, access terminates with an error response and no peripheral access * initiates. * * Values: * - 0 - This peripheral does not require supervisor privilege level for * accesses. * - 1 - This peripheral requires supervisor privilege level for accesses. */ /*@{*/ #define BP_AIPS_PACRH_SP2 (22U) /*!< Bit position for AIPS_PACRH_SP2. */ #define BM_AIPS_PACRH_SP2 (0x00400000U) /*!< Bit mask for AIPS_PACRH_SP2. */ #define BS_AIPS_PACRH_SP2 (1U) /*!< Bit field size in bits for AIPS_PACRH_SP2. */ /*! @brief Read current value of the AIPS_PACRH_SP2 field. */ #define BR_AIPS_PACRH_SP2(x) (BITBAND_ACCESS32(HW_AIPS_PACRH_ADDR(x), BP_AIPS_PACRH_SP2)) /*! @brief Format value for bitfield AIPS_PACRH_SP2. */ #define BF_AIPS_PACRH_SP2(v) ((uint32_t)((uint32_t)(v) << BP_AIPS_PACRH_SP2) & BM_AIPS_PACRH_SP2) /*! @brief Set the SP2 field to a new value. */ #define BW_AIPS_PACRH_SP2(x, v) (BITBAND_ACCESS32(HW_AIPS_PACRH_ADDR(x), BP_AIPS_PACRH_SP2) = (v)) /*@}*/ /*! * @name Register AIPS_PACRH, field TP1[24] (RW) * * Determines whether the peripheral allows accesses from an untrusted master. * When this field is set and an access is attempted by an untrusted master, the * access terminates with an error response and no peripheral access initiates. * * Values: * - 0 - Accesses from an untrusted master are allowed. * - 1 - Accesses from an untrusted master are not allowed. */ /*@{*/ #define BP_AIPS_PACRH_TP1 (24U) /*!< Bit position for AIPS_PACRH_TP1. */ #define BM_AIPS_PACRH_TP1 (0x01000000U) /*!< Bit mask for AIPS_PACRH_TP1. */ #define BS_AIPS_PACRH_TP1 (1U) /*!< Bit field size in bits for AIPS_PACRH_TP1. */ /*! @brief Read current value of the AIPS_PACRH_TP1 field. */ #define BR_AIPS_PACRH_TP1(x) (BITBAND_ACCESS32(HW_AIPS_PACRH_ADDR(x), BP_AIPS_PACRH_TP1)) /*! @brief Format value for bitfield AIPS_PACRH_TP1. */ #define BF_AIPS_PACRH_TP1(v) ((uint32_t)((uint32_t)(v) << BP_AIPS_PACRH_TP1) & BM_AIPS_PACRH_TP1) /*! @brief Set the TP1 field to a new value. */ #define BW_AIPS_PACRH_TP1(x, v) (BITBAND_ACCESS32(HW_AIPS_PACRH_ADDR(x), BP_AIPS_PACRH_TP1) = (v)) /*@}*/ /*! * @name Register AIPS_PACRH, field WP1[25] (RW) * * Determines whether the peripheral allows write accesses. When this field is * set and a write access is attempted, access terminates with an error response * and no peripheral access initiates. * * Values: * - 0 - This peripheral allows write accesses. * - 1 - This peripheral is write protected. */ /*@{*/ #define BP_AIPS_PACRH_WP1 (25U) /*!< Bit position for AIPS_PACRH_WP1. */ #define BM_AIPS_PACRH_WP1 (0x02000000U) /*!< Bit mask for AIPS_PACRH_WP1. */ #define BS_AIPS_PACRH_WP1 (1U) /*!< Bit field size in bits for AIPS_PACRH_WP1. */ /*! @brief Read current value of the AIPS_PACRH_WP1 field. */ #define BR_AIPS_PACRH_WP1(x) (BITBAND_ACCESS32(HW_AIPS_PACRH_ADDR(x), BP_AIPS_PACRH_WP1)) /*! @brief Format value for bitfield AIPS_PACRH_WP1. */ #define BF_AIPS_PACRH_WP1(v) ((uint32_t)((uint32_t)(v) << BP_AIPS_PACRH_WP1) & BM_AIPS_PACRH_WP1) /*! @brief Set the WP1 field to a new value. */ #define BW_AIPS_PACRH_WP1(x, v) (BITBAND_ACCESS32(HW_AIPS_PACRH_ADDR(x), BP_AIPS_PACRH_WP1) = (v)) /*@}*/ /*! * @name Register AIPS_PACRH, field SP1[26] (RW) * * Determines whether the peripheral requires supervisor privilege level for * access. When this field is set, the master privilege level must indicate the * supervisor access attribute, and the MPRx[MPLn] control field for the master must * be set. If not, access terminates with an error response and no peripheral * access initiates. * * Values: * - 0 - This peripheral does not require supervisor privilege level for * accesses. * - 1 - This peripheral requires supervisor privilege level for accesses. */ /*@{*/ #define BP_AIPS_PACRH_SP1 (26U) /*!< Bit position for AIPS_PACRH_SP1. */ #define BM_AIPS_PACRH_SP1 (0x04000000U) /*!< Bit mask for AIPS_PACRH_SP1. */ #define BS_AIPS_PACRH_SP1 (1U) /*!< Bit field size in bits for AIPS_PACRH_SP1. */ /*! @brief Read current value of the AIPS_PACRH_SP1 field. */ #define BR_AIPS_PACRH_SP1(x) (BITBAND_ACCESS32(HW_AIPS_PACRH_ADDR(x), BP_AIPS_PACRH_SP1)) /*! @brief Format value for bitfield AIPS_PACRH_SP1. */ #define BF_AIPS_PACRH_SP1(v) ((uint32_t)((uint32_t)(v) << BP_AIPS_PACRH_SP1) & BM_AIPS_PACRH_SP1) /*! @brief Set the SP1 field to a new value. */ #define BW_AIPS_PACRH_SP1(x, v) (BITBAND_ACCESS32(HW_AIPS_PACRH_ADDR(x), BP_AIPS_PACRH_SP1) = (v)) /*@}*/ /*! * @name Register AIPS_PACRH, field TP0[28] (RW) * * Determines whether the peripheral allows accesses from an untrusted master. * When this bit is set and an access is attempted by an untrusted master, the * access terminates with an error response and no peripheral access initiates. * * Values: * - 0 - Accesses from an untrusted master are allowed. * - 1 - Accesses from an untrusted master are not allowed. */ /*@{*/ #define BP_AIPS_PACRH_TP0 (28U) /*!< Bit position for AIPS_PACRH_TP0. */ #define BM_AIPS_PACRH_TP0 (0x10000000U) /*!< Bit mask for AIPS_PACRH_TP0. */ #define BS_AIPS_PACRH_TP0 (1U) /*!< Bit field size in bits for AIPS_PACRH_TP0. */ /*! @brief Read current value of the AIPS_PACRH_TP0 field. */ #define BR_AIPS_PACRH_TP0(x) (BITBAND_ACCESS32(HW_AIPS_PACRH_ADDR(x), BP_AIPS_PACRH_TP0)) /*! @brief Format value for bitfield AIPS_PACRH_TP0. */ #define BF_AIPS_PACRH_TP0(v) ((uint32_t)((uint32_t)(v) << BP_AIPS_PACRH_TP0) & BM_AIPS_PACRH_TP0) /*! @brief Set the TP0 field to a new value. */ #define BW_AIPS_PACRH_TP0(x, v) (BITBAND_ACCESS32(HW_AIPS_PACRH_ADDR(x), BP_AIPS_PACRH_TP0) = (v)) /*@}*/ /*! * @name Register AIPS_PACRH, field WP0[29] (RW) * * Determines whether the peripheral allows write accesses. When this field is * set and a write access is attempted, access terminates with an error response * and no peripheral access initiates. * * Values: * - 0 - This peripheral allows write accesses. * - 1 - This peripheral is write protected. */ /*@{*/ #define BP_AIPS_PACRH_WP0 (29U) /*!< Bit position for AIPS_PACRH_WP0. */ #define BM_AIPS_PACRH_WP0 (0x20000000U) /*!< Bit mask for AIPS_PACRH_WP0. */ #define BS_AIPS_PACRH_WP0 (1U) /*!< Bit field size in bits for AIPS_PACRH_WP0. */ /*! @brief Read current value of the AIPS_PACRH_WP0 field. */ #define BR_AIPS_PACRH_WP0(x) (BITBAND_ACCESS32(HW_AIPS_PACRH_ADDR(x), BP_AIPS_PACRH_WP0)) /*! @brief Format value for bitfield AIPS_PACRH_WP0. */ #define BF_AIPS_PACRH_WP0(v) ((uint32_t)((uint32_t)(v) << BP_AIPS_PACRH_WP0) & BM_AIPS_PACRH_WP0) /*! @brief Set the WP0 field to a new value. */ #define BW_AIPS_PACRH_WP0(x, v) (BITBAND_ACCESS32(HW_AIPS_PACRH_ADDR(x), BP_AIPS_PACRH_WP0) = (v)) /*@}*/ /*! * @name Register AIPS_PACRH, field SP0[30] (RW) * * Determines whether the peripheral requires supervisor privilege level for * accesses. When this field is set, the master privilege level must indicate the * supervisor access attribute, and the MPRx[MPLn] control field for the master * must be set. If not, access terminates with an error response and no peripheral * access initiates. * * Values: * - 0 - This peripheral does not require supervisor privilege level for * accesses. * - 1 - This peripheral requires supervisor privilege level for accesses. */ /*@{*/ #define BP_AIPS_PACRH_SP0 (30U) /*!< Bit position for AIPS_PACRH_SP0. */ #define BM_AIPS_PACRH_SP0 (0x40000000U) /*!< Bit mask for AIPS_PACRH_SP0. */ #define BS_AIPS_PACRH_SP0 (1U) /*!< Bit field size in bits for AIPS_PACRH_SP0. */ /*! @brief Read current value of the AIPS_PACRH_SP0 field. */ #define BR_AIPS_PACRH_SP0(x) (BITBAND_ACCESS32(HW_AIPS_PACRH_ADDR(x), BP_AIPS_PACRH_SP0)) /*! @brief Format value for bitfield AIPS_PACRH_SP0. */ #define BF_AIPS_PACRH_SP0(v) ((uint32_t)((uint32_t)(v) << BP_AIPS_PACRH_SP0) & BM_AIPS_PACRH_SP0) /*! @brief Set the SP0 field to a new value. */ #define BW_AIPS_PACRH_SP0(x, v) (BITBAND_ACCESS32(HW_AIPS_PACRH_ADDR(x), BP_AIPS_PACRH_SP0) = (v)) /*@}*/ /******************************************************************************* * HW_AIPS_PACRI - Peripheral Access Control Register ******************************************************************************/ /*! * @brief HW_AIPS_PACRI - Peripheral Access Control Register (RW) * * Reset value: 0x44444444U * * This section describes PACR registers E-P, which control peripheral slots * 32-127. See PACRPeripheral Access Control Register for the description of these * registers. */ typedef union _hw_aips_pacri { uint32_t U; struct _hw_aips_pacri_bitfields { uint32_t TP7 : 1; /*!< [0] Trusted Protect */ uint32_t WP7 : 1; /*!< [1] Write Protect */ uint32_t SP7 : 1; /*!< [2] Supervisor Protect */ uint32_t RESERVED0 : 1; /*!< [3] */ uint32_t TP6 : 1; /*!< [4] Trusted Protect */ uint32_t WP6 : 1; /*!< [5] Write Protect */ uint32_t SP6 : 1; /*!< [6] Supervisor Protect */ uint32_t RESERVED1 : 1; /*!< [7] */ uint32_t TP5 : 1; /*!< [8] Trusted Protect */ uint32_t WP5 : 1; /*!< [9] Write Protect */ uint32_t SP5 : 1; /*!< [10] Supervisor Protect */ uint32_t RESERVED2 : 1; /*!< [11] */ uint32_t TP4 : 1; /*!< [12] Trusted Protect */ uint32_t WP4 : 1; /*!< [13] Write Protect */ uint32_t SP4 : 1; /*!< [14] Supervisor Protect */ uint32_t RESERVED3 : 1; /*!< [15] */ uint32_t TP3 : 1; /*!< [16] Trusted Protect */ uint32_t WP3 : 1; /*!< [17] Write Protect */ uint32_t SP3 : 1; /*!< [18] Supervisor Protect */ uint32_t RESERVED4 : 1; /*!< [19] */ uint32_t TP2 : 1; /*!< [20] Trusted Protect */ uint32_t WP2 : 1; /*!< [21] Write Protect */ uint32_t SP2 : 1; /*!< [22] Supervisor Protect */ uint32_t RESERVED5 : 1; /*!< [23] */ uint32_t TP1 : 1; /*!< [24] Trusted Protect */ uint32_t WP1 : 1; /*!< [25] Write Protect */ uint32_t SP1 : 1; /*!< [26] Supervisor Protect */ uint32_t RESERVED6 : 1; /*!< [27] */ uint32_t TP0 : 1; /*!< [28] Trusted Protect */ uint32_t WP0 : 1; /*!< [29] Write Protect */ uint32_t SP0 : 1; /*!< [30] Supervisor Protect */ uint32_t RESERVED7 : 1; /*!< [31] */ } B; } hw_aips_pacri_t; /*! * @name Constants and macros for entire AIPS_PACRI register */ /*@{*/ #define HW_AIPS_PACRI_ADDR(x) ((x) + 0x50U) #define HW_AIPS_PACRI(x) (*(__IO hw_aips_pacri_t *) HW_AIPS_PACRI_ADDR(x)) #define HW_AIPS_PACRI_RD(x) (HW_AIPS_PACRI(x).U) #define HW_AIPS_PACRI_WR(x, v) (HW_AIPS_PACRI(x).U = (v)) #define HW_AIPS_PACRI_SET(x, v) (HW_AIPS_PACRI_WR(x, HW_AIPS_PACRI_RD(x) | (v))) #define HW_AIPS_PACRI_CLR(x, v) (HW_AIPS_PACRI_WR(x, HW_AIPS_PACRI_RD(x) & ~(v))) #define HW_AIPS_PACRI_TOG(x, v) (HW_AIPS_PACRI_WR(x, HW_AIPS_PACRI_RD(x) ^ (v))) /*@}*/ /* * Constants & macros for individual AIPS_PACRI bitfields */ /*! * @name Register AIPS_PACRI, field TP7[0] (RW) * * Determines whether the peripheral allows accesses from an untrusted master. * When this field is set and an access is attempted by an untrusted master, the * access terminates with an error response and no peripheral access initiates. * * Values: * - 0 - Accesses from an untrusted master are allowed. * - 1 - Accesses from an untrusted master are not allowed. */ /*@{*/ #define BP_AIPS_PACRI_TP7 (0U) /*!< Bit position for AIPS_PACRI_TP7. */ #define BM_AIPS_PACRI_TP7 (0x00000001U) /*!< Bit mask for AIPS_PACRI_TP7. */ #define BS_AIPS_PACRI_TP7 (1U) /*!< Bit field size in bits for AIPS_PACRI_TP7. */ /*! @brief Read current value of the AIPS_PACRI_TP7 field. */ #define BR_AIPS_PACRI_TP7(x) (BITBAND_ACCESS32(HW_AIPS_PACRI_ADDR(x), BP_AIPS_PACRI_TP7)) /*! @brief Format value for bitfield AIPS_PACRI_TP7. */ #define BF_AIPS_PACRI_TP7(v) ((uint32_t)((uint32_t)(v) << BP_AIPS_PACRI_TP7) & BM_AIPS_PACRI_TP7) /*! @brief Set the TP7 field to a new value. */ #define BW_AIPS_PACRI_TP7(x, v) (BITBAND_ACCESS32(HW_AIPS_PACRI_ADDR(x), BP_AIPS_PACRI_TP7) = (v)) /*@}*/ /*! * @name Register AIPS_PACRI, field WP7[1] (RW) * * Determines whether the peripheral allows write accesses. When this field is * set and a write access is attempted, access terminates with an error response * and no peripheral access initiates. * * Values: * - 0 - This peripheral allows write accesses. * - 1 - This peripheral is write protected. */ /*@{*/ #define BP_AIPS_PACRI_WP7 (1U) /*!< Bit position for AIPS_PACRI_WP7. */ #define BM_AIPS_PACRI_WP7 (0x00000002U) /*!< Bit mask for AIPS_PACRI_WP7. */ #define BS_AIPS_PACRI_WP7 (1U) /*!< Bit field size in bits for AIPS_PACRI_WP7. */ /*! @brief Read current value of the AIPS_PACRI_WP7 field. */ #define BR_AIPS_PACRI_WP7(x) (BITBAND_ACCESS32(HW_AIPS_PACRI_ADDR(x), BP_AIPS_PACRI_WP7)) /*! @brief Format value for bitfield AIPS_PACRI_WP7. */ #define BF_AIPS_PACRI_WP7(v) ((uint32_t)((uint32_t)(v) << BP_AIPS_PACRI_WP7) & BM_AIPS_PACRI_WP7) /*! @brief Set the WP7 field to a new value. */ #define BW_AIPS_PACRI_WP7(x, v) (BITBAND_ACCESS32(HW_AIPS_PACRI_ADDR(x), BP_AIPS_PACRI_WP7) = (v)) /*@}*/ /*! * @name Register AIPS_PACRI, field SP7[2] (RW) * * Determines whether the peripheral requires supervisor privilege level for * accesses. When this field is set, the master privilege level must indicate the * supervisor access attribute, and the MPRx[MPLn] control field for the master * must be set. If not, access terminates with an error response and no peripheral * access initiates. * * Values: * - 0 - This peripheral does not require supervisor privilege level for * accesses. * - 1 - This peripheral requires supervisor privilege level for accesses. */ /*@{*/ #define BP_AIPS_PACRI_SP7 (2U) /*!< Bit position for AIPS_PACRI_SP7. */ #define BM_AIPS_PACRI_SP7 (0x00000004U) /*!< Bit mask for AIPS_PACRI_SP7. */ #define BS_AIPS_PACRI_SP7 (1U) /*!< Bit field size in bits for AIPS_PACRI_SP7. */ /*! @brief Read current value of the AIPS_PACRI_SP7 field. */ #define BR_AIPS_PACRI_SP7(x) (BITBAND_ACCESS32(HW_AIPS_PACRI_ADDR(x), BP_AIPS_PACRI_SP7)) /*! @brief Format value for bitfield AIPS_PACRI_SP7. */ #define BF_AIPS_PACRI_SP7(v) ((uint32_t)((uint32_t)(v) << BP_AIPS_PACRI_SP7) & BM_AIPS_PACRI_SP7) /*! @brief Set the SP7 field to a new value. */ #define BW_AIPS_PACRI_SP7(x, v) (BITBAND_ACCESS32(HW_AIPS_PACRI_ADDR(x), BP_AIPS_PACRI_SP7) = (v)) /*@}*/ /*! * @name Register AIPS_PACRI, field TP6[4] (RW) * * Determines whether the peripheral allows accesses from an untrusted master. * When this field is set and an access is attempted by an untrusted master, the * access terminates with an error response and no peripheral access initiates. * * Values: * - 0 - Accesses from an untrusted master are allowed. * - 1 - Accesses from an untrusted master are not allowed. */ /*@{*/ #define BP_AIPS_PACRI_TP6 (4U) /*!< Bit position for AIPS_PACRI_TP6. */ #define BM_AIPS_PACRI_TP6 (0x00000010U) /*!< Bit mask for AIPS_PACRI_TP6. */ #define BS_AIPS_PACRI_TP6 (1U) /*!< Bit field size in bits for AIPS_PACRI_TP6. */ /*! @brief Read current value of the AIPS_PACRI_TP6 field. */ #define BR_AIPS_PACRI_TP6(x) (BITBAND_ACCESS32(HW_AIPS_PACRI_ADDR(x), BP_AIPS_PACRI_TP6)) /*! @brief Format value for bitfield AIPS_PACRI_TP6. */ #define BF_AIPS_PACRI_TP6(v) ((uint32_t)((uint32_t)(v) << BP_AIPS_PACRI_TP6) & BM_AIPS_PACRI_TP6) /*! @brief Set the TP6 field to a new value. */ #define BW_AIPS_PACRI_TP6(x, v) (BITBAND_ACCESS32(HW_AIPS_PACRI_ADDR(x), BP_AIPS_PACRI_TP6) = (v)) /*@}*/ /*! * @name Register AIPS_PACRI, field WP6[5] (RW) * * Determines whether the peripheral allows write accesses. When this field is * set and a write access is attempted, access terminates with an error response * and no peripheral access initiates. * * Values: * - 0 - This peripheral allows write accesses. * - 1 - This peripheral is write protected. */ /*@{*/ #define BP_AIPS_PACRI_WP6 (5U) /*!< Bit position for AIPS_PACRI_WP6. */ #define BM_AIPS_PACRI_WP6 (0x00000020U) /*!< Bit mask for AIPS_PACRI_WP6. */ #define BS_AIPS_PACRI_WP6 (1U) /*!< Bit field size in bits for AIPS_PACRI_WP6. */ /*! @brief Read current value of the AIPS_PACRI_WP6 field. */ #define BR_AIPS_PACRI_WP6(x) (BITBAND_ACCESS32(HW_AIPS_PACRI_ADDR(x), BP_AIPS_PACRI_WP6)) /*! @brief Format value for bitfield AIPS_PACRI_WP6. */ #define BF_AIPS_PACRI_WP6(v) ((uint32_t)((uint32_t)(v) << BP_AIPS_PACRI_WP6) & BM_AIPS_PACRI_WP6) /*! @brief Set the WP6 field to a new value. */ #define BW_AIPS_PACRI_WP6(x, v) (BITBAND_ACCESS32(HW_AIPS_PACRI_ADDR(x), BP_AIPS_PACRI_WP6) = (v)) /*@}*/ /*! * @name Register AIPS_PACRI, field SP6[6] (RW) * * Determines whether the peripheral requires supervisor privilege level for * accesses. When this field is set, the master privilege level must indicate the * supervisor access attribute, and the MPRx[MPLn] control field for the master * must be set. If not, access terminates with an error response and no peripheral * access initiates. * * Values: * - 0 - This peripheral does not require supervisor privilege level for * accesses. * - 1 - This peripheral requires supervisor privilege level for accesses. */ /*@{*/ #define BP_AIPS_PACRI_SP6 (6U) /*!< Bit position for AIPS_PACRI_SP6. */ #define BM_AIPS_PACRI_SP6 (0x00000040U) /*!< Bit mask for AIPS_PACRI_SP6. */ #define BS_AIPS_PACRI_SP6 (1U) /*!< Bit field size in bits for AIPS_PACRI_SP6. */ /*! @brief Read current value of the AIPS_PACRI_SP6 field. */ #define BR_AIPS_PACRI_SP6(x) (BITBAND_ACCESS32(HW_AIPS_PACRI_ADDR(x), BP_AIPS_PACRI_SP6)) /*! @brief Format value for bitfield AIPS_PACRI_SP6. */ #define BF_AIPS_PACRI_SP6(v) ((uint32_t)((uint32_t)(v) << BP_AIPS_PACRI_SP6) & BM_AIPS_PACRI_SP6) /*! @brief Set the SP6 field to a new value. */ #define BW_AIPS_PACRI_SP6(x, v) (BITBAND_ACCESS32(HW_AIPS_PACRI_ADDR(x), BP_AIPS_PACRI_SP6) = (v)) /*@}*/ /*! * @name Register AIPS_PACRI, field TP5[8] (RW) * * Determines whether the peripheral allows accesses from an untrusted master. * When this field is set and an access is attempted by an untrusted master, the * access terminates with an error response and no peripheral access initiates. * * Values: * - 0 - Accesses from an untrusted master are allowed. * - 1 - Accesses from an untrusted master are not allowed. */ /*@{*/ #define BP_AIPS_PACRI_TP5 (8U) /*!< Bit position for AIPS_PACRI_TP5. */ #define BM_AIPS_PACRI_TP5 (0x00000100U) /*!< Bit mask for AIPS_PACRI_TP5. */ #define BS_AIPS_PACRI_TP5 (1U) /*!< Bit field size in bits for AIPS_PACRI_TP5. */ /*! @brief Read current value of the AIPS_PACRI_TP5 field. */ #define BR_AIPS_PACRI_TP5(x) (BITBAND_ACCESS32(HW_AIPS_PACRI_ADDR(x), BP_AIPS_PACRI_TP5)) /*! @brief Format value for bitfield AIPS_PACRI_TP5. */ #define BF_AIPS_PACRI_TP5(v) ((uint32_t)((uint32_t)(v) << BP_AIPS_PACRI_TP5) & BM_AIPS_PACRI_TP5) /*! @brief Set the TP5 field to a new value. */ #define BW_AIPS_PACRI_TP5(x, v) (BITBAND_ACCESS32(HW_AIPS_PACRI_ADDR(x), BP_AIPS_PACRI_TP5) = (v)) /*@}*/ /*! * @name Register AIPS_PACRI, field WP5[9] (RW) * * Determines whether the peripheral allows write accesses. When this field is * set and a write access is attempted, access terminates with an error response * and no peripheral access initiates. * * Values: * - 0 - This peripheral allows write accesses. * - 1 - This peripheral is write protected. */ /*@{*/ #define BP_AIPS_PACRI_WP5 (9U) /*!< Bit position for AIPS_PACRI_WP5. */ #define BM_AIPS_PACRI_WP5 (0x00000200U) /*!< Bit mask for AIPS_PACRI_WP5. */ #define BS_AIPS_PACRI_WP5 (1U) /*!< Bit field size in bits for AIPS_PACRI_WP5. */ /*! @brief Read current value of the AIPS_PACRI_WP5 field. */ #define BR_AIPS_PACRI_WP5(x) (BITBAND_ACCESS32(HW_AIPS_PACRI_ADDR(x), BP_AIPS_PACRI_WP5)) /*! @brief Format value for bitfield AIPS_PACRI_WP5. */ #define BF_AIPS_PACRI_WP5(v) ((uint32_t)((uint32_t)(v) << BP_AIPS_PACRI_WP5) & BM_AIPS_PACRI_WP5) /*! @brief Set the WP5 field to a new value. */ #define BW_AIPS_PACRI_WP5(x, v) (BITBAND_ACCESS32(HW_AIPS_PACRI_ADDR(x), BP_AIPS_PACRI_WP5) = (v)) /*@}*/ /*! * @name Register AIPS_PACRI, field SP5[10] (RW) * * Determines whether the peripheral requires supervisor privilege level for * accesses. When this field is set, the master privilege level must indicate the * supervisor access attribute, and the MPRx[MPLn] control field for the master * must be set. If not, access terminates with an error response and no peripheral * access initiates. * * Values: * - 0 - This peripheral does not require supervisor privilege level for * accesses. * - 1 - This peripheral requires supervisor privilege level for accesses. */ /*@{*/ #define BP_AIPS_PACRI_SP5 (10U) /*!< Bit position for AIPS_PACRI_SP5. */ #define BM_AIPS_PACRI_SP5 (0x00000400U) /*!< Bit mask for AIPS_PACRI_SP5. */ #define BS_AIPS_PACRI_SP5 (1U) /*!< Bit field size in bits for AIPS_PACRI_SP5. */ /*! @brief Read current value of the AIPS_PACRI_SP5 field. */ #define BR_AIPS_PACRI_SP5(x) (BITBAND_ACCESS32(HW_AIPS_PACRI_ADDR(x), BP_AIPS_PACRI_SP5)) /*! @brief Format value for bitfield AIPS_PACRI_SP5. */ #define BF_AIPS_PACRI_SP5(v) ((uint32_t)((uint32_t)(v) << BP_AIPS_PACRI_SP5) & BM_AIPS_PACRI_SP5) /*! @brief Set the SP5 field to a new value. */ #define BW_AIPS_PACRI_SP5(x, v) (BITBAND_ACCESS32(HW_AIPS_PACRI_ADDR(x), BP_AIPS_PACRI_SP5) = (v)) /*@}*/ /*! * @name Register AIPS_PACRI, field TP4[12] (RW) * * Determines whether the peripheral allows accesses from an untrusted master. * When this bit is set and an access is attempted by an untrusted master, the * access terminates with an error response and no peripheral access initiates. * * Values: * - 0 - Accesses from an untrusted master are allowed. * - 1 - Accesses from an untrusted master are not allowed. */ /*@{*/ #define BP_AIPS_PACRI_TP4 (12U) /*!< Bit position for AIPS_PACRI_TP4. */ #define BM_AIPS_PACRI_TP4 (0x00001000U) /*!< Bit mask for AIPS_PACRI_TP4. */ #define BS_AIPS_PACRI_TP4 (1U) /*!< Bit field size in bits for AIPS_PACRI_TP4. */ /*! @brief Read current value of the AIPS_PACRI_TP4 field. */ #define BR_AIPS_PACRI_TP4(x) (BITBAND_ACCESS32(HW_AIPS_PACRI_ADDR(x), BP_AIPS_PACRI_TP4)) /*! @brief Format value for bitfield AIPS_PACRI_TP4. */ #define BF_AIPS_PACRI_TP4(v) ((uint32_t)((uint32_t)(v) << BP_AIPS_PACRI_TP4) & BM_AIPS_PACRI_TP4) /*! @brief Set the TP4 field to a new value. */ #define BW_AIPS_PACRI_TP4(x, v) (BITBAND_ACCESS32(HW_AIPS_PACRI_ADDR(x), BP_AIPS_PACRI_TP4) = (v)) /*@}*/ /*! * @name Register AIPS_PACRI, field WP4[13] (RW) * * Determines whether the peripheral allows write accesses. When this field is * set and a write access is attempted, access terminates with an error response * and no peripheral access initiates. * * Values: * - 0 - This peripheral allows write accesses. * - 1 - This peripheral is write protected. */ /*@{*/ #define BP_AIPS_PACRI_WP4 (13U) /*!< Bit position for AIPS_PACRI_WP4. */ #define BM_AIPS_PACRI_WP4 (0x00002000U) /*!< Bit mask for AIPS_PACRI_WP4. */ #define BS_AIPS_PACRI_WP4 (1U) /*!< Bit field size in bits for AIPS_PACRI_WP4. */ /*! @brief Read current value of the AIPS_PACRI_WP4 field. */ #define BR_AIPS_PACRI_WP4(x) (BITBAND_ACCESS32(HW_AIPS_PACRI_ADDR(x), BP_AIPS_PACRI_WP4)) /*! @brief Format value for bitfield AIPS_PACRI_WP4. */ #define BF_AIPS_PACRI_WP4(v) ((uint32_t)((uint32_t)(v) << BP_AIPS_PACRI_WP4) & BM_AIPS_PACRI_WP4) /*! @brief Set the WP4 field to a new value. */ #define BW_AIPS_PACRI_WP4(x, v) (BITBAND_ACCESS32(HW_AIPS_PACRI_ADDR(x), BP_AIPS_PACRI_WP4) = (v)) /*@}*/ /*! * @name Register AIPS_PACRI, field SP4[14] (RW) * * Determines whether the peripheral requires supervisor privilege level for * access. When this bit is set, the master privilege level must indicate the * supervisor access attribute, and the MPRx[MPLn] control bit for the master must be * set. If not, access terminates with an error response and no peripheral access * initiates. * * Values: * - 0 - This peripheral does not require supervisor privilege level for * accesses. * - 1 - This peripheral requires supervisor privilege level for accesses. */ /*@{*/ #define BP_AIPS_PACRI_SP4 (14U) /*!< Bit position for AIPS_PACRI_SP4. */ #define BM_AIPS_PACRI_SP4 (0x00004000U) /*!< Bit mask for AIPS_PACRI_SP4. */ #define BS_AIPS_PACRI_SP4 (1U) /*!< Bit field size in bits for AIPS_PACRI_SP4. */ /*! @brief Read current value of the AIPS_PACRI_SP4 field. */ #define BR_AIPS_PACRI_SP4(x) (BITBAND_ACCESS32(HW_AIPS_PACRI_ADDR(x), BP_AIPS_PACRI_SP4)) /*! @brief Format value for bitfield AIPS_PACRI_SP4. */ #define BF_AIPS_PACRI_SP4(v) ((uint32_t)((uint32_t)(v) << BP_AIPS_PACRI_SP4) & BM_AIPS_PACRI_SP4) /*! @brief Set the SP4 field to a new value. */ #define BW_AIPS_PACRI_SP4(x, v) (BITBAND_ACCESS32(HW_AIPS_PACRI_ADDR(x), BP_AIPS_PACRI_SP4) = (v)) /*@}*/ /*! * @name Register AIPS_PACRI, field TP3[16] (RW) * * Determines whether the peripheral allows accesses from an untrusted master. * When this field is set and an access is attempted by an untrusted master, the * access terminates with an error response and no peripheral access initiates. * * Values: * - 0 - Accesses from an untrusted master are allowed. * - 1 - Accesses from an untrusted master are not allowed. */ /*@{*/ #define BP_AIPS_PACRI_TP3 (16U) /*!< Bit position for AIPS_PACRI_TP3. */ #define BM_AIPS_PACRI_TP3 (0x00010000U) /*!< Bit mask for AIPS_PACRI_TP3. */ #define BS_AIPS_PACRI_TP3 (1U) /*!< Bit field size in bits for AIPS_PACRI_TP3. */ /*! @brief Read current value of the AIPS_PACRI_TP3 field. */ #define BR_AIPS_PACRI_TP3(x) (BITBAND_ACCESS32(HW_AIPS_PACRI_ADDR(x), BP_AIPS_PACRI_TP3)) /*! @brief Format value for bitfield AIPS_PACRI_TP3. */ #define BF_AIPS_PACRI_TP3(v) ((uint32_t)((uint32_t)(v) << BP_AIPS_PACRI_TP3) & BM_AIPS_PACRI_TP3) /*! @brief Set the TP3 field to a new value. */ #define BW_AIPS_PACRI_TP3(x, v) (BITBAND_ACCESS32(HW_AIPS_PACRI_ADDR(x), BP_AIPS_PACRI_TP3) = (v)) /*@}*/ /*! * @name Register AIPS_PACRI, field WP3[17] (RW) * * Determines whether the peripheral allows write accesss. When this bit is set * and a write access is attempted, access terminates with an error response and * no peripheral access initiates. * * Values: * - 0 - This peripheral allows write accesses. * - 1 - This peripheral is write protected. */ /*@{*/ #define BP_AIPS_PACRI_WP3 (17U) /*!< Bit position for AIPS_PACRI_WP3. */ #define BM_AIPS_PACRI_WP3 (0x00020000U) /*!< Bit mask for AIPS_PACRI_WP3. */ #define BS_AIPS_PACRI_WP3 (1U) /*!< Bit field size in bits for AIPS_PACRI_WP3. */ /*! @brief Read current value of the AIPS_PACRI_WP3 field. */ #define BR_AIPS_PACRI_WP3(x) (BITBAND_ACCESS32(HW_AIPS_PACRI_ADDR(x), BP_AIPS_PACRI_WP3)) /*! @brief Format value for bitfield AIPS_PACRI_WP3. */ #define BF_AIPS_PACRI_WP3(v) ((uint32_t)((uint32_t)(v) << BP_AIPS_PACRI_WP3) & BM_AIPS_PACRI_WP3) /*! @brief Set the WP3 field to a new value. */ #define BW_AIPS_PACRI_WP3(x, v) (BITBAND_ACCESS32(HW_AIPS_PACRI_ADDR(x), BP_AIPS_PACRI_WP3) = (v)) /*@}*/ /*! * @name Register AIPS_PACRI, field SP3[18] (RW) * * Determines whether the peripheral requires supervisor privilege level for * accesses. When this field is set, the master privilege level must indicate the * supervisor access attribute, and the MPRx[MPLn] control field for the master * must be set. If not, access terminates with an error response and no peripheral * access initiates. * * Values: * - 0 - This peripheral does not require supervisor privilege level for * accesses. * - 1 - This peripheral requires supervisor privilege level for accesses. */ /*@{*/ #define BP_AIPS_PACRI_SP3 (18U) /*!< Bit position for AIPS_PACRI_SP3. */ #define BM_AIPS_PACRI_SP3 (0x00040000U) /*!< Bit mask for AIPS_PACRI_SP3. */ #define BS_AIPS_PACRI_SP3 (1U) /*!< Bit field size in bits for AIPS_PACRI_SP3. */ /*! @brief Read current value of the AIPS_PACRI_SP3 field. */ #define BR_AIPS_PACRI_SP3(x) (BITBAND_ACCESS32(HW_AIPS_PACRI_ADDR(x), BP_AIPS_PACRI_SP3)) /*! @brief Format value for bitfield AIPS_PACRI_SP3. */ #define BF_AIPS_PACRI_SP3(v) ((uint32_t)((uint32_t)(v) << BP_AIPS_PACRI_SP3) & BM_AIPS_PACRI_SP3) /*! @brief Set the SP3 field to a new value. */ #define BW_AIPS_PACRI_SP3(x, v) (BITBAND_ACCESS32(HW_AIPS_PACRI_ADDR(x), BP_AIPS_PACRI_SP3) = (v)) /*@}*/ /*! * @name Register AIPS_PACRI, field TP2[20] (RW) * * Determines whether the peripheral allows accesses from an untrusted master. * When this bit is set and an access is attempted by an untrusted master, the * access terminates with an error response and no peripheral access initiates. * * Values: * - 0 - Accesses from an untrusted master are allowed. * - 1 - Accesses from an untrusted master are not allowed. */ /*@{*/ #define BP_AIPS_PACRI_TP2 (20U) /*!< Bit position for AIPS_PACRI_TP2. */ #define BM_AIPS_PACRI_TP2 (0x00100000U) /*!< Bit mask for AIPS_PACRI_TP2. */ #define BS_AIPS_PACRI_TP2 (1U) /*!< Bit field size in bits for AIPS_PACRI_TP2. */ /*! @brief Read current value of the AIPS_PACRI_TP2 field. */ #define BR_AIPS_PACRI_TP2(x) (BITBAND_ACCESS32(HW_AIPS_PACRI_ADDR(x), BP_AIPS_PACRI_TP2)) /*! @brief Format value for bitfield AIPS_PACRI_TP2. */ #define BF_AIPS_PACRI_TP2(v) ((uint32_t)((uint32_t)(v) << BP_AIPS_PACRI_TP2) & BM_AIPS_PACRI_TP2) /*! @brief Set the TP2 field to a new value. */ #define BW_AIPS_PACRI_TP2(x, v) (BITBAND_ACCESS32(HW_AIPS_PACRI_ADDR(x), BP_AIPS_PACRI_TP2) = (v)) /*@}*/ /*! * @name Register AIPS_PACRI, field WP2[21] (RW) * * Determines whether the peripheral allows write accesses. When this field is * set and a write access is attempted, access terminates with an error response * and no peripheral access initiates. * * Values: * - 0 - This peripheral allows write accesses. * - 1 - This peripheral is write protected. */ /*@{*/ #define BP_AIPS_PACRI_WP2 (21U) /*!< Bit position for AIPS_PACRI_WP2. */ #define BM_AIPS_PACRI_WP2 (0x00200000U) /*!< Bit mask for AIPS_PACRI_WP2. */ #define BS_AIPS_PACRI_WP2 (1U) /*!< Bit field size in bits for AIPS_PACRI_WP2. */ /*! @brief Read current value of the AIPS_PACRI_WP2 field. */ #define BR_AIPS_PACRI_WP2(x) (BITBAND_ACCESS32(HW_AIPS_PACRI_ADDR(x), BP_AIPS_PACRI_WP2)) /*! @brief Format value for bitfield AIPS_PACRI_WP2. */ #define BF_AIPS_PACRI_WP2(v) ((uint32_t)((uint32_t)(v) << BP_AIPS_PACRI_WP2) & BM_AIPS_PACRI_WP2) /*! @brief Set the WP2 field to a new value. */ #define BW_AIPS_PACRI_WP2(x, v) (BITBAND_ACCESS32(HW_AIPS_PACRI_ADDR(x), BP_AIPS_PACRI_WP2) = (v)) /*@}*/ /*! * @name Register AIPS_PACRI, field SP2[22] (RW) * * Determines whether the peripheral requires supervisor privilege level for * access. When this bit is set, the master privilege level must indicate the * supervisor access attribute, and the MPRx[MPLn] control bit for the master must be * set. If not, access terminates with an error response and no peripheral access * initiates. * * Values: * - 0 - This peripheral does not require supervisor privilege level for * accesses. * - 1 - This peripheral requires supervisor privilege level for accesses. */ /*@{*/ #define BP_AIPS_PACRI_SP2 (22U) /*!< Bit position for AIPS_PACRI_SP2. */ #define BM_AIPS_PACRI_SP2 (0x00400000U) /*!< Bit mask for AIPS_PACRI_SP2. */ #define BS_AIPS_PACRI_SP2 (1U) /*!< Bit field size in bits for AIPS_PACRI_SP2. */ /*! @brief Read current value of the AIPS_PACRI_SP2 field. */ #define BR_AIPS_PACRI_SP2(x) (BITBAND_ACCESS32(HW_AIPS_PACRI_ADDR(x), BP_AIPS_PACRI_SP2)) /*! @brief Format value for bitfield AIPS_PACRI_SP2. */ #define BF_AIPS_PACRI_SP2(v) ((uint32_t)((uint32_t)(v) << BP_AIPS_PACRI_SP2) & BM_AIPS_PACRI_SP2) /*! @brief Set the SP2 field to a new value. */ #define BW_AIPS_PACRI_SP2(x, v) (BITBAND_ACCESS32(HW_AIPS_PACRI_ADDR(x), BP_AIPS_PACRI_SP2) = (v)) /*@}*/ /*! * @name Register AIPS_PACRI, field TP1[24] (RW) * * Determines whether the peripheral allows accesses from an untrusted master. * When this field is set and an access is attempted by an untrusted master, the * access terminates with an error response and no peripheral access initiates. * * Values: * - 0 - Accesses from an untrusted master are allowed. * - 1 - Accesses from an untrusted master are not allowed. */ /*@{*/ #define BP_AIPS_PACRI_TP1 (24U) /*!< Bit position for AIPS_PACRI_TP1. */ #define BM_AIPS_PACRI_TP1 (0x01000000U) /*!< Bit mask for AIPS_PACRI_TP1. */ #define BS_AIPS_PACRI_TP1 (1U) /*!< Bit field size in bits for AIPS_PACRI_TP1. */ /*! @brief Read current value of the AIPS_PACRI_TP1 field. */ #define BR_AIPS_PACRI_TP1(x) (BITBAND_ACCESS32(HW_AIPS_PACRI_ADDR(x), BP_AIPS_PACRI_TP1)) /*! @brief Format value for bitfield AIPS_PACRI_TP1. */ #define BF_AIPS_PACRI_TP1(v) ((uint32_t)((uint32_t)(v) << BP_AIPS_PACRI_TP1) & BM_AIPS_PACRI_TP1) /*! @brief Set the TP1 field to a new value. */ #define BW_AIPS_PACRI_TP1(x, v) (BITBAND_ACCESS32(HW_AIPS_PACRI_ADDR(x), BP_AIPS_PACRI_TP1) = (v)) /*@}*/ /*! * @name Register AIPS_PACRI, field WP1[25] (RW) * * Determines whether the peripheral allows write accesses. When this field is * set and a write access is attempted, access terminates with an error response * and no peripheral access initiates. * * Values: * - 0 - This peripheral allows write accesses. * - 1 - This peripheral is write protected. */ /*@{*/ #define BP_AIPS_PACRI_WP1 (25U) /*!< Bit position for AIPS_PACRI_WP1. */ #define BM_AIPS_PACRI_WP1 (0x02000000U) /*!< Bit mask for AIPS_PACRI_WP1. */ #define BS_AIPS_PACRI_WP1 (1U) /*!< Bit field size in bits for AIPS_PACRI_WP1. */ /*! @brief Read current value of the AIPS_PACRI_WP1 field. */ #define BR_AIPS_PACRI_WP1(x) (BITBAND_ACCESS32(HW_AIPS_PACRI_ADDR(x), BP_AIPS_PACRI_WP1)) /*! @brief Format value for bitfield AIPS_PACRI_WP1. */ #define BF_AIPS_PACRI_WP1(v) ((uint32_t)((uint32_t)(v) << BP_AIPS_PACRI_WP1) & BM_AIPS_PACRI_WP1) /*! @brief Set the WP1 field to a new value. */ #define BW_AIPS_PACRI_WP1(x, v) (BITBAND_ACCESS32(HW_AIPS_PACRI_ADDR(x), BP_AIPS_PACRI_WP1) = (v)) /*@}*/ /*! * @name Register AIPS_PACRI, field SP1[26] (RW) * * Determines whether the peripheral requires supervisor privilege level for * access. When this field is set, the master privilege level must indicate the * supervisor access attribute, and the MPRx[MPLn] control field for the master must * be set. If not, access terminates with an error response and no peripheral * access initiates. * * Values: * - 0 - This peripheral does not require supervisor privilege level for * accesses. * - 1 - This peripheral requires supervisor privilege level for accesses. */ /*@{*/ #define BP_AIPS_PACRI_SP1 (26U) /*!< Bit position for AIPS_PACRI_SP1. */ #define BM_AIPS_PACRI_SP1 (0x04000000U) /*!< Bit mask for AIPS_PACRI_SP1. */ #define BS_AIPS_PACRI_SP1 (1U) /*!< Bit field size in bits for AIPS_PACRI_SP1. */ /*! @brief Read current value of the AIPS_PACRI_SP1 field. */ #define BR_AIPS_PACRI_SP1(x) (BITBAND_ACCESS32(HW_AIPS_PACRI_ADDR(x), BP_AIPS_PACRI_SP1)) /*! @brief Format value for bitfield AIPS_PACRI_SP1. */ #define BF_AIPS_PACRI_SP1(v) ((uint32_t)((uint32_t)(v) << BP_AIPS_PACRI_SP1) & BM_AIPS_PACRI_SP1) /*! @brief Set the SP1 field to a new value. */ #define BW_AIPS_PACRI_SP1(x, v) (BITBAND_ACCESS32(HW_AIPS_PACRI_ADDR(x), BP_AIPS_PACRI_SP1) = (v)) /*@}*/ /*! * @name Register AIPS_PACRI, field TP0[28] (RW) * * Determines whether the peripheral allows accesses from an untrusted master. * When this bit is set and an access is attempted by an untrusted master, the * access terminates with an error response and no peripheral access initiates. * * Values: * - 0 - Accesses from an untrusted master are allowed. * - 1 - Accesses from an untrusted master are not allowed. */ /*@{*/ #define BP_AIPS_PACRI_TP0 (28U) /*!< Bit position for AIPS_PACRI_TP0. */ #define BM_AIPS_PACRI_TP0 (0x10000000U) /*!< Bit mask for AIPS_PACRI_TP0. */ #define BS_AIPS_PACRI_TP0 (1U) /*!< Bit field size in bits for AIPS_PACRI_TP0. */ /*! @brief Read current value of the AIPS_PACRI_TP0 field. */ #define BR_AIPS_PACRI_TP0(x) (BITBAND_ACCESS32(HW_AIPS_PACRI_ADDR(x), BP_AIPS_PACRI_TP0)) /*! @brief Format value for bitfield AIPS_PACRI_TP0. */ #define BF_AIPS_PACRI_TP0(v) ((uint32_t)((uint32_t)(v) << BP_AIPS_PACRI_TP0) & BM_AIPS_PACRI_TP0) /*! @brief Set the TP0 field to a new value. */ #define BW_AIPS_PACRI_TP0(x, v) (BITBAND_ACCESS32(HW_AIPS_PACRI_ADDR(x), BP_AIPS_PACRI_TP0) = (v)) /*@}*/ /*! * @name Register AIPS_PACRI, field WP0[29] (RW) * * Determines whether the peripheral allows write accesses. When this field is * set and a write access is attempted, access terminates with an error response * and no peripheral access initiates. * * Values: * - 0 - This peripheral allows write accesses. * - 1 - This peripheral is write protected. */ /*@{*/ #define BP_AIPS_PACRI_WP0 (29U) /*!< Bit position for AIPS_PACRI_WP0. */ #define BM_AIPS_PACRI_WP0 (0x20000000U) /*!< Bit mask for AIPS_PACRI_WP0. */ #define BS_AIPS_PACRI_WP0 (1U) /*!< Bit field size in bits for AIPS_PACRI_WP0. */ /*! @brief Read current value of the AIPS_PACRI_WP0 field. */ #define BR_AIPS_PACRI_WP0(x) (BITBAND_ACCESS32(HW_AIPS_PACRI_ADDR(x), BP_AIPS_PACRI_WP0)) /*! @brief Format value for bitfield AIPS_PACRI_WP0. */ #define BF_AIPS_PACRI_WP0(v) ((uint32_t)((uint32_t)(v) << BP_AIPS_PACRI_WP0) & BM_AIPS_PACRI_WP0) /*! @brief Set the WP0 field to a new value. */ #define BW_AIPS_PACRI_WP0(x, v) (BITBAND_ACCESS32(HW_AIPS_PACRI_ADDR(x), BP_AIPS_PACRI_WP0) = (v)) /*@}*/ /*! * @name Register AIPS_PACRI, field SP0[30] (RW) * * Determines whether the peripheral requires supervisor privilege level for * accesses. When this field is set, the master privilege level must indicate the * supervisor access attribute, and the MPRx[MPLn] control field for the master * must be set. If not, access terminates with an error response and no peripheral * access initiates. * * Values: * - 0 - This peripheral does not require supervisor privilege level for * accesses. * - 1 - This peripheral requires supervisor privilege level for accesses. */ /*@{*/ #define BP_AIPS_PACRI_SP0 (30U) /*!< Bit position for AIPS_PACRI_SP0. */ #define BM_AIPS_PACRI_SP0 (0x40000000U) /*!< Bit mask for AIPS_PACRI_SP0. */ #define BS_AIPS_PACRI_SP0 (1U) /*!< Bit field size in bits for AIPS_PACRI_SP0. */ /*! @brief Read current value of the AIPS_PACRI_SP0 field. */ #define BR_AIPS_PACRI_SP0(x) (BITBAND_ACCESS32(HW_AIPS_PACRI_ADDR(x), BP_AIPS_PACRI_SP0)) /*! @brief Format value for bitfield AIPS_PACRI_SP0. */ #define BF_AIPS_PACRI_SP0(v) ((uint32_t)((uint32_t)(v) << BP_AIPS_PACRI_SP0) & BM_AIPS_PACRI_SP0) /*! @brief Set the SP0 field to a new value. */ #define BW_AIPS_PACRI_SP0(x, v) (BITBAND_ACCESS32(HW_AIPS_PACRI_ADDR(x), BP_AIPS_PACRI_SP0) = (v)) /*@}*/ /******************************************************************************* * HW_AIPS_PACRJ - Peripheral Access Control Register ******************************************************************************/ /*! * @brief HW_AIPS_PACRJ - Peripheral Access Control Register (RW) * * Reset value: 0x44444444U * * This section describes PACR registers E-P, which control peripheral slots * 32-127. See PACRPeripheral Access Control Register for the description of these * registers. */ typedef union _hw_aips_pacrj { uint32_t U; struct _hw_aips_pacrj_bitfields { uint32_t TP7 : 1; /*!< [0] Trusted Protect */ uint32_t WP7 : 1; /*!< [1] Write Protect */ uint32_t SP7 : 1; /*!< [2] Supervisor Protect */ uint32_t RESERVED0 : 1; /*!< [3] */ uint32_t TP6 : 1; /*!< [4] Trusted Protect */ uint32_t WP6 : 1; /*!< [5] Write Protect */ uint32_t SP6 : 1; /*!< [6] Supervisor Protect */ uint32_t RESERVED1 : 1; /*!< [7] */ uint32_t TP5 : 1; /*!< [8] Trusted Protect */ uint32_t WP5 : 1; /*!< [9] Write Protect */ uint32_t SP5 : 1; /*!< [10] Supervisor Protect */ uint32_t RESERVED2 : 1; /*!< [11] */ uint32_t TP4 : 1; /*!< [12] Trusted Protect */ uint32_t WP4 : 1; /*!< [13] Write Protect */ uint32_t SP4 : 1; /*!< [14] Supervisor Protect */ uint32_t RESERVED3 : 1; /*!< [15] */ uint32_t TP3 : 1; /*!< [16] Trusted Protect */ uint32_t WP3 : 1; /*!< [17] Write Protect */ uint32_t SP3 : 1; /*!< [18] Supervisor Protect */ uint32_t RESERVED4 : 1; /*!< [19] */ uint32_t TP2 : 1; /*!< [20] Trusted Protect */ uint32_t WP2 : 1; /*!< [21] Write Protect */ uint32_t SP2 : 1; /*!< [22] Supervisor Protect */ uint32_t RESERVED5 : 1; /*!< [23] */ uint32_t TP1 : 1; /*!< [24] Trusted Protect */ uint32_t WP1 : 1; /*!< [25] Write Protect */ uint32_t SP1 : 1; /*!< [26] Supervisor Protect */ uint32_t RESERVED6 : 1; /*!< [27] */ uint32_t TP0 : 1; /*!< [28] Trusted Protect */ uint32_t WP0 : 1; /*!< [29] Write Protect */ uint32_t SP0 : 1; /*!< [30] Supervisor Protect */ uint32_t RESERVED7 : 1; /*!< [31] */ } B; } hw_aips_pacrj_t; /*! * @name Constants and macros for entire AIPS_PACRJ register */ /*@{*/ #define HW_AIPS_PACRJ_ADDR(x) ((x) + 0x54U) #define HW_AIPS_PACRJ(x) (*(__IO hw_aips_pacrj_t *) HW_AIPS_PACRJ_ADDR(x)) #define HW_AIPS_PACRJ_RD(x) (HW_AIPS_PACRJ(x).U) #define HW_AIPS_PACRJ_WR(x, v) (HW_AIPS_PACRJ(x).U = (v)) #define HW_AIPS_PACRJ_SET(x, v) (HW_AIPS_PACRJ_WR(x, HW_AIPS_PACRJ_RD(x) | (v))) #define HW_AIPS_PACRJ_CLR(x, v) (HW_AIPS_PACRJ_WR(x, HW_AIPS_PACRJ_RD(x) & ~(v))) #define HW_AIPS_PACRJ_TOG(x, v) (HW_AIPS_PACRJ_WR(x, HW_AIPS_PACRJ_RD(x) ^ (v))) /*@}*/ /* * Constants & macros for individual AIPS_PACRJ bitfields */ /*! * @name Register AIPS_PACRJ, field TP7[0] (RW) * * Determines whether the peripheral allows accesses from an untrusted master. * When this field is set and an access is attempted by an untrusted master, the * access terminates with an error response and no peripheral access initiates. * * Values: * - 0 - Accesses from an untrusted master are allowed. * - 1 - Accesses from an untrusted master are not allowed. */ /*@{*/ #define BP_AIPS_PACRJ_TP7 (0U) /*!< Bit position for AIPS_PACRJ_TP7. */ #define BM_AIPS_PACRJ_TP7 (0x00000001U) /*!< Bit mask for AIPS_PACRJ_TP7. */ #define BS_AIPS_PACRJ_TP7 (1U) /*!< Bit field size in bits for AIPS_PACRJ_TP7. */ /*! @brief Read current value of the AIPS_PACRJ_TP7 field. */ #define BR_AIPS_PACRJ_TP7(x) (BITBAND_ACCESS32(HW_AIPS_PACRJ_ADDR(x), BP_AIPS_PACRJ_TP7)) /*! @brief Format value for bitfield AIPS_PACRJ_TP7. */ #define BF_AIPS_PACRJ_TP7(v) ((uint32_t)((uint32_t)(v) << BP_AIPS_PACRJ_TP7) & BM_AIPS_PACRJ_TP7) /*! @brief Set the TP7 field to a new value. */ #define BW_AIPS_PACRJ_TP7(x, v) (BITBAND_ACCESS32(HW_AIPS_PACRJ_ADDR(x), BP_AIPS_PACRJ_TP7) = (v)) /*@}*/ /*! * @name Register AIPS_PACRJ, field WP7[1] (RW) * * Determines whether the peripheral allows write accesses. When this field is * set and a write access is attempted, access terminates with an error response * and no peripheral access initiates. * * Values: * - 0 - This peripheral allows write accesses. * - 1 - This peripheral is write protected. */ /*@{*/ #define BP_AIPS_PACRJ_WP7 (1U) /*!< Bit position for AIPS_PACRJ_WP7. */ #define BM_AIPS_PACRJ_WP7 (0x00000002U) /*!< Bit mask for AIPS_PACRJ_WP7. */ #define BS_AIPS_PACRJ_WP7 (1U) /*!< Bit field size in bits for AIPS_PACRJ_WP7. */ /*! @brief Read current value of the AIPS_PACRJ_WP7 field. */ #define BR_AIPS_PACRJ_WP7(x) (BITBAND_ACCESS32(HW_AIPS_PACRJ_ADDR(x), BP_AIPS_PACRJ_WP7)) /*! @brief Format value for bitfield AIPS_PACRJ_WP7. */ #define BF_AIPS_PACRJ_WP7(v) ((uint32_t)((uint32_t)(v) << BP_AIPS_PACRJ_WP7) & BM_AIPS_PACRJ_WP7) /*! @brief Set the WP7 field to a new value. */ #define BW_AIPS_PACRJ_WP7(x, v) (BITBAND_ACCESS32(HW_AIPS_PACRJ_ADDR(x), BP_AIPS_PACRJ_WP7) = (v)) /*@}*/ /*! * @name Register AIPS_PACRJ, field SP7[2] (RW) * * Determines whether the peripheral requires supervisor privilege level for * accesses. When this field is set, the master privilege level must indicate the * supervisor access attribute, and the MPRx[MPLn] control field for the master * must be set. If not, access terminates with an error response and no peripheral * access initiates. * * Values: * - 0 - This peripheral does not require supervisor privilege level for * accesses. * - 1 - This peripheral requires supervisor privilege level for accesses. */ /*@{*/ #define BP_AIPS_PACRJ_SP7 (2U) /*!< Bit position for AIPS_PACRJ_SP7. */ #define BM_AIPS_PACRJ_SP7 (0x00000004U) /*!< Bit mask for AIPS_PACRJ_SP7. */ #define BS_AIPS_PACRJ_SP7 (1U) /*!< Bit field size in bits for AIPS_PACRJ_SP7. */ /*! @brief Read current value of the AIPS_PACRJ_SP7 field. */ #define BR_AIPS_PACRJ_SP7(x) (BITBAND_ACCESS32(HW_AIPS_PACRJ_ADDR(x), BP_AIPS_PACRJ_SP7)) /*! @brief Format value for bitfield AIPS_PACRJ_SP7. */ #define BF_AIPS_PACRJ_SP7(v) ((uint32_t)((uint32_t)(v) << BP_AIPS_PACRJ_SP7) & BM_AIPS_PACRJ_SP7) /*! @brief Set the SP7 field to a new value. */ #define BW_AIPS_PACRJ_SP7(x, v) (BITBAND_ACCESS32(HW_AIPS_PACRJ_ADDR(x), BP_AIPS_PACRJ_SP7) = (v)) /*@}*/ /*! * @name Register AIPS_PACRJ, field TP6[4] (RW) * * Determines whether the peripheral allows accesses from an untrusted master. * When this field is set and an access is attempted by an untrusted master, the * access terminates with an error response and no peripheral access initiates. * * Values: * - 0 - Accesses from an untrusted master are allowed. * - 1 - Accesses from an untrusted master are not allowed. */ /*@{*/ #define BP_AIPS_PACRJ_TP6 (4U) /*!< Bit position for AIPS_PACRJ_TP6. */ #define BM_AIPS_PACRJ_TP6 (0x00000010U) /*!< Bit mask for AIPS_PACRJ_TP6. */ #define BS_AIPS_PACRJ_TP6 (1U) /*!< Bit field size in bits for AIPS_PACRJ_TP6. */ /*! @brief Read current value of the AIPS_PACRJ_TP6 field. */ #define BR_AIPS_PACRJ_TP6(x) (BITBAND_ACCESS32(HW_AIPS_PACRJ_ADDR(x), BP_AIPS_PACRJ_TP6)) /*! @brief Format value for bitfield AIPS_PACRJ_TP6. */ #define BF_AIPS_PACRJ_TP6(v) ((uint32_t)((uint32_t)(v) << BP_AIPS_PACRJ_TP6) & BM_AIPS_PACRJ_TP6) /*! @brief Set the TP6 field to a new value. */ #define BW_AIPS_PACRJ_TP6(x, v) (BITBAND_ACCESS32(HW_AIPS_PACRJ_ADDR(x), BP_AIPS_PACRJ_TP6) = (v)) /*@}*/ /*! * @name Register AIPS_PACRJ, field WP6[5] (RW) * * Determines whether the peripheral allows write accesses. When this field is * set and a write access is attempted, access terminates with an error response * and no peripheral access initiates. * * Values: * - 0 - This peripheral allows write accesses. * - 1 - This peripheral is write protected. */ /*@{*/ #define BP_AIPS_PACRJ_WP6 (5U) /*!< Bit position for AIPS_PACRJ_WP6. */ #define BM_AIPS_PACRJ_WP6 (0x00000020U) /*!< Bit mask for AIPS_PACRJ_WP6. */ #define BS_AIPS_PACRJ_WP6 (1U) /*!< Bit field size in bits for AIPS_PACRJ_WP6. */ /*! @brief Read current value of the AIPS_PACRJ_WP6 field. */ #define BR_AIPS_PACRJ_WP6(x) (BITBAND_ACCESS32(HW_AIPS_PACRJ_ADDR(x), BP_AIPS_PACRJ_WP6)) /*! @brief Format value for bitfield AIPS_PACRJ_WP6. */ #define BF_AIPS_PACRJ_WP6(v) ((uint32_t)((uint32_t)(v) << BP_AIPS_PACRJ_WP6) & BM_AIPS_PACRJ_WP6) /*! @brief Set the WP6 field to a new value. */ #define BW_AIPS_PACRJ_WP6(x, v) (BITBAND_ACCESS32(HW_AIPS_PACRJ_ADDR(x), BP_AIPS_PACRJ_WP6) = (v)) /*@}*/ /*! * @name Register AIPS_PACRJ, field SP6[6] (RW) * * Determines whether the peripheral requires supervisor privilege level for * accesses. When this field is set, the master privilege level must indicate the * supervisor access attribute, and the MPRx[MPLn] control field for the master * must be set. If not, access terminates with an error response and no peripheral * access initiates. * * Values: * - 0 - This peripheral does not require supervisor privilege level for * accesses. * - 1 - This peripheral requires supervisor privilege level for accesses. */ /*@{*/ #define BP_AIPS_PACRJ_SP6 (6U) /*!< Bit position for AIPS_PACRJ_SP6. */ #define BM_AIPS_PACRJ_SP6 (0x00000040U) /*!< Bit mask for AIPS_PACRJ_SP6. */ #define BS_AIPS_PACRJ_SP6 (1U) /*!< Bit field size in bits for AIPS_PACRJ_SP6. */ /*! @brief Read current value of the AIPS_PACRJ_SP6 field. */ #define BR_AIPS_PACRJ_SP6(x) (BITBAND_ACCESS32(HW_AIPS_PACRJ_ADDR(x), BP_AIPS_PACRJ_SP6)) /*! @brief Format value for bitfield AIPS_PACRJ_SP6. */ #define BF_AIPS_PACRJ_SP6(v) ((uint32_t)((uint32_t)(v) << BP_AIPS_PACRJ_SP6) & BM_AIPS_PACRJ_SP6) /*! @brief Set the SP6 field to a new value. */ #define BW_AIPS_PACRJ_SP6(x, v) (BITBAND_ACCESS32(HW_AIPS_PACRJ_ADDR(x), BP_AIPS_PACRJ_SP6) = (v)) /*@}*/ /*! * @name Register AIPS_PACRJ, field TP5[8] (RW) * * Determines whether the peripheral allows accesses from an untrusted master. * When this field is set and an access is attempted by an untrusted master, the * access terminates with an error response and no peripheral access initiates. * * Values: * - 0 - Accesses from an untrusted master are allowed. * - 1 - Accesses from an untrusted master are not allowed. */ /*@{*/ #define BP_AIPS_PACRJ_TP5 (8U) /*!< Bit position for AIPS_PACRJ_TP5. */ #define BM_AIPS_PACRJ_TP5 (0x00000100U) /*!< Bit mask for AIPS_PACRJ_TP5. */ #define BS_AIPS_PACRJ_TP5 (1U) /*!< Bit field size in bits for AIPS_PACRJ_TP5. */ /*! @brief Read current value of the AIPS_PACRJ_TP5 field. */ #define BR_AIPS_PACRJ_TP5(x) (BITBAND_ACCESS32(HW_AIPS_PACRJ_ADDR(x), BP_AIPS_PACRJ_TP5)) /*! @brief Format value for bitfield AIPS_PACRJ_TP5. */ #define BF_AIPS_PACRJ_TP5(v) ((uint32_t)((uint32_t)(v) << BP_AIPS_PACRJ_TP5) & BM_AIPS_PACRJ_TP5) /*! @brief Set the TP5 field to a new value. */ #define BW_AIPS_PACRJ_TP5(x, v) (BITBAND_ACCESS32(HW_AIPS_PACRJ_ADDR(x), BP_AIPS_PACRJ_TP5) = (v)) /*@}*/ /*! * @name Register AIPS_PACRJ, field WP5[9] (RW) * * Determines whether the peripheral allows write accesses. When this field is * set and a write access is attempted, access terminates with an error response * and no peripheral access initiates. * * Values: * - 0 - This peripheral allows write accesses. * - 1 - This peripheral is write protected. */ /*@{*/ #define BP_AIPS_PACRJ_WP5 (9U) /*!< Bit position for AIPS_PACRJ_WP5. */ #define BM_AIPS_PACRJ_WP5 (0x00000200U) /*!< Bit mask for AIPS_PACRJ_WP5. */ #define BS_AIPS_PACRJ_WP5 (1U) /*!< Bit field size in bits for AIPS_PACRJ_WP5. */ /*! @brief Read current value of the AIPS_PACRJ_WP5 field. */ #define BR_AIPS_PACRJ_WP5(x) (BITBAND_ACCESS32(HW_AIPS_PACRJ_ADDR(x), BP_AIPS_PACRJ_WP5)) /*! @brief Format value for bitfield AIPS_PACRJ_WP5. */ #define BF_AIPS_PACRJ_WP5(v) ((uint32_t)((uint32_t)(v) << BP_AIPS_PACRJ_WP5) & BM_AIPS_PACRJ_WP5) /*! @brief Set the WP5 field to a new value. */ #define BW_AIPS_PACRJ_WP5(x, v) (BITBAND_ACCESS32(HW_AIPS_PACRJ_ADDR(x), BP_AIPS_PACRJ_WP5) = (v)) /*@}*/ /*! * @name Register AIPS_PACRJ, field SP5[10] (RW) * * Determines whether the peripheral requires supervisor privilege level for * accesses. When this field is set, the master privilege level must indicate the * supervisor access attribute, and the MPRx[MPLn] control field for the master * must be set. If not, access terminates with an error response and no peripheral * access initiates. * * Values: * - 0 - This peripheral does not require supervisor privilege level for * accesses. * - 1 - This peripheral requires supervisor privilege level for accesses. */ /*@{*/ #define BP_AIPS_PACRJ_SP5 (10U) /*!< Bit position for AIPS_PACRJ_SP5. */ #define BM_AIPS_PACRJ_SP5 (0x00000400U) /*!< Bit mask for AIPS_PACRJ_SP5. */ #define BS_AIPS_PACRJ_SP5 (1U) /*!< Bit field size in bits for AIPS_PACRJ_SP5. */ /*! @brief Read current value of the AIPS_PACRJ_SP5 field. */ #define BR_AIPS_PACRJ_SP5(x) (BITBAND_ACCESS32(HW_AIPS_PACRJ_ADDR(x), BP_AIPS_PACRJ_SP5)) /*! @brief Format value for bitfield AIPS_PACRJ_SP5. */ #define BF_AIPS_PACRJ_SP5(v) ((uint32_t)((uint32_t)(v) << BP_AIPS_PACRJ_SP5) & BM_AIPS_PACRJ_SP5) /*! @brief Set the SP5 field to a new value. */ #define BW_AIPS_PACRJ_SP5(x, v) (BITBAND_ACCESS32(HW_AIPS_PACRJ_ADDR(x), BP_AIPS_PACRJ_SP5) = (v)) /*@}*/ /*! * @name Register AIPS_PACRJ, field TP4[12] (RW) * * Determines whether the peripheral allows accesses from an untrusted master. * When this bit is set and an access is attempted by an untrusted master, the * access terminates with an error response and no peripheral access initiates. * * Values: * - 0 - Accesses from an untrusted master are allowed. * - 1 - Accesses from an untrusted master are not allowed. */ /*@{*/ #define BP_AIPS_PACRJ_TP4 (12U) /*!< Bit position for AIPS_PACRJ_TP4. */ #define BM_AIPS_PACRJ_TP4 (0x00001000U) /*!< Bit mask for AIPS_PACRJ_TP4. */ #define BS_AIPS_PACRJ_TP4 (1U) /*!< Bit field size in bits for AIPS_PACRJ_TP4. */ /*! @brief Read current value of the AIPS_PACRJ_TP4 field. */ #define BR_AIPS_PACRJ_TP4(x) (BITBAND_ACCESS32(HW_AIPS_PACRJ_ADDR(x), BP_AIPS_PACRJ_TP4)) /*! @brief Format value for bitfield AIPS_PACRJ_TP4. */ #define BF_AIPS_PACRJ_TP4(v) ((uint32_t)((uint32_t)(v) << BP_AIPS_PACRJ_TP4) & BM_AIPS_PACRJ_TP4) /*! @brief Set the TP4 field to a new value. */ #define BW_AIPS_PACRJ_TP4(x, v) (BITBAND_ACCESS32(HW_AIPS_PACRJ_ADDR(x), BP_AIPS_PACRJ_TP4) = (v)) /*@}*/ /*! * @name Register AIPS_PACRJ, field WP4[13] (RW) * * Determines whether the peripheral allows write accesses. When this field is * set and a write access is attempted, access terminates with an error response * and no peripheral access initiates. * * Values: * - 0 - This peripheral allows write accesses. * - 1 - This peripheral is write protected. */ /*@{*/ #define BP_AIPS_PACRJ_WP4 (13U) /*!< Bit position for AIPS_PACRJ_WP4. */ #define BM_AIPS_PACRJ_WP4 (0x00002000U) /*!< Bit mask for AIPS_PACRJ_WP4. */ #define BS_AIPS_PACRJ_WP4 (1U) /*!< Bit field size in bits for AIPS_PACRJ_WP4. */ /*! @brief Read current value of the AIPS_PACRJ_WP4 field. */ #define BR_AIPS_PACRJ_WP4(x) (BITBAND_ACCESS32(HW_AIPS_PACRJ_ADDR(x), BP_AIPS_PACRJ_WP4)) /*! @brief Format value for bitfield AIPS_PACRJ_WP4. */ #define BF_AIPS_PACRJ_WP4(v) ((uint32_t)((uint32_t)(v) << BP_AIPS_PACRJ_WP4) & BM_AIPS_PACRJ_WP4) /*! @brief Set the WP4 field to a new value. */ #define BW_AIPS_PACRJ_WP4(x, v) (BITBAND_ACCESS32(HW_AIPS_PACRJ_ADDR(x), BP_AIPS_PACRJ_WP4) = (v)) /*@}*/ /*! * @name Register AIPS_PACRJ, field SP4[14] (RW) * * Determines whether the peripheral requires supervisor privilege level for * access. When this bit is set, the master privilege level must indicate the * supervisor access attribute, and the MPRx[MPLn] control bit for the master must be * set. If not, access terminates with an error response and no peripheral access * initiates. * * Values: * - 0 - This peripheral does not require supervisor privilege level for * accesses. * - 1 - This peripheral requires supervisor privilege level for accesses. */ /*@{*/ #define BP_AIPS_PACRJ_SP4 (14U) /*!< Bit position for AIPS_PACRJ_SP4. */ #define BM_AIPS_PACRJ_SP4 (0x00004000U) /*!< Bit mask for AIPS_PACRJ_SP4. */ #define BS_AIPS_PACRJ_SP4 (1U) /*!< Bit field size in bits for AIPS_PACRJ_SP4. */ /*! @brief Read current value of the AIPS_PACRJ_SP4 field. */ #define BR_AIPS_PACRJ_SP4(x) (BITBAND_ACCESS32(HW_AIPS_PACRJ_ADDR(x), BP_AIPS_PACRJ_SP4)) /*! @brief Format value for bitfield AIPS_PACRJ_SP4. */ #define BF_AIPS_PACRJ_SP4(v) ((uint32_t)((uint32_t)(v) << BP_AIPS_PACRJ_SP4) & BM_AIPS_PACRJ_SP4) /*! @brief Set the SP4 field to a new value. */ #define BW_AIPS_PACRJ_SP4(x, v) (BITBAND_ACCESS32(HW_AIPS_PACRJ_ADDR(x), BP_AIPS_PACRJ_SP4) = (v)) /*@}*/ /*! * @name Register AIPS_PACRJ, field TP3[16] (RW) * * Determines whether the peripheral allows accesses from an untrusted master. * When this field is set and an access is attempted by an untrusted master, the * access terminates with an error response and no peripheral access initiates. * * Values: * - 0 - Accesses from an untrusted master are allowed. * - 1 - Accesses from an untrusted master are not allowed. */ /*@{*/ #define BP_AIPS_PACRJ_TP3 (16U) /*!< Bit position for AIPS_PACRJ_TP3. */ #define BM_AIPS_PACRJ_TP3 (0x00010000U) /*!< Bit mask for AIPS_PACRJ_TP3. */ #define BS_AIPS_PACRJ_TP3 (1U) /*!< Bit field size in bits for AIPS_PACRJ_TP3. */ /*! @brief Read current value of the AIPS_PACRJ_TP3 field. */ #define BR_AIPS_PACRJ_TP3(x) (BITBAND_ACCESS32(HW_AIPS_PACRJ_ADDR(x), BP_AIPS_PACRJ_TP3)) /*! @brief Format value for bitfield AIPS_PACRJ_TP3. */ #define BF_AIPS_PACRJ_TP3(v) ((uint32_t)((uint32_t)(v) << BP_AIPS_PACRJ_TP3) & BM_AIPS_PACRJ_TP3) /*! @brief Set the TP3 field to a new value. */ #define BW_AIPS_PACRJ_TP3(x, v) (BITBAND_ACCESS32(HW_AIPS_PACRJ_ADDR(x), BP_AIPS_PACRJ_TP3) = (v)) /*@}*/ /*! * @name Register AIPS_PACRJ, field WP3[17] (RW) * * Determines whether the peripheral allows write accesss. When this bit is set * and a write access is attempted, access terminates with an error response and * no peripheral access initiates. * * Values: * - 0 - This peripheral allows write accesses. * - 1 - This peripheral is write protected. */ /*@{*/ #define BP_AIPS_PACRJ_WP3 (17U) /*!< Bit position for AIPS_PACRJ_WP3. */ #define BM_AIPS_PACRJ_WP3 (0x00020000U) /*!< Bit mask for AIPS_PACRJ_WP3. */ #define BS_AIPS_PACRJ_WP3 (1U) /*!< Bit field size in bits for AIPS_PACRJ_WP3. */ /*! @brief Read current value of the AIPS_PACRJ_WP3 field. */ #define BR_AIPS_PACRJ_WP3(x) (BITBAND_ACCESS32(HW_AIPS_PACRJ_ADDR(x), BP_AIPS_PACRJ_WP3)) /*! @brief Format value for bitfield AIPS_PACRJ_WP3. */ #define BF_AIPS_PACRJ_WP3(v) ((uint32_t)((uint32_t)(v) << BP_AIPS_PACRJ_WP3) & BM_AIPS_PACRJ_WP3) /*! @brief Set the WP3 field to a new value. */ #define BW_AIPS_PACRJ_WP3(x, v) (BITBAND_ACCESS32(HW_AIPS_PACRJ_ADDR(x), BP_AIPS_PACRJ_WP3) = (v)) /*@}*/ /*! * @name Register AIPS_PACRJ, field SP3[18] (RW) * * Determines whether the peripheral requires supervisor privilege level for * accesses. When this field is set, the master privilege level must indicate the * supervisor access attribute, and the MPRx[MPLn] control field for the master * must be set. If not, access terminates with an error response and no peripheral * access initiates. * * Values: * - 0 - This peripheral does not require supervisor privilege level for * accesses. * - 1 - This peripheral requires supervisor privilege level for accesses. */ /*@{*/ #define BP_AIPS_PACRJ_SP3 (18U) /*!< Bit position for AIPS_PACRJ_SP3. */ #define BM_AIPS_PACRJ_SP3 (0x00040000U) /*!< Bit mask for AIPS_PACRJ_SP3. */ #define BS_AIPS_PACRJ_SP3 (1U) /*!< Bit field size in bits for AIPS_PACRJ_SP3. */ /*! @brief Read current value of the AIPS_PACRJ_SP3 field. */ #define BR_AIPS_PACRJ_SP3(x) (BITBAND_ACCESS32(HW_AIPS_PACRJ_ADDR(x), BP_AIPS_PACRJ_SP3)) /*! @brief Format value for bitfield AIPS_PACRJ_SP3. */ #define BF_AIPS_PACRJ_SP3(v) ((uint32_t)((uint32_t)(v) << BP_AIPS_PACRJ_SP3) & BM_AIPS_PACRJ_SP3) /*! @brief Set the SP3 field to a new value. */ #define BW_AIPS_PACRJ_SP3(x, v) (BITBAND_ACCESS32(HW_AIPS_PACRJ_ADDR(x), BP_AIPS_PACRJ_SP3) = (v)) /*@}*/ /*! * @name Register AIPS_PACRJ, field TP2[20] (RW) * * Determines whether the peripheral allows accesses from an untrusted master. * When this bit is set and an access is attempted by an untrusted master, the * access terminates with an error response and no peripheral access initiates. * * Values: * - 0 - Accesses from an untrusted master are allowed. * - 1 - Accesses from an untrusted master are not allowed. */ /*@{*/ #define BP_AIPS_PACRJ_TP2 (20U) /*!< Bit position for AIPS_PACRJ_TP2. */ #define BM_AIPS_PACRJ_TP2 (0x00100000U) /*!< Bit mask for AIPS_PACRJ_TP2. */ #define BS_AIPS_PACRJ_TP2 (1U) /*!< Bit field size in bits for AIPS_PACRJ_TP2. */ /*! @brief Read current value of the AIPS_PACRJ_TP2 field. */ #define BR_AIPS_PACRJ_TP2(x) (BITBAND_ACCESS32(HW_AIPS_PACRJ_ADDR(x), BP_AIPS_PACRJ_TP2)) /*! @brief Format value for bitfield AIPS_PACRJ_TP2. */ #define BF_AIPS_PACRJ_TP2(v) ((uint32_t)((uint32_t)(v) << BP_AIPS_PACRJ_TP2) & BM_AIPS_PACRJ_TP2) /*! @brief Set the TP2 field to a new value. */ #define BW_AIPS_PACRJ_TP2(x, v) (BITBAND_ACCESS32(HW_AIPS_PACRJ_ADDR(x), BP_AIPS_PACRJ_TP2) = (v)) /*@}*/ /*! * @name Register AIPS_PACRJ, field WP2[21] (RW) * * Determines whether the peripheral allows write accesses. When this field is * set and a write access is attempted, access terminates with an error response * and no peripheral access initiates. * * Values: * - 0 - This peripheral allows write accesses. * - 1 - This peripheral is write protected. */ /*@{*/ #define BP_AIPS_PACRJ_WP2 (21U) /*!< Bit position for AIPS_PACRJ_WP2. */ #define BM_AIPS_PACRJ_WP2 (0x00200000U) /*!< Bit mask for AIPS_PACRJ_WP2. */ #define BS_AIPS_PACRJ_WP2 (1U) /*!< Bit field size in bits for AIPS_PACRJ_WP2. */ /*! @brief Read current value of the AIPS_PACRJ_WP2 field. */ #define BR_AIPS_PACRJ_WP2(x) (BITBAND_ACCESS32(HW_AIPS_PACRJ_ADDR(x), BP_AIPS_PACRJ_WP2)) /*! @brief Format value for bitfield AIPS_PACRJ_WP2. */ #define BF_AIPS_PACRJ_WP2(v) ((uint32_t)((uint32_t)(v) << BP_AIPS_PACRJ_WP2) & BM_AIPS_PACRJ_WP2) /*! @brief Set the WP2 field to a new value. */ #define BW_AIPS_PACRJ_WP2(x, v) (BITBAND_ACCESS32(HW_AIPS_PACRJ_ADDR(x), BP_AIPS_PACRJ_WP2) = (v)) /*@}*/ /*! * @name Register AIPS_PACRJ, field SP2[22] (RW) * * Determines whether the peripheral requires supervisor privilege level for * access. When this bit is set, the master privilege level must indicate the * supervisor access attribute, and the MPRx[MPLn] control bit for the master must be * set. If not, access terminates with an error response and no peripheral access * initiates. * * Values: * - 0 - This peripheral does not require supervisor privilege level for * accesses. * - 1 - This peripheral requires supervisor privilege level for accesses. */ /*@{*/ #define BP_AIPS_PACRJ_SP2 (22U) /*!< Bit position for AIPS_PACRJ_SP2. */ #define BM_AIPS_PACRJ_SP2 (0x00400000U) /*!< Bit mask for AIPS_PACRJ_SP2. */ #define BS_AIPS_PACRJ_SP2 (1U) /*!< Bit field size in bits for AIPS_PACRJ_SP2. */ /*! @brief Read current value of the AIPS_PACRJ_SP2 field. */ #define BR_AIPS_PACRJ_SP2(x) (BITBAND_ACCESS32(HW_AIPS_PACRJ_ADDR(x), BP_AIPS_PACRJ_SP2)) /*! @brief Format value for bitfield AIPS_PACRJ_SP2. */ #define BF_AIPS_PACRJ_SP2(v) ((uint32_t)((uint32_t)(v) << BP_AIPS_PACRJ_SP2) & BM_AIPS_PACRJ_SP2) /*! @brief Set the SP2 field to a new value. */ #define BW_AIPS_PACRJ_SP2(x, v) (BITBAND_ACCESS32(HW_AIPS_PACRJ_ADDR(x), BP_AIPS_PACRJ_SP2) = (v)) /*@}*/ /*! * @name Register AIPS_PACRJ, field TP1[24] (RW) * * Determines whether the peripheral allows accesses from an untrusted master. * When this field is set and an access is attempted by an untrusted master, the * access terminates with an error response and no peripheral access initiates. * * Values: * - 0 - Accesses from an untrusted master are allowed. * - 1 - Accesses from an untrusted master are not allowed. */ /*@{*/ #define BP_AIPS_PACRJ_TP1 (24U) /*!< Bit position for AIPS_PACRJ_TP1. */ #define BM_AIPS_PACRJ_TP1 (0x01000000U) /*!< Bit mask for AIPS_PACRJ_TP1. */ #define BS_AIPS_PACRJ_TP1 (1U) /*!< Bit field size in bits for AIPS_PACRJ_TP1. */ /*! @brief Read current value of the AIPS_PACRJ_TP1 field. */ #define BR_AIPS_PACRJ_TP1(x) (BITBAND_ACCESS32(HW_AIPS_PACRJ_ADDR(x), BP_AIPS_PACRJ_TP1)) /*! @brief Format value for bitfield AIPS_PACRJ_TP1. */ #define BF_AIPS_PACRJ_TP1(v) ((uint32_t)((uint32_t)(v) << BP_AIPS_PACRJ_TP1) & BM_AIPS_PACRJ_TP1) /*! @brief Set the TP1 field to a new value. */ #define BW_AIPS_PACRJ_TP1(x, v) (BITBAND_ACCESS32(HW_AIPS_PACRJ_ADDR(x), BP_AIPS_PACRJ_TP1) = (v)) /*@}*/ /*! * @name Register AIPS_PACRJ, field WP1[25] (RW) * * Determines whether the peripheral allows write accesses. When this field is * set and a write access is attempted, access terminates with an error response * and no peripheral access initiates. * * Values: * - 0 - This peripheral allows write accesses. * - 1 - This peripheral is write protected. */ /*@{*/ #define BP_AIPS_PACRJ_WP1 (25U) /*!< Bit position for AIPS_PACRJ_WP1. */ #define BM_AIPS_PACRJ_WP1 (0x02000000U) /*!< Bit mask for AIPS_PACRJ_WP1. */ #define BS_AIPS_PACRJ_WP1 (1U) /*!< Bit field size in bits for AIPS_PACRJ_WP1. */ /*! @brief Read current value of the AIPS_PACRJ_WP1 field. */ #define BR_AIPS_PACRJ_WP1(x) (BITBAND_ACCESS32(HW_AIPS_PACRJ_ADDR(x), BP_AIPS_PACRJ_WP1)) /*! @brief Format value for bitfield AIPS_PACRJ_WP1. */ #define BF_AIPS_PACRJ_WP1(v) ((uint32_t)((uint32_t)(v) << BP_AIPS_PACRJ_WP1) & BM_AIPS_PACRJ_WP1) /*! @brief Set the WP1 field to a new value. */ #define BW_AIPS_PACRJ_WP1(x, v) (BITBAND_ACCESS32(HW_AIPS_PACRJ_ADDR(x), BP_AIPS_PACRJ_WP1) = (v)) /*@}*/ /*! * @name Register AIPS_PACRJ, field SP1[26] (RW) * * Determines whether the peripheral requires supervisor privilege level for * access. When this field is set, the master privilege level must indicate the * supervisor access attribute, and the MPRx[MPLn] control field for the master must * be set. If not, access terminates with an error response and no peripheral * access initiates. * * Values: * - 0 - This peripheral does not require supervisor privilege level for * accesses. * - 1 - This peripheral requires supervisor privilege level for accesses. */ /*@{*/ #define BP_AIPS_PACRJ_SP1 (26U) /*!< Bit position for AIPS_PACRJ_SP1. */ #define BM_AIPS_PACRJ_SP1 (0x04000000U) /*!< Bit mask for AIPS_PACRJ_SP1. */ #define BS_AIPS_PACRJ_SP1 (1U) /*!< Bit field size in bits for AIPS_PACRJ_SP1. */ /*! @brief Read current value of the AIPS_PACRJ_SP1 field. */ #define BR_AIPS_PACRJ_SP1(x) (BITBAND_ACCESS32(HW_AIPS_PACRJ_ADDR(x), BP_AIPS_PACRJ_SP1)) /*! @brief Format value for bitfield AIPS_PACRJ_SP1. */ #define BF_AIPS_PACRJ_SP1(v) ((uint32_t)((uint32_t)(v) << BP_AIPS_PACRJ_SP1) & BM_AIPS_PACRJ_SP1) /*! @brief Set the SP1 field to a new value. */ #define BW_AIPS_PACRJ_SP1(x, v) (BITBAND_ACCESS32(HW_AIPS_PACRJ_ADDR(x), BP_AIPS_PACRJ_SP1) = (v)) /*@}*/ /*! * @name Register AIPS_PACRJ, field TP0[28] (RW) * * Determines whether the peripheral allows accesses from an untrusted master. * When this bit is set and an access is attempted by an untrusted master, the * access terminates with an error response and no peripheral access initiates. * * Values: * - 0 - Accesses from an untrusted master are allowed. * - 1 - Accesses from an untrusted master are not allowed. */ /*@{*/ #define BP_AIPS_PACRJ_TP0 (28U) /*!< Bit position for AIPS_PACRJ_TP0. */ #define BM_AIPS_PACRJ_TP0 (0x10000000U) /*!< Bit mask for AIPS_PACRJ_TP0. */ #define BS_AIPS_PACRJ_TP0 (1U) /*!< Bit field size in bits for AIPS_PACRJ_TP0. */ /*! @brief Read current value of the AIPS_PACRJ_TP0 field. */ #define BR_AIPS_PACRJ_TP0(x) (BITBAND_ACCESS32(HW_AIPS_PACRJ_ADDR(x), BP_AIPS_PACRJ_TP0)) /*! @brief Format value for bitfield AIPS_PACRJ_TP0. */ #define BF_AIPS_PACRJ_TP0(v) ((uint32_t)((uint32_t)(v) << BP_AIPS_PACRJ_TP0) & BM_AIPS_PACRJ_TP0) /*! @brief Set the TP0 field to a new value. */ #define BW_AIPS_PACRJ_TP0(x, v) (BITBAND_ACCESS32(HW_AIPS_PACRJ_ADDR(x), BP_AIPS_PACRJ_TP0) = (v)) /*@}*/ /*! * @name Register AIPS_PACRJ, field WP0[29] (RW) * * Determines whether the peripheral allows write accesses. When this field is * set and a write access is attempted, access terminates with an error response * and no peripheral access initiates. * * Values: * - 0 - This peripheral allows write accesses. * - 1 - This peripheral is write protected. */ /*@{*/ #define BP_AIPS_PACRJ_WP0 (29U) /*!< Bit position for AIPS_PACRJ_WP0. */ #define BM_AIPS_PACRJ_WP0 (0x20000000U) /*!< Bit mask for AIPS_PACRJ_WP0. */ #define BS_AIPS_PACRJ_WP0 (1U) /*!< Bit field size in bits for AIPS_PACRJ_WP0. */ /*! @brief Read current value of the AIPS_PACRJ_WP0 field. */ #define BR_AIPS_PACRJ_WP0(x) (BITBAND_ACCESS32(HW_AIPS_PACRJ_ADDR(x), BP_AIPS_PACRJ_WP0)) /*! @brief Format value for bitfield AIPS_PACRJ_WP0. */ #define BF_AIPS_PACRJ_WP0(v) ((uint32_t)((uint32_t)(v) << BP_AIPS_PACRJ_WP0) & BM_AIPS_PACRJ_WP0) /*! @brief Set the WP0 field to a new value. */ #define BW_AIPS_PACRJ_WP0(x, v) (BITBAND_ACCESS32(HW_AIPS_PACRJ_ADDR(x), BP_AIPS_PACRJ_WP0) = (v)) /*@}*/ /*! * @name Register AIPS_PACRJ, field SP0[30] (RW) * * Determines whether the peripheral requires supervisor privilege level for * accesses. When this field is set, the master privilege level must indicate the * supervisor access attribute, and the MPRx[MPLn] control field for the master * must be set. If not, access terminates with an error response and no peripheral * access initiates. * * Values: * - 0 - This peripheral does not require supervisor privilege level for * accesses. * - 1 - This peripheral requires supervisor privilege level for accesses. */ /*@{*/ #define BP_AIPS_PACRJ_SP0 (30U) /*!< Bit position for AIPS_PACRJ_SP0. */ #define BM_AIPS_PACRJ_SP0 (0x40000000U) /*!< Bit mask for AIPS_PACRJ_SP0. */ #define BS_AIPS_PACRJ_SP0 (1U) /*!< Bit field size in bits for AIPS_PACRJ_SP0. */ /*! @brief Read current value of the AIPS_PACRJ_SP0 field. */ #define BR_AIPS_PACRJ_SP0(x) (BITBAND_ACCESS32(HW_AIPS_PACRJ_ADDR(x), BP_AIPS_PACRJ_SP0)) /*! @brief Format value for bitfield AIPS_PACRJ_SP0. */ #define BF_AIPS_PACRJ_SP0(v) ((uint32_t)((uint32_t)(v) << BP_AIPS_PACRJ_SP0) & BM_AIPS_PACRJ_SP0) /*! @brief Set the SP0 field to a new value. */ #define BW_AIPS_PACRJ_SP0(x, v) (BITBAND_ACCESS32(HW_AIPS_PACRJ_ADDR(x), BP_AIPS_PACRJ_SP0) = (v)) /*@}*/ /******************************************************************************* * HW_AIPS_PACRK - Peripheral Access Control Register ******************************************************************************/ /*! * @brief HW_AIPS_PACRK - Peripheral Access Control Register (RW) * * Reset value: 0x44444444U * * This section describes PACR registers E-P, which control peripheral slots * 32-127. See PACRPeripheral Access Control Register for the description of these * registers. */ typedef union _hw_aips_pacrk { uint32_t U; struct _hw_aips_pacrk_bitfields { uint32_t TP7 : 1; /*!< [0] Trusted Protect */ uint32_t WP7 : 1; /*!< [1] Write Protect */ uint32_t SP7 : 1; /*!< [2] Supervisor Protect */ uint32_t RESERVED0 : 1; /*!< [3] */ uint32_t TP6 : 1; /*!< [4] Trusted Protect */ uint32_t WP6 : 1; /*!< [5] Write Protect */ uint32_t SP6 : 1; /*!< [6] Supervisor Protect */ uint32_t RESERVED1 : 1; /*!< [7] */ uint32_t TP5 : 1; /*!< [8] Trusted Protect */ uint32_t WP5 : 1; /*!< [9] Write Protect */ uint32_t SP5 : 1; /*!< [10] Supervisor Protect */ uint32_t RESERVED2 : 1; /*!< [11] */ uint32_t TP4 : 1; /*!< [12] Trusted Protect */ uint32_t WP4 : 1; /*!< [13] Write Protect */ uint32_t SP4 : 1; /*!< [14] Supervisor Protect */ uint32_t RESERVED3 : 1; /*!< [15] */ uint32_t TP3 : 1; /*!< [16] Trusted Protect */ uint32_t WP3 : 1; /*!< [17] Write Protect */ uint32_t SP3 : 1; /*!< [18] Supervisor Protect */ uint32_t RESERVED4 : 1; /*!< [19] */ uint32_t TP2 : 1; /*!< [20] Trusted Protect */ uint32_t WP2 : 1; /*!< [21] Write Protect */ uint32_t SP2 : 1; /*!< [22] Supervisor Protect */ uint32_t RESERVED5 : 1; /*!< [23] */ uint32_t TP1 : 1; /*!< [24] Trusted Protect */ uint32_t WP1 : 1; /*!< [25] Write Protect */ uint32_t SP1 : 1; /*!< [26] Supervisor Protect */ uint32_t RESERVED6 : 1; /*!< [27] */ uint32_t TP0 : 1; /*!< [28] Trusted Protect */ uint32_t WP0 : 1; /*!< [29] Write Protect */ uint32_t SP0 : 1; /*!< [30] Supervisor Protect */ uint32_t RESERVED7 : 1; /*!< [31] */ } B; } hw_aips_pacrk_t; /*! * @name Constants and macros for entire AIPS_PACRK register */ /*@{*/ #define HW_AIPS_PACRK_ADDR(x) ((x) + 0x58U) #define HW_AIPS_PACRK(x) (*(__IO hw_aips_pacrk_t *) HW_AIPS_PACRK_ADDR(x)) #define HW_AIPS_PACRK_RD(x) (HW_AIPS_PACRK(x).U) #define HW_AIPS_PACRK_WR(x, v) (HW_AIPS_PACRK(x).U = (v)) #define HW_AIPS_PACRK_SET(x, v) (HW_AIPS_PACRK_WR(x, HW_AIPS_PACRK_RD(x) | (v))) #define HW_AIPS_PACRK_CLR(x, v) (HW_AIPS_PACRK_WR(x, HW_AIPS_PACRK_RD(x) & ~(v))) #define HW_AIPS_PACRK_TOG(x, v) (HW_AIPS_PACRK_WR(x, HW_AIPS_PACRK_RD(x) ^ (v))) /*@}*/ /* * Constants & macros for individual AIPS_PACRK bitfields */ /*! * @name Register AIPS_PACRK, field TP7[0] (RW) * * Determines whether the peripheral allows accesses from an untrusted master. * When this field is set and an access is attempted by an untrusted master, the * access terminates with an error response and no peripheral access initiates. * * Values: * - 0 - Accesses from an untrusted master are allowed. * - 1 - Accesses from an untrusted master are not allowed. */ /*@{*/ #define BP_AIPS_PACRK_TP7 (0U) /*!< Bit position for AIPS_PACRK_TP7. */ #define BM_AIPS_PACRK_TP7 (0x00000001U) /*!< Bit mask for AIPS_PACRK_TP7. */ #define BS_AIPS_PACRK_TP7 (1U) /*!< Bit field size in bits for AIPS_PACRK_TP7. */ /*! @brief Read current value of the AIPS_PACRK_TP7 field. */ #define BR_AIPS_PACRK_TP7(x) (BITBAND_ACCESS32(HW_AIPS_PACRK_ADDR(x), BP_AIPS_PACRK_TP7)) /*! @brief Format value for bitfield AIPS_PACRK_TP7. */ #define BF_AIPS_PACRK_TP7(v) ((uint32_t)((uint32_t)(v) << BP_AIPS_PACRK_TP7) & BM_AIPS_PACRK_TP7) /*! @brief Set the TP7 field to a new value. */ #define BW_AIPS_PACRK_TP7(x, v) (BITBAND_ACCESS32(HW_AIPS_PACRK_ADDR(x), BP_AIPS_PACRK_TP7) = (v)) /*@}*/ /*! * @name Register AIPS_PACRK, field WP7[1] (RW) * * Determines whether the peripheral allows write accesses. When this field is * set and a write access is attempted, access terminates with an error response * and no peripheral access initiates. * * Values: * - 0 - This peripheral allows write accesses. * - 1 - This peripheral is write protected. */ /*@{*/ #define BP_AIPS_PACRK_WP7 (1U) /*!< Bit position for AIPS_PACRK_WP7. */ #define BM_AIPS_PACRK_WP7 (0x00000002U) /*!< Bit mask for AIPS_PACRK_WP7. */ #define BS_AIPS_PACRK_WP7 (1U) /*!< Bit field size in bits for AIPS_PACRK_WP7. */ /*! @brief Read current value of the AIPS_PACRK_WP7 field. */ #define BR_AIPS_PACRK_WP7(x) (BITBAND_ACCESS32(HW_AIPS_PACRK_ADDR(x), BP_AIPS_PACRK_WP7)) /*! @brief Format value for bitfield AIPS_PACRK_WP7. */ #define BF_AIPS_PACRK_WP7(v) ((uint32_t)((uint32_t)(v) << BP_AIPS_PACRK_WP7) & BM_AIPS_PACRK_WP7) /*! @brief Set the WP7 field to a new value. */ #define BW_AIPS_PACRK_WP7(x, v) (BITBAND_ACCESS32(HW_AIPS_PACRK_ADDR(x), BP_AIPS_PACRK_WP7) = (v)) /*@}*/ /*! * @name Register AIPS_PACRK, field SP7[2] (RW) * * Determines whether the peripheral requires supervisor privilege level for * accesses. When this field is set, the master privilege level must indicate the * supervisor access attribute, and the MPRx[MPLn] control field for the master * must be set. If not, access terminates with an error response and no peripheral * access initiates. * * Values: * - 0 - This peripheral does not require supervisor privilege level for * accesses. * - 1 - This peripheral requires supervisor privilege level for accesses. */ /*@{*/ #define BP_AIPS_PACRK_SP7 (2U) /*!< Bit position for AIPS_PACRK_SP7. */ #define BM_AIPS_PACRK_SP7 (0x00000004U) /*!< Bit mask for AIPS_PACRK_SP7. */ #define BS_AIPS_PACRK_SP7 (1U) /*!< Bit field size in bits for AIPS_PACRK_SP7. */ /*! @brief Read current value of the AIPS_PACRK_SP7 field. */ #define BR_AIPS_PACRK_SP7(x) (BITBAND_ACCESS32(HW_AIPS_PACRK_ADDR(x), BP_AIPS_PACRK_SP7)) /*! @brief Format value for bitfield AIPS_PACRK_SP7. */ #define BF_AIPS_PACRK_SP7(v) ((uint32_t)((uint32_t)(v) << BP_AIPS_PACRK_SP7) & BM_AIPS_PACRK_SP7) /*! @brief Set the SP7 field to a new value. */ #define BW_AIPS_PACRK_SP7(x, v) (BITBAND_ACCESS32(HW_AIPS_PACRK_ADDR(x), BP_AIPS_PACRK_SP7) = (v)) /*@}*/ /*! * @name Register AIPS_PACRK, field TP6[4] (RW) * * Determines whether the peripheral allows accesses from an untrusted master. * When this field is set and an access is attempted by an untrusted master, the * access terminates with an error response and no peripheral access initiates. * * Values: * - 0 - Accesses from an untrusted master are allowed. * - 1 - Accesses from an untrusted master are not allowed. */ /*@{*/ #define BP_AIPS_PACRK_TP6 (4U) /*!< Bit position for AIPS_PACRK_TP6. */ #define BM_AIPS_PACRK_TP6 (0x00000010U) /*!< Bit mask for AIPS_PACRK_TP6. */ #define BS_AIPS_PACRK_TP6 (1U) /*!< Bit field size in bits for AIPS_PACRK_TP6. */ /*! @brief Read current value of the AIPS_PACRK_TP6 field. */ #define BR_AIPS_PACRK_TP6(x) (BITBAND_ACCESS32(HW_AIPS_PACRK_ADDR(x), BP_AIPS_PACRK_TP6)) /*! @brief Format value for bitfield AIPS_PACRK_TP6. */ #define BF_AIPS_PACRK_TP6(v) ((uint32_t)((uint32_t)(v) << BP_AIPS_PACRK_TP6) & BM_AIPS_PACRK_TP6) /*! @brief Set the TP6 field to a new value. */ #define BW_AIPS_PACRK_TP6(x, v) (BITBAND_ACCESS32(HW_AIPS_PACRK_ADDR(x), BP_AIPS_PACRK_TP6) = (v)) /*@}*/ /*! * @name Register AIPS_PACRK, field WP6[5] (RW) * * Determines whether the peripheral allows write accesses. When this field is * set and a write access is attempted, access terminates with an error response * and no peripheral access initiates. * * Values: * - 0 - This peripheral allows write accesses. * - 1 - This peripheral is write protected. */ /*@{*/ #define BP_AIPS_PACRK_WP6 (5U) /*!< Bit position for AIPS_PACRK_WP6. */ #define BM_AIPS_PACRK_WP6 (0x00000020U) /*!< Bit mask for AIPS_PACRK_WP6. */ #define BS_AIPS_PACRK_WP6 (1U) /*!< Bit field size in bits for AIPS_PACRK_WP6. */ /*! @brief Read current value of the AIPS_PACRK_WP6 field. */ #define BR_AIPS_PACRK_WP6(x) (BITBAND_ACCESS32(HW_AIPS_PACRK_ADDR(x), BP_AIPS_PACRK_WP6)) /*! @brief Format value for bitfield AIPS_PACRK_WP6. */ #define BF_AIPS_PACRK_WP6(v) ((uint32_t)((uint32_t)(v) << BP_AIPS_PACRK_WP6) & BM_AIPS_PACRK_WP6) /*! @brief Set the WP6 field to a new value. */ #define BW_AIPS_PACRK_WP6(x, v) (BITBAND_ACCESS32(HW_AIPS_PACRK_ADDR(x), BP_AIPS_PACRK_WP6) = (v)) /*@}*/ /*! * @name Register AIPS_PACRK, field SP6[6] (RW) * * Determines whether the peripheral requires supervisor privilege level for * accesses. When this field is set, the master privilege level must indicate the * supervisor access attribute, and the MPRx[MPLn] control field for the master * must be set. If not, access terminates with an error response and no peripheral * access initiates. * * Values: * - 0 - This peripheral does not require supervisor privilege level for * accesses. * - 1 - This peripheral requires supervisor privilege level for accesses. */ /*@{*/ #define BP_AIPS_PACRK_SP6 (6U) /*!< Bit position for AIPS_PACRK_SP6. */ #define BM_AIPS_PACRK_SP6 (0x00000040U) /*!< Bit mask for AIPS_PACRK_SP6. */ #define BS_AIPS_PACRK_SP6 (1U) /*!< Bit field size in bits for AIPS_PACRK_SP6. */ /*! @brief Read current value of the AIPS_PACRK_SP6 field. */ #define BR_AIPS_PACRK_SP6(x) (BITBAND_ACCESS32(HW_AIPS_PACRK_ADDR(x), BP_AIPS_PACRK_SP6)) /*! @brief Format value for bitfield AIPS_PACRK_SP6. */ #define BF_AIPS_PACRK_SP6(v) ((uint32_t)((uint32_t)(v) << BP_AIPS_PACRK_SP6) & BM_AIPS_PACRK_SP6) /*! @brief Set the SP6 field to a new value. */ #define BW_AIPS_PACRK_SP6(x, v) (BITBAND_ACCESS32(HW_AIPS_PACRK_ADDR(x), BP_AIPS_PACRK_SP6) = (v)) /*@}*/ /*! * @name Register AIPS_PACRK, field TP5[8] (RW) * * Determines whether the peripheral allows accesses from an untrusted master. * When this field is set and an access is attempted by an untrusted master, the * access terminates with an error response and no peripheral access initiates. * * Values: * - 0 - Accesses from an untrusted master are allowed. * - 1 - Accesses from an untrusted master are not allowed. */ /*@{*/ #define BP_AIPS_PACRK_TP5 (8U) /*!< Bit position for AIPS_PACRK_TP5. */ #define BM_AIPS_PACRK_TP5 (0x00000100U) /*!< Bit mask for AIPS_PACRK_TP5. */ #define BS_AIPS_PACRK_TP5 (1U) /*!< Bit field size in bits for AIPS_PACRK_TP5. */ /*! @brief Read current value of the AIPS_PACRK_TP5 field. */ #define BR_AIPS_PACRK_TP5(x) (BITBAND_ACCESS32(HW_AIPS_PACRK_ADDR(x), BP_AIPS_PACRK_TP5)) /*! @brief Format value for bitfield AIPS_PACRK_TP5. */ #define BF_AIPS_PACRK_TP5(v) ((uint32_t)((uint32_t)(v) << BP_AIPS_PACRK_TP5) & BM_AIPS_PACRK_TP5) /*! @brief Set the TP5 field to a new value. */ #define BW_AIPS_PACRK_TP5(x, v) (BITBAND_ACCESS32(HW_AIPS_PACRK_ADDR(x), BP_AIPS_PACRK_TP5) = (v)) /*@}*/ /*! * @name Register AIPS_PACRK, field WP5[9] (RW) * * Determines whether the peripheral allows write accesses. When this field is * set and a write access is attempted, access terminates with an error response * and no peripheral access initiates. * * Values: * - 0 - This peripheral allows write accesses. * - 1 - This peripheral is write protected. */ /*@{*/ #define BP_AIPS_PACRK_WP5 (9U) /*!< Bit position for AIPS_PACRK_WP5. */ #define BM_AIPS_PACRK_WP5 (0x00000200U) /*!< Bit mask for AIPS_PACRK_WP5. */ #define BS_AIPS_PACRK_WP5 (1U) /*!< Bit field size in bits for AIPS_PACRK_WP5. */ /*! @brief Read current value of the AIPS_PACRK_WP5 field. */ #define BR_AIPS_PACRK_WP5(x) (BITBAND_ACCESS32(HW_AIPS_PACRK_ADDR(x), BP_AIPS_PACRK_WP5)) /*! @brief Format value for bitfield AIPS_PACRK_WP5. */ #define BF_AIPS_PACRK_WP5(v) ((uint32_t)((uint32_t)(v) << BP_AIPS_PACRK_WP5) & BM_AIPS_PACRK_WP5) /*! @brief Set the WP5 field to a new value. */ #define BW_AIPS_PACRK_WP5(x, v) (BITBAND_ACCESS32(HW_AIPS_PACRK_ADDR(x), BP_AIPS_PACRK_WP5) = (v)) /*@}*/ /*! * @name Register AIPS_PACRK, field SP5[10] (RW) * * Determines whether the peripheral requires supervisor privilege level for * accesses. When this field is set, the master privilege level must indicate the * supervisor access attribute, and the MPRx[MPLn] control field for the master * must be set. If not, access terminates with an error response and no peripheral * access initiates. * * Values: * - 0 - This peripheral does not require supervisor privilege level for * accesses. * - 1 - This peripheral requires supervisor privilege level for accesses. */ /*@{*/ #define BP_AIPS_PACRK_SP5 (10U) /*!< Bit position for AIPS_PACRK_SP5. */ #define BM_AIPS_PACRK_SP5 (0x00000400U) /*!< Bit mask for AIPS_PACRK_SP5. */ #define BS_AIPS_PACRK_SP5 (1U) /*!< Bit field size in bits for AIPS_PACRK_SP5. */ /*! @brief Read current value of the AIPS_PACRK_SP5 field. */ #define BR_AIPS_PACRK_SP5(x) (BITBAND_ACCESS32(HW_AIPS_PACRK_ADDR(x), BP_AIPS_PACRK_SP5)) /*! @brief Format value for bitfield AIPS_PACRK_SP5. */ #define BF_AIPS_PACRK_SP5(v) ((uint32_t)((uint32_t)(v) << BP_AIPS_PACRK_SP5) & BM_AIPS_PACRK_SP5) /*! @brief Set the SP5 field to a new value. */ #define BW_AIPS_PACRK_SP5(x, v) (BITBAND_ACCESS32(HW_AIPS_PACRK_ADDR(x), BP_AIPS_PACRK_SP5) = (v)) /*@}*/ /*! * @name Register AIPS_PACRK, field TP4[12] (RW) * * Determines whether the peripheral allows accesses from an untrusted master. * When this bit is set and an access is attempted by an untrusted master, the * access terminates with an error response and no peripheral access initiates. * * Values: * - 0 - Accesses from an untrusted master are allowed. * - 1 - Accesses from an untrusted master are not allowed. */ /*@{*/ #define BP_AIPS_PACRK_TP4 (12U) /*!< Bit position for AIPS_PACRK_TP4. */ #define BM_AIPS_PACRK_TP4 (0x00001000U) /*!< Bit mask for AIPS_PACRK_TP4. */ #define BS_AIPS_PACRK_TP4 (1U) /*!< Bit field size in bits for AIPS_PACRK_TP4. */ /*! @brief Read current value of the AIPS_PACRK_TP4 field. */ #define BR_AIPS_PACRK_TP4(x) (BITBAND_ACCESS32(HW_AIPS_PACRK_ADDR(x), BP_AIPS_PACRK_TP4)) /*! @brief Format value for bitfield AIPS_PACRK_TP4. */ #define BF_AIPS_PACRK_TP4(v) ((uint32_t)((uint32_t)(v) << BP_AIPS_PACRK_TP4) & BM_AIPS_PACRK_TP4) /*! @brief Set the TP4 field to a new value. */ #define BW_AIPS_PACRK_TP4(x, v) (BITBAND_ACCESS32(HW_AIPS_PACRK_ADDR(x), BP_AIPS_PACRK_TP4) = (v)) /*@}*/ /*! * @name Register AIPS_PACRK, field WP4[13] (RW) * * Determines whether the peripheral allows write accesses. When this field is * set and a write access is attempted, access terminates with an error response * and no peripheral access initiates. * * Values: * - 0 - This peripheral allows write accesses. * - 1 - This peripheral is write protected. */ /*@{*/ #define BP_AIPS_PACRK_WP4 (13U) /*!< Bit position for AIPS_PACRK_WP4. */ #define BM_AIPS_PACRK_WP4 (0x00002000U) /*!< Bit mask for AIPS_PACRK_WP4. */ #define BS_AIPS_PACRK_WP4 (1U) /*!< Bit field size in bits for AIPS_PACRK_WP4. */ /*! @brief Read current value of the AIPS_PACRK_WP4 field. */ #define BR_AIPS_PACRK_WP4(x) (BITBAND_ACCESS32(HW_AIPS_PACRK_ADDR(x), BP_AIPS_PACRK_WP4)) /*! @brief Format value for bitfield AIPS_PACRK_WP4. */ #define BF_AIPS_PACRK_WP4(v) ((uint32_t)((uint32_t)(v) << BP_AIPS_PACRK_WP4) & BM_AIPS_PACRK_WP4) /*! @brief Set the WP4 field to a new value. */ #define BW_AIPS_PACRK_WP4(x, v) (BITBAND_ACCESS32(HW_AIPS_PACRK_ADDR(x), BP_AIPS_PACRK_WP4) = (v)) /*@}*/ /*! * @name Register AIPS_PACRK, field SP4[14] (RW) * * Determines whether the peripheral requires supervisor privilege level for * access. When this bit is set, the master privilege level must indicate the * supervisor access attribute, and the MPRx[MPLn] control bit for the master must be * set. If not, access terminates with an error response and no peripheral access * initiates. * * Values: * - 0 - This peripheral does not require supervisor privilege level for * accesses. * - 1 - This peripheral requires supervisor privilege level for accesses. */ /*@{*/ #define BP_AIPS_PACRK_SP4 (14U) /*!< Bit position for AIPS_PACRK_SP4. */ #define BM_AIPS_PACRK_SP4 (0x00004000U) /*!< Bit mask for AIPS_PACRK_SP4. */ #define BS_AIPS_PACRK_SP4 (1U) /*!< Bit field size in bits for AIPS_PACRK_SP4. */ /*! @brief Read current value of the AIPS_PACRK_SP4 field. */ #define BR_AIPS_PACRK_SP4(x) (BITBAND_ACCESS32(HW_AIPS_PACRK_ADDR(x), BP_AIPS_PACRK_SP4)) /*! @brief Format value for bitfield AIPS_PACRK_SP4. */ #define BF_AIPS_PACRK_SP4(v) ((uint32_t)((uint32_t)(v) << BP_AIPS_PACRK_SP4) & BM_AIPS_PACRK_SP4) /*! @brief Set the SP4 field to a new value. */ #define BW_AIPS_PACRK_SP4(x, v) (BITBAND_ACCESS32(HW_AIPS_PACRK_ADDR(x), BP_AIPS_PACRK_SP4) = (v)) /*@}*/ /*! * @name Register AIPS_PACRK, field TP3[16] (RW) * * Determines whether the peripheral allows accesses from an untrusted master. * When this field is set and an access is attempted by an untrusted master, the * access terminates with an error response and no peripheral access initiates. * * Values: * - 0 - Accesses from an untrusted master are allowed. * - 1 - Accesses from an untrusted master are not allowed. */ /*@{*/ #define BP_AIPS_PACRK_TP3 (16U) /*!< Bit position for AIPS_PACRK_TP3. */ #define BM_AIPS_PACRK_TP3 (0x00010000U) /*!< Bit mask for AIPS_PACRK_TP3. */ #define BS_AIPS_PACRK_TP3 (1U) /*!< Bit field size in bits for AIPS_PACRK_TP3. */ /*! @brief Read current value of the AIPS_PACRK_TP3 field. */ #define BR_AIPS_PACRK_TP3(x) (BITBAND_ACCESS32(HW_AIPS_PACRK_ADDR(x), BP_AIPS_PACRK_TP3)) /*! @brief Format value for bitfield AIPS_PACRK_TP3. */ #define BF_AIPS_PACRK_TP3(v) ((uint32_t)((uint32_t)(v) << BP_AIPS_PACRK_TP3) & BM_AIPS_PACRK_TP3) /*! @brief Set the TP3 field to a new value. */ #define BW_AIPS_PACRK_TP3(x, v) (BITBAND_ACCESS32(HW_AIPS_PACRK_ADDR(x), BP_AIPS_PACRK_TP3) = (v)) /*@}*/ /*! * @name Register AIPS_PACRK, field WP3[17] (RW) * * Determines whether the peripheral allows write accesss. When this bit is set * and a write access is attempted, access terminates with an error response and * no peripheral access initiates. * * Values: * - 0 - This peripheral allows write accesses. * - 1 - This peripheral is write protected. */ /*@{*/ #define BP_AIPS_PACRK_WP3 (17U) /*!< Bit position for AIPS_PACRK_WP3. */ #define BM_AIPS_PACRK_WP3 (0x00020000U) /*!< Bit mask for AIPS_PACRK_WP3. */ #define BS_AIPS_PACRK_WP3 (1U) /*!< Bit field size in bits for AIPS_PACRK_WP3. */ /*! @brief Read current value of the AIPS_PACRK_WP3 field. */ #define BR_AIPS_PACRK_WP3(x) (BITBAND_ACCESS32(HW_AIPS_PACRK_ADDR(x), BP_AIPS_PACRK_WP3)) /*! @brief Format value for bitfield AIPS_PACRK_WP3. */ #define BF_AIPS_PACRK_WP3(v) ((uint32_t)((uint32_t)(v) << BP_AIPS_PACRK_WP3) & BM_AIPS_PACRK_WP3) /*! @brief Set the WP3 field to a new value. */ #define BW_AIPS_PACRK_WP3(x, v) (BITBAND_ACCESS32(HW_AIPS_PACRK_ADDR(x), BP_AIPS_PACRK_WP3) = (v)) /*@}*/ /*! * @name Register AIPS_PACRK, field SP3[18] (RW) * * Determines whether the peripheral requires supervisor privilege level for * accesses. When this field is set, the master privilege level must indicate the * supervisor access attribute, and the MPRx[MPLn] control field for the master * must be set. If not, access terminates with an error response and no peripheral * access initiates. * * Values: * - 0 - This peripheral does not require supervisor privilege level for * accesses. * - 1 - This peripheral requires supervisor privilege level for accesses. */ /*@{*/ #define BP_AIPS_PACRK_SP3 (18U) /*!< Bit position for AIPS_PACRK_SP3. */ #define BM_AIPS_PACRK_SP3 (0x00040000U) /*!< Bit mask for AIPS_PACRK_SP3. */ #define BS_AIPS_PACRK_SP3 (1U) /*!< Bit field size in bits for AIPS_PACRK_SP3. */ /*! @brief Read current value of the AIPS_PACRK_SP3 field. */ #define BR_AIPS_PACRK_SP3(x) (BITBAND_ACCESS32(HW_AIPS_PACRK_ADDR(x), BP_AIPS_PACRK_SP3)) /*! @brief Format value for bitfield AIPS_PACRK_SP3. */ #define BF_AIPS_PACRK_SP3(v) ((uint32_t)((uint32_t)(v) << BP_AIPS_PACRK_SP3) & BM_AIPS_PACRK_SP3) /*! @brief Set the SP3 field to a new value. */ #define BW_AIPS_PACRK_SP3(x, v) (BITBAND_ACCESS32(HW_AIPS_PACRK_ADDR(x), BP_AIPS_PACRK_SP3) = (v)) /*@}*/ /*! * @name Register AIPS_PACRK, field TP2[20] (RW) * * Determines whether the peripheral allows accesses from an untrusted master. * When this bit is set and an access is attempted by an untrusted master, the * access terminates with an error response and no peripheral access initiates. * * Values: * - 0 - Accesses from an untrusted master are allowed. * - 1 - Accesses from an untrusted master are not allowed. */ /*@{*/ #define BP_AIPS_PACRK_TP2 (20U) /*!< Bit position for AIPS_PACRK_TP2. */ #define BM_AIPS_PACRK_TP2 (0x00100000U) /*!< Bit mask for AIPS_PACRK_TP2. */ #define BS_AIPS_PACRK_TP2 (1U) /*!< Bit field size in bits for AIPS_PACRK_TP2. */ /*! @brief Read current value of the AIPS_PACRK_TP2 field. */ #define BR_AIPS_PACRK_TP2(x) (BITBAND_ACCESS32(HW_AIPS_PACRK_ADDR(x), BP_AIPS_PACRK_TP2)) /*! @brief Format value for bitfield AIPS_PACRK_TP2. */ #define BF_AIPS_PACRK_TP2(v) ((uint32_t)((uint32_t)(v) << BP_AIPS_PACRK_TP2) & BM_AIPS_PACRK_TP2) /*! @brief Set the TP2 field to a new value. */ #define BW_AIPS_PACRK_TP2(x, v) (BITBAND_ACCESS32(HW_AIPS_PACRK_ADDR(x), BP_AIPS_PACRK_TP2) = (v)) /*@}*/ /*! * @name Register AIPS_PACRK, field WP2[21] (RW) * * Determines whether the peripheral allows write accesses. When this field is * set and a write access is attempted, access terminates with an error response * and no peripheral access initiates. * * Values: * - 0 - This peripheral allows write accesses. * - 1 - This peripheral is write protected. */ /*@{*/ #define BP_AIPS_PACRK_WP2 (21U) /*!< Bit position for AIPS_PACRK_WP2. */ #define BM_AIPS_PACRK_WP2 (0x00200000U) /*!< Bit mask for AIPS_PACRK_WP2. */ #define BS_AIPS_PACRK_WP2 (1U) /*!< Bit field size in bits for AIPS_PACRK_WP2. */ /*! @brief Read current value of the AIPS_PACRK_WP2 field. */ #define BR_AIPS_PACRK_WP2(x) (BITBAND_ACCESS32(HW_AIPS_PACRK_ADDR(x), BP_AIPS_PACRK_WP2)) /*! @brief Format value for bitfield AIPS_PACRK_WP2. */ #define BF_AIPS_PACRK_WP2(v) ((uint32_t)((uint32_t)(v) << BP_AIPS_PACRK_WP2) & BM_AIPS_PACRK_WP2) /*! @brief Set the WP2 field to a new value. */ #define BW_AIPS_PACRK_WP2(x, v) (BITBAND_ACCESS32(HW_AIPS_PACRK_ADDR(x), BP_AIPS_PACRK_WP2) = (v)) /*@}*/ /*! * @name Register AIPS_PACRK, field SP2[22] (RW) * * Determines whether the peripheral requires supervisor privilege level for * access. When this bit is set, the master privilege level must indicate the * supervisor access attribute, and the MPRx[MPLn] control bit for the master must be * set. If not, access terminates with an error response and no peripheral access * initiates. * * Values: * - 0 - This peripheral does not require supervisor privilege level for * accesses. * - 1 - This peripheral requires supervisor privilege level for accesses. */ /*@{*/ #define BP_AIPS_PACRK_SP2 (22U) /*!< Bit position for AIPS_PACRK_SP2. */ #define BM_AIPS_PACRK_SP2 (0x00400000U) /*!< Bit mask for AIPS_PACRK_SP2. */ #define BS_AIPS_PACRK_SP2 (1U) /*!< Bit field size in bits for AIPS_PACRK_SP2. */ /*! @brief Read current value of the AIPS_PACRK_SP2 field. */ #define BR_AIPS_PACRK_SP2(x) (BITBAND_ACCESS32(HW_AIPS_PACRK_ADDR(x), BP_AIPS_PACRK_SP2)) /*! @brief Format value for bitfield AIPS_PACRK_SP2. */ #define BF_AIPS_PACRK_SP2(v) ((uint32_t)((uint32_t)(v) << BP_AIPS_PACRK_SP2) & BM_AIPS_PACRK_SP2) /*! @brief Set the SP2 field to a new value. */ #define BW_AIPS_PACRK_SP2(x, v) (BITBAND_ACCESS32(HW_AIPS_PACRK_ADDR(x), BP_AIPS_PACRK_SP2) = (v)) /*@}*/ /*! * @name Register AIPS_PACRK, field TP1[24] (RW) * * Determines whether the peripheral allows accesses from an untrusted master. * When this field is set and an access is attempted by an untrusted master, the * access terminates with an error response and no peripheral access initiates. * * Values: * - 0 - Accesses from an untrusted master are allowed. * - 1 - Accesses from an untrusted master are not allowed. */ /*@{*/ #define BP_AIPS_PACRK_TP1 (24U) /*!< Bit position for AIPS_PACRK_TP1. */ #define BM_AIPS_PACRK_TP1 (0x01000000U) /*!< Bit mask for AIPS_PACRK_TP1. */ #define BS_AIPS_PACRK_TP1 (1U) /*!< Bit field size in bits for AIPS_PACRK_TP1. */ /*! @brief Read current value of the AIPS_PACRK_TP1 field. */ #define BR_AIPS_PACRK_TP1(x) (BITBAND_ACCESS32(HW_AIPS_PACRK_ADDR(x), BP_AIPS_PACRK_TP1)) /*! @brief Format value for bitfield AIPS_PACRK_TP1. */ #define BF_AIPS_PACRK_TP1(v) ((uint32_t)((uint32_t)(v) << BP_AIPS_PACRK_TP1) & BM_AIPS_PACRK_TP1) /*! @brief Set the TP1 field to a new value. */ #define BW_AIPS_PACRK_TP1(x, v) (BITBAND_ACCESS32(HW_AIPS_PACRK_ADDR(x), BP_AIPS_PACRK_TP1) = (v)) /*@}*/ /*! * @name Register AIPS_PACRK, field WP1[25] (RW) * * Determines whether the peripheral allows write accesses. When this field is * set and a write access is attempted, access terminates with an error response * and no peripheral access initiates. * * Values: * - 0 - This peripheral allows write accesses. * - 1 - This peripheral is write protected. */ /*@{*/ #define BP_AIPS_PACRK_WP1 (25U) /*!< Bit position for AIPS_PACRK_WP1. */ #define BM_AIPS_PACRK_WP1 (0x02000000U) /*!< Bit mask for AIPS_PACRK_WP1. */ #define BS_AIPS_PACRK_WP1 (1U) /*!< Bit field size in bits for AIPS_PACRK_WP1. */ /*! @brief Read current value of the AIPS_PACRK_WP1 field. */ #define BR_AIPS_PACRK_WP1(x) (BITBAND_ACCESS32(HW_AIPS_PACRK_ADDR(x), BP_AIPS_PACRK_WP1)) /*! @brief Format value for bitfield AIPS_PACRK_WP1. */ #define BF_AIPS_PACRK_WP1(v) ((uint32_t)((uint32_t)(v) << BP_AIPS_PACRK_WP1) & BM_AIPS_PACRK_WP1) /*! @brief Set the WP1 field to a new value. */ #define BW_AIPS_PACRK_WP1(x, v) (BITBAND_ACCESS32(HW_AIPS_PACRK_ADDR(x), BP_AIPS_PACRK_WP1) = (v)) /*@}*/ /*! * @name Register AIPS_PACRK, field SP1[26] (RW) * * Determines whether the peripheral requires supervisor privilege level for * access. When this field is set, the master privilege level must indicate the * supervisor access attribute, and the MPRx[MPLn] control field for the master must * be set. If not, access terminates with an error response and no peripheral * access initiates. * * Values: * - 0 - This peripheral does not require supervisor privilege level for * accesses. * - 1 - This peripheral requires supervisor privilege level for accesses. */ /*@{*/ #define BP_AIPS_PACRK_SP1 (26U) /*!< Bit position for AIPS_PACRK_SP1. */ #define BM_AIPS_PACRK_SP1 (0x04000000U) /*!< Bit mask for AIPS_PACRK_SP1. */ #define BS_AIPS_PACRK_SP1 (1U) /*!< Bit field size in bits for AIPS_PACRK_SP1. */ /*! @brief Read current value of the AIPS_PACRK_SP1 field. */ #define BR_AIPS_PACRK_SP1(x) (BITBAND_ACCESS32(HW_AIPS_PACRK_ADDR(x), BP_AIPS_PACRK_SP1)) /*! @brief Format value for bitfield AIPS_PACRK_SP1. */ #define BF_AIPS_PACRK_SP1(v) ((uint32_t)((uint32_t)(v) << BP_AIPS_PACRK_SP1) & BM_AIPS_PACRK_SP1) /*! @brief Set the SP1 field to a new value. */ #define BW_AIPS_PACRK_SP1(x, v) (BITBAND_ACCESS32(HW_AIPS_PACRK_ADDR(x), BP_AIPS_PACRK_SP1) = (v)) /*@}*/ /*! * @name Register AIPS_PACRK, field TP0[28] (RW) * * Determines whether the peripheral allows accesses from an untrusted master. * When this bit is set and an access is attempted by an untrusted master, the * access terminates with an error response and no peripheral access initiates. * * Values: * - 0 - Accesses from an untrusted master are allowed. * - 1 - Accesses from an untrusted master are not allowed. */ /*@{*/ #define BP_AIPS_PACRK_TP0 (28U) /*!< Bit position for AIPS_PACRK_TP0. */ #define BM_AIPS_PACRK_TP0 (0x10000000U) /*!< Bit mask for AIPS_PACRK_TP0. */ #define BS_AIPS_PACRK_TP0 (1U) /*!< Bit field size in bits for AIPS_PACRK_TP0. */ /*! @brief Read current value of the AIPS_PACRK_TP0 field. */ #define BR_AIPS_PACRK_TP0(x) (BITBAND_ACCESS32(HW_AIPS_PACRK_ADDR(x), BP_AIPS_PACRK_TP0)) /*! @brief Format value for bitfield AIPS_PACRK_TP0. */ #define BF_AIPS_PACRK_TP0(v) ((uint32_t)((uint32_t)(v) << BP_AIPS_PACRK_TP0) & BM_AIPS_PACRK_TP0) /*! @brief Set the TP0 field to a new value. */ #define BW_AIPS_PACRK_TP0(x, v) (BITBAND_ACCESS32(HW_AIPS_PACRK_ADDR(x), BP_AIPS_PACRK_TP0) = (v)) /*@}*/ /*! * @name Register AIPS_PACRK, field WP0[29] (RW) * * Determines whether the peripheral allows write accesses. When this field is * set and a write access is attempted, access terminates with an error response * and no peripheral access initiates. * * Values: * - 0 - This peripheral allows write accesses. * - 1 - This peripheral is write protected. */ /*@{*/ #define BP_AIPS_PACRK_WP0 (29U) /*!< Bit position for AIPS_PACRK_WP0. */ #define BM_AIPS_PACRK_WP0 (0x20000000U) /*!< Bit mask for AIPS_PACRK_WP0. */ #define BS_AIPS_PACRK_WP0 (1U) /*!< Bit field size in bits for AIPS_PACRK_WP0. */ /*! @brief Read current value of the AIPS_PACRK_WP0 field. */ #define BR_AIPS_PACRK_WP0(x) (BITBAND_ACCESS32(HW_AIPS_PACRK_ADDR(x), BP_AIPS_PACRK_WP0)) /*! @brief Format value for bitfield AIPS_PACRK_WP0. */ #define BF_AIPS_PACRK_WP0(v) ((uint32_t)((uint32_t)(v) << BP_AIPS_PACRK_WP0) & BM_AIPS_PACRK_WP0) /*! @brief Set the WP0 field to a new value. */ #define BW_AIPS_PACRK_WP0(x, v) (BITBAND_ACCESS32(HW_AIPS_PACRK_ADDR(x), BP_AIPS_PACRK_WP0) = (v)) /*@}*/ /*! * @name Register AIPS_PACRK, field SP0[30] (RW) * * Determines whether the peripheral requires supervisor privilege level for * accesses. When this field is set, the master privilege level must indicate the * supervisor access attribute, and the MPRx[MPLn] control field for the master * must be set. If not, access terminates with an error response and no peripheral * access initiates. * * Values: * - 0 - This peripheral does not require supervisor privilege level for * accesses. * - 1 - This peripheral requires supervisor privilege level for accesses. */ /*@{*/ #define BP_AIPS_PACRK_SP0 (30U) /*!< Bit position for AIPS_PACRK_SP0. */ #define BM_AIPS_PACRK_SP0 (0x40000000U) /*!< Bit mask for AIPS_PACRK_SP0. */ #define BS_AIPS_PACRK_SP0 (1U) /*!< Bit field size in bits for AIPS_PACRK_SP0. */ /*! @brief Read current value of the AIPS_PACRK_SP0 field. */ #define BR_AIPS_PACRK_SP0(x) (BITBAND_ACCESS32(HW_AIPS_PACRK_ADDR(x), BP_AIPS_PACRK_SP0)) /*! @brief Format value for bitfield AIPS_PACRK_SP0. */ #define BF_AIPS_PACRK_SP0(v) ((uint32_t)((uint32_t)(v) << BP_AIPS_PACRK_SP0) & BM_AIPS_PACRK_SP0) /*! @brief Set the SP0 field to a new value. */ #define BW_AIPS_PACRK_SP0(x, v) (BITBAND_ACCESS32(HW_AIPS_PACRK_ADDR(x), BP_AIPS_PACRK_SP0) = (v)) /*@}*/ /******************************************************************************* * HW_AIPS_PACRL - Peripheral Access Control Register ******************************************************************************/ /*! * @brief HW_AIPS_PACRL - Peripheral Access Control Register (RW) * * Reset value: 0x44444444U * * This section describes PACR registers E-P, which control peripheral slots * 32-127. See PACRPeripheral Access Control Register for the description of these * registers. */ typedef union _hw_aips_pacrl { uint32_t U; struct _hw_aips_pacrl_bitfields { uint32_t TP7 : 1; /*!< [0] Trusted Protect */ uint32_t WP7 : 1; /*!< [1] Write Protect */ uint32_t SP7 : 1; /*!< [2] Supervisor Protect */ uint32_t RESERVED0 : 1; /*!< [3] */ uint32_t TP6 : 1; /*!< [4] Trusted Protect */ uint32_t WP6 : 1; /*!< [5] Write Protect */ uint32_t SP6 : 1; /*!< [6] Supervisor Protect */ uint32_t RESERVED1 : 1; /*!< [7] */ uint32_t TP5 : 1; /*!< [8] Trusted Protect */ uint32_t WP5 : 1; /*!< [9] Write Protect */ uint32_t SP5 : 1; /*!< [10] Supervisor Protect */ uint32_t RESERVED2 : 1; /*!< [11] */ uint32_t TP4 : 1; /*!< [12] Trusted Protect */ uint32_t WP4 : 1; /*!< [13] Write Protect */ uint32_t SP4 : 1; /*!< [14] Supervisor Protect */ uint32_t RESERVED3 : 1; /*!< [15] */ uint32_t TP3 : 1; /*!< [16] Trusted Protect */ uint32_t WP3 : 1; /*!< [17] Write Protect */ uint32_t SP3 : 1; /*!< [18] Supervisor Protect */ uint32_t RESERVED4 : 1; /*!< [19] */ uint32_t TP2 : 1; /*!< [20] Trusted Protect */ uint32_t WP2 : 1; /*!< [21] Write Protect */ uint32_t SP2 : 1; /*!< [22] Supervisor Protect */ uint32_t RESERVED5 : 1; /*!< [23] */ uint32_t TP1 : 1; /*!< [24] Trusted Protect */ uint32_t WP1 : 1; /*!< [25] Write Protect */ uint32_t SP1 : 1; /*!< [26] Supervisor Protect */ uint32_t RESERVED6 : 1; /*!< [27] */ uint32_t TP0 : 1; /*!< [28] Trusted Protect */ uint32_t WP0 : 1; /*!< [29] Write Protect */ uint32_t SP0 : 1; /*!< [30] Supervisor Protect */ uint32_t RESERVED7 : 1; /*!< [31] */ } B; } hw_aips_pacrl_t; /*! * @name Constants and macros for entire AIPS_PACRL register */ /*@{*/ #define HW_AIPS_PACRL_ADDR(x) ((x) + 0x5CU) #define HW_AIPS_PACRL(x) (*(__IO hw_aips_pacrl_t *) HW_AIPS_PACRL_ADDR(x)) #define HW_AIPS_PACRL_RD(x) (HW_AIPS_PACRL(x).U) #define HW_AIPS_PACRL_WR(x, v) (HW_AIPS_PACRL(x).U = (v)) #define HW_AIPS_PACRL_SET(x, v) (HW_AIPS_PACRL_WR(x, HW_AIPS_PACRL_RD(x) | (v))) #define HW_AIPS_PACRL_CLR(x, v) (HW_AIPS_PACRL_WR(x, HW_AIPS_PACRL_RD(x) & ~(v))) #define HW_AIPS_PACRL_TOG(x, v) (HW_AIPS_PACRL_WR(x, HW_AIPS_PACRL_RD(x) ^ (v))) /*@}*/ /* * Constants & macros for individual AIPS_PACRL bitfields */ /*! * @name Register AIPS_PACRL, field TP7[0] (RW) * * Determines whether the peripheral allows accesses from an untrusted master. * When this field is set and an access is attempted by an untrusted master, the * access terminates with an error response and no peripheral access initiates. * * Values: * - 0 - Accesses from an untrusted master are allowed. * - 1 - Accesses from an untrusted master are not allowed. */ /*@{*/ #define BP_AIPS_PACRL_TP7 (0U) /*!< Bit position for AIPS_PACRL_TP7. */ #define BM_AIPS_PACRL_TP7 (0x00000001U) /*!< Bit mask for AIPS_PACRL_TP7. */ #define BS_AIPS_PACRL_TP7 (1U) /*!< Bit field size in bits for AIPS_PACRL_TP7. */ /*! @brief Read current value of the AIPS_PACRL_TP7 field. */ #define BR_AIPS_PACRL_TP7(x) (BITBAND_ACCESS32(HW_AIPS_PACRL_ADDR(x), BP_AIPS_PACRL_TP7)) /*! @brief Format value for bitfield AIPS_PACRL_TP7. */ #define BF_AIPS_PACRL_TP7(v) ((uint32_t)((uint32_t)(v) << BP_AIPS_PACRL_TP7) & BM_AIPS_PACRL_TP7) /*! @brief Set the TP7 field to a new value. */ #define BW_AIPS_PACRL_TP7(x, v) (BITBAND_ACCESS32(HW_AIPS_PACRL_ADDR(x), BP_AIPS_PACRL_TP7) = (v)) /*@}*/ /*! * @name Register AIPS_PACRL, field WP7[1] (RW) * * Determines whether the peripheral allows write accesses. When this field is * set and a write access is attempted, access terminates with an error response * and no peripheral access initiates. * * Values: * - 0 - This peripheral allows write accesses. * - 1 - This peripheral is write protected. */ /*@{*/ #define BP_AIPS_PACRL_WP7 (1U) /*!< Bit position for AIPS_PACRL_WP7. */ #define BM_AIPS_PACRL_WP7 (0x00000002U) /*!< Bit mask for AIPS_PACRL_WP7. */ #define BS_AIPS_PACRL_WP7 (1U) /*!< Bit field size in bits for AIPS_PACRL_WP7. */ /*! @brief Read current value of the AIPS_PACRL_WP7 field. */ #define BR_AIPS_PACRL_WP7(x) (BITBAND_ACCESS32(HW_AIPS_PACRL_ADDR(x), BP_AIPS_PACRL_WP7)) /*! @brief Format value for bitfield AIPS_PACRL_WP7. */ #define BF_AIPS_PACRL_WP7(v) ((uint32_t)((uint32_t)(v) << BP_AIPS_PACRL_WP7) & BM_AIPS_PACRL_WP7) /*! @brief Set the WP7 field to a new value. */ #define BW_AIPS_PACRL_WP7(x, v) (BITBAND_ACCESS32(HW_AIPS_PACRL_ADDR(x), BP_AIPS_PACRL_WP7) = (v)) /*@}*/ /*! * @name Register AIPS_PACRL, field SP7[2] (RW) * * Determines whether the peripheral requires supervisor privilege level for * accesses. When this field is set, the master privilege level must indicate the * supervisor access attribute, and the MPRx[MPLn] control field for the master * must be set. If not, access terminates with an error response and no peripheral * access initiates. * * Values: * - 0 - This peripheral does not require supervisor privilege level for * accesses. * - 1 - This peripheral requires supervisor privilege level for accesses. */ /*@{*/ #define BP_AIPS_PACRL_SP7 (2U) /*!< Bit position for AIPS_PACRL_SP7. */ #define BM_AIPS_PACRL_SP7 (0x00000004U) /*!< Bit mask for AIPS_PACRL_SP7. */ #define BS_AIPS_PACRL_SP7 (1U) /*!< Bit field size in bits for AIPS_PACRL_SP7. */ /*! @brief Read current value of the AIPS_PACRL_SP7 field. */ #define BR_AIPS_PACRL_SP7(x) (BITBAND_ACCESS32(HW_AIPS_PACRL_ADDR(x), BP_AIPS_PACRL_SP7)) /*! @brief Format value for bitfield AIPS_PACRL_SP7. */ #define BF_AIPS_PACRL_SP7(v) ((uint32_t)((uint32_t)(v) << BP_AIPS_PACRL_SP7) & BM_AIPS_PACRL_SP7) /*! @brief Set the SP7 field to a new value. */ #define BW_AIPS_PACRL_SP7(x, v) (BITBAND_ACCESS32(HW_AIPS_PACRL_ADDR(x), BP_AIPS_PACRL_SP7) = (v)) /*@}*/ /*! * @name Register AIPS_PACRL, field TP6[4] (RW) * * Determines whether the peripheral allows accesses from an untrusted master. * When this field is set and an access is attempted by an untrusted master, the * access terminates with an error response and no peripheral access initiates. * * Values: * - 0 - Accesses from an untrusted master are allowed. * - 1 - Accesses from an untrusted master are not allowed. */ /*@{*/ #define BP_AIPS_PACRL_TP6 (4U) /*!< Bit position for AIPS_PACRL_TP6. */ #define BM_AIPS_PACRL_TP6 (0x00000010U) /*!< Bit mask for AIPS_PACRL_TP6. */ #define BS_AIPS_PACRL_TP6 (1U) /*!< Bit field size in bits for AIPS_PACRL_TP6. */ /*! @brief Read current value of the AIPS_PACRL_TP6 field. */ #define BR_AIPS_PACRL_TP6(x) (BITBAND_ACCESS32(HW_AIPS_PACRL_ADDR(x), BP_AIPS_PACRL_TP6)) /*! @brief Format value for bitfield AIPS_PACRL_TP6. */ #define BF_AIPS_PACRL_TP6(v) ((uint32_t)((uint32_t)(v) << BP_AIPS_PACRL_TP6) & BM_AIPS_PACRL_TP6) /*! @brief Set the TP6 field to a new value. */ #define BW_AIPS_PACRL_TP6(x, v) (BITBAND_ACCESS32(HW_AIPS_PACRL_ADDR(x), BP_AIPS_PACRL_TP6) = (v)) /*@}*/ /*! * @name Register AIPS_PACRL, field WP6[5] (RW) * * Determines whether the peripheral allows write accesses. When this field is * set and a write access is attempted, access terminates with an error response * and no peripheral access initiates. * * Values: * - 0 - This peripheral allows write accesses. * - 1 - This peripheral is write protected. */ /*@{*/ #define BP_AIPS_PACRL_WP6 (5U) /*!< Bit position for AIPS_PACRL_WP6. */ #define BM_AIPS_PACRL_WP6 (0x00000020U) /*!< Bit mask for AIPS_PACRL_WP6. */ #define BS_AIPS_PACRL_WP6 (1U) /*!< Bit field size in bits for AIPS_PACRL_WP6. */ /*! @brief Read current value of the AIPS_PACRL_WP6 field. */ #define BR_AIPS_PACRL_WP6(x) (BITBAND_ACCESS32(HW_AIPS_PACRL_ADDR(x), BP_AIPS_PACRL_WP6)) /*! @brief Format value for bitfield AIPS_PACRL_WP6. */ #define BF_AIPS_PACRL_WP6(v) ((uint32_t)((uint32_t)(v) << BP_AIPS_PACRL_WP6) & BM_AIPS_PACRL_WP6) /*! @brief Set the WP6 field to a new value. */ #define BW_AIPS_PACRL_WP6(x, v) (BITBAND_ACCESS32(HW_AIPS_PACRL_ADDR(x), BP_AIPS_PACRL_WP6) = (v)) /*@}*/ /*! * @name Register AIPS_PACRL, field SP6[6] (RW) * * Determines whether the peripheral requires supervisor privilege level for * accesses. When this field is set, the master privilege level must indicate the * supervisor access attribute, and the MPRx[MPLn] control field for the master * must be set. If not, access terminates with an error response and no peripheral * access initiates. * * Values: * - 0 - This peripheral does not require supervisor privilege level for * accesses. * - 1 - This peripheral requires supervisor privilege level for accesses. */ /*@{*/ #define BP_AIPS_PACRL_SP6 (6U) /*!< Bit position for AIPS_PACRL_SP6. */ #define BM_AIPS_PACRL_SP6 (0x00000040U) /*!< Bit mask for AIPS_PACRL_SP6. */ #define BS_AIPS_PACRL_SP6 (1U) /*!< Bit field size in bits for AIPS_PACRL_SP6. */ /*! @brief Read current value of the AIPS_PACRL_SP6 field. */ #define BR_AIPS_PACRL_SP6(x) (BITBAND_ACCESS32(HW_AIPS_PACRL_ADDR(x), BP_AIPS_PACRL_SP6)) /*! @brief Format value for bitfield AIPS_PACRL_SP6. */ #define BF_AIPS_PACRL_SP6(v) ((uint32_t)((uint32_t)(v) << BP_AIPS_PACRL_SP6) & BM_AIPS_PACRL_SP6) /*! @brief Set the SP6 field to a new value. */ #define BW_AIPS_PACRL_SP6(x, v) (BITBAND_ACCESS32(HW_AIPS_PACRL_ADDR(x), BP_AIPS_PACRL_SP6) = (v)) /*@}*/ /*! * @name Register AIPS_PACRL, field TP5[8] (RW) * * Determines whether the peripheral allows accesses from an untrusted master. * When this field is set and an access is attempted by an untrusted master, the * access terminates with an error response and no peripheral access initiates. * * Values: * - 0 - Accesses from an untrusted master are allowed. * - 1 - Accesses from an untrusted master are not allowed. */ /*@{*/ #define BP_AIPS_PACRL_TP5 (8U) /*!< Bit position for AIPS_PACRL_TP5. */ #define BM_AIPS_PACRL_TP5 (0x00000100U) /*!< Bit mask for AIPS_PACRL_TP5. */ #define BS_AIPS_PACRL_TP5 (1U) /*!< Bit field size in bits for AIPS_PACRL_TP5. */ /*! @brief Read current value of the AIPS_PACRL_TP5 field. */ #define BR_AIPS_PACRL_TP5(x) (BITBAND_ACCESS32(HW_AIPS_PACRL_ADDR(x), BP_AIPS_PACRL_TP5)) /*! @brief Format value for bitfield AIPS_PACRL_TP5. */ #define BF_AIPS_PACRL_TP5(v) ((uint32_t)((uint32_t)(v) << BP_AIPS_PACRL_TP5) & BM_AIPS_PACRL_TP5) /*! @brief Set the TP5 field to a new value. */ #define BW_AIPS_PACRL_TP5(x, v) (BITBAND_ACCESS32(HW_AIPS_PACRL_ADDR(x), BP_AIPS_PACRL_TP5) = (v)) /*@}*/ /*! * @name Register AIPS_PACRL, field WP5[9] (RW) * * Determines whether the peripheral allows write accesses. When this field is * set and a write access is attempted, access terminates with an error response * and no peripheral access initiates. * * Values: * - 0 - This peripheral allows write accesses. * - 1 - This peripheral is write protected. */ /*@{*/ #define BP_AIPS_PACRL_WP5 (9U) /*!< Bit position for AIPS_PACRL_WP5. */ #define BM_AIPS_PACRL_WP5 (0x00000200U) /*!< Bit mask for AIPS_PACRL_WP5. */ #define BS_AIPS_PACRL_WP5 (1U) /*!< Bit field size in bits for AIPS_PACRL_WP5. */ /*! @brief Read current value of the AIPS_PACRL_WP5 field. */ #define BR_AIPS_PACRL_WP5(x) (BITBAND_ACCESS32(HW_AIPS_PACRL_ADDR(x), BP_AIPS_PACRL_WP5)) /*! @brief Format value for bitfield AIPS_PACRL_WP5. */ #define BF_AIPS_PACRL_WP5(v) ((uint32_t)((uint32_t)(v) << BP_AIPS_PACRL_WP5) & BM_AIPS_PACRL_WP5) /*! @brief Set the WP5 field to a new value. */ #define BW_AIPS_PACRL_WP5(x, v) (BITBAND_ACCESS32(HW_AIPS_PACRL_ADDR(x), BP_AIPS_PACRL_WP5) = (v)) /*@}*/ /*! * @name Register AIPS_PACRL, field SP5[10] (RW) * * Determines whether the peripheral requires supervisor privilege level for * accesses. When this field is set, the master privilege level must indicate the * supervisor access attribute, and the MPRx[MPLn] control field for the master * must be set. If not, access terminates with an error response and no peripheral * access initiates. * * Values: * - 0 - This peripheral does not require supervisor privilege level for * accesses. * - 1 - This peripheral requires supervisor privilege level for accesses. */ /*@{*/ #define BP_AIPS_PACRL_SP5 (10U) /*!< Bit position for AIPS_PACRL_SP5. */ #define BM_AIPS_PACRL_SP5 (0x00000400U) /*!< Bit mask for AIPS_PACRL_SP5. */ #define BS_AIPS_PACRL_SP5 (1U) /*!< Bit field size in bits for AIPS_PACRL_SP5. */ /*! @brief Read current value of the AIPS_PACRL_SP5 field. */ #define BR_AIPS_PACRL_SP5(x) (BITBAND_ACCESS32(HW_AIPS_PACRL_ADDR(x), BP_AIPS_PACRL_SP5)) /*! @brief Format value for bitfield AIPS_PACRL_SP5. */ #define BF_AIPS_PACRL_SP5(v) ((uint32_t)((uint32_t)(v) << BP_AIPS_PACRL_SP5) & BM_AIPS_PACRL_SP5) /*! @brief Set the SP5 field to a new value. */ #define BW_AIPS_PACRL_SP5(x, v) (BITBAND_ACCESS32(HW_AIPS_PACRL_ADDR(x), BP_AIPS_PACRL_SP5) = (v)) /*@}*/ /*! * @name Register AIPS_PACRL, field TP4[12] (RW) * * Determines whether the peripheral allows accesses from an untrusted master. * When this bit is set and an access is attempted by an untrusted master, the * access terminates with an error response and no peripheral access initiates. * * Values: * - 0 - Accesses from an untrusted master are allowed. * - 1 - Accesses from an untrusted master are not allowed. */ /*@{*/ #define BP_AIPS_PACRL_TP4 (12U) /*!< Bit position for AIPS_PACRL_TP4. */ #define BM_AIPS_PACRL_TP4 (0x00001000U) /*!< Bit mask for AIPS_PACRL_TP4. */ #define BS_AIPS_PACRL_TP4 (1U) /*!< Bit field size in bits for AIPS_PACRL_TP4. */ /*! @brief Read current value of the AIPS_PACRL_TP4 field. */ #define BR_AIPS_PACRL_TP4(x) (BITBAND_ACCESS32(HW_AIPS_PACRL_ADDR(x), BP_AIPS_PACRL_TP4)) /*! @brief Format value for bitfield AIPS_PACRL_TP4. */ #define BF_AIPS_PACRL_TP4(v) ((uint32_t)((uint32_t)(v) << BP_AIPS_PACRL_TP4) & BM_AIPS_PACRL_TP4) /*! @brief Set the TP4 field to a new value. */ #define BW_AIPS_PACRL_TP4(x, v) (BITBAND_ACCESS32(HW_AIPS_PACRL_ADDR(x), BP_AIPS_PACRL_TP4) = (v)) /*@}*/ /*! * @name Register AIPS_PACRL, field WP4[13] (RW) * * Determines whether the peripheral allows write accesses. When this field is * set and a write access is attempted, access terminates with an error response * and no peripheral access initiates. * * Values: * - 0 - This peripheral allows write accesses. * - 1 - This peripheral is write protected. */ /*@{*/ #define BP_AIPS_PACRL_WP4 (13U) /*!< Bit position for AIPS_PACRL_WP4. */ #define BM_AIPS_PACRL_WP4 (0x00002000U) /*!< Bit mask for AIPS_PACRL_WP4. */ #define BS_AIPS_PACRL_WP4 (1U) /*!< Bit field size in bits for AIPS_PACRL_WP4. */ /*! @brief Read current value of the AIPS_PACRL_WP4 field. */ #define BR_AIPS_PACRL_WP4(x) (BITBAND_ACCESS32(HW_AIPS_PACRL_ADDR(x), BP_AIPS_PACRL_WP4)) /*! @brief Format value for bitfield AIPS_PACRL_WP4. */ #define BF_AIPS_PACRL_WP4(v) ((uint32_t)((uint32_t)(v) << BP_AIPS_PACRL_WP4) & BM_AIPS_PACRL_WP4) /*! @brief Set the WP4 field to a new value. */ #define BW_AIPS_PACRL_WP4(x, v) (BITBAND_ACCESS32(HW_AIPS_PACRL_ADDR(x), BP_AIPS_PACRL_WP4) = (v)) /*@}*/ /*! * @name Register AIPS_PACRL, field SP4[14] (RW) * * Determines whether the peripheral requires supervisor privilege level for * access. When this bit is set, the master privilege level must indicate the * supervisor access attribute, and the MPRx[MPLn] control bit for the master must be * set. If not, access terminates with an error response and no peripheral access * initiates. * * Values: * - 0 - This peripheral does not require supervisor privilege level for * accesses. * - 1 - This peripheral requires supervisor privilege level for accesses. */ /*@{*/ #define BP_AIPS_PACRL_SP4 (14U) /*!< Bit position for AIPS_PACRL_SP4. */ #define BM_AIPS_PACRL_SP4 (0x00004000U) /*!< Bit mask for AIPS_PACRL_SP4. */ #define BS_AIPS_PACRL_SP4 (1U) /*!< Bit field size in bits for AIPS_PACRL_SP4. */ /*! @brief Read current value of the AIPS_PACRL_SP4 field. */ #define BR_AIPS_PACRL_SP4(x) (BITBAND_ACCESS32(HW_AIPS_PACRL_ADDR(x), BP_AIPS_PACRL_SP4)) /*! @brief Format value for bitfield AIPS_PACRL_SP4. */ #define BF_AIPS_PACRL_SP4(v) ((uint32_t)((uint32_t)(v) << BP_AIPS_PACRL_SP4) & BM_AIPS_PACRL_SP4) /*! @brief Set the SP4 field to a new value. */ #define BW_AIPS_PACRL_SP4(x, v) (BITBAND_ACCESS32(HW_AIPS_PACRL_ADDR(x), BP_AIPS_PACRL_SP4) = (v)) /*@}*/ /*! * @name Register AIPS_PACRL, field TP3[16] (RW) * * Determines whether the peripheral allows accesses from an untrusted master. * When this field is set and an access is attempted by an untrusted master, the * access terminates with an error response and no peripheral access initiates. * * Values: * - 0 - Accesses from an untrusted master are allowed. * - 1 - Accesses from an untrusted master are not allowed. */ /*@{*/ #define BP_AIPS_PACRL_TP3 (16U) /*!< Bit position for AIPS_PACRL_TP3. */ #define BM_AIPS_PACRL_TP3 (0x00010000U) /*!< Bit mask for AIPS_PACRL_TP3. */ #define BS_AIPS_PACRL_TP3 (1U) /*!< Bit field size in bits for AIPS_PACRL_TP3. */ /*! @brief Read current value of the AIPS_PACRL_TP3 field. */ #define BR_AIPS_PACRL_TP3(x) (BITBAND_ACCESS32(HW_AIPS_PACRL_ADDR(x), BP_AIPS_PACRL_TP3)) /*! @brief Format value for bitfield AIPS_PACRL_TP3. */ #define BF_AIPS_PACRL_TP3(v) ((uint32_t)((uint32_t)(v) << BP_AIPS_PACRL_TP3) & BM_AIPS_PACRL_TP3) /*! @brief Set the TP3 field to a new value. */ #define BW_AIPS_PACRL_TP3(x, v) (BITBAND_ACCESS32(HW_AIPS_PACRL_ADDR(x), BP_AIPS_PACRL_TP3) = (v)) /*@}*/ /*! * @name Register AIPS_PACRL, field WP3[17] (RW) * * Determines whether the peripheral allows write accesss. When this bit is set * and a write access is attempted, access terminates with an error response and * no peripheral access initiates. * * Values: * - 0 - This peripheral allows write accesses. * - 1 - This peripheral is write protected. */ /*@{*/ #define BP_AIPS_PACRL_WP3 (17U) /*!< Bit position for AIPS_PACRL_WP3. */ #define BM_AIPS_PACRL_WP3 (0x00020000U) /*!< Bit mask for AIPS_PACRL_WP3. */ #define BS_AIPS_PACRL_WP3 (1U) /*!< Bit field size in bits for AIPS_PACRL_WP3. */ /*! @brief Read current value of the AIPS_PACRL_WP3 field. */ #define BR_AIPS_PACRL_WP3(x) (BITBAND_ACCESS32(HW_AIPS_PACRL_ADDR(x), BP_AIPS_PACRL_WP3)) /*! @brief Format value for bitfield AIPS_PACRL_WP3. */ #define BF_AIPS_PACRL_WP3(v) ((uint32_t)((uint32_t)(v) << BP_AIPS_PACRL_WP3) & BM_AIPS_PACRL_WP3) /*! @brief Set the WP3 field to a new value. */ #define BW_AIPS_PACRL_WP3(x, v) (BITBAND_ACCESS32(HW_AIPS_PACRL_ADDR(x), BP_AIPS_PACRL_WP3) = (v)) /*@}*/ /*! * @name Register AIPS_PACRL, field SP3[18] (RW) * * Determines whether the peripheral requires supervisor privilege level for * accesses. When this field is set, the master privilege level must indicate the * supervisor access attribute, and the MPRx[MPLn] control field for the master * must be set. If not, access terminates with an error response and no peripheral * access initiates. * * Values: * - 0 - This peripheral does not require supervisor privilege level for * accesses. * - 1 - This peripheral requires supervisor privilege level for accesses. */ /*@{*/ #define BP_AIPS_PACRL_SP3 (18U) /*!< Bit position for AIPS_PACRL_SP3. */ #define BM_AIPS_PACRL_SP3 (0x00040000U) /*!< Bit mask for AIPS_PACRL_SP3. */ #define BS_AIPS_PACRL_SP3 (1U) /*!< Bit field size in bits for AIPS_PACRL_SP3. */ /*! @brief Read current value of the AIPS_PACRL_SP3 field. */ #define BR_AIPS_PACRL_SP3(x) (BITBAND_ACCESS32(HW_AIPS_PACRL_ADDR(x), BP_AIPS_PACRL_SP3)) /*! @brief Format value for bitfield AIPS_PACRL_SP3. */ #define BF_AIPS_PACRL_SP3(v) ((uint32_t)((uint32_t)(v) << BP_AIPS_PACRL_SP3) & BM_AIPS_PACRL_SP3) /*! @brief Set the SP3 field to a new value. */ #define BW_AIPS_PACRL_SP3(x, v) (BITBAND_ACCESS32(HW_AIPS_PACRL_ADDR(x), BP_AIPS_PACRL_SP3) = (v)) /*@}*/ /*! * @name Register AIPS_PACRL, field TP2[20] (RW) * * Determines whether the peripheral allows accesses from an untrusted master. * When this bit is set and an access is attempted by an untrusted master, the * access terminates with an error response and no peripheral access initiates. * * Values: * - 0 - Accesses from an untrusted master are allowed. * - 1 - Accesses from an untrusted master are not allowed. */ /*@{*/ #define BP_AIPS_PACRL_TP2 (20U) /*!< Bit position for AIPS_PACRL_TP2. */ #define BM_AIPS_PACRL_TP2 (0x00100000U) /*!< Bit mask for AIPS_PACRL_TP2. */ #define BS_AIPS_PACRL_TP2 (1U) /*!< Bit field size in bits for AIPS_PACRL_TP2. */ /*! @brief Read current value of the AIPS_PACRL_TP2 field. */ #define BR_AIPS_PACRL_TP2(x) (BITBAND_ACCESS32(HW_AIPS_PACRL_ADDR(x), BP_AIPS_PACRL_TP2)) /*! @brief Format value for bitfield AIPS_PACRL_TP2. */ #define BF_AIPS_PACRL_TP2(v) ((uint32_t)((uint32_t)(v) << BP_AIPS_PACRL_TP2) & BM_AIPS_PACRL_TP2) /*! @brief Set the TP2 field to a new value. */ #define BW_AIPS_PACRL_TP2(x, v) (BITBAND_ACCESS32(HW_AIPS_PACRL_ADDR(x), BP_AIPS_PACRL_TP2) = (v)) /*@}*/ /*! * @name Register AIPS_PACRL, field WP2[21] (RW) * * Determines whether the peripheral allows write accesses. When this field is * set and a write access is attempted, access terminates with an error response * and no peripheral access initiates. * * Values: * - 0 - This peripheral allows write accesses. * - 1 - This peripheral is write protected. */ /*@{*/ #define BP_AIPS_PACRL_WP2 (21U) /*!< Bit position for AIPS_PACRL_WP2. */ #define BM_AIPS_PACRL_WP2 (0x00200000U) /*!< Bit mask for AIPS_PACRL_WP2. */ #define BS_AIPS_PACRL_WP2 (1U) /*!< Bit field size in bits for AIPS_PACRL_WP2. */ /*! @brief Read current value of the AIPS_PACRL_WP2 field. */ #define BR_AIPS_PACRL_WP2(x) (BITBAND_ACCESS32(HW_AIPS_PACRL_ADDR(x), BP_AIPS_PACRL_WP2)) /*! @brief Format value for bitfield AIPS_PACRL_WP2. */ #define BF_AIPS_PACRL_WP2(v) ((uint32_t)((uint32_t)(v) << BP_AIPS_PACRL_WP2) & BM_AIPS_PACRL_WP2) /*! @brief Set the WP2 field to a new value. */ #define BW_AIPS_PACRL_WP2(x, v) (BITBAND_ACCESS32(HW_AIPS_PACRL_ADDR(x), BP_AIPS_PACRL_WP2) = (v)) /*@}*/ /*! * @name Register AIPS_PACRL, field SP2[22] (RW) * * Determines whether the peripheral requires supervisor privilege level for * access. When this bit is set, the master privilege level must indicate the * supervisor access attribute, and the MPRx[MPLn] control bit for the master must be * set. If not, access terminates with an error response and no peripheral access * initiates. * * Values: * - 0 - This peripheral does not require supervisor privilege level for * accesses. * - 1 - This peripheral requires supervisor privilege level for accesses. */ /*@{*/ #define BP_AIPS_PACRL_SP2 (22U) /*!< Bit position for AIPS_PACRL_SP2. */ #define BM_AIPS_PACRL_SP2 (0x00400000U) /*!< Bit mask for AIPS_PACRL_SP2. */ #define BS_AIPS_PACRL_SP2 (1U) /*!< Bit field size in bits for AIPS_PACRL_SP2. */ /*! @brief Read current value of the AIPS_PACRL_SP2 field. */ #define BR_AIPS_PACRL_SP2(x) (BITBAND_ACCESS32(HW_AIPS_PACRL_ADDR(x), BP_AIPS_PACRL_SP2)) /*! @brief Format value for bitfield AIPS_PACRL_SP2. */ #define BF_AIPS_PACRL_SP2(v) ((uint32_t)((uint32_t)(v) << BP_AIPS_PACRL_SP2) & BM_AIPS_PACRL_SP2) /*! @brief Set the SP2 field to a new value. */ #define BW_AIPS_PACRL_SP2(x, v) (BITBAND_ACCESS32(HW_AIPS_PACRL_ADDR(x), BP_AIPS_PACRL_SP2) = (v)) /*@}*/ /*! * @name Register AIPS_PACRL, field TP1[24] (RW) * * Determines whether the peripheral allows accesses from an untrusted master. * When this field is set and an access is attempted by an untrusted master, the * access terminates with an error response and no peripheral access initiates. * * Values: * - 0 - Accesses from an untrusted master are allowed. * - 1 - Accesses from an untrusted master are not allowed. */ /*@{*/ #define BP_AIPS_PACRL_TP1 (24U) /*!< Bit position for AIPS_PACRL_TP1. */ #define BM_AIPS_PACRL_TP1 (0x01000000U) /*!< Bit mask for AIPS_PACRL_TP1. */ #define BS_AIPS_PACRL_TP1 (1U) /*!< Bit field size in bits for AIPS_PACRL_TP1. */ /*! @brief Read current value of the AIPS_PACRL_TP1 field. */ #define BR_AIPS_PACRL_TP1(x) (BITBAND_ACCESS32(HW_AIPS_PACRL_ADDR(x), BP_AIPS_PACRL_TP1)) /*! @brief Format value for bitfield AIPS_PACRL_TP1. */ #define BF_AIPS_PACRL_TP1(v) ((uint32_t)((uint32_t)(v) << BP_AIPS_PACRL_TP1) & BM_AIPS_PACRL_TP1) /*! @brief Set the TP1 field to a new value. */ #define BW_AIPS_PACRL_TP1(x, v) (BITBAND_ACCESS32(HW_AIPS_PACRL_ADDR(x), BP_AIPS_PACRL_TP1) = (v)) /*@}*/ /*! * @name Register AIPS_PACRL, field WP1[25] (RW) * * Determines whether the peripheral allows write accesses. When this field is * set and a write access is attempted, access terminates with an error response * and no peripheral access initiates. * * Values: * - 0 - This peripheral allows write accesses. * - 1 - This peripheral is write protected. */ /*@{*/ #define BP_AIPS_PACRL_WP1 (25U) /*!< Bit position for AIPS_PACRL_WP1. */ #define BM_AIPS_PACRL_WP1 (0x02000000U) /*!< Bit mask for AIPS_PACRL_WP1. */ #define BS_AIPS_PACRL_WP1 (1U) /*!< Bit field size in bits for AIPS_PACRL_WP1. */ /*! @brief Read current value of the AIPS_PACRL_WP1 field. */ #define BR_AIPS_PACRL_WP1(x) (BITBAND_ACCESS32(HW_AIPS_PACRL_ADDR(x), BP_AIPS_PACRL_WP1)) /*! @brief Format value for bitfield AIPS_PACRL_WP1. */ #define BF_AIPS_PACRL_WP1(v) ((uint32_t)((uint32_t)(v) << BP_AIPS_PACRL_WP1) & BM_AIPS_PACRL_WP1) /*! @brief Set the WP1 field to a new value. */ #define BW_AIPS_PACRL_WP1(x, v) (BITBAND_ACCESS32(HW_AIPS_PACRL_ADDR(x), BP_AIPS_PACRL_WP1) = (v)) /*@}*/ /*! * @name Register AIPS_PACRL, field SP1[26] (RW) * * Determines whether the peripheral requires supervisor privilege level for * access. When this field is set, the master privilege level must indicate the * supervisor access attribute, and the MPRx[MPLn] control field for the master must * be set. If not, access terminates with an error response and no peripheral * access initiates. * * Values: * - 0 - This peripheral does not require supervisor privilege level for * accesses. * - 1 - This peripheral requires supervisor privilege level for accesses. */ /*@{*/ #define BP_AIPS_PACRL_SP1 (26U) /*!< Bit position for AIPS_PACRL_SP1. */ #define BM_AIPS_PACRL_SP1 (0x04000000U) /*!< Bit mask for AIPS_PACRL_SP1. */ #define BS_AIPS_PACRL_SP1 (1U) /*!< Bit field size in bits for AIPS_PACRL_SP1. */ /*! @brief Read current value of the AIPS_PACRL_SP1 field. */ #define BR_AIPS_PACRL_SP1(x) (BITBAND_ACCESS32(HW_AIPS_PACRL_ADDR(x), BP_AIPS_PACRL_SP1)) /*! @brief Format value for bitfield AIPS_PACRL_SP1. */ #define BF_AIPS_PACRL_SP1(v) ((uint32_t)((uint32_t)(v) << BP_AIPS_PACRL_SP1) & BM_AIPS_PACRL_SP1) /*! @brief Set the SP1 field to a new value. */ #define BW_AIPS_PACRL_SP1(x, v) (BITBAND_ACCESS32(HW_AIPS_PACRL_ADDR(x), BP_AIPS_PACRL_SP1) = (v)) /*@}*/ /*! * @name Register AIPS_PACRL, field TP0[28] (RW) * * Determines whether the peripheral allows accesses from an untrusted master. * When this bit is set and an access is attempted by an untrusted master, the * access terminates with an error response and no peripheral access initiates. * * Values: * - 0 - Accesses from an untrusted master are allowed. * - 1 - Accesses from an untrusted master are not allowed. */ /*@{*/ #define BP_AIPS_PACRL_TP0 (28U) /*!< Bit position for AIPS_PACRL_TP0. */ #define BM_AIPS_PACRL_TP0 (0x10000000U) /*!< Bit mask for AIPS_PACRL_TP0. */ #define BS_AIPS_PACRL_TP0 (1U) /*!< Bit field size in bits for AIPS_PACRL_TP0. */ /*! @brief Read current value of the AIPS_PACRL_TP0 field. */ #define BR_AIPS_PACRL_TP0(x) (BITBAND_ACCESS32(HW_AIPS_PACRL_ADDR(x), BP_AIPS_PACRL_TP0)) /*! @brief Format value for bitfield AIPS_PACRL_TP0. */ #define BF_AIPS_PACRL_TP0(v) ((uint32_t)((uint32_t)(v) << BP_AIPS_PACRL_TP0) & BM_AIPS_PACRL_TP0) /*! @brief Set the TP0 field to a new value. */ #define BW_AIPS_PACRL_TP0(x, v) (BITBAND_ACCESS32(HW_AIPS_PACRL_ADDR(x), BP_AIPS_PACRL_TP0) = (v)) /*@}*/ /*! * @name Register AIPS_PACRL, field WP0[29] (RW) * * Determines whether the peripheral allows write accesses. When this field is * set and a write access is attempted, access terminates with an error response * and no peripheral access initiates. * * Values: * - 0 - This peripheral allows write accesses. * - 1 - This peripheral is write protected. */ /*@{*/ #define BP_AIPS_PACRL_WP0 (29U) /*!< Bit position for AIPS_PACRL_WP0. */ #define BM_AIPS_PACRL_WP0 (0x20000000U) /*!< Bit mask for AIPS_PACRL_WP0. */ #define BS_AIPS_PACRL_WP0 (1U) /*!< Bit field size in bits for AIPS_PACRL_WP0. */ /*! @brief Read current value of the AIPS_PACRL_WP0 field. */ #define BR_AIPS_PACRL_WP0(x) (BITBAND_ACCESS32(HW_AIPS_PACRL_ADDR(x), BP_AIPS_PACRL_WP0)) /*! @brief Format value for bitfield AIPS_PACRL_WP0. */ #define BF_AIPS_PACRL_WP0(v) ((uint32_t)((uint32_t)(v) << BP_AIPS_PACRL_WP0) & BM_AIPS_PACRL_WP0) /*! @brief Set the WP0 field to a new value. */ #define BW_AIPS_PACRL_WP0(x, v) (BITBAND_ACCESS32(HW_AIPS_PACRL_ADDR(x), BP_AIPS_PACRL_WP0) = (v)) /*@}*/ /*! * @name Register AIPS_PACRL, field SP0[30] (RW) * * Determines whether the peripheral requires supervisor privilege level for * accesses. When this field is set, the master privilege level must indicate the * supervisor access attribute, and the MPRx[MPLn] control field for the master * must be set. If not, access terminates with an error response and no peripheral * access initiates. * * Values: * - 0 - This peripheral does not require supervisor privilege level for * accesses. * - 1 - This peripheral requires supervisor privilege level for accesses. */ /*@{*/ #define BP_AIPS_PACRL_SP0 (30U) /*!< Bit position for AIPS_PACRL_SP0. */ #define BM_AIPS_PACRL_SP0 (0x40000000U) /*!< Bit mask for AIPS_PACRL_SP0. */ #define BS_AIPS_PACRL_SP0 (1U) /*!< Bit field size in bits for AIPS_PACRL_SP0. */ /*! @brief Read current value of the AIPS_PACRL_SP0 field. */ #define BR_AIPS_PACRL_SP0(x) (BITBAND_ACCESS32(HW_AIPS_PACRL_ADDR(x), BP_AIPS_PACRL_SP0)) /*! @brief Format value for bitfield AIPS_PACRL_SP0. */ #define BF_AIPS_PACRL_SP0(v) ((uint32_t)((uint32_t)(v) << BP_AIPS_PACRL_SP0) & BM_AIPS_PACRL_SP0) /*! @brief Set the SP0 field to a new value. */ #define BW_AIPS_PACRL_SP0(x, v) (BITBAND_ACCESS32(HW_AIPS_PACRL_ADDR(x), BP_AIPS_PACRL_SP0) = (v)) /*@}*/ /******************************************************************************* * HW_AIPS_PACRM - Peripheral Access Control Register ******************************************************************************/ /*! * @brief HW_AIPS_PACRM - Peripheral Access Control Register (RW) * * Reset value: 0x44444444U * * This section describes PACR registers E-P, which control peripheral slots * 32-127. See PACRPeripheral Access Control Register for the description of these * registers. */ typedef union _hw_aips_pacrm { uint32_t U; struct _hw_aips_pacrm_bitfields { uint32_t TP7 : 1; /*!< [0] Trusted Protect */ uint32_t WP7 : 1; /*!< [1] Write Protect */ uint32_t SP7 : 1; /*!< [2] Supervisor Protect */ uint32_t RESERVED0 : 1; /*!< [3] */ uint32_t TP6 : 1; /*!< [4] Trusted Protect */ uint32_t WP6 : 1; /*!< [5] Write Protect */ uint32_t SP6 : 1; /*!< [6] Supervisor Protect */ uint32_t RESERVED1 : 1; /*!< [7] */ uint32_t TP5 : 1; /*!< [8] Trusted Protect */ uint32_t WP5 : 1; /*!< [9] Write Protect */ uint32_t SP5 : 1; /*!< [10] Supervisor Protect */ uint32_t RESERVED2 : 1; /*!< [11] */ uint32_t TP4 : 1; /*!< [12] Trusted Protect */ uint32_t WP4 : 1; /*!< [13] Write Protect */ uint32_t SP4 : 1; /*!< [14] Supervisor Protect */ uint32_t RESERVED3 : 1; /*!< [15] */ uint32_t TP3 : 1; /*!< [16] Trusted Protect */ uint32_t WP3 : 1; /*!< [17] Write Protect */ uint32_t SP3 : 1; /*!< [18] Supervisor Protect */ uint32_t RESERVED4 : 1; /*!< [19] */ uint32_t TP2 : 1; /*!< [20] Trusted Protect */ uint32_t WP2 : 1; /*!< [21] Write Protect */ uint32_t SP2 : 1; /*!< [22] Supervisor Protect */ uint32_t RESERVED5 : 1; /*!< [23] */ uint32_t TP1 : 1; /*!< [24] Trusted Protect */ uint32_t WP1 : 1; /*!< [25] Write Protect */ uint32_t SP1 : 1; /*!< [26] Supervisor Protect */ uint32_t RESERVED6 : 1; /*!< [27] */ uint32_t TP0 : 1; /*!< [28] Trusted Protect */ uint32_t WP0 : 1; /*!< [29] Write Protect */ uint32_t SP0 : 1; /*!< [30] Supervisor Protect */ uint32_t RESERVED7 : 1; /*!< [31] */ } B; } hw_aips_pacrm_t; /*! * @name Constants and macros for entire AIPS_PACRM register */ /*@{*/ #define HW_AIPS_PACRM_ADDR(x) ((x) + 0x60U) #define HW_AIPS_PACRM(x) (*(__IO hw_aips_pacrm_t *) HW_AIPS_PACRM_ADDR(x)) #define HW_AIPS_PACRM_RD(x) (HW_AIPS_PACRM(x).U) #define HW_AIPS_PACRM_WR(x, v) (HW_AIPS_PACRM(x).U = (v)) #define HW_AIPS_PACRM_SET(x, v) (HW_AIPS_PACRM_WR(x, HW_AIPS_PACRM_RD(x) | (v))) #define HW_AIPS_PACRM_CLR(x, v) (HW_AIPS_PACRM_WR(x, HW_AIPS_PACRM_RD(x) & ~(v))) #define HW_AIPS_PACRM_TOG(x, v) (HW_AIPS_PACRM_WR(x, HW_AIPS_PACRM_RD(x) ^ (v))) /*@}*/ /* * Constants & macros for individual AIPS_PACRM bitfields */ /*! * @name Register AIPS_PACRM, field TP7[0] (RW) * * Determines whether the peripheral allows accesses from an untrusted master. * When this field is set and an access is attempted by an untrusted master, the * access terminates with an error response and no peripheral access initiates. * * Values: * - 0 - Accesses from an untrusted master are allowed. * - 1 - Accesses from an untrusted master are not allowed. */ /*@{*/ #define BP_AIPS_PACRM_TP7 (0U) /*!< Bit position for AIPS_PACRM_TP7. */ #define BM_AIPS_PACRM_TP7 (0x00000001U) /*!< Bit mask for AIPS_PACRM_TP7. */ #define BS_AIPS_PACRM_TP7 (1U) /*!< Bit field size in bits for AIPS_PACRM_TP7. */ /*! @brief Read current value of the AIPS_PACRM_TP7 field. */ #define BR_AIPS_PACRM_TP7(x) (BITBAND_ACCESS32(HW_AIPS_PACRM_ADDR(x), BP_AIPS_PACRM_TP7)) /*! @brief Format value for bitfield AIPS_PACRM_TP7. */ #define BF_AIPS_PACRM_TP7(v) ((uint32_t)((uint32_t)(v) << BP_AIPS_PACRM_TP7) & BM_AIPS_PACRM_TP7) /*! @brief Set the TP7 field to a new value. */ #define BW_AIPS_PACRM_TP7(x, v) (BITBAND_ACCESS32(HW_AIPS_PACRM_ADDR(x), BP_AIPS_PACRM_TP7) = (v)) /*@}*/ /*! * @name Register AIPS_PACRM, field WP7[1] (RW) * * Determines whether the peripheral allows write accesses. When this field is * set and a write access is attempted, access terminates with an error response * and no peripheral access initiates. * * Values: * - 0 - This peripheral allows write accesses. * - 1 - This peripheral is write protected. */ /*@{*/ #define BP_AIPS_PACRM_WP7 (1U) /*!< Bit position for AIPS_PACRM_WP7. */ #define BM_AIPS_PACRM_WP7 (0x00000002U) /*!< Bit mask for AIPS_PACRM_WP7. */ #define BS_AIPS_PACRM_WP7 (1U) /*!< Bit field size in bits for AIPS_PACRM_WP7. */ /*! @brief Read current value of the AIPS_PACRM_WP7 field. */ #define BR_AIPS_PACRM_WP7(x) (BITBAND_ACCESS32(HW_AIPS_PACRM_ADDR(x), BP_AIPS_PACRM_WP7)) /*! @brief Format value for bitfield AIPS_PACRM_WP7. */ #define BF_AIPS_PACRM_WP7(v) ((uint32_t)((uint32_t)(v) << BP_AIPS_PACRM_WP7) & BM_AIPS_PACRM_WP7) /*! @brief Set the WP7 field to a new value. */ #define BW_AIPS_PACRM_WP7(x, v) (BITBAND_ACCESS32(HW_AIPS_PACRM_ADDR(x), BP_AIPS_PACRM_WP7) = (v)) /*@}*/ /*! * @name Register AIPS_PACRM, field SP7[2] (RW) * * Determines whether the peripheral requires supervisor privilege level for * accesses. When this field is set, the master privilege level must indicate the * supervisor access attribute, and the MPRx[MPLn] control field for the master * must be set. If not, access terminates with an error response and no peripheral * access initiates. * * Values: * - 0 - This peripheral does not require supervisor privilege level for * accesses. * - 1 - This peripheral requires supervisor privilege level for accesses. */ /*@{*/ #define BP_AIPS_PACRM_SP7 (2U) /*!< Bit position for AIPS_PACRM_SP7. */ #define BM_AIPS_PACRM_SP7 (0x00000004U) /*!< Bit mask for AIPS_PACRM_SP7. */ #define BS_AIPS_PACRM_SP7 (1U) /*!< Bit field size in bits for AIPS_PACRM_SP7. */ /*! @brief Read current value of the AIPS_PACRM_SP7 field. */ #define BR_AIPS_PACRM_SP7(x) (BITBAND_ACCESS32(HW_AIPS_PACRM_ADDR(x), BP_AIPS_PACRM_SP7)) /*! @brief Format value for bitfield AIPS_PACRM_SP7. */ #define BF_AIPS_PACRM_SP7(v) ((uint32_t)((uint32_t)(v) << BP_AIPS_PACRM_SP7) & BM_AIPS_PACRM_SP7) /*! @brief Set the SP7 field to a new value. */ #define BW_AIPS_PACRM_SP7(x, v) (BITBAND_ACCESS32(HW_AIPS_PACRM_ADDR(x), BP_AIPS_PACRM_SP7) = (v)) /*@}*/ /*! * @name Register AIPS_PACRM, field TP6[4] (RW) * * Determines whether the peripheral allows accesses from an untrusted master. * When this field is set and an access is attempted by an untrusted master, the * access terminates with an error response and no peripheral access initiates. * * Values: * - 0 - Accesses from an untrusted master are allowed. * - 1 - Accesses from an untrusted master are not allowed. */ /*@{*/ #define BP_AIPS_PACRM_TP6 (4U) /*!< Bit position for AIPS_PACRM_TP6. */ #define BM_AIPS_PACRM_TP6 (0x00000010U) /*!< Bit mask for AIPS_PACRM_TP6. */ #define BS_AIPS_PACRM_TP6 (1U) /*!< Bit field size in bits for AIPS_PACRM_TP6. */ /*! @brief Read current value of the AIPS_PACRM_TP6 field. */ #define BR_AIPS_PACRM_TP6(x) (BITBAND_ACCESS32(HW_AIPS_PACRM_ADDR(x), BP_AIPS_PACRM_TP6)) /*! @brief Format value for bitfield AIPS_PACRM_TP6. */ #define BF_AIPS_PACRM_TP6(v) ((uint32_t)((uint32_t)(v) << BP_AIPS_PACRM_TP6) & BM_AIPS_PACRM_TP6) /*! @brief Set the TP6 field to a new value. */ #define BW_AIPS_PACRM_TP6(x, v) (BITBAND_ACCESS32(HW_AIPS_PACRM_ADDR(x), BP_AIPS_PACRM_TP6) = (v)) /*@}*/ /*! * @name Register AIPS_PACRM, field WP6[5] (RW) * * Determines whether the peripheral allows write accesses. When this field is * set and a write access is attempted, access terminates with an error response * and no peripheral access initiates. * * Values: * - 0 - This peripheral allows write accesses. * - 1 - This peripheral is write protected. */ /*@{*/ #define BP_AIPS_PACRM_WP6 (5U) /*!< Bit position for AIPS_PACRM_WP6. */ #define BM_AIPS_PACRM_WP6 (0x00000020U) /*!< Bit mask for AIPS_PACRM_WP6. */ #define BS_AIPS_PACRM_WP6 (1U) /*!< Bit field size in bits for AIPS_PACRM_WP6. */ /*! @brief Read current value of the AIPS_PACRM_WP6 field. */ #define BR_AIPS_PACRM_WP6(x) (BITBAND_ACCESS32(HW_AIPS_PACRM_ADDR(x), BP_AIPS_PACRM_WP6)) /*! @brief Format value for bitfield AIPS_PACRM_WP6. */ #define BF_AIPS_PACRM_WP6(v) ((uint32_t)((uint32_t)(v) << BP_AIPS_PACRM_WP6) & BM_AIPS_PACRM_WP6) /*! @brief Set the WP6 field to a new value. */ #define BW_AIPS_PACRM_WP6(x, v) (BITBAND_ACCESS32(HW_AIPS_PACRM_ADDR(x), BP_AIPS_PACRM_WP6) = (v)) /*@}*/ /*! * @name Register AIPS_PACRM, field SP6[6] (RW) * * Determines whether the peripheral requires supervisor privilege level for * accesses. When this field is set, the master privilege level must indicate the * supervisor access attribute, and the MPRx[MPLn] control field for the master * must be set. If not, access terminates with an error response and no peripheral * access initiates. * * Values: * - 0 - This peripheral does not require supervisor privilege level for * accesses. * - 1 - This peripheral requires supervisor privilege level for accesses. */ /*@{*/ #define BP_AIPS_PACRM_SP6 (6U) /*!< Bit position for AIPS_PACRM_SP6. */ #define BM_AIPS_PACRM_SP6 (0x00000040U) /*!< Bit mask for AIPS_PACRM_SP6. */ #define BS_AIPS_PACRM_SP6 (1U) /*!< Bit field size in bits for AIPS_PACRM_SP6. */ /*! @brief Read current value of the AIPS_PACRM_SP6 field. */ #define BR_AIPS_PACRM_SP6(x) (BITBAND_ACCESS32(HW_AIPS_PACRM_ADDR(x), BP_AIPS_PACRM_SP6)) /*! @brief Format value for bitfield AIPS_PACRM_SP6. */ #define BF_AIPS_PACRM_SP6(v) ((uint32_t)((uint32_t)(v) << BP_AIPS_PACRM_SP6) & BM_AIPS_PACRM_SP6) /*! @brief Set the SP6 field to a new value. */ #define BW_AIPS_PACRM_SP6(x, v) (BITBAND_ACCESS32(HW_AIPS_PACRM_ADDR(x), BP_AIPS_PACRM_SP6) = (v)) /*@}*/ /*! * @name Register AIPS_PACRM, field TP5[8] (RW) * * Determines whether the peripheral allows accesses from an untrusted master. * When this field is set and an access is attempted by an untrusted master, the * access terminates with an error response and no peripheral access initiates. * * Values: * - 0 - Accesses from an untrusted master are allowed. * - 1 - Accesses from an untrusted master are not allowed. */ /*@{*/ #define BP_AIPS_PACRM_TP5 (8U) /*!< Bit position for AIPS_PACRM_TP5. */ #define BM_AIPS_PACRM_TP5 (0x00000100U) /*!< Bit mask for AIPS_PACRM_TP5. */ #define BS_AIPS_PACRM_TP5 (1U) /*!< Bit field size in bits for AIPS_PACRM_TP5. */ /*! @brief Read current value of the AIPS_PACRM_TP5 field. */ #define BR_AIPS_PACRM_TP5(x) (BITBAND_ACCESS32(HW_AIPS_PACRM_ADDR(x), BP_AIPS_PACRM_TP5)) /*! @brief Format value for bitfield AIPS_PACRM_TP5. */ #define BF_AIPS_PACRM_TP5(v) ((uint32_t)((uint32_t)(v) << BP_AIPS_PACRM_TP5) & BM_AIPS_PACRM_TP5) /*! @brief Set the TP5 field to a new value. */ #define BW_AIPS_PACRM_TP5(x, v) (BITBAND_ACCESS32(HW_AIPS_PACRM_ADDR(x), BP_AIPS_PACRM_TP5) = (v)) /*@}*/ /*! * @name Register AIPS_PACRM, field WP5[9] (RW) * * Determines whether the peripheral allows write accesses. When this field is * set and a write access is attempted, access terminates with an error response * and no peripheral access initiates. * * Values: * - 0 - This peripheral allows write accesses. * - 1 - This peripheral is write protected. */ /*@{*/ #define BP_AIPS_PACRM_WP5 (9U) /*!< Bit position for AIPS_PACRM_WP5. */ #define BM_AIPS_PACRM_WP5 (0x00000200U) /*!< Bit mask for AIPS_PACRM_WP5. */ #define BS_AIPS_PACRM_WP5 (1U) /*!< Bit field size in bits for AIPS_PACRM_WP5. */ /*! @brief Read current value of the AIPS_PACRM_WP5 field. */ #define BR_AIPS_PACRM_WP5(x) (BITBAND_ACCESS32(HW_AIPS_PACRM_ADDR(x), BP_AIPS_PACRM_WP5)) /*! @brief Format value for bitfield AIPS_PACRM_WP5. */ #define BF_AIPS_PACRM_WP5(v) ((uint32_t)((uint32_t)(v) << BP_AIPS_PACRM_WP5) & BM_AIPS_PACRM_WP5) /*! @brief Set the WP5 field to a new value. */ #define BW_AIPS_PACRM_WP5(x, v) (BITBAND_ACCESS32(HW_AIPS_PACRM_ADDR(x), BP_AIPS_PACRM_WP5) = (v)) /*@}*/ /*! * @name Register AIPS_PACRM, field SP5[10] (RW) * * Determines whether the peripheral requires supervisor privilege level for * accesses. When this field is set, the master privilege level must indicate the * supervisor access attribute, and the MPRx[MPLn] control field for the master * must be set. If not, access terminates with an error response and no peripheral * access initiates. * * Values: * - 0 - This peripheral does not require supervisor privilege level for * accesses. * - 1 - This peripheral requires supervisor privilege level for accesses. */ /*@{*/ #define BP_AIPS_PACRM_SP5 (10U) /*!< Bit position for AIPS_PACRM_SP5. */ #define BM_AIPS_PACRM_SP5 (0x00000400U) /*!< Bit mask for AIPS_PACRM_SP5. */ #define BS_AIPS_PACRM_SP5 (1U) /*!< Bit field size in bits for AIPS_PACRM_SP5. */ /*! @brief Read current value of the AIPS_PACRM_SP5 field. */ #define BR_AIPS_PACRM_SP5(x) (BITBAND_ACCESS32(HW_AIPS_PACRM_ADDR(x), BP_AIPS_PACRM_SP5)) /*! @brief Format value for bitfield AIPS_PACRM_SP5. */ #define BF_AIPS_PACRM_SP5(v) ((uint32_t)((uint32_t)(v) << BP_AIPS_PACRM_SP5) & BM_AIPS_PACRM_SP5) /*! @brief Set the SP5 field to a new value. */ #define BW_AIPS_PACRM_SP5(x, v) (BITBAND_ACCESS32(HW_AIPS_PACRM_ADDR(x), BP_AIPS_PACRM_SP5) = (v)) /*@}*/ /*! * @name Register AIPS_PACRM, field TP4[12] (RW) * * Determines whether the peripheral allows accesses from an untrusted master. * When this bit is set and an access is attempted by an untrusted master, the * access terminates with an error response and no peripheral access initiates. * * Values: * - 0 - Accesses from an untrusted master are allowed. * - 1 - Accesses from an untrusted master are not allowed. */ /*@{*/ #define BP_AIPS_PACRM_TP4 (12U) /*!< Bit position for AIPS_PACRM_TP4. */ #define BM_AIPS_PACRM_TP4 (0x00001000U) /*!< Bit mask for AIPS_PACRM_TP4. */ #define BS_AIPS_PACRM_TP4 (1U) /*!< Bit field size in bits for AIPS_PACRM_TP4. */ /*! @brief Read current value of the AIPS_PACRM_TP4 field. */ #define BR_AIPS_PACRM_TP4(x) (BITBAND_ACCESS32(HW_AIPS_PACRM_ADDR(x), BP_AIPS_PACRM_TP4)) /*! @brief Format value for bitfield AIPS_PACRM_TP4. */ #define BF_AIPS_PACRM_TP4(v) ((uint32_t)((uint32_t)(v) << BP_AIPS_PACRM_TP4) & BM_AIPS_PACRM_TP4) /*! @brief Set the TP4 field to a new value. */ #define BW_AIPS_PACRM_TP4(x, v) (BITBAND_ACCESS32(HW_AIPS_PACRM_ADDR(x), BP_AIPS_PACRM_TP4) = (v)) /*@}*/ /*! * @name Register AIPS_PACRM, field WP4[13] (RW) * * Determines whether the peripheral allows write accesses. When this field is * set and a write access is attempted, access terminates with an error response * and no peripheral access initiates. * * Values: * - 0 - This peripheral allows write accesses. * - 1 - This peripheral is write protected. */ /*@{*/ #define BP_AIPS_PACRM_WP4 (13U) /*!< Bit position for AIPS_PACRM_WP4. */ #define BM_AIPS_PACRM_WP4 (0x00002000U) /*!< Bit mask for AIPS_PACRM_WP4. */ #define BS_AIPS_PACRM_WP4 (1U) /*!< Bit field size in bits for AIPS_PACRM_WP4. */ /*! @brief Read current value of the AIPS_PACRM_WP4 field. */ #define BR_AIPS_PACRM_WP4(x) (BITBAND_ACCESS32(HW_AIPS_PACRM_ADDR(x), BP_AIPS_PACRM_WP4)) /*! @brief Format value for bitfield AIPS_PACRM_WP4. */ #define BF_AIPS_PACRM_WP4(v) ((uint32_t)((uint32_t)(v) << BP_AIPS_PACRM_WP4) & BM_AIPS_PACRM_WP4) /*! @brief Set the WP4 field to a new value. */ #define BW_AIPS_PACRM_WP4(x, v) (BITBAND_ACCESS32(HW_AIPS_PACRM_ADDR(x), BP_AIPS_PACRM_WP4) = (v)) /*@}*/ /*! * @name Register AIPS_PACRM, field SP4[14] (RW) * * Determines whether the peripheral requires supervisor privilege level for * access. When this bit is set, the master privilege level must indicate the * supervisor access attribute, and the MPRx[MPLn] control bit for the master must be * set. If not, access terminates with an error response and no peripheral access * initiates. * * Values: * - 0 - This peripheral does not require supervisor privilege level for * accesses. * - 1 - This peripheral requires supervisor privilege level for accesses. */ /*@{*/ #define BP_AIPS_PACRM_SP4 (14U) /*!< Bit position for AIPS_PACRM_SP4. */ #define BM_AIPS_PACRM_SP4 (0x00004000U) /*!< Bit mask for AIPS_PACRM_SP4. */ #define BS_AIPS_PACRM_SP4 (1U) /*!< Bit field size in bits for AIPS_PACRM_SP4. */ /*! @brief Read current value of the AIPS_PACRM_SP4 field. */ #define BR_AIPS_PACRM_SP4(x) (BITBAND_ACCESS32(HW_AIPS_PACRM_ADDR(x), BP_AIPS_PACRM_SP4)) /*! @brief Format value for bitfield AIPS_PACRM_SP4. */ #define BF_AIPS_PACRM_SP4(v) ((uint32_t)((uint32_t)(v) << BP_AIPS_PACRM_SP4) & BM_AIPS_PACRM_SP4) /*! @brief Set the SP4 field to a new value. */ #define BW_AIPS_PACRM_SP4(x, v) (BITBAND_ACCESS32(HW_AIPS_PACRM_ADDR(x), BP_AIPS_PACRM_SP4) = (v)) /*@}*/ /*! * @name Register AIPS_PACRM, field TP3[16] (RW) * * Determines whether the peripheral allows accesses from an untrusted master. * When this field is set and an access is attempted by an untrusted master, the * access terminates with an error response and no peripheral access initiates. * * Values: * - 0 - Accesses from an untrusted master are allowed. * - 1 - Accesses from an untrusted master are not allowed. */ /*@{*/ #define BP_AIPS_PACRM_TP3 (16U) /*!< Bit position for AIPS_PACRM_TP3. */ #define BM_AIPS_PACRM_TP3 (0x00010000U) /*!< Bit mask for AIPS_PACRM_TP3. */ #define BS_AIPS_PACRM_TP3 (1U) /*!< Bit field size in bits for AIPS_PACRM_TP3. */ /*! @brief Read current value of the AIPS_PACRM_TP3 field. */ #define BR_AIPS_PACRM_TP3(x) (BITBAND_ACCESS32(HW_AIPS_PACRM_ADDR(x), BP_AIPS_PACRM_TP3)) /*! @brief Format value for bitfield AIPS_PACRM_TP3. */ #define BF_AIPS_PACRM_TP3(v) ((uint32_t)((uint32_t)(v) << BP_AIPS_PACRM_TP3) & BM_AIPS_PACRM_TP3) /*! @brief Set the TP3 field to a new value. */ #define BW_AIPS_PACRM_TP3(x, v) (BITBAND_ACCESS32(HW_AIPS_PACRM_ADDR(x), BP_AIPS_PACRM_TP3) = (v)) /*@}*/ /*! * @name Register AIPS_PACRM, field WP3[17] (RW) * * Determines whether the peripheral allows write accesss. When this bit is set * and a write access is attempted, access terminates with an error response and * no peripheral access initiates. * * Values: * - 0 - This peripheral allows write accesses. * - 1 - This peripheral is write protected. */ /*@{*/ #define BP_AIPS_PACRM_WP3 (17U) /*!< Bit position for AIPS_PACRM_WP3. */ #define BM_AIPS_PACRM_WP3 (0x00020000U) /*!< Bit mask for AIPS_PACRM_WP3. */ #define BS_AIPS_PACRM_WP3 (1U) /*!< Bit field size in bits for AIPS_PACRM_WP3. */ /*! @brief Read current value of the AIPS_PACRM_WP3 field. */ #define BR_AIPS_PACRM_WP3(x) (BITBAND_ACCESS32(HW_AIPS_PACRM_ADDR(x), BP_AIPS_PACRM_WP3)) /*! @brief Format value for bitfield AIPS_PACRM_WP3. */ #define BF_AIPS_PACRM_WP3(v) ((uint32_t)((uint32_t)(v) << BP_AIPS_PACRM_WP3) & BM_AIPS_PACRM_WP3) /*! @brief Set the WP3 field to a new value. */ #define BW_AIPS_PACRM_WP3(x, v) (BITBAND_ACCESS32(HW_AIPS_PACRM_ADDR(x), BP_AIPS_PACRM_WP3) = (v)) /*@}*/ /*! * @name Register AIPS_PACRM, field SP3[18] (RW) * * Determines whether the peripheral requires supervisor privilege level for * accesses. When this field is set, the master privilege level must indicate the * supervisor access attribute, and the MPRx[MPLn] control field for the master * must be set. If not, access terminates with an error response and no peripheral * access initiates. * * Values: * - 0 - This peripheral does not require supervisor privilege level for * accesses. * - 1 - This peripheral requires supervisor privilege level for accesses. */ /*@{*/ #define BP_AIPS_PACRM_SP3 (18U) /*!< Bit position for AIPS_PACRM_SP3. */ #define BM_AIPS_PACRM_SP3 (0x00040000U) /*!< Bit mask for AIPS_PACRM_SP3. */ #define BS_AIPS_PACRM_SP3 (1U) /*!< Bit field size in bits for AIPS_PACRM_SP3. */ /*! @brief Read current value of the AIPS_PACRM_SP3 field. */ #define BR_AIPS_PACRM_SP3(x) (BITBAND_ACCESS32(HW_AIPS_PACRM_ADDR(x), BP_AIPS_PACRM_SP3)) /*! @brief Format value for bitfield AIPS_PACRM_SP3. */ #define BF_AIPS_PACRM_SP3(v) ((uint32_t)((uint32_t)(v) << BP_AIPS_PACRM_SP3) & BM_AIPS_PACRM_SP3) /*! @brief Set the SP3 field to a new value. */ #define BW_AIPS_PACRM_SP3(x, v) (BITBAND_ACCESS32(HW_AIPS_PACRM_ADDR(x), BP_AIPS_PACRM_SP3) = (v)) /*@}*/ /*! * @name Register AIPS_PACRM, field TP2[20] (RW) * * Determines whether the peripheral allows accesses from an untrusted master. * When this bit is set and an access is attempted by an untrusted master, the * access terminates with an error response and no peripheral access initiates. * * Values: * - 0 - Accesses from an untrusted master are allowed. * - 1 - Accesses from an untrusted master are not allowed. */ /*@{*/ #define BP_AIPS_PACRM_TP2 (20U) /*!< Bit position for AIPS_PACRM_TP2. */ #define BM_AIPS_PACRM_TP2 (0x00100000U) /*!< Bit mask for AIPS_PACRM_TP2. */ #define BS_AIPS_PACRM_TP2 (1U) /*!< Bit field size in bits for AIPS_PACRM_TP2. */ /*! @brief Read current value of the AIPS_PACRM_TP2 field. */ #define BR_AIPS_PACRM_TP2(x) (BITBAND_ACCESS32(HW_AIPS_PACRM_ADDR(x), BP_AIPS_PACRM_TP2)) /*! @brief Format value for bitfield AIPS_PACRM_TP2. */ #define BF_AIPS_PACRM_TP2(v) ((uint32_t)((uint32_t)(v) << BP_AIPS_PACRM_TP2) & BM_AIPS_PACRM_TP2) /*! @brief Set the TP2 field to a new value. */ #define BW_AIPS_PACRM_TP2(x, v) (BITBAND_ACCESS32(HW_AIPS_PACRM_ADDR(x), BP_AIPS_PACRM_TP2) = (v)) /*@}*/ /*! * @name Register AIPS_PACRM, field WP2[21] (RW) * * Determines whether the peripheral allows write accesses. When this field is * set and a write access is attempted, access terminates with an error response * and no peripheral access initiates. * * Values: * - 0 - This peripheral allows write accesses. * - 1 - This peripheral is write protected. */ /*@{*/ #define BP_AIPS_PACRM_WP2 (21U) /*!< Bit position for AIPS_PACRM_WP2. */ #define BM_AIPS_PACRM_WP2 (0x00200000U) /*!< Bit mask for AIPS_PACRM_WP2. */ #define BS_AIPS_PACRM_WP2 (1U) /*!< Bit field size in bits for AIPS_PACRM_WP2. */ /*! @brief Read current value of the AIPS_PACRM_WP2 field. */ #define BR_AIPS_PACRM_WP2(x) (BITBAND_ACCESS32(HW_AIPS_PACRM_ADDR(x), BP_AIPS_PACRM_WP2)) /*! @brief Format value for bitfield AIPS_PACRM_WP2. */ #define BF_AIPS_PACRM_WP2(v) ((uint32_t)((uint32_t)(v) << BP_AIPS_PACRM_WP2) & BM_AIPS_PACRM_WP2) /*! @brief Set the WP2 field to a new value. */ #define BW_AIPS_PACRM_WP2(x, v) (BITBAND_ACCESS32(HW_AIPS_PACRM_ADDR(x), BP_AIPS_PACRM_WP2) = (v)) /*@}*/ /*! * @name Register AIPS_PACRM, field SP2[22] (RW) * * Determines whether the peripheral requires supervisor privilege level for * access. When this bit is set, the master privilege level must indicate the * supervisor access attribute, and the MPRx[MPLn] control bit for the master must be * set. If not, access terminates with an error response and no peripheral access * initiates. * * Values: * - 0 - This peripheral does not require supervisor privilege level for * accesses. * - 1 - This peripheral requires supervisor privilege level for accesses. */ /*@{*/ #define BP_AIPS_PACRM_SP2 (22U) /*!< Bit position for AIPS_PACRM_SP2. */ #define BM_AIPS_PACRM_SP2 (0x00400000U) /*!< Bit mask for AIPS_PACRM_SP2. */ #define BS_AIPS_PACRM_SP2 (1U) /*!< Bit field size in bits for AIPS_PACRM_SP2. */ /*! @brief Read current value of the AIPS_PACRM_SP2 field. */ #define BR_AIPS_PACRM_SP2(x) (BITBAND_ACCESS32(HW_AIPS_PACRM_ADDR(x), BP_AIPS_PACRM_SP2)) /*! @brief Format value for bitfield AIPS_PACRM_SP2. */ #define BF_AIPS_PACRM_SP2(v) ((uint32_t)((uint32_t)(v) << BP_AIPS_PACRM_SP2) & BM_AIPS_PACRM_SP2) /*! @brief Set the SP2 field to a new value. */ #define BW_AIPS_PACRM_SP2(x, v) (BITBAND_ACCESS32(HW_AIPS_PACRM_ADDR(x), BP_AIPS_PACRM_SP2) = (v)) /*@}*/ /*! * @name Register AIPS_PACRM, field TP1[24] (RW) * * Determines whether the peripheral allows accesses from an untrusted master. * When this field is set and an access is attempted by an untrusted master, the * access terminates with an error response and no peripheral access initiates. * * Values: * - 0 - Accesses from an untrusted master are allowed. * - 1 - Accesses from an untrusted master are not allowed. */ /*@{*/ #define BP_AIPS_PACRM_TP1 (24U) /*!< Bit position for AIPS_PACRM_TP1. */ #define BM_AIPS_PACRM_TP1 (0x01000000U) /*!< Bit mask for AIPS_PACRM_TP1. */ #define BS_AIPS_PACRM_TP1 (1U) /*!< Bit field size in bits for AIPS_PACRM_TP1. */ /*! @brief Read current value of the AIPS_PACRM_TP1 field. */ #define BR_AIPS_PACRM_TP1(x) (BITBAND_ACCESS32(HW_AIPS_PACRM_ADDR(x), BP_AIPS_PACRM_TP1)) /*! @brief Format value for bitfield AIPS_PACRM_TP1. */ #define BF_AIPS_PACRM_TP1(v) ((uint32_t)((uint32_t)(v) << BP_AIPS_PACRM_TP1) & BM_AIPS_PACRM_TP1) /*! @brief Set the TP1 field to a new value. */ #define BW_AIPS_PACRM_TP1(x, v) (BITBAND_ACCESS32(HW_AIPS_PACRM_ADDR(x), BP_AIPS_PACRM_TP1) = (v)) /*@}*/ /*! * @name Register AIPS_PACRM, field WP1[25] (RW) * * Determines whether the peripheral allows write accesses. When this field is * set and a write access is attempted, access terminates with an error response * and no peripheral access initiates. * * Values: * - 0 - This peripheral allows write accesses. * - 1 - This peripheral is write protected. */ /*@{*/ #define BP_AIPS_PACRM_WP1 (25U) /*!< Bit position for AIPS_PACRM_WP1. */ #define BM_AIPS_PACRM_WP1 (0x02000000U) /*!< Bit mask for AIPS_PACRM_WP1. */ #define BS_AIPS_PACRM_WP1 (1U) /*!< Bit field size in bits for AIPS_PACRM_WP1. */ /*! @brief Read current value of the AIPS_PACRM_WP1 field. */ #define BR_AIPS_PACRM_WP1(x) (BITBAND_ACCESS32(HW_AIPS_PACRM_ADDR(x), BP_AIPS_PACRM_WP1)) /*! @brief Format value for bitfield AIPS_PACRM_WP1. */ #define BF_AIPS_PACRM_WP1(v) ((uint32_t)((uint32_t)(v) << BP_AIPS_PACRM_WP1) & BM_AIPS_PACRM_WP1) /*! @brief Set the WP1 field to a new value. */ #define BW_AIPS_PACRM_WP1(x, v) (BITBAND_ACCESS32(HW_AIPS_PACRM_ADDR(x), BP_AIPS_PACRM_WP1) = (v)) /*@}*/ /*! * @name Register AIPS_PACRM, field SP1[26] (RW) * * Determines whether the peripheral requires supervisor privilege level for * access. When this field is set, the master privilege level must indicate the * supervisor access attribute, and the MPRx[MPLn] control field for the master must * be set. If not, access terminates with an error response and no peripheral * access initiates. * * Values: * - 0 - This peripheral does not require supervisor privilege level for * accesses. * - 1 - This peripheral requires supervisor privilege level for accesses. */ /*@{*/ #define BP_AIPS_PACRM_SP1 (26U) /*!< Bit position for AIPS_PACRM_SP1. */ #define BM_AIPS_PACRM_SP1 (0x04000000U) /*!< Bit mask for AIPS_PACRM_SP1. */ #define BS_AIPS_PACRM_SP1 (1U) /*!< Bit field size in bits for AIPS_PACRM_SP1. */ /*! @brief Read current value of the AIPS_PACRM_SP1 field. */ #define BR_AIPS_PACRM_SP1(x) (BITBAND_ACCESS32(HW_AIPS_PACRM_ADDR(x), BP_AIPS_PACRM_SP1)) /*! @brief Format value for bitfield AIPS_PACRM_SP1. */ #define BF_AIPS_PACRM_SP1(v) ((uint32_t)((uint32_t)(v) << BP_AIPS_PACRM_SP1) & BM_AIPS_PACRM_SP1) /*! @brief Set the SP1 field to a new value. */ #define BW_AIPS_PACRM_SP1(x, v) (BITBAND_ACCESS32(HW_AIPS_PACRM_ADDR(x), BP_AIPS_PACRM_SP1) = (v)) /*@}*/ /*! * @name Register AIPS_PACRM, field TP0[28] (RW) * * Determines whether the peripheral allows accesses from an untrusted master. * When this bit is set and an access is attempted by an untrusted master, the * access terminates with an error response and no peripheral access initiates. * * Values: * - 0 - Accesses from an untrusted master are allowed. * - 1 - Accesses from an untrusted master are not allowed. */ /*@{*/ #define BP_AIPS_PACRM_TP0 (28U) /*!< Bit position for AIPS_PACRM_TP0. */ #define BM_AIPS_PACRM_TP0 (0x10000000U) /*!< Bit mask for AIPS_PACRM_TP0. */ #define BS_AIPS_PACRM_TP0 (1U) /*!< Bit field size in bits for AIPS_PACRM_TP0. */ /*! @brief Read current value of the AIPS_PACRM_TP0 field. */ #define BR_AIPS_PACRM_TP0(x) (BITBAND_ACCESS32(HW_AIPS_PACRM_ADDR(x), BP_AIPS_PACRM_TP0)) /*! @brief Format value for bitfield AIPS_PACRM_TP0. */ #define BF_AIPS_PACRM_TP0(v) ((uint32_t)((uint32_t)(v) << BP_AIPS_PACRM_TP0) & BM_AIPS_PACRM_TP0) /*! @brief Set the TP0 field to a new value. */ #define BW_AIPS_PACRM_TP0(x, v) (BITBAND_ACCESS32(HW_AIPS_PACRM_ADDR(x), BP_AIPS_PACRM_TP0) = (v)) /*@}*/ /*! * @name Register AIPS_PACRM, field WP0[29] (RW) * * Determines whether the peripheral allows write accesses. When this field is * set and a write access is attempted, access terminates with an error response * and no peripheral access initiates. * * Values: * - 0 - This peripheral allows write accesses. * - 1 - This peripheral is write protected. */ /*@{*/ #define BP_AIPS_PACRM_WP0 (29U) /*!< Bit position for AIPS_PACRM_WP0. */ #define BM_AIPS_PACRM_WP0 (0x20000000U) /*!< Bit mask for AIPS_PACRM_WP0. */ #define BS_AIPS_PACRM_WP0 (1U) /*!< Bit field size in bits for AIPS_PACRM_WP0. */ /*! @brief Read current value of the AIPS_PACRM_WP0 field. */ #define BR_AIPS_PACRM_WP0(x) (BITBAND_ACCESS32(HW_AIPS_PACRM_ADDR(x), BP_AIPS_PACRM_WP0)) /*! @brief Format value for bitfield AIPS_PACRM_WP0. */ #define BF_AIPS_PACRM_WP0(v) ((uint32_t)((uint32_t)(v) << BP_AIPS_PACRM_WP0) & BM_AIPS_PACRM_WP0) /*! @brief Set the WP0 field to a new value. */ #define BW_AIPS_PACRM_WP0(x, v) (BITBAND_ACCESS32(HW_AIPS_PACRM_ADDR(x), BP_AIPS_PACRM_WP0) = (v)) /*@}*/ /*! * @name Register AIPS_PACRM, field SP0[30] (RW) * * Determines whether the peripheral requires supervisor privilege level for * accesses. When this field is set, the master privilege level must indicate the * supervisor access attribute, and the MPRx[MPLn] control field for the master * must be set. If not, access terminates with an error response and no peripheral * access initiates. * * Values: * - 0 - This peripheral does not require supervisor privilege level for * accesses. * - 1 - This peripheral requires supervisor privilege level for accesses. */ /*@{*/ #define BP_AIPS_PACRM_SP0 (30U) /*!< Bit position for AIPS_PACRM_SP0. */ #define BM_AIPS_PACRM_SP0 (0x40000000U) /*!< Bit mask for AIPS_PACRM_SP0. */ #define BS_AIPS_PACRM_SP0 (1U) /*!< Bit field size in bits for AIPS_PACRM_SP0. */ /*! @brief Read current value of the AIPS_PACRM_SP0 field. */ #define BR_AIPS_PACRM_SP0(x) (BITBAND_ACCESS32(HW_AIPS_PACRM_ADDR(x), BP_AIPS_PACRM_SP0)) /*! @brief Format value for bitfield AIPS_PACRM_SP0. */ #define BF_AIPS_PACRM_SP0(v) ((uint32_t)((uint32_t)(v) << BP_AIPS_PACRM_SP0) & BM_AIPS_PACRM_SP0) /*! @brief Set the SP0 field to a new value. */ #define BW_AIPS_PACRM_SP0(x, v) (BITBAND_ACCESS32(HW_AIPS_PACRM_ADDR(x), BP_AIPS_PACRM_SP0) = (v)) /*@}*/ /******************************************************************************* * HW_AIPS_PACRN - Peripheral Access Control Register ******************************************************************************/ /*! * @brief HW_AIPS_PACRN - Peripheral Access Control Register (RW) * * Reset value: 0x44444444U * * This section describes PACR registers E-P, which control peripheral slots * 32-127. See PACRPeripheral Access Control Register for the description of these * registers. */ typedef union _hw_aips_pacrn { uint32_t U; struct _hw_aips_pacrn_bitfields { uint32_t TP7 : 1; /*!< [0] Trusted Protect */ uint32_t WP7 : 1; /*!< [1] Write Protect */ uint32_t SP7 : 1; /*!< [2] Supervisor Protect */ uint32_t RESERVED0 : 1; /*!< [3] */ uint32_t TP6 : 1; /*!< [4] Trusted Protect */ uint32_t WP6 : 1; /*!< [5] Write Protect */ uint32_t SP6 : 1; /*!< [6] Supervisor Protect */ uint32_t RESERVED1 : 1; /*!< [7] */ uint32_t TP5 : 1; /*!< [8] Trusted Protect */ uint32_t WP5 : 1; /*!< [9] Write Protect */ uint32_t SP5 : 1; /*!< [10] Supervisor Protect */ uint32_t RESERVED2 : 1; /*!< [11] */ uint32_t TP4 : 1; /*!< [12] Trusted Protect */ uint32_t WP4 : 1; /*!< [13] Write Protect */ uint32_t SP4 : 1; /*!< [14] Supervisor Protect */ uint32_t RESERVED3 : 1; /*!< [15] */ uint32_t TP3 : 1; /*!< [16] Trusted Protect */ uint32_t WP3 : 1; /*!< [17] Write Protect */ uint32_t SP3 : 1; /*!< [18] Supervisor Protect */ uint32_t RESERVED4 : 1; /*!< [19] */ uint32_t TP2 : 1; /*!< [20] Trusted Protect */ uint32_t WP2 : 1; /*!< [21] Write Protect */ uint32_t SP2 : 1; /*!< [22] Supervisor Protect */ uint32_t RESERVED5 : 1; /*!< [23] */ uint32_t TP1 : 1; /*!< [24] Trusted Protect */ uint32_t WP1 : 1; /*!< [25] Write Protect */ uint32_t SP1 : 1; /*!< [26] Supervisor Protect */ uint32_t RESERVED6 : 1; /*!< [27] */ uint32_t TP0 : 1; /*!< [28] Trusted Protect */ uint32_t WP0 : 1; /*!< [29] Write Protect */ uint32_t SP0 : 1; /*!< [30] Supervisor Protect */ uint32_t RESERVED7 : 1; /*!< [31] */ } B; } hw_aips_pacrn_t; /*! * @name Constants and macros for entire AIPS_PACRN register */ /*@{*/ #define HW_AIPS_PACRN_ADDR(x) ((x) + 0x64U) #define HW_AIPS_PACRN(x) (*(__IO hw_aips_pacrn_t *) HW_AIPS_PACRN_ADDR(x)) #define HW_AIPS_PACRN_RD(x) (HW_AIPS_PACRN(x).U) #define HW_AIPS_PACRN_WR(x, v) (HW_AIPS_PACRN(x).U = (v)) #define HW_AIPS_PACRN_SET(x, v) (HW_AIPS_PACRN_WR(x, HW_AIPS_PACRN_RD(x) | (v))) #define HW_AIPS_PACRN_CLR(x, v) (HW_AIPS_PACRN_WR(x, HW_AIPS_PACRN_RD(x) & ~(v))) #define HW_AIPS_PACRN_TOG(x, v) (HW_AIPS_PACRN_WR(x, HW_AIPS_PACRN_RD(x) ^ (v))) /*@}*/ /* * Constants & macros for individual AIPS_PACRN bitfields */ /*! * @name Register AIPS_PACRN, field TP7[0] (RW) * * Determines whether the peripheral allows accesses from an untrusted master. * When this field is set and an access is attempted by an untrusted master, the * access terminates with an error response and no peripheral access initiates. * * Values: * - 0 - Accesses from an untrusted master are allowed. * - 1 - Accesses from an untrusted master are not allowed. */ /*@{*/ #define BP_AIPS_PACRN_TP7 (0U) /*!< Bit position for AIPS_PACRN_TP7. */ #define BM_AIPS_PACRN_TP7 (0x00000001U) /*!< Bit mask for AIPS_PACRN_TP7. */ #define BS_AIPS_PACRN_TP7 (1U) /*!< Bit field size in bits for AIPS_PACRN_TP7. */ /*! @brief Read current value of the AIPS_PACRN_TP7 field. */ #define BR_AIPS_PACRN_TP7(x) (BITBAND_ACCESS32(HW_AIPS_PACRN_ADDR(x), BP_AIPS_PACRN_TP7)) /*! @brief Format value for bitfield AIPS_PACRN_TP7. */ #define BF_AIPS_PACRN_TP7(v) ((uint32_t)((uint32_t)(v) << BP_AIPS_PACRN_TP7) & BM_AIPS_PACRN_TP7) /*! @brief Set the TP7 field to a new value. */ #define BW_AIPS_PACRN_TP7(x, v) (BITBAND_ACCESS32(HW_AIPS_PACRN_ADDR(x), BP_AIPS_PACRN_TP7) = (v)) /*@}*/ /*! * @name Register AIPS_PACRN, field WP7[1] (RW) * * Determines whether the peripheral allows write accesses. When this field is * set and a write access is attempted, access terminates with an error response * and no peripheral access initiates. * * Values: * - 0 - This peripheral allows write accesses. * - 1 - This peripheral is write protected. */ /*@{*/ #define BP_AIPS_PACRN_WP7 (1U) /*!< Bit position for AIPS_PACRN_WP7. */ #define BM_AIPS_PACRN_WP7 (0x00000002U) /*!< Bit mask for AIPS_PACRN_WP7. */ #define BS_AIPS_PACRN_WP7 (1U) /*!< Bit field size in bits for AIPS_PACRN_WP7. */ /*! @brief Read current value of the AIPS_PACRN_WP7 field. */ #define BR_AIPS_PACRN_WP7(x) (BITBAND_ACCESS32(HW_AIPS_PACRN_ADDR(x), BP_AIPS_PACRN_WP7)) /*! @brief Format value for bitfield AIPS_PACRN_WP7. */ #define BF_AIPS_PACRN_WP7(v) ((uint32_t)((uint32_t)(v) << BP_AIPS_PACRN_WP7) & BM_AIPS_PACRN_WP7) /*! @brief Set the WP7 field to a new value. */ #define BW_AIPS_PACRN_WP7(x, v) (BITBAND_ACCESS32(HW_AIPS_PACRN_ADDR(x), BP_AIPS_PACRN_WP7) = (v)) /*@}*/ /*! * @name Register AIPS_PACRN, field SP7[2] (RW) * * Determines whether the peripheral requires supervisor privilege level for * accesses. When this field is set, the master privilege level must indicate the * supervisor access attribute, and the MPRx[MPLn] control field for the master * must be set. If not, access terminates with an error response and no peripheral * access initiates. * * Values: * - 0 - This peripheral does not require supervisor privilege level for * accesses. * - 1 - This peripheral requires supervisor privilege level for accesses. */ /*@{*/ #define BP_AIPS_PACRN_SP7 (2U) /*!< Bit position for AIPS_PACRN_SP7. */ #define BM_AIPS_PACRN_SP7 (0x00000004U) /*!< Bit mask for AIPS_PACRN_SP7. */ #define BS_AIPS_PACRN_SP7 (1U) /*!< Bit field size in bits for AIPS_PACRN_SP7. */ /*! @brief Read current value of the AIPS_PACRN_SP7 field. */ #define BR_AIPS_PACRN_SP7(x) (BITBAND_ACCESS32(HW_AIPS_PACRN_ADDR(x), BP_AIPS_PACRN_SP7)) /*! @brief Format value for bitfield AIPS_PACRN_SP7. */ #define BF_AIPS_PACRN_SP7(v) ((uint32_t)((uint32_t)(v) << BP_AIPS_PACRN_SP7) & BM_AIPS_PACRN_SP7) /*! @brief Set the SP7 field to a new value. */ #define BW_AIPS_PACRN_SP7(x, v) (BITBAND_ACCESS32(HW_AIPS_PACRN_ADDR(x), BP_AIPS_PACRN_SP7) = (v)) /*@}*/ /*! * @name Register AIPS_PACRN, field TP6[4] (RW) * * Determines whether the peripheral allows accesses from an untrusted master. * When this field is set and an access is attempted by an untrusted master, the * access terminates with an error response and no peripheral access initiates. * * Values: * - 0 - Accesses from an untrusted master are allowed. * - 1 - Accesses from an untrusted master are not allowed. */ /*@{*/ #define BP_AIPS_PACRN_TP6 (4U) /*!< Bit position for AIPS_PACRN_TP6. */ #define BM_AIPS_PACRN_TP6 (0x00000010U) /*!< Bit mask for AIPS_PACRN_TP6. */ #define BS_AIPS_PACRN_TP6 (1U) /*!< Bit field size in bits for AIPS_PACRN_TP6. */ /*! @brief Read current value of the AIPS_PACRN_TP6 field. */ #define BR_AIPS_PACRN_TP6(x) (BITBAND_ACCESS32(HW_AIPS_PACRN_ADDR(x), BP_AIPS_PACRN_TP6)) /*! @brief Format value for bitfield AIPS_PACRN_TP6. */ #define BF_AIPS_PACRN_TP6(v) ((uint32_t)((uint32_t)(v) << BP_AIPS_PACRN_TP6) & BM_AIPS_PACRN_TP6) /*! @brief Set the TP6 field to a new value. */ #define BW_AIPS_PACRN_TP6(x, v) (BITBAND_ACCESS32(HW_AIPS_PACRN_ADDR(x), BP_AIPS_PACRN_TP6) = (v)) /*@}*/ /*! * @name Register AIPS_PACRN, field WP6[5] (RW) * * Determines whether the peripheral allows write accesses. When this field is * set and a write access is attempted, access terminates with an error response * and no peripheral access initiates. * * Values: * - 0 - This peripheral allows write accesses. * - 1 - This peripheral is write protected. */ /*@{*/ #define BP_AIPS_PACRN_WP6 (5U) /*!< Bit position for AIPS_PACRN_WP6. */ #define BM_AIPS_PACRN_WP6 (0x00000020U) /*!< Bit mask for AIPS_PACRN_WP6. */ #define BS_AIPS_PACRN_WP6 (1U) /*!< Bit field size in bits for AIPS_PACRN_WP6. */ /*! @brief Read current value of the AIPS_PACRN_WP6 field. */ #define BR_AIPS_PACRN_WP6(x) (BITBAND_ACCESS32(HW_AIPS_PACRN_ADDR(x), BP_AIPS_PACRN_WP6)) /*! @brief Format value for bitfield AIPS_PACRN_WP6. */ #define BF_AIPS_PACRN_WP6(v) ((uint32_t)((uint32_t)(v) << BP_AIPS_PACRN_WP6) & BM_AIPS_PACRN_WP6) /*! @brief Set the WP6 field to a new value. */ #define BW_AIPS_PACRN_WP6(x, v) (BITBAND_ACCESS32(HW_AIPS_PACRN_ADDR(x), BP_AIPS_PACRN_WP6) = (v)) /*@}*/ /*! * @name Register AIPS_PACRN, field SP6[6] (RW) * * Determines whether the peripheral requires supervisor privilege level for * accesses. When this field is set, the master privilege level must indicate the * supervisor access attribute, and the MPRx[MPLn] control field for the master * must be set. If not, access terminates with an error response and no peripheral * access initiates. * * Values: * - 0 - This peripheral does not require supervisor privilege level for * accesses. * - 1 - This peripheral requires supervisor privilege level for accesses. */ /*@{*/ #define BP_AIPS_PACRN_SP6 (6U) /*!< Bit position for AIPS_PACRN_SP6. */ #define BM_AIPS_PACRN_SP6 (0x00000040U) /*!< Bit mask for AIPS_PACRN_SP6. */ #define BS_AIPS_PACRN_SP6 (1U) /*!< Bit field size in bits for AIPS_PACRN_SP6. */ /*! @brief Read current value of the AIPS_PACRN_SP6 field. */ #define BR_AIPS_PACRN_SP6(x) (BITBAND_ACCESS32(HW_AIPS_PACRN_ADDR(x), BP_AIPS_PACRN_SP6)) /*! @brief Format value for bitfield AIPS_PACRN_SP6. */ #define BF_AIPS_PACRN_SP6(v) ((uint32_t)((uint32_t)(v) << BP_AIPS_PACRN_SP6) & BM_AIPS_PACRN_SP6) /*! @brief Set the SP6 field to a new value. */ #define BW_AIPS_PACRN_SP6(x, v) (BITBAND_ACCESS32(HW_AIPS_PACRN_ADDR(x), BP_AIPS_PACRN_SP6) = (v)) /*@}*/ /*! * @name Register AIPS_PACRN, field TP5[8] (RW) * * Determines whether the peripheral allows accesses from an untrusted master. * When this field is set and an access is attempted by an untrusted master, the * access terminates with an error response and no peripheral access initiates. * * Values: * - 0 - Accesses from an untrusted master are allowed. * - 1 - Accesses from an untrusted master are not allowed. */ /*@{*/ #define BP_AIPS_PACRN_TP5 (8U) /*!< Bit position for AIPS_PACRN_TP5. */ #define BM_AIPS_PACRN_TP5 (0x00000100U) /*!< Bit mask for AIPS_PACRN_TP5. */ #define BS_AIPS_PACRN_TP5 (1U) /*!< Bit field size in bits for AIPS_PACRN_TP5. */ /*! @brief Read current value of the AIPS_PACRN_TP5 field. */ #define BR_AIPS_PACRN_TP5(x) (BITBAND_ACCESS32(HW_AIPS_PACRN_ADDR(x), BP_AIPS_PACRN_TP5)) /*! @brief Format value for bitfield AIPS_PACRN_TP5. */ #define BF_AIPS_PACRN_TP5(v) ((uint32_t)((uint32_t)(v) << BP_AIPS_PACRN_TP5) & BM_AIPS_PACRN_TP5) /*! @brief Set the TP5 field to a new value. */ #define BW_AIPS_PACRN_TP5(x, v) (BITBAND_ACCESS32(HW_AIPS_PACRN_ADDR(x), BP_AIPS_PACRN_TP5) = (v)) /*@}*/ /*! * @name Register AIPS_PACRN, field WP5[9] (RW) * * Determines whether the peripheral allows write accesses. When this field is * set and a write access is attempted, access terminates with an error response * and no peripheral access initiates. * * Values: * - 0 - This peripheral allows write accesses. * - 1 - This peripheral is write protected. */ /*@{*/ #define BP_AIPS_PACRN_WP5 (9U) /*!< Bit position for AIPS_PACRN_WP5. */ #define BM_AIPS_PACRN_WP5 (0x00000200U) /*!< Bit mask for AIPS_PACRN_WP5. */ #define BS_AIPS_PACRN_WP5 (1U) /*!< Bit field size in bits for AIPS_PACRN_WP5. */ /*! @brief Read current value of the AIPS_PACRN_WP5 field. */ #define BR_AIPS_PACRN_WP5(x) (BITBAND_ACCESS32(HW_AIPS_PACRN_ADDR(x), BP_AIPS_PACRN_WP5)) /*! @brief Format value for bitfield AIPS_PACRN_WP5. */ #define BF_AIPS_PACRN_WP5(v) ((uint32_t)((uint32_t)(v) << BP_AIPS_PACRN_WP5) & BM_AIPS_PACRN_WP5) /*! @brief Set the WP5 field to a new value. */ #define BW_AIPS_PACRN_WP5(x, v) (BITBAND_ACCESS32(HW_AIPS_PACRN_ADDR(x), BP_AIPS_PACRN_WP5) = (v)) /*@}*/ /*! * @name Register AIPS_PACRN, field SP5[10] (RW) * * Determines whether the peripheral requires supervisor privilege level for * accesses. When this field is set, the master privilege level must indicate the * supervisor access attribute, and the MPRx[MPLn] control field for the master * must be set. If not, access terminates with an error response and no peripheral * access initiates. * * Values: * - 0 - This peripheral does not require supervisor privilege level for * accesses. * - 1 - This peripheral requires supervisor privilege level for accesses. */ /*@{*/ #define BP_AIPS_PACRN_SP5 (10U) /*!< Bit position for AIPS_PACRN_SP5. */ #define BM_AIPS_PACRN_SP5 (0x00000400U) /*!< Bit mask for AIPS_PACRN_SP5. */ #define BS_AIPS_PACRN_SP5 (1U) /*!< Bit field size in bits for AIPS_PACRN_SP5. */ /*! @brief Read current value of the AIPS_PACRN_SP5 field. */ #define BR_AIPS_PACRN_SP5(x) (BITBAND_ACCESS32(HW_AIPS_PACRN_ADDR(x), BP_AIPS_PACRN_SP5)) /*! @brief Format value for bitfield AIPS_PACRN_SP5. */ #define BF_AIPS_PACRN_SP5(v) ((uint32_t)((uint32_t)(v) << BP_AIPS_PACRN_SP5) & BM_AIPS_PACRN_SP5) /*! @brief Set the SP5 field to a new value. */ #define BW_AIPS_PACRN_SP5(x, v) (BITBAND_ACCESS32(HW_AIPS_PACRN_ADDR(x), BP_AIPS_PACRN_SP5) = (v)) /*@}*/ /*! * @name Register AIPS_PACRN, field TP4[12] (RW) * * Determines whether the peripheral allows accesses from an untrusted master. * When this bit is set and an access is attempted by an untrusted master, the * access terminates with an error response and no peripheral access initiates. * * Values: * - 0 - Accesses from an untrusted master are allowed. * - 1 - Accesses from an untrusted master are not allowed. */ /*@{*/ #define BP_AIPS_PACRN_TP4 (12U) /*!< Bit position for AIPS_PACRN_TP4. */ #define BM_AIPS_PACRN_TP4 (0x00001000U) /*!< Bit mask for AIPS_PACRN_TP4. */ #define BS_AIPS_PACRN_TP4 (1U) /*!< Bit field size in bits for AIPS_PACRN_TP4. */ /*! @brief Read current value of the AIPS_PACRN_TP4 field. */ #define BR_AIPS_PACRN_TP4(x) (BITBAND_ACCESS32(HW_AIPS_PACRN_ADDR(x), BP_AIPS_PACRN_TP4)) /*! @brief Format value for bitfield AIPS_PACRN_TP4. */ #define BF_AIPS_PACRN_TP4(v) ((uint32_t)((uint32_t)(v) << BP_AIPS_PACRN_TP4) & BM_AIPS_PACRN_TP4) /*! @brief Set the TP4 field to a new value. */ #define BW_AIPS_PACRN_TP4(x, v) (BITBAND_ACCESS32(HW_AIPS_PACRN_ADDR(x), BP_AIPS_PACRN_TP4) = (v)) /*@}*/ /*! * @name Register AIPS_PACRN, field WP4[13] (RW) * * Determines whether the peripheral allows write accesses. When this field is * set and a write access is attempted, access terminates with an error response * and no peripheral access initiates. * * Values: * - 0 - This peripheral allows write accesses. * - 1 - This peripheral is write protected. */ /*@{*/ #define BP_AIPS_PACRN_WP4 (13U) /*!< Bit position for AIPS_PACRN_WP4. */ #define BM_AIPS_PACRN_WP4 (0x00002000U) /*!< Bit mask for AIPS_PACRN_WP4. */ #define BS_AIPS_PACRN_WP4 (1U) /*!< Bit field size in bits for AIPS_PACRN_WP4. */ /*! @brief Read current value of the AIPS_PACRN_WP4 field. */ #define BR_AIPS_PACRN_WP4(x) (BITBAND_ACCESS32(HW_AIPS_PACRN_ADDR(x), BP_AIPS_PACRN_WP4)) /*! @brief Format value for bitfield AIPS_PACRN_WP4. */ #define BF_AIPS_PACRN_WP4(v) ((uint32_t)((uint32_t)(v) << BP_AIPS_PACRN_WP4) & BM_AIPS_PACRN_WP4) /*! @brief Set the WP4 field to a new value. */ #define BW_AIPS_PACRN_WP4(x, v) (BITBAND_ACCESS32(HW_AIPS_PACRN_ADDR(x), BP_AIPS_PACRN_WP4) = (v)) /*@}*/ /*! * @name Register AIPS_PACRN, field SP4[14] (RW) * * Determines whether the peripheral requires supervisor privilege level for * access. When this bit is set, the master privilege level must indicate the * supervisor access attribute, and the MPRx[MPLn] control bit for the master must be * set. If not, access terminates with an error response and no peripheral access * initiates. * * Values: * - 0 - This peripheral does not require supervisor privilege level for * accesses. * - 1 - This peripheral requires supervisor privilege level for accesses. */ /*@{*/ #define BP_AIPS_PACRN_SP4 (14U) /*!< Bit position for AIPS_PACRN_SP4. */ #define BM_AIPS_PACRN_SP4 (0x00004000U) /*!< Bit mask for AIPS_PACRN_SP4. */ #define BS_AIPS_PACRN_SP4 (1U) /*!< Bit field size in bits for AIPS_PACRN_SP4. */ /*! @brief Read current value of the AIPS_PACRN_SP4 field. */ #define BR_AIPS_PACRN_SP4(x) (BITBAND_ACCESS32(HW_AIPS_PACRN_ADDR(x), BP_AIPS_PACRN_SP4)) /*! @brief Format value for bitfield AIPS_PACRN_SP4. */ #define BF_AIPS_PACRN_SP4(v) ((uint32_t)((uint32_t)(v) << BP_AIPS_PACRN_SP4) & BM_AIPS_PACRN_SP4) /*! @brief Set the SP4 field to a new value. */ #define BW_AIPS_PACRN_SP4(x, v) (BITBAND_ACCESS32(HW_AIPS_PACRN_ADDR(x), BP_AIPS_PACRN_SP4) = (v)) /*@}*/ /*! * @name Register AIPS_PACRN, field TP3[16] (RW) * * Determines whether the peripheral allows accesses from an untrusted master. * When this field is set and an access is attempted by an untrusted master, the * access terminates with an error response and no peripheral access initiates. * * Values: * - 0 - Accesses from an untrusted master are allowed. * - 1 - Accesses from an untrusted master are not allowed. */ /*@{*/ #define BP_AIPS_PACRN_TP3 (16U) /*!< Bit position for AIPS_PACRN_TP3. */ #define BM_AIPS_PACRN_TP3 (0x00010000U) /*!< Bit mask for AIPS_PACRN_TP3. */ #define BS_AIPS_PACRN_TP3 (1U) /*!< Bit field size in bits for AIPS_PACRN_TP3. */ /*! @brief Read current value of the AIPS_PACRN_TP3 field. */ #define BR_AIPS_PACRN_TP3(x) (BITBAND_ACCESS32(HW_AIPS_PACRN_ADDR(x), BP_AIPS_PACRN_TP3)) /*! @brief Format value for bitfield AIPS_PACRN_TP3. */ #define BF_AIPS_PACRN_TP3(v) ((uint32_t)((uint32_t)(v) << BP_AIPS_PACRN_TP3) & BM_AIPS_PACRN_TP3) /*! @brief Set the TP3 field to a new value. */ #define BW_AIPS_PACRN_TP3(x, v) (BITBAND_ACCESS32(HW_AIPS_PACRN_ADDR(x), BP_AIPS_PACRN_TP3) = (v)) /*@}*/ /*! * @name Register AIPS_PACRN, field WP3[17] (RW) * * Determines whether the peripheral allows write accesss. When this bit is set * and a write access is attempted, access terminates with an error response and * no peripheral access initiates. * * Values: * - 0 - This peripheral allows write accesses. * - 1 - This peripheral is write protected. */ /*@{*/ #define BP_AIPS_PACRN_WP3 (17U) /*!< Bit position for AIPS_PACRN_WP3. */ #define BM_AIPS_PACRN_WP3 (0x00020000U) /*!< Bit mask for AIPS_PACRN_WP3. */ #define BS_AIPS_PACRN_WP3 (1U) /*!< Bit field size in bits for AIPS_PACRN_WP3. */ /*! @brief Read current value of the AIPS_PACRN_WP3 field. */ #define BR_AIPS_PACRN_WP3(x) (BITBAND_ACCESS32(HW_AIPS_PACRN_ADDR(x), BP_AIPS_PACRN_WP3)) /*! @brief Format value for bitfield AIPS_PACRN_WP3. */ #define BF_AIPS_PACRN_WP3(v) ((uint32_t)((uint32_t)(v) << BP_AIPS_PACRN_WP3) & BM_AIPS_PACRN_WP3) /*! @brief Set the WP3 field to a new value. */ #define BW_AIPS_PACRN_WP3(x, v) (BITBAND_ACCESS32(HW_AIPS_PACRN_ADDR(x), BP_AIPS_PACRN_WP3) = (v)) /*@}*/ /*! * @name Register AIPS_PACRN, field SP3[18] (RW) * * Determines whether the peripheral requires supervisor privilege level for * accesses. When this field is set, the master privilege level must indicate the * supervisor access attribute, and the MPRx[MPLn] control field for the master * must be set. If not, access terminates with an error response and no peripheral * access initiates. * * Values: * - 0 - This peripheral does not require supervisor privilege level for * accesses. * - 1 - This peripheral requires supervisor privilege level for accesses. */ /*@{*/ #define BP_AIPS_PACRN_SP3 (18U) /*!< Bit position for AIPS_PACRN_SP3. */ #define BM_AIPS_PACRN_SP3 (0x00040000U) /*!< Bit mask for AIPS_PACRN_SP3. */ #define BS_AIPS_PACRN_SP3 (1U) /*!< Bit field size in bits for AIPS_PACRN_SP3. */ /*! @brief Read current value of the AIPS_PACRN_SP3 field. */ #define BR_AIPS_PACRN_SP3(x) (BITBAND_ACCESS32(HW_AIPS_PACRN_ADDR(x), BP_AIPS_PACRN_SP3)) /*! @brief Format value for bitfield AIPS_PACRN_SP3. */ #define BF_AIPS_PACRN_SP3(v) ((uint32_t)((uint32_t)(v) << BP_AIPS_PACRN_SP3) & BM_AIPS_PACRN_SP3) /*! @brief Set the SP3 field to a new value. */ #define BW_AIPS_PACRN_SP3(x, v) (BITBAND_ACCESS32(HW_AIPS_PACRN_ADDR(x), BP_AIPS_PACRN_SP3) = (v)) /*@}*/ /*! * @name Register AIPS_PACRN, field TP2[20] (RW) * * Determines whether the peripheral allows accesses from an untrusted master. * When this bit is set and an access is attempted by an untrusted master, the * access terminates with an error response and no peripheral access initiates. * * Values: * - 0 - Accesses from an untrusted master are allowed. * - 1 - Accesses from an untrusted master are not allowed. */ /*@{*/ #define BP_AIPS_PACRN_TP2 (20U) /*!< Bit position for AIPS_PACRN_TP2. */ #define BM_AIPS_PACRN_TP2 (0x00100000U) /*!< Bit mask for AIPS_PACRN_TP2. */ #define BS_AIPS_PACRN_TP2 (1U) /*!< Bit field size in bits for AIPS_PACRN_TP2. */ /*! @brief Read current value of the AIPS_PACRN_TP2 field. */ #define BR_AIPS_PACRN_TP2(x) (BITBAND_ACCESS32(HW_AIPS_PACRN_ADDR(x), BP_AIPS_PACRN_TP2)) /*! @brief Format value for bitfield AIPS_PACRN_TP2. */ #define BF_AIPS_PACRN_TP2(v) ((uint32_t)((uint32_t)(v) << BP_AIPS_PACRN_TP2) & BM_AIPS_PACRN_TP2) /*! @brief Set the TP2 field to a new value. */ #define BW_AIPS_PACRN_TP2(x, v) (BITBAND_ACCESS32(HW_AIPS_PACRN_ADDR(x), BP_AIPS_PACRN_TP2) = (v)) /*@}*/ /*! * @name Register AIPS_PACRN, field WP2[21] (RW) * * Determines whether the peripheral allows write accesses. When this field is * set and a write access is attempted, access terminates with an error response * and no peripheral access initiates. * * Values: * - 0 - This peripheral allows write accesses. * - 1 - This peripheral is write protected. */ /*@{*/ #define BP_AIPS_PACRN_WP2 (21U) /*!< Bit position for AIPS_PACRN_WP2. */ #define BM_AIPS_PACRN_WP2 (0x00200000U) /*!< Bit mask for AIPS_PACRN_WP2. */ #define BS_AIPS_PACRN_WP2 (1U) /*!< Bit field size in bits for AIPS_PACRN_WP2. */ /*! @brief Read current value of the AIPS_PACRN_WP2 field. */ #define BR_AIPS_PACRN_WP2(x) (BITBAND_ACCESS32(HW_AIPS_PACRN_ADDR(x), BP_AIPS_PACRN_WP2)) /*! @brief Format value for bitfield AIPS_PACRN_WP2. */ #define BF_AIPS_PACRN_WP2(v) ((uint32_t)((uint32_t)(v) << BP_AIPS_PACRN_WP2) & BM_AIPS_PACRN_WP2) /*! @brief Set the WP2 field to a new value. */ #define BW_AIPS_PACRN_WP2(x, v) (BITBAND_ACCESS32(HW_AIPS_PACRN_ADDR(x), BP_AIPS_PACRN_WP2) = (v)) /*@}*/ /*! * @name Register AIPS_PACRN, field SP2[22] (RW) * * Determines whether the peripheral requires supervisor privilege level for * access. When this bit is set, the master privilege level must indicate the * supervisor access attribute, and the MPRx[MPLn] control bit for the master must be * set. If not, access terminates with an error response and no peripheral access * initiates. * * Values: * - 0 - This peripheral does not require supervisor privilege level for * accesses. * - 1 - This peripheral requires supervisor privilege level for accesses. */ /*@{*/ #define BP_AIPS_PACRN_SP2 (22U) /*!< Bit position for AIPS_PACRN_SP2. */ #define BM_AIPS_PACRN_SP2 (0x00400000U) /*!< Bit mask for AIPS_PACRN_SP2. */ #define BS_AIPS_PACRN_SP2 (1U) /*!< Bit field size in bits for AIPS_PACRN_SP2. */ /*! @brief Read current value of the AIPS_PACRN_SP2 field. */ #define BR_AIPS_PACRN_SP2(x) (BITBAND_ACCESS32(HW_AIPS_PACRN_ADDR(x), BP_AIPS_PACRN_SP2)) /*! @brief Format value for bitfield AIPS_PACRN_SP2. */ #define BF_AIPS_PACRN_SP2(v) ((uint32_t)((uint32_t)(v) << BP_AIPS_PACRN_SP2) & BM_AIPS_PACRN_SP2) /*! @brief Set the SP2 field to a new value. */ #define BW_AIPS_PACRN_SP2(x, v) (BITBAND_ACCESS32(HW_AIPS_PACRN_ADDR(x), BP_AIPS_PACRN_SP2) = (v)) /*@}*/ /*! * @name Register AIPS_PACRN, field TP1[24] (RW) * * Determines whether the peripheral allows accesses from an untrusted master. * When this field is set and an access is attempted by an untrusted master, the * access terminates with an error response and no peripheral access initiates. * * Values: * - 0 - Accesses from an untrusted master are allowed. * - 1 - Accesses from an untrusted master are not allowed. */ /*@{*/ #define BP_AIPS_PACRN_TP1 (24U) /*!< Bit position for AIPS_PACRN_TP1. */ #define BM_AIPS_PACRN_TP1 (0x01000000U) /*!< Bit mask for AIPS_PACRN_TP1. */ #define BS_AIPS_PACRN_TP1 (1U) /*!< Bit field size in bits for AIPS_PACRN_TP1. */ /*! @brief Read current value of the AIPS_PACRN_TP1 field. */ #define BR_AIPS_PACRN_TP1(x) (BITBAND_ACCESS32(HW_AIPS_PACRN_ADDR(x), BP_AIPS_PACRN_TP1)) /*! @brief Format value for bitfield AIPS_PACRN_TP1. */ #define BF_AIPS_PACRN_TP1(v) ((uint32_t)((uint32_t)(v) << BP_AIPS_PACRN_TP1) & BM_AIPS_PACRN_TP1) /*! @brief Set the TP1 field to a new value. */ #define BW_AIPS_PACRN_TP1(x, v) (BITBAND_ACCESS32(HW_AIPS_PACRN_ADDR(x), BP_AIPS_PACRN_TP1) = (v)) /*@}*/ /*! * @name Register AIPS_PACRN, field WP1[25] (RW) * * Determines whether the peripheral allows write accesses. When this field is * set and a write access is attempted, access terminates with an error response * and no peripheral access initiates. * * Values: * - 0 - This peripheral allows write accesses. * - 1 - This peripheral is write protected. */ /*@{*/ #define BP_AIPS_PACRN_WP1 (25U) /*!< Bit position for AIPS_PACRN_WP1. */ #define BM_AIPS_PACRN_WP1 (0x02000000U) /*!< Bit mask for AIPS_PACRN_WP1. */ #define BS_AIPS_PACRN_WP1 (1U) /*!< Bit field size in bits for AIPS_PACRN_WP1. */ /*! @brief Read current value of the AIPS_PACRN_WP1 field. */ #define BR_AIPS_PACRN_WP1(x) (BITBAND_ACCESS32(HW_AIPS_PACRN_ADDR(x), BP_AIPS_PACRN_WP1)) /*! @brief Format value for bitfield AIPS_PACRN_WP1. */ #define BF_AIPS_PACRN_WP1(v) ((uint32_t)((uint32_t)(v) << BP_AIPS_PACRN_WP1) & BM_AIPS_PACRN_WP1) /*! @brief Set the WP1 field to a new value. */ #define BW_AIPS_PACRN_WP1(x, v) (BITBAND_ACCESS32(HW_AIPS_PACRN_ADDR(x), BP_AIPS_PACRN_WP1) = (v)) /*@}*/ /*! * @name Register AIPS_PACRN, field SP1[26] (RW) * * Determines whether the peripheral requires supervisor privilege level for * access. When this field is set, the master privilege level must indicate the * supervisor access attribute, and the MPRx[MPLn] control field for the master must * be set. If not, access terminates with an error response and no peripheral * access initiates. * * Values: * - 0 - This peripheral does not require supervisor privilege level for * accesses. * - 1 - This peripheral requires supervisor privilege level for accesses. */ /*@{*/ #define BP_AIPS_PACRN_SP1 (26U) /*!< Bit position for AIPS_PACRN_SP1. */ #define BM_AIPS_PACRN_SP1 (0x04000000U) /*!< Bit mask for AIPS_PACRN_SP1. */ #define BS_AIPS_PACRN_SP1 (1U) /*!< Bit field size in bits for AIPS_PACRN_SP1. */ /*! @brief Read current value of the AIPS_PACRN_SP1 field. */ #define BR_AIPS_PACRN_SP1(x) (BITBAND_ACCESS32(HW_AIPS_PACRN_ADDR(x), BP_AIPS_PACRN_SP1)) /*! @brief Format value for bitfield AIPS_PACRN_SP1. */ #define BF_AIPS_PACRN_SP1(v) ((uint32_t)((uint32_t)(v) << BP_AIPS_PACRN_SP1) & BM_AIPS_PACRN_SP1) /*! @brief Set the SP1 field to a new value. */ #define BW_AIPS_PACRN_SP1(x, v) (BITBAND_ACCESS32(HW_AIPS_PACRN_ADDR(x), BP_AIPS_PACRN_SP1) = (v)) /*@}*/ /*! * @name Register AIPS_PACRN, field TP0[28] (RW) * * Determines whether the peripheral allows accesses from an untrusted master. * When this bit is set and an access is attempted by an untrusted master, the * access terminates with an error response and no peripheral access initiates. * * Values: * - 0 - Accesses from an untrusted master are allowed. * - 1 - Accesses from an untrusted master are not allowed. */ /*@{*/ #define BP_AIPS_PACRN_TP0 (28U) /*!< Bit position for AIPS_PACRN_TP0. */ #define BM_AIPS_PACRN_TP0 (0x10000000U) /*!< Bit mask for AIPS_PACRN_TP0. */ #define BS_AIPS_PACRN_TP0 (1U) /*!< Bit field size in bits for AIPS_PACRN_TP0. */ /*! @brief Read current value of the AIPS_PACRN_TP0 field. */ #define BR_AIPS_PACRN_TP0(x) (BITBAND_ACCESS32(HW_AIPS_PACRN_ADDR(x), BP_AIPS_PACRN_TP0)) /*! @brief Format value for bitfield AIPS_PACRN_TP0. */ #define BF_AIPS_PACRN_TP0(v) ((uint32_t)((uint32_t)(v) << BP_AIPS_PACRN_TP0) & BM_AIPS_PACRN_TP0) /*! @brief Set the TP0 field to a new value. */ #define BW_AIPS_PACRN_TP0(x, v) (BITBAND_ACCESS32(HW_AIPS_PACRN_ADDR(x), BP_AIPS_PACRN_TP0) = (v)) /*@}*/ /*! * @name Register AIPS_PACRN, field WP0[29] (RW) * * Determines whether the peripheral allows write accesses. When this field is * set and a write access is attempted, access terminates with an error response * and no peripheral access initiates. * * Values: * - 0 - This peripheral allows write accesses. * - 1 - This peripheral is write protected. */ /*@{*/ #define BP_AIPS_PACRN_WP0 (29U) /*!< Bit position for AIPS_PACRN_WP0. */ #define BM_AIPS_PACRN_WP0 (0x20000000U) /*!< Bit mask for AIPS_PACRN_WP0. */ #define BS_AIPS_PACRN_WP0 (1U) /*!< Bit field size in bits for AIPS_PACRN_WP0. */ /*! @brief Read current value of the AIPS_PACRN_WP0 field. */ #define BR_AIPS_PACRN_WP0(x) (BITBAND_ACCESS32(HW_AIPS_PACRN_ADDR(x), BP_AIPS_PACRN_WP0)) /*! @brief Format value for bitfield AIPS_PACRN_WP0. */ #define BF_AIPS_PACRN_WP0(v) ((uint32_t)((uint32_t)(v) << BP_AIPS_PACRN_WP0) & BM_AIPS_PACRN_WP0) /*! @brief Set the WP0 field to a new value. */ #define BW_AIPS_PACRN_WP0(x, v) (BITBAND_ACCESS32(HW_AIPS_PACRN_ADDR(x), BP_AIPS_PACRN_WP0) = (v)) /*@}*/ /*! * @name Register AIPS_PACRN, field SP0[30] (RW) * * Determines whether the peripheral requires supervisor privilege level for * accesses. When this field is set, the master privilege level must indicate the * supervisor access attribute, and the MPRx[MPLn] control field for the master * must be set. If not, access terminates with an error response and no peripheral * access initiates. * * Values: * - 0 - This peripheral does not require supervisor privilege level for * accesses. * - 1 - This peripheral requires supervisor privilege level for accesses. */ /*@{*/ #define BP_AIPS_PACRN_SP0 (30U) /*!< Bit position for AIPS_PACRN_SP0. */ #define BM_AIPS_PACRN_SP0 (0x40000000U) /*!< Bit mask for AIPS_PACRN_SP0. */ #define BS_AIPS_PACRN_SP0 (1U) /*!< Bit field size in bits for AIPS_PACRN_SP0. */ /*! @brief Read current value of the AIPS_PACRN_SP0 field. */ #define BR_AIPS_PACRN_SP0(x) (BITBAND_ACCESS32(HW_AIPS_PACRN_ADDR(x), BP_AIPS_PACRN_SP0)) /*! @brief Format value for bitfield AIPS_PACRN_SP0. */ #define BF_AIPS_PACRN_SP0(v) ((uint32_t)((uint32_t)(v) << BP_AIPS_PACRN_SP0) & BM_AIPS_PACRN_SP0) /*! @brief Set the SP0 field to a new value. */ #define BW_AIPS_PACRN_SP0(x, v) (BITBAND_ACCESS32(HW_AIPS_PACRN_ADDR(x), BP_AIPS_PACRN_SP0) = (v)) /*@}*/ /******************************************************************************* * HW_AIPS_PACRO - Peripheral Access Control Register ******************************************************************************/ /*! * @brief HW_AIPS_PACRO - Peripheral Access Control Register (RW) * * Reset value: 0x44444444U * * This section describes PACR registers E-P, which control peripheral slots * 32-127. See PACRPeripheral Access Control Register for the description of these * registers. */ typedef union _hw_aips_pacro { uint32_t U; struct _hw_aips_pacro_bitfields { uint32_t TP7 : 1; /*!< [0] Trusted Protect */ uint32_t WP7 : 1; /*!< [1] Write Protect */ uint32_t SP7 : 1; /*!< [2] Supervisor Protect */ uint32_t RESERVED0 : 1; /*!< [3] */ uint32_t TP6 : 1; /*!< [4] Trusted Protect */ uint32_t WP6 : 1; /*!< [5] Write Protect */ uint32_t SP6 : 1; /*!< [6] Supervisor Protect */ uint32_t RESERVED1 : 1; /*!< [7] */ uint32_t TP5 : 1; /*!< [8] Trusted Protect */ uint32_t WP5 : 1; /*!< [9] Write Protect */ uint32_t SP5 : 1; /*!< [10] Supervisor Protect */ uint32_t RESERVED2 : 1; /*!< [11] */ uint32_t TP4 : 1; /*!< [12] Trusted Protect */ uint32_t WP4 : 1; /*!< [13] Write Protect */ uint32_t SP4 : 1; /*!< [14] Supervisor Protect */ uint32_t RESERVED3 : 1; /*!< [15] */ uint32_t TP3 : 1; /*!< [16] Trusted Protect */ uint32_t WP3 : 1; /*!< [17] Write Protect */ uint32_t SP3 : 1; /*!< [18] Supervisor Protect */ uint32_t RESERVED4 : 1; /*!< [19] */ uint32_t TP2 : 1; /*!< [20] Trusted Protect */ uint32_t WP2 : 1; /*!< [21] Write Protect */ uint32_t SP2 : 1; /*!< [22] Supervisor Protect */ uint32_t RESERVED5 : 1; /*!< [23] */ uint32_t TP1 : 1; /*!< [24] Trusted Protect */ uint32_t WP1 : 1; /*!< [25] Write Protect */ uint32_t SP1 : 1; /*!< [26] Supervisor Protect */ uint32_t RESERVED6 : 1; /*!< [27] */ uint32_t TP0 : 1; /*!< [28] Trusted Protect */ uint32_t WP0 : 1; /*!< [29] Write Protect */ uint32_t SP0 : 1; /*!< [30] Supervisor Protect */ uint32_t RESERVED7 : 1; /*!< [31] */ } B; } hw_aips_pacro_t; /*! * @name Constants and macros for entire AIPS_PACRO register */ /*@{*/ #define HW_AIPS_PACRO_ADDR(x) ((x) + 0x68U) #define HW_AIPS_PACRO(x) (*(__IO hw_aips_pacro_t *) HW_AIPS_PACRO_ADDR(x)) #define HW_AIPS_PACRO_RD(x) (HW_AIPS_PACRO(x).U) #define HW_AIPS_PACRO_WR(x, v) (HW_AIPS_PACRO(x).U = (v)) #define HW_AIPS_PACRO_SET(x, v) (HW_AIPS_PACRO_WR(x, HW_AIPS_PACRO_RD(x) | (v))) #define HW_AIPS_PACRO_CLR(x, v) (HW_AIPS_PACRO_WR(x, HW_AIPS_PACRO_RD(x) & ~(v))) #define HW_AIPS_PACRO_TOG(x, v) (HW_AIPS_PACRO_WR(x, HW_AIPS_PACRO_RD(x) ^ (v))) /*@}*/ /* * Constants & macros for individual AIPS_PACRO bitfields */ /*! * @name Register AIPS_PACRO, field TP7[0] (RW) * * Determines whether the peripheral allows accesses from an untrusted master. * When this field is set and an access is attempted by an untrusted master, the * access terminates with an error response and no peripheral access initiates. * * Values: * - 0 - Accesses from an untrusted master are allowed. * - 1 - Accesses from an untrusted master are not allowed. */ /*@{*/ #define BP_AIPS_PACRO_TP7 (0U) /*!< Bit position for AIPS_PACRO_TP7. */ #define BM_AIPS_PACRO_TP7 (0x00000001U) /*!< Bit mask for AIPS_PACRO_TP7. */ #define BS_AIPS_PACRO_TP7 (1U) /*!< Bit field size in bits for AIPS_PACRO_TP7. */ /*! @brief Read current value of the AIPS_PACRO_TP7 field. */ #define BR_AIPS_PACRO_TP7(x) (BITBAND_ACCESS32(HW_AIPS_PACRO_ADDR(x), BP_AIPS_PACRO_TP7)) /*! @brief Format value for bitfield AIPS_PACRO_TP7. */ #define BF_AIPS_PACRO_TP7(v) ((uint32_t)((uint32_t)(v) << BP_AIPS_PACRO_TP7) & BM_AIPS_PACRO_TP7) /*! @brief Set the TP7 field to a new value. */ #define BW_AIPS_PACRO_TP7(x, v) (BITBAND_ACCESS32(HW_AIPS_PACRO_ADDR(x), BP_AIPS_PACRO_TP7) = (v)) /*@}*/ /*! * @name Register AIPS_PACRO, field WP7[1] (RW) * * Determines whether the peripheral allows write accesses. When this field is * set and a write access is attempted, access terminates with an error response * and no peripheral access initiates. * * Values: * - 0 - This peripheral allows write accesses. * - 1 - This peripheral is write protected. */ /*@{*/ #define BP_AIPS_PACRO_WP7 (1U) /*!< Bit position for AIPS_PACRO_WP7. */ #define BM_AIPS_PACRO_WP7 (0x00000002U) /*!< Bit mask for AIPS_PACRO_WP7. */ #define BS_AIPS_PACRO_WP7 (1U) /*!< Bit field size in bits for AIPS_PACRO_WP7. */ /*! @brief Read current value of the AIPS_PACRO_WP7 field. */ #define BR_AIPS_PACRO_WP7(x) (BITBAND_ACCESS32(HW_AIPS_PACRO_ADDR(x), BP_AIPS_PACRO_WP7)) /*! @brief Format value for bitfield AIPS_PACRO_WP7. */ #define BF_AIPS_PACRO_WP7(v) ((uint32_t)((uint32_t)(v) << BP_AIPS_PACRO_WP7) & BM_AIPS_PACRO_WP7) /*! @brief Set the WP7 field to a new value. */ #define BW_AIPS_PACRO_WP7(x, v) (BITBAND_ACCESS32(HW_AIPS_PACRO_ADDR(x), BP_AIPS_PACRO_WP7) = (v)) /*@}*/ /*! * @name Register AIPS_PACRO, field SP7[2] (RW) * * Determines whether the peripheral requires supervisor privilege level for * accesses. When this field is set, the master privilege level must indicate the * supervisor access attribute, and the MPRx[MPLn] control field for the master * must be set. If not, access terminates with an error response and no peripheral * access initiates. * * Values: * - 0 - This peripheral does not require supervisor privilege level for * accesses. * - 1 - This peripheral requires supervisor privilege level for accesses. */ /*@{*/ #define BP_AIPS_PACRO_SP7 (2U) /*!< Bit position for AIPS_PACRO_SP7. */ #define BM_AIPS_PACRO_SP7 (0x00000004U) /*!< Bit mask for AIPS_PACRO_SP7. */ #define BS_AIPS_PACRO_SP7 (1U) /*!< Bit field size in bits for AIPS_PACRO_SP7. */ /*! @brief Read current value of the AIPS_PACRO_SP7 field. */ #define BR_AIPS_PACRO_SP7(x) (BITBAND_ACCESS32(HW_AIPS_PACRO_ADDR(x), BP_AIPS_PACRO_SP7)) /*! @brief Format value for bitfield AIPS_PACRO_SP7. */ #define BF_AIPS_PACRO_SP7(v) ((uint32_t)((uint32_t)(v) << BP_AIPS_PACRO_SP7) & BM_AIPS_PACRO_SP7) /*! @brief Set the SP7 field to a new value. */ #define BW_AIPS_PACRO_SP7(x, v) (BITBAND_ACCESS32(HW_AIPS_PACRO_ADDR(x), BP_AIPS_PACRO_SP7) = (v)) /*@}*/ /*! * @name Register AIPS_PACRO, field TP6[4] (RW) * * Determines whether the peripheral allows accesses from an untrusted master. * When this field is set and an access is attempted by an untrusted master, the * access terminates with an error response and no peripheral access initiates. * * Values: * - 0 - Accesses from an untrusted master are allowed. * - 1 - Accesses from an untrusted master are not allowed. */ /*@{*/ #define BP_AIPS_PACRO_TP6 (4U) /*!< Bit position for AIPS_PACRO_TP6. */ #define BM_AIPS_PACRO_TP6 (0x00000010U) /*!< Bit mask for AIPS_PACRO_TP6. */ #define BS_AIPS_PACRO_TP6 (1U) /*!< Bit field size in bits for AIPS_PACRO_TP6. */ /*! @brief Read current value of the AIPS_PACRO_TP6 field. */ #define BR_AIPS_PACRO_TP6(x) (BITBAND_ACCESS32(HW_AIPS_PACRO_ADDR(x), BP_AIPS_PACRO_TP6)) /*! @brief Format value for bitfield AIPS_PACRO_TP6. */ #define BF_AIPS_PACRO_TP6(v) ((uint32_t)((uint32_t)(v) << BP_AIPS_PACRO_TP6) & BM_AIPS_PACRO_TP6) /*! @brief Set the TP6 field to a new value. */ #define BW_AIPS_PACRO_TP6(x, v) (BITBAND_ACCESS32(HW_AIPS_PACRO_ADDR(x), BP_AIPS_PACRO_TP6) = (v)) /*@}*/ /*! * @name Register AIPS_PACRO, field WP6[5] (RW) * * Determines whether the peripheral allows write accesses. When this field is * set and a write access is attempted, access terminates with an error response * and no peripheral access initiates. * * Values: * - 0 - This peripheral allows write accesses. * - 1 - This peripheral is write protected. */ /*@{*/ #define BP_AIPS_PACRO_WP6 (5U) /*!< Bit position for AIPS_PACRO_WP6. */ #define BM_AIPS_PACRO_WP6 (0x00000020U) /*!< Bit mask for AIPS_PACRO_WP6. */ #define BS_AIPS_PACRO_WP6 (1U) /*!< Bit field size in bits for AIPS_PACRO_WP6. */ /*! @brief Read current value of the AIPS_PACRO_WP6 field. */ #define BR_AIPS_PACRO_WP6(x) (BITBAND_ACCESS32(HW_AIPS_PACRO_ADDR(x), BP_AIPS_PACRO_WP6)) /*! @brief Format value for bitfield AIPS_PACRO_WP6. */ #define BF_AIPS_PACRO_WP6(v) ((uint32_t)((uint32_t)(v) << BP_AIPS_PACRO_WP6) & BM_AIPS_PACRO_WP6) /*! @brief Set the WP6 field to a new value. */ #define BW_AIPS_PACRO_WP6(x, v) (BITBAND_ACCESS32(HW_AIPS_PACRO_ADDR(x), BP_AIPS_PACRO_WP6) = (v)) /*@}*/ /*! * @name Register AIPS_PACRO, field SP6[6] (RW) * * Determines whether the peripheral requires supervisor privilege level for * accesses. When this field is set, the master privilege level must indicate the * supervisor access attribute, and the MPRx[MPLn] control field for the master * must be set. If not, access terminates with an error response and no peripheral * access initiates. * * Values: * - 0 - This peripheral does not require supervisor privilege level for * accesses. * - 1 - This peripheral requires supervisor privilege level for accesses. */ /*@{*/ #define BP_AIPS_PACRO_SP6 (6U) /*!< Bit position for AIPS_PACRO_SP6. */ #define BM_AIPS_PACRO_SP6 (0x00000040U) /*!< Bit mask for AIPS_PACRO_SP6. */ #define BS_AIPS_PACRO_SP6 (1U) /*!< Bit field size in bits for AIPS_PACRO_SP6. */ /*! @brief Read current value of the AIPS_PACRO_SP6 field. */ #define BR_AIPS_PACRO_SP6(x) (BITBAND_ACCESS32(HW_AIPS_PACRO_ADDR(x), BP_AIPS_PACRO_SP6)) /*! @brief Format value for bitfield AIPS_PACRO_SP6. */ #define BF_AIPS_PACRO_SP6(v) ((uint32_t)((uint32_t)(v) << BP_AIPS_PACRO_SP6) & BM_AIPS_PACRO_SP6) /*! @brief Set the SP6 field to a new value. */ #define BW_AIPS_PACRO_SP6(x, v) (BITBAND_ACCESS32(HW_AIPS_PACRO_ADDR(x), BP_AIPS_PACRO_SP6) = (v)) /*@}*/ /*! * @name Register AIPS_PACRO, field TP5[8] (RW) * * Determines whether the peripheral allows accesses from an untrusted master. * When this field is set and an access is attempted by an untrusted master, the * access terminates with an error response and no peripheral access initiates. * * Values: * - 0 - Accesses from an untrusted master are allowed. * - 1 - Accesses from an untrusted master are not allowed. */ /*@{*/ #define BP_AIPS_PACRO_TP5 (8U) /*!< Bit position for AIPS_PACRO_TP5. */ #define BM_AIPS_PACRO_TP5 (0x00000100U) /*!< Bit mask for AIPS_PACRO_TP5. */ #define BS_AIPS_PACRO_TP5 (1U) /*!< Bit field size in bits for AIPS_PACRO_TP5. */ /*! @brief Read current value of the AIPS_PACRO_TP5 field. */ #define BR_AIPS_PACRO_TP5(x) (BITBAND_ACCESS32(HW_AIPS_PACRO_ADDR(x), BP_AIPS_PACRO_TP5)) /*! @brief Format value for bitfield AIPS_PACRO_TP5. */ #define BF_AIPS_PACRO_TP5(v) ((uint32_t)((uint32_t)(v) << BP_AIPS_PACRO_TP5) & BM_AIPS_PACRO_TP5) /*! @brief Set the TP5 field to a new value. */ #define BW_AIPS_PACRO_TP5(x, v) (BITBAND_ACCESS32(HW_AIPS_PACRO_ADDR(x), BP_AIPS_PACRO_TP5) = (v)) /*@}*/ /*! * @name Register AIPS_PACRO, field WP5[9] (RW) * * Determines whether the peripheral allows write accesses. When this field is * set and a write access is attempted, access terminates with an error response * and no peripheral access initiates. * * Values: * - 0 - This peripheral allows write accesses. * - 1 - This peripheral is write protected. */ /*@{*/ #define BP_AIPS_PACRO_WP5 (9U) /*!< Bit position for AIPS_PACRO_WP5. */ #define BM_AIPS_PACRO_WP5 (0x00000200U) /*!< Bit mask for AIPS_PACRO_WP5. */ #define BS_AIPS_PACRO_WP5 (1U) /*!< Bit field size in bits for AIPS_PACRO_WP5. */ /*! @brief Read current value of the AIPS_PACRO_WP5 field. */ #define BR_AIPS_PACRO_WP5(x) (BITBAND_ACCESS32(HW_AIPS_PACRO_ADDR(x), BP_AIPS_PACRO_WP5)) /*! @brief Format value for bitfield AIPS_PACRO_WP5. */ #define BF_AIPS_PACRO_WP5(v) ((uint32_t)((uint32_t)(v) << BP_AIPS_PACRO_WP5) & BM_AIPS_PACRO_WP5) /*! @brief Set the WP5 field to a new value. */ #define BW_AIPS_PACRO_WP5(x, v) (BITBAND_ACCESS32(HW_AIPS_PACRO_ADDR(x), BP_AIPS_PACRO_WP5) = (v)) /*@}*/ /*! * @name Register AIPS_PACRO, field SP5[10] (RW) * * Determines whether the peripheral requires supervisor privilege level for * accesses. When this field is set, the master privilege level must indicate the * supervisor access attribute, and the MPRx[MPLn] control field for the master * must be set. If not, access terminates with an error response and no peripheral * access initiates. * * Values: * - 0 - This peripheral does not require supervisor privilege level for * accesses. * - 1 - This peripheral requires supervisor privilege level for accesses. */ /*@{*/ #define BP_AIPS_PACRO_SP5 (10U) /*!< Bit position for AIPS_PACRO_SP5. */ #define BM_AIPS_PACRO_SP5 (0x00000400U) /*!< Bit mask for AIPS_PACRO_SP5. */ #define BS_AIPS_PACRO_SP5 (1U) /*!< Bit field size in bits for AIPS_PACRO_SP5. */ /*! @brief Read current value of the AIPS_PACRO_SP5 field. */ #define BR_AIPS_PACRO_SP5(x) (BITBAND_ACCESS32(HW_AIPS_PACRO_ADDR(x), BP_AIPS_PACRO_SP5)) /*! @brief Format value for bitfield AIPS_PACRO_SP5. */ #define BF_AIPS_PACRO_SP5(v) ((uint32_t)((uint32_t)(v) << BP_AIPS_PACRO_SP5) & BM_AIPS_PACRO_SP5) /*! @brief Set the SP5 field to a new value. */ #define BW_AIPS_PACRO_SP5(x, v) (BITBAND_ACCESS32(HW_AIPS_PACRO_ADDR(x), BP_AIPS_PACRO_SP5) = (v)) /*@}*/ /*! * @name Register AIPS_PACRO, field TP4[12] (RW) * * Determines whether the peripheral allows accesses from an untrusted master. * When this bit is set and an access is attempted by an untrusted master, the * access terminates with an error response and no peripheral access initiates. * * Values: * - 0 - Accesses from an untrusted master are allowed. * - 1 - Accesses from an untrusted master are not allowed. */ /*@{*/ #define BP_AIPS_PACRO_TP4 (12U) /*!< Bit position for AIPS_PACRO_TP4. */ #define BM_AIPS_PACRO_TP4 (0x00001000U) /*!< Bit mask for AIPS_PACRO_TP4. */ #define BS_AIPS_PACRO_TP4 (1U) /*!< Bit field size in bits for AIPS_PACRO_TP4. */ /*! @brief Read current value of the AIPS_PACRO_TP4 field. */ #define BR_AIPS_PACRO_TP4(x) (BITBAND_ACCESS32(HW_AIPS_PACRO_ADDR(x), BP_AIPS_PACRO_TP4)) /*! @brief Format value for bitfield AIPS_PACRO_TP4. */ #define BF_AIPS_PACRO_TP4(v) ((uint32_t)((uint32_t)(v) << BP_AIPS_PACRO_TP4) & BM_AIPS_PACRO_TP4) /*! @brief Set the TP4 field to a new value. */ #define BW_AIPS_PACRO_TP4(x, v) (BITBAND_ACCESS32(HW_AIPS_PACRO_ADDR(x), BP_AIPS_PACRO_TP4) = (v)) /*@}*/ /*! * @name Register AIPS_PACRO, field WP4[13] (RW) * * Determines whether the peripheral allows write accesses. When this field is * set and a write access is attempted, access terminates with an error response * and no peripheral access initiates. * * Values: * - 0 - This peripheral allows write accesses. * - 1 - This peripheral is write protected. */ /*@{*/ #define BP_AIPS_PACRO_WP4 (13U) /*!< Bit position for AIPS_PACRO_WP4. */ #define BM_AIPS_PACRO_WP4 (0x00002000U) /*!< Bit mask for AIPS_PACRO_WP4. */ #define BS_AIPS_PACRO_WP4 (1U) /*!< Bit field size in bits for AIPS_PACRO_WP4. */ /*! @brief Read current value of the AIPS_PACRO_WP4 field. */ #define BR_AIPS_PACRO_WP4(x) (BITBAND_ACCESS32(HW_AIPS_PACRO_ADDR(x), BP_AIPS_PACRO_WP4)) /*! @brief Format value for bitfield AIPS_PACRO_WP4. */ #define BF_AIPS_PACRO_WP4(v) ((uint32_t)((uint32_t)(v) << BP_AIPS_PACRO_WP4) & BM_AIPS_PACRO_WP4) /*! @brief Set the WP4 field to a new value. */ #define BW_AIPS_PACRO_WP4(x, v) (BITBAND_ACCESS32(HW_AIPS_PACRO_ADDR(x), BP_AIPS_PACRO_WP4) = (v)) /*@}*/ /*! * @name Register AIPS_PACRO, field SP4[14] (RW) * * Determines whether the peripheral requires supervisor privilege level for * access. When this bit is set, the master privilege level must indicate the * supervisor access attribute, and the MPRx[MPLn] control bit for the master must be * set. If not, access terminates with an error response and no peripheral access * initiates. * * Values: * - 0 - This peripheral does not require supervisor privilege level for * accesses. * - 1 - This peripheral requires supervisor privilege level for accesses. */ /*@{*/ #define BP_AIPS_PACRO_SP4 (14U) /*!< Bit position for AIPS_PACRO_SP4. */ #define BM_AIPS_PACRO_SP4 (0x00004000U) /*!< Bit mask for AIPS_PACRO_SP4. */ #define BS_AIPS_PACRO_SP4 (1U) /*!< Bit field size in bits for AIPS_PACRO_SP4. */ /*! @brief Read current value of the AIPS_PACRO_SP4 field. */ #define BR_AIPS_PACRO_SP4(x) (BITBAND_ACCESS32(HW_AIPS_PACRO_ADDR(x), BP_AIPS_PACRO_SP4)) /*! @brief Format value for bitfield AIPS_PACRO_SP4. */ #define BF_AIPS_PACRO_SP4(v) ((uint32_t)((uint32_t)(v) << BP_AIPS_PACRO_SP4) & BM_AIPS_PACRO_SP4) /*! @brief Set the SP4 field to a new value. */ #define BW_AIPS_PACRO_SP4(x, v) (BITBAND_ACCESS32(HW_AIPS_PACRO_ADDR(x), BP_AIPS_PACRO_SP4) = (v)) /*@}*/ /*! * @name Register AIPS_PACRO, field TP3[16] (RW) * * Determines whether the peripheral allows accesses from an untrusted master. * When this field is set and an access is attempted by an untrusted master, the * access terminates with an error response and no peripheral access initiates. * * Values: * - 0 - Accesses from an untrusted master are allowed. * - 1 - Accesses from an untrusted master are not allowed. */ /*@{*/ #define BP_AIPS_PACRO_TP3 (16U) /*!< Bit position for AIPS_PACRO_TP3. */ #define BM_AIPS_PACRO_TP3 (0x00010000U) /*!< Bit mask for AIPS_PACRO_TP3. */ #define BS_AIPS_PACRO_TP3 (1U) /*!< Bit field size in bits for AIPS_PACRO_TP3. */ /*! @brief Read current value of the AIPS_PACRO_TP3 field. */ #define BR_AIPS_PACRO_TP3(x) (BITBAND_ACCESS32(HW_AIPS_PACRO_ADDR(x), BP_AIPS_PACRO_TP3)) /*! @brief Format value for bitfield AIPS_PACRO_TP3. */ #define BF_AIPS_PACRO_TP3(v) ((uint32_t)((uint32_t)(v) << BP_AIPS_PACRO_TP3) & BM_AIPS_PACRO_TP3) /*! @brief Set the TP3 field to a new value. */ #define BW_AIPS_PACRO_TP3(x, v) (BITBAND_ACCESS32(HW_AIPS_PACRO_ADDR(x), BP_AIPS_PACRO_TP3) = (v)) /*@}*/ /*! * @name Register AIPS_PACRO, field WP3[17] (RW) * * Determines whether the peripheral allows write accesss. When this bit is set * and a write access is attempted, access terminates with an error response and * no peripheral access initiates. * * Values: * - 0 - This peripheral allows write accesses. * - 1 - This peripheral is write protected. */ /*@{*/ #define BP_AIPS_PACRO_WP3 (17U) /*!< Bit position for AIPS_PACRO_WP3. */ #define BM_AIPS_PACRO_WP3 (0x00020000U) /*!< Bit mask for AIPS_PACRO_WP3. */ #define BS_AIPS_PACRO_WP3 (1U) /*!< Bit field size in bits for AIPS_PACRO_WP3. */ /*! @brief Read current value of the AIPS_PACRO_WP3 field. */ #define BR_AIPS_PACRO_WP3(x) (BITBAND_ACCESS32(HW_AIPS_PACRO_ADDR(x), BP_AIPS_PACRO_WP3)) /*! @brief Format value for bitfield AIPS_PACRO_WP3. */ #define BF_AIPS_PACRO_WP3(v) ((uint32_t)((uint32_t)(v) << BP_AIPS_PACRO_WP3) & BM_AIPS_PACRO_WP3) /*! @brief Set the WP3 field to a new value. */ #define BW_AIPS_PACRO_WP3(x, v) (BITBAND_ACCESS32(HW_AIPS_PACRO_ADDR(x), BP_AIPS_PACRO_WP3) = (v)) /*@}*/ /*! * @name Register AIPS_PACRO, field SP3[18] (RW) * * Determines whether the peripheral requires supervisor privilege level for * accesses. When this field is set, the master privilege level must indicate the * supervisor access attribute, and the MPRx[MPLn] control field for the master * must be set. If not, access terminates with an error response and no peripheral * access initiates. * * Values: * - 0 - This peripheral does not require supervisor privilege level for * accesses. * - 1 - This peripheral requires supervisor privilege level for accesses. */ /*@{*/ #define BP_AIPS_PACRO_SP3 (18U) /*!< Bit position for AIPS_PACRO_SP3. */ #define BM_AIPS_PACRO_SP3 (0x00040000U) /*!< Bit mask for AIPS_PACRO_SP3. */ #define BS_AIPS_PACRO_SP3 (1U) /*!< Bit field size in bits for AIPS_PACRO_SP3. */ /*! @brief Read current value of the AIPS_PACRO_SP3 field. */ #define BR_AIPS_PACRO_SP3(x) (BITBAND_ACCESS32(HW_AIPS_PACRO_ADDR(x), BP_AIPS_PACRO_SP3)) /*! @brief Format value for bitfield AIPS_PACRO_SP3. */ #define BF_AIPS_PACRO_SP3(v) ((uint32_t)((uint32_t)(v) << BP_AIPS_PACRO_SP3) & BM_AIPS_PACRO_SP3) /*! @brief Set the SP3 field to a new value. */ #define BW_AIPS_PACRO_SP3(x, v) (BITBAND_ACCESS32(HW_AIPS_PACRO_ADDR(x), BP_AIPS_PACRO_SP3) = (v)) /*@}*/ /*! * @name Register AIPS_PACRO, field TP2[20] (RW) * * Determines whether the peripheral allows accesses from an untrusted master. * When this bit is set and an access is attempted by an untrusted master, the * access terminates with an error response and no peripheral access initiates. * * Values: * - 0 - Accesses from an untrusted master are allowed. * - 1 - Accesses from an untrusted master are not allowed. */ /*@{*/ #define BP_AIPS_PACRO_TP2 (20U) /*!< Bit position for AIPS_PACRO_TP2. */ #define BM_AIPS_PACRO_TP2 (0x00100000U) /*!< Bit mask for AIPS_PACRO_TP2. */ #define BS_AIPS_PACRO_TP2 (1U) /*!< Bit field size in bits for AIPS_PACRO_TP2. */ /*! @brief Read current value of the AIPS_PACRO_TP2 field. */ #define BR_AIPS_PACRO_TP2(x) (BITBAND_ACCESS32(HW_AIPS_PACRO_ADDR(x), BP_AIPS_PACRO_TP2)) /*! @brief Format value for bitfield AIPS_PACRO_TP2. */ #define BF_AIPS_PACRO_TP2(v) ((uint32_t)((uint32_t)(v) << BP_AIPS_PACRO_TP2) & BM_AIPS_PACRO_TP2) /*! @brief Set the TP2 field to a new value. */ #define BW_AIPS_PACRO_TP2(x, v) (BITBAND_ACCESS32(HW_AIPS_PACRO_ADDR(x), BP_AIPS_PACRO_TP2) = (v)) /*@}*/ /*! * @name Register AIPS_PACRO, field WP2[21] (RW) * * Determines whether the peripheral allows write accesses. When this field is * set and a write access is attempted, access terminates with an error response * and no peripheral access initiates. * * Values: * - 0 - This peripheral allows write accesses. * - 1 - This peripheral is write protected. */ /*@{*/ #define BP_AIPS_PACRO_WP2 (21U) /*!< Bit position for AIPS_PACRO_WP2. */ #define BM_AIPS_PACRO_WP2 (0x00200000U) /*!< Bit mask for AIPS_PACRO_WP2. */ #define BS_AIPS_PACRO_WP2 (1U) /*!< Bit field size in bits for AIPS_PACRO_WP2. */ /*! @brief Read current value of the AIPS_PACRO_WP2 field. */ #define BR_AIPS_PACRO_WP2(x) (BITBAND_ACCESS32(HW_AIPS_PACRO_ADDR(x), BP_AIPS_PACRO_WP2)) /*! @brief Format value for bitfield AIPS_PACRO_WP2. */ #define BF_AIPS_PACRO_WP2(v) ((uint32_t)((uint32_t)(v) << BP_AIPS_PACRO_WP2) & BM_AIPS_PACRO_WP2) /*! @brief Set the WP2 field to a new value. */ #define BW_AIPS_PACRO_WP2(x, v) (BITBAND_ACCESS32(HW_AIPS_PACRO_ADDR(x), BP_AIPS_PACRO_WP2) = (v)) /*@}*/ /*! * @name Register AIPS_PACRO, field SP2[22] (RW) * * Determines whether the peripheral requires supervisor privilege level for * access. When this bit is set, the master privilege level must indicate the * supervisor access attribute, and the MPRx[MPLn] control bit for the master must be * set. If not, access terminates with an error response and no peripheral access * initiates. * * Values: * - 0 - This peripheral does not require supervisor privilege level for * accesses. * - 1 - This peripheral requires supervisor privilege level for accesses. */ /*@{*/ #define BP_AIPS_PACRO_SP2 (22U) /*!< Bit position for AIPS_PACRO_SP2. */ #define BM_AIPS_PACRO_SP2 (0x00400000U) /*!< Bit mask for AIPS_PACRO_SP2. */ #define BS_AIPS_PACRO_SP2 (1U) /*!< Bit field size in bits for AIPS_PACRO_SP2. */ /*! @brief Read current value of the AIPS_PACRO_SP2 field. */ #define BR_AIPS_PACRO_SP2(x) (BITBAND_ACCESS32(HW_AIPS_PACRO_ADDR(x), BP_AIPS_PACRO_SP2)) /*! @brief Format value for bitfield AIPS_PACRO_SP2. */ #define BF_AIPS_PACRO_SP2(v) ((uint32_t)((uint32_t)(v) << BP_AIPS_PACRO_SP2) & BM_AIPS_PACRO_SP2) /*! @brief Set the SP2 field to a new value. */ #define BW_AIPS_PACRO_SP2(x, v) (BITBAND_ACCESS32(HW_AIPS_PACRO_ADDR(x), BP_AIPS_PACRO_SP2) = (v)) /*@}*/ /*! * @name Register AIPS_PACRO, field TP1[24] (RW) * * Determines whether the peripheral allows accesses from an untrusted master. * When this field is set and an access is attempted by an untrusted master, the * access terminates with an error response and no peripheral access initiates. * * Values: * - 0 - Accesses from an untrusted master are allowed. * - 1 - Accesses from an untrusted master are not allowed. */ /*@{*/ #define BP_AIPS_PACRO_TP1 (24U) /*!< Bit position for AIPS_PACRO_TP1. */ #define BM_AIPS_PACRO_TP1 (0x01000000U) /*!< Bit mask for AIPS_PACRO_TP1. */ #define BS_AIPS_PACRO_TP1 (1U) /*!< Bit field size in bits for AIPS_PACRO_TP1. */ /*! @brief Read current value of the AIPS_PACRO_TP1 field. */ #define BR_AIPS_PACRO_TP1(x) (BITBAND_ACCESS32(HW_AIPS_PACRO_ADDR(x), BP_AIPS_PACRO_TP1)) /*! @brief Format value for bitfield AIPS_PACRO_TP1. */ #define BF_AIPS_PACRO_TP1(v) ((uint32_t)((uint32_t)(v) << BP_AIPS_PACRO_TP1) & BM_AIPS_PACRO_TP1) /*! @brief Set the TP1 field to a new value. */ #define BW_AIPS_PACRO_TP1(x, v) (BITBAND_ACCESS32(HW_AIPS_PACRO_ADDR(x), BP_AIPS_PACRO_TP1) = (v)) /*@}*/ /*! * @name Register AIPS_PACRO, field WP1[25] (RW) * * Determines whether the peripheral allows write accesses. When this field is * set and a write access is attempted, access terminates with an error response * and no peripheral access initiates. * * Values: * - 0 - This peripheral allows write accesses. * - 1 - This peripheral is write protected. */ /*@{*/ #define BP_AIPS_PACRO_WP1 (25U) /*!< Bit position for AIPS_PACRO_WP1. */ #define BM_AIPS_PACRO_WP1 (0x02000000U) /*!< Bit mask for AIPS_PACRO_WP1. */ #define BS_AIPS_PACRO_WP1 (1U) /*!< Bit field size in bits for AIPS_PACRO_WP1. */ /*! @brief Read current value of the AIPS_PACRO_WP1 field. */ #define BR_AIPS_PACRO_WP1(x) (BITBAND_ACCESS32(HW_AIPS_PACRO_ADDR(x), BP_AIPS_PACRO_WP1)) /*! @brief Format value for bitfield AIPS_PACRO_WP1. */ #define BF_AIPS_PACRO_WP1(v) ((uint32_t)((uint32_t)(v) << BP_AIPS_PACRO_WP1) & BM_AIPS_PACRO_WP1) /*! @brief Set the WP1 field to a new value. */ #define BW_AIPS_PACRO_WP1(x, v) (BITBAND_ACCESS32(HW_AIPS_PACRO_ADDR(x), BP_AIPS_PACRO_WP1) = (v)) /*@}*/ /*! * @name Register AIPS_PACRO, field SP1[26] (RW) * * Determines whether the peripheral requires supervisor privilege level for * access. When this field is set, the master privilege level must indicate the * supervisor access attribute, and the MPRx[MPLn] control field for the master must * be set. If not, access terminates with an error response and no peripheral * access initiates. * * Values: * - 0 - This peripheral does not require supervisor privilege level for * accesses. * - 1 - This peripheral requires supervisor privilege level for accesses. */ /*@{*/ #define BP_AIPS_PACRO_SP1 (26U) /*!< Bit position for AIPS_PACRO_SP1. */ #define BM_AIPS_PACRO_SP1 (0x04000000U) /*!< Bit mask for AIPS_PACRO_SP1. */ #define BS_AIPS_PACRO_SP1 (1U) /*!< Bit field size in bits for AIPS_PACRO_SP1. */ /*! @brief Read current value of the AIPS_PACRO_SP1 field. */ #define BR_AIPS_PACRO_SP1(x) (BITBAND_ACCESS32(HW_AIPS_PACRO_ADDR(x), BP_AIPS_PACRO_SP1)) /*! @brief Format value for bitfield AIPS_PACRO_SP1. */ #define BF_AIPS_PACRO_SP1(v) ((uint32_t)((uint32_t)(v) << BP_AIPS_PACRO_SP1) & BM_AIPS_PACRO_SP1) /*! @brief Set the SP1 field to a new value. */ #define BW_AIPS_PACRO_SP1(x, v) (BITBAND_ACCESS32(HW_AIPS_PACRO_ADDR(x), BP_AIPS_PACRO_SP1) = (v)) /*@}*/ /*! * @name Register AIPS_PACRO, field TP0[28] (RW) * * Determines whether the peripheral allows accesses from an untrusted master. * When this bit is set and an access is attempted by an untrusted master, the * access terminates with an error response and no peripheral access initiates. * * Values: * - 0 - Accesses from an untrusted master are allowed. * - 1 - Accesses from an untrusted master are not allowed. */ /*@{*/ #define BP_AIPS_PACRO_TP0 (28U) /*!< Bit position for AIPS_PACRO_TP0. */ #define BM_AIPS_PACRO_TP0 (0x10000000U) /*!< Bit mask for AIPS_PACRO_TP0. */ #define BS_AIPS_PACRO_TP0 (1U) /*!< Bit field size in bits for AIPS_PACRO_TP0. */ /*! @brief Read current value of the AIPS_PACRO_TP0 field. */ #define BR_AIPS_PACRO_TP0(x) (BITBAND_ACCESS32(HW_AIPS_PACRO_ADDR(x), BP_AIPS_PACRO_TP0)) /*! @brief Format value for bitfield AIPS_PACRO_TP0. */ #define BF_AIPS_PACRO_TP0(v) ((uint32_t)((uint32_t)(v) << BP_AIPS_PACRO_TP0) & BM_AIPS_PACRO_TP0) /*! @brief Set the TP0 field to a new value. */ #define BW_AIPS_PACRO_TP0(x, v) (BITBAND_ACCESS32(HW_AIPS_PACRO_ADDR(x), BP_AIPS_PACRO_TP0) = (v)) /*@}*/ /*! * @name Register AIPS_PACRO, field WP0[29] (RW) * * Determines whether the peripheral allows write accesses. When this field is * set and a write access is attempted, access terminates with an error response * and no peripheral access initiates. * * Values: * - 0 - This peripheral allows write accesses. * - 1 - This peripheral is write protected. */ /*@{*/ #define BP_AIPS_PACRO_WP0 (29U) /*!< Bit position for AIPS_PACRO_WP0. */ #define BM_AIPS_PACRO_WP0 (0x20000000U) /*!< Bit mask for AIPS_PACRO_WP0. */ #define BS_AIPS_PACRO_WP0 (1U) /*!< Bit field size in bits for AIPS_PACRO_WP0. */ /*! @brief Read current value of the AIPS_PACRO_WP0 field. */ #define BR_AIPS_PACRO_WP0(x) (BITBAND_ACCESS32(HW_AIPS_PACRO_ADDR(x), BP_AIPS_PACRO_WP0)) /*! @brief Format value for bitfield AIPS_PACRO_WP0. */ #define BF_AIPS_PACRO_WP0(v) ((uint32_t)((uint32_t)(v) << BP_AIPS_PACRO_WP0) & BM_AIPS_PACRO_WP0) /*! @brief Set the WP0 field to a new value. */ #define BW_AIPS_PACRO_WP0(x, v) (BITBAND_ACCESS32(HW_AIPS_PACRO_ADDR(x), BP_AIPS_PACRO_WP0) = (v)) /*@}*/ /*! * @name Register AIPS_PACRO, field SP0[30] (RW) * * Determines whether the peripheral requires supervisor privilege level for * accesses. When this field is set, the master privilege level must indicate the * supervisor access attribute, and the MPRx[MPLn] control field for the master * must be set. If not, access terminates with an error response and no peripheral * access initiates. * * Values: * - 0 - This peripheral does not require supervisor privilege level for * accesses. * - 1 - This peripheral requires supervisor privilege level for accesses. */ /*@{*/ #define BP_AIPS_PACRO_SP0 (30U) /*!< Bit position for AIPS_PACRO_SP0. */ #define BM_AIPS_PACRO_SP0 (0x40000000U) /*!< Bit mask for AIPS_PACRO_SP0. */ #define BS_AIPS_PACRO_SP0 (1U) /*!< Bit field size in bits for AIPS_PACRO_SP0. */ /*! @brief Read current value of the AIPS_PACRO_SP0 field. */ #define BR_AIPS_PACRO_SP0(x) (BITBAND_ACCESS32(HW_AIPS_PACRO_ADDR(x), BP_AIPS_PACRO_SP0)) /*! @brief Format value for bitfield AIPS_PACRO_SP0. */ #define BF_AIPS_PACRO_SP0(v) ((uint32_t)((uint32_t)(v) << BP_AIPS_PACRO_SP0) & BM_AIPS_PACRO_SP0) /*! @brief Set the SP0 field to a new value. */ #define BW_AIPS_PACRO_SP0(x, v) (BITBAND_ACCESS32(HW_AIPS_PACRO_ADDR(x), BP_AIPS_PACRO_SP0) = (v)) /*@}*/ /******************************************************************************* * HW_AIPS_PACRP - Peripheral Access Control Register ******************************************************************************/ /*! * @brief HW_AIPS_PACRP - Peripheral Access Control Register (RW) * * Reset value: 0x44444444U * * This section describes PACR registers E-P, which control peripheral slots * 32-127. See PACRPeripheral Access Control Register for the description of these * registers. */ typedef union _hw_aips_pacrp { uint32_t U; struct _hw_aips_pacrp_bitfields { uint32_t TP7 : 1; /*!< [0] Trusted Protect */ uint32_t WP7 : 1; /*!< [1] Write Protect */ uint32_t SP7 : 1; /*!< [2] Supervisor Protect */ uint32_t RESERVED0 : 1; /*!< [3] */ uint32_t TP6 : 1; /*!< [4] Trusted Protect */ uint32_t WP6 : 1; /*!< [5] Write Protect */ uint32_t SP6 : 1; /*!< [6] Supervisor Protect */ uint32_t RESERVED1 : 1; /*!< [7] */ uint32_t TP5 : 1; /*!< [8] Trusted Protect */ uint32_t WP5 : 1; /*!< [9] Write Protect */ uint32_t SP5 : 1; /*!< [10] Supervisor Protect */ uint32_t RESERVED2 : 1; /*!< [11] */ uint32_t TP4 : 1; /*!< [12] Trusted Protect */ uint32_t WP4 : 1; /*!< [13] Write Protect */ uint32_t SP4 : 1; /*!< [14] Supervisor Protect */ uint32_t RESERVED3 : 1; /*!< [15] */ uint32_t TP3 : 1; /*!< [16] Trusted Protect */ uint32_t WP3 : 1; /*!< [17] Write Protect */ uint32_t SP3 : 1; /*!< [18] Supervisor Protect */ uint32_t RESERVED4 : 1; /*!< [19] */ uint32_t TP2 : 1; /*!< [20] Trusted Protect */ uint32_t WP2 : 1; /*!< [21] Write Protect */ uint32_t SP2 : 1; /*!< [22] Supervisor Protect */ uint32_t RESERVED5 : 1; /*!< [23] */ uint32_t TP1 : 1; /*!< [24] Trusted Protect */ uint32_t WP1 : 1; /*!< [25] Write Protect */ uint32_t SP1 : 1; /*!< [26] Supervisor Protect */ uint32_t RESERVED6 : 1; /*!< [27] */ uint32_t TP0 : 1; /*!< [28] Trusted Protect */ uint32_t WP0 : 1; /*!< [29] Write Protect */ uint32_t SP0 : 1; /*!< [30] Supervisor Protect */ uint32_t RESERVED7 : 1; /*!< [31] */ } B; } hw_aips_pacrp_t; /*! * @name Constants and macros for entire AIPS_PACRP register */ /*@{*/ #define HW_AIPS_PACRP_ADDR(x) ((x) + 0x6CU) #define HW_AIPS_PACRP(x) (*(__IO hw_aips_pacrp_t *) HW_AIPS_PACRP_ADDR(x)) #define HW_AIPS_PACRP_RD(x) (HW_AIPS_PACRP(x).U) #define HW_AIPS_PACRP_WR(x, v) (HW_AIPS_PACRP(x).U = (v)) #define HW_AIPS_PACRP_SET(x, v) (HW_AIPS_PACRP_WR(x, HW_AIPS_PACRP_RD(x) | (v))) #define HW_AIPS_PACRP_CLR(x, v) (HW_AIPS_PACRP_WR(x, HW_AIPS_PACRP_RD(x) & ~(v))) #define HW_AIPS_PACRP_TOG(x, v) (HW_AIPS_PACRP_WR(x, HW_AIPS_PACRP_RD(x) ^ (v))) /*@}*/ /* * Constants & macros for individual AIPS_PACRP bitfields */ /*! * @name Register AIPS_PACRP, field TP7[0] (RW) * * Determines whether the peripheral allows accesses from an untrusted master. * When this field is set and an access is attempted by an untrusted master, the * access terminates with an error response and no peripheral access initiates. * * Values: * - 0 - Accesses from an untrusted master are allowed. * - 1 - Accesses from an untrusted master are not allowed. */ /*@{*/ #define BP_AIPS_PACRP_TP7 (0U) /*!< Bit position for AIPS_PACRP_TP7. */ #define BM_AIPS_PACRP_TP7 (0x00000001U) /*!< Bit mask for AIPS_PACRP_TP7. */ #define BS_AIPS_PACRP_TP7 (1U) /*!< Bit field size in bits for AIPS_PACRP_TP7. */ /*! @brief Read current value of the AIPS_PACRP_TP7 field. */ #define BR_AIPS_PACRP_TP7(x) (BITBAND_ACCESS32(HW_AIPS_PACRP_ADDR(x), BP_AIPS_PACRP_TP7)) /*! @brief Format value for bitfield AIPS_PACRP_TP7. */ #define BF_AIPS_PACRP_TP7(v) ((uint32_t)((uint32_t)(v) << BP_AIPS_PACRP_TP7) & BM_AIPS_PACRP_TP7) /*! @brief Set the TP7 field to a new value. */ #define BW_AIPS_PACRP_TP7(x, v) (BITBAND_ACCESS32(HW_AIPS_PACRP_ADDR(x), BP_AIPS_PACRP_TP7) = (v)) /*@}*/ /*! * @name Register AIPS_PACRP, field WP7[1] (RW) * * Determines whether the peripheral allows write accesses. When this field is * set and a write access is attempted, access terminates with an error response * and no peripheral access initiates. * * Values: * - 0 - This peripheral allows write accesses. * - 1 - This peripheral is write protected. */ /*@{*/ #define BP_AIPS_PACRP_WP7 (1U) /*!< Bit position for AIPS_PACRP_WP7. */ #define BM_AIPS_PACRP_WP7 (0x00000002U) /*!< Bit mask for AIPS_PACRP_WP7. */ #define BS_AIPS_PACRP_WP7 (1U) /*!< Bit field size in bits for AIPS_PACRP_WP7. */ /*! @brief Read current value of the AIPS_PACRP_WP7 field. */ #define BR_AIPS_PACRP_WP7(x) (BITBAND_ACCESS32(HW_AIPS_PACRP_ADDR(x), BP_AIPS_PACRP_WP7)) /*! @brief Format value for bitfield AIPS_PACRP_WP7. */ #define BF_AIPS_PACRP_WP7(v) ((uint32_t)((uint32_t)(v) << BP_AIPS_PACRP_WP7) & BM_AIPS_PACRP_WP7) /*! @brief Set the WP7 field to a new value. */ #define BW_AIPS_PACRP_WP7(x, v) (BITBAND_ACCESS32(HW_AIPS_PACRP_ADDR(x), BP_AIPS_PACRP_WP7) = (v)) /*@}*/ /*! * @name Register AIPS_PACRP, field SP7[2] (RW) * * Determines whether the peripheral requires supervisor privilege level for * accesses. When this field is set, the master privilege level must indicate the * supervisor access attribute, and the MPRx[MPLn] control field for the master * must be set. If not, access terminates with an error response and no peripheral * access initiates. * * Values: * - 0 - This peripheral does not require supervisor privilege level for * accesses. * - 1 - This peripheral requires supervisor privilege level for accesses. */ /*@{*/ #define BP_AIPS_PACRP_SP7 (2U) /*!< Bit position for AIPS_PACRP_SP7. */ #define BM_AIPS_PACRP_SP7 (0x00000004U) /*!< Bit mask for AIPS_PACRP_SP7. */ #define BS_AIPS_PACRP_SP7 (1U) /*!< Bit field size in bits for AIPS_PACRP_SP7. */ /*! @brief Read current value of the AIPS_PACRP_SP7 field. */ #define BR_AIPS_PACRP_SP7(x) (BITBAND_ACCESS32(HW_AIPS_PACRP_ADDR(x), BP_AIPS_PACRP_SP7)) /*! @brief Format value for bitfield AIPS_PACRP_SP7. */ #define BF_AIPS_PACRP_SP7(v) ((uint32_t)((uint32_t)(v) << BP_AIPS_PACRP_SP7) & BM_AIPS_PACRP_SP7) /*! @brief Set the SP7 field to a new value. */ #define BW_AIPS_PACRP_SP7(x, v) (BITBAND_ACCESS32(HW_AIPS_PACRP_ADDR(x), BP_AIPS_PACRP_SP7) = (v)) /*@}*/ /*! * @name Register AIPS_PACRP, field TP6[4] (RW) * * Determines whether the peripheral allows accesses from an untrusted master. * When this field is set and an access is attempted by an untrusted master, the * access terminates with an error response and no peripheral access initiates. * * Values: * - 0 - Accesses from an untrusted master are allowed. * - 1 - Accesses from an untrusted master are not allowed. */ /*@{*/ #define BP_AIPS_PACRP_TP6 (4U) /*!< Bit position for AIPS_PACRP_TP6. */ #define BM_AIPS_PACRP_TP6 (0x00000010U) /*!< Bit mask for AIPS_PACRP_TP6. */ #define BS_AIPS_PACRP_TP6 (1U) /*!< Bit field size in bits for AIPS_PACRP_TP6. */ /*! @brief Read current value of the AIPS_PACRP_TP6 field. */ #define BR_AIPS_PACRP_TP6(x) (BITBAND_ACCESS32(HW_AIPS_PACRP_ADDR(x), BP_AIPS_PACRP_TP6)) /*! @brief Format value for bitfield AIPS_PACRP_TP6. */ #define BF_AIPS_PACRP_TP6(v) ((uint32_t)((uint32_t)(v) << BP_AIPS_PACRP_TP6) & BM_AIPS_PACRP_TP6) /*! @brief Set the TP6 field to a new value. */ #define BW_AIPS_PACRP_TP6(x, v) (BITBAND_ACCESS32(HW_AIPS_PACRP_ADDR(x), BP_AIPS_PACRP_TP6) = (v)) /*@}*/ /*! * @name Register AIPS_PACRP, field WP6[5] (RW) * * Determines whether the peripheral allows write accesses. When this field is * set and a write access is attempted, access terminates with an error response * and no peripheral access initiates. * * Values: * - 0 - This peripheral allows write accesses. * - 1 - This peripheral is write protected. */ /*@{*/ #define BP_AIPS_PACRP_WP6 (5U) /*!< Bit position for AIPS_PACRP_WP6. */ #define BM_AIPS_PACRP_WP6 (0x00000020U) /*!< Bit mask for AIPS_PACRP_WP6. */ #define BS_AIPS_PACRP_WP6 (1U) /*!< Bit field size in bits for AIPS_PACRP_WP6. */ /*! @brief Read current value of the AIPS_PACRP_WP6 field. */ #define BR_AIPS_PACRP_WP6(x) (BITBAND_ACCESS32(HW_AIPS_PACRP_ADDR(x), BP_AIPS_PACRP_WP6)) /*! @brief Format value for bitfield AIPS_PACRP_WP6. */ #define BF_AIPS_PACRP_WP6(v) ((uint32_t)((uint32_t)(v) << BP_AIPS_PACRP_WP6) & BM_AIPS_PACRP_WP6) /*! @brief Set the WP6 field to a new value. */ #define BW_AIPS_PACRP_WP6(x, v) (BITBAND_ACCESS32(HW_AIPS_PACRP_ADDR(x), BP_AIPS_PACRP_WP6) = (v)) /*@}*/ /*! * @name Register AIPS_PACRP, field SP6[6] (RW) * * Determines whether the peripheral requires supervisor privilege level for * accesses. When this field is set, the master privilege level must indicate the * supervisor access attribute, and the MPRx[MPLn] control field for the master * must be set. If not, access terminates with an error response and no peripheral * access initiates. * * Values: * - 0 - This peripheral does not require supervisor privilege level for * accesses. * - 1 - This peripheral requires supervisor privilege level for accesses. */ /*@{*/ #define BP_AIPS_PACRP_SP6 (6U) /*!< Bit position for AIPS_PACRP_SP6. */ #define BM_AIPS_PACRP_SP6 (0x00000040U) /*!< Bit mask for AIPS_PACRP_SP6. */ #define BS_AIPS_PACRP_SP6 (1U) /*!< Bit field size in bits for AIPS_PACRP_SP6. */ /*! @brief Read current value of the AIPS_PACRP_SP6 field. */ #define BR_AIPS_PACRP_SP6(x) (BITBAND_ACCESS32(HW_AIPS_PACRP_ADDR(x), BP_AIPS_PACRP_SP6)) /*! @brief Format value for bitfield AIPS_PACRP_SP6. */ #define BF_AIPS_PACRP_SP6(v) ((uint32_t)((uint32_t)(v) << BP_AIPS_PACRP_SP6) & BM_AIPS_PACRP_SP6) /*! @brief Set the SP6 field to a new value. */ #define BW_AIPS_PACRP_SP6(x, v) (BITBAND_ACCESS32(HW_AIPS_PACRP_ADDR(x), BP_AIPS_PACRP_SP6) = (v)) /*@}*/ /*! * @name Register AIPS_PACRP, field TP5[8] (RW) * * Determines whether the peripheral allows accesses from an untrusted master. * When this field is set and an access is attempted by an untrusted master, the * access terminates with an error response and no peripheral access initiates. * * Values: * - 0 - Accesses from an untrusted master are allowed. * - 1 - Accesses from an untrusted master are not allowed. */ /*@{*/ #define BP_AIPS_PACRP_TP5 (8U) /*!< Bit position for AIPS_PACRP_TP5. */ #define BM_AIPS_PACRP_TP5 (0x00000100U) /*!< Bit mask for AIPS_PACRP_TP5. */ #define BS_AIPS_PACRP_TP5 (1U) /*!< Bit field size in bits for AIPS_PACRP_TP5. */ /*! @brief Read current value of the AIPS_PACRP_TP5 field. */ #define BR_AIPS_PACRP_TP5(x) (BITBAND_ACCESS32(HW_AIPS_PACRP_ADDR(x), BP_AIPS_PACRP_TP5)) /*! @brief Format value for bitfield AIPS_PACRP_TP5. */ #define BF_AIPS_PACRP_TP5(v) ((uint32_t)((uint32_t)(v) << BP_AIPS_PACRP_TP5) & BM_AIPS_PACRP_TP5) /*! @brief Set the TP5 field to a new value. */ #define BW_AIPS_PACRP_TP5(x, v) (BITBAND_ACCESS32(HW_AIPS_PACRP_ADDR(x), BP_AIPS_PACRP_TP5) = (v)) /*@}*/ /*! * @name Register AIPS_PACRP, field WP5[9] (RW) * * Determines whether the peripheral allows write accesses. When this field is * set and a write access is attempted, access terminates with an error response * and no peripheral access initiates. * * Values: * - 0 - This peripheral allows write accesses. * - 1 - This peripheral is write protected. */ /*@{*/ #define BP_AIPS_PACRP_WP5 (9U) /*!< Bit position for AIPS_PACRP_WP5. */ #define BM_AIPS_PACRP_WP5 (0x00000200U) /*!< Bit mask for AIPS_PACRP_WP5. */ #define BS_AIPS_PACRP_WP5 (1U) /*!< Bit field size in bits for AIPS_PACRP_WP5. */ /*! @brief Read current value of the AIPS_PACRP_WP5 field. */ #define BR_AIPS_PACRP_WP5(x) (BITBAND_ACCESS32(HW_AIPS_PACRP_ADDR(x), BP_AIPS_PACRP_WP5)) /*! @brief Format value for bitfield AIPS_PACRP_WP5. */ #define BF_AIPS_PACRP_WP5(v) ((uint32_t)((uint32_t)(v) << BP_AIPS_PACRP_WP5) & BM_AIPS_PACRP_WP5) /*! @brief Set the WP5 field to a new value. */ #define BW_AIPS_PACRP_WP5(x, v) (BITBAND_ACCESS32(HW_AIPS_PACRP_ADDR(x), BP_AIPS_PACRP_WP5) = (v)) /*@}*/ /*! * @name Register AIPS_PACRP, field SP5[10] (RW) * * Determines whether the peripheral requires supervisor privilege level for * accesses. When this field is set, the master privilege level must indicate the * supervisor access attribute, and the MPRx[MPLn] control field for the master * must be set. If not, access terminates with an error response and no peripheral * access initiates. * * Values: * - 0 - This peripheral does not require supervisor privilege level for * accesses. * - 1 - This peripheral requires supervisor privilege level for accesses. */ /*@{*/ #define BP_AIPS_PACRP_SP5 (10U) /*!< Bit position for AIPS_PACRP_SP5. */ #define BM_AIPS_PACRP_SP5 (0x00000400U) /*!< Bit mask for AIPS_PACRP_SP5. */ #define BS_AIPS_PACRP_SP5 (1U) /*!< Bit field size in bits for AIPS_PACRP_SP5. */ /*! @brief Read current value of the AIPS_PACRP_SP5 field. */ #define BR_AIPS_PACRP_SP5(x) (BITBAND_ACCESS32(HW_AIPS_PACRP_ADDR(x), BP_AIPS_PACRP_SP5)) /*! @brief Format value for bitfield AIPS_PACRP_SP5. */ #define BF_AIPS_PACRP_SP5(v) ((uint32_t)((uint32_t)(v) << BP_AIPS_PACRP_SP5) & BM_AIPS_PACRP_SP5) /*! @brief Set the SP5 field to a new value. */ #define BW_AIPS_PACRP_SP5(x, v) (BITBAND_ACCESS32(HW_AIPS_PACRP_ADDR(x), BP_AIPS_PACRP_SP5) = (v)) /*@}*/ /*! * @name Register AIPS_PACRP, field TP4[12] (RW) * * Determines whether the peripheral allows accesses from an untrusted master. * When this bit is set and an access is attempted by an untrusted master, the * access terminates with an error response and no peripheral access initiates. * * Values: * - 0 - Accesses from an untrusted master are allowed. * - 1 - Accesses from an untrusted master are not allowed. */ /*@{*/ #define BP_AIPS_PACRP_TP4 (12U) /*!< Bit position for AIPS_PACRP_TP4. */ #define BM_AIPS_PACRP_TP4 (0x00001000U) /*!< Bit mask for AIPS_PACRP_TP4. */ #define BS_AIPS_PACRP_TP4 (1U) /*!< Bit field size in bits for AIPS_PACRP_TP4. */ /*! @brief Read current value of the AIPS_PACRP_TP4 field. */ #define BR_AIPS_PACRP_TP4(x) (BITBAND_ACCESS32(HW_AIPS_PACRP_ADDR(x), BP_AIPS_PACRP_TP4)) /*! @brief Format value for bitfield AIPS_PACRP_TP4. */ #define BF_AIPS_PACRP_TP4(v) ((uint32_t)((uint32_t)(v) << BP_AIPS_PACRP_TP4) & BM_AIPS_PACRP_TP4) /*! @brief Set the TP4 field to a new value. */ #define BW_AIPS_PACRP_TP4(x, v) (BITBAND_ACCESS32(HW_AIPS_PACRP_ADDR(x), BP_AIPS_PACRP_TP4) = (v)) /*@}*/ /*! * @name Register AIPS_PACRP, field WP4[13] (RW) * * Determines whether the peripheral allows write accesses. When this field is * set and a write access is attempted, access terminates with an error response * and no peripheral access initiates. * * Values: * - 0 - This peripheral allows write accesses. * - 1 - This peripheral is write protected. */ /*@{*/ #define BP_AIPS_PACRP_WP4 (13U) /*!< Bit position for AIPS_PACRP_WP4. */ #define BM_AIPS_PACRP_WP4 (0x00002000U) /*!< Bit mask for AIPS_PACRP_WP4. */ #define BS_AIPS_PACRP_WP4 (1U) /*!< Bit field size in bits for AIPS_PACRP_WP4. */ /*! @brief Read current value of the AIPS_PACRP_WP4 field. */ #define BR_AIPS_PACRP_WP4(x) (BITBAND_ACCESS32(HW_AIPS_PACRP_ADDR(x), BP_AIPS_PACRP_WP4)) /*! @brief Format value for bitfield AIPS_PACRP_WP4. */ #define BF_AIPS_PACRP_WP4(v) ((uint32_t)((uint32_t)(v) << BP_AIPS_PACRP_WP4) & BM_AIPS_PACRP_WP4) /*! @brief Set the WP4 field to a new value. */ #define BW_AIPS_PACRP_WP4(x, v) (BITBAND_ACCESS32(HW_AIPS_PACRP_ADDR(x), BP_AIPS_PACRP_WP4) = (v)) /*@}*/ /*! * @name Register AIPS_PACRP, field SP4[14] (RW) * * Determines whether the peripheral requires supervisor privilege level for * access. When this bit is set, the master privilege level must indicate the * supervisor access attribute, and the MPRx[MPLn] control bit for the master must be * set. If not, access terminates with an error response and no peripheral access * initiates. * * Values: * - 0 - This peripheral does not require supervisor privilege level for * accesses. * - 1 - This peripheral requires supervisor privilege level for accesses. */ /*@{*/ #define BP_AIPS_PACRP_SP4 (14U) /*!< Bit position for AIPS_PACRP_SP4. */ #define BM_AIPS_PACRP_SP4 (0x00004000U) /*!< Bit mask for AIPS_PACRP_SP4. */ #define BS_AIPS_PACRP_SP4 (1U) /*!< Bit field size in bits for AIPS_PACRP_SP4. */ /*! @brief Read current value of the AIPS_PACRP_SP4 field. */ #define BR_AIPS_PACRP_SP4(x) (BITBAND_ACCESS32(HW_AIPS_PACRP_ADDR(x), BP_AIPS_PACRP_SP4)) /*! @brief Format value for bitfield AIPS_PACRP_SP4. */ #define BF_AIPS_PACRP_SP4(v) ((uint32_t)((uint32_t)(v) << BP_AIPS_PACRP_SP4) & BM_AIPS_PACRP_SP4) /*! @brief Set the SP4 field to a new value. */ #define BW_AIPS_PACRP_SP4(x, v) (BITBAND_ACCESS32(HW_AIPS_PACRP_ADDR(x), BP_AIPS_PACRP_SP4) = (v)) /*@}*/ /*! * @name Register AIPS_PACRP, field TP3[16] (RW) * * Determines whether the peripheral allows accesses from an untrusted master. * When this field is set and an access is attempted by an untrusted master, the * access terminates with an error response and no peripheral access initiates. * * Values: * - 0 - Accesses from an untrusted master are allowed. * - 1 - Accesses from an untrusted master are not allowed. */ /*@{*/ #define BP_AIPS_PACRP_TP3 (16U) /*!< Bit position for AIPS_PACRP_TP3. */ #define BM_AIPS_PACRP_TP3 (0x00010000U) /*!< Bit mask for AIPS_PACRP_TP3. */ #define BS_AIPS_PACRP_TP3 (1U) /*!< Bit field size in bits for AIPS_PACRP_TP3. */ /*! @brief Read current value of the AIPS_PACRP_TP3 field. */ #define BR_AIPS_PACRP_TP3(x) (BITBAND_ACCESS32(HW_AIPS_PACRP_ADDR(x), BP_AIPS_PACRP_TP3)) /*! @brief Format value for bitfield AIPS_PACRP_TP3. */ #define BF_AIPS_PACRP_TP3(v) ((uint32_t)((uint32_t)(v) << BP_AIPS_PACRP_TP3) & BM_AIPS_PACRP_TP3) /*! @brief Set the TP3 field to a new value. */ #define BW_AIPS_PACRP_TP3(x, v) (BITBAND_ACCESS32(HW_AIPS_PACRP_ADDR(x), BP_AIPS_PACRP_TP3) = (v)) /*@}*/ /*! * @name Register AIPS_PACRP, field WP3[17] (RW) * * Determines whether the peripheral allows write accesss. When this bit is set * and a write access is attempted, access terminates with an error response and * no peripheral access initiates. * * Values: * - 0 - This peripheral allows write accesses. * - 1 - This peripheral is write protected. */ /*@{*/ #define BP_AIPS_PACRP_WP3 (17U) /*!< Bit position for AIPS_PACRP_WP3. */ #define BM_AIPS_PACRP_WP3 (0x00020000U) /*!< Bit mask for AIPS_PACRP_WP3. */ #define BS_AIPS_PACRP_WP3 (1U) /*!< Bit field size in bits for AIPS_PACRP_WP3. */ /*! @brief Read current value of the AIPS_PACRP_WP3 field. */ #define BR_AIPS_PACRP_WP3(x) (BITBAND_ACCESS32(HW_AIPS_PACRP_ADDR(x), BP_AIPS_PACRP_WP3)) /*! @brief Format value for bitfield AIPS_PACRP_WP3. */ #define BF_AIPS_PACRP_WP3(v) ((uint32_t)((uint32_t)(v) << BP_AIPS_PACRP_WP3) & BM_AIPS_PACRP_WP3) /*! @brief Set the WP3 field to a new value. */ #define BW_AIPS_PACRP_WP3(x, v) (BITBAND_ACCESS32(HW_AIPS_PACRP_ADDR(x), BP_AIPS_PACRP_WP3) = (v)) /*@}*/ /*! * @name Register AIPS_PACRP, field SP3[18] (RW) * * Determines whether the peripheral requires supervisor privilege level for * accesses. When this field is set, the master privilege level must indicate the * supervisor access attribute, and the MPRx[MPLn] control field for the master * must be set. If not, access terminates with an error response and no peripheral * access initiates. * * Values: * - 0 - This peripheral does not require supervisor privilege level for * accesses. * - 1 - This peripheral requires supervisor privilege level for accesses. */ /*@{*/ #define BP_AIPS_PACRP_SP3 (18U) /*!< Bit position for AIPS_PACRP_SP3. */ #define BM_AIPS_PACRP_SP3 (0x00040000U) /*!< Bit mask for AIPS_PACRP_SP3. */ #define BS_AIPS_PACRP_SP3 (1U) /*!< Bit field size in bits for AIPS_PACRP_SP3. */ /*! @brief Read current value of the AIPS_PACRP_SP3 field. */ #define BR_AIPS_PACRP_SP3(x) (BITBAND_ACCESS32(HW_AIPS_PACRP_ADDR(x), BP_AIPS_PACRP_SP3)) /*! @brief Format value for bitfield AIPS_PACRP_SP3. */ #define BF_AIPS_PACRP_SP3(v) ((uint32_t)((uint32_t)(v) << BP_AIPS_PACRP_SP3) & BM_AIPS_PACRP_SP3) /*! @brief Set the SP3 field to a new value. */ #define BW_AIPS_PACRP_SP3(x, v) (BITBAND_ACCESS32(HW_AIPS_PACRP_ADDR(x), BP_AIPS_PACRP_SP3) = (v)) /*@}*/ /*! * @name Register AIPS_PACRP, field TP2[20] (RW) * * Determines whether the peripheral allows accesses from an untrusted master. * When this bit is set and an access is attempted by an untrusted master, the * access terminates with an error response and no peripheral access initiates. * * Values: * - 0 - Accesses from an untrusted master are allowed. * - 1 - Accesses from an untrusted master are not allowed. */ /*@{*/ #define BP_AIPS_PACRP_TP2 (20U) /*!< Bit position for AIPS_PACRP_TP2. */ #define BM_AIPS_PACRP_TP2 (0x00100000U) /*!< Bit mask for AIPS_PACRP_TP2. */ #define BS_AIPS_PACRP_TP2 (1U) /*!< Bit field size in bits for AIPS_PACRP_TP2. */ /*! @brief Read current value of the AIPS_PACRP_TP2 field. */ #define BR_AIPS_PACRP_TP2(x) (BITBAND_ACCESS32(HW_AIPS_PACRP_ADDR(x), BP_AIPS_PACRP_TP2)) /*! @brief Format value for bitfield AIPS_PACRP_TP2. */ #define BF_AIPS_PACRP_TP2(v) ((uint32_t)((uint32_t)(v) << BP_AIPS_PACRP_TP2) & BM_AIPS_PACRP_TP2) /*! @brief Set the TP2 field to a new value. */ #define BW_AIPS_PACRP_TP2(x, v) (BITBAND_ACCESS32(HW_AIPS_PACRP_ADDR(x), BP_AIPS_PACRP_TP2) = (v)) /*@}*/ /*! * @name Register AIPS_PACRP, field WP2[21] (RW) * * Determines whether the peripheral allows write accesses. When this field is * set and a write access is attempted, access terminates with an error response * and no peripheral access initiates. * * Values: * - 0 - This peripheral allows write accesses. * - 1 - This peripheral is write protected. */ /*@{*/ #define BP_AIPS_PACRP_WP2 (21U) /*!< Bit position for AIPS_PACRP_WP2. */ #define BM_AIPS_PACRP_WP2 (0x00200000U) /*!< Bit mask for AIPS_PACRP_WP2. */ #define BS_AIPS_PACRP_WP2 (1U) /*!< Bit field size in bits for AIPS_PACRP_WP2. */ /*! @brief Read current value of the AIPS_PACRP_WP2 field. */ #define BR_AIPS_PACRP_WP2(x) (BITBAND_ACCESS32(HW_AIPS_PACRP_ADDR(x), BP_AIPS_PACRP_WP2)) /*! @brief Format value for bitfield AIPS_PACRP_WP2. */ #define BF_AIPS_PACRP_WP2(v) ((uint32_t)((uint32_t)(v) << BP_AIPS_PACRP_WP2) & BM_AIPS_PACRP_WP2) /*! @brief Set the WP2 field to a new value. */ #define BW_AIPS_PACRP_WP2(x, v) (BITBAND_ACCESS32(HW_AIPS_PACRP_ADDR(x), BP_AIPS_PACRP_WP2) = (v)) /*@}*/ /*! * @name Register AIPS_PACRP, field SP2[22] (RW) * * Determines whether the peripheral requires supervisor privilege level for * access. When this bit is set, the master privilege level must indicate the * supervisor access attribute, and the MPRx[MPLn] control bit for the master must be * set. If not, access terminates with an error response and no peripheral access * initiates. * * Values: * - 0 - This peripheral does not require supervisor privilege level for * accesses. * - 1 - This peripheral requires supervisor privilege level for accesses. */ /*@{*/ #define BP_AIPS_PACRP_SP2 (22U) /*!< Bit position for AIPS_PACRP_SP2. */ #define BM_AIPS_PACRP_SP2 (0x00400000U) /*!< Bit mask for AIPS_PACRP_SP2. */ #define BS_AIPS_PACRP_SP2 (1U) /*!< Bit field size in bits for AIPS_PACRP_SP2. */ /*! @brief Read current value of the AIPS_PACRP_SP2 field. */ #define BR_AIPS_PACRP_SP2(x) (BITBAND_ACCESS32(HW_AIPS_PACRP_ADDR(x), BP_AIPS_PACRP_SP2)) /*! @brief Format value for bitfield AIPS_PACRP_SP2. */ #define BF_AIPS_PACRP_SP2(v) ((uint32_t)((uint32_t)(v) << BP_AIPS_PACRP_SP2) & BM_AIPS_PACRP_SP2) /*! @brief Set the SP2 field to a new value. */ #define BW_AIPS_PACRP_SP2(x, v) (BITBAND_ACCESS32(HW_AIPS_PACRP_ADDR(x), BP_AIPS_PACRP_SP2) = (v)) /*@}*/ /*! * @name Register AIPS_PACRP, field TP1[24] (RW) * * Determines whether the peripheral allows accesses from an untrusted master. * When this field is set and an access is attempted by an untrusted master, the * access terminates with an error response and no peripheral access initiates. * * Values: * - 0 - Accesses from an untrusted master are allowed. * - 1 - Accesses from an untrusted master are not allowed. */ /*@{*/ #define BP_AIPS_PACRP_TP1 (24U) /*!< Bit position for AIPS_PACRP_TP1. */ #define BM_AIPS_PACRP_TP1 (0x01000000U) /*!< Bit mask for AIPS_PACRP_TP1. */ #define BS_AIPS_PACRP_TP1 (1U) /*!< Bit field size in bits for AIPS_PACRP_TP1. */ /*! @brief Read current value of the AIPS_PACRP_TP1 field. */ #define BR_AIPS_PACRP_TP1(x) (BITBAND_ACCESS32(HW_AIPS_PACRP_ADDR(x), BP_AIPS_PACRP_TP1)) /*! @brief Format value for bitfield AIPS_PACRP_TP1. */ #define BF_AIPS_PACRP_TP1(v) ((uint32_t)((uint32_t)(v) << BP_AIPS_PACRP_TP1) & BM_AIPS_PACRP_TP1) /*! @brief Set the TP1 field to a new value. */ #define BW_AIPS_PACRP_TP1(x, v) (BITBAND_ACCESS32(HW_AIPS_PACRP_ADDR(x), BP_AIPS_PACRP_TP1) = (v)) /*@}*/ /*! * @name Register AIPS_PACRP, field WP1[25] (RW) * * Determines whether the peripheral allows write accesses. When this field is * set and a write access is attempted, access terminates with an error response * and no peripheral access initiates. * * Values: * - 0 - This peripheral allows write accesses. * - 1 - This peripheral is write protected. */ /*@{*/ #define BP_AIPS_PACRP_WP1 (25U) /*!< Bit position for AIPS_PACRP_WP1. */ #define BM_AIPS_PACRP_WP1 (0x02000000U) /*!< Bit mask for AIPS_PACRP_WP1. */ #define BS_AIPS_PACRP_WP1 (1U) /*!< Bit field size in bits for AIPS_PACRP_WP1. */ /*! @brief Read current value of the AIPS_PACRP_WP1 field. */ #define BR_AIPS_PACRP_WP1(x) (BITBAND_ACCESS32(HW_AIPS_PACRP_ADDR(x), BP_AIPS_PACRP_WP1)) /*! @brief Format value for bitfield AIPS_PACRP_WP1. */ #define BF_AIPS_PACRP_WP1(v) ((uint32_t)((uint32_t)(v) << BP_AIPS_PACRP_WP1) & BM_AIPS_PACRP_WP1) /*! @brief Set the WP1 field to a new value. */ #define BW_AIPS_PACRP_WP1(x, v) (BITBAND_ACCESS32(HW_AIPS_PACRP_ADDR(x), BP_AIPS_PACRP_WP1) = (v)) /*@}*/ /*! * @name Register AIPS_PACRP, field SP1[26] (RW) * * Determines whether the peripheral requires supervisor privilege level for * access. When this field is set, the master privilege level must indicate the * supervisor access attribute, and the MPRx[MPLn] control field for the master must * be set. If not, access terminates with an error response and no peripheral * access initiates. * * Values: * - 0 - This peripheral does not require supervisor privilege level for * accesses. * - 1 - This peripheral requires supervisor privilege level for accesses. */ /*@{*/ #define BP_AIPS_PACRP_SP1 (26U) /*!< Bit position for AIPS_PACRP_SP1. */ #define BM_AIPS_PACRP_SP1 (0x04000000U) /*!< Bit mask for AIPS_PACRP_SP1. */ #define BS_AIPS_PACRP_SP1 (1U) /*!< Bit field size in bits for AIPS_PACRP_SP1. */ /*! @brief Read current value of the AIPS_PACRP_SP1 field. */ #define BR_AIPS_PACRP_SP1(x) (BITBAND_ACCESS32(HW_AIPS_PACRP_ADDR(x), BP_AIPS_PACRP_SP1)) /*! @brief Format value for bitfield AIPS_PACRP_SP1. */ #define BF_AIPS_PACRP_SP1(v) ((uint32_t)((uint32_t)(v) << BP_AIPS_PACRP_SP1) & BM_AIPS_PACRP_SP1) /*! @brief Set the SP1 field to a new value. */ #define BW_AIPS_PACRP_SP1(x, v) (BITBAND_ACCESS32(HW_AIPS_PACRP_ADDR(x), BP_AIPS_PACRP_SP1) = (v)) /*@}*/ /*! * @name Register AIPS_PACRP, field TP0[28] (RW) * * Determines whether the peripheral allows accesses from an untrusted master. * When this bit is set and an access is attempted by an untrusted master, the * access terminates with an error response and no peripheral access initiates. * * Values: * - 0 - Accesses from an untrusted master are allowed. * - 1 - Accesses from an untrusted master are not allowed. */ /*@{*/ #define BP_AIPS_PACRP_TP0 (28U) /*!< Bit position for AIPS_PACRP_TP0. */ #define BM_AIPS_PACRP_TP0 (0x10000000U) /*!< Bit mask for AIPS_PACRP_TP0. */ #define BS_AIPS_PACRP_TP0 (1U) /*!< Bit field size in bits for AIPS_PACRP_TP0. */ /*! @brief Read current value of the AIPS_PACRP_TP0 field. */ #define BR_AIPS_PACRP_TP0(x) (BITBAND_ACCESS32(HW_AIPS_PACRP_ADDR(x), BP_AIPS_PACRP_TP0)) /*! @brief Format value for bitfield AIPS_PACRP_TP0. */ #define BF_AIPS_PACRP_TP0(v) ((uint32_t)((uint32_t)(v) << BP_AIPS_PACRP_TP0) & BM_AIPS_PACRP_TP0) /*! @brief Set the TP0 field to a new value. */ #define BW_AIPS_PACRP_TP0(x, v) (BITBAND_ACCESS32(HW_AIPS_PACRP_ADDR(x), BP_AIPS_PACRP_TP0) = (v)) /*@}*/ /*! * @name Register AIPS_PACRP, field WP0[29] (RW) * * Determines whether the peripheral allows write accesses. When this field is * set and a write access is attempted, access terminates with an error response * and no peripheral access initiates. * * Values: * - 0 - This peripheral allows write accesses. * - 1 - This peripheral is write protected. */ /*@{*/ #define BP_AIPS_PACRP_WP0 (29U) /*!< Bit position for AIPS_PACRP_WP0. */ #define BM_AIPS_PACRP_WP0 (0x20000000U) /*!< Bit mask for AIPS_PACRP_WP0. */ #define BS_AIPS_PACRP_WP0 (1U) /*!< Bit field size in bits for AIPS_PACRP_WP0. */ /*! @brief Read current value of the AIPS_PACRP_WP0 field. */ #define BR_AIPS_PACRP_WP0(x) (BITBAND_ACCESS32(HW_AIPS_PACRP_ADDR(x), BP_AIPS_PACRP_WP0)) /*! @brief Format value for bitfield AIPS_PACRP_WP0. */ #define BF_AIPS_PACRP_WP0(v) ((uint32_t)((uint32_t)(v) << BP_AIPS_PACRP_WP0) & BM_AIPS_PACRP_WP0) /*! @brief Set the WP0 field to a new value. */ #define BW_AIPS_PACRP_WP0(x, v) (BITBAND_ACCESS32(HW_AIPS_PACRP_ADDR(x), BP_AIPS_PACRP_WP0) = (v)) /*@}*/ /*! * @name Register AIPS_PACRP, field SP0[30] (RW) * * Determines whether the peripheral requires supervisor privilege level for * accesses. When this field is set, the master privilege level must indicate the * supervisor access attribute, and the MPRx[MPLn] control field for the master * must be set. If not, access terminates with an error response and no peripheral * access initiates. * * Values: * - 0 - This peripheral does not require supervisor privilege level for * accesses. * - 1 - This peripheral requires supervisor privilege level for accesses. */ /*@{*/ #define BP_AIPS_PACRP_SP0 (30U) /*!< Bit position for AIPS_PACRP_SP0. */ #define BM_AIPS_PACRP_SP0 (0x40000000U) /*!< Bit mask for AIPS_PACRP_SP0. */ #define BS_AIPS_PACRP_SP0 (1U) /*!< Bit field size in bits for AIPS_PACRP_SP0. */ /*! @brief Read current value of the AIPS_PACRP_SP0 field. */ #define BR_AIPS_PACRP_SP0(x) (BITBAND_ACCESS32(HW_AIPS_PACRP_ADDR(x), BP_AIPS_PACRP_SP0)) /*! @brief Format value for bitfield AIPS_PACRP_SP0. */ #define BF_AIPS_PACRP_SP0(v) ((uint32_t)((uint32_t)(v) << BP_AIPS_PACRP_SP0) & BM_AIPS_PACRP_SP0) /*! @brief Set the SP0 field to a new value. */ #define BW_AIPS_PACRP_SP0(x, v) (BITBAND_ACCESS32(HW_AIPS_PACRP_ADDR(x), BP_AIPS_PACRP_SP0) = (v)) /*@}*/ /******************************************************************************* * HW_AIPS_PACRU - Peripheral Access Control Register ******************************************************************************/ /*! * @brief HW_AIPS_PACRU - Peripheral Access Control Register (RW) * * Reset value: 0x44000000U * * PACRU defines the access levels for the two global spaces. */ typedef union _hw_aips_pacru { uint32_t U; struct _hw_aips_pacru_bitfields { uint32_t RESERVED0 : 24; /*!< [23:0] */ uint32_t TP1 : 1; /*!< [24] Trusted Protect */ uint32_t WP1 : 1; /*!< [25] Write Protect */ uint32_t SP1 : 1; /*!< [26] Supervisor Protect */ uint32_t RESERVED1 : 1; /*!< [27] */ uint32_t TP0 : 1; /*!< [28] Trusted Protect */ uint32_t WP0 : 1; /*!< [29] Write Protect */ uint32_t SP0 : 1; /*!< [30] Supervisor Protect */ uint32_t RESERVED2 : 1; /*!< [31] */ } B; } hw_aips_pacru_t; /*! * @name Constants and macros for entire AIPS_PACRU register */ /*@{*/ #define HW_AIPS_PACRU_ADDR(x) ((x) + 0x80U) #define HW_AIPS_PACRU(x) (*(__IO hw_aips_pacru_t *) HW_AIPS_PACRU_ADDR(x)) #define HW_AIPS_PACRU_RD(x) (HW_AIPS_PACRU(x).U) #define HW_AIPS_PACRU_WR(x, v) (HW_AIPS_PACRU(x).U = (v)) #define HW_AIPS_PACRU_SET(x, v) (HW_AIPS_PACRU_WR(x, HW_AIPS_PACRU_RD(x) | (v))) #define HW_AIPS_PACRU_CLR(x, v) (HW_AIPS_PACRU_WR(x, HW_AIPS_PACRU_RD(x) & ~(v))) #define HW_AIPS_PACRU_TOG(x, v) (HW_AIPS_PACRU_WR(x, HW_AIPS_PACRU_RD(x) ^ (v))) /*@}*/ /* * Constants & macros for individual AIPS_PACRU bitfields */ /*! * @name Register AIPS_PACRU, field TP1[24] (RW) * * Determines whether the peripheral allows accesses from an untrusted master. * When this field is set and an access is attempted by an untrusted master, the * access terminates with an error response and no peripheral access initiates. * * Values: * - 0 - Accesses from an untrusted master are allowed. * - 1 - Accesses from an untrusted master are not allowed. */ /*@{*/ #define BP_AIPS_PACRU_TP1 (24U) /*!< Bit position for AIPS_PACRU_TP1. */ #define BM_AIPS_PACRU_TP1 (0x01000000U) /*!< Bit mask for AIPS_PACRU_TP1. */ #define BS_AIPS_PACRU_TP1 (1U) /*!< Bit field size in bits for AIPS_PACRU_TP1. */ /*! @brief Read current value of the AIPS_PACRU_TP1 field. */ #define BR_AIPS_PACRU_TP1(x) (BITBAND_ACCESS32(HW_AIPS_PACRU_ADDR(x), BP_AIPS_PACRU_TP1)) /*! @brief Format value for bitfield AIPS_PACRU_TP1. */ #define BF_AIPS_PACRU_TP1(v) ((uint32_t)((uint32_t)(v) << BP_AIPS_PACRU_TP1) & BM_AIPS_PACRU_TP1) /*! @brief Set the TP1 field to a new value. */ #define BW_AIPS_PACRU_TP1(x, v) (BITBAND_ACCESS32(HW_AIPS_PACRU_ADDR(x), BP_AIPS_PACRU_TP1) = (v)) /*@}*/ /*! * @name Register AIPS_PACRU, field WP1[25] (RW) * * Determines whether the peripheral allows write accesss. When this bit is set * and a write access is attempted, access terminates with an error response and * no peripheral access initiates. * * Values: * - 0 - This peripheral allows write accesses. * - 1 - This peripheral is write protected. */ /*@{*/ #define BP_AIPS_PACRU_WP1 (25U) /*!< Bit position for AIPS_PACRU_WP1. */ #define BM_AIPS_PACRU_WP1 (0x02000000U) /*!< Bit mask for AIPS_PACRU_WP1. */ #define BS_AIPS_PACRU_WP1 (1U) /*!< Bit field size in bits for AIPS_PACRU_WP1. */ /*! @brief Read current value of the AIPS_PACRU_WP1 field. */ #define BR_AIPS_PACRU_WP1(x) (BITBAND_ACCESS32(HW_AIPS_PACRU_ADDR(x), BP_AIPS_PACRU_WP1)) /*! @brief Format value for bitfield AIPS_PACRU_WP1. */ #define BF_AIPS_PACRU_WP1(v) ((uint32_t)((uint32_t)(v) << BP_AIPS_PACRU_WP1) & BM_AIPS_PACRU_WP1) /*! @brief Set the WP1 field to a new value. */ #define BW_AIPS_PACRU_WP1(x, v) (BITBAND_ACCESS32(HW_AIPS_PACRU_ADDR(x), BP_AIPS_PACRU_WP1) = (v)) /*@}*/ /*! * @name Register AIPS_PACRU, field SP1[26] (RW) * * Determines whether the peripheral requires supervisor privilege level for * accesses. When this field is set, the master privilege level must indicate the * supervisor access attribute, and the MPRx[MPLn] control field for the master * must be set. If not, access terminates with an error response and no peripheral * access initiates. * * Values: * - 0 - This peripheral does not require supervisor privilege level for * accesses. * - 1 - This peripheral requires supervisor privilege level for accesses. */ /*@{*/ #define BP_AIPS_PACRU_SP1 (26U) /*!< Bit position for AIPS_PACRU_SP1. */ #define BM_AIPS_PACRU_SP1 (0x04000000U) /*!< Bit mask for AIPS_PACRU_SP1. */ #define BS_AIPS_PACRU_SP1 (1U) /*!< Bit field size in bits for AIPS_PACRU_SP1. */ /*! @brief Read current value of the AIPS_PACRU_SP1 field. */ #define BR_AIPS_PACRU_SP1(x) (BITBAND_ACCESS32(HW_AIPS_PACRU_ADDR(x), BP_AIPS_PACRU_SP1)) /*! @brief Format value for bitfield AIPS_PACRU_SP1. */ #define BF_AIPS_PACRU_SP1(v) ((uint32_t)((uint32_t)(v) << BP_AIPS_PACRU_SP1) & BM_AIPS_PACRU_SP1) /*! @brief Set the SP1 field to a new value. */ #define BW_AIPS_PACRU_SP1(x, v) (BITBAND_ACCESS32(HW_AIPS_PACRU_ADDR(x), BP_AIPS_PACRU_SP1) = (v)) /*@}*/ /*! * @name Register AIPS_PACRU, field TP0[28] (RW) * * Determines whether the peripheral allows accesses from an untrusted master. * When this field is set and an access is attempted by an untrusted master, the * access terminates with an error response and no peripheral access initiates. * * Values: * - 0 - Accesses from an untrusted master are allowed. * - 1 - Accesses from an untrusted master are not allowed. */ /*@{*/ #define BP_AIPS_PACRU_TP0 (28U) /*!< Bit position for AIPS_PACRU_TP0. */ #define BM_AIPS_PACRU_TP0 (0x10000000U) /*!< Bit mask for AIPS_PACRU_TP0. */ #define BS_AIPS_PACRU_TP0 (1U) /*!< Bit field size in bits for AIPS_PACRU_TP0. */ /*! @brief Read current value of the AIPS_PACRU_TP0 field. */ #define BR_AIPS_PACRU_TP0(x) (BITBAND_ACCESS32(HW_AIPS_PACRU_ADDR(x), BP_AIPS_PACRU_TP0)) /*! @brief Format value for bitfield AIPS_PACRU_TP0. */ #define BF_AIPS_PACRU_TP0(v) ((uint32_t)((uint32_t)(v) << BP_AIPS_PACRU_TP0) & BM_AIPS_PACRU_TP0) /*! @brief Set the TP0 field to a new value. */ #define BW_AIPS_PACRU_TP0(x, v) (BITBAND_ACCESS32(HW_AIPS_PACRU_ADDR(x), BP_AIPS_PACRU_TP0) = (v)) /*@}*/ /*! * @name Register AIPS_PACRU, field WP0[29] (RW) * * Determines whether the peripheral allows write accesses. When this field is * set and a write access is attempted, access terminates with an error response * and no peripheral access initiates. * * Values: * - 0 - This peripheral allows write accesses. * - 1 - This peripheral is write protected. */ /*@{*/ #define BP_AIPS_PACRU_WP0 (29U) /*!< Bit position for AIPS_PACRU_WP0. */ #define BM_AIPS_PACRU_WP0 (0x20000000U) /*!< Bit mask for AIPS_PACRU_WP0. */ #define BS_AIPS_PACRU_WP0 (1U) /*!< Bit field size in bits for AIPS_PACRU_WP0. */ /*! @brief Read current value of the AIPS_PACRU_WP0 field. */ #define BR_AIPS_PACRU_WP0(x) (BITBAND_ACCESS32(HW_AIPS_PACRU_ADDR(x), BP_AIPS_PACRU_WP0)) /*! @brief Format value for bitfield AIPS_PACRU_WP0. */ #define BF_AIPS_PACRU_WP0(v) ((uint32_t)((uint32_t)(v) << BP_AIPS_PACRU_WP0) & BM_AIPS_PACRU_WP0) /*! @brief Set the WP0 field to a new value. */ #define BW_AIPS_PACRU_WP0(x, v) (BITBAND_ACCESS32(HW_AIPS_PACRU_ADDR(x), BP_AIPS_PACRU_WP0) = (v)) /*@}*/ /*! * @name Register AIPS_PACRU, field SP0[30] (RW) * * Determines whether the peripheral requires supervisor privilege level for * access. When this bit is set, the master privilege level must indicate the * supervisor access attribute, and the MPRx[MPLn] control bit for the master must be * set. If not, access terminates with an error response and no peripheral access * initiates. * * Values: * - 0 - This peripheral does not require supervisor privilege level for * accesses. * - 1 - This peripheral requires supervisor privilege level for accesses. */ /*@{*/ #define BP_AIPS_PACRU_SP0 (30U) /*!< Bit position for AIPS_PACRU_SP0. */ #define BM_AIPS_PACRU_SP0 (0x40000000U) /*!< Bit mask for AIPS_PACRU_SP0. */ #define BS_AIPS_PACRU_SP0 (1U) /*!< Bit field size in bits for AIPS_PACRU_SP0. */ /*! @brief Read current value of the AIPS_PACRU_SP0 field. */ #define BR_AIPS_PACRU_SP0(x) (BITBAND_ACCESS32(HW_AIPS_PACRU_ADDR(x), BP_AIPS_PACRU_SP0)) /*! @brief Format value for bitfield AIPS_PACRU_SP0. */ #define BF_AIPS_PACRU_SP0(v) ((uint32_t)((uint32_t)(v) << BP_AIPS_PACRU_SP0) & BM_AIPS_PACRU_SP0) /*! @brief Set the SP0 field to a new value. */ #define BW_AIPS_PACRU_SP0(x, v) (BITBAND_ACCESS32(HW_AIPS_PACRU_ADDR(x), BP_AIPS_PACRU_SP0) = (v)) /*@}*/ /******************************************************************************* * hw_aips_t - module struct ******************************************************************************/ /*! * @brief All AIPS module registers. */ #pragma pack(1) typedef struct _hw_aips { __IO hw_aips_mpra_t MPRA; /*!< [0x0] Master Privilege Register A */ uint8_t _reserved0[28]; __IO hw_aips_pacra_t PACRA; /*!< [0x20] Peripheral Access Control Register */ __IO hw_aips_pacrb_t PACRB; /*!< [0x24] Peripheral Access Control Register */ __IO hw_aips_pacrc_t PACRC; /*!< [0x28] Peripheral Access Control Register */ __IO hw_aips_pacrd_t PACRD; /*!< [0x2C] Peripheral Access Control Register */ uint8_t _reserved1[16]; __IO hw_aips_pacre_t PACRE; /*!< [0x40] Peripheral Access Control Register */ __IO hw_aips_pacrf_t PACRF; /*!< [0x44] Peripheral Access Control Register */ __IO hw_aips_pacrg_t PACRG; /*!< [0x48] Peripheral Access Control Register */ __IO hw_aips_pacrh_t PACRH; /*!< [0x4C] Peripheral Access Control Register */ __IO hw_aips_pacri_t PACRI; /*!< [0x50] Peripheral Access Control Register */ __IO hw_aips_pacrj_t PACRJ; /*!< [0x54] Peripheral Access Control Register */ __IO hw_aips_pacrk_t PACRK; /*!< [0x58] Peripheral Access Control Register */ __IO hw_aips_pacrl_t PACRL; /*!< [0x5C] Peripheral Access Control Register */ __IO hw_aips_pacrm_t PACRM; /*!< [0x60] Peripheral Access Control Register */ __IO hw_aips_pacrn_t PACRN; /*!< [0x64] Peripheral Access Control Register */ __IO hw_aips_pacro_t PACRO; /*!< [0x68] Peripheral Access Control Register */ __IO hw_aips_pacrp_t PACRP; /*!< [0x6C] Peripheral Access Control Register */ uint8_t _reserved2[16]; __IO hw_aips_pacru_t PACRU; /*!< [0x80] Peripheral Access Control Register */ } hw_aips_t; #pragma pack() /*! @brief Macro to access all AIPS registers. */ /*! @param x AIPS module instance base address. */ /*! @return Reference (not a pointer) to the registers struct. To get a pointer to the struct, * use the '&' operator, like &HW_AIPS(AIPS0_BASE). */ #define HW_AIPS(x) (*(hw_aips_t *)(x)) #endif /* __HW_AIPS_REGISTERS_H__ */ /* EOF */ ================================================ FILE: Zelig/mbed/TARGET_K64F/TARGET_Freescale/TARGET_KPSDK_MCUS/TARGET_MCU_K64F/device/device/MK64F12/MK64F12_axbs.h ================================================ /* ** ################################################################### ** Compilers: Keil ARM C/C++ Compiler ** Freescale C/C++ for Embedded ARM ** GNU C Compiler ** IAR ANSI C/C++ Compiler for ARM ** ** Reference manual: K64P144M120SF5RM, Rev.2, January 2014 ** Version: rev. 2.5, 2014-02-10 ** Build: b140604 ** ** Abstract: ** Extension to the CMSIS register access layer header. ** ** Copyright (c) 2014 Freescale Semiconductor, Inc. ** All rights reserved. ** ** Redistribution and use in source and binary forms, with or without modification, ** are permitted provided that the following conditions are met: ** ** o Redistributions of source code must retain the above copyright notice, this list ** of conditions and the following disclaimer. ** ** o Redistributions in binary form must reproduce the above copyright notice, this ** list of conditions and the following disclaimer in the documentation and/or ** other materials provided with the distribution. ** ** o Neither the name of Freescale Semiconductor, Inc. nor the names of its ** contributors may be used to endorse or promote products derived from this ** software without specific prior written permission. ** ** THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ** ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED ** WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE ** DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT 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. ** ** http: www.freescale.com ** mail: support@freescale.com ** ** Revisions: ** - rev. 1.0 (2013-08-12) ** Initial version. ** - rev. 2.0 (2013-10-29) ** Register accessor macros added to the memory map. ** Symbols for Processor Expert memory map compatibility added to the memory map. ** Startup file for gcc has been updated according to CMSIS 3.2. ** System initialization updated. ** MCG - registers updated. ** PORTA, PORTB, PORTC, PORTE - registers for digital filter removed. ** - rev. 2.1 (2013-10-30) ** Definition of BITBAND macros updated to support peripherals with 32-bit acces disabled. ** - rev. 2.2 (2013-12-09) ** DMA - EARS register removed. ** AIPS0, AIPS1 - MPRA register updated. ** - rev. 2.3 (2014-01-24) ** Update according to reference manual rev. 2 ** ENET, MCG, MCM, SIM, USB - registers updated ** - rev. 2.4 (2014-02-10) ** The declaration of clock configurations has been moved to separate header file system_MK64F12.h ** Update of SystemInit() and SystemCoreClockUpdate() functions. ** - rev. 2.5 (2014-02-10) ** The declaration of clock configurations has been moved to separate header file system_MK64F12.h ** Update of SystemInit() and SystemCoreClockUpdate() functions. ** Module access macro module_BASES replaced by module_BASE_PTRS. ** ** ################################################################### */ /* * WARNING! DO NOT EDIT THIS FILE DIRECTLY! * * This file was generated automatically and any changes may be lost. */ #ifndef __HW_AXBS_REGISTERS_H__ #define __HW_AXBS_REGISTERS_H__ #include "MK64F12.h" #include "fsl_bitaccess.h" /* * MK64F12 AXBS * * Crossbar switch * * Registers defined in this header file: * - HW_AXBS_PRSn - Priority Registers Slave * - HW_AXBS_CRSn - Control Register * - HW_AXBS_MGPCR0 - Master General Purpose Control Register * - HW_AXBS_MGPCR1 - Master General Purpose Control Register * - HW_AXBS_MGPCR2 - Master General Purpose Control Register * - HW_AXBS_MGPCR3 - Master General Purpose Control Register * - HW_AXBS_MGPCR4 - Master General Purpose Control Register * - HW_AXBS_MGPCR5 - Master General Purpose Control Register * * - hw_axbs_t - Struct containing all module registers. */ #define HW_AXBS_INSTANCE_COUNT (1U) /*!< Number of instances of the AXBS module. */ /******************************************************************************* * HW_AXBS_PRSn - Priority Registers Slave ******************************************************************************/ /*! * @brief HW_AXBS_PRSn - Priority Registers Slave (RW) * * Reset value: 0x00543210U * * The priority registers (PRSn) set the priority of each master port on a per * slave port basis and reside in each slave port. The priority register can be * accessed only with 32-bit accesses. After the CRSn[RO] bit is set, the PRSn * register can only be read; attempts to write to it have no effect on PRSn and * result in a bus-error response to the master initiating the write. Two available * masters must not be programmed with the same priority level. Attempts to * program two or more masters with the same priority level result in a bus-error * response and the PRSn is not updated. Valid values for the Mn priority fields * depend on which masters are available on the chip. This information can be found in * the chip-specific information for the crossbar. If the chip contains less * than five masters, values 0 to 3 are valid. Writing other values will result in * an error. If the chip contains five or more masters, valid values are 0 to n-1, * where n is the number of masters attached to the AXBS module. Other values * will result in an error. */ typedef union _hw_axbs_prsn { uint32_t U; struct _hw_axbs_prsn_bitfields { uint32_t M0 : 3; /*!< [2:0] Master 0 Priority. Sets the arbitration * priority for this port on the associated slave port. */ uint32_t RESERVED0 : 1; /*!< [3] */ uint32_t M1 : 3; /*!< [6:4] Master 1 Priority. Sets the arbitration * priority for this port on the associated slave port. */ uint32_t RESERVED1 : 1; /*!< [7] */ uint32_t M2 : 3; /*!< [10:8] Master 2 Priority. Sets the arbitration * priority for this port on the associated slave port. */ uint32_t RESERVED2 : 1; /*!< [11] */ uint32_t M3 : 3; /*!< [14:12] Master 3 Priority. Sets the arbitration * priority for this port on the associated slave port. */ uint32_t RESERVED3 : 1; /*!< [15] */ uint32_t M4 : 3; /*!< [18:16] Master 4 Priority. Sets the arbitration * priority for this port on the associated slave port. */ uint32_t RESERVED4 : 1; /*!< [19] */ uint32_t M5 : 3; /*!< [22:20] Master 5 Priority. Sets the arbitration * priority for this port on the associated slave port. */ uint32_t RESERVED5 : 9; /*!< [31:23] */ } B; } hw_axbs_prsn_t; /*! * @name Constants and macros for entire AXBS_PRSn register */ /*@{*/ #define HW_AXBS_PRSn_COUNT (5U) #define HW_AXBS_PRSn_ADDR(x, n) ((x) + 0x0U + (0x100U * (n))) #define HW_AXBS_PRSn(x, n) (*(__IO hw_axbs_prsn_t *) HW_AXBS_PRSn_ADDR(x, n)) #define HW_AXBS_PRSn_RD(x, n) (HW_AXBS_PRSn(x, n).U) #define HW_AXBS_PRSn_WR(x, n, v) (HW_AXBS_PRSn(x, n).U = (v)) #define HW_AXBS_PRSn_SET(x, n, v) (HW_AXBS_PRSn_WR(x, n, HW_AXBS_PRSn_RD(x, n) | (v))) #define HW_AXBS_PRSn_CLR(x, n, v) (HW_AXBS_PRSn_WR(x, n, HW_AXBS_PRSn_RD(x, n) & ~(v))) #define HW_AXBS_PRSn_TOG(x, n, v) (HW_AXBS_PRSn_WR(x, n, HW_AXBS_PRSn_RD(x, n) ^ (v))) /*@}*/ /* * Constants & macros for individual AXBS_PRSn bitfields */ /*! * @name Register AXBS_PRSn, field M0[2:0] (RW) * * Values: * - 000 - This master has level 1, or highest, priority when accessing the * slave port. * - 001 - This master has level 2 priority when accessing the slave port. * - 010 - This master has level 3 priority when accessing the slave port. * - 011 - This master has level 4 priority when accessing the slave port. * - 100 - This master has level 5 priority when accessing the slave port. * - 101 - This master has level 6 priority when accessing the slave port. * - 110 - This master has level 7 priority when accessing the slave port. * - 111 - This master has level 8, or lowest, priority when accessing the slave * port. */ /*@{*/ #define BP_AXBS_PRSn_M0 (0U) /*!< Bit position for AXBS_PRSn_M0. */ #define BM_AXBS_PRSn_M0 (0x00000007U) /*!< Bit mask for AXBS_PRSn_M0. */ #define BS_AXBS_PRSn_M0 (3U) /*!< Bit field size in bits for AXBS_PRSn_M0. */ /*! @brief Read current value of the AXBS_PRSn_M0 field. */ #define BR_AXBS_PRSn_M0(x, n) (HW_AXBS_PRSn(x, n).B.M0) /*! @brief Format value for bitfield AXBS_PRSn_M0. */ #define BF_AXBS_PRSn_M0(v) ((uint32_t)((uint32_t)(v) << BP_AXBS_PRSn_M0) & BM_AXBS_PRSn_M0) /*! @brief Set the M0 field to a new value. */ #define BW_AXBS_PRSn_M0(x, n, v) (HW_AXBS_PRSn_WR(x, n, (HW_AXBS_PRSn_RD(x, n) & ~BM_AXBS_PRSn_M0) | BF_AXBS_PRSn_M0(v))) /*@}*/ /*! * @name Register AXBS_PRSn, field M1[6:4] (RW) * * Values: * - 000 - This master has level 1, or highest, priority when accessing the * slave port. * - 001 - This master has level 2 priority when accessing the slave port. * - 010 - This master has level 3 priority when accessing the slave port. * - 011 - This master has level 4 priority when accessing the slave port. * - 100 - This master has level 5 priority when accessing the slave port. * - 101 - This master has level 6 priority when accessing the slave port. * - 110 - This master has level 7 priority when accessing the slave port. * - 111 - This master has level 8, or lowest, priority when accessing the slave * port. */ /*@{*/ #define BP_AXBS_PRSn_M1 (4U) /*!< Bit position for AXBS_PRSn_M1. */ #define BM_AXBS_PRSn_M1 (0x00000070U) /*!< Bit mask for AXBS_PRSn_M1. */ #define BS_AXBS_PRSn_M1 (3U) /*!< Bit field size in bits for AXBS_PRSn_M1. */ /*! @brief Read current value of the AXBS_PRSn_M1 field. */ #define BR_AXBS_PRSn_M1(x, n) (HW_AXBS_PRSn(x, n).B.M1) /*! @brief Format value for bitfield AXBS_PRSn_M1. */ #define BF_AXBS_PRSn_M1(v) ((uint32_t)((uint32_t)(v) << BP_AXBS_PRSn_M1) & BM_AXBS_PRSn_M1) /*! @brief Set the M1 field to a new value. */ #define BW_AXBS_PRSn_M1(x, n, v) (HW_AXBS_PRSn_WR(x, n, (HW_AXBS_PRSn_RD(x, n) & ~BM_AXBS_PRSn_M1) | BF_AXBS_PRSn_M1(v))) /*@}*/ /*! * @name Register AXBS_PRSn, field M2[10:8] (RW) * * Values: * - 000 - This master has level 1, or highest, priority when accessing the * slave port. * - 001 - This master has level 2 priority when accessing the slave port. * - 010 - This master has level 3 priority when accessing the slave port. * - 011 - This master has level 4 priority when accessing the slave port. * - 100 - This master has level 5 priority when accessing the slave port. * - 101 - This master has level 6 priority when accessing the slave port. * - 110 - This master has level 7 priority when accessing the slave port. * - 111 - This master has level 8, or lowest, priority when accessing the slave * port. */ /*@{*/ #define BP_AXBS_PRSn_M2 (8U) /*!< Bit position for AXBS_PRSn_M2. */ #define BM_AXBS_PRSn_M2 (0x00000700U) /*!< Bit mask for AXBS_PRSn_M2. */ #define BS_AXBS_PRSn_M2 (3U) /*!< Bit field size in bits for AXBS_PRSn_M2. */ /*! @brief Read current value of the AXBS_PRSn_M2 field. */ #define BR_AXBS_PRSn_M2(x, n) (HW_AXBS_PRSn(x, n).B.M2) /*! @brief Format value for bitfield AXBS_PRSn_M2. */ #define BF_AXBS_PRSn_M2(v) ((uint32_t)((uint32_t)(v) << BP_AXBS_PRSn_M2) & BM_AXBS_PRSn_M2) /*! @brief Set the M2 field to a new value. */ #define BW_AXBS_PRSn_M2(x, n, v) (HW_AXBS_PRSn_WR(x, n, (HW_AXBS_PRSn_RD(x, n) & ~BM_AXBS_PRSn_M2) | BF_AXBS_PRSn_M2(v))) /*@}*/ /*! * @name Register AXBS_PRSn, field M3[14:12] (RW) * * Values: * - 000 - This master has level 1, or highest, priority when accessing the * slave port. * - 001 - This master has level 2 priority when accessing the slave port. * - 010 - This master has level 3 priority when accessing the slave port. * - 011 - This master has level 4 priority when accessing the slave port. * - 100 - This master has level 5 priority when accessing the slave port. * - 101 - This master has level 6 priority when accessing the slave port. * - 110 - This master has level 7 priority when accessing the slave port. * - 111 - This master has level 8, or lowest, priority when accessing the slave * port. */ /*@{*/ #define BP_AXBS_PRSn_M3 (12U) /*!< Bit position for AXBS_PRSn_M3. */ #define BM_AXBS_PRSn_M3 (0x00007000U) /*!< Bit mask for AXBS_PRSn_M3. */ #define BS_AXBS_PRSn_M3 (3U) /*!< Bit field size in bits for AXBS_PRSn_M3. */ /*! @brief Read current value of the AXBS_PRSn_M3 field. */ #define BR_AXBS_PRSn_M3(x, n) (HW_AXBS_PRSn(x, n).B.M3) /*! @brief Format value for bitfield AXBS_PRSn_M3. */ #define BF_AXBS_PRSn_M3(v) ((uint32_t)((uint32_t)(v) << BP_AXBS_PRSn_M3) & BM_AXBS_PRSn_M3) /*! @brief Set the M3 field to a new value. */ #define BW_AXBS_PRSn_M3(x, n, v) (HW_AXBS_PRSn_WR(x, n, (HW_AXBS_PRSn_RD(x, n) & ~BM_AXBS_PRSn_M3) | BF_AXBS_PRSn_M3(v))) /*@}*/ /*! * @name Register AXBS_PRSn, field M4[18:16] (RW) * * Values: * - 000 - This master has level 1, or highest, priority when accessing the * slave port. * - 001 - This master has level 2 priority when accessing the slave port. * - 010 - This master has level 3 priority when accessing the slave port. * - 011 - This master has level 4 priority when accessing the slave port. * - 100 - This master has level 5 priority when accessing the slave port. * - 101 - This master has level 6 priority when accessing the slave port. * - 110 - This master has level 7 priority when accessing the slave port. * - 111 - This master has level 8, or lowest, priority when accessing the slave * port. */ /*@{*/ #define BP_AXBS_PRSn_M4 (16U) /*!< Bit position for AXBS_PRSn_M4. */ #define BM_AXBS_PRSn_M4 (0x00070000U) /*!< Bit mask for AXBS_PRSn_M4. */ #define BS_AXBS_PRSn_M4 (3U) /*!< Bit field size in bits for AXBS_PRSn_M4. */ /*! @brief Read current value of the AXBS_PRSn_M4 field. */ #define BR_AXBS_PRSn_M4(x, n) (HW_AXBS_PRSn(x, n).B.M4) /*! @brief Format value for bitfield AXBS_PRSn_M4. */ #define BF_AXBS_PRSn_M4(v) ((uint32_t)((uint32_t)(v) << BP_AXBS_PRSn_M4) & BM_AXBS_PRSn_M4) /*! @brief Set the M4 field to a new value. */ #define BW_AXBS_PRSn_M4(x, n, v) (HW_AXBS_PRSn_WR(x, n, (HW_AXBS_PRSn_RD(x, n) & ~BM_AXBS_PRSn_M4) | BF_AXBS_PRSn_M4(v))) /*@}*/ /*! * @name Register AXBS_PRSn, field M5[22:20] (RW) * * Values: * - 000 - This master has level 1, or highest, priority when accessing the * slave port. * - 001 - This master has level 2 priority when accessing the slave port. * - 010 - This master has level 3 priority when accessing the slave port. * - 011 - This master has level 4 priority when accessing the slave port. * - 100 - This master has level 5 priority when accessing the slave port. * - 101 - This master has level 6 priority when accessing the slave port. * - 110 - This master has level 7 priority when accessing the slave port. * - 111 - This master has level 8, or lowest, priority when accessing the slave * port. */ /*@{*/ #define BP_AXBS_PRSn_M5 (20U) /*!< Bit position for AXBS_PRSn_M5. */ #define BM_AXBS_PRSn_M5 (0x00700000U) /*!< Bit mask for AXBS_PRSn_M5. */ #define BS_AXBS_PRSn_M5 (3U) /*!< Bit field size in bits for AXBS_PRSn_M5. */ /*! @brief Read current value of the AXBS_PRSn_M5 field. */ #define BR_AXBS_PRSn_M5(x, n) (HW_AXBS_PRSn(x, n).B.M5) /*! @brief Format value for bitfield AXBS_PRSn_M5. */ #define BF_AXBS_PRSn_M5(v) ((uint32_t)((uint32_t)(v) << BP_AXBS_PRSn_M5) & BM_AXBS_PRSn_M5) /*! @brief Set the M5 field to a new value. */ #define BW_AXBS_PRSn_M5(x, n, v) (HW_AXBS_PRSn_WR(x, n, (HW_AXBS_PRSn_RD(x, n) & ~BM_AXBS_PRSn_M5) | BF_AXBS_PRSn_M5(v))) /*@}*/ /******************************************************************************* * HW_AXBS_CRSn - Control Register ******************************************************************************/ /*! * @brief HW_AXBS_CRSn - Control Register (RW) * * Reset value: 0x00000000U * * These registers control several features of each slave port and must be * accessed using 32-bit accesses. After CRSn[RO] is set, the PRSn can only be read; * attempts to write to it have no effect and result in an error response. */ typedef union _hw_axbs_crsn { uint32_t U; struct _hw_axbs_crsn_bitfields { uint32_t PARK : 3; /*!< [2:0] Park */ uint32_t RESERVED0 : 1; /*!< [3] */ uint32_t PCTL : 2; /*!< [5:4] Parking Control */ uint32_t RESERVED1 : 2; /*!< [7:6] */ uint32_t ARB : 2; /*!< [9:8] Arbitration Mode */ uint32_t RESERVED2 : 20; /*!< [29:10] */ uint32_t HLP : 1; /*!< [30] Halt Low Priority */ uint32_t RO : 1; /*!< [31] Read Only */ } B; } hw_axbs_crsn_t; /*! * @name Constants and macros for entire AXBS_CRSn register */ /*@{*/ #define HW_AXBS_CRSn_COUNT (5U) #define HW_AXBS_CRSn_ADDR(x, n) ((x) + 0x10U + (0x100U * (n))) #define HW_AXBS_CRSn(x, n) (*(__IO hw_axbs_crsn_t *) HW_AXBS_CRSn_ADDR(x, n)) #define HW_AXBS_CRSn_RD(x, n) (HW_AXBS_CRSn(x, n).U) #define HW_AXBS_CRSn_WR(x, n, v) (HW_AXBS_CRSn(x, n).U = (v)) #define HW_AXBS_CRSn_SET(x, n, v) (HW_AXBS_CRSn_WR(x, n, HW_AXBS_CRSn_RD(x, n) | (v))) #define HW_AXBS_CRSn_CLR(x, n, v) (HW_AXBS_CRSn_WR(x, n, HW_AXBS_CRSn_RD(x, n) & ~(v))) #define HW_AXBS_CRSn_TOG(x, n, v) (HW_AXBS_CRSn_WR(x, n, HW_AXBS_CRSn_RD(x, n) ^ (v))) /*@}*/ /* * Constants & macros for individual AXBS_CRSn bitfields */ /*! * @name Register AXBS_CRSn, field PARK[2:0] (RW) * * Determines which master port the current slave port parks on when no masters * are actively making requests and the PCTL bits are cleared. Select only master * ports that are present on the chip. Otherwise, undefined behavior might occur. * * Values: * - 000 - Park on master port M0 * - 001 - Park on master port M1 * - 010 - Park on master port M2 * - 011 - Park on master port M3 * - 100 - Park on master port M4 * - 101 - Park on master port M5 * - 110 - Park on master port M6 * - 111 - Park on master port M7 */ /*@{*/ #define BP_AXBS_CRSn_PARK (0U) /*!< Bit position for AXBS_CRSn_PARK. */ #define BM_AXBS_CRSn_PARK (0x00000007U) /*!< Bit mask for AXBS_CRSn_PARK. */ #define BS_AXBS_CRSn_PARK (3U) /*!< Bit field size in bits for AXBS_CRSn_PARK. */ /*! @brief Read current value of the AXBS_CRSn_PARK field. */ #define BR_AXBS_CRSn_PARK(x, n) (HW_AXBS_CRSn(x, n).B.PARK) /*! @brief Format value for bitfield AXBS_CRSn_PARK. */ #define BF_AXBS_CRSn_PARK(v) ((uint32_t)((uint32_t)(v) << BP_AXBS_CRSn_PARK) & BM_AXBS_CRSn_PARK) /*! @brief Set the PARK field to a new value. */ #define BW_AXBS_CRSn_PARK(x, n, v) (HW_AXBS_CRSn_WR(x, n, (HW_AXBS_CRSn_RD(x, n) & ~BM_AXBS_CRSn_PARK) | BF_AXBS_CRSn_PARK(v))) /*@}*/ /*! * @name Register AXBS_CRSn, field PCTL[5:4] (RW) * * Determines the slave port's parking control. The low-power park feature * results in an overall power savings if the slave port is not saturated. However, * this forces an extra latency clock when any master tries to access the slave * port while not in use because it is not parked on any master. * * Values: * - 00 - When no master makes a request, the arbiter parks the slave port on * the master port defined by the PARK field * - 01 - When no master makes a request, the arbiter parks the slave port on * the last master to be in control of the slave port * - 10 - When no master makes a request, the slave port is not parked on a * master and the arbiter drives all outputs to a constant safe state * - 11 - Reserved */ /*@{*/ #define BP_AXBS_CRSn_PCTL (4U) /*!< Bit position for AXBS_CRSn_PCTL. */ #define BM_AXBS_CRSn_PCTL (0x00000030U) /*!< Bit mask for AXBS_CRSn_PCTL. */ #define BS_AXBS_CRSn_PCTL (2U) /*!< Bit field size in bits for AXBS_CRSn_PCTL. */ /*! @brief Read current value of the AXBS_CRSn_PCTL field. */ #define BR_AXBS_CRSn_PCTL(x, n) (HW_AXBS_CRSn(x, n).B.PCTL) /*! @brief Format value for bitfield AXBS_CRSn_PCTL. */ #define BF_AXBS_CRSn_PCTL(v) ((uint32_t)((uint32_t)(v) << BP_AXBS_CRSn_PCTL) & BM_AXBS_CRSn_PCTL) /*! @brief Set the PCTL field to a new value. */ #define BW_AXBS_CRSn_PCTL(x, n, v) (HW_AXBS_CRSn_WR(x, n, (HW_AXBS_CRSn_RD(x, n) & ~BM_AXBS_CRSn_PCTL) | BF_AXBS_CRSn_PCTL(v))) /*@}*/ /*! * @name Register AXBS_CRSn, field ARB[9:8] (RW) * * Selects the arbitration policy for the slave port. * * Values: * - 00 - Fixed priority * - 01 - Round-robin, or rotating, priority * - 10 - Reserved * - 11 - Reserved */ /*@{*/ #define BP_AXBS_CRSn_ARB (8U) /*!< Bit position for AXBS_CRSn_ARB. */ #define BM_AXBS_CRSn_ARB (0x00000300U) /*!< Bit mask for AXBS_CRSn_ARB. */ #define BS_AXBS_CRSn_ARB (2U) /*!< Bit field size in bits for AXBS_CRSn_ARB. */ /*! @brief Read current value of the AXBS_CRSn_ARB field. */ #define BR_AXBS_CRSn_ARB(x, n) (HW_AXBS_CRSn(x, n).B.ARB) /*! @brief Format value for bitfield AXBS_CRSn_ARB. */ #define BF_AXBS_CRSn_ARB(v) ((uint32_t)((uint32_t)(v) << BP_AXBS_CRSn_ARB) & BM_AXBS_CRSn_ARB) /*! @brief Set the ARB field to a new value. */ #define BW_AXBS_CRSn_ARB(x, n, v) (HW_AXBS_CRSn_WR(x, n, (HW_AXBS_CRSn_RD(x, n) & ~BM_AXBS_CRSn_ARB) | BF_AXBS_CRSn_ARB(v))) /*@}*/ /*! * @name Register AXBS_CRSn, field HLP[30] (RW) * * Sets the initial arbitration priority for low power mode requests . Setting * this bit will not affect the request for low power mode from attaining highest * priority once it has control of the slave ports. * * Values: * - 0 - The low power mode request has the highest priority for arbitration on * this slave port * - 1 - The low power mode request has the lowest initial priority for * arbitration on this slave port */ /*@{*/ #define BP_AXBS_CRSn_HLP (30U) /*!< Bit position for AXBS_CRSn_HLP. */ #define BM_AXBS_CRSn_HLP (0x40000000U) /*!< Bit mask for AXBS_CRSn_HLP. */ #define BS_AXBS_CRSn_HLP (1U) /*!< Bit field size in bits for AXBS_CRSn_HLP. */ /*! @brief Read current value of the AXBS_CRSn_HLP field. */ #define BR_AXBS_CRSn_HLP(x, n) (BITBAND_ACCESS32(HW_AXBS_CRSn_ADDR(x, n), BP_AXBS_CRSn_HLP)) /*! @brief Format value for bitfield AXBS_CRSn_HLP. */ #define BF_AXBS_CRSn_HLP(v) ((uint32_t)((uint32_t)(v) << BP_AXBS_CRSn_HLP) & BM_AXBS_CRSn_HLP) /*! @brief Set the HLP field to a new value. */ #define BW_AXBS_CRSn_HLP(x, n, v) (BITBAND_ACCESS32(HW_AXBS_CRSn_ADDR(x, n), BP_AXBS_CRSn_HLP) = (v)) /*@}*/ /*! * @name Register AXBS_CRSn, field RO[31] (RW) * * Forces the slave port's CSRn and PRSn registers to be read-only. After set, * only a hardware reset clears it. * * Values: * - 0 - The slave port's registers are writeable * - 1 - The slave port's registers are read-only and cannot be written. * Attempted writes have no effect on the registers and result in a bus error * response. */ /*@{*/ #define BP_AXBS_CRSn_RO (31U) /*!< Bit position for AXBS_CRSn_RO. */ #define BM_AXBS_CRSn_RO (0x80000000U) /*!< Bit mask for AXBS_CRSn_RO. */ #define BS_AXBS_CRSn_RO (1U) /*!< Bit field size in bits for AXBS_CRSn_RO. */ /*! @brief Read current value of the AXBS_CRSn_RO field. */ #define BR_AXBS_CRSn_RO(x, n) (BITBAND_ACCESS32(HW_AXBS_CRSn_ADDR(x, n), BP_AXBS_CRSn_RO)) /*! @brief Format value for bitfield AXBS_CRSn_RO. */ #define BF_AXBS_CRSn_RO(v) ((uint32_t)((uint32_t)(v) << BP_AXBS_CRSn_RO) & BM_AXBS_CRSn_RO) /*! @brief Set the RO field to a new value. */ #define BW_AXBS_CRSn_RO(x, n, v) (BITBAND_ACCESS32(HW_AXBS_CRSn_ADDR(x, n), BP_AXBS_CRSn_RO) = (v)) /*@}*/ /******************************************************************************* * HW_AXBS_MGPCR0 - Master General Purpose Control Register ******************************************************************************/ /*! * @brief HW_AXBS_MGPCR0 - Master General Purpose Control Register (RW) * * Reset value: 0x00000000U * * The MGPCR controls only whether the master's undefined length burst accesses * are allowed to complete uninterrupted or whether they can be broken by * requests from higher priority masters. The MGPCR can be accessed only in Supervisor * mode with 32-bit accesses. */ typedef union _hw_axbs_mgpcr0 { uint32_t U; struct _hw_axbs_mgpcr0_bitfields { uint32_t AULB : 3; /*!< [2:0] Arbitrates On Undefined Length Bursts */ uint32_t RESERVED0 : 29; /*!< [31:3] */ } B; } hw_axbs_mgpcr0_t; /*! * @name Constants and macros for entire AXBS_MGPCR0 register */ /*@{*/ #define HW_AXBS_MGPCR0_ADDR(x) ((x) + 0x800U) #define HW_AXBS_MGPCR0(x) (*(__IO hw_axbs_mgpcr0_t *) HW_AXBS_MGPCR0_ADDR(x)) #define HW_AXBS_MGPCR0_RD(x) (HW_AXBS_MGPCR0(x).U) #define HW_AXBS_MGPCR0_WR(x, v) (HW_AXBS_MGPCR0(x).U = (v)) #define HW_AXBS_MGPCR0_SET(x, v) (HW_AXBS_MGPCR0_WR(x, HW_AXBS_MGPCR0_RD(x) | (v))) #define HW_AXBS_MGPCR0_CLR(x, v) (HW_AXBS_MGPCR0_WR(x, HW_AXBS_MGPCR0_RD(x) & ~(v))) #define HW_AXBS_MGPCR0_TOG(x, v) (HW_AXBS_MGPCR0_WR(x, HW_AXBS_MGPCR0_RD(x) ^ (v))) /*@}*/ /* * Constants & macros for individual AXBS_MGPCR0 bitfields */ /*! * @name Register AXBS_MGPCR0, field AULB[2:0] (RW) * * Determines whether, and when, the crossbar switch arbitrates away the slave * port the master owns when the master is performing undefined length burst * accesses. * * Values: * - 000 - No arbitration is allowed during an undefined length burst * - 001 - Arbitration is allowed at any time during an undefined length burst * - 010 - Arbitration is allowed after four beats of an undefined length burst * - 011 - Arbitration is allowed after eight beats of an undefined length burst * - 100 - Arbitration is allowed after 16 beats of an undefined length burst * - 101 - Reserved * - 110 - Reserved * - 111 - Reserved */ /*@{*/ #define BP_AXBS_MGPCR0_AULB (0U) /*!< Bit position for AXBS_MGPCR0_AULB. */ #define BM_AXBS_MGPCR0_AULB (0x00000007U) /*!< Bit mask for AXBS_MGPCR0_AULB. */ #define BS_AXBS_MGPCR0_AULB (3U) /*!< Bit field size in bits for AXBS_MGPCR0_AULB. */ /*! @brief Read current value of the AXBS_MGPCR0_AULB field. */ #define BR_AXBS_MGPCR0_AULB(x) (HW_AXBS_MGPCR0(x).B.AULB) /*! @brief Format value for bitfield AXBS_MGPCR0_AULB. */ #define BF_AXBS_MGPCR0_AULB(v) ((uint32_t)((uint32_t)(v) << BP_AXBS_MGPCR0_AULB) & BM_AXBS_MGPCR0_AULB) /*! @brief Set the AULB field to a new value. */ #define BW_AXBS_MGPCR0_AULB(x, v) (HW_AXBS_MGPCR0_WR(x, (HW_AXBS_MGPCR0_RD(x) & ~BM_AXBS_MGPCR0_AULB) | BF_AXBS_MGPCR0_AULB(v))) /*@}*/ /******************************************************************************* * HW_AXBS_MGPCR1 - Master General Purpose Control Register ******************************************************************************/ /*! * @brief HW_AXBS_MGPCR1 - Master General Purpose Control Register (RW) * * Reset value: 0x00000000U * * The MGPCR controls only whether the master's undefined length burst accesses * are allowed to complete uninterrupted or whether they can be broken by * requests from higher priority masters. The MGPCR can be accessed only in Supervisor * mode with 32-bit accesses. */ typedef union _hw_axbs_mgpcr1 { uint32_t U; struct _hw_axbs_mgpcr1_bitfields { uint32_t AULB : 3; /*!< [2:0] Arbitrates On Undefined Length Bursts */ uint32_t RESERVED0 : 29; /*!< [31:3] */ } B; } hw_axbs_mgpcr1_t; /*! * @name Constants and macros for entire AXBS_MGPCR1 register */ /*@{*/ #define HW_AXBS_MGPCR1_ADDR(x) ((x) + 0x900U) #define HW_AXBS_MGPCR1(x) (*(__IO hw_axbs_mgpcr1_t *) HW_AXBS_MGPCR1_ADDR(x)) #define HW_AXBS_MGPCR1_RD(x) (HW_AXBS_MGPCR1(x).U) #define HW_AXBS_MGPCR1_WR(x, v) (HW_AXBS_MGPCR1(x).U = (v)) #define HW_AXBS_MGPCR1_SET(x, v) (HW_AXBS_MGPCR1_WR(x, HW_AXBS_MGPCR1_RD(x) | (v))) #define HW_AXBS_MGPCR1_CLR(x, v) (HW_AXBS_MGPCR1_WR(x, HW_AXBS_MGPCR1_RD(x) & ~(v))) #define HW_AXBS_MGPCR1_TOG(x, v) (HW_AXBS_MGPCR1_WR(x, HW_AXBS_MGPCR1_RD(x) ^ (v))) /*@}*/ /* * Constants & macros for individual AXBS_MGPCR1 bitfields */ /*! * @name Register AXBS_MGPCR1, field AULB[2:0] (RW) * * Determines whether, and when, the crossbar switch arbitrates away the slave * port the master owns when the master is performing undefined length burst * accesses. * * Values: * - 000 - No arbitration is allowed during an undefined length burst * - 001 - Arbitration is allowed at any time during an undefined length burst * - 010 - Arbitration is allowed after four beats of an undefined length burst * - 011 - Arbitration is allowed after eight beats of an undefined length burst * - 100 - Arbitration is allowed after 16 beats of an undefined length burst * - 101 - Reserved * - 110 - Reserved * - 111 - Reserved */ /*@{*/ #define BP_AXBS_MGPCR1_AULB (0U) /*!< Bit position for AXBS_MGPCR1_AULB. */ #define BM_AXBS_MGPCR1_AULB (0x00000007U) /*!< Bit mask for AXBS_MGPCR1_AULB. */ #define BS_AXBS_MGPCR1_AULB (3U) /*!< Bit field size in bits for AXBS_MGPCR1_AULB. */ /*! @brief Read current value of the AXBS_MGPCR1_AULB field. */ #define BR_AXBS_MGPCR1_AULB(x) (HW_AXBS_MGPCR1(x).B.AULB) /*! @brief Format value for bitfield AXBS_MGPCR1_AULB. */ #define BF_AXBS_MGPCR1_AULB(v) ((uint32_t)((uint32_t)(v) << BP_AXBS_MGPCR1_AULB) & BM_AXBS_MGPCR1_AULB) /*! @brief Set the AULB field to a new value. */ #define BW_AXBS_MGPCR1_AULB(x, v) (HW_AXBS_MGPCR1_WR(x, (HW_AXBS_MGPCR1_RD(x) & ~BM_AXBS_MGPCR1_AULB) | BF_AXBS_MGPCR1_AULB(v))) /*@}*/ /******************************************************************************* * HW_AXBS_MGPCR2 - Master General Purpose Control Register ******************************************************************************/ /*! * @brief HW_AXBS_MGPCR2 - Master General Purpose Control Register (RW) * * Reset value: 0x00000000U * * The MGPCR controls only whether the master's undefined length burst accesses * are allowed to complete uninterrupted or whether they can be broken by * requests from higher priority masters. The MGPCR can be accessed only in Supervisor * mode with 32-bit accesses. */ typedef union _hw_axbs_mgpcr2 { uint32_t U; struct _hw_axbs_mgpcr2_bitfields { uint32_t AULB : 3; /*!< [2:0] Arbitrates On Undefined Length Bursts */ uint32_t RESERVED0 : 29; /*!< [31:3] */ } B; } hw_axbs_mgpcr2_t; /*! * @name Constants and macros for entire AXBS_MGPCR2 register */ /*@{*/ #define HW_AXBS_MGPCR2_ADDR(x) ((x) + 0xA00U) #define HW_AXBS_MGPCR2(x) (*(__IO hw_axbs_mgpcr2_t *) HW_AXBS_MGPCR2_ADDR(x)) #define HW_AXBS_MGPCR2_RD(x) (HW_AXBS_MGPCR2(x).U) #define HW_AXBS_MGPCR2_WR(x, v) (HW_AXBS_MGPCR2(x).U = (v)) #define HW_AXBS_MGPCR2_SET(x, v) (HW_AXBS_MGPCR2_WR(x, HW_AXBS_MGPCR2_RD(x) | (v))) #define HW_AXBS_MGPCR2_CLR(x, v) (HW_AXBS_MGPCR2_WR(x, HW_AXBS_MGPCR2_RD(x) & ~(v))) #define HW_AXBS_MGPCR2_TOG(x, v) (HW_AXBS_MGPCR2_WR(x, HW_AXBS_MGPCR2_RD(x) ^ (v))) /*@}*/ /* * Constants & macros for individual AXBS_MGPCR2 bitfields */ /*! * @name Register AXBS_MGPCR2, field AULB[2:0] (RW) * * Determines whether, and when, the crossbar switch arbitrates away the slave * port the master owns when the master is performing undefined length burst * accesses. * * Values: * - 000 - No arbitration is allowed during an undefined length burst * - 001 - Arbitration is allowed at any time during an undefined length burst * - 010 - Arbitration is allowed after four beats of an undefined length burst * - 011 - Arbitration is allowed after eight beats of an undefined length burst * - 100 - Arbitration is allowed after 16 beats of an undefined length burst * - 101 - Reserved * - 110 - Reserved * - 111 - Reserved */ /*@{*/ #define BP_AXBS_MGPCR2_AULB (0U) /*!< Bit position for AXBS_MGPCR2_AULB. */ #define BM_AXBS_MGPCR2_AULB (0x00000007U) /*!< Bit mask for AXBS_MGPCR2_AULB. */ #define BS_AXBS_MGPCR2_AULB (3U) /*!< Bit field size in bits for AXBS_MGPCR2_AULB. */ /*! @brief Read current value of the AXBS_MGPCR2_AULB field. */ #define BR_AXBS_MGPCR2_AULB(x) (HW_AXBS_MGPCR2(x).B.AULB) /*! @brief Format value for bitfield AXBS_MGPCR2_AULB. */ #define BF_AXBS_MGPCR2_AULB(v) ((uint32_t)((uint32_t)(v) << BP_AXBS_MGPCR2_AULB) & BM_AXBS_MGPCR2_AULB) /*! @brief Set the AULB field to a new value. */ #define BW_AXBS_MGPCR2_AULB(x, v) (HW_AXBS_MGPCR2_WR(x, (HW_AXBS_MGPCR2_RD(x) & ~BM_AXBS_MGPCR2_AULB) | BF_AXBS_MGPCR2_AULB(v))) /*@}*/ /******************************************************************************* * HW_AXBS_MGPCR3 - Master General Purpose Control Register ******************************************************************************/ /*! * @brief HW_AXBS_MGPCR3 - Master General Purpose Control Register (RW) * * Reset value: 0x00000000U * * The MGPCR controls only whether the master's undefined length burst accesses * are allowed to complete uninterrupted or whether they can be broken by * requests from higher priority masters. The MGPCR can be accessed only in Supervisor * mode with 32-bit accesses. */ typedef union _hw_axbs_mgpcr3 { uint32_t U; struct _hw_axbs_mgpcr3_bitfields { uint32_t AULB : 3; /*!< [2:0] Arbitrates On Undefined Length Bursts */ uint32_t RESERVED0 : 29; /*!< [31:3] */ } B; } hw_axbs_mgpcr3_t; /*! * @name Constants and macros for entire AXBS_MGPCR3 register */ /*@{*/ #define HW_AXBS_MGPCR3_ADDR(x) ((x) + 0xB00U) #define HW_AXBS_MGPCR3(x) (*(__IO hw_axbs_mgpcr3_t *) HW_AXBS_MGPCR3_ADDR(x)) #define HW_AXBS_MGPCR3_RD(x) (HW_AXBS_MGPCR3(x).U) #define HW_AXBS_MGPCR3_WR(x, v) (HW_AXBS_MGPCR3(x).U = (v)) #define HW_AXBS_MGPCR3_SET(x, v) (HW_AXBS_MGPCR3_WR(x, HW_AXBS_MGPCR3_RD(x) | (v))) #define HW_AXBS_MGPCR3_CLR(x, v) (HW_AXBS_MGPCR3_WR(x, HW_AXBS_MGPCR3_RD(x) & ~(v))) #define HW_AXBS_MGPCR3_TOG(x, v) (HW_AXBS_MGPCR3_WR(x, HW_AXBS_MGPCR3_RD(x) ^ (v))) /*@}*/ /* * Constants & macros for individual AXBS_MGPCR3 bitfields */ /*! * @name Register AXBS_MGPCR3, field AULB[2:0] (RW) * * Determines whether, and when, the crossbar switch arbitrates away the slave * port the master owns when the master is performing undefined length burst * accesses. * * Values: * - 000 - No arbitration is allowed during an undefined length burst * - 001 - Arbitration is allowed at any time during an undefined length burst * - 010 - Arbitration is allowed after four beats of an undefined length burst * - 011 - Arbitration is allowed after eight beats of an undefined length burst * - 100 - Arbitration is allowed after 16 beats of an undefined length burst * - 101 - Reserved * - 110 - Reserved * - 111 - Reserved */ /*@{*/ #define BP_AXBS_MGPCR3_AULB (0U) /*!< Bit position for AXBS_MGPCR3_AULB. */ #define BM_AXBS_MGPCR3_AULB (0x00000007U) /*!< Bit mask for AXBS_MGPCR3_AULB. */ #define BS_AXBS_MGPCR3_AULB (3U) /*!< Bit field size in bits for AXBS_MGPCR3_AULB. */ /*! @brief Read current value of the AXBS_MGPCR3_AULB field. */ #define BR_AXBS_MGPCR3_AULB(x) (HW_AXBS_MGPCR3(x).B.AULB) /*! @brief Format value for bitfield AXBS_MGPCR3_AULB. */ #define BF_AXBS_MGPCR3_AULB(v) ((uint32_t)((uint32_t)(v) << BP_AXBS_MGPCR3_AULB) & BM_AXBS_MGPCR3_AULB) /*! @brief Set the AULB field to a new value. */ #define BW_AXBS_MGPCR3_AULB(x, v) (HW_AXBS_MGPCR3_WR(x, (HW_AXBS_MGPCR3_RD(x) & ~BM_AXBS_MGPCR3_AULB) | BF_AXBS_MGPCR3_AULB(v))) /*@}*/ /******************************************************************************* * HW_AXBS_MGPCR4 - Master General Purpose Control Register ******************************************************************************/ /*! * @brief HW_AXBS_MGPCR4 - Master General Purpose Control Register (RW) * * Reset value: 0x00000000U * * The MGPCR controls only whether the master's undefined length burst accesses * are allowed to complete uninterrupted or whether they can be broken by * requests from higher priority masters. The MGPCR can be accessed only in Supervisor * mode with 32-bit accesses. */ typedef union _hw_axbs_mgpcr4 { uint32_t U; struct _hw_axbs_mgpcr4_bitfields { uint32_t AULB : 3; /*!< [2:0] Arbitrates On Undefined Length Bursts */ uint32_t RESERVED0 : 29; /*!< [31:3] */ } B; } hw_axbs_mgpcr4_t; /*! * @name Constants and macros for entire AXBS_MGPCR4 register */ /*@{*/ #define HW_AXBS_MGPCR4_ADDR(x) ((x) + 0xC00U) #define HW_AXBS_MGPCR4(x) (*(__IO hw_axbs_mgpcr4_t *) HW_AXBS_MGPCR4_ADDR(x)) #define HW_AXBS_MGPCR4_RD(x) (HW_AXBS_MGPCR4(x).U) #define HW_AXBS_MGPCR4_WR(x, v) (HW_AXBS_MGPCR4(x).U = (v)) #define HW_AXBS_MGPCR4_SET(x, v) (HW_AXBS_MGPCR4_WR(x, HW_AXBS_MGPCR4_RD(x) | (v))) #define HW_AXBS_MGPCR4_CLR(x, v) (HW_AXBS_MGPCR4_WR(x, HW_AXBS_MGPCR4_RD(x) & ~(v))) #define HW_AXBS_MGPCR4_TOG(x, v) (HW_AXBS_MGPCR4_WR(x, HW_AXBS_MGPCR4_RD(x) ^ (v))) /*@}*/ /* * Constants & macros for individual AXBS_MGPCR4 bitfields */ /*! * @name Register AXBS_MGPCR4, field AULB[2:0] (RW) * * Determines whether, and when, the crossbar switch arbitrates away the slave * port the master owns when the master is performing undefined length burst * accesses. * * Values: * - 000 - No arbitration is allowed during an undefined length burst * - 001 - Arbitration is allowed at any time during an undefined length burst * - 010 - Arbitration is allowed after four beats of an undefined length burst * - 011 - Arbitration is allowed after eight beats of an undefined length burst * - 100 - Arbitration is allowed after 16 beats of an undefined length burst * - 101 - Reserved * - 110 - Reserved * - 111 - Reserved */ /*@{*/ #define BP_AXBS_MGPCR4_AULB (0U) /*!< Bit position for AXBS_MGPCR4_AULB. */ #define BM_AXBS_MGPCR4_AULB (0x00000007U) /*!< Bit mask for AXBS_MGPCR4_AULB. */ #define BS_AXBS_MGPCR4_AULB (3U) /*!< Bit field size in bits for AXBS_MGPCR4_AULB. */ /*! @brief Read current value of the AXBS_MGPCR4_AULB field. */ #define BR_AXBS_MGPCR4_AULB(x) (HW_AXBS_MGPCR4(x).B.AULB) /*! @brief Format value for bitfield AXBS_MGPCR4_AULB. */ #define BF_AXBS_MGPCR4_AULB(v) ((uint32_t)((uint32_t)(v) << BP_AXBS_MGPCR4_AULB) & BM_AXBS_MGPCR4_AULB) /*! @brief Set the AULB field to a new value. */ #define BW_AXBS_MGPCR4_AULB(x, v) (HW_AXBS_MGPCR4_WR(x, (HW_AXBS_MGPCR4_RD(x) & ~BM_AXBS_MGPCR4_AULB) | BF_AXBS_MGPCR4_AULB(v))) /*@}*/ /******************************************************************************* * HW_AXBS_MGPCR5 - Master General Purpose Control Register ******************************************************************************/ /*! * @brief HW_AXBS_MGPCR5 - Master General Purpose Control Register (RW) * * Reset value: 0x00000000U * * The MGPCR controls only whether the master's undefined length burst accesses * are allowed to complete uninterrupted or whether they can be broken by * requests from higher priority masters. The MGPCR can be accessed only in Supervisor * mode with 32-bit accesses. */ typedef union _hw_axbs_mgpcr5 { uint32_t U; struct _hw_axbs_mgpcr5_bitfields { uint32_t AULB : 3; /*!< [2:0] Arbitrates On Undefined Length Bursts */ uint32_t RESERVED0 : 29; /*!< [31:3] */ } B; } hw_axbs_mgpcr5_t; /*! * @name Constants and macros for entire AXBS_MGPCR5 register */ /*@{*/ #define HW_AXBS_MGPCR5_ADDR(x) ((x) + 0xD00U) #define HW_AXBS_MGPCR5(x) (*(__IO hw_axbs_mgpcr5_t *) HW_AXBS_MGPCR5_ADDR(x)) #define HW_AXBS_MGPCR5_RD(x) (HW_AXBS_MGPCR5(x).U) #define HW_AXBS_MGPCR5_WR(x, v) (HW_AXBS_MGPCR5(x).U = (v)) #define HW_AXBS_MGPCR5_SET(x, v) (HW_AXBS_MGPCR5_WR(x, HW_AXBS_MGPCR5_RD(x) | (v))) #define HW_AXBS_MGPCR5_CLR(x, v) (HW_AXBS_MGPCR5_WR(x, HW_AXBS_MGPCR5_RD(x) & ~(v))) #define HW_AXBS_MGPCR5_TOG(x, v) (HW_AXBS_MGPCR5_WR(x, HW_AXBS_MGPCR5_RD(x) ^ (v))) /*@}*/ /* * Constants & macros for individual AXBS_MGPCR5 bitfields */ /*! * @name Register AXBS_MGPCR5, field AULB[2:0] (RW) * * Determines whether, and when, the crossbar switch arbitrates away the slave * port the master owns when the master is performing undefined length burst * accesses. * * Values: * - 000 - No arbitration is allowed during an undefined length burst * - 001 - Arbitration is allowed at any time during an undefined length burst * - 010 - Arbitration is allowed after four beats of an undefined length burst * - 011 - Arbitration is allowed after eight beats of an undefined length burst * - 100 - Arbitration is allowed after 16 beats of an undefined length burst * - 101 - Reserved * - 110 - Reserved * - 111 - Reserved */ /*@{*/ #define BP_AXBS_MGPCR5_AULB (0U) /*!< Bit position for AXBS_MGPCR5_AULB. */ #define BM_AXBS_MGPCR5_AULB (0x00000007U) /*!< Bit mask for AXBS_MGPCR5_AULB. */ #define BS_AXBS_MGPCR5_AULB (3U) /*!< Bit field size in bits for AXBS_MGPCR5_AULB. */ /*! @brief Read current value of the AXBS_MGPCR5_AULB field. */ #define BR_AXBS_MGPCR5_AULB(x) (HW_AXBS_MGPCR5(x).B.AULB) /*! @brief Format value for bitfield AXBS_MGPCR5_AULB. */ #define BF_AXBS_MGPCR5_AULB(v) ((uint32_t)((uint32_t)(v) << BP_AXBS_MGPCR5_AULB) & BM_AXBS_MGPCR5_AULB) /*! @brief Set the AULB field to a new value. */ #define BW_AXBS_MGPCR5_AULB(x, v) (HW_AXBS_MGPCR5_WR(x, (HW_AXBS_MGPCR5_RD(x) & ~BM_AXBS_MGPCR5_AULB) | BF_AXBS_MGPCR5_AULB(v))) /*@}*/ /******************************************************************************* * hw_axbs_t - module struct ******************************************************************************/ /*! * @brief All AXBS module registers. */ #pragma pack(1) typedef struct _hw_axbs { struct { __IO hw_axbs_prsn_t PRSn; /*!< [0x0] Priority Registers Slave */ uint8_t _reserved0[12]; __IO hw_axbs_crsn_t CRSn; /*!< [0x10] Control Register */ uint8_t _reserved1[236]; } SLAVE[5]; uint8_t _reserved0[768]; __IO hw_axbs_mgpcr0_t MGPCR0; /*!< [0x800] Master General Purpose Control Register */ uint8_t _reserved1[252]; __IO hw_axbs_mgpcr1_t MGPCR1; /*!< [0x900] Master General Purpose Control Register */ uint8_t _reserved2[252]; __IO hw_axbs_mgpcr2_t MGPCR2; /*!< [0xA00] Master General Purpose Control Register */ uint8_t _reserved3[252]; __IO hw_axbs_mgpcr3_t MGPCR3; /*!< [0xB00] Master General Purpose Control Register */ uint8_t _reserved4[252]; __IO hw_axbs_mgpcr4_t MGPCR4; /*!< [0xC00] Master General Purpose Control Register */ uint8_t _reserved5[252]; __IO hw_axbs_mgpcr5_t MGPCR5; /*!< [0xD00] Master General Purpose Control Register */ } hw_axbs_t; #pragma pack() /*! @brief Macro to access all AXBS registers. */ /*! @param x AXBS module instance base address. */ /*! @return Reference (not a pointer) to the registers struct. To get a pointer to the struct, * use the '&' operator, like &HW_AXBS(AXBS_BASE). */ #define HW_AXBS(x) (*(hw_axbs_t *)(x)) #endif /* __HW_AXBS_REGISTERS_H__ */ /* EOF */ ================================================ FILE: Zelig/mbed/TARGET_K64F/TARGET_Freescale/TARGET_KPSDK_MCUS/TARGET_MCU_K64F/device/device/MK64F12/MK64F12_can.h ================================================ /* ** ################################################################### ** Compilers: Keil ARM C/C++ Compiler ** Freescale C/C++ for Embedded ARM ** GNU C Compiler ** IAR ANSI C/C++ Compiler for ARM ** ** Reference manual: K64P144M120SF5RM, Rev.2, January 2014 ** Version: rev. 2.5, 2014-02-10 ** Build: b140604 ** ** Abstract: ** Extension to the CMSIS register access layer header. ** ** Copyright (c) 2014 Freescale Semiconductor, Inc. ** All rights reserved. ** ** Redistribution and use in source and binary forms, with or without modification, ** are permitted provided that the following conditions are met: ** ** o Redistributions of source code must retain the above copyright notice, this list ** of conditions and the following disclaimer. ** ** o Redistributions in binary form must reproduce the above copyright notice, this ** list of conditions and the following disclaimer in the documentation and/or ** other materials provided with the distribution. ** ** o Neither the name of Freescale Semiconductor, Inc. nor the names of its ** contributors may be used to endorse or promote products derived from this ** software without specific prior written permission. ** ** THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ** ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED ** WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE ** DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT 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. ** ** http: www.freescale.com ** mail: support@freescale.com ** ** Revisions: ** - rev. 1.0 (2013-08-12) ** Initial version. ** - rev. 2.0 (2013-10-29) ** Register accessor macros added to the memory map. ** Symbols for Processor Expert memory map compatibility added to the memory map. ** Startup file for gcc has been updated according to CMSIS 3.2. ** System initialization updated. ** MCG - registers updated. ** PORTA, PORTB, PORTC, PORTE - registers for digital filter removed. ** - rev. 2.1 (2013-10-30) ** Definition of BITBAND macros updated to support peripherals with 32-bit acces disabled. ** - rev. 2.2 (2013-12-09) ** DMA - EARS register removed. ** AIPS0, AIPS1 - MPRA register updated. ** - rev. 2.3 (2014-01-24) ** Update according to reference manual rev. 2 ** ENET, MCG, MCM, SIM, USB - registers updated ** - rev. 2.4 (2014-02-10) ** The declaration of clock configurations has been moved to separate header file system_MK64F12.h ** Update of SystemInit() and SystemCoreClockUpdate() functions. ** - rev. 2.5 (2014-02-10) ** The declaration of clock configurations has been moved to separate header file system_MK64F12.h ** Update of SystemInit() and SystemCoreClockUpdate() functions. ** Module access macro module_BASES replaced by module_BASE_PTRS. ** ** ################################################################### */ /* * WARNING! DO NOT EDIT THIS FILE DIRECTLY! * * This file was generated automatically and any changes may be lost. */ #ifndef __HW_CAN_REGISTERS_H__ #define __HW_CAN_REGISTERS_H__ #include "MK64F12.h" #include "fsl_bitaccess.h" /* * MK64F12 CAN * * Flex Controller Area Network module * * Registers defined in this header file: * - HW_CAN_MCR - Module Configuration Register * - HW_CAN_CTRL1 - Control 1 register * - HW_CAN_TIMER - Free Running Timer * - HW_CAN_RXMGMASK - Rx Mailboxes Global Mask Register * - HW_CAN_RX14MASK - Rx 14 Mask register * - HW_CAN_RX15MASK - Rx 15 Mask register * - HW_CAN_ECR - Error Counter * - HW_CAN_ESR1 - Error and Status 1 register * - HW_CAN_IMASK1 - Interrupt Masks 1 register * - HW_CAN_IFLAG1 - Interrupt Flags 1 register * - HW_CAN_CTRL2 - Control 2 register * - HW_CAN_ESR2 - Error and Status 2 register * - HW_CAN_CRCR - CRC Register * - HW_CAN_RXFGMASK - Rx FIFO Global Mask register * - HW_CAN_RXFIR - Rx FIFO Information Register * - HW_CAN_CSn - Message Buffer 0 CS Register * - HW_CAN_IDn - Message Buffer 0 ID Register * - HW_CAN_WORD0n - Message Buffer 0 WORD0 Register * - HW_CAN_WORD1n - Message Buffer 0 WORD1 Register * - HW_CAN_RXIMRn - Rx Individual Mask Registers * * - hw_can_t - Struct containing all module registers. */ #define HW_CAN_INSTANCE_COUNT (1U) /*!< Number of instances of the CAN module. */ /******************************************************************************* * HW_CAN_MCR - Module Configuration Register ******************************************************************************/ /*! * @brief HW_CAN_MCR - Module Configuration Register (RW) * * Reset value: 0xD890000FU * * This register defines global system configurations, such as the module * operation modes and the maximum message buffer configuration. */ typedef union _hw_can_mcr { uint32_t U; struct _hw_can_mcr_bitfields { uint32_t MAXMB : 7; /*!< [6:0] Number Of The Last Message Buffer */ uint32_t RESERVED0 : 1; /*!< [7] */ uint32_t IDAM : 2; /*!< [9:8] ID Acceptance Mode */ uint32_t RESERVED1 : 2; /*!< [11:10] */ uint32_t AEN : 1; /*!< [12] Abort Enable */ uint32_t LPRIOEN : 1; /*!< [13] Local Priority Enable */ uint32_t RESERVED2 : 2; /*!< [15:14] */ uint32_t IRMQ : 1; /*!< [16] Individual Rx Masking And Queue Enable */ uint32_t SRXDIS : 1; /*!< [17] Self Reception Disable */ uint32_t RESERVED3 : 1; /*!< [18] */ uint32_t WAKSRC : 1; /*!< [19] Wake Up Source */ uint32_t LPMACK : 1; /*!< [20] Low-Power Mode Acknowledge */ uint32_t WRNEN : 1; /*!< [21] Warning Interrupt Enable */ uint32_t SLFWAK : 1; /*!< [22] Self Wake Up */ uint32_t SUPV : 1; /*!< [23] Supervisor Mode */ uint32_t FRZACK : 1; /*!< [24] Freeze Mode Acknowledge */ uint32_t SOFTRST : 1; /*!< [25] Soft Reset */ uint32_t WAKMSK : 1; /*!< [26] Wake Up Interrupt Mask */ uint32_t NOTRDY : 1; /*!< [27] FlexCAN Not Ready */ uint32_t HALT : 1; /*!< [28] Halt FlexCAN */ uint32_t RFEN : 1; /*!< [29] Rx FIFO Enable */ uint32_t FRZ : 1; /*!< [30] Freeze Enable */ uint32_t MDIS : 1; /*!< [31] Module Disable */ } B; } hw_can_mcr_t; /*! * @name Constants and macros for entire CAN_MCR register */ /*@{*/ #define HW_CAN_MCR_ADDR(x) ((x) + 0x0U) #define HW_CAN_MCR(x) (*(__IO hw_can_mcr_t *) HW_CAN_MCR_ADDR(x)) #define HW_CAN_MCR_RD(x) (HW_CAN_MCR(x).U) #define HW_CAN_MCR_WR(x, v) (HW_CAN_MCR(x).U = (v)) #define HW_CAN_MCR_SET(x, v) (HW_CAN_MCR_WR(x, HW_CAN_MCR_RD(x) | (v))) #define HW_CAN_MCR_CLR(x, v) (HW_CAN_MCR_WR(x, HW_CAN_MCR_RD(x) & ~(v))) #define HW_CAN_MCR_TOG(x, v) (HW_CAN_MCR_WR(x, HW_CAN_MCR_RD(x) ^ (v))) /*@}*/ /* * Constants & macros for individual CAN_MCR bitfields */ /*! * @name Register CAN_MCR, field MAXMB[6:0] (RW) * * This 7-bit field defines the number of the last Message Buffers that will * take part in the matching and arbitration processes. The reset value (0x0F) is * equivalent to a 16 MB configuration. This field can be written only in Freeze * mode because it is blocked by hardware in other modes. Number of the last MB = * MAXMB MAXMB must be programmed with a value smaller than the parameter * NUMBER_OF_MB, otherwise the number of the last effective Message Buffer will be: * (NUMBER_OF_MB - 1) Additionally, the value of MAXMB must encompass the FIFO size * defined by CTRL2[RFFN]. MAXMB also impacts the definition of the minimum number * of peripheral clocks per CAN bit as described in Table "Minimum Ratio Between * Peripheral Clock Frequency and CAN Bit Rate" (in Section "Arbitration and * Matching Timing"). */ /*@{*/ #define BP_CAN_MCR_MAXMB (0U) /*!< Bit position for CAN_MCR_MAXMB. */ #define BM_CAN_MCR_MAXMB (0x0000007FU) /*!< Bit mask for CAN_MCR_MAXMB. */ #define BS_CAN_MCR_MAXMB (7U) /*!< Bit field size in bits for CAN_MCR_MAXMB. */ /*! @brief Read current value of the CAN_MCR_MAXMB field. */ #define BR_CAN_MCR_MAXMB(x) (HW_CAN_MCR(x).B.MAXMB) /*! @brief Format value for bitfield CAN_MCR_MAXMB. */ #define BF_CAN_MCR_MAXMB(v) ((uint32_t)((uint32_t)(v) << BP_CAN_MCR_MAXMB) & BM_CAN_MCR_MAXMB) /*! @brief Set the MAXMB field to a new value. */ #define BW_CAN_MCR_MAXMB(x, v) (HW_CAN_MCR_WR(x, (HW_CAN_MCR_RD(x) & ~BM_CAN_MCR_MAXMB) | BF_CAN_MCR_MAXMB(v))) /*@}*/ /*! * @name Register CAN_MCR, field IDAM[9:8] (RW) * * This 2-bit field identifies the format of the Rx FIFO ID Filter Table * elements. Note that all elements of the table are configured at the same time by this * field (they are all the same format). See Section "Rx FIFO Structure". This * field can be written only in Freeze mode because it is blocked by hardware in * other modes. * * Values: * - 00 - Format A: One full ID (standard and extended) per ID Filter Table * element. * - 01 - Format B: Two full standard IDs or two partial 14-bit (standard and * extended) IDs per ID Filter Table element. * - 10 - Format C: Four partial 8-bit Standard IDs per ID Filter Table element. * - 11 - Format D: All frames rejected. */ /*@{*/ #define BP_CAN_MCR_IDAM (8U) /*!< Bit position for CAN_MCR_IDAM. */ #define BM_CAN_MCR_IDAM (0x00000300U) /*!< Bit mask for CAN_MCR_IDAM. */ #define BS_CAN_MCR_IDAM (2U) /*!< Bit field size in bits for CAN_MCR_IDAM. */ /*! @brief Read current value of the CAN_MCR_IDAM field. */ #define BR_CAN_MCR_IDAM(x) (HW_CAN_MCR(x).B.IDAM) /*! @brief Format value for bitfield CAN_MCR_IDAM. */ #define BF_CAN_MCR_IDAM(v) ((uint32_t)((uint32_t)(v) << BP_CAN_MCR_IDAM) & BM_CAN_MCR_IDAM) /*! @brief Set the IDAM field to a new value. */ #define BW_CAN_MCR_IDAM(x, v) (HW_CAN_MCR_WR(x, (HW_CAN_MCR_RD(x) & ~BM_CAN_MCR_IDAM) | BF_CAN_MCR_IDAM(v))) /*@}*/ /*! * @name Register CAN_MCR, field AEN[12] (RW) * * This bit is supplied for backwards compatibility with legacy applications. * When asserted, it enables the Tx abort mechanism. This mechanism guarantees a * safe procedure for aborting a pending transmission, so that no frame is sent in * the CAN bus without notification. This bit can be written only in Freeze mode * because it is blocked by hardware in other modes. When MCR[AEN] is asserted, * only the abort mechanism (see Section "Transmission Abort Mechanism") must be * used for updating Mailboxes configured for transmission. Writing the Abort code * into Rx Mailboxes can cause unpredictable results when the MCR[AEN] is * asserted. * * Values: * - 0 - Abort disabled. * - 1 - Abort enabled. */ /*@{*/ #define BP_CAN_MCR_AEN (12U) /*!< Bit position for CAN_MCR_AEN. */ #define BM_CAN_MCR_AEN (0x00001000U) /*!< Bit mask for CAN_MCR_AEN. */ #define BS_CAN_MCR_AEN (1U) /*!< Bit field size in bits for CAN_MCR_AEN. */ /*! @brief Read current value of the CAN_MCR_AEN field. */ #define BR_CAN_MCR_AEN(x) (BITBAND_ACCESS32(HW_CAN_MCR_ADDR(x), BP_CAN_MCR_AEN)) /*! @brief Format value for bitfield CAN_MCR_AEN. */ #define BF_CAN_MCR_AEN(v) ((uint32_t)((uint32_t)(v) << BP_CAN_MCR_AEN) & BM_CAN_MCR_AEN) /*! @brief Set the AEN field to a new value. */ #define BW_CAN_MCR_AEN(x, v) (BITBAND_ACCESS32(HW_CAN_MCR_ADDR(x), BP_CAN_MCR_AEN) = (v)) /*@}*/ /*! * @name Register CAN_MCR, field LPRIOEN[13] (RW) * * This bit is provided for backwards compatibility with legacy applications. It * controls whether the local priority feature is enabled or not. It is used to * expand the ID used during the arbitration process. With this expanded ID * concept, the arbitration process is done based on the full 32-bit word, but the * actual transmitted ID still has 11-bit for standard frames and 29-bit for * extended frames. This bit can be written only in Freeze mode because it is blocked by * hardware in other modes. * * Values: * - 0 - Local Priority disabled. * - 1 - Local Priority enabled. */ /*@{*/ #define BP_CAN_MCR_LPRIOEN (13U) /*!< Bit position for CAN_MCR_LPRIOEN. */ #define BM_CAN_MCR_LPRIOEN (0x00002000U) /*!< Bit mask for CAN_MCR_LPRIOEN. */ #define BS_CAN_MCR_LPRIOEN (1U) /*!< Bit field size in bits for CAN_MCR_LPRIOEN. */ /*! @brief Read current value of the CAN_MCR_LPRIOEN field. */ #define BR_CAN_MCR_LPRIOEN(x) (BITBAND_ACCESS32(HW_CAN_MCR_ADDR(x), BP_CAN_MCR_LPRIOEN)) /*! @brief Format value for bitfield CAN_MCR_LPRIOEN. */ #define BF_CAN_MCR_LPRIOEN(v) ((uint32_t)((uint32_t)(v) << BP_CAN_MCR_LPRIOEN) & BM_CAN_MCR_LPRIOEN) /*! @brief Set the LPRIOEN field to a new value. */ #define BW_CAN_MCR_LPRIOEN(x, v) (BITBAND_ACCESS32(HW_CAN_MCR_ADDR(x), BP_CAN_MCR_LPRIOEN) = (v)) /*@}*/ /*! * @name Register CAN_MCR, field IRMQ[16] (RW) * * This bit indicates whether Rx matching process will be based either on * individual masking and queue or on masking scheme with RXMGMASK, RX14MASK and * RX15MASK, RXFGMASK. This bit can be written only in Freeze mode because it is * blocked by hardware in other modes. * * Values: * - 0 - Individual Rx masking and queue feature are disabled. For backward * compatibility with legacy applications, the reading of C/S word locks the MB * even if it is EMPTY. * - 1 - Individual Rx masking and queue feature are enabled. */ /*@{*/ #define BP_CAN_MCR_IRMQ (16U) /*!< Bit position for CAN_MCR_IRMQ. */ #define BM_CAN_MCR_IRMQ (0x00010000U) /*!< Bit mask for CAN_MCR_IRMQ. */ #define BS_CAN_MCR_IRMQ (1U) /*!< Bit field size in bits for CAN_MCR_IRMQ. */ /*! @brief Read current value of the CAN_MCR_IRMQ field. */ #define BR_CAN_MCR_IRMQ(x) (BITBAND_ACCESS32(HW_CAN_MCR_ADDR(x), BP_CAN_MCR_IRMQ)) /*! @brief Format value for bitfield CAN_MCR_IRMQ. */ #define BF_CAN_MCR_IRMQ(v) ((uint32_t)((uint32_t)(v) << BP_CAN_MCR_IRMQ) & BM_CAN_MCR_IRMQ) /*! @brief Set the IRMQ field to a new value. */ #define BW_CAN_MCR_IRMQ(x, v) (BITBAND_ACCESS32(HW_CAN_MCR_ADDR(x), BP_CAN_MCR_IRMQ) = (v)) /*@}*/ /*! * @name Register CAN_MCR, field SRXDIS[17] (RW) * * This bit defines whether FlexCAN is allowed to receive frames transmitted by * itself. If this bit is asserted, frames transmitted by the module will not be * stored in any MB, regardless if the MB is programmed with an ID that matches * the transmitted frame, and no interrupt flag or interrupt signal will be * generated due to the frame reception. This bit can be written only in Freeze mode * because it is blocked by hardware in other modes. * * Values: * - 0 - Self reception enabled. * - 1 - Self reception disabled. */ /*@{*/ #define BP_CAN_MCR_SRXDIS (17U) /*!< Bit position for CAN_MCR_SRXDIS. */ #define BM_CAN_MCR_SRXDIS (0x00020000U) /*!< Bit mask for CAN_MCR_SRXDIS. */ #define BS_CAN_MCR_SRXDIS (1U) /*!< Bit field size in bits for CAN_MCR_SRXDIS. */ /*! @brief Read current value of the CAN_MCR_SRXDIS field. */ #define BR_CAN_MCR_SRXDIS(x) (BITBAND_ACCESS32(HW_CAN_MCR_ADDR(x), BP_CAN_MCR_SRXDIS)) /*! @brief Format value for bitfield CAN_MCR_SRXDIS. */ #define BF_CAN_MCR_SRXDIS(v) ((uint32_t)((uint32_t)(v) << BP_CAN_MCR_SRXDIS) & BM_CAN_MCR_SRXDIS) /*! @brief Set the SRXDIS field to a new value. */ #define BW_CAN_MCR_SRXDIS(x, v) (BITBAND_ACCESS32(HW_CAN_MCR_ADDR(x), BP_CAN_MCR_SRXDIS) = (v)) /*@}*/ /*! * @name Register CAN_MCR, field WAKSRC[19] (RW) * * This bit defines whether the integrated low-pass filter is applied to protect * the Rx CAN input from spurious wake up. This bit can be written only in * Freeze mode because it is blocked by hardware in other modes. * * Values: * - 0 - FlexCAN uses the unfiltered Rx input to detect recessive to dominant * edges on the CAN bus. * - 1 - FlexCAN uses the filtered Rx input to detect recessive to dominant * edges on the CAN bus. */ /*@{*/ #define BP_CAN_MCR_WAKSRC (19U) /*!< Bit position for CAN_MCR_WAKSRC. */ #define BM_CAN_MCR_WAKSRC (0x00080000U) /*!< Bit mask for CAN_MCR_WAKSRC. */ #define BS_CAN_MCR_WAKSRC (1U) /*!< Bit field size in bits for CAN_MCR_WAKSRC. */ /*! @brief Read current value of the CAN_MCR_WAKSRC field. */ #define BR_CAN_MCR_WAKSRC(x) (BITBAND_ACCESS32(HW_CAN_MCR_ADDR(x), BP_CAN_MCR_WAKSRC)) /*! @brief Format value for bitfield CAN_MCR_WAKSRC. */ #define BF_CAN_MCR_WAKSRC(v) ((uint32_t)((uint32_t)(v) << BP_CAN_MCR_WAKSRC) & BM_CAN_MCR_WAKSRC) /*! @brief Set the WAKSRC field to a new value. */ #define BW_CAN_MCR_WAKSRC(x, v) (BITBAND_ACCESS32(HW_CAN_MCR_ADDR(x), BP_CAN_MCR_WAKSRC) = (v)) /*@}*/ /*! * @name Register CAN_MCR, field LPMACK[20] (RO) * * This read-only bit indicates that FlexCAN is in a low-power mode (Disable * mode , Stop mode ). A low-power mode cannot be entered until all current * transmission or reception processes have finished, so the CPU can poll the LPMACK bit * to know when FlexCAN has actually entered low power mode. LPMACK will be * asserted within 180 CAN bits from the low-power mode request by the CPU, and * negated within 2 CAN bits after the low-power mode request removal (see Section * "Protocol Timing"). * * Values: * - 0 - FlexCAN is not in a low-power mode. * - 1 - FlexCAN is in a low-power mode. */ /*@{*/ #define BP_CAN_MCR_LPMACK (20U) /*!< Bit position for CAN_MCR_LPMACK. */ #define BM_CAN_MCR_LPMACK (0x00100000U) /*!< Bit mask for CAN_MCR_LPMACK. */ #define BS_CAN_MCR_LPMACK (1U) /*!< Bit field size in bits for CAN_MCR_LPMACK. */ /*! @brief Read current value of the CAN_MCR_LPMACK field. */ #define BR_CAN_MCR_LPMACK(x) (BITBAND_ACCESS32(HW_CAN_MCR_ADDR(x), BP_CAN_MCR_LPMACK)) /*@}*/ /*! * @name Register CAN_MCR, field WRNEN[21] (RW) * * When asserted, this bit enables the generation of the TWRNINT and RWRNINT * flags in the Error and Status Register. If WRNEN is negated, the TWRNINT and * RWRNINT flags will always be zero, independent of the values of the error * counters, and no warning interrupt will ever be generated. This bit can be written * only in Freeze mode because it is blocked by hardware in other modes. * * Values: * - 0 - TWRNINT and RWRNINT bits are zero, independent of the values in the * error counters. * - 1 - TWRNINT and RWRNINT bits are set when the respective error counter * transitions from less than 96 to greater than or equal to 96. */ /*@{*/ #define BP_CAN_MCR_WRNEN (21U) /*!< Bit position for CAN_MCR_WRNEN. */ #define BM_CAN_MCR_WRNEN (0x00200000U) /*!< Bit mask for CAN_MCR_WRNEN. */ #define BS_CAN_MCR_WRNEN (1U) /*!< Bit field size in bits for CAN_MCR_WRNEN. */ /*! @brief Read current value of the CAN_MCR_WRNEN field. */ #define BR_CAN_MCR_WRNEN(x) (BITBAND_ACCESS32(HW_CAN_MCR_ADDR(x), BP_CAN_MCR_WRNEN)) /*! @brief Format value for bitfield CAN_MCR_WRNEN. */ #define BF_CAN_MCR_WRNEN(v) ((uint32_t)((uint32_t)(v) << BP_CAN_MCR_WRNEN) & BM_CAN_MCR_WRNEN) /*! @brief Set the WRNEN field to a new value. */ #define BW_CAN_MCR_WRNEN(x, v) (BITBAND_ACCESS32(HW_CAN_MCR_ADDR(x), BP_CAN_MCR_WRNEN) = (v)) /*@}*/ /*! * @name Register CAN_MCR, field SLFWAK[22] (RW) * * This bit enables the Self Wake Up feature when FlexCAN is in a low-power mode * other than Disable mode. When this feature is enabled, the FlexCAN module * monitors the bus for wake up event, that is, a recessive-to-dominant transition. * If a wake up event is detected during Stop mode, then FlexCAN generates, if * enabled to do so, a Wake Up interrupt to the CPU so that it can exit Stop mode * globally and FlexCAN can request to resume the clocks. When FlexCAN is in a * low-power mode other than Disable mode, this bit cannot be written as it is * blocked by hardware. * * Values: * - 0 - FlexCAN Self Wake Up feature is disabled. * - 1 - FlexCAN Self Wake Up feature is enabled. */ /*@{*/ #define BP_CAN_MCR_SLFWAK (22U) /*!< Bit position for CAN_MCR_SLFWAK. */ #define BM_CAN_MCR_SLFWAK (0x00400000U) /*!< Bit mask for CAN_MCR_SLFWAK. */ #define BS_CAN_MCR_SLFWAK (1U) /*!< Bit field size in bits for CAN_MCR_SLFWAK. */ /*! @brief Read current value of the CAN_MCR_SLFWAK field. */ #define BR_CAN_MCR_SLFWAK(x) (BITBAND_ACCESS32(HW_CAN_MCR_ADDR(x), BP_CAN_MCR_SLFWAK)) /*! @brief Format value for bitfield CAN_MCR_SLFWAK. */ #define BF_CAN_MCR_SLFWAK(v) ((uint32_t)((uint32_t)(v) << BP_CAN_MCR_SLFWAK) & BM_CAN_MCR_SLFWAK) /*! @brief Set the SLFWAK field to a new value. */ #define BW_CAN_MCR_SLFWAK(x, v) (BITBAND_ACCESS32(HW_CAN_MCR_ADDR(x), BP_CAN_MCR_SLFWAK) = (v)) /*@}*/ /*! * @name Register CAN_MCR, field SUPV[23] (RW) * * This bit configures the FlexCAN to be either in Supervisor or User mode. The * registers affected by this bit are marked as S/U in the Access Type column of * the module memory map. Reset value of this bit is 1, so the affected registers * start with Supervisor access allowance only . This bit can be written only in * Freeze mode because it is blocked by hardware in other modes. * * Values: * - 0 - FlexCAN is in User mode. Affected registers allow both Supervisor and * Unrestricted accesses . * - 1 - FlexCAN is in Supervisor mode. Affected registers allow only Supervisor * access. Unrestricted access behaves as though the access was done to an * unimplemented register location . */ /*@{*/ #define BP_CAN_MCR_SUPV (23U) /*!< Bit position for CAN_MCR_SUPV. */ #define BM_CAN_MCR_SUPV (0x00800000U) /*!< Bit mask for CAN_MCR_SUPV. */ #define BS_CAN_MCR_SUPV (1U) /*!< Bit field size in bits for CAN_MCR_SUPV. */ /*! @brief Read current value of the CAN_MCR_SUPV field. */ #define BR_CAN_MCR_SUPV(x) (BITBAND_ACCESS32(HW_CAN_MCR_ADDR(x), BP_CAN_MCR_SUPV)) /*! @brief Format value for bitfield CAN_MCR_SUPV. */ #define BF_CAN_MCR_SUPV(v) ((uint32_t)((uint32_t)(v) << BP_CAN_MCR_SUPV) & BM_CAN_MCR_SUPV) /*! @brief Set the SUPV field to a new value. */ #define BW_CAN_MCR_SUPV(x, v) (BITBAND_ACCESS32(HW_CAN_MCR_ADDR(x), BP_CAN_MCR_SUPV) = (v)) /*@}*/ /*! * @name Register CAN_MCR, field FRZACK[24] (RO) * * This read-only bit indicates that FlexCAN is in Freeze mode and its prescaler * is stopped. The Freeze mode request cannot be granted until current * transmission or reception processes have finished. Therefore the software can poll the * FRZACK bit to know when FlexCAN has actually entered Freeze mode. If Freeze * Mode request is negated, then this bit is negated after the FlexCAN prescaler is * running again. If Freeze mode is requested while FlexCAN is in a low power * mode, then the FRZACK bit will be set only when the low-power mode is exited. * See Section "Freeze Mode". FRZACK will be asserted within 178 CAN bits from the * freeze mode request by the CPU, and negated within 2 CAN bits after the freeze * mode request removal (see Section "Protocol Timing"). * * Values: * - 0 - FlexCAN not in Freeze mode, prescaler running. * - 1 - FlexCAN in Freeze mode, prescaler stopped. */ /*@{*/ #define BP_CAN_MCR_FRZACK (24U) /*!< Bit position for CAN_MCR_FRZACK. */ #define BM_CAN_MCR_FRZACK (0x01000000U) /*!< Bit mask for CAN_MCR_FRZACK. */ #define BS_CAN_MCR_FRZACK (1U) /*!< Bit field size in bits for CAN_MCR_FRZACK. */ /*! @brief Read current value of the CAN_MCR_FRZACK field. */ #define BR_CAN_MCR_FRZACK(x) (BITBAND_ACCESS32(HW_CAN_MCR_ADDR(x), BP_CAN_MCR_FRZACK)) /*@}*/ /*! * @name Register CAN_MCR, field SOFTRST[25] (RW) * * When this bit is asserted, FlexCAN resets its internal state machines and * some of the memory mapped registers. The following registers are reset: MCR * (except the MDIS bit), TIMER , ECR, ESR1, ESR2, IMASK1, IMASK2, IFLAG1, IFLAG2 and * CRCR. Configuration registers that control the interface to the CAN bus are * not affected by soft reset. The following registers are unaffected: CTRL1, * CTRL2, all RXIMR registers, RXMGMASK, RX14MASK, RX15MASK, RXFGMASK, RXFIR, all * Message Buffers . The SOFTRST bit can be asserted directly by the CPU when it * writes to the MCR Register, but it is also asserted when global soft reset is * requested at MCU level . Because soft reset is synchronous and has to follow a * request/acknowledge procedure across clock domains, it may take some time to * fully propagate its effect. The SOFTRST bit remains asserted while reset is * pending, and is automatically negated when reset completes. Therefore, software can * poll this bit to know when the soft reset has completed. Soft reset cannot be * applied while clocks are shut down in a low power mode. The module should be * first removed from low power mode, and then soft reset can be applied. * * Values: * - 0 - No reset request. * - 1 - Resets the registers affected by soft reset. */ /*@{*/ #define BP_CAN_MCR_SOFTRST (25U) /*!< Bit position for CAN_MCR_SOFTRST. */ #define BM_CAN_MCR_SOFTRST (0x02000000U) /*!< Bit mask for CAN_MCR_SOFTRST. */ #define BS_CAN_MCR_SOFTRST (1U) /*!< Bit field size in bits for CAN_MCR_SOFTRST. */ /*! @brief Read current value of the CAN_MCR_SOFTRST field. */ #define BR_CAN_MCR_SOFTRST(x) (BITBAND_ACCESS32(HW_CAN_MCR_ADDR(x), BP_CAN_MCR_SOFTRST)) /*! @brief Format value for bitfield CAN_MCR_SOFTRST. */ #define BF_CAN_MCR_SOFTRST(v) ((uint32_t)((uint32_t)(v) << BP_CAN_MCR_SOFTRST) & BM_CAN_MCR_SOFTRST) /*! @brief Set the SOFTRST field to a new value. */ #define BW_CAN_MCR_SOFTRST(x, v) (BITBAND_ACCESS32(HW_CAN_MCR_ADDR(x), BP_CAN_MCR_SOFTRST) = (v)) /*@}*/ /*! * @name Register CAN_MCR, field WAKMSK[26] (RW) * * This bit enables the Wake Up Interrupt generation under Self Wake Up * mechanism. * * Values: * - 0 - Wake Up Interrupt is disabled. * - 1 - Wake Up Interrupt is enabled. */ /*@{*/ #define BP_CAN_MCR_WAKMSK (26U) /*!< Bit position for CAN_MCR_WAKMSK. */ #define BM_CAN_MCR_WAKMSK (0x04000000U) /*!< Bit mask for CAN_MCR_WAKMSK. */ #define BS_CAN_MCR_WAKMSK (1U) /*!< Bit field size in bits for CAN_MCR_WAKMSK. */ /*! @brief Read current value of the CAN_MCR_WAKMSK field. */ #define BR_CAN_MCR_WAKMSK(x) (BITBAND_ACCESS32(HW_CAN_MCR_ADDR(x), BP_CAN_MCR_WAKMSK)) /*! @brief Format value for bitfield CAN_MCR_WAKMSK. */ #define BF_CAN_MCR_WAKMSK(v) ((uint32_t)((uint32_t)(v) << BP_CAN_MCR_WAKMSK) & BM_CAN_MCR_WAKMSK) /*! @brief Set the WAKMSK field to a new value. */ #define BW_CAN_MCR_WAKMSK(x, v) (BITBAND_ACCESS32(HW_CAN_MCR_ADDR(x), BP_CAN_MCR_WAKMSK) = (v)) /*@}*/ /*! * @name Register CAN_MCR, field NOTRDY[27] (RO) * * This read-only bit indicates that FlexCAN is either in Disable mode , Stop * mode or Freeze mode. It is negated once FlexCAN has exited these modes. * * Values: * - 0 - FlexCAN module is either in Normal mode, Listen-Only mode or Loop-Back * mode. * - 1 - FlexCAN module is either in Disable mode , Stop mode or Freeze mode. */ /*@{*/ #define BP_CAN_MCR_NOTRDY (27U) /*!< Bit position for CAN_MCR_NOTRDY. */ #define BM_CAN_MCR_NOTRDY (0x08000000U) /*!< Bit mask for CAN_MCR_NOTRDY. */ #define BS_CAN_MCR_NOTRDY (1U) /*!< Bit field size in bits for CAN_MCR_NOTRDY. */ /*! @brief Read current value of the CAN_MCR_NOTRDY field. */ #define BR_CAN_MCR_NOTRDY(x) (BITBAND_ACCESS32(HW_CAN_MCR_ADDR(x), BP_CAN_MCR_NOTRDY)) /*@}*/ /*! * @name Register CAN_MCR, field HALT[28] (RW) * * Assertion of this bit puts the FlexCAN module into Freeze mode. The CPU * should clear it after initializing the Message Buffers and Control Register. No * reception or transmission is performed by FlexCAN before this bit is cleared. * Freeze mode cannot be entered while FlexCAN is in a low power mode. * * Values: * - 0 - No Freeze mode request. * - 1 - Enters Freeze mode if the FRZ bit is asserted. */ /*@{*/ #define BP_CAN_MCR_HALT (28U) /*!< Bit position for CAN_MCR_HALT. */ #define BM_CAN_MCR_HALT (0x10000000U) /*!< Bit mask for CAN_MCR_HALT. */ #define BS_CAN_MCR_HALT (1U) /*!< Bit field size in bits for CAN_MCR_HALT. */ /*! @brief Read current value of the CAN_MCR_HALT field. */ #define BR_CAN_MCR_HALT(x) (BITBAND_ACCESS32(HW_CAN_MCR_ADDR(x), BP_CAN_MCR_HALT)) /*! @brief Format value for bitfield CAN_MCR_HALT. */ #define BF_CAN_MCR_HALT(v) ((uint32_t)((uint32_t)(v) << BP_CAN_MCR_HALT) & BM_CAN_MCR_HALT) /*! @brief Set the HALT field to a new value. */ #define BW_CAN_MCR_HALT(x, v) (BITBAND_ACCESS32(HW_CAN_MCR_ADDR(x), BP_CAN_MCR_HALT) = (v)) /*@}*/ /*! * @name Register CAN_MCR, field RFEN[29] (RW) * * This bit controls whether the Rx FIFO feature is enabled or not. When RFEN is * set, MBs 0 to 5 cannot be used for normal reception and transmission because * the corresponding memory region (0x80-0xDC) is used by the FIFO engine as well * as additional MBs (up to 32, depending on CTRL2[RFFN] setting) which are used * as Rx FIFO ID Filter Table elements. RFEN also impacts the definition of the * minimum number of peripheral clocks per CAN bit as described in the table * "Minimum Ratio Between Peripheral Clock Frequency and CAN Bit Rate" (in section * "Arbitration and Matching Timing"). This bit can be written only in Freeze mode * because it is blocked by hardware in other modes. * * Values: * - 0 - Rx FIFO not enabled. * - 1 - Rx FIFO enabled. */ /*@{*/ #define BP_CAN_MCR_RFEN (29U) /*!< Bit position for CAN_MCR_RFEN. */ #define BM_CAN_MCR_RFEN (0x20000000U) /*!< Bit mask for CAN_MCR_RFEN. */ #define BS_CAN_MCR_RFEN (1U) /*!< Bit field size in bits for CAN_MCR_RFEN. */ /*! @brief Read current value of the CAN_MCR_RFEN field. */ #define BR_CAN_MCR_RFEN(x) (BITBAND_ACCESS32(HW_CAN_MCR_ADDR(x), BP_CAN_MCR_RFEN)) /*! @brief Format value for bitfield CAN_MCR_RFEN. */ #define BF_CAN_MCR_RFEN(v) ((uint32_t)((uint32_t)(v) << BP_CAN_MCR_RFEN) & BM_CAN_MCR_RFEN) /*! @brief Set the RFEN field to a new value. */ #define BW_CAN_MCR_RFEN(x, v) (BITBAND_ACCESS32(HW_CAN_MCR_ADDR(x), BP_CAN_MCR_RFEN) = (v)) /*@}*/ /*! * @name Register CAN_MCR, field FRZ[30] (RW) * * The FRZ bit specifies the FlexCAN behavior when the HALT bit in the MCR * Register is set or when Debug mode is requested at MCU level . When FRZ is * asserted, FlexCAN is enabled to enter Freeze mode. Negation of this bit field causes * FlexCAN to exit from Freeze mode. * * Values: * - 0 - Not enabled to enter Freeze mode. * - 1 - Enabled to enter Freeze mode. */ /*@{*/ #define BP_CAN_MCR_FRZ (30U) /*!< Bit position for CAN_MCR_FRZ. */ #define BM_CAN_MCR_FRZ (0x40000000U) /*!< Bit mask for CAN_MCR_FRZ. */ #define BS_CAN_MCR_FRZ (1U) /*!< Bit field size in bits for CAN_MCR_FRZ. */ /*! @brief Read current value of the CAN_MCR_FRZ field. */ #define BR_CAN_MCR_FRZ(x) (BITBAND_ACCESS32(HW_CAN_MCR_ADDR(x), BP_CAN_MCR_FRZ)) /*! @brief Format value for bitfield CAN_MCR_FRZ. */ #define BF_CAN_MCR_FRZ(v) ((uint32_t)((uint32_t)(v) << BP_CAN_MCR_FRZ) & BM_CAN_MCR_FRZ) /*! @brief Set the FRZ field to a new value. */ #define BW_CAN_MCR_FRZ(x, v) (BITBAND_ACCESS32(HW_CAN_MCR_ADDR(x), BP_CAN_MCR_FRZ) = (v)) /*@}*/ /*! * @name Register CAN_MCR, field MDIS[31] (RW) * * This bit controls whether FlexCAN is enabled or not. When disabled, FlexCAN * disables the clocks to the CAN Protocol Engine and Controller Host Interface * sub-modules. This is the only bit within this register not affected by soft * reset. * * Values: * - 0 - Enable the FlexCAN module. * - 1 - Disable the FlexCAN module. */ /*@{*/ #define BP_CAN_MCR_MDIS (31U) /*!< Bit position for CAN_MCR_MDIS. */ #define BM_CAN_MCR_MDIS (0x80000000U) /*!< Bit mask for CAN_MCR_MDIS. */ #define BS_CAN_MCR_MDIS (1U) /*!< Bit field size in bits for CAN_MCR_MDIS. */ /*! @brief Read current value of the CAN_MCR_MDIS field. */ #define BR_CAN_MCR_MDIS(x) (BITBAND_ACCESS32(HW_CAN_MCR_ADDR(x), BP_CAN_MCR_MDIS)) /*! @brief Format value for bitfield CAN_MCR_MDIS. */ #define BF_CAN_MCR_MDIS(v) ((uint32_t)((uint32_t)(v) << BP_CAN_MCR_MDIS) & BM_CAN_MCR_MDIS) /*! @brief Set the MDIS field to a new value. */ #define BW_CAN_MCR_MDIS(x, v) (BITBAND_ACCESS32(HW_CAN_MCR_ADDR(x), BP_CAN_MCR_MDIS) = (v)) /*@}*/ /******************************************************************************* * HW_CAN_CTRL1 - Control 1 register ******************************************************************************/ /*! * @brief HW_CAN_CTRL1 - Control 1 register (RW) * * Reset value: 0x00000000U * * This register is defined for specific FlexCAN control features related to the * CAN bus, such as bit-rate, programmable sampling point within an Rx bit, Loop * Back mode, Listen-Only mode, Bus Off recovery behavior and interrupt enabling * (Bus-Off, Error, Warning). It also determines the Division Factor for the * clock prescaler. */ typedef union _hw_can_ctrl1 { uint32_t U; struct _hw_can_ctrl1_bitfields { uint32_t PROPSEG : 3; /*!< [2:0] Propagation Segment */ uint32_t LOM : 1; /*!< [3] Listen-Only Mode */ uint32_t LBUF : 1; /*!< [4] Lowest Buffer Transmitted First */ uint32_t TSYN : 1; /*!< [5] Timer Sync */ uint32_t BOFFREC : 1; /*!< [6] Bus Off Recovery */ uint32_t SMP : 1; /*!< [7] CAN Bit Sampling */ uint32_t RESERVED0 : 2; /*!< [9:8] */ uint32_t RWRNMSK : 1; /*!< [10] Rx Warning Interrupt Mask */ uint32_t TWRNMSK : 1; /*!< [11] Tx Warning Interrupt Mask */ uint32_t LPB : 1; /*!< [12] Loop Back Mode */ uint32_t CLKSRC : 1; /*!< [13] CAN Engine Clock Source */ uint32_t ERRMSK : 1; /*!< [14] Error Mask */ uint32_t BOFFMSK : 1; /*!< [15] Bus Off Mask */ uint32_t PSEG2 : 3; /*!< [18:16] Phase Segment 2 */ uint32_t PSEG1 : 3; /*!< [21:19] Phase Segment 1 */ uint32_t RJW : 2; /*!< [23:22] Resync Jump Width */ uint32_t PRESDIV : 8; /*!< [31:24] Prescaler Division Factor */ } B; } hw_can_ctrl1_t; /*! * @name Constants and macros for entire CAN_CTRL1 register */ /*@{*/ #define HW_CAN_CTRL1_ADDR(x) ((x) + 0x4U) #define HW_CAN_CTRL1(x) (*(__IO hw_can_ctrl1_t *) HW_CAN_CTRL1_ADDR(x)) #define HW_CAN_CTRL1_RD(x) (HW_CAN_CTRL1(x).U) #define HW_CAN_CTRL1_WR(x, v) (HW_CAN_CTRL1(x).U = (v)) #define HW_CAN_CTRL1_SET(x, v) (HW_CAN_CTRL1_WR(x, HW_CAN_CTRL1_RD(x) | (v))) #define HW_CAN_CTRL1_CLR(x, v) (HW_CAN_CTRL1_WR(x, HW_CAN_CTRL1_RD(x) & ~(v))) #define HW_CAN_CTRL1_TOG(x, v) (HW_CAN_CTRL1_WR(x, HW_CAN_CTRL1_RD(x) ^ (v))) /*@}*/ /* * Constants & macros for individual CAN_CTRL1 bitfields */ /*! * @name Register CAN_CTRL1, field PROPSEG[2:0] (RW) * * This 3-bit field defines the length of the Propagation Segment in the bit * time. The valid programmable values are 0-7. This field can be written only in * Freeze mode because it is blocked by hardware in other modes. Propagation * Segment Time = (PROPSEG + 1) * Time-Quanta. Time-Quantum = one Sclock period. */ /*@{*/ #define BP_CAN_CTRL1_PROPSEG (0U) /*!< Bit position for CAN_CTRL1_PROPSEG. */ #define BM_CAN_CTRL1_PROPSEG (0x00000007U) /*!< Bit mask for CAN_CTRL1_PROPSEG. */ #define BS_CAN_CTRL1_PROPSEG (3U) /*!< Bit field size in bits for CAN_CTRL1_PROPSEG. */ /*! @brief Read current value of the CAN_CTRL1_PROPSEG field. */ #define BR_CAN_CTRL1_PROPSEG(x) (HW_CAN_CTRL1(x).B.PROPSEG) /*! @brief Format value for bitfield CAN_CTRL1_PROPSEG. */ #define BF_CAN_CTRL1_PROPSEG(v) ((uint32_t)((uint32_t)(v) << BP_CAN_CTRL1_PROPSEG) & BM_CAN_CTRL1_PROPSEG) /*! @brief Set the PROPSEG field to a new value. */ #define BW_CAN_CTRL1_PROPSEG(x, v) (HW_CAN_CTRL1_WR(x, (HW_CAN_CTRL1_RD(x) & ~BM_CAN_CTRL1_PROPSEG) | BF_CAN_CTRL1_PROPSEG(v))) /*@}*/ /*! * @name Register CAN_CTRL1, field LOM[3] (RW) * * This bit configures FlexCAN to operate in Listen-Only mode. In this mode, * transmission is disabled, all error counters are frozen and the module operates * in a CAN Error Passive mode. Only messages acknowledged by another CAN station * will be received. If FlexCAN detects a message that has not been acknowledged, * it will flag a BIT0 error without changing the REC, as if it was trying to * acknowledge the message. Listen-Only mode acknowledgement can be obtained by the * state of ESR1[FLTCONF] field which is Passive Error when Listen-Only mode is * entered. There can be some delay between the Listen-Only mode request and * acknowledge. This bit can be written only in Freeze mode because it is blocked by * hardware in other modes. * * Values: * - 0 - Listen-Only mode is deactivated. * - 1 - FlexCAN module operates in Listen-Only mode. */ /*@{*/ #define BP_CAN_CTRL1_LOM (3U) /*!< Bit position for CAN_CTRL1_LOM. */ #define BM_CAN_CTRL1_LOM (0x00000008U) /*!< Bit mask for CAN_CTRL1_LOM. */ #define BS_CAN_CTRL1_LOM (1U) /*!< Bit field size in bits for CAN_CTRL1_LOM. */ /*! @brief Read current value of the CAN_CTRL1_LOM field. */ #define BR_CAN_CTRL1_LOM(x) (BITBAND_ACCESS32(HW_CAN_CTRL1_ADDR(x), BP_CAN_CTRL1_LOM)) /*! @brief Format value for bitfield CAN_CTRL1_LOM. */ #define BF_CAN_CTRL1_LOM(v) ((uint32_t)((uint32_t)(v) << BP_CAN_CTRL1_LOM) & BM_CAN_CTRL1_LOM) /*! @brief Set the LOM field to a new value. */ #define BW_CAN_CTRL1_LOM(x, v) (BITBAND_ACCESS32(HW_CAN_CTRL1_ADDR(x), BP_CAN_CTRL1_LOM) = (v)) /*@}*/ /*! * @name Register CAN_CTRL1, field LBUF[4] (RW) * * This bit defines the ordering mechanism for Message Buffer transmission. When * asserted, the LPRIOEN bit does not affect the priority arbitration. This bit * can be written only in Freeze mode because it is blocked by hardware in other * modes. * * Values: * - 0 - Buffer with highest priority is transmitted first. * - 1 - Lowest number buffer is transmitted first. */ /*@{*/ #define BP_CAN_CTRL1_LBUF (4U) /*!< Bit position for CAN_CTRL1_LBUF. */ #define BM_CAN_CTRL1_LBUF (0x00000010U) /*!< Bit mask for CAN_CTRL1_LBUF. */ #define BS_CAN_CTRL1_LBUF (1U) /*!< Bit field size in bits for CAN_CTRL1_LBUF. */ /*! @brief Read current value of the CAN_CTRL1_LBUF field. */ #define BR_CAN_CTRL1_LBUF(x) (BITBAND_ACCESS32(HW_CAN_CTRL1_ADDR(x), BP_CAN_CTRL1_LBUF)) /*! @brief Format value for bitfield CAN_CTRL1_LBUF. */ #define BF_CAN_CTRL1_LBUF(v) ((uint32_t)((uint32_t)(v) << BP_CAN_CTRL1_LBUF) & BM_CAN_CTRL1_LBUF) /*! @brief Set the LBUF field to a new value. */ #define BW_CAN_CTRL1_LBUF(x, v) (BITBAND_ACCESS32(HW_CAN_CTRL1_ADDR(x), BP_CAN_CTRL1_LBUF) = (v)) /*@}*/ /*! * @name Register CAN_CTRL1, field TSYN[5] (RW) * * This bit enables a mechanism that resets the free-running timer each time a * message is received in Message Buffer 0. This feature provides means to * synchronize multiple FlexCAN stations with a special "SYNC" message, that is, global * network time. If the RFEN bit in MCR is set (Rx FIFO enabled), the first * available Mailbox, according to CTRL2[RFFN] setting, is used for timer * synchronization instead of MB0. This bit can be written only in Freeze mode because it is * blocked by hardware in other modes. * * Values: * - 0 - Timer Sync feature disabled * - 1 - Timer Sync feature enabled */ /*@{*/ #define BP_CAN_CTRL1_TSYN (5U) /*!< Bit position for CAN_CTRL1_TSYN. */ #define BM_CAN_CTRL1_TSYN (0x00000020U) /*!< Bit mask for CAN_CTRL1_TSYN. */ #define BS_CAN_CTRL1_TSYN (1U) /*!< Bit field size in bits for CAN_CTRL1_TSYN. */ /*! @brief Read current value of the CAN_CTRL1_TSYN field. */ #define BR_CAN_CTRL1_TSYN(x) (BITBAND_ACCESS32(HW_CAN_CTRL1_ADDR(x), BP_CAN_CTRL1_TSYN)) /*! @brief Format value for bitfield CAN_CTRL1_TSYN. */ #define BF_CAN_CTRL1_TSYN(v) ((uint32_t)((uint32_t)(v) << BP_CAN_CTRL1_TSYN) & BM_CAN_CTRL1_TSYN) /*! @brief Set the TSYN field to a new value. */ #define BW_CAN_CTRL1_TSYN(x, v) (BITBAND_ACCESS32(HW_CAN_CTRL1_ADDR(x), BP_CAN_CTRL1_TSYN) = (v)) /*@}*/ /*! * @name Register CAN_CTRL1, field BOFFREC[6] (RW) * * This bit defines how FlexCAN recovers from Bus Off state. If this bit is * negated, automatic recovering from Bus Off state occurs according to the CAN * Specification 2.0B. If the bit is asserted, automatic recovering from Bus Off is * disabled and the module remains in Bus Off state until the bit is negated by the * user. If the negation occurs before 128 sequences of 11 recessive bits are * detected on the CAN bus, then Bus Off recovery happens as if the BOFFREC bit had * never been asserted. If the negation occurs after 128 sequences of 11 * recessive bits occurred, then FlexCAN will re-synchronize to the bus by waiting for * 11 recessive bits before joining the bus. After negation, the BOFFREC bit can * be re-asserted again during Bus Off, but it will be effective only the next * time the module enters Bus Off. If BOFFREC was negated when the module entered * Bus Off, asserting it during Bus Off will not be effective for the current Bus * Off recovery. * * Values: * - 0 - Automatic recovering from Bus Off state enabled, according to CAN Spec * 2.0 part B. * - 1 - Automatic recovering from Bus Off state disabled. */ /*@{*/ #define BP_CAN_CTRL1_BOFFREC (6U) /*!< Bit position for CAN_CTRL1_BOFFREC. */ #define BM_CAN_CTRL1_BOFFREC (0x00000040U) /*!< Bit mask for CAN_CTRL1_BOFFREC. */ #define BS_CAN_CTRL1_BOFFREC (1U) /*!< Bit field size in bits for CAN_CTRL1_BOFFREC. */ /*! @brief Read current value of the CAN_CTRL1_BOFFREC field. */ #define BR_CAN_CTRL1_BOFFREC(x) (BITBAND_ACCESS32(HW_CAN_CTRL1_ADDR(x), BP_CAN_CTRL1_BOFFREC)) /*! @brief Format value for bitfield CAN_CTRL1_BOFFREC. */ #define BF_CAN_CTRL1_BOFFREC(v) ((uint32_t)((uint32_t)(v) << BP_CAN_CTRL1_BOFFREC) & BM_CAN_CTRL1_BOFFREC) /*! @brief Set the BOFFREC field to a new value. */ #define BW_CAN_CTRL1_BOFFREC(x, v) (BITBAND_ACCESS32(HW_CAN_CTRL1_ADDR(x), BP_CAN_CTRL1_BOFFREC) = (v)) /*@}*/ /*! * @name Register CAN_CTRL1, field SMP[7] (RW) * * This bit defines the sampling mode of CAN bits at the Rx input. This bit can * be written only in Freeze mode because it is blocked by hardware in other * modes. * * Values: * - 0 - Just one sample is used to determine the bit value. * - 1 - Three samples are used to determine the value of the received bit: the * regular one (sample point) and 2 preceding samples; a majority rule is * used. */ /*@{*/ #define BP_CAN_CTRL1_SMP (7U) /*!< Bit position for CAN_CTRL1_SMP. */ #define BM_CAN_CTRL1_SMP (0x00000080U) /*!< Bit mask for CAN_CTRL1_SMP. */ #define BS_CAN_CTRL1_SMP (1U) /*!< Bit field size in bits for CAN_CTRL1_SMP. */ /*! @brief Read current value of the CAN_CTRL1_SMP field. */ #define BR_CAN_CTRL1_SMP(x) (BITBAND_ACCESS32(HW_CAN_CTRL1_ADDR(x), BP_CAN_CTRL1_SMP)) /*! @brief Format value for bitfield CAN_CTRL1_SMP. */ #define BF_CAN_CTRL1_SMP(v) ((uint32_t)((uint32_t)(v) << BP_CAN_CTRL1_SMP) & BM_CAN_CTRL1_SMP) /*! @brief Set the SMP field to a new value. */ #define BW_CAN_CTRL1_SMP(x, v) (BITBAND_ACCESS32(HW_CAN_CTRL1_ADDR(x), BP_CAN_CTRL1_SMP) = (v)) /*@}*/ /*! * @name Register CAN_CTRL1, field RWRNMSK[10] (RW) * * This bit provides a mask for the Rx Warning Interrupt associated with the * RWRNINT flag in the Error and Status Register. This bit is read as zero when * MCR[WRNEN] bit is negated. This bit can be written only if MCR[WRNEN] bit is * asserted. * * Values: * - 0 - Rx Warning Interrupt disabled. * - 1 - Rx Warning Interrupt enabled. */ /*@{*/ #define BP_CAN_CTRL1_RWRNMSK (10U) /*!< Bit position for CAN_CTRL1_RWRNMSK. */ #define BM_CAN_CTRL1_RWRNMSK (0x00000400U) /*!< Bit mask for CAN_CTRL1_RWRNMSK. */ #define BS_CAN_CTRL1_RWRNMSK (1U) /*!< Bit field size in bits for CAN_CTRL1_RWRNMSK. */ /*! @brief Read current value of the CAN_CTRL1_RWRNMSK field. */ #define BR_CAN_CTRL1_RWRNMSK(x) (BITBAND_ACCESS32(HW_CAN_CTRL1_ADDR(x), BP_CAN_CTRL1_RWRNMSK)) /*! @brief Format value for bitfield CAN_CTRL1_RWRNMSK. */ #define BF_CAN_CTRL1_RWRNMSK(v) ((uint32_t)((uint32_t)(v) << BP_CAN_CTRL1_RWRNMSK) & BM_CAN_CTRL1_RWRNMSK) /*! @brief Set the RWRNMSK field to a new value. */ #define BW_CAN_CTRL1_RWRNMSK(x, v) (BITBAND_ACCESS32(HW_CAN_CTRL1_ADDR(x), BP_CAN_CTRL1_RWRNMSK) = (v)) /*@}*/ /*! * @name Register CAN_CTRL1, field TWRNMSK[11] (RW) * * This bit provides a mask for the Tx Warning Interrupt associated with the * TWRNINT flag in the Error and Status Register. This bit is read as zero when * MCR[WRNEN] bit is negated. This bit can be written only if MCR[WRNEN] bit is * asserted. * * Values: * - 0 - Tx Warning Interrupt disabled. * - 1 - Tx Warning Interrupt enabled. */ /*@{*/ #define BP_CAN_CTRL1_TWRNMSK (11U) /*!< Bit position for CAN_CTRL1_TWRNMSK. */ #define BM_CAN_CTRL1_TWRNMSK (0x00000800U) /*!< Bit mask for CAN_CTRL1_TWRNMSK. */ #define BS_CAN_CTRL1_TWRNMSK (1U) /*!< Bit field size in bits for CAN_CTRL1_TWRNMSK. */ /*! @brief Read current value of the CAN_CTRL1_TWRNMSK field. */ #define BR_CAN_CTRL1_TWRNMSK(x) (BITBAND_ACCESS32(HW_CAN_CTRL1_ADDR(x), BP_CAN_CTRL1_TWRNMSK)) /*! @brief Format value for bitfield CAN_CTRL1_TWRNMSK. */ #define BF_CAN_CTRL1_TWRNMSK(v) ((uint32_t)((uint32_t)(v) << BP_CAN_CTRL1_TWRNMSK) & BM_CAN_CTRL1_TWRNMSK) /*! @brief Set the TWRNMSK field to a new value. */ #define BW_CAN_CTRL1_TWRNMSK(x, v) (BITBAND_ACCESS32(HW_CAN_CTRL1_ADDR(x), BP_CAN_CTRL1_TWRNMSK) = (v)) /*@}*/ /*! * @name Register CAN_CTRL1, field LPB[12] (RW) * * This bit configures FlexCAN to operate in Loop-Back mode. In this mode, * FlexCAN performs an internal loop back that can be used for self test operation. * The bit stream output of the transmitter is fed back internally to the receiver * input. The Rx CAN input pin is ignored and the Tx CAN output goes to the * recessive state (logic 1). FlexCAN behaves as it normally does when transmitting, * and treats its own transmitted message as a message received from a remote * node. In this mode, FlexCAN ignores the bit sent during the ACK slot in the CAN * frame acknowledge field, generating an internal acknowledge bit to ensure proper * reception of its own message. Both transmit and receive interrupts are * generated. This bit can be written only in Freeze mode because it is blocked by * hardware in other modes. In this mode, the MCR[SRXDIS] cannot be asserted because * this will impede the self reception of a transmitted message. * * Values: * - 0 - Loop Back disabled. * - 1 - Loop Back enabled. */ /*@{*/ #define BP_CAN_CTRL1_LPB (12U) /*!< Bit position for CAN_CTRL1_LPB. */ #define BM_CAN_CTRL1_LPB (0x00001000U) /*!< Bit mask for CAN_CTRL1_LPB. */ #define BS_CAN_CTRL1_LPB (1U) /*!< Bit field size in bits for CAN_CTRL1_LPB. */ /*! @brief Read current value of the CAN_CTRL1_LPB field. */ #define BR_CAN_CTRL1_LPB(x) (BITBAND_ACCESS32(HW_CAN_CTRL1_ADDR(x), BP_CAN_CTRL1_LPB)) /*! @brief Format value for bitfield CAN_CTRL1_LPB. */ #define BF_CAN_CTRL1_LPB(v) ((uint32_t)((uint32_t)(v) << BP_CAN_CTRL1_LPB) & BM_CAN_CTRL1_LPB) /*! @brief Set the LPB field to a new value. */ #define BW_CAN_CTRL1_LPB(x, v) (BITBAND_ACCESS32(HW_CAN_CTRL1_ADDR(x), BP_CAN_CTRL1_LPB) = (v)) /*@}*/ /*! * @name Register CAN_CTRL1, field CLKSRC[13] (RW) * * This bit selects the clock source to the CAN Protocol Engine (PE) to be * either the peripheral clock (driven by the PLL) or the crystal oscillator clock. * The selected clock is the one fed to the prescaler to generate the Serial Clock * (Sclock). In order to guarantee reliable operation, this bit can be written * only in Disable mode because it is blocked by hardware in other modes. See * Section "Protocol Timing". * * Values: * - 0 - The CAN engine clock source is the oscillator clock. Under this * condition, the oscillator clock frequency must be lower than the bus clock. * - 1 - The CAN engine clock source is the peripheral clock. */ /*@{*/ #define BP_CAN_CTRL1_CLKSRC (13U) /*!< Bit position for CAN_CTRL1_CLKSRC. */ #define BM_CAN_CTRL1_CLKSRC (0x00002000U) /*!< Bit mask for CAN_CTRL1_CLKSRC. */ #define BS_CAN_CTRL1_CLKSRC (1U) /*!< Bit field size in bits for CAN_CTRL1_CLKSRC. */ /*! @brief Read current value of the CAN_CTRL1_CLKSRC field. */ #define BR_CAN_CTRL1_CLKSRC(x) (BITBAND_ACCESS32(HW_CAN_CTRL1_ADDR(x), BP_CAN_CTRL1_CLKSRC)) /*! @brief Format value for bitfield CAN_CTRL1_CLKSRC. */ #define BF_CAN_CTRL1_CLKSRC(v) ((uint32_t)((uint32_t)(v) << BP_CAN_CTRL1_CLKSRC) & BM_CAN_CTRL1_CLKSRC) /*! @brief Set the CLKSRC field to a new value. */ #define BW_CAN_CTRL1_CLKSRC(x, v) (BITBAND_ACCESS32(HW_CAN_CTRL1_ADDR(x), BP_CAN_CTRL1_CLKSRC) = (v)) /*@}*/ /*! * @name Register CAN_CTRL1, field ERRMSK[14] (RW) * * This bit provides a mask for the Error Interrupt. * * Values: * - 0 - Error interrupt disabled. * - 1 - Error interrupt enabled. */ /*@{*/ #define BP_CAN_CTRL1_ERRMSK (14U) /*!< Bit position for CAN_CTRL1_ERRMSK. */ #define BM_CAN_CTRL1_ERRMSK (0x00004000U) /*!< Bit mask for CAN_CTRL1_ERRMSK. */ #define BS_CAN_CTRL1_ERRMSK (1U) /*!< Bit field size in bits for CAN_CTRL1_ERRMSK. */ /*! @brief Read current value of the CAN_CTRL1_ERRMSK field. */ #define BR_CAN_CTRL1_ERRMSK(x) (BITBAND_ACCESS32(HW_CAN_CTRL1_ADDR(x), BP_CAN_CTRL1_ERRMSK)) /*! @brief Format value for bitfield CAN_CTRL1_ERRMSK. */ #define BF_CAN_CTRL1_ERRMSK(v) ((uint32_t)((uint32_t)(v) << BP_CAN_CTRL1_ERRMSK) & BM_CAN_CTRL1_ERRMSK) /*! @brief Set the ERRMSK field to a new value. */ #define BW_CAN_CTRL1_ERRMSK(x, v) (BITBAND_ACCESS32(HW_CAN_CTRL1_ADDR(x), BP_CAN_CTRL1_ERRMSK) = (v)) /*@}*/ /*! * @name Register CAN_CTRL1, field BOFFMSK[15] (RW) * * This bit provides a mask for the Bus Off Interrupt. * * Values: * - 0 - Bus Off interrupt disabled. * - 1 - Bus Off interrupt enabled. */ /*@{*/ #define BP_CAN_CTRL1_BOFFMSK (15U) /*!< Bit position for CAN_CTRL1_BOFFMSK. */ #define BM_CAN_CTRL1_BOFFMSK (0x00008000U) /*!< Bit mask for CAN_CTRL1_BOFFMSK. */ #define BS_CAN_CTRL1_BOFFMSK (1U) /*!< Bit field size in bits for CAN_CTRL1_BOFFMSK. */ /*! @brief Read current value of the CAN_CTRL1_BOFFMSK field. */ #define BR_CAN_CTRL1_BOFFMSK(x) (BITBAND_ACCESS32(HW_CAN_CTRL1_ADDR(x), BP_CAN_CTRL1_BOFFMSK)) /*! @brief Format value for bitfield CAN_CTRL1_BOFFMSK. */ #define BF_CAN_CTRL1_BOFFMSK(v) ((uint32_t)((uint32_t)(v) << BP_CAN_CTRL1_BOFFMSK) & BM_CAN_CTRL1_BOFFMSK) /*! @brief Set the BOFFMSK field to a new value. */ #define BW_CAN_CTRL1_BOFFMSK(x, v) (BITBAND_ACCESS32(HW_CAN_CTRL1_ADDR(x), BP_CAN_CTRL1_BOFFMSK) = (v)) /*@}*/ /*! * @name Register CAN_CTRL1, field PSEG2[18:16] (RW) * * This 3-bit field defines the length of Phase Buffer Segment 2 in the bit * time. The valid programmable values are 1-7. This field can be written only in * Freeze mode because it is blocked by hardware in other modes. Phase Buffer * Segment 2 = (PSEG2 + 1) * Time-Quanta. */ /*@{*/ #define BP_CAN_CTRL1_PSEG2 (16U) /*!< Bit position for CAN_CTRL1_PSEG2. */ #define BM_CAN_CTRL1_PSEG2 (0x00070000U) /*!< Bit mask for CAN_CTRL1_PSEG2. */ #define BS_CAN_CTRL1_PSEG2 (3U) /*!< Bit field size in bits for CAN_CTRL1_PSEG2. */ /*! @brief Read current value of the CAN_CTRL1_PSEG2 field. */ #define BR_CAN_CTRL1_PSEG2(x) (HW_CAN_CTRL1(x).B.PSEG2) /*! @brief Format value for bitfield CAN_CTRL1_PSEG2. */ #define BF_CAN_CTRL1_PSEG2(v) ((uint32_t)((uint32_t)(v) << BP_CAN_CTRL1_PSEG2) & BM_CAN_CTRL1_PSEG2) /*! @brief Set the PSEG2 field to a new value. */ #define BW_CAN_CTRL1_PSEG2(x, v) (HW_CAN_CTRL1_WR(x, (HW_CAN_CTRL1_RD(x) & ~BM_CAN_CTRL1_PSEG2) | BF_CAN_CTRL1_PSEG2(v))) /*@}*/ /*! * @name Register CAN_CTRL1, field PSEG1[21:19] (RW) * * This 3-bit field defines the length of Phase Buffer Segment 1 in the bit * time. The valid programmable values are 0-7. This field can be written only in * Freeze mode because it is blocked by hardware in other modes. Phase Buffer * Segment 1 = (PSEG1 + 1) * Time-Quanta. */ /*@{*/ #define BP_CAN_CTRL1_PSEG1 (19U) /*!< Bit position for CAN_CTRL1_PSEG1. */ #define BM_CAN_CTRL1_PSEG1 (0x00380000U) /*!< Bit mask for CAN_CTRL1_PSEG1. */ #define BS_CAN_CTRL1_PSEG1 (3U) /*!< Bit field size in bits for CAN_CTRL1_PSEG1. */ /*! @brief Read current value of the CAN_CTRL1_PSEG1 field. */ #define BR_CAN_CTRL1_PSEG1(x) (HW_CAN_CTRL1(x).B.PSEG1) /*! @brief Format value for bitfield CAN_CTRL1_PSEG1. */ #define BF_CAN_CTRL1_PSEG1(v) ((uint32_t)((uint32_t)(v) << BP_CAN_CTRL1_PSEG1) & BM_CAN_CTRL1_PSEG1) /*! @brief Set the PSEG1 field to a new value. */ #define BW_CAN_CTRL1_PSEG1(x, v) (HW_CAN_CTRL1_WR(x, (HW_CAN_CTRL1_RD(x) & ~BM_CAN_CTRL1_PSEG1) | BF_CAN_CTRL1_PSEG1(v))) /*@}*/ /*! * @name Register CAN_CTRL1, field RJW[23:22] (RW) * * This 2-bit field defines the maximum number of time quanta that a bit time * can be changed by one re-synchronization. One time quantum is equal to the * Sclock period. The valid programmable values are 0-3. This field can be written * only in Freeze mode because it is blocked by hardware in other modes. Resync Jump * Width = RJW + 1. */ /*@{*/ #define BP_CAN_CTRL1_RJW (22U) /*!< Bit position for CAN_CTRL1_RJW. */ #define BM_CAN_CTRL1_RJW (0x00C00000U) /*!< Bit mask for CAN_CTRL1_RJW. */ #define BS_CAN_CTRL1_RJW (2U) /*!< Bit field size in bits for CAN_CTRL1_RJW. */ /*! @brief Read current value of the CAN_CTRL1_RJW field. */ #define BR_CAN_CTRL1_RJW(x) (HW_CAN_CTRL1(x).B.RJW) /*! @brief Format value for bitfield CAN_CTRL1_RJW. */ #define BF_CAN_CTRL1_RJW(v) ((uint32_t)((uint32_t)(v) << BP_CAN_CTRL1_RJW) & BM_CAN_CTRL1_RJW) /*! @brief Set the RJW field to a new value. */ #define BW_CAN_CTRL1_RJW(x, v) (HW_CAN_CTRL1_WR(x, (HW_CAN_CTRL1_RD(x) & ~BM_CAN_CTRL1_RJW) | BF_CAN_CTRL1_RJW(v))) /*@}*/ /*! * @name Register CAN_CTRL1, field PRESDIV[31:24] (RW) * * This 8-bit field defines the ratio between the PE clock frequency and the * Serial Clock (Sclock) frequency. The Sclock period defines the time quantum of * the CAN protocol. For the reset value, the Sclock frequency is equal to the PE * clock frequency. The Maximum value of this field is 0xFF, that gives a minimum * Sclock frequency equal to the PE clock frequency divided by 256. See Section * "Protocol Timing". This field can be written only in Freeze mode because it is * blocked by hardware in other modes. Sclock frequency = PE clock frequency / * (PRESDIV + 1) */ /*@{*/ #define BP_CAN_CTRL1_PRESDIV (24U) /*!< Bit position for CAN_CTRL1_PRESDIV. */ #define BM_CAN_CTRL1_PRESDIV (0xFF000000U) /*!< Bit mask for CAN_CTRL1_PRESDIV. */ #define BS_CAN_CTRL1_PRESDIV (8U) /*!< Bit field size in bits for CAN_CTRL1_PRESDIV. */ /*! @brief Read current value of the CAN_CTRL1_PRESDIV field. */ #define BR_CAN_CTRL1_PRESDIV(x) (HW_CAN_CTRL1(x).B.PRESDIV) /*! @brief Format value for bitfield CAN_CTRL1_PRESDIV. */ #define BF_CAN_CTRL1_PRESDIV(v) ((uint32_t)((uint32_t)(v) << BP_CAN_CTRL1_PRESDIV) & BM_CAN_CTRL1_PRESDIV) /*! @brief Set the PRESDIV field to a new value. */ #define BW_CAN_CTRL1_PRESDIV(x, v) (HW_CAN_CTRL1_WR(x, (HW_CAN_CTRL1_RD(x) & ~BM_CAN_CTRL1_PRESDIV) | BF_CAN_CTRL1_PRESDIV(v))) /*@}*/ /******************************************************************************* * HW_CAN_TIMER - Free Running Timer ******************************************************************************/ /*! * @brief HW_CAN_TIMER - Free Running Timer (RW) * * Reset value: 0x00000000U * * This register represents a 16-bit free running counter that can be read and * written by the CPU. The timer starts from 0x0 after Reset, counts linearly to * 0xFFFF, and wraps around. The timer is clocked by the FlexCAN bit-clock, which * defines the baud rate on the CAN bus. During a message transmission/reception, * it increments by one for each bit that is received or transmitted. When there * is no message on the bus, it counts using the previously programmed baud * rate. The timer is not incremented during Disable , Stop, and Freeze modes. The * timer value is captured when the second bit of the identifier field of any frame * is on the CAN bus. This captured value is written into the Time Stamp entry * in a message buffer after a successful reception or transmission of a message. * If bit CTRL1[TSYN] is asserted, the Timer is reset whenever a message is * received in the first available Mailbox, according to CTRL2[RFFN] setting. The CPU * can write to this register anytime. However, if the write occurs at the same * time that the Timer is being reset by a reception in the first Mailbox, then * the write value is discarded. Reading this register affects the Mailbox * Unlocking procedure; see Section "Mailbox Lock Mechanism". */ typedef union _hw_can_timer { uint32_t U; struct _hw_can_timer_bitfields { uint32_t TIMER : 16; /*!< [15:0] Timer Value */ uint32_t RESERVED0 : 16; /*!< [31:16] */ } B; } hw_can_timer_t; /*! * @name Constants and macros for entire CAN_TIMER register */ /*@{*/ #define HW_CAN_TIMER_ADDR(x) ((x) + 0x8U) #define HW_CAN_TIMER(x) (*(__IO hw_can_timer_t *) HW_CAN_TIMER_ADDR(x)) #define HW_CAN_TIMER_RD(x) (HW_CAN_TIMER(x).U) #define HW_CAN_TIMER_WR(x, v) (HW_CAN_TIMER(x).U = (v)) #define HW_CAN_TIMER_SET(x, v) (HW_CAN_TIMER_WR(x, HW_CAN_TIMER_RD(x) | (v))) #define HW_CAN_TIMER_CLR(x, v) (HW_CAN_TIMER_WR(x, HW_CAN_TIMER_RD(x) & ~(v))) #define HW_CAN_TIMER_TOG(x, v) (HW_CAN_TIMER_WR(x, HW_CAN_TIMER_RD(x) ^ (v))) /*@}*/ /* * Constants & macros for individual CAN_TIMER bitfields */ /*! * @name Register CAN_TIMER, field TIMER[15:0] (RW) * * Contains the free-running counter value. */ /*@{*/ #define BP_CAN_TIMER_TIMER (0U) /*!< Bit position for CAN_TIMER_TIMER. */ #define BM_CAN_TIMER_TIMER (0x0000FFFFU) /*!< Bit mask for CAN_TIMER_TIMER. */ #define BS_CAN_TIMER_TIMER (16U) /*!< Bit field size in bits for CAN_TIMER_TIMER. */ /*! @brief Read current value of the CAN_TIMER_TIMER field. */ #define BR_CAN_TIMER_TIMER(x) (HW_CAN_TIMER(x).B.TIMER) /*! @brief Format value for bitfield CAN_TIMER_TIMER. */ #define BF_CAN_TIMER_TIMER(v) ((uint32_t)((uint32_t)(v) << BP_CAN_TIMER_TIMER) & BM_CAN_TIMER_TIMER) /*! @brief Set the TIMER field to a new value. */ #define BW_CAN_TIMER_TIMER(x, v) (HW_CAN_TIMER_WR(x, (HW_CAN_TIMER_RD(x) & ~BM_CAN_TIMER_TIMER) | BF_CAN_TIMER_TIMER(v))) /*@}*/ /******************************************************************************* * HW_CAN_RXMGMASK - Rx Mailboxes Global Mask Register ******************************************************************************/ /*! * @brief HW_CAN_RXMGMASK - Rx Mailboxes Global Mask Register (RW) * * Reset value: 0xFFFFFFFFU * * This register is located in RAM. RXMGMASK is provided for legacy application * support. When the MCR[IRMQ] bit is negated, RXMGMASK is always in effect. When * the MCR[IRMQ] bit is asserted, RXMGMASK has no effect. RXMGMASK is used to * mask the filter fields of all Rx MBs, excluding MBs 14-15, which have individual * mask registers. This register can only be written in Freeze mode as it is * blocked by hardware in other modes. */ typedef union _hw_can_rxmgmask { uint32_t U; struct _hw_can_rxmgmask_bitfields { uint32_t MG : 32; /*!< [31:0] Rx Mailboxes Global Mask Bits */ } B; } hw_can_rxmgmask_t; /*! * @name Constants and macros for entire CAN_RXMGMASK register */ /*@{*/ #define HW_CAN_RXMGMASK_ADDR(x) ((x) + 0x10U) #define HW_CAN_RXMGMASK(x) (*(__IO hw_can_rxmgmask_t *) HW_CAN_RXMGMASK_ADDR(x)) #define HW_CAN_RXMGMASK_RD(x) (HW_CAN_RXMGMASK(x).U) #define HW_CAN_RXMGMASK_WR(x, v) (HW_CAN_RXMGMASK(x).U = (v)) #define HW_CAN_RXMGMASK_SET(x, v) (HW_CAN_RXMGMASK_WR(x, HW_CAN_RXMGMASK_RD(x) | (v))) #define HW_CAN_RXMGMASK_CLR(x, v) (HW_CAN_RXMGMASK_WR(x, HW_CAN_RXMGMASK_RD(x) & ~(v))) #define HW_CAN_RXMGMASK_TOG(x, v) (HW_CAN_RXMGMASK_WR(x, HW_CAN_RXMGMASK_RD(x) ^ (v))) /*@}*/ /* * Constants & macros for individual CAN_RXMGMASK bitfields */ /*! * @name Register CAN_RXMGMASK, field MG[31:0] (RW) * * These bits mask the Mailbox filter bits. Note that the alignment with the ID * word of the Mailbox is not perfect as the two most significant MG bits affect * the fields RTR and IDE, which are located in the Control and Status word of * the Mailbox. The following table shows in detail which MG bits mask each Mailbox * filter field. SMB[RTR] RTR bit of the Incoming Frame. It is saved into an * auxiliary MB called Rx Serial Message Buffer (Rx SMB). CTRL2[RRS] CTRL2[EACEN] * Mailbox filter fields MB[RTR] MB[IDE] MB[ID] Reserved 0 - 0 note If the * CTRL2[EACEN] bit is negated, the RTR bit of Mailbox is never compared with the RTR bit * of the incoming frame. note If the CTRL2[EACEN] bit is negated, the IDE bit * of Mailbox is always compared with the IDE bit of the incoming frame. MG[28:0] * MG[31:29] 0 - 1 MG[31] MG[30] MG[28:0] MG[29] 1 0 - - - - MG[31:0] 1 1 0 - - * MG[28:0] MG[31:29] 1 1 1 MG[31] MG[30] MG[28:0] MG[29] * * Values: * - 0 - The corresponding bit in the filter is "don't care." * - 1 - The corresponding bit in the filter is checked. */ /*@{*/ #define BP_CAN_RXMGMASK_MG (0U) /*!< Bit position for CAN_RXMGMASK_MG. */ #define BM_CAN_RXMGMASK_MG (0xFFFFFFFFU) /*!< Bit mask for CAN_RXMGMASK_MG. */ #define BS_CAN_RXMGMASK_MG (32U) /*!< Bit field size in bits for CAN_RXMGMASK_MG. */ /*! @brief Read current value of the CAN_RXMGMASK_MG field. */ #define BR_CAN_RXMGMASK_MG(x) (HW_CAN_RXMGMASK(x).U) /*! @brief Format value for bitfield CAN_RXMGMASK_MG. */ #define BF_CAN_RXMGMASK_MG(v) ((uint32_t)((uint32_t)(v) << BP_CAN_RXMGMASK_MG) & BM_CAN_RXMGMASK_MG) /*! @brief Set the MG field to a new value. */ #define BW_CAN_RXMGMASK_MG(x, v) (HW_CAN_RXMGMASK_WR(x, v)) /*@}*/ /******************************************************************************* * HW_CAN_RX14MASK - Rx 14 Mask register ******************************************************************************/ /*! * @brief HW_CAN_RX14MASK - Rx 14 Mask register (RW) * * Reset value: 0xFFFFFFFFU * * This register is located in RAM. RX14MASK is provided for legacy application * support. When the MCR[IRMQ] bit is asserted, RX14MASK has no effect. RX14MASK * is used to mask the filter fields of Message Buffer 14. This register can only * be programmed while the module is in Freeze mode as it is blocked by hardware * in other modes. */ typedef union _hw_can_rx14mask { uint32_t U; struct _hw_can_rx14mask_bitfields { uint32_t RX14M : 32; /*!< [31:0] Rx Buffer 14 Mask Bits */ } B; } hw_can_rx14mask_t; /*! * @name Constants and macros for entire CAN_RX14MASK register */ /*@{*/ #define HW_CAN_RX14MASK_ADDR(x) ((x) + 0x14U) #define HW_CAN_RX14MASK(x) (*(__IO hw_can_rx14mask_t *) HW_CAN_RX14MASK_ADDR(x)) #define HW_CAN_RX14MASK_RD(x) (HW_CAN_RX14MASK(x).U) #define HW_CAN_RX14MASK_WR(x, v) (HW_CAN_RX14MASK(x).U = (v)) #define HW_CAN_RX14MASK_SET(x, v) (HW_CAN_RX14MASK_WR(x, HW_CAN_RX14MASK_RD(x) | (v))) #define HW_CAN_RX14MASK_CLR(x, v) (HW_CAN_RX14MASK_WR(x, HW_CAN_RX14MASK_RD(x) & ~(v))) #define HW_CAN_RX14MASK_TOG(x, v) (HW_CAN_RX14MASK_WR(x, HW_CAN_RX14MASK_RD(x) ^ (v))) /*@}*/ /* * Constants & macros for individual CAN_RX14MASK bitfields */ /*! * @name Register CAN_RX14MASK, field RX14M[31:0] (RW) * * Each mask bit masks the corresponding Mailbox 14 filter field in the same way * that RXMGMASK masks other Mailboxes' filters. See the description of the * CAN_RXMGMASK register. * * Values: * - 0 - The corresponding bit in the filter is "don't care." * - 1 - The corresponding bit in the filter is checked. */ /*@{*/ #define BP_CAN_RX14MASK_RX14M (0U) /*!< Bit position for CAN_RX14MASK_RX14M. */ #define BM_CAN_RX14MASK_RX14M (0xFFFFFFFFU) /*!< Bit mask for CAN_RX14MASK_RX14M. */ #define BS_CAN_RX14MASK_RX14M (32U) /*!< Bit field size in bits for CAN_RX14MASK_RX14M. */ /*! @brief Read current value of the CAN_RX14MASK_RX14M field. */ #define BR_CAN_RX14MASK_RX14M(x) (HW_CAN_RX14MASK(x).U) /*! @brief Format value for bitfield CAN_RX14MASK_RX14M. */ #define BF_CAN_RX14MASK_RX14M(v) ((uint32_t)((uint32_t)(v) << BP_CAN_RX14MASK_RX14M) & BM_CAN_RX14MASK_RX14M) /*! @brief Set the RX14M field to a new value. */ #define BW_CAN_RX14MASK_RX14M(x, v) (HW_CAN_RX14MASK_WR(x, v)) /*@}*/ /******************************************************************************* * HW_CAN_RX15MASK - Rx 15 Mask register ******************************************************************************/ /*! * @brief HW_CAN_RX15MASK - Rx 15 Mask register (RW) * * Reset value: 0xFFFFFFFFU * * This register is located in RAM. RX15MASK is provided for legacy application * support. When the MCR[IRMQ] bit is asserted, RX15MASK has no effect. RX15MASK * is used to mask the filter fields of Message Buffer 15. This register can be * programmed only while the module is in Freeze mode because it is blocked by * hardware in other modes. */ typedef union _hw_can_rx15mask { uint32_t U; struct _hw_can_rx15mask_bitfields { uint32_t RX15M : 32; /*!< [31:0] Rx Buffer 15 Mask Bits */ } B; } hw_can_rx15mask_t; /*! * @name Constants and macros for entire CAN_RX15MASK register */ /*@{*/ #define HW_CAN_RX15MASK_ADDR(x) ((x) + 0x18U) #define HW_CAN_RX15MASK(x) (*(__IO hw_can_rx15mask_t *) HW_CAN_RX15MASK_ADDR(x)) #define HW_CAN_RX15MASK_RD(x) (HW_CAN_RX15MASK(x).U) #define HW_CAN_RX15MASK_WR(x, v) (HW_CAN_RX15MASK(x).U = (v)) #define HW_CAN_RX15MASK_SET(x, v) (HW_CAN_RX15MASK_WR(x, HW_CAN_RX15MASK_RD(x) | (v))) #define HW_CAN_RX15MASK_CLR(x, v) (HW_CAN_RX15MASK_WR(x, HW_CAN_RX15MASK_RD(x) & ~(v))) #define HW_CAN_RX15MASK_TOG(x, v) (HW_CAN_RX15MASK_WR(x, HW_CAN_RX15MASK_RD(x) ^ (v))) /*@}*/ /* * Constants & macros for individual CAN_RX15MASK bitfields */ /*! * @name Register CAN_RX15MASK, field RX15M[31:0] (RW) * * Each mask bit masks the corresponding Mailbox 15 filter field in the same way * that RXMGMASK masks other Mailboxes' filters. See the description of the * CAN_RXMGMASK register. * * Values: * - 0 - The corresponding bit in the filter is "don't care." * - 1 - The corresponding bit in the filter is checked. */ /*@{*/ #define BP_CAN_RX15MASK_RX15M (0U) /*!< Bit position for CAN_RX15MASK_RX15M. */ #define BM_CAN_RX15MASK_RX15M (0xFFFFFFFFU) /*!< Bit mask for CAN_RX15MASK_RX15M. */ #define BS_CAN_RX15MASK_RX15M (32U) /*!< Bit field size in bits for CAN_RX15MASK_RX15M. */ /*! @brief Read current value of the CAN_RX15MASK_RX15M field. */ #define BR_CAN_RX15MASK_RX15M(x) (HW_CAN_RX15MASK(x).U) /*! @brief Format value for bitfield CAN_RX15MASK_RX15M. */ #define BF_CAN_RX15MASK_RX15M(v) ((uint32_t)((uint32_t)(v) << BP_CAN_RX15MASK_RX15M) & BM_CAN_RX15MASK_RX15M) /*! @brief Set the RX15M field to a new value. */ #define BW_CAN_RX15MASK_RX15M(x, v) (HW_CAN_RX15MASK_WR(x, v)) /*@}*/ /******************************************************************************* * HW_CAN_ECR - Error Counter ******************************************************************************/ /*! * @brief HW_CAN_ECR - Error Counter (RW) * * Reset value: 0x00000000U * * This register has two 8-bit fields reflecting the value of two FlexCAN error * counters: Transmit Error Counter (TXERRCNT field) and Receive Error Counter * (RXERRCNT field). The rules for increasing and decreasing these counters are * described in the CAN protocol and are completely implemented in the FlexCAN * module. Both counters are read-only except in Freeze mode, where they can be * written by the CPU. FlexCAN responds to any bus state as described in the protocol, * for example, transmit Error Active or Error Passive flag, delay its * transmission start time (Error Passive) and avoid any influence on the bus when in Bus * Off state. The following are the basic rules for FlexCAN bus state transitions: * If the value of TXERRCNT or RXERRCNT increases to be greater than or equal to * 128, the FLTCONF field in the Error and Status Register is updated to reflect * 'Error Passive' state. If the FlexCAN state is 'Error Passive', and either * TXERRCNT or RXERRCNT decrements to a value less than or equal to 127 while the * other already satisfies this condition, the FLTCONF field in the Error and * Status Register is updated to reflect 'Error Active' state. If the value of * TXERRCNT increases to be greater than 255, the FLTCONF field in the Error and Status * Register is updated to reflect 'Bus Off' state, and an interrupt may be * issued. The value of TXERRCNT is then reset to zero. If FlexCAN is in 'Bus Off' * state, then TXERRCNT is cascaded together with another internal counter to count * the 128th occurrences of 11 consecutive recessive bits on the bus. Hence, * TXERRCNT is reset to zero and counts in a manner where the internal counter counts * 11 such bits and then wraps around while incrementing the TXERRCNT. When * TXERRCNT reaches the value of 128, the FLTCONF field in the Error and Status * Register is updated to be 'Error Active' and both error counters are reset to zero. * At any instance of dominant bit following a stream of less than 11 * consecutive recessive bits, the internal counter resets itself to zero without affecting * the TXERRCNT value. If during system start-up, only one node is operating, * then its TXERRCNT increases in each message it is trying to transmit, as a * result of acknowledge errors (indicated by the ACKERR bit in the Error and Status * Register). After the transition to 'Error Passive' state, the TXERRCNT does not * increment anymore by acknowledge errors. Therefore the device never goes to * the 'Bus Off' state. If the RXERRCNT increases to a value greater than 127, it * is not incremented further, even if more errors are detected while being a * receiver. At the next successful message reception, the counter is set to a value * between 119 and 127 to resume to 'Error Active' state. */ typedef union _hw_can_ecr { uint32_t U; struct _hw_can_ecr_bitfields { uint32_t TXERRCNT : 8; /*!< [7:0] Transmit Error Counter */ uint32_t RXERRCNT : 8; /*!< [15:8] Receive Error Counter */ uint32_t RESERVED0 : 16; /*!< [31:16] */ } B; } hw_can_ecr_t; /*! * @name Constants and macros for entire CAN_ECR register */ /*@{*/ #define HW_CAN_ECR_ADDR(x) ((x) + 0x1CU) #define HW_CAN_ECR(x) (*(__IO hw_can_ecr_t *) HW_CAN_ECR_ADDR(x)) #define HW_CAN_ECR_RD(x) (HW_CAN_ECR(x).U) #define HW_CAN_ECR_WR(x, v) (HW_CAN_ECR(x).U = (v)) #define HW_CAN_ECR_SET(x, v) (HW_CAN_ECR_WR(x, HW_CAN_ECR_RD(x) | (v))) #define HW_CAN_ECR_CLR(x, v) (HW_CAN_ECR_WR(x, HW_CAN_ECR_RD(x) & ~(v))) #define HW_CAN_ECR_TOG(x, v) (HW_CAN_ECR_WR(x, HW_CAN_ECR_RD(x) ^ (v))) /*@}*/ /* * Constants & macros for individual CAN_ECR bitfields */ /*! * @name Register CAN_ECR, field TXERRCNT[7:0] (RW) */ /*@{*/ #define BP_CAN_ECR_TXERRCNT (0U) /*!< Bit position for CAN_ECR_TXERRCNT. */ #define BM_CAN_ECR_TXERRCNT (0x000000FFU) /*!< Bit mask for CAN_ECR_TXERRCNT. */ #define BS_CAN_ECR_TXERRCNT (8U) /*!< Bit field size in bits for CAN_ECR_TXERRCNT. */ /*! @brief Read current value of the CAN_ECR_TXERRCNT field. */ #define BR_CAN_ECR_TXERRCNT(x) (HW_CAN_ECR(x).B.TXERRCNT) /*! @brief Format value for bitfield CAN_ECR_TXERRCNT. */ #define BF_CAN_ECR_TXERRCNT(v) ((uint32_t)((uint32_t)(v) << BP_CAN_ECR_TXERRCNT) & BM_CAN_ECR_TXERRCNT) /*! @brief Set the TXERRCNT field to a new value. */ #define BW_CAN_ECR_TXERRCNT(x, v) (HW_CAN_ECR_WR(x, (HW_CAN_ECR_RD(x) & ~BM_CAN_ECR_TXERRCNT) | BF_CAN_ECR_TXERRCNT(v))) /*@}*/ /*! * @name Register CAN_ECR, field RXERRCNT[15:8] (RW) */ /*@{*/ #define BP_CAN_ECR_RXERRCNT (8U) /*!< Bit position for CAN_ECR_RXERRCNT. */ #define BM_CAN_ECR_RXERRCNT (0x0000FF00U) /*!< Bit mask for CAN_ECR_RXERRCNT. */ #define BS_CAN_ECR_RXERRCNT (8U) /*!< Bit field size in bits for CAN_ECR_RXERRCNT. */ /*! @brief Read current value of the CAN_ECR_RXERRCNT field. */ #define BR_CAN_ECR_RXERRCNT(x) (HW_CAN_ECR(x).B.RXERRCNT) /*! @brief Format value for bitfield CAN_ECR_RXERRCNT. */ #define BF_CAN_ECR_RXERRCNT(v) ((uint32_t)((uint32_t)(v) << BP_CAN_ECR_RXERRCNT) & BM_CAN_ECR_RXERRCNT) /*! @brief Set the RXERRCNT field to a new value. */ #define BW_CAN_ECR_RXERRCNT(x, v) (HW_CAN_ECR_WR(x, (HW_CAN_ECR_RD(x) & ~BM_CAN_ECR_RXERRCNT) | BF_CAN_ECR_RXERRCNT(v))) /*@}*/ /******************************************************************************* * HW_CAN_ESR1 - Error and Status 1 register ******************************************************************************/ /*! * @brief HW_CAN_ESR1 - Error and Status 1 register (RW) * * Reset value: 0x00000000U * * This register reflects various error conditions, some general status of the * device and it is the source of interrupts to the CPU. The CPU read action * clears bits 15-10. Therefore the reported error conditions (bits 15-10) are those * that occurred since the last time the CPU read this register. Bits 9-3 are * status bits. The following table shows the FlexCAN state variables and their * meanings. Other combinations not shown in the table are reserved. SYNCH IDLE TX RX * FlexCAN State 0 0 0 0 Not synchronized to CAN bus 1 1 x x Idle 1 0 1 0 * Transmitting 1 0 0 1 Receiving */ typedef union _hw_can_esr1 { uint32_t U; struct _hw_can_esr1_bitfields { uint32_t WAKINT : 1; /*!< [0] Wake-Up Interrupt */ uint32_t ERRINT : 1; /*!< [1] Error Interrupt */ uint32_t BOFFINT : 1; /*!< [2] Bus Off Interrupt */ uint32_t RX : 1; /*!< [3] FlexCAN In Reception */ uint32_t FLTCONF : 2; /*!< [5:4] Fault Confinement State */ uint32_t TX : 1; /*!< [6] FlexCAN In Transmission */ uint32_t IDLE : 1; /*!< [7] */ uint32_t RXWRN : 1; /*!< [8] Rx Error Warning */ uint32_t TXWRN : 1; /*!< [9] TX Error Warning */ uint32_t STFERR : 1; /*!< [10] Stuffing Error */ uint32_t FRMERR : 1; /*!< [11] Form Error */ uint32_t CRCERR : 1; /*!< [12] Cyclic Redundancy Check Error */ uint32_t ACKERR : 1; /*!< [13] Acknowledge Error */ uint32_t BIT0ERR : 1; /*!< [14] Bit0 Error */ uint32_t BIT1ERR : 1; /*!< [15] Bit1 Error */ uint32_t RWRNINT : 1; /*!< [16] Rx Warning Interrupt Flag */ uint32_t TWRNINT : 1; /*!< [17] Tx Warning Interrupt Flag */ uint32_t SYNCH : 1; /*!< [18] CAN Synchronization Status */ uint32_t RESERVED0 : 13; /*!< [31:19] */ } B; } hw_can_esr1_t; /*! * @name Constants and macros for entire CAN_ESR1 register */ /*@{*/ #define HW_CAN_ESR1_ADDR(x) ((x) + 0x20U) #define HW_CAN_ESR1(x) (*(__IO hw_can_esr1_t *) HW_CAN_ESR1_ADDR(x)) #define HW_CAN_ESR1_RD(x) (HW_CAN_ESR1(x).U) #define HW_CAN_ESR1_WR(x, v) (HW_CAN_ESR1(x).U = (v)) #define HW_CAN_ESR1_SET(x, v) (HW_CAN_ESR1_WR(x, HW_CAN_ESR1_RD(x) | (v))) #define HW_CAN_ESR1_CLR(x, v) (HW_CAN_ESR1_WR(x, HW_CAN_ESR1_RD(x) & ~(v))) #define HW_CAN_ESR1_TOG(x, v) (HW_CAN_ESR1_WR(x, HW_CAN_ESR1_RD(x) ^ (v))) /*@}*/ /* * Constants & macros for individual CAN_ESR1 bitfields */ /*! * @name Register CAN_ESR1, field WAKINT[0] (W1C) * * This field applies when FlexCAN is in low-power mode under Self Wake Up * mechanism: Stop mode When a recessive-to-dominant transition is detected on the CAN * bus and if the MCR[WAKMSK] bit is set, an interrupt is generated to the CPU. * This bit is cleared by writing it to 1. When MCR[SLFWAK] is negated, this flag * is masked. The CPU must clear this flag before disabling the bit. Otherwise * it will be set when the SLFWAK is set again. Writing 0 has no effect. * * Values: * - 0 - No such occurrence. * - 1 - Indicates a recessive to dominant transition was received on the CAN * bus. */ /*@{*/ #define BP_CAN_ESR1_WAKINT (0U) /*!< Bit position for CAN_ESR1_WAKINT. */ #define BM_CAN_ESR1_WAKINT (0x00000001U) /*!< Bit mask for CAN_ESR1_WAKINT. */ #define BS_CAN_ESR1_WAKINT (1U) /*!< Bit field size in bits for CAN_ESR1_WAKINT. */ /*! @brief Read current value of the CAN_ESR1_WAKINT field. */ #define BR_CAN_ESR1_WAKINT(x) (BITBAND_ACCESS32(HW_CAN_ESR1_ADDR(x), BP_CAN_ESR1_WAKINT)) /*! @brief Format value for bitfield CAN_ESR1_WAKINT. */ #define BF_CAN_ESR1_WAKINT(v) ((uint32_t)((uint32_t)(v) << BP_CAN_ESR1_WAKINT) & BM_CAN_ESR1_WAKINT) /*! @brief Set the WAKINT field to a new value. */ #define BW_CAN_ESR1_WAKINT(x, v) (BITBAND_ACCESS32(HW_CAN_ESR1_ADDR(x), BP_CAN_ESR1_WAKINT) = (v)) /*@}*/ /*! * @name Register CAN_ESR1, field ERRINT[1] (W1C) * * This bit indicates that at least one of the Error Bits (bits 15-10) is set. * If the corresponding mask bit CTRL1[ERRMSK] is set, an interrupt is generated * to the CPU. This bit is cleared by writing it to 1. Writing 0 has no effect. * * Values: * - 0 - No such occurrence. * - 1 - Indicates setting of any Error Bit in the Error and Status Register. */ /*@{*/ #define BP_CAN_ESR1_ERRINT (1U) /*!< Bit position for CAN_ESR1_ERRINT. */ #define BM_CAN_ESR1_ERRINT (0x00000002U) /*!< Bit mask for CAN_ESR1_ERRINT. */ #define BS_CAN_ESR1_ERRINT (1U) /*!< Bit field size in bits for CAN_ESR1_ERRINT. */ /*! @brief Read current value of the CAN_ESR1_ERRINT field. */ #define BR_CAN_ESR1_ERRINT(x) (BITBAND_ACCESS32(HW_CAN_ESR1_ADDR(x), BP_CAN_ESR1_ERRINT)) /*! @brief Format value for bitfield CAN_ESR1_ERRINT. */ #define BF_CAN_ESR1_ERRINT(v) ((uint32_t)((uint32_t)(v) << BP_CAN_ESR1_ERRINT) & BM_CAN_ESR1_ERRINT) /*! @brief Set the ERRINT field to a new value. */ #define BW_CAN_ESR1_ERRINT(x, v) (BITBAND_ACCESS32(HW_CAN_ESR1_ADDR(x), BP_CAN_ESR1_ERRINT) = (v)) /*@}*/ /*! * @name Register CAN_ESR1, field BOFFINT[2] (W1C) * * This bit is set when FlexCAN enters 'Bus Off' state. If the corresponding * mask bit in the Control Register (BOFFMSK) is set, an interrupt is generated to * the CPU. This bit is cleared by writing it to 1. Writing 0 has no effect. * * Values: * - 0 - No such occurrence. * - 1 - FlexCAN module entered Bus Off state. */ /*@{*/ #define BP_CAN_ESR1_BOFFINT (2U) /*!< Bit position for CAN_ESR1_BOFFINT. */ #define BM_CAN_ESR1_BOFFINT (0x00000004U) /*!< Bit mask for CAN_ESR1_BOFFINT. */ #define BS_CAN_ESR1_BOFFINT (1U) /*!< Bit field size in bits for CAN_ESR1_BOFFINT. */ /*! @brief Read current value of the CAN_ESR1_BOFFINT field. */ #define BR_CAN_ESR1_BOFFINT(x) (BITBAND_ACCESS32(HW_CAN_ESR1_ADDR(x), BP_CAN_ESR1_BOFFINT)) /*! @brief Format value for bitfield CAN_ESR1_BOFFINT. */ #define BF_CAN_ESR1_BOFFINT(v) ((uint32_t)((uint32_t)(v) << BP_CAN_ESR1_BOFFINT) & BM_CAN_ESR1_BOFFINT) /*! @brief Set the BOFFINT field to a new value. */ #define BW_CAN_ESR1_BOFFINT(x, v) (BITBAND_ACCESS32(HW_CAN_ESR1_ADDR(x), BP_CAN_ESR1_BOFFINT) = (v)) /*@}*/ /*! * @name Register CAN_ESR1, field RX[3] (RO) * * This bit indicates if FlexCAN is receiving a message. See the table in the * overall CAN_ESR1 register description. * * Values: * - 0 - FlexCAN is not receiving a message. * - 1 - FlexCAN is receiving a message. */ /*@{*/ #define BP_CAN_ESR1_RX (3U) /*!< Bit position for CAN_ESR1_RX. */ #define BM_CAN_ESR1_RX (0x00000008U) /*!< Bit mask for CAN_ESR1_RX. */ #define BS_CAN_ESR1_RX (1U) /*!< Bit field size in bits for CAN_ESR1_RX. */ /*! @brief Read current value of the CAN_ESR1_RX field. */ #define BR_CAN_ESR1_RX(x) (BITBAND_ACCESS32(HW_CAN_ESR1_ADDR(x), BP_CAN_ESR1_RX)) /*@}*/ /*! * @name Register CAN_ESR1, field FLTCONF[5:4] (RO) * * This 2-bit field indicates the Confinement State of the FlexCAN module. If * the LOM bit in the Control Register is asserted, after some delay that depends * on the CAN bit timing the FLTCONF field will indicate "Error Passive". The very * same delay affects the way how FLTCONF reflects an update to ECR register by * the CPU. It may be necessary up to one CAN bit time to get them coherent * again. Because the Control Register is not affected by soft reset, the FLTCONF * field will not be affected by soft reset if the LOM bit is asserted. * * Values: * - 00 - Error Active * - 01 - Error Passive * - 1x - Bus Off */ /*@{*/ #define BP_CAN_ESR1_FLTCONF (4U) /*!< Bit position for CAN_ESR1_FLTCONF. */ #define BM_CAN_ESR1_FLTCONF (0x00000030U) /*!< Bit mask for CAN_ESR1_FLTCONF. */ #define BS_CAN_ESR1_FLTCONF (2U) /*!< Bit field size in bits for CAN_ESR1_FLTCONF. */ /*! @brief Read current value of the CAN_ESR1_FLTCONF field. */ #define BR_CAN_ESR1_FLTCONF(x) (HW_CAN_ESR1(x).B.FLTCONF) /*@}*/ /*! * @name Register CAN_ESR1, field TX[6] (RO) * * This bit indicates if FlexCAN is transmitting a message. See the table in the * overall CAN_ESR1 register description. * * Values: * - 0 - FlexCAN is not transmitting a message. * - 1 - FlexCAN is transmitting a message. */ /*@{*/ #define BP_CAN_ESR1_TX (6U) /*!< Bit position for CAN_ESR1_TX. */ #define BM_CAN_ESR1_TX (0x00000040U) /*!< Bit mask for CAN_ESR1_TX. */ #define BS_CAN_ESR1_TX (1U) /*!< Bit field size in bits for CAN_ESR1_TX. */ /*! @brief Read current value of the CAN_ESR1_TX field. */ #define BR_CAN_ESR1_TX(x) (BITBAND_ACCESS32(HW_CAN_ESR1_ADDR(x), BP_CAN_ESR1_TX)) /*@}*/ /*! * @name Register CAN_ESR1, field IDLE[7] (RO) * * This bit indicates when CAN bus is in IDLE state. See the table in the * overall CAN_ESR1 register description. * * Values: * - 0 - No such occurrence. * - 1 - CAN bus is now IDLE. */ /*@{*/ #define BP_CAN_ESR1_IDLE (7U) /*!< Bit position for CAN_ESR1_IDLE. */ #define BM_CAN_ESR1_IDLE (0x00000080U) /*!< Bit mask for CAN_ESR1_IDLE. */ #define BS_CAN_ESR1_IDLE (1U) /*!< Bit field size in bits for CAN_ESR1_IDLE. */ /*! @brief Read current value of the CAN_ESR1_IDLE field. */ #define BR_CAN_ESR1_IDLE(x) (BITBAND_ACCESS32(HW_CAN_ESR1_ADDR(x), BP_CAN_ESR1_IDLE)) /*@}*/ /*! * @name Register CAN_ESR1, field RXWRN[8] (RO) * * This bit indicates when repetitive errors are occurring during message * reception. This bit is not updated during Freeze mode. * * Values: * - 0 - No such occurrence. * - 1 - RXERRCNT is greater than or equal to 96. */ /*@{*/ #define BP_CAN_ESR1_RXWRN (8U) /*!< Bit position for CAN_ESR1_RXWRN. */ #define BM_CAN_ESR1_RXWRN (0x00000100U) /*!< Bit mask for CAN_ESR1_RXWRN. */ #define BS_CAN_ESR1_RXWRN (1U) /*!< Bit field size in bits for CAN_ESR1_RXWRN. */ /*! @brief Read current value of the CAN_ESR1_RXWRN field. */ #define BR_CAN_ESR1_RXWRN(x) (BITBAND_ACCESS32(HW_CAN_ESR1_ADDR(x), BP_CAN_ESR1_RXWRN)) /*@}*/ /*! * @name Register CAN_ESR1, field TXWRN[9] (RO) * * This bit indicates when repetitive errors are occurring during message * transmission. This bit is not updated during Freeze mode. * * Values: * - 0 - No such occurrence. * - 1 - TXERRCNT is greater than or equal to 96. */ /*@{*/ #define BP_CAN_ESR1_TXWRN (9U) /*!< Bit position for CAN_ESR1_TXWRN. */ #define BM_CAN_ESR1_TXWRN (0x00000200U) /*!< Bit mask for CAN_ESR1_TXWRN. */ #define BS_CAN_ESR1_TXWRN (1U) /*!< Bit field size in bits for CAN_ESR1_TXWRN. */ /*! @brief Read current value of the CAN_ESR1_TXWRN field. */ #define BR_CAN_ESR1_TXWRN(x) (BITBAND_ACCESS32(HW_CAN_ESR1_ADDR(x), BP_CAN_ESR1_TXWRN)) /*@}*/ /*! * @name Register CAN_ESR1, field STFERR[10] (RO) * * This bit indicates that a Stuffing Error has been etected. * * Values: * - 0 - No such occurrence. * - 1 - A Stuffing Error occurred since last read of this register. */ /*@{*/ #define BP_CAN_ESR1_STFERR (10U) /*!< Bit position for CAN_ESR1_STFERR. */ #define BM_CAN_ESR1_STFERR (0x00000400U) /*!< Bit mask for CAN_ESR1_STFERR. */ #define BS_CAN_ESR1_STFERR (1U) /*!< Bit field size in bits for CAN_ESR1_STFERR. */ /*! @brief Read current value of the CAN_ESR1_STFERR field. */ #define BR_CAN_ESR1_STFERR(x) (BITBAND_ACCESS32(HW_CAN_ESR1_ADDR(x), BP_CAN_ESR1_STFERR)) /*@}*/ /*! * @name Register CAN_ESR1, field FRMERR[11] (RO) * * This bit indicates that a Form Error has been detected by the receiver node, * that is, a fixed-form bit field contains at least one illegal bit. * * Values: * - 0 - No such occurrence. * - 1 - A Form Error occurred since last read of this register. */ /*@{*/ #define BP_CAN_ESR1_FRMERR (11U) /*!< Bit position for CAN_ESR1_FRMERR. */ #define BM_CAN_ESR1_FRMERR (0x00000800U) /*!< Bit mask for CAN_ESR1_FRMERR. */ #define BS_CAN_ESR1_FRMERR (1U) /*!< Bit field size in bits for CAN_ESR1_FRMERR. */ /*! @brief Read current value of the CAN_ESR1_FRMERR field. */ #define BR_CAN_ESR1_FRMERR(x) (BITBAND_ACCESS32(HW_CAN_ESR1_ADDR(x), BP_CAN_ESR1_FRMERR)) /*@}*/ /*! * @name Register CAN_ESR1, field CRCERR[12] (RO) * * This bit indicates that a CRC Error has been detected by the receiver node, * that is, the calculated CRC is different from the received. * * Values: * - 0 - No such occurrence. * - 1 - A CRC error occurred since last read of this register. */ /*@{*/ #define BP_CAN_ESR1_CRCERR (12U) /*!< Bit position for CAN_ESR1_CRCERR. */ #define BM_CAN_ESR1_CRCERR (0x00001000U) /*!< Bit mask for CAN_ESR1_CRCERR. */ #define BS_CAN_ESR1_CRCERR (1U) /*!< Bit field size in bits for CAN_ESR1_CRCERR. */ /*! @brief Read current value of the CAN_ESR1_CRCERR field. */ #define BR_CAN_ESR1_CRCERR(x) (BITBAND_ACCESS32(HW_CAN_ESR1_ADDR(x), BP_CAN_ESR1_CRCERR)) /*@}*/ /*! * @name Register CAN_ESR1, field ACKERR[13] (RO) * * This bit indicates that an Acknowledge Error has been detected by the * transmitter node, that is, a dominant bit has not been detected during the ACK SLOT. * * Values: * - 0 - No such occurrence. * - 1 - An ACK error occurred since last read of this register. */ /*@{*/ #define BP_CAN_ESR1_ACKERR (13U) /*!< Bit position for CAN_ESR1_ACKERR. */ #define BM_CAN_ESR1_ACKERR (0x00002000U) /*!< Bit mask for CAN_ESR1_ACKERR. */ #define BS_CAN_ESR1_ACKERR (1U) /*!< Bit field size in bits for CAN_ESR1_ACKERR. */ /*! @brief Read current value of the CAN_ESR1_ACKERR field. */ #define BR_CAN_ESR1_ACKERR(x) (BITBAND_ACCESS32(HW_CAN_ESR1_ADDR(x), BP_CAN_ESR1_ACKERR)) /*@}*/ /*! * @name Register CAN_ESR1, field BIT0ERR[14] (RO) * * This bit indicates when an inconsistency occurs between the transmitted and * the received bit in a message. * * Values: * - 0 - No such occurrence. * - 1 - At least one bit sent as dominant is received as recessive. */ /*@{*/ #define BP_CAN_ESR1_BIT0ERR (14U) /*!< Bit position for CAN_ESR1_BIT0ERR. */ #define BM_CAN_ESR1_BIT0ERR (0x00004000U) /*!< Bit mask for CAN_ESR1_BIT0ERR. */ #define BS_CAN_ESR1_BIT0ERR (1U) /*!< Bit field size in bits for CAN_ESR1_BIT0ERR. */ /*! @brief Read current value of the CAN_ESR1_BIT0ERR field. */ #define BR_CAN_ESR1_BIT0ERR(x) (BITBAND_ACCESS32(HW_CAN_ESR1_ADDR(x), BP_CAN_ESR1_BIT0ERR)) /*@}*/ /*! * @name Register CAN_ESR1, field BIT1ERR[15] (RO) * * This bit indicates when an inconsistency occurs between the transmitted and * the received bit in a message. This bit is not set by a transmitter in case of * arbitration field or ACK slot, or in case of a node sending a passive error * flag that detects dominant bits. * * Values: * - 0 - No such occurrence. * - 1 - At least one bit sent as recessive is received as dominant. */ /*@{*/ #define BP_CAN_ESR1_BIT1ERR (15U) /*!< Bit position for CAN_ESR1_BIT1ERR. */ #define BM_CAN_ESR1_BIT1ERR (0x00008000U) /*!< Bit mask for CAN_ESR1_BIT1ERR. */ #define BS_CAN_ESR1_BIT1ERR (1U) /*!< Bit field size in bits for CAN_ESR1_BIT1ERR. */ /*! @brief Read current value of the CAN_ESR1_BIT1ERR field. */ #define BR_CAN_ESR1_BIT1ERR(x) (BITBAND_ACCESS32(HW_CAN_ESR1_ADDR(x), BP_CAN_ESR1_BIT1ERR)) /*@}*/ /*! * @name Register CAN_ESR1, field RWRNINT[16] (W1C) * * If the WRNEN bit in MCR is asserted, the RWRNINT bit is set when the RXWRN * flag transitions from 0 to 1, meaning that the Rx error counters reached 96. If * the corresponding mask bit in the Control Register (RWRNMSK) is set, an * interrupt is generated to the CPU. This bit is cleared by writing it to 1. When * WRNEN is negated, this flag is masked. CPU must clear this flag before disabling * the bit. Otherwise it will be set when the WRNEN is set again. Writing 0 has no * effect. This bit is not updated during Freeze mode. * * Values: * - 0 - No such occurrence. * - 1 - The Rx error counter transitioned from less than 96 to greater than or * equal to 96. */ /*@{*/ #define BP_CAN_ESR1_RWRNINT (16U) /*!< Bit position for CAN_ESR1_RWRNINT. */ #define BM_CAN_ESR1_RWRNINT (0x00010000U) /*!< Bit mask for CAN_ESR1_RWRNINT. */ #define BS_CAN_ESR1_RWRNINT (1U) /*!< Bit field size in bits for CAN_ESR1_RWRNINT. */ /*! @brief Read current value of the CAN_ESR1_RWRNINT field. */ #define BR_CAN_ESR1_RWRNINT(x) (BITBAND_ACCESS32(HW_CAN_ESR1_ADDR(x), BP_CAN_ESR1_RWRNINT)) /*! @brief Format value for bitfield CAN_ESR1_RWRNINT. */ #define BF_CAN_ESR1_RWRNINT(v) ((uint32_t)((uint32_t)(v) << BP_CAN_ESR1_RWRNINT) & BM_CAN_ESR1_RWRNINT) /*! @brief Set the RWRNINT field to a new value. */ #define BW_CAN_ESR1_RWRNINT(x, v) (BITBAND_ACCESS32(HW_CAN_ESR1_ADDR(x), BP_CAN_ESR1_RWRNINT) = (v)) /*@}*/ /*! * @name Register CAN_ESR1, field TWRNINT[17] (W1C) * * If the WRNEN bit in MCR is asserted, the TWRNINT bit is set when the TXWRN * flag transitions from 0 to 1, meaning that the Tx error counter reached 96. If * the corresponding mask bit in the Control Register (TWRNMSK) is set, an * interrupt is generated to the CPU. This bit is cleared by writing it to 1. When WRNEN * is negated, this flag is masked. CPU must clear this flag before disabling * the bit. Otherwise it will be set when the WRNEN is set again. Writing 0 has no * effect. This flag is not generated during Bus Off state. This bit is not * updated during Freeze mode. * * Values: * - 0 - No such occurrence. * - 1 - The Tx error counter transitioned from less than 96 to greater than or * equal to 96. */ /*@{*/ #define BP_CAN_ESR1_TWRNINT (17U) /*!< Bit position for CAN_ESR1_TWRNINT. */ #define BM_CAN_ESR1_TWRNINT (0x00020000U) /*!< Bit mask for CAN_ESR1_TWRNINT. */ #define BS_CAN_ESR1_TWRNINT (1U) /*!< Bit field size in bits for CAN_ESR1_TWRNINT. */ /*! @brief Read current value of the CAN_ESR1_TWRNINT field. */ #define BR_CAN_ESR1_TWRNINT(x) (BITBAND_ACCESS32(HW_CAN_ESR1_ADDR(x), BP_CAN_ESR1_TWRNINT)) /*! @brief Format value for bitfield CAN_ESR1_TWRNINT. */ #define BF_CAN_ESR1_TWRNINT(v) ((uint32_t)((uint32_t)(v) << BP_CAN_ESR1_TWRNINT) & BM_CAN_ESR1_TWRNINT) /*! @brief Set the TWRNINT field to a new value. */ #define BW_CAN_ESR1_TWRNINT(x, v) (BITBAND_ACCESS32(HW_CAN_ESR1_ADDR(x), BP_CAN_ESR1_TWRNINT) = (v)) /*@}*/ /*! * @name Register CAN_ESR1, field SYNCH[18] (RO) * * This read-only flag indicates whether the FlexCAN is synchronized to the CAN * bus and able to participate in the communication process. It is set and * cleared by the FlexCAN. See the table in the overall CAN_ESR1 register description. * * Values: * - 0 - FlexCAN is not synchronized to the CAN bus. * - 1 - FlexCAN is synchronized to the CAN bus. */ /*@{*/ #define BP_CAN_ESR1_SYNCH (18U) /*!< Bit position for CAN_ESR1_SYNCH. */ #define BM_CAN_ESR1_SYNCH (0x00040000U) /*!< Bit mask for CAN_ESR1_SYNCH. */ #define BS_CAN_ESR1_SYNCH (1U) /*!< Bit field size in bits for CAN_ESR1_SYNCH. */ /*! @brief Read current value of the CAN_ESR1_SYNCH field. */ #define BR_CAN_ESR1_SYNCH(x) (BITBAND_ACCESS32(HW_CAN_ESR1_ADDR(x), BP_CAN_ESR1_SYNCH)) /*@}*/ /******************************************************************************* * HW_CAN_IMASK1 - Interrupt Masks 1 register ******************************************************************************/ /*! * @brief HW_CAN_IMASK1 - Interrupt Masks 1 register (RW) * * Reset value: 0x00000000U * * This register allows any number of a range of the 32 Message Buffer * Interrupts to be enabled or disabled for MB31 to MB0. It contains one interrupt mask * bit per buffer, enabling the CPU to determine which buffer generates an * interrupt after a successful transmission or reception, that is, when the * corresponding IFLAG1 bit is set. */ typedef union _hw_can_imask1 { uint32_t U; struct _hw_can_imask1_bitfields { uint32_t BUFLM : 32; /*!< [31:0] Buffer MB i Mask */ } B; } hw_can_imask1_t; /*! * @name Constants and macros for entire CAN_IMASK1 register */ /*@{*/ #define HW_CAN_IMASK1_ADDR(x) ((x) + 0x28U) #define HW_CAN_IMASK1(x) (*(__IO hw_can_imask1_t *) HW_CAN_IMASK1_ADDR(x)) #define HW_CAN_IMASK1_RD(x) (HW_CAN_IMASK1(x).U) #define HW_CAN_IMASK1_WR(x, v) (HW_CAN_IMASK1(x).U = (v)) #define HW_CAN_IMASK1_SET(x, v) (HW_CAN_IMASK1_WR(x, HW_CAN_IMASK1_RD(x) | (v))) #define HW_CAN_IMASK1_CLR(x, v) (HW_CAN_IMASK1_WR(x, HW_CAN_IMASK1_RD(x) & ~(v))) #define HW_CAN_IMASK1_TOG(x, v) (HW_CAN_IMASK1_WR(x, HW_CAN_IMASK1_RD(x) ^ (v))) /*@}*/ /* * Constants & macros for individual CAN_IMASK1 bitfields */ /*! * @name Register CAN_IMASK1, field BUFLM[31:0] (RW) * * Each bit enables or disables the corresponding FlexCAN Message Buffer * Interrupt for MB31 to MB0. Setting or clearing a bit in the IMASK1 Register can * assert or negate an interrupt request, if the corresponding IFLAG1 bit is set. * * Values: * - 0 - The corresponding buffer Interrupt is disabled. * - 1 - The corresponding buffer Interrupt is enabled. */ /*@{*/ #define BP_CAN_IMASK1_BUFLM (0U) /*!< Bit position for CAN_IMASK1_BUFLM. */ #define BM_CAN_IMASK1_BUFLM (0xFFFFFFFFU) /*!< Bit mask for CAN_IMASK1_BUFLM. */ #define BS_CAN_IMASK1_BUFLM (32U) /*!< Bit field size in bits for CAN_IMASK1_BUFLM. */ /*! @brief Read current value of the CAN_IMASK1_BUFLM field. */ #define BR_CAN_IMASK1_BUFLM(x) (HW_CAN_IMASK1(x).U) /*! @brief Format value for bitfield CAN_IMASK1_BUFLM. */ #define BF_CAN_IMASK1_BUFLM(v) ((uint32_t)((uint32_t)(v) << BP_CAN_IMASK1_BUFLM) & BM_CAN_IMASK1_BUFLM) /*! @brief Set the BUFLM field to a new value. */ #define BW_CAN_IMASK1_BUFLM(x, v) (HW_CAN_IMASK1_WR(x, v)) /*@}*/ /******************************************************************************* * HW_CAN_IFLAG1 - Interrupt Flags 1 register ******************************************************************************/ /*! * @brief HW_CAN_IFLAG1 - Interrupt Flags 1 register (W1C) * * Reset value: 0x00000000U * * This register defines the flags for the 32 Message Buffer interrupts for MB31 * to MB0. It contains one interrupt flag bit per buffer. Each successful * transmission or reception sets the corresponding IFLAG1 bit. If the corresponding * IMASK1 bit is set, an interrupt will be generated. The interrupt flag must be * cleared by writing 1 to it. Writing 0 has no effect. The BUF7I to BUF5I flags * are also used to represent FIFO interrupts when the Rx FIFO is enabled. When the * bit MCR[RFEN] is set, the function of the 8 least significant interrupt flags * BUF[7:0]I changes: BUF7I, BUF6I and BUF5I indicate operating conditions of * the FIFO, and the BUF4TO0I field is reserved. Before enabling the RFEN, the CPU * must service the IFLAG bits asserted in the Rx FIFO region; see Section "Rx * FIFO". Otherwise, these IFLAG bits will mistakenly show the related MBs now * belonging to FIFO as having contents to be serviced. When the RFEN bit is negated, * the FIFO flags must be cleared. The same care must be taken when an RFFN * value is selected extending Rx FIFO filters beyond MB7. For example, when RFFN is * 0x8, the MB0-23 range is occupied by Rx FIFO filters and related IFLAG bits * must be cleared. Before updating MCR[MAXMB] field, CPU must service the IFLAG1 * bits whose MB value is greater than the MCR[MAXMB] to be updated; otherwise, * they will remain set and be inconsistent with the number of MBs available. */ typedef union _hw_can_iflag1 { uint32_t U; struct _hw_can_iflag1_bitfields { uint32_t BUF0I : 1; /*!< [0] Buffer MB0 Interrupt Or "reserved" */ uint32_t BUF4TO1I : 4; /*!< [4:1] Buffer MB i Interrupt Or "reserved" * */ uint32_t BUF5I : 1; /*!< [5] Buffer MB5 Interrupt Or "Frames * available in Rx FIFO" */ uint32_t BUF6I : 1; /*!< [6] Buffer MB6 Interrupt Or "Rx FIFO * Warning" */ uint32_t BUF7I : 1; /*!< [7] Buffer MB7 Interrupt Or "Rx FIFO * Overflow" */ uint32_t BUF31TO8I : 24; /*!< [31:8] Buffer MBi Interrupt */ } B; } hw_can_iflag1_t; /*! * @name Constants and macros for entire CAN_IFLAG1 register */ /*@{*/ #define HW_CAN_IFLAG1_ADDR(x) ((x) + 0x30U) #define HW_CAN_IFLAG1(x) (*(__IO hw_can_iflag1_t *) HW_CAN_IFLAG1_ADDR(x)) #define HW_CAN_IFLAG1_RD(x) (HW_CAN_IFLAG1(x).U) #define HW_CAN_IFLAG1_WR(x, v) (HW_CAN_IFLAG1(x).U = (v)) #define HW_CAN_IFLAG1_SET(x, v) (HW_CAN_IFLAG1_WR(x, HW_CAN_IFLAG1_RD(x) | (v))) #define HW_CAN_IFLAG1_CLR(x, v) (HW_CAN_IFLAG1_WR(x, HW_CAN_IFLAG1_RD(x) & ~(v))) #define HW_CAN_IFLAG1_TOG(x, v) (HW_CAN_IFLAG1_WR(x, HW_CAN_IFLAG1_RD(x) ^ (v))) /*@}*/ /* * Constants & macros for individual CAN_IFLAG1 bitfields */ /*! * @name Register CAN_IFLAG1, field BUF0I[0] (W1C) * * When the RFEN bit in the MCR is cleared (Rx FIFO disabled), this bit flags * the interrupt for MB0. This flag is cleared by the FlexCAN whenever the bit * MCR[RFEN] is changed by CPU writes. The BUF0I flag is reserved when MCR[RFEN] is * set. * * Values: * - 0 - The corresponding buffer has no occurrence of successfully completed * transmission or reception when MCR[RFEN]=0. * - 1 - The corresponding buffer has successfully completed transmission or * reception when MCR[RFEN]=0. */ /*@{*/ #define BP_CAN_IFLAG1_BUF0I (0U) /*!< Bit position for CAN_IFLAG1_BUF0I. */ #define BM_CAN_IFLAG1_BUF0I (0x00000001U) /*!< Bit mask for CAN_IFLAG1_BUF0I. */ #define BS_CAN_IFLAG1_BUF0I (1U) /*!< Bit field size in bits for CAN_IFLAG1_BUF0I. */ /*! @brief Read current value of the CAN_IFLAG1_BUF0I field. */ #define BR_CAN_IFLAG1_BUF0I(x) (BITBAND_ACCESS32(HW_CAN_IFLAG1_ADDR(x), BP_CAN_IFLAG1_BUF0I)) /*! @brief Format value for bitfield CAN_IFLAG1_BUF0I. */ #define BF_CAN_IFLAG1_BUF0I(v) ((uint32_t)((uint32_t)(v) << BP_CAN_IFLAG1_BUF0I) & BM_CAN_IFLAG1_BUF0I) /*! @brief Set the BUF0I field to a new value. */ #define BW_CAN_IFLAG1_BUF0I(x, v) (BITBAND_ACCESS32(HW_CAN_IFLAG1_ADDR(x), BP_CAN_IFLAG1_BUF0I) = (v)) /*@}*/ /*! * @name Register CAN_IFLAG1, field BUF4TO1I[4:1] (W1C) * * When the RFEN bit in the MCR is cleared (Rx FIFO disabled), these bits flag * the interrupts for MB4 to MB1. These flags are cleared by the FlexCAN whenever * the bit MCR[RFEN] is changed by CPU writes. The BUF4TO1I flags are reserved * when MCR[RFEN] is set. * * Values: * - 0 - The corresponding buffer has no occurrence of successfully completed * transmission or reception when MCR[RFEN]=0. * - 1 - The corresponding buffer has successfully completed transmission or * reception when MCR[RFEN]=0. */ /*@{*/ #define BP_CAN_IFLAG1_BUF4TO1I (1U) /*!< Bit position for CAN_IFLAG1_BUF4TO1I. */ #define BM_CAN_IFLAG1_BUF4TO1I (0x0000001EU) /*!< Bit mask for CAN_IFLAG1_BUF4TO1I. */ #define BS_CAN_IFLAG1_BUF4TO1I (4U) /*!< Bit field size in bits for CAN_IFLAG1_BUF4TO1I. */ /*! @brief Read current value of the CAN_IFLAG1_BUF4TO1I field. */ #define BR_CAN_IFLAG1_BUF4TO1I(x) (HW_CAN_IFLAG1(x).B.BUF4TO1I) /*! @brief Format value for bitfield CAN_IFLAG1_BUF4TO1I. */ #define BF_CAN_IFLAG1_BUF4TO1I(v) ((uint32_t)((uint32_t)(v) << BP_CAN_IFLAG1_BUF4TO1I) & BM_CAN_IFLAG1_BUF4TO1I) /*! @brief Set the BUF4TO1I field to a new value. */ #define BW_CAN_IFLAG1_BUF4TO1I(x, v) (HW_CAN_IFLAG1_WR(x, (HW_CAN_IFLAG1_RD(x) & ~BM_CAN_IFLAG1_BUF4TO1I) | BF_CAN_IFLAG1_BUF4TO1I(v))) /*@}*/ /*! * @name Register CAN_IFLAG1, field BUF5I[5] (W1C) * * When the RFEN bit in the MCR is cleared (Rx FIFO disabled), this bit flags * the interrupt for MB5. This flag is cleared by the FlexCAN whenever the bit * MCR[RFEN] is changed by CPU writes. The BUF5I flag represents "Frames available in * Rx FIFO" when MCR[RFEN] is set. In this case, the flag indicates that at * least one frame is available to be read from the Rx FIFO. * * Values: * - 0 - No occurrence of MB5 completing transmission/reception when * MCR[RFEN]=0, or of frame(s) available in the FIFO, when MCR[RFEN]=1 * - 1 - MB5 completed transmission/reception when MCR[RFEN]=0, or frame(s) * available in the Rx FIFO when MCR[RFEN]=1 */ /*@{*/ #define BP_CAN_IFLAG1_BUF5I (5U) /*!< Bit position for CAN_IFLAG1_BUF5I. */ #define BM_CAN_IFLAG1_BUF5I (0x00000020U) /*!< Bit mask for CAN_IFLAG1_BUF5I. */ #define BS_CAN_IFLAG1_BUF5I (1U) /*!< Bit field size in bits for CAN_IFLAG1_BUF5I. */ /*! @brief Read current value of the CAN_IFLAG1_BUF5I field. */ #define BR_CAN_IFLAG1_BUF5I(x) (BITBAND_ACCESS32(HW_CAN_IFLAG1_ADDR(x), BP_CAN_IFLAG1_BUF5I)) /*! @brief Format value for bitfield CAN_IFLAG1_BUF5I. */ #define BF_CAN_IFLAG1_BUF5I(v) ((uint32_t)((uint32_t)(v) << BP_CAN_IFLAG1_BUF5I) & BM_CAN_IFLAG1_BUF5I) /*! @brief Set the BUF5I field to a new value. */ #define BW_CAN_IFLAG1_BUF5I(x, v) (BITBAND_ACCESS32(HW_CAN_IFLAG1_ADDR(x), BP_CAN_IFLAG1_BUF5I) = (v)) /*@}*/ /*! * @name Register CAN_IFLAG1, field BUF6I[6] (W1C) * * When the RFEN bit in the MCR is cleared (Rx FIFO disabled), this bit flags * the interrupt for MB6. This flag is cleared by the FlexCAN whenever the bit * MCR[RFEN] is changed by CPU writes. The BUF6I flag represents "Rx FIFO Warning" * when MCR[RFEN] is set. In this case, the flag indicates when the number of * unread messages within the Rx FIFO is increased to 5 from 4 due to the reception of * a new one, meaning that the Rx FIFO is almost full. Note that if the flag is * cleared while the number of unread messages is greater than 4, it does not * assert again until the number of unread messages within the Rx FIFO is decreased * to be equal to or less than 4. * * Values: * - 0 - No occurrence of MB6 completing transmission/reception when * MCR[RFEN]=0, or of Rx FIFO almost full when MCR[RFEN]=1 * - 1 - MB6 completed transmission/reception when MCR[RFEN]=0, or Rx FIFO * almost full when MCR[RFEN]=1 */ /*@{*/ #define BP_CAN_IFLAG1_BUF6I (6U) /*!< Bit position for CAN_IFLAG1_BUF6I. */ #define BM_CAN_IFLAG1_BUF6I (0x00000040U) /*!< Bit mask for CAN_IFLAG1_BUF6I. */ #define BS_CAN_IFLAG1_BUF6I (1U) /*!< Bit field size in bits for CAN_IFLAG1_BUF6I. */ /*! @brief Read current value of the CAN_IFLAG1_BUF6I field. */ #define BR_CAN_IFLAG1_BUF6I(x) (BITBAND_ACCESS32(HW_CAN_IFLAG1_ADDR(x), BP_CAN_IFLAG1_BUF6I)) /*! @brief Format value for bitfield CAN_IFLAG1_BUF6I. */ #define BF_CAN_IFLAG1_BUF6I(v) ((uint32_t)((uint32_t)(v) << BP_CAN_IFLAG1_BUF6I) & BM_CAN_IFLAG1_BUF6I) /*! @brief Set the BUF6I field to a new value. */ #define BW_CAN_IFLAG1_BUF6I(x, v) (BITBAND_ACCESS32(HW_CAN_IFLAG1_ADDR(x), BP_CAN_IFLAG1_BUF6I) = (v)) /*@}*/ /*! * @name Register CAN_IFLAG1, field BUF7I[7] (W1C) * * When the RFEN bit in the MCR is cleared (Rx FIFO disabled), this bit flags * the interrupt for MB7. This flag is cleared by the FlexCAN whenever the bit * MCR[RFEN] is changed by CPU writes. The BUF7I flag represents "Rx FIFO Overflow" * when MCR[RFEN] is set. In this case, the flag indicates that a message was lost * because the Rx FIFO is full. Note that the flag will not be asserted when the * Rx FIFO is full and the message was captured by a Mailbox. * * Values: * - 0 - No occurrence of MB7 completing transmission/reception when * MCR[RFEN]=0, or of Rx FIFO overflow when MCR[RFEN]=1 * - 1 - MB7 completed transmission/reception when MCR[RFEN]=0, or Rx FIFO * overflow when MCR[RFEN]=1 */ /*@{*/ #define BP_CAN_IFLAG1_BUF7I (7U) /*!< Bit position for CAN_IFLAG1_BUF7I. */ #define BM_CAN_IFLAG1_BUF7I (0x00000080U) /*!< Bit mask for CAN_IFLAG1_BUF7I. */ #define BS_CAN_IFLAG1_BUF7I (1U) /*!< Bit field size in bits for CAN_IFLAG1_BUF7I. */ /*! @brief Read current value of the CAN_IFLAG1_BUF7I field. */ #define BR_CAN_IFLAG1_BUF7I(x) (BITBAND_ACCESS32(HW_CAN_IFLAG1_ADDR(x), BP_CAN_IFLAG1_BUF7I)) /*! @brief Format value for bitfield CAN_IFLAG1_BUF7I. */ #define BF_CAN_IFLAG1_BUF7I(v) ((uint32_t)((uint32_t)(v) << BP_CAN_IFLAG1_BUF7I) & BM_CAN_IFLAG1_BUF7I) /*! @brief Set the BUF7I field to a new value. */ #define BW_CAN_IFLAG1_BUF7I(x, v) (BITBAND_ACCESS32(HW_CAN_IFLAG1_ADDR(x), BP_CAN_IFLAG1_BUF7I) = (v)) /*@}*/ /*! * @name Register CAN_IFLAG1, field BUF31TO8I[31:8] (W1C) * * Each bit flags the corresponding FlexCAN Message Buffer interrupt for MB31 to * MB8. * * Values: * - 0 - The corresponding buffer has no occurrence of successfully completed * transmission or reception. * - 1 - The corresponding buffer has successfully completed transmission or * reception. */ /*@{*/ #define BP_CAN_IFLAG1_BUF31TO8I (8U) /*!< Bit position for CAN_IFLAG1_BUF31TO8I. */ #define BM_CAN_IFLAG1_BUF31TO8I (0xFFFFFF00U) /*!< Bit mask for CAN_IFLAG1_BUF31TO8I. */ #define BS_CAN_IFLAG1_BUF31TO8I (24U) /*!< Bit field size in bits for CAN_IFLAG1_BUF31TO8I. */ /*! @brief Read current value of the CAN_IFLAG1_BUF31TO8I field. */ #define BR_CAN_IFLAG1_BUF31TO8I(x) (HW_CAN_IFLAG1(x).B.BUF31TO8I) /*! @brief Format value for bitfield CAN_IFLAG1_BUF31TO8I. */ #define BF_CAN_IFLAG1_BUF31TO8I(v) ((uint32_t)((uint32_t)(v) << BP_CAN_IFLAG1_BUF31TO8I) & BM_CAN_IFLAG1_BUF31TO8I) /*! @brief Set the BUF31TO8I field to a new value. */ #define BW_CAN_IFLAG1_BUF31TO8I(x, v) (HW_CAN_IFLAG1_WR(x, (HW_CAN_IFLAG1_RD(x) & ~BM_CAN_IFLAG1_BUF31TO8I) | BF_CAN_IFLAG1_BUF31TO8I(v))) /*@}*/ /******************************************************************************* * HW_CAN_CTRL2 - Control 2 register ******************************************************************************/ /*! * @brief HW_CAN_CTRL2 - Control 2 register (RW) * * Reset value: 0x00B00000U * * This register contains control bits for CAN errors, FIFO features, and mode * selection. */ typedef union _hw_can_ctrl2 { uint32_t U; struct _hw_can_ctrl2_bitfields { uint32_t RESERVED0 : 16; /*!< [15:0] */ uint32_t EACEN : 1; /*!< [16] Entire Frame Arbitration Field * Comparison Enable For Rx Mailboxes */ uint32_t RRS : 1; /*!< [17] Remote Request Storing */ uint32_t MRP : 1; /*!< [18] Mailboxes Reception Priority */ uint32_t TASD : 5; /*!< [23:19] Tx Arbitration Start Delay */ uint32_t RFFN : 4; /*!< [27:24] Number Of Rx FIFO Filters */ uint32_t WRMFRZ : 1; /*!< [28] Write-Access To Memory In Freeze Mode * */ uint32_t RESERVED1 : 3; /*!< [31:29] */ } B; } hw_can_ctrl2_t; /*! * @name Constants and macros for entire CAN_CTRL2 register */ /*@{*/ #define HW_CAN_CTRL2_ADDR(x) ((x) + 0x34U) #define HW_CAN_CTRL2(x) (*(__IO hw_can_ctrl2_t *) HW_CAN_CTRL2_ADDR(x)) #define HW_CAN_CTRL2_RD(x) (HW_CAN_CTRL2(x).U) #define HW_CAN_CTRL2_WR(x, v) (HW_CAN_CTRL2(x).U = (v)) #define HW_CAN_CTRL2_SET(x, v) (HW_CAN_CTRL2_WR(x, HW_CAN_CTRL2_RD(x) | (v))) #define HW_CAN_CTRL2_CLR(x, v) (HW_CAN_CTRL2_WR(x, HW_CAN_CTRL2_RD(x) & ~(v))) #define HW_CAN_CTRL2_TOG(x, v) (HW_CAN_CTRL2_WR(x, HW_CAN_CTRL2_RD(x) ^ (v))) /*@}*/ /* * Constants & macros for individual CAN_CTRL2 bitfields */ /*! * @name Register CAN_CTRL2, field EACEN[16] (RW) * * This bit controls the comparison of IDE and RTR bits whithin Rx Mailboxes * filters with their corresponding bits in the incoming frame by the matching * process. This bit does not affect matching for Rx FIFO. This bit can be written * only in Freeze mode because it is blocked by hardware in other modes. * * Values: * - 0 - Rx Mailbox filter's IDE bit is always compared and RTR is never * compared despite mask bits. * - 1 - Enables the comparison of both Rx Mailbox filter's IDE and RTR bit with * their corresponding bits within the incoming frame. Mask bits do apply. */ /*@{*/ #define BP_CAN_CTRL2_EACEN (16U) /*!< Bit position for CAN_CTRL2_EACEN. */ #define BM_CAN_CTRL2_EACEN (0x00010000U) /*!< Bit mask for CAN_CTRL2_EACEN. */ #define BS_CAN_CTRL2_EACEN (1U) /*!< Bit field size in bits for CAN_CTRL2_EACEN. */ /*! @brief Read current value of the CAN_CTRL2_EACEN field. */ #define BR_CAN_CTRL2_EACEN(x) (BITBAND_ACCESS32(HW_CAN_CTRL2_ADDR(x), BP_CAN_CTRL2_EACEN)) /*! @brief Format value for bitfield CAN_CTRL2_EACEN. */ #define BF_CAN_CTRL2_EACEN(v) ((uint32_t)((uint32_t)(v) << BP_CAN_CTRL2_EACEN) & BM_CAN_CTRL2_EACEN) /*! @brief Set the EACEN field to a new value. */ #define BW_CAN_CTRL2_EACEN(x, v) (BITBAND_ACCESS32(HW_CAN_CTRL2_ADDR(x), BP_CAN_CTRL2_EACEN) = (v)) /*@}*/ /*! * @name Register CAN_CTRL2, field RRS[17] (RW) * * If this bit is asserted Remote Request Frame is submitted to a matching * process and stored in the corresponding Message Buffer in the same fashion of a * Data Frame. No automatic Remote Response Frame will be generated. If this bit is * negated the Remote Request Frame is submitted to a matching process and an * automatic Remote Response Frame is generated if a Message Buffer with CODE=0b1010 * is found with the same ID. This bit can be written only in Freeze mode * because it is blocked by hardware in other modes. * * Values: * - 0 - Remote Response Frame is generated. * - 1 - Remote Request Frame is stored. */ /*@{*/ #define BP_CAN_CTRL2_RRS (17U) /*!< Bit position for CAN_CTRL2_RRS. */ #define BM_CAN_CTRL2_RRS (0x00020000U) /*!< Bit mask for CAN_CTRL2_RRS. */ #define BS_CAN_CTRL2_RRS (1U) /*!< Bit field size in bits for CAN_CTRL2_RRS. */ /*! @brief Read current value of the CAN_CTRL2_RRS field. */ #define BR_CAN_CTRL2_RRS(x) (BITBAND_ACCESS32(HW_CAN_CTRL2_ADDR(x), BP_CAN_CTRL2_RRS)) /*! @brief Format value for bitfield CAN_CTRL2_RRS. */ #define BF_CAN_CTRL2_RRS(v) ((uint32_t)((uint32_t)(v) << BP_CAN_CTRL2_RRS) & BM_CAN_CTRL2_RRS) /*! @brief Set the RRS field to a new value. */ #define BW_CAN_CTRL2_RRS(x, v) (BITBAND_ACCESS32(HW_CAN_CTRL2_ADDR(x), BP_CAN_CTRL2_RRS) = (v)) /*@}*/ /*! * @name Register CAN_CTRL2, field MRP[18] (RW) * * If this bit is set the matching process starts from the Mailboxes and if no * match occurs the matching continues on the Rx FIFO. This bit can be written * only in Freeze mode because it is blocked by hardware in other modes. * * Values: * - 0 - Matching starts from Rx FIFO and continues on Mailboxes. * - 1 - Matching starts from Mailboxes and continues on Rx FIFO. */ /*@{*/ #define BP_CAN_CTRL2_MRP (18U) /*!< Bit position for CAN_CTRL2_MRP. */ #define BM_CAN_CTRL2_MRP (0x00040000U) /*!< Bit mask for CAN_CTRL2_MRP. */ #define BS_CAN_CTRL2_MRP (1U) /*!< Bit field size in bits for CAN_CTRL2_MRP. */ /*! @brief Read current value of the CAN_CTRL2_MRP field. */ #define BR_CAN_CTRL2_MRP(x) (BITBAND_ACCESS32(HW_CAN_CTRL2_ADDR(x), BP_CAN_CTRL2_MRP)) /*! @brief Format value for bitfield CAN_CTRL2_MRP. */ #define BF_CAN_CTRL2_MRP(v) ((uint32_t)((uint32_t)(v) << BP_CAN_CTRL2_MRP) & BM_CAN_CTRL2_MRP) /*! @brief Set the MRP field to a new value. */ #define BW_CAN_CTRL2_MRP(x, v) (BITBAND_ACCESS32(HW_CAN_CTRL2_ADDR(x), BP_CAN_CTRL2_MRP) = (v)) /*@}*/ /*! * @name Register CAN_CTRL2, field TASD[23:19] (RW) * * This 5-bit field indicates how many CAN bits the Tx arbitration process start * point can be delayed from the first bit of CRC field on CAN bus. This field * can be written only in Freeze mode because it is blocked by hardware in other * modes. This field is useful to optimize the transmit performance based on * factors such as: peripheral/serial clock ratio, CAN bit timing and number of MBs. * The duration of an arbitration process, in terms of CAN bits, is directly * proportional to the number of available MBs and CAN baud rate and inversely * proportional to the peripheral clock frequency. The optimal arbitration timing is * that in which the last MB is scanned right before the first bit of the * Intermission field of a CAN frame. Therefore, if there are few MBs and the system/serial * clock ratio is high and the CAN baud rate is low then the arbitration can be * delayed and vice-versa. If TASD is 0 then the arbitration start is not * delayed, thus the CPU has less time to configure a Tx MB for the next arbitration, * but more time is reserved for arbitration. On the other hand, if TASD is 24 then * the CPU can configure a Tx MB later and less time is reserved for * arbitration. If too little time is reserved for arbitration the FlexCAN may be not able * to find winner MBs in time to compete with other nodes for the CAN bus. If the * arbitration ends too much time before the first bit of Intermission field then * there is a chance that the CPU reconfigures some Tx MBs and the winner MB is * not the best to be transmitted. The optimal configuration for TASD can be * calculated as: TASD = 25 - {f CANCLK * [MAXMB + 3 - (RFEN * 8) - (RFEN * RFFN * * 2)] * 2} / {f SYS * [1+(PSEG1+1)+(PSEG2+1)+(PROPSEG+1)] * (PRESDIV+1)} where: f * CANCLK is the Protocol Engine (PE) Clock (see section "Protocol Timing"), in * Hz f SYS is the peripheral clock, in Hz MAXMB is the value in CTRL1[MAXMB] * field RFEN is the value in CTRL1[RFEN] bit RFFN is the value in CTRL2[RFFN] field * PSEG1 is the value in CTRL1[PSEG1] field PSEG2 is the value in CTRL1[PSEG2] * field PROPSEG is the value in CTRL1[PROPSEG] field PRESDIV is the value in * CTRL1[PRESDIV] field See Section "Arbitration process" and Section "Protocol * Timing" for more details. */ /*@{*/ #define BP_CAN_CTRL2_TASD (19U) /*!< Bit position for CAN_CTRL2_TASD. */ #define BM_CAN_CTRL2_TASD (0x00F80000U) /*!< Bit mask for CAN_CTRL2_TASD. */ #define BS_CAN_CTRL2_TASD (5U) /*!< Bit field size in bits for CAN_CTRL2_TASD. */ /*! @brief Read current value of the CAN_CTRL2_TASD field. */ #define BR_CAN_CTRL2_TASD(x) (HW_CAN_CTRL2(x).B.TASD) /*! @brief Format value for bitfield CAN_CTRL2_TASD. */ #define BF_CAN_CTRL2_TASD(v) ((uint32_t)((uint32_t)(v) << BP_CAN_CTRL2_TASD) & BM_CAN_CTRL2_TASD) /*! @brief Set the TASD field to a new value. */ #define BW_CAN_CTRL2_TASD(x, v) (HW_CAN_CTRL2_WR(x, (HW_CAN_CTRL2_RD(x) & ~BM_CAN_CTRL2_TASD) | BF_CAN_CTRL2_TASD(v))) /*@}*/ /*! * @name Register CAN_CTRL2, field RFFN[27:24] (RW) * * This 4-bit field defines the number of Rx FIFO filters, as shown in the * following table. The maximum selectable number of filters is determined by the MCU. * This field can only be written in Freeze mode as it is blocked by hardware in * other modes. This field must not be programmed with values that make the * number of Message Buffers occupied by Rx FIFO and ID Filter exceed the number of * Mailboxes present, defined by MCR[MAXMB]. Each group of eight filters occupies * a memory space equivalent to two Message Buffers which means that the more * filters are implemented the less Mailboxes will be available. Considering that * the Rx FIFO occupies the memory space originally reserved for MB0-5, RFFN should * be programmed with a value correponding to a number of filters not greater * than the number of available memory words which can be calculated as follows: * (SETUP_MB - 6) * 4 where SETUP_MB is the least between NUMBER_OF_MB and MAXMB. * The number of remaining Mailboxes available will be: (SETUP_MB - 8) - (RFFN * * 2) If the Number of Rx FIFO Filters programmed through RFFN exceeds the * SETUP_MB value (memory space available) the exceeding ones will not be functional. * RFFN[3:0] Number of Rx FIFO filters Message Buffers occupied by Rx FIFO and ID * Filter Table Remaining Available MailboxesThe number of the last remaining * available mailboxes is defined by the least value between the parameter * NUMBER_OF_MB minus 1 and the MCR[MAXMB] field. Rx FIFO ID Filter Table Elements Affected * by Rx Individual MasksIf Rx Individual Mask Registers are not enabled then * all Rx FIFO filters are affected by the Rx FIFO Global Mask. Rx FIFO ID Filter * Table Elements Affected by Rx FIFO Global Mask #rxfgmask-note 0x0 8 MB 0-7 MB * 8-63 Elements 0-7 none 0x1 16 MB 0-9 MB 10-63 Elements 0-9 Elements 10-15 0x2 * 24 MB 0-11 MB 12-63 Elements 0-11 Elements 12-23 0x3 32 MB 0-13 MB 14-63 * Elements 0-13 Elements 14-31 0x4 40 MB 0-15 MB 16-63 Elements 0-15 Elements 16-39 * 0x5 48 MB 0-17 MB 18-63 Elements 0-17 Elements 18-47 0x6 56 MB 0-19 MB 20-63 * Elements 0-19 Elements 20-55 0x7 64 MB 0-21 MB 22-63 Elements 0-21 Elements 22-63 * 0x8 72 MB 0-23 MB 24-63 Elements 0-23 Elements 24-71 0x9 80 MB 0-25 MB 26-63 * Elements 0-25 Elements 26-79 0xA 88 MB 0-27 MB 28-63 Elements 0-27 Elements * 28-87 0xB 96 MB 0-29 MB 30-63 Elements 0-29 Elements 30-95 0xC 104 MB 0-31 MB * 32-63 Elements 0-31 Elements 32-103 0xD 112 MB 0-33 MB 34-63 Elements 0-31 * Elements 32-111 0xE 120 MB 0-35 MB 36-63 Elements 0-31 Elements 32-119 0xF 128 MB * 0-37 MB 38-63 Elements 0-31 Elements 32-127 */ /*@{*/ #define BP_CAN_CTRL2_RFFN (24U) /*!< Bit position for CAN_CTRL2_RFFN. */ #define BM_CAN_CTRL2_RFFN (0x0F000000U) /*!< Bit mask for CAN_CTRL2_RFFN. */ #define BS_CAN_CTRL2_RFFN (4U) /*!< Bit field size in bits for CAN_CTRL2_RFFN. */ /*! @brief Read current value of the CAN_CTRL2_RFFN field. */ #define BR_CAN_CTRL2_RFFN(x) (HW_CAN_CTRL2(x).B.RFFN) /*! @brief Format value for bitfield CAN_CTRL2_RFFN. */ #define BF_CAN_CTRL2_RFFN(v) ((uint32_t)((uint32_t)(v) << BP_CAN_CTRL2_RFFN) & BM_CAN_CTRL2_RFFN) /*! @brief Set the RFFN field to a new value. */ #define BW_CAN_CTRL2_RFFN(x, v) (HW_CAN_CTRL2_WR(x, (HW_CAN_CTRL2_RD(x) & ~BM_CAN_CTRL2_RFFN) | BF_CAN_CTRL2_RFFN(v))) /*@}*/ /*! * @name Register CAN_CTRL2, field WRMFRZ[28] (RW) * * Enable unrestricted write access to FlexCAN memory in Freeze mode. This bit * can only be written in Freeze mode and has no effect out of Freeze mode. * * Values: * - 0 - Maintain the write access restrictions. * - 1 - Enable unrestricted write access to FlexCAN memory. */ /*@{*/ #define BP_CAN_CTRL2_WRMFRZ (28U) /*!< Bit position for CAN_CTRL2_WRMFRZ. */ #define BM_CAN_CTRL2_WRMFRZ (0x10000000U) /*!< Bit mask for CAN_CTRL2_WRMFRZ. */ #define BS_CAN_CTRL2_WRMFRZ (1U) /*!< Bit field size in bits for CAN_CTRL2_WRMFRZ. */ /*! @brief Read current value of the CAN_CTRL2_WRMFRZ field. */ #define BR_CAN_CTRL2_WRMFRZ(x) (BITBAND_ACCESS32(HW_CAN_CTRL2_ADDR(x), BP_CAN_CTRL2_WRMFRZ)) /*! @brief Format value for bitfield CAN_CTRL2_WRMFRZ. */ #define BF_CAN_CTRL2_WRMFRZ(v) ((uint32_t)((uint32_t)(v) << BP_CAN_CTRL2_WRMFRZ) & BM_CAN_CTRL2_WRMFRZ) /*! @brief Set the WRMFRZ field to a new value. */ #define BW_CAN_CTRL2_WRMFRZ(x, v) (BITBAND_ACCESS32(HW_CAN_CTRL2_ADDR(x), BP_CAN_CTRL2_WRMFRZ) = (v)) /*@}*/ /******************************************************************************* * HW_CAN_ESR2 - Error and Status 2 register ******************************************************************************/ /*! * @brief HW_CAN_ESR2 - Error and Status 2 register (RO) * * Reset value: 0x00000000U * * This register reflects various interrupt flags and some general status. */ typedef union _hw_can_esr2 { uint32_t U; struct _hw_can_esr2_bitfields { uint32_t RESERVED0 : 13; /*!< [12:0] */ uint32_t IMB : 1; /*!< [13] Inactive Mailbox */ uint32_t VPS : 1; /*!< [14] Valid Priority Status */ uint32_t RESERVED1 : 1; /*!< [15] */ uint32_t LPTM : 7; /*!< [22:16] Lowest Priority Tx Mailbox */ uint32_t RESERVED2 : 9; /*!< [31:23] */ } B; } hw_can_esr2_t; /*! * @name Constants and macros for entire CAN_ESR2 register */ /*@{*/ #define HW_CAN_ESR2_ADDR(x) ((x) + 0x38U) #define HW_CAN_ESR2(x) (*(__I hw_can_esr2_t *) HW_CAN_ESR2_ADDR(x)) #define HW_CAN_ESR2_RD(x) (HW_CAN_ESR2(x).U) /*@}*/ /* * Constants & macros for individual CAN_ESR2 bitfields */ /*! * @name Register CAN_ESR2, field IMB[13] (RO) * * If ESR2[VPS] is asserted, this bit indicates whether there is any inactive * Mailbox (CODE field is either 0b1000 or 0b0000). This bit is asserted in the * following cases: During arbitration, if an LPTM is found and it is inactive. If * IMB is not asserted and a frame is transmitted successfully. This bit is * cleared in all start of arbitration (see Section "Arbitration process"). LPTM * mechanism have the following behavior: if an MB is successfully transmitted and * ESR2[IMB]=0 (no inactive Mailbox), then ESR2[VPS] and ESR2[IMB] are asserted and * the index related to the MB just transmitted is loaded into ESR2[LPTM]. * * Values: * - 0 - If ESR2[VPS] is asserted, the ESR2[LPTM] is not an inactive Mailbox. * - 1 - If ESR2[VPS] is asserted, there is at least one inactive Mailbox. LPTM * content is the number of the first one. */ /*@{*/ #define BP_CAN_ESR2_IMB (13U) /*!< Bit position for CAN_ESR2_IMB. */ #define BM_CAN_ESR2_IMB (0x00002000U) /*!< Bit mask for CAN_ESR2_IMB. */ #define BS_CAN_ESR2_IMB (1U) /*!< Bit field size in bits for CAN_ESR2_IMB. */ /*! @brief Read current value of the CAN_ESR2_IMB field. */ #define BR_CAN_ESR2_IMB(x) (BITBAND_ACCESS32(HW_CAN_ESR2_ADDR(x), BP_CAN_ESR2_IMB)) /*@}*/ /*! * @name Register CAN_ESR2, field VPS[14] (RO) * * This bit indicates whether IMB and LPTM contents are currently valid or not. * VPS is asserted upon every complete Tx arbitration process unless the CPU * writes to Control and Status word of a Mailbox that has already been scanned, that * is, it is behind Tx Arbitration Pointer, during the Tx arbitration process. * If there is no inactive Mailbox and only one Tx Mailbox that is being * transmitted then VPS is not asserted. VPS is negated upon the start of every Tx * arbitration process or upon a write to Control and Status word of any Mailbox. * ESR2[VPS] is not affected by any CPU write into Control Status (C/S) of a MB that is * blocked by abort mechanism. When MCR[AEN] is asserted, the abort code write * in C/S of a MB that is being transmitted (pending abort), or any write attempt * into a Tx MB with IFLAG set is blocked. * * Values: * - 0 - Contents of IMB and LPTM are invalid. * - 1 - Contents of IMB and LPTM are valid. */ /*@{*/ #define BP_CAN_ESR2_VPS (14U) /*!< Bit position for CAN_ESR2_VPS. */ #define BM_CAN_ESR2_VPS (0x00004000U) /*!< Bit mask for CAN_ESR2_VPS. */ #define BS_CAN_ESR2_VPS (1U) /*!< Bit field size in bits for CAN_ESR2_VPS. */ /*! @brief Read current value of the CAN_ESR2_VPS field. */ #define BR_CAN_ESR2_VPS(x) (BITBAND_ACCESS32(HW_CAN_ESR2_ADDR(x), BP_CAN_ESR2_VPS)) /*@}*/ /*! * @name Register CAN_ESR2, field LPTM[22:16] (RO) * * If ESR2[VPS] is asserted, this field indicates the lowest number inactive * Mailbox (see the IMB bit description). If there is no inactive Mailbox then the * Mailbox indicated depends on CTRL1[LBUF] bit value. If CTRL1[LBUF] bit is * negated then the Mailbox indicated is the one that has the greatest arbitration * value (see the "Highest priority Mailbox first" section). If CTRL1[LBUF] bit is * asserted then the Mailbox indicated is the highest number active Tx Mailbox. If * a Tx Mailbox is being transmitted it is not considered in LPTM calculation. * If ESR2[IMB] is not asserted and a frame is transmitted successfully, LPTM is * updated with its Mailbox number. */ /*@{*/ #define BP_CAN_ESR2_LPTM (16U) /*!< Bit position for CAN_ESR2_LPTM. */ #define BM_CAN_ESR2_LPTM (0x007F0000U) /*!< Bit mask for CAN_ESR2_LPTM. */ #define BS_CAN_ESR2_LPTM (7U) /*!< Bit field size in bits for CAN_ESR2_LPTM. */ /*! @brief Read current value of the CAN_ESR2_LPTM field. */ #define BR_CAN_ESR2_LPTM(x) (HW_CAN_ESR2(x).B.LPTM) /*@}*/ /******************************************************************************* * HW_CAN_CRCR - CRC Register ******************************************************************************/ /*! * @brief HW_CAN_CRCR - CRC Register (RO) * * Reset value: 0x00000000U * * This register provides information about the CRC of transmitted messages. */ typedef union _hw_can_crcr { uint32_t U; struct _hw_can_crcr_bitfields { uint32_t TXCRC : 15; /*!< [14:0] CRC Transmitted */ uint32_t RESERVED0 : 1; /*!< [15] */ uint32_t MBCRC : 7; /*!< [22:16] CRC Mailbox */ uint32_t RESERVED1 : 9; /*!< [31:23] */ } B; } hw_can_crcr_t; /*! * @name Constants and macros for entire CAN_CRCR register */ /*@{*/ #define HW_CAN_CRCR_ADDR(x) ((x) + 0x44U) #define HW_CAN_CRCR(x) (*(__I hw_can_crcr_t *) HW_CAN_CRCR_ADDR(x)) #define HW_CAN_CRCR_RD(x) (HW_CAN_CRCR(x).U) /*@}*/ /* * Constants & macros for individual CAN_CRCR bitfields */ /*! * @name Register CAN_CRCR, field TXCRC[14:0] (RO) * * This field indicates the CRC value of the last message transmitted. This * field is updated at the same time the Tx Interrupt Flag is asserted. */ /*@{*/ #define BP_CAN_CRCR_TXCRC (0U) /*!< Bit position for CAN_CRCR_TXCRC. */ #define BM_CAN_CRCR_TXCRC (0x00007FFFU) /*!< Bit mask for CAN_CRCR_TXCRC. */ #define BS_CAN_CRCR_TXCRC (15U) /*!< Bit field size in bits for CAN_CRCR_TXCRC. */ /*! @brief Read current value of the CAN_CRCR_TXCRC field. */ #define BR_CAN_CRCR_TXCRC(x) (HW_CAN_CRCR(x).B.TXCRC) /*@}*/ /*! * @name Register CAN_CRCR, field MBCRC[22:16] (RO) * * This field indicates the number of the Mailbox corresponding to the value in * TXCRC field. */ /*@{*/ #define BP_CAN_CRCR_MBCRC (16U) /*!< Bit position for CAN_CRCR_MBCRC. */ #define BM_CAN_CRCR_MBCRC (0x007F0000U) /*!< Bit mask for CAN_CRCR_MBCRC. */ #define BS_CAN_CRCR_MBCRC (7U) /*!< Bit field size in bits for CAN_CRCR_MBCRC. */ /*! @brief Read current value of the CAN_CRCR_MBCRC field. */ #define BR_CAN_CRCR_MBCRC(x) (HW_CAN_CRCR(x).B.MBCRC) /*@}*/ /******************************************************************************* * HW_CAN_RXFGMASK - Rx FIFO Global Mask register ******************************************************************************/ /*! * @brief HW_CAN_RXFGMASK - Rx FIFO Global Mask register (RW) * * Reset value: 0xFFFFFFFFU * * This register is located in RAM. If Rx FIFO is enabled RXFGMASK is used to * mask the Rx FIFO ID Filter Table elements that do not have a corresponding RXIMR * according to CTRL2[RFFN] field setting. This register can only be written in * Freeze mode as it is blocked by hardware in other modes. */ typedef union _hw_can_rxfgmask { uint32_t U; struct _hw_can_rxfgmask_bitfields { uint32_t FGM : 32; /*!< [31:0] Rx FIFO Global Mask Bits */ } B; } hw_can_rxfgmask_t; /*! * @name Constants and macros for entire CAN_RXFGMASK register */ /*@{*/ #define HW_CAN_RXFGMASK_ADDR(x) ((x) + 0x48U) #define HW_CAN_RXFGMASK(x) (*(__IO hw_can_rxfgmask_t *) HW_CAN_RXFGMASK_ADDR(x)) #define HW_CAN_RXFGMASK_RD(x) (HW_CAN_RXFGMASK(x).U) #define HW_CAN_RXFGMASK_WR(x, v) (HW_CAN_RXFGMASK(x).U = (v)) #define HW_CAN_RXFGMASK_SET(x, v) (HW_CAN_RXFGMASK_WR(x, HW_CAN_RXFGMASK_RD(x) | (v))) #define HW_CAN_RXFGMASK_CLR(x, v) (HW_CAN_RXFGMASK_WR(x, HW_CAN_RXFGMASK_RD(x) & ~(v))) #define HW_CAN_RXFGMASK_TOG(x, v) (HW_CAN_RXFGMASK_WR(x, HW_CAN_RXFGMASK_RD(x) ^ (v))) /*@}*/ /* * Constants & macros for individual CAN_RXFGMASK bitfields */ /*! * @name Register CAN_RXFGMASK, field FGM[31:0] (RW) * * These bits mask the ID Filter Table elements bits in a perfect alignment. The * following table shows how the FGM bits correspond to each IDAF field. Rx FIFO * ID Filter Table Elements Format (MCR[IDAM]) Identifier Acceptance Filter * Fields RTR IDE RXIDA RXIDB If MCR[IDAM] field is equivalent to the format B only * the fourteen most significant bits of the Identifier of the incoming frame are * compared with the Rx FIFO filter. RXIDC If MCR[IDAM] field is equivalent to * the format C only the eight most significant bits of the Identifier of the * incoming frame are compared with the Rx FIFO filter. Reserved A FGM[31] FGM[30] * FGM[29:1] - - FGM[0] B FGM[31], FGM[15] FGM[30], FGM[14] - FGM[29:16], FGM[13:0] * - C - - - FGM[31:24], FGM[23:16], FGM[15:8], FGM[7:0] * * Values: * - 0 - The corresponding bit in the filter is "don't care." * - 1 - The corresponding bit in the filter is checked. */ /*@{*/ #define BP_CAN_RXFGMASK_FGM (0U) /*!< Bit position for CAN_RXFGMASK_FGM. */ #define BM_CAN_RXFGMASK_FGM (0xFFFFFFFFU) /*!< Bit mask for CAN_RXFGMASK_FGM. */ #define BS_CAN_RXFGMASK_FGM (32U) /*!< Bit field size in bits for CAN_RXFGMASK_FGM. */ /*! @brief Read current value of the CAN_RXFGMASK_FGM field. */ #define BR_CAN_RXFGMASK_FGM(x) (HW_CAN_RXFGMASK(x).U) /*! @brief Format value for bitfield CAN_RXFGMASK_FGM. */ #define BF_CAN_RXFGMASK_FGM(v) ((uint32_t)((uint32_t)(v) << BP_CAN_RXFGMASK_FGM) & BM_CAN_RXFGMASK_FGM) /*! @brief Set the FGM field to a new value. */ #define BW_CAN_RXFGMASK_FGM(x, v) (HW_CAN_RXFGMASK_WR(x, v)) /*@}*/ /******************************************************************************* * HW_CAN_RXFIR - Rx FIFO Information Register ******************************************************************************/ /*! * @brief HW_CAN_RXFIR - Rx FIFO Information Register (RO) * * Reset value: 0x00000000U * * RXFIR provides information on Rx FIFO. This register is the port through * which the CPU accesses the output of the RXFIR FIFO located in RAM. The RXFIR FIFO * is written by the FlexCAN whenever a new message is moved into the Rx FIFO as * well as its output is updated whenever the output of the Rx FIFO is updated * with the next message. See Section "Rx FIFO" for instructions on reading this * register. */ typedef union _hw_can_rxfir { uint32_t U; struct _hw_can_rxfir_bitfields { uint32_t IDHIT : 9; /*!< [8:0] Identifier Acceptance Filter Hit * Indicator */ uint32_t RESERVED0 : 23; /*!< [31:9] */ } B; } hw_can_rxfir_t; /*! * @name Constants and macros for entire CAN_RXFIR register */ /*@{*/ #define HW_CAN_RXFIR_ADDR(x) ((x) + 0x4CU) #define HW_CAN_RXFIR(x) (*(__I hw_can_rxfir_t *) HW_CAN_RXFIR_ADDR(x)) #define HW_CAN_RXFIR_RD(x) (HW_CAN_RXFIR(x).U) /*@}*/ /* * Constants & macros for individual CAN_RXFIR bitfields */ /*! * @name Register CAN_RXFIR, field IDHIT[8:0] (RO) * * This field indicates which Identifier Acceptance Filter was hit by the * received message that is in the output of the Rx FIFO. If multiple filters match the * incoming message ID then the first matching IDAF found (lowest number) by the * matching process is indicated. This field is valid only while the * IFLAG[BUF5I] is asserted. */ /*@{*/ #define BP_CAN_RXFIR_IDHIT (0U) /*!< Bit position for CAN_RXFIR_IDHIT. */ #define BM_CAN_RXFIR_IDHIT (0x000001FFU) /*!< Bit mask for CAN_RXFIR_IDHIT. */ #define BS_CAN_RXFIR_IDHIT (9U) /*!< Bit field size in bits for CAN_RXFIR_IDHIT. */ /*! @brief Read current value of the CAN_RXFIR_IDHIT field. */ #define BR_CAN_RXFIR_IDHIT(x) (HW_CAN_RXFIR(x).B.IDHIT) /*@}*/ /******************************************************************************* * HW_CAN_CSn - Message Buffer 0 CS Register ******************************************************************************/ /*! * @brief HW_CAN_CSn - Message Buffer 0 CS Register (RW) * * Reset value: 0x00000000U */ typedef union _hw_can_csn { uint32_t U; struct _hw_can_csn_bitfields { uint32_t TIME_STAMP : 16; /*!< [15:0] Free-Running Counter Time * stamp. This 16-bit field is a copy of the Free-Running Timer, captured for Tx * and Rx frames at the time when the beginning of the Identifier field * appears on the CAN bus. */ uint32_t DLC : 4; /*!< [19:16] Length of the data to be * stored/transmitted. */ uint32_t RTR : 1; /*!< [20] Remote Transmission Request. One/zero for * remote/data frame. */ uint32_t IDE : 1; /*!< [21] ID Extended. One/zero for * extended/standard format frame. */ uint32_t SRR : 1; /*!< [22] Substitute Remote Request. Contains a * fixed recessive bit. */ uint32_t RESERVED0 : 1; /*!< [23] Reserved */ uint32_t CODE : 4; /*!< [27:24] Reserved */ uint32_t RESERVED1 : 4; /*!< [31:28] Reserved */ } B; } hw_can_csn_t; /*! * @name Constants and macros for entire CAN_CSn register */ /*@{*/ #define HW_CAN_CSn_COUNT (16U) #define HW_CAN_CSn_ADDR(x, n) ((x) + 0x80U + (0x10U * (n))) #define HW_CAN_CSn(x, n) (*(__IO hw_can_csn_t *) HW_CAN_CSn_ADDR(x, n)) #define HW_CAN_CSn_RD(x, n) (HW_CAN_CSn(x, n).U) #define HW_CAN_CSn_WR(x, n, v) (HW_CAN_CSn(x, n).U = (v)) #define HW_CAN_CSn_SET(x, n, v) (HW_CAN_CSn_WR(x, n, HW_CAN_CSn_RD(x, n) | (v))) #define HW_CAN_CSn_CLR(x, n, v) (HW_CAN_CSn_WR(x, n, HW_CAN_CSn_RD(x, n) & ~(v))) #define HW_CAN_CSn_TOG(x, n, v) (HW_CAN_CSn_WR(x, n, HW_CAN_CSn_RD(x, n) ^ (v))) /*@}*/ /* * Constants & macros for individual CAN_CSn bitfields */ /*! * @name Register CAN_CSn, field TIME_STAMP[15:0] (RW) */ /*@{*/ #define BP_CAN_CSn_TIME_STAMP (0U) /*!< Bit position for CAN_CSn_TIME_STAMP. */ #define BM_CAN_CSn_TIME_STAMP (0x0000FFFFU) /*!< Bit mask for CAN_CSn_TIME_STAMP. */ #define BS_CAN_CSn_TIME_STAMP (16U) /*!< Bit field size in bits for CAN_CSn_TIME_STAMP. */ /*! @brief Read current value of the CAN_CSn_TIME_STAMP field. */ #define BR_CAN_CSn_TIME_STAMP(x, n) (HW_CAN_CSn(x, n).B.TIME_STAMP) /*! @brief Format value for bitfield CAN_CSn_TIME_STAMP. */ #define BF_CAN_CSn_TIME_STAMP(v) ((uint32_t)((uint32_t)(v) << BP_CAN_CSn_TIME_STAMP) & BM_CAN_CSn_TIME_STAMP) /*! @brief Set the TIME_STAMP field to a new value. */ #define BW_CAN_CSn_TIME_STAMP(x, n, v) (HW_CAN_CSn_WR(x, n, (HW_CAN_CSn_RD(x, n) & ~BM_CAN_CSn_TIME_STAMP) | BF_CAN_CSn_TIME_STAMP(v))) /*@}*/ /*! * @name Register CAN_CSn, field DLC[19:16] (RW) */ /*@{*/ #define BP_CAN_CSn_DLC (16U) /*!< Bit position for CAN_CSn_DLC. */ #define BM_CAN_CSn_DLC (0x000F0000U) /*!< Bit mask for CAN_CSn_DLC. */ #define BS_CAN_CSn_DLC (4U) /*!< Bit field size in bits for CAN_CSn_DLC. */ /*! @brief Read current value of the CAN_CSn_DLC field. */ #define BR_CAN_CSn_DLC(x, n) (HW_CAN_CSn(x, n).B.DLC) /*! @brief Format value for bitfield CAN_CSn_DLC. */ #define BF_CAN_CSn_DLC(v) ((uint32_t)((uint32_t)(v) << BP_CAN_CSn_DLC) & BM_CAN_CSn_DLC) /*! @brief Set the DLC field to a new value. */ #define BW_CAN_CSn_DLC(x, n, v) (HW_CAN_CSn_WR(x, n, (HW_CAN_CSn_RD(x, n) & ~BM_CAN_CSn_DLC) | BF_CAN_CSn_DLC(v))) /*@}*/ /*! * @name Register CAN_CSn, field RTR[20] (RW) */ /*@{*/ #define BP_CAN_CSn_RTR (20U) /*!< Bit position for CAN_CSn_RTR. */ #define BM_CAN_CSn_RTR (0x00100000U) /*!< Bit mask for CAN_CSn_RTR. */ #define BS_CAN_CSn_RTR (1U) /*!< Bit field size in bits for CAN_CSn_RTR. */ /*! @brief Read current value of the CAN_CSn_RTR field. */ #define BR_CAN_CSn_RTR(x, n) (BITBAND_ACCESS32(HW_CAN_CSn_ADDR(x, n), BP_CAN_CSn_RTR)) /*! @brief Format value for bitfield CAN_CSn_RTR. */ #define BF_CAN_CSn_RTR(v) ((uint32_t)((uint32_t)(v) << BP_CAN_CSn_RTR) & BM_CAN_CSn_RTR) /*! @brief Set the RTR field to a new value. */ #define BW_CAN_CSn_RTR(x, n, v) (BITBAND_ACCESS32(HW_CAN_CSn_ADDR(x, n), BP_CAN_CSn_RTR) = (v)) /*@}*/ /*! * @name Register CAN_CSn, field IDE[21] (RW) */ /*@{*/ #define BP_CAN_CSn_IDE (21U) /*!< Bit position for CAN_CSn_IDE. */ #define BM_CAN_CSn_IDE (0x00200000U) /*!< Bit mask for CAN_CSn_IDE. */ #define BS_CAN_CSn_IDE (1U) /*!< Bit field size in bits for CAN_CSn_IDE. */ /*! @brief Read current value of the CAN_CSn_IDE field. */ #define BR_CAN_CSn_IDE(x, n) (BITBAND_ACCESS32(HW_CAN_CSn_ADDR(x, n), BP_CAN_CSn_IDE)) /*! @brief Format value for bitfield CAN_CSn_IDE. */ #define BF_CAN_CSn_IDE(v) ((uint32_t)((uint32_t)(v) << BP_CAN_CSn_IDE) & BM_CAN_CSn_IDE) /*! @brief Set the IDE field to a new value. */ #define BW_CAN_CSn_IDE(x, n, v) (BITBAND_ACCESS32(HW_CAN_CSn_ADDR(x, n), BP_CAN_CSn_IDE) = (v)) /*@}*/ /*! * @name Register CAN_CSn, field SRR[22] (RW) */ /*@{*/ #define BP_CAN_CSn_SRR (22U) /*!< Bit position for CAN_CSn_SRR. */ #define BM_CAN_CSn_SRR (0x00400000U) /*!< Bit mask for CAN_CSn_SRR. */ #define BS_CAN_CSn_SRR (1U) /*!< Bit field size in bits for CAN_CSn_SRR. */ /*! @brief Read current value of the CAN_CSn_SRR field. */ #define BR_CAN_CSn_SRR(x, n) (BITBAND_ACCESS32(HW_CAN_CSn_ADDR(x, n), BP_CAN_CSn_SRR)) /*! @brief Format value for bitfield CAN_CSn_SRR. */ #define BF_CAN_CSn_SRR(v) ((uint32_t)((uint32_t)(v) << BP_CAN_CSn_SRR) & BM_CAN_CSn_SRR) /*! @brief Set the SRR field to a new value. */ #define BW_CAN_CSn_SRR(x, n, v) (BITBAND_ACCESS32(HW_CAN_CSn_ADDR(x, n), BP_CAN_CSn_SRR) = (v)) /*@}*/ /*! * @name Register CAN_CSn, field CODE[27:24] (RW) */ /*@{*/ #define BP_CAN_CSn_CODE (24U) /*!< Bit position for CAN_CSn_CODE. */ #define BM_CAN_CSn_CODE (0x0F000000U) /*!< Bit mask for CAN_CSn_CODE. */ #define BS_CAN_CSn_CODE (4U) /*!< Bit field size in bits for CAN_CSn_CODE. */ /*! @brief Read current value of the CAN_CSn_CODE field. */ #define BR_CAN_CSn_CODE(x, n) (HW_CAN_CSn(x, n).B.CODE) /*! @brief Format value for bitfield CAN_CSn_CODE. */ #define BF_CAN_CSn_CODE(v) ((uint32_t)((uint32_t)(v) << BP_CAN_CSn_CODE) & BM_CAN_CSn_CODE) /*! @brief Set the CODE field to a new value. */ #define BW_CAN_CSn_CODE(x, n, v) (HW_CAN_CSn_WR(x, n, (HW_CAN_CSn_RD(x, n) & ~BM_CAN_CSn_CODE) | BF_CAN_CSn_CODE(v))) /*@}*/ /******************************************************************************* * HW_CAN_IDn - Message Buffer 0 ID Register ******************************************************************************/ /*! * @brief HW_CAN_IDn - Message Buffer 0 ID Register (RW) * * Reset value: 0x00000000U */ typedef union _hw_can_idn { uint32_t U; struct _hw_can_idn_bitfields { uint32_t EXT : 18; /*!< [17:0] Contains extended (LOW word) * identifier of message buffer. */ uint32_t STD : 11; /*!< [28:18] Contains standard/extended (HIGH * word) identifier of message buffer. */ uint32_t PRIO : 3; /*!< [31:29] Local priority. This 3-bit fieldis * only used when LPRIO_EN bit is set in MCR and it only makes sense for Tx * buffers. These bits are not transmitted. They are appended to the regular * ID to define the transmission priority. */ } B; } hw_can_idn_t; /*! * @name Constants and macros for entire CAN_IDn register */ /*@{*/ #define HW_CAN_IDn_COUNT (16U) #define HW_CAN_IDn_ADDR(x, n) ((x) + 0x84U + (0x10U * (n))) #define HW_CAN_IDn(x, n) (*(__IO hw_can_idn_t *) HW_CAN_IDn_ADDR(x, n)) #define HW_CAN_IDn_RD(x, n) (HW_CAN_IDn(x, n).U) #define HW_CAN_IDn_WR(x, n, v) (HW_CAN_IDn(x, n).U = (v)) #define HW_CAN_IDn_SET(x, n, v) (HW_CAN_IDn_WR(x, n, HW_CAN_IDn_RD(x, n) | (v))) #define HW_CAN_IDn_CLR(x, n, v) (HW_CAN_IDn_WR(x, n, HW_CAN_IDn_RD(x, n) & ~(v))) #define HW_CAN_IDn_TOG(x, n, v) (HW_CAN_IDn_WR(x, n, HW_CAN_IDn_RD(x, n) ^ (v))) /*@}*/ /* * Constants & macros for individual CAN_IDn bitfields */ /*! * @name Register CAN_IDn, field EXT[17:0] (RW) */ /*@{*/ #define BP_CAN_IDn_EXT (0U) /*!< Bit position for CAN_IDn_EXT. */ #define BM_CAN_IDn_EXT (0x0003FFFFU) /*!< Bit mask for CAN_IDn_EXT. */ #define BS_CAN_IDn_EXT (18U) /*!< Bit field size in bits for CAN_IDn_EXT. */ /*! @brief Read current value of the CAN_IDn_EXT field. */ #define BR_CAN_IDn_EXT(x, n) (HW_CAN_IDn(x, n).B.EXT) /*! @brief Format value for bitfield CAN_IDn_EXT. */ #define BF_CAN_IDn_EXT(v) ((uint32_t)((uint32_t)(v) << BP_CAN_IDn_EXT) & BM_CAN_IDn_EXT) /*! @brief Set the EXT field to a new value. */ #define BW_CAN_IDn_EXT(x, n, v) (HW_CAN_IDn_WR(x, n, (HW_CAN_IDn_RD(x, n) & ~BM_CAN_IDn_EXT) | BF_CAN_IDn_EXT(v))) /*@}*/ /*! * @name Register CAN_IDn, field STD[28:18] (RW) */ /*@{*/ #define BP_CAN_IDn_STD (18U) /*!< Bit position for CAN_IDn_STD. */ #define BM_CAN_IDn_STD (0x1FFC0000U) /*!< Bit mask for CAN_IDn_STD. */ #define BS_CAN_IDn_STD (11U) /*!< Bit field size in bits for CAN_IDn_STD. */ /*! @brief Read current value of the CAN_IDn_STD field. */ #define BR_CAN_IDn_STD(x, n) (HW_CAN_IDn(x, n).B.STD) /*! @brief Format value for bitfield CAN_IDn_STD. */ #define BF_CAN_IDn_STD(v) ((uint32_t)((uint32_t)(v) << BP_CAN_IDn_STD) & BM_CAN_IDn_STD) /*! @brief Set the STD field to a new value. */ #define BW_CAN_IDn_STD(x, n, v) (HW_CAN_IDn_WR(x, n, (HW_CAN_IDn_RD(x, n) & ~BM_CAN_IDn_STD) | BF_CAN_IDn_STD(v))) /*@}*/ /*! * @name Register CAN_IDn, field PRIO[31:29] (RW) */ /*@{*/ #define BP_CAN_IDn_PRIO (29U) /*!< Bit position for CAN_IDn_PRIO. */ #define BM_CAN_IDn_PRIO (0xE0000000U) /*!< Bit mask for CAN_IDn_PRIO. */ #define BS_CAN_IDn_PRIO (3U) /*!< Bit field size in bits for CAN_IDn_PRIO. */ /*! @brief Read current value of the CAN_IDn_PRIO field. */ #define BR_CAN_IDn_PRIO(x, n) (HW_CAN_IDn(x, n).B.PRIO) /*! @brief Format value for bitfield CAN_IDn_PRIO. */ #define BF_CAN_IDn_PRIO(v) ((uint32_t)((uint32_t)(v) << BP_CAN_IDn_PRIO) & BM_CAN_IDn_PRIO) /*! @brief Set the PRIO field to a new value. */ #define BW_CAN_IDn_PRIO(x, n, v) (HW_CAN_IDn_WR(x, n, (HW_CAN_IDn_RD(x, n) & ~BM_CAN_IDn_PRIO) | BF_CAN_IDn_PRIO(v))) /*@}*/ /******************************************************************************* * HW_CAN_WORD0n - Message Buffer 0 WORD0 Register ******************************************************************************/ /*! * @brief HW_CAN_WORD0n - Message Buffer 0 WORD0 Register (RW) * * Reset value: 0x00000000U */ typedef union _hw_can_word0n { uint32_t U; struct _hw_can_word0n_bitfields { uint32_t DATA_BYTE_3 : 8; /*!< [7:0] Data byte 3 of Rx/Tx frame. */ uint32_t DATA_BYTE_2 : 8; /*!< [15:8] Data byte 2 of Rx/Tx frame. */ uint32_t DATA_BYTE_1 : 8; /*!< [23:16] Data byte 1 of Rx/Tx frame. */ uint32_t DATA_BYTE_0 : 8; /*!< [31:24] Data byte 0 of Rx/Tx frame. */ } B; } hw_can_word0n_t; /*! * @name Constants and macros for entire CAN_WORD0n register */ /*@{*/ #define HW_CAN_WORD0n_COUNT (16U) #define HW_CAN_WORD0n_ADDR(x, n) ((x) + 0x88U + (0x10U * (n))) #define HW_CAN_WORD0n(x, n) (*(__IO hw_can_word0n_t *) HW_CAN_WORD0n_ADDR(x, n)) #define HW_CAN_WORD0n_RD(x, n) (HW_CAN_WORD0n(x, n).U) #define HW_CAN_WORD0n_WR(x, n, v) (HW_CAN_WORD0n(x, n).U = (v)) #define HW_CAN_WORD0n_SET(x, n, v) (HW_CAN_WORD0n_WR(x, n, HW_CAN_WORD0n_RD(x, n) | (v))) #define HW_CAN_WORD0n_CLR(x, n, v) (HW_CAN_WORD0n_WR(x, n, HW_CAN_WORD0n_RD(x, n) & ~(v))) #define HW_CAN_WORD0n_TOG(x, n, v) (HW_CAN_WORD0n_WR(x, n, HW_CAN_WORD0n_RD(x, n) ^ (v))) /*@}*/ /* * Constants & macros for individual CAN_WORD0n bitfields */ /*! * @name Register CAN_WORD0n, field DATA_BYTE_3[7:0] (RW) */ /*@{*/ #define BP_CAN_WORD0n_DATA_BYTE_3 (0U) /*!< Bit position for CAN_WORD0n_DATA_BYTE_3. */ #define BM_CAN_WORD0n_DATA_BYTE_3 (0x000000FFU) /*!< Bit mask for CAN_WORD0n_DATA_BYTE_3. */ #define BS_CAN_WORD0n_DATA_BYTE_3 (8U) /*!< Bit field size in bits for CAN_WORD0n_DATA_BYTE_3. */ /*! @brief Read current value of the CAN_WORD0n_DATA_BYTE_3 field. */ #define BR_CAN_WORD0n_DATA_BYTE_3(x, n) (HW_CAN_WORD0n(x, n).B.DATA_BYTE_3) /*! @brief Format value for bitfield CAN_WORD0n_DATA_BYTE_3. */ #define BF_CAN_WORD0n_DATA_BYTE_3(v) ((uint32_t)((uint32_t)(v) << BP_CAN_WORD0n_DATA_BYTE_3) & BM_CAN_WORD0n_DATA_BYTE_3) /*! @brief Set the DATA_BYTE_3 field to a new value. */ #define BW_CAN_WORD0n_DATA_BYTE_3(x, n, v) (HW_CAN_WORD0n_WR(x, n, (HW_CAN_WORD0n_RD(x, n) & ~BM_CAN_WORD0n_DATA_BYTE_3) | BF_CAN_WORD0n_DATA_BYTE_3(v))) /*@}*/ /*! * @name Register CAN_WORD0n, field DATA_BYTE_2[15:8] (RW) */ /*@{*/ #define BP_CAN_WORD0n_DATA_BYTE_2 (8U) /*!< Bit position for CAN_WORD0n_DATA_BYTE_2. */ #define BM_CAN_WORD0n_DATA_BYTE_2 (0x0000FF00U) /*!< Bit mask for CAN_WORD0n_DATA_BYTE_2. */ #define BS_CAN_WORD0n_DATA_BYTE_2 (8U) /*!< Bit field size in bits for CAN_WORD0n_DATA_BYTE_2. */ /*! @brief Read current value of the CAN_WORD0n_DATA_BYTE_2 field. */ #define BR_CAN_WORD0n_DATA_BYTE_2(x, n) (HW_CAN_WORD0n(x, n).B.DATA_BYTE_2) /*! @brief Format value for bitfield CAN_WORD0n_DATA_BYTE_2. */ #define BF_CAN_WORD0n_DATA_BYTE_2(v) ((uint32_t)((uint32_t)(v) << BP_CAN_WORD0n_DATA_BYTE_2) & BM_CAN_WORD0n_DATA_BYTE_2) /*! @brief Set the DATA_BYTE_2 field to a new value. */ #define BW_CAN_WORD0n_DATA_BYTE_2(x, n, v) (HW_CAN_WORD0n_WR(x, n, (HW_CAN_WORD0n_RD(x, n) & ~BM_CAN_WORD0n_DATA_BYTE_2) | BF_CAN_WORD0n_DATA_BYTE_2(v))) /*@}*/ /*! * @name Register CAN_WORD0n, field DATA_BYTE_1[23:16] (RW) */ /*@{*/ #define BP_CAN_WORD0n_DATA_BYTE_1 (16U) /*!< Bit position for CAN_WORD0n_DATA_BYTE_1. */ #define BM_CAN_WORD0n_DATA_BYTE_1 (0x00FF0000U) /*!< Bit mask for CAN_WORD0n_DATA_BYTE_1. */ #define BS_CAN_WORD0n_DATA_BYTE_1 (8U) /*!< Bit field size in bits for CAN_WORD0n_DATA_BYTE_1. */ /*! @brief Read current value of the CAN_WORD0n_DATA_BYTE_1 field. */ #define BR_CAN_WORD0n_DATA_BYTE_1(x, n) (HW_CAN_WORD0n(x, n).B.DATA_BYTE_1) /*! @brief Format value for bitfield CAN_WORD0n_DATA_BYTE_1. */ #define BF_CAN_WORD0n_DATA_BYTE_1(v) ((uint32_t)((uint32_t)(v) << BP_CAN_WORD0n_DATA_BYTE_1) & BM_CAN_WORD0n_DATA_BYTE_1) /*! @brief Set the DATA_BYTE_1 field to a new value. */ #define BW_CAN_WORD0n_DATA_BYTE_1(x, n, v) (HW_CAN_WORD0n_WR(x, n, (HW_CAN_WORD0n_RD(x, n) & ~BM_CAN_WORD0n_DATA_BYTE_1) | BF_CAN_WORD0n_DATA_BYTE_1(v))) /*@}*/ /*! * @name Register CAN_WORD0n, field DATA_BYTE_0[31:24] (RW) */ /*@{*/ #define BP_CAN_WORD0n_DATA_BYTE_0 (24U) /*!< Bit position for CAN_WORD0n_DATA_BYTE_0. */ #define BM_CAN_WORD0n_DATA_BYTE_0 (0xFF000000U) /*!< Bit mask for CAN_WORD0n_DATA_BYTE_0. */ #define BS_CAN_WORD0n_DATA_BYTE_0 (8U) /*!< Bit field size in bits for CAN_WORD0n_DATA_BYTE_0. */ /*! @brief Read current value of the CAN_WORD0n_DATA_BYTE_0 field. */ #define BR_CAN_WORD0n_DATA_BYTE_0(x, n) (HW_CAN_WORD0n(x, n).B.DATA_BYTE_0) /*! @brief Format value for bitfield CAN_WORD0n_DATA_BYTE_0. */ #define BF_CAN_WORD0n_DATA_BYTE_0(v) ((uint32_t)((uint32_t)(v) << BP_CAN_WORD0n_DATA_BYTE_0) & BM_CAN_WORD0n_DATA_BYTE_0) /*! @brief Set the DATA_BYTE_0 field to a new value. */ #define BW_CAN_WORD0n_DATA_BYTE_0(x, n, v) (HW_CAN_WORD0n_WR(x, n, (HW_CAN_WORD0n_RD(x, n) & ~BM_CAN_WORD0n_DATA_BYTE_0) | BF_CAN_WORD0n_DATA_BYTE_0(v))) /*@}*/ /******************************************************************************* * HW_CAN_WORD1n - Message Buffer 0 WORD1 Register ******************************************************************************/ /*! * @brief HW_CAN_WORD1n - Message Buffer 0 WORD1 Register (RW) * * Reset value: 0x00000000U */ typedef union _hw_can_word1n { uint32_t U; struct _hw_can_word1n_bitfields { uint32_t DATA_BYTE_7 : 8; /*!< [7:0] Data byte 7 of Rx/Tx frame. */ uint32_t DATA_BYTE_6 : 8; /*!< [15:8] Data byte 6 of Rx/Tx frame. */ uint32_t DATA_BYTE_5 : 8; /*!< [23:16] Data byte 5 of Rx/Tx frame. */ uint32_t DATA_BYTE_4 : 8; /*!< [31:24] Data byte 4 of Rx/Tx frame. */ } B; } hw_can_word1n_t; /*! * @name Constants and macros for entire CAN_WORD1n register */ /*@{*/ #define HW_CAN_WORD1n_COUNT (16U) #define HW_CAN_WORD1n_ADDR(x, n) ((x) + 0x8CU + (0x10U * (n))) #define HW_CAN_WORD1n(x, n) (*(__IO hw_can_word1n_t *) HW_CAN_WORD1n_ADDR(x, n)) #define HW_CAN_WORD1n_RD(x, n) (HW_CAN_WORD1n(x, n).U) #define HW_CAN_WORD1n_WR(x, n, v) (HW_CAN_WORD1n(x, n).U = (v)) #define HW_CAN_WORD1n_SET(x, n, v) (HW_CAN_WORD1n_WR(x, n, HW_CAN_WORD1n_RD(x, n) | (v))) #define HW_CAN_WORD1n_CLR(x, n, v) (HW_CAN_WORD1n_WR(x, n, HW_CAN_WORD1n_RD(x, n) & ~(v))) #define HW_CAN_WORD1n_TOG(x, n, v) (HW_CAN_WORD1n_WR(x, n, HW_CAN_WORD1n_RD(x, n) ^ (v))) /*@}*/ /* * Constants & macros for individual CAN_WORD1n bitfields */ /*! * @name Register CAN_WORD1n, field DATA_BYTE_7[7:0] (RW) */ /*@{*/ #define BP_CAN_WORD1n_DATA_BYTE_7 (0U) /*!< Bit position for CAN_WORD1n_DATA_BYTE_7. */ #define BM_CAN_WORD1n_DATA_BYTE_7 (0x000000FFU) /*!< Bit mask for CAN_WORD1n_DATA_BYTE_7. */ #define BS_CAN_WORD1n_DATA_BYTE_7 (8U) /*!< Bit field size in bits for CAN_WORD1n_DATA_BYTE_7. */ /*! @brief Read current value of the CAN_WORD1n_DATA_BYTE_7 field. */ #define BR_CAN_WORD1n_DATA_BYTE_7(x, n) (HW_CAN_WORD1n(x, n).B.DATA_BYTE_7) /*! @brief Format value for bitfield CAN_WORD1n_DATA_BYTE_7. */ #define BF_CAN_WORD1n_DATA_BYTE_7(v) ((uint32_t)((uint32_t)(v) << BP_CAN_WORD1n_DATA_BYTE_7) & BM_CAN_WORD1n_DATA_BYTE_7) /*! @brief Set the DATA_BYTE_7 field to a new value. */ #define BW_CAN_WORD1n_DATA_BYTE_7(x, n, v) (HW_CAN_WORD1n_WR(x, n, (HW_CAN_WORD1n_RD(x, n) & ~BM_CAN_WORD1n_DATA_BYTE_7) | BF_CAN_WORD1n_DATA_BYTE_7(v))) /*@}*/ /*! * @name Register CAN_WORD1n, field DATA_BYTE_6[15:8] (RW) */ /*@{*/ #define BP_CAN_WORD1n_DATA_BYTE_6 (8U) /*!< Bit position for CAN_WORD1n_DATA_BYTE_6. */ #define BM_CAN_WORD1n_DATA_BYTE_6 (0x0000FF00U) /*!< Bit mask for CAN_WORD1n_DATA_BYTE_6. */ #define BS_CAN_WORD1n_DATA_BYTE_6 (8U) /*!< Bit field size in bits for CAN_WORD1n_DATA_BYTE_6. */ /*! @brief Read current value of the CAN_WORD1n_DATA_BYTE_6 field. */ #define BR_CAN_WORD1n_DATA_BYTE_6(x, n) (HW_CAN_WORD1n(x, n).B.DATA_BYTE_6) /*! @brief Format value for bitfield CAN_WORD1n_DATA_BYTE_6. */ #define BF_CAN_WORD1n_DATA_BYTE_6(v) ((uint32_t)((uint32_t)(v) << BP_CAN_WORD1n_DATA_BYTE_6) & BM_CAN_WORD1n_DATA_BYTE_6) /*! @brief Set the DATA_BYTE_6 field to a new value. */ #define BW_CAN_WORD1n_DATA_BYTE_6(x, n, v) (HW_CAN_WORD1n_WR(x, n, (HW_CAN_WORD1n_RD(x, n) & ~BM_CAN_WORD1n_DATA_BYTE_6) | BF_CAN_WORD1n_DATA_BYTE_6(v))) /*@}*/ /*! * @name Register CAN_WORD1n, field DATA_BYTE_5[23:16] (RW) */ /*@{*/ #define BP_CAN_WORD1n_DATA_BYTE_5 (16U) /*!< Bit position for CAN_WORD1n_DATA_BYTE_5. */ #define BM_CAN_WORD1n_DATA_BYTE_5 (0x00FF0000U) /*!< Bit mask for CAN_WORD1n_DATA_BYTE_5. */ #define BS_CAN_WORD1n_DATA_BYTE_5 (8U) /*!< Bit field size in bits for CAN_WORD1n_DATA_BYTE_5. */ /*! @brief Read current value of the CAN_WORD1n_DATA_BYTE_5 field. */ #define BR_CAN_WORD1n_DATA_BYTE_5(x, n) (HW_CAN_WORD1n(x, n).B.DATA_BYTE_5) /*! @brief Format value for bitfield CAN_WORD1n_DATA_BYTE_5. */ #define BF_CAN_WORD1n_DATA_BYTE_5(v) ((uint32_t)((uint32_t)(v) << BP_CAN_WORD1n_DATA_BYTE_5) & BM_CAN_WORD1n_DATA_BYTE_5) /*! @brief Set the DATA_BYTE_5 field to a new value. */ #define BW_CAN_WORD1n_DATA_BYTE_5(x, n, v) (HW_CAN_WORD1n_WR(x, n, (HW_CAN_WORD1n_RD(x, n) & ~BM_CAN_WORD1n_DATA_BYTE_5) | BF_CAN_WORD1n_DATA_BYTE_5(v))) /*@}*/ /*! * @name Register CAN_WORD1n, field DATA_BYTE_4[31:24] (RW) */ /*@{*/ #define BP_CAN_WORD1n_DATA_BYTE_4 (24U) /*!< Bit position for CAN_WORD1n_DATA_BYTE_4. */ #define BM_CAN_WORD1n_DATA_BYTE_4 (0xFF000000U) /*!< Bit mask for CAN_WORD1n_DATA_BYTE_4. */ #define BS_CAN_WORD1n_DATA_BYTE_4 (8U) /*!< Bit field size in bits for CAN_WORD1n_DATA_BYTE_4. */ /*! @brief Read current value of the CAN_WORD1n_DATA_BYTE_4 field. */ #define BR_CAN_WORD1n_DATA_BYTE_4(x, n) (HW_CAN_WORD1n(x, n).B.DATA_BYTE_4) /*! @brief Format value for bitfield CAN_WORD1n_DATA_BYTE_4. */ #define BF_CAN_WORD1n_DATA_BYTE_4(v) ((uint32_t)((uint32_t)(v) << BP_CAN_WORD1n_DATA_BYTE_4) & BM_CAN_WORD1n_DATA_BYTE_4) /*! @brief Set the DATA_BYTE_4 field to a new value. */ #define BW_CAN_WORD1n_DATA_BYTE_4(x, n, v) (HW_CAN_WORD1n_WR(x, n, (HW_CAN_WORD1n_RD(x, n) & ~BM_CAN_WORD1n_DATA_BYTE_4) | BF_CAN_WORD1n_DATA_BYTE_4(v))) /*@}*/ /******************************************************************************* * HW_CAN_RXIMRn - Rx Individual Mask Registers ******************************************************************************/ /*! * @brief HW_CAN_RXIMRn - Rx Individual Mask Registers (RW) * * Reset value: 0x00000000U * * These registers are located in RAM. RXIMR are used as acceptance masks for ID * filtering in Rx MBs and the Rx FIFO. If the Rx FIFO is not enabled, one mask * register is provided for each available Mailbox, providing ID masking * capability on a per Mailbox basis. When the Rx FIFO is enabled (MCR[RFEN] bit is * asserted), up to 32 Rx Individual Mask Registers can apply to the Rx FIFO ID Filter * Table elements on a one-to-one correspondence depending on the setting of * CTRL2[RFFN]. RXIMR can only be written by the CPU while the module is in Freeze * mode; otherwise, they are blocked by hardware. The Individual Rx Mask Registers * are not affected by reset and must be explicitly initialized prior to any * reception. */ typedef union _hw_can_rximrn { uint32_t U; struct _hw_can_rximrn_bitfields { uint32_t MI : 32; /*!< [31:0] Individual Mask Bits */ } B; } hw_can_rximrn_t; /*! * @name Constants and macros for entire CAN_RXIMRn register */ /*@{*/ #define HW_CAN_RXIMRn_COUNT (16U) #define HW_CAN_RXIMRn_ADDR(x, n) ((x) + 0x880U + (0x4U * (n))) #define HW_CAN_RXIMRn(x, n) (*(__IO hw_can_rximrn_t *) HW_CAN_RXIMRn_ADDR(x, n)) #define HW_CAN_RXIMRn_RD(x, n) (HW_CAN_RXIMRn(x, n).U) #define HW_CAN_RXIMRn_WR(x, n, v) (HW_CAN_RXIMRn(x, n).U = (v)) #define HW_CAN_RXIMRn_SET(x, n, v) (HW_CAN_RXIMRn_WR(x, n, HW_CAN_RXIMRn_RD(x, n) | (v))) #define HW_CAN_RXIMRn_CLR(x, n, v) (HW_CAN_RXIMRn_WR(x, n, HW_CAN_RXIMRn_RD(x, n) & ~(v))) #define HW_CAN_RXIMRn_TOG(x, n, v) (HW_CAN_RXIMRn_WR(x, n, HW_CAN_RXIMRn_RD(x, n) ^ (v))) /*@}*/ /* * Constants & macros for individual CAN_RXIMRn bitfields */ /*! * @name Register CAN_RXIMRn, field MI[31:0] (RW) * * Each Individual Mask Bit masks the corresponding bit in both the Mailbox * filter and Rx FIFO ID Filter Table element in distinct ways. For Mailbox filters, * see the RXMGMASK register description. For Rx FIFO ID Filter Table elements, * see the RXFGMASK register description. * * Values: * - 0 - The corresponding bit in the filter is "don't care." * - 1 - The corresponding bit in the filter is checked. */ /*@{*/ #define BP_CAN_RXIMRn_MI (0U) /*!< Bit position for CAN_RXIMRn_MI. */ #define BM_CAN_RXIMRn_MI (0xFFFFFFFFU) /*!< Bit mask for CAN_RXIMRn_MI. */ #define BS_CAN_RXIMRn_MI (32U) /*!< Bit field size in bits for CAN_RXIMRn_MI. */ /*! @brief Read current value of the CAN_RXIMRn_MI field. */ #define BR_CAN_RXIMRn_MI(x, n) (HW_CAN_RXIMRn(x, n).U) /*! @brief Format value for bitfield CAN_RXIMRn_MI. */ #define BF_CAN_RXIMRn_MI(v) ((uint32_t)((uint32_t)(v) << BP_CAN_RXIMRn_MI) & BM_CAN_RXIMRn_MI) /*! @brief Set the MI field to a new value. */ #define BW_CAN_RXIMRn_MI(x, n, v) (HW_CAN_RXIMRn_WR(x, n, v)) /*@}*/ /******************************************************************************* * hw_can_t - module struct ******************************************************************************/ /*! * @brief All CAN module registers. */ #pragma pack(1) typedef struct _hw_can { __IO hw_can_mcr_t MCR; /*!< [0x0] Module Configuration Register */ __IO hw_can_ctrl1_t CTRL1; /*!< [0x4] Control 1 register */ __IO hw_can_timer_t TIMER; /*!< [0x8] Free Running Timer */ uint8_t _reserved0[4]; __IO hw_can_rxmgmask_t RXMGMASK; /*!< [0x10] Rx Mailboxes Global Mask Register */ __IO hw_can_rx14mask_t RX14MASK; /*!< [0x14] Rx 14 Mask register */ __IO hw_can_rx15mask_t RX15MASK; /*!< [0x18] Rx 15 Mask register */ __IO hw_can_ecr_t ECR; /*!< [0x1C] Error Counter */ __IO hw_can_esr1_t ESR1; /*!< [0x20] Error and Status 1 register */ uint8_t _reserved1[4]; __IO hw_can_imask1_t IMASK1; /*!< [0x28] Interrupt Masks 1 register */ uint8_t _reserved2[4]; __IO hw_can_iflag1_t IFLAG1; /*!< [0x30] Interrupt Flags 1 register */ __IO hw_can_ctrl2_t CTRL2; /*!< [0x34] Control 2 register */ __I hw_can_esr2_t ESR2; /*!< [0x38] Error and Status 2 register */ uint8_t _reserved3[8]; __I hw_can_crcr_t CRCR; /*!< [0x44] CRC Register */ __IO hw_can_rxfgmask_t RXFGMASK; /*!< [0x48] Rx FIFO Global Mask register */ __I hw_can_rxfir_t RXFIR; /*!< [0x4C] Rx FIFO Information Register */ uint8_t _reserved4[48]; struct { __IO hw_can_csn_t CSn; /*!< [0x80] Message Buffer 0 CS Register */ __IO hw_can_idn_t IDn; /*!< [0x84] Message Buffer 0 ID Register */ __IO hw_can_word0n_t WORD0n; /*!< [0x88] Message Buffer 0 WORD0 Register */ __IO hw_can_word1n_t WORD1n; /*!< [0x8C] Message Buffer 0 WORD1 Register */ } MB[16]; uint8_t _reserved5[1792]; __IO hw_can_rximrn_t RXIMRn[16]; /*!< [0x880] Rx Individual Mask Registers */ } hw_can_t; #pragma pack() /*! @brief Macro to access all CAN registers. */ /*! @param x CAN module instance base address. */ /*! @return Reference (not a pointer) to the registers struct. To get a pointer to the struct, * use the '&' operator, like &HW_CAN(CAN0_BASE). */ #define HW_CAN(x) (*(hw_can_t *)(x)) #endif /* __HW_CAN_REGISTERS_H__ */ /* EOF */ ================================================ FILE: Zelig/mbed/TARGET_K64F/TARGET_Freescale/TARGET_KPSDK_MCUS/TARGET_MCU_K64F/device/device/MK64F12/MK64F12_cau.h ================================================ /* ** ################################################################### ** Compilers: Keil ARM C/C++ Compiler ** Freescale C/C++ for Embedded ARM ** GNU C Compiler ** IAR ANSI C/C++ Compiler for ARM ** ** Reference manual: K64P144M120SF5RM, Rev.2, January 2014 ** Version: rev. 2.5, 2014-02-10 ** Build: b140604 ** ** Abstract: ** Extension to the CMSIS register access layer header. ** ** Copyright (c) 2014 Freescale Semiconductor, Inc. ** All rights reserved. ** ** Redistribution and use in source and binary forms, with or without modification, ** are permitted provided that the following conditions are met: ** ** o Redistributions of source code must retain the above copyright notice, this list ** of conditions and the following disclaimer. ** ** o Redistributions in binary form must reproduce the above copyright notice, this ** list of conditions and the following disclaimer in the documentation and/or ** other materials provided with the distribution. ** ** o Neither the name of Freescale Semiconductor, Inc. nor the names of its ** contributors may be used to endorse or promote products derived from this ** software without specific prior written permission. ** ** THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ** ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED ** WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE ** DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT 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. ** ** http: www.freescale.com ** mail: support@freescale.com ** ** Revisions: ** - rev. 1.0 (2013-08-12) ** Initial version. ** - rev. 2.0 (2013-10-29) ** Register accessor macros added to the memory map. ** Symbols for Processor Expert memory map compatibility added to the memory map. ** Startup file for gcc has been updated according to CMSIS 3.2. ** System initialization updated. ** MCG - registers updated. ** PORTA, PORTB, PORTC, PORTE - registers for digital filter removed. ** - rev. 2.1 (2013-10-30) ** Definition of BITBAND macros updated to support peripherals with 32-bit acces disabled. ** - rev. 2.2 (2013-12-09) ** DMA - EARS register removed. ** AIPS0, AIPS1 - MPRA register updated. ** - rev. 2.3 (2014-01-24) ** Update according to reference manual rev. 2 ** ENET, MCG, MCM, SIM, USB - registers updated ** - rev. 2.4 (2014-02-10) ** The declaration of clock configurations has been moved to separate header file system_MK64F12.h ** Update of SystemInit() and SystemCoreClockUpdate() functions. ** - rev. 2.5 (2014-02-10) ** The declaration of clock configurations has been moved to separate header file system_MK64F12.h ** Update of SystemInit() and SystemCoreClockUpdate() functions. ** Module access macro module_BASES replaced by module_BASE_PTRS. ** ** ################################################################### */ /* * WARNING! DO NOT EDIT THIS FILE DIRECTLY! * * This file was generated automatically and any changes may be lost. */ #ifndef __HW_CAU_REGISTERS_H__ #define __HW_CAU_REGISTERS_H__ #include "MK64F12.h" #include "fsl_bitaccess.h" /* * MK64F12 CAU * * Memory Mapped Cryptographic Acceleration Unit (MMCAU) * * Registers defined in this header file: * - HW_CAU_DIRECT0 - Direct access register 0 * - HW_CAU_DIRECT1 - Direct access register 1 * - HW_CAU_DIRECT2 - Direct access register 2 * - HW_CAU_DIRECT3 - Direct access register 3 * - HW_CAU_DIRECT4 - Direct access register 4 * - HW_CAU_DIRECT5 - Direct access register 5 * - HW_CAU_DIRECT6 - Direct access register 6 * - HW_CAU_DIRECT7 - Direct access register 7 * - HW_CAU_DIRECT8 - Direct access register 8 * - HW_CAU_DIRECT9 - Direct access register 9 * - HW_CAU_DIRECT10 - Direct access register 10 * - HW_CAU_DIRECT11 - Direct access register 11 * - HW_CAU_DIRECT12 - Direct access register 12 * - HW_CAU_DIRECT13 - Direct access register 13 * - HW_CAU_DIRECT14 - Direct access register 14 * - HW_CAU_DIRECT15 - Direct access register 15 * - HW_CAU_LDR_CASR - Status register - Load Register command * - HW_CAU_LDR_CAA - Accumulator register - Load Register command * - HW_CAU_LDR_CA0 - General Purpose Register 0 - Load Register command * - HW_CAU_LDR_CA1 - General Purpose Register 1 - Load Register command * - HW_CAU_LDR_CA2 - General Purpose Register 2 - Load Register command * - HW_CAU_LDR_CA3 - General Purpose Register 3 - Load Register command * - HW_CAU_LDR_CA4 - General Purpose Register 4 - Load Register command * - HW_CAU_LDR_CA5 - General Purpose Register 5 - Load Register command * - HW_CAU_LDR_CA6 - General Purpose Register 6 - Load Register command * - HW_CAU_LDR_CA7 - General Purpose Register 7 - Load Register command * - HW_CAU_LDR_CA8 - General Purpose Register 8 - Load Register command * - HW_CAU_STR_CASR - Status register - Store Register command * - HW_CAU_STR_CAA - Accumulator register - Store Register command * - HW_CAU_STR_CA0 - General Purpose Register 0 - Store Register command * - HW_CAU_STR_CA1 - General Purpose Register 1 - Store Register command * - HW_CAU_STR_CA2 - General Purpose Register 2 - Store Register command * - HW_CAU_STR_CA3 - General Purpose Register 3 - Store Register command * - HW_CAU_STR_CA4 - General Purpose Register 4 - Store Register command * - HW_CAU_STR_CA5 - General Purpose Register 5 - Store Register command * - HW_CAU_STR_CA6 - General Purpose Register 6 - Store Register command * - HW_CAU_STR_CA7 - General Purpose Register 7 - Store Register command * - HW_CAU_STR_CA8 - General Purpose Register 8 - Store Register command * - HW_CAU_ADR_CASR - Status register - Add Register command * - HW_CAU_ADR_CAA - Accumulator register - Add to register command * - HW_CAU_ADR_CA0 - General Purpose Register 0 - Add to register command * - HW_CAU_ADR_CA1 - General Purpose Register 1 - Add to register command * - HW_CAU_ADR_CA2 - General Purpose Register 2 - Add to register command * - HW_CAU_ADR_CA3 - General Purpose Register 3 - Add to register command * - HW_CAU_ADR_CA4 - General Purpose Register 4 - Add to register command * - HW_CAU_ADR_CA5 - General Purpose Register 5 - Add to register command * - HW_CAU_ADR_CA6 - General Purpose Register 6 - Add to register command * - HW_CAU_ADR_CA7 - General Purpose Register 7 - Add to register command * - HW_CAU_ADR_CA8 - General Purpose Register 8 - Add to register command * - HW_CAU_RADR_CASR - Status register - Reverse and Add to Register command * - HW_CAU_RADR_CAA - Accumulator register - Reverse and Add to Register command * - HW_CAU_RADR_CA0 - General Purpose Register 0 - Reverse and Add to Register command * - HW_CAU_RADR_CA1 - General Purpose Register 1 - Reverse and Add to Register command * - HW_CAU_RADR_CA2 - General Purpose Register 2 - Reverse and Add to Register command * - HW_CAU_RADR_CA3 - General Purpose Register 3 - Reverse and Add to Register command * - HW_CAU_RADR_CA4 - General Purpose Register 4 - Reverse and Add to Register command * - HW_CAU_RADR_CA5 - General Purpose Register 5 - Reverse and Add to Register command * - HW_CAU_RADR_CA6 - General Purpose Register 6 - Reverse and Add to Register command * - HW_CAU_RADR_CA7 - General Purpose Register 7 - Reverse and Add to Register command * - HW_CAU_RADR_CA8 - General Purpose Register 8 - Reverse and Add to Register command * - HW_CAU_XOR_CASR - Status register - Exclusive Or command * - HW_CAU_XOR_CAA - Accumulator register - Exclusive Or command * - HW_CAU_XOR_CA0 - General Purpose Register 0 - Exclusive Or command * - HW_CAU_XOR_CA1 - General Purpose Register 1 - Exclusive Or command * - HW_CAU_XOR_CA2 - General Purpose Register 2 - Exclusive Or command * - HW_CAU_XOR_CA3 - General Purpose Register 3 - Exclusive Or command * - HW_CAU_XOR_CA4 - General Purpose Register 4 - Exclusive Or command * - HW_CAU_XOR_CA5 - General Purpose Register 5 - Exclusive Or command * - HW_CAU_XOR_CA6 - General Purpose Register 6 - Exclusive Or command * - HW_CAU_XOR_CA7 - General Purpose Register 7 - Exclusive Or command * - HW_CAU_XOR_CA8 - General Purpose Register 8 - Exclusive Or command * - HW_CAU_ROTL_CASR - Status register - Rotate Left command * - HW_CAU_ROTL_CAA - Accumulator register - Rotate Left command * - HW_CAU_ROTL_CA0 - General Purpose Register 0 - Rotate Left command * - HW_CAU_ROTL_CA1 - General Purpose Register 1 - Rotate Left command * - HW_CAU_ROTL_CA2 - General Purpose Register 2 - Rotate Left command * - HW_CAU_ROTL_CA3 - General Purpose Register 3 - Rotate Left command * - HW_CAU_ROTL_CA4 - General Purpose Register 4 - Rotate Left command * - HW_CAU_ROTL_CA5 - General Purpose Register 5 - Rotate Left command * - HW_CAU_ROTL_CA6 - General Purpose Register 6 - Rotate Left command * - HW_CAU_ROTL_CA7 - General Purpose Register 7 - Rotate Left command * - HW_CAU_ROTL_CA8 - General Purpose Register 8 - Rotate Left command * - HW_CAU_AESC_CASR - Status register - AES Column Operation command * - HW_CAU_AESC_CAA - Accumulator register - AES Column Operation command * - HW_CAU_AESC_CA0 - General Purpose Register 0 - AES Column Operation command * - HW_CAU_AESC_CA1 - General Purpose Register 1 - AES Column Operation command * - HW_CAU_AESC_CA2 - General Purpose Register 2 - AES Column Operation command * - HW_CAU_AESC_CA3 - General Purpose Register 3 - AES Column Operation command * - HW_CAU_AESC_CA4 - General Purpose Register 4 - AES Column Operation command * - HW_CAU_AESC_CA5 - General Purpose Register 5 - AES Column Operation command * - HW_CAU_AESC_CA6 - General Purpose Register 6 - AES Column Operation command * - HW_CAU_AESC_CA7 - General Purpose Register 7 - AES Column Operation command * - HW_CAU_AESC_CA8 - General Purpose Register 8 - AES Column Operation command * - HW_CAU_AESIC_CASR - Status register - AES Inverse Column Operation command * - HW_CAU_AESIC_CAA - Accumulator register - AES Inverse Column Operation command * - HW_CAU_AESIC_CA0 - General Purpose Register 0 - AES Inverse Column Operation command * - HW_CAU_AESIC_CA1 - General Purpose Register 1 - AES Inverse Column Operation command * - HW_CAU_AESIC_CA2 - General Purpose Register 2 - AES Inverse Column Operation command * - HW_CAU_AESIC_CA3 - General Purpose Register 3 - AES Inverse Column Operation command * - HW_CAU_AESIC_CA4 - General Purpose Register 4 - AES Inverse Column Operation command * - HW_CAU_AESIC_CA5 - General Purpose Register 5 - AES Inverse Column Operation command * - HW_CAU_AESIC_CA6 - General Purpose Register 6 - AES Inverse Column Operation command * - HW_CAU_AESIC_CA7 - General Purpose Register 7 - AES Inverse Column Operation command * - HW_CAU_AESIC_CA8 - General Purpose Register 8 - AES Inverse Column Operation command * * - hw_cau_t - Struct containing all module registers. */ #define HW_CAU_INSTANCE_COUNT (1U) /*!< Number of instances of the CAU module. */ /******************************************************************************* * HW_CAU_DIRECT0 - Direct access register 0 ******************************************************************************/ /*! * @brief HW_CAU_DIRECT0 - Direct access register 0 (WO) * * Reset value: 0x00000000U */ typedef union _hw_cau_direct0 { uint32_t U; struct _hw_cau_direct0_bitfields { uint32_t CAU_DIRECT0b : 32; /*!< [31:0] Direct register 0 */ } B; } hw_cau_direct0_t; /*! * @name Constants and macros for entire CAU_DIRECT0 register */ /*@{*/ #define HW_CAU_DIRECT0_ADDR(x) ((x) + 0x0U) #define HW_CAU_DIRECT0(x) (*(__O hw_cau_direct0_t *) HW_CAU_DIRECT0_ADDR(x)) #define HW_CAU_DIRECT0_WR(x, v) (HW_CAU_DIRECT0(x).U = (v)) /*@}*/ /* * Constants & macros for individual CAU_DIRECT0 bitfields */ /*! * @name Register CAU_DIRECT0, field CAU_DIRECT0[31:0] (WO) */ /*@{*/ #define BP_CAU_DIRECT0_CAU_DIRECT0 (0U) /*!< Bit position for CAU_DIRECT0_CAU_DIRECT0. */ #define BM_CAU_DIRECT0_CAU_DIRECT0 (0xFFFFFFFFU) /*!< Bit mask for CAU_DIRECT0_CAU_DIRECT0. */ #define BS_CAU_DIRECT0_CAU_DIRECT0 (32U) /*!< Bit field size in bits for CAU_DIRECT0_CAU_DIRECT0. */ /*! @brief Format value for bitfield CAU_DIRECT0_CAU_DIRECT0. */ #define BF_CAU_DIRECT0_CAU_DIRECT0(v) ((uint32_t)((uint32_t)(v) << BP_CAU_DIRECT0_CAU_DIRECT0) & BM_CAU_DIRECT0_CAU_DIRECT0) /*@}*/ /******************************************************************************* * HW_CAU_DIRECT1 - Direct access register 1 ******************************************************************************/ /*! * @brief HW_CAU_DIRECT1 - Direct access register 1 (WO) * * Reset value: 0x00000000U */ typedef union _hw_cau_direct1 { uint32_t U; struct _hw_cau_direct1_bitfields { uint32_t CAU_DIRECT1b : 32; /*!< [31:0] Direct register 1 */ } B; } hw_cau_direct1_t; /*! * @name Constants and macros for entire CAU_DIRECT1 register */ /*@{*/ #define HW_CAU_DIRECT1_ADDR(x) ((x) + 0x4U) #define HW_CAU_DIRECT1(x) (*(__O hw_cau_direct1_t *) HW_CAU_DIRECT1_ADDR(x)) #define HW_CAU_DIRECT1_WR(x, v) (HW_CAU_DIRECT1(x).U = (v)) /*@}*/ /* * Constants & macros for individual CAU_DIRECT1 bitfields */ /*! * @name Register CAU_DIRECT1, field CAU_DIRECT1[31:0] (WO) */ /*@{*/ #define BP_CAU_DIRECT1_CAU_DIRECT1 (0U) /*!< Bit position for CAU_DIRECT1_CAU_DIRECT1. */ #define BM_CAU_DIRECT1_CAU_DIRECT1 (0xFFFFFFFFU) /*!< Bit mask for CAU_DIRECT1_CAU_DIRECT1. */ #define BS_CAU_DIRECT1_CAU_DIRECT1 (32U) /*!< Bit field size in bits for CAU_DIRECT1_CAU_DIRECT1. */ /*! @brief Format value for bitfield CAU_DIRECT1_CAU_DIRECT1. */ #define BF_CAU_DIRECT1_CAU_DIRECT1(v) ((uint32_t)((uint32_t)(v) << BP_CAU_DIRECT1_CAU_DIRECT1) & BM_CAU_DIRECT1_CAU_DIRECT1) /*@}*/ /******************************************************************************* * HW_CAU_DIRECT2 - Direct access register 2 ******************************************************************************/ /*! * @brief HW_CAU_DIRECT2 - Direct access register 2 (WO) * * Reset value: 0x00000000U */ typedef union _hw_cau_direct2 { uint32_t U; struct _hw_cau_direct2_bitfields { uint32_t CAU_DIRECT2b : 32; /*!< [31:0] Direct register 2 */ } B; } hw_cau_direct2_t; /*! * @name Constants and macros for entire CAU_DIRECT2 register */ /*@{*/ #define HW_CAU_DIRECT2_ADDR(x) ((x) + 0x8U) #define HW_CAU_DIRECT2(x) (*(__O hw_cau_direct2_t *) HW_CAU_DIRECT2_ADDR(x)) #define HW_CAU_DIRECT2_WR(x, v) (HW_CAU_DIRECT2(x).U = (v)) /*@}*/ /* * Constants & macros for individual CAU_DIRECT2 bitfields */ /*! * @name Register CAU_DIRECT2, field CAU_DIRECT2[31:0] (WO) */ /*@{*/ #define BP_CAU_DIRECT2_CAU_DIRECT2 (0U) /*!< Bit position for CAU_DIRECT2_CAU_DIRECT2. */ #define BM_CAU_DIRECT2_CAU_DIRECT2 (0xFFFFFFFFU) /*!< Bit mask for CAU_DIRECT2_CAU_DIRECT2. */ #define BS_CAU_DIRECT2_CAU_DIRECT2 (32U) /*!< Bit field size in bits for CAU_DIRECT2_CAU_DIRECT2. */ /*! @brief Format value for bitfield CAU_DIRECT2_CAU_DIRECT2. */ #define BF_CAU_DIRECT2_CAU_DIRECT2(v) ((uint32_t)((uint32_t)(v) << BP_CAU_DIRECT2_CAU_DIRECT2) & BM_CAU_DIRECT2_CAU_DIRECT2) /*@}*/ /******************************************************************************* * HW_CAU_DIRECT3 - Direct access register 3 ******************************************************************************/ /*! * @brief HW_CAU_DIRECT3 - Direct access register 3 (WO) * * Reset value: 0x00000000U */ typedef union _hw_cau_direct3 { uint32_t U; struct _hw_cau_direct3_bitfields { uint32_t CAU_DIRECT3b : 32; /*!< [31:0] Direct register 3 */ } B; } hw_cau_direct3_t; /*! * @name Constants and macros for entire CAU_DIRECT3 register */ /*@{*/ #define HW_CAU_DIRECT3_ADDR(x) ((x) + 0xCU) #define HW_CAU_DIRECT3(x) (*(__O hw_cau_direct3_t *) HW_CAU_DIRECT3_ADDR(x)) #define HW_CAU_DIRECT3_WR(x, v) (HW_CAU_DIRECT3(x).U = (v)) /*@}*/ /* * Constants & macros for individual CAU_DIRECT3 bitfields */ /*! * @name Register CAU_DIRECT3, field CAU_DIRECT3[31:0] (WO) */ /*@{*/ #define BP_CAU_DIRECT3_CAU_DIRECT3 (0U) /*!< Bit position for CAU_DIRECT3_CAU_DIRECT3. */ #define BM_CAU_DIRECT3_CAU_DIRECT3 (0xFFFFFFFFU) /*!< Bit mask for CAU_DIRECT3_CAU_DIRECT3. */ #define BS_CAU_DIRECT3_CAU_DIRECT3 (32U) /*!< Bit field size in bits for CAU_DIRECT3_CAU_DIRECT3. */ /*! @brief Format value for bitfield CAU_DIRECT3_CAU_DIRECT3. */ #define BF_CAU_DIRECT3_CAU_DIRECT3(v) ((uint32_t)((uint32_t)(v) << BP_CAU_DIRECT3_CAU_DIRECT3) & BM_CAU_DIRECT3_CAU_DIRECT3) /*@}*/ /******************************************************************************* * HW_CAU_DIRECT4 - Direct access register 4 ******************************************************************************/ /*! * @brief HW_CAU_DIRECT4 - Direct access register 4 (WO) * * Reset value: 0x00000000U */ typedef union _hw_cau_direct4 { uint32_t U; struct _hw_cau_direct4_bitfields { uint32_t CAU_DIRECT4b : 32; /*!< [31:0] Direct register 4 */ } B; } hw_cau_direct4_t; /*! * @name Constants and macros for entire CAU_DIRECT4 register */ /*@{*/ #define HW_CAU_DIRECT4_ADDR(x) ((x) + 0x10U) #define HW_CAU_DIRECT4(x) (*(__O hw_cau_direct4_t *) HW_CAU_DIRECT4_ADDR(x)) #define HW_CAU_DIRECT4_WR(x, v) (HW_CAU_DIRECT4(x).U = (v)) /*@}*/ /* * Constants & macros for individual CAU_DIRECT4 bitfields */ /*! * @name Register CAU_DIRECT4, field CAU_DIRECT4[31:0] (WO) */ /*@{*/ #define BP_CAU_DIRECT4_CAU_DIRECT4 (0U) /*!< Bit position for CAU_DIRECT4_CAU_DIRECT4. */ #define BM_CAU_DIRECT4_CAU_DIRECT4 (0xFFFFFFFFU) /*!< Bit mask for CAU_DIRECT4_CAU_DIRECT4. */ #define BS_CAU_DIRECT4_CAU_DIRECT4 (32U) /*!< Bit field size in bits for CAU_DIRECT4_CAU_DIRECT4. */ /*! @brief Format value for bitfield CAU_DIRECT4_CAU_DIRECT4. */ #define BF_CAU_DIRECT4_CAU_DIRECT4(v) ((uint32_t)((uint32_t)(v) << BP_CAU_DIRECT4_CAU_DIRECT4) & BM_CAU_DIRECT4_CAU_DIRECT4) /*@}*/ /******************************************************************************* * HW_CAU_DIRECT5 - Direct access register 5 ******************************************************************************/ /*! * @brief HW_CAU_DIRECT5 - Direct access register 5 (WO) * * Reset value: 0x00000000U */ typedef union _hw_cau_direct5 { uint32_t U; struct _hw_cau_direct5_bitfields { uint32_t CAU_DIRECT5b : 32; /*!< [31:0] Direct register 5 */ } B; } hw_cau_direct5_t; /*! * @name Constants and macros for entire CAU_DIRECT5 register */ /*@{*/ #define HW_CAU_DIRECT5_ADDR(x) ((x) + 0x14U) #define HW_CAU_DIRECT5(x) (*(__O hw_cau_direct5_t *) HW_CAU_DIRECT5_ADDR(x)) #define HW_CAU_DIRECT5_WR(x, v) (HW_CAU_DIRECT5(x).U = (v)) /*@}*/ /* * Constants & macros for individual CAU_DIRECT5 bitfields */ /*! * @name Register CAU_DIRECT5, field CAU_DIRECT5[31:0] (WO) */ /*@{*/ #define BP_CAU_DIRECT5_CAU_DIRECT5 (0U) /*!< Bit position for CAU_DIRECT5_CAU_DIRECT5. */ #define BM_CAU_DIRECT5_CAU_DIRECT5 (0xFFFFFFFFU) /*!< Bit mask for CAU_DIRECT5_CAU_DIRECT5. */ #define BS_CAU_DIRECT5_CAU_DIRECT5 (32U) /*!< Bit field size in bits for CAU_DIRECT5_CAU_DIRECT5. */ /*! @brief Format value for bitfield CAU_DIRECT5_CAU_DIRECT5. */ #define BF_CAU_DIRECT5_CAU_DIRECT5(v) ((uint32_t)((uint32_t)(v) << BP_CAU_DIRECT5_CAU_DIRECT5) & BM_CAU_DIRECT5_CAU_DIRECT5) /*@}*/ /******************************************************************************* * HW_CAU_DIRECT6 - Direct access register 6 ******************************************************************************/ /*! * @brief HW_CAU_DIRECT6 - Direct access register 6 (WO) * * Reset value: 0x00000000U */ typedef union _hw_cau_direct6 { uint32_t U; struct _hw_cau_direct6_bitfields { uint32_t CAU_DIRECT6b : 32; /*!< [31:0] Direct register 6 */ } B; } hw_cau_direct6_t; /*! * @name Constants and macros for entire CAU_DIRECT6 register */ /*@{*/ #define HW_CAU_DIRECT6_ADDR(x) ((x) + 0x18U) #define HW_CAU_DIRECT6(x) (*(__O hw_cau_direct6_t *) HW_CAU_DIRECT6_ADDR(x)) #define HW_CAU_DIRECT6_WR(x, v) (HW_CAU_DIRECT6(x).U = (v)) /*@}*/ /* * Constants & macros for individual CAU_DIRECT6 bitfields */ /*! * @name Register CAU_DIRECT6, field CAU_DIRECT6[31:0] (WO) */ /*@{*/ #define BP_CAU_DIRECT6_CAU_DIRECT6 (0U) /*!< Bit position for CAU_DIRECT6_CAU_DIRECT6. */ #define BM_CAU_DIRECT6_CAU_DIRECT6 (0xFFFFFFFFU) /*!< Bit mask for CAU_DIRECT6_CAU_DIRECT6. */ #define BS_CAU_DIRECT6_CAU_DIRECT6 (32U) /*!< Bit field size in bits for CAU_DIRECT6_CAU_DIRECT6. */ /*! @brief Format value for bitfield CAU_DIRECT6_CAU_DIRECT6. */ #define BF_CAU_DIRECT6_CAU_DIRECT6(v) ((uint32_t)((uint32_t)(v) << BP_CAU_DIRECT6_CAU_DIRECT6) & BM_CAU_DIRECT6_CAU_DIRECT6) /*@}*/ /******************************************************************************* * HW_CAU_DIRECT7 - Direct access register 7 ******************************************************************************/ /*! * @brief HW_CAU_DIRECT7 - Direct access register 7 (WO) * * Reset value: 0x00000000U */ typedef union _hw_cau_direct7 { uint32_t U; struct _hw_cau_direct7_bitfields { uint32_t CAU_DIRECT7b : 32; /*!< [31:0] Direct register 7 */ } B; } hw_cau_direct7_t; /*! * @name Constants and macros for entire CAU_DIRECT7 register */ /*@{*/ #define HW_CAU_DIRECT7_ADDR(x) ((x) + 0x1CU) #define HW_CAU_DIRECT7(x) (*(__O hw_cau_direct7_t *) HW_CAU_DIRECT7_ADDR(x)) #define HW_CAU_DIRECT7_WR(x, v) (HW_CAU_DIRECT7(x).U = (v)) /*@}*/ /* * Constants & macros for individual CAU_DIRECT7 bitfields */ /*! * @name Register CAU_DIRECT7, field CAU_DIRECT7[31:0] (WO) */ /*@{*/ #define BP_CAU_DIRECT7_CAU_DIRECT7 (0U) /*!< Bit position for CAU_DIRECT7_CAU_DIRECT7. */ #define BM_CAU_DIRECT7_CAU_DIRECT7 (0xFFFFFFFFU) /*!< Bit mask for CAU_DIRECT7_CAU_DIRECT7. */ #define BS_CAU_DIRECT7_CAU_DIRECT7 (32U) /*!< Bit field size in bits for CAU_DIRECT7_CAU_DIRECT7. */ /*! @brief Format value for bitfield CAU_DIRECT7_CAU_DIRECT7. */ #define BF_CAU_DIRECT7_CAU_DIRECT7(v) ((uint32_t)((uint32_t)(v) << BP_CAU_DIRECT7_CAU_DIRECT7) & BM_CAU_DIRECT7_CAU_DIRECT7) /*@}*/ /******************************************************************************* * HW_CAU_DIRECT8 - Direct access register 8 ******************************************************************************/ /*! * @brief HW_CAU_DIRECT8 - Direct access register 8 (WO) * * Reset value: 0x00000000U */ typedef union _hw_cau_direct8 { uint32_t U; struct _hw_cau_direct8_bitfields { uint32_t CAU_DIRECT8b : 32; /*!< [31:0] Direct register 8 */ } B; } hw_cau_direct8_t; /*! * @name Constants and macros for entire CAU_DIRECT8 register */ /*@{*/ #define HW_CAU_DIRECT8_ADDR(x) ((x) + 0x20U) #define HW_CAU_DIRECT8(x) (*(__O hw_cau_direct8_t *) HW_CAU_DIRECT8_ADDR(x)) #define HW_CAU_DIRECT8_WR(x, v) (HW_CAU_DIRECT8(x).U = (v)) /*@}*/ /* * Constants & macros for individual CAU_DIRECT8 bitfields */ /*! * @name Register CAU_DIRECT8, field CAU_DIRECT8[31:0] (WO) */ /*@{*/ #define BP_CAU_DIRECT8_CAU_DIRECT8 (0U) /*!< Bit position for CAU_DIRECT8_CAU_DIRECT8. */ #define BM_CAU_DIRECT8_CAU_DIRECT8 (0xFFFFFFFFU) /*!< Bit mask for CAU_DIRECT8_CAU_DIRECT8. */ #define BS_CAU_DIRECT8_CAU_DIRECT8 (32U) /*!< Bit field size in bits for CAU_DIRECT8_CAU_DIRECT8. */ /*! @brief Format value for bitfield CAU_DIRECT8_CAU_DIRECT8. */ #define BF_CAU_DIRECT8_CAU_DIRECT8(v) ((uint32_t)((uint32_t)(v) << BP_CAU_DIRECT8_CAU_DIRECT8) & BM_CAU_DIRECT8_CAU_DIRECT8) /*@}*/ /******************************************************************************* * HW_CAU_DIRECT9 - Direct access register 9 ******************************************************************************/ /*! * @brief HW_CAU_DIRECT9 - Direct access register 9 (WO) * * Reset value: 0x00000000U */ typedef union _hw_cau_direct9 { uint32_t U; struct _hw_cau_direct9_bitfields { uint32_t CAU_DIRECT9b : 32; /*!< [31:0] Direct register 9 */ } B; } hw_cau_direct9_t; /*! * @name Constants and macros for entire CAU_DIRECT9 register */ /*@{*/ #define HW_CAU_DIRECT9_ADDR(x) ((x) + 0x24U) #define HW_CAU_DIRECT9(x) (*(__O hw_cau_direct9_t *) HW_CAU_DIRECT9_ADDR(x)) #define HW_CAU_DIRECT9_WR(x, v) (HW_CAU_DIRECT9(x).U = (v)) /*@}*/ /* * Constants & macros for individual CAU_DIRECT9 bitfields */ /*! * @name Register CAU_DIRECT9, field CAU_DIRECT9[31:0] (WO) */ /*@{*/ #define BP_CAU_DIRECT9_CAU_DIRECT9 (0U) /*!< Bit position for CAU_DIRECT9_CAU_DIRECT9. */ #define BM_CAU_DIRECT9_CAU_DIRECT9 (0xFFFFFFFFU) /*!< Bit mask for CAU_DIRECT9_CAU_DIRECT9. */ #define BS_CAU_DIRECT9_CAU_DIRECT9 (32U) /*!< Bit field size in bits for CAU_DIRECT9_CAU_DIRECT9. */ /*! @brief Format value for bitfield CAU_DIRECT9_CAU_DIRECT9. */ #define BF_CAU_DIRECT9_CAU_DIRECT9(v) ((uint32_t)((uint32_t)(v) << BP_CAU_DIRECT9_CAU_DIRECT9) & BM_CAU_DIRECT9_CAU_DIRECT9) /*@}*/ /******************************************************************************* * HW_CAU_DIRECT10 - Direct access register 10 ******************************************************************************/ /*! * @brief HW_CAU_DIRECT10 - Direct access register 10 (WO) * * Reset value: 0x00000000U */ typedef union _hw_cau_direct10 { uint32_t U; struct _hw_cau_direct10_bitfields { uint32_t CAU_DIRECT10b : 32; /*!< [31:0] Direct register 10 */ } B; } hw_cau_direct10_t; /*! * @name Constants and macros for entire CAU_DIRECT10 register */ /*@{*/ #define HW_CAU_DIRECT10_ADDR(x) ((x) + 0x28U) #define HW_CAU_DIRECT10(x) (*(__O hw_cau_direct10_t *) HW_CAU_DIRECT10_ADDR(x)) #define HW_CAU_DIRECT10_WR(x, v) (HW_CAU_DIRECT10(x).U = (v)) /*@}*/ /* * Constants & macros for individual CAU_DIRECT10 bitfields */ /*! * @name Register CAU_DIRECT10, field CAU_DIRECT10[31:0] (WO) */ /*@{*/ #define BP_CAU_DIRECT10_CAU_DIRECT10 (0U) /*!< Bit position for CAU_DIRECT10_CAU_DIRECT10. */ #define BM_CAU_DIRECT10_CAU_DIRECT10 (0xFFFFFFFFU) /*!< Bit mask for CAU_DIRECT10_CAU_DIRECT10. */ #define BS_CAU_DIRECT10_CAU_DIRECT10 (32U) /*!< Bit field size in bits for CAU_DIRECT10_CAU_DIRECT10. */ /*! @brief Format value for bitfield CAU_DIRECT10_CAU_DIRECT10. */ #define BF_CAU_DIRECT10_CAU_DIRECT10(v) ((uint32_t)((uint32_t)(v) << BP_CAU_DIRECT10_CAU_DIRECT10) & BM_CAU_DIRECT10_CAU_DIRECT10) /*@}*/ /******************************************************************************* * HW_CAU_DIRECT11 - Direct access register 11 ******************************************************************************/ /*! * @brief HW_CAU_DIRECT11 - Direct access register 11 (WO) * * Reset value: 0x00000000U */ typedef union _hw_cau_direct11 { uint32_t U; struct _hw_cau_direct11_bitfields { uint32_t CAU_DIRECT11b : 32; /*!< [31:0] Direct register 11 */ } B; } hw_cau_direct11_t; /*! * @name Constants and macros for entire CAU_DIRECT11 register */ /*@{*/ #define HW_CAU_DIRECT11_ADDR(x) ((x) + 0x2CU) #define HW_CAU_DIRECT11(x) (*(__O hw_cau_direct11_t *) HW_CAU_DIRECT11_ADDR(x)) #define HW_CAU_DIRECT11_WR(x, v) (HW_CAU_DIRECT11(x).U = (v)) /*@}*/ /* * Constants & macros for individual CAU_DIRECT11 bitfields */ /*! * @name Register CAU_DIRECT11, field CAU_DIRECT11[31:0] (WO) */ /*@{*/ #define BP_CAU_DIRECT11_CAU_DIRECT11 (0U) /*!< Bit position for CAU_DIRECT11_CAU_DIRECT11. */ #define BM_CAU_DIRECT11_CAU_DIRECT11 (0xFFFFFFFFU) /*!< Bit mask for CAU_DIRECT11_CAU_DIRECT11. */ #define BS_CAU_DIRECT11_CAU_DIRECT11 (32U) /*!< Bit field size in bits for CAU_DIRECT11_CAU_DIRECT11. */ /*! @brief Format value for bitfield CAU_DIRECT11_CAU_DIRECT11. */ #define BF_CAU_DIRECT11_CAU_DIRECT11(v) ((uint32_t)((uint32_t)(v) << BP_CAU_DIRECT11_CAU_DIRECT11) & BM_CAU_DIRECT11_CAU_DIRECT11) /*@}*/ /******************************************************************************* * HW_CAU_DIRECT12 - Direct access register 12 ******************************************************************************/ /*! * @brief HW_CAU_DIRECT12 - Direct access register 12 (WO) * * Reset value: 0x00000000U */ typedef union _hw_cau_direct12 { uint32_t U; struct _hw_cau_direct12_bitfields { uint32_t CAU_DIRECT12b : 32; /*!< [31:0] Direct register 12 */ } B; } hw_cau_direct12_t; /*! * @name Constants and macros for entire CAU_DIRECT12 register */ /*@{*/ #define HW_CAU_DIRECT12_ADDR(x) ((x) + 0x30U) #define HW_CAU_DIRECT12(x) (*(__O hw_cau_direct12_t *) HW_CAU_DIRECT12_ADDR(x)) #define HW_CAU_DIRECT12_WR(x, v) (HW_CAU_DIRECT12(x).U = (v)) /*@}*/ /* * Constants & macros for individual CAU_DIRECT12 bitfields */ /*! * @name Register CAU_DIRECT12, field CAU_DIRECT12[31:0] (WO) */ /*@{*/ #define BP_CAU_DIRECT12_CAU_DIRECT12 (0U) /*!< Bit position for CAU_DIRECT12_CAU_DIRECT12. */ #define BM_CAU_DIRECT12_CAU_DIRECT12 (0xFFFFFFFFU) /*!< Bit mask for CAU_DIRECT12_CAU_DIRECT12. */ #define BS_CAU_DIRECT12_CAU_DIRECT12 (32U) /*!< Bit field size in bits for CAU_DIRECT12_CAU_DIRECT12. */ /*! @brief Format value for bitfield CAU_DIRECT12_CAU_DIRECT12. */ #define BF_CAU_DIRECT12_CAU_DIRECT12(v) ((uint32_t)((uint32_t)(v) << BP_CAU_DIRECT12_CAU_DIRECT12) & BM_CAU_DIRECT12_CAU_DIRECT12) /*@}*/ /******************************************************************************* * HW_CAU_DIRECT13 - Direct access register 13 ******************************************************************************/ /*! * @brief HW_CAU_DIRECT13 - Direct access register 13 (WO) * * Reset value: 0x00000000U */ typedef union _hw_cau_direct13 { uint32_t U; struct _hw_cau_direct13_bitfields { uint32_t CAU_DIRECT13b : 32; /*!< [31:0] Direct register 13 */ } B; } hw_cau_direct13_t; /*! * @name Constants and macros for entire CAU_DIRECT13 register */ /*@{*/ #define HW_CAU_DIRECT13_ADDR(x) ((x) + 0x34U) #define HW_CAU_DIRECT13(x) (*(__O hw_cau_direct13_t *) HW_CAU_DIRECT13_ADDR(x)) #define HW_CAU_DIRECT13_WR(x, v) (HW_CAU_DIRECT13(x).U = (v)) /*@}*/ /* * Constants & macros for individual CAU_DIRECT13 bitfields */ /*! * @name Register CAU_DIRECT13, field CAU_DIRECT13[31:0] (WO) */ /*@{*/ #define BP_CAU_DIRECT13_CAU_DIRECT13 (0U) /*!< Bit position for CAU_DIRECT13_CAU_DIRECT13. */ #define BM_CAU_DIRECT13_CAU_DIRECT13 (0xFFFFFFFFU) /*!< Bit mask for CAU_DIRECT13_CAU_DIRECT13. */ #define BS_CAU_DIRECT13_CAU_DIRECT13 (32U) /*!< Bit field size in bits for CAU_DIRECT13_CAU_DIRECT13. */ /*! @brief Format value for bitfield CAU_DIRECT13_CAU_DIRECT13. */ #define BF_CAU_DIRECT13_CAU_DIRECT13(v) ((uint32_t)((uint32_t)(v) << BP_CAU_DIRECT13_CAU_DIRECT13) & BM_CAU_DIRECT13_CAU_DIRECT13) /*@}*/ /******************************************************************************* * HW_CAU_DIRECT14 - Direct access register 14 ******************************************************************************/ /*! * @brief HW_CAU_DIRECT14 - Direct access register 14 (WO) * * Reset value: 0x00000000U */ typedef union _hw_cau_direct14 { uint32_t U; struct _hw_cau_direct14_bitfields { uint32_t CAU_DIRECT14b : 32; /*!< [31:0] Direct register 14 */ } B; } hw_cau_direct14_t; /*! * @name Constants and macros for entire CAU_DIRECT14 register */ /*@{*/ #define HW_CAU_DIRECT14_ADDR(x) ((x) + 0x38U) #define HW_CAU_DIRECT14(x) (*(__O hw_cau_direct14_t *) HW_CAU_DIRECT14_ADDR(x)) #define HW_CAU_DIRECT14_WR(x, v) (HW_CAU_DIRECT14(x).U = (v)) /*@}*/ /* * Constants & macros for individual CAU_DIRECT14 bitfields */ /*! * @name Register CAU_DIRECT14, field CAU_DIRECT14[31:0] (WO) */ /*@{*/ #define BP_CAU_DIRECT14_CAU_DIRECT14 (0U) /*!< Bit position for CAU_DIRECT14_CAU_DIRECT14. */ #define BM_CAU_DIRECT14_CAU_DIRECT14 (0xFFFFFFFFU) /*!< Bit mask for CAU_DIRECT14_CAU_DIRECT14. */ #define BS_CAU_DIRECT14_CAU_DIRECT14 (32U) /*!< Bit field size in bits for CAU_DIRECT14_CAU_DIRECT14. */ /*! @brief Format value for bitfield CAU_DIRECT14_CAU_DIRECT14. */ #define BF_CAU_DIRECT14_CAU_DIRECT14(v) ((uint32_t)((uint32_t)(v) << BP_CAU_DIRECT14_CAU_DIRECT14) & BM_CAU_DIRECT14_CAU_DIRECT14) /*@}*/ /******************************************************************************* * HW_CAU_DIRECT15 - Direct access register 15 ******************************************************************************/ /*! * @brief HW_CAU_DIRECT15 - Direct access register 15 (WO) * * Reset value: 0x00000000U */ typedef union _hw_cau_direct15 { uint32_t U; struct _hw_cau_direct15_bitfields { uint32_t CAU_DIRECT15b : 32; /*!< [31:0] Direct register 15 */ } B; } hw_cau_direct15_t; /*! * @name Constants and macros for entire CAU_DIRECT15 register */ /*@{*/ #define HW_CAU_DIRECT15_ADDR(x) ((x) + 0x3CU) #define HW_CAU_DIRECT15(x) (*(__O hw_cau_direct15_t *) HW_CAU_DIRECT15_ADDR(x)) #define HW_CAU_DIRECT15_WR(x, v) (HW_CAU_DIRECT15(x).U = (v)) /*@}*/ /* * Constants & macros for individual CAU_DIRECT15 bitfields */ /*! * @name Register CAU_DIRECT15, field CAU_DIRECT15[31:0] (WO) */ /*@{*/ #define BP_CAU_DIRECT15_CAU_DIRECT15 (0U) /*!< Bit position for CAU_DIRECT15_CAU_DIRECT15. */ #define BM_CAU_DIRECT15_CAU_DIRECT15 (0xFFFFFFFFU) /*!< Bit mask for CAU_DIRECT15_CAU_DIRECT15. */ #define BS_CAU_DIRECT15_CAU_DIRECT15 (32U) /*!< Bit field size in bits for CAU_DIRECT15_CAU_DIRECT15. */ /*! @brief Format value for bitfield CAU_DIRECT15_CAU_DIRECT15. */ #define BF_CAU_DIRECT15_CAU_DIRECT15(v) ((uint32_t)((uint32_t)(v) << BP_CAU_DIRECT15_CAU_DIRECT15) & BM_CAU_DIRECT15_CAU_DIRECT15) /*@}*/ /******************************************************************************* * HW_CAU_LDR_CASR - Status register - Load Register command ******************************************************************************/ /*! * @brief HW_CAU_LDR_CASR - Status register - Load Register command (WO) * * Reset value: 0x20000000U */ typedef union _hw_cau_ldr_casr { uint32_t U; struct _hw_cau_ldr_casr_bitfields { uint32_t IC : 1; /*!< [0] */ uint32_t DPE : 1; /*!< [1] */ uint32_t RESERVED0 : 26; /*!< [27:2] */ uint32_t VER : 4; /*!< [31:28] CAU version */ } B; } hw_cau_ldr_casr_t; /*! * @name Constants and macros for entire CAU_LDR_CASR register */ /*@{*/ #define HW_CAU_LDR_CASR_ADDR(x) ((x) + 0x840U) #define HW_CAU_LDR_CASR(x) (*(__O hw_cau_ldr_casr_t *) HW_CAU_LDR_CASR_ADDR(x)) #define HW_CAU_LDR_CASR_WR(x, v) (HW_CAU_LDR_CASR(x).U = (v)) /*@}*/ /* * Constants & macros for individual CAU_LDR_CASR bitfields */ /*! * @name Register CAU_LDR_CASR, field IC[0] (WO) * * Values: * - 0 - No illegal commands issued * - 1 - Illegal command issued */ /*@{*/ #define BP_CAU_LDR_CASR_IC (0U) /*!< Bit position for CAU_LDR_CASR_IC. */ #define BM_CAU_LDR_CASR_IC (0x00000001U) /*!< Bit mask for CAU_LDR_CASR_IC. */ #define BS_CAU_LDR_CASR_IC (1U) /*!< Bit field size in bits for CAU_LDR_CASR_IC. */ /*! @brief Format value for bitfield CAU_LDR_CASR_IC. */ #define BF_CAU_LDR_CASR_IC(v) ((uint32_t)((uint32_t)(v) << BP_CAU_LDR_CASR_IC) & BM_CAU_LDR_CASR_IC) /*@}*/ /*! * @name Register CAU_LDR_CASR, field DPE[1] (WO) * * Values: * - 0 - No error detected * - 1 - DES key parity error detected */ /*@{*/ #define BP_CAU_LDR_CASR_DPE (1U) /*!< Bit position for CAU_LDR_CASR_DPE. */ #define BM_CAU_LDR_CASR_DPE (0x00000002U) /*!< Bit mask for CAU_LDR_CASR_DPE. */ #define BS_CAU_LDR_CASR_DPE (1U) /*!< Bit field size in bits for CAU_LDR_CASR_DPE. */ /*! @brief Format value for bitfield CAU_LDR_CASR_DPE. */ #define BF_CAU_LDR_CASR_DPE(v) ((uint32_t)((uint32_t)(v) << BP_CAU_LDR_CASR_DPE) & BM_CAU_LDR_CASR_DPE) /*@}*/ /*! * @name Register CAU_LDR_CASR, field VER[31:28] (WO) * * Values: * - 0001 - Initial CAU version * - 0010 - Second version, added support for SHA-256 algorithm.(This is the * value on this device) */ /*@{*/ #define BP_CAU_LDR_CASR_VER (28U) /*!< Bit position for CAU_LDR_CASR_VER. */ #define BM_CAU_LDR_CASR_VER (0xF0000000U) /*!< Bit mask for CAU_LDR_CASR_VER. */ #define BS_CAU_LDR_CASR_VER (4U) /*!< Bit field size in bits for CAU_LDR_CASR_VER. */ /*! @brief Format value for bitfield CAU_LDR_CASR_VER. */ #define BF_CAU_LDR_CASR_VER(v) ((uint32_t)((uint32_t)(v) << BP_CAU_LDR_CASR_VER) & BM_CAU_LDR_CASR_VER) /*@}*/ /******************************************************************************* * HW_CAU_LDR_CAA - Accumulator register - Load Register command ******************************************************************************/ /*! * @brief HW_CAU_LDR_CAA - Accumulator register - Load Register command (WO) * * Reset value: 0x00000000U */ typedef union _hw_cau_ldr_caa { uint32_t U; struct _hw_cau_ldr_caa_bitfields { uint32_t ACC : 32; /*!< [31:0] ACC */ } B; } hw_cau_ldr_caa_t; /*! * @name Constants and macros for entire CAU_LDR_CAA register */ /*@{*/ #define HW_CAU_LDR_CAA_ADDR(x) ((x) + 0x844U) #define HW_CAU_LDR_CAA(x) (*(__O hw_cau_ldr_caa_t *) HW_CAU_LDR_CAA_ADDR(x)) #define HW_CAU_LDR_CAA_WR(x, v) (HW_CAU_LDR_CAA(x).U = (v)) /*@}*/ /* * Constants & macros for individual CAU_LDR_CAA bitfields */ /*! * @name Register CAU_LDR_CAA, field ACC[31:0] (WO) */ /*@{*/ #define BP_CAU_LDR_CAA_ACC (0U) /*!< Bit position for CAU_LDR_CAA_ACC. */ #define BM_CAU_LDR_CAA_ACC (0xFFFFFFFFU) /*!< Bit mask for CAU_LDR_CAA_ACC. */ #define BS_CAU_LDR_CAA_ACC (32U) /*!< Bit field size in bits for CAU_LDR_CAA_ACC. */ /*! @brief Format value for bitfield CAU_LDR_CAA_ACC. */ #define BF_CAU_LDR_CAA_ACC(v) ((uint32_t)((uint32_t)(v) << BP_CAU_LDR_CAA_ACC) & BM_CAU_LDR_CAA_ACC) /*@}*/ /******************************************************************************* * HW_CAU_LDR_CA0 - General Purpose Register 0 - Load Register command ******************************************************************************/ /*! * @brief HW_CAU_LDR_CA0 - General Purpose Register 0 - Load Register command (WO) * * Reset value: 0x00000000U */ typedef union _hw_cau_ldr_ca0 { uint32_t U; struct _hw_cau_ldr_ca0_bitfields { uint32_t CA0 : 32; /*!< [31:0] CA0 */ } B; } hw_cau_ldr_ca0_t; /*! * @name Constants and macros for entire CAU_LDR_CA0 register */ /*@{*/ #define HW_CAU_LDR_CA0_ADDR(x) ((x) + 0x848U) #define HW_CAU_LDR_CA0(x) (*(__O hw_cau_ldr_ca0_t *) HW_CAU_LDR_CA0_ADDR(x)) #define HW_CAU_LDR_CA0_WR(x, v) (HW_CAU_LDR_CA0(x).U = (v)) /*@}*/ /* * Constants & macros for individual CAU_LDR_CA0 bitfields */ /*! * @name Register CAU_LDR_CA0, field CA0[31:0] (WO) */ /*@{*/ #define BP_CAU_LDR_CA0_CA0 (0U) /*!< Bit position for CAU_LDR_CA0_CA0. */ #define BM_CAU_LDR_CA0_CA0 (0xFFFFFFFFU) /*!< Bit mask for CAU_LDR_CA0_CA0. */ #define BS_CAU_LDR_CA0_CA0 (32U) /*!< Bit field size in bits for CAU_LDR_CA0_CA0. */ /*! @brief Format value for bitfield CAU_LDR_CA0_CA0. */ #define BF_CAU_LDR_CA0_CA0(v) ((uint32_t)((uint32_t)(v) << BP_CAU_LDR_CA0_CA0) & BM_CAU_LDR_CA0_CA0) /*@}*/ /******************************************************************************* * HW_CAU_LDR_CA1 - General Purpose Register 1 - Load Register command ******************************************************************************/ /*! * @brief HW_CAU_LDR_CA1 - General Purpose Register 1 - Load Register command (WO) * * Reset value: 0x00000000U */ typedef union _hw_cau_ldr_ca1 { uint32_t U; struct _hw_cau_ldr_ca1_bitfields { uint32_t CA1 : 32; /*!< [31:0] CA1 */ } B; } hw_cau_ldr_ca1_t; /*! * @name Constants and macros for entire CAU_LDR_CA1 register */ /*@{*/ #define HW_CAU_LDR_CA1_ADDR(x) ((x) + 0x84CU) #define HW_CAU_LDR_CA1(x) (*(__O hw_cau_ldr_ca1_t *) HW_CAU_LDR_CA1_ADDR(x)) #define HW_CAU_LDR_CA1_WR(x, v) (HW_CAU_LDR_CA1(x).U = (v)) /*@}*/ /* * Constants & macros for individual CAU_LDR_CA1 bitfields */ /*! * @name Register CAU_LDR_CA1, field CA1[31:0] (WO) */ /*@{*/ #define BP_CAU_LDR_CA1_CA1 (0U) /*!< Bit position for CAU_LDR_CA1_CA1. */ #define BM_CAU_LDR_CA1_CA1 (0xFFFFFFFFU) /*!< Bit mask for CAU_LDR_CA1_CA1. */ #define BS_CAU_LDR_CA1_CA1 (32U) /*!< Bit field size in bits for CAU_LDR_CA1_CA1. */ /*! @brief Format value for bitfield CAU_LDR_CA1_CA1. */ #define BF_CAU_LDR_CA1_CA1(v) ((uint32_t)((uint32_t)(v) << BP_CAU_LDR_CA1_CA1) & BM_CAU_LDR_CA1_CA1) /*@}*/ /******************************************************************************* * HW_CAU_LDR_CA2 - General Purpose Register 2 - Load Register command ******************************************************************************/ /*! * @brief HW_CAU_LDR_CA2 - General Purpose Register 2 - Load Register command (WO) * * Reset value: 0x00000000U */ typedef union _hw_cau_ldr_ca2 { uint32_t U; struct _hw_cau_ldr_ca2_bitfields { uint32_t CA2 : 32; /*!< [31:0] CA2 */ } B; } hw_cau_ldr_ca2_t; /*! * @name Constants and macros for entire CAU_LDR_CA2 register */ /*@{*/ #define HW_CAU_LDR_CA2_ADDR(x) ((x) + 0x850U) #define HW_CAU_LDR_CA2(x) (*(__O hw_cau_ldr_ca2_t *) HW_CAU_LDR_CA2_ADDR(x)) #define HW_CAU_LDR_CA2_WR(x, v) (HW_CAU_LDR_CA2(x).U = (v)) /*@}*/ /* * Constants & macros for individual CAU_LDR_CA2 bitfields */ /*! * @name Register CAU_LDR_CA2, field CA2[31:0] (WO) */ /*@{*/ #define BP_CAU_LDR_CA2_CA2 (0U) /*!< Bit position for CAU_LDR_CA2_CA2. */ #define BM_CAU_LDR_CA2_CA2 (0xFFFFFFFFU) /*!< Bit mask for CAU_LDR_CA2_CA2. */ #define BS_CAU_LDR_CA2_CA2 (32U) /*!< Bit field size in bits for CAU_LDR_CA2_CA2. */ /*! @brief Format value for bitfield CAU_LDR_CA2_CA2. */ #define BF_CAU_LDR_CA2_CA2(v) ((uint32_t)((uint32_t)(v) << BP_CAU_LDR_CA2_CA2) & BM_CAU_LDR_CA2_CA2) /*@}*/ /******************************************************************************* * HW_CAU_LDR_CA3 - General Purpose Register 3 - Load Register command ******************************************************************************/ /*! * @brief HW_CAU_LDR_CA3 - General Purpose Register 3 - Load Register command (WO) * * Reset value: 0x00000000U */ typedef union _hw_cau_ldr_ca3 { uint32_t U; struct _hw_cau_ldr_ca3_bitfields { uint32_t CA3 : 32; /*!< [31:0] CA3 */ } B; } hw_cau_ldr_ca3_t; /*! * @name Constants and macros for entire CAU_LDR_CA3 register */ /*@{*/ #define HW_CAU_LDR_CA3_ADDR(x) ((x) + 0x854U) #define HW_CAU_LDR_CA3(x) (*(__O hw_cau_ldr_ca3_t *) HW_CAU_LDR_CA3_ADDR(x)) #define HW_CAU_LDR_CA3_WR(x, v) (HW_CAU_LDR_CA3(x).U = (v)) /*@}*/ /* * Constants & macros for individual CAU_LDR_CA3 bitfields */ /*! * @name Register CAU_LDR_CA3, field CA3[31:0] (WO) */ /*@{*/ #define BP_CAU_LDR_CA3_CA3 (0U) /*!< Bit position for CAU_LDR_CA3_CA3. */ #define BM_CAU_LDR_CA3_CA3 (0xFFFFFFFFU) /*!< Bit mask for CAU_LDR_CA3_CA3. */ #define BS_CAU_LDR_CA3_CA3 (32U) /*!< Bit field size in bits for CAU_LDR_CA3_CA3. */ /*! @brief Format value for bitfield CAU_LDR_CA3_CA3. */ #define BF_CAU_LDR_CA3_CA3(v) ((uint32_t)((uint32_t)(v) << BP_CAU_LDR_CA3_CA3) & BM_CAU_LDR_CA3_CA3) /*@}*/ /******************************************************************************* * HW_CAU_LDR_CA4 - General Purpose Register 4 - Load Register command ******************************************************************************/ /*! * @brief HW_CAU_LDR_CA4 - General Purpose Register 4 - Load Register command (WO) * * Reset value: 0x00000000U */ typedef union _hw_cau_ldr_ca4 { uint32_t U; struct _hw_cau_ldr_ca4_bitfields { uint32_t CA4 : 32; /*!< [31:0] CA4 */ } B; } hw_cau_ldr_ca4_t; /*! * @name Constants and macros for entire CAU_LDR_CA4 register */ /*@{*/ #define HW_CAU_LDR_CA4_ADDR(x) ((x) + 0x858U) #define HW_CAU_LDR_CA4(x) (*(__O hw_cau_ldr_ca4_t *) HW_CAU_LDR_CA4_ADDR(x)) #define HW_CAU_LDR_CA4_WR(x, v) (HW_CAU_LDR_CA4(x).U = (v)) /*@}*/ /* * Constants & macros for individual CAU_LDR_CA4 bitfields */ /*! * @name Register CAU_LDR_CA4, field CA4[31:0] (WO) */ /*@{*/ #define BP_CAU_LDR_CA4_CA4 (0U) /*!< Bit position for CAU_LDR_CA4_CA4. */ #define BM_CAU_LDR_CA4_CA4 (0xFFFFFFFFU) /*!< Bit mask for CAU_LDR_CA4_CA4. */ #define BS_CAU_LDR_CA4_CA4 (32U) /*!< Bit field size in bits for CAU_LDR_CA4_CA4. */ /*! @brief Format value for bitfield CAU_LDR_CA4_CA4. */ #define BF_CAU_LDR_CA4_CA4(v) ((uint32_t)((uint32_t)(v) << BP_CAU_LDR_CA4_CA4) & BM_CAU_LDR_CA4_CA4) /*@}*/ /******************************************************************************* * HW_CAU_LDR_CA5 - General Purpose Register 5 - Load Register command ******************************************************************************/ /*! * @brief HW_CAU_LDR_CA5 - General Purpose Register 5 - Load Register command (WO) * * Reset value: 0x00000000U */ typedef union _hw_cau_ldr_ca5 { uint32_t U; struct _hw_cau_ldr_ca5_bitfields { uint32_t CA5 : 32; /*!< [31:0] CA5 */ } B; } hw_cau_ldr_ca5_t; /*! * @name Constants and macros for entire CAU_LDR_CA5 register */ /*@{*/ #define HW_CAU_LDR_CA5_ADDR(x) ((x) + 0x85CU) #define HW_CAU_LDR_CA5(x) (*(__O hw_cau_ldr_ca5_t *) HW_CAU_LDR_CA5_ADDR(x)) #define HW_CAU_LDR_CA5_WR(x, v) (HW_CAU_LDR_CA5(x).U = (v)) /*@}*/ /* * Constants & macros for individual CAU_LDR_CA5 bitfields */ /*! * @name Register CAU_LDR_CA5, field CA5[31:0] (WO) */ /*@{*/ #define BP_CAU_LDR_CA5_CA5 (0U) /*!< Bit position for CAU_LDR_CA5_CA5. */ #define BM_CAU_LDR_CA5_CA5 (0xFFFFFFFFU) /*!< Bit mask for CAU_LDR_CA5_CA5. */ #define BS_CAU_LDR_CA5_CA5 (32U) /*!< Bit field size in bits for CAU_LDR_CA5_CA5. */ /*! @brief Format value for bitfield CAU_LDR_CA5_CA5. */ #define BF_CAU_LDR_CA5_CA5(v) ((uint32_t)((uint32_t)(v) << BP_CAU_LDR_CA5_CA5) & BM_CAU_LDR_CA5_CA5) /*@}*/ /******************************************************************************* * HW_CAU_LDR_CA6 - General Purpose Register 6 - Load Register command ******************************************************************************/ /*! * @brief HW_CAU_LDR_CA6 - General Purpose Register 6 - Load Register command (WO) * * Reset value: 0x00000000U */ typedef union _hw_cau_ldr_ca6 { uint32_t U; struct _hw_cau_ldr_ca6_bitfields { uint32_t CA6 : 32; /*!< [31:0] CA6 */ } B; } hw_cau_ldr_ca6_t; /*! * @name Constants and macros for entire CAU_LDR_CA6 register */ /*@{*/ #define HW_CAU_LDR_CA6_ADDR(x) ((x) + 0x860U) #define HW_CAU_LDR_CA6(x) (*(__O hw_cau_ldr_ca6_t *) HW_CAU_LDR_CA6_ADDR(x)) #define HW_CAU_LDR_CA6_WR(x, v) (HW_CAU_LDR_CA6(x).U = (v)) /*@}*/ /* * Constants & macros for individual CAU_LDR_CA6 bitfields */ /*! * @name Register CAU_LDR_CA6, field CA6[31:0] (WO) */ /*@{*/ #define BP_CAU_LDR_CA6_CA6 (0U) /*!< Bit position for CAU_LDR_CA6_CA6. */ #define BM_CAU_LDR_CA6_CA6 (0xFFFFFFFFU) /*!< Bit mask for CAU_LDR_CA6_CA6. */ #define BS_CAU_LDR_CA6_CA6 (32U) /*!< Bit field size in bits for CAU_LDR_CA6_CA6. */ /*! @brief Format value for bitfield CAU_LDR_CA6_CA6. */ #define BF_CAU_LDR_CA6_CA6(v) ((uint32_t)((uint32_t)(v) << BP_CAU_LDR_CA6_CA6) & BM_CAU_LDR_CA6_CA6) /*@}*/ /******************************************************************************* * HW_CAU_LDR_CA7 - General Purpose Register 7 - Load Register command ******************************************************************************/ /*! * @brief HW_CAU_LDR_CA7 - General Purpose Register 7 - Load Register command (WO) * * Reset value: 0x00000000U */ typedef union _hw_cau_ldr_ca7 { uint32_t U; struct _hw_cau_ldr_ca7_bitfields { uint32_t CA7 : 32; /*!< [31:0] CA7 */ } B; } hw_cau_ldr_ca7_t; /*! * @name Constants and macros for entire CAU_LDR_CA7 register */ /*@{*/ #define HW_CAU_LDR_CA7_ADDR(x) ((x) + 0x864U) #define HW_CAU_LDR_CA7(x) (*(__O hw_cau_ldr_ca7_t *) HW_CAU_LDR_CA7_ADDR(x)) #define HW_CAU_LDR_CA7_WR(x, v) (HW_CAU_LDR_CA7(x).U = (v)) /*@}*/ /* * Constants & macros for individual CAU_LDR_CA7 bitfields */ /*! * @name Register CAU_LDR_CA7, field CA7[31:0] (WO) */ /*@{*/ #define BP_CAU_LDR_CA7_CA7 (0U) /*!< Bit position for CAU_LDR_CA7_CA7. */ #define BM_CAU_LDR_CA7_CA7 (0xFFFFFFFFU) /*!< Bit mask for CAU_LDR_CA7_CA7. */ #define BS_CAU_LDR_CA7_CA7 (32U) /*!< Bit field size in bits for CAU_LDR_CA7_CA7. */ /*! @brief Format value for bitfield CAU_LDR_CA7_CA7. */ #define BF_CAU_LDR_CA7_CA7(v) ((uint32_t)((uint32_t)(v) << BP_CAU_LDR_CA7_CA7) & BM_CAU_LDR_CA7_CA7) /*@}*/ /******************************************************************************* * HW_CAU_LDR_CA8 - General Purpose Register 8 - Load Register command ******************************************************************************/ /*! * @brief HW_CAU_LDR_CA8 - General Purpose Register 8 - Load Register command (WO) * * Reset value: 0x00000000U */ typedef union _hw_cau_ldr_ca8 { uint32_t U; struct _hw_cau_ldr_ca8_bitfields { uint32_t CA8 : 32; /*!< [31:0] CA8 */ } B; } hw_cau_ldr_ca8_t; /*! * @name Constants and macros for entire CAU_LDR_CA8 register */ /*@{*/ #define HW_CAU_LDR_CA8_ADDR(x) ((x) + 0x868U) #define HW_CAU_LDR_CA8(x) (*(__O hw_cau_ldr_ca8_t *) HW_CAU_LDR_CA8_ADDR(x)) #define HW_CAU_LDR_CA8_WR(x, v) (HW_CAU_LDR_CA8(x).U = (v)) /*@}*/ /* * Constants & macros for individual CAU_LDR_CA8 bitfields */ /*! * @name Register CAU_LDR_CA8, field CA8[31:0] (WO) */ /*@{*/ #define BP_CAU_LDR_CA8_CA8 (0U) /*!< Bit position for CAU_LDR_CA8_CA8. */ #define BM_CAU_LDR_CA8_CA8 (0xFFFFFFFFU) /*!< Bit mask for CAU_LDR_CA8_CA8. */ #define BS_CAU_LDR_CA8_CA8 (32U) /*!< Bit field size in bits for CAU_LDR_CA8_CA8. */ /*! @brief Format value for bitfield CAU_LDR_CA8_CA8. */ #define BF_CAU_LDR_CA8_CA8(v) ((uint32_t)((uint32_t)(v) << BP_CAU_LDR_CA8_CA8) & BM_CAU_LDR_CA8_CA8) /*@}*/ /******************************************************************************* * HW_CAU_STR_CASR - Status register - Store Register command ******************************************************************************/ /*! * @brief HW_CAU_STR_CASR - Status register - Store Register command (RO) * * Reset value: 0x20000000U */ typedef union _hw_cau_str_casr { uint32_t U; struct _hw_cau_str_casr_bitfields { uint32_t IC : 1; /*!< [0] */ uint32_t DPE : 1; /*!< [1] */ uint32_t RESERVED0 : 26; /*!< [27:2] */ uint32_t VER : 4; /*!< [31:28] CAU version */ } B; } hw_cau_str_casr_t; /*! * @name Constants and macros for entire CAU_STR_CASR register */ /*@{*/ #define HW_CAU_STR_CASR_ADDR(x) ((x) + 0x880U) #define HW_CAU_STR_CASR(x) (*(__I hw_cau_str_casr_t *) HW_CAU_STR_CASR_ADDR(x)) #define HW_CAU_STR_CASR_RD(x) (HW_CAU_STR_CASR(x).U) /*@}*/ /* * Constants & macros for individual CAU_STR_CASR bitfields */ /*! * @name Register CAU_STR_CASR, field IC[0] (RO) * * Values: * - 0 - No illegal commands issued * - 1 - Illegal command issued */ /*@{*/ #define BP_CAU_STR_CASR_IC (0U) /*!< Bit position for CAU_STR_CASR_IC. */ #define BM_CAU_STR_CASR_IC (0x00000001U) /*!< Bit mask for CAU_STR_CASR_IC. */ #define BS_CAU_STR_CASR_IC (1U) /*!< Bit field size in bits for CAU_STR_CASR_IC. */ /*! @brief Read current value of the CAU_STR_CASR_IC field. */ #define BR_CAU_STR_CASR_IC(x) (HW_CAU_STR_CASR(x).B.IC) /*@}*/ /*! * @name Register CAU_STR_CASR, field DPE[1] (RO) * * Values: * - 0 - No error detected * - 1 - DES key parity error detected */ /*@{*/ #define BP_CAU_STR_CASR_DPE (1U) /*!< Bit position for CAU_STR_CASR_DPE. */ #define BM_CAU_STR_CASR_DPE (0x00000002U) /*!< Bit mask for CAU_STR_CASR_DPE. */ #define BS_CAU_STR_CASR_DPE (1U) /*!< Bit field size in bits for CAU_STR_CASR_DPE. */ /*! @brief Read current value of the CAU_STR_CASR_DPE field. */ #define BR_CAU_STR_CASR_DPE(x) (HW_CAU_STR_CASR(x).B.DPE) /*@}*/ /*! * @name Register CAU_STR_CASR, field VER[31:28] (RO) * * Values: * - 0001 - Initial CAU version * - 0010 - Second version, added support for SHA-256 algorithm.(This is the * value on this device) */ /*@{*/ #define BP_CAU_STR_CASR_VER (28U) /*!< Bit position for CAU_STR_CASR_VER. */ #define BM_CAU_STR_CASR_VER (0xF0000000U) /*!< Bit mask for CAU_STR_CASR_VER. */ #define BS_CAU_STR_CASR_VER (4U) /*!< Bit field size in bits for CAU_STR_CASR_VER. */ /*! @brief Read current value of the CAU_STR_CASR_VER field. */ #define BR_CAU_STR_CASR_VER(x) (HW_CAU_STR_CASR(x).B.VER) /*@}*/ /******************************************************************************* * HW_CAU_STR_CAA - Accumulator register - Store Register command ******************************************************************************/ /*! * @brief HW_CAU_STR_CAA - Accumulator register - Store Register command (RO) * * Reset value: 0x00000000U */ typedef union _hw_cau_str_caa { uint32_t U; struct _hw_cau_str_caa_bitfields { uint32_t ACC : 32; /*!< [31:0] ACC */ } B; } hw_cau_str_caa_t; /*! * @name Constants and macros for entire CAU_STR_CAA register */ /*@{*/ #define HW_CAU_STR_CAA_ADDR(x) ((x) + 0x884U) #define HW_CAU_STR_CAA(x) (*(__I hw_cau_str_caa_t *) HW_CAU_STR_CAA_ADDR(x)) #define HW_CAU_STR_CAA_RD(x) (HW_CAU_STR_CAA(x).U) /*@}*/ /* * Constants & macros for individual CAU_STR_CAA bitfields */ /*! * @name Register CAU_STR_CAA, field ACC[31:0] (RO) */ /*@{*/ #define BP_CAU_STR_CAA_ACC (0U) /*!< Bit position for CAU_STR_CAA_ACC. */ #define BM_CAU_STR_CAA_ACC (0xFFFFFFFFU) /*!< Bit mask for CAU_STR_CAA_ACC. */ #define BS_CAU_STR_CAA_ACC (32U) /*!< Bit field size in bits for CAU_STR_CAA_ACC. */ /*! @brief Read current value of the CAU_STR_CAA_ACC field. */ #define BR_CAU_STR_CAA_ACC(x) (HW_CAU_STR_CAA(x).U) /*@}*/ /******************************************************************************* * HW_CAU_STR_CA0 - General Purpose Register 0 - Store Register command ******************************************************************************/ /*! * @brief HW_CAU_STR_CA0 - General Purpose Register 0 - Store Register command (RO) * * Reset value: 0x00000000U */ typedef union _hw_cau_str_ca0 { uint32_t U; struct _hw_cau_str_ca0_bitfields { uint32_t CA0 : 32; /*!< [31:0] CA0 */ } B; } hw_cau_str_ca0_t; /*! * @name Constants and macros for entire CAU_STR_CA0 register */ /*@{*/ #define HW_CAU_STR_CA0_ADDR(x) ((x) + 0x888U) #define HW_CAU_STR_CA0(x) (*(__I hw_cau_str_ca0_t *) HW_CAU_STR_CA0_ADDR(x)) #define HW_CAU_STR_CA0_RD(x) (HW_CAU_STR_CA0(x).U) /*@}*/ /* * Constants & macros for individual CAU_STR_CA0 bitfields */ /*! * @name Register CAU_STR_CA0, field CA0[31:0] (RO) */ /*@{*/ #define BP_CAU_STR_CA0_CA0 (0U) /*!< Bit position for CAU_STR_CA0_CA0. */ #define BM_CAU_STR_CA0_CA0 (0xFFFFFFFFU) /*!< Bit mask for CAU_STR_CA0_CA0. */ #define BS_CAU_STR_CA0_CA0 (32U) /*!< Bit field size in bits for CAU_STR_CA0_CA0. */ /*! @brief Read current value of the CAU_STR_CA0_CA0 field. */ #define BR_CAU_STR_CA0_CA0(x) (HW_CAU_STR_CA0(x).U) /*@}*/ /******************************************************************************* * HW_CAU_STR_CA1 - General Purpose Register 1 - Store Register command ******************************************************************************/ /*! * @brief HW_CAU_STR_CA1 - General Purpose Register 1 - Store Register command (RO) * * Reset value: 0x00000000U */ typedef union _hw_cau_str_ca1 { uint32_t U; struct _hw_cau_str_ca1_bitfields { uint32_t CA1 : 32; /*!< [31:0] CA1 */ } B; } hw_cau_str_ca1_t; /*! * @name Constants and macros for entire CAU_STR_CA1 register */ /*@{*/ #define HW_CAU_STR_CA1_ADDR(x) ((x) + 0x88CU) #define HW_CAU_STR_CA1(x) (*(__I hw_cau_str_ca1_t *) HW_CAU_STR_CA1_ADDR(x)) #define HW_CAU_STR_CA1_RD(x) (HW_CAU_STR_CA1(x).U) /*@}*/ /* * Constants & macros for individual CAU_STR_CA1 bitfields */ /*! * @name Register CAU_STR_CA1, field CA1[31:0] (RO) */ /*@{*/ #define BP_CAU_STR_CA1_CA1 (0U) /*!< Bit position for CAU_STR_CA1_CA1. */ #define BM_CAU_STR_CA1_CA1 (0xFFFFFFFFU) /*!< Bit mask for CAU_STR_CA1_CA1. */ #define BS_CAU_STR_CA1_CA1 (32U) /*!< Bit field size in bits for CAU_STR_CA1_CA1. */ /*! @brief Read current value of the CAU_STR_CA1_CA1 field. */ #define BR_CAU_STR_CA1_CA1(x) (HW_CAU_STR_CA1(x).U) /*@}*/ /******************************************************************************* * HW_CAU_STR_CA2 - General Purpose Register 2 - Store Register command ******************************************************************************/ /*! * @brief HW_CAU_STR_CA2 - General Purpose Register 2 - Store Register command (RO) * * Reset value: 0x00000000U */ typedef union _hw_cau_str_ca2 { uint32_t U; struct _hw_cau_str_ca2_bitfields { uint32_t CA2 : 32; /*!< [31:0] CA2 */ } B; } hw_cau_str_ca2_t; /*! * @name Constants and macros for entire CAU_STR_CA2 register */ /*@{*/ #define HW_CAU_STR_CA2_ADDR(x) ((x) + 0x890U) #define HW_CAU_STR_CA2(x) (*(__I hw_cau_str_ca2_t *) HW_CAU_STR_CA2_ADDR(x)) #define HW_CAU_STR_CA2_RD(x) (HW_CAU_STR_CA2(x).U) /*@}*/ /* * Constants & macros for individual CAU_STR_CA2 bitfields */ /*! * @name Register CAU_STR_CA2, field CA2[31:0] (RO) */ /*@{*/ #define BP_CAU_STR_CA2_CA2 (0U) /*!< Bit position for CAU_STR_CA2_CA2. */ #define BM_CAU_STR_CA2_CA2 (0xFFFFFFFFU) /*!< Bit mask for CAU_STR_CA2_CA2. */ #define BS_CAU_STR_CA2_CA2 (32U) /*!< Bit field size in bits for CAU_STR_CA2_CA2. */ /*! @brief Read current value of the CAU_STR_CA2_CA2 field. */ #define BR_CAU_STR_CA2_CA2(x) (HW_CAU_STR_CA2(x).U) /*@}*/ /******************************************************************************* * HW_CAU_STR_CA3 - General Purpose Register 3 - Store Register command ******************************************************************************/ /*! * @brief HW_CAU_STR_CA3 - General Purpose Register 3 - Store Register command (RO) * * Reset value: 0x00000000U */ typedef union _hw_cau_str_ca3 { uint32_t U; struct _hw_cau_str_ca3_bitfields { uint32_t CA3 : 32; /*!< [31:0] CA3 */ } B; } hw_cau_str_ca3_t; /*! * @name Constants and macros for entire CAU_STR_CA3 register */ /*@{*/ #define HW_CAU_STR_CA3_ADDR(x) ((x) + 0x894U) #define HW_CAU_STR_CA3(x) (*(__I hw_cau_str_ca3_t *) HW_CAU_STR_CA3_ADDR(x)) #define HW_CAU_STR_CA3_RD(x) (HW_CAU_STR_CA3(x).U) /*@}*/ /* * Constants & macros for individual CAU_STR_CA3 bitfields */ /*! * @name Register CAU_STR_CA3, field CA3[31:0] (RO) */ /*@{*/ #define BP_CAU_STR_CA3_CA3 (0U) /*!< Bit position for CAU_STR_CA3_CA3. */ #define BM_CAU_STR_CA3_CA3 (0xFFFFFFFFU) /*!< Bit mask for CAU_STR_CA3_CA3. */ #define BS_CAU_STR_CA3_CA3 (32U) /*!< Bit field size in bits for CAU_STR_CA3_CA3. */ /*! @brief Read current value of the CAU_STR_CA3_CA3 field. */ #define BR_CAU_STR_CA3_CA3(x) (HW_CAU_STR_CA3(x).U) /*@}*/ /******************************************************************************* * HW_CAU_STR_CA4 - General Purpose Register 4 - Store Register command ******************************************************************************/ /*! * @brief HW_CAU_STR_CA4 - General Purpose Register 4 - Store Register command (RO) * * Reset value: 0x00000000U */ typedef union _hw_cau_str_ca4 { uint32_t U; struct _hw_cau_str_ca4_bitfields { uint32_t CA4 : 32; /*!< [31:0] CA4 */ } B; } hw_cau_str_ca4_t; /*! * @name Constants and macros for entire CAU_STR_CA4 register */ /*@{*/ #define HW_CAU_STR_CA4_ADDR(x) ((x) + 0x898U) #define HW_CAU_STR_CA4(x) (*(__I hw_cau_str_ca4_t *) HW_CAU_STR_CA4_ADDR(x)) #define HW_CAU_STR_CA4_RD(x) (HW_CAU_STR_CA4(x).U) /*@}*/ /* * Constants & macros for individual CAU_STR_CA4 bitfields */ /*! * @name Register CAU_STR_CA4, field CA4[31:0] (RO) */ /*@{*/ #define BP_CAU_STR_CA4_CA4 (0U) /*!< Bit position for CAU_STR_CA4_CA4. */ #define BM_CAU_STR_CA4_CA4 (0xFFFFFFFFU) /*!< Bit mask for CAU_STR_CA4_CA4. */ #define BS_CAU_STR_CA4_CA4 (32U) /*!< Bit field size in bits for CAU_STR_CA4_CA4. */ /*! @brief Read current value of the CAU_STR_CA4_CA4 field. */ #define BR_CAU_STR_CA4_CA4(x) (HW_CAU_STR_CA4(x).U) /*@}*/ /******************************************************************************* * HW_CAU_STR_CA5 - General Purpose Register 5 - Store Register command ******************************************************************************/ /*! * @brief HW_CAU_STR_CA5 - General Purpose Register 5 - Store Register command (RO) * * Reset value: 0x00000000U */ typedef union _hw_cau_str_ca5 { uint32_t U; struct _hw_cau_str_ca5_bitfields { uint32_t CA5 : 32; /*!< [31:0] CA5 */ } B; } hw_cau_str_ca5_t; /*! * @name Constants and macros for entire CAU_STR_CA5 register */ /*@{*/ #define HW_CAU_STR_CA5_ADDR(x) ((x) + 0x89CU) #define HW_CAU_STR_CA5(x) (*(__I hw_cau_str_ca5_t *) HW_CAU_STR_CA5_ADDR(x)) #define HW_CAU_STR_CA5_RD(x) (HW_CAU_STR_CA5(x).U) /*@}*/ /* * Constants & macros for individual CAU_STR_CA5 bitfields */ /*! * @name Register CAU_STR_CA5, field CA5[31:0] (RO) */ /*@{*/ #define BP_CAU_STR_CA5_CA5 (0U) /*!< Bit position for CAU_STR_CA5_CA5. */ #define BM_CAU_STR_CA5_CA5 (0xFFFFFFFFU) /*!< Bit mask for CAU_STR_CA5_CA5. */ #define BS_CAU_STR_CA5_CA5 (32U) /*!< Bit field size in bits for CAU_STR_CA5_CA5. */ /*! @brief Read current value of the CAU_STR_CA5_CA5 field. */ #define BR_CAU_STR_CA5_CA5(x) (HW_CAU_STR_CA5(x).U) /*@}*/ /******************************************************************************* * HW_CAU_STR_CA6 - General Purpose Register 6 - Store Register command ******************************************************************************/ /*! * @brief HW_CAU_STR_CA6 - General Purpose Register 6 - Store Register command (RO) * * Reset value: 0x00000000U */ typedef union _hw_cau_str_ca6 { uint32_t U; struct _hw_cau_str_ca6_bitfields { uint32_t CA6 : 32; /*!< [31:0] CA6 */ } B; } hw_cau_str_ca6_t; /*! * @name Constants and macros for entire CAU_STR_CA6 register */ /*@{*/ #define HW_CAU_STR_CA6_ADDR(x) ((x) + 0x8A0U) #define HW_CAU_STR_CA6(x) (*(__I hw_cau_str_ca6_t *) HW_CAU_STR_CA6_ADDR(x)) #define HW_CAU_STR_CA6_RD(x) (HW_CAU_STR_CA6(x).U) /*@}*/ /* * Constants & macros for individual CAU_STR_CA6 bitfields */ /*! * @name Register CAU_STR_CA6, field CA6[31:0] (RO) */ /*@{*/ #define BP_CAU_STR_CA6_CA6 (0U) /*!< Bit position for CAU_STR_CA6_CA6. */ #define BM_CAU_STR_CA6_CA6 (0xFFFFFFFFU) /*!< Bit mask for CAU_STR_CA6_CA6. */ #define BS_CAU_STR_CA6_CA6 (32U) /*!< Bit field size in bits for CAU_STR_CA6_CA6. */ /*! @brief Read current value of the CAU_STR_CA6_CA6 field. */ #define BR_CAU_STR_CA6_CA6(x) (HW_CAU_STR_CA6(x).U) /*@}*/ /******************************************************************************* * HW_CAU_STR_CA7 - General Purpose Register 7 - Store Register command ******************************************************************************/ /*! * @brief HW_CAU_STR_CA7 - General Purpose Register 7 - Store Register command (RO) * * Reset value: 0x00000000U */ typedef union _hw_cau_str_ca7 { uint32_t U; struct _hw_cau_str_ca7_bitfields { uint32_t CA7 : 32; /*!< [31:0] CA7 */ } B; } hw_cau_str_ca7_t; /*! * @name Constants and macros for entire CAU_STR_CA7 register */ /*@{*/ #define HW_CAU_STR_CA7_ADDR(x) ((x) + 0x8A4U) #define HW_CAU_STR_CA7(x) (*(__I hw_cau_str_ca7_t *) HW_CAU_STR_CA7_ADDR(x)) #define HW_CAU_STR_CA7_RD(x) (HW_CAU_STR_CA7(x).U) /*@}*/ /* * Constants & macros for individual CAU_STR_CA7 bitfields */ /*! * @name Register CAU_STR_CA7, field CA7[31:0] (RO) */ /*@{*/ #define BP_CAU_STR_CA7_CA7 (0U) /*!< Bit position for CAU_STR_CA7_CA7. */ #define BM_CAU_STR_CA7_CA7 (0xFFFFFFFFU) /*!< Bit mask for CAU_STR_CA7_CA7. */ #define BS_CAU_STR_CA7_CA7 (32U) /*!< Bit field size in bits for CAU_STR_CA7_CA7. */ /*! @brief Read current value of the CAU_STR_CA7_CA7 field. */ #define BR_CAU_STR_CA7_CA7(x) (HW_CAU_STR_CA7(x).U) /*@}*/ /******************************************************************************* * HW_CAU_STR_CA8 - General Purpose Register 8 - Store Register command ******************************************************************************/ /*! * @brief HW_CAU_STR_CA8 - General Purpose Register 8 - Store Register command (RO) * * Reset value: 0x00000000U */ typedef union _hw_cau_str_ca8 { uint32_t U; struct _hw_cau_str_ca8_bitfields { uint32_t CA8 : 32; /*!< [31:0] CA8 */ } B; } hw_cau_str_ca8_t; /*! * @name Constants and macros for entire CAU_STR_CA8 register */ /*@{*/ #define HW_CAU_STR_CA8_ADDR(x) ((x) + 0x8A8U) #define HW_CAU_STR_CA8(x) (*(__I hw_cau_str_ca8_t *) HW_CAU_STR_CA8_ADDR(x)) #define HW_CAU_STR_CA8_RD(x) (HW_CAU_STR_CA8(x).U) /*@}*/ /* * Constants & macros for individual CAU_STR_CA8 bitfields */ /*! * @name Register CAU_STR_CA8, field CA8[31:0] (RO) */ /*@{*/ #define BP_CAU_STR_CA8_CA8 (0U) /*!< Bit position for CAU_STR_CA8_CA8. */ #define BM_CAU_STR_CA8_CA8 (0xFFFFFFFFU) /*!< Bit mask for CAU_STR_CA8_CA8. */ #define BS_CAU_STR_CA8_CA8 (32U) /*!< Bit field size in bits for CAU_STR_CA8_CA8. */ /*! @brief Read current value of the CAU_STR_CA8_CA8 field. */ #define BR_CAU_STR_CA8_CA8(x) (HW_CAU_STR_CA8(x).U) /*@}*/ /******************************************************************************* * HW_CAU_ADR_CASR - Status register - Add Register command ******************************************************************************/ /*! * @brief HW_CAU_ADR_CASR - Status register - Add Register command (WO) * * Reset value: 0x20000000U */ typedef union _hw_cau_adr_casr { uint32_t U; struct _hw_cau_adr_casr_bitfields { uint32_t IC : 1; /*!< [0] */ uint32_t DPE : 1; /*!< [1] */ uint32_t RESERVED0 : 26; /*!< [27:2] */ uint32_t VER : 4; /*!< [31:28] CAU version */ } B; } hw_cau_adr_casr_t; /*! * @name Constants and macros for entire CAU_ADR_CASR register */ /*@{*/ #define HW_CAU_ADR_CASR_ADDR(x) ((x) + 0x8C0U) #define HW_CAU_ADR_CASR(x) (*(__O hw_cau_adr_casr_t *) HW_CAU_ADR_CASR_ADDR(x)) #define HW_CAU_ADR_CASR_WR(x, v) (HW_CAU_ADR_CASR(x).U = (v)) /*@}*/ /* * Constants & macros for individual CAU_ADR_CASR bitfields */ /*! * @name Register CAU_ADR_CASR, field IC[0] (WO) * * Values: * - 0 - No illegal commands issued * - 1 - Illegal command issued */ /*@{*/ #define BP_CAU_ADR_CASR_IC (0U) /*!< Bit position for CAU_ADR_CASR_IC. */ #define BM_CAU_ADR_CASR_IC (0x00000001U) /*!< Bit mask for CAU_ADR_CASR_IC. */ #define BS_CAU_ADR_CASR_IC (1U) /*!< Bit field size in bits for CAU_ADR_CASR_IC. */ /*! @brief Format value for bitfield CAU_ADR_CASR_IC. */ #define BF_CAU_ADR_CASR_IC(v) ((uint32_t)((uint32_t)(v) << BP_CAU_ADR_CASR_IC) & BM_CAU_ADR_CASR_IC) /*@}*/ /*! * @name Register CAU_ADR_CASR, field DPE[1] (WO) * * Values: * - 0 - No error detected * - 1 - DES key parity error detected */ /*@{*/ #define BP_CAU_ADR_CASR_DPE (1U) /*!< Bit position for CAU_ADR_CASR_DPE. */ #define BM_CAU_ADR_CASR_DPE (0x00000002U) /*!< Bit mask for CAU_ADR_CASR_DPE. */ #define BS_CAU_ADR_CASR_DPE (1U) /*!< Bit field size in bits for CAU_ADR_CASR_DPE. */ /*! @brief Format value for bitfield CAU_ADR_CASR_DPE. */ #define BF_CAU_ADR_CASR_DPE(v) ((uint32_t)((uint32_t)(v) << BP_CAU_ADR_CASR_DPE) & BM_CAU_ADR_CASR_DPE) /*@}*/ /*! * @name Register CAU_ADR_CASR, field VER[31:28] (WO) * * Values: * - 0001 - Initial CAU version * - 0010 - Second version, added support for SHA-256 algorithm.(This is the * value on this device) */ /*@{*/ #define BP_CAU_ADR_CASR_VER (28U) /*!< Bit position for CAU_ADR_CASR_VER. */ #define BM_CAU_ADR_CASR_VER (0xF0000000U) /*!< Bit mask for CAU_ADR_CASR_VER. */ #define BS_CAU_ADR_CASR_VER (4U) /*!< Bit field size in bits for CAU_ADR_CASR_VER. */ /*! @brief Format value for bitfield CAU_ADR_CASR_VER. */ #define BF_CAU_ADR_CASR_VER(v) ((uint32_t)((uint32_t)(v) << BP_CAU_ADR_CASR_VER) & BM_CAU_ADR_CASR_VER) /*@}*/ /******************************************************************************* * HW_CAU_ADR_CAA - Accumulator register - Add to register command ******************************************************************************/ /*! * @brief HW_CAU_ADR_CAA - Accumulator register - Add to register command (WO) * * Reset value: 0x00000000U */ typedef union _hw_cau_adr_caa { uint32_t U; struct _hw_cau_adr_caa_bitfields { uint32_t ACC : 32; /*!< [31:0] ACC */ } B; } hw_cau_adr_caa_t; /*! * @name Constants and macros for entire CAU_ADR_CAA register */ /*@{*/ #define HW_CAU_ADR_CAA_ADDR(x) ((x) + 0x8C4U) #define HW_CAU_ADR_CAA(x) (*(__O hw_cau_adr_caa_t *) HW_CAU_ADR_CAA_ADDR(x)) #define HW_CAU_ADR_CAA_WR(x, v) (HW_CAU_ADR_CAA(x).U = (v)) /*@}*/ /* * Constants & macros for individual CAU_ADR_CAA bitfields */ /*! * @name Register CAU_ADR_CAA, field ACC[31:0] (WO) */ /*@{*/ #define BP_CAU_ADR_CAA_ACC (0U) /*!< Bit position for CAU_ADR_CAA_ACC. */ #define BM_CAU_ADR_CAA_ACC (0xFFFFFFFFU) /*!< Bit mask for CAU_ADR_CAA_ACC. */ #define BS_CAU_ADR_CAA_ACC (32U) /*!< Bit field size in bits for CAU_ADR_CAA_ACC. */ /*! @brief Format value for bitfield CAU_ADR_CAA_ACC. */ #define BF_CAU_ADR_CAA_ACC(v) ((uint32_t)((uint32_t)(v) << BP_CAU_ADR_CAA_ACC) & BM_CAU_ADR_CAA_ACC) /*@}*/ /******************************************************************************* * HW_CAU_ADR_CA0 - General Purpose Register 0 - Add to register command ******************************************************************************/ /*! * @brief HW_CAU_ADR_CA0 - General Purpose Register 0 - Add to register command (WO) * * Reset value: 0x00000000U */ typedef union _hw_cau_adr_ca0 { uint32_t U; struct _hw_cau_adr_ca0_bitfields { uint32_t CA0 : 32; /*!< [31:0] CA0 */ } B; } hw_cau_adr_ca0_t; /*! * @name Constants and macros for entire CAU_ADR_CA0 register */ /*@{*/ #define HW_CAU_ADR_CA0_ADDR(x) ((x) + 0x8C8U) #define HW_CAU_ADR_CA0(x) (*(__O hw_cau_adr_ca0_t *) HW_CAU_ADR_CA0_ADDR(x)) #define HW_CAU_ADR_CA0_WR(x, v) (HW_CAU_ADR_CA0(x).U = (v)) /*@}*/ /* * Constants & macros for individual CAU_ADR_CA0 bitfields */ /*! * @name Register CAU_ADR_CA0, field CA0[31:0] (WO) */ /*@{*/ #define BP_CAU_ADR_CA0_CA0 (0U) /*!< Bit position for CAU_ADR_CA0_CA0. */ #define BM_CAU_ADR_CA0_CA0 (0xFFFFFFFFU) /*!< Bit mask for CAU_ADR_CA0_CA0. */ #define BS_CAU_ADR_CA0_CA0 (32U) /*!< Bit field size in bits for CAU_ADR_CA0_CA0. */ /*! @brief Format value for bitfield CAU_ADR_CA0_CA0. */ #define BF_CAU_ADR_CA0_CA0(v) ((uint32_t)((uint32_t)(v) << BP_CAU_ADR_CA0_CA0) & BM_CAU_ADR_CA0_CA0) /*@}*/ /******************************************************************************* * HW_CAU_ADR_CA1 - General Purpose Register 1 - Add to register command ******************************************************************************/ /*! * @brief HW_CAU_ADR_CA1 - General Purpose Register 1 - Add to register command (WO) * * Reset value: 0x00000000U */ typedef union _hw_cau_adr_ca1 { uint32_t U; struct _hw_cau_adr_ca1_bitfields { uint32_t CA1 : 32; /*!< [31:0] CA1 */ } B; } hw_cau_adr_ca1_t; /*! * @name Constants and macros for entire CAU_ADR_CA1 register */ /*@{*/ #define HW_CAU_ADR_CA1_ADDR(x) ((x) + 0x8CCU) #define HW_CAU_ADR_CA1(x) (*(__O hw_cau_adr_ca1_t *) HW_CAU_ADR_CA1_ADDR(x)) #define HW_CAU_ADR_CA1_WR(x, v) (HW_CAU_ADR_CA1(x).U = (v)) /*@}*/ /* * Constants & macros for individual CAU_ADR_CA1 bitfields */ /*! * @name Register CAU_ADR_CA1, field CA1[31:0] (WO) */ /*@{*/ #define BP_CAU_ADR_CA1_CA1 (0U) /*!< Bit position for CAU_ADR_CA1_CA1. */ #define BM_CAU_ADR_CA1_CA1 (0xFFFFFFFFU) /*!< Bit mask for CAU_ADR_CA1_CA1. */ #define BS_CAU_ADR_CA1_CA1 (32U) /*!< Bit field size in bits for CAU_ADR_CA1_CA1. */ /*! @brief Format value for bitfield CAU_ADR_CA1_CA1. */ #define BF_CAU_ADR_CA1_CA1(v) ((uint32_t)((uint32_t)(v) << BP_CAU_ADR_CA1_CA1) & BM_CAU_ADR_CA1_CA1) /*@}*/ /******************************************************************************* * HW_CAU_ADR_CA2 - General Purpose Register 2 - Add to register command ******************************************************************************/ /*! * @brief HW_CAU_ADR_CA2 - General Purpose Register 2 - Add to register command (WO) * * Reset value: 0x00000000U */ typedef union _hw_cau_adr_ca2 { uint32_t U; struct _hw_cau_adr_ca2_bitfields { uint32_t CA2 : 32; /*!< [31:0] CA2 */ } B; } hw_cau_adr_ca2_t; /*! * @name Constants and macros for entire CAU_ADR_CA2 register */ /*@{*/ #define HW_CAU_ADR_CA2_ADDR(x) ((x) + 0x8D0U) #define HW_CAU_ADR_CA2(x) (*(__O hw_cau_adr_ca2_t *) HW_CAU_ADR_CA2_ADDR(x)) #define HW_CAU_ADR_CA2_WR(x, v) (HW_CAU_ADR_CA2(x).U = (v)) /*@}*/ /* * Constants & macros for individual CAU_ADR_CA2 bitfields */ /*! * @name Register CAU_ADR_CA2, field CA2[31:0] (WO) */ /*@{*/ #define BP_CAU_ADR_CA2_CA2 (0U) /*!< Bit position for CAU_ADR_CA2_CA2. */ #define BM_CAU_ADR_CA2_CA2 (0xFFFFFFFFU) /*!< Bit mask for CAU_ADR_CA2_CA2. */ #define BS_CAU_ADR_CA2_CA2 (32U) /*!< Bit field size in bits for CAU_ADR_CA2_CA2. */ /*! @brief Format value for bitfield CAU_ADR_CA2_CA2. */ #define BF_CAU_ADR_CA2_CA2(v) ((uint32_t)((uint32_t)(v) << BP_CAU_ADR_CA2_CA2) & BM_CAU_ADR_CA2_CA2) /*@}*/ /******************************************************************************* * HW_CAU_ADR_CA3 - General Purpose Register 3 - Add to register command ******************************************************************************/ /*! * @brief HW_CAU_ADR_CA3 - General Purpose Register 3 - Add to register command (WO) * * Reset value: 0x00000000U */ typedef union _hw_cau_adr_ca3 { uint32_t U; struct _hw_cau_adr_ca3_bitfields { uint32_t CA3 : 32; /*!< [31:0] CA3 */ } B; } hw_cau_adr_ca3_t; /*! * @name Constants and macros for entire CAU_ADR_CA3 register */ /*@{*/ #define HW_CAU_ADR_CA3_ADDR(x) ((x) + 0x8D4U) #define HW_CAU_ADR_CA3(x) (*(__O hw_cau_adr_ca3_t *) HW_CAU_ADR_CA3_ADDR(x)) #define HW_CAU_ADR_CA3_WR(x, v) (HW_CAU_ADR_CA3(x).U = (v)) /*@}*/ /* * Constants & macros for individual CAU_ADR_CA3 bitfields */ /*! * @name Register CAU_ADR_CA3, field CA3[31:0] (WO) */ /*@{*/ #define BP_CAU_ADR_CA3_CA3 (0U) /*!< Bit position for CAU_ADR_CA3_CA3. */ #define BM_CAU_ADR_CA3_CA3 (0xFFFFFFFFU) /*!< Bit mask for CAU_ADR_CA3_CA3. */ #define BS_CAU_ADR_CA3_CA3 (32U) /*!< Bit field size in bits for CAU_ADR_CA3_CA3. */ /*! @brief Format value for bitfield CAU_ADR_CA3_CA3. */ #define BF_CAU_ADR_CA3_CA3(v) ((uint32_t)((uint32_t)(v) << BP_CAU_ADR_CA3_CA3) & BM_CAU_ADR_CA3_CA3) /*@}*/ /******************************************************************************* * HW_CAU_ADR_CA4 - General Purpose Register 4 - Add to register command ******************************************************************************/ /*! * @brief HW_CAU_ADR_CA4 - General Purpose Register 4 - Add to register command (WO) * * Reset value: 0x00000000U */ typedef union _hw_cau_adr_ca4 { uint32_t U; struct _hw_cau_adr_ca4_bitfields { uint32_t CA4 : 32; /*!< [31:0] CA4 */ } B; } hw_cau_adr_ca4_t; /*! * @name Constants and macros for entire CAU_ADR_CA4 register */ /*@{*/ #define HW_CAU_ADR_CA4_ADDR(x) ((x) + 0x8D8U) #define HW_CAU_ADR_CA4(x) (*(__O hw_cau_adr_ca4_t *) HW_CAU_ADR_CA4_ADDR(x)) #define HW_CAU_ADR_CA4_WR(x, v) (HW_CAU_ADR_CA4(x).U = (v)) /*@}*/ /* * Constants & macros for individual CAU_ADR_CA4 bitfields */ /*! * @name Register CAU_ADR_CA4, field CA4[31:0] (WO) */ /*@{*/ #define BP_CAU_ADR_CA4_CA4 (0U) /*!< Bit position for CAU_ADR_CA4_CA4. */ #define BM_CAU_ADR_CA4_CA4 (0xFFFFFFFFU) /*!< Bit mask for CAU_ADR_CA4_CA4. */ #define BS_CAU_ADR_CA4_CA4 (32U) /*!< Bit field size in bits for CAU_ADR_CA4_CA4. */ /*! @brief Format value for bitfield CAU_ADR_CA4_CA4. */ #define BF_CAU_ADR_CA4_CA4(v) ((uint32_t)((uint32_t)(v) << BP_CAU_ADR_CA4_CA4) & BM_CAU_ADR_CA4_CA4) /*@}*/ /******************************************************************************* * HW_CAU_ADR_CA5 - General Purpose Register 5 - Add to register command ******************************************************************************/ /*! * @brief HW_CAU_ADR_CA5 - General Purpose Register 5 - Add to register command (WO) * * Reset value: 0x00000000U */ typedef union _hw_cau_adr_ca5 { uint32_t U; struct _hw_cau_adr_ca5_bitfields { uint32_t CA5 : 32; /*!< [31:0] CA5 */ } B; } hw_cau_adr_ca5_t; /*! * @name Constants and macros for entire CAU_ADR_CA5 register */ /*@{*/ #define HW_CAU_ADR_CA5_ADDR(x) ((x) + 0x8DCU) #define HW_CAU_ADR_CA5(x) (*(__O hw_cau_adr_ca5_t *) HW_CAU_ADR_CA5_ADDR(x)) #define HW_CAU_ADR_CA5_WR(x, v) (HW_CAU_ADR_CA5(x).U = (v)) /*@}*/ /* * Constants & macros for individual CAU_ADR_CA5 bitfields */ /*! * @name Register CAU_ADR_CA5, field CA5[31:0] (WO) */ /*@{*/ #define BP_CAU_ADR_CA5_CA5 (0U) /*!< Bit position for CAU_ADR_CA5_CA5. */ #define BM_CAU_ADR_CA5_CA5 (0xFFFFFFFFU) /*!< Bit mask for CAU_ADR_CA5_CA5. */ #define BS_CAU_ADR_CA5_CA5 (32U) /*!< Bit field size in bits for CAU_ADR_CA5_CA5. */ /*! @brief Format value for bitfield CAU_ADR_CA5_CA5. */ #define BF_CAU_ADR_CA5_CA5(v) ((uint32_t)((uint32_t)(v) << BP_CAU_ADR_CA5_CA5) & BM_CAU_ADR_CA5_CA5) /*@}*/ /******************************************************************************* * HW_CAU_ADR_CA6 - General Purpose Register 6 - Add to register command ******************************************************************************/ /*! * @brief HW_CAU_ADR_CA6 - General Purpose Register 6 - Add to register command (WO) * * Reset value: 0x00000000U */ typedef union _hw_cau_adr_ca6 { uint32_t U; struct _hw_cau_adr_ca6_bitfields { uint32_t CA6 : 32; /*!< [31:0] CA6 */ } B; } hw_cau_adr_ca6_t; /*! * @name Constants and macros for entire CAU_ADR_CA6 register */ /*@{*/ #define HW_CAU_ADR_CA6_ADDR(x) ((x) + 0x8E0U) #define HW_CAU_ADR_CA6(x) (*(__O hw_cau_adr_ca6_t *) HW_CAU_ADR_CA6_ADDR(x)) #define HW_CAU_ADR_CA6_WR(x, v) (HW_CAU_ADR_CA6(x).U = (v)) /*@}*/ /* * Constants & macros for individual CAU_ADR_CA6 bitfields */ /*! * @name Register CAU_ADR_CA6, field CA6[31:0] (WO) */ /*@{*/ #define BP_CAU_ADR_CA6_CA6 (0U) /*!< Bit position for CAU_ADR_CA6_CA6. */ #define BM_CAU_ADR_CA6_CA6 (0xFFFFFFFFU) /*!< Bit mask for CAU_ADR_CA6_CA6. */ #define BS_CAU_ADR_CA6_CA6 (32U) /*!< Bit field size in bits for CAU_ADR_CA6_CA6. */ /*! @brief Format value for bitfield CAU_ADR_CA6_CA6. */ #define BF_CAU_ADR_CA6_CA6(v) ((uint32_t)((uint32_t)(v) << BP_CAU_ADR_CA6_CA6) & BM_CAU_ADR_CA6_CA6) /*@}*/ /******************************************************************************* * HW_CAU_ADR_CA7 - General Purpose Register 7 - Add to register command ******************************************************************************/ /*! * @brief HW_CAU_ADR_CA7 - General Purpose Register 7 - Add to register command (WO) * * Reset value: 0x00000000U */ typedef union _hw_cau_adr_ca7 { uint32_t U; struct _hw_cau_adr_ca7_bitfields { uint32_t CA7 : 32; /*!< [31:0] CA7 */ } B; } hw_cau_adr_ca7_t; /*! * @name Constants and macros for entire CAU_ADR_CA7 register */ /*@{*/ #define HW_CAU_ADR_CA7_ADDR(x) ((x) + 0x8E4U) #define HW_CAU_ADR_CA7(x) (*(__O hw_cau_adr_ca7_t *) HW_CAU_ADR_CA7_ADDR(x)) #define HW_CAU_ADR_CA7_WR(x, v) (HW_CAU_ADR_CA7(x).U = (v)) /*@}*/ /* * Constants & macros for individual CAU_ADR_CA7 bitfields */ /*! * @name Register CAU_ADR_CA7, field CA7[31:0] (WO) */ /*@{*/ #define BP_CAU_ADR_CA7_CA7 (0U) /*!< Bit position for CAU_ADR_CA7_CA7. */ #define BM_CAU_ADR_CA7_CA7 (0xFFFFFFFFU) /*!< Bit mask for CAU_ADR_CA7_CA7. */ #define BS_CAU_ADR_CA7_CA7 (32U) /*!< Bit field size in bits for CAU_ADR_CA7_CA7. */ /*! @brief Format value for bitfield CAU_ADR_CA7_CA7. */ #define BF_CAU_ADR_CA7_CA7(v) ((uint32_t)((uint32_t)(v) << BP_CAU_ADR_CA7_CA7) & BM_CAU_ADR_CA7_CA7) /*@}*/ /******************************************************************************* * HW_CAU_ADR_CA8 - General Purpose Register 8 - Add to register command ******************************************************************************/ /*! * @brief HW_CAU_ADR_CA8 - General Purpose Register 8 - Add to register command (WO) * * Reset value: 0x00000000U */ typedef union _hw_cau_adr_ca8 { uint32_t U; struct _hw_cau_adr_ca8_bitfields { uint32_t CA8 : 32; /*!< [31:0] CA8 */ } B; } hw_cau_adr_ca8_t; /*! * @name Constants and macros for entire CAU_ADR_CA8 register */ /*@{*/ #define HW_CAU_ADR_CA8_ADDR(x) ((x) + 0x8E8U) #define HW_CAU_ADR_CA8(x) (*(__O hw_cau_adr_ca8_t *) HW_CAU_ADR_CA8_ADDR(x)) #define HW_CAU_ADR_CA8_WR(x, v) (HW_CAU_ADR_CA8(x).U = (v)) /*@}*/ /* * Constants & macros for individual CAU_ADR_CA8 bitfields */ /*! * @name Register CAU_ADR_CA8, field CA8[31:0] (WO) */ /*@{*/ #define BP_CAU_ADR_CA8_CA8 (0U) /*!< Bit position for CAU_ADR_CA8_CA8. */ #define BM_CAU_ADR_CA8_CA8 (0xFFFFFFFFU) /*!< Bit mask for CAU_ADR_CA8_CA8. */ #define BS_CAU_ADR_CA8_CA8 (32U) /*!< Bit field size in bits for CAU_ADR_CA8_CA8. */ /*! @brief Format value for bitfield CAU_ADR_CA8_CA8. */ #define BF_CAU_ADR_CA8_CA8(v) ((uint32_t)((uint32_t)(v) << BP_CAU_ADR_CA8_CA8) & BM_CAU_ADR_CA8_CA8) /*@}*/ /******************************************************************************* * HW_CAU_RADR_CASR - Status register - Reverse and Add to Register command ******************************************************************************/ /*! * @brief HW_CAU_RADR_CASR - Status register - Reverse and Add to Register command (WO) * * Reset value: 0x20000000U */ typedef union _hw_cau_radr_casr { uint32_t U; struct _hw_cau_radr_casr_bitfields { uint32_t IC : 1; /*!< [0] */ uint32_t DPE : 1; /*!< [1] */ uint32_t RESERVED0 : 26; /*!< [27:2] */ uint32_t VER : 4; /*!< [31:28] CAU version */ } B; } hw_cau_radr_casr_t; /*! * @name Constants and macros for entire CAU_RADR_CASR register */ /*@{*/ #define HW_CAU_RADR_CASR_ADDR(x) ((x) + 0x900U) #define HW_CAU_RADR_CASR(x) (*(__O hw_cau_radr_casr_t *) HW_CAU_RADR_CASR_ADDR(x)) #define HW_CAU_RADR_CASR_WR(x, v) (HW_CAU_RADR_CASR(x).U = (v)) /*@}*/ /* * Constants & macros for individual CAU_RADR_CASR bitfields */ /*! * @name Register CAU_RADR_CASR, field IC[0] (WO) * * Values: * - 0 - No illegal commands issued * - 1 - Illegal command issued */ /*@{*/ #define BP_CAU_RADR_CASR_IC (0U) /*!< Bit position for CAU_RADR_CASR_IC. */ #define BM_CAU_RADR_CASR_IC (0x00000001U) /*!< Bit mask for CAU_RADR_CASR_IC. */ #define BS_CAU_RADR_CASR_IC (1U) /*!< Bit field size in bits for CAU_RADR_CASR_IC. */ /*! @brief Format value for bitfield CAU_RADR_CASR_IC. */ #define BF_CAU_RADR_CASR_IC(v) ((uint32_t)((uint32_t)(v) << BP_CAU_RADR_CASR_IC) & BM_CAU_RADR_CASR_IC) /*@}*/ /*! * @name Register CAU_RADR_CASR, field DPE[1] (WO) * * Values: * - 0 - No error detected * - 1 - DES key parity error detected */ /*@{*/ #define BP_CAU_RADR_CASR_DPE (1U) /*!< Bit position for CAU_RADR_CASR_DPE. */ #define BM_CAU_RADR_CASR_DPE (0x00000002U) /*!< Bit mask for CAU_RADR_CASR_DPE. */ #define BS_CAU_RADR_CASR_DPE (1U) /*!< Bit field size in bits for CAU_RADR_CASR_DPE. */ /*! @brief Format value for bitfield CAU_RADR_CASR_DPE. */ #define BF_CAU_RADR_CASR_DPE(v) ((uint32_t)((uint32_t)(v) << BP_CAU_RADR_CASR_DPE) & BM_CAU_RADR_CASR_DPE) /*@}*/ /*! * @name Register CAU_RADR_CASR, field VER[31:28] (WO) * * Values: * - 0001 - Initial CAU version * - 0010 - Second version, added support for SHA-256 algorithm.(This is the * value on this device) */ /*@{*/ #define BP_CAU_RADR_CASR_VER (28U) /*!< Bit position for CAU_RADR_CASR_VER. */ #define BM_CAU_RADR_CASR_VER (0xF0000000U) /*!< Bit mask for CAU_RADR_CASR_VER. */ #define BS_CAU_RADR_CASR_VER (4U) /*!< Bit field size in bits for CAU_RADR_CASR_VER. */ /*! @brief Format value for bitfield CAU_RADR_CASR_VER. */ #define BF_CAU_RADR_CASR_VER(v) ((uint32_t)((uint32_t)(v) << BP_CAU_RADR_CASR_VER) & BM_CAU_RADR_CASR_VER) /*@}*/ /******************************************************************************* * HW_CAU_RADR_CAA - Accumulator register - Reverse and Add to Register command ******************************************************************************/ /*! * @brief HW_CAU_RADR_CAA - Accumulator register - Reverse and Add to Register command (WO) * * Reset value: 0x00000000U */ typedef union _hw_cau_radr_caa { uint32_t U; struct _hw_cau_radr_caa_bitfields { uint32_t ACC : 32; /*!< [31:0] ACC */ } B; } hw_cau_radr_caa_t; /*! * @name Constants and macros for entire CAU_RADR_CAA register */ /*@{*/ #define HW_CAU_RADR_CAA_ADDR(x) ((x) + 0x904U) #define HW_CAU_RADR_CAA(x) (*(__O hw_cau_radr_caa_t *) HW_CAU_RADR_CAA_ADDR(x)) #define HW_CAU_RADR_CAA_WR(x, v) (HW_CAU_RADR_CAA(x).U = (v)) /*@}*/ /* * Constants & macros for individual CAU_RADR_CAA bitfields */ /*! * @name Register CAU_RADR_CAA, field ACC[31:0] (WO) */ /*@{*/ #define BP_CAU_RADR_CAA_ACC (0U) /*!< Bit position for CAU_RADR_CAA_ACC. */ #define BM_CAU_RADR_CAA_ACC (0xFFFFFFFFU) /*!< Bit mask for CAU_RADR_CAA_ACC. */ #define BS_CAU_RADR_CAA_ACC (32U) /*!< Bit field size in bits for CAU_RADR_CAA_ACC. */ /*! @brief Format value for bitfield CAU_RADR_CAA_ACC. */ #define BF_CAU_RADR_CAA_ACC(v) ((uint32_t)((uint32_t)(v) << BP_CAU_RADR_CAA_ACC) & BM_CAU_RADR_CAA_ACC) /*@}*/ /******************************************************************************* * HW_CAU_RADR_CA0 - General Purpose Register 0 - Reverse and Add to Register command ******************************************************************************/ /*! * @brief HW_CAU_RADR_CA0 - General Purpose Register 0 - Reverse and Add to Register command (WO) * * Reset value: 0x00000000U */ typedef union _hw_cau_radr_ca0 { uint32_t U; struct _hw_cau_radr_ca0_bitfields { uint32_t CA0 : 32; /*!< [31:0] CA0 */ } B; } hw_cau_radr_ca0_t; /*! * @name Constants and macros for entire CAU_RADR_CA0 register */ /*@{*/ #define HW_CAU_RADR_CA0_ADDR(x) ((x) + 0x908U) #define HW_CAU_RADR_CA0(x) (*(__O hw_cau_radr_ca0_t *) HW_CAU_RADR_CA0_ADDR(x)) #define HW_CAU_RADR_CA0_WR(x, v) (HW_CAU_RADR_CA0(x).U = (v)) /*@}*/ /* * Constants & macros for individual CAU_RADR_CA0 bitfields */ /*! * @name Register CAU_RADR_CA0, field CA0[31:0] (WO) */ /*@{*/ #define BP_CAU_RADR_CA0_CA0 (0U) /*!< Bit position for CAU_RADR_CA0_CA0. */ #define BM_CAU_RADR_CA0_CA0 (0xFFFFFFFFU) /*!< Bit mask for CAU_RADR_CA0_CA0. */ #define BS_CAU_RADR_CA0_CA0 (32U) /*!< Bit field size in bits for CAU_RADR_CA0_CA0. */ /*! @brief Format value for bitfield CAU_RADR_CA0_CA0. */ #define BF_CAU_RADR_CA0_CA0(v) ((uint32_t)((uint32_t)(v) << BP_CAU_RADR_CA0_CA0) & BM_CAU_RADR_CA0_CA0) /*@}*/ /******************************************************************************* * HW_CAU_RADR_CA1 - General Purpose Register 1 - Reverse and Add to Register command ******************************************************************************/ /*! * @brief HW_CAU_RADR_CA1 - General Purpose Register 1 - Reverse and Add to Register command (WO) * * Reset value: 0x00000000U */ typedef union _hw_cau_radr_ca1 { uint32_t U; struct _hw_cau_radr_ca1_bitfields { uint32_t CA1 : 32; /*!< [31:0] CA1 */ } B; } hw_cau_radr_ca1_t; /*! * @name Constants and macros for entire CAU_RADR_CA1 register */ /*@{*/ #define HW_CAU_RADR_CA1_ADDR(x) ((x) + 0x90CU) #define HW_CAU_RADR_CA1(x) (*(__O hw_cau_radr_ca1_t *) HW_CAU_RADR_CA1_ADDR(x)) #define HW_CAU_RADR_CA1_WR(x, v) (HW_CAU_RADR_CA1(x).U = (v)) /*@}*/ /* * Constants & macros for individual CAU_RADR_CA1 bitfields */ /*! * @name Register CAU_RADR_CA1, field CA1[31:0] (WO) */ /*@{*/ #define BP_CAU_RADR_CA1_CA1 (0U) /*!< Bit position for CAU_RADR_CA1_CA1. */ #define BM_CAU_RADR_CA1_CA1 (0xFFFFFFFFU) /*!< Bit mask for CAU_RADR_CA1_CA1. */ #define BS_CAU_RADR_CA1_CA1 (32U) /*!< Bit field size in bits for CAU_RADR_CA1_CA1. */ /*! @brief Format value for bitfield CAU_RADR_CA1_CA1. */ #define BF_CAU_RADR_CA1_CA1(v) ((uint32_t)((uint32_t)(v) << BP_CAU_RADR_CA1_CA1) & BM_CAU_RADR_CA1_CA1) /*@}*/ /******************************************************************************* * HW_CAU_RADR_CA2 - General Purpose Register 2 - Reverse and Add to Register command ******************************************************************************/ /*! * @brief HW_CAU_RADR_CA2 - General Purpose Register 2 - Reverse and Add to Register command (WO) * * Reset value: 0x00000000U */ typedef union _hw_cau_radr_ca2 { uint32_t U; struct _hw_cau_radr_ca2_bitfields { uint32_t CA2 : 32; /*!< [31:0] CA2 */ } B; } hw_cau_radr_ca2_t; /*! * @name Constants and macros for entire CAU_RADR_CA2 register */ /*@{*/ #define HW_CAU_RADR_CA2_ADDR(x) ((x) + 0x910U) #define HW_CAU_RADR_CA2(x) (*(__O hw_cau_radr_ca2_t *) HW_CAU_RADR_CA2_ADDR(x)) #define HW_CAU_RADR_CA2_WR(x, v) (HW_CAU_RADR_CA2(x).U = (v)) /*@}*/ /* * Constants & macros for individual CAU_RADR_CA2 bitfields */ /*! * @name Register CAU_RADR_CA2, field CA2[31:0] (WO) */ /*@{*/ #define BP_CAU_RADR_CA2_CA2 (0U) /*!< Bit position for CAU_RADR_CA2_CA2. */ #define BM_CAU_RADR_CA2_CA2 (0xFFFFFFFFU) /*!< Bit mask for CAU_RADR_CA2_CA2. */ #define BS_CAU_RADR_CA2_CA2 (32U) /*!< Bit field size in bits for CAU_RADR_CA2_CA2. */ /*! @brief Format value for bitfield CAU_RADR_CA2_CA2. */ #define BF_CAU_RADR_CA2_CA2(v) ((uint32_t)((uint32_t)(v) << BP_CAU_RADR_CA2_CA2) & BM_CAU_RADR_CA2_CA2) /*@}*/ /******************************************************************************* * HW_CAU_RADR_CA3 - General Purpose Register 3 - Reverse and Add to Register command ******************************************************************************/ /*! * @brief HW_CAU_RADR_CA3 - General Purpose Register 3 - Reverse and Add to Register command (WO) * * Reset value: 0x00000000U */ typedef union _hw_cau_radr_ca3 { uint32_t U; struct _hw_cau_radr_ca3_bitfields { uint32_t CA3 : 32; /*!< [31:0] CA3 */ } B; } hw_cau_radr_ca3_t; /*! * @name Constants and macros for entire CAU_RADR_CA3 register */ /*@{*/ #define HW_CAU_RADR_CA3_ADDR(x) ((x) + 0x914U) #define HW_CAU_RADR_CA3(x) (*(__O hw_cau_radr_ca3_t *) HW_CAU_RADR_CA3_ADDR(x)) #define HW_CAU_RADR_CA3_WR(x, v) (HW_CAU_RADR_CA3(x).U = (v)) /*@}*/ /* * Constants & macros for individual CAU_RADR_CA3 bitfields */ /*! * @name Register CAU_RADR_CA3, field CA3[31:0] (WO) */ /*@{*/ #define BP_CAU_RADR_CA3_CA3 (0U) /*!< Bit position for CAU_RADR_CA3_CA3. */ #define BM_CAU_RADR_CA3_CA3 (0xFFFFFFFFU) /*!< Bit mask for CAU_RADR_CA3_CA3. */ #define BS_CAU_RADR_CA3_CA3 (32U) /*!< Bit field size in bits for CAU_RADR_CA3_CA3. */ /*! @brief Format value for bitfield CAU_RADR_CA3_CA3. */ #define BF_CAU_RADR_CA3_CA3(v) ((uint32_t)((uint32_t)(v) << BP_CAU_RADR_CA3_CA3) & BM_CAU_RADR_CA3_CA3) /*@}*/ /******************************************************************************* * HW_CAU_RADR_CA4 - General Purpose Register 4 - Reverse and Add to Register command ******************************************************************************/ /*! * @brief HW_CAU_RADR_CA4 - General Purpose Register 4 - Reverse and Add to Register command (WO) * * Reset value: 0x00000000U */ typedef union _hw_cau_radr_ca4 { uint32_t U; struct _hw_cau_radr_ca4_bitfields { uint32_t CA4 : 32; /*!< [31:0] CA4 */ } B; } hw_cau_radr_ca4_t; /*! * @name Constants and macros for entire CAU_RADR_CA4 register */ /*@{*/ #define HW_CAU_RADR_CA4_ADDR(x) ((x) + 0x918U) #define HW_CAU_RADR_CA4(x) (*(__O hw_cau_radr_ca4_t *) HW_CAU_RADR_CA4_ADDR(x)) #define HW_CAU_RADR_CA4_WR(x, v) (HW_CAU_RADR_CA4(x).U = (v)) /*@}*/ /* * Constants & macros for individual CAU_RADR_CA4 bitfields */ /*! * @name Register CAU_RADR_CA4, field CA4[31:0] (WO) */ /*@{*/ #define BP_CAU_RADR_CA4_CA4 (0U) /*!< Bit position for CAU_RADR_CA4_CA4. */ #define BM_CAU_RADR_CA4_CA4 (0xFFFFFFFFU) /*!< Bit mask for CAU_RADR_CA4_CA4. */ #define BS_CAU_RADR_CA4_CA4 (32U) /*!< Bit field size in bits for CAU_RADR_CA4_CA4. */ /*! @brief Format value for bitfield CAU_RADR_CA4_CA4. */ #define BF_CAU_RADR_CA4_CA4(v) ((uint32_t)((uint32_t)(v) << BP_CAU_RADR_CA4_CA4) & BM_CAU_RADR_CA4_CA4) /*@}*/ /******************************************************************************* * HW_CAU_RADR_CA5 - General Purpose Register 5 - Reverse and Add to Register command ******************************************************************************/ /*! * @brief HW_CAU_RADR_CA5 - General Purpose Register 5 - Reverse and Add to Register command (WO) * * Reset value: 0x00000000U */ typedef union _hw_cau_radr_ca5 { uint32_t U; struct _hw_cau_radr_ca5_bitfields { uint32_t CA5 : 32; /*!< [31:0] CA5 */ } B; } hw_cau_radr_ca5_t; /*! * @name Constants and macros for entire CAU_RADR_CA5 register */ /*@{*/ #define HW_CAU_RADR_CA5_ADDR(x) ((x) + 0x91CU) #define HW_CAU_RADR_CA5(x) (*(__O hw_cau_radr_ca5_t *) HW_CAU_RADR_CA5_ADDR(x)) #define HW_CAU_RADR_CA5_WR(x, v) (HW_CAU_RADR_CA5(x).U = (v)) /*@}*/ /* * Constants & macros for individual CAU_RADR_CA5 bitfields */ /*! * @name Register CAU_RADR_CA5, field CA5[31:0] (WO) */ /*@{*/ #define BP_CAU_RADR_CA5_CA5 (0U) /*!< Bit position for CAU_RADR_CA5_CA5. */ #define BM_CAU_RADR_CA5_CA5 (0xFFFFFFFFU) /*!< Bit mask for CAU_RADR_CA5_CA5. */ #define BS_CAU_RADR_CA5_CA5 (32U) /*!< Bit field size in bits for CAU_RADR_CA5_CA5. */ /*! @brief Format value for bitfield CAU_RADR_CA5_CA5. */ #define BF_CAU_RADR_CA5_CA5(v) ((uint32_t)((uint32_t)(v) << BP_CAU_RADR_CA5_CA5) & BM_CAU_RADR_CA5_CA5) /*@}*/ /******************************************************************************* * HW_CAU_RADR_CA6 - General Purpose Register 6 - Reverse and Add to Register command ******************************************************************************/ /*! * @brief HW_CAU_RADR_CA6 - General Purpose Register 6 - Reverse and Add to Register command (WO) * * Reset value: 0x00000000U */ typedef union _hw_cau_radr_ca6 { uint32_t U; struct _hw_cau_radr_ca6_bitfields { uint32_t CA6 : 32; /*!< [31:0] CA6 */ } B; } hw_cau_radr_ca6_t; /*! * @name Constants and macros for entire CAU_RADR_CA6 register */ /*@{*/ #define HW_CAU_RADR_CA6_ADDR(x) ((x) + 0x920U) #define HW_CAU_RADR_CA6(x) (*(__O hw_cau_radr_ca6_t *) HW_CAU_RADR_CA6_ADDR(x)) #define HW_CAU_RADR_CA6_WR(x, v) (HW_CAU_RADR_CA6(x).U = (v)) /*@}*/ /* * Constants & macros for individual CAU_RADR_CA6 bitfields */ /*! * @name Register CAU_RADR_CA6, field CA6[31:0] (WO) */ /*@{*/ #define BP_CAU_RADR_CA6_CA6 (0U) /*!< Bit position for CAU_RADR_CA6_CA6. */ #define BM_CAU_RADR_CA6_CA6 (0xFFFFFFFFU) /*!< Bit mask for CAU_RADR_CA6_CA6. */ #define BS_CAU_RADR_CA6_CA6 (32U) /*!< Bit field size in bits for CAU_RADR_CA6_CA6. */ /*! @brief Format value for bitfield CAU_RADR_CA6_CA6. */ #define BF_CAU_RADR_CA6_CA6(v) ((uint32_t)((uint32_t)(v) << BP_CAU_RADR_CA6_CA6) & BM_CAU_RADR_CA6_CA6) /*@}*/ /******************************************************************************* * HW_CAU_RADR_CA7 - General Purpose Register 7 - Reverse and Add to Register command ******************************************************************************/ /*! * @brief HW_CAU_RADR_CA7 - General Purpose Register 7 - Reverse and Add to Register command (WO) * * Reset value: 0x00000000U */ typedef union _hw_cau_radr_ca7 { uint32_t U; struct _hw_cau_radr_ca7_bitfields { uint32_t CA7 : 32; /*!< [31:0] CA7 */ } B; } hw_cau_radr_ca7_t; /*! * @name Constants and macros for entire CAU_RADR_CA7 register */ /*@{*/ #define HW_CAU_RADR_CA7_ADDR(x) ((x) + 0x924U) #define HW_CAU_RADR_CA7(x) (*(__O hw_cau_radr_ca7_t *) HW_CAU_RADR_CA7_ADDR(x)) #define HW_CAU_RADR_CA7_WR(x, v) (HW_CAU_RADR_CA7(x).U = (v)) /*@}*/ /* * Constants & macros for individual CAU_RADR_CA7 bitfields */ /*! * @name Register CAU_RADR_CA7, field CA7[31:0] (WO) */ /*@{*/ #define BP_CAU_RADR_CA7_CA7 (0U) /*!< Bit position for CAU_RADR_CA7_CA7. */ #define BM_CAU_RADR_CA7_CA7 (0xFFFFFFFFU) /*!< Bit mask for CAU_RADR_CA7_CA7. */ #define BS_CAU_RADR_CA7_CA7 (32U) /*!< Bit field size in bits for CAU_RADR_CA7_CA7. */ /*! @brief Format value for bitfield CAU_RADR_CA7_CA7. */ #define BF_CAU_RADR_CA7_CA7(v) ((uint32_t)((uint32_t)(v) << BP_CAU_RADR_CA7_CA7) & BM_CAU_RADR_CA7_CA7) /*@}*/ /******************************************************************************* * HW_CAU_RADR_CA8 - General Purpose Register 8 - Reverse and Add to Register command ******************************************************************************/ /*! * @brief HW_CAU_RADR_CA8 - General Purpose Register 8 - Reverse and Add to Register command (WO) * * Reset value: 0x00000000U */ typedef union _hw_cau_radr_ca8 { uint32_t U; struct _hw_cau_radr_ca8_bitfields { uint32_t CA8 : 32; /*!< [31:0] CA8 */ } B; } hw_cau_radr_ca8_t; /*! * @name Constants and macros for entire CAU_RADR_CA8 register */ /*@{*/ #define HW_CAU_RADR_CA8_ADDR(x) ((x) + 0x928U) #define HW_CAU_RADR_CA8(x) (*(__O hw_cau_radr_ca8_t *) HW_CAU_RADR_CA8_ADDR(x)) #define HW_CAU_RADR_CA8_WR(x, v) (HW_CAU_RADR_CA8(x).U = (v)) /*@}*/ /* * Constants & macros for individual CAU_RADR_CA8 bitfields */ /*! * @name Register CAU_RADR_CA8, field CA8[31:0] (WO) */ /*@{*/ #define BP_CAU_RADR_CA8_CA8 (0U) /*!< Bit position for CAU_RADR_CA8_CA8. */ #define BM_CAU_RADR_CA8_CA8 (0xFFFFFFFFU) /*!< Bit mask for CAU_RADR_CA8_CA8. */ #define BS_CAU_RADR_CA8_CA8 (32U) /*!< Bit field size in bits for CAU_RADR_CA8_CA8. */ /*! @brief Format value for bitfield CAU_RADR_CA8_CA8. */ #define BF_CAU_RADR_CA8_CA8(v) ((uint32_t)((uint32_t)(v) << BP_CAU_RADR_CA8_CA8) & BM_CAU_RADR_CA8_CA8) /*@}*/ /******************************************************************************* * HW_CAU_XOR_CASR - Status register - Exclusive Or command ******************************************************************************/ /*! * @brief HW_CAU_XOR_CASR - Status register - Exclusive Or command (WO) * * Reset value: 0x20000000U */ typedef union _hw_cau_xor_casr { uint32_t U; struct _hw_cau_xor_casr_bitfields { uint32_t IC : 1; /*!< [0] */ uint32_t DPE : 1; /*!< [1] */ uint32_t RESERVED0 : 26; /*!< [27:2] */ uint32_t VER : 4; /*!< [31:28] CAU version */ } B; } hw_cau_xor_casr_t; /*! * @name Constants and macros for entire CAU_XOR_CASR register */ /*@{*/ #define HW_CAU_XOR_CASR_ADDR(x) ((x) + 0x980U) #define HW_CAU_XOR_CASR(x) (*(__O hw_cau_xor_casr_t *) HW_CAU_XOR_CASR_ADDR(x)) #define HW_CAU_XOR_CASR_WR(x, v) (HW_CAU_XOR_CASR(x).U = (v)) /*@}*/ /* * Constants & macros for individual CAU_XOR_CASR bitfields */ /*! * @name Register CAU_XOR_CASR, field IC[0] (WO) * * Values: * - 0 - No illegal commands issued * - 1 - Illegal command issued */ /*@{*/ #define BP_CAU_XOR_CASR_IC (0U) /*!< Bit position for CAU_XOR_CASR_IC. */ #define BM_CAU_XOR_CASR_IC (0x00000001U) /*!< Bit mask for CAU_XOR_CASR_IC. */ #define BS_CAU_XOR_CASR_IC (1U) /*!< Bit field size in bits for CAU_XOR_CASR_IC. */ /*! @brief Format value for bitfield CAU_XOR_CASR_IC. */ #define BF_CAU_XOR_CASR_IC(v) ((uint32_t)((uint32_t)(v) << BP_CAU_XOR_CASR_IC) & BM_CAU_XOR_CASR_IC) /*@}*/ /*! * @name Register CAU_XOR_CASR, field DPE[1] (WO) * * Values: * - 0 - No error detected * - 1 - DES key parity error detected */ /*@{*/ #define BP_CAU_XOR_CASR_DPE (1U) /*!< Bit position for CAU_XOR_CASR_DPE. */ #define BM_CAU_XOR_CASR_DPE (0x00000002U) /*!< Bit mask for CAU_XOR_CASR_DPE. */ #define BS_CAU_XOR_CASR_DPE (1U) /*!< Bit field size in bits for CAU_XOR_CASR_DPE. */ /*! @brief Format value for bitfield CAU_XOR_CASR_DPE. */ #define BF_CAU_XOR_CASR_DPE(v) ((uint32_t)((uint32_t)(v) << BP_CAU_XOR_CASR_DPE) & BM_CAU_XOR_CASR_DPE) /*@}*/ /*! * @name Register CAU_XOR_CASR, field VER[31:28] (WO) * * Values: * - 0001 - Initial CAU version * - 0010 - Second version, added support for SHA-256 algorithm.(This is the * value on this device) */ /*@{*/ #define BP_CAU_XOR_CASR_VER (28U) /*!< Bit position for CAU_XOR_CASR_VER. */ #define BM_CAU_XOR_CASR_VER (0xF0000000U) /*!< Bit mask for CAU_XOR_CASR_VER. */ #define BS_CAU_XOR_CASR_VER (4U) /*!< Bit field size in bits for CAU_XOR_CASR_VER. */ /*! @brief Format value for bitfield CAU_XOR_CASR_VER. */ #define BF_CAU_XOR_CASR_VER(v) ((uint32_t)((uint32_t)(v) << BP_CAU_XOR_CASR_VER) & BM_CAU_XOR_CASR_VER) /*@}*/ /******************************************************************************* * HW_CAU_XOR_CAA - Accumulator register - Exclusive Or command ******************************************************************************/ /*! * @brief HW_CAU_XOR_CAA - Accumulator register - Exclusive Or command (WO) * * Reset value: 0x00000000U */ typedef union _hw_cau_xor_caa { uint32_t U; struct _hw_cau_xor_caa_bitfields { uint32_t ACC : 32; /*!< [31:0] ACC */ } B; } hw_cau_xor_caa_t; /*! * @name Constants and macros for entire CAU_XOR_CAA register */ /*@{*/ #define HW_CAU_XOR_CAA_ADDR(x) ((x) + 0x984U) #define HW_CAU_XOR_CAA(x) (*(__O hw_cau_xor_caa_t *) HW_CAU_XOR_CAA_ADDR(x)) #define HW_CAU_XOR_CAA_WR(x, v) (HW_CAU_XOR_CAA(x).U = (v)) /*@}*/ /* * Constants & macros for individual CAU_XOR_CAA bitfields */ /*! * @name Register CAU_XOR_CAA, field ACC[31:0] (WO) */ /*@{*/ #define BP_CAU_XOR_CAA_ACC (0U) /*!< Bit position for CAU_XOR_CAA_ACC. */ #define BM_CAU_XOR_CAA_ACC (0xFFFFFFFFU) /*!< Bit mask for CAU_XOR_CAA_ACC. */ #define BS_CAU_XOR_CAA_ACC (32U) /*!< Bit field size in bits for CAU_XOR_CAA_ACC. */ /*! @brief Format value for bitfield CAU_XOR_CAA_ACC. */ #define BF_CAU_XOR_CAA_ACC(v) ((uint32_t)((uint32_t)(v) << BP_CAU_XOR_CAA_ACC) & BM_CAU_XOR_CAA_ACC) /*@}*/ /******************************************************************************* * HW_CAU_XOR_CA0 - General Purpose Register 0 - Exclusive Or command ******************************************************************************/ /*! * @brief HW_CAU_XOR_CA0 - General Purpose Register 0 - Exclusive Or command (WO) * * Reset value: 0x00000000U */ typedef union _hw_cau_xor_ca0 { uint32_t U; struct _hw_cau_xor_ca0_bitfields { uint32_t CA0 : 32; /*!< [31:0] CA0 */ } B; } hw_cau_xor_ca0_t; /*! * @name Constants and macros for entire CAU_XOR_CA0 register */ /*@{*/ #define HW_CAU_XOR_CA0_ADDR(x) ((x) + 0x988U) #define HW_CAU_XOR_CA0(x) (*(__O hw_cau_xor_ca0_t *) HW_CAU_XOR_CA0_ADDR(x)) #define HW_CAU_XOR_CA0_WR(x, v) (HW_CAU_XOR_CA0(x).U = (v)) /*@}*/ /* * Constants & macros for individual CAU_XOR_CA0 bitfields */ /*! * @name Register CAU_XOR_CA0, field CA0[31:0] (WO) */ /*@{*/ #define BP_CAU_XOR_CA0_CA0 (0U) /*!< Bit position for CAU_XOR_CA0_CA0. */ #define BM_CAU_XOR_CA0_CA0 (0xFFFFFFFFU) /*!< Bit mask for CAU_XOR_CA0_CA0. */ #define BS_CAU_XOR_CA0_CA0 (32U) /*!< Bit field size in bits for CAU_XOR_CA0_CA0. */ /*! @brief Format value for bitfield CAU_XOR_CA0_CA0. */ #define BF_CAU_XOR_CA0_CA0(v) ((uint32_t)((uint32_t)(v) << BP_CAU_XOR_CA0_CA0) & BM_CAU_XOR_CA0_CA0) /*@}*/ /******************************************************************************* * HW_CAU_XOR_CA1 - General Purpose Register 1 - Exclusive Or command ******************************************************************************/ /*! * @brief HW_CAU_XOR_CA1 - General Purpose Register 1 - Exclusive Or command (WO) * * Reset value: 0x00000000U */ typedef union _hw_cau_xor_ca1 { uint32_t U; struct _hw_cau_xor_ca1_bitfields { uint32_t CA1 : 32; /*!< [31:0] CA1 */ } B; } hw_cau_xor_ca1_t; /*! * @name Constants and macros for entire CAU_XOR_CA1 register */ /*@{*/ #define HW_CAU_XOR_CA1_ADDR(x) ((x) + 0x98CU) #define HW_CAU_XOR_CA1(x) (*(__O hw_cau_xor_ca1_t *) HW_CAU_XOR_CA1_ADDR(x)) #define HW_CAU_XOR_CA1_WR(x, v) (HW_CAU_XOR_CA1(x).U = (v)) /*@}*/ /* * Constants & macros for individual CAU_XOR_CA1 bitfields */ /*! * @name Register CAU_XOR_CA1, field CA1[31:0] (WO) */ /*@{*/ #define BP_CAU_XOR_CA1_CA1 (0U) /*!< Bit position for CAU_XOR_CA1_CA1. */ #define BM_CAU_XOR_CA1_CA1 (0xFFFFFFFFU) /*!< Bit mask for CAU_XOR_CA1_CA1. */ #define BS_CAU_XOR_CA1_CA1 (32U) /*!< Bit field size in bits for CAU_XOR_CA1_CA1. */ /*! @brief Format value for bitfield CAU_XOR_CA1_CA1. */ #define BF_CAU_XOR_CA1_CA1(v) ((uint32_t)((uint32_t)(v) << BP_CAU_XOR_CA1_CA1) & BM_CAU_XOR_CA1_CA1) /*@}*/ /******************************************************************************* * HW_CAU_XOR_CA2 - General Purpose Register 2 - Exclusive Or command ******************************************************************************/ /*! * @brief HW_CAU_XOR_CA2 - General Purpose Register 2 - Exclusive Or command (WO) * * Reset value: 0x00000000U */ typedef union _hw_cau_xor_ca2 { uint32_t U; struct _hw_cau_xor_ca2_bitfields { uint32_t CA2 : 32; /*!< [31:0] CA2 */ } B; } hw_cau_xor_ca2_t; /*! * @name Constants and macros for entire CAU_XOR_CA2 register */ /*@{*/ #define HW_CAU_XOR_CA2_ADDR(x) ((x) + 0x990U) #define HW_CAU_XOR_CA2(x) (*(__O hw_cau_xor_ca2_t *) HW_CAU_XOR_CA2_ADDR(x)) #define HW_CAU_XOR_CA2_WR(x, v) (HW_CAU_XOR_CA2(x).U = (v)) /*@}*/ /* * Constants & macros for individual CAU_XOR_CA2 bitfields */ /*! * @name Register CAU_XOR_CA2, field CA2[31:0] (WO) */ /*@{*/ #define BP_CAU_XOR_CA2_CA2 (0U) /*!< Bit position for CAU_XOR_CA2_CA2. */ #define BM_CAU_XOR_CA2_CA2 (0xFFFFFFFFU) /*!< Bit mask for CAU_XOR_CA2_CA2. */ #define BS_CAU_XOR_CA2_CA2 (32U) /*!< Bit field size in bits for CAU_XOR_CA2_CA2. */ /*! @brief Format value for bitfield CAU_XOR_CA2_CA2. */ #define BF_CAU_XOR_CA2_CA2(v) ((uint32_t)((uint32_t)(v) << BP_CAU_XOR_CA2_CA2) & BM_CAU_XOR_CA2_CA2) /*@}*/ /******************************************************************************* * HW_CAU_XOR_CA3 - General Purpose Register 3 - Exclusive Or command ******************************************************************************/ /*! * @brief HW_CAU_XOR_CA3 - General Purpose Register 3 - Exclusive Or command (WO) * * Reset value: 0x00000000U */ typedef union _hw_cau_xor_ca3 { uint32_t U; struct _hw_cau_xor_ca3_bitfields { uint32_t CA3 : 32; /*!< [31:0] CA3 */ } B; } hw_cau_xor_ca3_t; /*! * @name Constants and macros for entire CAU_XOR_CA3 register */ /*@{*/ #define HW_CAU_XOR_CA3_ADDR(x) ((x) + 0x994U) #define HW_CAU_XOR_CA3(x) (*(__O hw_cau_xor_ca3_t *) HW_CAU_XOR_CA3_ADDR(x)) #define HW_CAU_XOR_CA3_WR(x, v) (HW_CAU_XOR_CA3(x).U = (v)) /*@}*/ /* * Constants & macros for individual CAU_XOR_CA3 bitfields */ /*! * @name Register CAU_XOR_CA3, field CA3[31:0] (WO) */ /*@{*/ #define BP_CAU_XOR_CA3_CA3 (0U) /*!< Bit position for CAU_XOR_CA3_CA3. */ #define BM_CAU_XOR_CA3_CA3 (0xFFFFFFFFU) /*!< Bit mask for CAU_XOR_CA3_CA3. */ #define BS_CAU_XOR_CA3_CA3 (32U) /*!< Bit field size in bits for CAU_XOR_CA3_CA3. */ /*! @brief Format value for bitfield CAU_XOR_CA3_CA3. */ #define BF_CAU_XOR_CA3_CA3(v) ((uint32_t)((uint32_t)(v) << BP_CAU_XOR_CA3_CA3) & BM_CAU_XOR_CA3_CA3) /*@}*/ /******************************************************************************* * HW_CAU_XOR_CA4 - General Purpose Register 4 - Exclusive Or command ******************************************************************************/ /*! * @brief HW_CAU_XOR_CA4 - General Purpose Register 4 - Exclusive Or command (WO) * * Reset value: 0x00000000U */ typedef union _hw_cau_xor_ca4 { uint32_t U; struct _hw_cau_xor_ca4_bitfields { uint32_t CA4 : 32; /*!< [31:0] CA4 */ } B; } hw_cau_xor_ca4_t; /*! * @name Constants and macros for entire CAU_XOR_CA4 register */ /*@{*/ #define HW_CAU_XOR_CA4_ADDR(x) ((x) + 0x998U) #define HW_CAU_XOR_CA4(x) (*(__O hw_cau_xor_ca4_t *) HW_CAU_XOR_CA4_ADDR(x)) #define HW_CAU_XOR_CA4_WR(x, v) (HW_CAU_XOR_CA4(x).U = (v)) /*@}*/ /* * Constants & macros for individual CAU_XOR_CA4 bitfields */ /*! * @name Register CAU_XOR_CA4, field CA4[31:0] (WO) */ /*@{*/ #define BP_CAU_XOR_CA4_CA4 (0U) /*!< Bit position for CAU_XOR_CA4_CA4. */ #define BM_CAU_XOR_CA4_CA4 (0xFFFFFFFFU) /*!< Bit mask for CAU_XOR_CA4_CA4. */ #define BS_CAU_XOR_CA4_CA4 (32U) /*!< Bit field size in bits for CAU_XOR_CA4_CA4. */ /*! @brief Format value for bitfield CAU_XOR_CA4_CA4. */ #define BF_CAU_XOR_CA4_CA4(v) ((uint32_t)((uint32_t)(v) << BP_CAU_XOR_CA4_CA4) & BM_CAU_XOR_CA4_CA4) /*@}*/ /******************************************************************************* * HW_CAU_XOR_CA5 - General Purpose Register 5 - Exclusive Or command ******************************************************************************/ /*! * @brief HW_CAU_XOR_CA5 - General Purpose Register 5 - Exclusive Or command (WO) * * Reset value: 0x00000000U */ typedef union _hw_cau_xor_ca5 { uint32_t U; struct _hw_cau_xor_ca5_bitfields { uint32_t CA5 : 32; /*!< [31:0] CA5 */ } B; } hw_cau_xor_ca5_t; /*! * @name Constants and macros for entire CAU_XOR_CA5 register */ /*@{*/ #define HW_CAU_XOR_CA5_ADDR(x) ((x) + 0x99CU) #define HW_CAU_XOR_CA5(x) (*(__O hw_cau_xor_ca5_t *) HW_CAU_XOR_CA5_ADDR(x)) #define HW_CAU_XOR_CA5_WR(x, v) (HW_CAU_XOR_CA5(x).U = (v)) /*@}*/ /* * Constants & macros for individual CAU_XOR_CA5 bitfields */ /*! * @name Register CAU_XOR_CA5, field CA5[31:0] (WO) */ /*@{*/ #define BP_CAU_XOR_CA5_CA5 (0U) /*!< Bit position for CAU_XOR_CA5_CA5. */ #define BM_CAU_XOR_CA5_CA5 (0xFFFFFFFFU) /*!< Bit mask for CAU_XOR_CA5_CA5. */ #define BS_CAU_XOR_CA5_CA5 (32U) /*!< Bit field size in bits for CAU_XOR_CA5_CA5. */ /*! @brief Format value for bitfield CAU_XOR_CA5_CA5. */ #define BF_CAU_XOR_CA5_CA5(v) ((uint32_t)((uint32_t)(v) << BP_CAU_XOR_CA5_CA5) & BM_CAU_XOR_CA5_CA5) /*@}*/ /******************************************************************************* * HW_CAU_XOR_CA6 - General Purpose Register 6 - Exclusive Or command ******************************************************************************/ /*! * @brief HW_CAU_XOR_CA6 - General Purpose Register 6 - Exclusive Or command (WO) * * Reset value: 0x00000000U */ typedef union _hw_cau_xor_ca6 { uint32_t U; struct _hw_cau_xor_ca6_bitfields { uint32_t CA6 : 32; /*!< [31:0] CA6 */ } B; } hw_cau_xor_ca6_t; /*! * @name Constants and macros for entire CAU_XOR_CA6 register */ /*@{*/ #define HW_CAU_XOR_CA6_ADDR(x) ((x) + 0x9A0U) #define HW_CAU_XOR_CA6(x) (*(__O hw_cau_xor_ca6_t *) HW_CAU_XOR_CA6_ADDR(x)) #define HW_CAU_XOR_CA6_WR(x, v) (HW_CAU_XOR_CA6(x).U = (v)) /*@}*/ /* * Constants & macros for individual CAU_XOR_CA6 bitfields */ /*! * @name Register CAU_XOR_CA6, field CA6[31:0] (WO) */ /*@{*/ #define BP_CAU_XOR_CA6_CA6 (0U) /*!< Bit position for CAU_XOR_CA6_CA6. */ #define BM_CAU_XOR_CA6_CA6 (0xFFFFFFFFU) /*!< Bit mask for CAU_XOR_CA6_CA6. */ #define BS_CAU_XOR_CA6_CA6 (32U) /*!< Bit field size in bits for CAU_XOR_CA6_CA6. */ /*! @brief Format value for bitfield CAU_XOR_CA6_CA6. */ #define BF_CAU_XOR_CA6_CA6(v) ((uint32_t)((uint32_t)(v) << BP_CAU_XOR_CA6_CA6) & BM_CAU_XOR_CA6_CA6) /*@}*/ /******************************************************************************* * HW_CAU_XOR_CA7 - General Purpose Register 7 - Exclusive Or command ******************************************************************************/ /*! * @brief HW_CAU_XOR_CA7 - General Purpose Register 7 - Exclusive Or command (WO) * * Reset value: 0x00000000U */ typedef union _hw_cau_xor_ca7 { uint32_t U; struct _hw_cau_xor_ca7_bitfields { uint32_t CA7 : 32; /*!< [31:0] CA7 */ } B; } hw_cau_xor_ca7_t; /*! * @name Constants and macros for entire CAU_XOR_CA7 register */ /*@{*/ #define HW_CAU_XOR_CA7_ADDR(x) ((x) + 0x9A4U) #define HW_CAU_XOR_CA7(x) (*(__O hw_cau_xor_ca7_t *) HW_CAU_XOR_CA7_ADDR(x)) #define HW_CAU_XOR_CA7_WR(x, v) (HW_CAU_XOR_CA7(x).U = (v)) /*@}*/ /* * Constants & macros for individual CAU_XOR_CA7 bitfields */ /*! * @name Register CAU_XOR_CA7, field CA7[31:0] (WO) */ /*@{*/ #define BP_CAU_XOR_CA7_CA7 (0U) /*!< Bit position for CAU_XOR_CA7_CA7. */ #define BM_CAU_XOR_CA7_CA7 (0xFFFFFFFFU) /*!< Bit mask for CAU_XOR_CA7_CA7. */ #define BS_CAU_XOR_CA7_CA7 (32U) /*!< Bit field size in bits for CAU_XOR_CA7_CA7. */ /*! @brief Format value for bitfield CAU_XOR_CA7_CA7. */ #define BF_CAU_XOR_CA7_CA7(v) ((uint32_t)((uint32_t)(v) << BP_CAU_XOR_CA7_CA7) & BM_CAU_XOR_CA7_CA7) /*@}*/ /******************************************************************************* * HW_CAU_XOR_CA8 - General Purpose Register 8 - Exclusive Or command ******************************************************************************/ /*! * @brief HW_CAU_XOR_CA8 - General Purpose Register 8 - Exclusive Or command (WO) * * Reset value: 0x00000000U */ typedef union _hw_cau_xor_ca8 { uint32_t U; struct _hw_cau_xor_ca8_bitfields { uint32_t CA8 : 32; /*!< [31:0] CA8 */ } B; } hw_cau_xor_ca8_t; /*! * @name Constants and macros for entire CAU_XOR_CA8 register */ /*@{*/ #define HW_CAU_XOR_CA8_ADDR(x) ((x) + 0x9A8U) #define HW_CAU_XOR_CA8(x) (*(__O hw_cau_xor_ca8_t *) HW_CAU_XOR_CA8_ADDR(x)) #define HW_CAU_XOR_CA8_WR(x, v) (HW_CAU_XOR_CA8(x).U = (v)) /*@}*/ /* * Constants & macros for individual CAU_XOR_CA8 bitfields */ /*! * @name Register CAU_XOR_CA8, field CA8[31:0] (WO) */ /*@{*/ #define BP_CAU_XOR_CA8_CA8 (0U) /*!< Bit position for CAU_XOR_CA8_CA8. */ #define BM_CAU_XOR_CA8_CA8 (0xFFFFFFFFU) /*!< Bit mask for CAU_XOR_CA8_CA8. */ #define BS_CAU_XOR_CA8_CA8 (32U) /*!< Bit field size in bits for CAU_XOR_CA8_CA8. */ /*! @brief Format value for bitfield CAU_XOR_CA8_CA8. */ #define BF_CAU_XOR_CA8_CA8(v) ((uint32_t)((uint32_t)(v) << BP_CAU_XOR_CA8_CA8) & BM_CAU_XOR_CA8_CA8) /*@}*/ /******************************************************************************* * HW_CAU_ROTL_CASR - Status register - Rotate Left command ******************************************************************************/ /*! * @brief HW_CAU_ROTL_CASR - Status register - Rotate Left command (WO) * * Reset value: 0x20000000U */ typedef union _hw_cau_rotl_casr { uint32_t U; struct _hw_cau_rotl_casr_bitfields { uint32_t IC : 1; /*!< [0] */ uint32_t DPE : 1; /*!< [1] */ uint32_t RESERVED0 : 26; /*!< [27:2] */ uint32_t VER : 4; /*!< [31:28] CAU version */ } B; } hw_cau_rotl_casr_t; /*! * @name Constants and macros for entire CAU_ROTL_CASR register */ /*@{*/ #define HW_CAU_ROTL_CASR_ADDR(x) ((x) + 0x9C0U) #define HW_CAU_ROTL_CASR(x) (*(__O hw_cau_rotl_casr_t *) HW_CAU_ROTL_CASR_ADDR(x)) #define HW_CAU_ROTL_CASR_WR(x, v) (HW_CAU_ROTL_CASR(x).U = (v)) /*@}*/ /* * Constants & macros for individual CAU_ROTL_CASR bitfields */ /*! * @name Register CAU_ROTL_CASR, field IC[0] (WO) * * Values: * - 0 - No illegal commands issued * - 1 - Illegal command issued */ /*@{*/ #define BP_CAU_ROTL_CASR_IC (0U) /*!< Bit position for CAU_ROTL_CASR_IC. */ #define BM_CAU_ROTL_CASR_IC (0x00000001U) /*!< Bit mask for CAU_ROTL_CASR_IC. */ #define BS_CAU_ROTL_CASR_IC (1U) /*!< Bit field size in bits for CAU_ROTL_CASR_IC. */ /*! @brief Format value for bitfield CAU_ROTL_CASR_IC. */ #define BF_CAU_ROTL_CASR_IC(v) ((uint32_t)((uint32_t)(v) << BP_CAU_ROTL_CASR_IC) & BM_CAU_ROTL_CASR_IC) /*@}*/ /*! * @name Register CAU_ROTL_CASR, field DPE[1] (WO) * * Values: * - 0 - No error detected * - 1 - DES key parity error detected */ /*@{*/ #define BP_CAU_ROTL_CASR_DPE (1U) /*!< Bit position for CAU_ROTL_CASR_DPE. */ #define BM_CAU_ROTL_CASR_DPE (0x00000002U) /*!< Bit mask for CAU_ROTL_CASR_DPE. */ #define BS_CAU_ROTL_CASR_DPE (1U) /*!< Bit field size in bits for CAU_ROTL_CASR_DPE. */ /*! @brief Format value for bitfield CAU_ROTL_CASR_DPE. */ #define BF_CAU_ROTL_CASR_DPE(v) ((uint32_t)((uint32_t)(v) << BP_CAU_ROTL_CASR_DPE) & BM_CAU_ROTL_CASR_DPE) /*@}*/ /*! * @name Register CAU_ROTL_CASR, field VER[31:28] (WO) * * Values: * - 0001 - Initial CAU version * - 0010 - Second version, added support for SHA-256 algorithm.(This is the * value on this device) */ /*@{*/ #define BP_CAU_ROTL_CASR_VER (28U) /*!< Bit position for CAU_ROTL_CASR_VER. */ #define BM_CAU_ROTL_CASR_VER (0xF0000000U) /*!< Bit mask for CAU_ROTL_CASR_VER. */ #define BS_CAU_ROTL_CASR_VER (4U) /*!< Bit field size in bits for CAU_ROTL_CASR_VER. */ /*! @brief Format value for bitfield CAU_ROTL_CASR_VER. */ #define BF_CAU_ROTL_CASR_VER(v) ((uint32_t)((uint32_t)(v) << BP_CAU_ROTL_CASR_VER) & BM_CAU_ROTL_CASR_VER) /*@}*/ /******************************************************************************* * HW_CAU_ROTL_CAA - Accumulator register - Rotate Left command ******************************************************************************/ /*! * @brief HW_CAU_ROTL_CAA - Accumulator register - Rotate Left command (WO) * * Reset value: 0x00000000U */ typedef union _hw_cau_rotl_caa { uint32_t U; struct _hw_cau_rotl_caa_bitfields { uint32_t ACC : 32; /*!< [31:0] ACC */ } B; } hw_cau_rotl_caa_t; /*! * @name Constants and macros for entire CAU_ROTL_CAA register */ /*@{*/ #define HW_CAU_ROTL_CAA_ADDR(x) ((x) + 0x9C4U) #define HW_CAU_ROTL_CAA(x) (*(__O hw_cau_rotl_caa_t *) HW_CAU_ROTL_CAA_ADDR(x)) #define HW_CAU_ROTL_CAA_WR(x, v) (HW_CAU_ROTL_CAA(x).U = (v)) /*@}*/ /* * Constants & macros for individual CAU_ROTL_CAA bitfields */ /*! * @name Register CAU_ROTL_CAA, field ACC[31:0] (WO) */ /*@{*/ #define BP_CAU_ROTL_CAA_ACC (0U) /*!< Bit position for CAU_ROTL_CAA_ACC. */ #define BM_CAU_ROTL_CAA_ACC (0xFFFFFFFFU) /*!< Bit mask for CAU_ROTL_CAA_ACC. */ #define BS_CAU_ROTL_CAA_ACC (32U) /*!< Bit field size in bits for CAU_ROTL_CAA_ACC. */ /*! @brief Format value for bitfield CAU_ROTL_CAA_ACC. */ #define BF_CAU_ROTL_CAA_ACC(v) ((uint32_t)((uint32_t)(v) << BP_CAU_ROTL_CAA_ACC) & BM_CAU_ROTL_CAA_ACC) /*@}*/ /******************************************************************************* * HW_CAU_ROTL_CA0 - General Purpose Register 0 - Rotate Left command ******************************************************************************/ /*! * @brief HW_CAU_ROTL_CA0 - General Purpose Register 0 - Rotate Left command (WO) * * Reset value: 0x00000000U */ typedef union _hw_cau_rotl_ca0 { uint32_t U; struct _hw_cau_rotl_ca0_bitfields { uint32_t CA0 : 32; /*!< [31:0] CA0 */ } B; } hw_cau_rotl_ca0_t; /*! * @name Constants and macros for entire CAU_ROTL_CA0 register */ /*@{*/ #define HW_CAU_ROTL_CA0_ADDR(x) ((x) + 0x9C8U) #define HW_CAU_ROTL_CA0(x) (*(__O hw_cau_rotl_ca0_t *) HW_CAU_ROTL_CA0_ADDR(x)) #define HW_CAU_ROTL_CA0_WR(x, v) (HW_CAU_ROTL_CA0(x).U = (v)) /*@}*/ /* * Constants & macros for individual CAU_ROTL_CA0 bitfields */ /*! * @name Register CAU_ROTL_CA0, field CA0[31:0] (WO) */ /*@{*/ #define BP_CAU_ROTL_CA0_CA0 (0U) /*!< Bit position for CAU_ROTL_CA0_CA0. */ #define BM_CAU_ROTL_CA0_CA0 (0xFFFFFFFFU) /*!< Bit mask for CAU_ROTL_CA0_CA0. */ #define BS_CAU_ROTL_CA0_CA0 (32U) /*!< Bit field size in bits for CAU_ROTL_CA0_CA0. */ /*! @brief Format value for bitfield CAU_ROTL_CA0_CA0. */ #define BF_CAU_ROTL_CA0_CA0(v) ((uint32_t)((uint32_t)(v) << BP_CAU_ROTL_CA0_CA0) & BM_CAU_ROTL_CA0_CA0) /*@}*/ /******************************************************************************* * HW_CAU_ROTL_CA1 - General Purpose Register 1 - Rotate Left command ******************************************************************************/ /*! * @brief HW_CAU_ROTL_CA1 - General Purpose Register 1 - Rotate Left command (WO) * * Reset value: 0x00000000U */ typedef union _hw_cau_rotl_ca1 { uint32_t U; struct _hw_cau_rotl_ca1_bitfields { uint32_t CA1 : 32; /*!< [31:0] CA1 */ } B; } hw_cau_rotl_ca1_t; /*! * @name Constants and macros for entire CAU_ROTL_CA1 register */ /*@{*/ #define HW_CAU_ROTL_CA1_ADDR(x) ((x) + 0x9CCU) #define HW_CAU_ROTL_CA1(x) (*(__O hw_cau_rotl_ca1_t *) HW_CAU_ROTL_CA1_ADDR(x)) #define HW_CAU_ROTL_CA1_WR(x, v) (HW_CAU_ROTL_CA1(x).U = (v)) /*@}*/ /* * Constants & macros for individual CAU_ROTL_CA1 bitfields */ /*! * @name Register CAU_ROTL_CA1, field CA1[31:0] (WO) */ /*@{*/ #define BP_CAU_ROTL_CA1_CA1 (0U) /*!< Bit position for CAU_ROTL_CA1_CA1. */ #define BM_CAU_ROTL_CA1_CA1 (0xFFFFFFFFU) /*!< Bit mask for CAU_ROTL_CA1_CA1. */ #define BS_CAU_ROTL_CA1_CA1 (32U) /*!< Bit field size in bits for CAU_ROTL_CA1_CA1. */ /*! @brief Format value for bitfield CAU_ROTL_CA1_CA1. */ #define BF_CAU_ROTL_CA1_CA1(v) ((uint32_t)((uint32_t)(v) << BP_CAU_ROTL_CA1_CA1) & BM_CAU_ROTL_CA1_CA1) /*@}*/ /******************************************************************************* * HW_CAU_ROTL_CA2 - General Purpose Register 2 - Rotate Left command ******************************************************************************/ /*! * @brief HW_CAU_ROTL_CA2 - General Purpose Register 2 - Rotate Left command (WO) * * Reset value: 0x00000000U */ typedef union _hw_cau_rotl_ca2 { uint32_t U; struct _hw_cau_rotl_ca2_bitfields { uint32_t CA2 : 32; /*!< [31:0] CA2 */ } B; } hw_cau_rotl_ca2_t; /*! * @name Constants and macros for entire CAU_ROTL_CA2 register */ /*@{*/ #define HW_CAU_ROTL_CA2_ADDR(x) ((x) + 0x9D0U) #define HW_CAU_ROTL_CA2(x) (*(__O hw_cau_rotl_ca2_t *) HW_CAU_ROTL_CA2_ADDR(x)) #define HW_CAU_ROTL_CA2_WR(x, v) (HW_CAU_ROTL_CA2(x).U = (v)) /*@}*/ /* * Constants & macros for individual CAU_ROTL_CA2 bitfields */ /*! * @name Register CAU_ROTL_CA2, field CA2[31:0] (WO) */ /*@{*/ #define BP_CAU_ROTL_CA2_CA2 (0U) /*!< Bit position for CAU_ROTL_CA2_CA2. */ #define BM_CAU_ROTL_CA2_CA2 (0xFFFFFFFFU) /*!< Bit mask for CAU_ROTL_CA2_CA2. */ #define BS_CAU_ROTL_CA2_CA2 (32U) /*!< Bit field size in bits for CAU_ROTL_CA2_CA2. */ /*! @brief Format value for bitfield CAU_ROTL_CA2_CA2. */ #define BF_CAU_ROTL_CA2_CA2(v) ((uint32_t)((uint32_t)(v) << BP_CAU_ROTL_CA2_CA2) & BM_CAU_ROTL_CA2_CA2) /*@}*/ /******************************************************************************* * HW_CAU_ROTL_CA3 - General Purpose Register 3 - Rotate Left command ******************************************************************************/ /*! * @brief HW_CAU_ROTL_CA3 - General Purpose Register 3 - Rotate Left command (WO) * * Reset value: 0x00000000U */ typedef union _hw_cau_rotl_ca3 { uint32_t U; struct _hw_cau_rotl_ca3_bitfields { uint32_t CA3 : 32; /*!< [31:0] CA3 */ } B; } hw_cau_rotl_ca3_t; /*! * @name Constants and macros for entire CAU_ROTL_CA3 register */ /*@{*/ #define HW_CAU_ROTL_CA3_ADDR(x) ((x) + 0x9D4U) #define HW_CAU_ROTL_CA3(x) (*(__O hw_cau_rotl_ca3_t *) HW_CAU_ROTL_CA3_ADDR(x)) #define HW_CAU_ROTL_CA3_WR(x, v) (HW_CAU_ROTL_CA3(x).U = (v)) /*@}*/ /* * Constants & macros for individual CAU_ROTL_CA3 bitfields */ /*! * @name Register CAU_ROTL_CA3, field CA3[31:0] (WO) */ /*@{*/ #define BP_CAU_ROTL_CA3_CA3 (0U) /*!< Bit position for CAU_ROTL_CA3_CA3. */ #define BM_CAU_ROTL_CA3_CA3 (0xFFFFFFFFU) /*!< Bit mask for CAU_ROTL_CA3_CA3. */ #define BS_CAU_ROTL_CA3_CA3 (32U) /*!< Bit field size in bits for CAU_ROTL_CA3_CA3. */ /*! @brief Format value for bitfield CAU_ROTL_CA3_CA3. */ #define BF_CAU_ROTL_CA3_CA3(v) ((uint32_t)((uint32_t)(v) << BP_CAU_ROTL_CA3_CA3) & BM_CAU_ROTL_CA3_CA3) /*@}*/ /******************************************************************************* * HW_CAU_ROTL_CA4 - General Purpose Register 4 - Rotate Left command ******************************************************************************/ /*! * @brief HW_CAU_ROTL_CA4 - General Purpose Register 4 - Rotate Left command (WO) * * Reset value: 0x00000000U */ typedef union _hw_cau_rotl_ca4 { uint32_t U; struct _hw_cau_rotl_ca4_bitfields { uint32_t CA4 : 32; /*!< [31:0] CA4 */ } B; } hw_cau_rotl_ca4_t; /*! * @name Constants and macros for entire CAU_ROTL_CA4 register */ /*@{*/ #define HW_CAU_ROTL_CA4_ADDR(x) ((x) + 0x9D8U) #define HW_CAU_ROTL_CA4(x) (*(__O hw_cau_rotl_ca4_t *) HW_CAU_ROTL_CA4_ADDR(x)) #define HW_CAU_ROTL_CA4_WR(x, v) (HW_CAU_ROTL_CA4(x).U = (v)) /*@}*/ /* * Constants & macros for individual CAU_ROTL_CA4 bitfields */ /*! * @name Register CAU_ROTL_CA4, field CA4[31:0] (WO) */ /*@{*/ #define BP_CAU_ROTL_CA4_CA4 (0U) /*!< Bit position for CAU_ROTL_CA4_CA4. */ #define BM_CAU_ROTL_CA4_CA4 (0xFFFFFFFFU) /*!< Bit mask for CAU_ROTL_CA4_CA4. */ #define BS_CAU_ROTL_CA4_CA4 (32U) /*!< Bit field size in bits for CAU_ROTL_CA4_CA4. */ /*! @brief Format value for bitfield CAU_ROTL_CA4_CA4. */ #define BF_CAU_ROTL_CA4_CA4(v) ((uint32_t)((uint32_t)(v) << BP_CAU_ROTL_CA4_CA4) & BM_CAU_ROTL_CA4_CA4) /*@}*/ /******************************************************************************* * HW_CAU_ROTL_CA5 - General Purpose Register 5 - Rotate Left command ******************************************************************************/ /*! * @brief HW_CAU_ROTL_CA5 - General Purpose Register 5 - Rotate Left command (WO) * * Reset value: 0x00000000U */ typedef union _hw_cau_rotl_ca5 { uint32_t U; struct _hw_cau_rotl_ca5_bitfields { uint32_t CA5 : 32; /*!< [31:0] CA5 */ } B; } hw_cau_rotl_ca5_t; /*! * @name Constants and macros for entire CAU_ROTL_CA5 register */ /*@{*/ #define HW_CAU_ROTL_CA5_ADDR(x) ((x) + 0x9DCU) #define HW_CAU_ROTL_CA5(x) (*(__O hw_cau_rotl_ca5_t *) HW_CAU_ROTL_CA5_ADDR(x)) #define HW_CAU_ROTL_CA5_WR(x, v) (HW_CAU_ROTL_CA5(x).U = (v)) /*@}*/ /* * Constants & macros for individual CAU_ROTL_CA5 bitfields */ /*! * @name Register CAU_ROTL_CA5, field CA5[31:0] (WO) */ /*@{*/ #define BP_CAU_ROTL_CA5_CA5 (0U) /*!< Bit position for CAU_ROTL_CA5_CA5. */ #define BM_CAU_ROTL_CA5_CA5 (0xFFFFFFFFU) /*!< Bit mask for CAU_ROTL_CA5_CA5. */ #define BS_CAU_ROTL_CA5_CA5 (32U) /*!< Bit field size in bits for CAU_ROTL_CA5_CA5. */ /*! @brief Format value for bitfield CAU_ROTL_CA5_CA5. */ #define BF_CAU_ROTL_CA5_CA5(v) ((uint32_t)((uint32_t)(v) << BP_CAU_ROTL_CA5_CA5) & BM_CAU_ROTL_CA5_CA5) /*@}*/ /******************************************************************************* * HW_CAU_ROTL_CA6 - General Purpose Register 6 - Rotate Left command ******************************************************************************/ /*! * @brief HW_CAU_ROTL_CA6 - General Purpose Register 6 - Rotate Left command (WO) * * Reset value: 0x00000000U */ typedef union _hw_cau_rotl_ca6 { uint32_t U; struct _hw_cau_rotl_ca6_bitfields { uint32_t CA6 : 32; /*!< [31:0] CA6 */ } B; } hw_cau_rotl_ca6_t; /*! * @name Constants and macros for entire CAU_ROTL_CA6 register */ /*@{*/ #define HW_CAU_ROTL_CA6_ADDR(x) ((x) + 0x9E0U) #define HW_CAU_ROTL_CA6(x) (*(__O hw_cau_rotl_ca6_t *) HW_CAU_ROTL_CA6_ADDR(x)) #define HW_CAU_ROTL_CA6_WR(x, v) (HW_CAU_ROTL_CA6(x).U = (v)) /*@}*/ /* * Constants & macros for individual CAU_ROTL_CA6 bitfields */ /*! * @name Register CAU_ROTL_CA6, field CA6[31:0] (WO) */ /*@{*/ #define BP_CAU_ROTL_CA6_CA6 (0U) /*!< Bit position for CAU_ROTL_CA6_CA6. */ #define BM_CAU_ROTL_CA6_CA6 (0xFFFFFFFFU) /*!< Bit mask for CAU_ROTL_CA6_CA6. */ #define BS_CAU_ROTL_CA6_CA6 (32U) /*!< Bit field size in bits for CAU_ROTL_CA6_CA6. */ /*! @brief Format value for bitfield CAU_ROTL_CA6_CA6. */ #define BF_CAU_ROTL_CA6_CA6(v) ((uint32_t)((uint32_t)(v) << BP_CAU_ROTL_CA6_CA6) & BM_CAU_ROTL_CA6_CA6) /*@}*/ /******************************************************************************* * HW_CAU_ROTL_CA7 - General Purpose Register 7 - Rotate Left command ******************************************************************************/ /*! * @brief HW_CAU_ROTL_CA7 - General Purpose Register 7 - Rotate Left command (WO) * * Reset value: 0x00000000U */ typedef union _hw_cau_rotl_ca7 { uint32_t U; struct _hw_cau_rotl_ca7_bitfields { uint32_t CA7 : 32; /*!< [31:0] CA7 */ } B; } hw_cau_rotl_ca7_t; /*! * @name Constants and macros for entire CAU_ROTL_CA7 register */ /*@{*/ #define HW_CAU_ROTL_CA7_ADDR(x) ((x) + 0x9E4U) #define HW_CAU_ROTL_CA7(x) (*(__O hw_cau_rotl_ca7_t *) HW_CAU_ROTL_CA7_ADDR(x)) #define HW_CAU_ROTL_CA7_WR(x, v) (HW_CAU_ROTL_CA7(x).U = (v)) /*@}*/ /* * Constants & macros for individual CAU_ROTL_CA7 bitfields */ /*! * @name Register CAU_ROTL_CA7, field CA7[31:0] (WO) */ /*@{*/ #define BP_CAU_ROTL_CA7_CA7 (0U) /*!< Bit position for CAU_ROTL_CA7_CA7. */ #define BM_CAU_ROTL_CA7_CA7 (0xFFFFFFFFU) /*!< Bit mask for CAU_ROTL_CA7_CA7. */ #define BS_CAU_ROTL_CA7_CA7 (32U) /*!< Bit field size in bits for CAU_ROTL_CA7_CA7. */ /*! @brief Format value for bitfield CAU_ROTL_CA7_CA7. */ #define BF_CAU_ROTL_CA7_CA7(v) ((uint32_t)((uint32_t)(v) << BP_CAU_ROTL_CA7_CA7) & BM_CAU_ROTL_CA7_CA7) /*@}*/ /******************************************************************************* * HW_CAU_ROTL_CA8 - General Purpose Register 8 - Rotate Left command ******************************************************************************/ /*! * @brief HW_CAU_ROTL_CA8 - General Purpose Register 8 - Rotate Left command (WO) * * Reset value: 0x00000000U */ typedef union _hw_cau_rotl_ca8 { uint32_t U; struct _hw_cau_rotl_ca8_bitfields { uint32_t CA8 : 32; /*!< [31:0] CA8 */ } B; } hw_cau_rotl_ca8_t; /*! * @name Constants and macros for entire CAU_ROTL_CA8 register */ /*@{*/ #define HW_CAU_ROTL_CA8_ADDR(x) ((x) + 0x9E8U) #define HW_CAU_ROTL_CA8(x) (*(__O hw_cau_rotl_ca8_t *) HW_CAU_ROTL_CA8_ADDR(x)) #define HW_CAU_ROTL_CA8_WR(x, v) (HW_CAU_ROTL_CA8(x).U = (v)) /*@}*/ /* * Constants & macros for individual CAU_ROTL_CA8 bitfields */ /*! * @name Register CAU_ROTL_CA8, field CA8[31:0] (WO) */ /*@{*/ #define BP_CAU_ROTL_CA8_CA8 (0U) /*!< Bit position for CAU_ROTL_CA8_CA8. */ #define BM_CAU_ROTL_CA8_CA8 (0xFFFFFFFFU) /*!< Bit mask for CAU_ROTL_CA8_CA8. */ #define BS_CAU_ROTL_CA8_CA8 (32U) /*!< Bit field size in bits for CAU_ROTL_CA8_CA8. */ /*! @brief Format value for bitfield CAU_ROTL_CA8_CA8. */ #define BF_CAU_ROTL_CA8_CA8(v) ((uint32_t)((uint32_t)(v) << BP_CAU_ROTL_CA8_CA8) & BM_CAU_ROTL_CA8_CA8) /*@}*/ /******************************************************************************* * HW_CAU_AESC_CASR - Status register - AES Column Operation command ******************************************************************************/ /*! * @brief HW_CAU_AESC_CASR - Status register - AES Column Operation command (WO) * * Reset value: 0x20000000U */ typedef union _hw_cau_aesc_casr { uint32_t U; struct _hw_cau_aesc_casr_bitfields { uint32_t IC : 1; /*!< [0] */ uint32_t DPE : 1; /*!< [1] */ uint32_t RESERVED0 : 26; /*!< [27:2] */ uint32_t VER : 4; /*!< [31:28] CAU version */ } B; } hw_cau_aesc_casr_t; /*! * @name Constants and macros for entire CAU_AESC_CASR register */ /*@{*/ #define HW_CAU_AESC_CASR_ADDR(x) ((x) + 0xB00U) #define HW_CAU_AESC_CASR(x) (*(__O hw_cau_aesc_casr_t *) HW_CAU_AESC_CASR_ADDR(x)) #define HW_CAU_AESC_CASR_WR(x, v) (HW_CAU_AESC_CASR(x).U = (v)) /*@}*/ /* * Constants & macros for individual CAU_AESC_CASR bitfields */ /*! * @name Register CAU_AESC_CASR, field IC[0] (WO) * * Values: * - 0 - No illegal commands issued * - 1 - Illegal command issued */ /*@{*/ #define BP_CAU_AESC_CASR_IC (0U) /*!< Bit position for CAU_AESC_CASR_IC. */ #define BM_CAU_AESC_CASR_IC (0x00000001U) /*!< Bit mask for CAU_AESC_CASR_IC. */ #define BS_CAU_AESC_CASR_IC (1U) /*!< Bit field size in bits for CAU_AESC_CASR_IC. */ /*! @brief Format value for bitfield CAU_AESC_CASR_IC. */ #define BF_CAU_AESC_CASR_IC(v) ((uint32_t)((uint32_t)(v) << BP_CAU_AESC_CASR_IC) & BM_CAU_AESC_CASR_IC) /*@}*/ /*! * @name Register CAU_AESC_CASR, field DPE[1] (WO) * * Values: * - 0 - No error detected * - 1 - DES key parity error detected */ /*@{*/ #define BP_CAU_AESC_CASR_DPE (1U) /*!< Bit position for CAU_AESC_CASR_DPE. */ #define BM_CAU_AESC_CASR_DPE (0x00000002U) /*!< Bit mask for CAU_AESC_CASR_DPE. */ #define BS_CAU_AESC_CASR_DPE (1U) /*!< Bit field size in bits for CAU_AESC_CASR_DPE. */ /*! @brief Format value for bitfield CAU_AESC_CASR_DPE. */ #define BF_CAU_AESC_CASR_DPE(v) ((uint32_t)((uint32_t)(v) << BP_CAU_AESC_CASR_DPE) & BM_CAU_AESC_CASR_DPE) /*@}*/ /*! * @name Register CAU_AESC_CASR, field VER[31:28] (WO) * * Values: * - 0001 - Initial CAU version * - 0010 - Second version, added support for SHA-256 algorithm.(This is the * value on this device) */ /*@{*/ #define BP_CAU_AESC_CASR_VER (28U) /*!< Bit position for CAU_AESC_CASR_VER. */ #define BM_CAU_AESC_CASR_VER (0xF0000000U) /*!< Bit mask for CAU_AESC_CASR_VER. */ #define BS_CAU_AESC_CASR_VER (4U) /*!< Bit field size in bits for CAU_AESC_CASR_VER. */ /*! @brief Format value for bitfield CAU_AESC_CASR_VER. */ #define BF_CAU_AESC_CASR_VER(v) ((uint32_t)((uint32_t)(v) << BP_CAU_AESC_CASR_VER) & BM_CAU_AESC_CASR_VER) /*@}*/ /******************************************************************************* * HW_CAU_AESC_CAA - Accumulator register - AES Column Operation command ******************************************************************************/ /*! * @brief HW_CAU_AESC_CAA - Accumulator register - AES Column Operation command (WO) * * Reset value: 0x00000000U */ typedef union _hw_cau_aesc_caa { uint32_t U; struct _hw_cau_aesc_caa_bitfields { uint32_t ACC : 32; /*!< [31:0] ACC */ } B; } hw_cau_aesc_caa_t; /*! * @name Constants and macros for entire CAU_AESC_CAA register */ /*@{*/ #define HW_CAU_AESC_CAA_ADDR(x) ((x) + 0xB04U) #define HW_CAU_AESC_CAA(x) (*(__O hw_cau_aesc_caa_t *) HW_CAU_AESC_CAA_ADDR(x)) #define HW_CAU_AESC_CAA_WR(x, v) (HW_CAU_AESC_CAA(x).U = (v)) /*@}*/ /* * Constants & macros for individual CAU_AESC_CAA bitfields */ /*! * @name Register CAU_AESC_CAA, field ACC[31:0] (WO) */ /*@{*/ #define BP_CAU_AESC_CAA_ACC (0U) /*!< Bit position for CAU_AESC_CAA_ACC. */ #define BM_CAU_AESC_CAA_ACC (0xFFFFFFFFU) /*!< Bit mask for CAU_AESC_CAA_ACC. */ #define BS_CAU_AESC_CAA_ACC (32U) /*!< Bit field size in bits for CAU_AESC_CAA_ACC. */ /*! @brief Format value for bitfield CAU_AESC_CAA_ACC. */ #define BF_CAU_AESC_CAA_ACC(v) ((uint32_t)((uint32_t)(v) << BP_CAU_AESC_CAA_ACC) & BM_CAU_AESC_CAA_ACC) /*@}*/ /******************************************************************************* * HW_CAU_AESC_CA0 - General Purpose Register 0 - AES Column Operation command ******************************************************************************/ /*! * @brief HW_CAU_AESC_CA0 - General Purpose Register 0 - AES Column Operation command (WO) * * Reset value: 0x00000000U */ typedef union _hw_cau_aesc_ca0 { uint32_t U; struct _hw_cau_aesc_ca0_bitfields { uint32_t CA0 : 32; /*!< [31:0] CA0 */ } B; } hw_cau_aesc_ca0_t; /*! * @name Constants and macros for entire CAU_AESC_CA0 register */ /*@{*/ #define HW_CAU_AESC_CA0_ADDR(x) ((x) + 0xB08U) #define HW_CAU_AESC_CA0(x) (*(__O hw_cau_aesc_ca0_t *) HW_CAU_AESC_CA0_ADDR(x)) #define HW_CAU_AESC_CA0_WR(x, v) (HW_CAU_AESC_CA0(x).U = (v)) /*@}*/ /* * Constants & macros for individual CAU_AESC_CA0 bitfields */ /*! * @name Register CAU_AESC_CA0, field CA0[31:0] (WO) */ /*@{*/ #define BP_CAU_AESC_CA0_CA0 (0U) /*!< Bit position for CAU_AESC_CA0_CA0. */ #define BM_CAU_AESC_CA0_CA0 (0xFFFFFFFFU) /*!< Bit mask for CAU_AESC_CA0_CA0. */ #define BS_CAU_AESC_CA0_CA0 (32U) /*!< Bit field size in bits for CAU_AESC_CA0_CA0. */ /*! @brief Format value for bitfield CAU_AESC_CA0_CA0. */ #define BF_CAU_AESC_CA0_CA0(v) ((uint32_t)((uint32_t)(v) << BP_CAU_AESC_CA0_CA0) & BM_CAU_AESC_CA0_CA0) /*@}*/ /******************************************************************************* * HW_CAU_AESC_CA1 - General Purpose Register 1 - AES Column Operation command ******************************************************************************/ /*! * @brief HW_CAU_AESC_CA1 - General Purpose Register 1 - AES Column Operation command (WO) * * Reset value: 0x00000000U */ typedef union _hw_cau_aesc_ca1 { uint32_t U; struct _hw_cau_aesc_ca1_bitfields { uint32_t CA1 : 32; /*!< [31:0] CA1 */ } B; } hw_cau_aesc_ca1_t; /*! * @name Constants and macros for entire CAU_AESC_CA1 register */ /*@{*/ #define HW_CAU_AESC_CA1_ADDR(x) ((x) + 0xB0CU) #define HW_CAU_AESC_CA1(x) (*(__O hw_cau_aesc_ca1_t *) HW_CAU_AESC_CA1_ADDR(x)) #define HW_CAU_AESC_CA1_WR(x, v) (HW_CAU_AESC_CA1(x).U = (v)) /*@}*/ /* * Constants & macros for individual CAU_AESC_CA1 bitfields */ /*! * @name Register CAU_AESC_CA1, field CA1[31:0] (WO) */ /*@{*/ #define BP_CAU_AESC_CA1_CA1 (0U) /*!< Bit position for CAU_AESC_CA1_CA1. */ #define BM_CAU_AESC_CA1_CA1 (0xFFFFFFFFU) /*!< Bit mask for CAU_AESC_CA1_CA1. */ #define BS_CAU_AESC_CA1_CA1 (32U) /*!< Bit field size in bits for CAU_AESC_CA1_CA1. */ /*! @brief Format value for bitfield CAU_AESC_CA1_CA1. */ #define BF_CAU_AESC_CA1_CA1(v) ((uint32_t)((uint32_t)(v) << BP_CAU_AESC_CA1_CA1) & BM_CAU_AESC_CA1_CA1) /*@}*/ /******************************************************************************* * HW_CAU_AESC_CA2 - General Purpose Register 2 - AES Column Operation command ******************************************************************************/ /*! * @brief HW_CAU_AESC_CA2 - General Purpose Register 2 - AES Column Operation command (WO) * * Reset value: 0x00000000U */ typedef union _hw_cau_aesc_ca2 { uint32_t U; struct _hw_cau_aesc_ca2_bitfields { uint32_t CA2 : 32; /*!< [31:0] CA2 */ } B; } hw_cau_aesc_ca2_t; /*! * @name Constants and macros for entire CAU_AESC_CA2 register */ /*@{*/ #define HW_CAU_AESC_CA2_ADDR(x) ((x) + 0xB10U) #define HW_CAU_AESC_CA2(x) (*(__O hw_cau_aesc_ca2_t *) HW_CAU_AESC_CA2_ADDR(x)) #define HW_CAU_AESC_CA2_WR(x, v) (HW_CAU_AESC_CA2(x).U = (v)) /*@}*/ /* * Constants & macros for individual CAU_AESC_CA2 bitfields */ /*! * @name Register CAU_AESC_CA2, field CA2[31:0] (WO) */ /*@{*/ #define BP_CAU_AESC_CA2_CA2 (0U) /*!< Bit position for CAU_AESC_CA2_CA2. */ #define BM_CAU_AESC_CA2_CA2 (0xFFFFFFFFU) /*!< Bit mask for CAU_AESC_CA2_CA2. */ #define BS_CAU_AESC_CA2_CA2 (32U) /*!< Bit field size in bits for CAU_AESC_CA2_CA2. */ /*! @brief Format value for bitfield CAU_AESC_CA2_CA2. */ #define BF_CAU_AESC_CA2_CA2(v) ((uint32_t)((uint32_t)(v) << BP_CAU_AESC_CA2_CA2) & BM_CAU_AESC_CA2_CA2) /*@}*/ /******************************************************************************* * HW_CAU_AESC_CA3 - General Purpose Register 3 - AES Column Operation command ******************************************************************************/ /*! * @brief HW_CAU_AESC_CA3 - General Purpose Register 3 - AES Column Operation command (WO) * * Reset value: 0x00000000U */ typedef union _hw_cau_aesc_ca3 { uint32_t U; struct _hw_cau_aesc_ca3_bitfields { uint32_t CA3 : 32; /*!< [31:0] CA3 */ } B; } hw_cau_aesc_ca3_t; /*! * @name Constants and macros for entire CAU_AESC_CA3 register */ /*@{*/ #define HW_CAU_AESC_CA3_ADDR(x) ((x) + 0xB14U) #define HW_CAU_AESC_CA3(x) (*(__O hw_cau_aesc_ca3_t *) HW_CAU_AESC_CA3_ADDR(x)) #define HW_CAU_AESC_CA3_WR(x, v) (HW_CAU_AESC_CA3(x).U = (v)) /*@}*/ /* * Constants & macros for individual CAU_AESC_CA3 bitfields */ /*! * @name Register CAU_AESC_CA3, field CA3[31:0] (WO) */ /*@{*/ #define BP_CAU_AESC_CA3_CA3 (0U) /*!< Bit position for CAU_AESC_CA3_CA3. */ #define BM_CAU_AESC_CA3_CA3 (0xFFFFFFFFU) /*!< Bit mask for CAU_AESC_CA3_CA3. */ #define BS_CAU_AESC_CA3_CA3 (32U) /*!< Bit field size in bits for CAU_AESC_CA3_CA3. */ /*! @brief Format value for bitfield CAU_AESC_CA3_CA3. */ #define BF_CAU_AESC_CA3_CA3(v) ((uint32_t)((uint32_t)(v) << BP_CAU_AESC_CA3_CA3) & BM_CAU_AESC_CA3_CA3) /*@}*/ /******************************************************************************* * HW_CAU_AESC_CA4 - General Purpose Register 4 - AES Column Operation command ******************************************************************************/ /*! * @brief HW_CAU_AESC_CA4 - General Purpose Register 4 - AES Column Operation command (WO) * * Reset value: 0x00000000U */ typedef union _hw_cau_aesc_ca4 { uint32_t U; struct _hw_cau_aesc_ca4_bitfields { uint32_t CA4 : 32; /*!< [31:0] CA4 */ } B; } hw_cau_aesc_ca4_t; /*! * @name Constants and macros for entire CAU_AESC_CA4 register */ /*@{*/ #define HW_CAU_AESC_CA4_ADDR(x) ((x) + 0xB18U) #define HW_CAU_AESC_CA4(x) (*(__O hw_cau_aesc_ca4_t *) HW_CAU_AESC_CA4_ADDR(x)) #define HW_CAU_AESC_CA4_WR(x, v) (HW_CAU_AESC_CA4(x).U = (v)) /*@}*/ /* * Constants & macros for individual CAU_AESC_CA4 bitfields */ /*! * @name Register CAU_AESC_CA4, field CA4[31:0] (WO) */ /*@{*/ #define BP_CAU_AESC_CA4_CA4 (0U) /*!< Bit position for CAU_AESC_CA4_CA4. */ #define BM_CAU_AESC_CA4_CA4 (0xFFFFFFFFU) /*!< Bit mask for CAU_AESC_CA4_CA4. */ #define BS_CAU_AESC_CA4_CA4 (32U) /*!< Bit field size in bits for CAU_AESC_CA4_CA4. */ /*! @brief Format value for bitfield CAU_AESC_CA4_CA4. */ #define BF_CAU_AESC_CA4_CA4(v) ((uint32_t)((uint32_t)(v) << BP_CAU_AESC_CA4_CA4) & BM_CAU_AESC_CA4_CA4) /*@}*/ /******************************************************************************* * HW_CAU_AESC_CA5 - General Purpose Register 5 - AES Column Operation command ******************************************************************************/ /*! * @brief HW_CAU_AESC_CA5 - General Purpose Register 5 - AES Column Operation command (WO) * * Reset value: 0x00000000U */ typedef union _hw_cau_aesc_ca5 { uint32_t U; struct _hw_cau_aesc_ca5_bitfields { uint32_t CA5 : 32; /*!< [31:0] CA5 */ } B; } hw_cau_aesc_ca5_t; /*! * @name Constants and macros for entire CAU_AESC_CA5 register */ /*@{*/ #define HW_CAU_AESC_CA5_ADDR(x) ((x) + 0xB1CU) #define HW_CAU_AESC_CA5(x) (*(__O hw_cau_aesc_ca5_t *) HW_CAU_AESC_CA5_ADDR(x)) #define HW_CAU_AESC_CA5_WR(x, v) (HW_CAU_AESC_CA5(x).U = (v)) /*@}*/ /* * Constants & macros for individual CAU_AESC_CA5 bitfields */ /*! * @name Register CAU_AESC_CA5, field CA5[31:0] (WO) */ /*@{*/ #define BP_CAU_AESC_CA5_CA5 (0U) /*!< Bit position for CAU_AESC_CA5_CA5. */ #define BM_CAU_AESC_CA5_CA5 (0xFFFFFFFFU) /*!< Bit mask for CAU_AESC_CA5_CA5. */ #define BS_CAU_AESC_CA5_CA5 (32U) /*!< Bit field size in bits for CAU_AESC_CA5_CA5. */ /*! @brief Format value for bitfield CAU_AESC_CA5_CA5. */ #define BF_CAU_AESC_CA5_CA5(v) ((uint32_t)((uint32_t)(v) << BP_CAU_AESC_CA5_CA5) & BM_CAU_AESC_CA5_CA5) /*@}*/ /******************************************************************************* * HW_CAU_AESC_CA6 - General Purpose Register 6 - AES Column Operation command ******************************************************************************/ /*! * @brief HW_CAU_AESC_CA6 - General Purpose Register 6 - AES Column Operation command (WO) * * Reset value: 0x00000000U */ typedef union _hw_cau_aesc_ca6 { uint32_t U; struct _hw_cau_aesc_ca6_bitfields { uint32_t CA6 : 32; /*!< [31:0] CA6 */ } B; } hw_cau_aesc_ca6_t; /*! * @name Constants and macros for entire CAU_AESC_CA6 register */ /*@{*/ #define HW_CAU_AESC_CA6_ADDR(x) ((x) + 0xB20U) #define HW_CAU_AESC_CA6(x) (*(__O hw_cau_aesc_ca6_t *) HW_CAU_AESC_CA6_ADDR(x)) #define HW_CAU_AESC_CA6_WR(x, v) (HW_CAU_AESC_CA6(x).U = (v)) /*@}*/ /* * Constants & macros for individual CAU_AESC_CA6 bitfields */ /*! * @name Register CAU_AESC_CA6, field CA6[31:0] (WO) */ /*@{*/ #define BP_CAU_AESC_CA6_CA6 (0U) /*!< Bit position for CAU_AESC_CA6_CA6. */ #define BM_CAU_AESC_CA6_CA6 (0xFFFFFFFFU) /*!< Bit mask for CAU_AESC_CA6_CA6. */ #define BS_CAU_AESC_CA6_CA6 (32U) /*!< Bit field size in bits for CAU_AESC_CA6_CA6. */ /*! @brief Format value for bitfield CAU_AESC_CA6_CA6. */ #define BF_CAU_AESC_CA6_CA6(v) ((uint32_t)((uint32_t)(v) << BP_CAU_AESC_CA6_CA6) & BM_CAU_AESC_CA6_CA6) /*@}*/ /******************************************************************************* * HW_CAU_AESC_CA7 - General Purpose Register 7 - AES Column Operation command ******************************************************************************/ /*! * @brief HW_CAU_AESC_CA7 - General Purpose Register 7 - AES Column Operation command (WO) * * Reset value: 0x00000000U */ typedef union _hw_cau_aesc_ca7 { uint32_t U; struct _hw_cau_aesc_ca7_bitfields { uint32_t CA7 : 32; /*!< [31:0] CA7 */ } B; } hw_cau_aesc_ca7_t; /*! * @name Constants and macros for entire CAU_AESC_CA7 register */ /*@{*/ #define HW_CAU_AESC_CA7_ADDR(x) ((x) + 0xB24U) #define HW_CAU_AESC_CA7(x) (*(__O hw_cau_aesc_ca7_t *) HW_CAU_AESC_CA7_ADDR(x)) #define HW_CAU_AESC_CA7_WR(x, v) (HW_CAU_AESC_CA7(x).U = (v)) /*@}*/ /* * Constants & macros for individual CAU_AESC_CA7 bitfields */ /*! * @name Register CAU_AESC_CA7, field CA7[31:0] (WO) */ /*@{*/ #define BP_CAU_AESC_CA7_CA7 (0U) /*!< Bit position for CAU_AESC_CA7_CA7. */ #define BM_CAU_AESC_CA7_CA7 (0xFFFFFFFFU) /*!< Bit mask for CAU_AESC_CA7_CA7. */ #define BS_CAU_AESC_CA7_CA7 (32U) /*!< Bit field size in bits for CAU_AESC_CA7_CA7. */ /*! @brief Format value for bitfield CAU_AESC_CA7_CA7. */ #define BF_CAU_AESC_CA7_CA7(v) ((uint32_t)((uint32_t)(v) << BP_CAU_AESC_CA7_CA7) & BM_CAU_AESC_CA7_CA7) /*@}*/ /******************************************************************************* * HW_CAU_AESC_CA8 - General Purpose Register 8 - AES Column Operation command ******************************************************************************/ /*! * @brief HW_CAU_AESC_CA8 - General Purpose Register 8 - AES Column Operation command (WO) * * Reset value: 0x00000000U */ typedef union _hw_cau_aesc_ca8 { uint32_t U; struct _hw_cau_aesc_ca8_bitfields { uint32_t CA8 : 32; /*!< [31:0] CA8 */ } B; } hw_cau_aesc_ca8_t; /*! * @name Constants and macros for entire CAU_AESC_CA8 register */ /*@{*/ #define HW_CAU_AESC_CA8_ADDR(x) ((x) + 0xB28U) #define HW_CAU_AESC_CA8(x) (*(__O hw_cau_aesc_ca8_t *) HW_CAU_AESC_CA8_ADDR(x)) #define HW_CAU_AESC_CA8_WR(x, v) (HW_CAU_AESC_CA8(x).U = (v)) /*@}*/ /* * Constants & macros for individual CAU_AESC_CA8 bitfields */ /*! * @name Register CAU_AESC_CA8, field CA8[31:0] (WO) */ /*@{*/ #define BP_CAU_AESC_CA8_CA8 (0U) /*!< Bit position for CAU_AESC_CA8_CA8. */ #define BM_CAU_AESC_CA8_CA8 (0xFFFFFFFFU) /*!< Bit mask for CAU_AESC_CA8_CA8. */ #define BS_CAU_AESC_CA8_CA8 (32U) /*!< Bit field size in bits for CAU_AESC_CA8_CA8. */ /*! @brief Format value for bitfield CAU_AESC_CA8_CA8. */ #define BF_CAU_AESC_CA8_CA8(v) ((uint32_t)((uint32_t)(v) << BP_CAU_AESC_CA8_CA8) & BM_CAU_AESC_CA8_CA8) /*@}*/ /******************************************************************************* * HW_CAU_AESIC_CASR - Status register - AES Inverse Column Operation command ******************************************************************************/ /*! * @brief HW_CAU_AESIC_CASR - Status register - AES Inverse Column Operation command (WO) * * Reset value: 0x20000000U */ typedef union _hw_cau_aesic_casr { uint32_t U; struct _hw_cau_aesic_casr_bitfields { uint32_t IC : 1; /*!< [0] */ uint32_t DPE : 1; /*!< [1] */ uint32_t RESERVED0 : 26; /*!< [27:2] */ uint32_t VER : 4; /*!< [31:28] CAU version */ } B; } hw_cau_aesic_casr_t; /*! * @name Constants and macros for entire CAU_AESIC_CASR register */ /*@{*/ #define HW_CAU_AESIC_CASR_ADDR(x) ((x) + 0xB40U) #define HW_CAU_AESIC_CASR(x) (*(__O hw_cau_aesic_casr_t *) HW_CAU_AESIC_CASR_ADDR(x)) #define HW_CAU_AESIC_CASR_WR(x, v) (HW_CAU_AESIC_CASR(x).U = (v)) /*@}*/ /* * Constants & macros for individual CAU_AESIC_CASR bitfields */ /*! * @name Register CAU_AESIC_CASR, field IC[0] (WO) * * Values: * - 0 - No illegal commands issued * - 1 - Illegal command issued */ /*@{*/ #define BP_CAU_AESIC_CASR_IC (0U) /*!< Bit position for CAU_AESIC_CASR_IC. */ #define BM_CAU_AESIC_CASR_IC (0x00000001U) /*!< Bit mask for CAU_AESIC_CASR_IC. */ #define BS_CAU_AESIC_CASR_IC (1U) /*!< Bit field size in bits for CAU_AESIC_CASR_IC. */ /*! @brief Format value for bitfield CAU_AESIC_CASR_IC. */ #define BF_CAU_AESIC_CASR_IC(v) ((uint32_t)((uint32_t)(v) << BP_CAU_AESIC_CASR_IC) & BM_CAU_AESIC_CASR_IC) /*@}*/ /*! * @name Register CAU_AESIC_CASR, field DPE[1] (WO) * * Values: * - 0 - No error detected * - 1 - DES key parity error detected */ /*@{*/ #define BP_CAU_AESIC_CASR_DPE (1U) /*!< Bit position for CAU_AESIC_CASR_DPE. */ #define BM_CAU_AESIC_CASR_DPE (0x00000002U) /*!< Bit mask for CAU_AESIC_CASR_DPE. */ #define BS_CAU_AESIC_CASR_DPE (1U) /*!< Bit field size in bits for CAU_AESIC_CASR_DPE. */ /*! @brief Format value for bitfield CAU_AESIC_CASR_DPE. */ #define BF_CAU_AESIC_CASR_DPE(v) ((uint32_t)((uint32_t)(v) << BP_CAU_AESIC_CASR_DPE) & BM_CAU_AESIC_CASR_DPE) /*@}*/ /*! * @name Register CAU_AESIC_CASR, field VER[31:28] (WO) * * Values: * - 0001 - Initial CAU version * - 0010 - Second version, added support for SHA-256 algorithm.(This is the * value on this device) */ /*@{*/ #define BP_CAU_AESIC_CASR_VER (28U) /*!< Bit position for CAU_AESIC_CASR_VER. */ #define BM_CAU_AESIC_CASR_VER (0xF0000000U) /*!< Bit mask for CAU_AESIC_CASR_VER. */ #define BS_CAU_AESIC_CASR_VER (4U) /*!< Bit field size in bits for CAU_AESIC_CASR_VER. */ /*! @brief Format value for bitfield CAU_AESIC_CASR_VER. */ #define BF_CAU_AESIC_CASR_VER(v) ((uint32_t)((uint32_t)(v) << BP_CAU_AESIC_CASR_VER) & BM_CAU_AESIC_CASR_VER) /*@}*/ /******************************************************************************* * HW_CAU_AESIC_CAA - Accumulator register - AES Inverse Column Operation command ******************************************************************************/ /*! * @brief HW_CAU_AESIC_CAA - Accumulator register - AES Inverse Column Operation command (WO) * * Reset value: 0x00000000U */ typedef union _hw_cau_aesic_caa { uint32_t U; struct _hw_cau_aesic_caa_bitfields { uint32_t ACC : 32; /*!< [31:0] ACC */ } B; } hw_cau_aesic_caa_t; /*! * @name Constants and macros for entire CAU_AESIC_CAA register */ /*@{*/ #define HW_CAU_AESIC_CAA_ADDR(x) ((x) + 0xB44U) #define HW_CAU_AESIC_CAA(x) (*(__O hw_cau_aesic_caa_t *) HW_CAU_AESIC_CAA_ADDR(x)) #define HW_CAU_AESIC_CAA_WR(x, v) (HW_CAU_AESIC_CAA(x).U = (v)) /*@}*/ /* * Constants & macros for individual CAU_AESIC_CAA bitfields */ /*! * @name Register CAU_AESIC_CAA, field ACC[31:0] (WO) */ /*@{*/ #define BP_CAU_AESIC_CAA_ACC (0U) /*!< Bit position for CAU_AESIC_CAA_ACC. */ #define BM_CAU_AESIC_CAA_ACC (0xFFFFFFFFU) /*!< Bit mask for CAU_AESIC_CAA_ACC. */ #define BS_CAU_AESIC_CAA_ACC (32U) /*!< Bit field size in bits for CAU_AESIC_CAA_ACC. */ /*! @brief Format value for bitfield CAU_AESIC_CAA_ACC. */ #define BF_CAU_AESIC_CAA_ACC(v) ((uint32_t)((uint32_t)(v) << BP_CAU_AESIC_CAA_ACC) & BM_CAU_AESIC_CAA_ACC) /*@}*/ /******************************************************************************* * HW_CAU_AESIC_CA0 - General Purpose Register 0 - AES Inverse Column Operation command ******************************************************************************/ /*! * @brief HW_CAU_AESIC_CA0 - General Purpose Register 0 - AES Inverse Column Operation command (WO) * * Reset value: 0x00000000U */ typedef union _hw_cau_aesic_ca0 { uint32_t U; struct _hw_cau_aesic_ca0_bitfields { uint32_t CA0 : 32; /*!< [31:0] CA0 */ } B; } hw_cau_aesic_ca0_t; /*! * @name Constants and macros for entire CAU_AESIC_CA0 register */ /*@{*/ #define HW_CAU_AESIC_CA0_ADDR(x) ((x) + 0xB48U) #define HW_CAU_AESIC_CA0(x) (*(__O hw_cau_aesic_ca0_t *) HW_CAU_AESIC_CA0_ADDR(x)) #define HW_CAU_AESIC_CA0_WR(x, v) (HW_CAU_AESIC_CA0(x).U = (v)) /*@}*/ /* * Constants & macros for individual CAU_AESIC_CA0 bitfields */ /*! * @name Register CAU_AESIC_CA0, field CA0[31:0] (WO) */ /*@{*/ #define BP_CAU_AESIC_CA0_CA0 (0U) /*!< Bit position for CAU_AESIC_CA0_CA0. */ #define BM_CAU_AESIC_CA0_CA0 (0xFFFFFFFFU) /*!< Bit mask for CAU_AESIC_CA0_CA0. */ #define BS_CAU_AESIC_CA0_CA0 (32U) /*!< Bit field size in bits for CAU_AESIC_CA0_CA0. */ /*! @brief Format value for bitfield CAU_AESIC_CA0_CA0. */ #define BF_CAU_AESIC_CA0_CA0(v) ((uint32_t)((uint32_t)(v) << BP_CAU_AESIC_CA0_CA0) & BM_CAU_AESIC_CA0_CA0) /*@}*/ /******************************************************************************* * HW_CAU_AESIC_CA1 - General Purpose Register 1 - AES Inverse Column Operation command ******************************************************************************/ /*! * @brief HW_CAU_AESIC_CA1 - General Purpose Register 1 - AES Inverse Column Operation command (WO) * * Reset value: 0x00000000U */ typedef union _hw_cau_aesic_ca1 { uint32_t U; struct _hw_cau_aesic_ca1_bitfields { uint32_t CA1 : 32; /*!< [31:0] CA1 */ } B; } hw_cau_aesic_ca1_t; /*! * @name Constants and macros for entire CAU_AESIC_CA1 register */ /*@{*/ #define HW_CAU_AESIC_CA1_ADDR(x) ((x) + 0xB4CU) #define HW_CAU_AESIC_CA1(x) (*(__O hw_cau_aesic_ca1_t *) HW_CAU_AESIC_CA1_ADDR(x)) #define HW_CAU_AESIC_CA1_WR(x, v) (HW_CAU_AESIC_CA1(x).U = (v)) /*@}*/ /* * Constants & macros for individual CAU_AESIC_CA1 bitfields */ /*! * @name Register CAU_AESIC_CA1, field CA1[31:0] (WO) */ /*@{*/ #define BP_CAU_AESIC_CA1_CA1 (0U) /*!< Bit position for CAU_AESIC_CA1_CA1. */ #define BM_CAU_AESIC_CA1_CA1 (0xFFFFFFFFU) /*!< Bit mask for CAU_AESIC_CA1_CA1. */ #define BS_CAU_AESIC_CA1_CA1 (32U) /*!< Bit field size in bits for CAU_AESIC_CA1_CA1. */ /*! @brief Format value for bitfield CAU_AESIC_CA1_CA1. */ #define BF_CAU_AESIC_CA1_CA1(v) ((uint32_t)((uint32_t)(v) << BP_CAU_AESIC_CA1_CA1) & BM_CAU_AESIC_CA1_CA1) /*@}*/ /******************************************************************************* * HW_CAU_AESIC_CA2 - General Purpose Register 2 - AES Inverse Column Operation command ******************************************************************************/ /*! * @brief HW_CAU_AESIC_CA2 - General Purpose Register 2 - AES Inverse Column Operation command (WO) * * Reset value: 0x00000000U */ typedef union _hw_cau_aesic_ca2 { uint32_t U; struct _hw_cau_aesic_ca2_bitfields { uint32_t CA2 : 32; /*!< [31:0] CA2 */ } B; } hw_cau_aesic_ca2_t; /*! * @name Constants and macros for entire CAU_AESIC_CA2 register */ /*@{*/ #define HW_CAU_AESIC_CA2_ADDR(x) ((x) + 0xB50U) #define HW_CAU_AESIC_CA2(x) (*(__O hw_cau_aesic_ca2_t *) HW_CAU_AESIC_CA2_ADDR(x)) #define HW_CAU_AESIC_CA2_WR(x, v) (HW_CAU_AESIC_CA2(x).U = (v)) /*@}*/ /* * Constants & macros for individual CAU_AESIC_CA2 bitfields */ /*! * @name Register CAU_AESIC_CA2, field CA2[31:0] (WO) */ /*@{*/ #define BP_CAU_AESIC_CA2_CA2 (0U) /*!< Bit position for CAU_AESIC_CA2_CA2. */ #define BM_CAU_AESIC_CA2_CA2 (0xFFFFFFFFU) /*!< Bit mask for CAU_AESIC_CA2_CA2. */ #define BS_CAU_AESIC_CA2_CA2 (32U) /*!< Bit field size in bits for CAU_AESIC_CA2_CA2. */ /*! @brief Format value for bitfield CAU_AESIC_CA2_CA2. */ #define BF_CAU_AESIC_CA2_CA2(v) ((uint32_t)((uint32_t)(v) << BP_CAU_AESIC_CA2_CA2) & BM_CAU_AESIC_CA2_CA2) /*@}*/ /******************************************************************************* * HW_CAU_AESIC_CA3 - General Purpose Register 3 - AES Inverse Column Operation command ******************************************************************************/ /*! * @brief HW_CAU_AESIC_CA3 - General Purpose Register 3 - AES Inverse Column Operation command (WO) * * Reset value: 0x00000000U */ typedef union _hw_cau_aesic_ca3 { uint32_t U; struct _hw_cau_aesic_ca3_bitfields { uint32_t CA3 : 32; /*!< [31:0] CA3 */ } B; } hw_cau_aesic_ca3_t; /*! * @name Constants and macros for entire CAU_AESIC_CA3 register */ /*@{*/ #define HW_CAU_AESIC_CA3_ADDR(x) ((x) + 0xB54U) #define HW_CAU_AESIC_CA3(x) (*(__O hw_cau_aesic_ca3_t *) HW_CAU_AESIC_CA3_ADDR(x)) #define HW_CAU_AESIC_CA3_WR(x, v) (HW_CAU_AESIC_CA3(x).U = (v)) /*@}*/ /* * Constants & macros for individual CAU_AESIC_CA3 bitfields */ /*! * @name Register CAU_AESIC_CA3, field CA3[31:0] (WO) */ /*@{*/ #define BP_CAU_AESIC_CA3_CA3 (0U) /*!< Bit position for CAU_AESIC_CA3_CA3. */ #define BM_CAU_AESIC_CA3_CA3 (0xFFFFFFFFU) /*!< Bit mask for CAU_AESIC_CA3_CA3. */ #define BS_CAU_AESIC_CA3_CA3 (32U) /*!< Bit field size in bits for CAU_AESIC_CA3_CA3. */ /*! @brief Format value for bitfield CAU_AESIC_CA3_CA3. */ #define BF_CAU_AESIC_CA3_CA3(v) ((uint32_t)((uint32_t)(v) << BP_CAU_AESIC_CA3_CA3) & BM_CAU_AESIC_CA3_CA3) /*@}*/ /******************************************************************************* * HW_CAU_AESIC_CA4 - General Purpose Register 4 - AES Inverse Column Operation command ******************************************************************************/ /*! * @brief HW_CAU_AESIC_CA4 - General Purpose Register 4 - AES Inverse Column Operation command (WO) * * Reset value: 0x00000000U */ typedef union _hw_cau_aesic_ca4 { uint32_t U; struct _hw_cau_aesic_ca4_bitfields { uint32_t CA4 : 32; /*!< [31:0] CA4 */ } B; } hw_cau_aesic_ca4_t; /*! * @name Constants and macros for entire CAU_AESIC_CA4 register */ /*@{*/ #define HW_CAU_AESIC_CA4_ADDR(x) ((x) + 0xB58U) #define HW_CAU_AESIC_CA4(x) (*(__O hw_cau_aesic_ca4_t *) HW_CAU_AESIC_CA4_ADDR(x)) #define HW_CAU_AESIC_CA4_WR(x, v) (HW_CAU_AESIC_CA4(x).U = (v)) /*@}*/ /* * Constants & macros for individual CAU_AESIC_CA4 bitfields */ /*! * @name Register CAU_AESIC_CA4, field CA4[31:0] (WO) */ /*@{*/ #define BP_CAU_AESIC_CA4_CA4 (0U) /*!< Bit position for CAU_AESIC_CA4_CA4. */ #define BM_CAU_AESIC_CA4_CA4 (0xFFFFFFFFU) /*!< Bit mask for CAU_AESIC_CA4_CA4. */ #define BS_CAU_AESIC_CA4_CA4 (32U) /*!< Bit field size in bits for CAU_AESIC_CA4_CA4. */ /*! @brief Format value for bitfield CAU_AESIC_CA4_CA4. */ #define BF_CAU_AESIC_CA4_CA4(v) ((uint32_t)((uint32_t)(v) << BP_CAU_AESIC_CA4_CA4) & BM_CAU_AESIC_CA4_CA4) /*@}*/ /******************************************************************************* * HW_CAU_AESIC_CA5 - General Purpose Register 5 - AES Inverse Column Operation command ******************************************************************************/ /*! * @brief HW_CAU_AESIC_CA5 - General Purpose Register 5 - AES Inverse Column Operation command (WO) * * Reset value: 0x00000000U */ typedef union _hw_cau_aesic_ca5 { uint32_t U; struct _hw_cau_aesic_ca5_bitfields { uint32_t CA5 : 32; /*!< [31:0] CA5 */ } B; } hw_cau_aesic_ca5_t; /*! * @name Constants and macros for entire CAU_AESIC_CA5 register */ /*@{*/ #define HW_CAU_AESIC_CA5_ADDR(x) ((x) + 0xB5CU) #define HW_CAU_AESIC_CA5(x) (*(__O hw_cau_aesic_ca5_t *) HW_CAU_AESIC_CA5_ADDR(x)) #define HW_CAU_AESIC_CA5_WR(x, v) (HW_CAU_AESIC_CA5(x).U = (v)) /*@}*/ /* * Constants & macros for individual CAU_AESIC_CA5 bitfields */ /*! * @name Register CAU_AESIC_CA5, field CA5[31:0] (WO) */ /*@{*/ #define BP_CAU_AESIC_CA5_CA5 (0U) /*!< Bit position for CAU_AESIC_CA5_CA5. */ #define BM_CAU_AESIC_CA5_CA5 (0xFFFFFFFFU) /*!< Bit mask for CAU_AESIC_CA5_CA5. */ #define BS_CAU_AESIC_CA5_CA5 (32U) /*!< Bit field size in bits for CAU_AESIC_CA5_CA5. */ /*! @brief Format value for bitfield CAU_AESIC_CA5_CA5. */ #define BF_CAU_AESIC_CA5_CA5(v) ((uint32_t)((uint32_t)(v) << BP_CAU_AESIC_CA5_CA5) & BM_CAU_AESIC_CA5_CA5) /*@}*/ /******************************************************************************* * HW_CAU_AESIC_CA6 - General Purpose Register 6 - AES Inverse Column Operation command ******************************************************************************/ /*! * @brief HW_CAU_AESIC_CA6 - General Purpose Register 6 - AES Inverse Column Operation command (WO) * * Reset value: 0x00000000U */ typedef union _hw_cau_aesic_ca6 { uint32_t U; struct _hw_cau_aesic_ca6_bitfields { uint32_t CA6 : 32; /*!< [31:0] CA6 */ } B; } hw_cau_aesic_ca6_t; /*! * @name Constants and macros for entire CAU_AESIC_CA6 register */ /*@{*/ #define HW_CAU_AESIC_CA6_ADDR(x) ((x) + 0xB60U) #define HW_CAU_AESIC_CA6(x) (*(__O hw_cau_aesic_ca6_t *) HW_CAU_AESIC_CA6_ADDR(x)) #define HW_CAU_AESIC_CA6_WR(x, v) (HW_CAU_AESIC_CA6(x).U = (v)) /*@}*/ /* * Constants & macros for individual CAU_AESIC_CA6 bitfields */ /*! * @name Register CAU_AESIC_CA6, field CA6[31:0] (WO) */ /*@{*/ #define BP_CAU_AESIC_CA6_CA6 (0U) /*!< Bit position for CAU_AESIC_CA6_CA6. */ #define BM_CAU_AESIC_CA6_CA6 (0xFFFFFFFFU) /*!< Bit mask for CAU_AESIC_CA6_CA6. */ #define BS_CAU_AESIC_CA6_CA6 (32U) /*!< Bit field size in bits for CAU_AESIC_CA6_CA6. */ /*! @brief Format value for bitfield CAU_AESIC_CA6_CA6. */ #define BF_CAU_AESIC_CA6_CA6(v) ((uint32_t)((uint32_t)(v) << BP_CAU_AESIC_CA6_CA6) & BM_CAU_AESIC_CA6_CA6) /*@}*/ /******************************************************************************* * HW_CAU_AESIC_CA7 - General Purpose Register 7 - AES Inverse Column Operation command ******************************************************************************/ /*! * @brief HW_CAU_AESIC_CA7 - General Purpose Register 7 - AES Inverse Column Operation command (WO) * * Reset value: 0x00000000U */ typedef union _hw_cau_aesic_ca7 { uint32_t U; struct _hw_cau_aesic_ca7_bitfields { uint32_t CA7 : 32; /*!< [31:0] CA7 */ } B; } hw_cau_aesic_ca7_t; /*! * @name Constants and macros for entire CAU_AESIC_CA7 register */ /*@{*/ #define HW_CAU_AESIC_CA7_ADDR(x) ((x) + 0xB64U) #define HW_CAU_AESIC_CA7(x) (*(__O hw_cau_aesic_ca7_t *) HW_CAU_AESIC_CA7_ADDR(x)) #define HW_CAU_AESIC_CA7_WR(x, v) (HW_CAU_AESIC_CA7(x).U = (v)) /*@}*/ /* * Constants & macros for individual CAU_AESIC_CA7 bitfields */ /*! * @name Register CAU_AESIC_CA7, field CA7[31:0] (WO) */ /*@{*/ #define BP_CAU_AESIC_CA7_CA7 (0U) /*!< Bit position for CAU_AESIC_CA7_CA7. */ #define BM_CAU_AESIC_CA7_CA7 (0xFFFFFFFFU) /*!< Bit mask for CAU_AESIC_CA7_CA7. */ #define BS_CAU_AESIC_CA7_CA7 (32U) /*!< Bit field size in bits for CAU_AESIC_CA7_CA7. */ /*! @brief Format value for bitfield CAU_AESIC_CA7_CA7. */ #define BF_CAU_AESIC_CA7_CA7(v) ((uint32_t)((uint32_t)(v) << BP_CAU_AESIC_CA7_CA7) & BM_CAU_AESIC_CA7_CA7) /*@}*/ /******************************************************************************* * HW_CAU_AESIC_CA8 - General Purpose Register 8 - AES Inverse Column Operation command ******************************************************************************/ /*! * @brief HW_CAU_AESIC_CA8 - General Purpose Register 8 - AES Inverse Column Operation command (WO) * * Reset value: 0x00000000U */ typedef union _hw_cau_aesic_ca8 { uint32_t U; struct _hw_cau_aesic_ca8_bitfields { uint32_t CA8 : 32; /*!< [31:0] CA8 */ } B; } hw_cau_aesic_ca8_t; /*! * @name Constants and macros for entire CAU_AESIC_CA8 register */ /*@{*/ #define HW_CAU_AESIC_CA8_ADDR(x) ((x) + 0xB68U) #define HW_CAU_AESIC_CA8(x) (*(__O hw_cau_aesic_ca8_t *) HW_CAU_AESIC_CA8_ADDR(x)) #define HW_CAU_AESIC_CA8_WR(x, v) (HW_CAU_AESIC_CA8(x).U = (v)) /*@}*/ /* * Constants & macros for individual CAU_AESIC_CA8 bitfields */ /*! * @name Register CAU_AESIC_CA8, field CA8[31:0] (WO) */ /*@{*/ #define BP_CAU_AESIC_CA8_CA8 (0U) /*!< Bit position for CAU_AESIC_CA8_CA8. */ #define BM_CAU_AESIC_CA8_CA8 (0xFFFFFFFFU) /*!< Bit mask for CAU_AESIC_CA8_CA8. */ #define BS_CAU_AESIC_CA8_CA8 (32U) /*!< Bit field size in bits for CAU_AESIC_CA8_CA8. */ /*! @brief Format value for bitfield CAU_AESIC_CA8_CA8. */ #define BF_CAU_AESIC_CA8_CA8(v) ((uint32_t)((uint32_t)(v) << BP_CAU_AESIC_CA8_CA8) & BM_CAU_AESIC_CA8_CA8) /*@}*/ /******************************************************************************* * hw_cau_t - module struct ******************************************************************************/ /*! * @brief All CAU module registers. */ #pragma pack(1) typedef struct _hw_cau { __O hw_cau_direct0_t DIRECT0; /*!< [0x0] Direct access register 0 */ __O hw_cau_direct1_t DIRECT1; /*!< [0x4] Direct access register 1 */ __O hw_cau_direct2_t DIRECT2; /*!< [0x8] Direct access register 2 */ __O hw_cau_direct3_t DIRECT3; /*!< [0xC] Direct access register 3 */ __O hw_cau_direct4_t DIRECT4; /*!< [0x10] Direct access register 4 */ __O hw_cau_direct5_t DIRECT5; /*!< [0x14] Direct access register 5 */ __O hw_cau_direct6_t DIRECT6; /*!< [0x18] Direct access register 6 */ __O hw_cau_direct7_t DIRECT7; /*!< [0x1C] Direct access register 7 */ __O hw_cau_direct8_t DIRECT8; /*!< [0x20] Direct access register 8 */ __O hw_cau_direct9_t DIRECT9; /*!< [0x24] Direct access register 9 */ __O hw_cau_direct10_t DIRECT10; /*!< [0x28] Direct access register 10 */ __O hw_cau_direct11_t DIRECT11; /*!< [0x2C] Direct access register 11 */ __O hw_cau_direct12_t DIRECT12; /*!< [0x30] Direct access register 12 */ __O hw_cau_direct13_t DIRECT13; /*!< [0x34] Direct access register 13 */ __O hw_cau_direct14_t DIRECT14; /*!< [0x38] Direct access register 14 */ __O hw_cau_direct15_t DIRECT15; /*!< [0x3C] Direct access register 15 */ uint8_t _reserved0[2048]; __O hw_cau_ldr_casr_t LDR_CASR; /*!< [0x840] Status register - Load Register command */ __O hw_cau_ldr_caa_t LDR_CAA; /*!< [0x844] Accumulator register - Load Register command */ __O hw_cau_ldr_ca0_t LDR_CA0; /*!< [0x848] General Purpose Register 0 - Load Register command */ __O hw_cau_ldr_ca1_t LDR_CA1; /*!< [0x84C] General Purpose Register 1 - Load Register command */ __O hw_cau_ldr_ca2_t LDR_CA2; /*!< [0x850] General Purpose Register 2 - Load Register command */ __O hw_cau_ldr_ca3_t LDR_CA3; /*!< [0x854] General Purpose Register 3 - Load Register command */ __O hw_cau_ldr_ca4_t LDR_CA4; /*!< [0x858] General Purpose Register 4 - Load Register command */ __O hw_cau_ldr_ca5_t LDR_CA5; /*!< [0x85C] General Purpose Register 5 - Load Register command */ __O hw_cau_ldr_ca6_t LDR_CA6; /*!< [0x860] General Purpose Register 6 - Load Register command */ __O hw_cau_ldr_ca7_t LDR_CA7; /*!< [0x864] General Purpose Register 7 - Load Register command */ __O hw_cau_ldr_ca8_t LDR_CA8; /*!< [0x868] General Purpose Register 8 - Load Register command */ uint8_t _reserved1[20]; __I hw_cau_str_casr_t STR_CASR; /*!< [0x880] Status register - Store Register command */ __I hw_cau_str_caa_t STR_CAA; /*!< [0x884] Accumulator register - Store Register command */ __I hw_cau_str_ca0_t STR_CA0; /*!< [0x888] General Purpose Register 0 - Store Register command */ __I hw_cau_str_ca1_t STR_CA1; /*!< [0x88C] General Purpose Register 1 - Store Register command */ __I hw_cau_str_ca2_t STR_CA2; /*!< [0x890] General Purpose Register 2 - Store Register command */ __I hw_cau_str_ca3_t STR_CA3; /*!< [0x894] General Purpose Register 3 - Store Register command */ __I hw_cau_str_ca4_t STR_CA4; /*!< [0x898] General Purpose Register 4 - Store Register command */ __I hw_cau_str_ca5_t STR_CA5; /*!< [0x89C] General Purpose Register 5 - Store Register command */ __I hw_cau_str_ca6_t STR_CA6; /*!< [0x8A0] General Purpose Register 6 - Store Register command */ __I hw_cau_str_ca7_t STR_CA7; /*!< [0x8A4] General Purpose Register 7 - Store Register command */ __I hw_cau_str_ca8_t STR_CA8; /*!< [0x8A8] General Purpose Register 8 - Store Register command */ uint8_t _reserved2[20]; __O hw_cau_adr_casr_t ADR_CASR; /*!< [0x8C0] Status register - Add Register command */ __O hw_cau_adr_caa_t ADR_CAA; /*!< [0x8C4] Accumulator register - Add to register command */ __O hw_cau_adr_ca0_t ADR_CA0; /*!< [0x8C8] General Purpose Register 0 - Add to register command */ __O hw_cau_adr_ca1_t ADR_CA1; /*!< [0x8CC] General Purpose Register 1 - Add to register command */ __O hw_cau_adr_ca2_t ADR_CA2; /*!< [0x8D0] General Purpose Register 2 - Add to register command */ __O hw_cau_adr_ca3_t ADR_CA3; /*!< [0x8D4] General Purpose Register 3 - Add to register command */ __O hw_cau_adr_ca4_t ADR_CA4; /*!< [0x8D8] General Purpose Register 4 - Add to register command */ __O hw_cau_adr_ca5_t ADR_CA5; /*!< [0x8DC] General Purpose Register 5 - Add to register command */ __O hw_cau_adr_ca6_t ADR_CA6; /*!< [0x8E0] General Purpose Register 6 - Add to register command */ __O hw_cau_adr_ca7_t ADR_CA7; /*!< [0x8E4] General Purpose Register 7 - Add to register command */ __O hw_cau_adr_ca8_t ADR_CA8; /*!< [0x8E8] General Purpose Register 8 - Add to register command */ uint8_t _reserved3[20]; __O hw_cau_radr_casr_t RADR_CASR; /*!< [0x900] Status register - Reverse and Add to Register command */ __O hw_cau_radr_caa_t RADR_CAA; /*!< [0x904] Accumulator register - Reverse and Add to Register command */ __O hw_cau_radr_ca0_t RADR_CA0; /*!< [0x908] General Purpose Register 0 - Reverse and Add to Register command */ __O hw_cau_radr_ca1_t RADR_CA1; /*!< [0x90C] General Purpose Register 1 - Reverse and Add to Register command */ __O hw_cau_radr_ca2_t RADR_CA2; /*!< [0x910] General Purpose Register 2 - Reverse and Add to Register command */ __O hw_cau_radr_ca3_t RADR_CA3; /*!< [0x914] General Purpose Register 3 - Reverse and Add to Register command */ __O hw_cau_radr_ca4_t RADR_CA4; /*!< [0x918] General Purpose Register 4 - Reverse and Add to Register command */ __O hw_cau_radr_ca5_t RADR_CA5; /*!< [0x91C] General Purpose Register 5 - Reverse and Add to Register command */ __O hw_cau_radr_ca6_t RADR_CA6; /*!< [0x920] General Purpose Register 6 - Reverse and Add to Register command */ __O hw_cau_radr_ca7_t RADR_CA7; /*!< [0x924] General Purpose Register 7 - Reverse and Add to Register command */ __O hw_cau_radr_ca8_t RADR_CA8; /*!< [0x928] General Purpose Register 8 - Reverse and Add to Register command */ uint8_t _reserved4[84]; __O hw_cau_xor_casr_t XOR_CASR; /*!< [0x980] Status register - Exclusive Or command */ __O hw_cau_xor_caa_t XOR_CAA; /*!< [0x984] Accumulator register - Exclusive Or command */ __O hw_cau_xor_ca0_t XOR_CA0; /*!< [0x988] General Purpose Register 0 - Exclusive Or command */ __O hw_cau_xor_ca1_t XOR_CA1; /*!< [0x98C] General Purpose Register 1 - Exclusive Or command */ __O hw_cau_xor_ca2_t XOR_CA2; /*!< [0x990] General Purpose Register 2 - Exclusive Or command */ __O hw_cau_xor_ca3_t XOR_CA3; /*!< [0x994] General Purpose Register 3 - Exclusive Or command */ __O hw_cau_xor_ca4_t XOR_CA4; /*!< [0x998] General Purpose Register 4 - Exclusive Or command */ __O hw_cau_xor_ca5_t XOR_CA5; /*!< [0x99C] General Purpose Register 5 - Exclusive Or command */ __O hw_cau_xor_ca6_t XOR_CA6; /*!< [0x9A0] General Purpose Register 6 - Exclusive Or command */ __O hw_cau_xor_ca7_t XOR_CA7; /*!< [0x9A4] General Purpose Register 7 - Exclusive Or command */ __O hw_cau_xor_ca8_t XOR_CA8; /*!< [0x9A8] General Purpose Register 8 - Exclusive Or command */ uint8_t _reserved5[20]; __O hw_cau_rotl_casr_t ROTL_CASR; /*!< [0x9C0] Status register - Rotate Left command */ __O hw_cau_rotl_caa_t ROTL_CAA; /*!< [0x9C4] Accumulator register - Rotate Left command */ __O hw_cau_rotl_ca0_t ROTL_CA0; /*!< [0x9C8] General Purpose Register 0 - Rotate Left command */ __O hw_cau_rotl_ca1_t ROTL_CA1; /*!< [0x9CC] General Purpose Register 1 - Rotate Left command */ __O hw_cau_rotl_ca2_t ROTL_CA2; /*!< [0x9D0] General Purpose Register 2 - Rotate Left command */ __O hw_cau_rotl_ca3_t ROTL_CA3; /*!< [0x9D4] General Purpose Register 3 - Rotate Left command */ __O hw_cau_rotl_ca4_t ROTL_CA4; /*!< [0x9D8] General Purpose Register 4 - Rotate Left command */ __O hw_cau_rotl_ca5_t ROTL_CA5; /*!< [0x9DC] General Purpose Register 5 - Rotate Left command */ __O hw_cau_rotl_ca6_t ROTL_CA6; /*!< [0x9E0] General Purpose Register 6 - Rotate Left command */ __O hw_cau_rotl_ca7_t ROTL_CA7; /*!< [0x9E4] General Purpose Register 7 - Rotate Left command */ __O hw_cau_rotl_ca8_t ROTL_CA8; /*!< [0x9E8] General Purpose Register 8 - Rotate Left command */ uint8_t _reserved6[276]; __O hw_cau_aesc_casr_t AESC_CASR; /*!< [0xB00] Status register - AES Column Operation command */ __O hw_cau_aesc_caa_t AESC_CAA; /*!< [0xB04] Accumulator register - AES Column Operation command */ __O hw_cau_aesc_ca0_t AESC_CA0; /*!< [0xB08] General Purpose Register 0 - AES Column Operation command */ __O hw_cau_aesc_ca1_t AESC_CA1; /*!< [0xB0C] General Purpose Register 1 - AES Column Operation command */ __O hw_cau_aesc_ca2_t AESC_CA2; /*!< [0xB10] General Purpose Register 2 - AES Column Operation command */ __O hw_cau_aesc_ca3_t AESC_CA3; /*!< [0xB14] General Purpose Register 3 - AES Column Operation command */ __O hw_cau_aesc_ca4_t AESC_CA4; /*!< [0xB18] General Purpose Register 4 - AES Column Operation command */ __O hw_cau_aesc_ca5_t AESC_CA5; /*!< [0xB1C] General Purpose Register 5 - AES Column Operation command */ __O hw_cau_aesc_ca6_t AESC_CA6; /*!< [0xB20] General Purpose Register 6 - AES Column Operation command */ __O hw_cau_aesc_ca7_t AESC_CA7; /*!< [0xB24] General Purpose Register 7 - AES Column Operation command */ __O hw_cau_aesc_ca8_t AESC_CA8; /*!< [0xB28] General Purpose Register 8 - AES Column Operation command */ uint8_t _reserved7[20]; __O hw_cau_aesic_casr_t AESIC_CASR; /*!< [0xB40] Status register - AES Inverse Column Operation command */ __O hw_cau_aesic_caa_t AESIC_CAA; /*!< [0xB44] Accumulator register - AES Inverse Column Operation command */ __O hw_cau_aesic_ca0_t AESIC_CA0; /*!< [0xB48] General Purpose Register 0 - AES Inverse Column Operation command */ __O hw_cau_aesic_ca1_t AESIC_CA1; /*!< [0xB4C] General Purpose Register 1 - AES Inverse Column Operation command */ __O hw_cau_aesic_ca2_t AESIC_CA2; /*!< [0xB50] General Purpose Register 2 - AES Inverse Column Operation command */ __O hw_cau_aesic_ca3_t AESIC_CA3; /*!< [0xB54] General Purpose Register 3 - AES Inverse Column Operation command */ __O hw_cau_aesic_ca4_t AESIC_CA4; /*!< [0xB58] General Purpose Register 4 - AES Inverse Column Operation command */ __O hw_cau_aesic_ca5_t AESIC_CA5; /*!< [0xB5C] General Purpose Register 5 - AES Inverse Column Operation command */ __O hw_cau_aesic_ca6_t AESIC_CA6; /*!< [0xB60] General Purpose Register 6 - AES Inverse Column Operation command */ __O hw_cau_aesic_ca7_t AESIC_CA7; /*!< [0xB64] General Purpose Register 7 - AES Inverse Column Operation command */ __O hw_cau_aesic_ca8_t AESIC_CA8; /*!< [0xB68] General Purpose Register 8 - AES Inverse Column Operation command */ } hw_cau_t; #pragma pack() /*! @brief Macro to access all CAU registers. */ /*! @param x CAU module instance base address. */ /*! @return Reference (not a pointer) to the registers struct. To get a pointer to the struct, * use the '&' operator, like &HW_CAU(CAU_BASE). */ #define HW_CAU(x) (*(hw_cau_t *)(x)) #endif /* __HW_CAU_REGISTERS_H__ */ /* EOF */ ================================================ FILE: Zelig/mbed/TARGET_K64F/TARGET_Freescale/TARGET_KPSDK_MCUS/TARGET_MCU_K64F/device/device/MK64F12/MK64F12_cmp.h ================================================ /* ** ################################################################### ** Compilers: Keil ARM C/C++ Compiler ** Freescale C/C++ for Embedded ARM ** GNU C Compiler ** IAR ANSI C/C++ Compiler for ARM ** ** Reference manual: K64P144M120SF5RM, Rev.2, January 2014 ** Version: rev. 2.5, 2014-02-10 ** Build: b140604 ** ** Abstract: ** Extension to the CMSIS register access layer header. ** ** Copyright (c) 2014 Freescale Semiconductor, Inc. ** All rights reserved. ** ** Redistribution and use in source and binary forms, with or without modification, ** are permitted provided that the following conditions are met: ** ** o Redistributions of source code must retain the above copyright notice, this list ** of conditions and the following disclaimer. ** ** o Redistributions in binary form must reproduce the above copyright notice, this ** list of conditions and the following disclaimer in the documentation and/or ** other materials provided with the distribution. ** ** o Neither the name of Freescale Semiconductor, Inc. nor the names of its ** contributors may be used to endorse or promote products derived from this ** software without specific prior written permission. ** ** THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ** ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED ** WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE ** DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT 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. ** ** http: www.freescale.com ** mail: support@freescale.com ** ** Revisions: ** - rev. 1.0 (2013-08-12) ** Initial version. ** - rev. 2.0 (2013-10-29) ** Register accessor macros added to the memory map. ** Symbols for Processor Expert memory map compatibility added to the memory map. ** Startup file for gcc has been updated according to CMSIS 3.2. ** System initialization updated. ** MCG - registers updated. ** PORTA, PORTB, PORTC, PORTE - registers for digital filter removed. ** - rev. 2.1 (2013-10-30) ** Definition of BITBAND macros updated to support peripherals with 32-bit acces disabled. ** - rev. 2.2 (2013-12-09) ** DMA - EARS register removed. ** AIPS0, AIPS1 - MPRA register updated. ** - rev. 2.3 (2014-01-24) ** Update according to reference manual rev. 2 ** ENET, MCG, MCM, SIM, USB - registers updated ** - rev. 2.4 (2014-02-10) ** The declaration of clock configurations has been moved to separate header file system_MK64F12.h ** Update of SystemInit() and SystemCoreClockUpdate() functions. ** - rev. 2.5 (2014-02-10) ** The declaration of clock configurations has been moved to separate header file system_MK64F12.h ** Update of SystemInit() and SystemCoreClockUpdate() functions. ** Module access macro module_BASES replaced by module_BASE_PTRS. ** ** ################################################################### */ /* * WARNING! DO NOT EDIT THIS FILE DIRECTLY! * * This file was generated automatically and any changes may be lost. */ #ifndef __HW_CMP_REGISTERS_H__ #define __HW_CMP_REGISTERS_H__ #include "MK64F12.h" #include "fsl_bitaccess.h" /* * MK64F12 CMP * * High-Speed Comparator (CMP), Voltage Reference (VREF) Digital-to-Analog Converter (DAC), and Analog Mux (ANMUX) * * Registers defined in this header file: * - HW_CMP_CR0 - CMP Control Register 0 * - HW_CMP_CR1 - CMP Control Register 1 * - HW_CMP_FPR - CMP Filter Period Register * - HW_CMP_SCR - CMP Status and Control Register * - HW_CMP_DACCR - DAC Control Register * - HW_CMP_MUXCR - MUX Control Register * * - hw_cmp_t - Struct containing all module registers. */ #define HW_CMP_INSTANCE_COUNT (3U) /*!< Number of instances of the CMP module. */ #define HW_CMP0 (0U) /*!< Instance number for CMP0. */ #define HW_CMP1 (1U) /*!< Instance number for CMP1. */ #define HW_CMP2 (2U) /*!< Instance number for CMP2. */ /******************************************************************************* * HW_CMP_CR0 - CMP Control Register 0 ******************************************************************************/ /*! * @brief HW_CMP_CR0 - CMP Control Register 0 (RW) * * Reset value: 0x00U */ typedef union _hw_cmp_cr0 { uint8_t U; struct _hw_cmp_cr0_bitfields { uint8_t HYSTCTR : 2; /*!< [1:0] Comparator hard block hysteresis * control */ uint8_t RESERVED0 : 2; /*!< [3:2] */ uint8_t FILTER_CNT : 3; /*!< [6:4] Filter Sample Count */ uint8_t RESERVED1 : 1; /*!< [7] */ } B; } hw_cmp_cr0_t; /*! * @name Constants and macros for entire CMP_CR0 register */ /*@{*/ #define HW_CMP_CR0_ADDR(x) ((x) + 0x0U) #define HW_CMP_CR0(x) (*(__IO hw_cmp_cr0_t *) HW_CMP_CR0_ADDR(x)) #define HW_CMP_CR0_RD(x) (HW_CMP_CR0(x).U) #define HW_CMP_CR0_WR(x, v) (HW_CMP_CR0(x).U = (v)) #define HW_CMP_CR0_SET(x, v) (HW_CMP_CR0_WR(x, HW_CMP_CR0_RD(x) | (v))) #define HW_CMP_CR0_CLR(x, v) (HW_CMP_CR0_WR(x, HW_CMP_CR0_RD(x) & ~(v))) #define HW_CMP_CR0_TOG(x, v) (HW_CMP_CR0_WR(x, HW_CMP_CR0_RD(x) ^ (v))) /*@}*/ /* * Constants & macros for individual CMP_CR0 bitfields */ /*! * @name Register CMP_CR0, field HYSTCTR[1:0] (RW) * * Defines the programmable hysteresis level. The hysteresis values associated * with each level are device-specific. See the Data Sheet of the device for the * exact values. * * Values: * - 00 - Level 0 * - 01 - Level 1 * - 10 - Level 2 * - 11 - Level 3 */ /*@{*/ #define BP_CMP_CR0_HYSTCTR (0U) /*!< Bit position for CMP_CR0_HYSTCTR. */ #define BM_CMP_CR0_HYSTCTR (0x03U) /*!< Bit mask for CMP_CR0_HYSTCTR. */ #define BS_CMP_CR0_HYSTCTR (2U) /*!< Bit field size in bits for CMP_CR0_HYSTCTR. */ /*! @brief Read current value of the CMP_CR0_HYSTCTR field. */ #define BR_CMP_CR0_HYSTCTR(x) (HW_CMP_CR0(x).B.HYSTCTR) /*! @brief Format value for bitfield CMP_CR0_HYSTCTR. */ #define BF_CMP_CR0_HYSTCTR(v) ((uint8_t)((uint8_t)(v) << BP_CMP_CR0_HYSTCTR) & BM_CMP_CR0_HYSTCTR) /*! @brief Set the HYSTCTR field to a new value. */ #define BW_CMP_CR0_HYSTCTR(x, v) (HW_CMP_CR0_WR(x, (HW_CMP_CR0_RD(x) & ~BM_CMP_CR0_HYSTCTR) | BF_CMP_CR0_HYSTCTR(v))) /*@}*/ /*! * @name Register CMP_CR0, field FILTER_CNT[6:4] (RW) * * Represents the number of consecutive samples that must agree prior to the * comparator ouput filter accepting a new output state. For information regarding * filter programming and latency, see the Functional descriptionThe CMP module * can be used to compare two analog input voltages applied to INP and INM. . * * Values: * - 000 - Filter is disabled. If SE = 1, then COUT is a logic 0. This is not a * legal state, and is not recommended. If SE = 0, COUT = COUTA. * - 001 - One sample must agree. The comparator output is simply sampled. * - 010 - 2 consecutive samples must agree. * - 011 - 3 consecutive samples must agree. * - 100 - 4 consecutive samples must agree. * - 101 - 5 consecutive samples must agree. * - 110 - 6 consecutive samples must agree. * - 111 - 7 consecutive samples must agree. */ /*@{*/ #define BP_CMP_CR0_FILTER_CNT (4U) /*!< Bit position for CMP_CR0_FILTER_CNT. */ #define BM_CMP_CR0_FILTER_CNT (0x70U) /*!< Bit mask for CMP_CR0_FILTER_CNT. */ #define BS_CMP_CR0_FILTER_CNT (3U) /*!< Bit field size in bits for CMP_CR0_FILTER_CNT. */ /*! @brief Read current value of the CMP_CR0_FILTER_CNT field. */ #define BR_CMP_CR0_FILTER_CNT(x) (HW_CMP_CR0(x).B.FILTER_CNT) /*! @brief Format value for bitfield CMP_CR0_FILTER_CNT. */ #define BF_CMP_CR0_FILTER_CNT(v) ((uint8_t)((uint8_t)(v) << BP_CMP_CR0_FILTER_CNT) & BM_CMP_CR0_FILTER_CNT) /*! @brief Set the FILTER_CNT field to a new value. */ #define BW_CMP_CR0_FILTER_CNT(x, v) (HW_CMP_CR0_WR(x, (HW_CMP_CR0_RD(x) & ~BM_CMP_CR0_FILTER_CNT) | BF_CMP_CR0_FILTER_CNT(v))) /*@}*/ /******************************************************************************* * HW_CMP_CR1 - CMP Control Register 1 ******************************************************************************/ /*! * @brief HW_CMP_CR1 - CMP Control Register 1 (RW) * * Reset value: 0x00U */ typedef union _hw_cmp_cr1 { uint8_t U; struct _hw_cmp_cr1_bitfields { uint8_t EN : 1; /*!< [0] Comparator Module Enable */ uint8_t OPE : 1; /*!< [1] Comparator Output Pin Enable */ uint8_t COS : 1; /*!< [2] Comparator Output Select */ uint8_t INV : 1; /*!< [3] Comparator INVERT */ uint8_t PMODE : 1; /*!< [4] Power Mode Select */ uint8_t RESERVED0 : 1; /*!< [5] */ uint8_t WE : 1; /*!< [6] Windowing Enable */ uint8_t SE : 1; /*!< [7] Sample Enable */ } B; } hw_cmp_cr1_t; /*! * @name Constants and macros for entire CMP_CR1 register */ /*@{*/ #define HW_CMP_CR1_ADDR(x) ((x) + 0x1U) #define HW_CMP_CR1(x) (*(__IO hw_cmp_cr1_t *) HW_CMP_CR1_ADDR(x)) #define HW_CMP_CR1_RD(x) (HW_CMP_CR1(x).U) #define HW_CMP_CR1_WR(x, v) (HW_CMP_CR1(x).U = (v)) #define HW_CMP_CR1_SET(x, v) (HW_CMP_CR1_WR(x, HW_CMP_CR1_RD(x) | (v))) #define HW_CMP_CR1_CLR(x, v) (HW_CMP_CR1_WR(x, HW_CMP_CR1_RD(x) & ~(v))) #define HW_CMP_CR1_TOG(x, v) (HW_CMP_CR1_WR(x, HW_CMP_CR1_RD(x) ^ (v))) /*@}*/ /* * Constants & macros for individual CMP_CR1 bitfields */ /*! * @name Register CMP_CR1, field EN[0] (RW) * * Enables the Analog Comparator module. When the module is not enabled, it * remains in the off state, and consumes no power. When the user selects the same * input from analog mux to the positive and negative port, the comparator is * disabled automatically. * * Values: * - 0 - Analog Comparator is disabled. * - 1 - Analog Comparator is enabled. */ /*@{*/ #define BP_CMP_CR1_EN (0U) /*!< Bit position for CMP_CR1_EN. */ #define BM_CMP_CR1_EN (0x01U) /*!< Bit mask for CMP_CR1_EN. */ #define BS_CMP_CR1_EN (1U) /*!< Bit field size in bits for CMP_CR1_EN. */ /*! @brief Read current value of the CMP_CR1_EN field. */ #define BR_CMP_CR1_EN(x) (BITBAND_ACCESS8(HW_CMP_CR1_ADDR(x), BP_CMP_CR1_EN)) /*! @brief Format value for bitfield CMP_CR1_EN. */ #define BF_CMP_CR1_EN(v) ((uint8_t)((uint8_t)(v) << BP_CMP_CR1_EN) & BM_CMP_CR1_EN) /*! @brief Set the EN field to a new value. */ #define BW_CMP_CR1_EN(x, v) (BITBAND_ACCESS8(HW_CMP_CR1_ADDR(x), BP_CMP_CR1_EN) = (v)) /*@}*/ /*! * @name Register CMP_CR1, field OPE[1] (RW) * * Values: * - 0 - CMPO is not available on the associated CMPO output pin. If the * comparator does not own the pin, this field has no effect. * - 1 - CMPO is available on the associated CMPO output pin. The comparator * output (CMPO) is driven out on the associated CMPO output pin if the * comparator owns the pin. If the comparator does not own the field, this bit has no * effect. */ /*@{*/ #define BP_CMP_CR1_OPE (1U) /*!< Bit position for CMP_CR1_OPE. */ #define BM_CMP_CR1_OPE (0x02U) /*!< Bit mask for CMP_CR1_OPE. */ #define BS_CMP_CR1_OPE (1U) /*!< Bit field size in bits for CMP_CR1_OPE. */ /*! @brief Read current value of the CMP_CR1_OPE field. */ #define BR_CMP_CR1_OPE(x) (BITBAND_ACCESS8(HW_CMP_CR1_ADDR(x), BP_CMP_CR1_OPE)) /*! @brief Format value for bitfield CMP_CR1_OPE. */ #define BF_CMP_CR1_OPE(v) ((uint8_t)((uint8_t)(v) << BP_CMP_CR1_OPE) & BM_CMP_CR1_OPE) /*! @brief Set the OPE field to a new value. */ #define BW_CMP_CR1_OPE(x, v) (BITBAND_ACCESS8(HW_CMP_CR1_ADDR(x), BP_CMP_CR1_OPE) = (v)) /*@}*/ /*! * @name Register CMP_CR1, field COS[2] (RW) * * Values: * - 0 - Set the filtered comparator output (CMPO) to equal COUT. * - 1 - Set the unfiltered comparator output (CMPO) to equal COUTA. */ /*@{*/ #define BP_CMP_CR1_COS (2U) /*!< Bit position for CMP_CR1_COS. */ #define BM_CMP_CR1_COS (0x04U) /*!< Bit mask for CMP_CR1_COS. */ #define BS_CMP_CR1_COS (1U) /*!< Bit field size in bits for CMP_CR1_COS. */ /*! @brief Read current value of the CMP_CR1_COS field. */ #define BR_CMP_CR1_COS(x) (BITBAND_ACCESS8(HW_CMP_CR1_ADDR(x), BP_CMP_CR1_COS)) /*! @brief Format value for bitfield CMP_CR1_COS. */ #define BF_CMP_CR1_COS(v) ((uint8_t)((uint8_t)(v) << BP_CMP_CR1_COS) & BM_CMP_CR1_COS) /*! @brief Set the COS field to a new value. */ #define BW_CMP_CR1_COS(x, v) (BITBAND_ACCESS8(HW_CMP_CR1_ADDR(x), BP_CMP_CR1_COS) = (v)) /*@}*/ /*! * @name Register CMP_CR1, field INV[3] (RW) * * Allows selection of the polarity of the analog comparator function. It is * also driven to the COUT output, on both the device pin and as SCR[COUT], when * OPE=0. * * Values: * - 0 - Does not invert the comparator output. * - 1 - Inverts the comparator output. */ /*@{*/ #define BP_CMP_CR1_INV (3U) /*!< Bit position for CMP_CR1_INV. */ #define BM_CMP_CR1_INV (0x08U) /*!< Bit mask for CMP_CR1_INV. */ #define BS_CMP_CR1_INV (1U) /*!< Bit field size in bits for CMP_CR1_INV. */ /*! @brief Read current value of the CMP_CR1_INV field. */ #define BR_CMP_CR1_INV(x) (BITBAND_ACCESS8(HW_CMP_CR1_ADDR(x), BP_CMP_CR1_INV)) /*! @brief Format value for bitfield CMP_CR1_INV. */ #define BF_CMP_CR1_INV(v) ((uint8_t)((uint8_t)(v) << BP_CMP_CR1_INV) & BM_CMP_CR1_INV) /*! @brief Set the INV field to a new value. */ #define BW_CMP_CR1_INV(x, v) (BITBAND_ACCESS8(HW_CMP_CR1_ADDR(x), BP_CMP_CR1_INV) = (v)) /*@}*/ /*! * @name Register CMP_CR1, field PMODE[4] (RW) * * See the electrical specifications table in the device Data Sheet for details. * * Values: * - 0 - Low-Speed (LS) Comparison mode selected. In this mode, CMP has slower * output propagation delay and lower current consumption. * - 1 - High-Speed (HS) Comparison mode selected. In this mode, CMP has faster * output propagation delay and higher current consumption. */ /*@{*/ #define BP_CMP_CR1_PMODE (4U) /*!< Bit position for CMP_CR1_PMODE. */ #define BM_CMP_CR1_PMODE (0x10U) /*!< Bit mask for CMP_CR1_PMODE. */ #define BS_CMP_CR1_PMODE (1U) /*!< Bit field size in bits for CMP_CR1_PMODE. */ /*! @brief Read current value of the CMP_CR1_PMODE field. */ #define BR_CMP_CR1_PMODE(x) (BITBAND_ACCESS8(HW_CMP_CR1_ADDR(x), BP_CMP_CR1_PMODE)) /*! @brief Format value for bitfield CMP_CR1_PMODE. */ #define BF_CMP_CR1_PMODE(v) ((uint8_t)((uint8_t)(v) << BP_CMP_CR1_PMODE) & BM_CMP_CR1_PMODE) /*! @brief Set the PMODE field to a new value. */ #define BW_CMP_CR1_PMODE(x, v) (BITBAND_ACCESS8(HW_CMP_CR1_ADDR(x), BP_CMP_CR1_PMODE) = (v)) /*@}*/ /*! * @name Register CMP_CR1, field WE[6] (RW) * * At any given time, either SE or WE can be set. If a write to this register * attempts to set both, then SE is set and WE is cleared. However, avoid writing * 1s to both field locations because this "11" case is reserved and may change in * future implementations. * * Values: * - 0 - Windowing mode is not selected. * - 1 - Windowing mode is selected. */ /*@{*/ #define BP_CMP_CR1_WE (6U) /*!< Bit position for CMP_CR1_WE. */ #define BM_CMP_CR1_WE (0x40U) /*!< Bit mask for CMP_CR1_WE. */ #define BS_CMP_CR1_WE (1U) /*!< Bit field size in bits for CMP_CR1_WE. */ /*! @brief Read current value of the CMP_CR1_WE field. */ #define BR_CMP_CR1_WE(x) (BITBAND_ACCESS8(HW_CMP_CR1_ADDR(x), BP_CMP_CR1_WE)) /*! @brief Format value for bitfield CMP_CR1_WE. */ #define BF_CMP_CR1_WE(v) ((uint8_t)((uint8_t)(v) << BP_CMP_CR1_WE) & BM_CMP_CR1_WE) /*! @brief Set the WE field to a new value. */ #define BW_CMP_CR1_WE(x, v) (BITBAND_ACCESS8(HW_CMP_CR1_ADDR(x), BP_CMP_CR1_WE) = (v)) /*@}*/ /*! * @name Register CMP_CR1, field SE[7] (RW) * * At any given time, either SE or WE can be set. If a write to this register * attempts to set both, then SE is set and WE is cleared. However, avoid writing * 1s to both field locations because this "11" case is reserved and may change in * future implementations. * * Values: * - 0 - Sampling mode is not selected. * - 1 - Sampling mode is selected. */ /*@{*/ #define BP_CMP_CR1_SE (7U) /*!< Bit position for CMP_CR1_SE. */ #define BM_CMP_CR1_SE (0x80U) /*!< Bit mask for CMP_CR1_SE. */ #define BS_CMP_CR1_SE (1U) /*!< Bit field size in bits for CMP_CR1_SE. */ /*! @brief Read current value of the CMP_CR1_SE field. */ #define BR_CMP_CR1_SE(x) (BITBAND_ACCESS8(HW_CMP_CR1_ADDR(x), BP_CMP_CR1_SE)) /*! @brief Format value for bitfield CMP_CR1_SE. */ #define BF_CMP_CR1_SE(v) ((uint8_t)((uint8_t)(v) << BP_CMP_CR1_SE) & BM_CMP_CR1_SE) /*! @brief Set the SE field to a new value. */ #define BW_CMP_CR1_SE(x, v) (BITBAND_ACCESS8(HW_CMP_CR1_ADDR(x), BP_CMP_CR1_SE) = (v)) /*@}*/ /******************************************************************************* * HW_CMP_FPR - CMP Filter Period Register ******************************************************************************/ /*! * @brief HW_CMP_FPR - CMP Filter Period Register (RW) * * Reset value: 0x00U */ typedef union _hw_cmp_fpr { uint8_t U; struct _hw_cmp_fpr_bitfields { uint8_t FILT_PER : 8; /*!< [7:0] Filter Sample Period */ } B; } hw_cmp_fpr_t; /*! * @name Constants and macros for entire CMP_FPR register */ /*@{*/ #define HW_CMP_FPR_ADDR(x) ((x) + 0x2U) #define HW_CMP_FPR(x) (*(__IO hw_cmp_fpr_t *) HW_CMP_FPR_ADDR(x)) #define HW_CMP_FPR_RD(x) (HW_CMP_FPR(x).U) #define HW_CMP_FPR_WR(x, v) (HW_CMP_FPR(x).U = (v)) #define HW_CMP_FPR_SET(x, v) (HW_CMP_FPR_WR(x, HW_CMP_FPR_RD(x) | (v))) #define HW_CMP_FPR_CLR(x, v) (HW_CMP_FPR_WR(x, HW_CMP_FPR_RD(x) & ~(v))) #define HW_CMP_FPR_TOG(x, v) (HW_CMP_FPR_WR(x, HW_CMP_FPR_RD(x) ^ (v))) /*@}*/ /* * Constants & macros for individual CMP_FPR bitfields */ /*! * @name Register CMP_FPR, field FILT_PER[7:0] (RW) * * Specifies the sampling period, in bus clock cycles, of the comparator output * filter, when CR1[SE]=0. Setting FILT_PER to 0x0 disables the filter. Filter * programming and latency details appear in the Functional descriptionThe CMP * module can be used to compare two analog input voltages applied to INP and INM. . * This field has no effect when CR1[SE]=1. In that case, the external SAMPLE * signal is used to determine the sampling period. */ /*@{*/ #define BP_CMP_FPR_FILT_PER (0U) /*!< Bit position for CMP_FPR_FILT_PER. */ #define BM_CMP_FPR_FILT_PER (0xFFU) /*!< Bit mask for CMP_FPR_FILT_PER. */ #define BS_CMP_FPR_FILT_PER (8U) /*!< Bit field size in bits for CMP_FPR_FILT_PER. */ /*! @brief Read current value of the CMP_FPR_FILT_PER field. */ #define BR_CMP_FPR_FILT_PER(x) (HW_CMP_FPR(x).U) /*! @brief Format value for bitfield CMP_FPR_FILT_PER. */ #define BF_CMP_FPR_FILT_PER(v) ((uint8_t)((uint8_t)(v) << BP_CMP_FPR_FILT_PER) & BM_CMP_FPR_FILT_PER) /*! @brief Set the FILT_PER field to a new value. */ #define BW_CMP_FPR_FILT_PER(x, v) (HW_CMP_FPR_WR(x, v)) /*@}*/ /******************************************************************************* * HW_CMP_SCR - CMP Status and Control Register ******************************************************************************/ /*! * @brief HW_CMP_SCR - CMP Status and Control Register (RW) * * Reset value: 0x00U */ typedef union _hw_cmp_scr { uint8_t U; struct _hw_cmp_scr_bitfields { uint8_t COUT : 1; /*!< [0] Analog Comparator Output */ uint8_t CFF : 1; /*!< [1] Analog Comparator Flag Falling */ uint8_t CFR : 1; /*!< [2] Analog Comparator Flag Rising */ uint8_t IEF : 1; /*!< [3] Comparator Interrupt Enable Falling */ uint8_t IER : 1; /*!< [4] Comparator Interrupt Enable Rising */ uint8_t RESERVED0 : 1; /*!< [5] */ uint8_t DMAEN : 1; /*!< [6] DMA Enable Control */ uint8_t RESERVED1 : 1; /*!< [7] */ } B; } hw_cmp_scr_t; /*! * @name Constants and macros for entire CMP_SCR register */ /*@{*/ #define HW_CMP_SCR_ADDR(x) ((x) + 0x3U) #define HW_CMP_SCR(x) (*(__IO hw_cmp_scr_t *) HW_CMP_SCR_ADDR(x)) #define HW_CMP_SCR_RD(x) (HW_CMP_SCR(x).U) #define HW_CMP_SCR_WR(x, v) (HW_CMP_SCR(x).U = (v)) #define HW_CMP_SCR_SET(x, v) (HW_CMP_SCR_WR(x, HW_CMP_SCR_RD(x) | (v))) #define HW_CMP_SCR_CLR(x, v) (HW_CMP_SCR_WR(x, HW_CMP_SCR_RD(x) & ~(v))) #define HW_CMP_SCR_TOG(x, v) (HW_CMP_SCR_WR(x, HW_CMP_SCR_RD(x) ^ (v))) /*@}*/ /* * Constants & macros for individual CMP_SCR bitfields */ /*! * @name Register CMP_SCR, field COUT[0] (RO) * * Returns the current value of the Analog Comparator output, when read. The * field is reset to 0 and will read as CR1[INV] when the Analog Comparator module * is disabled, that is, when CR1[EN] = 0. Writes to this field are ignored. */ /*@{*/ #define BP_CMP_SCR_COUT (0U) /*!< Bit position for CMP_SCR_COUT. */ #define BM_CMP_SCR_COUT (0x01U) /*!< Bit mask for CMP_SCR_COUT. */ #define BS_CMP_SCR_COUT (1U) /*!< Bit field size in bits for CMP_SCR_COUT. */ /*! @brief Read current value of the CMP_SCR_COUT field. */ #define BR_CMP_SCR_COUT(x) (BITBAND_ACCESS8(HW_CMP_SCR_ADDR(x), BP_CMP_SCR_COUT)) /*@}*/ /*! * @name Register CMP_SCR, field CFF[1] (W1C) * * Detects a falling-edge on COUT, when set, during normal operation. CFF is * cleared by writing 1 to it. During Stop modes, CFF is level sensitive is edge * sensitive . * * Values: * - 0 - Falling-edge on COUT has not been detected. * - 1 - Falling-edge on COUT has occurred. */ /*@{*/ #define BP_CMP_SCR_CFF (1U) /*!< Bit position for CMP_SCR_CFF. */ #define BM_CMP_SCR_CFF (0x02U) /*!< Bit mask for CMP_SCR_CFF. */ #define BS_CMP_SCR_CFF (1U) /*!< Bit field size in bits for CMP_SCR_CFF. */ /*! @brief Read current value of the CMP_SCR_CFF field. */ #define BR_CMP_SCR_CFF(x) (BITBAND_ACCESS8(HW_CMP_SCR_ADDR(x), BP_CMP_SCR_CFF)) /*! @brief Format value for bitfield CMP_SCR_CFF. */ #define BF_CMP_SCR_CFF(v) ((uint8_t)((uint8_t)(v) << BP_CMP_SCR_CFF) & BM_CMP_SCR_CFF) /*! @brief Set the CFF field to a new value. */ #define BW_CMP_SCR_CFF(x, v) (BITBAND_ACCESS8(HW_CMP_SCR_ADDR(x), BP_CMP_SCR_CFF) = (v)) /*@}*/ /*! * @name Register CMP_SCR, field CFR[2] (W1C) * * Detects a rising-edge on COUT, when set, during normal operation. CFR is * cleared by writing 1 to it. During Stop modes, CFR is level sensitive is edge * sensitive . * * Values: * - 0 - Rising-edge on COUT has not been detected. * - 1 - Rising-edge on COUT has occurred. */ /*@{*/ #define BP_CMP_SCR_CFR (2U) /*!< Bit position for CMP_SCR_CFR. */ #define BM_CMP_SCR_CFR (0x04U) /*!< Bit mask for CMP_SCR_CFR. */ #define BS_CMP_SCR_CFR (1U) /*!< Bit field size in bits for CMP_SCR_CFR. */ /*! @brief Read current value of the CMP_SCR_CFR field. */ #define BR_CMP_SCR_CFR(x) (BITBAND_ACCESS8(HW_CMP_SCR_ADDR(x), BP_CMP_SCR_CFR)) /*! @brief Format value for bitfield CMP_SCR_CFR. */ #define BF_CMP_SCR_CFR(v) ((uint8_t)((uint8_t)(v) << BP_CMP_SCR_CFR) & BM_CMP_SCR_CFR) /*! @brief Set the CFR field to a new value. */ #define BW_CMP_SCR_CFR(x, v) (BITBAND_ACCESS8(HW_CMP_SCR_ADDR(x), BP_CMP_SCR_CFR) = (v)) /*@}*/ /*! * @name Register CMP_SCR, field IEF[3] (RW) * * Enables the CFF interrupt from the CMP. When this field is set, an interrupt * will be asserted when CFF is set. * * Values: * - 0 - Interrupt is disabled. * - 1 - Interrupt is enabled. */ /*@{*/ #define BP_CMP_SCR_IEF (3U) /*!< Bit position for CMP_SCR_IEF. */ #define BM_CMP_SCR_IEF (0x08U) /*!< Bit mask for CMP_SCR_IEF. */ #define BS_CMP_SCR_IEF (1U) /*!< Bit field size in bits for CMP_SCR_IEF. */ /*! @brief Read current value of the CMP_SCR_IEF field. */ #define BR_CMP_SCR_IEF(x) (BITBAND_ACCESS8(HW_CMP_SCR_ADDR(x), BP_CMP_SCR_IEF)) /*! @brief Format value for bitfield CMP_SCR_IEF. */ #define BF_CMP_SCR_IEF(v) ((uint8_t)((uint8_t)(v) << BP_CMP_SCR_IEF) & BM_CMP_SCR_IEF) /*! @brief Set the IEF field to a new value. */ #define BW_CMP_SCR_IEF(x, v) (BITBAND_ACCESS8(HW_CMP_SCR_ADDR(x), BP_CMP_SCR_IEF) = (v)) /*@}*/ /*! * @name Register CMP_SCR, field IER[4] (RW) * * Enables the CFR interrupt from the CMP. When this field is set, an interrupt * will be asserted when CFR is set. * * Values: * - 0 - Interrupt is disabled. * - 1 - Interrupt is enabled. */ /*@{*/ #define BP_CMP_SCR_IER (4U) /*!< Bit position for CMP_SCR_IER. */ #define BM_CMP_SCR_IER (0x10U) /*!< Bit mask for CMP_SCR_IER. */ #define BS_CMP_SCR_IER (1U) /*!< Bit field size in bits for CMP_SCR_IER. */ /*! @brief Read current value of the CMP_SCR_IER field. */ #define BR_CMP_SCR_IER(x) (BITBAND_ACCESS8(HW_CMP_SCR_ADDR(x), BP_CMP_SCR_IER)) /*! @brief Format value for bitfield CMP_SCR_IER. */ #define BF_CMP_SCR_IER(v) ((uint8_t)((uint8_t)(v) << BP_CMP_SCR_IER) & BM_CMP_SCR_IER) /*! @brief Set the IER field to a new value. */ #define BW_CMP_SCR_IER(x, v) (BITBAND_ACCESS8(HW_CMP_SCR_ADDR(x), BP_CMP_SCR_IER) = (v)) /*@}*/ /*! * @name Register CMP_SCR, field DMAEN[6] (RW) * * Enables the DMA transfer triggered from the CMP module. When this field is * set, a DMA request is asserted when CFR or CFF is set. * * Values: * - 0 - DMA is disabled. * - 1 - DMA is enabled. */ /*@{*/ #define BP_CMP_SCR_DMAEN (6U) /*!< Bit position for CMP_SCR_DMAEN. */ #define BM_CMP_SCR_DMAEN (0x40U) /*!< Bit mask for CMP_SCR_DMAEN. */ #define BS_CMP_SCR_DMAEN (1U) /*!< Bit field size in bits for CMP_SCR_DMAEN. */ /*! @brief Read current value of the CMP_SCR_DMAEN field. */ #define BR_CMP_SCR_DMAEN(x) (BITBAND_ACCESS8(HW_CMP_SCR_ADDR(x), BP_CMP_SCR_DMAEN)) /*! @brief Format value for bitfield CMP_SCR_DMAEN. */ #define BF_CMP_SCR_DMAEN(v) ((uint8_t)((uint8_t)(v) << BP_CMP_SCR_DMAEN) & BM_CMP_SCR_DMAEN) /*! @brief Set the DMAEN field to a new value. */ #define BW_CMP_SCR_DMAEN(x, v) (BITBAND_ACCESS8(HW_CMP_SCR_ADDR(x), BP_CMP_SCR_DMAEN) = (v)) /*@}*/ /******************************************************************************* * HW_CMP_DACCR - DAC Control Register ******************************************************************************/ /*! * @brief HW_CMP_DACCR - DAC Control Register (RW) * * Reset value: 0x00U */ typedef union _hw_cmp_daccr { uint8_t U; struct _hw_cmp_daccr_bitfields { uint8_t VOSEL : 6; /*!< [5:0] DAC Output Voltage Select */ uint8_t VRSEL : 1; /*!< [6] Supply Voltage Reference Source Select */ uint8_t DACEN : 1; /*!< [7] DAC Enable */ } B; } hw_cmp_daccr_t; /*! * @name Constants and macros for entire CMP_DACCR register */ /*@{*/ #define HW_CMP_DACCR_ADDR(x) ((x) + 0x4U) #define HW_CMP_DACCR(x) (*(__IO hw_cmp_daccr_t *) HW_CMP_DACCR_ADDR(x)) #define HW_CMP_DACCR_RD(x) (HW_CMP_DACCR(x).U) #define HW_CMP_DACCR_WR(x, v) (HW_CMP_DACCR(x).U = (v)) #define HW_CMP_DACCR_SET(x, v) (HW_CMP_DACCR_WR(x, HW_CMP_DACCR_RD(x) | (v))) #define HW_CMP_DACCR_CLR(x, v) (HW_CMP_DACCR_WR(x, HW_CMP_DACCR_RD(x) & ~(v))) #define HW_CMP_DACCR_TOG(x, v) (HW_CMP_DACCR_WR(x, HW_CMP_DACCR_RD(x) ^ (v))) /*@}*/ /* * Constants & macros for individual CMP_DACCR bitfields */ /*! * @name Register CMP_DACCR, field VOSEL[5:0] (RW) * * Selects an output voltage from one of 64 distinct levels. DACO = (V in /64) * * (VOSEL[5:0] + 1) , so the DACO range is from V in /64 to V in . */ /*@{*/ #define BP_CMP_DACCR_VOSEL (0U) /*!< Bit position for CMP_DACCR_VOSEL. */ #define BM_CMP_DACCR_VOSEL (0x3FU) /*!< Bit mask for CMP_DACCR_VOSEL. */ #define BS_CMP_DACCR_VOSEL (6U) /*!< Bit field size in bits for CMP_DACCR_VOSEL. */ /*! @brief Read current value of the CMP_DACCR_VOSEL field. */ #define BR_CMP_DACCR_VOSEL(x) (HW_CMP_DACCR(x).B.VOSEL) /*! @brief Format value for bitfield CMP_DACCR_VOSEL. */ #define BF_CMP_DACCR_VOSEL(v) ((uint8_t)((uint8_t)(v) << BP_CMP_DACCR_VOSEL) & BM_CMP_DACCR_VOSEL) /*! @brief Set the VOSEL field to a new value. */ #define BW_CMP_DACCR_VOSEL(x, v) (HW_CMP_DACCR_WR(x, (HW_CMP_DACCR_RD(x) & ~BM_CMP_DACCR_VOSEL) | BF_CMP_DACCR_VOSEL(v))) /*@}*/ /*! * @name Register CMP_DACCR, field VRSEL[6] (RW) * * Values: * - 0 - V is selected as resistor ladder network supply reference V. in1 in * - 1 - V is selected as resistor ladder network supply reference V. in2 in */ /*@{*/ #define BP_CMP_DACCR_VRSEL (6U) /*!< Bit position for CMP_DACCR_VRSEL. */ #define BM_CMP_DACCR_VRSEL (0x40U) /*!< Bit mask for CMP_DACCR_VRSEL. */ #define BS_CMP_DACCR_VRSEL (1U) /*!< Bit field size in bits for CMP_DACCR_VRSEL. */ /*! @brief Read current value of the CMP_DACCR_VRSEL field. */ #define BR_CMP_DACCR_VRSEL(x) (BITBAND_ACCESS8(HW_CMP_DACCR_ADDR(x), BP_CMP_DACCR_VRSEL)) /*! @brief Format value for bitfield CMP_DACCR_VRSEL. */ #define BF_CMP_DACCR_VRSEL(v) ((uint8_t)((uint8_t)(v) << BP_CMP_DACCR_VRSEL) & BM_CMP_DACCR_VRSEL) /*! @brief Set the VRSEL field to a new value. */ #define BW_CMP_DACCR_VRSEL(x, v) (BITBAND_ACCESS8(HW_CMP_DACCR_ADDR(x), BP_CMP_DACCR_VRSEL) = (v)) /*@}*/ /*! * @name Register CMP_DACCR, field DACEN[7] (RW) * * Enables the DAC. When the DAC is disabled, it is powered down to conserve * power. * * Values: * - 0 - DAC is disabled. * - 1 - DAC is enabled. */ /*@{*/ #define BP_CMP_DACCR_DACEN (7U) /*!< Bit position for CMP_DACCR_DACEN. */ #define BM_CMP_DACCR_DACEN (0x80U) /*!< Bit mask for CMP_DACCR_DACEN. */ #define BS_CMP_DACCR_DACEN (1U) /*!< Bit field size in bits for CMP_DACCR_DACEN. */ /*! @brief Read current value of the CMP_DACCR_DACEN field. */ #define BR_CMP_DACCR_DACEN(x) (BITBAND_ACCESS8(HW_CMP_DACCR_ADDR(x), BP_CMP_DACCR_DACEN)) /*! @brief Format value for bitfield CMP_DACCR_DACEN. */ #define BF_CMP_DACCR_DACEN(v) ((uint8_t)((uint8_t)(v) << BP_CMP_DACCR_DACEN) & BM_CMP_DACCR_DACEN) /*! @brief Set the DACEN field to a new value. */ #define BW_CMP_DACCR_DACEN(x, v) (BITBAND_ACCESS8(HW_CMP_DACCR_ADDR(x), BP_CMP_DACCR_DACEN) = (v)) /*@}*/ /******************************************************************************* * HW_CMP_MUXCR - MUX Control Register ******************************************************************************/ /*! * @brief HW_CMP_MUXCR - MUX Control Register (RW) * * Reset value: 0x00U */ typedef union _hw_cmp_muxcr { uint8_t U; struct _hw_cmp_muxcr_bitfields { uint8_t MSEL : 3; /*!< [2:0] Minus Input Mux Control */ uint8_t PSEL : 3; /*!< [5:3] Plus Input Mux Control */ uint8_t RESERVED0 : 1; /*!< [6] */ uint8_t PSTM : 1; /*!< [7] Pass Through Mode Enable */ } B; } hw_cmp_muxcr_t; /*! * @name Constants and macros for entire CMP_MUXCR register */ /*@{*/ #define HW_CMP_MUXCR_ADDR(x) ((x) + 0x5U) #define HW_CMP_MUXCR(x) (*(__IO hw_cmp_muxcr_t *) HW_CMP_MUXCR_ADDR(x)) #define HW_CMP_MUXCR_RD(x) (HW_CMP_MUXCR(x).U) #define HW_CMP_MUXCR_WR(x, v) (HW_CMP_MUXCR(x).U = (v)) #define HW_CMP_MUXCR_SET(x, v) (HW_CMP_MUXCR_WR(x, HW_CMP_MUXCR_RD(x) | (v))) #define HW_CMP_MUXCR_CLR(x, v) (HW_CMP_MUXCR_WR(x, HW_CMP_MUXCR_RD(x) & ~(v))) #define HW_CMP_MUXCR_TOG(x, v) (HW_CMP_MUXCR_WR(x, HW_CMP_MUXCR_RD(x) ^ (v))) /*@}*/ /* * Constants & macros for individual CMP_MUXCR bitfields */ /*! * @name Register CMP_MUXCR, field MSEL[2:0] (RW) * * Determines which input is selected for the minus input of the comparator. For * INx inputs, see CMP, DAC, and ANMUX block diagrams. When an inappropriate * operation selects the same input for both muxes, the comparator automatically * shuts down to prevent itself from becoming a noise generator. * * Values: * - 000 - IN0 * - 001 - IN1 * - 010 - IN2 * - 011 - IN3 * - 100 - IN4 * - 101 - IN5 * - 110 - IN6 * - 111 - IN7 */ /*@{*/ #define BP_CMP_MUXCR_MSEL (0U) /*!< Bit position for CMP_MUXCR_MSEL. */ #define BM_CMP_MUXCR_MSEL (0x07U) /*!< Bit mask for CMP_MUXCR_MSEL. */ #define BS_CMP_MUXCR_MSEL (3U) /*!< Bit field size in bits for CMP_MUXCR_MSEL. */ /*! @brief Read current value of the CMP_MUXCR_MSEL field. */ #define BR_CMP_MUXCR_MSEL(x) (HW_CMP_MUXCR(x).B.MSEL) /*! @brief Format value for bitfield CMP_MUXCR_MSEL. */ #define BF_CMP_MUXCR_MSEL(v) ((uint8_t)((uint8_t)(v) << BP_CMP_MUXCR_MSEL) & BM_CMP_MUXCR_MSEL) /*! @brief Set the MSEL field to a new value. */ #define BW_CMP_MUXCR_MSEL(x, v) (HW_CMP_MUXCR_WR(x, (HW_CMP_MUXCR_RD(x) & ~BM_CMP_MUXCR_MSEL) | BF_CMP_MUXCR_MSEL(v))) /*@}*/ /*! * @name Register CMP_MUXCR, field PSEL[5:3] (RW) * * Determines which input is selected for the plus input of the comparator. For * INx inputs, see CMP, DAC, and ANMUX block diagrams. When an inappropriate * operation selects the same input for both muxes, the comparator automatically * shuts down to prevent itself from becoming a noise generator. * * Values: * - 000 - IN0 * - 001 - IN1 * - 010 - IN2 * - 011 - IN3 * - 100 - IN4 * - 101 - IN5 * - 110 - IN6 * - 111 - IN7 */ /*@{*/ #define BP_CMP_MUXCR_PSEL (3U) /*!< Bit position for CMP_MUXCR_PSEL. */ #define BM_CMP_MUXCR_PSEL (0x38U) /*!< Bit mask for CMP_MUXCR_PSEL. */ #define BS_CMP_MUXCR_PSEL (3U) /*!< Bit field size in bits for CMP_MUXCR_PSEL. */ /*! @brief Read current value of the CMP_MUXCR_PSEL field. */ #define BR_CMP_MUXCR_PSEL(x) (HW_CMP_MUXCR(x).B.PSEL) /*! @brief Format value for bitfield CMP_MUXCR_PSEL. */ #define BF_CMP_MUXCR_PSEL(v) ((uint8_t)((uint8_t)(v) << BP_CMP_MUXCR_PSEL) & BM_CMP_MUXCR_PSEL) /*! @brief Set the PSEL field to a new value. */ #define BW_CMP_MUXCR_PSEL(x, v) (HW_CMP_MUXCR_WR(x, (HW_CMP_MUXCR_RD(x) & ~BM_CMP_MUXCR_PSEL) | BF_CMP_MUXCR_PSEL(v))) /*@}*/ /*! * @name Register CMP_MUXCR, field PSTM[7] (RW) * * This bit is used to enable to MUX pass through mode. Pass through mode is * always available but for some devices this feature must be always disabled due to * the lack of package pins. * * Values: * - 0 - Pass Through Mode is disabled. * - 1 - Pass Through Mode is enabled. */ /*@{*/ #define BP_CMP_MUXCR_PSTM (7U) /*!< Bit position for CMP_MUXCR_PSTM. */ #define BM_CMP_MUXCR_PSTM (0x80U) /*!< Bit mask for CMP_MUXCR_PSTM. */ #define BS_CMP_MUXCR_PSTM (1U) /*!< Bit field size in bits for CMP_MUXCR_PSTM. */ /*! @brief Read current value of the CMP_MUXCR_PSTM field. */ #define BR_CMP_MUXCR_PSTM(x) (BITBAND_ACCESS8(HW_CMP_MUXCR_ADDR(x), BP_CMP_MUXCR_PSTM)) /*! @brief Format value for bitfield CMP_MUXCR_PSTM. */ #define BF_CMP_MUXCR_PSTM(v) ((uint8_t)((uint8_t)(v) << BP_CMP_MUXCR_PSTM) & BM_CMP_MUXCR_PSTM) /*! @brief Set the PSTM field to a new value. */ #define BW_CMP_MUXCR_PSTM(x, v) (BITBAND_ACCESS8(HW_CMP_MUXCR_ADDR(x), BP_CMP_MUXCR_PSTM) = (v)) /*@}*/ /******************************************************************************* * hw_cmp_t - module struct ******************************************************************************/ /*! * @brief All CMP module registers. */ #pragma pack(1) typedef struct _hw_cmp { __IO hw_cmp_cr0_t CR0; /*!< [0x0] CMP Control Register 0 */ __IO hw_cmp_cr1_t CR1; /*!< [0x1] CMP Control Register 1 */ __IO hw_cmp_fpr_t FPR; /*!< [0x2] CMP Filter Period Register */ __IO hw_cmp_scr_t SCR; /*!< [0x3] CMP Status and Control Register */ __IO hw_cmp_daccr_t DACCR; /*!< [0x4] DAC Control Register */ __IO hw_cmp_muxcr_t MUXCR; /*!< [0x5] MUX Control Register */ } hw_cmp_t; #pragma pack() /*! @brief Macro to access all CMP registers. */ /*! @param x CMP module instance base address. */ /*! @return Reference (not a pointer) to the registers struct. To get a pointer to the struct, * use the '&' operator, like &HW_CMP(CMP0_BASE). */ #define HW_CMP(x) (*(hw_cmp_t *)(x)) #endif /* __HW_CMP_REGISTERS_H__ */ /* EOF */ ================================================ FILE: Zelig/mbed/TARGET_K64F/TARGET_Freescale/TARGET_KPSDK_MCUS/TARGET_MCU_K64F/device/device/MK64F12/MK64F12_cmt.h ================================================ /* ** ################################################################### ** Compilers: Keil ARM C/C++ Compiler ** Freescale C/C++ for Embedded ARM ** GNU C Compiler ** IAR ANSI C/C++ Compiler for ARM ** ** Reference manual: K64P144M120SF5RM, Rev.2, January 2014 ** Version: rev. 2.5, 2014-02-10 ** Build: b140604 ** ** Abstract: ** Extension to the CMSIS register access layer header. ** ** Copyright (c) 2014 Freescale Semiconductor, Inc. ** All rights reserved. ** ** Redistribution and use in source and binary forms, with or without modification, ** are permitted provided that the following conditions are met: ** ** o Redistributions of source code must retain the above copyright notice, this list ** of conditions and the following disclaimer. ** ** o Redistributions in binary form must reproduce the above copyright notice, this ** list of conditions and the following disclaimer in the documentation and/or ** other materials provided with the distribution. ** ** o Neither the name of Freescale Semiconductor, Inc. nor the names of its ** contributors may be used to endorse or promote products derived from this ** software without specific prior written permission. ** ** THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ** ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED ** WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE ** DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT 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. ** ** http: www.freescale.com ** mail: support@freescale.com ** ** Revisions: ** - rev. 1.0 (2013-08-12) ** Initial version. ** - rev. 2.0 (2013-10-29) ** Register accessor macros added to the memory map. ** Symbols for Processor Expert memory map compatibility added to the memory map. ** Startup file for gcc has been updated according to CMSIS 3.2. ** System initialization updated. ** MCG - registers updated. ** PORTA, PORTB, PORTC, PORTE - registers for digital filter removed. ** - rev. 2.1 (2013-10-30) ** Definition of BITBAND macros updated to support peripherals with 32-bit acces disabled. ** - rev. 2.2 (2013-12-09) ** DMA - EARS register removed. ** AIPS0, AIPS1 - MPRA register updated. ** - rev. 2.3 (2014-01-24) ** Update according to reference manual rev. 2 ** ENET, MCG, MCM, SIM, USB - registers updated ** - rev. 2.4 (2014-02-10) ** The declaration of clock configurations has been moved to separate header file system_MK64F12.h ** Update of SystemInit() and SystemCoreClockUpdate() functions. ** - rev. 2.5 (2014-02-10) ** The declaration of clock configurations has been moved to separate header file system_MK64F12.h ** Update of SystemInit() and SystemCoreClockUpdate() functions. ** Module access macro module_BASES replaced by module_BASE_PTRS. ** ** ################################################################### */ /* * WARNING! DO NOT EDIT THIS FILE DIRECTLY! * * This file was generated automatically and any changes may be lost. */ #ifndef __HW_CMT_REGISTERS_H__ #define __HW_CMT_REGISTERS_H__ #include "MK64F12.h" #include "fsl_bitaccess.h" /* * MK64F12 CMT * * Carrier Modulator Transmitter * * Registers defined in this header file: * - HW_CMT_CGH1 - CMT Carrier Generator High Data Register 1 * - HW_CMT_CGL1 - CMT Carrier Generator Low Data Register 1 * - HW_CMT_CGH2 - CMT Carrier Generator High Data Register 2 * - HW_CMT_CGL2 - CMT Carrier Generator Low Data Register 2 * - HW_CMT_OC - CMT Output Control Register * - HW_CMT_MSC - CMT Modulator Status and Control Register * - HW_CMT_CMD1 - CMT Modulator Data Register Mark High * - HW_CMT_CMD2 - CMT Modulator Data Register Mark Low * - HW_CMT_CMD3 - CMT Modulator Data Register Space High * - HW_CMT_CMD4 - CMT Modulator Data Register Space Low * - HW_CMT_PPS - CMT Primary Prescaler Register * - HW_CMT_DMA - CMT Direct Memory Access Register * * - hw_cmt_t - Struct containing all module registers. */ #define HW_CMT_INSTANCE_COUNT (1U) /*!< Number of instances of the CMT module. */ /******************************************************************************* * HW_CMT_CGH1 - CMT Carrier Generator High Data Register 1 ******************************************************************************/ /*! * @brief HW_CMT_CGH1 - CMT Carrier Generator High Data Register 1 (RW) * * Reset value: 0x00U * * This data register contains the primary high value for generating the carrier * output. */ typedef union _hw_cmt_cgh1 { uint8_t U; struct _hw_cmt_cgh1_bitfields { uint8_t PH : 8; /*!< [7:0] Primary Carrier High Time Data Value */ } B; } hw_cmt_cgh1_t; /*! * @name Constants and macros for entire CMT_CGH1 register */ /*@{*/ #define HW_CMT_CGH1_ADDR(x) ((x) + 0x0U) #define HW_CMT_CGH1(x) (*(__IO hw_cmt_cgh1_t *) HW_CMT_CGH1_ADDR(x)) #define HW_CMT_CGH1_RD(x) (HW_CMT_CGH1(x).U) #define HW_CMT_CGH1_WR(x, v) (HW_CMT_CGH1(x).U = (v)) #define HW_CMT_CGH1_SET(x, v) (HW_CMT_CGH1_WR(x, HW_CMT_CGH1_RD(x) | (v))) #define HW_CMT_CGH1_CLR(x, v) (HW_CMT_CGH1_WR(x, HW_CMT_CGH1_RD(x) & ~(v))) #define HW_CMT_CGH1_TOG(x, v) (HW_CMT_CGH1_WR(x, HW_CMT_CGH1_RD(x) ^ (v))) /*@}*/ /* * Constants & macros for individual CMT_CGH1 bitfields */ /*! * @name Register CMT_CGH1, field PH[7:0] (RW) * * Contains the number of input clocks required to generate the carrier high * time period. When operating in Time mode, this register is always selected. When * operating in FSK mode, this register and the secondary register pair are * alternately selected under the control of the modulator. The primary carrier high * time value is undefined out of reset. This register must be written to nonzero * values before the carrier generator is enabled to avoid spurious results. */ /*@{*/ #define BP_CMT_CGH1_PH (0U) /*!< Bit position for CMT_CGH1_PH. */ #define BM_CMT_CGH1_PH (0xFFU) /*!< Bit mask for CMT_CGH1_PH. */ #define BS_CMT_CGH1_PH (8U) /*!< Bit field size in bits for CMT_CGH1_PH. */ /*! @brief Read current value of the CMT_CGH1_PH field. */ #define BR_CMT_CGH1_PH(x) (HW_CMT_CGH1(x).U) /*! @brief Format value for bitfield CMT_CGH1_PH. */ #define BF_CMT_CGH1_PH(v) ((uint8_t)((uint8_t)(v) << BP_CMT_CGH1_PH) & BM_CMT_CGH1_PH) /*! @brief Set the PH field to a new value. */ #define BW_CMT_CGH1_PH(x, v) (HW_CMT_CGH1_WR(x, v)) /*@}*/ /******************************************************************************* * HW_CMT_CGL1 - CMT Carrier Generator Low Data Register 1 ******************************************************************************/ /*! * @brief HW_CMT_CGL1 - CMT Carrier Generator Low Data Register 1 (RW) * * Reset value: 0x00U * * This data register contains the primary low value for generating the carrier * output. */ typedef union _hw_cmt_cgl1 { uint8_t U; struct _hw_cmt_cgl1_bitfields { uint8_t PL : 8; /*!< [7:0] Primary Carrier Low Time Data Value */ } B; } hw_cmt_cgl1_t; /*! * @name Constants and macros for entire CMT_CGL1 register */ /*@{*/ #define HW_CMT_CGL1_ADDR(x) ((x) + 0x1U) #define HW_CMT_CGL1(x) (*(__IO hw_cmt_cgl1_t *) HW_CMT_CGL1_ADDR(x)) #define HW_CMT_CGL1_RD(x) (HW_CMT_CGL1(x).U) #define HW_CMT_CGL1_WR(x, v) (HW_CMT_CGL1(x).U = (v)) #define HW_CMT_CGL1_SET(x, v) (HW_CMT_CGL1_WR(x, HW_CMT_CGL1_RD(x) | (v))) #define HW_CMT_CGL1_CLR(x, v) (HW_CMT_CGL1_WR(x, HW_CMT_CGL1_RD(x) & ~(v))) #define HW_CMT_CGL1_TOG(x, v) (HW_CMT_CGL1_WR(x, HW_CMT_CGL1_RD(x) ^ (v))) /*@}*/ /* * Constants & macros for individual CMT_CGL1 bitfields */ /*! * @name Register CMT_CGL1, field PL[7:0] (RW) * * Contains the number of input clocks required to generate the carrier low time * period. When operating in Time mode, this register is always selected. When * operating in FSK mode, this register and the secondary register pair are * alternately selected under the control of the modulator. The primary carrier low * time value is undefined out of reset. This register must be written to nonzero * values before the carrier generator is enabled to avoid spurious results. */ /*@{*/ #define BP_CMT_CGL1_PL (0U) /*!< Bit position for CMT_CGL1_PL. */ #define BM_CMT_CGL1_PL (0xFFU) /*!< Bit mask for CMT_CGL1_PL. */ #define BS_CMT_CGL1_PL (8U) /*!< Bit field size in bits for CMT_CGL1_PL. */ /*! @brief Read current value of the CMT_CGL1_PL field. */ #define BR_CMT_CGL1_PL(x) (HW_CMT_CGL1(x).U) /*! @brief Format value for bitfield CMT_CGL1_PL. */ #define BF_CMT_CGL1_PL(v) ((uint8_t)((uint8_t)(v) << BP_CMT_CGL1_PL) & BM_CMT_CGL1_PL) /*! @brief Set the PL field to a new value. */ #define BW_CMT_CGL1_PL(x, v) (HW_CMT_CGL1_WR(x, v)) /*@}*/ /******************************************************************************* * HW_CMT_CGH2 - CMT Carrier Generator High Data Register 2 ******************************************************************************/ /*! * @brief HW_CMT_CGH2 - CMT Carrier Generator High Data Register 2 (RW) * * Reset value: 0x00U * * This data register contains the secondary high value for generating the * carrier output. */ typedef union _hw_cmt_cgh2 { uint8_t U; struct _hw_cmt_cgh2_bitfields { uint8_t SH : 8; /*!< [7:0] Secondary Carrier High Time Data Value */ } B; } hw_cmt_cgh2_t; /*! * @name Constants and macros for entire CMT_CGH2 register */ /*@{*/ #define HW_CMT_CGH2_ADDR(x) ((x) + 0x2U) #define HW_CMT_CGH2(x) (*(__IO hw_cmt_cgh2_t *) HW_CMT_CGH2_ADDR(x)) #define HW_CMT_CGH2_RD(x) (HW_CMT_CGH2(x).U) #define HW_CMT_CGH2_WR(x, v) (HW_CMT_CGH2(x).U = (v)) #define HW_CMT_CGH2_SET(x, v) (HW_CMT_CGH2_WR(x, HW_CMT_CGH2_RD(x) | (v))) #define HW_CMT_CGH2_CLR(x, v) (HW_CMT_CGH2_WR(x, HW_CMT_CGH2_RD(x) & ~(v))) #define HW_CMT_CGH2_TOG(x, v) (HW_CMT_CGH2_WR(x, HW_CMT_CGH2_RD(x) ^ (v))) /*@}*/ /* * Constants & macros for individual CMT_CGH2 bitfields */ /*! * @name Register CMT_CGH2, field SH[7:0] (RW) * * Contains the number of input clocks required to generate the carrier high * time period. When operating in Time mode, this register is never selected. When * operating in FSK mode, this register and the primary register pair are * alternately selected under control of the modulator. The secondary carrier high time * value is undefined out of reset. This register must be written to nonzero * values before the carrier generator is enabled when operating in FSK mode. */ /*@{*/ #define BP_CMT_CGH2_SH (0U) /*!< Bit position for CMT_CGH2_SH. */ #define BM_CMT_CGH2_SH (0xFFU) /*!< Bit mask for CMT_CGH2_SH. */ #define BS_CMT_CGH2_SH (8U) /*!< Bit field size in bits for CMT_CGH2_SH. */ /*! @brief Read current value of the CMT_CGH2_SH field. */ #define BR_CMT_CGH2_SH(x) (HW_CMT_CGH2(x).U) /*! @brief Format value for bitfield CMT_CGH2_SH. */ #define BF_CMT_CGH2_SH(v) ((uint8_t)((uint8_t)(v) << BP_CMT_CGH2_SH) & BM_CMT_CGH2_SH) /*! @brief Set the SH field to a new value. */ #define BW_CMT_CGH2_SH(x, v) (HW_CMT_CGH2_WR(x, v)) /*@}*/ /******************************************************************************* * HW_CMT_CGL2 - CMT Carrier Generator Low Data Register 2 ******************************************************************************/ /*! * @brief HW_CMT_CGL2 - CMT Carrier Generator Low Data Register 2 (RW) * * Reset value: 0x00U * * This data register contains the secondary low value for generating the * carrier output. */ typedef union _hw_cmt_cgl2 { uint8_t U; struct _hw_cmt_cgl2_bitfields { uint8_t SL : 8; /*!< [7:0] Secondary Carrier Low Time Data Value */ } B; } hw_cmt_cgl2_t; /*! * @name Constants and macros for entire CMT_CGL2 register */ /*@{*/ #define HW_CMT_CGL2_ADDR(x) ((x) + 0x3U) #define HW_CMT_CGL2(x) (*(__IO hw_cmt_cgl2_t *) HW_CMT_CGL2_ADDR(x)) #define HW_CMT_CGL2_RD(x) (HW_CMT_CGL2(x).U) #define HW_CMT_CGL2_WR(x, v) (HW_CMT_CGL2(x).U = (v)) #define HW_CMT_CGL2_SET(x, v) (HW_CMT_CGL2_WR(x, HW_CMT_CGL2_RD(x) | (v))) #define HW_CMT_CGL2_CLR(x, v) (HW_CMT_CGL2_WR(x, HW_CMT_CGL2_RD(x) & ~(v))) #define HW_CMT_CGL2_TOG(x, v) (HW_CMT_CGL2_WR(x, HW_CMT_CGL2_RD(x) ^ (v))) /*@}*/ /* * Constants & macros for individual CMT_CGL2 bitfields */ /*! * @name Register CMT_CGL2, field SL[7:0] (RW) * * Contains the number of input clocks required to generate the carrier low time * period. When operating in Time mode, this register is never selected. When * operating in FSK mode, this register and the primary register pair are * alternately selected under the control of the modulator. The secondary carrier low time * value is undefined out of reset. This register must be written to nonzero * values before the carrier generator is enabled when operating in FSK mode. */ /*@{*/ #define BP_CMT_CGL2_SL (0U) /*!< Bit position for CMT_CGL2_SL. */ #define BM_CMT_CGL2_SL (0xFFU) /*!< Bit mask for CMT_CGL2_SL. */ #define BS_CMT_CGL2_SL (8U) /*!< Bit field size in bits for CMT_CGL2_SL. */ /*! @brief Read current value of the CMT_CGL2_SL field. */ #define BR_CMT_CGL2_SL(x) (HW_CMT_CGL2(x).U) /*! @brief Format value for bitfield CMT_CGL2_SL. */ #define BF_CMT_CGL2_SL(v) ((uint8_t)((uint8_t)(v) << BP_CMT_CGL2_SL) & BM_CMT_CGL2_SL) /*! @brief Set the SL field to a new value. */ #define BW_CMT_CGL2_SL(x, v) (HW_CMT_CGL2_WR(x, v)) /*@}*/ /******************************************************************************* * HW_CMT_OC - CMT Output Control Register ******************************************************************************/ /*! * @brief HW_CMT_OC - CMT Output Control Register (RW) * * Reset value: 0x00U * * This register is used to control the IRO signal of the CMT module. */ typedef union _hw_cmt_oc { uint8_t U; struct _hw_cmt_oc_bitfields { uint8_t RESERVED0 : 5; /*!< [4:0] */ uint8_t IROPEN : 1; /*!< [5] IRO Pin Enable */ uint8_t CMTPOL : 1; /*!< [6] CMT Output Polarity */ uint8_t IROL : 1; /*!< [7] IRO Latch Control */ } B; } hw_cmt_oc_t; /*! * @name Constants and macros for entire CMT_OC register */ /*@{*/ #define HW_CMT_OC_ADDR(x) ((x) + 0x4U) #define HW_CMT_OC(x) (*(__IO hw_cmt_oc_t *) HW_CMT_OC_ADDR(x)) #define HW_CMT_OC_RD(x) (HW_CMT_OC(x).U) #define HW_CMT_OC_WR(x, v) (HW_CMT_OC(x).U = (v)) #define HW_CMT_OC_SET(x, v) (HW_CMT_OC_WR(x, HW_CMT_OC_RD(x) | (v))) #define HW_CMT_OC_CLR(x, v) (HW_CMT_OC_WR(x, HW_CMT_OC_RD(x) & ~(v))) #define HW_CMT_OC_TOG(x, v) (HW_CMT_OC_WR(x, HW_CMT_OC_RD(x) ^ (v))) /*@}*/ /* * Constants & macros for individual CMT_OC bitfields */ /*! * @name Register CMT_OC, field IROPEN[5] (RW) * * Enables and disables the IRO signal. When the IRO signal is enabled, it is an * output that drives out either the CMT transmitter output or the state of IROL * depending on whether MSC[MCGEN] is set or not. Also, the state of output is * either inverted or non-inverted, depending on the state of CMTPOL. When the IRO * signal is disabled, it is in a high-impedance state and is unable to draw any * current. This signal is disabled during reset. * * Values: * - 0 - The IRO signal is disabled. * - 1 - The IRO signal is enabled as output. */ /*@{*/ #define BP_CMT_OC_IROPEN (5U) /*!< Bit position for CMT_OC_IROPEN. */ #define BM_CMT_OC_IROPEN (0x20U) /*!< Bit mask for CMT_OC_IROPEN. */ #define BS_CMT_OC_IROPEN (1U) /*!< Bit field size in bits for CMT_OC_IROPEN. */ /*! @brief Read current value of the CMT_OC_IROPEN field. */ #define BR_CMT_OC_IROPEN(x) (BITBAND_ACCESS8(HW_CMT_OC_ADDR(x), BP_CMT_OC_IROPEN)) /*! @brief Format value for bitfield CMT_OC_IROPEN. */ #define BF_CMT_OC_IROPEN(v) ((uint8_t)((uint8_t)(v) << BP_CMT_OC_IROPEN) & BM_CMT_OC_IROPEN) /*! @brief Set the IROPEN field to a new value. */ #define BW_CMT_OC_IROPEN(x, v) (BITBAND_ACCESS8(HW_CMT_OC_ADDR(x), BP_CMT_OC_IROPEN) = (v)) /*@}*/ /*! * @name Register CMT_OC, field CMTPOL[6] (RW) * * Controls the polarity of the IRO signal. * * Values: * - 0 - The IRO signal is active-low. * - 1 - The IRO signal is active-high. */ /*@{*/ #define BP_CMT_OC_CMTPOL (6U) /*!< Bit position for CMT_OC_CMTPOL. */ #define BM_CMT_OC_CMTPOL (0x40U) /*!< Bit mask for CMT_OC_CMTPOL. */ #define BS_CMT_OC_CMTPOL (1U) /*!< Bit field size in bits for CMT_OC_CMTPOL. */ /*! @brief Read current value of the CMT_OC_CMTPOL field. */ #define BR_CMT_OC_CMTPOL(x) (BITBAND_ACCESS8(HW_CMT_OC_ADDR(x), BP_CMT_OC_CMTPOL)) /*! @brief Format value for bitfield CMT_OC_CMTPOL. */ #define BF_CMT_OC_CMTPOL(v) ((uint8_t)((uint8_t)(v) << BP_CMT_OC_CMTPOL) & BM_CMT_OC_CMTPOL) /*! @brief Set the CMTPOL field to a new value. */ #define BW_CMT_OC_CMTPOL(x, v) (BITBAND_ACCESS8(HW_CMT_OC_ADDR(x), BP_CMT_OC_CMTPOL) = (v)) /*@}*/ /*! * @name Register CMT_OC, field IROL[7] (RW) * * Reads the state of the IRO latch. Writing to IROL changes the state of the * IRO signal when MSC[MCGEN] is cleared and IROPEN is set. */ /*@{*/ #define BP_CMT_OC_IROL (7U) /*!< Bit position for CMT_OC_IROL. */ #define BM_CMT_OC_IROL (0x80U) /*!< Bit mask for CMT_OC_IROL. */ #define BS_CMT_OC_IROL (1U) /*!< Bit field size in bits for CMT_OC_IROL. */ /*! @brief Read current value of the CMT_OC_IROL field. */ #define BR_CMT_OC_IROL(x) (BITBAND_ACCESS8(HW_CMT_OC_ADDR(x), BP_CMT_OC_IROL)) /*! @brief Format value for bitfield CMT_OC_IROL. */ #define BF_CMT_OC_IROL(v) ((uint8_t)((uint8_t)(v) << BP_CMT_OC_IROL) & BM_CMT_OC_IROL) /*! @brief Set the IROL field to a new value. */ #define BW_CMT_OC_IROL(x, v) (BITBAND_ACCESS8(HW_CMT_OC_ADDR(x), BP_CMT_OC_IROL) = (v)) /*@}*/ /******************************************************************************* * HW_CMT_MSC - CMT Modulator Status and Control Register ******************************************************************************/ /*! * @brief HW_CMT_MSC - CMT Modulator Status and Control Register (RW) * * Reset value: 0x00U * * This register contains the modulator and carrier generator enable (MCGEN), * end of cycle interrupt enable (EOCIE), FSK mode select (FSK), baseband enable * (BASE), extended space (EXSPC), prescaler (CMTDIV) bits, and the end of cycle * (EOCF) status bit. */ typedef union _hw_cmt_msc { uint8_t U; struct _hw_cmt_msc_bitfields { uint8_t MCGEN : 1; /*!< [0] Modulator and Carrier Generator Enable */ uint8_t EOCIE : 1; /*!< [1] End of Cycle Interrupt Enable */ uint8_t FSK : 1; /*!< [2] FSK Mode Select */ uint8_t BASE : 1; /*!< [3] Baseband Enable */ uint8_t EXSPC : 1; /*!< [4] Extended Space Enable */ uint8_t CMTDIV : 2; /*!< [6:5] CMT Clock Divide Prescaler */ uint8_t EOCF : 1; /*!< [7] End Of Cycle Status Flag */ } B; } hw_cmt_msc_t; /*! * @name Constants and macros for entire CMT_MSC register */ /*@{*/ #define HW_CMT_MSC_ADDR(x) ((x) + 0x5U) #define HW_CMT_MSC(x) (*(__IO hw_cmt_msc_t *) HW_CMT_MSC_ADDR(x)) #define HW_CMT_MSC_RD(x) (HW_CMT_MSC(x).U) #define HW_CMT_MSC_WR(x, v) (HW_CMT_MSC(x).U = (v)) #define HW_CMT_MSC_SET(x, v) (HW_CMT_MSC_WR(x, HW_CMT_MSC_RD(x) | (v))) #define HW_CMT_MSC_CLR(x, v) (HW_CMT_MSC_WR(x, HW_CMT_MSC_RD(x) & ~(v))) #define HW_CMT_MSC_TOG(x, v) (HW_CMT_MSC_WR(x, HW_CMT_MSC_RD(x) ^ (v))) /*@}*/ /* * Constants & macros for individual CMT_MSC bitfields */ /*! * @name Register CMT_MSC, field MCGEN[0] (RW) * * Setting MCGEN will initialize the carrier generator and modulator and will * enable all clocks. When enabled, the carrier generator and modulator will * function continuously. When MCGEN is cleared, the current modulator cycle will be * allowed to expire before all carrier and modulator clocks are disabled to save * power and the modulator output is forced low. To prevent spurious operation, * the user should initialize all data and control registers before enabling the * system. * * Values: * - 0 - Modulator and carrier generator disabled * - 1 - Modulator and carrier generator enabled */ /*@{*/ #define BP_CMT_MSC_MCGEN (0U) /*!< Bit position for CMT_MSC_MCGEN. */ #define BM_CMT_MSC_MCGEN (0x01U) /*!< Bit mask for CMT_MSC_MCGEN. */ #define BS_CMT_MSC_MCGEN (1U) /*!< Bit field size in bits for CMT_MSC_MCGEN. */ /*! @brief Read current value of the CMT_MSC_MCGEN field. */ #define BR_CMT_MSC_MCGEN(x) (BITBAND_ACCESS8(HW_CMT_MSC_ADDR(x), BP_CMT_MSC_MCGEN)) /*! @brief Format value for bitfield CMT_MSC_MCGEN. */ #define BF_CMT_MSC_MCGEN(v) ((uint8_t)((uint8_t)(v) << BP_CMT_MSC_MCGEN) & BM_CMT_MSC_MCGEN) /*! @brief Set the MCGEN field to a new value. */ #define BW_CMT_MSC_MCGEN(x, v) (BITBAND_ACCESS8(HW_CMT_MSC_ADDR(x), BP_CMT_MSC_MCGEN) = (v)) /*@}*/ /*! * @name Register CMT_MSC, field EOCIE[1] (RW) * * Requests to enable a CPU interrupt when EOCF is set if EOCIE is high. * * Values: * - 0 - CPU interrupt is disabled. * - 1 - CPU interrupt is enabled. */ /*@{*/ #define BP_CMT_MSC_EOCIE (1U) /*!< Bit position for CMT_MSC_EOCIE. */ #define BM_CMT_MSC_EOCIE (0x02U) /*!< Bit mask for CMT_MSC_EOCIE. */ #define BS_CMT_MSC_EOCIE (1U) /*!< Bit field size in bits for CMT_MSC_EOCIE. */ /*! @brief Read current value of the CMT_MSC_EOCIE field. */ #define BR_CMT_MSC_EOCIE(x) (BITBAND_ACCESS8(HW_CMT_MSC_ADDR(x), BP_CMT_MSC_EOCIE)) /*! @brief Format value for bitfield CMT_MSC_EOCIE. */ #define BF_CMT_MSC_EOCIE(v) ((uint8_t)((uint8_t)(v) << BP_CMT_MSC_EOCIE) & BM_CMT_MSC_EOCIE) /*! @brief Set the EOCIE field to a new value. */ #define BW_CMT_MSC_EOCIE(x, v) (BITBAND_ACCESS8(HW_CMT_MSC_ADDR(x), BP_CMT_MSC_EOCIE) = (v)) /*@}*/ /*! * @name Register CMT_MSC, field FSK[2] (RW) * * Enables FSK operation. * * Values: * - 0 - The CMT operates in Time or Baseband mode. * - 1 - The CMT operates in FSK mode. */ /*@{*/ #define BP_CMT_MSC_FSK (2U) /*!< Bit position for CMT_MSC_FSK. */ #define BM_CMT_MSC_FSK (0x04U) /*!< Bit mask for CMT_MSC_FSK. */ #define BS_CMT_MSC_FSK (1U) /*!< Bit field size in bits for CMT_MSC_FSK. */ /*! @brief Read current value of the CMT_MSC_FSK field. */ #define BR_CMT_MSC_FSK(x) (BITBAND_ACCESS8(HW_CMT_MSC_ADDR(x), BP_CMT_MSC_FSK)) /*! @brief Format value for bitfield CMT_MSC_FSK. */ #define BF_CMT_MSC_FSK(v) ((uint8_t)((uint8_t)(v) << BP_CMT_MSC_FSK) & BM_CMT_MSC_FSK) /*! @brief Set the FSK field to a new value. */ #define BW_CMT_MSC_FSK(x, v) (BITBAND_ACCESS8(HW_CMT_MSC_ADDR(x), BP_CMT_MSC_FSK) = (v)) /*@}*/ /*! * @name Register CMT_MSC, field BASE[3] (RW) * * When set, BASE disables the carrier generator and forces the carrier output * high for generation of baseband protocols. When BASE is cleared, the carrier * generator is enabled and the carrier output toggles at the frequency determined * by values stored in the carrier data registers. This field is cleared by * reset. This field is not double-buffered and must not be written to during a * transmission. * * Values: * - 0 - Baseband mode is disabled. * - 1 - Baseband mode is enabled. */ /*@{*/ #define BP_CMT_MSC_BASE (3U) /*!< Bit position for CMT_MSC_BASE. */ #define BM_CMT_MSC_BASE (0x08U) /*!< Bit mask for CMT_MSC_BASE. */ #define BS_CMT_MSC_BASE (1U) /*!< Bit field size in bits for CMT_MSC_BASE. */ /*! @brief Read current value of the CMT_MSC_BASE field. */ #define BR_CMT_MSC_BASE(x) (BITBAND_ACCESS8(HW_CMT_MSC_ADDR(x), BP_CMT_MSC_BASE)) /*! @brief Format value for bitfield CMT_MSC_BASE. */ #define BF_CMT_MSC_BASE(v) ((uint8_t)((uint8_t)(v) << BP_CMT_MSC_BASE) & BM_CMT_MSC_BASE) /*! @brief Set the BASE field to a new value. */ #define BW_CMT_MSC_BASE(x, v) (BITBAND_ACCESS8(HW_CMT_MSC_ADDR(x), BP_CMT_MSC_BASE) = (v)) /*@}*/ /*! * @name Register CMT_MSC, field EXSPC[4] (RW) * * Enables the extended space operation. * * Values: * - 0 - Extended space is disabled. * - 1 - Extended space is enabled. */ /*@{*/ #define BP_CMT_MSC_EXSPC (4U) /*!< Bit position for CMT_MSC_EXSPC. */ #define BM_CMT_MSC_EXSPC (0x10U) /*!< Bit mask for CMT_MSC_EXSPC. */ #define BS_CMT_MSC_EXSPC (1U) /*!< Bit field size in bits for CMT_MSC_EXSPC. */ /*! @brief Read current value of the CMT_MSC_EXSPC field. */ #define BR_CMT_MSC_EXSPC(x) (BITBAND_ACCESS8(HW_CMT_MSC_ADDR(x), BP_CMT_MSC_EXSPC)) /*! @brief Format value for bitfield CMT_MSC_EXSPC. */ #define BF_CMT_MSC_EXSPC(v) ((uint8_t)((uint8_t)(v) << BP_CMT_MSC_EXSPC) & BM_CMT_MSC_EXSPC) /*! @brief Set the EXSPC field to a new value. */ #define BW_CMT_MSC_EXSPC(x, v) (BITBAND_ACCESS8(HW_CMT_MSC_ADDR(x), BP_CMT_MSC_EXSPC) = (v)) /*@}*/ /*! * @name Register CMT_MSC, field CMTDIV[6:5] (RW) * * Causes the CMT to be clocked at the IF signal frequency, or the IF frequency * divided by 2 ,4, or 8 . This field must not be changed during a transmission * because it is not double-buffered. * * Values: * - 00 - IF * 1 * - 01 - IF * 2 * - 10 - IF * 4 * - 11 - IF * 8 */ /*@{*/ #define BP_CMT_MSC_CMTDIV (5U) /*!< Bit position for CMT_MSC_CMTDIV. */ #define BM_CMT_MSC_CMTDIV (0x60U) /*!< Bit mask for CMT_MSC_CMTDIV. */ #define BS_CMT_MSC_CMTDIV (2U) /*!< Bit field size in bits for CMT_MSC_CMTDIV. */ /*! @brief Read current value of the CMT_MSC_CMTDIV field. */ #define BR_CMT_MSC_CMTDIV(x) (HW_CMT_MSC(x).B.CMTDIV) /*! @brief Format value for bitfield CMT_MSC_CMTDIV. */ #define BF_CMT_MSC_CMTDIV(v) ((uint8_t)((uint8_t)(v) << BP_CMT_MSC_CMTDIV) & BM_CMT_MSC_CMTDIV) /*! @brief Set the CMTDIV field to a new value. */ #define BW_CMT_MSC_CMTDIV(x, v) (HW_CMT_MSC_WR(x, (HW_CMT_MSC_RD(x) & ~BM_CMT_MSC_CMTDIV) | BF_CMT_MSC_CMTDIV(v))) /*@}*/ /*! * @name Register CMT_MSC, field EOCF[7] (RO) * * Sets when: The modulator is not currently active and MCGEN is set to begin * the initial CMT transmission. At the end of each modulation cycle while MCGEN is * set. This is recognized when a match occurs between the contents of the space * period register and the down counter. At this time, the counter is * initialized with, possibly new contents of the mark period buffer, CMD1 and CMD2, and * the space period register is loaded with, possibly new contents of the space * period buffer, CMD3 and CMD4. This flag is cleared by reading MSC followed by an * access of CMD2 or CMD4, or by the DMA transfer. * * Values: * - 0 - End of modulation cycle has not occured since the flag last cleared. * - 1 - End of modulator cycle has occurred. */ /*@{*/ #define BP_CMT_MSC_EOCF (7U) /*!< Bit position for CMT_MSC_EOCF. */ #define BM_CMT_MSC_EOCF (0x80U) /*!< Bit mask for CMT_MSC_EOCF. */ #define BS_CMT_MSC_EOCF (1U) /*!< Bit field size in bits for CMT_MSC_EOCF. */ /*! @brief Read current value of the CMT_MSC_EOCF field. */ #define BR_CMT_MSC_EOCF(x) (BITBAND_ACCESS8(HW_CMT_MSC_ADDR(x), BP_CMT_MSC_EOCF)) /*@}*/ /******************************************************************************* * HW_CMT_CMD1 - CMT Modulator Data Register Mark High ******************************************************************************/ /*! * @brief HW_CMT_CMD1 - CMT Modulator Data Register Mark High (RW) * * Reset value: 0x00U * * The contents of this register are transferred to the modulator down counter * upon the completion of a modulation period. */ typedef union _hw_cmt_cmd1 { uint8_t U; struct _hw_cmt_cmd1_bitfields { uint8_t MB : 8; /*!< [7:0] */ } B; } hw_cmt_cmd1_t; /*! * @name Constants and macros for entire CMT_CMD1 register */ /*@{*/ #define HW_CMT_CMD1_ADDR(x) ((x) + 0x6U) #define HW_CMT_CMD1(x) (*(__IO hw_cmt_cmd1_t *) HW_CMT_CMD1_ADDR(x)) #define HW_CMT_CMD1_RD(x) (HW_CMT_CMD1(x).U) #define HW_CMT_CMD1_WR(x, v) (HW_CMT_CMD1(x).U = (v)) #define HW_CMT_CMD1_SET(x, v) (HW_CMT_CMD1_WR(x, HW_CMT_CMD1_RD(x) | (v))) #define HW_CMT_CMD1_CLR(x, v) (HW_CMT_CMD1_WR(x, HW_CMT_CMD1_RD(x) & ~(v))) #define HW_CMT_CMD1_TOG(x, v) (HW_CMT_CMD1_WR(x, HW_CMT_CMD1_RD(x) ^ (v))) /*@}*/ /* * Constants & macros for individual CMT_CMD1 bitfields */ /*! * @name Register CMT_CMD1, field MB[7:0] (RW) * * Controls the upper mark periods of the modulator for all modes. */ /*@{*/ #define BP_CMT_CMD1_MB (0U) /*!< Bit position for CMT_CMD1_MB. */ #define BM_CMT_CMD1_MB (0xFFU) /*!< Bit mask for CMT_CMD1_MB. */ #define BS_CMT_CMD1_MB (8U) /*!< Bit field size in bits for CMT_CMD1_MB. */ /*! @brief Read current value of the CMT_CMD1_MB field. */ #define BR_CMT_CMD1_MB(x) (HW_CMT_CMD1(x).U) /*! @brief Format value for bitfield CMT_CMD1_MB. */ #define BF_CMT_CMD1_MB(v) ((uint8_t)((uint8_t)(v) << BP_CMT_CMD1_MB) & BM_CMT_CMD1_MB) /*! @brief Set the MB field to a new value. */ #define BW_CMT_CMD1_MB(x, v) (HW_CMT_CMD1_WR(x, v)) /*@}*/ /******************************************************************************* * HW_CMT_CMD2 - CMT Modulator Data Register Mark Low ******************************************************************************/ /*! * @brief HW_CMT_CMD2 - CMT Modulator Data Register Mark Low (RW) * * Reset value: 0x00U * * The contents of this register are transferred to the modulator down counter * upon the completion of a modulation period. */ typedef union _hw_cmt_cmd2 { uint8_t U; struct _hw_cmt_cmd2_bitfields { uint8_t MB : 8; /*!< [7:0] */ } B; } hw_cmt_cmd2_t; /*! * @name Constants and macros for entire CMT_CMD2 register */ /*@{*/ #define HW_CMT_CMD2_ADDR(x) ((x) + 0x7U) #define HW_CMT_CMD2(x) (*(__IO hw_cmt_cmd2_t *) HW_CMT_CMD2_ADDR(x)) #define HW_CMT_CMD2_RD(x) (HW_CMT_CMD2(x).U) #define HW_CMT_CMD2_WR(x, v) (HW_CMT_CMD2(x).U = (v)) #define HW_CMT_CMD2_SET(x, v) (HW_CMT_CMD2_WR(x, HW_CMT_CMD2_RD(x) | (v))) #define HW_CMT_CMD2_CLR(x, v) (HW_CMT_CMD2_WR(x, HW_CMT_CMD2_RD(x) & ~(v))) #define HW_CMT_CMD2_TOG(x, v) (HW_CMT_CMD2_WR(x, HW_CMT_CMD2_RD(x) ^ (v))) /*@}*/ /* * Constants & macros for individual CMT_CMD2 bitfields */ /*! * @name Register CMT_CMD2, field MB[7:0] (RW) * * Controls the lower mark periods of the modulator for all modes. */ /*@{*/ #define BP_CMT_CMD2_MB (0U) /*!< Bit position for CMT_CMD2_MB. */ #define BM_CMT_CMD2_MB (0xFFU) /*!< Bit mask for CMT_CMD2_MB. */ #define BS_CMT_CMD2_MB (8U) /*!< Bit field size in bits for CMT_CMD2_MB. */ /*! @brief Read current value of the CMT_CMD2_MB field. */ #define BR_CMT_CMD2_MB(x) (HW_CMT_CMD2(x).U) /*! @brief Format value for bitfield CMT_CMD2_MB. */ #define BF_CMT_CMD2_MB(v) ((uint8_t)((uint8_t)(v) << BP_CMT_CMD2_MB) & BM_CMT_CMD2_MB) /*! @brief Set the MB field to a new value. */ #define BW_CMT_CMD2_MB(x, v) (HW_CMT_CMD2_WR(x, v)) /*@}*/ /******************************************************************************* * HW_CMT_CMD3 - CMT Modulator Data Register Space High ******************************************************************************/ /*! * @brief HW_CMT_CMD3 - CMT Modulator Data Register Space High (RW) * * Reset value: 0x00U * * The contents of this register are transferred to the space period register * upon the completion of a modulation period. */ typedef union _hw_cmt_cmd3 { uint8_t U; struct _hw_cmt_cmd3_bitfields { uint8_t SB : 8; /*!< [7:0] */ } B; } hw_cmt_cmd3_t; /*! * @name Constants and macros for entire CMT_CMD3 register */ /*@{*/ #define HW_CMT_CMD3_ADDR(x) ((x) + 0x8U) #define HW_CMT_CMD3(x) (*(__IO hw_cmt_cmd3_t *) HW_CMT_CMD3_ADDR(x)) #define HW_CMT_CMD3_RD(x) (HW_CMT_CMD3(x).U) #define HW_CMT_CMD3_WR(x, v) (HW_CMT_CMD3(x).U = (v)) #define HW_CMT_CMD3_SET(x, v) (HW_CMT_CMD3_WR(x, HW_CMT_CMD3_RD(x) | (v))) #define HW_CMT_CMD3_CLR(x, v) (HW_CMT_CMD3_WR(x, HW_CMT_CMD3_RD(x) & ~(v))) #define HW_CMT_CMD3_TOG(x, v) (HW_CMT_CMD3_WR(x, HW_CMT_CMD3_RD(x) ^ (v))) /*@}*/ /* * Constants & macros for individual CMT_CMD3 bitfields */ /*! * @name Register CMT_CMD3, field SB[7:0] (RW) * * Controls the upper space periods of the modulator for all modes. */ /*@{*/ #define BP_CMT_CMD3_SB (0U) /*!< Bit position for CMT_CMD3_SB. */ #define BM_CMT_CMD3_SB (0xFFU) /*!< Bit mask for CMT_CMD3_SB. */ #define BS_CMT_CMD3_SB (8U) /*!< Bit field size in bits for CMT_CMD3_SB. */ /*! @brief Read current value of the CMT_CMD3_SB field. */ #define BR_CMT_CMD3_SB(x) (HW_CMT_CMD3(x).U) /*! @brief Format value for bitfield CMT_CMD3_SB. */ #define BF_CMT_CMD3_SB(v) ((uint8_t)((uint8_t)(v) << BP_CMT_CMD3_SB) & BM_CMT_CMD3_SB) /*! @brief Set the SB field to a new value. */ #define BW_CMT_CMD3_SB(x, v) (HW_CMT_CMD3_WR(x, v)) /*@}*/ /******************************************************************************* * HW_CMT_CMD4 - CMT Modulator Data Register Space Low ******************************************************************************/ /*! * @brief HW_CMT_CMD4 - CMT Modulator Data Register Space Low (RW) * * Reset value: 0x00U * * The contents of this register are transferred to the space period register * upon the completion of a modulation period. */ typedef union _hw_cmt_cmd4 { uint8_t U; struct _hw_cmt_cmd4_bitfields { uint8_t SB : 8; /*!< [7:0] */ } B; } hw_cmt_cmd4_t; /*! * @name Constants and macros for entire CMT_CMD4 register */ /*@{*/ #define HW_CMT_CMD4_ADDR(x) ((x) + 0x9U) #define HW_CMT_CMD4(x) (*(__IO hw_cmt_cmd4_t *) HW_CMT_CMD4_ADDR(x)) #define HW_CMT_CMD4_RD(x) (HW_CMT_CMD4(x).U) #define HW_CMT_CMD4_WR(x, v) (HW_CMT_CMD4(x).U = (v)) #define HW_CMT_CMD4_SET(x, v) (HW_CMT_CMD4_WR(x, HW_CMT_CMD4_RD(x) | (v))) #define HW_CMT_CMD4_CLR(x, v) (HW_CMT_CMD4_WR(x, HW_CMT_CMD4_RD(x) & ~(v))) #define HW_CMT_CMD4_TOG(x, v) (HW_CMT_CMD4_WR(x, HW_CMT_CMD4_RD(x) ^ (v))) /*@}*/ /* * Constants & macros for individual CMT_CMD4 bitfields */ /*! * @name Register CMT_CMD4, field SB[7:0] (RW) * * Controls the lower space periods of the modulator for all modes. */ /*@{*/ #define BP_CMT_CMD4_SB (0U) /*!< Bit position for CMT_CMD4_SB. */ #define BM_CMT_CMD4_SB (0xFFU) /*!< Bit mask for CMT_CMD4_SB. */ #define BS_CMT_CMD4_SB (8U) /*!< Bit field size in bits for CMT_CMD4_SB. */ /*! @brief Read current value of the CMT_CMD4_SB field. */ #define BR_CMT_CMD4_SB(x) (HW_CMT_CMD4(x).U) /*! @brief Format value for bitfield CMT_CMD4_SB. */ #define BF_CMT_CMD4_SB(v) ((uint8_t)((uint8_t)(v) << BP_CMT_CMD4_SB) & BM_CMT_CMD4_SB) /*! @brief Set the SB field to a new value. */ #define BW_CMT_CMD4_SB(x, v) (HW_CMT_CMD4_WR(x, v)) /*@}*/ /******************************************************************************* * HW_CMT_PPS - CMT Primary Prescaler Register ******************************************************************************/ /*! * @brief HW_CMT_PPS - CMT Primary Prescaler Register (RW) * * Reset value: 0x00U * * This register is used to set the Primary Prescaler Divider field (PPSDIV). */ typedef union _hw_cmt_pps { uint8_t U; struct _hw_cmt_pps_bitfields { uint8_t PPSDIV : 4; /*!< [3:0] Primary Prescaler Divider */ uint8_t RESERVED0 : 4; /*!< [7:4] */ } B; } hw_cmt_pps_t; /*! * @name Constants and macros for entire CMT_PPS register */ /*@{*/ #define HW_CMT_PPS_ADDR(x) ((x) + 0xAU) #define HW_CMT_PPS(x) (*(__IO hw_cmt_pps_t *) HW_CMT_PPS_ADDR(x)) #define HW_CMT_PPS_RD(x) (HW_CMT_PPS(x).U) #define HW_CMT_PPS_WR(x, v) (HW_CMT_PPS(x).U = (v)) #define HW_CMT_PPS_SET(x, v) (HW_CMT_PPS_WR(x, HW_CMT_PPS_RD(x) | (v))) #define HW_CMT_PPS_CLR(x, v) (HW_CMT_PPS_WR(x, HW_CMT_PPS_RD(x) & ~(v))) #define HW_CMT_PPS_TOG(x, v) (HW_CMT_PPS_WR(x, HW_CMT_PPS_RD(x) ^ (v))) /*@}*/ /* * Constants & macros for individual CMT_PPS bitfields */ /*! * @name Register CMT_PPS, field PPSDIV[3:0] (RW) * * Divides the CMT clock to generate the Intermediate Frequency clock enable to * the secondary prescaler. * * Values: * - 0000 - Bus clock * 1 * - 0001 - Bus clock * 2 * - 0010 - Bus clock * 3 * - 0011 - Bus clock * 4 * - 0100 - Bus clock * 5 * - 0101 - Bus clock * 6 * - 0110 - Bus clock * 7 * - 0111 - Bus clock * 8 * - 1000 - Bus clock * 9 * - 1001 - Bus clock * 10 * - 1010 - Bus clock * 11 * - 1011 - Bus clock * 12 * - 1100 - Bus clock * 13 * - 1101 - Bus clock * 14 * - 1110 - Bus clock * 15 * - 1111 - Bus clock * 16 */ /*@{*/ #define BP_CMT_PPS_PPSDIV (0U) /*!< Bit position for CMT_PPS_PPSDIV. */ #define BM_CMT_PPS_PPSDIV (0x0FU) /*!< Bit mask for CMT_PPS_PPSDIV. */ #define BS_CMT_PPS_PPSDIV (4U) /*!< Bit field size in bits for CMT_PPS_PPSDIV. */ /*! @brief Read current value of the CMT_PPS_PPSDIV field. */ #define BR_CMT_PPS_PPSDIV(x) (HW_CMT_PPS(x).B.PPSDIV) /*! @brief Format value for bitfield CMT_PPS_PPSDIV. */ #define BF_CMT_PPS_PPSDIV(v) ((uint8_t)((uint8_t)(v) << BP_CMT_PPS_PPSDIV) & BM_CMT_PPS_PPSDIV) /*! @brief Set the PPSDIV field to a new value. */ #define BW_CMT_PPS_PPSDIV(x, v) (HW_CMT_PPS_WR(x, (HW_CMT_PPS_RD(x) & ~BM_CMT_PPS_PPSDIV) | BF_CMT_PPS_PPSDIV(v))) /*@}*/ /******************************************************************************* * HW_CMT_DMA - CMT Direct Memory Access Register ******************************************************************************/ /*! * @brief HW_CMT_DMA - CMT Direct Memory Access Register (RW) * * Reset value: 0x00U * * This register is used to enable/disable direct memory access (DMA). */ typedef union _hw_cmt_dma { uint8_t U; struct _hw_cmt_dma_bitfields { uint8_t DMA : 1; /*!< [0] DMA Enable */ uint8_t RESERVED0 : 7; /*!< [7:1] */ } B; } hw_cmt_dma_t; /*! * @name Constants and macros for entire CMT_DMA register */ /*@{*/ #define HW_CMT_DMA_ADDR(x) ((x) + 0xBU) #define HW_CMT_DMA(x) (*(__IO hw_cmt_dma_t *) HW_CMT_DMA_ADDR(x)) #define HW_CMT_DMA_RD(x) (HW_CMT_DMA(x).U) #define HW_CMT_DMA_WR(x, v) (HW_CMT_DMA(x).U = (v)) #define HW_CMT_DMA_SET(x, v) (HW_CMT_DMA_WR(x, HW_CMT_DMA_RD(x) | (v))) #define HW_CMT_DMA_CLR(x, v) (HW_CMT_DMA_WR(x, HW_CMT_DMA_RD(x) & ~(v))) #define HW_CMT_DMA_TOG(x, v) (HW_CMT_DMA_WR(x, HW_CMT_DMA_RD(x) ^ (v))) /*@}*/ /* * Constants & macros for individual CMT_DMA bitfields */ /*! * @name Register CMT_DMA, field DMA[0] (RW) * * Enables the DMA protocol. * * Values: * - 0 - DMA transfer request and done are disabled. * - 1 - DMA transfer request and done are enabled. */ /*@{*/ #define BP_CMT_DMA_DMA (0U) /*!< Bit position for CMT_DMA_DMA. */ #define BM_CMT_DMA_DMA (0x01U) /*!< Bit mask for CMT_DMA_DMA. */ #define BS_CMT_DMA_DMA (1U) /*!< Bit field size in bits for CMT_DMA_DMA. */ /*! @brief Read current value of the CMT_DMA_DMA field. */ #define BR_CMT_DMA_DMA(x) (BITBAND_ACCESS8(HW_CMT_DMA_ADDR(x), BP_CMT_DMA_DMA)) /*! @brief Format value for bitfield CMT_DMA_DMA. */ #define BF_CMT_DMA_DMA(v) ((uint8_t)((uint8_t)(v) << BP_CMT_DMA_DMA) & BM_CMT_DMA_DMA) /*! @brief Set the DMA field to a new value. */ #define BW_CMT_DMA_DMA(x, v) (BITBAND_ACCESS8(HW_CMT_DMA_ADDR(x), BP_CMT_DMA_DMA) = (v)) /*@}*/ /******************************************************************************* * hw_cmt_t - module struct ******************************************************************************/ /*! * @brief All CMT module registers. */ #pragma pack(1) typedef struct _hw_cmt { __IO hw_cmt_cgh1_t CGH1; /*!< [0x0] CMT Carrier Generator High Data Register 1 */ __IO hw_cmt_cgl1_t CGL1; /*!< [0x1] CMT Carrier Generator Low Data Register 1 */ __IO hw_cmt_cgh2_t CGH2; /*!< [0x2] CMT Carrier Generator High Data Register 2 */ __IO hw_cmt_cgl2_t CGL2; /*!< [0x3] CMT Carrier Generator Low Data Register 2 */ __IO hw_cmt_oc_t OC; /*!< [0x4] CMT Output Control Register */ __IO hw_cmt_msc_t MSC; /*!< [0x5] CMT Modulator Status and Control Register */ __IO hw_cmt_cmd1_t CMD1; /*!< [0x6] CMT Modulator Data Register Mark High */ __IO hw_cmt_cmd2_t CMD2; /*!< [0x7] CMT Modulator Data Register Mark Low */ __IO hw_cmt_cmd3_t CMD3; /*!< [0x8] CMT Modulator Data Register Space High */ __IO hw_cmt_cmd4_t CMD4; /*!< [0x9] CMT Modulator Data Register Space Low */ __IO hw_cmt_pps_t PPS; /*!< [0xA] CMT Primary Prescaler Register */ __IO hw_cmt_dma_t DMA; /*!< [0xB] CMT Direct Memory Access Register */ } hw_cmt_t; #pragma pack() /*! @brief Macro to access all CMT registers. */ /*! @param x CMT module instance base address. */ /*! @return Reference (not a pointer) to the registers struct. To get a pointer to the struct, * use the '&' operator, like &HW_CMT(CMT_BASE). */ #define HW_CMT(x) (*(hw_cmt_t *)(x)) #endif /* __HW_CMT_REGISTERS_H__ */ /* EOF */ ================================================ FILE: Zelig/mbed/TARGET_K64F/TARGET_Freescale/TARGET_KPSDK_MCUS/TARGET_MCU_K64F/device/device/MK64F12/MK64F12_crc.h ================================================ /* ** ################################################################### ** Compilers: Keil ARM C/C++ Compiler ** Freescale C/C++ for Embedded ARM ** GNU C Compiler ** IAR ANSI C/C++ Compiler for ARM ** ** Reference manual: K64P144M120SF5RM, Rev.2, January 2014 ** Version: rev. 2.5, 2014-02-10 ** Build: b140604 ** ** Abstract: ** Extension to the CMSIS register access layer header. ** ** Copyright (c) 2014 Freescale Semiconductor, Inc. ** All rights reserved. ** ** Redistribution and use in source and binary forms, with or without modification, ** are permitted provided that the following conditions are met: ** ** o Redistributions of source code must retain the above copyright notice, this list ** of conditions and the following disclaimer. ** ** o Redistributions in binary form must reproduce the above copyright notice, this ** list of conditions and the following disclaimer in the documentation and/or ** other materials provided with the distribution. ** ** o Neither the name of Freescale Semiconductor, Inc. nor the names of its ** contributors may be used to endorse or promote products derived from this ** software without specific prior written permission. ** ** THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ** ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED ** WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE ** DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT 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. ** ** http: www.freescale.com ** mail: support@freescale.com ** ** Revisions: ** - rev. 1.0 (2013-08-12) ** Initial version. ** - rev. 2.0 (2013-10-29) ** Register accessor macros added to the memory map. ** Symbols for Processor Expert memory map compatibility added to the memory map. ** Startup file for gcc has been updated according to CMSIS 3.2. ** System initialization updated. ** MCG - registers updated. ** PORTA, PORTB, PORTC, PORTE - registers for digital filter removed. ** - rev. 2.1 (2013-10-30) ** Definition of BITBAND macros updated to support peripherals with 32-bit acces disabled. ** - rev. 2.2 (2013-12-09) ** DMA - EARS register removed. ** AIPS0, AIPS1 - MPRA register updated. ** - rev. 2.3 (2014-01-24) ** Update according to reference manual rev. 2 ** ENET, MCG, MCM, SIM, USB - registers updated ** - rev. 2.4 (2014-02-10) ** The declaration of clock configurations has been moved to separate header file system_MK64F12.h ** Update of SystemInit() and SystemCoreClockUpdate() functions. ** - rev. 2.5 (2014-02-10) ** The declaration of clock configurations has been moved to separate header file system_MK64F12.h ** Update of SystemInit() and SystemCoreClockUpdate() functions. ** Module access macro module_BASES replaced by module_BASE_PTRS. ** ** ################################################################### */ /* * WARNING! DO NOT EDIT THIS FILE DIRECTLY! * * This file was generated automatically and any changes may be lost. */ #ifndef __HW_CRC_REGISTERS_H__ #define __HW_CRC_REGISTERS_H__ #include "MK64F12.h" #include "fsl_bitaccess.h" /* * MK64F12 CRC * * Cyclic Redundancy Check * * Registers defined in this header file: * - HW_CRC_DATAL - CRC_DATAL register. * - HW_CRC_DATAH - CRC_DATAH register. * - HW_CRC_DATALL - CRC_DATALL register. * - HW_CRC_DATALU - CRC_DATALU register. * - HW_CRC_DATAHL - CRC_DATAHL register. * - HW_CRC_DATAHU - CRC_DATAHU register. * - HW_CRC_DATA - CRC Data register * - HW_CRC_GPOLY - CRC Polynomial register * - HW_CRC_GPOLYL - CRC_GPOLYL register. * - HW_CRC_GPOLYH - CRC_GPOLYH register. * - HW_CRC_GPOLYLL - CRC_GPOLYLL register. * - HW_CRC_GPOLYLU - CRC_GPOLYLU register. * - HW_CRC_GPOLYHL - CRC_GPOLYHL register. * - HW_CRC_GPOLYHU - CRC_GPOLYHU register. * - HW_CRC_CTRL - CRC Control register * - HW_CRC_CTRLHU - CRC_CTRLHU register. * * - hw_crc_t - Struct containing all module registers. */ #define HW_CRC_INSTANCE_COUNT (1U) /*!< Number of instances of the CRC module. */ /******************************************************************************* * HW_CRC_DATAL - CRC_DATAL register. ******************************************************************************/ /*! * @brief HW_CRC_DATAL - CRC_DATAL register. (RW) * * Reset value: 0xFFFFU */ typedef union _hw_crc_datal { uint16_t U; struct _hw_crc_datal_bitfields { uint16_t DATAL : 16; /*!< [15:0] DATAL stores the lower 16 bits of * the 16/32 bit CRC */ } B; } hw_crc_datal_t; /*! * @name Constants and macros for entire CRC_DATAL register */ /*@{*/ #define HW_CRC_DATAL_ADDR(x) ((x) + 0x0U) #define HW_CRC_DATAL(x) (*(__IO hw_crc_datal_t *) HW_CRC_DATAL_ADDR(x)) #define HW_CRC_DATAL_RD(x) (HW_CRC_DATAL(x).U) #define HW_CRC_DATAL_WR(x, v) (HW_CRC_DATAL(x).U = (v)) #define HW_CRC_DATAL_SET(x, v) (HW_CRC_DATAL_WR(x, HW_CRC_DATAL_RD(x) | (v))) #define HW_CRC_DATAL_CLR(x, v) (HW_CRC_DATAL_WR(x, HW_CRC_DATAL_RD(x) & ~(v))) #define HW_CRC_DATAL_TOG(x, v) (HW_CRC_DATAL_WR(x, HW_CRC_DATAL_RD(x) ^ (v))) /*@}*/ /* * Constants & macros for individual CRC_DATAL bitfields */ /*! * @name Register CRC_DATAL, field DATAL[15:0] (RW) */ /*@{*/ #define BP_CRC_DATAL_DATAL (0U) /*!< Bit position for CRC_DATAL_DATAL. */ #define BM_CRC_DATAL_DATAL (0xFFFFU) /*!< Bit mask for CRC_DATAL_DATAL. */ #define BS_CRC_DATAL_DATAL (16U) /*!< Bit field size in bits for CRC_DATAL_DATAL. */ /*! @brief Read current value of the CRC_DATAL_DATAL field. */ #define BR_CRC_DATAL_DATAL(x) (HW_CRC_DATAL(x).U) /*! @brief Format value for bitfield CRC_DATAL_DATAL. */ #define BF_CRC_DATAL_DATAL(v) ((uint16_t)((uint16_t)(v) << BP_CRC_DATAL_DATAL) & BM_CRC_DATAL_DATAL) /*! @brief Set the DATAL field to a new value. */ #define BW_CRC_DATAL_DATAL(x, v) (HW_CRC_DATAL_WR(x, v)) /*@}*/ /******************************************************************************* * HW_CRC_DATAH - CRC_DATAH register. ******************************************************************************/ /*! * @brief HW_CRC_DATAH - CRC_DATAH register. (RW) * * Reset value: 0xFFFFU */ typedef union _hw_crc_datah { uint16_t U; struct _hw_crc_datah_bitfields { uint16_t DATAH : 16; /*!< [15:0] DATAH stores the high 16 bits of the * 16/32 bit CRC */ } B; } hw_crc_datah_t; /*! * @name Constants and macros for entire CRC_DATAH register */ /*@{*/ #define HW_CRC_DATAH_ADDR(x) ((x) + 0x2U) #define HW_CRC_DATAH(x) (*(__IO hw_crc_datah_t *) HW_CRC_DATAH_ADDR(x)) #define HW_CRC_DATAH_RD(x) (HW_CRC_DATAH(x).U) #define HW_CRC_DATAH_WR(x, v) (HW_CRC_DATAH(x).U = (v)) #define HW_CRC_DATAH_SET(x, v) (HW_CRC_DATAH_WR(x, HW_CRC_DATAH_RD(x) | (v))) #define HW_CRC_DATAH_CLR(x, v) (HW_CRC_DATAH_WR(x, HW_CRC_DATAH_RD(x) & ~(v))) #define HW_CRC_DATAH_TOG(x, v) (HW_CRC_DATAH_WR(x, HW_CRC_DATAH_RD(x) ^ (v))) /*@}*/ /* * Constants & macros for individual CRC_DATAH bitfields */ /*! * @name Register CRC_DATAH, field DATAH[15:0] (RW) */ /*@{*/ #define BP_CRC_DATAH_DATAH (0U) /*!< Bit position for CRC_DATAH_DATAH. */ #define BM_CRC_DATAH_DATAH (0xFFFFU) /*!< Bit mask for CRC_DATAH_DATAH. */ #define BS_CRC_DATAH_DATAH (16U) /*!< Bit field size in bits for CRC_DATAH_DATAH. */ /*! @brief Read current value of the CRC_DATAH_DATAH field. */ #define BR_CRC_DATAH_DATAH(x) (HW_CRC_DATAH(x).U) /*! @brief Format value for bitfield CRC_DATAH_DATAH. */ #define BF_CRC_DATAH_DATAH(v) ((uint16_t)((uint16_t)(v) << BP_CRC_DATAH_DATAH) & BM_CRC_DATAH_DATAH) /*! @brief Set the DATAH field to a new value. */ #define BW_CRC_DATAH_DATAH(x, v) (HW_CRC_DATAH_WR(x, v)) /*@}*/ /******************************************************************************* * HW_CRC_DATALL - CRC_DATALL register. ******************************************************************************/ /*! * @brief HW_CRC_DATALL - CRC_DATALL register. (RW) * * Reset value: 0xFFU */ typedef union _hw_crc_datall { uint8_t U; struct _hw_crc_datall_bitfields { uint8_t DATALL : 8; /*!< [7:0] CRCLL stores the first 8 bits of the * 32 bit DATA */ } B; } hw_crc_datall_t; /*! * @name Constants and macros for entire CRC_DATALL register */ /*@{*/ #define HW_CRC_DATALL_ADDR(x) ((x) + 0x0U) #define HW_CRC_DATALL(x) (*(__IO hw_crc_datall_t *) HW_CRC_DATALL_ADDR(x)) #define HW_CRC_DATALL_RD(x) (HW_CRC_DATALL(x).U) #define HW_CRC_DATALL_WR(x, v) (HW_CRC_DATALL(x).U = (v)) #define HW_CRC_DATALL_SET(x, v) (HW_CRC_DATALL_WR(x, HW_CRC_DATALL_RD(x) | (v))) #define HW_CRC_DATALL_CLR(x, v) (HW_CRC_DATALL_WR(x, HW_CRC_DATALL_RD(x) & ~(v))) #define HW_CRC_DATALL_TOG(x, v) (HW_CRC_DATALL_WR(x, HW_CRC_DATALL_RD(x) ^ (v))) /*@}*/ /* * Constants & macros for individual CRC_DATALL bitfields */ /*! * @name Register CRC_DATALL, field DATALL[7:0] (RW) */ /*@{*/ #define BP_CRC_DATALL_DATALL (0U) /*!< Bit position for CRC_DATALL_DATALL. */ #define BM_CRC_DATALL_DATALL (0xFFU) /*!< Bit mask for CRC_DATALL_DATALL. */ #define BS_CRC_DATALL_DATALL (8U) /*!< Bit field size in bits for CRC_DATALL_DATALL. */ /*! @brief Read current value of the CRC_DATALL_DATALL field. */ #define BR_CRC_DATALL_DATALL(x) (HW_CRC_DATALL(x).U) /*! @brief Format value for bitfield CRC_DATALL_DATALL. */ #define BF_CRC_DATALL_DATALL(v) ((uint8_t)((uint8_t)(v) << BP_CRC_DATALL_DATALL) & BM_CRC_DATALL_DATALL) /*! @brief Set the DATALL field to a new value. */ #define BW_CRC_DATALL_DATALL(x, v) (HW_CRC_DATALL_WR(x, v)) /*@}*/ /******************************************************************************* * HW_CRC_DATALU - CRC_DATALU register. ******************************************************************************/ /*! * @brief HW_CRC_DATALU - CRC_DATALU register. (RW) * * Reset value: 0xFFU */ typedef union _hw_crc_datalu { uint8_t U; struct _hw_crc_datalu_bitfields { uint8_t DATALU : 8; /*!< [7:0] DATALL stores the second 8 bits of the * 32 bit CRC */ } B; } hw_crc_datalu_t; /*! * @name Constants and macros for entire CRC_DATALU register */ /*@{*/ #define HW_CRC_DATALU_ADDR(x) ((x) + 0x1U) #define HW_CRC_DATALU(x) (*(__IO hw_crc_datalu_t *) HW_CRC_DATALU_ADDR(x)) #define HW_CRC_DATALU_RD(x) (HW_CRC_DATALU(x).U) #define HW_CRC_DATALU_WR(x, v) (HW_CRC_DATALU(x).U = (v)) #define HW_CRC_DATALU_SET(x, v) (HW_CRC_DATALU_WR(x, HW_CRC_DATALU_RD(x) | (v))) #define HW_CRC_DATALU_CLR(x, v) (HW_CRC_DATALU_WR(x, HW_CRC_DATALU_RD(x) & ~(v))) #define HW_CRC_DATALU_TOG(x, v) (HW_CRC_DATALU_WR(x, HW_CRC_DATALU_RD(x) ^ (v))) /*@}*/ /* * Constants & macros for individual CRC_DATALU bitfields */ /*! * @name Register CRC_DATALU, field DATALU[7:0] (RW) */ /*@{*/ #define BP_CRC_DATALU_DATALU (0U) /*!< Bit position for CRC_DATALU_DATALU. */ #define BM_CRC_DATALU_DATALU (0xFFU) /*!< Bit mask for CRC_DATALU_DATALU. */ #define BS_CRC_DATALU_DATALU (8U) /*!< Bit field size in bits for CRC_DATALU_DATALU. */ /*! @brief Read current value of the CRC_DATALU_DATALU field. */ #define BR_CRC_DATALU_DATALU(x) (HW_CRC_DATALU(x).U) /*! @brief Format value for bitfield CRC_DATALU_DATALU. */ #define BF_CRC_DATALU_DATALU(v) ((uint8_t)((uint8_t)(v) << BP_CRC_DATALU_DATALU) & BM_CRC_DATALU_DATALU) /*! @brief Set the DATALU field to a new value. */ #define BW_CRC_DATALU_DATALU(x, v) (HW_CRC_DATALU_WR(x, v)) /*@}*/ /******************************************************************************* * HW_CRC_DATAHL - CRC_DATAHL register. ******************************************************************************/ /*! * @brief HW_CRC_DATAHL - CRC_DATAHL register. (RW) * * Reset value: 0xFFU */ typedef union _hw_crc_datahl { uint8_t U; struct _hw_crc_datahl_bitfields { uint8_t DATAHL : 8; /*!< [7:0] DATAHL stores the third 8 bits of the * 32 bit CRC */ } B; } hw_crc_datahl_t; /*! * @name Constants and macros for entire CRC_DATAHL register */ /*@{*/ #define HW_CRC_DATAHL_ADDR(x) ((x) + 0x2U) #define HW_CRC_DATAHL(x) (*(__IO hw_crc_datahl_t *) HW_CRC_DATAHL_ADDR(x)) #define HW_CRC_DATAHL_RD(x) (HW_CRC_DATAHL(x).U) #define HW_CRC_DATAHL_WR(x, v) (HW_CRC_DATAHL(x).U = (v)) #define HW_CRC_DATAHL_SET(x, v) (HW_CRC_DATAHL_WR(x, HW_CRC_DATAHL_RD(x) | (v))) #define HW_CRC_DATAHL_CLR(x, v) (HW_CRC_DATAHL_WR(x, HW_CRC_DATAHL_RD(x) & ~(v))) #define HW_CRC_DATAHL_TOG(x, v) (HW_CRC_DATAHL_WR(x, HW_CRC_DATAHL_RD(x) ^ (v))) /*@}*/ /* * Constants & macros for individual CRC_DATAHL bitfields */ /*! * @name Register CRC_DATAHL, field DATAHL[7:0] (RW) */ /*@{*/ #define BP_CRC_DATAHL_DATAHL (0U) /*!< Bit position for CRC_DATAHL_DATAHL. */ #define BM_CRC_DATAHL_DATAHL (0xFFU) /*!< Bit mask for CRC_DATAHL_DATAHL. */ #define BS_CRC_DATAHL_DATAHL (8U) /*!< Bit field size in bits for CRC_DATAHL_DATAHL. */ /*! @brief Read current value of the CRC_DATAHL_DATAHL field. */ #define BR_CRC_DATAHL_DATAHL(x) (HW_CRC_DATAHL(x).U) /*! @brief Format value for bitfield CRC_DATAHL_DATAHL. */ #define BF_CRC_DATAHL_DATAHL(v) ((uint8_t)((uint8_t)(v) << BP_CRC_DATAHL_DATAHL) & BM_CRC_DATAHL_DATAHL) /*! @brief Set the DATAHL field to a new value. */ #define BW_CRC_DATAHL_DATAHL(x, v) (HW_CRC_DATAHL_WR(x, v)) /*@}*/ /******************************************************************************* * HW_CRC_DATAHU - CRC_DATAHU register. ******************************************************************************/ /*! * @brief HW_CRC_DATAHU - CRC_DATAHU register. (RW) * * Reset value: 0xFFU */ typedef union _hw_crc_datahu { uint8_t U; struct _hw_crc_datahu_bitfields { uint8_t DATAHU : 8; /*!< [7:0] DATAHU stores the fourth 8 bits of the * 32 bit CRC */ } B; } hw_crc_datahu_t; /*! * @name Constants and macros for entire CRC_DATAHU register */ /*@{*/ #define HW_CRC_DATAHU_ADDR(x) ((x) + 0x3U) #define HW_CRC_DATAHU(x) (*(__IO hw_crc_datahu_t *) HW_CRC_DATAHU_ADDR(x)) #define HW_CRC_DATAHU_RD(x) (HW_CRC_DATAHU(x).U) #define HW_CRC_DATAHU_WR(x, v) (HW_CRC_DATAHU(x).U = (v)) #define HW_CRC_DATAHU_SET(x, v) (HW_CRC_DATAHU_WR(x, HW_CRC_DATAHU_RD(x) | (v))) #define HW_CRC_DATAHU_CLR(x, v) (HW_CRC_DATAHU_WR(x, HW_CRC_DATAHU_RD(x) & ~(v))) #define HW_CRC_DATAHU_TOG(x, v) (HW_CRC_DATAHU_WR(x, HW_CRC_DATAHU_RD(x) ^ (v))) /*@}*/ /* * Constants & macros for individual CRC_DATAHU bitfields */ /*! * @name Register CRC_DATAHU, field DATAHU[7:0] (RW) */ /*@{*/ #define BP_CRC_DATAHU_DATAHU (0U) /*!< Bit position for CRC_DATAHU_DATAHU. */ #define BM_CRC_DATAHU_DATAHU (0xFFU) /*!< Bit mask for CRC_DATAHU_DATAHU. */ #define BS_CRC_DATAHU_DATAHU (8U) /*!< Bit field size in bits for CRC_DATAHU_DATAHU. */ /*! @brief Read current value of the CRC_DATAHU_DATAHU field. */ #define BR_CRC_DATAHU_DATAHU(x) (HW_CRC_DATAHU(x).U) /*! @brief Format value for bitfield CRC_DATAHU_DATAHU. */ #define BF_CRC_DATAHU_DATAHU(v) ((uint8_t)((uint8_t)(v) << BP_CRC_DATAHU_DATAHU) & BM_CRC_DATAHU_DATAHU) /*! @brief Set the DATAHU field to a new value. */ #define BW_CRC_DATAHU_DATAHU(x, v) (HW_CRC_DATAHU_WR(x, v)) /*@}*/ /******************************************************************************* * HW_CRC_DATA - CRC Data register ******************************************************************************/ /*! * @brief HW_CRC_DATA - CRC Data register (RW) * * Reset value: 0xFFFFFFFFU * * The CRC Data register contains the value of the seed, data, and checksum. * When CTRL[WAS] is set, any write to the data register is regarded as the seed * value. When CTRL[WAS] is cleared, any write to the data register is regarded as * data for general CRC computation. In 16-bit CRC mode, the HU and HL fields are * not used for programming the seed value, and reads of these fields return an * indeterminate value. In 32-bit CRC mode, all fields are used for programming * the seed value. When programming data values, the values can be written 8 bits, * 16 bits, or 32 bits at a time, provided all bytes are contiguous; with MSB of * data value written first. After all data values are written, the CRC result * can be read from this data register. In 16-bit CRC mode, the CRC result is * available in the LU and LL fields. In 32-bit CRC mode, all fields contain the * result. Reads of this register at any time return the intermediate CRC value, * provided the CRC module is configured. */ typedef union _hw_crc_data { uint32_t U; struct _hw_crc_data_bitfields { uint32_t LL : 8; /*!< [7:0] CRC Low Lower Byte */ uint32_t LU : 8; /*!< [15:8] CRC Low Upper Byte */ uint32_t HL : 8; /*!< [23:16] CRC High Lower Byte */ uint32_t HU : 8; /*!< [31:24] CRC High Upper Byte */ } B; } hw_crc_data_t; /*! * @name Constants and macros for entire CRC_DATA register */ /*@{*/ #define HW_CRC_DATA_ADDR(x) ((x) + 0x0U) #define HW_CRC_DATA(x) (*(__IO hw_crc_data_t *) HW_CRC_DATA_ADDR(x)) #define HW_CRC_DATA_RD(x) (HW_CRC_DATA(x).U) #define HW_CRC_DATA_WR(x, v) (HW_CRC_DATA(x).U = (v)) #define HW_CRC_DATA_SET(x, v) (HW_CRC_DATA_WR(x, HW_CRC_DATA_RD(x) | (v))) #define HW_CRC_DATA_CLR(x, v) (HW_CRC_DATA_WR(x, HW_CRC_DATA_RD(x) & ~(v))) #define HW_CRC_DATA_TOG(x, v) (HW_CRC_DATA_WR(x, HW_CRC_DATA_RD(x) ^ (v))) /*@}*/ /* * Constants & macros for individual CRC_DATA bitfields */ /*! * @name Register CRC_DATA, field LL[7:0] (RW) * * When CTRL[WAS] is 1, values written to this field are part of the seed value. * When CTRL[WAS] is 0, data written to this field is used for CRC checksum * generation. */ /*@{*/ #define BP_CRC_DATA_LL (0U) /*!< Bit position for CRC_DATA_LL. */ #define BM_CRC_DATA_LL (0x000000FFU) /*!< Bit mask for CRC_DATA_LL. */ #define BS_CRC_DATA_LL (8U) /*!< Bit field size in bits for CRC_DATA_LL. */ /*! @brief Read current value of the CRC_DATA_LL field. */ #define BR_CRC_DATA_LL(x) (HW_CRC_DATA(x).B.LL) /*! @brief Format value for bitfield CRC_DATA_LL. */ #define BF_CRC_DATA_LL(v) ((uint32_t)((uint32_t)(v) << BP_CRC_DATA_LL) & BM_CRC_DATA_LL) /*! @brief Set the LL field to a new value. */ #define BW_CRC_DATA_LL(x, v) (HW_CRC_DATA_WR(x, (HW_CRC_DATA_RD(x) & ~BM_CRC_DATA_LL) | BF_CRC_DATA_LL(v))) /*@}*/ /*! * @name Register CRC_DATA, field LU[15:8] (RW) * * When CTRL[WAS] is 1, values written to this field are part of the seed value. * When CTRL[WAS] is 0, data written to this field is used for CRC checksum * generation. */ /*@{*/ #define BP_CRC_DATA_LU (8U) /*!< Bit position for CRC_DATA_LU. */ #define BM_CRC_DATA_LU (0x0000FF00U) /*!< Bit mask for CRC_DATA_LU. */ #define BS_CRC_DATA_LU (8U) /*!< Bit field size in bits for CRC_DATA_LU. */ /*! @brief Read current value of the CRC_DATA_LU field. */ #define BR_CRC_DATA_LU(x) (HW_CRC_DATA(x).B.LU) /*! @brief Format value for bitfield CRC_DATA_LU. */ #define BF_CRC_DATA_LU(v) ((uint32_t)((uint32_t)(v) << BP_CRC_DATA_LU) & BM_CRC_DATA_LU) /*! @brief Set the LU field to a new value. */ #define BW_CRC_DATA_LU(x, v) (HW_CRC_DATA_WR(x, (HW_CRC_DATA_RD(x) & ~BM_CRC_DATA_LU) | BF_CRC_DATA_LU(v))) /*@}*/ /*! * @name Register CRC_DATA, field HL[23:16] (RW) * * In 16-bit CRC mode (CTRL[TCRC] is 0), this field is not used for programming * a seed value. In 32-bit CRC mode (CTRL[TCRC] is 1), values written to this * field are part of the seed value when CTRL[WAS] is 1. When CTRL[WAS] is 0, data * written to this field is used for CRC checksum generation in both 16-bit and * 32-bit CRC modes. */ /*@{*/ #define BP_CRC_DATA_HL (16U) /*!< Bit position for CRC_DATA_HL. */ #define BM_CRC_DATA_HL (0x00FF0000U) /*!< Bit mask for CRC_DATA_HL. */ #define BS_CRC_DATA_HL (8U) /*!< Bit field size in bits for CRC_DATA_HL. */ /*! @brief Read current value of the CRC_DATA_HL field. */ #define BR_CRC_DATA_HL(x) (HW_CRC_DATA(x).B.HL) /*! @brief Format value for bitfield CRC_DATA_HL. */ #define BF_CRC_DATA_HL(v) ((uint32_t)((uint32_t)(v) << BP_CRC_DATA_HL) & BM_CRC_DATA_HL) /*! @brief Set the HL field to a new value. */ #define BW_CRC_DATA_HL(x, v) (HW_CRC_DATA_WR(x, (HW_CRC_DATA_RD(x) & ~BM_CRC_DATA_HL) | BF_CRC_DATA_HL(v))) /*@}*/ /*! * @name Register CRC_DATA, field HU[31:24] (RW) * * In 16-bit CRC mode (CTRL[TCRC] is 0), this field is not used for programming * a seed value. In 32-bit CRC mode (CTRL[TCRC] is 1), values written to this * field are part of the seed value when CTRL[WAS] is 1. When CTRL[WAS] is 0, data * written to this field is used for CRC checksum generation in both 16-bit and * 32-bit CRC modes. */ /*@{*/ #define BP_CRC_DATA_HU (24U) /*!< Bit position for CRC_DATA_HU. */ #define BM_CRC_DATA_HU (0xFF000000U) /*!< Bit mask for CRC_DATA_HU. */ #define BS_CRC_DATA_HU (8U) /*!< Bit field size in bits for CRC_DATA_HU. */ /*! @brief Read current value of the CRC_DATA_HU field. */ #define BR_CRC_DATA_HU(x) (HW_CRC_DATA(x).B.HU) /*! @brief Format value for bitfield CRC_DATA_HU. */ #define BF_CRC_DATA_HU(v) ((uint32_t)((uint32_t)(v) << BP_CRC_DATA_HU) & BM_CRC_DATA_HU) /*! @brief Set the HU field to a new value. */ #define BW_CRC_DATA_HU(x, v) (HW_CRC_DATA_WR(x, (HW_CRC_DATA_RD(x) & ~BM_CRC_DATA_HU) | BF_CRC_DATA_HU(v))) /*@}*/ /******************************************************************************* * HW_CRC_GPOLY - CRC Polynomial register ******************************************************************************/ /*! * @brief HW_CRC_GPOLY - CRC Polynomial register (RW) * * Reset value: 0x00001021U * * This register contains the value of the polynomial for the CRC calculation. * The HIGH field contains the upper 16 bits of the CRC polynomial, which are used * only in 32-bit CRC mode. Writes to the HIGH field are ignored in 16-bit CRC * mode. The LOW field contains the lower 16 bits of the CRC polynomial, which are * used in both 16- and 32-bit CRC modes. */ typedef union _hw_crc_gpoly { uint32_t U; struct _hw_crc_gpoly_bitfields { uint32_t LOW : 16; /*!< [15:0] Low Polynominal Half-word */ uint32_t HIGH : 16; /*!< [31:16] High Polynominal Half-word */ } B; } hw_crc_gpoly_t; /*! * @name Constants and macros for entire CRC_GPOLY register */ /*@{*/ #define HW_CRC_GPOLY_ADDR(x) ((x) + 0x4U) #define HW_CRC_GPOLY(x) (*(__IO hw_crc_gpoly_t *) HW_CRC_GPOLY_ADDR(x)) #define HW_CRC_GPOLY_RD(x) (HW_CRC_GPOLY(x).U) #define HW_CRC_GPOLY_WR(x, v) (HW_CRC_GPOLY(x).U = (v)) #define HW_CRC_GPOLY_SET(x, v) (HW_CRC_GPOLY_WR(x, HW_CRC_GPOLY_RD(x) | (v))) #define HW_CRC_GPOLY_CLR(x, v) (HW_CRC_GPOLY_WR(x, HW_CRC_GPOLY_RD(x) & ~(v))) #define HW_CRC_GPOLY_TOG(x, v) (HW_CRC_GPOLY_WR(x, HW_CRC_GPOLY_RD(x) ^ (v))) /*@}*/ /* * Constants & macros for individual CRC_GPOLY bitfields */ /*! * @name Register CRC_GPOLY, field LOW[15:0] (RW) * * Writable and readable in both 32-bit and 16-bit CRC modes. */ /*@{*/ #define BP_CRC_GPOLY_LOW (0U) /*!< Bit position for CRC_GPOLY_LOW. */ #define BM_CRC_GPOLY_LOW (0x0000FFFFU) /*!< Bit mask for CRC_GPOLY_LOW. */ #define BS_CRC_GPOLY_LOW (16U) /*!< Bit field size in bits for CRC_GPOLY_LOW. */ /*! @brief Read current value of the CRC_GPOLY_LOW field. */ #define BR_CRC_GPOLY_LOW(x) (HW_CRC_GPOLY(x).B.LOW) /*! @brief Format value for bitfield CRC_GPOLY_LOW. */ #define BF_CRC_GPOLY_LOW(v) ((uint32_t)((uint32_t)(v) << BP_CRC_GPOLY_LOW) & BM_CRC_GPOLY_LOW) /*! @brief Set the LOW field to a new value. */ #define BW_CRC_GPOLY_LOW(x, v) (HW_CRC_GPOLY_WR(x, (HW_CRC_GPOLY_RD(x) & ~BM_CRC_GPOLY_LOW) | BF_CRC_GPOLY_LOW(v))) /*@}*/ /*! * @name Register CRC_GPOLY, field HIGH[31:16] (RW) * * Writable and readable in 32-bit CRC mode (CTRL[TCRC] is 1). This field is not * writable in 16-bit CRC mode (CTRL[TCRC] is 0). */ /*@{*/ #define BP_CRC_GPOLY_HIGH (16U) /*!< Bit position for CRC_GPOLY_HIGH. */ #define BM_CRC_GPOLY_HIGH (0xFFFF0000U) /*!< Bit mask for CRC_GPOLY_HIGH. */ #define BS_CRC_GPOLY_HIGH (16U) /*!< Bit field size in bits for CRC_GPOLY_HIGH. */ /*! @brief Read current value of the CRC_GPOLY_HIGH field. */ #define BR_CRC_GPOLY_HIGH(x) (HW_CRC_GPOLY(x).B.HIGH) /*! @brief Format value for bitfield CRC_GPOLY_HIGH. */ #define BF_CRC_GPOLY_HIGH(v) ((uint32_t)((uint32_t)(v) << BP_CRC_GPOLY_HIGH) & BM_CRC_GPOLY_HIGH) /*! @brief Set the HIGH field to a new value. */ #define BW_CRC_GPOLY_HIGH(x, v) (HW_CRC_GPOLY_WR(x, (HW_CRC_GPOLY_RD(x) & ~BM_CRC_GPOLY_HIGH) | BF_CRC_GPOLY_HIGH(v))) /*@}*/ /******************************************************************************* * HW_CRC_GPOLYL - CRC_GPOLYL register. ******************************************************************************/ /*! * @brief HW_CRC_GPOLYL - CRC_GPOLYL register. (RW) * * Reset value: 0xFFFFU */ typedef union _hw_crc_gpolyl { uint16_t U; struct _hw_crc_gpolyl_bitfields { uint16_t GPOLYL : 16; /*!< [15:0] POLYL stores the lower 16 bits of * the 16/32 bit CRC polynomial value */ } B; } hw_crc_gpolyl_t; /*! * @name Constants and macros for entire CRC_GPOLYL register */ /*@{*/ #define HW_CRC_GPOLYL_ADDR(x) ((x) + 0x4U) #define HW_CRC_GPOLYL(x) (*(__IO hw_crc_gpolyl_t *) HW_CRC_GPOLYL_ADDR(x)) #define HW_CRC_GPOLYL_RD(x) (HW_CRC_GPOLYL(x).U) #define HW_CRC_GPOLYL_WR(x, v) (HW_CRC_GPOLYL(x).U = (v)) #define HW_CRC_GPOLYL_SET(x, v) (HW_CRC_GPOLYL_WR(x, HW_CRC_GPOLYL_RD(x) | (v))) #define HW_CRC_GPOLYL_CLR(x, v) (HW_CRC_GPOLYL_WR(x, HW_CRC_GPOLYL_RD(x) & ~(v))) #define HW_CRC_GPOLYL_TOG(x, v) (HW_CRC_GPOLYL_WR(x, HW_CRC_GPOLYL_RD(x) ^ (v))) /*@}*/ /* * Constants & macros for individual CRC_GPOLYL bitfields */ /*! * @name Register CRC_GPOLYL, field GPOLYL[15:0] (RW) */ /*@{*/ #define BP_CRC_GPOLYL_GPOLYL (0U) /*!< Bit position for CRC_GPOLYL_GPOLYL. */ #define BM_CRC_GPOLYL_GPOLYL (0xFFFFU) /*!< Bit mask for CRC_GPOLYL_GPOLYL. */ #define BS_CRC_GPOLYL_GPOLYL (16U) /*!< Bit field size in bits for CRC_GPOLYL_GPOLYL. */ /*! @brief Read current value of the CRC_GPOLYL_GPOLYL field. */ #define BR_CRC_GPOLYL_GPOLYL(x) (HW_CRC_GPOLYL(x).U) /*! @brief Format value for bitfield CRC_GPOLYL_GPOLYL. */ #define BF_CRC_GPOLYL_GPOLYL(v) ((uint16_t)((uint16_t)(v) << BP_CRC_GPOLYL_GPOLYL) & BM_CRC_GPOLYL_GPOLYL) /*! @brief Set the GPOLYL field to a new value. */ #define BW_CRC_GPOLYL_GPOLYL(x, v) (HW_CRC_GPOLYL_WR(x, v)) /*@}*/ /******************************************************************************* * HW_CRC_GPOLYH - CRC_GPOLYH register. ******************************************************************************/ /*! * @brief HW_CRC_GPOLYH - CRC_GPOLYH register. (RW) * * Reset value: 0xFFFFU */ typedef union _hw_crc_gpolyh { uint16_t U; struct _hw_crc_gpolyh_bitfields { uint16_t GPOLYH : 16; /*!< [15:0] POLYH stores the high 16 bits of * the 16/32 bit CRC polynomial value */ } B; } hw_crc_gpolyh_t; /*! * @name Constants and macros for entire CRC_GPOLYH register */ /*@{*/ #define HW_CRC_GPOLYH_ADDR(x) ((x) + 0x6U) #define HW_CRC_GPOLYH(x) (*(__IO hw_crc_gpolyh_t *) HW_CRC_GPOLYH_ADDR(x)) #define HW_CRC_GPOLYH_RD(x) (HW_CRC_GPOLYH(x).U) #define HW_CRC_GPOLYH_WR(x, v) (HW_CRC_GPOLYH(x).U = (v)) #define HW_CRC_GPOLYH_SET(x, v) (HW_CRC_GPOLYH_WR(x, HW_CRC_GPOLYH_RD(x) | (v))) #define HW_CRC_GPOLYH_CLR(x, v) (HW_CRC_GPOLYH_WR(x, HW_CRC_GPOLYH_RD(x) & ~(v))) #define HW_CRC_GPOLYH_TOG(x, v) (HW_CRC_GPOLYH_WR(x, HW_CRC_GPOLYH_RD(x) ^ (v))) /*@}*/ /* * Constants & macros for individual CRC_GPOLYH bitfields */ /*! * @name Register CRC_GPOLYH, field GPOLYH[15:0] (RW) */ /*@{*/ #define BP_CRC_GPOLYH_GPOLYH (0U) /*!< Bit position for CRC_GPOLYH_GPOLYH. */ #define BM_CRC_GPOLYH_GPOLYH (0xFFFFU) /*!< Bit mask for CRC_GPOLYH_GPOLYH. */ #define BS_CRC_GPOLYH_GPOLYH (16U) /*!< Bit field size in bits for CRC_GPOLYH_GPOLYH. */ /*! @brief Read current value of the CRC_GPOLYH_GPOLYH field. */ #define BR_CRC_GPOLYH_GPOLYH(x) (HW_CRC_GPOLYH(x).U) /*! @brief Format value for bitfield CRC_GPOLYH_GPOLYH. */ #define BF_CRC_GPOLYH_GPOLYH(v) ((uint16_t)((uint16_t)(v) << BP_CRC_GPOLYH_GPOLYH) & BM_CRC_GPOLYH_GPOLYH) /*! @brief Set the GPOLYH field to a new value. */ #define BW_CRC_GPOLYH_GPOLYH(x, v) (HW_CRC_GPOLYH_WR(x, v)) /*@}*/ /******************************************************************************* * HW_CRC_GPOLYLL - CRC_GPOLYLL register. ******************************************************************************/ /*! * @brief HW_CRC_GPOLYLL - CRC_GPOLYLL register. (RW) * * Reset value: 0xFFU */ typedef union _hw_crc_gpolyll { uint8_t U; struct _hw_crc_gpolyll_bitfields { uint8_t GPOLYLL : 8; /*!< [7:0] POLYLL stores the first 8 bits of the * 32 bit CRC */ } B; } hw_crc_gpolyll_t; /*! * @name Constants and macros for entire CRC_GPOLYLL register */ /*@{*/ #define HW_CRC_GPOLYLL_ADDR(x) ((x) + 0x4U) #define HW_CRC_GPOLYLL(x) (*(__IO hw_crc_gpolyll_t *) HW_CRC_GPOLYLL_ADDR(x)) #define HW_CRC_GPOLYLL_RD(x) (HW_CRC_GPOLYLL(x).U) #define HW_CRC_GPOLYLL_WR(x, v) (HW_CRC_GPOLYLL(x).U = (v)) #define HW_CRC_GPOLYLL_SET(x, v) (HW_CRC_GPOLYLL_WR(x, HW_CRC_GPOLYLL_RD(x) | (v))) #define HW_CRC_GPOLYLL_CLR(x, v) (HW_CRC_GPOLYLL_WR(x, HW_CRC_GPOLYLL_RD(x) & ~(v))) #define HW_CRC_GPOLYLL_TOG(x, v) (HW_CRC_GPOLYLL_WR(x, HW_CRC_GPOLYLL_RD(x) ^ (v))) /*@}*/ /* * Constants & macros for individual CRC_GPOLYLL bitfields */ /*! * @name Register CRC_GPOLYLL, field GPOLYLL[7:0] (RW) */ /*@{*/ #define BP_CRC_GPOLYLL_GPOLYLL (0U) /*!< Bit position for CRC_GPOLYLL_GPOLYLL. */ #define BM_CRC_GPOLYLL_GPOLYLL (0xFFU) /*!< Bit mask for CRC_GPOLYLL_GPOLYLL. */ #define BS_CRC_GPOLYLL_GPOLYLL (8U) /*!< Bit field size in bits for CRC_GPOLYLL_GPOLYLL. */ /*! @brief Read current value of the CRC_GPOLYLL_GPOLYLL field. */ #define BR_CRC_GPOLYLL_GPOLYLL(x) (HW_CRC_GPOLYLL(x).U) /*! @brief Format value for bitfield CRC_GPOLYLL_GPOLYLL. */ #define BF_CRC_GPOLYLL_GPOLYLL(v) ((uint8_t)((uint8_t)(v) << BP_CRC_GPOLYLL_GPOLYLL) & BM_CRC_GPOLYLL_GPOLYLL) /*! @brief Set the GPOLYLL field to a new value. */ #define BW_CRC_GPOLYLL_GPOLYLL(x, v) (HW_CRC_GPOLYLL_WR(x, v)) /*@}*/ /******************************************************************************* * HW_CRC_GPOLYLU - CRC_GPOLYLU register. ******************************************************************************/ /*! * @brief HW_CRC_GPOLYLU - CRC_GPOLYLU register. (RW) * * Reset value: 0xFFU */ typedef union _hw_crc_gpolylu { uint8_t U; struct _hw_crc_gpolylu_bitfields { uint8_t GPOLYLU : 8; /*!< [7:0] POLYLL stores the second 8 bits of * the 32 bit CRC */ } B; } hw_crc_gpolylu_t; /*! * @name Constants and macros for entire CRC_GPOLYLU register */ /*@{*/ #define HW_CRC_GPOLYLU_ADDR(x) ((x) + 0x5U) #define HW_CRC_GPOLYLU(x) (*(__IO hw_crc_gpolylu_t *) HW_CRC_GPOLYLU_ADDR(x)) #define HW_CRC_GPOLYLU_RD(x) (HW_CRC_GPOLYLU(x).U) #define HW_CRC_GPOLYLU_WR(x, v) (HW_CRC_GPOLYLU(x).U = (v)) #define HW_CRC_GPOLYLU_SET(x, v) (HW_CRC_GPOLYLU_WR(x, HW_CRC_GPOLYLU_RD(x) | (v))) #define HW_CRC_GPOLYLU_CLR(x, v) (HW_CRC_GPOLYLU_WR(x, HW_CRC_GPOLYLU_RD(x) & ~(v))) #define HW_CRC_GPOLYLU_TOG(x, v) (HW_CRC_GPOLYLU_WR(x, HW_CRC_GPOLYLU_RD(x) ^ (v))) /*@}*/ /* * Constants & macros for individual CRC_GPOLYLU bitfields */ /*! * @name Register CRC_GPOLYLU, field GPOLYLU[7:0] (RW) */ /*@{*/ #define BP_CRC_GPOLYLU_GPOLYLU (0U) /*!< Bit position for CRC_GPOLYLU_GPOLYLU. */ #define BM_CRC_GPOLYLU_GPOLYLU (0xFFU) /*!< Bit mask for CRC_GPOLYLU_GPOLYLU. */ #define BS_CRC_GPOLYLU_GPOLYLU (8U) /*!< Bit field size in bits for CRC_GPOLYLU_GPOLYLU. */ /*! @brief Read current value of the CRC_GPOLYLU_GPOLYLU field. */ #define BR_CRC_GPOLYLU_GPOLYLU(x) (HW_CRC_GPOLYLU(x).U) /*! @brief Format value for bitfield CRC_GPOLYLU_GPOLYLU. */ #define BF_CRC_GPOLYLU_GPOLYLU(v) ((uint8_t)((uint8_t)(v) << BP_CRC_GPOLYLU_GPOLYLU) & BM_CRC_GPOLYLU_GPOLYLU) /*! @brief Set the GPOLYLU field to a new value. */ #define BW_CRC_GPOLYLU_GPOLYLU(x, v) (HW_CRC_GPOLYLU_WR(x, v)) /*@}*/ /******************************************************************************* * HW_CRC_GPOLYHL - CRC_GPOLYHL register. ******************************************************************************/ /*! * @brief HW_CRC_GPOLYHL - CRC_GPOLYHL register. (RW) * * Reset value: 0xFFU */ typedef union _hw_crc_gpolyhl { uint8_t U; struct _hw_crc_gpolyhl_bitfields { uint8_t GPOLYHL : 8; /*!< [7:0] POLYHL stores the third 8 bits of the * 32 bit CRC */ } B; } hw_crc_gpolyhl_t; /*! * @name Constants and macros for entire CRC_GPOLYHL register */ /*@{*/ #define HW_CRC_GPOLYHL_ADDR(x) ((x) + 0x6U) #define HW_CRC_GPOLYHL(x) (*(__IO hw_crc_gpolyhl_t *) HW_CRC_GPOLYHL_ADDR(x)) #define HW_CRC_GPOLYHL_RD(x) (HW_CRC_GPOLYHL(x).U) #define HW_CRC_GPOLYHL_WR(x, v) (HW_CRC_GPOLYHL(x).U = (v)) #define HW_CRC_GPOLYHL_SET(x, v) (HW_CRC_GPOLYHL_WR(x, HW_CRC_GPOLYHL_RD(x) | (v))) #define HW_CRC_GPOLYHL_CLR(x, v) (HW_CRC_GPOLYHL_WR(x, HW_CRC_GPOLYHL_RD(x) & ~(v))) #define HW_CRC_GPOLYHL_TOG(x, v) (HW_CRC_GPOLYHL_WR(x, HW_CRC_GPOLYHL_RD(x) ^ (v))) /*@}*/ /* * Constants & macros for individual CRC_GPOLYHL bitfields */ /*! * @name Register CRC_GPOLYHL, field GPOLYHL[7:0] (RW) */ /*@{*/ #define BP_CRC_GPOLYHL_GPOLYHL (0U) /*!< Bit position for CRC_GPOLYHL_GPOLYHL. */ #define BM_CRC_GPOLYHL_GPOLYHL (0xFFU) /*!< Bit mask for CRC_GPOLYHL_GPOLYHL. */ #define BS_CRC_GPOLYHL_GPOLYHL (8U) /*!< Bit field size in bits for CRC_GPOLYHL_GPOLYHL. */ /*! @brief Read current value of the CRC_GPOLYHL_GPOLYHL field. */ #define BR_CRC_GPOLYHL_GPOLYHL(x) (HW_CRC_GPOLYHL(x).U) /*! @brief Format value for bitfield CRC_GPOLYHL_GPOLYHL. */ #define BF_CRC_GPOLYHL_GPOLYHL(v) ((uint8_t)((uint8_t)(v) << BP_CRC_GPOLYHL_GPOLYHL) & BM_CRC_GPOLYHL_GPOLYHL) /*! @brief Set the GPOLYHL field to a new value. */ #define BW_CRC_GPOLYHL_GPOLYHL(x, v) (HW_CRC_GPOLYHL_WR(x, v)) /*@}*/ /******************************************************************************* * HW_CRC_GPOLYHU - CRC_GPOLYHU register. ******************************************************************************/ /*! * @brief HW_CRC_GPOLYHU - CRC_GPOLYHU register. (RW) * * Reset value: 0xFFU */ typedef union _hw_crc_gpolyhu { uint8_t U; struct _hw_crc_gpolyhu_bitfields { uint8_t GPOLYHU : 8; /*!< [7:0] POLYHU stores the fourth 8 bits of * the 32 bit CRC */ } B; } hw_crc_gpolyhu_t; /*! * @name Constants and macros for entire CRC_GPOLYHU register */ /*@{*/ #define HW_CRC_GPOLYHU_ADDR(x) ((x) + 0x7U) #define HW_CRC_GPOLYHU(x) (*(__IO hw_crc_gpolyhu_t *) HW_CRC_GPOLYHU_ADDR(x)) #define HW_CRC_GPOLYHU_RD(x) (HW_CRC_GPOLYHU(x).U) #define HW_CRC_GPOLYHU_WR(x, v) (HW_CRC_GPOLYHU(x).U = (v)) #define HW_CRC_GPOLYHU_SET(x, v) (HW_CRC_GPOLYHU_WR(x, HW_CRC_GPOLYHU_RD(x) | (v))) #define HW_CRC_GPOLYHU_CLR(x, v) (HW_CRC_GPOLYHU_WR(x, HW_CRC_GPOLYHU_RD(x) & ~(v))) #define HW_CRC_GPOLYHU_TOG(x, v) (HW_CRC_GPOLYHU_WR(x, HW_CRC_GPOLYHU_RD(x) ^ (v))) /*@}*/ /* * Constants & macros for individual CRC_GPOLYHU bitfields */ /*! * @name Register CRC_GPOLYHU, field GPOLYHU[7:0] (RW) */ /*@{*/ #define BP_CRC_GPOLYHU_GPOLYHU (0U) /*!< Bit position for CRC_GPOLYHU_GPOLYHU. */ #define BM_CRC_GPOLYHU_GPOLYHU (0xFFU) /*!< Bit mask for CRC_GPOLYHU_GPOLYHU. */ #define BS_CRC_GPOLYHU_GPOLYHU (8U) /*!< Bit field size in bits for CRC_GPOLYHU_GPOLYHU. */ /*! @brief Read current value of the CRC_GPOLYHU_GPOLYHU field. */ #define BR_CRC_GPOLYHU_GPOLYHU(x) (HW_CRC_GPOLYHU(x).U) /*! @brief Format value for bitfield CRC_GPOLYHU_GPOLYHU. */ #define BF_CRC_GPOLYHU_GPOLYHU(v) ((uint8_t)((uint8_t)(v) << BP_CRC_GPOLYHU_GPOLYHU) & BM_CRC_GPOLYHU_GPOLYHU) /*! @brief Set the GPOLYHU field to a new value. */ #define BW_CRC_GPOLYHU_GPOLYHU(x, v) (HW_CRC_GPOLYHU_WR(x, v)) /*@}*/ /******************************************************************************* * HW_CRC_CTRL - CRC Control register ******************************************************************************/ /*! * @brief HW_CRC_CTRL - CRC Control register (RW) * * Reset value: 0x00000000U * * This register controls the configuration and working of the CRC module. * Appropriate bits must be set before starting a new CRC calculation. A new CRC * calculation is initialized by asserting CTRL[WAS] and then writing the seed into * the CRC data register. */ typedef union _hw_crc_ctrl { uint32_t U; struct _hw_crc_ctrl_bitfields { uint32_t RESERVED0 : 24; /*!< [23:0] */ uint32_t TCRC : 1; /*!< [24] */ uint32_t WAS : 1; /*!< [25] Write CRC Data Register As Seed */ uint32_t FXOR : 1; /*!< [26] Complement Read Of CRC Data Register */ uint32_t RESERVED1 : 1; /*!< [27] */ uint32_t TOTR : 2; /*!< [29:28] Type Of Transpose For Read */ uint32_t TOT : 2; /*!< [31:30] Type Of Transpose For Writes */ } B; } hw_crc_ctrl_t; /*! * @name Constants and macros for entire CRC_CTRL register */ /*@{*/ #define HW_CRC_CTRL_ADDR(x) ((x) + 0x8U) #define HW_CRC_CTRL(x) (*(__IO hw_crc_ctrl_t *) HW_CRC_CTRL_ADDR(x)) #define HW_CRC_CTRL_RD(x) (HW_CRC_CTRL(x).U) #define HW_CRC_CTRL_WR(x, v) (HW_CRC_CTRL(x).U = (v)) #define HW_CRC_CTRL_SET(x, v) (HW_CRC_CTRL_WR(x, HW_CRC_CTRL_RD(x) | (v))) #define HW_CRC_CTRL_CLR(x, v) (HW_CRC_CTRL_WR(x, HW_CRC_CTRL_RD(x) & ~(v))) #define HW_CRC_CTRL_TOG(x, v) (HW_CRC_CTRL_WR(x, HW_CRC_CTRL_RD(x) ^ (v))) /*@}*/ /* * Constants & macros for individual CRC_CTRL bitfields */ /*! * @name Register CRC_CTRL, field TCRC[24] (RW) * * Width of CRC protocol. * * Values: * - 0 - 16-bit CRC protocol. * - 1 - 32-bit CRC protocol. */ /*@{*/ #define BP_CRC_CTRL_TCRC (24U) /*!< Bit position for CRC_CTRL_TCRC. */ #define BM_CRC_CTRL_TCRC (0x01000000U) /*!< Bit mask for CRC_CTRL_TCRC. */ #define BS_CRC_CTRL_TCRC (1U) /*!< Bit field size in bits for CRC_CTRL_TCRC. */ /*! @brief Read current value of the CRC_CTRL_TCRC field. */ #define BR_CRC_CTRL_TCRC(x) (BITBAND_ACCESS32(HW_CRC_CTRL_ADDR(x), BP_CRC_CTRL_TCRC)) /*! @brief Format value for bitfield CRC_CTRL_TCRC. */ #define BF_CRC_CTRL_TCRC(v) ((uint32_t)((uint32_t)(v) << BP_CRC_CTRL_TCRC) & BM_CRC_CTRL_TCRC) /*! @brief Set the TCRC field to a new value. */ #define BW_CRC_CTRL_TCRC(x, v) (BITBAND_ACCESS32(HW_CRC_CTRL_ADDR(x), BP_CRC_CTRL_TCRC) = (v)) /*@}*/ /*! * @name Register CRC_CTRL, field WAS[25] (RW) * * When asserted, a value written to the CRC data register is considered a seed * value. When deasserted, a value written to the CRC data register is taken as * data for CRC computation. * * Values: * - 0 - Writes to the CRC data register are data values. * - 1 - Writes to the CRC data register are seed values. */ /*@{*/ #define BP_CRC_CTRL_WAS (25U) /*!< Bit position for CRC_CTRL_WAS. */ #define BM_CRC_CTRL_WAS (0x02000000U) /*!< Bit mask for CRC_CTRL_WAS. */ #define BS_CRC_CTRL_WAS (1U) /*!< Bit field size in bits for CRC_CTRL_WAS. */ /*! @brief Read current value of the CRC_CTRL_WAS field. */ #define BR_CRC_CTRL_WAS(x) (BITBAND_ACCESS32(HW_CRC_CTRL_ADDR(x), BP_CRC_CTRL_WAS)) /*! @brief Format value for bitfield CRC_CTRL_WAS. */ #define BF_CRC_CTRL_WAS(v) ((uint32_t)((uint32_t)(v) << BP_CRC_CTRL_WAS) & BM_CRC_CTRL_WAS) /*! @brief Set the WAS field to a new value. */ #define BW_CRC_CTRL_WAS(x, v) (BITBAND_ACCESS32(HW_CRC_CTRL_ADDR(x), BP_CRC_CTRL_WAS) = (v)) /*@}*/ /*! * @name Register CRC_CTRL, field FXOR[26] (RW) * * Some CRC protocols require the final checksum to be XORed with 0xFFFFFFFF or * 0xFFFF. Asserting this bit enables on the fly complementing of read data. * * Values: * - 0 - No XOR on reading. * - 1 - Invert or complement the read value of the CRC Data register. */ /*@{*/ #define BP_CRC_CTRL_FXOR (26U) /*!< Bit position for CRC_CTRL_FXOR. */ #define BM_CRC_CTRL_FXOR (0x04000000U) /*!< Bit mask for CRC_CTRL_FXOR. */ #define BS_CRC_CTRL_FXOR (1U) /*!< Bit field size in bits for CRC_CTRL_FXOR. */ /*! @brief Read current value of the CRC_CTRL_FXOR field. */ #define BR_CRC_CTRL_FXOR(x) (BITBAND_ACCESS32(HW_CRC_CTRL_ADDR(x), BP_CRC_CTRL_FXOR)) /*! @brief Format value for bitfield CRC_CTRL_FXOR. */ #define BF_CRC_CTRL_FXOR(v) ((uint32_t)((uint32_t)(v) << BP_CRC_CTRL_FXOR) & BM_CRC_CTRL_FXOR) /*! @brief Set the FXOR field to a new value. */ #define BW_CRC_CTRL_FXOR(x, v) (BITBAND_ACCESS32(HW_CRC_CTRL_ADDR(x), BP_CRC_CTRL_FXOR) = (v)) /*@}*/ /*! * @name Register CRC_CTRL, field TOTR[29:28] (RW) * * Identifies the transpose configuration of the value read from the CRC Data * register. See the description of the transpose feature for the available * transpose options. * * Values: * - 00 - No transposition. * - 01 - Bits in bytes are transposed; bytes are not transposed. * - 10 - Both bits in bytes and bytes are transposed. * - 11 - Only bytes are transposed; no bits in a byte are transposed. */ /*@{*/ #define BP_CRC_CTRL_TOTR (28U) /*!< Bit position for CRC_CTRL_TOTR. */ #define BM_CRC_CTRL_TOTR (0x30000000U) /*!< Bit mask for CRC_CTRL_TOTR. */ #define BS_CRC_CTRL_TOTR (2U) /*!< Bit field size in bits for CRC_CTRL_TOTR. */ /*! @brief Read current value of the CRC_CTRL_TOTR field. */ #define BR_CRC_CTRL_TOTR(x) (HW_CRC_CTRL(x).B.TOTR) /*! @brief Format value for bitfield CRC_CTRL_TOTR. */ #define BF_CRC_CTRL_TOTR(v) ((uint32_t)((uint32_t)(v) << BP_CRC_CTRL_TOTR) & BM_CRC_CTRL_TOTR) /*! @brief Set the TOTR field to a new value. */ #define BW_CRC_CTRL_TOTR(x, v) (HW_CRC_CTRL_WR(x, (HW_CRC_CTRL_RD(x) & ~BM_CRC_CTRL_TOTR) | BF_CRC_CTRL_TOTR(v))) /*@}*/ /*! * @name Register CRC_CTRL, field TOT[31:30] (RW) * * Defines the transpose configuration of the data written to the CRC data * register. See the description of the transpose feature for the available transpose * options. * * Values: * - 00 - No transposition. * - 01 - Bits in bytes are transposed; bytes are not transposed. * - 10 - Both bits in bytes and bytes are transposed. * - 11 - Only bytes are transposed; no bits in a byte are transposed. */ /*@{*/ #define BP_CRC_CTRL_TOT (30U) /*!< Bit position for CRC_CTRL_TOT. */ #define BM_CRC_CTRL_TOT (0xC0000000U) /*!< Bit mask for CRC_CTRL_TOT. */ #define BS_CRC_CTRL_TOT (2U) /*!< Bit field size in bits for CRC_CTRL_TOT. */ /*! @brief Read current value of the CRC_CTRL_TOT field. */ #define BR_CRC_CTRL_TOT(x) (HW_CRC_CTRL(x).B.TOT) /*! @brief Format value for bitfield CRC_CTRL_TOT. */ #define BF_CRC_CTRL_TOT(v) ((uint32_t)((uint32_t)(v) << BP_CRC_CTRL_TOT) & BM_CRC_CTRL_TOT) /*! @brief Set the TOT field to a new value. */ #define BW_CRC_CTRL_TOT(x, v) (HW_CRC_CTRL_WR(x, (HW_CRC_CTRL_RD(x) & ~BM_CRC_CTRL_TOT) | BF_CRC_CTRL_TOT(v))) /*@}*/ /******************************************************************************* * HW_CRC_CTRLHU - CRC_CTRLHU register. ******************************************************************************/ /*! * @brief HW_CRC_CTRLHU - CRC_CTRLHU register. (RW) * * Reset value: 0x00U */ typedef union _hw_crc_ctrlhu { uint8_t U; struct _hw_crc_ctrlhu_bitfields { uint8_t TCRC : 1; /*!< [0] */ uint8_t WAS : 1; /*!< [1] */ uint8_t FXOR : 1; /*!< [2] */ uint8_t RESERVED0 : 1; /*!< [3] */ uint8_t TOTR : 2; /*!< [5:4] */ uint8_t TOT : 2; /*!< [7:6] */ } B; } hw_crc_ctrlhu_t; /*! * @name Constants and macros for entire CRC_CTRLHU register */ /*@{*/ #define HW_CRC_CTRLHU_ADDR(x) ((x) + 0xBU) #define HW_CRC_CTRLHU(x) (*(__IO hw_crc_ctrlhu_t *) HW_CRC_CTRLHU_ADDR(x)) #define HW_CRC_CTRLHU_RD(x) (HW_CRC_CTRLHU(x).U) #define HW_CRC_CTRLHU_WR(x, v) (HW_CRC_CTRLHU(x).U = (v)) #define HW_CRC_CTRLHU_SET(x, v) (HW_CRC_CTRLHU_WR(x, HW_CRC_CTRLHU_RD(x) | (v))) #define HW_CRC_CTRLHU_CLR(x, v) (HW_CRC_CTRLHU_WR(x, HW_CRC_CTRLHU_RD(x) & ~(v))) #define HW_CRC_CTRLHU_TOG(x, v) (HW_CRC_CTRLHU_WR(x, HW_CRC_CTRLHU_RD(x) ^ (v))) /*@}*/ /* * Constants & macros for individual CRC_CTRLHU bitfields */ /*! * @name Register CRC_CTRLHU, field TCRC[0] (RW) * * Values: * - 0 - 16-bit CRC protocol. * - 1 - 32-bit CRC protocol. */ /*@{*/ #define BP_CRC_CTRLHU_TCRC (0U) /*!< Bit position for CRC_CTRLHU_TCRC. */ #define BM_CRC_CTRLHU_TCRC (0x01U) /*!< Bit mask for CRC_CTRLHU_TCRC. */ #define BS_CRC_CTRLHU_TCRC (1U) /*!< Bit field size in bits for CRC_CTRLHU_TCRC. */ /*! @brief Read current value of the CRC_CTRLHU_TCRC field. */ #define BR_CRC_CTRLHU_TCRC(x) (BITBAND_ACCESS8(HW_CRC_CTRLHU_ADDR(x), BP_CRC_CTRLHU_TCRC)) /*! @brief Format value for bitfield CRC_CTRLHU_TCRC. */ #define BF_CRC_CTRLHU_TCRC(v) ((uint8_t)((uint8_t)(v) << BP_CRC_CTRLHU_TCRC) & BM_CRC_CTRLHU_TCRC) /*! @brief Set the TCRC field to a new value. */ #define BW_CRC_CTRLHU_TCRC(x, v) (BITBAND_ACCESS8(HW_CRC_CTRLHU_ADDR(x), BP_CRC_CTRLHU_TCRC) = (v)) /*@}*/ /*! * @name Register CRC_CTRLHU, field WAS[1] (RW) * * Values: * - 0 - Writes to CRC data register are data values. * - 1 - Writes to CRC data reguster are seed values. */ /*@{*/ #define BP_CRC_CTRLHU_WAS (1U) /*!< Bit position for CRC_CTRLHU_WAS. */ #define BM_CRC_CTRLHU_WAS (0x02U) /*!< Bit mask for CRC_CTRLHU_WAS. */ #define BS_CRC_CTRLHU_WAS (1U) /*!< Bit field size in bits for CRC_CTRLHU_WAS. */ /*! @brief Read current value of the CRC_CTRLHU_WAS field. */ #define BR_CRC_CTRLHU_WAS(x) (BITBAND_ACCESS8(HW_CRC_CTRLHU_ADDR(x), BP_CRC_CTRLHU_WAS)) /*! @brief Format value for bitfield CRC_CTRLHU_WAS. */ #define BF_CRC_CTRLHU_WAS(v) ((uint8_t)((uint8_t)(v) << BP_CRC_CTRLHU_WAS) & BM_CRC_CTRLHU_WAS) /*! @brief Set the WAS field to a new value. */ #define BW_CRC_CTRLHU_WAS(x, v) (BITBAND_ACCESS8(HW_CRC_CTRLHU_ADDR(x), BP_CRC_CTRLHU_WAS) = (v)) /*@}*/ /*! * @name Register CRC_CTRLHU, field FXOR[2] (RW) * * Values: * - 0 - No XOR on reading. * - 1 - Invert or complement the read value of CRC data register. */ /*@{*/ #define BP_CRC_CTRLHU_FXOR (2U) /*!< Bit position for CRC_CTRLHU_FXOR. */ #define BM_CRC_CTRLHU_FXOR (0x04U) /*!< Bit mask for CRC_CTRLHU_FXOR. */ #define BS_CRC_CTRLHU_FXOR (1U) /*!< Bit field size in bits for CRC_CTRLHU_FXOR. */ /*! @brief Read current value of the CRC_CTRLHU_FXOR field. */ #define BR_CRC_CTRLHU_FXOR(x) (BITBAND_ACCESS8(HW_CRC_CTRLHU_ADDR(x), BP_CRC_CTRLHU_FXOR)) /*! @brief Format value for bitfield CRC_CTRLHU_FXOR. */ #define BF_CRC_CTRLHU_FXOR(v) ((uint8_t)((uint8_t)(v) << BP_CRC_CTRLHU_FXOR) & BM_CRC_CTRLHU_FXOR) /*! @brief Set the FXOR field to a new value. */ #define BW_CRC_CTRLHU_FXOR(x, v) (BITBAND_ACCESS8(HW_CRC_CTRLHU_ADDR(x), BP_CRC_CTRLHU_FXOR) = (v)) /*@}*/ /*! * @name Register CRC_CTRLHU, field TOTR[5:4] (RW) * * Values: * - 00 - No Transposition. * - 01 - Bits in bytes are transposed, bytes are not transposed. * - 10 - Both bits in bytes and bytes are transposed. * - 11 - Only bytes are transposed; no bits in a byte are transposed. */ /*@{*/ #define BP_CRC_CTRLHU_TOTR (4U) /*!< Bit position for CRC_CTRLHU_TOTR. */ #define BM_CRC_CTRLHU_TOTR (0x30U) /*!< Bit mask for CRC_CTRLHU_TOTR. */ #define BS_CRC_CTRLHU_TOTR (2U) /*!< Bit field size in bits for CRC_CTRLHU_TOTR. */ /*! @brief Read current value of the CRC_CTRLHU_TOTR field. */ #define BR_CRC_CTRLHU_TOTR(x) (HW_CRC_CTRLHU(x).B.TOTR) /*! @brief Format value for bitfield CRC_CTRLHU_TOTR. */ #define BF_CRC_CTRLHU_TOTR(v) ((uint8_t)((uint8_t)(v) << BP_CRC_CTRLHU_TOTR) & BM_CRC_CTRLHU_TOTR) /*! @brief Set the TOTR field to a new value. */ #define BW_CRC_CTRLHU_TOTR(x, v) (HW_CRC_CTRLHU_WR(x, (HW_CRC_CTRLHU_RD(x) & ~BM_CRC_CTRLHU_TOTR) | BF_CRC_CTRLHU_TOTR(v))) /*@}*/ /*! * @name Register CRC_CTRLHU, field TOT[7:6] (RW) * * Values: * - 00 - No Transposition. * - 01 - Bits in bytes are transposed, bytes are not transposed. * - 10 - Both bits in bytes and bytes are transposed. * - 11 - Only bytes are transposed; no bits in a byte are transposed. */ /*@{*/ #define BP_CRC_CTRLHU_TOT (6U) /*!< Bit position for CRC_CTRLHU_TOT. */ #define BM_CRC_CTRLHU_TOT (0xC0U) /*!< Bit mask for CRC_CTRLHU_TOT. */ #define BS_CRC_CTRLHU_TOT (2U) /*!< Bit field size in bits for CRC_CTRLHU_TOT. */ /*! @brief Read current value of the CRC_CTRLHU_TOT field. */ #define BR_CRC_CTRLHU_TOT(x) (HW_CRC_CTRLHU(x).B.TOT) /*! @brief Format value for bitfield CRC_CTRLHU_TOT. */ #define BF_CRC_CTRLHU_TOT(v) ((uint8_t)((uint8_t)(v) << BP_CRC_CTRLHU_TOT) & BM_CRC_CTRLHU_TOT) /*! @brief Set the TOT field to a new value. */ #define BW_CRC_CTRLHU_TOT(x, v) (HW_CRC_CTRLHU_WR(x, (HW_CRC_CTRLHU_RD(x) & ~BM_CRC_CTRLHU_TOT) | BF_CRC_CTRLHU_TOT(v))) /*@}*/ /* ** Start of section using anonymous unions */ #if defined(__ARMCC_VERSION) #pragma push #pragma anon_unions #elif defined(__CWCC__) #pragma push #pragma cpp_extensions on #elif defined(__GNUC__) /* anonymous unions are enabled by default */ #elif defined(__IAR_SYSTEMS_ICC__) #pragma language=extended #else #error Not supported compiler type #endif /******************************************************************************* * hw_crc_t - module struct ******************************************************************************/ /*! * @brief All CRC module registers. */ #pragma pack(1) typedef struct _hw_crc { union { struct { __IO hw_crc_datal_t DATAL; /*!< [0x0] CRC_DATAL register. */ __IO hw_crc_datah_t DATAH; /*!< [0x2] CRC_DATAH register. */ } ACCESS16BIT; struct { __IO hw_crc_datall_t DATALL; /*!< [0x0] CRC_DATALL register. */ __IO hw_crc_datalu_t DATALU; /*!< [0x1] CRC_DATALU register. */ __IO hw_crc_datahl_t DATAHL; /*!< [0x2] CRC_DATAHL register. */ __IO hw_crc_datahu_t DATAHU; /*!< [0x3] CRC_DATAHU register. */ } ACCESS8BIT; __IO hw_crc_data_t DATA; /*!< [0x0] CRC Data register */ }; union { __IO hw_crc_gpoly_t GPOLY; /*!< [0x4] CRC Polynomial register */ struct { __IO hw_crc_gpolyl_t GPOLYL; /*!< [0x4] CRC_GPOLYL register. */ __IO hw_crc_gpolyh_t GPOLYH; /*!< [0x6] CRC_GPOLYH register. */ } GPOLY_ACCESS16BIT; struct { __IO hw_crc_gpolyll_t GPOLYLL; /*!< [0x4] CRC_GPOLYLL register. */ __IO hw_crc_gpolylu_t GPOLYLU; /*!< [0x5] CRC_GPOLYLU register. */ __IO hw_crc_gpolyhl_t GPOLYHL; /*!< [0x6] CRC_GPOLYHL register. */ __IO hw_crc_gpolyhu_t GPOLYHU; /*!< [0x7] CRC_GPOLYHU register. */ } GPOLY_ACCESS8BIT; }; union { __IO hw_crc_ctrl_t CTRL; /*!< [0x8] CRC Control register */ struct { uint8_t _reserved0[3]; __IO hw_crc_ctrlhu_t CTRLHU; /*!< [0xB] CRC_CTRLHU register. */ } CTRL_ACCESS8BIT; }; } hw_crc_t; #pragma pack() /*! @brief Macro to access all CRC registers. */ /*! @param x CRC module instance base address. */ /*! @return Reference (not a pointer) to the registers struct. To get a pointer to the struct, * use the '&' operator, like &HW_CRC(CRC_BASE). */ #define HW_CRC(x) (*(hw_crc_t *)(x)) /* ** End of section using anonymous unions */ #if defined(__ARMCC_VERSION) #pragma pop #elif defined(__CWCC__) #pragma pop #elif defined(__GNUC__) /* leave anonymous unions enabled */ #elif defined(__IAR_SYSTEMS_ICC__) #pragma language=default #else #error Not supported compiler type #endif #endif /* __HW_CRC_REGISTERS_H__ */ /* EOF */ ================================================ FILE: Zelig/mbed/TARGET_K64F/TARGET_Freescale/TARGET_KPSDK_MCUS/TARGET_MCU_K64F/device/device/MK64F12/MK64F12_dac.h ================================================ /* ** ################################################################### ** Compilers: Keil ARM C/C++ Compiler ** Freescale C/C++ for Embedded ARM ** GNU C Compiler ** IAR ANSI C/C++ Compiler for ARM ** ** Reference manual: K64P144M120SF5RM, Rev.2, January 2014 ** Version: rev. 2.5, 2014-02-10 ** Build: b140604 ** ** Abstract: ** Extension to the CMSIS register access layer header. ** ** Copyright (c) 2014 Freescale Semiconductor, Inc. ** All rights reserved. ** ** Redistribution and use in source and binary forms, with or without modification, ** are permitted provided that the following conditions are met: ** ** o Redistributions of source code must retain the above copyright notice, this list ** of conditions and the following disclaimer. ** ** o Redistributions in binary form must reproduce the above copyright notice, this ** list of conditions and the following disclaimer in the documentation and/or ** other materials provided with the distribution. ** ** o Neither the name of Freescale Semiconductor, Inc. nor the names of its ** contributors may be used to endorse or promote products derived from this ** software without specific prior written permission. ** ** THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ** ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED ** WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE ** DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT 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. ** ** http: www.freescale.com ** mail: support@freescale.com ** ** Revisions: ** - rev. 1.0 (2013-08-12) ** Initial version. ** - rev. 2.0 (2013-10-29) ** Register accessor macros added to the memory map. ** Symbols for Processor Expert memory map compatibility added to the memory map. ** Startup file for gcc has been updated according to CMSIS 3.2. ** System initialization updated. ** MCG - registers updated. ** PORTA, PORTB, PORTC, PORTE - registers for digital filter removed. ** - rev. 2.1 (2013-10-30) ** Definition of BITBAND macros updated to support peripherals with 32-bit acces disabled. ** - rev. 2.2 (2013-12-09) ** DMA - EARS register removed. ** AIPS0, AIPS1 - MPRA register updated. ** - rev. 2.3 (2014-01-24) ** Update according to reference manual rev. 2 ** ENET, MCG, MCM, SIM, USB - registers updated ** - rev. 2.4 (2014-02-10) ** The declaration of clock configurations has been moved to separate header file system_MK64F12.h ** Update of SystemInit() and SystemCoreClockUpdate() functions. ** - rev. 2.5 (2014-02-10) ** The declaration of clock configurations has been moved to separate header file system_MK64F12.h ** Update of SystemInit() and SystemCoreClockUpdate() functions. ** Module access macro module_BASES replaced by module_BASE_PTRS. ** ** ################################################################### */ /* * WARNING! DO NOT EDIT THIS FILE DIRECTLY! * * This file was generated automatically and any changes may be lost. */ #ifndef __HW_DAC_REGISTERS_H__ #define __HW_DAC_REGISTERS_H__ #include "MK64F12.h" #include "fsl_bitaccess.h" /* * MK64F12 DAC * * 12-Bit Digital-to-Analog Converter * * Registers defined in this header file: * - HW_DAC_DATnL - DAC Data Low Register * - HW_DAC_DATnH - DAC Data High Register * - HW_DAC_SR - DAC Status Register * - HW_DAC_C0 - DAC Control Register * - HW_DAC_C1 - DAC Control Register 1 * - HW_DAC_C2 - DAC Control Register 2 * * - hw_dac_t - Struct containing all module registers. */ #define HW_DAC_INSTANCE_COUNT (2U) /*!< Number of instances of the DAC module. */ #define HW_DAC0 (0U) /*!< Instance number for DAC0. */ #define HW_DAC1 (1U) /*!< Instance number for DAC1. */ /******************************************************************************* * HW_DAC_DATnL - DAC Data Low Register ******************************************************************************/ /*! * @brief HW_DAC_DATnL - DAC Data Low Register (RW) * * Reset value: 0x00U */ typedef union _hw_dac_datnl { uint8_t U; struct _hw_dac_datnl_bitfields { uint8_t DATA0 : 8; /*!< [7:0] */ } B; } hw_dac_datnl_t; /*! * @name Constants and macros for entire DAC_DATnL register */ /*@{*/ #define HW_DAC_DATnL_COUNT (16U) #define HW_DAC_DATnL_ADDR(x, n) ((x) + 0x0U + (0x2U * (n))) #define HW_DAC_DATnL(x, n) (*(__IO hw_dac_datnl_t *) HW_DAC_DATnL_ADDR(x, n)) #define HW_DAC_DATnL_RD(x, n) (HW_DAC_DATnL(x, n).U) #define HW_DAC_DATnL_WR(x, n, v) (HW_DAC_DATnL(x, n).U = (v)) #define HW_DAC_DATnL_SET(x, n, v) (HW_DAC_DATnL_WR(x, n, HW_DAC_DATnL_RD(x, n) | (v))) #define HW_DAC_DATnL_CLR(x, n, v) (HW_DAC_DATnL_WR(x, n, HW_DAC_DATnL_RD(x, n) & ~(v))) #define HW_DAC_DATnL_TOG(x, n, v) (HW_DAC_DATnL_WR(x, n, HW_DAC_DATnL_RD(x, n) ^ (v))) /*@}*/ /* * Constants & macros for individual DAC_DATnL bitfields */ /*! * @name Register DAC_DATnL, field DATA0[7:0] (RW) * * When the DAC buffer is not enabled, DATA[11:0] controls the output voltage * based on the following formula: V out = V in * (1 + DACDAT0[11:0])/4096 When the * DAC buffer is enabled, DATA is mapped to the 16-word buffer. */ /*@{*/ #define BP_DAC_DATnL_DATA0 (0U) /*!< Bit position for DAC_DATnL_DATA0. */ #define BM_DAC_DATnL_DATA0 (0xFFU) /*!< Bit mask for DAC_DATnL_DATA0. */ #define BS_DAC_DATnL_DATA0 (8U) /*!< Bit field size in bits for DAC_DATnL_DATA0. */ /*! @brief Read current value of the DAC_DATnL_DATA0 field. */ #define BR_DAC_DATnL_DATA0(x, n) (HW_DAC_DATnL(x, n).U) /*! @brief Format value for bitfield DAC_DATnL_DATA0. */ #define BF_DAC_DATnL_DATA0(v) ((uint8_t)((uint8_t)(v) << BP_DAC_DATnL_DATA0) & BM_DAC_DATnL_DATA0) /*! @brief Set the DATA0 field to a new value. */ #define BW_DAC_DATnL_DATA0(x, n, v) (HW_DAC_DATnL_WR(x, n, v)) /*@}*/ /******************************************************************************* * HW_DAC_DATnH - DAC Data High Register ******************************************************************************/ /*! * @brief HW_DAC_DATnH - DAC Data High Register (RW) * * Reset value: 0x00U */ typedef union _hw_dac_datnh { uint8_t U; struct _hw_dac_datnh_bitfields { uint8_t DATA1 : 4; /*!< [3:0] */ uint8_t RESERVED0 : 4; /*!< [7:4] */ } B; } hw_dac_datnh_t; /*! * @name Constants and macros for entire DAC_DATnH register */ /*@{*/ #define HW_DAC_DATnH_COUNT (16U) #define HW_DAC_DATnH_ADDR(x, n) ((x) + 0x1U + (0x2U * (n))) #define HW_DAC_DATnH(x, n) (*(__IO hw_dac_datnh_t *) HW_DAC_DATnH_ADDR(x, n)) #define HW_DAC_DATnH_RD(x, n) (HW_DAC_DATnH(x, n).U) #define HW_DAC_DATnH_WR(x, n, v) (HW_DAC_DATnH(x, n).U = (v)) #define HW_DAC_DATnH_SET(x, n, v) (HW_DAC_DATnH_WR(x, n, HW_DAC_DATnH_RD(x, n) | (v))) #define HW_DAC_DATnH_CLR(x, n, v) (HW_DAC_DATnH_WR(x, n, HW_DAC_DATnH_RD(x, n) & ~(v))) #define HW_DAC_DATnH_TOG(x, n, v) (HW_DAC_DATnH_WR(x, n, HW_DAC_DATnH_RD(x, n) ^ (v))) /*@}*/ /* * Constants & macros for individual DAC_DATnH bitfields */ /*! * @name Register DAC_DATnH, field DATA1[3:0] (RW) * * When the DAC Buffer is not enabled, DATA[11:0] controls the output voltage * based on the following formula. V out = V in * (1 + DACDAT0[11:0])/4096 When the * DAC buffer is enabled, DATA[11:0] is mapped to the 16-word buffer. */ /*@{*/ #define BP_DAC_DATnH_DATA1 (0U) /*!< Bit position for DAC_DATnH_DATA1. */ #define BM_DAC_DATnH_DATA1 (0x0FU) /*!< Bit mask for DAC_DATnH_DATA1. */ #define BS_DAC_DATnH_DATA1 (4U) /*!< Bit field size in bits for DAC_DATnH_DATA1. */ /*! @brief Read current value of the DAC_DATnH_DATA1 field. */ #define BR_DAC_DATnH_DATA1(x, n) (HW_DAC_DATnH(x, n).B.DATA1) /*! @brief Format value for bitfield DAC_DATnH_DATA1. */ #define BF_DAC_DATnH_DATA1(v) ((uint8_t)((uint8_t)(v) << BP_DAC_DATnH_DATA1) & BM_DAC_DATnH_DATA1) /*! @brief Set the DATA1 field to a new value. */ #define BW_DAC_DATnH_DATA1(x, n, v) (HW_DAC_DATnH_WR(x, n, (HW_DAC_DATnH_RD(x, n) & ~BM_DAC_DATnH_DATA1) | BF_DAC_DATnH_DATA1(v))) /*@}*/ /******************************************************************************* * HW_DAC_SR - DAC Status Register ******************************************************************************/ /*! * @brief HW_DAC_SR - DAC Status Register (RW) * * Reset value: 0x02U * * If DMA is enabled, the flags can be cleared automatically by DMA when the DMA * request is done. Writing 0 to a field clears it whereas writing 1 has no * effect. After reset, DACBFRPTF is set and can be cleared by software, if needed. * The flags are set only when the data buffer status is changed. Do not use * 32/16-bit accesses to this register. */ typedef union _hw_dac_sr { uint8_t U; struct _hw_dac_sr_bitfields { uint8_t DACBFRPBF : 1; /*!< [0] DAC Buffer Read Pointer Bottom * Position Flag */ uint8_t DACBFRPTF : 1; /*!< [1] DAC Buffer Read Pointer Top Position * Flag */ uint8_t DACBFWMF : 1; /*!< [2] DAC Buffer Watermark Flag */ uint8_t RESERVED0 : 5; /*!< [7:3] */ } B; } hw_dac_sr_t; /*! * @name Constants and macros for entire DAC_SR register */ /*@{*/ #define HW_DAC_SR_ADDR(x) ((x) + 0x20U) #define HW_DAC_SR(x) (*(__IO hw_dac_sr_t *) HW_DAC_SR_ADDR(x)) #define HW_DAC_SR_RD(x) (HW_DAC_SR(x).U) #define HW_DAC_SR_WR(x, v) (HW_DAC_SR(x).U = (v)) #define HW_DAC_SR_SET(x, v) (HW_DAC_SR_WR(x, HW_DAC_SR_RD(x) | (v))) #define HW_DAC_SR_CLR(x, v) (HW_DAC_SR_WR(x, HW_DAC_SR_RD(x) & ~(v))) #define HW_DAC_SR_TOG(x, v) (HW_DAC_SR_WR(x, HW_DAC_SR_RD(x) ^ (v))) /*@}*/ /* * Constants & macros for individual DAC_SR bitfields */ /*! * @name Register DAC_SR, field DACBFRPBF[0] (RW) * * Values: * - 0 - The DAC buffer read pointer is not equal to C2[DACBFUP]. * - 1 - The DAC buffer read pointer is equal to C2[DACBFUP]. */ /*@{*/ #define BP_DAC_SR_DACBFRPBF (0U) /*!< Bit position for DAC_SR_DACBFRPBF. */ #define BM_DAC_SR_DACBFRPBF (0x01U) /*!< Bit mask for DAC_SR_DACBFRPBF. */ #define BS_DAC_SR_DACBFRPBF (1U) /*!< Bit field size in bits for DAC_SR_DACBFRPBF. */ /*! @brief Read current value of the DAC_SR_DACBFRPBF field. */ #define BR_DAC_SR_DACBFRPBF(x) (BITBAND_ACCESS8(HW_DAC_SR_ADDR(x), BP_DAC_SR_DACBFRPBF)) /*! @brief Format value for bitfield DAC_SR_DACBFRPBF. */ #define BF_DAC_SR_DACBFRPBF(v) ((uint8_t)((uint8_t)(v) << BP_DAC_SR_DACBFRPBF) & BM_DAC_SR_DACBFRPBF) /*! @brief Set the DACBFRPBF field to a new value. */ #define BW_DAC_SR_DACBFRPBF(x, v) (BITBAND_ACCESS8(HW_DAC_SR_ADDR(x), BP_DAC_SR_DACBFRPBF) = (v)) /*@}*/ /*! * @name Register DAC_SR, field DACBFRPTF[1] (RW) * * Values: * - 0 - The DAC buffer read pointer is not zero. * - 1 - The DAC buffer read pointer is zero. */ /*@{*/ #define BP_DAC_SR_DACBFRPTF (1U) /*!< Bit position for DAC_SR_DACBFRPTF. */ #define BM_DAC_SR_DACBFRPTF (0x02U) /*!< Bit mask for DAC_SR_DACBFRPTF. */ #define BS_DAC_SR_DACBFRPTF (1U) /*!< Bit field size in bits for DAC_SR_DACBFRPTF. */ /*! @brief Read current value of the DAC_SR_DACBFRPTF field. */ #define BR_DAC_SR_DACBFRPTF(x) (BITBAND_ACCESS8(HW_DAC_SR_ADDR(x), BP_DAC_SR_DACBFRPTF)) /*! @brief Format value for bitfield DAC_SR_DACBFRPTF. */ #define BF_DAC_SR_DACBFRPTF(v) ((uint8_t)((uint8_t)(v) << BP_DAC_SR_DACBFRPTF) & BM_DAC_SR_DACBFRPTF) /*! @brief Set the DACBFRPTF field to a new value. */ #define BW_DAC_SR_DACBFRPTF(x, v) (BITBAND_ACCESS8(HW_DAC_SR_ADDR(x), BP_DAC_SR_DACBFRPTF) = (v)) /*@}*/ /*! * @name Register DAC_SR, field DACBFWMF[2] (RW) * * Values: * - 0 - The DAC buffer read pointer has not reached the watermark level. * - 1 - The DAC buffer read pointer has reached the watermark level. */ /*@{*/ #define BP_DAC_SR_DACBFWMF (2U) /*!< Bit position for DAC_SR_DACBFWMF. */ #define BM_DAC_SR_DACBFWMF (0x04U) /*!< Bit mask for DAC_SR_DACBFWMF. */ #define BS_DAC_SR_DACBFWMF (1U) /*!< Bit field size in bits for DAC_SR_DACBFWMF. */ /*! @brief Read current value of the DAC_SR_DACBFWMF field. */ #define BR_DAC_SR_DACBFWMF(x) (BITBAND_ACCESS8(HW_DAC_SR_ADDR(x), BP_DAC_SR_DACBFWMF)) /*! @brief Format value for bitfield DAC_SR_DACBFWMF. */ #define BF_DAC_SR_DACBFWMF(v) ((uint8_t)((uint8_t)(v) << BP_DAC_SR_DACBFWMF) & BM_DAC_SR_DACBFWMF) /*! @brief Set the DACBFWMF field to a new value. */ #define BW_DAC_SR_DACBFWMF(x, v) (BITBAND_ACCESS8(HW_DAC_SR_ADDR(x), BP_DAC_SR_DACBFWMF) = (v)) /*@}*/ /******************************************************************************* * HW_DAC_C0 - DAC Control Register ******************************************************************************/ /*! * @brief HW_DAC_C0 - DAC Control Register (RW) * * Reset value: 0x00U * * Do not use 32- or 16-bit accesses to this register. */ typedef union _hw_dac_c0 { uint8_t U; struct _hw_dac_c0_bitfields { uint8_t DACBBIEN : 1; /*!< [0] DAC Buffer Read Pointer Bottom Flag * Interrupt Enable */ uint8_t DACBTIEN : 1; /*!< [1] DAC Buffer Read Pointer Top Flag * Interrupt Enable */ uint8_t DACBWIEN : 1; /*!< [2] DAC Buffer Watermark Interrupt Enable * */ uint8_t LPEN : 1; /*!< [3] DAC Low Power Control */ uint8_t DACSWTRG : 1; /*!< [4] DAC Software Trigger */ uint8_t DACTRGSEL : 1; /*!< [5] DAC Trigger Select */ uint8_t DACRFS : 1; /*!< [6] DAC Reference Select */ uint8_t DACEN : 1; /*!< [7] DAC Enable */ } B; } hw_dac_c0_t; /*! * @name Constants and macros for entire DAC_C0 register */ /*@{*/ #define HW_DAC_C0_ADDR(x) ((x) + 0x21U) #define HW_DAC_C0(x) (*(__IO hw_dac_c0_t *) HW_DAC_C0_ADDR(x)) #define HW_DAC_C0_RD(x) (HW_DAC_C0(x).U) #define HW_DAC_C0_WR(x, v) (HW_DAC_C0(x).U = (v)) #define HW_DAC_C0_SET(x, v) (HW_DAC_C0_WR(x, HW_DAC_C0_RD(x) | (v))) #define HW_DAC_C0_CLR(x, v) (HW_DAC_C0_WR(x, HW_DAC_C0_RD(x) & ~(v))) #define HW_DAC_C0_TOG(x, v) (HW_DAC_C0_WR(x, HW_DAC_C0_RD(x) ^ (v))) /*@}*/ /* * Constants & macros for individual DAC_C0 bitfields */ /*! * @name Register DAC_C0, field DACBBIEN[0] (RW) * * Values: * - 0 - The DAC buffer read pointer bottom flag interrupt is disabled. * - 1 - The DAC buffer read pointer bottom flag interrupt is enabled. */ /*@{*/ #define BP_DAC_C0_DACBBIEN (0U) /*!< Bit position for DAC_C0_DACBBIEN. */ #define BM_DAC_C0_DACBBIEN (0x01U) /*!< Bit mask for DAC_C0_DACBBIEN. */ #define BS_DAC_C0_DACBBIEN (1U) /*!< Bit field size in bits for DAC_C0_DACBBIEN. */ /*! @brief Read current value of the DAC_C0_DACBBIEN field. */ #define BR_DAC_C0_DACBBIEN(x) (BITBAND_ACCESS8(HW_DAC_C0_ADDR(x), BP_DAC_C0_DACBBIEN)) /*! @brief Format value for bitfield DAC_C0_DACBBIEN. */ #define BF_DAC_C0_DACBBIEN(v) ((uint8_t)((uint8_t)(v) << BP_DAC_C0_DACBBIEN) & BM_DAC_C0_DACBBIEN) /*! @brief Set the DACBBIEN field to a new value. */ #define BW_DAC_C0_DACBBIEN(x, v) (BITBAND_ACCESS8(HW_DAC_C0_ADDR(x), BP_DAC_C0_DACBBIEN) = (v)) /*@}*/ /*! * @name Register DAC_C0, field DACBTIEN[1] (RW) * * Values: * - 0 - The DAC buffer read pointer top flag interrupt is disabled. * - 1 - The DAC buffer read pointer top flag interrupt is enabled. */ /*@{*/ #define BP_DAC_C0_DACBTIEN (1U) /*!< Bit position for DAC_C0_DACBTIEN. */ #define BM_DAC_C0_DACBTIEN (0x02U) /*!< Bit mask for DAC_C0_DACBTIEN. */ #define BS_DAC_C0_DACBTIEN (1U) /*!< Bit field size in bits for DAC_C0_DACBTIEN. */ /*! @brief Read current value of the DAC_C0_DACBTIEN field. */ #define BR_DAC_C0_DACBTIEN(x) (BITBAND_ACCESS8(HW_DAC_C0_ADDR(x), BP_DAC_C0_DACBTIEN)) /*! @brief Format value for bitfield DAC_C0_DACBTIEN. */ #define BF_DAC_C0_DACBTIEN(v) ((uint8_t)((uint8_t)(v) << BP_DAC_C0_DACBTIEN) & BM_DAC_C0_DACBTIEN) /*! @brief Set the DACBTIEN field to a new value. */ #define BW_DAC_C0_DACBTIEN(x, v) (BITBAND_ACCESS8(HW_DAC_C0_ADDR(x), BP_DAC_C0_DACBTIEN) = (v)) /*@}*/ /*! * @name Register DAC_C0, field DACBWIEN[2] (RW) * * Values: * - 0 - The DAC buffer watermark interrupt is disabled. * - 1 - The DAC buffer watermark interrupt is enabled. */ /*@{*/ #define BP_DAC_C0_DACBWIEN (2U) /*!< Bit position for DAC_C0_DACBWIEN. */ #define BM_DAC_C0_DACBWIEN (0x04U) /*!< Bit mask for DAC_C0_DACBWIEN. */ #define BS_DAC_C0_DACBWIEN (1U) /*!< Bit field size in bits for DAC_C0_DACBWIEN. */ /*! @brief Read current value of the DAC_C0_DACBWIEN field. */ #define BR_DAC_C0_DACBWIEN(x) (BITBAND_ACCESS8(HW_DAC_C0_ADDR(x), BP_DAC_C0_DACBWIEN)) /*! @brief Format value for bitfield DAC_C0_DACBWIEN. */ #define BF_DAC_C0_DACBWIEN(v) ((uint8_t)((uint8_t)(v) << BP_DAC_C0_DACBWIEN) & BM_DAC_C0_DACBWIEN) /*! @brief Set the DACBWIEN field to a new value. */ #define BW_DAC_C0_DACBWIEN(x, v) (BITBAND_ACCESS8(HW_DAC_C0_ADDR(x), BP_DAC_C0_DACBWIEN) = (v)) /*@}*/ /*! * @name Register DAC_C0, field LPEN[3] (RW) * * See the 12-bit DAC electrical characteristics of the device data sheet for * details on the impact of the modes below. * * Values: * - 0 - High-Power mode * - 1 - Low-Power mode */ /*@{*/ #define BP_DAC_C0_LPEN (3U) /*!< Bit position for DAC_C0_LPEN. */ #define BM_DAC_C0_LPEN (0x08U) /*!< Bit mask for DAC_C0_LPEN. */ #define BS_DAC_C0_LPEN (1U) /*!< Bit field size in bits for DAC_C0_LPEN. */ /*! @brief Read current value of the DAC_C0_LPEN field. */ #define BR_DAC_C0_LPEN(x) (BITBAND_ACCESS8(HW_DAC_C0_ADDR(x), BP_DAC_C0_LPEN)) /*! @brief Format value for bitfield DAC_C0_LPEN. */ #define BF_DAC_C0_LPEN(v) ((uint8_t)((uint8_t)(v) << BP_DAC_C0_LPEN) & BM_DAC_C0_LPEN) /*! @brief Set the LPEN field to a new value. */ #define BW_DAC_C0_LPEN(x, v) (BITBAND_ACCESS8(HW_DAC_C0_ADDR(x), BP_DAC_C0_LPEN) = (v)) /*@}*/ /*! * @name Register DAC_C0, field DACSWTRG[4] (WORZ) * * Active high. This is a write-only field, which always reads 0. If DAC * software trigger is selected and buffer is enabled, writing 1 to this field will * advance the buffer read pointer once. * * Values: * - 0 - The DAC soft trigger is not valid. * - 1 - The DAC soft trigger is valid. */ /*@{*/ #define BP_DAC_C0_DACSWTRG (4U) /*!< Bit position for DAC_C0_DACSWTRG. */ #define BM_DAC_C0_DACSWTRG (0x10U) /*!< Bit mask for DAC_C0_DACSWTRG. */ #define BS_DAC_C0_DACSWTRG (1U) /*!< Bit field size in bits for DAC_C0_DACSWTRG. */ /*! @brief Format value for bitfield DAC_C0_DACSWTRG. */ #define BF_DAC_C0_DACSWTRG(v) ((uint8_t)((uint8_t)(v) << BP_DAC_C0_DACSWTRG) & BM_DAC_C0_DACSWTRG) /*! @brief Set the DACSWTRG field to a new value. */ #define BW_DAC_C0_DACSWTRG(x, v) (BITBAND_ACCESS8(HW_DAC_C0_ADDR(x), BP_DAC_C0_DACSWTRG) = (v)) /*@}*/ /*! * @name Register DAC_C0, field DACTRGSEL[5] (RW) * * Values: * - 0 - The DAC hardware trigger is selected. * - 1 - The DAC software trigger is selected. */ /*@{*/ #define BP_DAC_C0_DACTRGSEL (5U) /*!< Bit position for DAC_C0_DACTRGSEL. */ #define BM_DAC_C0_DACTRGSEL (0x20U) /*!< Bit mask for DAC_C0_DACTRGSEL. */ #define BS_DAC_C0_DACTRGSEL (1U) /*!< Bit field size in bits for DAC_C0_DACTRGSEL. */ /*! @brief Read current value of the DAC_C0_DACTRGSEL field. */ #define BR_DAC_C0_DACTRGSEL(x) (BITBAND_ACCESS8(HW_DAC_C0_ADDR(x), BP_DAC_C0_DACTRGSEL)) /*! @brief Format value for bitfield DAC_C0_DACTRGSEL. */ #define BF_DAC_C0_DACTRGSEL(v) ((uint8_t)((uint8_t)(v) << BP_DAC_C0_DACTRGSEL) & BM_DAC_C0_DACTRGSEL) /*! @brief Set the DACTRGSEL field to a new value. */ #define BW_DAC_C0_DACTRGSEL(x, v) (BITBAND_ACCESS8(HW_DAC_C0_ADDR(x), BP_DAC_C0_DACTRGSEL) = (v)) /*@}*/ /*! * @name Register DAC_C0, field DACRFS[6] (RW) * * Values: * - 0 - The DAC selects DACREF_1 as the reference voltage. * - 1 - The DAC selects DACREF_2 as the reference voltage. */ /*@{*/ #define BP_DAC_C0_DACRFS (6U) /*!< Bit position for DAC_C0_DACRFS. */ #define BM_DAC_C0_DACRFS (0x40U) /*!< Bit mask for DAC_C0_DACRFS. */ #define BS_DAC_C0_DACRFS (1U) /*!< Bit field size in bits for DAC_C0_DACRFS. */ /*! @brief Read current value of the DAC_C0_DACRFS field. */ #define BR_DAC_C0_DACRFS(x) (BITBAND_ACCESS8(HW_DAC_C0_ADDR(x), BP_DAC_C0_DACRFS)) /*! @brief Format value for bitfield DAC_C0_DACRFS. */ #define BF_DAC_C0_DACRFS(v) ((uint8_t)((uint8_t)(v) << BP_DAC_C0_DACRFS) & BM_DAC_C0_DACRFS) /*! @brief Set the DACRFS field to a new value. */ #define BW_DAC_C0_DACRFS(x, v) (BITBAND_ACCESS8(HW_DAC_C0_ADDR(x), BP_DAC_C0_DACRFS) = (v)) /*@}*/ /*! * @name Register DAC_C0, field DACEN[7] (RW) * * Starts the Programmable Reference Generator operation. * * Values: * - 0 - The DAC system is disabled. * - 1 - The DAC system is enabled. */ /*@{*/ #define BP_DAC_C0_DACEN (7U) /*!< Bit position for DAC_C0_DACEN. */ #define BM_DAC_C0_DACEN (0x80U) /*!< Bit mask for DAC_C0_DACEN. */ #define BS_DAC_C0_DACEN (1U) /*!< Bit field size in bits for DAC_C0_DACEN. */ /*! @brief Read current value of the DAC_C0_DACEN field. */ #define BR_DAC_C0_DACEN(x) (BITBAND_ACCESS8(HW_DAC_C0_ADDR(x), BP_DAC_C0_DACEN)) /*! @brief Format value for bitfield DAC_C0_DACEN. */ #define BF_DAC_C0_DACEN(v) ((uint8_t)((uint8_t)(v) << BP_DAC_C0_DACEN) & BM_DAC_C0_DACEN) /*! @brief Set the DACEN field to a new value. */ #define BW_DAC_C0_DACEN(x, v) (BITBAND_ACCESS8(HW_DAC_C0_ADDR(x), BP_DAC_C0_DACEN) = (v)) /*@}*/ /******************************************************************************* * HW_DAC_C1 - DAC Control Register 1 ******************************************************************************/ /*! * @brief HW_DAC_C1 - DAC Control Register 1 (RW) * * Reset value: 0x00U * * Do not use 32- or 16-bit accesses to this register. */ typedef union _hw_dac_c1 { uint8_t U; struct _hw_dac_c1_bitfields { uint8_t DACBFEN : 1; /*!< [0] DAC Buffer Enable */ uint8_t DACBFMD : 2; /*!< [2:1] DAC Buffer Work Mode Select */ uint8_t DACBFWM : 2; /*!< [4:3] DAC Buffer Watermark Select */ uint8_t RESERVED0 : 2; /*!< [6:5] */ uint8_t DMAEN : 1; /*!< [7] DMA Enable Select */ } B; } hw_dac_c1_t; /*! * @name Constants and macros for entire DAC_C1 register */ /*@{*/ #define HW_DAC_C1_ADDR(x) ((x) + 0x22U) #define HW_DAC_C1(x) (*(__IO hw_dac_c1_t *) HW_DAC_C1_ADDR(x)) #define HW_DAC_C1_RD(x) (HW_DAC_C1(x).U) #define HW_DAC_C1_WR(x, v) (HW_DAC_C1(x).U = (v)) #define HW_DAC_C1_SET(x, v) (HW_DAC_C1_WR(x, HW_DAC_C1_RD(x) | (v))) #define HW_DAC_C1_CLR(x, v) (HW_DAC_C1_WR(x, HW_DAC_C1_RD(x) & ~(v))) #define HW_DAC_C1_TOG(x, v) (HW_DAC_C1_WR(x, HW_DAC_C1_RD(x) ^ (v))) /*@}*/ /* * Constants & macros for individual DAC_C1 bitfields */ /*! * @name Register DAC_C1, field DACBFEN[0] (RW) * * Values: * - 0 - Buffer read pointer is disabled. The converted data is always the first * word of the buffer. * - 1 - Buffer read pointer is enabled. The converted data is the word that the * read pointer points to. It means converted data can be from any word of * the buffer. */ /*@{*/ #define BP_DAC_C1_DACBFEN (0U) /*!< Bit position for DAC_C1_DACBFEN. */ #define BM_DAC_C1_DACBFEN (0x01U) /*!< Bit mask for DAC_C1_DACBFEN. */ #define BS_DAC_C1_DACBFEN (1U) /*!< Bit field size in bits for DAC_C1_DACBFEN. */ /*! @brief Read current value of the DAC_C1_DACBFEN field. */ #define BR_DAC_C1_DACBFEN(x) (BITBAND_ACCESS8(HW_DAC_C1_ADDR(x), BP_DAC_C1_DACBFEN)) /*! @brief Format value for bitfield DAC_C1_DACBFEN. */ #define BF_DAC_C1_DACBFEN(v) ((uint8_t)((uint8_t)(v) << BP_DAC_C1_DACBFEN) & BM_DAC_C1_DACBFEN) /*! @brief Set the DACBFEN field to a new value. */ #define BW_DAC_C1_DACBFEN(x, v) (BITBAND_ACCESS8(HW_DAC_C1_ADDR(x), BP_DAC_C1_DACBFEN) = (v)) /*@}*/ /*! * @name Register DAC_C1, field DACBFMD[2:1] (RW) * * Values: * - 00 - Normal mode * - 01 - Swing mode * - 10 - One-Time Scan mode * - 11 - Reserved */ /*@{*/ #define BP_DAC_C1_DACBFMD (1U) /*!< Bit position for DAC_C1_DACBFMD. */ #define BM_DAC_C1_DACBFMD (0x06U) /*!< Bit mask for DAC_C1_DACBFMD. */ #define BS_DAC_C1_DACBFMD (2U) /*!< Bit field size in bits for DAC_C1_DACBFMD. */ /*! @brief Read current value of the DAC_C1_DACBFMD field. */ #define BR_DAC_C1_DACBFMD(x) (HW_DAC_C1(x).B.DACBFMD) /*! @brief Format value for bitfield DAC_C1_DACBFMD. */ #define BF_DAC_C1_DACBFMD(v) ((uint8_t)((uint8_t)(v) << BP_DAC_C1_DACBFMD) & BM_DAC_C1_DACBFMD) /*! @brief Set the DACBFMD field to a new value. */ #define BW_DAC_C1_DACBFMD(x, v) (HW_DAC_C1_WR(x, (HW_DAC_C1_RD(x) & ~BM_DAC_C1_DACBFMD) | BF_DAC_C1_DACBFMD(v))) /*@}*/ /*! * @name Register DAC_C1, field DACBFWM[4:3] (RW) * * Controls when SR[DACBFWMF] is set. When the DAC buffer read pointer reaches * the word defined by this field, which is 1-4 words away from the upper limit * (DACBUP), SR[DACBFWMF] will be set. This allows user configuration of the * watermark interrupt. * * Values: * - 00 - 1 word * - 01 - 2 words * - 10 - 3 words * - 11 - 4 words */ /*@{*/ #define BP_DAC_C1_DACBFWM (3U) /*!< Bit position for DAC_C1_DACBFWM. */ #define BM_DAC_C1_DACBFWM (0x18U) /*!< Bit mask for DAC_C1_DACBFWM. */ #define BS_DAC_C1_DACBFWM (2U) /*!< Bit field size in bits for DAC_C1_DACBFWM. */ /*! @brief Read current value of the DAC_C1_DACBFWM field. */ #define BR_DAC_C1_DACBFWM(x) (HW_DAC_C1(x).B.DACBFWM) /*! @brief Format value for bitfield DAC_C1_DACBFWM. */ #define BF_DAC_C1_DACBFWM(v) ((uint8_t)((uint8_t)(v) << BP_DAC_C1_DACBFWM) & BM_DAC_C1_DACBFWM) /*! @brief Set the DACBFWM field to a new value. */ #define BW_DAC_C1_DACBFWM(x, v) (HW_DAC_C1_WR(x, (HW_DAC_C1_RD(x) & ~BM_DAC_C1_DACBFWM) | BF_DAC_C1_DACBFWM(v))) /*@}*/ /*! * @name Register DAC_C1, field DMAEN[7] (RW) * * Values: * - 0 - DMA is disabled. * - 1 - DMA is enabled. When DMA is enabled, the DMA request will be generated * by original interrupts. The interrupts will not be presented on this * module at the same time. */ /*@{*/ #define BP_DAC_C1_DMAEN (7U) /*!< Bit position for DAC_C1_DMAEN. */ #define BM_DAC_C1_DMAEN (0x80U) /*!< Bit mask for DAC_C1_DMAEN. */ #define BS_DAC_C1_DMAEN (1U) /*!< Bit field size in bits for DAC_C1_DMAEN. */ /*! @brief Read current value of the DAC_C1_DMAEN field. */ #define BR_DAC_C1_DMAEN(x) (BITBAND_ACCESS8(HW_DAC_C1_ADDR(x), BP_DAC_C1_DMAEN)) /*! @brief Format value for bitfield DAC_C1_DMAEN. */ #define BF_DAC_C1_DMAEN(v) ((uint8_t)((uint8_t)(v) << BP_DAC_C1_DMAEN) & BM_DAC_C1_DMAEN) /*! @brief Set the DMAEN field to a new value. */ #define BW_DAC_C1_DMAEN(x, v) (BITBAND_ACCESS8(HW_DAC_C1_ADDR(x), BP_DAC_C1_DMAEN) = (v)) /*@}*/ /******************************************************************************* * HW_DAC_C2 - DAC Control Register 2 ******************************************************************************/ /*! * @brief HW_DAC_C2 - DAC Control Register 2 (RW) * * Reset value: 0x0FU */ typedef union _hw_dac_c2 { uint8_t U; struct _hw_dac_c2_bitfields { uint8_t DACBFUP : 4; /*!< [3:0] DAC Buffer Upper Limit */ uint8_t DACBFRP : 4; /*!< [7:4] DAC Buffer Read Pointer */ } B; } hw_dac_c2_t; /*! * @name Constants and macros for entire DAC_C2 register */ /*@{*/ #define HW_DAC_C2_ADDR(x) ((x) + 0x23U) #define HW_DAC_C2(x) (*(__IO hw_dac_c2_t *) HW_DAC_C2_ADDR(x)) #define HW_DAC_C2_RD(x) (HW_DAC_C2(x).U) #define HW_DAC_C2_WR(x, v) (HW_DAC_C2(x).U = (v)) #define HW_DAC_C2_SET(x, v) (HW_DAC_C2_WR(x, HW_DAC_C2_RD(x) | (v))) #define HW_DAC_C2_CLR(x, v) (HW_DAC_C2_WR(x, HW_DAC_C2_RD(x) & ~(v))) #define HW_DAC_C2_TOG(x, v) (HW_DAC_C2_WR(x, HW_DAC_C2_RD(x) ^ (v))) /*@}*/ /* * Constants & macros for individual DAC_C2 bitfields */ /*! * @name Register DAC_C2, field DACBFUP[3:0] (RW) * * Selects the upper limit of the DAC buffer. The buffer read pointer cannot * exceed it. */ /*@{*/ #define BP_DAC_C2_DACBFUP (0U) /*!< Bit position for DAC_C2_DACBFUP. */ #define BM_DAC_C2_DACBFUP (0x0FU) /*!< Bit mask for DAC_C2_DACBFUP. */ #define BS_DAC_C2_DACBFUP (4U) /*!< Bit field size in bits for DAC_C2_DACBFUP. */ /*! @brief Read current value of the DAC_C2_DACBFUP field. */ #define BR_DAC_C2_DACBFUP(x) (HW_DAC_C2(x).B.DACBFUP) /*! @brief Format value for bitfield DAC_C2_DACBFUP. */ #define BF_DAC_C2_DACBFUP(v) ((uint8_t)((uint8_t)(v) << BP_DAC_C2_DACBFUP) & BM_DAC_C2_DACBFUP) /*! @brief Set the DACBFUP field to a new value. */ #define BW_DAC_C2_DACBFUP(x, v) (HW_DAC_C2_WR(x, (HW_DAC_C2_RD(x) & ~BM_DAC_C2_DACBFUP) | BF_DAC_C2_DACBFUP(v))) /*@}*/ /*! * @name Register DAC_C2, field DACBFRP[7:4] (RW) * * Keeps the current value of the buffer read pointer. */ /*@{*/ #define BP_DAC_C2_DACBFRP (4U) /*!< Bit position for DAC_C2_DACBFRP. */ #define BM_DAC_C2_DACBFRP (0xF0U) /*!< Bit mask for DAC_C2_DACBFRP. */ #define BS_DAC_C2_DACBFRP (4U) /*!< Bit field size in bits for DAC_C2_DACBFRP. */ /*! @brief Read current value of the DAC_C2_DACBFRP field. */ #define BR_DAC_C2_DACBFRP(x) (HW_DAC_C2(x).B.DACBFRP) /*! @brief Format value for bitfield DAC_C2_DACBFRP. */ #define BF_DAC_C2_DACBFRP(v) ((uint8_t)((uint8_t)(v) << BP_DAC_C2_DACBFRP) & BM_DAC_C2_DACBFRP) /*! @brief Set the DACBFRP field to a new value. */ #define BW_DAC_C2_DACBFRP(x, v) (HW_DAC_C2_WR(x, (HW_DAC_C2_RD(x) & ~BM_DAC_C2_DACBFRP) | BF_DAC_C2_DACBFRP(v))) /*@}*/ /******************************************************************************* * hw_dac_t - module struct ******************************************************************************/ /*! * @brief All DAC module registers. */ #pragma pack(1) typedef struct _hw_dac { struct { __IO hw_dac_datnl_t DATnL; /*!< [0x0] DAC Data Low Register */ __IO hw_dac_datnh_t DATnH; /*!< [0x1] DAC Data High Register */ } DAT[16]; __IO hw_dac_sr_t SR; /*!< [0x20] DAC Status Register */ __IO hw_dac_c0_t C0; /*!< [0x21] DAC Control Register */ __IO hw_dac_c1_t C1; /*!< [0x22] DAC Control Register 1 */ __IO hw_dac_c2_t C2; /*!< [0x23] DAC Control Register 2 */ } hw_dac_t; #pragma pack() /*! @brief Macro to access all DAC registers. */ /*! @param x DAC module instance base address. */ /*! @return Reference (not a pointer) to the registers struct. To get a pointer to the struct, * use the '&' operator, like &HW_DAC(DAC0_BASE). */ #define HW_DAC(x) (*(hw_dac_t *)(x)) #endif /* __HW_DAC_REGISTERS_H__ */ /* EOF */ ================================================ FILE: Zelig/mbed/TARGET_K64F/TARGET_Freescale/TARGET_KPSDK_MCUS/TARGET_MCU_K64F/device/device/MK64F12/MK64F12_dma.h ================================================ /* ** ################################################################### ** Compilers: Keil ARM C/C++ Compiler ** Freescale C/C++ for Embedded ARM ** GNU C Compiler ** IAR ANSI C/C++ Compiler for ARM ** ** Reference manual: K64P144M120SF5RM, Rev.2, January 2014 ** Version: rev. 2.5, 2014-02-10 ** Build: b140604 ** ** Abstract: ** Extension to the CMSIS register access layer header. ** ** Copyright (c) 2014 Freescale Semiconductor, Inc. ** All rights reserved. ** ** Redistribution and use in source and binary forms, with or without modification, ** are permitted provided that the following conditions are met: ** ** o Redistributions of source code must retain the above copyright notice, this list ** of conditions and the following disclaimer. ** ** o Redistributions in binary form must reproduce the above copyright notice, this ** list of conditions and the following disclaimer in the documentation and/or ** other materials provided with the distribution. ** ** o Neither the name of Freescale Semiconductor, Inc. nor the names of its ** contributors may be used to endorse or promote products derived from this ** software without specific prior written permission. ** ** THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ** ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED ** WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE ** DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT 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. ** ** http: www.freescale.com ** mail: support@freescale.com ** ** Revisions: ** - rev. 1.0 (2013-08-12) ** Initial version. ** - rev. 2.0 (2013-10-29) ** Register accessor macros added to the memory map. ** Symbols for Processor Expert memory map compatibility added to the memory map. ** Startup file for gcc has been updated according to CMSIS 3.2. ** System initialization updated. ** MCG - registers updated. ** PORTA, PORTB, PORTC, PORTE - registers for digital filter removed. ** - rev. 2.1 (2013-10-30) ** Definition of BITBAND macros updated to support peripherals with 32-bit acces disabled. ** - rev. 2.2 (2013-12-09) ** DMA - EARS register removed. ** AIPS0, AIPS1 - MPRA register updated. ** - rev. 2.3 (2014-01-24) ** Update according to reference manual rev. 2 ** ENET, MCG, MCM, SIM, USB - registers updated ** - rev. 2.4 (2014-02-10) ** The declaration of clock configurations has been moved to separate header file system_MK64F12.h ** Update of SystemInit() and SystemCoreClockUpdate() functions. ** - rev. 2.5 (2014-02-10) ** The declaration of clock configurations has been moved to separate header file system_MK64F12.h ** Update of SystemInit() and SystemCoreClockUpdate() functions. ** Module access macro module_BASES replaced by module_BASE_PTRS. ** ** ################################################################### */ /* * WARNING! DO NOT EDIT THIS FILE DIRECTLY! * * This file was generated automatically and any changes may be lost. */ #ifndef __HW_DMA_REGISTERS_H__ #define __HW_DMA_REGISTERS_H__ #include "MK64F12.h" #include "fsl_bitaccess.h" /* * MK64F12 DMA * * Enhanced direct memory access controller * * Registers defined in this header file: * - HW_DMA_CR - Control Register * - HW_DMA_ES - Error Status Register * - HW_DMA_ERQ - Enable Request Register * - HW_DMA_EEI - Enable Error Interrupt Register * - HW_DMA_CEEI - Clear Enable Error Interrupt Register * - HW_DMA_SEEI - Set Enable Error Interrupt Register * - HW_DMA_CERQ - Clear Enable Request Register * - HW_DMA_SERQ - Set Enable Request Register * - HW_DMA_CDNE - Clear DONE Status Bit Register * - HW_DMA_SSRT - Set START Bit Register * - HW_DMA_CERR - Clear Error Register * - HW_DMA_CINT - Clear Interrupt Request Register * - HW_DMA_INT - Interrupt Request Register * - HW_DMA_ERR - Error Register * - HW_DMA_HRS - Hardware Request Status Register * - HW_DMA_DCHPRIn - Channel n Priority Register * - HW_DMA_TCDn_SADDR - TCD Source Address * - HW_DMA_TCDn_SOFF - TCD Signed Source Address Offset * - HW_DMA_TCDn_ATTR - TCD Transfer Attributes * - HW_DMA_TCDn_NBYTES_MLNO - TCD Minor Byte Count (Minor Loop Disabled) * - HW_DMA_TCDn_NBYTES_MLOFFNO - TCD Signed Minor Loop Offset (Minor Loop Enabled and Offset Disabled) * - HW_DMA_TCDn_NBYTES_MLOFFYES - TCD Signed Minor Loop Offset (Minor Loop and Offset Enabled) * - HW_DMA_TCDn_SLAST - TCD Last Source Address Adjustment * - HW_DMA_TCDn_DADDR - TCD Destination Address * - HW_DMA_TCDn_DOFF - TCD Signed Destination Address Offset * - HW_DMA_TCDn_CITER_ELINKNO - TCD Current Minor Loop Link, Major Loop Count (Channel Linking Disabled) * - HW_DMA_TCDn_CITER_ELINKYES - TCD Current Minor Loop Link, Major Loop Count (Channel Linking Enabled) * - HW_DMA_TCDn_DLASTSGA - TCD Last Destination Address Adjustment/Scatter Gather Address * - HW_DMA_TCDn_CSR - TCD Control and Status * - HW_DMA_TCDn_BITER_ELINKNO - TCD Beginning Minor Loop Link, Major Loop Count (Channel Linking Disabled) * - HW_DMA_TCDn_BITER_ELINKYES - TCD Beginning Minor Loop Link, Major Loop Count (Channel Linking Enabled) * * - hw_dma_t - Struct containing all module registers. */ #define HW_DMA_INSTANCE_COUNT (1U) /*!< Number of instances of the DMA module. */ /******************************************************************************* * HW_DMA_CR - Control Register ******************************************************************************/ /*! * @brief HW_DMA_CR - Control Register (RW) * * Reset value: 0x00000000U * * The CR defines the basic operating configuration of the DMA. Arbitration can * be configured to use either a fixed-priority or a round-robin scheme. For * fixed-priority arbitration, the highest priority channel requesting service is * selected to execute. The channel priority registers assign the priorities; see * the DCHPRIn registers. For round-robin arbitration, the channel priorities are * ignored and channels are cycled through (from high to low channel number) * without regard to priority. For correct operation, writes to the CR register must * be performed only when the DMA channels are inactive; that is, when * TCDn_CSR[ACTIVE] bits are cleared. Minor loop offsets are address offset values added to * the final source address (TCDn_SADDR) or destination address (TCDn_DADDR) upon * minor loop completion. When minor loop offsets are enabled, the minor loop * offset (MLOFF) is added to the final source address (TCDn_SADDR), to the final * destination address (TCDn_DADDR), or to both prior to the addresses being * written back into the TCD. If the major loop is complete, the minor loop offset is * ignored and the major loop address offsets (TCDn_SLAST and TCDn_DLAST_SGA) are * used to compute the next TCDn_SADDR and TCDn_DADDR values. When minor loop * mapping is enabled (EMLM is 1), TCDn word2 is redefined. A portion of TCDn word2 * is used to specify multiple fields: a source enable bit (SMLOE) to specify * the minor loop offset should be applied to the source address (TCDn_SADDR) upon * minor loop completion, a destination enable bit (DMLOE) to specify the minor * loop offset should be applied to the destination address (TCDn_DADDR) upon * minor loop completion, and the sign extended minor loop offset value (MLOFF). The * same offset value (MLOFF) is used for both source and destination minor loop * offsets. When either minor loop offset is enabled (SMLOE set or DMLOE set), the * NBYTES field is reduced to 10 bits. When both minor loop offsets are disabled * (SMLOE cleared and DMLOE cleared), the NBYTES field is a 30-bit vector. When * minor loop mapping is disabled (EMLM is 0), all 32 bits of TCDn word2 are * assigned to the NBYTES field. */ typedef union _hw_dma_cr { uint32_t U; struct _hw_dma_cr_bitfields { uint32_t RESERVED0 : 1; /*!< [0] Reserved. */ uint32_t EDBG : 1; /*!< [1] Enable Debug */ uint32_t ERCA : 1; /*!< [2] Enable Round Robin Channel Arbitration */ uint32_t RESERVED1 : 1; /*!< [3] Reserved. */ uint32_t HOE : 1; /*!< [4] Halt On Error */ uint32_t HALT : 1; /*!< [5] Halt DMA Operations */ uint32_t CLM : 1; /*!< [6] Continuous Link Mode */ uint32_t EMLM : 1; /*!< [7] Enable Minor Loop Mapping */ uint32_t RESERVED2 : 8; /*!< [15:8] */ uint32_t ECX : 1; /*!< [16] Error Cancel Transfer */ uint32_t CX : 1; /*!< [17] Cancel Transfer */ uint32_t RESERVED3 : 14; /*!< [31:18] */ } B; } hw_dma_cr_t; /*! * @name Constants and macros for entire DMA_CR register */ /*@{*/ #define HW_DMA_CR_ADDR(x) ((x) + 0x0U) #define HW_DMA_CR(x) (*(__IO hw_dma_cr_t *) HW_DMA_CR_ADDR(x)) #define HW_DMA_CR_RD(x) (HW_DMA_CR(x).U) #define HW_DMA_CR_WR(x, v) (HW_DMA_CR(x).U = (v)) #define HW_DMA_CR_SET(x, v) (HW_DMA_CR_WR(x, HW_DMA_CR_RD(x) | (v))) #define HW_DMA_CR_CLR(x, v) (HW_DMA_CR_WR(x, HW_DMA_CR_RD(x) & ~(v))) #define HW_DMA_CR_TOG(x, v) (HW_DMA_CR_WR(x, HW_DMA_CR_RD(x) ^ (v))) /*@}*/ /* * Constants & macros for individual DMA_CR bitfields */ /*! * @name Register DMA_CR, field EDBG[1] (RW) * * Values: * - 0 - When in debug mode, the DMA continues to operate. * - 1 - When in debug mode, the DMA stalls the start of a new channel. * Executing channels are allowed to complete. Channel execution resumes when the * system exits debug mode or the EDBG bit is cleared. */ /*@{*/ #define BP_DMA_CR_EDBG (1U) /*!< Bit position for DMA_CR_EDBG. */ #define BM_DMA_CR_EDBG (0x00000002U) /*!< Bit mask for DMA_CR_EDBG. */ #define BS_DMA_CR_EDBG (1U) /*!< Bit field size in bits for DMA_CR_EDBG. */ /*! @brief Read current value of the DMA_CR_EDBG field. */ #define BR_DMA_CR_EDBG(x) (BITBAND_ACCESS32(HW_DMA_CR_ADDR(x), BP_DMA_CR_EDBG)) /*! @brief Format value for bitfield DMA_CR_EDBG. */ #define BF_DMA_CR_EDBG(v) ((uint32_t)((uint32_t)(v) << BP_DMA_CR_EDBG) & BM_DMA_CR_EDBG) /*! @brief Set the EDBG field to a new value. */ #define BW_DMA_CR_EDBG(x, v) (BITBAND_ACCESS32(HW_DMA_CR_ADDR(x), BP_DMA_CR_EDBG) = (v)) /*@}*/ /*! * @name Register DMA_CR, field ERCA[2] (RW) * * Values: * - 0 - Fixed priority arbitration is used for channel selection . * - 1 - Round robin arbitration is used for channel selection . */ /*@{*/ #define BP_DMA_CR_ERCA (2U) /*!< Bit position for DMA_CR_ERCA. */ #define BM_DMA_CR_ERCA (0x00000004U) /*!< Bit mask for DMA_CR_ERCA. */ #define BS_DMA_CR_ERCA (1U) /*!< Bit field size in bits for DMA_CR_ERCA. */ /*! @brief Read current value of the DMA_CR_ERCA field. */ #define BR_DMA_CR_ERCA(x) (BITBAND_ACCESS32(HW_DMA_CR_ADDR(x), BP_DMA_CR_ERCA)) /*! @brief Format value for bitfield DMA_CR_ERCA. */ #define BF_DMA_CR_ERCA(v) ((uint32_t)((uint32_t)(v) << BP_DMA_CR_ERCA) & BM_DMA_CR_ERCA) /*! @brief Set the ERCA field to a new value. */ #define BW_DMA_CR_ERCA(x, v) (BITBAND_ACCESS32(HW_DMA_CR_ADDR(x), BP_DMA_CR_ERCA) = (v)) /*@}*/ /*! * @name Register DMA_CR, field HOE[4] (RW) * * Values: * - 0 - Normal operation * - 1 - Any error causes the HALT bit to set. Subsequently, all service * requests are ignored until the HALT bit is cleared. */ /*@{*/ #define BP_DMA_CR_HOE (4U) /*!< Bit position for DMA_CR_HOE. */ #define BM_DMA_CR_HOE (0x00000010U) /*!< Bit mask for DMA_CR_HOE. */ #define BS_DMA_CR_HOE (1U) /*!< Bit field size in bits for DMA_CR_HOE. */ /*! @brief Read current value of the DMA_CR_HOE field. */ #define BR_DMA_CR_HOE(x) (BITBAND_ACCESS32(HW_DMA_CR_ADDR(x), BP_DMA_CR_HOE)) /*! @brief Format value for bitfield DMA_CR_HOE. */ #define BF_DMA_CR_HOE(v) ((uint32_t)((uint32_t)(v) << BP_DMA_CR_HOE) & BM_DMA_CR_HOE) /*! @brief Set the HOE field to a new value. */ #define BW_DMA_CR_HOE(x, v) (BITBAND_ACCESS32(HW_DMA_CR_ADDR(x), BP_DMA_CR_HOE) = (v)) /*@}*/ /*! * @name Register DMA_CR, field HALT[5] (RW) * * Values: * - 0 - Normal operation * - 1 - Stall the start of any new channels. Executing channels are allowed to * complete. Channel execution resumes when this bit is cleared. */ /*@{*/ #define BP_DMA_CR_HALT (5U) /*!< Bit position for DMA_CR_HALT. */ #define BM_DMA_CR_HALT (0x00000020U) /*!< Bit mask for DMA_CR_HALT. */ #define BS_DMA_CR_HALT (1U) /*!< Bit field size in bits for DMA_CR_HALT. */ /*! @brief Read current value of the DMA_CR_HALT field. */ #define BR_DMA_CR_HALT(x) (BITBAND_ACCESS32(HW_DMA_CR_ADDR(x), BP_DMA_CR_HALT)) /*! @brief Format value for bitfield DMA_CR_HALT. */ #define BF_DMA_CR_HALT(v) ((uint32_t)((uint32_t)(v) << BP_DMA_CR_HALT) & BM_DMA_CR_HALT) /*! @brief Set the HALT field to a new value. */ #define BW_DMA_CR_HALT(x, v) (BITBAND_ACCESS32(HW_DMA_CR_ADDR(x), BP_DMA_CR_HALT) = (v)) /*@}*/ /*! * @name Register DMA_CR, field CLM[6] (RW) * * Values: * - 0 - A minor loop channel link made to itself goes through channel * arbitration before being activated again. * - 1 - A minor loop channel link made to itself does not go through channel * arbitration before being activated again. Upon minor loop completion, the * channel activates again if that channel has a minor loop channel link * enabled and the link channel is itself. This effectively applies the minor loop * offsets and restarts the next minor loop. */ /*@{*/ #define BP_DMA_CR_CLM (6U) /*!< Bit position for DMA_CR_CLM. */ #define BM_DMA_CR_CLM (0x00000040U) /*!< Bit mask for DMA_CR_CLM. */ #define BS_DMA_CR_CLM (1U) /*!< Bit field size in bits for DMA_CR_CLM. */ /*! @brief Read current value of the DMA_CR_CLM field. */ #define BR_DMA_CR_CLM(x) (BITBAND_ACCESS32(HW_DMA_CR_ADDR(x), BP_DMA_CR_CLM)) /*! @brief Format value for bitfield DMA_CR_CLM. */ #define BF_DMA_CR_CLM(v) ((uint32_t)((uint32_t)(v) << BP_DMA_CR_CLM) & BM_DMA_CR_CLM) /*! @brief Set the CLM field to a new value. */ #define BW_DMA_CR_CLM(x, v) (BITBAND_ACCESS32(HW_DMA_CR_ADDR(x), BP_DMA_CR_CLM) = (v)) /*@}*/ /*! * @name Register DMA_CR, field EMLM[7] (RW) * * Values: * - 0 - Disabled. TCDn.word2 is defined as a 32-bit NBYTES field. * - 1 - Enabled. TCDn.word2 is redefined to include individual enable fields, * an offset field, and the NBYTES field. The individual enable fields allow * the minor loop offset to be applied to the source address, the destination * address, or both. The NBYTES field is reduced when either offset is * enabled. */ /*@{*/ #define BP_DMA_CR_EMLM (7U) /*!< Bit position for DMA_CR_EMLM. */ #define BM_DMA_CR_EMLM (0x00000080U) /*!< Bit mask for DMA_CR_EMLM. */ #define BS_DMA_CR_EMLM (1U) /*!< Bit field size in bits for DMA_CR_EMLM. */ /*! @brief Read current value of the DMA_CR_EMLM field. */ #define BR_DMA_CR_EMLM(x) (BITBAND_ACCESS32(HW_DMA_CR_ADDR(x), BP_DMA_CR_EMLM)) /*! @brief Format value for bitfield DMA_CR_EMLM. */ #define BF_DMA_CR_EMLM(v) ((uint32_t)((uint32_t)(v) << BP_DMA_CR_EMLM) & BM_DMA_CR_EMLM) /*! @brief Set the EMLM field to a new value. */ #define BW_DMA_CR_EMLM(x, v) (BITBAND_ACCESS32(HW_DMA_CR_ADDR(x), BP_DMA_CR_EMLM) = (v)) /*@}*/ /*! * @name Register DMA_CR, field ECX[16] (RW) * * Values: * - 0 - Normal operation * - 1 - Cancel the remaining data transfer in the same fashion as the CX bit. * Stop the executing channel and force the minor loop to finish. The cancel * takes effect after the last write of the current read/write sequence. The * ECX bit clears itself after the cancel is honored. In addition to * cancelling the transfer, ECX treats the cancel as an error condition, thus updating * the Error Status register (DMAx_ES) and generating an optional error * interrupt. */ /*@{*/ #define BP_DMA_CR_ECX (16U) /*!< Bit position for DMA_CR_ECX. */ #define BM_DMA_CR_ECX (0x00010000U) /*!< Bit mask for DMA_CR_ECX. */ #define BS_DMA_CR_ECX (1U) /*!< Bit field size in bits for DMA_CR_ECX. */ /*! @brief Read current value of the DMA_CR_ECX field. */ #define BR_DMA_CR_ECX(x) (BITBAND_ACCESS32(HW_DMA_CR_ADDR(x), BP_DMA_CR_ECX)) /*! @brief Format value for bitfield DMA_CR_ECX. */ #define BF_DMA_CR_ECX(v) ((uint32_t)((uint32_t)(v) << BP_DMA_CR_ECX) & BM_DMA_CR_ECX) /*! @brief Set the ECX field to a new value. */ #define BW_DMA_CR_ECX(x, v) (BITBAND_ACCESS32(HW_DMA_CR_ADDR(x), BP_DMA_CR_ECX) = (v)) /*@}*/ /*! * @name Register DMA_CR, field CX[17] (RW) * * Values: * - 0 - Normal operation * - 1 - Cancel the remaining data transfer. Stop the executing channel and * force the minor loop to finish. The cancel takes effect after the last write * of the current read/write sequence. The CX bit clears itself after the * cancel has been honored. This cancel retires the channel normally as if the * minor loop was completed. */ /*@{*/ #define BP_DMA_CR_CX (17U) /*!< Bit position for DMA_CR_CX. */ #define BM_DMA_CR_CX (0x00020000U) /*!< Bit mask for DMA_CR_CX. */ #define BS_DMA_CR_CX (1U) /*!< Bit field size in bits for DMA_CR_CX. */ /*! @brief Read current value of the DMA_CR_CX field. */ #define BR_DMA_CR_CX(x) (BITBAND_ACCESS32(HW_DMA_CR_ADDR(x), BP_DMA_CR_CX)) /*! @brief Format value for bitfield DMA_CR_CX. */ #define BF_DMA_CR_CX(v) ((uint32_t)((uint32_t)(v) << BP_DMA_CR_CX) & BM_DMA_CR_CX) /*! @brief Set the CX field to a new value. */ #define BW_DMA_CR_CX(x, v) (BITBAND_ACCESS32(HW_DMA_CR_ADDR(x), BP_DMA_CR_CX) = (v)) /*@}*/ /******************************************************************************* * HW_DMA_ES - Error Status Register ******************************************************************************/ /*! * @brief HW_DMA_ES - Error Status Register (RO) * * Reset value: 0x00000000U * * The ES provides information concerning the last recorded channel error. * Channel errors can be caused by: A configuration error, that is: An illegal setting * in the transfer-control descriptor, or An illegal priority register setting * in fixed-arbitration An error termination to a bus master read or write cycle * See the Error Reporting and Handling section for more details. */ typedef union _hw_dma_es { uint32_t U; struct _hw_dma_es_bitfields { uint32_t DBE : 1; /*!< [0] Destination Bus Error */ uint32_t SBE : 1; /*!< [1] Source Bus Error */ uint32_t SGE : 1; /*!< [2] Scatter/Gather Configuration Error */ uint32_t NCE : 1; /*!< [3] NBYTES/CITER Configuration Error */ uint32_t DOE : 1; /*!< [4] Destination Offset Error */ uint32_t DAE : 1; /*!< [5] Destination Address Error */ uint32_t SOE : 1; /*!< [6] Source Offset Error */ uint32_t SAE : 1; /*!< [7] Source Address Error */ uint32_t ERRCHN : 4; /*!< [11:8] Error Channel Number or Canceled * Channel Number */ uint32_t RESERVED0 : 2; /*!< [13:12] */ uint32_t CPE : 1; /*!< [14] Channel Priority Error */ uint32_t RESERVED1 : 1; /*!< [15] */ uint32_t ECX : 1; /*!< [16] Transfer Canceled */ uint32_t RESERVED2 : 14; /*!< [30:17] */ uint32_t VLD : 1; /*!< [31] */ } B; } hw_dma_es_t; /*! * @name Constants and macros for entire DMA_ES register */ /*@{*/ #define HW_DMA_ES_ADDR(x) ((x) + 0x4U) #define HW_DMA_ES(x) (*(__I hw_dma_es_t *) HW_DMA_ES_ADDR(x)) #define HW_DMA_ES_RD(x) (HW_DMA_ES(x).U) /*@}*/ /* * Constants & macros for individual DMA_ES bitfields */ /*! * @name Register DMA_ES, field DBE[0] (RO) * * Values: * - 0 - No destination bus error * - 1 - The last recorded error was a bus error on a destination write */ /*@{*/ #define BP_DMA_ES_DBE (0U) /*!< Bit position for DMA_ES_DBE. */ #define BM_DMA_ES_DBE (0x00000001U) /*!< Bit mask for DMA_ES_DBE. */ #define BS_DMA_ES_DBE (1U) /*!< Bit field size in bits for DMA_ES_DBE. */ /*! @brief Read current value of the DMA_ES_DBE field. */ #define BR_DMA_ES_DBE(x) (BITBAND_ACCESS32(HW_DMA_ES_ADDR(x), BP_DMA_ES_DBE)) /*@}*/ /*! * @name Register DMA_ES, field SBE[1] (RO) * * Values: * - 0 - No source bus error * - 1 - The last recorded error was a bus error on a source read */ /*@{*/ #define BP_DMA_ES_SBE (1U) /*!< Bit position for DMA_ES_SBE. */ #define BM_DMA_ES_SBE (0x00000002U) /*!< Bit mask for DMA_ES_SBE. */ #define BS_DMA_ES_SBE (1U) /*!< Bit field size in bits for DMA_ES_SBE. */ /*! @brief Read current value of the DMA_ES_SBE field. */ #define BR_DMA_ES_SBE(x) (BITBAND_ACCESS32(HW_DMA_ES_ADDR(x), BP_DMA_ES_SBE)) /*@}*/ /*! * @name Register DMA_ES, field SGE[2] (RO) * * Values: * - 0 - No scatter/gather configuration error * - 1 - The last recorded error was a configuration error detected in the * TCDn_DLASTSGA field. This field is checked at the beginning of a scatter/gather * operation after major loop completion if TCDn_CSR[ESG] is enabled. * TCDn_DLASTSGA is not on a 32 byte boundary. */ /*@{*/ #define BP_DMA_ES_SGE (2U) /*!< Bit position for DMA_ES_SGE. */ #define BM_DMA_ES_SGE (0x00000004U) /*!< Bit mask for DMA_ES_SGE. */ #define BS_DMA_ES_SGE (1U) /*!< Bit field size in bits for DMA_ES_SGE. */ /*! @brief Read current value of the DMA_ES_SGE field. */ #define BR_DMA_ES_SGE(x) (BITBAND_ACCESS32(HW_DMA_ES_ADDR(x), BP_DMA_ES_SGE)) /*@}*/ /*! * @name Register DMA_ES, field NCE[3] (RO) * * Values: * - 0 - No NBYTES/CITER configuration error * - 1 - The last recorded error was a configuration error detected in the * TCDn_NBYTES or TCDn_CITER fields. TCDn_NBYTES is not a multiple of * TCDn_ATTR[SSIZE] and TCDn_ATTR[DSIZE], or TCDn_CITER[CITER] is equal to zero, or * TCDn_CITER[ELINK] is not equal to TCDn_BITER[ELINK] */ /*@{*/ #define BP_DMA_ES_NCE (3U) /*!< Bit position for DMA_ES_NCE. */ #define BM_DMA_ES_NCE (0x00000008U) /*!< Bit mask for DMA_ES_NCE. */ #define BS_DMA_ES_NCE (1U) /*!< Bit field size in bits for DMA_ES_NCE. */ /*! @brief Read current value of the DMA_ES_NCE field. */ #define BR_DMA_ES_NCE(x) (BITBAND_ACCESS32(HW_DMA_ES_ADDR(x), BP_DMA_ES_NCE)) /*@}*/ /*! * @name Register DMA_ES, field DOE[4] (RO) * * Values: * - 0 - No destination offset configuration error * - 1 - The last recorded error was a configuration error detected in the * TCDn_DOFF field. TCDn_DOFF is inconsistent with TCDn_ATTR[DSIZE]. */ /*@{*/ #define BP_DMA_ES_DOE (4U) /*!< Bit position for DMA_ES_DOE. */ #define BM_DMA_ES_DOE (0x00000010U) /*!< Bit mask for DMA_ES_DOE. */ #define BS_DMA_ES_DOE (1U) /*!< Bit field size in bits for DMA_ES_DOE. */ /*! @brief Read current value of the DMA_ES_DOE field. */ #define BR_DMA_ES_DOE(x) (BITBAND_ACCESS32(HW_DMA_ES_ADDR(x), BP_DMA_ES_DOE)) /*@}*/ /*! * @name Register DMA_ES, field DAE[5] (RO) * * Values: * - 0 - No destination address configuration error * - 1 - The last recorded error was a configuration error detected in the * TCDn_DADDR field. TCDn_DADDR is inconsistent with TCDn_ATTR[DSIZE]. */ /*@{*/ #define BP_DMA_ES_DAE (5U) /*!< Bit position for DMA_ES_DAE. */ #define BM_DMA_ES_DAE (0x00000020U) /*!< Bit mask for DMA_ES_DAE. */ #define BS_DMA_ES_DAE (1U) /*!< Bit field size in bits for DMA_ES_DAE. */ /*! @brief Read current value of the DMA_ES_DAE field. */ #define BR_DMA_ES_DAE(x) (BITBAND_ACCESS32(HW_DMA_ES_ADDR(x), BP_DMA_ES_DAE)) /*@}*/ /*! * @name Register DMA_ES, field SOE[6] (RO) * * Values: * - 0 - No source offset configuration error * - 1 - The last recorded error was a configuration error detected in the * TCDn_SOFF field. TCDn_SOFF is inconsistent with TCDn_ATTR[SSIZE]. */ /*@{*/ #define BP_DMA_ES_SOE (6U) /*!< Bit position for DMA_ES_SOE. */ #define BM_DMA_ES_SOE (0x00000040U) /*!< Bit mask for DMA_ES_SOE. */ #define BS_DMA_ES_SOE (1U) /*!< Bit field size in bits for DMA_ES_SOE. */ /*! @brief Read current value of the DMA_ES_SOE field. */ #define BR_DMA_ES_SOE(x) (BITBAND_ACCESS32(HW_DMA_ES_ADDR(x), BP_DMA_ES_SOE)) /*@}*/ /*! * @name Register DMA_ES, field SAE[7] (RO) * * Values: * - 0 - No source address configuration error. * - 1 - The last recorded error was a configuration error detected in the * TCDn_SADDR field. TCDn_SADDR is inconsistent with TCDn_ATTR[SSIZE]. */ /*@{*/ #define BP_DMA_ES_SAE (7U) /*!< Bit position for DMA_ES_SAE. */ #define BM_DMA_ES_SAE (0x00000080U) /*!< Bit mask for DMA_ES_SAE. */ #define BS_DMA_ES_SAE (1U) /*!< Bit field size in bits for DMA_ES_SAE. */ /*! @brief Read current value of the DMA_ES_SAE field. */ #define BR_DMA_ES_SAE(x) (BITBAND_ACCESS32(HW_DMA_ES_ADDR(x), BP_DMA_ES_SAE)) /*@}*/ /*! * @name Register DMA_ES, field ERRCHN[11:8] (RO) * * The channel number of the last recorded error (excluding CPE errors) or last * recorded error canceled transfer. */ /*@{*/ #define BP_DMA_ES_ERRCHN (8U) /*!< Bit position for DMA_ES_ERRCHN. */ #define BM_DMA_ES_ERRCHN (0x00000F00U) /*!< Bit mask for DMA_ES_ERRCHN. */ #define BS_DMA_ES_ERRCHN (4U) /*!< Bit field size in bits for DMA_ES_ERRCHN. */ /*! @brief Read current value of the DMA_ES_ERRCHN field. */ #define BR_DMA_ES_ERRCHN(x) (HW_DMA_ES(x).B.ERRCHN) /*@}*/ /*! * @name Register DMA_ES, field CPE[14] (RO) * * Values: * - 0 - No channel priority error * - 1 - The last recorded error was a configuration error in the channel * priorities . Channel priorities are not unique. */ /*@{*/ #define BP_DMA_ES_CPE (14U) /*!< Bit position for DMA_ES_CPE. */ #define BM_DMA_ES_CPE (0x00004000U) /*!< Bit mask for DMA_ES_CPE. */ #define BS_DMA_ES_CPE (1U) /*!< Bit field size in bits for DMA_ES_CPE. */ /*! @brief Read current value of the DMA_ES_CPE field. */ #define BR_DMA_ES_CPE(x) (BITBAND_ACCESS32(HW_DMA_ES_ADDR(x), BP_DMA_ES_CPE)) /*@}*/ /*! * @name Register DMA_ES, field ECX[16] (RO) * * Values: * - 0 - No canceled transfers * - 1 - The last recorded entry was a canceled transfer by the error cancel * transfer input */ /*@{*/ #define BP_DMA_ES_ECX (16U) /*!< Bit position for DMA_ES_ECX. */ #define BM_DMA_ES_ECX (0x00010000U) /*!< Bit mask for DMA_ES_ECX. */ #define BS_DMA_ES_ECX (1U) /*!< Bit field size in bits for DMA_ES_ECX. */ /*! @brief Read current value of the DMA_ES_ECX field. */ #define BR_DMA_ES_ECX(x) (BITBAND_ACCESS32(HW_DMA_ES_ADDR(x), BP_DMA_ES_ECX)) /*@}*/ /*! * @name Register DMA_ES, field VLD[31] (RO) * * Logical OR of all ERR status bits * * Values: * - 0 - No ERR bits are set * - 1 - At least one ERR bit is set indicating a valid error exists that has * not been cleared */ /*@{*/ #define BP_DMA_ES_VLD (31U) /*!< Bit position for DMA_ES_VLD. */ #define BM_DMA_ES_VLD (0x80000000U) /*!< Bit mask for DMA_ES_VLD. */ #define BS_DMA_ES_VLD (1U) /*!< Bit field size in bits for DMA_ES_VLD. */ /*! @brief Read current value of the DMA_ES_VLD field. */ #define BR_DMA_ES_VLD(x) (BITBAND_ACCESS32(HW_DMA_ES_ADDR(x), BP_DMA_ES_VLD)) /*@}*/ /******************************************************************************* * HW_DMA_ERQ - Enable Request Register ******************************************************************************/ /*! * @brief HW_DMA_ERQ - Enable Request Register (RW) * * Reset value: 0x00000000U * * The ERQ register provides a bit map for the 16 implemented channels to enable * the request signal for each channel. The state of any given channel enable is * directly affected by writes to this register; it is also affected by writes * to the SERQ and CERQ. The {S,C}ERQ registers are provided so the request enable * for a single channel can easily be modified without needing to perform a * read-modify-write sequence to the ERQ. DMA request input signals and this enable * request flag must be asserted before a channel's hardware service request is * accepted. The state of the DMA enable request flag does not affect a channel * service request made explicitly through software or a linked channel request. */ typedef union _hw_dma_erq { uint32_t U; struct _hw_dma_erq_bitfields { uint32_t ERQ0 : 1; /*!< [0] Enable DMA Request 0 */ uint32_t ERQ1 : 1; /*!< [1] Enable DMA Request 1 */ uint32_t ERQ2 : 1; /*!< [2] Enable DMA Request 2 */ uint32_t ERQ3 : 1; /*!< [3] Enable DMA Request 3 */ uint32_t ERQ4 : 1; /*!< [4] Enable DMA Request 4 */ uint32_t ERQ5 : 1; /*!< [5] Enable DMA Request 5 */ uint32_t ERQ6 : 1; /*!< [6] Enable DMA Request 6 */ uint32_t ERQ7 : 1; /*!< [7] Enable DMA Request 7 */ uint32_t ERQ8 : 1; /*!< [8] Enable DMA Request 8 */ uint32_t ERQ9 : 1; /*!< [9] Enable DMA Request 9 */ uint32_t ERQ10 : 1; /*!< [10] Enable DMA Request 10 */ uint32_t ERQ11 : 1; /*!< [11] Enable DMA Request 11 */ uint32_t ERQ12 : 1; /*!< [12] Enable DMA Request 12 */ uint32_t ERQ13 : 1; /*!< [13] Enable DMA Request 13 */ uint32_t ERQ14 : 1; /*!< [14] Enable DMA Request 14 */ uint32_t ERQ15 : 1; /*!< [15] Enable DMA Request 15 */ uint32_t RESERVED0 : 16; /*!< [31:16] */ } B; } hw_dma_erq_t; /*! * @name Constants and macros for entire DMA_ERQ register */ /*@{*/ #define HW_DMA_ERQ_ADDR(x) ((x) + 0xCU) #define HW_DMA_ERQ(x) (*(__IO hw_dma_erq_t *) HW_DMA_ERQ_ADDR(x)) #define HW_DMA_ERQ_RD(x) (HW_DMA_ERQ(x).U) #define HW_DMA_ERQ_WR(x, v) (HW_DMA_ERQ(x).U = (v)) #define HW_DMA_ERQ_SET(x, v) (HW_DMA_ERQ_WR(x, HW_DMA_ERQ_RD(x) | (v))) #define HW_DMA_ERQ_CLR(x, v) (HW_DMA_ERQ_WR(x, HW_DMA_ERQ_RD(x) & ~(v))) #define HW_DMA_ERQ_TOG(x, v) (HW_DMA_ERQ_WR(x, HW_DMA_ERQ_RD(x) ^ (v))) /*@}*/ /* * Constants & macros for individual DMA_ERQ bitfields */ /*! * @name Register DMA_ERQ, field ERQ0[0] (RW) * * Values: * - 0 - The DMA request signal for the corresponding channel is disabled * - 1 - The DMA request signal for the corresponding channel is enabled */ /*@{*/ #define BP_DMA_ERQ_ERQ0 (0U) /*!< Bit position for DMA_ERQ_ERQ0. */ #define BM_DMA_ERQ_ERQ0 (0x00000001U) /*!< Bit mask for DMA_ERQ_ERQ0. */ #define BS_DMA_ERQ_ERQ0 (1U) /*!< Bit field size in bits for DMA_ERQ_ERQ0. */ /*! @brief Read current value of the DMA_ERQ_ERQ0 field. */ #define BR_DMA_ERQ_ERQ0(x) (BITBAND_ACCESS32(HW_DMA_ERQ_ADDR(x), BP_DMA_ERQ_ERQ0)) /*! @brief Format value for bitfield DMA_ERQ_ERQ0. */ #define BF_DMA_ERQ_ERQ0(v) ((uint32_t)((uint32_t)(v) << BP_DMA_ERQ_ERQ0) & BM_DMA_ERQ_ERQ0) /*! @brief Set the ERQ0 field to a new value. */ #define BW_DMA_ERQ_ERQ0(x, v) (BITBAND_ACCESS32(HW_DMA_ERQ_ADDR(x), BP_DMA_ERQ_ERQ0) = (v)) /*@}*/ /*! * @name Register DMA_ERQ, field ERQ1[1] (RW) * * Values: * - 0 - The DMA request signal for the corresponding channel is disabled * - 1 - The DMA request signal for the corresponding channel is enabled */ /*@{*/ #define BP_DMA_ERQ_ERQ1 (1U) /*!< Bit position for DMA_ERQ_ERQ1. */ #define BM_DMA_ERQ_ERQ1 (0x00000002U) /*!< Bit mask for DMA_ERQ_ERQ1. */ #define BS_DMA_ERQ_ERQ1 (1U) /*!< Bit field size in bits for DMA_ERQ_ERQ1. */ /*! @brief Read current value of the DMA_ERQ_ERQ1 field. */ #define BR_DMA_ERQ_ERQ1(x) (BITBAND_ACCESS32(HW_DMA_ERQ_ADDR(x), BP_DMA_ERQ_ERQ1)) /*! @brief Format value for bitfield DMA_ERQ_ERQ1. */ #define BF_DMA_ERQ_ERQ1(v) ((uint32_t)((uint32_t)(v) << BP_DMA_ERQ_ERQ1) & BM_DMA_ERQ_ERQ1) /*! @brief Set the ERQ1 field to a new value. */ #define BW_DMA_ERQ_ERQ1(x, v) (BITBAND_ACCESS32(HW_DMA_ERQ_ADDR(x), BP_DMA_ERQ_ERQ1) = (v)) /*@}*/ /*! * @name Register DMA_ERQ, field ERQ2[2] (RW) * * Values: * - 0 - The DMA request signal for the corresponding channel is disabled * - 1 - The DMA request signal for the corresponding channel is enabled */ /*@{*/ #define BP_DMA_ERQ_ERQ2 (2U) /*!< Bit position for DMA_ERQ_ERQ2. */ #define BM_DMA_ERQ_ERQ2 (0x00000004U) /*!< Bit mask for DMA_ERQ_ERQ2. */ #define BS_DMA_ERQ_ERQ2 (1U) /*!< Bit field size in bits for DMA_ERQ_ERQ2. */ /*! @brief Read current value of the DMA_ERQ_ERQ2 field. */ #define BR_DMA_ERQ_ERQ2(x) (BITBAND_ACCESS32(HW_DMA_ERQ_ADDR(x), BP_DMA_ERQ_ERQ2)) /*! @brief Format value for bitfield DMA_ERQ_ERQ2. */ #define BF_DMA_ERQ_ERQ2(v) ((uint32_t)((uint32_t)(v) << BP_DMA_ERQ_ERQ2) & BM_DMA_ERQ_ERQ2) /*! @brief Set the ERQ2 field to a new value. */ #define BW_DMA_ERQ_ERQ2(x, v) (BITBAND_ACCESS32(HW_DMA_ERQ_ADDR(x), BP_DMA_ERQ_ERQ2) = (v)) /*@}*/ /*! * @name Register DMA_ERQ, field ERQ3[3] (RW) * * Values: * - 0 - The DMA request signal for the corresponding channel is disabled * - 1 - The DMA request signal for the corresponding channel is enabled */ /*@{*/ #define BP_DMA_ERQ_ERQ3 (3U) /*!< Bit position for DMA_ERQ_ERQ3. */ #define BM_DMA_ERQ_ERQ3 (0x00000008U) /*!< Bit mask for DMA_ERQ_ERQ3. */ #define BS_DMA_ERQ_ERQ3 (1U) /*!< Bit field size in bits for DMA_ERQ_ERQ3. */ /*! @brief Read current value of the DMA_ERQ_ERQ3 field. */ #define BR_DMA_ERQ_ERQ3(x) (BITBAND_ACCESS32(HW_DMA_ERQ_ADDR(x), BP_DMA_ERQ_ERQ3)) /*! @brief Format value for bitfield DMA_ERQ_ERQ3. */ #define BF_DMA_ERQ_ERQ3(v) ((uint32_t)((uint32_t)(v) << BP_DMA_ERQ_ERQ3) & BM_DMA_ERQ_ERQ3) /*! @brief Set the ERQ3 field to a new value. */ #define BW_DMA_ERQ_ERQ3(x, v) (BITBAND_ACCESS32(HW_DMA_ERQ_ADDR(x), BP_DMA_ERQ_ERQ3) = (v)) /*@}*/ /*! * @name Register DMA_ERQ, field ERQ4[4] (RW) * * Values: * - 0 - The DMA request signal for the corresponding channel is disabled * - 1 - The DMA request signal for the corresponding channel is enabled */ /*@{*/ #define BP_DMA_ERQ_ERQ4 (4U) /*!< Bit position for DMA_ERQ_ERQ4. */ #define BM_DMA_ERQ_ERQ4 (0x00000010U) /*!< Bit mask for DMA_ERQ_ERQ4. */ #define BS_DMA_ERQ_ERQ4 (1U) /*!< Bit field size in bits for DMA_ERQ_ERQ4. */ /*! @brief Read current value of the DMA_ERQ_ERQ4 field. */ #define BR_DMA_ERQ_ERQ4(x) (BITBAND_ACCESS32(HW_DMA_ERQ_ADDR(x), BP_DMA_ERQ_ERQ4)) /*! @brief Format value for bitfield DMA_ERQ_ERQ4. */ #define BF_DMA_ERQ_ERQ4(v) ((uint32_t)((uint32_t)(v) << BP_DMA_ERQ_ERQ4) & BM_DMA_ERQ_ERQ4) /*! @brief Set the ERQ4 field to a new value. */ #define BW_DMA_ERQ_ERQ4(x, v) (BITBAND_ACCESS32(HW_DMA_ERQ_ADDR(x), BP_DMA_ERQ_ERQ4) = (v)) /*@}*/ /*! * @name Register DMA_ERQ, field ERQ5[5] (RW) * * Values: * - 0 - The DMA request signal for the corresponding channel is disabled * - 1 - The DMA request signal for the corresponding channel is enabled */ /*@{*/ #define BP_DMA_ERQ_ERQ5 (5U) /*!< Bit position for DMA_ERQ_ERQ5. */ #define BM_DMA_ERQ_ERQ5 (0x00000020U) /*!< Bit mask for DMA_ERQ_ERQ5. */ #define BS_DMA_ERQ_ERQ5 (1U) /*!< Bit field size in bits for DMA_ERQ_ERQ5. */ /*! @brief Read current value of the DMA_ERQ_ERQ5 field. */ #define BR_DMA_ERQ_ERQ5(x) (BITBAND_ACCESS32(HW_DMA_ERQ_ADDR(x), BP_DMA_ERQ_ERQ5)) /*! @brief Format value for bitfield DMA_ERQ_ERQ5. */ #define BF_DMA_ERQ_ERQ5(v) ((uint32_t)((uint32_t)(v) << BP_DMA_ERQ_ERQ5) & BM_DMA_ERQ_ERQ5) /*! @brief Set the ERQ5 field to a new value. */ #define BW_DMA_ERQ_ERQ5(x, v) (BITBAND_ACCESS32(HW_DMA_ERQ_ADDR(x), BP_DMA_ERQ_ERQ5) = (v)) /*@}*/ /*! * @name Register DMA_ERQ, field ERQ6[6] (RW) * * Values: * - 0 - The DMA request signal for the corresponding channel is disabled * - 1 - The DMA request signal for the corresponding channel is enabled */ /*@{*/ #define BP_DMA_ERQ_ERQ6 (6U) /*!< Bit position for DMA_ERQ_ERQ6. */ #define BM_DMA_ERQ_ERQ6 (0x00000040U) /*!< Bit mask for DMA_ERQ_ERQ6. */ #define BS_DMA_ERQ_ERQ6 (1U) /*!< Bit field size in bits for DMA_ERQ_ERQ6. */ /*! @brief Read current value of the DMA_ERQ_ERQ6 field. */ #define BR_DMA_ERQ_ERQ6(x) (BITBAND_ACCESS32(HW_DMA_ERQ_ADDR(x), BP_DMA_ERQ_ERQ6)) /*! @brief Format value for bitfield DMA_ERQ_ERQ6. */ #define BF_DMA_ERQ_ERQ6(v) ((uint32_t)((uint32_t)(v) << BP_DMA_ERQ_ERQ6) & BM_DMA_ERQ_ERQ6) /*! @brief Set the ERQ6 field to a new value. */ #define BW_DMA_ERQ_ERQ6(x, v) (BITBAND_ACCESS32(HW_DMA_ERQ_ADDR(x), BP_DMA_ERQ_ERQ6) = (v)) /*@}*/ /*! * @name Register DMA_ERQ, field ERQ7[7] (RW) * * Values: * - 0 - The DMA request signal for the corresponding channel is disabled * - 1 - The DMA request signal for the corresponding channel is enabled */ /*@{*/ #define BP_DMA_ERQ_ERQ7 (7U) /*!< Bit position for DMA_ERQ_ERQ7. */ #define BM_DMA_ERQ_ERQ7 (0x00000080U) /*!< Bit mask for DMA_ERQ_ERQ7. */ #define BS_DMA_ERQ_ERQ7 (1U) /*!< Bit field size in bits for DMA_ERQ_ERQ7. */ /*! @brief Read current value of the DMA_ERQ_ERQ7 field. */ #define BR_DMA_ERQ_ERQ7(x) (BITBAND_ACCESS32(HW_DMA_ERQ_ADDR(x), BP_DMA_ERQ_ERQ7)) /*! @brief Format value for bitfield DMA_ERQ_ERQ7. */ #define BF_DMA_ERQ_ERQ7(v) ((uint32_t)((uint32_t)(v) << BP_DMA_ERQ_ERQ7) & BM_DMA_ERQ_ERQ7) /*! @brief Set the ERQ7 field to a new value. */ #define BW_DMA_ERQ_ERQ7(x, v) (BITBAND_ACCESS32(HW_DMA_ERQ_ADDR(x), BP_DMA_ERQ_ERQ7) = (v)) /*@}*/ /*! * @name Register DMA_ERQ, field ERQ8[8] (RW) * * Values: * - 0 - The DMA request signal for the corresponding channel is disabled * - 1 - The DMA request signal for the corresponding channel is enabled */ /*@{*/ #define BP_DMA_ERQ_ERQ8 (8U) /*!< Bit position for DMA_ERQ_ERQ8. */ #define BM_DMA_ERQ_ERQ8 (0x00000100U) /*!< Bit mask for DMA_ERQ_ERQ8. */ #define BS_DMA_ERQ_ERQ8 (1U) /*!< Bit field size in bits for DMA_ERQ_ERQ8. */ /*! @brief Read current value of the DMA_ERQ_ERQ8 field. */ #define BR_DMA_ERQ_ERQ8(x) (BITBAND_ACCESS32(HW_DMA_ERQ_ADDR(x), BP_DMA_ERQ_ERQ8)) /*! @brief Format value for bitfield DMA_ERQ_ERQ8. */ #define BF_DMA_ERQ_ERQ8(v) ((uint32_t)((uint32_t)(v) << BP_DMA_ERQ_ERQ8) & BM_DMA_ERQ_ERQ8) /*! @brief Set the ERQ8 field to a new value. */ #define BW_DMA_ERQ_ERQ8(x, v) (BITBAND_ACCESS32(HW_DMA_ERQ_ADDR(x), BP_DMA_ERQ_ERQ8) = (v)) /*@}*/ /*! * @name Register DMA_ERQ, field ERQ9[9] (RW) * * Values: * - 0 - The DMA request signal for the corresponding channel is disabled * - 1 - The DMA request signal for the corresponding channel is enabled */ /*@{*/ #define BP_DMA_ERQ_ERQ9 (9U) /*!< Bit position for DMA_ERQ_ERQ9. */ #define BM_DMA_ERQ_ERQ9 (0x00000200U) /*!< Bit mask for DMA_ERQ_ERQ9. */ #define BS_DMA_ERQ_ERQ9 (1U) /*!< Bit field size in bits for DMA_ERQ_ERQ9. */ /*! @brief Read current value of the DMA_ERQ_ERQ9 field. */ #define BR_DMA_ERQ_ERQ9(x) (BITBAND_ACCESS32(HW_DMA_ERQ_ADDR(x), BP_DMA_ERQ_ERQ9)) /*! @brief Format value for bitfield DMA_ERQ_ERQ9. */ #define BF_DMA_ERQ_ERQ9(v) ((uint32_t)((uint32_t)(v) << BP_DMA_ERQ_ERQ9) & BM_DMA_ERQ_ERQ9) /*! @brief Set the ERQ9 field to a new value. */ #define BW_DMA_ERQ_ERQ9(x, v) (BITBAND_ACCESS32(HW_DMA_ERQ_ADDR(x), BP_DMA_ERQ_ERQ9) = (v)) /*@}*/ /*! * @name Register DMA_ERQ, field ERQ10[10] (RW) * * Values: * - 0 - The DMA request signal for the corresponding channel is disabled * - 1 - The DMA request signal for the corresponding channel is enabled */ /*@{*/ #define BP_DMA_ERQ_ERQ10 (10U) /*!< Bit position for DMA_ERQ_ERQ10. */ #define BM_DMA_ERQ_ERQ10 (0x00000400U) /*!< Bit mask for DMA_ERQ_ERQ10. */ #define BS_DMA_ERQ_ERQ10 (1U) /*!< Bit field size in bits for DMA_ERQ_ERQ10. */ /*! @brief Read current value of the DMA_ERQ_ERQ10 field. */ #define BR_DMA_ERQ_ERQ10(x) (BITBAND_ACCESS32(HW_DMA_ERQ_ADDR(x), BP_DMA_ERQ_ERQ10)) /*! @brief Format value for bitfield DMA_ERQ_ERQ10. */ #define BF_DMA_ERQ_ERQ10(v) ((uint32_t)((uint32_t)(v) << BP_DMA_ERQ_ERQ10) & BM_DMA_ERQ_ERQ10) /*! @brief Set the ERQ10 field to a new value. */ #define BW_DMA_ERQ_ERQ10(x, v) (BITBAND_ACCESS32(HW_DMA_ERQ_ADDR(x), BP_DMA_ERQ_ERQ10) = (v)) /*@}*/ /*! * @name Register DMA_ERQ, field ERQ11[11] (RW) * * Values: * - 0 - The DMA request signal for the corresponding channel is disabled * - 1 - The DMA request signal for the corresponding channel is enabled */ /*@{*/ #define BP_DMA_ERQ_ERQ11 (11U) /*!< Bit position for DMA_ERQ_ERQ11. */ #define BM_DMA_ERQ_ERQ11 (0x00000800U) /*!< Bit mask for DMA_ERQ_ERQ11. */ #define BS_DMA_ERQ_ERQ11 (1U) /*!< Bit field size in bits for DMA_ERQ_ERQ11. */ /*! @brief Read current value of the DMA_ERQ_ERQ11 field. */ #define BR_DMA_ERQ_ERQ11(x) (BITBAND_ACCESS32(HW_DMA_ERQ_ADDR(x), BP_DMA_ERQ_ERQ11)) /*! @brief Format value for bitfield DMA_ERQ_ERQ11. */ #define BF_DMA_ERQ_ERQ11(v) ((uint32_t)((uint32_t)(v) << BP_DMA_ERQ_ERQ11) & BM_DMA_ERQ_ERQ11) /*! @brief Set the ERQ11 field to a new value. */ #define BW_DMA_ERQ_ERQ11(x, v) (BITBAND_ACCESS32(HW_DMA_ERQ_ADDR(x), BP_DMA_ERQ_ERQ11) = (v)) /*@}*/ /*! * @name Register DMA_ERQ, field ERQ12[12] (RW) * * Values: * - 0 - The DMA request signal for the corresponding channel is disabled * - 1 - The DMA request signal for the corresponding channel is enabled */ /*@{*/ #define BP_DMA_ERQ_ERQ12 (12U) /*!< Bit position for DMA_ERQ_ERQ12. */ #define BM_DMA_ERQ_ERQ12 (0x00001000U) /*!< Bit mask for DMA_ERQ_ERQ12. */ #define BS_DMA_ERQ_ERQ12 (1U) /*!< Bit field size in bits for DMA_ERQ_ERQ12. */ /*! @brief Read current value of the DMA_ERQ_ERQ12 field. */ #define BR_DMA_ERQ_ERQ12(x) (BITBAND_ACCESS32(HW_DMA_ERQ_ADDR(x), BP_DMA_ERQ_ERQ12)) /*! @brief Format value for bitfield DMA_ERQ_ERQ12. */ #define BF_DMA_ERQ_ERQ12(v) ((uint32_t)((uint32_t)(v) << BP_DMA_ERQ_ERQ12) & BM_DMA_ERQ_ERQ12) /*! @brief Set the ERQ12 field to a new value. */ #define BW_DMA_ERQ_ERQ12(x, v) (BITBAND_ACCESS32(HW_DMA_ERQ_ADDR(x), BP_DMA_ERQ_ERQ12) = (v)) /*@}*/ /*! * @name Register DMA_ERQ, field ERQ13[13] (RW) * * Values: * - 0 - The DMA request signal for the corresponding channel is disabled * - 1 - The DMA request signal for the corresponding channel is enabled */ /*@{*/ #define BP_DMA_ERQ_ERQ13 (13U) /*!< Bit position for DMA_ERQ_ERQ13. */ #define BM_DMA_ERQ_ERQ13 (0x00002000U) /*!< Bit mask for DMA_ERQ_ERQ13. */ #define BS_DMA_ERQ_ERQ13 (1U) /*!< Bit field size in bits for DMA_ERQ_ERQ13. */ /*! @brief Read current value of the DMA_ERQ_ERQ13 field. */ #define BR_DMA_ERQ_ERQ13(x) (BITBAND_ACCESS32(HW_DMA_ERQ_ADDR(x), BP_DMA_ERQ_ERQ13)) /*! @brief Format value for bitfield DMA_ERQ_ERQ13. */ #define BF_DMA_ERQ_ERQ13(v) ((uint32_t)((uint32_t)(v) << BP_DMA_ERQ_ERQ13) & BM_DMA_ERQ_ERQ13) /*! @brief Set the ERQ13 field to a new value. */ #define BW_DMA_ERQ_ERQ13(x, v) (BITBAND_ACCESS32(HW_DMA_ERQ_ADDR(x), BP_DMA_ERQ_ERQ13) = (v)) /*@}*/ /*! * @name Register DMA_ERQ, field ERQ14[14] (RW) * * Values: * - 0 - The DMA request signal for the corresponding channel is disabled * - 1 - The DMA request signal for the corresponding channel is enabled */ /*@{*/ #define BP_DMA_ERQ_ERQ14 (14U) /*!< Bit position for DMA_ERQ_ERQ14. */ #define BM_DMA_ERQ_ERQ14 (0x00004000U) /*!< Bit mask for DMA_ERQ_ERQ14. */ #define BS_DMA_ERQ_ERQ14 (1U) /*!< Bit field size in bits for DMA_ERQ_ERQ14. */ /*! @brief Read current value of the DMA_ERQ_ERQ14 field. */ #define BR_DMA_ERQ_ERQ14(x) (BITBAND_ACCESS32(HW_DMA_ERQ_ADDR(x), BP_DMA_ERQ_ERQ14)) /*! @brief Format value for bitfield DMA_ERQ_ERQ14. */ #define BF_DMA_ERQ_ERQ14(v) ((uint32_t)((uint32_t)(v) << BP_DMA_ERQ_ERQ14) & BM_DMA_ERQ_ERQ14) /*! @brief Set the ERQ14 field to a new value. */ #define BW_DMA_ERQ_ERQ14(x, v) (BITBAND_ACCESS32(HW_DMA_ERQ_ADDR(x), BP_DMA_ERQ_ERQ14) = (v)) /*@}*/ /*! * @name Register DMA_ERQ, field ERQ15[15] (RW) * * Values: * - 0 - The DMA request signal for the corresponding channel is disabled * - 1 - The DMA request signal for the corresponding channel is enabled */ /*@{*/ #define BP_DMA_ERQ_ERQ15 (15U) /*!< Bit position for DMA_ERQ_ERQ15. */ #define BM_DMA_ERQ_ERQ15 (0x00008000U) /*!< Bit mask for DMA_ERQ_ERQ15. */ #define BS_DMA_ERQ_ERQ15 (1U) /*!< Bit field size in bits for DMA_ERQ_ERQ15. */ /*! @brief Read current value of the DMA_ERQ_ERQ15 field. */ #define BR_DMA_ERQ_ERQ15(x) (BITBAND_ACCESS32(HW_DMA_ERQ_ADDR(x), BP_DMA_ERQ_ERQ15)) /*! @brief Format value for bitfield DMA_ERQ_ERQ15. */ #define BF_DMA_ERQ_ERQ15(v) ((uint32_t)((uint32_t)(v) << BP_DMA_ERQ_ERQ15) & BM_DMA_ERQ_ERQ15) /*! @brief Set the ERQ15 field to a new value. */ #define BW_DMA_ERQ_ERQ15(x, v) (BITBAND_ACCESS32(HW_DMA_ERQ_ADDR(x), BP_DMA_ERQ_ERQ15) = (v)) /*@}*/ /******************************************************************************* * HW_DMA_EEI - Enable Error Interrupt Register ******************************************************************************/ /*! * @brief HW_DMA_EEI - Enable Error Interrupt Register (RW) * * Reset value: 0x00000000U * * The EEI register provides a bit map for the 16 channels to enable the error * interrupt signal for each channel. The state of any given channel's error * interrupt enable is directly affected by writes to this register; it is also * affected by writes to the SEEI and CEEI. The {S,C}EEI are provided so the error * interrupt enable for a single channel can easily be modified without the need to * perform a read-modify-write sequence to the EEI register. The DMA error * indicator and the error interrupt enable flag must be asserted before an error * interrupt request for a given channel is asserted to the interrupt controller. */ typedef union _hw_dma_eei { uint32_t U; struct _hw_dma_eei_bitfields { uint32_t EEI0 : 1; /*!< [0] Enable Error Interrupt 0 */ uint32_t EEI1 : 1; /*!< [1] Enable Error Interrupt 1 */ uint32_t EEI2 : 1; /*!< [2] Enable Error Interrupt 2 */ uint32_t EEI3 : 1; /*!< [3] Enable Error Interrupt 3 */ uint32_t EEI4 : 1; /*!< [4] Enable Error Interrupt 4 */ uint32_t EEI5 : 1; /*!< [5] Enable Error Interrupt 5 */ uint32_t EEI6 : 1; /*!< [6] Enable Error Interrupt 6 */ uint32_t EEI7 : 1; /*!< [7] Enable Error Interrupt 7 */ uint32_t EEI8 : 1; /*!< [8] Enable Error Interrupt 8 */ uint32_t EEI9 : 1; /*!< [9] Enable Error Interrupt 9 */ uint32_t EEI10 : 1; /*!< [10] Enable Error Interrupt 10 */ uint32_t EEI11 : 1; /*!< [11] Enable Error Interrupt 11 */ uint32_t EEI12 : 1; /*!< [12] Enable Error Interrupt 12 */ uint32_t EEI13 : 1; /*!< [13] Enable Error Interrupt 13 */ uint32_t EEI14 : 1; /*!< [14] Enable Error Interrupt 14 */ uint32_t EEI15 : 1; /*!< [15] Enable Error Interrupt 15 */ uint32_t RESERVED0 : 16; /*!< [31:16] */ } B; } hw_dma_eei_t; /*! * @name Constants and macros for entire DMA_EEI register */ /*@{*/ #define HW_DMA_EEI_ADDR(x) ((x) + 0x14U) #define HW_DMA_EEI(x) (*(__IO hw_dma_eei_t *) HW_DMA_EEI_ADDR(x)) #define HW_DMA_EEI_RD(x) (HW_DMA_EEI(x).U) #define HW_DMA_EEI_WR(x, v) (HW_DMA_EEI(x).U = (v)) #define HW_DMA_EEI_SET(x, v) (HW_DMA_EEI_WR(x, HW_DMA_EEI_RD(x) | (v))) #define HW_DMA_EEI_CLR(x, v) (HW_DMA_EEI_WR(x, HW_DMA_EEI_RD(x) & ~(v))) #define HW_DMA_EEI_TOG(x, v) (HW_DMA_EEI_WR(x, HW_DMA_EEI_RD(x) ^ (v))) /*@}*/ /* * Constants & macros for individual DMA_EEI bitfields */ /*! * @name Register DMA_EEI, field EEI0[0] (RW) * * Values: * - 0 - The error signal for corresponding channel does not generate an error * interrupt * - 1 - The assertion of the error signal for corresponding channel generates * an error interrupt request */ /*@{*/ #define BP_DMA_EEI_EEI0 (0U) /*!< Bit position for DMA_EEI_EEI0. */ #define BM_DMA_EEI_EEI0 (0x00000001U) /*!< Bit mask for DMA_EEI_EEI0. */ #define BS_DMA_EEI_EEI0 (1U) /*!< Bit field size in bits for DMA_EEI_EEI0. */ /*! @brief Read current value of the DMA_EEI_EEI0 field. */ #define BR_DMA_EEI_EEI0(x) (BITBAND_ACCESS32(HW_DMA_EEI_ADDR(x), BP_DMA_EEI_EEI0)) /*! @brief Format value for bitfield DMA_EEI_EEI0. */ #define BF_DMA_EEI_EEI0(v) ((uint32_t)((uint32_t)(v) << BP_DMA_EEI_EEI0) & BM_DMA_EEI_EEI0) /*! @brief Set the EEI0 field to a new value. */ #define BW_DMA_EEI_EEI0(x, v) (BITBAND_ACCESS32(HW_DMA_EEI_ADDR(x), BP_DMA_EEI_EEI0) = (v)) /*@}*/ /*! * @name Register DMA_EEI, field EEI1[1] (RW) * * Values: * - 0 - The error signal for corresponding channel does not generate an error * interrupt * - 1 - The assertion of the error signal for corresponding channel generates * an error interrupt request */ /*@{*/ #define BP_DMA_EEI_EEI1 (1U) /*!< Bit position for DMA_EEI_EEI1. */ #define BM_DMA_EEI_EEI1 (0x00000002U) /*!< Bit mask for DMA_EEI_EEI1. */ #define BS_DMA_EEI_EEI1 (1U) /*!< Bit field size in bits for DMA_EEI_EEI1. */ /*! @brief Read current value of the DMA_EEI_EEI1 field. */ #define BR_DMA_EEI_EEI1(x) (BITBAND_ACCESS32(HW_DMA_EEI_ADDR(x), BP_DMA_EEI_EEI1)) /*! @brief Format value for bitfield DMA_EEI_EEI1. */ #define BF_DMA_EEI_EEI1(v) ((uint32_t)((uint32_t)(v) << BP_DMA_EEI_EEI1) & BM_DMA_EEI_EEI1) /*! @brief Set the EEI1 field to a new value. */ #define BW_DMA_EEI_EEI1(x, v) (BITBAND_ACCESS32(HW_DMA_EEI_ADDR(x), BP_DMA_EEI_EEI1) = (v)) /*@}*/ /*! * @name Register DMA_EEI, field EEI2[2] (RW) * * Values: * - 0 - The error signal for corresponding channel does not generate an error * interrupt * - 1 - The assertion of the error signal for corresponding channel generates * an error interrupt request */ /*@{*/ #define BP_DMA_EEI_EEI2 (2U) /*!< Bit position for DMA_EEI_EEI2. */ #define BM_DMA_EEI_EEI2 (0x00000004U) /*!< Bit mask for DMA_EEI_EEI2. */ #define BS_DMA_EEI_EEI2 (1U) /*!< Bit field size in bits for DMA_EEI_EEI2. */ /*! @brief Read current value of the DMA_EEI_EEI2 field. */ #define BR_DMA_EEI_EEI2(x) (BITBAND_ACCESS32(HW_DMA_EEI_ADDR(x), BP_DMA_EEI_EEI2)) /*! @brief Format value for bitfield DMA_EEI_EEI2. */ #define BF_DMA_EEI_EEI2(v) ((uint32_t)((uint32_t)(v) << BP_DMA_EEI_EEI2) & BM_DMA_EEI_EEI2) /*! @brief Set the EEI2 field to a new value. */ #define BW_DMA_EEI_EEI2(x, v) (BITBAND_ACCESS32(HW_DMA_EEI_ADDR(x), BP_DMA_EEI_EEI2) = (v)) /*@}*/ /*! * @name Register DMA_EEI, field EEI3[3] (RW) * * Values: * - 0 - The error signal for corresponding channel does not generate an error * interrupt * - 1 - The assertion of the error signal for corresponding channel generates * an error interrupt request */ /*@{*/ #define BP_DMA_EEI_EEI3 (3U) /*!< Bit position for DMA_EEI_EEI3. */ #define BM_DMA_EEI_EEI3 (0x00000008U) /*!< Bit mask for DMA_EEI_EEI3. */ #define BS_DMA_EEI_EEI3 (1U) /*!< Bit field size in bits for DMA_EEI_EEI3. */ /*! @brief Read current value of the DMA_EEI_EEI3 field. */ #define BR_DMA_EEI_EEI3(x) (BITBAND_ACCESS32(HW_DMA_EEI_ADDR(x), BP_DMA_EEI_EEI3)) /*! @brief Format value for bitfield DMA_EEI_EEI3. */ #define BF_DMA_EEI_EEI3(v) ((uint32_t)((uint32_t)(v) << BP_DMA_EEI_EEI3) & BM_DMA_EEI_EEI3) /*! @brief Set the EEI3 field to a new value. */ #define BW_DMA_EEI_EEI3(x, v) (BITBAND_ACCESS32(HW_DMA_EEI_ADDR(x), BP_DMA_EEI_EEI3) = (v)) /*@}*/ /*! * @name Register DMA_EEI, field EEI4[4] (RW) * * Values: * - 0 - The error signal for corresponding channel does not generate an error * interrupt * - 1 - The assertion of the error signal for corresponding channel generates * an error interrupt request */ /*@{*/ #define BP_DMA_EEI_EEI4 (4U) /*!< Bit position for DMA_EEI_EEI4. */ #define BM_DMA_EEI_EEI4 (0x00000010U) /*!< Bit mask for DMA_EEI_EEI4. */ #define BS_DMA_EEI_EEI4 (1U) /*!< Bit field size in bits for DMA_EEI_EEI4. */ /*! @brief Read current value of the DMA_EEI_EEI4 field. */ #define BR_DMA_EEI_EEI4(x) (BITBAND_ACCESS32(HW_DMA_EEI_ADDR(x), BP_DMA_EEI_EEI4)) /*! @brief Format value for bitfield DMA_EEI_EEI4. */ #define BF_DMA_EEI_EEI4(v) ((uint32_t)((uint32_t)(v) << BP_DMA_EEI_EEI4) & BM_DMA_EEI_EEI4) /*! @brief Set the EEI4 field to a new value. */ #define BW_DMA_EEI_EEI4(x, v) (BITBAND_ACCESS32(HW_DMA_EEI_ADDR(x), BP_DMA_EEI_EEI4) = (v)) /*@}*/ /*! * @name Register DMA_EEI, field EEI5[5] (RW) * * Values: * - 0 - The error signal for corresponding channel does not generate an error * interrupt * - 1 - The assertion of the error signal for corresponding channel generates * an error interrupt request */ /*@{*/ #define BP_DMA_EEI_EEI5 (5U) /*!< Bit position for DMA_EEI_EEI5. */ #define BM_DMA_EEI_EEI5 (0x00000020U) /*!< Bit mask for DMA_EEI_EEI5. */ #define BS_DMA_EEI_EEI5 (1U) /*!< Bit field size in bits for DMA_EEI_EEI5. */ /*! @brief Read current value of the DMA_EEI_EEI5 field. */ #define BR_DMA_EEI_EEI5(x) (BITBAND_ACCESS32(HW_DMA_EEI_ADDR(x), BP_DMA_EEI_EEI5)) /*! @brief Format value for bitfield DMA_EEI_EEI5. */ #define BF_DMA_EEI_EEI5(v) ((uint32_t)((uint32_t)(v) << BP_DMA_EEI_EEI5) & BM_DMA_EEI_EEI5) /*! @brief Set the EEI5 field to a new value. */ #define BW_DMA_EEI_EEI5(x, v) (BITBAND_ACCESS32(HW_DMA_EEI_ADDR(x), BP_DMA_EEI_EEI5) = (v)) /*@}*/ /*! * @name Register DMA_EEI, field EEI6[6] (RW) * * Values: * - 0 - The error signal for corresponding channel does not generate an error * interrupt * - 1 - The assertion of the error signal for corresponding channel generates * an error interrupt request */ /*@{*/ #define BP_DMA_EEI_EEI6 (6U) /*!< Bit position for DMA_EEI_EEI6. */ #define BM_DMA_EEI_EEI6 (0x00000040U) /*!< Bit mask for DMA_EEI_EEI6. */ #define BS_DMA_EEI_EEI6 (1U) /*!< Bit field size in bits for DMA_EEI_EEI6. */ /*! @brief Read current value of the DMA_EEI_EEI6 field. */ #define BR_DMA_EEI_EEI6(x) (BITBAND_ACCESS32(HW_DMA_EEI_ADDR(x), BP_DMA_EEI_EEI6)) /*! @brief Format value for bitfield DMA_EEI_EEI6. */ #define BF_DMA_EEI_EEI6(v) ((uint32_t)((uint32_t)(v) << BP_DMA_EEI_EEI6) & BM_DMA_EEI_EEI6) /*! @brief Set the EEI6 field to a new value. */ #define BW_DMA_EEI_EEI6(x, v) (BITBAND_ACCESS32(HW_DMA_EEI_ADDR(x), BP_DMA_EEI_EEI6) = (v)) /*@}*/ /*! * @name Register DMA_EEI, field EEI7[7] (RW) * * Values: * - 0 - The error signal for corresponding channel does not generate an error * interrupt * - 1 - The assertion of the error signal for corresponding channel generates * an error interrupt request */ /*@{*/ #define BP_DMA_EEI_EEI7 (7U) /*!< Bit position for DMA_EEI_EEI7. */ #define BM_DMA_EEI_EEI7 (0x00000080U) /*!< Bit mask for DMA_EEI_EEI7. */ #define BS_DMA_EEI_EEI7 (1U) /*!< Bit field size in bits for DMA_EEI_EEI7. */ /*! @brief Read current value of the DMA_EEI_EEI7 field. */ #define BR_DMA_EEI_EEI7(x) (BITBAND_ACCESS32(HW_DMA_EEI_ADDR(x), BP_DMA_EEI_EEI7)) /*! @brief Format value for bitfield DMA_EEI_EEI7. */ #define BF_DMA_EEI_EEI7(v) ((uint32_t)((uint32_t)(v) << BP_DMA_EEI_EEI7) & BM_DMA_EEI_EEI7) /*! @brief Set the EEI7 field to a new value. */ #define BW_DMA_EEI_EEI7(x, v) (BITBAND_ACCESS32(HW_DMA_EEI_ADDR(x), BP_DMA_EEI_EEI7) = (v)) /*@}*/ /*! * @name Register DMA_EEI, field EEI8[8] (RW) * * Values: * - 0 - The error signal for corresponding channel does not generate an error * interrupt * - 1 - The assertion of the error signal for corresponding channel generates * an error interrupt request */ /*@{*/ #define BP_DMA_EEI_EEI8 (8U) /*!< Bit position for DMA_EEI_EEI8. */ #define BM_DMA_EEI_EEI8 (0x00000100U) /*!< Bit mask for DMA_EEI_EEI8. */ #define BS_DMA_EEI_EEI8 (1U) /*!< Bit field size in bits for DMA_EEI_EEI8. */ /*! @brief Read current value of the DMA_EEI_EEI8 field. */ #define BR_DMA_EEI_EEI8(x) (BITBAND_ACCESS32(HW_DMA_EEI_ADDR(x), BP_DMA_EEI_EEI8)) /*! @brief Format value for bitfield DMA_EEI_EEI8. */ #define BF_DMA_EEI_EEI8(v) ((uint32_t)((uint32_t)(v) << BP_DMA_EEI_EEI8) & BM_DMA_EEI_EEI8) /*! @brief Set the EEI8 field to a new value. */ #define BW_DMA_EEI_EEI8(x, v) (BITBAND_ACCESS32(HW_DMA_EEI_ADDR(x), BP_DMA_EEI_EEI8) = (v)) /*@}*/ /*! * @name Register DMA_EEI, field EEI9[9] (RW) * * Values: * - 0 - The error signal for corresponding channel does not generate an error * interrupt * - 1 - The assertion of the error signal for corresponding channel generates * an error interrupt request */ /*@{*/ #define BP_DMA_EEI_EEI9 (9U) /*!< Bit position for DMA_EEI_EEI9. */ #define BM_DMA_EEI_EEI9 (0x00000200U) /*!< Bit mask for DMA_EEI_EEI9. */ #define BS_DMA_EEI_EEI9 (1U) /*!< Bit field size in bits for DMA_EEI_EEI9. */ /*! @brief Read current value of the DMA_EEI_EEI9 field. */ #define BR_DMA_EEI_EEI9(x) (BITBAND_ACCESS32(HW_DMA_EEI_ADDR(x), BP_DMA_EEI_EEI9)) /*! @brief Format value for bitfield DMA_EEI_EEI9. */ #define BF_DMA_EEI_EEI9(v) ((uint32_t)((uint32_t)(v) << BP_DMA_EEI_EEI9) & BM_DMA_EEI_EEI9) /*! @brief Set the EEI9 field to a new value. */ #define BW_DMA_EEI_EEI9(x, v) (BITBAND_ACCESS32(HW_DMA_EEI_ADDR(x), BP_DMA_EEI_EEI9) = (v)) /*@}*/ /*! * @name Register DMA_EEI, field EEI10[10] (RW) * * Values: * - 0 - The error signal for corresponding channel does not generate an error * interrupt * - 1 - The assertion of the error signal for corresponding channel generates * an error interrupt request */ /*@{*/ #define BP_DMA_EEI_EEI10 (10U) /*!< Bit position for DMA_EEI_EEI10. */ #define BM_DMA_EEI_EEI10 (0x00000400U) /*!< Bit mask for DMA_EEI_EEI10. */ #define BS_DMA_EEI_EEI10 (1U) /*!< Bit field size in bits for DMA_EEI_EEI10. */ /*! @brief Read current value of the DMA_EEI_EEI10 field. */ #define BR_DMA_EEI_EEI10(x) (BITBAND_ACCESS32(HW_DMA_EEI_ADDR(x), BP_DMA_EEI_EEI10)) /*! @brief Format value for bitfield DMA_EEI_EEI10. */ #define BF_DMA_EEI_EEI10(v) ((uint32_t)((uint32_t)(v) << BP_DMA_EEI_EEI10) & BM_DMA_EEI_EEI10) /*! @brief Set the EEI10 field to a new value. */ #define BW_DMA_EEI_EEI10(x, v) (BITBAND_ACCESS32(HW_DMA_EEI_ADDR(x), BP_DMA_EEI_EEI10) = (v)) /*@}*/ /*! * @name Register DMA_EEI, field EEI11[11] (RW) * * Values: * - 0 - The error signal for corresponding channel does not generate an error * interrupt * - 1 - The assertion of the error signal for corresponding channel generates * an error interrupt request */ /*@{*/ #define BP_DMA_EEI_EEI11 (11U) /*!< Bit position for DMA_EEI_EEI11. */ #define BM_DMA_EEI_EEI11 (0x00000800U) /*!< Bit mask for DMA_EEI_EEI11. */ #define BS_DMA_EEI_EEI11 (1U) /*!< Bit field size in bits for DMA_EEI_EEI11. */ /*! @brief Read current value of the DMA_EEI_EEI11 field. */ #define BR_DMA_EEI_EEI11(x) (BITBAND_ACCESS32(HW_DMA_EEI_ADDR(x), BP_DMA_EEI_EEI11)) /*! @brief Format value for bitfield DMA_EEI_EEI11. */ #define BF_DMA_EEI_EEI11(v) ((uint32_t)((uint32_t)(v) << BP_DMA_EEI_EEI11) & BM_DMA_EEI_EEI11) /*! @brief Set the EEI11 field to a new value. */ #define BW_DMA_EEI_EEI11(x, v) (BITBAND_ACCESS32(HW_DMA_EEI_ADDR(x), BP_DMA_EEI_EEI11) = (v)) /*@}*/ /*! * @name Register DMA_EEI, field EEI12[12] (RW) * * Values: * - 0 - The error signal for corresponding channel does not generate an error * interrupt * - 1 - The assertion of the error signal for corresponding channel generates * an error interrupt request */ /*@{*/ #define BP_DMA_EEI_EEI12 (12U) /*!< Bit position for DMA_EEI_EEI12. */ #define BM_DMA_EEI_EEI12 (0x00001000U) /*!< Bit mask for DMA_EEI_EEI12. */ #define BS_DMA_EEI_EEI12 (1U) /*!< Bit field size in bits for DMA_EEI_EEI12. */ /*! @brief Read current value of the DMA_EEI_EEI12 field. */ #define BR_DMA_EEI_EEI12(x) (BITBAND_ACCESS32(HW_DMA_EEI_ADDR(x), BP_DMA_EEI_EEI12)) /*! @brief Format value for bitfield DMA_EEI_EEI12. */ #define BF_DMA_EEI_EEI12(v) ((uint32_t)((uint32_t)(v) << BP_DMA_EEI_EEI12) & BM_DMA_EEI_EEI12) /*! @brief Set the EEI12 field to a new value. */ #define BW_DMA_EEI_EEI12(x, v) (BITBAND_ACCESS32(HW_DMA_EEI_ADDR(x), BP_DMA_EEI_EEI12) = (v)) /*@}*/ /*! * @name Register DMA_EEI, field EEI13[13] (RW) * * Values: * - 0 - The error signal for corresponding channel does not generate an error * interrupt * - 1 - The assertion of the error signal for corresponding channel generates * an error interrupt request */ /*@{*/ #define BP_DMA_EEI_EEI13 (13U) /*!< Bit position for DMA_EEI_EEI13. */ #define BM_DMA_EEI_EEI13 (0x00002000U) /*!< Bit mask for DMA_EEI_EEI13. */ #define BS_DMA_EEI_EEI13 (1U) /*!< Bit field size in bits for DMA_EEI_EEI13. */ /*! @brief Read current value of the DMA_EEI_EEI13 field. */ #define BR_DMA_EEI_EEI13(x) (BITBAND_ACCESS32(HW_DMA_EEI_ADDR(x), BP_DMA_EEI_EEI13)) /*! @brief Format value for bitfield DMA_EEI_EEI13. */ #define BF_DMA_EEI_EEI13(v) ((uint32_t)((uint32_t)(v) << BP_DMA_EEI_EEI13) & BM_DMA_EEI_EEI13) /*! @brief Set the EEI13 field to a new value. */ #define BW_DMA_EEI_EEI13(x, v) (BITBAND_ACCESS32(HW_DMA_EEI_ADDR(x), BP_DMA_EEI_EEI13) = (v)) /*@}*/ /*! * @name Register DMA_EEI, field EEI14[14] (RW) * * Values: * - 0 - The error signal for corresponding channel does not generate an error * interrupt * - 1 - The assertion of the error signal for corresponding channel generates * an error interrupt request */ /*@{*/ #define BP_DMA_EEI_EEI14 (14U) /*!< Bit position for DMA_EEI_EEI14. */ #define BM_DMA_EEI_EEI14 (0x00004000U) /*!< Bit mask for DMA_EEI_EEI14. */ #define BS_DMA_EEI_EEI14 (1U) /*!< Bit field size in bits for DMA_EEI_EEI14. */ /*! @brief Read current value of the DMA_EEI_EEI14 field. */ #define BR_DMA_EEI_EEI14(x) (BITBAND_ACCESS32(HW_DMA_EEI_ADDR(x), BP_DMA_EEI_EEI14)) /*! @brief Format value for bitfield DMA_EEI_EEI14. */ #define BF_DMA_EEI_EEI14(v) ((uint32_t)((uint32_t)(v) << BP_DMA_EEI_EEI14) & BM_DMA_EEI_EEI14) /*! @brief Set the EEI14 field to a new value. */ #define BW_DMA_EEI_EEI14(x, v) (BITBAND_ACCESS32(HW_DMA_EEI_ADDR(x), BP_DMA_EEI_EEI14) = (v)) /*@}*/ /*! * @name Register DMA_EEI, field EEI15[15] (RW) * * Values: * - 0 - The error signal for corresponding channel does not generate an error * interrupt * - 1 - The assertion of the error signal for corresponding channel generates * an error interrupt request */ /*@{*/ #define BP_DMA_EEI_EEI15 (15U) /*!< Bit position for DMA_EEI_EEI15. */ #define BM_DMA_EEI_EEI15 (0x00008000U) /*!< Bit mask for DMA_EEI_EEI15. */ #define BS_DMA_EEI_EEI15 (1U) /*!< Bit field size in bits for DMA_EEI_EEI15. */ /*! @brief Read current value of the DMA_EEI_EEI15 field. */ #define BR_DMA_EEI_EEI15(x) (BITBAND_ACCESS32(HW_DMA_EEI_ADDR(x), BP_DMA_EEI_EEI15)) /*! @brief Format value for bitfield DMA_EEI_EEI15. */ #define BF_DMA_EEI_EEI15(v) ((uint32_t)((uint32_t)(v) << BP_DMA_EEI_EEI15) & BM_DMA_EEI_EEI15) /*! @brief Set the EEI15 field to a new value. */ #define BW_DMA_EEI_EEI15(x, v) (BITBAND_ACCESS32(HW_DMA_EEI_ADDR(x), BP_DMA_EEI_EEI15) = (v)) /*@}*/ /******************************************************************************* * HW_DMA_CEEI - Clear Enable Error Interrupt Register ******************************************************************************/ /*! * @brief HW_DMA_CEEI - Clear Enable Error Interrupt Register (WO) * * Reset value: 0x00U * * The CEEI provides a simple memory-mapped mechanism to clear a given bit in * the EEI to disable the error interrupt for a given channel. The data value on a * register write causes the corresponding bit in the EEI to be cleared. Setting * the CAEE bit provides a global clear function, forcing the EEI contents to be * cleared, disabling all DMA request inputs. If the NOP bit is set, the command * is ignored. This allows you to write multiple-byte registers as a 32-bit word. * Reads of this register return all zeroes. */ typedef union _hw_dma_ceei { uint8_t U; struct _hw_dma_ceei_bitfields { uint8_t CEEI : 4; /*!< [3:0] Clear Enable Error Interrupt */ uint8_t RESERVED0 : 2; /*!< [5:4] */ uint8_t CAEE : 1; /*!< [6] Clear All Enable Error Interrupts */ uint8_t NOP : 1; /*!< [7] No Op enable */ } B; } hw_dma_ceei_t; /*! * @name Constants and macros for entire DMA_CEEI register */ /*@{*/ #define HW_DMA_CEEI_ADDR(x) ((x) + 0x18U) #define HW_DMA_CEEI(x) (*(__O hw_dma_ceei_t *) HW_DMA_CEEI_ADDR(x)) #define HW_DMA_CEEI_RD(x) (HW_DMA_CEEI(x).U) #define HW_DMA_CEEI_WR(x, v) (HW_DMA_CEEI(x).U = (v)) /*@}*/ /* * Constants & macros for individual DMA_CEEI bitfields */ /*! * @name Register DMA_CEEI, field CEEI[3:0] (WORZ) * * Clears the corresponding bit in EEI */ /*@{*/ #define BP_DMA_CEEI_CEEI (0U) /*!< Bit position for DMA_CEEI_CEEI. */ #define BM_DMA_CEEI_CEEI (0x0FU) /*!< Bit mask for DMA_CEEI_CEEI. */ #define BS_DMA_CEEI_CEEI (4U) /*!< Bit field size in bits for DMA_CEEI_CEEI. */ /*! @brief Format value for bitfield DMA_CEEI_CEEI. */ #define BF_DMA_CEEI_CEEI(v) ((uint8_t)((uint8_t)(v) << BP_DMA_CEEI_CEEI) & BM_DMA_CEEI_CEEI) /*! @brief Set the CEEI field to a new value. */ #define BW_DMA_CEEI_CEEI(x, v) (HW_DMA_CEEI_WR(x, (HW_DMA_CEEI_RD(x) & ~BM_DMA_CEEI_CEEI) | BF_DMA_CEEI_CEEI(v))) /*@}*/ /*! * @name Register DMA_CEEI, field CAEE[6] (WORZ) * * Values: * - 0 - Clear only the EEI bit specified in the CEEI field * - 1 - Clear all bits in EEI */ /*@{*/ #define BP_DMA_CEEI_CAEE (6U) /*!< Bit position for DMA_CEEI_CAEE. */ #define BM_DMA_CEEI_CAEE (0x40U) /*!< Bit mask for DMA_CEEI_CAEE. */ #define BS_DMA_CEEI_CAEE (1U) /*!< Bit field size in bits for DMA_CEEI_CAEE. */ /*! @brief Format value for bitfield DMA_CEEI_CAEE. */ #define BF_DMA_CEEI_CAEE(v) ((uint8_t)((uint8_t)(v) << BP_DMA_CEEI_CAEE) & BM_DMA_CEEI_CAEE) /*! @brief Set the CAEE field to a new value. */ #define BW_DMA_CEEI_CAEE(x, v) (BITBAND_ACCESS8(HW_DMA_CEEI_ADDR(x), BP_DMA_CEEI_CAEE) = (v)) /*@}*/ /*! * @name Register DMA_CEEI, field NOP[7] (WORZ) * * Values: * - 0 - Normal operation * - 1 - No operation, ignore the other bits in this register */ /*@{*/ #define BP_DMA_CEEI_NOP (7U) /*!< Bit position for DMA_CEEI_NOP. */ #define BM_DMA_CEEI_NOP (0x80U) /*!< Bit mask for DMA_CEEI_NOP. */ #define BS_DMA_CEEI_NOP (1U) /*!< Bit field size in bits for DMA_CEEI_NOP. */ /*! @brief Format value for bitfield DMA_CEEI_NOP. */ #define BF_DMA_CEEI_NOP(v) ((uint8_t)((uint8_t)(v) << BP_DMA_CEEI_NOP) & BM_DMA_CEEI_NOP) /*! @brief Set the NOP field to a new value. */ #define BW_DMA_CEEI_NOP(x, v) (BITBAND_ACCESS8(HW_DMA_CEEI_ADDR(x), BP_DMA_CEEI_NOP) = (v)) /*@}*/ /******************************************************************************* * HW_DMA_SEEI - Set Enable Error Interrupt Register ******************************************************************************/ /*! * @brief HW_DMA_SEEI - Set Enable Error Interrupt Register (WO) * * Reset value: 0x00U * * The SEEI provides a simple memory-mapped mechanism to set a given bit in the * EEI to enable the error interrupt for a given channel. The data value on a * register write causes the corresponding bit in the EEI to be set. Setting the * SAEE bit provides a global set function, forcing the entire EEI contents to be * set. If the NOP bit is set, the command is ignored. This allows you to write * multiple-byte registers as a 32-bit word. Reads of this register return all * zeroes. */ typedef union _hw_dma_seei { uint8_t U; struct _hw_dma_seei_bitfields { uint8_t SEEI : 4; /*!< [3:0] Set Enable Error Interrupt */ uint8_t RESERVED0 : 2; /*!< [5:4] */ uint8_t SAEE : 1; /*!< [6] Sets All Enable Error Interrupts */ uint8_t NOP : 1; /*!< [7] No Op enable */ } B; } hw_dma_seei_t; /*! * @name Constants and macros for entire DMA_SEEI register */ /*@{*/ #define HW_DMA_SEEI_ADDR(x) ((x) + 0x19U) #define HW_DMA_SEEI(x) (*(__O hw_dma_seei_t *) HW_DMA_SEEI_ADDR(x)) #define HW_DMA_SEEI_RD(x) (HW_DMA_SEEI(x).U) #define HW_DMA_SEEI_WR(x, v) (HW_DMA_SEEI(x).U = (v)) /*@}*/ /* * Constants & macros for individual DMA_SEEI bitfields */ /*! * @name Register DMA_SEEI, field SEEI[3:0] (WORZ) * * Sets the corresponding bit in EEI */ /*@{*/ #define BP_DMA_SEEI_SEEI (0U) /*!< Bit position for DMA_SEEI_SEEI. */ #define BM_DMA_SEEI_SEEI (0x0FU) /*!< Bit mask for DMA_SEEI_SEEI. */ #define BS_DMA_SEEI_SEEI (4U) /*!< Bit field size in bits for DMA_SEEI_SEEI. */ /*! @brief Format value for bitfield DMA_SEEI_SEEI. */ #define BF_DMA_SEEI_SEEI(v) ((uint8_t)((uint8_t)(v) << BP_DMA_SEEI_SEEI) & BM_DMA_SEEI_SEEI) /*! @brief Set the SEEI field to a new value. */ #define BW_DMA_SEEI_SEEI(x, v) (HW_DMA_SEEI_WR(x, (HW_DMA_SEEI_RD(x) & ~BM_DMA_SEEI_SEEI) | BF_DMA_SEEI_SEEI(v))) /*@}*/ /*! * @name Register DMA_SEEI, field SAEE[6] (WORZ) * * Values: * - 0 - Set only the EEI bit specified in the SEEI field. * - 1 - Sets all bits in EEI */ /*@{*/ #define BP_DMA_SEEI_SAEE (6U) /*!< Bit position for DMA_SEEI_SAEE. */ #define BM_DMA_SEEI_SAEE (0x40U) /*!< Bit mask for DMA_SEEI_SAEE. */ #define BS_DMA_SEEI_SAEE (1U) /*!< Bit field size in bits for DMA_SEEI_SAEE. */ /*! @brief Format value for bitfield DMA_SEEI_SAEE. */ #define BF_DMA_SEEI_SAEE(v) ((uint8_t)((uint8_t)(v) << BP_DMA_SEEI_SAEE) & BM_DMA_SEEI_SAEE) /*! @brief Set the SAEE field to a new value. */ #define BW_DMA_SEEI_SAEE(x, v) (BITBAND_ACCESS8(HW_DMA_SEEI_ADDR(x), BP_DMA_SEEI_SAEE) = (v)) /*@}*/ /*! * @name Register DMA_SEEI, field NOP[7] (WORZ) * * Values: * - 0 - Normal operation * - 1 - No operation, ignore the other bits in this register */ /*@{*/ #define BP_DMA_SEEI_NOP (7U) /*!< Bit position for DMA_SEEI_NOP. */ #define BM_DMA_SEEI_NOP (0x80U) /*!< Bit mask for DMA_SEEI_NOP. */ #define BS_DMA_SEEI_NOP (1U) /*!< Bit field size in bits for DMA_SEEI_NOP. */ /*! @brief Format value for bitfield DMA_SEEI_NOP. */ #define BF_DMA_SEEI_NOP(v) ((uint8_t)((uint8_t)(v) << BP_DMA_SEEI_NOP) & BM_DMA_SEEI_NOP) /*! @brief Set the NOP field to a new value. */ #define BW_DMA_SEEI_NOP(x, v) (BITBAND_ACCESS8(HW_DMA_SEEI_ADDR(x), BP_DMA_SEEI_NOP) = (v)) /*@}*/ /******************************************************************************* * HW_DMA_CERQ - Clear Enable Request Register ******************************************************************************/ /*! * @brief HW_DMA_CERQ - Clear Enable Request Register (WO) * * Reset value: 0x00U * * The CERQ provides a simple memory-mapped mechanism to clear a given bit in * the ERQ to disable the DMA request for a given channel. The data value on a * register write causes the corresponding bit in the ERQ to be cleared. Setting the * CAER bit provides a global clear function, forcing the entire contents of the * ERQ to be cleared, disabling all DMA request inputs. If NOP is set, the * command is ignored. This allows you to write multiple-byte registers as a 32-bit * word. Reads of this register return all zeroes. */ typedef union _hw_dma_cerq { uint8_t U; struct _hw_dma_cerq_bitfields { uint8_t CERQ : 4; /*!< [3:0] Clear Enable Request */ uint8_t RESERVED0 : 2; /*!< [5:4] */ uint8_t CAER : 1; /*!< [6] Clear All Enable Requests */ uint8_t NOP : 1; /*!< [7] No Op enable */ } B; } hw_dma_cerq_t; /*! * @name Constants and macros for entire DMA_CERQ register */ /*@{*/ #define HW_DMA_CERQ_ADDR(x) ((x) + 0x1AU) #define HW_DMA_CERQ(x) (*(__O hw_dma_cerq_t *) HW_DMA_CERQ_ADDR(x)) #define HW_DMA_CERQ_RD(x) (HW_DMA_CERQ(x).U) #define HW_DMA_CERQ_WR(x, v) (HW_DMA_CERQ(x).U = (v)) /*@}*/ /* * Constants & macros for individual DMA_CERQ bitfields */ /*! * @name Register DMA_CERQ, field CERQ[3:0] (WORZ) * * Clears the corresponding bit in ERQ */ /*@{*/ #define BP_DMA_CERQ_CERQ (0U) /*!< Bit position for DMA_CERQ_CERQ. */ #define BM_DMA_CERQ_CERQ (0x0FU) /*!< Bit mask for DMA_CERQ_CERQ. */ #define BS_DMA_CERQ_CERQ (4U) /*!< Bit field size in bits for DMA_CERQ_CERQ. */ /*! @brief Format value for bitfield DMA_CERQ_CERQ. */ #define BF_DMA_CERQ_CERQ(v) ((uint8_t)((uint8_t)(v) << BP_DMA_CERQ_CERQ) & BM_DMA_CERQ_CERQ) /*! @brief Set the CERQ field to a new value. */ #define BW_DMA_CERQ_CERQ(x, v) (HW_DMA_CERQ_WR(x, (HW_DMA_CERQ_RD(x) & ~BM_DMA_CERQ_CERQ) | BF_DMA_CERQ_CERQ(v))) /*@}*/ /*! * @name Register DMA_CERQ, field CAER[6] (WORZ) * * Values: * - 0 - Clear only the ERQ bit specified in the CERQ field * - 1 - Clear all bits in ERQ */ /*@{*/ #define BP_DMA_CERQ_CAER (6U) /*!< Bit position for DMA_CERQ_CAER. */ #define BM_DMA_CERQ_CAER (0x40U) /*!< Bit mask for DMA_CERQ_CAER. */ #define BS_DMA_CERQ_CAER (1U) /*!< Bit field size in bits for DMA_CERQ_CAER. */ /*! @brief Format value for bitfield DMA_CERQ_CAER. */ #define BF_DMA_CERQ_CAER(v) ((uint8_t)((uint8_t)(v) << BP_DMA_CERQ_CAER) & BM_DMA_CERQ_CAER) /*! @brief Set the CAER field to a new value. */ #define BW_DMA_CERQ_CAER(x, v) (BITBAND_ACCESS8(HW_DMA_CERQ_ADDR(x), BP_DMA_CERQ_CAER) = (v)) /*@}*/ /*! * @name Register DMA_CERQ, field NOP[7] (WORZ) * * Values: * - 0 - Normal operation * - 1 - No operation, ignore the other bits in this register */ /*@{*/ #define BP_DMA_CERQ_NOP (7U) /*!< Bit position for DMA_CERQ_NOP. */ #define BM_DMA_CERQ_NOP (0x80U) /*!< Bit mask for DMA_CERQ_NOP. */ #define BS_DMA_CERQ_NOP (1U) /*!< Bit field size in bits for DMA_CERQ_NOP. */ /*! @brief Format value for bitfield DMA_CERQ_NOP. */ #define BF_DMA_CERQ_NOP(v) ((uint8_t)((uint8_t)(v) << BP_DMA_CERQ_NOP) & BM_DMA_CERQ_NOP) /*! @brief Set the NOP field to a new value. */ #define BW_DMA_CERQ_NOP(x, v) (BITBAND_ACCESS8(HW_DMA_CERQ_ADDR(x), BP_DMA_CERQ_NOP) = (v)) /*@}*/ /******************************************************************************* * HW_DMA_SERQ - Set Enable Request Register ******************************************************************************/ /*! * @brief HW_DMA_SERQ - Set Enable Request Register (WO) * * Reset value: 0x00U * * The SERQ provides a simple memory-mapped mechanism to set a given bit in the * ERQ to enable the DMA request for a given channel. The data value on a * register write causes the corresponding bit in the ERQ to be set. Setting the SAER * bit provides a global set function, forcing the entire contents of ERQ to be * set. If the NOP bit is set, the command is ignored. This allows you to write * multiple-byte registers as a 32-bit word. Reads of this register return all zeroes. */ typedef union _hw_dma_serq { uint8_t U; struct _hw_dma_serq_bitfields { uint8_t SERQ : 4; /*!< [3:0] Set enable request */ uint8_t RESERVED0 : 2; /*!< [5:4] */ uint8_t SAER : 1; /*!< [6] Set All Enable Requests */ uint8_t NOP : 1; /*!< [7] No Op enable */ } B; } hw_dma_serq_t; /*! * @name Constants and macros for entire DMA_SERQ register */ /*@{*/ #define HW_DMA_SERQ_ADDR(x) ((x) + 0x1BU) #define HW_DMA_SERQ(x) (*(__O hw_dma_serq_t *) HW_DMA_SERQ_ADDR(x)) #define HW_DMA_SERQ_RD(x) (HW_DMA_SERQ(x).U) #define HW_DMA_SERQ_WR(x, v) (HW_DMA_SERQ(x).U = (v)) /*@}*/ /* * Constants & macros for individual DMA_SERQ bitfields */ /*! * @name Register DMA_SERQ, field SERQ[3:0] (WORZ) * * Sets the corresponding bit in ERQ */ /*@{*/ #define BP_DMA_SERQ_SERQ (0U) /*!< Bit position for DMA_SERQ_SERQ. */ #define BM_DMA_SERQ_SERQ (0x0FU) /*!< Bit mask for DMA_SERQ_SERQ. */ #define BS_DMA_SERQ_SERQ (4U) /*!< Bit field size in bits for DMA_SERQ_SERQ. */ /*! @brief Format value for bitfield DMA_SERQ_SERQ. */ #define BF_DMA_SERQ_SERQ(v) ((uint8_t)((uint8_t)(v) << BP_DMA_SERQ_SERQ) & BM_DMA_SERQ_SERQ) /*! @brief Set the SERQ field to a new value. */ #define BW_DMA_SERQ_SERQ(x, v) (HW_DMA_SERQ_WR(x, (HW_DMA_SERQ_RD(x) & ~BM_DMA_SERQ_SERQ) | BF_DMA_SERQ_SERQ(v))) /*@}*/ /*! * @name Register DMA_SERQ, field SAER[6] (WORZ) * * Values: * - 0 - Set only the ERQ bit specified in the SERQ field * - 1 - Set all bits in ERQ */ /*@{*/ #define BP_DMA_SERQ_SAER (6U) /*!< Bit position for DMA_SERQ_SAER. */ #define BM_DMA_SERQ_SAER (0x40U) /*!< Bit mask for DMA_SERQ_SAER. */ #define BS_DMA_SERQ_SAER (1U) /*!< Bit field size in bits for DMA_SERQ_SAER. */ /*! @brief Format value for bitfield DMA_SERQ_SAER. */ #define BF_DMA_SERQ_SAER(v) ((uint8_t)((uint8_t)(v) << BP_DMA_SERQ_SAER) & BM_DMA_SERQ_SAER) /*! @brief Set the SAER field to a new value. */ #define BW_DMA_SERQ_SAER(x, v) (BITBAND_ACCESS8(HW_DMA_SERQ_ADDR(x), BP_DMA_SERQ_SAER) = (v)) /*@}*/ /*! * @name Register DMA_SERQ, field NOP[7] (WORZ) * * Values: * - 0 - Normal operation * - 1 - No operation, ignore the other bits in this register */ /*@{*/ #define BP_DMA_SERQ_NOP (7U) /*!< Bit position for DMA_SERQ_NOP. */ #define BM_DMA_SERQ_NOP (0x80U) /*!< Bit mask for DMA_SERQ_NOP. */ #define BS_DMA_SERQ_NOP (1U) /*!< Bit field size in bits for DMA_SERQ_NOP. */ /*! @brief Format value for bitfield DMA_SERQ_NOP. */ #define BF_DMA_SERQ_NOP(v) ((uint8_t)((uint8_t)(v) << BP_DMA_SERQ_NOP) & BM_DMA_SERQ_NOP) /*! @brief Set the NOP field to a new value. */ #define BW_DMA_SERQ_NOP(x, v) (BITBAND_ACCESS8(HW_DMA_SERQ_ADDR(x), BP_DMA_SERQ_NOP) = (v)) /*@}*/ /******************************************************************************* * HW_DMA_CDNE - Clear DONE Status Bit Register ******************************************************************************/ /*! * @brief HW_DMA_CDNE - Clear DONE Status Bit Register (WO) * * Reset value: 0x00U * * The CDNE provides a simple memory-mapped mechanism to clear the DONE bit in * the TCD of the given channel. The data value on a register write causes the * DONE bit in the corresponding transfer control descriptor to be cleared. Setting * the CADN bit provides a global clear function, forcing all DONE bits to be * cleared. If the NOP bit is set, the command is ignored. This allows you to write * multiple-byte registers as a 32-bit word. Reads of this register return all * zeroes. */ typedef union _hw_dma_cdne { uint8_t U; struct _hw_dma_cdne_bitfields { uint8_t CDNE : 4; /*!< [3:0] Clear DONE Bit */ uint8_t RESERVED0 : 2; /*!< [5:4] */ uint8_t CADN : 1; /*!< [6] Clears All DONE Bits */ uint8_t NOP : 1; /*!< [7] No Op enable */ } B; } hw_dma_cdne_t; /*! * @name Constants and macros for entire DMA_CDNE register */ /*@{*/ #define HW_DMA_CDNE_ADDR(x) ((x) + 0x1CU) #define HW_DMA_CDNE(x) (*(__O hw_dma_cdne_t *) HW_DMA_CDNE_ADDR(x)) #define HW_DMA_CDNE_RD(x) (HW_DMA_CDNE(x).U) #define HW_DMA_CDNE_WR(x, v) (HW_DMA_CDNE(x).U = (v)) /*@}*/ /* * Constants & macros for individual DMA_CDNE bitfields */ /*! * @name Register DMA_CDNE, field CDNE[3:0] (WORZ) * * Clears the corresponding bit in TCDn_CSR[DONE] */ /*@{*/ #define BP_DMA_CDNE_CDNE (0U) /*!< Bit position for DMA_CDNE_CDNE. */ #define BM_DMA_CDNE_CDNE (0x0FU) /*!< Bit mask for DMA_CDNE_CDNE. */ #define BS_DMA_CDNE_CDNE (4U) /*!< Bit field size in bits for DMA_CDNE_CDNE. */ /*! @brief Format value for bitfield DMA_CDNE_CDNE. */ #define BF_DMA_CDNE_CDNE(v) ((uint8_t)((uint8_t)(v) << BP_DMA_CDNE_CDNE) & BM_DMA_CDNE_CDNE) /*! @brief Set the CDNE field to a new value. */ #define BW_DMA_CDNE_CDNE(x, v) (HW_DMA_CDNE_WR(x, (HW_DMA_CDNE_RD(x) & ~BM_DMA_CDNE_CDNE) | BF_DMA_CDNE_CDNE(v))) /*@}*/ /*! * @name Register DMA_CDNE, field CADN[6] (WORZ) * * Values: * - 0 - Clears only the TCDn_CSR[DONE] bit specified in the CDNE field * - 1 - Clears all bits in TCDn_CSR[DONE] */ /*@{*/ #define BP_DMA_CDNE_CADN (6U) /*!< Bit position for DMA_CDNE_CADN. */ #define BM_DMA_CDNE_CADN (0x40U) /*!< Bit mask for DMA_CDNE_CADN. */ #define BS_DMA_CDNE_CADN (1U) /*!< Bit field size in bits for DMA_CDNE_CADN. */ /*! @brief Format value for bitfield DMA_CDNE_CADN. */ #define BF_DMA_CDNE_CADN(v) ((uint8_t)((uint8_t)(v) << BP_DMA_CDNE_CADN) & BM_DMA_CDNE_CADN) /*! @brief Set the CADN field to a new value. */ #define BW_DMA_CDNE_CADN(x, v) (BITBAND_ACCESS8(HW_DMA_CDNE_ADDR(x), BP_DMA_CDNE_CADN) = (v)) /*@}*/ /*! * @name Register DMA_CDNE, field NOP[7] (WORZ) * * Values: * - 0 - Normal operation * - 1 - No operation, ignore the other bits in this register */ /*@{*/ #define BP_DMA_CDNE_NOP (7U) /*!< Bit position for DMA_CDNE_NOP. */ #define BM_DMA_CDNE_NOP (0x80U) /*!< Bit mask for DMA_CDNE_NOP. */ #define BS_DMA_CDNE_NOP (1U) /*!< Bit field size in bits for DMA_CDNE_NOP. */ /*! @brief Format value for bitfield DMA_CDNE_NOP. */ #define BF_DMA_CDNE_NOP(v) ((uint8_t)((uint8_t)(v) << BP_DMA_CDNE_NOP) & BM_DMA_CDNE_NOP) /*! @brief Set the NOP field to a new value. */ #define BW_DMA_CDNE_NOP(x, v) (BITBAND_ACCESS8(HW_DMA_CDNE_ADDR(x), BP_DMA_CDNE_NOP) = (v)) /*@}*/ /******************************************************************************* * HW_DMA_SSRT - Set START Bit Register ******************************************************************************/ /*! * @brief HW_DMA_SSRT - Set START Bit Register (WO) * * Reset value: 0x00U * * The SSRT provides a simple memory-mapped mechanism to set the START bit in * the TCD of the given channel. The data value on a register write causes the * START bit in the corresponding transfer control descriptor to be set. Setting the * SAST bit provides a global set function, forcing all START bits to be set. If * the NOP bit is set, the command is ignored. This allows you to write * multiple-byte registers as a 32-bit word. Reads of this register return all zeroes. */ typedef union _hw_dma_ssrt { uint8_t U; struct _hw_dma_ssrt_bitfields { uint8_t SSRT : 4; /*!< [3:0] Set START Bit */ uint8_t RESERVED0 : 2; /*!< [5:4] */ uint8_t SAST : 1; /*!< [6] Set All START Bits (activates all * channels) */ uint8_t NOP : 1; /*!< [7] No Op enable */ } B; } hw_dma_ssrt_t; /*! * @name Constants and macros for entire DMA_SSRT register */ /*@{*/ #define HW_DMA_SSRT_ADDR(x) ((x) + 0x1DU) #define HW_DMA_SSRT(x) (*(__O hw_dma_ssrt_t *) HW_DMA_SSRT_ADDR(x)) #define HW_DMA_SSRT_RD(x) (HW_DMA_SSRT(x).U) #define HW_DMA_SSRT_WR(x, v) (HW_DMA_SSRT(x).U = (v)) /*@}*/ /* * Constants & macros for individual DMA_SSRT bitfields */ /*! * @name Register DMA_SSRT, field SSRT[3:0] (WORZ) * * Sets the corresponding bit in TCDn_CSR[START] */ /*@{*/ #define BP_DMA_SSRT_SSRT (0U) /*!< Bit position for DMA_SSRT_SSRT. */ #define BM_DMA_SSRT_SSRT (0x0FU) /*!< Bit mask for DMA_SSRT_SSRT. */ #define BS_DMA_SSRT_SSRT (4U) /*!< Bit field size in bits for DMA_SSRT_SSRT. */ /*! @brief Format value for bitfield DMA_SSRT_SSRT. */ #define BF_DMA_SSRT_SSRT(v) ((uint8_t)((uint8_t)(v) << BP_DMA_SSRT_SSRT) & BM_DMA_SSRT_SSRT) /*! @brief Set the SSRT field to a new value. */ #define BW_DMA_SSRT_SSRT(x, v) (HW_DMA_SSRT_WR(x, (HW_DMA_SSRT_RD(x) & ~BM_DMA_SSRT_SSRT) | BF_DMA_SSRT_SSRT(v))) /*@}*/ /*! * @name Register DMA_SSRT, field SAST[6] (WORZ) * * Values: * - 0 - Set only the TCDn_CSR[START] bit specified in the SSRT field * - 1 - Set all bits in TCDn_CSR[START] */ /*@{*/ #define BP_DMA_SSRT_SAST (6U) /*!< Bit position for DMA_SSRT_SAST. */ #define BM_DMA_SSRT_SAST (0x40U) /*!< Bit mask for DMA_SSRT_SAST. */ #define BS_DMA_SSRT_SAST (1U) /*!< Bit field size in bits for DMA_SSRT_SAST. */ /*! @brief Format value for bitfield DMA_SSRT_SAST. */ #define BF_DMA_SSRT_SAST(v) ((uint8_t)((uint8_t)(v) << BP_DMA_SSRT_SAST) & BM_DMA_SSRT_SAST) /*! @brief Set the SAST field to a new value. */ #define BW_DMA_SSRT_SAST(x, v) (BITBAND_ACCESS8(HW_DMA_SSRT_ADDR(x), BP_DMA_SSRT_SAST) = (v)) /*@}*/ /*! * @name Register DMA_SSRT, field NOP[7] (WORZ) * * Values: * - 0 - Normal operation * - 1 - No operation, ignore the other bits in this register */ /*@{*/ #define BP_DMA_SSRT_NOP (7U) /*!< Bit position for DMA_SSRT_NOP. */ #define BM_DMA_SSRT_NOP (0x80U) /*!< Bit mask for DMA_SSRT_NOP. */ #define BS_DMA_SSRT_NOP (1U) /*!< Bit field size in bits for DMA_SSRT_NOP. */ /*! @brief Format value for bitfield DMA_SSRT_NOP. */ #define BF_DMA_SSRT_NOP(v) ((uint8_t)((uint8_t)(v) << BP_DMA_SSRT_NOP) & BM_DMA_SSRT_NOP) /*! @brief Set the NOP field to a new value. */ #define BW_DMA_SSRT_NOP(x, v) (BITBAND_ACCESS8(HW_DMA_SSRT_ADDR(x), BP_DMA_SSRT_NOP) = (v)) /*@}*/ /******************************************************************************* * HW_DMA_CERR - Clear Error Register ******************************************************************************/ /*! * @brief HW_DMA_CERR - Clear Error Register (WO) * * Reset value: 0x00U * * The CERR provides a simple memory-mapped mechanism to clear a given bit in * the ERR to disable the error condition flag for a given channel. The given value * on a register write causes the corresponding bit in the ERR to be cleared. * Setting the CAEI bit provides a global clear function, forcing the ERR contents * to be cleared, clearing all channel error indicators. If the NOP bit is set, * the command is ignored. This allows you to write multiple-byte registers as a * 32-bit word. Reads of this register return all zeroes. */ typedef union _hw_dma_cerr { uint8_t U; struct _hw_dma_cerr_bitfields { uint8_t CERR : 4; /*!< [3:0] Clear Error Indicator */ uint8_t RESERVED0 : 2; /*!< [5:4] */ uint8_t CAEI : 1; /*!< [6] Clear All Error Indicators */ uint8_t NOP : 1; /*!< [7] No Op enable */ } B; } hw_dma_cerr_t; /*! * @name Constants and macros for entire DMA_CERR register */ /*@{*/ #define HW_DMA_CERR_ADDR(x) ((x) + 0x1EU) #define HW_DMA_CERR(x) (*(__O hw_dma_cerr_t *) HW_DMA_CERR_ADDR(x)) #define HW_DMA_CERR_RD(x) (HW_DMA_CERR(x).U) #define HW_DMA_CERR_WR(x, v) (HW_DMA_CERR(x).U = (v)) /*@}*/ /* * Constants & macros for individual DMA_CERR bitfields */ /*! * @name Register DMA_CERR, field CERR[3:0] (WORZ) * * Clears the corresponding bit in ERR */ /*@{*/ #define BP_DMA_CERR_CERR (0U) /*!< Bit position for DMA_CERR_CERR. */ #define BM_DMA_CERR_CERR (0x0FU) /*!< Bit mask for DMA_CERR_CERR. */ #define BS_DMA_CERR_CERR (4U) /*!< Bit field size in bits for DMA_CERR_CERR. */ /*! @brief Format value for bitfield DMA_CERR_CERR. */ #define BF_DMA_CERR_CERR(v) ((uint8_t)((uint8_t)(v) << BP_DMA_CERR_CERR) & BM_DMA_CERR_CERR) /*! @brief Set the CERR field to a new value. */ #define BW_DMA_CERR_CERR(x, v) (HW_DMA_CERR_WR(x, (HW_DMA_CERR_RD(x) & ~BM_DMA_CERR_CERR) | BF_DMA_CERR_CERR(v))) /*@}*/ /*! * @name Register DMA_CERR, field CAEI[6] (WORZ) * * Values: * - 0 - Clear only the ERR bit specified in the CERR field * - 1 - Clear all bits in ERR */ /*@{*/ #define BP_DMA_CERR_CAEI (6U) /*!< Bit position for DMA_CERR_CAEI. */ #define BM_DMA_CERR_CAEI (0x40U) /*!< Bit mask for DMA_CERR_CAEI. */ #define BS_DMA_CERR_CAEI (1U) /*!< Bit field size in bits for DMA_CERR_CAEI. */ /*! @brief Format value for bitfield DMA_CERR_CAEI. */ #define BF_DMA_CERR_CAEI(v) ((uint8_t)((uint8_t)(v) << BP_DMA_CERR_CAEI) & BM_DMA_CERR_CAEI) /*! @brief Set the CAEI field to a new value. */ #define BW_DMA_CERR_CAEI(x, v) (BITBAND_ACCESS8(HW_DMA_CERR_ADDR(x), BP_DMA_CERR_CAEI) = (v)) /*@}*/ /*! * @name Register DMA_CERR, field NOP[7] (WORZ) * * Values: * - 0 - Normal operation * - 1 - No operation, ignore the other bits in this register */ /*@{*/ #define BP_DMA_CERR_NOP (7U) /*!< Bit position for DMA_CERR_NOP. */ #define BM_DMA_CERR_NOP (0x80U) /*!< Bit mask for DMA_CERR_NOP. */ #define BS_DMA_CERR_NOP (1U) /*!< Bit field size in bits for DMA_CERR_NOP. */ /*! @brief Format value for bitfield DMA_CERR_NOP. */ #define BF_DMA_CERR_NOP(v) ((uint8_t)((uint8_t)(v) << BP_DMA_CERR_NOP) & BM_DMA_CERR_NOP) /*! @brief Set the NOP field to a new value. */ #define BW_DMA_CERR_NOP(x, v) (BITBAND_ACCESS8(HW_DMA_CERR_ADDR(x), BP_DMA_CERR_NOP) = (v)) /*@}*/ /******************************************************************************* * HW_DMA_CINT - Clear Interrupt Request Register ******************************************************************************/ /*! * @brief HW_DMA_CINT - Clear Interrupt Request Register (WO) * * Reset value: 0x00U * * The CINT provides a simple, memory-mapped mechanism to clear a given bit in * the INT to disable the interrupt request for a given channel. The given value * on a register write causes the corresponding bit in the INT to be cleared. * Setting the CAIR bit provides a global clear function, forcing the entire contents * of the INT to be cleared, disabling all DMA interrupt requests. If the NOP * bit is set, the command is ignored. This allows you to write multiple-byte * registers as a 32-bit word. Reads of this register return all zeroes. */ typedef union _hw_dma_cint { uint8_t U; struct _hw_dma_cint_bitfields { uint8_t CINT : 4; /*!< [3:0] Clear Interrupt Request */ uint8_t RESERVED0 : 2; /*!< [5:4] */ uint8_t CAIR : 1; /*!< [6] Clear All Interrupt Requests */ uint8_t NOP : 1; /*!< [7] No Op enable */ } B; } hw_dma_cint_t; /*! * @name Constants and macros for entire DMA_CINT register */ /*@{*/ #define HW_DMA_CINT_ADDR(x) ((x) + 0x1FU) #define HW_DMA_CINT(x) (*(__O hw_dma_cint_t *) HW_DMA_CINT_ADDR(x)) #define HW_DMA_CINT_RD(x) (HW_DMA_CINT(x).U) #define HW_DMA_CINT_WR(x, v) (HW_DMA_CINT(x).U = (v)) /*@}*/ /* * Constants & macros for individual DMA_CINT bitfields */ /*! * @name Register DMA_CINT, field CINT[3:0] (WORZ) * * Clears the corresponding bit in INT */ /*@{*/ #define BP_DMA_CINT_CINT (0U) /*!< Bit position for DMA_CINT_CINT. */ #define BM_DMA_CINT_CINT (0x0FU) /*!< Bit mask for DMA_CINT_CINT. */ #define BS_DMA_CINT_CINT (4U) /*!< Bit field size in bits for DMA_CINT_CINT. */ /*! @brief Format value for bitfield DMA_CINT_CINT. */ #define BF_DMA_CINT_CINT(v) ((uint8_t)((uint8_t)(v) << BP_DMA_CINT_CINT) & BM_DMA_CINT_CINT) /*! @brief Set the CINT field to a new value. */ #define BW_DMA_CINT_CINT(x, v) (HW_DMA_CINT_WR(x, (HW_DMA_CINT_RD(x) & ~BM_DMA_CINT_CINT) | BF_DMA_CINT_CINT(v))) /*@}*/ /*! * @name Register DMA_CINT, field CAIR[6] (WORZ) * * Values: * - 0 - Clear only the INT bit specified in the CINT field * - 1 - Clear all bits in INT */ /*@{*/ #define BP_DMA_CINT_CAIR (6U) /*!< Bit position for DMA_CINT_CAIR. */ #define BM_DMA_CINT_CAIR (0x40U) /*!< Bit mask for DMA_CINT_CAIR. */ #define BS_DMA_CINT_CAIR (1U) /*!< Bit field size in bits for DMA_CINT_CAIR. */ /*! @brief Format value for bitfield DMA_CINT_CAIR. */ #define BF_DMA_CINT_CAIR(v) ((uint8_t)((uint8_t)(v) << BP_DMA_CINT_CAIR) & BM_DMA_CINT_CAIR) /*! @brief Set the CAIR field to a new value. */ #define BW_DMA_CINT_CAIR(x, v) (BITBAND_ACCESS8(HW_DMA_CINT_ADDR(x), BP_DMA_CINT_CAIR) = (v)) /*@}*/ /*! * @name Register DMA_CINT, field NOP[7] (WORZ) * * Values: * - 0 - Normal operation * - 1 - No operation, ignore the other bits in this register */ /*@{*/ #define BP_DMA_CINT_NOP (7U) /*!< Bit position for DMA_CINT_NOP. */ #define BM_DMA_CINT_NOP (0x80U) /*!< Bit mask for DMA_CINT_NOP. */ #define BS_DMA_CINT_NOP (1U) /*!< Bit field size in bits for DMA_CINT_NOP. */ /*! @brief Format value for bitfield DMA_CINT_NOP. */ #define BF_DMA_CINT_NOP(v) ((uint8_t)((uint8_t)(v) << BP_DMA_CINT_NOP) & BM_DMA_CINT_NOP) /*! @brief Set the NOP field to a new value. */ #define BW_DMA_CINT_NOP(x, v) (BITBAND_ACCESS8(HW_DMA_CINT_ADDR(x), BP_DMA_CINT_NOP) = (v)) /*@}*/ /******************************************************************************* * HW_DMA_INT - Interrupt Request Register ******************************************************************************/ /*! * @brief HW_DMA_INT - Interrupt Request Register (RW) * * Reset value: 0x00000000U * * The INT register provides a bit map for the 16 channels signaling the * presence of an interrupt request for each channel. Depending on the appropriate bit * setting in the transfer-control descriptors, the eDMA engine generates an * interrupt on data transfer completion. The outputs of this register are directly * routed to the interrupt controller (INTC). During the interrupt-service routine * associated with any given channel, it is the software's responsibility to * clear the appropriate bit, negating the interrupt request. Typically, a write to * the CINT register in the interrupt service routine is used for this purpose. * The state of any given channel's interrupt request is directly affected by * writes to this register; it is also affected by writes to the CINT register. On * writes to INT, a 1 in any bit position clears the corresponding channel's * interrupt request. A zero in any bit position has no affect on the corresponding * channel's current interrupt status. The CINT register is provided so the interrupt * request for a single channel can easily be cleared without the need to * perform a read-modify-write sequence to the INT register. */ typedef union _hw_dma_int { uint32_t U; struct _hw_dma_int_bitfields { uint32_t INT0 : 1; /*!< [0] Interrupt Request 0 */ uint32_t INT1 : 1; /*!< [1] Interrupt Request 1 */ uint32_t INT2 : 1; /*!< [2] Interrupt Request 2 */ uint32_t INT3 : 1; /*!< [3] Interrupt Request 3 */ uint32_t INT4 : 1; /*!< [4] Interrupt Request 4 */ uint32_t INT5 : 1; /*!< [5] Interrupt Request 5 */ uint32_t INT6 : 1; /*!< [6] Interrupt Request 6 */ uint32_t INT7 : 1; /*!< [7] Interrupt Request 7 */ uint32_t INT8 : 1; /*!< [8] Interrupt Request 8 */ uint32_t INT9 : 1; /*!< [9] Interrupt Request 9 */ uint32_t INT10 : 1; /*!< [10] Interrupt Request 10 */ uint32_t INT11 : 1; /*!< [11] Interrupt Request 11 */ uint32_t INT12 : 1; /*!< [12] Interrupt Request 12 */ uint32_t INT13 : 1; /*!< [13] Interrupt Request 13 */ uint32_t INT14 : 1; /*!< [14] Interrupt Request 14 */ uint32_t INT15 : 1; /*!< [15] Interrupt Request 15 */ uint32_t RESERVED0 : 16; /*!< [31:16] */ } B; } hw_dma_int_t; /*! * @name Constants and macros for entire DMA_INT register */ /*@{*/ #define HW_DMA_INT_ADDR(x) ((x) + 0x24U) #define HW_DMA_INT(x) (*(__IO hw_dma_int_t *) HW_DMA_INT_ADDR(x)) #define HW_DMA_INT_RD(x) (HW_DMA_INT(x).U) #define HW_DMA_INT_WR(x, v) (HW_DMA_INT(x).U = (v)) #define HW_DMA_INT_SET(x, v) (HW_DMA_INT_WR(x, HW_DMA_INT_RD(x) | (v))) #define HW_DMA_INT_CLR(x, v) (HW_DMA_INT_WR(x, HW_DMA_INT_RD(x) & ~(v))) #define HW_DMA_INT_TOG(x, v) (HW_DMA_INT_WR(x, HW_DMA_INT_RD(x) ^ (v))) /*@}*/ /* * Constants & macros for individual DMA_INT bitfields */ /*! * @name Register DMA_INT, field INT0[0] (W1C) * * Values: * - 0 - The interrupt request for corresponding channel is cleared * - 1 - The interrupt request for corresponding channel is active */ /*@{*/ #define BP_DMA_INT_INT0 (0U) /*!< Bit position for DMA_INT_INT0. */ #define BM_DMA_INT_INT0 (0x00000001U) /*!< Bit mask for DMA_INT_INT0. */ #define BS_DMA_INT_INT0 (1U) /*!< Bit field size in bits for DMA_INT_INT0. */ /*! @brief Read current value of the DMA_INT_INT0 field. */ #define BR_DMA_INT_INT0(x) (BITBAND_ACCESS32(HW_DMA_INT_ADDR(x), BP_DMA_INT_INT0)) /*! @brief Format value for bitfield DMA_INT_INT0. */ #define BF_DMA_INT_INT0(v) ((uint32_t)((uint32_t)(v) << BP_DMA_INT_INT0) & BM_DMA_INT_INT0) /*! @brief Set the INT0 field to a new value. */ #define BW_DMA_INT_INT0(x, v) (BITBAND_ACCESS32(HW_DMA_INT_ADDR(x), BP_DMA_INT_INT0) = (v)) /*@}*/ /*! * @name Register DMA_INT, field INT1[1] (W1C) * * Values: * - 0 - The interrupt request for corresponding channel is cleared * - 1 - The interrupt request for corresponding channel is active */ /*@{*/ #define BP_DMA_INT_INT1 (1U) /*!< Bit position for DMA_INT_INT1. */ #define BM_DMA_INT_INT1 (0x00000002U) /*!< Bit mask for DMA_INT_INT1. */ #define BS_DMA_INT_INT1 (1U) /*!< Bit field size in bits for DMA_INT_INT1. */ /*! @brief Read current value of the DMA_INT_INT1 field. */ #define BR_DMA_INT_INT1(x) (BITBAND_ACCESS32(HW_DMA_INT_ADDR(x), BP_DMA_INT_INT1)) /*! @brief Format value for bitfield DMA_INT_INT1. */ #define BF_DMA_INT_INT1(v) ((uint32_t)((uint32_t)(v) << BP_DMA_INT_INT1) & BM_DMA_INT_INT1) /*! @brief Set the INT1 field to a new value. */ #define BW_DMA_INT_INT1(x, v) (BITBAND_ACCESS32(HW_DMA_INT_ADDR(x), BP_DMA_INT_INT1) = (v)) /*@}*/ /*! * @name Register DMA_INT, field INT2[2] (W1C) * * Values: * - 0 - The interrupt request for corresponding channel is cleared * - 1 - The interrupt request for corresponding channel is active */ /*@{*/ #define BP_DMA_INT_INT2 (2U) /*!< Bit position for DMA_INT_INT2. */ #define BM_DMA_INT_INT2 (0x00000004U) /*!< Bit mask for DMA_INT_INT2. */ #define BS_DMA_INT_INT2 (1U) /*!< Bit field size in bits for DMA_INT_INT2. */ /*! @brief Read current value of the DMA_INT_INT2 field. */ #define BR_DMA_INT_INT2(x) (BITBAND_ACCESS32(HW_DMA_INT_ADDR(x), BP_DMA_INT_INT2)) /*! @brief Format value for bitfield DMA_INT_INT2. */ #define BF_DMA_INT_INT2(v) ((uint32_t)((uint32_t)(v) << BP_DMA_INT_INT2) & BM_DMA_INT_INT2) /*! @brief Set the INT2 field to a new value. */ #define BW_DMA_INT_INT2(x, v) (BITBAND_ACCESS32(HW_DMA_INT_ADDR(x), BP_DMA_INT_INT2) = (v)) /*@}*/ /*! * @name Register DMA_INT, field INT3[3] (W1C) * * Values: * - 0 - The interrupt request for corresponding channel is cleared * - 1 - The interrupt request for corresponding channel is active */ /*@{*/ #define BP_DMA_INT_INT3 (3U) /*!< Bit position for DMA_INT_INT3. */ #define BM_DMA_INT_INT3 (0x00000008U) /*!< Bit mask for DMA_INT_INT3. */ #define BS_DMA_INT_INT3 (1U) /*!< Bit field size in bits for DMA_INT_INT3. */ /*! @brief Read current value of the DMA_INT_INT3 field. */ #define BR_DMA_INT_INT3(x) (BITBAND_ACCESS32(HW_DMA_INT_ADDR(x), BP_DMA_INT_INT3)) /*! @brief Format value for bitfield DMA_INT_INT3. */ #define BF_DMA_INT_INT3(v) ((uint32_t)((uint32_t)(v) << BP_DMA_INT_INT3) & BM_DMA_INT_INT3) /*! @brief Set the INT3 field to a new value. */ #define BW_DMA_INT_INT3(x, v) (BITBAND_ACCESS32(HW_DMA_INT_ADDR(x), BP_DMA_INT_INT3) = (v)) /*@}*/ /*! * @name Register DMA_INT, field INT4[4] (W1C) * * Values: * - 0 - The interrupt request for corresponding channel is cleared * - 1 - The interrupt request for corresponding channel is active */ /*@{*/ #define BP_DMA_INT_INT4 (4U) /*!< Bit position for DMA_INT_INT4. */ #define BM_DMA_INT_INT4 (0x00000010U) /*!< Bit mask for DMA_INT_INT4. */ #define BS_DMA_INT_INT4 (1U) /*!< Bit field size in bits for DMA_INT_INT4. */ /*! @brief Read current value of the DMA_INT_INT4 field. */ #define BR_DMA_INT_INT4(x) (BITBAND_ACCESS32(HW_DMA_INT_ADDR(x), BP_DMA_INT_INT4)) /*! @brief Format value for bitfield DMA_INT_INT4. */ #define BF_DMA_INT_INT4(v) ((uint32_t)((uint32_t)(v) << BP_DMA_INT_INT4) & BM_DMA_INT_INT4) /*! @brief Set the INT4 field to a new value. */ #define BW_DMA_INT_INT4(x, v) (BITBAND_ACCESS32(HW_DMA_INT_ADDR(x), BP_DMA_INT_INT4) = (v)) /*@}*/ /*! * @name Register DMA_INT, field INT5[5] (W1C) * * Values: * - 0 - The interrupt request for corresponding channel is cleared * - 1 - The interrupt request for corresponding channel is active */ /*@{*/ #define BP_DMA_INT_INT5 (5U) /*!< Bit position for DMA_INT_INT5. */ #define BM_DMA_INT_INT5 (0x00000020U) /*!< Bit mask for DMA_INT_INT5. */ #define BS_DMA_INT_INT5 (1U) /*!< Bit field size in bits for DMA_INT_INT5. */ /*! @brief Read current value of the DMA_INT_INT5 field. */ #define BR_DMA_INT_INT5(x) (BITBAND_ACCESS32(HW_DMA_INT_ADDR(x), BP_DMA_INT_INT5)) /*! @brief Format value for bitfield DMA_INT_INT5. */ #define BF_DMA_INT_INT5(v) ((uint32_t)((uint32_t)(v) << BP_DMA_INT_INT5) & BM_DMA_INT_INT5) /*! @brief Set the INT5 field to a new value. */ #define BW_DMA_INT_INT5(x, v) (BITBAND_ACCESS32(HW_DMA_INT_ADDR(x), BP_DMA_INT_INT5) = (v)) /*@}*/ /*! * @name Register DMA_INT, field INT6[6] (W1C) * * Values: * - 0 - The interrupt request for corresponding channel is cleared * - 1 - The interrupt request for corresponding channel is active */ /*@{*/ #define BP_DMA_INT_INT6 (6U) /*!< Bit position for DMA_INT_INT6. */ #define BM_DMA_INT_INT6 (0x00000040U) /*!< Bit mask for DMA_INT_INT6. */ #define BS_DMA_INT_INT6 (1U) /*!< Bit field size in bits for DMA_INT_INT6. */ /*! @brief Read current value of the DMA_INT_INT6 field. */ #define BR_DMA_INT_INT6(x) (BITBAND_ACCESS32(HW_DMA_INT_ADDR(x), BP_DMA_INT_INT6)) /*! @brief Format value for bitfield DMA_INT_INT6. */ #define BF_DMA_INT_INT6(v) ((uint32_t)((uint32_t)(v) << BP_DMA_INT_INT6) & BM_DMA_INT_INT6) /*! @brief Set the INT6 field to a new value. */ #define BW_DMA_INT_INT6(x, v) (BITBAND_ACCESS32(HW_DMA_INT_ADDR(x), BP_DMA_INT_INT6) = (v)) /*@}*/ /*! * @name Register DMA_INT, field INT7[7] (W1C) * * Values: * - 0 - The interrupt request for corresponding channel is cleared * - 1 - The interrupt request for corresponding channel is active */ /*@{*/ #define BP_DMA_INT_INT7 (7U) /*!< Bit position for DMA_INT_INT7. */ #define BM_DMA_INT_INT7 (0x00000080U) /*!< Bit mask for DMA_INT_INT7. */ #define BS_DMA_INT_INT7 (1U) /*!< Bit field size in bits for DMA_INT_INT7. */ /*! @brief Read current value of the DMA_INT_INT7 field. */ #define BR_DMA_INT_INT7(x) (BITBAND_ACCESS32(HW_DMA_INT_ADDR(x), BP_DMA_INT_INT7)) /*! @brief Format value for bitfield DMA_INT_INT7. */ #define BF_DMA_INT_INT7(v) ((uint32_t)((uint32_t)(v) << BP_DMA_INT_INT7) & BM_DMA_INT_INT7) /*! @brief Set the INT7 field to a new value. */ #define BW_DMA_INT_INT7(x, v) (BITBAND_ACCESS32(HW_DMA_INT_ADDR(x), BP_DMA_INT_INT7) = (v)) /*@}*/ /*! * @name Register DMA_INT, field INT8[8] (W1C) * * Values: * - 0 - The interrupt request for corresponding channel is cleared * - 1 - The interrupt request for corresponding channel is active */ /*@{*/ #define BP_DMA_INT_INT8 (8U) /*!< Bit position for DMA_INT_INT8. */ #define BM_DMA_INT_INT8 (0x00000100U) /*!< Bit mask for DMA_INT_INT8. */ #define BS_DMA_INT_INT8 (1U) /*!< Bit field size in bits for DMA_INT_INT8. */ /*! @brief Read current value of the DMA_INT_INT8 field. */ #define BR_DMA_INT_INT8(x) (BITBAND_ACCESS32(HW_DMA_INT_ADDR(x), BP_DMA_INT_INT8)) /*! @brief Format value for bitfield DMA_INT_INT8. */ #define BF_DMA_INT_INT8(v) ((uint32_t)((uint32_t)(v) << BP_DMA_INT_INT8) & BM_DMA_INT_INT8) /*! @brief Set the INT8 field to a new value. */ #define BW_DMA_INT_INT8(x, v) (BITBAND_ACCESS32(HW_DMA_INT_ADDR(x), BP_DMA_INT_INT8) = (v)) /*@}*/ /*! * @name Register DMA_INT, field INT9[9] (W1C) * * Values: * - 0 - The interrupt request for corresponding channel is cleared * - 1 - The interrupt request for corresponding channel is active */ /*@{*/ #define BP_DMA_INT_INT9 (9U) /*!< Bit position for DMA_INT_INT9. */ #define BM_DMA_INT_INT9 (0x00000200U) /*!< Bit mask for DMA_INT_INT9. */ #define BS_DMA_INT_INT9 (1U) /*!< Bit field size in bits for DMA_INT_INT9. */ /*! @brief Read current value of the DMA_INT_INT9 field. */ #define BR_DMA_INT_INT9(x) (BITBAND_ACCESS32(HW_DMA_INT_ADDR(x), BP_DMA_INT_INT9)) /*! @brief Format value for bitfield DMA_INT_INT9. */ #define BF_DMA_INT_INT9(v) ((uint32_t)((uint32_t)(v) << BP_DMA_INT_INT9) & BM_DMA_INT_INT9) /*! @brief Set the INT9 field to a new value. */ #define BW_DMA_INT_INT9(x, v) (BITBAND_ACCESS32(HW_DMA_INT_ADDR(x), BP_DMA_INT_INT9) = (v)) /*@}*/ /*! * @name Register DMA_INT, field INT10[10] (W1C) * * Values: * - 0 - The interrupt request for corresponding channel is cleared * - 1 - The interrupt request for corresponding channel is active */ /*@{*/ #define BP_DMA_INT_INT10 (10U) /*!< Bit position for DMA_INT_INT10. */ #define BM_DMA_INT_INT10 (0x00000400U) /*!< Bit mask for DMA_INT_INT10. */ #define BS_DMA_INT_INT10 (1U) /*!< Bit field size in bits for DMA_INT_INT10. */ /*! @brief Read current value of the DMA_INT_INT10 field. */ #define BR_DMA_INT_INT10(x) (BITBAND_ACCESS32(HW_DMA_INT_ADDR(x), BP_DMA_INT_INT10)) /*! @brief Format value for bitfield DMA_INT_INT10. */ #define BF_DMA_INT_INT10(v) ((uint32_t)((uint32_t)(v) << BP_DMA_INT_INT10) & BM_DMA_INT_INT10) /*! @brief Set the INT10 field to a new value. */ #define BW_DMA_INT_INT10(x, v) (BITBAND_ACCESS32(HW_DMA_INT_ADDR(x), BP_DMA_INT_INT10) = (v)) /*@}*/ /*! * @name Register DMA_INT, field INT11[11] (W1C) * * Values: * - 0 - The interrupt request for corresponding channel is cleared * - 1 - The interrupt request for corresponding channel is active */ /*@{*/ #define BP_DMA_INT_INT11 (11U) /*!< Bit position for DMA_INT_INT11. */ #define BM_DMA_INT_INT11 (0x00000800U) /*!< Bit mask for DMA_INT_INT11. */ #define BS_DMA_INT_INT11 (1U) /*!< Bit field size in bits for DMA_INT_INT11. */ /*! @brief Read current value of the DMA_INT_INT11 field. */ #define BR_DMA_INT_INT11(x) (BITBAND_ACCESS32(HW_DMA_INT_ADDR(x), BP_DMA_INT_INT11)) /*! @brief Format value for bitfield DMA_INT_INT11. */ #define BF_DMA_INT_INT11(v) ((uint32_t)((uint32_t)(v) << BP_DMA_INT_INT11) & BM_DMA_INT_INT11) /*! @brief Set the INT11 field to a new value. */ #define BW_DMA_INT_INT11(x, v) (BITBAND_ACCESS32(HW_DMA_INT_ADDR(x), BP_DMA_INT_INT11) = (v)) /*@}*/ /*! * @name Register DMA_INT, field INT12[12] (W1C) * * Values: * - 0 - The interrupt request for corresponding channel is cleared * - 1 - The interrupt request for corresponding channel is active */ /*@{*/ #define BP_DMA_INT_INT12 (12U) /*!< Bit position for DMA_INT_INT12. */ #define BM_DMA_INT_INT12 (0x00001000U) /*!< Bit mask for DMA_INT_INT12. */ #define BS_DMA_INT_INT12 (1U) /*!< Bit field size in bits for DMA_INT_INT12. */ /*! @brief Read current value of the DMA_INT_INT12 field. */ #define BR_DMA_INT_INT12(x) (BITBAND_ACCESS32(HW_DMA_INT_ADDR(x), BP_DMA_INT_INT12)) /*! @brief Format value for bitfield DMA_INT_INT12. */ #define BF_DMA_INT_INT12(v) ((uint32_t)((uint32_t)(v) << BP_DMA_INT_INT12) & BM_DMA_INT_INT12) /*! @brief Set the INT12 field to a new value. */ #define BW_DMA_INT_INT12(x, v) (BITBAND_ACCESS32(HW_DMA_INT_ADDR(x), BP_DMA_INT_INT12) = (v)) /*@}*/ /*! * @name Register DMA_INT, field INT13[13] (W1C) * * Values: * - 0 - The interrupt request for corresponding channel is cleared * - 1 - The interrupt request for corresponding channel is active */ /*@{*/ #define BP_DMA_INT_INT13 (13U) /*!< Bit position for DMA_INT_INT13. */ #define BM_DMA_INT_INT13 (0x00002000U) /*!< Bit mask for DMA_INT_INT13. */ #define BS_DMA_INT_INT13 (1U) /*!< Bit field size in bits for DMA_INT_INT13. */ /*! @brief Read current value of the DMA_INT_INT13 field. */ #define BR_DMA_INT_INT13(x) (BITBAND_ACCESS32(HW_DMA_INT_ADDR(x), BP_DMA_INT_INT13)) /*! @brief Format value for bitfield DMA_INT_INT13. */ #define BF_DMA_INT_INT13(v) ((uint32_t)((uint32_t)(v) << BP_DMA_INT_INT13) & BM_DMA_INT_INT13) /*! @brief Set the INT13 field to a new value. */ #define BW_DMA_INT_INT13(x, v) (BITBAND_ACCESS32(HW_DMA_INT_ADDR(x), BP_DMA_INT_INT13) = (v)) /*@}*/ /*! * @name Register DMA_INT, field INT14[14] (W1C) * * Values: * - 0 - The interrupt request for corresponding channel is cleared * - 1 - The interrupt request for corresponding channel is active */ /*@{*/ #define BP_DMA_INT_INT14 (14U) /*!< Bit position for DMA_INT_INT14. */ #define BM_DMA_INT_INT14 (0x00004000U) /*!< Bit mask for DMA_INT_INT14. */ #define BS_DMA_INT_INT14 (1U) /*!< Bit field size in bits for DMA_INT_INT14. */ /*! @brief Read current value of the DMA_INT_INT14 field. */ #define BR_DMA_INT_INT14(x) (BITBAND_ACCESS32(HW_DMA_INT_ADDR(x), BP_DMA_INT_INT14)) /*! @brief Format value for bitfield DMA_INT_INT14. */ #define BF_DMA_INT_INT14(v) ((uint32_t)((uint32_t)(v) << BP_DMA_INT_INT14) & BM_DMA_INT_INT14) /*! @brief Set the INT14 field to a new value. */ #define BW_DMA_INT_INT14(x, v) (BITBAND_ACCESS32(HW_DMA_INT_ADDR(x), BP_DMA_INT_INT14) = (v)) /*@}*/ /*! * @name Register DMA_INT, field INT15[15] (W1C) * * Values: * - 0 - The interrupt request for corresponding channel is cleared * - 1 - The interrupt request for corresponding channel is active */ /*@{*/ #define BP_DMA_INT_INT15 (15U) /*!< Bit position for DMA_INT_INT15. */ #define BM_DMA_INT_INT15 (0x00008000U) /*!< Bit mask for DMA_INT_INT15. */ #define BS_DMA_INT_INT15 (1U) /*!< Bit field size in bits for DMA_INT_INT15. */ /*! @brief Read current value of the DMA_INT_INT15 field. */ #define BR_DMA_INT_INT15(x) (BITBAND_ACCESS32(HW_DMA_INT_ADDR(x), BP_DMA_INT_INT15)) /*! @brief Format value for bitfield DMA_INT_INT15. */ #define BF_DMA_INT_INT15(v) ((uint32_t)((uint32_t)(v) << BP_DMA_INT_INT15) & BM_DMA_INT_INT15) /*! @brief Set the INT15 field to a new value. */ #define BW_DMA_INT_INT15(x, v) (BITBAND_ACCESS32(HW_DMA_INT_ADDR(x), BP_DMA_INT_INT15) = (v)) /*@}*/ /******************************************************************************* * HW_DMA_ERR - Error Register ******************************************************************************/ /*! * @brief HW_DMA_ERR - Error Register (RW) * * Reset value: 0x00000000U * * The ERR provides a bit map for the 16 channels, signaling the presence of an * error for each channel. The eDMA engine signals the occurrence of an error * condition by setting the appropriate bit in this register. The outputs of this * register are enabled by the contents of the EEI, and then routed to the * interrupt controller. During the execution of the interrupt-service routine associated * with any DMA errors, it is software's responsibility to clear the appropriate * bit, negating the error-interrupt request. Typically, a write to the CERR in * the interrupt-service routine is used for this purpose. The normal DMA channel * completion indicators (setting the transfer control descriptor DONE flag and * the possible assertion of an interrupt request) are not affected when an error * is detected. The contents of this register can also be polled because a * non-zero value indicates the presence of a channel error regardless of the state of * the EEI. The state of any given channel's error indicators is affected by * writes to this register; it is also affected by writes to the CERR. On writes to * the ERR, a one in any bit position clears the corresponding channel's error * status. A zero in any bit position has no affect on the corresponding channel's * current error status. The CERR is provided so the error indicator for a single * channel can easily be cleared. */ typedef union _hw_dma_err { uint32_t U; struct _hw_dma_err_bitfields { uint32_t ERR0 : 1; /*!< [0] Error In Channel 0 */ uint32_t ERR1 : 1; /*!< [1] Error In Channel 1 */ uint32_t ERR2 : 1; /*!< [2] Error In Channel 2 */ uint32_t ERR3 : 1; /*!< [3] Error In Channel 3 */ uint32_t ERR4 : 1; /*!< [4] Error In Channel 4 */ uint32_t ERR5 : 1; /*!< [5] Error In Channel 5 */ uint32_t ERR6 : 1; /*!< [6] Error In Channel 6 */ uint32_t ERR7 : 1; /*!< [7] Error In Channel 7 */ uint32_t ERR8 : 1; /*!< [8] Error In Channel 8 */ uint32_t ERR9 : 1; /*!< [9] Error In Channel 9 */ uint32_t ERR10 : 1; /*!< [10] Error In Channel 10 */ uint32_t ERR11 : 1; /*!< [11] Error In Channel 11 */ uint32_t ERR12 : 1; /*!< [12] Error In Channel 12 */ uint32_t ERR13 : 1; /*!< [13] Error In Channel 13 */ uint32_t ERR14 : 1; /*!< [14] Error In Channel 14 */ uint32_t ERR15 : 1; /*!< [15] Error In Channel 15 */ uint32_t RESERVED0 : 16; /*!< [31:16] */ } B; } hw_dma_err_t; /*! * @name Constants and macros for entire DMA_ERR register */ /*@{*/ #define HW_DMA_ERR_ADDR(x) ((x) + 0x2CU) #define HW_DMA_ERR(x) (*(__IO hw_dma_err_t *) HW_DMA_ERR_ADDR(x)) #define HW_DMA_ERR_RD(x) (HW_DMA_ERR(x).U) #define HW_DMA_ERR_WR(x, v) (HW_DMA_ERR(x).U = (v)) #define HW_DMA_ERR_SET(x, v) (HW_DMA_ERR_WR(x, HW_DMA_ERR_RD(x) | (v))) #define HW_DMA_ERR_CLR(x, v) (HW_DMA_ERR_WR(x, HW_DMA_ERR_RD(x) & ~(v))) #define HW_DMA_ERR_TOG(x, v) (HW_DMA_ERR_WR(x, HW_DMA_ERR_RD(x) ^ (v))) /*@}*/ /* * Constants & macros for individual DMA_ERR bitfields */ /*! * @name Register DMA_ERR, field ERR0[0] (W1C) * * Values: * - 0 - An error in the corresponding channel has not occurred * - 1 - An error in the corresponding channel has occurred */ /*@{*/ #define BP_DMA_ERR_ERR0 (0U) /*!< Bit position for DMA_ERR_ERR0. */ #define BM_DMA_ERR_ERR0 (0x00000001U) /*!< Bit mask for DMA_ERR_ERR0. */ #define BS_DMA_ERR_ERR0 (1U) /*!< Bit field size in bits for DMA_ERR_ERR0. */ /*! @brief Read current value of the DMA_ERR_ERR0 field. */ #define BR_DMA_ERR_ERR0(x) (BITBAND_ACCESS32(HW_DMA_ERR_ADDR(x), BP_DMA_ERR_ERR0)) /*! @brief Format value for bitfield DMA_ERR_ERR0. */ #define BF_DMA_ERR_ERR0(v) ((uint32_t)((uint32_t)(v) << BP_DMA_ERR_ERR0) & BM_DMA_ERR_ERR0) /*! @brief Set the ERR0 field to a new value. */ #define BW_DMA_ERR_ERR0(x, v) (BITBAND_ACCESS32(HW_DMA_ERR_ADDR(x), BP_DMA_ERR_ERR0) = (v)) /*@}*/ /*! * @name Register DMA_ERR, field ERR1[1] (W1C) * * Values: * - 0 - An error in the corresponding channel has not occurred * - 1 - An error in the corresponding channel has occurred */ /*@{*/ #define BP_DMA_ERR_ERR1 (1U) /*!< Bit position for DMA_ERR_ERR1. */ #define BM_DMA_ERR_ERR1 (0x00000002U) /*!< Bit mask for DMA_ERR_ERR1. */ #define BS_DMA_ERR_ERR1 (1U) /*!< Bit field size in bits for DMA_ERR_ERR1. */ /*! @brief Read current value of the DMA_ERR_ERR1 field. */ #define BR_DMA_ERR_ERR1(x) (BITBAND_ACCESS32(HW_DMA_ERR_ADDR(x), BP_DMA_ERR_ERR1)) /*! @brief Format value for bitfield DMA_ERR_ERR1. */ #define BF_DMA_ERR_ERR1(v) ((uint32_t)((uint32_t)(v) << BP_DMA_ERR_ERR1) & BM_DMA_ERR_ERR1) /*! @brief Set the ERR1 field to a new value. */ #define BW_DMA_ERR_ERR1(x, v) (BITBAND_ACCESS32(HW_DMA_ERR_ADDR(x), BP_DMA_ERR_ERR1) = (v)) /*@}*/ /*! * @name Register DMA_ERR, field ERR2[2] (W1C) * * Values: * - 0 - An error in the corresponding channel has not occurred * - 1 - An error in the corresponding channel has occurred */ /*@{*/ #define BP_DMA_ERR_ERR2 (2U) /*!< Bit position for DMA_ERR_ERR2. */ #define BM_DMA_ERR_ERR2 (0x00000004U) /*!< Bit mask for DMA_ERR_ERR2. */ #define BS_DMA_ERR_ERR2 (1U) /*!< Bit field size in bits for DMA_ERR_ERR2. */ /*! @brief Read current value of the DMA_ERR_ERR2 field. */ #define BR_DMA_ERR_ERR2(x) (BITBAND_ACCESS32(HW_DMA_ERR_ADDR(x), BP_DMA_ERR_ERR2)) /*! @brief Format value for bitfield DMA_ERR_ERR2. */ #define BF_DMA_ERR_ERR2(v) ((uint32_t)((uint32_t)(v) << BP_DMA_ERR_ERR2) & BM_DMA_ERR_ERR2) /*! @brief Set the ERR2 field to a new value. */ #define BW_DMA_ERR_ERR2(x, v) (BITBAND_ACCESS32(HW_DMA_ERR_ADDR(x), BP_DMA_ERR_ERR2) = (v)) /*@}*/ /*! * @name Register DMA_ERR, field ERR3[3] (W1C) * * Values: * - 0 - An error in the corresponding channel has not occurred * - 1 - An error in the corresponding channel has occurred */ /*@{*/ #define BP_DMA_ERR_ERR3 (3U) /*!< Bit position for DMA_ERR_ERR3. */ #define BM_DMA_ERR_ERR3 (0x00000008U) /*!< Bit mask for DMA_ERR_ERR3. */ #define BS_DMA_ERR_ERR3 (1U) /*!< Bit field size in bits for DMA_ERR_ERR3. */ /*! @brief Read current value of the DMA_ERR_ERR3 field. */ #define BR_DMA_ERR_ERR3(x) (BITBAND_ACCESS32(HW_DMA_ERR_ADDR(x), BP_DMA_ERR_ERR3)) /*! @brief Format value for bitfield DMA_ERR_ERR3. */ #define BF_DMA_ERR_ERR3(v) ((uint32_t)((uint32_t)(v) << BP_DMA_ERR_ERR3) & BM_DMA_ERR_ERR3) /*! @brief Set the ERR3 field to a new value. */ #define BW_DMA_ERR_ERR3(x, v) (BITBAND_ACCESS32(HW_DMA_ERR_ADDR(x), BP_DMA_ERR_ERR3) = (v)) /*@}*/ /*! * @name Register DMA_ERR, field ERR4[4] (W1C) * * Values: * - 0 - An error in the corresponding channel has not occurred * - 1 - An error in the corresponding channel has occurred */ /*@{*/ #define BP_DMA_ERR_ERR4 (4U) /*!< Bit position for DMA_ERR_ERR4. */ #define BM_DMA_ERR_ERR4 (0x00000010U) /*!< Bit mask for DMA_ERR_ERR4. */ #define BS_DMA_ERR_ERR4 (1U) /*!< Bit field size in bits for DMA_ERR_ERR4. */ /*! @brief Read current value of the DMA_ERR_ERR4 field. */ #define BR_DMA_ERR_ERR4(x) (BITBAND_ACCESS32(HW_DMA_ERR_ADDR(x), BP_DMA_ERR_ERR4)) /*! @brief Format value for bitfield DMA_ERR_ERR4. */ #define BF_DMA_ERR_ERR4(v) ((uint32_t)((uint32_t)(v) << BP_DMA_ERR_ERR4) & BM_DMA_ERR_ERR4) /*! @brief Set the ERR4 field to a new value. */ #define BW_DMA_ERR_ERR4(x, v) (BITBAND_ACCESS32(HW_DMA_ERR_ADDR(x), BP_DMA_ERR_ERR4) = (v)) /*@}*/ /*! * @name Register DMA_ERR, field ERR5[5] (W1C) * * Values: * - 0 - An error in the corresponding channel has not occurred * - 1 - An error in the corresponding channel has occurred */ /*@{*/ #define BP_DMA_ERR_ERR5 (5U) /*!< Bit position for DMA_ERR_ERR5. */ #define BM_DMA_ERR_ERR5 (0x00000020U) /*!< Bit mask for DMA_ERR_ERR5. */ #define BS_DMA_ERR_ERR5 (1U) /*!< Bit field size in bits for DMA_ERR_ERR5. */ /*! @brief Read current value of the DMA_ERR_ERR5 field. */ #define BR_DMA_ERR_ERR5(x) (BITBAND_ACCESS32(HW_DMA_ERR_ADDR(x), BP_DMA_ERR_ERR5)) /*! @brief Format value for bitfield DMA_ERR_ERR5. */ #define BF_DMA_ERR_ERR5(v) ((uint32_t)((uint32_t)(v) << BP_DMA_ERR_ERR5) & BM_DMA_ERR_ERR5) /*! @brief Set the ERR5 field to a new value. */ #define BW_DMA_ERR_ERR5(x, v) (BITBAND_ACCESS32(HW_DMA_ERR_ADDR(x), BP_DMA_ERR_ERR5) = (v)) /*@}*/ /*! * @name Register DMA_ERR, field ERR6[6] (W1C) * * Values: * - 0 - An error in the corresponding channel has not occurred * - 1 - An error in the corresponding channel has occurred */ /*@{*/ #define BP_DMA_ERR_ERR6 (6U) /*!< Bit position for DMA_ERR_ERR6. */ #define BM_DMA_ERR_ERR6 (0x00000040U) /*!< Bit mask for DMA_ERR_ERR6. */ #define BS_DMA_ERR_ERR6 (1U) /*!< Bit field size in bits for DMA_ERR_ERR6. */ /*! @brief Read current value of the DMA_ERR_ERR6 field. */ #define BR_DMA_ERR_ERR6(x) (BITBAND_ACCESS32(HW_DMA_ERR_ADDR(x), BP_DMA_ERR_ERR6)) /*! @brief Format value for bitfield DMA_ERR_ERR6. */ #define BF_DMA_ERR_ERR6(v) ((uint32_t)((uint32_t)(v) << BP_DMA_ERR_ERR6) & BM_DMA_ERR_ERR6) /*! @brief Set the ERR6 field to a new value. */ #define BW_DMA_ERR_ERR6(x, v) (BITBAND_ACCESS32(HW_DMA_ERR_ADDR(x), BP_DMA_ERR_ERR6) = (v)) /*@}*/ /*! * @name Register DMA_ERR, field ERR7[7] (W1C) * * Values: * - 0 - An error in the corresponding channel has not occurred * - 1 - An error in the corresponding channel has occurred */ /*@{*/ #define BP_DMA_ERR_ERR7 (7U) /*!< Bit position for DMA_ERR_ERR7. */ #define BM_DMA_ERR_ERR7 (0x00000080U) /*!< Bit mask for DMA_ERR_ERR7. */ #define BS_DMA_ERR_ERR7 (1U) /*!< Bit field size in bits for DMA_ERR_ERR7. */ /*! @brief Read current value of the DMA_ERR_ERR7 field. */ #define BR_DMA_ERR_ERR7(x) (BITBAND_ACCESS32(HW_DMA_ERR_ADDR(x), BP_DMA_ERR_ERR7)) /*! @brief Format value for bitfield DMA_ERR_ERR7. */ #define BF_DMA_ERR_ERR7(v) ((uint32_t)((uint32_t)(v) << BP_DMA_ERR_ERR7) & BM_DMA_ERR_ERR7) /*! @brief Set the ERR7 field to a new value. */ #define BW_DMA_ERR_ERR7(x, v) (BITBAND_ACCESS32(HW_DMA_ERR_ADDR(x), BP_DMA_ERR_ERR7) = (v)) /*@}*/ /*! * @name Register DMA_ERR, field ERR8[8] (W1C) * * Values: * - 0 - An error in the corresponding channel has not occurred * - 1 - An error in the corresponding channel has occurred */ /*@{*/ #define BP_DMA_ERR_ERR8 (8U) /*!< Bit position for DMA_ERR_ERR8. */ #define BM_DMA_ERR_ERR8 (0x00000100U) /*!< Bit mask for DMA_ERR_ERR8. */ #define BS_DMA_ERR_ERR8 (1U) /*!< Bit field size in bits for DMA_ERR_ERR8. */ /*! @brief Read current value of the DMA_ERR_ERR8 field. */ #define BR_DMA_ERR_ERR8(x) (BITBAND_ACCESS32(HW_DMA_ERR_ADDR(x), BP_DMA_ERR_ERR8)) /*! @brief Format value for bitfield DMA_ERR_ERR8. */ #define BF_DMA_ERR_ERR8(v) ((uint32_t)((uint32_t)(v) << BP_DMA_ERR_ERR8) & BM_DMA_ERR_ERR8) /*! @brief Set the ERR8 field to a new value. */ #define BW_DMA_ERR_ERR8(x, v) (BITBAND_ACCESS32(HW_DMA_ERR_ADDR(x), BP_DMA_ERR_ERR8) = (v)) /*@}*/ /*! * @name Register DMA_ERR, field ERR9[9] (W1C) * * Values: * - 0 - An error in the corresponding channel has not occurred * - 1 - An error in the corresponding channel has occurred */ /*@{*/ #define BP_DMA_ERR_ERR9 (9U) /*!< Bit position for DMA_ERR_ERR9. */ #define BM_DMA_ERR_ERR9 (0x00000200U) /*!< Bit mask for DMA_ERR_ERR9. */ #define BS_DMA_ERR_ERR9 (1U) /*!< Bit field size in bits for DMA_ERR_ERR9. */ /*! @brief Read current value of the DMA_ERR_ERR9 field. */ #define BR_DMA_ERR_ERR9(x) (BITBAND_ACCESS32(HW_DMA_ERR_ADDR(x), BP_DMA_ERR_ERR9)) /*! @brief Format value for bitfield DMA_ERR_ERR9. */ #define BF_DMA_ERR_ERR9(v) ((uint32_t)((uint32_t)(v) << BP_DMA_ERR_ERR9) & BM_DMA_ERR_ERR9) /*! @brief Set the ERR9 field to a new value. */ #define BW_DMA_ERR_ERR9(x, v) (BITBAND_ACCESS32(HW_DMA_ERR_ADDR(x), BP_DMA_ERR_ERR9) = (v)) /*@}*/ /*! * @name Register DMA_ERR, field ERR10[10] (W1C) * * Values: * - 0 - An error in the corresponding channel has not occurred * - 1 - An error in the corresponding channel has occurred */ /*@{*/ #define BP_DMA_ERR_ERR10 (10U) /*!< Bit position for DMA_ERR_ERR10. */ #define BM_DMA_ERR_ERR10 (0x00000400U) /*!< Bit mask for DMA_ERR_ERR10. */ #define BS_DMA_ERR_ERR10 (1U) /*!< Bit field size in bits for DMA_ERR_ERR10. */ /*! @brief Read current value of the DMA_ERR_ERR10 field. */ #define BR_DMA_ERR_ERR10(x) (BITBAND_ACCESS32(HW_DMA_ERR_ADDR(x), BP_DMA_ERR_ERR10)) /*! @brief Format value for bitfield DMA_ERR_ERR10. */ #define BF_DMA_ERR_ERR10(v) ((uint32_t)((uint32_t)(v) << BP_DMA_ERR_ERR10) & BM_DMA_ERR_ERR10) /*! @brief Set the ERR10 field to a new value. */ #define BW_DMA_ERR_ERR10(x, v) (BITBAND_ACCESS32(HW_DMA_ERR_ADDR(x), BP_DMA_ERR_ERR10) = (v)) /*@}*/ /*! * @name Register DMA_ERR, field ERR11[11] (W1C) * * Values: * - 0 - An error in the corresponding channel has not occurred * - 1 - An error in the corresponding channel has occurred */ /*@{*/ #define BP_DMA_ERR_ERR11 (11U) /*!< Bit position for DMA_ERR_ERR11. */ #define BM_DMA_ERR_ERR11 (0x00000800U) /*!< Bit mask for DMA_ERR_ERR11. */ #define BS_DMA_ERR_ERR11 (1U) /*!< Bit field size in bits for DMA_ERR_ERR11. */ /*! @brief Read current value of the DMA_ERR_ERR11 field. */ #define BR_DMA_ERR_ERR11(x) (BITBAND_ACCESS32(HW_DMA_ERR_ADDR(x), BP_DMA_ERR_ERR11)) /*! @brief Format value for bitfield DMA_ERR_ERR11. */ #define BF_DMA_ERR_ERR11(v) ((uint32_t)((uint32_t)(v) << BP_DMA_ERR_ERR11) & BM_DMA_ERR_ERR11) /*! @brief Set the ERR11 field to a new value. */ #define BW_DMA_ERR_ERR11(x, v) (BITBAND_ACCESS32(HW_DMA_ERR_ADDR(x), BP_DMA_ERR_ERR11) = (v)) /*@}*/ /*! * @name Register DMA_ERR, field ERR12[12] (W1C) * * Values: * - 0 - An error in the corresponding channel has not occurred * - 1 - An error in the corresponding channel has occurred */ /*@{*/ #define BP_DMA_ERR_ERR12 (12U) /*!< Bit position for DMA_ERR_ERR12. */ #define BM_DMA_ERR_ERR12 (0x00001000U) /*!< Bit mask for DMA_ERR_ERR12. */ #define BS_DMA_ERR_ERR12 (1U) /*!< Bit field size in bits for DMA_ERR_ERR12. */ /*! @brief Read current value of the DMA_ERR_ERR12 field. */ #define BR_DMA_ERR_ERR12(x) (BITBAND_ACCESS32(HW_DMA_ERR_ADDR(x), BP_DMA_ERR_ERR12)) /*! @brief Format value for bitfield DMA_ERR_ERR12. */ #define BF_DMA_ERR_ERR12(v) ((uint32_t)((uint32_t)(v) << BP_DMA_ERR_ERR12) & BM_DMA_ERR_ERR12) /*! @brief Set the ERR12 field to a new value. */ #define BW_DMA_ERR_ERR12(x, v) (BITBAND_ACCESS32(HW_DMA_ERR_ADDR(x), BP_DMA_ERR_ERR12) = (v)) /*@}*/ /*! * @name Register DMA_ERR, field ERR13[13] (W1C) * * Values: * - 0 - An error in the corresponding channel has not occurred * - 1 - An error in the corresponding channel has occurred */ /*@{*/ #define BP_DMA_ERR_ERR13 (13U) /*!< Bit position for DMA_ERR_ERR13. */ #define BM_DMA_ERR_ERR13 (0x00002000U) /*!< Bit mask for DMA_ERR_ERR13. */ #define BS_DMA_ERR_ERR13 (1U) /*!< Bit field size in bits for DMA_ERR_ERR13. */ /*! @brief Read current value of the DMA_ERR_ERR13 field. */ #define BR_DMA_ERR_ERR13(x) (BITBAND_ACCESS32(HW_DMA_ERR_ADDR(x), BP_DMA_ERR_ERR13)) /*! @brief Format value for bitfield DMA_ERR_ERR13. */ #define BF_DMA_ERR_ERR13(v) ((uint32_t)((uint32_t)(v) << BP_DMA_ERR_ERR13) & BM_DMA_ERR_ERR13) /*! @brief Set the ERR13 field to a new value. */ #define BW_DMA_ERR_ERR13(x, v) (BITBAND_ACCESS32(HW_DMA_ERR_ADDR(x), BP_DMA_ERR_ERR13) = (v)) /*@}*/ /*! * @name Register DMA_ERR, field ERR14[14] (W1C) * * Values: * - 0 - An error in the corresponding channel has not occurred * - 1 - An error in the corresponding channel has occurred */ /*@{*/ #define BP_DMA_ERR_ERR14 (14U) /*!< Bit position for DMA_ERR_ERR14. */ #define BM_DMA_ERR_ERR14 (0x00004000U) /*!< Bit mask for DMA_ERR_ERR14. */ #define BS_DMA_ERR_ERR14 (1U) /*!< Bit field size in bits for DMA_ERR_ERR14. */ /*! @brief Read current value of the DMA_ERR_ERR14 field. */ #define BR_DMA_ERR_ERR14(x) (BITBAND_ACCESS32(HW_DMA_ERR_ADDR(x), BP_DMA_ERR_ERR14)) /*! @brief Format value for bitfield DMA_ERR_ERR14. */ #define BF_DMA_ERR_ERR14(v) ((uint32_t)((uint32_t)(v) << BP_DMA_ERR_ERR14) & BM_DMA_ERR_ERR14) /*! @brief Set the ERR14 field to a new value. */ #define BW_DMA_ERR_ERR14(x, v) (BITBAND_ACCESS32(HW_DMA_ERR_ADDR(x), BP_DMA_ERR_ERR14) = (v)) /*@}*/ /*! * @name Register DMA_ERR, field ERR15[15] (W1C) * * Values: * - 0 - An error in the corresponding channel has not occurred * - 1 - An error in the corresponding channel has occurred */ /*@{*/ #define BP_DMA_ERR_ERR15 (15U) /*!< Bit position for DMA_ERR_ERR15. */ #define BM_DMA_ERR_ERR15 (0x00008000U) /*!< Bit mask for DMA_ERR_ERR15. */ #define BS_DMA_ERR_ERR15 (1U) /*!< Bit field size in bits for DMA_ERR_ERR15. */ /*! @brief Read current value of the DMA_ERR_ERR15 field. */ #define BR_DMA_ERR_ERR15(x) (BITBAND_ACCESS32(HW_DMA_ERR_ADDR(x), BP_DMA_ERR_ERR15)) /*! @brief Format value for bitfield DMA_ERR_ERR15. */ #define BF_DMA_ERR_ERR15(v) ((uint32_t)((uint32_t)(v) << BP_DMA_ERR_ERR15) & BM_DMA_ERR_ERR15) /*! @brief Set the ERR15 field to a new value. */ #define BW_DMA_ERR_ERR15(x, v) (BITBAND_ACCESS32(HW_DMA_ERR_ADDR(x), BP_DMA_ERR_ERR15) = (v)) /*@}*/ /******************************************************************************* * HW_DMA_HRS - Hardware Request Status Register ******************************************************************************/ /*! * @brief HW_DMA_HRS - Hardware Request Status Register (RO) * * Reset value: 0x00000000U * * The HRS register provides a bit map for the DMA channels, signaling the * presence of a hardware request for each channel. The hardware request status bits * reflect the current state of the register and qualified (via the ERQ fields) * DMA request signals as seen by the DMA's arbitration logic. This view into the * hardware request signals may be used for debug purposes. These bits reflect the * state of the request as seen by the arbitration logic. Therefore, this status * is affected by the ERQ bits. */ typedef union _hw_dma_hrs { uint32_t U; struct _hw_dma_hrs_bitfields { uint32_t HRS0 : 1; /*!< [0] Hardware Request Status Channel 0 */ uint32_t HRS1 : 1; /*!< [1] Hardware Request Status Channel 1 */ uint32_t HRS2 : 1; /*!< [2] Hardware Request Status Channel 2 */ uint32_t HRS3 : 1; /*!< [3] Hardware Request Status Channel 3 */ uint32_t HRS4 : 1; /*!< [4] Hardware Request Status Channel 4 */ uint32_t HRS5 : 1; /*!< [5] Hardware Request Status Channel 5 */ uint32_t HRS6 : 1; /*!< [6] Hardware Request Status Channel 6 */ uint32_t HRS7 : 1; /*!< [7] Hardware Request Status Channel 7 */ uint32_t HRS8 : 1; /*!< [8] Hardware Request Status Channel 8 */ uint32_t HRS9 : 1; /*!< [9] Hardware Request Status Channel 9 */ uint32_t HRS10 : 1; /*!< [10] Hardware Request Status Channel 10 */ uint32_t HRS11 : 1; /*!< [11] Hardware Request Status Channel 11 */ uint32_t HRS12 : 1; /*!< [12] Hardware Request Status Channel 12 */ uint32_t HRS13 : 1; /*!< [13] Hardware Request Status Channel 13 */ uint32_t HRS14 : 1; /*!< [14] Hardware Request Status Channel 14 */ uint32_t HRS15 : 1; /*!< [15] Hardware Request Status Channel 15 */ uint32_t RESERVED0 : 16; /*!< [31:16] Reserved */ } B; } hw_dma_hrs_t; /*! * @name Constants and macros for entire DMA_HRS register */ /*@{*/ #define HW_DMA_HRS_ADDR(x) ((x) + 0x34U) #define HW_DMA_HRS(x) (*(__I hw_dma_hrs_t *) HW_DMA_HRS_ADDR(x)) #define HW_DMA_HRS_RD(x) (HW_DMA_HRS(x).U) /*@}*/ /* * Constants & macros for individual DMA_HRS bitfields */ /*! * @name Register DMA_HRS, field HRS0[0] (RO) * * The HRS bit for its respective channel remains asserted for the period when a * Hardware Request is Present on the Channel. After the Request is completed * and Channel is free , the HRS bit is automatically cleared by hardware. * * Values: * - 0 - A hardware service request for channel 0 is not present * - 1 - A hardware service request for channel 0 is present */ /*@{*/ #define BP_DMA_HRS_HRS0 (0U) /*!< Bit position for DMA_HRS_HRS0. */ #define BM_DMA_HRS_HRS0 (0x00000001U) /*!< Bit mask for DMA_HRS_HRS0. */ #define BS_DMA_HRS_HRS0 (1U) /*!< Bit field size in bits for DMA_HRS_HRS0. */ /*! @brief Read current value of the DMA_HRS_HRS0 field. */ #define BR_DMA_HRS_HRS0(x) (BITBAND_ACCESS32(HW_DMA_HRS_ADDR(x), BP_DMA_HRS_HRS0)) /*@}*/ /*! * @name Register DMA_HRS, field HRS1[1] (RO) * * The HRS bit for its respective channel remains asserted for the period when a * Hardware Request is Present on the Channel. After the Request is completed * and Channel is free , the HRS bit is automatically cleared by hardware. * * Values: * - 0 - A hardware service request for channel 1 is not present * - 1 - A hardware service request for channel 1 is present */ /*@{*/ #define BP_DMA_HRS_HRS1 (1U) /*!< Bit position for DMA_HRS_HRS1. */ #define BM_DMA_HRS_HRS1 (0x00000002U) /*!< Bit mask for DMA_HRS_HRS1. */ #define BS_DMA_HRS_HRS1 (1U) /*!< Bit field size in bits for DMA_HRS_HRS1. */ /*! @brief Read current value of the DMA_HRS_HRS1 field. */ #define BR_DMA_HRS_HRS1(x) (BITBAND_ACCESS32(HW_DMA_HRS_ADDR(x), BP_DMA_HRS_HRS1)) /*@}*/ /*! * @name Register DMA_HRS, field HRS2[2] (RO) * * The HRS bit for its respective channel remains asserted for the period when a * Hardware Request is Present on the Channel. After the Request is completed * and Channel is free , the HRS bit is automatically cleared by hardware. * * Values: * - 0 - A hardware service request for channel 2 is not present * - 1 - A hardware service request for channel 2 is present */ /*@{*/ #define BP_DMA_HRS_HRS2 (2U) /*!< Bit position for DMA_HRS_HRS2. */ #define BM_DMA_HRS_HRS2 (0x00000004U) /*!< Bit mask for DMA_HRS_HRS2. */ #define BS_DMA_HRS_HRS2 (1U) /*!< Bit field size in bits for DMA_HRS_HRS2. */ /*! @brief Read current value of the DMA_HRS_HRS2 field. */ #define BR_DMA_HRS_HRS2(x) (BITBAND_ACCESS32(HW_DMA_HRS_ADDR(x), BP_DMA_HRS_HRS2)) /*@}*/ /*! * @name Register DMA_HRS, field HRS3[3] (RO) * * The HRS bit for its respective channel remains asserted for the period when a * Hardware Request is Present on the Channel. After the Request is completed * and Channel is free , the HRS bit is automatically cleared by hardware. * * Values: * - 0 - A hardware service request for channel 3 is not present * - 1 - A hardware service request for channel 3 is present */ /*@{*/ #define BP_DMA_HRS_HRS3 (3U) /*!< Bit position for DMA_HRS_HRS3. */ #define BM_DMA_HRS_HRS3 (0x00000008U) /*!< Bit mask for DMA_HRS_HRS3. */ #define BS_DMA_HRS_HRS3 (1U) /*!< Bit field size in bits for DMA_HRS_HRS3. */ /*! @brief Read current value of the DMA_HRS_HRS3 field. */ #define BR_DMA_HRS_HRS3(x) (BITBAND_ACCESS32(HW_DMA_HRS_ADDR(x), BP_DMA_HRS_HRS3)) /*@}*/ /*! * @name Register DMA_HRS, field HRS4[4] (RO) * * The HRS bit for its respective channel remains asserted for the period when a * Hardware Request is Present on the Channel. After the Request is completed * and Channel is free , the HRS bit is automatically cleared by hardware. * * Values: * - 0 - A hardware service request for channel 4 is not present * - 1 - A hardware service request for channel 4 is present */ /*@{*/ #define BP_DMA_HRS_HRS4 (4U) /*!< Bit position for DMA_HRS_HRS4. */ #define BM_DMA_HRS_HRS4 (0x00000010U) /*!< Bit mask for DMA_HRS_HRS4. */ #define BS_DMA_HRS_HRS4 (1U) /*!< Bit field size in bits for DMA_HRS_HRS4. */ /*! @brief Read current value of the DMA_HRS_HRS4 field. */ #define BR_DMA_HRS_HRS4(x) (BITBAND_ACCESS32(HW_DMA_HRS_ADDR(x), BP_DMA_HRS_HRS4)) /*@}*/ /*! * @name Register DMA_HRS, field HRS5[5] (RO) * * The HRS bit for its respective channel remains asserted for the period when a * Hardware Request is Present on the Channel. After the Request is completed * and Channel is free , the HRS bit is automatically cleared by hardware. * * Values: * - 0 - A hardware service request for channel 5 is not present * - 1 - A hardware service request for channel 5 is present */ /*@{*/ #define BP_DMA_HRS_HRS5 (5U) /*!< Bit position for DMA_HRS_HRS5. */ #define BM_DMA_HRS_HRS5 (0x00000020U) /*!< Bit mask for DMA_HRS_HRS5. */ #define BS_DMA_HRS_HRS5 (1U) /*!< Bit field size in bits for DMA_HRS_HRS5. */ /*! @brief Read current value of the DMA_HRS_HRS5 field. */ #define BR_DMA_HRS_HRS5(x) (BITBAND_ACCESS32(HW_DMA_HRS_ADDR(x), BP_DMA_HRS_HRS5)) /*@}*/ /*! * @name Register DMA_HRS, field HRS6[6] (RO) * * The HRS bit for its respective channel remains asserted for the period when a * Hardware Request is Present on the Channel. After the Request is completed * and Channel is free , the HRS bit is automatically cleared by hardware. * * Values: * - 0 - A hardware service request for channel 6 is not present * - 1 - A hardware service request for channel 6 is present */ /*@{*/ #define BP_DMA_HRS_HRS6 (6U) /*!< Bit position for DMA_HRS_HRS6. */ #define BM_DMA_HRS_HRS6 (0x00000040U) /*!< Bit mask for DMA_HRS_HRS6. */ #define BS_DMA_HRS_HRS6 (1U) /*!< Bit field size in bits for DMA_HRS_HRS6. */ /*! @brief Read current value of the DMA_HRS_HRS6 field. */ #define BR_DMA_HRS_HRS6(x) (BITBAND_ACCESS32(HW_DMA_HRS_ADDR(x), BP_DMA_HRS_HRS6)) /*@}*/ /*! * @name Register DMA_HRS, field HRS7[7] (RO) * * The HRS bit for its respective channel remains asserted for the period when a * Hardware Request is Present on the Channel. After the Request is completed * and Channel is free , the HRS bit is automatically cleared by hardware. * * Values: * - 0 - A hardware service request for channel 7 is not present * - 1 - A hardware service request for channel 7 is present */ /*@{*/ #define BP_DMA_HRS_HRS7 (7U) /*!< Bit position for DMA_HRS_HRS7. */ #define BM_DMA_HRS_HRS7 (0x00000080U) /*!< Bit mask for DMA_HRS_HRS7. */ #define BS_DMA_HRS_HRS7 (1U) /*!< Bit field size in bits for DMA_HRS_HRS7. */ /*! @brief Read current value of the DMA_HRS_HRS7 field. */ #define BR_DMA_HRS_HRS7(x) (BITBAND_ACCESS32(HW_DMA_HRS_ADDR(x), BP_DMA_HRS_HRS7)) /*@}*/ /*! * @name Register DMA_HRS, field HRS8[8] (RO) * * The HRS bit for its respective channel remains asserted for the period when a * Hardware Request is Present on the Channel. After the Request is completed * and Channel is free , the HRS bit is automatically cleared by hardware. * * Values: * - 0 - A hardware service request for channel 8 is not present * - 1 - A hardware service request for channel 8 is present */ /*@{*/ #define BP_DMA_HRS_HRS8 (8U) /*!< Bit position for DMA_HRS_HRS8. */ #define BM_DMA_HRS_HRS8 (0x00000100U) /*!< Bit mask for DMA_HRS_HRS8. */ #define BS_DMA_HRS_HRS8 (1U) /*!< Bit field size in bits for DMA_HRS_HRS8. */ /*! @brief Read current value of the DMA_HRS_HRS8 field. */ #define BR_DMA_HRS_HRS8(x) (BITBAND_ACCESS32(HW_DMA_HRS_ADDR(x), BP_DMA_HRS_HRS8)) /*@}*/ /*! * @name Register DMA_HRS, field HRS9[9] (RO) * * The HRS bit for its respective channel remains asserted for the period when a * Hardware Request is Present on the Channel. After the Request is completed * and Channel is free , the HRS bit is automatically cleared by hardware. * * Values: * - 0 - A hardware service request for channel 9 is not present * - 1 - A hardware service request for channel 9 is present */ /*@{*/ #define BP_DMA_HRS_HRS9 (9U) /*!< Bit position for DMA_HRS_HRS9. */ #define BM_DMA_HRS_HRS9 (0x00000200U) /*!< Bit mask for DMA_HRS_HRS9. */ #define BS_DMA_HRS_HRS9 (1U) /*!< Bit field size in bits for DMA_HRS_HRS9. */ /*! @brief Read current value of the DMA_HRS_HRS9 field. */ #define BR_DMA_HRS_HRS9(x) (BITBAND_ACCESS32(HW_DMA_HRS_ADDR(x), BP_DMA_HRS_HRS9)) /*@}*/ /*! * @name Register DMA_HRS, field HRS10[10] (RO) * * The HRS bit for its respective channel remains asserted for the period when a * Hardware Request is Present on the Channel. After the Request is completed * and Channel is free , the HRS bit is automatically cleared by hardware. * * Values: * - 0 - A hardware service request for channel 10 is not present * - 1 - A hardware service request for channel 10 is present */ /*@{*/ #define BP_DMA_HRS_HRS10 (10U) /*!< Bit position for DMA_HRS_HRS10. */ #define BM_DMA_HRS_HRS10 (0x00000400U) /*!< Bit mask for DMA_HRS_HRS10. */ #define BS_DMA_HRS_HRS10 (1U) /*!< Bit field size in bits for DMA_HRS_HRS10. */ /*! @brief Read current value of the DMA_HRS_HRS10 field. */ #define BR_DMA_HRS_HRS10(x) (BITBAND_ACCESS32(HW_DMA_HRS_ADDR(x), BP_DMA_HRS_HRS10)) /*@}*/ /*! * @name Register DMA_HRS, field HRS11[11] (RO) * * The HRS bit for its respective channel remains asserted for the period when a * Hardware Request is Present on the Channel. After the Request is completed * and Channel is free , the HRS bit is automatically cleared by hardware. * * Values: * - 0 - A hardware service request for channel 11 is not present * - 1 - A hardware service request for channel 11 is present */ /*@{*/ #define BP_DMA_HRS_HRS11 (11U) /*!< Bit position for DMA_HRS_HRS11. */ #define BM_DMA_HRS_HRS11 (0x00000800U) /*!< Bit mask for DMA_HRS_HRS11. */ #define BS_DMA_HRS_HRS11 (1U) /*!< Bit field size in bits for DMA_HRS_HRS11. */ /*! @brief Read current value of the DMA_HRS_HRS11 field. */ #define BR_DMA_HRS_HRS11(x) (BITBAND_ACCESS32(HW_DMA_HRS_ADDR(x), BP_DMA_HRS_HRS11)) /*@}*/ /*! * @name Register DMA_HRS, field HRS12[12] (RO) * * The HRS bit for its respective channel remains asserted for the period when a * Hardware Request is Present on the Channel. After the Request is completed * and Channel is free , the HRS bit is automatically cleared by hardware. * * Values: * - 0 - A hardware service request for channel 12 is not present * - 1 - A hardware service request for channel 12 is present */ /*@{*/ #define BP_DMA_HRS_HRS12 (12U) /*!< Bit position for DMA_HRS_HRS12. */ #define BM_DMA_HRS_HRS12 (0x00001000U) /*!< Bit mask for DMA_HRS_HRS12. */ #define BS_DMA_HRS_HRS12 (1U) /*!< Bit field size in bits for DMA_HRS_HRS12. */ /*! @brief Read current value of the DMA_HRS_HRS12 field. */ #define BR_DMA_HRS_HRS12(x) (BITBAND_ACCESS32(HW_DMA_HRS_ADDR(x), BP_DMA_HRS_HRS12)) /*@}*/ /*! * @name Register DMA_HRS, field HRS13[13] (RO) * * The HRS bit for its respective channel remains asserted for the period when a * Hardware Request is Present on the Channel. After the Request is completed * and Channel is free , the HRS bit is automatically cleared by hardware. * * Values: * - 0 - A hardware service request for channel 13 is not present * - 1 - A hardware service request for channel 13 is present */ /*@{*/ #define BP_DMA_HRS_HRS13 (13U) /*!< Bit position for DMA_HRS_HRS13. */ #define BM_DMA_HRS_HRS13 (0x00002000U) /*!< Bit mask for DMA_HRS_HRS13. */ #define BS_DMA_HRS_HRS13 (1U) /*!< Bit field size in bits for DMA_HRS_HRS13. */ /*! @brief Read current value of the DMA_HRS_HRS13 field. */ #define BR_DMA_HRS_HRS13(x) (BITBAND_ACCESS32(HW_DMA_HRS_ADDR(x), BP_DMA_HRS_HRS13)) /*@}*/ /*! * @name Register DMA_HRS, field HRS14[14] (RO) * * The HRS bit for its respective channel remains asserted for the period when a * Hardware Request is Present on the Channel. After the Request is completed * and Channel is free , the HRS bit is automatically cleared by hardware. * * Values: * - 0 - A hardware service request for channel 14 is not present * - 1 - A hardware service request for channel 14 is present */ /*@{*/ #define BP_DMA_HRS_HRS14 (14U) /*!< Bit position for DMA_HRS_HRS14. */ #define BM_DMA_HRS_HRS14 (0x00004000U) /*!< Bit mask for DMA_HRS_HRS14. */ #define BS_DMA_HRS_HRS14 (1U) /*!< Bit field size in bits for DMA_HRS_HRS14. */ /*! @brief Read current value of the DMA_HRS_HRS14 field. */ #define BR_DMA_HRS_HRS14(x) (BITBAND_ACCESS32(HW_DMA_HRS_ADDR(x), BP_DMA_HRS_HRS14)) /*@}*/ /*! * @name Register DMA_HRS, field HRS15[15] (RO) * * The HRS bit for its respective channel remains asserted for the period when a * Hardware Request is Present on the Channel. After the Request is completed * and Channel is free , the HRS bit is automatically cleared by hardware. * * Values: * - 0 - A hardware service request for channel 15 is not present * - 1 - A hardware service request for channel 15 is present */ /*@{*/ #define BP_DMA_HRS_HRS15 (15U) /*!< Bit position for DMA_HRS_HRS15. */ #define BM_DMA_HRS_HRS15 (0x00008000U) /*!< Bit mask for DMA_HRS_HRS15. */ #define BS_DMA_HRS_HRS15 (1U) /*!< Bit field size in bits for DMA_HRS_HRS15. */ /*! @brief Read current value of the DMA_HRS_HRS15 field. */ #define BR_DMA_HRS_HRS15(x) (BITBAND_ACCESS32(HW_DMA_HRS_ADDR(x), BP_DMA_HRS_HRS15)) /*@}*/ /******************************************************************************* * HW_DMA_DCHPRIn - Channel n Priority Register ******************************************************************************/ /*! * @brief HW_DMA_DCHPRIn - Channel n Priority Register (RW) * * Reset value: 0x00U * * When fixed-priority channel arbitration is enabled (CR[ERCA] = 0), the * contents of these registers define the unique priorities associated with each * channel . The channel priorities are evaluated by numeric value; for example, 0 is * the lowest priority, 1 is the next priority, then 2, 3, etc. Software must * program the channel priorities with unique values; otherwise, a configuration * error is reported. The range of the priority value is limited to the values of 0 * through 15. */ typedef union _hw_dma_dchprin { uint8_t U; struct _hw_dma_dchprin_bitfields { uint8_t CHPRI : 4; /*!< [3:0] Channel n Arbitration Priority */ uint8_t RESERVED0 : 2; /*!< [5:4] */ uint8_t DPA : 1; /*!< [6] Disable Preempt Ability */ uint8_t ECP : 1; /*!< [7] Enable Channel Preemption */ } B; } hw_dma_dchprin_t; /*! * @name Constants and macros for entire DMA_DCHPRIn register */ /*@{*/ #define HW_DMA_DCHPRIn_COUNT (16U) #define HW_DMA_DCHPRIn_ADDR(x, n) ((x) + 0x100U + (0x1U * (n))) /* DMA channel index to DMA channel priority register array index conversion macro */ #define HW_DMA_DCHPRIn_CHANNEL(n) (((n) & ~0x03U) | (3 - ((n) & 0x03U))) #define HW_DMA_DCHPRIn(x, n) (*(__IO hw_dma_dchprin_t *) HW_DMA_DCHPRIn_ADDR(x, n)) #define HW_DMA_DCHPRIn_RD(x, n) (HW_DMA_DCHPRIn(x, n).U) #define HW_DMA_DCHPRIn_WR(x, n, v) (HW_DMA_DCHPRIn(x, n).U = (v)) #define HW_DMA_DCHPRIn_SET(x, n, v) (HW_DMA_DCHPRIn_WR(x, n, HW_DMA_DCHPRIn_RD(x, n) | (v))) #define HW_DMA_DCHPRIn_CLR(x, n, v) (HW_DMA_DCHPRIn_WR(x, n, HW_DMA_DCHPRIn_RD(x, n) & ~(v))) #define HW_DMA_DCHPRIn_TOG(x, n, v) (HW_DMA_DCHPRIn_WR(x, n, HW_DMA_DCHPRIn_RD(x, n) ^ (v))) /*@}*/ /* * Constants & macros for individual DMA_DCHPRIn bitfields */ /*! * @name Register DMA_DCHPRIn, field CHPRI[3:0] (RW) * * Channel priority when fixed-priority arbitration is enabled Reset value for * the channel priority fields, CHPRI, is equal to the corresponding channel * number for each priority register, i.e., DCHPRI15[CHPRI] equals 0b1111. */ /*@{*/ #define BP_DMA_DCHPRIn_CHPRI (0U) /*!< Bit position for DMA_DCHPRIn_CHPRI. */ #define BM_DMA_DCHPRIn_CHPRI (0x0FU) /*!< Bit mask for DMA_DCHPRIn_CHPRI. */ #define BS_DMA_DCHPRIn_CHPRI (4U) /*!< Bit field size in bits for DMA_DCHPRIn_CHPRI. */ /*! @brief Read current value of the DMA_DCHPRIn_CHPRI field. */ #define BR_DMA_DCHPRIn_CHPRI(x, n) (HW_DMA_DCHPRIn(x, n).B.CHPRI) /*! @brief Format value for bitfield DMA_DCHPRIn_CHPRI. */ #define BF_DMA_DCHPRIn_CHPRI(v) ((uint8_t)((uint8_t)(v) << BP_DMA_DCHPRIn_CHPRI) & BM_DMA_DCHPRIn_CHPRI) /*! @brief Set the CHPRI field to a new value. */ #define BW_DMA_DCHPRIn_CHPRI(x, n, v) (HW_DMA_DCHPRIn_WR(x, n, (HW_DMA_DCHPRIn_RD(x, n) & ~BM_DMA_DCHPRIn_CHPRI) | BF_DMA_DCHPRIn_CHPRI(v))) /*@}*/ /*! * @name Register DMA_DCHPRIn, field DPA[6] (RW) * * Values: * - 0 - Channel n can suspend a lower priority channel * - 1 - Channel n cannot suspend any channel, regardless of channel priority */ /*@{*/ #define BP_DMA_DCHPRIn_DPA (6U) /*!< Bit position for DMA_DCHPRIn_DPA. */ #define BM_DMA_DCHPRIn_DPA (0x40U) /*!< Bit mask for DMA_DCHPRIn_DPA. */ #define BS_DMA_DCHPRIn_DPA (1U) /*!< Bit field size in bits for DMA_DCHPRIn_DPA. */ /*! @brief Read current value of the DMA_DCHPRIn_DPA field. */ #define BR_DMA_DCHPRIn_DPA(x, n) (BITBAND_ACCESS8(HW_DMA_DCHPRIn_ADDR(x, n), BP_DMA_DCHPRIn_DPA)) /*! @brief Format value for bitfield DMA_DCHPRIn_DPA. */ #define BF_DMA_DCHPRIn_DPA(v) ((uint8_t)((uint8_t)(v) << BP_DMA_DCHPRIn_DPA) & BM_DMA_DCHPRIn_DPA) /*! @brief Set the DPA field to a new value. */ #define BW_DMA_DCHPRIn_DPA(x, n, v) (BITBAND_ACCESS8(HW_DMA_DCHPRIn_ADDR(x, n), BP_DMA_DCHPRIn_DPA) = (v)) /*@}*/ /*! * @name Register DMA_DCHPRIn, field ECP[7] (RW) * * Values: * - 0 - Channel n cannot be suspended by a higher priority channel's service * request * - 1 - Channel n can be temporarily suspended by the service request of a * higher priority channel */ /*@{*/ #define BP_DMA_DCHPRIn_ECP (7U) /*!< Bit position for DMA_DCHPRIn_ECP. */ #define BM_DMA_DCHPRIn_ECP (0x80U) /*!< Bit mask for DMA_DCHPRIn_ECP. */ #define BS_DMA_DCHPRIn_ECP (1U) /*!< Bit field size in bits for DMA_DCHPRIn_ECP. */ /*! @brief Read current value of the DMA_DCHPRIn_ECP field. */ #define BR_DMA_DCHPRIn_ECP(x, n) (BITBAND_ACCESS8(HW_DMA_DCHPRIn_ADDR(x, n), BP_DMA_DCHPRIn_ECP)) /*! @brief Format value for bitfield DMA_DCHPRIn_ECP. */ #define BF_DMA_DCHPRIn_ECP(v) ((uint8_t)((uint8_t)(v) << BP_DMA_DCHPRIn_ECP) & BM_DMA_DCHPRIn_ECP) /*! @brief Set the ECP field to a new value. */ #define BW_DMA_DCHPRIn_ECP(x, n, v) (BITBAND_ACCESS8(HW_DMA_DCHPRIn_ADDR(x, n), BP_DMA_DCHPRIn_ECP) = (v)) /*@}*/ /******************************************************************************* * HW_DMA_TCDn_SADDR - TCD Source Address ******************************************************************************/ /*! * @brief HW_DMA_TCDn_SADDR - TCD Source Address (RW) * * Reset value: 0x00000000U */ typedef union _hw_dma_tcdn_saddr { uint32_t U; struct _hw_dma_tcdn_saddr_bitfields { uint32_t SADDR : 32; /*!< [31:0] Source Address */ } B; } hw_dma_tcdn_saddr_t; /*! * @name Constants and macros for entire DMA_TCDn_SADDR register */ /*@{*/ #define HW_DMA_TCDn_SADDR_COUNT (16U) #define HW_DMA_TCDn_SADDR_ADDR(x, n) ((x) + 0x1000U + (0x20U * (n))) #define HW_DMA_TCDn_SADDR(x, n) (*(__IO hw_dma_tcdn_saddr_t *) HW_DMA_TCDn_SADDR_ADDR(x, n)) #define HW_DMA_TCDn_SADDR_RD(x, n) (HW_DMA_TCDn_SADDR(x, n).U) #define HW_DMA_TCDn_SADDR_WR(x, n, v) (HW_DMA_TCDn_SADDR(x, n).U = (v)) #define HW_DMA_TCDn_SADDR_SET(x, n, v) (HW_DMA_TCDn_SADDR_WR(x, n, HW_DMA_TCDn_SADDR_RD(x, n) | (v))) #define HW_DMA_TCDn_SADDR_CLR(x, n, v) (HW_DMA_TCDn_SADDR_WR(x, n, HW_DMA_TCDn_SADDR_RD(x, n) & ~(v))) #define HW_DMA_TCDn_SADDR_TOG(x, n, v) (HW_DMA_TCDn_SADDR_WR(x, n, HW_DMA_TCDn_SADDR_RD(x, n) ^ (v))) /*@}*/ /* * Constants & macros for individual DMA_TCDn_SADDR bitfields */ /*! * @name Register DMA_TCDn_SADDR, field SADDR[31:0] (RW) * * Memory address pointing to the source data. */ /*@{*/ #define BP_DMA_TCDn_SADDR_SADDR (0U) /*!< Bit position for DMA_TCDn_SADDR_SADDR. */ #define BM_DMA_TCDn_SADDR_SADDR (0xFFFFFFFFU) /*!< Bit mask for DMA_TCDn_SADDR_SADDR. */ #define BS_DMA_TCDn_SADDR_SADDR (32U) /*!< Bit field size in bits for DMA_TCDn_SADDR_SADDR. */ /*! @brief Read current value of the DMA_TCDn_SADDR_SADDR field. */ #define BR_DMA_TCDn_SADDR_SADDR(x, n) (HW_DMA_TCDn_SADDR(x, n).U) /*! @brief Format value for bitfield DMA_TCDn_SADDR_SADDR. */ #define BF_DMA_TCDn_SADDR_SADDR(v) ((uint32_t)((uint32_t)(v) << BP_DMA_TCDn_SADDR_SADDR) & BM_DMA_TCDn_SADDR_SADDR) /*! @brief Set the SADDR field to a new value. */ #define BW_DMA_TCDn_SADDR_SADDR(x, n, v) (HW_DMA_TCDn_SADDR_WR(x, n, v)) /*@}*/ /******************************************************************************* * HW_DMA_TCDn_SOFF - TCD Signed Source Address Offset ******************************************************************************/ /*! * @brief HW_DMA_TCDn_SOFF - TCD Signed Source Address Offset (RW) * * Reset value: 0x0000U */ typedef union _hw_dma_tcdn_soff { uint16_t U; struct _hw_dma_tcdn_soff_bitfields { uint16_t SOFF : 16; /*!< [15:0] Source address signed offset */ } B; } hw_dma_tcdn_soff_t; /*! * @name Constants and macros for entire DMA_TCDn_SOFF register */ /*@{*/ #define HW_DMA_TCDn_SOFF_COUNT (16U) #define HW_DMA_TCDn_SOFF_ADDR(x, n) ((x) + 0x1004U + (0x20U * (n))) #define HW_DMA_TCDn_SOFF(x, n) (*(__IO hw_dma_tcdn_soff_t *) HW_DMA_TCDn_SOFF_ADDR(x, n)) #define HW_DMA_TCDn_SOFF_RD(x, n) (HW_DMA_TCDn_SOFF(x, n).U) #define HW_DMA_TCDn_SOFF_WR(x, n, v) (HW_DMA_TCDn_SOFF(x, n).U = (v)) #define HW_DMA_TCDn_SOFF_SET(x, n, v) (HW_DMA_TCDn_SOFF_WR(x, n, HW_DMA_TCDn_SOFF_RD(x, n) | (v))) #define HW_DMA_TCDn_SOFF_CLR(x, n, v) (HW_DMA_TCDn_SOFF_WR(x, n, HW_DMA_TCDn_SOFF_RD(x, n) & ~(v))) #define HW_DMA_TCDn_SOFF_TOG(x, n, v) (HW_DMA_TCDn_SOFF_WR(x, n, HW_DMA_TCDn_SOFF_RD(x, n) ^ (v))) /*@}*/ /* * Constants & macros for individual DMA_TCDn_SOFF bitfields */ /*! * @name Register DMA_TCDn_SOFF, field SOFF[15:0] (RW) * * Sign-extended offset applied to the current source address to form the * next-state value as each source read is completed. */ /*@{*/ #define BP_DMA_TCDn_SOFF_SOFF (0U) /*!< Bit position for DMA_TCDn_SOFF_SOFF. */ #define BM_DMA_TCDn_SOFF_SOFF (0xFFFFU) /*!< Bit mask for DMA_TCDn_SOFF_SOFF. */ #define BS_DMA_TCDn_SOFF_SOFF (16U) /*!< Bit field size in bits for DMA_TCDn_SOFF_SOFF. */ /*! @brief Read current value of the DMA_TCDn_SOFF_SOFF field. */ #define BR_DMA_TCDn_SOFF_SOFF(x, n) (HW_DMA_TCDn_SOFF(x, n).U) /*! @brief Format value for bitfield DMA_TCDn_SOFF_SOFF. */ #define BF_DMA_TCDn_SOFF_SOFF(v) ((uint16_t)((uint16_t)(v) << BP_DMA_TCDn_SOFF_SOFF) & BM_DMA_TCDn_SOFF_SOFF) /*! @brief Set the SOFF field to a new value. */ #define BW_DMA_TCDn_SOFF_SOFF(x, n, v) (HW_DMA_TCDn_SOFF_WR(x, n, v)) /*@}*/ /******************************************************************************* * HW_DMA_TCDn_ATTR - TCD Transfer Attributes ******************************************************************************/ /*! * @brief HW_DMA_TCDn_ATTR - TCD Transfer Attributes (RW) * * Reset value: 0x0000U */ typedef union _hw_dma_tcdn_attr { uint16_t U; struct _hw_dma_tcdn_attr_bitfields { uint16_t DSIZE : 3; /*!< [2:0] Destination Data Transfer Size */ uint16_t DMOD : 5; /*!< [7:3] Destination Address Modulo */ uint16_t SSIZE : 3; /*!< [10:8] Source data transfer size */ uint16_t SMOD : 5; /*!< [15:11] Source Address Modulo. */ } B; } hw_dma_tcdn_attr_t; /*! * @name Constants and macros for entire DMA_TCDn_ATTR register */ /*@{*/ #define HW_DMA_TCDn_ATTR_COUNT (16U) #define HW_DMA_TCDn_ATTR_ADDR(x, n) ((x) + 0x1006U + (0x20U * (n))) #define HW_DMA_TCDn_ATTR(x, n) (*(__IO hw_dma_tcdn_attr_t *) HW_DMA_TCDn_ATTR_ADDR(x, n)) #define HW_DMA_TCDn_ATTR_RD(x, n) (HW_DMA_TCDn_ATTR(x, n).U) #define HW_DMA_TCDn_ATTR_WR(x, n, v) (HW_DMA_TCDn_ATTR(x, n).U = (v)) #define HW_DMA_TCDn_ATTR_SET(x, n, v) (HW_DMA_TCDn_ATTR_WR(x, n, HW_DMA_TCDn_ATTR_RD(x, n) | (v))) #define HW_DMA_TCDn_ATTR_CLR(x, n, v) (HW_DMA_TCDn_ATTR_WR(x, n, HW_DMA_TCDn_ATTR_RD(x, n) & ~(v))) #define HW_DMA_TCDn_ATTR_TOG(x, n, v) (HW_DMA_TCDn_ATTR_WR(x, n, HW_DMA_TCDn_ATTR_RD(x, n) ^ (v))) /*@}*/ /* * Constants & macros for individual DMA_TCDn_ATTR bitfields */ /*! * @name Register DMA_TCDn_ATTR, field DSIZE[2:0] (RW) * * See the SSIZE definition */ /*@{*/ #define BP_DMA_TCDn_ATTR_DSIZE (0U) /*!< Bit position for DMA_TCDn_ATTR_DSIZE. */ #define BM_DMA_TCDn_ATTR_DSIZE (0x0007U) /*!< Bit mask for DMA_TCDn_ATTR_DSIZE. */ #define BS_DMA_TCDn_ATTR_DSIZE (3U) /*!< Bit field size in bits for DMA_TCDn_ATTR_DSIZE. */ /*! @brief Read current value of the DMA_TCDn_ATTR_DSIZE field. */ #define BR_DMA_TCDn_ATTR_DSIZE(x, n) (HW_DMA_TCDn_ATTR(x, n).B.DSIZE) /*! @brief Format value for bitfield DMA_TCDn_ATTR_DSIZE. */ #define BF_DMA_TCDn_ATTR_DSIZE(v) ((uint16_t)((uint16_t)(v) << BP_DMA_TCDn_ATTR_DSIZE) & BM_DMA_TCDn_ATTR_DSIZE) /*! @brief Set the DSIZE field to a new value. */ #define BW_DMA_TCDn_ATTR_DSIZE(x, n, v) (HW_DMA_TCDn_ATTR_WR(x, n, (HW_DMA_TCDn_ATTR_RD(x, n) & ~BM_DMA_TCDn_ATTR_DSIZE) | BF_DMA_TCDn_ATTR_DSIZE(v))) /*@}*/ /*! * @name Register DMA_TCDn_ATTR, field DMOD[7:3] (RW) * * See the SMOD definition */ /*@{*/ #define BP_DMA_TCDn_ATTR_DMOD (3U) /*!< Bit position for DMA_TCDn_ATTR_DMOD. */ #define BM_DMA_TCDn_ATTR_DMOD (0x00F8U) /*!< Bit mask for DMA_TCDn_ATTR_DMOD. */ #define BS_DMA_TCDn_ATTR_DMOD (5U) /*!< Bit field size in bits for DMA_TCDn_ATTR_DMOD. */ /*! @brief Read current value of the DMA_TCDn_ATTR_DMOD field. */ #define BR_DMA_TCDn_ATTR_DMOD(x, n) (HW_DMA_TCDn_ATTR(x, n).B.DMOD) /*! @brief Format value for bitfield DMA_TCDn_ATTR_DMOD. */ #define BF_DMA_TCDn_ATTR_DMOD(v) ((uint16_t)((uint16_t)(v) << BP_DMA_TCDn_ATTR_DMOD) & BM_DMA_TCDn_ATTR_DMOD) /*! @brief Set the DMOD field to a new value. */ #define BW_DMA_TCDn_ATTR_DMOD(x, n, v) (HW_DMA_TCDn_ATTR_WR(x, n, (HW_DMA_TCDn_ATTR_RD(x, n) & ~BM_DMA_TCDn_ATTR_DMOD) | BF_DMA_TCDn_ATTR_DMOD(v))) /*@}*/ /*! * @name Register DMA_TCDn_ATTR, field SSIZE[10:8] (RW) * * The attempted use of a Reserved encoding causes a configuration error. * * Values: * - 000 - 8-bit * - 001 - 16-bit * - 010 - 32-bit * - 011 - Reserved * - 100 - 16-byte * - 101 - 32-byte * - 110 - Reserved * - 111 - Reserved */ /*@{*/ #define BP_DMA_TCDn_ATTR_SSIZE (8U) /*!< Bit position for DMA_TCDn_ATTR_SSIZE. */ #define BM_DMA_TCDn_ATTR_SSIZE (0x0700U) /*!< Bit mask for DMA_TCDn_ATTR_SSIZE. */ #define BS_DMA_TCDn_ATTR_SSIZE (3U) /*!< Bit field size in bits for DMA_TCDn_ATTR_SSIZE. */ /*! @brief Read current value of the DMA_TCDn_ATTR_SSIZE field. */ #define BR_DMA_TCDn_ATTR_SSIZE(x, n) (HW_DMA_TCDn_ATTR(x, n).B.SSIZE) /*! @brief Format value for bitfield DMA_TCDn_ATTR_SSIZE. */ #define BF_DMA_TCDn_ATTR_SSIZE(v) ((uint16_t)((uint16_t)(v) << BP_DMA_TCDn_ATTR_SSIZE) & BM_DMA_TCDn_ATTR_SSIZE) /*! @brief Set the SSIZE field to a new value. */ #define BW_DMA_TCDn_ATTR_SSIZE(x, n, v) (HW_DMA_TCDn_ATTR_WR(x, n, (HW_DMA_TCDn_ATTR_RD(x, n) & ~BM_DMA_TCDn_ATTR_SSIZE) | BF_DMA_TCDn_ATTR_SSIZE(v))) /*@}*/ /*! * @name Register DMA_TCDn_ATTR, field SMOD[15:11] (RW) * * Values: * - 0 - Source address modulo feature is disabled */ /*@{*/ #define BP_DMA_TCDn_ATTR_SMOD (11U) /*!< Bit position for DMA_TCDn_ATTR_SMOD. */ #define BM_DMA_TCDn_ATTR_SMOD (0xF800U) /*!< Bit mask for DMA_TCDn_ATTR_SMOD. */ #define BS_DMA_TCDn_ATTR_SMOD (5U) /*!< Bit field size in bits for DMA_TCDn_ATTR_SMOD. */ /*! @brief Read current value of the DMA_TCDn_ATTR_SMOD field. */ #define BR_DMA_TCDn_ATTR_SMOD(x, n) (HW_DMA_TCDn_ATTR(x, n).B.SMOD) /*! @brief Format value for bitfield DMA_TCDn_ATTR_SMOD. */ #define BF_DMA_TCDn_ATTR_SMOD(v) ((uint16_t)((uint16_t)(v) << BP_DMA_TCDn_ATTR_SMOD) & BM_DMA_TCDn_ATTR_SMOD) /*! @brief Set the SMOD field to a new value. */ #define BW_DMA_TCDn_ATTR_SMOD(x, n, v) (HW_DMA_TCDn_ATTR_WR(x, n, (HW_DMA_TCDn_ATTR_RD(x, n) & ~BM_DMA_TCDn_ATTR_SMOD) | BF_DMA_TCDn_ATTR_SMOD(v))) /*@}*/ /******************************************************************************* * HW_DMA_TCDn_NBYTES_MLNO - TCD Minor Byte Count (Minor Loop Disabled) ******************************************************************************/ /*! * @brief HW_DMA_TCDn_NBYTES_MLNO - TCD Minor Byte Count (Minor Loop Disabled) (RW) * * Reset value: 0x00000000U * * This register, or one of the next two registers (TCD_NBYTES_MLOFFNO, * TCD_NBYTES_MLOFFYES), defines the number of bytes to transfer per request. Which * register to use depends on whether minor loop mapping is disabled, enabled but not * used for this channel, or enabled and used. TCD word 2 is defined as follows * if: Minor loop mapping is disabled (CR[EMLM] = 0) If minor loop mapping is * enabled, see the TCD_NBYTES_MLOFFNO and TCD_NBYTES_MLOFFYES register descriptions * for TCD word 2's definition. */ typedef union _hw_dma_tcdn_nbytes_mlno { uint32_t U; struct _hw_dma_tcdn_nbytes_mlno_bitfields { uint32_t NBYTES : 32; /*!< [31:0] Minor Byte Transfer Count */ } B; } hw_dma_tcdn_nbytes_mlno_t; /*! * @name Constants and macros for entire DMA_TCDn_NBYTES_MLNO register */ /*@{*/ #define HW_DMA_TCDn_NBYTES_MLNO_COUNT (16U) #define HW_DMA_TCDn_NBYTES_MLNO_ADDR(x, n) ((x) + 0x1008U + (0x20U * (n))) #define HW_DMA_TCDn_NBYTES_MLNO(x, n) (*(__IO hw_dma_tcdn_nbytes_mlno_t *) HW_DMA_TCDn_NBYTES_MLNO_ADDR(x, n)) #define HW_DMA_TCDn_NBYTES_MLNO_RD(x, n) (HW_DMA_TCDn_NBYTES_MLNO(x, n).U) #define HW_DMA_TCDn_NBYTES_MLNO_WR(x, n, v) (HW_DMA_TCDn_NBYTES_MLNO(x, n).U = (v)) #define HW_DMA_TCDn_NBYTES_MLNO_SET(x, n, v) (HW_DMA_TCDn_NBYTES_MLNO_WR(x, n, HW_DMA_TCDn_NBYTES_MLNO_RD(x, n) | (v))) #define HW_DMA_TCDn_NBYTES_MLNO_CLR(x, n, v) (HW_DMA_TCDn_NBYTES_MLNO_WR(x, n, HW_DMA_TCDn_NBYTES_MLNO_RD(x, n) & ~(v))) #define HW_DMA_TCDn_NBYTES_MLNO_TOG(x, n, v) (HW_DMA_TCDn_NBYTES_MLNO_WR(x, n, HW_DMA_TCDn_NBYTES_MLNO_RD(x, n) ^ (v))) /*@}*/ /* * Constants & macros for individual DMA_TCDn_NBYTES_MLNO bitfields */ /*! * @name Register DMA_TCDn_NBYTES_MLNO, field NBYTES[31:0] (RW) * * Number of bytes to be transferred in each service request of the channel. As * a channel activates, the appropriate TCD contents load into the eDMA engine, * and the appropriate reads and writes perform until the minor byte transfer * count has transferred. This is an indivisible operation and cannot be halted. * (Although, it may be stalled by using the bandwidth control field, or via * preemption.) After the minor count is exhausted, the SADDR and DADDR values are * written back into the TCD memory, the major iteration count is decremented and * restored to the TCD memory. If the major iteration count is completed, additional * processing is performed. An NBYTES value of 0x0000_0000 is interpreted as a 4 * GB transfer. */ /*@{*/ #define BP_DMA_TCDn_NBYTES_MLNO_NBYTES (0U) /*!< Bit position for DMA_TCDn_NBYTES_MLNO_NBYTES. */ #define BM_DMA_TCDn_NBYTES_MLNO_NBYTES (0xFFFFFFFFU) /*!< Bit mask for DMA_TCDn_NBYTES_MLNO_NBYTES. */ #define BS_DMA_TCDn_NBYTES_MLNO_NBYTES (32U) /*!< Bit field size in bits for DMA_TCDn_NBYTES_MLNO_NBYTES. */ /*! @brief Read current value of the DMA_TCDn_NBYTES_MLNO_NBYTES field. */ #define BR_DMA_TCDn_NBYTES_MLNO_NBYTES(x, n) (HW_DMA_TCDn_NBYTES_MLNO(x, n).U) /*! @brief Format value for bitfield DMA_TCDn_NBYTES_MLNO_NBYTES. */ #define BF_DMA_TCDn_NBYTES_MLNO_NBYTES(v) ((uint32_t)((uint32_t)(v) << BP_DMA_TCDn_NBYTES_MLNO_NBYTES) & BM_DMA_TCDn_NBYTES_MLNO_NBYTES) /*! @brief Set the NBYTES field to a new value. */ #define BW_DMA_TCDn_NBYTES_MLNO_NBYTES(x, n, v) (HW_DMA_TCDn_NBYTES_MLNO_WR(x, n, v)) /*@}*/ /******************************************************************************* * HW_DMA_TCDn_NBYTES_MLOFFNO - TCD Signed Minor Loop Offset (Minor Loop Enabled and Offset Disabled) ******************************************************************************/ /*! * @brief HW_DMA_TCDn_NBYTES_MLOFFNO - TCD Signed Minor Loop Offset (Minor Loop Enabled and Offset Disabled) (RW) * * Reset value: 0x00000000U * * One of three registers (this register, TCD_NBYTES_MLNO, or * TCD_NBYTES_MLOFFYES), defines the number of bytes to transfer per request. Which register to use * depends on whether minor loop mapping is disabled, enabled but not used for * this channel, or enabled and used. TCD word 2 is defined as follows if: Minor * loop mapping is enabled (CR[EMLM] = 1) and SMLOE = 0 and DMLOE = 0 If minor * loop mapping is enabled and SMLOE or DMLOE is set, then refer to the * TCD_NBYTES_MLOFFYES register description. If minor loop mapping is disabled, then refer to * the TCD_NBYTES_MLNO register description. */ typedef union _hw_dma_tcdn_nbytes_mloffno { uint32_t U; struct _hw_dma_tcdn_nbytes_mloffno_bitfields { uint32_t NBYTES : 30; /*!< [29:0] Minor Byte Transfer Count */ uint32_t DMLOE : 1; /*!< [30] Destination Minor Loop Offset enable */ uint32_t SMLOE : 1; /*!< [31] Source Minor Loop Offset Enable */ } B; } hw_dma_tcdn_nbytes_mloffno_t; /*! * @name Constants and macros for entire DMA_TCDn_NBYTES_MLOFFNO register */ /*@{*/ #define HW_DMA_TCDn_NBYTES_MLOFFNO_COUNT (16U) #define HW_DMA_TCDn_NBYTES_MLOFFNO_ADDR(x, n) ((x) + 0x1008U + (0x20U * (n))) #define HW_DMA_TCDn_NBYTES_MLOFFNO(x, n) (*(__IO hw_dma_tcdn_nbytes_mloffno_t *) HW_DMA_TCDn_NBYTES_MLOFFNO_ADDR(x, n)) #define HW_DMA_TCDn_NBYTES_MLOFFNO_RD(x, n) (HW_DMA_TCDn_NBYTES_MLOFFNO(x, n).U) #define HW_DMA_TCDn_NBYTES_MLOFFNO_WR(x, n, v) (HW_DMA_TCDn_NBYTES_MLOFFNO(x, n).U = (v)) #define HW_DMA_TCDn_NBYTES_MLOFFNO_SET(x, n, v) (HW_DMA_TCDn_NBYTES_MLOFFNO_WR(x, n, HW_DMA_TCDn_NBYTES_MLOFFNO_RD(x, n) | (v))) #define HW_DMA_TCDn_NBYTES_MLOFFNO_CLR(x, n, v) (HW_DMA_TCDn_NBYTES_MLOFFNO_WR(x, n, HW_DMA_TCDn_NBYTES_MLOFFNO_RD(x, n) & ~(v))) #define HW_DMA_TCDn_NBYTES_MLOFFNO_TOG(x, n, v) (HW_DMA_TCDn_NBYTES_MLOFFNO_WR(x, n, HW_DMA_TCDn_NBYTES_MLOFFNO_RD(x, n) ^ (v))) /*@}*/ /* * Constants & macros for individual DMA_TCDn_NBYTES_MLOFFNO bitfields */ /*! * @name Register DMA_TCDn_NBYTES_MLOFFNO, field NBYTES[29:0] (RW) * * Number of bytes to be transferred in each service request of the channel. As * a channel activates, the appropriate TCD contents load into the eDMA engine, * and the appropriate reads and writes perform until the minor byte transfer * count has transferred. This is an indivisible operation and cannot be halted; * although, it may be stalled by using the bandwidth control field, or via * preemption. After the minor count is exhausted, the SADDR and DADDR values are written * back into the TCD memory, the major iteration count is decremented and * restored to the TCD memory. If the major iteration count is completed, additional * processing is performed. */ /*@{*/ #define BP_DMA_TCDn_NBYTES_MLOFFNO_NBYTES (0U) /*!< Bit position for DMA_TCDn_NBYTES_MLOFFNO_NBYTES. */ #define BM_DMA_TCDn_NBYTES_MLOFFNO_NBYTES (0x3FFFFFFFU) /*!< Bit mask for DMA_TCDn_NBYTES_MLOFFNO_NBYTES. */ #define BS_DMA_TCDn_NBYTES_MLOFFNO_NBYTES (30U) /*!< Bit field size in bits for DMA_TCDn_NBYTES_MLOFFNO_NBYTES. */ /*! @brief Read current value of the DMA_TCDn_NBYTES_MLOFFNO_NBYTES field. */ #define BR_DMA_TCDn_NBYTES_MLOFFNO_NBYTES(x, n) (HW_DMA_TCDn_NBYTES_MLOFFNO(x, n).B.NBYTES) /*! @brief Format value for bitfield DMA_TCDn_NBYTES_MLOFFNO_NBYTES. */ #define BF_DMA_TCDn_NBYTES_MLOFFNO_NBYTES(v) ((uint32_t)((uint32_t)(v) << BP_DMA_TCDn_NBYTES_MLOFFNO_NBYTES) & BM_DMA_TCDn_NBYTES_MLOFFNO_NBYTES) /*! @brief Set the NBYTES field to a new value. */ #define BW_DMA_TCDn_NBYTES_MLOFFNO_NBYTES(x, n, v) (HW_DMA_TCDn_NBYTES_MLOFFNO_WR(x, n, (HW_DMA_TCDn_NBYTES_MLOFFNO_RD(x, n) & ~BM_DMA_TCDn_NBYTES_MLOFFNO_NBYTES) | BF_DMA_TCDn_NBYTES_MLOFFNO_NBYTES(v))) /*@}*/ /*! * @name Register DMA_TCDn_NBYTES_MLOFFNO, field DMLOE[30] (RW) * * Selects whether the minor loop offset is applied to the destination address * upon minor loop completion. * * Values: * - 0 - The minor loop offset is not applied to the DADDR * - 1 - The minor loop offset is applied to the DADDR */ /*@{*/ #define BP_DMA_TCDn_NBYTES_MLOFFNO_DMLOE (30U) /*!< Bit position for DMA_TCDn_NBYTES_MLOFFNO_DMLOE. */ #define BM_DMA_TCDn_NBYTES_MLOFFNO_DMLOE (0x40000000U) /*!< Bit mask for DMA_TCDn_NBYTES_MLOFFNO_DMLOE. */ #define BS_DMA_TCDn_NBYTES_MLOFFNO_DMLOE (1U) /*!< Bit field size in bits for DMA_TCDn_NBYTES_MLOFFNO_DMLOE. */ /*! @brief Read current value of the DMA_TCDn_NBYTES_MLOFFNO_DMLOE field. */ #define BR_DMA_TCDn_NBYTES_MLOFFNO_DMLOE(x, n) (BITBAND_ACCESS32(HW_DMA_TCDn_NBYTES_MLOFFNO_ADDR(x, n), BP_DMA_TCDn_NBYTES_MLOFFNO_DMLOE)) /*! @brief Format value for bitfield DMA_TCDn_NBYTES_MLOFFNO_DMLOE. */ #define BF_DMA_TCDn_NBYTES_MLOFFNO_DMLOE(v) ((uint32_t)((uint32_t)(v) << BP_DMA_TCDn_NBYTES_MLOFFNO_DMLOE) & BM_DMA_TCDn_NBYTES_MLOFFNO_DMLOE) /*! @brief Set the DMLOE field to a new value. */ #define BW_DMA_TCDn_NBYTES_MLOFFNO_DMLOE(x, n, v) (BITBAND_ACCESS32(HW_DMA_TCDn_NBYTES_MLOFFNO_ADDR(x, n), BP_DMA_TCDn_NBYTES_MLOFFNO_DMLOE) = (v)) /*@}*/ /*! * @name Register DMA_TCDn_NBYTES_MLOFFNO, field SMLOE[31] (RW) * * Selects whether the minor loop offset is applied to the source address upon * minor loop completion. * * Values: * - 0 - The minor loop offset is not applied to the SADDR * - 1 - The minor loop offset is applied to the SADDR */ /*@{*/ #define BP_DMA_TCDn_NBYTES_MLOFFNO_SMLOE (31U) /*!< Bit position for DMA_TCDn_NBYTES_MLOFFNO_SMLOE. */ #define BM_DMA_TCDn_NBYTES_MLOFFNO_SMLOE (0x80000000U) /*!< Bit mask for DMA_TCDn_NBYTES_MLOFFNO_SMLOE. */ #define BS_DMA_TCDn_NBYTES_MLOFFNO_SMLOE (1U) /*!< Bit field size in bits for DMA_TCDn_NBYTES_MLOFFNO_SMLOE. */ /*! @brief Read current value of the DMA_TCDn_NBYTES_MLOFFNO_SMLOE field. */ #define BR_DMA_TCDn_NBYTES_MLOFFNO_SMLOE(x, n) (BITBAND_ACCESS32(HW_DMA_TCDn_NBYTES_MLOFFNO_ADDR(x, n), BP_DMA_TCDn_NBYTES_MLOFFNO_SMLOE)) /*! @brief Format value for bitfield DMA_TCDn_NBYTES_MLOFFNO_SMLOE. */ #define BF_DMA_TCDn_NBYTES_MLOFFNO_SMLOE(v) ((uint32_t)((uint32_t)(v) << BP_DMA_TCDn_NBYTES_MLOFFNO_SMLOE) & BM_DMA_TCDn_NBYTES_MLOFFNO_SMLOE) /*! @brief Set the SMLOE field to a new value. */ #define BW_DMA_TCDn_NBYTES_MLOFFNO_SMLOE(x, n, v) (BITBAND_ACCESS32(HW_DMA_TCDn_NBYTES_MLOFFNO_ADDR(x, n), BP_DMA_TCDn_NBYTES_MLOFFNO_SMLOE) = (v)) /*@}*/ /******************************************************************************* * HW_DMA_TCDn_NBYTES_MLOFFYES - TCD Signed Minor Loop Offset (Minor Loop and Offset Enabled) ******************************************************************************/ /*! * @brief HW_DMA_TCDn_NBYTES_MLOFFYES - TCD Signed Minor Loop Offset (Minor Loop and Offset Enabled) (RW) * * Reset value: 0x00000000U * * One of three registers (this register, TCD_NBYTES_MLNO, or * TCD_NBYTES_MLOFFNO), defines the number of bytes to transfer per request. Which register to use * depends on whether minor loop mapping is disabled, enabled but not used for * this channel, or enabled and used. TCD word 2 is defined as follows if: Minor * loop mapping is enabled (CR[EMLM] = 1) and Minor loop offset is enabled (SMLOE * or DMLOE = 1) If minor loop mapping is enabled and SMLOE and DMLOE are cleared, * then refer to the TCD_NBYTES_MLOFFNO register description. If minor loop * mapping is disabled, then refer to the TCD_NBYTES_MLNO register description. */ typedef union _hw_dma_tcdn_nbytes_mloffyes { uint32_t U; struct _hw_dma_tcdn_nbytes_mloffyes_bitfields { uint32_t NBYTES : 10; /*!< [9:0] Minor Byte Transfer Count */ uint32_t MLOFF : 20; /*!< [29:10] If SMLOE or DMLOE is set, this * field represents a sign-extended offset applied to the source or destination * address to form the next-state value after the minor loop completes. */ uint32_t DMLOE : 1; /*!< [30] Destination Minor Loop Offset enable */ uint32_t SMLOE : 1; /*!< [31] Source Minor Loop Offset Enable */ } B; } hw_dma_tcdn_nbytes_mloffyes_t; /*! * @name Constants and macros for entire DMA_TCDn_NBYTES_MLOFFYES register */ /*@{*/ #define HW_DMA_TCDn_NBYTES_MLOFFYES_COUNT (16U) #define HW_DMA_TCDn_NBYTES_MLOFFYES_ADDR(x, n) ((x) + 0x1008U + (0x20U * (n))) #define HW_DMA_TCDn_NBYTES_MLOFFYES(x, n) (*(__IO hw_dma_tcdn_nbytes_mloffyes_t *) HW_DMA_TCDn_NBYTES_MLOFFYES_ADDR(x, n)) #define HW_DMA_TCDn_NBYTES_MLOFFYES_RD(x, n) (HW_DMA_TCDn_NBYTES_MLOFFYES(x, n).U) #define HW_DMA_TCDn_NBYTES_MLOFFYES_WR(x, n, v) (HW_DMA_TCDn_NBYTES_MLOFFYES(x, n).U = (v)) #define HW_DMA_TCDn_NBYTES_MLOFFYES_SET(x, n, v) (HW_DMA_TCDn_NBYTES_MLOFFYES_WR(x, n, HW_DMA_TCDn_NBYTES_MLOFFYES_RD(x, n) | (v))) #define HW_DMA_TCDn_NBYTES_MLOFFYES_CLR(x, n, v) (HW_DMA_TCDn_NBYTES_MLOFFYES_WR(x, n, HW_DMA_TCDn_NBYTES_MLOFFYES_RD(x, n) & ~(v))) #define HW_DMA_TCDn_NBYTES_MLOFFYES_TOG(x, n, v) (HW_DMA_TCDn_NBYTES_MLOFFYES_WR(x, n, HW_DMA_TCDn_NBYTES_MLOFFYES_RD(x, n) ^ (v))) /*@}*/ /* * Constants & macros for individual DMA_TCDn_NBYTES_MLOFFYES bitfields */ /*! * @name Register DMA_TCDn_NBYTES_MLOFFYES, field NBYTES[9:0] (RW) * * Number of bytes to be transferred in each service request of the channel. As * a channel activates, the appropriate TCD contents load into the eDMA engine, * and the appropriate reads and writes perform until the minor byte transfer * count has transferred. This is an indivisible operation and cannot be halted. * (Although, it may be stalled by using the bandwidth control field, or via * preemption.) After the minor count is exhausted, the SADDR and DADDR values are * written back into the TCD memory, the major iteration count is decremented and * restored to the TCD memory. If the major iteration count is completed, additional * processing is performed. */ /*@{*/ #define BP_DMA_TCDn_NBYTES_MLOFFYES_NBYTES (0U) /*!< Bit position for DMA_TCDn_NBYTES_MLOFFYES_NBYTES. */ #define BM_DMA_TCDn_NBYTES_MLOFFYES_NBYTES (0x000003FFU) /*!< Bit mask for DMA_TCDn_NBYTES_MLOFFYES_NBYTES. */ #define BS_DMA_TCDn_NBYTES_MLOFFYES_NBYTES (10U) /*!< Bit field size in bits for DMA_TCDn_NBYTES_MLOFFYES_NBYTES. */ /*! @brief Read current value of the DMA_TCDn_NBYTES_MLOFFYES_NBYTES field. */ #define BR_DMA_TCDn_NBYTES_MLOFFYES_NBYTES(x, n) (HW_DMA_TCDn_NBYTES_MLOFFYES(x, n).B.NBYTES) /*! @brief Format value for bitfield DMA_TCDn_NBYTES_MLOFFYES_NBYTES. */ #define BF_DMA_TCDn_NBYTES_MLOFFYES_NBYTES(v) ((uint32_t)((uint32_t)(v) << BP_DMA_TCDn_NBYTES_MLOFFYES_NBYTES) & BM_DMA_TCDn_NBYTES_MLOFFYES_NBYTES) /*! @brief Set the NBYTES field to a new value. */ #define BW_DMA_TCDn_NBYTES_MLOFFYES_NBYTES(x, n, v) (HW_DMA_TCDn_NBYTES_MLOFFYES_WR(x, n, (HW_DMA_TCDn_NBYTES_MLOFFYES_RD(x, n) & ~BM_DMA_TCDn_NBYTES_MLOFFYES_NBYTES) | BF_DMA_TCDn_NBYTES_MLOFFYES_NBYTES(v))) /*@}*/ /*! * @name Register DMA_TCDn_NBYTES_MLOFFYES, field MLOFF[29:10] (RW) */ /*@{*/ #define BP_DMA_TCDn_NBYTES_MLOFFYES_MLOFF (10U) /*!< Bit position for DMA_TCDn_NBYTES_MLOFFYES_MLOFF. */ #define BM_DMA_TCDn_NBYTES_MLOFFYES_MLOFF (0x3FFFFC00U) /*!< Bit mask for DMA_TCDn_NBYTES_MLOFFYES_MLOFF. */ #define BS_DMA_TCDn_NBYTES_MLOFFYES_MLOFF (20U) /*!< Bit field size in bits for DMA_TCDn_NBYTES_MLOFFYES_MLOFF. */ /*! @brief Read current value of the DMA_TCDn_NBYTES_MLOFFYES_MLOFF field. */ #define BR_DMA_TCDn_NBYTES_MLOFFYES_MLOFF(x, n) (HW_DMA_TCDn_NBYTES_MLOFFYES(x, n).B.MLOFF) /*! @brief Format value for bitfield DMA_TCDn_NBYTES_MLOFFYES_MLOFF. */ #define BF_DMA_TCDn_NBYTES_MLOFFYES_MLOFF(v) ((uint32_t)((uint32_t)(v) << BP_DMA_TCDn_NBYTES_MLOFFYES_MLOFF) & BM_DMA_TCDn_NBYTES_MLOFFYES_MLOFF) /*! @brief Set the MLOFF field to a new value. */ #define BW_DMA_TCDn_NBYTES_MLOFFYES_MLOFF(x, n, v) (HW_DMA_TCDn_NBYTES_MLOFFYES_WR(x, n, (HW_DMA_TCDn_NBYTES_MLOFFYES_RD(x, n) & ~BM_DMA_TCDn_NBYTES_MLOFFYES_MLOFF) | BF_DMA_TCDn_NBYTES_MLOFFYES_MLOFF(v))) /*@}*/ /*! * @name Register DMA_TCDn_NBYTES_MLOFFYES, field DMLOE[30] (RW) * * Selects whether the minor loop offset is applied to the destination address * upon minor loop completion. * * Values: * - 0 - The minor loop offset is not applied to the DADDR * - 1 - The minor loop offset is applied to the DADDR */ /*@{*/ #define BP_DMA_TCDn_NBYTES_MLOFFYES_DMLOE (30U) /*!< Bit position for DMA_TCDn_NBYTES_MLOFFYES_DMLOE. */ #define BM_DMA_TCDn_NBYTES_MLOFFYES_DMLOE (0x40000000U) /*!< Bit mask for DMA_TCDn_NBYTES_MLOFFYES_DMLOE. */ #define BS_DMA_TCDn_NBYTES_MLOFFYES_DMLOE (1U) /*!< Bit field size in bits for DMA_TCDn_NBYTES_MLOFFYES_DMLOE. */ /*! @brief Read current value of the DMA_TCDn_NBYTES_MLOFFYES_DMLOE field. */ #define BR_DMA_TCDn_NBYTES_MLOFFYES_DMLOE(x, n) (BITBAND_ACCESS32(HW_DMA_TCDn_NBYTES_MLOFFYES_ADDR(x, n), BP_DMA_TCDn_NBYTES_MLOFFYES_DMLOE)) /*! @brief Format value for bitfield DMA_TCDn_NBYTES_MLOFFYES_DMLOE. */ #define BF_DMA_TCDn_NBYTES_MLOFFYES_DMLOE(v) ((uint32_t)((uint32_t)(v) << BP_DMA_TCDn_NBYTES_MLOFFYES_DMLOE) & BM_DMA_TCDn_NBYTES_MLOFFYES_DMLOE) /*! @brief Set the DMLOE field to a new value. */ #define BW_DMA_TCDn_NBYTES_MLOFFYES_DMLOE(x, n, v) (BITBAND_ACCESS32(HW_DMA_TCDn_NBYTES_MLOFFYES_ADDR(x, n), BP_DMA_TCDn_NBYTES_MLOFFYES_DMLOE) = (v)) /*@}*/ /*! * @name Register DMA_TCDn_NBYTES_MLOFFYES, field SMLOE[31] (RW) * * Selects whether the minor loop offset is applied to the source address upon * minor loop completion. * * Values: * - 0 - The minor loop offset is not applied to the SADDR * - 1 - The minor loop offset is applied to the SADDR */ /*@{*/ #define BP_DMA_TCDn_NBYTES_MLOFFYES_SMLOE (31U) /*!< Bit position for DMA_TCDn_NBYTES_MLOFFYES_SMLOE. */ #define BM_DMA_TCDn_NBYTES_MLOFFYES_SMLOE (0x80000000U) /*!< Bit mask for DMA_TCDn_NBYTES_MLOFFYES_SMLOE. */ #define BS_DMA_TCDn_NBYTES_MLOFFYES_SMLOE (1U) /*!< Bit field size in bits for DMA_TCDn_NBYTES_MLOFFYES_SMLOE. */ /*! @brief Read current value of the DMA_TCDn_NBYTES_MLOFFYES_SMLOE field. */ #define BR_DMA_TCDn_NBYTES_MLOFFYES_SMLOE(x, n) (BITBAND_ACCESS32(HW_DMA_TCDn_NBYTES_MLOFFYES_ADDR(x, n), BP_DMA_TCDn_NBYTES_MLOFFYES_SMLOE)) /*! @brief Format value for bitfield DMA_TCDn_NBYTES_MLOFFYES_SMLOE. */ #define BF_DMA_TCDn_NBYTES_MLOFFYES_SMLOE(v) ((uint32_t)((uint32_t)(v) << BP_DMA_TCDn_NBYTES_MLOFFYES_SMLOE) & BM_DMA_TCDn_NBYTES_MLOFFYES_SMLOE) /*! @brief Set the SMLOE field to a new value. */ #define BW_DMA_TCDn_NBYTES_MLOFFYES_SMLOE(x, n, v) (BITBAND_ACCESS32(HW_DMA_TCDn_NBYTES_MLOFFYES_ADDR(x, n), BP_DMA_TCDn_NBYTES_MLOFFYES_SMLOE) = (v)) /*@}*/ /******************************************************************************* * HW_DMA_TCDn_SLAST - TCD Last Source Address Adjustment ******************************************************************************/ /*! * @brief HW_DMA_TCDn_SLAST - TCD Last Source Address Adjustment (RW) * * Reset value: 0x00000000U */ typedef union _hw_dma_tcdn_slast { uint32_t U; struct _hw_dma_tcdn_slast_bitfields { uint32_t SLAST : 32; /*!< [31:0] Last source Address Adjustment */ } B; } hw_dma_tcdn_slast_t; /*! * @name Constants and macros for entire DMA_TCDn_SLAST register */ /*@{*/ #define HW_DMA_TCDn_SLAST_COUNT (16U) #define HW_DMA_TCDn_SLAST_ADDR(x, n) ((x) + 0x100CU + (0x20U * (n))) #define HW_DMA_TCDn_SLAST(x, n) (*(__IO hw_dma_tcdn_slast_t *) HW_DMA_TCDn_SLAST_ADDR(x, n)) #define HW_DMA_TCDn_SLAST_RD(x, n) (HW_DMA_TCDn_SLAST(x, n).U) #define HW_DMA_TCDn_SLAST_WR(x, n, v) (HW_DMA_TCDn_SLAST(x, n).U = (v)) #define HW_DMA_TCDn_SLAST_SET(x, n, v) (HW_DMA_TCDn_SLAST_WR(x, n, HW_DMA_TCDn_SLAST_RD(x, n) | (v))) #define HW_DMA_TCDn_SLAST_CLR(x, n, v) (HW_DMA_TCDn_SLAST_WR(x, n, HW_DMA_TCDn_SLAST_RD(x, n) & ~(v))) #define HW_DMA_TCDn_SLAST_TOG(x, n, v) (HW_DMA_TCDn_SLAST_WR(x, n, HW_DMA_TCDn_SLAST_RD(x, n) ^ (v))) /*@}*/ /* * Constants & macros for individual DMA_TCDn_SLAST bitfields */ /*! * @name Register DMA_TCDn_SLAST, field SLAST[31:0] (RW) * * Adjustment value added to the source address at the completion of the major * iteration count. This value can be applied to restore the source address to the * initial value, or adjust the address to reference the next data structure. * This register uses two's complement notation; the overflow bit is discarded. */ /*@{*/ #define BP_DMA_TCDn_SLAST_SLAST (0U) /*!< Bit position for DMA_TCDn_SLAST_SLAST. */ #define BM_DMA_TCDn_SLAST_SLAST (0xFFFFFFFFU) /*!< Bit mask for DMA_TCDn_SLAST_SLAST. */ #define BS_DMA_TCDn_SLAST_SLAST (32U) /*!< Bit field size in bits for DMA_TCDn_SLAST_SLAST. */ /*! @brief Read current value of the DMA_TCDn_SLAST_SLAST field. */ #define BR_DMA_TCDn_SLAST_SLAST(x, n) (HW_DMA_TCDn_SLAST(x, n).U) /*! @brief Format value for bitfield DMA_TCDn_SLAST_SLAST. */ #define BF_DMA_TCDn_SLAST_SLAST(v) ((uint32_t)((uint32_t)(v) << BP_DMA_TCDn_SLAST_SLAST) & BM_DMA_TCDn_SLAST_SLAST) /*! @brief Set the SLAST field to a new value. */ #define BW_DMA_TCDn_SLAST_SLAST(x, n, v) (HW_DMA_TCDn_SLAST_WR(x, n, v)) /*@}*/ /******************************************************************************* * HW_DMA_TCDn_DADDR - TCD Destination Address ******************************************************************************/ /*! * @brief HW_DMA_TCDn_DADDR - TCD Destination Address (RW) * * Reset value: 0x00000000U */ typedef union _hw_dma_tcdn_daddr { uint32_t U; struct _hw_dma_tcdn_daddr_bitfields { uint32_t DADDR : 32; /*!< [31:0] Destination Address */ } B; } hw_dma_tcdn_daddr_t; /*! * @name Constants and macros for entire DMA_TCDn_DADDR register */ /*@{*/ #define HW_DMA_TCDn_DADDR_COUNT (16U) #define HW_DMA_TCDn_DADDR_ADDR(x, n) ((x) + 0x1010U + (0x20U * (n))) #define HW_DMA_TCDn_DADDR(x, n) (*(__IO hw_dma_tcdn_daddr_t *) HW_DMA_TCDn_DADDR_ADDR(x, n)) #define HW_DMA_TCDn_DADDR_RD(x, n) (HW_DMA_TCDn_DADDR(x, n).U) #define HW_DMA_TCDn_DADDR_WR(x, n, v) (HW_DMA_TCDn_DADDR(x, n).U = (v)) #define HW_DMA_TCDn_DADDR_SET(x, n, v) (HW_DMA_TCDn_DADDR_WR(x, n, HW_DMA_TCDn_DADDR_RD(x, n) | (v))) #define HW_DMA_TCDn_DADDR_CLR(x, n, v) (HW_DMA_TCDn_DADDR_WR(x, n, HW_DMA_TCDn_DADDR_RD(x, n) & ~(v))) #define HW_DMA_TCDn_DADDR_TOG(x, n, v) (HW_DMA_TCDn_DADDR_WR(x, n, HW_DMA_TCDn_DADDR_RD(x, n) ^ (v))) /*@}*/ /* * Constants & macros for individual DMA_TCDn_DADDR bitfields */ /*! * @name Register DMA_TCDn_DADDR, field DADDR[31:0] (RW) * * Memory address pointing to the destination data. */ /*@{*/ #define BP_DMA_TCDn_DADDR_DADDR (0U) /*!< Bit position for DMA_TCDn_DADDR_DADDR. */ #define BM_DMA_TCDn_DADDR_DADDR (0xFFFFFFFFU) /*!< Bit mask for DMA_TCDn_DADDR_DADDR. */ #define BS_DMA_TCDn_DADDR_DADDR (32U) /*!< Bit field size in bits for DMA_TCDn_DADDR_DADDR. */ /*! @brief Read current value of the DMA_TCDn_DADDR_DADDR field. */ #define BR_DMA_TCDn_DADDR_DADDR(x, n) (HW_DMA_TCDn_DADDR(x, n).U) /*! @brief Format value for bitfield DMA_TCDn_DADDR_DADDR. */ #define BF_DMA_TCDn_DADDR_DADDR(v) ((uint32_t)((uint32_t)(v) << BP_DMA_TCDn_DADDR_DADDR) & BM_DMA_TCDn_DADDR_DADDR) /*! @brief Set the DADDR field to a new value. */ #define BW_DMA_TCDn_DADDR_DADDR(x, n, v) (HW_DMA_TCDn_DADDR_WR(x, n, v)) /*@}*/ /******************************************************************************* * HW_DMA_TCDn_DOFF - TCD Signed Destination Address Offset ******************************************************************************/ /*! * @brief HW_DMA_TCDn_DOFF - TCD Signed Destination Address Offset (RW) * * Reset value: 0x0000U */ typedef union _hw_dma_tcdn_doff { uint16_t U; struct _hw_dma_tcdn_doff_bitfields { uint16_t DOFF : 16; /*!< [15:0] Destination Address Signed offset */ } B; } hw_dma_tcdn_doff_t; /*! * @name Constants and macros for entire DMA_TCDn_DOFF register */ /*@{*/ #define HW_DMA_TCDn_DOFF_COUNT (16U) #define HW_DMA_TCDn_DOFF_ADDR(x, n) ((x) + 0x1014U + (0x20U * (n))) #define HW_DMA_TCDn_DOFF(x, n) (*(__IO hw_dma_tcdn_doff_t *) HW_DMA_TCDn_DOFF_ADDR(x, n)) #define HW_DMA_TCDn_DOFF_RD(x, n) (HW_DMA_TCDn_DOFF(x, n).U) #define HW_DMA_TCDn_DOFF_WR(x, n, v) (HW_DMA_TCDn_DOFF(x, n).U = (v)) #define HW_DMA_TCDn_DOFF_SET(x, n, v) (HW_DMA_TCDn_DOFF_WR(x, n, HW_DMA_TCDn_DOFF_RD(x, n) | (v))) #define HW_DMA_TCDn_DOFF_CLR(x, n, v) (HW_DMA_TCDn_DOFF_WR(x, n, HW_DMA_TCDn_DOFF_RD(x, n) & ~(v))) #define HW_DMA_TCDn_DOFF_TOG(x, n, v) (HW_DMA_TCDn_DOFF_WR(x, n, HW_DMA_TCDn_DOFF_RD(x, n) ^ (v))) /*@}*/ /* * Constants & macros for individual DMA_TCDn_DOFF bitfields */ /*! * @name Register DMA_TCDn_DOFF, field DOFF[15:0] (RW) * * Sign-extended offset applied to the current destination address to form the * next-state value as each destination write is completed. */ /*@{*/ #define BP_DMA_TCDn_DOFF_DOFF (0U) /*!< Bit position for DMA_TCDn_DOFF_DOFF. */ #define BM_DMA_TCDn_DOFF_DOFF (0xFFFFU) /*!< Bit mask for DMA_TCDn_DOFF_DOFF. */ #define BS_DMA_TCDn_DOFF_DOFF (16U) /*!< Bit field size in bits for DMA_TCDn_DOFF_DOFF. */ /*! @brief Read current value of the DMA_TCDn_DOFF_DOFF field. */ #define BR_DMA_TCDn_DOFF_DOFF(x, n) (HW_DMA_TCDn_DOFF(x, n).U) /*! @brief Format value for bitfield DMA_TCDn_DOFF_DOFF. */ #define BF_DMA_TCDn_DOFF_DOFF(v) ((uint16_t)((uint16_t)(v) << BP_DMA_TCDn_DOFF_DOFF) & BM_DMA_TCDn_DOFF_DOFF) /*! @brief Set the DOFF field to a new value. */ #define BW_DMA_TCDn_DOFF_DOFF(x, n, v) (HW_DMA_TCDn_DOFF_WR(x, n, v)) /*@}*/ /******************************************************************************* * HW_DMA_TCDn_CITER_ELINKNO - TCD Current Minor Loop Link, Major Loop Count (Channel Linking Disabled) ******************************************************************************/ /*! * @brief HW_DMA_TCDn_CITER_ELINKNO - TCD Current Minor Loop Link, Major Loop Count (Channel Linking Disabled) (RW) * * Reset value: 0x0000U * * If TCDn_CITER[ELINK] is cleared, the TCDn_CITER register is defined as * follows. */ typedef union _hw_dma_tcdn_citer_elinkno { uint16_t U; struct _hw_dma_tcdn_citer_elinkno_bitfields { uint16_t CITER : 15; /*!< [14:0] Current Major Iteration Count */ uint16_t ELINK : 1; /*!< [15] Enable channel-to-channel linking on * minor-loop complete */ } B; } hw_dma_tcdn_citer_elinkno_t; /*! * @name Constants and macros for entire DMA_TCDn_CITER_ELINKNO register */ /*@{*/ #define HW_DMA_TCDn_CITER_ELINKNO_COUNT (16U) #define HW_DMA_TCDn_CITER_ELINKNO_ADDR(x, n) ((x) + 0x1016U + (0x20U * (n))) #define HW_DMA_TCDn_CITER_ELINKNO(x, n) (*(__IO hw_dma_tcdn_citer_elinkno_t *) HW_DMA_TCDn_CITER_ELINKNO_ADDR(x, n)) #define HW_DMA_TCDn_CITER_ELINKNO_RD(x, n) (HW_DMA_TCDn_CITER_ELINKNO(x, n).U) #define HW_DMA_TCDn_CITER_ELINKNO_WR(x, n, v) (HW_DMA_TCDn_CITER_ELINKNO(x, n).U = (v)) #define HW_DMA_TCDn_CITER_ELINKNO_SET(x, n, v) (HW_DMA_TCDn_CITER_ELINKNO_WR(x, n, HW_DMA_TCDn_CITER_ELINKNO_RD(x, n) | (v))) #define HW_DMA_TCDn_CITER_ELINKNO_CLR(x, n, v) (HW_DMA_TCDn_CITER_ELINKNO_WR(x, n, HW_DMA_TCDn_CITER_ELINKNO_RD(x, n) & ~(v))) #define HW_DMA_TCDn_CITER_ELINKNO_TOG(x, n, v) (HW_DMA_TCDn_CITER_ELINKNO_WR(x, n, HW_DMA_TCDn_CITER_ELINKNO_RD(x, n) ^ (v))) /*@}*/ /* * Constants & macros for individual DMA_TCDn_CITER_ELINKNO bitfields */ /*! * @name Register DMA_TCDn_CITER_ELINKNO, field CITER[14:0] (RW) * * This 9-bit (ELINK = 1) or 15-bit (ELINK = 0) count represents the current * major loop count for the channel. It is decremented each time the minor loop is * completed and updated in the transfer control descriptor memory. After the * major iteration count is exhausted, the channel performs a number of operations * (e.g., final source and destination address calculations), optionally generating * an interrupt to signal channel completion before reloading the CITER field * from the beginning iteration count (BITER) field. When the CITER field is * initially loaded by software, it must be set to the same value as that contained in * the BITER field. If the channel is configured to execute a single service * request, the initial values of BITER and CITER should be 0x0001. */ /*@{*/ #define BP_DMA_TCDn_CITER_ELINKNO_CITER (0U) /*!< Bit position for DMA_TCDn_CITER_ELINKNO_CITER. */ #define BM_DMA_TCDn_CITER_ELINKNO_CITER (0x7FFFU) /*!< Bit mask for DMA_TCDn_CITER_ELINKNO_CITER. */ #define BS_DMA_TCDn_CITER_ELINKNO_CITER (15U) /*!< Bit field size in bits for DMA_TCDn_CITER_ELINKNO_CITER. */ /*! @brief Read current value of the DMA_TCDn_CITER_ELINKNO_CITER field. */ #define BR_DMA_TCDn_CITER_ELINKNO_CITER(x, n) (HW_DMA_TCDn_CITER_ELINKNO(x, n).B.CITER) /*! @brief Format value for bitfield DMA_TCDn_CITER_ELINKNO_CITER. */ #define BF_DMA_TCDn_CITER_ELINKNO_CITER(v) ((uint16_t)((uint16_t)(v) << BP_DMA_TCDn_CITER_ELINKNO_CITER) & BM_DMA_TCDn_CITER_ELINKNO_CITER) /*! @brief Set the CITER field to a new value. */ #define BW_DMA_TCDn_CITER_ELINKNO_CITER(x, n, v) (HW_DMA_TCDn_CITER_ELINKNO_WR(x, n, (HW_DMA_TCDn_CITER_ELINKNO_RD(x, n) & ~BM_DMA_TCDn_CITER_ELINKNO_CITER) | BF_DMA_TCDn_CITER_ELINKNO_CITER(v))) /*@}*/ /*! * @name Register DMA_TCDn_CITER_ELINKNO, field ELINK[15] (RW) * * As the channel completes the minor loop, this flag enables linking to another * channel, defined by the LINKCH field. The link target channel initiates a * channel service request via an internal mechanism that sets the TCDn_CSR[START] * bit of the specified channel. If channel linking is disabled, the CITER value * is extended to 15 bits in place of a link channel number. If the major loop is * exhausted, this link mechanism is suppressed in favor of the MAJORELINK * channel linking. This bit must be equal to the BITER[ELINK] bit; otherwise, a * configuration error is reported. * * Values: * - 0 - The channel-to-channel linking is disabled * - 1 - The channel-to-channel linking is enabled */ /*@{*/ #define BP_DMA_TCDn_CITER_ELINKNO_ELINK (15U) /*!< Bit position for DMA_TCDn_CITER_ELINKNO_ELINK. */ #define BM_DMA_TCDn_CITER_ELINKNO_ELINK (0x8000U) /*!< Bit mask for DMA_TCDn_CITER_ELINKNO_ELINK. */ #define BS_DMA_TCDn_CITER_ELINKNO_ELINK (1U) /*!< Bit field size in bits for DMA_TCDn_CITER_ELINKNO_ELINK. */ /*! @brief Read current value of the DMA_TCDn_CITER_ELINKNO_ELINK field. */ #define BR_DMA_TCDn_CITER_ELINKNO_ELINK(x, n) (BITBAND_ACCESS16(HW_DMA_TCDn_CITER_ELINKNO_ADDR(x, n), BP_DMA_TCDn_CITER_ELINKNO_ELINK)) /*! @brief Format value for bitfield DMA_TCDn_CITER_ELINKNO_ELINK. */ #define BF_DMA_TCDn_CITER_ELINKNO_ELINK(v) ((uint16_t)((uint16_t)(v) << BP_DMA_TCDn_CITER_ELINKNO_ELINK) & BM_DMA_TCDn_CITER_ELINKNO_ELINK) /*! @brief Set the ELINK field to a new value. */ #define BW_DMA_TCDn_CITER_ELINKNO_ELINK(x, n, v) (BITBAND_ACCESS16(HW_DMA_TCDn_CITER_ELINKNO_ADDR(x, n), BP_DMA_TCDn_CITER_ELINKNO_ELINK) = (v)) /*@}*/ /******************************************************************************* * HW_DMA_TCDn_CITER_ELINKYES - TCD Current Minor Loop Link, Major Loop Count (Channel Linking Enabled) ******************************************************************************/ /*! * @brief HW_DMA_TCDn_CITER_ELINKYES - TCD Current Minor Loop Link, Major Loop Count (Channel Linking Enabled) (RW) * * Reset value: 0x0000U * * If TCDn_CITER[ELINK] is set, the TCDn_CITER register is defined as follows. */ typedef union _hw_dma_tcdn_citer_elinkyes { uint16_t U; struct _hw_dma_tcdn_citer_elinkyes_bitfields { uint16_t CITER : 9; /*!< [8:0] Current Major Iteration Count */ uint16_t LINKCH : 4; /*!< [12:9] Link Channel Number */ uint16_t RESERVED0 : 2; /*!< [14:13] */ uint16_t ELINK : 1; /*!< [15] Enable channel-to-channel linking on * minor-loop complete */ } B; } hw_dma_tcdn_citer_elinkyes_t; /*! * @name Constants and macros for entire DMA_TCDn_CITER_ELINKYES register */ /*@{*/ #define HW_DMA_TCDn_CITER_ELINKYES_COUNT (16U) #define HW_DMA_TCDn_CITER_ELINKYES_ADDR(x, n) ((x) + 0x1016U + (0x20U * (n))) #define HW_DMA_TCDn_CITER_ELINKYES(x, n) (*(__IO hw_dma_tcdn_citer_elinkyes_t *) HW_DMA_TCDn_CITER_ELINKYES_ADDR(x, n)) #define HW_DMA_TCDn_CITER_ELINKYES_RD(x, n) (HW_DMA_TCDn_CITER_ELINKYES(x, n).U) #define HW_DMA_TCDn_CITER_ELINKYES_WR(x, n, v) (HW_DMA_TCDn_CITER_ELINKYES(x, n).U = (v)) #define HW_DMA_TCDn_CITER_ELINKYES_SET(x, n, v) (HW_DMA_TCDn_CITER_ELINKYES_WR(x, n, HW_DMA_TCDn_CITER_ELINKYES_RD(x, n) | (v))) #define HW_DMA_TCDn_CITER_ELINKYES_CLR(x, n, v) (HW_DMA_TCDn_CITER_ELINKYES_WR(x, n, HW_DMA_TCDn_CITER_ELINKYES_RD(x, n) & ~(v))) #define HW_DMA_TCDn_CITER_ELINKYES_TOG(x, n, v) (HW_DMA_TCDn_CITER_ELINKYES_WR(x, n, HW_DMA_TCDn_CITER_ELINKYES_RD(x, n) ^ (v))) /*@}*/ /* * Constants & macros for individual DMA_TCDn_CITER_ELINKYES bitfields */ /*! * @name Register DMA_TCDn_CITER_ELINKYES, field CITER[8:0] (RW) * * This 9-bit (ELINK = 1) or 15-bit (ELINK = 0) count represents the current * major loop count for the channel. It is decremented each time the minor loop is * completed and updated in the transfer control descriptor memory. After the * major iteration count is exhausted, the channel performs a number of operations * (e.g., final source and destination address calculations), optionally generating * an interrupt to signal channel completion before reloading the CITER field * from the beginning iteration count (BITER) field. When the CITER field is * initially loaded by software, it must be set to the same value as that contained in * the BITER field. If the channel is configured to execute a single service * request, the initial values of BITER and CITER should be 0x0001. */ /*@{*/ #define BP_DMA_TCDn_CITER_ELINKYES_CITER (0U) /*!< Bit position for DMA_TCDn_CITER_ELINKYES_CITER. */ #define BM_DMA_TCDn_CITER_ELINKYES_CITER (0x01FFU) /*!< Bit mask for DMA_TCDn_CITER_ELINKYES_CITER. */ #define BS_DMA_TCDn_CITER_ELINKYES_CITER (9U) /*!< Bit field size in bits for DMA_TCDn_CITER_ELINKYES_CITER. */ /*! @brief Read current value of the DMA_TCDn_CITER_ELINKYES_CITER field. */ #define BR_DMA_TCDn_CITER_ELINKYES_CITER(x, n) (HW_DMA_TCDn_CITER_ELINKYES(x, n).B.CITER) /*! @brief Format value for bitfield DMA_TCDn_CITER_ELINKYES_CITER. */ #define BF_DMA_TCDn_CITER_ELINKYES_CITER(v) ((uint16_t)((uint16_t)(v) << BP_DMA_TCDn_CITER_ELINKYES_CITER) & BM_DMA_TCDn_CITER_ELINKYES_CITER) /*! @brief Set the CITER field to a new value. */ #define BW_DMA_TCDn_CITER_ELINKYES_CITER(x, n, v) (HW_DMA_TCDn_CITER_ELINKYES_WR(x, n, (HW_DMA_TCDn_CITER_ELINKYES_RD(x, n) & ~BM_DMA_TCDn_CITER_ELINKYES_CITER) | BF_DMA_TCDn_CITER_ELINKYES_CITER(v))) /*@}*/ /*! * @name Register DMA_TCDn_CITER_ELINKYES, field LINKCH[12:9] (RW) * * If channel-to-channel linking is enabled (ELINK = 1), then after the minor * loop is exhausted, the eDMA engine initiates a channel service request to the * channel defined by these four bits by setting that channel's TCDn_CSR[START] bit. */ /*@{*/ #define BP_DMA_TCDn_CITER_ELINKYES_LINKCH (9U) /*!< Bit position for DMA_TCDn_CITER_ELINKYES_LINKCH. */ #define BM_DMA_TCDn_CITER_ELINKYES_LINKCH (0x1E00U) /*!< Bit mask for DMA_TCDn_CITER_ELINKYES_LINKCH. */ #define BS_DMA_TCDn_CITER_ELINKYES_LINKCH (4U) /*!< Bit field size in bits for DMA_TCDn_CITER_ELINKYES_LINKCH. */ /*! @brief Read current value of the DMA_TCDn_CITER_ELINKYES_LINKCH field. */ #define BR_DMA_TCDn_CITER_ELINKYES_LINKCH(x, n) (HW_DMA_TCDn_CITER_ELINKYES(x, n).B.LINKCH) /*! @brief Format value for bitfield DMA_TCDn_CITER_ELINKYES_LINKCH. */ #define BF_DMA_TCDn_CITER_ELINKYES_LINKCH(v) ((uint16_t)((uint16_t)(v) << BP_DMA_TCDn_CITER_ELINKYES_LINKCH) & BM_DMA_TCDn_CITER_ELINKYES_LINKCH) /*! @brief Set the LINKCH field to a new value. */ #define BW_DMA_TCDn_CITER_ELINKYES_LINKCH(x, n, v) (HW_DMA_TCDn_CITER_ELINKYES_WR(x, n, (HW_DMA_TCDn_CITER_ELINKYES_RD(x, n) & ~BM_DMA_TCDn_CITER_ELINKYES_LINKCH) | BF_DMA_TCDn_CITER_ELINKYES_LINKCH(v))) /*@}*/ /*! * @name Register DMA_TCDn_CITER_ELINKYES, field ELINK[15] (RW) * * As the channel completes the minor loop, this flag enables linking to another * channel, defined by the LINKCH field. The link target channel initiates a * channel service request via an internal mechanism that sets the TCDn_CSR[START] * bit of the specified channel. If channel linking is disabled, the CITER value * is extended to 15 bits in place of a link channel number. If the major loop is * exhausted, this link mechanism is suppressed in favor of the MAJORELINK * channel linking. This bit must be equal to the BITER[ELINK] bit; otherwise, a * configuration error is reported. * * Values: * - 0 - The channel-to-channel linking is disabled * - 1 - The channel-to-channel linking is enabled */ /*@{*/ #define BP_DMA_TCDn_CITER_ELINKYES_ELINK (15U) /*!< Bit position for DMA_TCDn_CITER_ELINKYES_ELINK. */ #define BM_DMA_TCDn_CITER_ELINKYES_ELINK (0x8000U) /*!< Bit mask for DMA_TCDn_CITER_ELINKYES_ELINK. */ #define BS_DMA_TCDn_CITER_ELINKYES_ELINK (1U) /*!< Bit field size in bits for DMA_TCDn_CITER_ELINKYES_ELINK. */ /*! @brief Read current value of the DMA_TCDn_CITER_ELINKYES_ELINK field. */ #define BR_DMA_TCDn_CITER_ELINKYES_ELINK(x, n) (BITBAND_ACCESS16(HW_DMA_TCDn_CITER_ELINKYES_ADDR(x, n), BP_DMA_TCDn_CITER_ELINKYES_ELINK)) /*! @brief Format value for bitfield DMA_TCDn_CITER_ELINKYES_ELINK. */ #define BF_DMA_TCDn_CITER_ELINKYES_ELINK(v) ((uint16_t)((uint16_t)(v) << BP_DMA_TCDn_CITER_ELINKYES_ELINK) & BM_DMA_TCDn_CITER_ELINKYES_ELINK) /*! @brief Set the ELINK field to a new value. */ #define BW_DMA_TCDn_CITER_ELINKYES_ELINK(x, n, v) (BITBAND_ACCESS16(HW_DMA_TCDn_CITER_ELINKYES_ADDR(x, n), BP_DMA_TCDn_CITER_ELINKYES_ELINK) = (v)) /*@}*/ /******************************************************************************* * HW_DMA_TCDn_DLASTSGA - TCD Last Destination Address Adjustment/Scatter Gather Address ******************************************************************************/ /*! * @brief HW_DMA_TCDn_DLASTSGA - TCD Last Destination Address Adjustment/Scatter Gather Address (RW) * * Reset value: 0x00000000U */ typedef union _hw_dma_tcdn_dlastsga { uint32_t U; struct _hw_dma_tcdn_dlastsga_bitfields { uint32_t DLASTSGA : 32; /*!< [31:0] */ } B; } hw_dma_tcdn_dlastsga_t; /*! * @name Constants and macros for entire DMA_TCDn_DLASTSGA register */ /*@{*/ #define HW_DMA_TCDn_DLASTSGA_COUNT (16U) #define HW_DMA_TCDn_DLASTSGA_ADDR(x, n) ((x) + 0x1018U + (0x20U * (n))) #define HW_DMA_TCDn_DLASTSGA(x, n) (*(__IO hw_dma_tcdn_dlastsga_t *) HW_DMA_TCDn_DLASTSGA_ADDR(x, n)) #define HW_DMA_TCDn_DLASTSGA_RD(x, n) (HW_DMA_TCDn_DLASTSGA(x, n).U) #define HW_DMA_TCDn_DLASTSGA_WR(x, n, v) (HW_DMA_TCDn_DLASTSGA(x, n).U = (v)) #define HW_DMA_TCDn_DLASTSGA_SET(x, n, v) (HW_DMA_TCDn_DLASTSGA_WR(x, n, HW_DMA_TCDn_DLASTSGA_RD(x, n) | (v))) #define HW_DMA_TCDn_DLASTSGA_CLR(x, n, v) (HW_DMA_TCDn_DLASTSGA_WR(x, n, HW_DMA_TCDn_DLASTSGA_RD(x, n) & ~(v))) #define HW_DMA_TCDn_DLASTSGA_TOG(x, n, v) (HW_DMA_TCDn_DLASTSGA_WR(x, n, HW_DMA_TCDn_DLASTSGA_RD(x, n) ^ (v))) /*@}*/ /* * Constants & macros for individual DMA_TCDn_DLASTSGA bitfields */ /*! * @name Register DMA_TCDn_DLASTSGA, field DLASTSGA[31:0] (RW) * * Destination last address adjustment or the memory address for the next * transfer control descriptor to be loaded into this channel (scatter/gather). If * (TCDn_CSR[ESG] = 0), then: Adjustment value added to the destination address at * the completion of the major iteration count. This value can apply to restore the * destination address to the initial value or adjust the address to reference * the next data structure. This field uses two's complement notation for the * final destination address adjustment. Otherwise: This address points to the * beginning of a 0-modulo-32-byte region containing the next transfer control * descriptor to be loaded into this channel. This channel reload is performed as the * major iteration count completes. The scatter/gather address must be * 0-modulo-32-byte, else a configuration error is reported. */ /*@{*/ #define BP_DMA_TCDn_DLASTSGA_DLASTSGA (0U) /*!< Bit position for DMA_TCDn_DLASTSGA_DLASTSGA. */ #define BM_DMA_TCDn_DLASTSGA_DLASTSGA (0xFFFFFFFFU) /*!< Bit mask for DMA_TCDn_DLASTSGA_DLASTSGA. */ #define BS_DMA_TCDn_DLASTSGA_DLASTSGA (32U) /*!< Bit field size in bits for DMA_TCDn_DLASTSGA_DLASTSGA. */ /*! @brief Read current value of the DMA_TCDn_DLASTSGA_DLASTSGA field. */ #define BR_DMA_TCDn_DLASTSGA_DLASTSGA(x, n) (HW_DMA_TCDn_DLASTSGA(x, n).U) /*! @brief Format value for bitfield DMA_TCDn_DLASTSGA_DLASTSGA. */ #define BF_DMA_TCDn_DLASTSGA_DLASTSGA(v) ((uint32_t)((uint32_t)(v) << BP_DMA_TCDn_DLASTSGA_DLASTSGA) & BM_DMA_TCDn_DLASTSGA_DLASTSGA) /*! @brief Set the DLASTSGA field to a new value. */ #define BW_DMA_TCDn_DLASTSGA_DLASTSGA(x, n, v) (HW_DMA_TCDn_DLASTSGA_WR(x, n, v)) /*@}*/ /******************************************************************************* * HW_DMA_TCDn_CSR - TCD Control and Status ******************************************************************************/ /*! * @brief HW_DMA_TCDn_CSR - TCD Control and Status (RW) * * Reset value: 0x0000U */ typedef union _hw_dma_tcdn_csr { uint16_t U; struct _hw_dma_tcdn_csr_bitfields { uint16_t START : 1; /*!< [0] Channel Start */ uint16_t INTMAJOR : 1; /*!< [1] Enable an interrupt when major * iteration count completes */ uint16_t INTHALF : 1; /*!< [2] Enable an interrupt when major counter * is half complete. */ uint16_t DREQ : 1; /*!< [3] Disable Request */ uint16_t ESG : 1; /*!< [4] Enable Scatter/Gather Processing */ uint16_t MAJORELINK : 1; /*!< [5] Enable channel-to-channel linking * on major loop complete */ uint16_t ACTIVE : 1; /*!< [6] Channel Active */ uint16_t DONE : 1; /*!< [7] Channel Done */ uint16_t MAJORLINKCH : 4; /*!< [11:8] Link Channel Number */ uint16_t RESERVED0 : 2; /*!< [13:12] */ uint16_t BWC : 2; /*!< [15:14] Bandwidth Control */ } B; } hw_dma_tcdn_csr_t; /*! * @name Constants and macros for entire DMA_TCDn_CSR register */ /*@{*/ #define HW_DMA_TCDn_CSR_COUNT (16U) #define HW_DMA_TCDn_CSR_ADDR(x, n) ((x) + 0x101CU + (0x20U * (n))) #define HW_DMA_TCDn_CSR(x, n) (*(__IO hw_dma_tcdn_csr_t *) HW_DMA_TCDn_CSR_ADDR(x, n)) #define HW_DMA_TCDn_CSR_RD(x, n) (HW_DMA_TCDn_CSR(x, n).U) #define HW_DMA_TCDn_CSR_WR(x, n, v) (HW_DMA_TCDn_CSR(x, n).U = (v)) #define HW_DMA_TCDn_CSR_SET(x, n, v) (HW_DMA_TCDn_CSR_WR(x, n, HW_DMA_TCDn_CSR_RD(x, n) | (v))) #define HW_DMA_TCDn_CSR_CLR(x, n, v) (HW_DMA_TCDn_CSR_WR(x, n, HW_DMA_TCDn_CSR_RD(x, n) & ~(v))) #define HW_DMA_TCDn_CSR_TOG(x, n, v) (HW_DMA_TCDn_CSR_WR(x, n, HW_DMA_TCDn_CSR_RD(x, n) ^ (v))) /*@}*/ /* * Constants & macros for individual DMA_TCDn_CSR bitfields */ /*! * @name Register DMA_TCDn_CSR, field START[0] (RW) * * If this flag is set, the channel is requesting service. The eDMA hardware * automatically clears this flag after the channel begins execution. * * Values: * - 0 - The channel is not explicitly started * - 1 - The channel is explicitly started via a software initiated service * request */ /*@{*/ #define BP_DMA_TCDn_CSR_START (0U) /*!< Bit position for DMA_TCDn_CSR_START. */ #define BM_DMA_TCDn_CSR_START (0x0001U) /*!< Bit mask for DMA_TCDn_CSR_START. */ #define BS_DMA_TCDn_CSR_START (1U) /*!< Bit field size in bits for DMA_TCDn_CSR_START. */ /*! @brief Read current value of the DMA_TCDn_CSR_START field. */ #define BR_DMA_TCDn_CSR_START(x, n) (BITBAND_ACCESS16(HW_DMA_TCDn_CSR_ADDR(x, n), BP_DMA_TCDn_CSR_START)) /*! @brief Format value for bitfield DMA_TCDn_CSR_START. */ #define BF_DMA_TCDn_CSR_START(v) ((uint16_t)((uint16_t)(v) << BP_DMA_TCDn_CSR_START) & BM_DMA_TCDn_CSR_START) /*! @brief Set the START field to a new value. */ #define BW_DMA_TCDn_CSR_START(x, n, v) (BITBAND_ACCESS16(HW_DMA_TCDn_CSR_ADDR(x, n), BP_DMA_TCDn_CSR_START) = (v)) /*@}*/ /*! * @name Register DMA_TCDn_CSR, field INTMAJOR[1] (RW) * * If this flag is set, the channel generates an interrupt request by setting * the appropriate bit in the INT when the current major iteration count reaches * zero. * * Values: * - 0 - The end-of-major loop interrupt is disabled * - 1 - The end-of-major loop interrupt is enabled */ /*@{*/ #define BP_DMA_TCDn_CSR_INTMAJOR (1U) /*!< Bit position for DMA_TCDn_CSR_INTMAJOR. */ #define BM_DMA_TCDn_CSR_INTMAJOR (0x0002U) /*!< Bit mask for DMA_TCDn_CSR_INTMAJOR. */ #define BS_DMA_TCDn_CSR_INTMAJOR (1U) /*!< Bit field size in bits for DMA_TCDn_CSR_INTMAJOR. */ /*! @brief Read current value of the DMA_TCDn_CSR_INTMAJOR field. */ #define BR_DMA_TCDn_CSR_INTMAJOR(x, n) (BITBAND_ACCESS16(HW_DMA_TCDn_CSR_ADDR(x, n), BP_DMA_TCDn_CSR_INTMAJOR)) /*! @brief Format value for bitfield DMA_TCDn_CSR_INTMAJOR. */ #define BF_DMA_TCDn_CSR_INTMAJOR(v) ((uint16_t)((uint16_t)(v) << BP_DMA_TCDn_CSR_INTMAJOR) & BM_DMA_TCDn_CSR_INTMAJOR) /*! @brief Set the INTMAJOR field to a new value. */ #define BW_DMA_TCDn_CSR_INTMAJOR(x, n, v) (BITBAND_ACCESS16(HW_DMA_TCDn_CSR_ADDR(x, n), BP_DMA_TCDn_CSR_INTMAJOR) = (v)) /*@}*/ /*! * @name Register DMA_TCDn_CSR, field INTHALF[2] (RW) * * If this flag is set, the channel generates an interrupt request by setting * the appropriate bit in the INT register when the current major iteration count * reaches the halfway point. Specifically, the comparison performed by the eDMA * engine is (CITER == (BITER >> 1)). This halfway point interrupt request is * provided to support double-buffered (aka ping-pong) schemes or other types of data * movement where the processor needs an early indication of the transfer's * progress. If BITER is set, do not use INTHALF. Use INTMAJOR instead. * * Values: * - 0 - The half-point interrupt is disabled * - 1 - The half-point interrupt is enabled */ /*@{*/ #define BP_DMA_TCDn_CSR_INTHALF (2U) /*!< Bit position for DMA_TCDn_CSR_INTHALF. */ #define BM_DMA_TCDn_CSR_INTHALF (0x0004U) /*!< Bit mask for DMA_TCDn_CSR_INTHALF. */ #define BS_DMA_TCDn_CSR_INTHALF (1U) /*!< Bit field size in bits for DMA_TCDn_CSR_INTHALF. */ /*! @brief Read current value of the DMA_TCDn_CSR_INTHALF field. */ #define BR_DMA_TCDn_CSR_INTHALF(x, n) (BITBAND_ACCESS16(HW_DMA_TCDn_CSR_ADDR(x, n), BP_DMA_TCDn_CSR_INTHALF)) /*! @brief Format value for bitfield DMA_TCDn_CSR_INTHALF. */ #define BF_DMA_TCDn_CSR_INTHALF(v) ((uint16_t)((uint16_t)(v) << BP_DMA_TCDn_CSR_INTHALF) & BM_DMA_TCDn_CSR_INTHALF) /*! @brief Set the INTHALF field to a new value. */ #define BW_DMA_TCDn_CSR_INTHALF(x, n, v) (BITBAND_ACCESS16(HW_DMA_TCDn_CSR_ADDR(x, n), BP_DMA_TCDn_CSR_INTHALF) = (v)) /*@}*/ /*! * @name Register DMA_TCDn_CSR, field DREQ[3] (RW) * * If this flag is set, the eDMA hardware automatically clears the corresponding * ERQ bit when the current major iteration count reaches zero. * * Values: * - 0 - The channel's ERQ bit is not affected * - 1 - The channel's ERQ bit is cleared when the major loop is complete */ /*@{*/ #define BP_DMA_TCDn_CSR_DREQ (3U) /*!< Bit position for DMA_TCDn_CSR_DREQ. */ #define BM_DMA_TCDn_CSR_DREQ (0x0008U) /*!< Bit mask for DMA_TCDn_CSR_DREQ. */ #define BS_DMA_TCDn_CSR_DREQ (1U) /*!< Bit field size in bits for DMA_TCDn_CSR_DREQ. */ /*! @brief Read current value of the DMA_TCDn_CSR_DREQ field. */ #define BR_DMA_TCDn_CSR_DREQ(x, n) (BITBAND_ACCESS16(HW_DMA_TCDn_CSR_ADDR(x, n), BP_DMA_TCDn_CSR_DREQ)) /*! @brief Format value for bitfield DMA_TCDn_CSR_DREQ. */ #define BF_DMA_TCDn_CSR_DREQ(v) ((uint16_t)((uint16_t)(v) << BP_DMA_TCDn_CSR_DREQ) & BM_DMA_TCDn_CSR_DREQ) /*! @brief Set the DREQ field to a new value. */ #define BW_DMA_TCDn_CSR_DREQ(x, n, v) (BITBAND_ACCESS16(HW_DMA_TCDn_CSR_ADDR(x, n), BP_DMA_TCDn_CSR_DREQ) = (v)) /*@}*/ /*! * @name Register DMA_TCDn_CSR, field ESG[4] (RW) * * As the channel completes the major loop, this flag enables scatter/gather * processing in the current channel. If enabled, the eDMA engine uses DLASTSGA as a * memory pointer to a 0-modulo-32 address containing a 32-byte data structure * loaded as the transfer control descriptor into the local memory. To support the * dynamic scatter/gather coherency model, this field is forced to zero when * written to while the TCDn_CSR[DONE] bit is set. * * Values: * - 0 - The current channel's TCD is normal format. * - 1 - The current channel's TCD specifies a scatter gather format. The * DLASTSGA field provides a memory pointer to the next TCD to be loaded into this * channel after the major loop completes its execution. */ /*@{*/ #define BP_DMA_TCDn_CSR_ESG (4U) /*!< Bit position for DMA_TCDn_CSR_ESG. */ #define BM_DMA_TCDn_CSR_ESG (0x0010U) /*!< Bit mask for DMA_TCDn_CSR_ESG. */ #define BS_DMA_TCDn_CSR_ESG (1U) /*!< Bit field size in bits for DMA_TCDn_CSR_ESG. */ /*! @brief Read current value of the DMA_TCDn_CSR_ESG field. */ #define BR_DMA_TCDn_CSR_ESG(x, n) (BITBAND_ACCESS16(HW_DMA_TCDn_CSR_ADDR(x, n), BP_DMA_TCDn_CSR_ESG)) /*! @brief Format value for bitfield DMA_TCDn_CSR_ESG. */ #define BF_DMA_TCDn_CSR_ESG(v) ((uint16_t)((uint16_t)(v) << BP_DMA_TCDn_CSR_ESG) & BM_DMA_TCDn_CSR_ESG) /*! @brief Set the ESG field to a new value. */ #define BW_DMA_TCDn_CSR_ESG(x, n, v) (BITBAND_ACCESS16(HW_DMA_TCDn_CSR_ADDR(x, n), BP_DMA_TCDn_CSR_ESG) = (v)) /*@}*/ /*! * @name Register DMA_TCDn_CSR, field MAJORELINK[5] (RW) * * As the channel completes the major loop, this flag enables the linking to * another channel, defined by MAJORLINKCH. The link target channel initiates a * channel service request via an internal mechanism that sets the TCDn_CSR[START] * bit of the specified channel. To support the dynamic linking coherency model, * this field is forced to zero when written to while the TCDn_CSR[DONE] bit is set. * * Values: * - 0 - The channel-to-channel linking is disabled * - 1 - The channel-to-channel linking is enabled */ /*@{*/ #define BP_DMA_TCDn_CSR_MAJORELINK (5U) /*!< Bit position for DMA_TCDn_CSR_MAJORELINK. */ #define BM_DMA_TCDn_CSR_MAJORELINK (0x0020U) /*!< Bit mask for DMA_TCDn_CSR_MAJORELINK. */ #define BS_DMA_TCDn_CSR_MAJORELINK (1U) /*!< Bit field size in bits for DMA_TCDn_CSR_MAJORELINK. */ /*! @brief Read current value of the DMA_TCDn_CSR_MAJORELINK field. */ #define BR_DMA_TCDn_CSR_MAJORELINK(x, n) (BITBAND_ACCESS16(HW_DMA_TCDn_CSR_ADDR(x, n), BP_DMA_TCDn_CSR_MAJORELINK)) /*! @brief Format value for bitfield DMA_TCDn_CSR_MAJORELINK. */ #define BF_DMA_TCDn_CSR_MAJORELINK(v) ((uint16_t)((uint16_t)(v) << BP_DMA_TCDn_CSR_MAJORELINK) & BM_DMA_TCDn_CSR_MAJORELINK) /*! @brief Set the MAJORELINK field to a new value. */ #define BW_DMA_TCDn_CSR_MAJORELINK(x, n, v) (BITBAND_ACCESS16(HW_DMA_TCDn_CSR_ADDR(x, n), BP_DMA_TCDn_CSR_MAJORELINK) = (v)) /*@}*/ /*! * @name Register DMA_TCDn_CSR, field ACTIVE[6] (RW) * * This flag signals the channel is currently in execution. It is set when * channel service begins, and the eDMA clears it as the minor loop completes or if * any error condition is detected. This bit resets to zero. */ /*@{*/ #define BP_DMA_TCDn_CSR_ACTIVE (6U) /*!< Bit position for DMA_TCDn_CSR_ACTIVE. */ #define BM_DMA_TCDn_CSR_ACTIVE (0x0040U) /*!< Bit mask for DMA_TCDn_CSR_ACTIVE. */ #define BS_DMA_TCDn_CSR_ACTIVE (1U) /*!< Bit field size in bits for DMA_TCDn_CSR_ACTIVE. */ /*! @brief Read current value of the DMA_TCDn_CSR_ACTIVE field. */ #define BR_DMA_TCDn_CSR_ACTIVE(x, n) (BITBAND_ACCESS16(HW_DMA_TCDn_CSR_ADDR(x, n), BP_DMA_TCDn_CSR_ACTIVE)) /*! @brief Format value for bitfield DMA_TCDn_CSR_ACTIVE. */ #define BF_DMA_TCDn_CSR_ACTIVE(v) ((uint16_t)((uint16_t)(v) << BP_DMA_TCDn_CSR_ACTIVE) & BM_DMA_TCDn_CSR_ACTIVE) /*! @brief Set the ACTIVE field to a new value. */ #define BW_DMA_TCDn_CSR_ACTIVE(x, n, v) (BITBAND_ACCESS16(HW_DMA_TCDn_CSR_ADDR(x, n), BP_DMA_TCDn_CSR_ACTIVE) = (v)) /*@}*/ /*! * @name Register DMA_TCDn_CSR, field DONE[7] (RW) * * This flag indicates the eDMA has completed the major loop. The eDMA engine * sets it as the CITER count reaches zero; The software clears it, or the hardware * when the channel is activated. This bit must be cleared to write the * MAJORELINK or ESG bits. */ /*@{*/ #define BP_DMA_TCDn_CSR_DONE (7U) /*!< Bit position for DMA_TCDn_CSR_DONE. */ #define BM_DMA_TCDn_CSR_DONE (0x0080U) /*!< Bit mask for DMA_TCDn_CSR_DONE. */ #define BS_DMA_TCDn_CSR_DONE (1U) /*!< Bit field size in bits for DMA_TCDn_CSR_DONE. */ /*! @brief Read current value of the DMA_TCDn_CSR_DONE field. */ #define BR_DMA_TCDn_CSR_DONE(x, n) (BITBAND_ACCESS16(HW_DMA_TCDn_CSR_ADDR(x, n), BP_DMA_TCDn_CSR_DONE)) /*! @brief Format value for bitfield DMA_TCDn_CSR_DONE. */ #define BF_DMA_TCDn_CSR_DONE(v) ((uint16_t)((uint16_t)(v) << BP_DMA_TCDn_CSR_DONE) & BM_DMA_TCDn_CSR_DONE) /*! @brief Set the DONE field to a new value. */ #define BW_DMA_TCDn_CSR_DONE(x, n, v) (BITBAND_ACCESS16(HW_DMA_TCDn_CSR_ADDR(x, n), BP_DMA_TCDn_CSR_DONE) = (v)) /*@}*/ /*! * @name Register DMA_TCDn_CSR, field MAJORLINKCH[11:8] (RW) * * If (MAJORELINK = 0) then No channel-to-channel linking (or chaining) is * performed after the major loop counter is exhausted. else After the major loop * counter is exhausted, the eDMA engine initiates a channel service request at the * channel defined by these six bits by setting that channel's TCDn_CSR[START] bit. */ /*@{*/ #define BP_DMA_TCDn_CSR_MAJORLINKCH (8U) /*!< Bit position for DMA_TCDn_CSR_MAJORLINKCH. */ #define BM_DMA_TCDn_CSR_MAJORLINKCH (0x0F00U) /*!< Bit mask for DMA_TCDn_CSR_MAJORLINKCH. */ #define BS_DMA_TCDn_CSR_MAJORLINKCH (4U) /*!< Bit field size in bits for DMA_TCDn_CSR_MAJORLINKCH. */ /*! @brief Read current value of the DMA_TCDn_CSR_MAJORLINKCH field. */ #define BR_DMA_TCDn_CSR_MAJORLINKCH(x, n) (HW_DMA_TCDn_CSR(x, n).B.MAJORLINKCH) /*! @brief Format value for bitfield DMA_TCDn_CSR_MAJORLINKCH. */ #define BF_DMA_TCDn_CSR_MAJORLINKCH(v) ((uint16_t)((uint16_t)(v) << BP_DMA_TCDn_CSR_MAJORLINKCH) & BM_DMA_TCDn_CSR_MAJORLINKCH) /*! @brief Set the MAJORLINKCH field to a new value. */ #define BW_DMA_TCDn_CSR_MAJORLINKCH(x, n, v) (HW_DMA_TCDn_CSR_WR(x, n, (HW_DMA_TCDn_CSR_RD(x, n) & ~BM_DMA_TCDn_CSR_MAJORLINKCH) | BF_DMA_TCDn_CSR_MAJORLINKCH(v))) /*@}*/ /*! * @name Register DMA_TCDn_CSR, field BWC[15:14] (RW) * * Throttles the amount of bus bandwidth consumed by the eDMA. In general, as * the eDMA processes the minor loop, it continuously generates read/write * sequences until the minor count is exhausted. This field forces the eDMA to stall * after the completion of each read/write access to control the bus request * bandwidth seen by the crossbar switch. If the source and destination sizes are equal, * this field is ignored between the first and second transfers and after the * last write of each minor loop. This behavior is a side effect of reducing * start-up latency. * * Values: * - 00 - No eDMA engine stalls * - 01 - Reserved * - 10 - eDMA engine stalls for 4 cycles after each r/w * - 11 - eDMA engine stalls for 8 cycles after each r/w */ /*@{*/ #define BP_DMA_TCDn_CSR_BWC (14U) /*!< Bit position for DMA_TCDn_CSR_BWC. */ #define BM_DMA_TCDn_CSR_BWC (0xC000U) /*!< Bit mask for DMA_TCDn_CSR_BWC. */ #define BS_DMA_TCDn_CSR_BWC (2U) /*!< Bit field size in bits for DMA_TCDn_CSR_BWC. */ /*! @brief Read current value of the DMA_TCDn_CSR_BWC field. */ #define BR_DMA_TCDn_CSR_BWC(x, n) (HW_DMA_TCDn_CSR(x, n).B.BWC) /*! @brief Format value for bitfield DMA_TCDn_CSR_BWC. */ #define BF_DMA_TCDn_CSR_BWC(v) ((uint16_t)((uint16_t)(v) << BP_DMA_TCDn_CSR_BWC) & BM_DMA_TCDn_CSR_BWC) /*! @brief Set the BWC field to a new value. */ #define BW_DMA_TCDn_CSR_BWC(x, n, v) (HW_DMA_TCDn_CSR_WR(x, n, (HW_DMA_TCDn_CSR_RD(x, n) & ~BM_DMA_TCDn_CSR_BWC) | BF_DMA_TCDn_CSR_BWC(v))) /*@}*/ /******************************************************************************* * HW_DMA_TCDn_BITER_ELINKNO - TCD Beginning Minor Loop Link, Major Loop Count (Channel Linking Disabled) ******************************************************************************/ /*! * @brief HW_DMA_TCDn_BITER_ELINKNO - TCD Beginning Minor Loop Link, Major Loop Count (Channel Linking Disabled) (RW) * * Reset value: 0x0000U * * If the TCDn_BITER[ELINK] bit is cleared, the TCDn_BITER register is defined * as follows. */ typedef union _hw_dma_tcdn_biter_elinkno { uint16_t U; struct _hw_dma_tcdn_biter_elinkno_bitfields { uint16_t BITER : 15; /*!< [14:0] Starting Major Iteration Count */ uint16_t ELINK : 1; /*!< [15] Enables channel-to-channel linking on * minor loop complete */ } B; } hw_dma_tcdn_biter_elinkno_t; /*! * @name Constants and macros for entire DMA_TCDn_BITER_ELINKNO register */ /*@{*/ #define HW_DMA_TCDn_BITER_ELINKNO_COUNT (16U) #define HW_DMA_TCDn_BITER_ELINKNO_ADDR(x, n) ((x) + 0x101EU + (0x20U * (n))) #define HW_DMA_TCDn_BITER_ELINKNO(x, n) (*(__IO hw_dma_tcdn_biter_elinkno_t *) HW_DMA_TCDn_BITER_ELINKNO_ADDR(x, n)) #define HW_DMA_TCDn_BITER_ELINKNO_RD(x, n) (HW_DMA_TCDn_BITER_ELINKNO(x, n).U) #define HW_DMA_TCDn_BITER_ELINKNO_WR(x, n, v) (HW_DMA_TCDn_BITER_ELINKNO(x, n).U = (v)) #define HW_DMA_TCDn_BITER_ELINKNO_SET(x, n, v) (HW_DMA_TCDn_BITER_ELINKNO_WR(x, n, HW_DMA_TCDn_BITER_ELINKNO_RD(x, n) | (v))) #define HW_DMA_TCDn_BITER_ELINKNO_CLR(x, n, v) (HW_DMA_TCDn_BITER_ELINKNO_WR(x, n, HW_DMA_TCDn_BITER_ELINKNO_RD(x, n) & ~(v))) #define HW_DMA_TCDn_BITER_ELINKNO_TOG(x, n, v) (HW_DMA_TCDn_BITER_ELINKNO_WR(x, n, HW_DMA_TCDn_BITER_ELINKNO_RD(x, n) ^ (v))) /*@}*/ /* * Constants & macros for individual DMA_TCDn_BITER_ELINKNO bitfields */ /*! * @name Register DMA_TCDn_BITER_ELINKNO, field BITER[14:0] (RW) * * As the transfer control descriptor is first loaded by software, this 9-bit * (ELINK = 1) or 15-bit (ELINK = 0) field must be equal to the value in the CITER * field. As the major iteration count is exhausted, the contents of this field * are reloaded into the CITER field. When the software loads the TCD, this field * must be set equal to the corresponding CITER field; otherwise, a configuration * error is reported. As the major iteration count is exhausted, the contents of * this field is reloaded into the CITER field. If the channel is configured to * execute a single service request, the initial values of BITER and CITER should * be 0x0001. */ /*@{*/ #define BP_DMA_TCDn_BITER_ELINKNO_BITER (0U) /*!< Bit position for DMA_TCDn_BITER_ELINKNO_BITER. */ #define BM_DMA_TCDn_BITER_ELINKNO_BITER (0x7FFFU) /*!< Bit mask for DMA_TCDn_BITER_ELINKNO_BITER. */ #define BS_DMA_TCDn_BITER_ELINKNO_BITER (15U) /*!< Bit field size in bits for DMA_TCDn_BITER_ELINKNO_BITER. */ /*! @brief Read current value of the DMA_TCDn_BITER_ELINKNO_BITER field. */ #define BR_DMA_TCDn_BITER_ELINKNO_BITER(x, n) (HW_DMA_TCDn_BITER_ELINKNO(x, n).B.BITER) /*! @brief Format value for bitfield DMA_TCDn_BITER_ELINKNO_BITER. */ #define BF_DMA_TCDn_BITER_ELINKNO_BITER(v) ((uint16_t)((uint16_t)(v) << BP_DMA_TCDn_BITER_ELINKNO_BITER) & BM_DMA_TCDn_BITER_ELINKNO_BITER) /*! @brief Set the BITER field to a new value. */ #define BW_DMA_TCDn_BITER_ELINKNO_BITER(x, n, v) (HW_DMA_TCDn_BITER_ELINKNO_WR(x, n, (HW_DMA_TCDn_BITER_ELINKNO_RD(x, n) & ~BM_DMA_TCDn_BITER_ELINKNO_BITER) | BF_DMA_TCDn_BITER_ELINKNO_BITER(v))) /*@}*/ /*! * @name Register DMA_TCDn_BITER_ELINKNO, field ELINK[15] (RW) * * As the channel completes the minor loop, this flag enables the linking to * another channel, defined by BITER[LINKCH]. The link target channel initiates a * channel service request via an internal mechanism that sets the TCDn_CSR[START] * bit of the specified channel. If channel linking is disabled, the BITER value * extends to 15 bits in place of a link channel number. If the major loop is * exhausted, this link mechanism is suppressed in favor of the MAJORELINK channel * linking. When the software loads the TCD, this field must be set equal to the * corresponding CITER field; otherwise, a configuration error is reported. As the * major iteration count is exhausted, the contents of this field is reloaded * into the CITER field. * * Values: * - 0 - The channel-to-channel linking is disabled * - 1 - The channel-to-channel linking is enabled */ /*@{*/ #define BP_DMA_TCDn_BITER_ELINKNO_ELINK (15U) /*!< Bit position for DMA_TCDn_BITER_ELINKNO_ELINK. */ #define BM_DMA_TCDn_BITER_ELINKNO_ELINK (0x8000U) /*!< Bit mask for DMA_TCDn_BITER_ELINKNO_ELINK. */ #define BS_DMA_TCDn_BITER_ELINKNO_ELINK (1U) /*!< Bit field size in bits for DMA_TCDn_BITER_ELINKNO_ELINK. */ /*! @brief Read current value of the DMA_TCDn_BITER_ELINKNO_ELINK field. */ #define BR_DMA_TCDn_BITER_ELINKNO_ELINK(x, n) (BITBAND_ACCESS16(HW_DMA_TCDn_BITER_ELINKNO_ADDR(x, n), BP_DMA_TCDn_BITER_ELINKNO_ELINK)) /*! @brief Format value for bitfield DMA_TCDn_BITER_ELINKNO_ELINK. */ #define BF_DMA_TCDn_BITER_ELINKNO_ELINK(v) ((uint16_t)((uint16_t)(v) << BP_DMA_TCDn_BITER_ELINKNO_ELINK) & BM_DMA_TCDn_BITER_ELINKNO_ELINK) /*! @brief Set the ELINK field to a new value. */ #define BW_DMA_TCDn_BITER_ELINKNO_ELINK(x, n, v) (BITBAND_ACCESS16(HW_DMA_TCDn_BITER_ELINKNO_ADDR(x, n), BP_DMA_TCDn_BITER_ELINKNO_ELINK) = (v)) /*@}*/ /******************************************************************************* * HW_DMA_TCDn_BITER_ELINKYES - TCD Beginning Minor Loop Link, Major Loop Count (Channel Linking Enabled) ******************************************************************************/ /*! * @brief HW_DMA_TCDn_BITER_ELINKYES - TCD Beginning Minor Loop Link, Major Loop Count (Channel Linking Enabled) (RW) * * Reset value: 0x0000U * * If the TCDn_BITER[ELINK] bit is set, the TCDn_BITER register is defined as * follows. */ typedef union _hw_dma_tcdn_biter_elinkyes { uint16_t U; struct _hw_dma_tcdn_biter_elinkyes_bitfields { uint16_t BITER : 9; /*!< [8:0] Starting Major Iteration Count */ uint16_t LINKCH : 4; /*!< [12:9] Link Channel Number */ uint16_t RESERVED0 : 2; /*!< [14:13] */ uint16_t ELINK : 1; /*!< [15] Enables channel-to-channel linking on * minor loop complete */ } B; } hw_dma_tcdn_biter_elinkyes_t; /*! * @name Constants and macros for entire DMA_TCDn_BITER_ELINKYES register */ /*@{*/ #define HW_DMA_TCDn_BITER_ELINKYES_COUNT (16U) #define HW_DMA_TCDn_BITER_ELINKYES_ADDR(x, n) ((x) + 0x101EU + (0x20U * (n))) #define HW_DMA_TCDn_BITER_ELINKYES(x, n) (*(__IO hw_dma_tcdn_biter_elinkyes_t *) HW_DMA_TCDn_BITER_ELINKYES_ADDR(x, n)) #define HW_DMA_TCDn_BITER_ELINKYES_RD(x, n) (HW_DMA_TCDn_BITER_ELINKYES(x, n).U) #define HW_DMA_TCDn_BITER_ELINKYES_WR(x, n, v) (HW_DMA_TCDn_BITER_ELINKYES(x, n).U = (v)) #define HW_DMA_TCDn_BITER_ELINKYES_SET(x, n, v) (HW_DMA_TCDn_BITER_ELINKYES_WR(x, n, HW_DMA_TCDn_BITER_ELINKYES_RD(x, n) | (v))) #define HW_DMA_TCDn_BITER_ELINKYES_CLR(x, n, v) (HW_DMA_TCDn_BITER_ELINKYES_WR(x, n, HW_DMA_TCDn_BITER_ELINKYES_RD(x, n) & ~(v))) #define HW_DMA_TCDn_BITER_ELINKYES_TOG(x, n, v) (HW_DMA_TCDn_BITER_ELINKYES_WR(x, n, HW_DMA_TCDn_BITER_ELINKYES_RD(x, n) ^ (v))) /*@}*/ /* * Constants & macros for individual DMA_TCDn_BITER_ELINKYES bitfields */ /*! * @name Register DMA_TCDn_BITER_ELINKYES, field BITER[8:0] (RW) * * As the transfer control descriptor is first loaded by software, this 9-bit * (ELINK = 1) or 15-bit (ELINK = 0) field must be equal to the value in the CITER * field. As the major iteration count is exhausted, the contents of this field * are reloaded into the CITER field. When the software loads the TCD, this field * must be set equal to the corresponding CITER field; otherwise, a configuration * error is reported. As the major iteration count is exhausted, the contents of * this field is reloaded into the CITER field. If the channel is configured to * execute a single service request, the initial values of BITER and CITER should * be 0x0001. */ /*@{*/ #define BP_DMA_TCDn_BITER_ELINKYES_BITER (0U) /*!< Bit position for DMA_TCDn_BITER_ELINKYES_BITER. */ #define BM_DMA_TCDn_BITER_ELINKYES_BITER (0x01FFU) /*!< Bit mask for DMA_TCDn_BITER_ELINKYES_BITER. */ #define BS_DMA_TCDn_BITER_ELINKYES_BITER (9U) /*!< Bit field size in bits for DMA_TCDn_BITER_ELINKYES_BITER. */ /*! @brief Read current value of the DMA_TCDn_BITER_ELINKYES_BITER field. */ #define BR_DMA_TCDn_BITER_ELINKYES_BITER(x, n) (HW_DMA_TCDn_BITER_ELINKYES(x, n).B.BITER) /*! @brief Format value for bitfield DMA_TCDn_BITER_ELINKYES_BITER. */ #define BF_DMA_TCDn_BITER_ELINKYES_BITER(v) ((uint16_t)((uint16_t)(v) << BP_DMA_TCDn_BITER_ELINKYES_BITER) & BM_DMA_TCDn_BITER_ELINKYES_BITER) /*! @brief Set the BITER field to a new value. */ #define BW_DMA_TCDn_BITER_ELINKYES_BITER(x, n, v) (HW_DMA_TCDn_BITER_ELINKYES_WR(x, n, (HW_DMA_TCDn_BITER_ELINKYES_RD(x, n) & ~BM_DMA_TCDn_BITER_ELINKYES_BITER) | BF_DMA_TCDn_BITER_ELINKYES_BITER(v))) /*@}*/ /*! * @name Register DMA_TCDn_BITER_ELINKYES, field LINKCH[12:9] (RW) * * If channel-to-channel linking is enabled (ELINK = 1), then after the minor * loop is exhausted, the eDMA engine initiates a channel service request at the * channel defined by these four bits by setting that channel's TCDn_CSR[START] * bit. When the software loads the TCD, this field must be set equal to the * corresponding CITER field; otherwise, a configuration error is reported. As the major * iteration count is exhausted, the contents of this field is reloaded into the * CITER field. */ /*@{*/ #define BP_DMA_TCDn_BITER_ELINKYES_LINKCH (9U) /*!< Bit position for DMA_TCDn_BITER_ELINKYES_LINKCH. */ #define BM_DMA_TCDn_BITER_ELINKYES_LINKCH (0x1E00U) /*!< Bit mask for DMA_TCDn_BITER_ELINKYES_LINKCH. */ #define BS_DMA_TCDn_BITER_ELINKYES_LINKCH (4U) /*!< Bit field size in bits for DMA_TCDn_BITER_ELINKYES_LINKCH. */ /*! @brief Read current value of the DMA_TCDn_BITER_ELINKYES_LINKCH field. */ #define BR_DMA_TCDn_BITER_ELINKYES_LINKCH(x, n) (HW_DMA_TCDn_BITER_ELINKYES(x, n).B.LINKCH) /*! @brief Format value for bitfield DMA_TCDn_BITER_ELINKYES_LINKCH. */ #define BF_DMA_TCDn_BITER_ELINKYES_LINKCH(v) ((uint16_t)((uint16_t)(v) << BP_DMA_TCDn_BITER_ELINKYES_LINKCH) & BM_DMA_TCDn_BITER_ELINKYES_LINKCH) /*! @brief Set the LINKCH field to a new value. */ #define BW_DMA_TCDn_BITER_ELINKYES_LINKCH(x, n, v) (HW_DMA_TCDn_BITER_ELINKYES_WR(x, n, (HW_DMA_TCDn_BITER_ELINKYES_RD(x, n) & ~BM_DMA_TCDn_BITER_ELINKYES_LINKCH) | BF_DMA_TCDn_BITER_ELINKYES_LINKCH(v))) /*@}*/ /*! * @name Register DMA_TCDn_BITER_ELINKYES, field ELINK[15] (RW) * * As the channel completes the minor loop, this flag enables the linking to * another channel, defined by BITER[LINKCH]. The link target channel initiates a * channel service request via an internal mechanism that sets the TCDn_CSR[START] * bit of the specified channel. If channel linking disables, the BITER value * extends to 15 bits in place of a link channel number. If the major loop is * exhausted, this link mechanism is suppressed in favor of the MAJORELINK channel * linking. When the software loads the TCD, this field must be set equal to the * corresponding CITER field; otherwise, a configuration error is reported. As the * major iteration count is exhausted, the contents of this field is reloaded into * the CITER field. * * Values: * - 0 - The channel-to-channel linking is disabled * - 1 - The channel-to-channel linking is enabled */ /*@{*/ #define BP_DMA_TCDn_BITER_ELINKYES_ELINK (15U) /*!< Bit position for DMA_TCDn_BITER_ELINKYES_ELINK. */ #define BM_DMA_TCDn_BITER_ELINKYES_ELINK (0x8000U) /*!< Bit mask for DMA_TCDn_BITER_ELINKYES_ELINK. */ #define BS_DMA_TCDn_BITER_ELINKYES_ELINK (1U) /*!< Bit field size in bits for DMA_TCDn_BITER_ELINKYES_ELINK. */ /*! @brief Read current value of the DMA_TCDn_BITER_ELINKYES_ELINK field. */ #define BR_DMA_TCDn_BITER_ELINKYES_ELINK(x, n) (BITBAND_ACCESS16(HW_DMA_TCDn_BITER_ELINKYES_ADDR(x, n), BP_DMA_TCDn_BITER_ELINKYES_ELINK)) /*! @brief Format value for bitfield DMA_TCDn_BITER_ELINKYES_ELINK. */ #define BF_DMA_TCDn_BITER_ELINKYES_ELINK(v) ((uint16_t)((uint16_t)(v) << BP_DMA_TCDn_BITER_ELINKYES_ELINK) & BM_DMA_TCDn_BITER_ELINKYES_ELINK) /*! @brief Set the ELINK field to a new value. */ #define BW_DMA_TCDn_BITER_ELINKYES_ELINK(x, n, v) (BITBAND_ACCESS16(HW_DMA_TCDn_BITER_ELINKYES_ADDR(x, n), BP_DMA_TCDn_BITER_ELINKYES_ELINK) = (v)) /*@}*/ /* ** Start of section using anonymous unions */ #if defined(__ARMCC_VERSION) #pragma push #pragma anon_unions #elif defined(__CWCC__) #pragma push #pragma cpp_extensions on #elif defined(__GNUC__) /* anonymous unions are enabled by default */ #elif defined(__IAR_SYSTEMS_ICC__) #pragma language=extended #else #error Not supported compiler type #endif /******************************************************************************* * hw_dma_t - module struct ******************************************************************************/ /*! * @brief All DMA module registers. */ #pragma pack(1) typedef struct _hw_dma { __IO hw_dma_cr_t CR; /*!< [0x0] Control Register */ __I hw_dma_es_t ES; /*!< [0x4] Error Status Register */ uint8_t _reserved0[4]; __IO hw_dma_erq_t ERQ; /*!< [0xC] Enable Request Register */ uint8_t _reserved1[4]; __IO hw_dma_eei_t EEI; /*!< [0x14] Enable Error Interrupt Register */ __O hw_dma_ceei_t CEEI; /*!< [0x18] Clear Enable Error Interrupt Register */ __O hw_dma_seei_t SEEI; /*!< [0x19] Set Enable Error Interrupt Register */ __O hw_dma_cerq_t CERQ; /*!< [0x1A] Clear Enable Request Register */ __O hw_dma_serq_t SERQ; /*!< [0x1B] Set Enable Request Register */ __O hw_dma_cdne_t CDNE; /*!< [0x1C] Clear DONE Status Bit Register */ __O hw_dma_ssrt_t SSRT; /*!< [0x1D] Set START Bit Register */ __O hw_dma_cerr_t CERR; /*!< [0x1E] Clear Error Register */ __O hw_dma_cint_t CINT; /*!< [0x1F] Clear Interrupt Request Register */ uint8_t _reserved2[4]; __IO hw_dma_int_t INT; /*!< [0x24] Interrupt Request Register */ uint8_t _reserved3[4]; __IO hw_dma_err_t ERR; /*!< [0x2C] Error Register */ uint8_t _reserved4[4]; __I hw_dma_hrs_t HRS; /*!< [0x34] Hardware Request Status Register */ uint8_t _reserved5[200]; __IO hw_dma_dchprin_t DCHPRIn[16]; /*!< [0x100] Channel n Priority Register */ uint8_t _reserved6[3824]; struct { __IO hw_dma_tcdn_saddr_t TCDn_SADDR; /*!< [0x1000] TCD Source Address */ __IO hw_dma_tcdn_soff_t TCDn_SOFF; /*!< [0x1004] TCD Signed Source Address Offset */ __IO hw_dma_tcdn_attr_t TCDn_ATTR; /*!< [0x1006] TCD Transfer Attributes */ union { __IO hw_dma_tcdn_nbytes_mlno_t TCDn_NBYTES_MLNO; /*!< [0x1008] TCD Minor Byte Count (Minor Loop Disabled) */ __IO hw_dma_tcdn_nbytes_mloffno_t TCDn_NBYTES_MLOFFNO; /*!< [0x1008] TCD Signed Minor Loop Offset (Minor Loop Enabled and Offset Disabled) */ __IO hw_dma_tcdn_nbytes_mloffyes_t TCDn_NBYTES_MLOFFYES; /*!< [0x1008] TCD Signed Minor Loop Offset (Minor Loop and Offset Enabled) */ }; __IO hw_dma_tcdn_slast_t TCDn_SLAST; /*!< [0x100C] TCD Last Source Address Adjustment */ __IO hw_dma_tcdn_daddr_t TCDn_DADDR; /*!< [0x1010] TCD Destination Address */ __IO hw_dma_tcdn_doff_t TCDn_DOFF; /*!< [0x1014] TCD Signed Destination Address Offset */ union { __IO hw_dma_tcdn_citer_elinkno_t TCDn_CITER_ELINKNO; /*!< [0x1016] TCD Current Minor Loop Link, Major Loop Count (Channel Linking Disabled) */ __IO hw_dma_tcdn_citer_elinkyes_t TCDn_CITER_ELINKYES; /*!< [0x1016] TCD Current Minor Loop Link, Major Loop Count (Channel Linking Enabled) */ }; __IO hw_dma_tcdn_dlastsga_t TCDn_DLASTSGA; /*!< [0x1018] TCD Last Destination Address Adjustment/Scatter Gather Address */ __IO hw_dma_tcdn_csr_t TCDn_CSR; /*!< [0x101C] TCD Control and Status */ union { __IO hw_dma_tcdn_biter_elinkno_t TCDn_BITER_ELINKNO; /*!< [0x101E] TCD Beginning Minor Loop Link, Major Loop Count (Channel Linking Disabled) */ __IO hw_dma_tcdn_biter_elinkyes_t TCDn_BITER_ELINKYES; /*!< [0x101E] TCD Beginning Minor Loop Link, Major Loop Count (Channel Linking Enabled) */ }; } TCD[16]; } hw_dma_t; #pragma pack() /*! @brief Macro to access all DMA registers. */ /*! @param x DMA module instance base address. */ /*! @return Reference (not a pointer) to the registers struct. To get a pointer to the struct, * use the '&' operator, like &HW_DMA(DMA_BASE). */ #define HW_DMA(x) (*(hw_dma_t *)(x)) /* ** End of section using anonymous unions */ #if defined(__ARMCC_VERSION) #pragma pop #elif defined(__CWCC__) #pragma pop #elif defined(__GNUC__) /* leave anonymous unions enabled */ #elif defined(__IAR_SYSTEMS_ICC__) #pragma language=default #else #error Not supported compiler type #endif #endif /* __HW_DMA_REGISTERS_H__ */ /* EOF */ ================================================ FILE: Zelig/mbed/TARGET_K64F/TARGET_Freescale/TARGET_KPSDK_MCUS/TARGET_MCU_K64F/device/device/MK64F12/MK64F12_dmamux.h ================================================ /* ** ################################################################### ** Compilers: Keil ARM C/C++ Compiler ** Freescale C/C++ for Embedded ARM ** GNU C Compiler ** IAR ANSI C/C++ Compiler for ARM ** ** Reference manual: K64P144M120SF5RM, Rev.2, January 2014 ** Version: rev. 2.5, 2014-02-10 ** Build: b140604 ** ** Abstract: ** Extension to the CMSIS register access layer header. ** ** Copyright (c) 2014 Freescale Semiconductor, Inc. ** All rights reserved. ** ** Redistribution and use in source and binary forms, with or without modification, ** are permitted provided that the following conditions are met: ** ** o Redistributions of source code must retain the above copyright notice, this list ** of conditions and the following disclaimer. ** ** o Redistributions in binary form must reproduce the above copyright notice, this ** list of conditions and the following disclaimer in the documentation and/or ** other materials provided with the distribution. ** ** o Neither the name of Freescale Semiconductor, Inc. nor the names of its ** contributors may be used to endorse or promote products derived from this ** software without specific prior written permission. ** ** THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ** ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED ** WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE ** DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT 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. ** ** http: www.freescale.com ** mail: support@freescale.com ** ** Revisions: ** - rev. 1.0 (2013-08-12) ** Initial version. ** - rev. 2.0 (2013-10-29) ** Register accessor macros added to the memory map. ** Symbols for Processor Expert memory map compatibility added to the memory map. ** Startup file for gcc has been updated according to CMSIS 3.2. ** System initialization updated. ** MCG - registers updated. ** PORTA, PORTB, PORTC, PORTE - registers for digital filter removed. ** - rev. 2.1 (2013-10-30) ** Definition of BITBAND macros updated to support peripherals with 32-bit acces disabled. ** - rev. 2.2 (2013-12-09) ** DMA - EARS register removed. ** AIPS0, AIPS1 - MPRA register updated. ** - rev. 2.3 (2014-01-24) ** Update according to reference manual rev. 2 ** ENET, MCG, MCM, SIM, USB - registers updated ** - rev. 2.4 (2014-02-10) ** The declaration of clock configurations has been moved to separate header file system_MK64F12.h ** Update of SystemInit() and SystemCoreClockUpdate() functions. ** - rev. 2.5 (2014-02-10) ** The declaration of clock configurations has been moved to separate header file system_MK64F12.h ** Update of SystemInit() and SystemCoreClockUpdate() functions. ** Module access macro module_BASES replaced by module_BASE_PTRS. ** ** ################################################################### */ /* * WARNING! DO NOT EDIT THIS FILE DIRECTLY! * * This file was generated automatically and any changes may be lost. */ #ifndef __HW_DMAMUX_REGISTERS_H__ #define __HW_DMAMUX_REGISTERS_H__ #include "MK64F12.h" #include "fsl_bitaccess.h" /* * MK64F12 DMAMUX * * DMA channel multiplexor * * Registers defined in this header file: * - HW_DMAMUX_CHCFGn - Channel Configuration register * * - hw_dmamux_t - Struct containing all module registers. */ #define HW_DMAMUX_INSTANCE_COUNT (1U) /*!< Number of instances of the DMAMUX module. */ /******************************************************************************* * HW_DMAMUX_CHCFGn - Channel Configuration register ******************************************************************************/ /*! * @brief HW_DMAMUX_CHCFGn - Channel Configuration register (RW) * * Reset value: 0x00U * * Each of the DMA channels can be independently enabled/disabled and associated * with one of the DMA slots (peripheral slots or always-on slots) in the * system. Setting multiple CHCFG registers with the same source value will result in * unpredictable behavior. This is true, even if a channel is disabled (ENBL==0). * Before changing the trigger or source settings, a DMA channel must be disabled * via CHCFGn[ENBL]. */ typedef union _hw_dmamux_chcfgn { uint8_t U; struct _hw_dmamux_chcfgn_bitfields { uint8_t SOURCE : 6; /*!< [5:0] DMA Channel Source (Slot) */ uint8_t TRIG : 1; /*!< [6] DMA Channel Trigger Enable */ uint8_t ENBL : 1; /*!< [7] DMA Channel Enable */ } B; } hw_dmamux_chcfgn_t; /*! * @name Constants and macros for entire DMAMUX_CHCFGn register */ /*@{*/ #define HW_DMAMUX_CHCFGn_COUNT (16U) #define HW_DMAMUX_CHCFGn_ADDR(x, n) ((x) + 0x0U + (0x1U * (n))) #define HW_DMAMUX_CHCFGn(x, n) (*(__IO hw_dmamux_chcfgn_t *) HW_DMAMUX_CHCFGn_ADDR(x, n)) #define HW_DMAMUX_CHCFGn_RD(x, n) (HW_DMAMUX_CHCFGn(x, n).U) #define HW_DMAMUX_CHCFGn_WR(x, n, v) (HW_DMAMUX_CHCFGn(x, n).U = (v)) #define HW_DMAMUX_CHCFGn_SET(x, n, v) (HW_DMAMUX_CHCFGn_WR(x, n, HW_DMAMUX_CHCFGn_RD(x, n) | (v))) #define HW_DMAMUX_CHCFGn_CLR(x, n, v) (HW_DMAMUX_CHCFGn_WR(x, n, HW_DMAMUX_CHCFGn_RD(x, n) & ~(v))) #define HW_DMAMUX_CHCFGn_TOG(x, n, v) (HW_DMAMUX_CHCFGn_WR(x, n, HW_DMAMUX_CHCFGn_RD(x, n) ^ (v))) /*@}*/ /* * Constants & macros for individual DMAMUX_CHCFGn bitfields */ /*! * @name Register DMAMUX_CHCFGn, field SOURCE[5:0] (RW) * * Specifies which DMA source, if any, is routed to a particular DMA channel. * See your device's chip configuration details for information about the * peripherals and their slot numbers. */ /*@{*/ #define BP_DMAMUX_CHCFGn_SOURCE (0U) /*!< Bit position for DMAMUX_CHCFGn_SOURCE. */ #define BM_DMAMUX_CHCFGn_SOURCE (0x3FU) /*!< Bit mask for DMAMUX_CHCFGn_SOURCE. */ #define BS_DMAMUX_CHCFGn_SOURCE (6U) /*!< Bit field size in bits for DMAMUX_CHCFGn_SOURCE. */ /*! @brief Read current value of the DMAMUX_CHCFGn_SOURCE field. */ #define BR_DMAMUX_CHCFGn_SOURCE(x, n) (HW_DMAMUX_CHCFGn(x, n).B.SOURCE) /*! @brief Format value for bitfield DMAMUX_CHCFGn_SOURCE. */ #define BF_DMAMUX_CHCFGn_SOURCE(v) ((uint8_t)((uint8_t)(v) << BP_DMAMUX_CHCFGn_SOURCE) & BM_DMAMUX_CHCFGn_SOURCE) /*! @brief Set the SOURCE field to a new value. */ #define BW_DMAMUX_CHCFGn_SOURCE(x, n, v) (HW_DMAMUX_CHCFGn_WR(x, n, (HW_DMAMUX_CHCFGn_RD(x, n) & ~BM_DMAMUX_CHCFGn_SOURCE) | BF_DMAMUX_CHCFGn_SOURCE(v))) /*@}*/ /*! * @name Register DMAMUX_CHCFGn, field TRIG[6] (RW) * * Enables the periodic trigger capability for the triggered DMA channel. * * Values: * - 0 - Triggering is disabled. If triggering is disabled and ENBL is set, the * DMA Channel will simply route the specified source to the DMA channel. * (Normal mode) * - 1 - Triggering is enabled. If triggering is enabled and ENBL is set, the * DMAMUX is in Periodic Trigger mode. */ /*@{*/ #define BP_DMAMUX_CHCFGn_TRIG (6U) /*!< Bit position for DMAMUX_CHCFGn_TRIG. */ #define BM_DMAMUX_CHCFGn_TRIG (0x40U) /*!< Bit mask for DMAMUX_CHCFGn_TRIG. */ #define BS_DMAMUX_CHCFGn_TRIG (1U) /*!< Bit field size in bits for DMAMUX_CHCFGn_TRIG. */ /*! @brief Read current value of the DMAMUX_CHCFGn_TRIG field. */ #define BR_DMAMUX_CHCFGn_TRIG(x, n) (BITBAND_ACCESS8(HW_DMAMUX_CHCFGn_ADDR(x, n), BP_DMAMUX_CHCFGn_TRIG)) /*! @brief Format value for bitfield DMAMUX_CHCFGn_TRIG. */ #define BF_DMAMUX_CHCFGn_TRIG(v) ((uint8_t)((uint8_t)(v) << BP_DMAMUX_CHCFGn_TRIG) & BM_DMAMUX_CHCFGn_TRIG) /*! @brief Set the TRIG field to a new value. */ #define BW_DMAMUX_CHCFGn_TRIG(x, n, v) (BITBAND_ACCESS8(HW_DMAMUX_CHCFGn_ADDR(x, n), BP_DMAMUX_CHCFGn_TRIG) = (v)) /*@}*/ /*! * @name Register DMAMUX_CHCFGn, field ENBL[7] (RW) * * Enables the DMA channel. * * Values: * - 0 - DMA channel is disabled. This mode is primarily used during * configuration of the DMAMux. The DMA has separate channel enables/disables, which * should be used to disable or reconfigure a DMA channel. * - 1 - DMA channel is enabled */ /*@{*/ #define BP_DMAMUX_CHCFGn_ENBL (7U) /*!< Bit position for DMAMUX_CHCFGn_ENBL. */ #define BM_DMAMUX_CHCFGn_ENBL (0x80U) /*!< Bit mask for DMAMUX_CHCFGn_ENBL. */ #define BS_DMAMUX_CHCFGn_ENBL (1U) /*!< Bit field size in bits for DMAMUX_CHCFGn_ENBL. */ /*! @brief Read current value of the DMAMUX_CHCFGn_ENBL field. */ #define BR_DMAMUX_CHCFGn_ENBL(x, n) (BITBAND_ACCESS8(HW_DMAMUX_CHCFGn_ADDR(x, n), BP_DMAMUX_CHCFGn_ENBL)) /*! @brief Format value for bitfield DMAMUX_CHCFGn_ENBL. */ #define BF_DMAMUX_CHCFGn_ENBL(v) ((uint8_t)((uint8_t)(v) << BP_DMAMUX_CHCFGn_ENBL) & BM_DMAMUX_CHCFGn_ENBL) /*! @brief Set the ENBL field to a new value. */ #define BW_DMAMUX_CHCFGn_ENBL(x, n, v) (BITBAND_ACCESS8(HW_DMAMUX_CHCFGn_ADDR(x, n), BP_DMAMUX_CHCFGn_ENBL) = (v)) /*@}*/ /******************************************************************************* * hw_dmamux_t - module struct ******************************************************************************/ /*! * @brief All DMAMUX module registers. */ #pragma pack(1) typedef struct _hw_dmamux { __IO hw_dmamux_chcfgn_t CHCFGn[16]; /*!< [0x0] Channel Configuration register */ } hw_dmamux_t; #pragma pack() /*! @brief Macro to access all DMAMUX registers. */ /*! @param x DMAMUX module instance base address. */ /*! @return Reference (not a pointer) to the registers struct. To get a pointer to the struct, * use the '&' operator, like &HW_DMAMUX(DMAMUX_BASE). */ #define HW_DMAMUX(x) (*(hw_dmamux_t *)(x)) #endif /* __HW_DMAMUX_REGISTERS_H__ */ /* EOF */ ================================================ FILE: Zelig/mbed/TARGET_K64F/TARGET_Freescale/TARGET_KPSDK_MCUS/TARGET_MCU_K64F/device/device/MK64F12/MK64F12_enet.h ================================================ /* ** ################################################################### ** Compilers: Keil ARM C/C++ Compiler ** Freescale C/C++ for Embedded ARM ** GNU C Compiler ** IAR ANSI C/C++ Compiler for ARM ** ** Reference manual: K64P144M120SF5RM, Rev.2, January 2014 ** Version: rev. 2.5, 2014-02-10 ** Build: b140604 ** ** Abstract: ** Extension to the CMSIS register access layer header. ** ** Copyright (c) 2014 Freescale Semiconductor, Inc. ** All rights reserved. ** ** Redistribution and use in source and binary forms, with or without modification, ** are permitted provided that the following conditions are met: ** ** o Redistributions of source code must retain the above copyright notice, this list ** of conditions and the following disclaimer. ** ** o Redistributions in binary form must reproduce the above copyright notice, this ** list of conditions and the following disclaimer in the documentation and/or ** other materials provided with the distribution. ** ** o Neither the name of Freescale Semiconductor, Inc. nor the names of its ** contributors may be used to endorse or promote products derived from this ** software without specific prior written permission. ** ** THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ** ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED ** WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE ** DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT 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. ** ** http: www.freescale.com ** mail: support@freescale.com ** ** Revisions: ** - rev. 1.0 (2013-08-12) ** Initial version. ** - rev. 2.0 (2013-10-29) ** Register accessor macros added to the memory map. ** Symbols for Processor Expert memory map compatibility added to the memory map. ** Startup file for gcc has been updated according to CMSIS 3.2. ** System initialization updated. ** MCG - registers updated. ** PORTA, PORTB, PORTC, PORTE - registers for digital filter removed. ** - rev. 2.1 (2013-10-30) ** Definition of BITBAND macros updated to support peripherals with 32-bit acces disabled. ** - rev. 2.2 (2013-12-09) ** DMA - EARS register removed. ** AIPS0, AIPS1 - MPRA register updated. ** - rev. 2.3 (2014-01-24) ** Update according to reference manual rev. 2 ** ENET, MCG, MCM, SIM, USB - registers updated ** - rev. 2.4 (2014-02-10) ** The declaration of clock configurations has been moved to separate header file system_MK64F12.h ** Update of SystemInit() and SystemCoreClockUpdate() functions. ** - rev. 2.5 (2014-02-10) ** The declaration of clock configurations has been moved to separate header file system_MK64F12.h ** Update of SystemInit() and SystemCoreClockUpdate() functions. ** Module access macro module_BASES replaced by module_BASE_PTRS. ** ** ################################################################### */ /* * WARNING! DO NOT EDIT THIS FILE DIRECTLY! * * This file was generated automatically and any changes may be lost. */ #ifndef __HW_ENET_REGISTERS_H__ #define __HW_ENET_REGISTERS_H__ #include "MK64F12.h" #include "fsl_bitaccess.h" /* * MK64F12 ENET * * Ethernet MAC-NET Core * * Registers defined in this header file: * - HW_ENET_EIR - Interrupt Event Register * - HW_ENET_EIMR - Interrupt Mask Register * - HW_ENET_RDAR - Receive Descriptor Active Register * - HW_ENET_TDAR - Transmit Descriptor Active Register * - HW_ENET_ECR - Ethernet Control Register * - HW_ENET_MMFR - MII Management Frame Register * - HW_ENET_MSCR - MII Speed Control Register * - HW_ENET_MIBC - MIB Control Register * - HW_ENET_RCR - Receive Control Register * - HW_ENET_TCR - Transmit Control Register * - HW_ENET_PALR - Physical Address Lower Register * - HW_ENET_PAUR - Physical Address Upper Register * - HW_ENET_OPD - Opcode/Pause Duration Register * - HW_ENET_IAUR - Descriptor Individual Upper Address Register * - HW_ENET_IALR - Descriptor Individual Lower Address Register * - HW_ENET_GAUR - Descriptor Group Upper Address Register * - HW_ENET_GALR - Descriptor Group Lower Address Register * - HW_ENET_TFWR - Transmit FIFO Watermark Register * - HW_ENET_RDSR - Receive Descriptor Ring Start Register * - HW_ENET_TDSR - Transmit Buffer Descriptor Ring Start Register * - HW_ENET_MRBR - Maximum Receive Buffer Size Register * - HW_ENET_RSFL - Receive FIFO Section Full Threshold * - HW_ENET_RSEM - Receive FIFO Section Empty Threshold * - HW_ENET_RAEM - Receive FIFO Almost Empty Threshold * - HW_ENET_RAFL - Receive FIFO Almost Full Threshold * - HW_ENET_TSEM - Transmit FIFO Section Empty Threshold * - HW_ENET_TAEM - Transmit FIFO Almost Empty Threshold * - HW_ENET_TAFL - Transmit FIFO Almost Full Threshold * - HW_ENET_TIPG - Transmit Inter-Packet Gap * - HW_ENET_FTRL - Frame Truncation Length * - HW_ENET_TACC - Transmit Accelerator Function Configuration * - HW_ENET_RACC - Receive Accelerator Function Configuration * - HW_ENET_RMON_T_PACKETS - Tx Packet Count Statistic Register * - HW_ENET_RMON_T_BC_PKT - Tx Broadcast Packets Statistic Register * - HW_ENET_RMON_T_MC_PKT - Tx Multicast Packets Statistic Register * - HW_ENET_RMON_T_CRC_ALIGN - Tx Packets with CRC/Align Error Statistic Register * - HW_ENET_RMON_T_UNDERSIZE - Tx Packets Less Than Bytes and Good CRC Statistic Register * - HW_ENET_RMON_T_OVERSIZE - Tx Packets GT MAX_FL bytes and Good CRC Statistic Register * - HW_ENET_RMON_T_FRAG - Tx Packets Less Than 64 Bytes and Bad CRC Statistic Register * - HW_ENET_RMON_T_JAB - Tx Packets Greater Than MAX_FL bytes and Bad CRC Statistic Register * - HW_ENET_RMON_T_COL - Tx Collision Count Statistic Register * - HW_ENET_RMON_T_P64 - Tx 64-Byte Packets Statistic Register * - HW_ENET_RMON_T_P65TO127 - Tx 65- to 127-byte Packets Statistic Register * - HW_ENET_RMON_T_P128TO255 - Tx 128- to 255-byte Packets Statistic Register * - HW_ENET_RMON_T_P256TO511 - Tx 256- to 511-byte Packets Statistic Register * - HW_ENET_RMON_T_P512TO1023 - Tx 512- to 1023-byte Packets Statistic Register * - HW_ENET_RMON_T_P1024TO2047 - Tx 1024- to 2047-byte Packets Statistic Register * - HW_ENET_RMON_T_P_GTE2048 - Tx Packets Greater Than 2048 Bytes Statistic Register * - HW_ENET_RMON_T_OCTETS - Tx Octets Statistic Register * - HW_ENET_IEEE_T_FRAME_OK - Frames Transmitted OK Statistic Register * - HW_ENET_IEEE_T_1COL - Frames Transmitted with Single Collision Statistic Register * - HW_ENET_IEEE_T_MCOL - Frames Transmitted with Multiple Collisions Statistic Register * - HW_ENET_IEEE_T_DEF - Frames Transmitted after Deferral Delay Statistic Register * - HW_ENET_IEEE_T_LCOL - Frames Transmitted with Late Collision Statistic Register * - HW_ENET_IEEE_T_EXCOL - Frames Transmitted with Excessive Collisions Statistic Register * - HW_ENET_IEEE_T_MACERR - Frames Transmitted with Tx FIFO Underrun Statistic Register * - HW_ENET_IEEE_T_CSERR - Frames Transmitted with Carrier Sense Error Statistic Register * - HW_ENET_IEEE_T_FDXFC - Flow Control Pause Frames Transmitted Statistic Register * - HW_ENET_IEEE_T_OCTETS_OK - Octet Count for Frames Transmitted w/o Error Statistic Register * - HW_ENET_RMON_R_PACKETS - Rx Packet Count Statistic Register * - HW_ENET_RMON_R_BC_PKT - Rx Broadcast Packets Statistic Register * - HW_ENET_RMON_R_MC_PKT - Rx Multicast Packets Statistic Register * - HW_ENET_RMON_R_CRC_ALIGN - Rx Packets with CRC/Align Error Statistic Register * - HW_ENET_RMON_R_UNDERSIZE - Rx Packets with Less Than 64 Bytes and Good CRC Statistic Register * - HW_ENET_RMON_R_OVERSIZE - Rx Packets Greater Than MAX_FL and Good CRC Statistic Register * - HW_ENET_RMON_R_FRAG - Rx Packets Less Than 64 Bytes and Bad CRC Statistic Register * - HW_ENET_RMON_R_JAB - Rx Packets Greater Than MAX_FL Bytes and Bad CRC Statistic Register * - HW_ENET_RMON_R_P64 - Rx 64-Byte Packets Statistic Register * - HW_ENET_RMON_R_P65TO127 - Rx 65- to 127-Byte Packets Statistic Register * - HW_ENET_RMON_R_P128TO255 - Rx 128- to 255-Byte Packets Statistic Register * - HW_ENET_RMON_R_P256TO511 - Rx 256- to 511-Byte Packets Statistic Register * - HW_ENET_RMON_R_P512TO1023 - Rx 512- to 1023-Byte Packets Statistic Register * - HW_ENET_RMON_R_P1024TO2047 - Rx 1024- to 2047-Byte Packets Statistic Register * - HW_ENET_RMON_R_P_GTE2048 - Rx Packets Greater than 2048 Bytes Statistic Register * - HW_ENET_RMON_R_OCTETS - Rx Octets Statistic Register * - HW_ENET_IEEE_R_DROP - Frames not Counted Correctly Statistic Register * - HW_ENET_IEEE_R_FRAME_OK - Frames Received OK Statistic Register * - HW_ENET_IEEE_R_CRC - Frames Received with CRC Error Statistic Register * - HW_ENET_IEEE_R_ALIGN - Frames Received with Alignment Error Statistic Register * - HW_ENET_IEEE_R_MACERR - Receive FIFO Overflow Count Statistic Register * - HW_ENET_IEEE_R_FDXFC - Flow Control Pause Frames Received Statistic Register * - HW_ENET_IEEE_R_OCTETS_OK - Octet Count for Frames Received without Error Statistic Register * - HW_ENET_ATCR - Adjustable Timer Control Register * - HW_ENET_ATVR - Timer Value Register * - HW_ENET_ATOFF - Timer Offset Register * - HW_ENET_ATPER - Timer Period Register * - HW_ENET_ATCOR - Timer Correction Register * - HW_ENET_ATINC - Time-Stamping Clock Period Register * - HW_ENET_ATSTMP - Timestamp of Last Transmitted Frame * - HW_ENET_TGSR - Timer Global Status Register * - HW_ENET_TCSRn - Timer Control Status Register * - HW_ENET_TCCRn - Timer Compare Capture Register * * - hw_enet_t - Struct containing all module registers. */ #define HW_ENET_INSTANCE_COUNT (1U) /*!< Number of instances of the ENET module. */ /******************************************************************************* * HW_ENET_EIR - Interrupt Event Register ******************************************************************************/ /*! * @brief HW_ENET_EIR - Interrupt Event Register (RW) * * Reset value: 0x00000000U * * When an event occurs that sets a bit in EIR, an interrupt occurs if the * corresponding bit in the interrupt mask register (EIMR) is also set. Writing a 1 to * an EIR bit clears it; writing 0 has no effect. This register is cleared upon * hardware reset. TxBD[INT] and RxBD[INT] must be set to 1 to allow setting the * corresponding EIR register flags in enhanced mode, ENET_ECR[EN1588] = 1. * Legacy mode does not require these flags to be enabled. */ typedef union _hw_enet_eir { uint32_t U; struct _hw_enet_eir_bitfields { uint32_t RESERVED0 : 15; /*!< [14:0] */ uint32_t TS_TIMER : 1; /*!< [15] Timestamp Timer */ uint32_t TS_AVAIL : 1; /*!< [16] Transmit Timestamp Available */ uint32_t WAKEUP : 1; /*!< [17] Node Wakeup Request Indication */ uint32_t PLR : 1; /*!< [18] Payload Receive Error */ uint32_t UN : 1; /*!< [19] Transmit FIFO Underrun */ uint32_t RL : 1; /*!< [20] Collision Retry Limit */ uint32_t LC : 1; /*!< [21] Late Collision */ uint32_t EBERR : 1; /*!< [22] Ethernet Bus Error */ uint32_t MII : 1; /*!< [23] MII Interrupt. */ uint32_t RXB : 1; /*!< [24] Receive Buffer Interrupt */ uint32_t RXF : 1; /*!< [25] Receive Frame Interrupt */ uint32_t TXB : 1; /*!< [26] Transmit Buffer Interrupt */ uint32_t TXF : 1; /*!< [27] Transmit Frame Interrupt */ uint32_t GRA : 1; /*!< [28] Graceful Stop Complete */ uint32_t BABT : 1; /*!< [29] Babbling Transmit Error */ uint32_t BABR : 1; /*!< [30] Babbling Receive Error */ uint32_t RESERVED1 : 1; /*!< [31] */ } B; } hw_enet_eir_t; /*! * @name Constants and macros for entire ENET_EIR register */ /*@{*/ #define HW_ENET_EIR_ADDR(x) ((x) + 0x4U) #define HW_ENET_EIR(x) (*(__IO hw_enet_eir_t *) HW_ENET_EIR_ADDR(x)) #define HW_ENET_EIR_RD(x) (HW_ENET_EIR(x).U) #define HW_ENET_EIR_WR(x, v) (HW_ENET_EIR(x).U = (v)) #define HW_ENET_EIR_SET(x, v) (HW_ENET_EIR_WR(x, HW_ENET_EIR_RD(x) | (v))) #define HW_ENET_EIR_CLR(x, v) (HW_ENET_EIR_WR(x, HW_ENET_EIR_RD(x) & ~(v))) #define HW_ENET_EIR_TOG(x, v) (HW_ENET_EIR_WR(x, HW_ENET_EIR_RD(x) ^ (v))) /*@}*/ /* * Constants & macros for individual ENET_EIR bitfields */ /*! * @name Register ENET_EIR, field TS_TIMER[15] (W1C) * * The adjustable timer reached the period event. A period event interrupt can * be generated if ATCR[PEREN] is set and the timer wraps according to the * periodic setting in the ATPER register. Set the timer period value before setting * ATCR[PEREN]. */ /*@{*/ #define BP_ENET_EIR_TS_TIMER (15U) /*!< Bit position for ENET_EIR_TS_TIMER. */ #define BM_ENET_EIR_TS_TIMER (0x00008000U) /*!< Bit mask for ENET_EIR_TS_TIMER. */ #define BS_ENET_EIR_TS_TIMER (1U) /*!< Bit field size in bits for ENET_EIR_TS_TIMER. */ /*! @brief Read current value of the ENET_EIR_TS_TIMER field. */ #define BR_ENET_EIR_TS_TIMER(x) (BITBAND_ACCESS32(HW_ENET_EIR_ADDR(x), BP_ENET_EIR_TS_TIMER)) /*! @brief Format value for bitfield ENET_EIR_TS_TIMER. */ #define BF_ENET_EIR_TS_TIMER(v) ((uint32_t)((uint32_t)(v) << BP_ENET_EIR_TS_TIMER) & BM_ENET_EIR_TS_TIMER) /*! @brief Set the TS_TIMER field to a new value. */ #define BW_ENET_EIR_TS_TIMER(x, v) (BITBAND_ACCESS32(HW_ENET_EIR_ADDR(x), BP_ENET_EIR_TS_TIMER) = (v)) /*@}*/ /*! * @name Register ENET_EIR, field TS_AVAIL[16] (W1C) * * Indicates that the timestamp of the last transmitted timing frame is * available in the ATSTMP register. */ /*@{*/ #define BP_ENET_EIR_TS_AVAIL (16U) /*!< Bit position for ENET_EIR_TS_AVAIL. */ #define BM_ENET_EIR_TS_AVAIL (0x00010000U) /*!< Bit mask for ENET_EIR_TS_AVAIL. */ #define BS_ENET_EIR_TS_AVAIL (1U) /*!< Bit field size in bits for ENET_EIR_TS_AVAIL. */ /*! @brief Read current value of the ENET_EIR_TS_AVAIL field. */ #define BR_ENET_EIR_TS_AVAIL(x) (BITBAND_ACCESS32(HW_ENET_EIR_ADDR(x), BP_ENET_EIR_TS_AVAIL)) /*! @brief Format value for bitfield ENET_EIR_TS_AVAIL. */ #define BF_ENET_EIR_TS_AVAIL(v) ((uint32_t)((uint32_t)(v) << BP_ENET_EIR_TS_AVAIL) & BM_ENET_EIR_TS_AVAIL) /*! @brief Set the TS_AVAIL field to a new value. */ #define BW_ENET_EIR_TS_AVAIL(x, v) (BITBAND_ACCESS32(HW_ENET_EIR_ADDR(x), BP_ENET_EIR_TS_AVAIL) = (v)) /*@}*/ /*! * @name Register ENET_EIR, field WAKEUP[17] (W1C) * * Read-only status bit to indicate that a magic packet has been detected. Will * act only if ECR[MAGICEN] is set. */ /*@{*/ #define BP_ENET_EIR_WAKEUP (17U) /*!< Bit position for ENET_EIR_WAKEUP. */ #define BM_ENET_EIR_WAKEUP (0x00020000U) /*!< Bit mask for ENET_EIR_WAKEUP. */ #define BS_ENET_EIR_WAKEUP (1U) /*!< Bit field size in bits for ENET_EIR_WAKEUP. */ /*! @brief Read current value of the ENET_EIR_WAKEUP field. */ #define BR_ENET_EIR_WAKEUP(x) (BITBAND_ACCESS32(HW_ENET_EIR_ADDR(x), BP_ENET_EIR_WAKEUP)) /*! @brief Format value for bitfield ENET_EIR_WAKEUP. */ #define BF_ENET_EIR_WAKEUP(v) ((uint32_t)((uint32_t)(v) << BP_ENET_EIR_WAKEUP) & BM_ENET_EIR_WAKEUP) /*! @brief Set the WAKEUP field to a new value. */ #define BW_ENET_EIR_WAKEUP(x, v) (BITBAND_ACCESS32(HW_ENET_EIR_ADDR(x), BP_ENET_EIR_WAKEUP) = (v)) /*@}*/ /*! * @name Register ENET_EIR, field PLR[18] (W1C) * * Indicates a frame was received with a payload length error. See Frame * Length/Type Verification: Payload Length Check for more information. */ /*@{*/ #define BP_ENET_EIR_PLR (18U) /*!< Bit position for ENET_EIR_PLR. */ #define BM_ENET_EIR_PLR (0x00040000U) /*!< Bit mask for ENET_EIR_PLR. */ #define BS_ENET_EIR_PLR (1U) /*!< Bit field size in bits for ENET_EIR_PLR. */ /*! @brief Read current value of the ENET_EIR_PLR field. */ #define BR_ENET_EIR_PLR(x) (BITBAND_ACCESS32(HW_ENET_EIR_ADDR(x), BP_ENET_EIR_PLR)) /*! @brief Format value for bitfield ENET_EIR_PLR. */ #define BF_ENET_EIR_PLR(v) ((uint32_t)((uint32_t)(v) << BP_ENET_EIR_PLR) & BM_ENET_EIR_PLR) /*! @brief Set the PLR field to a new value. */ #define BW_ENET_EIR_PLR(x, v) (BITBAND_ACCESS32(HW_ENET_EIR_ADDR(x), BP_ENET_EIR_PLR) = (v)) /*@}*/ /*! * @name Register ENET_EIR, field UN[19] (W1C) * * Indicates the transmit FIFO became empty before the complete frame was * transmitted. A bad CRC is appended to the frame fragment and the remainder of the * frame is discarded. */ /*@{*/ #define BP_ENET_EIR_UN (19U) /*!< Bit position for ENET_EIR_UN. */ #define BM_ENET_EIR_UN (0x00080000U) /*!< Bit mask for ENET_EIR_UN. */ #define BS_ENET_EIR_UN (1U) /*!< Bit field size in bits for ENET_EIR_UN. */ /*! @brief Read current value of the ENET_EIR_UN field. */ #define BR_ENET_EIR_UN(x) (BITBAND_ACCESS32(HW_ENET_EIR_ADDR(x), BP_ENET_EIR_UN)) /*! @brief Format value for bitfield ENET_EIR_UN. */ #define BF_ENET_EIR_UN(v) ((uint32_t)((uint32_t)(v) << BP_ENET_EIR_UN) & BM_ENET_EIR_UN) /*! @brief Set the UN field to a new value. */ #define BW_ENET_EIR_UN(x, v) (BITBAND_ACCESS32(HW_ENET_EIR_ADDR(x), BP_ENET_EIR_UN) = (v)) /*@}*/ /*! * @name Register ENET_EIR, field RL[20] (W1C) * * Indicates a collision occurred on each of 16 successive attempts to transmit * the frame. The frame is discarded without being transmitted and transmission * of the next frame commences. This error can only occur in half-duplex mode. */ /*@{*/ #define BP_ENET_EIR_RL (20U) /*!< Bit position for ENET_EIR_RL. */ #define BM_ENET_EIR_RL (0x00100000U) /*!< Bit mask for ENET_EIR_RL. */ #define BS_ENET_EIR_RL (1U) /*!< Bit field size in bits for ENET_EIR_RL. */ /*! @brief Read current value of the ENET_EIR_RL field. */ #define BR_ENET_EIR_RL(x) (BITBAND_ACCESS32(HW_ENET_EIR_ADDR(x), BP_ENET_EIR_RL)) /*! @brief Format value for bitfield ENET_EIR_RL. */ #define BF_ENET_EIR_RL(v) ((uint32_t)((uint32_t)(v) << BP_ENET_EIR_RL) & BM_ENET_EIR_RL) /*! @brief Set the RL field to a new value. */ #define BW_ENET_EIR_RL(x, v) (BITBAND_ACCESS32(HW_ENET_EIR_ADDR(x), BP_ENET_EIR_RL) = (v)) /*@}*/ /*! * @name Register ENET_EIR, field LC[21] (W1C) * * Indicates a collision occurred beyond the collision window (slot time) in * half-duplex mode. The frame truncates with a bad CRC and the remainder of the * frame is discarded. */ /*@{*/ #define BP_ENET_EIR_LC (21U) /*!< Bit position for ENET_EIR_LC. */ #define BM_ENET_EIR_LC (0x00200000U) /*!< Bit mask for ENET_EIR_LC. */ #define BS_ENET_EIR_LC (1U) /*!< Bit field size in bits for ENET_EIR_LC. */ /*! @brief Read current value of the ENET_EIR_LC field. */ #define BR_ENET_EIR_LC(x) (BITBAND_ACCESS32(HW_ENET_EIR_ADDR(x), BP_ENET_EIR_LC)) /*! @brief Format value for bitfield ENET_EIR_LC. */ #define BF_ENET_EIR_LC(v) ((uint32_t)((uint32_t)(v) << BP_ENET_EIR_LC) & BM_ENET_EIR_LC) /*! @brief Set the LC field to a new value. */ #define BW_ENET_EIR_LC(x, v) (BITBAND_ACCESS32(HW_ENET_EIR_ADDR(x), BP_ENET_EIR_LC) = (v)) /*@}*/ /*! * @name Register ENET_EIR, field EBERR[22] (W1C) * * Indicates a system bus error occurred when a uDMA transaction is underway. * When this bit is set, ECR[ETHEREN] is cleared, halting frame processing by the * MAC. When this occurs, software must ensure proper actions, possibly resetting * the system, to resume normal operation. */ /*@{*/ #define BP_ENET_EIR_EBERR (22U) /*!< Bit position for ENET_EIR_EBERR. */ #define BM_ENET_EIR_EBERR (0x00400000U) /*!< Bit mask for ENET_EIR_EBERR. */ #define BS_ENET_EIR_EBERR (1U) /*!< Bit field size in bits for ENET_EIR_EBERR. */ /*! @brief Read current value of the ENET_EIR_EBERR field. */ #define BR_ENET_EIR_EBERR(x) (BITBAND_ACCESS32(HW_ENET_EIR_ADDR(x), BP_ENET_EIR_EBERR)) /*! @brief Format value for bitfield ENET_EIR_EBERR. */ #define BF_ENET_EIR_EBERR(v) ((uint32_t)((uint32_t)(v) << BP_ENET_EIR_EBERR) & BM_ENET_EIR_EBERR) /*! @brief Set the EBERR field to a new value. */ #define BW_ENET_EIR_EBERR(x, v) (BITBAND_ACCESS32(HW_ENET_EIR_ADDR(x), BP_ENET_EIR_EBERR) = (v)) /*@}*/ /*! * @name Register ENET_EIR, field MII[23] (W1C) * * Indicates that the MII has completed the data transfer requested. */ /*@{*/ #define BP_ENET_EIR_MII (23U) /*!< Bit position for ENET_EIR_MII. */ #define BM_ENET_EIR_MII (0x00800000U) /*!< Bit mask for ENET_EIR_MII. */ #define BS_ENET_EIR_MII (1U) /*!< Bit field size in bits for ENET_EIR_MII. */ /*! @brief Read current value of the ENET_EIR_MII field. */ #define BR_ENET_EIR_MII(x) (BITBAND_ACCESS32(HW_ENET_EIR_ADDR(x), BP_ENET_EIR_MII)) /*! @brief Format value for bitfield ENET_EIR_MII. */ #define BF_ENET_EIR_MII(v) ((uint32_t)((uint32_t)(v) << BP_ENET_EIR_MII) & BM_ENET_EIR_MII) /*! @brief Set the MII field to a new value. */ #define BW_ENET_EIR_MII(x, v) (BITBAND_ACCESS32(HW_ENET_EIR_ADDR(x), BP_ENET_EIR_MII) = (v)) /*@}*/ /*! * @name Register ENET_EIR, field RXB[24] (W1C) * * Indicates a receive buffer descriptor is not the last in the frame has been * updated. */ /*@{*/ #define BP_ENET_EIR_RXB (24U) /*!< Bit position for ENET_EIR_RXB. */ #define BM_ENET_EIR_RXB (0x01000000U) /*!< Bit mask for ENET_EIR_RXB. */ #define BS_ENET_EIR_RXB (1U) /*!< Bit field size in bits for ENET_EIR_RXB. */ /*! @brief Read current value of the ENET_EIR_RXB field. */ #define BR_ENET_EIR_RXB(x) (BITBAND_ACCESS32(HW_ENET_EIR_ADDR(x), BP_ENET_EIR_RXB)) /*! @brief Format value for bitfield ENET_EIR_RXB. */ #define BF_ENET_EIR_RXB(v) ((uint32_t)((uint32_t)(v) << BP_ENET_EIR_RXB) & BM_ENET_EIR_RXB) /*! @brief Set the RXB field to a new value. */ #define BW_ENET_EIR_RXB(x, v) (BITBAND_ACCESS32(HW_ENET_EIR_ADDR(x), BP_ENET_EIR_RXB) = (v)) /*@}*/ /*! * @name Register ENET_EIR, field RXF[25] (W1C) * * Indicates a frame has been received and the last corresponding buffer * descriptor has been updated. */ /*@{*/ #define BP_ENET_EIR_RXF (25U) /*!< Bit position for ENET_EIR_RXF. */ #define BM_ENET_EIR_RXF (0x02000000U) /*!< Bit mask for ENET_EIR_RXF. */ #define BS_ENET_EIR_RXF (1U) /*!< Bit field size in bits for ENET_EIR_RXF. */ /*! @brief Read current value of the ENET_EIR_RXF field. */ #define BR_ENET_EIR_RXF(x) (BITBAND_ACCESS32(HW_ENET_EIR_ADDR(x), BP_ENET_EIR_RXF)) /*! @brief Format value for bitfield ENET_EIR_RXF. */ #define BF_ENET_EIR_RXF(v) ((uint32_t)((uint32_t)(v) << BP_ENET_EIR_RXF) & BM_ENET_EIR_RXF) /*! @brief Set the RXF field to a new value. */ #define BW_ENET_EIR_RXF(x, v) (BITBAND_ACCESS32(HW_ENET_EIR_ADDR(x), BP_ENET_EIR_RXF) = (v)) /*@}*/ /*! * @name Register ENET_EIR, field TXB[26] (W1C) * * Indicates a transmit buffer descriptor has been updated. */ /*@{*/ #define BP_ENET_EIR_TXB (26U) /*!< Bit position for ENET_EIR_TXB. */ #define BM_ENET_EIR_TXB (0x04000000U) /*!< Bit mask for ENET_EIR_TXB. */ #define BS_ENET_EIR_TXB (1U) /*!< Bit field size in bits for ENET_EIR_TXB. */ /*! @brief Read current value of the ENET_EIR_TXB field. */ #define BR_ENET_EIR_TXB(x) (BITBAND_ACCESS32(HW_ENET_EIR_ADDR(x), BP_ENET_EIR_TXB)) /*! @brief Format value for bitfield ENET_EIR_TXB. */ #define BF_ENET_EIR_TXB(v) ((uint32_t)((uint32_t)(v) << BP_ENET_EIR_TXB) & BM_ENET_EIR_TXB) /*! @brief Set the TXB field to a new value. */ #define BW_ENET_EIR_TXB(x, v) (BITBAND_ACCESS32(HW_ENET_EIR_ADDR(x), BP_ENET_EIR_TXB) = (v)) /*@}*/ /*! * @name Register ENET_EIR, field TXF[27] (W1C) * * Indicates a frame has been transmitted and the last corresponding buffer * descriptor has been updated. */ /*@{*/ #define BP_ENET_EIR_TXF (27U) /*!< Bit position for ENET_EIR_TXF. */ #define BM_ENET_EIR_TXF (0x08000000U) /*!< Bit mask for ENET_EIR_TXF. */ #define BS_ENET_EIR_TXF (1U) /*!< Bit field size in bits for ENET_EIR_TXF. */ /*! @brief Read current value of the ENET_EIR_TXF field. */ #define BR_ENET_EIR_TXF(x) (BITBAND_ACCESS32(HW_ENET_EIR_ADDR(x), BP_ENET_EIR_TXF)) /*! @brief Format value for bitfield ENET_EIR_TXF. */ #define BF_ENET_EIR_TXF(v) ((uint32_t)((uint32_t)(v) << BP_ENET_EIR_TXF) & BM_ENET_EIR_TXF) /*! @brief Set the TXF field to a new value. */ #define BW_ENET_EIR_TXF(x, v) (BITBAND_ACCESS32(HW_ENET_EIR_ADDR(x), BP_ENET_EIR_TXF) = (v)) /*@}*/ /*! * @name Register ENET_EIR, field GRA[28] (W1C) * * This interrupt is asserted after the transmitter is put into a pause state * after completion of the frame currently being transmitted. See Graceful Transmit * Stop (GTS) for conditions that lead to graceful stop. The GRA interrupt is * asserted only when the TX transitions into the stopped state. If this bit is * cleared by writing 1 and the TX is still stopped, the bit is not set again. */ /*@{*/ #define BP_ENET_EIR_GRA (28U) /*!< Bit position for ENET_EIR_GRA. */ #define BM_ENET_EIR_GRA (0x10000000U) /*!< Bit mask for ENET_EIR_GRA. */ #define BS_ENET_EIR_GRA (1U) /*!< Bit field size in bits for ENET_EIR_GRA. */ /*! @brief Read current value of the ENET_EIR_GRA field. */ #define BR_ENET_EIR_GRA(x) (BITBAND_ACCESS32(HW_ENET_EIR_ADDR(x), BP_ENET_EIR_GRA)) /*! @brief Format value for bitfield ENET_EIR_GRA. */ #define BF_ENET_EIR_GRA(v) ((uint32_t)((uint32_t)(v) << BP_ENET_EIR_GRA) & BM_ENET_EIR_GRA) /*! @brief Set the GRA field to a new value. */ #define BW_ENET_EIR_GRA(x, v) (BITBAND_ACCESS32(HW_ENET_EIR_ADDR(x), BP_ENET_EIR_GRA) = (v)) /*@}*/ /*! * @name Register ENET_EIR, field BABT[29] (W1C) * * Indicates the transmitted frame length exceeds RCR[MAX_FL] bytes. Usually * this condition is caused when a frame that is too long is placed into the * transmit data buffer(s). Truncation does not occur. */ /*@{*/ #define BP_ENET_EIR_BABT (29U) /*!< Bit position for ENET_EIR_BABT. */ #define BM_ENET_EIR_BABT (0x20000000U) /*!< Bit mask for ENET_EIR_BABT. */ #define BS_ENET_EIR_BABT (1U) /*!< Bit field size in bits for ENET_EIR_BABT. */ /*! @brief Read current value of the ENET_EIR_BABT field. */ #define BR_ENET_EIR_BABT(x) (BITBAND_ACCESS32(HW_ENET_EIR_ADDR(x), BP_ENET_EIR_BABT)) /*! @brief Format value for bitfield ENET_EIR_BABT. */ #define BF_ENET_EIR_BABT(v) ((uint32_t)((uint32_t)(v) << BP_ENET_EIR_BABT) & BM_ENET_EIR_BABT) /*! @brief Set the BABT field to a new value. */ #define BW_ENET_EIR_BABT(x, v) (BITBAND_ACCESS32(HW_ENET_EIR_ADDR(x), BP_ENET_EIR_BABT) = (v)) /*@}*/ /*! * @name Register ENET_EIR, field BABR[30] (W1C) * * Indicates a frame was received with length in excess of RCR[MAX_FL] bytes. */ /*@{*/ #define BP_ENET_EIR_BABR (30U) /*!< Bit position for ENET_EIR_BABR. */ #define BM_ENET_EIR_BABR (0x40000000U) /*!< Bit mask for ENET_EIR_BABR. */ #define BS_ENET_EIR_BABR (1U) /*!< Bit field size in bits for ENET_EIR_BABR. */ /*! @brief Read current value of the ENET_EIR_BABR field. */ #define BR_ENET_EIR_BABR(x) (BITBAND_ACCESS32(HW_ENET_EIR_ADDR(x), BP_ENET_EIR_BABR)) /*! @brief Format value for bitfield ENET_EIR_BABR. */ #define BF_ENET_EIR_BABR(v) ((uint32_t)((uint32_t)(v) << BP_ENET_EIR_BABR) & BM_ENET_EIR_BABR) /*! @brief Set the BABR field to a new value. */ #define BW_ENET_EIR_BABR(x, v) (BITBAND_ACCESS32(HW_ENET_EIR_ADDR(x), BP_ENET_EIR_BABR) = (v)) /*@}*/ /******************************************************************************* * HW_ENET_EIMR - Interrupt Mask Register ******************************************************************************/ /*! * @brief HW_ENET_EIMR - Interrupt Mask Register (RW) * * Reset value: 0x00000000U * * EIMR controls which interrupt events are allowed to generate actual * interrupts. A hardware reset clears this register. If the corresponding bits in the EIR * and EIMR registers are set, an interrupt is generated. The interrupt signal * remains asserted until a 1 is written to the EIR field (write 1 to clear) or a * 0 is written to the EIMR field. */ typedef union _hw_enet_eimr { uint32_t U; struct _hw_enet_eimr_bitfields { uint32_t RESERVED0 : 15; /*!< [14:0] */ uint32_t TS_TIMER : 1; /*!< [15] TS_TIMER Interrupt Mask */ uint32_t TS_AVAIL : 1; /*!< [16] TS_AVAIL Interrupt Mask */ uint32_t WAKEUP : 1; /*!< [17] WAKEUP Interrupt Mask */ uint32_t PLR : 1; /*!< [18] PLR Interrupt Mask */ uint32_t UN : 1; /*!< [19] UN Interrupt Mask */ uint32_t RL : 1; /*!< [20] RL Interrupt Mask */ uint32_t LC : 1; /*!< [21] LC Interrupt Mask */ uint32_t EBERR : 1; /*!< [22] EBERR Interrupt Mask */ uint32_t MII : 1; /*!< [23] MII Interrupt Mask */ uint32_t RXB : 1; /*!< [24] RXB Interrupt Mask */ uint32_t RXF : 1; /*!< [25] RXF Interrupt Mask */ uint32_t TXB : 1; /*!< [26] TXB Interrupt Mask */ uint32_t TXF : 1; /*!< [27] TXF Interrupt Mask */ uint32_t GRA : 1; /*!< [28] GRA Interrupt Mask */ uint32_t BABT : 1; /*!< [29] BABT Interrupt Mask */ uint32_t BABR : 1; /*!< [30] BABR Interrupt Mask */ uint32_t RESERVED1 : 1; /*!< [31] */ } B; } hw_enet_eimr_t; /*! * @name Constants and macros for entire ENET_EIMR register */ /*@{*/ #define HW_ENET_EIMR_ADDR(x) ((x) + 0x8U) #define HW_ENET_EIMR(x) (*(__IO hw_enet_eimr_t *) HW_ENET_EIMR_ADDR(x)) #define HW_ENET_EIMR_RD(x) (HW_ENET_EIMR(x).U) #define HW_ENET_EIMR_WR(x, v) (HW_ENET_EIMR(x).U = (v)) #define HW_ENET_EIMR_SET(x, v) (HW_ENET_EIMR_WR(x, HW_ENET_EIMR_RD(x) | (v))) #define HW_ENET_EIMR_CLR(x, v) (HW_ENET_EIMR_WR(x, HW_ENET_EIMR_RD(x) & ~(v))) #define HW_ENET_EIMR_TOG(x, v) (HW_ENET_EIMR_WR(x, HW_ENET_EIMR_RD(x) ^ (v))) /*@}*/ /* * Constants & macros for individual ENET_EIMR bitfields */ /*! * @name Register ENET_EIMR, field TS_TIMER[15] (RW) * * Corresponds to interrupt source EIR[TS_TIMER] register and determines whether * an interrupt condition can generate an interrupt. At every module clock, the * EIR samples the signal generated by the interrupting source. The corresponding * EIR TS_TIMER field reflects the state of the interrupt signal even if the * corresponding EIMR field is cleared. */ /*@{*/ #define BP_ENET_EIMR_TS_TIMER (15U) /*!< Bit position for ENET_EIMR_TS_TIMER. */ #define BM_ENET_EIMR_TS_TIMER (0x00008000U) /*!< Bit mask for ENET_EIMR_TS_TIMER. */ #define BS_ENET_EIMR_TS_TIMER (1U) /*!< Bit field size in bits for ENET_EIMR_TS_TIMER. */ /*! @brief Read current value of the ENET_EIMR_TS_TIMER field. */ #define BR_ENET_EIMR_TS_TIMER(x) (BITBAND_ACCESS32(HW_ENET_EIMR_ADDR(x), BP_ENET_EIMR_TS_TIMER)) /*! @brief Format value for bitfield ENET_EIMR_TS_TIMER. */ #define BF_ENET_EIMR_TS_TIMER(v) ((uint32_t)((uint32_t)(v) << BP_ENET_EIMR_TS_TIMER) & BM_ENET_EIMR_TS_TIMER) /*! @brief Set the TS_TIMER field to a new value. */ #define BW_ENET_EIMR_TS_TIMER(x, v) (BITBAND_ACCESS32(HW_ENET_EIMR_ADDR(x), BP_ENET_EIMR_TS_TIMER) = (v)) /*@}*/ /*! * @name Register ENET_EIMR, field TS_AVAIL[16] (RW) * * Corresponds to interrupt source EIR[TS_AVAIL] register and determines whether * an interrupt condition can generate an interrupt. At every module clock, the * EIR samples the signal generated by the interrupting source. The corresponding * EIR TS_AVAIL field reflects the state of the interrupt signal even if the * corresponding EIMR field is cleared. */ /*@{*/ #define BP_ENET_EIMR_TS_AVAIL (16U) /*!< Bit position for ENET_EIMR_TS_AVAIL. */ #define BM_ENET_EIMR_TS_AVAIL (0x00010000U) /*!< Bit mask for ENET_EIMR_TS_AVAIL. */ #define BS_ENET_EIMR_TS_AVAIL (1U) /*!< Bit field size in bits for ENET_EIMR_TS_AVAIL. */ /*! @brief Read current value of the ENET_EIMR_TS_AVAIL field. */ #define BR_ENET_EIMR_TS_AVAIL(x) (BITBAND_ACCESS32(HW_ENET_EIMR_ADDR(x), BP_ENET_EIMR_TS_AVAIL)) /*! @brief Format value for bitfield ENET_EIMR_TS_AVAIL. */ #define BF_ENET_EIMR_TS_AVAIL(v) ((uint32_t)((uint32_t)(v) << BP_ENET_EIMR_TS_AVAIL) & BM_ENET_EIMR_TS_AVAIL) /*! @brief Set the TS_AVAIL field to a new value. */ #define BW_ENET_EIMR_TS_AVAIL(x, v) (BITBAND_ACCESS32(HW_ENET_EIMR_ADDR(x), BP_ENET_EIMR_TS_AVAIL) = (v)) /*@}*/ /*! * @name Register ENET_EIMR, field WAKEUP[17] (RW) * * Corresponds to interrupt source EIR[WAKEUP] register and determines whether * an interrupt condition can generate an interrupt. At every module clock, the * EIR samples the signal generated by the interrupting source. The corresponding * EIR WAKEUP field reflects the state of the interrupt signal even if the * corresponding EIMR field is cleared. */ /*@{*/ #define BP_ENET_EIMR_WAKEUP (17U) /*!< Bit position for ENET_EIMR_WAKEUP. */ #define BM_ENET_EIMR_WAKEUP (0x00020000U) /*!< Bit mask for ENET_EIMR_WAKEUP. */ #define BS_ENET_EIMR_WAKEUP (1U) /*!< Bit field size in bits for ENET_EIMR_WAKEUP. */ /*! @brief Read current value of the ENET_EIMR_WAKEUP field. */ #define BR_ENET_EIMR_WAKEUP(x) (BITBAND_ACCESS32(HW_ENET_EIMR_ADDR(x), BP_ENET_EIMR_WAKEUP)) /*! @brief Format value for bitfield ENET_EIMR_WAKEUP. */ #define BF_ENET_EIMR_WAKEUP(v) ((uint32_t)((uint32_t)(v) << BP_ENET_EIMR_WAKEUP) & BM_ENET_EIMR_WAKEUP) /*! @brief Set the WAKEUP field to a new value. */ #define BW_ENET_EIMR_WAKEUP(x, v) (BITBAND_ACCESS32(HW_ENET_EIMR_ADDR(x), BP_ENET_EIMR_WAKEUP) = (v)) /*@}*/ /*! * @name Register ENET_EIMR, field PLR[18] (RW) * * Corresponds to interrupt source EIR[PLR] and determines whether an interrupt * condition can generate an interrupt. At every module clock, the EIR samples * the signal generated by the interrupting source. The corresponding EIR PLR field * reflects the state of the interrupt signal even if the corresponding EIMR * field is cleared. */ /*@{*/ #define BP_ENET_EIMR_PLR (18U) /*!< Bit position for ENET_EIMR_PLR. */ #define BM_ENET_EIMR_PLR (0x00040000U) /*!< Bit mask for ENET_EIMR_PLR. */ #define BS_ENET_EIMR_PLR (1U) /*!< Bit field size in bits for ENET_EIMR_PLR. */ /*! @brief Read current value of the ENET_EIMR_PLR field. */ #define BR_ENET_EIMR_PLR(x) (BITBAND_ACCESS32(HW_ENET_EIMR_ADDR(x), BP_ENET_EIMR_PLR)) /*! @brief Format value for bitfield ENET_EIMR_PLR. */ #define BF_ENET_EIMR_PLR(v) ((uint32_t)((uint32_t)(v) << BP_ENET_EIMR_PLR) & BM_ENET_EIMR_PLR) /*! @brief Set the PLR field to a new value. */ #define BW_ENET_EIMR_PLR(x, v) (BITBAND_ACCESS32(HW_ENET_EIMR_ADDR(x), BP_ENET_EIMR_PLR) = (v)) /*@}*/ /*! * @name Register ENET_EIMR, field UN[19] (RW) * * Corresponds to interrupt source EIR[UN] and determines whether an interrupt * condition can generate an interrupt. At every module clock, the EIR samples the * signal generated by the interrupting source. The corresponding EIR UN field * reflects the state of the interrupt signal even if the corresponding EIMR field * is cleared. */ /*@{*/ #define BP_ENET_EIMR_UN (19U) /*!< Bit position for ENET_EIMR_UN. */ #define BM_ENET_EIMR_UN (0x00080000U) /*!< Bit mask for ENET_EIMR_UN. */ #define BS_ENET_EIMR_UN (1U) /*!< Bit field size in bits for ENET_EIMR_UN. */ /*! @brief Read current value of the ENET_EIMR_UN field. */ #define BR_ENET_EIMR_UN(x) (BITBAND_ACCESS32(HW_ENET_EIMR_ADDR(x), BP_ENET_EIMR_UN)) /*! @brief Format value for bitfield ENET_EIMR_UN. */ #define BF_ENET_EIMR_UN(v) ((uint32_t)((uint32_t)(v) << BP_ENET_EIMR_UN) & BM_ENET_EIMR_UN) /*! @brief Set the UN field to a new value. */ #define BW_ENET_EIMR_UN(x, v) (BITBAND_ACCESS32(HW_ENET_EIMR_ADDR(x), BP_ENET_EIMR_UN) = (v)) /*@}*/ /*! * @name Register ENET_EIMR, field RL[20] (RW) * * Corresponds to interrupt source EIR[RL] and determines whether an interrupt * condition can generate an interrupt. At every module clock, the EIR samples the * signal generated by the interrupting source. The corresponding EIR RL field * reflects the state of the interrupt signal even if the corresponding EIMR field * is cleared. */ /*@{*/ #define BP_ENET_EIMR_RL (20U) /*!< Bit position for ENET_EIMR_RL. */ #define BM_ENET_EIMR_RL (0x00100000U) /*!< Bit mask for ENET_EIMR_RL. */ #define BS_ENET_EIMR_RL (1U) /*!< Bit field size in bits for ENET_EIMR_RL. */ /*! @brief Read current value of the ENET_EIMR_RL field. */ #define BR_ENET_EIMR_RL(x) (BITBAND_ACCESS32(HW_ENET_EIMR_ADDR(x), BP_ENET_EIMR_RL)) /*! @brief Format value for bitfield ENET_EIMR_RL. */ #define BF_ENET_EIMR_RL(v) ((uint32_t)((uint32_t)(v) << BP_ENET_EIMR_RL) & BM_ENET_EIMR_RL) /*! @brief Set the RL field to a new value. */ #define BW_ENET_EIMR_RL(x, v) (BITBAND_ACCESS32(HW_ENET_EIMR_ADDR(x), BP_ENET_EIMR_RL) = (v)) /*@}*/ /*! * @name Register ENET_EIMR, field LC[21] (RW) * * Corresponds to interrupt source EIR[LC] and determines whether an interrupt * condition can generate an interrupt. At every module clock, the EIR samples the * signal generated by the interrupting source. The corresponding EIR LC field * reflects the state of the interrupt signal even if the corresponding EIMR field * is cleared. */ /*@{*/ #define BP_ENET_EIMR_LC (21U) /*!< Bit position for ENET_EIMR_LC. */ #define BM_ENET_EIMR_LC (0x00200000U) /*!< Bit mask for ENET_EIMR_LC. */ #define BS_ENET_EIMR_LC (1U) /*!< Bit field size in bits for ENET_EIMR_LC. */ /*! @brief Read current value of the ENET_EIMR_LC field. */ #define BR_ENET_EIMR_LC(x) (BITBAND_ACCESS32(HW_ENET_EIMR_ADDR(x), BP_ENET_EIMR_LC)) /*! @brief Format value for bitfield ENET_EIMR_LC. */ #define BF_ENET_EIMR_LC(v) ((uint32_t)((uint32_t)(v) << BP_ENET_EIMR_LC) & BM_ENET_EIMR_LC) /*! @brief Set the LC field to a new value. */ #define BW_ENET_EIMR_LC(x, v) (BITBAND_ACCESS32(HW_ENET_EIMR_ADDR(x), BP_ENET_EIMR_LC) = (v)) /*@}*/ /*! * @name Register ENET_EIMR, field EBERR[22] (RW) * * Corresponds to interrupt source EIR[EBERR] and determines whether an * interrupt condition can generate an interrupt. At every module clock, the EIR samples * the signal generated by the interrupting source. The corresponding EIR EBERR * field reflects the state of the interrupt signal even if the corresponding EIMR * field is cleared. */ /*@{*/ #define BP_ENET_EIMR_EBERR (22U) /*!< Bit position for ENET_EIMR_EBERR. */ #define BM_ENET_EIMR_EBERR (0x00400000U) /*!< Bit mask for ENET_EIMR_EBERR. */ #define BS_ENET_EIMR_EBERR (1U) /*!< Bit field size in bits for ENET_EIMR_EBERR. */ /*! @brief Read current value of the ENET_EIMR_EBERR field. */ #define BR_ENET_EIMR_EBERR(x) (BITBAND_ACCESS32(HW_ENET_EIMR_ADDR(x), BP_ENET_EIMR_EBERR)) /*! @brief Format value for bitfield ENET_EIMR_EBERR. */ #define BF_ENET_EIMR_EBERR(v) ((uint32_t)((uint32_t)(v) << BP_ENET_EIMR_EBERR) & BM_ENET_EIMR_EBERR) /*! @brief Set the EBERR field to a new value. */ #define BW_ENET_EIMR_EBERR(x, v) (BITBAND_ACCESS32(HW_ENET_EIMR_ADDR(x), BP_ENET_EIMR_EBERR) = (v)) /*@}*/ /*! * @name Register ENET_EIMR, field MII[23] (RW) * * Corresponds to interrupt source EIR[MII] and determines whether an interrupt * condition can generate an interrupt. At every module clock, the EIR samples * the signal generated by the interrupting source. The corresponding EIR MII field * reflects the state of the interrupt signal even if the corresponding EIMR * field is cleared. */ /*@{*/ #define BP_ENET_EIMR_MII (23U) /*!< Bit position for ENET_EIMR_MII. */ #define BM_ENET_EIMR_MII (0x00800000U) /*!< Bit mask for ENET_EIMR_MII. */ #define BS_ENET_EIMR_MII (1U) /*!< Bit field size in bits for ENET_EIMR_MII. */ /*! @brief Read current value of the ENET_EIMR_MII field. */ #define BR_ENET_EIMR_MII(x) (BITBAND_ACCESS32(HW_ENET_EIMR_ADDR(x), BP_ENET_EIMR_MII)) /*! @brief Format value for bitfield ENET_EIMR_MII. */ #define BF_ENET_EIMR_MII(v) ((uint32_t)((uint32_t)(v) << BP_ENET_EIMR_MII) & BM_ENET_EIMR_MII) /*! @brief Set the MII field to a new value. */ #define BW_ENET_EIMR_MII(x, v) (BITBAND_ACCESS32(HW_ENET_EIMR_ADDR(x), BP_ENET_EIMR_MII) = (v)) /*@}*/ /*! * @name Register ENET_EIMR, field RXB[24] (RW) * * Corresponds to interrupt source EIR[RXB] and determines whether an interrupt * condition can generate an interrupt. At every module clock, the EIR samples * the signal generated by the interrupting source. The corresponding EIR RXB field * reflects the state of the interrupt signal even if the corresponding EIMR * field is cleared. */ /*@{*/ #define BP_ENET_EIMR_RXB (24U) /*!< Bit position for ENET_EIMR_RXB. */ #define BM_ENET_EIMR_RXB (0x01000000U) /*!< Bit mask for ENET_EIMR_RXB. */ #define BS_ENET_EIMR_RXB (1U) /*!< Bit field size in bits for ENET_EIMR_RXB. */ /*! @brief Read current value of the ENET_EIMR_RXB field. */ #define BR_ENET_EIMR_RXB(x) (BITBAND_ACCESS32(HW_ENET_EIMR_ADDR(x), BP_ENET_EIMR_RXB)) /*! @brief Format value for bitfield ENET_EIMR_RXB. */ #define BF_ENET_EIMR_RXB(v) ((uint32_t)((uint32_t)(v) << BP_ENET_EIMR_RXB) & BM_ENET_EIMR_RXB) /*! @brief Set the RXB field to a new value. */ #define BW_ENET_EIMR_RXB(x, v) (BITBAND_ACCESS32(HW_ENET_EIMR_ADDR(x), BP_ENET_EIMR_RXB) = (v)) /*@}*/ /*! * @name Register ENET_EIMR, field RXF[25] (RW) * * Corresponds to interrupt source EIR[RXF] and determines whether an interrupt * condition can generate an interrupt. At every module clock, the EIR samples * the signal generated by the interrupting source. The corresponding EIR RXF field * reflects the state of the interrupt signal even if the corresponding EIMR * field is cleared. */ /*@{*/ #define BP_ENET_EIMR_RXF (25U) /*!< Bit position for ENET_EIMR_RXF. */ #define BM_ENET_EIMR_RXF (0x02000000U) /*!< Bit mask for ENET_EIMR_RXF. */ #define BS_ENET_EIMR_RXF (1U) /*!< Bit field size in bits for ENET_EIMR_RXF. */ /*! @brief Read current value of the ENET_EIMR_RXF field. */ #define BR_ENET_EIMR_RXF(x) (BITBAND_ACCESS32(HW_ENET_EIMR_ADDR(x), BP_ENET_EIMR_RXF)) /*! @brief Format value for bitfield ENET_EIMR_RXF. */ #define BF_ENET_EIMR_RXF(v) ((uint32_t)((uint32_t)(v) << BP_ENET_EIMR_RXF) & BM_ENET_EIMR_RXF) /*! @brief Set the RXF field to a new value. */ #define BW_ENET_EIMR_RXF(x, v) (BITBAND_ACCESS32(HW_ENET_EIMR_ADDR(x), BP_ENET_EIMR_RXF) = (v)) /*@}*/ /*! * @name Register ENET_EIMR, field TXB[26] (RW) * * Corresponds to interrupt source EIR[TXB] and determines whether an interrupt * condition can generate an interrupt. At every module clock, the EIR samples * the signal generated by the interrupting source. The corresponding EIR TXF field * reflects the state of the interrupt signal even if the corresponding EIMR * field is cleared. * * Values: * - 0 - The corresponding interrupt source is masked. * - 1 - The corresponding interrupt source is not masked. */ /*@{*/ #define BP_ENET_EIMR_TXB (26U) /*!< Bit position for ENET_EIMR_TXB. */ #define BM_ENET_EIMR_TXB (0x04000000U) /*!< Bit mask for ENET_EIMR_TXB. */ #define BS_ENET_EIMR_TXB (1U) /*!< Bit field size in bits for ENET_EIMR_TXB. */ /*! @brief Read current value of the ENET_EIMR_TXB field. */ #define BR_ENET_EIMR_TXB(x) (BITBAND_ACCESS32(HW_ENET_EIMR_ADDR(x), BP_ENET_EIMR_TXB)) /*! @brief Format value for bitfield ENET_EIMR_TXB. */ #define BF_ENET_EIMR_TXB(v) ((uint32_t)((uint32_t)(v) << BP_ENET_EIMR_TXB) & BM_ENET_EIMR_TXB) /*! @brief Set the TXB field to a new value. */ #define BW_ENET_EIMR_TXB(x, v) (BITBAND_ACCESS32(HW_ENET_EIMR_ADDR(x), BP_ENET_EIMR_TXB) = (v)) /*@}*/ /*! * @name Register ENET_EIMR, field TXF[27] (RW) * * Corresponds to interrupt source EIR[TXF] and determines whether an interrupt * condition can generate an interrupt. At every module clock, the EIR samples * the signal generated by the interrupting source. The corresponding EIR TXF field * reflects the state of the interrupt signal even if the corresponding EIMR * field is cleared. * * Values: * - 0 - The corresponding interrupt source is masked. * - 1 - The corresponding interrupt source is not masked. */ /*@{*/ #define BP_ENET_EIMR_TXF (27U) /*!< Bit position for ENET_EIMR_TXF. */ #define BM_ENET_EIMR_TXF (0x08000000U) /*!< Bit mask for ENET_EIMR_TXF. */ #define BS_ENET_EIMR_TXF (1U) /*!< Bit field size in bits for ENET_EIMR_TXF. */ /*! @brief Read current value of the ENET_EIMR_TXF field. */ #define BR_ENET_EIMR_TXF(x) (BITBAND_ACCESS32(HW_ENET_EIMR_ADDR(x), BP_ENET_EIMR_TXF)) /*! @brief Format value for bitfield ENET_EIMR_TXF. */ #define BF_ENET_EIMR_TXF(v) ((uint32_t)((uint32_t)(v) << BP_ENET_EIMR_TXF) & BM_ENET_EIMR_TXF) /*! @brief Set the TXF field to a new value. */ #define BW_ENET_EIMR_TXF(x, v) (BITBAND_ACCESS32(HW_ENET_EIMR_ADDR(x), BP_ENET_EIMR_TXF) = (v)) /*@}*/ /*! * @name Register ENET_EIMR, field GRA[28] (RW) * * Corresponds to interrupt source EIR[GRA] and determines whether an interrupt * condition can generate an interrupt. At every module clock, the EIR samples * the signal generated by the interrupting source. The corresponding EIR GRA field * reflects the state of the interrupt signal even if the corresponding EIMR * field is cleared. * * Values: * - 0 - The corresponding interrupt source is masked. * - 1 - The corresponding interrupt source is not masked. */ /*@{*/ #define BP_ENET_EIMR_GRA (28U) /*!< Bit position for ENET_EIMR_GRA. */ #define BM_ENET_EIMR_GRA (0x10000000U) /*!< Bit mask for ENET_EIMR_GRA. */ #define BS_ENET_EIMR_GRA (1U) /*!< Bit field size in bits for ENET_EIMR_GRA. */ /*! @brief Read current value of the ENET_EIMR_GRA field. */ #define BR_ENET_EIMR_GRA(x) (BITBAND_ACCESS32(HW_ENET_EIMR_ADDR(x), BP_ENET_EIMR_GRA)) /*! @brief Format value for bitfield ENET_EIMR_GRA. */ #define BF_ENET_EIMR_GRA(v) ((uint32_t)((uint32_t)(v) << BP_ENET_EIMR_GRA) & BM_ENET_EIMR_GRA) /*! @brief Set the GRA field to a new value. */ #define BW_ENET_EIMR_GRA(x, v) (BITBAND_ACCESS32(HW_ENET_EIMR_ADDR(x), BP_ENET_EIMR_GRA) = (v)) /*@}*/ /*! * @name Register ENET_EIMR, field BABT[29] (RW) * * Corresponds to interrupt source EIR[BABT] and determines whether an interrupt * condition can generate an interrupt. At every module clock, the EIR samples * the signal generated by the interrupting source. The corresponding EIR BABT * field reflects the state of the interrupt signal even if the corresponding EIMR * field is cleared. * * Values: * - 0 - The corresponding interrupt source is masked. * - 1 - The corresponding interrupt source is not masked. */ /*@{*/ #define BP_ENET_EIMR_BABT (29U) /*!< Bit position for ENET_EIMR_BABT. */ #define BM_ENET_EIMR_BABT (0x20000000U) /*!< Bit mask for ENET_EIMR_BABT. */ #define BS_ENET_EIMR_BABT (1U) /*!< Bit field size in bits for ENET_EIMR_BABT. */ /*! @brief Read current value of the ENET_EIMR_BABT field. */ #define BR_ENET_EIMR_BABT(x) (BITBAND_ACCESS32(HW_ENET_EIMR_ADDR(x), BP_ENET_EIMR_BABT)) /*! @brief Format value for bitfield ENET_EIMR_BABT. */ #define BF_ENET_EIMR_BABT(v) ((uint32_t)((uint32_t)(v) << BP_ENET_EIMR_BABT) & BM_ENET_EIMR_BABT) /*! @brief Set the BABT field to a new value. */ #define BW_ENET_EIMR_BABT(x, v) (BITBAND_ACCESS32(HW_ENET_EIMR_ADDR(x), BP_ENET_EIMR_BABT) = (v)) /*@}*/ /*! * @name Register ENET_EIMR, field BABR[30] (RW) * * Corresponds to interrupt source EIR[BABR] and determines whether an interrupt * condition can generate an interrupt. At every module clock, the EIR samples * the signal generated by the interrupting source. The corresponding EIR BABR * field reflects the state of the interrupt signal even if the corresponding EIMR * field is cleared. * * Values: * - 0 - The corresponding interrupt source is masked. * - 1 - The corresponding interrupt source is not masked. */ /*@{*/ #define BP_ENET_EIMR_BABR (30U) /*!< Bit position for ENET_EIMR_BABR. */ #define BM_ENET_EIMR_BABR (0x40000000U) /*!< Bit mask for ENET_EIMR_BABR. */ #define BS_ENET_EIMR_BABR (1U) /*!< Bit field size in bits for ENET_EIMR_BABR. */ /*! @brief Read current value of the ENET_EIMR_BABR field. */ #define BR_ENET_EIMR_BABR(x) (BITBAND_ACCESS32(HW_ENET_EIMR_ADDR(x), BP_ENET_EIMR_BABR)) /*! @brief Format value for bitfield ENET_EIMR_BABR. */ #define BF_ENET_EIMR_BABR(v) ((uint32_t)((uint32_t)(v) << BP_ENET_EIMR_BABR) & BM_ENET_EIMR_BABR) /*! @brief Set the BABR field to a new value. */ #define BW_ENET_EIMR_BABR(x, v) (BITBAND_ACCESS32(HW_ENET_EIMR_ADDR(x), BP_ENET_EIMR_BABR) = (v)) /*@}*/ /******************************************************************************* * HW_ENET_RDAR - Receive Descriptor Active Register ******************************************************************************/ /*! * @brief HW_ENET_RDAR - Receive Descriptor Active Register (RW) * * Reset value: 0x00000000U * * RDAR is a command register, written by the user, to indicate that the receive * descriptor ring has been updated, that is, that the driver produced empty * receive buffers with the empty bit set. */ typedef union _hw_enet_rdar { uint32_t U; struct _hw_enet_rdar_bitfields { uint32_t RESERVED0 : 24; /*!< [23:0] */ uint32_t RDAR : 1; /*!< [24] Receive Descriptor Active */ uint32_t RESERVED1 : 7; /*!< [31:25] */ } B; } hw_enet_rdar_t; /*! * @name Constants and macros for entire ENET_RDAR register */ /*@{*/ #define HW_ENET_RDAR_ADDR(x) ((x) + 0x10U) #define HW_ENET_RDAR(x) (*(__IO hw_enet_rdar_t *) HW_ENET_RDAR_ADDR(x)) #define HW_ENET_RDAR_RD(x) (HW_ENET_RDAR(x).U) #define HW_ENET_RDAR_WR(x, v) (HW_ENET_RDAR(x).U = (v)) #define HW_ENET_RDAR_SET(x, v) (HW_ENET_RDAR_WR(x, HW_ENET_RDAR_RD(x) | (v))) #define HW_ENET_RDAR_CLR(x, v) (HW_ENET_RDAR_WR(x, HW_ENET_RDAR_RD(x) & ~(v))) #define HW_ENET_RDAR_TOG(x, v) (HW_ENET_RDAR_WR(x, HW_ENET_RDAR_RD(x) ^ (v))) /*@}*/ /* * Constants & macros for individual ENET_RDAR bitfields */ /*! * @name Register ENET_RDAR, field RDAR[24] (RW) * * Always set to 1 when this register is written, regardless of the value * written. This field is cleared by the MAC device when no additional empty * descriptors remain in the receive ring. It is also cleared when ECR[ETHEREN] transitions * from set to cleared or when ECR[RESET] is set. */ /*@{*/ #define BP_ENET_RDAR_RDAR (24U) /*!< Bit position for ENET_RDAR_RDAR. */ #define BM_ENET_RDAR_RDAR (0x01000000U) /*!< Bit mask for ENET_RDAR_RDAR. */ #define BS_ENET_RDAR_RDAR (1U) /*!< Bit field size in bits for ENET_RDAR_RDAR. */ /*! @brief Read current value of the ENET_RDAR_RDAR field. */ #define BR_ENET_RDAR_RDAR(x) (BITBAND_ACCESS32(HW_ENET_RDAR_ADDR(x), BP_ENET_RDAR_RDAR)) /*! @brief Format value for bitfield ENET_RDAR_RDAR. */ #define BF_ENET_RDAR_RDAR(v) ((uint32_t)((uint32_t)(v) << BP_ENET_RDAR_RDAR) & BM_ENET_RDAR_RDAR) /*! @brief Set the RDAR field to a new value. */ #define BW_ENET_RDAR_RDAR(x, v) (BITBAND_ACCESS32(HW_ENET_RDAR_ADDR(x), BP_ENET_RDAR_RDAR) = (v)) /*@}*/ /******************************************************************************* * HW_ENET_TDAR - Transmit Descriptor Active Register ******************************************************************************/ /*! * @brief HW_ENET_TDAR - Transmit Descriptor Active Register (RW) * * Reset value: 0x00000000U * * The TDAR is a command register that the user writes to indicate that the * transmit descriptor ring has been updated, that is, that transmit buffers have * been produced by the driver with the ready bit set in the buffer descriptor. The * TDAR register is cleared at reset, when ECR[ETHEREN] transitions from set to * cleared, or when ECR[RESET] is set. */ typedef union _hw_enet_tdar { uint32_t U; struct _hw_enet_tdar_bitfields { uint32_t RESERVED0 : 24; /*!< [23:0] */ uint32_t TDAR : 1; /*!< [24] Transmit Descriptor Active */ uint32_t RESERVED1 : 7; /*!< [31:25] */ } B; } hw_enet_tdar_t; /*! * @name Constants and macros for entire ENET_TDAR register */ /*@{*/ #define HW_ENET_TDAR_ADDR(x) ((x) + 0x14U) #define HW_ENET_TDAR(x) (*(__IO hw_enet_tdar_t *) HW_ENET_TDAR_ADDR(x)) #define HW_ENET_TDAR_RD(x) (HW_ENET_TDAR(x).U) #define HW_ENET_TDAR_WR(x, v) (HW_ENET_TDAR(x).U = (v)) #define HW_ENET_TDAR_SET(x, v) (HW_ENET_TDAR_WR(x, HW_ENET_TDAR_RD(x) | (v))) #define HW_ENET_TDAR_CLR(x, v) (HW_ENET_TDAR_WR(x, HW_ENET_TDAR_RD(x) & ~(v))) #define HW_ENET_TDAR_TOG(x, v) (HW_ENET_TDAR_WR(x, HW_ENET_TDAR_RD(x) ^ (v))) /*@}*/ /* * Constants & macros for individual ENET_TDAR bitfields */ /*! * @name Register ENET_TDAR, field TDAR[24] (RW) * * Always set to 1 when this register is written, regardless of the value * written. This bit is cleared by the MAC device when no additional ready descriptors * remain in the transmit ring. Also cleared when ECR[ETHEREN] transitions from * set to cleared or when ECR[RESET] is set. */ /*@{*/ #define BP_ENET_TDAR_TDAR (24U) /*!< Bit position for ENET_TDAR_TDAR. */ #define BM_ENET_TDAR_TDAR (0x01000000U) /*!< Bit mask for ENET_TDAR_TDAR. */ #define BS_ENET_TDAR_TDAR (1U) /*!< Bit field size in bits for ENET_TDAR_TDAR. */ /*! @brief Read current value of the ENET_TDAR_TDAR field. */ #define BR_ENET_TDAR_TDAR(x) (BITBAND_ACCESS32(HW_ENET_TDAR_ADDR(x), BP_ENET_TDAR_TDAR)) /*! @brief Format value for bitfield ENET_TDAR_TDAR. */ #define BF_ENET_TDAR_TDAR(v) ((uint32_t)((uint32_t)(v) << BP_ENET_TDAR_TDAR) & BM_ENET_TDAR_TDAR) /*! @brief Set the TDAR field to a new value. */ #define BW_ENET_TDAR_TDAR(x, v) (BITBAND_ACCESS32(HW_ENET_TDAR_ADDR(x), BP_ENET_TDAR_TDAR) = (v)) /*@}*/ /******************************************************************************* * HW_ENET_ECR - Ethernet Control Register ******************************************************************************/ /*! * @brief HW_ENET_ECR - Ethernet Control Register (RW) * * Reset value: 0xF0000000U * * ECR is a read/write user register, though hardware may also alter fields in * this register. It controls many of the high level features of the Ethernet MAC, * including legacy FEC support through the EN1588 field. */ typedef union _hw_enet_ecr { uint32_t U; struct _hw_enet_ecr_bitfields { uint32_t RESET : 1; /*!< [0] Ethernet MAC Reset */ uint32_t ETHEREN : 1; /*!< [1] Ethernet Enable */ uint32_t MAGICEN : 1; /*!< [2] Magic Packet Detection Enable */ uint32_t SLEEP : 1; /*!< [3] Sleep Mode Enable */ uint32_t EN1588 : 1; /*!< [4] EN1588 Enable */ uint32_t RESERVED0 : 1; /*!< [5] */ uint32_t DBGEN : 1; /*!< [6] Debug Enable */ uint32_t STOPEN : 1; /*!< [7] STOPEN Signal Control */ uint32_t DBSWP : 1; /*!< [8] Descriptor Byte Swapping Enable */ uint32_t RESERVED1 : 23; /*!< [31:9] */ } B; } hw_enet_ecr_t; /*! * @name Constants and macros for entire ENET_ECR register */ /*@{*/ #define HW_ENET_ECR_ADDR(x) ((x) + 0x24U) #define HW_ENET_ECR(x) (*(__IO hw_enet_ecr_t *) HW_ENET_ECR_ADDR(x)) #define HW_ENET_ECR_RD(x) (HW_ENET_ECR(x).U) #define HW_ENET_ECR_WR(x, v) (HW_ENET_ECR(x).U = (v)) #define HW_ENET_ECR_SET(x, v) (HW_ENET_ECR_WR(x, HW_ENET_ECR_RD(x) | (v))) #define HW_ENET_ECR_CLR(x, v) (HW_ENET_ECR_WR(x, HW_ENET_ECR_RD(x) & ~(v))) #define HW_ENET_ECR_TOG(x, v) (HW_ENET_ECR_WR(x, HW_ENET_ECR_RD(x) ^ (v))) /*@}*/ /* * Constants & macros for individual ENET_ECR bitfields */ /*! * @name Register ENET_ECR, field RESET[0] (RW) * * When this field is set, it clears the ETHEREN field. */ /*@{*/ #define BP_ENET_ECR_RESET (0U) /*!< Bit position for ENET_ECR_RESET. */ #define BM_ENET_ECR_RESET (0x00000001U) /*!< Bit mask for ENET_ECR_RESET. */ #define BS_ENET_ECR_RESET (1U) /*!< Bit field size in bits for ENET_ECR_RESET. */ /*! @brief Read current value of the ENET_ECR_RESET field. */ #define BR_ENET_ECR_RESET(x) (BITBAND_ACCESS32(HW_ENET_ECR_ADDR(x), BP_ENET_ECR_RESET)) /*! @brief Format value for bitfield ENET_ECR_RESET. */ #define BF_ENET_ECR_RESET(v) ((uint32_t)((uint32_t)(v) << BP_ENET_ECR_RESET) & BM_ENET_ECR_RESET) /*! @brief Set the RESET field to a new value. */ #define BW_ENET_ECR_RESET(x, v) (BITBAND_ACCESS32(HW_ENET_ECR_ADDR(x), BP_ENET_ECR_RESET) = (v)) /*@}*/ /*! * @name Register ENET_ECR, field ETHEREN[1] (RW) * * Enables/disables the Ethernet MAC. When the MAC is disabled, the buffer * descriptors for an aborted transmit frame are not updated. The uDMA, buffer * descriptor, and FIFO control logic are reset, including the buffer descriptor and * FIFO pointers. Hardware clears this field under the following conditions: RESET * is set by software An error condition causes the EBERR field to set. ETHEREN * must be set at the very last step during ENET * configuration/setup/initialization, only after all other ENET-related registers have been configured. If ETHEREN * is cleared to 0 by software then then next time ETHEREN is set, the EIR * interrupts must cleared to 0 due to previous pending interrupts. * * Values: * - 0 - Reception immediately stops and transmission stops after a bad CRC is * appended to any currently transmitted frame. * - 1 - MAC is enabled, and reception and transmission are possible. */ /*@{*/ #define BP_ENET_ECR_ETHEREN (1U) /*!< Bit position for ENET_ECR_ETHEREN. */ #define BM_ENET_ECR_ETHEREN (0x00000002U) /*!< Bit mask for ENET_ECR_ETHEREN. */ #define BS_ENET_ECR_ETHEREN (1U) /*!< Bit field size in bits for ENET_ECR_ETHEREN. */ /*! @brief Read current value of the ENET_ECR_ETHEREN field. */ #define BR_ENET_ECR_ETHEREN(x) (BITBAND_ACCESS32(HW_ENET_ECR_ADDR(x), BP_ENET_ECR_ETHEREN)) /*! @brief Format value for bitfield ENET_ECR_ETHEREN. */ #define BF_ENET_ECR_ETHEREN(v) ((uint32_t)((uint32_t)(v) << BP_ENET_ECR_ETHEREN) & BM_ENET_ECR_ETHEREN) /*! @brief Set the ETHEREN field to a new value. */ #define BW_ENET_ECR_ETHEREN(x, v) (BITBAND_ACCESS32(HW_ENET_ECR_ADDR(x), BP_ENET_ECR_ETHEREN) = (v)) /*@}*/ /*! * @name Register ENET_ECR, field MAGICEN[2] (RW) * * Enables/disables magic packet detection. MAGICEN is relevant only if the * SLEEP field is set. If MAGICEN is set, changing the SLEEP field enables/disables * sleep mode and magic packet detection. * * Values: * - 0 - Magic detection logic disabled. * - 1 - The MAC core detects magic packets and asserts EIR[WAKEUP] when a frame * is detected. */ /*@{*/ #define BP_ENET_ECR_MAGICEN (2U) /*!< Bit position for ENET_ECR_MAGICEN. */ #define BM_ENET_ECR_MAGICEN (0x00000004U) /*!< Bit mask for ENET_ECR_MAGICEN. */ #define BS_ENET_ECR_MAGICEN (1U) /*!< Bit field size in bits for ENET_ECR_MAGICEN. */ /*! @brief Read current value of the ENET_ECR_MAGICEN field. */ #define BR_ENET_ECR_MAGICEN(x) (BITBAND_ACCESS32(HW_ENET_ECR_ADDR(x), BP_ENET_ECR_MAGICEN)) /*! @brief Format value for bitfield ENET_ECR_MAGICEN. */ #define BF_ENET_ECR_MAGICEN(v) ((uint32_t)((uint32_t)(v) << BP_ENET_ECR_MAGICEN) & BM_ENET_ECR_MAGICEN) /*! @brief Set the MAGICEN field to a new value. */ #define BW_ENET_ECR_MAGICEN(x, v) (BITBAND_ACCESS32(HW_ENET_ECR_ADDR(x), BP_ENET_ECR_MAGICEN) = (v)) /*@}*/ /*! * @name Register ENET_ECR, field SLEEP[3] (RW) * * Values: * - 0 - Normal operating mode. * - 1 - Sleep mode. */ /*@{*/ #define BP_ENET_ECR_SLEEP (3U) /*!< Bit position for ENET_ECR_SLEEP. */ #define BM_ENET_ECR_SLEEP (0x00000008U) /*!< Bit mask for ENET_ECR_SLEEP. */ #define BS_ENET_ECR_SLEEP (1U) /*!< Bit field size in bits for ENET_ECR_SLEEP. */ /*! @brief Read current value of the ENET_ECR_SLEEP field. */ #define BR_ENET_ECR_SLEEP(x) (BITBAND_ACCESS32(HW_ENET_ECR_ADDR(x), BP_ENET_ECR_SLEEP)) /*! @brief Format value for bitfield ENET_ECR_SLEEP. */ #define BF_ENET_ECR_SLEEP(v) ((uint32_t)((uint32_t)(v) << BP_ENET_ECR_SLEEP) & BM_ENET_ECR_SLEEP) /*! @brief Set the SLEEP field to a new value. */ #define BW_ENET_ECR_SLEEP(x, v) (BITBAND_ACCESS32(HW_ENET_ECR_ADDR(x), BP_ENET_ECR_SLEEP) = (v)) /*@}*/ /*! * @name Register ENET_ECR, field EN1588[4] (RW) * * Enables enhanced functionality of the MAC. * * Values: * - 0 - Legacy FEC buffer descriptors and functions enabled. * - 1 - Enhanced frame time-stamping functions enabled. */ /*@{*/ #define BP_ENET_ECR_EN1588 (4U) /*!< Bit position for ENET_ECR_EN1588. */ #define BM_ENET_ECR_EN1588 (0x00000010U) /*!< Bit mask for ENET_ECR_EN1588. */ #define BS_ENET_ECR_EN1588 (1U) /*!< Bit field size in bits for ENET_ECR_EN1588. */ /*! @brief Read current value of the ENET_ECR_EN1588 field. */ #define BR_ENET_ECR_EN1588(x) (BITBAND_ACCESS32(HW_ENET_ECR_ADDR(x), BP_ENET_ECR_EN1588)) /*! @brief Format value for bitfield ENET_ECR_EN1588. */ #define BF_ENET_ECR_EN1588(v) ((uint32_t)((uint32_t)(v) << BP_ENET_ECR_EN1588) & BM_ENET_ECR_EN1588) /*! @brief Set the EN1588 field to a new value. */ #define BW_ENET_ECR_EN1588(x, v) (BITBAND_ACCESS32(HW_ENET_ECR_ADDR(x), BP_ENET_ECR_EN1588) = (v)) /*@}*/ /*! * @name Register ENET_ECR, field DBGEN[6] (RW) * * Enables the MAC to enter hardware freeze mode when the device enters debug * mode. * * Values: * - 0 - MAC continues operation in debug mode. * - 1 - MAC enters hardware freeze mode when the processor is in debug mode. */ /*@{*/ #define BP_ENET_ECR_DBGEN (6U) /*!< Bit position for ENET_ECR_DBGEN. */ #define BM_ENET_ECR_DBGEN (0x00000040U) /*!< Bit mask for ENET_ECR_DBGEN. */ #define BS_ENET_ECR_DBGEN (1U) /*!< Bit field size in bits for ENET_ECR_DBGEN. */ /*! @brief Read current value of the ENET_ECR_DBGEN field. */ #define BR_ENET_ECR_DBGEN(x) (BITBAND_ACCESS32(HW_ENET_ECR_ADDR(x), BP_ENET_ECR_DBGEN)) /*! @brief Format value for bitfield ENET_ECR_DBGEN. */ #define BF_ENET_ECR_DBGEN(v) ((uint32_t)((uint32_t)(v) << BP_ENET_ECR_DBGEN) & BM_ENET_ECR_DBGEN) /*! @brief Set the DBGEN field to a new value. */ #define BW_ENET_ECR_DBGEN(x, v) (BITBAND_ACCESS32(HW_ENET_ECR_ADDR(x), BP_ENET_ECR_DBGEN) = (v)) /*@}*/ /*! * @name Register ENET_ECR, field STOPEN[7] (RW) * * Controls device behavior in doze mode. In doze mode, if this field is set * then all the clocks of the ENET assembly are disabled, except the RMII /MII * clock. Doze mode is similar to a conditional stop mode entry for the ENET assembly * depending on ECR[STOPEN]. If module clocks are gated in this mode, the module * can still wake the system after receiving a magic packet in stop mode. MAGICEN * must be set prior to entering sleep/stop mode. */ /*@{*/ #define BP_ENET_ECR_STOPEN (7U) /*!< Bit position for ENET_ECR_STOPEN. */ #define BM_ENET_ECR_STOPEN (0x00000080U) /*!< Bit mask for ENET_ECR_STOPEN. */ #define BS_ENET_ECR_STOPEN (1U) /*!< Bit field size in bits for ENET_ECR_STOPEN. */ /*! @brief Read current value of the ENET_ECR_STOPEN field. */ #define BR_ENET_ECR_STOPEN(x) (BITBAND_ACCESS32(HW_ENET_ECR_ADDR(x), BP_ENET_ECR_STOPEN)) /*! @brief Format value for bitfield ENET_ECR_STOPEN. */ #define BF_ENET_ECR_STOPEN(v) ((uint32_t)((uint32_t)(v) << BP_ENET_ECR_STOPEN) & BM_ENET_ECR_STOPEN) /*! @brief Set the STOPEN field to a new value. */ #define BW_ENET_ECR_STOPEN(x, v) (BITBAND_ACCESS32(HW_ENET_ECR_ADDR(x), BP_ENET_ECR_STOPEN) = (v)) /*@}*/ /*! * @name Register ENET_ECR, field DBSWP[8] (RW) * * Swaps the byte locations of the buffer descriptors. This field must be * written to 1 after reset. * * Values: * - 0 - The buffer descriptor bytes are not swapped to support big-endian * devices. * - 1 - The buffer descriptor bytes are swapped to support little-endian * devices. */ /*@{*/ #define BP_ENET_ECR_DBSWP (8U) /*!< Bit position for ENET_ECR_DBSWP. */ #define BM_ENET_ECR_DBSWP (0x00000100U) /*!< Bit mask for ENET_ECR_DBSWP. */ #define BS_ENET_ECR_DBSWP (1U) /*!< Bit field size in bits for ENET_ECR_DBSWP. */ /*! @brief Read current value of the ENET_ECR_DBSWP field. */ #define BR_ENET_ECR_DBSWP(x) (BITBAND_ACCESS32(HW_ENET_ECR_ADDR(x), BP_ENET_ECR_DBSWP)) /*! @brief Format value for bitfield ENET_ECR_DBSWP. */ #define BF_ENET_ECR_DBSWP(v) ((uint32_t)((uint32_t)(v) << BP_ENET_ECR_DBSWP) & BM_ENET_ECR_DBSWP) /*! @brief Set the DBSWP field to a new value. */ #define BW_ENET_ECR_DBSWP(x, v) (BITBAND_ACCESS32(HW_ENET_ECR_ADDR(x), BP_ENET_ECR_DBSWP) = (v)) /*@}*/ /******************************************************************************* * HW_ENET_MMFR - MII Management Frame Register ******************************************************************************/ /*! * @brief HW_ENET_MMFR - MII Management Frame Register (RW) * * Reset value: 0x00000000U * * Writing to MMFR triggers a management frame transaction to the PHY device * unless MSCR is programmed to zero. If MSCR is changed from zero to non-zero * during a write to MMFR, an MII frame is generated with the data previously written * to the MMFR. This allows MMFR and MSCR to be programmed in either order if * MSCR is currently zero. If the MMFR register is written while frame generation is * in progress, the frame contents are altered. Software must use the EIR[MII] * interrupt indication to avoid writing to the MMFR register while frame * generation is in progress. */ typedef union _hw_enet_mmfr { uint32_t U; struct _hw_enet_mmfr_bitfields { uint32_t DATA : 16; /*!< [15:0] Management Frame Data */ uint32_t TA : 2; /*!< [17:16] Turn Around */ uint32_t RA : 5; /*!< [22:18] Register Address */ uint32_t PA : 5; /*!< [27:23] PHY Address */ uint32_t OP : 2; /*!< [29:28] Operation Code */ uint32_t ST : 2; /*!< [31:30] Start Of Frame Delimiter */ } B; } hw_enet_mmfr_t; /*! * @name Constants and macros for entire ENET_MMFR register */ /*@{*/ #define HW_ENET_MMFR_ADDR(x) ((x) + 0x40U) #define HW_ENET_MMFR(x) (*(__IO hw_enet_mmfr_t *) HW_ENET_MMFR_ADDR(x)) #define HW_ENET_MMFR_RD(x) (HW_ENET_MMFR(x).U) #define HW_ENET_MMFR_WR(x, v) (HW_ENET_MMFR(x).U = (v)) #define HW_ENET_MMFR_SET(x, v) (HW_ENET_MMFR_WR(x, HW_ENET_MMFR_RD(x) | (v))) #define HW_ENET_MMFR_CLR(x, v) (HW_ENET_MMFR_WR(x, HW_ENET_MMFR_RD(x) & ~(v))) #define HW_ENET_MMFR_TOG(x, v) (HW_ENET_MMFR_WR(x, HW_ENET_MMFR_RD(x) ^ (v))) /*@}*/ /* * Constants & macros for individual ENET_MMFR bitfields */ /*! * @name Register ENET_MMFR, field DATA[15:0] (RW) * * This is the field for data to be written to or read from the PHY register. */ /*@{*/ #define BP_ENET_MMFR_DATA (0U) /*!< Bit position for ENET_MMFR_DATA. */ #define BM_ENET_MMFR_DATA (0x0000FFFFU) /*!< Bit mask for ENET_MMFR_DATA. */ #define BS_ENET_MMFR_DATA (16U) /*!< Bit field size in bits for ENET_MMFR_DATA. */ /*! @brief Read current value of the ENET_MMFR_DATA field. */ #define BR_ENET_MMFR_DATA(x) (HW_ENET_MMFR(x).B.DATA) /*! @brief Format value for bitfield ENET_MMFR_DATA. */ #define BF_ENET_MMFR_DATA(v) ((uint32_t)((uint32_t)(v) << BP_ENET_MMFR_DATA) & BM_ENET_MMFR_DATA) /*! @brief Set the DATA field to a new value. */ #define BW_ENET_MMFR_DATA(x, v) (HW_ENET_MMFR_WR(x, (HW_ENET_MMFR_RD(x) & ~BM_ENET_MMFR_DATA) | BF_ENET_MMFR_DATA(v))) /*@}*/ /*! * @name Register ENET_MMFR, field TA[17:16] (RW) * * This field must be programmed to 10 to generate a valid MII management frame. */ /*@{*/ #define BP_ENET_MMFR_TA (16U) /*!< Bit position for ENET_MMFR_TA. */ #define BM_ENET_MMFR_TA (0x00030000U) /*!< Bit mask for ENET_MMFR_TA. */ #define BS_ENET_MMFR_TA (2U) /*!< Bit field size in bits for ENET_MMFR_TA. */ /*! @brief Read current value of the ENET_MMFR_TA field. */ #define BR_ENET_MMFR_TA(x) (HW_ENET_MMFR(x).B.TA) /*! @brief Format value for bitfield ENET_MMFR_TA. */ #define BF_ENET_MMFR_TA(v) ((uint32_t)((uint32_t)(v) << BP_ENET_MMFR_TA) & BM_ENET_MMFR_TA) /*! @brief Set the TA field to a new value. */ #define BW_ENET_MMFR_TA(x, v) (HW_ENET_MMFR_WR(x, (HW_ENET_MMFR_RD(x) & ~BM_ENET_MMFR_TA) | BF_ENET_MMFR_TA(v))) /*@}*/ /*! * @name Register ENET_MMFR, field RA[22:18] (RW) * * Specifies one of up to 32 registers within the specified PHY device. */ /*@{*/ #define BP_ENET_MMFR_RA (18U) /*!< Bit position for ENET_MMFR_RA. */ #define BM_ENET_MMFR_RA (0x007C0000U) /*!< Bit mask for ENET_MMFR_RA. */ #define BS_ENET_MMFR_RA (5U) /*!< Bit field size in bits for ENET_MMFR_RA. */ /*! @brief Read current value of the ENET_MMFR_RA field. */ #define BR_ENET_MMFR_RA(x) (HW_ENET_MMFR(x).B.RA) /*! @brief Format value for bitfield ENET_MMFR_RA. */ #define BF_ENET_MMFR_RA(v) ((uint32_t)((uint32_t)(v) << BP_ENET_MMFR_RA) & BM_ENET_MMFR_RA) /*! @brief Set the RA field to a new value. */ #define BW_ENET_MMFR_RA(x, v) (HW_ENET_MMFR_WR(x, (HW_ENET_MMFR_RD(x) & ~BM_ENET_MMFR_RA) | BF_ENET_MMFR_RA(v))) /*@}*/ /*! * @name Register ENET_MMFR, field PA[27:23] (RW) * * Specifies one of up to 32 attached PHY devices. */ /*@{*/ #define BP_ENET_MMFR_PA (23U) /*!< Bit position for ENET_MMFR_PA. */ #define BM_ENET_MMFR_PA (0x0F800000U) /*!< Bit mask for ENET_MMFR_PA. */ #define BS_ENET_MMFR_PA (5U) /*!< Bit field size in bits for ENET_MMFR_PA. */ /*! @brief Read current value of the ENET_MMFR_PA field. */ #define BR_ENET_MMFR_PA(x) (HW_ENET_MMFR(x).B.PA) /*! @brief Format value for bitfield ENET_MMFR_PA. */ #define BF_ENET_MMFR_PA(v) ((uint32_t)((uint32_t)(v) << BP_ENET_MMFR_PA) & BM_ENET_MMFR_PA) /*! @brief Set the PA field to a new value. */ #define BW_ENET_MMFR_PA(x, v) (HW_ENET_MMFR_WR(x, (HW_ENET_MMFR_RD(x) & ~BM_ENET_MMFR_PA) | BF_ENET_MMFR_PA(v))) /*@}*/ /*! * @name Register ENET_MMFR, field OP[29:28] (RW) * * Determines the frame operation. * * Values: * - 00 - Write frame operation, but not MII compliant. * - 01 - Write frame operation for a valid MII management frame. * - 10 - Read frame operation for a valid MII management frame. * - 11 - Read frame operation, but not MII compliant. */ /*@{*/ #define BP_ENET_MMFR_OP (28U) /*!< Bit position for ENET_MMFR_OP. */ #define BM_ENET_MMFR_OP (0x30000000U) /*!< Bit mask for ENET_MMFR_OP. */ #define BS_ENET_MMFR_OP (2U) /*!< Bit field size in bits for ENET_MMFR_OP. */ /*! @brief Read current value of the ENET_MMFR_OP field. */ #define BR_ENET_MMFR_OP(x) (HW_ENET_MMFR(x).B.OP) /*! @brief Format value for bitfield ENET_MMFR_OP. */ #define BF_ENET_MMFR_OP(v) ((uint32_t)((uint32_t)(v) << BP_ENET_MMFR_OP) & BM_ENET_MMFR_OP) /*! @brief Set the OP field to a new value. */ #define BW_ENET_MMFR_OP(x, v) (HW_ENET_MMFR_WR(x, (HW_ENET_MMFR_RD(x) & ~BM_ENET_MMFR_OP) | BF_ENET_MMFR_OP(v))) /*@}*/ /*! * @name Register ENET_MMFR, field ST[31:30] (RW) * * These fields must be programmed to 01 for a valid MII management frame. */ /*@{*/ #define BP_ENET_MMFR_ST (30U) /*!< Bit position for ENET_MMFR_ST. */ #define BM_ENET_MMFR_ST (0xC0000000U) /*!< Bit mask for ENET_MMFR_ST. */ #define BS_ENET_MMFR_ST (2U) /*!< Bit field size in bits for ENET_MMFR_ST. */ /*! @brief Read current value of the ENET_MMFR_ST field. */ #define BR_ENET_MMFR_ST(x) (HW_ENET_MMFR(x).B.ST) /*! @brief Format value for bitfield ENET_MMFR_ST. */ #define BF_ENET_MMFR_ST(v) ((uint32_t)((uint32_t)(v) << BP_ENET_MMFR_ST) & BM_ENET_MMFR_ST) /*! @brief Set the ST field to a new value. */ #define BW_ENET_MMFR_ST(x, v) (HW_ENET_MMFR_WR(x, (HW_ENET_MMFR_RD(x) & ~BM_ENET_MMFR_ST) | BF_ENET_MMFR_ST(v))) /*@}*/ /******************************************************************************* * HW_ENET_MSCR - MII Speed Control Register ******************************************************************************/ /*! * @brief HW_ENET_MSCR - MII Speed Control Register (RW) * * Reset value: 0x00000000U * * MSCR provides control of the MII clock (MDC pin) frequency and allows a * preamble drop on the MII management frame. The MII_SPEED field must be programmed * with a value to provide an MDC frequency of less than or equal to 2.5 MHz to be * compliant with the IEEE 802.3 MII specification. The MII_SPEED must be set to * a non-zero value to source a read or write management frame. After the * management frame is complete, the MSCR register may optionally be cleared to turn * off MDC. The MDC signal generated has a 50% duty cycle except when MII_SPEED * changes during operation. This change takes effect following a rising or falling * edge of MDC. If the internal module clock is 25 MHz, programming this register * to 0x0000_0004 results in an MDC as stated in the following equation: 25 MHz * / ((4 + 1) x 2) = 2.5 MHz The following table shows the optimum values for * MII_SPEED as a function of internal module clock frequency. Programming Examples * for MSCR Internal MAC clock frequency MSCR [MII_SPEED] MDC frequency 25 MHz * 0x4 2.50 MHz 33 MHz 0x6 2.36 MHz 40 MHz 0x7 2.50 MHz 50 MHz 0x9 2.50 MHz 66 MHz * 0xD 2.36 MHz */ typedef union _hw_enet_mscr { uint32_t U; struct _hw_enet_mscr_bitfields { uint32_t RESERVED0 : 1; /*!< [0] */ uint32_t MII_SPEED : 6; /*!< [6:1] MII Speed */ uint32_t DIS_PRE : 1; /*!< [7] Disable Preamble */ uint32_t HOLDTIME : 3; /*!< [10:8] Hold time On MDIO Output */ uint32_t RESERVED1 : 21; /*!< [31:11] */ } B; } hw_enet_mscr_t; /*! * @name Constants and macros for entire ENET_MSCR register */ /*@{*/ #define HW_ENET_MSCR_ADDR(x) ((x) + 0x44U) #define HW_ENET_MSCR(x) (*(__IO hw_enet_mscr_t *) HW_ENET_MSCR_ADDR(x)) #define HW_ENET_MSCR_RD(x) (HW_ENET_MSCR(x).U) #define HW_ENET_MSCR_WR(x, v) (HW_ENET_MSCR(x).U = (v)) #define HW_ENET_MSCR_SET(x, v) (HW_ENET_MSCR_WR(x, HW_ENET_MSCR_RD(x) | (v))) #define HW_ENET_MSCR_CLR(x, v) (HW_ENET_MSCR_WR(x, HW_ENET_MSCR_RD(x) & ~(v))) #define HW_ENET_MSCR_TOG(x, v) (HW_ENET_MSCR_WR(x, HW_ENET_MSCR_RD(x) ^ (v))) /*@}*/ /* * Constants & macros for individual ENET_MSCR bitfields */ /*! * @name Register ENET_MSCR, field MII_SPEED[6:1] (RW) * * Controls the frequency of the MII management interface clock (MDC) relative * to the internal module clock. A value of 0 in this field turns off MDC and * leaves it in low voltage state. Any non-zero value results in the MDC frequency * of: 1/((MII_SPEED + 1) x 2) of the internal module clock frequency */ /*@{*/ #define BP_ENET_MSCR_MII_SPEED (1U) /*!< Bit position for ENET_MSCR_MII_SPEED. */ #define BM_ENET_MSCR_MII_SPEED (0x0000007EU) /*!< Bit mask for ENET_MSCR_MII_SPEED. */ #define BS_ENET_MSCR_MII_SPEED (6U) /*!< Bit field size in bits for ENET_MSCR_MII_SPEED. */ /*! @brief Read current value of the ENET_MSCR_MII_SPEED field. */ #define BR_ENET_MSCR_MII_SPEED(x) (HW_ENET_MSCR(x).B.MII_SPEED) /*! @brief Format value for bitfield ENET_MSCR_MII_SPEED. */ #define BF_ENET_MSCR_MII_SPEED(v) ((uint32_t)((uint32_t)(v) << BP_ENET_MSCR_MII_SPEED) & BM_ENET_MSCR_MII_SPEED) /*! @brief Set the MII_SPEED field to a new value. */ #define BW_ENET_MSCR_MII_SPEED(x, v) (HW_ENET_MSCR_WR(x, (HW_ENET_MSCR_RD(x) & ~BM_ENET_MSCR_MII_SPEED) | BF_ENET_MSCR_MII_SPEED(v))) /*@}*/ /*! * @name Register ENET_MSCR, field DIS_PRE[7] (RW) * * Enables/disables prepending a preamble to the MII management frame. The MII * standard allows the preamble to be dropped if the attached PHY devices do not * require it. * * Values: * - 0 - Preamble enabled. * - 1 - Preamble (32 ones) is not prepended to the MII management frame. */ /*@{*/ #define BP_ENET_MSCR_DIS_PRE (7U) /*!< Bit position for ENET_MSCR_DIS_PRE. */ #define BM_ENET_MSCR_DIS_PRE (0x00000080U) /*!< Bit mask for ENET_MSCR_DIS_PRE. */ #define BS_ENET_MSCR_DIS_PRE (1U) /*!< Bit field size in bits for ENET_MSCR_DIS_PRE. */ /*! @brief Read current value of the ENET_MSCR_DIS_PRE field. */ #define BR_ENET_MSCR_DIS_PRE(x) (BITBAND_ACCESS32(HW_ENET_MSCR_ADDR(x), BP_ENET_MSCR_DIS_PRE)) /*! @brief Format value for bitfield ENET_MSCR_DIS_PRE. */ #define BF_ENET_MSCR_DIS_PRE(v) ((uint32_t)((uint32_t)(v) << BP_ENET_MSCR_DIS_PRE) & BM_ENET_MSCR_DIS_PRE) /*! @brief Set the DIS_PRE field to a new value. */ #define BW_ENET_MSCR_DIS_PRE(x, v) (BITBAND_ACCESS32(HW_ENET_MSCR_ADDR(x), BP_ENET_MSCR_DIS_PRE) = (v)) /*@}*/ /*! * @name Register ENET_MSCR, field HOLDTIME[10:8] (RW) * * IEEE802.3 clause 22 defines a minimum of 10 ns for the hold time on the MDIO * output. Depending on the host bus frequency, the setting may need to be * increased. * * Values: * - 000 - 1 internal module clock cycle * - 001 - 2 internal module clock cycles * - 010 - 3 internal module clock cycles * - 111 - 8 internal module clock cycles */ /*@{*/ #define BP_ENET_MSCR_HOLDTIME (8U) /*!< Bit position for ENET_MSCR_HOLDTIME. */ #define BM_ENET_MSCR_HOLDTIME (0x00000700U) /*!< Bit mask for ENET_MSCR_HOLDTIME. */ #define BS_ENET_MSCR_HOLDTIME (3U) /*!< Bit field size in bits for ENET_MSCR_HOLDTIME. */ /*! @brief Read current value of the ENET_MSCR_HOLDTIME field. */ #define BR_ENET_MSCR_HOLDTIME(x) (HW_ENET_MSCR(x).B.HOLDTIME) /*! @brief Format value for bitfield ENET_MSCR_HOLDTIME. */ #define BF_ENET_MSCR_HOLDTIME(v) ((uint32_t)((uint32_t)(v) << BP_ENET_MSCR_HOLDTIME) & BM_ENET_MSCR_HOLDTIME) /*! @brief Set the HOLDTIME field to a new value. */ #define BW_ENET_MSCR_HOLDTIME(x, v) (HW_ENET_MSCR_WR(x, (HW_ENET_MSCR_RD(x) & ~BM_ENET_MSCR_HOLDTIME) | BF_ENET_MSCR_HOLDTIME(v))) /*@}*/ /******************************************************************************* * HW_ENET_MIBC - MIB Control Register ******************************************************************************/ /*! * @brief HW_ENET_MIBC - MIB Control Register (RW) * * Reset value: 0xC0000000U * * MIBC is a read/write register controlling and observing the state of the MIB * block. Access this register to disable the MIB block operation or clear the * MIB counters. The MIB_DIS field resets to 1. */ typedef union _hw_enet_mibc { uint32_t U; struct _hw_enet_mibc_bitfields { uint32_t RESERVED0 : 29; /*!< [28:0] */ uint32_t MIB_CLEAR : 1; /*!< [29] MIB Clear */ uint32_t MIB_IDLE : 1; /*!< [30] MIB Idle */ uint32_t MIB_DIS : 1; /*!< [31] Disable MIB Logic */ } B; } hw_enet_mibc_t; /*! * @name Constants and macros for entire ENET_MIBC register */ /*@{*/ #define HW_ENET_MIBC_ADDR(x) ((x) + 0x64U) #define HW_ENET_MIBC(x) (*(__IO hw_enet_mibc_t *) HW_ENET_MIBC_ADDR(x)) #define HW_ENET_MIBC_RD(x) (HW_ENET_MIBC(x).U) #define HW_ENET_MIBC_WR(x, v) (HW_ENET_MIBC(x).U = (v)) #define HW_ENET_MIBC_SET(x, v) (HW_ENET_MIBC_WR(x, HW_ENET_MIBC_RD(x) | (v))) #define HW_ENET_MIBC_CLR(x, v) (HW_ENET_MIBC_WR(x, HW_ENET_MIBC_RD(x) & ~(v))) #define HW_ENET_MIBC_TOG(x, v) (HW_ENET_MIBC_WR(x, HW_ENET_MIBC_RD(x) ^ (v))) /*@}*/ /* * Constants & macros for individual ENET_MIBC bitfields */ /*! * @name Register ENET_MIBC, field MIB_CLEAR[29] (RW) * * If set, all statistics counters are reset to 0. This field is not * self-clearing. To clear the MIB counters set and then clear the field. */ /*@{*/ #define BP_ENET_MIBC_MIB_CLEAR (29U) /*!< Bit position for ENET_MIBC_MIB_CLEAR. */ #define BM_ENET_MIBC_MIB_CLEAR (0x20000000U) /*!< Bit mask for ENET_MIBC_MIB_CLEAR. */ #define BS_ENET_MIBC_MIB_CLEAR (1U) /*!< Bit field size in bits for ENET_MIBC_MIB_CLEAR. */ /*! @brief Read current value of the ENET_MIBC_MIB_CLEAR field. */ #define BR_ENET_MIBC_MIB_CLEAR(x) (BITBAND_ACCESS32(HW_ENET_MIBC_ADDR(x), BP_ENET_MIBC_MIB_CLEAR)) /*! @brief Format value for bitfield ENET_MIBC_MIB_CLEAR. */ #define BF_ENET_MIBC_MIB_CLEAR(v) ((uint32_t)((uint32_t)(v) << BP_ENET_MIBC_MIB_CLEAR) & BM_ENET_MIBC_MIB_CLEAR) /*! @brief Set the MIB_CLEAR field to a new value. */ #define BW_ENET_MIBC_MIB_CLEAR(x, v) (BITBAND_ACCESS32(HW_ENET_MIBC_ADDR(x), BP_ENET_MIBC_MIB_CLEAR) = (v)) /*@}*/ /*! * @name Register ENET_MIBC, field MIB_IDLE[30] (RO) * * If this status field is set, the MIB block is not currently updating any MIB * counters. */ /*@{*/ #define BP_ENET_MIBC_MIB_IDLE (30U) /*!< Bit position for ENET_MIBC_MIB_IDLE. */ #define BM_ENET_MIBC_MIB_IDLE (0x40000000U) /*!< Bit mask for ENET_MIBC_MIB_IDLE. */ #define BS_ENET_MIBC_MIB_IDLE (1U) /*!< Bit field size in bits for ENET_MIBC_MIB_IDLE. */ /*! @brief Read current value of the ENET_MIBC_MIB_IDLE field. */ #define BR_ENET_MIBC_MIB_IDLE(x) (BITBAND_ACCESS32(HW_ENET_MIBC_ADDR(x), BP_ENET_MIBC_MIB_IDLE)) /*@}*/ /*! * @name Register ENET_MIBC, field MIB_DIS[31] (RW) * * If this control field is set, the MIB logic halts and does not update any MIB * counters. */ /*@{*/ #define BP_ENET_MIBC_MIB_DIS (31U) /*!< Bit position for ENET_MIBC_MIB_DIS. */ #define BM_ENET_MIBC_MIB_DIS (0x80000000U) /*!< Bit mask for ENET_MIBC_MIB_DIS. */ #define BS_ENET_MIBC_MIB_DIS (1U) /*!< Bit field size in bits for ENET_MIBC_MIB_DIS. */ /*! @brief Read current value of the ENET_MIBC_MIB_DIS field. */ #define BR_ENET_MIBC_MIB_DIS(x) (BITBAND_ACCESS32(HW_ENET_MIBC_ADDR(x), BP_ENET_MIBC_MIB_DIS)) /*! @brief Format value for bitfield ENET_MIBC_MIB_DIS. */ #define BF_ENET_MIBC_MIB_DIS(v) ((uint32_t)((uint32_t)(v) << BP_ENET_MIBC_MIB_DIS) & BM_ENET_MIBC_MIB_DIS) /*! @brief Set the MIB_DIS field to a new value. */ #define BW_ENET_MIBC_MIB_DIS(x, v) (BITBAND_ACCESS32(HW_ENET_MIBC_ADDR(x), BP_ENET_MIBC_MIB_DIS) = (v)) /*@}*/ /******************************************************************************* * HW_ENET_RCR - Receive Control Register ******************************************************************************/ /*! * @brief HW_ENET_RCR - Receive Control Register (RW) * * Reset value: 0x05EE0001U */ typedef union _hw_enet_rcr { uint32_t U; struct _hw_enet_rcr_bitfields { uint32_t LOOP : 1; /*!< [0] Internal Loopback */ uint32_t DRT : 1; /*!< [1] Disable Receive On Transmit */ uint32_t MII_MODE : 1; /*!< [2] Media Independent Interface Mode */ uint32_t PROM : 1; /*!< [3] Promiscuous Mode */ uint32_t BC_REJ : 1; /*!< [4] Broadcast Frame Reject */ uint32_t FCE : 1; /*!< [5] Flow Control Enable */ uint32_t RESERVED0 : 2; /*!< [7:6] */ uint32_t RMII_MODE : 1; /*!< [8] RMII Mode Enable */ uint32_t RMII_10T : 1; /*!< [9] */ uint32_t RESERVED1 : 2; /*!< [11:10] */ uint32_t PADEN : 1; /*!< [12] Enable Frame Padding Remove On Receive * */ uint32_t PAUFWD : 1; /*!< [13] Terminate/Forward Pause Frames */ uint32_t CRCFWD : 1; /*!< [14] Terminate/Forward Received CRC */ uint32_t CFEN : 1; /*!< [15] MAC Control Frame Enable */ uint32_t MAX_FL : 14; /*!< [29:16] Maximum Frame Length */ uint32_t NLC : 1; /*!< [30] Payload Length Check Disable */ uint32_t GRS : 1; /*!< [31] Graceful Receive Stopped */ } B; } hw_enet_rcr_t; /*! * @name Constants and macros for entire ENET_RCR register */ /*@{*/ #define HW_ENET_RCR_ADDR(x) ((x) + 0x84U) #define HW_ENET_RCR(x) (*(__IO hw_enet_rcr_t *) HW_ENET_RCR_ADDR(x)) #define HW_ENET_RCR_RD(x) (HW_ENET_RCR(x).U) #define HW_ENET_RCR_WR(x, v) (HW_ENET_RCR(x).U = (v)) #define HW_ENET_RCR_SET(x, v) (HW_ENET_RCR_WR(x, HW_ENET_RCR_RD(x) | (v))) #define HW_ENET_RCR_CLR(x, v) (HW_ENET_RCR_WR(x, HW_ENET_RCR_RD(x) & ~(v))) #define HW_ENET_RCR_TOG(x, v) (HW_ENET_RCR_WR(x, HW_ENET_RCR_RD(x) ^ (v))) /*@}*/ /* * Constants & macros for individual ENET_RCR bitfields */ /*! * @name Register ENET_RCR, field LOOP[0] (RW) * * This is an MII internal loopback, therefore MII_MODE must be written to 1 and * RMII_MODE must be written to 0. * * Values: * - 0 - Loopback disabled. * - 1 - Transmitted frames are looped back internal to the device and transmit * MII output signals are not asserted. DRT must be cleared. */ /*@{*/ #define BP_ENET_RCR_LOOP (0U) /*!< Bit position for ENET_RCR_LOOP. */ #define BM_ENET_RCR_LOOP (0x00000001U) /*!< Bit mask for ENET_RCR_LOOP. */ #define BS_ENET_RCR_LOOP (1U) /*!< Bit field size in bits for ENET_RCR_LOOP. */ /*! @brief Read current value of the ENET_RCR_LOOP field. */ #define BR_ENET_RCR_LOOP(x) (BITBAND_ACCESS32(HW_ENET_RCR_ADDR(x), BP_ENET_RCR_LOOP)) /*! @brief Format value for bitfield ENET_RCR_LOOP. */ #define BF_ENET_RCR_LOOP(v) ((uint32_t)((uint32_t)(v) << BP_ENET_RCR_LOOP) & BM_ENET_RCR_LOOP) /*! @brief Set the LOOP field to a new value. */ #define BW_ENET_RCR_LOOP(x, v) (BITBAND_ACCESS32(HW_ENET_RCR_ADDR(x), BP_ENET_RCR_LOOP) = (v)) /*@}*/ /*! * @name Register ENET_RCR, field DRT[1] (RW) * * Values: * - 0 - Receive path operates independently of transmit. Used for full-duplex * or to monitor transmit activity in half-duplex mode. * - 1 - Disable reception of frames while transmitting. Normally used for * half-duplex mode. */ /*@{*/ #define BP_ENET_RCR_DRT (1U) /*!< Bit position for ENET_RCR_DRT. */ #define BM_ENET_RCR_DRT (0x00000002U) /*!< Bit mask for ENET_RCR_DRT. */ #define BS_ENET_RCR_DRT (1U) /*!< Bit field size in bits for ENET_RCR_DRT. */ /*! @brief Read current value of the ENET_RCR_DRT field. */ #define BR_ENET_RCR_DRT(x) (BITBAND_ACCESS32(HW_ENET_RCR_ADDR(x), BP_ENET_RCR_DRT)) /*! @brief Format value for bitfield ENET_RCR_DRT. */ #define BF_ENET_RCR_DRT(v) ((uint32_t)((uint32_t)(v) << BP_ENET_RCR_DRT) & BM_ENET_RCR_DRT) /*! @brief Set the DRT field to a new value. */ #define BW_ENET_RCR_DRT(x, v) (BITBAND_ACCESS32(HW_ENET_RCR_ADDR(x), BP_ENET_RCR_DRT) = (v)) /*@}*/ /*! * @name Register ENET_RCR, field MII_MODE[2] (RW) * * This field must always be set. * * Values: * - 0 - Reserved. * - 1 - MII or RMII mode, as indicated by the RMII_MODE field. */ /*@{*/ #define BP_ENET_RCR_MII_MODE (2U) /*!< Bit position for ENET_RCR_MII_MODE. */ #define BM_ENET_RCR_MII_MODE (0x00000004U) /*!< Bit mask for ENET_RCR_MII_MODE. */ #define BS_ENET_RCR_MII_MODE (1U) /*!< Bit field size in bits for ENET_RCR_MII_MODE. */ /*! @brief Read current value of the ENET_RCR_MII_MODE field. */ #define BR_ENET_RCR_MII_MODE(x) (BITBAND_ACCESS32(HW_ENET_RCR_ADDR(x), BP_ENET_RCR_MII_MODE)) /*! @brief Format value for bitfield ENET_RCR_MII_MODE. */ #define BF_ENET_RCR_MII_MODE(v) ((uint32_t)((uint32_t)(v) << BP_ENET_RCR_MII_MODE) & BM_ENET_RCR_MII_MODE) /*! @brief Set the MII_MODE field to a new value. */ #define BW_ENET_RCR_MII_MODE(x, v) (BITBAND_ACCESS32(HW_ENET_RCR_ADDR(x), BP_ENET_RCR_MII_MODE) = (v)) /*@}*/ /*! * @name Register ENET_RCR, field PROM[3] (RW) * * All frames are accepted regardless of address matching. * * Values: * - 0 - Disabled. * - 1 - Enabled. */ /*@{*/ #define BP_ENET_RCR_PROM (3U) /*!< Bit position for ENET_RCR_PROM. */ #define BM_ENET_RCR_PROM (0x00000008U) /*!< Bit mask for ENET_RCR_PROM. */ #define BS_ENET_RCR_PROM (1U) /*!< Bit field size in bits for ENET_RCR_PROM. */ /*! @brief Read current value of the ENET_RCR_PROM field. */ #define BR_ENET_RCR_PROM(x) (BITBAND_ACCESS32(HW_ENET_RCR_ADDR(x), BP_ENET_RCR_PROM)) /*! @brief Format value for bitfield ENET_RCR_PROM. */ #define BF_ENET_RCR_PROM(v) ((uint32_t)((uint32_t)(v) << BP_ENET_RCR_PROM) & BM_ENET_RCR_PROM) /*! @brief Set the PROM field to a new value. */ #define BW_ENET_RCR_PROM(x, v) (BITBAND_ACCESS32(HW_ENET_RCR_ADDR(x), BP_ENET_RCR_PROM) = (v)) /*@}*/ /*! * @name Register ENET_RCR, field BC_REJ[4] (RW) * * If set, frames with destination address (DA) equal to 0xFFFF_FFFF_FFFF are * rejected unless the PROM field is set. If BC_REJ and PROM are set, frames with * broadcast DA are accepted and the MISS (M) is set in the receive buffer * descriptor. */ /*@{*/ #define BP_ENET_RCR_BC_REJ (4U) /*!< Bit position for ENET_RCR_BC_REJ. */ #define BM_ENET_RCR_BC_REJ (0x00000010U) /*!< Bit mask for ENET_RCR_BC_REJ. */ #define BS_ENET_RCR_BC_REJ (1U) /*!< Bit field size in bits for ENET_RCR_BC_REJ. */ /*! @brief Read current value of the ENET_RCR_BC_REJ field. */ #define BR_ENET_RCR_BC_REJ(x) (BITBAND_ACCESS32(HW_ENET_RCR_ADDR(x), BP_ENET_RCR_BC_REJ)) /*! @brief Format value for bitfield ENET_RCR_BC_REJ. */ #define BF_ENET_RCR_BC_REJ(v) ((uint32_t)((uint32_t)(v) << BP_ENET_RCR_BC_REJ) & BM_ENET_RCR_BC_REJ) /*! @brief Set the BC_REJ field to a new value. */ #define BW_ENET_RCR_BC_REJ(x, v) (BITBAND_ACCESS32(HW_ENET_RCR_ADDR(x), BP_ENET_RCR_BC_REJ) = (v)) /*@}*/ /*! * @name Register ENET_RCR, field FCE[5] (RW) * * If set, the receiver detects PAUSE frames. Upon PAUSE frame detection, the * transmitter stops transmitting data frames for a given duration. */ /*@{*/ #define BP_ENET_RCR_FCE (5U) /*!< Bit position for ENET_RCR_FCE. */ #define BM_ENET_RCR_FCE (0x00000020U) /*!< Bit mask for ENET_RCR_FCE. */ #define BS_ENET_RCR_FCE (1U) /*!< Bit field size in bits for ENET_RCR_FCE. */ /*! @brief Read current value of the ENET_RCR_FCE field. */ #define BR_ENET_RCR_FCE(x) (BITBAND_ACCESS32(HW_ENET_RCR_ADDR(x), BP_ENET_RCR_FCE)) /*! @brief Format value for bitfield ENET_RCR_FCE. */ #define BF_ENET_RCR_FCE(v) ((uint32_t)((uint32_t)(v) << BP_ENET_RCR_FCE) & BM_ENET_RCR_FCE) /*! @brief Set the FCE field to a new value. */ #define BW_ENET_RCR_FCE(x, v) (BITBAND_ACCESS32(HW_ENET_RCR_ADDR(x), BP_ENET_RCR_FCE) = (v)) /*@}*/ /*! * @name Register ENET_RCR, field RMII_MODE[8] (RW) * * Specifies whether the MAC is configured for MII mode or RMII operation . * * Values: * - 0 - MAC configured for MII mode. * - 1 - MAC configured for RMII operation. */ /*@{*/ #define BP_ENET_RCR_RMII_MODE (8U) /*!< Bit position for ENET_RCR_RMII_MODE. */ #define BM_ENET_RCR_RMII_MODE (0x00000100U) /*!< Bit mask for ENET_RCR_RMII_MODE. */ #define BS_ENET_RCR_RMII_MODE (1U) /*!< Bit field size in bits for ENET_RCR_RMII_MODE. */ /*! @brief Read current value of the ENET_RCR_RMII_MODE field. */ #define BR_ENET_RCR_RMII_MODE(x) (BITBAND_ACCESS32(HW_ENET_RCR_ADDR(x), BP_ENET_RCR_RMII_MODE)) /*! @brief Format value for bitfield ENET_RCR_RMII_MODE. */ #define BF_ENET_RCR_RMII_MODE(v) ((uint32_t)((uint32_t)(v) << BP_ENET_RCR_RMII_MODE) & BM_ENET_RCR_RMII_MODE) /*! @brief Set the RMII_MODE field to a new value. */ #define BW_ENET_RCR_RMII_MODE(x, v) (BITBAND_ACCESS32(HW_ENET_RCR_ADDR(x), BP_ENET_RCR_RMII_MODE) = (v)) /*@}*/ /*! * @name Register ENET_RCR, field RMII_10T[9] (RW) * * Enables 10-Mbps mode of the RMII . * * Values: * - 0 - 100 Mbps operation. * - 1 - 10 Mbps operation. */ /*@{*/ #define BP_ENET_RCR_RMII_10T (9U) /*!< Bit position for ENET_RCR_RMII_10T. */ #define BM_ENET_RCR_RMII_10T (0x00000200U) /*!< Bit mask for ENET_RCR_RMII_10T. */ #define BS_ENET_RCR_RMII_10T (1U) /*!< Bit field size in bits for ENET_RCR_RMII_10T. */ /*! @brief Read current value of the ENET_RCR_RMII_10T field. */ #define BR_ENET_RCR_RMII_10T(x) (BITBAND_ACCESS32(HW_ENET_RCR_ADDR(x), BP_ENET_RCR_RMII_10T)) /*! @brief Format value for bitfield ENET_RCR_RMII_10T. */ #define BF_ENET_RCR_RMII_10T(v) ((uint32_t)((uint32_t)(v) << BP_ENET_RCR_RMII_10T) & BM_ENET_RCR_RMII_10T) /*! @brief Set the RMII_10T field to a new value. */ #define BW_ENET_RCR_RMII_10T(x, v) (BITBAND_ACCESS32(HW_ENET_RCR_ADDR(x), BP_ENET_RCR_RMII_10T) = (v)) /*@}*/ /*! * @name Register ENET_RCR, field PADEN[12] (RW) * * Specifies whether the MAC removes padding from received frames. * * Values: * - 0 - No padding is removed on receive by the MAC. * - 1 - Padding is removed from received frames. */ /*@{*/ #define BP_ENET_RCR_PADEN (12U) /*!< Bit position for ENET_RCR_PADEN. */ #define BM_ENET_RCR_PADEN (0x00001000U) /*!< Bit mask for ENET_RCR_PADEN. */ #define BS_ENET_RCR_PADEN (1U) /*!< Bit field size in bits for ENET_RCR_PADEN. */ /*! @brief Read current value of the ENET_RCR_PADEN field. */ #define BR_ENET_RCR_PADEN(x) (BITBAND_ACCESS32(HW_ENET_RCR_ADDR(x), BP_ENET_RCR_PADEN)) /*! @brief Format value for bitfield ENET_RCR_PADEN. */ #define BF_ENET_RCR_PADEN(v) ((uint32_t)((uint32_t)(v) << BP_ENET_RCR_PADEN) & BM_ENET_RCR_PADEN) /*! @brief Set the PADEN field to a new value. */ #define BW_ENET_RCR_PADEN(x, v) (BITBAND_ACCESS32(HW_ENET_RCR_ADDR(x), BP_ENET_RCR_PADEN) = (v)) /*@}*/ /*! * @name Register ENET_RCR, field PAUFWD[13] (RW) * * Specifies whether pause frames are terminated or forwarded. * * Values: * - 0 - Pause frames are terminated and discarded in the MAC. * - 1 - Pause frames are forwarded to the user application. */ /*@{*/ #define BP_ENET_RCR_PAUFWD (13U) /*!< Bit position for ENET_RCR_PAUFWD. */ #define BM_ENET_RCR_PAUFWD (0x00002000U) /*!< Bit mask for ENET_RCR_PAUFWD. */ #define BS_ENET_RCR_PAUFWD (1U) /*!< Bit field size in bits for ENET_RCR_PAUFWD. */ /*! @brief Read current value of the ENET_RCR_PAUFWD field. */ #define BR_ENET_RCR_PAUFWD(x) (BITBAND_ACCESS32(HW_ENET_RCR_ADDR(x), BP_ENET_RCR_PAUFWD)) /*! @brief Format value for bitfield ENET_RCR_PAUFWD. */ #define BF_ENET_RCR_PAUFWD(v) ((uint32_t)((uint32_t)(v) << BP_ENET_RCR_PAUFWD) & BM_ENET_RCR_PAUFWD) /*! @brief Set the PAUFWD field to a new value. */ #define BW_ENET_RCR_PAUFWD(x, v) (BITBAND_ACCESS32(HW_ENET_RCR_ADDR(x), BP_ENET_RCR_PAUFWD) = (v)) /*@}*/ /*! * @name Register ENET_RCR, field CRCFWD[14] (RW) * * Specifies whether the CRC field of received frames is transmitted or * stripped. If padding function is enabled (PADEN = 1), CRCFWD is ignored and the CRC * field is checked and always terminated and removed. * * Values: * - 0 - The CRC field of received frames is transmitted to the user application. * - 1 - The CRC field is stripped from the frame. */ /*@{*/ #define BP_ENET_RCR_CRCFWD (14U) /*!< Bit position for ENET_RCR_CRCFWD. */ #define BM_ENET_RCR_CRCFWD (0x00004000U) /*!< Bit mask for ENET_RCR_CRCFWD. */ #define BS_ENET_RCR_CRCFWD (1U) /*!< Bit field size in bits for ENET_RCR_CRCFWD. */ /*! @brief Read current value of the ENET_RCR_CRCFWD field. */ #define BR_ENET_RCR_CRCFWD(x) (BITBAND_ACCESS32(HW_ENET_RCR_ADDR(x), BP_ENET_RCR_CRCFWD)) /*! @brief Format value for bitfield ENET_RCR_CRCFWD. */ #define BF_ENET_RCR_CRCFWD(v) ((uint32_t)((uint32_t)(v) << BP_ENET_RCR_CRCFWD) & BM_ENET_RCR_CRCFWD) /*! @brief Set the CRCFWD field to a new value. */ #define BW_ENET_RCR_CRCFWD(x, v) (BITBAND_ACCESS32(HW_ENET_RCR_ADDR(x), BP_ENET_RCR_CRCFWD) = (v)) /*@}*/ /*! * @name Register ENET_RCR, field CFEN[15] (RW) * * Enables/disables the MAC control frame. * * Values: * - 0 - MAC control frames with any opcode other than 0x0001 (pause frame) are * accepted and forwarded to the client interface. * - 1 - MAC control frames with any opcode other than 0x0001 (pause frame) are * silently discarded. */ /*@{*/ #define BP_ENET_RCR_CFEN (15U) /*!< Bit position for ENET_RCR_CFEN. */ #define BM_ENET_RCR_CFEN (0x00008000U) /*!< Bit mask for ENET_RCR_CFEN. */ #define BS_ENET_RCR_CFEN (1U) /*!< Bit field size in bits for ENET_RCR_CFEN. */ /*! @brief Read current value of the ENET_RCR_CFEN field. */ #define BR_ENET_RCR_CFEN(x) (BITBAND_ACCESS32(HW_ENET_RCR_ADDR(x), BP_ENET_RCR_CFEN)) /*! @brief Format value for bitfield ENET_RCR_CFEN. */ #define BF_ENET_RCR_CFEN(v) ((uint32_t)((uint32_t)(v) << BP_ENET_RCR_CFEN) & BM_ENET_RCR_CFEN) /*! @brief Set the CFEN field to a new value. */ #define BW_ENET_RCR_CFEN(x, v) (BITBAND_ACCESS32(HW_ENET_RCR_ADDR(x), BP_ENET_RCR_CFEN) = (v)) /*@}*/ /*! * @name Register ENET_RCR, field MAX_FL[29:16] (RW) * * Resets to decimal 1518. Length is measured starting at DA and includes the * CRC at the end of the frame. Transmit frames longer than MAX_FL cause the BABT * interrupt to occur. Receive frames longer than MAX_FL cause the BABR interrupt * to occur and set the LG field in the end of frame receive buffer descriptor. * The recommended default value to be programmed is 1518 or 1522 if VLAN tags are * supported. */ /*@{*/ #define BP_ENET_RCR_MAX_FL (16U) /*!< Bit position for ENET_RCR_MAX_FL. */ #define BM_ENET_RCR_MAX_FL (0x3FFF0000U) /*!< Bit mask for ENET_RCR_MAX_FL. */ #define BS_ENET_RCR_MAX_FL (14U) /*!< Bit field size in bits for ENET_RCR_MAX_FL. */ /*! @brief Read current value of the ENET_RCR_MAX_FL field. */ #define BR_ENET_RCR_MAX_FL(x) (HW_ENET_RCR(x).B.MAX_FL) /*! @brief Format value for bitfield ENET_RCR_MAX_FL. */ #define BF_ENET_RCR_MAX_FL(v) ((uint32_t)((uint32_t)(v) << BP_ENET_RCR_MAX_FL) & BM_ENET_RCR_MAX_FL) /*! @brief Set the MAX_FL field to a new value. */ #define BW_ENET_RCR_MAX_FL(x, v) (HW_ENET_RCR_WR(x, (HW_ENET_RCR_RD(x) & ~BM_ENET_RCR_MAX_FL) | BF_ENET_RCR_MAX_FL(v))) /*@}*/ /*! * @name Register ENET_RCR, field NLC[30] (RW) * * Enables/disables a payload length check. * * Values: * - 0 - The payload length check is disabled. * - 1 - The core checks the frame's payload length with the frame length/type * field. Errors are indicated in the EIR[PLC] field. */ /*@{*/ #define BP_ENET_RCR_NLC (30U) /*!< Bit position for ENET_RCR_NLC. */ #define BM_ENET_RCR_NLC (0x40000000U) /*!< Bit mask for ENET_RCR_NLC. */ #define BS_ENET_RCR_NLC (1U) /*!< Bit field size in bits for ENET_RCR_NLC. */ /*! @brief Read current value of the ENET_RCR_NLC field. */ #define BR_ENET_RCR_NLC(x) (BITBAND_ACCESS32(HW_ENET_RCR_ADDR(x), BP_ENET_RCR_NLC)) /*! @brief Format value for bitfield ENET_RCR_NLC. */ #define BF_ENET_RCR_NLC(v) ((uint32_t)((uint32_t)(v) << BP_ENET_RCR_NLC) & BM_ENET_RCR_NLC) /*! @brief Set the NLC field to a new value. */ #define BW_ENET_RCR_NLC(x, v) (BITBAND_ACCESS32(HW_ENET_RCR_ADDR(x), BP_ENET_RCR_NLC) = (v)) /*@}*/ /*! * @name Register ENET_RCR, field GRS[31] (RO) * * Read-only status indicating that the MAC receive datapath is stopped. */ /*@{*/ #define BP_ENET_RCR_GRS (31U) /*!< Bit position for ENET_RCR_GRS. */ #define BM_ENET_RCR_GRS (0x80000000U) /*!< Bit mask for ENET_RCR_GRS. */ #define BS_ENET_RCR_GRS (1U) /*!< Bit field size in bits for ENET_RCR_GRS. */ /*! @brief Read current value of the ENET_RCR_GRS field. */ #define BR_ENET_RCR_GRS(x) (BITBAND_ACCESS32(HW_ENET_RCR_ADDR(x), BP_ENET_RCR_GRS)) /*@}*/ /******************************************************************************* * HW_ENET_TCR - Transmit Control Register ******************************************************************************/ /*! * @brief HW_ENET_TCR - Transmit Control Register (RW) * * Reset value: 0x00000000U * * TCR is read/write and configures the transmit block. This register is cleared * at system reset. FDEN can only be modified when ECR[ETHEREN] is cleared. */ typedef union _hw_enet_tcr { uint32_t U; struct _hw_enet_tcr_bitfields { uint32_t GTS : 1; /*!< [0] Graceful Transmit Stop */ uint32_t RESERVED0 : 1; /*!< [1] */ uint32_t FDEN : 1; /*!< [2] Full-Duplex Enable */ uint32_t TFC_PAUSE : 1; /*!< [3] Transmit Frame Control Pause */ uint32_t RFC_PAUSE : 1; /*!< [4] Receive Frame Control Pause */ uint32_t ADDSEL : 3; /*!< [7:5] Source MAC Address Select On Transmit * */ uint32_t ADDINS : 1; /*!< [8] Set MAC Address On Transmit */ uint32_t CRCFWD : 1; /*!< [9] Forward Frame From Application With CRC * */ uint32_t RESERVED1 : 22; /*!< [31:10] */ } B; } hw_enet_tcr_t; /*! * @name Constants and macros for entire ENET_TCR register */ /*@{*/ #define HW_ENET_TCR_ADDR(x) ((x) + 0xC4U) #define HW_ENET_TCR(x) (*(__IO hw_enet_tcr_t *) HW_ENET_TCR_ADDR(x)) #define HW_ENET_TCR_RD(x) (HW_ENET_TCR(x).U) #define HW_ENET_TCR_WR(x, v) (HW_ENET_TCR(x).U = (v)) #define HW_ENET_TCR_SET(x, v) (HW_ENET_TCR_WR(x, HW_ENET_TCR_RD(x) | (v))) #define HW_ENET_TCR_CLR(x, v) (HW_ENET_TCR_WR(x, HW_ENET_TCR_RD(x) & ~(v))) #define HW_ENET_TCR_TOG(x, v) (HW_ENET_TCR_WR(x, HW_ENET_TCR_RD(x) ^ (v))) /*@}*/ /* * Constants & macros for individual ENET_TCR bitfields */ /*! * @name Register ENET_TCR, field GTS[0] (RW) * * When this field is set, MAC stops transmission after any frame currently * transmitted is complete and EIR[GRA] is set. If frame transmission is not * currently underway, the GRA interrupt is asserted immediately. After transmission * finishes, clear GTS to restart. The next frame in the transmit FIFO is then * transmitted. If an early collision occurs during transmission when GTS is set, * transmission stops after the collision. The frame is transmitted again after GTS is * cleared. There may be old frames in the transmit FIFO that transmit when GTS * is reasserted. To avoid this, clear ECR[ETHEREN] following the GRA interrupt. */ /*@{*/ #define BP_ENET_TCR_GTS (0U) /*!< Bit position for ENET_TCR_GTS. */ #define BM_ENET_TCR_GTS (0x00000001U) /*!< Bit mask for ENET_TCR_GTS. */ #define BS_ENET_TCR_GTS (1U) /*!< Bit field size in bits for ENET_TCR_GTS. */ /*! @brief Read current value of the ENET_TCR_GTS field. */ #define BR_ENET_TCR_GTS(x) (BITBAND_ACCESS32(HW_ENET_TCR_ADDR(x), BP_ENET_TCR_GTS)) /*! @brief Format value for bitfield ENET_TCR_GTS. */ #define BF_ENET_TCR_GTS(v) ((uint32_t)((uint32_t)(v) << BP_ENET_TCR_GTS) & BM_ENET_TCR_GTS) /*! @brief Set the GTS field to a new value. */ #define BW_ENET_TCR_GTS(x, v) (BITBAND_ACCESS32(HW_ENET_TCR_ADDR(x), BP_ENET_TCR_GTS) = (v)) /*@}*/ /*! * @name Register ENET_TCR, field FDEN[2] (RW) * * If this field is set, frames transmit independent of carrier sense and * collision inputs. Only modify this bit when ECR[ETHEREN] is cleared. */ /*@{*/ #define BP_ENET_TCR_FDEN (2U) /*!< Bit position for ENET_TCR_FDEN. */ #define BM_ENET_TCR_FDEN (0x00000004U) /*!< Bit mask for ENET_TCR_FDEN. */ #define BS_ENET_TCR_FDEN (1U) /*!< Bit field size in bits for ENET_TCR_FDEN. */ /*! @brief Read current value of the ENET_TCR_FDEN field. */ #define BR_ENET_TCR_FDEN(x) (BITBAND_ACCESS32(HW_ENET_TCR_ADDR(x), BP_ENET_TCR_FDEN)) /*! @brief Format value for bitfield ENET_TCR_FDEN. */ #define BF_ENET_TCR_FDEN(v) ((uint32_t)((uint32_t)(v) << BP_ENET_TCR_FDEN) & BM_ENET_TCR_FDEN) /*! @brief Set the FDEN field to a new value. */ #define BW_ENET_TCR_FDEN(x, v) (BITBAND_ACCESS32(HW_ENET_TCR_ADDR(x), BP_ENET_TCR_FDEN) = (v)) /*@}*/ /*! * @name Register ENET_TCR, field TFC_PAUSE[3] (RW) * * Pauses frame transmission. When this field is set, EIR[GRA] is set. With * transmission of data frames stopped, the MAC transmits a MAC control PAUSE frame. * Next, the MAC clears TFC_PAUSE and resumes transmitting data frames. If the * transmitter pauses due to user assertion of GTS or reception of a PAUSE frame, * the MAC may continue transmitting a MAC control PAUSE frame. * * Values: * - 0 - No PAUSE frame transmitted. * - 1 - The MAC stops transmission of data frames after the current * transmission is complete. */ /*@{*/ #define BP_ENET_TCR_TFC_PAUSE (3U) /*!< Bit position for ENET_TCR_TFC_PAUSE. */ #define BM_ENET_TCR_TFC_PAUSE (0x00000008U) /*!< Bit mask for ENET_TCR_TFC_PAUSE. */ #define BS_ENET_TCR_TFC_PAUSE (1U) /*!< Bit field size in bits for ENET_TCR_TFC_PAUSE. */ /*! @brief Read current value of the ENET_TCR_TFC_PAUSE field. */ #define BR_ENET_TCR_TFC_PAUSE(x) (BITBAND_ACCESS32(HW_ENET_TCR_ADDR(x), BP_ENET_TCR_TFC_PAUSE)) /*! @brief Format value for bitfield ENET_TCR_TFC_PAUSE. */ #define BF_ENET_TCR_TFC_PAUSE(v) ((uint32_t)((uint32_t)(v) << BP_ENET_TCR_TFC_PAUSE) & BM_ENET_TCR_TFC_PAUSE) /*! @brief Set the TFC_PAUSE field to a new value. */ #define BW_ENET_TCR_TFC_PAUSE(x, v) (BITBAND_ACCESS32(HW_ENET_TCR_ADDR(x), BP_ENET_TCR_TFC_PAUSE) = (v)) /*@}*/ /*! * @name Register ENET_TCR, field RFC_PAUSE[4] (RO) * * This status field is set when a full-duplex flow control pause frame is * received and the transmitter pauses for the duration defined in this pause frame. * This field automatically clears when the pause duration is complete. */ /*@{*/ #define BP_ENET_TCR_RFC_PAUSE (4U) /*!< Bit position for ENET_TCR_RFC_PAUSE. */ #define BM_ENET_TCR_RFC_PAUSE (0x00000010U) /*!< Bit mask for ENET_TCR_RFC_PAUSE. */ #define BS_ENET_TCR_RFC_PAUSE (1U) /*!< Bit field size in bits for ENET_TCR_RFC_PAUSE. */ /*! @brief Read current value of the ENET_TCR_RFC_PAUSE field. */ #define BR_ENET_TCR_RFC_PAUSE(x) (BITBAND_ACCESS32(HW_ENET_TCR_ADDR(x), BP_ENET_TCR_RFC_PAUSE)) /*@}*/ /*! * @name Register ENET_TCR, field ADDSEL[7:5] (RW) * * If ADDINS is set, indicates the MAC address that overwrites the source MAC * address. * * Values: * - 000 - Node MAC address programmed on PADDR1/2 registers. * - 100 - Reserved. * - 101 - Reserved. * - 110 - Reserved. */ /*@{*/ #define BP_ENET_TCR_ADDSEL (5U) /*!< Bit position for ENET_TCR_ADDSEL. */ #define BM_ENET_TCR_ADDSEL (0x000000E0U) /*!< Bit mask for ENET_TCR_ADDSEL. */ #define BS_ENET_TCR_ADDSEL (3U) /*!< Bit field size in bits for ENET_TCR_ADDSEL. */ /*! @brief Read current value of the ENET_TCR_ADDSEL field. */ #define BR_ENET_TCR_ADDSEL(x) (HW_ENET_TCR(x).B.ADDSEL) /*! @brief Format value for bitfield ENET_TCR_ADDSEL. */ #define BF_ENET_TCR_ADDSEL(v) ((uint32_t)((uint32_t)(v) << BP_ENET_TCR_ADDSEL) & BM_ENET_TCR_ADDSEL) /*! @brief Set the ADDSEL field to a new value. */ #define BW_ENET_TCR_ADDSEL(x, v) (HW_ENET_TCR_WR(x, (HW_ENET_TCR_RD(x) & ~BM_ENET_TCR_ADDSEL) | BF_ENET_TCR_ADDSEL(v))) /*@}*/ /*! * @name Register ENET_TCR, field ADDINS[8] (RW) * * Values: * - 0 - The source MAC address is not modified by the MAC. * - 1 - The MAC overwrites the source MAC address with the programmed MAC * address according to ADDSEL. */ /*@{*/ #define BP_ENET_TCR_ADDINS (8U) /*!< Bit position for ENET_TCR_ADDINS. */ #define BM_ENET_TCR_ADDINS (0x00000100U) /*!< Bit mask for ENET_TCR_ADDINS. */ #define BS_ENET_TCR_ADDINS (1U) /*!< Bit field size in bits for ENET_TCR_ADDINS. */ /*! @brief Read current value of the ENET_TCR_ADDINS field. */ #define BR_ENET_TCR_ADDINS(x) (BITBAND_ACCESS32(HW_ENET_TCR_ADDR(x), BP_ENET_TCR_ADDINS)) /*! @brief Format value for bitfield ENET_TCR_ADDINS. */ #define BF_ENET_TCR_ADDINS(v) ((uint32_t)((uint32_t)(v) << BP_ENET_TCR_ADDINS) & BM_ENET_TCR_ADDINS) /*! @brief Set the ADDINS field to a new value. */ #define BW_ENET_TCR_ADDINS(x, v) (BITBAND_ACCESS32(HW_ENET_TCR_ADDR(x), BP_ENET_TCR_ADDINS) = (v)) /*@}*/ /*! * @name Register ENET_TCR, field CRCFWD[9] (RW) * * Values: * - 0 - TxBD[TC] controls whether the frame has a CRC from the application. * - 1 - The transmitter does not append any CRC to transmitted frames, as it is * expecting a frame with CRC from the application. */ /*@{*/ #define BP_ENET_TCR_CRCFWD (9U) /*!< Bit position for ENET_TCR_CRCFWD. */ #define BM_ENET_TCR_CRCFWD (0x00000200U) /*!< Bit mask for ENET_TCR_CRCFWD. */ #define BS_ENET_TCR_CRCFWD (1U) /*!< Bit field size in bits for ENET_TCR_CRCFWD. */ /*! @brief Read current value of the ENET_TCR_CRCFWD field. */ #define BR_ENET_TCR_CRCFWD(x) (BITBAND_ACCESS32(HW_ENET_TCR_ADDR(x), BP_ENET_TCR_CRCFWD)) /*! @brief Format value for bitfield ENET_TCR_CRCFWD. */ #define BF_ENET_TCR_CRCFWD(v) ((uint32_t)((uint32_t)(v) << BP_ENET_TCR_CRCFWD) & BM_ENET_TCR_CRCFWD) /*! @brief Set the CRCFWD field to a new value. */ #define BW_ENET_TCR_CRCFWD(x, v) (BITBAND_ACCESS32(HW_ENET_TCR_ADDR(x), BP_ENET_TCR_CRCFWD) = (v)) /*@}*/ /******************************************************************************* * HW_ENET_PALR - Physical Address Lower Register ******************************************************************************/ /*! * @brief HW_ENET_PALR - Physical Address Lower Register (RW) * * Reset value: 0x00000000U * * PALR contains the lower 32 bits (bytes 0, 1, 2, 3) of the 48-bit address used * in the address recognition process to compare with the destination address * (DA) field of receive frames with an individual DA. In addition, this register * is used in bytes 0 through 3 of the six-byte source address field when * transmitting PAUSE frames. This register is not reset and you must initialize it. */ typedef union _hw_enet_palr { uint32_t U; struct _hw_enet_palr_bitfields { uint32_t PADDR1 : 32; /*!< [31:0] Pause Address */ } B; } hw_enet_palr_t; /*! * @name Constants and macros for entire ENET_PALR register */ /*@{*/ #define HW_ENET_PALR_ADDR(x) ((x) + 0xE4U) #define HW_ENET_PALR(x) (*(__IO hw_enet_palr_t *) HW_ENET_PALR_ADDR(x)) #define HW_ENET_PALR_RD(x) (HW_ENET_PALR(x).U) #define HW_ENET_PALR_WR(x, v) (HW_ENET_PALR(x).U = (v)) #define HW_ENET_PALR_SET(x, v) (HW_ENET_PALR_WR(x, HW_ENET_PALR_RD(x) | (v))) #define HW_ENET_PALR_CLR(x, v) (HW_ENET_PALR_WR(x, HW_ENET_PALR_RD(x) & ~(v))) #define HW_ENET_PALR_TOG(x, v) (HW_ENET_PALR_WR(x, HW_ENET_PALR_RD(x) ^ (v))) /*@}*/ /* * Constants & macros for individual ENET_PALR bitfields */ /*! * @name Register ENET_PALR, field PADDR1[31:0] (RW) * * Bytes 0 (bits 31:24), 1 (bits 23:16), 2 (bits 15:8), and 3 (bits 7:0) of the * 6-byte individual address are used for exact match and the source address * field in PAUSE frames. */ /*@{*/ #define BP_ENET_PALR_PADDR1 (0U) /*!< Bit position for ENET_PALR_PADDR1. */ #define BM_ENET_PALR_PADDR1 (0xFFFFFFFFU) /*!< Bit mask for ENET_PALR_PADDR1. */ #define BS_ENET_PALR_PADDR1 (32U) /*!< Bit field size in bits for ENET_PALR_PADDR1. */ /*! @brief Read current value of the ENET_PALR_PADDR1 field. */ #define BR_ENET_PALR_PADDR1(x) (HW_ENET_PALR(x).U) /*! @brief Format value for bitfield ENET_PALR_PADDR1. */ #define BF_ENET_PALR_PADDR1(v) ((uint32_t)((uint32_t)(v) << BP_ENET_PALR_PADDR1) & BM_ENET_PALR_PADDR1) /*! @brief Set the PADDR1 field to a new value. */ #define BW_ENET_PALR_PADDR1(x, v) (HW_ENET_PALR_WR(x, v)) /*@}*/ /******************************************************************************* * HW_ENET_PAUR - Physical Address Upper Register ******************************************************************************/ /*! * @brief HW_ENET_PAUR - Physical Address Upper Register (RW) * * Reset value: 0x00008808U * * PAUR contains the upper 16 bits (bytes 4 and 5) of the 48-bit address used in * the address recognition process to compare with the destination address (DA) * field of receive frames with an individual DA. In addition, this register is * used in bytes 4 and 5 of the six-byte source address field when transmitting * PAUSE frames. Bits 15:0 of PAUR contain a constant type field (0x8808) for * transmission of PAUSE frames. The upper 16 bits of this register are not reset and * you must initialize it. */ typedef union _hw_enet_paur { uint32_t U; struct _hw_enet_paur_bitfields { uint32_t TYPE : 16; /*!< [15:0] Type Field In PAUSE Frames */ uint32_t PADDR2 : 16; /*!< [31:16] */ } B; } hw_enet_paur_t; /*! * @name Constants and macros for entire ENET_PAUR register */ /*@{*/ #define HW_ENET_PAUR_ADDR(x) ((x) + 0xE8U) #define HW_ENET_PAUR(x) (*(__IO hw_enet_paur_t *) HW_ENET_PAUR_ADDR(x)) #define HW_ENET_PAUR_RD(x) (HW_ENET_PAUR(x).U) #define HW_ENET_PAUR_WR(x, v) (HW_ENET_PAUR(x).U = (v)) #define HW_ENET_PAUR_SET(x, v) (HW_ENET_PAUR_WR(x, HW_ENET_PAUR_RD(x) | (v))) #define HW_ENET_PAUR_CLR(x, v) (HW_ENET_PAUR_WR(x, HW_ENET_PAUR_RD(x) & ~(v))) #define HW_ENET_PAUR_TOG(x, v) (HW_ENET_PAUR_WR(x, HW_ENET_PAUR_RD(x) ^ (v))) /*@}*/ /* * Constants & macros for individual ENET_PAUR bitfields */ /*! * @name Register ENET_PAUR, field TYPE[15:0] (RO) * * These fields have a constant value of 0x8808. */ /*@{*/ #define BP_ENET_PAUR_TYPE (0U) /*!< Bit position for ENET_PAUR_TYPE. */ #define BM_ENET_PAUR_TYPE (0x0000FFFFU) /*!< Bit mask for ENET_PAUR_TYPE. */ #define BS_ENET_PAUR_TYPE (16U) /*!< Bit field size in bits for ENET_PAUR_TYPE. */ /*! @brief Read current value of the ENET_PAUR_TYPE field. */ #define BR_ENET_PAUR_TYPE(x) (HW_ENET_PAUR(x).B.TYPE) /*@}*/ /*! * @name Register ENET_PAUR, field PADDR2[31:16] (RW) * * Bytes 4 (bits 31:24) and 5 (bits 23:16) of the 6-byte individual address used * for exact match, and the source address field in PAUSE frames. */ /*@{*/ #define BP_ENET_PAUR_PADDR2 (16U) /*!< Bit position for ENET_PAUR_PADDR2. */ #define BM_ENET_PAUR_PADDR2 (0xFFFF0000U) /*!< Bit mask for ENET_PAUR_PADDR2. */ #define BS_ENET_PAUR_PADDR2 (16U) /*!< Bit field size in bits for ENET_PAUR_PADDR2. */ /*! @brief Read current value of the ENET_PAUR_PADDR2 field. */ #define BR_ENET_PAUR_PADDR2(x) (HW_ENET_PAUR(x).B.PADDR2) /*! @brief Format value for bitfield ENET_PAUR_PADDR2. */ #define BF_ENET_PAUR_PADDR2(v) ((uint32_t)((uint32_t)(v) << BP_ENET_PAUR_PADDR2) & BM_ENET_PAUR_PADDR2) /*! @brief Set the PADDR2 field to a new value. */ #define BW_ENET_PAUR_PADDR2(x, v) (HW_ENET_PAUR_WR(x, (HW_ENET_PAUR_RD(x) & ~BM_ENET_PAUR_PADDR2) | BF_ENET_PAUR_PADDR2(v))) /*@}*/ /******************************************************************************* * HW_ENET_OPD - Opcode/Pause Duration Register ******************************************************************************/ /*! * @brief HW_ENET_OPD - Opcode/Pause Duration Register (RW) * * Reset value: 0x00010000U * * OPD is read/write accessible. This register contains the 16-bit opcode and * 16-bit pause duration fields used in transmission of a PAUSE frame. The opcode * field is a constant value, 0x0001. When another node detects a PAUSE frame, * that node pauses transmission for the duration specified in the pause duration * field. The lower 16 bits of this register are not reset and you must initialize * it. */ typedef union _hw_enet_opd { uint32_t U; struct _hw_enet_opd_bitfields { uint32_t PAUSE_DUR : 16; /*!< [15:0] Pause Duration */ uint32_t OPCODE : 16; /*!< [31:16] Opcode Field In PAUSE Frames */ } B; } hw_enet_opd_t; /*! * @name Constants and macros for entire ENET_OPD register */ /*@{*/ #define HW_ENET_OPD_ADDR(x) ((x) + 0xECU) #define HW_ENET_OPD(x) (*(__IO hw_enet_opd_t *) HW_ENET_OPD_ADDR(x)) #define HW_ENET_OPD_RD(x) (HW_ENET_OPD(x).U) #define HW_ENET_OPD_WR(x, v) (HW_ENET_OPD(x).U = (v)) #define HW_ENET_OPD_SET(x, v) (HW_ENET_OPD_WR(x, HW_ENET_OPD_RD(x) | (v))) #define HW_ENET_OPD_CLR(x, v) (HW_ENET_OPD_WR(x, HW_ENET_OPD_RD(x) & ~(v))) #define HW_ENET_OPD_TOG(x, v) (HW_ENET_OPD_WR(x, HW_ENET_OPD_RD(x) ^ (v))) /*@}*/ /* * Constants & macros for individual ENET_OPD bitfields */ /*! * @name Register ENET_OPD, field PAUSE_DUR[15:0] (RW) * * Pause duration field used in PAUSE frames. */ /*@{*/ #define BP_ENET_OPD_PAUSE_DUR (0U) /*!< Bit position for ENET_OPD_PAUSE_DUR. */ #define BM_ENET_OPD_PAUSE_DUR (0x0000FFFFU) /*!< Bit mask for ENET_OPD_PAUSE_DUR. */ #define BS_ENET_OPD_PAUSE_DUR (16U) /*!< Bit field size in bits for ENET_OPD_PAUSE_DUR. */ /*! @brief Read current value of the ENET_OPD_PAUSE_DUR field. */ #define BR_ENET_OPD_PAUSE_DUR(x) (HW_ENET_OPD(x).B.PAUSE_DUR) /*! @brief Format value for bitfield ENET_OPD_PAUSE_DUR. */ #define BF_ENET_OPD_PAUSE_DUR(v) ((uint32_t)((uint32_t)(v) << BP_ENET_OPD_PAUSE_DUR) & BM_ENET_OPD_PAUSE_DUR) /*! @brief Set the PAUSE_DUR field to a new value. */ #define BW_ENET_OPD_PAUSE_DUR(x, v) (HW_ENET_OPD_WR(x, (HW_ENET_OPD_RD(x) & ~BM_ENET_OPD_PAUSE_DUR) | BF_ENET_OPD_PAUSE_DUR(v))) /*@}*/ /*! * @name Register ENET_OPD, field OPCODE[31:16] (RO) * * These fields have a constant value of 0x0001. */ /*@{*/ #define BP_ENET_OPD_OPCODE (16U) /*!< Bit position for ENET_OPD_OPCODE. */ #define BM_ENET_OPD_OPCODE (0xFFFF0000U) /*!< Bit mask for ENET_OPD_OPCODE. */ #define BS_ENET_OPD_OPCODE (16U) /*!< Bit field size in bits for ENET_OPD_OPCODE. */ /*! @brief Read current value of the ENET_OPD_OPCODE field. */ #define BR_ENET_OPD_OPCODE(x) (HW_ENET_OPD(x).B.OPCODE) /*@}*/ /******************************************************************************* * HW_ENET_IAUR - Descriptor Individual Upper Address Register ******************************************************************************/ /*! * @brief HW_ENET_IAUR - Descriptor Individual Upper Address Register (RW) * * Reset value: 0x00000000U * * IAUR contains the upper 32 bits of the 64-bit individual address hash table. * The address recognition process uses this table to check for a possible match * with the destination address (DA) field of receive frames with an individual * DA. This register is not reset and you must initialize it. */ typedef union _hw_enet_iaur { uint32_t U; struct _hw_enet_iaur_bitfields { uint32_t IADDR1 : 32; /*!< [31:0] */ } B; } hw_enet_iaur_t; /*! * @name Constants and macros for entire ENET_IAUR register */ /*@{*/ #define HW_ENET_IAUR_ADDR(x) ((x) + 0x118U) #define HW_ENET_IAUR(x) (*(__IO hw_enet_iaur_t *) HW_ENET_IAUR_ADDR(x)) #define HW_ENET_IAUR_RD(x) (HW_ENET_IAUR(x).U) #define HW_ENET_IAUR_WR(x, v) (HW_ENET_IAUR(x).U = (v)) #define HW_ENET_IAUR_SET(x, v) (HW_ENET_IAUR_WR(x, HW_ENET_IAUR_RD(x) | (v))) #define HW_ENET_IAUR_CLR(x, v) (HW_ENET_IAUR_WR(x, HW_ENET_IAUR_RD(x) & ~(v))) #define HW_ENET_IAUR_TOG(x, v) (HW_ENET_IAUR_WR(x, HW_ENET_IAUR_RD(x) ^ (v))) /*@}*/ /* * Constants & macros for individual ENET_IAUR bitfields */ /*! * @name Register ENET_IAUR, field IADDR1[31:0] (RW) * * Contains the upper 32 bits of the 64-bit hash table used in the address * recognition process for receive frames with a unicast address. Bit 31 of IADDR1 * contains hash index bit 63. Bit 0 of IADDR1 contains hash index bit 32. */ /*@{*/ #define BP_ENET_IAUR_IADDR1 (0U) /*!< Bit position for ENET_IAUR_IADDR1. */ #define BM_ENET_IAUR_IADDR1 (0xFFFFFFFFU) /*!< Bit mask for ENET_IAUR_IADDR1. */ #define BS_ENET_IAUR_IADDR1 (32U) /*!< Bit field size in bits for ENET_IAUR_IADDR1. */ /*! @brief Read current value of the ENET_IAUR_IADDR1 field. */ #define BR_ENET_IAUR_IADDR1(x) (HW_ENET_IAUR(x).U) /*! @brief Format value for bitfield ENET_IAUR_IADDR1. */ #define BF_ENET_IAUR_IADDR1(v) ((uint32_t)((uint32_t)(v) << BP_ENET_IAUR_IADDR1) & BM_ENET_IAUR_IADDR1) /*! @brief Set the IADDR1 field to a new value. */ #define BW_ENET_IAUR_IADDR1(x, v) (HW_ENET_IAUR_WR(x, v)) /*@}*/ /******************************************************************************* * HW_ENET_IALR - Descriptor Individual Lower Address Register ******************************************************************************/ /*! * @brief HW_ENET_IALR - Descriptor Individual Lower Address Register (RW) * * Reset value: 0x00000000U * * IALR contains the lower 32 bits of the 64-bit individual address hash table. * The address recognition process uses this table to check for a possible match * with the DA field of receive frames with an individual DA. This register is * not reset and you must initialize it. */ typedef union _hw_enet_ialr { uint32_t U; struct _hw_enet_ialr_bitfields { uint32_t IADDR2 : 32; /*!< [31:0] */ } B; } hw_enet_ialr_t; /*! * @name Constants and macros for entire ENET_IALR register */ /*@{*/ #define HW_ENET_IALR_ADDR(x) ((x) + 0x11CU) #define HW_ENET_IALR(x) (*(__IO hw_enet_ialr_t *) HW_ENET_IALR_ADDR(x)) #define HW_ENET_IALR_RD(x) (HW_ENET_IALR(x).U) #define HW_ENET_IALR_WR(x, v) (HW_ENET_IALR(x).U = (v)) #define HW_ENET_IALR_SET(x, v) (HW_ENET_IALR_WR(x, HW_ENET_IALR_RD(x) | (v))) #define HW_ENET_IALR_CLR(x, v) (HW_ENET_IALR_WR(x, HW_ENET_IALR_RD(x) & ~(v))) #define HW_ENET_IALR_TOG(x, v) (HW_ENET_IALR_WR(x, HW_ENET_IALR_RD(x) ^ (v))) /*@}*/ /* * Constants & macros for individual ENET_IALR bitfields */ /*! * @name Register ENET_IALR, field IADDR2[31:0] (RW) * * Contains the lower 32 bits of the 64-bit hash table used in the address * recognition process for receive frames with a unicast address. Bit 31 of IADDR2 * contains hash index bit 31. Bit 0 of IADDR2 contains hash index bit 0. */ /*@{*/ #define BP_ENET_IALR_IADDR2 (0U) /*!< Bit position for ENET_IALR_IADDR2. */ #define BM_ENET_IALR_IADDR2 (0xFFFFFFFFU) /*!< Bit mask for ENET_IALR_IADDR2. */ #define BS_ENET_IALR_IADDR2 (32U) /*!< Bit field size in bits for ENET_IALR_IADDR2. */ /*! @brief Read current value of the ENET_IALR_IADDR2 field. */ #define BR_ENET_IALR_IADDR2(x) (HW_ENET_IALR(x).U) /*! @brief Format value for bitfield ENET_IALR_IADDR2. */ #define BF_ENET_IALR_IADDR2(v) ((uint32_t)((uint32_t)(v) << BP_ENET_IALR_IADDR2) & BM_ENET_IALR_IADDR2) /*! @brief Set the IADDR2 field to a new value. */ #define BW_ENET_IALR_IADDR2(x, v) (HW_ENET_IALR_WR(x, v)) /*@}*/ /******************************************************************************* * HW_ENET_GAUR - Descriptor Group Upper Address Register ******************************************************************************/ /*! * @brief HW_ENET_GAUR - Descriptor Group Upper Address Register (RW) * * Reset value: 0x00000000U * * GAUR contains the upper 32 bits of the 64-bit hash table used in the address * recognition process for receive frames with a multicast address. You must * initialize this register. */ typedef union _hw_enet_gaur { uint32_t U; struct _hw_enet_gaur_bitfields { uint32_t GADDR1 : 32; /*!< [31:0] */ } B; } hw_enet_gaur_t; /*! * @name Constants and macros for entire ENET_GAUR register */ /*@{*/ #define HW_ENET_GAUR_ADDR(x) ((x) + 0x120U) #define HW_ENET_GAUR(x) (*(__IO hw_enet_gaur_t *) HW_ENET_GAUR_ADDR(x)) #define HW_ENET_GAUR_RD(x) (HW_ENET_GAUR(x).U) #define HW_ENET_GAUR_WR(x, v) (HW_ENET_GAUR(x).U = (v)) #define HW_ENET_GAUR_SET(x, v) (HW_ENET_GAUR_WR(x, HW_ENET_GAUR_RD(x) | (v))) #define HW_ENET_GAUR_CLR(x, v) (HW_ENET_GAUR_WR(x, HW_ENET_GAUR_RD(x) & ~(v))) #define HW_ENET_GAUR_TOG(x, v) (HW_ENET_GAUR_WR(x, HW_ENET_GAUR_RD(x) ^ (v))) /*@}*/ /* * Constants & macros for individual ENET_GAUR bitfields */ /*! * @name Register ENET_GAUR, field GADDR1[31:0] (RW) * * Contains the upper 32 bits of the 64-bit hash table used in the address * recognition process for receive frames with a multicast address. Bit 31 of GADDR1 * contains hash index bit 63. Bit 0 of GADDR1 contains hash index bit 32. */ /*@{*/ #define BP_ENET_GAUR_GADDR1 (0U) /*!< Bit position for ENET_GAUR_GADDR1. */ #define BM_ENET_GAUR_GADDR1 (0xFFFFFFFFU) /*!< Bit mask for ENET_GAUR_GADDR1. */ #define BS_ENET_GAUR_GADDR1 (32U) /*!< Bit field size in bits for ENET_GAUR_GADDR1. */ /*! @brief Read current value of the ENET_GAUR_GADDR1 field. */ #define BR_ENET_GAUR_GADDR1(x) (HW_ENET_GAUR(x).U) /*! @brief Format value for bitfield ENET_GAUR_GADDR1. */ #define BF_ENET_GAUR_GADDR1(v) ((uint32_t)((uint32_t)(v) << BP_ENET_GAUR_GADDR1) & BM_ENET_GAUR_GADDR1) /*! @brief Set the GADDR1 field to a new value. */ #define BW_ENET_GAUR_GADDR1(x, v) (HW_ENET_GAUR_WR(x, v)) /*@}*/ /******************************************************************************* * HW_ENET_GALR - Descriptor Group Lower Address Register ******************************************************************************/ /*! * @brief HW_ENET_GALR - Descriptor Group Lower Address Register (RW) * * Reset value: 0x00000000U * * GALR contains the lower 32 bits of the 64-bit hash table used in the address * recognition process for receive frames with a multicast address. You must * initialize this register. */ typedef union _hw_enet_galr { uint32_t U; struct _hw_enet_galr_bitfields { uint32_t GADDR2 : 32; /*!< [31:0] */ } B; } hw_enet_galr_t; /*! * @name Constants and macros for entire ENET_GALR register */ /*@{*/ #define HW_ENET_GALR_ADDR(x) ((x) + 0x124U) #define HW_ENET_GALR(x) (*(__IO hw_enet_galr_t *) HW_ENET_GALR_ADDR(x)) #define HW_ENET_GALR_RD(x) (HW_ENET_GALR(x).U) #define HW_ENET_GALR_WR(x, v) (HW_ENET_GALR(x).U = (v)) #define HW_ENET_GALR_SET(x, v) (HW_ENET_GALR_WR(x, HW_ENET_GALR_RD(x) | (v))) #define HW_ENET_GALR_CLR(x, v) (HW_ENET_GALR_WR(x, HW_ENET_GALR_RD(x) & ~(v))) #define HW_ENET_GALR_TOG(x, v) (HW_ENET_GALR_WR(x, HW_ENET_GALR_RD(x) ^ (v))) /*@}*/ /* * Constants & macros for individual ENET_GALR bitfields */ /*! * @name Register ENET_GALR, field GADDR2[31:0] (RW) * * Contains the lower 32 bits of the 64-bit hash table used in the address * recognition process for receive frames with a multicast address. Bit 31 of GADDR2 * contains hash index bit 31. Bit 0 of GADDR2 contains hash index bit 0. */ /*@{*/ #define BP_ENET_GALR_GADDR2 (0U) /*!< Bit position for ENET_GALR_GADDR2. */ #define BM_ENET_GALR_GADDR2 (0xFFFFFFFFU) /*!< Bit mask for ENET_GALR_GADDR2. */ #define BS_ENET_GALR_GADDR2 (32U) /*!< Bit field size in bits for ENET_GALR_GADDR2. */ /*! @brief Read current value of the ENET_GALR_GADDR2 field. */ #define BR_ENET_GALR_GADDR2(x) (HW_ENET_GALR(x).U) /*! @brief Format value for bitfield ENET_GALR_GADDR2. */ #define BF_ENET_GALR_GADDR2(v) ((uint32_t)((uint32_t)(v) << BP_ENET_GALR_GADDR2) & BM_ENET_GALR_GADDR2) /*! @brief Set the GADDR2 field to a new value. */ #define BW_ENET_GALR_GADDR2(x, v) (HW_ENET_GALR_WR(x, v)) /*@}*/ /******************************************************************************* * HW_ENET_TFWR - Transmit FIFO Watermark Register ******************************************************************************/ /*! * @brief HW_ENET_TFWR - Transmit FIFO Watermark Register (RW) * * Reset value: 0x00000000U * * If TFWR[STRFWD] is cleared, TFWR[TFWR] controls the amount of data required * in the transmit FIFO before transmission of a frame can begin. This allows you * to minimize transmit latency (TFWR = 00 or 01) or allow for larger bus access * latency (TFWR = 11) due to contention for the system bus. Setting the * watermark to a high value minimizes the risk of transmit FIFO underrun due to * contention for the system bus. The byte counts associated with the TFWR field may need * to be modified to match a given system requirement. For example, worst case * bus access latency by the transmit data DMA channel. When the FIFO level * reaches the value the TFWR field and when the STR_FWD is set to '0', the MAC * transmit control logic starts frame transmission even before the end-of-frame is * available in the FIFO (cut-through operation). If a complete frame has a size * smaller than the threshold programmed with TFWR, the MAC also transmits the Frame * to the line. To enable store and forward on the Transmit path, set STR_FWD to * '1'. In this case, the MAC starts to transmit data only when a complete frame * is stored in the Transmit FIFO. */ typedef union _hw_enet_tfwr { uint32_t U; struct _hw_enet_tfwr_bitfields { uint32_t TFWR : 6; /*!< [5:0] Transmit FIFO Write */ uint32_t RESERVED0 : 2; /*!< [7:6] */ uint32_t STRFWD : 1; /*!< [8] Store And Forward Enable */ uint32_t RESERVED1 : 23; /*!< [31:9] */ } B; } hw_enet_tfwr_t; /*! * @name Constants and macros for entire ENET_TFWR register */ /*@{*/ #define HW_ENET_TFWR_ADDR(x) ((x) + 0x144U) #define HW_ENET_TFWR(x) (*(__IO hw_enet_tfwr_t *) HW_ENET_TFWR_ADDR(x)) #define HW_ENET_TFWR_RD(x) (HW_ENET_TFWR(x).U) #define HW_ENET_TFWR_WR(x, v) (HW_ENET_TFWR(x).U = (v)) #define HW_ENET_TFWR_SET(x, v) (HW_ENET_TFWR_WR(x, HW_ENET_TFWR_RD(x) | (v))) #define HW_ENET_TFWR_CLR(x, v) (HW_ENET_TFWR_WR(x, HW_ENET_TFWR_RD(x) & ~(v))) #define HW_ENET_TFWR_TOG(x, v) (HW_ENET_TFWR_WR(x, HW_ENET_TFWR_RD(x) ^ (v))) /*@}*/ /* * Constants & macros for individual ENET_TFWR bitfields */ /*! * @name Register ENET_TFWR, field TFWR[5:0] (RW) * * If TFWR[STRFWD] is cleared, this field indicates the number of bytes, in * steps of 64 bytes, written to the transmit FIFO before transmission of a frame * begins. If a frame with less than the threshold is written, it is still sent * independently of this threshold setting. The threshold is relevant only if the * frame is larger than the threshold given. This chip may not support the maximum * number of bytes written shown below. See the chip-specific information for the * ENET module for this value. * * Values: * - 000000 - 64 bytes written. * - 000001 - 64 bytes written. * - 000010 - 128 bytes written. * - 000011 - 192 bytes written. * - 111110 - 3968 bytes written. * - 111111 - 4032 bytes written. */ /*@{*/ #define BP_ENET_TFWR_TFWR (0U) /*!< Bit position for ENET_TFWR_TFWR. */ #define BM_ENET_TFWR_TFWR (0x0000003FU) /*!< Bit mask for ENET_TFWR_TFWR. */ #define BS_ENET_TFWR_TFWR (6U) /*!< Bit field size in bits for ENET_TFWR_TFWR. */ /*! @brief Read current value of the ENET_TFWR_TFWR field. */ #define BR_ENET_TFWR_TFWR(x) (HW_ENET_TFWR(x).B.TFWR) /*! @brief Format value for bitfield ENET_TFWR_TFWR. */ #define BF_ENET_TFWR_TFWR(v) ((uint32_t)((uint32_t)(v) << BP_ENET_TFWR_TFWR) & BM_ENET_TFWR_TFWR) /*! @brief Set the TFWR field to a new value. */ #define BW_ENET_TFWR_TFWR(x, v) (HW_ENET_TFWR_WR(x, (HW_ENET_TFWR_RD(x) & ~BM_ENET_TFWR_TFWR) | BF_ENET_TFWR_TFWR(v))) /*@}*/ /*! * @name Register ENET_TFWR, field STRFWD[8] (RW) * * Values: * - 0 - Reset. The transmission start threshold is programmed in TFWR[TFWR]. * - 1 - Enabled. */ /*@{*/ #define BP_ENET_TFWR_STRFWD (8U) /*!< Bit position for ENET_TFWR_STRFWD. */ #define BM_ENET_TFWR_STRFWD (0x00000100U) /*!< Bit mask for ENET_TFWR_STRFWD. */ #define BS_ENET_TFWR_STRFWD (1U) /*!< Bit field size in bits for ENET_TFWR_STRFWD. */ /*! @brief Read current value of the ENET_TFWR_STRFWD field. */ #define BR_ENET_TFWR_STRFWD(x) (BITBAND_ACCESS32(HW_ENET_TFWR_ADDR(x), BP_ENET_TFWR_STRFWD)) /*! @brief Format value for bitfield ENET_TFWR_STRFWD. */ #define BF_ENET_TFWR_STRFWD(v) ((uint32_t)((uint32_t)(v) << BP_ENET_TFWR_STRFWD) & BM_ENET_TFWR_STRFWD) /*! @brief Set the STRFWD field to a new value. */ #define BW_ENET_TFWR_STRFWD(x, v) (BITBAND_ACCESS32(HW_ENET_TFWR_ADDR(x), BP_ENET_TFWR_STRFWD) = (v)) /*@}*/ /******************************************************************************* * HW_ENET_RDSR - Receive Descriptor Ring Start Register ******************************************************************************/ /*! * @brief HW_ENET_RDSR - Receive Descriptor Ring Start Register (RW) * * Reset value: 0x00000000U * * RDSR points to the beginning of the circular receive buffer descriptor queue * in external memory. This pointer must be 64-bit aligned (bits 2-0 must be * zero); however, it is recommended to be 128-bit aligned, that is, evenly divisible * by 16. This register must be initialized prior to operation */ typedef union _hw_enet_rdsr { uint32_t U; struct _hw_enet_rdsr_bitfields { uint32_t RESERVED0 : 3; /*!< [2:0] */ uint32_t R_DES_START : 29; /*!< [31:3] */ } B; } hw_enet_rdsr_t; /*! * @name Constants and macros for entire ENET_RDSR register */ /*@{*/ #define HW_ENET_RDSR_ADDR(x) ((x) + 0x180U) #define HW_ENET_RDSR(x) (*(__IO hw_enet_rdsr_t *) HW_ENET_RDSR_ADDR(x)) #define HW_ENET_RDSR_RD(x) (HW_ENET_RDSR(x).U) #define HW_ENET_RDSR_WR(x, v) (HW_ENET_RDSR(x).U = (v)) #define HW_ENET_RDSR_SET(x, v) (HW_ENET_RDSR_WR(x, HW_ENET_RDSR_RD(x) | (v))) #define HW_ENET_RDSR_CLR(x, v) (HW_ENET_RDSR_WR(x, HW_ENET_RDSR_RD(x) & ~(v))) #define HW_ENET_RDSR_TOG(x, v) (HW_ENET_RDSR_WR(x, HW_ENET_RDSR_RD(x) ^ (v))) /*@}*/ /* * Constants & macros for individual ENET_RDSR bitfields */ /*! * @name Register ENET_RDSR, field R_DES_START[31:3] (RW) * * Pointer to the beginning of the receive buffer descriptor queue. */ /*@{*/ #define BP_ENET_RDSR_R_DES_START (3U) /*!< Bit position for ENET_RDSR_R_DES_START. */ #define BM_ENET_RDSR_R_DES_START (0xFFFFFFF8U) /*!< Bit mask for ENET_RDSR_R_DES_START. */ #define BS_ENET_RDSR_R_DES_START (29U) /*!< Bit field size in bits for ENET_RDSR_R_DES_START. */ /*! @brief Read current value of the ENET_RDSR_R_DES_START field. */ #define BR_ENET_RDSR_R_DES_START(x) (HW_ENET_RDSR(x).B.R_DES_START) /*! @brief Format value for bitfield ENET_RDSR_R_DES_START. */ #define BF_ENET_RDSR_R_DES_START(v) ((uint32_t)((uint32_t)(v) << BP_ENET_RDSR_R_DES_START) & BM_ENET_RDSR_R_DES_START) /*! @brief Set the R_DES_START field to a new value. */ #define BW_ENET_RDSR_R_DES_START(x, v) (HW_ENET_RDSR_WR(x, (HW_ENET_RDSR_RD(x) & ~BM_ENET_RDSR_R_DES_START) | BF_ENET_RDSR_R_DES_START(v))) /*@}*/ /******************************************************************************* * HW_ENET_TDSR - Transmit Buffer Descriptor Ring Start Register ******************************************************************************/ /*! * @brief HW_ENET_TDSR - Transmit Buffer Descriptor Ring Start Register (RW) * * Reset value: 0x00000000U * * TDSR provides a pointer to the beginning of the circular transmit buffer * descriptor queue in external memory. This pointer must be 64-bit aligned (bits 2-0 * must be zero); however, it is recommended to be 128-bit aligned, that is, * evenly divisible by 16. This register must be initialized prior to operation. */ typedef union _hw_enet_tdsr { uint32_t U; struct _hw_enet_tdsr_bitfields { uint32_t RESERVED0 : 3; /*!< [2:0] */ uint32_t X_DES_START : 29; /*!< [31:3] */ } B; } hw_enet_tdsr_t; /*! * @name Constants and macros for entire ENET_TDSR register */ /*@{*/ #define HW_ENET_TDSR_ADDR(x) ((x) + 0x184U) #define HW_ENET_TDSR(x) (*(__IO hw_enet_tdsr_t *) HW_ENET_TDSR_ADDR(x)) #define HW_ENET_TDSR_RD(x) (HW_ENET_TDSR(x).U) #define HW_ENET_TDSR_WR(x, v) (HW_ENET_TDSR(x).U = (v)) #define HW_ENET_TDSR_SET(x, v) (HW_ENET_TDSR_WR(x, HW_ENET_TDSR_RD(x) | (v))) #define HW_ENET_TDSR_CLR(x, v) (HW_ENET_TDSR_WR(x, HW_ENET_TDSR_RD(x) & ~(v))) #define HW_ENET_TDSR_TOG(x, v) (HW_ENET_TDSR_WR(x, HW_ENET_TDSR_RD(x) ^ (v))) /*@}*/ /* * Constants & macros for individual ENET_TDSR bitfields */ /*! * @name Register ENET_TDSR, field X_DES_START[31:3] (RW) * * Pointer to the beginning of the transmit buffer descriptor queue. */ /*@{*/ #define BP_ENET_TDSR_X_DES_START (3U) /*!< Bit position for ENET_TDSR_X_DES_START. */ #define BM_ENET_TDSR_X_DES_START (0xFFFFFFF8U) /*!< Bit mask for ENET_TDSR_X_DES_START. */ #define BS_ENET_TDSR_X_DES_START (29U) /*!< Bit field size in bits for ENET_TDSR_X_DES_START. */ /*! @brief Read current value of the ENET_TDSR_X_DES_START field. */ #define BR_ENET_TDSR_X_DES_START(x) (HW_ENET_TDSR(x).B.X_DES_START) /*! @brief Format value for bitfield ENET_TDSR_X_DES_START. */ #define BF_ENET_TDSR_X_DES_START(v) ((uint32_t)((uint32_t)(v) << BP_ENET_TDSR_X_DES_START) & BM_ENET_TDSR_X_DES_START) /*! @brief Set the X_DES_START field to a new value. */ #define BW_ENET_TDSR_X_DES_START(x, v) (HW_ENET_TDSR_WR(x, (HW_ENET_TDSR_RD(x) & ~BM_ENET_TDSR_X_DES_START) | BF_ENET_TDSR_X_DES_START(v))) /*@}*/ /******************************************************************************* * HW_ENET_MRBR - Maximum Receive Buffer Size Register ******************************************************************************/ /*! * @brief HW_ENET_MRBR - Maximum Receive Buffer Size Register (RW) * * Reset value: 0x00000000U * * The MRBR is a user-programmable register that dictates the maximum size of * all receive buffers. This value should take into consideration that the receive * CRC is always written into the last receive buffer. To allow one maximum size * frame per buffer, MRBR must be set to RCR[MAX_FL] or larger. To properly align * the buffer, MRBR must be evenly divisible by 16. To ensure this, bits 3-0 are * set to zero by the device. To minimize bus usage (descriptor fetches), set * MRBR greater than or equal to 256 bytes. This register must be initialized * before operation. */ typedef union _hw_enet_mrbr { uint32_t U; struct _hw_enet_mrbr_bitfields { uint32_t RESERVED0 : 4; /*!< [3:0] */ uint32_t R_BUF_SIZE : 10; /*!< [13:4] */ uint32_t RESERVED1 : 18; /*!< [31:14] */ } B; } hw_enet_mrbr_t; /*! * @name Constants and macros for entire ENET_MRBR register */ /*@{*/ #define HW_ENET_MRBR_ADDR(x) ((x) + 0x188U) #define HW_ENET_MRBR(x) (*(__IO hw_enet_mrbr_t *) HW_ENET_MRBR_ADDR(x)) #define HW_ENET_MRBR_RD(x) (HW_ENET_MRBR(x).U) #define HW_ENET_MRBR_WR(x, v) (HW_ENET_MRBR(x).U = (v)) #define HW_ENET_MRBR_SET(x, v) (HW_ENET_MRBR_WR(x, HW_ENET_MRBR_RD(x) | (v))) #define HW_ENET_MRBR_CLR(x, v) (HW_ENET_MRBR_WR(x, HW_ENET_MRBR_RD(x) & ~(v))) #define HW_ENET_MRBR_TOG(x, v) (HW_ENET_MRBR_WR(x, HW_ENET_MRBR_RD(x) ^ (v))) /*@}*/ /* * Constants & macros for individual ENET_MRBR bitfields */ /*! * @name Register ENET_MRBR, field R_BUF_SIZE[13:4] (RW) * * Receive buffer size in bytes. */ /*@{*/ #define BP_ENET_MRBR_R_BUF_SIZE (4U) /*!< Bit position for ENET_MRBR_R_BUF_SIZE. */ #define BM_ENET_MRBR_R_BUF_SIZE (0x00003FF0U) /*!< Bit mask for ENET_MRBR_R_BUF_SIZE. */ #define BS_ENET_MRBR_R_BUF_SIZE (10U) /*!< Bit field size in bits for ENET_MRBR_R_BUF_SIZE. */ /*! @brief Read current value of the ENET_MRBR_R_BUF_SIZE field. */ #define BR_ENET_MRBR_R_BUF_SIZE(x) (HW_ENET_MRBR(x).B.R_BUF_SIZE) /*! @brief Format value for bitfield ENET_MRBR_R_BUF_SIZE. */ #define BF_ENET_MRBR_R_BUF_SIZE(v) ((uint32_t)((uint32_t)(v) << BP_ENET_MRBR_R_BUF_SIZE) & BM_ENET_MRBR_R_BUF_SIZE) /*! @brief Set the R_BUF_SIZE field to a new value. */ #define BW_ENET_MRBR_R_BUF_SIZE(x, v) (HW_ENET_MRBR_WR(x, (HW_ENET_MRBR_RD(x) & ~BM_ENET_MRBR_R_BUF_SIZE) | BF_ENET_MRBR_R_BUF_SIZE(v))) /*@}*/ /******************************************************************************* * HW_ENET_RSFL - Receive FIFO Section Full Threshold ******************************************************************************/ /*! * @brief HW_ENET_RSFL - Receive FIFO Section Full Threshold (RW) * * Reset value: 0x00000000U */ typedef union _hw_enet_rsfl { uint32_t U; struct _hw_enet_rsfl_bitfields { uint32_t RX_SECTION_FULL : 8; /*!< [7:0] Value Of Receive FIFO * Section Full Threshold */ uint32_t RESERVED0 : 24; /*!< [31:8] */ } B; } hw_enet_rsfl_t; /*! * @name Constants and macros for entire ENET_RSFL register */ /*@{*/ #define HW_ENET_RSFL_ADDR(x) ((x) + 0x190U) #define HW_ENET_RSFL(x) (*(__IO hw_enet_rsfl_t *) HW_ENET_RSFL_ADDR(x)) #define HW_ENET_RSFL_RD(x) (HW_ENET_RSFL(x).U) #define HW_ENET_RSFL_WR(x, v) (HW_ENET_RSFL(x).U = (v)) #define HW_ENET_RSFL_SET(x, v) (HW_ENET_RSFL_WR(x, HW_ENET_RSFL_RD(x) | (v))) #define HW_ENET_RSFL_CLR(x, v) (HW_ENET_RSFL_WR(x, HW_ENET_RSFL_RD(x) & ~(v))) #define HW_ENET_RSFL_TOG(x, v) (HW_ENET_RSFL_WR(x, HW_ENET_RSFL_RD(x) ^ (v))) /*@}*/ /* * Constants & macros for individual ENET_RSFL bitfields */ /*! * @name Register ENET_RSFL, field RX_SECTION_FULL[7:0] (RW) * * Value, in 64-bit words, of the receive FIFO section full threshold. Clear * this field to enable store and forward on the RX FIFO. When programming a value * greater than 0 (cut-through operation), it must be greater than * RAEM[RX_ALMOST_EMPTY]. When the FIFO level reaches the value in this field, data is available * in the Receive FIFO (cut-through operation). */ /*@{*/ #define BP_ENET_RSFL_RX_SECTION_FULL (0U) /*!< Bit position for ENET_RSFL_RX_SECTION_FULL. */ #define BM_ENET_RSFL_RX_SECTION_FULL (0x000000FFU) /*!< Bit mask for ENET_RSFL_RX_SECTION_FULL. */ #define BS_ENET_RSFL_RX_SECTION_FULL (8U) /*!< Bit field size in bits for ENET_RSFL_RX_SECTION_FULL. */ /*! @brief Read current value of the ENET_RSFL_RX_SECTION_FULL field. */ #define BR_ENET_RSFL_RX_SECTION_FULL(x) (HW_ENET_RSFL(x).B.RX_SECTION_FULL) /*! @brief Format value for bitfield ENET_RSFL_RX_SECTION_FULL. */ #define BF_ENET_RSFL_RX_SECTION_FULL(v) ((uint32_t)((uint32_t)(v) << BP_ENET_RSFL_RX_SECTION_FULL) & BM_ENET_RSFL_RX_SECTION_FULL) /*! @brief Set the RX_SECTION_FULL field to a new value. */ #define BW_ENET_RSFL_RX_SECTION_FULL(x, v) (HW_ENET_RSFL_WR(x, (HW_ENET_RSFL_RD(x) & ~BM_ENET_RSFL_RX_SECTION_FULL) | BF_ENET_RSFL_RX_SECTION_FULL(v))) /*@}*/ /******************************************************************************* * HW_ENET_RSEM - Receive FIFO Section Empty Threshold ******************************************************************************/ /*! * @brief HW_ENET_RSEM - Receive FIFO Section Empty Threshold (RW) * * Reset value: 0x00000000U */ typedef union _hw_enet_rsem { uint32_t U; struct _hw_enet_rsem_bitfields { uint32_t RX_SECTION_EMPTY : 8; /*!< [7:0] Value Of The Receive FIFO * Section Empty Threshold */ uint32_t RESERVED0 : 8; /*!< [15:8] */ uint32_t STAT_SECTION_EMPTY : 5; /*!< [20:16] RX Status FIFO Section * Empty Threshold */ uint32_t RESERVED1 : 11; /*!< [31:21] */ } B; } hw_enet_rsem_t; /*! * @name Constants and macros for entire ENET_RSEM register */ /*@{*/ #define HW_ENET_RSEM_ADDR(x) ((x) + 0x194U) #define HW_ENET_RSEM(x) (*(__IO hw_enet_rsem_t *) HW_ENET_RSEM_ADDR(x)) #define HW_ENET_RSEM_RD(x) (HW_ENET_RSEM(x).U) #define HW_ENET_RSEM_WR(x, v) (HW_ENET_RSEM(x).U = (v)) #define HW_ENET_RSEM_SET(x, v) (HW_ENET_RSEM_WR(x, HW_ENET_RSEM_RD(x) | (v))) #define HW_ENET_RSEM_CLR(x, v) (HW_ENET_RSEM_WR(x, HW_ENET_RSEM_RD(x) & ~(v))) #define HW_ENET_RSEM_TOG(x, v) (HW_ENET_RSEM_WR(x, HW_ENET_RSEM_RD(x) ^ (v))) /*@}*/ /* * Constants & macros for individual ENET_RSEM bitfields */ /*! * @name Register ENET_RSEM, field RX_SECTION_EMPTY[7:0] (RW) * * Value, in 64-bit words, of the receive FIFO section empty threshold. When the * FIFO has reached this level, a pause frame will be issued. A value of 0 * disables automatic pause frame generation. When the FIFO level goes below the value * programmed in this field, an XON pause frame is issued to indicate the FIFO * congestion is cleared to the remote Ethernet client. The section-empty * threshold indications from both FIFOs are OR'ed to cause XOFF pause frame generation. */ /*@{*/ #define BP_ENET_RSEM_RX_SECTION_EMPTY (0U) /*!< Bit position for ENET_RSEM_RX_SECTION_EMPTY. */ #define BM_ENET_RSEM_RX_SECTION_EMPTY (0x000000FFU) /*!< Bit mask for ENET_RSEM_RX_SECTION_EMPTY. */ #define BS_ENET_RSEM_RX_SECTION_EMPTY (8U) /*!< Bit field size in bits for ENET_RSEM_RX_SECTION_EMPTY. */ /*! @brief Read current value of the ENET_RSEM_RX_SECTION_EMPTY field. */ #define BR_ENET_RSEM_RX_SECTION_EMPTY(x) (HW_ENET_RSEM(x).B.RX_SECTION_EMPTY) /*! @brief Format value for bitfield ENET_RSEM_RX_SECTION_EMPTY. */ #define BF_ENET_RSEM_RX_SECTION_EMPTY(v) ((uint32_t)((uint32_t)(v) << BP_ENET_RSEM_RX_SECTION_EMPTY) & BM_ENET_RSEM_RX_SECTION_EMPTY) /*! @brief Set the RX_SECTION_EMPTY field to a new value. */ #define BW_ENET_RSEM_RX_SECTION_EMPTY(x, v) (HW_ENET_RSEM_WR(x, (HW_ENET_RSEM_RD(x) & ~BM_ENET_RSEM_RX_SECTION_EMPTY) | BF_ENET_RSEM_RX_SECTION_EMPTY(v))) /*@}*/ /*! * @name Register ENET_RSEM, field STAT_SECTION_EMPTY[20:16] (RW) * * Defines number of frames in the receive FIFO, independent of its size, that * can be accepted. If the limit is reached, reception will continue normally, * however a pause frame will be triggered to indicate a possible congestion to the * remote device to avoid FIFO overflow. A value of 0 disables automatic pause * frame generation */ /*@{*/ #define BP_ENET_RSEM_STAT_SECTION_EMPTY (16U) /*!< Bit position for ENET_RSEM_STAT_SECTION_EMPTY. */ #define BM_ENET_RSEM_STAT_SECTION_EMPTY (0x001F0000U) /*!< Bit mask for ENET_RSEM_STAT_SECTION_EMPTY. */ #define BS_ENET_RSEM_STAT_SECTION_EMPTY (5U) /*!< Bit field size in bits for ENET_RSEM_STAT_SECTION_EMPTY. */ /*! @brief Read current value of the ENET_RSEM_STAT_SECTION_EMPTY field. */ #define BR_ENET_RSEM_STAT_SECTION_EMPTY(x) (HW_ENET_RSEM(x).B.STAT_SECTION_EMPTY) /*! @brief Format value for bitfield ENET_RSEM_STAT_SECTION_EMPTY. */ #define BF_ENET_RSEM_STAT_SECTION_EMPTY(v) ((uint32_t)((uint32_t)(v) << BP_ENET_RSEM_STAT_SECTION_EMPTY) & BM_ENET_RSEM_STAT_SECTION_EMPTY) /*! @brief Set the STAT_SECTION_EMPTY field to a new value. */ #define BW_ENET_RSEM_STAT_SECTION_EMPTY(x, v) (HW_ENET_RSEM_WR(x, (HW_ENET_RSEM_RD(x) & ~BM_ENET_RSEM_STAT_SECTION_EMPTY) | BF_ENET_RSEM_STAT_SECTION_EMPTY(v))) /*@}*/ /******************************************************************************* * HW_ENET_RAEM - Receive FIFO Almost Empty Threshold ******************************************************************************/ /*! * @brief HW_ENET_RAEM - Receive FIFO Almost Empty Threshold (RW) * * Reset value: 0x00000004U */ typedef union _hw_enet_raem { uint32_t U; struct _hw_enet_raem_bitfields { uint32_t RX_ALMOST_EMPTY : 8; /*!< [7:0] Value Of The Receive FIFO * Almost Empty Threshold */ uint32_t RESERVED0 : 24; /*!< [31:8] */ } B; } hw_enet_raem_t; /*! * @name Constants and macros for entire ENET_RAEM register */ /*@{*/ #define HW_ENET_RAEM_ADDR(x) ((x) + 0x198U) #define HW_ENET_RAEM(x) (*(__IO hw_enet_raem_t *) HW_ENET_RAEM_ADDR(x)) #define HW_ENET_RAEM_RD(x) (HW_ENET_RAEM(x).U) #define HW_ENET_RAEM_WR(x, v) (HW_ENET_RAEM(x).U = (v)) #define HW_ENET_RAEM_SET(x, v) (HW_ENET_RAEM_WR(x, HW_ENET_RAEM_RD(x) | (v))) #define HW_ENET_RAEM_CLR(x, v) (HW_ENET_RAEM_WR(x, HW_ENET_RAEM_RD(x) & ~(v))) #define HW_ENET_RAEM_TOG(x, v) (HW_ENET_RAEM_WR(x, HW_ENET_RAEM_RD(x) ^ (v))) /*@}*/ /* * Constants & macros for individual ENET_RAEM bitfields */ /*! * @name Register ENET_RAEM, field RX_ALMOST_EMPTY[7:0] (RW) * * Value, in 64-bit words, of the receive FIFO almost empty threshold. When the * FIFO level reaches the value programmed in this field and the end-of-frame has * not been received for the frame yet, the core receive read control stops FIFO * read (and subsequently stops transferring data to the MAC client * application). It continues to deliver the frame, if again more data than the threshold or * the end-of-frame is available in the FIFO. A minimum value of 4 should be set. */ /*@{*/ #define BP_ENET_RAEM_RX_ALMOST_EMPTY (0U) /*!< Bit position for ENET_RAEM_RX_ALMOST_EMPTY. */ #define BM_ENET_RAEM_RX_ALMOST_EMPTY (0x000000FFU) /*!< Bit mask for ENET_RAEM_RX_ALMOST_EMPTY. */ #define BS_ENET_RAEM_RX_ALMOST_EMPTY (8U) /*!< Bit field size in bits for ENET_RAEM_RX_ALMOST_EMPTY. */ /*! @brief Read current value of the ENET_RAEM_RX_ALMOST_EMPTY field. */ #define BR_ENET_RAEM_RX_ALMOST_EMPTY(x) (HW_ENET_RAEM(x).B.RX_ALMOST_EMPTY) /*! @brief Format value for bitfield ENET_RAEM_RX_ALMOST_EMPTY. */ #define BF_ENET_RAEM_RX_ALMOST_EMPTY(v) ((uint32_t)((uint32_t)(v) << BP_ENET_RAEM_RX_ALMOST_EMPTY) & BM_ENET_RAEM_RX_ALMOST_EMPTY) /*! @brief Set the RX_ALMOST_EMPTY field to a new value. */ #define BW_ENET_RAEM_RX_ALMOST_EMPTY(x, v) (HW_ENET_RAEM_WR(x, (HW_ENET_RAEM_RD(x) & ~BM_ENET_RAEM_RX_ALMOST_EMPTY) | BF_ENET_RAEM_RX_ALMOST_EMPTY(v))) /*@}*/ /******************************************************************************* * HW_ENET_RAFL - Receive FIFO Almost Full Threshold ******************************************************************************/ /*! * @brief HW_ENET_RAFL - Receive FIFO Almost Full Threshold (RW) * * Reset value: 0x00000004U */ typedef union _hw_enet_rafl { uint32_t U; struct _hw_enet_rafl_bitfields { uint32_t RX_ALMOST_FULL : 8; /*!< [7:0] Value Of The Receive FIFO * Almost Full Threshold */ uint32_t RESERVED0 : 24; /*!< [31:8] */ } B; } hw_enet_rafl_t; /*! * @name Constants and macros for entire ENET_RAFL register */ /*@{*/ #define HW_ENET_RAFL_ADDR(x) ((x) + 0x19CU) #define HW_ENET_RAFL(x) (*(__IO hw_enet_rafl_t *) HW_ENET_RAFL_ADDR(x)) #define HW_ENET_RAFL_RD(x) (HW_ENET_RAFL(x).U) #define HW_ENET_RAFL_WR(x, v) (HW_ENET_RAFL(x).U = (v)) #define HW_ENET_RAFL_SET(x, v) (HW_ENET_RAFL_WR(x, HW_ENET_RAFL_RD(x) | (v))) #define HW_ENET_RAFL_CLR(x, v) (HW_ENET_RAFL_WR(x, HW_ENET_RAFL_RD(x) & ~(v))) #define HW_ENET_RAFL_TOG(x, v) (HW_ENET_RAFL_WR(x, HW_ENET_RAFL_RD(x) ^ (v))) /*@}*/ /* * Constants & macros for individual ENET_RAFL bitfields */ /*! * @name Register ENET_RAFL, field RX_ALMOST_FULL[7:0] (RW) * * Value, in 64-bit words, of the receive FIFO almost full threshold. When the * FIFO level comes close to the maximum, so that there is no more space for at * least RX_ALMOST_FULL number of words, the MAC stops writing data in the FIFO and * truncates the received frame to avoid FIFO overflow. The corresponding error * status will be set when the frame is delivered to the application. A minimum * value of 4 should be set. */ /*@{*/ #define BP_ENET_RAFL_RX_ALMOST_FULL (0U) /*!< Bit position for ENET_RAFL_RX_ALMOST_FULL. */ #define BM_ENET_RAFL_RX_ALMOST_FULL (0x000000FFU) /*!< Bit mask for ENET_RAFL_RX_ALMOST_FULL. */ #define BS_ENET_RAFL_RX_ALMOST_FULL (8U) /*!< Bit field size in bits for ENET_RAFL_RX_ALMOST_FULL. */ /*! @brief Read current value of the ENET_RAFL_RX_ALMOST_FULL field. */ #define BR_ENET_RAFL_RX_ALMOST_FULL(x) (HW_ENET_RAFL(x).B.RX_ALMOST_FULL) /*! @brief Format value for bitfield ENET_RAFL_RX_ALMOST_FULL. */ #define BF_ENET_RAFL_RX_ALMOST_FULL(v) ((uint32_t)((uint32_t)(v) << BP_ENET_RAFL_RX_ALMOST_FULL) & BM_ENET_RAFL_RX_ALMOST_FULL) /*! @brief Set the RX_ALMOST_FULL field to a new value. */ #define BW_ENET_RAFL_RX_ALMOST_FULL(x, v) (HW_ENET_RAFL_WR(x, (HW_ENET_RAFL_RD(x) & ~BM_ENET_RAFL_RX_ALMOST_FULL) | BF_ENET_RAFL_RX_ALMOST_FULL(v))) /*@}*/ /******************************************************************************* * HW_ENET_TSEM - Transmit FIFO Section Empty Threshold ******************************************************************************/ /*! * @brief HW_ENET_TSEM - Transmit FIFO Section Empty Threshold (RW) * * Reset value: 0x00000000U */ typedef union _hw_enet_tsem { uint32_t U; struct _hw_enet_tsem_bitfields { uint32_t TX_SECTION_EMPTY : 8; /*!< [7:0] Value Of The Transmit FIFO * Section Empty Threshold */ uint32_t RESERVED0 : 24; /*!< [31:8] */ } B; } hw_enet_tsem_t; /*! * @name Constants and macros for entire ENET_TSEM register */ /*@{*/ #define HW_ENET_TSEM_ADDR(x) ((x) + 0x1A0U) #define HW_ENET_TSEM(x) (*(__IO hw_enet_tsem_t *) HW_ENET_TSEM_ADDR(x)) #define HW_ENET_TSEM_RD(x) (HW_ENET_TSEM(x).U) #define HW_ENET_TSEM_WR(x, v) (HW_ENET_TSEM(x).U = (v)) #define HW_ENET_TSEM_SET(x, v) (HW_ENET_TSEM_WR(x, HW_ENET_TSEM_RD(x) | (v))) #define HW_ENET_TSEM_CLR(x, v) (HW_ENET_TSEM_WR(x, HW_ENET_TSEM_RD(x) & ~(v))) #define HW_ENET_TSEM_TOG(x, v) (HW_ENET_TSEM_WR(x, HW_ENET_TSEM_RD(x) ^ (v))) /*@}*/ /* * Constants & macros for individual ENET_TSEM bitfields */ /*! * @name Register ENET_TSEM, field TX_SECTION_EMPTY[7:0] (RW) * * Value, in 64-bit words, of the transmit FIFO section empty threshold. See * Transmit FIFOFour programmable thresholds are available which control the core * operation. for more information. */ /*@{*/ #define BP_ENET_TSEM_TX_SECTION_EMPTY (0U) /*!< Bit position for ENET_TSEM_TX_SECTION_EMPTY. */ #define BM_ENET_TSEM_TX_SECTION_EMPTY (0x000000FFU) /*!< Bit mask for ENET_TSEM_TX_SECTION_EMPTY. */ #define BS_ENET_TSEM_TX_SECTION_EMPTY (8U) /*!< Bit field size in bits for ENET_TSEM_TX_SECTION_EMPTY. */ /*! @brief Read current value of the ENET_TSEM_TX_SECTION_EMPTY field. */ #define BR_ENET_TSEM_TX_SECTION_EMPTY(x) (HW_ENET_TSEM(x).B.TX_SECTION_EMPTY) /*! @brief Format value for bitfield ENET_TSEM_TX_SECTION_EMPTY. */ #define BF_ENET_TSEM_TX_SECTION_EMPTY(v) ((uint32_t)((uint32_t)(v) << BP_ENET_TSEM_TX_SECTION_EMPTY) & BM_ENET_TSEM_TX_SECTION_EMPTY) /*! @brief Set the TX_SECTION_EMPTY field to a new value. */ #define BW_ENET_TSEM_TX_SECTION_EMPTY(x, v) (HW_ENET_TSEM_WR(x, (HW_ENET_TSEM_RD(x) & ~BM_ENET_TSEM_TX_SECTION_EMPTY) | BF_ENET_TSEM_TX_SECTION_EMPTY(v))) /*@}*/ /******************************************************************************* * HW_ENET_TAEM - Transmit FIFO Almost Empty Threshold ******************************************************************************/ /*! * @brief HW_ENET_TAEM - Transmit FIFO Almost Empty Threshold (RW) * * Reset value: 0x00000004U */ typedef union _hw_enet_taem { uint32_t U; struct _hw_enet_taem_bitfields { uint32_t TX_ALMOST_EMPTY : 8; /*!< [7:0] Value of Transmit FIFO * Almost Empty Threshold */ uint32_t RESERVED0 : 24; /*!< [31:8] */ } B; } hw_enet_taem_t; /*! * @name Constants and macros for entire ENET_TAEM register */ /*@{*/ #define HW_ENET_TAEM_ADDR(x) ((x) + 0x1A4U) #define HW_ENET_TAEM(x) (*(__IO hw_enet_taem_t *) HW_ENET_TAEM_ADDR(x)) #define HW_ENET_TAEM_RD(x) (HW_ENET_TAEM(x).U) #define HW_ENET_TAEM_WR(x, v) (HW_ENET_TAEM(x).U = (v)) #define HW_ENET_TAEM_SET(x, v) (HW_ENET_TAEM_WR(x, HW_ENET_TAEM_RD(x) | (v))) #define HW_ENET_TAEM_CLR(x, v) (HW_ENET_TAEM_WR(x, HW_ENET_TAEM_RD(x) & ~(v))) #define HW_ENET_TAEM_TOG(x, v) (HW_ENET_TAEM_WR(x, HW_ENET_TAEM_RD(x) ^ (v))) /*@}*/ /* * Constants & macros for individual ENET_TAEM bitfields */ /*! * @name Register ENET_TAEM, field TX_ALMOST_EMPTY[7:0] (RW) * * Value, in 64-bit words, of the transmit FIFO almost empty threshold. When the * FIFO level reaches the value programmed in this field, and no end-of-frame is * available for the frame, the MAC transmit logic, to avoid FIFO underflow, * stops reading the FIFO and transmits a frame with an MII error indication. See * Transmit FIFOFour programmable thresholds are available which control the core * operation. for more information. A minimum value of 4 should be set. */ /*@{*/ #define BP_ENET_TAEM_TX_ALMOST_EMPTY (0U) /*!< Bit position for ENET_TAEM_TX_ALMOST_EMPTY. */ #define BM_ENET_TAEM_TX_ALMOST_EMPTY (0x000000FFU) /*!< Bit mask for ENET_TAEM_TX_ALMOST_EMPTY. */ #define BS_ENET_TAEM_TX_ALMOST_EMPTY (8U) /*!< Bit field size in bits for ENET_TAEM_TX_ALMOST_EMPTY. */ /*! @brief Read current value of the ENET_TAEM_TX_ALMOST_EMPTY field. */ #define BR_ENET_TAEM_TX_ALMOST_EMPTY(x) (HW_ENET_TAEM(x).B.TX_ALMOST_EMPTY) /*! @brief Format value for bitfield ENET_TAEM_TX_ALMOST_EMPTY. */ #define BF_ENET_TAEM_TX_ALMOST_EMPTY(v) ((uint32_t)((uint32_t)(v) << BP_ENET_TAEM_TX_ALMOST_EMPTY) & BM_ENET_TAEM_TX_ALMOST_EMPTY) /*! @brief Set the TX_ALMOST_EMPTY field to a new value. */ #define BW_ENET_TAEM_TX_ALMOST_EMPTY(x, v) (HW_ENET_TAEM_WR(x, (HW_ENET_TAEM_RD(x) & ~BM_ENET_TAEM_TX_ALMOST_EMPTY) | BF_ENET_TAEM_TX_ALMOST_EMPTY(v))) /*@}*/ /******************************************************************************* * HW_ENET_TAFL - Transmit FIFO Almost Full Threshold ******************************************************************************/ /*! * @brief HW_ENET_TAFL - Transmit FIFO Almost Full Threshold (RW) * * Reset value: 0x00000008U */ typedef union _hw_enet_tafl { uint32_t U; struct _hw_enet_tafl_bitfields { uint32_t TX_ALMOST_FULL : 8; /*!< [7:0] Value Of The Transmit FIFO * Almost Full Threshold */ uint32_t RESERVED0 : 24; /*!< [31:8] */ } B; } hw_enet_tafl_t; /*! * @name Constants and macros for entire ENET_TAFL register */ /*@{*/ #define HW_ENET_TAFL_ADDR(x) ((x) + 0x1A8U) #define HW_ENET_TAFL(x) (*(__IO hw_enet_tafl_t *) HW_ENET_TAFL_ADDR(x)) #define HW_ENET_TAFL_RD(x) (HW_ENET_TAFL(x).U) #define HW_ENET_TAFL_WR(x, v) (HW_ENET_TAFL(x).U = (v)) #define HW_ENET_TAFL_SET(x, v) (HW_ENET_TAFL_WR(x, HW_ENET_TAFL_RD(x) | (v))) #define HW_ENET_TAFL_CLR(x, v) (HW_ENET_TAFL_WR(x, HW_ENET_TAFL_RD(x) & ~(v))) #define HW_ENET_TAFL_TOG(x, v) (HW_ENET_TAFL_WR(x, HW_ENET_TAFL_RD(x) ^ (v))) /*@}*/ /* * Constants & macros for individual ENET_TAFL bitfields */ /*! * @name Register ENET_TAFL, field TX_ALMOST_FULL[7:0] (RW) * * Value, in 64-bit words, of the transmit FIFO almost full threshold. A minimum * value of six is required . A recommended value of at least 8 should be set * allowing a latency of two clock cycles to the application. If more latency is * required the value can be increased as necessary (latency = TAFL - 5). When the * FIFO level comes close to the maximum, so that there is no more space for at * least TX_ALMOST_FULL number of words, the pin ff_tx_rdy is deasserted. If the * application does not react on this signal, the FIFO write control logic, to * avoid FIFO overflow, truncates the current frame and sets the error status. As a * result, the frame will be transmitted with an GMII/MII error indication. See * Transmit FIFOFour programmable thresholds are available which control the core * operation. for more information. A FIFO overflow is a fatal error and requires * a global reset on the transmit datapath or at least deassertion of ETHEREN. */ /*@{*/ #define BP_ENET_TAFL_TX_ALMOST_FULL (0U) /*!< Bit position for ENET_TAFL_TX_ALMOST_FULL. */ #define BM_ENET_TAFL_TX_ALMOST_FULL (0x000000FFU) /*!< Bit mask for ENET_TAFL_TX_ALMOST_FULL. */ #define BS_ENET_TAFL_TX_ALMOST_FULL (8U) /*!< Bit field size in bits for ENET_TAFL_TX_ALMOST_FULL. */ /*! @brief Read current value of the ENET_TAFL_TX_ALMOST_FULL field. */ #define BR_ENET_TAFL_TX_ALMOST_FULL(x) (HW_ENET_TAFL(x).B.TX_ALMOST_FULL) /*! @brief Format value for bitfield ENET_TAFL_TX_ALMOST_FULL. */ #define BF_ENET_TAFL_TX_ALMOST_FULL(v) ((uint32_t)((uint32_t)(v) << BP_ENET_TAFL_TX_ALMOST_FULL) & BM_ENET_TAFL_TX_ALMOST_FULL) /*! @brief Set the TX_ALMOST_FULL field to a new value. */ #define BW_ENET_TAFL_TX_ALMOST_FULL(x, v) (HW_ENET_TAFL_WR(x, (HW_ENET_TAFL_RD(x) & ~BM_ENET_TAFL_TX_ALMOST_FULL) | BF_ENET_TAFL_TX_ALMOST_FULL(v))) /*@}*/ /******************************************************************************* * HW_ENET_TIPG - Transmit Inter-Packet Gap ******************************************************************************/ /*! * @brief HW_ENET_TIPG - Transmit Inter-Packet Gap (RW) * * Reset value: 0x0000000CU */ typedef union _hw_enet_tipg { uint32_t U; struct _hw_enet_tipg_bitfields { uint32_t IPG : 5; /*!< [4:0] Transmit Inter-Packet Gap */ uint32_t RESERVED0 : 27; /*!< [31:5] */ } B; } hw_enet_tipg_t; /*! * @name Constants and macros for entire ENET_TIPG register */ /*@{*/ #define HW_ENET_TIPG_ADDR(x) ((x) + 0x1ACU) #define HW_ENET_TIPG(x) (*(__IO hw_enet_tipg_t *) HW_ENET_TIPG_ADDR(x)) #define HW_ENET_TIPG_RD(x) (HW_ENET_TIPG(x).U) #define HW_ENET_TIPG_WR(x, v) (HW_ENET_TIPG(x).U = (v)) #define HW_ENET_TIPG_SET(x, v) (HW_ENET_TIPG_WR(x, HW_ENET_TIPG_RD(x) | (v))) #define HW_ENET_TIPG_CLR(x, v) (HW_ENET_TIPG_WR(x, HW_ENET_TIPG_RD(x) & ~(v))) #define HW_ENET_TIPG_TOG(x, v) (HW_ENET_TIPG_WR(x, HW_ENET_TIPG_RD(x) ^ (v))) /*@}*/ /* * Constants & macros for individual ENET_TIPG bitfields */ /*! * @name Register ENET_TIPG, field IPG[4:0] (RW) * * Indicates the IPG, in bytes, between transmitted frames. Valid values range * from 8 to 27. If value is less than 8, the IPG is 8. If value is greater than * 27, the IPG is 27. */ /*@{*/ #define BP_ENET_TIPG_IPG (0U) /*!< Bit position for ENET_TIPG_IPG. */ #define BM_ENET_TIPG_IPG (0x0000001FU) /*!< Bit mask for ENET_TIPG_IPG. */ #define BS_ENET_TIPG_IPG (5U) /*!< Bit field size in bits for ENET_TIPG_IPG. */ /*! @brief Read current value of the ENET_TIPG_IPG field. */ #define BR_ENET_TIPG_IPG(x) (HW_ENET_TIPG(x).B.IPG) /*! @brief Format value for bitfield ENET_TIPG_IPG. */ #define BF_ENET_TIPG_IPG(v) ((uint32_t)((uint32_t)(v) << BP_ENET_TIPG_IPG) & BM_ENET_TIPG_IPG) /*! @brief Set the IPG field to a new value. */ #define BW_ENET_TIPG_IPG(x, v) (HW_ENET_TIPG_WR(x, (HW_ENET_TIPG_RD(x) & ~BM_ENET_TIPG_IPG) | BF_ENET_TIPG_IPG(v))) /*@}*/ /******************************************************************************* * HW_ENET_FTRL - Frame Truncation Length ******************************************************************************/ /*! * @brief HW_ENET_FTRL - Frame Truncation Length (RW) * * Reset value: 0x000007FFU */ typedef union _hw_enet_ftrl { uint32_t U; struct _hw_enet_ftrl_bitfields { uint32_t TRUNC_FL : 14; /*!< [13:0] Frame Truncation Length */ uint32_t RESERVED0 : 18; /*!< [31:14] */ } B; } hw_enet_ftrl_t; /*! * @name Constants and macros for entire ENET_FTRL register */ /*@{*/ #define HW_ENET_FTRL_ADDR(x) ((x) + 0x1B0U) #define HW_ENET_FTRL(x) (*(__IO hw_enet_ftrl_t *) HW_ENET_FTRL_ADDR(x)) #define HW_ENET_FTRL_RD(x) (HW_ENET_FTRL(x).U) #define HW_ENET_FTRL_WR(x, v) (HW_ENET_FTRL(x).U = (v)) #define HW_ENET_FTRL_SET(x, v) (HW_ENET_FTRL_WR(x, HW_ENET_FTRL_RD(x) | (v))) #define HW_ENET_FTRL_CLR(x, v) (HW_ENET_FTRL_WR(x, HW_ENET_FTRL_RD(x) & ~(v))) #define HW_ENET_FTRL_TOG(x, v) (HW_ENET_FTRL_WR(x, HW_ENET_FTRL_RD(x) ^ (v))) /*@}*/ /* * Constants & macros for individual ENET_FTRL bitfields */ /*! * @name Register ENET_FTRL, field TRUNC_FL[13:0] (RW) * * Indicates the value a receive frame is truncated, if it is greater than this * value. Must be greater than or equal to RCR[MAX_FL]. Truncation happens at * TRUNC_FL. However, when truncation occurs, the application (FIFO) may receive * less data, guaranteeing that it never receives more than the set limit. */ /*@{*/ #define BP_ENET_FTRL_TRUNC_FL (0U) /*!< Bit position for ENET_FTRL_TRUNC_FL. */ #define BM_ENET_FTRL_TRUNC_FL (0x00003FFFU) /*!< Bit mask for ENET_FTRL_TRUNC_FL. */ #define BS_ENET_FTRL_TRUNC_FL (14U) /*!< Bit field size in bits for ENET_FTRL_TRUNC_FL. */ /*! @brief Read current value of the ENET_FTRL_TRUNC_FL field. */ #define BR_ENET_FTRL_TRUNC_FL(x) (HW_ENET_FTRL(x).B.TRUNC_FL) /*! @brief Format value for bitfield ENET_FTRL_TRUNC_FL. */ #define BF_ENET_FTRL_TRUNC_FL(v) ((uint32_t)((uint32_t)(v) << BP_ENET_FTRL_TRUNC_FL) & BM_ENET_FTRL_TRUNC_FL) /*! @brief Set the TRUNC_FL field to a new value. */ #define BW_ENET_FTRL_TRUNC_FL(x, v) (HW_ENET_FTRL_WR(x, (HW_ENET_FTRL_RD(x) & ~BM_ENET_FTRL_TRUNC_FL) | BF_ENET_FTRL_TRUNC_FL(v))) /*@}*/ /******************************************************************************* * HW_ENET_TACC - Transmit Accelerator Function Configuration ******************************************************************************/ /*! * @brief HW_ENET_TACC - Transmit Accelerator Function Configuration (RW) * * Reset value: 0x00000000U * * TACC controls accelerator actions when sending frames. The register can be * changed before or after each frame, but it must remain unmodified during frame * writes into the transmit FIFO. The TFWR[STRFWD] field must be set to use the * checksum feature. */ typedef union _hw_enet_tacc { uint32_t U; struct _hw_enet_tacc_bitfields { uint32_t SHIFT16 : 1; /*!< [0] TX FIFO Shift-16 */ uint32_t RESERVED0 : 2; /*!< [2:1] */ uint32_t IPCHK : 1; /*!< [3] */ uint32_t PROCHK : 1; /*!< [4] */ uint32_t RESERVED1 : 27; /*!< [31:5] */ } B; } hw_enet_tacc_t; /*! * @name Constants and macros for entire ENET_TACC register */ /*@{*/ #define HW_ENET_TACC_ADDR(x) ((x) + 0x1C0U) #define HW_ENET_TACC(x) (*(__IO hw_enet_tacc_t *) HW_ENET_TACC_ADDR(x)) #define HW_ENET_TACC_RD(x) (HW_ENET_TACC(x).U) #define HW_ENET_TACC_WR(x, v) (HW_ENET_TACC(x).U = (v)) #define HW_ENET_TACC_SET(x, v) (HW_ENET_TACC_WR(x, HW_ENET_TACC_RD(x) | (v))) #define HW_ENET_TACC_CLR(x, v) (HW_ENET_TACC_WR(x, HW_ENET_TACC_RD(x) & ~(v))) #define HW_ENET_TACC_TOG(x, v) (HW_ENET_TACC_WR(x, HW_ENET_TACC_RD(x) ^ (v))) /*@}*/ /* * Constants & macros for individual ENET_TACC bitfields */ /*! * @name Register ENET_TACC, field SHIFT16[0] (RW) * * Values: * - 0 - Disabled. * - 1 - Indicates to the transmit data FIFO that the written frames contain two * additional octets before the frame data. This means the actual frame * begins at bit 16 of the first word written into the FIFO. This function allows * putting the frame payload on a 32-bit boundary in memory, as the 14-byte * Ethernet header is extended to a 16-byte header. */ /*@{*/ #define BP_ENET_TACC_SHIFT16 (0U) /*!< Bit position for ENET_TACC_SHIFT16. */ #define BM_ENET_TACC_SHIFT16 (0x00000001U) /*!< Bit mask for ENET_TACC_SHIFT16. */ #define BS_ENET_TACC_SHIFT16 (1U) /*!< Bit field size in bits for ENET_TACC_SHIFT16. */ /*! @brief Read current value of the ENET_TACC_SHIFT16 field. */ #define BR_ENET_TACC_SHIFT16(x) (BITBAND_ACCESS32(HW_ENET_TACC_ADDR(x), BP_ENET_TACC_SHIFT16)) /*! @brief Format value for bitfield ENET_TACC_SHIFT16. */ #define BF_ENET_TACC_SHIFT16(v) ((uint32_t)((uint32_t)(v) << BP_ENET_TACC_SHIFT16) & BM_ENET_TACC_SHIFT16) /*! @brief Set the SHIFT16 field to a new value. */ #define BW_ENET_TACC_SHIFT16(x, v) (BITBAND_ACCESS32(HW_ENET_TACC_ADDR(x), BP_ENET_TACC_SHIFT16) = (v)) /*@}*/ /*! * @name Register ENET_TACC, field IPCHK[3] (RW) * * Enables insertion of IP header checksum. * * Values: * - 0 - Checksum is not inserted. * - 1 - If an IP frame is transmitted, the checksum is inserted automatically. * The IP header checksum field must be cleared. If a non-IP frame is * transmitted the frame is not modified. */ /*@{*/ #define BP_ENET_TACC_IPCHK (3U) /*!< Bit position for ENET_TACC_IPCHK. */ #define BM_ENET_TACC_IPCHK (0x00000008U) /*!< Bit mask for ENET_TACC_IPCHK. */ #define BS_ENET_TACC_IPCHK (1U) /*!< Bit field size in bits for ENET_TACC_IPCHK. */ /*! @brief Read current value of the ENET_TACC_IPCHK field. */ #define BR_ENET_TACC_IPCHK(x) (BITBAND_ACCESS32(HW_ENET_TACC_ADDR(x), BP_ENET_TACC_IPCHK)) /*! @brief Format value for bitfield ENET_TACC_IPCHK. */ #define BF_ENET_TACC_IPCHK(v) ((uint32_t)((uint32_t)(v) << BP_ENET_TACC_IPCHK) & BM_ENET_TACC_IPCHK) /*! @brief Set the IPCHK field to a new value. */ #define BW_ENET_TACC_IPCHK(x, v) (BITBAND_ACCESS32(HW_ENET_TACC_ADDR(x), BP_ENET_TACC_IPCHK) = (v)) /*@}*/ /*! * @name Register ENET_TACC, field PROCHK[4] (RW) * * Enables insertion of protocol checksum. * * Values: * - 0 - Checksum not inserted. * - 1 - If an IP frame with a known protocol is transmitted, the checksum is * inserted automatically into the frame. The checksum field must be cleared. * The other frames are not modified. */ /*@{*/ #define BP_ENET_TACC_PROCHK (4U) /*!< Bit position for ENET_TACC_PROCHK. */ #define BM_ENET_TACC_PROCHK (0x00000010U) /*!< Bit mask for ENET_TACC_PROCHK. */ #define BS_ENET_TACC_PROCHK (1U) /*!< Bit field size in bits for ENET_TACC_PROCHK. */ /*! @brief Read current value of the ENET_TACC_PROCHK field. */ #define BR_ENET_TACC_PROCHK(x) (BITBAND_ACCESS32(HW_ENET_TACC_ADDR(x), BP_ENET_TACC_PROCHK)) /*! @brief Format value for bitfield ENET_TACC_PROCHK. */ #define BF_ENET_TACC_PROCHK(v) ((uint32_t)((uint32_t)(v) << BP_ENET_TACC_PROCHK) & BM_ENET_TACC_PROCHK) /*! @brief Set the PROCHK field to a new value. */ #define BW_ENET_TACC_PROCHK(x, v) (BITBAND_ACCESS32(HW_ENET_TACC_ADDR(x), BP_ENET_TACC_PROCHK) = (v)) /*@}*/ /******************************************************************************* * HW_ENET_RACC - Receive Accelerator Function Configuration ******************************************************************************/ /*! * @brief HW_ENET_RACC - Receive Accelerator Function Configuration (RW) * * Reset value: 0x00000000U */ typedef union _hw_enet_racc { uint32_t U; struct _hw_enet_racc_bitfields { uint32_t PADREM : 1; /*!< [0] Enable Padding Removal For Short IP * Frames */ uint32_t IPDIS : 1; /*!< [1] Enable Discard Of Frames With Wrong IPv4 * Header Checksum */ uint32_t PRODIS : 1; /*!< [2] Enable Discard Of Frames With Wrong * Protocol Checksum */ uint32_t RESERVED0 : 3; /*!< [5:3] */ uint32_t LINEDIS : 1; /*!< [6] Enable Discard Of Frames With MAC * Layer Errors */ uint32_t SHIFT16 : 1; /*!< [7] RX FIFO Shift-16 */ uint32_t RESERVED1 : 24; /*!< [31:8] */ } B; } hw_enet_racc_t; /*! * @name Constants and macros for entire ENET_RACC register */ /*@{*/ #define HW_ENET_RACC_ADDR(x) ((x) + 0x1C4U) #define HW_ENET_RACC(x) (*(__IO hw_enet_racc_t *) HW_ENET_RACC_ADDR(x)) #define HW_ENET_RACC_RD(x) (HW_ENET_RACC(x).U) #define HW_ENET_RACC_WR(x, v) (HW_ENET_RACC(x).U = (v)) #define HW_ENET_RACC_SET(x, v) (HW_ENET_RACC_WR(x, HW_ENET_RACC_RD(x) | (v))) #define HW_ENET_RACC_CLR(x, v) (HW_ENET_RACC_WR(x, HW_ENET_RACC_RD(x) & ~(v))) #define HW_ENET_RACC_TOG(x, v) (HW_ENET_RACC_WR(x, HW_ENET_RACC_RD(x) ^ (v))) /*@}*/ /* * Constants & macros for individual ENET_RACC bitfields */ /*! * @name Register ENET_RACC, field PADREM[0] (RW) * * Values: * - 0 - Padding not removed. * - 1 - Any bytes following the IP payload section of the frame are removed * from the frame. */ /*@{*/ #define BP_ENET_RACC_PADREM (0U) /*!< Bit position for ENET_RACC_PADREM. */ #define BM_ENET_RACC_PADREM (0x00000001U) /*!< Bit mask for ENET_RACC_PADREM. */ #define BS_ENET_RACC_PADREM (1U) /*!< Bit field size in bits for ENET_RACC_PADREM. */ /*! @brief Read current value of the ENET_RACC_PADREM field. */ #define BR_ENET_RACC_PADREM(x) (BITBAND_ACCESS32(HW_ENET_RACC_ADDR(x), BP_ENET_RACC_PADREM)) /*! @brief Format value for bitfield ENET_RACC_PADREM. */ #define BF_ENET_RACC_PADREM(v) ((uint32_t)((uint32_t)(v) << BP_ENET_RACC_PADREM) & BM_ENET_RACC_PADREM) /*! @brief Set the PADREM field to a new value. */ #define BW_ENET_RACC_PADREM(x, v) (BITBAND_ACCESS32(HW_ENET_RACC_ADDR(x), BP_ENET_RACC_PADREM) = (v)) /*@}*/ /*! * @name Register ENET_RACC, field IPDIS[1] (RW) * * Values: * - 0 - Frames with wrong IPv4 header checksum are not discarded. * - 1 - If an IPv4 frame is received with a mismatching header checksum, the * frame is discarded. IPv6 has no header checksum and is not affected by this * setting. Discarding is only available when the RX FIFO operates in store * and forward mode (RSFL cleared). */ /*@{*/ #define BP_ENET_RACC_IPDIS (1U) /*!< Bit position for ENET_RACC_IPDIS. */ #define BM_ENET_RACC_IPDIS (0x00000002U) /*!< Bit mask for ENET_RACC_IPDIS. */ #define BS_ENET_RACC_IPDIS (1U) /*!< Bit field size in bits for ENET_RACC_IPDIS. */ /*! @brief Read current value of the ENET_RACC_IPDIS field. */ #define BR_ENET_RACC_IPDIS(x) (BITBAND_ACCESS32(HW_ENET_RACC_ADDR(x), BP_ENET_RACC_IPDIS)) /*! @brief Format value for bitfield ENET_RACC_IPDIS. */ #define BF_ENET_RACC_IPDIS(v) ((uint32_t)((uint32_t)(v) << BP_ENET_RACC_IPDIS) & BM_ENET_RACC_IPDIS) /*! @brief Set the IPDIS field to a new value. */ #define BW_ENET_RACC_IPDIS(x, v) (BITBAND_ACCESS32(HW_ENET_RACC_ADDR(x), BP_ENET_RACC_IPDIS) = (v)) /*@}*/ /*! * @name Register ENET_RACC, field PRODIS[2] (RW) * * Values: * - 0 - Frames with wrong checksum are not discarded. * - 1 - If a TCP/IP, UDP/IP, or ICMP/IP frame is received that has a wrong TCP, * UDP, or ICMP checksum, the frame is discarded. Discarding is only * available when the RX FIFO operates in store and forward mode (RSFL cleared). */ /*@{*/ #define BP_ENET_RACC_PRODIS (2U) /*!< Bit position for ENET_RACC_PRODIS. */ #define BM_ENET_RACC_PRODIS (0x00000004U) /*!< Bit mask for ENET_RACC_PRODIS. */ #define BS_ENET_RACC_PRODIS (1U) /*!< Bit field size in bits for ENET_RACC_PRODIS. */ /*! @brief Read current value of the ENET_RACC_PRODIS field. */ #define BR_ENET_RACC_PRODIS(x) (BITBAND_ACCESS32(HW_ENET_RACC_ADDR(x), BP_ENET_RACC_PRODIS)) /*! @brief Format value for bitfield ENET_RACC_PRODIS. */ #define BF_ENET_RACC_PRODIS(v) ((uint32_t)((uint32_t)(v) << BP_ENET_RACC_PRODIS) & BM_ENET_RACC_PRODIS) /*! @brief Set the PRODIS field to a new value. */ #define BW_ENET_RACC_PRODIS(x, v) (BITBAND_ACCESS32(HW_ENET_RACC_ADDR(x), BP_ENET_RACC_PRODIS) = (v)) /*@}*/ /*! * @name Register ENET_RACC, field LINEDIS[6] (RW) * * Values: * - 0 - Frames with errors are not discarded. * - 1 - Any frame received with a CRC, length, or PHY error is automatically * discarded and not forwarded to the user application interface. */ /*@{*/ #define BP_ENET_RACC_LINEDIS (6U) /*!< Bit position for ENET_RACC_LINEDIS. */ #define BM_ENET_RACC_LINEDIS (0x00000040U) /*!< Bit mask for ENET_RACC_LINEDIS. */ #define BS_ENET_RACC_LINEDIS (1U) /*!< Bit field size in bits for ENET_RACC_LINEDIS. */ /*! @brief Read current value of the ENET_RACC_LINEDIS field. */ #define BR_ENET_RACC_LINEDIS(x) (BITBAND_ACCESS32(HW_ENET_RACC_ADDR(x), BP_ENET_RACC_LINEDIS)) /*! @brief Format value for bitfield ENET_RACC_LINEDIS. */ #define BF_ENET_RACC_LINEDIS(v) ((uint32_t)((uint32_t)(v) << BP_ENET_RACC_LINEDIS) & BM_ENET_RACC_LINEDIS) /*! @brief Set the LINEDIS field to a new value. */ #define BW_ENET_RACC_LINEDIS(x, v) (BITBAND_ACCESS32(HW_ENET_RACC_ADDR(x), BP_ENET_RACC_LINEDIS) = (v)) /*@}*/ /*! * @name Register ENET_RACC, field SHIFT16[7] (RW) * * When this field is set, the actual frame data starts at bit 16 of the first * word read from the RX FIFO aligning the Ethernet payload on a 32-bit boundary. * This function only affects the FIFO storage and has no influence on the * statistics, which use the actual length of the frame received. * * Values: * - 0 - Disabled. * - 1 - Instructs the MAC to write two additional bytes in front of each frame * received into the RX FIFO. */ /*@{*/ #define BP_ENET_RACC_SHIFT16 (7U) /*!< Bit position for ENET_RACC_SHIFT16. */ #define BM_ENET_RACC_SHIFT16 (0x00000080U) /*!< Bit mask for ENET_RACC_SHIFT16. */ #define BS_ENET_RACC_SHIFT16 (1U) /*!< Bit field size in bits for ENET_RACC_SHIFT16. */ /*! @brief Read current value of the ENET_RACC_SHIFT16 field. */ #define BR_ENET_RACC_SHIFT16(x) (BITBAND_ACCESS32(HW_ENET_RACC_ADDR(x), BP_ENET_RACC_SHIFT16)) /*! @brief Format value for bitfield ENET_RACC_SHIFT16. */ #define BF_ENET_RACC_SHIFT16(v) ((uint32_t)((uint32_t)(v) << BP_ENET_RACC_SHIFT16) & BM_ENET_RACC_SHIFT16) /*! @brief Set the SHIFT16 field to a new value. */ #define BW_ENET_RACC_SHIFT16(x, v) (BITBAND_ACCESS32(HW_ENET_RACC_ADDR(x), BP_ENET_RACC_SHIFT16) = (v)) /*@}*/ /******************************************************************************* * HW_ENET_RMON_T_PACKETS - Tx Packet Count Statistic Register ******************************************************************************/ /*! * @brief HW_ENET_RMON_T_PACKETS - Tx Packet Count Statistic Register (RO) * * Reset value: 0x00000000U */ typedef union _hw_enet_rmon_t_packets { uint32_t U; struct _hw_enet_rmon_t_packets_bitfields { uint32_t TXPKTS : 16; /*!< [15:0] Packet count */ uint32_t RESERVED0 : 16; /*!< [31:16] */ } B; } hw_enet_rmon_t_packets_t; /*! * @name Constants and macros for entire ENET_RMON_T_PACKETS register */ /*@{*/ #define HW_ENET_RMON_T_PACKETS_ADDR(x) ((x) + 0x204U) #define HW_ENET_RMON_T_PACKETS(x) (*(__I hw_enet_rmon_t_packets_t *) HW_ENET_RMON_T_PACKETS_ADDR(x)) #define HW_ENET_RMON_T_PACKETS_RD(x) (HW_ENET_RMON_T_PACKETS(x).U) /*@}*/ /* * Constants & macros for individual ENET_RMON_T_PACKETS bitfields */ /*! * @name Register ENET_RMON_T_PACKETS, field TXPKTS[15:0] (RO) */ /*@{*/ #define BP_ENET_RMON_T_PACKETS_TXPKTS (0U) /*!< Bit position for ENET_RMON_T_PACKETS_TXPKTS. */ #define BM_ENET_RMON_T_PACKETS_TXPKTS (0x0000FFFFU) /*!< Bit mask for ENET_RMON_T_PACKETS_TXPKTS. */ #define BS_ENET_RMON_T_PACKETS_TXPKTS (16U) /*!< Bit field size in bits for ENET_RMON_T_PACKETS_TXPKTS. */ /*! @brief Read current value of the ENET_RMON_T_PACKETS_TXPKTS field. */ #define BR_ENET_RMON_T_PACKETS_TXPKTS(x) (HW_ENET_RMON_T_PACKETS(x).B.TXPKTS) /*@}*/ /******************************************************************************* * HW_ENET_RMON_T_BC_PKT - Tx Broadcast Packets Statistic Register ******************************************************************************/ /*! * @brief HW_ENET_RMON_T_BC_PKT - Tx Broadcast Packets Statistic Register (RO) * * Reset value: 0x00000000U * * RMON Tx Broadcast Packets */ typedef union _hw_enet_rmon_t_bc_pkt { uint32_t U; struct _hw_enet_rmon_t_bc_pkt_bitfields { uint32_t TXPKTS : 16; /*!< [15:0] Broadcast packets */ uint32_t RESERVED0 : 16; /*!< [31:16] */ } B; } hw_enet_rmon_t_bc_pkt_t; /*! * @name Constants and macros for entire ENET_RMON_T_BC_PKT register */ /*@{*/ #define HW_ENET_RMON_T_BC_PKT_ADDR(x) ((x) + 0x208U) #define HW_ENET_RMON_T_BC_PKT(x) (*(__I hw_enet_rmon_t_bc_pkt_t *) HW_ENET_RMON_T_BC_PKT_ADDR(x)) #define HW_ENET_RMON_T_BC_PKT_RD(x) (HW_ENET_RMON_T_BC_PKT(x).U) /*@}*/ /* * Constants & macros for individual ENET_RMON_T_BC_PKT bitfields */ /*! * @name Register ENET_RMON_T_BC_PKT, field TXPKTS[15:0] (RO) */ /*@{*/ #define BP_ENET_RMON_T_BC_PKT_TXPKTS (0U) /*!< Bit position for ENET_RMON_T_BC_PKT_TXPKTS. */ #define BM_ENET_RMON_T_BC_PKT_TXPKTS (0x0000FFFFU) /*!< Bit mask for ENET_RMON_T_BC_PKT_TXPKTS. */ #define BS_ENET_RMON_T_BC_PKT_TXPKTS (16U) /*!< Bit field size in bits for ENET_RMON_T_BC_PKT_TXPKTS. */ /*! @brief Read current value of the ENET_RMON_T_BC_PKT_TXPKTS field. */ #define BR_ENET_RMON_T_BC_PKT_TXPKTS(x) (HW_ENET_RMON_T_BC_PKT(x).B.TXPKTS) /*@}*/ /******************************************************************************* * HW_ENET_RMON_T_MC_PKT - Tx Multicast Packets Statistic Register ******************************************************************************/ /*! * @brief HW_ENET_RMON_T_MC_PKT - Tx Multicast Packets Statistic Register (RO) * * Reset value: 0x00000000U */ typedef union _hw_enet_rmon_t_mc_pkt { uint32_t U; struct _hw_enet_rmon_t_mc_pkt_bitfields { uint32_t TXPKTS : 16; /*!< [15:0] Multicast packets */ uint32_t RESERVED0 : 16; /*!< [31:16] */ } B; } hw_enet_rmon_t_mc_pkt_t; /*! * @name Constants and macros for entire ENET_RMON_T_MC_PKT register */ /*@{*/ #define HW_ENET_RMON_T_MC_PKT_ADDR(x) ((x) + 0x20CU) #define HW_ENET_RMON_T_MC_PKT(x) (*(__I hw_enet_rmon_t_mc_pkt_t *) HW_ENET_RMON_T_MC_PKT_ADDR(x)) #define HW_ENET_RMON_T_MC_PKT_RD(x) (HW_ENET_RMON_T_MC_PKT(x).U) /*@}*/ /* * Constants & macros for individual ENET_RMON_T_MC_PKT bitfields */ /*! * @name Register ENET_RMON_T_MC_PKT, field TXPKTS[15:0] (RO) */ /*@{*/ #define BP_ENET_RMON_T_MC_PKT_TXPKTS (0U) /*!< Bit position for ENET_RMON_T_MC_PKT_TXPKTS. */ #define BM_ENET_RMON_T_MC_PKT_TXPKTS (0x0000FFFFU) /*!< Bit mask for ENET_RMON_T_MC_PKT_TXPKTS. */ #define BS_ENET_RMON_T_MC_PKT_TXPKTS (16U) /*!< Bit field size in bits for ENET_RMON_T_MC_PKT_TXPKTS. */ /*! @brief Read current value of the ENET_RMON_T_MC_PKT_TXPKTS field. */ #define BR_ENET_RMON_T_MC_PKT_TXPKTS(x) (HW_ENET_RMON_T_MC_PKT(x).B.TXPKTS) /*@}*/ /******************************************************************************* * HW_ENET_RMON_T_CRC_ALIGN - Tx Packets with CRC/Align Error Statistic Register ******************************************************************************/ /*! * @brief HW_ENET_RMON_T_CRC_ALIGN - Tx Packets with CRC/Align Error Statistic Register (RO) * * Reset value: 0x00000000U */ typedef union _hw_enet_rmon_t_crc_align { uint32_t U; struct _hw_enet_rmon_t_crc_align_bitfields { uint32_t TXPKTS : 16; /*!< [15:0] Packets with CRC/align error */ uint32_t RESERVED0 : 16; /*!< [31:16] */ } B; } hw_enet_rmon_t_crc_align_t; /*! * @name Constants and macros for entire ENET_RMON_T_CRC_ALIGN register */ /*@{*/ #define HW_ENET_RMON_T_CRC_ALIGN_ADDR(x) ((x) + 0x210U) #define HW_ENET_RMON_T_CRC_ALIGN(x) (*(__I hw_enet_rmon_t_crc_align_t *) HW_ENET_RMON_T_CRC_ALIGN_ADDR(x)) #define HW_ENET_RMON_T_CRC_ALIGN_RD(x) (HW_ENET_RMON_T_CRC_ALIGN(x).U) /*@}*/ /* * Constants & macros for individual ENET_RMON_T_CRC_ALIGN bitfields */ /*! * @name Register ENET_RMON_T_CRC_ALIGN, field TXPKTS[15:0] (RO) */ /*@{*/ #define BP_ENET_RMON_T_CRC_ALIGN_TXPKTS (0U) /*!< Bit position for ENET_RMON_T_CRC_ALIGN_TXPKTS. */ #define BM_ENET_RMON_T_CRC_ALIGN_TXPKTS (0x0000FFFFU) /*!< Bit mask for ENET_RMON_T_CRC_ALIGN_TXPKTS. */ #define BS_ENET_RMON_T_CRC_ALIGN_TXPKTS (16U) /*!< Bit field size in bits for ENET_RMON_T_CRC_ALIGN_TXPKTS. */ /*! @brief Read current value of the ENET_RMON_T_CRC_ALIGN_TXPKTS field. */ #define BR_ENET_RMON_T_CRC_ALIGN_TXPKTS(x) (HW_ENET_RMON_T_CRC_ALIGN(x).B.TXPKTS) /*@}*/ /******************************************************************************* * HW_ENET_RMON_T_UNDERSIZE - Tx Packets Less Than Bytes and Good CRC Statistic Register ******************************************************************************/ /*! * @brief HW_ENET_RMON_T_UNDERSIZE - Tx Packets Less Than Bytes and Good CRC Statistic Register (RO) * * Reset value: 0x00000000U */ typedef union _hw_enet_rmon_t_undersize { uint32_t U; struct _hw_enet_rmon_t_undersize_bitfields { uint32_t TXPKTS : 16; /*!< [15:0] Packet count */ uint32_t RESERVED0 : 16; /*!< [31:16] */ } B; } hw_enet_rmon_t_undersize_t; /*! * @name Constants and macros for entire ENET_RMON_T_UNDERSIZE register */ /*@{*/ #define HW_ENET_RMON_T_UNDERSIZE_ADDR(x) ((x) + 0x214U) #define HW_ENET_RMON_T_UNDERSIZE(x) (*(__I hw_enet_rmon_t_undersize_t *) HW_ENET_RMON_T_UNDERSIZE_ADDR(x)) #define HW_ENET_RMON_T_UNDERSIZE_RD(x) (HW_ENET_RMON_T_UNDERSIZE(x).U) /*@}*/ /* * Constants & macros for individual ENET_RMON_T_UNDERSIZE bitfields */ /*! * @name Register ENET_RMON_T_UNDERSIZE, field TXPKTS[15:0] (RO) */ /*@{*/ #define BP_ENET_RMON_T_UNDERSIZE_TXPKTS (0U) /*!< Bit position for ENET_RMON_T_UNDERSIZE_TXPKTS. */ #define BM_ENET_RMON_T_UNDERSIZE_TXPKTS (0x0000FFFFU) /*!< Bit mask for ENET_RMON_T_UNDERSIZE_TXPKTS. */ #define BS_ENET_RMON_T_UNDERSIZE_TXPKTS (16U) /*!< Bit field size in bits for ENET_RMON_T_UNDERSIZE_TXPKTS. */ /*! @brief Read current value of the ENET_RMON_T_UNDERSIZE_TXPKTS field. */ #define BR_ENET_RMON_T_UNDERSIZE_TXPKTS(x) (HW_ENET_RMON_T_UNDERSIZE(x).B.TXPKTS) /*@}*/ /******************************************************************************* * HW_ENET_RMON_T_OVERSIZE - Tx Packets GT MAX_FL bytes and Good CRC Statistic Register ******************************************************************************/ /*! * @brief HW_ENET_RMON_T_OVERSIZE - Tx Packets GT MAX_FL bytes and Good CRC Statistic Register (RO) * * Reset value: 0x00000000U */ typedef union _hw_enet_rmon_t_oversize { uint32_t U; struct _hw_enet_rmon_t_oversize_bitfields { uint32_t TXPKTS : 16; /*!< [15:0] Packet count */ uint32_t RESERVED0 : 16; /*!< [31:16] */ } B; } hw_enet_rmon_t_oversize_t; /*! * @name Constants and macros for entire ENET_RMON_T_OVERSIZE register */ /*@{*/ #define HW_ENET_RMON_T_OVERSIZE_ADDR(x) ((x) + 0x218U) #define HW_ENET_RMON_T_OVERSIZE(x) (*(__I hw_enet_rmon_t_oversize_t *) HW_ENET_RMON_T_OVERSIZE_ADDR(x)) #define HW_ENET_RMON_T_OVERSIZE_RD(x) (HW_ENET_RMON_T_OVERSIZE(x).U) /*@}*/ /* * Constants & macros for individual ENET_RMON_T_OVERSIZE bitfields */ /*! * @name Register ENET_RMON_T_OVERSIZE, field TXPKTS[15:0] (RO) */ /*@{*/ #define BP_ENET_RMON_T_OVERSIZE_TXPKTS (0U) /*!< Bit position for ENET_RMON_T_OVERSIZE_TXPKTS. */ #define BM_ENET_RMON_T_OVERSIZE_TXPKTS (0x0000FFFFU) /*!< Bit mask for ENET_RMON_T_OVERSIZE_TXPKTS. */ #define BS_ENET_RMON_T_OVERSIZE_TXPKTS (16U) /*!< Bit field size in bits for ENET_RMON_T_OVERSIZE_TXPKTS. */ /*! @brief Read current value of the ENET_RMON_T_OVERSIZE_TXPKTS field. */ #define BR_ENET_RMON_T_OVERSIZE_TXPKTS(x) (HW_ENET_RMON_T_OVERSIZE(x).B.TXPKTS) /*@}*/ /******************************************************************************* * HW_ENET_RMON_T_FRAG - Tx Packets Less Than 64 Bytes and Bad CRC Statistic Register ******************************************************************************/ /*! * @brief HW_ENET_RMON_T_FRAG - Tx Packets Less Than 64 Bytes and Bad CRC Statistic Register (RO) * * Reset value: 0x00000000U * * . */ typedef union _hw_enet_rmon_t_frag { uint32_t U; struct _hw_enet_rmon_t_frag_bitfields { uint32_t TXPKTS : 16; /*!< [15:0] Packet count */ uint32_t RESERVED0 : 16; /*!< [31:16] */ } B; } hw_enet_rmon_t_frag_t; /*! * @name Constants and macros for entire ENET_RMON_T_FRAG register */ /*@{*/ #define HW_ENET_RMON_T_FRAG_ADDR(x) ((x) + 0x21CU) #define HW_ENET_RMON_T_FRAG(x) (*(__I hw_enet_rmon_t_frag_t *) HW_ENET_RMON_T_FRAG_ADDR(x)) #define HW_ENET_RMON_T_FRAG_RD(x) (HW_ENET_RMON_T_FRAG(x).U) /*@}*/ /* * Constants & macros for individual ENET_RMON_T_FRAG bitfields */ /*! * @name Register ENET_RMON_T_FRAG, field TXPKTS[15:0] (RO) */ /*@{*/ #define BP_ENET_RMON_T_FRAG_TXPKTS (0U) /*!< Bit position for ENET_RMON_T_FRAG_TXPKTS. */ #define BM_ENET_RMON_T_FRAG_TXPKTS (0x0000FFFFU) /*!< Bit mask for ENET_RMON_T_FRAG_TXPKTS. */ #define BS_ENET_RMON_T_FRAG_TXPKTS (16U) /*!< Bit field size in bits for ENET_RMON_T_FRAG_TXPKTS. */ /*! @brief Read current value of the ENET_RMON_T_FRAG_TXPKTS field. */ #define BR_ENET_RMON_T_FRAG_TXPKTS(x) (HW_ENET_RMON_T_FRAG(x).B.TXPKTS) /*@}*/ /******************************************************************************* * HW_ENET_RMON_T_JAB - Tx Packets Greater Than MAX_FL bytes and Bad CRC Statistic Register ******************************************************************************/ /*! * @brief HW_ENET_RMON_T_JAB - Tx Packets Greater Than MAX_FL bytes and Bad CRC Statistic Register (RO) * * Reset value: 0x00000000U */ typedef union _hw_enet_rmon_t_jab { uint32_t U; struct _hw_enet_rmon_t_jab_bitfields { uint32_t TXPKTS : 16; /*!< [15:0] Packet count */ uint32_t RESERVED0 : 16; /*!< [31:16] */ } B; } hw_enet_rmon_t_jab_t; /*! * @name Constants and macros for entire ENET_RMON_T_JAB register */ /*@{*/ #define HW_ENET_RMON_T_JAB_ADDR(x) ((x) + 0x220U) #define HW_ENET_RMON_T_JAB(x) (*(__I hw_enet_rmon_t_jab_t *) HW_ENET_RMON_T_JAB_ADDR(x)) #define HW_ENET_RMON_T_JAB_RD(x) (HW_ENET_RMON_T_JAB(x).U) /*@}*/ /* * Constants & macros for individual ENET_RMON_T_JAB bitfields */ /*! * @name Register ENET_RMON_T_JAB, field TXPKTS[15:0] (RO) */ /*@{*/ #define BP_ENET_RMON_T_JAB_TXPKTS (0U) /*!< Bit position for ENET_RMON_T_JAB_TXPKTS. */ #define BM_ENET_RMON_T_JAB_TXPKTS (0x0000FFFFU) /*!< Bit mask for ENET_RMON_T_JAB_TXPKTS. */ #define BS_ENET_RMON_T_JAB_TXPKTS (16U) /*!< Bit field size in bits for ENET_RMON_T_JAB_TXPKTS. */ /*! @brief Read current value of the ENET_RMON_T_JAB_TXPKTS field. */ #define BR_ENET_RMON_T_JAB_TXPKTS(x) (HW_ENET_RMON_T_JAB(x).B.TXPKTS) /*@}*/ /******************************************************************************* * HW_ENET_RMON_T_COL - Tx Collision Count Statistic Register ******************************************************************************/ /*! * @brief HW_ENET_RMON_T_COL - Tx Collision Count Statistic Register (RO) * * Reset value: 0x00000000U */ typedef union _hw_enet_rmon_t_col { uint32_t U; struct _hw_enet_rmon_t_col_bitfields { uint32_t TXPKTS : 16; /*!< [15:0] Packet count */ uint32_t RESERVED0 : 16; /*!< [31:16] */ } B; } hw_enet_rmon_t_col_t; /*! * @name Constants and macros for entire ENET_RMON_T_COL register */ /*@{*/ #define HW_ENET_RMON_T_COL_ADDR(x) ((x) + 0x224U) #define HW_ENET_RMON_T_COL(x) (*(__I hw_enet_rmon_t_col_t *) HW_ENET_RMON_T_COL_ADDR(x)) #define HW_ENET_RMON_T_COL_RD(x) (HW_ENET_RMON_T_COL(x).U) /*@}*/ /* * Constants & macros for individual ENET_RMON_T_COL bitfields */ /*! * @name Register ENET_RMON_T_COL, field TXPKTS[15:0] (RO) */ /*@{*/ #define BP_ENET_RMON_T_COL_TXPKTS (0U) /*!< Bit position for ENET_RMON_T_COL_TXPKTS. */ #define BM_ENET_RMON_T_COL_TXPKTS (0x0000FFFFU) /*!< Bit mask for ENET_RMON_T_COL_TXPKTS. */ #define BS_ENET_RMON_T_COL_TXPKTS (16U) /*!< Bit field size in bits for ENET_RMON_T_COL_TXPKTS. */ /*! @brief Read current value of the ENET_RMON_T_COL_TXPKTS field. */ #define BR_ENET_RMON_T_COL_TXPKTS(x) (HW_ENET_RMON_T_COL(x).B.TXPKTS) /*@}*/ /******************************************************************************* * HW_ENET_RMON_T_P64 - Tx 64-Byte Packets Statistic Register ******************************************************************************/ /*! * @brief HW_ENET_RMON_T_P64 - Tx 64-Byte Packets Statistic Register (RO) * * Reset value: 0x00000000U * * . */ typedef union _hw_enet_rmon_t_p64 { uint32_t U; struct _hw_enet_rmon_t_p64_bitfields { uint32_t TXPKTS : 16; /*!< [15:0] Packet count */ uint32_t RESERVED0 : 16; /*!< [31:16] */ } B; } hw_enet_rmon_t_p64_t; /*! * @name Constants and macros for entire ENET_RMON_T_P64 register */ /*@{*/ #define HW_ENET_RMON_T_P64_ADDR(x) ((x) + 0x228U) #define HW_ENET_RMON_T_P64(x) (*(__I hw_enet_rmon_t_p64_t *) HW_ENET_RMON_T_P64_ADDR(x)) #define HW_ENET_RMON_T_P64_RD(x) (HW_ENET_RMON_T_P64(x).U) /*@}*/ /* * Constants & macros for individual ENET_RMON_T_P64 bitfields */ /*! * @name Register ENET_RMON_T_P64, field TXPKTS[15:0] (RO) */ /*@{*/ #define BP_ENET_RMON_T_P64_TXPKTS (0U) /*!< Bit position for ENET_RMON_T_P64_TXPKTS. */ #define BM_ENET_RMON_T_P64_TXPKTS (0x0000FFFFU) /*!< Bit mask for ENET_RMON_T_P64_TXPKTS. */ #define BS_ENET_RMON_T_P64_TXPKTS (16U) /*!< Bit field size in bits for ENET_RMON_T_P64_TXPKTS. */ /*! @brief Read current value of the ENET_RMON_T_P64_TXPKTS field. */ #define BR_ENET_RMON_T_P64_TXPKTS(x) (HW_ENET_RMON_T_P64(x).B.TXPKTS) /*@}*/ /******************************************************************************* * HW_ENET_RMON_T_P65TO127 - Tx 65- to 127-byte Packets Statistic Register ******************************************************************************/ /*! * @brief HW_ENET_RMON_T_P65TO127 - Tx 65- to 127-byte Packets Statistic Register (RO) * * Reset value: 0x00000000U */ typedef union _hw_enet_rmon_t_p65to127 { uint32_t U; struct _hw_enet_rmon_t_p65to127_bitfields { uint32_t TXPKTS : 16; /*!< [15:0] Packet count */ uint32_t RESERVED0 : 16; /*!< [31:16] */ } B; } hw_enet_rmon_t_p65to127_t; /*! * @name Constants and macros for entire ENET_RMON_T_P65TO127 register */ /*@{*/ #define HW_ENET_RMON_T_P65TO127_ADDR(x) ((x) + 0x22CU) #define HW_ENET_RMON_T_P65TO127(x) (*(__I hw_enet_rmon_t_p65to127_t *) HW_ENET_RMON_T_P65TO127_ADDR(x)) #define HW_ENET_RMON_T_P65TO127_RD(x) (HW_ENET_RMON_T_P65TO127(x).U) /*@}*/ /* * Constants & macros for individual ENET_RMON_T_P65TO127 bitfields */ /*! * @name Register ENET_RMON_T_P65TO127, field TXPKTS[15:0] (RO) */ /*@{*/ #define BP_ENET_RMON_T_P65TO127_TXPKTS (0U) /*!< Bit position for ENET_RMON_T_P65TO127_TXPKTS. */ #define BM_ENET_RMON_T_P65TO127_TXPKTS (0x0000FFFFU) /*!< Bit mask for ENET_RMON_T_P65TO127_TXPKTS. */ #define BS_ENET_RMON_T_P65TO127_TXPKTS (16U) /*!< Bit field size in bits for ENET_RMON_T_P65TO127_TXPKTS. */ /*! @brief Read current value of the ENET_RMON_T_P65TO127_TXPKTS field. */ #define BR_ENET_RMON_T_P65TO127_TXPKTS(x) (HW_ENET_RMON_T_P65TO127(x).B.TXPKTS) /*@}*/ /******************************************************************************* * HW_ENET_RMON_T_P128TO255 - Tx 128- to 255-byte Packets Statistic Register ******************************************************************************/ /*! * @brief HW_ENET_RMON_T_P128TO255 - Tx 128- to 255-byte Packets Statistic Register (RO) * * Reset value: 0x00000000U */ typedef union _hw_enet_rmon_t_p128to255 { uint32_t U; struct _hw_enet_rmon_t_p128to255_bitfields { uint32_t TXPKTS : 16; /*!< [15:0] Packet count */ uint32_t RESERVED0 : 16; /*!< [31:16] */ } B; } hw_enet_rmon_t_p128to255_t; /*! * @name Constants and macros for entire ENET_RMON_T_P128TO255 register */ /*@{*/ #define HW_ENET_RMON_T_P128TO255_ADDR(x) ((x) + 0x230U) #define HW_ENET_RMON_T_P128TO255(x) (*(__I hw_enet_rmon_t_p128to255_t *) HW_ENET_RMON_T_P128TO255_ADDR(x)) #define HW_ENET_RMON_T_P128TO255_RD(x) (HW_ENET_RMON_T_P128TO255(x).U) /*@}*/ /* * Constants & macros for individual ENET_RMON_T_P128TO255 bitfields */ /*! * @name Register ENET_RMON_T_P128TO255, field TXPKTS[15:0] (RO) */ /*@{*/ #define BP_ENET_RMON_T_P128TO255_TXPKTS (0U) /*!< Bit position for ENET_RMON_T_P128TO255_TXPKTS. */ #define BM_ENET_RMON_T_P128TO255_TXPKTS (0x0000FFFFU) /*!< Bit mask for ENET_RMON_T_P128TO255_TXPKTS. */ #define BS_ENET_RMON_T_P128TO255_TXPKTS (16U) /*!< Bit field size in bits for ENET_RMON_T_P128TO255_TXPKTS. */ /*! @brief Read current value of the ENET_RMON_T_P128TO255_TXPKTS field. */ #define BR_ENET_RMON_T_P128TO255_TXPKTS(x) (HW_ENET_RMON_T_P128TO255(x).B.TXPKTS) /*@}*/ /******************************************************************************* * HW_ENET_RMON_T_P256TO511 - Tx 256- to 511-byte Packets Statistic Register ******************************************************************************/ /*! * @brief HW_ENET_RMON_T_P256TO511 - Tx 256- to 511-byte Packets Statistic Register (RO) * * Reset value: 0x00000000U */ typedef union _hw_enet_rmon_t_p256to511 { uint32_t U; struct _hw_enet_rmon_t_p256to511_bitfields { uint32_t TXPKTS : 16; /*!< [15:0] Packet count */ uint32_t RESERVED0 : 16; /*!< [31:16] */ } B; } hw_enet_rmon_t_p256to511_t; /*! * @name Constants and macros for entire ENET_RMON_T_P256TO511 register */ /*@{*/ #define HW_ENET_RMON_T_P256TO511_ADDR(x) ((x) + 0x234U) #define HW_ENET_RMON_T_P256TO511(x) (*(__I hw_enet_rmon_t_p256to511_t *) HW_ENET_RMON_T_P256TO511_ADDR(x)) #define HW_ENET_RMON_T_P256TO511_RD(x) (HW_ENET_RMON_T_P256TO511(x).U) /*@}*/ /* * Constants & macros for individual ENET_RMON_T_P256TO511 bitfields */ /*! * @name Register ENET_RMON_T_P256TO511, field TXPKTS[15:0] (RO) */ /*@{*/ #define BP_ENET_RMON_T_P256TO511_TXPKTS (0U) /*!< Bit position for ENET_RMON_T_P256TO511_TXPKTS. */ #define BM_ENET_RMON_T_P256TO511_TXPKTS (0x0000FFFFU) /*!< Bit mask for ENET_RMON_T_P256TO511_TXPKTS. */ #define BS_ENET_RMON_T_P256TO511_TXPKTS (16U) /*!< Bit field size in bits for ENET_RMON_T_P256TO511_TXPKTS. */ /*! @brief Read current value of the ENET_RMON_T_P256TO511_TXPKTS field. */ #define BR_ENET_RMON_T_P256TO511_TXPKTS(x) (HW_ENET_RMON_T_P256TO511(x).B.TXPKTS) /*@}*/ /******************************************************************************* * HW_ENET_RMON_T_P512TO1023 - Tx 512- to 1023-byte Packets Statistic Register ******************************************************************************/ /*! * @brief HW_ENET_RMON_T_P512TO1023 - Tx 512- to 1023-byte Packets Statistic Register (RO) * * Reset value: 0x00000000U * * . */ typedef union _hw_enet_rmon_t_p512to1023 { uint32_t U; struct _hw_enet_rmon_t_p512to1023_bitfields { uint32_t TXPKTS : 16; /*!< [15:0] Packet count */ uint32_t RESERVED0 : 16; /*!< [31:16] */ } B; } hw_enet_rmon_t_p512to1023_t; /*! * @name Constants and macros for entire ENET_RMON_T_P512TO1023 register */ /*@{*/ #define HW_ENET_RMON_T_P512TO1023_ADDR(x) ((x) + 0x238U) #define HW_ENET_RMON_T_P512TO1023(x) (*(__I hw_enet_rmon_t_p512to1023_t *) HW_ENET_RMON_T_P512TO1023_ADDR(x)) #define HW_ENET_RMON_T_P512TO1023_RD(x) (HW_ENET_RMON_T_P512TO1023(x).U) /*@}*/ /* * Constants & macros for individual ENET_RMON_T_P512TO1023 bitfields */ /*! * @name Register ENET_RMON_T_P512TO1023, field TXPKTS[15:0] (RO) */ /*@{*/ #define BP_ENET_RMON_T_P512TO1023_TXPKTS (0U) /*!< Bit position for ENET_RMON_T_P512TO1023_TXPKTS. */ #define BM_ENET_RMON_T_P512TO1023_TXPKTS (0x0000FFFFU) /*!< Bit mask for ENET_RMON_T_P512TO1023_TXPKTS. */ #define BS_ENET_RMON_T_P512TO1023_TXPKTS (16U) /*!< Bit field size in bits for ENET_RMON_T_P512TO1023_TXPKTS. */ /*! @brief Read current value of the ENET_RMON_T_P512TO1023_TXPKTS field. */ #define BR_ENET_RMON_T_P512TO1023_TXPKTS(x) (HW_ENET_RMON_T_P512TO1023(x).B.TXPKTS) /*@}*/ /******************************************************************************* * HW_ENET_RMON_T_P1024TO2047 - Tx 1024- to 2047-byte Packets Statistic Register ******************************************************************************/ /*! * @brief HW_ENET_RMON_T_P1024TO2047 - Tx 1024- to 2047-byte Packets Statistic Register (RO) * * Reset value: 0x00000000U */ typedef union _hw_enet_rmon_t_p1024to2047 { uint32_t U; struct _hw_enet_rmon_t_p1024to2047_bitfields { uint32_t TXPKTS : 16; /*!< [15:0] Packet count */ uint32_t RESERVED0 : 16; /*!< [31:16] */ } B; } hw_enet_rmon_t_p1024to2047_t; /*! * @name Constants and macros for entire ENET_RMON_T_P1024TO2047 register */ /*@{*/ #define HW_ENET_RMON_T_P1024TO2047_ADDR(x) ((x) + 0x23CU) #define HW_ENET_RMON_T_P1024TO2047(x) (*(__I hw_enet_rmon_t_p1024to2047_t *) HW_ENET_RMON_T_P1024TO2047_ADDR(x)) #define HW_ENET_RMON_T_P1024TO2047_RD(x) (HW_ENET_RMON_T_P1024TO2047(x).U) /*@}*/ /* * Constants & macros for individual ENET_RMON_T_P1024TO2047 bitfields */ /*! * @name Register ENET_RMON_T_P1024TO2047, field TXPKTS[15:0] (RO) */ /*@{*/ #define BP_ENET_RMON_T_P1024TO2047_TXPKTS (0U) /*!< Bit position for ENET_RMON_T_P1024TO2047_TXPKTS. */ #define BM_ENET_RMON_T_P1024TO2047_TXPKTS (0x0000FFFFU) /*!< Bit mask for ENET_RMON_T_P1024TO2047_TXPKTS. */ #define BS_ENET_RMON_T_P1024TO2047_TXPKTS (16U) /*!< Bit field size in bits for ENET_RMON_T_P1024TO2047_TXPKTS. */ /*! @brief Read current value of the ENET_RMON_T_P1024TO2047_TXPKTS field. */ #define BR_ENET_RMON_T_P1024TO2047_TXPKTS(x) (HW_ENET_RMON_T_P1024TO2047(x).B.TXPKTS) /*@}*/ /******************************************************************************* * HW_ENET_RMON_T_P_GTE2048 - Tx Packets Greater Than 2048 Bytes Statistic Register ******************************************************************************/ /*! * @brief HW_ENET_RMON_T_P_GTE2048 - Tx Packets Greater Than 2048 Bytes Statistic Register (RO) * * Reset value: 0x00000000U */ typedef union _hw_enet_rmon_t_p_gte2048 { uint32_t U; struct _hw_enet_rmon_t_p_gte2048_bitfields { uint32_t TXPKTS : 16; /*!< [15:0] Packet count */ uint32_t RESERVED0 : 16; /*!< [31:16] */ } B; } hw_enet_rmon_t_p_gte2048_t; /*! * @name Constants and macros for entire ENET_RMON_T_P_GTE2048 register */ /*@{*/ #define HW_ENET_RMON_T_P_GTE2048_ADDR(x) ((x) + 0x240U) #define HW_ENET_RMON_T_P_GTE2048(x) (*(__I hw_enet_rmon_t_p_gte2048_t *) HW_ENET_RMON_T_P_GTE2048_ADDR(x)) #define HW_ENET_RMON_T_P_GTE2048_RD(x) (HW_ENET_RMON_T_P_GTE2048(x).U) /*@}*/ /* * Constants & macros for individual ENET_RMON_T_P_GTE2048 bitfields */ /*! * @name Register ENET_RMON_T_P_GTE2048, field TXPKTS[15:0] (RO) */ /*@{*/ #define BP_ENET_RMON_T_P_GTE2048_TXPKTS (0U) /*!< Bit position for ENET_RMON_T_P_GTE2048_TXPKTS. */ #define BM_ENET_RMON_T_P_GTE2048_TXPKTS (0x0000FFFFU) /*!< Bit mask for ENET_RMON_T_P_GTE2048_TXPKTS. */ #define BS_ENET_RMON_T_P_GTE2048_TXPKTS (16U) /*!< Bit field size in bits for ENET_RMON_T_P_GTE2048_TXPKTS. */ /*! @brief Read current value of the ENET_RMON_T_P_GTE2048_TXPKTS field. */ #define BR_ENET_RMON_T_P_GTE2048_TXPKTS(x) (HW_ENET_RMON_T_P_GTE2048(x).B.TXPKTS) /*@}*/ /******************************************************************************* * HW_ENET_RMON_T_OCTETS - Tx Octets Statistic Register ******************************************************************************/ /*! * @brief HW_ENET_RMON_T_OCTETS - Tx Octets Statistic Register (RO) * * Reset value: 0x00000000U */ typedef union _hw_enet_rmon_t_octets { uint32_t U; struct _hw_enet_rmon_t_octets_bitfields { uint32_t TXOCTS : 32; /*!< [31:0] Octet count */ } B; } hw_enet_rmon_t_octets_t; /*! * @name Constants and macros for entire ENET_RMON_T_OCTETS register */ /*@{*/ #define HW_ENET_RMON_T_OCTETS_ADDR(x) ((x) + 0x244U) #define HW_ENET_RMON_T_OCTETS(x) (*(__I hw_enet_rmon_t_octets_t *) HW_ENET_RMON_T_OCTETS_ADDR(x)) #define HW_ENET_RMON_T_OCTETS_RD(x) (HW_ENET_RMON_T_OCTETS(x).U) /*@}*/ /* * Constants & macros for individual ENET_RMON_T_OCTETS bitfields */ /*! * @name Register ENET_RMON_T_OCTETS, field TXOCTS[31:0] (RO) */ /*@{*/ #define BP_ENET_RMON_T_OCTETS_TXOCTS (0U) /*!< Bit position for ENET_RMON_T_OCTETS_TXOCTS. */ #define BM_ENET_RMON_T_OCTETS_TXOCTS (0xFFFFFFFFU) /*!< Bit mask for ENET_RMON_T_OCTETS_TXOCTS. */ #define BS_ENET_RMON_T_OCTETS_TXOCTS (32U) /*!< Bit field size in bits for ENET_RMON_T_OCTETS_TXOCTS. */ /*! @brief Read current value of the ENET_RMON_T_OCTETS_TXOCTS field. */ #define BR_ENET_RMON_T_OCTETS_TXOCTS(x) (HW_ENET_RMON_T_OCTETS(x).U) /*@}*/ /******************************************************************************* * HW_ENET_IEEE_T_FRAME_OK - Frames Transmitted OK Statistic Register ******************************************************************************/ /*! * @brief HW_ENET_IEEE_T_FRAME_OK - Frames Transmitted OK Statistic Register (RO) * * Reset value: 0x00000000U */ typedef union _hw_enet_ieee_t_frame_ok { uint32_t U; struct _hw_enet_ieee_t_frame_ok_bitfields { uint32_t COUNT : 16; /*!< [15:0] Frame count */ uint32_t RESERVED0 : 16; /*!< [31:16] */ } B; } hw_enet_ieee_t_frame_ok_t; /*! * @name Constants and macros for entire ENET_IEEE_T_FRAME_OK register */ /*@{*/ #define HW_ENET_IEEE_T_FRAME_OK_ADDR(x) ((x) + 0x24CU) #define HW_ENET_IEEE_T_FRAME_OK(x) (*(__I hw_enet_ieee_t_frame_ok_t *) HW_ENET_IEEE_T_FRAME_OK_ADDR(x)) #define HW_ENET_IEEE_T_FRAME_OK_RD(x) (HW_ENET_IEEE_T_FRAME_OK(x).U) /*@}*/ /* * Constants & macros for individual ENET_IEEE_T_FRAME_OK bitfields */ /*! * @name Register ENET_IEEE_T_FRAME_OK, field COUNT[15:0] (RO) */ /*@{*/ #define BP_ENET_IEEE_T_FRAME_OK_COUNT (0U) /*!< Bit position for ENET_IEEE_T_FRAME_OK_COUNT. */ #define BM_ENET_IEEE_T_FRAME_OK_COUNT (0x0000FFFFU) /*!< Bit mask for ENET_IEEE_T_FRAME_OK_COUNT. */ #define BS_ENET_IEEE_T_FRAME_OK_COUNT (16U) /*!< Bit field size in bits for ENET_IEEE_T_FRAME_OK_COUNT. */ /*! @brief Read current value of the ENET_IEEE_T_FRAME_OK_COUNT field. */ #define BR_ENET_IEEE_T_FRAME_OK_COUNT(x) (HW_ENET_IEEE_T_FRAME_OK(x).B.COUNT) /*@}*/ /******************************************************************************* * HW_ENET_IEEE_T_1COL - Frames Transmitted with Single Collision Statistic Register ******************************************************************************/ /*! * @brief HW_ENET_IEEE_T_1COL - Frames Transmitted with Single Collision Statistic Register (RO) * * Reset value: 0x00000000U */ typedef union _hw_enet_ieee_t_1col { uint32_t U; struct _hw_enet_ieee_t_1col_bitfields { uint32_t COUNT : 16; /*!< [15:0] Frame count */ uint32_t RESERVED0 : 16; /*!< [31:16] */ } B; } hw_enet_ieee_t_1col_t; /*! * @name Constants and macros for entire ENET_IEEE_T_1COL register */ /*@{*/ #define HW_ENET_IEEE_T_1COL_ADDR(x) ((x) + 0x250U) #define HW_ENET_IEEE_T_1COL(x) (*(__I hw_enet_ieee_t_1col_t *) HW_ENET_IEEE_T_1COL_ADDR(x)) #define HW_ENET_IEEE_T_1COL_RD(x) (HW_ENET_IEEE_T_1COL(x).U) /*@}*/ /* * Constants & macros for individual ENET_IEEE_T_1COL bitfields */ /*! * @name Register ENET_IEEE_T_1COL, field COUNT[15:0] (RO) */ /*@{*/ #define BP_ENET_IEEE_T_1COL_COUNT (0U) /*!< Bit position for ENET_IEEE_T_1COL_COUNT. */ #define BM_ENET_IEEE_T_1COL_COUNT (0x0000FFFFU) /*!< Bit mask for ENET_IEEE_T_1COL_COUNT. */ #define BS_ENET_IEEE_T_1COL_COUNT (16U) /*!< Bit field size in bits for ENET_IEEE_T_1COL_COUNT. */ /*! @brief Read current value of the ENET_IEEE_T_1COL_COUNT field. */ #define BR_ENET_IEEE_T_1COL_COUNT(x) (HW_ENET_IEEE_T_1COL(x).B.COUNT) /*@}*/ /******************************************************************************* * HW_ENET_IEEE_T_MCOL - Frames Transmitted with Multiple Collisions Statistic Register ******************************************************************************/ /*! * @brief HW_ENET_IEEE_T_MCOL - Frames Transmitted with Multiple Collisions Statistic Register (RO) * * Reset value: 0x00000000U */ typedef union _hw_enet_ieee_t_mcol { uint32_t U; struct _hw_enet_ieee_t_mcol_bitfields { uint32_t COUNT : 16; /*!< [15:0] Frame count */ uint32_t RESERVED0 : 16; /*!< [31:16] */ } B; } hw_enet_ieee_t_mcol_t; /*! * @name Constants and macros for entire ENET_IEEE_T_MCOL register */ /*@{*/ #define HW_ENET_IEEE_T_MCOL_ADDR(x) ((x) + 0x254U) #define HW_ENET_IEEE_T_MCOL(x) (*(__I hw_enet_ieee_t_mcol_t *) HW_ENET_IEEE_T_MCOL_ADDR(x)) #define HW_ENET_IEEE_T_MCOL_RD(x) (HW_ENET_IEEE_T_MCOL(x).U) /*@}*/ /* * Constants & macros for individual ENET_IEEE_T_MCOL bitfields */ /*! * @name Register ENET_IEEE_T_MCOL, field COUNT[15:0] (RO) */ /*@{*/ #define BP_ENET_IEEE_T_MCOL_COUNT (0U) /*!< Bit position for ENET_IEEE_T_MCOL_COUNT. */ #define BM_ENET_IEEE_T_MCOL_COUNT (0x0000FFFFU) /*!< Bit mask for ENET_IEEE_T_MCOL_COUNT. */ #define BS_ENET_IEEE_T_MCOL_COUNT (16U) /*!< Bit field size in bits for ENET_IEEE_T_MCOL_COUNT. */ /*! @brief Read current value of the ENET_IEEE_T_MCOL_COUNT field. */ #define BR_ENET_IEEE_T_MCOL_COUNT(x) (HW_ENET_IEEE_T_MCOL(x).B.COUNT) /*@}*/ /******************************************************************************* * HW_ENET_IEEE_T_DEF - Frames Transmitted after Deferral Delay Statistic Register ******************************************************************************/ /*! * @brief HW_ENET_IEEE_T_DEF - Frames Transmitted after Deferral Delay Statistic Register (RO) * * Reset value: 0x00000000U */ typedef union _hw_enet_ieee_t_def { uint32_t U; struct _hw_enet_ieee_t_def_bitfields { uint32_t COUNT : 16; /*!< [15:0] Frame count */ uint32_t RESERVED0 : 16; /*!< [31:16] */ } B; } hw_enet_ieee_t_def_t; /*! * @name Constants and macros for entire ENET_IEEE_T_DEF register */ /*@{*/ #define HW_ENET_IEEE_T_DEF_ADDR(x) ((x) + 0x258U) #define HW_ENET_IEEE_T_DEF(x) (*(__I hw_enet_ieee_t_def_t *) HW_ENET_IEEE_T_DEF_ADDR(x)) #define HW_ENET_IEEE_T_DEF_RD(x) (HW_ENET_IEEE_T_DEF(x).U) /*@}*/ /* * Constants & macros for individual ENET_IEEE_T_DEF bitfields */ /*! * @name Register ENET_IEEE_T_DEF, field COUNT[15:0] (RO) */ /*@{*/ #define BP_ENET_IEEE_T_DEF_COUNT (0U) /*!< Bit position for ENET_IEEE_T_DEF_COUNT. */ #define BM_ENET_IEEE_T_DEF_COUNT (0x0000FFFFU) /*!< Bit mask for ENET_IEEE_T_DEF_COUNT. */ #define BS_ENET_IEEE_T_DEF_COUNT (16U) /*!< Bit field size in bits for ENET_IEEE_T_DEF_COUNT. */ /*! @brief Read current value of the ENET_IEEE_T_DEF_COUNT field. */ #define BR_ENET_IEEE_T_DEF_COUNT(x) (HW_ENET_IEEE_T_DEF(x).B.COUNT) /*@}*/ /******************************************************************************* * HW_ENET_IEEE_T_LCOL - Frames Transmitted with Late Collision Statistic Register ******************************************************************************/ /*! * @brief HW_ENET_IEEE_T_LCOL - Frames Transmitted with Late Collision Statistic Register (RO) * * Reset value: 0x00000000U */ typedef union _hw_enet_ieee_t_lcol { uint32_t U; struct _hw_enet_ieee_t_lcol_bitfields { uint32_t COUNT : 16; /*!< [15:0] Frame count */ uint32_t RESERVED0 : 16; /*!< [31:16] */ } B; } hw_enet_ieee_t_lcol_t; /*! * @name Constants and macros for entire ENET_IEEE_T_LCOL register */ /*@{*/ #define HW_ENET_IEEE_T_LCOL_ADDR(x) ((x) + 0x25CU) #define HW_ENET_IEEE_T_LCOL(x) (*(__I hw_enet_ieee_t_lcol_t *) HW_ENET_IEEE_T_LCOL_ADDR(x)) #define HW_ENET_IEEE_T_LCOL_RD(x) (HW_ENET_IEEE_T_LCOL(x).U) /*@}*/ /* * Constants & macros for individual ENET_IEEE_T_LCOL bitfields */ /*! * @name Register ENET_IEEE_T_LCOL, field COUNT[15:0] (RO) */ /*@{*/ #define BP_ENET_IEEE_T_LCOL_COUNT (0U) /*!< Bit position for ENET_IEEE_T_LCOL_COUNT. */ #define BM_ENET_IEEE_T_LCOL_COUNT (0x0000FFFFU) /*!< Bit mask for ENET_IEEE_T_LCOL_COUNT. */ #define BS_ENET_IEEE_T_LCOL_COUNT (16U) /*!< Bit field size in bits for ENET_IEEE_T_LCOL_COUNT. */ /*! @brief Read current value of the ENET_IEEE_T_LCOL_COUNT field. */ #define BR_ENET_IEEE_T_LCOL_COUNT(x) (HW_ENET_IEEE_T_LCOL(x).B.COUNT) /*@}*/ /******************************************************************************* * HW_ENET_IEEE_T_EXCOL - Frames Transmitted with Excessive Collisions Statistic Register ******************************************************************************/ /*! * @brief HW_ENET_IEEE_T_EXCOL - Frames Transmitted with Excessive Collisions Statistic Register (RO) * * Reset value: 0x00000000U */ typedef union _hw_enet_ieee_t_excol { uint32_t U; struct _hw_enet_ieee_t_excol_bitfields { uint32_t COUNT : 16; /*!< [15:0] Frame count */ uint32_t RESERVED0 : 16; /*!< [31:16] */ } B; } hw_enet_ieee_t_excol_t; /*! * @name Constants and macros for entire ENET_IEEE_T_EXCOL register */ /*@{*/ #define HW_ENET_IEEE_T_EXCOL_ADDR(x) ((x) + 0x260U) #define HW_ENET_IEEE_T_EXCOL(x) (*(__I hw_enet_ieee_t_excol_t *) HW_ENET_IEEE_T_EXCOL_ADDR(x)) #define HW_ENET_IEEE_T_EXCOL_RD(x) (HW_ENET_IEEE_T_EXCOL(x).U) /*@}*/ /* * Constants & macros for individual ENET_IEEE_T_EXCOL bitfields */ /*! * @name Register ENET_IEEE_T_EXCOL, field COUNT[15:0] (RO) */ /*@{*/ #define BP_ENET_IEEE_T_EXCOL_COUNT (0U) /*!< Bit position for ENET_IEEE_T_EXCOL_COUNT. */ #define BM_ENET_IEEE_T_EXCOL_COUNT (0x0000FFFFU) /*!< Bit mask for ENET_IEEE_T_EXCOL_COUNT. */ #define BS_ENET_IEEE_T_EXCOL_COUNT (16U) /*!< Bit field size in bits for ENET_IEEE_T_EXCOL_COUNT. */ /*! @brief Read current value of the ENET_IEEE_T_EXCOL_COUNT field. */ #define BR_ENET_IEEE_T_EXCOL_COUNT(x) (HW_ENET_IEEE_T_EXCOL(x).B.COUNT) /*@}*/ /******************************************************************************* * HW_ENET_IEEE_T_MACERR - Frames Transmitted with Tx FIFO Underrun Statistic Register ******************************************************************************/ /*! * @brief HW_ENET_IEEE_T_MACERR - Frames Transmitted with Tx FIFO Underrun Statistic Register (RO) * * Reset value: 0x00000000U */ typedef union _hw_enet_ieee_t_macerr { uint32_t U; struct _hw_enet_ieee_t_macerr_bitfields { uint32_t COUNT : 16; /*!< [15:0] Frame count */ uint32_t RESERVED0 : 16; /*!< [31:16] */ } B; } hw_enet_ieee_t_macerr_t; /*! * @name Constants and macros for entire ENET_IEEE_T_MACERR register */ /*@{*/ #define HW_ENET_IEEE_T_MACERR_ADDR(x) ((x) + 0x264U) #define HW_ENET_IEEE_T_MACERR(x) (*(__I hw_enet_ieee_t_macerr_t *) HW_ENET_IEEE_T_MACERR_ADDR(x)) #define HW_ENET_IEEE_T_MACERR_RD(x) (HW_ENET_IEEE_T_MACERR(x).U) /*@}*/ /* * Constants & macros for individual ENET_IEEE_T_MACERR bitfields */ /*! * @name Register ENET_IEEE_T_MACERR, field COUNT[15:0] (RO) */ /*@{*/ #define BP_ENET_IEEE_T_MACERR_COUNT (0U) /*!< Bit position for ENET_IEEE_T_MACERR_COUNT. */ #define BM_ENET_IEEE_T_MACERR_COUNT (0x0000FFFFU) /*!< Bit mask for ENET_IEEE_T_MACERR_COUNT. */ #define BS_ENET_IEEE_T_MACERR_COUNT (16U) /*!< Bit field size in bits for ENET_IEEE_T_MACERR_COUNT. */ /*! @brief Read current value of the ENET_IEEE_T_MACERR_COUNT field. */ #define BR_ENET_IEEE_T_MACERR_COUNT(x) (HW_ENET_IEEE_T_MACERR(x).B.COUNT) /*@}*/ /******************************************************************************* * HW_ENET_IEEE_T_CSERR - Frames Transmitted with Carrier Sense Error Statistic Register ******************************************************************************/ /*! * @brief HW_ENET_IEEE_T_CSERR - Frames Transmitted with Carrier Sense Error Statistic Register (RO) * * Reset value: 0x00000000U */ typedef union _hw_enet_ieee_t_cserr { uint32_t U; struct _hw_enet_ieee_t_cserr_bitfields { uint32_t COUNT : 16; /*!< [15:0] Frame count */ uint32_t RESERVED0 : 16; /*!< [31:16] */ } B; } hw_enet_ieee_t_cserr_t; /*! * @name Constants and macros for entire ENET_IEEE_T_CSERR register */ /*@{*/ #define HW_ENET_IEEE_T_CSERR_ADDR(x) ((x) + 0x268U) #define HW_ENET_IEEE_T_CSERR(x) (*(__I hw_enet_ieee_t_cserr_t *) HW_ENET_IEEE_T_CSERR_ADDR(x)) #define HW_ENET_IEEE_T_CSERR_RD(x) (HW_ENET_IEEE_T_CSERR(x).U) /*@}*/ /* * Constants & macros for individual ENET_IEEE_T_CSERR bitfields */ /*! * @name Register ENET_IEEE_T_CSERR, field COUNT[15:0] (RO) */ /*@{*/ #define BP_ENET_IEEE_T_CSERR_COUNT (0U) /*!< Bit position for ENET_IEEE_T_CSERR_COUNT. */ #define BM_ENET_IEEE_T_CSERR_COUNT (0x0000FFFFU) /*!< Bit mask for ENET_IEEE_T_CSERR_COUNT. */ #define BS_ENET_IEEE_T_CSERR_COUNT (16U) /*!< Bit field size in bits for ENET_IEEE_T_CSERR_COUNT. */ /*! @brief Read current value of the ENET_IEEE_T_CSERR_COUNT field. */ #define BR_ENET_IEEE_T_CSERR_COUNT(x) (HW_ENET_IEEE_T_CSERR(x).B.COUNT) /*@}*/ /******************************************************************************* * HW_ENET_IEEE_T_FDXFC - Flow Control Pause Frames Transmitted Statistic Register ******************************************************************************/ /*! * @brief HW_ENET_IEEE_T_FDXFC - Flow Control Pause Frames Transmitted Statistic Register (RO) * * Reset value: 0x00000000U */ typedef union _hw_enet_ieee_t_fdxfc { uint32_t U; struct _hw_enet_ieee_t_fdxfc_bitfields { uint32_t COUNT : 16; /*!< [15:0] Frame count */ uint32_t RESERVED0 : 16; /*!< [31:16] */ } B; } hw_enet_ieee_t_fdxfc_t; /*! * @name Constants and macros for entire ENET_IEEE_T_FDXFC register */ /*@{*/ #define HW_ENET_IEEE_T_FDXFC_ADDR(x) ((x) + 0x270U) #define HW_ENET_IEEE_T_FDXFC(x) (*(__I hw_enet_ieee_t_fdxfc_t *) HW_ENET_IEEE_T_FDXFC_ADDR(x)) #define HW_ENET_IEEE_T_FDXFC_RD(x) (HW_ENET_IEEE_T_FDXFC(x).U) /*@}*/ /* * Constants & macros for individual ENET_IEEE_T_FDXFC bitfields */ /*! * @name Register ENET_IEEE_T_FDXFC, field COUNT[15:0] (RO) */ /*@{*/ #define BP_ENET_IEEE_T_FDXFC_COUNT (0U) /*!< Bit position for ENET_IEEE_T_FDXFC_COUNT. */ #define BM_ENET_IEEE_T_FDXFC_COUNT (0x0000FFFFU) /*!< Bit mask for ENET_IEEE_T_FDXFC_COUNT. */ #define BS_ENET_IEEE_T_FDXFC_COUNT (16U) /*!< Bit field size in bits for ENET_IEEE_T_FDXFC_COUNT. */ /*! @brief Read current value of the ENET_IEEE_T_FDXFC_COUNT field. */ #define BR_ENET_IEEE_T_FDXFC_COUNT(x) (HW_ENET_IEEE_T_FDXFC(x).B.COUNT) /*@}*/ /******************************************************************************* * HW_ENET_IEEE_T_OCTETS_OK - Octet Count for Frames Transmitted w/o Error Statistic Register ******************************************************************************/ /*! * @brief HW_ENET_IEEE_T_OCTETS_OK - Octet Count for Frames Transmitted w/o Error Statistic Register (RO) * * Reset value: 0x00000000U * * Counts total octets (includes header and FCS fields). */ typedef union _hw_enet_ieee_t_octets_ok { uint32_t U; struct _hw_enet_ieee_t_octets_ok_bitfields { uint32_t COUNT : 32; /*!< [31:0] Octet count */ } B; } hw_enet_ieee_t_octets_ok_t; /*! * @name Constants and macros for entire ENET_IEEE_T_OCTETS_OK register */ /*@{*/ #define HW_ENET_IEEE_T_OCTETS_OK_ADDR(x) ((x) + 0x274U) #define HW_ENET_IEEE_T_OCTETS_OK(x) (*(__I hw_enet_ieee_t_octets_ok_t *) HW_ENET_IEEE_T_OCTETS_OK_ADDR(x)) #define HW_ENET_IEEE_T_OCTETS_OK_RD(x) (HW_ENET_IEEE_T_OCTETS_OK(x).U) /*@}*/ /* * Constants & macros for individual ENET_IEEE_T_OCTETS_OK bitfields */ /*! * @name Register ENET_IEEE_T_OCTETS_OK, field COUNT[31:0] (RO) */ /*@{*/ #define BP_ENET_IEEE_T_OCTETS_OK_COUNT (0U) /*!< Bit position for ENET_IEEE_T_OCTETS_OK_COUNT. */ #define BM_ENET_IEEE_T_OCTETS_OK_COUNT (0xFFFFFFFFU) /*!< Bit mask for ENET_IEEE_T_OCTETS_OK_COUNT. */ #define BS_ENET_IEEE_T_OCTETS_OK_COUNT (32U) /*!< Bit field size in bits for ENET_IEEE_T_OCTETS_OK_COUNT. */ /*! @brief Read current value of the ENET_IEEE_T_OCTETS_OK_COUNT field. */ #define BR_ENET_IEEE_T_OCTETS_OK_COUNT(x) (HW_ENET_IEEE_T_OCTETS_OK(x).U) /*@}*/ /******************************************************************************* * HW_ENET_RMON_R_PACKETS - Rx Packet Count Statistic Register ******************************************************************************/ /*! * @brief HW_ENET_RMON_R_PACKETS - Rx Packet Count Statistic Register (RO) * * Reset value: 0x00000000U */ typedef union _hw_enet_rmon_r_packets { uint32_t U; struct _hw_enet_rmon_r_packets_bitfields { uint32_t COUNT : 16; /*!< [15:0] Packet count */ uint32_t RESERVED0 : 16; /*!< [31:16] */ } B; } hw_enet_rmon_r_packets_t; /*! * @name Constants and macros for entire ENET_RMON_R_PACKETS register */ /*@{*/ #define HW_ENET_RMON_R_PACKETS_ADDR(x) ((x) + 0x284U) #define HW_ENET_RMON_R_PACKETS(x) (*(__I hw_enet_rmon_r_packets_t *) HW_ENET_RMON_R_PACKETS_ADDR(x)) #define HW_ENET_RMON_R_PACKETS_RD(x) (HW_ENET_RMON_R_PACKETS(x).U) /*@}*/ /* * Constants & macros for individual ENET_RMON_R_PACKETS bitfields */ /*! * @name Register ENET_RMON_R_PACKETS, field COUNT[15:0] (RO) */ /*@{*/ #define BP_ENET_RMON_R_PACKETS_COUNT (0U) /*!< Bit position for ENET_RMON_R_PACKETS_COUNT. */ #define BM_ENET_RMON_R_PACKETS_COUNT (0x0000FFFFU) /*!< Bit mask for ENET_RMON_R_PACKETS_COUNT. */ #define BS_ENET_RMON_R_PACKETS_COUNT (16U) /*!< Bit field size in bits for ENET_RMON_R_PACKETS_COUNT. */ /*! @brief Read current value of the ENET_RMON_R_PACKETS_COUNT field. */ #define BR_ENET_RMON_R_PACKETS_COUNT(x) (HW_ENET_RMON_R_PACKETS(x).B.COUNT) /*@}*/ /******************************************************************************* * HW_ENET_RMON_R_BC_PKT - Rx Broadcast Packets Statistic Register ******************************************************************************/ /*! * @brief HW_ENET_RMON_R_BC_PKT - Rx Broadcast Packets Statistic Register (RO) * * Reset value: 0x00000000U */ typedef union _hw_enet_rmon_r_bc_pkt { uint32_t U; struct _hw_enet_rmon_r_bc_pkt_bitfields { uint32_t COUNT : 16; /*!< [15:0] Packet count */ uint32_t RESERVED0 : 16; /*!< [31:16] */ } B; } hw_enet_rmon_r_bc_pkt_t; /*! * @name Constants and macros for entire ENET_RMON_R_BC_PKT register */ /*@{*/ #define HW_ENET_RMON_R_BC_PKT_ADDR(x) ((x) + 0x288U) #define HW_ENET_RMON_R_BC_PKT(x) (*(__I hw_enet_rmon_r_bc_pkt_t *) HW_ENET_RMON_R_BC_PKT_ADDR(x)) #define HW_ENET_RMON_R_BC_PKT_RD(x) (HW_ENET_RMON_R_BC_PKT(x).U) /*@}*/ /* * Constants & macros for individual ENET_RMON_R_BC_PKT bitfields */ /*! * @name Register ENET_RMON_R_BC_PKT, field COUNT[15:0] (RO) */ /*@{*/ #define BP_ENET_RMON_R_BC_PKT_COUNT (0U) /*!< Bit position for ENET_RMON_R_BC_PKT_COUNT. */ #define BM_ENET_RMON_R_BC_PKT_COUNT (0x0000FFFFU) /*!< Bit mask for ENET_RMON_R_BC_PKT_COUNT. */ #define BS_ENET_RMON_R_BC_PKT_COUNT (16U) /*!< Bit field size in bits for ENET_RMON_R_BC_PKT_COUNT. */ /*! @brief Read current value of the ENET_RMON_R_BC_PKT_COUNT field. */ #define BR_ENET_RMON_R_BC_PKT_COUNT(x) (HW_ENET_RMON_R_BC_PKT(x).B.COUNT) /*@}*/ /******************************************************************************* * HW_ENET_RMON_R_MC_PKT - Rx Multicast Packets Statistic Register ******************************************************************************/ /*! * @brief HW_ENET_RMON_R_MC_PKT - Rx Multicast Packets Statistic Register (RO) * * Reset value: 0x00000000U */ typedef union _hw_enet_rmon_r_mc_pkt { uint32_t U; struct _hw_enet_rmon_r_mc_pkt_bitfields { uint32_t COUNT : 16; /*!< [15:0] Packet count */ uint32_t RESERVED0 : 16; /*!< [31:16] */ } B; } hw_enet_rmon_r_mc_pkt_t; /*! * @name Constants and macros for entire ENET_RMON_R_MC_PKT register */ /*@{*/ #define HW_ENET_RMON_R_MC_PKT_ADDR(x) ((x) + 0x28CU) #define HW_ENET_RMON_R_MC_PKT(x) (*(__I hw_enet_rmon_r_mc_pkt_t *) HW_ENET_RMON_R_MC_PKT_ADDR(x)) #define HW_ENET_RMON_R_MC_PKT_RD(x) (HW_ENET_RMON_R_MC_PKT(x).U) /*@}*/ /* * Constants & macros for individual ENET_RMON_R_MC_PKT bitfields */ /*! * @name Register ENET_RMON_R_MC_PKT, field COUNT[15:0] (RO) */ /*@{*/ #define BP_ENET_RMON_R_MC_PKT_COUNT (0U) /*!< Bit position for ENET_RMON_R_MC_PKT_COUNT. */ #define BM_ENET_RMON_R_MC_PKT_COUNT (0x0000FFFFU) /*!< Bit mask for ENET_RMON_R_MC_PKT_COUNT. */ #define BS_ENET_RMON_R_MC_PKT_COUNT (16U) /*!< Bit field size in bits for ENET_RMON_R_MC_PKT_COUNT. */ /*! @brief Read current value of the ENET_RMON_R_MC_PKT_COUNT field. */ #define BR_ENET_RMON_R_MC_PKT_COUNT(x) (HW_ENET_RMON_R_MC_PKT(x).B.COUNT) /*@}*/ /******************************************************************************* * HW_ENET_RMON_R_CRC_ALIGN - Rx Packets with CRC/Align Error Statistic Register ******************************************************************************/ /*! * @brief HW_ENET_RMON_R_CRC_ALIGN - Rx Packets with CRC/Align Error Statistic Register (RO) * * Reset value: 0x00000000U */ typedef union _hw_enet_rmon_r_crc_align { uint32_t U; struct _hw_enet_rmon_r_crc_align_bitfields { uint32_t COUNT : 16; /*!< [15:0] Packet count */ uint32_t RESERVED0 : 16; /*!< [31:16] */ } B; } hw_enet_rmon_r_crc_align_t; /*! * @name Constants and macros for entire ENET_RMON_R_CRC_ALIGN register */ /*@{*/ #define HW_ENET_RMON_R_CRC_ALIGN_ADDR(x) ((x) + 0x290U) #define HW_ENET_RMON_R_CRC_ALIGN(x) (*(__I hw_enet_rmon_r_crc_align_t *) HW_ENET_RMON_R_CRC_ALIGN_ADDR(x)) #define HW_ENET_RMON_R_CRC_ALIGN_RD(x) (HW_ENET_RMON_R_CRC_ALIGN(x).U) /*@}*/ /* * Constants & macros for individual ENET_RMON_R_CRC_ALIGN bitfields */ /*! * @name Register ENET_RMON_R_CRC_ALIGN, field COUNT[15:0] (RO) */ /*@{*/ #define BP_ENET_RMON_R_CRC_ALIGN_COUNT (0U) /*!< Bit position for ENET_RMON_R_CRC_ALIGN_COUNT. */ #define BM_ENET_RMON_R_CRC_ALIGN_COUNT (0x0000FFFFU) /*!< Bit mask for ENET_RMON_R_CRC_ALIGN_COUNT. */ #define BS_ENET_RMON_R_CRC_ALIGN_COUNT (16U) /*!< Bit field size in bits for ENET_RMON_R_CRC_ALIGN_COUNT. */ /*! @brief Read current value of the ENET_RMON_R_CRC_ALIGN_COUNT field. */ #define BR_ENET_RMON_R_CRC_ALIGN_COUNT(x) (HW_ENET_RMON_R_CRC_ALIGN(x).B.COUNT) /*@}*/ /******************************************************************************* * HW_ENET_RMON_R_UNDERSIZE - Rx Packets with Less Than 64 Bytes and Good CRC Statistic Register ******************************************************************************/ /*! * @brief HW_ENET_RMON_R_UNDERSIZE - Rx Packets with Less Than 64 Bytes and Good CRC Statistic Register (RO) * * Reset value: 0x00000000U */ typedef union _hw_enet_rmon_r_undersize { uint32_t U; struct _hw_enet_rmon_r_undersize_bitfields { uint32_t COUNT : 16; /*!< [15:0] Packet count */ uint32_t RESERVED0 : 16; /*!< [31:16] */ } B; } hw_enet_rmon_r_undersize_t; /*! * @name Constants and macros for entire ENET_RMON_R_UNDERSIZE register */ /*@{*/ #define HW_ENET_RMON_R_UNDERSIZE_ADDR(x) ((x) + 0x294U) #define HW_ENET_RMON_R_UNDERSIZE(x) (*(__I hw_enet_rmon_r_undersize_t *) HW_ENET_RMON_R_UNDERSIZE_ADDR(x)) #define HW_ENET_RMON_R_UNDERSIZE_RD(x) (HW_ENET_RMON_R_UNDERSIZE(x).U) /*@}*/ /* * Constants & macros for individual ENET_RMON_R_UNDERSIZE bitfields */ /*! * @name Register ENET_RMON_R_UNDERSIZE, field COUNT[15:0] (RO) */ /*@{*/ #define BP_ENET_RMON_R_UNDERSIZE_COUNT (0U) /*!< Bit position for ENET_RMON_R_UNDERSIZE_COUNT. */ #define BM_ENET_RMON_R_UNDERSIZE_COUNT (0x0000FFFFU) /*!< Bit mask for ENET_RMON_R_UNDERSIZE_COUNT. */ #define BS_ENET_RMON_R_UNDERSIZE_COUNT (16U) /*!< Bit field size in bits for ENET_RMON_R_UNDERSIZE_COUNT. */ /*! @brief Read current value of the ENET_RMON_R_UNDERSIZE_COUNT field. */ #define BR_ENET_RMON_R_UNDERSIZE_COUNT(x) (HW_ENET_RMON_R_UNDERSIZE(x).B.COUNT) /*@}*/ /******************************************************************************* * HW_ENET_RMON_R_OVERSIZE - Rx Packets Greater Than MAX_FL and Good CRC Statistic Register ******************************************************************************/ /*! * @brief HW_ENET_RMON_R_OVERSIZE - Rx Packets Greater Than MAX_FL and Good CRC Statistic Register (RO) * * Reset value: 0x00000000U */ typedef union _hw_enet_rmon_r_oversize { uint32_t U; struct _hw_enet_rmon_r_oversize_bitfields { uint32_t COUNT : 16; /*!< [15:0] Packet count */ uint32_t RESERVED0 : 16; /*!< [31:16] */ } B; } hw_enet_rmon_r_oversize_t; /*! * @name Constants and macros for entire ENET_RMON_R_OVERSIZE register */ /*@{*/ #define HW_ENET_RMON_R_OVERSIZE_ADDR(x) ((x) + 0x298U) #define HW_ENET_RMON_R_OVERSIZE(x) (*(__I hw_enet_rmon_r_oversize_t *) HW_ENET_RMON_R_OVERSIZE_ADDR(x)) #define HW_ENET_RMON_R_OVERSIZE_RD(x) (HW_ENET_RMON_R_OVERSIZE(x).U) /*@}*/ /* * Constants & macros for individual ENET_RMON_R_OVERSIZE bitfields */ /*! * @name Register ENET_RMON_R_OVERSIZE, field COUNT[15:0] (RO) */ /*@{*/ #define BP_ENET_RMON_R_OVERSIZE_COUNT (0U) /*!< Bit position for ENET_RMON_R_OVERSIZE_COUNT. */ #define BM_ENET_RMON_R_OVERSIZE_COUNT (0x0000FFFFU) /*!< Bit mask for ENET_RMON_R_OVERSIZE_COUNT. */ #define BS_ENET_RMON_R_OVERSIZE_COUNT (16U) /*!< Bit field size in bits for ENET_RMON_R_OVERSIZE_COUNT. */ /*! @brief Read current value of the ENET_RMON_R_OVERSIZE_COUNT field. */ #define BR_ENET_RMON_R_OVERSIZE_COUNT(x) (HW_ENET_RMON_R_OVERSIZE(x).B.COUNT) /*@}*/ /******************************************************************************* * HW_ENET_RMON_R_FRAG - Rx Packets Less Than 64 Bytes and Bad CRC Statistic Register ******************************************************************************/ /*! * @brief HW_ENET_RMON_R_FRAG - Rx Packets Less Than 64 Bytes and Bad CRC Statistic Register (RO) * * Reset value: 0x00000000U */ typedef union _hw_enet_rmon_r_frag { uint32_t U; struct _hw_enet_rmon_r_frag_bitfields { uint32_t COUNT : 16; /*!< [15:0] Packet count */ uint32_t RESERVED0 : 16; /*!< [31:16] */ } B; } hw_enet_rmon_r_frag_t; /*! * @name Constants and macros for entire ENET_RMON_R_FRAG register */ /*@{*/ #define HW_ENET_RMON_R_FRAG_ADDR(x) ((x) + 0x29CU) #define HW_ENET_RMON_R_FRAG(x) (*(__I hw_enet_rmon_r_frag_t *) HW_ENET_RMON_R_FRAG_ADDR(x)) #define HW_ENET_RMON_R_FRAG_RD(x) (HW_ENET_RMON_R_FRAG(x).U) /*@}*/ /* * Constants & macros for individual ENET_RMON_R_FRAG bitfields */ /*! * @name Register ENET_RMON_R_FRAG, field COUNT[15:0] (RO) */ /*@{*/ #define BP_ENET_RMON_R_FRAG_COUNT (0U) /*!< Bit position for ENET_RMON_R_FRAG_COUNT. */ #define BM_ENET_RMON_R_FRAG_COUNT (0x0000FFFFU) /*!< Bit mask for ENET_RMON_R_FRAG_COUNT. */ #define BS_ENET_RMON_R_FRAG_COUNT (16U) /*!< Bit field size in bits for ENET_RMON_R_FRAG_COUNT. */ /*! @brief Read current value of the ENET_RMON_R_FRAG_COUNT field. */ #define BR_ENET_RMON_R_FRAG_COUNT(x) (HW_ENET_RMON_R_FRAG(x).B.COUNT) /*@}*/ /******************************************************************************* * HW_ENET_RMON_R_JAB - Rx Packets Greater Than MAX_FL Bytes and Bad CRC Statistic Register ******************************************************************************/ /*! * @brief HW_ENET_RMON_R_JAB - Rx Packets Greater Than MAX_FL Bytes and Bad CRC Statistic Register (RO) * * Reset value: 0x00000000U */ typedef union _hw_enet_rmon_r_jab { uint32_t U; struct _hw_enet_rmon_r_jab_bitfields { uint32_t COUNT : 16; /*!< [15:0] Packet count */ uint32_t RESERVED0 : 16; /*!< [31:16] */ } B; } hw_enet_rmon_r_jab_t; /*! * @name Constants and macros for entire ENET_RMON_R_JAB register */ /*@{*/ #define HW_ENET_RMON_R_JAB_ADDR(x) ((x) + 0x2A0U) #define HW_ENET_RMON_R_JAB(x) (*(__I hw_enet_rmon_r_jab_t *) HW_ENET_RMON_R_JAB_ADDR(x)) #define HW_ENET_RMON_R_JAB_RD(x) (HW_ENET_RMON_R_JAB(x).U) /*@}*/ /* * Constants & macros for individual ENET_RMON_R_JAB bitfields */ /*! * @name Register ENET_RMON_R_JAB, field COUNT[15:0] (RO) */ /*@{*/ #define BP_ENET_RMON_R_JAB_COUNT (0U) /*!< Bit position for ENET_RMON_R_JAB_COUNT. */ #define BM_ENET_RMON_R_JAB_COUNT (0x0000FFFFU) /*!< Bit mask for ENET_RMON_R_JAB_COUNT. */ #define BS_ENET_RMON_R_JAB_COUNT (16U) /*!< Bit field size in bits for ENET_RMON_R_JAB_COUNT. */ /*! @brief Read current value of the ENET_RMON_R_JAB_COUNT field. */ #define BR_ENET_RMON_R_JAB_COUNT(x) (HW_ENET_RMON_R_JAB(x).B.COUNT) /*@}*/ /******************************************************************************* * HW_ENET_RMON_R_P64 - Rx 64-Byte Packets Statistic Register ******************************************************************************/ /*! * @brief HW_ENET_RMON_R_P64 - Rx 64-Byte Packets Statistic Register (RO) * * Reset value: 0x00000000U */ typedef union _hw_enet_rmon_r_p64 { uint32_t U; struct _hw_enet_rmon_r_p64_bitfields { uint32_t COUNT : 16; /*!< [15:0] Packet count */ uint32_t RESERVED0 : 16; /*!< [31:16] */ } B; } hw_enet_rmon_r_p64_t; /*! * @name Constants and macros for entire ENET_RMON_R_P64 register */ /*@{*/ #define HW_ENET_RMON_R_P64_ADDR(x) ((x) + 0x2A8U) #define HW_ENET_RMON_R_P64(x) (*(__I hw_enet_rmon_r_p64_t *) HW_ENET_RMON_R_P64_ADDR(x)) #define HW_ENET_RMON_R_P64_RD(x) (HW_ENET_RMON_R_P64(x).U) /*@}*/ /* * Constants & macros for individual ENET_RMON_R_P64 bitfields */ /*! * @name Register ENET_RMON_R_P64, field COUNT[15:0] (RO) */ /*@{*/ #define BP_ENET_RMON_R_P64_COUNT (0U) /*!< Bit position for ENET_RMON_R_P64_COUNT. */ #define BM_ENET_RMON_R_P64_COUNT (0x0000FFFFU) /*!< Bit mask for ENET_RMON_R_P64_COUNT. */ #define BS_ENET_RMON_R_P64_COUNT (16U) /*!< Bit field size in bits for ENET_RMON_R_P64_COUNT. */ /*! @brief Read current value of the ENET_RMON_R_P64_COUNT field. */ #define BR_ENET_RMON_R_P64_COUNT(x) (HW_ENET_RMON_R_P64(x).B.COUNT) /*@}*/ /******************************************************************************* * HW_ENET_RMON_R_P65TO127 - Rx 65- to 127-Byte Packets Statistic Register ******************************************************************************/ /*! * @brief HW_ENET_RMON_R_P65TO127 - Rx 65- to 127-Byte Packets Statistic Register (RO) * * Reset value: 0x00000000U */ typedef union _hw_enet_rmon_r_p65to127 { uint32_t U; struct _hw_enet_rmon_r_p65to127_bitfields { uint32_t COUNT : 16; /*!< [15:0] Packet count */ uint32_t RESERVED0 : 16; /*!< [31:16] */ } B; } hw_enet_rmon_r_p65to127_t; /*! * @name Constants and macros for entire ENET_RMON_R_P65TO127 register */ /*@{*/ #define HW_ENET_RMON_R_P65TO127_ADDR(x) ((x) + 0x2ACU) #define HW_ENET_RMON_R_P65TO127(x) (*(__I hw_enet_rmon_r_p65to127_t *) HW_ENET_RMON_R_P65TO127_ADDR(x)) #define HW_ENET_RMON_R_P65TO127_RD(x) (HW_ENET_RMON_R_P65TO127(x).U) /*@}*/ /* * Constants & macros for individual ENET_RMON_R_P65TO127 bitfields */ /*! * @name Register ENET_RMON_R_P65TO127, field COUNT[15:0] (RO) */ /*@{*/ #define BP_ENET_RMON_R_P65TO127_COUNT (0U) /*!< Bit position for ENET_RMON_R_P65TO127_COUNT. */ #define BM_ENET_RMON_R_P65TO127_COUNT (0x0000FFFFU) /*!< Bit mask for ENET_RMON_R_P65TO127_COUNT. */ #define BS_ENET_RMON_R_P65TO127_COUNT (16U) /*!< Bit field size in bits for ENET_RMON_R_P65TO127_COUNT. */ /*! @brief Read current value of the ENET_RMON_R_P65TO127_COUNT field. */ #define BR_ENET_RMON_R_P65TO127_COUNT(x) (HW_ENET_RMON_R_P65TO127(x).B.COUNT) /*@}*/ /******************************************************************************* * HW_ENET_RMON_R_P128TO255 - Rx 128- to 255-Byte Packets Statistic Register ******************************************************************************/ /*! * @brief HW_ENET_RMON_R_P128TO255 - Rx 128- to 255-Byte Packets Statistic Register (RO) * * Reset value: 0x00000000U */ typedef union _hw_enet_rmon_r_p128to255 { uint32_t U; struct _hw_enet_rmon_r_p128to255_bitfields { uint32_t COUNT : 16; /*!< [15:0] Packet count */ uint32_t RESERVED0 : 16; /*!< [31:16] */ } B; } hw_enet_rmon_r_p128to255_t; /*! * @name Constants and macros for entire ENET_RMON_R_P128TO255 register */ /*@{*/ #define HW_ENET_RMON_R_P128TO255_ADDR(x) ((x) + 0x2B0U) #define HW_ENET_RMON_R_P128TO255(x) (*(__I hw_enet_rmon_r_p128to255_t *) HW_ENET_RMON_R_P128TO255_ADDR(x)) #define HW_ENET_RMON_R_P128TO255_RD(x) (HW_ENET_RMON_R_P128TO255(x).U) /*@}*/ /* * Constants & macros for individual ENET_RMON_R_P128TO255 bitfields */ /*! * @name Register ENET_RMON_R_P128TO255, field COUNT[15:0] (RO) */ /*@{*/ #define BP_ENET_RMON_R_P128TO255_COUNT (0U) /*!< Bit position for ENET_RMON_R_P128TO255_COUNT. */ #define BM_ENET_RMON_R_P128TO255_COUNT (0x0000FFFFU) /*!< Bit mask for ENET_RMON_R_P128TO255_COUNT. */ #define BS_ENET_RMON_R_P128TO255_COUNT (16U) /*!< Bit field size in bits for ENET_RMON_R_P128TO255_COUNT. */ /*! @brief Read current value of the ENET_RMON_R_P128TO255_COUNT field. */ #define BR_ENET_RMON_R_P128TO255_COUNT(x) (HW_ENET_RMON_R_P128TO255(x).B.COUNT) /*@}*/ /******************************************************************************* * HW_ENET_RMON_R_P256TO511 - Rx 256- to 511-Byte Packets Statistic Register ******************************************************************************/ /*! * @brief HW_ENET_RMON_R_P256TO511 - Rx 256- to 511-Byte Packets Statistic Register (RO) * * Reset value: 0x00000000U */ typedef union _hw_enet_rmon_r_p256to511 { uint32_t U; struct _hw_enet_rmon_r_p256to511_bitfields { uint32_t COUNT : 16; /*!< [15:0] Packet count */ uint32_t RESERVED0 : 16; /*!< [31:16] */ } B; } hw_enet_rmon_r_p256to511_t; /*! * @name Constants and macros for entire ENET_RMON_R_P256TO511 register */ /*@{*/ #define HW_ENET_RMON_R_P256TO511_ADDR(x) ((x) + 0x2B4U) #define HW_ENET_RMON_R_P256TO511(x) (*(__I hw_enet_rmon_r_p256to511_t *) HW_ENET_RMON_R_P256TO511_ADDR(x)) #define HW_ENET_RMON_R_P256TO511_RD(x) (HW_ENET_RMON_R_P256TO511(x).U) /*@}*/ /* * Constants & macros for individual ENET_RMON_R_P256TO511 bitfields */ /*! * @name Register ENET_RMON_R_P256TO511, field COUNT[15:0] (RO) */ /*@{*/ #define BP_ENET_RMON_R_P256TO511_COUNT (0U) /*!< Bit position for ENET_RMON_R_P256TO511_COUNT. */ #define BM_ENET_RMON_R_P256TO511_COUNT (0x0000FFFFU) /*!< Bit mask for ENET_RMON_R_P256TO511_COUNT. */ #define BS_ENET_RMON_R_P256TO511_COUNT (16U) /*!< Bit field size in bits for ENET_RMON_R_P256TO511_COUNT. */ /*! @brief Read current value of the ENET_RMON_R_P256TO511_COUNT field. */ #define BR_ENET_RMON_R_P256TO511_COUNT(x) (HW_ENET_RMON_R_P256TO511(x).B.COUNT) /*@}*/ /******************************************************************************* * HW_ENET_RMON_R_P512TO1023 - Rx 512- to 1023-Byte Packets Statistic Register ******************************************************************************/ /*! * @brief HW_ENET_RMON_R_P512TO1023 - Rx 512- to 1023-Byte Packets Statistic Register (RO) * * Reset value: 0x00000000U */ typedef union _hw_enet_rmon_r_p512to1023 { uint32_t U; struct _hw_enet_rmon_r_p512to1023_bitfields { uint32_t COUNT : 16; /*!< [15:0] Packet count */ uint32_t RESERVED0 : 16; /*!< [31:16] */ } B; } hw_enet_rmon_r_p512to1023_t; /*! * @name Constants and macros for entire ENET_RMON_R_P512TO1023 register */ /*@{*/ #define HW_ENET_RMON_R_P512TO1023_ADDR(x) ((x) + 0x2B8U) #define HW_ENET_RMON_R_P512TO1023(x) (*(__I hw_enet_rmon_r_p512to1023_t *) HW_ENET_RMON_R_P512TO1023_ADDR(x)) #define HW_ENET_RMON_R_P512TO1023_RD(x) (HW_ENET_RMON_R_P512TO1023(x).U) /*@}*/ /* * Constants & macros for individual ENET_RMON_R_P512TO1023 bitfields */ /*! * @name Register ENET_RMON_R_P512TO1023, field COUNT[15:0] (RO) */ /*@{*/ #define BP_ENET_RMON_R_P512TO1023_COUNT (0U) /*!< Bit position for ENET_RMON_R_P512TO1023_COUNT. */ #define BM_ENET_RMON_R_P512TO1023_COUNT (0x0000FFFFU) /*!< Bit mask for ENET_RMON_R_P512TO1023_COUNT. */ #define BS_ENET_RMON_R_P512TO1023_COUNT (16U) /*!< Bit field size in bits for ENET_RMON_R_P512TO1023_COUNT. */ /*! @brief Read current value of the ENET_RMON_R_P512TO1023_COUNT field. */ #define BR_ENET_RMON_R_P512TO1023_COUNT(x) (HW_ENET_RMON_R_P512TO1023(x).B.COUNT) /*@}*/ /******************************************************************************* * HW_ENET_RMON_R_P1024TO2047 - Rx 1024- to 2047-Byte Packets Statistic Register ******************************************************************************/ /*! * @brief HW_ENET_RMON_R_P1024TO2047 - Rx 1024- to 2047-Byte Packets Statistic Register (RO) * * Reset value: 0x00000000U */ typedef union _hw_enet_rmon_r_p1024to2047 { uint32_t U; struct _hw_enet_rmon_r_p1024to2047_bitfields { uint32_t COUNT : 16; /*!< [15:0] Packet count */ uint32_t RESERVED0 : 16; /*!< [31:16] */ } B; } hw_enet_rmon_r_p1024to2047_t; /*! * @name Constants and macros for entire ENET_RMON_R_P1024TO2047 register */ /*@{*/ #define HW_ENET_RMON_R_P1024TO2047_ADDR(x) ((x) + 0x2BCU) #define HW_ENET_RMON_R_P1024TO2047(x) (*(__I hw_enet_rmon_r_p1024to2047_t *) HW_ENET_RMON_R_P1024TO2047_ADDR(x)) #define HW_ENET_RMON_R_P1024TO2047_RD(x) (HW_ENET_RMON_R_P1024TO2047(x).U) /*@}*/ /* * Constants & macros for individual ENET_RMON_R_P1024TO2047 bitfields */ /*! * @name Register ENET_RMON_R_P1024TO2047, field COUNT[15:0] (RO) */ /*@{*/ #define BP_ENET_RMON_R_P1024TO2047_COUNT (0U) /*!< Bit position for ENET_RMON_R_P1024TO2047_COUNT. */ #define BM_ENET_RMON_R_P1024TO2047_COUNT (0x0000FFFFU) /*!< Bit mask for ENET_RMON_R_P1024TO2047_COUNT. */ #define BS_ENET_RMON_R_P1024TO2047_COUNT (16U) /*!< Bit field size in bits for ENET_RMON_R_P1024TO2047_COUNT. */ /*! @brief Read current value of the ENET_RMON_R_P1024TO2047_COUNT field. */ #define BR_ENET_RMON_R_P1024TO2047_COUNT(x) (HW_ENET_RMON_R_P1024TO2047(x).B.COUNT) /*@}*/ /******************************************************************************* * HW_ENET_RMON_R_P_GTE2048 - Rx Packets Greater than 2048 Bytes Statistic Register ******************************************************************************/ /*! * @brief HW_ENET_RMON_R_P_GTE2048 - Rx Packets Greater than 2048 Bytes Statistic Register (RO) * * Reset value: 0x00000000U */ typedef union _hw_enet_rmon_r_p_gte2048 { uint32_t U; struct _hw_enet_rmon_r_p_gte2048_bitfields { uint32_t COUNT : 16; /*!< [15:0] Packet count */ uint32_t RESERVED0 : 16; /*!< [31:16] */ } B; } hw_enet_rmon_r_p_gte2048_t; /*! * @name Constants and macros for entire ENET_RMON_R_P_GTE2048 register */ /*@{*/ #define HW_ENET_RMON_R_P_GTE2048_ADDR(x) ((x) + 0x2C0U) #define HW_ENET_RMON_R_P_GTE2048(x) (*(__I hw_enet_rmon_r_p_gte2048_t *) HW_ENET_RMON_R_P_GTE2048_ADDR(x)) #define HW_ENET_RMON_R_P_GTE2048_RD(x) (HW_ENET_RMON_R_P_GTE2048(x).U) /*@}*/ /* * Constants & macros for individual ENET_RMON_R_P_GTE2048 bitfields */ /*! * @name Register ENET_RMON_R_P_GTE2048, field COUNT[15:0] (RO) */ /*@{*/ #define BP_ENET_RMON_R_P_GTE2048_COUNT (0U) /*!< Bit position for ENET_RMON_R_P_GTE2048_COUNT. */ #define BM_ENET_RMON_R_P_GTE2048_COUNT (0x0000FFFFU) /*!< Bit mask for ENET_RMON_R_P_GTE2048_COUNT. */ #define BS_ENET_RMON_R_P_GTE2048_COUNT (16U) /*!< Bit field size in bits for ENET_RMON_R_P_GTE2048_COUNT. */ /*! @brief Read current value of the ENET_RMON_R_P_GTE2048_COUNT field. */ #define BR_ENET_RMON_R_P_GTE2048_COUNT(x) (HW_ENET_RMON_R_P_GTE2048(x).B.COUNT) /*@}*/ /******************************************************************************* * HW_ENET_RMON_R_OCTETS - Rx Octets Statistic Register ******************************************************************************/ /*! * @brief HW_ENET_RMON_R_OCTETS - Rx Octets Statistic Register (RO) * * Reset value: 0x00000000U */ typedef union _hw_enet_rmon_r_octets { uint32_t U; struct _hw_enet_rmon_r_octets_bitfields { uint32_t COUNT : 32; /*!< [31:0] Octet count */ } B; } hw_enet_rmon_r_octets_t; /*! * @name Constants and macros for entire ENET_RMON_R_OCTETS register */ /*@{*/ #define HW_ENET_RMON_R_OCTETS_ADDR(x) ((x) + 0x2C4U) #define HW_ENET_RMON_R_OCTETS(x) (*(__I hw_enet_rmon_r_octets_t *) HW_ENET_RMON_R_OCTETS_ADDR(x)) #define HW_ENET_RMON_R_OCTETS_RD(x) (HW_ENET_RMON_R_OCTETS(x).U) /*@}*/ /* * Constants & macros for individual ENET_RMON_R_OCTETS bitfields */ /*! * @name Register ENET_RMON_R_OCTETS, field COUNT[31:0] (RO) */ /*@{*/ #define BP_ENET_RMON_R_OCTETS_COUNT (0U) /*!< Bit position for ENET_RMON_R_OCTETS_COUNT. */ #define BM_ENET_RMON_R_OCTETS_COUNT (0xFFFFFFFFU) /*!< Bit mask for ENET_RMON_R_OCTETS_COUNT. */ #define BS_ENET_RMON_R_OCTETS_COUNT (32U) /*!< Bit field size in bits for ENET_RMON_R_OCTETS_COUNT. */ /*! @brief Read current value of the ENET_RMON_R_OCTETS_COUNT field. */ #define BR_ENET_RMON_R_OCTETS_COUNT(x) (HW_ENET_RMON_R_OCTETS(x).U) /*@}*/ /******************************************************************************* * HW_ENET_IEEE_R_DROP - Frames not Counted Correctly Statistic Register ******************************************************************************/ /*! * @brief HW_ENET_IEEE_R_DROP - Frames not Counted Correctly Statistic Register (RO) * * Reset value: 0x00000000U * * Counter increments if a frame with invalid or missing SFD character is * detected and has been dropped. None of the other counters increments if this counter * increments. */ typedef union _hw_enet_ieee_r_drop { uint32_t U; struct _hw_enet_ieee_r_drop_bitfields { uint32_t COUNT : 16; /*!< [15:0] Frame count */ uint32_t RESERVED0 : 16; /*!< [31:16] */ } B; } hw_enet_ieee_r_drop_t; /*! * @name Constants and macros for entire ENET_IEEE_R_DROP register */ /*@{*/ #define HW_ENET_IEEE_R_DROP_ADDR(x) ((x) + 0x2C8U) #define HW_ENET_IEEE_R_DROP(x) (*(__I hw_enet_ieee_r_drop_t *) HW_ENET_IEEE_R_DROP_ADDR(x)) #define HW_ENET_IEEE_R_DROP_RD(x) (HW_ENET_IEEE_R_DROP(x).U) /*@}*/ /* * Constants & macros for individual ENET_IEEE_R_DROP bitfields */ /*! * @name Register ENET_IEEE_R_DROP, field COUNT[15:0] (RO) */ /*@{*/ #define BP_ENET_IEEE_R_DROP_COUNT (0U) /*!< Bit position for ENET_IEEE_R_DROP_COUNT. */ #define BM_ENET_IEEE_R_DROP_COUNT (0x0000FFFFU) /*!< Bit mask for ENET_IEEE_R_DROP_COUNT. */ #define BS_ENET_IEEE_R_DROP_COUNT (16U) /*!< Bit field size in bits for ENET_IEEE_R_DROP_COUNT. */ /*! @brief Read current value of the ENET_IEEE_R_DROP_COUNT field. */ #define BR_ENET_IEEE_R_DROP_COUNT(x) (HW_ENET_IEEE_R_DROP(x).B.COUNT) /*@}*/ /******************************************************************************* * HW_ENET_IEEE_R_FRAME_OK - Frames Received OK Statistic Register ******************************************************************************/ /*! * @brief HW_ENET_IEEE_R_FRAME_OK - Frames Received OK Statistic Register (RO) * * Reset value: 0x00000000U */ typedef union _hw_enet_ieee_r_frame_ok { uint32_t U; struct _hw_enet_ieee_r_frame_ok_bitfields { uint32_t COUNT : 16; /*!< [15:0] Frame count */ uint32_t RESERVED0 : 16; /*!< [31:16] */ } B; } hw_enet_ieee_r_frame_ok_t; /*! * @name Constants and macros for entire ENET_IEEE_R_FRAME_OK register */ /*@{*/ #define HW_ENET_IEEE_R_FRAME_OK_ADDR(x) ((x) + 0x2CCU) #define HW_ENET_IEEE_R_FRAME_OK(x) (*(__I hw_enet_ieee_r_frame_ok_t *) HW_ENET_IEEE_R_FRAME_OK_ADDR(x)) #define HW_ENET_IEEE_R_FRAME_OK_RD(x) (HW_ENET_IEEE_R_FRAME_OK(x).U) /*@}*/ /* * Constants & macros for individual ENET_IEEE_R_FRAME_OK bitfields */ /*! * @name Register ENET_IEEE_R_FRAME_OK, field COUNT[15:0] (RO) */ /*@{*/ #define BP_ENET_IEEE_R_FRAME_OK_COUNT (0U) /*!< Bit position for ENET_IEEE_R_FRAME_OK_COUNT. */ #define BM_ENET_IEEE_R_FRAME_OK_COUNT (0x0000FFFFU) /*!< Bit mask for ENET_IEEE_R_FRAME_OK_COUNT. */ #define BS_ENET_IEEE_R_FRAME_OK_COUNT (16U) /*!< Bit field size in bits for ENET_IEEE_R_FRAME_OK_COUNT. */ /*! @brief Read current value of the ENET_IEEE_R_FRAME_OK_COUNT field. */ #define BR_ENET_IEEE_R_FRAME_OK_COUNT(x) (HW_ENET_IEEE_R_FRAME_OK(x).B.COUNT) /*@}*/ /******************************************************************************* * HW_ENET_IEEE_R_CRC - Frames Received with CRC Error Statistic Register ******************************************************************************/ /*! * @brief HW_ENET_IEEE_R_CRC - Frames Received with CRC Error Statistic Register (RO) * * Reset value: 0x00000000U */ typedef union _hw_enet_ieee_r_crc { uint32_t U; struct _hw_enet_ieee_r_crc_bitfields { uint32_t COUNT : 16; /*!< [15:0] Frame count */ uint32_t RESERVED0 : 16; /*!< [31:16] */ } B; } hw_enet_ieee_r_crc_t; /*! * @name Constants and macros for entire ENET_IEEE_R_CRC register */ /*@{*/ #define HW_ENET_IEEE_R_CRC_ADDR(x) ((x) + 0x2D0U) #define HW_ENET_IEEE_R_CRC(x) (*(__I hw_enet_ieee_r_crc_t *) HW_ENET_IEEE_R_CRC_ADDR(x)) #define HW_ENET_IEEE_R_CRC_RD(x) (HW_ENET_IEEE_R_CRC(x).U) /*@}*/ /* * Constants & macros for individual ENET_IEEE_R_CRC bitfields */ /*! * @name Register ENET_IEEE_R_CRC, field COUNT[15:0] (RO) */ /*@{*/ #define BP_ENET_IEEE_R_CRC_COUNT (0U) /*!< Bit position for ENET_IEEE_R_CRC_COUNT. */ #define BM_ENET_IEEE_R_CRC_COUNT (0x0000FFFFU) /*!< Bit mask for ENET_IEEE_R_CRC_COUNT. */ #define BS_ENET_IEEE_R_CRC_COUNT (16U) /*!< Bit field size in bits for ENET_IEEE_R_CRC_COUNT. */ /*! @brief Read current value of the ENET_IEEE_R_CRC_COUNT field. */ #define BR_ENET_IEEE_R_CRC_COUNT(x) (HW_ENET_IEEE_R_CRC(x).B.COUNT) /*@}*/ /******************************************************************************* * HW_ENET_IEEE_R_ALIGN - Frames Received with Alignment Error Statistic Register ******************************************************************************/ /*! * @brief HW_ENET_IEEE_R_ALIGN - Frames Received with Alignment Error Statistic Register (RO) * * Reset value: 0x00000000U */ typedef union _hw_enet_ieee_r_align { uint32_t U; struct _hw_enet_ieee_r_align_bitfields { uint32_t COUNT : 16; /*!< [15:0] Frame count */ uint32_t RESERVED0 : 16; /*!< [31:16] */ } B; } hw_enet_ieee_r_align_t; /*! * @name Constants and macros for entire ENET_IEEE_R_ALIGN register */ /*@{*/ #define HW_ENET_IEEE_R_ALIGN_ADDR(x) ((x) + 0x2D4U) #define HW_ENET_IEEE_R_ALIGN(x) (*(__I hw_enet_ieee_r_align_t *) HW_ENET_IEEE_R_ALIGN_ADDR(x)) #define HW_ENET_IEEE_R_ALIGN_RD(x) (HW_ENET_IEEE_R_ALIGN(x).U) /*@}*/ /* * Constants & macros for individual ENET_IEEE_R_ALIGN bitfields */ /*! * @name Register ENET_IEEE_R_ALIGN, field COUNT[15:0] (RO) */ /*@{*/ #define BP_ENET_IEEE_R_ALIGN_COUNT (0U) /*!< Bit position for ENET_IEEE_R_ALIGN_COUNT. */ #define BM_ENET_IEEE_R_ALIGN_COUNT (0x0000FFFFU) /*!< Bit mask for ENET_IEEE_R_ALIGN_COUNT. */ #define BS_ENET_IEEE_R_ALIGN_COUNT (16U) /*!< Bit field size in bits for ENET_IEEE_R_ALIGN_COUNT. */ /*! @brief Read current value of the ENET_IEEE_R_ALIGN_COUNT field. */ #define BR_ENET_IEEE_R_ALIGN_COUNT(x) (HW_ENET_IEEE_R_ALIGN(x).B.COUNT) /*@}*/ /******************************************************************************* * HW_ENET_IEEE_R_MACERR - Receive FIFO Overflow Count Statistic Register ******************************************************************************/ /*! * @brief HW_ENET_IEEE_R_MACERR - Receive FIFO Overflow Count Statistic Register (RO) * * Reset value: 0x00000000U */ typedef union _hw_enet_ieee_r_macerr { uint32_t U; struct _hw_enet_ieee_r_macerr_bitfields { uint32_t COUNT : 16; /*!< [15:0] Count */ uint32_t RESERVED0 : 16; /*!< [31:16] */ } B; } hw_enet_ieee_r_macerr_t; /*! * @name Constants and macros for entire ENET_IEEE_R_MACERR register */ /*@{*/ #define HW_ENET_IEEE_R_MACERR_ADDR(x) ((x) + 0x2D8U) #define HW_ENET_IEEE_R_MACERR(x) (*(__I hw_enet_ieee_r_macerr_t *) HW_ENET_IEEE_R_MACERR_ADDR(x)) #define HW_ENET_IEEE_R_MACERR_RD(x) (HW_ENET_IEEE_R_MACERR(x).U) /*@}*/ /* * Constants & macros for individual ENET_IEEE_R_MACERR bitfields */ /*! * @name Register ENET_IEEE_R_MACERR, field COUNT[15:0] (RO) */ /*@{*/ #define BP_ENET_IEEE_R_MACERR_COUNT (0U) /*!< Bit position for ENET_IEEE_R_MACERR_COUNT. */ #define BM_ENET_IEEE_R_MACERR_COUNT (0x0000FFFFU) /*!< Bit mask for ENET_IEEE_R_MACERR_COUNT. */ #define BS_ENET_IEEE_R_MACERR_COUNT (16U) /*!< Bit field size in bits for ENET_IEEE_R_MACERR_COUNT. */ /*! @brief Read current value of the ENET_IEEE_R_MACERR_COUNT field. */ #define BR_ENET_IEEE_R_MACERR_COUNT(x) (HW_ENET_IEEE_R_MACERR(x).B.COUNT) /*@}*/ /******************************************************************************* * HW_ENET_IEEE_R_FDXFC - Flow Control Pause Frames Received Statistic Register ******************************************************************************/ /*! * @brief HW_ENET_IEEE_R_FDXFC - Flow Control Pause Frames Received Statistic Register (RO) * * Reset value: 0x00000000U */ typedef union _hw_enet_ieee_r_fdxfc { uint32_t U; struct _hw_enet_ieee_r_fdxfc_bitfields { uint32_t COUNT : 16; /*!< [15:0] Pause frame count */ uint32_t RESERVED0 : 16; /*!< [31:16] */ } B; } hw_enet_ieee_r_fdxfc_t; /*! * @name Constants and macros for entire ENET_IEEE_R_FDXFC register */ /*@{*/ #define HW_ENET_IEEE_R_FDXFC_ADDR(x) ((x) + 0x2DCU) #define HW_ENET_IEEE_R_FDXFC(x) (*(__I hw_enet_ieee_r_fdxfc_t *) HW_ENET_IEEE_R_FDXFC_ADDR(x)) #define HW_ENET_IEEE_R_FDXFC_RD(x) (HW_ENET_IEEE_R_FDXFC(x).U) /*@}*/ /* * Constants & macros for individual ENET_IEEE_R_FDXFC bitfields */ /*! * @name Register ENET_IEEE_R_FDXFC, field COUNT[15:0] (RO) */ /*@{*/ #define BP_ENET_IEEE_R_FDXFC_COUNT (0U) /*!< Bit position for ENET_IEEE_R_FDXFC_COUNT. */ #define BM_ENET_IEEE_R_FDXFC_COUNT (0x0000FFFFU) /*!< Bit mask for ENET_IEEE_R_FDXFC_COUNT. */ #define BS_ENET_IEEE_R_FDXFC_COUNT (16U) /*!< Bit field size in bits for ENET_IEEE_R_FDXFC_COUNT. */ /*! @brief Read current value of the ENET_IEEE_R_FDXFC_COUNT field. */ #define BR_ENET_IEEE_R_FDXFC_COUNT(x) (HW_ENET_IEEE_R_FDXFC(x).B.COUNT) /*@}*/ /******************************************************************************* * HW_ENET_IEEE_R_OCTETS_OK - Octet Count for Frames Received without Error Statistic Register ******************************************************************************/ /*! * @brief HW_ENET_IEEE_R_OCTETS_OK - Octet Count for Frames Received without Error Statistic Register (RO) * * Reset value: 0x00000000U */ typedef union _hw_enet_ieee_r_octets_ok { uint32_t U; struct _hw_enet_ieee_r_octets_ok_bitfields { uint32_t COUNT : 32; /*!< [31:0] Octet count */ } B; } hw_enet_ieee_r_octets_ok_t; /*! * @name Constants and macros for entire ENET_IEEE_R_OCTETS_OK register */ /*@{*/ #define HW_ENET_IEEE_R_OCTETS_OK_ADDR(x) ((x) + 0x2E0U) #define HW_ENET_IEEE_R_OCTETS_OK(x) (*(__I hw_enet_ieee_r_octets_ok_t *) HW_ENET_IEEE_R_OCTETS_OK_ADDR(x)) #define HW_ENET_IEEE_R_OCTETS_OK_RD(x) (HW_ENET_IEEE_R_OCTETS_OK(x).U) /*@}*/ /* * Constants & macros for individual ENET_IEEE_R_OCTETS_OK bitfields */ /*! * @name Register ENET_IEEE_R_OCTETS_OK, field COUNT[31:0] (RO) */ /*@{*/ #define BP_ENET_IEEE_R_OCTETS_OK_COUNT (0U) /*!< Bit position for ENET_IEEE_R_OCTETS_OK_COUNT. */ #define BM_ENET_IEEE_R_OCTETS_OK_COUNT (0xFFFFFFFFU) /*!< Bit mask for ENET_IEEE_R_OCTETS_OK_COUNT. */ #define BS_ENET_IEEE_R_OCTETS_OK_COUNT (32U) /*!< Bit field size in bits for ENET_IEEE_R_OCTETS_OK_COUNT. */ /*! @brief Read current value of the ENET_IEEE_R_OCTETS_OK_COUNT field. */ #define BR_ENET_IEEE_R_OCTETS_OK_COUNT(x) (HW_ENET_IEEE_R_OCTETS_OK(x).U) /*@}*/ /******************************************************************************* * HW_ENET_ATCR - Adjustable Timer Control Register ******************************************************************************/ /*! * @brief HW_ENET_ATCR - Adjustable Timer Control Register (RW) * * Reset value: 0x00000000U * * ATCR command fields can trigger the corresponding events directly. It is not * necessary to preserve any of the configuration fields when a command field is * set in the register, that is, no read-modify-write is required. The fields are * automatically cleared after the command completes. */ typedef union _hw_enet_atcr { uint32_t U; struct _hw_enet_atcr_bitfields { uint32_t EN : 1; /*!< [0] Enable Timer */ uint32_t RESERVED0 : 1; /*!< [1] */ uint32_t OFFEN : 1; /*!< [2] Enable One-Shot Offset Event */ uint32_t OFFRST : 1; /*!< [3] Reset Timer On Offset Event */ uint32_t PEREN : 1; /*!< [4] Enable Periodical Event */ uint32_t RESERVED1 : 2; /*!< [6:5] */ uint32_t PINPER : 1; /*!< [7] */ uint32_t RESERVED2 : 1; /*!< [8] */ uint32_t RESTART : 1; /*!< [9] Reset Timer */ uint32_t RESERVED3 : 1; /*!< [10] */ uint32_t CAPTURE : 1; /*!< [11] Capture Timer Value */ uint32_t RESERVED4 : 1; /*!< [12] */ uint32_t SLAVE : 1; /*!< [13] Enable Timer Slave Mode */ uint32_t RESERVED5 : 18; /*!< [31:14] */ } B; } hw_enet_atcr_t; /*! * @name Constants and macros for entire ENET_ATCR register */ /*@{*/ #define HW_ENET_ATCR_ADDR(x) ((x) + 0x400U) #define HW_ENET_ATCR(x) (*(__IO hw_enet_atcr_t *) HW_ENET_ATCR_ADDR(x)) #define HW_ENET_ATCR_RD(x) (HW_ENET_ATCR(x).U) #define HW_ENET_ATCR_WR(x, v) (HW_ENET_ATCR(x).U = (v)) #define HW_ENET_ATCR_SET(x, v) (HW_ENET_ATCR_WR(x, HW_ENET_ATCR_RD(x) | (v))) #define HW_ENET_ATCR_CLR(x, v) (HW_ENET_ATCR_WR(x, HW_ENET_ATCR_RD(x) & ~(v))) #define HW_ENET_ATCR_TOG(x, v) (HW_ENET_ATCR_WR(x, HW_ENET_ATCR_RD(x) ^ (v))) /*@}*/ /* * Constants & macros for individual ENET_ATCR bitfields */ /*! * @name Register ENET_ATCR, field EN[0] (RW) * * Values: * - 0 - The timer stops at the current value. * - 1 - The timer starts incrementing. */ /*@{*/ #define BP_ENET_ATCR_EN (0U) /*!< Bit position for ENET_ATCR_EN. */ #define BM_ENET_ATCR_EN (0x00000001U) /*!< Bit mask for ENET_ATCR_EN. */ #define BS_ENET_ATCR_EN (1U) /*!< Bit field size in bits for ENET_ATCR_EN. */ /*! @brief Read current value of the ENET_ATCR_EN field. */ #define BR_ENET_ATCR_EN(x) (BITBAND_ACCESS32(HW_ENET_ATCR_ADDR(x), BP_ENET_ATCR_EN)) /*! @brief Format value for bitfield ENET_ATCR_EN. */ #define BF_ENET_ATCR_EN(v) ((uint32_t)((uint32_t)(v) << BP_ENET_ATCR_EN) & BM_ENET_ATCR_EN) /*! @brief Set the EN field to a new value. */ #define BW_ENET_ATCR_EN(x, v) (BITBAND_ACCESS32(HW_ENET_ATCR_ADDR(x), BP_ENET_ATCR_EN) = (v)) /*@}*/ /*! * @name Register ENET_ATCR, field OFFEN[2] (RW) * * Values: * - 0 - Disable. * - 1 - The timer can be reset to zero when the given offset time is reached * (offset event). The field is cleared when the offset event is reached, so no * further event occurs until the field is set again. The timer offset value * must be set before setting this field. */ /*@{*/ #define BP_ENET_ATCR_OFFEN (2U) /*!< Bit position for ENET_ATCR_OFFEN. */ #define BM_ENET_ATCR_OFFEN (0x00000004U) /*!< Bit mask for ENET_ATCR_OFFEN. */ #define BS_ENET_ATCR_OFFEN (1U) /*!< Bit field size in bits for ENET_ATCR_OFFEN. */ /*! @brief Read current value of the ENET_ATCR_OFFEN field. */ #define BR_ENET_ATCR_OFFEN(x) (BITBAND_ACCESS32(HW_ENET_ATCR_ADDR(x), BP_ENET_ATCR_OFFEN)) /*! @brief Format value for bitfield ENET_ATCR_OFFEN. */ #define BF_ENET_ATCR_OFFEN(v) ((uint32_t)((uint32_t)(v) << BP_ENET_ATCR_OFFEN) & BM_ENET_ATCR_OFFEN) /*! @brief Set the OFFEN field to a new value. */ #define BW_ENET_ATCR_OFFEN(x, v) (BITBAND_ACCESS32(HW_ENET_ATCR_ADDR(x), BP_ENET_ATCR_OFFEN) = (v)) /*@}*/ /*! * @name Register ENET_ATCR, field OFFRST[3] (RW) * * Values: * - 0 - The timer is not affected and no action occurs, besides clearing OFFEN, * when the offset is reached. * - 1 - If OFFEN is set, the timer resets to zero when the offset setting is * reached. The offset event does not cause a timer interrupt. */ /*@{*/ #define BP_ENET_ATCR_OFFRST (3U) /*!< Bit position for ENET_ATCR_OFFRST. */ #define BM_ENET_ATCR_OFFRST (0x00000008U) /*!< Bit mask for ENET_ATCR_OFFRST. */ #define BS_ENET_ATCR_OFFRST (1U) /*!< Bit field size in bits for ENET_ATCR_OFFRST. */ /*! @brief Read current value of the ENET_ATCR_OFFRST field. */ #define BR_ENET_ATCR_OFFRST(x) (BITBAND_ACCESS32(HW_ENET_ATCR_ADDR(x), BP_ENET_ATCR_OFFRST)) /*! @brief Format value for bitfield ENET_ATCR_OFFRST. */ #define BF_ENET_ATCR_OFFRST(v) ((uint32_t)((uint32_t)(v) << BP_ENET_ATCR_OFFRST) & BM_ENET_ATCR_OFFRST) /*! @brief Set the OFFRST field to a new value. */ #define BW_ENET_ATCR_OFFRST(x, v) (BITBAND_ACCESS32(HW_ENET_ATCR_ADDR(x), BP_ENET_ATCR_OFFRST) = (v)) /*@}*/ /*! * @name Register ENET_ATCR, field PEREN[4] (RW) * * Values: * - 0 - Disable. * - 1 - A period event interrupt can be generated (EIR[TS_TIMER]) and the event * signal output is asserted when the timer wraps around according to the * periodic setting ATPER. The timer period value must be set before setting * this bit. Not all devices contain the event signal output. See the chip * configuration details. */ /*@{*/ #define BP_ENET_ATCR_PEREN (4U) /*!< Bit position for ENET_ATCR_PEREN. */ #define BM_ENET_ATCR_PEREN (0x00000010U) /*!< Bit mask for ENET_ATCR_PEREN. */ #define BS_ENET_ATCR_PEREN (1U) /*!< Bit field size in bits for ENET_ATCR_PEREN. */ /*! @brief Read current value of the ENET_ATCR_PEREN field. */ #define BR_ENET_ATCR_PEREN(x) (BITBAND_ACCESS32(HW_ENET_ATCR_ADDR(x), BP_ENET_ATCR_PEREN)) /*! @brief Format value for bitfield ENET_ATCR_PEREN. */ #define BF_ENET_ATCR_PEREN(v) ((uint32_t)((uint32_t)(v) << BP_ENET_ATCR_PEREN) & BM_ENET_ATCR_PEREN) /*! @brief Set the PEREN field to a new value. */ #define BW_ENET_ATCR_PEREN(x, v) (BITBAND_ACCESS32(HW_ENET_ATCR_ADDR(x), BP_ENET_ATCR_PEREN) = (v)) /*@}*/ /*! * @name Register ENET_ATCR, field PINPER[7] (RW) * * Enables event signal output assertion on period event. Not all devices * contain the event signal output. See the chip configuration details. * * Values: * - 0 - Disable. * - 1 - Enable. */ /*@{*/ #define BP_ENET_ATCR_PINPER (7U) /*!< Bit position for ENET_ATCR_PINPER. */ #define BM_ENET_ATCR_PINPER (0x00000080U) /*!< Bit mask for ENET_ATCR_PINPER. */ #define BS_ENET_ATCR_PINPER (1U) /*!< Bit field size in bits for ENET_ATCR_PINPER. */ /*! @brief Read current value of the ENET_ATCR_PINPER field. */ #define BR_ENET_ATCR_PINPER(x) (BITBAND_ACCESS32(HW_ENET_ATCR_ADDR(x), BP_ENET_ATCR_PINPER)) /*! @brief Format value for bitfield ENET_ATCR_PINPER. */ #define BF_ENET_ATCR_PINPER(v) ((uint32_t)((uint32_t)(v) << BP_ENET_ATCR_PINPER) & BM_ENET_ATCR_PINPER) /*! @brief Set the PINPER field to a new value. */ #define BW_ENET_ATCR_PINPER(x, v) (BITBAND_ACCESS32(HW_ENET_ATCR_ADDR(x), BP_ENET_ATCR_PINPER) = (v)) /*@}*/ /*! * @name Register ENET_ATCR, field RESTART[9] (RW) * * Resets the timer to zero. This has no effect on the counter enable. If the * counter is enabled when this field is set, the timer is reset to zero and starts * counting from there. When set, all other fields are ignored during a write. */ /*@{*/ #define BP_ENET_ATCR_RESTART (9U) /*!< Bit position for ENET_ATCR_RESTART. */ #define BM_ENET_ATCR_RESTART (0x00000200U) /*!< Bit mask for ENET_ATCR_RESTART. */ #define BS_ENET_ATCR_RESTART (1U) /*!< Bit field size in bits for ENET_ATCR_RESTART. */ /*! @brief Read current value of the ENET_ATCR_RESTART field. */ #define BR_ENET_ATCR_RESTART(x) (BITBAND_ACCESS32(HW_ENET_ATCR_ADDR(x), BP_ENET_ATCR_RESTART)) /*! @brief Format value for bitfield ENET_ATCR_RESTART. */ #define BF_ENET_ATCR_RESTART(v) ((uint32_t)((uint32_t)(v) << BP_ENET_ATCR_RESTART) & BM_ENET_ATCR_RESTART) /*! @brief Set the RESTART field to a new value. */ #define BW_ENET_ATCR_RESTART(x, v) (BITBAND_ACCESS32(HW_ENET_ATCR_ADDR(x), BP_ENET_ATCR_RESTART) = (v)) /*@}*/ /*! * @name Register ENET_ATCR, field CAPTURE[11] (RW) * * Values: * - 0 - No effect. * - 1 - The current time is captured and can be read from the ATVR register. */ /*@{*/ #define BP_ENET_ATCR_CAPTURE (11U) /*!< Bit position for ENET_ATCR_CAPTURE. */ #define BM_ENET_ATCR_CAPTURE (0x00000800U) /*!< Bit mask for ENET_ATCR_CAPTURE. */ #define BS_ENET_ATCR_CAPTURE (1U) /*!< Bit field size in bits for ENET_ATCR_CAPTURE. */ /*! @brief Read current value of the ENET_ATCR_CAPTURE field. */ #define BR_ENET_ATCR_CAPTURE(x) (BITBAND_ACCESS32(HW_ENET_ATCR_ADDR(x), BP_ENET_ATCR_CAPTURE)) /*! @brief Format value for bitfield ENET_ATCR_CAPTURE. */ #define BF_ENET_ATCR_CAPTURE(v) ((uint32_t)((uint32_t)(v) << BP_ENET_ATCR_CAPTURE) & BM_ENET_ATCR_CAPTURE) /*! @brief Set the CAPTURE field to a new value. */ #define BW_ENET_ATCR_CAPTURE(x, v) (BITBAND_ACCESS32(HW_ENET_ATCR_ADDR(x), BP_ENET_ATCR_CAPTURE) = (v)) /*@}*/ /*! * @name Register ENET_ATCR, field SLAVE[13] (RW) * * Values: * - 0 - The timer is active and all configuration fields in this register are * relevant. * - 1 - The internal timer is disabled and the externally provided timer value * is used. All other fields, except CAPTURE, in this register have no * effect. CAPTURE can still be used to capture the current timer value. */ /*@{*/ #define BP_ENET_ATCR_SLAVE (13U) /*!< Bit position for ENET_ATCR_SLAVE. */ #define BM_ENET_ATCR_SLAVE (0x00002000U) /*!< Bit mask for ENET_ATCR_SLAVE. */ #define BS_ENET_ATCR_SLAVE (1U) /*!< Bit field size in bits for ENET_ATCR_SLAVE. */ /*! @brief Read current value of the ENET_ATCR_SLAVE field. */ #define BR_ENET_ATCR_SLAVE(x) (BITBAND_ACCESS32(HW_ENET_ATCR_ADDR(x), BP_ENET_ATCR_SLAVE)) /*! @brief Format value for bitfield ENET_ATCR_SLAVE. */ #define BF_ENET_ATCR_SLAVE(v) ((uint32_t)((uint32_t)(v) << BP_ENET_ATCR_SLAVE) & BM_ENET_ATCR_SLAVE) /*! @brief Set the SLAVE field to a new value. */ #define BW_ENET_ATCR_SLAVE(x, v) (BITBAND_ACCESS32(HW_ENET_ATCR_ADDR(x), BP_ENET_ATCR_SLAVE) = (v)) /*@}*/ /******************************************************************************* * HW_ENET_ATVR - Timer Value Register ******************************************************************************/ /*! * @brief HW_ENET_ATVR - Timer Value Register (RW) * * Reset value: 0x00000000U */ typedef union _hw_enet_atvr { uint32_t U; struct _hw_enet_atvr_bitfields { uint32_t ATIME : 32; /*!< [31:0] */ } B; } hw_enet_atvr_t; /*! * @name Constants and macros for entire ENET_ATVR register */ /*@{*/ #define HW_ENET_ATVR_ADDR(x) ((x) + 0x404U) #define HW_ENET_ATVR(x) (*(__IO hw_enet_atvr_t *) HW_ENET_ATVR_ADDR(x)) #define HW_ENET_ATVR_RD(x) (HW_ENET_ATVR(x).U) #define HW_ENET_ATVR_WR(x, v) (HW_ENET_ATVR(x).U = (v)) #define HW_ENET_ATVR_SET(x, v) (HW_ENET_ATVR_WR(x, HW_ENET_ATVR_RD(x) | (v))) #define HW_ENET_ATVR_CLR(x, v) (HW_ENET_ATVR_WR(x, HW_ENET_ATVR_RD(x) & ~(v))) #define HW_ENET_ATVR_TOG(x, v) (HW_ENET_ATVR_WR(x, HW_ENET_ATVR_RD(x) ^ (v))) /*@}*/ /* * Constants & macros for individual ENET_ATVR bitfields */ /*! * @name Register ENET_ATVR, field ATIME[31:0] (RW) * * A write sets the timer. A read returns the last captured value. To read the * current value, issue a capture command (set ATCR[CAPTURE]) prior to reading * this register. */ /*@{*/ #define BP_ENET_ATVR_ATIME (0U) /*!< Bit position for ENET_ATVR_ATIME. */ #define BM_ENET_ATVR_ATIME (0xFFFFFFFFU) /*!< Bit mask for ENET_ATVR_ATIME. */ #define BS_ENET_ATVR_ATIME (32U) /*!< Bit field size in bits for ENET_ATVR_ATIME. */ /*! @brief Read current value of the ENET_ATVR_ATIME field. */ #define BR_ENET_ATVR_ATIME(x) (HW_ENET_ATVR(x).U) /*! @brief Format value for bitfield ENET_ATVR_ATIME. */ #define BF_ENET_ATVR_ATIME(v) ((uint32_t)((uint32_t)(v) << BP_ENET_ATVR_ATIME) & BM_ENET_ATVR_ATIME) /*! @brief Set the ATIME field to a new value. */ #define BW_ENET_ATVR_ATIME(x, v) (HW_ENET_ATVR_WR(x, v)) /*@}*/ /******************************************************************************* * HW_ENET_ATOFF - Timer Offset Register ******************************************************************************/ /*! * @brief HW_ENET_ATOFF - Timer Offset Register (RW) * * Reset value: 0x00000000U */ typedef union _hw_enet_atoff { uint32_t U; struct _hw_enet_atoff_bitfields { uint32_t OFFSET : 32; /*!< [31:0] */ } B; } hw_enet_atoff_t; /*! * @name Constants and macros for entire ENET_ATOFF register */ /*@{*/ #define HW_ENET_ATOFF_ADDR(x) ((x) + 0x408U) #define HW_ENET_ATOFF(x) (*(__IO hw_enet_atoff_t *) HW_ENET_ATOFF_ADDR(x)) #define HW_ENET_ATOFF_RD(x) (HW_ENET_ATOFF(x).U) #define HW_ENET_ATOFF_WR(x, v) (HW_ENET_ATOFF(x).U = (v)) #define HW_ENET_ATOFF_SET(x, v) (HW_ENET_ATOFF_WR(x, HW_ENET_ATOFF_RD(x) | (v))) #define HW_ENET_ATOFF_CLR(x, v) (HW_ENET_ATOFF_WR(x, HW_ENET_ATOFF_RD(x) & ~(v))) #define HW_ENET_ATOFF_TOG(x, v) (HW_ENET_ATOFF_WR(x, HW_ENET_ATOFF_RD(x) ^ (v))) /*@}*/ /* * Constants & macros for individual ENET_ATOFF bitfields */ /*! * @name Register ENET_ATOFF, field OFFSET[31:0] (RW) * * Offset value for one-shot event generation. When the timer reaches the value, * an event can be generated to reset the counter. If the increment value in * ATINC is given in true nanoseconds, this value is also given in true nanoseconds. */ /*@{*/ #define BP_ENET_ATOFF_OFFSET (0U) /*!< Bit position for ENET_ATOFF_OFFSET. */ #define BM_ENET_ATOFF_OFFSET (0xFFFFFFFFU) /*!< Bit mask for ENET_ATOFF_OFFSET. */ #define BS_ENET_ATOFF_OFFSET (32U) /*!< Bit field size in bits for ENET_ATOFF_OFFSET. */ /*! @brief Read current value of the ENET_ATOFF_OFFSET field. */ #define BR_ENET_ATOFF_OFFSET(x) (HW_ENET_ATOFF(x).U) /*! @brief Format value for bitfield ENET_ATOFF_OFFSET. */ #define BF_ENET_ATOFF_OFFSET(v) ((uint32_t)((uint32_t)(v) << BP_ENET_ATOFF_OFFSET) & BM_ENET_ATOFF_OFFSET) /*! @brief Set the OFFSET field to a new value. */ #define BW_ENET_ATOFF_OFFSET(x, v) (HW_ENET_ATOFF_WR(x, v)) /*@}*/ /******************************************************************************* * HW_ENET_ATPER - Timer Period Register ******************************************************************************/ /*! * @brief HW_ENET_ATPER - Timer Period Register (RW) * * Reset value: 0x3B9ACA00U */ typedef union _hw_enet_atper { uint32_t U; struct _hw_enet_atper_bitfields { uint32_t PERIOD : 32; /*!< [31:0] */ } B; } hw_enet_atper_t; /*! * @name Constants and macros for entire ENET_ATPER register */ /*@{*/ #define HW_ENET_ATPER_ADDR(x) ((x) + 0x40CU) #define HW_ENET_ATPER(x) (*(__IO hw_enet_atper_t *) HW_ENET_ATPER_ADDR(x)) #define HW_ENET_ATPER_RD(x) (HW_ENET_ATPER(x).U) #define HW_ENET_ATPER_WR(x, v) (HW_ENET_ATPER(x).U = (v)) #define HW_ENET_ATPER_SET(x, v) (HW_ENET_ATPER_WR(x, HW_ENET_ATPER_RD(x) | (v))) #define HW_ENET_ATPER_CLR(x, v) (HW_ENET_ATPER_WR(x, HW_ENET_ATPER_RD(x) & ~(v))) #define HW_ENET_ATPER_TOG(x, v) (HW_ENET_ATPER_WR(x, HW_ENET_ATPER_RD(x) ^ (v))) /*@}*/ /* * Constants & macros for individual ENET_ATPER bitfields */ /*! * @name Register ENET_ATPER, field PERIOD[31:0] (RW) * * Value for generating periodic events. Each instance the timer reaches this * value, the period event occurs and the timer restarts. If the increment value in * ATINC is given in true nanoseconds, this value is also given in true * nanoseconds. The value should be initialized to 1,000,000,000 (1 x 10 9 ) to represent * a timer wrap around of one second. The increment value set in ATINC should be * set to the true nanoseconds of the period of clock ts_clk, hence implementing * a true 1 second counter. */ /*@{*/ #define BP_ENET_ATPER_PERIOD (0U) /*!< Bit position for ENET_ATPER_PERIOD. */ #define BM_ENET_ATPER_PERIOD (0xFFFFFFFFU) /*!< Bit mask for ENET_ATPER_PERIOD. */ #define BS_ENET_ATPER_PERIOD (32U) /*!< Bit field size in bits for ENET_ATPER_PERIOD. */ /*! @brief Read current value of the ENET_ATPER_PERIOD field. */ #define BR_ENET_ATPER_PERIOD(x) (HW_ENET_ATPER(x).U) /*! @brief Format value for bitfield ENET_ATPER_PERIOD. */ #define BF_ENET_ATPER_PERIOD(v) ((uint32_t)((uint32_t)(v) << BP_ENET_ATPER_PERIOD) & BM_ENET_ATPER_PERIOD) /*! @brief Set the PERIOD field to a new value. */ #define BW_ENET_ATPER_PERIOD(x, v) (HW_ENET_ATPER_WR(x, v)) /*@}*/ /******************************************************************************* * HW_ENET_ATCOR - Timer Correction Register ******************************************************************************/ /*! * @brief HW_ENET_ATCOR - Timer Correction Register (RW) * * Reset value: 0x00000000U */ typedef union _hw_enet_atcor { uint32_t U; struct _hw_enet_atcor_bitfields { uint32_t COR : 31; /*!< [30:0] Correction Counter Wrap-Around Value */ uint32_t RESERVED0 : 1; /*!< [31] */ } B; } hw_enet_atcor_t; /*! * @name Constants and macros for entire ENET_ATCOR register */ /*@{*/ #define HW_ENET_ATCOR_ADDR(x) ((x) + 0x410U) #define HW_ENET_ATCOR(x) (*(__IO hw_enet_atcor_t *) HW_ENET_ATCOR_ADDR(x)) #define HW_ENET_ATCOR_RD(x) (HW_ENET_ATCOR(x).U) #define HW_ENET_ATCOR_WR(x, v) (HW_ENET_ATCOR(x).U = (v)) #define HW_ENET_ATCOR_SET(x, v) (HW_ENET_ATCOR_WR(x, HW_ENET_ATCOR_RD(x) | (v))) #define HW_ENET_ATCOR_CLR(x, v) (HW_ENET_ATCOR_WR(x, HW_ENET_ATCOR_RD(x) & ~(v))) #define HW_ENET_ATCOR_TOG(x, v) (HW_ENET_ATCOR_WR(x, HW_ENET_ATCOR_RD(x) ^ (v))) /*@}*/ /* * Constants & macros for individual ENET_ATCOR bitfields */ /*! * @name Register ENET_ATCOR, field COR[30:0] (RW) * * Defines after how many timer clock cycles (ts_clk) the correction counter * should be reset and trigger a correction increment on the timer. The amount of * correction is defined in ATINC[INC_CORR]. A value of 0 disables the correction * counter and no corrections occur. This value is given in clock cycles, not in * nanoseconds as all other values. */ /*@{*/ #define BP_ENET_ATCOR_COR (0U) /*!< Bit position for ENET_ATCOR_COR. */ #define BM_ENET_ATCOR_COR (0x7FFFFFFFU) /*!< Bit mask for ENET_ATCOR_COR. */ #define BS_ENET_ATCOR_COR (31U) /*!< Bit field size in bits for ENET_ATCOR_COR. */ /*! @brief Read current value of the ENET_ATCOR_COR field. */ #define BR_ENET_ATCOR_COR(x) (HW_ENET_ATCOR(x).B.COR) /*! @brief Format value for bitfield ENET_ATCOR_COR. */ #define BF_ENET_ATCOR_COR(v) ((uint32_t)((uint32_t)(v) << BP_ENET_ATCOR_COR) & BM_ENET_ATCOR_COR) /*! @brief Set the COR field to a new value. */ #define BW_ENET_ATCOR_COR(x, v) (HW_ENET_ATCOR_WR(x, (HW_ENET_ATCOR_RD(x) & ~BM_ENET_ATCOR_COR) | BF_ENET_ATCOR_COR(v))) /*@}*/ /******************************************************************************* * HW_ENET_ATINC - Time-Stamping Clock Period Register ******************************************************************************/ /*! * @brief HW_ENET_ATINC - Time-Stamping Clock Period Register (RW) * * Reset value: 0x00000000U */ typedef union _hw_enet_atinc { uint32_t U; struct _hw_enet_atinc_bitfields { uint32_t INC : 7; /*!< [6:0] Clock Period Of The Timestamping Clock * (ts_clk) In Nanoseconds */ uint32_t RESERVED0 : 1; /*!< [7] */ uint32_t INC_CORR : 7; /*!< [14:8] Correction Increment Value */ uint32_t RESERVED1 : 17; /*!< [31:15] */ } B; } hw_enet_atinc_t; /*! * @name Constants and macros for entire ENET_ATINC register */ /*@{*/ #define HW_ENET_ATINC_ADDR(x) ((x) + 0x414U) #define HW_ENET_ATINC(x) (*(__IO hw_enet_atinc_t *) HW_ENET_ATINC_ADDR(x)) #define HW_ENET_ATINC_RD(x) (HW_ENET_ATINC(x).U) #define HW_ENET_ATINC_WR(x, v) (HW_ENET_ATINC(x).U = (v)) #define HW_ENET_ATINC_SET(x, v) (HW_ENET_ATINC_WR(x, HW_ENET_ATINC_RD(x) | (v))) #define HW_ENET_ATINC_CLR(x, v) (HW_ENET_ATINC_WR(x, HW_ENET_ATINC_RD(x) & ~(v))) #define HW_ENET_ATINC_TOG(x, v) (HW_ENET_ATINC_WR(x, HW_ENET_ATINC_RD(x) ^ (v))) /*@}*/ /* * Constants & macros for individual ENET_ATINC bitfields */ /*! * @name Register ENET_ATINC, field INC[6:0] (RW) * * The timer increments by this amount each clock cycle. For example, set to 10 * for 100 MHz, 8 for 125 MHz, 5 for 200 MHz. For highest precision, use a value * that is an integer fraction of the period set in ATPER. */ /*@{*/ #define BP_ENET_ATINC_INC (0U) /*!< Bit position for ENET_ATINC_INC. */ #define BM_ENET_ATINC_INC (0x0000007FU) /*!< Bit mask for ENET_ATINC_INC. */ #define BS_ENET_ATINC_INC (7U) /*!< Bit field size in bits for ENET_ATINC_INC. */ /*! @brief Read current value of the ENET_ATINC_INC field. */ #define BR_ENET_ATINC_INC(x) (HW_ENET_ATINC(x).B.INC) /*! @brief Format value for bitfield ENET_ATINC_INC. */ #define BF_ENET_ATINC_INC(v) ((uint32_t)((uint32_t)(v) << BP_ENET_ATINC_INC) & BM_ENET_ATINC_INC) /*! @brief Set the INC field to a new value. */ #define BW_ENET_ATINC_INC(x, v) (HW_ENET_ATINC_WR(x, (HW_ENET_ATINC_RD(x) & ~BM_ENET_ATINC_INC) | BF_ENET_ATINC_INC(v))) /*@}*/ /*! * @name Register ENET_ATINC, field INC_CORR[14:8] (RW) * * This value is added every time the correction timer expires (every clock * cycle given in ATCOR). A value less than INC slows down the timer. A value greater * than INC speeds up the timer. */ /*@{*/ #define BP_ENET_ATINC_INC_CORR (8U) /*!< Bit position for ENET_ATINC_INC_CORR. */ #define BM_ENET_ATINC_INC_CORR (0x00007F00U) /*!< Bit mask for ENET_ATINC_INC_CORR. */ #define BS_ENET_ATINC_INC_CORR (7U) /*!< Bit field size in bits for ENET_ATINC_INC_CORR. */ /*! @brief Read current value of the ENET_ATINC_INC_CORR field. */ #define BR_ENET_ATINC_INC_CORR(x) (HW_ENET_ATINC(x).B.INC_CORR) /*! @brief Format value for bitfield ENET_ATINC_INC_CORR. */ #define BF_ENET_ATINC_INC_CORR(v) ((uint32_t)((uint32_t)(v) << BP_ENET_ATINC_INC_CORR) & BM_ENET_ATINC_INC_CORR) /*! @brief Set the INC_CORR field to a new value. */ #define BW_ENET_ATINC_INC_CORR(x, v) (HW_ENET_ATINC_WR(x, (HW_ENET_ATINC_RD(x) & ~BM_ENET_ATINC_INC_CORR) | BF_ENET_ATINC_INC_CORR(v))) /*@}*/ /******************************************************************************* * HW_ENET_ATSTMP - Timestamp of Last Transmitted Frame ******************************************************************************/ /*! * @brief HW_ENET_ATSTMP - Timestamp of Last Transmitted Frame (RO) * * Reset value: 0x00000000U */ typedef union _hw_enet_atstmp { uint32_t U; struct _hw_enet_atstmp_bitfields { uint32_t TIMESTAMP : 32; /*!< [31:0] */ } B; } hw_enet_atstmp_t; /*! * @name Constants and macros for entire ENET_ATSTMP register */ /*@{*/ #define HW_ENET_ATSTMP_ADDR(x) ((x) + 0x418U) #define HW_ENET_ATSTMP(x) (*(__I hw_enet_atstmp_t *) HW_ENET_ATSTMP_ADDR(x)) #define HW_ENET_ATSTMP_RD(x) (HW_ENET_ATSTMP(x).U) /*@}*/ /* * Constants & macros for individual ENET_ATSTMP bitfields */ /*! * @name Register ENET_ATSTMP, field TIMESTAMP[31:0] (RO) * * Timestamp of the last frame transmitted by the core that had TxBD[TS] set . * This register is only valid when EIR[TS_AVAIL] is set. */ /*@{*/ #define BP_ENET_ATSTMP_TIMESTAMP (0U) /*!< Bit position for ENET_ATSTMP_TIMESTAMP. */ #define BM_ENET_ATSTMP_TIMESTAMP (0xFFFFFFFFU) /*!< Bit mask for ENET_ATSTMP_TIMESTAMP. */ #define BS_ENET_ATSTMP_TIMESTAMP (32U) /*!< Bit field size in bits for ENET_ATSTMP_TIMESTAMP. */ /*! @brief Read current value of the ENET_ATSTMP_TIMESTAMP field. */ #define BR_ENET_ATSTMP_TIMESTAMP(x) (HW_ENET_ATSTMP(x).U) /*@}*/ /******************************************************************************* * HW_ENET_TGSR - Timer Global Status Register ******************************************************************************/ /*! * @brief HW_ENET_TGSR - Timer Global Status Register (RW) * * Reset value: 0x00000000U */ typedef union _hw_enet_tgsr { uint32_t U; struct _hw_enet_tgsr_bitfields { uint32_t TF0 : 1; /*!< [0] Copy Of Timer Flag For Channel 0 */ uint32_t TF1 : 1; /*!< [1] Copy Of Timer Flag For Channel 1 */ uint32_t TF2 : 1; /*!< [2] Copy Of Timer Flag For Channel 2 */ uint32_t TF3 : 1; /*!< [3] Copy Of Timer Flag For Channel 3 */ uint32_t RESERVED0 : 28; /*!< [31:4] */ } B; } hw_enet_tgsr_t; /*! * @name Constants and macros for entire ENET_TGSR register */ /*@{*/ #define HW_ENET_TGSR_ADDR(x) ((x) + 0x604U) #define HW_ENET_TGSR(x) (*(__IO hw_enet_tgsr_t *) HW_ENET_TGSR_ADDR(x)) #define HW_ENET_TGSR_RD(x) (HW_ENET_TGSR(x).U) #define HW_ENET_TGSR_WR(x, v) (HW_ENET_TGSR(x).U = (v)) #define HW_ENET_TGSR_SET(x, v) (HW_ENET_TGSR_WR(x, HW_ENET_TGSR_RD(x) | (v))) #define HW_ENET_TGSR_CLR(x, v) (HW_ENET_TGSR_WR(x, HW_ENET_TGSR_RD(x) & ~(v))) #define HW_ENET_TGSR_TOG(x, v) (HW_ENET_TGSR_WR(x, HW_ENET_TGSR_RD(x) ^ (v))) /*@}*/ /* * Constants & macros for individual ENET_TGSR bitfields */ /*! * @name Register ENET_TGSR, field TF0[0] (W1C) * * Values: * - 0 - Timer Flag for Channel 0 is clear * - 1 - Timer Flag for Channel 0 is set */ /*@{*/ #define BP_ENET_TGSR_TF0 (0U) /*!< Bit position for ENET_TGSR_TF0. */ #define BM_ENET_TGSR_TF0 (0x00000001U) /*!< Bit mask for ENET_TGSR_TF0. */ #define BS_ENET_TGSR_TF0 (1U) /*!< Bit field size in bits for ENET_TGSR_TF0. */ /*! @brief Read current value of the ENET_TGSR_TF0 field. */ #define BR_ENET_TGSR_TF0(x) (BITBAND_ACCESS32(HW_ENET_TGSR_ADDR(x), BP_ENET_TGSR_TF0)) /*! @brief Format value for bitfield ENET_TGSR_TF0. */ #define BF_ENET_TGSR_TF0(v) ((uint32_t)((uint32_t)(v) << BP_ENET_TGSR_TF0) & BM_ENET_TGSR_TF0) /*! @brief Set the TF0 field to a new value. */ #define BW_ENET_TGSR_TF0(x, v) (BITBAND_ACCESS32(HW_ENET_TGSR_ADDR(x), BP_ENET_TGSR_TF0) = (v)) /*@}*/ /*! * @name Register ENET_TGSR, field TF1[1] (W1C) * * Values: * - 0 - Timer Flag for Channel 1 is clear * - 1 - Timer Flag for Channel 1 is set */ /*@{*/ #define BP_ENET_TGSR_TF1 (1U) /*!< Bit position for ENET_TGSR_TF1. */ #define BM_ENET_TGSR_TF1 (0x00000002U) /*!< Bit mask for ENET_TGSR_TF1. */ #define BS_ENET_TGSR_TF1 (1U) /*!< Bit field size in bits for ENET_TGSR_TF1. */ /*! @brief Read current value of the ENET_TGSR_TF1 field. */ #define BR_ENET_TGSR_TF1(x) (BITBAND_ACCESS32(HW_ENET_TGSR_ADDR(x), BP_ENET_TGSR_TF1)) /*! @brief Format value for bitfield ENET_TGSR_TF1. */ #define BF_ENET_TGSR_TF1(v) ((uint32_t)((uint32_t)(v) << BP_ENET_TGSR_TF1) & BM_ENET_TGSR_TF1) /*! @brief Set the TF1 field to a new value. */ #define BW_ENET_TGSR_TF1(x, v) (BITBAND_ACCESS32(HW_ENET_TGSR_ADDR(x), BP_ENET_TGSR_TF1) = (v)) /*@}*/ /*! * @name Register ENET_TGSR, field TF2[2] (W1C) * * Values: * - 0 - Timer Flag for Channel 2 is clear * - 1 - Timer Flag for Channel 2 is set */ /*@{*/ #define BP_ENET_TGSR_TF2 (2U) /*!< Bit position for ENET_TGSR_TF2. */ #define BM_ENET_TGSR_TF2 (0x00000004U) /*!< Bit mask for ENET_TGSR_TF2. */ #define BS_ENET_TGSR_TF2 (1U) /*!< Bit field size in bits for ENET_TGSR_TF2. */ /*! @brief Read current value of the ENET_TGSR_TF2 field. */ #define BR_ENET_TGSR_TF2(x) (BITBAND_ACCESS32(HW_ENET_TGSR_ADDR(x), BP_ENET_TGSR_TF2)) /*! @brief Format value for bitfield ENET_TGSR_TF2. */ #define BF_ENET_TGSR_TF2(v) ((uint32_t)((uint32_t)(v) << BP_ENET_TGSR_TF2) & BM_ENET_TGSR_TF2) /*! @brief Set the TF2 field to a new value. */ #define BW_ENET_TGSR_TF2(x, v) (BITBAND_ACCESS32(HW_ENET_TGSR_ADDR(x), BP_ENET_TGSR_TF2) = (v)) /*@}*/ /*! * @name Register ENET_TGSR, field TF3[3] (W1C) * * Values: * - 0 - Timer Flag for Channel 3 is clear * - 1 - Timer Flag for Channel 3 is set */ /*@{*/ #define BP_ENET_TGSR_TF3 (3U) /*!< Bit position for ENET_TGSR_TF3. */ #define BM_ENET_TGSR_TF3 (0x00000008U) /*!< Bit mask for ENET_TGSR_TF3. */ #define BS_ENET_TGSR_TF3 (1U) /*!< Bit field size in bits for ENET_TGSR_TF3. */ /*! @brief Read current value of the ENET_TGSR_TF3 field. */ #define BR_ENET_TGSR_TF3(x) (BITBAND_ACCESS32(HW_ENET_TGSR_ADDR(x), BP_ENET_TGSR_TF3)) /*! @brief Format value for bitfield ENET_TGSR_TF3. */ #define BF_ENET_TGSR_TF3(v) ((uint32_t)((uint32_t)(v) << BP_ENET_TGSR_TF3) & BM_ENET_TGSR_TF3) /*! @brief Set the TF3 field to a new value. */ #define BW_ENET_TGSR_TF3(x, v) (BITBAND_ACCESS32(HW_ENET_TGSR_ADDR(x), BP_ENET_TGSR_TF3) = (v)) /*@}*/ /******************************************************************************* * HW_ENET_TCSRn - Timer Control Status Register ******************************************************************************/ /*! * @brief HW_ENET_TCSRn - Timer Control Status Register (RW) * * Reset value: 0x00000000U */ typedef union _hw_enet_tcsrn { uint32_t U; struct _hw_enet_tcsrn_bitfields { uint32_t TDRE : 1; /*!< [0] Timer DMA Request Enable */ uint32_t RESERVED0 : 1; /*!< [1] */ uint32_t TMODE : 4; /*!< [5:2] Timer Mode */ uint32_t TIE : 1; /*!< [6] Timer Interrupt Enable */ uint32_t TF : 1; /*!< [7] Timer Flag */ uint32_t RESERVED1 : 24; /*!< [31:8] */ } B; } hw_enet_tcsrn_t; /*! * @name Constants and macros for entire ENET_TCSRn register */ /*@{*/ #define HW_ENET_TCSRn_COUNT (4U) #define HW_ENET_TCSRn_ADDR(x, n) ((x) + 0x608U + (0x8U * (n))) #define HW_ENET_TCSRn(x, n) (*(__IO hw_enet_tcsrn_t *) HW_ENET_TCSRn_ADDR(x, n)) #define HW_ENET_TCSRn_RD(x, n) (HW_ENET_TCSRn(x, n).U) #define HW_ENET_TCSRn_WR(x, n, v) (HW_ENET_TCSRn(x, n).U = (v)) #define HW_ENET_TCSRn_SET(x, n, v) (HW_ENET_TCSRn_WR(x, n, HW_ENET_TCSRn_RD(x, n) | (v))) #define HW_ENET_TCSRn_CLR(x, n, v) (HW_ENET_TCSRn_WR(x, n, HW_ENET_TCSRn_RD(x, n) & ~(v))) #define HW_ENET_TCSRn_TOG(x, n, v) (HW_ENET_TCSRn_WR(x, n, HW_ENET_TCSRn_RD(x, n) ^ (v))) /*@}*/ /* * Constants & macros for individual ENET_TCSRn bitfields */ /*! * @name Register ENET_TCSRn, field TDRE[0] (RW) * * Values: * - 0 - DMA request is disabled * - 1 - DMA request is enabled */ /*@{*/ #define BP_ENET_TCSRn_TDRE (0U) /*!< Bit position for ENET_TCSRn_TDRE. */ #define BM_ENET_TCSRn_TDRE (0x00000001U) /*!< Bit mask for ENET_TCSRn_TDRE. */ #define BS_ENET_TCSRn_TDRE (1U) /*!< Bit field size in bits for ENET_TCSRn_TDRE. */ /*! @brief Read current value of the ENET_TCSRn_TDRE field. */ #define BR_ENET_TCSRn_TDRE(x, n) (BITBAND_ACCESS32(HW_ENET_TCSRn_ADDR(x, n), BP_ENET_TCSRn_TDRE)) /*! @brief Format value for bitfield ENET_TCSRn_TDRE. */ #define BF_ENET_TCSRn_TDRE(v) ((uint32_t)((uint32_t)(v) << BP_ENET_TCSRn_TDRE) & BM_ENET_TCSRn_TDRE) /*! @brief Set the TDRE field to a new value. */ #define BW_ENET_TCSRn_TDRE(x, n, v) (BITBAND_ACCESS32(HW_ENET_TCSRn_ADDR(x, n), BP_ENET_TCSRn_TDRE) = (v)) /*@}*/ /*! * @name Register ENET_TCSRn, field TMODE[5:2] (RW) * * Updating the Timer Mode field takes a few cycles to register because it is * synchronized to the 1588 clock. The version of Timer Mode returned on a read is * from the 1588 clock domain. When changing Timer Mode, always disable the * channel and read this register to verify the channel is disabled first. * * Values: * - 0000 - Timer Channel is disabled. * - 0001 - Timer Channel is configured for Input Capture on rising edge * - 0010 - Timer Channel is configured for Input Capture on falling edge * - 0011 - Timer Channel is configured for Input Capture on both edges * - 0100 - Timer Channel is configured for Output Compare - software only * - 0101 - Timer Channel is configured for Output Compare - toggle output on * compare * - 0110 - Timer Channel is configured for Output Compare - clear output on * compare * - 0111 - Timer Channel is configured for Output Compare - set output on * compare * - 1000 - Reserved * - 1010 - Timer Channel is configured for Output Compare - clear output on * compare, set output on overflow * - 10x1 - Timer Channel is configured for Output Compare - set output on * compare, clear output on overflow * - 1100 - Reserved * - 1110 - Timer Channel is configured for Output Compare - pulse output low on * compare for one 1588 clock cycle * - 1111 - Timer Channel is configured for Output Compare - pulse output high * on compare for one 1588 clock cycle */ /*@{*/ #define BP_ENET_TCSRn_TMODE (2U) /*!< Bit position for ENET_TCSRn_TMODE. */ #define BM_ENET_TCSRn_TMODE (0x0000003CU) /*!< Bit mask for ENET_TCSRn_TMODE. */ #define BS_ENET_TCSRn_TMODE (4U) /*!< Bit field size in bits for ENET_TCSRn_TMODE. */ /*! @brief Read current value of the ENET_TCSRn_TMODE field. */ #define BR_ENET_TCSRn_TMODE(x, n) (HW_ENET_TCSRn(x, n).B.TMODE) /*! @brief Format value for bitfield ENET_TCSRn_TMODE. */ #define BF_ENET_TCSRn_TMODE(v) ((uint32_t)((uint32_t)(v) << BP_ENET_TCSRn_TMODE) & BM_ENET_TCSRn_TMODE) /*! @brief Set the TMODE field to a new value. */ #define BW_ENET_TCSRn_TMODE(x, n, v) (HW_ENET_TCSRn_WR(x, n, (HW_ENET_TCSRn_RD(x, n) & ~BM_ENET_TCSRn_TMODE) | BF_ENET_TCSRn_TMODE(v))) /*@}*/ /*! * @name Register ENET_TCSRn, field TIE[6] (RW) * * Values: * - 0 - Interrupt is disabled * - 1 - Interrupt is enabled */ /*@{*/ #define BP_ENET_TCSRn_TIE (6U) /*!< Bit position for ENET_TCSRn_TIE. */ #define BM_ENET_TCSRn_TIE (0x00000040U) /*!< Bit mask for ENET_TCSRn_TIE. */ #define BS_ENET_TCSRn_TIE (1U) /*!< Bit field size in bits for ENET_TCSRn_TIE. */ /*! @brief Read current value of the ENET_TCSRn_TIE field. */ #define BR_ENET_TCSRn_TIE(x, n) (BITBAND_ACCESS32(HW_ENET_TCSRn_ADDR(x, n), BP_ENET_TCSRn_TIE)) /*! @brief Format value for bitfield ENET_TCSRn_TIE. */ #define BF_ENET_TCSRn_TIE(v) ((uint32_t)((uint32_t)(v) << BP_ENET_TCSRn_TIE) & BM_ENET_TCSRn_TIE) /*! @brief Set the TIE field to a new value. */ #define BW_ENET_TCSRn_TIE(x, n, v) (BITBAND_ACCESS32(HW_ENET_TCSRn_ADDR(x, n), BP_ENET_TCSRn_TIE) = (v)) /*@}*/ /*! * @name Register ENET_TCSRn, field TF[7] (W1C) * * Sets when input capture or output compare occurs. This flag is double * buffered between the module clock and 1588 clock domains. When this field is 1, it * can be cleared to 0 by writing 1 to it. * * Values: * - 0 - Input Capture or Output Compare has not occurred * - 1 - Input Capture or Output Compare has occurred */ /*@{*/ #define BP_ENET_TCSRn_TF (7U) /*!< Bit position for ENET_TCSRn_TF. */ #define BM_ENET_TCSRn_TF (0x00000080U) /*!< Bit mask for ENET_TCSRn_TF. */ #define BS_ENET_TCSRn_TF (1U) /*!< Bit field size in bits for ENET_TCSRn_TF. */ /*! @brief Read current value of the ENET_TCSRn_TF field. */ #define BR_ENET_TCSRn_TF(x, n) (BITBAND_ACCESS32(HW_ENET_TCSRn_ADDR(x, n), BP_ENET_TCSRn_TF)) /*! @brief Format value for bitfield ENET_TCSRn_TF. */ #define BF_ENET_TCSRn_TF(v) ((uint32_t)((uint32_t)(v) << BP_ENET_TCSRn_TF) & BM_ENET_TCSRn_TF) /*! @brief Set the TF field to a new value. */ #define BW_ENET_TCSRn_TF(x, n, v) (BITBAND_ACCESS32(HW_ENET_TCSRn_ADDR(x, n), BP_ENET_TCSRn_TF) = (v)) /*@}*/ /******************************************************************************* * HW_ENET_TCCRn - Timer Compare Capture Register ******************************************************************************/ /*! * @brief HW_ENET_TCCRn - Timer Compare Capture Register (RW) * * Reset value: 0x00000000U */ typedef union _hw_enet_tccrn { uint32_t U; struct _hw_enet_tccrn_bitfields { uint32_t TCC : 32; /*!< [31:0] Timer Capture Compare */ } B; } hw_enet_tccrn_t; /*! * @name Constants and macros for entire ENET_TCCRn register */ /*@{*/ #define HW_ENET_TCCRn_COUNT (4U) #define HW_ENET_TCCRn_ADDR(x, n) ((x) + 0x60CU + (0x8U * (n))) #define HW_ENET_TCCRn(x, n) (*(__IO hw_enet_tccrn_t *) HW_ENET_TCCRn_ADDR(x, n)) #define HW_ENET_TCCRn_RD(x, n) (HW_ENET_TCCRn(x, n).U) #define HW_ENET_TCCRn_WR(x, n, v) (HW_ENET_TCCRn(x, n).U = (v)) #define HW_ENET_TCCRn_SET(x, n, v) (HW_ENET_TCCRn_WR(x, n, HW_ENET_TCCRn_RD(x, n) | (v))) #define HW_ENET_TCCRn_CLR(x, n, v) (HW_ENET_TCCRn_WR(x, n, HW_ENET_TCCRn_RD(x, n) & ~(v))) #define HW_ENET_TCCRn_TOG(x, n, v) (HW_ENET_TCCRn_WR(x, n, HW_ENET_TCCRn_RD(x, n) ^ (v))) /*@}*/ /* * Constants & macros for individual ENET_TCCRn bitfields */ /*! * @name Register ENET_TCCRn, field TCC[31:0] (RW) * * This register is double buffered between the module clock and 1588 clock * domains. When configured for compare, the 1588 clock domain updates with the value * in the module clock domain whenever the Timer Channel is first enabled and on * each subsequent compare. Write to this register with the first compare value * before enabling the Timer Channel. When the Timer Channel is enabled, write * the second compare value either immediately, or at least before the first * compare occurs. After each compare, write the next compare value before the previous * compare occurs and before clearing the Timer Flag. The compare occurs one * 1588 clock cycle after the IEEE 1588 Counter increments past the compare value in * the 1588 clock domain. If the compare value is less than the value of the * 1588 Counter when the Timer Channel is first enabled, then the compare does not * occur until following the next overflow of the 1588 Counter. If the compare * value is greater than the IEEE 1588 Counter when the 1588 Counter overflows, or * the compare value is less than the value of the IEEE 1588 Counter after the * overflow, then the compare occurs one 1588 clock cycle following the overflow. * When configured for Capture, the value of the IEEE 1588 Counter is captured into * the 1588 clock domain and then updated into the module clock domain, provided * the Timer Flag is clear. Always read the capture value before clearing the * Timer Flag. */ /*@{*/ #define BP_ENET_TCCRn_TCC (0U) /*!< Bit position for ENET_TCCRn_TCC. */ #define BM_ENET_TCCRn_TCC (0xFFFFFFFFU) /*!< Bit mask for ENET_TCCRn_TCC. */ #define BS_ENET_TCCRn_TCC (32U) /*!< Bit field size in bits for ENET_TCCRn_TCC. */ /*! @brief Read current value of the ENET_TCCRn_TCC field. */ #define BR_ENET_TCCRn_TCC(x, n) (HW_ENET_TCCRn(x, n).U) /*! @brief Format value for bitfield ENET_TCCRn_TCC. */ #define BF_ENET_TCCRn_TCC(v) ((uint32_t)((uint32_t)(v) << BP_ENET_TCCRn_TCC) & BM_ENET_TCCRn_TCC) /*! @brief Set the TCC field to a new value. */ #define BW_ENET_TCCRn_TCC(x, n, v) (HW_ENET_TCCRn_WR(x, n, v)) /*@}*/ /******************************************************************************* * hw_enet_t - module struct ******************************************************************************/ /*! * @brief All ENET module registers. */ #pragma pack(1) typedef struct _hw_enet { uint8_t _reserved0[4]; __IO hw_enet_eir_t EIR; /*!< [0x4] Interrupt Event Register */ __IO hw_enet_eimr_t EIMR; /*!< [0x8] Interrupt Mask Register */ uint8_t _reserved1[4]; __IO hw_enet_rdar_t RDAR; /*!< [0x10] Receive Descriptor Active Register */ __IO hw_enet_tdar_t TDAR; /*!< [0x14] Transmit Descriptor Active Register */ uint8_t _reserved2[12]; __IO hw_enet_ecr_t ECR; /*!< [0x24] Ethernet Control Register */ uint8_t _reserved3[24]; __IO hw_enet_mmfr_t MMFR; /*!< [0x40] MII Management Frame Register */ __IO hw_enet_mscr_t MSCR; /*!< [0x44] MII Speed Control Register */ uint8_t _reserved4[28]; __IO hw_enet_mibc_t MIBC; /*!< [0x64] MIB Control Register */ uint8_t _reserved5[28]; __IO hw_enet_rcr_t RCR; /*!< [0x84] Receive Control Register */ uint8_t _reserved6[60]; __IO hw_enet_tcr_t TCR; /*!< [0xC4] Transmit Control Register */ uint8_t _reserved7[28]; __IO hw_enet_palr_t PALR; /*!< [0xE4] Physical Address Lower Register */ __IO hw_enet_paur_t PAUR; /*!< [0xE8] Physical Address Upper Register */ __IO hw_enet_opd_t OPD; /*!< [0xEC] Opcode/Pause Duration Register */ uint8_t _reserved8[40]; __IO hw_enet_iaur_t IAUR; /*!< [0x118] Descriptor Individual Upper Address Register */ __IO hw_enet_ialr_t IALR; /*!< [0x11C] Descriptor Individual Lower Address Register */ __IO hw_enet_gaur_t GAUR; /*!< [0x120] Descriptor Group Upper Address Register */ __IO hw_enet_galr_t GALR; /*!< [0x124] Descriptor Group Lower Address Register */ uint8_t _reserved9[28]; __IO hw_enet_tfwr_t TFWR; /*!< [0x144] Transmit FIFO Watermark Register */ uint8_t _reserved10[56]; __IO hw_enet_rdsr_t RDSR; /*!< [0x180] Receive Descriptor Ring Start Register */ __IO hw_enet_tdsr_t TDSR; /*!< [0x184] Transmit Buffer Descriptor Ring Start Register */ __IO hw_enet_mrbr_t MRBR; /*!< [0x188] Maximum Receive Buffer Size Register */ uint8_t _reserved11[4]; __IO hw_enet_rsfl_t RSFL; /*!< [0x190] Receive FIFO Section Full Threshold */ __IO hw_enet_rsem_t RSEM; /*!< [0x194] Receive FIFO Section Empty Threshold */ __IO hw_enet_raem_t RAEM; /*!< [0x198] Receive FIFO Almost Empty Threshold */ __IO hw_enet_rafl_t RAFL; /*!< [0x19C] Receive FIFO Almost Full Threshold */ __IO hw_enet_tsem_t TSEM; /*!< [0x1A0] Transmit FIFO Section Empty Threshold */ __IO hw_enet_taem_t TAEM; /*!< [0x1A4] Transmit FIFO Almost Empty Threshold */ __IO hw_enet_tafl_t TAFL; /*!< [0x1A8] Transmit FIFO Almost Full Threshold */ __IO hw_enet_tipg_t TIPG; /*!< [0x1AC] Transmit Inter-Packet Gap */ __IO hw_enet_ftrl_t FTRL; /*!< [0x1B0] Frame Truncation Length */ uint8_t _reserved12[12]; __IO hw_enet_tacc_t TACC; /*!< [0x1C0] Transmit Accelerator Function Configuration */ __IO hw_enet_racc_t RACC; /*!< [0x1C4] Receive Accelerator Function Configuration */ uint8_t _reserved13[60]; __I hw_enet_rmon_t_packets_t RMON_T_PACKETS; /*!< [0x204] Tx Packet Count Statistic Register */ __I hw_enet_rmon_t_bc_pkt_t RMON_T_BC_PKT; /*!< [0x208] Tx Broadcast Packets Statistic Register */ __I hw_enet_rmon_t_mc_pkt_t RMON_T_MC_PKT; /*!< [0x20C] Tx Multicast Packets Statistic Register */ __I hw_enet_rmon_t_crc_align_t RMON_T_CRC_ALIGN; /*!< [0x210] Tx Packets with CRC/Align Error Statistic Register */ __I hw_enet_rmon_t_undersize_t RMON_T_UNDERSIZE; /*!< [0x214] Tx Packets Less Than Bytes and Good CRC Statistic Register */ __I hw_enet_rmon_t_oversize_t RMON_T_OVERSIZE; /*!< [0x218] Tx Packets GT MAX_FL bytes and Good CRC Statistic Register */ __I hw_enet_rmon_t_frag_t RMON_T_FRAG; /*!< [0x21C] Tx Packets Less Than 64 Bytes and Bad CRC Statistic Register */ __I hw_enet_rmon_t_jab_t RMON_T_JAB; /*!< [0x220] Tx Packets Greater Than MAX_FL bytes and Bad CRC Statistic Register */ __I hw_enet_rmon_t_col_t RMON_T_COL; /*!< [0x224] Tx Collision Count Statistic Register */ __I hw_enet_rmon_t_p64_t RMON_T_P64; /*!< [0x228] Tx 64-Byte Packets Statistic Register */ __I hw_enet_rmon_t_p65to127_t RMON_T_P65TO127; /*!< [0x22C] Tx 65- to 127-byte Packets Statistic Register */ __I hw_enet_rmon_t_p128to255_t RMON_T_P128TO255; /*!< [0x230] Tx 128- to 255-byte Packets Statistic Register */ __I hw_enet_rmon_t_p256to511_t RMON_T_P256TO511; /*!< [0x234] Tx 256- to 511-byte Packets Statistic Register */ __I hw_enet_rmon_t_p512to1023_t RMON_T_P512TO1023; /*!< [0x238] Tx 512- to 1023-byte Packets Statistic Register */ __I hw_enet_rmon_t_p1024to2047_t RMON_T_P1024TO2047; /*!< [0x23C] Tx 1024- to 2047-byte Packets Statistic Register */ __I hw_enet_rmon_t_p_gte2048_t RMON_T_P_GTE2048; /*!< [0x240] Tx Packets Greater Than 2048 Bytes Statistic Register */ __I hw_enet_rmon_t_octets_t RMON_T_OCTETS; /*!< [0x244] Tx Octets Statistic Register */ uint8_t _reserved14[4]; __I hw_enet_ieee_t_frame_ok_t IEEE_T_FRAME_OK; /*!< [0x24C] Frames Transmitted OK Statistic Register */ __I hw_enet_ieee_t_1col_t IEEE_T_1COL; /*!< [0x250] Frames Transmitted with Single Collision Statistic Register */ __I hw_enet_ieee_t_mcol_t IEEE_T_MCOL; /*!< [0x254] Frames Transmitted with Multiple Collisions Statistic Register */ __I hw_enet_ieee_t_def_t IEEE_T_DEF; /*!< [0x258] Frames Transmitted after Deferral Delay Statistic Register */ __I hw_enet_ieee_t_lcol_t IEEE_T_LCOL; /*!< [0x25C] Frames Transmitted with Late Collision Statistic Register */ __I hw_enet_ieee_t_excol_t IEEE_T_EXCOL; /*!< [0x260] Frames Transmitted with Excessive Collisions Statistic Register */ __I hw_enet_ieee_t_macerr_t IEEE_T_MACERR; /*!< [0x264] Frames Transmitted with Tx FIFO Underrun Statistic Register */ __I hw_enet_ieee_t_cserr_t IEEE_T_CSERR; /*!< [0x268] Frames Transmitted with Carrier Sense Error Statistic Register */ uint8_t _reserved15[4]; __I hw_enet_ieee_t_fdxfc_t IEEE_T_FDXFC; /*!< [0x270] Flow Control Pause Frames Transmitted Statistic Register */ __I hw_enet_ieee_t_octets_ok_t IEEE_T_OCTETS_OK; /*!< [0x274] Octet Count for Frames Transmitted w/o Error Statistic Register */ uint8_t _reserved16[12]; __I hw_enet_rmon_r_packets_t RMON_R_PACKETS; /*!< [0x284] Rx Packet Count Statistic Register */ __I hw_enet_rmon_r_bc_pkt_t RMON_R_BC_PKT; /*!< [0x288] Rx Broadcast Packets Statistic Register */ __I hw_enet_rmon_r_mc_pkt_t RMON_R_MC_PKT; /*!< [0x28C] Rx Multicast Packets Statistic Register */ __I hw_enet_rmon_r_crc_align_t RMON_R_CRC_ALIGN; /*!< [0x290] Rx Packets with CRC/Align Error Statistic Register */ __I hw_enet_rmon_r_undersize_t RMON_R_UNDERSIZE; /*!< [0x294] Rx Packets with Less Than 64 Bytes and Good CRC Statistic Register */ __I hw_enet_rmon_r_oversize_t RMON_R_OVERSIZE; /*!< [0x298] Rx Packets Greater Than MAX_FL and Good CRC Statistic Register */ __I hw_enet_rmon_r_frag_t RMON_R_FRAG; /*!< [0x29C] Rx Packets Less Than 64 Bytes and Bad CRC Statistic Register */ __I hw_enet_rmon_r_jab_t RMON_R_JAB; /*!< [0x2A0] Rx Packets Greater Than MAX_FL Bytes and Bad CRC Statistic Register */ uint8_t _reserved17[4]; __I hw_enet_rmon_r_p64_t RMON_R_P64; /*!< [0x2A8] Rx 64-Byte Packets Statistic Register */ __I hw_enet_rmon_r_p65to127_t RMON_R_P65TO127; /*!< [0x2AC] Rx 65- to 127-Byte Packets Statistic Register */ __I hw_enet_rmon_r_p128to255_t RMON_R_P128TO255; /*!< [0x2B0] Rx 128- to 255-Byte Packets Statistic Register */ __I hw_enet_rmon_r_p256to511_t RMON_R_P256TO511; /*!< [0x2B4] Rx 256- to 511-Byte Packets Statistic Register */ __I hw_enet_rmon_r_p512to1023_t RMON_R_P512TO1023; /*!< [0x2B8] Rx 512- to 1023-Byte Packets Statistic Register */ __I hw_enet_rmon_r_p1024to2047_t RMON_R_P1024TO2047; /*!< [0x2BC] Rx 1024- to 2047-Byte Packets Statistic Register */ __I hw_enet_rmon_r_p_gte2048_t RMON_R_P_GTE2048; /*!< [0x2C0] Rx Packets Greater than 2048 Bytes Statistic Register */ __I hw_enet_rmon_r_octets_t RMON_R_OCTETS; /*!< [0x2C4] Rx Octets Statistic Register */ __I hw_enet_ieee_r_drop_t IEEE_R_DROP; /*!< [0x2C8] Frames not Counted Correctly Statistic Register */ __I hw_enet_ieee_r_frame_ok_t IEEE_R_FRAME_OK; /*!< [0x2CC] Frames Received OK Statistic Register */ __I hw_enet_ieee_r_crc_t IEEE_R_CRC; /*!< [0x2D0] Frames Received with CRC Error Statistic Register */ __I hw_enet_ieee_r_align_t IEEE_R_ALIGN; /*!< [0x2D4] Frames Received with Alignment Error Statistic Register */ __I hw_enet_ieee_r_macerr_t IEEE_R_MACERR; /*!< [0x2D8] Receive FIFO Overflow Count Statistic Register */ __I hw_enet_ieee_r_fdxfc_t IEEE_R_FDXFC; /*!< [0x2DC] Flow Control Pause Frames Received Statistic Register */ __I hw_enet_ieee_r_octets_ok_t IEEE_R_OCTETS_OK; /*!< [0x2E0] Octet Count for Frames Received without Error Statistic Register */ uint8_t _reserved18[284]; __IO hw_enet_atcr_t ATCR; /*!< [0x400] Adjustable Timer Control Register */ __IO hw_enet_atvr_t ATVR; /*!< [0x404] Timer Value Register */ __IO hw_enet_atoff_t ATOFF; /*!< [0x408] Timer Offset Register */ __IO hw_enet_atper_t ATPER; /*!< [0x40C] Timer Period Register */ __IO hw_enet_atcor_t ATCOR; /*!< [0x410] Timer Correction Register */ __IO hw_enet_atinc_t ATINC; /*!< [0x414] Time-Stamping Clock Period Register */ __I hw_enet_atstmp_t ATSTMP; /*!< [0x418] Timestamp of Last Transmitted Frame */ uint8_t _reserved19[488]; __IO hw_enet_tgsr_t TGSR; /*!< [0x604] Timer Global Status Register */ struct { __IO hw_enet_tcsrn_t TCSRn; /*!< [0x608] Timer Control Status Register */ __IO hw_enet_tccrn_t TCCRn; /*!< [0x60C] Timer Compare Capture Register */ } CHANNEL[4]; } hw_enet_t; #pragma pack() /*! @brief Macro to access all ENET registers. */ /*! @param x ENET module instance base address. */ /*! @return Reference (not a pointer) to the registers struct. To get a pointer to the struct, * use the '&' operator, like &HW_ENET(ENET_BASE). */ #define HW_ENET(x) (*(hw_enet_t *)(x)) #endif /* __HW_ENET_REGISTERS_H__ */ /* EOF */ ================================================ FILE: Zelig/mbed/TARGET_K64F/TARGET_Freescale/TARGET_KPSDK_MCUS/TARGET_MCU_K64F/device/device/MK64F12/MK64F12_ewm.h ================================================ /* ** ################################################################### ** Compilers: Keil ARM C/C++ Compiler ** Freescale C/C++ for Embedded ARM ** GNU C Compiler ** IAR ANSI C/C++ Compiler for ARM ** ** Reference manual: K64P144M120SF5RM, Rev.2, January 2014 ** Version: rev. 2.5, 2014-02-10 ** Build: b140604 ** ** Abstract: ** Extension to the CMSIS register access layer header. ** ** Copyright (c) 2014 Freescale Semiconductor, Inc. ** All rights reserved. ** ** Redistribution and use in source and binary forms, with or without modification, ** are permitted provided that the following conditions are met: ** ** o Redistributions of source code must retain the above copyright notice, this list ** of conditions and the following disclaimer. ** ** o Redistributions in binary form must reproduce the above copyright notice, this ** list of conditions and the following disclaimer in the documentation and/or ** other materials provided with the distribution. ** ** o Neither the name of Freescale Semiconductor, Inc. nor the names of its ** contributors may be used to endorse or promote products derived from this ** software without specific prior written permission. ** ** THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ** ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED ** WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE ** DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT 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. ** ** http: www.freescale.com ** mail: support@freescale.com ** ** Revisions: ** - rev. 1.0 (2013-08-12) ** Initial version. ** - rev. 2.0 (2013-10-29) ** Register accessor macros added to the memory map. ** Symbols for Processor Expert memory map compatibility added to the memory map. ** Startup file for gcc has been updated according to CMSIS 3.2. ** System initialization updated. ** MCG - registers updated. ** PORTA, PORTB, PORTC, PORTE - registers for digital filter removed. ** - rev. 2.1 (2013-10-30) ** Definition of BITBAND macros updated to support peripherals with 32-bit acces disabled. ** - rev. 2.2 (2013-12-09) ** DMA - EARS register removed. ** AIPS0, AIPS1 - MPRA register updated. ** - rev. 2.3 (2014-01-24) ** Update according to reference manual rev. 2 ** ENET, MCG, MCM, SIM, USB - registers updated ** - rev. 2.4 (2014-02-10) ** The declaration of clock configurations has been moved to separate header file system_MK64F12.h ** Update of SystemInit() and SystemCoreClockUpdate() functions. ** - rev. 2.5 (2014-02-10) ** The declaration of clock configurations has been moved to separate header file system_MK64F12.h ** Update of SystemInit() and SystemCoreClockUpdate() functions. ** Module access macro module_BASES replaced by module_BASE_PTRS. ** ** ################################################################### */ /* * WARNING! DO NOT EDIT THIS FILE DIRECTLY! * * This file was generated automatically and any changes may be lost. */ #ifndef __HW_EWM_REGISTERS_H__ #define __HW_EWM_REGISTERS_H__ #include "MK64F12.h" #include "fsl_bitaccess.h" /* * MK64F12 EWM * * External Watchdog Monitor * * Registers defined in this header file: * - HW_EWM_CTRL - Control Register * - HW_EWM_SERV - Service Register * - HW_EWM_CMPL - Compare Low Register * - HW_EWM_CMPH - Compare High Register * * - hw_ewm_t - Struct containing all module registers. */ #define HW_EWM_INSTANCE_COUNT (1U) /*!< Number of instances of the EWM module. */ /******************************************************************************* * HW_EWM_CTRL - Control Register ******************************************************************************/ /*! * @brief HW_EWM_CTRL - Control Register (RW) * * Reset value: 0x00U * * The CTRL register is cleared by any reset. INEN, ASSIN and EWMEN bits can be * written once after a CPU reset. Modifying these bits more than once, generates * a bus transfer error. */ typedef union _hw_ewm_ctrl { uint8_t U; struct _hw_ewm_ctrl_bitfields { uint8_t EWMEN : 1; /*!< [0] EWM enable. */ uint8_t ASSIN : 1; /*!< [1] EWM_in's Assertion State Select. */ uint8_t INEN : 1; /*!< [2] Input Enable. */ uint8_t INTEN : 1; /*!< [3] Interrupt Enable. */ uint8_t RESERVED0 : 4; /*!< [7:4] */ } B; } hw_ewm_ctrl_t; /*! * @name Constants and macros for entire EWM_CTRL register */ /*@{*/ #define HW_EWM_CTRL_ADDR(x) ((x) + 0x0U) #define HW_EWM_CTRL(x) (*(__IO hw_ewm_ctrl_t *) HW_EWM_CTRL_ADDR(x)) #define HW_EWM_CTRL_RD(x) (HW_EWM_CTRL(x).U) #define HW_EWM_CTRL_WR(x, v) (HW_EWM_CTRL(x).U = (v)) #define HW_EWM_CTRL_SET(x, v) (HW_EWM_CTRL_WR(x, HW_EWM_CTRL_RD(x) | (v))) #define HW_EWM_CTRL_CLR(x, v) (HW_EWM_CTRL_WR(x, HW_EWM_CTRL_RD(x) & ~(v))) #define HW_EWM_CTRL_TOG(x, v) (HW_EWM_CTRL_WR(x, HW_EWM_CTRL_RD(x) ^ (v))) /*@}*/ /* * Constants & macros for individual EWM_CTRL bitfields */ /*! * @name Register EWM_CTRL, field EWMEN[0] (RW) * * This bit when set, enables the EWM module. This resets the EWM counter to * zero and deasserts the EWM_out signal. Clearing EWMEN bit disables the EWM, and * therefore it cannot be enabled until a reset occurs, due to the write-once * nature of this bit. */ /*@{*/ #define BP_EWM_CTRL_EWMEN (0U) /*!< Bit position for EWM_CTRL_EWMEN. */ #define BM_EWM_CTRL_EWMEN (0x01U) /*!< Bit mask for EWM_CTRL_EWMEN. */ #define BS_EWM_CTRL_EWMEN (1U) /*!< Bit field size in bits for EWM_CTRL_EWMEN. */ /*! @brief Read current value of the EWM_CTRL_EWMEN field. */ #define BR_EWM_CTRL_EWMEN(x) (BITBAND_ACCESS8(HW_EWM_CTRL_ADDR(x), BP_EWM_CTRL_EWMEN)) /*! @brief Format value for bitfield EWM_CTRL_EWMEN. */ #define BF_EWM_CTRL_EWMEN(v) ((uint8_t)((uint8_t)(v) << BP_EWM_CTRL_EWMEN) & BM_EWM_CTRL_EWMEN) /*! @brief Set the EWMEN field to a new value. */ #define BW_EWM_CTRL_EWMEN(x, v) (BITBAND_ACCESS8(HW_EWM_CTRL_ADDR(x), BP_EWM_CTRL_EWMEN) = (v)) /*@}*/ /*! * @name Register EWM_CTRL, field ASSIN[1] (RW) * * Default assert state of the EWM_in signal is logic zero. Setting ASSIN bit * inverts the assert state to a logic one. */ /*@{*/ #define BP_EWM_CTRL_ASSIN (1U) /*!< Bit position for EWM_CTRL_ASSIN. */ #define BM_EWM_CTRL_ASSIN (0x02U) /*!< Bit mask for EWM_CTRL_ASSIN. */ #define BS_EWM_CTRL_ASSIN (1U) /*!< Bit field size in bits for EWM_CTRL_ASSIN. */ /*! @brief Read current value of the EWM_CTRL_ASSIN field. */ #define BR_EWM_CTRL_ASSIN(x) (BITBAND_ACCESS8(HW_EWM_CTRL_ADDR(x), BP_EWM_CTRL_ASSIN)) /*! @brief Format value for bitfield EWM_CTRL_ASSIN. */ #define BF_EWM_CTRL_ASSIN(v) ((uint8_t)((uint8_t)(v) << BP_EWM_CTRL_ASSIN) & BM_EWM_CTRL_ASSIN) /*! @brief Set the ASSIN field to a new value. */ #define BW_EWM_CTRL_ASSIN(x, v) (BITBAND_ACCESS8(HW_EWM_CTRL_ADDR(x), BP_EWM_CTRL_ASSIN) = (v)) /*@}*/ /*! * @name Register EWM_CTRL, field INEN[2] (RW) * * This bit when set, enables the EWM_in port. */ /*@{*/ #define BP_EWM_CTRL_INEN (2U) /*!< Bit position for EWM_CTRL_INEN. */ #define BM_EWM_CTRL_INEN (0x04U) /*!< Bit mask for EWM_CTRL_INEN. */ #define BS_EWM_CTRL_INEN (1U) /*!< Bit field size in bits for EWM_CTRL_INEN. */ /*! @brief Read current value of the EWM_CTRL_INEN field. */ #define BR_EWM_CTRL_INEN(x) (BITBAND_ACCESS8(HW_EWM_CTRL_ADDR(x), BP_EWM_CTRL_INEN)) /*! @brief Format value for bitfield EWM_CTRL_INEN. */ #define BF_EWM_CTRL_INEN(v) ((uint8_t)((uint8_t)(v) << BP_EWM_CTRL_INEN) & BM_EWM_CTRL_INEN) /*! @brief Set the INEN field to a new value. */ #define BW_EWM_CTRL_INEN(x, v) (BITBAND_ACCESS8(HW_EWM_CTRL_ADDR(x), BP_EWM_CTRL_INEN) = (v)) /*@}*/ /*! * @name Register EWM_CTRL, field INTEN[3] (RW) * * This bit when set and EWM_out is asserted, an interrupt request is generated. * To de-assert interrupt request, user should clear this bit by writing 0. */ /*@{*/ #define BP_EWM_CTRL_INTEN (3U) /*!< Bit position for EWM_CTRL_INTEN. */ #define BM_EWM_CTRL_INTEN (0x08U) /*!< Bit mask for EWM_CTRL_INTEN. */ #define BS_EWM_CTRL_INTEN (1U) /*!< Bit field size in bits for EWM_CTRL_INTEN. */ /*! @brief Read current value of the EWM_CTRL_INTEN field. */ #define BR_EWM_CTRL_INTEN(x) (BITBAND_ACCESS8(HW_EWM_CTRL_ADDR(x), BP_EWM_CTRL_INTEN)) /*! @brief Format value for bitfield EWM_CTRL_INTEN. */ #define BF_EWM_CTRL_INTEN(v) ((uint8_t)((uint8_t)(v) << BP_EWM_CTRL_INTEN) & BM_EWM_CTRL_INTEN) /*! @brief Set the INTEN field to a new value. */ #define BW_EWM_CTRL_INTEN(x, v) (BITBAND_ACCESS8(HW_EWM_CTRL_ADDR(x), BP_EWM_CTRL_INTEN) = (v)) /*@}*/ /******************************************************************************* * HW_EWM_SERV - Service Register ******************************************************************************/ /*! * @brief HW_EWM_SERV - Service Register (WORZ) * * Reset value: 0x00U * * The SERV register provides the interface from the CPU to the EWM module. It * is write-only and reads of this register return zero. */ typedef union _hw_ewm_serv { uint8_t U; struct _hw_ewm_serv_bitfields { uint8_t SERVICE : 8; /*!< [7:0] */ } B; } hw_ewm_serv_t; /*! * @name Constants and macros for entire EWM_SERV register */ /*@{*/ #define HW_EWM_SERV_ADDR(x) ((x) + 0x1U) #define HW_EWM_SERV(x) (*(__O hw_ewm_serv_t *) HW_EWM_SERV_ADDR(x)) #define HW_EWM_SERV_RD(x) (HW_EWM_SERV(x).U) #define HW_EWM_SERV_WR(x, v) (HW_EWM_SERV(x).U = (v)) /*@}*/ /* * Constants & macros for individual EWM_SERV bitfields */ /*! * @name Register EWM_SERV, field SERVICE[7:0] (WORZ) * * The EWM service mechanism requires the CPU to write two values to the SERV * register: a first data byte of 0xB4, followed by a second data byte of 0x2C. The * EWM service is illegal if either of the following conditions is true. The * first or second data byte is not written correctly. The second data byte is not * written within a fixed number of peripheral bus cycles of the first data byte. * This fixed number of cycles is called EWM_service_time. */ /*@{*/ #define BP_EWM_SERV_SERVICE (0U) /*!< Bit position for EWM_SERV_SERVICE. */ #define BM_EWM_SERV_SERVICE (0xFFU) /*!< Bit mask for EWM_SERV_SERVICE. */ #define BS_EWM_SERV_SERVICE (8U) /*!< Bit field size in bits for EWM_SERV_SERVICE. */ /*! @brief Format value for bitfield EWM_SERV_SERVICE. */ #define BF_EWM_SERV_SERVICE(v) ((uint8_t)((uint8_t)(v) << BP_EWM_SERV_SERVICE) & BM_EWM_SERV_SERVICE) /*! @brief Set the SERVICE field to a new value. */ #define BW_EWM_SERV_SERVICE(x, v) (HW_EWM_SERV_WR(x, v)) /*@}*/ /******************************************************************************* * HW_EWM_CMPL - Compare Low Register ******************************************************************************/ /*! * @brief HW_EWM_CMPL - Compare Low Register (RW) * * Reset value: 0x00U * * The CMPL register is reset to zero after a CPU reset. This provides no * minimum time for the CPU to service the EWM counter. This register can be written * only once after a CPU reset. Writing this register more than once generates a * bus transfer error. */ typedef union _hw_ewm_cmpl { uint8_t U; struct _hw_ewm_cmpl_bitfields { uint8_t COMPAREL : 8; /*!< [7:0] */ } B; } hw_ewm_cmpl_t; /*! * @name Constants and macros for entire EWM_CMPL register */ /*@{*/ #define HW_EWM_CMPL_ADDR(x) ((x) + 0x2U) #define HW_EWM_CMPL(x) (*(__IO hw_ewm_cmpl_t *) HW_EWM_CMPL_ADDR(x)) #define HW_EWM_CMPL_RD(x) (HW_EWM_CMPL(x).U) #define HW_EWM_CMPL_WR(x, v) (HW_EWM_CMPL(x).U = (v)) #define HW_EWM_CMPL_SET(x, v) (HW_EWM_CMPL_WR(x, HW_EWM_CMPL_RD(x) | (v))) #define HW_EWM_CMPL_CLR(x, v) (HW_EWM_CMPL_WR(x, HW_EWM_CMPL_RD(x) & ~(v))) #define HW_EWM_CMPL_TOG(x, v) (HW_EWM_CMPL_WR(x, HW_EWM_CMPL_RD(x) ^ (v))) /*@}*/ /* * Constants & macros for individual EWM_CMPL bitfields */ /*! * @name Register EWM_CMPL, field COMPAREL[7:0] (RW) * * To prevent runaway code from changing this field, software should write to * this field after a CPU reset even if the (default) minimum service time is * required. */ /*@{*/ #define BP_EWM_CMPL_COMPAREL (0U) /*!< Bit position for EWM_CMPL_COMPAREL. */ #define BM_EWM_CMPL_COMPAREL (0xFFU) /*!< Bit mask for EWM_CMPL_COMPAREL. */ #define BS_EWM_CMPL_COMPAREL (8U) /*!< Bit field size in bits for EWM_CMPL_COMPAREL. */ /*! @brief Read current value of the EWM_CMPL_COMPAREL field. */ #define BR_EWM_CMPL_COMPAREL(x) (HW_EWM_CMPL(x).U) /*! @brief Format value for bitfield EWM_CMPL_COMPAREL. */ #define BF_EWM_CMPL_COMPAREL(v) ((uint8_t)((uint8_t)(v) << BP_EWM_CMPL_COMPAREL) & BM_EWM_CMPL_COMPAREL) /*! @brief Set the COMPAREL field to a new value. */ #define BW_EWM_CMPL_COMPAREL(x, v) (HW_EWM_CMPL_WR(x, v)) /*@}*/ /******************************************************************************* * HW_EWM_CMPH - Compare High Register ******************************************************************************/ /*! * @brief HW_EWM_CMPH - Compare High Register (RW) * * Reset value: 0xFFU * * The CMPH register is reset to 0xFF after a CPU reset. This provides a maximum * of 256 clocks time, for the CPU to service the EWM counter. This register can * be written only once after a CPU reset. Writing this register more than once * generates a bus transfer error. The valid values for CMPH are up to 0xFE * because the EWM counter never expires when CMPH = 0xFF. The expiration happens only * if EWM counter is greater than CMPH. */ typedef union _hw_ewm_cmph { uint8_t U; struct _hw_ewm_cmph_bitfields { uint8_t COMPAREH : 8; /*!< [7:0] */ } B; } hw_ewm_cmph_t; /*! * @name Constants and macros for entire EWM_CMPH register */ /*@{*/ #define HW_EWM_CMPH_ADDR(x) ((x) + 0x3U) #define HW_EWM_CMPH(x) (*(__IO hw_ewm_cmph_t *) HW_EWM_CMPH_ADDR(x)) #define HW_EWM_CMPH_RD(x) (HW_EWM_CMPH(x).U) #define HW_EWM_CMPH_WR(x, v) (HW_EWM_CMPH(x).U = (v)) #define HW_EWM_CMPH_SET(x, v) (HW_EWM_CMPH_WR(x, HW_EWM_CMPH_RD(x) | (v))) #define HW_EWM_CMPH_CLR(x, v) (HW_EWM_CMPH_WR(x, HW_EWM_CMPH_RD(x) & ~(v))) #define HW_EWM_CMPH_TOG(x, v) (HW_EWM_CMPH_WR(x, HW_EWM_CMPH_RD(x) ^ (v))) /*@}*/ /* * Constants & macros for individual EWM_CMPH bitfields */ /*! * @name Register EWM_CMPH, field COMPAREH[7:0] (RW) * * To prevent runaway code from changing this field, software should write to * this field after a CPU reset even if the (default) maximum service time is * required. */ /*@{*/ #define BP_EWM_CMPH_COMPAREH (0U) /*!< Bit position for EWM_CMPH_COMPAREH. */ #define BM_EWM_CMPH_COMPAREH (0xFFU) /*!< Bit mask for EWM_CMPH_COMPAREH. */ #define BS_EWM_CMPH_COMPAREH (8U) /*!< Bit field size in bits for EWM_CMPH_COMPAREH. */ /*! @brief Read current value of the EWM_CMPH_COMPAREH field. */ #define BR_EWM_CMPH_COMPAREH(x) (HW_EWM_CMPH(x).U) /*! @brief Format value for bitfield EWM_CMPH_COMPAREH. */ #define BF_EWM_CMPH_COMPAREH(v) ((uint8_t)((uint8_t)(v) << BP_EWM_CMPH_COMPAREH) & BM_EWM_CMPH_COMPAREH) /*! @brief Set the COMPAREH field to a new value. */ #define BW_EWM_CMPH_COMPAREH(x, v) (HW_EWM_CMPH_WR(x, v)) /*@}*/ /******************************************************************************* * hw_ewm_t - module struct ******************************************************************************/ /*! * @brief All EWM module registers. */ #pragma pack(1) typedef struct _hw_ewm { __IO hw_ewm_ctrl_t CTRL; /*!< [0x0] Control Register */ __O hw_ewm_serv_t SERV; /*!< [0x1] Service Register */ __IO hw_ewm_cmpl_t CMPL; /*!< [0x2] Compare Low Register */ __IO hw_ewm_cmph_t CMPH; /*!< [0x3] Compare High Register */ } hw_ewm_t; #pragma pack() /*! @brief Macro to access all EWM registers. */ /*! @param x EWM module instance base address. */ /*! @return Reference (not a pointer) to the registers struct. To get a pointer to the struct, * use the '&' operator, like &HW_EWM(EWM_BASE). */ #define HW_EWM(x) (*(hw_ewm_t *)(x)) #endif /* __HW_EWM_REGISTERS_H__ */ /* EOF */ ================================================ FILE: Zelig/mbed/TARGET_K64F/TARGET_Freescale/TARGET_KPSDK_MCUS/TARGET_MCU_K64F/device/device/MK64F12/MK64F12_fb.h ================================================ /* ** ################################################################### ** Compilers: Keil ARM C/C++ Compiler ** Freescale C/C++ for Embedded ARM ** GNU C Compiler ** IAR ANSI C/C++ Compiler for ARM ** ** Reference manual: K64P144M120SF5RM, Rev.2, January 2014 ** Version: rev. 2.5, 2014-02-10 ** Build: b140604 ** ** Abstract: ** Extension to the CMSIS register access layer header. ** ** Copyright (c) 2014 Freescale Semiconductor, Inc. ** All rights reserved. ** ** Redistribution and use in source and binary forms, with or without modification, ** are permitted provided that the following conditions are met: ** ** o Redistributions of source code must retain the above copyright notice, this list ** of conditions and the following disclaimer. ** ** o Redistributions in binary form must reproduce the above copyright notice, this ** list of conditions and the following disclaimer in the documentation and/or ** other materials provided with the distribution. ** ** o Neither the name of Freescale Semiconductor, Inc. nor the names of its ** contributors may be used to endorse or promote products derived from this ** software without specific prior written permission. ** ** THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ** ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED ** WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE ** DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT 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. ** ** http: www.freescale.com ** mail: support@freescale.com ** ** Revisions: ** - rev. 1.0 (2013-08-12) ** Initial version. ** - rev. 2.0 (2013-10-29) ** Register accessor macros added to the memory map. ** Symbols for Processor Expert memory map compatibility added to the memory map. ** Startup file for gcc has been updated according to CMSIS 3.2. ** System initialization updated. ** MCG - registers updated. ** PORTA, PORTB, PORTC, PORTE - registers for digital filter removed. ** - rev. 2.1 (2013-10-30) ** Definition of BITBAND macros updated to support peripherals with 32-bit acces disabled. ** - rev. 2.2 (2013-12-09) ** DMA - EARS register removed. ** AIPS0, AIPS1 - MPRA register updated. ** - rev. 2.3 (2014-01-24) ** Update according to reference manual rev. 2 ** ENET, MCG, MCM, SIM, USB - registers updated ** - rev. 2.4 (2014-02-10) ** The declaration of clock configurations has been moved to separate header file system_MK64F12.h ** Update of SystemInit() and SystemCoreClockUpdate() functions. ** - rev. 2.5 (2014-02-10) ** The declaration of clock configurations has been moved to separate header file system_MK64F12.h ** Update of SystemInit() and SystemCoreClockUpdate() functions. ** Module access macro module_BASES replaced by module_BASE_PTRS. ** ** ################################################################### */ /* * WARNING! DO NOT EDIT THIS FILE DIRECTLY! * * This file was generated automatically and any changes may be lost. */ #ifndef __HW_FB_REGISTERS_H__ #define __HW_FB_REGISTERS_H__ #include "MK64F12.h" #include "fsl_bitaccess.h" /* * MK64F12 FB * * FlexBus external bus interface * * Registers defined in this header file: * - HW_FB_CSARn - Chip Select Address Register * - HW_FB_CSMRn - Chip Select Mask Register * - HW_FB_CSCRn - Chip Select Control Register * - HW_FB_CSPMCR - Chip Select port Multiplexing Control Register * * - hw_fb_t - Struct containing all module registers. */ #define HW_FB_INSTANCE_COUNT (1U) /*!< Number of instances of the FB module. */ /******************************************************************************* * HW_FB_CSARn - Chip Select Address Register ******************************************************************************/ /*! * @brief HW_FB_CSARn - Chip Select Address Register (RW) * * Reset value: 0x00000000U * * Specifies the associated chip-select's base address. */ typedef union _hw_fb_csarn { uint32_t U; struct _hw_fb_csarn_bitfields { uint32_t RESERVED0 : 16; /*!< [15:0] */ uint32_t BA : 16; /*!< [31:16] Base Address */ } B; } hw_fb_csarn_t; /*! * @name Constants and macros for entire FB_CSARn register */ /*@{*/ #define HW_FB_CSARn_COUNT (6U) #define HW_FB_CSARn_ADDR(x, n) ((x) + 0x0U + (0xCU * (n))) #define HW_FB_CSARn(x, n) (*(__IO hw_fb_csarn_t *) HW_FB_CSARn_ADDR(x, n)) #define HW_FB_CSARn_RD(x, n) (HW_FB_CSARn(x, n).U) #define HW_FB_CSARn_WR(x, n, v) (HW_FB_CSARn(x, n).U = (v)) #define HW_FB_CSARn_SET(x, n, v) (HW_FB_CSARn_WR(x, n, HW_FB_CSARn_RD(x, n) | (v))) #define HW_FB_CSARn_CLR(x, n, v) (HW_FB_CSARn_WR(x, n, HW_FB_CSARn_RD(x, n) & ~(v))) #define HW_FB_CSARn_TOG(x, n, v) (HW_FB_CSARn_WR(x, n, HW_FB_CSARn_RD(x, n) ^ (v))) /*@}*/ /* * Constants & macros for individual FB_CSARn bitfields */ /*! * @name Register FB_CSARn, field BA[31:16] (RW) * * Defines the base address for memory dedicated to the associated chip-select. * BA is compared to bits 31-16 on the internal address bus to determine if the * associated chip-select's memory is being accessed. Because the FlexBus module * is one of the slaves connected to the crossbar switch, it is only accessible * within a certain memory range. See the chip memory map for the applicable * FlexBus "expansion" address range for which the chip-selects can be active. Set the * CSARn and CSMRn registers appropriately before accessing this region. */ /*@{*/ #define BP_FB_CSARn_BA (16U) /*!< Bit position for FB_CSARn_BA. */ #define BM_FB_CSARn_BA (0xFFFF0000U) /*!< Bit mask for FB_CSARn_BA. */ #define BS_FB_CSARn_BA (16U) /*!< Bit field size in bits for FB_CSARn_BA. */ /*! @brief Read current value of the FB_CSARn_BA field. */ #define BR_FB_CSARn_BA(x, n) (HW_FB_CSARn(x, n).B.BA) /*! @brief Format value for bitfield FB_CSARn_BA. */ #define BF_FB_CSARn_BA(v) ((uint32_t)((uint32_t)(v) << BP_FB_CSARn_BA) & BM_FB_CSARn_BA) /*! @brief Set the BA field to a new value. */ #define BW_FB_CSARn_BA(x, n, v) (HW_FB_CSARn_WR(x, n, (HW_FB_CSARn_RD(x, n) & ~BM_FB_CSARn_BA) | BF_FB_CSARn_BA(v))) /*@}*/ /******************************************************************************* * HW_FB_CSMRn - Chip Select Mask Register ******************************************************************************/ /*! * @brief HW_FB_CSMRn - Chip Select Mask Register (RW) * * Reset value: 0x00000000U * * Specifies the address mask and allowable access types for the associated * chip-select. */ typedef union _hw_fb_csmrn { uint32_t U; struct _hw_fb_csmrn_bitfields { uint32_t V : 1; /*!< [0] Valid */ uint32_t RESERVED0 : 7; /*!< [7:1] */ uint32_t WP : 1; /*!< [8] Write Protect */ uint32_t RESERVED1 : 7; /*!< [15:9] */ uint32_t BAM : 16; /*!< [31:16] Base Address Mask */ } B; } hw_fb_csmrn_t; /*! * @name Constants and macros for entire FB_CSMRn register */ /*@{*/ #define HW_FB_CSMRn_COUNT (6U) #define HW_FB_CSMRn_ADDR(x, n) ((x) + 0x4U + (0xCU * (n))) #define HW_FB_CSMRn(x, n) (*(__IO hw_fb_csmrn_t *) HW_FB_CSMRn_ADDR(x, n)) #define HW_FB_CSMRn_RD(x, n) (HW_FB_CSMRn(x, n).U) #define HW_FB_CSMRn_WR(x, n, v) (HW_FB_CSMRn(x, n).U = (v)) #define HW_FB_CSMRn_SET(x, n, v) (HW_FB_CSMRn_WR(x, n, HW_FB_CSMRn_RD(x, n) | (v))) #define HW_FB_CSMRn_CLR(x, n, v) (HW_FB_CSMRn_WR(x, n, HW_FB_CSMRn_RD(x, n) & ~(v))) #define HW_FB_CSMRn_TOG(x, n, v) (HW_FB_CSMRn_WR(x, n, HW_FB_CSMRn_RD(x, n) ^ (v))) /*@}*/ /* * Constants & macros for individual FB_CSMRn bitfields */ /*! * @name Register FB_CSMRn, field V[0] (RW) * * Specifies whether the corresponding CSAR, CSMR, and CSCR contents are valid. * Programmed chip-selects do not assert until the V bit is 1b (except for * FB_CS0, which acts as the global chip-select). At reset, FB_CS0 will fire for any * access to the FlexBus memory region. CSMR0[V] must be set as part of the chip * select initialization sequence to allow other chip selects to function as * programmed. * * Values: * - 0 - Chip-select is invalid. * - 1 - Chip-select is valid. */ /*@{*/ #define BP_FB_CSMRn_V (0U) /*!< Bit position for FB_CSMRn_V. */ #define BM_FB_CSMRn_V (0x00000001U) /*!< Bit mask for FB_CSMRn_V. */ #define BS_FB_CSMRn_V (1U) /*!< Bit field size in bits for FB_CSMRn_V. */ /*! @brief Read current value of the FB_CSMRn_V field. */ #define BR_FB_CSMRn_V(x, n) (BITBAND_ACCESS32(HW_FB_CSMRn_ADDR(x, n), BP_FB_CSMRn_V)) /*! @brief Format value for bitfield FB_CSMRn_V. */ #define BF_FB_CSMRn_V(v) ((uint32_t)((uint32_t)(v) << BP_FB_CSMRn_V) & BM_FB_CSMRn_V) /*! @brief Set the V field to a new value. */ #define BW_FB_CSMRn_V(x, n, v) (BITBAND_ACCESS32(HW_FB_CSMRn_ADDR(x, n), BP_FB_CSMRn_V) = (v)) /*@}*/ /*! * @name Register FB_CSMRn, field WP[8] (RW) * * Controls write accesses to the address range in the corresponding CSAR. * * Values: * - 0 - Write accesses are allowed. * - 1 - Write accesses are not allowed. Attempting to write to the range of * addresses for which the WP bit is set results in a bus error termination of * the internal cycle and no external cycle. */ /*@{*/ #define BP_FB_CSMRn_WP (8U) /*!< Bit position for FB_CSMRn_WP. */ #define BM_FB_CSMRn_WP (0x00000100U) /*!< Bit mask for FB_CSMRn_WP. */ #define BS_FB_CSMRn_WP (1U) /*!< Bit field size in bits for FB_CSMRn_WP. */ /*! @brief Read current value of the FB_CSMRn_WP field. */ #define BR_FB_CSMRn_WP(x, n) (BITBAND_ACCESS32(HW_FB_CSMRn_ADDR(x, n), BP_FB_CSMRn_WP)) /*! @brief Format value for bitfield FB_CSMRn_WP. */ #define BF_FB_CSMRn_WP(v) ((uint32_t)((uint32_t)(v) << BP_FB_CSMRn_WP) & BM_FB_CSMRn_WP) /*! @brief Set the WP field to a new value. */ #define BW_FB_CSMRn_WP(x, n, v) (BITBAND_ACCESS32(HW_FB_CSMRn_ADDR(x, n), BP_FB_CSMRn_WP) = (v)) /*@}*/ /*! * @name Register FB_CSMRn, field BAM[31:16] (RW) * * Defines the associated chip-select's block size by masking address bits. * * Values: * - 0 - The corresponding address bit in CSAR is used in the chip-select decode. * - 1 - The corresponding address bit in CSAR is a don't care in the * chip-select decode. */ /*@{*/ #define BP_FB_CSMRn_BAM (16U) /*!< Bit position for FB_CSMRn_BAM. */ #define BM_FB_CSMRn_BAM (0xFFFF0000U) /*!< Bit mask for FB_CSMRn_BAM. */ #define BS_FB_CSMRn_BAM (16U) /*!< Bit field size in bits for FB_CSMRn_BAM. */ /*! @brief Read current value of the FB_CSMRn_BAM field. */ #define BR_FB_CSMRn_BAM(x, n) (HW_FB_CSMRn(x, n).B.BAM) /*! @brief Format value for bitfield FB_CSMRn_BAM. */ #define BF_FB_CSMRn_BAM(v) ((uint32_t)((uint32_t)(v) << BP_FB_CSMRn_BAM) & BM_FB_CSMRn_BAM) /*! @brief Set the BAM field to a new value. */ #define BW_FB_CSMRn_BAM(x, n, v) (HW_FB_CSMRn_WR(x, n, (HW_FB_CSMRn_RD(x, n) & ~BM_FB_CSMRn_BAM) | BF_FB_CSMRn_BAM(v))) /*@}*/ /******************************************************************************* * HW_FB_CSCRn - Chip Select Control Register ******************************************************************************/ /*! * @brief HW_FB_CSCRn - Chip Select Control Register (RW) * * Reset value: 0x003FFC00U * * Controls the auto-acknowledge, address setup and hold times, port size, burst * capability, and number of wait states for the associated chip select. To * support the global chip-select (FB_CS0), the CSCR0 reset values differ from the * other CSCRs. The reset value of CSCR0 is as follows: Bits 31-24 are 0b Bit 23-3 * are chip-dependent Bits 3-0 are 0b See the chip configuration details for your * particular chip for information on the exact CSCR0 reset value. */ typedef union _hw_fb_cscrn { uint32_t U; struct _hw_fb_cscrn_bitfields { uint32_t RESERVED0 : 3; /*!< [2:0] */ uint32_t BSTW : 1; /*!< [3] Burst-Write Enable */ uint32_t BSTR : 1; /*!< [4] Burst-Read Enable */ uint32_t BEM : 1; /*!< [5] Byte-Enable Mode */ uint32_t PS : 2; /*!< [7:6] Port Size */ uint32_t AA : 1; /*!< [8] Auto-Acknowledge Enable */ uint32_t BLS : 1; /*!< [9] Byte-Lane Shift */ uint32_t WS : 6; /*!< [15:10] Wait States */ uint32_t WRAH : 2; /*!< [17:16] Write Address Hold or Deselect */ uint32_t RDAH : 2; /*!< [19:18] Read Address Hold or Deselect */ uint32_t ASET : 2; /*!< [21:20] Address Setup */ uint32_t EXTS : 1; /*!< [22] */ uint32_t SWSEN : 1; /*!< [23] Secondary Wait State Enable */ uint32_t RESERVED1 : 2; /*!< [25:24] */ uint32_t SWS : 6; /*!< [31:26] Secondary Wait States */ } B; } hw_fb_cscrn_t; /*! * @name Constants and macros for entire FB_CSCRn register */ /*@{*/ #define HW_FB_CSCRn_COUNT (6U) #define HW_FB_CSCRn_ADDR(x, n) ((x) + 0x8U + (0xCU * (n))) #define HW_FB_CSCRn(x, n) (*(__IO hw_fb_cscrn_t *) HW_FB_CSCRn_ADDR(x, n)) #define HW_FB_CSCRn_RD(x, n) (HW_FB_CSCRn(x, n).U) #define HW_FB_CSCRn_WR(x, n, v) (HW_FB_CSCRn(x, n).U = (v)) #define HW_FB_CSCRn_SET(x, n, v) (HW_FB_CSCRn_WR(x, n, HW_FB_CSCRn_RD(x, n) | (v))) #define HW_FB_CSCRn_CLR(x, n, v) (HW_FB_CSCRn_WR(x, n, HW_FB_CSCRn_RD(x, n) & ~(v))) #define HW_FB_CSCRn_TOG(x, n, v) (HW_FB_CSCRn_WR(x, n, HW_FB_CSCRn_RD(x, n) ^ (v))) /*@}*/ /* * Constants & macros for individual FB_CSCRn bitfields */ /*! * @name Register FB_CSCRn, field BSTW[3] (RW) * * Specifies whether burst writes are enabled for memory associated with each * chip select. * * Values: * - 0 - Disabled. Data exceeding the specified port size is broken into * individual, port-sized, non-burst writes. For example, a 32-bit write to an 8-bit * port takes four byte writes. * - 1 - Enabled. Enables burst write of data larger than the specified port * size, including 32-bit writes to 8- and 16-bit ports, 16-bit writes to 8-bit * ports, and line writes to 8-, 16-, and 32-bit ports. */ /*@{*/ #define BP_FB_CSCRn_BSTW (3U) /*!< Bit position for FB_CSCRn_BSTW. */ #define BM_FB_CSCRn_BSTW (0x00000008U) /*!< Bit mask for FB_CSCRn_BSTW. */ #define BS_FB_CSCRn_BSTW (1U) /*!< Bit field size in bits for FB_CSCRn_BSTW. */ /*! @brief Read current value of the FB_CSCRn_BSTW field. */ #define BR_FB_CSCRn_BSTW(x, n) (BITBAND_ACCESS32(HW_FB_CSCRn_ADDR(x, n), BP_FB_CSCRn_BSTW)) /*! @brief Format value for bitfield FB_CSCRn_BSTW. */ #define BF_FB_CSCRn_BSTW(v) ((uint32_t)((uint32_t)(v) << BP_FB_CSCRn_BSTW) & BM_FB_CSCRn_BSTW) /*! @brief Set the BSTW field to a new value. */ #define BW_FB_CSCRn_BSTW(x, n, v) (BITBAND_ACCESS32(HW_FB_CSCRn_ADDR(x, n), BP_FB_CSCRn_BSTW) = (v)) /*@}*/ /*! * @name Register FB_CSCRn, field BSTR[4] (RW) * * Specifies whether burst reads are enabled for memory associated with each * chip select. * * Values: * - 0 - Disabled. Data exceeding the specified port size is broken into * individual, port-sized, non-burst reads. For example, a 32-bit read from an 8-bit * port is broken into four 8-bit reads. * - 1 - Enabled. Enables data burst reads larger than the specified port size, * including 32-bit reads from 8- and 16-bit ports, 16-bit reads from 8-bit * ports, and line reads from 8-, 16-, and 32-bit ports. */ /*@{*/ #define BP_FB_CSCRn_BSTR (4U) /*!< Bit position for FB_CSCRn_BSTR. */ #define BM_FB_CSCRn_BSTR (0x00000010U) /*!< Bit mask for FB_CSCRn_BSTR. */ #define BS_FB_CSCRn_BSTR (1U) /*!< Bit field size in bits for FB_CSCRn_BSTR. */ /*! @brief Read current value of the FB_CSCRn_BSTR field. */ #define BR_FB_CSCRn_BSTR(x, n) (BITBAND_ACCESS32(HW_FB_CSCRn_ADDR(x, n), BP_FB_CSCRn_BSTR)) /*! @brief Format value for bitfield FB_CSCRn_BSTR. */ #define BF_FB_CSCRn_BSTR(v) ((uint32_t)((uint32_t)(v) << BP_FB_CSCRn_BSTR) & BM_FB_CSCRn_BSTR) /*! @brief Set the BSTR field to a new value. */ #define BW_FB_CSCRn_BSTR(x, n, v) (BITBAND_ACCESS32(HW_FB_CSCRn_ADDR(x, n), BP_FB_CSCRn_BSTR) = (v)) /*@}*/ /*! * @name Register FB_CSCRn, field BEM[5] (RW) * * Specifies whether the corresponding FB_BE is asserted for read accesses. * Certain memories have byte enables that must be asserted during reads and writes. * Write 1b to the BEM bit in the relevant CSCR to provide the appropriate mode * of byte enable support for these SRAMs. * * Values: * - 0 - FB_BE is asserted for data write only. * - 1 - FB_BE is asserted for data read and write accesses. */ /*@{*/ #define BP_FB_CSCRn_BEM (5U) /*!< Bit position for FB_CSCRn_BEM. */ #define BM_FB_CSCRn_BEM (0x00000020U) /*!< Bit mask for FB_CSCRn_BEM. */ #define BS_FB_CSCRn_BEM (1U) /*!< Bit field size in bits for FB_CSCRn_BEM. */ /*! @brief Read current value of the FB_CSCRn_BEM field. */ #define BR_FB_CSCRn_BEM(x, n) (BITBAND_ACCESS32(HW_FB_CSCRn_ADDR(x, n), BP_FB_CSCRn_BEM)) /*! @brief Format value for bitfield FB_CSCRn_BEM. */ #define BF_FB_CSCRn_BEM(v) ((uint32_t)((uint32_t)(v) << BP_FB_CSCRn_BEM) & BM_FB_CSCRn_BEM) /*! @brief Set the BEM field to a new value. */ #define BW_FB_CSCRn_BEM(x, n, v) (BITBAND_ACCESS32(HW_FB_CSCRn_ADDR(x, n), BP_FB_CSCRn_BEM) = (v)) /*@}*/ /*! * @name Register FB_CSCRn, field PS[7:6] (RW) * * Specifies the data port width of the associated chip-select, and determines * where data is driven during write cycles and where data is sampled during read * cycles. * * Values: * - 00 - 32-bit port size. Valid data is sampled and driven on FB_D[31:0]. * - 01 - 8-bit port size. Valid data is sampled and driven on FB_D[31:24] when * BLS is 0b, or FB_D[7:0] when BLS is 1b. */ /*@{*/ #define BP_FB_CSCRn_PS (6U) /*!< Bit position for FB_CSCRn_PS. */ #define BM_FB_CSCRn_PS (0x000000C0U) /*!< Bit mask for FB_CSCRn_PS. */ #define BS_FB_CSCRn_PS (2U) /*!< Bit field size in bits for FB_CSCRn_PS. */ /*! @brief Read current value of the FB_CSCRn_PS field. */ #define BR_FB_CSCRn_PS(x, n) (HW_FB_CSCRn(x, n).B.PS) /*! @brief Format value for bitfield FB_CSCRn_PS. */ #define BF_FB_CSCRn_PS(v) ((uint32_t)((uint32_t)(v) << BP_FB_CSCRn_PS) & BM_FB_CSCRn_PS) /*! @brief Set the PS field to a new value. */ #define BW_FB_CSCRn_PS(x, n, v) (HW_FB_CSCRn_WR(x, n, (HW_FB_CSCRn_RD(x, n) & ~BM_FB_CSCRn_PS) | BF_FB_CSCRn_PS(v))) /*@}*/ /*! * @name Register FB_CSCRn, field AA[8] (RW) * * Asserts the internal transfer acknowledge for accesses specified by the * chip-select address. If AA is 1b for a corresponding FB_CSn and the external system * asserts an external FB_TA before the wait-state countdown asserts the * internal FB_TA, the cycle is terminated. Burst cycles increment the address bus * between each internal termination. This field must be 1b if CSPMCR disables FB_TA. * * Values: * - 0 - Disabled. No internal transfer acknowledge is asserted and the cycle is * terminated externally. * - 1 - Enabled. Internal transfer acknowledge is asserted as specified by WS. */ /*@{*/ #define BP_FB_CSCRn_AA (8U) /*!< Bit position for FB_CSCRn_AA. */ #define BM_FB_CSCRn_AA (0x00000100U) /*!< Bit mask for FB_CSCRn_AA. */ #define BS_FB_CSCRn_AA (1U) /*!< Bit field size in bits for FB_CSCRn_AA. */ /*! @brief Read current value of the FB_CSCRn_AA field. */ #define BR_FB_CSCRn_AA(x, n) (BITBAND_ACCESS32(HW_FB_CSCRn_ADDR(x, n), BP_FB_CSCRn_AA)) /*! @brief Format value for bitfield FB_CSCRn_AA. */ #define BF_FB_CSCRn_AA(v) ((uint32_t)((uint32_t)(v) << BP_FB_CSCRn_AA) & BM_FB_CSCRn_AA) /*! @brief Set the AA field to a new value. */ #define BW_FB_CSCRn_AA(x, n, v) (BITBAND_ACCESS32(HW_FB_CSCRn_ADDR(x, n), BP_FB_CSCRn_AA) = (v)) /*@}*/ /*! * @name Register FB_CSCRn, field BLS[9] (RW) * * Specifies if data on FB_AD appears left-aligned or right-aligned during the * data phase of a FlexBus access. * * Values: * - 0 - Not shifted. Data is left-aligned on FB_AD. * - 1 - Shifted. Data is right-aligned on FB_AD. */ /*@{*/ #define BP_FB_CSCRn_BLS (9U) /*!< Bit position for FB_CSCRn_BLS. */ #define BM_FB_CSCRn_BLS (0x00000200U) /*!< Bit mask for FB_CSCRn_BLS. */ #define BS_FB_CSCRn_BLS (1U) /*!< Bit field size in bits for FB_CSCRn_BLS. */ /*! @brief Read current value of the FB_CSCRn_BLS field. */ #define BR_FB_CSCRn_BLS(x, n) (BITBAND_ACCESS32(HW_FB_CSCRn_ADDR(x, n), BP_FB_CSCRn_BLS)) /*! @brief Format value for bitfield FB_CSCRn_BLS. */ #define BF_FB_CSCRn_BLS(v) ((uint32_t)((uint32_t)(v) << BP_FB_CSCRn_BLS) & BM_FB_CSCRn_BLS) /*! @brief Set the BLS field to a new value. */ #define BW_FB_CSCRn_BLS(x, n, v) (BITBAND_ACCESS32(HW_FB_CSCRn_ADDR(x, n), BP_FB_CSCRn_BLS) = (v)) /*@}*/ /*! * @name Register FB_CSCRn, field WS[15:10] (RW) * * Specifies the number of wait states inserted after FlexBus asserts the * associated chip-select and before an internal transfer acknowledge is generated (WS * = 00h inserts 0 wait states, ..., WS = 3Fh inserts 63 wait states). */ /*@{*/ #define BP_FB_CSCRn_WS (10U) /*!< Bit position for FB_CSCRn_WS. */ #define BM_FB_CSCRn_WS (0x0000FC00U) /*!< Bit mask for FB_CSCRn_WS. */ #define BS_FB_CSCRn_WS (6U) /*!< Bit field size in bits for FB_CSCRn_WS. */ /*! @brief Read current value of the FB_CSCRn_WS field. */ #define BR_FB_CSCRn_WS(x, n) (HW_FB_CSCRn(x, n).B.WS) /*! @brief Format value for bitfield FB_CSCRn_WS. */ #define BF_FB_CSCRn_WS(v) ((uint32_t)((uint32_t)(v) << BP_FB_CSCRn_WS) & BM_FB_CSCRn_WS) /*! @brief Set the WS field to a new value. */ #define BW_FB_CSCRn_WS(x, n, v) (HW_FB_CSCRn_WR(x, n, (HW_FB_CSCRn_RD(x, n) & ~BM_FB_CSCRn_WS) | BF_FB_CSCRn_WS(v))) /*@}*/ /*! * @name Register FB_CSCRn, field WRAH[17:16] (RW) * * Controls the address, data, and attribute hold time after the termination of * a write cycle that hits in the associated chip-select's address space. The * hold time applies only at the end of a transfer. Therefore, during a burst * transfer or a transfer to a port size smaller than the transfer size, the hold time * is only added after the last bus cycle. * * Values: * - 00 - 1 cycle (default for all but FB_CS0 ) * - 01 - 2 cycles * - 10 - 3 cycles * - 11 - 4 cycles (default for FB_CS0 ) */ /*@{*/ #define BP_FB_CSCRn_WRAH (16U) /*!< Bit position for FB_CSCRn_WRAH. */ #define BM_FB_CSCRn_WRAH (0x00030000U) /*!< Bit mask for FB_CSCRn_WRAH. */ #define BS_FB_CSCRn_WRAH (2U) /*!< Bit field size in bits for FB_CSCRn_WRAH. */ /*! @brief Read current value of the FB_CSCRn_WRAH field. */ #define BR_FB_CSCRn_WRAH(x, n) (HW_FB_CSCRn(x, n).B.WRAH) /*! @brief Format value for bitfield FB_CSCRn_WRAH. */ #define BF_FB_CSCRn_WRAH(v) ((uint32_t)((uint32_t)(v) << BP_FB_CSCRn_WRAH) & BM_FB_CSCRn_WRAH) /*! @brief Set the WRAH field to a new value. */ #define BW_FB_CSCRn_WRAH(x, n, v) (HW_FB_CSCRn_WR(x, n, (HW_FB_CSCRn_RD(x, n) & ~BM_FB_CSCRn_WRAH) | BF_FB_CSCRn_WRAH(v))) /*@}*/ /*! * @name Register FB_CSCRn, field RDAH[19:18] (RW) * * Controls the address and attribute hold time after the termination during a * read cycle that hits in the associated chip-select's address space. The hold * time applies only at the end of a transfer. Therefore, during a burst transfer * or a transfer to a port size smaller than the transfer size, the hold time is * only added after the last bus cycle. The number of cycles the address and * attributes are held after FB_CSn deassertion depends on the value of the AA bit. * * Values: * - 00 - When AA is 0b, 1 cycle. When AA is 1b, 0 cycles. * - 01 - When AA is 0b, 2 cycles. When AA is 1b, 1 cycle. * - 10 - When AA is 0b, 3 cycles. When AA is 1b, 2 cycles. * - 11 - When AA is 0b, 4 cycles. When AA is 1b, 3 cycles. */ /*@{*/ #define BP_FB_CSCRn_RDAH (18U) /*!< Bit position for FB_CSCRn_RDAH. */ #define BM_FB_CSCRn_RDAH (0x000C0000U) /*!< Bit mask for FB_CSCRn_RDAH. */ #define BS_FB_CSCRn_RDAH (2U) /*!< Bit field size in bits for FB_CSCRn_RDAH. */ /*! @brief Read current value of the FB_CSCRn_RDAH field. */ #define BR_FB_CSCRn_RDAH(x, n) (HW_FB_CSCRn(x, n).B.RDAH) /*! @brief Format value for bitfield FB_CSCRn_RDAH. */ #define BF_FB_CSCRn_RDAH(v) ((uint32_t)((uint32_t)(v) << BP_FB_CSCRn_RDAH) & BM_FB_CSCRn_RDAH) /*! @brief Set the RDAH field to a new value. */ #define BW_FB_CSCRn_RDAH(x, n, v) (HW_FB_CSCRn_WR(x, n, (HW_FB_CSCRn_RD(x, n) & ~BM_FB_CSCRn_RDAH) | BF_FB_CSCRn_RDAH(v))) /*@}*/ /*! * @name Register FB_CSCRn, field ASET[21:20] (RW) * * Controls when the chip-select is asserted with respect to assertion of a * valid address and attributes. * * Values: * - 00 - Assert FB_CSn on the first rising clock edge after the address is * asserted (default for all but FB_CS0 ). * - 01 - Assert FB_CSn on the second rising clock edge after the address is * asserted. * - 10 - Assert FB_CSn on the third rising clock edge after the address is * asserted. * - 11 - Assert FB_CSn on the fourth rising clock edge after the address is * asserted (default for FB_CS0 ). */ /*@{*/ #define BP_FB_CSCRn_ASET (20U) /*!< Bit position for FB_CSCRn_ASET. */ #define BM_FB_CSCRn_ASET (0x00300000U) /*!< Bit mask for FB_CSCRn_ASET. */ #define BS_FB_CSCRn_ASET (2U) /*!< Bit field size in bits for FB_CSCRn_ASET. */ /*! @brief Read current value of the FB_CSCRn_ASET field. */ #define BR_FB_CSCRn_ASET(x, n) (HW_FB_CSCRn(x, n).B.ASET) /*! @brief Format value for bitfield FB_CSCRn_ASET. */ #define BF_FB_CSCRn_ASET(v) ((uint32_t)((uint32_t)(v) << BP_FB_CSCRn_ASET) & BM_FB_CSCRn_ASET) /*! @brief Set the ASET field to a new value. */ #define BW_FB_CSCRn_ASET(x, n, v) (HW_FB_CSCRn_WR(x, n, (HW_FB_CSCRn_RD(x, n) & ~BM_FB_CSCRn_ASET) | BF_FB_CSCRn_ASET(v))) /*@}*/ /*! * @name Register FB_CSCRn, field EXTS[22] (RW) * * Extended Transfer Start/Extended Address Latch Enable Controls how long FB_TS * /FB_ALE is asserted. * * Values: * - 0 - Disabled. FB_TS /FB_ALE asserts for one bus clock cycle. * - 1 - Enabled. FB_TS /FB_ALE remains asserted until the first positive clock * edge after FB_CSn asserts. */ /*@{*/ #define BP_FB_CSCRn_EXTS (22U) /*!< Bit position for FB_CSCRn_EXTS. */ #define BM_FB_CSCRn_EXTS (0x00400000U) /*!< Bit mask for FB_CSCRn_EXTS. */ #define BS_FB_CSCRn_EXTS (1U) /*!< Bit field size in bits for FB_CSCRn_EXTS. */ /*! @brief Read current value of the FB_CSCRn_EXTS field. */ #define BR_FB_CSCRn_EXTS(x, n) (BITBAND_ACCESS32(HW_FB_CSCRn_ADDR(x, n), BP_FB_CSCRn_EXTS)) /*! @brief Format value for bitfield FB_CSCRn_EXTS. */ #define BF_FB_CSCRn_EXTS(v) ((uint32_t)((uint32_t)(v) << BP_FB_CSCRn_EXTS) & BM_FB_CSCRn_EXTS) /*! @brief Set the EXTS field to a new value. */ #define BW_FB_CSCRn_EXTS(x, n, v) (BITBAND_ACCESS32(HW_FB_CSCRn_ADDR(x, n), BP_FB_CSCRn_EXTS) = (v)) /*@}*/ /*! * @name Register FB_CSCRn, field SWSEN[23] (RW) * * Values: * - 0 - Disabled. A number of wait states (specified by WS) are inserted before * an internal transfer acknowledge is generated for all transfers. * - 1 - Enabled. A number of wait states (specified by SWS) are inserted before * an internal transfer acknowledge is generated for burst transfer * secondary terminations. */ /*@{*/ #define BP_FB_CSCRn_SWSEN (23U) /*!< Bit position for FB_CSCRn_SWSEN. */ #define BM_FB_CSCRn_SWSEN (0x00800000U) /*!< Bit mask for FB_CSCRn_SWSEN. */ #define BS_FB_CSCRn_SWSEN (1U) /*!< Bit field size in bits for FB_CSCRn_SWSEN. */ /*! @brief Read current value of the FB_CSCRn_SWSEN field. */ #define BR_FB_CSCRn_SWSEN(x, n) (BITBAND_ACCESS32(HW_FB_CSCRn_ADDR(x, n), BP_FB_CSCRn_SWSEN)) /*! @brief Format value for bitfield FB_CSCRn_SWSEN. */ #define BF_FB_CSCRn_SWSEN(v) ((uint32_t)((uint32_t)(v) << BP_FB_CSCRn_SWSEN) & BM_FB_CSCRn_SWSEN) /*! @brief Set the SWSEN field to a new value. */ #define BW_FB_CSCRn_SWSEN(x, n, v) (BITBAND_ACCESS32(HW_FB_CSCRn_ADDR(x, n), BP_FB_CSCRn_SWSEN) = (v)) /*@}*/ /*! * @name Register FB_CSCRn, field SWS[31:26] (RW) * * Used only when the SWSEN bit is 1b. Specifies the number of wait states * inserted before an internal transfer acknowledge is generated for a burst transfer * (except for the first termination, which is controlled by WS). */ /*@{*/ #define BP_FB_CSCRn_SWS (26U) /*!< Bit position for FB_CSCRn_SWS. */ #define BM_FB_CSCRn_SWS (0xFC000000U) /*!< Bit mask for FB_CSCRn_SWS. */ #define BS_FB_CSCRn_SWS (6U) /*!< Bit field size in bits for FB_CSCRn_SWS. */ /*! @brief Read current value of the FB_CSCRn_SWS field. */ #define BR_FB_CSCRn_SWS(x, n) (HW_FB_CSCRn(x, n).B.SWS) /*! @brief Format value for bitfield FB_CSCRn_SWS. */ #define BF_FB_CSCRn_SWS(v) ((uint32_t)((uint32_t)(v) << BP_FB_CSCRn_SWS) & BM_FB_CSCRn_SWS) /*! @brief Set the SWS field to a new value. */ #define BW_FB_CSCRn_SWS(x, n, v) (HW_FB_CSCRn_WR(x, n, (HW_FB_CSCRn_RD(x, n) & ~BM_FB_CSCRn_SWS) | BF_FB_CSCRn_SWS(v))) /*@}*/ /******************************************************************************* * HW_FB_CSPMCR - Chip Select port Multiplexing Control Register ******************************************************************************/ /*! * @brief HW_FB_CSPMCR - Chip Select port Multiplexing Control Register (RW) * * Reset value: 0x00000000U * * Controls the multiplexing of the FlexBus signals. A bus error occurs when you * do any of the following: Write to a reserved address Write to a reserved * field in this register, or Access this register using a size other than 32 bits. */ typedef union _hw_fb_cspmcr { uint32_t U; struct _hw_fb_cspmcr_bitfields { uint32_t RESERVED0 : 12; /*!< [11:0] */ uint32_t GROUP5 : 4; /*!< [15:12] FlexBus Signal Group 5 Multiplex * control */ uint32_t GROUP4 : 4; /*!< [19:16] FlexBus Signal Group 4 Multiplex * control */ uint32_t GROUP3 : 4; /*!< [23:20] FlexBus Signal Group 3 Multiplex * control */ uint32_t GROUP2 : 4; /*!< [27:24] FlexBus Signal Group 2 Multiplex * control */ uint32_t GROUP1 : 4; /*!< [31:28] FlexBus Signal Group 1 Multiplex * control */ } B; } hw_fb_cspmcr_t; /*! * @name Constants and macros for entire FB_CSPMCR register */ /*@{*/ #define HW_FB_CSPMCR_ADDR(x) ((x) + 0x60U) #define HW_FB_CSPMCR(x) (*(__IO hw_fb_cspmcr_t *) HW_FB_CSPMCR_ADDR(x)) #define HW_FB_CSPMCR_RD(x) (HW_FB_CSPMCR(x).U) #define HW_FB_CSPMCR_WR(x, v) (HW_FB_CSPMCR(x).U = (v)) #define HW_FB_CSPMCR_SET(x, v) (HW_FB_CSPMCR_WR(x, HW_FB_CSPMCR_RD(x) | (v))) #define HW_FB_CSPMCR_CLR(x, v) (HW_FB_CSPMCR_WR(x, HW_FB_CSPMCR_RD(x) & ~(v))) #define HW_FB_CSPMCR_TOG(x, v) (HW_FB_CSPMCR_WR(x, HW_FB_CSPMCR_RD(x) ^ (v))) /*@}*/ /* * Constants & macros for individual FB_CSPMCR bitfields */ /*! * @name Register FB_CSPMCR, field GROUP5[15:12] (RW) * * Controls the multiplexing of the FB_TA , FB_CS3 , and FB_BE_7_0 signals. When * GROUP5 is not 0000b, you must write 1b to the CSCR[AA] bit. Otherwise, the * bus hangs during a transfer. * * Values: * - 0000 - FB_TA * - 0001 - FB_CS3 . You must also write 1b to CSCR[AA]. * - 0010 - FB_BE_7_0 . You must also write 1b to CSCR[AA]. */ /*@{*/ #define BP_FB_CSPMCR_GROUP5 (12U) /*!< Bit position for FB_CSPMCR_GROUP5. */ #define BM_FB_CSPMCR_GROUP5 (0x0000F000U) /*!< Bit mask for FB_CSPMCR_GROUP5. */ #define BS_FB_CSPMCR_GROUP5 (4U) /*!< Bit field size in bits for FB_CSPMCR_GROUP5. */ /*! @brief Read current value of the FB_CSPMCR_GROUP5 field. */ #define BR_FB_CSPMCR_GROUP5(x) (HW_FB_CSPMCR(x).B.GROUP5) /*! @brief Format value for bitfield FB_CSPMCR_GROUP5. */ #define BF_FB_CSPMCR_GROUP5(v) ((uint32_t)((uint32_t)(v) << BP_FB_CSPMCR_GROUP5) & BM_FB_CSPMCR_GROUP5) /*! @brief Set the GROUP5 field to a new value. */ #define BW_FB_CSPMCR_GROUP5(x, v) (HW_FB_CSPMCR_WR(x, (HW_FB_CSPMCR_RD(x) & ~BM_FB_CSPMCR_GROUP5) | BF_FB_CSPMCR_GROUP5(v))) /*@}*/ /*! * @name Register FB_CSPMCR, field GROUP4[19:16] (RW) * * Controls the multiplexing of the FB_TBST , FB_CS2 , and FB_BE_15_8 signals. * * Values: * - 0000 - FB_TBST * - 0001 - FB_CS2 * - 0010 - FB_BE_15_8 */ /*@{*/ #define BP_FB_CSPMCR_GROUP4 (16U) /*!< Bit position for FB_CSPMCR_GROUP4. */ #define BM_FB_CSPMCR_GROUP4 (0x000F0000U) /*!< Bit mask for FB_CSPMCR_GROUP4. */ #define BS_FB_CSPMCR_GROUP4 (4U) /*!< Bit field size in bits for FB_CSPMCR_GROUP4. */ /*! @brief Read current value of the FB_CSPMCR_GROUP4 field. */ #define BR_FB_CSPMCR_GROUP4(x) (HW_FB_CSPMCR(x).B.GROUP4) /*! @brief Format value for bitfield FB_CSPMCR_GROUP4. */ #define BF_FB_CSPMCR_GROUP4(v) ((uint32_t)((uint32_t)(v) << BP_FB_CSPMCR_GROUP4) & BM_FB_CSPMCR_GROUP4) /*! @brief Set the GROUP4 field to a new value. */ #define BW_FB_CSPMCR_GROUP4(x, v) (HW_FB_CSPMCR_WR(x, (HW_FB_CSPMCR_RD(x) & ~BM_FB_CSPMCR_GROUP4) | BF_FB_CSPMCR_GROUP4(v))) /*@}*/ /*! * @name Register FB_CSPMCR, field GROUP3[23:20] (RW) * * Controls the multiplexing of the FB_CS5 , FB_TSIZ1, and FB_BE_23_16 signals. * * Values: * - 0000 - FB_CS5 * - 0001 - FB_TSIZ1 * - 0010 - FB_BE_23_16 */ /*@{*/ #define BP_FB_CSPMCR_GROUP3 (20U) /*!< Bit position for FB_CSPMCR_GROUP3. */ #define BM_FB_CSPMCR_GROUP3 (0x00F00000U) /*!< Bit mask for FB_CSPMCR_GROUP3. */ #define BS_FB_CSPMCR_GROUP3 (4U) /*!< Bit field size in bits for FB_CSPMCR_GROUP3. */ /*! @brief Read current value of the FB_CSPMCR_GROUP3 field. */ #define BR_FB_CSPMCR_GROUP3(x) (HW_FB_CSPMCR(x).B.GROUP3) /*! @brief Format value for bitfield FB_CSPMCR_GROUP3. */ #define BF_FB_CSPMCR_GROUP3(v) ((uint32_t)((uint32_t)(v) << BP_FB_CSPMCR_GROUP3) & BM_FB_CSPMCR_GROUP3) /*! @brief Set the GROUP3 field to a new value. */ #define BW_FB_CSPMCR_GROUP3(x, v) (HW_FB_CSPMCR_WR(x, (HW_FB_CSPMCR_RD(x) & ~BM_FB_CSPMCR_GROUP3) | BF_FB_CSPMCR_GROUP3(v))) /*@}*/ /*! * @name Register FB_CSPMCR, field GROUP2[27:24] (RW) * * Controls the multiplexing of the FB_CS4 , FB_TSIZ0, and FB_BE_31_24 signals. * * Values: * - 0000 - FB_CS4 * - 0001 - FB_TSIZ0 * - 0010 - FB_BE_31_24 */ /*@{*/ #define BP_FB_CSPMCR_GROUP2 (24U) /*!< Bit position for FB_CSPMCR_GROUP2. */ #define BM_FB_CSPMCR_GROUP2 (0x0F000000U) /*!< Bit mask for FB_CSPMCR_GROUP2. */ #define BS_FB_CSPMCR_GROUP2 (4U) /*!< Bit field size in bits for FB_CSPMCR_GROUP2. */ /*! @brief Read current value of the FB_CSPMCR_GROUP2 field. */ #define BR_FB_CSPMCR_GROUP2(x) (HW_FB_CSPMCR(x).B.GROUP2) /*! @brief Format value for bitfield FB_CSPMCR_GROUP2. */ #define BF_FB_CSPMCR_GROUP2(v) ((uint32_t)((uint32_t)(v) << BP_FB_CSPMCR_GROUP2) & BM_FB_CSPMCR_GROUP2) /*! @brief Set the GROUP2 field to a new value. */ #define BW_FB_CSPMCR_GROUP2(x, v) (HW_FB_CSPMCR_WR(x, (HW_FB_CSPMCR_RD(x) & ~BM_FB_CSPMCR_GROUP2) | BF_FB_CSPMCR_GROUP2(v))) /*@}*/ /*! * @name Register FB_CSPMCR, field GROUP1[31:28] (RW) * * Controls the multiplexing of the FB_ALE, FB_CS1 , and FB_TS signals. * * Values: * - 0000 - FB_ALE * - 0001 - FB_CS1 * - 0010 - FB_TS */ /*@{*/ #define BP_FB_CSPMCR_GROUP1 (28U) /*!< Bit position for FB_CSPMCR_GROUP1. */ #define BM_FB_CSPMCR_GROUP1 (0xF0000000U) /*!< Bit mask for FB_CSPMCR_GROUP1. */ #define BS_FB_CSPMCR_GROUP1 (4U) /*!< Bit field size in bits for FB_CSPMCR_GROUP1. */ /*! @brief Read current value of the FB_CSPMCR_GROUP1 field. */ #define BR_FB_CSPMCR_GROUP1(x) (HW_FB_CSPMCR(x).B.GROUP1) /*! @brief Format value for bitfield FB_CSPMCR_GROUP1. */ #define BF_FB_CSPMCR_GROUP1(v) ((uint32_t)((uint32_t)(v) << BP_FB_CSPMCR_GROUP1) & BM_FB_CSPMCR_GROUP1) /*! @brief Set the GROUP1 field to a new value. */ #define BW_FB_CSPMCR_GROUP1(x, v) (HW_FB_CSPMCR_WR(x, (HW_FB_CSPMCR_RD(x) & ~BM_FB_CSPMCR_GROUP1) | BF_FB_CSPMCR_GROUP1(v))) /*@}*/ /******************************************************************************* * hw_fb_t - module struct ******************************************************************************/ /*! * @brief All FB module registers. */ #pragma pack(1) typedef struct _hw_fb { struct { __IO hw_fb_csarn_t CSARn; /*!< [0x0] Chip Select Address Register */ __IO hw_fb_csmrn_t CSMRn; /*!< [0x4] Chip Select Mask Register */ __IO hw_fb_cscrn_t CSCRn; /*!< [0x8] Chip Select Control Register */ } CS[6]; uint8_t _reserved0[24]; __IO hw_fb_cspmcr_t CSPMCR; /*!< [0x60] Chip Select port Multiplexing Control Register */ } hw_fb_t; #pragma pack() /*! @brief Macro to access all FB registers. */ /*! @param x FB module instance base address. */ /*! @return Reference (not a pointer) to the registers struct. To get a pointer to the struct, * use the '&' operator, like &HW_FB(FB_BASE). */ #define HW_FB(x) (*(hw_fb_t *)(x)) #endif /* __HW_FB_REGISTERS_H__ */ /* EOF */ ================================================ FILE: Zelig/mbed/TARGET_K64F/TARGET_Freescale/TARGET_KPSDK_MCUS/TARGET_MCU_K64F/device/device/MK64F12/MK64F12_fmc.h ================================================ /* ** ################################################################### ** Compilers: Keil ARM C/C++ Compiler ** Freescale C/C++ for Embedded ARM ** GNU C Compiler ** IAR ANSI C/C++ Compiler for ARM ** ** Reference manual: K64P144M120SF5RM, Rev.2, January 2014 ** Version: rev. 2.5, 2014-02-10 ** Build: b140604 ** ** Abstract: ** Extension to the CMSIS register access layer header. ** ** Copyright (c) 2014 Freescale Semiconductor, Inc. ** All rights reserved. ** ** Redistribution and use in source and binary forms, with or without modification, ** are permitted provided that the following conditions are met: ** ** o Redistributions of source code must retain the above copyright notice, this list ** of conditions and the following disclaimer. ** ** o Redistributions in binary form must reproduce the above copyright notice, this ** list of conditions and the following disclaimer in the documentation and/or ** other materials provided with the distribution. ** ** o Neither the name of Freescale Semiconductor, Inc. nor the names of its ** contributors may be used to endorse or promote products derived from this ** software without specific prior written permission. ** ** THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ** ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED ** WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE ** DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT 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. ** ** http: www.freescale.com ** mail: support@freescale.com ** ** Revisions: ** - rev. 1.0 (2013-08-12) ** Initial version. ** - rev. 2.0 (2013-10-29) ** Register accessor macros added to the memory map. ** Symbols for Processor Expert memory map compatibility added to the memory map. ** Startup file for gcc has been updated according to CMSIS 3.2. ** System initialization updated. ** MCG - registers updated. ** PORTA, PORTB, PORTC, PORTE - registers for digital filter removed. ** - rev. 2.1 (2013-10-30) ** Definition of BITBAND macros updated to support peripherals with 32-bit acces disabled. ** - rev. 2.2 (2013-12-09) ** DMA - EARS register removed. ** AIPS0, AIPS1 - MPRA register updated. ** - rev. 2.3 (2014-01-24) ** Update according to reference manual rev. 2 ** ENET, MCG, MCM, SIM, USB - registers updated ** - rev. 2.4 (2014-02-10) ** The declaration of clock configurations has been moved to separate header file system_MK64F12.h ** Update of SystemInit() and SystemCoreClockUpdate() functions. ** - rev. 2.5 (2014-02-10) ** The declaration of clock configurations has been moved to separate header file system_MK64F12.h ** Update of SystemInit() and SystemCoreClockUpdate() functions. ** Module access macro module_BASES replaced by module_BASE_PTRS. ** ** ################################################################### */ /* * WARNING! DO NOT EDIT THIS FILE DIRECTLY! * * This file was generated automatically and any changes may be lost. */ #ifndef __HW_FMC_REGISTERS_H__ #define __HW_FMC_REGISTERS_H__ #include "MK64F12.h" #include "fsl_bitaccess.h" /* * MK64F12 FMC * * Flash Memory Controller * * Registers defined in this header file: * - HW_FMC_PFAPR - Flash Access Protection Register * - HW_FMC_PFB0CR - Flash Bank 0 Control Register * - HW_FMC_PFB1CR - Flash Bank 1 Control Register * - HW_FMC_TAGVDW0Sn - Cache Tag Storage * - HW_FMC_TAGVDW1Sn - Cache Tag Storage * - HW_FMC_TAGVDW2Sn - Cache Tag Storage * - HW_FMC_TAGVDW3Sn - Cache Tag Storage * - HW_FMC_DATAW0SnU - Cache Data Storage (upper word) * - HW_FMC_DATAW0SnL - Cache Data Storage (lower word) * - HW_FMC_DATAW1SnU - Cache Data Storage (upper word) * - HW_FMC_DATAW1SnL - Cache Data Storage (lower word) * - HW_FMC_DATAW2SnU - Cache Data Storage (upper word) * - HW_FMC_DATAW2SnL - Cache Data Storage (lower word) * - HW_FMC_DATAW3SnU - Cache Data Storage (upper word) * - HW_FMC_DATAW3SnL - Cache Data Storage (lower word) * * - hw_fmc_t - Struct containing all module registers. */ #define HW_FMC_INSTANCE_COUNT (1U) /*!< Number of instances of the FMC module. */ /******************************************************************************* * HW_FMC_PFAPR - Flash Access Protection Register ******************************************************************************/ /*! * @brief HW_FMC_PFAPR - Flash Access Protection Register (RW) * * Reset value: 0x00F8003FU */ typedef union _hw_fmc_pfapr { uint32_t U; struct _hw_fmc_pfapr_bitfields { uint32_t M0AP : 2; /*!< [1:0] Master 0 Access Protection */ uint32_t M1AP : 2; /*!< [3:2] Master 1 Access Protection */ uint32_t M2AP : 2; /*!< [5:4] Master 2 Access Protection */ uint32_t M3AP : 2; /*!< [7:6] Master 3 Access Protection */ uint32_t M4AP : 2; /*!< [9:8] Master 4 Access Protection */ uint32_t M5AP : 2; /*!< [11:10] Master 5 Access Protection */ uint32_t M6AP : 2; /*!< [13:12] Master 6 Access Protection */ uint32_t M7AP : 2; /*!< [15:14] Master 7 Access Protection */ uint32_t M0PFD : 1; /*!< [16] Master 0 Prefetch Disable */ uint32_t M1PFD : 1; /*!< [17] Master 1 Prefetch Disable */ uint32_t M2PFD : 1; /*!< [18] Master 2 Prefetch Disable */ uint32_t M3PFD : 1; /*!< [19] Master 3 Prefetch Disable */ uint32_t M4PFD : 1; /*!< [20] Master 4 Prefetch Disable */ uint32_t M5PFD : 1; /*!< [21] Master 5 Prefetch Disable */ uint32_t M6PFD : 1; /*!< [22] Master 6 Prefetch Disable */ uint32_t M7PFD : 1; /*!< [23] Master 7 Prefetch Disable */ uint32_t RESERVED0 : 8; /*!< [31:24] */ } B; } hw_fmc_pfapr_t; /*! * @name Constants and macros for entire FMC_PFAPR register */ /*@{*/ #define HW_FMC_PFAPR_ADDR(x) ((x) + 0x0U) #define HW_FMC_PFAPR(x) (*(__IO hw_fmc_pfapr_t *) HW_FMC_PFAPR_ADDR(x)) #define HW_FMC_PFAPR_RD(x) (HW_FMC_PFAPR(x).U) #define HW_FMC_PFAPR_WR(x, v) (HW_FMC_PFAPR(x).U = (v)) #define HW_FMC_PFAPR_SET(x, v) (HW_FMC_PFAPR_WR(x, HW_FMC_PFAPR_RD(x) | (v))) #define HW_FMC_PFAPR_CLR(x, v) (HW_FMC_PFAPR_WR(x, HW_FMC_PFAPR_RD(x) & ~(v))) #define HW_FMC_PFAPR_TOG(x, v) (HW_FMC_PFAPR_WR(x, HW_FMC_PFAPR_RD(x) ^ (v))) /*@}*/ /* * Constants & macros for individual FMC_PFAPR bitfields */ /*! * @name Register FMC_PFAPR, field M0AP[1:0] (RW) * * This field controls whether read and write access to the flash are allowed * based on the logical master number of the requesting crossbar switch master. * * Values: * - 00 - No access may be performed by this master * - 01 - Only read accesses may be performed by this master * - 10 - Only write accesses may be performed by this master * - 11 - Both read and write accesses may be performed by this master */ /*@{*/ #define BP_FMC_PFAPR_M0AP (0U) /*!< Bit position for FMC_PFAPR_M0AP. */ #define BM_FMC_PFAPR_M0AP (0x00000003U) /*!< Bit mask for FMC_PFAPR_M0AP. */ #define BS_FMC_PFAPR_M0AP (2U) /*!< Bit field size in bits for FMC_PFAPR_M0AP. */ /*! @brief Read current value of the FMC_PFAPR_M0AP field. */ #define BR_FMC_PFAPR_M0AP(x) (HW_FMC_PFAPR(x).B.M0AP) /*! @brief Format value for bitfield FMC_PFAPR_M0AP. */ #define BF_FMC_PFAPR_M0AP(v) ((uint32_t)((uint32_t)(v) << BP_FMC_PFAPR_M0AP) & BM_FMC_PFAPR_M0AP) /*! @brief Set the M0AP field to a new value. */ #define BW_FMC_PFAPR_M0AP(x, v) (HW_FMC_PFAPR_WR(x, (HW_FMC_PFAPR_RD(x) & ~BM_FMC_PFAPR_M0AP) | BF_FMC_PFAPR_M0AP(v))) /*@}*/ /*! * @name Register FMC_PFAPR, field M1AP[3:2] (RW) * * This field controls whether read and write access to the flash are allowed * based on the logical master number of the requesting crossbar switch master. * * Values: * - 00 - No access may be performed by this master * - 01 - Only read accesses may be performed by this master * - 10 - Only write accesses may be performed by this master * - 11 - Both read and write accesses may be performed by this master */ /*@{*/ #define BP_FMC_PFAPR_M1AP (2U) /*!< Bit position for FMC_PFAPR_M1AP. */ #define BM_FMC_PFAPR_M1AP (0x0000000CU) /*!< Bit mask for FMC_PFAPR_M1AP. */ #define BS_FMC_PFAPR_M1AP (2U) /*!< Bit field size in bits for FMC_PFAPR_M1AP. */ /*! @brief Read current value of the FMC_PFAPR_M1AP field. */ #define BR_FMC_PFAPR_M1AP(x) (HW_FMC_PFAPR(x).B.M1AP) /*! @brief Format value for bitfield FMC_PFAPR_M1AP. */ #define BF_FMC_PFAPR_M1AP(v) ((uint32_t)((uint32_t)(v) << BP_FMC_PFAPR_M1AP) & BM_FMC_PFAPR_M1AP) /*! @brief Set the M1AP field to a new value. */ #define BW_FMC_PFAPR_M1AP(x, v) (HW_FMC_PFAPR_WR(x, (HW_FMC_PFAPR_RD(x) & ~BM_FMC_PFAPR_M1AP) | BF_FMC_PFAPR_M1AP(v))) /*@}*/ /*! * @name Register FMC_PFAPR, field M2AP[5:4] (RW) * * This field controls whether read and write access to the flash are allowed * based on the logical master number of the requesting crossbar switch master. * * Values: * - 00 - No access may be performed by this master * - 01 - Only read accesses may be performed by this master * - 10 - Only write accesses may be performed by this master * - 11 - Both read and write accesses may be performed by this master */ /*@{*/ #define BP_FMC_PFAPR_M2AP (4U) /*!< Bit position for FMC_PFAPR_M2AP. */ #define BM_FMC_PFAPR_M2AP (0x00000030U) /*!< Bit mask for FMC_PFAPR_M2AP. */ #define BS_FMC_PFAPR_M2AP (2U) /*!< Bit field size in bits for FMC_PFAPR_M2AP. */ /*! @brief Read current value of the FMC_PFAPR_M2AP field. */ #define BR_FMC_PFAPR_M2AP(x) (HW_FMC_PFAPR(x).B.M2AP) /*! @brief Format value for bitfield FMC_PFAPR_M2AP. */ #define BF_FMC_PFAPR_M2AP(v) ((uint32_t)((uint32_t)(v) << BP_FMC_PFAPR_M2AP) & BM_FMC_PFAPR_M2AP) /*! @brief Set the M2AP field to a new value. */ #define BW_FMC_PFAPR_M2AP(x, v) (HW_FMC_PFAPR_WR(x, (HW_FMC_PFAPR_RD(x) & ~BM_FMC_PFAPR_M2AP) | BF_FMC_PFAPR_M2AP(v))) /*@}*/ /*! * @name Register FMC_PFAPR, field M3AP[7:6] (RW) * * This field controls whether read and write access to the flash are allowed * based on the logical master number of the requesting crossbar switch master. * * Values: * - 00 - No access may be performed by this master * - 01 - Only read accesses may be performed by this master * - 10 - Only write accesses may be performed by this master * - 11 - Both read and write accesses may be performed by this master */ /*@{*/ #define BP_FMC_PFAPR_M3AP (6U) /*!< Bit position for FMC_PFAPR_M3AP. */ #define BM_FMC_PFAPR_M3AP (0x000000C0U) /*!< Bit mask for FMC_PFAPR_M3AP. */ #define BS_FMC_PFAPR_M3AP (2U) /*!< Bit field size in bits for FMC_PFAPR_M3AP. */ /*! @brief Read current value of the FMC_PFAPR_M3AP field. */ #define BR_FMC_PFAPR_M3AP(x) (HW_FMC_PFAPR(x).B.M3AP) /*! @brief Format value for bitfield FMC_PFAPR_M3AP. */ #define BF_FMC_PFAPR_M3AP(v) ((uint32_t)((uint32_t)(v) << BP_FMC_PFAPR_M3AP) & BM_FMC_PFAPR_M3AP) /*! @brief Set the M3AP field to a new value. */ #define BW_FMC_PFAPR_M3AP(x, v) (HW_FMC_PFAPR_WR(x, (HW_FMC_PFAPR_RD(x) & ~BM_FMC_PFAPR_M3AP) | BF_FMC_PFAPR_M3AP(v))) /*@}*/ /*! * @name Register FMC_PFAPR, field M4AP[9:8] (RW) * * This field controls whether read and write access to the flash are allowed * based on the logical master number of the requesting crossbar switch master. * * Values: * - 00 - No access may be performed by this master * - 01 - Only read accesses may be performed by this master * - 10 - Only write accesses may be performed by this master * - 11 - Both read and write accesses may be performed by this master */ /*@{*/ #define BP_FMC_PFAPR_M4AP (8U) /*!< Bit position for FMC_PFAPR_M4AP. */ #define BM_FMC_PFAPR_M4AP (0x00000300U) /*!< Bit mask for FMC_PFAPR_M4AP. */ #define BS_FMC_PFAPR_M4AP (2U) /*!< Bit field size in bits for FMC_PFAPR_M4AP. */ /*! @brief Read current value of the FMC_PFAPR_M4AP field. */ #define BR_FMC_PFAPR_M4AP(x) (HW_FMC_PFAPR(x).B.M4AP) /*! @brief Format value for bitfield FMC_PFAPR_M4AP. */ #define BF_FMC_PFAPR_M4AP(v) ((uint32_t)((uint32_t)(v) << BP_FMC_PFAPR_M4AP) & BM_FMC_PFAPR_M4AP) /*! @brief Set the M4AP field to a new value. */ #define BW_FMC_PFAPR_M4AP(x, v) (HW_FMC_PFAPR_WR(x, (HW_FMC_PFAPR_RD(x) & ~BM_FMC_PFAPR_M4AP) | BF_FMC_PFAPR_M4AP(v))) /*@}*/ /*! * @name Register FMC_PFAPR, field M5AP[11:10] (RW) * * This field controls whether read and write access to the flash are allowed * based on the logical master number of the requesting crossbar switch master. * * Values: * - 00 - No access may be performed by this master * - 01 - Only read accesses may be performed by this master * - 10 - Only write accesses may be performed by this master * - 11 - Both read and write accesses may be performed by this master */ /*@{*/ #define BP_FMC_PFAPR_M5AP (10U) /*!< Bit position for FMC_PFAPR_M5AP. */ #define BM_FMC_PFAPR_M5AP (0x00000C00U) /*!< Bit mask for FMC_PFAPR_M5AP. */ #define BS_FMC_PFAPR_M5AP (2U) /*!< Bit field size in bits for FMC_PFAPR_M5AP. */ /*! @brief Read current value of the FMC_PFAPR_M5AP field. */ #define BR_FMC_PFAPR_M5AP(x) (HW_FMC_PFAPR(x).B.M5AP) /*! @brief Format value for bitfield FMC_PFAPR_M5AP. */ #define BF_FMC_PFAPR_M5AP(v) ((uint32_t)((uint32_t)(v) << BP_FMC_PFAPR_M5AP) & BM_FMC_PFAPR_M5AP) /*! @brief Set the M5AP field to a new value. */ #define BW_FMC_PFAPR_M5AP(x, v) (HW_FMC_PFAPR_WR(x, (HW_FMC_PFAPR_RD(x) & ~BM_FMC_PFAPR_M5AP) | BF_FMC_PFAPR_M5AP(v))) /*@}*/ /*! * @name Register FMC_PFAPR, field M6AP[13:12] (RW) * * This field controls whether read and write access to the flash are allowed * based on the logical master number of the requesting crossbar switch master. * * Values: * - 00 - No access may be performed by this master * - 01 - Only read accesses may be performed by this master * - 10 - Only write accesses may be performed by this master * - 11 - Both read and write accesses may be performed by this master */ /*@{*/ #define BP_FMC_PFAPR_M6AP (12U) /*!< Bit position for FMC_PFAPR_M6AP. */ #define BM_FMC_PFAPR_M6AP (0x00003000U) /*!< Bit mask for FMC_PFAPR_M6AP. */ #define BS_FMC_PFAPR_M6AP (2U) /*!< Bit field size in bits for FMC_PFAPR_M6AP. */ /*! @brief Read current value of the FMC_PFAPR_M6AP field. */ #define BR_FMC_PFAPR_M6AP(x) (HW_FMC_PFAPR(x).B.M6AP) /*! @brief Format value for bitfield FMC_PFAPR_M6AP. */ #define BF_FMC_PFAPR_M6AP(v) ((uint32_t)((uint32_t)(v) << BP_FMC_PFAPR_M6AP) & BM_FMC_PFAPR_M6AP) /*! @brief Set the M6AP field to a new value. */ #define BW_FMC_PFAPR_M6AP(x, v) (HW_FMC_PFAPR_WR(x, (HW_FMC_PFAPR_RD(x) & ~BM_FMC_PFAPR_M6AP) | BF_FMC_PFAPR_M6AP(v))) /*@}*/ /*! * @name Register FMC_PFAPR, field M7AP[15:14] (RW) * * This field controls whether read and write access to the flash are allowed * based on the logical master number of the requesting crossbar switch master. * * Values: * - 00 - No access may be performed by this master. * - 01 - Only read accesses may be performed by this master. * - 10 - Only write accesses may be performed by this master. * - 11 - Both read and write accesses may be performed by this master. */ /*@{*/ #define BP_FMC_PFAPR_M7AP (14U) /*!< Bit position for FMC_PFAPR_M7AP. */ #define BM_FMC_PFAPR_M7AP (0x0000C000U) /*!< Bit mask for FMC_PFAPR_M7AP. */ #define BS_FMC_PFAPR_M7AP (2U) /*!< Bit field size in bits for FMC_PFAPR_M7AP. */ /*! @brief Read current value of the FMC_PFAPR_M7AP field. */ #define BR_FMC_PFAPR_M7AP(x) (HW_FMC_PFAPR(x).B.M7AP) /*! @brief Format value for bitfield FMC_PFAPR_M7AP. */ #define BF_FMC_PFAPR_M7AP(v) ((uint32_t)((uint32_t)(v) << BP_FMC_PFAPR_M7AP) & BM_FMC_PFAPR_M7AP) /*! @brief Set the M7AP field to a new value. */ #define BW_FMC_PFAPR_M7AP(x, v) (HW_FMC_PFAPR_WR(x, (HW_FMC_PFAPR_RD(x) & ~BM_FMC_PFAPR_M7AP) | BF_FMC_PFAPR_M7AP(v))) /*@}*/ /*! * @name Register FMC_PFAPR, field M0PFD[16] (RW) * * These bits control whether prefetching is enabled based on the logical number * of the requesting crossbar switch master. This field is further qualified by * the PFBnCR[BxDPE,BxIPE] bits. * * Values: * - 0 - Prefetching for this master is enabled. * - 1 - Prefetching for this master is disabled. */ /*@{*/ #define BP_FMC_PFAPR_M0PFD (16U) /*!< Bit position for FMC_PFAPR_M0PFD. */ #define BM_FMC_PFAPR_M0PFD (0x00010000U) /*!< Bit mask for FMC_PFAPR_M0PFD. */ #define BS_FMC_PFAPR_M0PFD (1U) /*!< Bit field size in bits for FMC_PFAPR_M0PFD. */ /*! @brief Read current value of the FMC_PFAPR_M0PFD field. */ #define BR_FMC_PFAPR_M0PFD(x) (BITBAND_ACCESS32(HW_FMC_PFAPR_ADDR(x), BP_FMC_PFAPR_M0PFD)) /*! @brief Format value for bitfield FMC_PFAPR_M0PFD. */ #define BF_FMC_PFAPR_M0PFD(v) ((uint32_t)((uint32_t)(v) << BP_FMC_PFAPR_M0PFD) & BM_FMC_PFAPR_M0PFD) /*! @brief Set the M0PFD field to a new value. */ #define BW_FMC_PFAPR_M0PFD(x, v) (BITBAND_ACCESS32(HW_FMC_PFAPR_ADDR(x), BP_FMC_PFAPR_M0PFD) = (v)) /*@}*/ /*! * @name Register FMC_PFAPR, field M1PFD[17] (RW) * * These bits control whether prefetching is enabled based on the logical number * of the requesting crossbar switch master. This field is further qualified by * the PFBnCR[BxDPE,BxIPE] bits. * * Values: * - 0 - Prefetching for this master is enabled. * - 1 - Prefetching for this master is disabled. */ /*@{*/ #define BP_FMC_PFAPR_M1PFD (17U) /*!< Bit position for FMC_PFAPR_M1PFD. */ #define BM_FMC_PFAPR_M1PFD (0x00020000U) /*!< Bit mask for FMC_PFAPR_M1PFD. */ #define BS_FMC_PFAPR_M1PFD (1U) /*!< Bit field size in bits for FMC_PFAPR_M1PFD. */ /*! @brief Read current value of the FMC_PFAPR_M1PFD field. */ #define BR_FMC_PFAPR_M1PFD(x) (BITBAND_ACCESS32(HW_FMC_PFAPR_ADDR(x), BP_FMC_PFAPR_M1PFD)) /*! @brief Format value for bitfield FMC_PFAPR_M1PFD. */ #define BF_FMC_PFAPR_M1PFD(v) ((uint32_t)((uint32_t)(v) << BP_FMC_PFAPR_M1PFD) & BM_FMC_PFAPR_M1PFD) /*! @brief Set the M1PFD field to a new value. */ #define BW_FMC_PFAPR_M1PFD(x, v) (BITBAND_ACCESS32(HW_FMC_PFAPR_ADDR(x), BP_FMC_PFAPR_M1PFD) = (v)) /*@}*/ /*! * @name Register FMC_PFAPR, field M2PFD[18] (RW) * * These bits control whether prefetching is enabled based on the logical number * of the requesting crossbar switch master. This field is further qualified by * the PFBnCR[BxDPE,BxIPE] bits. * * Values: * - 0 - Prefetching for this master is enabled. * - 1 - Prefetching for this master is disabled. */ /*@{*/ #define BP_FMC_PFAPR_M2PFD (18U) /*!< Bit position for FMC_PFAPR_M2PFD. */ #define BM_FMC_PFAPR_M2PFD (0x00040000U) /*!< Bit mask for FMC_PFAPR_M2PFD. */ #define BS_FMC_PFAPR_M2PFD (1U) /*!< Bit field size in bits for FMC_PFAPR_M2PFD. */ /*! @brief Read current value of the FMC_PFAPR_M2PFD field. */ #define BR_FMC_PFAPR_M2PFD(x) (BITBAND_ACCESS32(HW_FMC_PFAPR_ADDR(x), BP_FMC_PFAPR_M2PFD)) /*! @brief Format value for bitfield FMC_PFAPR_M2PFD. */ #define BF_FMC_PFAPR_M2PFD(v) ((uint32_t)((uint32_t)(v) << BP_FMC_PFAPR_M2PFD) & BM_FMC_PFAPR_M2PFD) /*! @brief Set the M2PFD field to a new value. */ #define BW_FMC_PFAPR_M2PFD(x, v) (BITBAND_ACCESS32(HW_FMC_PFAPR_ADDR(x), BP_FMC_PFAPR_M2PFD) = (v)) /*@}*/ /*! * @name Register FMC_PFAPR, field M3PFD[19] (RW) * * These bits control whether prefetching is enabled based on the logical number * of the requesting crossbar switch master. This field is further qualified by * the PFBnCR[BxDPE,BxIPE] bits. * * Values: * - 0 - Prefetching for this master is enabled. * - 1 - Prefetching for this master is disabled. */ /*@{*/ #define BP_FMC_PFAPR_M3PFD (19U) /*!< Bit position for FMC_PFAPR_M3PFD. */ #define BM_FMC_PFAPR_M3PFD (0x00080000U) /*!< Bit mask for FMC_PFAPR_M3PFD. */ #define BS_FMC_PFAPR_M3PFD (1U) /*!< Bit field size in bits for FMC_PFAPR_M3PFD. */ /*! @brief Read current value of the FMC_PFAPR_M3PFD field. */ #define BR_FMC_PFAPR_M3PFD(x) (BITBAND_ACCESS32(HW_FMC_PFAPR_ADDR(x), BP_FMC_PFAPR_M3PFD)) /*! @brief Format value for bitfield FMC_PFAPR_M3PFD. */ #define BF_FMC_PFAPR_M3PFD(v) ((uint32_t)((uint32_t)(v) << BP_FMC_PFAPR_M3PFD) & BM_FMC_PFAPR_M3PFD) /*! @brief Set the M3PFD field to a new value. */ #define BW_FMC_PFAPR_M3PFD(x, v) (BITBAND_ACCESS32(HW_FMC_PFAPR_ADDR(x), BP_FMC_PFAPR_M3PFD) = (v)) /*@}*/ /*! * @name Register FMC_PFAPR, field M4PFD[20] (RW) * * These bits control whether prefetching is enabled based on the logical number * of the requesting crossbar switch master. This field is further qualified by * the PFBnCR[BxDPE,BxIPE] bits. * * Values: * - 0 - Prefetching for this master is enabled. * - 1 - Prefetching for this master is disabled. */ /*@{*/ #define BP_FMC_PFAPR_M4PFD (20U) /*!< Bit position for FMC_PFAPR_M4PFD. */ #define BM_FMC_PFAPR_M4PFD (0x00100000U) /*!< Bit mask for FMC_PFAPR_M4PFD. */ #define BS_FMC_PFAPR_M4PFD (1U) /*!< Bit field size in bits for FMC_PFAPR_M4PFD. */ /*! @brief Read current value of the FMC_PFAPR_M4PFD field. */ #define BR_FMC_PFAPR_M4PFD(x) (BITBAND_ACCESS32(HW_FMC_PFAPR_ADDR(x), BP_FMC_PFAPR_M4PFD)) /*! @brief Format value for bitfield FMC_PFAPR_M4PFD. */ #define BF_FMC_PFAPR_M4PFD(v) ((uint32_t)((uint32_t)(v) << BP_FMC_PFAPR_M4PFD) & BM_FMC_PFAPR_M4PFD) /*! @brief Set the M4PFD field to a new value. */ #define BW_FMC_PFAPR_M4PFD(x, v) (BITBAND_ACCESS32(HW_FMC_PFAPR_ADDR(x), BP_FMC_PFAPR_M4PFD) = (v)) /*@}*/ /*! * @name Register FMC_PFAPR, field M5PFD[21] (RW) * * These bits control whether prefetching is enabled based on the logical number * of the requesting crossbar switch master. This field is further qualified by * the PFBnCR[BxDPE,BxIPE] bits. * * Values: * - 0 - Prefetching for this master is enabled. * - 1 - Prefetching for this master is disabled. */ /*@{*/ #define BP_FMC_PFAPR_M5PFD (21U) /*!< Bit position for FMC_PFAPR_M5PFD. */ #define BM_FMC_PFAPR_M5PFD (0x00200000U) /*!< Bit mask for FMC_PFAPR_M5PFD. */ #define BS_FMC_PFAPR_M5PFD (1U) /*!< Bit field size in bits for FMC_PFAPR_M5PFD. */ /*! @brief Read current value of the FMC_PFAPR_M5PFD field. */ #define BR_FMC_PFAPR_M5PFD(x) (BITBAND_ACCESS32(HW_FMC_PFAPR_ADDR(x), BP_FMC_PFAPR_M5PFD)) /*! @brief Format value for bitfield FMC_PFAPR_M5PFD. */ #define BF_FMC_PFAPR_M5PFD(v) ((uint32_t)((uint32_t)(v) << BP_FMC_PFAPR_M5PFD) & BM_FMC_PFAPR_M5PFD) /*! @brief Set the M5PFD field to a new value. */ #define BW_FMC_PFAPR_M5PFD(x, v) (BITBAND_ACCESS32(HW_FMC_PFAPR_ADDR(x), BP_FMC_PFAPR_M5PFD) = (v)) /*@}*/ /*! * @name Register FMC_PFAPR, field M6PFD[22] (RW) * * These bits control whether prefetching is enabled based on the logical number * of the requesting crossbar switch master. This field is further qualified by * the PFBnCR[BxDPE,BxIPE] bits. * * Values: * - 0 - Prefetching for this master is enabled. * - 1 - Prefetching for this master is disabled. */ /*@{*/ #define BP_FMC_PFAPR_M6PFD (22U) /*!< Bit position for FMC_PFAPR_M6PFD. */ #define BM_FMC_PFAPR_M6PFD (0x00400000U) /*!< Bit mask for FMC_PFAPR_M6PFD. */ #define BS_FMC_PFAPR_M6PFD (1U) /*!< Bit field size in bits for FMC_PFAPR_M6PFD. */ /*! @brief Read current value of the FMC_PFAPR_M6PFD field. */ #define BR_FMC_PFAPR_M6PFD(x) (BITBAND_ACCESS32(HW_FMC_PFAPR_ADDR(x), BP_FMC_PFAPR_M6PFD)) /*! @brief Format value for bitfield FMC_PFAPR_M6PFD. */ #define BF_FMC_PFAPR_M6PFD(v) ((uint32_t)((uint32_t)(v) << BP_FMC_PFAPR_M6PFD) & BM_FMC_PFAPR_M6PFD) /*! @brief Set the M6PFD field to a new value. */ #define BW_FMC_PFAPR_M6PFD(x, v) (BITBAND_ACCESS32(HW_FMC_PFAPR_ADDR(x), BP_FMC_PFAPR_M6PFD) = (v)) /*@}*/ /*! * @name Register FMC_PFAPR, field M7PFD[23] (RW) * * These bits control whether prefetching is enabled based on the logical number * of the requesting crossbar switch master. This field is further qualified by * the PFBnCR[BxDPE,BxIPE] bits. * * Values: * - 0 - Prefetching for this master is enabled. * - 1 - Prefetching for this master is disabled. */ /*@{*/ #define BP_FMC_PFAPR_M7PFD (23U) /*!< Bit position for FMC_PFAPR_M7PFD. */ #define BM_FMC_PFAPR_M7PFD (0x00800000U) /*!< Bit mask for FMC_PFAPR_M7PFD. */ #define BS_FMC_PFAPR_M7PFD (1U) /*!< Bit field size in bits for FMC_PFAPR_M7PFD. */ /*! @brief Read current value of the FMC_PFAPR_M7PFD field. */ #define BR_FMC_PFAPR_M7PFD(x) (BITBAND_ACCESS32(HW_FMC_PFAPR_ADDR(x), BP_FMC_PFAPR_M7PFD)) /*! @brief Format value for bitfield FMC_PFAPR_M7PFD. */ #define BF_FMC_PFAPR_M7PFD(v) ((uint32_t)((uint32_t)(v) << BP_FMC_PFAPR_M7PFD) & BM_FMC_PFAPR_M7PFD) /*! @brief Set the M7PFD field to a new value. */ #define BW_FMC_PFAPR_M7PFD(x, v) (BITBAND_ACCESS32(HW_FMC_PFAPR_ADDR(x), BP_FMC_PFAPR_M7PFD) = (v)) /*@}*/ /******************************************************************************* * HW_FMC_PFB0CR - Flash Bank 0 Control Register ******************************************************************************/ /*! * @brief HW_FMC_PFB0CR - Flash Bank 0 Control Register (RW) * * Reset value: 0x3004001FU */ typedef union _hw_fmc_pfb0cr { uint32_t U; struct _hw_fmc_pfb0cr_bitfields { uint32_t B0SEBE : 1; /*!< [0] Bank 0 Single Entry Buffer Enable */ uint32_t B0IPE : 1; /*!< [1] Bank 0 Instruction Prefetch Enable */ uint32_t B0DPE : 1; /*!< [2] Bank 0 Data Prefetch Enable */ uint32_t B0ICE : 1; /*!< [3] Bank 0 Instruction Cache Enable */ uint32_t B0DCE : 1; /*!< [4] Bank 0 Data Cache Enable */ uint32_t CRC : 3; /*!< [7:5] Cache Replacement Control */ uint32_t RESERVED0 : 9; /*!< [16:8] */ uint32_t B0MW : 2; /*!< [18:17] Bank 0 Memory Width */ uint32_t S_B_INV : 1; /*!< [19] Invalidate Prefetch Speculation * Buffer */ uint32_t CINV_WAY : 4; /*!< [23:20] Cache Invalidate Way x */ uint32_t CLCK_WAY : 4; /*!< [27:24] Cache Lock Way x */ uint32_t B0RWSC : 4; /*!< [31:28] Bank 0 Read Wait State Control */ } B; } hw_fmc_pfb0cr_t; /*! * @name Constants and macros for entire FMC_PFB0CR register */ /*@{*/ #define HW_FMC_PFB0CR_ADDR(x) ((x) + 0x4U) #define HW_FMC_PFB0CR(x) (*(__IO hw_fmc_pfb0cr_t *) HW_FMC_PFB0CR_ADDR(x)) #define HW_FMC_PFB0CR_RD(x) (HW_FMC_PFB0CR(x).U) #define HW_FMC_PFB0CR_WR(x, v) (HW_FMC_PFB0CR(x).U = (v)) #define HW_FMC_PFB0CR_SET(x, v) (HW_FMC_PFB0CR_WR(x, HW_FMC_PFB0CR_RD(x) | (v))) #define HW_FMC_PFB0CR_CLR(x, v) (HW_FMC_PFB0CR_WR(x, HW_FMC_PFB0CR_RD(x) & ~(v))) #define HW_FMC_PFB0CR_TOG(x, v) (HW_FMC_PFB0CR_WR(x, HW_FMC_PFB0CR_RD(x) ^ (v))) /*@}*/ /* * Constants & macros for individual FMC_PFB0CR bitfields */ /*! * @name Register FMC_PFB0CR, field B0SEBE[0] (RW) * * This bit controls whether the single entry page buffer is enabled in response * to flash read accesses. Its operation is independent from bank 1's cache. A * high-to-low transition of this enable forces the page buffer to be invalidated. * * Values: * - 0 - Single entry buffer is disabled. * - 1 - Single entry buffer is enabled. */ /*@{*/ #define BP_FMC_PFB0CR_B0SEBE (0U) /*!< Bit position for FMC_PFB0CR_B0SEBE. */ #define BM_FMC_PFB0CR_B0SEBE (0x00000001U) /*!< Bit mask for FMC_PFB0CR_B0SEBE. */ #define BS_FMC_PFB0CR_B0SEBE (1U) /*!< Bit field size in bits for FMC_PFB0CR_B0SEBE. */ /*! @brief Read current value of the FMC_PFB0CR_B0SEBE field. */ #define BR_FMC_PFB0CR_B0SEBE(x) (BITBAND_ACCESS32(HW_FMC_PFB0CR_ADDR(x), BP_FMC_PFB0CR_B0SEBE)) /*! @brief Format value for bitfield FMC_PFB0CR_B0SEBE. */ #define BF_FMC_PFB0CR_B0SEBE(v) ((uint32_t)((uint32_t)(v) << BP_FMC_PFB0CR_B0SEBE) & BM_FMC_PFB0CR_B0SEBE) /*! @brief Set the B0SEBE field to a new value. */ #define BW_FMC_PFB0CR_B0SEBE(x, v) (BITBAND_ACCESS32(HW_FMC_PFB0CR_ADDR(x), BP_FMC_PFB0CR_B0SEBE) = (v)) /*@}*/ /*! * @name Register FMC_PFB0CR, field B0IPE[1] (RW) * * This bit controls whether prefetches (or speculative accesses) are initiated * in response to instruction fetches. * * Values: * - 0 - Do not prefetch in response to instruction fetches. * - 1 - Enable prefetches in response to instruction fetches. */ /*@{*/ #define BP_FMC_PFB0CR_B0IPE (1U) /*!< Bit position for FMC_PFB0CR_B0IPE. */ #define BM_FMC_PFB0CR_B0IPE (0x00000002U) /*!< Bit mask for FMC_PFB0CR_B0IPE. */ #define BS_FMC_PFB0CR_B0IPE (1U) /*!< Bit field size in bits for FMC_PFB0CR_B0IPE. */ /*! @brief Read current value of the FMC_PFB0CR_B0IPE field. */ #define BR_FMC_PFB0CR_B0IPE(x) (BITBAND_ACCESS32(HW_FMC_PFB0CR_ADDR(x), BP_FMC_PFB0CR_B0IPE)) /*! @brief Format value for bitfield FMC_PFB0CR_B0IPE. */ #define BF_FMC_PFB0CR_B0IPE(v) ((uint32_t)((uint32_t)(v) << BP_FMC_PFB0CR_B0IPE) & BM_FMC_PFB0CR_B0IPE) /*! @brief Set the B0IPE field to a new value. */ #define BW_FMC_PFB0CR_B0IPE(x, v) (BITBAND_ACCESS32(HW_FMC_PFB0CR_ADDR(x), BP_FMC_PFB0CR_B0IPE) = (v)) /*@}*/ /*! * @name Register FMC_PFB0CR, field B0DPE[2] (RW) * * This bit controls whether prefetches (or speculative accesses) are initiated * in response to data references. * * Values: * - 0 - Do not prefetch in response to data references. * - 1 - Enable prefetches in response to data references. */ /*@{*/ #define BP_FMC_PFB0CR_B0DPE (2U) /*!< Bit position for FMC_PFB0CR_B0DPE. */ #define BM_FMC_PFB0CR_B0DPE (0x00000004U) /*!< Bit mask for FMC_PFB0CR_B0DPE. */ #define BS_FMC_PFB0CR_B0DPE (1U) /*!< Bit field size in bits for FMC_PFB0CR_B0DPE. */ /*! @brief Read current value of the FMC_PFB0CR_B0DPE field. */ #define BR_FMC_PFB0CR_B0DPE(x) (BITBAND_ACCESS32(HW_FMC_PFB0CR_ADDR(x), BP_FMC_PFB0CR_B0DPE)) /*! @brief Format value for bitfield FMC_PFB0CR_B0DPE. */ #define BF_FMC_PFB0CR_B0DPE(v) ((uint32_t)((uint32_t)(v) << BP_FMC_PFB0CR_B0DPE) & BM_FMC_PFB0CR_B0DPE) /*! @brief Set the B0DPE field to a new value. */ #define BW_FMC_PFB0CR_B0DPE(x, v) (BITBAND_ACCESS32(HW_FMC_PFB0CR_ADDR(x), BP_FMC_PFB0CR_B0DPE) = (v)) /*@}*/ /*! * @name Register FMC_PFB0CR, field B0ICE[3] (RW) * * This bit controls whether instruction fetches are loaded into the cache. * * Values: * - 0 - Do not cache instruction fetches. * - 1 - Cache instruction fetches. */ /*@{*/ #define BP_FMC_PFB0CR_B0ICE (3U) /*!< Bit position for FMC_PFB0CR_B0ICE. */ #define BM_FMC_PFB0CR_B0ICE (0x00000008U) /*!< Bit mask for FMC_PFB0CR_B0ICE. */ #define BS_FMC_PFB0CR_B0ICE (1U) /*!< Bit field size in bits for FMC_PFB0CR_B0ICE. */ /*! @brief Read current value of the FMC_PFB0CR_B0ICE field. */ #define BR_FMC_PFB0CR_B0ICE(x) (BITBAND_ACCESS32(HW_FMC_PFB0CR_ADDR(x), BP_FMC_PFB0CR_B0ICE)) /*! @brief Format value for bitfield FMC_PFB0CR_B0ICE. */ #define BF_FMC_PFB0CR_B0ICE(v) ((uint32_t)((uint32_t)(v) << BP_FMC_PFB0CR_B0ICE) & BM_FMC_PFB0CR_B0ICE) /*! @brief Set the B0ICE field to a new value. */ #define BW_FMC_PFB0CR_B0ICE(x, v) (BITBAND_ACCESS32(HW_FMC_PFB0CR_ADDR(x), BP_FMC_PFB0CR_B0ICE) = (v)) /*@}*/ /*! * @name Register FMC_PFB0CR, field B0DCE[4] (RW) * * This bit controls whether data references are loaded into the cache. * * Values: * - 0 - Do not cache data references. * - 1 - Cache data references. */ /*@{*/ #define BP_FMC_PFB0CR_B0DCE (4U) /*!< Bit position for FMC_PFB0CR_B0DCE. */ #define BM_FMC_PFB0CR_B0DCE (0x00000010U) /*!< Bit mask for FMC_PFB0CR_B0DCE. */ #define BS_FMC_PFB0CR_B0DCE (1U) /*!< Bit field size in bits for FMC_PFB0CR_B0DCE. */ /*! @brief Read current value of the FMC_PFB0CR_B0DCE field. */ #define BR_FMC_PFB0CR_B0DCE(x) (BITBAND_ACCESS32(HW_FMC_PFB0CR_ADDR(x), BP_FMC_PFB0CR_B0DCE)) /*! @brief Format value for bitfield FMC_PFB0CR_B0DCE. */ #define BF_FMC_PFB0CR_B0DCE(v) ((uint32_t)((uint32_t)(v) << BP_FMC_PFB0CR_B0DCE) & BM_FMC_PFB0CR_B0DCE) /*! @brief Set the B0DCE field to a new value. */ #define BW_FMC_PFB0CR_B0DCE(x, v) (BITBAND_ACCESS32(HW_FMC_PFB0CR_ADDR(x), BP_FMC_PFB0CR_B0DCE) = (v)) /*@}*/ /*! * @name Register FMC_PFB0CR, field CRC[7:5] (RW) * * This 3-bit field defines the replacement algorithm for accesses that are * cached. * * Values: * - 000 - LRU replacement algorithm per set across all four ways * - 001 - Reserved * - 010 - Independent LRU with ways [0-1] for ifetches, [2-3] for data * - 011 - Independent LRU with ways [0-2] for ifetches, [3] for data * - 1xx - Reserved */ /*@{*/ #define BP_FMC_PFB0CR_CRC (5U) /*!< Bit position for FMC_PFB0CR_CRC. */ #define BM_FMC_PFB0CR_CRC (0x000000E0U) /*!< Bit mask for FMC_PFB0CR_CRC. */ #define BS_FMC_PFB0CR_CRC (3U) /*!< Bit field size in bits for FMC_PFB0CR_CRC. */ /*! @brief Read current value of the FMC_PFB0CR_CRC field. */ #define BR_FMC_PFB0CR_CRC(x) (HW_FMC_PFB0CR(x).B.CRC) /*! @brief Format value for bitfield FMC_PFB0CR_CRC. */ #define BF_FMC_PFB0CR_CRC(v) ((uint32_t)((uint32_t)(v) << BP_FMC_PFB0CR_CRC) & BM_FMC_PFB0CR_CRC) /*! @brief Set the CRC field to a new value. */ #define BW_FMC_PFB0CR_CRC(x, v) (HW_FMC_PFB0CR_WR(x, (HW_FMC_PFB0CR_RD(x) & ~BM_FMC_PFB0CR_CRC) | BF_FMC_PFB0CR_CRC(v))) /*@}*/ /*! * @name Register FMC_PFB0CR, field B0MW[18:17] (RO) * * This read-only field defines the width of the bank 0 memory. * * Values: * - 00 - 32 bits * - 01 - 64 bits * - 10 - 128 bits * - 11 - Reserved */ /*@{*/ #define BP_FMC_PFB0CR_B0MW (17U) /*!< Bit position for FMC_PFB0CR_B0MW. */ #define BM_FMC_PFB0CR_B0MW (0x00060000U) /*!< Bit mask for FMC_PFB0CR_B0MW. */ #define BS_FMC_PFB0CR_B0MW (2U) /*!< Bit field size in bits for FMC_PFB0CR_B0MW. */ /*! @brief Read current value of the FMC_PFB0CR_B0MW field. */ #define BR_FMC_PFB0CR_B0MW(x) (HW_FMC_PFB0CR(x).B.B0MW) /*@}*/ /*! * @name Register FMC_PFB0CR, field S_B_INV[19] (WORZ) * * This bit determines if the FMC's prefetch speculation buffer and the single * entry page buffer are to be invalidated (cleared). When this bit is written, * the speculation buffer and single entry buffer are immediately cleared. This bit * always reads as zero. * * Values: * - 0 - Speculation buffer and single entry buffer are not affected. * - 1 - Invalidate (clear) speculation buffer and single entry buffer. */ /*@{*/ #define BP_FMC_PFB0CR_S_B_INV (19U) /*!< Bit position for FMC_PFB0CR_S_B_INV. */ #define BM_FMC_PFB0CR_S_B_INV (0x00080000U) /*!< Bit mask for FMC_PFB0CR_S_B_INV. */ #define BS_FMC_PFB0CR_S_B_INV (1U) /*!< Bit field size in bits for FMC_PFB0CR_S_B_INV. */ /*! @brief Format value for bitfield FMC_PFB0CR_S_B_INV. */ #define BF_FMC_PFB0CR_S_B_INV(v) ((uint32_t)((uint32_t)(v) << BP_FMC_PFB0CR_S_B_INV) & BM_FMC_PFB0CR_S_B_INV) /*! @brief Set the S_B_INV field to a new value. */ #define BW_FMC_PFB0CR_S_B_INV(x, v) (BITBAND_ACCESS32(HW_FMC_PFB0CR_ADDR(x), BP_FMC_PFB0CR_S_B_INV) = (v)) /*@}*/ /*! * @name Register FMC_PFB0CR, field CINV_WAY[23:20] (WORZ) * * These bits determine if the given cache way is to be invalidated (cleared). * When a bit within this field is written, the corresponding cache way is * immediately invalidated: the way's tag, data, and valid contents are cleared. This * field always reads as zero. Cache invalidation takes precedence over locking. * The cache is invalidated by system reset. System software is required to * maintain memory coherency when any segment of the flash memory is programmed or * erased. Accordingly, cache invalidations must occur after a programming or erase * event is completed and before the new memory image is accessed. The bit setting * definitions are for each bit in the field. * * Values: * - 0 - No cache way invalidation for the corresponding cache * - 1 - Invalidate cache way for the corresponding cache: clear the tag, data, * and vld bits of ways selected */ /*@{*/ #define BP_FMC_PFB0CR_CINV_WAY (20U) /*!< Bit position for FMC_PFB0CR_CINV_WAY. */ #define BM_FMC_PFB0CR_CINV_WAY (0x00F00000U) /*!< Bit mask for FMC_PFB0CR_CINV_WAY. */ #define BS_FMC_PFB0CR_CINV_WAY (4U) /*!< Bit field size in bits for FMC_PFB0CR_CINV_WAY. */ /*! @brief Format value for bitfield FMC_PFB0CR_CINV_WAY. */ #define BF_FMC_PFB0CR_CINV_WAY(v) ((uint32_t)((uint32_t)(v) << BP_FMC_PFB0CR_CINV_WAY) & BM_FMC_PFB0CR_CINV_WAY) /*! @brief Set the CINV_WAY field to a new value. */ #define BW_FMC_PFB0CR_CINV_WAY(x, v) (HW_FMC_PFB0CR_WR(x, (HW_FMC_PFB0CR_RD(x) & ~BM_FMC_PFB0CR_CINV_WAY) | BF_FMC_PFB0CR_CINV_WAY(v))) /*@}*/ /*! * @name Register FMC_PFB0CR, field CLCK_WAY[27:24] (RW) * * These bits determine if the given cache way is locked such that its contents * will not be displaced by future misses. The bit setting definitions are for * each bit in the field. * * Values: * - 0 - Cache way is unlocked and may be displaced * - 1 - Cache way is locked and its contents are not displaced */ /*@{*/ #define BP_FMC_PFB0CR_CLCK_WAY (24U) /*!< Bit position for FMC_PFB0CR_CLCK_WAY. */ #define BM_FMC_PFB0CR_CLCK_WAY (0x0F000000U) /*!< Bit mask for FMC_PFB0CR_CLCK_WAY. */ #define BS_FMC_PFB0CR_CLCK_WAY (4U) /*!< Bit field size in bits for FMC_PFB0CR_CLCK_WAY. */ /*! @brief Read current value of the FMC_PFB0CR_CLCK_WAY field. */ #define BR_FMC_PFB0CR_CLCK_WAY(x) (HW_FMC_PFB0CR(x).B.CLCK_WAY) /*! @brief Format value for bitfield FMC_PFB0CR_CLCK_WAY. */ #define BF_FMC_PFB0CR_CLCK_WAY(v) ((uint32_t)((uint32_t)(v) << BP_FMC_PFB0CR_CLCK_WAY) & BM_FMC_PFB0CR_CLCK_WAY) /*! @brief Set the CLCK_WAY field to a new value. */ #define BW_FMC_PFB0CR_CLCK_WAY(x, v) (HW_FMC_PFB0CR_WR(x, (HW_FMC_PFB0CR_RD(x) & ~BM_FMC_PFB0CR_CLCK_WAY) | BF_FMC_PFB0CR_CLCK_WAY(v))) /*@}*/ /*! * @name Register FMC_PFB0CR, field B0RWSC[31:28] (RO) * * This read-only field defines the number of wait states required to access the * bank 0 flash memory. The relationship between the read access time of the * flash array (expressed in system clock cycles) and RWSC is defined as: Access * time of flash array [system clocks] = RWSC + 1 The FMC automatically calculates * this value based on the ratio of the system clock speed to the flash clock * speed. For example, when this ratio is 4:1, the field's value is 3h. */ /*@{*/ #define BP_FMC_PFB0CR_B0RWSC (28U) /*!< Bit position for FMC_PFB0CR_B0RWSC. */ #define BM_FMC_PFB0CR_B0RWSC (0xF0000000U) /*!< Bit mask for FMC_PFB0CR_B0RWSC. */ #define BS_FMC_PFB0CR_B0RWSC (4U) /*!< Bit field size in bits for FMC_PFB0CR_B0RWSC. */ /*! @brief Read current value of the FMC_PFB0CR_B0RWSC field. */ #define BR_FMC_PFB0CR_B0RWSC(x) (HW_FMC_PFB0CR(x).B.B0RWSC) /*@}*/ /******************************************************************************* * HW_FMC_PFB1CR - Flash Bank 1 Control Register ******************************************************************************/ /*! * @brief HW_FMC_PFB1CR - Flash Bank 1 Control Register (RW) * * Reset value: 0x3004001FU * * This register has a format similar to that for PFB0CR, except it controls the * operation of flash bank 1, and the "global" cache control fields are empty. */ typedef union _hw_fmc_pfb1cr { uint32_t U; struct _hw_fmc_pfb1cr_bitfields { uint32_t B1SEBE : 1; /*!< [0] Bank 1 Single Entry Buffer Enable */ uint32_t B1IPE : 1; /*!< [1] Bank 1 Instruction Prefetch Enable */ uint32_t B1DPE : 1; /*!< [2] Bank 1 Data Prefetch Enable */ uint32_t B1ICE : 1; /*!< [3] Bank 1 Instruction Cache Enable */ uint32_t B1DCE : 1; /*!< [4] Bank 1 Data Cache Enable */ uint32_t RESERVED0 : 12; /*!< [16:5] */ uint32_t B1MW : 2; /*!< [18:17] Bank 1 Memory Width */ uint32_t RESERVED1 : 9; /*!< [27:19] */ uint32_t B1RWSC : 4; /*!< [31:28] Bank 1 Read Wait State Control */ } B; } hw_fmc_pfb1cr_t; /*! * @name Constants and macros for entire FMC_PFB1CR register */ /*@{*/ #define HW_FMC_PFB1CR_ADDR(x) ((x) + 0x8U) #define HW_FMC_PFB1CR(x) (*(__IO hw_fmc_pfb1cr_t *) HW_FMC_PFB1CR_ADDR(x)) #define HW_FMC_PFB1CR_RD(x) (HW_FMC_PFB1CR(x).U) #define HW_FMC_PFB1CR_WR(x, v) (HW_FMC_PFB1CR(x).U = (v)) #define HW_FMC_PFB1CR_SET(x, v) (HW_FMC_PFB1CR_WR(x, HW_FMC_PFB1CR_RD(x) | (v))) #define HW_FMC_PFB1CR_CLR(x, v) (HW_FMC_PFB1CR_WR(x, HW_FMC_PFB1CR_RD(x) & ~(v))) #define HW_FMC_PFB1CR_TOG(x, v) (HW_FMC_PFB1CR_WR(x, HW_FMC_PFB1CR_RD(x) ^ (v))) /*@}*/ /* * Constants & macros for individual FMC_PFB1CR bitfields */ /*! * @name Register FMC_PFB1CR, field B1SEBE[0] (RW) * * This bit controls whether the single entry buffer is enabled in response to * flash read accesses. Its operation is independent from bank 0's cache. A * high-to-low transition of this enable forces the page buffer to be invalidated. * * Values: * - 0 - Single entry buffer is disabled. * - 1 - Single entry buffer is enabled. */ /*@{*/ #define BP_FMC_PFB1CR_B1SEBE (0U) /*!< Bit position for FMC_PFB1CR_B1SEBE. */ #define BM_FMC_PFB1CR_B1SEBE (0x00000001U) /*!< Bit mask for FMC_PFB1CR_B1SEBE. */ #define BS_FMC_PFB1CR_B1SEBE (1U) /*!< Bit field size in bits for FMC_PFB1CR_B1SEBE. */ /*! @brief Read current value of the FMC_PFB1CR_B1SEBE field. */ #define BR_FMC_PFB1CR_B1SEBE(x) (BITBAND_ACCESS32(HW_FMC_PFB1CR_ADDR(x), BP_FMC_PFB1CR_B1SEBE)) /*! @brief Format value for bitfield FMC_PFB1CR_B1SEBE. */ #define BF_FMC_PFB1CR_B1SEBE(v) ((uint32_t)((uint32_t)(v) << BP_FMC_PFB1CR_B1SEBE) & BM_FMC_PFB1CR_B1SEBE) /*! @brief Set the B1SEBE field to a new value. */ #define BW_FMC_PFB1CR_B1SEBE(x, v) (BITBAND_ACCESS32(HW_FMC_PFB1CR_ADDR(x), BP_FMC_PFB1CR_B1SEBE) = (v)) /*@}*/ /*! * @name Register FMC_PFB1CR, field B1IPE[1] (RW) * * This bit controls whether prefetches (or speculative accesses) are initiated * in response to instruction fetches. * * Values: * - 0 - Do not prefetch in response to instruction fetches. * - 1 - Enable prefetches in response to instruction fetches. */ /*@{*/ #define BP_FMC_PFB1CR_B1IPE (1U) /*!< Bit position for FMC_PFB1CR_B1IPE. */ #define BM_FMC_PFB1CR_B1IPE (0x00000002U) /*!< Bit mask for FMC_PFB1CR_B1IPE. */ #define BS_FMC_PFB1CR_B1IPE (1U) /*!< Bit field size in bits for FMC_PFB1CR_B1IPE. */ /*! @brief Read current value of the FMC_PFB1CR_B1IPE field. */ #define BR_FMC_PFB1CR_B1IPE(x) (BITBAND_ACCESS32(HW_FMC_PFB1CR_ADDR(x), BP_FMC_PFB1CR_B1IPE)) /*! @brief Format value for bitfield FMC_PFB1CR_B1IPE. */ #define BF_FMC_PFB1CR_B1IPE(v) ((uint32_t)((uint32_t)(v) << BP_FMC_PFB1CR_B1IPE) & BM_FMC_PFB1CR_B1IPE) /*! @brief Set the B1IPE field to a new value. */ #define BW_FMC_PFB1CR_B1IPE(x, v) (BITBAND_ACCESS32(HW_FMC_PFB1CR_ADDR(x), BP_FMC_PFB1CR_B1IPE) = (v)) /*@}*/ /*! * @name Register FMC_PFB1CR, field B1DPE[2] (RW) * * This bit controls whether prefetches (or speculative accesses) are initiated * in response to data references. * * Values: * - 0 - Do not prefetch in response to data references. * - 1 - Enable prefetches in response to data references. */ /*@{*/ #define BP_FMC_PFB1CR_B1DPE (2U) /*!< Bit position for FMC_PFB1CR_B1DPE. */ #define BM_FMC_PFB1CR_B1DPE (0x00000004U) /*!< Bit mask for FMC_PFB1CR_B1DPE. */ #define BS_FMC_PFB1CR_B1DPE (1U) /*!< Bit field size in bits for FMC_PFB1CR_B1DPE. */ /*! @brief Read current value of the FMC_PFB1CR_B1DPE field. */ #define BR_FMC_PFB1CR_B1DPE(x) (BITBAND_ACCESS32(HW_FMC_PFB1CR_ADDR(x), BP_FMC_PFB1CR_B1DPE)) /*! @brief Format value for bitfield FMC_PFB1CR_B1DPE. */ #define BF_FMC_PFB1CR_B1DPE(v) ((uint32_t)((uint32_t)(v) << BP_FMC_PFB1CR_B1DPE) & BM_FMC_PFB1CR_B1DPE) /*! @brief Set the B1DPE field to a new value. */ #define BW_FMC_PFB1CR_B1DPE(x, v) (BITBAND_ACCESS32(HW_FMC_PFB1CR_ADDR(x), BP_FMC_PFB1CR_B1DPE) = (v)) /*@}*/ /*! * @name Register FMC_PFB1CR, field B1ICE[3] (RW) * * This bit controls whether instruction fetches are loaded into the cache. * * Values: * - 0 - Do not cache instruction fetches. * - 1 - Cache instruction fetches. */ /*@{*/ #define BP_FMC_PFB1CR_B1ICE (3U) /*!< Bit position for FMC_PFB1CR_B1ICE. */ #define BM_FMC_PFB1CR_B1ICE (0x00000008U) /*!< Bit mask for FMC_PFB1CR_B1ICE. */ #define BS_FMC_PFB1CR_B1ICE (1U) /*!< Bit field size in bits for FMC_PFB1CR_B1ICE. */ /*! @brief Read current value of the FMC_PFB1CR_B1ICE field. */ #define BR_FMC_PFB1CR_B1ICE(x) (BITBAND_ACCESS32(HW_FMC_PFB1CR_ADDR(x), BP_FMC_PFB1CR_B1ICE)) /*! @brief Format value for bitfield FMC_PFB1CR_B1ICE. */ #define BF_FMC_PFB1CR_B1ICE(v) ((uint32_t)((uint32_t)(v) << BP_FMC_PFB1CR_B1ICE) & BM_FMC_PFB1CR_B1ICE) /*! @brief Set the B1ICE field to a new value. */ #define BW_FMC_PFB1CR_B1ICE(x, v) (BITBAND_ACCESS32(HW_FMC_PFB1CR_ADDR(x), BP_FMC_PFB1CR_B1ICE) = (v)) /*@}*/ /*! * @name Register FMC_PFB1CR, field B1DCE[4] (RW) * * This bit controls whether data references are loaded into the cache. * * Values: * - 0 - Do not cache data references. * - 1 - Cache data references. */ /*@{*/ #define BP_FMC_PFB1CR_B1DCE (4U) /*!< Bit position for FMC_PFB1CR_B1DCE. */ #define BM_FMC_PFB1CR_B1DCE (0x00000010U) /*!< Bit mask for FMC_PFB1CR_B1DCE. */ #define BS_FMC_PFB1CR_B1DCE (1U) /*!< Bit field size in bits for FMC_PFB1CR_B1DCE. */ /*! @brief Read current value of the FMC_PFB1CR_B1DCE field. */ #define BR_FMC_PFB1CR_B1DCE(x) (BITBAND_ACCESS32(HW_FMC_PFB1CR_ADDR(x), BP_FMC_PFB1CR_B1DCE)) /*! @brief Format value for bitfield FMC_PFB1CR_B1DCE. */ #define BF_FMC_PFB1CR_B1DCE(v) ((uint32_t)((uint32_t)(v) << BP_FMC_PFB1CR_B1DCE) & BM_FMC_PFB1CR_B1DCE) /*! @brief Set the B1DCE field to a new value. */ #define BW_FMC_PFB1CR_B1DCE(x, v) (BITBAND_ACCESS32(HW_FMC_PFB1CR_ADDR(x), BP_FMC_PFB1CR_B1DCE) = (v)) /*@}*/ /*! * @name Register FMC_PFB1CR, field B1MW[18:17] (RO) * * This read-only field defines the width of the bank 1 memory. * * Values: * - 00 - 32 bits * - 01 - 64 bits * - 10 - 128 bits * - 11 - Reserved */ /*@{*/ #define BP_FMC_PFB1CR_B1MW (17U) /*!< Bit position for FMC_PFB1CR_B1MW. */ #define BM_FMC_PFB1CR_B1MW (0x00060000U) /*!< Bit mask for FMC_PFB1CR_B1MW. */ #define BS_FMC_PFB1CR_B1MW (2U) /*!< Bit field size in bits for FMC_PFB1CR_B1MW. */ /*! @brief Read current value of the FMC_PFB1CR_B1MW field. */ #define BR_FMC_PFB1CR_B1MW(x) (HW_FMC_PFB1CR(x).B.B1MW) /*@}*/ /*! * @name Register FMC_PFB1CR, field B1RWSC[31:28] (RO) * * This read-only field defines the number of wait states required to access the * bank 1 flash memory. The relationship between the read access time of the * flash array (expressed in system clock cycles) and RWSC is defined as: Access * time of flash array [system clocks] = RWSC + 1 The FMC automatically calculates * this value based on the ratio of the system clock speed to the flash clock * speed. For example, when this ratio is 4:1, the field's value is 3h. */ /*@{*/ #define BP_FMC_PFB1CR_B1RWSC (28U) /*!< Bit position for FMC_PFB1CR_B1RWSC. */ #define BM_FMC_PFB1CR_B1RWSC (0xF0000000U) /*!< Bit mask for FMC_PFB1CR_B1RWSC. */ #define BS_FMC_PFB1CR_B1RWSC (4U) /*!< Bit field size in bits for FMC_PFB1CR_B1RWSC. */ /*! @brief Read current value of the FMC_PFB1CR_B1RWSC field. */ #define BR_FMC_PFB1CR_B1RWSC(x) (HW_FMC_PFB1CR(x).B.B1RWSC) /*@}*/ /******************************************************************************* * HW_FMC_TAGVDW0Sn - Cache Tag Storage ******************************************************************************/ /*! * @brief HW_FMC_TAGVDW0Sn - Cache Tag Storage (RW) * * Reset value: 0x00000000U * * The cache is a 4-way, set-associative cache with 4 sets. The ways are * numbered 0-3 and the sets are numbered 0-3. In TAGVDWxSy, x denotes the way, and y * denotes the set. This section represents tag/vld information for all sets in the * indicated way. */ typedef union _hw_fmc_tagvdw0sn { uint32_t U; struct _hw_fmc_tagvdw0sn_bitfields { uint32_t valid : 1; /*!< [0] 1-bit valid for cache entry */ uint32_t RESERVED0 : 4; /*!< [4:1] */ uint32_t tag : 14; /*!< [18:5] 14-bit tag for cache entry */ uint32_t RESERVED1 : 13; /*!< [31:19] */ } B; } hw_fmc_tagvdw0sn_t; /*! * @name Constants and macros for entire FMC_TAGVDW0Sn register */ /*@{*/ #define HW_FMC_TAGVDW0Sn_COUNT (4U) #define HW_FMC_TAGVDW0Sn_ADDR(x, n) ((x) + 0x100U + (0x4U * (n))) #define HW_FMC_TAGVDW0Sn(x, n) (*(__IO hw_fmc_tagvdw0sn_t *) HW_FMC_TAGVDW0Sn_ADDR(x, n)) #define HW_FMC_TAGVDW0Sn_RD(x, n) (HW_FMC_TAGVDW0Sn(x, n).U) #define HW_FMC_TAGVDW0Sn_WR(x, n, v) (HW_FMC_TAGVDW0Sn(x, n).U = (v)) #define HW_FMC_TAGVDW0Sn_SET(x, n, v) (HW_FMC_TAGVDW0Sn_WR(x, n, HW_FMC_TAGVDW0Sn_RD(x, n) | (v))) #define HW_FMC_TAGVDW0Sn_CLR(x, n, v) (HW_FMC_TAGVDW0Sn_WR(x, n, HW_FMC_TAGVDW0Sn_RD(x, n) & ~(v))) #define HW_FMC_TAGVDW0Sn_TOG(x, n, v) (HW_FMC_TAGVDW0Sn_WR(x, n, HW_FMC_TAGVDW0Sn_RD(x, n) ^ (v))) /*@}*/ /* * Constants & macros for individual FMC_TAGVDW0Sn bitfields */ /*! * @name Register FMC_TAGVDW0Sn, field valid[0] (RW) */ /*@{*/ #define BP_FMC_TAGVDW0Sn_valid (0U) /*!< Bit position for FMC_TAGVDW0Sn_valid. */ #define BM_FMC_TAGVDW0Sn_valid (0x00000001U) /*!< Bit mask for FMC_TAGVDW0Sn_valid. */ #define BS_FMC_TAGVDW0Sn_valid (1U) /*!< Bit field size in bits for FMC_TAGVDW0Sn_valid. */ /*! @brief Read current value of the FMC_TAGVDW0Sn_valid field. */ #define BR_FMC_TAGVDW0Sn_valid(x, n) (BITBAND_ACCESS32(HW_FMC_TAGVDW0Sn_ADDR(x, n), BP_FMC_TAGVDW0Sn_valid)) /*! @brief Format value for bitfield FMC_TAGVDW0Sn_valid. */ #define BF_FMC_TAGVDW0Sn_valid(v) ((uint32_t)((uint32_t)(v) << BP_FMC_TAGVDW0Sn_valid) & BM_FMC_TAGVDW0Sn_valid) /*! @brief Set the valid field to a new value. */ #define BW_FMC_TAGVDW0Sn_valid(x, n, v) (BITBAND_ACCESS32(HW_FMC_TAGVDW0Sn_ADDR(x, n), BP_FMC_TAGVDW0Sn_valid) = (v)) /*@}*/ /*! * @name Register FMC_TAGVDW0Sn, field tag[18:5] (RW) */ /*@{*/ #define BP_FMC_TAGVDW0Sn_tag (5U) /*!< Bit position for FMC_TAGVDW0Sn_tag. */ #define BM_FMC_TAGVDW0Sn_tag (0x0007FFE0U) /*!< Bit mask for FMC_TAGVDW0Sn_tag. */ #define BS_FMC_TAGVDW0Sn_tag (14U) /*!< Bit field size in bits for FMC_TAGVDW0Sn_tag. */ /*! @brief Read current value of the FMC_TAGVDW0Sn_tag field. */ #define BR_FMC_TAGVDW0Sn_tag(x, n) (HW_FMC_TAGVDW0Sn(x, n).B.tag) /*! @brief Format value for bitfield FMC_TAGVDW0Sn_tag. */ #define BF_FMC_TAGVDW0Sn_tag(v) ((uint32_t)((uint32_t)(v) << BP_FMC_TAGVDW0Sn_tag) & BM_FMC_TAGVDW0Sn_tag) /*! @brief Set the tag field to a new value. */ #define BW_FMC_TAGVDW0Sn_tag(x, n, v) (HW_FMC_TAGVDW0Sn_WR(x, n, (HW_FMC_TAGVDW0Sn_RD(x, n) & ~BM_FMC_TAGVDW0Sn_tag) | BF_FMC_TAGVDW0Sn_tag(v))) /*@}*/ /******************************************************************************* * HW_FMC_TAGVDW1Sn - Cache Tag Storage ******************************************************************************/ /*! * @brief HW_FMC_TAGVDW1Sn - Cache Tag Storage (RW) * * Reset value: 0x00000000U * * The cache is a 4-way, set-associative cache with 4 sets. The ways are * numbered 0-3 and the sets are numbered 0-3. In TAGVDWxSy, x denotes the way, and y * denotes the set. This section represents tag/vld information for all sets in the * indicated way. */ typedef union _hw_fmc_tagvdw1sn { uint32_t U; struct _hw_fmc_tagvdw1sn_bitfields { uint32_t valid : 1; /*!< [0] 1-bit valid for cache entry */ uint32_t RESERVED0 : 4; /*!< [4:1] */ uint32_t tag : 14; /*!< [18:5] 14-bit tag for cache entry */ uint32_t RESERVED1 : 13; /*!< [31:19] */ } B; } hw_fmc_tagvdw1sn_t; /*! * @name Constants and macros for entire FMC_TAGVDW1Sn register */ /*@{*/ #define HW_FMC_TAGVDW1Sn_COUNT (4U) #define HW_FMC_TAGVDW1Sn_ADDR(x, n) ((x) + 0x110U + (0x4U * (n))) #define HW_FMC_TAGVDW1Sn(x, n) (*(__IO hw_fmc_tagvdw1sn_t *) HW_FMC_TAGVDW1Sn_ADDR(x, n)) #define HW_FMC_TAGVDW1Sn_RD(x, n) (HW_FMC_TAGVDW1Sn(x, n).U) #define HW_FMC_TAGVDW1Sn_WR(x, n, v) (HW_FMC_TAGVDW1Sn(x, n).U = (v)) #define HW_FMC_TAGVDW1Sn_SET(x, n, v) (HW_FMC_TAGVDW1Sn_WR(x, n, HW_FMC_TAGVDW1Sn_RD(x, n) | (v))) #define HW_FMC_TAGVDW1Sn_CLR(x, n, v) (HW_FMC_TAGVDW1Sn_WR(x, n, HW_FMC_TAGVDW1Sn_RD(x, n) & ~(v))) #define HW_FMC_TAGVDW1Sn_TOG(x, n, v) (HW_FMC_TAGVDW1Sn_WR(x, n, HW_FMC_TAGVDW1Sn_RD(x, n) ^ (v))) /*@}*/ /* * Constants & macros for individual FMC_TAGVDW1Sn bitfields */ /*! * @name Register FMC_TAGVDW1Sn, field valid[0] (RW) */ /*@{*/ #define BP_FMC_TAGVDW1Sn_valid (0U) /*!< Bit position for FMC_TAGVDW1Sn_valid. */ #define BM_FMC_TAGVDW1Sn_valid (0x00000001U) /*!< Bit mask for FMC_TAGVDW1Sn_valid. */ #define BS_FMC_TAGVDW1Sn_valid (1U) /*!< Bit field size in bits for FMC_TAGVDW1Sn_valid. */ /*! @brief Read current value of the FMC_TAGVDW1Sn_valid field. */ #define BR_FMC_TAGVDW1Sn_valid(x, n) (BITBAND_ACCESS32(HW_FMC_TAGVDW1Sn_ADDR(x, n), BP_FMC_TAGVDW1Sn_valid)) /*! @brief Format value for bitfield FMC_TAGVDW1Sn_valid. */ #define BF_FMC_TAGVDW1Sn_valid(v) ((uint32_t)((uint32_t)(v) << BP_FMC_TAGVDW1Sn_valid) & BM_FMC_TAGVDW1Sn_valid) /*! @brief Set the valid field to a new value. */ #define BW_FMC_TAGVDW1Sn_valid(x, n, v) (BITBAND_ACCESS32(HW_FMC_TAGVDW1Sn_ADDR(x, n), BP_FMC_TAGVDW1Sn_valid) = (v)) /*@}*/ /*! * @name Register FMC_TAGVDW1Sn, field tag[18:5] (RW) */ /*@{*/ #define BP_FMC_TAGVDW1Sn_tag (5U) /*!< Bit position for FMC_TAGVDW1Sn_tag. */ #define BM_FMC_TAGVDW1Sn_tag (0x0007FFE0U) /*!< Bit mask for FMC_TAGVDW1Sn_tag. */ #define BS_FMC_TAGVDW1Sn_tag (14U) /*!< Bit field size in bits for FMC_TAGVDW1Sn_tag. */ /*! @brief Read current value of the FMC_TAGVDW1Sn_tag field. */ #define BR_FMC_TAGVDW1Sn_tag(x, n) (HW_FMC_TAGVDW1Sn(x, n).B.tag) /*! @brief Format value for bitfield FMC_TAGVDW1Sn_tag. */ #define BF_FMC_TAGVDW1Sn_tag(v) ((uint32_t)((uint32_t)(v) << BP_FMC_TAGVDW1Sn_tag) & BM_FMC_TAGVDW1Sn_tag) /*! @brief Set the tag field to a new value. */ #define BW_FMC_TAGVDW1Sn_tag(x, n, v) (HW_FMC_TAGVDW1Sn_WR(x, n, (HW_FMC_TAGVDW1Sn_RD(x, n) & ~BM_FMC_TAGVDW1Sn_tag) | BF_FMC_TAGVDW1Sn_tag(v))) /*@}*/ /******************************************************************************* * HW_FMC_TAGVDW2Sn - Cache Tag Storage ******************************************************************************/ /*! * @brief HW_FMC_TAGVDW2Sn - Cache Tag Storage (RW) * * Reset value: 0x00000000U * * The cache is a 4-way, set-associative cache with 4 sets. The ways are * numbered 0-3 and the sets are numbered 0-3. In TAGVDWxSy, x denotes the way, and y * denotes the set. This section represents tag/vld information for all sets in the * indicated way. */ typedef union _hw_fmc_tagvdw2sn { uint32_t U; struct _hw_fmc_tagvdw2sn_bitfields { uint32_t valid : 1; /*!< [0] 1-bit valid for cache entry */ uint32_t RESERVED0 : 4; /*!< [4:1] */ uint32_t tag : 14; /*!< [18:5] 14-bit tag for cache entry */ uint32_t RESERVED1 : 13; /*!< [31:19] */ } B; } hw_fmc_tagvdw2sn_t; /*! * @name Constants and macros for entire FMC_TAGVDW2Sn register */ /*@{*/ #define HW_FMC_TAGVDW2Sn_COUNT (4U) #define HW_FMC_TAGVDW2Sn_ADDR(x, n) ((x) + 0x120U + (0x4U * (n))) #define HW_FMC_TAGVDW2Sn(x, n) (*(__IO hw_fmc_tagvdw2sn_t *) HW_FMC_TAGVDW2Sn_ADDR(x, n)) #define HW_FMC_TAGVDW2Sn_RD(x, n) (HW_FMC_TAGVDW2Sn(x, n).U) #define HW_FMC_TAGVDW2Sn_WR(x, n, v) (HW_FMC_TAGVDW2Sn(x, n).U = (v)) #define HW_FMC_TAGVDW2Sn_SET(x, n, v) (HW_FMC_TAGVDW2Sn_WR(x, n, HW_FMC_TAGVDW2Sn_RD(x, n) | (v))) #define HW_FMC_TAGVDW2Sn_CLR(x, n, v) (HW_FMC_TAGVDW2Sn_WR(x, n, HW_FMC_TAGVDW2Sn_RD(x, n) & ~(v))) #define HW_FMC_TAGVDW2Sn_TOG(x, n, v) (HW_FMC_TAGVDW2Sn_WR(x, n, HW_FMC_TAGVDW2Sn_RD(x, n) ^ (v))) /*@}*/ /* * Constants & macros for individual FMC_TAGVDW2Sn bitfields */ /*! * @name Register FMC_TAGVDW2Sn, field valid[0] (RW) */ /*@{*/ #define BP_FMC_TAGVDW2Sn_valid (0U) /*!< Bit position for FMC_TAGVDW2Sn_valid. */ #define BM_FMC_TAGVDW2Sn_valid (0x00000001U) /*!< Bit mask for FMC_TAGVDW2Sn_valid. */ #define BS_FMC_TAGVDW2Sn_valid (1U) /*!< Bit field size in bits for FMC_TAGVDW2Sn_valid. */ /*! @brief Read current value of the FMC_TAGVDW2Sn_valid field. */ #define BR_FMC_TAGVDW2Sn_valid(x, n) (BITBAND_ACCESS32(HW_FMC_TAGVDW2Sn_ADDR(x, n), BP_FMC_TAGVDW2Sn_valid)) /*! @brief Format value for bitfield FMC_TAGVDW2Sn_valid. */ #define BF_FMC_TAGVDW2Sn_valid(v) ((uint32_t)((uint32_t)(v) << BP_FMC_TAGVDW2Sn_valid) & BM_FMC_TAGVDW2Sn_valid) /*! @brief Set the valid field to a new value. */ #define BW_FMC_TAGVDW2Sn_valid(x, n, v) (BITBAND_ACCESS32(HW_FMC_TAGVDW2Sn_ADDR(x, n), BP_FMC_TAGVDW2Sn_valid) = (v)) /*@}*/ /*! * @name Register FMC_TAGVDW2Sn, field tag[18:5] (RW) */ /*@{*/ #define BP_FMC_TAGVDW2Sn_tag (5U) /*!< Bit position for FMC_TAGVDW2Sn_tag. */ #define BM_FMC_TAGVDW2Sn_tag (0x0007FFE0U) /*!< Bit mask for FMC_TAGVDW2Sn_tag. */ #define BS_FMC_TAGVDW2Sn_tag (14U) /*!< Bit field size in bits for FMC_TAGVDW2Sn_tag. */ /*! @brief Read current value of the FMC_TAGVDW2Sn_tag field. */ #define BR_FMC_TAGVDW2Sn_tag(x, n) (HW_FMC_TAGVDW2Sn(x, n).B.tag) /*! @brief Format value for bitfield FMC_TAGVDW2Sn_tag. */ #define BF_FMC_TAGVDW2Sn_tag(v) ((uint32_t)((uint32_t)(v) << BP_FMC_TAGVDW2Sn_tag) & BM_FMC_TAGVDW2Sn_tag) /*! @brief Set the tag field to a new value. */ #define BW_FMC_TAGVDW2Sn_tag(x, n, v) (HW_FMC_TAGVDW2Sn_WR(x, n, (HW_FMC_TAGVDW2Sn_RD(x, n) & ~BM_FMC_TAGVDW2Sn_tag) | BF_FMC_TAGVDW2Sn_tag(v))) /*@}*/ /******************************************************************************* * HW_FMC_TAGVDW3Sn - Cache Tag Storage ******************************************************************************/ /*! * @brief HW_FMC_TAGVDW3Sn - Cache Tag Storage (RW) * * Reset value: 0x00000000U * * The cache is a 4-way, set-associative cache with 4 sets. The ways are * numbered 0-3 and the sets are numbered 0-3. In TAGVDWxSy, x denotes the way, and y * denotes the set. This section represents tag/vld information for all sets in the * indicated way. */ typedef union _hw_fmc_tagvdw3sn { uint32_t U; struct _hw_fmc_tagvdw3sn_bitfields { uint32_t valid : 1; /*!< [0] 1-bit valid for cache entry */ uint32_t RESERVED0 : 4; /*!< [4:1] */ uint32_t tag : 14; /*!< [18:5] 14-bit tag for cache entry */ uint32_t RESERVED1 : 13; /*!< [31:19] */ } B; } hw_fmc_tagvdw3sn_t; /*! * @name Constants and macros for entire FMC_TAGVDW3Sn register */ /*@{*/ #define HW_FMC_TAGVDW3Sn_COUNT (4U) #define HW_FMC_TAGVDW3Sn_ADDR(x, n) ((x) + 0x130U + (0x4U * (n))) #define HW_FMC_TAGVDW3Sn(x, n) (*(__IO hw_fmc_tagvdw3sn_t *) HW_FMC_TAGVDW3Sn_ADDR(x, n)) #define HW_FMC_TAGVDW3Sn_RD(x, n) (HW_FMC_TAGVDW3Sn(x, n).U) #define HW_FMC_TAGVDW3Sn_WR(x, n, v) (HW_FMC_TAGVDW3Sn(x, n).U = (v)) #define HW_FMC_TAGVDW3Sn_SET(x, n, v) (HW_FMC_TAGVDW3Sn_WR(x, n, HW_FMC_TAGVDW3Sn_RD(x, n) | (v))) #define HW_FMC_TAGVDW3Sn_CLR(x, n, v) (HW_FMC_TAGVDW3Sn_WR(x, n, HW_FMC_TAGVDW3Sn_RD(x, n) & ~(v))) #define HW_FMC_TAGVDW3Sn_TOG(x, n, v) (HW_FMC_TAGVDW3Sn_WR(x, n, HW_FMC_TAGVDW3Sn_RD(x, n) ^ (v))) /*@}*/ /* * Constants & macros for individual FMC_TAGVDW3Sn bitfields */ /*! * @name Register FMC_TAGVDW3Sn, field valid[0] (RW) */ /*@{*/ #define BP_FMC_TAGVDW3Sn_valid (0U) /*!< Bit position for FMC_TAGVDW3Sn_valid. */ #define BM_FMC_TAGVDW3Sn_valid (0x00000001U) /*!< Bit mask for FMC_TAGVDW3Sn_valid. */ #define BS_FMC_TAGVDW3Sn_valid (1U) /*!< Bit field size in bits for FMC_TAGVDW3Sn_valid. */ /*! @brief Read current value of the FMC_TAGVDW3Sn_valid field. */ #define BR_FMC_TAGVDW3Sn_valid(x, n) (BITBAND_ACCESS32(HW_FMC_TAGVDW3Sn_ADDR(x, n), BP_FMC_TAGVDW3Sn_valid)) /*! @brief Format value for bitfield FMC_TAGVDW3Sn_valid. */ #define BF_FMC_TAGVDW3Sn_valid(v) ((uint32_t)((uint32_t)(v) << BP_FMC_TAGVDW3Sn_valid) & BM_FMC_TAGVDW3Sn_valid) /*! @brief Set the valid field to a new value. */ #define BW_FMC_TAGVDW3Sn_valid(x, n, v) (BITBAND_ACCESS32(HW_FMC_TAGVDW3Sn_ADDR(x, n), BP_FMC_TAGVDW3Sn_valid) = (v)) /*@}*/ /*! * @name Register FMC_TAGVDW3Sn, field tag[18:5] (RW) */ /*@{*/ #define BP_FMC_TAGVDW3Sn_tag (5U) /*!< Bit position for FMC_TAGVDW3Sn_tag. */ #define BM_FMC_TAGVDW3Sn_tag (0x0007FFE0U) /*!< Bit mask for FMC_TAGVDW3Sn_tag. */ #define BS_FMC_TAGVDW3Sn_tag (14U) /*!< Bit field size in bits for FMC_TAGVDW3Sn_tag. */ /*! @brief Read current value of the FMC_TAGVDW3Sn_tag field. */ #define BR_FMC_TAGVDW3Sn_tag(x, n) (HW_FMC_TAGVDW3Sn(x, n).B.tag) /*! @brief Format value for bitfield FMC_TAGVDW3Sn_tag. */ #define BF_FMC_TAGVDW3Sn_tag(v) ((uint32_t)((uint32_t)(v) << BP_FMC_TAGVDW3Sn_tag) & BM_FMC_TAGVDW3Sn_tag) /*! @brief Set the tag field to a new value. */ #define BW_FMC_TAGVDW3Sn_tag(x, n, v) (HW_FMC_TAGVDW3Sn_WR(x, n, (HW_FMC_TAGVDW3Sn_RD(x, n) & ~BM_FMC_TAGVDW3Sn_tag) | BF_FMC_TAGVDW3Sn_tag(v))) /*@}*/ /******************************************************************************* * HW_FMC_DATAW0SnU - Cache Data Storage (upper word) ******************************************************************************/ /*! * @brief HW_FMC_DATAW0SnU - Cache Data Storage (upper word) (RW) * * Reset value: 0x00000000U * * The cache of 64-bit entries is a 4-way, set-associative cache with 4 sets. * The ways are numbered 0-3 and the sets are numbered 0-3. In DATAWxSyU and * DATAWxSyL, x denotes the way, y denotes the set, and U and L represent upper and * lower word, respectively. This section represents data for the upper word (bits * [63:32]) of all sets in the indicated way. */ typedef union _hw_fmc_dataw0snu { uint32_t U; struct _hw_fmc_dataw0snu_bitfields { uint32_t data : 32; /*!< [31:0] Bits [63:32] of data entry */ } B; } hw_fmc_dataw0snu_t; /*! * @name Constants and macros for entire FMC_DATAW0SnU register */ /*@{*/ #define HW_FMC_DATAW0SnU_COUNT (4U) #define HW_FMC_DATAW0SnU_ADDR(x, n) ((x) + 0x200U + (0x8U * (n))) #define HW_FMC_DATAW0SnU(x, n) (*(__IO hw_fmc_dataw0snu_t *) HW_FMC_DATAW0SnU_ADDR(x, n)) #define HW_FMC_DATAW0SnU_RD(x, n) (HW_FMC_DATAW0SnU(x, n).U) #define HW_FMC_DATAW0SnU_WR(x, n, v) (HW_FMC_DATAW0SnU(x, n).U = (v)) #define HW_FMC_DATAW0SnU_SET(x, n, v) (HW_FMC_DATAW0SnU_WR(x, n, HW_FMC_DATAW0SnU_RD(x, n) | (v))) #define HW_FMC_DATAW0SnU_CLR(x, n, v) (HW_FMC_DATAW0SnU_WR(x, n, HW_FMC_DATAW0SnU_RD(x, n) & ~(v))) #define HW_FMC_DATAW0SnU_TOG(x, n, v) (HW_FMC_DATAW0SnU_WR(x, n, HW_FMC_DATAW0SnU_RD(x, n) ^ (v))) /*@}*/ /* * Constants & macros for individual FMC_DATAW0SnU bitfields */ /*! * @name Register FMC_DATAW0SnU, field data[31:0] (RW) */ /*@{*/ #define BP_FMC_DATAW0SnU_data (0U) /*!< Bit position for FMC_DATAW0SnU_data. */ #define BM_FMC_DATAW0SnU_data (0xFFFFFFFFU) /*!< Bit mask for FMC_DATAW0SnU_data. */ #define BS_FMC_DATAW0SnU_data (32U) /*!< Bit field size in bits for FMC_DATAW0SnU_data. */ /*! @brief Read current value of the FMC_DATAW0SnU_data field. */ #define BR_FMC_DATAW0SnU_data(x, n) (HW_FMC_DATAW0SnU(x, n).U) /*! @brief Format value for bitfield FMC_DATAW0SnU_data. */ #define BF_FMC_DATAW0SnU_data(v) ((uint32_t)((uint32_t)(v) << BP_FMC_DATAW0SnU_data) & BM_FMC_DATAW0SnU_data) /*! @brief Set the data field to a new value. */ #define BW_FMC_DATAW0SnU_data(x, n, v) (HW_FMC_DATAW0SnU_WR(x, n, v)) /*@}*/ /******************************************************************************* * HW_FMC_DATAW0SnL - Cache Data Storage (lower word) ******************************************************************************/ /*! * @brief HW_FMC_DATAW0SnL - Cache Data Storage (lower word) (RW) * * Reset value: 0x00000000U * * The cache of 64-bit entries is a 4-way, set-associative cache with 4 sets. * The ways are numbered 0-3 and the sets are numbered 0-3. In DATAWxSyU and * DATAWxSyL, x denotes the way, y denotes the set, and U and L represent upper and * lower word, respectively. This section represents data for the lower word (bits * [31:0]) of all sets in the indicated way. */ typedef union _hw_fmc_dataw0snl { uint32_t U; struct _hw_fmc_dataw0snl_bitfields { uint32_t data : 32; /*!< [31:0] Bits [31:0] of data entry */ } B; } hw_fmc_dataw0snl_t; /*! * @name Constants and macros for entire FMC_DATAW0SnL register */ /*@{*/ #define HW_FMC_DATAW0SnL_COUNT (4U) #define HW_FMC_DATAW0SnL_ADDR(x, n) ((x) + 0x204U + (0x8U * (n))) #define HW_FMC_DATAW0SnL(x, n) (*(__IO hw_fmc_dataw0snl_t *) HW_FMC_DATAW0SnL_ADDR(x, n)) #define HW_FMC_DATAW0SnL_RD(x, n) (HW_FMC_DATAW0SnL(x, n).U) #define HW_FMC_DATAW0SnL_WR(x, n, v) (HW_FMC_DATAW0SnL(x, n).U = (v)) #define HW_FMC_DATAW0SnL_SET(x, n, v) (HW_FMC_DATAW0SnL_WR(x, n, HW_FMC_DATAW0SnL_RD(x, n) | (v))) #define HW_FMC_DATAW0SnL_CLR(x, n, v) (HW_FMC_DATAW0SnL_WR(x, n, HW_FMC_DATAW0SnL_RD(x, n) & ~(v))) #define HW_FMC_DATAW0SnL_TOG(x, n, v) (HW_FMC_DATAW0SnL_WR(x, n, HW_FMC_DATAW0SnL_RD(x, n) ^ (v))) /*@}*/ /* * Constants & macros for individual FMC_DATAW0SnL bitfields */ /*! * @name Register FMC_DATAW0SnL, field data[31:0] (RW) */ /*@{*/ #define BP_FMC_DATAW0SnL_data (0U) /*!< Bit position for FMC_DATAW0SnL_data. */ #define BM_FMC_DATAW0SnL_data (0xFFFFFFFFU) /*!< Bit mask for FMC_DATAW0SnL_data. */ #define BS_FMC_DATAW0SnL_data (32U) /*!< Bit field size in bits for FMC_DATAW0SnL_data. */ /*! @brief Read current value of the FMC_DATAW0SnL_data field. */ #define BR_FMC_DATAW0SnL_data(x, n) (HW_FMC_DATAW0SnL(x, n).U) /*! @brief Format value for bitfield FMC_DATAW0SnL_data. */ #define BF_FMC_DATAW0SnL_data(v) ((uint32_t)((uint32_t)(v) << BP_FMC_DATAW0SnL_data) & BM_FMC_DATAW0SnL_data) /*! @brief Set the data field to a new value. */ #define BW_FMC_DATAW0SnL_data(x, n, v) (HW_FMC_DATAW0SnL_WR(x, n, v)) /*@}*/ /******************************************************************************* * HW_FMC_DATAW1SnU - Cache Data Storage (upper word) ******************************************************************************/ /*! * @brief HW_FMC_DATAW1SnU - Cache Data Storage (upper word) (RW) * * Reset value: 0x00000000U * * The cache of 64-bit entries is a 4-way, set-associative cache with 4 sets. * The ways are numbered 0-3 and the sets are numbered 0-3. In DATAWxSyU and * DATAWxSyL, x denotes the way, y denotes the set, and U and L represent upper and * lower word, respectively. This section represents data for the upper word (bits * [63:32]) of all sets in the indicated way. */ typedef union _hw_fmc_dataw1snu { uint32_t U; struct _hw_fmc_dataw1snu_bitfields { uint32_t data : 32; /*!< [31:0] Bits [63:32] of data entry */ } B; } hw_fmc_dataw1snu_t; /*! * @name Constants and macros for entire FMC_DATAW1SnU register */ /*@{*/ #define HW_FMC_DATAW1SnU_COUNT (4U) #define HW_FMC_DATAW1SnU_ADDR(x, n) ((x) + 0x220U + (0x8U * (n))) #define HW_FMC_DATAW1SnU(x, n) (*(__IO hw_fmc_dataw1snu_t *) HW_FMC_DATAW1SnU_ADDR(x, n)) #define HW_FMC_DATAW1SnU_RD(x, n) (HW_FMC_DATAW1SnU(x, n).U) #define HW_FMC_DATAW1SnU_WR(x, n, v) (HW_FMC_DATAW1SnU(x, n).U = (v)) #define HW_FMC_DATAW1SnU_SET(x, n, v) (HW_FMC_DATAW1SnU_WR(x, n, HW_FMC_DATAW1SnU_RD(x, n) | (v))) #define HW_FMC_DATAW1SnU_CLR(x, n, v) (HW_FMC_DATAW1SnU_WR(x, n, HW_FMC_DATAW1SnU_RD(x, n) & ~(v))) #define HW_FMC_DATAW1SnU_TOG(x, n, v) (HW_FMC_DATAW1SnU_WR(x, n, HW_FMC_DATAW1SnU_RD(x, n) ^ (v))) /*@}*/ /* * Constants & macros for individual FMC_DATAW1SnU bitfields */ /*! * @name Register FMC_DATAW1SnU, field data[31:0] (RW) */ /*@{*/ #define BP_FMC_DATAW1SnU_data (0U) /*!< Bit position for FMC_DATAW1SnU_data. */ #define BM_FMC_DATAW1SnU_data (0xFFFFFFFFU) /*!< Bit mask for FMC_DATAW1SnU_data. */ #define BS_FMC_DATAW1SnU_data (32U) /*!< Bit field size in bits for FMC_DATAW1SnU_data. */ /*! @brief Read current value of the FMC_DATAW1SnU_data field. */ #define BR_FMC_DATAW1SnU_data(x, n) (HW_FMC_DATAW1SnU(x, n).U) /*! @brief Format value for bitfield FMC_DATAW1SnU_data. */ #define BF_FMC_DATAW1SnU_data(v) ((uint32_t)((uint32_t)(v) << BP_FMC_DATAW1SnU_data) & BM_FMC_DATAW1SnU_data) /*! @brief Set the data field to a new value. */ #define BW_FMC_DATAW1SnU_data(x, n, v) (HW_FMC_DATAW1SnU_WR(x, n, v)) /*@}*/ /******************************************************************************* * HW_FMC_DATAW1SnL - Cache Data Storage (lower word) ******************************************************************************/ /*! * @brief HW_FMC_DATAW1SnL - Cache Data Storage (lower word) (RW) * * Reset value: 0x00000000U * * The cache of 64-bit entries is a 4-way, set-associative cache with 4 sets. * The ways are numbered 0-3 and the sets are numbered 0-3. In DATAWxSyU and * DATAWxSyL, x denotes the way, y denotes the set, and U and L represent upper and * lower word, respectively. This section represents data for the lower word (bits * [31:0]) of all sets in the indicated way. */ typedef union _hw_fmc_dataw1snl { uint32_t U; struct _hw_fmc_dataw1snl_bitfields { uint32_t data : 32; /*!< [31:0] Bits [31:0] of data entry */ } B; } hw_fmc_dataw1snl_t; /*! * @name Constants and macros for entire FMC_DATAW1SnL register */ /*@{*/ #define HW_FMC_DATAW1SnL_COUNT (4U) #define HW_FMC_DATAW1SnL_ADDR(x, n) ((x) + 0x224U + (0x8U * (n))) #define HW_FMC_DATAW1SnL(x, n) (*(__IO hw_fmc_dataw1snl_t *) HW_FMC_DATAW1SnL_ADDR(x, n)) #define HW_FMC_DATAW1SnL_RD(x, n) (HW_FMC_DATAW1SnL(x, n).U) #define HW_FMC_DATAW1SnL_WR(x, n, v) (HW_FMC_DATAW1SnL(x, n).U = (v)) #define HW_FMC_DATAW1SnL_SET(x, n, v) (HW_FMC_DATAW1SnL_WR(x, n, HW_FMC_DATAW1SnL_RD(x, n) | (v))) #define HW_FMC_DATAW1SnL_CLR(x, n, v) (HW_FMC_DATAW1SnL_WR(x, n, HW_FMC_DATAW1SnL_RD(x, n) & ~(v))) #define HW_FMC_DATAW1SnL_TOG(x, n, v) (HW_FMC_DATAW1SnL_WR(x, n, HW_FMC_DATAW1SnL_RD(x, n) ^ (v))) /*@}*/ /* * Constants & macros for individual FMC_DATAW1SnL bitfields */ /*! * @name Register FMC_DATAW1SnL, field data[31:0] (RW) */ /*@{*/ #define BP_FMC_DATAW1SnL_data (0U) /*!< Bit position for FMC_DATAW1SnL_data. */ #define BM_FMC_DATAW1SnL_data (0xFFFFFFFFU) /*!< Bit mask for FMC_DATAW1SnL_data. */ #define BS_FMC_DATAW1SnL_data (32U) /*!< Bit field size in bits for FMC_DATAW1SnL_data. */ /*! @brief Read current value of the FMC_DATAW1SnL_data field. */ #define BR_FMC_DATAW1SnL_data(x, n) (HW_FMC_DATAW1SnL(x, n).U) /*! @brief Format value for bitfield FMC_DATAW1SnL_data. */ #define BF_FMC_DATAW1SnL_data(v) ((uint32_t)((uint32_t)(v) << BP_FMC_DATAW1SnL_data) & BM_FMC_DATAW1SnL_data) /*! @brief Set the data field to a new value. */ #define BW_FMC_DATAW1SnL_data(x, n, v) (HW_FMC_DATAW1SnL_WR(x, n, v)) /*@}*/ /******************************************************************************* * HW_FMC_DATAW2SnU - Cache Data Storage (upper word) ******************************************************************************/ /*! * @brief HW_FMC_DATAW2SnU - Cache Data Storage (upper word) (RW) * * Reset value: 0x00000000U * * The cache of 64-bit entries is a 4-way, set-associative cache with 4 sets. * The ways are numbered 0-3 and the sets are numbered 0-3. In DATAWxSyU and * DATAWxSyL, x denotes the way, y denotes the set, and U and L represent upper and * lower word, respectively. This section represents data for the upper word (bits * [63:32]) of all sets in the indicated way. */ typedef union _hw_fmc_dataw2snu { uint32_t U; struct _hw_fmc_dataw2snu_bitfields { uint32_t data : 32; /*!< [31:0] Bits [63:32] of data entry */ } B; } hw_fmc_dataw2snu_t; /*! * @name Constants and macros for entire FMC_DATAW2SnU register */ /*@{*/ #define HW_FMC_DATAW2SnU_COUNT (4U) #define HW_FMC_DATAW2SnU_ADDR(x, n) ((x) + 0x240U + (0x8U * (n))) #define HW_FMC_DATAW2SnU(x, n) (*(__IO hw_fmc_dataw2snu_t *) HW_FMC_DATAW2SnU_ADDR(x, n)) #define HW_FMC_DATAW2SnU_RD(x, n) (HW_FMC_DATAW2SnU(x, n).U) #define HW_FMC_DATAW2SnU_WR(x, n, v) (HW_FMC_DATAW2SnU(x, n).U = (v)) #define HW_FMC_DATAW2SnU_SET(x, n, v) (HW_FMC_DATAW2SnU_WR(x, n, HW_FMC_DATAW2SnU_RD(x, n) | (v))) #define HW_FMC_DATAW2SnU_CLR(x, n, v) (HW_FMC_DATAW2SnU_WR(x, n, HW_FMC_DATAW2SnU_RD(x, n) & ~(v))) #define HW_FMC_DATAW2SnU_TOG(x, n, v) (HW_FMC_DATAW2SnU_WR(x, n, HW_FMC_DATAW2SnU_RD(x, n) ^ (v))) /*@}*/ /* * Constants & macros for individual FMC_DATAW2SnU bitfields */ /*! * @name Register FMC_DATAW2SnU, field data[31:0] (RW) */ /*@{*/ #define BP_FMC_DATAW2SnU_data (0U) /*!< Bit position for FMC_DATAW2SnU_data. */ #define BM_FMC_DATAW2SnU_data (0xFFFFFFFFU) /*!< Bit mask for FMC_DATAW2SnU_data. */ #define BS_FMC_DATAW2SnU_data (32U) /*!< Bit field size in bits for FMC_DATAW2SnU_data. */ /*! @brief Read current value of the FMC_DATAW2SnU_data field. */ #define BR_FMC_DATAW2SnU_data(x, n) (HW_FMC_DATAW2SnU(x, n).U) /*! @brief Format value for bitfield FMC_DATAW2SnU_data. */ #define BF_FMC_DATAW2SnU_data(v) ((uint32_t)((uint32_t)(v) << BP_FMC_DATAW2SnU_data) & BM_FMC_DATAW2SnU_data) /*! @brief Set the data field to a new value. */ #define BW_FMC_DATAW2SnU_data(x, n, v) (HW_FMC_DATAW2SnU_WR(x, n, v)) /*@}*/ /******************************************************************************* * HW_FMC_DATAW2SnL - Cache Data Storage (lower word) ******************************************************************************/ /*! * @brief HW_FMC_DATAW2SnL - Cache Data Storage (lower word) (RW) * * Reset value: 0x00000000U * * The cache of 64-bit entries is a 4-way, set-associative cache with 4 sets. * The ways are numbered 0-3 and the sets are numbered 0-3. In DATAWxSyU and * DATAWxSyL, x denotes the way, y denotes the set, and U and L represent upper and * lower word, respectively. This section represents data for the lower word (bits * [31:0]) of all sets in the indicated way. */ typedef union _hw_fmc_dataw2snl { uint32_t U; struct _hw_fmc_dataw2snl_bitfields { uint32_t data : 32; /*!< [31:0] Bits [31:0] of data entry */ } B; } hw_fmc_dataw2snl_t; /*! * @name Constants and macros for entire FMC_DATAW2SnL register */ /*@{*/ #define HW_FMC_DATAW2SnL_COUNT (4U) #define HW_FMC_DATAW2SnL_ADDR(x, n) ((x) + 0x244U + (0x8U * (n))) #define HW_FMC_DATAW2SnL(x, n) (*(__IO hw_fmc_dataw2snl_t *) HW_FMC_DATAW2SnL_ADDR(x, n)) #define HW_FMC_DATAW2SnL_RD(x, n) (HW_FMC_DATAW2SnL(x, n).U) #define HW_FMC_DATAW2SnL_WR(x, n, v) (HW_FMC_DATAW2SnL(x, n).U = (v)) #define HW_FMC_DATAW2SnL_SET(x, n, v) (HW_FMC_DATAW2SnL_WR(x, n, HW_FMC_DATAW2SnL_RD(x, n) | (v))) #define HW_FMC_DATAW2SnL_CLR(x, n, v) (HW_FMC_DATAW2SnL_WR(x, n, HW_FMC_DATAW2SnL_RD(x, n) & ~(v))) #define HW_FMC_DATAW2SnL_TOG(x, n, v) (HW_FMC_DATAW2SnL_WR(x, n, HW_FMC_DATAW2SnL_RD(x, n) ^ (v))) /*@}*/ /* * Constants & macros for individual FMC_DATAW2SnL bitfields */ /*! * @name Register FMC_DATAW2SnL, field data[31:0] (RW) */ /*@{*/ #define BP_FMC_DATAW2SnL_data (0U) /*!< Bit position for FMC_DATAW2SnL_data. */ #define BM_FMC_DATAW2SnL_data (0xFFFFFFFFU) /*!< Bit mask for FMC_DATAW2SnL_data. */ #define BS_FMC_DATAW2SnL_data (32U) /*!< Bit field size in bits for FMC_DATAW2SnL_data. */ /*! @brief Read current value of the FMC_DATAW2SnL_data field. */ #define BR_FMC_DATAW2SnL_data(x, n) (HW_FMC_DATAW2SnL(x, n).U) /*! @brief Format value for bitfield FMC_DATAW2SnL_data. */ #define BF_FMC_DATAW2SnL_data(v) ((uint32_t)((uint32_t)(v) << BP_FMC_DATAW2SnL_data) & BM_FMC_DATAW2SnL_data) /*! @brief Set the data field to a new value. */ #define BW_FMC_DATAW2SnL_data(x, n, v) (HW_FMC_DATAW2SnL_WR(x, n, v)) /*@}*/ /******************************************************************************* * HW_FMC_DATAW3SnU - Cache Data Storage (upper word) ******************************************************************************/ /*! * @brief HW_FMC_DATAW3SnU - Cache Data Storage (upper word) (RW) * * Reset value: 0x00000000U * * The cache of 64-bit entries is a 4-way, set-associative cache with 4 sets. * The ways are numbered 0-3 and the sets are numbered 0-3. In DATAWxSyU and * DATAWxSyL, x denotes the way, y denotes the set, and U and L represent upper and * lower word, respectively. This section represents data for the upper word (bits * [63:32]) of all sets in the indicated way. */ typedef union _hw_fmc_dataw3snu { uint32_t U; struct _hw_fmc_dataw3snu_bitfields { uint32_t data : 32; /*!< [31:0] Bits [63:32] of data entry */ } B; } hw_fmc_dataw3snu_t; /*! * @name Constants and macros for entire FMC_DATAW3SnU register */ /*@{*/ #define HW_FMC_DATAW3SnU_COUNT (4U) #define HW_FMC_DATAW3SnU_ADDR(x, n) ((x) + 0x260U + (0x8U * (n))) #define HW_FMC_DATAW3SnU(x, n) (*(__IO hw_fmc_dataw3snu_t *) HW_FMC_DATAW3SnU_ADDR(x, n)) #define HW_FMC_DATAW3SnU_RD(x, n) (HW_FMC_DATAW3SnU(x, n).U) #define HW_FMC_DATAW3SnU_WR(x, n, v) (HW_FMC_DATAW3SnU(x, n).U = (v)) #define HW_FMC_DATAW3SnU_SET(x, n, v) (HW_FMC_DATAW3SnU_WR(x, n, HW_FMC_DATAW3SnU_RD(x, n) | (v))) #define HW_FMC_DATAW3SnU_CLR(x, n, v) (HW_FMC_DATAW3SnU_WR(x, n, HW_FMC_DATAW3SnU_RD(x, n) & ~(v))) #define HW_FMC_DATAW3SnU_TOG(x, n, v) (HW_FMC_DATAW3SnU_WR(x, n, HW_FMC_DATAW3SnU_RD(x, n) ^ (v))) /*@}*/ /* * Constants & macros for individual FMC_DATAW3SnU bitfields */ /*! * @name Register FMC_DATAW3SnU, field data[31:0] (RW) */ /*@{*/ #define BP_FMC_DATAW3SnU_data (0U) /*!< Bit position for FMC_DATAW3SnU_data. */ #define BM_FMC_DATAW3SnU_data (0xFFFFFFFFU) /*!< Bit mask for FMC_DATAW3SnU_data. */ #define BS_FMC_DATAW3SnU_data (32U) /*!< Bit field size in bits for FMC_DATAW3SnU_data. */ /*! @brief Read current value of the FMC_DATAW3SnU_data field. */ #define BR_FMC_DATAW3SnU_data(x, n) (HW_FMC_DATAW3SnU(x, n).U) /*! @brief Format value for bitfield FMC_DATAW3SnU_data. */ #define BF_FMC_DATAW3SnU_data(v) ((uint32_t)((uint32_t)(v) << BP_FMC_DATAW3SnU_data) & BM_FMC_DATAW3SnU_data) /*! @brief Set the data field to a new value. */ #define BW_FMC_DATAW3SnU_data(x, n, v) (HW_FMC_DATAW3SnU_WR(x, n, v)) /*@}*/ /******************************************************************************* * HW_FMC_DATAW3SnL - Cache Data Storage (lower word) ******************************************************************************/ /*! * @brief HW_FMC_DATAW3SnL - Cache Data Storage (lower word) (RW) * * Reset value: 0x00000000U * * The cache of 64-bit entries is a 4-way, set-associative cache with 4 sets. * The ways are numbered 0-3 and the sets are numbered 0-3. In DATAWxSyU and * DATAWxSyL, x denotes the way, y denotes the set, and U and L represent upper and * lower word, respectively. This section represents data for the lower word (bits * [31:0]) of all sets in the indicated way. */ typedef union _hw_fmc_dataw3snl { uint32_t U; struct _hw_fmc_dataw3snl_bitfields { uint32_t data : 32; /*!< [31:0] Bits [31:0] of data entry */ } B; } hw_fmc_dataw3snl_t; /*! * @name Constants and macros for entire FMC_DATAW3SnL register */ /*@{*/ #define HW_FMC_DATAW3SnL_COUNT (4U) #define HW_FMC_DATAW3SnL_ADDR(x, n) ((x) + 0x264U + (0x8U * (n))) #define HW_FMC_DATAW3SnL(x, n) (*(__IO hw_fmc_dataw3snl_t *) HW_FMC_DATAW3SnL_ADDR(x, n)) #define HW_FMC_DATAW3SnL_RD(x, n) (HW_FMC_DATAW3SnL(x, n).U) #define HW_FMC_DATAW3SnL_WR(x, n, v) (HW_FMC_DATAW3SnL(x, n).U = (v)) #define HW_FMC_DATAW3SnL_SET(x, n, v) (HW_FMC_DATAW3SnL_WR(x, n, HW_FMC_DATAW3SnL_RD(x, n) | (v))) #define HW_FMC_DATAW3SnL_CLR(x, n, v) (HW_FMC_DATAW3SnL_WR(x, n, HW_FMC_DATAW3SnL_RD(x, n) & ~(v))) #define HW_FMC_DATAW3SnL_TOG(x, n, v) (HW_FMC_DATAW3SnL_WR(x, n, HW_FMC_DATAW3SnL_RD(x, n) ^ (v))) /*@}*/ /* * Constants & macros for individual FMC_DATAW3SnL bitfields */ /*! * @name Register FMC_DATAW3SnL, field data[31:0] (RW) */ /*@{*/ #define BP_FMC_DATAW3SnL_data (0U) /*!< Bit position for FMC_DATAW3SnL_data. */ #define BM_FMC_DATAW3SnL_data (0xFFFFFFFFU) /*!< Bit mask for FMC_DATAW3SnL_data. */ #define BS_FMC_DATAW3SnL_data (32U) /*!< Bit field size in bits for FMC_DATAW3SnL_data. */ /*! @brief Read current value of the FMC_DATAW3SnL_data field. */ #define BR_FMC_DATAW3SnL_data(x, n) (HW_FMC_DATAW3SnL(x, n).U) /*! @brief Format value for bitfield FMC_DATAW3SnL_data. */ #define BF_FMC_DATAW3SnL_data(v) ((uint32_t)((uint32_t)(v) << BP_FMC_DATAW3SnL_data) & BM_FMC_DATAW3SnL_data) /*! @brief Set the data field to a new value. */ #define BW_FMC_DATAW3SnL_data(x, n, v) (HW_FMC_DATAW3SnL_WR(x, n, v)) /*@}*/ /******************************************************************************* * hw_fmc_t - module struct ******************************************************************************/ /*! * @brief All FMC module registers. */ #pragma pack(1) typedef struct _hw_fmc { __IO hw_fmc_pfapr_t PFAPR; /*!< [0x0] Flash Access Protection Register */ __IO hw_fmc_pfb0cr_t PFB0CR; /*!< [0x4] Flash Bank 0 Control Register */ __IO hw_fmc_pfb1cr_t PFB1CR; /*!< [0x8] Flash Bank 1 Control Register */ uint8_t _reserved0[244]; __IO hw_fmc_tagvdw0sn_t TAGVDW0Sn[4]; /*!< [0x100] Cache Tag Storage */ __IO hw_fmc_tagvdw1sn_t TAGVDW1Sn[4]; /*!< [0x110] Cache Tag Storage */ __IO hw_fmc_tagvdw2sn_t TAGVDW2Sn[4]; /*!< [0x120] Cache Tag Storage */ __IO hw_fmc_tagvdw3sn_t TAGVDW3Sn[4]; /*!< [0x130] Cache Tag Storage */ uint8_t _reserved1[192]; struct { __IO hw_fmc_dataw0snu_t DATAW0SnU; /*!< [0x200] Cache Data Storage (upper word) */ __IO hw_fmc_dataw0snl_t DATAW0SnL; /*!< [0x204] Cache Data Storage (lower word) */ } DATAW0Sn[4]; struct { __IO hw_fmc_dataw1snu_t DATAW1SnU; /*!< [0x220] Cache Data Storage (upper word) */ __IO hw_fmc_dataw1snl_t DATAW1SnL; /*!< [0x224] Cache Data Storage (lower word) */ } DATAW1Sn[4]; struct { __IO hw_fmc_dataw2snu_t DATAW2SnU; /*!< [0x240] Cache Data Storage (upper word) */ __IO hw_fmc_dataw2snl_t DATAW2SnL; /*!< [0x244] Cache Data Storage (lower word) */ } DATAW2Sn[4]; struct { __IO hw_fmc_dataw3snu_t DATAW3SnU; /*!< [0x260] Cache Data Storage (upper word) */ __IO hw_fmc_dataw3snl_t DATAW3SnL; /*!< [0x264] Cache Data Storage (lower word) */ } DATAW3Sn[4]; } hw_fmc_t; #pragma pack() /*! @brief Macro to access all FMC registers. */ /*! @param x FMC module instance base address. */ /*! @return Reference (not a pointer) to the registers struct. To get a pointer to the struct, * use the '&' operator, like &HW_FMC(FMC_BASE). */ #define HW_FMC(x) (*(hw_fmc_t *)(x)) #endif /* __HW_FMC_REGISTERS_H__ */ /* EOF */ ================================================ FILE: Zelig/mbed/TARGET_K64F/TARGET_Freescale/TARGET_KPSDK_MCUS/TARGET_MCU_K64F/device/device/MK64F12/MK64F12_ftfe.h ================================================ /* ** ################################################################### ** Compilers: Keil ARM C/C++ Compiler ** Freescale C/C++ for Embedded ARM ** GNU C Compiler ** IAR ANSI C/C++ Compiler for ARM ** ** Reference manual: K64P144M120SF5RM, Rev.2, January 2014 ** Version: rev. 2.5, 2014-02-10 ** Build: b140604 ** ** Abstract: ** Extension to the CMSIS register access layer header. ** ** Copyright (c) 2014 Freescale Semiconductor, Inc. ** All rights reserved. ** ** Redistribution and use in source and binary forms, with or without modification, ** are permitted provided that the following conditions are met: ** ** o Redistributions of source code must retain the above copyright notice, this list ** of conditions and the following disclaimer. ** ** o Redistributions in binary form must reproduce the above copyright notice, this ** list of conditions and the following disclaimer in the documentation and/or ** other materials provided with the distribution. ** ** o Neither the name of Freescale Semiconductor, Inc. nor the names of its ** contributors may be used to endorse or promote products derived from this ** software without specific prior written permission. ** ** THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ** ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED ** WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE ** DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT 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. ** ** http: www.freescale.com ** mail: support@freescale.com ** ** Revisions: ** - rev. 1.0 (2013-08-12) ** Initial version. ** - rev. 2.0 (2013-10-29) ** Register accessor macros added to the memory map. ** Symbols for Processor Expert memory map compatibility added to the memory map. ** Startup file for gcc has been updated according to CMSIS 3.2. ** System initialization updated. ** MCG - registers updated. ** PORTA, PORTB, PORTC, PORTE - registers for digital filter removed. ** - rev. 2.1 (2013-10-30) ** Definition of BITBAND macros updated to support peripherals with 32-bit acces disabled. ** - rev. 2.2 (2013-12-09) ** DMA - EARS register removed. ** AIPS0, AIPS1 - MPRA register updated. ** - rev. 2.3 (2014-01-24) ** Update according to reference manual rev. 2 ** ENET, MCG, MCM, SIM, USB - registers updated ** - rev. 2.4 (2014-02-10) ** The declaration of clock configurations has been moved to separate header file system_MK64F12.h ** Update of SystemInit() and SystemCoreClockUpdate() functions. ** - rev. 2.5 (2014-02-10) ** The declaration of clock configurations has been moved to separate header file system_MK64F12.h ** Update of SystemInit() and SystemCoreClockUpdate() functions. ** Module access macro module_BASES replaced by module_BASE_PTRS. ** ** ################################################################### */ /* * WARNING! DO NOT EDIT THIS FILE DIRECTLY! * * This file was generated automatically and any changes may be lost. */ #ifndef __HW_FTFE_REGISTERS_H__ #define __HW_FTFE_REGISTERS_H__ #include "MK64F12.h" #include "fsl_bitaccess.h" /* * MK64F12 FTFE * * Flash Memory Interface * * Registers defined in this header file: * - HW_FTFE_FSTAT - Flash Status Register * - HW_FTFE_FCNFG - Flash Configuration Register * - HW_FTFE_FSEC - Flash Security Register * - HW_FTFE_FOPT - Flash Option Register * - HW_FTFE_FCCOB3 - Flash Common Command Object Registers * - HW_FTFE_FCCOB2 - Flash Common Command Object Registers * - HW_FTFE_FCCOB1 - Flash Common Command Object Registers * - HW_FTFE_FCCOB0 - Flash Common Command Object Registers * - HW_FTFE_FCCOB7 - Flash Common Command Object Registers * - HW_FTFE_FCCOB6 - Flash Common Command Object Registers * - HW_FTFE_FCCOB5 - Flash Common Command Object Registers * - HW_FTFE_FCCOB4 - Flash Common Command Object Registers * - HW_FTFE_FCCOBB - Flash Common Command Object Registers * - HW_FTFE_FCCOBA - Flash Common Command Object Registers * - HW_FTFE_FCCOB9 - Flash Common Command Object Registers * - HW_FTFE_FCCOB8 - Flash Common Command Object Registers * - HW_FTFE_FPROT3 - Program Flash Protection Registers * - HW_FTFE_FPROT2 - Program Flash Protection Registers * - HW_FTFE_FPROT1 - Program Flash Protection Registers * - HW_FTFE_FPROT0 - Program Flash Protection Registers * - HW_FTFE_FEPROT - EEPROM Protection Register * - HW_FTFE_FDPROT - Data Flash Protection Register * * - hw_ftfe_t - Struct containing all module registers. */ #define HW_FTFE_INSTANCE_COUNT (1U) /*!< Number of instances of the FTFE module. */ /******************************************************************************* * HW_FTFE_FSTAT - Flash Status Register ******************************************************************************/ /*! * @brief HW_FTFE_FSTAT - Flash Status Register (RW) * * Reset value: 0x00U * * The FSTAT register reports the operational status of the FTFE module. The * CCIF, RDCOLERR, ACCERR, and FPVIOL bits are readable and writable. The MGSTAT0 * bit is read only. The unassigned bits read 0 and are not writable. When set, the * Access Error (ACCERR) and Flash Protection Violation (FPVIOL) bits in this * register prevent the launch of any more commands or writes to the FlexRAM (when * EEERDY is set) until the flag is cleared (by writing a one to it). */ typedef union _hw_ftfe_fstat { uint8_t U; struct _hw_ftfe_fstat_bitfields { uint8_t MGSTAT0 : 1; /*!< [0] Memory Controller Command Completion * Status Flag */ uint8_t RESERVED0 : 3; /*!< [3:1] */ uint8_t FPVIOL : 1; /*!< [4] Flash Protection Violation Flag */ uint8_t ACCERR : 1; /*!< [5] Flash Access Error Flag */ uint8_t RDCOLERR : 1; /*!< [6] FTFE Read Collision Error Flag */ uint8_t CCIF : 1; /*!< [7] Command Complete Interrupt Flag */ } B; } hw_ftfe_fstat_t; /*! * @name Constants and macros for entire FTFE_FSTAT register */ /*@{*/ #define HW_FTFE_FSTAT_ADDR(x) ((x) + 0x0U) #define HW_FTFE_FSTAT(x) (*(__IO hw_ftfe_fstat_t *) HW_FTFE_FSTAT_ADDR(x)) #define HW_FTFE_FSTAT_RD(x) (HW_FTFE_FSTAT(x).U) #define HW_FTFE_FSTAT_WR(x, v) (HW_FTFE_FSTAT(x).U = (v)) #define HW_FTFE_FSTAT_SET(x, v) (HW_FTFE_FSTAT_WR(x, HW_FTFE_FSTAT_RD(x) | (v))) #define HW_FTFE_FSTAT_CLR(x, v) (HW_FTFE_FSTAT_WR(x, HW_FTFE_FSTAT_RD(x) & ~(v))) #define HW_FTFE_FSTAT_TOG(x, v) (HW_FTFE_FSTAT_WR(x, HW_FTFE_FSTAT_RD(x) ^ (v))) /*@}*/ /* * Constants & macros for individual FTFE_FSTAT bitfields */ /*! * @name Register FTFE_FSTAT, field MGSTAT0[0] (RO) * * The MGSTAT0 status flag is set if an error is detected during execution of an * FTFE command or during the flash reset sequence. As a status flag, this bit * cannot (and need not) be cleared by the user like the other error flags in this * register. The value of the MGSTAT0 bit for "command-N" is valid only at the * end of the "command-N" execution when CCIF=1 and before the next command has * been launched. At some point during the execution of "command-N+1," the previous * result is discarded and any previous error is cleared. */ /*@{*/ #define BP_FTFE_FSTAT_MGSTAT0 (0U) /*!< Bit position for FTFE_FSTAT_MGSTAT0. */ #define BM_FTFE_FSTAT_MGSTAT0 (0x01U) /*!< Bit mask for FTFE_FSTAT_MGSTAT0. */ #define BS_FTFE_FSTAT_MGSTAT0 (1U) /*!< Bit field size in bits for FTFE_FSTAT_MGSTAT0. */ /*! @brief Read current value of the FTFE_FSTAT_MGSTAT0 field. */ #define BR_FTFE_FSTAT_MGSTAT0(x) (BITBAND_ACCESS8(HW_FTFE_FSTAT_ADDR(x), BP_FTFE_FSTAT_MGSTAT0)) /*@}*/ /*! * @name Register FTFE_FSTAT, field FPVIOL[4] (W1C) * * The FPVIOL error bit indicates an attempt was made to program or erase an * address in a protected area of program flash or data flash memory during a * command write sequence or a write was attempted to a protected area of the FlexRAM * while enabled for EEPROM. While FPVIOL is set, the CCIF flag cannot be cleared * to launch a command. The FPVIOL bit is cleared by writing a 1 to it. Writing a * 0 to the FPVIOL bit has no effect. * * Values: * - 0 - No protection violation detected * - 1 - Protection violation detected */ /*@{*/ #define BP_FTFE_FSTAT_FPVIOL (4U) /*!< Bit position for FTFE_FSTAT_FPVIOL. */ #define BM_FTFE_FSTAT_FPVIOL (0x10U) /*!< Bit mask for FTFE_FSTAT_FPVIOL. */ #define BS_FTFE_FSTAT_FPVIOL (1U) /*!< Bit field size in bits for FTFE_FSTAT_FPVIOL. */ /*! @brief Read current value of the FTFE_FSTAT_FPVIOL field. */ #define BR_FTFE_FSTAT_FPVIOL(x) (BITBAND_ACCESS8(HW_FTFE_FSTAT_ADDR(x), BP_FTFE_FSTAT_FPVIOL)) /*! @brief Format value for bitfield FTFE_FSTAT_FPVIOL. */ #define BF_FTFE_FSTAT_FPVIOL(v) ((uint8_t)((uint8_t)(v) << BP_FTFE_FSTAT_FPVIOL) & BM_FTFE_FSTAT_FPVIOL) /*! @brief Set the FPVIOL field to a new value. */ #define BW_FTFE_FSTAT_FPVIOL(x, v) (BITBAND_ACCESS8(HW_FTFE_FSTAT_ADDR(x), BP_FTFE_FSTAT_FPVIOL) = (v)) /*@}*/ /*! * @name Register FTFE_FSTAT, field ACCERR[5] (W1C) * * The ACCERR error bit indicates an illegal access has occurred to an FTFE * resource caused by a violation of the command write sequence or issuing an illegal * FTFE command. While ACCERR is set, the CCIF flag cannot be cleared to launch * a command. The ACCERR bit is cleared by writing a 1 to it. Writing a 0 to the * ACCERR bit has no effect. * * Values: * - 0 - No access error detected * - 1 - Access error detected */ /*@{*/ #define BP_FTFE_FSTAT_ACCERR (5U) /*!< Bit position for FTFE_FSTAT_ACCERR. */ #define BM_FTFE_FSTAT_ACCERR (0x20U) /*!< Bit mask for FTFE_FSTAT_ACCERR. */ #define BS_FTFE_FSTAT_ACCERR (1U) /*!< Bit field size in bits for FTFE_FSTAT_ACCERR. */ /*! @brief Read current value of the FTFE_FSTAT_ACCERR field. */ #define BR_FTFE_FSTAT_ACCERR(x) (BITBAND_ACCESS8(HW_FTFE_FSTAT_ADDR(x), BP_FTFE_FSTAT_ACCERR)) /*! @brief Format value for bitfield FTFE_FSTAT_ACCERR. */ #define BF_FTFE_FSTAT_ACCERR(v) ((uint8_t)((uint8_t)(v) << BP_FTFE_FSTAT_ACCERR) & BM_FTFE_FSTAT_ACCERR) /*! @brief Set the ACCERR field to a new value. */ #define BW_FTFE_FSTAT_ACCERR(x, v) (BITBAND_ACCESS8(HW_FTFE_FSTAT_ADDR(x), BP_FTFE_FSTAT_ACCERR) = (v)) /*@}*/ /*! * @name Register FTFE_FSTAT, field RDCOLERR[6] (W1C) * * The RDCOLERR error bit indicates that the MCU attempted a read from an FTFE * resource that was being manipulated by an FTFE command (CCIF=0). Any * simultaneous access is detected as a collision error by the block arbitration logic. The * read data in this case cannot be guaranteed. The RDCOLERR bit is cleared by * writing a 1 to it. Writing a 0 to RDCOLERR has no effect. * * Values: * - 0 - No collision error detected * - 1 - Collision error detected */ /*@{*/ #define BP_FTFE_FSTAT_RDCOLERR (6U) /*!< Bit position for FTFE_FSTAT_RDCOLERR. */ #define BM_FTFE_FSTAT_RDCOLERR (0x40U) /*!< Bit mask for FTFE_FSTAT_RDCOLERR. */ #define BS_FTFE_FSTAT_RDCOLERR (1U) /*!< Bit field size in bits for FTFE_FSTAT_RDCOLERR. */ /*! @brief Read current value of the FTFE_FSTAT_RDCOLERR field. */ #define BR_FTFE_FSTAT_RDCOLERR(x) (BITBAND_ACCESS8(HW_FTFE_FSTAT_ADDR(x), BP_FTFE_FSTAT_RDCOLERR)) /*! @brief Format value for bitfield FTFE_FSTAT_RDCOLERR. */ #define BF_FTFE_FSTAT_RDCOLERR(v) ((uint8_t)((uint8_t)(v) << BP_FTFE_FSTAT_RDCOLERR) & BM_FTFE_FSTAT_RDCOLERR) /*! @brief Set the RDCOLERR field to a new value. */ #define BW_FTFE_FSTAT_RDCOLERR(x, v) (BITBAND_ACCESS8(HW_FTFE_FSTAT_ADDR(x), BP_FTFE_FSTAT_RDCOLERR) = (v)) /*@}*/ /*! * @name Register FTFE_FSTAT, field CCIF[7] (W1C) * * The CCIF flag indicates that a FTFE command or EEPROM file system operation * has completed. The CCIF flag is cleared by writing a 1 to CCIF to launch a * command, and CCIF stays low until command completion or command violation. The * CCIF flag is also cleared by a successful write to FlexRAM while enabled for EEE, * and CCIF stays low until the EEPROM file system has created the associated * EEPROM data record. The CCIF bit is reset to 0 but is set to 1 by the memory * controller at the end of the reset initialization sequence. Depending on how * quickly the read occurs after reset release, the user may or may not see the 0 * hardware reset value. * * Values: * - 0 - FTFE command or EEPROM file system operation in progress * - 1 - FTFE command or EEPROM file system operation has completed */ /*@{*/ #define BP_FTFE_FSTAT_CCIF (7U) /*!< Bit position for FTFE_FSTAT_CCIF. */ #define BM_FTFE_FSTAT_CCIF (0x80U) /*!< Bit mask for FTFE_FSTAT_CCIF. */ #define BS_FTFE_FSTAT_CCIF (1U) /*!< Bit field size in bits for FTFE_FSTAT_CCIF. */ /*! @brief Read current value of the FTFE_FSTAT_CCIF field. */ #define BR_FTFE_FSTAT_CCIF(x) (BITBAND_ACCESS8(HW_FTFE_FSTAT_ADDR(x), BP_FTFE_FSTAT_CCIF)) /*! @brief Format value for bitfield FTFE_FSTAT_CCIF. */ #define BF_FTFE_FSTAT_CCIF(v) ((uint8_t)((uint8_t)(v) << BP_FTFE_FSTAT_CCIF) & BM_FTFE_FSTAT_CCIF) /*! @brief Set the CCIF field to a new value. */ #define BW_FTFE_FSTAT_CCIF(x, v) (BITBAND_ACCESS8(HW_FTFE_FSTAT_ADDR(x), BP_FTFE_FSTAT_CCIF) = (v)) /*@}*/ /******************************************************************************* * HW_FTFE_FCNFG - Flash Configuration Register ******************************************************************************/ /*! * @brief HW_FTFE_FCNFG - Flash Configuration Register (RW) * * Reset value: 0x00U * * This register provides information on the current functional state of the * FTFE module. The erase control bits (ERSAREQ and ERSSUSP) have write * restrictions. SWAP, PFLSH, RAMRDY, and EEERDY are read-only status bits. The unassigned * bits read as noted and are not writable. The reset values for the SWAP, PFLSH, * RAMRDY, and EEERDY bits are determined during the reset sequence. */ typedef union _hw_ftfe_fcnfg { uint8_t U; struct _hw_ftfe_fcnfg_bitfields { uint8_t EEERDY : 1; /*!< [0] */ uint8_t RAMRDY : 1; /*!< [1] RAM Ready */ uint8_t PFLSH : 1; /*!< [2] FTFE configuration */ uint8_t SWAP : 1; /*!< [3] Swap */ uint8_t ERSSUSP : 1; /*!< [4] Erase Suspend */ uint8_t ERSAREQ : 1; /*!< [5] Erase All Request */ uint8_t RDCOLLIE : 1; /*!< [6] Read Collision Error Interrupt Enable * */ uint8_t CCIE : 1; /*!< [7] Command Complete Interrupt Enable */ } B; } hw_ftfe_fcnfg_t; /*! * @name Constants and macros for entire FTFE_FCNFG register */ /*@{*/ #define HW_FTFE_FCNFG_ADDR(x) ((x) + 0x1U) #define HW_FTFE_FCNFG(x) (*(__IO hw_ftfe_fcnfg_t *) HW_FTFE_FCNFG_ADDR(x)) #define HW_FTFE_FCNFG_RD(x) (HW_FTFE_FCNFG(x).U) #define HW_FTFE_FCNFG_WR(x, v) (HW_FTFE_FCNFG(x).U = (v)) #define HW_FTFE_FCNFG_SET(x, v) (HW_FTFE_FCNFG_WR(x, HW_FTFE_FCNFG_RD(x) | (v))) #define HW_FTFE_FCNFG_CLR(x, v) (HW_FTFE_FCNFG_WR(x, HW_FTFE_FCNFG_RD(x) & ~(v))) #define HW_FTFE_FCNFG_TOG(x, v) (HW_FTFE_FCNFG_WR(x, HW_FTFE_FCNFG_RD(x) ^ (v))) /*@}*/ /* * Constants & macros for individual FTFE_FCNFG bitfields */ /*! * @name Register FTFE_FCNFG, field EEERDY[0] (RO) * * For devices with FlexNVM: This flag indicates if the EEPROM backup data has * been copied to the FlexRAM and is therefore available for read access. During * the reset sequence, the EEERDY flag remains clear while CCIF=0 and only sets if * the FlexNVM block is partitioned for EEPROM. For devices without FlexNVM: * This bit is reserved. * * Values: * - 0 - For devices with FlexNVM: FlexRAM is not available for EEPROM operation. * - 1 - For devices with FlexNVM: FlexRAM is available for EEPROM operations * where: reads from the FlexRAM return data previously written to the FlexRAM * in EEPROM mode and writes launch an EEPROM operation to store the written * data in the FlexRAM and EEPROM backup. */ /*@{*/ #define BP_FTFE_FCNFG_EEERDY (0U) /*!< Bit position for FTFE_FCNFG_EEERDY. */ #define BM_FTFE_FCNFG_EEERDY (0x01U) /*!< Bit mask for FTFE_FCNFG_EEERDY. */ #define BS_FTFE_FCNFG_EEERDY (1U) /*!< Bit field size in bits for FTFE_FCNFG_EEERDY. */ /*! @brief Read current value of the FTFE_FCNFG_EEERDY field. */ #define BR_FTFE_FCNFG_EEERDY(x) (BITBAND_ACCESS8(HW_FTFE_FCNFG_ADDR(x), BP_FTFE_FCNFG_EEERDY)) /*@}*/ /*! * @name Register FTFE_FCNFG, field RAMRDY[1] (RO) * * This flag indicates the current status of the FlexRAM/ programming * acceleration RAM. For devices with FlexNVM: The state of the RAMRDY flag is normally * controlled by the Set FlexRAM Function command. During the reset sequence, the * RAMRDY flag is cleared if the FlexNVM block is partitioned for EEPROM and will * be set if the FlexNVM block is not partitioned for EEPROM . The RAMRDY flag is * cleared if the Program Partition command is run to partition the FlexNVM block * for EEPROM. The RAMRDY flag sets after completion of the Erase All Blocks * command or execution of the erase-all operation triggered external to the FTFE. * For devices without FlexNVM: This bit should always be set. * * Values: * - 0 - For devices with FlexNVM: FlexRAM is not available for traditional RAM * access. For devices without FlexNVM: Programming acceleration RAM is not * available. * - 1 - For devices with FlexNVM: FlexRAM is available as traditional RAM only; * writes to the FlexRAM do not trigger EEPROM operations. For devices * without FlexNVM: Programming acceleration RAM is available. */ /*@{*/ #define BP_FTFE_FCNFG_RAMRDY (1U) /*!< Bit position for FTFE_FCNFG_RAMRDY. */ #define BM_FTFE_FCNFG_RAMRDY (0x02U) /*!< Bit mask for FTFE_FCNFG_RAMRDY. */ #define BS_FTFE_FCNFG_RAMRDY (1U) /*!< Bit field size in bits for FTFE_FCNFG_RAMRDY. */ /*! @brief Read current value of the FTFE_FCNFG_RAMRDY field. */ #define BR_FTFE_FCNFG_RAMRDY(x) (BITBAND_ACCESS8(HW_FTFE_FCNFG_ADDR(x), BP_FTFE_FCNFG_RAMRDY)) /*@}*/ /*! * @name Register FTFE_FCNFG, field PFLSH[2] (RO) * * Values: * - 0 - For devices with FlexNVM: FTFE configuration supports two program flash * blocks and two FlexNVM blocks For devices with program flash only: * Reserved * - 1 - For devices with FlexNVM: Reserved For devices with program flash only: * FTFE configuration supports four program flash blocks */ /*@{*/ #define BP_FTFE_FCNFG_PFLSH (2U) /*!< Bit position for FTFE_FCNFG_PFLSH. */ #define BM_FTFE_FCNFG_PFLSH (0x04U) /*!< Bit mask for FTFE_FCNFG_PFLSH. */ #define BS_FTFE_FCNFG_PFLSH (1U) /*!< Bit field size in bits for FTFE_FCNFG_PFLSH. */ /*! @brief Read current value of the FTFE_FCNFG_PFLSH field. */ #define BR_FTFE_FCNFG_PFLSH(x) (BITBAND_ACCESS8(HW_FTFE_FCNFG_ADDR(x), BP_FTFE_FCNFG_PFLSH)) /*@}*/ /*! * @name Register FTFE_FCNFG, field SWAP[3] (RO) * * The SWAP flag indicates which half of the program flash space is located at * relative address 0x0000. The state of the SWAP flag is set by the FTFE during * the reset sequence. See for information on swap management. * * Values: * - 0 - For devices with FlexNVM: Program flash 0 block is located at relative * address 0x0000 For devices with program flash only: Program flash 0 block * is located at relative address 0x0000 * - 1 - For devices with FlexNVM: Reserved For devices with program flash only: * Program flash 1 block is located at relative address 0x0000 */ /*@{*/ #define BP_FTFE_FCNFG_SWAP (3U) /*!< Bit position for FTFE_FCNFG_SWAP. */ #define BM_FTFE_FCNFG_SWAP (0x08U) /*!< Bit mask for FTFE_FCNFG_SWAP. */ #define BS_FTFE_FCNFG_SWAP (1U) /*!< Bit field size in bits for FTFE_FCNFG_SWAP. */ /*! @brief Read current value of the FTFE_FCNFG_SWAP field. */ #define BR_FTFE_FCNFG_SWAP(x) (BITBAND_ACCESS8(HW_FTFE_FCNFG_ADDR(x), BP_FTFE_FCNFG_SWAP)) /*@}*/ /*! * @name Register FTFE_FCNFG, field ERSSUSP[4] (RW) * * The ERSSUSP bit allows the user to suspend (interrupt) the Erase Flash Sector * command while it is executing. * * Values: * - 0 - No suspend requested * - 1 - Suspend the current Erase Flash Sector command execution. */ /*@{*/ #define BP_FTFE_FCNFG_ERSSUSP (4U) /*!< Bit position for FTFE_FCNFG_ERSSUSP. */ #define BM_FTFE_FCNFG_ERSSUSP (0x10U) /*!< Bit mask for FTFE_FCNFG_ERSSUSP. */ #define BS_FTFE_FCNFG_ERSSUSP (1U) /*!< Bit field size in bits for FTFE_FCNFG_ERSSUSP. */ /*! @brief Read current value of the FTFE_FCNFG_ERSSUSP field. */ #define BR_FTFE_FCNFG_ERSSUSP(x) (BITBAND_ACCESS8(HW_FTFE_FCNFG_ADDR(x), BP_FTFE_FCNFG_ERSSUSP)) /*! @brief Format value for bitfield FTFE_FCNFG_ERSSUSP. */ #define BF_FTFE_FCNFG_ERSSUSP(v) ((uint8_t)((uint8_t)(v) << BP_FTFE_FCNFG_ERSSUSP) & BM_FTFE_FCNFG_ERSSUSP) /*! @brief Set the ERSSUSP field to a new value. */ #define BW_FTFE_FCNFG_ERSSUSP(x, v) (BITBAND_ACCESS8(HW_FTFE_FCNFG_ADDR(x), BP_FTFE_FCNFG_ERSSUSP) = (v)) /*@}*/ /*! * @name Register FTFE_FCNFG, field ERSAREQ[5] (RO) * * This bit issues a request to the memory controller to execute the Erase All * Blocks command and release security. ERSAREQ is not directly writable but is * under indirect user control. Refer to the device's Chip Configuration details on * how to request this command. The ERSAREQ bit sets when an erase all request * is triggered external to the FTFE and CCIF is set (no command is currently * being executed). ERSAREQ is cleared by the FTFE when the operation completes. * * Values: * - 0 - No request or request complete * - 1 - Request to: run the Erase All Blocks command, verify the erased state, * program the security byte in the Flash Configuration Field to the unsecure * state, and release MCU security by setting the FSEC[SEC] field to the * unsecure state. */ /*@{*/ #define BP_FTFE_FCNFG_ERSAREQ (5U) /*!< Bit position for FTFE_FCNFG_ERSAREQ. */ #define BM_FTFE_FCNFG_ERSAREQ (0x20U) /*!< Bit mask for FTFE_FCNFG_ERSAREQ. */ #define BS_FTFE_FCNFG_ERSAREQ (1U) /*!< Bit field size in bits for FTFE_FCNFG_ERSAREQ. */ /*! @brief Read current value of the FTFE_FCNFG_ERSAREQ field. */ #define BR_FTFE_FCNFG_ERSAREQ(x) (BITBAND_ACCESS8(HW_FTFE_FCNFG_ADDR(x), BP_FTFE_FCNFG_ERSAREQ)) /*@}*/ /*! * @name Register FTFE_FCNFG, field RDCOLLIE[6] (RW) * * The RDCOLLIE bit controls interrupt generation when an FTFE read collision * error occurs. * * Values: * - 0 - Read collision error interrupt disabled * - 1 - Read collision error interrupt enabled. An interrupt request is * generated whenever an FTFE read collision error is detected (see the description * of FSTAT[RDCOLERR]). */ /*@{*/ #define BP_FTFE_FCNFG_RDCOLLIE (6U) /*!< Bit position for FTFE_FCNFG_RDCOLLIE. */ #define BM_FTFE_FCNFG_RDCOLLIE (0x40U) /*!< Bit mask for FTFE_FCNFG_RDCOLLIE. */ #define BS_FTFE_FCNFG_RDCOLLIE (1U) /*!< Bit field size in bits for FTFE_FCNFG_RDCOLLIE. */ /*! @brief Read current value of the FTFE_FCNFG_RDCOLLIE field. */ #define BR_FTFE_FCNFG_RDCOLLIE(x) (BITBAND_ACCESS8(HW_FTFE_FCNFG_ADDR(x), BP_FTFE_FCNFG_RDCOLLIE)) /*! @brief Format value for bitfield FTFE_FCNFG_RDCOLLIE. */ #define BF_FTFE_FCNFG_RDCOLLIE(v) ((uint8_t)((uint8_t)(v) << BP_FTFE_FCNFG_RDCOLLIE) & BM_FTFE_FCNFG_RDCOLLIE) /*! @brief Set the RDCOLLIE field to a new value. */ #define BW_FTFE_FCNFG_RDCOLLIE(x, v) (BITBAND_ACCESS8(HW_FTFE_FCNFG_ADDR(x), BP_FTFE_FCNFG_RDCOLLIE) = (v)) /*@}*/ /*! * @name Register FTFE_FCNFG, field CCIE[7] (RW) * * The CCIE bit controls interrupt generation when an FTFE command completes. * * Values: * - 0 - Command complete interrupt disabled * - 1 - Command complete interrupt enabled. An interrupt request is generated * whenever the FSTAT[CCIF] flag is set. */ /*@{*/ #define BP_FTFE_FCNFG_CCIE (7U) /*!< Bit position for FTFE_FCNFG_CCIE. */ #define BM_FTFE_FCNFG_CCIE (0x80U) /*!< Bit mask for FTFE_FCNFG_CCIE. */ #define BS_FTFE_FCNFG_CCIE (1U) /*!< Bit field size in bits for FTFE_FCNFG_CCIE. */ /*! @brief Read current value of the FTFE_FCNFG_CCIE field. */ #define BR_FTFE_FCNFG_CCIE(x) (BITBAND_ACCESS8(HW_FTFE_FCNFG_ADDR(x), BP_FTFE_FCNFG_CCIE)) /*! @brief Format value for bitfield FTFE_FCNFG_CCIE. */ #define BF_FTFE_FCNFG_CCIE(v) ((uint8_t)((uint8_t)(v) << BP_FTFE_FCNFG_CCIE) & BM_FTFE_FCNFG_CCIE) /*! @brief Set the CCIE field to a new value. */ #define BW_FTFE_FCNFG_CCIE(x, v) (BITBAND_ACCESS8(HW_FTFE_FCNFG_ADDR(x), BP_FTFE_FCNFG_CCIE) = (v)) /*@}*/ /******************************************************************************* * HW_FTFE_FSEC - Flash Security Register ******************************************************************************/ /*! * @brief HW_FTFE_FSEC - Flash Security Register (RO) * * Reset value: 0x00U * * This read-only register holds all bits associated with the security of the * MCU and FTFE module. During the reset sequence, the register is loaded with the * contents of the flash security byte in the Flash Configuration Field located * in program flash memory. The Flash basis for the values is signified by X in * the reset value. */ typedef union _hw_ftfe_fsec { uint8_t U; struct _hw_ftfe_fsec_bitfields { uint8_t SEC : 2; /*!< [1:0] Flash Security */ uint8_t FSLACC : 2; /*!< [3:2] Freescale Failure Analysis Access Code * */ uint8_t MEEN : 2; /*!< [5:4] Mass Erase Enable Bits */ uint8_t KEYEN : 2; /*!< [7:6] Backdoor Key Security Enable */ } B; } hw_ftfe_fsec_t; /*! * @name Constants and macros for entire FTFE_FSEC register */ /*@{*/ #define HW_FTFE_FSEC_ADDR(x) ((x) + 0x2U) #define HW_FTFE_FSEC(x) (*(__I hw_ftfe_fsec_t *) HW_FTFE_FSEC_ADDR(x)) #define HW_FTFE_FSEC_RD(x) (HW_FTFE_FSEC(x).U) /*@}*/ /* * Constants & macros for individual FTFE_FSEC bitfields */ /*! * @name Register FTFE_FSEC, field SEC[1:0] (RO) * * These bits define the security state of the MCU. In the secure state, the MCU * limits access to FTFE module resources. The limitations are defined per * device and are detailed in the Chip Configuration details. If the FTFE module is * unsecured using backdoor key access, the SEC bits are forced to 10b. * * Values: * - 00 - MCU security status is secure * - 01 - MCU security status is secure * - 10 - MCU security status is unsecure (The standard shipping condition of * the FTFE is unsecure.) * - 11 - MCU security status is secure */ /*@{*/ #define BP_FTFE_FSEC_SEC (0U) /*!< Bit position for FTFE_FSEC_SEC. */ #define BM_FTFE_FSEC_SEC (0x03U) /*!< Bit mask for FTFE_FSEC_SEC. */ #define BS_FTFE_FSEC_SEC (2U) /*!< Bit field size in bits for FTFE_FSEC_SEC. */ /*! @brief Read current value of the FTFE_FSEC_SEC field. */ #define BR_FTFE_FSEC_SEC(x) (HW_FTFE_FSEC(x).B.SEC) /*@}*/ /*! * @name Register FTFE_FSEC, field FSLACC[3:2] (RO) * * These bits enable or disable access to the flash memory contents during * returned part failure analysis at Freescale. When SEC is secure and FSLACC is * denied, access to the program flash contents is denied and any failure analysis * performed by Freescale factory test must begin with a full erase to unsecure the * part. When access is granted (SEC is unsecure, or SEC is secure and FSLACC is * granted), Freescale factory testing has visibility of the current flash * contents. The state of the FSLACC bits is only relevant when the SEC bits are set to * secure. When the SEC field is set to unsecure, the FSLACC setting does not * matter. * * Values: * - 00 - Freescale factory access granted * - 01 - Freescale factory access denied * - 10 - Freescale factory access denied * - 11 - Freescale factory access granted */ /*@{*/ #define BP_FTFE_FSEC_FSLACC (2U) /*!< Bit position for FTFE_FSEC_FSLACC. */ #define BM_FTFE_FSEC_FSLACC (0x0CU) /*!< Bit mask for FTFE_FSEC_FSLACC. */ #define BS_FTFE_FSEC_FSLACC (2U) /*!< Bit field size in bits for FTFE_FSEC_FSLACC. */ /*! @brief Read current value of the FTFE_FSEC_FSLACC field. */ #define BR_FTFE_FSEC_FSLACC(x) (HW_FTFE_FSEC(x).B.FSLACC) /*@}*/ /*! * @name Register FTFE_FSEC, field MEEN[5:4] (RO) * * Enables and disables mass erase capability of the FTFE module. The state of * the MEEN bits is only relevant when the SEC bits are set to secure outside of * NVM Normal Mode. When the SEC field is set to unsecure, the MEEN setting does * not matter. * * Values: * - 00 - Mass erase is enabled * - 01 - Mass erase is enabled * - 10 - Mass erase is disabled * - 11 - Mass erase is enabled */ /*@{*/ #define BP_FTFE_FSEC_MEEN (4U) /*!< Bit position for FTFE_FSEC_MEEN. */ #define BM_FTFE_FSEC_MEEN (0x30U) /*!< Bit mask for FTFE_FSEC_MEEN. */ #define BS_FTFE_FSEC_MEEN (2U) /*!< Bit field size in bits for FTFE_FSEC_MEEN. */ /*! @brief Read current value of the FTFE_FSEC_MEEN field. */ #define BR_FTFE_FSEC_MEEN(x) (HW_FTFE_FSEC(x).B.MEEN) /*@}*/ /*! * @name Register FTFE_FSEC, field KEYEN[7:6] (RO) * * These bits enable and disable backdoor key access to the FTFE module. * * Values: * - 00 - Backdoor key access disabled * - 01 - Backdoor key access disabled (preferred KEYEN state to disable * backdoor key access) * - 10 - Backdoor key access enabled * - 11 - Backdoor key access disabled */ /*@{*/ #define BP_FTFE_FSEC_KEYEN (6U) /*!< Bit position for FTFE_FSEC_KEYEN. */ #define BM_FTFE_FSEC_KEYEN (0xC0U) /*!< Bit mask for FTFE_FSEC_KEYEN. */ #define BS_FTFE_FSEC_KEYEN (2U) /*!< Bit field size in bits for FTFE_FSEC_KEYEN. */ /*! @brief Read current value of the FTFE_FSEC_KEYEN field. */ #define BR_FTFE_FSEC_KEYEN(x) (HW_FTFE_FSEC(x).B.KEYEN) /*@}*/ /******************************************************************************* * HW_FTFE_FOPT - Flash Option Register ******************************************************************************/ /*! * @brief HW_FTFE_FOPT - Flash Option Register (RO) * * Reset value: 0x00U * * The flash option register allows the MCU to customize its operations by * examining the state of these read-only bits, which are loaded from NVM at reset. * The function of the bits is defined in the device's Chip Configuration details. * All bits in the register are read-only. During the reset sequence, the * register is loaded from the flash nonvolatile option byte in the Flash Configuration * Field located in program flash memory. The flash basis for the values is * signified by X in the reset value. */ typedef union _hw_ftfe_fopt { uint8_t U; struct _hw_ftfe_fopt_bitfields { uint8_t OPT : 8; /*!< [7:0] Nonvolatile Option */ } B; } hw_ftfe_fopt_t; /*! * @name Constants and macros for entire FTFE_FOPT register */ /*@{*/ #define HW_FTFE_FOPT_ADDR(x) ((x) + 0x3U) #define HW_FTFE_FOPT(x) (*(__I hw_ftfe_fopt_t *) HW_FTFE_FOPT_ADDR(x)) #define HW_FTFE_FOPT_RD(x) (HW_FTFE_FOPT(x).U) /*@}*/ /* * Constants & macros for individual FTFE_FOPT bitfields */ /*! * @name Register FTFE_FOPT, field OPT[7:0] (RO) * * These bits are loaded from flash to this register at reset. Refer to the * device's Chip Configuration details for the definition and use of these bits. */ /*@{*/ #define BP_FTFE_FOPT_OPT (0U) /*!< Bit position for FTFE_FOPT_OPT. */ #define BM_FTFE_FOPT_OPT (0xFFU) /*!< Bit mask for FTFE_FOPT_OPT. */ #define BS_FTFE_FOPT_OPT (8U) /*!< Bit field size in bits for FTFE_FOPT_OPT. */ /*! @brief Read current value of the FTFE_FOPT_OPT field. */ #define BR_FTFE_FOPT_OPT(x) (HW_FTFE_FOPT(x).U) /*@}*/ /******************************************************************************* * HW_FTFE_FCCOB3 - Flash Common Command Object Registers ******************************************************************************/ /*! * @brief HW_FTFE_FCCOB3 - Flash Common Command Object Registers (RW) * * Reset value: 0x00U * * The FCCOB register group provides 12 bytes for command codes and parameters. * The individual bytes within the set append a 0-B hex identifier to the FCCOB * register name: FCCOB0, FCCOB1, ..., FCCOBB. */ typedef union _hw_ftfe_fccob3 { uint8_t U; struct _hw_ftfe_fccob3_bitfields { uint8_t CCOBn : 8; /*!< [7:0] */ } B; } hw_ftfe_fccob3_t; /*! * @name Constants and macros for entire FTFE_FCCOB3 register */ /*@{*/ #define HW_FTFE_FCCOB3_ADDR(x) ((x) + 0x4U) #define HW_FTFE_FCCOB3(x) (*(__IO hw_ftfe_fccob3_t *) HW_FTFE_FCCOB3_ADDR(x)) #define HW_FTFE_FCCOB3_RD(x) (HW_FTFE_FCCOB3(x).U) #define HW_FTFE_FCCOB3_WR(x, v) (HW_FTFE_FCCOB3(x).U = (v)) #define HW_FTFE_FCCOB3_SET(x, v) (HW_FTFE_FCCOB3_WR(x, HW_FTFE_FCCOB3_RD(x) | (v))) #define HW_FTFE_FCCOB3_CLR(x, v) (HW_FTFE_FCCOB3_WR(x, HW_FTFE_FCCOB3_RD(x) & ~(v))) #define HW_FTFE_FCCOB3_TOG(x, v) (HW_FTFE_FCCOB3_WR(x, HW_FTFE_FCCOB3_RD(x) ^ (v))) /*@}*/ /* * Constants & macros for individual FTFE_FCCOB3 bitfields */ /*! * @name Register FTFE_FCCOB3, field CCOBn[7:0] (RW) * * The FCCOB register provides a command code and relevant parameters to the * memory controller. The individual registers that compose the FCCOB data set can * be written in any order, but you must provide all needed values, which vary * from command to command. First, set up all required FCCOB fields and then * initiate the command's execution by writing a 1 to the FSTAT[CCIF] bit. This clears * the CCIF bit, which locks all FCCOB parameter fields and they cannot be changed * by the user until the command completes (CCIF returns to 1). No command * buffering or queueing is provided; the next command can be loaded only after the * current command completes. Some commands return information to the FCCOB * registers. Any values returned to FCCOB are available for reading after the * FSTAT[CCIF] flag returns to 1 by the memory controller. The following table shows a * generic FTFE command format. The first FCCOB register, FCCOB0, always contains * the command code. This 8-bit value defines the command to be executed. The * command code is followed by the parameters required for this specific FTFE command, * typically an address and/or data values. The command parameter table is * written in terms of FCCOB Number (which is equivalent to the byte number). This * number is a reference to the FCCOB register name and is not the register address. * FCCOB NumberRefers to FCCOB register name, not register address Typical * Command Parameter Contents [7:0] 0 FCMD (a code that defines the FTFE command) 1 * Flash address [23:16] 2 Flash address [15:8] 3 Flash address [7:0] 4 Data Byte 0 * 5 Data Byte 1 6 Data Byte 2 7 Data Byte 3 8 Data Byte 4 9 Data Byte 5 A Data * Byte 6 B Data Byte 7 FCCOB Endianness and Multi-Byte Access: The FCCOB * register group uses a big endian addressing convention. For all command parameter * fields larger than 1 byte, the most significant data resides in the lowest FCCOB * register number. The FCCOB register group may be read and written as * individual bytes, aligned words (2 bytes) or aligned longwords (4 bytes). */ /*@{*/ #define BP_FTFE_FCCOB3_CCOBn (0U) /*!< Bit position for FTFE_FCCOB3_CCOBn. */ #define BM_FTFE_FCCOB3_CCOBn (0xFFU) /*!< Bit mask for FTFE_FCCOB3_CCOBn. */ #define BS_FTFE_FCCOB3_CCOBn (8U) /*!< Bit field size in bits for FTFE_FCCOB3_CCOBn. */ /*! @brief Read current value of the FTFE_FCCOB3_CCOBn field. */ #define BR_FTFE_FCCOB3_CCOBn(x) (HW_FTFE_FCCOB3(x).U) /*! @brief Format value for bitfield FTFE_FCCOB3_CCOBn. */ #define BF_FTFE_FCCOB3_CCOBn(v) ((uint8_t)((uint8_t)(v) << BP_FTFE_FCCOB3_CCOBn) & BM_FTFE_FCCOB3_CCOBn) /*! @brief Set the CCOBn field to a new value. */ #define BW_FTFE_FCCOB3_CCOBn(x, v) (HW_FTFE_FCCOB3_WR(x, v)) /*@}*/ /******************************************************************************* * HW_FTFE_FCCOB2 - Flash Common Command Object Registers ******************************************************************************/ /*! * @brief HW_FTFE_FCCOB2 - Flash Common Command Object Registers (RW) * * Reset value: 0x00U * * The FCCOB register group provides 12 bytes for command codes and parameters. * The individual bytes within the set append a 0-B hex identifier to the FCCOB * register name: FCCOB0, FCCOB1, ..., FCCOBB. */ typedef union _hw_ftfe_fccob2 { uint8_t U; struct _hw_ftfe_fccob2_bitfields { uint8_t CCOBn : 8; /*!< [7:0] */ } B; } hw_ftfe_fccob2_t; /*! * @name Constants and macros for entire FTFE_FCCOB2 register */ /*@{*/ #define HW_FTFE_FCCOB2_ADDR(x) ((x) + 0x5U) #define HW_FTFE_FCCOB2(x) (*(__IO hw_ftfe_fccob2_t *) HW_FTFE_FCCOB2_ADDR(x)) #define HW_FTFE_FCCOB2_RD(x) (HW_FTFE_FCCOB2(x).U) #define HW_FTFE_FCCOB2_WR(x, v) (HW_FTFE_FCCOB2(x).U = (v)) #define HW_FTFE_FCCOB2_SET(x, v) (HW_FTFE_FCCOB2_WR(x, HW_FTFE_FCCOB2_RD(x) | (v))) #define HW_FTFE_FCCOB2_CLR(x, v) (HW_FTFE_FCCOB2_WR(x, HW_FTFE_FCCOB2_RD(x) & ~(v))) #define HW_FTFE_FCCOB2_TOG(x, v) (HW_FTFE_FCCOB2_WR(x, HW_FTFE_FCCOB2_RD(x) ^ (v))) /*@}*/ /* * Constants & macros for individual FTFE_FCCOB2 bitfields */ /*! * @name Register FTFE_FCCOB2, field CCOBn[7:0] (RW) * * The FCCOB register provides a command code and relevant parameters to the * memory controller. The individual registers that compose the FCCOB data set can * be written in any order, but you must provide all needed values, which vary * from command to command. First, set up all required FCCOB fields and then * initiate the command's execution by writing a 1 to the FSTAT[CCIF] bit. This clears * the CCIF bit, which locks all FCCOB parameter fields and they cannot be changed * by the user until the command completes (CCIF returns to 1). No command * buffering or queueing is provided; the next command can be loaded only after the * current command completes. Some commands return information to the FCCOB * registers. Any values returned to FCCOB are available for reading after the * FSTAT[CCIF] flag returns to 1 by the memory controller. The following table shows a * generic FTFE command format. The first FCCOB register, FCCOB0, always contains * the command code. This 8-bit value defines the command to be executed. The * command code is followed by the parameters required for this specific FTFE command, * typically an address and/or data values. The command parameter table is * written in terms of FCCOB Number (which is equivalent to the byte number). This * number is a reference to the FCCOB register name and is not the register address. * FCCOB NumberRefers to FCCOB register name, not register address Typical * Command Parameter Contents [7:0] 0 FCMD (a code that defines the FTFE command) 1 * Flash address [23:16] 2 Flash address [15:8] 3 Flash address [7:0] 4 Data Byte 0 * 5 Data Byte 1 6 Data Byte 2 7 Data Byte 3 8 Data Byte 4 9 Data Byte 5 A Data * Byte 6 B Data Byte 7 FCCOB Endianness and Multi-Byte Access: The FCCOB * register group uses a big endian addressing convention. For all command parameter * fields larger than 1 byte, the most significant data resides in the lowest FCCOB * register number. The FCCOB register group may be read and written as * individual bytes, aligned words (2 bytes) or aligned longwords (4 bytes). */ /*@{*/ #define BP_FTFE_FCCOB2_CCOBn (0U) /*!< Bit position for FTFE_FCCOB2_CCOBn. */ #define BM_FTFE_FCCOB2_CCOBn (0xFFU) /*!< Bit mask for FTFE_FCCOB2_CCOBn. */ #define BS_FTFE_FCCOB2_CCOBn (8U) /*!< Bit field size in bits for FTFE_FCCOB2_CCOBn. */ /*! @brief Read current value of the FTFE_FCCOB2_CCOBn field. */ #define BR_FTFE_FCCOB2_CCOBn(x) (HW_FTFE_FCCOB2(x).U) /*! @brief Format value for bitfield FTFE_FCCOB2_CCOBn. */ #define BF_FTFE_FCCOB2_CCOBn(v) ((uint8_t)((uint8_t)(v) << BP_FTFE_FCCOB2_CCOBn) & BM_FTFE_FCCOB2_CCOBn) /*! @brief Set the CCOBn field to a new value. */ #define BW_FTFE_FCCOB2_CCOBn(x, v) (HW_FTFE_FCCOB2_WR(x, v)) /*@}*/ /******************************************************************************* * HW_FTFE_FCCOB1 - Flash Common Command Object Registers ******************************************************************************/ /*! * @brief HW_FTFE_FCCOB1 - Flash Common Command Object Registers (RW) * * Reset value: 0x00U * * The FCCOB register group provides 12 bytes for command codes and parameters. * The individual bytes within the set append a 0-B hex identifier to the FCCOB * register name: FCCOB0, FCCOB1, ..., FCCOBB. */ typedef union _hw_ftfe_fccob1 { uint8_t U; struct _hw_ftfe_fccob1_bitfields { uint8_t CCOBn : 8; /*!< [7:0] */ } B; } hw_ftfe_fccob1_t; /*! * @name Constants and macros for entire FTFE_FCCOB1 register */ /*@{*/ #define HW_FTFE_FCCOB1_ADDR(x) ((x) + 0x6U) #define HW_FTFE_FCCOB1(x) (*(__IO hw_ftfe_fccob1_t *) HW_FTFE_FCCOB1_ADDR(x)) #define HW_FTFE_FCCOB1_RD(x) (HW_FTFE_FCCOB1(x).U) #define HW_FTFE_FCCOB1_WR(x, v) (HW_FTFE_FCCOB1(x).U = (v)) #define HW_FTFE_FCCOB1_SET(x, v) (HW_FTFE_FCCOB1_WR(x, HW_FTFE_FCCOB1_RD(x) | (v))) #define HW_FTFE_FCCOB1_CLR(x, v) (HW_FTFE_FCCOB1_WR(x, HW_FTFE_FCCOB1_RD(x) & ~(v))) #define HW_FTFE_FCCOB1_TOG(x, v) (HW_FTFE_FCCOB1_WR(x, HW_FTFE_FCCOB1_RD(x) ^ (v))) /*@}*/ /* * Constants & macros for individual FTFE_FCCOB1 bitfields */ /*! * @name Register FTFE_FCCOB1, field CCOBn[7:0] (RW) * * The FCCOB register provides a command code and relevant parameters to the * memory controller. The individual registers that compose the FCCOB data set can * be written in any order, but you must provide all needed values, which vary * from command to command. First, set up all required FCCOB fields and then * initiate the command's execution by writing a 1 to the FSTAT[CCIF] bit. This clears * the CCIF bit, which locks all FCCOB parameter fields and they cannot be changed * by the user until the command completes (CCIF returns to 1). No command * buffering or queueing is provided; the next command can be loaded only after the * current command completes. Some commands return information to the FCCOB * registers. Any values returned to FCCOB are available for reading after the * FSTAT[CCIF] flag returns to 1 by the memory controller. The following table shows a * generic FTFE command format. The first FCCOB register, FCCOB0, always contains * the command code. This 8-bit value defines the command to be executed. The * command code is followed by the parameters required for this specific FTFE command, * typically an address and/or data values. The command parameter table is * written in terms of FCCOB Number (which is equivalent to the byte number). This * number is a reference to the FCCOB register name and is not the register address. * FCCOB NumberRefers to FCCOB register name, not register address Typical * Command Parameter Contents [7:0] 0 FCMD (a code that defines the FTFE command) 1 * Flash address [23:16] 2 Flash address [15:8] 3 Flash address [7:0] 4 Data Byte 0 * 5 Data Byte 1 6 Data Byte 2 7 Data Byte 3 8 Data Byte 4 9 Data Byte 5 A Data * Byte 6 B Data Byte 7 FCCOB Endianness and Multi-Byte Access: The FCCOB * register group uses a big endian addressing convention. For all command parameter * fields larger than 1 byte, the most significant data resides in the lowest FCCOB * register number. The FCCOB register group may be read and written as * individual bytes, aligned words (2 bytes) or aligned longwords (4 bytes). */ /*@{*/ #define BP_FTFE_FCCOB1_CCOBn (0U) /*!< Bit position for FTFE_FCCOB1_CCOBn. */ #define BM_FTFE_FCCOB1_CCOBn (0xFFU) /*!< Bit mask for FTFE_FCCOB1_CCOBn. */ #define BS_FTFE_FCCOB1_CCOBn (8U) /*!< Bit field size in bits for FTFE_FCCOB1_CCOBn. */ /*! @brief Read current value of the FTFE_FCCOB1_CCOBn field. */ #define BR_FTFE_FCCOB1_CCOBn(x) (HW_FTFE_FCCOB1(x).U) /*! @brief Format value for bitfield FTFE_FCCOB1_CCOBn. */ #define BF_FTFE_FCCOB1_CCOBn(v) ((uint8_t)((uint8_t)(v) << BP_FTFE_FCCOB1_CCOBn) & BM_FTFE_FCCOB1_CCOBn) /*! @brief Set the CCOBn field to a new value. */ #define BW_FTFE_FCCOB1_CCOBn(x, v) (HW_FTFE_FCCOB1_WR(x, v)) /*@}*/ /******************************************************************************* * HW_FTFE_FCCOB0 - Flash Common Command Object Registers ******************************************************************************/ /*! * @brief HW_FTFE_FCCOB0 - Flash Common Command Object Registers (RW) * * Reset value: 0x00U * * The FCCOB register group provides 12 bytes for command codes and parameters. * The individual bytes within the set append a 0-B hex identifier to the FCCOB * register name: FCCOB0, FCCOB1, ..., FCCOBB. */ typedef union _hw_ftfe_fccob0 { uint8_t U; struct _hw_ftfe_fccob0_bitfields { uint8_t CCOBn : 8; /*!< [7:0] */ } B; } hw_ftfe_fccob0_t; /*! * @name Constants and macros for entire FTFE_FCCOB0 register */ /*@{*/ #define HW_FTFE_FCCOB0_ADDR(x) ((x) + 0x7U) #define HW_FTFE_FCCOB0(x) (*(__IO hw_ftfe_fccob0_t *) HW_FTFE_FCCOB0_ADDR(x)) #define HW_FTFE_FCCOB0_RD(x) (HW_FTFE_FCCOB0(x).U) #define HW_FTFE_FCCOB0_WR(x, v) (HW_FTFE_FCCOB0(x).U = (v)) #define HW_FTFE_FCCOB0_SET(x, v) (HW_FTFE_FCCOB0_WR(x, HW_FTFE_FCCOB0_RD(x) | (v))) #define HW_FTFE_FCCOB0_CLR(x, v) (HW_FTFE_FCCOB0_WR(x, HW_FTFE_FCCOB0_RD(x) & ~(v))) #define HW_FTFE_FCCOB0_TOG(x, v) (HW_FTFE_FCCOB0_WR(x, HW_FTFE_FCCOB0_RD(x) ^ (v))) /*@}*/ /* * Constants & macros for individual FTFE_FCCOB0 bitfields */ /*! * @name Register FTFE_FCCOB0, field CCOBn[7:0] (RW) * * The FCCOB register provides a command code and relevant parameters to the * memory controller. The individual registers that compose the FCCOB data set can * be written in any order, but you must provide all needed values, which vary * from command to command. First, set up all required FCCOB fields and then * initiate the command's execution by writing a 1 to the FSTAT[CCIF] bit. This clears * the CCIF bit, which locks all FCCOB parameter fields and they cannot be changed * by the user until the command completes (CCIF returns to 1). No command * buffering or queueing is provided; the next command can be loaded only after the * current command completes. Some commands return information to the FCCOB * registers. Any values returned to FCCOB are available for reading after the * FSTAT[CCIF] flag returns to 1 by the memory controller. The following table shows a * generic FTFE command format. The first FCCOB register, FCCOB0, always contains * the command code. This 8-bit value defines the command to be executed. The * command code is followed by the parameters required for this specific FTFE command, * typically an address and/or data values. The command parameter table is * written in terms of FCCOB Number (which is equivalent to the byte number). This * number is a reference to the FCCOB register name and is not the register address. * FCCOB NumberRefers to FCCOB register name, not register address Typical * Command Parameter Contents [7:0] 0 FCMD (a code that defines the FTFE command) 1 * Flash address [23:16] 2 Flash address [15:8] 3 Flash address [7:0] 4 Data Byte 0 * 5 Data Byte 1 6 Data Byte 2 7 Data Byte 3 8 Data Byte 4 9 Data Byte 5 A Data * Byte 6 B Data Byte 7 FCCOB Endianness and Multi-Byte Access: The FCCOB * register group uses a big endian addressing convention. For all command parameter * fields larger than 1 byte, the most significant data resides in the lowest FCCOB * register number. The FCCOB register group may be read and written as * individual bytes, aligned words (2 bytes) or aligned longwords (4 bytes). */ /*@{*/ #define BP_FTFE_FCCOB0_CCOBn (0U) /*!< Bit position for FTFE_FCCOB0_CCOBn. */ #define BM_FTFE_FCCOB0_CCOBn (0xFFU) /*!< Bit mask for FTFE_FCCOB0_CCOBn. */ #define BS_FTFE_FCCOB0_CCOBn (8U) /*!< Bit field size in bits for FTFE_FCCOB0_CCOBn. */ /*! @brief Read current value of the FTFE_FCCOB0_CCOBn field. */ #define BR_FTFE_FCCOB0_CCOBn(x) (HW_FTFE_FCCOB0(x).U) /*! @brief Format value for bitfield FTFE_FCCOB0_CCOBn. */ #define BF_FTFE_FCCOB0_CCOBn(v) ((uint8_t)((uint8_t)(v) << BP_FTFE_FCCOB0_CCOBn) & BM_FTFE_FCCOB0_CCOBn) /*! @brief Set the CCOBn field to a new value. */ #define BW_FTFE_FCCOB0_CCOBn(x, v) (HW_FTFE_FCCOB0_WR(x, v)) /*@}*/ /******************************************************************************* * HW_FTFE_FCCOB7 - Flash Common Command Object Registers ******************************************************************************/ /*! * @brief HW_FTFE_FCCOB7 - Flash Common Command Object Registers (RW) * * Reset value: 0x00U * * The FCCOB register group provides 12 bytes for command codes and parameters. * The individual bytes within the set append a 0-B hex identifier to the FCCOB * register name: FCCOB0, FCCOB1, ..., FCCOBB. */ typedef union _hw_ftfe_fccob7 { uint8_t U; struct _hw_ftfe_fccob7_bitfields { uint8_t CCOBn : 8; /*!< [7:0] */ } B; } hw_ftfe_fccob7_t; /*! * @name Constants and macros for entire FTFE_FCCOB7 register */ /*@{*/ #define HW_FTFE_FCCOB7_ADDR(x) ((x) + 0x8U) #define HW_FTFE_FCCOB7(x) (*(__IO hw_ftfe_fccob7_t *) HW_FTFE_FCCOB7_ADDR(x)) #define HW_FTFE_FCCOB7_RD(x) (HW_FTFE_FCCOB7(x).U) #define HW_FTFE_FCCOB7_WR(x, v) (HW_FTFE_FCCOB7(x).U = (v)) #define HW_FTFE_FCCOB7_SET(x, v) (HW_FTFE_FCCOB7_WR(x, HW_FTFE_FCCOB7_RD(x) | (v))) #define HW_FTFE_FCCOB7_CLR(x, v) (HW_FTFE_FCCOB7_WR(x, HW_FTFE_FCCOB7_RD(x) & ~(v))) #define HW_FTFE_FCCOB7_TOG(x, v) (HW_FTFE_FCCOB7_WR(x, HW_FTFE_FCCOB7_RD(x) ^ (v))) /*@}*/ /* * Constants & macros for individual FTFE_FCCOB7 bitfields */ /*! * @name Register FTFE_FCCOB7, field CCOBn[7:0] (RW) * * The FCCOB register provides a command code and relevant parameters to the * memory controller. The individual registers that compose the FCCOB data set can * be written in any order, but you must provide all needed values, which vary * from command to command. First, set up all required FCCOB fields and then * initiate the command's execution by writing a 1 to the FSTAT[CCIF] bit. This clears * the CCIF bit, which locks all FCCOB parameter fields and they cannot be changed * by the user until the command completes (CCIF returns to 1). No command * buffering or queueing is provided; the next command can be loaded only after the * current command completes. Some commands return information to the FCCOB * registers. Any values returned to FCCOB are available for reading after the * FSTAT[CCIF] flag returns to 1 by the memory controller. The following table shows a * generic FTFE command format. The first FCCOB register, FCCOB0, always contains * the command code. This 8-bit value defines the command to be executed. The * command code is followed by the parameters required for this specific FTFE command, * typically an address and/or data values. The command parameter table is * written in terms of FCCOB Number (which is equivalent to the byte number). This * number is a reference to the FCCOB register name and is not the register address. * FCCOB NumberRefers to FCCOB register name, not register address Typical * Command Parameter Contents [7:0] 0 FCMD (a code that defines the FTFE command) 1 * Flash address [23:16] 2 Flash address [15:8] 3 Flash address [7:0] 4 Data Byte 0 * 5 Data Byte 1 6 Data Byte 2 7 Data Byte 3 8 Data Byte 4 9 Data Byte 5 A Data * Byte 6 B Data Byte 7 FCCOB Endianness and Multi-Byte Access: The FCCOB * register group uses a big endian addressing convention. For all command parameter * fields larger than 1 byte, the most significant data resides in the lowest FCCOB * register number. The FCCOB register group may be read and written as * individual bytes, aligned words (2 bytes) or aligned longwords (4 bytes). */ /*@{*/ #define BP_FTFE_FCCOB7_CCOBn (0U) /*!< Bit position for FTFE_FCCOB7_CCOBn. */ #define BM_FTFE_FCCOB7_CCOBn (0xFFU) /*!< Bit mask for FTFE_FCCOB7_CCOBn. */ #define BS_FTFE_FCCOB7_CCOBn (8U) /*!< Bit field size in bits for FTFE_FCCOB7_CCOBn. */ /*! @brief Read current value of the FTFE_FCCOB7_CCOBn field. */ #define BR_FTFE_FCCOB7_CCOBn(x) (HW_FTFE_FCCOB7(x).U) /*! @brief Format value for bitfield FTFE_FCCOB7_CCOBn. */ #define BF_FTFE_FCCOB7_CCOBn(v) ((uint8_t)((uint8_t)(v) << BP_FTFE_FCCOB7_CCOBn) & BM_FTFE_FCCOB7_CCOBn) /*! @brief Set the CCOBn field to a new value. */ #define BW_FTFE_FCCOB7_CCOBn(x, v) (HW_FTFE_FCCOB7_WR(x, v)) /*@}*/ /******************************************************************************* * HW_FTFE_FCCOB6 - Flash Common Command Object Registers ******************************************************************************/ /*! * @brief HW_FTFE_FCCOB6 - Flash Common Command Object Registers (RW) * * Reset value: 0x00U * * The FCCOB register group provides 12 bytes for command codes and parameters. * The individual bytes within the set append a 0-B hex identifier to the FCCOB * register name: FCCOB0, FCCOB1, ..., FCCOBB. */ typedef union _hw_ftfe_fccob6 { uint8_t U; struct _hw_ftfe_fccob6_bitfields { uint8_t CCOBn : 8; /*!< [7:0] */ } B; } hw_ftfe_fccob6_t; /*! * @name Constants and macros for entire FTFE_FCCOB6 register */ /*@{*/ #define HW_FTFE_FCCOB6_ADDR(x) ((x) + 0x9U) #define HW_FTFE_FCCOB6(x) (*(__IO hw_ftfe_fccob6_t *) HW_FTFE_FCCOB6_ADDR(x)) #define HW_FTFE_FCCOB6_RD(x) (HW_FTFE_FCCOB6(x).U) #define HW_FTFE_FCCOB6_WR(x, v) (HW_FTFE_FCCOB6(x).U = (v)) #define HW_FTFE_FCCOB6_SET(x, v) (HW_FTFE_FCCOB6_WR(x, HW_FTFE_FCCOB6_RD(x) | (v))) #define HW_FTFE_FCCOB6_CLR(x, v) (HW_FTFE_FCCOB6_WR(x, HW_FTFE_FCCOB6_RD(x) & ~(v))) #define HW_FTFE_FCCOB6_TOG(x, v) (HW_FTFE_FCCOB6_WR(x, HW_FTFE_FCCOB6_RD(x) ^ (v))) /*@}*/ /* * Constants & macros for individual FTFE_FCCOB6 bitfields */ /*! * @name Register FTFE_FCCOB6, field CCOBn[7:0] (RW) * * The FCCOB register provides a command code and relevant parameters to the * memory controller. The individual registers that compose the FCCOB data set can * be written in any order, but you must provide all needed values, which vary * from command to command. First, set up all required FCCOB fields and then * initiate the command's execution by writing a 1 to the FSTAT[CCIF] bit. This clears * the CCIF bit, which locks all FCCOB parameter fields and they cannot be changed * by the user until the command completes (CCIF returns to 1). No command * buffering or queueing is provided; the next command can be loaded only after the * current command completes. Some commands return information to the FCCOB * registers. Any values returned to FCCOB are available for reading after the * FSTAT[CCIF] flag returns to 1 by the memory controller. The following table shows a * generic FTFE command format. The first FCCOB register, FCCOB0, always contains * the command code. This 8-bit value defines the command to be executed. The * command code is followed by the parameters required for this specific FTFE command, * typically an address and/or data values. The command parameter table is * written in terms of FCCOB Number (which is equivalent to the byte number). This * number is a reference to the FCCOB register name and is not the register address. * FCCOB NumberRefers to FCCOB register name, not register address Typical * Command Parameter Contents [7:0] 0 FCMD (a code that defines the FTFE command) 1 * Flash address [23:16] 2 Flash address [15:8] 3 Flash address [7:0] 4 Data Byte 0 * 5 Data Byte 1 6 Data Byte 2 7 Data Byte 3 8 Data Byte 4 9 Data Byte 5 A Data * Byte 6 B Data Byte 7 FCCOB Endianness and Multi-Byte Access: The FCCOB * register group uses a big endian addressing convention. For all command parameter * fields larger than 1 byte, the most significant data resides in the lowest FCCOB * register number. The FCCOB register group may be read and written as * individual bytes, aligned words (2 bytes) or aligned longwords (4 bytes). */ /*@{*/ #define BP_FTFE_FCCOB6_CCOBn (0U) /*!< Bit position for FTFE_FCCOB6_CCOBn. */ #define BM_FTFE_FCCOB6_CCOBn (0xFFU) /*!< Bit mask for FTFE_FCCOB6_CCOBn. */ #define BS_FTFE_FCCOB6_CCOBn (8U) /*!< Bit field size in bits for FTFE_FCCOB6_CCOBn. */ /*! @brief Read current value of the FTFE_FCCOB6_CCOBn field. */ #define BR_FTFE_FCCOB6_CCOBn(x) (HW_FTFE_FCCOB6(x).U) /*! @brief Format value for bitfield FTFE_FCCOB6_CCOBn. */ #define BF_FTFE_FCCOB6_CCOBn(v) ((uint8_t)((uint8_t)(v) << BP_FTFE_FCCOB6_CCOBn) & BM_FTFE_FCCOB6_CCOBn) /*! @brief Set the CCOBn field to a new value. */ #define BW_FTFE_FCCOB6_CCOBn(x, v) (HW_FTFE_FCCOB6_WR(x, v)) /*@}*/ /******************************************************************************* * HW_FTFE_FCCOB5 - Flash Common Command Object Registers ******************************************************************************/ /*! * @brief HW_FTFE_FCCOB5 - Flash Common Command Object Registers (RW) * * Reset value: 0x00U * * The FCCOB register group provides 12 bytes for command codes and parameters. * The individual bytes within the set append a 0-B hex identifier to the FCCOB * register name: FCCOB0, FCCOB1, ..., FCCOBB. */ typedef union _hw_ftfe_fccob5 { uint8_t U; struct _hw_ftfe_fccob5_bitfields { uint8_t CCOBn : 8; /*!< [7:0] */ } B; } hw_ftfe_fccob5_t; /*! * @name Constants and macros for entire FTFE_FCCOB5 register */ /*@{*/ #define HW_FTFE_FCCOB5_ADDR(x) ((x) + 0xAU) #define HW_FTFE_FCCOB5(x) (*(__IO hw_ftfe_fccob5_t *) HW_FTFE_FCCOB5_ADDR(x)) #define HW_FTFE_FCCOB5_RD(x) (HW_FTFE_FCCOB5(x).U) #define HW_FTFE_FCCOB5_WR(x, v) (HW_FTFE_FCCOB5(x).U = (v)) #define HW_FTFE_FCCOB5_SET(x, v) (HW_FTFE_FCCOB5_WR(x, HW_FTFE_FCCOB5_RD(x) | (v))) #define HW_FTFE_FCCOB5_CLR(x, v) (HW_FTFE_FCCOB5_WR(x, HW_FTFE_FCCOB5_RD(x) & ~(v))) #define HW_FTFE_FCCOB5_TOG(x, v) (HW_FTFE_FCCOB5_WR(x, HW_FTFE_FCCOB5_RD(x) ^ (v))) /*@}*/ /* * Constants & macros for individual FTFE_FCCOB5 bitfields */ /*! * @name Register FTFE_FCCOB5, field CCOBn[7:0] (RW) * * The FCCOB register provides a command code and relevant parameters to the * memory controller. The individual registers that compose the FCCOB data set can * be written in any order, but you must provide all needed values, which vary * from command to command. First, set up all required FCCOB fields and then * initiate the command's execution by writing a 1 to the FSTAT[CCIF] bit. This clears * the CCIF bit, which locks all FCCOB parameter fields and they cannot be changed * by the user until the command completes (CCIF returns to 1). No command * buffering or queueing is provided; the next command can be loaded only after the * current command completes. Some commands return information to the FCCOB * registers. Any values returned to FCCOB are available for reading after the * FSTAT[CCIF] flag returns to 1 by the memory controller. The following table shows a * generic FTFE command format. The first FCCOB register, FCCOB0, always contains * the command code. This 8-bit value defines the command to be executed. The * command code is followed by the parameters required for this specific FTFE command, * typically an address and/or data values. The command parameter table is * written in terms of FCCOB Number (which is equivalent to the byte number). This * number is a reference to the FCCOB register name and is not the register address. * FCCOB NumberRefers to FCCOB register name, not register address Typical * Command Parameter Contents [7:0] 0 FCMD (a code that defines the FTFE command) 1 * Flash address [23:16] 2 Flash address [15:8] 3 Flash address [7:0] 4 Data Byte 0 * 5 Data Byte 1 6 Data Byte 2 7 Data Byte 3 8 Data Byte 4 9 Data Byte 5 A Data * Byte 6 B Data Byte 7 FCCOB Endianness and Multi-Byte Access: The FCCOB * register group uses a big endian addressing convention. For all command parameter * fields larger than 1 byte, the most significant data resides in the lowest FCCOB * register number. The FCCOB register group may be read and written as * individual bytes, aligned words (2 bytes) or aligned longwords (4 bytes). */ /*@{*/ #define BP_FTFE_FCCOB5_CCOBn (0U) /*!< Bit position for FTFE_FCCOB5_CCOBn. */ #define BM_FTFE_FCCOB5_CCOBn (0xFFU) /*!< Bit mask for FTFE_FCCOB5_CCOBn. */ #define BS_FTFE_FCCOB5_CCOBn (8U) /*!< Bit field size in bits for FTFE_FCCOB5_CCOBn. */ /*! @brief Read current value of the FTFE_FCCOB5_CCOBn field. */ #define BR_FTFE_FCCOB5_CCOBn(x) (HW_FTFE_FCCOB5(x).U) /*! @brief Format value for bitfield FTFE_FCCOB5_CCOBn. */ #define BF_FTFE_FCCOB5_CCOBn(v) ((uint8_t)((uint8_t)(v) << BP_FTFE_FCCOB5_CCOBn) & BM_FTFE_FCCOB5_CCOBn) /*! @brief Set the CCOBn field to a new value. */ #define BW_FTFE_FCCOB5_CCOBn(x, v) (HW_FTFE_FCCOB5_WR(x, v)) /*@}*/ /******************************************************************************* * HW_FTFE_FCCOB4 - Flash Common Command Object Registers ******************************************************************************/ /*! * @brief HW_FTFE_FCCOB4 - Flash Common Command Object Registers (RW) * * Reset value: 0x00U * * The FCCOB register group provides 12 bytes for command codes and parameters. * The individual bytes within the set append a 0-B hex identifier to the FCCOB * register name: FCCOB0, FCCOB1, ..., FCCOBB. */ typedef union _hw_ftfe_fccob4 { uint8_t U; struct _hw_ftfe_fccob4_bitfields { uint8_t CCOBn : 8; /*!< [7:0] */ } B; } hw_ftfe_fccob4_t; /*! * @name Constants and macros for entire FTFE_FCCOB4 register */ /*@{*/ #define HW_FTFE_FCCOB4_ADDR(x) ((x) + 0xBU) #define HW_FTFE_FCCOB4(x) (*(__IO hw_ftfe_fccob4_t *) HW_FTFE_FCCOB4_ADDR(x)) #define HW_FTFE_FCCOB4_RD(x) (HW_FTFE_FCCOB4(x).U) #define HW_FTFE_FCCOB4_WR(x, v) (HW_FTFE_FCCOB4(x).U = (v)) #define HW_FTFE_FCCOB4_SET(x, v) (HW_FTFE_FCCOB4_WR(x, HW_FTFE_FCCOB4_RD(x) | (v))) #define HW_FTFE_FCCOB4_CLR(x, v) (HW_FTFE_FCCOB4_WR(x, HW_FTFE_FCCOB4_RD(x) & ~(v))) #define HW_FTFE_FCCOB4_TOG(x, v) (HW_FTFE_FCCOB4_WR(x, HW_FTFE_FCCOB4_RD(x) ^ (v))) /*@}*/ /* * Constants & macros for individual FTFE_FCCOB4 bitfields */ /*! * @name Register FTFE_FCCOB4, field CCOBn[7:0] (RW) * * The FCCOB register provides a command code and relevant parameters to the * memory controller. The individual registers that compose the FCCOB data set can * be written in any order, but you must provide all needed values, which vary * from command to command. First, set up all required FCCOB fields and then * initiate the command's execution by writing a 1 to the FSTAT[CCIF] bit. This clears * the CCIF bit, which locks all FCCOB parameter fields and they cannot be changed * by the user until the command completes (CCIF returns to 1). No command * buffering or queueing is provided; the next command can be loaded only after the * current command completes. Some commands return information to the FCCOB * registers. Any values returned to FCCOB are available for reading after the * FSTAT[CCIF] flag returns to 1 by the memory controller. The following table shows a * generic FTFE command format. The first FCCOB register, FCCOB0, always contains * the command code. This 8-bit value defines the command to be executed. The * command code is followed by the parameters required for this specific FTFE command, * typically an address and/or data values. The command parameter table is * written in terms of FCCOB Number (which is equivalent to the byte number). This * number is a reference to the FCCOB register name and is not the register address. * FCCOB NumberRefers to FCCOB register name, not register address Typical * Command Parameter Contents [7:0] 0 FCMD (a code that defines the FTFE command) 1 * Flash address [23:16] 2 Flash address [15:8] 3 Flash address [7:0] 4 Data Byte 0 * 5 Data Byte 1 6 Data Byte 2 7 Data Byte 3 8 Data Byte 4 9 Data Byte 5 A Data * Byte 6 B Data Byte 7 FCCOB Endianness and Multi-Byte Access: The FCCOB * register group uses a big endian addressing convention. For all command parameter * fields larger than 1 byte, the most significant data resides in the lowest FCCOB * register number. The FCCOB register group may be read and written as * individual bytes, aligned words (2 bytes) or aligned longwords (4 bytes). */ /*@{*/ #define BP_FTFE_FCCOB4_CCOBn (0U) /*!< Bit position for FTFE_FCCOB4_CCOBn. */ #define BM_FTFE_FCCOB4_CCOBn (0xFFU) /*!< Bit mask for FTFE_FCCOB4_CCOBn. */ #define BS_FTFE_FCCOB4_CCOBn (8U) /*!< Bit field size in bits for FTFE_FCCOB4_CCOBn. */ /*! @brief Read current value of the FTFE_FCCOB4_CCOBn field. */ #define BR_FTFE_FCCOB4_CCOBn(x) (HW_FTFE_FCCOB4(x).U) /*! @brief Format value for bitfield FTFE_FCCOB4_CCOBn. */ #define BF_FTFE_FCCOB4_CCOBn(v) ((uint8_t)((uint8_t)(v) << BP_FTFE_FCCOB4_CCOBn) & BM_FTFE_FCCOB4_CCOBn) /*! @brief Set the CCOBn field to a new value. */ #define BW_FTFE_FCCOB4_CCOBn(x, v) (HW_FTFE_FCCOB4_WR(x, v)) /*@}*/ /******************************************************************************* * HW_FTFE_FCCOBB - Flash Common Command Object Registers ******************************************************************************/ /*! * @brief HW_FTFE_FCCOBB - Flash Common Command Object Registers (RW) * * Reset value: 0x00U * * The FCCOB register group provides 12 bytes for command codes and parameters. * The individual bytes within the set append a 0-B hex identifier to the FCCOB * register name: FCCOB0, FCCOB1, ..., FCCOBB. */ typedef union _hw_ftfe_fccobb { uint8_t U; struct _hw_ftfe_fccobb_bitfields { uint8_t CCOBn : 8; /*!< [7:0] */ } B; } hw_ftfe_fccobb_t; /*! * @name Constants and macros for entire FTFE_FCCOBB register */ /*@{*/ #define HW_FTFE_FCCOBB_ADDR(x) ((x) + 0xCU) #define HW_FTFE_FCCOBB(x) (*(__IO hw_ftfe_fccobb_t *) HW_FTFE_FCCOBB_ADDR(x)) #define HW_FTFE_FCCOBB_RD(x) (HW_FTFE_FCCOBB(x).U) #define HW_FTFE_FCCOBB_WR(x, v) (HW_FTFE_FCCOBB(x).U = (v)) #define HW_FTFE_FCCOBB_SET(x, v) (HW_FTFE_FCCOBB_WR(x, HW_FTFE_FCCOBB_RD(x) | (v))) #define HW_FTFE_FCCOBB_CLR(x, v) (HW_FTFE_FCCOBB_WR(x, HW_FTFE_FCCOBB_RD(x) & ~(v))) #define HW_FTFE_FCCOBB_TOG(x, v) (HW_FTFE_FCCOBB_WR(x, HW_FTFE_FCCOBB_RD(x) ^ (v))) /*@}*/ /* * Constants & macros for individual FTFE_FCCOBB bitfields */ /*! * @name Register FTFE_FCCOBB, field CCOBn[7:0] (RW) * * The FCCOB register provides a command code and relevant parameters to the * memory controller. The individual registers that compose the FCCOB data set can * be written in any order, but you must provide all needed values, which vary * from command to command. First, set up all required FCCOB fields and then * initiate the command's execution by writing a 1 to the FSTAT[CCIF] bit. This clears * the CCIF bit, which locks all FCCOB parameter fields and they cannot be changed * by the user until the command completes (CCIF returns to 1). No command * buffering or queueing is provided; the next command can be loaded only after the * current command completes. Some commands return information to the FCCOB * registers. Any values returned to FCCOB are available for reading after the * FSTAT[CCIF] flag returns to 1 by the memory controller. The following table shows a * generic FTFE command format. The first FCCOB register, FCCOB0, always contains * the command code. This 8-bit value defines the command to be executed. The * command code is followed by the parameters required for this specific FTFE command, * typically an address and/or data values. The command parameter table is * written in terms of FCCOB Number (which is equivalent to the byte number). This * number is a reference to the FCCOB register name and is not the register address. * FCCOB NumberRefers to FCCOB register name, not register address Typical * Command Parameter Contents [7:0] 0 FCMD (a code that defines the FTFE command) 1 * Flash address [23:16] 2 Flash address [15:8] 3 Flash address [7:0] 4 Data Byte 0 * 5 Data Byte 1 6 Data Byte 2 7 Data Byte 3 8 Data Byte 4 9 Data Byte 5 A Data * Byte 6 B Data Byte 7 FCCOB Endianness and Multi-Byte Access: The FCCOB * register group uses a big endian addressing convention. For all command parameter * fields larger than 1 byte, the most significant data resides in the lowest FCCOB * register number. The FCCOB register group may be read and written as * individual bytes, aligned words (2 bytes) or aligned longwords (4 bytes). */ /*@{*/ #define BP_FTFE_FCCOBB_CCOBn (0U) /*!< Bit position for FTFE_FCCOBB_CCOBn. */ #define BM_FTFE_FCCOBB_CCOBn (0xFFU) /*!< Bit mask for FTFE_FCCOBB_CCOBn. */ #define BS_FTFE_FCCOBB_CCOBn (8U) /*!< Bit field size in bits for FTFE_FCCOBB_CCOBn. */ /*! @brief Read current value of the FTFE_FCCOBB_CCOBn field. */ #define BR_FTFE_FCCOBB_CCOBn(x) (HW_FTFE_FCCOBB(x).U) /*! @brief Format value for bitfield FTFE_FCCOBB_CCOBn. */ #define BF_FTFE_FCCOBB_CCOBn(v) ((uint8_t)((uint8_t)(v) << BP_FTFE_FCCOBB_CCOBn) & BM_FTFE_FCCOBB_CCOBn) /*! @brief Set the CCOBn field to a new value. */ #define BW_FTFE_FCCOBB_CCOBn(x, v) (HW_FTFE_FCCOBB_WR(x, v)) /*@}*/ /******************************************************************************* * HW_FTFE_FCCOBA - Flash Common Command Object Registers ******************************************************************************/ /*! * @brief HW_FTFE_FCCOBA - Flash Common Command Object Registers (RW) * * Reset value: 0x00U * * The FCCOB register group provides 12 bytes for command codes and parameters. * The individual bytes within the set append a 0-B hex identifier to the FCCOB * register name: FCCOB0, FCCOB1, ..., FCCOBB. */ typedef union _hw_ftfe_fccoba { uint8_t U; struct _hw_ftfe_fccoba_bitfields { uint8_t CCOBn : 8; /*!< [7:0] */ } B; } hw_ftfe_fccoba_t; /*! * @name Constants and macros for entire FTFE_FCCOBA register */ /*@{*/ #define HW_FTFE_FCCOBA_ADDR(x) ((x) + 0xDU) #define HW_FTFE_FCCOBA(x) (*(__IO hw_ftfe_fccoba_t *) HW_FTFE_FCCOBA_ADDR(x)) #define HW_FTFE_FCCOBA_RD(x) (HW_FTFE_FCCOBA(x).U) #define HW_FTFE_FCCOBA_WR(x, v) (HW_FTFE_FCCOBA(x).U = (v)) #define HW_FTFE_FCCOBA_SET(x, v) (HW_FTFE_FCCOBA_WR(x, HW_FTFE_FCCOBA_RD(x) | (v))) #define HW_FTFE_FCCOBA_CLR(x, v) (HW_FTFE_FCCOBA_WR(x, HW_FTFE_FCCOBA_RD(x) & ~(v))) #define HW_FTFE_FCCOBA_TOG(x, v) (HW_FTFE_FCCOBA_WR(x, HW_FTFE_FCCOBA_RD(x) ^ (v))) /*@}*/ /* * Constants & macros for individual FTFE_FCCOBA bitfields */ /*! * @name Register FTFE_FCCOBA, field CCOBn[7:0] (RW) * * The FCCOB register provides a command code and relevant parameters to the * memory controller. The individual registers that compose the FCCOB data set can * be written in any order, but you must provide all needed values, which vary * from command to command. First, set up all required FCCOB fields and then * initiate the command's execution by writing a 1 to the FSTAT[CCIF] bit. This clears * the CCIF bit, which locks all FCCOB parameter fields and they cannot be changed * by the user until the command completes (CCIF returns to 1). No command * buffering or queueing is provided; the next command can be loaded only after the * current command completes. Some commands return information to the FCCOB * registers. Any values returned to FCCOB are available for reading after the * FSTAT[CCIF] flag returns to 1 by the memory controller. The following table shows a * generic FTFE command format. The first FCCOB register, FCCOB0, always contains * the command code. This 8-bit value defines the command to be executed. The * command code is followed by the parameters required for this specific FTFE command, * typically an address and/or data values. The command parameter table is * written in terms of FCCOB Number (which is equivalent to the byte number). This * number is a reference to the FCCOB register name and is not the register address. * FCCOB NumberRefers to FCCOB register name, not register address Typical * Command Parameter Contents [7:0] 0 FCMD (a code that defines the FTFE command) 1 * Flash address [23:16] 2 Flash address [15:8] 3 Flash address [7:0] 4 Data Byte 0 * 5 Data Byte 1 6 Data Byte 2 7 Data Byte 3 8 Data Byte 4 9 Data Byte 5 A Data * Byte 6 B Data Byte 7 FCCOB Endianness and Multi-Byte Access: The FCCOB * register group uses a big endian addressing convention. For all command parameter * fields larger than 1 byte, the most significant data resides in the lowest FCCOB * register number. The FCCOB register group may be read and written as * individual bytes, aligned words (2 bytes) or aligned longwords (4 bytes). */ /*@{*/ #define BP_FTFE_FCCOBA_CCOBn (0U) /*!< Bit position for FTFE_FCCOBA_CCOBn. */ #define BM_FTFE_FCCOBA_CCOBn (0xFFU) /*!< Bit mask for FTFE_FCCOBA_CCOBn. */ #define BS_FTFE_FCCOBA_CCOBn (8U) /*!< Bit field size in bits for FTFE_FCCOBA_CCOBn. */ /*! @brief Read current value of the FTFE_FCCOBA_CCOBn field. */ #define BR_FTFE_FCCOBA_CCOBn(x) (HW_FTFE_FCCOBA(x).U) /*! @brief Format value for bitfield FTFE_FCCOBA_CCOBn. */ #define BF_FTFE_FCCOBA_CCOBn(v) ((uint8_t)((uint8_t)(v) << BP_FTFE_FCCOBA_CCOBn) & BM_FTFE_FCCOBA_CCOBn) /*! @brief Set the CCOBn field to a new value. */ #define BW_FTFE_FCCOBA_CCOBn(x, v) (HW_FTFE_FCCOBA_WR(x, v)) /*@}*/ /******************************************************************************* * HW_FTFE_FCCOB9 - Flash Common Command Object Registers ******************************************************************************/ /*! * @brief HW_FTFE_FCCOB9 - Flash Common Command Object Registers (RW) * * Reset value: 0x00U * * The FCCOB register group provides 12 bytes for command codes and parameters. * The individual bytes within the set append a 0-B hex identifier to the FCCOB * register name: FCCOB0, FCCOB1, ..., FCCOBB. */ typedef union _hw_ftfe_fccob9 { uint8_t U; struct _hw_ftfe_fccob9_bitfields { uint8_t CCOBn : 8; /*!< [7:0] */ } B; } hw_ftfe_fccob9_t; /*! * @name Constants and macros for entire FTFE_FCCOB9 register */ /*@{*/ #define HW_FTFE_FCCOB9_ADDR(x) ((x) + 0xEU) #define HW_FTFE_FCCOB9(x) (*(__IO hw_ftfe_fccob9_t *) HW_FTFE_FCCOB9_ADDR(x)) #define HW_FTFE_FCCOB9_RD(x) (HW_FTFE_FCCOB9(x).U) #define HW_FTFE_FCCOB9_WR(x, v) (HW_FTFE_FCCOB9(x).U = (v)) #define HW_FTFE_FCCOB9_SET(x, v) (HW_FTFE_FCCOB9_WR(x, HW_FTFE_FCCOB9_RD(x) | (v))) #define HW_FTFE_FCCOB9_CLR(x, v) (HW_FTFE_FCCOB9_WR(x, HW_FTFE_FCCOB9_RD(x) & ~(v))) #define HW_FTFE_FCCOB9_TOG(x, v) (HW_FTFE_FCCOB9_WR(x, HW_FTFE_FCCOB9_RD(x) ^ (v))) /*@}*/ /* * Constants & macros for individual FTFE_FCCOB9 bitfields */ /*! * @name Register FTFE_FCCOB9, field CCOBn[7:0] (RW) * * The FCCOB register provides a command code and relevant parameters to the * memory controller. The individual registers that compose the FCCOB data set can * be written in any order, but you must provide all needed values, which vary * from command to command. First, set up all required FCCOB fields and then * initiate the command's execution by writing a 1 to the FSTAT[CCIF] bit. This clears * the CCIF bit, which locks all FCCOB parameter fields and they cannot be changed * by the user until the command completes (CCIF returns to 1). No command * buffering or queueing is provided; the next command can be loaded only after the * current command completes. Some commands return information to the FCCOB * registers. Any values returned to FCCOB are available for reading after the * FSTAT[CCIF] flag returns to 1 by the memory controller. The following table shows a * generic FTFE command format. The first FCCOB register, FCCOB0, always contains * the command code. This 8-bit value defines the command to be executed. The * command code is followed by the parameters required for this specific FTFE command, * typically an address and/or data values. The command parameter table is * written in terms of FCCOB Number (which is equivalent to the byte number). This * number is a reference to the FCCOB register name and is not the register address. * FCCOB NumberRefers to FCCOB register name, not register address Typical * Command Parameter Contents [7:0] 0 FCMD (a code that defines the FTFE command) 1 * Flash address [23:16] 2 Flash address [15:8] 3 Flash address [7:0] 4 Data Byte 0 * 5 Data Byte 1 6 Data Byte 2 7 Data Byte 3 8 Data Byte 4 9 Data Byte 5 A Data * Byte 6 B Data Byte 7 FCCOB Endianness and Multi-Byte Access: The FCCOB * register group uses a big endian addressing convention. For all command parameter * fields larger than 1 byte, the most significant data resides in the lowest FCCOB * register number. The FCCOB register group may be read and written as * individual bytes, aligned words (2 bytes) or aligned longwords (4 bytes). */ /*@{*/ #define BP_FTFE_FCCOB9_CCOBn (0U) /*!< Bit position for FTFE_FCCOB9_CCOBn. */ #define BM_FTFE_FCCOB9_CCOBn (0xFFU) /*!< Bit mask for FTFE_FCCOB9_CCOBn. */ #define BS_FTFE_FCCOB9_CCOBn (8U) /*!< Bit field size in bits for FTFE_FCCOB9_CCOBn. */ /*! @brief Read current value of the FTFE_FCCOB9_CCOBn field. */ #define BR_FTFE_FCCOB9_CCOBn(x) (HW_FTFE_FCCOB9(x).U) /*! @brief Format value for bitfield FTFE_FCCOB9_CCOBn. */ #define BF_FTFE_FCCOB9_CCOBn(v) ((uint8_t)((uint8_t)(v) << BP_FTFE_FCCOB9_CCOBn) & BM_FTFE_FCCOB9_CCOBn) /*! @brief Set the CCOBn field to a new value. */ #define BW_FTFE_FCCOB9_CCOBn(x, v) (HW_FTFE_FCCOB9_WR(x, v)) /*@}*/ /******************************************************************************* * HW_FTFE_FCCOB8 - Flash Common Command Object Registers ******************************************************************************/ /*! * @brief HW_FTFE_FCCOB8 - Flash Common Command Object Registers (RW) * * Reset value: 0x00U * * The FCCOB register group provides 12 bytes for command codes and parameters. * The individual bytes within the set append a 0-B hex identifier to the FCCOB * register name: FCCOB0, FCCOB1, ..., FCCOBB. */ typedef union _hw_ftfe_fccob8 { uint8_t U; struct _hw_ftfe_fccob8_bitfields { uint8_t CCOBn : 8; /*!< [7:0] */ } B; } hw_ftfe_fccob8_t; /*! * @name Constants and macros for entire FTFE_FCCOB8 register */ /*@{*/ #define HW_FTFE_FCCOB8_ADDR(x) ((x) + 0xFU) #define HW_FTFE_FCCOB8(x) (*(__IO hw_ftfe_fccob8_t *) HW_FTFE_FCCOB8_ADDR(x)) #define HW_FTFE_FCCOB8_RD(x) (HW_FTFE_FCCOB8(x).U) #define HW_FTFE_FCCOB8_WR(x, v) (HW_FTFE_FCCOB8(x).U = (v)) #define HW_FTFE_FCCOB8_SET(x, v) (HW_FTFE_FCCOB8_WR(x, HW_FTFE_FCCOB8_RD(x) | (v))) #define HW_FTFE_FCCOB8_CLR(x, v) (HW_FTFE_FCCOB8_WR(x, HW_FTFE_FCCOB8_RD(x) & ~(v))) #define HW_FTFE_FCCOB8_TOG(x, v) (HW_FTFE_FCCOB8_WR(x, HW_FTFE_FCCOB8_RD(x) ^ (v))) /*@}*/ /* * Constants & macros for individual FTFE_FCCOB8 bitfields */ /*! * @name Register FTFE_FCCOB8, field CCOBn[7:0] (RW) * * The FCCOB register provides a command code and relevant parameters to the * memory controller. The individual registers that compose the FCCOB data set can * be written in any order, but you must provide all needed values, which vary * from command to command. First, set up all required FCCOB fields and then * initiate the command's execution by writing a 1 to the FSTAT[CCIF] bit. This clears * the CCIF bit, which locks all FCCOB parameter fields and they cannot be changed * by the user until the command completes (CCIF returns to 1). No command * buffering or queueing is provided; the next command can be loaded only after the * current command completes. Some commands return information to the FCCOB * registers. Any values returned to FCCOB are available for reading after the * FSTAT[CCIF] flag returns to 1 by the memory controller. The following table shows a * generic FTFE command format. The first FCCOB register, FCCOB0, always contains * the command code. This 8-bit value defines the command to be executed. The * command code is followed by the parameters required for this specific FTFE command, * typically an address and/or data values. The command parameter table is * written in terms of FCCOB Number (which is equivalent to the byte number). This * number is a reference to the FCCOB register name and is not the register address. * FCCOB NumberRefers to FCCOB register name, not register address Typical * Command Parameter Contents [7:0] 0 FCMD (a code that defines the FTFE command) 1 * Flash address [23:16] 2 Flash address [15:8] 3 Flash address [7:0] 4 Data Byte 0 * 5 Data Byte 1 6 Data Byte 2 7 Data Byte 3 8 Data Byte 4 9 Data Byte 5 A Data * Byte 6 B Data Byte 7 FCCOB Endianness and Multi-Byte Access: The FCCOB * register group uses a big endian addressing convention. For all command parameter * fields larger than 1 byte, the most significant data resides in the lowest FCCOB * register number. The FCCOB register group may be read and written as * individual bytes, aligned words (2 bytes) or aligned longwords (4 bytes). */ /*@{*/ #define BP_FTFE_FCCOB8_CCOBn (0U) /*!< Bit position for FTFE_FCCOB8_CCOBn. */ #define BM_FTFE_FCCOB8_CCOBn (0xFFU) /*!< Bit mask for FTFE_FCCOB8_CCOBn. */ #define BS_FTFE_FCCOB8_CCOBn (8U) /*!< Bit field size in bits for FTFE_FCCOB8_CCOBn. */ /*! @brief Read current value of the FTFE_FCCOB8_CCOBn field. */ #define BR_FTFE_FCCOB8_CCOBn(x) (HW_FTFE_FCCOB8(x).U) /*! @brief Format value for bitfield FTFE_FCCOB8_CCOBn. */ #define BF_FTFE_FCCOB8_CCOBn(v) ((uint8_t)((uint8_t)(v) << BP_FTFE_FCCOB8_CCOBn) & BM_FTFE_FCCOB8_CCOBn) /*! @brief Set the CCOBn field to a new value. */ #define BW_FTFE_FCCOB8_CCOBn(x, v) (HW_FTFE_FCCOB8_WR(x, v)) /*@}*/ /******************************************************************************* * HW_FTFE_FPROT3 - Program Flash Protection Registers ******************************************************************************/ /*! * @brief HW_FTFE_FPROT3 - Program Flash Protection Registers (RW) * * Reset value: 0x00U * * The FPROT registers define which program flash regions are protected from * program and erase operations. Protected flash regions cannot have their content * changed; that is, these regions cannot be programmed and cannot be erased by * any FTFE command. Unprotected regions can be changed by program and erase * operations. The four FPROT registers allow up to 32 protectable regions of equal * memory size. Program flash protection register Program flash protection bits * FPROT0 PROT[31:24] FPROT1 PROT[23:16] FPROT2 PROT[15:8] FPROT3 PROT[7:0] During * the reset sequence, the FPROT registers are loaded with the contents of the * program flash protection bytes in the Flash Configuration Field as indicated in * the following table. Program flash protection register Flash Configuration Field * offset address FPROT0 0x000B FPROT1 0x000A FPROT2 0x0009 FPROT3 0x0008 To * change the program flash protection that is loaded during the reset sequence, * unprotect the sector of program flash memory that contains the Flash * Configuration Field. Then, reprogram the program flash protection byte. */ typedef union _hw_ftfe_fprot3 { uint8_t U; struct _hw_ftfe_fprot3_bitfields { uint8_t PROT : 8; /*!< [7:0] Program Flash Region Protect */ } B; } hw_ftfe_fprot3_t; /*! * @name Constants and macros for entire FTFE_FPROT3 register */ /*@{*/ #define HW_FTFE_FPROT3_ADDR(x) ((x) + 0x10U) #define HW_FTFE_FPROT3(x) (*(__IO hw_ftfe_fprot3_t *) HW_FTFE_FPROT3_ADDR(x)) #define HW_FTFE_FPROT3_RD(x) (HW_FTFE_FPROT3(x).U) #define HW_FTFE_FPROT3_WR(x, v) (HW_FTFE_FPROT3(x).U = (v)) #define HW_FTFE_FPROT3_SET(x, v) (HW_FTFE_FPROT3_WR(x, HW_FTFE_FPROT3_RD(x) | (v))) #define HW_FTFE_FPROT3_CLR(x, v) (HW_FTFE_FPROT3_WR(x, HW_FTFE_FPROT3_RD(x) & ~(v))) #define HW_FTFE_FPROT3_TOG(x, v) (HW_FTFE_FPROT3_WR(x, HW_FTFE_FPROT3_RD(x) ^ (v))) /*@}*/ /* * Constants & macros for individual FTFE_FPROT3 bitfields */ /*! * @name Register FTFE_FPROT3, field PROT[7:0] (RW) * * Each program flash region can be protected from program and erase operations * by setting the associated PROT bit. In NVM Normal mode: The protection can * only be increased, meaning that currently unprotected memory can be protected, * but currently protected memory cannot be unprotected. Since unprotected regions * are marked with a 1 and protected regions use a 0, only writes changing 1s to * 0s are accepted. This 1-to-0 transition check is performed on a bit-by-bit * basis. Those FPROT bits with 1-to-0 transitions are accepted while all bits with * 0-to-1 transitions are ignored. In NVM Special mode: All bits of FPROT are * writable without restriction. Unprotected areas can be protected and protected * areas can be unprotected. The user must never write to any FPROT register while * a command is running (CCIF=0). Trying to alter data in any protected area in * the program flash memory results in a protection violation error and sets the * FSTAT[FPVIOL] bit. A full block erase of a program flash block is not possible * if it contains any protected region. * * Values: * - 0 - Program flash region is protected. * - 1 - Program flash region is not protected */ /*@{*/ #define BP_FTFE_FPROT3_PROT (0U) /*!< Bit position for FTFE_FPROT3_PROT. */ #define BM_FTFE_FPROT3_PROT (0xFFU) /*!< Bit mask for FTFE_FPROT3_PROT. */ #define BS_FTFE_FPROT3_PROT (8U) /*!< Bit field size in bits for FTFE_FPROT3_PROT. */ /*! @brief Read current value of the FTFE_FPROT3_PROT field. */ #define BR_FTFE_FPROT3_PROT(x) (HW_FTFE_FPROT3(x).U) /*! @brief Format value for bitfield FTFE_FPROT3_PROT. */ #define BF_FTFE_FPROT3_PROT(v) ((uint8_t)((uint8_t)(v) << BP_FTFE_FPROT3_PROT) & BM_FTFE_FPROT3_PROT) /*! @brief Set the PROT field to a new value. */ #define BW_FTFE_FPROT3_PROT(x, v) (HW_FTFE_FPROT3_WR(x, v)) /*@}*/ /******************************************************************************* * HW_FTFE_FPROT2 - Program Flash Protection Registers ******************************************************************************/ /*! * @brief HW_FTFE_FPROT2 - Program Flash Protection Registers (RW) * * Reset value: 0x00U * * The FPROT registers define which program flash regions are protected from * program and erase operations. Protected flash regions cannot have their content * changed; that is, these regions cannot be programmed and cannot be erased by * any FTFE command. Unprotected regions can be changed by program and erase * operations. The four FPROT registers allow up to 32 protectable regions of equal * memory size. Program flash protection register Program flash protection bits * FPROT0 PROT[31:24] FPROT1 PROT[23:16] FPROT2 PROT[15:8] FPROT3 PROT[7:0] During * the reset sequence, the FPROT registers are loaded with the contents of the * program flash protection bytes in the Flash Configuration Field as indicated in * the following table. Program flash protection register Flash Configuration Field * offset address FPROT0 0x000B FPROT1 0x000A FPROT2 0x0009 FPROT3 0x0008 To * change the program flash protection that is loaded during the reset sequence, * unprotect the sector of program flash memory that contains the Flash * Configuration Field. Then, reprogram the program flash protection byte. */ typedef union _hw_ftfe_fprot2 { uint8_t U; struct _hw_ftfe_fprot2_bitfields { uint8_t PROT : 8; /*!< [7:0] Program Flash Region Protect */ } B; } hw_ftfe_fprot2_t; /*! * @name Constants and macros for entire FTFE_FPROT2 register */ /*@{*/ #define HW_FTFE_FPROT2_ADDR(x) ((x) + 0x11U) #define HW_FTFE_FPROT2(x) (*(__IO hw_ftfe_fprot2_t *) HW_FTFE_FPROT2_ADDR(x)) #define HW_FTFE_FPROT2_RD(x) (HW_FTFE_FPROT2(x).U) #define HW_FTFE_FPROT2_WR(x, v) (HW_FTFE_FPROT2(x).U = (v)) #define HW_FTFE_FPROT2_SET(x, v) (HW_FTFE_FPROT2_WR(x, HW_FTFE_FPROT2_RD(x) | (v))) #define HW_FTFE_FPROT2_CLR(x, v) (HW_FTFE_FPROT2_WR(x, HW_FTFE_FPROT2_RD(x) & ~(v))) #define HW_FTFE_FPROT2_TOG(x, v) (HW_FTFE_FPROT2_WR(x, HW_FTFE_FPROT2_RD(x) ^ (v))) /*@}*/ /* * Constants & macros for individual FTFE_FPROT2 bitfields */ /*! * @name Register FTFE_FPROT2, field PROT[7:0] (RW) * * Each program flash region can be protected from program and erase operations * by setting the associated PROT bit. In NVM Normal mode: The protection can * only be increased, meaning that currently unprotected memory can be protected, * but currently protected memory cannot be unprotected. Since unprotected regions * are marked with a 1 and protected regions use a 0, only writes changing 1s to * 0s are accepted. This 1-to-0 transition check is performed on a bit-by-bit * basis. Those FPROT bits with 1-to-0 transitions are accepted while all bits with * 0-to-1 transitions are ignored. In NVM Special mode: All bits of FPROT are * writable without restriction. Unprotected areas can be protected and protected * areas can be unprotected. The user must never write to any FPROT register while * a command is running (CCIF=0). Trying to alter data in any protected area in * the program flash memory results in a protection violation error and sets the * FSTAT[FPVIOL] bit. A full block erase of a program flash block is not possible * if it contains any protected region. * * Values: * - 0 - Program flash region is protected. * - 1 - Program flash region is not protected */ /*@{*/ #define BP_FTFE_FPROT2_PROT (0U) /*!< Bit position for FTFE_FPROT2_PROT. */ #define BM_FTFE_FPROT2_PROT (0xFFU) /*!< Bit mask for FTFE_FPROT2_PROT. */ #define BS_FTFE_FPROT2_PROT (8U) /*!< Bit field size in bits for FTFE_FPROT2_PROT. */ /*! @brief Read current value of the FTFE_FPROT2_PROT field. */ #define BR_FTFE_FPROT2_PROT(x) (HW_FTFE_FPROT2(x).U) /*! @brief Format value for bitfield FTFE_FPROT2_PROT. */ #define BF_FTFE_FPROT2_PROT(v) ((uint8_t)((uint8_t)(v) << BP_FTFE_FPROT2_PROT) & BM_FTFE_FPROT2_PROT) /*! @brief Set the PROT field to a new value. */ #define BW_FTFE_FPROT2_PROT(x, v) (HW_FTFE_FPROT2_WR(x, v)) /*@}*/ /******************************************************************************* * HW_FTFE_FPROT1 - Program Flash Protection Registers ******************************************************************************/ /*! * @brief HW_FTFE_FPROT1 - Program Flash Protection Registers (RW) * * Reset value: 0x00U * * The FPROT registers define which program flash regions are protected from * program and erase operations. Protected flash regions cannot have their content * changed; that is, these regions cannot be programmed and cannot be erased by * any FTFE command. Unprotected regions can be changed by program and erase * operations. The four FPROT registers allow up to 32 protectable regions of equal * memory size. Program flash protection register Program flash protection bits * FPROT0 PROT[31:24] FPROT1 PROT[23:16] FPROT2 PROT[15:8] FPROT3 PROT[7:0] During * the reset sequence, the FPROT registers are loaded with the contents of the * program flash protection bytes in the Flash Configuration Field as indicated in * the following table. Program flash protection register Flash Configuration Field * offset address FPROT0 0x000B FPROT1 0x000A FPROT2 0x0009 FPROT3 0x0008 To * change the program flash protection that is loaded during the reset sequence, * unprotect the sector of program flash memory that contains the Flash * Configuration Field. Then, reprogram the program flash protection byte. */ typedef union _hw_ftfe_fprot1 { uint8_t U; struct _hw_ftfe_fprot1_bitfields { uint8_t PROT : 8; /*!< [7:0] Program Flash Region Protect */ } B; } hw_ftfe_fprot1_t; /*! * @name Constants and macros for entire FTFE_FPROT1 register */ /*@{*/ #define HW_FTFE_FPROT1_ADDR(x) ((x) + 0x12U) #define HW_FTFE_FPROT1(x) (*(__IO hw_ftfe_fprot1_t *) HW_FTFE_FPROT1_ADDR(x)) #define HW_FTFE_FPROT1_RD(x) (HW_FTFE_FPROT1(x).U) #define HW_FTFE_FPROT1_WR(x, v) (HW_FTFE_FPROT1(x).U = (v)) #define HW_FTFE_FPROT1_SET(x, v) (HW_FTFE_FPROT1_WR(x, HW_FTFE_FPROT1_RD(x) | (v))) #define HW_FTFE_FPROT1_CLR(x, v) (HW_FTFE_FPROT1_WR(x, HW_FTFE_FPROT1_RD(x) & ~(v))) #define HW_FTFE_FPROT1_TOG(x, v) (HW_FTFE_FPROT1_WR(x, HW_FTFE_FPROT1_RD(x) ^ (v))) /*@}*/ /* * Constants & macros for individual FTFE_FPROT1 bitfields */ /*! * @name Register FTFE_FPROT1, field PROT[7:0] (RW) * * Each program flash region can be protected from program and erase operations * by setting the associated PROT bit. In NVM Normal mode: The protection can * only be increased, meaning that currently unprotected memory can be protected, * but currently protected memory cannot be unprotected. Since unprotected regions * are marked with a 1 and protected regions use a 0, only writes changing 1s to * 0s are accepted. This 1-to-0 transition check is performed on a bit-by-bit * basis. Those FPROT bits with 1-to-0 transitions are accepted while all bits with * 0-to-1 transitions are ignored. In NVM Special mode: All bits of FPROT are * writable without restriction. Unprotected areas can be protected and protected * areas can be unprotected. The user must never write to any FPROT register while * a command is running (CCIF=0). Trying to alter data in any protected area in * the program flash memory results in a protection violation error and sets the * FSTAT[FPVIOL] bit. A full block erase of a program flash block is not possible * if it contains any protected region. * * Values: * - 0 - Program flash region is protected. * - 1 - Program flash region is not protected */ /*@{*/ #define BP_FTFE_FPROT1_PROT (0U) /*!< Bit position for FTFE_FPROT1_PROT. */ #define BM_FTFE_FPROT1_PROT (0xFFU) /*!< Bit mask for FTFE_FPROT1_PROT. */ #define BS_FTFE_FPROT1_PROT (8U) /*!< Bit field size in bits for FTFE_FPROT1_PROT. */ /*! @brief Read current value of the FTFE_FPROT1_PROT field. */ #define BR_FTFE_FPROT1_PROT(x) (HW_FTFE_FPROT1(x).U) /*! @brief Format value for bitfield FTFE_FPROT1_PROT. */ #define BF_FTFE_FPROT1_PROT(v) ((uint8_t)((uint8_t)(v) << BP_FTFE_FPROT1_PROT) & BM_FTFE_FPROT1_PROT) /*! @brief Set the PROT field to a new value. */ #define BW_FTFE_FPROT1_PROT(x, v) (HW_FTFE_FPROT1_WR(x, v)) /*@}*/ /******************************************************************************* * HW_FTFE_FPROT0 - Program Flash Protection Registers ******************************************************************************/ /*! * @brief HW_FTFE_FPROT0 - Program Flash Protection Registers (RW) * * Reset value: 0x00U * * The FPROT registers define which program flash regions are protected from * program and erase operations. Protected flash regions cannot have their content * changed; that is, these regions cannot be programmed and cannot be erased by * any FTFE command. Unprotected regions can be changed by program and erase * operations. The four FPROT registers allow up to 32 protectable regions of equal * memory size. Program flash protection register Program flash protection bits * FPROT0 PROT[31:24] FPROT1 PROT[23:16] FPROT2 PROT[15:8] FPROT3 PROT[7:0] During * the reset sequence, the FPROT registers are loaded with the contents of the * program flash protection bytes in the Flash Configuration Field as indicated in * the following table. Program flash protection register Flash Configuration Field * offset address FPROT0 0x000B FPROT1 0x000A FPROT2 0x0009 FPROT3 0x0008 To * change the program flash protection that is loaded during the reset sequence, * unprotect the sector of program flash memory that contains the Flash * Configuration Field. Then, reprogram the program flash protection byte. */ typedef union _hw_ftfe_fprot0 { uint8_t U; struct _hw_ftfe_fprot0_bitfields { uint8_t PROT : 8; /*!< [7:0] Program Flash Region Protect */ } B; } hw_ftfe_fprot0_t; /*! * @name Constants and macros for entire FTFE_FPROT0 register */ /*@{*/ #define HW_FTFE_FPROT0_ADDR(x) ((x) + 0x13U) #define HW_FTFE_FPROT0(x) (*(__IO hw_ftfe_fprot0_t *) HW_FTFE_FPROT0_ADDR(x)) #define HW_FTFE_FPROT0_RD(x) (HW_FTFE_FPROT0(x).U) #define HW_FTFE_FPROT0_WR(x, v) (HW_FTFE_FPROT0(x).U = (v)) #define HW_FTFE_FPROT0_SET(x, v) (HW_FTFE_FPROT0_WR(x, HW_FTFE_FPROT0_RD(x) | (v))) #define HW_FTFE_FPROT0_CLR(x, v) (HW_FTFE_FPROT0_WR(x, HW_FTFE_FPROT0_RD(x) & ~(v))) #define HW_FTFE_FPROT0_TOG(x, v) (HW_FTFE_FPROT0_WR(x, HW_FTFE_FPROT0_RD(x) ^ (v))) /*@}*/ /* * Constants & macros for individual FTFE_FPROT0 bitfields */ /*! * @name Register FTFE_FPROT0, field PROT[7:0] (RW) * * Each program flash region can be protected from program and erase operations * by setting the associated PROT bit. In NVM Normal mode: The protection can * only be increased, meaning that currently unprotected memory can be protected, * but currently protected memory cannot be unprotected. Since unprotected regions * are marked with a 1 and protected regions use a 0, only writes changing 1s to * 0s are accepted. This 1-to-0 transition check is performed on a bit-by-bit * basis. Those FPROT bits with 1-to-0 transitions are accepted while all bits with * 0-to-1 transitions are ignored. In NVM Special mode: All bits of FPROT are * writable without restriction. Unprotected areas can be protected and protected * areas can be unprotected. The user must never write to any FPROT register while * a command is running (CCIF=0). Trying to alter data in any protected area in * the program flash memory results in a protection violation error and sets the * FSTAT[FPVIOL] bit. A full block erase of a program flash block is not possible * if it contains any protected region. * * Values: * - 0 - Program flash region is protected. * - 1 - Program flash region is not protected */ /*@{*/ #define BP_FTFE_FPROT0_PROT (0U) /*!< Bit position for FTFE_FPROT0_PROT. */ #define BM_FTFE_FPROT0_PROT (0xFFU) /*!< Bit mask for FTFE_FPROT0_PROT. */ #define BS_FTFE_FPROT0_PROT (8U) /*!< Bit field size in bits for FTFE_FPROT0_PROT. */ /*! @brief Read current value of the FTFE_FPROT0_PROT field. */ #define BR_FTFE_FPROT0_PROT(x) (HW_FTFE_FPROT0(x).U) /*! @brief Format value for bitfield FTFE_FPROT0_PROT. */ #define BF_FTFE_FPROT0_PROT(v) ((uint8_t)((uint8_t)(v) << BP_FTFE_FPROT0_PROT) & BM_FTFE_FPROT0_PROT) /*! @brief Set the PROT field to a new value. */ #define BW_FTFE_FPROT0_PROT(x, v) (HW_FTFE_FPROT0_WR(x, v)) /*@}*/ /******************************************************************************* * HW_FTFE_FEPROT - EEPROM Protection Register ******************************************************************************/ /*! * @brief HW_FTFE_FEPROT - EEPROM Protection Register (RW) * * Reset value: 0x00U * * For devices with FlexNVM: The FEPROT register defines which EEPROM regions of * the FlexRAM are protected against program and erase operations. Protected * EEPROM regions cannot have their content changed by writing to it. Unprotected * regions can be changed by writing to the FlexRAM. For devices with program flash * only: This register is reserved and not used. */ typedef union _hw_ftfe_feprot { uint8_t U; struct _hw_ftfe_feprot_bitfields { uint8_t EPROT : 8; /*!< [7:0] EEPROM Region Protect */ } B; } hw_ftfe_feprot_t; /*! * @name Constants and macros for entire FTFE_FEPROT register */ /*@{*/ #define HW_FTFE_FEPROT_ADDR(x) ((x) + 0x16U) #define HW_FTFE_FEPROT(x) (*(__IO hw_ftfe_feprot_t *) HW_FTFE_FEPROT_ADDR(x)) #define HW_FTFE_FEPROT_RD(x) (HW_FTFE_FEPROT(x).U) #define HW_FTFE_FEPROT_WR(x, v) (HW_FTFE_FEPROT(x).U = (v)) #define HW_FTFE_FEPROT_SET(x, v) (HW_FTFE_FEPROT_WR(x, HW_FTFE_FEPROT_RD(x) | (v))) #define HW_FTFE_FEPROT_CLR(x, v) (HW_FTFE_FEPROT_WR(x, HW_FTFE_FEPROT_RD(x) & ~(v))) #define HW_FTFE_FEPROT_TOG(x, v) (HW_FTFE_FEPROT_WR(x, HW_FTFE_FEPROT_RD(x) ^ (v))) /*@}*/ /* * Constants & macros for individual FTFE_FEPROT bitfields */ /*! * @name Register FTFE_FEPROT, field EPROT[7:0] (RW) * * For devices with program flash only: Reserved For devices with FlexNVM: * Individual EEPROM regions can be protected from alteration by setting the * associated EPROT bit. The EPROT bits are not used when the FlexNVM Partition Code is * set to data flash only. When the FlexNVM Partition Code is set to data flash and * EEPROM or EEPROM only, each EPROT bit covers one-eighth of the configured * EEPROM data (see the EEPROM Data Set Size parameter description). In NVM Normal * mode: The protection can only be increased. This means that * currently-unprotected memory can be protected, but currently-protected memory cannot be * unprotected. Since unprotected regions are marked with a 1 and protected regions use a * 0, only writes changing 1s to 0s are accepted. This 1-to-0 transition check is * performed on a bit-by-bit basis. Those FEPROT bits with 1-to-0 transitions * are accepted while all bits with 0-to-1 transitions are ignored. In NVM Special * mode: All bits of the FEPROT register are writable without restriction. * Unprotected areas can be protected and protected areas can be unprotected. Never * write to the FEPROT register while a command is running (CCIF=0). Reset: During * the reset sequence, the FEPROT register is loaded with the contents of the * FlexRAM protection byte in the Flash Configuration Field located in program flash. * The flash basis for the reset values is signified by X in the register * diagram. To change the EEPROM protection that will be loaded during the reset * sequence, the sector of program flash that contains the Flash Configuration Field * must be unprotected; then the EEPROM protection byte must be erased and * reprogrammed. Trying to alter data by writing to any protected area in the EEPROM * results in a protection violation error and sets the FSTAT[FPVIOL] bit. * * Values: * - 0 - For devices with program flash only: Reserved For devices with FlexNVM: * EEPROM region is protected * - 1 - For devices with program flash only: Reserved For devices with FlexNVM: * EEPROM region is not protected */ /*@{*/ #define BP_FTFE_FEPROT_EPROT (0U) /*!< Bit position for FTFE_FEPROT_EPROT. */ #define BM_FTFE_FEPROT_EPROT (0xFFU) /*!< Bit mask for FTFE_FEPROT_EPROT. */ #define BS_FTFE_FEPROT_EPROT (8U) /*!< Bit field size in bits for FTFE_FEPROT_EPROT. */ /*! @brief Read current value of the FTFE_FEPROT_EPROT field. */ #define BR_FTFE_FEPROT_EPROT(x) (HW_FTFE_FEPROT(x).U) /*! @brief Format value for bitfield FTFE_FEPROT_EPROT. */ #define BF_FTFE_FEPROT_EPROT(v) ((uint8_t)((uint8_t)(v) << BP_FTFE_FEPROT_EPROT) & BM_FTFE_FEPROT_EPROT) /*! @brief Set the EPROT field to a new value. */ #define BW_FTFE_FEPROT_EPROT(x, v) (HW_FTFE_FEPROT_WR(x, v)) /*@}*/ /******************************************************************************* * HW_FTFE_FDPROT - Data Flash Protection Register ******************************************************************************/ /*! * @brief HW_FTFE_FDPROT - Data Flash Protection Register (RW) * * Reset value: 0x00U * * The FDPROT register defines which data flash regions are protected against * program and erase operations. Protected Flash regions cannot have their content * changed; that is, these regions cannot be programmed and cannot be erased by * any FTFE command. Unprotected regions can be changed by both program and erase * operations. */ typedef union _hw_ftfe_fdprot { uint8_t U; struct _hw_ftfe_fdprot_bitfields { uint8_t DPROT : 8; /*!< [7:0] Data Flash Region Protect */ } B; } hw_ftfe_fdprot_t; /*! * @name Constants and macros for entire FTFE_FDPROT register */ /*@{*/ #define HW_FTFE_FDPROT_ADDR(x) ((x) + 0x17U) #define HW_FTFE_FDPROT(x) (*(__IO hw_ftfe_fdprot_t *) HW_FTFE_FDPROT_ADDR(x)) #define HW_FTFE_FDPROT_RD(x) (HW_FTFE_FDPROT(x).U) #define HW_FTFE_FDPROT_WR(x, v) (HW_FTFE_FDPROT(x).U = (v)) #define HW_FTFE_FDPROT_SET(x, v) (HW_FTFE_FDPROT_WR(x, HW_FTFE_FDPROT_RD(x) | (v))) #define HW_FTFE_FDPROT_CLR(x, v) (HW_FTFE_FDPROT_WR(x, HW_FTFE_FDPROT_RD(x) & ~(v))) #define HW_FTFE_FDPROT_TOG(x, v) (HW_FTFE_FDPROT_WR(x, HW_FTFE_FDPROT_RD(x) ^ (v))) /*@}*/ /* * Constants & macros for individual FTFE_FDPROT bitfields */ /*! * @name Register FTFE_FDPROT, field DPROT[7:0] (RW) * * Individual data flash regions can be protected from program and erase * operations by setting the associated DPROT bit. Each DPROT bit protects one-eighth of * the partitioned data flash memory space. The granularity of data flash * protection cannot be less than the data flash sector size. If an unused DPROT bit is * set, the Erase all Blocks command does not execute and sets the FSTAT[FPVIOL] * bit. In NVM Normal mode: The protection can only be increased, meaning that * currently unprotected memory can be protected but currently protected memory * cannot be unprotected. Since unprotected regions are marked with a 1 and * protected regions use a 0, only writes changing 1s to 0s are accepted. This 1-to-0 * transition check is performed on a bit-by-bit basis. Those FDPROT bits with * 1-to-0 transitions are accepted while all bits with 0-to-1 transitions are * ignored. In NVM Special mode: All bits of the FDPROT register are writable without * restriction. Unprotected areas can be protected and protected areas can be * unprotected. The user must never write to the FDPROT register while a command is * running (CCIF=0). Reset: During the reset sequence, the FDPROT register is * loaded with the contents of the data flash protection byte in the Flash * Configuration Field located in program flash memory. The flash basis for the reset values * is signified by X in the register diagram. To change the data flash * protection that will be loaded during the reset sequence, unprotect the sector of * program flash that contains the Flash Configuration Field. Then, erase and * reprogram the data flash protection byte. Trying to alter data with the program and * erase commands in any protected area in the data flash memory results in a * protection violation error and sets the FSTAT[FPVIOL] bit. A block erase of any * data flash memory block (see the Erase Flash Block command description) is not * possible if the data flash block contains any protected region or if the FlexNVM * memory has been partitioned for EEPROM. * * Values: * - 0 - Data Flash region is protected * - 1 - Data Flash region is not protected */ /*@{*/ #define BP_FTFE_FDPROT_DPROT (0U) /*!< Bit position for FTFE_FDPROT_DPROT. */ #define BM_FTFE_FDPROT_DPROT (0xFFU) /*!< Bit mask for FTFE_FDPROT_DPROT. */ #define BS_FTFE_FDPROT_DPROT (8U) /*!< Bit field size in bits for FTFE_FDPROT_DPROT. */ /*! @brief Read current value of the FTFE_FDPROT_DPROT field. */ #define BR_FTFE_FDPROT_DPROT(x) (HW_FTFE_FDPROT(x).U) /*! @brief Format value for bitfield FTFE_FDPROT_DPROT. */ #define BF_FTFE_FDPROT_DPROT(v) ((uint8_t)((uint8_t)(v) << BP_FTFE_FDPROT_DPROT) & BM_FTFE_FDPROT_DPROT) /*! @brief Set the DPROT field to a new value. */ #define BW_FTFE_FDPROT_DPROT(x, v) (HW_FTFE_FDPROT_WR(x, v)) /*@}*/ /******************************************************************************* * hw_ftfe_t - module struct ******************************************************************************/ /*! * @brief All FTFE module registers. */ #pragma pack(1) typedef struct _hw_ftfe { __IO hw_ftfe_fstat_t FSTAT; /*!< [0x0] Flash Status Register */ __IO hw_ftfe_fcnfg_t FCNFG; /*!< [0x1] Flash Configuration Register */ __I hw_ftfe_fsec_t FSEC; /*!< [0x2] Flash Security Register */ __I hw_ftfe_fopt_t FOPT; /*!< [0x3] Flash Option Register */ __IO hw_ftfe_fccob3_t FCCOB3; /*!< [0x4] Flash Common Command Object Registers */ __IO hw_ftfe_fccob2_t FCCOB2; /*!< [0x5] Flash Common Command Object Registers */ __IO hw_ftfe_fccob1_t FCCOB1; /*!< [0x6] Flash Common Command Object Registers */ __IO hw_ftfe_fccob0_t FCCOB0; /*!< [0x7] Flash Common Command Object Registers */ __IO hw_ftfe_fccob7_t FCCOB7; /*!< [0x8] Flash Common Command Object Registers */ __IO hw_ftfe_fccob6_t FCCOB6; /*!< [0x9] Flash Common Command Object Registers */ __IO hw_ftfe_fccob5_t FCCOB5; /*!< [0xA] Flash Common Command Object Registers */ __IO hw_ftfe_fccob4_t FCCOB4; /*!< [0xB] Flash Common Command Object Registers */ __IO hw_ftfe_fccobb_t FCCOBB; /*!< [0xC] Flash Common Command Object Registers */ __IO hw_ftfe_fccoba_t FCCOBA; /*!< [0xD] Flash Common Command Object Registers */ __IO hw_ftfe_fccob9_t FCCOB9; /*!< [0xE] Flash Common Command Object Registers */ __IO hw_ftfe_fccob8_t FCCOB8; /*!< [0xF] Flash Common Command Object Registers */ __IO hw_ftfe_fprot3_t FPROT3; /*!< [0x10] Program Flash Protection Registers */ __IO hw_ftfe_fprot2_t FPROT2; /*!< [0x11] Program Flash Protection Registers */ __IO hw_ftfe_fprot1_t FPROT1; /*!< [0x12] Program Flash Protection Registers */ __IO hw_ftfe_fprot0_t FPROT0; /*!< [0x13] Program Flash Protection Registers */ uint8_t _reserved0[2]; __IO hw_ftfe_feprot_t FEPROT; /*!< [0x16] EEPROM Protection Register */ __IO hw_ftfe_fdprot_t FDPROT; /*!< [0x17] Data Flash Protection Register */ } hw_ftfe_t; #pragma pack() /*! @brief Macro to access all FTFE registers. */ /*! @param x FTFE module instance base address. */ /*! @return Reference (not a pointer) to the registers struct. To get a pointer to the struct, * use the '&' operator, like &HW_FTFE(FTFE_BASE). */ #define HW_FTFE(x) (*(hw_ftfe_t *)(x)) #endif /* __HW_FTFE_REGISTERS_H__ */ /* EOF */ ================================================ FILE: Zelig/mbed/TARGET_K64F/TARGET_Freescale/TARGET_KPSDK_MCUS/TARGET_MCU_K64F/device/device/MK64F12/MK64F12_ftm.h ================================================ /* ** ################################################################### ** Compilers: Keil ARM C/C++ Compiler ** Freescale C/C++ for Embedded ARM ** GNU C Compiler ** IAR ANSI C/C++ Compiler for ARM ** ** Reference manual: K64P144M120SF5RM, Rev.2, January 2014 ** Version: rev. 2.5, 2014-02-10 ** Build: b140604 ** ** Abstract: ** Extension to the CMSIS register access layer header. ** ** Copyright (c) 2014 Freescale Semiconductor, Inc. ** All rights reserved. ** ** Redistribution and use in source and binary forms, with or without modification, ** are permitted provided that the following conditions are met: ** ** o Redistributions of source code must retain the above copyright notice, this list ** of conditions and the following disclaimer. ** ** o Redistributions in binary form must reproduce the above copyright notice, this ** list of conditions and the following disclaimer in the documentation and/or ** other materials provided with the distribution. ** ** o Neither the name of Freescale Semiconductor, Inc. nor the names of its ** contributors may be used to endorse or promote products derived from this ** software without specific prior written permission. ** ** THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ** ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED ** WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE ** DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT 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. ** ** http: www.freescale.com ** mail: support@freescale.com ** ** Revisions: ** - rev. 1.0 (2013-08-12) ** Initial version. ** - rev. 2.0 (2013-10-29) ** Register accessor macros added to the memory map. ** Symbols for Processor Expert memory map compatibility added to the memory map. ** Startup file for gcc has been updated according to CMSIS 3.2. ** System initialization updated. ** MCG - registers updated. ** PORTA, PORTB, PORTC, PORTE - registers for digital filter removed. ** - rev. 2.1 (2013-10-30) ** Definition of BITBAND macros updated to support peripherals with 32-bit acces disabled. ** - rev. 2.2 (2013-12-09) ** DMA - EARS register removed. ** AIPS0, AIPS1 - MPRA register updated. ** - rev. 2.3 (2014-01-24) ** Update according to reference manual rev. 2 ** ENET, MCG, MCM, SIM, USB - registers updated ** - rev. 2.4 (2014-02-10) ** The declaration of clock configurations has been moved to separate header file system_MK64F12.h ** Update of SystemInit() and SystemCoreClockUpdate() functions. ** - rev. 2.5 (2014-02-10) ** The declaration of clock configurations has been moved to separate header file system_MK64F12.h ** Update of SystemInit() and SystemCoreClockUpdate() functions. ** Module access macro module_BASES replaced by module_BASE_PTRS. ** ** ################################################################### */ /* * WARNING! DO NOT EDIT THIS FILE DIRECTLY! * * This file was generated automatically and any changes may be lost. */ #ifndef __HW_FTM_REGISTERS_H__ #define __HW_FTM_REGISTERS_H__ #include "MK64F12.h" #include "fsl_bitaccess.h" /* * MK64F12 FTM * * FlexTimer Module * * Registers defined in this header file: * - HW_FTM_SC - Status And Control * - HW_FTM_CNT - Counter * - HW_FTM_MOD - Modulo * - HW_FTM_CnSC - Channel (n) Status And Control * - HW_FTM_CnV - Channel (n) Value * - HW_FTM_CNTIN - Counter Initial Value * - HW_FTM_STATUS - Capture And Compare Status * - HW_FTM_MODE - Features Mode Selection * - HW_FTM_SYNC - Synchronization * - HW_FTM_OUTINIT - Initial State For Channels Output * - HW_FTM_OUTMASK - Output Mask * - HW_FTM_COMBINE - Function For Linked Channels * - HW_FTM_DEADTIME - Deadtime Insertion Control * - HW_FTM_EXTTRIG - FTM External Trigger * - HW_FTM_POL - Channels Polarity * - HW_FTM_FMS - Fault Mode Status * - HW_FTM_FILTER - Input Capture Filter Control * - HW_FTM_FLTCTRL - Fault Control * - HW_FTM_QDCTRL - Quadrature Decoder Control And Status * - HW_FTM_CONF - Configuration * - HW_FTM_FLTPOL - FTM Fault Input Polarity * - HW_FTM_SYNCONF - Synchronization Configuration * - HW_FTM_INVCTRL - FTM Inverting Control * - HW_FTM_SWOCTRL - FTM Software Output Control * - HW_FTM_PWMLOAD - FTM PWM Load * * - hw_ftm_t - Struct containing all module registers. */ #define HW_FTM_INSTANCE_COUNT (4U) /*!< Number of instances of the FTM module. */ #define HW_FTM0 (0U) /*!< Instance number for FTM0. */ #define HW_FTM1 (1U) /*!< Instance number for FTM1. */ #define HW_FTM2 (2U) /*!< Instance number for FTM2. */ #define HW_FTM3 (3U) /*!< Instance number for FTM3. */ /******************************************************************************* * HW_FTM_SC - Status And Control ******************************************************************************/ /*! * @brief HW_FTM_SC - Status And Control (RW) * * Reset value: 0x00000000U * * SC contains the overflow status flag and control bits used to configure the * interrupt enable, FTM configuration, clock source, and prescaler factor. These * controls relate to all channels within this module. */ typedef union _hw_ftm_sc { uint32_t U; struct _hw_ftm_sc_bitfields { uint32_t PS : 3; /*!< [2:0] Prescale Factor Selection */ uint32_t CLKS : 2; /*!< [4:3] Clock Source Selection */ uint32_t CPWMS : 1; /*!< [5] Center-Aligned PWM Select */ uint32_t TOIE : 1; /*!< [6] Timer Overflow Interrupt Enable */ uint32_t TOF : 1; /*!< [7] Timer Overflow Flag */ uint32_t RESERVED0 : 24; /*!< [31:8] */ } B; } hw_ftm_sc_t; /*! * @name Constants and macros for entire FTM_SC register */ /*@{*/ #define HW_FTM_SC_ADDR(x) ((x) + 0x0U) #define HW_FTM_SC(x) (*(__IO hw_ftm_sc_t *) HW_FTM_SC_ADDR(x)) #define HW_FTM_SC_RD(x) (HW_FTM_SC(x).U) #define HW_FTM_SC_WR(x, v) (HW_FTM_SC(x).U = (v)) #define HW_FTM_SC_SET(x, v) (HW_FTM_SC_WR(x, HW_FTM_SC_RD(x) | (v))) #define HW_FTM_SC_CLR(x, v) (HW_FTM_SC_WR(x, HW_FTM_SC_RD(x) & ~(v))) #define HW_FTM_SC_TOG(x, v) (HW_FTM_SC_WR(x, HW_FTM_SC_RD(x) ^ (v))) /*@}*/ /* * Constants & macros for individual FTM_SC bitfields */ /*! * @name Register FTM_SC, field PS[2:0] (RW) * * Selects one of 8 division factors for the clock source selected by CLKS. The * new prescaler factor affects the clock source on the next system clock cycle * after the new value is updated into the register bits. This field is write * protected. It can be written only when MODE[WPDIS] = 1. * * Values: * - 000 - Divide by 1 * - 001 - Divide by 2 * - 010 - Divide by 4 * - 011 - Divide by 8 * - 100 - Divide by 16 * - 101 - Divide by 32 * - 110 - Divide by 64 * - 111 - Divide by 128 */ /*@{*/ #define BP_FTM_SC_PS (0U) /*!< Bit position for FTM_SC_PS. */ #define BM_FTM_SC_PS (0x00000007U) /*!< Bit mask for FTM_SC_PS. */ #define BS_FTM_SC_PS (3U) /*!< Bit field size in bits for FTM_SC_PS. */ /*! @brief Read current value of the FTM_SC_PS field. */ #define BR_FTM_SC_PS(x) (HW_FTM_SC(x).B.PS) /*! @brief Format value for bitfield FTM_SC_PS. */ #define BF_FTM_SC_PS(v) ((uint32_t)((uint32_t)(v) << BP_FTM_SC_PS) & BM_FTM_SC_PS) /*! @brief Set the PS field to a new value. */ #define BW_FTM_SC_PS(x, v) (HW_FTM_SC_WR(x, (HW_FTM_SC_RD(x) & ~BM_FTM_SC_PS) | BF_FTM_SC_PS(v))) /*@}*/ /*! * @name Register FTM_SC, field CLKS[4:3] (RW) * * Selects one of the three FTM counter clock sources. This field is write * protected. It can be written only when MODE[WPDIS] = 1. * * Values: * - 00 - No clock selected. This in effect disables the FTM counter. * - 01 - System clock * - 10 - Fixed frequency clock * - 11 - External clock */ /*@{*/ #define BP_FTM_SC_CLKS (3U) /*!< Bit position for FTM_SC_CLKS. */ #define BM_FTM_SC_CLKS (0x00000018U) /*!< Bit mask for FTM_SC_CLKS. */ #define BS_FTM_SC_CLKS (2U) /*!< Bit field size in bits for FTM_SC_CLKS. */ /*! @brief Read current value of the FTM_SC_CLKS field. */ #define BR_FTM_SC_CLKS(x) (HW_FTM_SC(x).B.CLKS) /*! @brief Format value for bitfield FTM_SC_CLKS. */ #define BF_FTM_SC_CLKS(v) ((uint32_t)((uint32_t)(v) << BP_FTM_SC_CLKS) & BM_FTM_SC_CLKS) /*! @brief Set the CLKS field to a new value. */ #define BW_FTM_SC_CLKS(x, v) (HW_FTM_SC_WR(x, (HW_FTM_SC_RD(x) & ~BM_FTM_SC_CLKS) | BF_FTM_SC_CLKS(v))) /*@}*/ /*! * @name Register FTM_SC, field CPWMS[5] (RW) * * Selects CPWM mode. This mode configures the FTM to operate in Up-Down * Counting mode. This field is write protected. It can be written only when MODE[WPDIS] * = 1. * * Values: * - 0 - FTM counter operates in Up Counting mode. * - 1 - FTM counter operates in Up-Down Counting mode. */ /*@{*/ #define BP_FTM_SC_CPWMS (5U) /*!< Bit position for FTM_SC_CPWMS. */ #define BM_FTM_SC_CPWMS (0x00000020U) /*!< Bit mask for FTM_SC_CPWMS. */ #define BS_FTM_SC_CPWMS (1U) /*!< Bit field size in bits for FTM_SC_CPWMS. */ /*! @brief Read current value of the FTM_SC_CPWMS field. */ #define BR_FTM_SC_CPWMS(x) (BITBAND_ACCESS32(HW_FTM_SC_ADDR(x), BP_FTM_SC_CPWMS)) /*! @brief Format value for bitfield FTM_SC_CPWMS. */ #define BF_FTM_SC_CPWMS(v) ((uint32_t)((uint32_t)(v) << BP_FTM_SC_CPWMS) & BM_FTM_SC_CPWMS) /*! @brief Set the CPWMS field to a new value. */ #define BW_FTM_SC_CPWMS(x, v) (BITBAND_ACCESS32(HW_FTM_SC_ADDR(x), BP_FTM_SC_CPWMS) = (v)) /*@}*/ /*! * @name Register FTM_SC, field TOIE[6] (RW) * * Enables FTM overflow interrupts. * * Values: * - 0 - Disable TOF interrupts. Use software polling. * - 1 - Enable TOF interrupts. An interrupt is generated when TOF equals one. */ /*@{*/ #define BP_FTM_SC_TOIE (6U) /*!< Bit position for FTM_SC_TOIE. */ #define BM_FTM_SC_TOIE (0x00000040U) /*!< Bit mask for FTM_SC_TOIE. */ #define BS_FTM_SC_TOIE (1U) /*!< Bit field size in bits for FTM_SC_TOIE. */ /*! @brief Read current value of the FTM_SC_TOIE field. */ #define BR_FTM_SC_TOIE(x) (BITBAND_ACCESS32(HW_FTM_SC_ADDR(x), BP_FTM_SC_TOIE)) /*! @brief Format value for bitfield FTM_SC_TOIE. */ #define BF_FTM_SC_TOIE(v) ((uint32_t)((uint32_t)(v) << BP_FTM_SC_TOIE) & BM_FTM_SC_TOIE) /*! @brief Set the TOIE field to a new value. */ #define BW_FTM_SC_TOIE(x, v) (BITBAND_ACCESS32(HW_FTM_SC_ADDR(x), BP_FTM_SC_TOIE) = (v)) /*@}*/ /*! * @name Register FTM_SC, field TOF[7] (ROWZ) * * Set by hardware when the FTM counter passes the value in the MOD register. * The TOF bit is cleared by reading the SC register while TOF is set and then * writing a 0 to TOF bit. Writing a 1 to TOF has no effect. If another FTM overflow * occurs between the read and write operations, the write operation has no * effect; therefore, TOF remains set indicating an overflow has occurred. In this * case, a TOF interrupt request is not lost due to the clearing sequence for a * previous TOF. * * Values: * - 0 - FTM counter has not overflowed. * - 1 - FTM counter has overflowed. */ /*@{*/ #define BP_FTM_SC_TOF (7U) /*!< Bit position for FTM_SC_TOF. */ #define BM_FTM_SC_TOF (0x00000080U) /*!< Bit mask for FTM_SC_TOF. */ #define BS_FTM_SC_TOF (1U) /*!< Bit field size in bits for FTM_SC_TOF. */ /*! @brief Read current value of the FTM_SC_TOF field. */ #define BR_FTM_SC_TOF(x) (BITBAND_ACCESS32(HW_FTM_SC_ADDR(x), BP_FTM_SC_TOF)) /*! @brief Format value for bitfield FTM_SC_TOF. */ #define BF_FTM_SC_TOF(v) ((uint32_t)((uint32_t)(v) << BP_FTM_SC_TOF) & BM_FTM_SC_TOF) /*! @brief Set the TOF field to a new value. */ #define BW_FTM_SC_TOF(x, v) (BITBAND_ACCESS32(HW_FTM_SC_ADDR(x), BP_FTM_SC_TOF) = (v)) /*@}*/ /******************************************************************************* * HW_FTM_CNT - Counter ******************************************************************************/ /*! * @brief HW_FTM_CNT - Counter (RW) * * Reset value: 0x00000000U * * The CNT register contains the FTM counter value. Reset clears the CNT * register. Writing any value to COUNT updates the counter with its initial value, * CNTIN. When BDM is active, the FTM counter is frozen. This is the value that you * may read. */ typedef union _hw_ftm_cnt { uint32_t U; struct _hw_ftm_cnt_bitfields { uint32_t COUNT : 16; /*!< [15:0] Counter Value */ uint32_t RESERVED0 : 16; /*!< [31:16] */ } B; } hw_ftm_cnt_t; /*! * @name Constants and macros for entire FTM_CNT register */ /*@{*/ #define HW_FTM_CNT_ADDR(x) ((x) + 0x4U) #define HW_FTM_CNT(x) (*(__IO hw_ftm_cnt_t *) HW_FTM_CNT_ADDR(x)) #define HW_FTM_CNT_RD(x) (HW_FTM_CNT(x).U) #define HW_FTM_CNT_WR(x, v) (HW_FTM_CNT(x).U = (v)) #define HW_FTM_CNT_SET(x, v) (HW_FTM_CNT_WR(x, HW_FTM_CNT_RD(x) | (v))) #define HW_FTM_CNT_CLR(x, v) (HW_FTM_CNT_WR(x, HW_FTM_CNT_RD(x) & ~(v))) #define HW_FTM_CNT_TOG(x, v) (HW_FTM_CNT_WR(x, HW_FTM_CNT_RD(x) ^ (v))) /*@}*/ /* * Constants & macros for individual FTM_CNT bitfields */ /*! * @name Register FTM_CNT, field COUNT[15:0] (RW) */ /*@{*/ #define BP_FTM_CNT_COUNT (0U) /*!< Bit position for FTM_CNT_COUNT. */ #define BM_FTM_CNT_COUNT (0x0000FFFFU) /*!< Bit mask for FTM_CNT_COUNT. */ #define BS_FTM_CNT_COUNT (16U) /*!< Bit field size in bits for FTM_CNT_COUNT. */ /*! @brief Read current value of the FTM_CNT_COUNT field. */ #define BR_FTM_CNT_COUNT(x) (HW_FTM_CNT(x).B.COUNT) /*! @brief Format value for bitfield FTM_CNT_COUNT. */ #define BF_FTM_CNT_COUNT(v) ((uint32_t)((uint32_t)(v) << BP_FTM_CNT_COUNT) & BM_FTM_CNT_COUNT) /*! @brief Set the COUNT field to a new value. */ #define BW_FTM_CNT_COUNT(x, v) (HW_FTM_CNT_WR(x, (HW_FTM_CNT_RD(x) & ~BM_FTM_CNT_COUNT) | BF_FTM_CNT_COUNT(v))) /*@}*/ /******************************************************************************* * HW_FTM_MOD - Modulo ******************************************************************************/ /*! * @brief HW_FTM_MOD - Modulo (RW) * * Reset value: 0x00000000U * * The Modulo register contains the modulo value for the FTM counter. After the * FTM counter reaches the modulo value, the overflow flag (TOF) becomes set at * the next clock, and the next value of FTM counter depends on the selected * counting method; see Counter. Writing to the MOD register latches the value into a * buffer. The MOD register is updated with the value of its write buffer * according to Registers updated from write buffers. If FTMEN = 0, this write coherency * mechanism may be manually reset by writing to the SC register whether BDM is * active or not. Initialize the FTM counter, by writing to CNT, before writing * to the MOD register to avoid confusion about when the first counter overflow * will occur. */ typedef union _hw_ftm_mod { uint32_t U; struct _hw_ftm_mod_bitfields { uint32_t MOD : 16; /*!< [15:0] */ uint32_t RESERVED0 : 16; /*!< [31:16] */ } B; } hw_ftm_mod_t; /*! * @name Constants and macros for entire FTM_MOD register */ /*@{*/ #define HW_FTM_MOD_ADDR(x) ((x) + 0x8U) #define HW_FTM_MOD(x) (*(__IO hw_ftm_mod_t *) HW_FTM_MOD_ADDR(x)) #define HW_FTM_MOD_RD(x) (HW_FTM_MOD(x).U) #define HW_FTM_MOD_WR(x, v) (HW_FTM_MOD(x).U = (v)) #define HW_FTM_MOD_SET(x, v) (HW_FTM_MOD_WR(x, HW_FTM_MOD_RD(x) | (v))) #define HW_FTM_MOD_CLR(x, v) (HW_FTM_MOD_WR(x, HW_FTM_MOD_RD(x) & ~(v))) #define HW_FTM_MOD_TOG(x, v) (HW_FTM_MOD_WR(x, HW_FTM_MOD_RD(x) ^ (v))) /*@}*/ /* * Constants & macros for individual FTM_MOD bitfields */ /*! * @name Register FTM_MOD, field MOD[15:0] (RW) * * Modulo Value */ /*@{*/ #define BP_FTM_MOD_MOD (0U) /*!< Bit position for FTM_MOD_MOD. */ #define BM_FTM_MOD_MOD (0x0000FFFFU) /*!< Bit mask for FTM_MOD_MOD. */ #define BS_FTM_MOD_MOD (16U) /*!< Bit field size in bits for FTM_MOD_MOD. */ /*! @brief Read current value of the FTM_MOD_MOD field. */ #define BR_FTM_MOD_MOD(x) (HW_FTM_MOD(x).B.MOD) /*! @brief Format value for bitfield FTM_MOD_MOD. */ #define BF_FTM_MOD_MOD(v) ((uint32_t)((uint32_t)(v) << BP_FTM_MOD_MOD) & BM_FTM_MOD_MOD) /*! @brief Set the MOD field to a new value. */ #define BW_FTM_MOD_MOD(x, v) (HW_FTM_MOD_WR(x, (HW_FTM_MOD_RD(x) & ~BM_FTM_MOD_MOD) | BF_FTM_MOD_MOD(v))) /*@}*/ /******************************************************************************* * HW_FTM_CnSC - Channel (n) Status And Control ******************************************************************************/ /*! * @brief HW_FTM_CnSC - Channel (n) Status And Control (RW) * * Reset value: 0x00000000U * * CnSC contains the channel-interrupt-status flag and control bits used to * configure the interrupt enable, channel configuration, and pin function. Mode, * edge, and level selection DECAPEN COMBINE CPWMS MSnB:MSnA ELSnB:ELSnA Mode * Configuration X X X XX 0 Pin not used for FTM-revert the channel pin to general * purpose I/O or other peripheral control 0 0 0 0 1 Input Capture Capture on Rising * Edge Only 10 Capture on Falling Edge Only 11 Capture on Rising or Falling Edge * 1 1 Output Compare Toggle Output on match 10 Clear Output on match 11 Set * Output on match 1X 10 Edge-Aligned PWM High-true pulses (clear Output on match) * X1 Low-true pulses (set Output on match) 1 XX 10 Center-Aligned PWM High-true * pulses (clear Output on match-up) X1 Low-true pulses (set Output on match-up) 1 * 0 XX 10 Combine PWM High-true pulses (set on channel (n) match, and clear on * channel (n+1) match) X1 Low-true pulses (clear on channel (n) match, and set * on channel (n+1) match) 1 0 0 X0 See the following table (#ModeSel2Table). Dual * Edge Capture One-Shot Capture mode X1 Continuous Capture mode Dual Edge * Capture mode - edge polarity selection ELSnB ELSnA Channel Port Enable Detected * Edges 0 0 Disabled No edge 0 1 Enabled Rising edge 1 0 Enabled Falling edge 1 1 * Enabled Rising and falling edges */ typedef union _hw_ftm_cnsc { uint32_t U; struct _hw_ftm_cnsc_bitfields { uint32_t DMA : 1; /*!< [0] DMA Enable */ uint32_t RESERVED0 : 1; /*!< [1] */ uint32_t ELSA : 1; /*!< [2] Edge or Level Select */ uint32_t ELSB : 1; /*!< [3] Edge or Level Select */ uint32_t MSA : 1; /*!< [4] Channel Mode Select */ uint32_t MSB : 1; /*!< [5] Channel Mode Select */ uint32_t CHIE : 1; /*!< [6] Channel Interrupt Enable */ uint32_t CHF : 1; /*!< [7] Channel Flag */ uint32_t RESERVED1 : 24; /*!< [31:8] */ } B; } hw_ftm_cnsc_t; /*! * @name Constants and macros for entire FTM_CnSC register */ /*@{*/ #define HW_FTM_CnSC_COUNT (8U) #define HW_FTM_CnSC_ADDR(x, n) ((x) + 0xCU + (0x8U * (n))) #define HW_FTM_CnSC(x, n) (*(__IO hw_ftm_cnsc_t *) HW_FTM_CnSC_ADDR(x, n)) #define HW_FTM_CnSC_RD(x, n) (HW_FTM_CnSC(x, n).U) #define HW_FTM_CnSC_WR(x, n, v) (HW_FTM_CnSC(x, n).U = (v)) #define HW_FTM_CnSC_SET(x, n, v) (HW_FTM_CnSC_WR(x, n, HW_FTM_CnSC_RD(x, n) | (v))) #define HW_FTM_CnSC_CLR(x, n, v) (HW_FTM_CnSC_WR(x, n, HW_FTM_CnSC_RD(x, n) & ~(v))) #define HW_FTM_CnSC_TOG(x, n, v) (HW_FTM_CnSC_WR(x, n, HW_FTM_CnSC_RD(x, n) ^ (v))) /*@}*/ /* * Constants & macros for individual FTM_CnSC bitfields */ /*! * @name Register FTM_CnSC, field DMA[0] (RW) * * Enables DMA transfers for the channel. * * Values: * - 0 - Disable DMA transfers. * - 1 - Enable DMA transfers. */ /*@{*/ #define BP_FTM_CnSC_DMA (0U) /*!< Bit position for FTM_CnSC_DMA. */ #define BM_FTM_CnSC_DMA (0x00000001U) /*!< Bit mask for FTM_CnSC_DMA. */ #define BS_FTM_CnSC_DMA (1U) /*!< Bit field size in bits for FTM_CnSC_DMA. */ /*! @brief Read current value of the FTM_CnSC_DMA field. */ #define BR_FTM_CnSC_DMA(x, n) (BITBAND_ACCESS32(HW_FTM_CnSC_ADDR(x, n), BP_FTM_CnSC_DMA)) /*! @brief Format value for bitfield FTM_CnSC_DMA. */ #define BF_FTM_CnSC_DMA(v) ((uint32_t)((uint32_t)(v) << BP_FTM_CnSC_DMA) & BM_FTM_CnSC_DMA) /*! @brief Set the DMA field to a new value. */ #define BW_FTM_CnSC_DMA(x, n, v) (BITBAND_ACCESS32(HW_FTM_CnSC_ADDR(x, n), BP_FTM_CnSC_DMA) = (v)) /*@}*/ /*! * @name Register FTM_CnSC, field ELSA[2] (RW) * * The functionality of ELSB and ELSA depends on the channel mode. See * #ModeSel1Table. This field is write protected. It can be written only when MODE[WPDIS] * = 1. */ /*@{*/ #define BP_FTM_CnSC_ELSA (2U) /*!< Bit position for FTM_CnSC_ELSA. */ #define BM_FTM_CnSC_ELSA (0x00000004U) /*!< Bit mask for FTM_CnSC_ELSA. */ #define BS_FTM_CnSC_ELSA (1U) /*!< Bit field size in bits for FTM_CnSC_ELSA. */ /*! @brief Read current value of the FTM_CnSC_ELSA field. */ #define BR_FTM_CnSC_ELSA(x, n) (BITBAND_ACCESS32(HW_FTM_CnSC_ADDR(x, n), BP_FTM_CnSC_ELSA)) /*! @brief Format value for bitfield FTM_CnSC_ELSA. */ #define BF_FTM_CnSC_ELSA(v) ((uint32_t)((uint32_t)(v) << BP_FTM_CnSC_ELSA) & BM_FTM_CnSC_ELSA) /*! @brief Set the ELSA field to a new value. */ #define BW_FTM_CnSC_ELSA(x, n, v) (BITBAND_ACCESS32(HW_FTM_CnSC_ADDR(x, n), BP_FTM_CnSC_ELSA) = (v)) /*@}*/ /*! * @name Register FTM_CnSC, field ELSB[3] (RW) * * The functionality of ELSB and ELSA depends on the channel mode. See * #ModeSel1Table. This field is write protected. It can be written only when MODE[WPDIS] * = 1. */ /*@{*/ #define BP_FTM_CnSC_ELSB (3U) /*!< Bit position for FTM_CnSC_ELSB. */ #define BM_FTM_CnSC_ELSB (0x00000008U) /*!< Bit mask for FTM_CnSC_ELSB. */ #define BS_FTM_CnSC_ELSB (1U) /*!< Bit field size in bits for FTM_CnSC_ELSB. */ /*! @brief Read current value of the FTM_CnSC_ELSB field. */ #define BR_FTM_CnSC_ELSB(x, n) (BITBAND_ACCESS32(HW_FTM_CnSC_ADDR(x, n), BP_FTM_CnSC_ELSB)) /*! @brief Format value for bitfield FTM_CnSC_ELSB. */ #define BF_FTM_CnSC_ELSB(v) ((uint32_t)((uint32_t)(v) << BP_FTM_CnSC_ELSB) & BM_FTM_CnSC_ELSB) /*! @brief Set the ELSB field to a new value. */ #define BW_FTM_CnSC_ELSB(x, n, v) (BITBAND_ACCESS32(HW_FTM_CnSC_ADDR(x, n), BP_FTM_CnSC_ELSB) = (v)) /*@}*/ /*! * @name Register FTM_CnSC, field MSA[4] (RW) * * Used for further selections in the channel logic. Its functionality is * dependent on the channel mode. See #ModeSel1Table. This field is write protected. It * can be written only when MODE[WPDIS] = 1. */ /*@{*/ #define BP_FTM_CnSC_MSA (4U) /*!< Bit position for FTM_CnSC_MSA. */ #define BM_FTM_CnSC_MSA (0x00000010U) /*!< Bit mask for FTM_CnSC_MSA. */ #define BS_FTM_CnSC_MSA (1U) /*!< Bit field size in bits for FTM_CnSC_MSA. */ /*! @brief Read current value of the FTM_CnSC_MSA field. */ #define BR_FTM_CnSC_MSA(x, n) (BITBAND_ACCESS32(HW_FTM_CnSC_ADDR(x, n), BP_FTM_CnSC_MSA)) /*! @brief Format value for bitfield FTM_CnSC_MSA. */ #define BF_FTM_CnSC_MSA(v) ((uint32_t)((uint32_t)(v) << BP_FTM_CnSC_MSA) & BM_FTM_CnSC_MSA) /*! @brief Set the MSA field to a new value. */ #define BW_FTM_CnSC_MSA(x, n, v) (BITBAND_ACCESS32(HW_FTM_CnSC_ADDR(x, n), BP_FTM_CnSC_MSA) = (v)) /*@}*/ /*! * @name Register FTM_CnSC, field MSB[5] (RW) * * Used for further selections in the channel logic. Its functionality is * dependent on the channel mode. See #ModeSel1Table. This field is write protected. It * can be written only when MODE[WPDIS] = 1. */ /*@{*/ #define BP_FTM_CnSC_MSB (5U) /*!< Bit position for FTM_CnSC_MSB. */ #define BM_FTM_CnSC_MSB (0x00000020U) /*!< Bit mask for FTM_CnSC_MSB. */ #define BS_FTM_CnSC_MSB (1U) /*!< Bit field size in bits for FTM_CnSC_MSB. */ /*! @brief Read current value of the FTM_CnSC_MSB field. */ #define BR_FTM_CnSC_MSB(x, n) (BITBAND_ACCESS32(HW_FTM_CnSC_ADDR(x, n), BP_FTM_CnSC_MSB)) /*! @brief Format value for bitfield FTM_CnSC_MSB. */ #define BF_FTM_CnSC_MSB(v) ((uint32_t)((uint32_t)(v) << BP_FTM_CnSC_MSB) & BM_FTM_CnSC_MSB) /*! @brief Set the MSB field to a new value. */ #define BW_FTM_CnSC_MSB(x, n, v) (BITBAND_ACCESS32(HW_FTM_CnSC_ADDR(x, n), BP_FTM_CnSC_MSB) = (v)) /*@}*/ /*! * @name Register FTM_CnSC, field CHIE[6] (RW) * * Enables channel interrupts. * * Values: * - 0 - Disable channel interrupts. Use software polling. * - 1 - Enable channel interrupts. */ /*@{*/ #define BP_FTM_CnSC_CHIE (6U) /*!< Bit position for FTM_CnSC_CHIE. */ #define BM_FTM_CnSC_CHIE (0x00000040U) /*!< Bit mask for FTM_CnSC_CHIE. */ #define BS_FTM_CnSC_CHIE (1U) /*!< Bit field size in bits for FTM_CnSC_CHIE. */ /*! @brief Read current value of the FTM_CnSC_CHIE field. */ #define BR_FTM_CnSC_CHIE(x, n) (BITBAND_ACCESS32(HW_FTM_CnSC_ADDR(x, n), BP_FTM_CnSC_CHIE)) /*! @brief Format value for bitfield FTM_CnSC_CHIE. */ #define BF_FTM_CnSC_CHIE(v) ((uint32_t)((uint32_t)(v) << BP_FTM_CnSC_CHIE) & BM_FTM_CnSC_CHIE) /*! @brief Set the CHIE field to a new value. */ #define BW_FTM_CnSC_CHIE(x, n, v) (BITBAND_ACCESS32(HW_FTM_CnSC_ADDR(x, n), BP_FTM_CnSC_CHIE) = (v)) /*@}*/ /*! * @name Register FTM_CnSC, field CHF[7] (ROWZ) * * Set by hardware when an event occurs on the channel. CHF is cleared by * reading the CSC register while CHnF is set and then writing a 0 to the CHF bit. * Writing a 1 to CHF has no effect. If another event occurs between the read and * write operations, the write operation has no effect; therefore, CHF remains set * indicating an event has occurred. In this case a CHF interrupt request is not * lost due to the clearing sequence for a previous CHF. * * Values: * - 0 - No channel event has occurred. * - 1 - A channel event has occurred. */ /*@{*/ #define BP_FTM_CnSC_CHF (7U) /*!< Bit position for FTM_CnSC_CHF. */ #define BM_FTM_CnSC_CHF (0x00000080U) /*!< Bit mask for FTM_CnSC_CHF. */ #define BS_FTM_CnSC_CHF (1U) /*!< Bit field size in bits for FTM_CnSC_CHF. */ /*! @brief Read current value of the FTM_CnSC_CHF field. */ #define BR_FTM_CnSC_CHF(x, n) (BITBAND_ACCESS32(HW_FTM_CnSC_ADDR(x, n), BP_FTM_CnSC_CHF)) /*! @brief Format value for bitfield FTM_CnSC_CHF. */ #define BF_FTM_CnSC_CHF(v) ((uint32_t)((uint32_t)(v) << BP_FTM_CnSC_CHF) & BM_FTM_CnSC_CHF) /*! @brief Set the CHF field to a new value. */ #define BW_FTM_CnSC_CHF(x, n, v) (BITBAND_ACCESS32(HW_FTM_CnSC_ADDR(x, n), BP_FTM_CnSC_CHF) = (v)) /*@}*/ /******************************************************************************* * HW_FTM_CnV - Channel (n) Value ******************************************************************************/ /*! * @brief HW_FTM_CnV - Channel (n) Value (RW) * * Reset value: 0x00000000U * * These registers contain the captured FTM counter value for the input modes or * the match value for the output modes. In Input Capture, Capture Test, and * Dual Edge Capture modes, any write to a CnV register is ignored. In output modes, * writing to a CnV register latches the value into a buffer. A CnV register is * updated with the value of its write buffer according to Registers updated from * write buffers. If FTMEN = 0, this write coherency mechanism may be manually * reset by writing to the CnSC register whether BDM mode is active or not. */ typedef union _hw_ftm_cnv { uint32_t U; struct _hw_ftm_cnv_bitfields { uint32_t VAL : 16; /*!< [15:0] Channel Value */ uint32_t RESERVED0 : 16; /*!< [31:16] */ } B; } hw_ftm_cnv_t; /*! * @name Constants and macros for entire FTM_CnV register */ /*@{*/ #define HW_FTM_CnV_COUNT (8U) #define HW_FTM_CnV_ADDR(x, n) ((x) + 0x10U + (0x8U * (n))) #define HW_FTM_CnV(x, n) (*(__IO hw_ftm_cnv_t *) HW_FTM_CnV_ADDR(x, n)) #define HW_FTM_CnV_RD(x, n) (HW_FTM_CnV(x, n).U) #define HW_FTM_CnV_WR(x, n, v) (HW_FTM_CnV(x, n).U = (v)) #define HW_FTM_CnV_SET(x, n, v) (HW_FTM_CnV_WR(x, n, HW_FTM_CnV_RD(x, n) | (v))) #define HW_FTM_CnV_CLR(x, n, v) (HW_FTM_CnV_WR(x, n, HW_FTM_CnV_RD(x, n) & ~(v))) #define HW_FTM_CnV_TOG(x, n, v) (HW_FTM_CnV_WR(x, n, HW_FTM_CnV_RD(x, n) ^ (v))) /*@}*/ /* * Constants & macros for individual FTM_CnV bitfields */ /*! * @name Register FTM_CnV, field VAL[15:0] (RW) * * Captured FTM counter value of the input modes or the match value for the * output modes */ /*@{*/ #define BP_FTM_CnV_VAL (0U) /*!< Bit position for FTM_CnV_VAL. */ #define BM_FTM_CnV_VAL (0x0000FFFFU) /*!< Bit mask for FTM_CnV_VAL. */ #define BS_FTM_CnV_VAL (16U) /*!< Bit field size in bits for FTM_CnV_VAL. */ /*! @brief Read current value of the FTM_CnV_VAL field. */ #define BR_FTM_CnV_VAL(x, n) (HW_FTM_CnV(x, n).B.VAL) /*! @brief Format value for bitfield FTM_CnV_VAL. */ #define BF_FTM_CnV_VAL(v) ((uint32_t)((uint32_t)(v) << BP_FTM_CnV_VAL) & BM_FTM_CnV_VAL) /*! @brief Set the VAL field to a new value. */ #define BW_FTM_CnV_VAL(x, n, v) (HW_FTM_CnV_WR(x, n, (HW_FTM_CnV_RD(x, n) & ~BM_FTM_CnV_VAL) | BF_FTM_CnV_VAL(v))) /*@}*/ /******************************************************************************* * HW_FTM_CNTIN - Counter Initial Value ******************************************************************************/ /*! * @brief HW_FTM_CNTIN - Counter Initial Value (RW) * * Reset value: 0x00000000U * * The Counter Initial Value register contains the initial value for the FTM * counter. Writing to the CNTIN register latches the value into a buffer. The CNTIN * register is updated with the value of its write buffer according to Registers * updated from write buffers. When the FTM clock is initially selected, by * writing a non-zero value to the CLKS bits, the FTM counter starts with the value * 0x0000. To avoid this behavior, before the first write to select the FTM clock, * write the new value to the the CNTIN register and then initialize the FTM * counter by writing any value to the CNT register. */ typedef union _hw_ftm_cntin { uint32_t U; struct _hw_ftm_cntin_bitfields { uint32_t INIT : 16; /*!< [15:0] */ uint32_t RESERVED0 : 16; /*!< [31:16] */ } B; } hw_ftm_cntin_t; /*! * @name Constants and macros for entire FTM_CNTIN register */ /*@{*/ #define HW_FTM_CNTIN_ADDR(x) ((x) + 0x4CU) #define HW_FTM_CNTIN(x) (*(__IO hw_ftm_cntin_t *) HW_FTM_CNTIN_ADDR(x)) #define HW_FTM_CNTIN_RD(x) (HW_FTM_CNTIN(x).U) #define HW_FTM_CNTIN_WR(x, v) (HW_FTM_CNTIN(x).U = (v)) #define HW_FTM_CNTIN_SET(x, v) (HW_FTM_CNTIN_WR(x, HW_FTM_CNTIN_RD(x) | (v))) #define HW_FTM_CNTIN_CLR(x, v) (HW_FTM_CNTIN_WR(x, HW_FTM_CNTIN_RD(x) & ~(v))) #define HW_FTM_CNTIN_TOG(x, v) (HW_FTM_CNTIN_WR(x, HW_FTM_CNTIN_RD(x) ^ (v))) /*@}*/ /* * Constants & macros for individual FTM_CNTIN bitfields */ /*! * @name Register FTM_CNTIN, field INIT[15:0] (RW) * * Initial Value Of The FTM Counter */ /*@{*/ #define BP_FTM_CNTIN_INIT (0U) /*!< Bit position for FTM_CNTIN_INIT. */ #define BM_FTM_CNTIN_INIT (0x0000FFFFU) /*!< Bit mask for FTM_CNTIN_INIT. */ #define BS_FTM_CNTIN_INIT (16U) /*!< Bit field size in bits for FTM_CNTIN_INIT. */ /*! @brief Read current value of the FTM_CNTIN_INIT field. */ #define BR_FTM_CNTIN_INIT(x) (HW_FTM_CNTIN(x).B.INIT) /*! @brief Format value for bitfield FTM_CNTIN_INIT. */ #define BF_FTM_CNTIN_INIT(v) ((uint32_t)((uint32_t)(v) << BP_FTM_CNTIN_INIT) & BM_FTM_CNTIN_INIT) /*! @brief Set the INIT field to a new value. */ #define BW_FTM_CNTIN_INIT(x, v) (HW_FTM_CNTIN_WR(x, (HW_FTM_CNTIN_RD(x) & ~BM_FTM_CNTIN_INIT) | BF_FTM_CNTIN_INIT(v))) /*@}*/ /******************************************************************************* * HW_FTM_STATUS - Capture And Compare Status ******************************************************************************/ /*! * @brief HW_FTM_STATUS - Capture And Compare Status (RW) * * Reset value: 0x00000000U * * The STATUS register contains a copy of the status flag CHnF bit in CnSC for * each FTM channel for software convenience. Each CHnF bit in STATUS is a mirror * of CHnF bit in CnSC. All CHnF bits can be checked using only one read of * STATUS. All CHnF bits can be cleared by reading STATUS followed by writing 0x00 to * STATUS. Hardware sets the individual channel flags when an event occurs on the * channel. CHnF is cleared by reading STATUS while CHnF is set and then writing * a 0 to the CHnF bit. Writing a 1 to CHnF has no effect. If another event * occurs between the read and write operations, the write operation has no effect; * therefore, CHnF remains set indicating an event has occurred. In this case, a * CHnF interrupt request is not lost due to the clearing sequence for a previous * CHnF. The STATUS register should be used only in Combine mode. */ typedef union _hw_ftm_status { uint32_t U; struct _hw_ftm_status_bitfields { uint32_t CH0F : 1; /*!< [0] Channel 0 Flag */ uint32_t CH1F : 1; /*!< [1] Channel 1 Flag */ uint32_t CH2F : 1; /*!< [2] Channel 2 Flag */ uint32_t CH3F : 1; /*!< [3] Channel 3 Flag */ uint32_t CH4F : 1; /*!< [4] Channel 4 Flag */ uint32_t CH5F : 1; /*!< [5] Channel 5 Flag */ uint32_t CH6F : 1; /*!< [6] Channel 6 Flag */ uint32_t CH7F : 1; /*!< [7] Channel 7 Flag */ uint32_t RESERVED0 : 24; /*!< [31:8] */ } B; } hw_ftm_status_t; /*! * @name Constants and macros for entire FTM_STATUS register */ /*@{*/ #define HW_FTM_STATUS_ADDR(x) ((x) + 0x50U) #define HW_FTM_STATUS(x) (*(__IO hw_ftm_status_t *) HW_FTM_STATUS_ADDR(x)) #define HW_FTM_STATUS_RD(x) (HW_FTM_STATUS(x).U) #define HW_FTM_STATUS_WR(x, v) (HW_FTM_STATUS(x).U = (v)) #define HW_FTM_STATUS_SET(x, v) (HW_FTM_STATUS_WR(x, HW_FTM_STATUS_RD(x) | (v))) #define HW_FTM_STATUS_CLR(x, v) (HW_FTM_STATUS_WR(x, HW_FTM_STATUS_RD(x) & ~(v))) #define HW_FTM_STATUS_TOG(x, v) (HW_FTM_STATUS_WR(x, HW_FTM_STATUS_RD(x) ^ (v))) /*@}*/ /* * Constants & macros for individual FTM_STATUS bitfields */ /*! * @name Register FTM_STATUS, field CH0F[0] (W1C) * * See the register description. * * Values: * - 0 - No channel event has occurred. * - 1 - A channel event has occurred. */ /*@{*/ #define BP_FTM_STATUS_CH0F (0U) /*!< Bit position for FTM_STATUS_CH0F. */ #define BM_FTM_STATUS_CH0F (0x00000001U) /*!< Bit mask for FTM_STATUS_CH0F. */ #define BS_FTM_STATUS_CH0F (1U) /*!< Bit field size in bits for FTM_STATUS_CH0F. */ /*! @brief Read current value of the FTM_STATUS_CH0F field. */ #define BR_FTM_STATUS_CH0F(x) (BITBAND_ACCESS32(HW_FTM_STATUS_ADDR(x), BP_FTM_STATUS_CH0F)) /*! @brief Format value for bitfield FTM_STATUS_CH0F. */ #define BF_FTM_STATUS_CH0F(v) ((uint32_t)((uint32_t)(v) << BP_FTM_STATUS_CH0F) & BM_FTM_STATUS_CH0F) /*! @brief Set the CH0F field to a new value. */ #define BW_FTM_STATUS_CH0F(x, v) (BITBAND_ACCESS32(HW_FTM_STATUS_ADDR(x), BP_FTM_STATUS_CH0F) = (v)) /*@}*/ /*! * @name Register FTM_STATUS, field CH1F[1] (W1C) * * See the register description. * * Values: * - 0 - No channel event has occurred. * - 1 - A channel event has occurred. */ /*@{*/ #define BP_FTM_STATUS_CH1F (1U) /*!< Bit position for FTM_STATUS_CH1F. */ #define BM_FTM_STATUS_CH1F (0x00000002U) /*!< Bit mask for FTM_STATUS_CH1F. */ #define BS_FTM_STATUS_CH1F (1U) /*!< Bit field size in bits for FTM_STATUS_CH1F. */ /*! @brief Read current value of the FTM_STATUS_CH1F field. */ #define BR_FTM_STATUS_CH1F(x) (BITBAND_ACCESS32(HW_FTM_STATUS_ADDR(x), BP_FTM_STATUS_CH1F)) /*! @brief Format value for bitfield FTM_STATUS_CH1F. */ #define BF_FTM_STATUS_CH1F(v) ((uint32_t)((uint32_t)(v) << BP_FTM_STATUS_CH1F) & BM_FTM_STATUS_CH1F) /*! @brief Set the CH1F field to a new value. */ #define BW_FTM_STATUS_CH1F(x, v) (BITBAND_ACCESS32(HW_FTM_STATUS_ADDR(x), BP_FTM_STATUS_CH1F) = (v)) /*@}*/ /*! * @name Register FTM_STATUS, field CH2F[2] (W1C) * * See the register description. * * Values: * - 0 - No channel event has occurred. * - 1 - A channel event has occurred. */ /*@{*/ #define BP_FTM_STATUS_CH2F (2U) /*!< Bit position for FTM_STATUS_CH2F. */ #define BM_FTM_STATUS_CH2F (0x00000004U) /*!< Bit mask for FTM_STATUS_CH2F. */ #define BS_FTM_STATUS_CH2F (1U) /*!< Bit field size in bits for FTM_STATUS_CH2F. */ /*! @brief Read current value of the FTM_STATUS_CH2F field. */ #define BR_FTM_STATUS_CH2F(x) (BITBAND_ACCESS32(HW_FTM_STATUS_ADDR(x), BP_FTM_STATUS_CH2F)) /*! @brief Format value for bitfield FTM_STATUS_CH2F. */ #define BF_FTM_STATUS_CH2F(v) ((uint32_t)((uint32_t)(v) << BP_FTM_STATUS_CH2F) & BM_FTM_STATUS_CH2F) /*! @brief Set the CH2F field to a new value. */ #define BW_FTM_STATUS_CH2F(x, v) (BITBAND_ACCESS32(HW_FTM_STATUS_ADDR(x), BP_FTM_STATUS_CH2F) = (v)) /*@}*/ /*! * @name Register FTM_STATUS, field CH3F[3] (W1C) * * See the register description. * * Values: * - 0 - No channel event has occurred. * - 1 - A channel event has occurred. */ /*@{*/ #define BP_FTM_STATUS_CH3F (3U) /*!< Bit position for FTM_STATUS_CH3F. */ #define BM_FTM_STATUS_CH3F (0x00000008U) /*!< Bit mask for FTM_STATUS_CH3F. */ #define BS_FTM_STATUS_CH3F (1U) /*!< Bit field size in bits for FTM_STATUS_CH3F. */ /*! @brief Read current value of the FTM_STATUS_CH3F field. */ #define BR_FTM_STATUS_CH3F(x) (BITBAND_ACCESS32(HW_FTM_STATUS_ADDR(x), BP_FTM_STATUS_CH3F)) /*! @brief Format value for bitfield FTM_STATUS_CH3F. */ #define BF_FTM_STATUS_CH3F(v) ((uint32_t)((uint32_t)(v) << BP_FTM_STATUS_CH3F) & BM_FTM_STATUS_CH3F) /*! @brief Set the CH3F field to a new value. */ #define BW_FTM_STATUS_CH3F(x, v) (BITBAND_ACCESS32(HW_FTM_STATUS_ADDR(x), BP_FTM_STATUS_CH3F) = (v)) /*@}*/ /*! * @name Register FTM_STATUS, field CH4F[4] (W1C) * * See the register description. * * Values: * - 0 - No channel event has occurred. * - 1 - A channel event has occurred. */ /*@{*/ #define BP_FTM_STATUS_CH4F (4U) /*!< Bit position for FTM_STATUS_CH4F. */ #define BM_FTM_STATUS_CH4F (0x00000010U) /*!< Bit mask for FTM_STATUS_CH4F. */ #define BS_FTM_STATUS_CH4F (1U) /*!< Bit field size in bits for FTM_STATUS_CH4F. */ /*! @brief Read current value of the FTM_STATUS_CH4F field. */ #define BR_FTM_STATUS_CH4F(x) (BITBAND_ACCESS32(HW_FTM_STATUS_ADDR(x), BP_FTM_STATUS_CH4F)) /*! @brief Format value for bitfield FTM_STATUS_CH4F. */ #define BF_FTM_STATUS_CH4F(v) ((uint32_t)((uint32_t)(v) << BP_FTM_STATUS_CH4F) & BM_FTM_STATUS_CH4F) /*! @brief Set the CH4F field to a new value. */ #define BW_FTM_STATUS_CH4F(x, v) (BITBAND_ACCESS32(HW_FTM_STATUS_ADDR(x), BP_FTM_STATUS_CH4F) = (v)) /*@}*/ /*! * @name Register FTM_STATUS, field CH5F[5] (W1C) * * See the register description. * * Values: * - 0 - No channel event has occurred. * - 1 - A channel event has occurred. */ /*@{*/ #define BP_FTM_STATUS_CH5F (5U) /*!< Bit position for FTM_STATUS_CH5F. */ #define BM_FTM_STATUS_CH5F (0x00000020U) /*!< Bit mask for FTM_STATUS_CH5F. */ #define BS_FTM_STATUS_CH5F (1U) /*!< Bit field size in bits for FTM_STATUS_CH5F. */ /*! @brief Read current value of the FTM_STATUS_CH5F field. */ #define BR_FTM_STATUS_CH5F(x) (BITBAND_ACCESS32(HW_FTM_STATUS_ADDR(x), BP_FTM_STATUS_CH5F)) /*! @brief Format value for bitfield FTM_STATUS_CH5F. */ #define BF_FTM_STATUS_CH5F(v) ((uint32_t)((uint32_t)(v) << BP_FTM_STATUS_CH5F) & BM_FTM_STATUS_CH5F) /*! @brief Set the CH5F field to a new value. */ #define BW_FTM_STATUS_CH5F(x, v) (BITBAND_ACCESS32(HW_FTM_STATUS_ADDR(x), BP_FTM_STATUS_CH5F) = (v)) /*@}*/ /*! * @name Register FTM_STATUS, field CH6F[6] (W1C) * * See the register description. * * Values: * - 0 - No channel event has occurred. * - 1 - A channel event has occurred. */ /*@{*/ #define BP_FTM_STATUS_CH6F (6U) /*!< Bit position for FTM_STATUS_CH6F. */ #define BM_FTM_STATUS_CH6F (0x00000040U) /*!< Bit mask for FTM_STATUS_CH6F. */ #define BS_FTM_STATUS_CH6F (1U) /*!< Bit field size in bits for FTM_STATUS_CH6F. */ /*! @brief Read current value of the FTM_STATUS_CH6F field. */ #define BR_FTM_STATUS_CH6F(x) (BITBAND_ACCESS32(HW_FTM_STATUS_ADDR(x), BP_FTM_STATUS_CH6F)) /*! @brief Format value for bitfield FTM_STATUS_CH6F. */ #define BF_FTM_STATUS_CH6F(v) ((uint32_t)((uint32_t)(v) << BP_FTM_STATUS_CH6F) & BM_FTM_STATUS_CH6F) /*! @brief Set the CH6F field to a new value. */ #define BW_FTM_STATUS_CH6F(x, v) (BITBAND_ACCESS32(HW_FTM_STATUS_ADDR(x), BP_FTM_STATUS_CH6F) = (v)) /*@}*/ /*! * @name Register FTM_STATUS, field CH7F[7] (W1C) * * See the register description. * * Values: * - 0 - No channel event has occurred. * - 1 - A channel event has occurred. */ /*@{*/ #define BP_FTM_STATUS_CH7F (7U) /*!< Bit position for FTM_STATUS_CH7F. */ #define BM_FTM_STATUS_CH7F (0x00000080U) /*!< Bit mask for FTM_STATUS_CH7F. */ #define BS_FTM_STATUS_CH7F (1U) /*!< Bit field size in bits for FTM_STATUS_CH7F. */ /*! @brief Read current value of the FTM_STATUS_CH7F field. */ #define BR_FTM_STATUS_CH7F(x) (BITBAND_ACCESS32(HW_FTM_STATUS_ADDR(x), BP_FTM_STATUS_CH7F)) /*! @brief Format value for bitfield FTM_STATUS_CH7F. */ #define BF_FTM_STATUS_CH7F(v) ((uint32_t)((uint32_t)(v) << BP_FTM_STATUS_CH7F) & BM_FTM_STATUS_CH7F) /*! @brief Set the CH7F field to a new value. */ #define BW_FTM_STATUS_CH7F(x, v) (BITBAND_ACCESS32(HW_FTM_STATUS_ADDR(x), BP_FTM_STATUS_CH7F) = (v)) /*@}*/ /******************************************************************************* * HW_FTM_MODE - Features Mode Selection ******************************************************************************/ /*! * @brief HW_FTM_MODE - Features Mode Selection (RW) * * Reset value: 0x00000004U * * This register contains the global enable bit for FTM-specific features and * the control bits used to configure: Fault control mode and interrupt Capture * Test mode PWM synchronization Write protection Channel output initialization * These controls relate to all channels within this module. */ typedef union _hw_ftm_mode { uint32_t U; struct _hw_ftm_mode_bitfields { uint32_t FTMEN : 1; /*!< [0] FTM Enable */ uint32_t INIT : 1; /*!< [1] Initialize The Channels Output */ uint32_t WPDIS : 1; /*!< [2] Write Protection Disable */ uint32_t PWMSYNC : 1; /*!< [3] PWM Synchronization Mode */ uint32_t CAPTEST : 1; /*!< [4] Capture Test Mode Enable */ uint32_t FAULTM : 2; /*!< [6:5] Fault Control Mode */ uint32_t FAULTIE : 1; /*!< [7] Fault Interrupt Enable */ uint32_t RESERVED0 : 24; /*!< [31:8] */ } B; } hw_ftm_mode_t; /*! * @name Constants and macros for entire FTM_MODE register */ /*@{*/ #define HW_FTM_MODE_ADDR(x) ((x) + 0x54U) #define HW_FTM_MODE(x) (*(__IO hw_ftm_mode_t *) HW_FTM_MODE_ADDR(x)) #define HW_FTM_MODE_RD(x) (HW_FTM_MODE(x).U) #define HW_FTM_MODE_WR(x, v) (HW_FTM_MODE(x).U = (v)) #define HW_FTM_MODE_SET(x, v) (HW_FTM_MODE_WR(x, HW_FTM_MODE_RD(x) | (v))) #define HW_FTM_MODE_CLR(x, v) (HW_FTM_MODE_WR(x, HW_FTM_MODE_RD(x) & ~(v))) #define HW_FTM_MODE_TOG(x, v) (HW_FTM_MODE_WR(x, HW_FTM_MODE_RD(x) ^ (v))) /*@}*/ /* * Constants & macros for individual FTM_MODE bitfields */ /*! * @name Register FTM_MODE, field FTMEN[0] (RW) * * This field is write protected. It can be written only when MODE[WPDIS] = 1. * * Values: * - 0 - Only the TPM-compatible registers (first set of registers) can be used * without any restriction. Do not use the FTM-specific registers. * - 1 - All registers including the FTM-specific registers (second set of * registers) are available for use with no restrictions. */ /*@{*/ #define BP_FTM_MODE_FTMEN (0U) /*!< Bit position for FTM_MODE_FTMEN. */ #define BM_FTM_MODE_FTMEN (0x00000001U) /*!< Bit mask for FTM_MODE_FTMEN. */ #define BS_FTM_MODE_FTMEN (1U) /*!< Bit field size in bits for FTM_MODE_FTMEN. */ /*! @brief Read current value of the FTM_MODE_FTMEN field. */ #define BR_FTM_MODE_FTMEN(x) (BITBAND_ACCESS32(HW_FTM_MODE_ADDR(x), BP_FTM_MODE_FTMEN)) /*! @brief Format value for bitfield FTM_MODE_FTMEN. */ #define BF_FTM_MODE_FTMEN(v) ((uint32_t)((uint32_t)(v) << BP_FTM_MODE_FTMEN) & BM_FTM_MODE_FTMEN) /*! @brief Set the FTMEN field to a new value. */ #define BW_FTM_MODE_FTMEN(x, v) (BITBAND_ACCESS32(HW_FTM_MODE_ADDR(x), BP_FTM_MODE_FTMEN) = (v)) /*@}*/ /*! * @name Register FTM_MODE, field INIT[1] (RW) * * When a 1 is written to INIT bit the channels output is initialized according * to the state of their corresponding bit in the OUTINIT register. Writing a 0 * to INIT bit has no effect. The INIT bit is always read as 0. */ /*@{*/ #define BP_FTM_MODE_INIT (1U) /*!< Bit position for FTM_MODE_INIT. */ #define BM_FTM_MODE_INIT (0x00000002U) /*!< Bit mask for FTM_MODE_INIT. */ #define BS_FTM_MODE_INIT (1U) /*!< Bit field size in bits for FTM_MODE_INIT. */ /*! @brief Read current value of the FTM_MODE_INIT field. */ #define BR_FTM_MODE_INIT(x) (BITBAND_ACCESS32(HW_FTM_MODE_ADDR(x), BP_FTM_MODE_INIT)) /*! @brief Format value for bitfield FTM_MODE_INIT. */ #define BF_FTM_MODE_INIT(v) ((uint32_t)((uint32_t)(v) << BP_FTM_MODE_INIT) & BM_FTM_MODE_INIT) /*! @brief Set the INIT field to a new value. */ #define BW_FTM_MODE_INIT(x, v) (BITBAND_ACCESS32(HW_FTM_MODE_ADDR(x), BP_FTM_MODE_INIT) = (v)) /*@}*/ /*! * @name Register FTM_MODE, field WPDIS[2] (RW) * * When write protection is enabled (WPDIS = 0), write protected bits cannot be * written. When write protection is disabled (WPDIS = 1), write protected bits * can be written. The WPDIS bit is the negation of the WPEN bit. WPDIS is cleared * when 1 is written to WPEN. WPDIS is set when WPEN bit is read as a 1 and then * 1 is written to WPDIS. Writing 0 to WPDIS has no effect. * * Values: * - 0 - Write protection is enabled. * - 1 - Write protection is disabled. */ /*@{*/ #define BP_FTM_MODE_WPDIS (2U) /*!< Bit position for FTM_MODE_WPDIS. */ #define BM_FTM_MODE_WPDIS (0x00000004U) /*!< Bit mask for FTM_MODE_WPDIS. */ #define BS_FTM_MODE_WPDIS (1U) /*!< Bit field size in bits for FTM_MODE_WPDIS. */ /*! @brief Read current value of the FTM_MODE_WPDIS field. */ #define BR_FTM_MODE_WPDIS(x) (BITBAND_ACCESS32(HW_FTM_MODE_ADDR(x), BP_FTM_MODE_WPDIS)) /*! @brief Format value for bitfield FTM_MODE_WPDIS. */ #define BF_FTM_MODE_WPDIS(v) ((uint32_t)((uint32_t)(v) << BP_FTM_MODE_WPDIS) & BM_FTM_MODE_WPDIS) /*! @brief Set the WPDIS field to a new value. */ #define BW_FTM_MODE_WPDIS(x, v) (BITBAND_ACCESS32(HW_FTM_MODE_ADDR(x), BP_FTM_MODE_WPDIS) = (v)) /*@}*/ /*! * @name Register FTM_MODE, field PWMSYNC[3] (RW) * * Selects which triggers can be used by MOD, CnV, OUTMASK, and FTM counter * synchronization. See PWM synchronization. The PWMSYNC bit configures the * synchronization when SYNCMODE is 0. * * Values: * - 0 - No restrictions. Software and hardware triggers can be used by MOD, * CnV, OUTMASK, and FTM counter synchronization. * - 1 - Software trigger can only be used by MOD and CnV synchronization, and * hardware triggers can only be used by OUTMASK and FTM counter * synchronization. */ /*@{*/ #define BP_FTM_MODE_PWMSYNC (3U) /*!< Bit position for FTM_MODE_PWMSYNC. */ #define BM_FTM_MODE_PWMSYNC (0x00000008U) /*!< Bit mask for FTM_MODE_PWMSYNC. */ #define BS_FTM_MODE_PWMSYNC (1U) /*!< Bit field size in bits for FTM_MODE_PWMSYNC. */ /*! @brief Read current value of the FTM_MODE_PWMSYNC field. */ #define BR_FTM_MODE_PWMSYNC(x) (BITBAND_ACCESS32(HW_FTM_MODE_ADDR(x), BP_FTM_MODE_PWMSYNC)) /*! @brief Format value for bitfield FTM_MODE_PWMSYNC. */ #define BF_FTM_MODE_PWMSYNC(v) ((uint32_t)((uint32_t)(v) << BP_FTM_MODE_PWMSYNC) & BM_FTM_MODE_PWMSYNC) /*! @brief Set the PWMSYNC field to a new value. */ #define BW_FTM_MODE_PWMSYNC(x, v) (BITBAND_ACCESS32(HW_FTM_MODE_ADDR(x), BP_FTM_MODE_PWMSYNC) = (v)) /*@}*/ /*! * @name Register FTM_MODE, field CAPTEST[4] (RW) * * Enables the capture test mode. This field is write protected. It can be * written only when MODE[WPDIS] = 1. * * Values: * - 0 - Capture test mode is disabled. * - 1 - Capture test mode is enabled. */ /*@{*/ #define BP_FTM_MODE_CAPTEST (4U) /*!< Bit position for FTM_MODE_CAPTEST. */ #define BM_FTM_MODE_CAPTEST (0x00000010U) /*!< Bit mask for FTM_MODE_CAPTEST. */ #define BS_FTM_MODE_CAPTEST (1U) /*!< Bit field size in bits for FTM_MODE_CAPTEST. */ /*! @brief Read current value of the FTM_MODE_CAPTEST field. */ #define BR_FTM_MODE_CAPTEST(x) (BITBAND_ACCESS32(HW_FTM_MODE_ADDR(x), BP_FTM_MODE_CAPTEST)) /*! @brief Format value for bitfield FTM_MODE_CAPTEST. */ #define BF_FTM_MODE_CAPTEST(v) ((uint32_t)((uint32_t)(v) << BP_FTM_MODE_CAPTEST) & BM_FTM_MODE_CAPTEST) /*! @brief Set the CAPTEST field to a new value. */ #define BW_FTM_MODE_CAPTEST(x, v) (BITBAND_ACCESS32(HW_FTM_MODE_ADDR(x), BP_FTM_MODE_CAPTEST) = (v)) /*@}*/ /*! * @name Register FTM_MODE, field FAULTM[6:5] (RW) * * Defines the FTM fault control mode. This field is write protected. It can be * written only when MODE[WPDIS] = 1. * * Values: * - 00 - Fault control is disabled for all channels. * - 01 - Fault control is enabled for even channels only (channels 0, 2, 4, and * 6), and the selected mode is the manual fault clearing. * - 10 - Fault control is enabled for all channels, and the selected mode is * the manual fault clearing. * - 11 - Fault control is enabled for all channels, and the selected mode is * the automatic fault clearing. */ /*@{*/ #define BP_FTM_MODE_FAULTM (5U) /*!< Bit position for FTM_MODE_FAULTM. */ #define BM_FTM_MODE_FAULTM (0x00000060U) /*!< Bit mask for FTM_MODE_FAULTM. */ #define BS_FTM_MODE_FAULTM (2U) /*!< Bit field size in bits for FTM_MODE_FAULTM. */ /*! @brief Read current value of the FTM_MODE_FAULTM field. */ #define BR_FTM_MODE_FAULTM(x) (HW_FTM_MODE(x).B.FAULTM) /*! @brief Format value for bitfield FTM_MODE_FAULTM. */ #define BF_FTM_MODE_FAULTM(v) ((uint32_t)((uint32_t)(v) << BP_FTM_MODE_FAULTM) & BM_FTM_MODE_FAULTM) /*! @brief Set the FAULTM field to a new value. */ #define BW_FTM_MODE_FAULTM(x, v) (HW_FTM_MODE_WR(x, (HW_FTM_MODE_RD(x) & ~BM_FTM_MODE_FAULTM) | BF_FTM_MODE_FAULTM(v))) /*@}*/ /*! * @name Register FTM_MODE, field FAULTIE[7] (RW) * * Enables the generation of an interrupt when a fault is detected by FTM and * the FTM fault control is enabled. * * Values: * - 0 - Fault control interrupt is disabled. * - 1 - Fault control interrupt is enabled. */ /*@{*/ #define BP_FTM_MODE_FAULTIE (7U) /*!< Bit position for FTM_MODE_FAULTIE. */ #define BM_FTM_MODE_FAULTIE (0x00000080U) /*!< Bit mask for FTM_MODE_FAULTIE. */ #define BS_FTM_MODE_FAULTIE (1U) /*!< Bit field size in bits for FTM_MODE_FAULTIE. */ /*! @brief Read current value of the FTM_MODE_FAULTIE field. */ #define BR_FTM_MODE_FAULTIE(x) (BITBAND_ACCESS32(HW_FTM_MODE_ADDR(x), BP_FTM_MODE_FAULTIE)) /*! @brief Format value for bitfield FTM_MODE_FAULTIE. */ #define BF_FTM_MODE_FAULTIE(v) ((uint32_t)((uint32_t)(v) << BP_FTM_MODE_FAULTIE) & BM_FTM_MODE_FAULTIE) /*! @brief Set the FAULTIE field to a new value. */ #define BW_FTM_MODE_FAULTIE(x, v) (BITBAND_ACCESS32(HW_FTM_MODE_ADDR(x), BP_FTM_MODE_FAULTIE) = (v)) /*@}*/ /******************************************************************************* * HW_FTM_SYNC - Synchronization ******************************************************************************/ /*! * @brief HW_FTM_SYNC - Synchronization (RW) * * Reset value: 0x00000000U * * This register configures the PWM synchronization. A synchronization event can * perform the synchronized update of MOD, CV, and OUTMASK registers with the * value of their write buffer and the FTM counter initialization. The software * trigger, SWSYNC bit, and hardware triggers TRIG0, TRIG1, and TRIG2 bits have a * potential conflict if used together when SYNCMODE = 0. Use only hardware or * software triggers but not both at the same time, otherwise unpredictable behavior * is likely to happen. The selection of the loading point, CNTMAX and CNTMIN * bits, is intended to provide the update of MOD, CNTIN, and CnV registers across * all enabled channels simultaneously. The use of the loading point selection * together with SYNCMODE = 0 and hardware trigger selection, TRIG0, TRIG1, or TRIG2 * bits, is likely to result in unpredictable behavior. The synchronization * event selection also depends on the PWMSYNC (MODE register) and SYNCMODE (SYNCONF * register) bits. See PWM synchronization. */ typedef union _hw_ftm_sync { uint32_t U; struct _hw_ftm_sync_bitfields { uint32_t CNTMIN : 1; /*!< [0] Minimum Loading Point Enable */ uint32_t CNTMAX : 1; /*!< [1] Maximum Loading Point Enable */ uint32_t REINIT : 1; /*!< [2] FTM Counter Reinitialization By * Synchronization (FTM counter synchronization) */ uint32_t SYNCHOM : 1; /*!< [3] Output Mask Synchronization */ uint32_t TRIG0 : 1; /*!< [4] PWM Synchronization Hardware Trigger 0 */ uint32_t TRIG1 : 1; /*!< [5] PWM Synchronization Hardware Trigger 1 */ uint32_t TRIG2 : 1; /*!< [6] PWM Synchronization Hardware Trigger 2 */ uint32_t SWSYNC : 1; /*!< [7] PWM Synchronization Software Trigger */ uint32_t RESERVED0 : 24; /*!< [31:8] */ } B; } hw_ftm_sync_t; /*! * @name Constants and macros for entire FTM_SYNC register */ /*@{*/ #define HW_FTM_SYNC_ADDR(x) ((x) + 0x58U) #define HW_FTM_SYNC(x) (*(__IO hw_ftm_sync_t *) HW_FTM_SYNC_ADDR(x)) #define HW_FTM_SYNC_RD(x) (HW_FTM_SYNC(x).U) #define HW_FTM_SYNC_WR(x, v) (HW_FTM_SYNC(x).U = (v)) #define HW_FTM_SYNC_SET(x, v) (HW_FTM_SYNC_WR(x, HW_FTM_SYNC_RD(x) | (v))) #define HW_FTM_SYNC_CLR(x, v) (HW_FTM_SYNC_WR(x, HW_FTM_SYNC_RD(x) & ~(v))) #define HW_FTM_SYNC_TOG(x, v) (HW_FTM_SYNC_WR(x, HW_FTM_SYNC_RD(x) ^ (v))) /*@}*/ /* * Constants & macros for individual FTM_SYNC bitfields */ /*! * @name Register FTM_SYNC, field CNTMIN[0] (RW) * * Selects the minimum loading point to PWM synchronization. See Boundary cycle * and loading points. If CNTMIN is one, the selected loading point is when the * FTM counter reaches its minimum value (CNTIN register). * * Values: * - 0 - The minimum loading point is disabled. * - 1 - The minimum loading point is enabled. */ /*@{*/ #define BP_FTM_SYNC_CNTMIN (0U) /*!< Bit position for FTM_SYNC_CNTMIN. */ #define BM_FTM_SYNC_CNTMIN (0x00000001U) /*!< Bit mask for FTM_SYNC_CNTMIN. */ #define BS_FTM_SYNC_CNTMIN (1U) /*!< Bit field size in bits for FTM_SYNC_CNTMIN. */ /*! @brief Read current value of the FTM_SYNC_CNTMIN field. */ #define BR_FTM_SYNC_CNTMIN(x) (BITBAND_ACCESS32(HW_FTM_SYNC_ADDR(x), BP_FTM_SYNC_CNTMIN)) /*! @brief Format value for bitfield FTM_SYNC_CNTMIN. */ #define BF_FTM_SYNC_CNTMIN(v) ((uint32_t)((uint32_t)(v) << BP_FTM_SYNC_CNTMIN) & BM_FTM_SYNC_CNTMIN) /*! @brief Set the CNTMIN field to a new value. */ #define BW_FTM_SYNC_CNTMIN(x, v) (BITBAND_ACCESS32(HW_FTM_SYNC_ADDR(x), BP_FTM_SYNC_CNTMIN) = (v)) /*@}*/ /*! * @name Register FTM_SYNC, field CNTMAX[1] (RW) * * Selects the maximum loading point to PWM synchronization. See Boundary cycle * and loading points. If CNTMAX is 1, the selected loading point is when the FTM * counter reaches its maximum value (MOD register). * * Values: * - 0 - The maximum loading point is disabled. * - 1 - The maximum loading point is enabled. */ /*@{*/ #define BP_FTM_SYNC_CNTMAX (1U) /*!< Bit position for FTM_SYNC_CNTMAX. */ #define BM_FTM_SYNC_CNTMAX (0x00000002U) /*!< Bit mask for FTM_SYNC_CNTMAX. */ #define BS_FTM_SYNC_CNTMAX (1U) /*!< Bit field size in bits for FTM_SYNC_CNTMAX. */ /*! @brief Read current value of the FTM_SYNC_CNTMAX field. */ #define BR_FTM_SYNC_CNTMAX(x) (BITBAND_ACCESS32(HW_FTM_SYNC_ADDR(x), BP_FTM_SYNC_CNTMAX)) /*! @brief Format value for bitfield FTM_SYNC_CNTMAX. */ #define BF_FTM_SYNC_CNTMAX(v) ((uint32_t)((uint32_t)(v) << BP_FTM_SYNC_CNTMAX) & BM_FTM_SYNC_CNTMAX) /*! @brief Set the CNTMAX field to a new value. */ #define BW_FTM_SYNC_CNTMAX(x, v) (BITBAND_ACCESS32(HW_FTM_SYNC_ADDR(x), BP_FTM_SYNC_CNTMAX) = (v)) /*@}*/ /*! * @name Register FTM_SYNC, field REINIT[2] (RW) * * Determines if the FTM counter is reinitialized when the selected trigger for * the synchronization is detected. The REINIT bit configures the synchronization * when SYNCMODE is zero. * * Values: * - 0 - FTM counter continues to count normally. * - 1 - FTM counter is updated with its initial value when the selected trigger * is detected. */ /*@{*/ #define BP_FTM_SYNC_REINIT (2U) /*!< Bit position for FTM_SYNC_REINIT. */ #define BM_FTM_SYNC_REINIT (0x00000004U) /*!< Bit mask for FTM_SYNC_REINIT. */ #define BS_FTM_SYNC_REINIT (1U) /*!< Bit field size in bits for FTM_SYNC_REINIT. */ /*! @brief Read current value of the FTM_SYNC_REINIT field. */ #define BR_FTM_SYNC_REINIT(x) (BITBAND_ACCESS32(HW_FTM_SYNC_ADDR(x), BP_FTM_SYNC_REINIT)) /*! @brief Format value for bitfield FTM_SYNC_REINIT. */ #define BF_FTM_SYNC_REINIT(v) ((uint32_t)((uint32_t)(v) << BP_FTM_SYNC_REINIT) & BM_FTM_SYNC_REINIT) /*! @brief Set the REINIT field to a new value. */ #define BW_FTM_SYNC_REINIT(x, v) (BITBAND_ACCESS32(HW_FTM_SYNC_ADDR(x), BP_FTM_SYNC_REINIT) = (v)) /*@}*/ /*! * @name Register FTM_SYNC, field SYNCHOM[3] (RW) * * Selects when the OUTMASK register is updated with the value of its buffer. * * Values: * - 0 - OUTMASK register is updated with the value of its buffer in all rising * edges of the system clock. * - 1 - OUTMASK register is updated with the value of its buffer only by the * PWM synchronization. */ /*@{*/ #define BP_FTM_SYNC_SYNCHOM (3U) /*!< Bit position for FTM_SYNC_SYNCHOM. */ #define BM_FTM_SYNC_SYNCHOM (0x00000008U) /*!< Bit mask for FTM_SYNC_SYNCHOM. */ #define BS_FTM_SYNC_SYNCHOM (1U) /*!< Bit field size in bits for FTM_SYNC_SYNCHOM. */ /*! @brief Read current value of the FTM_SYNC_SYNCHOM field. */ #define BR_FTM_SYNC_SYNCHOM(x) (BITBAND_ACCESS32(HW_FTM_SYNC_ADDR(x), BP_FTM_SYNC_SYNCHOM)) /*! @brief Format value for bitfield FTM_SYNC_SYNCHOM. */ #define BF_FTM_SYNC_SYNCHOM(v) ((uint32_t)((uint32_t)(v) << BP_FTM_SYNC_SYNCHOM) & BM_FTM_SYNC_SYNCHOM) /*! @brief Set the SYNCHOM field to a new value. */ #define BW_FTM_SYNC_SYNCHOM(x, v) (BITBAND_ACCESS32(HW_FTM_SYNC_ADDR(x), BP_FTM_SYNC_SYNCHOM) = (v)) /*@}*/ /*! * @name Register FTM_SYNC, field TRIG0[4] (RW) * * Enables hardware trigger 0 to the PWM synchronization. Hardware trigger 0 * occurs when a rising edge is detected at the trigger 0 input signal. * * Values: * - 0 - Trigger is disabled. * - 1 - Trigger is enabled. */ /*@{*/ #define BP_FTM_SYNC_TRIG0 (4U) /*!< Bit position for FTM_SYNC_TRIG0. */ #define BM_FTM_SYNC_TRIG0 (0x00000010U) /*!< Bit mask for FTM_SYNC_TRIG0. */ #define BS_FTM_SYNC_TRIG0 (1U) /*!< Bit field size in bits for FTM_SYNC_TRIG0. */ /*! @brief Read current value of the FTM_SYNC_TRIG0 field. */ #define BR_FTM_SYNC_TRIG0(x) (BITBAND_ACCESS32(HW_FTM_SYNC_ADDR(x), BP_FTM_SYNC_TRIG0)) /*! @brief Format value for bitfield FTM_SYNC_TRIG0. */ #define BF_FTM_SYNC_TRIG0(v) ((uint32_t)((uint32_t)(v) << BP_FTM_SYNC_TRIG0) & BM_FTM_SYNC_TRIG0) /*! @brief Set the TRIG0 field to a new value. */ #define BW_FTM_SYNC_TRIG0(x, v) (BITBAND_ACCESS32(HW_FTM_SYNC_ADDR(x), BP_FTM_SYNC_TRIG0) = (v)) /*@}*/ /*! * @name Register FTM_SYNC, field TRIG1[5] (RW) * * Enables hardware trigger 1 to the PWM synchronization. Hardware trigger 1 * happens when a rising edge is detected at the trigger 1 input signal. * * Values: * - 0 - Trigger is disabled. * - 1 - Trigger is enabled. */ /*@{*/ #define BP_FTM_SYNC_TRIG1 (5U) /*!< Bit position for FTM_SYNC_TRIG1. */ #define BM_FTM_SYNC_TRIG1 (0x00000020U) /*!< Bit mask for FTM_SYNC_TRIG1. */ #define BS_FTM_SYNC_TRIG1 (1U) /*!< Bit field size in bits for FTM_SYNC_TRIG1. */ /*! @brief Read current value of the FTM_SYNC_TRIG1 field. */ #define BR_FTM_SYNC_TRIG1(x) (BITBAND_ACCESS32(HW_FTM_SYNC_ADDR(x), BP_FTM_SYNC_TRIG1)) /*! @brief Format value for bitfield FTM_SYNC_TRIG1. */ #define BF_FTM_SYNC_TRIG1(v) ((uint32_t)((uint32_t)(v) << BP_FTM_SYNC_TRIG1) & BM_FTM_SYNC_TRIG1) /*! @brief Set the TRIG1 field to a new value. */ #define BW_FTM_SYNC_TRIG1(x, v) (BITBAND_ACCESS32(HW_FTM_SYNC_ADDR(x), BP_FTM_SYNC_TRIG1) = (v)) /*@}*/ /*! * @name Register FTM_SYNC, field TRIG2[6] (RW) * * Enables hardware trigger 2 to the PWM synchronization. Hardware trigger 2 * happens when a rising edge is detected at the trigger 2 input signal. * * Values: * - 0 - Trigger is disabled. * - 1 - Trigger is enabled. */ /*@{*/ #define BP_FTM_SYNC_TRIG2 (6U) /*!< Bit position for FTM_SYNC_TRIG2. */ #define BM_FTM_SYNC_TRIG2 (0x00000040U) /*!< Bit mask for FTM_SYNC_TRIG2. */ #define BS_FTM_SYNC_TRIG2 (1U) /*!< Bit field size in bits for FTM_SYNC_TRIG2. */ /*! @brief Read current value of the FTM_SYNC_TRIG2 field. */ #define BR_FTM_SYNC_TRIG2(x) (BITBAND_ACCESS32(HW_FTM_SYNC_ADDR(x), BP_FTM_SYNC_TRIG2)) /*! @brief Format value for bitfield FTM_SYNC_TRIG2. */ #define BF_FTM_SYNC_TRIG2(v) ((uint32_t)((uint32_t)(v) << BP_FTM_SYNC_TRIG2) & BM_FTM_SYNC_TRIG2) /*! @brief Set the TRIG2 field to a new value. */ #define BW_FTM_SYNC_TRIG2(x, v) (BITBAND_ACCESS32(HW_FTM_SYNC_ADDR(x), BP_FTM_SYNC_TRIG2) = (v)) /*@}*/ /*! * @name Register FTM_SYNC, field SWSYNC[7] (RW) * * Selects the software trigger as the PWM synchronization trigger. The software * trigger happens when a 1 is written to SWSYNC bit. * * Values: * - 0 - Software trigger is not selected. * - 1 - Software trigger is selected. */ /*@{*/ #define BP_FTM_SYNC_SWSYNC (7U) /*!< Bit position for FTM_SYNC_SWSYNC. */ #define BM_FTM_SYNC_SWSYNC (0x00000080U) /*!< Bit mask for FTM_SYNC_SWSYNC. */ #define BS_FTM_SYNC_SWSYNC (1U) /*!< Bit field size in bits for FTM_SYNC_SWSYNC. */ /*! @brief Read current value of the FTM_SYNC_SWSYNC field. */ #define BR_FTM_SYNC_SWSYNC(x) (BITBAND_ACCESS32(HW_FTM_SYNC_ADDR(x), BP_FTM_SYNC_SWSYNC)) /*! @brief Format value for bitfield FTM_SYNC_SWSYNC. */ #define BF_FTM_SYNC_SWSYNC(v) ((uint32_t)((uint32_t)(v) << BP_FTM_SYNC_SWSYNC) & BM_FTM_SYNC_SWSYNC) /*! @brief Set the SWSYNC field to a new value. */ #define BW_FTM_SYNC_SWSYNC(x, v) (BITBAND_ACCESS32(HW_FTM_SYNC_ADDR(x), BP_FTM_SYNC_SWSYNC) = (v)) /*@}*/ /******************************************************************************* * HW_FTM_OUTINIT - Initial State For Channels Output ******************************************************************************/ /*! * @brief HW_FTM_OUTINIT - Initial State For Channels Output (RW) * * Reset value: 0x00000000U */ typedef union _hw_ftm_outinit { uint32_t U; struct _hw_ftm_outinit_bitfields { uint32_t CH0OI : 1; /*!< [0] Channel 0 Output Initialization Value */ uint32_t CH1OI : 1; /*!< [1] Channel 1 Output Initialization Value */ uint32_t CH2OI : 1; /*!< [2] Channel 2 Output Initialization Value */ uint32_t CH3OI : 1; /*!< [3] Channel 3 Output Initialization Value */ uint32_t CH4OI : 1; /*!< [4] Channel 4 Output Initialization Value */ uint32_t CH5OI : 1; /*!< [5] Channel 5 Output Initialization Value */ uint32_t CH6OI : 1; /*!< [6] Channel 6 Output Initialization Value */ uint32_t CH7OI : 1; /*!< [7] Channel 7 Output Initialization Value */ uint32_t RESERVED0 : 24; /*!< [31:8] */ } B; } hw_ftm_outinit_t; /*! * @name Constants and macros for entire FTM_OUTINIT register */ /*@{*/ #define HW_FTM_OUTINIT_ADDR(x) ((x) + 0x5CU) #define HW_FTM_OUTINIT(x) (*(__IO hw_ftm_outinit_t *) HW_FTM_OUTINIT_ADDR(x)) #define HW_FTM_OUTINIT_RD(x) (HW_FTM_OUTINIT(x).U) #define HW_FTM_OUTINIT_WR(x, v) (HW_FTM_OUTINIT(x).U = (v)) #define HW_FTM_OUTINIT_SET(x, v) (HW_FTM_OUTINIT_WR(x, HW_FTM_OUTINIT_RD(x) | (v))) #define HW_FTM_OUTINIT_CLR(x, v) (HW_FTM_OUTINIT_WR(x, HW_FTM_OUTINIT_RD(x) & ~(v))) #define HW_FTM_OUTINIT_TOG(x, v) (HW_FTM_OUTINIT_WR(x, HW_FTM_OUTINIT_RD(x) ^ (v))) /*@}*/ /* * Constants & macros for individual FTM_OUTINIT bitfields */ /*! * @name Register FTM_OUTINIT, field CH0OI[0] (RW) * * Selects the value that is forced into the channel output when the * initialization occurs. * * Values: * - 0 - The initialization value is 0. * - 1 - The initialization value is 1. */ /*@{*/ #define BP_FTM_OUTINIT_CH0OI (0U) /*!< Bit position for FTM_OUTINIT_CH0OI. */ #define BM_FTM_OUTINIT_CH0OI (0x00000001U) /*!< Bit mask for FTM_OUTINIT_CH0OI. */ #define BS_FTM_OUTINIT_CH0OI (1U) /*!< Bit field size in bits for FTM_OUTINIT_CH0OI. */ /*! @brief Read current value of the FTM_OUTINIT_CH0OI field. */ #define BR_FTM_OUTINIT_CH0OI(x) (BITBAND_ACCESS32(HW_FTM_OUTINIT_ADDR(x), BP_FTM_OUTINIT_CH0OI)) /*! @brief Format value for bitfield FTM_OUTINIT_CH0OI. */ #define BF_FTM_OUTINIT_CH0OI(v) ((uint32_t)((uint32_t)(v) << BP_FTM_OUTINIT_CH0OI) & BM_FTM_OUTINIT_CH0OI) /*! @brief Set the CH0OI field to a new value. */ #define BW_FTM_OUTINIT_CH0OI(x, v) (BITBAND_ACCESS32(HW_FTM_OUTINIT_ADDR(x), BP_FTM_OUTINIT_CH0OI) = (v)) /*@}*/ /*! * @name Register FTM_OUTINIT, field CH1OI[1] (RW) * * Selects the value that is forced into the channel output when the * initialization occurs. * * Values: * - 0 - The initialization value is 0. * - 1 - The initialization value is 1. */ /*@{*/ #define BP_FTM_OUTINIT_CH1OI (1U) /*!< Bit position for FTM_OUTINIT_CH1OI. */ #define BM_FTM_OUTINIT_CH1OI (0x00000002U) /*!< Bit mask for FTM_OUTINIT_CH1OI. */ #define BS_FTM_OUTINIT_CH1OI (1U) /*!< Bit field size in bits for FTM_OUTINIT_CH1OI. */ /*! @brief Read current value of the FTM_OUTINIT_CH1OI field. */ #define BR_FTM_OUTINIT_CH1OI(x) (BITBAND_ACCESS32(HW_FTM_OUTINIT_ADDR(x), BP_FTM_OUTINIT_CH1OI)) /*! @brief Format value for bitfield FTM_OUTINIT_CH1OI. */ #define BF_FTM_OUTINIT_CH1OI(v) ((uint32_t)((uint32_t)(v) << BP_FTM_OUTINIT_CH1OI) & BM_FTM_OUTINIT_CH1OI) /*! @brief Set the CH1OI field to a new value. */ #define BW_FTM_OUTINIT_CH1OI(x, v) (BITBAND_ACCESS32(HW_FTM_OUTINIT_ADDR(x), BP_FTM_OUTINIT_CH1OI) = (v)) /*@}*/ /*! * @name Register FTM_OUTINIT, field CH2OI[2] (RW) * * Selects the value that is forced into the channel output when the * initialization occurs. * * Values: * - 0 - The initialization value is 0. * - 1 - The initialization value is 1. */ /*@{*/ #define BP_FTM_OUTINIT_CH2OI (2U) /*!< Bit position for FTM_OUTINIT_CH2OI. */ #define BM_FTM_OUTINIT_CH2OI (0x00000004U) /*!< Bit mask for FTM_OUTINIT_CH2OI. */ #define BS_FTM_OUTINIT_CH2OI (1U) /*!< Bit field size in bits for FTM_OUTINIT_CH2OI. */ /*! @brief Read current value of the FTM_OUTINIT_CH2OI field. */ #define BR_FTM_OUTINIT_CH2OI(x) (BITBAND_ACCESS32(HW_FTM_OUTINIT_ADDR(x), BP_FTM_OUTINIT_CH2OI)) /*! @brief Format value for bitfield FTM_OUTINIT_CH2OI. */ #define BF_FTM_OUTINIT_CH2OI(v) ((uint32_t)((uint32_t)(v) << BP_FTM_OUTINIT_CH2OI) & BM_FTM_OUTINIT_CH2OI) /*! @brief Set the CH2OI field to a new value. */ #define BW_FTM_OUTINIT_CH2OI(x, v) (BITBAND_ACCESS32(HW_FTM_OUTINIT_ADDR(x), BP_FTM_OUTINIT_CH2OI) = (v)) /*@}*/ /*! * @name Register FTM_OUTINIT, field CH3OI[3] (RW) * * Selects the value that is forced into the channel output when the * initialization occurs. * * Values: * - 0 - The initialization value is 0. * - 1 - The initialization value is 1. */ /*@{*/ #define BP_FTM_OUTINIT_CH3OI (3U) /*!< Bit position for FTM_OUTINIT_CH3OI. */ #define BM_FTM_OUTINIT_CH3OI (0x00000008U) /*!< Bit mask for FTM_OUTINIT_CH3OI. */ #define BS_FTM_OUTINIT_CH3OI (1U) /*!< Bit field size in bits for FTM_OUTINIT_CH3OI. */ /*! @brief Read current value of the FTM_OUTINIT_CH3OI field. */ #define BR_FTM_OUTINIT_CH3OI(x) (BITBAND_ACCESS32(HW_FTM_OUTINIT_ADDR(x), BP_FTM_OUTINIT_CH3OI)) /*! @brief Format value for bitfield FTM_OUTINIT_CH3OI. */ #define BF_FTM_OUTINIT_CH3OI(v) ((uint32_t)((uint32_t)(v) << BP_FTM_OUTINIT_CH3OI) & BM_FTM_OUTINIT_CH3OI) /*! @brief Set the CH3OI field to a new value. */ #define BW_FTM_OUTINIT_CH3OI(x, v) (BITBAND_ACCESS32(HW_FTM_OUTINIT_ADDR(x), BP_FTM_OUTINIT_CH3OI) = (v)) /*@}*/ /*! * @name Register FTM_OUTINIT, field CH4OI[4] (RW) * * Selects the value that is forced into the channel output when the * initialization occurs. * * Values: * - 0 - The initialization value is 0. * - 1 - The initialization value is 1. */ /*@{*/ #define BP_FTM_OUTINIT_CH4OI (4U) /*!< Bit position for FTM_OUTINIT_CH4OI. */ #define BM_FTM_OUTINIT_CH4OI (0x00000010U) /*!< Bit mask for FTM_OUTINIT_CH4OI. */ #define BS_FTM_OUTINIT_CH4OI (1U) /*!< Bit field size in bits for FTM_OUTINIT_CH4OI. */ /*! @brief Read current value of the FTM_OUTINIT_CH4OI field. */ #define BR_FTM_OUTINIT_CH4OI(x) (BITBAND_ACCESS32(HW_FTM_OUTINIT_ADDR(x), BP_FTM_OUTINIT_CH4OI)) /*! @brief Format value for bitfield FTM_OUTINIT_CH4OI. */ #define BF_FTM_OUTINIT_CH4OI(v) ((uint32_t)((uint32_t)(v) << BP_FTM_OUTINIT_CH4OI) & BM_FTM_OUTINIT_CH4OI) /*! @brief Set the CH4OI field to a new value. */ #define BW_FTM_OUTINIT_CH4OI(x, v) (BITBAND_ACCESS32(HW_FTM_OUTINIT_ADDR(x), BP_FTM_OUTINIT_CH4OI) = (v)) /*@}*/ /*! * @name Register FTM_OUTINIT, field CH5OI[5] (RW) * * Selects the value that is forced into the channel output when the * initialization occurs. * * Values: * - 0 - The initialization value is 0. * - 1 - The initialization value is 1. */ /*@{*/ #define BP_FTM_OUTINIT_CH5OI (5U) /*!< Bit position for FTM_OUTINIT_CH5OI. */ #define BM_FTM_OUTINIT_CH5OI (0x00000020U) /*!< Bit mask for FTM_OUTINIT_CH5OI. */ #define BS_FTM_OUTINIT_CH5OI (1U) /*!< Bit field size in bits for FTM_OUTINIT_CH5OI. */ /*! @brief Read current value of the FTM_OUTINIT_CH5OI field. */ #define BR_FTM_OUTINIT_CH5OI(x) (BITBAND_ACCESS32(HW_FTM_OUTINIT_ADDR(x), BP_FTM_OUTINIT_CH5OI)) /*! @brief Format value for bitfield FTM_OUTINIT_CH5OI. */ #define BF_FTM_OUTINIT_CH5OI(v) ((uint32_t)((uint32_t)(v) << BP_FTM_OUTINIT_CH5OI) & BM_FTM_OUTINIT_CH5OI) /*! @brief Set the CH5OI field to a new value. */ #define BW_FTM_OUTINIT_CH5OI(x, v) (BITBAND_ACCESS32(HW_FTM_OUTINIT_ADDR(x), BP_FTM_OUTINIT_CH5OI) = (v)) /*@}*/ /*! * @name Register FTM_OUTINIT, field CH6OI[6] (RW) * * Selects the value that is forced into the channel output when the * initialization occurs. * * Values: * - 0 - The initialization value is 0. * - 1 - The initialization value is 1. */ /*@{*/ #define BP_FTM_OUTINIT_CH6OI (6U) /*!< Bit position for FTM_OUTINIT_CH6OI. */ #define BM_FTM_OUTINIT_CH6OI (0x00000040U) /*!< Bit mask for FTM_OUTINIT_CH6OI. */ #define BS_FTM_OUTINIT_CH6OI (1U) /*!< Bit field size in bits for FTM_OUTINIT_CH6OI. */ /*! @brief Read current value of the FTM_OUTINIT_CH6OI field. */ #define BR_FTM_OUTINIT_CH6OI(x) (BITBAND_ACCESS32(HW_FTM_OUTINIT_ADDR(x), BP_FTM_OUTINIT_CH6OI)) /*! @brief Format value for bitfield FTM_OUTINIT_CH6OI. */ #define BF_FTM_OUTINIT_CH6OI(v) ((uint32_t)((uint32_t)(v) << BP_FTM_OUTINIT_CH6OI) & BM_FTM_OUTINIT_CH6OI) /*! @brief Set the CH6OI field to a new value. */ #define BW_FTM_OUTINIT_CH6OI(x, v) (BITBAND_ACCESS32(HW_FTM_OUTINIT_ADDR(x), BP_FTM_OUTINIT_CH6OI) = (v)) /*@}*/ /*! * @name Register FTM_OUTINIT, field CH7OI[7] (RW) * * Selects the value that is forced into the channel output when the * initialization occurs. * * Values: * - 0 - The initialization value is 0. * - 1 - The initialization value is 1. */ /*@{*/ #define BP_FTM_OUTINIT_CH7OI (7U) /*!< Bit position for FTM_OUTINIT_CH7OI. */ #define BM_FTM_OUTINIT_CH7OI (0x00000080U) /*!< Bit mask for FTM_OUTINIT_CH7OI. */ #define BS_FTM_OUTINIT_CH7OI (1U) /*!< Bit field size in bits for FTM_OUTINIT_CH7OI. */ /*! @brief Read current value of the FTM_OUTINIT_CH7OI field. */ #define BR_FTM_OUTINIT_CH7OI(x) (BITBAND_ACCESS32(HW_FTM_OUTINIT_ADDR(x), BP_FTM_OUTINIT_CH7OI)) /*! @brief Format value for bitfield FTM_OUTINIT_CH7OI. */ #define BF_FTM_OUTINIT_CH7OI(v) ((uint32_t)((uint32_t)(v) << BP_FTM_OUTINIT_CH7OI) & BM_FTM_OUTINIT_CH7OI) /*! @brief Set the CH7OI field to a new value. */ #define BW_FTM_OUTINIT_CH7OI(x, v) (BITBAND_ACCESS32(HW_FTM_OUTINIT_ADDR(x), BP_FTM_OUTINIT_CH7OI) = (v)) /*@}*/ /******************************************************************************* * HW_FTM_OUTMASK - Output Mask ******************************************************************************/ /*! * @brief HW_FTM_OUTMASK - Output Mask (RW) * * Reset value: 0x00000000U * * This register provides a mask for each FTM channel. The mask of a channel * determines if its output responds, that is, it is masked or not, when a match * occurs. This feature is used for BLDC control where the PWM signal is presented * to an electric motor at specific times to provide electronic commutation. Any * write to the OUTMASK register, stores the value in its write buffer. The * register is updated with the value of its write buffer according to PWM * synchronization. */ typedef union _hw_ftm_outmask { uint32_t U; struct _hw_ftm_outmask_bitfields { uint32_t CH0OM : 1; /*!< [0] Channel 0 Output Mask */ uint32_t CH1OM : 1; /*!< [1] Channel 1 Output Mask */ uint32_t CH2OM : 1; /*!< [2] Channel 2 Output Mask */ uint32_t CH3OM : 1; /*!< [3] Channel 3 Output Mask */ uint32_t CH4OM : 1; /*!< [4] Channel 4 Output Mask */ uint32_t CH5OM : 1; /*!< [5] Channel 5 Output Mask */ uint32_t CH6OM : 1; /*!< [6] Channel 6 Output Mask */ uint32_t CH7OM : 1; /*!< [7] Channel 7 Output Mask */ uint32_t RESERVED0 : 24; /*!< [31:8] */ } B; } hw_ftm_outmask_t; /*! * @name Constants and macros for entire FTM_OUTMASK register */ /*@{*/ #define HW_FTM_OUTMASK_ADDR(x) ((x) + 0x60U) #define HW_FTM_OUTMASK(x) (*(__IO hw_ftm_outmask_t *) HW_FTM_OUTMASK_ADDR(x)) #define HW_FTM_OUTMASK_RD(x) (HW_FTM_OUTMASK(x).U) #define HW_FTM_OUTMASK_WR(x, v) (HW_FTM_OUTMASK(x).U = (v)) #define HW_FTM_OUTMASK_SET(x, v) (HW_FTM_OUTMASK_WR(x, HW_FTM_OUTMASK_RD(x) | (v))) #define HW_FTM_OUTMASK_CLR(x, v) (HW_FTM_OUTMASK_WR(x, HW_FTM_OUTMASK_RD(x) & ~(v))) #define HW_FTM_OUTMASK_TOG(x, v) (HW_FTM_OUTMASK_WR(x, HW_FTM_OUTMASK_RD(x) ^ (v))) /*@}*/ /* * Constants & macros for individual FTM_OUTMASK bitfields */ /*! * @name Register FTM_OUTMASK, field CH0OM[0] (RW) * * Defines if the channel output is masked or unmasked. * * Values: * - 0 - Channel output is not masked. It continues to operate normally. * - 1 - Channel output is masked. It is forced to its inactive state. */ /*@{*/ #define BP_FTM_OUTMASK_CH0OM (0U) /*!< Bit position for FTM_OUTMASK_CH0OM. */ #define BM_FTM_OUTMASK_CH0OM (0x00000001U) /*!< Bit mask for FTM_OUTMASK_CH0OM. */ #define BS_FTM_OUTMASK_CH0OM (1U) /*!< Bit field size in bits for FTM_OUTMASK_CH0OM. */ /*! @brief Read current value of the FTM_OUTMASK_CH0OM field. */ #define BR_FTM_OUTMASK_CH0OM(x) (BITBAND_ACCESS32(HW_FTM_OUTMASK_ADDR(x), BP_FTM_OUTMASK_CH0OM)) /*! @brief Format value for bitfield FTM_OUTMASK_CH0OM. */ #define BF_FTM_OUTMASK_CH0OM(v) ((uint32_t)((uint32_t)(v) << BP_FTM_OUTMASK_CH0OM) & BM_FTM_OUTMASK_CH0OM) /*! @brief Set the CH0OM field to a new value. */ #define BW_FTM_OUTMASK_CH0OM(x, v) (BITBAND_ACCESS32(HW_FTM_OUTMASK_ADDR(x), BP_FTM_OUTMASK_CH0OM) = (v)) /*@}*/ /*! * @name Register FTM_OUTMASK, field CH1OM[1] (RW) * * Defines if the channel output is masked or unmasked. * * Values: * - 0 - Channel output is not masked. It continues to operate normally. * - 1 - Channel output is masked. It is forced to its inactive state. */ /*@{*/ #define BP_FTM_OUTMASK_CH1OM (1U) /*!< Bit position for FTM_OUTMASK_CH1OM. */ #define BM_FTM_OUTMASK_CH1OM (0x00000002U) /*!< Bit mask for FTM_OUTMASK_CH1OM. */ #define BS_FTM_OUTMASK_CH1OM (1U) /*!< Bit field size in bits for FTM_OUTMASK_CH1OM. */ /*! @brief Read current value of the FTM_OUTMASK_CH1OM field. */ #define BR_FTM_OUTMASK_CH1OM(x) (BITBAND_ACCESS32(HW_FTM_OUTMASK_ADDR(x), BP_FTM_OUTMASK_CH1OM)) /*! @brief Format value for bitfield FTM_OUTMASK_CH1OM. */ #define BF_FTM_OUTMASK_CH1OM(v) ((uint32_t)((uint32_t)(v) << BP_FTM_OUTMASK_CH1OM) & BM_FTM_OUTMASK_CH1OM) /*! @brief Set the CH1OM field to a new value. */ #define BW_FTM_OUTMASK_CH1OM(x, v) (BITBAND_ACCESS32(HW_FTM_OUTMASK_ADDR(x), BP_FTM_OUTMASK_CH1OM) = (v)) /*@}*/ /*! * @name Register FTM_OUTMASK, field CH2OM[2] (RW) * * Defines if the channel output is masked or unmasked. * * Values: * - 0 - Channel output is not masked. It continues to operate normally. * - 1 - Channel output is masked. It is forced to its inactive state. */ /*@{*/ #define BP_FTM_OUTMASK_CH2OM (2U) /*!< Bit position for FTM_OUTMASK_CH2OM. */ #define BM_FTM_OUTMASK_CH2OM (0x00000004U) /*!< Bit mask for FTM_OUTMASK_CH2OM. */ #define BS_FTM_OUTMASK_CH2OM (1U) /*!< Bit field size in bits for FTM_OUTMASK_CH2OM. */ /*! @brief Read current value of the FTM_OUTMASK_CH2OM field. */ #define BR_FTM_OUTMASK_CH2OM(x) (BITBAND_ACCESS32(HW_FTM_OUTMASK_ADDR(x), BP_FTM_OUTMASK_CH2OM)) /*! @brief Format value for bitfield FTM_OUTMASK_CH2OM. */ #define BF_FTM_OUTMASK_CH2OM(v) ((uint32_t)((uint32_t)(v) << BP_FTM_OUTMASK_CH2OM) & BM_FTM_OUTMASK_CH2OM) /*! @brief Set the CH2OM field to a new value. */ #define BW_FTM_OUTMASK_CH2OM(x, v) (BITBAND_ACCESS32(HW_FTM_OUTMASK_ADDR(x), BP_FTM_OUTMASK_CH2OM) = (v)) /*@}*/ /*! * @name Register FTM_OUTMASK, field CH3OM[3] (RW) * * Defines if the channel output is masked or unmasked. * * Values: * - 0 - Channel output is not masked. It continues to operate normally. * - 1 - Channel output is masked. It is forced to its inactive state. */ /*@{*/ #define BP_FTM_OUTMASK_CH3OM (3U) /*!< Bit position for FTM_OUTMASK_CH3OM. */ #define BM_FTM_OUTMASK_CH3OM (0x00000008U) /*!< Bit mask for FTM_OUTMASK_CH3OM. */ #define BS_FTM_OUTMASK_CH3OM (1U) /*!< Bit field size in bits for FTM_OUTMASK_CH3OM. */ /*! @brief Read current value of the FTM_OUTMASK_CH3OM field. */ #define BR_FTM_OUTMASK_CH3OM(x) (BITBAND_ACCESS32(HW_FTM_OUTMASK_ADDR(x), BP_FTM_OUTMASK_CH3OM)) /*! @brief Format value for bitfield FTM_OUTMASK_CH3OM. */ #define BF_FTM_OUTMASK_CH3OM(v) ((uint32_t)((uint32_t)(v) << BP_FTM_OUTMASK_CH3OM) & BM_FTM_OUTMASK_CH3OM) /*! @brief Set the CH3OM field to a new value. */ #define BW_FTM_OUTMASK_CH3OM(x, v) (BITBAND_ACCESS32(HW_FTM_OUTMASK_ADDR(x), BP_FTM_OUTMASK_CH3OM) = (v)) /*@}*/ /*! * @name Register FTM_OUTMASK, field CH4OM[4] (RW) * * Defines if the channel output is masked or unmasked. * * Values: * - 0 - Channel output is not masked. It continues to operate normally. * - 1 - Channel output is masked. It is forced to its inactive state. */ /*@{*/ #define BP_FTM_OUTMASK_CH4OM (4U) /*!< Bit position for FTM_OUTMASK_CH4OM. */ #define BM_FTM_OUTMASK_CH4OM (0x00000010U) /*!< Bit mask for FTM_OUTMASK_CH4OM. */ #define BS_FTM_OUTMASK_CH4OM (1U) /*!< Bit field size in bits for FTM_OUTMASK_CH4OM. */ /*! @brief Read current value of the FTM_OUTMASK_CH4OM field. */ #define BR_FTM_OUTMASK_CH4OM(x) (BITBAND_ACCESS32(HW_FTM_OUTMASK_ADDR(x), BP_FTM_OUTMASK_CH4OM)) /*! @brief Format value for bitfield FTM_OUTMASK_CH4OM. */ #define BF_FTM_OUTMASK_CH4OM(v) ((uint32_t)((uint32_t)(v) << BP_FTM_OUTMASK_CH4OM) & BM_FTM_OUTMASK_CH4OM) /*! @brief Set the CH4OM field to a new value. */ #define BW_FTM_OUTMASK_CH4OM(x, v) (BITBAND_ACCESS32(HW_FTM_OUTMASK_ADDR(x), BP_FTM_OUTMASK_CH4OM) = (v)) /*@}*/ /*! * @name Register FTM_OUTMASK, field CH5OM[5] (RW) * * Defines if the channel output is masked or unmasked. * * Values: * - 0 - Channel output is not masked. It continues to operate normally. * - 1 - Channel output is masked. It is forced to its inactive state. */ /*@{*/ #define BP_FTM_OUTMASK_CH5OM (5U) /*!< Bit position for FTM_OUTMASK_CH5OM. */ #define BM_FTM_OUTMASK_CH5OM (0x00000020U) /*!< Bit mask for FTM_OUTMASK_CH5OM. */ #define BS_FTM_OUTMASK_CH5OM (1U) /*!< Bit field size in bits for FTM_OUTMASK_CH5OM. */ /*! @brief Read current value of the FTM_OUTMASK_CH5OM field. */ #define BR_FTM_OUTMASK_CH5OM(x) (BITBAND_ACCESS32(HW_FTM_OUTMASK_ADDR(x), BP_FTM_OUTMASK_CH5OM)) /*! @brief Format value for bitfield FTM_OUTMASK_CH5OM. */ #define BF_FTM_OUTMASK_CH5OM(v) ((uint32_t)((uint32_t)(v) << BP_FTM_OUTMASK_CH5OM) & BM_FTM_OUTMASK_CH5OM) /*! @brief Set the CH5OM field to a new value. */ #define BW_FTM_OUTMASK_CH5OM(x, v) (BITBAND_ACCESS32(HW_FTM_OUTMASK_ADDR(x), BP_FTM_OUTMASK_CH5OM) = (v)) /*@}*/ /*! * @name Register FTM_OUTMASK, field CH6OM[6] (RW) * * Defines if the channel output is masked or unmasked. * * Values: * - 0 - Channel output is not masked. It continues to operate normally. * - 1 - Channel output is masked. It is forced to its inactive state. */ /*@{*/ #define BP_FTM_OUTMASK_CH6OM (6U) /*!< Bit position for FTM_OUTMASK_CH6OM. */ #define BM_FTM_OUTMASK_CH6OM (0x00000040U) /*!< Bit mask for FTM_OUTMASK_CH6OM. */ #define BS_FTM_OUTMASK_CH6OM (1U) /*!< Bit field size in bits for FTM_OUTMASK_CH6OM. */ /*! @brief Read current value of the FTM_OUTMASK_CH6OM field. */ #define BR_FTM_OUTMASK_CH6OM(x) (BITBAND_ACCESS32(HW_FTM_OUTMASK_ADDR(x), BP_FTM_OUTMASK_CH6OM)) /*! @brief Format value for bitfield FTM_OUTMASK_CH6OM. */ #define BF_FTM_OUTMASK_CH6OM(v) ((uint32_t)((uint32_t)(v) << BP_FTM_OUTMASK_CH6OM) & BM_FTM_OUTMASK_CH6OM) /*! @brief Set the CH6OM field to a new value. */ #define BW_FTM_OUTMASK_CH6OM(x, v) (BITBAND_ACCESS32(HW_FTM_OUTMASK_ADDR(x), BP_FTM_OUTMASK_CH6OM) = (v)) /*@}*/ /*! * @name Register FTM_OUTMASK, field CH7OM[7] (RW) * * Defines if the channel output is masked or unmasked. * * Values: * - 0 - Channel output is not masked. It continues to operate normally. * - 1 - Channel output is masked. It is forced to its inactive state. */ /*@{*/ #define BP_FTM_OUTMASK_CH7OM (7U) /*!< Bit position for FTM_OUTMASK_CH7OM. */ #define BM_FTM_OUTMASK_CH7OM (0x00000080U) /*!< Bit mask for FTM_OUTMASK_CH7OM. */ #define BS_FTM_OUTMASK_CH7OM (1U) /*!< Bit field size in bits for FTM_OUTMASK_CH7OM. */ /*! @brief Read current value of the FTM_OUTMASK_CH7OM field. */ #define BR_FTM_OUTMASK_CH7OM(x) (BITBAND_ACCESS32(HW_FTM_OUTMASK_ADDR(x), BP_FTM_OUTMASK_CH7OM)) /*! @brief Format value for bitfield FTM_OUTMASK_CH7OM. */ #define BF_FTM_OUTMASK_CH7OM(v) ((uint32_t)((uint32_t)(v) << BP_FTM_OUTMASK_CH7OM) & BM_FTM_OUTMASK_CH7OM) /*! @brief Set the CH7OM field to a new value. */ #define BW_FTM_OUTMASK_CH7OM(x, v) (BITBAND_ACCESS32(HW_FTM_OUTMASK_ADDR(x), BP_FTM_OUTMASK_CH7OM) = (v)) /*@}*/ /******************************************************************************* * HW_FTM_COMBINE - Function For Linked Channels ******************************************************************************/ /*! * @brief HW_FTM_COMBINE - Function For Linked Channels (RW) * * Reset value: 0x00000000U * * This register contains the control bits used to configure the fault control, * synchronization, deadtime insertion, Dual Edge Capture mode, Complementary, * and Combine mode for each pair of channels (n) and (n+1), where n equals 0, 2, * 4, and 6. */ typedef union _hw_ftm_combine { uint32_t U; struct _hw_ftm_combine_bitfields { uint32_t COMBINE0 : 1; /*!< [0] Combine Channels For n = 0 */ uint32_t COMP0 : 1; /*!< [1] Complement Of Channel (n) For n = 0 */ uint32_t DECAPEN0 : 1; /*!< [2] Dual Edge Capture Mode Enable For n = * 0 */ uint32_t DECAP0 : 1; /*!< [3] Dual Edge Capture Mode Captures For n = * 0 */ uint32_t DTEN0 : 1; /*!< [4] Deadtime Enable For n = 0 */ uint32_t SYNCEN0 : 1; /*!< [5] Synchronization Enable For n = 0 */ uint32_t FAULTEN0 : 1; /*!< [6] Fault Control Enable For n = 0 */ uint32_t RESERVED0 : 1; /*!< [7] */ uint32_t COMBINE1 : 1; /*!< [8] Combine Channels For n = 2 */ uint32_t COMP1 : 1; /*!< [9] Complement Of Channel (n) For n = 2 */ uint32_t DECAPEN1 : 1; /*!< [10] Dual Edge Capture Mode Enable For n * = 2 */ uint32_t DECAP1 : 1; /*!< [11] Dual Edge Capture Mode Captures For n * = 2 */ uint32_t DTEN1 : 1; /*!< [12] Deadtime Enable For n = 2 */ uint32_t SYNCEN1 : 1; /*!< [13] Synchronization Enable For n = 2 */ uint32_t FAULTEN1 : 1; /*!< [14] Fault Control Enable For n = 2 */ uint32_t RESERVED1 : 1; /*!< [15] */ uint32_t COMBINE2 : 1; /*!< [16] Combine Channels For n = 4 */ uint32_t COMP2 : 1; /*!< [17] Complement Of Channel (n) For n = 4 */ uint32_t DECAPEN2 : 1; /*!< [18] Dual Edge Capture Mode Enable For n * = 4 */ uint32_t DECAP2 : 1; /*!< [19] Dual Edge Capture Mode Captures For n * = 4 */ uint32_t DTEN2 : 1; /*!< [20] Deadtime Enable For n = 4 */ uint32_t SYNCEN2 : 1; /*!< [21] Synchronization Enable For n = 4 */ uint32_t FAULTEN2 : 1; /*!< [22] Fault Control Enable For n = 4 */ uint32_t RESERVED2 : 1; /*!< [23] */ uint32_t COMBINE3 : 1; /*!< [24] Combine Channels For n = 6 */ uint32_t COMP3 : 1; /*!< [25] Complement Of Channel (n) for n = 6 */ uint32_t DECAPEN3 : 1; /*!< [26] Dual Edge Capture Mode Enable For n * = 6 */ uint32_t DECAP3 : 1; /*!< [27] Dual Edge Capture Mode Captures For n * = 6 */ uint32_t DTEN3 : 1; /*!< [28] Deadtime Enable For n = 6 */ uint32_t SYNCEN3 : 1; /*!< [29] Synchronization Enable For n = 6 */ uint32_t FAULTEN3 : 1; /*!< [30] Fault Control Enable For n = 6 */ uint32_t RESERVED3 : 1; /*!< [31] */ } B; } hw_ftm_combine_t; /*! * @name Constants and macros for entire FTM_COMBINE register */ /*@{*/ #define HW_FTM_COMBINE_ADDR(x) ((x) + 0x64U) #define HW_FTM_COMBINE(x) (*(__IO hw_ftm_combine_t *) HW_FTM_COMBINE_ADDR(x)) #define HW_FTM_COMBINE_RD(x) (HW_FTM_COMBINE(x).U) #define HW_FTM_COMBINE_WR(x, v) (HW_FTM_COMBINE(x).U = (v)) #define HW_FTM_COMBINE_SET(x, v) (HW_FTM_COMBINE_WR(x, HW_FTM_COMBINE_RD(x) | (v))) #define HW_FTM_COMBINE_CLR(x, v) (HW_FTM_COMBINE_WR(x, HW_FTM_COMBINE_RD(x) & ~(v))) #define HW_FTM_COMBINE_TOG(x, v) (HW_FTM_COMBINE_WR(x, HW_FTM_COMBINE_RD(x) ^ (v))) /*@}*/ /* * Constants & macros for individual FTM_COMBINE bitfields */ /*! * @name Register FTM_COMBINE, field COMBINE0[0] (RW) * * Enables the combine feature for channels (n) and (n+1). This field is write * protected. It can be written only when MODE[WPDIS] = 1. * * Values: * - 0 - Channels (n) and (n+1) are independent. * - 1 - Channels (n) and (n+1) are combined. */ /*@{*/ #define BP_FTM_COMBINE_COMBINE0 (0U) /*!< Bit position for FTM_COMBINE_COMBINE0. */ #define BM_FTM_COMBINE_COMBINE0 (0x00000001U) /*!< Bit mask for FTM_COMBINE_COMBINE0. */ #define BS_FTM_COMBINE_COMBINE0 (1U) /*!< Bit field size in bits for FTM_COMBINE_COMBINE0. */ /*! @brief Read current value of the FTM_COMBINE_COMBINE0 field. */ #define BR_FTM_COMBINE_COMBINE0(x) (BITBAND_ACCESS32(HW_FTM_COMBINE_ADDR(x), BP_FTM_COMBINE_COMBINE0)) /*! @brief Format value for bitfield FTM_COMBINE_COMBINE0. */ #define BF_FTM_COMBINE_COMBINE0(v) ((uint32_t)((uint32_t)(v) << BP_FTM_COMBINE_COMBINE0) & BM_FTM_COMBINE_COMBINE0) /*! @brief Set the COMBINE0 field to a new value. */ #define BW_FTM_COMBINE_COMBINE0(x, v) (BITBAND_ACCESS32(HW_FTM_COMBINE_ADDR(x), BP_FTM_COMBINE_COMBINE0) = (v)) /*@}*/ /*! * @name Register FTM_COMBINE, field COMP0[1] (RW) * * Enables Complementary mode for the combined channels. In Complementary mode * the channel (n+1) output is the inverse of the channel (n) output. This field * is write protected. It can be written only when MODE[WPDIS] = 1. * * Values: * - 0 - The channel (n+1) output is the same as the channel (n) output. * - 1 - The channel (n+1) output is the complement of the channel (n) output. */ /*@{*/ #define BP_FTM_COMBINE_COMP0 (1U) /*!< Bit position for FTM_COMBINE_COMP0. */ #define BM_FTM_COMBINE_COMP0 (0x00000002U) /*!< Bit mask for FTM_COMBINE_COMP0. */ #define BS_FTM_COMBINE_COMP0 (1U) /*!< Bit field size in bits for FTM_COMBINE_COMP0. */ /*! @brief Read current value of the FTM_COMBINE_COMP0 field. */ #define BR_FTM_COMBINE_COMP0(x) (BITBAND_ACCESS32(HW_FTM_COMBINE_ADDR(x), BP_FTM_COMBINE_COMP0)) /*! @brief Format value for bitfield FTM_COMBINE_COMP0. */ #define BF_FTM_COMBINE_COMP0(v) ((uint32_t)((uint32_t)(v) << BP_FTM_COMBINE_COMP0) & BM_FTM_COMBINE_COMP0) /*! @brief Set the COMP0 field to a new value. */ #define BW_FTM_COMBINE_COMP0(x, v) (BITBAND_ACCESS32(HW_FTM_COMBINE_ADDR(x), BP_FTM_COMBINE_COMP0) = (v)) /*@}*/ /*! * @name Register FTM_COMBINE, field DECAPEN0[2] (RW) * * Enables the Dual Edge Capture mode in the channels (n) and (n+1). This bit * reconfigures the function of MSnA, ELSnB:ELSnA and ELS(n+1)B:ELS(n+1)A bits in * Dual Edge Capture mode according to #ModeSel1Table. This field applies only * when FTMEN = 1. This field is write protected. It can be written only when * MODE[WPDIS] = 1. * * Values: * - 0 - The Dual Edge Capture mode in this pair of channels is disabled. * - 1 - The Dual Edge Capture mode in this pair of channels is enabled. */ /*@{*/ #define BP_FTM_COMBINE_DECAPEN0 (2U) /*!< Bit position for FTM_COMBINE_DECAPEN0. */ #define BM_FTM_COMBINE_DECAPEN0 (0x00000004U) /*!< Bit mask for FTM_COMBINE_DECAPEN0. */ #define BS_FTM_COMBINE_DECAPEN0 (1U) /*!< Bit field size in bits for FTM_COMBINE_DECAPEN0. */ /*! @brief Read current value of the FTM_COMBINE_DECAPEN0 field. */ #define BR_FTM_COMBINE_DECAPEN0(x) (BITBAND_ACCESS32(HW_FTM_COMBINE_ADDR(x), BP_FTM_COMBINE_DECAPEN0)) /*! @brief Format value for bitfield FTM_COMBINE_DECAPEN0. */ #define BF_FTM_COMBINE_DECAPEN0(v) ((uint32_t)((uint32_t)(v) << BP_FTM_COMBINE_DECAPEN0) & BM_FTM_COMBINE_DECAPEN0) /*! @brief Set the DECAPEN0 field to a new value. */ #define BW_FTM_COMBINE_DECAPEN0(x, v) (BITBAND_ACCESS32(HW_FTM_COMBINE_ADDR(x), BP_FTM_COMBINE_DECAPEN0) = (v)) /*@}*/ /*! * @name Register FTM_COMBINE, field DECAP0[3] (RW) * * Enables the capture of the FTM counter value according to the channel (n) * input event and the configuration of the dual edge capture bits. This field * applies only when FTMEN = 1 and DECAPEN = 1. DECAP bit is cleared automatically by * hardware if dual edge capture - one-shot mode is selected and when the capture * of channel (n+1) event is made. * * Values: * - 0 - The dual edge captures are inactive. * - 1 - The dual edge captures are active. */ /*@{*/ #define BP_FTM_COMBINE_DECAP0 (3U) /*!< Bit position for FTM_COMBINE_DECAP0. */ #define BM_FTM_COMBINE_DECAP0 (0x00000008U) /*!< Bit mask for FTM_COMBINE_DECAP0. */ #define BS_FTM_COMBINE_DECAP0 (1U) /*!< Bit field size in bits for FTM_COMBINE_DECAP0. */ /*! @brief Read current value of the FTM_COMBINE_DECAP0 field. */ #define BR_FTM_COMBINE_DECAP0(x) (BITBAND_ACCESS32(HW_FTM_COMBINE_ADDR(x), BP_FTM_COMBINE_DECAP0)) /*! @brief Format value for bitfield FTM_COMBINE_DECAP0. */ #define BF_FTM_COMBINE_DECAP0(v) ((uint32_t)((uint32_t)(v) << BP_FTM_COMBINE_DECAP0) & BM_FTM_COMBINE_DECAP0) /*! @brief Set the DECAP0 field to a new value. */ #define BW_FTM_COMBINE_DECAP0(x, v) (BITBAND_ACCESS32(HW_FTM_COMBINE_ADDR(x), BP_FTM_COMBINE_DECAP0) = (v)) /*@}*/ /*! * @name Register FTM_COMBINE, field DTEN0[4] (RW) * * Enables the deadtime insertion in the channels (n) and (n+1). This field is * write protected. It can be written only when MODE[WPDIS] = 1. * * Values: * - 0 - The deadtime insertion in this pair of channels is disabled. * - 1 - The deadtime insertion in this pair of channels is enabled. */ /*@{*/ #define BP_FTM_COMBINE_DTEN0 (4U) /*!< Bit position for FTM_COMBINE_DTEN0. */ #define BM_FTM_COMBINE_DTEN0 (0x00000010U) /*!< Bit mask for FTM_COMBINE_DTEN0. */ #define BS_FTM_COMBINE_DTEN0 (1U) /*!< Bit field size in bits for FTM_COMBINE_DTEN0. */ /*! @brief Read current value of the FTM_COMBINE_DTEN0 field. */ #define BR_FTM_COMBINE_DTEN0(x) (BITBAND_ACCESS32(HW_FTM_COMBINE_ADDR(x), BP_FTM_COMBINE_DTEN0)) /*! @brief Format value for bitfield FTM_COMBINE_DTEN0. */ #define BF_FTM_COMBINE_DTEN0(v) ((uint32_t)((uint32_t)(v) << BP_FTM_COMBINE_DTEN0) & BM_FTM_COMBINE_DTEN0) /*! @brief Set the DTEN0 field to a new value. */ #define BW_FTM_COMBINE_DTEN0(x, v) (BITBAND_ACCESS32(HW_FTM_COMBINE_ADDR(x), BP_FTM_COMBINE_DTEN0) = (v)) /*@}*/ /*! * @name Register FTM_COMBINE, field SYNCEN0[5] (RW) * * Enables PWM synchronization of registers C(n)V and C(n+1)V. * * Values: * - 0 - The PWM synchronization in this pair of channels is disabled. * - 1 - The PWM synchronization in this pair of channels is enabled. */ /*@{*/ #define BP_FTM_COMBINE_SYNCEN0 (5U) /*!< Bit position for FTM_COMBINE_SYNCEN0. */ #define BM_FTM_COMBINE_SYNCEN0 (0x00000020U) /*!< Bit mask for FTM_COMBINE_SYNCEN0. */ #define BS_FTM_COMBINE_SYNCEN0 (1U) /*!< Bit field size in bits for FTM_COMBINE_SYNCEN0. */ /*! @brief Read current value of the FTM_COMBINE_SYNCEN0 field. */ #define BR_FTM_COMBINE_SYNCEN0(x) (BITBAND_ACCESS32(HW_FTM_COMBINE_ADDR(x), BP_FTM_COMBINE_SYNCEN0)) /*! @brief Format value for bitfield FTM_COMBINE_SYNCEN0. */ #define BF_FTM_COMBINE_SYNCEN0(v) ((uint32_t)((uint32_t)(v) << BP_FTM_COMBINE_SYNCEN0) & BM_FTM_COMBINE_SYNCEN0) /*! @brief Set the SYNCEN0 field to a new value. */ #define BW_FTM_COMBINE_SYNCEN0(x, v) (BITBAND_ACCESS32(HW_FTM_COMBINE_ADDR(x), BP_FTM_COMBINE_SYNCEN0) = (v)) /*@}*/ /*! * @name Register FTM_COMBINE, field FAULTEN0[6] (RW) * * Enables the fault control in channels (n) and (n+1). This field is write * protected. It can be written only when MODE[WPDIS] = 1. * * Values: * - 0 - The fault control in this pair of channels is disabled. * - 1 - The fault control in this pair of channels is enabled. */ /*@{*/ #define BP_FTM_COMBINE_FAULTEN0 (6U) /*!< Bit position for FTM_COMBINE_FAULTEN0. */ #define BM_FTM_COMBINE_FAULTEN0 (0x00000040U) /*!< Bit mask for FTM_COMBINE_FAULTEN0. */ #define BS_FTM_COMBINE_FAULTEN0 (1U) /*!< Bit field size in bits for FTM_COMBINE_FAULTEN0. */ /*! @brief Read current value of the FTM_COMBINE_FAULTEN0 field. */ #define BR_FTM_COMBINE_FAULTEN0(x) (BITBAND_ACCESS32(HW_FTM_COMBINE_ADDR(x), BP_FTM_COMBINE_FAULTEN0)) /*! @brief Format value for bitfield FTM_COMBINE_FAULTEN0. */ #define BF_FTM_COMBINE_FAULTEN0(v) ((uint32_t)((uint32_t)(v) << BP_FTM_COMBINE_FAULTEN0) & BM_FTM_COMBINE_FAULTEN0) /*! @brief Set the FAULTEN0 field to a new value. */ #define BW_FTM_COMBINE_FAULTEN0(x, v) (BITBAND_ACCESS32(HW_FTM_COMBINE_ADDR(x), BP_FTM_COMBINE_FAULTEN0) = (v)) /*@}*/ /*! * @name Register FTM_COMBINE, field COMBINE1[8] (RW) * * Enables the combine feature for channels (n) and (n+1). This field is write * protected. It can be written only when MODE[WPDIS] = 1. * * Values: * - 0 - Channels (n) and (n+1) are independent. * - 1 - Channels (n) and (n+1) are combined. */ /*@{*/ #define BP_FTM_COMBINE_COMBINE1 (8U) /*!< Bit position for FTM_COMBINE_COMBINE1. */ #define BM_FTM_COMBINE_COMBINE1 (0x00000100U) /*!< Bit mask for FTM_COMBINE_COMBINE1. */ #define BS_FTM_COMBINE_COMBINE1 (1U) /*!< Bit field size in bits for FTM_COMBINE_COMBINE1. */ /*! @brief Read current value of the FTM_COMBINE_COMBINE1 field. */ #define BR_FTM_COMBINE_COMBINE1(x) (BITBAND_ACCESS32(HW_FTM_COMBINE_ADDR(x), BP_FTM_COMBINE_COMBINE1)) /*! @brief Format value for bitfield FTM_COMBINE_COMBINE1. */ #define BF_FTM_COMBINE_COMBINE1(v) ((uint32_t)((uint32_t)(v) << BP_FTM_COMBINE_COMBINE1) & BM_FTM_COMBINE_COMBINE1) /*! @brief Set the COMBINE1 field to a new value. */ #define BW_FTM_COMBINE_COMBINE1(x, v) (BITBAND_ACCESS32(HW_FTM_COMBINE_ADDR(x), BP_FTM_COMBINE_COMBINE1) = (v)) /*@}*/ /*! * @name Register FTM_COMBINE, field COMP1[9] (RW) * * Enables Complementary mode for the combined channels. In Complementary mode * the channel (n+1) output is the inverse of the channel (n) output. This field * is write protected. It can be written only when MODE[WPDIS] = 1. * * Values: * - 0 - The channel (n+1) output is the same as the channel (n) output. * - 1 - The channel (n+1) output is the complement of the channel (n) output. */ /*@{*/ #define BP_FTM_COMBINE_COMP1 (9U) /*!< Bit position for FTM_COMBINE_COMP1. */ #define BM_FTM_COMBINE_COMP1 (0x00000200U) /*!< Bit mask for FTM_COMBINE_COMP1. */ #define BS_FTM_COMBINE_COMP1 (1U) /*!< Bit field size in bits for FTM_COMBINE_COMP1. */ /*! @brief Read current value of the FTM_COMBINE_COMP1 field. */ #define BR_FTM_COMBINE_COMP1(x) (BITBAND_ACCESS32(HW_FTM_COMBINE_ADDR(x), BP_FTM_COMBINE_COMP1)) /*! @brief Format value for bitfield FTM_COMBINE_COMP1. */ #define BF_FTM_COMBINE_COMP1(v) ((uint32_t)((uint32_t)(v) << BP_FTM_COMBINE_COMP1) & BM_FTM_COMBINE_COMP1) /*! @brief Set the COMP1 field to a new value. */ #define BW_FTM_COMBINE_COMP1(x, v) (BITBAND_ACCESS32(HW_FTM_COMBINE_ADDR(x), BP_FTM_COMBINE_COMP1) = (v)) /*@}*/ /*! * @name Register FTM_COMBINE, field DECAPEN1[10] (RW) * * Enables the Dual Edge Capture mode in the channels (n) and (n+1). This bit * reconfigures the function of MSnA, ELSnB:ELSnA and ELS(n+1)B:ELS(n+1)A bits in * Dual Edge Capture mode according to #ModeSel1Table. This field applies only * when FTMEN = 1. This field is write protected. It can be written only when * MODE[WPDIS] = 1. * * Values: * - 0 - The Dual Edge Capture mode in this pair of channels is disabled. * - 1 - The Dual Edge Capture mode in this pair of channels is enabled. */ /*@{*/ #define BP_FTM_COMBINE_DECAPEN1 (10U) /*!< Bit position for FTM_COMBINE_DECAPEN1. */ #define BM_FTM_COMBINE_DECAPEN1 (0x00000400U) /*!< Bit mask for FTM_COMBINE_DECAPEN1. */ #define BS_FTM_COMBINE_DECAPEN1 (1U) /*!< Bit field size in bits for FTM_COMBINE_DECAPEN1. */ /*! @brief Read current value of the FTM_COMBINE_DECAPEN1 field. */ #define BR_FTM_COMBINE_DECAPEN1(x) (BITBAND_ACCESS32(HW_FTM_COMBINE_ADDR(x), BP_FTM_COMBINE_DECAPEN1)) /*! @brief Format value for bitfield FTM_COMBINE_DECAPEN1. */ #define BF_FTM_COMBINE_DECAPEN1(v) ((uint32_t)((uint32_t)(v) << BP_FTM_COMBINE_DECAPEN1) & BM_FTM_COMBINE_DECAPEN1) /*! @brief Set the DECAPEN1 field to a new value. */ #define BW_FTM_COMBINE_DECAPEN1(x, v) (BITBAND_ACCESS32(HW_FTM_COMBINE_ADDR(x), BP_FTM_COMBINE_DECAPEN1) = (v)) /*@}*/ /*! * @name Register FTM_COMBINE, field DECAP1[11] (RW) * * Enables the capture of the FTM counter value according to the channel (n) * input event and the configuration of the dual edge capture bits. This field * applies only when FTMEN = 1 and DECAPEN = 1. DECAP bit is cleared automatically by * hardware if Dual Edge Capture - One-Shot mode is selected and when the capture * of channel (n+1) event is made. * * Values: * - 0 - The dual edge captures are inactive. * - 1 - The dual edge captures are active. */ /*@{*/ #define BP_FTM_COMBINE_DECAP1 (11U) /*!< Bit position for FTM_COMBINE_DECAP1. */ #define BM_FTM_COMBINE_DECAP1 (0x00000800U) /*!< Bit mask for FTM_COMBINE_DECAP1. */ #define BS_FTM_COMBINE_DECAP1 (1U) /*!< Bit field size in bits for FTM_COMBINE_DECAP1. */ /*! @brief Read current value of the FTM_COMBINE_DECAP1 field. */ #define BR_FTM_COMBINE_DECAP1(x) (BITBAND_ACCESS32(HW_FTM_COMBINE_ADDR(x), BP_FTM_COMBINE_DECAP1)) /*! @brief Format value for bitfield FTM_COMBINE_DECAP1. */ #define BF_FTM_COMBINE_DECAP1(v) ((uint32_t)((uint32_t)(v) << BP_FTM_COMBINE_DECAP1) & BM_FTM_COMBINE_DECAP1) /*! @brief Set the DECAP1 field to a new value. */ #define BW_FTM_COMBINE_DECAP1(x, v) (BITBAND_ACCESS32(HW_FTM_COMBINE_ADDR(x), BP_FTM_COMBINE_DECAP1) = (v)) /*@}*/ /*! * @name Register FTM_COMBINE, field DTEN1[12] (RW) * * Enables the deadtime insertion in the channels (n) and (n+1). This field is * write protected. It can be written only when MODE[WPDIS] = 1. * * Values: * - 0 - The deadtime insertion in this pair of channels is disabled. * - 1 - The deadtime insertion in this pair of channels is enabled. */ /*@{*/ #define BP_FTM_COMBINE_DTEN1 (12U) /*!< Bit position for FTM_COMBINE_DTEN1. */ #define BM_FTM_COMBINE_DTEN1 (0x00001000U) /*!< Bit mask for FTM_COMBINE_DTEN1. */ #define BS_FTM_COMBINE_DTEN1 (1U) /*!< Bit field size in bits for FTM_COMBINE_DTEN1. */ /*! @brief Read current value of the FTM_COMBINE_DTEN1 field. */ #define BR_FTM_COMBINE_DTEN1(x) (BITBAND_ACCESS32(HW_FTM_COMBINE_ADDR(x), BP_FTM_COMBINE_DTEN1)) /*! @brief Format value for bitfield FTM_COMBINE_DTEN1. */ #define BF_FTM_COMBINE_DTEN1(v) ((uint32_t)((uint32_t)(v) << BP_FTM_COMBINE_DTEN1) & BM_FTM_COMBINE_DTEN1) /*! @brief Set the DTEN1 field to a new value. */ #define BW_FTM_COMBINE_DTEN1(x, v) (BITBAND_ACCESS32(HW_FTM_COMBINE_ADDR(x), BP_FTM_COMBINE_DTEN1) = (v)) /*@}*/ /*! * @name Register FTM_COMBINE, field SYNCEN1[13] (RW) * * Enables PWM synchronization of registers C(n)V and C(n+1)V. * * Values: * - 0 - The PWM synchronization in this pair of channels is disabled. * - 1 - The PWM synchronization in this pair of channels is enabled. */ /*@{*/ #define BP_FTM_COMBINE_SYNCEN1 (13U) /*!< Bit position for FTM_COMBINE_SYNCEN1. */ #define BM_FTM_COMBINE_SYNCEN1 (0x00002000U) /*!< Bit mask for FTM_COMBINE_SYNCEN1. */ #define BS_FTM_COMBINE_SYNCEN1 (1U) /*!< Bit field size in bits for FTM_COMBINE_SYNCEN1. */ /*! @brief Read current value of the FTM_COMBINE_SYNCEN1 field. */ #define BR_FTM_COMBINE_SYNCEN1(x) (BITBAND_ACCESS32(HW_FTM_COMBINE_ADDR(x), BP_FTM_COMBINE_SYNCEN1)) /*! @brief Format value for bitfield FTM_COMBINE_SYNCEN1. */ #define BF_FTM_COMBINE_SYNCEN1(v) ((uint32_t)((uint32_t)(v) << BP_FTM_COMBINE_SYNCEN1) & BM_FTM_COMBINE_SYNCEN1) /*! @brief Set the SYNCEN1 field to a new value. */ #define BW_FTM_COMBINE_SYNCEN1(x, v) (BITBAND_ACCESS32(HW_FTM_COMBINE_ADDR(x), BP_FTM_COMBINE_SYNCEN1) = (v)) /*@}*/ /*! * @name Register FTM_COMBINE, field FAULTEN1[14] (RW) * * Enables the fault control in channels (n) and (n+1). This field is write * protected. It can be written only when MODE[WPDIS] = 1. * * Values: * - 0 - The fault control in this pair of channels is disabled. * - 1 - The fault control in this pair of channels is enabled. */ /*@{*/ #define BP_FTM_COMBINE_FAULTEN1 (14U) /*!< Bit position for FTM_COMBINE_FAULTEN1. */ #define BM_FTM_COMBINE_FAULTEN1 (0x00004000U) /*!< Bit mask for FTM_COMBINE_FAULTEN1. */ #define BS_FTM_COMBINE_FAULTEN1 (1U) /*!< Bit field size in bits for FTM_COMBINE_FAULTEN1. */ /*! @brief Read current value of the FTM_COMBINE_FAULTEN1 field. */ #define BR_FTM_COMBINE_FAULTEN1(x) (BITBAND_ACCESS32(HW_FTM_COMBINE_ADDR(x), BP_FTM_COMBINE_FAULTEN1)) /*! @brief Format value for bitfield FTM_COMBINE_FAULTEN1. */ #define BF_FTM_COMBINE_FAULTEN1(v) ((uint32_t)((uint32_t)(v) << BP_FTM_COMBINE_FAULTEN1) & BM_FTM_COMBINE_FAULTEN1) /*! @brief Set the FAULTEN1 field to a new value. */ #define BW_FTM_COMBINE_FAULTEN1(x, v) (BITBAND_ACCESS32(HW_FTM_COMBINE_ADDR(x), BP_FTM_COMBINE_FAULTEN1) = (v)) /*@}*/ /*! * @name Register FTM_COMBINE, field COMBINE2[16] (RW) * * Enables the combine feature for channels (n) and (n+1). This field is write * protected. It can be written only when MODE[WPDIS] = 1. * * Values: * - 0 - Channels (n) and (n+1) are independent. * - 1 - Channels (n) and (n+1) are combined. */ /*@{*/ #define BP_FTM_COMBINE_COMBINE2 (16U) /*!< Bit position for FTM_COMBINE_COMBINE2. */ #define BM_FTM_COMBINE_COMBINE2 (0x00010000U) /*!< Bit mask for FTM_COMBINE_COMBINE2. */ #define BS_FTM_COMBINE_COMBINE2 (1U) /*!< Bit field size in bits for FTM_COMBINE_COMBINE2. */ /*! @brief Read current value of the FTM_COMBINE_COMBINE2 field. */ #define BR_FTM_COMBINE_COMBINE2(x) (BITBAND_ACCESS32(HW_FTM_COMBINE_ADDR(x), BP_FTM_COMBINE_COMBINE2)) /*! @brief Format value for bitfield FTM_COMBINE_COMBINE2. */ #define BF_FTM_COMBINE_COMBINE2(v) ((uint32_t)((uint32_t)(v) << BP_FTM_COMBINE_COMBINE2) & BM_FTM_COMBINE_COMBINE2) /*! @brief Set the COMBINE2 field to a new value. */ #define BW_FTM_COMBINE_COMBINE2(x, v) (BITBAND_ACCESS32(HW_FTM_COMBINE_ADDR(x), BP_FTM_COMBINE_COMBINE2) = (v)) /*@}*/ /*! * @name Register FTM_COMBINE, field COMP2[17] (RW) * * Enables Complementary mode for the combined channels. In Complementary mode * the channel (n+1) output is the inverse of the channel (n) output. This field * is write protected. It can be written only when MODE[WPDIS] = 1. * * Values: * - 0 - The channel (n+1) output is the same as the channel (n) output. * - 1 - The channel (n+1) output is the complement of the channel (n) output. */ /*@{*/ #define BP_FTM_COMBINE_COMP2 (17U) /*!< Bit position for FTM_COMBINE_COMP2. */ #define BM_FTM_COMBINE_COMP2 (0x00020000U) /*!< Bit mask for FTM_COMBINE_COMP2. */ #define BS_FTM_COMBINE_COMP2 (1U) /*!< Bit field size in bits for FTM_COMBINE_COMP2. */ /*! @brief Read current value of the FTM_COMBINE_COMP2 field. */ #define BR_FTM_COMBINE_COMP2(x) (BITBAND_ACCESS32(HW_FTM_COMBINE_ADDR(x), BP_FTM_COMBINE_COMP2)) /*! @brief Format value for bitfield FTM_COMBINE_COMP2. */ #define BF_FTM_COMBINE_COMP2(v) ((uint32_t)((uint32_t)(v) << BP_FTM_COMBINE_COMP2) & BM_FTM_COMBINE_COMP2) /*! @brief Set the COMP2 field to a new value. */ #define BW_FTM_COMBINE_COMP2(x, v) (BITBAND_ACCESS32(HW_FTM_COMBINE_ADDR(x), BP_FTM_COMBINE_COMP2) = (v)) /*@}*/ /*! * @name Register FTM_COMBINE, field DECAPEN2[18] (RW) * * Enables the Dual Edge Capture mode in the channels (n) and (n+1). This bit * reconfigures the function of MSnA, ELSnB:ELSnA and ELS(n+1)B:ELS(n+1)A bits in * Dual Edge Capture mode according to #ModeSel1Table. This field applies only * when FTMEN = 1. This field is write protected. It can be written only when * MODE[WPDIS] = 1. * * Values: * - 0 - The Dual Edge Capture mode in this pair of channels is disabled. * - 1 - The Dual Edge Capture mode in this pair of channels is enabled. */ /*@{*/ #define BP_FTM_COMBINE_DECAPEN2 (18U) /*!< Bit position for FTM_COMBINE_DECAPEN2. */ #define BM_FTM_COMBINE_DECAPEN2 (0x00040000U) /*!< Bit mask for FTM_COMBINE_DECAPEN2. */ #define BS_FTM_COMBINE_DECAPEN2 (1U) /*!< Bit field size in bits for FTM_COMBINE_DECAPEN2. */ /*! @brief Read current value of the FTM_COMBINE_DECAPEN2 field. */ #define BR_FTM_COMBINE_DECAPEN2(x) (BITBAND_ACCESS32(HW_FTM_COMBINE_ADDR(x), BP_FTM_COMBINE_DECAPEN2)) /*! @brief Format value for bitfield FTM_COMBINE_DECAPEN2. */ #define BF_FTM_COMBINE_DECAPEN2(v) ((uint32_t)((uint32_t)(v) << BP_FTM_COMBINE_DECAPEN2) & BM_FTM_COMBINE_DECAPEN2) /*! @brief Set the DECAPEN2 field to a new value. */ #define BW_FTM_COMBINE_DECAPEN2(x, v) (BITBAND_ACCESS32(HW_FTM_COMBINE_ADDR(x), BP_FTM_COMBINE_DECAPEN2) = (v)) /*@}*/ /*! * @name Register FTM_COMBINE, field DECAP2[19] (RW) * * Enables the capture of the FTM counter value according to the channel (n) * input event and the configuration of the dual edge capture bits. This field * applies only when FTMEN = 1 and DECAPEN = 1. DECAP bit is cleared automatically by * hardware if dual edge capture - one-shot mode is selected and when the capture * of channel (n+1) event is made. * * Values: * - 0 - The dual edge captures are inactive. * - 1 - The dual edge captures are active. */ /*@{*/ #define BP_FTM_COMBINE_DECAP2 (19U) /*!< Bit position for FTM_COMBINE_DECAP2. */ #define BM_FTM_COMBINE_DECAP2 (0x00080000U) /*!< Bit mask for FTM_COMBINE_DECAP2. */ #define BS_FTM_COMBINE_DECAP2 (1U) /*!< Bit field size in bits for FTM_COMBINE_DECAP2. */ /*! @brief Read current value of the FTM_COMBINE_DECAP2 field. */ #define BR_FTM_COMBINE_DECAP2(x) (BITBAND_ACCESS32(HW_FTM_COMBINE_ADDR(x), BP_FTM_COMBINE_DECAP2)) /*! @brief Format value for bitfield FTM_COMBINE_DECAP2. */ #define BF_FTM_COMBINE_DECAP2(v) ((uint32_t)((uint32_t)(v) << BP_FTM_COMBINE_DECAP2) & BM_FTM_COMBINE_DECAP2) /*! @brief Set the DECAP2 field to a new value. */ #define BW_FTM_COMBINE_DECAP2(x, v) (BITBAND_ACCESS32(HW_FTM_COMBINE_ADDR(x), BP_FTM_COMBINE_DECAP2) = (v)) /*@}*/ /*! * @name Register FTM_COMBINE, field DTEN2[20] (RW) * * Enables the deadtime insertion in the channels (n) and (n+1). This field is * write protected. It can be written only when MODE[WPDIS] = 1. * * Values: * - 0 - The deadtime insertion in this pair of channels is disabled. * - 1 - The deadtime insertion in this pair of channels is enabled. */ /*@{*/ #define BP_FTM_COMBINE_DTEN2 (20U) /*!< Bit position for FTM_COMBINE_DTEN2. */ #define BM_FTM_COMBINE_DTEN2 (0x00100000U) /*!< Bit mask for FTM_COMBINE_DTEN2. */ #define BS_FTM_COMBINE_DTEN2 (1U) /*!< Bit field size in bits for FTM_COMBINE_DTEN2. */ /*! @brief Read current value of the FTM_COMBINE_DTEN2 field. */ #define BR_FTM_COMBINE_DTEN2(x) (BITBAND_ACCESS32(HW_FTM_COMBINE_ADDR(x), BP_FTM_COMBINE_DTEN2)) /*! @brief Format value for bitfield FTM_COMBINE_DTEN2. */ #define BF_FTM_COMBINE_DTEN2(v) ((uint32_t)((uint32_t)(v) << BP_FTM_COMBINE_DTEN2) & BM_FTM_COMBINE_DTEN2) /*! @brief Set the DTEN2 field to a new value. */ #define BW_FTM_COMBINE_DTEN2(x, v) (BITBAND_ACCESS32(HW_FTM_COMBINE_ADDR(x), BP_FTM_COMBINE_DTEN2) = (v)) /*@}*/ /*! * @name Register FTM_COMBINE, field SYNCEN2[21] (RW) * * Enables PWM synchronization of registers C(n)V and C(n+1)V. * * Values: * - 0 - The PWM synchronization in this pair of channels is disabled. * - 1 - The PWM synchronization in this pair of channels is enabled. */ /*@{*/ #define BP_FTM_COMBINE_SYNCEN2 (21U) /*!< Bit position for FTM_COMBINE_SYNCEN2. */ #define BM_FTM_COMBINE_SYNCEN2 (0x00200000U) /*!< Bit mask for FTM_COMBINE_SYNCEN2. */ #define BS_FTM_COMBINE_SYNCEN2 (1U) /*!< Bit field size in bits for FTM_COMBINE_SYNCEN2. */ /*! @brief Read current value of the FTM_COMBINE_SYNCEN2 field. */ #define BR_FTM_COMBINE_SYNCEN2(x) (BITBAND_ACCESS32(HW_FTM_COMBINE_ADDR(x), BP_FTM_COMBINE_SYNCEN2)) /*! @brief Format value for bitfield FTM_COMBINE_SYNCEN2. */ #define BF_FTM_COMBINE_SYNCEN2(v) ((uint32_t)((uint32_t)(v) << BP_FTM_COMBINE_SYNCEN2) & BM_FTM_COMBINE_SYNCEN2) /*! @brief Set the SYNCEN2 field to a new value. */ #define BW_FTM_COMBINE_SYNCEN2(x, v) (BITBAND_ACCESS32(HW_FTM_COMBINE_ADDR(x), BP_FTM_COMBINE_SYNCEN2) = (v)) /*@}*/ /*! * @name Register FTM_COMBINE, field FAULTEN2[22] (RW) * * Enables the fault control in channels (n) and (n+1). This field is write * protected. It can be written only when MODE[WPDIS] = 1. * * Values: * - 0 - The fault control in this pair of channels is disabled. * - 1 - The fault control in this pair of channels is enabled. */ /*@{*/ #define BP_FTM_COMBINE_FAULTEN2 (22U) /*!< Bit position for FTM_COMBINE_FAULTEN2. */ #define BM_FTM_COMBINE_FAULTEN2 (0x00400000U) /*!< Bit mask for FTM_COMBINE_FAULTEN2. */ #define BS_FTM_COMBINE_FAULTEN2 (1U) /*!< Bit field size in bits for FTM_COMBINE_FAULTEN2. */ /*! @brief Read current value of the FTM_COMBINE_FAULTEN2 field. */ #define BR_FTM_COMBINE_FAULTEN2(x) (BITBAND_ACCESS32(HW_FTM_COMBINE_ADDR(x), BP_FTM_COMBINE_FAULTEN2)) /*! @brief Format value for bitfield FTM_COMBINE_FAULTEN2. */ #define BF_FTM_COMBINE_FAULTEN2(v) ((uint32_t)((uint32_t)(v) << BP_FTM_COMBINE_FAULTEN2) & BM_FTM_COMBINE_FAULTEN2) /*! @brief Set the FAULTEN2 field to a new value. */ #define BW_FTM_COMBINE_FAULTEN2(x, v) (BITBAND_ACCESS32(HW_FTM_COMBINE_ADDR(x), BP_FTM_COMBINE_FAULTEN2) = (v)) /*@}*/ /*! * @name Register FTM_COMBINE, field COMBINE3[24] (RW) * * Enables the combine feature for channels (n) and (n+1). This field is write * protected. It can be written only when MODE[WPDIS] = 1. * * Values: * - 0 - Channels (n) and (n+1) are independent. * - 1 - Channels (n) and (n+1) are combined. */ /*@{*/ #define BP_FTM_COMBINE_COMBINE3 (24U) /*!< Bit position for FTM_COMBINE_COMBINE3. */ #define BM_FTM_COMBINE_COMBINE3 (0x01000000U) /*!< Bit mask for FTM_COMBINE_COMBINE3. */ #define BS_FTM_COMBINE_COMBINE3 (1U) /*!< Bit field size in bits for FTM_COMBINE_COMBINE3. */ /*! @brief Read current value of the FTM_COMBINE_COMBINE3 field. */ #define BR_FTM_COMBINE_COMBINE3(x) (BITBAND_ACCESS32(HW_FTM_COMBINE_ADDR(x), BP_FTM_COMBINE_COMBINE3)) /*! @brief Format value for bitfield FTM_COMBINE_COMBINE3. */ #define BF_FTM_COMBINE_COMBINE3(v) ((uint32_t)((uint32_t)(v) << BP_FTM_COMBINE_COMBINE3) & BM_FTM_COMBINE_COMBINE3) /*! @brief Set the COMBINE3 field to a new value. */ #define BW_FTM_COMBINE_COMBINE3(x, v) (BITBAND_ACCESS32(HW_FTM_COMBINE_ADDR(x), BP_FTM_COMBINE_COMBINE3) = (v)) /*@}*/ /*! * @name Register FTM_COMBINE, field COMP3[25] (RW) * * Enables Complementary mode for the combined channels. In Complementary mode * the channel (n+1) output is the inverse of the channel (n) output. This field * is write protected. It can be written only when MODE[WPDIS] = 1. * * Values: * - 0 - The channel (n+1) output is the same as the channel (n) output. * - 1 - The channel (n+1) output is the complement of the channel (n) output. */ /*@{*/ #define BP_FTM_COMBINE_COMP3 (25U) /*!< Bit position for FTM_COMBINE_COMP3. */ #define BM_FTM_COMBINE_COMP3 (0x02000000U) /*!< Bit mask for FTM_COMBINE_COMP3. */ #define BS_FTM_COMBINE_COMP3 (1U) /*!< Bit field size in bits for FTM_COMBINE_COMP3. */ /*! @brief Read current value of the FTM_COMBINE_COMP3 field. */ #define BR_FTM_COMBINE_COMP3(x) (BITBAND_ACCESS32(HW_FTM_COMBINE_ADDR(x), BP_FTM_COMBINE_COMP3)) /*! @brief Format value for bitfield FTM_COMBINE_COMP3. */ #define BF_FTM_COMBINE_COMP3(v) ((uint32_t)((uint32_t)(v) << BP_FTM_COMBINE_COMP3) & BM_FTM_COMBINE_COMP3) /*! @brief Set the COMP3 field to a new value. */ #define BW_FTM_COMBINE_COMP3(x, v) (BITBAND_ACCESS32(HW_FTM_COMBINE_ADDR(x), BP_FTM_COMBINE_COMP3) = (v)) /*@}*/ /*! * @name Register FTM_COMBINE, field DECAPEN3[26] (RW) * * Enables the Dual Edge Capture mode in the channels (n) and (n+1). This bit * reconfigures the function of MSnA, ELSnB:ELSnA and ELS(n+1)B:ELS(n+1)A bits in * Dual Edge Capture mode according to #ModeSel1Table. This field applies only * when FTMEN = 1. This field is write protected. It can be written only when * MODE[WPDIS] = 1. * * Values: * - 0 - The Dual Edge Capture mode in this pair of channels is disabled. * - 1 - The Dual Edge Capture mode in this pair of channels is enabled. */ /*@{*/ #define BP_FTM_COMBINE_DECAPEN3 (26U) /*!< Bit position for FTM_COMBINE_DECAPEN3. */ #define BM_FTM_COMBINE_DECAPEN3 (0x04000000U) /*!< Bit mask for FTM_COMBINE_DECAPEN3. */ #define BS_FTM_COMBINE_DECAPEN3 (1U) /*!< Bit field size in bits for FTM_COMBINE_DECAPEN3. */ /*! @brief Read current value of the FTM_COMBINE_DECAPEN3 field. */ #define BR_FTM_COMBINE_DECAPEN3(x) (BITBAND_ACCESS32(HW_FTM_COMBINE_ADDR(x), BP_FTM_COMBINE_DECAPEN3)) /*! @brief Format value for bitfield FTM_COMBINE_DECAPEN3. */ #define BF_FTM_COMBINE_DECAPEN3(v) ((uint32_t)((uint32_t)(v) << BP_FTM_COMBINE_DECAPEN3) & BM_FTM_COMBINE_DECAPEN3) /*! @brief Set the DECAPEN3 field to a new value. */ #define BW_FTM_COMBINE_DECAPEN3(x, v) (BITBAND_ACCESS32(HW_FTM_COMBINE_ADDR(x), BP_FTM_COMBINE_DECAPEN3) = (v)) /*@}*/ /*! * @name Register FTM_COMBINE, field DECAP3[27] (RW) * * Enables the capture of the FTM counter value according to the channel (n) * input event and the configuration of the dual edge capture bits. This field * applies only when FTMEN = 1 and DECAPEN = 1. DECAP bit is cleared automatically by * hardware if dual edge capture - one-shot mode is selected and when the capture * of channel (n+1) event is made. * * Values: * - 0 - The dual edge captures are inactive. * - 1 - The dual edge captures are active. */ /*@{*/ #define BP_FTM_COMBINE_DECAP3 (27U) /*!< Bit position for FTM_COMBINE_DECAP3. */ #define BM_FTM_COMBINE_DECAP3 (0x08000000U) /*!< Bit mask for FTM_COMBINE_DECAP3. */ #define BS_FTM_COMBINE_DECAP3 (1U) /*!< Bit field size in bits for FTM_COMBINE_DECAP3. */ /*! @brief Read current value of the FTM_COMBINE_DECAP3 field. */ #define BR_FTM_COMBINE_DECAP3(x) (BITBAND_ACCESS32(HW_FTM_COMBINE_ADDR(x), BP_FTM_COMBINE_DECAP3)) /*! @brief Format value for bitfield FTM_COMBINE_DECAP3. */ #define BF_FTM_COMBINE_DECAP3(v) ((uint32_t)((uint32_t)(v) << BP_FTM_COMBINE_DECAP3) & BM_FTM_COMBINE_DECAP3) /*! @brief Set the DECAP3 field to a new value. */ #define BW_FTM_COMBINE_DECAP3(x, v) (BITBAND_ACCESS32(HW_FTM_COMBINE_ADDR(x), BP_FTM_COMBINE_DECAP3) = (v)) /*@}*/ /*! * @name Register FTM_COMBINE, field DTEN3[28] (RW) * * Enables the deadtime insertion in the channels (n) and (n+1). This field is * write protected. It can be written only when MODE[WPDIS] = 1. * * Values: * - 0 - The deadtime insertion in this pair of channels is disabled. * - 1 - The deadtime insertion in this pair of channels is enabled. */ /*@{*/ #define BP_FTM_COMBINE_DTEN3 (28U) /*!< Bit position for FTM_COMBINE_DTEN3. */ #define BM_FTM_COMBINE_DTEN3 (0x10000000U) /*!< Bit mask for FTM_COMBINE_DTEN3. */ #define BS_FTM_COMBINE_DTEN3 (1U) /*!< Bit field size in bits for FTM_COMBINE_DTEN3. */ /*! @brief Read current value of the FTM_COMBINE_DTEN3 field. */ #define BR_FTM_COMBINE_DTEN3(x) (BITBAND_ACCESS32(HW_FTM_COMBINE_ADDR(x), BP_FTM_COMBINE_DTEN3)) /*! @brief Format value for bitfield FTM_COMBINE_DTEN3. */ #define BF_FTM_COMBINE_DTEN3(v) ((uint32_t)((uint32_t)(v) << BP_FTM_COMBINE_DTEN3) & BM_FTM_COMBINE_DTEN3) /*! @brief Set the DTEN3 field to a new value. */ #define BW_FTM_COMBINE_DTEN3(x, v) (BITBAND_ACCESS32(HW_FTM_COMBINE_ADDR(x), BP_FTM_COMBINE_DTEN3) = (v)) /*@}*/ /*! * @name Register FTM_COMBINE, field SYNCEN3[29] (RW) * * Enables PWM synchronization of registers C(n)V and C(n+1)V. * * Values: * - 0 - The PWM synchronization in this pair of channels is disabled. * - 1 - The PWM synchronization in this pair of channels is enabled. */ /*@{*/ #define BP_FTM_COMBINE_SYNCEN3 (29U) /*!< Bit position for FTM_COMBINE_SYNCEN3. */ #define BM_FTM_COMBINE_SYNCEN3 (0x20000000U) /*!< Bit mask for FTM_COMBINE_SYNCEN3. */ #define BS_FTM_COMBINE_SYNCEN3 (1U) /*!< Bit field size in bits for FTM_COMBINE_SYNCEN3. */ /*! @brief Read current value of the FTM_COMBINE_SYNCEN3 field. */ #define BR_FTM_COMBINE_SYNCEN3(x) (BITBAND_ACCESS32(HW_FTM_COMBINE_ADDR(x), BP_FTM_COMBINE_SYNCEN3)) /*! @brief Format value for bitfield FTM_COMBINE_SYNCEN3. */ #define BF_FTM_COMBINE_SYNCEN3(v) ((uint32_t)((uint32_t)(v) << BP_FTM_COMBINE_SYNCEN3) & BM_FTM_COMBINE_SYNCEN3) /*! @brief Set the SYNCEN3 field to a new value. */ #define BW_FTM_COMBINE_SYNCEN3(x, v) (BITBAND_ACCESS32(HW_FTM_COMBINE_ADDR(x), BP_FTM_COMBINE_SYNCEN3) = (v)) /*@}*/ /*! * @name Register FTM_COMBINE, field FAULTEN3[30] (RW) * * Enables the fault control in channels (n) and (n+1). This field is write * protected. It can be written only when MODE[WPDIS] = 1. * * Values: * - 0 - The fault control in this pair of channels is disabled. * - 1 - The fault control in this pair of channels is enabled. */ /*@{*/ #define BP_FTM_COMBINE_FAULTEN3 (30U) /*!< Bit position for FTM_COMBINE_FAULTEN3. */ #define BM_FTM_COMBINE_FAULTEN3 (0x40000000U) /*!< Bit mask for FTM_COMBINE_FAULTEN3. */ #define BS_FTM_COMBINE_FAULTEN3 (1U) /*!< Bit field size in bits for FTM_COMBINE_FAULTEN3. */ /*! @brief Read current value of the FTM_COMBINE_FAULTEN3 field. */ #define BR_FTM_COMBINE_FAULTEN3(x) (BITBAND_ACCESS32(HW_FTM_COMBINE_ADDR(x), BP_FTM_COMBINE_FAULTEN3)) /*! @brief Format value for bitfield FTM_COMBINE_FAULTEN3. */ #define BF_FTM_COMBINE_FAULTEN3(v) ((uint32_t)((uint32_t)(v) << BP_FTM_COMBINE_FAULTEN3) & BM_FTM_COMBINE_FAULTEN3) /*! @brief Set the FAULTEN3 field to a new value. */ #define BW_FTM_COMBINE_FAULTEN3(x, v) (BITBAND_ACCESS32(HW_FTM_COMBINE_ADDR(x), BP_FTM_COMBINE_FAULTEN3) = (v)) /*@}*/ /******************************************************************************* * HW_FTM_DEADTIME - Deadtime Insertion Control ******************************************************************************/ /*! * @brief HW_FTM_DEADTIME - Deadtime Insertion Control (RW) * * Reset value: 0x00000000U * * This register selects the deadtime prescaler factor and deadtime value. All * FTM channels use this clock prescaler and this deadtime value for the deadtime * insertion. */ typedef union _hw_ftm_deadtime { uint32_t U; struct _hw_ftm_deadtime_bitfields { uint32_t DTVAL : 6; /*!< [5:0] Deadtime Value */ uint32_t DTPS : 2; /*!< [7:6] Deadtime Prescaler Value */ uint32_t RESERVED0 : 24; /*!< [31:8] */ } B; } hw_ftm_deadtime_t; /*! * @name Constants and macros for entire FTM_DEADTIME register */ /*@{*/ #define HW_FTM_DEADTIME_ADDR(x) ((x) + 0x68U) #define HW_FTM_DEADTIME(x) (*(__IO hw_ftm_deadtime_t *) HW_FTM_DEADTIME_ADDR(x)) #define HW_FTM_DEADTIME_RD(x) (HW_FTM_DEADTIME(x).U) #define HW_FTM_DEADTIME_WR(x, v) (HW_FTM_DEADTIME(x).U = (v)) #define HW_FTM_DEADTIME_SET(x, v) (HW_FTM_DEADTIME_WR(x, HW_FTM_DEADTIME_RD(x) | (v))) #define HW_FTM_DEADTIME_CLR(x, v) (HW_FTM_DEADTIME_WR(x, HW_FTM_DEADTIME_RD(x) & ~(v))) #define HW_FTM_DEADTIME_TOG(x, v) (HW_FTM_DEADTIME_WR(x, HW_FTM_DEADTIME_RD(x) ^ (v))) /*@}*/ /* * Constants & macros for individual FTM_DEADTIME bitfields */ /*! * @name Register FTM_DEADTIME, field DTVAL[5:0] (RW) * * Selects the deadtime insertion value for the deadtime counter. The deadtime * counter is clocked by a scaled version of the system clock. See the description * of DTPS. Deadtime insert value = (DTPS * DTVAL). DTVAL selects the number of * deadtime counts inserted as follows: When DTVAL is 0, no counts are inserted. * When DTVAL is 1, 1 count is inserted. When DTVAL is 2, 2 counts are inserted. * This pattern continues up to a possible 63 counts. This field is write * protected. It can be written only when MODE[WPDIS] = 1. */ /*@{*/ #define BP_FTM_DEADTIME_DTVAL (0U) /*!< Bit position for FTM_DEADTIME_DTVAL. */ #define BM_FTM_DEADTIME_DTVAL (0x0000003FU) /*!< Bit mask for FTM_DEADTIME_DTVAL. */ #define BS_FTM_DEADTIME_DTVAL (6U) /*!< Bit field size in bits for FTM_DEADTIME_DTVAL. */ /*! @brief Read current value of the FTM_DEADTIME_DTVAL field. */ #define BR_FTM_DEADTIME_DTVAL(x) (HW_FTM_DEADTIME(x).B.DTVAL) /*! @brief Format value for bitfield FTM_DEADTIME_DTVAL. */ #define BF_FTM_DEADTIME_DTVAL(v) ((uint32_t)((uint32_t)(v) << BP_FTM_DEADTIME_DTVAL) & BM_FTM_DEADTIME_DTVAL) /*! @brief Set the DTVAL field to a new value. */ #define BW_FTM_DEADTIME_DTVAL(x, v) (HW_FTM_DEADTIME_WR(x, (HW_FTM_DEADTIME_RD(x) & ~BM_FTM_DEADTIME_DTVAL) | BF_FTM_DEADTIME_DTVAL(v))) /*@}*/ /*! * @name Register FTM_DEADTIME, field DTPS[7:6] (RW) * * Selects the division factor of the system clock. This prescaled clock is used * by the deadtime counter. This field is write protected. It can be written * only when MODE[WPDIS] = 1. * * Values: * - 0x - Divide the system clock by 1. * - 10 - Divide the system clock by 4. * - 11 - Divide the system clock by 16. */ /*@{*/ #define BP_FTM_DEADTIME_DTPS (6U) /*!< Bit position for FTM_DEADTIME_DTPS. */ #define BM_FTM_DEADTIME_DTPS (0x000000C0U) /*!< Bit mask for FTM_DEADTIME_DTPS. */ #define BS_FTM_DEADTIME_DTPS (2U) /*!< Bit field size in bits for FTM_DEADTIME_DTPS. */ /*! @brief Read current value of the FTM_DEADTIME_DTPS field. */ #define BR_FTM_DEADTIME_DTPS(x) (HW_FTM_DEADTIME(x).B.DTPS) /*! @brief Format value for bitfield FTM_DEADTIME_DTPS. */ #define BF_FTM_DEADTIME_DTPS(v) ((uint32_t)((uint32_t)(v) << BP_FTM_DEADTIME_DTPS) & BM_FTM_DEADTIME_DTPS) /*! @brief Set the DTPS field to a new value. */ #define BW_FTM_DEADTIME_DTPS(x, v) (HW_FTM_DEADTIME_WR(x, (HW_FTM_DEADTIME_RD(x) & ~BM_FTM_DEADTIME_DTPS) | BF_FTM_DEADTIME_DTPS(v))) /*@}*/ /******************************************************************************* * HW_FTM_EXTTRIG - FTM External Trigger ******************************************************************************/ /*! * @brief HW_FTM_EXTTRIG - FTM External Trigger (RW) * * Reset value: 0x00000000U * * This register: Indicates when a channel trigger was generated Enables the * generation of a trigger when the FTM counter is equal to its initial value * Selects which channels are used in the generation of the channel triggers Several * channels can be selected to generate multiple triggers in one PWM period. * Channels 6 and 7 are not used to generate channel triggers. */ typedef union _hw_ftm_exttrig { uint32_t U; struct _hw_ftm_exttrig_bitfields { uint32_t CH2TRIG : 1; /*!< [0] Channel 2 Trigger Enable */ uint32_t CH3TRIG : 1; /*!< [1] Channel 3 Trigger Enable */ uint32_t CH4TRIG : 1; /*!< [2] Channel 4 Trigger Enable */ uint32_t CH5TRIG : 1; /*!< [3] Channel 5 Trigger Enable */ uint32_t CH0TRIG : 1; /*!< [4] Channel 0 Trigger Enable */ uint32_t CH1TRIG : 1; /*!< [5] Channel 1 Trigger Enable */ uint32_t INITTRIGEN : 1; /*!< [6] Initialization Trigger Enable */ uint32_t TRIGF : 1; /*!< [7] Channel Trigger Flag */ uint32_t RESERVED0 : 24; /*!< [31:8] */ } B; } hw_ftm_exttrig_t; /*! * @name Constants and macros for entire FTM_EXTTRIG register */ /*@{*/ #define HW_FTM_EXTTRIG_ADDR(x) ((x) + 0x6CU) #define HW_FTM_EXTTRIG(x) (*(__IO hw_ftm_exttrig_t *) HW_FTM_EXTTRIG_ADDR(x)) #define HW_FTM_EXTTRIG_RD(x) (HW_FTM_EXTTRIG(x).U) #define HW_FTM_EXTTRIG_WR(x, v) (HW_FTM_EXTTRIG(x).U = (v)) #define HW_FTM_EXTTRIG_SET(x, v) (HW_FTM_EXTTRIG_WR(x, HW_FTM_EXTTRIG_RD(x) | (v))) #define HW_FTM_EXTTRIG_CLR(x, v) (HW_FTM_EXTTRIG_WR(x, HW_FTM_EXTTRIG_RD(x) & ~(v))) #define HW_FTM_EXTTRIG_TOG(x, v) (HW_FTM_EXTTRIG_WR(x, HW_FTM_EXTTRIG_RD(x) ^ (v))) /*@}*/ /* * Constants & macros for individual FTM_EXTTRIG bitfields */ /*! * @name Register FTM_EXTTRIG, field CH2TRIG[0] (RW) * * Enables the generation of the channel trigger when the FTM counter is equal * to the CnV register. * * Values: * - 0 - The generation of the channel trigger is disabled. * - 1 - The generation of the channel trigger is enabled. */ /*@{*/ #define BP_FTM_EXTTRIG_CH2TRIG (0U) /*!< Bit position for FTM_EXTTRIG_CH2TRIG. */ #define BM_FTM_EXTTRIG_CH2TRIG (0x00000001U) /*!< Bit mask for FTM_EXTTRIG_CH2TRIG. */ #define BS_FTM_EXTTRIG_CH2TRIG (1U) /*!< Bit field size in bits for FTM_EXTTRIG_CH2TRIG. */ /*! @brief Read current value of the FTM_EXTTRIG_CH2TRIG field. */ #define BR_FTM_EXTTRIG_CH2TRIG(x) (BITBAND_ACCESS32(HW_FTM_EXTTRIG_ADDR(x), BP_FTM_EXTTRIG_CH2TRIG)) /*! @brief Format value for bitfield FTM_EXTTRIG_CH2TRIG. */ #define BF_FTM_EXTTRIG_CH2TRIG(v) ((uint32_t)((uint32_t)(v) << BP_FTM_EXTTRIG_CH2TRIG) & BM_FTM_EXTTRIG_CH2TRIG) /*! @brief Set the CH2TRIG field to a new value. */ #define BW_FTM_EXTTRIG_CH2TRIG(x, v) (BITBAND_ACCESS32(HW_FTM_EXTTRIG_ADDR(x), BP_FTM_EXTTRIG_CH2TRIG) = (v)) /*@}*/ /*! * @name Register FTM_EXTTRIG, field CH3TRIG[1] (RW) * * Enables the generation of the channel trigger when the FTM counter is equal * to the CnV register. * * Values: * - 0 - The generation of the channel trigger is disabled. * - 1 - The generation of the channel trigger is enabled. */ /*@{*/ #define BP_FTM_EXTTRIG_CH3TRIG (1U) /*!< Bit position for FTM_EXTTRIG_CH3TRIG. */ #define BM_FTM_EXTTRIG_CH3TRIG (0x00000002U) /*!< Bit mask for FTM_EXTTRIG_CH3TRIG. */ #define BS_FTM_EXTTRIG_CH3TRIG (1U) /*!< Bit field size in bits for FTM_EXTTRIG_CH3TRIG. */ /*! @brief Read current value of the FTM_EXTTRIG_CH3TRIG field. */ #define BR_FTM_EXTTRIG_CH3TRIG(x) (BITBAND_ACCESS32(HW_FTM_EXTTRIG_ADDR(x), BP_FTM_EXTTRIG_CH3TRIG)) /*! @brief Format value for bitfield FTM_EXTTRIG_CH3TRIG. */ #define BF_FTM_EXTTRIG_CH3TRIG(v) ((uint32_t)((uint32_t)(v) << BP_FTM_EXTTRIG_CH3TRIG) & BM_FTM_EXTTRIG_CH3TRIG) /*! @brief Set the CH3TRIG field to a new value. */ #define BW_FTM_EXTTRIG_CH3TRIG(x, v) (BITBAND_ACCESS32(HW_FTM_EXTTRIG_ADDR(x), BP_FTM_EXTTRIG_CH3TRIG) = (v)) /*@}*/ /*! * @name Register FTM_EXTTRIG, field CH4TRIG[2] (RW) * * Enables the generation of the channel trigger when the FTM counter is equal * to the CnV register. * * Values: * - 0 - The generation of the channel trigger is disabled. * - 1 - The generation of the channel trigger is enabled. */ /*@{*/ #define BP_FTM_EXTTRIG_CH4TRIG (2U) /*!< Bit position for FTM_EXTTRIG_CH4TRIG. */ #define BM_FTM_EXTTRIG_CH4TRIG (0x00000004U) /*!< Bit mask for FTM_EXTTRIG_CH4TRIG. */ #define BS_FTM_EXTTRIG_CH4TRIG (1U) /*!< Bit field size in bits for FTM_EXTTRIG_CH4TRIG. */ /*! @brief Read current value of the FTM_EXTTRIG_CH4TRIG field. */ #define BR_FTM_EXTTRIG_CH4TRIG(x) (BITBAND_ACCESS32(HW_FTM_EXTTRIG_ADDR(x), BP_FTM_EXTTRIG_CH4TRIG)) /*! @brief Format value for bitfield FTM_EXTTRIG_CH4TRIG. */ #define BF_FTM_EXTTRIG_CH4TRIG(v) ((uint32_t)((uint32_t)(v) << BP_FTM_EXTTRIG_CH4TRIG) & BM_FTM_EXTTRIG_CH4TRIG) /*! @brief Set the CH4TRIG field to a new value. */ #define BW_FTM_EXTTRIG_CH4TRIG(x, v) (BITBAND_ACCESS32(HW_FTM_EXTTRIG_ADDR(x), BP_FTM_EXTTRIG_CH4TRIG) = (v)) /*@}*/ /*! * @name Register FTM_EXTTRIG, field CH5TRIG[3] (RW) * * Enables the generation of the channel trigger when the FTM counter is equal * to the CnV register. * * Values: * - 0 - The generation of the channel trigger is disabled. * - 1 - The generation of the channel trigger is enabled. */ /*@{*/ #define BP_FTM_EXTTRIG_CH5TRIG (3U) /*!< Bit position for FTM_EXTTRIG_CH5TRIG. */ #define BM_FTM_EXTTRIG_CH5TRIG (0x00000008U) /*!< Bit mask for FTM_EXTTRIG_CH5TRIG. */ #define BS_FTM_EXTTRIG_CH5TRIG (1U) /*!< Bit field size in bits for FTM_EXTTRIG_CH5TRIG. */ /*! @brief Read current value of the FTM_EXTTRIG_CH5TRIG field. */ #define BR_FTM_EXTTRIG_CH5TRIG(x) (BITBAND_ACCESS32(HW_FTM_EXTTRIG_ADDR(x), BP_FTM_EXTTRIG_CH5TRIG)) /*! @brief Format value for bitfield FTM_EXTTRIG_CH5TRIG. */ #define BF_FTM_EXTTRIG_CH5TRIG(v) ((uint32_t)((uint32_t)(v) << BP_FTM_EXTTRIG_CH5TRIG) & BM_FTM_EXTTRIG_CH5TRIG) /*! @brief Set the CH5TRIG field to a new value. */ #define BW_FTM_EXTTRIG_CH5TRIG(x, v) (BITBAND_ACCESS32(HW_FTM_EXTTRIG_ADDR(x), BP_FTM_EXTTRIG_CH5TRIG) = (v)) /*@}*/ /*! * @name Register FTM_EXTTRIG, field CH0TRIG[4] (RW) * * Enables the generation of the channel trigger when the FTM counter is equal * to the CnV register. * * Values: * - 0 - The generation of the channel trigger is disabled. * - 1 - The generation of the channel trigger is enabled. */ /*@{*/ #define BP_FTM_EXTTRIG_CH0TRIG (4U) /*!< Bit position for FTM_EXTTRIG_CH0TRIG. */ #define BM_FTM_EXTTRIG_CH0TRIG (0x00000010U) /*!< Bit mask for FTM_EXTTRIG_CH0TRIG. */ #define BS_FTM_EXTTRIG_CH0TRIG (1U) /*!< Bit field size in bits for FTM_EXTTRIG_CH0TRIG. */ /*! @brief Read current value of the FTM_EXTTRIG_CH0TRIG field. */ #define BR_FTM_EXTTRIG_CH0TRIG(x) (BITBAND_ACCESS32(HW_FTM_EXTTRIG_ADDR(x), BP_FTM_EXTTRIG_CH0TRIG)) /*! @brief Format value for bitfield FTM_EXTTRIG_CH0TRIG. */ #define BF_FTM_EXTTRIG_CH0TRIG(v) ((uint32_t)((uint32_t)(v) << BP_FTM_EXTTRIG_CH0TRIG) & BM_FTM_EXTTRIG_CH0TRIG) /*! @brief Set the CH0TRIG field to a new value. */ #define BW_FTM_EXTTRIG_CH0TRIG(x, v) (BITBAND_ACCESS32(HW_FTM_EXTTRIG_ADDR(x), BP_FTM_EXTTRIG_CH0TRIG) = (v)) /*@}*/ /*! * @name Register FTM_EXTTRIG, field CH1TRIG[5] (RW) * * Enables the generation of the channel trigger when the FTM counter is equal * to the CnV register. * * Values: * - 0 - The generation of the channel trigger is disabled. * - 1 - The generation of the channel trigger is enabled. */ /*@{*/ #define BP_FTM_EXTTRIG_CH1TRIG (5U) /*!< Bit position for FTM_EXTTRIG_CH1TRIG. */ #define BM_FTM_EXTTRIG_CH1TRIG (0x00000020U) /*!< Bit mask for FTM_EXTTRIG_CH1TRIG. */ #define BS_FTM_EXTTRIG_CH1TRIG (1U) /*!< Bit field size in bits for FTM_EXTTRIG_CH1TRIG. */ /*! @brief Read current value of the FTM_EXTTRIG_CH1TRIG field. */ #define BR_FTM_EXTTRIG_CH1TRIG(x) (BITBAND_ACCESS32(HW_FTM_EXTTRIG_ADDR(x), BP_FTM_EXTTRIG_CH1TRIG)) /*! @brief Format value for bitfield FTM_EXTTRIG_CH1TRIG. */ #define BF_FTM_EXTTRIG_CH1TRIG(v) ((uint32_t)((uint32_t)(v) << BP_FTM_EXTTRIG_CH1TRIG) & BM_FTM_EXTTRIG_CH1TRIG) /*! @brief Set the CH1TRIG field to a new value. */ #define BW_FTM_EXTTRIG_CH1TRIG(x, v) (BITBAND_ACCESS32(HW_FTM_EXTTRIG_ADDR(x), BP_FTM_EXTTRIG_CH1TRIG) = (v)) /*@}*/ /*! * @name Register FTM_EXTTRIG, field INITTRIGEN[6] (RW) * * Enables the generation of the trigger when the FTM counter is equal to the * CNTIN register. * * Values: * - 0 - The generation of initialization trigger is disabled. * - 1 - The generation of initialization trigger is enabled. */ /*@{*/ #define BP_FTM_EXTTRIG_INITTRIGEN (6U) /*!< Bit position for FTM_EXTTRIG_INITTRIGEN. */ #define BM_FTM_EXTTRIG_INITTRIGEN (0x00000040U) /*!< Bit mask for FTM_EXTTRIG_INITTRIGEN. */ #define BS_FTM_EXTTRIG_INITTRIGEN (1U) /*!< Bit field size in bits for FTM_EXTTRIG_INITTRIGEN. */ /*! @brief Read current value of the FTM_EXTTRIG_INITTRIGEN field. */ #define BR_FTM_EXTTRIG_INITTRIGEN(x) (BITBAND_ACCESS32(HW_FTM_EXTTRIG_ADDR(x), BP_FTM_EXTTRIG_INITTRIGEN)) /*! @brief Format value for bitfield FTM_EXTTRIG_INITTRIGEN. */ #define BF_FTM_EXTTRIG_INITTRIGEN(v) ((uint32_t)((uint32_t)(v) << BP_FTM_EXTTRIG_INITTRIGEN) & BM_FTM_EXTTRIG_INITTRIGEN) /*! @brief Set the INITTRIGEN field to a new value. */ #define BW_FTM_EXTTRIG_INITTRIGEN(x, v) (BITBAND_ACCESS32(HW_FTM_EXTTRIG_ADDR(x), BP_FTM_EXTTRIG_INITTRIGEN) = (v)) /*@}*/ /*! * @name Register FTM_EXTTRIG, field TRIGF[7] (ROWZ) * * Set by hardware when a channel trigger is generated. Clear TRIGF by reading * EXTTRIG while TRIGF is set and then writing a 0 to TRIGF. Writing a 1 to TRIGF * has no effect. If another channel trigger is generated before the clearing * sequence is completed, the sequence is reset so TRIGF remains set after the clear * sequence is completed for the earlier TRIGF. * * Values: * - 0 - No channel trigger was generated. * - 1 - A channel trigger was generated. */ /*@{*/ #define BP_FTM_EXTTRIG_TRIGF (7U) /*!< Bit position for FTM_EXTTRIG_TRIGF. */ #define BM_FTM_EXTTRIG_TRIGF (0x00000080U) /*!< Bit mask for FTM_EXTTRIG_TRIGF. */ #define BS_FTM_EXTTRIG_TRIGF (1U) /*!< Bit field size in bits for FTM_EXTTRIG_TRIGF. */ /*! @brief Read current value of the FTM_EXTTRIG_TRIGF field. */ #define BR_FTM_EXTTRIG_TRIGF(x) (BITBAND_ACCESS32(HW_FTM_EXTTRIG_ADDR(x), BP_FTM_EXTTRIG_TRIGF)) /*! @brief Format value for bitfield FTM_EXTTRIG_TRIGF. */ #define BF_FTM_EXTTRIG_TRIGF(v) ((uint32_t)((uint32_t)(v) << BP_FTM_EXTTRIG_TRIGF) & BM_FTM_EXTTRIG_TRIGF) /*! @brief Set the TRIGF field to a new value. */ #define BW_FTM_EXTTRIG_TRIGF(x, v) (BITBAND_ACCESS32(HW_FTM_EXTTRIG_ADDR(x), BP_FTM_EXTTRIG_TRIGF) = (v)) /*@}*/ /******************************************************************************* * HW_FTM_POL - Channels Polarity ******************************************************************************/ /*! * @brief HW_FTM_POL - Channels Polarity (RW) * * Reset value: 0x00000000U * * This register defines the output polarity of the FTM channels. The safe value * that is driven in a channel output when the fault control is enabled and a * fault condition is detected is the inactive state of the channel. That is, the * safe value of a channel is the value of its POL bit. */ typedef union _hw_ftm_pol { uint32_t U; struct _hw_ftm_pol_bitfields { uint32_t POL0 : 1; /*!< [0] Channel 0 Polarity */ uint32_t POL1 : 1; /*!< [1] Channel 1 Polarity */ uint32_t POL2 : 1; /*!< [2] Channel 2 Polarity */ uint32_t POL3 : 1; /*!< [3] Channel 3 Polarity */ uint32_t POL4 : 1; /*!< [4] Channel 4 Polarity */ uint32_t POL5 : 1; /*!< [5] Channel 5 Polarity */ uint32_t POL6 : 1; /*!< [6] Channel 6 Polarity */ uint32_t POL7 : 1; /*!< [7] Channel 7 Polarity */ uint32_t RESERVED0 : 24; /*!< [31:8] */ } B; } hw_ftm_pol_t; /*! * @name Constants and macros for entire FTM_POL register */ /*@{*/ #define HW_FTM_POL_ADDR(x) ((x) + 0x70U) #define HW_FTM_POL(x) (*(__IO hw_ftm_pol_t *) HW_FTM_POL_ADDR(x)) #define HW_FTM_POL_RD(x) (HW_FTM_POL(x).U) #define HW_FTM_POL_WR(x, v) (HW_FTM_POL(x).U = (v)) #define HW_FTM_POL_SET(x, v) (HW_FTM_POL_WR(x, HW_FTM_POL_RD(x) | (v))) #define HW_FTM_POL_CLR(x, v) (HW_FTM_POL_WR(x, HW_FTM_POL_RD(x) & ~(v))) #define HW_FTM_POL_TOG(x, v) (HW_FTM_POL_WR(x, HW_FTM_POL_RD(x) ^ (v))) /*@}*/ /* * Constants & macros for individual FTM_POL bitfields */ /*! * @name Register FTM_POL, field POL0[0] (RW) * * Defines the polarity of the channel output. This field is write protected. It * can be written only when MODE[WPDIS] = 1. * * Values: * - 0 - The channel polarity is active high. * - 1 - The channel polarity is active low. */ /*@{*/ #define BP_FTM_POL_POL0 (0U) /*!< Bit position for FTM_POL_POL0. */ #define BM_FTM_POL_POL0 (0x00000001U) /*!< Bit mask for FTM_POL_POL0. */ #define BS_FTM_POL_POL0 (1U) /*!< Bit field size in bits for FTM_POL_POL0. */ /*! @brief Read current value of the FTM_POL_POL0 field. */ #define BR_FTM_POL_POL0(x) (BITBAND_ACCESS32(HW_FTM_POL_ADDR(x), BP_FTM_POL_POL0)) /*! @brief Format value for bitfield FTM_POL_POL0. */ #define BF_FTM_POL_POL0(v) ((uint32_t)((uint32_t)(v) << BP_FTM_POL_POL0) & BM_FTM_POL_POL0) /*! @brief Set the POL0 field to a new value. */ #define BW_FTM_POL_POL0(x, v) (BITBAND_ACCESS32(HW_FTM_POL_ADDR(x), BP_FTM_POL_POL0) = (v)) /*@}*/ /*! * @name Register FTM_POL, field POL1[1] (RW) * * Defines the polarity of the channel output. This field is write protected. It * can be written only when MODE[WPDIS] = 1. * * Values: * - 0 - The channel polarity is active high. * - 1 - The channel polarity is active low. */ /*@{*/ #define BP_FTM_POL_POL1 (1U) /*!< Bit position for FTM_POL_POL1. */ #define BM_FTM_POL_POL1 (0x00000002U) /*!< Bit mask for FTM_POL_POL1. */ #define BS_FTM_POL_POL1 (1U) /*!< Bit field size in bits for FTM_POL_POL1. */ /*! @brief Read current value of the FTM_POL_POL1 field. */ #define BR_FTM_POL_POL1(x) (BITBAND_ACCESS32(HW_FTM_POL_ADDR(x), BP_FTM_POL_POL1)) /*! @brief Format value for bitfield FTM_POL_POL1. */ #define BF_FTM_POL_POL1(v) ((uint32_t)((uint32_t)(v) << BP_FTM_POL_POL1) & BM_FTM_POL_POL1) /*! @brief Set the POL1 field to a new value. */ #define BW_FTM_POL_POL1(x, v) (BITBAND_ACCESS32(HW_FTM_POL_ADDR(x), BP_FTM_POL_POL1) = (v)) /*@}*/ /*! * @name Register FTM_POL, field POL2[2] (RW) * * Defines the polarity of the channel output. This field is write protected. It * can be written only when MODE[WPDIS] = 1. * * Values: * - 0 - The channel polarity is active high. * - 1 - The channel polarity is active low. */ /*@{*/ #define BP_FTM_POL_POL2 (2U) /*!< Bit position for FTM_POL_POL2. */ #define BM_FTM_POL_POL2 (0x00000004U) /*!< Bit mask for FTM_POL_POL2. */ #define BS_FTM_POL_POL2 (1U) /*!< Bit field size in bits for FTM_POL_POL2. */ /*! @brief Read current value of the FTM_POL_POL2 field. */ #define BR_FTM_POL_POL2(x) (BITBAND_ACCESS32(HW_FTM_POL_ADDR(x), BP_FTM_POL_POL2)) /*! @brief Format value for bitfield FTM_POL_POL2. */ #define BF_FTM_POL_POL2(v) ((uint32_t)((uint32_t)(v) << BP_FTM_POL_POL2) & BM_FTM_POL_POL2) /*! @brief Set the POL2 field to a new value. */ #define BW_FTM_POL_POL2(x, v) (BITBAND_ACCESS32(HW_FTM_POL_ADDR(x), BP_FTM_POL_POL2) = (v)) /*@}*/ /*! * @name Register FTM_POL, field POL3[3] (RW) * * Defines the polarity of the channel output. This field is write protected. It * can be written only when MODE[WPDIS] = 1. * * Values: * - 0 - The channel polarity is active high. * - 1 - The channel polarity is active low. */ /*@{*/ #define BP_FTM_POL_POL3 (3U) /*!< Bit position for FTM_POL_POL3. */ #define BM_FTM_POL_POL3 (0x00000008U) /*!< Bit mask for FTM_POL_POL3. */ #define BS_FTM_POL_POL3 (1U) /*!< Bit field size in bits for FTM_POL_POL3. */ /*! @brief Read current value of the FTM_POL_POL3 field. */ #define BR_FTM_POL_POL3(x) (BITBAND_ACCESS32(HW_FTM_POL_ADDR(x), BP_FTM_POL_POL3)) /*! @brief Format value for bitfield FTM_POL_POL3. */ #define BF_FTM_POL_POL3(v) ((uint32_t)((uint32_t)(v) << BP_FTM_POL_POL3) & BM_FTM_POL_POL3) /*! @brief Set the POL3 field to a new value. */ #define BW_FTM_POL_POL3(x, v) (BITBAND_ACCESS32(HW_FTM_POL_ADDR(x), BP_FTM_POL_POL3) = (v)) /*@}*/ /*! * @name Register FTM_POL, field POL4[4] (RW) * * Defines the polarity of the channel output. This field is write protected. It * can be written only when MODE[WPDIS] = 1. * * Values: * - 0 - The channel polarity is active high. * - 1 - The channel polarity is active low. */ /*@{*/ #define BP_FTM_POL_POL4 (4U) /*!< Bit position for FTM_POL_POL4. */ #define BM_FTM_POL_POL4 (0x00000010U) /*!< Bit mask for FTM_POL_POL4. */ #define BS_FTM_POL_POL4 (1U) /*!< Bit field size in bits for FTM_POL_POL4. */ /*! @brief Read current value of the FTM_POL_POL4 field. */ #define BR_FTM_POL_POL4(x) (BITBAND_ACCESS32(HW_FTM_POL_ADDR(x), BP_FTM_POL_POL4)) /*! @brief Format value for bitfield FTM_POL_POL4. */ #define BF_FTM_POL_POL4(v) ((uint32_t)((uint32_t)(v) << BP_FTM_POL_POL4) & BM_FTM_POL_POL4) /*! @brief Set the POL4 field to a new value. */ #define BW_FTM_POL_POL4(x, v) (BITBAND_ACCESS32(HW_FTM_POL_ADDR(x), BP_FTM_POL_POL4) = (v)) /*@}*/ /*! * @name Register FTM_POL, field POL5[5] (RW) * * Defines the polarity of the channel output. This field is write protected. It * can be written only when MODE[WPDIS] = 1. * * Values: * - 0 - The channel polarity is active high. * - 1 - The channel polarity is active low. */ /*@{*/ #define BP_FTM_POL_POL5 (5U) /*!< Bit position for FTM_POL_POL5. */ #define BM_FTM_POL_POL5 (0x00000020U) /*!< Bit mask for FTM_POL_POL5. */ #define BS_FTM_POL_POL5 (1U) /*!< Bit field size in bits for FTM_POL_POL5. */ /*! @brief Read current value of the FTM_POL_POL5 field. */ #define BR_FTM_POL_POL5(x) (BITBAND_ACCESS32(HW_FTM_POL_ADDR(x), BP_FTM_POL_POL5)) /*! @brief Format value for bitfield FTM_POL_POL5. */ #define BF_FTM_POL_POL5(v) ((uint32_t)((uint32_t)(v) << BP_FTM_POL_POL5) & BM_FTM_POL_POL5) /*! @brief Set the POL5 field to a new value. */ #define BW_FTM_POL_POL5(x, v) (BITBAND_ACCESS32(HW_FTM_POL_ADDR(x), BP_FTM_POL_POL5) = (v)) /*@}*/ /*! * @name Register FTM_POL, field POL6[6] (RW) * * Defines the polarity of the channel output. This field is write protected. It * can be written only when MODE[WPDIS] = 1. * * Values: * - 0 - The channel polarity is active high. * - 1 - The channel polarity is active low. */ /*@{*/ #define BP_FTM_POL_POL6 (6U) /*!< Bit position for FTM_POL_POL6. */ #define BM_FTM_POL_POL6 (0x00000040U) /*!< Bit mask for FTM_POL_POL6. */ #define BS_FTM_POL_POL6 (1U) /*!< Bit field size in bits for FTM_POL_POL6. */ /*! @brief Read current value of the FTM_POL_POL6 field. */ #define BR_FTM_POL_POL6(x) (BITBAND_ACCESS32(HW_FTM_POL_ADDR(x), BP_FTM_POL_POL6)) /*! @brief Format value for bitfield FTM_POL_POL6. */ #define BF_FTM_POL_POL6(v) ((uint32_t)((uint32_t)(v) << BP_FTM_POL_POL6) & BM_FTM_POL_POL6) /*! @brief Set the POL6 field to a new value. */ #define BW_FTM_POL_POL6(x, v) (BITBAND_ACCESS32(HW_FTM_POL_ADDR(x), BP_FTM_POL_POL6) = (v)) /*@}*/ /*! * @name Register FTM_POL, field POL7[7] (RW) * * Defines the polarity of the channel output. This field is write protected. It * can be written only when MODE[WPDIS] = 1. * * Values: * - 0 - The channel polarity is active high. * - 1 - The channel polarity is active low. */ /*@{*/ #define BP_FTM_POL_POL7 (7U) /*!< Bit position for FTM_POL_POL7. */ #define BM_FTM_POL_POL7 (0x00000080U) /*!< Bit mask for FTM_POL_POL7. */ #define BS_FTM_POL_POL7 (1U) /*!< Bit field size in bits for FTM_POL_POL7. */ /*! @brief Read current value of the FTM_POL_POL7 field. */ #define BR_FTM_POL_POL7(x) (BITBAND_ACCESS32(HW_FTM_POL_ADDR(x), BP_FTM_POL_POL7)) /*! @brief Format value for bitfield FTM_POL_POL7. */ #define BF_FTM_POL_POL7(v) ((uint32_t)((uint32_t)(v) << BP_FTM_POL_POL7) & BM_FTM_POL_POL7) /*! @brief Set the POL7 field to a new value. */ #define BW_FTM_POL_POL7(x, v) (BITBAND_ACCESS32(HW_FTM_POL_ADDR(x), BP_FTM_POL_POL7) = (v)) /*@}*/ /******************************************************************************* * HW_FTM_FMS - Fault Mode Status ******************************************************************************/ /*! * @brief HW_FTM_FMS - Fault Mode Status (RW) * * Reset value: 0x00000000U * * This register contains the fault detection flags, write protection enable * bit, and the logic OR of the enabled fault inputs. */ typedef union _hw_ftm_fms { uint32_t U; struct _hw_ftm_fms_bitfields { uint32_t FAULTF0 : 1; /*!< [0] Fault Detection Flag 0 */ uint32_t FAULTF1 : 1; /*!< [1] Fault Detection Flag 1 */ uint32_t FAULTF2 : 1; /*!< [2] Fault Detection Flag 2 */ uint32_t FAULTF3 : 1; /*!< [3] Fault Detection Flag 3 */ uint32_t RESERVED0 : 1; /*!< [4] */ uint32_t FAULTIN : 1; /*!< [5] Fault Inputs */ uint32_t WPEN : 1; /*!< [6] Write Protection Enable */ uint32_t FAULTF : 1; /*!< [7] Fault Detection Flag */ uint32_t RESERVED1 : 24; /*!< [31:8] */ } B; } hw_ftm_fms_t; /*! * @name Constants and macros for entire FTM_FMS register */ /*@{*/ #define HW_FTM_FMS_ADDR(x) ((x) + 0x74U) #define HW_FTM_FMS(x) (*(__IO hw_ftm_fms_t *) HW_FTM_FMS_ADDR(x)) #define HW_FTM_FMS_RD(x) (HW_FTM_FMS(x).U) #define HW_FTM_FMS_WR(x, v) (HW_FTM_FMS(x).U = (v)) #define HW_FTM_FMS_SET(x, v) (HW_FTM_FMS_WR(x, HW_FTM_FMS_RD(x) | (v))) #define HW_FTM_FMS_CLR(x, v) (HW_FTM_FMS_WR(x, HW_FTM_FMS_RD(x) & ~(v))) #define HW_FTM_FMS_TOG(x, v) (HW_FTM_FMS_WR(x, HW_FTM_FMS_RD(x) ^ (v))) /*@}*/ /* * Constants & macros for individual FTM_FMS bitfields */ /*! * @name Register FTM_FMS, field FAULTF0[0] (ROWZ) * * Set by hardware when fault control is enabled, the corresponding fault input * is enabled and a fault condition is detected at the fault input. Clear FAULTF0 * by reading the FMS register while FAULTF0 is set and then writing a 0 to * FAULTF0 while there is no existing fault condition at the corresponding fault * input. Writing a 1 to FAULTF0 has no effect. FAULTF0 bit is also cleared when * FAULTF bit is cleared. If another fault condition is detected at the corresponding * fault input before the clearing sequence is completed, the sequence is reset * so FAULTF0 remains set after the clearing sequence is completed for the * earlier fault condition. * * Values: * - 0 - No fault condition was detected at the fault input. * - 1 - A fault condition was detected at the fault input. */ /*@{*/ #define BP_FTM_FMS_FAULTF0 (0U) /*!< Bit position for FTM_FMS_FAULTF0. */ #define BM_FTM_FMS_FAULTF0 (0x00000001U) /*!< Bit mask for FTM_FMS_FAULTF0. */ #define BS_FTM_FMS_FAULTF0 (1U) /*!< Bit field size in bits for FTM_FMS_FAULTF0. */ /*! @brief Read current value of the FTM_FMS_FAULTF0 field. */ #define BR_FTM_FMS_FAULTF0(x) (BITBAND_ACCESS32(HW_FTM_FMS_ADDR(x), BP_FTM_FMS_FAULTF0)) /*! @brief Format value for bitfield FTM_FMS_FAULTF0. */ #define BF_FTM_FMS_FAULTF0(v) ((uint32_t)((uint32_t)(v) << BP_FTM_FMS_FAULTF0) & BM_FTM_FMS_FAULTF0) /*! @brief Set the FAULTF0 field to a new value. */ #define BW_FTM_FMS_FAULTF0(x, v) (BITBAND_ACCESS32(HW_FTM_FMS_ADDR(x), BP_FTM_FMS_FAULTF0) = (v)) /*@}*/ /*! * @name Register FTM_FMS, field FAULTF1[1] (ROWZ) * * Set by hardware when fault control is enabled, the corresponding fault input * is enabled and a fault condition is detected at the fault input. Clear FAULTF1 * by reading the FMS register while FAULTF1 is set and then writing a 0 to * FAULTF1 while there is no existing fault condition at the corresponding fault * input. Writing a 1 to FAULTF1 has no effect. FAULTF1 bit is also cleared when * FAULTF bit is cleared. If another fault condition is detected at the corresponding * fault input before the clearing sequence is completed, the sequence is reset * so FAULTF1 remains set after the clearing sequence is completed for the * earlier fault condition. * * Values: * - 0 - No fault condition was detected at the fault input. * - 1 - A fault condition was detected at the fault input. */ /*@{*/ #define BP_FTM_FMS_FAULTF1 (1U) /*!< Bit position for FTM_FMS_FAULTF1. */ #define BM_FTM_FMS_FAULTF1 (0x00000002U) /*!< Bit mask for FTM_FMS_FAULTF1. */ #define BS_FTM_FMS_FAULTF1 (1U) /*!< Bit field size in bits for FTM_FMS_FAULTF1. */ /*! @brief Read current value of the FTM_FMS_FAULTF1 field. */ #define BR_FTM_FMS_FAULTF1(x) (BITBAND_ACCESS32(HW_FTM_FMS_ADDR(x), BP_FTM_FMS_FAULTF1)) /*! @brief Format value for bitfield FTM_FMS_FAULTF1. */ #define BF_FTM_FMS_FAULTF1(v) ((uint32_t)((uint32_t)(v) << BP_FTM_FMS_FAULTF1) & BM_FTM_FMS_FAULTF1) /*! @brief Set the FAULTF1 field to a new value. */ #define BW_FTM_FMS_FAULTF1(x, v) (BITBAND_ACCESS32(HW_FTM_FMS_ADDR(x), BP_FTM_FMS_FAULTF1) = (v)) /*@}*/ /*! * @name Register FTM_FMS, field FAULTF2[2] (ROWZ) * * Set by hardware when fault control is enabled, the corresponding fault input * is enabled and a fault condition is detected at the fault input. Clear FAULTF2 * by reading the FMS register while FAULTF2 is set and then writing a 0 to * FAULTF2 while there is no existing fault condition at the corresponding fault * input. Writing a 1 to FAULTF2 has no effect. FAULTF2 bit is also cleared when * FAULTF bit is cleared. If another fault condition is detected at the corresponding * fault input before the clearing sequence is completed, the sequence is reset * so FAULTF2 remains set after the clearing sequence is completed for the * earlier fault condition. * * Values: * - 0 - No fault condition was detected at the fault input. * - 1 - A fault condition was detected at the fault input. */ /*@{*/ #define BP_FTM_FMS_FAULTF2 (2U) /*!< Bit position for FTM_FMS_FAULTF2. */ #define BM_FTM_FMS_FAULTF2 (0x00000004U) /*!< Bit mask for FTM_FMS_FAULTF2. */ #define BS_FTM_FMS_FAULTF2 (1U) /*!< Bit field size in bits for FTM_FMS_FAULTF2. */ /*! @brief Read current value of the FTM_FMS_FAULTF2 field. */ #define BR_FTM_FMS_FAULTF2(x) (BITBAND_ACCESS32(HW_FTM_FMS_ADDR(x), BP_FTM_FMS_FAULTF2)) /*! @brief Format value for bitfield FTM_FMS_FAULTF2. */ #define BF_FTM_FMS_FAULTF2(v) ((uint32_t)((uint32_t)(v) << BP_FTM_FMS_FAULTF2) & BM_FTM_FMS_FAULTF2) /*! @brief Set the FAULTF2 field to a new value. */ #define BW_FTM_FMS_FAULTF2(x, v) (BITBAND_ACCESS32(HW_FTM_FMS_ADDR(x), BP_FTM_FMS_FAULTF2) = (v)) /*@}*/ /*! * @name Register FTM_FMS, field FAULTF3[3] (ROWZ) * * Set by hardware when fault control is enabled, the corresponding fault input * is enabled and a fault condition is detected at the fault input. Clear FAULTF3 * by reading the FMS register while FAULTF3 is set and then writing a 0 to * FAULTF3 while there is no existing fault condition at the corresponding fault * input. Writing a 1 to FAULTF3 has no effect. FAULTF3 bit is also cleared when * FAULTF bit is cleared. If another fault condition is detected at the corresponding * fault input before the clearing sequence is completed, the sequence is reset * so FAULTF3 remains set after the clearing sequence is completed for the * earlier fault condition. * * Values: * - 0 - No fault condition was detected at the fault input. * - 1 - A fault condition was detected at the fault input. */ /*@{*/ #define BP_FTM_FMS_FAULTF3 (3U) /*!< Bit position for FTM_FMS_FAULTF3. */ #define BM_FTM_FMS_FAULTF3 (0x00000008U) /*!< Bit mask for FTM_FMS_FAULTF3. */ #define BS_FTM_FMS_FAULTF3 (1U) /*!< Bit field size in bits for FTM_FMS_FAULTF3. */ /*! @brief Read current value of the FTM_FMS_FAULTF3 field. */ #define BR_FTM_FMS_FAULTF3(x) (BITBAND_ACCESS32(HW_FTM_FMS_ADDR(x), BP_FTM_FMS_FAULTF3)) /*! @brief Format value for bitfield FTM_FMS_FAULTF3. */ #define BF_FTM_FMS_FAULTF3(v) ((uint32_t)((uint32_t)(v) << BP_FTM_FMS_FAULTF3) & BM_FTM_FMS_FAULTF3) /*! @brief Set the FAULTF3 field to a new value. */ #define BW_FTM_FMS_FAULTF3(x, v) (BITBAND_ACCESS32(HW_FTM_FMS_ADDR(x), BP_FTM_FMS_FAULTF3) = (v)) /*@}*/ /*! * @name Register FTM_FMS, field FAULTIN[5] (RO) * * Represents the logic OR of the enabled fault inputs after their filter (if * their filter is enabled) when fault control is enabled. * * Values: * - 0 - The logic OR of the enabled fault inputs is 0. * - 1 - The logic OR of the enabled fault inputs is 1. */ /*@{*/ #define BP_FTM_FMS_FAULTIN (5U) /*!< Bit position for FTM_FMS_FAULTIN. */ #define BM_FTM_FMS_FAULTIN (0x00000020U) /*!< Bit mask for FTM_FMS_FAULTIN. */ #define BS_FTM_FMS_FAULTIN (1U) /*!< Bit field size in bits for FTM_FMS_FAULTIN. */ /*! @brief Read current value of the FTM_FMS_FAULTIN field. */ #define BR_FTM_FMS_FAULTIN(x) (BITBAND_ACCESS32(HW_FTM_FMS_ADDR(x), BP_FTM_FMS_FAULTIN)) /*@}*/ /*! * @name Register FTM_FMS, field WPEN[6] (RW) * * The WPEN bit is the negation of the WPDIS bit. WPEN is set when 1 is written * to it. WPEN is cleared when WPEN bit is read as a 1 and then 1 is written to * WPDIS. Writing 0 to WPEN has no effect. * * Values: * - 0 - Write protection is disabled. Write protected bits can be written. * - 1 - Write protection is enabled. Write protected bits cannot be written. */ /*@{*/ #define BP_FTM_FMS_WPEN (6U) /*!< Bit position for FTM_FMS_WPEN. */ #define BM_FTM_FMS_WPEN (0x00000040U) /*!< Bit mask for FTM_FMS_WPEN. */ #define BS_FTM_FMS_WPEN (1U) /*!< Bit field size in bits for FTM_FMS_WPEN. */ /*! @brief Read current value of the FTM_FMS_WPEN field. */ #define BR_FTM_FMS_WPEN(x) (BITBAND_ACCESS32(HW_FTM_FMS_ADDR(x), BP_FTM_FMS_WPEN)) /*! @brief Format value for bitfield FTM_FMS_WPEN. */ #define BF_FTM_FMS_WPEN(v) ((uint32_t)((uint32_t)(v) << BP_FTM_FMS_WPEN) & BM_FTM_FMS_WPEN) /*! @brief Set the WPEN field to a new value. */ #define BW_FTM_FMS_WPEN(x, v) (BITBAND_ACCESS32(HW_FTM_FMS_ADDR(x), BP_FTM_FMS_WPEN) = (v)) /*@}*/ /*! * @name Register FTM_FMS, field FAULTF[7] (ROWZ) * * Represents the logic OR of the individual FAULTFj bits where j = 3, 2, 1, 0. * Clear FAULTF by reading the FMS register while FAULTF is set and then writing * a 0 to FAULTF while there is no existing fault condition at the enabled fault * inputs. Writing a 1 to FAULTF has no effect. If another fault condition is * detected in an enabled fault input before the clearing sequence is completed, the * sequence is reset so FAULTF remains set after the clearing sequence is * completed for the earlier fault condition. FAULTF is also cleared when FAULTFj bits * are cleared individually. * * Values: * - 0 - No fault condition was detected. * - 1 - A fault condition was detected. */ /*@{*/ #define BP_FTM_FMS_FAULTF (7U) /*!< Bit position for FTM_FMS_FAULTF. */ #define BM_FTM_FMS_FAULTF (0x00000080U) /*!< Bit mask for FTM_FMS_FAULTF. */ #define BS_FTM_FMS_FAULTF (1U) /*!< Bit field size in bits for FTM_FMS_FAULTF. */ /*! @brief Read current value of the FTM_FMS_FAULTF field. */ #define BR_FTM_FMS_FAULTF(x) (BITBAND_ACCESS32(HW_FTM_FMS_ADDR(x), BP_FTM_FMS_FAULTF)) /*! @brief Format value for bitfield FTM_FMS_FAULTF. */ #define BF_FTM_FMS_FAULTF(v) ((uint32_t)((uint32_t)(v) << BP_FTM_FMS_FAULTF) & BM_FTM_FMS_FAULTF) /*! @brief Set the FAULTF field to a new value. */ #define BW_FTM_FMS_FAULTF(x, v) (BITBAND_ACCESS32(HW_FTM_FMS_ADDR(x), BP_FTM_FMS_FAULTF) = (v)) /*@}*/ /******************************************************************************* * HW_FTM_FILTER - Input Capture Filter Control ******************************************************************************/ /*! * @brief HW_FTM_FILTER - Input Capture Filter Control (RW) * * Reset value: 0x00000000U * * This register selects the filter value for the inputs of channels. Channels * 4, 5, 6 and 7 do not have an input filter. Writing to the FILTER register has * immediate effect and must be done only when the channels 0, 1, 2, and 3 are not * in input modes. Failure to do this could result in a missing valid signal. */ typedef union _hw_ftm_filter { uint32_t U; struct _hw_ftm_filter_bitfields { uint32_t CH0FVAL : 4; /*!< [3:0] Channel 0 Input Filter */ uint32_t CH1FVAL : 4; /*!< [7:4] Channel 1 Input Filter */ uint32_t CH2FVAL : 4; /*!< [11:8] Channel 2 Input Filter */ uint32_t CH3FVAL : 4; /*!< [15:12] Channel 3 Input Filter */ uint32_t RESERVED0 : 16; /*!< [31:16] */ } B; } hw_ftm_filter_t; /*! * @name Constants and macros for entire FTM_FILTER register */ /*@{*/ #define HW_FTM_FILTER_ADDR(x) ((x) + 0x78U) #define HW_FTM_FILTER(x) (*(__IO hw_ftm_filter_t *) HW_FTM_FILTER_ADDR(x)) #define HW_FTM_FILTER_RD(x) (HW_FTM_FILTER(x).U) #define HW_FTM_FILTER_WR(x, v) (HW_FTM_FILTER(x).U = (v)) #define HW_FTM_FILTER_SET(x, v) (HW_FTM_FILTER_WR(x, HW_FTM_FILTER_RD(x) | (v))) #define HW_FTM_FILTER_CLR(x, v) (HW_FTM_FILTER_WR(x, HW_FTM_FILTER_RD(x) & ~(v))) #define HW_FTM_FILTER_TOG(x, v) (HW_FTM_FILTER_WR(x, HW_FTM_FILTER_RD(x) ^ (v))) /*@}*/ /* * Constants & macros for individual FTM_FILTER bitfields */ /*! * @name Register FTM_FILTER, field CH0FVAL[3:0] (RW) * * Selects the filter value for the channel input. The filter is disabled when * the value is zero. */ /*@{*/ #define BP_FTM_FILTER_CH0FVAL (0U) /*!< Bit position for FTM_FILTER_CH0FVAL. */ #define BM_FTM_FILTER_CH0FVAL (0x0000000FU) /*!< Bit mask for FTM_FILTER_CH0FVAL. */ #define BS_FTM_FILTER_CH0FVAL (4U) /*!< Bit field size in bits for FTM_FILTER_CH0FVAL. */ /*! @brief Read current value of the FTM_FILTER_CH0FVAL field. */ #define BR_FTM_FILTER_CH0FVAL(x) (HW_FTM_FILTER(x).B.CH0FVAL) /*! @brief Format value for bitfield FTM_FILTER_CH0FVAL. */ #define BF_FTM_FILTER_CH0FVAL(v) ((uint32_t)((uint32_t)(v) << BP_FTM_FILTER_CH0FVAL) & BM_FTM_FILTER_CH0FVAL) /*! @brief Set the CH0FVAL field to a new value. */ #define BW_FTM_FILTER_CH0FVAL(x, v) (HW_FTM_FILTER_WR(x, (HW_FTM_FILTER_RD(x) & ~BM_FTM_FILTER_CH0FVAL) | BF_FTM_FILTER_CH0FVAL(v))) /*@}*/ /*! * @name Register FTM_FILTER, field CH1FVAL[7:4] (RW) * * Selects the filter value for the channel input. The filter is disabled when * the value is zero. */ /*@{*/ #define BP_FTM_FILTER_CH1FVAL (4U) /*!< Bit position for FTM_FILTER_CH1FVAL. */ #define BM_FTM_FILTER_CH1FVAL (0x000000F0U) /*!< Bit mask for FTM_FILTER_CH1FVAL. */ #define BS_FTM_FILTER_CH1FVAL (4U) /*!< Bit field size in bits for FTM_FILTER_CH1FVAL. */ /*! @brief Read current value of the FTM_FILTER_CH1FVAL field. */ #define BR_FTM_FILTER_CH1FVAL(x) (HW_FTM_FILTER(x).B.CH1FVAL) /*! @brief Format value for bitfield FTM_FILTER_CH1FVAL. */ #define BF_FTM_FILTER_CH1FVAL(v) ((uint32_t)((uint32_t)(v) << BP_FTM_FILTER_CH1FVAL) & BM_FTM_FILTER_CH1FVAL) /*! @brief Set the CH1FVAL field to a new value. */ #define BW_FTM_FILTER_CH1FVAL(x, v) (HW_FTM_FILTER_WR(x, (HW_FTM_FILTER_RD(x) & ~BM_FTM_FILTER_CH1FVAL) | BF_FTM_FILTER_CH1FVAL(v))) /*@}*/ /*! * @name Register FTM_FILTER, field CH2FVAL[11:8] (RW) * * Selects the filter value for the channel input. The filter is disabled when * the value is zero. */ /*@{*/ #define BP_FTM_FILTER_CH2FVAL (8U) /*!< Bit position for FTM_FILTER_CH2FVAL. */ #define BM_FTM_FILTER_CH2FVAL (0x00000F00U) /*!< Bit mask for FTM_FILTER_CH2FVAL. */ #define BS_FTM_FILTER_CH2FVAL (4U) /*!< Bit field size in bits for FTM_FILTER_CH2FVAL. */ /*! @brief Read current value of the FTM_FILTER_CH2FVAL field. */ #define BR_FTM_FILTER_CH2FVAL(x) (HW_FTM_FILTER(x).B.CH2FVAL) /*! @brief Format value for bitfield FTM_FILTER_CH2FVAL. */ #define BF_FTM_FILTER_CH2FVAL(v) ((uint32_t)((uint32_t)(v) << BP_FTM_FILTER_CH2FVAL) & BM_FTM_FILTER_CH2FVAL) /*! @brief Set the CH2FVAL field to a new value. */ #define BW_FTM_FILTER_CH2FVAL(x, v) (HW_FTM_FILTER_WR(x, (HW_FTM_FILTER_RD(x) & ~BM_FTM_FILTER_CH2FVAL) | BF_FTM_FILTER_CH2FVAL(v))) /*@}*/ /*! * @name Register FTM_FILTER, field CH3FVAL[15:12] (RW) * * Selects the filter value for the channel input. The filter is disabled when * the value is zero. */ /*@{*/ #define BP_FTM_FILTER_CH3FVAL (12U) /*!< Bit position for FTM_FILTER_CH3FVAL. */ #define BM_FTM_FILTER_CH3FVAL (0x0000F000U) /*!< Bit mask for FTM_FILTER_CH3FVAL. */ #define BS_FTM_FILTER_CH3FVAL (4U) /*!< Bit field size in bits for FTM_FILTER_CH3FVAL. */ /*! @brief Read current value of the FTM_FILTER_CH3FVAL field. */ #define BR_FTM_FILTER_CH3FVAL(x) (HW_FTM_FILTER(x).B.CH3FVAL) /*! @brief Format value for bitfield FTM_FILTER_CH3FVAL. */ #define BF_FTM_FILTER_CH3FVAL(v) ((uint32_t)((uint32_t)(v) << BP_FTM_FILTER_CH3FVAL) & BM_FTM_FILTER_CH3FVAL) /*! @brief Set the CH3FVAL field to a new value. */ #define BW_FTM_FILTER_CH3FVAL(x, v) (HW_FTM_FILTER_WR(x, (HW_FTM_FILTER_RD(x) & ~BM_FTM_FILTER_CH3FVAL) | BF_FTM_FILTER_CH3FVAL(v))) /*@}*/ /******************************************************************************* * HW_FTM_FLTCTRL - Fault Control ******************************************************************************/ /*! * @brief HW_FTM_FLTCTRL - Fault Control (RW) * * Reset value: 0x00000000U * * This register selects the filter value for the fault inputs, enables the * fault inputs and the fault inputs filter. */ typedef union _hw_ftm_fltctrl { uint32_t U; struct _hw_ftm_fltctrl_bitfields { uint32_t FAULT0EN : 1; /*!< [0] Fault Input 0 Enable */ uint32_t FAULT1EN : 1; /*!< [1] Fault Input 1 Enable */ uint32_t FAULT2EN : 1; /*!< [2] Fault Input 2 Enable */ uint32_t FAULT3EN : 1; /*!< [3] Fault Input 3 Enable */ uint32_t FFLTR0EN : 1; /*!< [4] Fault Input 0 Filter Enable */ uint32_t FFLTR1EN : 1; /*!< [5] Fault Input 1 Filter Enable */ uint32_t FFLTR2EN : 1; /*!< [6] Fault Input 2 Filter Enable */ uint32_t FFLTR3EN : 1; /*!< [7] Fault Input 3 Filter Enable */ uint32_t FFVAL : 4; /*!< [11:8] Fault Input Filter */ uint32_t RESERVED0 : 20; /*!< [31:12] */ } B; } hw_ftm_fltctrl_t; /*! * @name Constants and macros for entire FTM_FLTCTRL register */ /*@{*/ #define HW_FTM_FLTCTRL_ADDR(x) ((x) + 0x7CU) #define HW_FTM_FLTCTRL(x) (*(__IO hw_ftm_fltctrl_t *) HW_FTM_FLTCTRL_ADDR(x)) #define HW_FTM_FLTCTRL_RD(x) (HW_FTM_FLTCTRL(x).U) #define HW_FTM_FLTCTRL_WR(x, v) (HW_FTM_FLTCTRL(x).U = (v)) #define HW_FTM_FLTCTRL_SET(x, v) (HW_FTM_FLTCTRL_WR(x, HW_FTM_FLTCTRL_RD(x) | (v))) #define HW_FTM_FLTCTRL_CLR(x, v) (HW_FTM_FLTCTRL_WR(x, HW_FTM_FLTCTRL_RD(x) & ~(v))) #define HW_FTM_FLTCTRL_TOG(x, v) (HW_FTM_FLTCTRL_WR(x, HW_FTM_FLTCTRL_RD(x) ^ (v))) /*@}*/ /* * Constants & macros for individual FTM_FLTCTRL bitfields */ /*! * @name Register FTM_FLTCTRL, field FAULT0EN[0] (RW) * * Enables the fault input. This field is write protected. It can be written * only when MODE[WPDIS] = 1. * * Values: * - 0 - Fault input is disabled. * - 1 - Fault input is enabled. */ /*@{*/ #define BP_FTM_FLTCTRL_FAULT0EN (0U) /*!< Bit position for FTM_FLTCTRL_FAULT0EN. */ #define BM_FTM_FLTCTRL_FAULT0EN (0x00000001U) /*!< Bit mask for FTM_FLTCTRL_FAULT0EN. */ #define BS_FTM_FLTCTRL_FAULT0EN (1U) /*!< Bit field size in bits for FTM_FLTCTRL_FAULT0EN. */ /*! @brief Read current value of the FTM_FLTCTRL_FAULT0EN field. */ #define BR_FTM_FLTCTRL_FAULT0EN(x) (BITBAND_ACCESS32(HW_FTM_FLTCTRL_ADDR(x), BP_FTM_FLTCTRL_FAULT0EN)) /*! @brief Format value for bitfield FTM_FLTCTRL_FAULT0EN. */ #define BF_FTM_FLTCTRL_FAULT0EN(v) ((uint32_t)((uint32_t)(v) << BP_FTM_FLTCTRL_FAULT0EN) & BM_FTM_FLTCTRL_FAULT0EN) /*! @brief Set the FAULT0EN field to a new value. */ #define BW_FTM_FLTCTRL_FAULT0EN(x, v) (BITBAND_ACCESS32(HW_FTM_FLTCTRL_ADDR(x), BP_FTM_FLTCTRL_FAULT0EN) = (v)) /*@}*/ /*! * @name Register FTM_FLTCTRL, field FAULT1EN[1] (RW) * * Enables the fault input. This field is write protected. It can be written * only when MODE[WPDIS] = 1. * * Values: * - 0 - Fault input is disabled. * - 1 - Fault input is enabled. */ /*@{*/ #define BP_FTM_FLTCTRL_FAULT1EN (1U) /*!< Bit position for FTM_FLTCTRL_FAULT1EN. */ #define BM_FTM_FLTCTRL_FAULT1EN (0x00000002U) /*!< Bit mask for FTM_FLTCTRL_FAULT1EN. */ #define BS_FTM_FLTCTRL_FAULT1EN (1U) /*!< Bit field size in bits for FTM_FLTCTRL_FAULT1EN. */ /*! @brief Read current value of the FTM_FLTCTRL_FAULT1EN field. */ #define BR_FTM_FLTCTRL_FAULT1EN(x) (BITBAND_ACCESS32(HW_FTM_FLTCTRL_ADDR(x), BP_FTM_FLTCTRL_FAULT1EN)) /*! @brief Format value for bitfield FTM_FLTCTRL_FAULT1EN. */ #define BF_FTM_FLTCTRL_FAULT1EN(v) ((uint32_t)((uint32_t)(v) << BP_FTM_FLTCTRL_FAULT1EN) & BM_FTM_FLTCTRL_FAULT1EN) /*! @brief Set the FAULT1EN field to a new value. */ #define BW_FTM_FLTCTRL_FAULT1EN(x, v) (BITBAND_ACCESS32(HW_FTM_FLTCTRL_ADDR(x), BP_FTM_FLTCTRL_FAULT1EN) = (v)) /*@}*/ /*! * @name Register FTM_FLTCTRL, field FAULT2EN[2] (RW) * * Enables the fault input. This field is write protected. It can be written * only when MODE[WPDIS] = 1. * * Values: * - 0 - Fault input is disabled. * - 1 - Fault input is enabled. */ /*@{*/ #define BP_FTM_FLTCTRL_FAULT2EN (2U) /*!< Bit position for FTM_FLTCTRL_FAULT2EN. */ #define BM_FTM_FLTCTRL_FAULT2EN (0x00000004U) /*!< Bit mask for FTM_FLTCTRL_FAULT2EN. */ #define BS_FTM_FLTCTRL_FAULT2EN (1U) /*!< Bit field size in bits for FTM_FLTCTRL_FAULT2EN. */ /*! @brief Read current value of the FTM_FLTCTRL_FAULT2EN field. */ #define BR_FTM_FLTCTRL_FAULT2EN(x) (BITBAND_ACCESS32(HW_FTM_FLTCTRL_ADDR(x), BP_FTM_FLTCTRL_FAULT2EN)) /*! @brief Format value for bitfield FTM_FLTCTRL_FAULT2EN. */ #define BF_FTM_FLTCTRL_FAULT2EN(v) ((uint32_t)((uint32_t)(v) << BP_FTM_FLTCTRL_FAULT2EN) & BM_FTM_FLTCTRL_FAULT2EN) /*! @brief Set the FAULT2EN field to a new value. */ #define BW_FTM_FLTCTRL_FAULT2EN(x, v) (BITBAND_ACCESS32(HW_FTM_FLTCTRL_ADDR(x), BP_FTM_FLTCTRL_FAULT2EN) = (v)) /*@}*/ /*! * @name Register FTM_FLTCTRL, field FAULT3EN[3] (RW) * * Enables the fault input. This field is write protected. It can be written * only when MODE[WPDIS] = 1. * * Values: * - 0 - Fault input is disabled. * - 1 - Fault input is enabled. */ /*@{*/ #define BP_FTM_FLTCTRL_FAULT3EN (3U) /*!< Bit position for FTM_FLTCTRL_FAULT3EN. */ #define BM_FTM_FLTCTRL_FAULT3EN (0x00000008U) /*!< Bit mask for FTM_FLTCTRL_FAULT3EN. */ #define BS_FTM_FLTCTRL_FAULT3EN (1U) /*!< Bit field size in bits for FTM_FLTCTRL_FAULT3EN. */ /*! @brief Read current value of the FTM_FLTCTRL_FAULT3EN field. */ #define BR_FTM_FLTCTRL_FAULT3EN(x) (BITBAND_ACCESS32(HW_FTM_FLTCTRL_ADDR(x), BP_FTM_FLTCTRL_FAULT3EN)) /*! @brief Format value for bitfield FTM_FLTCTRL_FAULT3EN. */ #define BF_FTM_FLTCTRL_FAULT3EN(v) ((uint32_t)((uint32_t)(v) << BP_FTM_FLTCTRL_FAULT3EN) & BM_FTM_FLTCTRL_FAULT3EN) /*! @brief Set the FAULT3EN field to a new value. */ #define BW_FTM_FLTCTRL_FAULT3EN(x, v) (BITBAND_ACCESS32(HW_FTM_FLTCTRL_ADDR(x), BP_FTM_FLTCTRL_FAULT3EN) = (v)) /*@}*/ /*! * @name Register FTM_FLTCTRL, field FFLTR0EN[4] (RW) * * Enables the filter for the fault input. This field is write protected. It can * be written only when MODE[WPDIS] = 1. * * Values: * - 0 - Fault input filter is disabled. * - 1 - Fault input filter is enabled. */ /*@{*/ #define BP_FTM_FLTCTRL_FFLTR0EN (4U) /*!< Bit position for FTM_FLTCTRL_FFLTR0EN. */ #define BM_FTM_FLTCTRL_FFLTR0EN (0x00000010U) /*!< Bit mask for FTM_FLTCTRL_FFLTR0EN. */ #define BS_FTM_FLTCTRL_FFLTR0EN (1U) /*!< Bit field size in bits for FTM_FLTCTRL_FFLTR0EN. */ /*! @brief Read current value of the FTM_FLTCTRL_FFLTR0EN field. */ #define BR_FTM_FLTCTRL_FFLTR0EN(x) (BITBAND_ACCESS32(HW_FTM_FLTCTRL_ADDR(x), BP_FTM_FLTCTRL_FFLTR0EN)) /*! @brief Format value for bitfield FTM_FLTCTRL_FFLTR0EN. */ #define BF_FTM_FLTCTRL_FFLTR0EN(v) ((uint32_t)((uint32_t)(v) << BP_FTM_FLTCTRL_FFLTR0EN) & BM_FTM_FLTCTRL_FFLTR0EN) /*! @brief Set the FFLTR0EN field to a new value. */ #define BW_FTM_FLTCTRL_FFLTR0EN(x, v) (BITBAND_ACCESS32(HW_FTM_FLTCTRL_ADDR(x), BP_FTM_FLTCTRL_FFLTR0EN) = (v)) /*@}*/ /*! * @name Register FTM_FLTCTRL, field FFLTR1EN[5] (RW) * * Enables the filter for the fault input. This field is write protected. It can * be written only when MODE[WPDIS] = 1. * * Values: * - 0 - Fault input filter is disabled. * - 1 - Fault input filter is enabled. */ /*@{*/ #define BP_FTM_FLTCTRL_FFLTR1EN (5U) /*!< Bit position for FTM_FLTCTRL_FFLTR1EN. */ #define BM_FTM_FLTCTRL_FFLTR1EN (0x00000020U) /*!< Bit mask for FTM_FLTCTRL_FFLTR1EN. */ #define BS_FTM_FLTCTRL_FFLTR1EN (1U) /*!< Bit field size in bits for FTM_FLTCTRL_FFLTR1EN. */ /*! @brief Read current value of the FTM_FLTCTRL_FFLTR1EN field. */ #define BR_FTM_FLTCTRL_FFLTR1EN(x) (BITBAND_ACCESS32(HW_FTM_FLTCTRL_ADDR(x), BP_FTM_FLTCTRL_FFLTR1EN)) /*! @brief Format value for bitfield FTM_FLTCTRL_FFLTR1EN. */ #define BF_FTM_FLTCTRL_FFLTR1EN(v) ((uint32_t)((uint32_t)(v) << BP_FTM_FLTCTRL_FFLTR1EN) & BM_FTM_FLTCTRL_FFLTR1EN) /*! @brief Set the FFLTR1EN field to a new value. */ #define BW_FTM_FLTCTRL_FFLTR1EN(x, v) (BITBAND_ACCESS32(HW_FTM_FLTCTRL_ADDR(x), BP_FTM_FLTCTRL_FFLTR1EN) = (v)) /*@}*/ /*! * @name Register FTM_FLTCTRL, field FFLTR2EN[6] (RW) * * Enables the filter for the fault input. This field is write protected. It can * be written only when MODE[WPDIS] = 1. * * Values: * - 0 - Fault input filter is disabled. * - 1 - Fault input filter is enabled. */ /*@{*/ #define BP_FTM_FLTCTRL_FFLTR2EN (6U) /*!< Bit position for FTM_FLTCTRL_FFLTR2EN. */ #define BM_FTM_FLTCTRL_FFLTR2EN (0x00000040U) /*!< Bit mask for FTM_FLTCTRL_FFLTR2EN. */ #define BS_FTM_FLTCTRL_FFLTR2EN (1U) /*!< Bit field size in bits for FTM_FLTCTRL_FFLTR2EN. */ /*! @brief Read current value of the FTM_FLTCTRL_FFLTR2EN field. */ #define BR_FTM_FLTCTRL_FFLTR2EN(x) (BITBAND_ACCESS32(HW_FTM_FLTCTRL_ADDR(x), BP_FTM_FLTCTRL_FFLTR2EN)) /*! @brief Format value for bitfield FTM_FLTCTRL_FFLTR2EN. */ #define BF_FTM_FLTCTRL_FFLTR2EN(v) ((uint32_t)((uint32_t)(v) << BP_FTM_FLTCTRL_FFLTR2EN) & BM_FTM_FLTCTRL_FFLTR2EN) /*! @brief Set the FFLTR2EN field to a new value. */ #define BW_FTM_FLTCTRL_FFLTR2EN(x, v) (BITBAND_ACCESS32(HW_FTM_FLTCTRL_ADDR(x), BP_FTM_FLTCTRL_FFLTR2EN) = (v)) /*@}*/ /*! * @name Register FTM_FLTCTRL, field FFLTR3EN[7] (RW) * * Enables the filter for the fault input. This field is write protected. It can * be written only when MODE[WPDIS] = 1. * * Values: * - 0 - Fault input filter is disabled. * - 1 - Fault input filter is enabled. */ /*@{*/ #define BP_FTM_FLTCTRL_FFLTR3EN (7U) /*!< Bit position for FTM_FLTCTRL_FFLTR3EN. */ #define BM_FTM_FLTCTRL_FFLTR3EN (0x00000080U) /*!< Bit mask for FTM_FLTCTRL_FFLTR3EN. */ #define BS_FTM_FLTCTRL_FFLTR3EN (1U) /*!< Bit field size in bits for FTM_FLTCTRL_FFLTR3EN. */ /*! @brief Read current value of the FTM_FLTCTRL_FFLTR3EN field. */ #define BR_FTM_FLTCTRL_FFLTR3EN(x) (BITBAND_ACCESS32(HW_FTM_FLTCTRL_ADDR(x), BP_FTM_FLTCTRL_FFLTR3EN)) /*! @brief Format value for bitfield FTM_FLTCTRL_FFLTR3EN. */ #define BF_FTM_FLTCTRL_FFLTR3EN(v) ((uint32_t)((uint32_t)(v) << BP_FTM_FLTCTRL_FFLTR3EN) & BM_FTM_FLTCTRL_FFLTR3EN) /*! @brief Set the FFLTR3EN field to a new value. */ #define BW_FTM_FLTCTRL_FFLTR3EN(x, v) (BITBAND_ACCESS32(HW_FTM_FLTCTRL_ADDR(x), BP_FTM_FLTCTRL_FFLTR3EN) = (v)) /*@}*/ /*! * @name Register FTM_FLTCTRL, field FFVAL[11:8] (RW) * * Selects the filter value for the fault inputs. The fault filter is disabled * when the value is zero. Writing to this field has immediate effect and must be * done only when the fault control or all fault inputs are disabled. Failure to * do this could result in a missing fault detection. */ /*@{*/ #define BP_FTM_FLTCTRL_FFVAL (8U) /*!< Bit position for FTM_FLTCTRL_FFVAL. */ #define BM_FTM_FLTCTRL_FFVAL (0x00000F00U) /*!< Bit mask for FTM_FLTCTRL_FFVAL. */ #define BS_FTM_FLTCTRL_FFVAL (4U) /*!< Bit field size in bits for FTM_FLTCTRL_FFVAL. */ /*! @brief Read current value of the FTM_FLTCTRL_FFVAL field. */ #define BR_FTM_FLTCTRL_FFVAL(x) (HW_FTM_FLTCTRL(x).B.FFVAL) /*! @brief Format value for bitfield FTM_FLTCTRL_FFVAL. */ #define BF_FTM_FLTCTRL_FFVAL(v) ((uint32_t)((uint32_t)(v) << BP_FTM_FLTCTRL_FFVAL) & BM_FTM_FLTCTRL_FFVAL) /*! @brief Set the FFVAL field to a new value. */ #define BW_FTM_FLTCTRL_FFVAL(x, v) (HW_FTM_FLTCTRL_WR(x, (HW_FTM_FLTCTRL_RD(x) & ~BM_FTM_FLTCTRL_FFVAL) | BF_FTM_FLTCTRL_FFVAL(v))) /*@}*/ /******************************************************************************* * HW_FTM_QDCTRL - Quadrature Decoder Control And Status ******************************************************************************/ /*! * @brief HW_FTM_QDCTRL - Quadrature Decoder Control And Status (RW) * * Reset value: 0x00000000U * * This register has the control and status bits for the Quadrature Decoder mode. */ typedef union _hw_ftm_qdctrl { uint32_t U; struct _hw_ftm_qdctrl_bitfields { uint32_t QUADEN : 1; /*!< [0] Quadrature Decoder Mode Enable */ uint32_t TOFDIR : 1; /*!< [1] Timer Overflow Direction In Quadrature * Decoder Mode */ uint32_t QUADIR : 1; /*!< [2] FTM Counter Direction In Quadrature * Decoder Mode */ uint32_t QUADMODE : 1; /*!< [3] Quadrature Decoder Mode */ uint32_t PHBPOL : 1; /*!< [4] Phase B Input Polarity */ uint32_t PHAPOL : 1; /*!< [5] Phase A Input Polarity */ uint32_t PHBFLTREN : 1; /*!< [6] Phase B Input Filter Enable */ uint32_t PHAFLTREN : 1; /*!< [7] Phase A Input Filter Enable */ uint32_t RESERVED0 : 24; /*!< [31:8] */ } B; } hw_ftm_qdctrl_t; /*! * @name Constants and macros for entire FTM_QDCTRL register */ /*@{*/ #define HW_FTM_QDCTRL_ADDR(x) ((x) + 0x80U) #define HW_FTM_QDCTRL(x) (*(__IO hw_ftm_qdctrl_t *) HW_FTM_QDCTRL_ADDR(x)) #define HW_FTM_QDCTRL_RD(x) (HW_FTM_QDCTRL(x).U) #define HW_FTM_QDCTRL_WR(x, v) (HW_FTM_QDCTRL(x).U = (v)) #define HW_FTM_QDCTRL_SET(x, v) (HW_FTM_QDCTRL_WR(x, HW_FTM_QDCTRL_RD(x) | (v))) #define HW_FTM_QDCTRL_CLR(x, v) (HW_FTM_QDCTRL_WR(x, HW_FTM_QDCTRL_RD(x) & ~(v))) #define HW_FTM_QDCTRL_TOG(x, v) (HW_FTM_QDCTRL_WR(x, HW_FTM_QDCTRL_RD(x) ^ (v))) /*@}*/ /* * Constants & macros for individual FTM_QDCTRL bitfields */ /*! * @name Register FTM_QDCTRL, field QUADEN[0] (RW) * * Enables the Quadrature Decoder mode. In this mode, the phase A and B input * signals control the FTM counter direction. The Quadrature Decoder mode has * precedence over the other modes. See #ModeSel1Table. This field is write protected. * It can be written only when MODE[WPDIS] = 1. * * Values: * - 0 - Quadrature Decoder mode is disabled. * - 1 - Quadrature Decoder mode is enabled. */ /*@{*/ #define BP_FTM_QDCTRL_QUADEN (0U) /*!< Bit position for FTM_QDCTRL_QUADEN. */ #define BM_FTM_QDCTRL_QUADEN (0x00000001U) /*!< Bit mask for FTM_QDCTRL_QUADEN. */ #define BS_FTM_QDCTRL_QUADEN (1U) /*!< Bit field size in bits for FTM_QDCTRL_QUADEN. */ /*! @brief Read current value of the FTM_QDCTRL_QUADEN field. */ #define BR_FTM_QDCTRL_QUADEN(x) (BITBAND_ACCESS32(HW_FTM_QDCTRL_ADDR(x), BP_FTM_QDCTRL_QUADEN)) /*! @brief Format value for bitfield FTM_QDCTRL_QUADEN. */ #define BF_FTM_QDCTRL_QUADEN(v) ((uint32_t)((uint32_t)(v) << BP_FTM_QDCTRL_QUADEN) & BM_FTM_QDCTRL_QUADEN) /*! @brief Set the QUADEN field to a new value. */ #define BW_FTM_QDCTRL_QUADEN(x, v) (BITBAND_ACCESS32(HW_FTM_QDCTRL_ADDR(x), BP_FTM_QDCTRL_QUADEN) = (v)) /*@}*/ /*! * @name Register FTM_QDCTRL, field TOFDIR[1] (RO) * * Indicates if the TOF bit was set on the top or the bottom of counting. * * Values: * - 0 - TOF bit was set on the bottom of counting. There was an FTM counter * decrement and FTM counter changes from its minimum value (CNTIN register) to * its maximum value (MOD register). * - 1 - TOF bit was set on the top of counting. There was an FTM counter * increment and FTM counter changes from its maximum value (MOD register) to its * minimum value (CNTIN register). */ /*@{*/ #define BP_FTM_QDCTRL_TOFDIR (1U) /*!< Bit position for FTM_QDCTRL_TOFDIR. */ #define BM_FTM_QDCTRL_TOFDIR (0x00000002U) /*!< Bit mask for FTM_QDCTRL_TOFDIR. */ #define BS_FTM_QDCTRL_TOFDIR (1U) /*!< Bit field size in bits for FTM_QDCTRL_TOFDIR. */ /*! @brief Read current value of the FTM_QDCTRL_TOFDIR field. */ #define BR_FTM_QDCTRL_TOFDIR(x) (BITBAND_ACCESS32(HW_FTM_QDCTRL_ADDR(x), BP_FTM_QDCTRL_TOFDIR)) /*@}*/ /*! * @name Register FTM_QDCTRL, field QUADIR[2] (RO) * * Indicates the counting direction. * * Values: * - 0 - Counting direction is decreasing (FTM counter decrement). * - 1 - Counting direction is increasing (FTM counter increment). */ /*@{*/ #define BP_FTM_QDCTRL_QUADIR (2U) /*!< Bit position for FTM_QDCTRL_QUADIR. */ #define BM_FTM_QDCTRL_QUADIR (0x00000004U) /*!< Bit mask for FTM_QDCTRL_QUADIR. */ #define BS_FTM_QDCTRL_QUADIR (1U) /*!< Bit field size in bits for FTM_QDCTRL_QUADIR. */ /*! @brief Read current value of the FTM_QDCTRL_QUADIR field. */ #define BR_FTM_QDCTRL_QUADIR(x) (BITBAND_ACCESS32(HW_FTM_QDCTRL_ADDR(x), BP_FTM_QDCTRL_QUADIR)) /*@}*/ /*! * @name Register FTM_QDCTRL, field QUADMODE[3] (RW) * * Selects the encoding mode used in the Quadrature Decoder mode. * * Values: * - 0 - Phase A and phase B encoding mode. * - 1 - Count and direction encoding mode. */ /*@{*/ #define BP_FTM_QDCTRL_QUADMODE (3U) /*!< Bit position for FTM_QDCTRL_QUADMODE. */ #define BM_FTM_QDCTRL_QUADMODE (0x00000008U) /*!< Bit mask for FTM_QDCTRL_QUADMODE. */ #define BS_FTM_QDCTRL_QUADMODE (1U) /*!< Bit field size in bits for FTM_QDCTRL_QUADMODE. */ /*! @brief Read current value of the FTM_QDCTRL_QUADMODE field. */ #define BR_FTM_QDCTRL_QUADMODE(x) (BITBAND_ACCESS32(HW_FTM_QDCTRL_ADDR(x), BP_FTM_QDCTRL_QUADMODE)) /*! @brief Format value for bitfield FTM_QDCTRL_QUADMODE. */ #define BF_FTM_QDCTRL_QUADMODE(v) ((uint32_t)((uint32_t)(v) << BP_FTM_QDCTRL_QUADMODE) & BM_FTM_QDCTRL_QUADMODE) /*! @brief Set the QUADMODE field to a new value. */ #define BW_FTM_QDCTRL_QUADMODE(x, v) (BITBAND_ACCESS32(HW_FTM_QDCTRL_ADDR(x), BP_FTM_QDCTRL_QUADMODE) = (v)) /*@}*/ /*! * @name Register FTM_QDCTRL, field PHBPOL[4] (RW) * * Selects the polarity for the quadrature decoder phase B input. * * Values: * - 0 - Normal polarity. Phase B input signal is not inverted before * identifying the rising and falling edges of this signal. * - 1 - Inverted polarity. Phase B input signal is inverted before identifying * the rising and falling edges of this signal. */ /*@{*/ #define BP_FTM_QDCTRL_PHBPOL (4U) /*!< Bit position for FTM_QDCTRL_PHBPOL. */ #define BM_FTM_QDCTRL_PHBPOL (0x00000010U) /*!< Bit mask for FTM_QDCTRL_PHBPOL. */ #define BS_FTM_QDCTRL_PHBPOL (1U) /*!< Bit field size in bits for FTM_QDCTRL_PHBPOL. */ /*! @brief Read current value of the FTM_QDCTRL_PHBPOL field. */ #define BR_FTM_QDCTRL_PHBPOL(x) (BITBAND_ACCESS32(HW_FTM_QDCTRL_ADDR(x), BP_FTM_QDCTRL_PHBPOL)) /*! @brief Format value for bitfield FTM_QDCTRL_PHBPOL. */ #define BF_FTM_QDCTRL_PHBPOL(v) ((uint32_t)((uint32_t)(v) << BP_FTM_QDCTRL_PHBPOL) & BM_FTM_QDCTRL_PHBPOL) /*! @brief Set the PHBPOL field to a new value. */ #define BW_FTM_QDCTRL_PHBPOL(x, v) (BITBAND_ACCESS32(HW_FTM_QDCTRL_ADDR(x), BP_FTM_QDCTRL_PHBPOL) = (v)) /*@}*/ /*! * @name Register FTM_QDCTRL, field PHAPOL[5] (RW) * * Selects the polarity for the quadrature decoder phase A input. * * Values: * - 0 - Normal polarity. Phase A input signal is not inverted before * identifying the rising and falling edges of this signal. * - 1 - Inverted polarity. Phase A input signal is inverted before identifying * the rising and falling edges of this signal. */ /*@{*/ #define BP_FTM_QDCTRL_PHAPOL (5U) /*!< Bit position for FTM_QDCTRL_PHAPOL. */ #define BM_FTM_QDCTRL_PHAPOL (0x00000020U) /*!< Bit mask for FTM_QDCTRL_PHAPOL. */ #define BS_FTM_QDCTRL_PHAPOL (1U) /*!< Bit field size in bits for FTM_QDCTRL_PHAPOL. */ /*! @brief Read current value of the FTM_QDCTRL_PHAPOL field. */ #define BR_FTM_QDCTRL_PHAPOL(x) (BITBAND_ACCESS32(HW_FTM_QDCTRL_ADDR(x), BP_FTM_QDCTRL_PHAPOL)) /*! @brief Format value for bitfield FTM_QDCTRL_PHAPOL. */ #define BF_FTM_QDCTRL_PHAPOL(v) ((uint32_t)((uint32_t)(v) << BP_FTM_QDCTRL_PHAPOL) & BM_FTM_QDCTRL_PHAPOL) /*! @brief Set the PHAPOL field to a new value. */ #define BW_FTM_QDCTRL_PHAPOL(x, v) (BITBAND_ACCESS32(HW_FTM_QDCTRL_ADDR(x), BP_FTM_QDCTRL_PHAPOL) = (v)) /*@}*/ /*! * @name Register FTM_QDCTRL, field PHBFLTREN[6] (RW) * * Enables the filter for the quadrature decoder phase B input. The filter value * for the phase B input is defined by the CH1FVAL field of FILTER. The phase B * filter is also disabled when CH1FVAL is zero. * * Values: * - 0 - Phase B input filter is disabled. * - 1 - Phase B input filter is enabled. */ /*@{*/ #define BP_FTM_QDCTRL_PHBFLTREN (6U) /*!< Bit position for FTM_QDCTRL_PHBFLTREN. */ #define BM_FTM_QDCTRL_PHBFLTREN (0x00000040U) /*!< Bit mask for FTM_QDCTRL_PHBFLTREN. */ #define BS_FTM_QDCTRL_PHBFLTREN (1U) /*!< Bit field size in bits for FTM_QDCTRL_PHBFLTREN. */ /*! @brief Read current value of the FTM_QDCTRL_PHBFLTREN field. */ #define BR_FTM_QDCTRL_PHBFLTREN(x) (BITBAND_ACCESS32(HW_FTM_QDCTRL_ADDR(x), BP_FTM_QDCTRL_PHBFLTREN)) /*! @brief Format value for bitfield FTM_QDCTRL_PHBFLTREN. */ #define BF_FTM_QDCTRL_PHBFLTREN(v) ((uint32_t)((uint32_t)(v) << BP_FTM_QDCTRL_PHBFLTREN) & BM_FTM_QDCTRL_PHBFLTREN) /*! @brief Set the PHBFLTREN field to a new value. */ #define BW_FTM_QDCTRL_PHBFLTREN(x, v) (BITBAND_ACCESS32(HW_FTM_QDCTRL_ADDR(x), BP_FTM_QDCTRL_PHBFLTREN) = (v)) /*@}*/ /*! * @name Register FTM_QDCTRL, field PHAFLTREN[7] (RW) * * Enables the filter for the quadrature decoder phase A input. The filter value * for the phase A input is defined by the CH0FVAL field of FILTER. The phase A * filter is also disabled when CH0FVAL is zero. * * Values: * - 0 - Phase A input filter is disabled. * - 1 - Phase A input filter is enabled. */ /*@{*/ #define BP_FTM_QDCTRL_PHAFLTREN (7U) /*!< Bit position for FTM_QDCTRL_PHAFLTREN. */ #define BM_FTM_QDCTRL_PHAFLTREN (0x00000080U) /*!< Bit mask for FTM_QDCTRL_PHAFLTREN. */ #define BS_FTM_QDCTRL_PHAFLTREN (1U) /*!< Bit field size in bits for FTM_QDCTRL_PHAFLTREN. */ /*! @brief Read current value of the FTM_QDCTRL_PHAFLTREN field. */ #define BR_FTM_QDCTRL_PHAFLTREN(x) (BITBAND_ACCESS32(HW_FTM_QDCTRL_ADDR(x), BP_FTM_QDCTRL_PHAFLTREN)) /*! @brief Format value for bitfield FTM_QDCTRL_PHAFLTREN. */ #define BF_FTM_QDCTRL_PHAFLTREN(v) ((uint32_t)((uint32_t)(v) << BP_FTM_QDCTRL_PHAFLTREN) & BM_FTM_QDCTRL_PHAFLTREN) /*! @brief Set the PHAFLTREN field to a new value. */ #define BW_FTM_QDCTRL_PHAFLTREN(x, v) (BITBAND_ACCESS32(HW_FTM_QDCTRL_ADDR(x), BP_FTM_QDCTRL_PHAFLTREN) = (v)) /*@}*/ /******************************************************************************* * HW_FTM_CONF - Configuration ******************************************************************************/ /*! * @brief HW_FTM_CONF - Configuration (RW) * * Reset value: 0x00000000U * * This register selects the number of times that the FTM counter overflow * should occur before the TOF bit to be set, the FTM behavior in BDM modes, the use * of an external global time base, and the global time base signal generation. */ typedef union _hw_ftm_conf { uint32_t U; struct _hw_ftm_conf_bitfields { uint32_t NUMTOF : 5; /*!< [4:0] TOF Frequency */ uint32_t RESERVED0 : 1; /*!< [5] */ uint32_t BDMMODE : 2; /*!< [7:6] BDM Mode */ uint32_t RESERVED1 : 1; /*!< [8] */ uint32_t GTBEEN : 1; /*!< [9] Global Time Base Enable */ uint32_t GTBEOUT : 1; /*!< [10] Global Time Base Output */ uint32_t RESERVED2 : 21; /*!< [31:11] */ } B; } hw_ftm_conf_t; /*! * @name Constants and macros for entire FTM_CONF register */ /*@{*/ #define HW_FTM_CONF_ADDR(x) ((x) + 0x84U) #define HW_FTM_CONF(x) (*(__IO hw_ftm_conf_t *) HW_FTM_CONF_ADDR(x)) #define HW_FTM_CONF_RD(x) (HW_FTM_CONF(x).U) #define HW_FTM_CONF_WR(x, v) (HW_FTM_CONF(x).U = (v)) #define HW_FTM_CONF_SET(x, v) (HW_FTM_CONF_WR(x, HW_FTM_CONF_RD(x) | (v))) #define HW_FTM_CONF_CLR(x, v) (HW_FTM_CONF_WR(x, HW_FTM_CONF_RD(x) & ~(v))) #define HW_FTM_CONF_TOG(x, v) (HW_FTM_CONF_WR(x, HW_FTM_CONF_RD(x) ^ (v))) /*@}*/ /* * Constants & macros for individual FTM_CONF bitfields */ /*! * @name Register FTM_CONF, field NUMTOF[4:0] (RW) * * Selects the ratio between the number of counter overflows to the number of * times the TOF bit is set. NUMTOF = 0: The TOF bit is set for each counter * overflow. NUMTOF = 1: The TOF bit is set for the first counter overflow but not for * the next overflow. NUMTOF = 2: The TOF bit is set for the first counter * overflow but not for the next 2 overflows. NUMTOF = 3: The TOF bit is set for the * first counter overflow but not for the next 3 overflows. This pattern continues * up to a maximum of 31. */ /*@{*/ #define BP_FTM_CONF_NUMTOF (0U) /*!< Bit position for FTM_CONF_NUMTOF. */ #define BM_FTM_CONF_NUMTOF (0x0000001FU) /*!< Bit mask for FTM_CONF_NUMTOF. */ #define BS_FTM_CONF_NUMTOF (5U) /*!< Bit field size in bits for FTM_CONF_NUMTOF. */ /*! @brief Read current value of the FTM_CONF_NUMTOF field. */ #define BR_FTM_CONF_NUMTOF(x) (HW_FTM_CONF(x).B.NUMTOF) /*! @brief Format value for bitfield FTM_CONF_NUMTOF. */ #define BF_FTM_CONF_NUMTOF(v) ((uint32_t)((uint32_t)(v) << BP_FTM_CONF_NUMTOF) & BM_FTM_CONF_NUMTOF) /*! @brief Set the NUMTOF field to a new value. */ #define BW_FTM_CONF_NUMTOF(x, v) (HW_FTM_CONF_WR(x, (HW_FTM_CONF_RD(x) & ~BM_FTM_CONF_NUMTOF) | BF_FTM_CONF_NUMTOF(v))) /*@}*/ /*! * @name Register FTM_CONF, field BDMMODE[7:6] (RW) * * Selects the FTM behavior in BDM mode. See BDM mode. */ /*@{*/ #define BP_FTM_CONF_BDMMODE (6U) /*!< Bit position for FTM_CONF_BDMMODE. */ #define BM_FTM_CONF_BDMMODE (0x000000C0U) /*!< Bit mask for FTM_CONF_BDMMODE. */ #define BS_FTM_CONF_BDMMODE (2U) /*!< Bit field size in bits for FTM_CONF_BDMMODE. */ /*! @brief Read current value of the FTM_CONF_BDMMODE field. */ #define BR_FTM_CONF_BDMMODE(x) (HW_FTM_CONF(x).B.BDMMODE) /*! @brief Format value for bitfield FTM_CONF_BDMMODE. */ #define BF_FTM_CONF_BDMMODE(v) ((uint32_t)((uint32_t)(v) << BP_FTM_CONF_BDMMODE) & BM_FTM_CONF_BDMMODE) /*! @brief Set the BDMMODE field to a new value. */ #define BW_FTM_CONF_BDMMODE(x, v) (HW_FTM_CONF_WR(x, (HW_FTM_CONF_RD(x) & ~BM_FTM_CONF_BDMMODE) | BF_FTM_CONF_BDMMODE(v))) /*@}*/ /*! * @name Register FTM_CONF, field GTBEEN[9] (RW) * * Configures the FTM to use an external global time base signal that is * generated by another FTM. * * Values: * - 0 - Use of an external global time base is disabled. * - 1 - Use of an external global time base is enabled. */ /*@{*/ #define BP_FTM_CONF_GTBEEN (9U) /*!< Bit position for FTM_CONF_GTBEEN. */ #define BM_FTM_CONF_GTBEEN (0x00000200U) /*!< Bit mask for FTM_CONF_GTBEEN. */ #define BS_FTM_CONF_GTBEEN (1U) /*!< Bit field size in bits for FTM_CONF_GTBEEN. */ /*! @brief Read current value of the FTM_CONF_GTBEEN field. */ #define BR_FTM_CONF_GTBEEN(x) (BITBAND_ACCESS32(HW_FTM_CONF_ADDR(x), BP_FTM_CONF_GTBEEN)) /*! @brief Format value for bitfield FTM_CONF_GTBEEN. */ #define BF_FTM_CONF_GTBEEN(v) ((uint32_t)((uint32_t)(v) << BP_FTM_CONF_GTBEEN) & BM_FTM_CONF_GTBEEN) /*! @brief Set the GTBEEN field to a new value. */ #define BW_FTM_CONF_GTBEEN(x, v) (BITBAND_ACCESS32(HW_FTM_CONF_ADDR(x), BP_FTM_CONF_GTBEEN) = (v)) /*@}*/ /*! * @name Register FTM_CONF, field GTBEOUT[10] (RW) * * Enables the global time base signal generation to other FTMs. * * Values: * - 0 - A global time base signal generation is disabled. * - 1 - A global time base signal generation is enabled. */ /*@{*/ #define BP_FTM_CONF_GTBEOUT (10U) /*!< Bit position for FTM_CONF_GTBEOUT. */ #define BM_FTM_CONF_GTBEOUT (0x00000400U) /*!< Bit mask for FTM_CONF_GTBEOUT. */ #define BS_FTM_CONF_GTBEOUT (1U) /*!< Bit field size in bits for FTM_CONF_GTBEOUT. */ /*! @brief Read current value of the FTM_CONF_GTBEOUT field. */ #define BR_FTM_CONF_GTBEOUT(x) (BITBAND_ACCESS32(HW_FTM_CONF_ADDR(x), BP_FTM_CONF_GTBEOUT)) /*! @brief Format value for bitfield FTM_CONF_GTBEOUT. */ #define BF_FTM_CONF_GTBEOUT(v) ((uint32_t)((uint32_t)(v) << BP_FTM_CONF_GTBEOUT) & BM_FTM_CONF_GTBEOUT) /*! @brief Set the GTBEOUT field to a new value. */ #define BW_FTM_CONF_GTBEOUT(x, v) (BITBAND_ACCESS32(HW_FTM_CONF_ADDR(x), BP_FTM_CONF_GTBEOUT) = (v)) /*@}*/ /******************************************************************************* * HW_FTM_FLTPOL - FTM Fault Input Polarity ******************************************************************************/ /*! * @brief HW_FTM_FLTPOL - FTM Fault Input Polarity (RW) * * Reset value: 0x00000000U * * This register defines the fault inputs polarity. */ typedef union _hw_ftm_fltpol { uint32_t U; struct _hw_ftm_fltpol_bitfields { uint32_t FLT0POL : 1; /*!< [0] Fault Input 0 Polarity */ uint32_t FLT1POL : 1; /*!< [1] Fault Input 1 Polarity */ uint32_t FLT2POL : 1; /*!< [2] Fault Input 2 Polarity */ uint32_t FLT3POL : 1; /*!< [3] Fault Input 3 Polarity */ uint32_t RESERVED0 : 28; /*!< [31:4] */ } B; } hw_ftm_fltpol_t; /*! * @name Constants and macros for entire FTM_FLTPOL register */ /*@{*/ #define HW_FTM_FLTPOL_ADDR(x) ((x) + 0x88U) #define HW_FTM_FLTPOL(x) (*(__IO hw_ftm_fltpol_t *) HW_FTM_FLTPOL_ADDR(x)) #define HW_FTM_FLTPOL_RD(x) (HW_FTM_FLTPOL(x).U) #define HW_FTM_FLTPOL_WR(x, v) (HW_FTM_FLTPOL(x).U = (v)) #define HW_FTM_FLTPOL_SET(x, v) (HW_FTM_FLTPOL_WR(x, HW_FTM_FLTPOL_RD(x) | (v))) #define HW_FTM_FLTPOL_CLR(x, v) (HW_FTM_FLTPOL_WR(x, HW_FTM_FLTPOL_RD(x) & ~(v))) #define HW_FTM_FLTPOL_TOG(x, v) (HW_FTM_FLTPOL_WR(x, HW_FTM_FLTPOL_RD(x) ^ (v))) /*@}*/ /* * Constants & macros for individual FTM_FLTPOL bitfields */ /*! * @name Register FTM_FLTPOL, field FLT0POL[0] (RW) * * Defines the polarity of the fault input. This field is write protected. It * can be written only when MODE[WPDIS] = 1. * * Values: * - 0 - The fault input polarity is active high. A 1 at the fault input * indicates a fault. * - 1 - The fault input polarity is active low. A 0 at the fault input * indicates a fault. */ /*@{*/ #define BP_FTM_FLTPOL_FLT0POL (0U) /*!< Bit position for FTM_FLTPOL_FLT0POL. */ #define BM_FTM_FLTPOL_FLT0POL (0x00000001U) /*!< Bit mask for FTM_FLTPOL_FLT0POL. */ #define BS_FTM_FLTPOL_FLT0POL (1U) /*!< Bit field size in bits for FTM_FLTPOL_FLT0POL. */ /*! @brief Read current value of the FTM_FLTPOL_FLT0POL field. */ #define BR_FTM_FLTPOL_FLT0POL(x) (BITBAND_ACCESS32(HW_FTM_FLTPOL_ADDR(x), BP_FTM_FLTPOL_FLT0POL)) /*! @brief Format value for bitfield FTM_FLTPOL_FLT0POL. */ #define BF_FTM_FLTPOL_FLT0POL(v) ((uint32_t)((uint32_t)(v) << BP_FTM_FLTPOL_FLT0POL) & BM_FTM_FLTPOL_FLT0POL) /*! @brief Set the FLT0POL field to a new value. */ #define BW_FTM_FLTPOL_FLT0POL(x, v) (BITBAND_ACCESS32(HW_FTM_FLTPOL_ADDR(x), BP_FTM_FLTPOL_FLT0POL) = (v)) /*@}*/ /*! * @name Register FTM_FLTPOL, field FLT1POL[1] (RW) * * Defines the polarity of the fault input. This field is write protected. It * can be written only when MODE[WPDIS] = 1. * * Values: * - 0 - The fault input polarity is active high. A 1 at the fault input * indicates a fault. * - 1 - The fault input polarity is active low. A 0 at the fault input * indicates a fault. */ /*@{*/ #define BP_FTM_FLTPOL_FLT1POL (1U) /*!< Bit position for FTM_FLTPOL_FLT1POL. */ #define BM_FTM_FLTPOL_FLT1POL (0x00000002U) /*!< Bit mask for FTM_FLTPOL_FLT1POL. */ #define BS_FTM_FLTPOL_FLT1POL (1U) /*!< Bit field size in bits for FTM_FLTPOL_FLT1POL. */ /*! @brief Read current value of the FTM_FLTPOL_FLT1POL field. */ #define BR_FTM_FLTPOL_FLT1POL(x) (BITBAND_ACCESS32(HW_FTM_FLTPOL_ADDR(x), BP_FTM_FLTPOL_FLT1POL)) /*! @brief Format value for bitfield FTM_FLTPOL_FLT1POL. */ #define BF_FTM_FLTPOL_FLT1POL(v) ((uint32_t)((uint32_t)(v) << BP_FTM_FLTPOL_FLT1POL) & BM_FTM_FLTPOL_FLT1POL) /*! @brief Set the FLT1POL field to a new value. */ #define BW_FTM_FLTPOL_FLT1POL(x, v) (BITBAND_ACCESS32(HW_FTM_FLTPOL_ADDR(x), BP_FTM_FLTPOL_FLT1POL) = (v)) /*@}*/ /*! * @name Register FTM_FLTPOL, field FLT2POL[2] (RW) * * Defines the polarity of the fault input. This field is write protected. It * can be written only when MODE[WPDIS] = 1. * * Values: * - 0 - The fault input polarity is active high. A 1 at the fault input * indicates a fault. * - 1 - The fault input polarity is active low. A 0 at the fault input * indicates a fault. */ /*@{*/ #define BP_FTM_FLTPOL_FLT2POL (2U) /*!< Bit position for FTM_FLTPOL_FLT2POL. */ #define BM_FTM_FLTPOL_FLT2POL (0x00000004U) /*!< Bit mask for FTM_FLTPOL_FLT2POL. */ #define BS_FTM_FLTPOL_FLT2POL (1U) /*!< Bit field size in bits for FTM_FLTPOL_FLT2POL. */ /*! @brief Read current value of the FTM_FLTPOL_FLT2POL field. */ #define BR_FTM_FLTPOL_FLT2POL(x) (BITBAND_ACCESS32(HW_FTM_FLTPOL_ADDR(x), BP_FTM_FLTPOL_FLT2POL)) /*! @brief Format value for bitfield FTM_FLTPOL_FLT2POL. */ #define BF_FTM_FLTPOL_FLT2POL(v) ((uint32_t)((uint32_t)(v) << BP_FTM_FLTPOL_FLT2POL) & BM_FTM_FLTPOL_FLT2POL) /*! @brief Set the FLT2POL field to a new value. */ #define BW_FTM_FLTPOL_FLT2POL(x, v) (BITBAND_ACCESS32(HW_FTM_FLTPOL_ADDR(x), BP_FTM_FLTPOL_FLT2POL) = (v)) /*@}*/ /*! * @name Register FTM_FLTPOL, field FLT3POL[3] (RW) * * Defines the polarity of the fault input. This field is write protected. It * can be written only when MODE[WPDIS] = 1. * * Values: * - 0 - The fault input polarity is active high. A 1 at the fault input * indicates a fault. * - 1 - The fault input polarity is active low. A 0 at the fault input * indicates a fault. */ /*@{*/ #define BP_FTM_FLTPOL_FLT3POL (3U) /*!< Bit position for FTM_FLTPOL_FLT3POL. */ #define BM_FTM_FLTPOL_FLT3POL (0x00000008U) /*!< Bit mask for FTM_FLTPOL_FLT3POL. */ #define BS_FTM_FLTPOL_FLT3POL (1U) /*!< Bit field size in bits for FTM_FLTPOL_FLT3POL. */ /*! @brief Read current value of the FTM_FLTPOL_FLT3POL field. */ #define BR_FTM_FLTPOL_FLT3POL(x) (BITBAND_ACCESS32(HW_FTM_FLTPOL_ADDR(x), BP_FTM_FLTPOL_FLT3POL)) /*! @brief Format value for bitfield FTM_FLTPOL_FLT3POL. */ #define BF_FTM_FLTPOL_FLT3POL(v) ((uint32_t)((uint32_t)(v) << BP_FTM_FLTPOL_FLT3POL) & BM_FTM_FLTPOL_FLT3POL) /*! @brief Set the FLT3POL field to a new value. */ #define BW_FTM_FLTPOL_FLT3POL(x, v) (BITBAND_ACCESS32(HW_FTM_FLTPOL_ADDR(x), BP_FTM_FLTPOL_FLT3POL) = (v)) /*@}*/ /******************************************************************************* * HW_FTM_SYNCONF - Synchronization Configuration ******************************************************************************/ /*! * @brief HW_FTM_SYNCONF - Synchronization Configuration (RW) * * Reset value: 0x00000000U * * This register selects the PWM synchronization configuration, SWOCTRL, INVCTRL * and CNTIN registers synchronization, if FTM clears the TRIGj bit, where j = * 0, 1, 2, when the hardware trigger j is detected. */ typedef union _hw_ftm_synconf { uint32_t U; struct _hw_ftm_synconf_bitfields { uint32_t HWTRIGMODE : 1; /*!< [0] Hardware Trigger Mode */ uint32_t RESERVED0 : 1; /*!< [1] */ uint32_t CNTINC : 1; /*!< [2] CNTIN Register Synchronization */ uint32_t RESERVED1 : 1; /*!< [3] */ uint32_t INVC : 1; /*!< [4] INVCTRL Register Synchronization */ uint32_t SWOC : 1; /*!< [5] SWOCTRL Register Synchronization */ uint32_t RESERVED2 : 1; /*!< [6] */ uint32_t SYNCMODE : 1; /*!< [7] Synchronization Mode */ uint32_t SWRSTCNT : 1; /*!< [8] */ uint32_t SWWRBUF : 1; /*!< [9] */ uint32_t SWOM : 1; /*!< [10] */ uint32_t SWINVC : 1; /*!< [11] */ uint32_t SWSOC : 1; /*!< [12] */ uint32_t RESERVED3 : 3; /*!< [15:13] */ uint32_t HWRSTCNT : 1; /*!< [16] */ uint32_t HWWRBUF : 1; /*!< [17] */ uint32_t HWOM : 1; /*!< [18] */ uint32_t HWINVC : 1; /*!< [19] */ uint32_t HWSOC : 1; /*!< [20] */ uint32_t RESERVED4 : 11; /*!< [31:21] */ } B; } hw_ftm_synconf_t; /*! * @name Constants and macros for entire FTM_SYNCONF register */ /*@{*/ #define HW_FTM_SYNCONF_ADDR(x) ((x) + 0x8CU) #define HW_FTM_SYNCONF(x) (*(__IO hw_ftm_synconf_t *) HW_FTM_SYNCONF_ADDR(x)) #define HW_FTM_SYNCONF_RD(x) (HW_FTM_SYNCONF(x).U) #define HW_FTM_SYNCONF_WR(x, v) (HW_FTM_SYNCONF(x).U = (v)) #define HW_FTM_SYNCONF_SET(x, v) (HW_FTM_SYNCONF_WR(x, HW_FTM_SYNCONF_RD(x) | (v))) #define HW_FTM_SYNCONF_CLR(x, v) (HW_FTM_SYNCONF_WR(x, HW_FTM_SYNCONF_RD(x) & ~(v))) #define HW_FTM_SYNCONF_TOG(x, v) (HW_FTM_SYNCONF_WR(x, HW_FTM_SYNCONF_RD(x) ^ (v))) /*@}*/ /* * Constants & macros for individual FTM_SYNCONF bitfields */ /*! * @name Register FTM_SYNCONF, field HWTRIGMODE[0] (RW) * * Values: * - 0 - FTM clears the TRIGj bit when the hardware trigger j is detected, where * j = 0, 1,2. * - 1 - FTM does not clear the TRIGj bit when the hardware trigger j is * detected, where j = 0, 1,2. */ /*@{*/ #define BP_FTM_SYNCONF_HWTRIGMODE (0U) /*!< Bit position for FTM_SYNCONF_HWTRIGMODE. */ #define BM_FTM_SYNCONF_HWTRIGMODE (0x00000001U) /*!< Bit mask for FTM_SYNCONF_HWTRIGMODE. */ #define BS_FTM_SYNCONF_HWTRIGMODE (1U) /*!< Bit field size in bits for FTM_SYNCONF_HWTRIGMODE. */ /*! @brief Read current value of the FTM_SYNCONF_HWTRIGMODE field. */ #define BR_FTM_SYNCONF_HWTRIGMODE(x) (BITBAND_ACCESS32(HW_FTM_SYNCONF_ADDR(x), BP_FTM_SYNCONF_HWTRIGMODE)) /*! @brief Format value for bitfield FTM_SYNCONF_HWTRIGMODE. */ #define BF_FTM_SYNCONF_HWTRIGMODE(v) ((uint32_t)((uint32_t)(v) << BP_FTM_SYNCONF_HWTRIGMODE) & BM_FTM_SYNCONF_HWTRIGMODE) /*! @brief Set the HWTRIGMODE field to a new value. */ #define BW_FTM_SYNCONF_HWTRIGMODE(x, v) (BITBAND_ACCESS32(HW_FTM_SYNCONF_ADDR(x), BP_FTM_SYNCONF_HWTRIGMODE) = (v)) /*@}*/ /*! * @name Register FTM_SYNCONF, field CNTINC[2] (RW) * * Values: * - 0 - CNTIN register is updated with its buffer value at all rising edges of * system clock. * - 1 - CNTIN register is updated with its buffer value by the PWM * synchronization. */ /*@{*/ #define BP_FTM_SYNCONF_CNTINC (2U) /*!< Bit position for FTM_SYNCONF_CNTINC. */ #define BM_FTM_SYNCONF_CNTINC (0x00000004U) /*!< Bit mask for FTM_SYNCONF_CNTINC. */ #define BS_FTM_SYNCONF_CNTINC (1U) /*!< Bit field size in bits for FTM_SYNCONF_CNTINC. */ /*! @brief Read current value of the FTM_SYNCONF_CNTINC field. */ #define BR_FTM_SYNCONF_CNTINC(x) (BITBAND_ACCESS32(HW_FTM_SYNCONF_ADDR(x), BP_FTM_SYNCONF_CNTINC)) /*! @brief Format value for bitfield FTM_SYNCONF_CNTINC. */ #define BF_FTM_SYNCONF_CNTINC(v) ((uint32_t)((uint32_t)(v) << BP_FTM_SYNCONF_CNTINC) & BM_FTM_SYNCONF_CNTINC) /*! @brief Set the CNTINC field to a new value. */ #define BW_FTM_SYNCONF_CNTINC(x, v) (BITBAND_ACCESS32(HW_FTM_SYNCONF_ADDR(x), BP_FTM_SYNCONF_CNTINC) = (v)) /*@}*/ /*! * @name Register FTM_SYNCONF, field INVC[4] (RW) * * Values: * - 0 - INVCTRL register is updated with its buffer value at all rising edges * of system clock. * - 1 - INVCTRL register is updated with its buffer value by the PWM * synchronization. */ /*@{*/ #define BP_FTM_SYNCONF_INVC (4U) /*!< Bit position for FTM_SYNCONF_INVC. */ #define BM_FTM_SYNCONF_INVC (0x00000010U) /*!< Bit mask for FTM_SYNCONF_INVC. */ #define BS_FTM_SYNCONF_INVC (1U) /*!< Bit field size in bits for FTM_SYNCONF_INVC. */ /*! @brief Read current value of the FTM_SYNCONF_INVC field. */ #define BR_FTM_SYNCONF_INVC(x) (BITBAND_ACCESS32(HW_FTM_SYNCONF_ADDR(x), BP_FTM_SYNCONF_INVC)) /*! @brief Format value for bitfield FTM_SYNCONF_INVC. */ #define BF_FTM_SYNCONF_INVC(v) ((uint32_t)((uint32_t)(v) << BP_FTM_SYNCONF_INVC) & BM_FTM_SYNCONF_INVC) /*! @brief Set the INVC field to a new value. */ #define BW_FTM_SYNCONF_INVC(x, v) (BITBAND_ACCESS32(HW_FTM_SYNCONF_ADDR(x), BP_FTM_SYNCONF_INVC) = (v)) /*@}*/ /*! * @name Register FTM_SYNCONF, field SWOC[5] (RW) * * Values: * - 0 - SWOCTRL register is updated with its buffer value at all rising edges * of system clock. * - 1 - SWOCTRL register is updated with its buffer value by the PWM * synchronization. */ /*@{*/ #define BP_FTM_SYNCONF_SWOC (5U) /*!< Bit position for FTM_SYNCONF_SWOC. */ #define BM_FTM_SYNCONF_SWOC (0x00000020U) /*!< Bit mask for FTM_SYNCONF_SWOC. */ #define BS_FTM_SYNCONF_SWOC (1U) /*!< Bit field size in bits for FTM_SYNCONF_SWOC. */ /*! @brief Read current value of the FTM_SYNCONF_SWOC field. */ #define BR_FTM_SYNCONF_SWOC(x) (BITBAND_ACCESS32(HW_FTM_SYNCONF_ADDR(x), BP_FTM_SYNCONF_SWOC)) /*! @brief Format value for bitfield FTM_SYNCONF_SWOC. */ #define BF_FTM_SYNCONF_SWOC(v) ((uint32_t)((uint32_t)(v) << BP_FTM_SYNCONF_SWOC) & BM_FTM_SYNCONF_SWOC) /*! @brief Set the SWOC field to a new value. */ #define BW_FTM_SYNCONF_SWOC(x, v) (BITBAND_ACCESS32(HW_FTM_SYNCONF_ADDR(x), BP_FTM_SYNCONF_SWOC) = (v)) /*@}*/ /*! * @name Register FTM_SYNCONF, field SYNCMODE[7] (RW) * * Selects the PWM Synchronization mode. * * Values: * - 0 - Legacy PWM synchronization is selected. * - 1 - Enhanced PWM synchronization is selected. */ /*@{*/ #define BP_FTM_SYNCONF_SYNCMODE (7U) /*!< Bit position for FTM_SYNCONF_SYNCMODE. */ #define BM_FTM_SYNCONF_SYNCMODE (0x00000080U) /*!< Bit mask for FTM_SYNCONF_SYNCMODE. */ #define BS_FTM_SYNCONF_SYNCMODE (1U) /*!< Bit field size in bits for FTM_SYNCONF_SYNCMODE. */ /*! @brief Read current value of the FTM_SYNCONF_SYNCMODE field. */ #define BR_FTM_SYNCONF_SYNCMODE(x) (BITBAND_ACCESS32(HW_FTM_SYNCONF_ADDR(x), BP_FTM_SYNCONF_SYNCMODE)) /*! @brief Format value for bitfield FTM_SYNCONF_SYNCMODE. */ #define BF_FTM_SYNCONF_SYNCMODE(v) ((uint32_t)((uint32_t)(v) << BP_FTM_SYNCONF_SYNCMODE) & BM_FTM_SYNCONF_SYNCMODE) /*! @brief Set the SYNCMODE field to a new value. */ #define BW_FTM_SYNCONF_SYNCMODE(x, v) (BITBAND_ACCESS32(HW_FTM_SYNCONF_ADDR(x), BP_FTM_SYNCONF_SYNCMODE) = (v)) /*@}*/ /*! * @name Register FTM_SYNCONF, field SWRSTCNT[8] (RW) * * FTM counter synchronization is activated by the software trigger. * * Values: * - 0 - The software trigger does not activate the FTM counter synchronization. * - 1 - The software trigger activates the FTM counter synchronization. */ /*@{*/ #define BP_FTM_SYNCONF_SWRSTCNT (8U) /*!< Bit position for FTM_SYNCONF_SWRSTCNT. */ #define BM_FTM_SYNCONF_SWRSTCNT (0x00000100U) /*!< Bit mask for FTM_SYNCONF_SWRSTCNT. */ #define BS_FTM_SYNCONF_SWRSTCNT (1U) /*!< Bit field size in bits for FTM_SYNCONF_SWRSTCNT. */ /*! @brief Read current value of the FTM_SYNCONF_SWRSTCNT field. */ #define BR_FTM_SYNCONF_SWRSTCNT(x) (BITBAND_ACCESS32(HW_FTM_SYNCONF_ADDR(x), BP_FTM_SYNCONF_SWRSTCNT)) /*! @brief Format value for bitfield FTM_SYNCONF_SWRSTCNT. */ #define BF_FTM_SYNCONF_SWRSTCNT(v) ((uint32_t)((uint32_t)(v) << BP_FTM_SYNCONF_SWRSTCNT) & BM_FTM_SYNCONF_SWRSTCNT) /*! @brief Set the SWRSTCNT field to a new value. */ #define BW_FTM_SYNCONF_SWRSTCNT(x, v) (BITBAND_ACCESS32(HW_FTM_SYNCONF_ADDR(x), BP_FTM_SYNCONF_SWRSTCNT) = (v)) /*@}*/ /*! * @name Register FTM_SYNCONF, field SWWRBUF[9] (RW) * * MOD, CNTIN, and CV registers synchronization is activated by the software * trigger. * * Values: * - 0 - The software trigger does not activate MOD, CNTIN, and CV registers * synchronization. * - 1 - The software trigger activates MOD, CNTIN, and CV registers * synchronization. */ /*@{*/ #define BP_FTM_SYNCONF_SWWRBUF (9U) /*!< Bit position for FTM_SYNCONF_SWWRBUF. */ #define BM_FTM_SYNCONF_SWWRBUF (0x00000200U) /*!< Bit mask for FTM_SYNCONF_SWWRBUF. */ #define BS_FTM_SYNCONF_SWWRBUF (1U) /*!< Bit field size in bits for FTM_SYNCONF_SWWRBUF. */ /*! @brief Read current value of the FTM_SYNCONF_SWWRBUF field. */ #define BR_FTM_SYNCONF_SWWRBUF(x) (BITBAND_ACCESS32(HW_FTM_SYNCONF_ADDR(x), BP_FTM_SYNCONF_SWWRBUF)) /*! @brief Format value for bitfield FTM_SYNCONF_SWWRBUF. */ #define BF_FTM_SYNCONF_SWWRBUF(v) ((uint32_t)((uint32_t)(v) << BP_FTM_SYNCONF_SWWRBUF) & BM_FTM_SYNCONF_SWWRBUF) /*! @brief Set the SWWRBUF field to a new value. */ #define BW_FTM_SYNCONF_SWWRBUF(x, v) (BITBAND_ACCESS32(HW_FTM_SYNCONF_ADDR(x), BP_FTM_SYNCONF_SWWRBUF) = (v)) /*@}*/ /*! * @name Register FTM_SYNCONF, field SWOM[10] (RW) * * Output mask synchronization is activated by the software trigger. * * Values: * - 0 - The software trigger does not activate the OUTMASK register * synchronization. * - 1 - The software trigger activates the OUTMASK register synchronization. */ /*@{*/ #define BP_FTM_SYNCONF_SWOM (10U) /*!< Bit position for FTM_SYNCONF_SWOM. */ #define BM_FTM_SYNCONF_SWOM (0x00000400U) /*!< Bit mask for FTM_SYNCONF_SWOM. */ #define BS_FTM_SYNCONF_SWOM (1U) /*!< Bit field size in bits for FTM_SYNCONF_SWOM. */ /*! @brief Read current value of the FTM_SYNCONF_SWOM field. */ #define BR_FTM_SYNCONF_SWOM(x) (BITBAND_ACCESS32(HW_FTM_SYNCONF_ADDR(x), BP_FTM_SYNCONF_SWOM)) /*! @brief Format value for bitfield FTM_SYNCONF_SWOM. */ #define BF_FTM_SYNCONF_SWOM(v) ((uint32_t)((uint32_t)(v) << BP_FTM_SYNCONF_SWOM) & BM_FTM_SYNCONF_SWOM) /*! @brief Set the SWOM field to a new value. */ #define BW_FTM_SYNCONF_SWOM(x, v) (BITBAND_ACCESS32(HW_FTM_SYNCONF_ADDR(x), BP_FTM_SYNCONF_SWOM) = (v)) /*@}*/ /*! * @name Register FTM_SYNCONF, field SWINVC[11] (RW) * * Inverting control synchronization is activated by the software trigger. * * Values: * - 0 - The software trigger does not activate the INVCTRL register * synchronization. * - 1 - The software trigger activates the INVCTRL register synchronization. */ /*@{*/ #define BP_FTM_SYNCONF_SWINVC (11U) /*!< Bit position for FTM_SYNCONF_SWINVC. */ #define BM_FTM_SYNCONF_SWINVC (0x00000800U) /*!< Bit mask for FTM_SYNCONF_SWINVC. */ #define BS_FTM_SYNCONF_SWINVC (1U) /*!< Bit field size in bits for FTM_SYNCONF_SWINVC. */ /*! @brief Read current value of the FTM_SYNCONF_SWINVC field. */ #define BR_FTM_SYNCONF_SWINVC(x) (BITBAND_ACCESS32(HW_FTM_SYNCONF_ADDR(x), BP_FTM_SYNCONF_SWINVC)) /*! @brief Format value for bitfield FTM_SYNCONF_SWINVC. */ #define BF_FTM_SYNCONF_SWINVC(v) ((uint32_t)((uint32_t)(v) << BP_FTM_SYNCONF_SWINVC) & BM_FTM_SYNCONF_SWINVC) /*! @brief Set the SWINVC field to a new value. */ #define BW_FTM_SYNCONF_SWINVC(x, v) (BITBAND_ACCESS32(HW_FTM_SYNCONF_ADDR(x), BP_FTM_SYNCONF_SWINVC) = (v)) /*@}*/ /*! * @name Register FTM_SYNCONF, field SWSOC[12] (RW) * * Software output control synchronization is activated by the software trigger. * * Values: * - 0 - The software trigger does not activate the SWOCTRL register * synchronization. * - 1 - The software trigger activates the SWOCTRL register synchronization. */ /*@{*/ #define BP_FTM_SYNCONF_SWSOC (12U) /*!< Bit position for FTM_SYNCONF_SWSOC. */ #define BM_FTM_SYNCONF_SWSOC (0x00001000U) /*!< Bit mask for FTM_SYNCONF_SWSOC. */ #define BS_FTM_SYNCONF_SWSOC (1U) /*!< Bit field size in bits for FTM_SYNCONF_SWSOC. */ /*! @brief Read current value of the FTM_SYNCONF_SWSOC field. */ #define BR_FTM_SYNCONF_SWSOC(x) (BITBAND_ACCESS32(HW_FTM_SYNCONF_ADDR(x), BP_FTM_SYNCONF_SWSOC)) /*! @brief Format value for bitfield FTM_SYNCONF_SWSOC. */ #define BF_FTM_SYNCONF_SWSOC(v) ((uint32_t)((uint32_t)(v) << BP_FTM_SYNCONF_SWSOC) & BM_FTM_SYNCONF_SWSOC) /*! @brief Set the SWSOC field to a new value. */ #define BW_FTM_SYNCONF_SWSOC(x, v) (BITBAND_ACCESS32(HW_FTM_SYNCONF_ADDR(x), BP_FTM_SYNCONF_SWSOC) = (v)) /*@}*/ /*! * @name Register FTM_SYNCONF, field HWRSTCNT[16] (RW) * * FTM counter synchronization is activated by a hardware trigger. * * Values: * - 0 - A hardware trigger does not activate the FTM counter synchronization. * - 1 - A hardware trigger activates the FTM counter synchronization. */ /*@{*/ #define BP_FTM_SYNCONF_HWRSTCNT (16U) /*!< Bit position for FTM_SYNCONF_HWRSTCNT. */ #define BM_FTM_SYNCONF_HWRSTCNT (0x00010000U) /*!< Bit mask for FTM_SYNCONF_HWRSTCNT. */ #define BS_FTM_SYNCONF_HWRSTCNT (1U) /*!< Bit field size in bits for FTM_SYNCONF_HWRSTCNT. */ /*! @brief Read current value of the FTM_SYNCONF_HWRSTCNT field. */ #define BR_FTM_SYNCONF_HWRSTCNT(x) (BITBAND_ACCESS32(HW_FTM_SYNCONF_ADDR(x), BP_FTM_SYNCONF_HWRSTCNT)) /*! @brief Format value for bitfield FTM_SYNCONF_HWRSTCNT. */ #define BF_FTM_SYNCONF_HWRSTCNT(v) ((uint32_t)((uint32_t)(v) << BP_FTM_SYNCONF_HWRSTCNT) & BM_FTM_SYNCONF_HWRSTCNT) /*! @brief Set the HWRSTCNT field to a new value. */ #define BW_FTM_SYNCONF_HWRSTCNT(x, v) (BITBAND_ACCESS32(HW_FTM_SYNCONF_ADDR(x), BP_FTM_SYNCONF_HWRSTCNT) = (v)) /*@}*/ /*! * @name Register FTM_SYNCONF, field HWWRBUF[17] (RW) * * MOD, CNTIN, and CV registers synchronization is activated by a hardware * trigger. * * Values: * - 0 - A hardware trigger does not activate MOD, CNTIN, and CV registers * synchronization. * - 1 - A hardware trigger activates MOD, CNTIN, and CV registers * synchronization. */ /*@{*/ #define BP_FTM_SYNCONF_HWWRBUF (17U) /*!< Bit position for FTM_SYNCONF_HWWRBUF. */ #define BM_FTM_SYNCONF_HWWRBUF (0x00020000U) /*!< Bit mask for FTM_SYNCONF_HWWRBUF. */ #define BS_FTM_SYNCONF_HWWRBUF (1U) /*!< Bit field size in bits for FTM_SYNCONF_HWWRBUF. */ /*! @brief Read current value of the FTM_SYNCONF_HWWRBUF field. */ #define BR_FTM_SYNCONF_HWWRBUF(x) (BITBAND_ACCESS32(HW_FTM_SYNCONF_ADDR(x), BP_FTM_SYNCONF_HWWRBUF)) /*! @brief Format value for bitfield FTM_SYNCONF_HWWRBUF. */ #define BF_FTM_SYNCONF_HWWRBUF(v) ((uint32_t)((uint32_t)(v) << BP_FTM_SYNCONF_HWWRBUF) & BM_FTM_SYNCONF_HWWRBUF) /*! @brief Set the HWWRBUF field to a new value. */ #define BW_FTM_SYNCONF_HWWRBUF(x, v) (BITBAND_ACCESS32(HW_FTM_SYNCONF_ADDR(x), BP_FTM_SYNCONF_HWWRBUF) = (v)) /*@}*/ /*! * @name Register FTM_SYNCONF, field HWOM[18] (RW) * * Output mask synchronization is activated by a hardware trigger. * * Values: * - 0 - A hardware trigger does not activate the OUTMASK register * synchronization. * - 1 - A hardware trigger activates the OUTMASK register synchronization. */ /*@{*/ #define BP_FTM_SYNCONF_HWOM (18U) /*!< Bit position for FTM_SYNCONF_HWOM. */ #define BM_FTM_SYNCONF_HWOM (0x00040000U) /*!< Bit mask for FTM_SYNCONF_HWOM. */ #define BS_FTM_SYNCONF_HWOM (1U) /*!< Bit field size in bits for FTM_SYNCONF_HWOM. */ /*! @brief Read current value of the FTM_SYNCONF_HWOM field. */ #define BR_FTM_SYNCONF_HWOM(x) (BITBAND_ACCESS32(HW_FTM_SYNCONF_ADDR(x), BP_FTM_SYNCONF_HWOM)) /*! @brief Format value for bitfield FTM_SYNCONF_HWOM. */ #define BF_FTM_SYNCONF_HWOM(v) ((uint32_t)((uint32_t)(v) << BP_FTM_SYNCONF_HWOM) & BM_FTM_SYNCONF_HWOM) /*! @brief Set the HWOM field to a new value. */ #define BW_FTM_SYNCONF_HWOM(x, v) (BITBAND_ACCESS32(HW_FTM_SYNCONF_ADDR(x), BP_FTM_SYNCONF_HWOM) = (v)) /*@}*/ /*! * @name Register FTM_SYNCONF, field HWINVC[19] (RW) * * Inverting control synchronization is activated by a hardware trigger. * * Values: * - 0 - A hardware trigger does not activate the INVCTRL register * synchronization. * - 1 - A hardware trigger activates the INVCTRL register synchronization. */ /*@{*/ #define BP_FTM_SYNCONF_HWINVC (19U) /*!< Bit position for FTM_SYNCONF_HWINVC. */ #define BM_FTM_SYNCONF_HWINVC (0x00080000U) /*!< Bit mask for FTM_SYNCONF_HWINVC. */ #define BS_FTM_SYNCONF_HWINVC (1U) /*!< Bit field size in bits for FTM_SYNCONF_HWINVC. */ /*! @brief Read current value of the FTM_SYNCONF_HWINVC field. */ #define BR_FTM_SYNCONF_HWINVC(x) (BITBAND_ACCESS32(HW_FTM_SYNCONF_ADDR(x), BP_FTM_SYNCONF_HWINVC)) /*! @brief Format value for bitfield FTM_SYNCONF_HWINVC. */ #define BF_FTM_SYNCONF_HWINVC(v) ((uint32_t)((uint32_t)(v) << BP_FTM_SYNCONF_HWINVC) & BM_FTM_SYNCONF_HWINVC) /*! @brief Set the HWINVC field to a new value. */ #define BW_FTM_SYNCONF_HWINVC(x, v) (BITBAND_ACCESS32(HW_FTM_SYNCONF_ADDR(x), BP_FTM_SYNCONF_HWINVC) = (v)) /*@}*/ /*! * @name Register FTM_SYNCONF, field HWSOC[20] (RW) * * Software output control synchronization is activated by a hardware trigger. * * Values: * - 0 - A hardware trigger does not activate the SWOCTRL register * synchronization. * - 1 - A hardware trigger activates the SWOCTRL register synchronization. */ /*@{*/ #define BP_FTM_SYNCONF_HWSOC (20U) /*!< Bit position for FTM_SYNCONF_HWSOC. */ #define BM_FTM_SYNCONF_HWSOC (0x00100000U) /*!< Bit mask for FTM_SYNCONF_HWSOC. */ #define BS_FTM_SYNCONF_HWSOC (1U) /*!< Bit field size in bits for FTM_SYNCONF_HWSOC. */ /*! @brief Read current value of the FTM_SYNCONF_HWSOC field. */ #define BR_FTM_SYNCONF_HWSOC(x) (BITBAND_ACCESS32(HW_FTM_SYNCONF_ADDR(x), BP_FTM_SYNCONF_HWSOC)) /*! @brief Format value for bitfield FTM_SYNCONF_HWSOC. */ #define BF_FTM_SYNCONF_HWSOC(v) ((uint32_t)((uint32_t)(v) << BP_FTM_SYNCONF_HWSOC) & BM_FTM_SYNCONF_HWSOC) /*! @brief Set the HWSOC field to a new value. */ #define BW_FTM_SYNCONF_HWSOC(x, v) (BITBAND_ACCESS32(HW_FTM_SYNCONF_ADDR(x), BP_FTM_SYNCONF_HWSOC) = (v)) /*@}*/ /******************************************************************************* * HW_FTM_INVCTRL - FTM Inverting Control ******************************************************************************/ /*! * @brief HW_FTM_INVCTRL - FTM Inverting Control (RW) * * Reset value: 0x00000000U * * This register controls when the channel (n) output becomes the channel (n+1) * output, and channel (n+1) output becomes the channel (n) output. Each INVmEN * bit enables the inverting operation for the corresponding pair channels m. This * register has a write buffer. The INVmEN bit is updated by the INVCTRL * register synchronization. */ typedef union _hw_ftm_invctrl { uint32_t U; struct _hw_ftm_invctrl_bitfields { uint32_t INV0EN : 1; /*!< [0] Pair Channels 0 Inverting Enable */ uint32_t INV1EN : 1; /*!< [1] Pair Channels 1 Inverting Enable */ uint32_t INV2EN : 1; /*!< [2] Pair Channels 2 Inverting Enable */ uint32_t INV3EN : 1; /*!< [3] Pair Channels 3 Inverting Enable */ uint32_t RESERVED0 : 28; /*!< [31:4] */ } B; } hw_ftm_invctrl_t; /*! * @name Constants and macros for entire FTM_INVCTRL register */ /*@{*/ #define HW_FTM_INVCTRL_ADDR(x) ((x) + 0x90U) #define HW_FTM_INVCTRL(x) (*(__IO hw_ftm_invctrl_t *) HW_FTM_INVCTRL_ADDR(x)) #define HW_FTM_INVCTRL_RD(x) (HW_FTM_INVCTRL(x).U) #define HW_FTM_INVCTRL_WR(x, v) (HW_FTM_INVCTRL(x).U = (v)) #define HW_FTM_INVCTRL_SET(x, v) (HW_FTM_INVCTRL_WR(x, HW_FTM_INVCTRL_RD(x) | (v))) #define HW_FTM_INVCTRL_CLR(x, v) (HW_FTM_INVCTRL_WR(x, HW_FTM_INVCTRL_RD(x) & ~(v))) #define HW_FTM_INVCTRL_TOG(x, v) (HW_FTM_INVCTRL_WR(x, HW_FTM_INVCTRL_RD(x) ^ (v))) /*@}*/ /* * Constants & macros for individual FTM_INVCTRL bitfields */ /*! * @name Register FTM_INVCTRL, field INV0EN[0] (RW) * * Values: * - 0 - Inverting is disabled. * - 1 - Inverting is enabled. */ /*@{*/ #define BP_FTM_INVCTRL_INV0EN (0U) /*!< Bit position for FTM_INVCTRL_INV0EN. */ #define BM_FTM_INVCTRL_INV0EN (0x00000001U) /*!< Bit mask for FTM_INVCTRL_INV0EN. */ #define BS_FTM_INVCTRL_INV0EN (1U) /*!< Bit field size in bits for FTM_INVCTRL_INV0EN. */ /*! @brief Read current value of the FTM_INVCTRL_INV0EN field. */ #define BR_FTM_INVCTRL_INV0EN(x) (BITBAND_ACCESS32(HW_FTM_INVCTRL_ADDR(x), BP_FTM_INVCTRL_INV0EN)) /*! @brief Format value for bitfield FTM_INVCTRL_INV0EN. */ #define BF_FTM_INVCTRL_INV0EN(v) ((uint32_t)((uint32_t)(v) << BP_FTM_INVCTRL_INV0EN) & BM_FTM_INVCTRL_INV0EN) /*! @brief Set the INV0EN field to a new value. */ #define BW_FTM_INVCTRL_INV0EN(x, v) (BITBAND_ACCESS32(HW_FTM_INVCTRL_ADDR(x), BP_FTM_INVCTRL_INV0EN) = (v)) /*@}*/ /*! * @name Register FTM_INVCTRL, field INV1EN[1] (RW) * * Values: * - 0 - Inverting is disabled. * - 1 - Inverting is enabled. */ /*@{*/ #define BP_FTM_INVCTRL_INV1EN (1U) /*!< Bit position for FTM_INVCTRL_INV1EN. */ #define BM_FTM_INVCTRL_INV1EN (0x00000002U) /*!< Bit mask for FTM_INVCTRL_INV1EN. */ #define BS_FTM_INVCTRL_INV1EN (1U) /*!< Bit field size in bits for FTM_INVCTRL_INV1EN. */ /*! @brief Read current value of the FTM_INVCTRL_INV1EN field. */ #define BR_FTM_INVCTRL_INV1EN(x) (BITBAND_ACCESS32(HW_FTM_INVCTRL_ADDR(x), BP_FTM_INVCTRL_INV1EN)) /*! @brief Format value for bitfield FTM_INVCTRL_INV1EN. */ #define BF_FTM_INVCTRL_INV1EN(v) ((uint32_t)((uint32_t)(v) << BP_FTM_INVCTRL_INV1EN) & BM_FTM_INVCTRL_INV1EN) /*! @brief Set the INV1EN field to a new value. */ #define BW_FTM_INVCTRL_INV1EN(x, v) (BITBAND_ACCESS32(HW_FTM_INVCTRL_ADDR(x), BP_FTM_INVCTRL_INV1EN) = (v)) /*@}*/ /*! * @name Register FTM_INVCTRL, field INV2EN[2] (RW) * * Values: * - 0 - Inverting is disabled. * - 1 - Inverting is enabled. */ /*@{*/ #define BP_FTM_INVCTRL_INV2EN (2U) /*!< Bit position for FTM_INVCTRL_INV2EN. */ #define BM_FTM_INVCTRL_INV2EN (0x00000004U) /*!< Bit mask for FTM_INVCTRL_INV2EN. */ #define BS_FTM_INVCTRL_INV2EN (1U) /*!< Bit field size in bits for FTM_INVCTRL_INV2EN. */ /*! @brief Read current value of the FTM_INVCTRL_INV2EN field. */ #define BR_FTM_INVCTRL_INV2EN(x) (BITBAND_ACCESS32(HW_FTM_INVCTRL_ADDR(x), BP_FTM_INVCTRL_INV2EN)) /*! @brief Format value for bitfield FTM_INVCTRL_INV2EN. */ #define BF_FTM_INVCTRL_INV2EN(v) ((uint32_t)((uint32_t)(v) << BP_FTM_INVCTRL_INV2EN) & BM_FTM_INVCTRL_INV2EN) /*! @brief Set the INV2EN field to a new value. */ #define BW_FTM_INVCTRL_INV2EN(x, v) (BITBAND_ACCESS32(HW_FTM_INVCTRL_ADDR(x), BP_FTM_INVCTRL_INV2EN) = (v)) /*@}*/ /*! * @name Register FTM_INVCTRL, field INV3EN[3] (RW) * * Values: * - 0 - Inverting is disabled. * - 1 - Inverting is enabled. */ /*@{*/ #define BP_FTM_INVCTRL_INV3EN (3U) /*!< Bit position for FTM_INVCTRL_INV3EN. */ #define BM_FTM_INVCTRL_INV3EN (0x00000008U) /*!< Bit mask for FTM_INVCTRL_INV3EN. */ #define BS_FTM_INVCTRL_INV3EN (1U) /*!< Bit field size in bits for FTM_INVCTRL_INV3EN. */ /*! @brief Read current value of the FTM_INVCTRL_INV3EN field. */ #define BR_FTM_INVCTRL_INV3EN(x) (BITBAND_ACCESS32(HW_FTM_INVCTRL_ADDR(x), BP_FTM_INVCTRL_INV3EN)) /*! @brief Format value for bitfield FTM_INVCTRL_INV3EN. */ #define BF_FTM_INVCTRL_INV3EN(v) ((uint32_t)((uint32_t)(v) << BP_FTM_INVCTRL_INV3EN) & BM_FTM_INVCTRL_INV3EN) /*! @brief Set the INV3EN field to a new value. */ #define BW_FTM_INVCTRL_INV3EN(x, v) (BITBAND_ACCESS32(HW_FTM_INVCTRL_ADDR(x), BP_FTM_INVCTRL_INV3EN) = (v)) /*@}*/ /******************************************************************************* * HW_FTM_SWOCTRL - FTM Software Output Control ******************************************************************************/ /*! * @brief HW_FTM_SWOCTRL - FTM Software Output Control (RW) * * Reset value: 0x00000000U * * This register enables software control of channel (n) output and defines the * value forced to the channel (n) output: The CHnOC bits enable the control of * the corresponding channel (n) output by software. The CHnOCV bits select the * value that is forced at the corresponding channel (n) output. This register has * a write buffer. The fields are updated by the SWOCTRL register synchronization. */ typedef union _hw_ftm_swoctrl { uint32_t U; struct _hw_ftm_swoctrl_bitfields { uint32_t CH0OC : 1; /*!< [0] Channel 0 Software Output Control Enable * */ uint32_t CH1OC : 1; /*!< [1] Channel 1 Software Output Control Enable * */ uint32_t CH2OC : 1; /*!< [2] Channel 2 Software Output Control Enable * */ uint32_t CH3OC : 1; /*!< [3] Channel 3 Software Output Control Enable * */ uint32_t CH4OC : 1; /*!< [4] Channel 4 Software Output Control Enable * */ uint32_t CH5OC : 1; /*!< [5] Channel 5 Software Output Control Enable * */ uint32_t CH6OC : 1; /*!< [6] Channel 6 Software Output Control Enable * */ uint32_t CH7OC : 1; /*!< [7] Channel 7 Software Output Control Enable * */ uint32_t CH0OCV : 1; /*!< [8] Channel 0 Software Output Control Value * */ uint32_t CH1OCV : 1; /*!< [9] Channel 1 Software Output Control Value * */ uint32_t CH2OCV : 1; /*!< [10] Channel 2 Software Output Control * Value */ uint32_t CH3OCV : 1; /*!< [11] Channel 3 Software Output Control * Value */ uint32_t CH4OCV : 1; /*!< [12] Channel 4 Software Output Control * Value */ uint32_t CH5OCV : 1; /*!< [13] Channel 5 Software Output Control * Value */ uint32_t CH6OCV : 1; /*!< [14] Channel 6 Software Output Control * Value */ uint32_t CH7OCV : 1; /*!< [15] Channel 7 Software Output Control * Value */ uint32_t RESERVED0 : 16; /*!< [31:16] */ } B; } hw_ftm_swoctrl_t; /*! * @name Constants and macros for entire FTM_SWOCTRL register */ /*@{*/ #define HW_FTM_SWOCTRL_ADDR(x) ((x) + 0x94U) #define HW_FTM_SWOCTRL(x) (*(__IO hw_ftm_swoctrl_t *) HW_FTM_SWOCTRL_ADDR(x)) #define HW_FTM_SWOCTRL_RD(x) (HW_FTM_SWOCTRL(x).U) #define HW_FTM_SWOCTRL_WR(x, v) (HW_FTM_SWOCTRL(x).U = (v)) #define HW_FTM_SWOCTRL_SET(x, v) (HW_FTM_SWOCTRL_WR(x, HW_FTM_SWOCTRL_RD(x) | (v))) #define HW_FTM_SWOCTRL_CLR(x, v) (HW_FTM_SWOCTRL_WR(x, HW_FTM_SWOCTRL_RD(x) & ~(v))) #define HW_FTM_SWOCTRL_TOG(x, v) (HW_FTM_SWOCTRL_WR(x, HW_FTM_SWOCTRL_RD(x) ^ (v))) /*@}*/ /* * Constants & macros for individual FTM_SWOCTRL bitfields */ /*! * @name Register FTM_SWOCTRL, field CH0OC[0] (RW) * * Values: * - 0 - The channel output is not affected by software output control. * - 1 - The channel output is affected by software output control. */ /*@{*/ #define BP_FTM_SWOCTRL_CH0OC (0U) /*!< Bit position for FTM_SWOCTRL_CH0OC. */ #define BM_FTM_SWOCTRL_CH0OC (0x00000001U) /*!< Bit mask for FTM_SWOCTRL_CH0OC. */ #define BS_FTM_SWOCTRL_CH0OC (1U) /*!< Bit field size in bits for FTM_SWOCTRL_CH0OC. */ /*! @brief Read current value of the FTM_SWOCTRL_CH0OC field. */ #define BR_FTM_SWOCTRL_CH0OC(x) (BITBAND_ACCESS32(HW_FTM_SWOCTRL_ADDR(x), BP_FTM_SWOCTRL_CH0OC)) /*! @brief Format value for bitfield FTM_SWOCTRL_CH0OC. */ #define BF_FTM_SWOCTRL_CH0OC(v) ((uint32_t)((uint32_t)(v) << BP_FTM_SWOCTRL_CH0OC) & BM_FTM_SWOCTRL_CH0OC) /*! @brief Set the CH0OC field to a new value. */ #define BW_FTM_SWOCTRL_CH0OC(x, v) (BITBAND_ACCESS32(HW_FTM_SWOCTRL_ADDR(x), BP_FTM_SWOCTRL_CH0OC) = (v)) /*@}*/ /*! * @name Register FTM_SWOCTRL, field CH1OC[1] (RW) * * Values: * - 0 - The channel output is not affected by software output control. * - 1 - The channel output is affected by software output control. */ /*@{*/ #define BP_FTM_SWOCTRL_CH1OC (1U) /*!< Bit position for FTM_SWOCTRL_CH1OC. */ #define BM_FTM_SWOCTRL_CH1OC (0x00000002U) /*!< Bit mask for FTM_SWOCTRL_CH1OC. */ #define BS_FTM_SWOCTRL_CH1OC (1U) /*!< Bit field size in bits for FTM_SWOCTRL_CH1OC. */ /*! @brief Read current value of the FTM_SWOCTRL_CH1OC field. */ #define BR_FTM_SWOCTRL_CH1OC(x) (BITBAND_ACCESS32(HW_FTM_SWOCTRL_ADDR(x), BP_FTM_SWOCTRL_CH1OC)) /*! @brief Format value for bitfield FTM_SWOCTRL_CH1OC. */ #define BF_FTM_SWOCTRL_CH1OC(v) ((uint32_t)((uint32_t)(v) << BP_FTM_SWOCTRL_CH1OC) & BM_FTM_SWOCTRL_CH1OC) /*! @brief Set the CH1OC field to a new value. */ #define BW_FTM_SWOCTRL_CH1OC(x, v) (BITBAND_ACCESS32(HW_FTM_SWOCTRL_ADDR(x), BP_FTM_SWOCTRL_CH1OC) = (v)) /*@}*/ /*! * @name Register FTM_SWOCTRL, field CH2OC[2] (RW) * * Values: * - 0 - The channel output is not affected by software output control. * - 1 - The channel output is affected by software output control. */ /*@{*/ #define BP_FTM_SWOCTRL_CH2OC (2U) /*!< Bit position for FTM_SWOCTRL_CH2OC. */ #define BM_FTM_SWOCTRL_CH2OC (0x00000004U) /*!< Bit mask for FTM_SWOCTRL_CH2OC. */ #define BS_FTM_SWOCTRL_CH2OC (1U) /*!< Bit field size in bits for FTM_SWOCTRL_CH2OC. */ /*! @brief Read current value of the FTM_SWOCTRL_CH2OC field. */ #define BR_FTM_SWOCTRL_CH2OC(x) (BITBAND_ACCESS32(HW_FTM_SWOCTRL_ADDR(x), BP_FTM_SWOCTRL_CH2OC)) /*! @brief Format value for bitfield FTM_SWOCTRL_CH2OC. */ #define BF_FTM_SWOCTRL_CH2OC(v) ((uint32_t)((uint32_t)(v) << BP_FTM_SWOCTRL_CH2OC) & BM_FTM_SWOCTRL_CH2OC) /*! @brief Set the CH2OC field to a new value. */ #define BW_FTM_SWOCTRL_CH2OC(x, v) (BITBAND_ACCESS32(HW_FTM_SWOCTRL_ADDR(x), BP_FTM_SWOCTRL_CH2OC) = (v)) /*@}*/ /*! * @name Register FTM_SWOCTRL, field CH3OC[3] (RW) * * Values: * - 0 - The channel output is not affected by software output control. * - 1 - The channel output is affected by software output control. */ /*@{*/ #define BP_FTM_SWOCTRL_CH3OC (3U) /*!< Bit position for FTM_SWOCTRL_CH3OC. */ #define BM_FTM_SWOCTRL_CH3OC (0x00000008U) /*!< Bit mask for FTM_SWOCTRL_CH3OC. */ #define BS_FTM_SWOCTRL_CH3OC (1U) /*!< Bit field size in bits for FTM_SWOCTRL_CH3OC. */ /*! @brief Read current value of the FTM_SWOCTRL_CH3OC field. */ #define BR_FTM_SWOCTRL_CH3OC(x) (BITBAND_ACCESS32(HW_FTM_SWOCTRL_ADDR(x), BP_FTM_SWOCTRL_CH3OC)) /*! @brief Format value for bitfield FTM_SWOCTRL_CH3OC. */ #define BF_FTM_SWOCTRL_CH3OC(v) ((uint32_t)((uint32_t)(v) << BP_FTM_SWOCTRL_CH3OC) & BM_FTM_SWOCTRL_CH3OC) /*! @brief Set the CH3OC field to a new value. */ #define BW_FTM_SWOCTRL_CH3OC(x, v) (BITBAND_ACCESS32(HW_FTM_SWOCTRL_ADDR(x), BP_FTM_SWOCTRL_CH3OC) = (v)) /*@}*/ /*! * @name Register FTM_SWOCTRL, field CH4OC[4] (RW) * * Values: * - 0 - The channel output is not affected by software output control. * - 1 - The channel output is affected by software output control. */ /*@{*/ #define BP_FTM_SWOCTRL_CH4OC (4U) /*!< Bit position for FTM_SWOCTRL_CH4OC. */ #define BM_FTM_SWOCTRL_CH4OC (0x00000010U) /*!< Bit mask for FTM_SWOCTRL_CH4OC. */ #define BS_FTM_SWOCTRL_CH4OC (1U) /*!< Bit field size in bits for FTM_SWOCTRL_CH4OC. */ /*! @brief Read current value of the FTM_SWOCTRL_CH4OC field. */ #define BR_FTM_SWOCTRL_CH4OC(x) (BITBAND_ACCESS32(HW_FTM_SWOCTRL_ADDR(x), BP_FTM_SWOCTRL_CH4OC)) /*! @brief Format value for bitfield FTM_SWOCTRL_CH4OC. */ #define BF_FTM_SWOCTRL_CH4OC(v) ((uint32_t)((uint32_t)(v) << BP_FTM_SWOCTRL_CH4OC) & BM_FTM_SWOCTRL_CH4OC) /*! @brief Set the CH4OC field to a new value. */ #define BW_FTM_SWOCTRL_CH4OC(x, v) (BITBAND_ACCESS32(HW_FTM_SWOCTRL_ADDR(x), BP_FTM_SWOCTRL_CH4OC) = (v)) /*@}*/ /*! * @name Register FTM_SWOCTRL, field CH5OC[5] (RW) * * Values: * - 0 - The channel output is not affected by software output control. * - 1 - The channel output is affected by software output control. */ /*@{*/ #define BP_FTM_SWOCTRL_CH5OC (5U) /*!< Bit position for FTM_SWOCTRL_CH5OC. */ #define BM_FTM_SWOCTRL_CH5OC (0x00000020U) /*!< Bit mask for FTM_SWOCTRL_CH5OC. */ #define BS_FTM_SWOCTRL_CH5OC (1U) /*!< Bit field size in bits for FTM_SWOCTRL_CH5OC. */ /*! @brief Read current value of the FTM_SWOCTRL_CH5OC field. */ #define BR_FTM_SWOCTRL_CH5OC(x) (BITBAND_ACCESS32(HW_FTM_SWOCTRL_ADDR(x), BP_FTM_SWOCTRL_CH5OC)) /*! @brief Format value for bitfield FTM_SWOCTRL_CH5OC. */ #define BF_FTM_SWOCTRL_CH5OC(v) ((uint32_t)((uint32_t)(v) << BP_FTM_SWOCTRL_CH5OC) & BM_FTM_SWOCTRL_CH5OC) /*! @brief Set the CH5OC field to a new value. */ #define BW_FTM_SWOCTRL_CH5OC(x, v) (BITBAND_ACCESS32(HW_FTM_SWOCTRL_ADDR(x), BP_FTM_SWOCTRL_CH5OC) = (v)) /*@}*/ /*! * @name Register FTM_SWOCTRL, field CH6OC[6] (RW) * * Values: * - 0 - The channel output is not affected by software output control. * - 1 - The channel output is affected by software output control. */ /*@{*/ #define BP_FTM_SWOCTRL_CH6OC (6U) /*!< Bit position for FTM_SWOCTRL_CH6OC. */ #define BM_FTM_SWOCTRL_CH6OC (0x00000040U) /*!< Bit mask for FTM_SWOCTRL_CH6OC. */ #define BS_FTM_SWOCTRL_CH6OC (1U) /*!< Bit field size in bits for FTM_SWOCTRL_CH6OC. */ /*! @brief Read current value of the FTM_SWOCTRL_CH6OC field. */ #define BR_FTM_SWOCTRL_CH6OC(x) (BITBAND_ACCESS32(HW_FTM_SWOCTRL_ADDR(x), BP_FTM_SWOCTRL_CH6OC)) /*! @brief Format value for bitfield FTM_SWOCTRL_CH6OC. */ #define BF_FTM_SWOCTRL_CH6OC(v) ((uint32_t)((uint32_t)(v) << BP_FTM_SWOCTRL_CH6OC) & BM_FTM_SWOCTRL_CH6OC) /*! @brief Set the CH6OC field to a new value. */ #define BW_FTM_SWOCTRL_CH6OC(x, v) (BITBAND_ACCESS32(HW_FTM_SWOCTRL_ADDR(x), BP_FTM_SWOCTRL_CH6OC) = (v)) /*@}*/ /*! * @name Register FTM_SWOCTRL, field CH7OC[7] (RW) * * Values: * - 0 - The channel output is not affected by software output control. * - 1 - The channel output is affected by software output control. */ /*@{*/ #define BP_FTM_SWOCTRL_CH7OC (7U) /*!< Bit position for FTM_SWOCTRL_CH7OC. */ #define BM_FTM_SWOCTRL_CH7OC (0x00000080U) /*!< Bit mask for FTM_SWOCTRL_CH7OC. */ #define BS_FTM_SWOCTRL_CH7OC (1U) /*!< Bit field size in bits for FTM_SWOCTRL_CH7OC. */ /*! @brief Read current value of the FTM_SWOCTRL_CH7OC field. */ #define BR_FTM_SWOCTRL_CH7OC(x) (BITBAND_ACCESS32(HW_FTM_SWOCTRL_ADDR(x), BP_FTM_SWOCTRL_CH7OC)) /*! @brief Format value for bitfield FTM_SWOCTRL_CH7OC. */ #define BF_FTM_SWOCTRL_CH7OC(v) ((uint32_t)((uint32_t)(v) << BP_FTM_SWOCTRL_CH7OC) & BM_FTM_SWOCTRL_CH7OC) /*! @brief Set the CH7OC field to a new value. */ #define BW_FTM_SWOCTRL_CH7OC(x, v) (BITBAND_ACCESS32(HW_FTM_SWOCTRL_ADDR(x), BP_FTM_SWOCTRL_CH7OC) = (v)) /*@}*/ /*! * @name Register FTM_SWOCTRL, field CH0OCV[8] (RW) * * Values: * - 0 - The software output control forces 0 to the channel output. * - 1 - The software output control forces 1 to the channel output. */ /*@{*/ #define BP_FTM_SWOCTRL_CH0OCV (8U) /*!< Bit position for FTM_SWOCTRL_CH0OCV. */ #define BM_FTM_SWOCTRL_CH0OCV (0x00000100U) /*!< Bit mask for FTM_SWOCTRL_CH0OCV. */ #define BS_FTM_SWOCTRL_CH0OCV (1U) /*!< Bit field size in bits for FTM_SWOCTRL_CH0OCV. */ /*! @brief Read current value of the FTM_SWOCTRL_CH0OCV field. */ #define BR_FTM_SWOCTRL_CH0OCV(x) (BITBAND_ACCESS32(HW_FTM_SWOCTRL_ADDR(x), BP_FTM_SWOCTRL_CH0OCV)) /*! @brief Format value for bitfield FTM_SWOCTRL_CH0OCV. */ #define BF_FTM_SWOCTRL_CH0OCV(v) ((uint32_t)((uint32_t)(v) << BP_FTM_SWOCTRL_CH0OCV) & BM_FTM_SWOCTRL_CH0OCV) /*! @brief Set the CH0OCV field to a new value. */ #define BW_FTM_SWOCTRL_CH0OCV(x, v) (BITBAND_ACCESS32(HW_FTM_SWOCTRL_ADDR(x), BP_FTM_SWOCTRL_CH0OCV) = (v)) /*@}*/ /*! * @name Register FTM_SWOCTRL, field CH1OCV[9] (RW) * * Values: * - 0 - The software output control forces 0 to the channel output. * - 1 - The software output control forces 1 to the channel output. */ /*@{*/ #define BP_FTM_SWOCTRL_CH1OCV (9U) /*!< Bit position for FTM_SWOCTRL_CH1OCV. */ #define BM_FTM_SWOCTRL_CH1OCV (0x00000200U) /*!< Bit mask for FTM_SWOCTRL_CH1OCV. */ #define BS_FTM_SWOCTRL_CH1OCV (1U) /*!< Bit field size in bits for FTM_SWOCTRL_CH1OCV. */ /*! @brief Read current value of the FTM_SWOCTRL_CH1OCV field. */ #define BR_FTM_SWOCTRL_CH1OCV(x) (BITBAND_ACCESS32(HW_FTM_SWOCTRL_ADDR(x), BP_FTM_SWOCTRL_CH1OCV)) /*! @brief Format value for bitfield FTM_SWOCTRL_CH1OCV. */ #define BF_FTM_SWOCTRL_CH1OCV(v) ((uint32_t)((uint32_t)(v) << BP_FTM_SWOCTRL_CH1OCV) & BM_FTM_SWOCTRL_CH1OCV) /*! @brief Set the CH1OCV field to a new value. */ #define BW_FTM_SWOCTRL_CH1OCV(x, v) (BITBAND_ACCESS32(HW_FTM_SWOCTRL_ADDR(x), BP_FTM_SWOCTRL_CH1OCV) = (v)) /*@}*/ /*! * @name Register FTM_SWOCTRL, field CH2OCV[10] (RW) * * Values: * - 0 - The software output control forces 0 to the channel output. * - 1 - The software output control forces 1 to the channel output. */ /*@{*/ #define BP_FTM_SWOCTRL_CH2OCV (10U) /*!< Bit position for FTM_SWOCTRL_CH2OCV. */ #define BM_FTM_SWOCTRL_CH2OCV (0x00000400U) /*!< Bit mask for FTM_SWOCTRL_CH2OCV. */ #define BS_FTM_SWOCTRL_CH2OCV (1U) /*!< Bit field size in bits for FTM_SWOCTRL_CH2OCV. */ /*! @brief Read current value of the FTM_SWOCTRL_CH2OCV field. */ #define BR_FTM_SWOCTRL_CH2OCV(x) (BITBAND_ACCESS32(HW_FTM_SWOCTRL_ADDR(x), BP_FTM_SWOCTRL_CH2OCV)) /*! @brief Format value for bitfield FTM_SWOCTRL_CH2OCV. */ #define BF_FTM_SWOCTRL_CH2OCV(v) ((uint32_t)((uint32_t)(v) << BP_FTM_SWOCTRL_CH2OCV) & BM_FTM_SWOCTRL_CH2OCV) /*! @brief Set the CH2OCV field to a new value. */ #define BW_FTM_SWOCTRL_CH2OCV(x, v) (BITBAND_ACCESS32(HW_FTM_SWOCTRL_ADDR(x), BP_FTM_SWOCTRL_CH2OCV) = (v)) /*@}*/ /*! * @name Register FTM_SWOCTRL, field CH3OCV[11] (RW) * * Values: * - 0 - The software output control forces 0 to the channel output. * - 1 - The software output control forces 1 to the channel output. */ /*@{*/ #define BP_FTM_SWOCTRL_CH3OCV (11U) /*!< Bit position for FTM_SWOCTRL_CH3OCV. */ #define BM_FTM_SWOCTRL_CH3OCV (0x00000800U) /*!< Bit mask for FTM_SWOCTRL_CH3OCV. */ #define BS_FTM_SWOCTRL_CH3OCV (1U) /*!< Bit field size in bits for FTM_SWOCTRL_CH3OCV. */ /*! @brief Read current value of the FTM_SWOCTRL_CH3OCV field. */ #define BR_FTM_SWOCTRL_CH3OCV(x) (BITBAND_ACCESS32(HW_FTM_SWOCTRL_ADDR(x), BP_FTM_SWOCTRL_CH3OCV)) /*! @brief Format value for bitfield FTM_SWOCTRL_CH3OCV. */ #define BF_FTM_SWOCTRL_CH3OCV(v) ((uint32_t)((uint32_t)(v) << BP_FTM_SWOCTRL_CH3OCV) & BM_FTM_SWOCTRL_CH3OCV) /*! @brief Set the CH3OCV field to a new value. */ #define BW_FTM_SWOCTRL_CH3OCV(x, v) (BITBAND_ACCESS32(HW_FTM_SWOCTRL_ADDR(x), BP_FTM_SWOCTRL_CH3OCV) = (v)) /*@}*/ /*! * @name Register FTM_SWOCTRL, field CH4OCV[12] (RW) * * Values: * - 0 - The software output control forces 0 to the channel output. * - 1 - The software output control forces 1 to the channel output. */ /*@{*/ #define BP_FTM_SWOCTRL_CH4OCV (12U) /*!< Bit position for FTM_SWOCTRL_CH4OCV. */ #define BM_FTM_SWOCTRL_CH4OCV (0x00001000U) /*!< Bit mask for FTM_SWOCTRL_CH4OCV. */ #define BS_FTM_SWOCTRL_CH4OCV (1U) /*!< Bit field size in bits for FTM_SWOCTRL_CH4OCV. */ /*! @brief Read current value of the FTM_SWOCTRL_CH4OCV field. */ #define BR_FTM_SWOCTRL_CH4OCV(x) (BITBAND_ACCESS32(HW_FTM_SWOCTRL_ADDR(x), BP_FTM_SWOCTRL_CH4OCV)) /*! @brief Format value for bitfield FTM_SWOCTRL_CH4OCV. */ #define BF_FTM_SWOCTRL_CH4OCV(v) ((uint32_t)((uint32_t)(v) << BP_FTM_SWOCTRL_CH4OCV) & BM_FTM_SWOCTRL_CH4OCV) /*! @brief Set the CH4OCV field to a new value. */ #define BW_FTM_SWOCTRL_CH4OCV(x, v) (BITBAND_ACCESS32(HW_FTM_SWOCTRL_ADDR(x), BP_FTM_SWOCTRL_CH4OCV) = (v)) /*@}*/ /*! * @name Register FTM_SWOCTRL, field CH5OCV[13] (RW) * * Values: * - 0 - The software output control forces 0 to the channel output. * - 1 - The software output control forces 1 to the channel output. */ /*@{*/ #define BP_FTM_SWOCTRL_CH5OCV (13U) /*!< Bit position for FTM_SWOCTRL_CH5OCV. */ #define BM_FTM_SWOCTRL_CH5OCV (0x00002000U) /*!< Bit mask for FTM_SWOCTRL_CH5OCV. */ #define BS_FTM_SWOCTRL_CH5OCV (1U) /*!< Bit field size in bits for FTM_SWOCTRL_CH5OCV. */ /*! @brief Read current value of the FTM_SWOCTRL_CH5OCV field. */ #define BR_FTM_SWOCTRL_CH5OCV(x) (BITBAND_ACCESS32(HW_FTM_SWOCTRL_ADDR(x), BP_FTM_SWOCTRL_CH5OCV)) /*! @brief Format value for bitfield FTM_SWOCTRL_CH5OCV. */ #define BF_FTM_SWOCTRL_CH5OCV(v) ((uint32_t)((uint32_t)(v) << BP_FTM_SWOCTRL_CH5OCV) & BM_FTM_SWOCTRL_CH5OCV) /*! @brief Set the CH5OCV field to a new value. */ #define BW_FTM_SWOCTRL_CH5OCV(x, v) (BITBAND_ACCESS32(HW_FTM_SWOCTRL_ADDR(x), BP_FTM_SWOCTRL_CH5OCV) = (v)) /*@}*/ /*! * @name Register FTM_SWOCTRL, field CH6OCV[14] (RW) * * Values: * - 0 - The software output control forces 0 to the channel output. * - 1 - The software output control forces 1 to the channel output. */ /*@{*/ #define BP_FTM_SWOCTRL_CH6OCV (14U) /*!< Bit position for FTM_SWOCTRL_CH6OCV. */ #define BM_FTM_SWOCTRL_CH6OCV (0x00004000U) /*!< Bit mask for FTM_SWOCTRL_CH6OCV. */ #define BS_FTM_SWOCTRL_CH6OCV (1U) /*!< Bit field size in bits for FTM_SWOCTRL_CH6OCV. */ /*! @brief Read current value of the FTM_SWOCTRL_CH6OCV field. */ #define BR_FTM_SWOCTRL_CH6OCV(x) (BITBAND_ACCESS32(HW_FTM_SWOCTRL_ADDR(x), BP_FTM_SWOCTRL_CH6OCV)) /*! @brief Format value for bitfield FTM_SWOCTRL_CH6OCV. */ #define BF_FTM_SWOCTRL_CH6OCV(v) ((uint32_t)((uint32_t)(v) << BP_FTM_SWOCTRL_CH6OCV) & BM_FTM_SWOCTRL_CH6OCV) /*! @brief Set the CH6OCV field to a new value. */ #define BW_FTM_SWOCTRL_CH6OCV(x, v) (BITBAND_ACCESS32(HW_FTM_SWOCTRL_ADDR(x), BP_FTM_SWOCTRL_CH6OCV) = (v)) /*@}*/ /*! * @name Register FTM_SWOCTRL, field CH7OCV[15] (RW) * * Values: * - 0 - The software output control forces 0 to the channel output. * - 1 - The software output control forces 1 to the channel output. */ /*@{*/ #define BP_FTM_SWOCTRL_CH7OCV (15U) /*!< Bit position for FTM_SWOCTRL_CH7OCV. */ #define BM_FTM_SWOCTRL_CH7OCV (0x00008000U) /*!< Bit mask for FTM_SWOCTRL_CH7OCV. */ #define BS_FTM_SWOCTRL_CH7OCV (1U) /*!< Bit field size in bits for FTM_SWOCTRL_CH7OCV. */ /*! @brief Read current value of the FTM_SWOCTRL_CH7OCV field. */ #define BR_FTM_SWOCTRL_CH7OCV(x) (BITBAND_ACCESS32(HW_FTM_SWOCTRL_ADDR(x), BP_FTM_SWOCTRL_CH7OCV)) /*! @brief Format value for bitfield FTM_SWOCTRL_CH7OCV. */ #define BF_FTM_SWOCTRL_CH7OCV(v) ((uint32_t)((uint32_t)(v) << BP_FTM_SWOCTRL_CH7OCV) & BM_FTM_SWOCTRL_CH7OCV) /*! @brief Set the CH7OCV field to a new value. */ #define BW_FTM_SWOCTRL_CH7OCV(x, v) (BITBAND_ACCESS32(HW_FTM_SWOCTRL_ADDR(x), BP_FTM_SWOCTRL_CH7OCV) = (v)) /*@}*/ /******************************************************************************* * HW_FTM_PWMLOAD - FTM PWM Load ******************************************************************************/ /*! * @brief HW_FTM_PWMLOAD - FTM PWM Load (RW) * * Reset value: 0x00000000U * * Enables the loading of the MOD, CNTIN, C(n)V, and C(n+1)V registers with the * values of their write buffers when the FTM counter changes from the MOD * register value to its next value or when a channel (j) match occurs. A match occurs * for the channel (j) when FTM counter = C(j)V. */ typedef union _hw_ftm_pwmload { uint32_t U; struct _hw_ftm_pwmload_bitfields { uint32_t CH0SEL : 1; /*!< [0] Channel 0 Select */ uint32_t CH1SEL : 1; /*!< [1] Channel 1 Select */ uint32_t CH2SEL : 1; /*!< [2] Channel 2 Select */ uint32_t CH3SEL : 1; /*!< [3] Channel 3 Select */ uint32_t CH4SEL : 1; /*!< [4] Channel 4 Select */ uint32_t CH5SEL : 1; /*!< [5] Channel 5 Select */ uint32_t CH6SEL : 1; /*!< [6] Channel 6 Select */ uint32_t CH7SEL : 1; /*!< [7] Channel 7 Select */ uint32_t RESERVED0 : 1; /*!< [8] */ uint32_t LDOK : 1; /*!< [9] Load Enable */ uint32_t RESERVED1 : 22; /*!< [31:10] */ } B; } hw_ftm_pwmload_t; /*! * @name Constants and macros for entire FTM_PWMLOAD register */ /*@{*/ #define HW_FTM_PWMLOAD_ADDR(x) ((x) + 0x98U) #define HW_FTM_PWMLOAD(x) (*(__IO hw_ftm_pwmload_t *) HW_FTM_PWMLOAD_ADDR(x)) #define HW_FTM_PWMLOAD_RD(x) (HW_FTM_PWMLOAD(x).U) #define HW_FTM_PWMLOAD_WR(x, v) (HW_FTM_PWMLOAD(x).U = (v)) #define HW_FTM_PWMLOAD_SET(x, v) (HW_FTM_PWMLOAD_WR(x, HW_FTM_PWMLOAD_RD(x) | (v))) #define HW_FTM_PWMLOAD_CLR(x, v) (HW_FTM_PWMLOAD_WR(x, HW_FTM_PWMLOAD_RD(x) & ~(v))) #define HW_FTM_PWMLOAD_TOG(x, v) (HW_FTM_PWMLOAD_WR(x, HW_FTM_PWMLOAD_RD(x) ^ (v))) /*@}*/ /* * Constants & macros for individual FTM_PWMLOAD bitfields */ /*! * @name Register FTM_PWMLOAD, field CH0SEL[0] (RW) * * Values: * - 0 - Do not include the channel in the matching process. * - 1 - Include the channel in the matching process. */ /*@{*/ #define BP_FTM_PWMLOAD_CH0SEL (0U) /*!< Bit position for FTM_PWMLOAD_CH0SEL. */ #define BM_FTM_PWMLOAD_CH0SEL (0x00000001U) /*!< Bit mask for FTM_PWMLOAD_CH0SEL. */ #define BS_FTM_PWMLOAD_CH0SEL (1U) /*!< Bit field size in bits for FTM_PWMLOAD_CH0SEL. */ /*! @brief Read current value of the FTM_PWMLOAD_CH0SEL field. */ #define BR_FTM_PWMLOAD_CH0SEL(x) (BITBAND_ACCESS32(HW_FTM_PWMLOAD_ADDR(x), BP_FTM_PWMLOAD_CH0SEL)) /*! @brief Format value for bitfield FTM_PWMLOAD_CH0SEL. */ #define BF_FTM_PWMLOAD_CH0SEL(v) ((uint32_t)((uint32_t)(v) << BP_FTM_PWMLOAD_CH0SEL) & BM_FTM_PWMLOAD_CH0SEL) /*! @brief Set the CH0SEL field to a new value. */ #define BW_FTM_PWMLOAD_CH0SEL(x, v) (BITBAND_ACCESS32(HW_FTM_PWMLOAD_ADDR(x), BP_FTM_PWMLOAD_CH0SEL) = (v)) /*@}*/ /*! * @name Register FTM_PWMLOAD, field CH1SEL[1] (RW) * * Values: * - 0 - Do not include the channel in the matching process. * - 1 - Include the channel in the matching process. */ /*@{*/ #define BP_FTM_PWMLOAD_CH1SEL (1U) /*!< Bit position for FTM_PWMLOAD_CH1SEL. */ #define BM_FTM_PWMLOAD_CH1SEL (0x00000002U) /*!< Bit mask for FTM_PWMLOAD_CH1SEL. */ #define BS_FTM_PWMLOAD_CH1SEL (1U) /*!< Bit field size in bits for FTM_PWMLOAD_CH1SEL. */ /*! @brief Read current value of the FTM_PWMLOAD_CH1SEL field. */ #define BR_FTM_PWMLOAD_CH1SEL(x) (BITBAND_ACCESS32(HW_FTM_PWMLOAD_ADDR(x), BP_FTM_PWMLOAD_CH1SEL)) /*! @brief Format value for bitfield FTM_PWMLOAD_CH1SEL. */ #define BF_FTM_PWMLOAD_CH1SEL(v) ((uint32_t)((uint32_t)(v) << BP_FTM_PWMLOAD_CH1SEL) & BM_FTM_PWMLOAD_CH1SEL) /*! @brief Set the CH1SEL field to a new value. */ #define BW_FTM_PWMLOAD_CH1SEL(x, v) (BITBAND_ACCESS32(HW_FTM_PWMLOAD_ADDR(x), BP_FTM_PWMLOAD_CH1SEL) = (v)) /*@}*/ /*! * @name Register FTM_PWMLOAD, field CH2SEL[2] (RW) * * Values: * - 0 - Do not include the channel in the matching process. * - 1 - Include the channel in the matching process. */ /*@{*/ #define BP_FTM_PWMLOAD_CH2SEL (2U) /*!< Bit position for FTM_PWMLOAD_CH2SEL. */ #define BM_FTM_PWMLOAD_CH2SEL (0x00000004U) /*!< Bit mask for FTM_PWMLOAD_CH2SEL. */ #define BS_FTM_PWMLOAD_CH2SEL (1U) /*!< Bit field size in bits for FTM_PWMLOAD_CH2SEL. */ /*! @brief Read current value of the FTM_PWMLOAD_CH2SEL field. */ #define BR_FTM_PWMLOAD_CH2SEL(x) (BITBAND_ACCESS32(HW_FTM_PWMLOAD_ADDR(x), BP_FTM_PWMLOAD_CH2SEL)) /*! @brief Format value for bitfield FTM_PWMLOAD_CH2SEL. */ #define BF_FTM_PWMLOAD_CH2SEL(v) ((uint32_t)((uint32_t)(v) << BP_FTM_PWMLOAD_CH2SEL) & BM_FTM_PWMLOAD_CH2SEL) /*! @brief Set the CH2SEL field to a new value. */ #define BW_FTM_PWMLOAD_CH2SEL(x, v) (BITBAND_ACCESS32(HW_FTM_PWMLOAD_ADDR(x), BP_FTM_PWMLOAD_CH2SEL) = (v)) /*@}*/ /*! * @name Register FTM_PWMLOAD, field CH3SEL[3] (RW) * * Values: * - 0 - Do not include the channel in the matching process. * - 1 - Include the channel in the matching process. */ /*@{*/ #define BP_FTM_PWMLOAD_CH3SEL (3U) /*!< Bit position for FTM_PWMLOAD_CH3SEL. */ #define BM_FTM_PWMLOAD_CH3SEL (0x00000008U) /*!< Bit mask for FTM_PWMLOAD_CH3SEL. */ #define BS_FTM_PWMLOAD_CH3SEL (1U) /*!< Bit field size in bits for FTM_PWMLOAD_CH3SEL. */ /*! @brief Read current value of the FTM_PWMLOAD_CH3SEL field. */ #define BR_FTM_PWMLOAD_CH3SEL(x) (BITBAND_ACCESS32(HW_FTM_PWMLOAD_ADDR(x), BP_FTM_PWMLOAD_CH3SEL)) /*! @brief Format value for bitfield FTM_PWMLOAD_CH3SEL. */ #define BF_FTM_PWMLOAD_CH3SEL(v) ((uint32_t)((uint32_t)(v) << BP_FTM_PWMLOAD_CH3SEL) & BM_FTM_PWMLOAD_CH3SEL) /*! @brief Set the CH3SEL field to a new value. */ #define BW_FTM_PWMLOAD_CH3SEL(x, v) (BITBAND_ACCESS32(HW_FTM_PWMLOAD_ADDR(x), BP_FTM_PWMLOAD_CH3SEL) = (v)) /*@}*/ /*! * @name Register FTM_PWMLOAD, field CH4SEL[4] (RW) * * Values: * - 0 - Do not include the channel in the matching process. * - 1 - Include the channel in the matching process. */ /*@{*/ #define BP_FTM_PWMLOAD_CH4SEL (4U) /*!< Bit position for FTM_PWMLOAD_CH4SEL. */ #define BM_FTM_PWMLOAD_CH4SEL (0x00000010U) /*!< Bit mask for FTM_PWMLOAD_CH4SEL. */ #define BS_FTM_PWMLOAD_CH4SEL (1U) /*!< Bit field size in bits for FTM_PWMLOAD_CH4SEL. */ /*! @brief Read current value of the FTM_PWMLOAD_CH4SEL field. */ #define BR_FTM_PWMLOAD_CH4SEL(x) (BITBAND_ACCESS32(HW_FTM_PWMLOAD_ADDR(x), BP_FTM_PWMLOAD_CH4SEL)) /*! @brief Format value for bitfield FTM_PWMLOAD_CH4SEL. */ #define BF_FTM_PWMLOAD_CH4SEL(v) ((uint32_t)((uint32_t)(v) << BP_FTM_PWMLOAD_CH4SEL) & BM_FTM_PWMLOAD_CH4SEL) /*! @brief Set the CH4SEL field to a new value. */ #define BW_FTM_PWMLOAD_CH4SEL(x, v) (BITBAND_ACCESS32(HW_FTM_PWMLOAD_ADDR(x), BP_FTM_PWMLOAD_CH4SEL) = (v)) /*@}*/ /*! * @name Register FTM_PWMLOAD, field CH5SEL[5] (RW) * * Values: * - 0 - Do not include the channel in the matching process. * - 1 - Include the channel in the matching process. */ /*@{*/ #define BP_FTM_PWMLOAD_CH5SEL (5U) /*!< Bit position for FTM_PWMLOAD_CH5SEL. */ #define BM_FTM_PWMLOAD_CH5SEL (0x00000020U) /*!< Bit mask for FTM_PWMLOAD_CH5SEL. */ #define BS_FTM_PWMLOAD_CH5SEL (1U) /*!< Bit field size in bits for FTM_PWMLOAD_CH5SEL. */ /*! @brief Read current value of the FTM_PWMLOAD_CH5SEL field. */ #define BR_FTM_PWMLOAD_CH5SEL(x) (BITBAND_ACCESS32(HW_FTM_PWMLOAD_ADDR(x), BP_FTM_PWMLOAD_CH5SEL)) /*! @brief Format value for bitfield FTM_PWMLOAD_CH5SEL. */ #define BF_FTM_PWMLOAD_CH5SEL(v) ((uint32_t)((uint32_t)(v) << BP_FTM_PWMLOAD_CH5SEL) & BM_FTM_PWMLOAD_CH5SEL) /*! @brief Set the CH5SEL field to a new value. */ #define BW_FTM_PWMLOAD_CH5SEL(x, v) (BITBAND_ACCESS32(HW_FTM_PWMLOAD_ADDR(x), BP_FTM_PWMLOAD_CH5SEL) = (v)) /*@}*/ /*! * @name Register FTM_PWMLOAD, field CH6SEL[6] (RW) * * Values: * - 0 - Do not include the channel in the matching process. * - 1 - Include the channel in the matching process. */ /*@{*/ #define BP_FTM_PWMLOAD_CH6SEL (6U) /*!< Bit position for FTM_PWMLOAD_CH6SEL. */ #define BM_FTM_PWMLOAD_CH6SEL (0x00000040U) /*!< Bit mask for FTM_PWMLOAD_CH6SEL. */ #define BS_FTM_PWMLOAD_CH6SEL (1U) /*!< Bit field size in bits for FTM_PWMLOAD_CH6SEL. */ /*! @brief Read current value of the FTM_PWMLOAD_CH6SEL field. */ #define BR_FTM_PWMLOAD_CH6SEL(x) (BITBAND_ACCESS32(HW_FTM_PWMLOAD_ADDR(x), BP_FTM_PWMLOAD_CH6SEL)) /*! @brief Format value for bitfield FTM_PWMLOAD_CH6SEL. */ #define BF_FTM_PWMLOAD_CH6SEL(v) ((uint32_t)((uint32_t)(v) << BP_FTM_PWMLOAD_CH6SEL) & BM_FTM_PWMLOAD_CH6SEL) /*! @brief Set the CH6SEL field to a new value. */ #define BW_FTM_PWMLOAD_CH6SEL(x, v) (BITBAND_ACCESS32(HW_FTM_PWMLOAD_ADDR(x), BP_FTM_PWMLOAD_CH6SEL) = (v)) /*@}*/ /*! * @name Register FTM_PWMLOAD, field CH7SEL[7] (RW) * * Values: * - 0 - Do not include the channel in the matching process. * - 1 - Include the channel in the matching process. */ /*@{*/ #define BP_FTM_PWMLOAD_CH7SEL (7U) /*!< Bit position for FTM_PWMLOAD_CH7SEL. */ #define BM_FTM_PWMLOAD_CH7SEL (0x00000080U) /*!< Bit mask for FTM_PWMLOAD_CH7SEL. */ #define BS_FTM_PWMLOAD_CH7SEL (1U) /*!< Bit field size in bits for FTM_PWMLOAD_CH7SEL. */ /*! @brief Read current value of the FTM_PWMLOAD_CH7SEL field. */ #define BR_FTM_PWMLOAD_CH7SEL(x) (BITBAND_ACCESS32(HW_FTM_PWMLOAD_ADDR(x), BP_FTM_PWMLOAD_CH7SEL)) /*! @brief Format value for bitfield FTM_PWMLOAD_CH7SEL. */ #define BF_FTM_PWMLOAD_CH7SEL(v) ((uint32_t)((uint32_t)(v) << BP_FTM_PWMLOAD_CH7SEL) & BM_FTM_PWMLOAD_CH7SEL) /*! @brief Set the CH7SEL field to a new value. */ #define BW_FTM_PWMLOAD_CH7SEL(x, v) (BITBAND_ACCESS32(HW_FTM_PWMLOAD_ADDR(x), BP_FTM_PWMLOAD_CH7SEL) = (v)) /*@}*/ /*! * @name Register FTM_PWMLOAD, field LDOK[9] (RW) * * Enables the loading of the MOD, CNTIN, and CV registers with the values of * their write buffers. * * Values: * - 0 - Loading updated values is disabled. * - 1 - Loading updated values is enabled. */ /*@{*/ #define BP_FTM_PWMLOAD_LDOK (9U) /*!< Bit position for FTM_PWMLOAD_LDOK. */ #define BM_FTM_PWMLOAD_LDOK (0x00000200U) /*!< Bit mask for FTM_PWMLOAD_LDOK. */ #define BS_FTM_PWMLOAD_LDOK (1U) /*!< Bit field size in bits for FTM_PWMLOAD_LDOK. */ /*! @brief Read current value of the FTM_PWMLOAD_LDOK field. */ #define BR_FTM_PWMLOAD_LDOK(x) (BITBAND_ACCESS32(HW_FTM_PWMLOAD_ADDR(x), BP_FTM_PWMLOAD_LDOK)) /*! @brief Format value for bitfield FTM_PWMLOAD_LDOK. */ #define BF_FTM_PWMLOAD_LDOK(v) ((uint32_t)((uint32_t)(v) << BP_FTM_PWMLOAD_LDOK) & BM_FTM_PWMLOAD_LDOK) /*! @brief Set the LDOK field to a new value. */ #define BW_FTM_PWMLOAD_LDOK(x, v) (BITBAND_ACCESS32(HW_FTM_PWMLOAD_ADDR(x), BP_FTM_PWMLOAD_LDOK) = (v)) /*@}*/ /******************************************************************************* * hw_ftm_t - module struct ******************************************************************************/ /*! * @brief All FTM module registers. */ #pragma pack(1) typedef struct _hw_ftm { __IO hw_ftm_sc_t SC; /*!< [0x0] Status And Control */ __IO hw_ftm_cnt_t CNT; /*!< [0x4] Counter */ __IO hw_ftm_mod_t MOD; /*!< [0x8] Modulo */ struct { __IO hw_ftm_cnsc_t CnSC; /*!< [0xC] Channel (n) Status And Control */ __IO hw_ftm_cnv_t CnV; /*!< [0x10] Channel (n) Value */ } CONTROLS[8]; __IO hw_ftm_cntin_t CNTIN; /*!< [0x4C] Counter Initial Value */ __IO hw_ftm_status_t STATUS; /*!< [0x50] Capture And Compare Status */ __IO hw_ftm_mode_t MODE; /*!< [0x54] Features Mode Selection */ __IO hw_ftm_sync_t SYNC; /*!< [0x58] Synchronization */ __IO hw_ftm_outinit_t OUTINIT; /*!< [0x5C] Initial State For Channels Output */ __IO hw_ftm_outmask_t OUTMASK; /*!< [0x60] Output Mask */ __IO hw_ftm_combine_t COMBINE; /*!< [0x64] Function For Linked Channels */ __IO hw_ftm_deadtime_t DEADTIME; /*!< [0x68] Deadtime Insertion Control */ __IO hw_ftm_exttrig_t EXTTRIG; /*!< [0x6C] FTM External Trigger */ __IO hw_ftm_pol_t POL; /*!< [0x70] Channels Polarity */ __IO hw_ftm_fms_t FMS; /*!< [0x74] Fault Mode Status */ __IO hw_ftm_filter_t FILTER; /*!< [0x78] Input Capture Filter Control */ __IO hw_ftm_fltctrl_t FLTCTRL; /*!< [0x7C] Fault Control */ __IO hw_ftm_qdctrl_t QDCTRL; /*!< [0x80] Quadrature Decoder Control And Status */ __IO hw_ftm_conf_t CONF; /*!< [0x84] Configuration */ __IO hw_ftm_fltpol_t FLTPOL; /*!< [0x88] FTM Fault Input Polarity */ __IO hw_ftm_synconf_t SYNCONF; /*!< [0x8C] Synchronization Configuration */ __IO hw_ftm_invctrl_t INVCTRL; /*!< [0x90] FTM Inverting Control */ __IO hw_ftm_swoctrl_t SWOCTRL; /*!< [0x94] FTM Software Output Control */ __IO hw_ftm_pwmload_t PWMLOAD; /*!< [0x98] FTM PWM Load */ } hw_ftm_t; #pragma pack() /*! @brief Macro to access all FTM registers. */ /*! @param x FTM module instance base address. */ /*! @return Reference (not a pointer) to the registers struct. To get a pointer to the struct, * use the '&' operator, like &HW_FTM(FTM0_BASE). */ #define HW_FTM(x) (*(hw_ftm_t *)(x)) #endif /* __HW_FTM_REGISTERS_H__ */ /* EOF */ ================================================ FILE: Zelig/mbed/TARGET_K64F/TARGET_Freescale/TARGET_KPSDK_MCUS/TARGET_MCU_K64F/device/device/MK64F12/MK64F12_gpio.h ================================================ /* ** ################################################################### ** Compilers: Keil ARM C/C++ Compiler ** Freescale C/C++ for Embedded ARM ** GNU C Compiler ** IAR ANSI C/C++ Compiler for ARM ** ** Reference manual: K64P144M120SF5RM, Rev.2, January 2014 ** Version: rev. 2.5, 2014-02-10 ** Build: b140604 ** ** Abstract: ** Extension to the CMSIS register access layer header. ** ** Copyright (c) 2014 Freescale Semiconductor, Inc. ** All rights reserved. ** ** Redistribution and use in source and binary forms, with or without modification, ** are permitted provided that the following conditions are met: ** ** o Redistributions of source code must retain the above copyright notice, this list ** of conditions and the following disclaimer. ** ** o Redistributions in binary form must reproduce the above copyright notice, this ** list of conditions and the following disclaimer in the documentation and/or ** other materials provided with the distribution. ** ** o Neither the name of Freescale Semiconductor, Inc. nor the names of its ** contributors may be used to endorse or promote products derived from this ** software without specific prior written permission. ** ** THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ** ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED ** WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE ** DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT 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. ** ** http: www.freescale.com ** mail: support@freescale.com ** ** Revisions: ** - rev. 1.0 (2013-08-12) ** Initial version. ** - rev. 2.0 (2013-10-29) ** Register accessor macros added to the memory map. ** Symbols for Processor Expert memory map compatibility added to the memory map. ** Startup file for gcc has been updated according to CMSIS 3.2. ** System initialization updated. ** MCG - registers updated. ** PORTA, PORTB, PORTC, PORTE - registers for digital filter removed. ** - rev. 2.1 (2013-10-30) ** Definition of BITBAND macros updated to support peripherals with 32-bit acces disabled. ** - rev. 2.2 (2013-12-09) ** DMA - EARS register removed. ** AIPS0, AIPS1 - MPRA register updated. ** - rev. 2.3 (2014-01-24) ** Update according to reference manual rev. 2 ** ENET, MCG, MCM, SIM, USB - registers updated ** - rev. 2.4 (2014-02-10) ** The declaration of clock configurations has been moved to separate header file system_MK64F12.h ** Update of SystemInit() and SystemCoreClockUpdate() functions. ** - rev. 2.5 (2014-02-10) ** The declaration of clock configurations has been moved to separate header file system_MK64F12.h ** Update of SystemInit() and SystemCoreClockUpdate() functions. ** Module access macro module_BASES replaced by module_BASE_PTRS. ** ** ################################################################### */ /* * WARNING! DO NOT EDIT THIS FILE DIRECTLY! * * This file was generated automatically and any changes may be lost. */ #ifndef __HW_GPIO_REGISTERS_H__ #define __HW_GPIO_REGISTERS_H__ #include "MK64F12.h" #include "fsl_bitaccess.h" /* * MK64F12 GPIO * * General Purpose Input/Output * * Registers defined in this header file: * - HW_GPIO_PDOR - Port Data Output Register * - HW_GPIO_PSOR - Port Set Output Register * - HW_GPIO_PCOR - Port Clear Output Register * - HW_GPIO_PTOR - Port Toggle Output Register * - HW_GPIO_PDIR - Port Data Input Register * - HW_GPIO_PDDR - Port Data Direction Register * * - hw_gpio_t - Struct containing all module registers. */ #define HW_GPIO_INSTANCE_COUNT (5U) /*!< Number of instances of the GPIO module. */ #define HW_GPIOA (0U) /*!< Instance number for GPIOA. */ #define HW_GPIOB (1U) /*!< Instance number for GPIOB. */ #define HW_GPIOC (2U) /*!< Instance number for GPIOC. */ #define HW_GPIOD (3U) /*!< Instance number for GPIOD. */ #define HW_GPIOE (4U) /*!< Instance number for GPIOE. */ /******************************************************************************* * HW_GPIO_PDOR - Port Data Output Register ******************************************************************************/ /*! * @brief HW_GPIO_PDOR - Port Data Output Register (RW) * * Reset value: 0x00000000U * * This register configures the logic levels that are driven on each * general-purpose output pins. Do not modify pin configuration registers associated with * pins not available in your selected package. All unbonded pins not available in * your package will default to DISABLE state for lowest power consumption. */ typedef union _hw_gpio_pdor { uint32_t U; struct _hw_gpio_pdor_bitfields { uint32_t PDO : 32; /*!< [31:0] Port Data Output */ } B; } hw_gpio_pdor_t; /*! * @name Constants and macros for entire GPIO_PDOR register */ /*@{*/ #define HW_GPIO_PDOR_ADDR(x) ((x) + 0x0U) #define HW_GPIO_PDOR(x) (*(__IO hw_gpio_pdor_t *) HW_GPIO_PDOR_ADDR(x)) #define HW_GPIO_PDOR_RD(x) (HW_GPIO_PDOR(x).U) #define HW_GPIO_PDOR_WR(x, v) (HW_GPIO_PDOR(x).U = (v)) #define HW_GPIO_PDOR_SET(x, v) (HW_GPIO_PDOR_WR(x, HW_GPIO_PDOR_RD(x) | (v))) #define HW_GPIO_PDOR_CLR(x, v) (HW_GPIO_PDOR_WR(x, HW_GPIO_PDOR_RD(x) & ~(v))) #define HW_GPIO_PDOR_TOG(x, v) (HW_GPIO_PDOR_WR(x, HW_GPIO_PDOR_RD(x) ^ (v))) /*@}*/ /* * Constants & macros for individual GPIO_PDOR bitfields */ /*! * @name Register GPIO_PDOR, field PDO[31:0] (RW) * * Register bits for unbonded pins return a undefined value when read. * * Values: * - 0 - Logic level 0 is driven on pin, provided pin is configured for * general-purpose output. * - 1 - Logic level 1 is driven on pin, provided pin is configured for * general-purpose output. */ /*@{*/ #define BP_GPIO_PDOR_PDO (0U) /*!< Bit position for GPIO_PDOR_PDO. */ #define BM_GPIO_PDOR_PDO (0xFFFFFFFFU) /*!< Bit mask for GPIO_PDOR_PDO. */ #define BS_GPIO_PDOR_PDO (32U) /*!< Bit field size in bits for GPIO_PDOR_PDO. */ /*! @brief Read current value of the GPIO_PDOR_PDO field. */ #define BR_GPIO_PDOR_PDO(x) (HW_GPIO_PDOR(x).U) /*! @brief Format value for bitfield GPIO_PDOR_PDO. */ #define BF_GPIO_PDOR_PDO(v) ((uint32_t)((uint32_t)(v) << BP_GPIO_PDOR_PDO) & BM_GPIO_PDOR_PDO) /*! @brief Set the PDO field to a new value. */ #define BW_GPIO_PDOR_PDO(x, v) (HW_GPIO_PDOR_WR(x, v)) /*@}*/ /******************************************************************************* * HW_GPIO_PSOR - Port Set Output Register ******************************************************************************/ /*! * @brief HW_GPIO_PSOR - Port Set Output Register (WORZ) * * Reset value: 0x00000000U * * This register configures whether to set the fields of the PDOR. */ typedef union _hw_gpio_psor { uint32_t U; struct _hw_gpio_psor_bitfields { uint32_t PTSO : 32; /*!< [31:0] Port Set Output */ } B; } hw_gpio_psor_t; /*! * @name Constants and macros for entire GPIO_PSOR register */ /*@{*/ #define HW_GPIO_PSOR_ADDR(x) ((x) + 0x4U) #define HW_GPIO_PSOR(x) (*(__O hw_gpio_psor_t *) HW_GPIO_PSOR_ADDR(x)) #define HW_GPIO_PSOR_RD(x) (HW_GPIO_PSOR(x).U) #define HW_GPIO_PSOR_WR(x, v) (HW_GPIO_PSOR(x).U = (v)) /*@}*/ /* * Constants & macros for individual GPIO_PSOR bitfields */ /*! * @name Register GPIO_PSOR, field PTSO[31:0] (WORZ) * * Writing to this register will update the contents of the corresponding bit in * the PDOR as follows: * * Values: * - 0 - Corresponding bit in PDORn does not change. * - 1 - Corresponding bit in PDORn is set to logic 1. */ /*@{*/ #define BP_GPIO_PSOR_PTSO (0U) /*!< Bit position for GPIO_PSOR_PTSO. */ #define BM_GPIO_PSOR_PTSO (0xFFFFFFFFU) /*!< Bit mask for GPIO_PSOR_PTSO. */ #define BS_GPIO_PSOR_PTSO (32U) /*!< Bit field size in bits for GPIO_PSOR_PTSO. */ /*! @brief Format value for bitfield GPIO_PSOR_PTSO. */ #define BF_GPIO_PSOR_PTSO(v) ((uint32_t)((uint32_t)(v) << BP_GPIO_PSOR_PTSO) & BM_GPIO_PSOR_PTSO) /*! @brief Set the PTSO field to a new value. */ #define BW_GPIO_PSOR_PTSO(x, v) (HW_GPIO_PSOR_WR(x, v)) /*@}*/ /******************************************************************************* * HW_GPIO_PCOR - Port Clear Output Register ******************************************************************************/ /*! * @brief HW_GPIO_PCOR - Port Clear Output Register (WORZ) * * Reset value: 0x00000000U * * This register configures whether to clear the fields of PDOR. */ typedef union _hw_gpio_pcor { uint32_t U; struct _hw_gpio_pcor_bitfields { uint32_t PTCO : 32; /*!< [31:0] Port Clear Output */ } B; } hw_gpio_pcor_t; /*! * @name Constants and macros for entire GPIO_PCOR register */ /*@{*/ #define HW_GPIO_PCOR_ADDR(x) ((x) + 0x8U) #define HW_GPIO_PCOR(x) (*(__O hw_gpio_pcor_t *) HW_GPIO_PCOR_ADDR(x)) #define HW_GPIO_PCOR_RD(x) (HW_GPIO_PCOR(x).U) #define HW_GPIO_PCOR_WR(x, v) (HW_GPIO_PCOR(x).U = (v)) /*@}*/ /* * Constants & macros for individual GPIO_PCOR bitfields */ /*! * @name Register GPIO_PCOR, field PTCO[31:0] (WORZ) * * Writing to this register will update the contents of the corresponding bit in * the Port Data Output Register (PDOR) as follows: * * Values: * - 0 - Corresponding bit in PDORn does not change. * - 1 - Corresponding bit in PDORn is cleared to logic 0. */ /*@{*/ #define BP_GPIO_PCOR_PTCO (0U) /*!< Bit position for GPIO_PCOR_PTCO. */ #define BM_GPIO_PCOR_PTCO (0xFFFFFFFFU) /*!< Bit mask for GPIO_PCOR_PTCO. */ #define BS_GPIO_PCOR_PTCO (32U) /*!< Bit field size in bits for GPIO_PCOR_PTCO. */ /*! @brief Format value for bitfield GPIO_PCOR_PTCO. */ #define BF_GPIO_PCOR_PTCO(v) ((uint32_t)((uint32_t)(v) << BP_GPIO_PCOR_PTCO) & BM_GPIO_PCOR_PTCO) /*! @brief Set the PTCO field to a new value. */ #define BW_GPIO_PCOR_PTCO(x, v) (HW_GPIO_PCOR_WR(x, v)) /*@}*/ /******************************************************************************* * HW_GPIO_PTOR - Port Toggle Output Register ******************************************************************************/ /*! * @brief HW_GPIO_PTOR - Port Toggle Output Register (WORZ) * * Reset value: 0x00000000U */ typedef union _hw_gpio_ptor { uint32_t U; struct _hw_gpio_ptor_bitfields { uint32_t PTTO : 32; /*!< [31:0] Port Toggle Output */ } B; } hw_gpio_ptor_t; /*! * @name Constants and macros for entire GPIO_PTOR register */ /*@{*/ #define HW_GPIO_PTOR_ADDR(x) ((x) + 0xCU) #define HW_GPIO_PTOR(x) (*(__O hw_gpio_ptor_t *) HW_GPIO_PTOR_ADDR(x)) #define HW_GPIO_PTOR_RD(x) (HW_GPIO_PTOR(x).U) #define HW_GPIO_PTOR_WR(x, v) (HW_GPIO_PTOR(x).U = (v)) /*@}*/ /* * Constants & macros for individual GPIO_PTOR bitfields */ /*! * @name Register GPIO_PTOR, field PTTO[31:0] (WORZ) * * Writing to this register will update the contents of the corresponding bit in * the PDOR as follows: * * Values: * - 0 - Corresponding bit in PDORn does not change. * - 1 - Corresponding bit in PDORn is set to the inverse of its existing logic * state. */ /*@{*/ #define BP_GPIO_PTOR_PTTO (0U) /*!< Bit position for GPIO_PTOR_PTTO. */ #define BM_GPIO_PTOR_PTTO (0xFFFFFFFFU) /*!< Bit mask for GPIO_PTOR_PTTO. */ #define BS_GPIO_PTOR_PTTO (32U) /*!< Bit field size in bits for GPIO_PTOR_PTTO. */ /*! @brief Format value for bitfield GPIO_PTOR_PTTO. */ #define BF_GPIO_PTOR_PTTO(v) ((uint32_t)((uint32_t)(v) << BP_GPIO_PTOR_PTTO) & BM_GPIO_PTOR_PTTO) /*! @brief Set the PTTO field to a new value. */ #define BW_GPIO_PTOR_PTTO(x, v) (HW_GPIO_PTOR_WR(x, v)) /*@}*/ /******************************************************************************* * HW_GPIO_PDIR - Port Data Input Register ******************************************************************************/ /*! * @brief HW_GPIO_PDIR - Port Data Input Register (RO) * * Reset value: 0x00000000U * * Do not modify pin configuration registers associated with pins not available * in your selected package. All unbonded pins not available in your package will * default to DISABLE state for lowest power consumption. */ typedef union _hw_gpio_pdir { uint32_t U; struct _hw_gpio_pdir_bitfields { uint32_t PDI : 32; /*!< [31:0] Port Data Input */ } B; } hw_gpio_pdir_t; /*! * @name Constants and macros for entire GPIO_PDIR register */ /*@{*/ #define HW_GPIO_PDIR_ADDR(x) ((x) + 0x10U) #define HW_GPIO_PDIR(x) (*(__I hw_gpio_pdir_t *) HW_GPIO_PDIR_ADDR(x)) #define HW_GPIO_PDIR_RD(x) (HW_GPIO_PDIR(x).U) /*@}*/ /* * Constants & macros for individual GPIO_PDIR bitfields */ /*! * @name Register GPIO_PDIR, field PDI[31:0] (RO) * * Reads 0 at the unimplemented pins for a particular device. Pins that are not * configured for a digital function read 0. If the Port Control and Interrupt * module is disabled, then the corresponding bit in PDIR does not update. * * Values: * - 0 - Pin logic level is logic 0, or is not configured for use by digital * function. * - 1 - Pin logic level is logic 1. */ /*@{*/ #define BP_GPIO_PDIR_PDI (0U) /*!< Bit position for GPIO_PDIR_PDI. */ #define BM_GPIO_PDIR_PDI (0xFFFFFFFFU) /*!< Bit mask for GPIO_PDIR_PDI. */ #define BS_GPIO_PDIR_PDI (32U) /*!< Bit field size in bits for GPIO_PDIR_PDI. */ /*! @brief Read current value of the GPIO_PDIR_PDI field. */ #define BR_GPIO_PDIR_PDI(x) (HW_GPIO_PDIR(x).U) /*@}*/ /******************************************************************************* * HW_GPIO_PDDR - Port Data Direction Register ******************************************************************************/ /*! * @brief HW_GPIO_PDDR - Port Data Direction Register (RW) * * Reset value: 0x00000000U * * The PDDR configures the individual port pins for input or output. */ typedef union _hw_gpio_pddr { uint32_t U; struct _hw_gpio_pddr_bitfields { uint32_t PDD : 32; /*!< [31:0] Port Data Direction */ } B; } hw_gpio_pddr_t; /*! * @name Constants and macros for entire GPIO_PDDR register */ /*@{*/ #define HW_GPIO_PDDR_ADDR(x) ((x) + 0x14U) #define HW_GPIO_PDDR(x) (*(__IO hw_gpio_pddr_t *) HW_GPIO_PDDR_ADDR(x)) #define HW_GPIO_PDDR_RD(x) (HW_GPIO_PDDR(x).U) #define HW_GPIO_PDDR_WR(x, v) (HW_GPIO_PDDR(x).U = (v)) #define HW_GPIO_PDDR_SET(x, v) (HW_GPIO_PDDR_WR(x, HW_GPIO_PDDR_RD(x) | (v))) #define HW_GPIO_PDDR_CLR(x, v) (HW_GPIO_PDDR_WR(x, HW_GPIO_PDDR_RD(x) & ~(v))) #define HW_GPIO_PDDR_TOG(x, v) (HW_GPIO_PDDR_WR(x, HW_GPIO_PDDR_RD(x) ^ (v))) /*@}*/ /* * Constants & macros for individual GPIO_PDDR bitfields */ /*! * @name Register GPIO_PDDR, field PDD[31:0] (RW) * * Configures individual port pins for input or output. * * Values: * - 0 - Pin is configured as general-purpose input, for the GPIO function. * - 1 - Pin is configured as general-purpose output, for the GPIO function. */ /*@{*/ #define BP_GPIO_PDDR_PDD (0U) /*!< Bit position for GPIO_PDDR_PDD. */ #define BM_GPIO_PDDR_PDD (0xFFFFFFFFU) /*!< Bit mask for GPIO_PDDR_PDD. */ #define BS_GPIO_PDDR_PDD (32U) /*!< Bit field size in bits for GPIO_PDDR_PDD. */ /*! @brief Read current value of the GPIO_PDDR_PDD field. */ #define BR_GPIO_PDDR_PDD(x) (HW_GPIO_PDDR(x).U) /*! @brief Format value for bitfield GPIO_PDDR_PDD. */ #define BF_GPIO_PDDR_PDD(v) ((uint32_t)((uint32_t)(v) << BP_GPIO_PDDR_PDD) & BM_GPIO_PDDR_PDD) /*! @brief Set the PDD field to a new value. */ #define BW_GPIO_PDDR_PDD(x, v) (HW_GPIO_PDDR_WR(x, v)) /*@}*/ /******************************************************************************* * hw_gpio_t - module struct ******************************************************************************/ /*! * @brief All GPIO module registers. */ #pragma pack(1) typedef struct _hw_gpio { __IO hw_gpio_pdor_t PDOR; /*!< [0x0] Port Data Output Register */ __O hw_gpio_psor_t PSOR; /*!< [0x4] Port Set Output Register */ __O hw_gpio_pcor_t PCOR; /*!< [0x8] Port Clear Output Register */ __O hw_gpio_ptor_t PTOR; /*!< [0xC] Port Toggle Output Register */ __I hw_gpio_pdir_t PDIR; /*!< [0x10] Port Data Input Register */ __IO hw_gpio_pddr_t PDDR; /*!< [0x14] Port Data Direction Register */ } hw_gpio_t; #pragma pack() /*! @brief Macro to access all GPIO registers. */ /*! @param x GPIO module instance base address. */ /*! @return Reference (not a pointer) to the registers struct. To get a pointer to the struct, * use the '&' operator, like &HW_GPIO(GPIOA_BASE). */ #define HW_GPIO(x) (*(hw_gpio_t *)(x)) #endif /* __HW_GPIO_REGISTERS_H__ */ /* EOF */ ================================================ FILE: Zelig/mbed/TARGET_K64F/TARGET_Freescale/TARGET_KPSDK_MCUS/TARGET_MCU_K64F/device/device/MK64F12/MK64F12_i2c.h ================================================ /* ** ################################################################### ** Compilers: Keil ARM C/C++ Compiler ** Freescale C/C++ for Embedded ARM ** GNU C Compiler ** IAR ANSI C/C++ Compiler for ARM ** ** Reference manual: K64P144M120SF5RM, Rev.2, January 2014 ** Version: rev. 2.5, 2014-02-10 ** Build: b140604 ** ** Abstract: ** Extension to the CMSIS register access layer header. ** ** Copyright (c) 2014 Freescale Semiconductor, Inc. ** All rights reserved. ** ** Redistribution and use in source and binary forms, with or without modification, ** are permitted provided that the following conditions are met: ** ** o Redistributions of source code must retain the above copyright notice, this list ** of conditions and the following disclaimer. ** ** o Redistributions in binary form must reproduce the above copyright notice, this ** list of conditions and the following disclaimer in the documentation and/or ** other materials provided with the distribution. ** ** o Neither the name of Freescale Semiconductor, Inc. nor the names of its ** contributors may be used to endorse or promote products derived from this ** software without specific prior written permission. ** ** THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ** ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED ** WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE ** DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT 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. ** ** http: www.freescale.com ** mail: support@freescale.com ** ** Revisions: ** - rev. 1.0 (2013-08-12) ** Initial version. ** - rev. 2.0 (2013-10-29) ** Register accessor macros added to the memory map. ** Symbols for Processor Expert memory map compatibility added to the memory map. ** Startup file for gcc has been updated according to CMSIS 3.2. ** System initialization updated. ** MCG - registers updated. ** PORTA, PORTB, PORTC, PORTE - registers for digital filter removed. ** - rev. 2.1 (2013-10-30) ** Definition of BITBAND macros updated to support peripherals with 32-bit acces disabled. ** - rev. 2.2 (2013-12-09) ** DMA - EARS register removed. ** AIPS0, AIPS1 - MPRA register updated. ** - rev. 2.3 (2014-01-24) ** Update according to reference manual rev. 2 ** ENET, MCG, MCM, SIM, USB - registers updated ** - rev. 2.4 (2014-02-10) ** The declaration of clock configurations has been moved to separate header file system_MK64F12.h ** Update of SystemInit() and SystemCoreClockUpdate() functions. ** - rev. 2.5 (2014-02-10) ** The declaration of clock configurations has been moved to separate header file system_MK64F12.h ** Update of SystemInit() and SystemCoreClockUpdate() functions. ** Module access macro module_BASES replaced by module_BASE_PTRS. ** ** ################################################################### */ /* * WARNING! DO NOT EDIT THIS FILE DIRECTLY! * * This file was generated automatically and any changes may be lost. */ #ifndef __HW_I2C_REGISTERS_H__ #define __HW_I2C_REGISTERS_H__ #include "MK64F12.h" #include "fsl_bitaccess.h" /* * MK64F12 I2C * * Inter-Integrated Circuit * * Registers defined in this header file: * - HW_I2C_A1 - I2C Address Register 1 * - HW_I2C_F - I2C Frequency Divider register * - HW_I2C_C1 - I2C Control Register 1 * - HW_I2C_S - I2C Status register * - HW_I2C_D - I2C Data I/O register * - HW_I2C_C2 - I2C Control Register 2 * - HW_I2C_FLT - I2C Programmable Input Glitch Filter register * - HW_I2C_RA - I2C Range Address register * - HW_I2C_SMB - I2C SMBus Control and Status register * - HW_I2C_A2 - I2C Address Register 2 * - HW_I2C_SLTH - I2C SCL Low Timeout Register High * - HW_I2C_SLTL - I2C SCL Low Timeout Register Low * * - hw_i2c_t - Struct containing all module registers. */ #define HW_I2C_INSTANCE_COUNT (3U) /*!< Number of instances of the I2C module. */ #define HW_I2C0 (0U) /*!< Instance number for I2C0. */ #define HW_I2C1 (1U) /*!< Instance number for I2C1. */ #define HW_I2C2 (2U) /*!< Instance number for I2C2. */ /******************************************************************************* * HW_I2C_A1 - I2C Address Register 1 ******************************************************************************/ /*! * @brief HW_I2C_A1 - I2C Address Register 1 (RW) * * Reset value: 0x00U * * This register contains the slave address to be used by the I2C module. */ typedef union _hw_i2c_a1 { uint8_t U; struct _hw_i2c_a1_bitfields { uint8_t RESERVED0 : 1; /*!< [0] */ uint8_t AD : 7; /*!< [7:1] Address */ } B; } hw_i2c_a1_t; /*! * @name Constants and macros for entire I2C_A1 register */ /*@{*/ #define HW_I2C_A1_ADDR(x) ((x) + 0x0U) #define HW_I2C_A1(x) (*(__IO hw_i2c_a1_t *) HW_I2C_A1_ADDR(x)) #define HW_I2C_A1_RD(x) (HW_I2C_A1(x).U) #define HW_I2C_A1_WR(x, v) (HW_I2C_A1(x).U = (v)) #define HW_I2C_A1_SET(x, v) (HW_I2C_A1_WR(x, HW_I2C_A1_RD(x) | (v))) #define HW_I2C_A1_CLR(x, v) (HW_I2C_A1_WR(x, HW_I2C_A1_RD(x) & ~(v))) #define HW_I2C_A1_TOG(x, v) (HW_I2C_A1_WR(x, HW_I2C_A1_RD(x) ^ (v))) /*@}*/ /* * Constants & macros for individual I2C_A1 bitfields */ /*! * @name Register I2C_A1, field AD[7:1] (RW) * * Contains the primary slave address used by the I2C module when it is * addressed as a slave. This field is used in the 7-bit address scheme and the lower * seven bits in the 10-bit address scheme. */ /*@{*/ #define BP_I2C_A1_AD (1U) /*!< Bit position for I2C_A1_AD. */ #define BM_I2C_A1_AD (0xFEU) /*!< Bit mask for I2C_A1_AD. */ #define BS_I2C_A1_AD (7U) /*!< Bit field size in bits for I2C_A1_AD. */ /*! @brief Read current value of the I2C_A1_AD field. */ #define BR_I2C_A1_AD(x) (HW_I2C_A1(x).B.AD) /*! @brief Format value for bitfield I2C_A1_AD. */ #define BF_I2C_A1_AD(v) ((uint8_t)((uint8_t)(v) << BP_I2C_A1_AD) & BM_I2C_A1_AD) /*! @brief Set the AD field to a new value. */ #define BW_I2C_A1_AD(x, v) (HW_I2C_A1_WR(x, (HW_I2C_A1_RD(x) & ~BM_I2C_A1_AD) | BF_I2C_A1_AD(v))) /*@}*/ /******************************************************************************* * HW_I2C_F - I2C Frequency Divider register ******************************************************************************/ /*! * @brief HW_I2C_F - I2C Frequency Divider register (RW) * * Reset value: 0x00U */ typedef union _hw_i2c_f { uint8_t U; struct _hw_i2c_f_bitfields { uint8_t ICR : 6; /*!< [5:0] ClockRate */ uint8_t MULT : 2; /*!< [7:6] Multiplier Factor */ } B; } hw_i2c_f_t; /*! * @name Constants and macros for entire I2C_F register */ /*@{*/ #define HW_I2C_F_ADDR(x) ((x) + 0x1U) #define HW_I2C_F(x) (*(__IO hw_i2c_f_t *) HW_I2C_F_ADDR(x)) #define HW_I2C_F_RD(x) (HW_I2C_F(x).U) #define HW_I2C_F_WR(x, v) (HW_I2C_F(x).U = (v)) #define HW_I2C_F_SET(x, v) (HW_I2C_F_WR(x, HW_I2C_F_RD(x) | (v))) #define HW_I2C_F_CLR(x, v) (HW_I2C_F_WR(x, HW_I2C_F_RD(x) & ~(v))) #define HW_I2C_F_TOG(x, v) (HW_I2C_F_WR(x, HW_I2C_F_RD(x) ^ (v))) /*@}*/ /* * Constants & macros for individual I2C_F bitfields */ /*! * @name Register I2C_F, field ICR[5:0] (RW) * * Prescales the I2C module clock for bit rate selection. This field and the * MULT field determine the I2C baud rate, the SDA hold time, the SCL start hold * time, and the SCL stop hold time. For a list of values corresponding to each ICR * setting, see I2C divider and hold values. The SCL divider multiplied by * multiplier factor (mul) determines the I2C baud rate. I2C baud rate = I2C module * clock speed (Hz)/(mul * SCL divider) The SDA hold time is the delay from the * falling edge of SCL (I2C clock) to the changing of SDA (I2C data). SDA hold time = * I2C module clock period (s) * mul * SDA hold value The SCL start hold time is * the delay from the falling edge of SDA (I2C data) while SCL is high (start * condition) to the falling edge of SCL (I2C clock). SCL start hold time = I2C * module clock period (s) * mul * SCL start hold value The SCL stop hold time is * the delay from the rising edge of SCL (I2C clock) to the rising edge of SDA (I2C * data) while SCL is high (stop condition). SCL stop hold time = I2C module * clock period (s) * mul * SCL stop hold value For example, if the I2C module clock * speed is 8 MHz, the following table shows the possible hold time values with * different ICR and MULT selections to achieve an I2C baud rate of 100 kbit/s. * MULT ICR Hold times (us) SDA SCL Start SCL Stop 2h 00h 3.500 3.000 5.500 1h 07h * 2.500 4.000 5.250 1h 0Bh 2.250 4.000 5.250 0h 14h 2.125 4.250 5.125 0h 18h * 1.125 4.750 5.125 */ /*@{*/ #define BP_I2C_F_ICR (0U) /*!< Bit position for I2C_F_ICR. */ #define BM_I2C_F_ICR (0x3FU) /*!< Bit mask for I2C_F_ICR. */ #define BS_I2C_F_ICR (6U) /*!< Bit field size in bits for I2C_F_ICR. */ /*! @brief Read current value of the I2C_F_ICR field. */ #define BR_I2C_F_ICR(x) (HW_I2C_F(x).B.ICR) /*! @brief Format value for bitfield I2C_F_ICR. */ #define BF_I2C_F_ICR(v) ((uint8_t)((uint8_t)(v) << BP_I2C_F_ICR) & BM_I2C_F_ICR) /*! @brief Set the ICR field to a new value. */ #define BW_I2C_F_ICR(x, v) (HW_I2C_F_WR(x, (HW_I2C_F_RD(x) & ~BM_I2C_F_ICR) | BF_I2C_F_ICR(v))) /*@}*/ /*! * @name Register I2C_F, field MULT[7:6] (RW) * * Defines the multiplier factor (mul). This factor is used along with the SCL * divider to generate the I2C baud rate. * * Values: * - 00 - mul = 1 * - 01 - mul = 2 * - 10 - mul = 4 * - 11 - Reserved */ /*@{*/ #define BP_I2C_F_MULT (6U) /*!< Bit position for I2C_F_MULT. */ #define BM_I2C_F_MULT (0xC0U) /*!< Bit mask for I2C_F_MULT. */ #define BS_I2C_F_MULT (2U) /*!< Bit field size in bits for I2C_F_MULT. */ /*! @brief Read current value of the I2C_F_MULT field. */ #define BR_I2C_F_MULT(x) (HW_I2C_F(x).B.MULT) /*! @brief Format value for bitfield I2C_F_MULT. */ #define BF_I2C_F_MULT(v) ((uint8_t)((uint8_t)(v) << BP_I2C_F_MULT) & BM_I2C_F_MULT) /*! @brief Set the MULT field to a new value. */ #define BW_I2C_F_MULT(x, v) (HW_I2C_F_WR(x, (HW_I2C_F_RD(x) & ~BM_I2C_F_MULT) | BF_I2C_F_MULT(v))) /*@}*/ /******************************************************************************* * HW_I2C_C1 - I2C Control Register 1 ******************************************************************************/ /*! * @brief HW_I2C_C1 - I2C Control Register 1 (RW) * * Reset value: 0x00U */ typedef union _hw_i2c_c1 { uint8_t U; struct _hw_i2c_c1_bitfields { uint8_t DMAEN : 1; /*!< [0] DMA Enable */ uint8_t WUEN : 1; /*!< [1] Wakeup Enable */ uint8_t RSTA : 1; /*!< [2] Repeat START */ uint8_t TXAK : 1; /*!< [3] Transmit Acknowledge Enable */ uint8_t TX : 1; /*!< [4] Transmit Mode Select */ uint8_t MST : 1; /*!< [5] Master Mode Select */ uint8_t IICIE : 1; /*!< [6] I2C Interrupt Enable */ uint8_t IICEN : 1; /*!< [7] I2C Enable */ } B; } hw_i2c_c1_t; /*! * @name Constants and macros for entire I2C_C1 register */ /*@{*/ #define HW_I2C_C1_ADDR(x) ((x) + 0x2U) #define HW_I2C_C1(x) (*(__IO hw_i2c_c1_t *) HW_I2C_C1_ADDR(x)) #define HW_I2C_C1_RD(x) (HW_I2C_C1(x).U) #define HW_I2C_C1_WR(x, v) (HW_I2C_C1(x).U = (v)) #define HW_I2C_C1_SET(x, v) (HW_I2C_C1_WR(x, HW_I2C_C1_RD(x) | (v))) #define HW_I2C_C1_CLR(x, v) (HW_I2C_C1_WR(x, HW_I2C_C1_RD(x) & ~(v))) #define HW_I2C_C1_TOG(x, v) (HW_I2C_C1_WR(x, HW_I2C_C1_RD(x) ^ (v))) /*@}*/ /* * Constants & macros for individual I2C_C1 bitfields */ /*! * @name Register I2C_C1, field DMAEN[0] (RW) * * Enables or disables the DMA function. * * Values: * - 0 - All DMA signalling disabled. * - 1 - DMA transfer is enabled. While SMB[FACK] = 0, the following conditions * trigger the DMA request: a data byte is received, and either address or * data is transmitted. (ACK/NACK is automatic) the first byte received matches * the A1 register or is a general call address. If any address matching * occurs, S[IAAS] and S[TCF] are set. If the direction of transfer is known * from master to slave, then it is not required to check S[SRW]. With this * assumption, DMA can also be used in this case. In other cases, if the master * reads data from the slave, then it is required to rewrite the C1 register * operation. With this assumption, DMA cannot be used. When FACK = 1, an * address or a data byte is transmitted. */ /*@{*/ #define BP_I2C_C1_DMAEN (0U) /*!< Bit position for I2C_C1_DMAEN. */ #define BM_I2C_C1_DMAEN (0x01U) /*!< Bit mask for I2C_C1_DMAEN. */ #define BS_I2C_C1_DMAEN (1U) /*!< Bit field size in bits for I2C_C1_DMAEN. */ /*! @brief Read current value of the I2C_C1_DMAEN field. */ #define BR_I2C_C1_DMAEN(x) (BITBAND_ACCESS8(HW_I2C_C1_ADDR(x), BP_I2C_C1_DMAEN)) /*! @brief Format value for bitfield I2C_C1_DMAEN. */ #define BF_I2C_C1_DMAEN(v) ((uint8_t)((uint8_t)(v) << BP_I2C_C1_DMAEN) & BM_I2C_C1_DMAEN) /*! @brief Set the DMAEN field to a new value. */ #define BW_I2C_C1_DMAEN(x, v) (BITBAND_ACCESS8(HW_I2C_C1_ADDR(x), BP_I2C_C1_DMAEN) = (v)) /*@}*/ /*! * @name Register I2C_C1, field WUEN[1] (RW) * * The I2C module can wake the MCU from low power mode with no peripheral bus * running when slave address matching occurs. * * Values: * - 0 - Normal operation. No interrupt generated when address matching in low * power mode. * - 1 - Enables the wakeup function in low power mode. */ /*@{*/ #define BP_I2C_C1_WUEN (1U) /*!< Bit position for I2C_C1_WUEN. */ #define BM_I2C_C1_WUEN (0x02U) /*!< Bit mask for I2C_C1_WUEN. */ #define BS_I2C_C1_WUEN (1U) /*!< Bit field size in bits for I2C_C1_WUEN. */ /*! @brief Read current value of the I2C_C1_WUEN field. */ #define BR_I2C_C1_WUEN(x) (BITBAND_ACCESS8(HW_I2C_C1_ADDR(x), BP_I2C_C1_WUEN)) /*! @brief Format value for bitfield I2C_C1_WUEN. */ #define BF_I2C_C1_WUEN(v) ((uint8_t)((uint8_t)(v) << BP_I2C_C1_WUEN) & BM_I2C_C1_WUEN) /*! @brief Set the WUEN field to a new value. */ #define BW_I2C_C1_WUEN(x, v) (BITBAND_ACCESS8(HW_I2C_C1_ADDR(x), BP_I2C_C1_WUEN) = (v)) /*@}*/ /*! * @name Register I2C_C1, field RSTA[2] (WORZ) * * Writing 1 to this bit generates a repeated START condition provided it is the * current master. This bit will always be read as 0. Attempting a repeat at the * wrong time results in loss of arbitration. */ /*@{*/ #define BP_I2C_C1_RSTA (2U) /*!< Bit position for I2C_C1_RSTA. */ #define BM_I2C_C1_RSTA (0x04U) /*!< Bit mask for I2C_C1_RSTA. */ #define BS_I2C_C1_RSTA (1U) /*!< Bit field size in bits for I2C_C1_RSTA. */ /*! @brief Format value for bitfield I2C_C1_RSTA. */ #define BF_I2C_C1_RSTA(v) ((uint8_t)((uint8_t)(v) << BP_I2C_C1_RSTA) & BM_I2C_C1_RSTA) /*! @brief Set the RSTA field to a new value. */ #define BW_I2C_C1_RSTA(x, v) (BITBAND_ACCESS8(HW_I2C_C1_ADDR(x), BP_I2C_C1_RSTA) = (v)) /*@}*/ /*! * @name Register I2C_C1, field TXAK[3] (RW) * * Specifies the value driven onto the SDA during data acknowledge cycles for * both master and slave receivers. The value of SMB[FACK] affects NACK/ACK * generation. SCL is held low until TXAK is written. * * Values: * - 0 - An acknowledge signal is sent to the bus on the following receiving * byte (if FACK is cleared) or the current receiving byte (if FACK is set). * - 1 - No acknowledge signal is sent to the bus on the following receiving * data byte (if FACK is cleared) or the current receiving data byte (if FACK is * set). */ /*@{*/ #define BP_I2C_C1_TXAK (3U) /*!< Bit position for I2C_C1_TXAK. */ #define BM_I2C_C1_TXAK (0x08U) /*!< Bit mask for I2C_C1_TXAK. */ #define BS_I2C_C1_TXAK (1U) /*!< Bit field size in bits for I2C_C1_TXAK. */ /*! @brief Read current value of the I2C_C1_TXAK field. */ #define BR_I2C_C1_TXAK(x) (BITBAND_ACCESS8(HW_I2C_C1_ADDR(x), BP_I2C_C1_TXAK)) /*! @brief Format value for bitfield I2C_C1_TXAK. */ #define BF_I2C_C1_TXAK(v) ((uint8_t)((uint8_t)(v) << BP_I2C_C1_TXAK) & BM_I2C_C1_TXAK) /*! @brief Set the TXAK field to a new value. */ #define BW_I2C_C1_TXAK(x, v) (BITBAND_ACCESS8(HW_I2C_C1_ADDR(x), BP_I2C_C1_TXAK) = (v)) /*@}*/ /*! * @name Register I2C_C1, field TX[4] (RW) * * Selects the direction of master and slave transfers. In master mode this bit * must be set according to the type of transfer required. Therefore, for address * cycles, this bit is always set. When addressed as a slave this bit must be * set by software according to the SRW bit in the status register. * * Values: * - 0 - Receive * - 1 - Transmit */ /*@{*/ #define BP_I2C_C1_TX (4U) /*!< Bit position for I2C_C1_TX. */ #define BM_I2C_C1_TX (0x10U) /*!< Bit mask for I2C_C1_TX. */ #define BS_I2C_C1_TX (1U) /*!< Bit field size in bits for I2C_C1_TX. */ /*! @brief Read current value of the I2C_C1_TX field. */ #define BR_I2C_C1_TX(x) (BITBAND_ACCESS8(HW_I2C_C1_ADDR(x), BP_I2C_C1_TX)) /*! @brief Format value for bitfield I2C_C1_TX. */ #define BF_I2C_C1_TX(v) ((uint8_t)((uint8_t)(v) << BP_I2C_C1_TX) & BM_I2C_C1_TX) /*! @brief Set the TX field to a new value. */ #define BW_I2C_C1_TX(x, v) (BITBAND_ACCESS8(HW_I2C_C1_ADDR(x), BP_I2C_C1_TX) = (v)) /*@}*/ /*! * @name Register I2C_C1, field MST[5] (RW) * * When MST is changed from 0 to 1, a START signal is generated on the bus and * master mode is selected. When this bit changes from 1 to 0, a STOP signal is * generated and the mode of operation changes from master to slave. * * Values: * - 0 - Slave mode * - 1 - Master mode */ /*@{*/ #define BP_I2C_C1_MST (5U) /*!< Bit position for I2C_C1_MST. */ #define BM_I2C_C1_MST (0x20U) /*!< Bit mask for I2C_C1_MST. */ #define BS_I2C_C1_MST (1U) /*!< Bit field size in bits for I2C_C1_MST. */ /*! @brief Read current value of the I2C_C1_MST field. */ #define BR_I2C_C1_MST(x) (BITBAND_ACCESS8(HW_I2C_C1_ADDR(x), BP_I2C_C1_MST)) /*! @brief Format value for bitfield I2C_C1_MST. */ #define BF_I2C_C1_MST(v) ((uint8_t)((uint8_t)(v) << BP_I2C_C1_MST) & BM_I2C_C1_MST) /*! @brief Set the MST field to a new value. */ #define BW_I2C_C1_MST(x, v) (BITBAND_ACCESS8(HW_I2C_C1_ADDR(x), BP_I2C_C1_MST) = (v)) /*@}*/ /*! * @name Register I2C_C1, field IICIE[6] (RW) * * Enables I2C interrupt requests. * * Values: * - 0 - Disabled * - 1 - Enabled */ /*@{*/ #define BP_I2C_C1_IICIE (6U) /*!< Bit position for I2C_C1_IICIE. */ #define BM_I2C_C1_IICIE (0x40U) /*!< Bit mask for I2C_C1_IICIE. */ #define BS_I2C_C1_IICIE (1U) /*!< Bit field size in bits for I2C_C1_IICIE. */ /*! @brief Read current value of the I2C_C1_IICIE field. */ #define BR_I2C_C1_IICIE(x) (BITBAND_ACCESS8(HW_I2C_C1_ADDR(x), BP_I2C_C1_IICIE)) /*! @brief Format value for bitfield I2C_C1_IICIE. */ #define BF_I2C_C1_IICIE(v) ((uint8_t)((uint8_t)(v) << BP_I2C_C1_IICIE) & BM_I2C_C1_IICIE) /*! @brief Set the IICIE field to a new value. */ #define BW_I2C_C1_IICIE(x, v) (BITBAND_ACCESS8(HW_I2C_C1_ADDR(x), BP_I2C_C1_IICIE) = (v)) /*@}*/ /*! * @name Register I2C_C1, field IICEN[7] (RW) * * Enables I2C module operation. * * Values: * - 0 - Disabled * - 1 - Enabled */ /*@{*/ #define BP_I2C_C1_IICEN (7U) /*!< Bit position for I2C_C1_IICEN. */ #define BM_I2C_C1_IICEN (0x80U) /*!< Bit mask for I2C_C1_IICEN. */ #define BS_I2C_C1_IICEN (1U) /*!< Bit field size in bits for I2C_C1_IICEN. */ /*! @brief Read current value of the I2C_C1_IICEN field. */ #define BR_I2C_C1_IICEN(x) (BITBAND_ACCESS8(HW_I2C_C1_ADDR(x), BP_I2C_C1_IICEN)) /*! @brief Format value for bitfield I2C_C1_IICEN. */ #define BF_I2C_C1_IICEN(v) ((uint8_t)((uint8_t)(v) << BP_I2C_C1_IICEN) & BM_I2C_C1_IICEN) /*! @brief Set the IICEN field to a new value. */ #define BW_I2C_C1_IICEN(x, v) (BITBAND_ACCESS8(HW_I2C_C1_ADDR(x), BP_I2C_C1_IICEN) = (v)) /*@}*/ /******************************************************************************* * HW_I2C_S - I2C Status register ******************************************************************************/ /*! * @brief HW_I2C_S - I2C Status register (RW) * * Reset value: 0x80U */ typedef union _hw_i2c_s { uint8_t U; struct _hw_i2c_s_bitfields { uint8_t RXAK : 1; /*!< [0] Receive Acknowledge */ uint8_t IICIF : 1; /*!< [1] Interrupt Flag */ uint8_t SRW : 1; /*!< [2] Slave Read/Write */ uint8_t RAM : 1; /*!< [3] Range Address Match */ uint8_t ARBL : 1; /*!< [4] Arbitration Lost */ uint8_t BUSY : 1; /*!< [5] Bus Busy */ uint8_t IAAS : 1; /*!< [6] Addressed As A Slave */ uint8_t TCF : 1; /*!< [7] Transfer Complete Flag */ } B; } hw_i2c_s_t; /*! * @name Constants and macros for entire I2C_S register */ /*@{*/ #define HW_I2C_S_ADDR(x) ((x) + 0x3U) #define HW_I2C_S(x) (*(__IO hw_i2c_s_t *) HW_I2C_S_ADDR(x)) #define HW_I2C_S_RD(x) (HW_I2C_S(x).U) #define HW_I2C_S_WR(x, v) (HW_I2C_S(x).U = (v)) #define HW_I2C_S_SET(x, v) (HW_I2C_S_WR(x, HW_I2C_S_RD(x) | (v))) #define HW_I2C_S_CLR(x, v) (HW_I2C_S_WR(x, HW_I2C_S_RD(x) & ~(v))) #define HW_I2C_S_TOG(x, v) (HW_I2C_S_WR(x, HW_I2C_S_RD(x) ^ (v))) /*@}*/ /* * Constants & macros for individual I2C_S bitfields */ /*! * @name Register I2C_S, field RXAK[0] (RO) * * Values: * - 0 - Acknowledge signal was received after the completion of one byte of * data transmission on the bus * - 1 - No acknowledge signal detected */ /*@{*/ #define BP_I2C_S_RXAK (0U) /*!< Bit position for I2C_S_RXAK. */ #define BM_I2C_S_RXAK (0x01U) /*!< Bit mask for I2C_S_RXAK. */ #define BS_I2C_S_RXAK (1U) /*!< Bit field size in bits for I2C_S_RXAK. */ /*! @brief Read current value of the I2C_S_RXAK field. */ #define BR_I2C_S_RXAK(x) (BITBAND_ACCESS8(HW_I2C_S_ADDR(x), BP_I2C_S_RXAK)) /*@}*/ /*! * @name Register I2C_S, field IICIF[1] (W1C) * * This bit sets when an interrupt is pending. This bit must be cleared by * software by writing 1 to it, such as in the interrupt routine. One of the following * events can set this bit: One byte transfer, including ACK/NACK bit, completes * if FACK is 0. An ACK or NACK is sent on the bus by writing 0 or 1 to TXAK * after this bit is set in receive mode. One byte transfer, excluding ACK/NACK bit, * completes if FACK is 1. Match of slave address to calling address including * primary slave address, range slave address , alert response address, second * slave address, or general call address. Arbitration lost In SMBus mode, any * timeouts except SCL and SDA high timeouts I2C bus stop or start detection if the * SSIE bit in the Input Glitch Filter register is 1 To clear the I2C bus stop or * start detection interrupt: In the interrupt service routine, first clear the * STOPF or STARTF bit in the Input Glitch Filter register by writing 1 to it, and * then clear the IICIF bit. If this sequence is reversed, the IICIF bit is * asserted again. * * Values: * - 0 - No interrupt pending * - 1 - Interrupt pending */ /*@{*/ #define BP_I2C_S_IICIF (1U) /*!< Bit position for I2C_S_IICIF. */ #define BM_I2C_S_IICIF (0x02U) /*!< Bit mask for I2C_S_IICIF. */ #define BS_I2C_S_IICIF (1U) /*!< Bit field size in bits for I2C_S_IICIF. */ /*! @brief Read current value of the I2C_S_IICIF field. */ #define BR_I2C_S_IICIF(x) (BITBAND_ACCESS8(HW_I2C_S_ADDR(x), BP_I2C_S_IICIF)) /*! @brief Format value for bitfield I2C_S_IICIF. */ #define BF_I2C_S_IICIF(v) ((uint8_t)((uint8_t)(v) << BP_I2C_S_IICIF) & BM_I2C_S_IICIF) /*! @brief Set the IICIF field to a new value. */ #define BW_I2C_S_IICIF(x, v) (BITBAND_ACCESS8(HW_I2C_S_ADDR(x), BP_I2C_S_IICIF) = (v)) /*@}*/ /*! * @name Register I2C_S, field SRW[2] (RO) * * When addressed as a slave, SRW indicates the value of the R/W command bit of * the calling address sent to the master. * * Values: * - 0 - Slave receive, master writing to slave * - 1 - Slave transmit, master reading from slave */ /*@{*/ #define BP_I2C_S_SRW (2U) /*!< Bit position for I2C_S_SRW. */ #define BM_I2C_S_SRW (0x04U) /*!< Bit mask for I2C_S_SRW. */ #define BS_I2C_S_SRW (1U) /*!< Bit field size in bits for I2C_S_SRW. */ /*! @brief Read current value of the I2C_S_SRW field. */ #define BR_I2C_S_SRW(x) (BITBAND_ACCESS8(HW_I2C_S_ADDR(x), BP_I2C_S_SRW)) /*@}*/ /*! * @name Register I2C_S, field RAM[3] (RW) * * This bit is set to 1 by any of the following conditions, if I2C_C2[RMEN] = 1: * Any nonzero calling address is received that matches the address in the RA * register. The calling address is within the range of values of the A1 and RA * registers. For the RAM bit to be set to 1 correctly, C1[IICIE] must be set to 1. * Writing the C1 register with any value clears this bit to 0. * * Values: * - 0 - Not addressed * - 1 - Addressed as a slave */ /*@{*/ #define BP_I2C_S_RAM (3U) /*!< Bit position for I2C_S_RAM. */ #define BM_I2C_S_RAM (0x08U) /*!< Bit mask for I2C_S_RAM. */ #define BS_I2C_S_RAM (1U) /*!< Bit field size in bits for I2C_S_RAM. */ /*! @brief Read current value of the I2C_S_RAM field. */ #define BR_I2C_S_RAM(x) (BITBAND_ACCESS8(HW_I2C_S_ADDR(x), BP_I2C_S_RAM)) /*! @brief Format value for bitfield I2C_S_RAM. */ #define BF_I2C_S_RAM(v) ((uint8_t)((uint8_t)(v) << BP_I2C_S_RAM) & BM_I2C_S_RAM) /*! @brief Set the RAM field to a new value. */ #define BW_I2C_S_RAM(x, v) (BITBAND_ACCESS8(HW_I2C_S_ADDR(x), BP_I2C_S_RAM) = (v)) /*@}*/ /*! * @name Register I2C_S, field ARBL[4] (W1C) * * This bit is set by hardware when the arbitration procedure is lost. The ARBL * bit must be cleared by software, by writing 1 to it. * * Values: * - 0 - Standard bus operation. * - 1 - Loss of arbitration. */ /*@{*/ #define BP_I2C_S_ARBL (4U) /*!< Bit position for I2C_S_ARBL. */ #define BM_I2C_S_ARBL (0x10U) /*!< Bit mask for I2C_S_ARBL. */ #define BS_I2C_S_ARBL (1U) /*!< Bit field size in bits for I2C_S_ARBL. */ /*! @brief Read current value of the I2C_S_ARBL field. */ #define BR_I2C_S_ARBL(x) (BITBAND_ACCESS8(HW_I2C_S_ADDR(x), BP_I2C_S_ARBL)) /*! @brief Format value for bitfield I2C_S_ARBL. */ #define BF_I2C_S_ARBL(v) ((uint8_t)((uint8_t)(v) << BP_I2C_S_ARBL) & BM_I2C_S_ARBL) /*! @brief Set the ARBL field to a new value. */ #define BW_I2C_S_ARBL(x, v) (BITBAND_ACCESS8(HW_I2C_S_ADDR(x), BP_I2C_S_ARBL) = (v)) /*@}*/ /*! * @name Register I2C_S, field BUSY[5] (RO) * * Indicates the status of the bus regardless of slave or master mode. This bit * is set when a START signal is detected and cleared when a STOP signal is * detected. * * Values: * - 0 - Bus is idle * - 1 - Bus is busy */ /*@{*/ #define BP_I2C_S_BUSY (5U) /*!< Bit position for I2C_S_BUSY. */ #define BM_I2C_S_BUSY (0x20U) /*!< Bit mask for I2C_S_BUSY. */ #define BS_I2C_S_BUSY (1U) /*!< Bit field size in bits for I2C_S_BUSY. */ /*! @brief Read current value of the I2C_S_BUSY field. */ #define BR_I2C_S_BUSY(x) (BITBAND_ACCESS8(HW_I2C_S_ADDR(x), BP_I2C_S_BUSY)) /*@}*/ /*! * @name Register I2C_S, field IAAS[6] (RW) * * This bit is set by one of the following conditions: The calling address * matches the programmed primary slave address in the A1 register, or matches the * range address in the RA register (which must be set to a nonzero value and under * the condition I2C_C2[RMEN] = 1). C2[GCAEN] is set and a general call is * received. SMB[SIICAEN] is set and the calling address matches the second programmed * slave address. ALERTEN is set and an SMBus alert response address is received * RMEN is set and an address is received that is within the range between the * values of the A1 and RA registers. IAAS sets before the ACK bit. The CPU must * check the SRW bit and set TX/RX accordingly. Writing the C1 register with any * value clears this bit. * * Values: * - 0 - Not addressed * - 1 - Addressed as a slave */ /*@{*/ #define BP_I2C_S_IAAS (6U) /*!< Bit position for I2C_S_IAAS. */ #define BM_I2C_S_IAAS (0x40U) /*!< Bit mask for I2C_S_IAAS. */ #define BS_I2C_S_IAAS (1U) /*!< Bit field size in bits for I2C_S_IAAS. */ /*! @brief Read current value of the I2C_S_IAAS field. */ #define BR_I2C_S_IAAS(x) (BITBAND_ACCESS8(HW_I2C_S_ADDR(x), BP_I2C_S_IAAS)) /*! @brief Format value for bitfield I2C_S_IAAS. */ #define BF_I2C_S_IAAS(v) ((uint8_t)((uint8_t)(v) << BP_I2C_S_IAAS) & BM_I2C_S_IAAS) /*! @brief Set the IAAS field to a new value. */ #define BW_I2C_S_IAAS(x, v) (BITBAND_ACCESS8(HW_I2C_S_ADDR(x), BP_I2C_S_IAAS) = (v)) /*@}*/ /*! * @name Register I2C_S, field TCF[7] (RO) * * Acknowledges a byte transfer; TCF sets on the completion of a byte transfer. * This bit is valid only during or immediately following a transfer to or from * the I2C module. TCF is cleared by reading the I2C data register in receive mode * or by writing to the I2C data register in transmit mode. * * Values: * - 0 - Transfer in progress * - 1 - Transfer complete */ /*@{*/ #define BP_I2C_S_TCF (7U) /*!< Bit position for I2C_S_TCF. */ #define BM_I2C_S_TCF (0x80U) /*!< Bit mask for I2C_S_TCF. */ #define BS_I2C_S_TCF (1U) /*!< Bit field size in bits for I2C_S_TCF. */ /*! @brief Read current value of the I2C_S_TCF field. */ #define BR_I2C_S_TCF(x) (BITBAND_ACCESS8(HW_I2C_S_ADDR(x), BP_I2C_S_TCF)) /*@}*/ /******************************************************************************* * HW_I2C_D - I2C Data I/O register ******************************************************************************/ /*! * @brief HW_I2C_D - I2C Data I/O register (RW) * * Reset value: 0x00U */ typedef union _hw_i2c_d { uint8_t U; struct _hw_i2c_d_bitfields { uint8_t DATA : 8; /*!< [7:0] Data */ } B; } hw_i2c_d_t; /*! * @name Constants and macros for entire I2C_D register */ /*@{*/ #define HW_I2C_D_ADDR(x) ((x) + 0x4U) #define HW_I2C_D(x) (*(__IO hw_i2c_d_t *) HW_I2C_D_ADDR(x)) #define HW_I2C_D_RD(x) (HW_I2C_D(x).U) #define HW_I2C_D_WR(x, v) (HW_I2C_D(x).U = (v)) #define HW_I2C_D_SET(x, v) (HW_I2C_D_WR(x, HW_I2C_D_RD(x) | (v))) #define HW_I2C_D_CLR(x, v) (HW_I2C_D_WR(x, HW_I2C_D_RD(x) & ~(v))) #define HW_I2C_D_TOG(x, v) (HW_I2C_D_WR(x, HW_I2C_D_RD(x) ^ (v))) /*@}*/ /* * Constants & macros for individual I2C_D bitfields */ /*! * @name Register I2C_D, field DATA[7:0] (RW) * * In master transmit mode, when data is written to this register, a data * transfer is initiated. The most significant bit is sent first. In master receive * mode, reading this register initiates receiving of the next byte of data. When * making the transition out of master receive mode, switch the I2C mode before * reading the Data register to prevent an inadvertent initiation of a master * receive data transfer. In slave mode, the same functions are available after an * address match occurs. The C1[TX] bit must correctly reflect the desired direction * of transfer in master and slave modes for the transmission to begin. For * example, if the I2C module is configured for master transmit but a master receive * is desired, reading the Data register does not initiate the receive. Reading * the Data register returns the last byte received while the I2C module is * configured in master receive or slave receive mode. The Data register does not * reflect every byte that is transmitted on the I2C bus, and neither can software * verify that a byte has been written to the Data register correctly by reading it * back. In master transmit mode, the first byte of data written to the Data * register following assertion of MST (start bit) or assertion of RSTA (repeated * start bit) is used for the address transfer and must consist of the calling * address (in bits 7-1) concatenated with the required R/W bit (in position bit 0). */ /*@{*/ #define BP_I2C_D_DATA (0U) /*!< Bit position for I2C_D_DATA. */ #define BM_I2C_D_DATA (0xFFU) /*!< Bit mask for I2C_D_DATA. */ #define BS_I2C_D_DATA (8U) /*!< Bit field size in bits for I2C_D_DATA. */ /*! @brief Read current value of the I2C_D_DATA field. */ #define BR_I2C_D_DATA(x) (HW_I2C_D(x).U) /*! @brief Format value for bitfield I2C_D_DATA. */ #define BF_I2C_D_DATA(v) ((uint8_t)((uint8_t)(v) << BP_I2C_D_DATA) & BM_I2C_D_DATA) /*! @brief Set the DATA field to a new value. */ #define BW_I2C_D_DATA(x, v) (HW_I2C_D_WR(x, v)) /*@}*/ /******************************************************************************* * HW_I2C_C2 - I2C Control Register 2 ******************************************************************************/ /*! * @brief HW_I2C_C2 - I2C Control Register 2 (RW) * * Reset value: 0x00U */ typedef union _hw_i2c_c2 { uint8_t U; struct _hw_i2c_c2_bitfields { uint8_t AD : 3; /*!< [2:0] Slave Address */ uint8_t RMEN : 1; /*!< [3] Range Address Matching Enable */ uint8_t SBRC : 1; /*!< [4] Slave Baud Rate Control */ uint8_t HDRS : 1; /*!< [5] High Drive Select */ uint8_t ADEXT : 1; /*!< [6] Address Extension */ uint8_t GCAEN : 1; /*!< [7] General Call Address Enable */ } B; } hw_i2c_c2_t; /*! * @name Constants and macros for entire I2C_C2 register */ /*@{*/ #define HW_I2C_C2_ADDR(x) ((x) + 0x5U) #define HW_I2C_C2(x) (*(__IO hw_i2c_c2_t *) HW_I2C_C2_ADDR(x)) #define HW_I2C_C2_RD(x) (HW_I2C_C2(x).U) #define HW_I2C_C2_WR(x, v) (HW_I2C_C2(x).U = (v)) #define HW_I2C_C2_SET(x, v) (HW_I2C_C2_WR(x, HW_I2C_C2_RD(x) | (v))) #define HW_I2C_C2_CLR(x, v) (HW_I2C_C2_WR(x, HW_I2C_C2_RD(x) & ~(v))) #define HW_I2C_C2_TOG(x, v) (HW_I2C_C2_WR(x, HW_I2C_C2_RD(x) ^ (v))) /*@}*/ /* * Constants & macros for individual I2C_C2 bitfields */ /*! * @name Register I2C_C2, field AD[2:0] (RW) * * Contains the upper three bits of the slave address in the 10-bit address * scheme. This field is valid only while the ADEXT bit is set. */ /*@{*/ #define BP_I2C_C2_AD (0U) /*!< Bit position for I2C_C2_AD. */ #define BM_I2C_C2_AD (0x07U) /*!< Bit mask for I2C_C2_AD. */ #define BS_I2C_C2_AD (3U) /*!< Bit field size in bits for I2C_C2_AD. */ /*! @brief Read current value of the I2C_C2_AD field. */ #define BR_I2C_C2_AD(x) (HW_I2C_C2(x).B.AD) /*! @brief Format value for bitfield I2C_C2_AD. */ #define BF_I2C_C2_AD(v) ((uint8_t)((uint8_t)(v) << BP_I2C_C2_AD) & BM_I2C_C2_AD) /*! @brief Set the AD field to a new value. */ #define BW_I2C_C2_AD(x, v) (HW_I2C_C2_WR(x, (HW_I2C_C2_RD(x) & ~BM_I2C_C2_AD) | BF_I2C_C2_AD(v))) /*@}*/ /*! * @name Register I2C_C2, field RMEN[3] (RW) * * This bit controls the slave address matching for addresses between the values * of the A1 and RA registers. When this bit is set, a slave address matching * occurs for any address greater than the value of the A1 register and less than * or equal to the value of the RA register. * * Values: * - 0 - Range mode disabled. No address matching occurs for an address within * the range of values of the A1 and RA registers. * - 1 - Range mode enabled. Address matching occurs when a slave receives an * address within the range of values of the A1 and RA registers. */ /*@{*/ #define BP_I2C_C2_RMEN (3U) /*!< Bit position for I2C_C2_RMEN. */ #define BM_I2C_C2_RMEN (0x08U) /*!< Bit mask for I2C_C2_RMEN. */ #define BS_I2C_C2_RMEN (1U) /*!< Bit field size in bits for I2C_C2_RMEN. */ /*! @brief Read current value of the I2C_C2_RMEN field. */ #define BR_I2C_C2_RMEN(x) (BITBAND_ACCESS8(HW_I2C_C2_ADDR(x), BP_I2C_C2_RMEN)) /*! @brief Format value for bitfield I2C_C2_RMEN. */ #define BF_I2C_C2_RMEN(v) ((uint8_t)((uint8_t)(v) << BP_I2C_C2_RMEN) & BM_I2C_C2_RMEN) /*! @brief Set the RMEN field to a new value. */ #define BW_I2C_C2_RMEN(x, v) (BITBAND_ACCESS8(HW_I2C_C2_ADDR(x), BP_I2C_C2_RMEN) = (v)) /*@}*/ /*! * @name Register I2C_C2, field SBRC[4] (RW) * * Enables independent slave mode baud rate at maximum frequency, which forces * clock stretching on SCL in very fast I2C modes. To a slave, an example of a * "very fast" mode is when the master transfers at 40 kbit/s but the slave can * capture the master's data at only 10 kbit/s. * * Values: * - 0 - The slave baud rate follows the master baud rate and clock stretching * may occur * - 1 - Slave baud rate is independent of the master baud rate */ /*@{*/ #define BP_I2C_C2_SBRC (4U) /*!< Bit position for I2C_C2_SBRC. */ #define BM_I2C_C2_SBRC (0x10U) /*!< Bit mask for I2C_C2_SBRC. */ #define BS_I2C_C2_SBRC (1U) /*!< Bit field size in bits for I2C_C2_SBRC. */ /*! @brief Read current value of the I2C_C2_SBRC field. */ #define BR_I2C_C2_SBRC(x) (BITBAND_ACCESS8(HW_I2C_C2_ADDR(x), BP_I2C_C2_SBRC)) /*! @brief Format value for bitfield I2C_C2_SBRC. */ #define BF_I2C_C2_SBRC(v) ((uint8_t)((uint8_t)(v) << BP_I2C_C2_SBRC) & BM_I2C_C2_SBRC) /*! @brief Set the SBRC field to a new value. */ #define BW_I2C_C2_SBRC(x, v) (BITBAND_ACCESS8(HW_I2C_C2_ADDR(x), BP_I2C_C2_SBRC) = (v)) /*@}*/ /*! * @name Register I2C_C2, field HDRS[5] (RW) * * Controls the drive capability of the I2C pads. * * Values: * - 0 - Normal drive mode * - 1 - High drive mode */ /*@{*/ #define BP_I2C_C2_HDRS (5U) /*!< Bit position for I2C_C2_HDRS. */ #define BM_I2C_C2_HDRS (0x20U) /*!< Bit mask for I2C_C2_HDRS. */ #define BS_I2C_C2_HDRS (1U) /*!< Bit field size in bits for I2C_C2_HDRS. */ /*! @brief Read current value of the I2C_C2_HDRS field. */ #define BR_I2C_C2_HDRS(x) (BITBAND_ACCESS8(HW_I2C_C2_ADDR(x), BP_I2C_C2_HDRS)) /*! @brief Format value for bitfield I2C_C2_HDRS. */ #define BF_I2C_C2_HDRS(v) ((uint8_t)((uint8_t)(v) << BP_I2C_C2_HDRS) & BM_I2C_C2_HDRS) /*! @brief Set the HDRS field to a new value. */ #define BW_I2C_C2_HDRS(x, v) (BITBAND_ACCESS8(HW_I2C_C2_ADDR(x), BP_I2C_C2_HDRS) = (v)) /*@}*/ /*! * @name Register I2C_C2, field ADEXT[6] (RW) * * Controls the number of bits used for the slave address. * * Values: * - 0 - 7-bit address scheme * - 1 - 10-bit address scheme */ /*@{*/ #define BP_I2C_C2_ADEXT (6U) /*!< Bit position for I2C_C2_ADEXT. */ #define BM_I2C_C2_ADEXT (0x40U) /*!< Bit mask for I2C_C2_ADEXT. */ #define BS_I2C_C2_ADEXT (1U) /*!< Bit field size in bits for I2C_C2_ADEXT. */ /*! @brief Read current value of the I2C_C2_ADEXT field. */ #define BR_I2C_C2_ADEXT(x) (BITBAND_ACCESS8(HW_I2C_C2_ADDR(x), BP_I2C_C2_ADEXT)) /*! @brief Format value for bitfield I2C_C2_ADEXT. */ #define BF_I2C_C2_ADEXT(v) ((uint8_t)((uint8_t)(v) << BP_I2C_C2_ADEXT) & BM_I2C_C2_ADEXT) /*! @brief Set the ADEXT field to a new value. */ #define BW_I2C_C2_ADEXT(x, v) (BITBAND_ACCESS8(HW_I2C_C2_ADDR(x), BP_I2C_C2_ADEXT) = (v)) /*@}*/ /*! * @name Register I2C_C2, field GCAEN[7] (RW) * * Enables general call address. * * Values: * - 0 - Disabled * - 1 - Enabled */ /*@{*/ #define BP_I2C_C2_GCAEN (7U) /*!< Bit position for I2C_C2_GCAEN. */ #define BM_I2C_C2_GCAEN (0x80U) /*!< Bit mask for I2C_C2_GCAEN. */ #define BS_I2C_C2_GCAEN (1U) /*!< Bit field size in bits for I2C_C2_GCAEN. */ /*! @brief Read current value of the I2C_C2_GCAEN field. */ #define BR_I2C_C2_GCAEN(x) (BITBAND_ACCESS8(HW_I2C_C2_ADDR(x), BP_I2C_C2_GCAEN)) /*! @brief Format value for bitfield I2C_C2_GCAEN. */ #define BF_I2C_C2_GCAEN(v) ((uint8_t)((uint8_t)(v) << BP_I2C_C2_GCAEN) & BM_I2C_C2_GCAEN) /*! @brief Set the GCAEN field to a new value. */ #define BW_I2C_C2_GCAEN(x, v) (BITBAND_ACCESS8(HW_I2C_C2_ADDR(x), BP_I2C_C2_GCAEN) = (v)) /*@}*/ /******************************************************************************* * HW_I2C_FLT - I2C Programmable Input Glitch Filter register ******************************************************************************/ /*! * @brief HW_I2C_FLT - I2C Programmable Input Glitch Filter register (RW) * * Reset value: 0x00U */ typedef union _hw_i2c_flt { uint8_t U; struct _hw_i2c_flt_bitfields { uint8_t FLT : 4; /*!< [3:0] I2C Programmable Filter Factor */ uint8_t STARTF : 1; /*!< [4] I2C Bus Start Detect Flag */ uint8_t SSIE : 1; /*!< [5] I2C Bus Stop or Start Interrupt Enable */ uint8_t STOPF : 1; /*!< [6] I2C Bus Stop Detect Flag */ uint8_t SHEN : 1; /*!< [7] Stop Hold Enable */ } B; } hw_i2c_flt_t; /*! * @name Constants and macros for entire I2C_FLT register */ /*@{*/ #define HW_I2C_FLT_ADDR(x) ((x) + 0x6U) #define HW_I2C_FLT(x) (*(__IO hw_i2c_flt_t *) HW_I2C_FLT_ADDR(x)) #define HW_I2C_FLT_RD(x) (HW_I2C_FLT(x).U) #define HW_I2C_FLT_WR(x, v) (HW_I2C_FLT(x).U = (v)) #define HW_I2C_FLT_SET(x, v) (HW_I2C_FLT_WR(x, HW_I2C_FLT_RD(x) | (v))) #define HW_I2C_FLT_CLR(x, v) (HW_I2C_FLT_WR(x, HW_I2C_FLT_RD(x) & ~(v))) #define HW_I2C_FLT_TOG(x, v) (HW_I2C_FLT_WR(x, HW_I2C_FLT_RD(x) ^ (v))) /*@}*/ /* * Constants & macros for individual I2C_FLT bitfields */ /*! * @name Register I2C_FLT, field FLT[3:0] (RW) * * Controls the width of the glitch, in terms of I2C module clock cycles, that * the filter must absorb. For any glitch whose size is less than or equal to this * width setting, the filter does not allow the glitch to pass. * * Values: * - 0 - No filter/bypass */ /*@{*/ #define BP_I2C_FLT_FLT (0U) /*!< Bit position for I2C_FLT_FLT. */ #define BM_I2C_FLT_FLT (0x0FU) /*!< Bit mask for I2C_FLT_FLT. */ #define BS_I2C_FLT_FLT (4U) /*!< Bit field size in bits for I2C_FLT_FLT. */ /*! @brief Read current value of the I2C_FLT_FLT field. */ #define BR_I2C_FLT_FLT(x) (HW_I2C_FLT(x).B.FLT) /*! @brief Format value for bitfield I2C_FLT_FLT. */ #define BF_I2C_FLT_FLT(v) ((uint8_t)((uint8_t)(v) << BP_I2C_FLT_FLT) & BM_I2C_FLT_FLT) /*! @brief Set the FLT field to a new value. */ #define BW_I2C_FLT_FLT(x, v) (HW_I2C_FLT_WR(x, (HW_I2C_FLT_RD(x) & ~BM_I2C_FLT_FLT) | BF_I2C_FLT_FLT(v))) /*@}*/ /*! * @name Register I2C_FLT, field STARTF[4] (W1C) * * Hardware sets this bit when the I2C bus's start status is detected. The * STARTF bit must be cleared by writing 1 to it. * * Values: * - 0 - No start happens on I2C bus * - 1 - Start detected on I2C bus */ /*@{*/ #define BP_I2C_FLT_STARTF (4U) /*!< Bit position for I2C_FLT_STARTF. */ #define BM_I2C_FLT_STARTF (0x10U) /*!< Bit mask for I2C_FLT_STARTF. */ #define BS_I2C_FLT_STARTF (1U) /*!< Bit field size in bits for I2C_FLT_STARTF. */ /*! @brief Read current value of the I2C_FLT_STARTF field. */ #define BR_I2C_FLT_STARTF(x) (BITBAND_ACCESS8(HW_I2C_FLT_ADDR(x), BP_I2C_FLT_STARTF)) /*! @brief Format value for bitfield I2C_FLT_STARTF. */ #define BF_I2C_FLT_STARTF(v) ((uint8_t)((uint8_t)(v) << BP_I2C_FLT_STARTF) & BM_I2C_FLT_STARTF) /*! @brief Set the STARTF field to a new value. */ #define BW_I2C_FLT_STARTF(x, v) (BITBAND_ACCESS8(HW_I2C_FLT_ADDR(x), BP_I2C_FLT_STARTF) = (v)) /*@}*/ /*! * @name Register I2C_FLT, field SSIE[5] (RW) * * This bit enables the interrupt for I2C bus stop or start detection. To clear * the I2C bus stop or start detection interrupt: In the interrupt service * routine, first clear the STOPF or STARTF bit by writing 1 to it, and then clear the * IICIF bit in the status register. If this sequence is reversed, the IICIF bit * is asserted again. * * Values: * - 0 - Stop or start detection interrupt is disabled * - 1 - Stop or start detection interrupt is enabled */ /*@{*/ #define BP_I2C_FLT_SSIE (5U) /*!< Bit position for I2C_FLT_SSIE. */ #define BM_I2C_FLT_SSIE (0x20U) /*!< Bit mask for I2C_FLT_SSIE. */ #define BS_I2C_FLT_SSIE (1U) /*!< Bit field size in bits for I2C_FLT_SSIE. */ /*! @brief Read current value of the I2C_FLT_SSIE field. */ #define BR_I2C_FLT_SSIE(x) (BITBAND_ACCESS8(HW_I2C_FLT_ADDR(x), BP_I2C_FLT_SSIE)) /*! @brief Format value for bitfield I2C_FLT_SSIE. */ #define BF_I2C_FLT_SSIE(v) ((uint8_t)((uint8_t)(v) << BP_I2C_FLT_SSIE) & BM_I2C_FLT_SSIE) /*! @brief Set the SSIE field to a new value. */ #define BW_I2C_FLT_SSIE(x, v) (BITBAND_ACCESS8(HW_I2C_FLT_ADDR(x), BP_I2C_FLT_SSIE) = (v)) /*@}*/ /*! * @name Register I2C_FLT, field STOPF[6] (W1C) * * Hardware sets this bit when the I2C bus's stop status is detected. The STOPF * bit must be cleared by writing 1 to it. * * Values: * - 0 - No stop happens on I2C bus * - 1 - Stop detected on I2C bus */ /*@{*/ #define BP_I2C_FLT_STOPF (6U) /*!< Bit position for I2C_FLT_STOPF. */ #define BM_I2C_FLT_STOPF (0x40U) /*!< Bit mask for I2C_FLT_STOPF. */ #define BS_I2C_FLT_STOPF (1U) /*!< Bit field size in bits for I2C_FLT_STOPF. */ /*! @brief Read current value of the I2C_FLT_STOPF field. */ #define BR_I2C_FLT_STOPF(x) (BITBAND_ACCESS8(HW_I2C_FLT_ADDR(x), BP_I2C_FLT_STOPF)) /*! @brief Format value for bitfield I2C_FLT_STOPF. */ #define BF_I2C_FLT_STOPF(v) ((uint8_t)((uint8_t)(v) << BP_I2C_FLT_STOPF) & BM_I2C_FLT_STOPF) /*! @brief Set the STOPF field to a new value. */ #define BW_I2C_FLT_STOPF(x, v) (BITBAND_ACCESS8(HW_I2C_FLT_ADDR(x), BP_I2C_FLT_STOPF) = (v)) /*@}*/ /*! * @name Register I2C_FLT, field SHEN[7] (RW) * * Set this bit to hold off entry to stop mode when any data transmission or * reception is occurring. The following scenario explains the holdoff * functionality: The I2C module is configured for a basic transfer, and the SHEN bit is set * to 1. A transfer begins. The MCU signals the I2C module to enter stop mode. The * byte currently being transferred, including both address and data, completes * its transfer. The I2C slave or master acknowledges that the in-transfer byte * completed its transfer and acknowledges the request to enter stop mode. After * receiving the I2C module's acknowledgment of the request to enter stop mode, * the MCU determines whether to shut off the I2C module's clock. If the SHEN bit * is set to 1 and the I2C module is in an idle or disabled state when the MCU * signals to enter stop mode, the module immediately acknowledges the request to * enter stop mode. If SHEN is cleared to 0 and the overall data transmission or * reception that was suspended by stop mode entry was incomplete: To resume the * overall transmission or reception after the MCU exits stop mode, software must * reinitialize the transfer by resending the address of the slave. If the I2C * Control Register 1's IICIE bit was set to 1 before the MCU entered stop mode, * system software will receive the interrupt triggered by the I2C Status Register's * TCF bit after the MCU wakes from the stop mode. * * Values: * - 0 - Stop holdoff is disabled. The MCU's entry to stop mode is not gated. * - 1 - Stop holdoff is enabled. */ /*@{*/ #define BP_I2C_FLT_SHEN (7U) /*!< Bit position for I2C_FLT_SHEN. */ #define BM_I2C_FLT_SHEN (0x80U) /*!< Bit mask for I2C_FLT_SHEN. */ #define BS_I2C_FLT_SHEN (1U) /*!< Bit field size in bits for I2C_FLT_SHEN. */ /*! @brief Read current value of the I2C_FLT_SHEN field. */ #define BR_I2C_FLT_SHEN(x) (BITBAND_ACCESS8(HW_I2C_FLT_ADDR(x), BP_I2C_FLT_SHEN)) /*! @brief Format value for bitfield I2C_FLT_SHEN. */ #define BF_I2C_FLT_SHEN(v) ((uint8_t)((uint8_t)(v) << BP_I2C_FLT_SHEN) & BM_I2C_FLT_SHEN) /*! @brief Set the SHEN field to a new value. */ #define BW_I2C_FLT_SHEN(x, v) (BITBAND_ACCESS8(HW_I2C_FLT_ADDR(x), BP_I2C_FLT_SHEN) = (v)) /*@}*/ /******************************************************************************* * HW_I2C_RA - I2C Range Address register ******************************************************************************/ /*! * @brief HW_I2C_RA - I2C Range Address register (RW) * * Reset value: 0x00U */ typedef union _hw_i2c_ra { uint8_t U; struct _hw_i2c_ra_bitfields { uint8_t RESERVED0 : 1; /*!< [0] */ uint8_t RAD : 7; /*!< [7:1] Range Slave Address */ } B; } hw_i2c_ra_t; /*! * @name Constants and macros for entire I2C_RA register */ /*@{*/ #define HW_I2C_RA_ADDR(x) ((x) + 0x7U) #define HW_I2C_RA(x) (*(__IO hw_i2c_ra_t *) HW_I2C_RA_ADDR(x)) #define HW_I2C_RA_RD(x) (HW_I2C_RA(x).U) #define HW_I2C_RA_WR(x, v) (HW_I2C_RA(x).U = (v)) #define HW_I2C_RA_SET(x, v) (HW_I2C_RA_WR(x, HW_I2C_RA_RD(x) | (v))) #define HW_I2C_RA_CLR(x, v) (HW_I2C_RA_WR(x, HW_I2C_RA_RD(x) & ~(v))) #define HW_I2C_RA_TOG(x, v) (HW_I2C_RA_WR(x, HW_I2C_RA_RD(x) ^ (v))) /*@}*/ /* * Constants & macros for individual I2C_RA bitfields */ /*! * @name Register I2C_RA, field RAD[7:1] (RW) * * This field contains the slave address to be used by the I2C module. The field * is used in the 7-bit address scheme. If I2C_C2[RMEN] is set to 1, any nonzero * value write enables this register. This register value can be considered as a * maximum boundary in the range matching mode. */ /*@{*/ #define BP_I2C_RA_RAD (1U) /*!< Bit position for I2C_RA_RAD. */ #define BM_I2C_RA_RAD (0xFEU) /*!< Bit mask for I2C_RA_RAD. */ #define BS_I2C_RA_RAD (7U) /*!< Bit field size in bits for I2C_RA_RAD. */ /*! @brief Read current value of the I2C_RA_RAD field. */ #define BR_I2C_RA_RAD(x) (HW_I2C_RA(x).B.RAD) /*! @brief Format value for bitfield I2C_RA_RAD. */ #define BF_I2C_RA_RAD(v) ((uint8_t)((uint8_t)(v) << BP_I2C_RA_RAD) & BM_I2C_RA_RAD) /*! @brief Set the RAD field to a new value. */ #define BW_I2C_RA_RAD(x, v) (HW_I2C_RA_WR(x, (HW_I2C_RA_RD(x) & ~BM_I2C_RA_RAD) | BF_I2C_RA_RAD(v))) /*@}*/ /******************************************************************************* * HW_I2C_SMB - I2C SMBus Control and Status register ******************************************************************************/ /*! * @brief HW_I2C_SMB - I2C SMBus Control and Status register (RW) * * Reset value: 0x00U * * When the SCL and SDA signals are held high for a length of time greater than * the high timeout period, the SHTF1 flag sets. Before reaching this threshold, * while the system is detecting how long these signals are being held high, a * master assumes that the bus is free. However, the SHTF1 bit is set to 1 in the * bus transmission process with the idle bus state. When the TCKSEL bit is set, * there is no need to monitor the SHTF1 bit because the bus speed is too high to * match the protocol of SMBus. */ typedef union _hw_i2c_smb { uint8_t U; struct _hw_i2c_smb_bitfields { uint8_t SHTF2IE : 1; /*!< [0] SHTF2 Interrupt Enable */ uint8_t SHTF2 : 1; /*!< [1] SCL High Timeout Flag 2 */ uint8_t SHTF1 : 1; /*!< [2] SCL High Timeout Flag 1 */ uint8_t SLTF : 1; /*!< [3] SCL Low Timeout Flag */ uint8_t TCKSEL : 1; /*!< [4] Timeout Counter Clock Select */ uint8_t SIICAEN : 1; /*!< [5] Second I2C Address Enable */ uint8_t ALERTEN : 1; /*!< [6] SMBus Alert Response Address Enable */ uint8_t FACK : 1; /*!< [7] Fast NACK/ACK Enable */ } B; } hw_i2c_smb_t; /*! * @name Constants and macros for entire I2C_SMB register */ /*@{*/ #define HW_I2C_SMB_ADDR(x) ((x) + 0x8U) #define HW_I2C_SMB(x) (*(__IO hw_i2c_smb_t *) HW_I2C_SMB_ADDR(x)) #define HW_I2C_SMB_RD(x) (HW_I2C_SMB(x).U) #define HW_I2C_SMB_WR(x, v) (HW_I2C_SMB(x).U = (v)) #define HW_I2C_SMB_SET(x, v) (HW_I2C_SMB_WR(x, HW_I2C_SMB_RD(x) | (v))) #define HW_I2C_SMB_CLR(x, v) (HW_I2C_SMB_WR(x, HW_I2C_SMB_RD(x) & ~(v))) #define HW_I2C_SMB_TOG(x, v) (HW_I2C_SMB_WR(x, HW_I2C_SMB_RD(x) ^ (v))) /*@}*/ /* * Constants & macros for individual I2C_SMB bitfields */ /*! * @name Register I2C_SMB, field SHTF2IE[0] (RW) * * Enables SCL high and SDA low timeout interrupt. * * Values: * - 0 - SHTF2 interrupt is disabled * - 1 - SHTF2 interrupt is enabled */ /*@{*/ #define BP_I2C_SMB_SHTF2IE (0U) /*!< Bit position for I2C_SMB_SHTF2IE. */ #define BM_I2C_SMB_SHTF2IE (0x01U) /*!< Bit mask for I2C_SMB_SHTF2IE. */ #define BS_I2C_SMB_SHTF2IE (1U) /*!< Bit field size in bits for I2C_SMB_SHTF2IE. */ /*! @brief Read current value of the I2C_SMB_SHTF2IE field. */ #define BR_I2C_SMB_SHTF2IE(x) (BITBAND_ACCESS8(HW_I2C_SMB_ADDR(x), BP_I2C_SMB_SHTF2IE)) /*! @brief Format value for bitfield I2C_SMB_SHTF2IE. */ #define BF_I2C_SMB_SHTF2IE(v) ((uint8_t)((uint8_t)(v) << BP_I2C_SMB_SHTF2IE) & BM_I2C_SMB_SHTF2IE) /*! @brief Set the SHTF2IE field to a new value. */ #define BW_I2C_SMB_SHTF2IE(x, v) (BITBAND_ACCESS8(HW_I2C_SMB_ADDR(x), BP_I2C_SMB_SHTF2IE) = (v)) /*@}*/ /*! * @name Register I2C_SMB, field SHTF2[1] (W1C) * * This bit sets when SCL is held high and SDA is held low more than clock * * LoValue / 512. Software clears this bit by writing 1 to it. * * Values: * - 0 - No SCL high and SDA low timeout occurs * - 1 - SCL high and SDA low timeout occurs */ /*@{*/ #define BP_I2C_SMB_SHTF2 (1U) /*!< Bit position for I2C_SMB_SHTF2. */ #define BM_I2C_SMB_SHTF2 (0x02U) /*!< Bit mask for I2C_SMB_SHTF2. */ #define BS_I2C_SMB_SHTF2 (1U) /*!< Bit field size in bits for I2C_SMB_SHTF2. */ /*! @brief Read current value of the I2C_SMB_SHTF2 field. */ #define BR_I2C_SMB_SHTF2(x) (BITBAND_ACCESS8(HW_I2C_SMB_ADDR(x), BP_I2C_SMB_SHTF2)) /*! @brief Format value for bitfield I2C_SMB_SHTF2. */ #define BF_I2C_SMB_SHTF2(v) ((uint8_t)((uint8_t)(v) << BP_I2C_SMB_SHTF2) & BM_I2C_SMB_SHTF2) /*! @brief Set the SHTF2 field to a new value. */ #define BW_I2C_SMB_SHTF2(x, v) (BITBAND_ACCESS8(HW_I2C_SMB_ADDR(x), BP_I2C_SMB_SHTF2) = (v)) /*@}*/ /*! * @name Register I2C_SMB, field SHTF1[2] (RO) * * This read-only bit sets when SCL and SDA are held high more than clock * * LoValue / 512, which indicates the bus is free. This bit is cleared automatically. * * Values: * - 0 - No SCL high and SDA high timeout occurs * - 1 - SCL high and SDA high timeout occurs */ /*@{*/ #define BP_I2C_SMB_SHTF1 (2U) /*!< Bit position for I2C_SMB_SHTF1. */ #define BM_I2C_SMB_SHTF1 (0x04U) /*!< Bit mask for I2C_SMB_SHTF1. */ #define BS_I2C_SMB_SHTF1 (1U) /*!< Bit field size in bits for I2C_SMB_SHTF1. */ /*! @brief Read current value of the I2C_SMB_SHTF1 field. */ #define BR_I2C_SMB_SHTF1(x) (BITBAND_ACCESS8(HW_I2C_SMB_ADDR(x), BP_I2C_SMB_SHTF1)) /*@}*/ /*! * @name Register I2C_SMB, field SLTF[3] (W1C) * * This bit is set when the SLT register (consisting of the SLTH and SLTL * registers) is loaded with a non-zero value (LoValue) and an SCL low timeout occurs. * Software clears this bit by writing a logic 1 to it. The low timeout function * is disabled when the SLT register's value is 0. * * Values: * - 0 - No low timeout occurs * - 1 - Low timeout occurs */ /*@{*/ #define BP_I2C_SMB_SLTF (3U) /*!< Bit position for I2C_SMB_SLTF. */ #define BM_I2C_SMB_SLTF (0x08U) /*!< Bit mask for I2C_SMB_SLTF. */ #define BS_I2C_SMB_SLTF (1U) /*!< Bit field size in bits for I2C_SMB_SLTF. */ /*! @brief Read current value of the I2C_SMB_SLTF field. */ #define BR_I2C_SMB_SLTF(x) (BITBAND_ACCESS8(HW_I2C_SMB_ADDR(x), BP_I2C_SMB_SLTF)) /*! @brief Format value for bitfield I2C_SMB_SLTF. */ #define BF_I2C_SMB_SLTF(v) ((uint8_t)((uint8_t)(v) << BP_I2C_SMB_SLTF) & BM_I2C_SMB_SLTF) /*! @brief Set the SLTF field to a new value. */ #define BW_I2C_SMB_SLTF(x, v) (BITBAND_ACCESS8(HW_I2C_SMB_ADDR(x), BP_I2C_SMB_SLTF) = (v)) /*@}*/ /*! * @name Register I2C_SMB, field TCKSEL[4] (RW) * * Selects the clock source of the timeout counter. * * Values: * - 0 - Timeout counter counts at the frequency of the I2C module clock / 64 * - 1 - Timeout counter counts at the frequency of the I2C module clock */ /*@{*/ #define BP_I2C_SMB_TCKSEL (4U) /*!< Bit position for I2C_SMB_TCKSEL. */ #define BM_I2C_SMB_TCKSEL (0x10U) /*!< Bit mask for I2C_SMB_TCKSEL. */ #define BS_I2C_SMB_TCKSEL (1U) /*!< Bit field size in bits for I2C_SMB_TCKSEL. */ /*! @brief Read current value of the I2C_SMB_TCKSEL field. */ #define BR_I2C_SMB_TCKSEL(x) (BITBAND_ACCESS8(HW_I2C_SMB_ADDR(x), BP_I2C_SMB_TCKSEL)) /*! @brief Format value for bitfield I2C_SMB_TCKSEL. */ #define BF_I2C_SMB_TCKSEL(v) ((uint8_t)((uint8_t)(v) << BP_I2C_SMB_TCKSEL) & BM_I2C_SMB_TCKSEL) /*! @brief Set the TCKSEL field to a new value. */ #define BW_I2C_SMB_TCKSEL(x, v) (BITBAND_ACCESS8(HW_I2C_SMB_ADDR(x), BP_I2C_SMB_TCKSEL) = (v)) /*@}*/ /*! * @name Register I2C_SMB, field SIICAEN[5] (RW) * * Enables or disables SMBus device default address. * * Values: * - 0 - I2C address register 2 matching is disabled * - 1 - I2C address register 2 matching is enabled */ /*@{*/ #define BP_I2C_SMB_SIICAEN (5U) /*!< Bit position for I2C_SMB_SIICAEN. */ #define BM_I2C_SMB_SIICAEN (0x20U) /*!< Bit mask for I2C_SMB_SIICAEN. */ #define BS_I2C_SMB_SIICAEN (1U) /*!< Bit field size in bits for I2C_SMB_SIICAEN. */ /*! @brief Read current value of the I2C_SMB_SIICAEN field. */ #define BR_I2C_SMB_SIICAEN(x) (BITBAND_ACCESS8(HW_I2C_SMB_ADDR(x), BP_I2C_SMB_SIICAEN)) /*! @brief Format value for bitfield I2C_SMB_SIICAEN. */ #define BF_I2C_SMB_SIICAEN(v) ((uint8_t)((uint8_t)(v) << BP_I2C_SMB_SIICAEN) & BM_I2C_SMB_SIICAEN) /*! @brief Set the SIICAEN field to a new value. */ #define BW_I2C_SMB_SIICAEN(x, v) (BITBAND_ACCESS8(HW_I2C_SMB_ADDR(x), BP_I2C_SMB_SIICAEN) = (v)) /*@}*/ /*! * @name Register I2C_SMB, field ALERTEN[6] (RW) * * Enables or disables SMBus alert response address matching. After the host * responds to a device that used the alert response address, you must use software * to put the device's address on the bus. The alert protocol is described in the * SMBus specification. * * Values: * - 0 - SMBus alert response address matching is disabled * - 1 - SMBus alert response address matching is enabled */ /*@{*/ #define BP_I2C_SMB_ALERTEN (6U) /*!< Bit position for I2C_SMB_ALERTEN. */ #define BM_I2C_SMB_ALERTEN (0x40U) /*!< Bit mask for I2C_SMB_ALERTEN. */ #define BS_I2C_SMB_ALERTEN (1U) /*!< Bit field size in bits for I2C_SMB_ALERTEN. */ /*! @brief Read current value of the I2C_SMB_ALERTEN field. */ #define BR_I2C_SMB_ALERTEN(x) (BITBAND_ACCESS8(HW_I2C_SMB_ADDR(x), BP_I2C_SMB_ALERTEN)) /*! @brief Format value for bitfield I2C_SMB_ALERTEN. */ #define BF_I2C_SMB_ALERTEN(v) ((uint8_t)((uint8_t)(v) << BP_I2C_SMB_ALERTEN) & BM_I2C_SMB_ALERTEN) /*! @brief Set the ALERTEN field to a new value. */ #define BW_I2C_SMB_ALERTEN(x, v) (BITBAND_ACCESS8(HW_I2C_SMB_ADDR(x), BP_I2C_SMB_ALERTEN) = (v)) /*@}*/ /*! * @name Register I2C_SMB, field FACK[7] (RW) * * For SMBus packet error checking, the CPU must be able to issue an ACK or NACK * according to the result of receiving data byte. * * Values: * - 0 - An ACK or NACK is sent on the following receiving data byte * - 1 - Writing 0 to TXAK after receiving a data byte generates an ACK. Writing * 1 to TXAK after receiving a data byte generates a NACK. */ /*@{*/ #define BP_I2C_SMB_FACK (7U) /*!< Bit position for I2C_SMB_FACK. */ #define BM_I2C_SMB_FACK (0x80U) /*!< Bit mask for I2C_SMB_FACK. */ #define BS_I2C_SMB_FACK (1U) /*!< Bit field size in bits for I2C_SMB_FACK. */ /*! @brief Read current value of the I2C_SMB_FACK field. */ #define BR_I2C_SMB_FACK(x) (BITBAND_ACCESS8(HW_I2C_SMB_ADDR(x), BP_I2C_SMB_FACK)) /*! @brief Format value for bitfield I2C_SMB_FACK. */ #define BF_I2C_SMB_FACK(v) ((uint8_t)((uint8_t)(v) << BP_I2C_SMB_FACK) & BM_I2C_SMB_FACK) /*! @brief Set the FACK field to a new value. */ #define BW_I2C_SMB_FACK(x, v) (BITBAND_ACCESS8(HW_I2C_SMB_ADDR(x), BP_I2C_SMB_FACK) = (v)) /*@}*/ /******************************************************************************* * HW_I2C_A2 - I2C Address Register 2 ******************************************************************************/ /*! * @brief HW_I2C_A2 - I2C Address Register 2 (RW) * * Reset value: 0xC2U */ typedef union _hw_i2c_a2 { uint8_t U; struct _hw_i2c_a2_bitfields { uint8_t RESERVED0 : 1; /*!< [0] */ uint8_t SAD : 7; /*!< [7:1] SMBus Address */ } B; } hw_i2c_a2_t; /*! * @name Constants and macros for entire I2C_A2 register */ /*@{*/ #define HW_I2C_A2_ADDR(x) ((x) + 0x9U) #define HW_I2C_A2(x) (*(__IO hw_i2c_a2_t *) HW_I2C_A2_ADDR(x)) #define HW_I2C_A2_RD(x) (HW_I2C_A2(x).U) #define HW_I2C_A2_WR(x, v) (HW_I2C_A2(x).U = (v)) #define HW_I2C_A2_SET(x, v) (HW_I2C_A2_WR(x, HW_I2C_A2_RD(x) | (v))) #define HW_I2C_A2_CLR(x, v) (HW_I2C_A2_WR(x, HW_I2C_A2_RD(x) & ~(v))) #define HW_I2C_A2_TOG(x, v) (HW_I2C_A2_WR(x, HW_I2C_A2_RD(x) ^ (v))) /*@}*/ /* * Constants & macros for individual I2C_A2 bitfields */ /*! * @name Register I2C_A2, field SAD[7:1] (RW) * * Contains the slave address used by the SMBus. This field is used on the * device default address or other related addresses. */ /*@{*/ #define BP_I2C_A2_SAD (1U) /*!< Bit position for I2C_A2_SAD. */ #define BM_I2C_A2_SAD (0xFEU) /*!< Bit mask for I2C_A2_SAD. */ #define BS_I2C_A2_SAD (7U) /*!< Bit field size in bits for I2C_A2_SAD. */ /*! @brief Read current value of the I2C_A2_SAD field. */ #define BR_I2C_A2_SAD(x) (HW_I2C_A2(x).B.SAD) /*! @brief Format value for bitfield I2C_A2_SAD. */ #define BF_I2C_A2_SAD(v) ((uint8_t)((uint8_t)(v) << BP_I2C_A2_SAD) & BM_I2C_A2_SAD) /*! @brief Set the SAD field to a new value. */ #define BW_I2C_A2_SAD(x, v) (HW_I2C_A2_WR(x, (HW_I2C_A2_RD(x) & ~BM_I2C_A2_SAD) | BF_I2C_A2_SAD(v))) /*@}*/ /******************************************************************************* * HW_I2C_SLTH - I2C SCL Low Timeout Register High ******************************************************************************/ /*! * @brief HW_I2C_SLTH - I2C SCL Low Timeout Register High (RW) * * Reset value: 0x00U */ typedef union _hw_i2c_slth { uint8_t U; struct _hw_i2c_slth_bitfields { uint8_t SSLT : 8; /*!< [7:0] */ } B; } hw_i2c_slth_t; /*! * @name Constants and macros for entire I2C_SLTH register */ /*@{*/ #define HW_I2C_SLTH_ADDR(x) ((x) + 0xAU) #define HW_I2C_SLTH(x) (*(__IO hw_i2c_slth_t *) HW_I2C_SLTH_ADDR(x)) #define HW_I2C_SLTH_RD(x) (HW_I2C_SLTH(x).U) #define HW_I2C_SLTH_WR(x, v) (HW_I2C_SLTH(x).U = (v)) #define HW_I2C_SLTH_SET(x, v) (HW_I2C_SLTH_WR(x, HW_I2C_SLTH_RD(x) | (v))) #define HW_I2C_SLTH_CLR(x, v) (HW_I2C_SLTH_WR(x, HW_I2C_SLTH_RD(x) & ~(v))) #define HW_I2C_SLTH_TOG(x, v) (HW_I2C_SLTH_WR(x, HW_I2C_SLTH_RD(x) ^ (v))) /*@}*/ /* * Constants & macros for individual I2C_SLTH bitfields */ /*! * @name Register I2C_SLTH, field SSLT[7:0] (RW) * * Most significant byte of SCL low timeout value that determines the timeout * period of SCL low. */ /*@{*/ #define BP_I2C_SLTH_SSLT (0U) /*!< Bit position for I2C_SLTH_SSLT. */ #define BM_I2C_SLTH_SSLT (0xFFU) /*!< Bit mask for I2C_SLTH_SSLT. */ #define BS_I2C_SLTH_SSLT (8U) /*!< Bit field size in bits for I2C_SLTH_SSLT. */ /*! @brief Read current value of the I2C_SLTH_SSLT field. */ #define BR_I2C_SLTH_SSLT(x) (HW_I2C_SLTH(x).U) /*! @brief Format value for bitfield I2C_SLTH_SSLT. */ #define BF_I2C_SLTH_SSLT(v) ((uint8_t)((uint8_t)(v) << BP_I2C_SLTH_SSLT) & BM_I2C_SLTH_SSLT) /*! @brief Set the SSLT field to a new value. */ #define BW_I2C_SLTH_SSLT(x, v) (HW_I2C_SLTH_WR(x, v)) /*@}*/ /******************************************************************************* * HW_I2C_SLTL - I2C SCL Low Timeout Register Low ******************************************************************************/ /*! * @brief HW_I2C_SLTL - I2C SCL Low Timeout Register Low (RW) * * Reset value: 0x00U */ typedef union _hw_i2c_sltl { uint8_t U; struct _hw_i2c_sltl_bitfields { uint8_t SSLT : 8; /*!< [7:0] */ } B; } hw_i2c_sltl_t; /*! * @name Constants and macros for entire I2C_SLTL register */ /*@{*/ #define HW_I2C_SLTL_ADDR(x) ((x) + 0xBU) #define HW_I2C_SLTL(x) (*(__IO hw_i2c_sltl_t *) HW_I2C_SLTL_ADDR(x)) #define HW_I2C_SLTL_RD(x) (HW_I2C_SLTL(x).U) #define HW_I2C_SLTL_WR(x, v) (HW_I2C_SLTL(x).U = (v)) #define HW_I2C_SLTL_SET(x, v) (HW_I2C_SLTL_WR(x, HW_I2C_SLTL_RD(x) | (v))) #define HW_I2C_SLTL_CLR(x, v) (HW_I2C_SLTL_WR(x, HW_I2C_SLTL_RD(x) & ~(v))) #define HW_I2C_SLTL_TOG(x, v) (HW_I2C_SLTL_WR(x, HW_I2C_SLTL_RD(x) ^ (v))) /*@}*/ /* * Constants & macros for individual I2C_SLTL bitfields */ /*! * @name Register I2C_SLTL, field SSLT[7:0] (RW) * * Least significant byte of SCL low timeout value that determines the timeout * period of SCL low. */ /*@{*/ #define BP_I2C_SLTL_SSLT (0U) /*!< Bit position for I2C_SLTL_SSLT. */ #define BM_I2C_SLTL_SSLT (0xFFU) /*!< Bit mask for I2C_SLTL_SSLT. */ #define BS_I2C_SLTL_SSLT (8U) /*!< Bit field size in bits for I2C_SLTL_SSLT. */ /*! @brief Read current value of the I2C_SLTL_SSLT field. */ #define BR_I2C_SLTL_SSLT(x) (HW_I2C_SLTL(x).U) /*! @brief Format value for bitfield I2C_SLTL_SSLT. */ #define BF_I2C_SLTL_SSLT(v) ((uint8_t)((uint8_t)(v) << BP_I2C_SLTL_SSLT) & BM_I2C_SLTL_SSLT) /*! @brief Set the SSLT field to a new value. */ #define BW_I2C_SLTL_SSLT(x, v) (HW_I2C_SLTL_WR(x, v)) /*@}*/ /******************************************************************************* * hw_i2c_t - module struct ******************************************************************************/ /*! * @brief All I2C module registers. */ #pragma pack(1) typedef struct _hw_i2c { __IO hw_i2c_a1_t A1; /*!< [0x0] I2C Address Register 1 */ __IO hw_i2c_f_t F; /*!< [0x1] I2C Frequency Divider register */ __IO hw_i2c_c1_t C1; /*!< [0x2] I2C Control Register 1 */ __IO hw_i2c_s_t S; /*!< [0x3] I2C Status register */ __IO hw_i2c_d_t D; /*!< [0x4] I2C Data I/O register */ __IO hw_i2c_c2_t C2; /*!< [0x5] I2C Control Register 2 */ __IO hw_i2c_flt_t FLT; /*!< [0x6] I2C Programmable Input Glitch Filter register */ __IO hw_i2c_ra_t RA; /*!< [0x7] I2C Range Address register */ __IO hw_i2c_smb_t SMB; /*!< [0x8] I2C SMBus Control and Status register */ __IO hw_i2c_a2_t A2; /*!< [0x9] I2C Address Register 2 */ __IO hw_i2c_slth_t SLTH; /*!< [0xA] I2C SCL Low Timeout Register High */ __IO hw_i2c_sltl_t SLTL; /*!< [0xB] I2C SCL Low Timeout Register Low */ } hw_i2c_t; #pragma pack() /*! @brief Macro to access all I2C registers. */ /*! @param x I2C module instance base address. */ /*! @return Reference (not a pointer) to the registers struct. To get a pointer to the struct, * use the '&' operator, like &HW_I2C(I2C0_BASE). */ #define HW_I2C(x) (*(hw_i2c_t *)(x)) #endif /* __HW_I2C_REGISTERS_H__ */ /* EOF */ ================================================ FILE: Zelig/mbed/TARGET_K64F/TARGET_Freescale/TARGET_KPSDK_MCUS/TARGET_MCU_K64F/device/device/MK64F12/MK64F12_i2s.h ================================================ /* ** ################################################################### ** Compilers: Keil ARM C/C++ Compiler ** Freescale C/C++ for Embedded ARM ** GNU C Compiler ** IAR ANSI C/C++ Compiler for ARM ** ** Reference manual: K64P144M120SF5RM, Rev.2, January 2014 ** Version: rev. 2.5, 2014-02-10 ** Build: b140604 ** ** Abstract: ** Extension to the CMSIS register access layer header. ** ** Copyright (c) 2014 Freescale Semiconductor, Inc. ** All rights reserved. ** ** Redistribution and use in source and binary forms, with or without modification, ** are permitted provided that the following conditions are met: ** ** o Redistributions of source code must retain the above copyright notice, this list ** of conditions and the following disclaimer. ** ** o Redistributions in binary form must reproduce the above copyright notice, this ** list of conditions and the following disclaimer in the documentation and/or ** other materials provided with the distribution. ** ** o Neither the name of Freescale Semiconductor, Inc. nor the names of its ** contributors may be used to endorse or promote products derived from this ** software without specific prior written permission. ** ** THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ** ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED ** WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE ** DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT 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. ** ** http: www.freescale.com ** mail: support@freescale.com ** ** Revisions: ** - rev. 1.0 (2013-08-12) ** Initial version. ** - rev. 2.0 (2013-10-29) ** Register accessor macros added to the memory map. ** Symbols for Processor Expert memory map compatibility added to the memory map. ** Startup file for gcc has been updated according to CMSIS 3.2. ** System initialization updated. ** MCG - registers updated. ** PORTA, PORTB, PORTC, PORTE - registers for digital filter removed. ** - rev. 2.1 (2013-10-30) ** Definition of BITBAND macros updated to support peripherals with 32-bit acces disabled. ** - rev. 2.2 (2013-12-09) ** DMA - EARS register removed. ** AIPS0, AIPS1 - MPRA register updated. ** - rev. 2.3 (2014-01-24) ** Update according to reference manual rev. 2 ** ENET, MCG, MCM, SIM, USB - registers updated ** - rev. 2.4 (2014-02-10) ** The declaration of clock configurations has been moved to separate header file system_MK64F12.h ** Update of SystemInit() and SystemCoreClockUpdate() functions. ** - rev. 2.5 (2014-02-10) ** The declaration of clock configurations has been moved to separate header file system_MK64F12.h ** Update of SystemInit() and SystemCoreClockUpdate() functions. ** Module access macro module_BASES replaced by module_BASE_PTRS. ** ** ################################################################### */ /* * WARNING! DO NOT EDIT THIS FILE DIRECTLY! * * This file was generated automatically and any changes may be lost. */ #ifndef __HW_I2S_REGISTERS_H__ #define __HW_I2S_REGISTERS_H__ #include "MK64F12.h" #include "fsl_bitaccess.h" /* * MK64F12 I2S * * Inter-IC Sound / Synchronous Audio Interface * * Registers defined in this header file: * - HW_I2S_TCSR - SAI Transmit Control Register * - HW_I2S_TCR1 - SAI Transmit Configuration 1 Register * - HW_I2S_TCR2 - SAI Transmit Configuration 2 Register * - HW_I2S_TCR3 - SAI Transmit Configuration 3 Register * - HW_I2S_TCR4 - SAI Transmit Configuration 4 Register * - HW_I2S_TCR5 - SAI Transmit Configuration 5 Register * - HW_I2S_TDRn - SAI Transmit Data Register * - HW_I2S_TFRn - SAI Transmit FIFO Register * - HW_I2S_TMR - SAI Transmit Mask Register * - HW_I2S_RCSR - SAI Receive Control Register * - HW_I2S_RCR1 - SAI Receive Configuration 1 Register * - HW_I2S_RCR2 - SAI Receive Configuration 2 Register * - HW_I2S_RCR3 - SAI Receive Configuration 3 Register * - HW_I2S_RCR4 - SAI Receive Configuration 4 Register * - HW_I2S_RCR5 - SAI Receive Configuration 5 Register * - HW_I2S_RDRn - SAI Receive Data Register * - HW_I2S_RFRn - SAI Receive FIFO Register * - HW_I2S_RMR - SAI Receive Mask Register * - HW_I2S_MCR - SAI MCLK Control Register * - HW_I2S_MDR - SAI MCLK Divide Register * * - hw_i2s_t - Struct containing all module registers. */ #define HW_I2S_INSTANCE_COUNT (1U) /*!< Number of instances of the I2S module. */ /******************************************************************************* * HW_I2S_TCSR - SAI Transmit Control Register ******************************************************************************/ /*! * @brief HW_I2S_TCSR - SAI Transmit Control Register (RW) * * Reset value: 0x00000000U */ typedef union _hw_i2s_tcsr { uint32_t U; struct _hw_i2s_tcsr_bitfields { uint32_t FRDE : 1; /*!< [0] FIFO Request DMA Enable */ uint32_t FWDE : 1; /*!< [1] FIFO Warning DMA Enable */ uint32_t RESERVED0 : 6; /*!< [7:2] */ uint32_t FRIE : 1; /*!< [8] FIFO Request Interrupt Enable */ uint32_t FWIE : 1; /*!< [9] FIFO Warning Interrupt Enable */ uint32_t FEIE : 1; /*!< [10] FIFO Error Interrupt Enable */ uint32_t SEIE : 1; /*!< [11] Sync Error Interrupt Enable */ uint32_t WSIE : 1; /*!< [12] Word Start Interrupt Enable */ uint32_t RESERVED1 : 3; /*!< [15:13] */ uint32_t FRF : 1; /*!< [16] FIFO Request Flag */ uint32_t FWF : 1; /*!< [17] FIFO Warning Flag */ uint32_t FEF : 1; /*!< [18] FIFO Error Flag */ uint32_t SEF : 1; /*!< [19] Sync Error Flag */ uint32_t WSF : 1; /*!< [20] Word Start Flag */ uint32_t RESERVED2 : 3; /*!< [23:21] */ uint32_t SR : 1; /*!< [24] Software Reset */ uint32_t FR : 1; /*!< [25] FIFO Reset */ uint32_t RESERVED3 : 2; /*!< [27:26] */ uint32_t BCE : 1; /*!< [28] Bit Clock Enable */ uint32_t DBGE : 1; /*!< [29] Debug Enable */ uint32_t STOPE : 1; /*!< [30] Stop Enable */ uint32_t TE : 1; /*!< [31] Transmitter Enable */ } B; } hw_i2s_tcsr_t; /*! * @name Constants and macros for entire I2S_TCSR register */ /*@{*/ #define HW_I2S_TCSR_ADDR(x) ((x) + 0x0U) #define HW_I2S_TCSR(x) (*(__IO hw_i2s_tcsr_t *) HW_I2S_TCSR_ADDR(x)) #define HW_I2S_TCSR_RD(x) (HW_I2S_TCSR(x).U) #define HW_I2S_TCSR_WR(x, v) (HW_I2S_TCSR(x).U = (v)) #define HW_I2S_TCSR_SET(x, v) (HW_I2S_TCSR_WR(x, HW_I2S_TCSR_RD(x) | (v))) #define HW_I2S_TCSR_CLR(x, v) (HW_I2S_TCSR_WR(x, HW_I2S_TCSR_RD(x) & ~(v))) #define HW_I2S_TCSR_TOG(x, v) (HW_I2S_TCSR_WR(x, HW_I2S_TCSR_RD(x) ^ (v))) /*@}*/ /* * Constants & macros for individual I2S_TCSR bitfields */ /*! * @name Register I2S_TCSR, field FRDE[0] (RW) * * Enables/disables DMA requests. * * Values: * - 0 - Disables the DMA request. * - 1 - Enables the DMA request. */ /*@{*/ #define BP_I2S_TCSR_FRDE (0U) /*!< Bit position for I2S_TCSR_FRDE. */ #define BM_I2S_TCSR_FRDE (0x00000001U) /*!< Bit mask for I2S_TCSR_FRDE. */ #define BS_I2S_TCSR_FRDE (1U) /*!< Bit field size in bits for I2S_TCSR_FRDE. */ /*! @brief Read current value of the I2S_TCSR_FRDE field. */ #define BR_I2S_TCSR_FRDE(x) (BITBAND_ACCESS32(HW_I2S_TCSR_ADDR(x), BP_I2S_TCSR_FRDE)) /*! @brief Format value for bitfield I2S_TCSR_FRDE. */ #define BF_I2S_TCSR_FRDE(v) ((uint32_t)((uint32_t)(v) << BP_I2S_TCSR_FRDE) & BM_I2S_TCSR_FRDE) /*! @brief Set the FRDE field to a new value. */ #define BW_I2S_TCSR_FRDE(x, v) (BITBAND_ACCESS32(HW_I2S_TCSR_ADDR(x), BP_I2S_TCSR_FRDE) = (v)) /*@}*/ /*! * @name Register I2S_TCSR, field FWDE[1] (RW) * * Enables/disables DMA requests. * * Values: * - 0 - Disables the DMA request. * - 1 - Enables the DMA request. */ /*@{*/ #define BP_I2S_TCSR_FWDE (1U) /*!< Bit position for I2S_TCSR_FWDE. */ #define BM_I2S_TCSR_FWDE (0x00000002U) /*!< Bit mask for I2S_TCSR_FWDE. */ #define BS_I2S_TCSR_FWDE (1U) /*!< Bit field size in bits for I2S_TCSR_FWDE. */ /*! @brief Read current value of the I2S_TCSR_FWDE field. */ #define BR_I2S_TCSR_FWDE(x) (BITBAND_ACCESS32(HW_I2S_TCSR_ADDR(x), BP_I2S_TCSR_FWDE)) /*! @brief Format value for bitfield I2S_TCSR_FWDE. */ #define BF_I2S_TCSR_FWDE(v) ((uint32_t)((uint32_t)(v) << BP_I2S_TCSR_FWDE) & BM_I2S_TCSR_FWDE) /*! @brief Set the FWDE field to a new value. */ #define BW_I2S_TCSR_FWDE(x, v) (BITBAND_ACCESS32(HW_I2S_TCSR_ADDR(x), BP_I2S_TCSR_FWDE) = (v)) /*@}*/ /*! * @name Register I2S_TCSR, field FRIE[8] (RW) * * Enables/disables FIFO request interrupts. * * Values: * - 0 - Disables the interrupt. * - 1 - Enables the interrupt. */ /*@{*/ #define BP_I2S_TCSR_FRIE (8U) /*!< Bit position for I2S_TCSR_FRIE. */ #define BM_I2S_TCSR_FRIE (0x00000100U) /*!< Bit mask for I2S_TCSR_FRIE. */ #define BS_I2S_TCSR_FRIE (1U) /*!< Bit field size in bits for I2S_TCSR_FRIE. */ /*! @brief Read current value of the I2S_TCSR_FRIE field. */ #define BR_I2S_TCSR_FRIE(x) (BITBAND_ACCESS32(HW_I2S_TCSR_ADDR(x), BP_I2S_TCSR_FRIE)) /*! @brief Format value for bitfield I2S_TCSR_FRIE. */ #define BF_I2S_TCSR_FRIE(v) ((uint32_t)((uint32_t)(v) << BP_I2S_TCSR_FRIE) & BM_I2S_TCSR_FRIE) /*! @brief Set the FRIE field to a new value. */ #define BW_I2S_TCSR_FRIE(x, v) (BITBAND_ACCESS32(HW_I2S_TCSR_ADDR(x), BP_I2S_TCSR_FRIE) = (v)) /*@}*/ /*! * @name Register I2S_TCSR, field FWIE[9] (RW) * * Enables/disables FIFO warning interrupts. * * Values: * - 0 - Disables the interrupt. * - 1 - Enables the interrupt. */ /*@{*/ #define BP_I2S_TCSR_FWIE (9U) /*!< Bit position for I2S_TCSR_FWIE. */ #define BM_I2S_TCSR_FWIE (0x00000200U) /*!< Bit mask for I2S_TCSR_FWIE. */ #define BS_I2S_TCSR_FWIE (1U) /*!< Bit field size in bits for I2S_TCSR_FWIE. */ /*! @brief Read current value of the I2S_TCSR_FWIE field. */ #define BR_I2S_TCSR_FWIE(x) (BITBAND_ACCESS32(HW_I2S_TCSR_ADDR(x), BP_I2S_TCSR_FWIE)) /*! @brief Format value for bitfield I2S_TCSR_FWIE. */ #define BF_I2S_TCSR_FWIE(v) ((uint32_t)((uint32_t)(v) << BP_I2S_TCSR_FWIE) & BM_I2S_TCSR_FWIE) /*! @brief Set the FWIE field to a new value. */ #define BW_I2S_TCSR_FWIE(x, v) (BITBAND_ACCESS32(HW_I2S_TCSR_ADDR(x), BP_I2S_TCSR_FWIE) = (v)) /*@}*/ /*! * @name Register I2S_TCSR, field FEIE[10] (RW) * * Enables/disables FIFO error interrupts. * * Values: * - 0 - Disables the interrupt. * - 1 - Enables the interrupt. */ /*@{*/ #define BP_I2S_TCSR_FEIE (10U) /*!< Bit position for I2S_TCSR_FEIE. */ #define BM_I2S_TCSR_FEIE (0x00000400U) /*!< Bit mask for I2S_TCSR_FEIE. */ #define BS_I2S_TCSR_FEIE (1U) /*!< Bit field size in bits for I2S_TCSR_FEIE. */ /*! @brief Read current value of the I2S_TCSR_FEIE field. */ #define BR_I2S_TCSR_FEIE(x) (BITBAND_ACCESS32(HW_I2S_TCSR_ADDR(x), BP_I2S_TCSR_FEIE)) /*! @brief Format value for bitfield I2S_TCSR_FEIE. */ #define BF_I2S_TCSR_FEIE(v) ((uint32_t)((uint32_t)(v) << BP_I2S_TCSR_FEIE) & BM_I2S_TCSR_FEIE) /*! @brief Set the FEIE field to a new value. */ #define BW_I2S_TCSR_FEIE(x, v) (BITBAND_ACCESS32(HW_I2S_TCSR_ADDR(x), BP_I2S_TCSR_FEIE) = (v)) /*@}*/ /*! * @name Register I2S_TCSR, field SEIE[11] (RW) * * Enables/disables sync error interrupts. * * Values: * - 0 - Disables interrupt. * - 1 - Enables interrupt. */ /*@{*/ #define BP_I2S_TCSR_SEIE (11U) /*!< Bit position for I2S_TCSR_SEIE. */ #define BM_I2S_TCSR_SEIE (0x00000800U) /*!< Bit mask for I2S_TCSR_SEIE. */ #define BS_I2S_TCSR_SEIE (1U) /*!< Bit field size in bits for I2S_TCSR_SEIE. */ /*! @brief Read current value of the I2S_TCSR_SEIE field. */ #define BR_I2S_TCSR_SEIE(x) (BITBAND_ACCESS32(HW_I2S_TCSR_ADDR(x), BP_I2S_TCSR_SEIE)) /*! @brief Format value for bitfield I2S_TCSR_SEIE. */ #define BF_I2S_TCSR_SEIE(v) ((uint32_t)((uint32_t)(v) << BP_I2S_TCSR_SEIE) & BM_I2S_TCSR_SEIE) /*! @brief Set the SEIE field to a new value. */ #define BW_I2S_TCSR_SEIE(x, v) (BITBAND_ACCESS32(HW_I2S_TCSR_ADDR(x), BP_I2S_TCSR_SEIE) = (v)) /*@}*/ /*! * @name Register I2S_TCSR, field WSIE[12] (RW) * * Enables/disables word start interrupts. * * Values: * - 0 - Disables interrupt. * - 1 - Enables interrupt. */ /*@{*/ #define BP_I2S_TCSR_WSIE (12U) /*!< Bit position for I2S_TCSR_WSIE. */ #define BM_I2S_TCSR_WSIE (0x00001000U) /*!< Bit mask for I2S_TCSR_WSIE. */ #define BS_I2S_TCSR_WSIE (1U) /*!< Bit field size in bits for I2S_TCSR_WSIE. */ /*! @brief Read current value of the I2S_TCSR_WSIE field. */ #define BR_I2S_TCSR_WSIE(x) (BITBAND_ACCESS32(HW_I2S_TCSR_ADDR(x), BP_I2S_TCSR_WSIE)) /*! @brief Format value for bitfield I2S_TCSR_WSIE. */ #define BF_I2S_TCSR_WSIE(v) ((uint32_t)((uint32_t)(v) << BP_I2S_TCSR_WSIE) & BM_I2S_TCSR_WSIE) /*! @brief Set the WSIE field to a new value. */ #define BW_I2S_TCSR_WSIE(x, v) (BITBAND_ACCESS32(HW_I2S_TCSR_ADDR(x), BP_I2S_TCSR_WSIE) = (v)) /*@}*/ /*! * @name Register I2S_TCSR, field FRF[16] (RO) * * Indicates that the number of words in an enabled transmit channel FIFO is * less than or equal to the transmit FIFO watermark. * * Values: * - 0 - Transmit FIFO watermark has not been reached. * - 1 - Transmit FIFO watermark has been reached. */ /*@{*/ #define BP_I2S_TCSR_FRF (16U) /*!< Bit position for I2S_TCSR_FRF. */ #define BM_I2S_TCSR_FRF (0x00010000U) /*!< Bit mask for I2S_TCSR_FRF. */ #define BS_I2S_TCSR_FRF (1U) /*!< Bit field size in bits for I2S_TCSR_FRF. */ /*! @brief Read current value of the I2S_TCSR_FRF field. */ #define BR_I2S_TCSR_FRF(x) (BITBAND_ACCESS32(HW_I2S_TCSR_ADDR(x), BP_I2S_TCSR_FRF)) /*@}*/ /*! * @name Register I2S_TCSR, field FWF[17] (RO) * * Indicates that an enabled transmit FIFO is empty. * * Values: * - 0 - No enabled transmit FIFO is empty. * - 1 - Enabled transmit FIFO is empty. */ /*@{*/ #define BP_I2S_TCSR_FWF (17U) /*!< Bit position for I2S_TCSR_FWF. */ #define BM_I2S_TCSR_FWF (0x00020000U) /*!< Bit mask for I2S_TCSR_FWF. */ #define BS_I2S_TCSR_FWF (1U) /*!< Bit field size in bits for I2S_TCSR_FWF. */ /*! @brief Read current value of the I2S_TCSR_FWF field. */ #define BR_I2S_TCSR_FWF(x) (BITBAND_ACCESS32(HW_I2S_TCSR_ADDR(x), BP_I2S_TCSR_FWF)) /*@}*/ /*! * @name Register I2S_TCSR, field FEF[18] (W1C) * * Indicates that an enabled transmit FIFO has underrun. Write a logic 1 to this * field to clear this flag. * * Values: * - 0 - Transmit underrun not detected. * - 1 - Transmit underrun detected. */ /*@{*/ #define BP_I2S_TCSR_FEF (18U) /*!< Bit position for I2S_TCSR_FEF. */ #define BM_I2S_TCSR_FEF (0x00040000U) /*!< Bit mask for I2S_TCSR_FEF. */ #define BS_I2S_TCSR_FEF (1U) /*!< Bit field size in bits for I2S_TCSR_FEF. */ /*! @brief Read current value of the I2S_TCSR_FEF field. */ #define BR_I2S_TCSR_FEF(x) (BITBAND_ACCESS32(HW_I2S_TCSR_ADDR(x), BP_I2S_TCSR_FEF)) /*! @brief Format value for bitfield I2S_TCSR_FEF. */ #define BF_I2S_TCSR_FEF(v) ((uint32_t)((uint32_t)(v) << BP_I2S_TCSR_FEF) & BM_I2S_TCSR_FEF) /*! @brief Set the FEF field to a new value. */ #define BW_I2S_TCSR_FEF(x, v) (BITBAND_ACCESS32(HW_I2S_TCSR_ADDR(x), BP_I2S_TCSR_FEF) = (v)) /*@}*/ /*! * @name Register I2S_TCSR, field SEF[19] (W1C) * * Indicates that an error in the externally-generated frame sync has been * detected. Write a logic 1 to this field to clear this flag. * * Values: * - 0 - Sync error not detected. * - 1 - Frame sync error detected. */ /*@{*/ #define BP_I2S_TCSR_SEF (19U) /*!< Bit position for I2S_TCSR_SEF. */ #define BM_I2S_TCSR_SEF (0x00080000U) /*!< Bit mask for I2S_TCSR_SEF. */ #define BS_I2S_TCSR_SEF (1U) /*!< Bit field size in bits for I2S_TCSR_SEF. */ /*! @brief Read current value of the I2S_TCSR_SEF field. */ #define BR_I2S_TCSR_SEF(x) (BITBAND_ACCESS32(HW_I2S_TCSR_ADDR(x), BP_I2S_TCSR_SEF)) /*! @brief Format value for bitfield I2S_TCSR_SEF. */ #define BF_I2S_TCSR_SEF(v) ((uint32_t)((uint32_t)(v) << BP_I2S_TCSR_SEF) & BM_I2S_TCSR_SEF) /*! @brief Set the SEF field to a new value. */ #define BW_I2S_TCSR_SEF(x, v) (BITBAND_ACCESS32(HW_I2S_TCSR_ADDR(x), BP_I2S_TCSR_SEF) = (v)) /*@}*/ /*! * @name Register I2S_TCSR, field WSF[20] (W1C) * * Indicates that the start of the configured word has been detected. Write a * logic 1 to this field to clear this flag. * * Values: * - 0 - Start of word not detected. * - 1 - Start of word detected. */ /*@{*/ #define BP_I2S_TCSR_WSF (20U) /*!< Bit position for I2S_TCSR_WSF. */ #define BM_I2S_TCSR_WSF (0x00100000U) /*!< Bit mask for I2S_TCSR_WSF. */ #define BS_I2S_TCSR_WSF (1U) /*!< Bit field size in bits for I2S_TCSR_WSF. */ /*! @brief Read current value of the I2S_TCSR_WSF field. */ #define BR_I2S_TCSR_WSF(x) (BITBAND_ACCESS32(HW_I2S_TCSR_ADDR(x), BP_I2S_TCSR_WSF)) /*! @brief Format value for bitfield I2S_TCSR_WSF. */ #define BF_I2S_TCSR_WSF(v) ((uint32_t)((uint32_t)(v) << BP_I2S_TCSR_WSF) & BM_I2S_TCSR_WSF) /*! @brief Set the WSF field to a new value. */ #define BW_I2S_TCSR_WSF(x, v) (BITBAND_ACCESS32(HW_I2S_TCSR_ADDR(x), BP_I2S_TCSR_WSF) = (v)) /*@}*/ /*! * @name Register I2S_TCSR, field SR[24] (RW) * * When set, resets the internal transmitter logic including the FIFO pointers. * Software-visible registers are not affected, except for the status registers. * * Values: * - 0 - No effect. * - 1 - Software reset. */ /*@{*/ #define BP_I2S_TCSR_SR (24U) /*!< Bit position for I2S_TCSR_SR. */ #define BM_I2S_TCSR_SR (0x01000000U) /*!< Bit mask for I2S_TCSR_SR. */ #define BS_I2S_TCSR_SR (1U) /*!< Bit field size in bits for I2S_TCSR_SR. */ /*! @brief Read current value of the I2S_TCSR_SR field. */ #define BR_I2S_TCSR_SR(x) (BITBAND_ACCESS32(HW_I2S_TCSR_ADDR(x), BP_I2S_TCSR_SR)) /*! @brief Format value for bitfield I2S_TCSR_SR. */ #define BF_I2S_TCSR_SR(v) ((uint32_t)((uint32_t)(v) << BP_I2S_TCSR_SR) & BM_I2S_TCSR_SR) /*! @brief Set the SR field to a new value. */ #define BW_I2S_TCSR_SR(x, v) (BITBAND_ACCESS32(HW_I2S_TCSR_ADDR(x), BP_I2S_TCSR_SR) = (v)) /*@}*/ /*! * @name Register I2S_TCSR, field FR[25] (WORZ) * * Resets the FIFO pointers. Reading this field will always return zero. FIFO * pointers should only be reset when the transmitter is disabled or the FIFO error * flag is set. * * Values: * - 0 - No effect. * - 1 - FIFO reset. */ /*@{*/ #define BP_I2S_TCSR_FR (25U) /*!< Bit position for I2S_TCSR_FR. */ #define BM_I2S_TCSR_FR (0x02000000U) /*!< Bit mask for I2S_TCSR_FR. */ #define BS_I2S_TCSR_FR (1U) /*!< Bit field size in bits for I2S_TCSR_FR. */ /*! @brief Format value for bitfield I2S_TCSR_FR. */ #define BF_I2S_TCSR_FR(v) ((uint32_t)((uint32_t)(v) << BP_I2S_TCSR_FR) & BM_I2S_TCSR_FR) /*! @brief Set the FR field to a new value. */ #define BW_I2S_TCSR_FR(x, v) (BITBAND_ACCESS32(HW_I2S_TCSR_ADDR(x), BP_I2S_TCSR_FR) = (v)) /*@}*/ /*! * @name Register I2S_TCSR, field BCE[28] (RW) * * Enables the transmit bit clock, separately from the TE. This field is * automatically set whenever TE is set. When software clears this field, the transmit * bit clock remains enabled, and this bit remains set, until the end of the * current frame. * * Values: * - 0 - Transmit bit clock is disabled. * - 1 - Transmit bit clock is enabled. */ /*@{*/ #define BP_I2S_TCSR_BCE (28U) /*!< Bit position for I2S_TCSR_BCE. */ #define BM_I2S_TCSR_BCE (0x10000000U) /*!< Bit mask for I2S_TCSR_BCE. */ #define BS_I2S_TCSR_BCE (1U) /*!< Bit field size in bits for I2S_TCSR_BCE. */ /*! @brief Read current value of the I2S_TCSR_BCE field. */ #define BR_I2S_TCSR_BCE(x) (BITBAND_ACCESS32(HW_I2S_TCSR_ADDR(x), BP_I2S_TCSR_BCE)) /*! @brief Format value for bitfield I2S_TCSR_BCE. */ #define BF_I2S_TCSR_BCE(v) ((uint32_t)((uint32_t)(v) << BP_I2S_TCSR_BCE) & BM_I2S_TCSR_BCE) /*! @brief Set the BCE field to a new value. */ #define BW_I2S_TCSR_BCE(x, v) (BITBAND_ACCESS32(HW_I2S_TCSR_ADDR(x), BP_I2S_TCSR_BCE) = (v)) /*@}*/ /*! * @name Register I2S_TCSR, field DBGE[29] (RW) * * Enables/disables transmitter operation in Debug mode. The transmit bit clock * is not affected by debug mode. * * Values: * - 0 - Transmitter is disabled in Debug mode, after completing the current * frame. * - 1 - Transmitter is enabled in Debug mode. */ /*@{*/ #define BP_I2S_TCSR_DBGE (29U) /*!< Bit position for I2S_TCSR_DBGE. */ #define BM_I2S_TCSR_DBGE (0x20000000U) /*!< Bit mask for I2S_TCSR_DBGE. */ #define BS_I2S_TCSR_DBGE (1U) /*!< Bit field size in bits for I2S_TCSR_DBGE. */ /*! @brief Read current value of the I2S_TCSR_DBGE field. */ #define BR_I2S_TCSR_DBGE(x) (BITBAND_ACCESS32(HW_I2S_TCSR_ADDR(x), BP_I2S_TCSR_DBGE)) /*! @brief Format value for bitfield I2S_TCSR_DBGE. */ #define BF_I2S_TCSR_DBGE(v) ((uint32_t)((uint32_t)(v) << BP_I2S_TCSR_DBGE) & BM_I2S_TCSR_DBGE) /*! @brief Set the DBGE field to a new value. */ #define BW_I2S_TCSR_DBGE(x, v) (BITBAND_ACCESS32(HW_I2S_TCSR_ADDR(x), BP_I2S_TCSR_DBGE) = (v)) /*@}*/ /*! * @name Register I2S_TCSR, field STOPE[30] (RW) * * Configures transmitter operation in Stop mode. This field is ignored and the * transmitter is disabled in all low-leakage stop modes. * * Values: * - 0 - Transmitter disabled in Stop mode. * - 1 - Transmitter enabled in Stop mode. */ /*@{*/ #define BP_I2S_TCSR_STOPE (30U) /*!< Bit position for I2S_TCSR_STOPE. */ #define BM_I2S_TCSR_STOPE (0x40000000U) /*!< Bit mask for I2S_TCSR_STOPE. */ #define BS_I2S_TCSR_STOPE (1U) /*!< Bit field size in bits for I2S_TCSR_STOPE. */ /*! @brief Read current value of the I2S_TCSR_STOPE field. */ #define BR_I2S_TCSR_STOPE(x) (BITBAND_ACCESS32(HW_I2S_TCSR_ADDR(x), BP_I2S_TCSR_STOPE)) /*! @brief Format value for bitfield I2S_TCSR_STOPE. */ #define BF_I2S_TCSR_STOPE(v) ((uint32_t)((uint32_t)(v) << BP_I2S_TCSR_STOPE) & BM_I2S_TCSR_STOPE) /*! @brief Set the STOPE field to a new value. */ #define BW_I2S_TCSR_STOPE(x, v) (BITBAND_ACCESS32(HW_I2S_TCSR_ADDR(x), BP_I2S_TCSR_STOPE) = (v)) /*@}*/ /*! * @name Register I2S_TCSR, field TE[31] (RW) * * Enables/disables the transmitter. When software clears this field, the * transmitter remains enabled, and this bit remains set, until the end of the current * frame. * * Values: * - 0 - Transmitter is disabled. * - 1 - Transmitter is enabled, or transmitter has been disabled and has not * yet reached end of frame. */ /*@{*/ #define BP_I2S_TCSR_TE (31U) /*!< Bit position for I2S_TCSR_TE. */ #define BM_I2S_TCSR_TE (0x80000000U) /*!< Bit mask for I2S_TCSR_TE. */ #define BS_I2S_TCSR_TE (1U) /*!< Bit field size in bits for I2S_TCSR_TE. */ /*! @brief Read current value of the I2S_TCSR_TE field. */ #define BR_I2S_TCSR_TE(x) (BITBAND_ACCESS32(HW_I2S_TCSR_ADDR(x), BP_I2S_TCSR_TE)) /*! @brief Format value for bitfield I2S_TCSR_TE. */ #define BF_I2S_TCSR_TE(v) ((uint32_t)((uint32_t)(v) << BP_I2S_TCSR_TE) & BM_I2S_TCSR_TE) /*! @brief Set the TE field to a new value. */ #define BW_I2S_TCSR_TE(x, v) (BITBAND_ACCESS32(HW_I2S_TCSR_ADDR(x), BP_I2S_TCSR_TE) = (v)) /*@}*/ /******************************************************************************* * HW_I2S_TCR1 - SAI Transmit Configuration 1 Register ******************************************************************************/ /*! * @brief HW_I2S_TCR1 - SAI Transmit Configuration 1 Register (RW) * * Reset value: 0x00000000U */ typedef union _hw_i2s_tcr1 { uint32_t U; struct _hw_i2s_tcr1_bitfields { uint32_t TFW : 3; /*!< [2:0] Transmit FIFO Watermark */ uint32_t RESERVED0 : 29; /*!< [31:3] */ } B; } hw_i2s_tcr1_t; /*! * @name Constants and macros for entire I2S_TCR1 register */ /*@{*/ #define HW_I2S_TCR1_ADDR(x) ((x) + 0x4U) #define HW_I2S_TCR1(x) (*(__IO hw_i2s_tcr1_t *) HW_I2S_TCR1_ADDR(x)) #define HW_I2S_TCR1_RD(x) (HW_I2S_TCR1(x).U) #define HW_I2S_TCR1_WR(x, v) (HW_I2S_TCR1(x).U = (v)) #define HW_I2S_TCR1_SET(x, v) (HW_I2S_TCR1_WR(x, HW_I2S_TCR1_RD(x) | (v))) #define HW_I2S_TCR1_CLR(x, v) (HW_I2S_TCR1_WR(x, HW_I2S_TCR1_RD(x) & ~(v))) #define HW_I2S_TCR1_TOG(x, v) (HW_I2S_TCR1_WR(x, HW_I2S_TCR1_RD(x) ^ (v))) /*@}*/ /* * Constants & macros for individual I2S_TCR1 bitfields */ /*! * @name Register I2S_TCR1, field TFW[2:0] (RW) * * Configures the watermark level for all enabled transmit channels. */ /*@{*/ #define BP_I2S_TCR1_TFW (0U) /*!< Bit position for I2S_TCR1_TFW. */ #define BM_I2S_TCR1_TFW (0x00000007U) /*!< Bit mask for I2S_TCR1_TFW. */ #define BS_I2S_TCR1_TFW (3U) /*!< Bit field size in bits for I2S_TCR1_TFW. */ /*! @brief Read current value of the I2S_TCR1_TFW field. */ #define BR_I2S_TCR1_TFW(x) (HW_I2S_TCR1(x).B.TFW) /*! @brief Format value for bitfield I2S_TCR1_TFW. */ #define BF_I2S_TCR1_TFW(v) ((uint32_t)((uint32_t)(v) << BP_I2S_TCR1_TFW) & BM_I2S_TCR1_TFW) /*! @brief Set the TFW field to a new value. */ #define BW_I2S_TCR1_TFW(x, v) (HW_I2S_TCR1_WR(x, (HW_I2S_TCR1_RD(x) & ~BM_I2S_TCR1_TFW) | BF_I2S_TCR1_TFW(v))) /*@}*/ /******************************************************************************* * HW_I2S_TCR2 - SAI Transmit Configuration 2 Register ******************************************************************************/ /*! * @brief HW_I2S_TCR2 - SAI Transmit Configuration 2 Register (RW) * * Reset value: 0x00000000U * * This register must not be altered when TCSR[TE] is set. */ typedef union _hw_i2s_tcr2 { uint32_t U; struct _hw_i2s_tcr2_bitfields { uint32_t DIV : 8; /*!< [7:0] Bit Clock Divide */ uint32_t RESERVED0 : 16; /*!< [23:8] */ uint32_t BCD : 1; /*!< [24] Bit Clock Direction */ uint32_t BCP : 1; /*!< [25] Bit Clock Polarity */ uint32_t MSEL : 2; /*!< [27:26] MCLK Select */ uint32_t BCI : 1; /*!< [28] Bit Clock Input */ uint32_t BCS : 1; /*!< [29] Bit Clock Swap */ uint32_t SYNC : 2; /*!< [31:30] Synchronous Mode */ } B; } hw_i2s_tcr2_t; /*! * @name Constants and macros for entire I2S_TCR2 register */ /*@{*/ #define HW_I2S_TCR2_ADDR(x) ((x) + 0x8U) #define HW_I2S_TCR2(x) (*(__IO hw_i2s_tcr2_t *) HW_I2S_TCR2_ADDR(x)) #define HW_I2S_TCR2_RD(x) (HW_I2S_TCR2(x).U) #define HW_I2S_TCR2_WR(x, v) (HW_I2S_TCR2(x).U = (v)) #define HW_I2S_TCR2_SET(x, v) (HW_I2S_TCR2_WR(x, HW_I2S_TCR2_RD(x) | (v))) #define HW_I2S_TCR2_CLR(x, v) (HW_I2S_TCR2_WR(x, HW_I2S_TCR2_RD(x) & ~(v))) #define HW_I2S_TCR2_TOG(x, v) (HW_I2S_TCR2_WR(x, HW_I2S_TCR2_RD(x) ^ (v))) /*@}*/ /* * Constants & macros for individual I2S_TCR2 bitfields */ /*! * @name Register I2S_TCR2, field DIV[7:0] (RW) * * Divides down the audio master clock to generate the bit clock when configured * for an internal bit clock. The division value is (DIV + 1) * 2. */ /*@{*/ #define BP_I2S_TCR2_DIV (0U) /*!< Bit position for I2S_TCR2_DIV. */ #define BM_I2S_TCR2_DIV (0x000000FFU) /*!< Bit mask for I2S_TCR2_DIV. */ #define BS_I2S_TCR2_DIV (8U) /*!< Bit field size in bits for I2S_TCR2_DIV. */ /*! @brief Read current value of the I2S_TCR2_DIV field. */ #define BR_I2S_TCR2_DIV(x) (HW_I2S_TCR2(x).B.DIV) /*! @brief Format value for bitfield I2S_TCR2_DIV. */ #define BF_I2S_TCR2_DIV(v) ((uint32_t)((uint32_t)(v) << BP_I2S_TCR2_DIV) & BM_I2S_TCR2_DIV) /*! @brief Set the DIV field to a new value. */ #define BW_I2S_TCR2_DIV(x, v) (HW_I2S_TCR2_WR(x, (HW_I2S_TCR2_RD(x) & ~BM_I2S_TCR2_DIV) | BF_I2S_TCR2_DIV(v))) /*@}*/ /*! * @name Register I2S_TCR2, field BCD[24] (RW) * * Configures the direction of the bit clock. * * Values: * - 0 - Bit clock is generated externally in Slave mode. * - 1 - Bit clock is generated internally in Master mode. */ /*@{*/ #define BP_I2S_TCR2_BCD (24U) /*!< Bit position for I2S_TCR2_BCD. */ #define BM_I2S_TCR2_BCD (0x01000000U) /*!< Bit mask for I2S_TCR2_BCD. */ #define BS_I2S_TCR2_BCD (1U) /*!< Bit field size in bits for I2S_TCR2_BCD. */ /*! @brief Read current value of the I2S_TCR2_BCD field. */ #define BR_I2S_TCR2_BCD(x) (BITBAND_ACCESS32(HW_I2S_TCR2_ADDR(x), BP_I2S_TCR2_BCD)) /*! @brief Format value for bitfield I2S_TCR2_BCD. */ #define BF_I2S_TCR2_BCD(v) ((uint32_t)((uint32_t)(v) << BP_I2S_TCR2_BCD) & BM_I2S_TCR2_BCD) /*! @brief Set the BCD field to a new value. */ #define BW_I2S_TCR2_BCD(x, v) (BITBAND_ACCESS32(HW_I2S_TCR2_ADDR(x), BP_I2S_TCR2_BCD) = (v)) /*@}*/ /*! * @name Register I2S_TCR2, field BCP[25] (RW) * * Configures the polarity of the bit clock. * * Values: * - 0 - Bit clock is active high with drive outputs on rising edge and sample * inputs on falling edge. * - 1 - Bit clock is active low with drive outputs on falling edge and sample * inputs on rising edge. */ /*@{*/ #define BP_I2S_TCR2_BCP (25U) /*!< Bit position for I2S_TCR2_BCP. */ #define BM_I2S_TCR2_BCP (0x02000000U) /*!< Bit mask for I2S_TCR2_BCP. */ #define BS_I2S_TCR2_BCP (1U) /*!< Bit field size in bits for I2S_TCR2_BCP. */ /*! @brief Read current value of the I2S_TCR2_BCP field. */ #define BR_I2S_TCR2_BCP(x) (BITBAND_ACCESS32(HW_I2S_TCR2_ADDR(x), BP_I2S_TCR2_BCP)) /*! @brief Format value for bitfield I2S_TCR2_BCP. */ #define BF_I2S_TCR2_BCP(v) ((uint32_t)((uint32_t)(v) << BP_I2S_TCR2_BCP) & BM_I2S_TCR2_BCP) /*! @brief Set the BCP field to a new value. */ #define BW_I2S_TCR2_BCP(x, v) (BITBAND_ACCESS32(HW_I2S_TCR2_ADDR(x), BP_I2S_TCR2_BCP) = (v)) /*@}*/ /*! * @name Register I2S_TCR2, field MSEL[27:26] (RW) * * Selects the audio Master Clock option used to generate an internally * generated bit clock. This field has no effect when configured for an externally * generated bit clock. Depending on the device, some Master Clock options might not be * available. See the chip configuration details for the availability and * chip-specific meaning of each option. * * Values: * - 00 - Bus Clock selected. * - 01 - Master Clock (MCLK) 1 option selected. * - 10 - Master Clock (MCLK) 2 option selected. * - 11 - Master Clock (MCLK) 3 option selected. */ /*@{*/ #define BP_I2S_TCR2_MSEL (26U) /*!< Bit position for I2S_TCR2_MSEL. */ #define BM_I2S_TCR2_MSEL (0x0C000000U) /*!< Bit mask for I2S_TCR2_MSEL. */ #define BS_I2S_TCR2_MSEL (2U) /*!< Bit field size in bits for I2S_TCR2_MSEL. */ /*! @brief Read current value of the I2S_TCR2_MSEL field. */ #define BR_I2S_TCR2_MSEL(x) (HW_I2S_TCR2(x).B.MSEL) /*! @brief Format value for bitfield I2S_TCR2_MSEL. */ #define BF_I2S_TCR2_MSEL(v) ((uint32_t)((uint32_t)(v) << BP_I2S_TCR2_MSEL) & BM_I2S_TCR2_MSEL) /*! @brief Set the MSEL field to a new value. */ #define BW_I2S_TCR2_MSEL(x, v) (HW_I2S_TCR2_WR(x, (HW_I2S_TCR2_RD(x) & ~BM_I2S_TCR2_MSEL) | BF_I2S_TCR2_MSEL(v))) /*@}*/ /*! * @name Register I2S_TCR2, field BCI[28] (RW) * * When this field is set and using an internally generated bit clock in either * synchronous or asynchronous mode, the bit clock actually used by the * transmitter is delayed by the pad output delay (the transmitter is clocked by the pad * input as if the clock was externally generated). This has the effect of * decreasing the data input setup time, but increasing the data output valid time. The * slave mode timing from the datasheet should be used for the transmitter when * this bit is set. In synchronous mode, this bit allows the transmitter to use * the slave mode timing from the datasheet, while the receiver uses the master * mode timing. This field has no effect when configured for an externally generated * bit clock or when synchronous to another SAI peripheral . * * Values: * - 0 - No effect. * - 1 - Internal logic is clocked as if bit clock was externally generated. */ /*@{*/ #define BP_I2S_TCR2_BCI (28U) /*!< Bit position for I2S_TCR2_BCI. */ #define BM_I2S_TCR2_BCI (0x10000000U) /*!< Bit mask for I2S_TCR2_BCI. */ #define BS_I2S_TCR2_BCI (1U) /*!< Bit field size in bits for I2S_TCR2_BCI. */ /*! @brief Read current value of the I2S_TCR2_BCI field. */ #define BR_I2S_TCR2_BCI(x) (BITBAND_ACCESS32(HW_I2S_TCR2_ADDR(x), BP_I2S_TCR2_BCI)) /*! @brief Format value for bitfield I2S_TCR2_BCI. */ #define BF_I2S_TCR2_BCI(v) ((uint32_t)((uint32_t)(v) << BP_I2S_TCR2_BCI) & BM_I2S_TCR2_BCI) /*! @brief Set the BCI field to a new value. */ #define BW_I2S_TCR2_BCI(x, v) (BITBAND_ACCESS32(HW_I2S_TCR2_ADDR(x), BP_I2S_TCR2_BCI) = (v)) /*@}*/ /*! * @name Register I2S_TCR2, field BCS[29] (RW) * * This field swaps the bit clock used by the transmitter. When the transmitter * is configured in asynchronous mode and this bit is set, the transmitter is * clocked by the receiver bit clock (SAI_RX_BCLK). This allows the transmitter and * receiver to share the same bit clock, but the transmitter continues to use the * transmit frame sync (SAI_TX_SYNC). When the transmitter is configured in * synchronous mode, the transmitter BCS field and receiver BCS field must be set to * the same value. When both are set, the transmitter and receiver are both * clocked by the transmitter bit clock (SAI_TX_BCLK) but use the receiver frame sync * (SAI_RX_SYNC). This field has no effect when synchronous to another SAI * peripheral. * * Values: * - 0 - Use the normal bit clock source. * - 1 - Swap the bit clock source. */ /*@{*/ #define BP_I2S_TCR2_BCS (29U) /*!< Bit position for I2S_TCR2_BCS. */ #define BM_I2S_TCR2_BCS (0x20000000U) /*!< Bit mask for I2S_TCR2_BCS. */ #define BS_I2S_TCR2_BCS (1U) /*!< Bit field size in bits for I2S_TCR2_BCS. */ /*! @brief Read current value of the I2S_TCR2_BCS field. */ #define BR_I2S_TCR2_BCS(x) (BITBAND_ACCESS32(HW_I2S_TCR2_ADDR(x), BP_I2S_TCR2_BCS)) /*! @brief Format value for bitfield I2S_TCR2_BCS. */ #define BF_I2S_TCR2_BCS(v) ((uint32_t)((uint32_t)(v) << BP_I2S_TCR2_BCS) & BM_I2S_TCR2_BCS) /*! @brief Set the BCS field to a new value. */ #define BW_I2S_TCR2_BCS(x, v) (BITBAND_ACCESS32(HW_I2S_TCR2_ADDR(x), BP_I2S_TCR2_BCS) = (v)) /*@}*/ /*! * @name Register I2S_TCR2, field SYNC[31:30] (RW) * * Configures between asynchronous and synchronous modes of operation. When * configured for a synchronous mode of operation, the receiver or other SAI * peripheral must be configured for asynchronous operation. * * Values: * - 00 - Asynchronous mode. * - 01 - Synchronous with receiver. * - 10 - Synchronous with another SAI transmitter. * - 11 - Synchronous with another SAI receiver. */ /*@{*/ #define BP_I2S_TCR2_SYNC (30U) /*!< Bit position for I2S_TCR2_SYNC. */ #define BM_I2S_TCR2_SYNC (0xC0000000U) /*!< Bit mask for I2S_TCR2_SYNC. */ #define BS_I2S_TCR2_SYNC (2U) /*!< Bit field size in bits for I2S_TCR2_SYNC. */ /*! @brief Read current value of the I2S_TCR2_SYNC field. */ #define BR_I2S_TCR2_SYNC(x) (HW_I2S_TCR2(x).B.SYNC) /*! @brief Format value for bitfield I2S_TCR2_SYNC. */ #define BF_I2S_TCR2_SYNC(v) ((uint32_t)((uint32_t)(v) << BP_I2S_TCR2_SYNC) & BM_I2S_TCR2_SYNC) /*! @brief Set the SYNC field to a new value. */ #define BW_I2S_TCR2_SYNC(x, v) (HW_I2S_TCR2_WR(x, (HW_I2S_TCR2_RD(x) & ~BM_I2S_TCR2_SYNC) | BF_I2S_TCR2_SYNC(v))) /*@}*/ /******************************************************************************* * HW_I2S_TCR3 - SAI Transmit Configuration 3 Register ******************************************************************************/ /*! * @brief HW_I2S_TCR3 - SAI Transmit Configuration 3 Register (RW) * * Reset value: 0x00000000U * * This register must not be altered when TCSR[TE] is set. */ typedef union _hw_i2s_tcr3 { uint32_t U; struct _hw_i2s_tcr3_bitfields { uint32_t WDFL : 5; /*!< [4:0] Word Flag Configuration */ uint32_t RESERVED0 : 11; /*!< [15:5] */ uint32_t TCE : 2; /*!< [17:16] Transmit Channel Enable */ uint32_t RESERVED1 : 14; /*!< [31:18] */ } B; } hw_i2s_tcr3_t; /*! * @name Constants and macros for entire I2S_TCR3 register */ /*@{*/ #define HW_I2S_TCR3_ADDR(x) ((x) + 0xCU) #define HW_I2S_TCR3(x) (*(__IO hw_i2s_tcr3_t *) HW_I2S_TCR3_ADDR(x)) #define HW_I2S_TCR3_RD(x) (HW_I2S_TCR3(x).U) #define HW_I2S_TCR3_WR(x, v) (HW_I2S_TCR3(x).U = (v)) #define HW_I2S_TCR3_SET(x, v) (HW_I2S_TCR3_WR(x, HW_I2S_TCR3_RD(x) | (v))) #define HW_I2S_TCR3_CLR(x, v) (HW_I2S_TCR3_WR(x, HW_I2S_TCR3_RD(x) & ~(v))) #define HW_I2S_TCR3_TOG(x, v) (HW_I2S_TCR3_WR(x, HW_I2S_TCR3_RD(x) ^ (v))) /*@}*/ /* * Constants & macros for individual I2S_TCR3 bitfields */ /*! * @name Register I2S_TCR3, field WDFL[4:0] (RW) * * Configures which word sets the start of word flag. The value written must be * one less than the word number. For example, writing 0 configures the first * word in the frame. When configured to a value greater than TCR4[FRSZ], then the * start of word flag is never set. */ /*@{*/ #define BP_I2S_TCR3_WDFL (0U) /*!< Bit position for I2S_TCR3_WDFL. */ #define BM_I2S_TCR3_WDFL (0x0000001FU) /*!< Bit mask for I2S_TCR3_WDFL. */ #define BS_I2S_TCR3_WDFL (5U) /*!< Bit field size in bits for I2S_TCR3_WDFL. */ /*! @brief Read current value of the I2S_TCR3_WDFL field. */ #define BR_I2S_TCR3_WDFL(x) (HW_I2S_TCR3(x).B.WDFL) /*! @brief Format value for bitfield I2S_TCR3_WDFL. */ #define BF_I2S_TCR3_WDFL(v) ((uint32_t)((uint32_t)(v) << BP_I2S_TCR3_WDFL) & BM_I2S_TCR3_WDFL) /*! @brief Set the WDFL field to a new value. */ #define BW_I2S_TCR3_WDFL(x, v) (HW_I2S_TCR3_WR(x, (HW_I2S_TCR3_RD(x) & ~BM_I2S_TCR3_WDFL) | BF_I2S_TCR3_WDFL(v))) /*@}*/ /*! * @name Register I2S_TCR3, field TCE[17:16] (RW) * * Enables the corresponding data channel for transmit operation. A channel must * be enabled before its FIFO is accessed. * * Values: * - 0 - Transmit data channel N is disabled. * - 1 - Transmit data channel N is enabled. */ /*@{*/ #define BP_I2S_TCR3_TCE (16U) /*!< Bit position for I2S_TCR3_TCE. */ #define BM_I2S_TCR3_TCE (0x00030000U) /*!< Bit mask for I2S_TCR3_TCE. */ #define BS_I2S_TCR3_TCE (2U) /*!< Bit field size in bits for I2S_TCR3_TCE. */ /*! @brief Read current value of the I2S_TCR3_TCE field. */ #define BR_I2S_TCR3_TCE(x) (HW_I2S_TCR3(x).B.TCE) /*! @brief Format value for bitfield I2S_TCR3_TCE. */ #define BF_I2S_TCR3_TCE(v) ((uint32_t)((uint32_t)(v) << BP_I2S_TCR3_TCE) & BM_I2S_TCR3_TCE) /*! @brief Set the TCE field to a new value. */ #define BW_I2S_TCR3_TCE(x, v) (HW_I2S_TCR3_WR(x, (HW_I2S_TCR3_RD(x) & ~BM_I2S_TCR3_TCE) | BF_I2S_TCR3_TCE(v))) /*@}*/ /******************************************************************************* * HW_I2S_TCR4 - SAI Transmit Configuration 4 Register ******************************************************************************/ /*! * @brief HW_I2S_TCR4 - SAI Transmit Configuration 4 Register (RW) * * Reset value: 0x00000000U * * This register must not be altered when TCSR[TE] is set. */ typedef union _hw_i2s_tcr4 { uint32_t U; struct _hw_i2s_tcr4_bitfields { uint32_t FSD : 1; /*!< [0] Frame Sync Direction */ uint32_t FSP : 1; /*!< [1] Frame Sync Polarity */ uint32_t RESERVED0 : 1; /*!< [2] */ uint32_t FSE : 1; /*!< [3] Frame Sync Early */ uint32_t MF : 1; /*!< [4] MSB First */ uint32_t RESERVED1 : 3; /*!< [7:5] */ uint32_t SYWD : 5; /*!< [12:8] Sync Width */ uint32_t RESERVED2 : 3; /*!< [15:13] */ uint32_t FRSZ : 5; /*!< [20:16] Frame size */ uint32_t RESERVED3 : 11; /*!< [31:21] */ } B; } hw_i2s_tcr4_t; /*! * @name Constants and macros for entire I2S_TCR4 register */ /*@{*/ #define HW_I2S_TCR4_ADDR(x) ((x) + 0x10U) #define HW_I2S_TCR4(x) (*(__IO hw_i2s_tcr4_t *) HW_I2S_TCR4_ADDR(x)) #define HW_I2S_TCR4_RD(x) (HW_I2S_TCR4(x).U) #define HW_I2S_TCR4_WR(x, v) (HW_I2S_TCR4(x).U = (v)) #define HW_I2S_TCR4_SET(x, v) (HW_I2S_TCR4_WR(x, HW_I2S_TCR4_RD(x) | (v))) #define HW_I2S_TCR4_CLR(x, v) (HW_I2S_TCR4_WR(x, HW_I2S_TCR4_RD(x) & ~(v))) #define HW_I2S_TCR4_TOG(x, v) (HW_I2S_TCR4_WR(x, HW_I2S_TCR4_RD(x) ^ (v))) /*@}*/ /* * Constants & macros for individual I2S_TCR4 bitfields */ /*! * @name Register I2S_TCR4, field FSD[0] (RW) * * Configures the direction of the frame sync. * * Values: * - 0 - Frame sync is generated externally in Slave mode. * - 1 - Frame sync is generated internally in Master mode. */ /*@{*/ #define BP_I2S_TCR4_FSD (0U) /*!< Bit position for I2S_TCR4_FSD. */ #define BM_I2S_TCR4_FSD (0x00000001U) /*!< Bit mask for I2S_TCR4_FSD. */ #define BS_I2S_TCR4_FSD (1U) /*!< Bit field size in bits for I2S_TCR4_FSD. */ /*! @brief Read current value of the I2S_TCR4_FSD field. */ #define BR_I2S_TCR4_FSD(x) (BITBAND_ACCESS32(HW_I2S_TCR4_ADDR(x), BP_I2S_TCR4_FSD)) /*! @brief Format value for bitfield I2S_TCR4_FSD. */ #define BF_I2S_TCR4_FSD(v) ((uint32_t)((uint32_t)(v) << BP_I2S_TCR4_FSD) & BM_I2S_TCR4_FSD) /*! @brief Set the FSD field to a new value. */ #define BW_I2S_TCR4_FSD(x, v) (BITBAND_ACCESS32(HW_I2S_TCR4_ADDR(x), BP_I2S_TCR4_FSD) = (v)) /*@}*/ /*! * @name Register I2S_TCR4, field FSP[1] (RW) * * Configures the polarity of the frame sync. * * Values: * - 0 - Frame sync is active high. * - 1 - Frame sync is active low. */ /*@{*/ #define BP_I2S_TCR4_FSP (1U) /*!< Bit position for I2S_TCR4_FSP. */ #define BM_I2S_TCR4_FSP (0x00000002U) /*!< Bit mask for I2S_TCR4_FSP. */ #define BS_I2S_TCR4_FSP (1U) /*!< Bit field size in bits for I2S_TCR4_FSP. */ /*! @brief Read current value of the I2S_TCR4_FSP field. */ #define BR_I2S_TCR4_FSP(x) (BITBAND_ACCESS32(HW_I2S_TCR4_ADDR(x), BP_I2S_TCR4_FSP)) /*! @brief Format value for bitfield I2S_TCR4_FSP. */ #define BF_I2S_TCR4_FSP(v) ((uint32_t)((uint32_t)(v) << BP_I2S_TCR4_FSP) & BM_I2S_TCR4_FSP) /*! @brief Set the FSP field to a new value. */ #define BW_I2S_TCR4_FSP(x, v) (BITBAND_ACCESS32(HW_I2S_TCR4_ADDR(x), BP_I2S_TCR4_FSP) = (v)) /*@}*/ /*! * @name Register I2S_TCR4, field FSE[3] (RW) * * Values: * - 0 - Frame sync asserts with the first bit of the frame. * - 1 - Frame sync asserts one bit before the first bit of the frame. */ /*@{*/ #define BP_I2S_TCR4_FSE (3U) /*!< Bit position for I2S_TCR4_FSE. */ #define BM_I2S_TCR4_FSE (0x00000008U) /*!< Bit mask for I2S_TCR4_FSE. */ #define BS_I2S_TCR4_FSE (1U) /*!< Bit field size in bits for I2S_TCR4_FSE. */ /*! @brief Read current value of the I2S_TCR4_FSE field. */ #define BR_I2S_TCR4_FSE(x) (BITBAND_ACCESS32(HW_I2S_TCR4_ADDR(x), BP_I2S_TCR4_FSE)) /*! @brief Format value for bitfield I2S_TCR4_FSE. */ #define BF_I2S_TCR4_FSE(v) ((uint32_t)((uint32_t)(v) << BP_I2S_TCR4_FSE) & BM_I2S_TCR4_FSE) /*! @brief Set the FSE field to a new value. */ #define BW_I2S_TCR4_FSE(x, v) (BITBAND_ACCESS32(HW_I2S_TCR4_ADDR(x), BP_I2S_TCR4_FSE) = (v)) /*@}*/ /*! * @name Register I2S_TCR4, field MF[4] (RW) * * Configures whether the LSB or the MSB is transmitted first. * * Values: * - 0 - LSB is transmitted first. * - 1 - MSB is transmitted first. */ /*@{*/ #define BP_I2S_TCR4_MF (4U) /*!< Bit position for I2S_TCR4_MF. */ #define BM_I2S_TCR4_MF (0x00000010U) /*!< Bit mask for I2S_TCR4_MF. */ #define BS_I2S_TCR4_MF (1U) /*!< Bit field size in bits for I2S_TCR4_MF. */ /*! @brief Read current value of the I2S_TCR4_MF field. */ #define BR_I2S_TCR4_MF(x) (BITBAND_ACCESS32(HW_I2S_TCR4_ADDR(x), BP_I2S_TCR4_MF)) /*! @brief Format value for bitfield I2S_TCR4_MF. */ #define BF_I2S_TCR4_MF(v) ((uint32_t)((uint32_t)(v) << BP_I2S_TCR4_MF) & BM_I2S_TCR4_MF) /*! @brief Set the MF field to a new value. */ #define BW_I2S_TCR4_MF(x, v) (BITBAND_ACCESS32(HW_I2S_TCR4_ADDR(x), BP_I2S_TCR4_MF) = (v)) /*@}*/ /*! * @name Register I2S_TCR4, field SYWD[12:8] (RW) * * Configures the length of the frame sync in number of bit clocks. The value * written must be one less than the number of bit clocks. For example, write 0 for * the frame sync to assert for one bit clock only. The sync width cannot be * configured longer than the first word of the frame. */ /*@{*/ #define BP_I2S_TCR4_SYWD (8U) /*!< Bit position for I2S_TCR4_SYWD. */ #define BM_I2S_TCR4_SYWD (0x00001F00U) /*!< Bit mask for I2S_TCR4_SYWD. */ #define BS_I2S_TCR4_SYWD (5U) /*!< Bit field size in bits for I2S_TCR4_SYWD. */ /*! @brief Read current value of the I2S_TCR4_SYWD field. */ #define BR_I2S_TCR4_SYWD(x) (HW_I2S_TCR4(x).B.SYWD) /*! @brief Format value for bitfield I2S_TCR4_SYWD. */ #define BF_I2S_TCR4_SYWD(v) ((uint32_t)((uint32_t)(v) << BP_I2S_TCR4_SYWD) & BM_I2S_TCR4_SYWD) /*! @brief Set the SYWD field to a new value. */ #define BW_I2S_TCR4_SYWD(x, v) (HW_I2S_TCR4_WR(x, (HW_I2S_TCR4_RD(x) & ~BM_I2S_TCR4_SYWD) | BF_I2S_TCR4_SYWD(v))) /*@}*/ /*! * @name Register I2S_TCR4, field FRSZ[20:16] (RW) * * Configures the number of words in each frame. The value written must be one * less than the number of words in the frame. For example, write 0 for one word * per frame. The maximum supported frame size is 32 words. */ /*@{*/ #define BP_I2S_TCR4_FRSZ (16U) /*!< Bit position for I2S_TCR4_FRSZ. */ #define BM_I2S_TCR4_FRSZ (0x001F0000U) /*!< Bit mask for I2S_TCR4_FRSZ. */ #define BS_I2S_TCR4_FRSZ (5U) /*!< Bit field size in bits for I2S_TCR4_FRSZ. */ /*! @brief Read current value of the I2S_TCR4_FRSZ field. */ #define BR_I2S_TCR4_FRSZ(x) (HW_I2S_TCR4(x).B.FRSZ) /*! @brief Format value for bitfield I2S_TCR4_FRSZ. */ #define BF_I2S_TCR4_FRSZ(v) ((uint32_t)((uint32_t)(v) << BP_I2S_TCR4_FRSZ) & BM_I2S_TCR4_FRSZ) /*! @brief Set the FRSZ field to a new value. */ #define BW_I2S_TCR4_FRSZ(x, v) (HW_I2S_TCR4_WR(x, (HW_I2S_TCR4_RD(x) & ~BM_I2S_TCR4_FRSZ) | BF_I2S_TCR4_FRSZ(v))) /*@}*/ /******************************************************************************* * HW_I2S_TCR5 - SAI Transmit Configuration 5 Register ******************************************************************************/ /*! * @brief HW_I2S_TCR5 - SAI Transmit Configuration 5 Register (RW) * * Reset value: 0x00000000U * * This register must not be altered when TCSR[TE] is set. */ typedef union _hw_i2s_tcr5 { uint32_t U; struct _hw_i2s_tcr5_bitfields { uint32_t RESERVED0 : 8; /*!< [7:0] */ uint32_t FBT : 5; /*!< [12:8] First Bit Shifted */ uint32_t RESERVED1 : 3; /*!< [15:13] */ uint32_t W0W : 5; /*!< [20:16] Word 0 Width */ uint32_t RESERVED2 : 3; /*!< [23:21] */ uint32_t WNW : 5; /*!< [28:24] Word N Width */ uint32_t RESERVED3 : 3; /*!< [31:29] */ } B; } hw_i2s_tcr5_t; /*! * @name Constants and macros for entire I2S_TCR5 register */ /*@{*/ #define HW_I2S_TCR5_ADDR(x) ((x) + 0x14U) #define HW_I2S_TCR5(x) (*(__IO hw_i2s_tcr5_t *) HW_I2S_TCR5_ADDR(x)) #define HW_I2S_TCR5_RD(x) (HW_I2S_TCR5(x).U) #define HW_I2S_TCR5_WR(x, v) (HW_I2S_TCR5(x).U = (v)) #define HW_I2S_TCR5_SET(x, v) (HW_I2S_TCR5_WR(x, HW_I2S_TCR5_RD(x) | (v))) #define HW_I2S_TCR5_CLR(x, v) (HW_I2S_TCR5_WR(x, HW_I2S_TCR5_RD(x) & ~(v))) #define HW_I2S_TCR5_TOG(x, v) (HW_I2S_TCR5_WR(x, HW_I2S_TCR5_RD(x) ^ (v))) /*@}*/ /* * Constants & macros for individual I2S_TCR5 bitfields */ /*! * @name Register I2S_TCR5, field FBT[12:8] (RW) * * Configures the bit index for the first bit transmitted for each word in the * frame. If configured for MSB First, the index of the next bit transmitted is * one less than the current bit transmitted. If configured for LSB First, the * index of the next bit transmitted is one more than the current bit transmitted. * The value written must be greater than or equal to the word width when * configured for MSB First. The value written must be less than or equal to 31-word width * when configured for LSB First. */ /*@{*/ #define BP_I2S_TCR5_FBT (8U) /*!< Bit position for I2S_TCR5_FBT. */ #define BM_I2S_TCR5_FBT (0x00001F00U) /*!< Bit mask for I2S_TCR5_FBT. */ #define BS_I2S_TCR5_FBT (5U) /*!< Bit field size in bits for I2S_TCR5_FBT. */ /*! @brief Read current value of the I2S_TCR5_FBT field. */ #define BR_I2S_TCR5_FBT(x) (HW_I2S_TCR5(x).B.FBT) /*! @brief Format value for bitfield I2S_TCR5_FBT. */ #define BF_I2S_TCR5_FBT(v) ((uint32_t)((uint32_t)(v) << BP_I2S_TCR5_FBT) & BM_I2S_TCR5_FBT) /*! @brief Set the FBT field to a new value. */ #define BW_I2S_TCR5_FBT(x, v) (HW_I2S_TCR5_WR(x, (HW_I2S_TCR5_RD(x) & ~BM_I2S_TCR5_FBT) | BF_I2S_TCR5_FBT(v))) /*@}*/ /*! * @name Register I2S_TCR5, field W0W[20:16] (RW) * * Configures the number of bits in the first word in each frame. The value * written must be one less than the number of bits in the first word. Word width of * less than 8 bits is not supported if there is only one word per frame. */ /*@{*/ #define BP_I2S_TCR5_W0W (16U) /*!< Bit position for I2S_TCR5_W0W. */ #define BM_I2S_TCR5_W0W (0x001F0000U) /*!< Bit mask for I2S_TCR5_W0W. */ #define BS_I2S_TCR5_W0W (5U) /*!< Bit field size in bits for I2S_TCR5_W0W. */ /*! @brief Read current value of the I2S_TCR5_W0W field. */ #define BR_I2S_TCR5_W0W(x) (HW_I2S_TCR5(x).B.W0W) /*! @brief Format value for bitfield I2S_TCR5_W0W. */ #define BF_I2S_TCR5_W0W(v) ((uint32_t)((uint32_t)(v) << BP_I2S_TCR5_W0W) & BM_I2S_TCR5_W0W) /*! @brief Set the W0W field to a new value. */ #define BW_I2S_TCR5_W0W(x, v) (HW_I2S_TCR5_WR(x, (HW_I2S_TCR5_RD(x) & ~BM_I2S_TCR5_W0W) | BF_I2S_TCR5_W0W(v))) /*@}*/ /*! * @name Register I2S_TCR5, field WNW[28:24] (RW) * * Configures the number of bits in each word, for each word except the first in * the frame. The value written must be one less than the number of bits per * word. Word width of less than 8 bits is not supported. */ /*@{*/ #define BP_I2S_TCR5_WNW (24U) /*!< Bit position for I2S_TCR5_WNW. */ #define BM_I2S_TCR5_WNW (0x1F000000U) /*!< Bit mask for I2S_TCR5_WNW. */ #define BS_I2S_TCR5_WNW (5U) /*!< Bit field size in bits for I2S_TCR5_WNW. */ /*! @brief Read current value of the I2S_TCR5_WNW field. */ #define BR_I2S_TCR5_WNW(x) (HW_I2S_TCR5(x).B.WNW) /*! @brief Format value for bitfield I2S_TCR5_WNW. */ #define BF_I2S_TCR5_WNW(v) ((uint32_t)((uint32_t)(v) << BP_I2S_TCR5_WNW) & BM_I2S_TCR5_WNW) /*! @brief Set the WNW field to a new value. */ #define BW_I2S_TCR5_WNW(x, v) (HW_I2S_TCR5_WR(x, (HW_I2S_TCR5_RD(x) & ~BM_I2S_TCR5_WNW) | BF_I2S_TCR5_WNW(v))) /*@}*/ /******************************************************************************* * HW_I2S_TDRn - SAI Transmit Data Register ******************************************************************************/ /*! * @brief HW_I2S_TDRn - SAI Transmit Data Register (WORZ) * * Reset value: 0x00000000U */ typedef union _hw_i2s_tdrn { uint32_t U; struct _hw_i2s_tdrn_bitfields { uint32_t TDR : 32; /*!< [31:0] Transmit Data Register */ } B; } hw_i2s_tdrn_t; /*! * @name Constants and macros for entire I2S_TDRn register */ /*@{*/ #define HW_I2S_TDRn_COUNT (2U) #define HW_I2S_TDRn_ADDR(x, n) ((x) + 0x20U + (0x4U * (n))) #define HW_I2S_TDRn(x, n) (*(__O hw_i2s_tdrn_t *) HW_I2S_TDRn_ADDR(x, n)) #define HW_I2S_TDRn_RD(x, n) (HW_I2S_TDRn(x, n).U) #define HW_I2S_TDRn_WR(x, n, v) (HW_I2S_TDRn(x, n).U = (v)) /*@}*/ /* * Constants & macros for individual I2S_TDRn bitfields */ /*! * @name Register I2S_TDRn, field TDR[31:0] (WORZ) * * The corresponding TCR3[TCE] bit must be set before accessing the channel's * transmit data register. Writes to this register when the transmit FIFO is not * full will push the data written into the transmit data FIFO. Writes to this * register when the transmit FIFO is full are ignored. */ /*@{*/ #define BP_I2S_TDRn_TDR (0U) /*!< Bit position for I2S_TDRn_TDR. */ #define BM_I2S_TDRn_TDR (0xFFFFFFFFU) /*!< Bit mask for I2S_TDRn_TDR. */ #define BS_I2S_TDRn_TDR (32U) /*!< Bit field size in bits for I2S_TDRn_TDR. */ /*! @brief Format value for bitfield I2S_TDRn_TDR. */ #define BF_I2S_TDRn_TDR(v) ((uint32_t)((uint32_t)(v) << BP_I2S_TDRn_TDR) & BM_I2S_TDRn_TDR) /*! @brief Set the TDR field to a new value. */ #define BW_I2S_TDRn_TDR(x, n, v) (HW_I2S_TDRn_WR(x, n, v)) /*@}*/ /******************************************************************************* * HW_I2S_TFRn - SAI Transmit FIFO Register ******************************************************************************/ /*! * @brief HW_I2S_TFRn - SAI Transmit FIFO Register (RO) * * Reset value: 0x00000000U * * The MSB of the read and write pointers is used to distinguish between FIFO * full and empty conditions. If the read and write pointers are identical, then * the FIFO is empty. If the read and write pointers are identical except for the * MSB, then the FIFO is full. */ typedef union _hw_i2s_tfrn { uint32_t U; struct _hw_i2s_tfrn_bitfields { uint32_t RFP : 4; /*!< [3:0] Read FIFO Pointer */ uint32_t RESERVED0 : 12; /*!< [15:4] */ uint32_t WFP : 4; /*!< [19:16] Write FIFO Pointer */ uint32_t RESERVED1 : 12; /*!< [31:20] */ } B; } hw_i2s_tfrn_t; /*! * @name Constants and macros for entire I2S_TFRn register */ /*@{*/ #define HW_I2S_TFRn_COUNT (2U) #define HW_I2S_TFRn_ADDR(x, n) ((x) + 0x40U + (0x4U * (n))) #define HW_I2S_TFRn(x, n) (*(__I hw_i2s_tfrn_t *) HW_I2S_TFRn_ADDR(x, n)) #define HW_I2S_TFRn_RD(x, n) (HW_I2S_TFRn(x, n).U) /*@}*/ /* * Constants & macros for individual I2S_TFRn bitfields */ /*! * @name Register I2S_TFRn, field RFP[3:0] (RO) * * FIFO read pointer for transmit data channel. */ /*@{*/ #define BP_I2S_TFRn_RFP (0U) /*!< Bit position for I2S_TFRn_RFP. */ #define BM_I2S_TFRn_RFP (0x0000000FU) /*!< Bit mask for I2S_TFRn_RFP. */ #define BS_I2S_TFRn_RFP (4U) /*!< Bit field size in bits for I2S_TFRn_RFP. */ /*! @brief Read current value of the I2S_TFRn_RFP field. */ #define BR_I2S_TFRn_RFP(x, n) (HW_I2S_TFRn(x, n).B.RFP) /*@}*/ /*! * @name Register I2S_TFRn, field WFP[19:16] (RO) * * FIFO write pointer for transmit data channel. */ /*@{*/ #define BP_I2S_TFRn_WFP (16U) /*!< Bit position for I2S_TFRn_WFP. */ #define BM_I2S_TFRn_WFP (0x000F0000U) /*!< Bit mask for I2S_TFRn_WFP. */ #define BS_I2S_TFRn_WFP (4U) /*!< Bit field size in bits for I2S_TFRn_WFP. */ /*! @brief Read current value of the I2S_TFRn_WFP field. */ #define BR_I2S_TFRn_WFP(x, n) (HW_I2S_TFRn(x, n).B.WFP) /*@}*/ /******************************************************************************* * HW_I2S_TMR - SAI Transmit Mask Register ******************************************************************************/ /*! * @brief HW_I2S_TMR - SAI Transmit Mask Register (RW) * * Reset value: 0x00000000U * * This register is double-buffered and updates: When TCSR[TE] is first set At * the end of each frame. This allows the masked words in each frame to change * from frame to frame. */ typedef union _hw_i2s_tmr { uint32_t U; struct _hw_i2s_tmr_bitfields { uint32_t TWM : 32; /*!< [31:0] Transmit Word Mask */ } B; } hw_i2s_tmr_t; /*! * @name Constants and macros for entire I2S_TMR register */ /*@{*/ #define HW_I2S_TMR_ADDR(x) ((x) + 0x60U) #define HW_I2S_TMR(x) (*(__IO hw_i2s_tmr_t *) HW_I2S_TMR_ADDR(x)) #define HW_I2S_TMR_RD(x) (HW_I2S_TMR(x).U) #define HW_I2S_TMR_WR(x, v) (HW_I2S_TMR(x).U = (v)) #define HW_I2S_TMR_SET(x, v) (HW_I2S_TMR_WR(x, HW_I2S_TMR_RD(x) | (v))) #define HW_I2S_TMR_CLR(x, v) (HW_I2S_TMR_WR(x, HW_I2S_TMR_RD(x) & ~(v))) #define HW_I2S_TMR_TOG(x, v) (HW_I2S_TMR_WR(x, HW_I2S_TMR_RD(x) ^ (v))) /*@}*/ /* * Constants & macros for individual I2S_TMR bitfields */ /*! * @name Register I2S_TMR, field TWM[31:0] (RW) * * Configures whether the transmit word is masked (transmit data pin tristated * and transmit data not read from FIFO) for the corresponding word in the frame. * * Values: * - 0 - Word N is enabled. * - 1 - Word N is masked. The transmit data pins are tri-stated when masked. */ /*@{*/ #define BP_I2S_TMR_TWM (0U) /*!< Bit position for I2S_TMR_TWM. */ #define BM_I2S_TMR_TWM (0xFFFFFFFFU) /*!< Bit mask for I2S_TMR_TWM. */ #define BS_I2S_TMR_TWM (32U) /*!< Bit field size in bits for I2S_TMR_TWM. */ /*! @brief Read current value of the I2S_TMR_TWM field. */ #define BR_I2S_TMR_TWM(x) (HW_I2S_TMR(x).U) /*! @brief Format value for bitfield I2S_TMR_TWM. */ #define BF_I2S_TMR_TWM(v) ((uint32_t)((uint32_t)(v) << BP_I2S_TMR_TWM) & BM_I2S_TMR_TWM) /*! @brief Set the TWM field to a new value. */ #define BW_I2S_TMR_TWM(x, v) (HW_I2S_TMR_WR(x, v)) /*@}*/ /******************************************************************************* * HW_I2S_RCSR - SAI Receive Control Register ******************************************************************************/ /*! * @brief HW_I2S_RCSR - SAI Receive Control Register (RW) * * Reset value: 0x00000000U */ typedef union _hw_i2s_rcsr { uint32_t U; struct _hw_i2s_rcsr_bitfields { uint32_t FRDE : 1; /*!< [0] FIFO Request DMA Enable */ uint32_t FWDE : 1; /*!< [1] FIFO Warning DMA Enable */ uint32_t RESERVED0 : 6; /*!< [7:2] */ uint32_t FRIE : 1; /*!< [8] FIFO Request Interrupt Enable */ uint32_t FWIE : 1; /*!< [9] FIFO Warning Interrupt Enable */ uint32_t FEIE : 1; /*!< [10] FIFO Error Interrupt Enable */ uint32_t SEIE : 1; /*!< [11] Sync Error Interrupt Enable */ uint32_t WSIE : 1; /*!< [12] Word Start Interrupt Enable */ uint32_t RESERVED1 : 3; /*!< [15:13] */ uint32_t FRF : 1; /*!< [16] FIFO Request Flag */ uint32_t FWF : 1; /*!< [17] FIFO Warning Flag */ uint32_t FEF : 1; /*!< [18] FIFO Error Flag */ uint32_t SEF : 1; /*!< [19] Sync Error Flag */ uint32_t WSF : 1; /*!< [20] Word Start Flag */ uint32_t RESERVED2 : 3; /*!< [23:21] */ uint32_t SR : 1; /*!< [24] Software Reset */ uint32_t FR : 1; /*!< [25] FIFO Reset */ uint32_t RESERVED3 : 2; /*!< [27:26] */ uint32_t BCE : 1; /*!< [28] Bit Clock Enable */ uint32_t DBGE : 1; /*!< [29] Debug Enable */ uint32_t STOPE : 1; /*!< [30] Stop Enable */ uint32_t RE : 1; /*!< [31] Receiver Enable */ } B; } hw_i2s_rcsr_t; /*! * @name Constants and macros for entire I2S_RCSR register */ /*@{*/ #define HW_I2S_RCSR_ADDR(x) ((x) + 0x80U) #define HW_I2S_RCSR(x) (*(__IO hw_i2s_rcsr_t *) HW_I2S_RCSR_ADDR(x)) #define HW_I2S_RCSR_RD(x) (HW_I2S_RCSR(x).U) #define HW_I2S_RCSR_WR(x, v) (HW_I2S_RCSR(x).U = (v)) #define HW_I2S_RCSR_SET(x, v) (HW_I2S_RCSR_WR(x, HW_I2S_RCSR_RD(x) | (v))) #define HW_I2S_RCSR_CLR(x, v) (HW_I2S_RCSR_WR(x, HW_I2S_RCSR_RD(x) & ~(v))) #define HW_I2S_RCSR_TOG(x, v) (HW_I2S_RCSR_WR(x, HW_I2S_RCSR_RD(x) ^ (v))) /*@}*/ /* * Constants & macros for individual I2S_RCSR bitfields */ /*! * @name Register I2S_RCSR, field FRDE[0] (RW) * * Enables/disables DMA requests. * * Values: * - 0 - Disables the DMA request. * - 1 - Enables the DMA request. */ /*@{*/ #define BP_I2S_RCSR_FRDE (0U) /*!< Bit position for I2S_RCSR_FRDE. */ #define BM_I2S_RCSR_FRDE (0x00000001U) /*!< Bit mask for I2S_RCSR_FRDE. */ #define BS_I2S_RCSR_FRDE (1U) /*!< Bit field size in bits for I2S_RCSR_FRDE. */ /*! @brief Read current value of the I2S_RCSR_FRDE field. */ #define BR_I2S_RCSR_FRDE(x) (BITBAND_ACCESS32(HW_I2S_RCSR_ADDR(x), BP_I2S_RCSR_FRDE)) /*! @brief Format value for bitfield I2S_RCSR_FRDE. */ #define BF_I2S_RCSR_FRDE(v) ((uint32_t)((uint32_t)(v) << BP_I2S_RCSR_FRDE) & BM_I2S_RCSR_FRDE) /*! @brief Set the FRDE field to a new value. */ #define BW_I2S_RCSR_FRDE(x, v) (BITBAND_ACCESS32(HW_I2S_RCSR_ADDR(x), BP_I2S_RCSR_FRDE) = (v)) /*@}*/ /*! * @name Register I2S_RCSR, field FWDE[1] (RW) * * Enables/disables DMA requests. * * Values: * - 0 - Disables the DMA request. * - 1 - Enables the DMA request. */ /*@{*/ #define BP_I2S_RCSR_FWDE (1U) /*!< Bit position for I2S_RCSR_FWDE. */ #define BM_I2S_RCSR_FWDE (0x00000002U) /*!< Bit mask for I2S_RCSR_FWDE. */ #define BS_I2S_RCSR_FWDE (1U) /*!< Bit field size in bits for I2S_RCSR_FWDE. */ /*! @brief Read current value of the I2S_RCSR_FWDE field. */ #define BR_I2S_RCSR_FWDE(x) (BITBAND_ACCESS32(HW_I2S_RCSR_ADDR(x), BP_I2S_RCSR_FWDE)) /*! @brief Format value for bitfield I2S_RCSR_FWDE. */ #define BF_I2S_RCSR_FWDE(v) ((uint32_t)((uint32_t)(v) << BP_I2S_RCSR_FWDE) & BM_I2S_RCSR_FWDE) /*! @brief Set the FWDE field to a new value. */ #define BW_I2S_RCSR_FWDE(x, v) (BITBAND_ACCESS32(HW_I2S_RCSR_ADDR(x), BP_I2S_RCSR_FWDE) = (v)) /*@}*/ /*! * @name Register I2S_RCSR, field FRIE[8] (RW) * * Enables/disables FIFO request interrupts. * * Values: * - 0 - Disables the interrupt. * - 1 - Enables the interrupt. */ /*@{*/ #define BP_I2S_RCSR_FRIE (8U) /*!< Bit position for I2S_RCSR_FRIE. */ #define BM_I2S_RCSR_FRIE (0x00000100U) /*!< Bit mask for I2S_RCSR_FRIE. */ #define BS_I2S_RCSR_FRIE (1U) /*!< Bit field size in bits for I2S_RCSR_FRIE. */ /*! @brief Read current value of the I2S_RCSR_FRIE field. */ #define BR_I2S_RCSR_FRIE(x) (BITBAND_ACCESS32(HW_I2S_RCSR_ADDR(x), BP_I2S_RCSR_FRIE)) /*! @brief Format value for bitfield I2S_RCSR_FRIE. */ #define BF_I2S_RCSR_FRIE(v) ((uint32_t)((uint32_t)(v) << BP_I2S_RCSR_FRIE) & BM_I2S_RCSR_FRIE) /*! @brief Set the FRIE field to a new value. */ #define BW_I2S_RCSR_FRIE(x, v) (BITBAND_ACCESS32(HW_I2S_RCSR_ADDR(x), BP_I2S_RCSR_FRIE) = (v)) /*@}*/ /*! * @name Register I2S_RCSR, field FWIE[9] (RW) * * Enables/disables FIFO warning interrupts. * * Values: * - 0 - Disables the interrupt. * - 1 - Enables the interrupt. */ /*@{*/ #define BP_I2S_RCSR_FWIE (9U) /*!< Bit position for I2S_RCSR_FWIE. */ #define BM_I2S_RCSR_FWIE (0x00000200U) /*!< Bit mask for I2S_RCSR_FWIE. */ #define BS_I2S_RCSR_FWIE (1U) /*!< Bit field size in bits for I2S_RCSR_FWIE. */ /*! @brief Read current value of the I2S_RCSR_FWIE field. */ #define BR_I2S_RCSR_FWIE(x) (BITBAND_ACCESS32(HW_I2S_RCSR_ADDR(x), BP_I2S_RCSR_FWIE)) /*! @brief Format value for bitfield I2S_RCSR_FWIE. */ #define BF_I2S_RCSR_FWIE(v) ((uint32_t)((uint32_t)(v) << BP_I2S_RCSR_FWIE) & BM_I2S_RCSR_FWIE) /*! @brief Set the FWIE field to a new value. */ #define BW_I2S_RCSR_FWIE(x, v) (BITBAND_ACCESS32(HW_I2S_RCSR_ADDR(x), BP_I2S_RCSR_FWIE) = (v)) /*@}*/ /*! * @name Register I2S_RCSR, field FEIE[10] (RW) * * Enables/disables FIFO error interrupts. * * Values: * - 0 - Disables the interrupt. * - 1 - Enables the interrupt. */ /*@{*/ #define BP_I2S_RCSR_FEIE (10U) /*!< Bit position for I2S_RCSR_FEIE. */ #define BM_I2S_RCSR_FEIE (0x00000400U) /*!< Bit mask for I2S_RCSR_FEIE. */ #define BS_I2S_RCSR_FEIE (1U) /*!< Bit field size in bits for I2S_RCSR_FEIE. */ /*! @brief Read current value of the I2S_RCSR_FEIE field. */ #define BR_I2S_RCSR_FEIE(x) (BITBAND_ACCESS32(HW_I2S_RCSR_ADDR(x), BP_I2S_RCSR_FEIE)) /*! @brief Format value for bitfield I2S_RCSR_FEIE. */ #define BF_I2S_RCSR_FEIE(v) ((uint32_t)((uint32_t)(v) << BP_I2S_RCSR_FEIE) & BM_I2S_RCSR_FEIE) /*! @brief Set the FEIE field to a new value. */ #define BW_I2S_RCSR_FEIE(x, v) (BITBAND_ACCESS32(HW_I2S_RCSR_ADDR(x), BP_I2S_RCSR_FEIE) = (v)) /*@}*/ /*! * @name Register I2S_RCSR, field SEIE[11] (RW) * * Enables/disables sync error interrupts. * * Values: * - 0 - Disables interrupt. * - 1 - Enables interrupt. */ /*@{*/ #define BP_I2S_RCSR_SEIE (11U) /*!< Bit position for I2S_RCSR_SEIE. */ #define BM_I2S_RCSR_SEIE (0x00000800U) /*!< Bit mask for I2S_RCSR_SEIE. */ #define BS_I2S_RCSR_SEIE (1U) /*!< Bit field size in bits for I2S_RCSR_SEIE. */ /*! @brief Read current value of the I2S_RCSR_SEIE field. */ #define BR_I2S_RCSR_SEIE(x) (BITBAND_ACCESS32(HW_I2S_RCSR_ADDR(x), BP_I2S_RCSR_SEIE)) /*! @brief Format value for bitfield I2S_RCSR_SEIE. */ #define BF_I2S_RCSR_SEIE(v) ((uint32_t)((uint32_t)(v) << BP_I2S_RCSR_SEIE) & BM_I2S_RCSR_SEIE) /*! @brief Set the SEIE field to a new value. */ #define BW_I2S_RCSR_SEIE(x, v) (BITBAND_ACCESS32(HW_I2S_RCSR_ADDR(x), BP_I2S_RCSR_SEIE) = (v)) /*@}*/ /*! * @name Register I2S_RCSR, field WSIE[12] (RW) * * Enables/disables word start interrupts. * * Values: * - 0 - Disables interrupt. * - 1 - Enables interrupt. */ /*@{*/ #define BP_I2S_RCSR_WSIE (12U) /*!< Bit position for I2S_RCSR_WSIE. */ #define BM_I2S_RCSR_WSIE (0x00001000U) /*!< Bit mask for I2S_RCSR_WSIE. */ #define BS_I2S_RCSR_WSIE (1U) /*!< Bit field size in bits for I2S_RCSR_WSIE. */ /*! @brief Read current value of the I2S_RCSR_WSIE field. */ #define BR_I2S_RCSR_WSIE(x) (BITBAND_ACCESS32(HW_I2S_RCSR_ADDR(x), BP_I2S_RCSR_WSIE)) /*! @brief Format value for bitfield I2S_RCSR_WSIE. */ #define BF_I2S_RCSR_WSIE(v) ((uint32_t)((uint32_t)(v) << BP_I2S_RCSR_WSIE) & BM_I2S_RCSR_WSIE) /*! @brief Set the WSIE field to a new value. */ #define BW_I2S_RCSR_WSIE(x, v) (BITBAND_ACCESS32(HW_I2S_RCSR_ADDR(x), BP_I2S_RCSR_WSIE) = (v)) /*@}*/ /*! * @name Register I2S_RCSR, field FRF[16] (RO) * * Indicates that the number of words in an enabled receive channel FIFO is * greater than the receive FIFO watermark. * * Values: * - 0 - Receive FIFO watermark not reached. * - 1 - Receive FIFO watermark has been reached. */ /*@{*/ #define BP_I2S_RCSR_FRF (16U) /*!< Bit position for I2S_RCSR_FRF. */ #define BM_I2S_RCSR_FRF (0x00010000U) /*!< Bit mask for I2S_RCSR_FRF. */ #define BS_I2S_RCSR_FRF (1U) /*!< Bit field size in bits for I2S_RCSR_FRF. */ /*! @brief Read current value of the I2S_RCSR_FRF field. */ #define BR_I2S_RCSR_FRF(x) (BITBAND_ACCESS32(HW_I2S_RCSR_ADDR(x), BP_I2S_RCSR_FRF)) /*@}*/ /*! * @name Register I2S_RCSR, field FWF[17] (RO) * * Indicates that an enabled receive FIFO is full. * * Values: * - 0 - No enabled receive FIFO is full. * - 1 - Enabled receive FIFO is full. */ /*@{*/ #define BP_I2S_RCSR_FWF (17U) /*!< Bit position for I2S_RCSR_FWF. */ #define BM_I2S_RCSR_FWF (0x00020000U) /*!< Bit mask for I2S_RCSR_FWF. */ #define BS_I2S_RCSR_FWF (1U) /*!< Bit field size in bits for I2S_RCSR_FWF. */ /*! @brief Read current value of the I2S_RCSR_FWF field. */ #define BR_I2S_RCSR_FWF(x) (BITBAND_ACCESS32(HW_I2S_RCSR_ADDR(x), BP_I2S_RCSR_FWF)) /*@}*/ /*! * @name Register I2S_RCSR, field FEF[18] (W1C) * * Indicates that an enabled receive FIFO has overflowed. Write a logic 1 to * this field to clear this flag. * * Values: * - 0 - Receive overflow not detected. * - 1 - Receive overflow detected. */ /*@{*/ #define BP_I2S_RCSR_FEF (18U) /*!< Bit position for I2S_RCSR_FEF. */ #define BM_I2S_RCSR_FEF (0x00040000U) /*!< Bit mask for I2S_RCSR_FEF. */ #define BS_I2S_RCSR_FEF (1U) /*!< Bit field size in bits for I2S_RCSR_FEF. */ /*! @brief Read current value of the I2S_RCSR_FEF field. */ #define BR_I2S_RCSR_FEF(x) (BITBAND_ACCESS32(HW_I2S_RCSR_ADDR(x), BP_I2S_RCSR_FEF)) /*! @brief Format value for bitfield I2S_RCSR_FEF. */ #define BF_I2S_RCSR_FEF(v) ((uint32_t)((uint32_t)(v) << BP_I2S_RCSR_FEF) & BM_I2S_RCSR_FEF) /*! @brief Set the FEF field to a new value. */ #define BW_I2S_RCSR_FEF(x, v) (BITBAND_ACCESS32(HW_I2S_RCSR_ADDR(x), BP_I2S_RCSR_FEF) = (v)) /*@}*/ /*! * @name Register I2S_RCSR, field SEF[19] (W1C) * * Indicates that an error in the externally-generated frame sync has been * detected. Write a logic 1 to this field to clear this flag. * * Values: * - 0 - Sync error not detected. * - 1 - Frame sync error detected. */ /*@{*/ #define BP_I2S_RCSR_SEF (19U) /*!< Bit position for I2S_RCSR_SEF. */ #define BM_I2S_RCSR_SEF (0x00080000U) /*!< Bit mask for I2S_RCSR_SEF. */ #define BS_I2S_RCSR_SEF (1U) /*!< Bit field size in bits for I2S_RCSR_SEF. */ /*! @brief Read current value of the I2S_RCSR_SEF field. */ #define BR_I2S_RCSR_SEF(x) (BITBAND_ACCESS32(HW_I2S_RCSR_ADDR(x), BP_I2S_RCSR_SEF)) /*! @brief Format value for bitfield I2S_RCSR_SEF. */ #define BF_I2S_RCSR_SEF(v) ((uint32_t)((uint32_t)(v) << BP_I2S_RCSR_SEF) & BM_I2S_RCSR_SEF) /*! @brief Set the SEF field to a new value. */ #define BW_I2S_RCSR_SEF(x, v) (BITBAND_ACCESS32(HW_I2S_RCSR_ADDR(x), BP_I2S_RCSR_SEF) = (v)) /*@}*/ /*! * @name Register I2S_RCSR, field WSF[20] (W1C) * * Indicates that the start of the configured word has been detected. Write a * logic 1 to this field to clear this flag. * * Values: * - 0 - Start of word not detected. * - 1 - Start of word detected. */ /*@{*/ #define BP_I2S_RCSR_WSF (20U) /*!< Bit position for I2S_RCSR_WSF. */ #define BM_I2S_RCSR_WSF (0x00100000U) /*!< Bit mask for I2S_RCSR_WSF. */ #define BS_I2S_RCSR_WSF (1U) /*!< Bit field size in bits for I2S_RCSR_WSF. */ /*! @brief Read current value of the I2S_RCSR_WSF field. */ #define BR_I2S_RCSR_WSF(x) (BITBAND_ACCESS32(HW_I2S_RCSR_ADDR(x), BP_I2S_RCSR_WSF)) /*! @brief Format value for bitfield I2S_RCSR_WSF. */ #define BF_I2S_RCSR_WSF(v) ((uint32_t)((uint32_t)(v) << BP_I2S_RCSR_WSF) & BM_I2S_RCSR_WSF) /*! @brief Set the WSF field to a new value. */ #define BW_I2S_RCSR_WSF(x, v) (BITBAND_ACCESS32(HW_I2S_RCSR_ADDR(x), BP_I2S_RCSR_WSF) = (v)) /*@}*/ /*! * @name Register I2S_RCSR, field SR[24] (RW) * * Resets the internal receiver logic including the FIFO pointers. * Software-visible registers are not affected, except for the status registers. * * Values: * - 0 - No effect. * - 1 - Software reset. */ /*@{*/ #define BP_I2S_RCSR_SR (24U) /*!< Bit position for I2S_RCSR_SR. */ #define BM_I2S_RCSR_SR (0x01000000U) /*!< Bit mask for I2S_RCSR_SR. */ #define BS_I2S_RCSR_SR (1U) /*!< Bit field size in bits for I2S_RCSR_SR. */ /*! @brief Read current value of the I2S_RCSR_SR field. */ #define BR_I2S_RCSR_SR(x) (BITBAND_ACCESS32(HW_I2S_RCSR_ADDR(x), BP_I2S_RCSR_SR)) /*! @brief Format value for bitfield I2S_RCSR_SR. */ #define BF_I2S_RCSR_SR(v) ((uint32_t)((uint32_t)(v) << BP_I2S_RCSR_SR) & BM_I2S_RCSR_SR) /*! @brief Set the SR field to a new value. */ #define BW_I2S_RCSR_SR(x, v) (BITBAND_ACCESS32(HW_I2S_RCSR_ADDR(x), BP_I2S_RCSR_SR) = (v)) /*@}*/ /*! * @name Register I2S_RCSR, field FR[25] (WORZ) * * Resets the FIFO pointers. Reading this field will always return zero. FIFO * pointers should only be reset when the receiver is disabled or the FIFO error * flag is set. * * Values: * - 0 - No effect. * - 1 - FIFO reset. */ /*@{*/ #define BP_I2S_RCSR_FR (25U) /*!< Bit position for I2S_RCSR_FR. */ #define BM_I2S_RCSR_FR (0x02000000U) /*!< Bit mask for I2S_RCSR_FR. */ #define BS_I2S_RCSR_FR (1U) /*!< Bit field size in bits for I2S_RCSR_FR. */ /*! @brief Format value for bitfield I2S_RCSR_FR. */ #define BF_I2S_RCSR_FR(v) ((uint32_t)((uint32_t)(v) << BP_I2S_RCSR_FR) & BM_I2S_RCSR_FR) /*! @brief Set the FR field to a new value. */ #define BW_I2S_RCSR_FR(x, v) (BITBAND_ACCESS32(HW_I2S_RCSR_ADDR(x), BP_I2S_RCSR_FR) = (v)) /*@}*/ /*! * @name Register I2S_RCSR, field BCE[28] (RW) * * Enables the receive bit clock, separately from RE. This field is * automatically set whenever RE is set. When software clears this field, the receive bit * clock remains enabled, and this field remains set, until the end of the current * frame. * * Values: * - 0 - Receive bit clock is disabled. * - 1 - Receive bit clock is enabled. */ /*@{*/ #define BP_I2S_RCSR_BCE (28U) /*!< Bit position for I2S_RCSR_BCE. */ #define BM_I2S_RCSR_BCE (0x10000000U) /*!< Bit mask for I2S_RCSR_BCE. */ #define BS_I2S_RCSR_BCE (1U) /*!< Bit field size in bits for I2S_RCSR_BCE. */ /*! @brief Read current value of the I2S_RCSR_BCE field. */ #define BR_I2S_RCSR_BCE(x) (BITBAND_ACCESS32(HW_I2S_RCSR_ADDR(x), BP_I2S_RCSR_BCE)) /*! @brief Format value for bitfield I2S_RCSR_BCE. */ #define BF_I2S_RCSR_BCE(v) ((uint32_t)((uint32_t)(v) << BP_I2S_RCSR_BCE) & BM_I2S_RCSR_BCE) /*! @brief Set the BCE field to a new value. */ #define BW_I2S_RCSR_BCE(x, v) (BITBAND_ACCESS32(HW_I2S_RCSR_ADDR(x), BP_I2S_RCSR_BCE) = (v)) /*@}*/ /*! * @name Register I2S_RCSR, field DBGE[29] (RW) * * Enables/disables receiver operation in Debug mode. The receive bit clock is * not affected by Debug mode. * * Values: * - 0 - Receiver is disabled in Debug mode, after completing the current frame. * - 1 - Receiver is enabled in Debug mode. */ /*@{*/ #define BP_I2S_RCSR_DBGE (29U) /*!< Bit position for I2S_RCSR_DBGE. */ #define BM_I2S_RCSR_DBGE (0x20000000U) /*!< Bit mask for I2S_RCSR_DBGE. */ #define BS_I2S_RCSR_DBGE (1U) /*!< Bit field size in bits for I2S_RCSR_DBGE. */ /*! @brief Read current value of the I2S_RCSR_DBGE field. */ #define BR_I2S_RCSR_DBGE(x) (BITBAND_ACCESS32(HW_I2S_RCSR_ADDR(x), BP_I2S_RCSR_DBGE)) /*! @brief Format value for bitfield I2S_RCSR_DBGE. */ #define BF_I2S_RCSR_DBGE(v) ((uint32_t)((uint32_t)(v) << BP_I2S_RCSR_DBGE) & BM_I2S_RCSR_DBGE) /*! @brief Set the DBGE field to a new value. */ #define BW_I2S_RCSR_DBGE(x, v) (BITBAND_ACCESS32(HW_I2S_RCSR_ADDR(x), BP_I2S_RCSR_DBGE) = (v)) /*@}*/ /*! * @name Register I2S_RCSR, field STOPE[30] (RW) * * Configures receiver operation in Stop mode. This bit is ignored and the * receiver is disabled in all low-leakage stop modes. * * Values: * - 0 - Receiver disabled in Stop mode. * - 1 - Receiver enabled in Stop mode. */ /*@{*/ #define BP_I2S_RCSR_STOPE (30U) /*!< Bit position for I2S_RCSR_STOPE. */ #define BM_I2S_RCSR_STOPE (0x40000000U) /*!< Bit mask for I2S_RCSR_STOPE. */ #define BS_I2S_RCSR_STOPE (1U) /*!< Bit field size in bits for I2S_RCSR_STOPE. */ /*! @brief Read current value of the I2S_RCSR_STOPE field. */ #define BR_I2S_RCSR_STOPE(x) (BITBAND_ACCESS32(HW_I2S_RCSR_ADDR(x), BP_I2S_RCSR_STOPE)) /*! @brief Format value for bitfield I2S_RCSR_STOPE. */ #define BF_I2S_RCSR_STOPE(v) ((uint32_t)((uint32_t)(v) << BP_I2S_RCSR_STOPE) & BM_I2S_RCSR_STOPE) /*! @brief Set the STOPE field to a new value. */ #define BW_I2S_RCSR_STOPE(x, v) (BITBAND_ACCESS32(HW_I2S_RCSR_ADDR(x), BP_I2S_RCSR_STOPE) = (v)) /*@}*/ /*! * @name Register I2S_RCSR, field RE[31] (RW) * * Enables/disables the receiver. When software clears this field, the receiver * remains enabled, and this bit remains set, until the end of the current frame. * * Values: * - 0 - Receiver is disabled. * - 1 - Receiver is enabled, or receiver has been disabled and has not yet * reached end of frame. */ /*@{*/ #define BP_I2S_RCSR_RE (31U) /*!< Bit position for I2S_RCSR_RE. */ #define BM_I2S_RCSR_RE (0x80000000U) /*!< Bit mask for I2S_RCSR_RE. */ #define BS_I2S_RCSR_RE (1U) /*!< Bit field size in bits for I2S_RCSR_RE. */ /*! @brief Read current value of the I2S_RCSR_RE field. */ #define BR_I2S_RCSR_RE(x) (BITBAND_ACCESS32(HW_I2S_RCSR_ADDR(x), BP_I2S_RCSR_RE)) /*! @brief Format value for bitfield I2S_RCSR_RE. */ #define BF_I2S_RCSR_RE(v) ((uint32_t)((uint32_t)(v) << BP_I2S_RCSR_RE) & BM_I2S_RCSR_RE) /*! @brief Set the RE field to a new value. */ #define BW_I2S_RCSR_RE(x, v) (BITBAND_ACCESS32(HW_I2S_RCSR_ADDR(x), BP_I2S_RCSR_RE) = (v)) /*@}*/ /******************************************************************************* * HW_I2S_RCR1 - SAI Receive Configuration 1 Register ******************************************************************************/ /*! * @brief HW_I2S_RCR1 - SAI Receive Configuration 1 Register (RW) * * Reset value: 0x00000000U */ typedef union _hw_i2s_rcr1 { uint32_t U; struct _hw_i2s_rcr1_bitfields { uint32_t RFW : 3; /*!< [2:0] Receive FIFO Watermark */ uint32_t RESERVED0 : 29; /*!< [31:3] */ } B; } hw_i2s_rcr1_t; /*! * @name Constants and macros for entire I2S_RCR1 register */ /*@{*/ #define HW_I2S_RCR1_ADDR(x) ((x) + 0x84U) #define HW_I2S_RCR1(x) (*(__IO hw_i2s_rcr1_t *) HW_I2S_RCR1_ADDR(x)) #define HW_I2S_RCR1_RD(x) (HW_I2S_RCR1(x).U) #define HW_I2S_RCR1_WR(x, v) (HW_I2S_RCR1(x).U = (v)) #define HW_I2S_RCR1_SET(x, v) (HW_I2S_RCR1_WR(x, HW_I2S_RCR1_RD(x) | (v))) #define HW_I2S_RCR1_CLR(x, v) (HW_I2S_RCR1_WR(x, HW_I2S_RCR1_RD(x) & ~(v))) #define HW_I2S_RCR1_TOG(x, v) (HW_I2S_RCR1_WR(x, HW_I2S_RCR1_RD(x) ^ (v))) /*@}*/ /* * Constants & macros for individual I2S_RCR1 bitfields */ /*! * @name Register I2S_RCR1, field RFW[2:0] (RW) * * Configures the watermark level for all enabled receiver channels. */ /*@{*/ #define BP_I2S_RCR1_RFW (0U) /*!< Bit position for I2S_RCR1_RFW. */ #define BM_I2S_RCR1_RFW (0x00000007U) /*!< Bit mask for I2S_RCR1_RFW. */ #define BS_I2S_RCR1_RFW (3U) /*!< Bit field size in bits for I2S_RCR1_RFW. */ /*! @brief Read current value of the I2S_RCR1_RFW field. */ #define BR_I2S_RCR1_RFW(x) (HW_I2S_RCR1(x).B.RFW) /*! @brief Format value for bitfield I2S_RCR1_RFW. */ #define BF_I2S_RCR1_RFW(v) ((uint32_t)((uint32_t)(v) << BP_I2S_RCR1_RFW) & BM_I2S_RCR1_RFW) /*! @brief Set the RFW field to a new value. */ #define BW_I2S_RCR1_RFW(x, v) (HW_I2S_RCR1_WR(x, (HW_I2S_RCR1_RD(x) & ~BM_I2S_RCR1_RFW) | BF_I2S_RCR1_RFW(v))) /*@}*/ /******************************************************************************* * HW_I2S_RCR2 - SAI Receive Configuration 2 Register ******************************************************************************/ /*! * @brief HW_I2S_RCR2 - SAI Receive Configuration 2 Register (RW) * * Reset value: 0x00000000U * * This register must not be altered when RCSR[RE] is set. */ typedef union _hw_i2s_rcr2 { uint32_t U; struct _hw_i2s_rcr2_bitfields { uint32_t DIV : 8; /*!< [7:0] Bit Clock Divide */ uint32_t RESERVED0 : 16; /*!< [23:8] */ uint32_t BCD : 1; /*!< [24] Bit Clock Direction */ uint32_t BCP : 1; /*!< [25] Bit Clock Polarity */ uint32_t MSEL : 2; /*!< [27:26] MCLK Select */ uint32_t BCI : 1; /*!< [28] Bit Clock Input */ uint32_t BCS : 1; /*!< [29] Bit Clock Swap */ uint32_t SYNC : 2; /*!< [31:30] Synchronous Mode */ } B; } hw_i2s_rcr2_t; /*! * @name Constants and macros for entire I2S_RCR2 register */ /*@{*/ #define HW_I2S_RCR2_ADDR(x) ((x) + 0x88U) #define HW_I2S_RCR2(x) (*(__IO hw_i2s_rcr2_t *) HW_I2S_RCR2_ADDR(x)) #define HW_I2S_RCR2_RD(x) (HW_I2S_RCR2(x).U) #define HW_I2S_RCR2_WR(x, v) (HW_I2S_RCR2(x).U = (v)) #define HW_I2S_RCR2_SET(x, v) (HW_I2S_RCR2_WR(x, HW_I2S_RCR2_RD(x) | (v))) #define HW_I2S_RCR2_CLR(x, v) (HW_I2S_RCR2_WR(x, HW_I2S_RCR2_RD(x) & ~(v))) #define HW_I2S_RCR2_TOG(x, v) (HW_I2S_RCR2_WR(x, HW_I2S_RCR2_RD(x) ^ (v))) /*@}*/ /* * Constants & macros for individual I2S_RCR2 bitfields */ /*! * @name Register I2S_RCR2, field DIV[7:0] (RW) * * Divides down the audio master clock to generate the bit clock when configured * for an internal bit clock. The division value is (DIV + 1) * 2. */ /*@{*/ #define BP_I2S_RCR2_DIV (0U) /*!< Bit position for I2S_RCR2_DIV. */ #define BM_I2S_RCR2_DIV (0x000000FFU) /*!< Bit mask for I2S_RCR2_DIV. */ #define BS_I2S_RCR2_DIV (8U) /*!< Bit field size in bits for I2S_RCR2_DIV. */ /*! @brief Read current value of the I2S_RCR2_DIV field. */ #define BR_I2S_RCR2_DIV(x) (HW_I2S_RCR2(x).B.DIV) /*! @brief Format value for bitfield I2S_RCR2_DIV. */ #define BF_I2S_RCR2_DIV(v) ((uint32_t)((uint32_t)(v) << BP_I2S_RCR2_DIV) & BM_I2S_RCR2_DIV) /*! @brief Set the DIV field to a new value. */ #define BW_I2S_RCR2_DIV(x, v) (HW_I2S_RCR2_WR(x, (HW_I2S_RCR2_RD(x) & ~BM_I2S_RCR2_DIV) | BF_I2S_RCR2_DIV(v))) /*@}*/ /*! * @name Register I2S_RCR2, field BCD[24] (RW) * * Configures the direction of the bit clock. * * Values: * - 0 - Bit clock is generated externally in Slave mode. * - 1 - Bit clock is generated internally in Master mode. */ /*@{*/ #define BP_I2S_RCR2_BCD (24U) /*!< Bit position for I2S_RCR2_BCD. */ #define BM_I2S_RCR2_BCD (0x01000000U) /*!< Bit mask for I2S_RCR2_BCD. */ #define BS_I2S_RCR2_BCD (1U) /*!< Bit field size in bits for I2S_RCR2_BCD. */ /*! @brief Read current value of the I2S_RCR2_BCD field. */ #define BR_I2S_RCR2_BCD(x) (BITBAND_ACCESS32(HW_I2S_RCR2_ADDR(x), BP_I2S_RCR2_BCD)) /*! @brief Format value for bitfield I2S_RCR2_BCD. */ #define BF_I2S_RCR2_BCD(v) ((uint32_t)((uint32_t)(v) << BP_I2S_RCR2_BCD) & BM_I2S_RCR2_BCD) /*! @brief Set the BCD field to a new value. */ #define BW_I2S_RCR2_BCD(x, v) (BITBAND_ACCESS32(HW_I2S_RCR2_ADDR(x), BP_I2S_RCR2_BCD) = (v)) /*@}*/ /*! * @name Register I2S_RCR2, field BCP[25] (RW) * * Configures the polarity of the bit clock. * * Values: * - 0 - Bit Clock is active high with drive outputs on rising edge and sample * inputs on falling edge. * - 1 - Bit Clock is active low with drive outputs on falling edge and sample * inputs on rising edge. */ /*@{*/ #define BP_I2S_RCR2_BCP (25U) /*!< Bit position for I2S_RCR2_BCP. */ #define BM_I2S_RCR2_BCP (0x02000000U) /*!< Bit mask for I2S_RCR2_BCP. */ #define BS_I2S_RCR2_BCP (1U) /*!< Bit field size in bits for I2S_RCR2_BCP. */ /*! @brief Read current value of the I2S_RCR2_BCP field. */ #define BR_I2S_RCR2_BCP(x) (BITBAND_ACCESS32(HW_I2S_RCR2_ADDR(x), BP_I2S_RCR2_BCP)) /*! @brief Format value for bitfield I2S_RCR2_BCP. */ #define BF_I2S_RCR2_BCP(v) ((uint32_t)((uint32_t)(v) << BP_I2S_RCR2_BCP) & BM_I2S_RCR2_BCP) /*! @brief Set the BCP field to a new value. */ #define BW_I2S_RCR2_BCP(x, v) (BITBAND_ACCESS32(HW_I2S_RCR2_ADDR(x), BP_I2S_RCR2_BCP) = (v)) /*@}*/ /*! * @name Register I2S_RCR2, field MSEL[27:26] (RW) * * Selects the audio Master Clock option used to generate an internally * generated bit clock. This field has no effect when configured for an externally * generated bit clock. Depending on the device, some Master Clock options might not be * available. See the chip configuration details for the availability and * chip-specific meaning of each option. * * Values: * - 00 - Bus Clock selected. * - 01 - Master Clock (MCLK) 1 option selected. * - 10 - Master Clock (MCLK) 2 option selected. * - 11 - Master Clock (MCLK) 3 option selected. */ /*@{*/ #define BP_I2S_RCR2_MSEL (26U) /*!< Bit position for I2S_RCR2_MSEL. */ #define BM_I2S_RCR2_MSEL (0x0C000000U) /*!< Bit mask for I2S_RCR2_MSEL. */ #define BS_I2S_RCR2_MSEL (2U) /*!< Bit field size in bits for I2S_RCR2_MSEL. */ /*! @brief Read current value of the I2S_RCR2_MSEL field. */ #define BR_I2S_RCR2_MSEL(x) (HW_I2S_RCR2(x).B.MSEL) /*! @brief Format value for bitfield I2S_RCR2_MSEL. */ #define BF_I2S_RCR2_MSEL(v) ((uint32_t)((uint32_t)(v) << BP_I2S_RCR2_MSEL) & BM_I2S_RCR2_MSEL) /*! @brief Set the MSEL field to a new value. */ #define BW_I2S_RCR2_MSEL(x, v) (HW_I2S_RCR2_WR(x, (HW_I2S_RCR2_RD(x) & ~BM_I2S_RCR2_MSEL) | BF_I2S_RCR2_MSEL(v))) /*@}*/ /*! * @name Register I2S_RCR2, field BCI[28] (RW) * * When this field is set and using an internally generated bit clock in either * synchronous or asynchronous mode, the bit clock actually used by the receiver * is delayed by the pad output delay (the receiver is clocked by the pad input * as if the clock was externally generated). This has the effect of decreasing * the data input setup time, but increasing the data output valid time. The slave * mode timing from the datasheet should be used for the receiver when this bit * is set. In synchronous mode, this bit allows the receiver to use the slave mode * timing from the datasheet, while the transmitter uses the master mode timing. * This field has no effect when configured for an externally generated bit * clock or when synchronous to another SAI peripheral . * * Values: * - 0 - No effect. * - 1 - Internal logic is clocked as if bit clock was externally generated. */ /*@{*/ #define BP_I2S_RCR2_BCI (28U) /*!< Bit position for I2S_RCR2_BCI. */ #define BM_I2S_RCR2_BCI (0x10000000U) /*!< Bit mask for I2S_RCR2_BCI. */ #define BS_I2S_RCR2_BCI (1U) /*!< Bit field size in bits for I2S_RCR2_BCI. */ /*! @brief Read current value of the I2S_RCR2_BCI field. */ #define BR_I2S_RCR2_BCI(x) (BITBAND_ACCESS32(HW_I2S_RCR2_ADDR(x), BP_I2S_RCR2_BCI)) /*! @brief Format value for bitfield I2S_RCR2_BCI. */ #define BF_I2S_RCR2_BCI(v) ((uint32_t)((uint32_t)(v) << BP_I2S_RCR2_BCI) & BM_I2S_RCR2_BCI) /*! @brief Set the BCI field to a new value. */ #define BW_I2S_RCR2_BCI(x, v) (BITBAND_ACCESS32(HW_I2S_RCR2_ADDR(x), BP_I2S_RCR2_BCI) = (v)) /*@}*/ /*! * @name Register I2S_RCR2, field BCS[29] (RW) * * This field swaps the bit clock used by the receiver. When the receiver is * configured in asynchronous mode and this bit is set, the receiver is clocked by * the transmitter bit clock (SAI_TX_BCLK). This allows the transmitter and * receiver to share the same bit clock, but the receiver continues to use the receiver * frame sync (SAI_RX_SYNC). When the receiver is configured in synchronous * mode, the transmitter BCS field and receiver BCS field must be set to the same * value. When both are set, the transmitter and receiver are both clocked by the * receiver bit clock (SAI_RX_BCLK) but use the transmitter frame sync * (SAI_TX_SYNC). This field has no effect when synchronous to another SAI peripheral. * * Values: * - 0 - Use the normal bit clock source. * - 1 - Swap the bit clock source. */ /*@{*/ #define BP_I2S_RCR2_BCS (29U) /*!< Bit position for I2S_RCR2_BCS. */ #define BM_I2S_RCR2_BCS (0x20000000U) /*!< Bit mask for I2S_RCR2_BCS. */ #define BS_I2S_RCR2_BCS (1U) /*!< Bit field size in bits for I2S_RCR2_BCS. */ /*! @brief Read current value of the I2S_RCR2_BCS field. */ #define BR_I2S_RCR2_BCS(x) (BITBAND_ACCESS32(HW_I2S_RCR2_ADDR(x), BP_I2S_RCR2_BCS)) /*! @brief Format value for bitfield I2S_RCR2_BCS. */ #define BF_I2S_RCR2_BCS(v) ((uint32_t)((uint32_t)(v) << BP_I2S_RCR2_BCS) & BM_I2S_RCR2_BCS) /*! @brief Set the BCS field to a new value. */ #define BW_I2S_RCR2_BCS(x, v) (BITBAND_ACCESS32(HW_I2S_RCR2_ADDR(x), BP_I2S_RCR2_BCS) = (v)) /*@}*/ /*! * @name Register I2S_RCR2, field SYNC[31:30] (RW) * * Configures between asynchronous and synchronous modes of operation. When * configured for a synchronous mode of operation, the transmitter or other SAI * peripheral must be configured for asynchronous operation. * * Values: * - 00 - Asynchronous mode. * - 01 - Synchronous with transmitter. * - 10 - Synchronous with another SAI receiver. * - 11 - Synchronous with another SAI transmitter. */ /*@{*/ #define BP_I2S_RCR2_SYNC (30U) /*!< Bit position for I2S_RCR2_SYNC. */ #define BM_I2S_RCR2_SYNC (0xC0000000U) /*!< Bit mask for I2S_RCR2_SYNC. */ #define BS_I2S_RCR2_SYNC (2U) /*!< Bit field size in bits for I2S_RCR2_SYNC. */ /*! @brief Read current value of the I2S_RCR2_SYNC field. */ #define BR_I2S_RCR2_SYNC(x) (HW_I2S_RCR2(x).B.SYNC) /*! @brief Format value for bitfield I2S_RCR2_SYNC. */ #define BF_I2S_RCR2_SYNC(v) ((uint32_t)((uint32_t)(v) << BP_I2S_RCR2_SYNC) & BM_I2S_RCR2_SYNC) /*! @brief Set the SYNC field to a new value. */ #define BW_I2S_RCR2_SYNC(x, v) (HW_I2S_RCR2_WR(x, (HW_I2S_RCR2_RD(x) & ~BM_I2S_RCR2_SYNC) | BF_I2S_RCR2_SYNC(v))) /*@}*/ /******************************************************************************* * HW_I2S_RCR3 - SAI Receive Configuration 3 Register ******************************************************************************/ /*! * @brief HW_I2S_RCR3 - SAI Receive Configuration 3 Register (RW) * * Reset value: 0x00000000U * * This register must not be altered when RCSR[RE] is set. */ typedef union _hw_i2s_rcr3 { uint32_t U; struct _hw_i2s_rcr3_bitfields { uint32_t WDFL : 5; /*!< [4:0] Word Flag Configuration */ uint32_t RESERVED0 : 11; /*!< [15:5] */ uint32_t RCE : 2; /*!< [17:16] Receive Channel Enable */ uint32_t RESERVED1 : 14; /*!< [31:18] */ } B; } hw_i2s_rcr3_t; /*! * @name Constants and macros for entire I2S_RCR3 register */ /*@{*/ #define HW_I2S_RCR3_ADDR(x) ((x) + 0x8CU) #define HW_I2S_RCR3(x) (*(__IO hw_i2s_rcr3_t *) HW_I2S_RCR3_ADDR(x)) #define HW_I2S_RCR3_RD(x) (HW_I2S_RCR3(x).U) #define HW_I2S_RCR3_WR(x, v) (HW_I2S_RCR3(x).U = (v)) #define HW_I2S_RCR3_SET(x, v) (HW_I2S_RCR3_WR(x, HW_I2S_RCR3_RD(x) | (v))) #define HW_I2S_RCR3_CLR(x, v) (HW_I2S_RCR3_WR(x, HW_I2S_RCR3_RD(x) & ~(v))) #define HW_I2S_RCR3_TOG(x, v) (HW_I2S_RCR3_WR(x, HW_I2S_RCR3_RD(x) ^ (v))) /*@}*/ /* * Constants & macros for individual I2S_RCR3 bitfields */ /*! * @name Register I2S_RCR3, field WDFL[4:0] (RW) * * Configures which word the start of word flag is set. The value written should * be one less than the word number (for example, write zero to configure for * the first word in the frame). When configured to a value greater than the Frame * Size field, then the start of word flag is never set. */ /*@{*/ #define BP_I2S_RCR3_WDFL (0U) /*!< Bit position for I2S_RCR3_WDFL. */ #define BM_I2S_RCR3_WDFL (0x0000001FU) /*!< Bit mask for I2S_RCR3_WDFL. */ #define BS_I2S_RCR3_WDFL (5U) /*!< Bit field size in bits for I2S_RCR3_WDFL. */ /*! @brief Read current value of the I2S_RCR3_WDFL field. */ #define BR_I2S_RCR3_WDFL(x) (HW_I2S_RCR3(x).B.WDFL) /*! @brief Format value for bitfield I2S_RCR3_WDFL. */ #define BF_I2S_RCR3_WDFL(v) ((uint32_t)((uint32_t)(v) << BP_I2S_RCR3_WDFL) & BM_I2S_RCR3_WDFL) /*! @brief Set the WDFL field to a new value. */ #define BW_I2S_RCR3_WDFL(x, v) (HW_I2S_RCR3_WR(x, (HW_I2S_RCR3_RD(x) & ~BM_I2S_RCR3_WDFL) | BF_I2S_RCR3_WDFL(v))) /*@}*/ /*! * @name Register I2S_RCR3, field RCE[17:16] (RW) * * Enables the corresponding data channel for receive operation. A channel must * be enabled before its FIFO is accessed. * * Values: * - 0 - Receive data channel N is disabled. * - 1 - Receive data channel N is enabled. */ /*@{*/ #define BP_I2S_RCR3_RCE (16U) /*!< Bit position for I2S_RCR3_RCE. */ #define BM_I2S_RCR3_RCE (0x00030000U) /*!< Bit mask for I2S_RCR3_RCE. */ #define BS_I2S_RCR3_RCE (2U) /*!< Bit field size in bits for I2S_RCR3_RCE. */ /*! @brief Read current value of the I2S_RCR3_RCE field. */ #define BR_I2S_RCR3_RCE(x) (HW_I2S_RCR3(x).B.RCE) /*! @brief Format value for bitfield I2S_RCR3_RCE. */ #define BF_I2S_RCR3_RCE(v) ((uint32_t)((uint32_t)(v) << BP_I2S_RCR3_RCE) & BM_I2S_RCR3_RCE) /*! @brief Set the RCE field to a new value. */ #define BW_I2S_RCR3_RCE(x, v) (HW_I2S_RCR3_WR(x, (HW_I2S_RCR3_RD(x) & ~BM_I2S_RCR3_RCE) | BF_I2S_RCR3_RCE(v))) /*@}*/ /******************************************************************************* * HW_I2S_RCR4 - SAI Receive Configuration 4 Register ******************************************************************************/ /*! * @brief HW_I2S_RCR4 - SAI Receive Configuration 4 Register (RW) * * Reset value: 0x00000000U * * This register must not be altered when RCSR[RE] is set. */ typedef union _hw_i2s_rcr4 { uint32_t U; struct _hw_i2s_rcr4_bitfields { uint32_t FSD : 1; /*!< [0] Frame Sync Direction */ uint32_t FSP : 1; /*!< [1] Frame Sync Polarity */ uint32_t RESERVED0 : 1; /*!< [2] */ uint32_t FSE : 1; /*!< [3] Frame Sync Early */ uint32_t MF : 1; /*!< [4] MSB First */ uint32_t RESERVED1 : 3; /*!< [7:5] */ uint32_t SYWD : 5; /*!< [12:8] Sync Width */ uint32_t RESERVED2 : 3; /*!< [15:13] */ uint32_t FRSZ : 5; /*!< [20:16] Frame Size */ uint32_t RESERVED3 : 11; /*!< [31:21] */ } B; } hw_i2s_rcr4_t; /*! * @name Constants and macros for entire I2S_RCR4 register */ /*@{*/ #define HW_I2S_RCR4_ADDR(x) ((x) + 0x90U) #define HW_I2S_RCR4(x) (*(__IO hw_i2s_rcr4_t *) HW_I2S_RCR4_ADDR(x)) #define HW_I2S_RCR4_RD(x) (HW_I2S_RCR4(x).U) #define HW_I2S_RCR4_WR(x, v) (HW_I2S_RCR4(x).U = (v)) #define HW_I2S_RCR4_SET(x, v) (HW_I2S_RCR4_WR(x, HW_I2S_RCR4_RD(x) | (v))) #define HW_I2S_RCR4_CLR(x, v) (HW_I2S_RCR4_WR(x, HW_I2S_RCR4_RD(x) & ~(v))) #define HW_I2S_RCR4_TOG(x, v) (HW_I2S_RCR4_WR(x, HW_I2S_RCR4_RD(x) ^ (v))) /*@}*/ /* * Constants & macros for individual I2S_RCR4 bitfields */ /*! * @name Register I2S_RCR4, field FSD[0] (RW) * * Configures the direction of the frame sync. * * Values: * - 0 - Frame Sync is generated externally in Slave mode. * - 1 - Frame Sync is generated internally in Master mode. */ /*@{*/ #define BP_I2S_RCR4_FSD (0U) /*!< Bit position for I2S_RCR4_FSD. */ #define BM_I2S_RCR4_FSD (0x00000001U) /*!< Bit mask for I2S_RCR4_FSD. */ #define BS_I2S_RCR4_FSD (1U) /*!< Bit field size in bits for I2S_RCR4_FSD. */ /*! @brief Read current value of the I2S_RCR4_FSD field. */ #define BR_I2S_RCR4_FSD(x) (BITBAND_ACCESS32(HW_I2S_RCR4_ADDR(x), BP_I2S_RCR4_FSD)) /*! @brief Format value for bitfield I2S_RCR4_FSD. */ #define BF_I2S_RCR4_FSD(v) ((uint32_t)((uint32_t)(v) << BP_I2S_RCR4_FSD) & BM_I2S_RCR4_FSD) /*! @brief Set the FSD field to a new value. */ #define BW_I2S_RCR4_FSD(x, v) (BITBAND_ACCESS32(HW_I2S_RCR4_ADDR(x), BP_I2S_RCR4_FSD) = (v)) /*@}*/ /*! * @name Register I2S_RCR4, field FSP[1] (RW) * * Configures the polarity of the frame sync. * * Values: * - 0 - Frame sync is active high. * - 1 - Frame sync is active low. */ /*@{*/ #define BP_I2S_RCR4_FSP (1U) /*!< Bit position for I2S_RCR4_FSP. */ #define BM_I2S_RCR4_FSP (0x00000002U) /*!< Bit mask for I2S_RCR4_FSP. */ #define BS_I2S_RCR4_FSP (1U) /*!< Bit field size in bits for I2S_RCR4_FSP. */ /*! @brief Read current value of the I2S_RCR4_FSP field. */ #define BR_I2S_RCR4_FSP(x) (BITBAND_ACCESS32(HW_I2S_RCR4_ADDR(x), BP_I2S_RCR4_FSP)) /*! @brief Format value for bitfield I2S_RCR4_FSP. */ #define BF_I2S_RCR4_FSP(v) ((uint32_t)((uint32_t)(v) << BP_I2S_RCR4_FSP) & BM_I2S_RCR4_FSP) /*! @brief Set the FSP field to a new value. */ #define BW_I2S_RCR4_FSP(x, v) (BITBAND_ACCESS32(HW_I2S_RCR4_ADDR(x), BP_I2S_RCR4_FSP) = (v)) /*@}*/ /*! * @name Register I2S_RCR4, field FSE[3] (RW) * * Values: * - 0 - Frame sync asserts with the first bit of the frame. * - 1 - Frame sync asserts one bit before the first bit of the frame. */ /*@{*/ #define BP_I2S_RCR4_FSE (3U) /*!< Bit position for I2S_RCR4_FSE. */ #define BM_I2S_RCR4_FSE (0x00000008U) /*!< Bit mask for I2S_RCR4_FSE. */ #define BS_I2S_RCR4_FSE (1U) /*!< Bit field size in bits for I2S_RCR4_FSE. */ /*! @brief Read current value of the I2S_RCR4_FSE field. */ #define BR_I2S_RCR4_FSE(x) (BITBAND_ACCESS32(HW_I2S_RCR4_ADDR(x), BP_I2S_RCR4_FSE)) /*! @brief Format value for bitfield I2S_RCR4_FSE. */ #define BF_I2S_RCR4_FSE(v) ((uint32_t)((uint32_t)(v) << BP_I2S_RCR4_FSE) & BM_I2S_RCR4_FSE) /*! @brief Set the FSE field to a new value. */ #define BW_I2S_RCR4_FSE(x, v) (BITBAND_ACCESS32(HW_I2S_RCR4_ADDR(x), BP_I2S_RCR4_FSE) = (v)) /*@}*/ /*! * @name Register I2S_RCR4, field MF[4] (RW) * * Configures whether the LSB or the MSB is received first. * * Values: * - 0 - LSB is received first. * - 1 - MSB is received first. */ /*@{*/ #define BP_I2S_RCR4_MF (4U) /*!< Bit position for I2S_RCR4_MF. */ #define BM_I2S_RCR4_MF (0x00000010U) /*!< Bit mask for I2S_RCR4_MF. */ #define BS_I2S_RCR4_MF (1U) /*!< Bit field size in bits for I2S_RCR4_MF. */ /*! @brief Read current value of the I2S_RCR4_MF field. */ #define BR_I2S_RCR4_MF(x) (BITBAND_ACCESS32(HW_I2S_RCR4_ADDR(x), BP_I2S_RCR4_MF)) /*! @brief Format value for bitfield I2S_RCR4_MF. */ #define BF_I2S_RCR4_MF(v) ((uint32_t)((uint32_t)(v) << BP_I2S_RCR4_MF) & BM_I2S_RCR4_MF) /*! @brief Set the MF field to a new value. */ #define BW_I2S_RCR4_MF(x, v) (BITBAND_ACCESS32(HW_I2S_RCR4_ADDR(x), BP_I2S_RCR4_MF) = (v)) /*@}*/ /*! * @name Register I2S_RCR4, field SYWD[12:8] (RW) * * Configures the length of the frame sync in number of bit clocks. The value * written must be one less than the number of bit clocks. For example, write 0 for * the frame sync to assert for one bit clock only. The sync width cannot be * configured longer than the first word of the frame. */ /*@{*/ #define BP_I2S_RCR4_SYWD (8U) /*!< Bit position for I2S_RCR4_SYWD. */ #define BM_I2S_RCR4_SYWD (0x00001F00U) /*!< Bit mask for I2S_RCR4_SYWD. */ #define BS_I2S_RCR4_SYWD (5U) /*!< Bit field size in bits for I2S_RCR4_SYWD. */ /*! @brief Read current value of the I2S_RCR4_SYWD field. */ #define BR_I2S_RCR4_SYWD(x) (HW_I2S_RCR4(x).B.SYWD) /*! @brief Format value for bitfield I2S_RCR4_SYWD. */ #define BF_I2S_RCR4_SYWD(v) ((uint32_t)((uint32_t)(v) << BP_I2S_RCR4_SYWD) & BM_I2S_RCR4_SYWD) /*! @brief Set the SYWD field to a new value. */ #define BW_I2S_RCR4_SYWD(x, v) (HW_I2S_RCR4_WR(x, (HW_I2S_RCR4_RD(x) & ~BM_I2S_RCR4_SYWD) | BF_I2S_RCR4_SYWD(v))) /*@}*/ /*! * @name Register I2S_RCR4, field FRSZ[20:16] (RW) * * Configures the number of words in each frame. The value written must be one * less than the number of words in the frame. For example, write 0 for one word * per frame. The maximum supported frame size is 32 words. */ /*@{*/ #define BP_I2S_RCR4_FRSZ (16U) /*!< Bit position for I2S_RCR4_FRSZ. */ #define BM_I2S_RCR4_FRSZ (0x001F0000U) /*!< Bit mask for I2S_RCR4_FRSZ. */ #define BS_I2S_RCR4_FRSZ (5U) /*!< Bit field size in bits for I2S_RCR4_FRSZ. */ /*! @brief Read current value of the I2S_RCR4_FRSZ field. */ #define BR_I2S_RCR4_FRSZ(x) (HW_I2S_RCR4(x).B.FRSZ) /*! @brief Format value for bitfield I2S_RCR4_FRSZ. */ #define BF_I2S_RCR4_FRSZ(v) ((uint32_t)((uint32_t)(v) << BP_I2S_RCR4_FRSZ) & BM_I2S_RCR4_FRSZ) /*! @brief Set the FRSZ field to a new value. */ #define BW_I2S_RCR4_FRSZ(x, v) (HW_I2S_RCR4_WR(x, (HW_I2S_RCR4_RD(x) & ~BM_I2S_RCR4_FRSZ) | BF_I2S_RCR4_FRSZ(v))) /*@}*/ /******************************************************************************* * HW_I2S_RCR5 - SAI Receive Configuration 5 Register ******************************************************************************/ /*! * @brief HW_I2S_RCR5 - SAI Receive Configuration 5 Register (RW) * * Reset value: 0x00000000U * * This register must not be altered when RCSR[RE] is set. */ typedef union _hw_i2s_rcr5 { uint32_t U; struct _hw_i2s_rcr5_bitfields { uint32_t RESERVED0 : 8; /*!< [7:0] */ uint32_t FBT : 5; /*!< [12:8] First Bit Shifted */ uint32_t RESERVED1 : 3; /*!< [15:13] */ uint32_t W0W : 5; /*!< [20:16] Word 0 Width */ uint32_t RESERVED2 : 3; /*!< [23:21] */ uint32_t WNW : 5; /*!< [28:24] Word N Width */ uint32_t RESERVED3 : 3; /*!< [31:29] */ } B; } hw_i2s_rcr5_t; /*! * @name Constants and macros for entire I2S_RCR5 register */ /*@{*/ #define HW_I2S_RCR5_ADDR(x) ((x) + 0x94U) #define HW_I2S_RCR5(x) (*(__IO hw_i2s_rcr5_t *) HW_I2S_RCR5_ADDR(x)) #define HW_I2S_RCR5_RD(x) (HW_I2S_RCR5(x).U) #define HW_I2S_RCR5_WR(x, v) (HW_I2S_RCR5(x).U = (v)) #define HW_I2S_RCR5_SET(x, v) (HW_I2S_RCR5_WR(x, HW_I2S_RCR5_RD(x) | (v))) #define HW_I2S_RCR5_CLR(x, v) (HW_I2S_RCR5_WR(x, HW_I2S_RCR5_RD(x) & ~(v))) #define HW_I2S_RCR5_TOG(x, v) (HW_I2S_RCR5_WR(x, HW_I2S_RCR5_RD(x) ^ (v))) /*@}*/ /* * Constants & macros for individual I2S_RCR5 bitfields */ /*! * @name Register I2S_RCR5, field FBT[12:8] (RW) * * Configures the bit index for the first bit received for each word in the * frame. If configured for MSB First, the index of the next bit received is one less * than the current bit received. If configured for LSB First, the index of the * next bit received is one more than the current bit received. The value written * must be greater than or equal to the word width when configured for MSB * First. The value written must be less than or equal to 31-word width when * configured for LSB First. */ /*@{*/ #define BP_I2S_RCR5_FBT (8U) /*!< Bit position for I2S_RCR5_FBT. */ #define BM_I2S_RCR5_FBT (0x00001F00U) /*!< Bit mask for I2S_RCR5_FBT. */ #define BS_I2S_RCR5_FBT (5U) /*!< Bit field size in bits for I2S_RCR5_FBT. */ /*! @brief Read current value of the I2S_RCR5_FBT field. */ #define BR_I2S_RCR5_FBT(x) (HW_I2S_RCR5(x).B.FBT) /*! @brief Format value for bitfield I2S_RCR5_FBT. */ #define BF_I2S_RCR5_FBT(v) ((uint32_t)((uint32_t)(v) << BP_I2S_RCR5_FBT) & BM_I2S_RCR5_FBT) /*! @brief Set the FBT field to a new value. */ #define BW_I2S_RCR5_FBT(x, v) (HW_I2S_RCR5_WR(x, (HW_I2S_RCR5_RD(x) & ~BM_I2S_RCR5_FBT) | BF_I2S_RCR5_FBT(v))) /*@}*/ /*! * @name Register I2S_RCR5, field W0W[20:16] (RW) * * Configures the number of bits in the first word in each frame. The value * written must be one less than the number of bits in the first word. Word width of * less than 8 bits is not supported if there is only one word per frame. */ /*@{*/ #define BP_I2S_RCR5_W0W (16U) /*!< Bit position for I2S_RCR5_W0W. */ #define BM_I2S_RCR5_W0W (0x001F0000U) /*!< Bit mask for I2S_RCR5_W0W. */ #define BS_I2S_RCR5_W0W (5U) /*!< Bit field size in bits for I2S_RCR5_W0W. */ /*! @brief Read current value of the I2S_RCR5_W0W field. */ #define BR_I2S_RCR5_W0W(x) (HW_I2S_RCR5(x).B.W0W) /*! @brief Format value for bitfield I2S_RCR5_W0W. */ #define BF_I2S_RCR5_W0W(v) ((uint32_t)((uint32_t)(v) << BP_I2S_RCR5_W0W) & BM_I2S_RCR5_W0W) /*! @brief Set the W0W field to a new value. */ #define BW_I2S_RCR5_W0W(x, v) (HW_I2S_RCR5_WR(x, (HW_I2S_RCR5_RD(x) & ~BM_I2S_RCR5_W0W) | BF_I2S_RCR5_W0W(v))) /*@}*/ /*! * @name Register I2S_RCR5, field WNW[28:24] (RW) * * Configures the number of bits in each word, for each word except the first in * the frame. The value written must be one less than the number of bits per * word. Word width of less than 8 bits is not supported. */ /*@{*/ #define BP_I2S_RCR5_WNW (24U) /*!< Bit position for I2S_RCR5_WNW. */ #define BM_I2S_RCR5_WNW (0x1F000000U) /*!< Bit mask for I2S_RCR5_WNW. */ #define BS_I2S_RCR5_WNW (5U) /*!< Bit field size in bits for I2S_RCR5_WNW. */ /*! @brief Read current value of the I2S_RCR5_WNW field. */ #define BR_I2S_RCR5_WNW(x) (HW_I2S_RCR5(x).B.WNW) /*! @brief Format value for bitfield I2S_RCR5_WNW. */ #define BF_I2S_RCR5_WNW(v) ((uint32_t)((uint32_t)(v) << BP_I2S_RCR5_WNW) & BM_I2S_RCR5_WNW) /*! @brief Set the WNW field to a new value. */ #define BW_I2S_RCR5_WNW(x, v) (HW_I2S_RCR5_WR(x, (HW_I2S_RCR5_RD(x) & ~BM_I2S_RCR5_WNW) | BF_I2S_RCR5_WNW(v))) /*@}*/ /******************************************************************************* * HW_I2S_RDRn - SAI Receive Data Register ******************************************************************************/ /*! * @brief HW_I2S_RDRn - SAI Receive Data Register (RO) * * Reset value: 0x00000000U * * Reading this register introduces one additional peripheral clock wait state * on each read. */ typedef union _hw_i2s_rdrn { uint32_t U; struct _hw_i2s_rdrn_bitfields { uint32_t RDR : 32; /*!< [31:0] Receive Data Register */ } B; } hw_i2s_rdrn_t; /*! * @name Constants and macros for entire I2S_RDRn register */ /*@{*/ #define HW_I2S_RDRn_COUNT (2U) #define HW_I2S_RDRn_ADDR(x, n) ((x) + 0xA0U + (0x4U * (n))) #define HW_I2S_RDRn(x, n) (*(__I hw_i2s_rdrn_t *) HW_I2S_RDRn_ADDR(x, n)) #define HW_I2S_RDRn_RD(x, n) (HW_I2S_RDRn(x, n).U) /*@}*/ /* * Constants & macros for individual I2S_RDRn bitfields */ /*! * @name Register I2S_RDRn, field RDR[31:0] (RO) * * The corresponding RCR3[RCE] bit must be set before accessing the channel's * receive data register. Reads from this register when the receive FIFO is not * empty will return the data from the top of the receive FIFO. Reads from this * register when the receive FIFO is empty are ignored. */ /*@{*/ #define BP_I2S_RDRn_RDR (0U) /*!< Bit position for I2S_RDRn_RDR. */ #define BM_I2S_RDRn_RDR (0xFFFFFFFFU) /*!< Bit mask for I2S_RDRn_RDR. */ #define BS_I2S_RDRn_RDR (32U) /*!< Bit field size in bits for I2S_RDRn_RDR. */ /*! @brief Read current value of the I2S_RDRn_RDR field. */ #define BR_I2S_RDRn_RDR(x, n) (HW_I2S_RDRn(x, n).U) /*@}*/ /******************************************************************************* * HW_I2S_RFRn - SAI Receive FIFO Register ******************************************************************************/ /*! * @brief HW_I2S_RFRn - SAI Receive FIFO Register (RO) * * Reset value: 0x00000000U * * The MSB of the read and write pointers is used to distinguish between FIFO * full and empty conditions. If the read and write pointers are identical, then * the FIFO is empty. If the read and write pointers are identical except for the * MSB, then the FIFO is full. */ typedef union _hw_i2s_rfrn { uint32_t U; struct _hw_i2s_rfrn_bitfields { uint32_t RFP : 4; /*!< [3:0] Read FIFO Pointer */ uint32_t RESERVED0 : 12; /*!< [15:4] */ uint32_t WFP : 4; /*!< [19:16] Write FIFO Pointer */ uint32_t RESERVED1 : 12; /*!< [31:20] */ } B; } hw_i2s_rfrn_t; /*! * @name Constants and macros for entire I2S_RFRn register */ /*@{*/ #define HW_I2S_RFRn_COUNT (2U) #define HW_I2S_RFRn_ADDR(x, n) ((x) + 0xC0U + (0x4U * (n))) #define HW_I2S_RFRn(x, n) (*(__I hw_i2s_rfrn_t *) HW_I2S_RFRn_ADDR(x, n)) #define HW_I2S_RFRn_RD(x, n) (HW_I2S_RFRn(x, n).U) /*@}*/ /* * Constants & macros for individual I2S_RFRn bitfields */ /*! * @name Register I2S_RFRn, field RFP[3:0] (RO) * * FIFO read pointer for receive data channel. */ /*@{*/ #define BP_I2S_RFRn_RFP (0U) /*!< Bit position for I2S_RFRn_RFP. */ #define BM_I2S_RFRn_RFP (0x0000000FU) /*!< Bit mask for I2S_RFRn_RFP. */ #define BS_I2S_RFRn_RFP (4U) /*!< Bit field size in bits for I2S_RFRn_RFP. */ /*! @brief Read current value of the I2S_RFRn_RFP field. */ #define BR_I2S_RFRn_RFP(x, n) (HW_I2S_RFRn(x, n).B.RFP) /*@}*/ /*! * @name Register I2S_RFRn, field WFP[19:16] (RO) * * FIFO write pointer for receive data channel. */ /*@{*/ #define BP_I2S_RFRn_WFP (16U) /*!< Bit position for I2S_RFRn_WFP. */ #define BM_I2S_RFRn_WFP (0x000F0000U) /*!< Bit mask for I2S_RFRn_WFP. */ #define BS_I2S_RFRn_WFP (4U) /*!< Bit field size in bits for I2S_RFRn_WFP. */ /*! @brief Read current value of the I2S_RFRn_WFP field. */ #define BR_I2S_RFRn_WFP(x, n) (HW_I2S_RFRn(x, n).B.WFP) /*@}*/ /******************************************************************************* * HW_I2S_RMR - SAI Receive Mask Register ******************************************************************************/ /*! * @brief HW_I2S_RMR - SAI Receive Mask Register (RW) * * Reset value: 0x00000000U * * This register is double-buffered and updates: When RCSR[RE] is first set At * the end of each frame This allows the masked words in each frame to change from * frame to frame. */ typedef union _hw_i2s_rmr { uint32_t U; struct _hw_i2s_rmr_bitfields { uint32_t RWM : 32; /*!< [31:0] Receive Word Mask */ } B; } hw_i2s_rmr_t; /*! * @name Constants and macros for entire I2S_RMR register */ /*@{*/ #define HW_I2S_RMR_ADDR(x) ((x) + 0xE0U) #define HW_I2S_RMR(x) (*(__IO hw_i2s_rmr_t *) HW_I2S_RMR_ADDR(x)) #define HW_I2S_RMR_RD(x) (HW_I2S_RMR(x).U) #define HW_I2S_RMR_WR(x, v) (HW_I2S_RMR(x).U = (v)) #define HW_I2S_RMR_SET(x, v) (HW_I2S_RMR_WR(x, HW_I2S_RMR_RD(x) | (v))) #define HW_I2S_RMR_CLR(x, v) (HW_I2S_RMR_WR(x, HW_I2S_RMR_RD(x) & ~(v))) #define HW_I2S_RMR_TOG(x, v) (HW_I2S_RMR_WR(x, HW_I2S_RMR_RD(x) ^ (v))) /*@}*/ /* * Constants & macros for individual I2S_RMR bitfields */ /*! * @name Register I2S_RMR, field RWM[31:0] (RW) * * Configures whether the receive word is masked (received data ignored and not * written to receive FIFO) for the corresponding word in the frame. * * Values: * - 0 - Word N is enabled. * - 1 - Word N is masked. */ /*@{*/ #define BP_I2S_RMR_RWM (0U) /*!< Bit position for I2S_RMR_RWM. */ #define BM_I2S_RMR_RWM (0xFFFFFFFFU) /*!< Bit mask for I2S_RMR_RWM. */ #define BS_I2S_RMR_RWM (32U) /*!< Bit field size in bits for I2S_RMR_RWM. */ /*! @brief Read current value of the I2S_RMR_RWM field. */ #define BR_I2S_RMR_RWM(x) (HW_I2S_RMR(x).U) /*! @brief Format value for bitfield I2S_RMR_RWM. */ #define BF_I2S_RMR_RWM(v) ((uint32_t)((uint32_t)(v) << BP_I2S_RMR_RWM) & BM_I2S_RMR_RWM) /*! @brief Set the RWM field to a new value. */ #define BW_I2S_RMR_RWM(x, v) (HW_I2S_RMR_WR(x, v)) /*@}*/ /******************************************************************************* * HW_I2S_MCR - SAI MCLK Control Register ******************************************************************************/ /*! * @brief HW_I2S_MCR - SAI MCLK Control Register (RW) * * Reset value: 0x00000000U * * The MCLK Control Register (MCR) controls the clock source and direction of * the audio master clock. */ typedef union _hw_i2s_mcr { uint32_t U; struct _hw_i2s_mcr_bitfields { uint32_t RESERVED0 : 24; /*!< [23:0] */ uint32_t MICS : 2; /*!< [25:24] MCLK Input Clock Select */ uint32_t RESERVED1 : 4; /*!< [29:26] */ uint32_t MOE : 1; /*!< [30] MCLK Output Enable */ uint32_t DUF : 1; /*!< [31] Divider Update Flag */ } B; } hw_i2s_mcr_t; /*! * @name Constants and macros for entire I2S_MCR register */ /*@{*/ #define HW_I2S_MCR_ADDR(x) ((x) + 0x100U) #define HW_I2S_MCR(x) (*(__IO hw_i2s_mcr_t *) HW_I2S_MCR_ADDR(x)) #define HW_I2S_MCR_RD(x) (HW_I2S_MCR(x).U) #define HW_I2S_MCR_WR(x, v) (HW_I2S_MCR(x).U = (v)) #define HW_I2S_MCR_SET(x, v) (HW_I2S_MCR_WR(x, HW_I2S_MCR_RD(x) | (v))) #define HW_I2S_MCR_CLR(x, v) (HW_I2S_MCR_WR(x, HW_I2S_MCR_RD(x) & ~(v))) #define HW_I2S_MCR_TOG(x, v) (HW_I2S_MCR_WR(x, HW_I2S_MCR_RD(x) ^ (v))) /*@}*/ /* * Constants & macros for individual I2S_MCR bitfields */ /*! * @name Register I2S_MCR, field MICS[25:24] (RW) * * Selects the clock input to the MCLK divider. This field cannot be changed * while the MCLK divider is enabled. See the chip configuration details for * information about the connections to these inputs. * * Values: * - 00 - MCLK divider input clock 0 selected. * - 01 - MCLK divider input clock 1 selected. * - 10 - MCLK divider input clock 2 selected. * - 11 - MCLK divider input clock 3 selected. */ /*@{*/ #define BP_I2S_MCR_MICS (24U) /*!< Bit position for I2S_MCR_MICS. */ #define BM_I2S_MCR_MICS (0x03000000U) /*!< Bit mask for I2S_MCR_MICS. */ #define BS_I2S_MCR_MICS (2U) /*!< Bit field size in bits for I2S_MCR_MICS. */ /*! @brief Read current value of the I2S_MCR_MICS field. */ #define BR_I2S_MCR_MICS(x) (HW_I2S_MCR(x).B.MICS) /*! @brief Format value for bitfield I2S_MCR_MICS. */ #define BF_I2S_MCR_MICS(v) ((uint32_t)((uint32_t)(v) << BP_I2S_MCR_MICS) & BM_I2S_MCR_MICS) /*! @brief Set the MICS field to a new value. */ #define BW_I2S_MCR_MICS(x, v) (HW_I2S_MCR_WR(x, (HW_I2S_MCR_RD(x) & ~BM_I2S_MCR_MICS) | BF_I2S_MCR_MICS(v))) /*@}*/ /*! * @name Register I2S_MCR, field MOE[30] (RW) * * Enables the MCLK divider and configures the MCLK signal pin as an output. * When software clears this field, it remains set until the MCLK divider is fully * disabled. * * Values: * - 0 - MCLK signal pin is configured as an input that bypasses the MCLK * divider. * - 1 - MCLK signal pin is configured as an output from the MCLK divider and * the MCLK divider is enabled. */ /*@{*/ #define BP_I2S_MCR_MOE (30U) /*!< Bit position for I2S_MCR_MOE. */ #define BM_I2S_MCR_MOE (0x40000000U) /*!< Bit mask for I2S_MCR_MOE. */ #define BS_I2S_MCR_MOE (1U) /*!< Bit field size in bits for I2S_MCR_MOE. */ /*! @brief Read current value of the I2S_MCR_MOE field. */ #define BR_I2S_MCR_MOE(x) (BITBAND_ACCESS32(HW_I2S_MCR_ADDR(x), BP_I2S_MCR_MOE)) /*! @brief Format value for bitfield I2S_MCR_MOE. */ #define BF_I2S_MCR_MOE(v) ((uint32_t)((uint32_t)(v) << BP_I2S_MCR_MOE) & BM_I2S_MCR_MOE) /*! @brief Set the MOE field to a new value. */ #define BW_I2S_MCR_MOE(x, v) (BITBAND_ACCESS32(HW_I2S_MCR_ADDR(x), BP_I2S_MCR_MOE) = (v)) /*@}*/ /*! * @name Register I2S_MCR, field DUF[31] (RO) * * Provides the status of on-the-fly updates to the MCLK divider ratio. * * Values: * - 0 - MCLK divider ratio is not being updated currently. * - 1 - MCLK divider ratio is updating on-the-fly. Further updates to the MCLK * divider ratio are blocked while this flag remains set. */ /*@{*/ #define BP_I2S_MCR_DUF (31U) /*!< Bit position for I2S_MCR_DUF. */ #define BM_I2S_MCR_DUF (0x80000000U) /*!< Bit mask for I2S_MCR_DUF. */ #define BS_I2S_MCR_DUF (1U) /*!< Bit field size in bits for I2S_MCR_DUF. */ /*! @brief Read current value of the I2S_MCR_DUF field. */ #define BR_I2S_MCR_DUF(x) (BITBAND_ACCESS32(HW_I2S_MCR_ADDR(x), BP_I2S_MCR_DUF)) /*@}*/ /******************************************************************************* * HW_I2S_MDR - SAI MCLK Divide Register ******************************************************************************/ /*! * @brief HW_I2S_MDR - SAI MCLK Divide Register (RW) * * Reset value: 0x00000000U * * The MCLK Divide Register (MDR) configures the MCLK divide ratio. Although the * MDR can be changed when the MCLK divider clock is enabled, additional writes * to the MDR are blocked while MCR[DUF] is set. Writes to the MDR when the MCLK * divided clock is disabled do not set MCR[DUF]. */ typedef union _hw_i2s_mdr { uint32_t U; struct _hw_i2s_mdr_bitfields { uint32_t DIVIDE : 12; /*!< [11:0] MCLK Divide */ uint32_t FRACT : 8; /*!< [19:12] MCLK Fraction */ uint32_t RESERVED0 : 12; /*!< [31:20] */ } B; } hw_i2s_mdr_t; /*! * @name Constants and macros for entire I2S_MDR register */ /*@{*/ #define HW_I2S_MDR_ADDR(x) ((x) + 0x104U) #define HW_I2S_MDR(x) (*(__IO hw_i2s_mdr_t *) HW_I2S_MDR_ADDR(x)) #define HW_I2S_MDR_RD(x) (HW_I2S_MDR(x).U) #define HW_I2S_MDR_WR(x, v) (HW_I2S_MDR(x).U = (v)) #define HW_I2S_MDR_SET(x, v) (HW_I2S_MDR_WR(x, HW_I2S_MDR_RD(x) | (v))) #define HW_I2S_MDR_CLR(x, v) (HW_I2S_MDR_WR(x, HW_I2S_MDR_RD(x) & ~(v))) #define HW_I2S_MDR_TOG(x, v) (HW_I2S_MDR_WR(x, HW_I2S_MDR_RD(x) ^ (v))) /*@}*/ /* * Constants & macros for individual I2S_MDR bitfields */ /*! * @name Register I2S_MDR, field DIVIDE[11:0] (RW) * * Sets the MCLK divide ratio such that: MCLK output = MCLK input * ( (FRACT + * 1) / (DIVIDE + 1) ). FRACT must be set equal or less than the value in the * DIVIDE field. */ /*@{*/ #define BP_I2S_MDR_DIVIDE (0U) /*!< Bit position for I2S_MDR_DIVIDE. */ #define BM_I2S_MDR_DIVIDE (0x00000FFFU) /*!< Bit mask for I2S_MDR_DIVIDE. */ #define BS_I2S_MDR_DIVIDE (12U) /*!< Bit field size in bits for I2S_MDR_DIVIDE. */ /*! @brief Read current value of the I2S_MDR_DIVIDE field. */ #define BR_I2S_MDR_DIVIDE(x) (HW_I2S_MDR(x).B.DIVIDE) /*! @brief Format value for bitfield I2S_MDR_DIVIDE. */ #define BF_I2S_MDR_DIVIDE(v) ((uint32_t)((uint32_t)(v) << BP_I2S_MDR_DIVIDE) & BM_I2S_MDR_DIVIDE) /*! @brief Set the DIVIDE field to a new value. */ #define BW_I2S_MDR_DIVIDE(x, v) (HW_I2S_MDR_WR(x, (HW_I2S_MDR_RD(x) & ~BM_I2S_MDR_DIVIDE) | BF_I2S_MDR_DIVIDE(v))) /*@}*/ /*! * @name Register I2S_MDR, field FRACT[19:12] (RW) * * Sets the MCLK divide ratio such that: MCLK output = MCLK input * ( (FRACT + * 1) / (DIVIDE + 1) ). FRACT must be set equal or less than the value in the * DIVIDE field. */ /*@{*/ #define BP_I2S_MDR_FRACT (12U) /*!< Bit position for I2S_MDR_FRACT. */ #define BM_I2S_MDR_FRACT (0x000FF000U) /*!< Bit mask for I2S_MDR_FRACT. */ #define BS_I2S_MDR_FRACT (8U) /*!< Bit field size in bits for I2S_MDR_FRACT. */ /*! @brief Read current value of the I2S_MDR_FRACT field. */ #define BR_I2S_MDR_FRACT(x) (HW_I2S_MDR(x).B.FRACT) /*! @brief Format value for bitfield I2S_MDR_FRACT. */ #define BF_I2S_MDR_FRACT(v) ((uint32_t)((uint32_t)(v) << BP_I2S_MDR_FRACT) & BM_I2S_MDR_FRACT) /*! @brief Set the FRACT field to a new value. */ #define BW_I2S_MDR_FRACT(x, v) (HW_I2S_MDR_WR(x, (HW_I2S_MDR_RD(x) & ~BM_I2S_MDR_FRACT) | BF_I2S_MDR_FRACT(v))) /*@}*/ /******************************************************************************* * hw_i2s_t - module struct ******************************************************************************/ /*! * @brief All I2S module registers. */ #pragma pack(1) typedef struct _hw_i2s { __IO hw_i2s_tcsr_t TCSR; /*!< [0x0] SAI Transmit Control Register */ __IO hw_i2s_tcr1_t TCR1; /*!< [0x4] SAI Transmit Configuration 1 Register */ __IO hw_i2s_tcr2_t TCR2; /*!< [0x8] SAI Transmit Configuration 2 Register */ __IO hw_i2s_tcr3_t TCR3; /*!< [0xC] SAI Transmit Configuration 3 Register */ __IO hw_i2s_tcr4_t TCR4; /*!< [0x10] SAI Transmit Configuration 4 Register */ __IO hw_i2s_tcr5_t TCR5; /*!< [0x14] SAI Transmit Configuration 5 Register */ uint8_t _reserved0[8]; __O hw_i2s_tdrn_t TDRn[2]; /*!< [0x20] SAI Transmit Data Register */ uint8_t _reserved1[24]; __I hw_i2s_tfrn_t TFRn[2]; /*!< [0x40] SAI Transmit FIFO Register */ uint8_t _reserved2[24]; __IO hw_i2s_tmr_t TMR; /*!< [0x60] SAI Transmit Mask Register */ uint8_t _reserved3[28]; __IO hw_i2s_rcsr_t RCSR; /*!< [0x80] SAI Receive Control Register */ __IO hw_i2s_rcr1_t RCR1; /*!< [0x84] SAI Receive Configuration 1 Register */ __IO hw_i2s_rcr2_t RCR2; /*!< [0x88] SAI Receive Configuration 2 Register */ __IO hw_i2s_rcr3_t RCR3; /*!< [0x8C] SAI Receive Configuration 3 Register */ __IO hw_i2s_rcr4_t RCR4; /*!< [0x90] SAI Receive Configuration 4 Register */ __IO hw_i2s_rcr5_t RCR5; /*!< [0x94] SAI Receive Configuration 5 Register */ uint8_t _reserved4[8]; __I hw_i2s_rdrn_t RDRn[2]; /*!< [0xA0] SAI Receive Data Register */ uint8_t _reserved5[24]; __I hw_i2s_rfrn_t RFRn[2]; /*!< [0xC0] SAI Receive FIFO Register */ uint8_t _reserved6[24]; __IO hw_i2s_rmr_t RMR; /*!< [0xE0] SAI Receive Mask Register */ uint8_t _reserved7[28]; __IO hw_i2s_mcr_t MCR; /*!< [0x100] SAI MCLK Control Register */ __IO hw_i2s_mdr_t MDR; /*!< [0x104] SAI MCLK Divide Register */ } hw_i2s_t; #pragma pack() /*! @brief Macro to access all I2S registers. */ /*! @param x I2S module instance base address. */ /*! @return Reference (not a pointer) to the registers struct. To get a pointer to the struct, * use the '&' operator, like &HW_I2S(I2S0_BASE). */ #define HW_I2S(x) (*(hw_i2s_t *)(x)) #endif /* __HW_I2S_REGISTERS_H__ */ /* EOF */ ================================================ FILE: Zelig/mbed/TARGET_K64F/TARGET_Freescale/TARGET_KPSDK_MCUS/TARGET_MCU_K64F/device/device/MK64F12/MK64F12_llwu.h ================================================ /* ** ################################################################### ** Compilers: Keil ARM C/C++ Compiler ** Freescale C/C++ for Embedded ARM ** GNU C Compiler ** IAR ANSI C/C++ Compiler for ARM ** ** Reference manual: K64P144M120SF5RM, Rev.2, January 2014 ** Version: rev. 2.5, 2014-02-10 ** Build: b140604 ** ** Abstract: ** Extension to the CMSIS register access layer header. ** ** Copyright (c) 2014 Freescale Semiconductor, Inc. ** All rights reserved. ** ** Redistribution and use in source and binary forms, with or without modification, ** are permitted provided that the following conditions are met: ** ** o Redistributions of source code must retain the above copyright notice, this list ** of conditions and the following disclaimer. ** ** o Redistributions in binary form must reproduce the above copyright notice, this ** list of conditions and the following disclaimer in the documentation and/or ** other materials provided with the distribution. ** ** o Neither the name of Freescale Semiconductor, Inc. nor the names of its ** contributors may be used to endorse or promote products derived from this ** software without specific prior written permission. ** ** THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ** ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED ** WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE ** DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT 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. ** ** http: www.freescale.com ** mail: support@freescale.com ** ** Revisions: ** - rev. 1.0 (2013-08-12) ** Initial version. ** - rev. 2.0 (2013-10-29) ** Register accessor macros added to the memory map. ** Symbols for Processor Expert memory map compatibility added to the memory map. ** Startup file for gcc has been updated according to CMSIS 3.2. ** System initialization updated. ** MCG - registers updated. ** PORTA, PORTB, PORTC, PORTE - registers for digital filter removed. ** - rev. 2.1 (2013-10-30) ** Definition of BITBAND macros updated to support peripherals with 32-bit acces disabled. ** - rev. 2.2 (2013-12-09) ** DMA - EARS register removed. ** AIPS0, AIPS1 - MPRA register updated. ** - rev. 2.3 (2014-01-24) ** Update according to reference manual rev. 2 ** ENET, MCG, MCM, SIM, USB - registers updated ** - rev. 2.4 (2014-02-10) ** The declaration of clock configurations has been moved to separate header file system_MK64F12.h ** Update of SystemInit() and SystemCoreClockUpdate() functions. ** - rev. 2.5 (2014-02-10) ** The declaration of clock configurations has been moved to separate header file system_MK64F12.h ** Update of SystemInit() and SystemCoreClockUpdate() functions. ** Module access macro module_BASES replaced by module_BASE_PTRS. ** ** ################################################################### */ /* * WARNING! DO NOT EDIT THIS FILE DIRECTLY! * * This file was generated automatically and any changes may be lost. */ #ifndef __HW_LLWU_REGISTERS_H__ #define __HW_LLWU_REGISTERS_H__ #include "MK64F12.h" #include "fsl_bitaccess.h" /* * MK64F12 LLWU * * Low leakage wakeup unit * * Registers defined in this header file: * - HW_LLWU_PE1 - LLWU Pin Enable 1 register * - HW_LLWU_PE2 - LLWU Pin Enable 2 register * - HW_LLWU_PE3 - LLWU Pin Enable 3 register * - HW_LLWU_PE4 - LLWU Pin Enable 4 register * - HW_LLWU_ME - LLWU Module Enable register * - HW_LLWU_F1 - LLWU Flag 1 register * - HW_LLWU_F2 - LLWU Flag 2 register * - HW_LLWU_F3 - LLWU Flag 3 register * - HW_LLWU_FILT1 - LLWU Pin Filter 1 register * - HW_LLWU_FILT2 - LLWU Pin Filter 2 register * - HW_LLWU_RST - LLWU Reset Enable register * * - hw_llwu_t - Struct containing all module registers. */ #define HW_LLWU_INSTANCE_COUNT (1U) /*!< Number of instances of the LLWU module. */ /******************************************************************************* * HW_LLWU_PE1 - LLWU Pin Enable 1 register ******************************************************************************/ /*! * @brief HW_LLWU_PE1 - LLWU Pin Enable 1 register (RW) * * Reset value: 0x00U * * LLWU_PE1 contains the field to enable and select the edge detect type for the * external wakeup input pins LLWU_P3-LLWU_P0. This register is reset on Chip * Reset not VLLS and by reset types that trigger Chip Reset not VLLS. It is * unaffected by reset types that do not trigger Chip Reset not VLLS. See the * IntroductionInformation found here describes the registers of the Reset Control Module * (RCM). The RCM implements many of the reset functions for the chip. See the * chip's reset chapter for more information. details for more information. */ typedef union _hw_llwu_pe1 { uint8_t U; struct _hw_llwu_pe1_bitfields { uint8_t WUPE0 : 2; /*!< [1:0] Wakeup Pin Enable For LLWU_P0 */ uint8_t WUPE1 : 2; /*!< [3:2] Wakeup Pin Enable For LLWU_P1 */ uint8_t WUPE2 : 2; /*!< [5:4] Wakeup Pin Enable For LLWU_P2 */ uint8_t WUPE3 : 2; /*!< [7:6] Wakeup Pin Enable For LLWU_P3 */ } B; } hw_llwu_pe1_t; /*! * @name Constants and macros for entire LLWU_PE1 register */ /*@{*/ #define HW_LLWU_PE1_ADDR(x) ((x) + 0x0U) #define HW_LLWU_PE1(x) (*(__IO hw_llwu_pe1_t *) HW_LLWU_PE1_ADDR(x)) #define HW_LLWU_PE1_RD(x) (HW_LLWU_PE1(x).U) #define HW_LLWU_PE1_WR(x, v) (HW_LLWU_PE1(x).U = (v)) #define HW_LLWU_PE1_SET(x, v) (HW_LLWU_PE1_WR(x, HW_LLWU_PE1_RD(x) | (v))) #define HW_LLWU_PE1_CLR(x, v) (HW_LLWU_PE1_WR(x, HW_LLWU_PE1_RD(x) & ~(v))) #define HW_LLWU_PE1_TOG(x, v) (HW_LLWU_PE1_WR(x, HW_LLWU_PE1_RD(x) ^ (v))) /*@}*/ /* * Constants & macros for individual LLWU_PE1 bitfields */ /*! * @name Register LLWU_PE1, field WUPE0[1:0] (RW) * * Enables and configures the edge detection for the wakeup pin. * * Values: * - 00 - External input pin disabled as wakeup input * - 01 - External input pin enabled with rising edge detection * - 10 - External input pin enabled with falling edge detection * - 11 - External input pin enabled with any change detection */ /*@{*/ #define BP_LLWU_PE1_WUPE0 (0U) /*!< Bit position for LLWU_PE1_WUPE0. */ #define BM_LLWU_PE1_WUPE0 (0x03U) /*!< Bit mask for LLWU_PE1_WUPE0. */ #define BS_LLWU_PE1_WUPE0 (2U) /*!< Bit field size in bits for LLWU_PE1_WUPE0. */ /*! @brief Read current value of the LLWU_PE1_WUPE0 field. */ #define BR_LLWU_PE1_WUPE0(x) (HW_LLWU_PE1(x).B.WUPE0) /*! @brief Format value for bitfield LLWU_PE1_WUPE0. */ #define BF_LLWU_PE1_WUPE0(v) ((uint8_t)((uint8_t)(v) << BP_LLWU_PE1_WUPE0) & BM_LLWU_PE1_WUPE0) /*! @brief Set the WUPE0 field to a new value. */ #define BW_LLWU_PE1_WUPE0(x, v) (HW_LLWU_PE1_WR(x, (HW_LLWU_PE1_RD(x) & ~BM_LLWU_PE1_WUPE0) | BF_LLWU_PE1_WUPE0(v))) /*@}*/ /*! * @name Register LLWU_PE1, field WUPE1[3:2] (RW) * * Enables and configures the edge detection for the wakeup pin. * * Values: * - 00 - External input pin disabled as wakeup input * - 01 - External input pin enabled with rising edge detection * - 10 - External input pin enabled with falling edge detection * - 11 - External input pin enabled with any change detection */ /*@{*/ #define BP_LLWU_PE1_WUPE1 (2U) /*!< Bit position for LLWU_PE1_WUPE1. */ #define BM_LLWU_PE1_WUPE1 (0x0CU) /*!< Bit mask for LLWU_PE1_WUPE1. */ #define BS_LLWU_PE1_WUPE1 (2U) /*!< Bit field size in bits for LLWU_PE1_WUPE1. */ /*! @brief Read current value of the LLWU_PE1_WUPE1 field. */ #define BR_LLWU_PE1_WUPE1(x) (HW_LLWU_PE1(x).B.WUPE1) /*! @brief Format value for bitfield LLWU_PE1_WUPE1. */ #define BF_LLWU_PE1_WUPE1(v) ((uint8_t)((uint8_t)(v) << BP_LLWU_PE1_WUPE1) & BM_LLWU_PE1_WUPE1) /*! @brief Set the WUPE1 field to a new value. */ #define BW_LLWU_PE1_WUPE1(x, v) (HW_LLWU_PE1_WR(x, (HW_LLWU_PE1_RD(x) & ~BM_LLWU_PE1_WUPE1) | BF_LLWU_PE1_WUPE1(v))) /*@}*/ /*! * @name Register LLWU_PE1, field WUPE2[5:4] (RW) * * Enables and configures the edge detection for the wakeup pin. * * Values: * - 00 - External input pin disabled as wakeup input * - 01 - External input pin enabled with rising edge detection * - 10 - External input pin enabled with falling edge detection * - 11 - External input pin enabled with any change detection */ /*@{*/ #define BP_LLWU_PE1_WUPE2 (4U) /*!< Bit position for LLWU_PE1_WUPE2. */ #define BM_LLWU_PE1_WUPE2 (0x30U) /*!< Bit mask for LLWU_PE1_WUPE2. */ #define BS_LLWU_PE1_WUPE2 (2U) /*!< Bit field size in bits for LLWU_PE1_WUPE2. */ /*! @brief Read current value of the LLWU_PE1_WUPE2 field. */ #define BR_LLWU_PE1_WUPE2(x) (HW_LLWU_PE1(x).B.WUPE2) /*! @brief Format value for bitfield LLWU_PE1_WUPE2. */ #define BF_LLWU_PE1_WUPE2(v) ((uint8_t)((uint8_t)(v) << BP_LLWU_PE1_WUPE2) & BM_LLWU_PE1_WUPE2) /*! @brief Set the WUPE2 field to a new value. */ #define BW_LLWU_PE1_WUPE2(x, v) (HW_LLWU_PE1_WR(x, (HW_LLWU_PE1_RD(x) & ~BM_LLWU_PE1_WUPE2) | BF_LLWU_PE1_WUPE2(v))) /*@}*/ /*! * @name Register LLWU_PE1, field WUPE3[7:6] (RW) * * Enables and configures the edge detection for the wakeup pin. * * Values: * - 00 - External input pin disabled as wakeup input * - 01 - External input pin enabled with rising edge detection * - 10 - External input pin enabled with falling edge detection * - 11 - External input pin enabled with any change detection */ /*@{*/ #define BP_LLWU_PE1_WUPE3 (6U) /*!< Bit position for LLWU_PE1_WUPE3. */ #define BM_LLWU_PE1_WUPE3 (0xC0U) /*!< Bit mask for LLWU_PE1_WUPE3. */ #define BS_LLWU_PE1_WUPE3 (2U) /*!< Bit field size in bits for LLWU_PE1_WUPE3. */ /*! @brief Read current value of the LLWU_PE1_WUPE3 field. */ #define BR_LLWU_PE1_WUPE3(x) (HW_LLWU_PE1(x).B.WUPE3) /*! @brief Format value for bitfield LLWU_PE1_WUPE3. */ #define BF_LLWU_PE1_WUPE3(v) ((uint8_t)((uint8_t)(v) << BP_LLWU_PE1_WUPE3) & BM_LLWU_PE1_WUPE3) /*! @brief Set the WUPE3 field to a new value. */ #define BW_LLWU_PE1_WUPE3(x, v) (HW_LLWU_PE1_WR(x, (HW_LLWU_PE1_RD(x) & ~BM_LLWU_PE1_WUPE3) | BF_LLWU_PE1_WUPE3(v))) /*@}*/ /******************************************************************************* * HW_LLWU_PE2 - LLWU Pin Enable 2 register ******************************************************************************/ /*! * @brief HW_LLWU_PE2 - LLWU Pin Enable 2 register (RW) * * Reset value: 0x00U * * LLWU_PE2 contains the field to enable and select the edge detect type for the * external wakeup input pins LLWU_P7-LLWU_P4. This register is reset on Chip * Reset not VLLS and by reset types that trigger Chip Reset not VLLS. It is * unaffected by reset types that do not trigger Chip Reset not VLLS. See the * IntroductionInformation found here describes the registers of the Reset Control Module * (RCM). The RCM implements many of the reset functions for the chip. See the * chip's reset chapter for more information. details for more information. */ typedef union _hw_llwu_pe2 { uint8_t U; struct _hw_llwu_pe2_bitfields { uint8_t WUPE4 : 2; /*!< [1:0] Wakeup Pin Enable For LLWU_P4 */ uint8_t WUPE5 : 2; /*!< [3:2] Wakeup Pin Enable For LLWU_P5 */ uint8_t WUPE6 : 2; /*!< [5:4] Wakeup Pin Enable For LLWU_P6 */ uint8_t WUPE7 : 2; /*!< [7:6] Wakeup Pin Enable For LLWU_P7 */ } B; } hw_llwu_pe2_t; /*! * @name Constants and macros for entire LLWU_PE2 register */ /*@{*/ #define HW_LLWU_PE2_ADDR(x) ((x) + 0x1U) #define HW_LLWU_PE2(x) (*(__IO hw_llwu_pe2_t *) HW_LLWU_PE2_ADDR(x)) #define HW_LLWU_PE2_RD(x) (HW_LLWU_PE2(x).U) #define HW_LLWU_PE2_WR(x, v) (HW_LLWU_PE2(x).U = (v)) #define HW_LLWU_PE2_SET(x, v) (HW_LLWU_PE2_WR(x, HW_LLWU_PE2_RD(x) | (v))) #define HW_LLWU_PE2_CLR(x, v) (HW_LLWU_PE2_WR(x, HW_LLWU_PE2_RD(x) & ~(v))) #define HW_LLWU_PE2_TOG(x, v) (HW_LLWU_PE2_WR(x, HW_LLWU_PE2_RD(x) ^ (v))) /*@}*/ /* * Constants & macros for individual LLWU_PE2 bitfields */ /*! * @name Register LLWU_PE2, field WUPE4[1:0] (RW) * * Enables and configures the edge detection for the wakeup pin. * * Values: * - 00 - External input pin disabled as wakeup input * - 01 - External input pin enabled with rising edge detection * - 10 - External input pin enabled with falling edge detection * - 11 - External input pin enabled with any change detection */ /*@{*/ #define BP_LLWU_PE2_WUPE4 (0U) /*!< Bit position for LLWU_PE2_WUPE4. */ #define BM_LLWU_PE2_WUPE4 (0x03U) /*!< Bit mask for LLWU_PE2_WUPE4. */ #define BS_LLWU_PE2_WUPE4 (2U) /*!< Bit field size in bits for LLWU_PE2_WUPE4. */ /*! @brief Read current value of the LLWU_PE2_WUPE4 field. */ #define BR_LLWU_PE2_WUPE4(x) (HW_LLWU_PE2(x).B.WUPE4) /*! @brief Format value for bitfield LLWU_PE2_WUPE4. */ #define BF_LLWU_PE2_WUPE4(v) ((uint8_t)((uint8_t)(v) << BP_LLWU_PE2_WUPE4) & BM_LLWU_PE2_WUPE4) /*! @brief Set the WUPE4 field to a new value. */ #define BW_LLWU_PE2_WUPE4(x, v) (HW_LLWU_PE2_WR(x, (HW_LLWU_PE2_RD(x) & ~BM_LLWU_PE2_WUPE4) | BF_LLWU_PE2_WUPE4(v))) /*@}*/ /*! * @name Register LLWU_PE2, field WUPE5[3:2] (RW) * * Enables and configures the edge detection for the wakeup pin. * * Values: * - 00 - External input pin disabled as wakeup input * - 01 - External input pin enabled with rising edge detection * - 10 - External input pin enabled with falling edge detection * - 11 - External input pin enabled with any change detection */ /*@{*/ #define BP_LLWU_PE2_WUPE5 (2U) /*!< Bit position for LLWU_PE2_WUPE5. */ #define BM_LLWU_PE2_WUPE5 (0x0CU) /*!< Bit mask for LLWU_PE2_WUPE5. */ #define BS_LLWU_PE2_WUPE5 (2U) /*!< Bit field size in bits for LLWU_PE2_WUPE5. */ /*! @brief Read current value of the LLWU_PE2_WUPE5 field. */ #define BR_LLWU_PE2_WUPE5(x) (HW_LLWU_PE2(x).B.WUPE5) /*! @brief Format value for bitfield LLWU_PE2_WUPE5. */ #define BF_LLWU_PE2_WUPE5(v) ((uint8_t)((uint8_t)(v) << BP_LLWU_PE2_WUPE5) & BM_LLWU_PE2_WUPE5) /*! @brief Set the WUPE5 field to a new value. */ #define BW_LLWU_PE2_WUPE5(x, v) (HW_LLWU_PE2_WR(x, (HW_LLWU_PE2_RD(x) & ~BM_LLWU_PE2_WUPE5) | BF_LLWU_PE2_WUPE5(v))) /*@}*/ /*! * @name Register LLWU_PE2, field WUPE6[5:4] (RW) * * Enables and configures the edge detection for the wakeup pin. * * Values: * - 00 - External input pin disabled as wakeup input * - 01 - External input pin enabled with rising edge detection * - 10 - External input pin enabled with falling edge detection * - 11 - External input pin enabled with any change detection */ /*@{*/ #define BP_LLWU_PE2_WUPE6 (4U) /*!< Bit position for LLWU_PE2_WUPE6. */ #define BM_LLWU_PE2_WUPE6 (0x30U) /*!< Bit mask for LLWU_PE2_WUPE6. */ #define BS_LLWU_PE2_WUPE6 (2U) /*!< Bit field size in bits for LLWU_PE2_WUPE6. */ /*! @brief Read current value of the LLWU_PE2_WUPE6 field. */ #define BR_LLWU_PE2_WUPE6(x) (HW_LLWU_PE2(x).B.WUPE6) /*! @brief Format value for bitfield LLWU_PE2_WUPE6. */ #define BF_LLWU_PE2_WUPE6(v) ((uint8_t)((uint8_t)(v) << BP_LLWU_PE2_WUPE6) & BM_LLWU_PE2_WUPE6) /*! @brief Set the WUPE6 field to a new value. */ #define BW_LLWU_PE2_WUPE6(x, v) (HW_LLWU_PE2_WR(x, (HW_LLWU_PE2_RD(x) & ~BM_LLWU_PE2_WUPE6) | BF_LLWU_PE2_WUPE6(v))) /*@}*/ /*! * @name Register LLWU_PE2, field WUPE7[7:6] (RW) * * Enables and configures the edge detection for the wakeup pin. * * Values: * - 00 - External input pin disabled as wakeup input * - 01 - External input pin enabled with rising edge detection * - 10 - External input pin enabled with falling edge detection * - 11 - External input pin enabled with any change detection */ /*@{*/ #define BP_LLWU_PE2_WUPE7 (6U) /*!< Bit position for LLWU_PE2_WUPE7. */ #define BM_LLWU_PE2_WUPE7 (0xC0U) /*!< Bit mask for LLWU_PE2_WUPE7. */ #define BS_LLWU_PE2_WUPE7 (2U) /*!< Bit field size in bits for LLWU_PE2_WUPE7. */ /*! @brief Read current value of the LLWU_PE2_WUPE7 field. */ #define BR_LLWU_PE2_WUPE7(x) (HW_LLWU_PE2(x).B.WUPE7) /*! @brief Format value for bitfield LLWU_PE2_WUPE7. */ #define BF_LLWU_PE2_WUPE7(v) ((uint8_t)((uint8_t)(v) << BP_LLWU_PE2_WUPE7) & BM_LLWU_PE2_WUPE7) /*! @brief Set the WUPE7 field to a new value. */ #define BW_LLWU_PE2_WUPE7(x, v) (HW_LLWU_PE2_WR(x, (HW_LLWU_PE2_RD(x) & ~BM_LLWU_PE2_WUPE7) | BF_LLWU_PE2_WUPE7(v))) /*@}*/ /******************************************************************************* * HW_LLWU_PE3 - LLWU Pin Enable 3 register ******************************************************************************/ /*! * @brief HW_LLWU_PE3 - LLWU Pin Enable 3 register (RW) * * Reset value: 0x00U * * LLWU_PE3 contains the field to enable and select the edge detect type for the * external wakeup input pins LLWU_P11-LLWU_P8. This register is reset on Chip * Reset not VLLS and by reset types that trigger Chip Reset not VLLS. It is * unaffected by reset types that do not trigger Chip Reset not VLLS. See the * IntroductionInformation found here describes the registers of the Reset Control Module * (RCM). The RCM implements many of the reset functions for the chip. See the * chip's reset chapter for more information. details for more information. */ typedef union _hw_llwu_pe3 { uint8_t U; struct _hw_llwu_pe3_bitfields { uint8_t WUPE8 : 2; /*!< [1:0] Wakeup Pin Enable For LLWU_P8 */ uint8_t WUPE9 : 2; /*!< [3:2] Wakeup Pin Enable For LLWU_P9 */ uint8_t WUPE10 : 2; /*!< [5:4] Wakeup Pin Enable For LLWU_P10 */ uint8_t WUPE11 : 2; /*!< [7:6] Wakeup Pin Enable For LLWU_P11 */ } B; } hw_llwu_pe3_t; /*! * @name Constants and macros for entire LLWU_PE3 register */ /*@{*/ #define HW_LLWU_PE3_ADDR(x) ((x) + 0x2U) #define HW_LLWU_PE3(x) (*(__IO hw_llwu_pe3_t *) HW_LLWU_PE3_ADDR(x)) #define HW_LLWU_PE3_RD(x) (HW_LLWU_PE3(x).U) #define HW_LLWU_PE3_WR(x, v) (HW_LLWU_PE3(x).U = (v)) #define HW_LLWU_PE3_SET(x, v) (HW_LLWU_PE3_WR(x, HW_LLWU_PE3_RD(x) | (v))) #define HW_LLWU_PE3_CLR(x, v) (HW_LLWU_PE3_WR(x, HW_LLWU_PE3_RD(x) & ~(v))) #define HW_LLWU_PE3_TOG(x, v) (HW_LLWU_PE3_WR(x, HW_LLWU_PE3_RD(x) ^ (v))) /*@}*/ /* * Constants & macros for individual LLWU_PE3 bitfields */ /*! * @name Register LLWU_PE3, field WUPE8[1:0] (RW) * * Enables and configures the edge detection for the wakeup pin. * * Values: * - 00 - External input pin disabled as wakeup input * - 01 - External input pin enabled with rising edge detection * - 10 - External input pin enabled with falling edge detection * - 11 - External input pin enabled with any change detection */ /*@{*/ #define BP_LLWU_PE3_WUPE8 (0U) /*!< Bit position for LLWU_PE3_WUPE8. */ #define BM_LLWU_PE3_WUPE8 (0x03U) /*!< Bit mask for LLWU_PE3_WUPE8. */ #define BS_LLWU_PE3_WUPE8 (2U) /*!< Bit field size in bits for LLWU_PE3_WUPE8. */ /*! @brief Read current value of the LLWU_PE3_WUPE8 field. */ #define BR_LLWU_PE3_WUPE8(x) (HW_LLWU_PE3(x).B.WUPE8) /*! @brief Format value for bitfield LLWU_PE3_WUPE8. */ #define BF_LLWU_PE3_WUPE8(v) ((uint8_t)((uint8_t)(v) << BP_LLWU_PE3_WUPE8) & BM_LLWU_PE3_WUPE8) /*! @brief Set the WUPE8 field to a new value. */ #define BW_LLWU_PE3_WUPE8(x, v) (HW_LLWU_PE3_WR(x, (HW_LLWU_PE3_RD(x) & ~BM_LLWU_PE3_WUPE8) | BF_LLWU_PE3_WUPE8(v))) /*@}*/ /*! * @name Register LLWU_PE3, field WUPE9[3:2] (RW) * * Enables and configures the edge detection for the wakeup pin. * * Values: * - 00 - External input pin disabled as wakeup input * - 01 - External input pin enabled with rising edge detection * - 10 - External input pin enabled with falling edge detection * - 11 - External input pin enabled with any change detection */ /*@{*/ #define BP_LLWU_PE3_WUPE9 (2U) /*!< Bit position for LLWU_PE3_WUPE9. */ #define BM_LLWU_PE3_WUPE9 (0x0CU) /*!< Bit mask for LLWU_PE3_WUPE9. */ #define BS_LLWU_PE3_WUPE9 (2U) /*!< Bit field size in bits for LLWU_PE3_WUPE9. */ /*! @brief Read current value of the LLWU_PE3_WUPE9 field. */ #define BR_LLWU_PE3_WUPE9(x) (HW_LLWU_PE3(x).B.WUPE9) /*! @brief Format value for bitfield LLWU_PE3_WUPE9. */ #define BF_LLWU_PE3_WUPE9(v) ((uint8_t)((uint8_t)(v) << BP_LLWU_PE3_WUPE9) & BM_LLWU_PE3_WUPE9) /*! @brief Set the WUPE9 field to a new value. */ #define BW_LLWU_PE3_WUPE9(x, v) (HW_LLWU_PE3_WR(x, (HW_LLWU_PE3_RD(x) & ~BM_LLWU_PE3_WUPE9) | BF_LLWU_PE3_WUPE9(v))) /*@}*/ /*! * @name Register LLWU_PE3, field WUPE10[5:4] (RW) * * Enables and configures the edge detection for the wakeup pin. * * Values: * - 00 - External input pin disabled as wakeup input * - 01 - External input pin enabled with rising edge detection * - 10 - External input pin enabled with falling edge detection * - 11 - External input pin enabled with any change detection */ /*@{*/ #define BP_LLWU_PE3_WUPE10 (4U) /*!< Bit position for LLWU_PE3_WUPE10. */ #define BM_LLWU_PE3_WUPE10 (0x30U) /*!< Bit mask for LLWU_PE3_WUPE10. */ #define BS_LLWU_PE3_WUPE10 (2U) /*!< Bit field size in bits for LLWU_PE3_WUPE10. */ /*! @brief Read current value of the LLWU_PE3_WUPE10 field. */ #define BR_LLWU_PE3_WUPE10(x) (HW_LLWU_PE3(x).B.WUPE10) /*! @brief Format value for bitfield LLWU_PE3_WUPE10. */ #define BF_LLWU_PE3_WUPE10(v) ((uint8_t)((uint8_t)(v) << BP_LLWU_PE3_WUPE10) & BM_LLWU_PE3_WUPE10) /*! @brief Set the WUPE10 field to a new value. */ #define BW_LLWU_PE3_WUPE10(x, v) (HW_LLWU_PE3_WR(x, (HW_LLWU_PE3_RD(x) & ~BM_LLWU_PE3_WUPE10) | BF_LLWU_PE3_WUPE10(v))) /*@}*/ /*! * @name Register LLWU_PE3, field WUPE11[7:6] (RW) * * Enables and configures the edge detection for the wakeup pin. * * Values: * - 00 - External input pin disabled as wakeup input * - 01 - External input pin enabled with rising edge detection * - 10 - External input pin enabled with falling edge detection * - 11 - External input pin enabled with any change detection */ /*@{*/ #define BP_LLWU_PE3_WUPE11 (6U) /*!< Bit position for LLWU_PE3_WUPE11. */ #define BM_LLWU_PE3_WUPE11 (0xC0U) /*!< Bit mask for LLWU_PE3_WUPE11. */ #define BS_LLWU_PE3_WUPE11 (2U) /*!< Bit field size in bits for LLWU_PE3_WUPE11. */ /*! @brief Read current value of the LLWU_PE3_WUPE11 field. */ #define BR_LLWU_PE3_WUPE11(x) (HW_LLWU_PE3(x).B.WUPE11) /*! @brief Format value for bitfield LLWU_PE3_WUPE11. */ #define BF_LLWU_PE3_WUPE11(v) ((uint8_t)((uint8_t)(v) << BP_LLWU_PE3_WUPE11) & BM_LLWU_PE3_WUPE11) /*! @brief Set the WUPE11 field to a new value. */ #define BW_LLWU_PE3_WUPE11(x, v) (HW_LLWU_PE3_WR(x, (HW_LLWU_PE3_RD(x) & ~BM_LLWU_PE3_WUPE11) | BF_LLWU_PE3_WUPE11(v))) /*@}*/ /******************************************************************************* * HW_LLWU_PE4 - LLWU Pin Enable 4 register ******************************************************************************/ /*! * @brief HW_LLWU_PE4 - LLWU Pin Enable 4 register (RW) * * Reset value: 0x00U * * LLWU_PE4 contains the field to enable and select the edge detect type for the * external wakeup input pins LLWU_P15-LLWU_P12. This register is reset on Chip * Reset not VLLS and by reset types that trigger Chip Reset not VLLS. It is * unaffected by reset types that do not trigger Chip Reset not VLLS. See the * IntroductionInformation found here describes the registers of the Reset Control * Module (RCM). The RCM implements many of the reset functions for the chip. See the * chip's reset chapter for more information. details for more information. */ typedef union _hw_llwu_pe4 { uint8_t U; struct _hw_llwu_pe4_bitfields { uint8_t WUPE12 : 2; /*!< [1:0] Wakeup Pin Enable For LLWU_P12 */ uint8_t WUPE13 : 2; /*!< [3:2] Wakeup Pin Enable For LLWU_P13 */ uint8_t WUPE14 : 2; /*!< [5:4] Wakeup Pin Enable For LLWU_P14 */ uint8_t WUPE15 : 2; /*!< [7:6] Wakeup Pin Enable For LLWU_P15 */ } B; } hw_llwu_pe4_t; /*! * @name Constants and macros for entire LLWU_PE4 register */ /*@{*/ #define HW_LLWU_PE4_ADDR(x) ((x) + 0x3U) #define HW_LLWU_PE4(x) (*(__IO hw_llwu_pe4_t *) HW_LLWU_PE4_ADDR(x)) #define HW_LLWU_PE4_RD(x) (HW_LLWU_PE4(x).U) #define HW_LLWU_PE4_WR(x, v) (HW_LLWU_PE4(x).U = (v)) #define HW_LLWU_PE4_SET(x, v) (HW_LLWU_PE4_WR(x, HW_LLWU_PE4_RD(x) | (v))) #define HW_LLWU_PE4_CLR(x, v) (HW_LLWU_PE4_WR(x, HW_LLWU_PE4_RD(x) & ~(v))) #define HW_LLWU_PE4_TOG(x, v) (HW_LLWU_PE4_WR(x, HW_LLWU_PE4_RD(x) ^ (v))) /*@}*/ /* * Constants & macros for individual LLWU_PE4 bitfields */ /*! * @name Register LLWU_PE4, field WUPE12[1:0] (RW) * * Enables and configures the edge detection for the wakeup pin. * * Values: * - 00 - External input pin disabled as wakeup input * - 01 - External input pin enabled with rising edge detection * - 10 - External input pin enabled with falling edge detection * - 11 - External input pin enabled with any change detection */ /*@{*/ #define BP_LLWU_PE4_WUPE12 (0U) /*!< Bit position for LLWU_PE4_WUPE12. */ #define BM_LLWU_PE4_WUPE12 (0x03U) /*!< Bit mask for LLWU_PE4_WUPE12. */ #define BS_LLWU_PE4_WUPE12 (2U) /*!< Bit field size in bits for LLWU_PE4_WUPE12. */ /*! @brief Read current value of the LLWU_PE4_WUPE12 field. */ #define BR_LLWU_PE4_WUPE12(x) (HW_LLWU_PE4(x).B.WUPE12) /*! @brief Format value for bitfield LLWU_PE4_WUPE12. */ #define BF_LLWU_PE4_WUPE12(v) ((uint8_t)((uint8_t)(v) << BP_LLWU_PE4_WUPE12) & BM_LLWU_PE4_WUPE12) /*! @brief Set the WUPE12 field to a new value. */ #define BW_LLWU_PE4_WUPE12(x, v) (HW_LLWU_PE4_WR(x, (HW_LLWU_PE4_RD(x) & ~BM_LLWU_PE4_WUPE12) | BF_LLWU_PE4_WUPE12(v))) /*@}*/ /*! * @name Register LLWU_PE4, field WUPE13[3:2] (RW) * * Enables and configures the edge detection for the wakeup pin. * * Values: * - 00 - External input pin disabled as wakeup input * - 01 - External input pin enabled with rising edge detection * - 10 - External input pin enabled with falling edge detection * - 11 - External input pin enabled with any change detection */ /*@{*/ #define BP_LLWU_PE4_WUPE13 (2U) /*!< Bit position for LLWU_PE4_WUPE13. */ #define BM_LLWU_PE4_WUPE13 (0x0CU) /*!< Bit mask for LLWU_PE4_WUPE13. */ #define BS_LLWU_PE4_WUPE13 (2U) /*!< Bit field size in bits for LLWU_PE4_WUPE13. */ /*! @brief Read current value of the LLWU_PE4_WUPE13 field. */ #define BR_LLWU_PE4_WUPE13(x) (HW_LLWU_PE4(x).B.WUPE13) /*! @brief Format value for bitfield LLWU_PE4_WUPE13. */ #define BF_LLWU_PE4_WUPE13(v) ((uint8_t)((uint8_t)(v) << BP_LLWU_PE4_WUPE13) & BM_LLWU_PE4_WUPE13) /*! @brief Set the WUPE13 field to a new value. */ #define BW_LLWU_PE4_WUPE13(x, v) (HW_LLWU_PE4_WR(x, (HW_LLWU_PE4_RD(x) & ~BM_LLWU_PE4_WUPE13) | BF_LLWU_PE4_WUPE13(v))) /*@}*/ /*! * @name Register LLWU_PE4, field WUPE14[5:4] (RW) * * Enables and configures the edge detection for the wakeup pin. * * Values: * - 00 - External input pin disabled as wakeup input * - 01 - External input pin enabled with rising edge detection * - 10 - External input pin enabled with falling edge detection * - 11 - External input pin enabled with any change detection */ /*@{*/ #define BP_LLWU_PE4_WUPE14 (4U) /*!< Bit position for LLWU_PE4_WUPE14. */ #define BM_LLWU_PE4_WUPE14 (0x30U) /*!< Bit mask for LLWU_PE4_WUPE14. */ #define BS_LLWU_PE4_WUPE14 (2U) /*!< Bit field size in bits for LLWU_PE4_WUPE14. */ /*! @brief Read current value of the LLWU_PE4_WUPE14 field. */ #define BR_LLWU_PE4_WUPE14(x) (HW_LLWU_PE4(x).B.WUPE14) /*! @brief Format value for bitfield LLWU_PE4_WUPE14. */ #define BF_LLWU_PE4_WUPE14(v) ((uint8_t)((uint8_t)(v) << BP_LLWU_PE4_WUPE14) & BM_LLWU_PE4_WUPE14) /*! @brief Set the WUPE14 field to a new value. */ #define BW_LLWU_PE4_WUPE14(x, v) (HW_LLWU_PE4_WR(x, (HW_LLWU_PE4_RD(x) & ~BM_LLWU_PE4_WUPE14) | BF_LLWU_PE4_WUPE14(v))) /*@}*/ /*! * @name Register LLWU_PE4, field WUPE15[7:6] (RW) * * Enables and configures the edge detection for the wakeup pin. * * Values: * - 00 - External input pin disabled as wakeup input * - 01 - External input pin enabled with rising edge detection * - 10 - External input pin enabled with falling edge detection * - 11 - External input pin enabled with any change detection */ /*@{*/ #define BP_LLWU_PE4_WUPE15 (6U) /*!< Bit position for LLWU_PE4_WUPE15. */ #define BM_LLWU_PE4_WUPE15 (0xC0U) /*!< Bit mask for LLWU_PE4_WUPE15. */ #define BS_LLWU_PE4_WUPE15 (2U) /*!< Bit field size in bits for LLWU_PE4_WUPE15. */ /*! @brief Read current value of the LLWU_PE4_WUPE15 field. */ #define BR_LLWU_PE4_WUPE15(x) (HW_LLWU_PE4(x).B.WUPE15) /*! @brief Format value for bitfield LLWU_PE4_WUPE15. */ #define BF_LLWU_PE4_WUPE15(v) ((uint8_t)((uint8_t)(v) << BP_LLWU_PE4_WUPE15) & BM_LLWU_PE4_WUPE15) /*! @brief Set the WUPE15 field to a new value. */ #define BW_LLWU_PE4_WUPE15(x, v) (HW_LLWU_PE4_WR(x, (HW_LLWU_PE4_RD(x) & ~BM_LLWU_PE4_WUPE15) | BF_LLWU_PE4_WUPE15(v))) /*@}*/ /******************************************************************************* * HW_LLWU_ME - LLWU Module Enable register ******************************************************************************/ /*! * @brief HW_LLWU_ME - LLWU Module Enable register (RW) * * Reset value: 0x00U * * LLWU_ME contains the bits to enable the internal module flag as a wakeup * input source for inputs MWUF7-MWUF0. This register is reset on Chip Reset not VLLS * and by reset types that trigger Chip Reset not VLLS. It is unaffected by * reset types that do not trigger Chip Reset not VLLS. See the * IntroductionInformation found here describes the registers of the Reset Control Module (RCM). The * RCM implements many of the reset functions for the chip. See the chip's reset * chapter for more information. details for more information. */ typedef union _hw_llwu_me { uint8_t U; struct _hw_llwu_me_bitfields { uint8_t WUME0 : 1; /*!< [0] Wakeup Module Enable For Module 0 */ uint8_t WUME1 : 1; /*!< [1] Wakeup Module Enable for Module 1 */ uint8_t WUME2 : 1; /*!< [2] Wakeup Module Enable For Module 2 */ uint8_t WUME3 : 1; /*!< [3] Wakeup Module Enable For Module 3 */ uint8_t WUME4 : 1; /*!< [4] Wakeup Module Enable For Module 4 */ uint8_t WUME5 : 1; /*!< [5] Wakeup Module Enable For Module 5 */ uint8_t WUME6 : 1; /*!< [6] Wakeup Module Enable For Module 6 */ uint8_t WUME7 : 1; /*!< [7] Wakeup Module Enable For Module 7 */ } B; } hw_llwu_me_t; /*! * @name Constants and macros for entire LLWU_ME register */ /*@{*/ #define HW_LLWU_ME_ADDR(x) ((x) + 0x4U) #define HW_LLWU_ME(x) (*(__IO hw_llwu_me_t *) HW_LLWU_ME_ADDR(x)) #define HW_LLWU_ME_RD(x) (HW_LLWU_ME(x).U) #define HW_LLWU_ME_WR(x, v) (HW_LLWU_ME(x).U = (v)) #define HW_LLWU_ME_SET(x, v) (HW_LLWU_ME_WR(x, HW_LLWU_ME_RD(x) | (v))) #define HW_LLWU_ME_CLR(x, v) (HW_LLWU_ME_WR(x, HW_LLWU_ME_RD(x) & ~(v))) #define HW_LLWU_ME_TOG(x, v) (HW_LLWU_ME_WR(x, HW_LLWU_ME_RD(x) ^ (v))) /*@}*/ /* * Constants & macros for individual LLWU_ME bitfields */ /*! * @name Register LLWU_ME, field WUME0[0] (RW) * * Enables an internal module as a wakeup source input. * * Values: * - 0 - Internal module flag not used as wakeup source * - 1 - Internal module flag used as wakeup source */ /*@{*/ #define BP_LLWU_ME_WUME0 (0U) /*!< Bit position for LLWU_ME_WUME0. */ #define BM_LLWU_ME_WUME0 (0x01U) /*!< Bit mask for LLWU_ME_WUME0. */ #define BS_LLWU_ME_WUME0 (1U) /*!< Bit field size in bits for LLWU_ME_WUME0. */ /*! @brief Read current value of the LLWU_ME_WUME0 field. */ #define BR_LLWU_ME_WUME0(x) (BITBAND_ACCESS8(HW_LLWU_ME_ADDR(x), BP_LLWU_ME_WUME0)) /*! @brief Format value for bitfield LLWU_ME_WUME0. */ #define BF_LLWU_ME_WUME0(v) ((uint8_t)((uint8_t)(v) << BP_LLWU_ME_WUME0) & BM_LLWU_ME_WUME0) /*! @brief Set the WUME0 field to a new value. */ #define BW_LLWU_ME_WUME0(x, v) (BITBAND_ACCESS8(HW_LLWU_ME_ADDR(x), BP_LLWU_ME_WUME0) = (v)) /*@}*/ /*! * @name Register LLWU_ME, field WUME1[1] (RW) * * Enables an internal module as a wakeup source input. * * Values: * - 0 - Internal module flag not used as wakeup source * - 1 - Internal module flag used as wakeup source */ /*@{*/ #define BP_LLWU_ME_WUME1 (1U) /*!< Bit position for LLWU_ME_WUME1. */ #define BM_LLWU_ME_WUME1 (0x02U) /*!< Bit mask for LLWU_ME_WUME1. */ #define BS_LLWU_ME_WUME1 (1U) /*!< Bit field size in bits for LLWU_ME_WUME1. */ /*! @brief Read current value of the LLWU_ME_WUME1 field. */ #define BR_LLWU_ME_WUME1(x) (BITBAND_ACCESS8(HW_LLWU_ME_ADDR(x), BP_LLWU_ME_WUME1)) /*! @brief Format value for bitfield LLWU_ME_WUME1. */ #define BF_LLWU_ME_WUME1(v) ((uint8_t)((uint8_t)(v) << BP_LLWU_ME_WUME1) & BM_LLWU_ME_WUME1) /*! @brief Set the WUME1 field to a new value. */ #define BW_LLWU_ME_WUME1(x, v) (BITBAND_ACCESS8(HW_LLWU_ME_ADDR(x), BP_LLWU_ME_WUME1) = (v)) /*@}*/ /*! * @name Register LLWU_ME, field WUME2[2] (RW) * * Enables an internal module as a wakeup source input. * * Values: * - 0 - Internal module flag not used as wakeup source * - 1 - Internal module flag used as wakeup source */ /*@{*/ #define BP_LLWU_ME_WUME2 (2U) /*!< Bit position for LLWU_ME_WUME2. */ #define BM_LLWU_ME_WUME2 (0x04U) /*!< Bit mask for LLWU_ME_WUME2. */ #define BS_LLWU_ME_WUME2 (1U) /*!< Bit field size in bits for LLWU_ME_WUME2. */ /*! @brief Read current value of the LLWU_ME_WUME2 field. */ #define BR_LLWU_ME_WUME2(x) (BITBAND_ACCESS8(HW_LLWU_ME_ADDR(x), BP_LLWU_ME_WUME2)) /*! @brief Format value for bitfield LLWU_ME_WUME2. */ #define BF_LLWU_ME_WUME2(v) ((uint8_t)((uint8_t)(v) << BP_LLWU_ME_WUME2) & BM_LLWU_ME_WUME2) /*! @brief Set the WUME2 field to a new value. */ #define BW_LLWU_ME_WUME2(x, v) (BITBAND_ACCESS8(HW_LLWU_ME_ADDR(x), BP_LLWU_ME_WUME2) = (v)) /*@}*/ /*! * @name Register LLWU_ME, field WUME3[3] (RW) * * Enables an internal module as a wakeup source input. * * Values: * - 0 - Internal module flag not used as wakeup source * - 1 - Internal module flag used as wakeup source */ /*@{*/ #define BP_LLWU_ME_WUME3 (3U) /*!< Bit position for LLWU_ME_WUME3. */ #define BM_LLWU_ME_WUME3 (0x08U) /*!< Bit mask for LLWU_ME_WUME3. */ #define BS_LLWU_ME_WUME3 (1U) /*!< Bit field size in bits for LLWU_ME_WUME3. */ /*! @brief Read current value of the LLWU_ME_WUME3 field. */ #define BR_LLWU_ME_WUME3(x) (BITBAND_ACCESS8(HW_LLWU_ME_ADDR(x), BP_LLWU_ME_WUME3)) /*! @brief Format value for bitfield LLWU_ME_WUME3. */ #define BF_LLWU_ME_WUME3(v) ((uint8_t)((uint8_t)(v) << BP_LLWU_ME_WUME3) & BM_LLWU_ME_WUME3) /*! @brief Set the WUME3 field to a new value. */ #define BW_LLWU_ME_WUME3(x, v) (BITBAND_ACCESS8(HW_LLWU_ME_ADDR(x), BP_LLWU_ME_WUME3) = (v)) /*@}*/ /*! * @name Register LLWU_ME, field WUME4[4] (RW) * * Enables an internal module as a wakeup source input. * * Values: * - 0 - Internal module flag not used as wakeup source * - 1 - Internal module flag used as wakeup source */ /*@{*/ #define BP_LLWU_ME_WUME4 (4U) /*!< Bit position for LLWU_ME_WUME4. */ #define BM_LLWU_ME_WUME4 (0x10U) /*!< Bit mask for LLWU_ME_WUME4. */ #define BS_LLWU_ME_WUME4 (1U) /*!< Bit field size in bits for LLWU_ME_WUME4. */ /*! @brief Read current value of the LLWU_ME_WUME4 field. */ #define BR_LLWU_ME_WUME4(x) (BITBAND_ACCESS8(HW_LLWU_ME_ADDR(x), BP_LLWU_ME_WUME4)) /*! @brief Format value for bitfield LLWU_ME_WUME4. */ #define BF_LLWU_ME_WUME4(v) ((uint8_t)((uint8_t)(v) << BP_LLWU_ME_WUME4) & BM_LLWU_ME_WUME4) /*! @brief Set the WUME4 field to a new value. */ #define BW_LLWU_ME_WUME4(x, v) (BITBAND_ACCESS8(HW_LLWU_ME_ADDR(x), BP_LLWU_ME_WUME4) = (v)) /*@}*/ /*! * @name Register LLWU_ME, field WUME5[5] (RW) * * Enables an internal module as a wakeup source input. * * Values: * - 0 - Internal module flag not used as wakeup source * - 1 - Internal module flag used as wakeup source */ /*@{*/ #define BP_LLWU_ME_WUME5 (5U) /*!< Bit position for LLWU_ME_WUME5. */ #define BM_LLWU_ME_WUME5 (0x20U) /*!< Bit mask for LLWU_ME_WUME5. */ #define BS_LLWU_ME_WUME5 (1U) /*!< Bit field size in bits for LLWU_ME_WUME5. */ /*! @brief Read current value of the LLWU_ME_WUME5 field. */ #define BR_LLWU_ME_WUME5(x) (BITBAND_ACCESS8(HW_LLWU_ME_ADDR(x), BP_LLWU_ME_WUME5)) /*! @brief Format value for bitfield LLWU_ME_WUME5. */ #define BF_LLWU_ME_WUME5(v) ((uint8_t)((uint8_t)(v) << BP_LLWU_ME_WUME5) & BM_LLWU_ME_WUME5) /*! @brief Set the WUME5 field to a new value. */ #define BW_LLWU_ME_WUME5(x, v) (BITBAND_ACCESS8(HW_LLWU_ME_ADDR(x), BP_LLWU_ME_WUME5) = (v)) /*@}*/ /*! * @name Register LLWU_ME, field WUME6[6] (RW) * * Enables an internal module as a wakeup source input. * * Values: * - 0 - Internal module flag not used as wakeup source * - 1 - Internal module flag used as wakeup source */ /*@{*/ #define BP_LLWU_ME_WUME6 (6U) /*!< Bit position for LLWU_ME_WUME6. */ #define BM_LLWU_ME_WUME6 (0x40U) /*!< Bit mask for LLWU_ME_WUME6. */ #define BS_LLWU_ME_WUME6 (1U) /*!< Bit field size in bits for LLWU_ME_WUME6. */ /*! @brief Read current value of the LLWU_ME_WUME6 field. */ #define BR_LLWU_ME_WUME6(x) (BITBAND_ACCESS8(HW_LLWU_ME_ADDR(x), BP_LLWU_ME_WUME6)) /*! @brief Format value for bitfield LLWU_ME_WUME6. */ #define BF_LLWU_ME_WUME6(v) ((uint8_t)((uint8_t)(v) << BP_LLWU_ME_WUME6) & BM_LLWU_ME_WUME6) /*! @brief Set the WUME6 field to a new value. */ #define BW_LLWU_ME_WUME6(x, v) (BITBAND_ACCESS8(HW_LLWU_ME_ADDR(x), BP_LLWU_ME_WUME6) = (v)) /*@}*/ /*! * @name Register LLWU_ME, field WUME7[7] (RW) * * Enables an internal module as a wakeup source input. * * Values: * - 0 - Internal module flag not used as wakeup source * - 1 - Internal module flag used as wakeup source */ /*@{*/ #define BP_LLWU_ME_WUME7 (7U) /*!< Bit position for LLWU_ME_WUME7. */ #define BM_LLWU_ME_WUME7 (0x80U) /*!< Bit mask for LLWU_ME_WUME7. */ #define BS_LLWU_ME_WUME7 (1U) /*!< Bit field size in bits for LLWU_ME_WUME7. */ /*! @brief Read current value of the LLWU_ME_WUME7 field. */ #define BR_LLWU_ME_WUME7(x) (BITBAND_ACCESS8(HW_LLWU_ME_ADDR(x), BP_LLWU_ME_WUME7)) /*! @brief Format value for bitfield LLWU_ME_WUME7. */ #define BF_LLWU_ME_WUME7(v) ((uint8_t)((uint8_t)(v) << BP_LLWU_ME_WUME7) & BM_LLWU_ME_WUME7) /*! @brief Set the WUME7 field to a new value. */ #define BW_LLWU_ME_WUME7(x, v) (BITBAND_ACCESS8(HW_LLWU_ME_ADDR(x), BP_LLWU_ME_WUME7) = (v)) /*@}*/ /******************************************************************************* * HW_LLWU_F1 - LLWU Flag 1 register ******************************************************************************/ /*! * @brief HW_LLWU_F1 - LLWU Flag 1 register (W1C) * * Reset value: 0x00U * * LLWU_F1 contains the wakeup flags indicating which wakeup source caused the * MCU to exit LLS or VLLS mode. For LLS, this is the source causing the CPU * interrupt flow. For VLLS, this is the source causing the MCU reset flow. The * external wakeup flags are read-only and clearing a flag is accomplished by a write * of a 1 to the corresponding WUFx bit. The wakeup flag (WUFx), if set, will * remain set if the associated WUPEx bit is cleared. This register is reset on Chip * Reset not VLLS and by reset types that trigger Chip Reset not VLLS. It is * unaffected by reset types that do not trigger Chip Reset not VLLS. See the * IntroductionInformation found here describes the registers of the Reset Control * Module (RCM). The RCM implements many of the reset functions for the chip. See the * chip's reset chapter for more information. details for more information. */ typedef union _hw_llwu_f1 { uint8_t U; struct _hw_llwu_f1_bitfields { uint8_t WUF0 : 1; /*!< [0] Wakeup Flag For LLWU_P0 */ uint8_t WUF1 : 1; /*!< [1] Wakeup Flag For LLWU_P1 */ uint8_t WUF2 : 1; /*!< [2] Wakeup Flag For LLWU_P2 */ uint8_t WUF3 : 1; /*!< [3] Wakeup Flag For LLWU_P3 */ uint8_t WUF4 : 1; /*!< [4] Wakeup Flag For LLWU_P4 */ uint8_t WUF5 : 1; /*!< [5] Wakeup Flag For LLWU_P5 */ uint8_t WUF6 : 1; /*!< [6] Wakeup Flag For LLWU_P6 */ uint8_t WUF7 : 1; /*!< [7] Wakeup Flag For LLWU_P7 */ } B; } hw_llwu_f1_t; /*! * @name Constants and macros for entire LLWU_F1 register */ /*@{*/ #define HW_LLWU_F1_ADDR(x) ((x) + 0x5U) #define HW_LLWU_F1(x) (*(__IO hw_llwu_f1_t *) HW_LLWU_F1_ADDR(x)) #define HW_LLWU_F1_RD(x) (HW_LLWU_F1(x).U) #define HW_LLWU_F1_WR(x, v) (HW_LLWU_F1(x).U = (v)) #define HW_LLWU_F1_SET(x, v) (HW_LLWU_F1_WR(x, HW_LLWU_F1_RD(x) | (v))) #define HW_LLWU_F1_CLR(x, v) (HW_LLWU_F1_WR(x, HW_LLWU_F1_RD(x) & ~(v))) #define HW_LLWU_F1_TOG(x, v) (HW_LLWU_F1_WR(x, HW_LLWU_F1_RD(x) ^ (v))) /*@}*/ /* * Constants & macros for individual LLWU_F1 bitfields */ /*! * @name Register LLWU_F1, field WUF0[0] (W1C) * * Indicates that an enabled external wake-up pin was a source of exiting a * low-leakage power mode. To clear the flag, write a 1 to WUF0. * * Values: * - 0 - LLWU_P0 input was not a wakeup source * - 1 - LLWU_P0 input was a wakeup source */ /*@{*/ #define BP_LLWU_F1_WUF0 (0U) /*!< Bit position for LLWU_F1_WUF0. */ #define BM_LLWU_F1_WUF0 (0x01U) /*!< Bit mask for LLWU_F1_WUF0. */ #define BS_LLWU_F1_WUF0 (1U) /*!< Bit field size in bits for LLWU_F1_WUF0. */ /*! @brief Read current value of the LLWU_F1_WUF0 field. */ #define BR_LLWU_F1_WUF0(x) (BITBAND_ACCESS8(HW_LLWU_F1_ADDR(x), BP_LLWU_F1_WUF0)) /*! @brief Format value for bitfield LLWU_F1_WUF0. */ #define BF_LLWU_F1_WUF0(v) ((uint8_t)((uint8_t)(v) << BP_LLWU_F1_WUF0) & BM_LLWU_F1_WUF0) /*! @brief Set the WUF0 field to a new value. */ #define BW_LLWU_F1_WUF0(x, v) (BITBAND_ACCESS8(HW_LLWU_F1_ADDR(x), BP_LLWU_F1_WUF0) = (v)) /*@}*/ /*! * @name Register LLWU_F1, field WUF1[1] (W1C) * * Indicates that an enabled external wakeup pin was a source of exiting a * low-leakage power mode. To clear the flag, write a 1 to WUF1. * * Values: * - 0 - LLWU_P1 input was not a wakeup source * - 1 - LLWU_P1 input was a wakeup source */ /*@{*/ #define BP_LLWU_F1_WUF1 (1U) /*!< Bit position for LLWU_F1_WUF1. */ #define BM_LLWU_F1_WUF1 (0x02U) /*!< Bit mask for LLWU_F1_WUF1. */ #define BS_LLWU_F1_WUF1 (1U) /*!< Bit field size in bits for LLWU_F1_WUF1. */ /*! @brief Read current value of the LLWU_F1_WUF1 field. */ #define BR_LLWU_F1_WUF1(x) (BITBAND_ACCESS8(HW_LLWU_F1_ADDR(x), BP_LLWU_F1_WUF1)) /*! @brief Format value for bitfield LLWU_F1_WUF1. */ #define BF_LLWU_F1_WUF1(v) ((uint8_t)((uint8_t)(v) << BP_LLWU_F1_WUF1) & BM_LLWU_F1_WUF1) /*! @brief Set the WUF1 field to a new value. */ #define BW_LLWU_F1_WUF1(x, v) (BITBAND_ACCESS8(HW_LLWU_F1_ADDR(x), BP_LLWU_F1_WUF1) = (v)) /*@}*/ /*! * @name Register LLWU_F1, field WUF2[2] (W1C) * * Indicates that an enabled external wakeup pin was a source of exiting a * low-leakage power mode. To clear the flag, write a 1 to WUF2. * * Values: * - 0 - LLWU_P2 input was not a wakeup source * - 1 - LLWU_P2 input was a wakeup source */ /*@{*/ #define BP_LLWU_F1_WUF2 (2U) /*!< Bit position for LLWU_F1_WUF2. */ #define BM_LLWU_F1_WUF2 (0x04U) /*!< Bit mask for LLWU_F1_WUF2. */ #define BS_LLWU_F1_WUF2 (1U) /*!< Bit field size in bits for LLWU_F1_WUF2. */ /*! @brief Read current value of the LLWU_F1_WUF2 field. */ #define BR_LLWU_F1_WUF2(x) (BITBAND_ACCESS8(HW_LLWU_F1_ADDR(x), BP_LLWU_F1_WUF2)) /*! @brief Format value for bitfield LLWU_F1_WUF2. */ #define BF_LLWU_F1_WUF2(v) ((uint8_t)((uint8_t)(v) << BP_LLWU_F1_WUF2) & BM_LLWU_F1_WUF2) /*! @brief Set the WUF2 field to a new value. */ #define BW_LLWU_F1_WUF2(x, v) (BITBAND_ACCESS8(HW_LLWU_F1_ADDR(x), BP_LLWU_F1_WUF2) = (v)) /*@}*/ /*! * @name Register LLWU_F1, field WUF3[3] (W1C) * * Indicates that an enabled external wakeup pin was a source of exiting a * low-leakage power mode. To clear the flag, write a 1 to WUF3. * * Values: * - 0 - LLWU_P3 input was not a wake-up source * - 1 - LLWU_P3 input was a wake-up source */ /*@{*/ #define BP_LLWU_F1_WUF3 (3U) /*!< Bit position for LLWU_F1_WUF3. */ #define BM_LLWU_F1_WUF3 (0x08U) /*!< Bit mask for LLWU_F1_WUF3. */ #define BS_LLWU_F1_WUF3 (1U) /*!< Bit field size in bits for LLWU_F1_WUF3. */ /*! @brief Read current value of the LLWU_F1_WUF3 field. */ #define BR_LLWU_F1_WUF3(x) (BITBAND_ACCESS8(HW_LLWU_F1_ADDR(x), BP_LLWU_F1_WUF3)) /*! @brief Format value for bitfield LLWU_F1_WUF3. */ #define BF_LLWU_F1_WUF3(v) ((uint8_t)((uint8_t)(v) << BP_LLWU_F1_WUF3) & BM_LLWU_F1_WUF3) /*! @brief Set the WUF3 field to a new value. */ #define BW_LLWU_F1_WUF3(x, v) (BITBAND_ACCESS8(HW_LLWU_F1_ADDR(x), BP_LLWU_F1_WUF3) = (v)) /*@}*/ /*! * @name Register LLWU_F1, field WUF4[4] (W1C) * * Indicates that an enabled external wake-up pin was a source of exiting a * low-leakage power mode. To clear the flag, write a 1 to WUF4. * * Values: * - 0 - LLWU_P4 input was not a wakeup source * - 1 - LLWU_P4 input was a wakeup source */ /*@{*/ #define BP_LLWU_F1_WUF4 (4U) /*!< Bit position for LLWU_F1_WUF4. */ #define BM_LLWU_F1_WUF4 (0x10U) /*!< Bit mask for LLWU_F1_WUF4. */ #define BS_LLWU_F1_WUF4 (1U) /*!< Bit field size in bits for LLWU_F1_WUF4. */ /*! @brief Read current value of the LLWU_F1_WUF4 field. */ #define BR_LLWU_F1_WUF4(x) (BITBAND_ACCESS8(HW_LLWU_F1_ADDR(x), BP_LLWU_F1_WUF4)) /*! @brief Format value for bitfield LLWU_F1_WUF4. */ #define BF_LLWU_F1_WUF4(v) ((uint8_t)((uint8_t)(v) << BP_LLWU_F1_WUF4) & BM_LLWU_F1_WUF4) /*! @brief Set the WUF4 field to a new value. */ #define BW_LLWU_F1_WUF4(x, v) (BITBAND_ACCESS8(HW_LLWU_F1_ADDR(x), BP_LLWU_F1_WUF4) = (v)) /*@}*/ /*! * @name Register LLWU_F1, field WUF5[5] (W1C) * * Indicates that an enabled external wakeup pin was a source of exiting a * low-leakage power mode. To clear the flag, write a 1 to WUF5. * * Values: * - 0 - LLWU_P5 input was not a wakeup source * - 1 - LLWU_P5 input was a wakeup source */ /*@{*/ #define BP_LLWU_F1_WUF5 (5U) /*!< Bit position for LLWU_F1_WUF5. */ #define BM_LLWU_F1_WUF5 (0x20U) /*!< Bit mask for LLWU_F1_WUF5. */ #define BS_LLWU_F1_WUF5 (1U) /*!< Bit field size in bits for LLWU_F1_WUF5. */ /*! @brief Read current value of the LLWU_F1_WUF5 field. */ #define BR_LLWU_F1_WUF5(x) (BITBAND_ACCESS8(HW_LLWU_F1_ADDR(x), BP_LLWU_F1_WUF5)) /*! @brief Format value for bitfield LLWU_F1_WUF5. */ #define BF_LLWU_F1_WUF5(v) ((uint8_t)((uint8_t)(v) << BP_LLWU_F1_WUF5) & BM_LLWU_F1_WUF5) /*! @brief Set the WUF5 field to a new value. */ #define BW_LLWU_F1_WUF5(x, v) (BITBAND_ACCESS8(HW_LLWU_F1_ADDR(x), BP_LLWU_F1_WUF5) = (v)) /*@}*/ /*! * @name Register LLWU_F1, field WUF6[6] (W1C) * * Indicates that an enabled external wakeup pin was a source of exiting a * low-leakage power mode. To clear the flag, write a 1 to WUF6. * * Values: * - 0 - LLWU_P6 input was not a wakeup source * - 1 - LLWU_P6 input was a wakeup source */ /*@{*/ #define BP_LLWU_F1_WUF6 (6U) /*!< Bit position for LLWU_F1_WUF6. */ #define BM_LLWU_F1_WUF6 (0x40U) /*!< Bit mask for LLWU_F1_WUF6. */ #define BS_LLWU_F1_WUF6 (1U) /*!< Bit field size in bits for LLWU_F1_WUF6. */ /*! @brief Read current value of the LLWU_F1_WUF6 field. */ #define BR_LLWU_F1_WUF6(x) (BITBAND_ACCESS8(HW_LLWU_F1_ADDR(x), BP_LLWU_F1_WUF6)) /*! @brief Format value for bitfield LLWU_F1_WUF6. */ #define BF_LLWU_F1_WUF6(v) ((uint8_t)((uint8_t)(v) << BP_LLWU_F1_WUF6) & BM_LLWU_F1_WUF6) /*! @brief Set the WUF6 field to a new value. */ #define BW_LLWU_F1_WUF6(x, v) (BITBAND_ACCESS8(HW_LLWU_F1_ADDR(x), BP_LLWU_F1_WUF6) = (v)) /*@}*/ /*! * @name Register LLWU_F1, field WUF7[7] (W1C) * * Indicates that an enabled external wakeup pin was a source of exiting a * low-leakage power mode. To clear the flag, write a 1 to WUF7. * * Values: * - 0 - LLWU_P7 input was not a wakeup source * - 1 - LLWU_P7 input was a wakeup source */ /*@{*/ #define BP_LLWU_F1_WUF7 (7U) /*!< Bit position for LLWU_F1_WUF7. */ #define BM_LLWU_F1_WUF7 (0x80U) /*!< Bit mask for LLWU_F1_WUF7. */ #define BS_LLWU_F1_WUF7 (1U) /*!< Bit field size in bits for LLWU_F1_WUF7. */ /*! @brief Read current value of the LLWU_F1_WUF7 field. */ #define BR_LLWU_F1_WUF7(x) (BITBAND_ACCESS8(HW_LLWU_F1_ADDR(x), BP_LLWU_F1_WUF7)) /*! @brief Format value for bitfield LLWU_F1_WUF7. */ #define BF_LLWU_F1_WUF7(v) ((uint8_t)((uint8_t)(v) << BP_LLWU_F1_WUF7) & BM_LLWU_F1_WUF7) /*! @brief Set the WUF7 field to a new value. */ #define BW_LLWU_F1_WUF7(x, v) (BITBAND_ACCESS8(HW_LLWU_F1_ADDR(x), BP_LLWU_F1_WUF7) = (v)) /*@}*/ /******************************************************************************* * HW_LLWU_F2 - LLWU Flag 2 register ******************************************************************************/ /*! * @brief HW_LLWU_F2 - LLWU Flag 2 register (W1C) * * Reset value: 0x00U * * LLWU_F2 contains the wakeup flags indicating which wakeup source caused the * MCU to exit LLS or VLLS mode. For LLS, this is the source causing the CPU * interrupt flow. For VLLS, this is the source causing the MCU reset flow. The * external wakeup flags are read-only and clearing a flag is accomplished by a write * of a 1 to the corresponding WUFx bit. The wakeup flag (WUFx), if set, will * remain set if the associated WUPEx bit is cleared. This register is reset on Chip * Reset not VLLS and by reset types that trigger Chip Reset not VLLS. It is * unaffected by reset types that do not trigger Chip Reset not VLLS. See the * IntroductionInformation found here describes the registers of the Reset Control * Module (RCM). The RCM implements many of the reset functions for the chip. See the * chip's reset chapter for more information. details for more information. */ typedef union _hw_llwu_f2 { uint8_t U; struct _hw_llwu_f2_bitfields { uint8_t WUF8 : 1; /*!< [0] Wakeup Flag For LLWU_P8 */ uint8_t WUF9 : 1; /*!< [1] Wakeup Flag For LLWU_P9 */ uint8_t WUF10 : 1; /*!< [2] Wakeup Flag For LLWU_P10 */ uint8_t WUF11 : 1; /*!< [3] Wakeup Flag For LLWU_P11 */ uint8_t WUF12 : 1; /*!< [4] Wakeup Flag For LLWU_P12 */ uint8_t WUF13 : 1; /*!< [5] Wakeup Flag For LLWU_P13 */ uint8_t WUF14 : 1; /*!< [6] Wakeup Flag For LLWU_P14 */ uint8_t WUF15 : 1; /*!< [7] Wakeup Flag For LLWU_P15 */ } B; } hw_llwu_f2_t; /*! * @name Constants and macros for entire LLWU_F2 register */ /*@{*/ #define HW_LLWU_F2_ADDR(x) ((x) + 0x6U) #define HW_LLWU_F2(x) (*(__IO hw_llwu_f2_t *) HW_LLWU_F2_ADDR(x)) #define HW_LLWU_F2_RD(x) (HW_LLWU_F2(x).U) #define HW_LLWU_F2_WR(x, v) (HW_LLWU_F2(x).U = (v)) #define HW_LLWU_F2_SET(x, v) (HW_LLWU_F2_WR(x, HW_LLWU_F2_RD(x) | (v))) #define HW_LLWU_F2_CLR(x, v) (HW_LLWU_F2_WR(x, HW_LLWU_F2_RD(x) & ~(v))) #define HW_LLWU_F2_TOG(x, v) (HW_LLWU_F2_WR(x, HW_LLWU_F2_RD(x) ^ (v))) /*@}*/ /* * Constants & macros for individual LLWU_F2 bitfields */ /*! * @name Register LLWU_F2, field WUF8[0] (W1C) * * Indicates that an enabled external wakeup pin was a source of exiting a * low-leakage power mode. To clear the flag, write a 1 to WUF8. * * Values: * - 0 - LLWU_P8 input was not a wakeup source * - 1 - LLWU_P8 input was a wakeup source */ /*@{*/ #define BP_LLWU_F2_WUF8 (0U) /*!< Bit position for LLWU_F2_WUF8. */ #define BM_LLWU_F2_WUF8 (0x01U) /*!< Bit mask for LLWU_F2_WUF8. */ #define BS_LLWU_F2_WUF8 (1U) /*!< Bit field size in bits for LLWU_F2_WUF8. */ /*! @brief Read current value of the LLWU_F2_WUF8 field. */ #define BR_LLWU_F2_WUF8(x) (BITBAND_ACCESS8(HW_LLWU_F2_ADDR(x), BP_LLWU_F2_WUF8)) /*! @brief Format value for bitfield LLWU_F2_WUF8. */ #define BF_LLWU_F2_WUF8(v) ((uint8_t)((uint8_t)(v) << BP_LLWU_F2_WUF8) & BM_LLWU_F2_WUF8) /*! @brief Set the WUF8 field to a new value. */ #define BW_LLWU_F2_WUF8(x, v) (BITBAND_ACCESS8(HW_LLWU_F2_ADDR(x), BP_LLWU_F2_WUF8) = (v)) /*@}*/ /*! * @name Register LLWU_F2, field WUF9[1] (W1C) * * Indicates that an enabled external wakeup pin was a source of exiting a * low-leakage power mode. To clear the flag, write a 1 to WUF9. * * Values: * - 0 - LLWU_P9 input was not a wakeup source * - 1 - LLWU_P9 input was a wakeup source */ /*@{*/ #define BP_LLWU_F2_WUF9 (1U) /*!< Bit position for LLWU_F2_WUF9. */ #define BM_LLWU_F2_WUF9 (0x02U) /*!< Bit mask for LLWU_F2_WUF9. */ #define BS_LLWU_F2_WUF9 (1U) /*!< Bit field size in bits for LLWU_F2_WUF9. */ /*! @brief Read current value of the LLWU_F2_WUF9 field. */ #define BR_LLWU_F2_WUF9(x) (BITBAND_ACCESS8(HW_LLWU_F2_ADDR(x), BP_LLWU_F2_WUF9)) /*! @brief Format value for bitfield LLWU_F2_WUF9. */ #define BF_LLWU_F2_WUF9(v) ((uint8_t)((uint8_t)(v) << BP_LLWU_F2_WUF9) & BM_LLWU_F2_WUF9) /*! @brief Set the WUF9 field to a new value. */ #define BW_LLWU_F2_WUF9(x, v) (BITBAND_ACCESS8(HW_LLWU_F2_ADDR(x), BP_LLWU_F2_WUF9) = (v)) /*@}*/ /*! * @name Register LLWU_F2, field WUF10[2] (W1C) * * Indicates that an enabled external wakeup pin was a source of exiting a * low-leakage power mode. To clear the flag, write a 1 to WUF10. * * Values: * - 0 - LLWU_P10 input was not a wakeup source * - 1 - LLWU_P10 input was a wakeup source */ /*@{*/ #define BP_LLWU_F2_WUF10 (2U) /*!< Bit position for LLWU_F2_WUF10. */ #define BM_LLWU_F2_WUF10 (0x04U) /*!< Bit mask for LLWU_F2_WUF10. */ #define BS_LLWU_F2_WUF10 (1U) /*!< Bit field size in bits for LLWU_F2_WUF10. */ /*! @brief Read current value of the LLWU_F2_WUF10 field. */ #define BR_LLWU_F2_WUF10(x) (BITBAND_ACCESS8(HW_LLWU_F2_ADDR(x), BP_LLWU_F2_WUF10)) /*! @brief Format value for bitfield LLWU_F2_WUF10. */ #define BF_LLWU_F2_WUF10(v) ((uint8_t)((uint8_t)(v) << BP_LLWU_F2_WUF10) & BM_LLWU_F2_WUF10) /*! @brief Set the WUF10 field to a new value. */ #define BW_LLWU_F2_WUF10(x, v) (BITBAND_ACCESS8(HW_LLWU_F2_ADDR(x), BP_LLWU_F2_WUF10) = (v)) /*@}*/ /*! * @name Register LLWU_F2, field WUF11[3] (W1C) * * Indicates that an enabled external wakeup pin was a source of exiting a * low-leakage power mode. To clear the flag, write a 1 to WUF11. * * Values: * - 0 - LLWU_P11 input was not a wakeup source * - 1 - LLWU_P11 input was a wakeup source */ /*@{*/ #define BP_LLWU_F2_WUF11 (3U) /*!< Bit position for LLWU_F2_WUF11. */ #define BM_LLWU_F2_WUF11 (0x08U) /*!< Bit mask for LLWU_F2_WUF11. */ #define BS_LLWU_F2_WUF11 (1U) /*!< Bit field size in bits for LLWU_F2_WUF11. */ /*! @brief Read current value of the LLWU_F2_WUF11 field. */ #define BR_LLWU_F2_WUF11(x) (BITBAND_ACCESS8(HW_LLWU_F2_ADDR(x), BP_LLWU_F2_WUF11)) /*! @brief Format value for bitfield LLWU_F2_WUF11. */ #define BF_LLWU_F2_WUF11(v) ((uint8_t)((uint8_t)(v) << BP_LLWU_F2_WUF11) & BM_LLWU_F2_WUF11) /*! @brief Set the WUF11 field to a new value. */ #define BW_LLWU_F2_WUF11(x, v) (BITBAND_ACCESS8(HW_LLWU_F2_ADDR(x), BP_LLWU_F2_WUF11) = (v)) /*@}*/ /*! * @name Register LLWU_F2, field WUF12[4] (W1C) * * Indicates that an enabled external wakeup pin was a source of exiting a * low-leakage power mode. To clear the flag, write a 1 to WUF12. * * Values: * - 0 - LLWU_P12 input was not a wakeup source * - 1 - LLWU_P12 input was a wakeup source */ /*@{*/ #define BP_LLWU_F2_WUF12 (4U) /*!< Bit position for LLWU_F2_WUF12. */ #define BM_LLWU_F2_WUF12 (0x10U) /*!< Bit mask for LLWU_F2_WUF12. */ #define BS_LLWU_F2_WUF12 (1U) /*!< Bit field size in bits for LLWU_F2_WUF12. */ /*! @brief Read current value of the LLWU_F2_WUF12 field. */ #define BR_LLWU_F2_WUF12(x) (BITBAND_ACCESS8(HW_LLWU_F2_ADDR(x), BP_LLWU_F2_WUF12)) /*! @brief Format value for bitfield LLWU_F2_WUF12. */ #define BF_LLWU_F2_WUF12(v) ((uint8_t)((uint8_t)(v) << BP_LLWU_F2_WUF12) & BM_LLWU_F2_WUF12) /*! @brief Set the WUF12 field to a new value. */ #define BW_LLWU_F2_WUF12(x, v) (BITBAND_ACCESS8(HW_LLWU_F2_ADDR(x), BP_LLWU_F2_WUF12) = (v)) /*@}*/ /*! * @name Register LLWU_F2, field WUF13[5] (W1C) * * Indicates that an enabled external wakeup pin was a source of exiting a * low-leakage power mode. To clear the flag, write a 1 to WUF13. * * Values: * - 0 - LLWU_P13 input was not a wakeup source * - 1 - LLWU_P13 input was a wakeup source */ /*@{*/ #define BP_LLWU_F2_WUF13 (5U) /*!< Bit position for LLWU_F2_WUF13. */ #define BM_LLWU_F2_WUF13 (0x20U) /*!< Bit mask for LLWU_F2_WUF13. */ #define BS_LLWU_F2_WUF13 (1U) /*!< Bit field size in bits for LLWU_F2_WUF13. */ /*! @brief Read current value of the LLWU_F2_WUF13 field. */ #define BR_LLWU_F2_WUF13(x) (BITBAND_ACCESS8(HW_LLWU_F2_ADDR(x), BP_LLWU_F2_WUF13)) /*! @brief Format value for bitfield LLWU_F2_WUF13. */ #define BF_LLWU_F2_WUF13(v) ((uint8_t)((uint8_t)(v) << BP_LLWU_F2_WUF13) & BM_LLWU_F2_WUF13) /*! @brief Set the WUF13 field to a new value. */ #define BW_LLWU_F2_WUF13(x, v) (BITBAND_ACCESS8(HW_LLWU_F2_ADDR(x), BP_LLWU_F2_WUF13) = (v)) /*@}*/ /*! * @name Register LLWU_F2, field WUF14[6] (W1C) * * Indicates that an enabled external wakeup pin was a source of exiting a * low-leakage power mode. To clear the flag, write a 1 to WUF14. * * Values: * - 0 - LLWU_P14 input was not a wakeup source * - 1 - LLWU_P14 input was a wakeup source */ /*@{*/ #define BP_LLWU_F2_WUF14 (6U) /*!< Bit position for LLWU_F2_WUF14. */ #define BM_LLWU_F2_WUF14 (0x40U) /*!< Bit mask for LLWU_F2_WUF14. */ #define BS_LLWU_F2_WUF14 (1U) /*!< Bit field size in bits for LLWU_F2_WUF14. */ /*! @brief Read current value of the LLWU_F2_WUF14 field. */ #define BR_LLWU_F2_WUF14(x) (BITBAND_ACCESS8(HW_LLWU_F2_ADDR(x), BP_LLWU_F2_WUF14)) /*! @brief Format value for bitfield LLWU_F2_WUF14. */ #define BF_LLWU_F2_WUF14(v) ((uint8_t)((uint8_t)(v) << BP_LLWU_F2_WUF14) & BM_LLWU_F2_WUF14) /*! @brief Set the WUF14 field to a new value. */ #define BW_LLWU_F2_WUF14(x, v) (BITBAND_ACCESS8(HW_LLWU_F2_ADDR(x), BP_LLWU_F2_WUF14) = (v)) /*@}*/ /*! * @name Register LLWU_F2, field WUF15[7] (W1C) * * Indicates that an enabled external wakeup pin was a source of exiting a * low-leakage power mode. To clear the flag, write a 1 to WUF15. * * Values: * - 0 - LLWU_P15 input was not a wakeup source * - 1 - LLWU_P15 input was a wakeup source */ /*@{*/ #define BP_LLWU_F2_WUF15 (7U) /*!< Bit position for LLWU_F2_WUF15. */ #define BM_LLWU_F2_WUF15 (0x80U) /*!< Bit mask for LLWU_F2_WUF15. */ #define BS_LLWU_F2_WUF15 (1U) /*!< Bit field size in bits for LLWU_F2_WUF15. */ /*! @brief Read current value of the LLWU_F2_WUF15 field. */ #define BR_LLWU_F2_WUF15(x) (BITBAND_ACCESS8(HW_LLWU_F2_ADDR(x), BP_LLWU_F2_WUF15)) /*! @brief Format value for bitfield LLWU_F2_WUF15. */ #define BF_LLWU_F2_WUF15(v) ((uint8_t)((uint8_t)(v) << BP_LLWU_F2_WUF15) & BM_LLWU_F2_WUF15) /*! @brief Set the WUF15 field to a new value. */ #define BW_LLWU_F2_WUF15(x, v) (BITBAND_ACCESS8(HW_LLWU_F2_ADDR(x), BP_LLWU_F2_WUF15) = (v)) /*@}*/ /******************************************************************************* * HW_LLWU_F3 - LLWU Flag 3 register ******************************************************************************/ /*! * @brief HW_LLWU_F3 - LLWU Flag 3 register (RO) * * Reset value: 0x00U * * LLWU_F3 contains the wakeup flags indicating which internal wakeup source * caused the MCU to exit LLS or VLLS mode. For LLS, this is the source causing the * CPU interrupt flow. For VLLS, this is the source causing the MCU reset flow. * For internal peripherals that are capable of running in a low-leakage power * mode, such as a real time clock module or CMP module, the flag from the * associated peripheral is accessible as the MWUFx bit. The flag will need to be cleared * in the peripheral instead of writing a 1 to the MWUFx bit. This register is * reset on Chip Reset not VLLS and by reset types that trigger Chip Reset not * VLLS. It is unaffected by reset types that do not trigger Chip Reset not VLLS. See * the IntroductionInformation found here describes the registers of the Reset * Control Module (RCM). The RCM implements many of the reset functions for the * chip. See the chip's reset chapter for more information. details for more * information. */ typedef union _hw_llwu_f3 { uint8_t U; struct _hw_llwu_f3_bitfields { uint8_t MWUF0 : 1; /*!< [0] Wakeup flag For module 0 */ uint8_t MWUF1 : 1; /*!< [1] Wakeup flag For module 1 */ uint8_t MWUF2 : 1; /*!< [2] Wakeup flag For module 2 */ uint8_t MWUF3 : 1; /*!< [3] Wakeup flag For module 3 */ uint8_t MWUF4 : 1; /*!< [4] Wakeup flag For module 4 */ uint8_t MWUF5 : 1; /*!< [5] Wakeup flag For module 5 */ uint8_t MWUF6 : 1; /*!< [6] Wakeup flag For module 6 */ uint8_t MWUF7 : 1; /*!< [7] Wakeup flag For module 7 */ } B; } hw_llwu_f3_t; /*! * @name Constants and macros for entire LLWU_F3 register */ /*@{*/ #define HW_LLWU_F3_ADDR(x) ((x) + 0x7U) #define HW_LLWU_F3(x) (*(__I hw_llwu_f3_t *) HW_LLWU_F3_ADDR(x)) #define HW_LLWU_F3_RD(x) (HW_LLWU_F3(x).U) /*@}*/ /* * Constants & macros for individual LLWU_F3 bitfields */ /*! * @name Register LLWU_F3, field MWUF0[0] (RO) * * Indicates that an enabled internal peripheral was a source of exiting a * low-leakage power mode. To clear the flag, follow the internal peripheral flag * clearing mechanism. * * Values: * - 0 - Module 0 input was not a wakeup source * - 1 - Module 0 input was a wakeup source */ /*@{*/ #define BP_LLWU_F3_MWUF0 (0U) /*!< Bit position for LLWU_F3_MWUF0. */ #define BM_LLWU_F3_MWUF0 (0x01U) /*!< Bit mask for LLWU_F3_MWUF0. */ #define BS_LLWU_F3_MWUF0 (1U) /*!< Bit field size in bits for LLWU_F3_MWUF0. */ /*! @brief Read current value of the LLWU_F3_MWUF0 field. */ #define BR_LLWU_F3_MWUF0(x) (BITBAND_ACCESS8(HW_LLWU_F3_ADDR(x), BP_LLWU_F3_MWUF0)) /*@}*/ /*! * @name Register LLWU_F3, field MWUF1[1] (RO) * * Indicates that an enabled internal peripheral was a source of exiting a * low-leakage power mode. To clear the flag, follow the internal peripheral flag * clearing mechanism. * * Values: * - 0 - Module 1 input was not a wakeup source * - 1 - Module 1 input was a wakeup source */ /*@{*/ #define BP_LLWU_F3_MWUF1 (1U) /*!< Bit position for LLWU_F3_MWUF1. */ #define BM_LLWU_F3_MWUF1 (0x02U) /*!< Bit mask for LLWU_F3_MWUF1. */ #define BS_LLWU_F3_MWUF1 (1U) /*!< Bit field size in bits for LLWU_F3_MWUF1. */ /*! @brief Read current value of the LLWU_F3_MWUF1 field. */ #define BR_LLWU_F3_MWUF1(x) (BITBAND_ACCESS8(HW_LLWU_F3_ADDR(x), BP_LLWU_F3_MWUF1)) /*@}*/ /*! * @name Register LLWU_F3, field MWUF2[2] (RO) * * Indicates that an enabled internal peripheral was a source of exiting a * low-leakage power mode. To clear the flag, follow the internal peripheral flag * clearing mechanism. * * Values: * - 0 - Module 2 input was not a wakeup source * - 1 - Module 2 input was a wakeup source */ /*@{*/ #define BP_LLWU_F3_MWUF2 (2U) /*!< Bit position for LLWU_F3_MWUF2. */ #define BM_LLWU_F3_MWUF2 (0x04U) /*!< Bit mask for LLWU_F3_MWUF2. */ #define BS_LLWU_F3_MWUF2 (1U) /*!< Bit field size in bits for LLWU_F3_MWUF2. */ /*! @brief Read current value of the LLWU_F3_MWUF2 field. */ #define BR_LLWU_F3_MWUF2(x) (BITBAND_ACCESS8(HW_LLWU_F3_ADDR(x), BP_LLWU_F3_MWUF2)) /*@}*/ /*! * @name Register LLWU_F3, field MWUF3[3] (RO) * * Indicates that an enabled internal peripheral was a source of exiting a * low-leakage power mode. To clear the flag, follow the internal peripheral flag * clearing mechanism. * * Values: * - 0 - Module 3 input was not a wakeup source * - 1 - Module 3 input was a wakeup source */ /*@{*/ #define BP_LLWU_F3_MWUF3 (3U) /*!< Bit position for LLWU_F3_MWUF3. */ #define BM_LLWU_F3_MWUF3 (0x08U) /*!< Bit mask for LLWU_F3_MWUF3. */ #define BS_LLWU_F3_MWUF3 (1U) /*!< Bit field size in bits for LLWU_F3_MWUF3. */ /*! @brief Read current value of the LLWU_F3_MWUF3 field. */ #define BR_LLWU_F3_MWUF3(x) (BITBAND_ACCESS8(HW_LLWU_F3_ADDR(x), BP_LLWU_F3_MWUF3)) /*@}*/ /*! * @name Register LLWU_F3, field MWUF4[4] (RO) * * Indicates that an enabled internal peripheral was a source of exiting a * low-leakage power mode. To clear the flag, follow the internal peripheral flag * clearing mechanism. * * Values: * - 0 - Module 4 input was not a wakeup source * - 1 - Module 4 input was a wakeup source */ /*@{*/ #define BP_LLWU_F3_MWUF4 (4U) /*!< Bit position for LLWU_F3_MWUF4. */ #define BM_LLWU_F3_MWUF4 (0x10U) /*!< Bit mask for LLWU_F3_MWUF4. */ #define BS_LLWU_F3_MWUF4 (1U) /*!< Bit field size in bits for LLWU_F3_MWUF4. */ /*! @brief Read current value of the LLWU_F3_MWUF4 field. */ #define BR_LLWU_F3_MWUF4(x) (BITBAND_ACCESS8(HW_LLWU_F3_ADDR(x), BP_LLWU_F3_MWUF4)) /*@}*/ /*! * @name Register LLWU_F3, field MWUF5[5] (RO) * * Indicates that an enabled internal peripheral was a source of exiting a * low-leakage power mode. To clear the flag, follow the internal peripheral flag * clearing mechanism. * * Values: * - 0 - Module 5 input was not a wakeup source * - 1 - Module 5 input was a wakeup source */ /*@{*/ #define BP_LLWU_F3_MWUF5 (5U) /*!< Bit position for LLWU_F3_MWUF5. */ #define BM_LLWU_F3_MWUF5 (0x20U) /*!< Bit mask for LLWU_F3_MWUF5. */ #define BS_LLWU_F3_MWUF5 (1U) /*!< Bit field size in bits for LLWU_F3_MWUF5. */ /*! @brief Read current value of the LLWU_F3_MWUF5 field. */ #define BR_LLWU_F3_MWUF5(x) (BITBAND_ACCESS8(HW_LLWU_F3_ADDR(x), BP_LLWU_F3_MWUF5)) /*@}*/ /*! * @name Register LLWU_F3, field MWUF6[6] (RO) * * Indicates that an enabled internal peripheral was a source of exiting a * low-leakage power mode. To clear the flag, follow the internal peripheral flag * clearing mechanism. * * Values: * - 0 - Module 6 input was not a wakeup source * - 1 - Module 6 input was a wakeup source */ /*@{*/ #define BP_LLWU_F3_MWUF6 (6U) /*!< Bit position for LLWU_F3_MWUF6. */ #define BM_LLWU_F3_MWUF6 (0x40U) /*!< Bit mask for LLWU_F3_MWUF6. */ #define BS_LLWU_F3_MWUF6 (1U) /*!< Bit field size in bits for LLWU_F3_MWUF6. */ /*! @brief Read current value of the LLWU_F3_MWUF6 field. */ #define BR_LLWU_F3_MWUF6(x) (BITBAND_ACCESS8(HW_LLWU_F3_ADDR(x), BP_LLWU_F3_MWUF6)) /*@}*/ /*! * @name Register LLWU_F3, field MWUF7[7] (RO) * * Indicates that an enabled internal peripheral was a source of exiting a * low-leakage power mode. To clear the flag, follow the internal peripheral flag * clearing mechanism. * * Values: * - 0 - Module 7 input was not a wakeup source * - 1 - Module 7 input was a wakeup source */ /*@{*/ #define BP_LLWU_F3_MWUF7 (7U) /*!< Bit position for LLWU_F3_MWUF7. */ #define BM_LLWU_F3_MWUF7 (0x80U) /*!< Bit mask for LLWU_F3_MWUF7. */ #define BS_LLWU_F3_MWUF7 (1U) /*!< Bit field size in bits for LLWU_F3_MWUF7. */ /*! @brief Read current value of the LLWU_F3_MWUF7 field. */ #define BR_LLWU_F3_MWUF7(x) (BITBAND_ACCESS8(HW_LLWU_F3_ADDR(x), BP_LLWU_F3_MWUF7)) /*@}*/ /******************************************************************************* * HW_LLWU_FILT1 - LLWU Pin Filter 1 register ******************************************************************************/ /*! * @brief HW_LLWU_FILT1 - LLWU Pin Filter 1 register (RW) * * Reset value: 0x00U * * LLWU_FILT1 is a control and status register that is used to enable/disable * the digital filter 1 features for an external pin. This register is reset on * Chip Reset not VLLS and by reset types that trigger Chip Reset not VLLS. It is * unaffected by reset types that do not trigger Chip Reset not VLLS. See the * IntroductionInformation found here describes the registers of the Reset Control * Module (RCM). The RCM implements many of the reset functions for the chip. See * the chip's reset chapter for more information. details for more information. */ typedef union _hw_llwu_filt1 { uint8_t U; struct _hw_llwu_filt1_bitfields { uint8_t FILTSEL : 4; /*!< [3:0] Filter Pin Select */ uint8_t RESERVED0 : 1; /*!< [4] */ uint8_t FILTE : 2; /*!< [6:5] Digital Filter On External Pin */ uint8_t FILTF : 1; /*!< [7] Filter Detect Flag */ } B; } hw_llwu_filt1_t; /*! * @name Constants and macros for entire LLWU_FILT1 register */ /*@{*/ #define HW_LLWU_FILT1_ADDR(x) ((x) + 0x8U) #define HW_LLWU_FILT1(x) (*(__IO hw_llwu_filt1_t *) HW_LLWU_FILT1_ADDR(x)) #define HW_LLWU_FILT1_RD(x) (HW_LLWU_FILT1(x).U) #define HW_LLWU_FILT1_WR(x, v) (HW_LLWU_FILT1(x).U = (v)) #define HW_LLWU_FILT1_SET(x, v) (HW_LLWU_FILT1_WR(x, HW_LLWU_FILT1_RD(x) | (v))) #define HW_LLWU_FILT1_CLR(x, v) (HW_LLWU_FILT1_WR(x, HW_LLWU_FILT1_RD(x) & ~(v))) #define HW_LLWU_FILT1_TOG(x, v) (HW_LLWU_FILT1_WR(x, HW_LLWU_FILT1_RD(x) ^ (v))) /*@}*/ /* * Constants & macros for individual LLWU_FILT1 bitfields */ /*! * @name Register LLWU_FILT1, field FILTSEL[3:0] (RW) * * Selects 1 out of the 16 wakeup pins to be muxed into the filter. * * Values: * - 0000 - Select LLWU_P0 for filter * - 1111 - Select LLWU_P15 for filter */ /*@{*/ #define BP_LLWU_FILT1_FILTSEL (0U) /*!< Bit position for LLWU_FILT1_FILTSEL. */ #define BM_LLWU_FILT1_FILTSEL (0x0FU) /*!< Bit mask for LLWU_FILT1_FILTSEL. */ #define BS_LLWU_FILT1_FILTSEL (4U) /*!< Bit field size in bits for LLWU_FILT1_FILTSEL. */ /*! @brief Read current value of the LLWU_FILT1_FILTSEL field. */ #define BR_LLWU_FILT1_FILTSEL(x) (HW_LLWU_FILT1(x).B.FILTSEL) /*! @brief Format value for bitfield LLWU_FILT1_FILTSEL. */ #define BF_LLWU_FILT1_FILTSEL(v) ((uint8_t)((uint8_t)(v) << BP_LLWU_FILT1_FILTSEL) & BM_LLWU_FILT1_FILTSEL) /*! @brief Set the FILTSEL field to a new value. */ #define BW_LLWU_FILT1_FILTSEL(x, v) (HW_LLWU_FILT1_WR(x, (HW_LLWU_FILT1_RD(x) & ~BM_LLWU_FILT1_FILTSEL) | BF_LLWU_FILT1_FILTSEL(v))) /*@}*/ /*! * @name Register LLWU_FILT1, field FILTE[6:5] (RW) * * Controls the digital filter options for the external pin detect. * * Values: * - 00 - Filter disabled * - 01 - Filter posedge detect enabled * - 10 - Filter negedge detect enabled * - 11 - Filter any edge detect enabled */ /*@{*/ #define BP_LLWU_FILT1_FILTE (5U) /*!< Bit position for LLWU_FILT1_FILTE. */ #define BM_LLWU_FILT1_FILTE (0x60U) /*!< Bit mask for LLWU_FILT1_FILTE. */ #define BS_LLWU_FILT1_FILTE (2U) /*!< Bit field size in bits for LLWU_FILT1_FILTE. */ /*! @brief Read current value of the LLWU_FILT1_FILTE field. */ #define BR_LLWU_FILT1_FILTE(x) (HW_LLWU_FILT1(x).B.FILTE) /*! @brief Format value for bitfield LLWU_FILT1_FILTE. */ #define BF_LLWU_FILT1_FILTE(v) ((uint8_t)((uint8_t)(v) << BP_LLWU_FILT1_FILTE) & BM_LLWU_FILT1_FILTE) /*! @brief Set the FILTE field to a new value. */ #define BW_LLWU_FILT1_FILTE(x, v) (HW_LLWU_FILT1_WR(x, (HW_LLWU_FILT1_RD(x) & ~BM_LLWU_FILT1_FILTE) | BF_LLWU_FILT1_FILTE(v))) /*@}*/ /*! * @name Register LLWU_FILT1, field FILTF[7] (W1C) * * Indicates that the filtered external wakeup pin, selected by FILTSEL, was a * source of exiting a low-leakage power mode. To clear the flag write a one to * FILTF. * * Values: * - 0 - Pin Filter 1 was not a wakeup source * - 1 - Pin Filter 1 was a wakeup source */ /*@{*/ #define BP_LLWU_FILT1_FILTF (7U) /*!< Bit position for LLWU_FILT1_FILTF. */ #define BM_LLWU_FILT1_FILTF (0x80U) /*!< Bit mask for LLWU_FILT1_FILTF. */ #define BS_LLWU_FILT1_FILTF (1U) /*!< Bit field size in bits for LLWU_FILT1_FILTF. */ /*! @brief Read current value of the LLWU_FILT1_FILTF field. */ #define BR_LLWU_FILT1_FILTF(x) (BITBAND_ACCESS8(HW_LLWU_FILT1_ADDR(x), BP_LLWU_FILT1_FILTF)) /*! @brief Format value for bitfield LLWU_FILT1_FILTF. */ #define BF_LLWU_FILT1_FILTF(v) ((uint8_t)((uint8_t)(v) << BP_LLWU_FILT1_FILTF) & BM_LLWU_FILT1_FILTF) /*! @brief Set the FILTF field to a new value. */ #define BW_LLWU_FILT1_FILTF(x, v) (BITBAND_ACCESS8(HW_LLWU_FILT1_ADDR(x), BP_LLWU_FILT1_FILTF) = (v)) /*@}*/ /******************************************************************************* * HW_LLWU_FILT2 - LLWU Pin Filter 2 register ******************************************************************************/ /*! * @brief HW_LLWU_FILT2 - LLWU Pin Filter 2 register (RW) * * Reset value: 0x00U * * LLWU_FILT2 is a control and status register that is used to enable/disable * the digital filter 2 features for an external pin. This register is reset on * Chip Reset not VLLS and by reset types that trigger Chip Reset not VLLS. It is * unaffected by reset types that do not trigger Chip Reset not VLLS. See the * IntroductionInformation found here describes the registers of the Reset Control * Module (RCM). The RCM implements many of the reset functions for the chip. See * the chip's reset chapter for more information. details for more information. */ typedef union _hw_llwu_filt2 { uint8_t U; struct _hw_llwu_filt2_bitfields { uint8_t FILTSEL : 4; /*!< [3:0] Filter Pin Select */ uint8_t RESERVED0 : 1; /*!< [4] */ uint8_t FILTE : 2; /*!< [6:5] Digital Filter On External Pin */ uint8_t FILTF : 1; /*!< [7] Filter Detect Flag */ } B; } hw_llwu_filt2_t; /*! * @name Constants and macros for entire LLWU_FILT2 register */ /*@{*/ #define HW_LLWU_FILT2_ADDR(x) ((x) + 0x9U) #define HW_LLWU_FILT2(x) (*(__IO hw_llwu_filt2_t *) HW_LLWU_FILT2_ADDR(x)) #define HW_LLWU_FILT2_RD(x) (HW_LLWU_FILT2(x).U) #define HW_LLWU_FILT2_WR(x, v) (HW_LLWU_FILT2(x).U = (v)) #define HW_LLWU_FILT2_SET(x, v) (HW_LLWU_FILT2_WR(x, HW_LLWU_FILT2_RD(x) | (v))) #define HW_LLWU_FILT2_CLR(x, v) (HW_LLWU_FILT2_WR(x, HW_LLWU_FILT2_RD(x) & ~(v))) #define HW_LLWU_FILT2_TOG(x, v) (HW_LLWU_FILT2_WR(x, HW_LLWU_FILT2_RD(x) ^ (v))) /*@}*/ /* * Constants & macros for individual LLWU_FILT2 bitfields */ /*! * @name Register LLWU_FILT2, field FILTSEL[3:0] (RW) * * Selects 1 out of the 16 wakeup pins to be muxed into the filter. * * Values: * - 0000 - Select LLWU_P0 for filter * - 1111 - Select LLWU_P15 for filter */ /*@{*/ #define BP_LLWU_FILT2_FILTSEL (0U) /*!< Bit position for LLWU_FILT2_FILTSEL. */ #define BM_LLWU_FILT2_FILTSEL (0x0FU) /*!< Bit mask for LLWU_FILT2_FILTSEL. */ #define BS_LLWU_FILT2_FILTSEL (4U) /*!< Bit field size in bits for LLWU_FILT2_FILTSEL. */ /*! @brief Read current value of the LLWU_FILT2_FILTSEL field. */ #define BR_LLWU_FILT2_FILTSEL(x) (HW_LLWU_FILT2(x).B.FILTSEL) /*! @brief Format value for bitfield LLWU_FILT2_FILTSEL. */ #define BF_LLWU_FILT2_FILTSEL(v) ((uint8_t)((uint8_t)(v) << BP_LLWU_FILT2_FILTSEL) & BM_LLWU_FILT2_FILTSEL) /*! @brief Set the FILTSEL field to a new value. */ #define BW_LLWU_FILT2_FILTSEL(x, v) (HW_LLWU_FILT2_WR(x, (HW_LLWU_FILT2_RD(x) & ~BM_LLWU_FILT2_FILTSEL) | BF_LLWU_FILT2_FILTSEL(v))) /*@}*/ /*! * @name Register LLWU_FILT2, field FILTE[6:5] (RW) * * Controls the digital filter options for the external pin detect. * * Values: * - 00 - Filter disabled * - 01 - Filter posedge detect enabled * - 10 - Filter negedge detect enabled * - 11 - Filter any edge detect enabled */ /*@{*/ #define BP_LLWU_FILT2_FILTE (5U) /*!< Bit position for LLWU_FILT2_FILTE. */ #define BM_LLWU_FILT2_FILTE (0x60U) /*!< Bit mask for LLWU_FILT2_FILTE. */ #define BS_LLWU_FILT2_FILTE (2U) /*!< Bit field size in bits for LLWU_FILT2_FILTE. */ /*! @brief Read current value of the LLWU_FILT2_FILTE field. */ #define BR_LLWU_FILT2_FILTE(x) (HW_LLWU_FILT2(x).B.FILTE) /*! @brief Format value for bitfield LLWU_FILT2_FILTE. */ #define BF_LLWU_FILT2_FILTE(v) ((uint8_t)((uint8_t)(v) << BP_LLWU_FILT2_FILTE) & BM_LLWU_FILT2_FILTE) /*! @brief Set the FILTE field to a new value. */ #define BW_LLWU_FILT2_FILTE(x, v) (HW_LLWU_FILT2_WR(x, (HW_LLWU_FILT2_RD(x) & ~BM_LLWU_FILT2_FILTE) | BF_LLWU_FILT2_FILTE(v))) /*@}*/ /*! * @name Register LLWU_FILT2, field FILTF[7] (W1C) * * Indicates that the filtered external wakeup pin, selected by FILTSEL, was a * source of exiting a low-leakage power mode. To clear the flag write a one to * FILTF. * * Values: * - 0 - Pin Filter 2 was not a wakeup source * - 1 - Pin Filter 2 was a wakeup source */ /*@{*/ #define BP_LLWU_FILT2_FILTF (7U) /*!< Bit position for LLWU_FILT2_FILTF. */ #define BM_LLWU_FILT2_FILTF (0x80U) /*!< Bit mask for LLWU_FILT2_FILTF. */ #define BS_LLWU_FILT2_FILTF (1U) /*!< Bit field size in bits for LLWU_FILT2_FILTF. */ /*! @brief Read current value of the LLWU_FILT2_FILTF field. */ #define BR_LLWU_FILT2_FILTF(x) (BITBAND_ACCESS8(HW_LLWU_FILT2_ADDR(x), BP_LLWU_FILT2_FILTF)) /*! @brief Format value for bitfield LLWU_FILT2_FILTF. */ #define BF_LLWU_FILT2_FILTF(v) ((uint8_t)((uint8_t)(v) << BP_LLWU_FILT2_FILTF) & BM_LLWU_FILT2_FILTF) /*! @brief Set the FILTF field to a new value. */ #define BW_LLWU_FILT2_FILTF(x, v) (BITBAND_ACCESS8(HW_LLWU_FILT2_ADDR(x), BP_LLWU_FILT2_FILTF) = (v)) /*@}*/ /******************************************************************************* * HW_LLWU_RST - LLWU Reset Enable register ******************************************************************************/ /*! * @brief HW_LLWU_RST - LLWU Reset Enable register (RW) * * Reset value: 0x02U * * LLWU_RST is a control register that is used to enable/disable the digital * filter for the external pin detect and RESET pin. This register is reset on Chip * Reset not VLLS and by reset types that trigger Chip Reset not VLLS. It is * unaffected by reset types that do not trigger Chip Reset not VLLS. See the * IntroductionInformation found here describes the registers of the Reset Control * Module (RCM). The RCM implements many of the reset functions for the chip. See the * chip's reset chapter for more information. details for more information. */ typedef union _hw_llwu_rst { uint8_t U; struct _hw_llwu_rst_bitfields { uint8_t RSTFILT : 1; /*!< [0] Digital Filter On RESET Pin */ uint8_t LLRSTE : 1; /*!< [1] Low-Leakage Mode RESET Enable */ uint8_t RESERVED0 : 6; /*!< [7:2] */ } B; } hw_llwu_rst_t; /*! * @name Constants and macros for entire LLWU_RST register */ /*@{*/ #define HW_LLWU_RST_ADDR(x) ((x) + 0xAU) #define HW_LLWU_RST(x) (*(__IO hw_llwu_rst_t *) HW_LLWU_RST_ADDR(x)) #define HW_LLWU_RST_RD(x) (HW_LLWU_RST(x).U) #define HW_LLWU_RST_WR(x, v) (HW_LLWU_RST(x).U = (v)) #define HW_LLWU_RST_SET(x, v) (HW_LLWU_RST_WR(x, HW_LLWU_RST_RD(x) | (v))) #define HW_LLWU_RST_CLR(x, v) (HW_LLWU_RST_WR(x, HW_LLWU_RST_RD(x) & ~(v))) #define HW_LLWU_RST_TOG(x, v) (HW_LLWU_RST_WR(x, HW_LLWU_RST_RD(x) ^ (v))) /*@}*/ /* * Constants & macros for individual LLWU_RST bitfields */ /*! * @name Register LLWU_RST, field RSTFILT[0] (RW) * * Enables the digital filter for the RESET pin during LLS, VLLS3, VLLS2, or * VLLS1 modes. * * Values: * - 0 - Filter not enabled * - 1 - Filter enabled */ /*@{*/ #define BP_LLWU_RST_RSTFILT (0U) /*!< Bit position for LLWU_RST_RSTFILT. */ #define BM_LLWU_RST_RSTFILT (0x01U) /*!< Bit mask for LLWU_RST_RSTFILT. */ #define BS_LLWU_RST_RSTFILT (1U) /*!< Bit field size in bits for LLWU_RST_RSTFILT. */ /*! @brief Read current value of the LLWU_RST_RSTFILT field. */ #define BR_LLWU_RST_RSTFILT(x) (BITBAND_ACCESS8(HW_LLWU_RST_ADDR(x), BP_LLWU_RST_RSTFILT)) /*! @brief Format value for bitfield LLWU_RST_RSTFILT. */ #define BF_LLWU_RST_RSTFILT(v) ((uint8_t)((uint8_t)(v) << BP_LLWU_RST_RSTFILT) & BM_LLWU_RST_RSTFILT) /*! @brief Set the RSTFILT field to a new value. */ #define BW_LLWU_RST_RSTFILT(x, v) (BITBAND_ACCESS8(HW_LLWU_RST_ADDR(x), BP_LLWU_RST_RSTFILT) = (v)) /*@}*/ /*! * @name Register LLWU_RST, field LLRSTE[1] (RW) * * This bit must be set to allow the device to be reset while in a low-leakage * power mode. On devices where Reset is not a dedicated pin, the RESET pin must * also be enabled in the explicit port mux control. * * Values: * - 0 - RESET pin not enabled as a leakage mode exit source * - 1 - RESET pin enabled as a low leakage mode exit source */ /*@{*/ #define BP_LLWU_RST_LLRSTE (1U) /*!< Bit position for LLWU_RST_LLRSTE. */ #define BM_LLWU_RST_LLRSTE (0x02U) /*!< Bit mask for LLWU_RST_LLRSTE. */ #define BS_LLWU_RST_LLRSTE (1U) /*!< Bit field size in bits for LLWU_RST_LLRSTE. */ /*! @brief Read current value of the LLWU_RST_LLRSTE field. */ #define BR_LLWU_RST_LLRSTE(x) (BITBAND_ACCESS8(HW_LLWU_RST_ADDR(x), BP_LLWU_RST_LLRSTE)) /*! @brief Format value for bitfield LLWU_RST_LLRSTE. */ #define BF_LLWU_RST_LLRSTE(v) ((uint8_t)((uint8_t)(v) << BP_LLWU_RST_LLRSTE) & BM_LLWU_RST_LLRSTE) /*! @brief Set the LLRSTE field to a new value. */ #define BW_LLWU_RST_LLRSTE(x, v) (BITBAND_ACCESS8(HW_LLWU_RST_ADDR(x), BP_LLWU_RST_LLRSTE) = (v)) /*@}*/ /******************************************************************************* * hw_llwu_t - module struct ******************************************************************************/ /*! * @brief All LLWU module registers. */ #pragma pack(1) typedef struct _hw_llwu { __IO hw_llwu_pe1_t PE1; /*!< [0x0] LLWU Pin Enable 1 register */ __IO hw_llwu_pe2_t PE2; /*!< [0x1] LLWU Pin Enable 2 register */ __IO hw_llwu_pe3_t PE3; /*!< [0x2] LLWU Pin Enable 3 register */ __IO hw_llwu_pe4_t PE4; /*!< [0x3] LLWU Pin Enable 4 register */ __IO hw_llwu_me_t ME; /*!< [0x4] LLWU Module Enable register */ __IO hw_llwu_f1_t F1; /*!< [0x5] LLWU Flag 1 register */ __IO hw_llwu_f2_t F2; /*!< [0x6] LLWU Flag 2 register */ __I hw_llwu_f3_t F3; /*!< [0x7] LLWU Flag 3 register */ __IO hw_llwu_filt1_t FILT1; /*!< [0x8] LLWU Pin Filter 1 register */ __IO hw_llwu_filt2_t FILT2; /*!< [0x9] LLWU Pin Filter 2 register */ __IO hw_llwu_rst_t RST; /*!< [0xA] LLWU Reset Enable register */ } hw_llwu_t; #pragma pack() /*! @brief Macro to access all LLWU registers. */ /*! @param x LLWU module instance base address. */ /*! @return Reference (not a pointer) to the registers struct. To get a pointer to the struct, * use the '&' operator, like &HW_LLWU(LLWU_BASE). */ #define HW_LLWU(x) (*(hw_llwu_t *)(x)) #endif /* __HW_LLWU_REGISTERS_H__ */ /* EOF */ ================================================ FILE: Zelig/mbed/TARGET_K64F/TARGET_Freescale/TARGET_KPSDK_MCUS/TARGET_MCU_K64F/device/device/MK64F12/MK64F12_lptmr.h ================================================ /* ** ################################################################### ** Compilers: Keil ARM C/C++ Compiler ** Freescale C/C++ for Embedded ARM ** GNU C Compiler ** IAR ANSI C/C++ Compiler for ARM ** ** Reference manual: K64P144M120SF5RM, Rev.2, January 2014 ** Version: rev. 2.5, 2014-02-10 ** Build: b140604 ** ** Abstract: ** Extension to the CMSIS register access layer header. ** ** Copyright (c) 2014 Freescale Semiconductor, Inc. ** All rights reserved. ** ** Redistribution and use in source and binary forms, with or without modification, ** are permitted provided that the following conditions are met: ** ** o Redistributions of source code must retain the above copyright notice, this list ** of conditions and the following disclaimer. ** ** o Redistributions in binary form must reproduce the above copyright notice, this ** list of conditions and the following disclaimer in the documentation and/or ** other materials provided with the distribution. ** ** o Neither the name of Freescale Semiconductor, Inc. nor the names of its ** contributors may be used to endorse or promote products derived from this ** software without specific prior written permission. ** ** THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ** ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED ** WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE ** DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT 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. ** ** http: www.freescale.com ** mail: support@freescale.com ** ** Revisions: ** - rev. 1.0 (2013-08-12) ** Initial version. ** - rev. 2.0 (2013-10-29) ** Register accessor macros added to the memory map. ** Symbols for Processor Expert memory map compatibility added to the memory map. ** Startup file for gcc has been updated according to CMSIS 3.2. ** System initialization updated. ** MCG - registers updated. ** PORTA, PORTB, PORTC, PORTE - registers for digital filter removed. ** - rev. 2.1 (2013-10-30) ** Definition of BITBAND macros updated to support peripherals with 32-bit acces disabled. ** - rev. 2.2 (2013-12-09) ** DMA - EARS register removed. ** AIPS0, AIPS1 - MPRA register updated. ** - rev. 2.3 (2014-01-24) ** Update according to reference manual rev. 2 ** ENET, MCG, MCM, SIM, USB - registers updated ** - rev. 2.4 (2014-02-10) ** The declaration of clock configurations has been moved to separate header file system_MK64F12.h ** Update of SystemInit() and SystemCoreClockUpdate() functions. ** - rev. 2.5 (2014-02-10) ** The declaration of clock configurations has been moved to separate header file system_MK64F12.h ** Update of SystemInit() and SystemCoreClockUpdate() functions. ** Module access macro module_BASES replaced by module_BASE_PTRS. ** ** ################################################################### */ /* * WARNING! DO NOT EDIT THIS FILE DIRECTLY! * * This file was generated automatically and any changes may be lost. */ #ifndef __HW_LPTMR_REGISTERS_H__ #define __HW_LPTMR_REGISTERS_H__ #include "MK64F12.h" #include "fsl_bitaccess.h" /* * MK64F12 LPTMR * * Low Power Timer * * Registers defined in this header file: * - HW_LPTMR_CSR - Low Power Timer Control Status Register * - HW_LPTMR_PSR - Low Power Timer Prescale Register * - HW_LPTMR_CMR - Low Power Timer Compare Register * - HW_LPTMR_CNR - Low Power Timer Counter Register * * - hw_lptmr_t - Struct containing all module registers. */ #define HW_LPTMR_INSTANCE_COUNT (1U) /*!< Number of instances of the LPTMR module. */ /******************************************************************************* * HW_LPTMR_CSR - Low Power Timer Control Status Register ******************************************************************************/ /*! * @brief HW_LPTMR_CSR - Low Power Timer Control Status Register (RW) * * Reset value: 0x00000000U */ typedef union _hw_lptmr_csr { uint32_t U; struct _hw_lptmr_csr_bitfields { uint32_t TEN : 1; /*!< [0] Timer Enable */ uint32_t TMS : 1; /*!< [1] Timer Mode Select */ uint32_t TFC : 1; /*!< [2] Timer Free-Running Counter */ uint32_t TPP : 1; /*!< [3] Timer Pin Polarity */ uint32_t TPS : 2; /*!< [5:4] Timer Pin Select */ uint32_t TIE : 1; /*!< [6] Timer Interrupt Enable */ uint32_t TCF : 1; /*!< [7] Timer Compare Flag */ uint32_t RESERVED0 : 24; /*!< [31:8] */ } B; } hw_lptmr_csr_t; /*! * @name Constants and macros for entire LPTMR_CSR register */ /*@{*/ #define HW_LPTMR_CSR_ADDR(x) ((x) + 0x0U) #define HW_LPTMR_CSR(x) (*(__IO hw_lptmr_csr_t *) HW_LPTMR_CSR_ADDR(x)) #define HW_LPTMR_CSR_RD(x) (HW_LPTMR_CSR(x).U) #define HW_LPTMR_CSR_WR(x, v) (HW_LPTMR_CSR(x).U = (v)) #define HW_LPTMR_CSR_SET(x, v) (HW_LPTMR_CSR_WR(x, HW_LPTMR_CSR_RD(x) | (v))) #define HW_LPTMR_CSR_CLR(x, v) (HW_LPTMR_CSR_WR(x, HW_LPTMR_CSR_RD(x) & ~(v))) #define HW_LPTMR_CSR_TOG(x, v) (HW_LPTMR_CSR_WR(x, HW_LPTMR_CSR_RD(x) ^ (v))) /*@}*/ /* * Constants & macros for individual LPTMR_CSR bitfields */ /*! * @name Register LPTMR_CSR, field TEN[0] (RW) * * When TEN is clear, it resets the LPTMR internal logic, including the CNR and * TCF. When TEN is set, the LPTMR is enabled. While writing 1 to this field, * CSR[5:1] must not be altered. * * Values: * - 0 - LPTMR is disabled and internal logic is reset. * - 1 - LPTMR is enabled. */ /*@{*/ #define BP_LPTMR_CSR_TEN (0U) /*!< Bit position for LPTMR_CSR_TEN. */ #define BM_LPTMR_CSR_TEN (0x00000001U) /*!< Bit mask for LPTMR_CSR_TEN. */ #define BS_LPTMR_CSR_TEN (1U) /*!< Bit field size in bits for LPTMR_CSR_TEN. */ /*! @brief Read current value of the LPTMR_CSR_TEN field. */ #define BR_LPTMR_CSR_TEN(x) (BITBAND_ACCESS32(HW_LPTMR_CSR_ADDR(x), BP_LPTMR_CSR_TEN)) /*! @brief Format value for bitfield LPTMR_CSR_TEN. */ #define BF_LPTMR_CSR_TEN(v) ((uint32_t)((uint32_t)(v) << BP_LPTMR_CSR_TEN) & BM_LPTMR_CSR_TEN) /*! @brief Set the TEN field to a new value. */ #define BW_LPTMR_CSR_TEN(x, v) (BITBAND_ACCESS32(HW_LPTMR_CSR_ADDR(x), BP_LPTMR_CSR_TEN) = (v)) /*@}*/ /*! * @name Register LPTMR_CSR, field TMS[1] (RW) * * Configures the mode of the LPTMR. TMS must be altered only when the LPTMR is * disabled. * * Values: * - 0 - Time Counter mode. * - 1 - Pulse Counter mode. */ /*@{*/ #define BP_LPTMR_CSR_TMS (1U) /*!< Bit position for LPTMR_CSR_TMS. */ #define BM_LPTMR_CSR_TMS (0x00000002U) /*!< Bit mask for LPTMR_CSR_TMS. */ #define BS_LPTMR_CSR_TMS (1U) /*!< Bit field size in bits for LPTMR_CSR_TMS. */ /*! @brief Read current value of the LPTMR_CSR_TMS field. */ #define BR_LPTMR_CSR_TMS(x) (BITBAND_ACCESS32(HW_LPTMR_CSR_ADDR(x), BP_LPTMR_CSR_TMS)) /*! @brief Format value for bitfield LPTMR_CSR_TMS. */ #define BF_LPTMR_CSR_TMS(v) ((uint32_t)((uint32_t)(v) << BP_LPTMR_CSR_TMS) & BM_LPTMR_CSR_TMS) /*! @brief Set the TMS field to a new value. */ #define BW_LPTMR_CSR_TMS(x, v) (BITBAND_ACCESS32(HW_LPTMR_CSR_ADDR(x), BP_LPTMR_CSR_TMS) = (v)) /*@}*/ /*! * @name Register LPTMR_CSR, field TFC[2] (RW) * * When clear, TFC configures the CNR to reset whenever TCF is set. When set, * TFC configures the CNR to reset on overflow. TFC must be altered only when the * LPTMR is disabled. * * Values: * - 0 - CNR is reset whenever TCF is set. * - 1 - CNR is reset on overflow. */ /*@{*/ #define BP_LPTMR_CSR_TFC (2U) /*!< Bit position for LPTMR_CSR_TFC. */ #define BM_LPTMR_CSR_TFC (0x00000004U) /*!< Bit mask for LPTMR_CSR_TFC. */ #define BS_LPTMR_CSR_TFC (1U) /*!< Bit field size in bits for LPTMR_CSR_TFC. */ /*! @brief Read current value of the LPTMR_CSR_TFC field. */ #define BR_LPTMR_CSR_TFC(x) (BITBAND_ACCESS32(HW_LPTMR_CSR_ADDR(x), BP_LPTMR_CSR_TFC)) /*! @brief Format value for bitfield LPTMR_CSR_TFC. */ #define BF_LPTMR_CSR_TFC(v) ((uint32_t)((uint32_t)(v) << BP_LPTMR_CSR_TFC) & BM_LPTMR_CSR_TFC) /*! @brief Set the TFC field to a new value. */ #define BW_LPTMR_CSR_TFC(x, v) (BITBAND_ACCESS32(HW_LPTMR_CSR_ADDR(x), BP_LPTMR_CSR_TFC) = (v)) /*@}*/ /*! * @name Register LPTMR_CSR, field TPP[3] (RW) * * Configures the polarity of the input source in Pulse Counter mode. TPP must * be changed only when the LPTMR is disabled. * * Values: * - 0 - Pulse Counter input source is active-high, and the CNR will increment * on the rising-edge. * - 1 - Pulse Counter input source is active-low, and the CNR will increment on * the falling-edge. */ /*@{*/ #define BP_LPTMR_CSR_TPP (3U) /*!< Bit position for LPTMR_CSR_TPP. */ #define BM_LPTMR_CSR_TPP (0x00000008U) /*!< Bit mask for LPTMR_CSR_TPP. */ #define BS_LPTMR_CSR_TPP (1U) /*!< Bit field size in bits for LPTMR_CSR_TPP. */ /*! @brief Read current value of the LPTMR_CSR_TPP field. */ #define BR_LPTMR_CSR_TPP(x) (BITBAND_ACCESS32(HW_LPTMR_CSR_ADDR(x), BP_LPTMR_CSR_TPP)) /*! @brief Format value for bitfield LPTMR_CSR_TPP. */ #define BF_LPTMR_CSR_TPP(v) ((uint32_t)((uint32_t)(v) << BP_LPTMR_CSR_TPP) & BM_LPTMR_CSR_TPP) /*! @brief Set the TPP field to a new value. */ #define BW_LPTMR_CSR_TPP(x, v) (BITBAND_ACCESS32(HW_LPTMR_CSR_ADDR(x), BP_LPTMR_CSR_TPP) = (v)) /*@}*/ /*! * @name Register LPTMR_CSR, field TPS[5:4] (RW) * * Configures the input source to be used in Pulse Counter mode. TPS must be * altered only when the LPTMR is disabled. The input connections vary by device. * See the chip configuration details for information on the connections to these * inputs. * * Values: * - 00 - Pulse counter input 0 is selected. * - 01 - Pulse counter input 1 is selected. * - 10 - Pulse counter input 2 is selected. * - 11 - Pulse counter input 3 is selected. */ /*@{*/ #define BP_LPTMR_CSR_TPS (4U) /*!< Bit position for LPTMR_CSR_TPS. */ #define BM_LPTMR_CSR_TPS (0x00000030U) /*!< Bit mask for LPTMR_CSR_TPS. */ #define BS_LPTMR_CSR_TPS (2U) /*!< Bit field size in bits for LPTMR_CSR_TPS. */ /*! @brief Read current value of the LPTMR_CSR_TPS field. */ #define BR_LPTMR_CSR_TPS(x) (HW_LPTMR_CSR(x).B.TPS) /*! @brief Format value for bitfield LPTMR_CSR_TPS. */ #define BF_LPTMR_CSR_TPS(v) ((uint32_t)((uint32_t)(v) << BP_LPTMR_CSR_TPS) & BM_LPTMR_CSR_TPS) /*! @brief Set the TPS field to a new value. */ #define BW_LPTMR_CSR_TPS(x, v) (HW_LPTMR_CSR_WR(x, (HW_LPTMR_CSR_RD(x) & ~BM_LPTMR_CSR_TPS) | BF_LPTMR_CSR_TPS(v))) /*@}*/ /*! * @name Register LPTMR_CSR, field TIE[6] (RW) * * When TIE is set, the LPTMR Interrupt is generated whenever TCF is also set. * * Values: * - 0 - Timer interrupt disabled. * - 1 - Timer interrupt enabled. */ /*@{*/ #define BP_LPTMR_CSR_TIE (6U) /*!< Bit position for LPTMR_CSR_TIE. */ #define BM_LPTMR_CSR_TIE (0x00000040U) /*!< Bit mask for LPTMR_CSR_TIE. */ #define BS_LPTMR_CSR_TIE (1U) /*!< Bit field size in bits for LPTMR_CSR_TIE. */ /*! @brief Read current value of the LPTMR_CSR_TIE field. */ #define BR_LPTMR_CSR_TIE(x) (BITBAND_ACCESS32(HW_LPTMR_CSR_ADDR(x), BP_LPTMR_CSR_TIE)) /*! @brief Format value for bitfield LPTMR_CSR_TIE. */ #define BF_LPTMR_CSR_TIE(v) ((uint32_t)((uint32_t)(v) << BP_LPTMR_CSR_TIE) & BM_LPTMR_CSR_TIE) /*! @brief Set the TIE field to a new value. */ #define BW_LPTMR_CSR_TIE(x, v) (BITBAND_ACCESS32(HW_LPTMR_CSR_ADDR(x), BP_LPTMR_CSR_TIE) = (v)) /*@}*/ /*! * @name Register LPTMR_CSR, field TCF[7] (W1C) * * TCF is set when the LPTMR is enabled and the CNR equals the CMR and * increments. TCF is cleared when the LPTMR is disabled or a logic 1 is written to it. * * Values: * - 0 - The value of CNR is not equal to CMR and increments. * - 1 - The value of CNR is equal to CMR and increments. */ /*@{*/ #define BP_LPTMR_CSR_TCF (7U) /*!< Bit position for LPTMR_CSR_TCF. */ #define BM_LPTMR_CSR_TCF (0x00000080U) /*!< Bit mask for LPTMR_CSR_TCF. */ #define BS_LPTMR_CSR_TCF (1U) /*!< Bit field size in bits for LPTMR_CSR_TCF. */ /*! @brief Read current value of the LPTMR_CSR_TCF field. */ #define BR_LPTMR_CSR_TCF(x) (BITBAND_ACCESS32(HW_LPTMR_CSR_ADDR(x), BP_LPTMR_CSR_TCF)) /*! @brief Format value for bitfield LPTMR_CSR_TCF. */ #define BF_LPTMR_CSR_TCF(v) ((uint32_t)((uint32_t)(v) << BP_LPTMR_CSR_TCF) & BM_LPTMR_CSR_TCF) /*! @brief Set the TCF field to a new value. */ #define BW_LPTMR_CSR_TCF(x, v) (BITBAND_ACCESS32(HW_LPTMR_CSR_ADDR(x), BP_LPTMR_CSR_TCF) = (v)) /*@}*/ /******************************************************************************* * HW_LPTMR_PSR - Low Power Timer Prescale Register ******************************************************************************/ /*! * @brief HW_LPTMR_PSR - Low Power Timer Prescale Register (RW) * * Reset value: 0x00000000U */ typedef union _hw_lptmr_psr { uint32_t U; struct _hw_lptmr_psr_bitfields { uint32_t PCS : 2; /*!< [1:0] Prescaler Clock Select */ uint32_t PBYP : 1; /*!< [2] Prescaler Bypass */ uint32_t PRESCALE : 4; /*!< [6:3] Prescale Value */ uint32_t RESERVED0 : 25; /*!< [31:7] */ } B; } hw_lptmr_psr_t; /*! * @name Constants and macros for entire LPTMR_PSR register */ /*@{*/ #define HW_LPTMR_PSR_ADDR(x) ((x) + 0x4U) #define HW_LPTMR_PSR(x) (*(__IO hw_lptmr_psr_t *) HW_LPTMR_PSR_ADDR(x)) #define HW_LPTMR_PSR_RD(x) (HW_LPTMR_PSR(x).U) #define HW_LPTMR_PSR_WR(x, v) (HW_LPTMR_PSR(x).U = (v)) #define HW_LPTMR_PSR_SET(x, v) (HW_LPTMR_PSR_WR(x, HW_LPTMR_PSR_RD(x) | (v))) #define HW_LPTMR_PSR_CLR(x, v) (HW_LPTMR_PSR_WR(x, HW_LPTMR_PSR_RD(x) & ~(v))) #define HW_LPTMR_PSR_TOG(x, v) (HW_LPTMR_PSR_WR(x, HW_LPTMR_PSR_RD(x) ^ (v))) /*@}*/ /* * Constants & macros for individual LPTMR_PSR bitfields */ /*! * @name Register LPTMR_PSR, field PCS[1:0] (RW) * * Selects the clock to be used by the LPTMR prescaler/glitch filter. PCS must * be altered only when the LPTMR is disabled. The clock connections vary by * device. See the chip configuration details for information on the connections to * these inputs. * * Values: * - 00 - Prescaler/glitch filter clock 0 selected. * - 01 - Prescaler/glitch filter clock 1 selected. * - 10 - Prescaler/glitch filter clock 2 selected. * - 11 - Prescaler/glitch filter clock 3 selected. */ /*@{*/ #define BP_LPTMR_PSR_PCS (0U) /*!< Bit position for LPTMR_PSR_PCS. */ #define BM_LPTMR_PSR_PCS (0x00000003U) /*!< Bit mask for LPTMR_PSR_PCS. */ #define BS_LPTMR_PSR_PCS (2U) /*!< Bit field size in bits for LPTMR_PSR_PCS. */ /*! @brief Read current value of the LPTMR_PSR_PCS field. */ #define BR_LPTMR_PSR_PCS(x) (HW_LPTMR_PSR(x).B.PCS) /*! @brief Format value for bitfield LPTMR_PSR_PCS. */ #define BF_LPTMR_PSR_PCS(v) ((uint32_t)((uint32_t)(v) << BP_LPTMR_PSR_PCS) & BM_LPTMR_PSR_PCS) /*! @brief Set the PCS field to a new value. */ #define BW_LPTMR_PSR_PCS(x, v) (HW_LPTMR_PSR_WR(x, (HW_LPTMR_PSR_RD(x) & ~BM_LPTMR_PSR_PCS) | BF_LPTMR_PSR_PCS(v))) /*@}*/ /*! * @name Register LPTMR_PSR, field PBYP[2] (RW) * * When PBYP is set, the selected prescaler clock in Time Counter mode or * selected input source in Pulse Counter mode directly clocks the CNR. When PBYP is * clear, the CNR is clocked by the output of the prescaler/glitch filter. PBYP * must be altered only when the LPTMR is disabled. * * Values: * - 0 - Prescaler/glitch filter is enabled. * - 1 - Prescaler/glitch filter is bypassed. */ /*@{*/ #define BP_LPTMR_PSR_PBYP (2U) /*!< Bit position for LPTMR_PSR_PBYP. */ #define BM_LPTMR_PSR_PBYP (0x00000004U) /*!< Bit mask for LPTMR_PSR_PBYP. */ #define BS_LPTMR_PSR_PBYP (1U) /*!< Bit field size in bits for LPTMR_PSR_PBYP. */ /*! @brief Read current value of the LPTMR_PSR_PBYP field. */ #define BR_LPTMR_PSR_PBYP(x) (BITBAND_ACCESS32(HW_LPTMR_PSR_ADDR(x), BP_LPTMR_PSR_PBYP)) /*! @brief Format value for bitfield LPTMR_PSR_PBYP. */ #define BF_LPTMR_PSR_PBYP(v) ((uint32_t)((uint32_t)(v) << BP_LPTMR_PSR_PBYP) & BM_LPTMR_PSR_PBYP) /*! @brief Set the PBYP field to a new value. */ #define BW_LPTMR_PSR_PBYP(x, v) (BITBAND_ACCESS32(HW_LPTMR_PSR_ADDR(x), BP_LPTMR_PSR_PBYP) = (v)) /*@}*/ /*! * @name Register LPTMR_PSR, field PRESCALE[6:3] (RW) * * Configures the size of the Prescaler in Time Counter mode or width of the * glitch filter in Pulse Counter mode. PRESCALE must be altered only when the LPTMR * is disabled. * * Values: * - 0000 - Prescaler divides the prescaler clock by 2; glitch filter does not * support this configuration. * - 0001 - Prescaler divides the prescaler clock by 4; glitch filter recognizes * change on input pin after 2 rising clock edges. * - 0010 - Prescaler divides the prescaler clock by 8; glitch filter recognizes * change on input pin after 4 rising clock edges. * - 0011 - Prescaler divides the prescaler clock by 16; glitch filter * recognizes change on input pin after 8 rising clock edges. * - 0100 - Prescaler divides the prescaler clock by 32; glitch filter * recognizes change on input pin after 16 rising clock edges. * - 0101 - Prescaler divides the prescaler clock by 64; glitch filter * recognizes change on input pin after 32 rising clock edges. * - 0110 - Prescaler divides the prescaler clock by 128; glitch filter * recognizes change on input pin after 64 rising clock edges. * - 0111 - Prescaler divides the prescaler clock by 256; glitch filter * recognizes change on input pin after 128 rising clock edges. * - 1000 - Prescaler divides the prescaler clock by 512; glitch filter * recognizes change on input pin after 256 rising clock edges. * - 1001 - Prescaler divides the prescaler clock by 1024; glitch filter * recognizes change on input pin after 512 rising clock edges. * - 1010 - Prescaler divides the prescaler clock by 2048; glitch filter * recognizes change on input pin after 1024 rising clock edges. * - 1011 - Prescaler divides the prescaler clock by 4096; glitch filter * recognizes change on input pin after 2048 rising clock edges. * - 1100 - Prescaler divides the prescaler clock by 8192; glitch filter * recognizes change on input pin after 4096 rising clock edges. * - 1101 - Prescaler divides the prescaler clock by 16,384; glitch filter * recognizes change on input pin after 8192 rising clock edges. * - 1110 - Prescaler divides the prescaler clock by 32,768; glitch filter * recognizes change on input pin after 16,384 rising clock edges. * - 1111 - Prescaler divides the prescaler clock by 65,536; glitch filter * recognizes change on input pin after 32,768 rising clock edges. */ /*@{*/ #define BP_LPTMR_PSR_PRESCALE (3U) /*!< Bit position for LPTMR_PSR_PRESCALE. */ #define BM_LPTMR_PSR_PRESCALE (0x00000078U) /*!< Bit mask for LPTMR_PSR_PRESCALE. */ #define BS_LPTMR_PSR_PRESCALE (4U) /*!< Bit field size in bits for LPTMR_PSR_PRESCALE. */ /*! @brief Read current value of the LPTMR_PSR_PRESCALE field. */ #define BR_LPTMR_PSR_PRESCALE(x) (HW_LPTMR_PSR(x).B.PRESCALE) /*! @brief Format value for bitfield LPTMR_PSR_PRESCALE. */ #define BF_LPTMR_PSR_PRESCALE(v) ((uint32_t)((uint32_t)(v) << BP_LPTMR_PSR_PRESCALE) & BM_LPTMR_PSR_PRESCALE) /*! @brief Set the PRESCALE field to a new value. */ #define BW_LPTMR_PSR_PRESCALE(x, v) (HW_LPTMR_PSR_WR(x, (HW_LPTMR_PSR_RD(x) & ~BM_LPTMR_PSR_PRESCALE) | BF_LPTMR_PSR_PRESCALE(v))) /*@}*/ /******************************************************************************* * HW_LPTMR_CMR - Low Power Timer Compare Register ******************************************************************************/ /*! * @brief HW_LPTMR_CMR - Low Power Timer Compare Register (RW) * * Reset value: 0x00000000U */ typedef union _hw_lptmr_cmr { uint32_t U; struct _hw_lptmr_cmr_bitfields { uint32_t COMPARE : 16; /*!< [15:0] Compare Value */ uint32_t RESERVED0 : 16; /*!< [31:16] */ } B; } hw_lptmr_cmr_t; /*! * @name Constants and macros for entire LPTMR_CMR register */ /*@{*/ #define HW_LPTMR_CMR_ADDR(x) ((x) + 0x8U) #define HW_LPTMR_CMR(x) (*(__IO hw_lptmr_cmr_t *) HW_LPTMR_CMR_ADDR(x)) #define HW_LPTMR_CMR_RD(x) (HW_LPTMR_CMR(x).U) #define HW_LPTMR_CMR_WR(x, v) (HW_LPTMR_CMR(x).U = (v)) #define HW_LPTMR_CMR_SET(x, v) (HW_LPTMR_CMR_WR(x, HW_LPTMR_CMR_RD(x) | (v))) #define HW_LPTMR_CMR_CLR(x, v) (HW_LPTMR_CMR_WR(x, HW_LPTMR_CMR_RD(x) & ~(v))) #define HW_LPTMR_CMR_TOG(x, v) (HW_LPTMR_CMR_WR(x, HW_LPTMR_CMR_RD(x) ^ (v))) /*@}*/ /* * Constants & macros for individual LPTMR_CMR bitfields */ /*! * @name Register LPTMR_CMR, field COMPARE[15:0] (RW) * * When the LPTMR is enabled and the CNR equals the value in the CMR and * increments, TCF is set and the hardware trigger asserts until the next time the CNR * increments. If the CMR is 0, the hardware trigger will remain asserted until * the LPTMR is disabled. If the LPTMR is enabled, the CMR must be altered only * when TCF is set. */ /*@{*/ #define BP_LPTMR_CMR_COMPARE (0U) /*!< Bit position for LPTMR_CMR_COMPARE. */ #define BM_LPTMR_CMR_COMPARE (0x0000FFFFU) /*!< Bit mask for LPTMR_CMR_COMPARE. */ #define BS_LPTMR_CMR_COMPARE (16U) /*!< Bit field size in bits for LPTMR_CMR_COMPARE. */ /*! @brief Read current value of the LPTMR_CMR_COMPARE field. */ #define BR_LPTMR_CMR_COMPARE(x) (HW_LPTMR_CMR(x).B.COMPARE) /*! @brief Format value for bitfield LPTMR_CMR_COMPARE. */ #define BF_LPTMR_CMR_COMPARE(v) ((uint32_t)((uint32_t)(v) << BP_LPTMR_CMR_COMPARE) & BM_LPTMR_CMR_COMPARE) /*! @brief Set the COMPARE field to a new value. */ #define BW_LPTMR_CMR_COMPARE(x, v) (HW_LPTMR_CMR_WR(x, (HW_LPTMR_CMR_RD(x) & ~BM_LPTMR_CMR_COMPARE) | BF_LPTMR_CMR_COMPARE(v))) /*@}*/ /******************************************************************************* * HW_LPTMR_CNR - Low Power Timer Counter Register ******************************************************************************/ /*! * @brief HW_LPTMR_CNR - Low Power Timer Counter Register (RW) * * Reset value: 0x00000000U */ typedef union _hw_lptmr_cnr { uint32_t U; struct _hw_lptmr_cnr_bitfields { uint32_t COUNTER : 16; /*!< [15:0] Counter Value */ uint32_t RESERVED0 : 16; /*!< [31:16] */ } B; } hw_lptmr_cnr_t; /*! * @name Constants and macros for entire LPTMR_CNR register */ /*@{*/ #define HW_LPTMR_CNR_ADDR(x) ((x) + 0xCU) #define HW_LPTMR_CNR(x) (*(__IO hw_lptmr_cnr_t *) HW_LPTMR_CNR_ADDR(x)) #define HW_LPTMR_CNR_RD(x) (HW_LPTMR_CNR(x).U) #define HW_LPTMR_CNR_WR(x, v) (HW_LPTMR_CNR(x).U = (v)) #define HW_LPTMR_CNR_SET(x, v) (HW_LPTMR_CNR_WR(x, HW_LPTMR_CNR_RD(x) | (v))) #define HW_LPTMR_CNR_CLR(x, v) (HW_LPTMR_CNR_WR(x, HW_LPTMR_CNR_RD(x) & ~(v))) #define HW_LPTMR_CNR_TOG(x, v) (HW_LPTMR_CNR_WR(x, HW_LPTMR_CNR_RD(x) ^ (v))) /*@}*/ /* * Constants & macros for individual LPTMR_CNR bitfields */ /*! * @name Register LPTMR_CNR, field COUNTER[15:0] (RW) */ /*@{*/ #define BP_LPTMR_CNR_COUNTER (0U) /*!< Bit position for LPTMR_CNR_COUNTER. */ #define BM_LPTMR_CNR_COUNTER (0x0000FFFFU) /*!< Bit mask for LPTMR_CNR_COUNTER. */ #define BS_LPTMR_CNR_COUNTER (16U) /*!< Bit field size in bits for LPTMR_CNR_COUNTER. */ /*! @brief Read current value of the LPTMR_CNR_COUNTER field. */ #define BR_LPTMR_CNR_COUNTER(x) (HW_LPTMR_CNR(x).B.COUNTER) /*! @brief Format value for bitfield LPTMR_CNR_COUNTER. */ #define BF_LPTMR_CNR_COUNTER(v) ((uint32_t)((uint32_t)(v) << BP_LPTMR_CNR_COUNTER) & BM_LPTMR_CNR_COUNTER) /*! @brief Set the COUNTER field to a new value. */ #define BW_LPTMR_CNR_COUNTER(x, v) (HW_LPTMR_CNR_WR(x, (HW_LPTMR_CNR_RD(x) & ~BM_LPTMR_CNR_COUNTER) | BF_LPTMR_CNR_COUNTER(v))) /*@}*/ /******************************************************************************* * hw_lptmr_t - module struct ******************************************************************************/ /*! * @brief All LPTMR module registers. */ #pragma pack(1) typedef struct _hw_lptmr { __IO hw_lptmr_csr_t CSR; /*!< [0x0] Low Power Timer Control Status Register */ __IO hw_lptmr_psr_t PSR; /*!< [0x4] Low Power Timer Prescale Register */ __IO hw_lptmr_cmr_t CMR; /*!< [0x8] Low Power Timer Compare Register */ __IO hw_lptmr_cnr_t CNR; /*!< [0xC] Low Power Timer Counter Register */ } hw_lptmr_t; #pragma pack() /*! @brief Macro to access all LPTMR registers. */ /*! @param x LPTMR module instance base address. */ /*! @return Reference (not a pointer) to the registers struct. To get a pointer to the struct, * use the '&' operator, like &HW_LPTMR(LPTMR0_BASE). */ #define HW_LPTMR(x) (*(hw_lptmr_t *)(x)) #endif /* __HW_LPTMR_REGISTERS_H__ */ /* EOF */ ================================================ FILE: Zelig/mbed/TARGET_K64F/TARGET_Freescale/TARGET_KPSDK_MCUS/TARGET_MCU_K64F/device/device/MK64F12/MK64F12_mcg.h ================================================ /* ** ################################################################### ** Compilers: Keil ARM C/C++ Compiler ** Freescale C/C++ for Embedded ARM ** GNU C Compiler ** IAR ANSI C/C++ Compiler for ARM ** ** Reference manual: K64P144M120SF5RM, Rev.2, January 2014 ** Version: rev. 2.5, 2014-02-10 ** Build: b140604 ** ** Abstract: ** Extension to the CMSIS register access layer header. ** ** Copyright (c) 2014 Freescale Semiconductor, Inc. ** All rights reserved. ** ** Redistribution and use in source and binary forms, with or without modification, ** are permitted provided that the following conditions are met: ** ** o Redistributions of source code must retain the above copyright notice, this list ** of conditions and the following disclaimer. ** ** o Redistributions in binary form must reproduce the above copyright notice, this ** list of conditions and the following disclaimer in the documentation and/or ** other materials provided with the distribution. ** ** o Neither the name of Freescale Semiconductor, Inc. nor the names of its ** contributors may be used to endorse or promote products derived from this ** software without specific prior written permission. ** ** THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ** ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED ** WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE ** DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT 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. ** ** http: www.freescale.com ** mail: support@freescale.com ** ** Revisions: ** - rev. 1.0 (2013-08-12) ** Initial version. ** - rev. 2.0 (2013-10-29) ** Register accessor macros added to the memory map. ** Symbols for Processor Expert memory map compatibility added to the memory map. ** Startup file for gcc has been updated according to CMSIS 3.2. ** System initialization updated. ** MCG - registers updated. ** PORTA, PORTB, PORTC, PORTE - registers for digital filter removed. ** - rev. 2.1 (2013-10-30) ** Definition of BITBAND macros updated to support peripherals with 32-bit acces disabled. ** - rev. 2.2 (2013-12-09) ** DMA - EARS register removed. ** AIPS0, AIPS1 - MPRA register updated. ** - rev. 2.3 (2014-01-24) ** Update according to reference manual rev. 2 ** ENET, MCG, MCM, SIM, USB - registers updated ** - rev. 2.4 (2014-02-10) ** The declaration of clock configurations has been moved to separate header file system_MK64F12.h ** Update of SystemInit() and SystemCoreClockUpdate() functions. ** - rev. 2.5 (2014-02-10) ** The declaration of clock configurations has been moved to separate header file system_MK64F12.h ** Update of SystemInit() and SystemCoreClockUpdate() functions. ** Module access macro module_BASES replaced by module_BASE_PTRS. ** ** ################################################################### */ /* * WARNING! DO NOT EDIT THIS FILE DIRECTLY! * * This file was generated automatically and any changes may be lost. */ #ifndef __HW_MCG_REGISTERS_H__ #define __HW_MCG_REGISTERS_H__ #include "MK64F12.h" #include "fsl_bitaccess.h" /* * MK64F12 MCG * * Multipurpose Clock Generator module * * Registers defined in this header file: * - HW_MCG_C1 - MCG Control 1 Register * - HW_MCG_C2 - MCG Control 2 Register * - HW_MCG_C3 - MCG Control 3 Register * - HW_MCG_C4 - MCG Control 4 Register * - HW_MCG_C5 - MCG Control 5 Register * - HW_MCG_C6 - MCG Control 6 Register * - HW_MCG_S - MCG Status Register * - HW_MCG_SC - MCG Status and Control Register * - HW_MCG_ATCVH - MCG Auto Trim Compare Value High Register * - HW_MCG_ATCVL - MCG Auto Trim Compare Value Low Register * - HW_MCG_C7 - MCG Control 7 Register * - HW_MCG_C8 - MCG Control 8 Register * * - hw_mcg_t - Struct containing all module registers. */ #define HW_MCG_INSTANCE_COUNT (1U) /*!< Number of instances of the MCG module. */ /******************************************************************************* * HW_MCG_C1 - MCG Control 1 Register ******************************************************************************/ /*! * @brief HW_MCG_C1 - MCG Control 1 Register (RW) * * Reset value: 0x04U */ typedef union _hw_mcg_c1 { uint8_t U; struct _hw_mcg_c1_bitfields { uint8_t IREFSTEN : 1; /*!< [0] Internal Reference Stop Enable */ uint8_t IRCLKEN : 1; /*!< [1] Internal Reference Clock Enable */ uint8_t IREFS : 1; /*!< [2] Internal Reference Select */ uint8_t FRDIV : 3; /*!< [5:3] FLL External Reference Divider */ uint8_t CLKS : 2; /*!< [7:6] Clock Source Select */ } B; } hw_mcg_c1_t; /*! * @name Constants and macros for entire MCG_C1 register */ /*@{*/ #define HW_MCG_C1_ADDR(x) ((x) + 0x0U) #define HW_MCG_C1(x) (*(__IO hw_mcg_c1_t *) HW_MCG_C1_ADDR(x)) #define HW_MCG_C1_RD(x) (HW_MCG_C1(x).U) #define HW_MCG_C1_WR(x, v) (HW_MCG_C1(x).U = (v)) #define HW_MCG_C1_SET(x, v) (HW_MCG_C1_WR(x, HW_MCG_C1_RD(x) | (v))) #define HW_MCG_C1_CLR(x, v) (HW_MCG_C1_WR(x, HW_MCG_C1_RD(x) & ~(v))) #define HW_MCG_C1_TOG(x, v) (HW_MCG_C1_WR(x, HW_MCG_C1_RD(x) ^ (v))) /*@}*/ /* * Constants & macros for individual MCG_C1 bitfields */ /*! * @name Register MCG_C1, field IREFSTEN[0] (RW) * * Controls whether or not the internal reference clock remains enabled when the * MCG enters Stop mode. * * Values: * - 0 - Internal reference clock is disabled in Stop mode. * - 1 - Internal reference clock is enabled in Stop mode if IRCLKEN is set or * if MCG is in FEI, FBI, or BLPI modes before entering Stop mode. */ /*@{*/ #define BP_MCG_C1_IREFSTEN (0U) /*!< Bit position for MCG_C1_IREFSTEN. */ #define BM_MCG_C1_IREFSTEN (0x01U) /*!< Bit mask for MCG_C1_IREFSTEN. */ #define BS_MCG_C1_IREFSTEN (1U) /*!< Bit field size in bits for MCG_C1_IREFSTEN. */ /*! @brief Read current value of the MCG_C1_IREFSTEN field. */ #define BR_MCG_C1_IREFSTEN(x) (BITBAND_ACCESS8(HW_MCG_C1_ADDR(x), BP_MCG_C1_IREFSTEN)) /*! @brief Format value for bitfield MCG_C1_IREFSTEN. */ #define BF_MCG_C1_IREFSTEN(v) ((uint8_t)((uint8_t)(v) << BP_MCG_C1_IREFSTEN) & BM_MCG_C1_IREFSTEN) /*! @brief Set the IREFSTEN field to a new value. */ #define BW_MCG_C1_IREFSTEN(x, v) (BITBAND_ACCESS8(HW_MCG_C1_ADDR(x), BP_MCG_C1_IREFSTEN) = (v)) /*@}*/ /*! * @name Register MCG_C1, field IRCLKEN[1] (RW) * * Enables the internal reference clock for use as MCGIRCLK. * * Values: * - 0 - MCGIRCLK inactive. * - 1 - MCGIRCLK active. */ /*@{*/ #define BP_MCG_C1_IRCLKEN (1U) /*!< Bit position for MCG_C1_IRCLKEN. */ #define BM_MCG_C1_IRCLKEN (0x02U) /*!< Bit mask for MCG_C1_IRCLKEN. */ #define BS_MCG_C1_IRCLKEN (1U) /*!< Bit field size in bits for MCG_C1_IRCLKEN. */ /*! @brief Read current value of the MCG_C1_IRCLKEN field. */ #define BR_MCG_C1_IRCLKEN(x) (BITBAND_ACCESS8(HW_MCG_C1_ADDR(x), BP_MCG_C1_IRCLKEN)) /*! @brief Format value for bitfield MCG_C1_IRCLKEN. */ #define BF_MCG_C1_IRCLKEN(v) ((uint8_t)((uint8_t)(v) << BP_MCG_C1_IRCLKEN) & BM_MCG_C1_IRCLKEN) /*! @brief Set the IRCLKEN field to a new value. */ #define BW_MCG_C1_IRCLKEN(x, v) (BITBAND_ACCESS8(HW_MCG_C1_ADDR(x), BP_MCG_C1_IRCLKEN) = (v)) /*@}*/ /*! * @name Register MCG_C1, field IREFS[2] (RW) * * Selects the reference clock source for the FLL. * * Values: * - 0 - External reference clock is selected. * - 1 - The slow internal reference clock is selected. */ /*@{*/ #define BP_MCG_C1_IREFS (2U) /*!< Bit position for MCG_C1_IREFS. */ #define BM_MCG_C1_IREFS (0x04U) /*!< Bit mask for MCG_C1_IREFS. */ #define BS_MCG_C1_IREFS (1U) /*!< Bit field size in bits for MCG_C1_IREFS. */ /*! @brief Read current value of the MCG_C1_IREFS field. */ #define BR_MCG_C1_IREFS(x) (BITBAND_ACCESS8(HW_MCG_C1_ADDR(x), BP_MCG_C1_IREFS)) /*! @brief Format value for bitfield MCG_C1_IREFS. */ #define BF_MCG_C1_IREFS(v) ((uint8_t)((uint8_t)(v) << BP_MCG_C1_IREFS) & BM_MCG_C1_IREFS) /*! @brief Set the IREFS field to a new value. */ #define BW_MCG_C1_IREFS(x, v) (BITBAND_ACCESS8(HW_MCG_C1_ADDR(x), BP_MCG_C1_IREFS) = (v)) /*@}*/ /*! * @name Register MCG_C1, field FRDIV[5:3] (RW) * * Selects the amount to divide down the external reference clock for the FLL. * The resulting frequency must be in the range 31.25 kHz to 39.0625 kHz (This is * required when FLL/DCO is the clock source for MCGOUTCLK . In FBE mode, it is * not required to meet this range, but it is recommended in the cases when trying * to enter a FLL mode from FBE). * * Values: * - 000 - If RANGE = 0 or OSCSEL=1 , Divide Factor is 1; for all other RANGE * values, Divide Factor is 32. * - 001 - If RANGE = 0 or OSCSEL=1 , Divide Factor is 2; for all other RANGE * values, Divide Factor is 64. * - 010 - If RANGE = 0 or OSCSEL=1 , Divide Factor is 4; for all other RANGE * values, Divide Factor is 128. * - 011 - If RANGE = 0 or OSCSEL=1 , Divide Factor is 8; for all other RANGE * values, Divide Factor is 256. * - 100 - If RANGE = 0 or OSCSEL=1 , Divide Factor is 16; for all other RANGE * values, Divide Factor is 512. * - 101 - If RANGE = 0 or OSCSEL=1 , Divide Factor is 32; for all other RANGE * values, Divide Factor is 1024. * - 110 - If RANGE = 0 or OSCSEL=1 , Divide Factor is 64; for all other RANGE * values, Divide Factor is 1280 . * - 111 - If RANGE = 0 or OSCSEL=1 , Divide Factor is 128; for all other RANGE * values, Divide Factor is 1536 . */ /*@{*/ #define BP_MCG_C1_FRDIV (3U) /*!< Bit position for MCG_C1_FRDIV. */ #define BM_MCG_C1_FRDIV (0x38U) /*!< Bit mask for MCG_C1_FRDIV. */ #define BS_MCG_C1_FRDIV (3U) /*!< Bit field size in bits for MCG_C1_FRDIV. */ /*! @brief Read current value of the MCG_C1_FRDIV field. */ #define BR_MCG_C1_FRDIV(x) (HW_MCG_C1(x).B.FRDIV) /*! @brief Format value for bitfield MCG_C1_FRDIV. */ #define BF_MCG_C1_FRDIV(v) ((uint8_t)((uint8_t)(v) << BP_MCG_C1_FRDIV) & BM_MCG_C1_FRDIV) /*! @brief Set the FRDIV field to a new value. */ #define BW_MCG_C1_FRDIV(x, v) (HW_MCG_C1_WR(x, (HW_MCG_C1_RD(x) & ~BM_MCG_C1_FRDIV) | BF_MCG_C1_FRDIV(v))) /*@}*/ /*! * @name Register MCG_C1, field CLKS[7:6] (RW) * * Selects the clock source for MCGOUTCLK . * * Values: * - 00 - Encoding 0 - Output of FLL or PLL is selected (depends on PLLS control * bit). * - 01 - Encoding 1 - Internal reference clock is selected. * - 10 - Encoding 2 - External reference clock is selected. * - 11 - Encoding 3 - Reserved. */ /*@{*/ #define BP_MCG_C1_CLKS (6U) /*!< Bit position for MCG_C1_CLKS. */ #define BM_MCG_C1_CLKS (0xC0U) /*!< Bit mask for MCG_C1_CLKS. */ #define BS_MCG_C1_CLKS (2U) /*!< Bit field size in bits for MCG_C1_CLKS. */ /*! @brief Read current value of the MCG_C1_CLKS field. */ #define BR_MCG_C1_CLKS(x) (HW_MCG_C1(x).B.CLKS) /*! @brief Format value for bitfield MCG_C1_CLKS. */ #define BF_MCG_C1_CLKS(v) ((uint8_t)((uint8_t)(v) << BP_MCG_C1_CLKS) & BM_MCG_C1_CLKS) /*! @brief Set the CLKS field to a new value. */ #define BW_MCG_C1_CLKS(x, v) (HW_MCG_C1_WR(x, (HW_MCG_C1_RD(x) & ~BM_MCG_C1_CLKS) | BF_MCG_C1_CLKS(v))) /*@}*/ /******************************************************************************* * HW_MCG_C2 - MCG Control 2 Register ******************************************************************************/ /*! * @brief HW_MCG_C2 - MCG Control 2 Register (RW) * * Reset value: 0x80U */ typedef union _hw_mcg_c2 { uint8_t U; struct _hw_mcg_c2_bitfields { uint8_t IRCS : 1; /*!< [0] Internal Reference Clock Select */ uint8_t LP : 1; /*!< [1] Low Power Select */ uint8_t EREFS : 1; /*!< [2] External Reference Select */ uint8_t HGO : 1; /*!< [3] High Gain Oscillator Select */ uint8_t RANGE : 2; /*!< [5:4] Frequency Range Select */ uint8_t FCFTRIM : 1; /*!< [6] Fast Internal Reference Clock Fine Trim * */ uint8_t LOCRE0 : 1; /*!< [7] Loss of Clock Reset Enable */ } B; } hw_mcg_c2_t; /*! * @name Constants and macros for entire MCG_C2 register */ /*@{*/ #define HW_MCG_C2_ADDR(x) ((x) + 0x1U) #define HW_MCG_C2(x) (*(__IO hw_mcg_c2_t *) HW_MCG_C2_ADDR(x)) #define HW_MCG_C2_RD(x) (HW_MCG_C2(x).U) #define HW_MCG_C2_WR(x, v) (HW_MCG_C2(x).U = (v)) #define HW_MCG_C2_SET(x, v) (HW_MCG_C2_WR(x, HW_MCG_C2_RD(x) | (v))) #define HW_MCG_C2_CLR(x, v) (HW_MCG_C2_WR(x, HW_MCG_C2_RD(x) & ~(v))) #define HW_MCG_C2_TOG(x, v) (HW_MCG_C2_WR(x, HW_MCG_C2_RD(x) ^ (v))) /*@}*/ /* * Constants & macros for individual MCG_C2 bitfields */ /*! * @name Register MCG_C2, field IRCS[0] (RW) * * Selects between the fast or slow internal reference clock source. * * Values: * - 0 - Slow internal reference clock selected. * - 1 - Fast internal reference clock selected. */ /*@{*/ #define BP_MCG_C2_IRCS (0U) /*!< Bit position for MCG_C2_IRCS. */ #define BM_MCG_C2_IRCS (0x01U) /*!< Bit mask for MCG_C2_IRCS. */ #define BS_MCG_C2_IRCS (1U) /*!< Bit field size in bits for MCG_C2_IRCS. */ /*! @brief Read current value of the MCG_C2_IRCS field. */ #define BR_MCG_C2_IRCS(x) (BITBAND_ACCESS8(HW_MCG_C2_ADDR(x), BP_MCG_C2_IRCS)) /*! @brief Format value for bitfield MCG_C2_IRCS. */ #define BF_MCG_C2_IRCS(v) ((uint8_t)((uint8_t)(v) << BP_MCG_C2_IRCS) & BM_MCG_C2_IRCS) /*! @brief Set the IRCS field to a new value. */ #define BW_MCG_C2_IRCS(x, v) (BITBAND_ACCESS8(HW_MCG_C2_ADDR(x), BP_MCG_C2_IRCS) = (v)) /*@}*/ /*! * @name Register MCG_C2, field LP[1] (RW) * * Controls whether the FLL or PLL is disabled in BLPI and BLPE modes. In FBE or * PBE modes, setting this bit to 1 will transition the MCG into BLPE mode; in * FBI mode, setting this bit to 1 will transition the MCG into BLPI mode. In any * other MCG mode, LP bit has no affect. * * Values: * - 0 - FLL or PLL is not disabled in bypass modes. * - 1 - FLL or PLL is disabled in bypass modes (lower power) */ /*@{*/ #define BP_MCG_C2_LP (1U) /*!< Bit position for MCG_C2_LP. */ #define BM_MCG_C2_LP (0x02U) /*!< Bit mask for MCG_C2_LP. */ #define BS_MCG_C2_LP (1U) /*!< Bit field size in bits for MCG_C2_LP. */ /*! @brief Read current value of the MCG_C2_LP field. */ #define BR_MCG_C2_LP(x) (BITBAND_ACCESS8(HW_MCG_C2_ADDR(x), BP_MCG_C2_LP)) /*! @brief Format value for bitfield MCG_C2_LP. */ #define BF_MCG_C2_LP(v) ((uint8_t)((uint8_t)(v) << BP_MCG_C2_LP) & BM_MCG_C2_LP) /*! @brief Set the LP field to a new value. */ #define BW_MCG_C2_LP(x, v) (BITBAND_ACCESS8(HW_MCG_C2_ADDR(x), BP_MCG_C2_LP) = (v)) /*@}*/ /*! * @name Register MCG_C2, field EREFS[2] (RW) * * Selects the source for the external reference clock. See the Oscillator (OSC) * chapter for more details. * * Values: * - 0 - External reference clock requested. * - 1 - Oscillator requested. */ /*@{*/ #define BP_MCG_C2_EREFS (2U) /*!< Bit position for MCG_C2_EREFS. */ #define BM_MCG_C2_EREFS (0x04U) /*!< Bit mask for MCG_C2_EREFS. */ #define BS_MCG_C2_EREFS (1U) /*!< Bit field size in bits for MCG_C2_EREFS. */ /*! @brief Read current value of the MCG_C2_EREFS field. */ #define BR_MCG_C2_EREFS(x) (BITBAND_ACCESS8(HW_MCG_C2_ADDR(x), BP_MCG_C2_EREFS)) /*! @brief Format value for bitfield MCG_C2_EREFS. */ #define BF_MCG_C2_EREFS(v) ((uint8_t)((uint8_t)(v) << BP_MCG_C2_EREFS) & BM_MCG_C2_EREFS) /*! @brief Set the EREFS field to a new value. */ #define BW_MCG_C2_EREFS(x, v) (BITBAND_ACCESS8(HW_MCG_C2_ADDR(x), BP_MCG_C2_EREFS) = (v)) /*@}*/ /*! * @name Register MCG_C2, field HGO[3] (RW) * * Controls the crystal oscillator mode of operation. See the Oscillator (OSC) * chapter for more details. * * Values: * - 0 - Configure crystal oscillator for low-power operation. * - 1 - Configure crystal oscillator for high-gain operation. */ /*@{*/ #define BP_MCG_C2_HGO (3U) /*!< Bit position for MCG_C2_HGO. */ #define BM_MCG_C2_HGO (0x08U) /*!< Bit mask for MCG_C2_HGO. */ #define BS_MCG_C2_HGO (1U) /*!< Bit field size in bits for MCG_C2_HGO. */ /*! @brief Read current value of the MCG_C2_HGO field. */ #define BR_MCG_C2_HGO(x) (BITBAND_ACCESS8(HW_MCG_C2_ADDR(x), BP_MCG_C2_HGO)) /*! @brief Format value for bitfield MCG_C2_HGO. */ #define BF_MCG_C2_HGO(v) ((uint8_t)((uint8_t)(v) << BP_MCG_C2_HGO) & BM_MCG_C2_HGO) /*! @brief Set the HGO field to a new value. */ #define BW_MCG_C2_HGO(x, v) (BITBAND_ACCESS8(HW_MCG_C2_ADDR(x), BP_MCG_C2_HGO) = (v)) /*@}*/ /*! * @name Register MCG_C2, field RANGE[5:4] (RW) * * Selects the frequency range for the crystal oscillator or external clock * source. See the Oscillator (OSC) chapter for more details and the device data * sheet for the frequency ranges used. * * Values: * - 00 - Encoding 0 - Low frequency range selected for the crystal oscillator . * - 01 - Encoding 1 - High frequency range selected for the crystal oscillator . */ /*@{*/ #define BP_MCG_C2_RANGE (4U) /*!< Bit position for MCG_C2_RANGE. */ #define BM_MCG_C2_RANGE (0x30U) /*!< Bit mask for MCG_C2_RANGE. */ #define BS_MCG_C2_RANGE (2U) /*!< Bit field size in bits for MCG_C2_RANGE. */ /*! @brief Read current value of the MCG_C2_RANGE field. */ #define BR_MCG_C2_RANGE(x) (HW_MCG_C2(x).B.RANGE) /*! @brief Format value for bitfield MCG_C2_RANGE. */ #define BF_MCG_C2_RANGE(v) ((uint8_t)((uint8_t)(v) << BP_MCG_C2_RANGE) & BM_MCG_C2_RANGE) /*! @brief Set the RANGE field to a new value. */ #define BW_MCG_C2_RANGE(x, v) (HW_MCG_C2_WR(x, (HW_MCG_C2_RD(x) & ~BM_MCG_C2_RANGE) | BF_MCG_C2_RANGE(v))) /*@}*/ /*! * @name Register MCG_C2, field FCFTRIM[6] (RW) * * FCFTRIM controls the smallest adjustment of the fast internal reference clock * frequency. Setting FCFTRIM increases the period and clearing FCFTRIM * decreases the period by the smallest amount possible. If an FCFTRIM value stored in * nonvolatile memory is to be used, it is your responsibility to copy that value * from the nonvolatile memory location to this bit. */ /*@{*/ #define BP_MCG_C2_FCFTRIM (6U) /*!< Bit position for MCG_C2_FCFTRIM. */ #define BM_MCG_C2_FCFTRIM (0x40U) /*!< Bit mask for MCG_C2_FCFTRIM. */ #define BS_MCG_C2_FCFTRIM (1U) /*!< Bit field size in bits for MCG_C2_FCFTRIM. */ /*! @brief Read current value of the MCG_C2_FCFTRIM field. */ #define BR_MCG_C2_FCFTRIM(x) (BITBAND_ACCESS8(HW_MCG_C2_ADDR(x), BP_MCG_C2_FCFTRIM)) /*! @brief Format value for bitfield MCG_C2_FCFTRIM. */ #define BF_MCG_C2_FCFTRIM(v) ((uint8_t)((uint8_t)(v) << BP_MCG_C2_FCFTRIM) & BM_MCG_C2_FCFTRIM) /*! @brief Set the FCFTRIM field to a new value. */ #define BW_MCG_C2_FCFTRIM(x, v) (BITBAND_ACCESS8(HW_MCG_C2_ADDR(x), BP_MCG_C2_FCFTRIM) = (v)) /*@}*/ /*! * @name Register MCG_C2, field LOCRE0[7] (RW) * * Determines whether an interrupt or a reset request is made following a loss * of OSC0 external reference clock. The LOCRE0 only has an affect when CME0 is * set. * * Values: * - 0 - Interrupt request is generated on a loss of OSC0 external reference * clock. * - 1 - Generate a reset request on a loss of OSC0 external reference clock. */ /*@{*/ #define BP_MCG_C2_LOCRE0 (7U) /*!< Bit position for MCG_C2_LOCRE0. */ #define BM_MCG_C2_LOCRE0 (0x80U) /*!< Bit mask for MCG_C2_LOCRE0. */ #define BS_MCG_C2_LOCRE0 (1U) /*!< Bit field size in bits for MCG_C2_LOCRE0. */ /*! @brief Read current value of the MCG_C2_LOCRE0 field. */ #define BR_MCG_C2_LOCRE0(x) (BITBAND_ACCESS8(HW_MCG_C2_ADDR(x), BP_MCG_C2_LOCRE0)) /*! @brief Format value for bitfield MCG_C2_LOCRE0. */ #define BF_MCG_C2_LOCRE0(v) ((uint8_t)((uint8_t)(v) << BP_MCG_C2_LOCRE0) & BM_MCG_C2_LOCRE0) /*! @brief Set the LOCRE0 field to a new value. */ #define BW_MCG_C2_LOCRE0(x, v) (BITBAND_ACCESS8(HW_MCG_C2_ADDR(x), BP_MCG_C2_LOCRE0) = (v)) /*@}*/ /******************************************************************************* * HW_MCG_C3 - MCG Control 3 Register ******************************************************************************/ /*! * @brief HW_MCG_C3 - MCG Control 3 Register (RW) * * Reset value: 0x00U */ typedef union _hw_mcg_c3 { uint8_t U; struct _hw_mcg_c3_bitfields { uint8_t SCTRIM : 8; /*!< [7:0] Slow Internal Reference Clock Trim * Setting */ } B; } hw_mcg_c3_t; /*! * @name Constants and macros for entire MCG_C3 register */ /*@{*/ #define HW_MCG_C3_ADDR(x) ((x) + 0x2U) #define HW_MCG_C3(x) (*(__IO hw_mcg_c3_t *) HW_MCG_C3_ADDR(x)) #define HW_MCG_C3_RD(x) (HW_MCG_C3(x).U) #define HW_MCG_C3_WR(x, v) (HW_MCG_C3(x).U = (v)) #define HW_MCG_C3_SET(x, v) (HW_MCG_C3_WR(x, HW_MCG_C3_RD(x) | (v))) #define HW_MCG_C3_CLR(x, v) (HW_MCG_C3_WR(x, HW_MCG_C3_RD(x) & ~(v))) #define HW_MCG_C3_TOG(x, v) (HW_MCG_C3_WR(x, HW_MCG_C3_RD(x) ^ (v))) /*@}*/ /* * Constants & macros for individual MCG_C3 bitfields */ /*! * @name Register MCG_C3, field SCTRIM[7:0] (RW) * * SCTRIM A value for SCTRIM is loaded during reset from a factory programmed * location. controls the slow internal reference clock frequency by controlling * the slow internal reference clock period. The SCTRIM bits are binary weighted, * that is, bit 1 adjusts twice as much as bit 0. Increasing the binary value * increases the period, and decreasing the value decreases the period. An additional * fine trim bit is available in C4 register as the SCFTRIM bit. Upon reset, * this value is loaded with a factory trim value. If an SCTRIM value stored in * nonvolatile memory is to be used, it is your responsibility to copy that value * from the nonvolatile memory location to this register. */ /*@{*/ #define BP_MCG_C3_SCTRIM (0U) /*!< Bit position for MCG_C3_SCTRIM. */ #define BM_MCG_C3_SCTRIM (0xFFU) /*!< Bit mask for MCG_C3_SCTRIM. */ #define BS_MCG_C3_SCTRIM (8U) /*!< Bit field size in bits for MCG_C3_SCTRIM. */ /*! @brief Read current value of the MCG_C3_SCTRIM field. */ #define BR_MCG_C3_SCTRIM(x) (HW_MCG_C3(x).U) /*! @brief Format value for bitfield MCG_C3_SCTRIM. */ #define BF_MCG_C3_SCTRIM(v) ((uint8_t)((uint8_t)(v) << BP_MCG_C3_SCTRIM) & BM_MCG_C3_SCTRIM) /*! @brief Set the SCTRIM field to a new value. */ #define BW_MCG_C3_SCTRIM(x, v) (HW_MCG_C3_WR(x, v)) /*@}*/ /******************************************************************************* * HW_MCG_C4 - MCG Control 4 Register ******************************************************************************/ /*! * @brief HW_MCG_C4 - MCG Control 4 Register (RW) * * Reset value: 0x00U * * Reset values for DRST and DMX32 bits are 0. */ typedef union _hw_mcg_c4 { uint8_t U; struct _hw_mcg_c4_bitfields { uint8_t SCFTRIM : 1; /*!< [0] Slow Internal Reference Clock Fine Trim * */ uint8_t FCTRIM : 4; /*!< [4:1] Fast Internal Reference Clock Trim * Setting */ uint8_t DRST_DRS : 2; /*!< [6:5] DCO Range Select */ uint8_t DMX32 : 1; /*!< [7] DCO Maximum Frequency with 32.768 kHz * Reference */ } B; } hw_mcg_c4_t; /*! * @name Constants and macros for entire MCG_C4 register */ /*@{*/ #define HW_MCG_C4_ADDR(x) ((x) + 0x3U) #define HW_MCG_C4(x) (*(__IO hw_mcg_c4_t *) HW_MCG_C4_ADDR(x)) #define HW_MCG_C4_RD(x) (HW_MCG_C4(x).U) #define HW_MCG_C4_WR(x, v) (HW_MCG_C4(x).U = (v)) #define HW_MCG_C4_SET(x, v) (HW_MCG_C4_WR(x, HW_MCG_C4_RD(x) | (v))) #define HW_MCG_C4_CLR(x, v) (HW_MCG_C4_WR(x, HW_MCG_C4_RD(x) & ~(v))) #define HW_MCG_C4_TOG(x, v) (HW_MCG_C4_WR(x, HW_MCG_C4_RD(x) ^ (v))) /*@}*/ /* * Constants & macros for individual MCG_C4 bitfields */ /*! * @name Register MCG_C4, field SCFTRIM[0] (RW) * * SCFTRIM A value for SCFTRIM is loaded during reset from a factory programmed * location . controls the smallest adjustment of the slow internal reference * clock frequency. Setting SCFTRIM increases the period and clearing SCFTRIM * decreases the period by the smallest amount possible. If an SCFTRIM value stored in * nonvolatile memory is to be used, it is your responsibility to copy that value * from the nonvolatile memory location to this bit. */ /*@{*/ #define BP_MCG_C4_SCFTRIM (0U) /*!< Bit position for MCG_C4_SCFTRIM. */ #define BM_MCG_C4_SCFTRIM (0x01U) /*!< Bit mask for MCG_C4_SCFTRIM. */ #define BS_MCG_C4_SCFTRIM (1U) /*!< Bit field size in bits for MCG_C4_SCFTRIM. */ /*! @brief Read current value of the MCG_C4_SCFTRIM field. */ #define BR_MCG_C4_SCFTRIM(x) (BITBAND_ACCESS8(HW_MCG_C4_ADDR(x), BP_MCG_C4_SCFTRIM)) /*! @brief Format value for bitfield MCG_C4_SCFTRIM. */ #define BF_MCG_C4_SCFTRIM(v) ((uint8_t)((uint8_t)(v) << BP_MCG_C4_SCFTRIM) & BM_MCG_C4_SCFTRIM) /*! @brief Set the SCFTRIM field to a new value. */ #define BW_MCG_C4_SCFTRIM(x, v) (BITBAND_ACCESS8(HW_MCG_C4_ADDR(x), BP_MCG_C4_SCFTRIM) = (v)) /*@}*/ /*! * @name Register MCG_C4, field FCTRIM[4:1] (RW) * * FCTRIM A value for FCTRIM is loaded during reset from a factory programmed * location. controls the fast internal reference clock frequency by controlling * the fast internal reference clock period. The FCTRIM bits are binary weighted, * that is, bit 1 adjusts twice as much as bit 0. Increasing the binary value * increases the period, and decreasing the value decreases the period. If an * FCTRIM[3:0] value stored in nonvolatile memory is to be used, it is your * responsibility to copy that value from the nonvolatile memory location to this register. */ /*@{*/ #define BP_MCG_C4_FCTRIM (1U) /*!< Bit position for MCG_C4_FCTRIM. */ #define BM_MCG_C4_FCTRIM (0x1EU) /*!< Bit mask for MCG_C4_FCTRIM. */ #define BS_MCG_C4_FCTRIM (4U) /*!< Bit field size in bits for MCG_C4_FCTRIM. */ /*! @brief Read current value of the MCG_C4_FCTRIM field. */ #define BR_MCG_C4_FCTRIM(x) (HW_MCG_C4(x).B.FCTRIM) /*! @brief Format value for bitfield MCG_C4_FCTRIM. */ #define BF_MCG_C4_FCTRIM(v) ((uint8_t)((uint8_t)(v) << BP_MCG_C4_FCTRIM) & BM_MCG_C4_FCTRIM) /*! @brief Set the FCTRIM field to a new value. */ #define BW_MCG_C4_FCTRIM(x, v) (HW_MCG_C4_WR(x, (HW_MCG_C4_RD(x) & ~BM_MCG_C4_FCTRIM) | BF_MCG_C4_FCTRIM(v))) /*@}*/ /*! * @name Register MCG_C4, field DRST_DRS[6:5] (RW) * * The DRS bits select the frequency range for the FLL output, DCOOUT. When the * LP bit is set, writes to the DRS bits are ignored. The DRST read field * indicates the current frequency range for DCOOUT. The DRST field does not update * immediately after a write to the DRS field due to internal synchronization between * clock domains. See the DCO Frequency Range table for more details. * * Values: * - 00 - Encoding 0 - Low range (reset default). * - 01 - Encoding 1 - Mid range. * - 10 - Encoding 2 - Mid-high range. * - 11 - Encoding 3 - High range. */ /*@{*/ #define BP_MCG_C4_DRST_DRS (5U) /*!< Bit position for MCG_C4_DRST_DRS. */ #define BM_MCG_C4_DRST_DRS (0x60U) /*!< Bit mask for MCG_C4_DRST_DRS. */ #define BS_MCG_C4_DRST_DRS (2U) /*!< Bit field size in bits for MCG_C4_DRST_DRS. */ /*! @brief Read current value of the MCG_C4_DRST_DRS field. */ #define BR_MCG_C4_DRST_DRS(x) (HW_MCG_C4(x).B.DRST_DRS) /*! @brief Format value for bitfield MCG_C4_DRST_DRS. */ #define BF_MCG_C4_DRST_DRS(v) ((uint8_t)((uint8_t)(v) << BP_MCG_C4_DRST_DRS) & BM_MCG_C4_DRST_DRS) /*! @brief Set the DRST_DRS field to a new value. */ #define BW_MCG_C4_DRST_DRS(x, v) (HW_MCG_C4_WR(x, (HW_MCG_C4_RD(x) & ~BM_MCG_C4_DRST_DRS) | BF_MCG_C4_DRST_DRS(v))) /*@}*/ /*! * @name Register MCG_C4, field DMX32[7] (RW) * * The DMX32 bit controls whether the DCO frequency range is narrowed to its * maximum frequency with a 32.768 kHz reference. The following table identifies * settings for the DCO frequency range. The system clocks derived from this source * should not exceed their specified maximums. DRST_DRS DMX32 Reference Range FLL * Factor DCO Range 00 0 31.25-39.0625 kHz 640 20-25 MHz 1 32.768 kHz 732 24 MHz * 01 0 31.25-39.0625 kHz 1280 40-50 MHz 1 32.768 kHz 1464 48 MHz 10 0 * 31.25-39.0625 kHz 1920 60-75 MHz 1 32.768 kHz 2197 72 MHz 11 0 31.25-39.0625 kHz 2560 * 80-100 MHz 1 32.768 kHz 2929 96 MHz * * Values: * - 0 - DCO has a default range of 25%. * - 1 - DCO is fine-tuned for maximum frequency with 32.768 kHz reference. */ /*@{*/ #define BP_MCG_C4_DMX32 (7U) /*!< Bit position for MCG_C4_DMX32. */ #define BM_MCG_C4_DMX32 (0x80U) /*!< Bit mask for MCG_C4_DMX32. */ #define BS_MCG_C4_DMX32 (1U) /*!< Bit field size in bits for MCG_C4_DMX32. */ /*! @brief Read current value of the MCG_C4_DMX32 field. */ #define BR_MCG_C4_DMX32(x) (BITBAND_ACCESS8(HW_MCG_C4_ADDR(x), BP_MCG_C4_DMX32)) /*! @brief Format value for bitfield MCG_C4_DMX32. */ #define BF_MCG_C4_DMX32(v) ((uint8_t)((uint8_t)(v) << BP_MCG_C4_DMX32) & BM_MCG_C4_DMX32) /*! @brief Set the DMX32 field to a new value. */ #define BW_MCG_C4_DMX32(x, v) (BITBAND_ACCESS8(HW_MCG_C4_ADDR(x), BP_MCG_C4_DMX32) = (v)) /*@}*/ /******************************************************************************* * HW_MCG_C5 - MCG Control 5 Register ******************************************************************************/ /*! * @brief HW_MCG_C5 - MCG Control 5 Register (RW) * * Reset value: 0x00U */ typedef union _hw_mcg_c5 { uint8_t U; struct _hw_mcg_c5_bitfields { uint8_t PRDIV0 : 5; /*!< [4:0] PLL External Reference Divider */ uint8_t PLLSTEN0 : 1; /*!< [5] PLL Stop Enable */ uint8_t PLLCLKEN0 : 1; /*!< [6] PLL Clock Enable */ uint8_t RESERVED0 : 1; /*!< [7] */ } B; } hw_mcg_c5_t; /*! * @name Constants and macros for entire MCG_C5 register */ /*@{*/ #define HW_MCG_C5_ADDR(x) ((x) + 0x4U) #define HW_MCG_C5(x) (*(__IO hw_mcg_c5_t *) HW_MCG_C5_ADDR(x)) #define HW_MCG_C5_RD(x) (HW_MCG_C5(x).U) #define HW_MCG_C5_WR(x, v) (HW_MCG_C5(x).U = (v)) #define HW_MCG_C5_SET(x, v) (HW_MCG_C5_WR(x, HW_MCG_C5_RD(x) | (v))) #define HW_MCG_C5_CLR(x, v) (HW_MCG_C5_WR(x, HW_MCG_C5_RD(x) & ~(v))) #define HW_MCG_C5_TOG(x, v) (HW_MCG_C5_WR(x, HW_MCG_C5_RD(x) ^ (v))) /*@}*/ /* * Constants & macros for individual MCG_C5 bitfields */ /*! * @name Register MCG_C5, field PRDIV0[4:0] (RW) * * Selects the amount to divide down the external reference clock for the PLL. * The resulting frequency must be in the range of 2 MHz to 4 MHz. After the PLL * is enabled (by setting either PLLCLKEN 0 or PLLS), the PRDIV 0 value must not * be changed when LOCK0 is zero. PLL External Reference Divide Factor PRDIV 0 * Divide Factor PRDIV 0 Divide Factor PRDIV 0 Divide Factor PRDIV 0 Divide Factor * 00000 1 01000 9 10000 17 11000 25 00001 2 01001 10 10001 18 11001 Reserved * 00010 3 01010 11 10010 19 11010 Reserved 00011 4 01011 12 10011 20 11011 Reserved * 00100 5 01100 13 10100 21 11100 Reserved 00101 6 01101 14 10101 22 11101 * Reserved 00110 7 01110 15 10110 23 11110 Reserved 00111 8 01111 16 10111 24 11111 * Reserved */ /*@{*/ #define BP_MCG_C5_PRDIV0 (0U) /*!< Bit position for MCG_C5_PRDIV0. */ #define BM_MCG_C5_PRDIV0 (0x1FU) /*!< Bit mask for MCG_C5_PRDIV0. */ #define BS_MCG_C5_PRDIV0 (5U) /*!< Bit field size in bits for MCG_C5_PRDIV0. */ /*! @brief Read current value of the MCG_C5_PRDIV0 field. */ #define BR_MCG_C5_PRDIV0(x) (HW_MCG_C5(x).B.PRDIV0) /*! @brief Format value for bitfield MCG_C5_PRDIV0. */ #define BF_MCG_C5_PRDIV0(v) ((uint8_t)((uint8_t)(v) << BP_MCG_C5_PRDIV0) & BM_MCG_C5_PRDIV0) /*! @brief Set the PRDIV0 field to a new value. */ #define BW_MCG_C5_PRDIV0(x, v) (HW_MCG_C5_WR(x, (HW_MCG_C5_RD(x) & ~BM_MCG_C5_PRDIV0) | BF_MCG_C5_PRDIV0(v))) /*@}*/ /*! * @name Register MCG_C5, field PLLSTEN0[5] (RW) * * Enables the PLL Clock during Normal Stop. In Low Power Stop mode, the PLL * clock gets disabled even if PLLSTEN 0 =1. All other power modes, PLLSTEN 0 bit * has no affect and does not enable the PLL Clock to run if it is written to 1. * * Values: * - 0 - MCGPLLCLK is disabled in any of the Stop modes. * - 1 - MCGPLLCLK is enabled if system is in Normal Stop mode. */ /*@{*/ #define BP_MCG_C5_PLLSTEN0 (5U) /*!< Bit position for MCG_C5_PLLSTEN0. */ #define BM_MCG_C5_PLLSTEN0 (0x20U) /*!< Bit mask for MCG_C5_PLLSTEN0. */ #define BS_MCG_C5_PLLSTEN0 (1U) /*!< Bit field size in bits for MCG_C5_PLLSTEN0. */ /*! @brief Read current value of the MCG_C5_PLLSTEN0 field. */ #define BR_MCG_C5_PLLSTEN0(x) (BITBAND_ACCESS8(HW_MCG_C5_ADDR(x), BP_MCG_C5_PLLSTEN0)) /*! @brief Format value for bitfield MCG_C5_PLLSTEN0. */ #define BF_MCG_C5_PLLSTEN0(v) ((uint8_t)((uint8_t)(v) << BP_MCG_C5_PLLSTEN0) & BM_MCG_C5_PLLSTEN0) /*! @brief Set the PLLSTEN0 field to a new value. */ #define BW_MCG_C5_PLLSTEN0(x, v) (BITBAND_ACCESS8(HW_MCG_C5_ADDR(x), BP_MCG_C5_PLLSTEN0) = (v)) /*@}*/ /*! * @name Register MCG_C5, field PLLCLKEN0[6] (RW) * * Enables the PLL independent of PLLS and enables the PLL clock for use as * MCGPLLCLK. (PRDIV 0 needs to be programmed to the correct divider to generate a * PLL reference clock in the range of 2 - 4 MHz range prior to setting the * PLLCLKEN 0 bit). Setting PLLCLKEN 0 will enable the external oscillator if not * already enabled. Whenever the PLL is being enabled by means of the PLLCLKEN 0 bit, * and the external oscillator is being used as the reference clock, the OSCINIT 0 * bit should be checked to make sure it is set. * * Values: * - 0 - MCGPLLCLK is inactive. * - 1 - MCGPLLCLK is active. */ /*@{*/ #define BP_MCG_C5_PLLCLKEN0 (6U) /*!< Bit position for MCG_C5_PLLCLKEN0. */ #define BM_MCG_C5_PLLCLKEN0 (0x40U) /*!< Bit mask for MCG_C5_PLLCLKEN0. */ #define BS_MCG_C5_PLLCLKEN0 (1U) /*!< Bit field size in bits for MCG_C5_PLLCLKEN0. */ /*! @brief Read current value of the MCG_C5_PLLCLKEN0 field. */ #define BR_MCG_C5_PLLCLKEN0(x) (BITBAND_ACCESS8(HW_MCG_C5_ADDR(x), BP_MCG_C5_PLLCLKEN0)) /*! @brief Format value for bitfield MCG_C5_PLLCLKEN0. */ #define BF_MCG_C5_PLLCLKEN0(v) ((uint8_t)((uint8_t)(v) << BP_MCG_C5_PLLCLKEN0) & BM_MCG_C5_PLLCLKEN0) /*! @brief Set the PLLCLKEN0 field to a new value. */ #define BW_MCG_C5_PLLCLKEN0(x, v) (BITBAND_ACCESS8(HW_MCG_C5_ADDR(x), BP_MCG_C5_PLLCLKEN0) = (v)) /*@}*/ /******************************************************************************* * HW_MCG_C6 - MCG Control 6 Register ******************************************************************************/ /*! * @brief HW_MCG_C6 - MCG Control 6 Register (RW) * * Reset value: 0x00U */ typedef union _hw_mcg_c6 { uint8_t U; struct _hw_mcg_c6_bitfields { uint8_t VDIV0 : 5; /*!< [4:0] VCO 0 Divider */ uint8_t CME0 : 1; /*!< [5] Clock Monitor Enable */ uint8_t PLLS : 1; /*!< [6] PLL Select */ uint8_t LOLIE0 : 1; /*!< [7] Loss of Lock Interrrupt Enable */ } B; } hw_mcg_c6_t; /*! * @name Constants and macros for entire MCG_C6 register */ /*@{*/ #define HW_MCG_C6_ADDR(x) ((x) + 0x5U) #define HW_MCG_C6(x) (*(__IO hw_mcg_c6_t *) HW_MCG_C6_ADDR(x)) #define HW_MCG_C6_RD(x) (HW_MCG_C6(x).U) #define HW_MCG_C6_WR(x, v) (HW_MCG_C6(x).U = (v)) #define HW_MCG_C6_SET(x, v) (HW_MCG_C6_WR(x, HW_MCG_C6_RD(x) | (v))) #define HW_MCG_C6_CLR(x, v) (HW_MCG_C6_WR(x, HW_MCG_C6_RD(x) & ~(v))) #define HW_MCG_C6_TOG(x, v) (HW_MCG_C6_WR(x, HW_MCG_C6_RD(x) ^ (v))) /*@}*/ /* * Constants & macros for individual MCG_C6 bitfields */ /*! * @name Register MCG_C6, field VDIV0[4:0] (RW) * * Selects the amount to divide the VCO output of the PLL. The VDIV 0 bits * establish the multiplication factor (M) applied to the reference clock frequency. * After the PLL is enabled (by setting either PLLCLKEN 0 or PLLS), the VDIV 0 * value must not be changed when LOCK 0 is zero. PLL VCO Divide Factor VDIV 0 * Multiply Factor VDIV 0 Multiply Factor VDIV 0 Multiply Factor VDIV 0 Multiply * Factor 00000 24 01000 32 10000 40 11000 48 00001 25 01001 33 10001 41 11001 49 * 00010 26 01010 34 10010 42 11010 50 00011 27 01011 35 10011 43 11011 51 00100 28 * 01100 36 10100 44 11100 52 00101 29 01101 37 10101 45 11101 53 00110 30 01110 * 38 10110 46 11110 54 00111 31 01111 39 10111 47 11111 55 */ /*@{*/ #define BP_MCG_C6_VDIV0 (0U) /*!< Bit position for MCG_C6_VDIV0. */ #define BM_MCG_C6_VDIV0 (0x1FU) /*!< Bit mask for MCG_C6_VDIV0. */ #define BS_MCG_C6_VDIV0 (5U) /*!< Bit field size in bits for MCG_C6_VDIV0. */ /*! @brief Read current value of the MCG_C6_VDIV0 field. */ #define BR_MCG_C6_VDIV0(x) (HW_MCG_C6(x).B.VDIV0) /*! @brief Format value for bitfield MCG_C6_VDIV0. */ #define BF_MCG_C6_VDIV0(v) ((uint8_t)((uint8_t)(v) << BP_MCG_C6_VDIV0) & BM_MCG_C6_VDIV0) /*! @brief Set the VDIV0 field to a new value. */ #define BW_MCG_C6_VDIV0(x, v) (HW_MCG_C6_WR(x, (HW_MCG_C6_RD(x) & ~BM_MCG_C6_VDIV0) | BF_MCG_C6_VDIV0(v))) /*@}*/ /*! * @name Register MCG_C6, field CME0[5] (RW) * * Enables the loss of clock monitoring circuit for the OSC0 external reference * mux select. The LOCRE0 bit will determine if a interrupt or a reset request is * generated following a loss of OSC0 indication. The CME0 bit must only be set * to a logic 1 when the MCG is in an operational mode that uses the external * clock (FEE, FBE, PEE, PBE, or BLPE) . Whenever the CME0 bit is set to a logic 1, * the value of the RANGE0 bits in the C2 register should not be changed. CME0 * bit should be set to a logic 0 before the MCG enters any Stop mode. Otherwise, a * reset request may occur while in Stop mode. CME0 should also be set to a * logic 0 before entering VLPR or VLPW power modes if the MCG is in BLPE mode. * * Values: * - 0 - External clock monitor is disabled for OSC0. * - 1 - External clock monitor is enabled for OSC0. */ /*@{*/ #define BP_MCG_C6_CME0 (5U) /*!< Bit position for MCG_C6_CME0. */ #define BM_MCG_C6_CME0 (0x20U) /*!< Bit mask for MCG_C6_CME0. */ #define BS_MCG_C6_CME0 (1U) /*!< Bit field size in bits for MCG_C6_CME0. */ /*! @brief Read current value of the MCG_C6_CME0 field. */ #define BR_MCG_C6_CME0(x) (BITBAND_ACCESS8(HW_MCG_C6_ADDR(x), BP_MCG_C6_CME0)) /*! @brief Format value for bitfield MCG_C6_CME0. */ #define BF_MCG_C6_CME0(v) ((uint8_t)((uint8_t)(v) << BP_MCG_C6_CME0) & BM_MCG_C6_CME0) /*! @brief Set the CME0 field to a new value. */ #define BW_MCG_C6_CME0(x, v) (BITBAND_ACCESS8(HW_MCG_C6_ADDR(x), BP_MCG_C6_CME0) = (v)) /*@}*/ /*! * @name Register MCG_C6, field PLLS[6] (RW) * * Controls whether the PLL or FLL output is selected as the MCG source when * CLKS[1:0]=00. If the PLLS bit is cleared and PLLCLKEN 0 is not set, the PLL is * disabled in all modes. If the PLLS is set, the FLL is disabled in all modes. * * Values: * - 0 - FLL is selected. * - 1 - PLL is selected (PRDIV 0 need to be programmed to the correct divider * to generate a PLL reference clock in the range of 2-4 MHz prior to setting * the PLLS bit). */ /*@{*/ #define BP_MCG_C6_PLLS (6U) /*!< Bit position for MCG_C6_PLLS. */ #define BM_MCG_C6_PLLS (0x40U) /*!< Bit mask for MCG_C6_PLLS. */ #define BS_MCG_C6_PLLS (1U) /*!< Bit field size in bits for MCG_C6_PLLS. */ /*! @brief Read current value of the MCG_C6_PLLS field. */ #define BR_MCG_C6_PLLS(x) (BITBAND_ACCESS8(HW_MCG_C6_ADDR(x), BP_MCG_C6_PLLS)) /*! @brief Format value for bitfield MCG_C6_PLLS. */ #define BF_MCG_C6_PLLS(v) ((uint8_t)((uint8_t)(v) << BP_MCG_C6_PLLS) & BM_MCG_C6_PLLS) /*! @brief Set the PLLS field to a new value. */ #define BW_MCG_C6_PLLS(x, v) (BITBAND_ACCESS8(HW_MCG_C6_ADDR(x), BP_MCG_C6_PLLS) = (v)) /*@}*/ /*! * @name Register MCG_C6, field LOLIE0[7] (RW) * * Determines if an interrupt request is made following a loss of lock * indication. This bit only has an effect when LOLS 0 is set. * * Values: * - 0 - No interrupt request is generated on loss of lock. * - 1 - Generate an interrupt request on loss of lock. */ /*@{*/ #define BP_MCG_C6_LOLIE0 (7U) /*!< Bit position for MCG_C6_LOLIE0. */ #define BM_MCG_C6_LOLIE0 (0x80U) /*!< Bit mask for MCG_C6_LOLIE0. */ #define BS_MCG_C6_LOLIE0 (1U) /*!< Bit field size in bits for MCG_C6_LOLIE0. */ /*! @brief Read current value of the MCG_C6_LOLIE0 field. */ #define BR_MCG_C6_LOLIE0(x) (BITBAND_ACCESS8(HW_MCG_C6_ADDR(x), BP_MCG_C6_LOLIE0)) /*! @brief Format value for bitfield MCG_C6_LOLIE0. */ #define BF_MCG_C6_LOLIE0(v) ((uint8_t)((uint8_t)(v) << BP_MCG_C6_LOLIE0) & BM_MCG_C6_LOLIE0) /*! @brief Set the LOLIE0 field to a new value. */ #define BW_MCG_C6_LOLIE0(x, v) (BITBAND_ACCESS8(HW_MCG_C6_ADDR(x), BP_MCG_C6_LOLIE0) = (v)) /*@}*/ /******************************************************************************* * HW_MCG_S - MCG Status Register ******************************************************************************/ /*! * @brief HW_MCG_S - MCG Status Register (RW) * * Reset value: 0x10U */ typedef union _hw_mcg_s { uint8_t U; struct _hw_mcg_s_bitfields { uint8_t IRCST : 1; /*!< [0] Internal Reference Clock Status */ uint8_t OSCINIT0 : 1; /*!< [1] OSC Initialization */ uint8_t CLKST : 2; /*!< [3:2] Clock Mode Status */ uint8_t IREFST : 1; /*!< [4] Internal Reference Status */ uint8_t PLLST : 1; /*!< [5] PLL Select Status */ uint8_t LOCK0 : 1; /*!< [6] Lock Status */ uint8_t LOLS0 : 1; /*!< [7] Loss of Lock Status */ } B; } hw_mcg_s_t; /*! * @name Constants and macros for entire MCG_S register */ /*@{*/ #define HW_MCG_S_ADDR(x) ((x) + 0x6U) #define HW_MCG_S(x) (*(__IO hw_mcg_s_t *) HW_MCG_S_ADDR(x)) #define HW_MCG_S_RD(x) (HW_MCG_S(x).U) #define HW_MCG_S_WR(x, v) (HW_MCG_S(x).U = (v)) #define HW_MCG_S_SET(x, v) (HW_MCG_S_WR(x, HW_MCG_S_RD(x) | (v))) #define HW_MCG_S_CLR(x, v) (HW_MCG_S_WR(x, HW_MCG_S_RD(x) & ~(v))) #define HW_MCG_S_TOG(x, v) (HW_MCG_S_WR(x, HW_MCG_S_RD(x) ^ (v))) /*@}*/ /* * Constants & macros for individual MCG_S bitfields */ /*! * @name Register MCG_S, field IRCST[0] (RO) * * The IRCST bit indicates the current source for the internal reference clock * select clock (IRCSCLK). The IRCST bit does not update immediately after a write * to the IRCS bit due to internal synchronization between clock domains. The * IRCST bit will only be updated if the internal reference clock is enabled, * either by the MCG being in a mode that uses the IRC or by setting the C1[IRCLKEN] * bit . * * Values: * - 0 - Source of internal reference clock is the slow clock (32 kHz IRC). * - 1 - Source of internal reference clock is the fast clock (4 MHz IRC). */ /*@{*/ #define BP_MCG_S_IRCST (0U) /*!< Bit position for MCG_S_IRCST. */ #define BM_MCG_S_IRCST (0x01U) /*!< Bit mask for MCG_S_IRCST. */ #define BS_MCG_S_IRCST (1U) /*!< Bit field size in bits for MCG_S_IRCST. */ /*! @brief Read current value of the MCG_S_IRCST field. */ #define BR_MCG_S_IRCST(x) (BITBAND_ACCESS8(HW_MCG_S_ADDR(x), BP_MCG_S_IRCST)) /*@}*/ /*! * @name Register MCG_S, field OSCINIT0[1] (RO) * * This bit, which resets to 0, is set to 1 after the initialization cycles of * the crystal oscillator clock have completed. After being set, the bit is * cleared to 0 if the OSC is subsequently disabled. See the OSC module's detailed * description for more information. */ /*@{*/ #define BP_MCG_S_OSCINIT0 (1U) /*!< Bit position for MCG_S_OSCINIT0. */ #define BM_MCG_S_OSCINIT0 (0x02U) /*!< Bit mask for MCG_S_OSCINIT0. */ #define BS_MCG_S_OSCINIT0 (1U) /*!< Bit field size in bits for MCG_S_OSCINIT0. */ /*! @brief Read current value of the MCG_S_OSCINIT0 field. */ #define BR_MCG_S_OSCINIT0(x) (BITBAND_ACCESS8(HW_MCG_S_ADDR(x), BP_MCG_S_OSCINIT0)) /*@}*/ /*! * @name Register MCG_S, field CLKST[3:2] (RO) * * These bits indicate the current clock mode. The CLKST bits do not update * immediately after a write to the CLKS bits due to internal synchronization between * clock domains. * * Values: * - 00 - Encoding 0 - Output of the FLL is selected (reset default). * - 01 - Encoding 1 - Internal reference clock is selected. * - 10 - Encoding 2 - External reference clock is selected. * - 11 - Encoding 3 - Output of the PLL is selected. */ /*@{*/ #define BP_MCG_S_CLKST (2U) /*!< Bit position for MCG_S_CLKST. */ #define BM_MCG_S_CLKST (0x0CU) /*!< Bit mask for MCG_S_CLKST. */ #define BS_MCG_S_CLKST (2U) /*!< Bit field size in bits for MCG_S_CLKST. */ /*! @brief Read current value of the MCG_S_CLKST field. */ #define BR_MCG_S_CLKST(x) (HW_MCG_S(x).B.CLKST) /*@}*/ /*! * @name Register MCG_S, field IREFST[4] (RO) * * This bit indicates the current source for the FLL reference clock. The IREFST * bit does not update immediately after a write to the IREFS bit due to * internal synchronization between clock domains. * * Values: * - 0 - Source of FLL reference clock is the external reference clock. * - 1 - Source of FLL reference clock is the internal reference clock. */ /*@{*/ #define BP_MCG_S_IREFST (4U) /*!< Bit position for MCG_S_IREFST. */ #define BM_MCG_S_IREFST (0x10U) /*!< Bit mask for MCG_S_IREFST. */ #define BS_MCG_S_IREFST (1U) /*!< Bit field size in bits for MCG_S_IREFST. */ /*! @brief Read current value of the MCG_S_IREFST field. */ #define BR_MCG_S_IREFST(x) (BITBAND_ACCESS8(HW_MCG_S_ADDR(x), BP_MCG_S_IREFST)) /*@}*/ /*! * @name Register MCG_S, field PLLST[5] (RO) * * This bit indicates the clock source selected by PLLS . The PLLST bit does not * update immediately after a write to the PLLS bit due to internal * synchronization between clock domains. * * Values: * - 0 - Source of PLLS clock is FLL clock. * - 1 - Source of PLLS clock is PLL output clock. */ /*@{*/ #define BP_MCG_S_PLLST (5U) /*!< Bit position for MCG_S_PLLST. */ #define BM_MCG_S_PLLST (0x20U) /*!< Bit mask for MCG_S_PLLST. */ #define BS_MCG_S_PLLST (1U) /*!< Bit field size in bits for MCG_S_PLLST. */ /*! @brief Read current value of the MCG_S_PLLST field. */ #define BR_MCG_S_PLLST(x) (BITBAND_ACCESS8(HW_MCG_S_ADDR(x), BP_MCG_S_PLLST)) /*@}*/ /*! * @name Register MCG_S, field LOCK0[6] (RO) * * This bit indicates whether the PLL has acquired lock. Lock detection is only * enabled when the PLL is enabled (either through clock mode selection or * PLLCLKEN0=1 setting). While the PLL clock is locking to the desired frequency, the * MCG PLL clock (MCGPLLCLK) will be gated off until the LOCK bit gets asserted. * If the lock status bit is set, changing the value of the PRDIV0 [4:0] bits in * the C5 register or the VDIV0[4:0] bits in the C6 register causes the lock * status bit to clear and stay cleared until the PLL has reacquired lock. Loss of PLL * reference clock will also cause the LOCK0 bit to clear until the PLL has * reacquired lock. Entry into LLS, VLPS, or regular Stop with PLLSTEN=0 also causes * the lock status bit to clear and stay cleared until the Stop mode is exited * and the PLL has reacquired lock. Any time the PLL is enabled and the LOCK0 bit * is cleared, the MCGPLLCLK will be gated off until the LOCK0 bit is asserted * again. * * Values: * - 0 - PLL is currently unlocked. * - 1 - PLL is currently locked. */ /*@{*/ #define BP_MCG_S_LOCK0 (6U) /*!< Bit position for MCG_S_LOCK0. */ #define BM_MCG_S_LOCK0 (0x40U) /*!< Bit mask for MCG_S_LOCK0. */ #define BS_MCG_S_LOCK0 (1U) /*!< Bit field size in bits for MCG_S_LOCK0. */ /*! @brief Read current value of the MCG_S_LOCK0 field. */ #define BR_MCG_S_LOCK0(x) (BITBAND_ACCESS8(HW_MCG_S_ADDR(x), BP_MCG_S_LOCK0)) /*@}*/ /*! * @name Register MCG_S, field LOLS0[7] (W1C) * * This bit is a sticky bit indicating the lock status for the PLL. LOLS is set * if after acquiring lock, the PLL output frequency has fallen outside the lock * exit frequency tolerance, D unl . LOLIE determines whether an interrupt * request is made when LOLS is set. LOLRE determines whether a reset request is made * when LOLS is set. This bit is cleared by reset or by writing a logic 1 to it * when set. Writing a logic 0 to this bit has no effect. * * Values: * - 0 - PLL has not lost lock since LOLS 0 was last cleared. * - 1 - PLL has lost lock since LOLS 0 was last cleared. */ /*@{*/ #define BP_MCG_S_LOLS0 (7U) /*!< Bit position for MCG_S_LOLS0. */ #define BM_MCG_S_LOLS0 (0x80U) /*!< Bit mask for MCG_S_LOLS0. */ #define BS_MCG_S_LOLS0 (1U) /*!< Bit field size in bits for MCG_S_LOLS0. */ /*! @brief Read current value of the MCG_S_LOLS0 field. */ #define BR_MCG_S_LOLS0(x) (BITBAND_ACCESS8(HW_MCG_S_ADDR(x), BP_MCG_S_LOLS0)) /*! @brief Format value for bitfield MCG_S_LOLS0. */ #define BF_MCG_S_LOLS0(v) ((uint8_t)((uint8_t)(v) << BP_MCG_S_LOLS0) & BM_MCG_S_LOLS0) /*! @brief Set the LOLS0 field to a new value. */ #define BW_MCG_S_LOLS0(x, v) (BITBAND_ACCESS8(HW_MCG_S_ADDR(x), BP_MCG_S_LOLS0) = (v)) /*@}*/ /******************************************************************************* * HW_MCG_SC - MCG Status and Control Register ******************************************************************************/ /*! * @brief HW_MCG_SC - MCG Status and Control Register (RW) * * Reset value: 0x02U */ typedef union _hw_mcg_sc { uint8_t U; struct _hw_mcg_sc_bitfields { uint8_t LOCS0 : 1; /*!< [0] OSC0 Loss of Clock Status */ uint8_t FCRDIV : 3; /*!< [3:1] Fast Clock Internal Reference Divider * */ uint8_t FLTPRSRV : 1; /*!< [4] FLL Filter Preserve Enable */ uint8_t ATMF : 1; /*!< [5] Automatic Trim Machine Fail Flag */ uint8_t ATMS : 1; /*!< [6] Automatic Trim Machine Select */ uint8_t ATME : 1; /*!< [7] Automatic Trim Machine Enable */ } B; } hw_mcg_sc_t; /*! * @name Constants and macros for entire MCG_SC register */ /*@{*/ #define HW_MCG_SC_ADDR(x) ((x) + 0x8U) #define HW_MCG_SC(x) (*(__IO hw_mcg_sc_t *) HW_MCG_SC_ADDR(x)) #define HW_MCG_SC_RD(x) (HW_MCG_SC(x).U) #define HW_MCG_SC_WR(x, v) (HW_MCG_SC(x).U = (v)) #define HW_MCG_SC_SET(x, v) (HW_MCG_SC_WR(x, HW_MCG_SC_RD(x) | (v))) #define HW_MCG_SC_CLR(x, v) (HW_MCG_SC_WR(x, HW_MCG_SC_RD(x) & ~(v))) #define HW_MCG_SC_TOG(x, v) (HW_MCG_SC_WR(x, HW_MCG_SC_RD(x) ^ (v))) /*@}*/ /* * Constants & macros for individual MCG_SC bitfields */ /*! * @name Register MCG_SC, field LOCS0[0] (W1C) * * The LOCS0 indicates when a loss of OSC0 reference clock has occurred. The * LOCS0 bit only has an effect when CME0 is set. This bit is cleared by writing a * logic 1 to it when set. * * Values: * - 0 - Loss of OSC0 has not occurred. * - 1 - Loss of OSC0 has occurred. */ /*@{*/ #define BP_MCG_SC_LOCS0 (0U) /*!< Bit position for MCG_SC_LOCS0. */ #define BM_MCG_SC_LOCS0 (0x01U) /*!< Bit mask for MCG_SC_LOCS0. */ #define BS_MCG_SC_LOCS0 (1U) /*!< Bit field size in bits for MCG_SC_LOCS0. */ /*! @brief Read current value of the MCG_SC_LOCS0 field. */ #define BR_MCG_SC_LOCS0(x) (BITBAND_ACCESS8(HW_MCG_SC_ADDR(x), BP_MCG_SC_LOCS0)) /*! @brief Format value for bitfield MCG_SC_LOCS0. */ #define BF_MCG_SC_LOCS0(v) ((uint8_t)((uint8_t)(v) << BP_MCG_SC_LOCS0) & BM_MCG_SC_LOCS0) /*! @brief Set the LOCS0 field to a new value. */ #define BW_MCG_SC_LOCS0(x, v) (BITBAND_ACCESS8(HW_MCG_SC_ADDR(x), BP_MCG_SC_LOCS0) = (v)) /*@}*/ /*! * @name Register MCG_SC, field FCRDIV[3:1] (RW) * * Selects the amount to divide down the fast internal reference clock. The * resulting frequency will be in the range 31.25 kHz to 4 MHz (Note: Changing the * divider when the Fast IRC is enabled is not supported). * * Values: * - 000 - Divide Factor is 1 * - 001 - Divide Factor is 2. * - 010 - Divide Factor is 4. * - 011 - Divide Factor is 8. * - 100 - Divide Factor is 16 * - 101 - Divide Factor is 32 * - 110 - Divide Factor is 64 * - 111 - Divide Factor is 128. */ /*@{*/ #define BP_MCG_SC_FCRDIV (1U) /*!< Bit position for MCG_SC_FCRDIV. */ #define BM_MCG_SC_FCRDIV (0x0EU) /*!< Bit mask for MCG_SC_FCRDIV. */ #define BS_MCG_SC_FCRDIV (3U) /*!< Bit field size in bits for MCG_SC_FCRDIV. */ /*! @brief Read current value of the MCG_SC_FCRDIV field. */ #define BR_MCG_SC_FCRDIV(x) (HW_MCG_SC(x).B.FCRDIV) /*! @brief Format value for bitfield MCG_SC_FCRDIV. */ #define BF_MCG_SC_FCRDIV(v) ((uint8_t)((uint8_t)(v) << BP_MCG_SC_FCRDIV) & BM_MCG_SC_FCRDIV) /*! @brief Set the FCRDIV field to a new value. */ #define BW_MCG_SC_FCRDIV(x, v) (HW_MCG_SC_WR(x, (HW_MCG_SC_RD(x) & ~BM_MCG_SC_FCRDIV) | BF_MCG_SC_FCRDIV(v))) /*@}*/ /*! * @name Register MCG_SC, field FLTPRSRV[4] (RW) * * This bit will prevent the FLL filter values from resetting allowing the FLL * output frequency to remain the same during clock mode changes where the FLL/DCO * output is still valid. (Note: This requires that the FLL reference frequency * to remain the same as what it was prior to the new clock mode switch. * Otherwise FLL filter and frequency values will change.) * * Values: * - 0 - FLL filter and FLL frequency will reset on changes to currect clock * mode. * - 1 - Fll filter and FLL frequency retain their previous values during new * clock mode change. */ /*@{*/ #define BP_MCG_SC_FLTPRSRV (4U) /*!< Bit position for MCG_SC_FLTPRSRV. */ #define BM_MCG_SC_FLTPRSRV (0x10U) /*!< Bit mask for MCG_SC_FLTPRSRV. */ #define BS_MCG_SC_FLTPRSRV (1U) /*!< Bit field size in bits for MCG_SC_FLTPRSRV. */ /*! @brief Read current value of the MCG_SC_FLTPRSRV field. */ #define BR_MCG_SC_FLTPRSRV(x) (BITBAND_ACCESS8(HW_MCG_SC_ADDR(x), BP_MCG_SC_FLTPRSRV)) /*! @brief Format value for bitfield MCG_SC_FLTPRSRV. */ #define BF_MCG_SC_FLTPRSRV(v) ((uint8_t)((uint8_t)(v) << BP_MCG_SC_FLTPRSRV) & BM_MCG_SC_FLTPRSRV) /*! @brief Set the FLTPRSRV field to a new value. */ #define BW_MCG_SC_FLTPRSRV(x, v) (BITBAND_ACCESS8(HW_MCG_SC_ADDR(x), BP_MCG_SC_FLTPRSRV) = (v)) /*@}*/ /*! * @name Register MCG_SC, field ATMF[5] (RW) * * Fail flag for the Automatic Trim Machine (ATM). This bit asserts when the * Automatic Trim Machine is enabled, ATME=1, and a write to the C1, C3, C4, and SC * registers is detected or the MCG enters into any Stop mode. A write to ATMF * clears the flag. * * Values: * - 0 - Automatic Trim Machine completed normally. * - 1 - Automatic Trim Machine failed. */ /*@{*/ #define BP_MCG_SC_ATMF (5U) /*!< Bit position for MCG_SC_ATMF. */ #define BM_MCG_SC_ATMF (0x20U) /*!< Bit mask for MCG_SC_ATMF. */ #define BS_MCG_SC_ATMF (1U) /*!< Bit field size in bits for MCG_SC_ATMF. */ /*! @brief Read current value of the MCG_SC_ATMF field. */ #define BR_MCG_SC_ATMF(x) (BITBAND_ACCESS8(HW_MCG_SC_ADDR(x), BP_MCG_SC_ATMF)) /*! @brief Format value for bitfield MCG_SC_ATMF. */ #define BF_MCG_SC_ATMF(v) ((uint8_t)((uint8_t)(v) << BP_MCG_SC_ATMF) & BM_MCG_SC_ATMF) /*! @brief Set the ATMF field to a new value. */ #define BW_MCG_SC_ATMF(x, v) (BITBAND_ACCESS8(HW_MCG_SC_ADDR(x), BP_MCG_SC_ATMF) = (v)) /*@}*/ /*! * @name Register MCG_SC, field ATMS[6] (RW) * * Selects the IRCS clock for Auto Trim Test. * * Values: * - 0 - 32 kHz Internal Reference Clock selected. * - 1 - 4 MHz Internal Reference Clock selected. */ /*@{*/ #define BP_MCG_SC_ATMS (6U) /*!< Bit position for MCG_SC_ATMS. */ #define BM_MCG_SC_ATMS (0x40U) /*!< Bit mask for MCG_SC_ATMS. */ #define BS_MCG_SC_ATMS (1U) /*!< Bit field size in bits for MCG_SC_ATMS. */ /*! @brief Read current value of the MCG_SC_ATMS field. */ #define BR_MCG_SC_ATMS(x) (BITBAND_ACCESS8(HW_MCG_SC_ADDR(x), BP_MCG_SC_ATMS)) /*! @brief Format value for bitfield MCG_SC_ATMS. */ #define BF_MCG_SC_ATMS(v) ((uint8_t)((uint8_t)(v) << BP_MCG_SC_ATMS) & BM_MCG_SC_ATMS) /*! @brief Set the ATMS field to a new value. */ #define BW_MCG_SC_ATMS(x, v) (BITBAND_ACCESS8(HW_MCG_SC_ADDR(x), BP_MCG_SC_ATMS) = (v)) /*@}*/ /*! * @name Register MCG_SC, field ATME[7] (RW) * * Enables the Auto Trim Machine to start automatically trimming the selected * Internal Reference Clock. ATME deasserts after the Auto Trim Machine has * completed trimming all trim bits of the IRCS clock selected by the ATMS bit. Writing * to C1, C3, C4, and SC registers or entering Stop mode aborts the auto trim * operation and clears this bit. * * Values: * - 0 - Auto Trim Machine disabled. * - 1 - Auto Trim Machine enabled. */ /*@{*/ #define BP_MCG_SC_ATME (7U) /*!< Bit position for MCG_SC_ATME. */ #define BM_MCG_SC_ATME (0x80U) /*!< Bit mask for MCG_SC_ATME. */ #define BS_MCG_SC_ATME (1U) /*!< Bit field size in bits for MCG_SC_ATME. */ /*! @brief Read current value of the MCG_SC_ATME field. */ #define BR_MCG_SC_ATME(x) (BITBAND_ACCESS8(HW_MCG_SC_ADDR(x), BP_MCG_SC_ATME)) /*! @brief Format value for bitfield MCG_SC_ATME. */ #define BF_MCG_SC_ATME(v) ((uint8_t)((uint8_t)(v) << BP_MCG_SC_ATME) & BM_MCG_SC_ATME) /*! @brief Set the ATME field to a new value. */ #define BW_MCG_SC_ATME(x, v) (BITBAND_ACCESS8(HW_MCG_SC_ADDR(x), BP_MCG_SC_ATME) = (v)) /*@}*/ /******************************************************************************* * HW_MCG_ATCVH - MCG Auto Trim Compare Value High Register ******************************************************************************/ /*! * @brief HW_MCG_ATCVH - MCG Auto Trim Compare Value High Register (RW) * * Reset value: 0x00U */ typedef union _hw_mcg_atcvh { uint8_t U; struct _hw_mcg_atcvh_bitfields { uint8_t ATCVH : 8; /*!< [7:0] ATM Compare Value High */ } B; } hw_mcg_atcvh_t; /*! * @name Constants and macros for entire MCG_ATCVH register */ /*@{*/ #define HW_MCG_ATCVH_ADDR(x) ((x) + 0xAU) #define HW_MCG_ATCVH(x) (*(__IO hw_mcg_atcvh_t *) HW_MCG_ATCVH_ADDR(x)) #define HW_MCG_ATCVH_RD(x) (HW_MCG_ATCVH(x).U) #define HW_MCG_ATCVH_WR(x, v) (HW_MCG_ATCVH(x).U = (v)) #define HW_MCG_ATCVH_SET(x, v) (HW_MCG_ATCVH_WR(x, HW_MCG_ATCVH_RD(x) | (v))) #define HW_MCG_ATCVH_CLR(x, v) (HW_MCG_ATCVH_WR(x, HW_MCG_ATCVH_RD(x) & ~(v))) #define HW_MCG_ATCVH_TOG(x, v) (HW_MCG_ATCVH_WR(x, HW_MCG_ATCVH_RD(x) ^ (v))) /*@}*/ /* * Constants & macros for individual MCG_ATCVH bitfields */ /*! * @name Register MCG_ATCVH, field ATCVH[7:0] (RW) * * Values are used by Auto Trim Machine to compare and adjust Internal Reference * trim values during ATM SAR conversion. */ /*@{*/ #define BP_MCG_ATCVH_ATCVH (0U) /*!< Bit position for MCG_ATCVH_ATCVH. */ #define BM_MCG_ATCVH_ATCVH (0xFFU) /*!< Bit mask for MCG_ATCVH_ATCVH. */ #define BS_MCG_ATCVH_ATCVH (8U) /*!< Bit field size in bits for MCG_ATCVH_ATCVH. */ /*! @brief Read current value of the MCG_ATCVH_ATCVH field. */ #define BR_MCG_ATCVH_ATCVH(x) (HW_MCG_ATCVH(x).U) /*! @brief Format value for bitfield MCG_ATCVH_ATCVH. */ #define BF_MCG_ATCVH_ATCVH(v) ((uint8_t)((uint8_t)(v) << BP_MCG_ATCVH_ATCVH) & BM_MCG_ATCVH_ATCVH) /*! @brief Set the ATCVH field to a new value. */ #define BW_MCG_ATCVH_ATCVH(x, v) (HW_MCG_ATCVH_WR(x, v)) /*@}*/ /******************************************************************************* * HW_MCG_ATCVL - MCG Auto Trim Compare Value Low Register ******************************************************************************/ /*! * @brief HW_MCG_ATCVL - MCG Auto Trim Compare Value Low Register (RW) * * Reset value: 0x00U */ typedef union _hw_mcg_atcvl { uint8_t U; struct _hw_mcg_atcvl_bitfields { uint8_t ATCVL : 8; /*!< [7:0] ATM Compare Value Low */ } B; } hw_mcg_atcvl_t; /*! * @name Constants and macros for entire MCG_ATCVL register */ /*@{*/ #define HW_MCG_ATCVL_ADDR(x) ((x) + 0xBU) #define HW_MCG_ATCVL(x) (*(__IO hw_mcg_atcvl_t *) HW_MCG_ATCVL_ADDR(x)) #define HW_MCG_ATCVL_RD(x) (HW_MCG_ATCVL(x).U) #define HW_MCG_ATCVL_WR(x, v) (HW_MCG_ATCVL(x).U = (v)) #define HW_MCG_ATCVL_SET(x, v) (HW_MCG_ATCVL_WR(x, HW_MCG_ATCVL_RD(x) | (v))) #define HW_MCG_ATCVL_CLR(x, v) (HW_MCG_ATCVL_WR(x, HW_MCG_ATCVL_RD(x) & ~(v))) #define HW_MCG_ATCVL_TOG(x, v) (HW_MCG_ATCVL_WR(x, HW_MCG_ATCVL_RD(x) ^ (v))) /*@}*/ /* * Constants & macros for individual MCG_ATCVL bitfields */ /*! * @name Register MCG_ATCVL, field ATCVL[7:0] (RW) * * Values are used by Auto Trim Machine to compare and adjust Internal Reference * trim values during ATM SAR conversion. */ /*@{*/ #define BP_MCG_ATCVL_ATCVL (0U) /*!< Bit position for MCG_ATCVL_ATCVL. */ #define BM_MCG_ATCVL_ATCVL (0xFFU) /*!< Bit mask for MCG_ATCVL_ATCVL. */ #define BS_MCG_ATCVL_ATCVL (8U) /*!< Bit field size in bits for MCG_ATCVL_ATCVL. */ /*! @brief Read current value of the MCG_ATCVL_ATCVL field. */ #define BR_MCG_ATCVL_ATCVL(x) (HW_MCG_ATCVL(x).U) /*! @brief Format value for bitfield MCG_ATCVL_ATCVL. */ #define BF_MCG_ATCVL_ATCVL(v) ((uint8_t)((uint8_t)(v) << BP_MCG_ATCVL_ATCVL) & BM_MCG_ATCVL_ATCVL) /*! @brief Set the ATCVL field to a new value. */ #define BW_MCG_ATCVL_ATCVL(x, v) (HW_MCG_ATCVL_WR(x, v)) /*@}*/ /******************************************************************************* * HW_MCG_C7 - MCG Control 7 Register ******************************************************************************/ /*! * @brief HW_MCG_C7 - MCG Control 7 Register (RW) * * Reset value: 0x00U */ typedef union _hw_mcg_c7 { uint8_t U; struct _hw_mcg_c7_bitfields { uint8_t OSCSEL : 2; /*!< [1:0] MCG OSC Clock Select */ uint8_t RESERVED0 : 6; /*!< [7:2] */ } B; } hw_mcg_c7_t; /*! * @name Constants and macros for entire MCG_C7 register */ /*@{*/ #define HW_MCG_C7_ADDR(x) ((x) + 0xCU) #define HW_MCG_C7(x) (*(__IO hw_mcg_c7_t *) HW_MCG_C7_ADDR(x)) #define HW_MCG_C7_RD(x) (HW_MCG_C7(x).U) #define HW_MCG_C7_WR(x, v) (HW_MCG_C7(x).U = (v)) #define HW_MCG_C7_SET(x, v) (HW_MCG_C7_WR(x, HW_MCG_C7_RD(x) | (v))) #define HW_MCG_C7_CLR(x, v) (HW_MCG_C7_WR(x, HW_MCG_C7_RD(x) & ~(v))) #define HW_MCG_C7_TOG(x, v) (HW_MCG_C7_WR(x, HW_MCG_C7_RD(x) ^ (v))) /*@}*/ /* * Constants & macros for individual MCG_C7 bitfields */ /*! * @name Register MCG_C7, field OSCSEL[1:0] (RW) * * Selects the MCG FLL external reference clock * * Values: * - 00 - Selects Oscillator (OSCCLK0). * - 01 - Selects 32 kHz RTC Oscillator. * - 10 - Selects Oscillator (OSCCLK1). * - 11 - RESERVED */ /*@{*/ #define BP_MCG_C7_OSCSEL (0U) /*!< Bit position for MCG_C7_OSCSEL. */ #define BM_MCG_C7_OSCSEL (0x03U) /*!< Bit mask for MCG_C7_OSCSEL. */ #define BS_MCG_C7_OSCSEL (2U) /*!< Bit field size in bits for MCG_C7_OSCSEL. */ /*! @brief Read current value of the MCG_C7_OSCSEL field. */ #define BR_MCG_C7_OSCSEL(x) (HW_MCG_C7(x).B.OSCSEL) /*! @brief Format value for bitfield MCG_C7_OSCSEL. */ #define BF_MCG_C7_OSCSEL(v) ((uint8_t)((uint8_t)(v) << BP_MCG_C7_OSCSEL) & BM_MCG_C7_OSCSEL) /*! @brief Set the OSCSEL field to a new value. */ #define BW_MCG_C7_OSCSEL(x, v) (HW_MCG_C7_WR(x, (HW_MCG_C7_RD(x) & ~BM_MCG_C7_OSCSEL) | BF_MCG_C7_OSCSEL(v))) /*@}*/ /******************************************************************************* * HW_MCG_C8 - MCG Control 8 Register ******************************************************************************/ /*! * @brief HW_MCG_C8 - MCG Control 8 Register (RW) * * Reset value: 0x80U */ typedef union _hw_mcg_c8 { uint8_t U; struct _hw_mcg_c8_bitfields { uint8_t LOCS1 : 1; /*!< [0] RTC Loss of Clock Status */ uint8_t RESERVED0 : 4; /*!< [4:1] */ uint8_t CME1 : 1; /*!< [5] Clock Monitor Enable1 */ uint8_t LOLRE : 1; /*!< [6] PLL Loss of Lock Reset Enable */ uint8_t LOCRE1 : 1; /*!< [7] Loss of Clock Reset Enable */ } B; } hw_mcg_c8_t; /*! * @name Constants and macros for entire MCG_C8 register */ /*@{*/ #define HW_MCG_C8_ADDR(x) ((x) + 0xDU) #define HW_MCG_C8(x) (*(__IO hw_mcg_c8_t *) HW_MCG_C8_ADDR(x)) #define HW_MCG_C8_RD(x) (HW_MCG_C8(x).U) #define HW_MCG_C8_WR(x, v) (HW_MCG_C8(x).U = (v)) #define HW_MCG_C8_SET(x, v) (HW_MCG_C8_WR(x, HW_MCG_C8_RD(x) | (v))) #define HW_MCG_C8_CLR(x, v) (HW_MCG_C8_WR(x, HW_MCG_C8_RD(x) & ~(v))) #define HW_MCG_C8_TOG(x, v) (HW_MCG_C8_WR(x, HW_MCG_C8_RD(x) ^ (v))) /*@}*/ /* * Constants & macros for individual MCG_C8 bitfields */ /*! * @name Register MCG_C8, field LOCS1[0] (W1C) * * This bit indicates when a loss of clock has occurred. This bit is cleared by * writing a logic 1 to it when set. * * Values: * - 0 - Loss of RTC has not occur. * - 1 - Loss of RTC has occur */ /*@{*/ #define BP_MCG_C8_LOCS1 (0U) /*!< Bit position for MCG_C8_LOCS1. */ #define BM_MCG_C8_LOCS1 (0x01U) /*!< Bit mask for MCG_C8_LOCS1. */ #define BS_MCG_C8_LOCS1 (1U) /*!< Bit field size in bits for MCG_C8_LOCS1. */ /*! @brief Read current value of the MCG_C8_LOCS1 field. */ #define BR_MCG_C8_LOCS1(x) (BITBAND_ACCESS8(HW_MCG_C8_ADDR(x), BP_MCG_C8_LOCS1)) /*! @brief Format value for bitfield MCG_C8_LOCS1. */ #define BF_MCG_C8_LOCS1(v) ((uint8_t)((uint8_t)(v) << BP_MCG_C8_LOCS1) & BM_MCG_C8_LOCS1) /*! @brief Set the LOCS1 field to a new value. */ #define BW_MCG_C8_LOCS1(x, v) (BITBAND_ACCESS8(HW_MCG_C8_ADDR(x), BP_MCG_C8_LOCS1) = (v)) /*@}*/ /*! * @name Register MCG_C8, field CME1[5] (RW) * * Enables the loss of clock monitoring circuit for the output of the RTC * external reference clock. The LOCRE1 bit will determine whether an interrupt or a * reset request is generated following a loss of RTC clock indication. The CME1 * bit should be set to a logic 1 when the MCG is in an operational mode that uses * the RTC as its external reference clock or if the RTC is operational. CME1 bit * must be set to a logic 0 before the MCG enters any Stop mode. Otherwise, a * reset request may occur when in Stop mode. CME1 should also be set to a logic 0 * before entering VLPR or VLPW power modes. * * Values: * - 0 - External clock monitor is disabled for RTC clock. * - 1 - External clock monitor is enabled for RTC clock. */ /*@{*/ #define BP_MCG_C8_CME1 (5U) /*!< Bit position for MCG_C8_CME1. */ #define BM_MCG_C8_CME1 (0x20U) /*!< Bit mask for MCG_C8_CME1. */ #define BS_MCG_C8_CME1 (1U) /*!< Bit field size in bits for MCG_C8_CME1. */ /*! @brief Read current value of the MCG_C8_CME1 field. */ #define BR_MCG_C8_CME1(x) (BITBAND_ACCESS8(HW_MCG_C8_ADDR(x), BP_MCG_C8_CME1)) /*! @brief Format value for bitfield MCG_C8_CME1. */ #define BF_MCG_C8_CME1(v) ((uint8_t)((uint8_t)(v) << BP_MCG_C8_CME1) & BM_MCG_C8_CME1) /*! @brief Set the CME1 field to a new value. */ #define BW_MCG_C8_CME1(x, v) (BITBAND_ACCESS8(HW_MCG_C8_ADDR(x), BP_MCG_C8_CME1) = (v)) /*@}*/ /*! * @name Register MCG_C8, field LOLRE[6] (RW) * * Determines if an interrupt or a reset request is made following a PLL loss of * lock. * * Values: * - 0 - Interrupt request is generated on a PLL loss of lock indication. The * PLL loss of lock interrupt enable bit must also be set to generate the * interrupt request. * - 1 - Generate a reset request on a PLL loss of lock indication. */ /*@{*/ #define BP_MCG_C8_LOLRE (6U) /*!< Bit position for MCG_C8_LOLRE. */ #define BM_MCG_C8_LOLRE (0x40U) /*!< Bit mask for MCG_C8_LOLRE. */ #define BS_MCG_C8_LOLRE (1U) /*!< Bit field size in bits for MCG_C8_LOLRE. */ /*! @brief Read current value of the MCG_C8_LOLRE field. */ #define BR_MCG_C8_LOLRE(x) (BITBAND_ACCESS8(HW_MCG_C8_ADDR(x), BP_MCG_C8_LOLRE)) /*! @brief Format value for bitfield MCG_C8_LOLRE. */ #define BF_MCG_C8_LOLRE(v) ((uint8_t)((uint8_t)(v) << BP_MCG_C8_LOLRE) & BM_MCG_C8_LOLRE) /*! @brief Set the LOLRE field to a new value. */ #define BW_MCG_C8_LOLRE(x, v) (BITBAND_ACCESS8(HW_MCG_C8_ADDR(x), BP_MCG_C8_LOLRE) = (v)) /*@}*/ /*! * @name Register MCG_C8, field LOCRE1[7] (RW) * * Determines if a interrupt or a reset request is made following a loss of RTC * external reference clock. The LOCRE1 only has an affect when CME1 is set. * * Values: * - 0 - Interrupt request is generated on a loss of RTC external reference * clock. * - 1 - Generate a reset request on a loss of RTC external reference clock */ /*@{*/ #define BP_MCG_C8_LOCRE1 (7U) /*!< Bit position for MCG_C8_LOCRE1. */ #define BM_MCG_C8_LOCRE1 (0x80U) /*!< Bit mask for MCG_C8_LOCRE1. */ #define BS_MCG_C8_LOCRE1 (1U) /*!< Bit field size in bits for MCG_C8_LOCRE1. */ /*! @brief Read current value of the MCG_C8_LOCRE1 field. */ #define BR_MCG_C8_LOCRE1(x) (BITBAND_ACCESS8(HW_MCG_C8_ADDR(x), BP_MCG_C8_LOCRE1)) /*! @brief Format value for bitfield MCG_C8_LOCRE1. */ #define BF_MCG_C8_LOCRE1(v) ((uint8_t)((uint8_t)(v) << BP_MCG_C8_LOCRE1) & BM_MCG_C8_LOCRE1) /*! @brief Set the LOCRE1 field to a new value. */ #define BW_MCG_C8_LOCRE1(x, v) (BITBAND_ACCESS8(HW_MCG_C8_ADDR(x), BP_MCG_C8_LOCRE1) = (v)) /*@}*/ /******************************************************************************* * hw_mcg_t - module struct ******************************************************************************/ /*! * @brief All MCG module registers. */ #pragma pack(1) typedef struct _hw_mcg { __IO hw_mcg_c1_t C1; /*!< [0x0] MCG Control 1 Register */ __IO hw_mcg_c2_t C2; /*!< [0x1] MCG Control 2 Register */ __IO hw_mcg_c3_t C3; /*!< [0x2] MCG Control 3 Register */ __IO hw_mcg_c4_t C4; /*!< [0x3] MCG Control 4 Register */ __IO hw_mcg_c5_t C5; /*!< [0x4] MCG Control 5 Register */ __IO hw_mcg_c6_t C6; /*!< [0x5] MCG Control 6 Register */ __IO hw_mcg_s_t S; /*!< [0x6] MCG Status Register */ uint8_t _reserved0[1]; __IO hw_mcg_sc_t SC; /*!< [0x8] MCG Status and Control Register */ uint8_t _reserved1[1]; __IO hw_mcg_atcvh_t ATCVH; /*!< [0xA] MCG Auto Trim Compare Value High Register */ __IO hw_mcg_atcvl_t ATCVL; /*!< [0xB] MCG Auto Trim Compare Value Low Register */ __IO hw_mcg_c7_t C7; /*!< [0xC] MCG Control 7 Register */ __IO hw_mcg_c8_t C8; /*!< [0xD] MCG Control 8 Register */ } hw_mcg_t; #pragma pack() /*! @brief Macro to access all MCG registers. */ /*! @param x MCG module instance base address. */ /*! @return Reference (not a pointer) to the registers struct. To get a pointer to the struct, * use the '&' operator, like &HW_MCG(MCG_BASE). */ #define HW_MCG(x) (*(hw_mcg_t *)(x)) #endif /* __HW_MCG_REGISTERS_H__ */ /* EOF */ ================================================ FILE: Zelig/mbed/TARGET_K64F/TARGET_Freescale/TARGET_KPSDK_MCUS/TARGET_MCU_K64F/device/device/MK64F12/MK64F12_mcm.h ================================================ /* ** ################################################################### ** Compilers: Keil ARM C/C++ Compiler ** Freescale C/C++ for Embedded ARM ** GNU C Compiler ** IAR ANSI C/C++ Compiler for ARM ** ** Reference manual: K64P144M120SF5RM, Rev.2, January 2014 ** Version: rev. 2.5, 2014-02-10 ** Build: b140604 ** ** Abstract: ** Extension to the CMSIS register access layer header. ** ** Copyright (c) 2014 Freescale Semiconductor, Inc. ** All rights reserved. ** ** Redistribution and use in source and binary forms, with or without modification, ** are permitted provided that the following conditions are met: ** ** o Redistributions of source code must retain the above copyright notice, this list ** of conditions and the following disclaimer. ** ** o Redistributions in binary form must reproduce the above copyright notice, this ** list of conditions and the following disclaimer in the documentation and/or ** other materials provided with the distribution. ** ** o Neither the name of Freescale Semiconductor, Inc. nor the names of its ** contributors may be used to endorse or promote products derived from this ** software without specific prior written permission. ** ** THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ** ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED ** WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE ** DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT 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. ** ** http: www.freescale.com ** mail: support@freescale.com ** ** Revisions: ** - rev. 1.0 (2013-08-12) ** Initial version. ** - rev. 2.0 (2013-10-29) ** Register accessor macros added to the memory map. ** Symbols for Processor Expert memory map compatibility added to the memory map. ** Startup file for gcc has been updated according to CMSIS 3.2. ** System initialization updated. ** MCG - registers updated. ** PORTA, PORTB, PORTC, PORTE - registers for digital filter removed. ** - rev. 2.1 (2013-10-30) ** Definition of BITBAND macros updated to support peripherals with 32-bit acces disabled. ** - rev. 2.2 (2013-12-09) ** DMA - EARS register removed. ** AIPS0, AIPS1 - MPRA register updated. ** - rev. 2.3 (2014-01-24) ** Update according to reference manual rev. 2 ** ENET, MCG, MCM, SIM, USB - registers updated ** - rev. 2.4 (2014-02-10) ** The declaration of clock configurations has been moved to separate header file system_MK64F12.h ** Update of SystemInit() and SystemCoreClockUpdate() functions. ** - rev. 2.5 (2014-02-10) ** The declaration of clock configurations has been moved to separate header file system_MK64F12.h ** Update of SystemInit() and SystemCoreClockUpdate() functions. ** Module access macro module_BASES replaced by module_BASE_PTRS. ** ** ################################################################### */ /* * WARNING! DO NOT EDIT THIS FILE DIRECTLY! * * This file was generated automatically and any changes may be lost. */ #ifndef __HW_MCM_REGISTERS_H__ #define __HW_MCM_REGISTERS_H__ #include "MK64F12.h" #include "fsl_bitaccess.h" /* * MK64F12 MCM * * Core Platform Miscellaneous Control Module * * Registers defined in this header file: * - HW_MCM_PLASC - Crossbar Switch (AXBS) Slave Configuration * - HW_MCM_PLAMC - Crossbar Switch (AXBS) Master Configuration * - HW_MCM_CR - Control Register * - HW_MCM_ISCR - Interrupt Status Register * - HW_MCM_ETBCC - ETB Counter Control register * - HW_MCM_ETBRL - ETB Reload register * - HW_MCM_ETBCNT - ETB Counter Value register * - HW_MCM_PID - Process ID register * * - hw_mcm_t - Struct containing all module registers. */ #define HW_MCM_INSTANCE_COUNT (1U) /*!< Number of instances of the MCM module. */ /******************************************************************************* * HW_MCM_PLASC - Crossbar Switch (AXBS) Slave Configuration ******************************************************************************/ /*! * @brief HW_MCM_PLASC - Crossbar Switch (AXBS) Slave Configuration (RO) * * Reset value: 0x001FU * * PLASC is a 16-bit read-only register identifying the presence/absence of bus * slave connections to the device's crossbar switch. */ typedef union _hw_mcm_plasc { uint16_t U; struct _hw_mcm_plasc_bitfields { uint16_t ASC : 8; /*!< [7:0] Each bit in the ASC field indicates * whether there is a corresponding connection to the crossbar switch's slave * input port. */ uint16_t RESERVED0 : 8; /*!< [15:8] */ } B; } hw_mcm_plasc_t; /*! * @name Constants and macros for entire MCM_PLASC register */ /*@{*/ #define HW_MCM_PLASC_ADDR(x) ((x) + 0x8U) #define HW_MCM_PLASC(x) (*(__I hw_mcm_plasc_t *) HW_MCM_PLASC_ADDR(x)) #define HW_MCM_PLASC_RD(x) (HW_MCM_PLASC(x).U) /*@}*/ /* * Constants & macros for individual MCM_PLASC bitfields */ /*! * @name Register MCM_PLASC, field ASC[7:0] (RO) * * Values: * - 0 - A bus slave connection to AXBS input port n is absent * - 1 - A bus slave connection to AXBS input port n is present */ /*@{*/ #define BP_MCM_PLASC_ASC (0U) /*!< Bit position for MCM_PLASC_ASC. */ #define BM_MCM_PLASC_ASC (0x00FFU) /*!< Bit mask for MCM_PLASC_ASC. */ #define BS_MCM_PLASC_ASC (8U) /*!< Bit field size in bits for MCM_PLASC_ASC. */ /*! @brief Read current value of the MCM_PLASC_ASC field. */ #define BR_MCM_PLASC_ASC(x) (HW_MCM_PLASC(x).B.ASC) /*@}*/ /******************************************************************************* * HW_MCM_PLAMC - Crossbar Switch (AXBS) Master Configuration ******************************************************************************/ /*! * @brief HW_MCM_PLAMC - Crossbar Switch (AXBS) Master Configuration (RO) * * Reset value: 0x0037U * * PLAMC is a 16-bit read-only register identifying the presence/absence of bus * master connections to the device's crossbar switch. */ typedef union _hw_mcm_plamc { uint16_t U; struct _hw_mcm_plamc_bitfields { uint16_t AMC : 8; /*!< [7:0] Each bit in the AMC field indicates * whether there is a corresponding connection to the AXBS master input port. */ uint16_t RESERVED0 : 8; /*!< [15:8] */ } B; } hw_mcm_plamc_t; /*! * @name Constants and macros for entire MCM_PLAMC register */ /*@{*/ #define HW_MCM_PLAMC_ADDR(x) ((x) + 0xAU) #define HW_MCM_PLAMC(x) (*(__I hw_mcm_plamc_t *) HW_MCM_PLAMC_ADDR(x)) #define HW_MCM_PLAMC_RD(x) (HW_MCM_PLAMC(x).U) /*@}*/ /* * Constants & macros for individual MCM_PLAMC bitfields */ /*! * @name Register MCM_PLAMC, field AMC[7:0] (RO) * * Values: * - 0 - A bus master connection to AXBS input port n is absent * - 1 - A bus master connection to AXBS input port n is present */ /*@{*/ #define BP_MCM_PLAMC_AMC (0U) /*!< Bit position for MCM_PLAMC_AMC. */ #define BM_MCM_PLAMC_AMC (0x00FFU) /*!< Bit mask for MCM_PLAMC_AMC. */ #define BS_MCM_PLAMC_AMC (8U) /*!< Bit field size in bits for MCM_PLAMC_AMC. */ /*! @brief Read current value of the MCM_PLAMC_AMC field. */ #define BR_MCM_PLAMC_AMC(x) (HW_MCM_PLAMC(x).B.AMC) /*@}*/ /******************************************************************************* * HW_MCM_CR - Control Register ******************************************************************************/ /*! * @brief HW_MCM_CR - Control Register (RW) * * Reset value: 0x00000000U * * CR defines the arbitration and protection schemes for the two system RAM * arrays. */ typedef union _hw_mcm_cr { uint32_t U; struct _hw_mcm_cr_bitfields { uint32_t RESERVED0 : 24; /*!< [23:0] */ uint32_t SRAMUAP : 2; /*!< [25:24] SRAM_U arbitration priority */ uint32_t SRAMUWP : 1; /*!< [26] SRAM_U write protect */ uint32_t RESERVED1 : 1; /*!< [27] */ uint32_t SRAMLAP : 2; /*!< [29:28] SRAM_L arbitration priority */ uint32_t SRAMLWP : 1; /*!< [30] SRAM_L Write Protect */ uint32_t RESERVED2 : 1; /*!< [31] */ } B; } hw_mcm_cr_t; /*! * @name Constants and macros for entire MCM_CR register */ /*@{*/ #define HW_MCM_CR_ADDR(x) ((x) + 0xCU) #define HW_MCM_CR(x) (*(__IO hw_mcm_cr_t *) HW_MCM_CR_ADDR(x)) #define HW_MCM_CR_RD(x) (HW_MCM_CR(x).U) #define HW_MCM_CR_WR(x, v) (HW_MCM_CR(x).U = (v)) #define HW_MCM_CR_SET(x, v) (HW_MCM_CR_WR(x, HW_MCM_CR_RD(x) | (v))) #define HW_MCM_CR_CLR(x, v) (HW_MCM_CR_WR(x, HW_MCM_CR_RD(x) & ~(v))) #define HW_MCM_CR_TOG(x, v) (HW_MCM_CR_WR(x, HW_MCM_CR_RD(x) ^ (v))) /*@}*/ /* * Constants & macros for individual MCM_CR bitfields */ /*! * @name Register MCM_CR, field SRAMUAP[25:24] (RW) * * Defines the arbitration scheme and priority for the processor and SRAM * backdoor accesses to the SRAM_U array. * * Values: * - 00 - Round robin * - 01 - Special round robin (favors SRAM backoor accesses over the processor) * - 10 - Fixed priority. Processor has highest, backdoor has lowest * - 11 - Fixed priority. Backdoor has highest, processor has lowest */ /*@{*/ #define BP_MCM_CR_SRAMUAP (24U) /*!< Bit position for MCM_CR_SRAMUAP. */ #define BM_MCM_CR_SRAMUAP (0x03000000U) /*!< Bit mask for MCM_CR_SRAMUAP. */ #define BS_MCM_CR_SRAMUAP (2U) /*!< Bit field size in bits for MCM_CR_SRAMUAP. */ /*! @brief Read current value of the MCM_CR_SRAMUAP field. */ #define BR_MCM_CR_SRAMUAP(x) (HW_MCM_CR(x).B.SRAMUAP) /*! @brief Format value for bitfield MCM_CR_SRAMUAP. */ #define BF_MCM_CR_SRAMUAP(v) ((uint32_t)((uint32_t)(v) << BP_MCM_CR_SRAMUAP) & BM_MCM_CR_SRAMUAP) /*! @brief Set the SRAMUAP field to a new value. */ #define BW_MCM_CR_SRAMUAP(x, v) (HW_MCM_CR_WR(x, (HW_MCM_CR_RD(x) & ~BM_MCM_CR_SRAMUAP) | BF_MCM_CR_SRAMUAP(v))) /*@}*/ /*! * @name Register MCM_CR, field SRAMUWP[26] (RW) * * When this bit is set, writes to SRAM_U array generates a bus error. */ /*@{*/ #define BP_MCM_CR_SRAMUWP (26U) /*!< Bit position for MCM_CR_SRAMUWP. */ #define BM_MCM_CR_SRAMUWP (0x04000000U) /*!< Bit mask for MCM_CR_SRAMUWP. */ #define BS_MCM_CR_SRAMUWP (1U) /*!< Bit field size in bits for MCM_CR_SRAMUWP. */ /*! @brief Read current value of the MCM_CR_SRAMUWP field. */ #define BR_MCM_CR_SRAMUWP(x) (HW_MCM_CR(x).B.SRAMUWP) /*! @brief Format value for bitfield MCM_CR_SRAMUWP. */ #define BF_MCM_CR_SRAMUWP(v) ((uint32_t)((uint32_t)(v) << BP_MCM_CR_SRAMUWP) & BM_MCM_CR_SRAMUWP) /*! @brief Set the SRAMUWP field to a new value. */ #define BW_MCM_CR_SRAMUWP(x, v) (HW_MCM_CR_WR(x, (HW_MCM_CR_RD(x) & ~BM_MCM_CR_SRAMUWP) | BF_MCM_CR_SRAMUWP(v))) /*@}*/ /*! * @name Register MCM_CR, field SRAMLAP[29:28] (RW) * * Defines the arbitration scheme and priority for the processor and SRAM * backdoor accesses to the SRAM_L array. * * Values: * - 00 - Round robin * - 01 - Special round robin (favors SRAM backoor accesses over the processor) * - 10 - Fixed priority. Processor has highest, backdoor has lowest * - 11 - Fixed priority. Backdoor has highest, processor has lowest */ /*@{*/ #define BP_MCM_CR_SRAMLAP (28U) /*!< Bit position for MCM_CR_SRAMLAP. */ #define BM_MCM_CR_SRAMLAP (0x30000000U) /*!< Bit mask for MCM_CR_SRAMLAP. */ #define BS_MCM_CR_SRAMLAP (2U) /*!< Bit field size in bits for MCM_CR_SRAMLAP. */ /*! @brief Read current value of the MCM_CR_SRAMLAP field. */ #define BR_MCM_CR_SRAMLAP(x) (HW_MCM_CR(x).B.SRAMLAP) /*! @brief Format value for bitfield MCM_CR_SRAMLAP. */ #define BF_MCM_CR_SRAMLAP(v) ((uint32_t)((uint32_t)(v) << BP_MCM_CR_SRAMLAP) & BM_MCM_CR_SRAMLAP) /*! @brief Set the SRAMLAP field to a new value. */ #define BW_MCM_CR_SRAMLAP(x, v) (HW_MCM_CR_WR(x, (HW_MCM_CR_RD(x) & ~BM_MCM_CR_SRAMLAP) | BF_MCM_CR_SRAMLAP(v))) /*@}*/ /*! * @name Register MCM_CR, field SRAMLWP[30] (RW) * * When this bit is set, writes to SRAM_L array generates a bus error. */ /*@{*/ #define BP_MCM_CR_SRAMLWP (30U) /*!< Bit position for MCM_CR_SRAMLWP. */ #define BM_MCM_CR_SRAMLWP (0x40000000U) /*!< Bit mask for MCM_CR_SRAMLWP. */ #define BS_MCM_CR_SRAMLWP (1U) /*!< Bit field size in bits for MCM_CR_SRAMLWP. */ /*! @brief Read current value of the MCM_CR_SRAMLWP field. */ #define BR_MCM_CR_SRAMLWP(x) (HW_MCM_CR(x).B.SRAMLWP) /*! @brief Format value for bitfield MCM_CR_SRAMLWP. */ #define BF_MCM_CR_SRAMLWP(v) ((uint32_t)((uint32_t)(v) << BP_MCM_CR_SRAMLWP) & BM_MCM_CR_SRAMLWP) /*! @brief Set the SRAMLWP field to a new value. */ #define BW_MCM_CR_SRAMLWP(x, v) (HW_MCM_CR_WR(x, (HW_MCM_CR_RD(x) & ~BM_MCM_CR_SRAMLWP) | BF_MCM_CR_SRAMLWP(v))) /*@}*/ /******************************************************************************* * HW_MCM_ISCR - Interrupt Status Register ******************************************************************************/ /*! * @brief HW_MCM_ISCR - Interrupt Status Register (RW) * * Reset value: 0x00000000U */ typedef union _hw_mcm_iscr { uint32_t U; struct _hw_mcm_iscr_bitfields { uint32_t RESERVED0 : 1; /*!< [0] */ uint32_t IRQ : 1; /*!< [1] Normal Interrupt Pending */ uint32_t NMI : 1; /*!< [2] Non-maskable Interrupt Pending */ uint32_t DHREQ : 1; /*!< [3] Debug Halt Request Indicator */ uint32_t RESERVED1 : 4; /*!< [7:4] */ uint32_t FIOC : 1; /*!< [8] FPU invalid operation interrupt status */ uint32_t FDZC : 1; /*!< [9] FPU divide-by-zero interrupt status */ uint32_t FOFC : 1; /*!< [10] FPU overflow interrupt status */ uint32_t FUFC : 1; /*!< [11] FPU underflow interrupt status */ uint32_t FIXC : 1; /*!< [12] FPU inexact interrupt status */ uint32_t RESERVED2 : 2; /*!< [14:13] */ uint32_t FIDC : 1; /*!< [15] FPU input denormal interrupt status */ uint32_t RESERVED3 : 8; /*!< [23:16] */ uint32_t FIOCE : 1; /*!< [24] FPU invalid operation interrupt enable * */ uint32_t FDZCE : 1; /*!< [25] FPU divide-by-zero interrupt enable */ uint32_t FOFCE : 1; /*!< [26] FPU overflow interrupt enable */ uint32_t FUFCE : 1; /*!< [27] FPU underflow interrupt enable */ uint32_t FIXCE : 1; /*!< [28] FPU inexact interrupt enable */ uint32_t RESERVED4 : 2; /*!< [30:29] */ uint32_t FIDCE : 1; /*!< [31] FPU input denormal interrupt enable */ } B; } hw_mcm_iscr_t; /*! * @name Constants and macros for entire MCM_ISCR register */ /*@{*/ #define HW_MCM_ISCR_ADDR(x) ((x) + 0x10U) #define HW_MCM_ISCR(x) (*(__IO hw_mcm_iscr_t *) HW_MCM_ISCR_ADDR(x)) #define HW_MCM_ISCR_RD(x) (HW_MCM_ISCR(x).U) #define HW_MCM_ISCR_WR(x, v) (HW_MCM_ISCR(x).U = (v)) #define HW_MCM_ISCR_SET(x, v) (HW_MCM_ISCR_WR(x, HW_MCM_ISCR_RD(x) | (v))) #define HW_MCM_ISCR_CLR(x, v) (HW_MCM_ISCR_WR(x, HW_MCM_ISCR_RD(x) & ~(v))) #define HW_MCM_ISCR_TOG(x, v) (HW_MCM_ISCR_WR(x, HW_MCM_ISCR_RD(x) ^ (v))) /*@}*/ /* * Constants & macros for individual MCM_ISCR bitfields */ /*! * @name Register MCM_ISCR, field IRQ[1] (W1C) * * If ETBCC[RSPT] is set to 01b, this bit is set when the ETB counter expires. * * Values: * - 0 - No pending interrupt * - 1 - Due to the ETB counter expiring, a normal interrupt is pending */ /*@{*/ #define BP_MCM_ISCR_IRQ (1U) /*!< Bit position for MCM_ISCR_IRQ. */ #define BM_MCM_ISCR_IRQ (0x00000002U) /*!< Bit mask for MCM_ISCR_IRQ. */ #define BS_MCM_ISCR_IRQ (1U) /*!< Bit field size in bits for MCM_ISCR_IRQ. */ /*! @brief Read current value of the MCM_ISCR_IRQ field. */ #define BR_MCM_ISCR_IRQ(x) (HW_MCM_ISCR(x).B.IRQ) /*! @brief Format value for bitfield MCM_ISCR_IRQ. */ #define BF_MCM_ISCR_IRQ(v) ((uint32_t)((uint32_t)(v) << BP_MCM_ISCR_IRQ) & BM_MCM_ISCR_IRQ) /*! @brief Set the IRQ field to a new value. */ #define BW_MCM_ISCR_IRQ(x, v) (HW_MCM_ISCR_WR(x, (HW_MCM_ISCR_RD(x) & ~BM_MCM_ISCR_IRQ) | BF_MCM_ISCR_IRQ(v))) /*@}*/ /*! * @name Register MCM_ISCR, field NMI[2] (W1C) * * If ETBCC[RSPT] is set to 10b, this bit is set when the ETB counter expires. * * Values: * - 0 - No pending NMI * - 1 - Due to the ETB counter expiring, an NMI is pending */ /*@{*/ #define BP_MCM_ISCR_NMI (2U) /*!< Bit position for MCM_ISCR_NMI. */ #define BM_MCM_ISCR_NMI (0x00000004U) /*!< Bit mask for MCM_ISCR_NMI. */ #define BS_MCM_ISCR_NMI (1U) /*!< Bit field size in bits for MCM_ISCR_NMI. */ /*! @brief Read current value of the MCM_ISCR_NMI field. */ #define BR_MCM_ISCR_NMI(x) (HW_MCM_ISCR(x).B.NMI) /*! @brief Format value for bitfield MCM_ISCR_NMI. */ #define BF_MCM_ISCR_NMI(v) ((uint32_t)((uint32_t)(v) << BP_MCM_ISCR_NMI) & BM_MCM_ISCR_NMI) /*! @brief Set the NMI field to a new value. */ #define BW_MCM_ISCR_NMI(x, v) (HW_MCM_ISCR_WR(x, (HW_MCM_ISCR_RD(x) & ~BM_MCM_ISCR_NMI) | BF_MCM_ISCR_NMI(v))) /*@}*/ /*! * @name Register MCM_ISCR, field DHREQ[3] (RO) * * Indicates that a debug halt request is initiated due to a ETB counter * expiration, ETBCC[2:0] = 3b111 & ETBCV[10:0] = 11h0. This bit is cleared when the * counter is disabled or when the ETB counter is reloaded. * * Values: * - 0 - No debug halt request * - 1 - Debug halt request initiated */ /*@{*/ #define BP_MCM_ISCR_DHREQ (3U) /*!< Bit position for MCM_ISCR_DHREQ. */ #define BM_MCM_ISCR_DHREQ (0x00000008U) /*!< Bit mask for MCM_ISCR_DHREQ. */ #define BS_MCM_ISCR_DHREQ (1U) /*!< Bit field size in bits for MCM_ISCR_DHREQ. */ /*! @brief Read current value of the MCM_ISCR_DHREQ field. */ #define BR_MCM_ISCR_DHREQ(x) (HW_MCM_ISCR(x).B.DHREQ) /*@}*/ /*! * @name Register MCM_ISCR, field FIOC[8] (RO) * * This read-only bit is a copy of the core's FPSCR[IOC] bit and signals an * illegal operation has been detected in the processor's FPU. Once set, this bit * remains set until software clears the FPSCR[IOC] bit. * * Values: * - 0 - No interrupt * - 1 - Interrupt occurred */ /*@{*/ #define BP_MCM_ISCR_FIOC (8U) /*!< Bit position for MCM_ISCR_FIOC. */ #define BM_MCM_ISCR_FIOC (0x00000100U) /*!< Bit mask for MCM_ISCR_FIOC. */ #define BS_MCM_ISCR_FIOC (1U) /*!< Bit field size in bits for MCM_ISCR_FIOC. */ /*! @brief Read current value of the MCM_ISCR_FIOC field. */ #define BR_MCM_ISCR_FIOC(x) (HW_MCM_ISCR(x).B.FIOC) /*@}*/ /*! * @name Register MCM_ISCR, field FDZC[9] (RO) * * This read-only bit is a copy of the core's FPSCR[DZC] bit and signals a * divide by zero has been detected in the processor's FPU. Once set, this bit remains * set until software clears the FPSCR[DZC] bit. * * Values: * - 0 - No interrupt * - 1 - Interrupt occurred */ /*@{*/ #define BP_MCM_ISCR_FDZC (9U) /*!< Bit position for MCM_ISCR_FDZC. */ #define BM_MCM_ISCR_FDZC (0x00000200U) /*!< Bit mask for MCM_ISCR_FDZC. */ #define BS_MCM_ISCR_FDZC (1U) /*!< Bit field size in bits for MCM_ISCR_FDZC. */ /*! @brief Read current value of the MCM_ISCR_FDZC field. */ #define BR_MCM_ISCR_FDZC(x) (HW_MCM_ISCR(x).B.FDZC) /*@}*/ /*! * @name Register MCM_ISCR, field FOFC[10] (RO) * * This read-only bit is a copy of the core's FPSCR[OFC] bit and signals an * overflow has been detected in the processor's FPU. Once set, this bit remains set * until software clears the FPSCR[OFC] bit. * * Values: * - 0 - No interrupt * - 1 - Interrupt occurred */ /*@{*/ #define BP_MCM_ISCR_FOFC (10U) /*!< Bit position for MCM_ISCR_FOFC. */ #define BM_MCM_ISCR_FOFC (0x00000400U) /*!< Bit mask for MCM_ISCR_FOFC. */ #define BS_MCM_ISCR_FOFC (1U) /*!< Bit field size in bits for MCM_ISCR_FOFC. */ /*! @brief Read current value of the MCM_ISCR_FOFC field. */ #define BR_MCM_ISCR_FOFC(x) (HW_MCM_ISCR(x).B.FOFC) /*@}*/ /*! * @name Register MCM_ISCR, field FUFC[11] (RO) * * This read-only bit is a copy of the core's FPSCR[UFC] bit and signals an * underflow has been detected in the processor's FPU. Once set, this bit remains set * until software clears the FPSCR[UFC] bit. * * Values: * - 0 - No interrupt * - 1 - Interrupt occurred */ /*@{*/ #define BP_MCM_ISCR_FUFC (11U) /*!< Bit position for MCM_ISCR_FUFC. */ #define BM_MCM_ISCR_FUFC (0x00000800U) /*!< Bit mask for MCM_ISCR_FUFC. */ #define BS_MCM_ISCR_FUFC (1U) /*!< Bit field size in bits for MCM_ISCR_FUFC. */ /*! @brief Read current value of the MCM_ISCR_FUFC field. */ #define BR_MCM_ISCR_FUFC(x) (HW_MCM_ISCR(x).B.FUFC) /*@}*/ /*! * @name Register MCM_ISCR, field FIXC[12] (RO) * * This read-only bit is a copy of the core's FPSCR[IXC] bit and signals an * inexact number has been detected in the processor's FPU. Once set, this bit * remains set until software clears the FPSCR[IXC] bit. * * Values: * - 0 - No interrupt * - 1 - Interrupt occurred */ /*@{*/ #define BP_MCM_ISCR_FIXC (12U) /*!< Bit position for MCM_ISCR_FIXC. */ #define BM_MCM_ISCR_FIXC (0x00001000U) /*!< Bit mask for MCM_ISCR_FIXC. */ #define BS_MCM_ISCR_FIXC (1U) /*!< Bit field size in bits for MCM_ISCR_FIXC. */ /*! @brief Read current value of the MCM_ISCR_FIXC field. */ #define BR_MCM_ISCR_FIXC(x) (HW_MCM_ISCR(x).B.FIXC) /*@}*/ /*! * @name Register MCM_ISCR, field FIDC[15] (RO) * * This read-only bit is a copy of the core's FPSCR[IDC] bit and signals input * denormalized number has been detected in the processor's FPU. Once set, this * bit remains set until software clears the FPSCR[IDC] bit. * * Values: * - 0 - No interrupt * - 1 - Interrupt occurred */ /*@{*/ #define BP_MCM_ISCR_FIDC (15U) /*!< Bit position for MCM_ISCR_FIDC. */ #define BM_MCM_ISCR_FIDC (0x00008000U) /*!< Bit mask for MCM_ISCR_FIDC. */ #define BS_MCM_ISCR_FIDC (1U) /*!< Bit field size in bits for MCM_ISCR_FIDC. */ /*! @brief Read current value of the MCM_ISCR_FIDC field. */ #define BR_MCM_ISCR_FIDC(x) (HW_MCM_ISCR(x).B.FIDC) /*@}*/ /*! * @name Register MCM_ISCR, field FIOCE[24] (RW) * * Values: * - 0 - Disable interrupt * - 1 - Enable interrupt */ /*@{*/ #define BP_MCM_ISCR_FIOCE (24U) /*!< Bit position for MCM_ISCR_FIOCE. */ #define BM_MCM_ISCR_FIOCE (0x01000000U) /*!< Bit mask for MCM_ISCR_FIOCE. */ #define BS_MCM_ISCR_FIOCE (1U) /*!< Bit field size in bits for MCM_ISCR_FIOCE. */ /*! @brief Read current value of the MCM_ISCR_FIOCE field. */ #define BR_MCM_ISCR_FIOCE(x) (HW_MCM_ISCR(x).B.FIOCE) /*! @brief Format value for bitfield MCM_ISCR_FIOCE. */ #define BF_MCM_ISCR_FIOCE(v) ((uint32_t)((uint32_t)(v) << BP_MCM_ISCR_FIOCE) & BM_MCM_ISCR_FIOCE) /*! @brief Set the FIOCE field to a new value. */ #define BW_MCM_ISCR_FIOCE(x, v) (HW_MCM_ISCR_WR(x, (HW_MCM_ISCR_RD(x) & ~BM_MCM_ISCR_FIOCE) | BF_MCM_ISCR_FIOCE(v))) /*@}*/ /*! * @name Register MCM_ISCR, field FDZCE[25] (RW) * * Values: * - 0 - Disable interrupt * - 1 - Enable interrupt */ /*@{*/ #define BP_MCM_ISCR_FDZCE (25U) /*!< Bit position for MCM_ISCR_FDZCE. */ #define BM_MCM_ISCR_FDZCE (0x02000000U) /*!< Bit mask for MCM_ISCR_FDZCE. */ #define BS_MCM_ISCR_FDZCE (1U) /*!< Bit field size in bits for MCM_ISCR_FDZCE. */ /*! @brief Read current value of the MCM_ISCR_FDZCE field. */ #define BR_MCM_ISCR_FDZCE(x) (HW_MCM_ISCR(x).B.FDZCE) /*! @brief Format value for bitfield MCM_ISCR_FDZCE. */ #define BF_MCM_ISCR_FDZCE(v) ((uint32_t)((uint32_t)(v) << BP_MCM_ISCR_FDZCE) & BM_MCM_ISCR_FDZCE) /*! @brief Set the FDZCE field to a new value. */ #define BW_MCM_ISCR_FDZCE(x, v) (HW_MCM_ISCR_WR(x, (HW_MCM_ISCR_RD(x) & ~BM_MCM_ISCR_FDZCE) | BF_MCM_ISCR_FDZCE(v))) /*@}*/ /*! * @name Register MCM_ISCR, field FOFCE[26] (RW) * * Values: * - 0 - Disable interrupt * - 1 - Enable interrupt */ /*@{*/ #define BP_MCM_ISCR_FOFCE (26U) /*!< Bit position for MCM_ISCR_FOFCE. */ #define BM_MCM_ISCR_FOFCE (0x04000000U) /*!< Bit mask for MCM_ISCR_FOFCE. */ #define BS_MCM_ISCR_FOFCE (1U) /*!< Bit field size in bits for MCM_ISCR_FOFCE. */ /*! @brief Read current value of the MCM_ISCR_FOFCE field. */ #define BR_MCM_ISCR_FOFCE(x) (HW_MCM_ISCR(x).B.FOFCE) /*! @brief Format value for bitfield MCM_ISCR_FOFCE. */ #define BF_MCM_ISCR_FOFCE(v) ((uint32_t)((uint32_t)(v) << BP_MCM_ISCR_FOFCE) & BM_MCM_ISCR_FOFCE) /*! @brief Set the FOFCE field to a new value. */ #define BW_MCM_ISCR_FOFCE(x, v) (HW_MCM_ISCR_WR(x, (HW_MCM_ISCR_RD(x) & ~BM_MCM_ISCR_FOFCE) | BF_MCM_ISCR_FOFCE(v))) /*@}*/ /*! * @name Register MCM_ISCR, field FUFCE[27] (RW) * * Values: * - 0 - Disable interrupt * - 1 - Enable interrupt */ /*@{*/ #define BP_MCM_ISCR_FUFCE (27U) /*!< Bit position for MCM_ISCR_FUFCE. */ #define BM_MCM_ISCR_FUFCE (0x08000000U) /*!< Bit mask for MCM_ISCR_FUFCE. */ #define BS_MCM_ISCR_FUFCE (1U) /*!< Bit field size in bits for MCM_ISCR_FUFCE. */ /*! @brief Read current value of the MCM_ISCR_FUFCE field. */ #define BR_MCM_ISCR_FUFCE(x) (HW_MCM_ISCR(x).B.FUFCE) /*! @brief Format value for bitfield MCM_ISCR_FUFCE. */ #define BF_MCM_ISCR_FUFCE(v) ((uint32_t)((uint32_t)(v) << BP_MCM_ISCR_FUFCE) & BM_MCM_ISCR_FUFCE) /*! @brief Set the FUFCE field to a new value. */ #define BW_MCM_ISCR_FUFCE(x, v) (HW_MCM_ISCR_WR(x, (HW_MCM_ISCR_RD(x) & ~BM_MCM_ISCR_FUFCE) | BF_MCM_ISCR_FUFCE(v))) /*@}*/ /*! * @name Register MCM_ISCR, field FIXCE[28] (RW) * * Values: * - 0 - Disable interrupt * - 1 - Enable interrupt */ /*@{*/ #define BP_MCM_ISCR_FIXCE (28U) /*!< Bit position for MCM_ISCR_FIXCE. */ #define BM_MCM_ISCR_FIXCE (0x10000000U) /*!< Bit mask for MCM_ISCR_FIXCE. */ #define BS_MCM_ISCR_FIXCE (1U) /*!< Bit field size in bits for MCM_ISCR_FIXCE. */ /*! @brief Read current value of the MCM_ISCR_FIXCE field. */ #define BR_MCM_ISCR_FIXCE(x) (HW_MCM_ISCR(x).B.FIXCE) /*! @brief Format value for bitfield MCM_ISCR_FIXCE. */ #define BF_MCM_ISCR_FIXCE(v) ((uint32_t)((uint32_t)(v) << BP_MCM_ISCR_FIXCE) & BM_MCM_ISCR_FIXCE) /*! @brief Set the FIXCE field to a new value. */ #define BW_MCM_ISCR_FIXCE(x, v) (HW_MCM_ISCR_WR(x, (HW_MCM_ISCR_RD(x) & ~BM_MCM_ISCR_FIXCE) | BF_MCM_ISCR_FIXCE(v))) /*@}*/ /*! * @name Register MCM_ISCR, field FIDCE[31] (RW) * * Values: * - 0 - Disable interrupt * - 1 - Enable interrupt */ /*@{*/ #define BP_MCM_ISCR_FIDCE (31U) /*!< Bit position for MCM_ISCR_FIDCE. */ #define BM_MCM_ISCR_FIDCE (0x80000000U) /*!< Bit mask for MCM_ISCR_FIDCE. */ #define BS_MCM_ISCR_FIDCE (1U) /*!< Bit field size in bits for MCM_ISCR_FIDCE. */ /*! @brief Read current value of the MCM_ISCR_FIDCE field. */ #define BR_MCM_ISCR_FIDCE(x) (HW_MCM_ISCR(x).B.FIDCE) /*! @brief Format value for bitfield MCM_ISCR_FIDCE. */ #define BF_MCM_ISCR_FIDCE(v) ((uint32_t)((uint32_t)(v) << BP_MCM_ISCR_FIDCE) & BM_MCM_ISCR_FIDCE) /*! @brief Set the FIDCE field to a new value. */ #define BW_MCM_ISCR_FIDCE(x, v) (HW_MCM_ISCR_WR(x, (HW_MCM_ISCR_RD(x) & ~BM_MCM_ISCR_FIDCE) | BF_MCM_ISCR_FIDCE(v))) /*@}*/ /******************************************************************************* * HW_MCM_ETBCC - ETB Counter Control register ******************************************************************************/ /*! * @brief HW_MCM_ETBCC - ETB Counter Control register (RW) * * Reset value: 0x00000000U */ typedef union _hw_mcm_etbcc { uint32_t U; struct _hw_mcm_etbcc_bitfields { uint32_t CNTEN : 1; /*!< [0] Counter Enable */ uint32_t RSPT : 2; /*!< [2:1] Response Type */ uint32_t RLRQ : 1; /*!< [3] Reload Request */ uint32_t ETDIS : 1; /*!< [4] ETM-To-TPIU Disable */ uint32_t ITDIS : 1; /*!< [5] ITM-To-TPIU Disable */ uint32_t RESERVED0 : 26; /*!< [31:6] */ } B; } hw_mcm_etbcc_t; /*! * @name Constants and macros for entire MCM_ETBCC register */ /*@{*/ #define HW_MCM_ETBCC_ADDR(x) ((x) + 0x14U) #define HW_MCM_ETBCC(x) (*(__IO hw_mcm_etbcc_t *) HW_MCM_ETBCC_ADDR(x)) #define HW_MCM_ETBCC_RD(x) (HW_MCM_ETBCC(x).U) #define HW_MCM_ETBCC_WR(x, v) (HW_MCM_ETBCC(x).U = (v)) #define HW_MCM_ETBCC_SET(x, v) (HW_MCM_ETBCC_WR(x, HW_MCM_ETBCC_RD(x) | (v))) #define HW_MCM_ETBCC_CLR(x, v) (HW_MCM_ETBCC_WR(x, HW_MCM_ETBCC_RD(x) & ~(v))) #define HW_MCM_ETBCC_TOG(x, v) (HW_MCM_ETBCC_WR(x, HW_MCM_ETBCC_RD(x) ^ (v))) /*@}*/ /* * Constants & macros for individual MCM_ETBCC bitfields */ /*! * @name Register MCM_ETBCC, field CNTEN[0] (RW) * * Enables the ETB counter. * * Values: * - 0 - ETB counter disabled * - 1 - ETB counter enabled */ /*@{*/ #define BP_MCM_ETBCC_CNTEN (0U) /*!< Bit position for MCM_ETBCC_CNTEN. */ #define BM_MCM_ETBCC_CNTEN (0x00000001U) /*!< Bit mask for MCM_ETBCC_CNTEN. */ #define BS_MCM_ETBCC_CNTEN (1U) /*!< Bit field size in bits for MCM_ETBCC_CNTEN. */ /*! @brief Read current value of the MCM_ETBCC_CNTEN field. */ #define BR_MCM_ETBCC_CNTEN(x) (HW_MCM_ETBCC(x).B.CNTEN) /*! @brief Format value for bitfield MCM_ETBCC_CNTEN. */ #define BF_MCM_ETBCC_CNTEN(v) ((uint32_t)((uint32_t)(v) << BP_MCM_ETBCC_CNTEN) & BM_MCM_ETBCC_CNTEN) /*! @brief Set the CNTEN field to a new value. */ #define BW_MCM_ETBCC_CNTEN(x, v) (HW_MCM_ETBCC_WR(x, (HW_MCM_ETBCC_RD(x) & ~BM_MCM_ETBCC_CNTEN) | BF_MCM_ETBCC_CNTEN(v))) /*@}*/ /*! * @name Register MCM_ETBCC, field RSPT[2:1] (RW) * * Values: * - 00 - No response when the ETB count expires * - 01 - Generate a normal interrupt when the ETB count expires * - 10 - Generate an NMI when the ETB count expires * - 11 - Generate a debug halt when the ETB count expires */ /*@{*/ #define BP_MCM_ETBCC_RSPT (1U) /*!< Bit position for MCM_ETBCC_RSPT. */ #define BM_MCM_ETBCC_RSPT (0x00000006U) /*!< Bit mask for MCM_ETBCC_RSPT. */ #define BS_MCM_ETBCC_RSPT (2U) /*!< Bit field size in bits for MCM_ETBCC_RSPT. */ /*! @brief Read current value of the MCM_ETBCC_RSPT field. */ #define BR_MCM_ETBCC_RSPT(x) (HW_MCM_ETBCC(x).B.RSPT) /*! @brief Format value for bitfield MCM_ETBCC_RSPT. */ #define BF_MCM_ETBCC_RSPT(v) ((uint32_t)((uint32_t)(v) << BP_MCM_ETBCC_RSPT) & BM_MCM_ETBCC_RSPT) /*! @brief Set the RSPT field to a new value. */ #define BW_MCM_ETBCC_RSPT(x, v) (HW_MCM_ETBCC_WR(x, (HW_MCM_ETBCC_RD(x) & ~BM_MCM_ETBCC_RSPT) | BF_MCM_ETBCC_RSPT(v))) /*@}*/ /*! * @name Register MCM_ETBCC, field RLRQ[3] (RW) * * Reloads the ETB packet counter with the MCM_ETBRL RELOAD value. If IRQ or NMI * interrupts were enabled and an NMI or IRQ interrupt was generated on counter * expiration, setting this bit clears the pending NMI or IRQ interrupt request. * If debug halt was enabled and a debug halt request was asserted on counter * expiration, setting this bit clears the debug halt request. * * Values: * - 0 - No effect * - 1 - Clears pending debug halt, NMI, or IRQ interrupt requests */ /*@{*/ #define BP_MCM_ETBCC_RLRQ (3U) /*!< Bit position for MCM_ETBCC_RLRQ. */ #define BM_MCM_ETBCC_RLRQ (0x00000008U) /*!< Bit mask for MCM_ETBCC_RLRQ. */ #define BS_MCM_ETBCC_RLRQ (1U) /*!< Bit field size in bits for MCM_ETBCC_RLRQ. */ /*! @brief Read current value of the MCM_ETBCC_RLRQ field. */ #define BR_MCM_ETBCC_RLRQ(x) (HW_MCM_ETBCC(x).B.RLRQ) /*! @brief Format value for bitfield MCM_ETBCC_RLRQ. */ #define BF_MCM_ETBCC_RLRQ(v) ((uint32_t)((uint32_t)(v) << BP_MCM_ETBCC_RLRQ) & BM_MCM_ETBCC_RLRQ) /*! @brief Set the RLRQ field to a new value. */ #define BW_MCM_ETBCC_RLRQ(x, v) (HW_MCM_ETBCC_WR(x, (HW_MCM_ETBCC_RD(x) & ~BM_MCM_ETBCC_RLRQ) | BF_MCM_ETBCC_RLRQ(v))) /*@}*/ /*! * @name Register MCM_ETBCC, field ETDIS[4] (RW) * * Disables the trace path from ETM to TPIU. * * Values: * - 0 - ETM-to-TPIU trace path enabled * - 1 - ETM-to-TPIU trace path disabled */ /*@{*/ #define BP_MCM_ETBCC_ETDIS (4U) /*!< Bit position for MCM_ETBCC_ETDIS. */ #define BM_MCM_ETBCC_ETDIS (0x00000010U) /*!< Bit mask for MCM_ETBCC_ETDIS. */ #define BS_MCM_ETBCC_ETDIS (1U) /*!< Bit field size in bits for MCM_ETBCC_ETDIS. */ /*! @brief Read current value of the MCM_ETBCC_ETDIS field. */ #define BR_MCM_ETBCC_ETDIS(x) (HW_MCM_ETBCC(x).B.ETDIS) /*! @brief Format value for bitfield MCM_ETBCC_ETDIS. */ #define BF_MCM_ETBCC_ETDIS(v) ((uint32_t)((uint32_t)(v) << BP_MCM_ETBCC_ETDIS) & BM_MCM_ETBCC_ETDIS) /*! @brief Set the ETDIS field to a new value. */ #define BW_MCM_ETBCC_ETDIS(x, v) (HW_MCM_ETBCC_WR(x, (HW_MCM_ETBCC_RD(x) & ~BM_MCM_ETBCC_ETDIS) | BF_MCM_ETBCC_ETDIS(v))) /*@}*/ /*! * @name Register MCM_ETBCC, field ITDIS[5] (RW) * * Disables the trace path from ITM to TPIU. * * Values: * - 0 - ITM-to-TPIU trace path enabled * - 1 - ITM-to-TPIU trace path disabled */ /*@{*/ #define BP_MCM_ETBCC_ITDIS (5U) /*!< Bit position for MCM_ETBCC_ITDIS. */ #define BM_MCM_ETBCC_ITDIS (0x00000020U) /*!< Bit mask for MCM_ETBCC_ITDIS. */ #define BS_MCM_ETBCC_ITDIS (1U) /*!< Bit field size in bits for MCM_ETBCC_ITDIS. */ /*! @brief Read current value of the MCM_ETBCC_ITDIS field. */ #define BR_MCM_ETBCC_ITDIS(x) (HW_MCM_ETBCC(x).B.ITDIS) /*! @brief Format value for bitfield MCM_ETBCC_ITDIS. */ #define BF_MCM_ETBCC_ITDIS(v) ((uint32_t)((uint32_t)(v) << BP_MCM_ETBCC_ITDIS) & BM_MCM_ETBCC_ITDIS) /*! @brief Set the ITDIS field to a new value. */ #define BW_MCM_ETBCC_ITDIS(x, v) (HW_MCM_ETBCC_WR(x, (HW_MCM_ETBCC_RD(x) & ~BM_MCM_ETBCC_ITDIS) | BF_MCM_ETBCC_ITDIS(v))) /*@}*/ /******************************************************************************* * HW_MCM_ETBRL - ETB Reload register ******************************************************************************/ /*! * @brief HW_MCM_ETBRL - ETB Reload register (RW) * * Reset value: 0x00000000U */ typedef union _hw_mcm_etbrl { uint32_t U; struct _hw_mcm_etbrl_bitfields { uint32_t RELOAD : 11; /*!< [10:0] Byte Count Reload Value */ uint32_t RESERVED0 : 21; /*!< [31:11] */ } B; } hw_mcm_etbrl_t; /*! * @name Constants and macros for entire MCM_ETBRL register */ /*@{*/ #define HW_MCM_ETBRL_ADDR(x) ((x) + 0x18U) #define HW_MCM_ETBRL(x) (*(__IO hw_mcm_etbrl_t *) HW_MCM_ETBRL_ADDR(x)) #define HW_MCM_ETBRL_RD(x) (HW_MCM_ETBRL(x).U) #define HW_MCM_ETBRL_WR(x, v) (HW_MCM_ETBRL(x).U = (v)) #define HW_MCM_ETBRL_SET(x, v) (HW_MCM_ETBRL_WR(x, HW_MCM_ETBRL_RD(x) | (v))) #define HW_MCM_ETBRL_CLR(x, v) (HW_MCM_ETBRL_WR(x, HW_MCM_ETBRL_RD(x) & ~(v))) #define HW_MCM_ETBRL_TOG(x, v) (HW_MCM_ETBRL_WR(x, HW_MCM_ETBRL_RD(x) ^ (v))) /*@}*/ /* * Constants & macros for individual MCM_ETBRL bitfields */ /*! * @name Register MCM_ETBRL, field RELOAD[10:0] (RW) * * Indicates the 0-mod-4 value the counter reloads to. Writing a non-0-mod-4 * value to this field results in a bus error. */ /*@{*/ #define BP_MCM_ETBRL_RELOAD (0U) /*!< Bit position for MCM_ETBRL_RELOAD. */ #define BM_MCM_ETBRL_RELOAD (0x000007FFU) /*!< Bit mask for MCM_ETBRL_RELOAD. */ #define BS_MCM_ETBRL_RELOAD (11U) /*!< Bit field size in bits for MCM_ETBRL_RELOAD. */ /*! @brief Read current value of the MCM_ETBRL_RELOAD field. */ #define BR_MCM_ETBRL_RELOAD(x) (HW_MCM_ETBRL(x).B.RELOAD) /*! @brief Format value for bitfield MCM_ETBRL_RELOAD. */ #define BF_MCM_ETBRL_RELOAD(v) ((uint32_t)((uint32_t)(v) << BP_MCM_ETBRL_RELOAD) & BM_MCM_ETBRL_RELOAD) /*! @brief Set the RELOAD field to a new value. */ #define BW_MCM_ETBRL_RELOAD(x, v) (HW_MCM_ETBRL_WR(x, (HW_MCM_ETBRL_RD(x) & ~BM_MCM_ETBRL_RELOAD) | BF_MCM_ETBRL_RELOAD(v))) /*@}*/ /******************************************************************************* * HW_MCM_ETBCNT - ETB Counter Value register ******************************************************************************/ /*! * @brief HW_MCM_ETBCNT - ETB Counter Value register (RO) * * Reset value: 0x00000000U */ typedef union _hw_mcm_etbcnt { uint32_t U; struct _hw_mcm_etbcnt_bitfields { uint32_t COUNTER : 11; /*!< [10:0] Byte Count Counter Value */ uint32_t RESERVED0 : 21; /*!< [31:11] */ } B; } hw_mcm_etbcnt_t; /*! * @name Constants and macros for entire MCM_ETBCNT register */ /*@{*/ #define HW_MCM_ETBCNT_ADDR(x) ((x) + 0x1CU) #define HW_MCM_ETBCNT(x) (*(__I hw_mcm_etbcnt_t *) HW_MCM_ETBCNT_ADDR(x)) #define HW_MCM_ETBCNT_RD(x) (HW_MCM_ETBCNT(x).U) /*@}*/ /* * Constants & macros for individual MCM_ETBCNT bitfields */ /*! * @name Register MCM_ETBCNT, field COUNTER[10:0] (RO) * * Indicates the current 0-mod-4 value of the counter. */ /*@{*/ #define BP_MCM_ETBCNT_COUNTER (0U) /*!< Bit position for MCM_ETBCNT_COUNTER. */ #define BM_MCM_ETBCNT_COUNTER (0x000007FFU) /*!< Bit mask for MCM_ETBCNT_COUNTER. */ #define BS_MCM_ETBCNT_COUNTER (11U) /*!< Bit field size in bits for MCM_ETBCNT_COUNTER. */ /*! @brief Read current value of the MCM_ETBCNT_COUNTER field. */ #define BR_MCM_ETBCNT_COUNTER(x) (HW_MCM_ETBCNT(x).B.COUNTER) /*@}*/ /******************************************************************************* * HW_MCM_PID - Process ID register ******************************************************************************/ /*! * @brief HW_MCM_PID - Process ID register (RW) * * Reset value: 0x00000000U * * This register drives the M0_PID and M1_PID values in the Memory Protection * Unit(MPU). System software loads this register before passing control to a given * user mode process. If the PID of the process does not match the value in this * register, a bus error occurs. See the MPU chapter for more details. */ typedef union _hw_mcm_pid { uint32_t U; struct _hw_mcm_pid_bitfields { uint32_t PID : 8; /*!< [7:0] M0_PID And M1_PID For MPU */ uint32_t RESERVED0 : 24; /*!< [31:8] */ } B; } hw_mcm_pid_t; /*! * @name Constants and macros for entire MCM_PID register */ /*@{*/ #define HW_MCM_PID_ADDR(x) ((x) + 0x30U) #define HW_MCM_PID(x) (*(__IO hw_mcm_pid_t *) HW_MCM_PID_ADDR(x)) #define HW_MCM_PID_RD(x) (HW_MCM_PID(x).U) #define HW_MCM_PID_WR(x, v) (HW_MCM_PID(x).U = (v)) #define HW_MCM_PID_SET(x, v) (HW_MCM_PID_WR(x, HW_MCM_PID_RD(x) | (v))) #define HW_MCM_PID_CLR(x, v) (HW_MCM_PID_WR(x, HW_MCM_PID_RD(x) & ~(v))) #define HW_MCM_PID_TOG(x, v) (HW_MCM_PID_WR(x, HW_MCM_PID_RD(x) ^ (v))) /*@}*/ /* * Constants & macros for individual MCM_PID bitfields */ /*! * @name Register MCM_PID, field PID[7:0] (RW) * * Drives the M0_PID and M1_PID values in the MPU. */ /*@{*/ #define BP_MCM_PID_PID (0U) /*!< Bit position for MCM_PID_PID. */ #define BM_MCM_PID_PID (0x000000FFU) /*!< Bit mask for MCM_PID_PID. */ #define BS_MCM_PID_PID (8U) /*!< Bit field size in bits for MCM_PID_PID. */ /*! @brief Read current value of the MCM_PID_PID field. */ #define BR_MCM_PID_PID(x) (HW_MCM_PID(x).B.PID) /*! @brief Format value for bitfield MCM_PID_PID. */ #define BF_MCM_PID_PID(v) ((uint32_t)((uint32_t)(v) << BP_MCM_PID_PID) & BM_MCM_PID_PID) /*! @brief Set the PID field to a new value. */ #define BW_MCM_PID_PID(x, v) (HW_MCM_PID_WR(x, (HW_MCM_PID_RD(x) & ~BM_MCM_PID_PID) | BF_MCM_PID_PID(v))) /*@}*/ /******************************************************************************* * hw_mcm_t - module struct ******************************************************************************/ /*! * @brief All MCM module registers. */ #pragma pack(1) typedef struct _hw_mcm { uint8_t _reserved0[8]; __I hw_mcm_plasc_t PLASC; /*!< [0x8] Crossbar Switch (AXBS) Slave Configuration */ __I hw_mcm_plamc_t PLAMC; /*!< [0xA] Crossbar Switch (AXBS) Master Configuration */ __IO hw_mcm_cr_t CR; /*!< [0xC] Control Register */ __IO hw_mcm_iscr_t ISCR; /*!< [0x10] Interrupt Status Register */ __IO hw_mcm_etbcc_t ETBCC; /*!< [0x14] ETB Counter Control register */ __IO hw_mcm_etbrl_t ETBRL; /*!< [0x18] ETB Reload register */ __I hw_mcm_etbcnt_t ETBCNT; /*!< [0x1C] ETB Counter Value register */ uint8_t _reserved1[16]; __IO hw_mcm_pid_t PID; /*!< [0x30] Process ID register */ } hw_mcm_t; #pragma pack() /*! @brief Macro to access all MCM registers. */ /*! @param x MCM module instance base address. */ /*! @return Reference (not a pointer) to the registers struct. To get a pointer to the struct, * use the '&' operator, like &HW_MCM(MCM_BASE). */ #define HW_MCM(x) (*(hw_mcm_t *)(x)) #endif /* __HW_MCM_REGISTERS_H__ */ /* EOF */ ================================================ FILE: Zelig/mbed/TARGET_K64F/TARGET_Freescale/TARGET_KPSDK_MCUS/TARGET_MCU_K64F/device/device/MK64F12/MK64F12_mpu.h ================================================ /* ** ################################################################### ** Compilers: Keil ARM C/C++ Compiler ** Freescale C/C++ for Embedded ARM ** GNU C Compiler ** IAR ANSI C/C++ Compiler for ARM ** ** Reference manual: K64P144M120SF5RM, Rev.2, January 2014 ** Version: rev. 2.5, 2014-02-10 ** Build: b140604 ** ** Abstract: ** Extension to the CMSIS register access layer header. ** ** Copyright (c) 2014 Freescale Semiconductor, Inc. ** All rights reserved. ** ** Redistribution and use in source and binary forms, with or without modification, ** are permitted provided that the following conditions are met: ** ** o Redistributions of source code must retain the above copyright notice, this list ** of conditions and the following disclaimer. ** ** o Redistributions in binary form must reproduce the above copyright notice, this ** list of conditions and the following disclaimer in the documentation and/or ** other materials provided with the distribution. ** ** o Neither the name of Freescale Semiconductor, Inc. nor the names of its ** contributors may be used to endorse or promote products derived from this ** software without specific prior written permission. ** ** THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ** ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED ** WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE ** DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT 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. ** ** http: www.freescale.com ** mail: support@freescale.com ** ** Revisions: ** - rev. 1.0 (2013-08-12) ** Initial version. ** - rev. 2.0 (2013-10-29) ** Register accessor macros added to the memory map. ** Symbols for Processor Expert memory map compatibility added to the memory map. ** Startup file for gcc has been updated according to CMSIS 3.2. ** System initialization updated. ** MCG - registers updated. ** PORTA, PORTB, PORTC, PORTE - registers for digital filter removed. ** - rev. 2.1 (2013-10-30) ** Definition of BITBAND macros updated to support peripherals with 32-bit acces disabled. ** - rev. 2.2 (2013-12-09) ** DMA - EARS register removed. ** AIPS0, AIPS1 - MPRA register updated. ** - rev. 2.3 (2014-01-24) ** Update according to reference manual rev. 2 ** ENET, MCG, MCM, SIM, USB - registers updated ** - rev. 2.4 (2014-02-10) ** The declaration of clock configurations has been moved to separate header file system_MK64F12.h ** Update of SystemInit() and SystemCoreClockUpdate() functions. ** - rev. 2.5 (2014-02-10) ** The declaration of clock configurations has been moved to separate header file system_MK64F12.h ** Update of SystemInit() and SystemCoreClockUpdate() functions. ** Module access macro module_BASES replaced by module_BASE_PTRS. ** ** ################################################################### */ /* * WARNING! DO NOT EDIT THIS FILE DIRECTLY! * * This file was generated automatically and any changes may be lost. */ #ifndef __HW_MPU_REGISTERS_H__ #define __HW_MPU_REGISTERS_H__ #include "MK64F12.h" #include "fsl_bitaccess.h" /* * MK64F12 MPU * * Memory protection unit * * Registers defined in this header file: * - HW_MPU_CESR - Control/Error Status Register * - HW_MPU_EARn - Error Address Register, slave port n * - HW_MPU_EDRn - Error Detail Register, slave port n * - HW_MPU_RGDn_WORD0 - Region Descriptor n, Word 0 * - HW_MPU_RGDn_WORD1 - Region Descriptor n, Word 1 * - HW_MPU_RGDn_WORD2 - Region Descriptor n, Word 2 * - HW_MPU_RGDn_WORD3 - Region Descriptor n, Word 3 * - HW_MPU_RGDAACn - Region Descriptor Alternate Access Control n * * - hw_mpu_t - Struct containing all module registers. */ #define HW_MPU_INSTANCE_COUNT (1U) /*!< Number of instances of the MPU module. */ /******************************************************************************* * HW_MPU_CESR - Control/Error Status Register ******************************************************************************/ /*! * @brief HW_MPU_CESR - Control/Error Status Register (RW) * * Reset value: 0x00815101U */ typedef union _hw_mpu_cesr { uint32_t U; struct _hw_mpu_cesr_bitfields { uint32_t VLD : 1; /*!< [0] Valid */ uint32_t RESERVED0 : 7; /*!< [7:1] */ uint32_t NRGD : 4; /*!< [11:8] Number Of Region Descriptors */ uint32_t NSP : 4; /*!< [15:12] Number Of Slave Ports */ uint32_t HRL : 4; /*!< [19:16] Hardware Revision Level */ uint32_t RESERVED1 : 7; /*!< [26:20] */ uint32_t SPERR : 5; /*!< [31:27] Slave Port n Error */ } B; } hw_mpu_cesr_t; /*! * @name Constants and macros for entire MPU_CESR register */ /*@{*/ #define HW_MPU_CESR_ADDR(x) ((x) + 0x0U) #define HW_MPU_CESR(x) (*(__IO hw_mpu_cesr_t *) HW_MPU_CESR_ADDR(x)) #define HW_MPU_CESR_RD(x) (HW_MPU_CESR(x).U) #define HW_MPU_CESR_WR(x, v) (HW_MPU_CESR(x).U = (v)) #define HW_MPU_CESR_SET(x, v) (HW_MPU_CESR_WR(x, HW_MPU_CESR_RD(x) | (v))) #define HW_MPU_CESR_CLR(x, v) (HW_MPU_CESR_WR(x, HW_MPU_CESR_RD(x) & ~(v))) #define HW_MPU_CESR_TOG(x, v) (HW_MPU_CESR_WR(x, HW_MPU_CESR_RD(x) ^ (v))) /*@}*/ /* * Constants & macros for individual MPU_CESR bitfields */ /*! * @name Register MPU_CESR, field VLD[0] (RW) * * Global enable/disable for the MPU. * * Values: * - 0 - MPU is disabled. All accesses from all bus masters are allowed. * - 1 - MPU is enabled */ /*@{*/ #define BP_MPU_CESR_VLD (0U) /*!< Bit position for MPU_CESR_VLD. */ #define BM_MPU_CESR_VLD (0x00000001U) /*!< Bit mask for MPU_CESR_VLD. */ #define BS_MPU_CESR_VLD (1U) /*!< Bit field size in bits for MPU_CESR_VLD. */ /*! @brief Read current value of the MPU_CESR_VLD field. */ #define BR_MPU_CESR_VLD(x) (BITBAND_ACCESS32(HW_MPU_CESR_ADDR(x), BP_MPU_CESR_VLD)) /*! @brief Format value for bitfield MPU_CESR_VLD. */ #define BF_MPU_CESR_VLD(v) ((uint32_t)((uint32_t)(v) << BP_MPU_CESR_VLD) & BM_MPU_CESR_VLD) /*! @brief Set the VLD field to a new value. */ #define BW_MPU_CESR_VLD(x, v) (BITBAND_ACCESS32(HW_MPU_CESR_ADDR(x), BP_MPU_CESR_VLD) = (v)) /*@}*/ /*! * @name Register MPU_CESR, field NRGD[11:8] (RO) * * Indicates the number of region descriptors implemented in the MPU. * * Values: * - 0000 - 8 region descriptors * - 0001 - 12 region descriptors * - 0010 - 16 region descriptors */ /*@{*/ #define BP_MPU_CESR_NRGD (8U) /*!< Bit position for MPU_CESR_NRGD. */ #define BM_MPU_CESR_NRGD (0x00000F00U) /*!< Bit mask for MPU_CESR_NRGD. */ #define BS_MPU_CESR_NRGD (4U) /*!< Bit field size in bits for MPU_CESR_NRGD. */ /*! @brief Read current value of the MPU_CESR_NRGD field. */ #define BR_MPU_CESR_NRGD(x) (HW_MPU_CESR(x).B.NRGD) /*@}*/ /*! * @name Register MPU_CESR, field NSP[15:12] (RO) * * Specifies the number of slave ports connected to the MPU. */ /*@{*/ #define BP_MPU_CESR_NSP (12U) /*!< Bit position for MPU_CESR_NSP. */ #define BM_MPU_CESR_NSP (0x0000F000U) /*!< Bit mask for MPU_CESR_NSP. */ #define BS_MPU_CESR_NSP (4U) /*!< Bit field size in bits for MPU_CESR_NSP. */ /*! @brief Read current value of the MPU_CESR_NSP field. */ #define BR_MPU_CESR_NSP(x) (HW_MPU_CESR(x).B.NSP) /*@}*/ /*! * @name Register MPU_CESR, field HRL[19:16] (RO) * * Specifies the MPU's hardware and definition revision level. It can be read by * software to determine the functional definition of the module. */ /*@{*/ #define BP_MPU_CESR_HRL (16U) /*!< Bit position for MPU_CESR_HRL. */ #define BM_MPU_CESR_HRL (0x000F0000U) /*!< Bit mask for MPU_CESR_HRL. */ #define BS_MPU_CESR_HRL (4U) /*!< Bit field size in bits for MPU_CESR_HRL. */ /*! @brief Read current value of the MPU_CESR_HRL field. */ #define BR_MPU_CESR_HRL(x) (HW_MPU_CESR(x).B.HRL) /*@}*/ /*! * @name Register MPU_CESR, field SPERR[31:27] (W1C) * * Indicates a captured error in EARn and EDRn. This bit is set when the * hardware detects an error and records the faulting address and attributes. It is * cleared by writing one to it. If another error is captured at the exact same cycle * as the write, the flag remains set. A find-first-one instruction or * equivalent can detect the presence of a captured error. The following shows the * correspondence between the bit number and slave port number: Bit 31 corresponds to * slave port 0. Bit 30 corresponds to slave port 1. Bit 29 corresponds to slave * port 2. Bit 28 corresponds to slave port 3. Bit 27 corresponds to slave port 4. * * Values: * - 0 - No error has occurred for slave port n. * - 1 - An error has occurred for slave port n. */ /*@{*/ #define BP_MPU_CESR_SPERR (27U) /*!< Bit position for MPU_CESR_SPERR. */ #define BM_MPU_CESR_SPERR (0xF8000000U) /*!< Bit mask for MPU_CESR_SPERR. */ #define BS_MPU_CESR_SPERR (5U) /*!< Bit field size in bits for MPU_CESR_SPERR. */ /*! @brief Read current value of the MPU_CESR_SPERR field. */ #define BR_MPU_CESR_SPERR(x) (HW_MPU_CESR(x).B.SPERR) /*! @brief Format value for bitfield MPU_CESR_SPERR. */ #define BF_MPU_CESR_SPERR(v) ((uint32_t)((uint32_t)(v) << BP_MPU_CESR_SPERR) & BM_MPU_CESR_SPERR) /*! @brief Set the SPERR field to a new value. */ #define BW_MPU_CESR_SPERR(x, v) (HW_MPU_CESR_WR(x, (HW_MPU_CESR_RD(x) & ~BM_MPU_CESR_SPERR) | BF_MPU_CESR_SPERR(v))) /*@}*/ /******************************************************************************* * HW_MPU_EARn - Error Address Register, slave port n ******************************************************************************/ /*! * @brief HW_MPU_EARn - Error Address Register, slave port n (RO) * * Reset value: 0x00000000U * * When the MPU detects an access error on slave port n, the 32-bit reference * address is captured in this read-only register and the corresponding bit in * CESR[SPERR] set. Additional information about the faulting access is captured in * the corresponding EDRn at the same time. This register and the corresponding * EDRn contain the most recent access error; there are no hardware interlocks with * CESR[SPERR], as the error registers are always loaded upon the occurrence of * each protection violation. */ typedef union _hw_mpu_earn { uint32_t U; struct _hw_mpu_earn_bitfields { uint32_t EADDR : 32; /*!< [31:0] Error Address */ } B; } hw_mpu_earn_t; /*! * @name Constants and macros for entire MPU_EARn register */ /*@{*/ #define HW_MPU_EARn_COUNT (5U) #define HW_MPU_EARn_ADDR(x, n) ((x) + 0x10U + (0x8U * (n))) #define HW_MPU_EARn(x, n) (*(__I hw_mpu_earn_t *) HW_MPU_EARn_ADDR(x, n)) #define HW_MPU_EARn_RD(x, n) (HW_MPU_EARn(x, n).U) /*@}*/ /* * Constants & macros for individual MPU_EARn bitfields */ /*! * @name Register MPU_EARn, field EADDR[31:0] (RO) * * Indicates the reference address from slave port n that generated the access * error */ /*@{*/ #define BP_MPU_EARn_EADDR (0U) /*!< Bit position for MPU_EARn_EADDR. */ #define BM_MPU_EARn_EADDR (0xFFFFFFFFU) /*!< Bit mask for MPU_EARn_EADDR. */ #define BS_MPU_EARn_EADDR (32U) /*!< Bit field size in bits for MPU_EARn_EADDR. */ /*! @brief Read current value of the MPU_EARn_EADDR field. */ #define BR_MPU_EARn_EADDR(x, n) (HW_MPU_EARn(x, n).U) /*@}*/ /******************************************************************************* * HW_MPU_EDRn - Error Detail Register, slave port n ******************************************************************************/ /*! * @brief HW_MPU_EDRn - Error Detail Register, slave port n (RO) * * Reset value: 0x00000000U * * When the MPU detects an access error on slave port n, 32 bits of error detail * are captured in this read-only register and the corresponding bit in * CESR[SPERR] is set. Information on the faulting address is captured in the * corresponding EARn register at the same time. This register and the corresponding EARn * register contain the most recent access error; there are no hardware interlocks * with CESR[SPERR] as the error registers are always loaded upon the occurrence * of each protection violation. */ typedef union _hw_mpu_edrn { uint32_t U; struct _hw_mpu_edrn_bitfields { uint32_t ERW : 1; /*!< [0] Error Read/Write */ uint32_t EATTR : 3; /*!< [3:1] Error Attributes */ uint32_t EMN : 4; /*!< [7:4] Error Master Number */ uint32_t EPID : 8; /*!< [15:8] Error Process Identification */ uint32_t EACD : 16; /*!< [31:16] Error Access Control Detail */ } B; } hw_mpu_edrn_t; /*! * @name Constants and macros for entire MPU_EDRn register */ /*@{*/ #define HW_MPU_EDRn_COUNT (5U) #define HW_MPU_EDRn_ADDR(x, n) ((x) + 0x14U + (0x8U * (n))) #define HW_MPU_EDRn(x, n) (*(__I hw_mpu_edrn_t *) HW_MPU_EDRn_ADDR(x, n)) #define HW_MPU_EDRn_RD(x, n) (HW_MPU_EDRn(x, n).U) /*@}*/ /* * Constants & macros for individual MPU_EDRn bitfields */ /*! * @name Register MPU_EDRn, field ERW[0] (RO) * * Indicates the access type of the faulting reference. * * Values: * - 0 - Read * - 1 - Write */ /*@{*/ #define BP_MPU_EDRn_ERW (0U) /*!< Bit position for MPU_EDRn_ERW. */ #define BM_MPU_EDRn_ERW (0x00000001U) /*!< Bit mask for MPU_EDRn_ERW. */ #define BS_MPU_EDRn_ERW (1U) /*!< Bit field size in bits for MPU_EDRn_ERW. */ /*! @brief Read current value of the MPU_EDRn_ERW field. */ #define BR_MPU_EDRn_ERW(x, n) (BITBAND_ACCESS32(HW_MPU_EDRn_ADDR(x, n), BP_MPU_EDRn_ERW)) /*@}*/ /*! * @name Register MPU_EDRn, field EATTR[3:1] (RO) * * Indicates attribute information about the faulting reference. All other * encodings are reserved. * * Values: * - 000 - User mode, instruction access * - 001 - User mode, data access * - 010 - Supervisor mode, instruction access * - 011 - Supervisor mode, data access */ /*@{*/ #define BP_MPU_EDRn_EATTR (1U) /*!< Bit position for MPU_EDRn_EATTR. */ #define BM_MPU_EDRn_EATTR (0x0000000EU) /*!< Bit mask for MPU_EDRn_EATTR. */ #define BS_MPU_EDRn_EATTR (3U) /*!< Bit field size in bits for MPU_EDRn_EATTR. */ /*! @brief Read current value of the MPU_EDRn_EATTR field. */ #define BR_MPU_EDRn_EATTR(x, n) (HW_MPU_EDRn(x, n).B.EATTR) /*@}*/ /*! * @name Register MPU_EDRn, field EMN[7:4] (RO) * * Indicates the bus master that generated the access error. */ /*@{*/ #define BP_MPU_EDRn_EMN (4U) /*!< Bit position for MPU_EDRn_EMN. */ #define BM_MPU_EDRn_EMN (0x000000F0U) /*!< Bit mask for MPU_EDRn_EMN. */ #define BS_MPU_EDRn_EMN (4U) /*!< Bit field size in bits for MPU_EDRn_EMN. */ /*! @brief Read current value of the MPU_EDRn_EMN field. */ #define BR_MPU_EDRn_EMN(x, n) (HW_MPU_EDRn(x, n).B.EMN) /*@}*/ /*! * @name Register MPU_EDRn, field EPID[15:8] (RO) * * Records the process identifier of the faulting reference. The process * identifier is typically driven only by processor cores; for other bus masters, this * field is cleared. */ /*@{*/ #define BP_MPU_EDRn_EPID (8U) /*!< Bit position for MPU_EDRn_EPID. */ #define BM_MPU_EDRn_EPID (0x0000FF00U) /*!< Bit mask for MPU_EDRn_EPID. */ #define BS_MPU_EDRn_EPID (8U) /*!< Bit field size in bits for MPU_EDRn_EPID. */ /*! @brief Read current value of the MPU_EDRn_EPID field. */ #define BR_MPU_EDRn_EPID(x, n) (HW_MPU_EDRn(x, n).B.EPID) /*@}*/ /*! * @name Register MPU_EDRn, field EACD[31:16] (RO) * * Indicates the region descriptor with the access error. If EDRn contains a * captured error and EACD is cleared, an access did not hit in any region * descriptor. If only a single EACD bit is set, the protection error was caused by a * single non-overlapping region descriptor. If two or more EACD bits are set, the * protection error was caused by an overlapping set of region descriptors. */ /*@{*/ #define BP_MPU_EDRn_EACD (16U) /*!< Bit position for MPU_EDRn_EACD. */ #define BM_MPU_EDRn_EACD (0xFFFF0000U) /*!< Bit mask for MPU_EDRn_EACD. */ #define BS_MPU_EDRn_EACD (16U) /*!< Bit field size in bits for MPU_EDRn_EACD. */ /*! @brief Read current value of the MPU_EDRn_EACD field. */ #define BR_MPU_EDRn_EACD(x, n) (HW_MPU_EDRn(x, n).B.EACD) /*@}*/ /******************************************************************************* * HW_MPU_RGDn_WORD0 - Region Descriptor n, Word 0 ******************************************************************************/ /*! * @brief HW_MPU_RGDn_WORD0 - Region Descriptor n, Word 0 (RW) * * Reset value: 0x00000000U * * The first word of the region descriptor defines the 0-modulo-32 byte start * address of the memory region. Writes to this register clear the region * descriptor's valid bit (RGDn_WORD3[VLD]). */ typedef union _hw_mpu_rgdn_word0 { uint32_t U; struct _hw_mpu_rgdn_word0_bitfields { uint32_t RESERVED0 : 5; /*!< [4:0] */ uint32_t SRTADDR : 27; /*!< [31:5] Start Address */ } B; } hw_mpu_rgdn_word0_t; /*! * @name Constants and macros for entire MPU_RGDn_WORD0 register */ /*@{*/ #define HW_MPU_RGDn_WORD0_COUNT (12U) #define HW_MPU_RGDn_WORD0_ADDR(x, n) ((x) + 0x400U + (0x10U * (n))) #define HW_MPU_RGDn_WORD0(x, n) (*(__IO hw_mpu_rgdn_word0_t *) HW_MPU_RGDn_WORD0_ADDR(x, n)) #define HW_MPU_RGDn_WORD0_RD(x, n) (HW_MPU_RGDn_WORD0(x, n).U) #define HW_MPU_RGDn_WORD0_WR(x, n, v) (HW_MPU_RGDn_WORD0(x, n).U = (v)) #define HW_MPU_RGDn_WORD0_SET(x, n, v) (HW_MPU_RGDn_WORD0_WR(x, n, HW_MPU_RGDn_WORD0_RD(x, n) | (v))) #define HW_MPU_RGDn_WORD0_CLR(x, n, v) (HW_MPU_RGDn_WORD0_WR(x, n, HW_MPU_RGDn_WORD0_RD(x, n) & ~(v))) #define HW_MPU_RGDn_WORD0_TOG(x, n, v) (HW_MPU_RGDn_WORD0_WR(x, n, HW_MPU_RGDn_WORD0_RD(x, n) ^ (v))) /*@}*/ /* * Constants & macros for individual MPU_RGDn_WORD0 bitfields */ /*! * @name Register MPU_RGDn_WORD0, field SRTADDR[31:5] (RW) * * Defines the most significant bits of the 0-modulo-32 byte start address of * the memory region. */ /*@{*/ #define BP_MPU_RGDn_WORD0_SRTADDR (5U) /*!< Bit position for MPU_RGDn_WORD0_SRTADDR. */ #define BM_MPU_RGDn_WORD0_SRTADDR (0xFFFFFFE0U) /*!< Bit mask for MPU_RGDn_WORD0_SRTADDR. */ #define BS_MPU_RGDn_WORD0_SRTADDR (27U) /*!< Bit field size in bits for MPU_RGDn_WORD0_SRTADDR. */ /*! @brief Read current value of the MPU_RGDn_WORD0_SRTADDR field. */ #define BR_MPU_RGDn_WORD0_SRTADDR(x, n) (HW_MPU_RGDn_WORD0(x, n).B.SRTADDR) /*! @brief Format value for bitfield MPU_RGDn_WORD0_SRTADDR. */ #define BF_MPU_RGDn_WORD0_SRTADDR(v) ((uint32_t)((uint32_t)(v) << BP_MPU_RGDn_WORD0_SRTADDR) & BM_MPU_RGDn_WORD0_SRTADDR) /*! @brief Set the SRTADDR field to a new value. */ #define BW_MPU_RGDn_WORD0_SRTADDR(x, n, v) (HW_MPU_RGDn_WORD0_WR(x, n, (HW_MPU_RGDn_WORD0_RD(x, n) & ~BM_MPU_RGDn_WORD0_SRTADDR) | BF_MPU_RGDn_WORD0_SRTADDR(v))) /*@}*/ /******************************************************************************* * HW_MPU_RGDn_WORD1 - Region Descriptor n, Word 1 ******************************************************************************/ /*! * @brief HW_MPU_RGDn_WORD1 - Region Descriptor n, Word 1 (RW) * * Reset value: 0xFFFFFFFFU * * The second word of the region descriptor defines the 31-modulo-32 byte end * address of the memory region. Writes to this register clear the region * descriptor's valid bit (RGDn_WORD3[VLD]). */ typedef union _hw_mpu_rgdn_word1 { uint32_t U; struct _hw_mpu_rgdn_word1_bitfields { uint32_t RESERVED0 : 5; /*!< [4:0] */ uint32_t ENDADDR : 27; /*!< [31:5] End Address */ } B; } hw_mpu_rgdn_word1_t; /*! * @name Constants and macros for entire MPU_RGDn_WORD1 register */ /*@{*/ #define HW_MPU_RGDn_WORD1_COUNT (12U) #define HW_MPU_RGDn_WORD1_ADDR(x, n) ((x) + 0x404U + (0x10U * (n))) #define HW_MPU_RGDn_WORD1(x, n) (*(__IO hw_mpu_rgdn_word1_t *) HW_MPU_RGDn_WORD1_ADDR(x, n)) #define HW_MPU_RGDn_WORD1_RD(x, n) (HW_MPU_RGDn_WORD1(x, n).U) #define HW_MPU_RGDn_WORD1_WR(x, n, v) (HW_MPU_RGDn_WORD1(x, n).U = (v)) #define HW_MPU_RGDn_WORD1_SET(x, n, v) (HW_MPU_RGDn_WORD1_WR(x, n, HW_MPU_RGDn_WORD1_RD(x, n) | (v))) #define HW_MPU_RGDn_WORD1_CLR(x, n, v) (HW_MPU_RGDn_WORD1_WR(x, n, HW_MPU_RGDn_WORD1_RD(x, n) & ~(v))) #define HW_MPU_RGDn_WORD1_TOG(x, n, v) (HW_MPU_RGDn_WORD1_WR(x, n, HW_MPU_RGDn_WORD1_RD(x, n) ^ (v))) /*@}*/ /* * Constants & macros for individual MPU_RGDn_WORD1 bitfields */ /*! * @name Register MPU_RGDn_WORD1, field ENDADDR[31:5] (RW) * * Defines the most significant bits of the 31-modulo-32 byte end address of the * memory region. The MPU does not verify that ENDADDR >= SRTADDR. */ /*@{*/ #define BP_MPU_RGDn_WORD1_ENDADDR (5U) /*!< Bit position for MPU_RGDn_WORD1_ENDADDR. */ #define BM_MPU_RGDn_WORD1_ENDADDR (0xFFFFFFE0U) /*!< Bit mask for MPU_RGDn_WORD1_ENDADDR. */ #define BS_MPU_RGDn_WORD1_ENDADDR (27U) /*!< Bit field size in bits for MPU_RGDn_WORD1_ENDADDR. */ /*! @brief Read current value of the MPU_RGDn_WORD1_ENDADDR field. */ #define BR_MPU_RGDn_WORD1_ENDADDR(x, n) (HW_MPU_RGDn_WORD1(x, n).B.ENDADDR) /*! @brief Format value for bitfield MPU_RGDn_WORD1_ENDADDR. */ #define BF_MPU_RGDn_WORD1_ENDADDR(v) ((uint32_t)((uint32_t)(v) << BP_MPU_RGDn_WORD1_ENDADDR) & BM_MPU_RGDn_WORD1_ENDADDR) /*! @brief Set the ENDADDR field to a new value. */ #define BW_MPU_RGDn_WORD1_ENDADDR(x, n, v) (HW_MPU_RGDn_WORD1_WR(x, n, (HW_MPU_RGDn_WORD1_RD(x, n) & ~BM_MPU_RGDn_WORD1_ENDADDR) | BF_MPU_RGDn_WORD1_ENDADDR(v))) /*@}*/ /******************************************************************************* * HW_MPU_RGDn_WORD2 - Region Descriptor n, Word 2 ******************************************************************************/ /*! * @brief HW_MPU_RGDn_WORD2 - Region Descriptor n, Word 2 (RW) * * Reset value: 0x0061F7DFU * * The third word of the region descriptor defines the access control rights of * the memory region. The access control privileges depend on two broad * classifications of bus masters: Bus masters 0-3 have a 5-bit field defining separate * privilege rights for user and supervisor mode accesses, as well as the optional * inclusion of a process identification field within the definition. Bus masters * 4-7 are limited to separate read and write permissions. For the privilege * rights of bus masters 0-3, there are three flags associated with this function: * Read (r) refers to accessing the referenced memory address using an operand * (data) fetch Write (w) refers to updating the referenced memory address using a * store (data) instruction Execute (x) refers to reading the referenced memory * address using an instruction fetch Writes to RGDn_WORD2 clear the region * descriptor's valid bit (RGDn_WORD3[VLD]). If only updating the access controls, write * to RGDAACn instead because stores to these locations do not affect the * descriptor's valid bit. */ typedef union _hw_mpu_rgdn_word2 { uint32_t U; struct _hw_mpu_rgdn_word2_bitfields { uint32_t M0UM : 3; /*!< [2:0] Bus Master 0 User Mode Access Control */ uint32_t M0SM : 2; /*!< [4:3] Bus Master 0 Supervisor Mode Access * Control */ uint32_t M0PE : 1; /*!< [5] Bus Master 0 Process Identifier enable */ uint32_t M1UM : 3; /*!< [8:6] Bus Master 1 User Mode Access Control */ uint32_t M1SM : 2; /*!< [10:9] Bus Master 1 Supervisor Mode Access * Control */ uint32_t M1PE : 1; /*!< [11] Bus Master 1 Process Identifier enable */ uint32_t M2UM : 3; /*!< [14:12] Bus Master 2 User Mode Access control * */ uint32_t M2SM : 2; /*!< [16:15] Bus Master 2 Supervisor Mode Access * Control */ uint32_t M2PE : 1; /*!< [17] Bus Master 2 Process Identifier Enable */ uint32_t M3UM : 3; /*!< [20:18] Bus Master 3 User Mode Access Control * */ uint32_t M3SM : 2; /*!< [22:21] Bus Master 3 Supervisor Mode Access * Control */ uint32_t M3PE : 1; /*!< [23] Bus Master 3 Process Identifier Enable */ uint32_t M4WE : 1; /*!< [24] Bus Master 4 Write Enable */ uint32_t M4RE : 1; /*!< [25] Bus Master 4 Read Enable */ uint32_t M5WE : 1; /*!< [26] Bus Master 5 Write Enable */ uint32_t M5RE : 1; /*!< [27] Bus Master 5 Read Enable */ uint32_t M6WE : 1; /*!< [28] Bus Master 6 Write Enable */ uint32_t M6RE : 1; /*!< [29] Bus Master 6 Read Enable */ uint32_t M7WE : 1; /*!< [30] Bus Master 7 Write Enable */ uint32_t M7RE : 1; /*!< [31] Bus Master 7 Read Enable */ } B; } hw_mpu_rgdn_word2_t; /*! * @name Constants and macros for entire MPU_RGDn_WORD2 register */ /*@{*/ #define HW_MPU_RGDn_WORD2_COUNT (12U) #define HW_MPU_RGDn_WORD2_ADDR(x, n) ((x) + 0x408U + (0x10U * (n))) #define HW_MPU_RGDn_WORD2(x, n) (*(__IO hw_mpu_rgdn_word2_t *) HW_MPU_RGDn_WORD2_ADDR(x, n)) #define HW_MPU_RGDn_WORD2_RD(x, n) (HW_MPU_RGDn_WORD2(x, n).U) #define HW_MPU_RGDn_WORD2_WR(x, n, v) (HW_MPU_RGDn_WORD2(x, n).U = (v)) #define HW_MPU_RGDn_WORD2_SET(x, n, v) (HW_MPU_RGDn_WORD2_WR(x, n, HW_MPU_RGDn_WORD2_RD(x, n) | (v))) #define HW_MPU_RGDn_WORD2_CLR(x, n, v) (HW_MPU_RGDn_WORD2_WR(x, n, HW_MPU_RGDn_WORD2_RD(x, n) & ~(v))) #define HW_MPU_RGDn_WORD2_TOG(x, n, v) (HW_MPU_RGDn_WORD2_WR(x, n, HW_MPU_RGDn_WORD2_RD(x, n) ^ (v))) /*@}*/ /* * Constants & macros for individual MPU_RGDn_WORD2 bitfields */ /*! * @name Register MPU_RGDn_WORD2, field M0UM[2:0] (RW) * * See M3UM description. */ /*@{*/ #define BP_MPU_RGDn_WORD2_M0UM (0U) /*!< Bit position for MPU_RGDn_WORD2_M0UM. */ #define BM_MPU_RGDn_WORD2_M0UM (0x00000007U) /*!< Bit mask for MPU_RGDn_WORD2_M0UM. */ #define BS_MPU_RGDn_WORD2_M0UM (3U) /*!< Bit field size in bits for MPU_RGDn_WORD2_M0UM. */ /*! @brief Read current value of the MPU_RGDn_WORD2_M0UM field. */ #define BR_MPU_RGDn_WORD2_M0UM(x, n) (HW_MPU_RGDn_WORD2(x, n).B.M0UM) /*! @brief Format value for bitfield MPU_RGDn_WORD2_M0UM. */ #define BF_MPU_RGDn_WORD2_M0UM(v) ((uint32_t)((uint32_t)(v) << BP_MPU_RGDn_WORD2_M0UM) & BM_MPU_RGDn_WORD2_M0UM) /*! @brief Set the M0UM field to a new value. */ #define BW_MPU_RGDn_WORD2_M0UM(x, n, v) (HW_MPU_RGDn_WORD2_WR(x, n, (HW_MPU_RGDn_WORD2_RD(x, n) & ~BM_MPU_RGDn_WORD2_M0UM) | BF_MPU_RGDn_WORD2_M0UM(v))) /*@}*/ /*! * @name Register MPU_RGDn_WORD2, field M0SM[4:3] (RW) * * See M3SM description. */ /*@{*/ #define BP_MPU_RGDn_WORD2_M0SM (3U) /*!< Bit position for MPU_RGDn_WORD2_M0SM. */ #define BM_MPU_RGDn_WORD2_M0SM (0x00000018U) /*!< Bit mask for MPU_RGDn_WORD2_M0SM. */ #define BS_MPU_RGDn_WORD2_M0SM (2U) /*!< Bit field size in bits for MPU_RGDn_WORD2_M0SM. */ /*! @brief Read current value of the MPU_RGDn_WORD2_M0SM field. */ #define BR_MPU_RGDn_WORD2_M0SM(x, n) (HW_MPU_RGDn_WORD2(x, n).B.M0SM) /*! @brief Format value for bitfield MPU_RGDn_WORD2_M0SM. */ #define BF_MPU_RGDn_WORD2_M0SM(v) ((uint32_t)((uint32_t)(v) << BP_MPU_RGDn_WORD2_M0SM) & BM_MPU_RGDn_WORD2_M0SM) /*! @brief Set the M0SM field to a new value. */ #define BW_MPU_RGDn_WORD2_M0SM(x, n, v) (HW_MPU_RGDn_WORD2_WR(x, n, (HW_MPU_RGDn_WORD2_RD(x, n) & ~BM_MPU_RGDn_WORD2_M0SM) | BF_MPU_RGDn_WORD2_M0SM(v))) /*@}*/ /*! * @name Register MPU_RGDn_WORD2, field M0PE[5] (RW) * * See M0PE description. */ /*@{*/ #define BP_MPU_RGDn_WORD2_M0PE (5U) /*!< Bit position for MPU_RGDn_WORD2_M0PE. */ #define BM_MPU_RGDn_WORD2_M0PE (0x00000020U) /*!< Bit mask for MPU_RGDn_WORD2_M0PE. */ #define BS_MPU_RGDn_WORD2_M0PE (1U) /*!< Bit field size in bits for MPU_RGDn_WORD2_M0PE. */ /*! @brief Read current value of the MPU_RGDn_WORD2_M0PE field. */ #define BR_MPU_RGDn_WORD2_M0PE(x, n) (BITBAND_ACCESS32(HW_MPU_RGDn_WORD2_ADDR(x, n), BP_MPU_RGDn_WORD2_M0PE)) /*! @brief Format value for bitfield MPU_RGDn_WORD2_M0PE. */ #define BF_MPU_RGDn_WORD2_M0PE(v) ((uint32_t)((uint32_t)(v) << BP_MPU_RGDn_WORD2_M0PE) & BM_MPU_RGDn_WORD2_M0PE) /*! @brief Set the M0PE field to a new value. */ #define BW_MPU_RGDn_WORD2_M0PE(x, n, v) (BITBAND_ACCESS32(HW_MPU_RGDn_WORD2_ADDR(x, n), BP_MPU_RGDn_WORD2_M0PE) = (v)) /*@}*/ /*! * @name Register MPU_RGDn_WORD2, field M1UM[8:6] (RW) * * See M3UM description. */ /*@{*/ #define BP_MPU_RGDn_WORD2_M1UM (6U) /*!< Bit position for MPU_RGDn_WORD2_M1UM. */ #define BM_MPU_RGDn_WORD2_M1UM (0x000001C0U) /*!< Bit mask for MPU_RGDn_WORD2_M1UM. */ #define BS_MPU_RGDn_WORD2_M1UM (3U) /*!< Bit field size in bits for MPU_RGDn_WORD2_M1UM. */ /*! @brief Read current value of the MPU_RGDn_WORD2_M1UM field. */ #define BR_MPU_RGDn_WORD2_M1UM(x, n) (HW_MPU_RGDn_WORD2(x, n).B.M1UM) /*! @brief Format value for bitfield MPU_RGDn_WORD2_M1UM. */ #define BF_MPU_RGDn_WORD2_M1UM(v) ((uint32_t)((uint32_t)(v) << BP_MPU_RGDn_WORD2_M1UM) & BM_MPU_RGDn_WORD2_M1UM) /*! @brief Set the M1UM field to a new value. */ #define BW_MPU_RGDn_WORD2_M1UM(x, n, v) (HW_MPU_RGDn_WORD2_WR(x, n, (HW_MPU_RGDn_WORD2_RD(x, n) & ~BM_MPU_RGDn_WORD2_M1UM) | BF_MPU_RGDn_WORD2_M1UM(v))) /*@}*/ /*! * @name Register MPU_RGDn_WORD2, field M1SM[10:9] (RW) * * See M3SM description. */ /*@{*/ #define BP_MPU_RGDn_WORD2_M1SM (9U) /*!< Bit position for MPU_RGDn_WORD2_M1SM. */ #define BM_MPU_RGDn_WORD2_M1SM (0x00000600U) /*!< Bit mask for MPU_RGDn_WORD2_M1SM. */ #define BS_MPU_RGDn_WORD2_M1SM (2U) /*!< Bit field size in bits for MPU_RGDn_WORD2_M1SM. */ /*! @brief Read current value of the MPU_RGDn_WORD2_M1SM field. */ #define BR_MPU_RGDn_WORD2_M1SM(x, n) (HW_MPU_RGDn_WORD2(x, n).B.M1SM) /*! @brief Format value for bitfield MPU_RGDn_WORD2_M1SM. */ #define BF_MPU_RGDn_WORD2_M1SM(v) ((uint32_t)((uint32_t)(v) << BP_MPU_RGDn_WORD2_M1SM) & BM_MPU_RGDn_WORD2_M1SM) /*! @brief Set the M1SM field to a new value. */ #define BW_MPU_RGDn_WORD2_M1SM(x, n, v) (HW_MPU_RGDn_WORD2_WR(x, n, (HW_MPU_RGDn_WORD2_RD(x, n) & ~BM_MPU_RGDn_WORD2_M1SM) | BF_MPU_RGDn_WORD2_M1SM(v))) /*@}*/ /*! * @name Register MPU_RGDn_WORD2, field M1PE[11] (RW) * * See M3PE description. */ /*@{*/ #define BP_MPU_RGDn_WORD2_M1PE (11U) /*!< Bit position for MPU_RGDn_WORD2_M1PE. */ #define BM_MPU_RGDn_WORD2_M1PE (0x00000800U) /*!< Bit mask for MPU_RGDn_WORD2_M1PE. */ #define BS_MPU_RGDn_WORD2_M1PE (1U) /*!< Bit field size in bits for MPU_RGDn_WORD2_M1PE. */ /*! @brief Read current value of the MPU_RGDn_WORD2_M1PE field. */ #define BR_MPU_RGDn_WORD2_M1PE(x, n) (BITBAND_ACCESS32(HW_MPU_RGDn_WORD2_ADDR(x, n), BP_MPU_RGDn_WORD2_M1PE)) /*! @brief Format value for bitfield MPU_RGDn_WORD2_M1PE. */ #define BF_MPU_RGDn_WORD2_M1PE(v) ((uint32_t)((uint32_t)(v) << BP_MPU_RGDn_WORD2_M1PE) & BM_MPU_RGDn_WORD2_M1PE) /*! @brief Set the M1PE field to a new value. */ #define BW_MPU_RGDn_WORD2_M1PE(x, n, v) (BITBAND_ACCESS32(HW_MPU_RGDn_WORD2_ADDR(x, n), BP_MPU_RGDn_WORD2_M1PE) = (v)) /*@}*/ /*! * @name Register MPU_RGDn_WORD2, field M2UM[14:12] (RW) * * See M3UM description. */ /*@{*/ #define BP_MPU_RGDn_WORD2_M2UM (12U) /*!< Bit position for MPU_RGDn_WORD2_M2UM. */ #define BM_MPU_RGDn_WORD2_M2UM (0x00007000U) /*!< Bit mask for MPU_RGDn_WORD2_M2UM. */ #define BS_MPU_RGDn_WORD2_M2UM (3U) /*!< Bit field size in bits for MPU_RGDn_WORD2_M2UM. */ /*! @brief Read current value of the MPU_RGDn_WORD2_M2UM field. */ #define BR_MPU_RGDn_WORD2_M2UM(x, n) (HW_MPU_RGDn_WORD2(x, n).B.M2UM) /*! @brief Format value for bitfield MPU_RGDn_WORD2_M2UM. */ #define BF_MPU_RGDn_WORD2_M2UM(v) ((uint32_t)((uint32_t)(v) << BP_MPU_RGDn_WORD2_M2UM) & BM_MPU_RGDn_WORD2_M2UM) /*! @brief Set the M2UM field to a new value. */ #define BW_MPU_RGDn_WORD2_M2UM(x, n, v) (HW_MPU_RGDn_WORD2_WR(x, n, (HW_MPU_RGDn_WORD2_RD(x, n) & ~BM_MPU_RGDn_WORD2_M2UM) | BF_MPU_RGDn_WORD2_M2UM(v))) /*@}*/ /*! * @name Register MPU_RGDn_WORD2, field M2SM[16:15] (RW) * * See M3SM description. */ /*@{*/ #define BP_MPU_RGDn_WORD2_M2SM (15U) /*!< Bit position for MPU_RGDn_WORD2_M2SM. */ #define BM_MPU_RGDn_WORD2_M2SM (0x00018000U) /*!< Bit mask for MPU_RGDn_WORD2_M2SM. */ #define BS_MPU_RGDn_WORD2_M2SM (2U) /*!< Bit field size in bits for MPU_RGDn_WORD2_M2SM. */ /*! @brief Read current value of the MPU_RGDn_WORD2_M2SM field. */ #define BR_MPU_RGDn_WORD2_M2SM(x, n) (HW_MPU_RGDn_WORD2(x, n).B.M2SM) /*! @brief Format value for bitfield MPU_RGDn_WORD2_M2SM. */ #define BF_MPU_RGDn_WORD2_M2SM(v) ((uint32_t)((uint32_t)(v) << BP_MPU_RGDn_WORD2_M2SM) & BM_MPU_RGDn_WORD2_M2SM) /*! @brief Set the M2SM field to a new value. */ #define BW_MPU_RGDn_WORD2_M2SM(x, n, v) (HW_MPU_RGDn_WORD2_WR(x, n, (HW_MPU_RGDn_WORD2_RD(x, n) & ~BM_MPU_RGDn_WORD2_M2SM) | BF_MPU_RGDn_WORD2_M2SM(v))) /*@}*/ /*! * @name Register MPU_RGDn_WORD2, field M2PE[17] (RW) * * See M3PE description. */ /*@{*/ #define BP_MPU_RGDn_WORD2_M2PE (17U) /*!< Bit position for MPU_RGDn_WORD2_M2PE. */ #define BM_MPU_RGDn_WORD2_M2PE (0x00020000U) /*!< Bit mask for MPU_RGDn_WORD2_M2PE. */ #define BS_MPU_RGDn_WORD2_M2PE (1U) /*!< Bit field size in bits for MPU_RGDn_WORD2_M2PE. */ /*! @brief Read current value of the MPU_RGDn_WORD2_M2PE field. */ #define BR_MPU_RGDn_WORD2_M2PE(x, n) (BITBAND_ACCESS32(HW_MPU_RGDn_WORD2_ADDR(x, n), BP_MPU_RGDn_WORD2_M2PE)) /*! @brief Format value for bitfield MPU_RGDn_WORD2_M2PE. */ #define BF_MPU_RGDn_WORD2_M2PE(v) ((uint32_t)((uint32_t)(v) << BP_MPU_RGDn_WORD2_M2PE) & BM_MPU_RGDn_WORD2_M2PE) /*! @brief Set the M2PE field to a new value. */ #define BW_MPU_RGDn_WORD2_M2PE(x, n, v) (BITBAND_ACCESS32(HW_MPU_RGDn_WORD2_ADDR(x, n), BP_MPU_RGDn_WORD2_M2PE) = (v)) /*@}*/ /*! * @name Register MPU_RGDn_WORD2, field M3UM[20:18] (RW) * * Defines the access controls for bus master 3 in User mode. M3UM consists of * three independent bits, enabling read (r), write (w), and execute (x) * permissions. * * Values: * - 0 - An attempted access of that mode may be terminated with an access error * (if not allowed by another descriptor) and the access not performed. * - 1 - Allows the given access type to occur */ /*@{*/ #define BP_MPU_RGDn_WORD2_M3UM (18U) /*!< Bit position for MPU_RGDn_WORD2_M3UM. */ #define BM_MPU_RGDn_WORD2_M3UM (0x001C0000U) /*!< Bit mask for MPU_RGDn_WORD2_M3UM. */ #define BS_MPU_RGDn_WORD2_M3UM (3U) /*!< Bit field size in bits for MPU_RGDn_WORD2_M3UM. */ /*! @brief Read current value of the MPU_RGDn_WORD2_M3UM field. */ #define BR_MPU_RGDn_WORD2_M3UM(x, n) (HW_MPU_RGDn_WORD2(x, n).B.M3UM) /*! @brief Format value for bitfield MPU_RGDn_WORD2_M3UM. */ #define BF_MPU_RGDn_WORD2_M3UM(v) ((uint32_t)((uint32_t)(v) << BP_MPU_RGDn_WORD2_M3UM) & BM_MPU_RGDn_WORD2_M3UM) /*! @brief Set the M3UM field to a new value. */ #define BW_MPU_RGDn_WORD2_M3UM(x, n, v) (HW_MPU_RGDn_WORD2_WR(x, n, (HW_MPU_RGDn_WORD2_RD(x, n) & ~BM_MPU_RGDn_WORD2_M3UM) | BF_MPU_RGDn_WORD2_M3UM(v))) /*@}*/ /*! * @name Register MPU_RGDn_WORD2, field M3SM[22:21] (RW) * * Defines the access controls for bus master 3 in Supervisor mode. * * Values: * - 00 - r/w/x; read, write and execute allowed * - 01 - r/x; read and execute allowed, but no write * - 10 - r/w; read and write allowed, but no execute * - 11 - Same as User mode defined in M3UM */ /*@{*/ #define BP_MPU_RGDn_WORD2_M3SM (21U) /*!< Bit position for MPU_RGDn_WORD2_M3SM. */ #define BM_MPU_RGDn_WORD2_M3SM (0x00600000U) /*!< Bit mask for MPU_RGDn_WORD2_M3SM. */ #define BS_MPU_RGDn_WORD2_M3SM (2U) /*!< Bit field size in bits for MPU_RGDn_WORD2_M3SM. */ /*! @brief Read current value of the MPU_RGDn_WORD2_M3SM field. */ #define BR_MPU_RGDn_WORD2_M3SM(x, n) (HW_MPU_RGDn_WORD2(x, n).B.M3SM) /*! @brief Format value for bitfield MPU_RGDn_WORD2_M3SM. */ #define BF_MPU_RGDn_WORD2_M3SM(v) ((uint32_t)((uint32_t)(v) << BP_MPU_RGDn_WORD2_M3SM) & BM_MPU_RGDn_WORD2_M3SM) /*! @brief Set the M3SM field to a new value. */ #define BW_MPU_RGDn_WORD2_M3SM(x, n, v) (HW_MPU_RGDn_WORD2_WR(x, n, (HW_MPU_RGDn_WORD2_RD(x, n) & ~BM_MPU_RGDn_WORD2_M3SM) | BF_MPU_RGDn_WORD2_M3SM(v))) /*@}*/ /*! * @name Register MPU_RGDn_WORD2, field M3PE[23] (RW) * * Values: * - 0 - Do not include the process identifier in the evaluation * - 1 - Include the process identifier and mask (RGDn_WORD3) in the region hit * evaluation */ /*@{*/ #define BP_MPU_RGDn_WORD2_M3PE (23U) /*!< Bit position for MPU_RGDn_WORD2_M3PE. */ #define BM_MPU_RGDn_WORD2_M3PE (0x00800000U) /*!< Bit mask for MPU_RGDn_WORD2_M3PE. */ #define BS_MPU_RGDn_WORD2_M3PE (1U) /*!< Bit field size in bits for MPU_RGDn_WORD2_M3PE. */ /*! @brief Read current value of the MPU_RGDn_WORD2_M3PE field. */ #define BR_MPU_RGDn_WORD2_M3PE(x, n) (BITBAND_ACCESS32(HW_MPU_RGDn_WORD2_ADDR(x, n), BP_MPU_RGDn_WORD2_M3PE)) /*! @brief Format value for bitfield MPU_RGDn_WORD2_M3PE. */ #define BF_MPU_RGDn_WORD2_M3PE(v) ((uint32_t)((uint32_t)(v) << BP_MPU_RGDn_WORD2_M3PE) & BM_MPU_RGDn_WORD2_M3PE) /*! @brief Set the M3PE field to a new value. */ #define BW_MPU_RGDn_WORD2_M3PE(x, n, v) (BITBAND_ACCESS32(HW_MPU_RGDn_WORD2_ADDR(x, n), BP_MPU_RGDn_WORD2_M3PE) = (v)) /*@}*/ /*! * @name Register MPU_RGDn_WORD2, field M4WE[24] (RW) * * Values: * - 0 - Bus master 4 writes terminate with an access error and the write is not * performed * - 1 - Bus master 4 writes allowed */ /*@{*/ #define BP_MPU_RGDn_WORD2_M4WE (24U) /*!< Bit position for MPU_RGDn_WORD2_M4WE. */ #define BM_MPU_RGDn_WORD2_M4WE (0x01000000U) /*!< Bit mask for MPU_RGDn_WORD2_M4WE. */ #define BS_MPU_RGDn_WORD2_M4WE (1U) /*!< Bit field size in bits for MPU_RGDn_WORD2_M4WE. */ /*! @brief Read current value of the MPU_RGDn_WORD2_M4WE field. */ #define BR_MPU_RGDn_WORD2_M4WE(x, n) (BITBAND_ACCESS32(HW_MPU_RGDn_WORD2_ADDR(x, n), BP_MPU_RGDn_WORD2_M4WE)) /*! @brief Format value for bitfield MPU_RGDn_WORD2_M4WE. */ #define BF_MPU_RGDn_WORD2_M4WE(v) ((uint32_t)((uint32_t)(v) << BP_MPU_RGDn_WORD2_M4WE) & BM_MPU_RGDn_WORD2_M4WE) /*! @brief Set the M4WE field to a new value. */ #define BW_MPU_RGDn_WORD2_M4WE(x, n, v) (BITBAND_ACCESS32(HW_MPU_RGDn_WORD2_ADDR(x, n), BP_MPU_RGDn_WORD2_M4WE) = (v)) /*@}*/ /*! * @name Register MPU_RGDn_WORD2, field M4RE[25] (RW) * * Values: * - 0 - Bus master 4 reads terminate with an access error and the read is not * performed * - 1 - Bus master 4 reads allowed */ /*@{*/ #define BP_MPU_RGDn_WORD2_M4RE (25U) /*!< Bit position for MPU_RGDn_WORD2_M4RE. */ #define BM_MPU_RGDn_WORD2_M4RE (0x02000000U) /*!< Bit mask for MPU_RGDn_WORD2_M4RE. */ #define BS_MPU_RGDn_WORD2_M4RE (1U) /*!< Bit field size in bits for MPU_RGDn_WORD2_M4RE. */ /*! @brief Read current value of the MPU_RGDn_WORD2_M4RE field. */ #define BR_MPU_RGDn_WORD2_M4RE(x, n) (BITBAND_ACCESS32(HW_MPU_RGDn_WORD2_ADDR(x, n), BP_MPU_RGDn_WORD2_M4RE)) /*! @brief Format value for bitfield MPU_RGDn_WORD2_M4RE. */ #define BF_MPU_RGDn_WORD2_M4RE(v) ((uint32_t)((uint32_t)(v) << BP_MPU_RGDn_WORD2_M4RE) & BM_MPU_RGDn_WORD2_M4RE) /*! @brief Set the M4RE field to a new value. */ #define BW_MPU_RGDn_WORD2_M4RE(x, n, v) (BITBAND_ACCESS32(HW_MPU_RGDn_WORD2_ADDR(x, n), BP_MPU_RGDn_WORD2_M4RE) = (v)) /*@}*/ /*! * @name Register MPU_RGDn_WORD2, field M5WE[26] (RW) * * Values: * - 0 - Bus master 5 writes terminate with an access error and the write is not * performed * - 1 - Bus master 5 writes allowed */ /*@{*/ #define BP_MPU_RGDn_WORD2_M5WE (26U) /*!< Bit position for MPU_RGDn_WORD2_M5WE. */ #define BM_MPU_RGDn_WORD2_M5WE (0x04000000U) /*!< Bit mask for MPU_RGDn_WORD2_M5WE. */ #define BS_MPU_RGDn_WORD2_M5WE (1U) /*!< Bit field size in bits for MPU_RGDn_WORD2_M5WE. */ /*! @brief Read current value of the MPU_RGDn_WORD2_M5WE field. */ #define BR_MPU_RGDn_WORD2_M5WE(x, n) (BITBAND_ACCESS32(HW_MPU_RGDn_WORD2_ADDR(x, n), BP_MPU_RGDn_WORD2_M5WE)) /*! @brief Format value for bitfield MPU_RGDn_WORD2_M5WE. */ #define BF_MPU_RGDn_WORD2_M5WE(v) ((uint32_t)((uint32_t)(v) << BP_MPU_RGDn_WORD2_M5WE) & BM_MPU_RGDn_WORD2_M5WE) /*! @brief Set the M5WE field to a new value. */ #define BW_MPU_RGDn_WORD2_M5WE(x, n, v) (BITBAND_ACCESS32(HW_MPU_RGDn_WORD2_ADDR(x, n), BP_MPU_RGDn_WORD2_M5WE) = (v)) /*@}*/ /*! * @name Register MPU_RGDn_WORD2, field M5RE[27] (RW) * * Values: * - 0 - Bus master 5 reads terminate with an access error and the read is not * performed * - 1 - Bus master 5 reads allowed */ /*@{*/ #define BP_MPU_RGDn_WORD2_M5RE (27U) /*!< Bit position for MPU_RGDn_WORD2_M5RE. */ #define BM_MPU_RGDn_WORD2_M5RE (0x08000000U) /*!< Bit mask for MPU_RGDn_WORD2_M5RE. */ #define BS_MPU_RGDn_WORD2_M5RE (1U) /*!< Bit field size in bits for MPU_RGDn_WORD2_M5RE. */ /*! @brief Read current value of the MPU_RGDn_WORD2_M5RE field. */ #define BR_MPU_RGDn_WORD2_M5RE(x, n) (BITBAND_ACCESS32(HW_MPU_RGDn_WORD2_ADDR(x, n), BP_MPU_RGDn_WORD2_M5RE)) /*! @brief Format value for bitfield MPU_RGDn_WORD2_M5RE. */ #define BF_MPU_RGDn_WORD2_M5RE(v) ((uint32_t)((uint32_t)(v) << BP_MPU_RGDn_WORD2_M5RE) & BM_MPU_RGDn_WORD2_M5RE) /*! @brief Set the M5RE field to a new value. */ #define BW_MPU_RGDn_WORD2_M5RE(x, n, v) (BITBAND_ACCESS32(HW_MPU_RGDn_WORD2_ADDR(x, n), BP_MPU_RGDn_WORD2_M5RE) = (v)) /*@}*/ /*! * @name Register MPU_RGDn_WORD2, field M6WE[28] (RW) * * Values: * - 0 - Bus master 6 writes terminate with an access error and the write is not * performed * - 1 - Bus master 6 writes allowed */ /*@{*/ #define BP_MPU_RGDn_WORD2_M6WE (28U) /*!< Bit position for MPU_RGDn_WORD2_M6WE. */ #define BM_MPU_RGDn_WORD2_M6WE (0x10000000U) /*!< Bit mask for MPU_RGDn_WORD2_M6WE. */ #define BS_MPU_RGDn_WORD2_M6WE (1U) /*!< Bit field size in bits for MPU_RGDn_WORD2_M6WE. */ /*! @brief Read current value of the MPU_RGDn_WORD2_M6WE field. */ #define BR_MPU_RGDn_WORD2_M6WE(x, n) (BITBAND_ACCESS32(HW_MPU_RGDn_WORD2_ADDR(x, n), BP_MPU_RGDn_WORD2_M6WE)) /*! @brief Format value for bitfield MPU_RGDn_WORD2_M6WE. */ #define BF_MPU_RGDn_WORD2_M6WE(v) ((uint32_t)((uint32_t)(v) << BP_MPU_RGDn_WORD2_M6WE) & BM_MPU_RGDn_WORD2_M6WE) /*! @brief Set the M6WE field to a new value. */ #define BW_MPU_RGDn_WORD2_M6WE(x, n, v) (BITBAND_ACCESS32(HW_MPU_RGDn_WORD2_ADDR(x, n), BP_MPU_RGDn_WORD2_M6WE) = (v)) /*@}*/ /*! * @name Register MPU_RGDn_WORD2, field M6RE[29] (RW) * * Values: * - 0 - Bus master 6 reads terminate with an access error and the read is not * performed * - 1 - Bus master 6 reads allowed */ /*@{*/ #define BP_MPU_RGDn_WORD2_M6RE (29U) /*!< Bit position for MPU_RGDn_WORD2_M6RE. */ #define BM_MPU_RGDn_WORD2_M6RE (0x20000000U) /*!< Bit mask for MPU_RGDn_WORD2_M6RE. */ #define BS_MPU_RGDn_WORD2_M6RE (1U) /*!< Bit field size in bits for MPU_RGDn_WORD2_M6RE. */ /*! @brief Read current value of the MPU_RGDn_WORD2_M6RE field. */ #define BR_MPU_RGDn_WORD2_M6RE(x, n) (BITBAND_ACCESS32(HW_MPU_RGDn_WORD2_ADDR(x, n), BP_MPU_RGDn_WORD2_M6RE)) /*! @brief Format value for bitfield MPU_RGDn_WORD2_M6RE. */ #define BF_MPU_RGDn_WORD2_M6RE(v) ((uint32_t)((uint32_t)(v) << BP_MPU_RGDn_WORD2_M6RE) & BM_MPU_RGDn_WORD2_M6RE) /*! @brief Set the M6RE field to a new value. */ #define BW_MPU_RGDn_WORD2_M6RE(x, n, v) (BITBAND_ACCESS32(HW_MPU_RGDn_WORD2_ADDR(x, n), BP_MPU_RGDn_WORD2_M6RE) = (v)) /*@}*/ /*! * @name Register MPU_RGDn_WORD2, field M7WE[30] (RW) * * Values: * - 0 - Bus master 7 writes terminate with an access error and the write is not * performed * - 1 - Bus master 7 writes allowed */ /*@{*/ #define BP_MPU_RGDn_WORD2_M7WE (30U) /*!< Bit position for MPU_RGDn_WORD2_M7WE. */ #define BM_MPU_RGDn_WORD2_M7WE (0x40000000U) /*!< Bit mask for MPU_RGDn_WORD2_M7WE. */ #define BS_MPU_RGDn_WORD2_M7WE (1U) /*!< Bit field size in bits for MPU_RGDn_WORD2_M7WE. */ /*! @brief Read current value of the MPU_RGDn_WORD2_M7WE field. */ #define BR_MPU_RGDn_WORD2_M7WE(x, n) (BITBAND_ACCESS32(HW_MPU_RGDn_WORD2_ADDR(x, n), BP_MPU_RGDn_WORD2_M7WE)) /*! @brief Format value for bitfield MPU_RGDn_WORD2_M7WE. */ #define BF_MPU_RGDn_WORD2_M7WE(v) ((uint32_t)((uint32_t)(v) << BP_MPU_RGDn_WORD2_M7WE) & BM_MPU_RGDn_WORD2_M7WE) /*! @brief Set the M7WE field to a new value. */ #define BW_MPU_RGDn_WORD2_M7WE(x, n, v) (BITBAND_ACCESS32(HW_MPU_RGDn_WORD2_ADDR(x, n), BP_MPU_RGDn_WORD2_M7WE) = (v)) /*@}*/ /*! * @name Register MPU_RGDn_WORD2, field M7RE[31] (RW) * * Values: * - 0 - Bus master 7 reads terminate with an access error and the read is not * performed * - 1 - Bus master 7 reads allowed */ /*@{*/ #define BP_MPU_RGDn_WORD2_M7RE (31U) /*!< Bit position for MPU_RGDn_WORD2_M7RE. */ #define BM_MPU_RGDn_WORD2_M7RE (0x80000000U) /*!< Bit mask for MPU_RGDn_WORD2_M7RE. */ #define BS_MPU_RGDn_WORD2_M7RE (1U) /*!< Bit field size in bits for MPU_RGDn_WORD2_M7RE. */ /*! @brief Read current value of the MPU_RGDn_WORD2_M7RE field. */ #define BR_MPU_RGDn_WORD2_M7RE(x, n) (BITBAND_ACCESS32(HW_MPU_RGDn_WORD2_ADDR(x, n), BP_MPU_RGDn_WORD2_M7RE)) /*! @brief Format value for bitfield MPU_RGDn_WORD2_M7RE. */ #define BF_MPU_RGDn_WORD2_M7RE(v) ((uint32_t)((uint32_t)(v) << BP_MPU_RGDn_WORD2_M7RE) & BM_MPU_RGDn_WORD2_M7RE) /*! @brief Set the M7RE field to a new value. */ #define BW_MPU_RGDn_WORD2_M7RE(x, n, v) (BITBAND_ACCESS32(HW_MPU_RGDn_WORD2_ADDR(x, n), BP_MPU_RGDn_WORD2_M7RE) = (v)) /*@}*/ /******************************************************************************* * HW_MPU_RGDn_WORD3 - Region Descriptor n, Word 3 ******************************************************************************/ /*! * @brief HW_MPU_RGDn_WORD3 - Region Descriptor n, Word 3 (RW) * * Reset value: 0x00000001U * * The fourth word of the region descriptor contains the optional process * identifier and mask, plus the region descriptor's valid bit. */ typedef union _hw_mpu_rgdn_word3 { uint32_t U; struct _hw_mpu_rgdn_word3_bitfields { uint32_t VLD : 1; /*!< [0] Valid */ uint32_t RESERVED0 : 15; /*!< [15:1] */ uint32_t PIDMASK : 8; /*!< [23:16] Process Identifier Mask */ uint32_t PID : 8; /*!< [31:24] Process Identifier */ } B; } hw_mpu_rgdn_word3_t; /*! * @name Constants and macros for entire MPU_RGDn_WORD3 register */ /*@{*/ #define HW_MPU_RGDn_WORD3_COUNT (12U) #define HW_MPU_RGDn_WORD3_ADDR(x, n) ((x) + 0x40CU + (0x10U * (n))) #define HW_MPU_RGDn_WORD3(x, n) (*(__IO hw_mpu_rgdn_word3_t *) HW_MPU_RGDn_WORD3_ADDR(x, n)) #define HW_MPU_RGDn_WORD3_RD(x, n) (HW_MPU_RGDn_WORD3(x, n).U) #define HW_MPU_RGDn_WORD3_WR(x, n, v) (HW_MPU_RGDn_WORD3(x, n).U = (v)) #define HW_MPU_RGDn_WORD3_SET(x, n, v) (HW_MPU_RGDn_WORD3_WR(x, n, HW_MPU_RGDn_WORD3_RD(x, n) | (v))) #define HW_MPU_RGDn_WORD3_CLR(x, n, v) (HW_MPU_RGDn_WORD3_WR(x, n, HW_MPU_RGDn_WORD3_RD(x, n) & ~(v))) #define HW_MPU_RGDn_WORD3_TOG(x, n, v) (HW_MPU_RGDn_WORD3_WR(x, n, HW_MPU_RGDn_WORD3_RD(x, n) ^ (v))) /*@}*/ /* * Constants & macros for individual MPU_RGDn_WORD3 bitfields */ /*! * @name Register MPU_RGDn_WORD3, field VLD[0] (RW) * * Signals the region descriptor is valid. Any write to RGDn_WORD0-2 clears this * bit. * * Values: * - 0 - Region descriptor is invalid * - 1 - Region descriptor is valid */ /*@{*/ #define BP_MPU_RGDn_WORD3_VLD (0U) /*!< Bit position for MPU_RGDn_WORD3_VLD. */ #define BM_MPU_RGDn_WORD3_VLD (0x00000001U) /*!< Bit mask for MPU_RGDn_WORD3_VLD. */ #define BS_MPU_RGDn_WORD3_VLD (1U) /*!< Bit field size in bits for MPU_RGDn_WORD3_VLD. */ /*! @brief Read current value of the MPU_RGDn_WORD3_VLD field. */ #define BR_MPU_RGDn_WORD3_VLD(x, n) (BITBAND_ACCESS32(HW_MPU_RGDn_WORD3_ADDR(x, n), BP_MPU_RGDn_WORD3_VLD)) /*! @brief Format value for bitfield MPU_RGDn_WORD3_VLD. */ #define BF_MPU_RGDn_WORD3_VLD(v) ((uint32_t)((uint32_t)(v) << BP_MPU_RGDn_WORD3_VLD) & BM_MPU_RGDn_WORD3_VLD) /*! @brief Set the VLD field to a new value. */ #define BW_MPU_RGDn_WORD3_VLD(x, n, v) (BITBAND_ACCESS32(HW_MPU_RGDn_WORD3_ADDR(x, n), BP_MPU_RGDn_WORD3_VLD) = (v)) /*@}*/ /*! * @name Register MPU_RGDn_WORD3, field PIDMASK[23:16] (RW) * * Provides a masking capability so that multiple process identifiers can be * included as part of the region hit determination. If a bit in PIDMASK is set, * then the corresponding PID bit is ignored in the comparison. This field and PID * are included in the region hit determination if RGDn_WORD2[MxPE] is set. For * more information on the handling of the PID and PIDMASK, see "Access Evaluation * - Hit Determination." */ /*@{*/ #define BP_MPU_RGDn_WORD3_PIDMASK (16U) /*!< Bit position for MPU_RGDn_WORD3_PIDMASK. */ #define BM_MPU_RGDn_WORD3_PIDMASK (0x00FF0000U) /*!< Bit mask for MPU_RGDn_WORD3_PIDMASK. */ #define BS_MPU_RGDn_WORD3_PIDMASK (8U) /*!< Bit field size in bits for MPU_RGDn_WORD3_PIDMASK. */ /*! @brief Read current value of the MPU_RGDn_WORD3_PIDMASK field. */ #define BR_MPU_RGDn_WORD3_PIDMASK(x, n) (HW_MPU_RGDn_WORD3(x, n).B.PIDMASK) /*! @brief Format value for bitfield MPU_RGDn_WORD3_PIDMASK. */ #define BF_MPU_RGDn_WORD3_PIDMASK(v) ((uint32_t)((uint32_t)(v) << BP_MPU_RGDn_WORD3_PIDMASK) & BM_MPU_RGDn_WORD3_PIDMASK) /*! @brief Set the PIDMASK field to a new value. */ #define BW_MPU_RGDn_WORD3_PIDMASK(x, n, v) (HW_MPU_RGDn_WORD3_WR(x, n, (HW_MPU_RGDn_WORD3_RD(x, n) & ~BM_MPU_RGDn_WORD3_PIDMASK) | BF_MPU_RGDn_WORD3_PIDMASK(v))) /*@}*/ /*! * @name Register MPU_RGDn_WORD3, field PID[31:24] (RW) * * Specifies the process identifier that is included in the region hit * determination if RGDn_WORD2[MxPE] is set. PIDMASK can mask individual bits in this * field. */ /*@{*/ #define BP_MPU_RGDn_WORD3_PID (24U) /*!< Bit position for MPU_RGDn_WORD3_PID. */ #define BM_MPU_RGDn_WORD3_PID (0xFF000000U) /*!< Bit mask for MPU_RGDn_WORD3_PID. */ #define BS_MPU_RGDn_WORD3_PID (8U) /*!< Bit field size in bits for MPU_RGDn_WORD3_PID. */ /*! @brief Read current value of the MPU_RGDn_WORD3_PID field. */ #define BR_MPU_RGDn_WORD3_PID(x, n) (HW_MPU_RGDn_WORD3(x, n).B.PID) /*! @brief Format value for bitfield MPU_RGDn_WORD3_PID. */ #define BF_MPU_RGDn_WORD3_PID(v) ((uint32_t)((uint32_t)(v) << BP_MPU_RGDn_WORD3_PID) & BM_MPU_RGDn_WORD3_PID) /*! @brief Set the PID field to a new value. */ #define BW_MPU_RGDn_WORD3_PID(x, n, v) (HW_MPU_RGDn_WORD3_WR(x, n, (HW_MPU_RGDn_WORD3_RD(x, n) & ~BM_MPU_RGDn_WORD3_PID) | BF_MPU_RGDn_WORD3_PID(v))) /*@}*/ /******************************************************************************* * HW_MPU_RGDAACn - Region Descriptor Alternate Access Control n ******************************************************************************/ /*! * @brief HW_MPU_RGDAACn - Region Descriptor Alternate Access Control n (RW) * * Reset value: 0x0061F7DFU * * Because software may adjust only the access controls within a region * descriptor (RGDn_WORD2) as different tasks execute, an alternate programming view of * this 32-bit entity is available. Writing to this register does not affect the * descriptor's valid bit. */ typedef union _hw_mpu_rgdaacn { uint32_t U; struct _hw_mpu_rgdaacn_bitfields { uint32_t M0UM : 3; /*!< [2:0] Bus Master 0 User Mode Access Control */ uint32_t M0SM : 2; /*!< [4:3] Bus Master 0 Supervisor Mode Access * Control */ uint32_t M0PE : 1; /*!< [5] Bus Master 0 Process Identifier Enable */ uint32_t M1UM : 3; /*!< [8:6] Bus Master 1 User Mode Access Control */ uint32_t M1SM : 2; /*!< [10:9] Bus Master 1 Supervisor Mode Access * Control */ uint32_t M1PE : 1; /*!< [11] Bus Master 1 Process Identifier Enable */ uint32_t M2UM : 3; /*!< [14:12] Bus Master 2 User Mode Access Control * */ uint32_t M2SM : 2; /*!< [16:15] Bus Master 2 Supervisor Mode Access * Control */ uint32_t M2PE : 1; /*!< [17] Bus Master 2 Process Identifier Enable */ uint32_t M3UM : 3; /*!< [20:18] Bus Master 3 User Mode Access Control * */ uint32_t M3SM : 2; /*!< [22:21] Bus Master 3 Supervisor Mode Access * Control */ uint32_t M3PE : 1; /*!< [23] Bus Master 3 Process Identifier Enable */ uint32_t M4WE : 1; /*!< [24] Bus Master 4 Write Enable */ uint32_t M4RE : 1; /*!< [25] Bus Master 4 Read Enable */ uint32_t M5WE : 1; /*!< [26] Bus Master 5 Write Enable */ uint32_t M5RE : 1; /*!< [27] Bus Master 5 Read Enable */ uint32_t M6WE : 1; /*!< [28] Bus Master 6 Write Enable */ uint32_t M6RE : 1; /*!< [29] Bus Master 6 Read Enable */ uint32_t M7WE : 1; /*!< [30] Bus Master 7 Write Enable */ uint32_t M7RE : 1; /*!< [31] Bus Master 7 Read Enable */ } B; } hw_mpu_rgdaacn_t; /*! * @name Constants and macros for entire MPU_RGDAACn register */ /*@{*/ #define HW_MPU_RGDAACn_COUNT (12U) #define HW_MPU_RGDAACn_ADDR(x, n) ((x) + 0x800U + (0x4U * (n))) #define HW_MPU_RGDAACn(x, n) (*(__IO hw_mpu_rgdaacn_t *) HW_MPU_RGDAACn_ADDR(x, n)) #define HW_MPU_RGDAACn_RD(x, n) (HW_MPU_RGDAACn(x, n).U) #define HW_MPU_RGDAACn_WR(x, n, v) (HW_MPU_RGDAACn(x, n).U = (v)) #define HW_MPU_RGDAACn_SET(x, n, v) (HW_MPU_RGDAACn_WR(x, n, HW_MPU_RGDAACn_RD(x, n) | (v))) #define HW_MPU_RGDAACn_CLR(x, n, v) (HW_MPU_RGDAACn_WR(x, n, HW_MPU_RGDAACn_RD(x, n) & ~(v))) #define HW_MPU_RGDAACn_TOG(x, n, v) (HW_MPU_RGDAACn_WR(x, n, HW_MPU_RGDAACn_RD(x, n) ^ (v))) /*@}*/ /* * Constants & macros for individual MPU_RGDAACn bitfields */ /*! * @name Register MPU_RGDAACn, field M0UM[2:0] (RW) * * See M3UM description. */ /*@{*/ #define BP_MPU_RGDAACn_M0UM (0U) /*!< Bit position for MPU_RGDAACn_M0UM. */ #define BM_MPU_RGDAACn_M0UM (0x00000007U) /*!< Bit mask for MPU_RGDAACn_M0UM. */ #define BS_MPU_RGDAACn_M0UM (3U) /*!< Bit field size in bits for MPU_RGDAACn_M0UM. */ /*! @brief Read current value of the MPU_RGDAACn_M0UM field. */ #define BR_MPU_RGDAACn_M0UM(x, n) (HW_MPU_RGDAACn(x, n).B.M0UM) /*! @brief Format value for bitfield MPU_RGDAACn_M0UM. */ #define BF_MPU_RGDAACn_M0UM(v) ((uint32_t)((uint32_t)(v) << BP_MPU_RGDAACn_M0UM) & BM_MPU_RGDAACn_M0UM) /*! @brief Set the M0UM field to a new value. */ #define BW_MPU_RGDAACn_M0UM(x, n, v) (HW_MPU_RGDAACn_WR(x, n, (HW_MPU_RGDAACn_RD(x, n) & ~BM_MPU_RGDAACn_M0UM) | BF_MPU_RGDAACn_M0UM(v))) /*@}*/ /*! * @name Register MPU_RGDAACn, field M0SM[4:3] (RW) * * See M3SM description. */ /*@{*/ #define BP_MPU_RGDAACn_M0SM (3U) /*!< Bit position for MPU_RGDAACn_M0SM. */ #define BM_MPU_RGDAACn_M0SM (0x00000018U) /*!< Bit mask for MPU_RGDAACn_M0SM. */ #define BS_MPU_RGDAACn_M0SM (2U) /*!< Bit field size in bits for MPU_RGDAACn_M0SM. */ /*! @brief Read current value of the MPU_RGDAACn_M0SM field. */ #define BR_MPU_RGDAACn_M0SM(x, n) (HW_MPU_RGDAACn(x, n).B.M0SM) /*! @brief Format value for bitfield MPU_RGDAACn_M0SM. */ #define BF_MPU_RGDAACn_M0SM(v) ((uint32_t)((uint32_t)(v) << BP_MPU_RGDAACn_M0SM) & BM_MPU_RGDAACn_M0SM) /*! @brief Set the M0SM field to a new value. */ #define BW_MPU_RGDAACn_M0SM(x, n, v) (HW_MPU_RGDAACn_WR(x, n, (HW_MPU_RGDAACn_RD(x, n) & ~BM_MPU_RGDAACn_M0SM) | BF_MPU_RGDAACn_M0SM(v))) /*@}*/ /*! * @name Register MPU_RGDAACn, field M0PE[5] (RW) * * See M3PE description. */ /*@{*/ #define BP_MPU_RGDAACn_M0PE (5U) /*!< Bit position for MPU_RGDAACn_M0PE. */ #define BM_MPU_RGDAACn_M0PE (0x00000020U) /*!< Bit mask for MPU_RGDAACn_M0PE. */ #define BS_MPU_RGDAACn_M0PE (1U) /*!< Bit field size in bits for MPU_RGDAACn_M0PE. */ /*! @brief Read current value of the MPU_RGDAACn_M0PE field. */ #define BR_MPU_RGDAACn_M0PE(x, n) (BITBAND_ACCESS32(HW_MPU_RGDAACn_ADDR(x, n), BP_MPU_RGDAACn_M0PE)) /*! @brief Format value for bitfield MPU_RGDAACn_M0PE. */ #define BF_MPU_RGDAACn_M0PE(v) ((uint32_t)((uint32_t)(v) << BP_MPU_RGDAACn_M0PE) & BM_MPU_RGDAACn_M0PE) /*! @brief Set the M0PE field to a new value. */ #define BW_MPU_RGDAACn_M0PE(x, n, v) (BITBAND_ACCESS32(HW_MPU_RGDAACn_ADDR(x, n), BP_MPU_RGDAACn_M0PE) = (v)) /*@}*/ /*! * @name Register MPU_RGDAACn, field M1UM[8:6] (RW) * * See M3UM description. */ /*@{*/ #define BP_MPU_RGDAACn_M1UM (6U) /*!< Bit position for MPU_RGDAACn_M1UM. */ #define BM_MPU_RGDAACn_M1UM (0x000001C0U) /*!< Bit mask for MPU_RGDAACn_M1UM. */ #define BS_MPU_RGDAACn_M1UM (3U) /*!< Bit field size in bits for MPU_RGDAACn_M1UM. */ /*! @brief Read current value of the MPU_RGDAACn_M1UM field. */ #define BR_MPU_RGDAACn_M1UM(x, n) (HW_MPU_RGDAACn(x, n).B.M1UM) /*! @brief Format value for bitfield MPU_RGDAACn_M1UM. */ #define BF_MPU_RGDAACn_M1UM(v) ((uint32_t)((uint32_t)(v) << BP_MPU_RGDAACn_M1UM) & BM_MPU_RGDAACn_M1UM) /*! @brief Set the M1UM field to a new value. */ #define BW_MPU_RGDAACn_M1UM(x, n, v) (HW_MPU_RGDAACn_WR(x, n, (HW_MPU_RGDAACn_RD(x, n) & ~BM_MPU_RGDAACn_M1UM) | BF_MPU_RGDAACn_M1UM(v))) /*@}*/ /*! * @name Register MPU_RGDAACn, field M1SM[10:9] (RW) * * See M3SM description. */ /*@{*/ #define BP_MPU_RGDAACn_M1SM (9U) /*!< Bit position for MPU_RGDAACn_M1SM. */ #define BM_MPU_RGDAACn_M1SM (0x00000600U) /*!< Bit mask for MPU_RGDAACn_M1SM. */ #define BS_MPU_RGDAACn_M1SM (2U) /*!< Bit field size in bits for MPU_RGDAACn_M1SM. */ /*! @brief Read current value of the MPU_RGDAACn_M1SM field. */ #define BR_MPU_RGDAACn_M1SM(x, n) (HW_MPU_RGDAACn(x, n).B.M1SM) /*! @brief Format value for bitfield MPU_RGDAACn_M1SM. */ #define BF_MPU_RGDAACn_M1SM(v) ((uint32_t)((uint32_t)(v) << BP_MPU_RGDAACn_M1SM) & BM_MPU_RGDAACn_M1SM) /*! @brief Set the M1SM field to a new value. */ #define BW_MPU_RGDAACn_M1SM(x, n, v) (HW_MPU_RGDAACn_WR(x, n, (HW_MPU_RGDAACn_RD(x, n) & ~BM_MPU_RGDAACn_M1SM) | BF_MPU_RGDAACn_M1SM(v))) /*@}*/ /*! * @name Register MPU_RGDAACn, field M1PE[11] (RW) * * See M3PE description. */ /*@{*/ #define BP_MPU_RGDAACn_M1PE (11U) /*!< Bit position for MPU_RGDAACn_M1PE. */ #define BM_MPU_RGDAACn_M1PE (0x00000800U) /*!< Bit mask for MPU_RGDAACn_M1PE. */ #define BS_MPU_RGDAACn_M1PE (1U) /*!< Bit field size in bits for MPU_RGDAACn_M1PE. */ /*! @brief Read current value of the MPU_RGDAACn_M1PE field. */ #define BR_MPU_RGDAACn_M1PE(x, n) (BITBAND_ACCESS32(HW_MPU_RGDAACn_ADDR(x, n), BP_MPU_RGDAACn_M1PE)) /*! @brief Format value for bitfield MPU_RGDAACn_M1PE. */ #define BF_MPU_RGDAACn_M1PE(v) ((uint32_t)((uint32_t)(v) << BP_MPU_RGDAACn_M1PE) & BM_MPU_RGDAACn_M1PE) /*! @brief Set the M1PE field to a new value. */ #define BW_MPU_RGDAACn_M1PE(x, n, v) (BITBAND_ACCESS32(HW_MPU_RGDAACn_ADDR(x, n), BP_MPU_RGDAACn_M1PE) = (v)) /*@}*/ /*! * @name Register MPU_RGDAACn, field M2UM[14:12] (RW) * * See M3UM description. */ /*@{*/ #define BP_MPU_RGDAACn_M2UM (12U) /*!< Bit position for MPU_RGDAACn_M2UM. */ #define BM_MPU_RGDAACn_M2UM (0x00007000U) /*!< Bit mask for MPU_RGDAACn_M2UM. */ #define BS_MPU_RGDAACn_M2UM (3U) /*!< Bit field size in bits for MPU_RGDAACn_M2UM. */ /*! @brief Read current value of the MPU_RGDAACn_M2UM field. */ #define BR_MPU_RGDAACn_M2UM(x, n) (HW_MPU_RGDAACn(x, n).B.M2UM) /*! @brief Format value for bitfield MPU_RGDAACn_M2UM. */ #define BF_MPU_RGDAACn_M2UM(v) ((uint32_t)((uint32_t)(v) << BP_MPU_RGDAACn_M2UM) & BM_MPU_RGDAACn_M2UM) /*! @brief Set the M2UM field to a new value. */ #define BW_MPU_RGDAACn_M2UM(x, n, v) (HW_MPU_RGDAACn_WR(x, n, (HW_MPU_RGDAACn_RD(x, n) & ~BM_MPU_RGDAACn_M2UM) | BF_MPU_RGDAACn_M2UM(v))) /*@}*/ /*! * @name Register MPU_RGDAACn, field M2SM[16:15] (RW) * * See M3SM description. */ /*@{*/ #define BP_MPU_RGDAACn_M2SM (15U) /*!< Bit position for MPU_RGDAACn_M2SM. */ #define BM_MPU_RGDAACn_M2SM (0x00018000U) /*!< Bit mask for MPU_RGDAACn_M2SM. */ #define BS_MPU_RGDAACn_M2SM (2U) /*!< Bit field size in bits for MPU_RGDAACn_M2SM. */ /*! @brief Read current value of the MPU_RGDAACn_M2SM field. */ #define BR_MPU_RGDAACn_M2SM(x, n) (HW_MPU_RGDAACn(x, n).B.M2SM) /*! @brief Format value for bitfield MPU_RGDAACn_M2SM. */ #define BF_MPU_RGDAACn_M2SM(v) ((uint32_t)((uint32_t)(v) << BP_MPU_RGDAACn_M2SM) & BM_MPU_RGDAACn_M2SM) /*! @brief Set the M2SM field to a new value. */ #define BW_MPU_RGDAACn_M2SM(x, n, v) (HW_MPU_RGDAACn_WR(x, n, (HW_MPU_RGDAACn_RD(x, n) & ~BM_MPU_RGDAACn_M2SM) | BF_MPU_RGDAACn_M2SM(v))) /*@}*/ /*! * @name Register MPU_RGDAACn, field M2PE[17] (RW) * * See M3PE description. */ /*@{*/ #define BP_MPU_RGDAACn_M2PE (17U) /*!< Bit position for MPU_RGDAACn_M2PE. */ #define BM_MPU_RGDAACn_M2PE (0x00020000U) /*!< Bit mask for MPU_RGDAACn_M2PE. */ #define BS_MPU_RGDAACn_M2PE (1U) /*!< Bit field size in bits for MPU_RGDAACn_M2PE. */ /*! @brief Read current value of the MPU_RGDAACn_M2PE field. */ #define BR_MPU_RGDAACn_M2PE(x, n) (BITBAND_ACCESS32(HW_MPU_RGDAACn_ADDR(x, n), BP_MPU_RGDAACn_M2PE)) /*! @brief Format value for bitfield MPU_RGDAACn_M2PE. */ #define BF_MPU_RGDAACn_M2PE(v) ((uint32_t)((uint32_t)(v) << BP_MPU_RGDAACn_M2PE) & BM_MPU_RGDAACn_M2PE) /*! @brief Set the M2PE field to a new value. */ #define BW_MPU_RGDAACn_M2PE(x, n, v) (BITBAND_ACCESS32(HW_MPU_RGDAACn_ADDR(x, n), BP_MPU_RGDAACn_M2PE) = (v)) /*@}*/ /*! * @name Register MPU_RGDAACn, field M3UM[20:18] (RW) * * Defines the access controls for bus master 3 in user mode. M3UM consists of * three independent bits, enabling read (r), write (w), and execute (x) * permissions. * * Values: * - 0 - An attempted access of that mode may be terminated with an access error * (if not allowed by another descriptor) and the access not performed. * - 1 - Allows the given access type to occur */ /*@{*/ #define BP_MPU_RGDAACn_M3UM (18U) /*!< Bit position for MPU_RGDAACn_M3UM. */ #define BM_MPU_RGDAACn_M3UM (0x001C0000U) /*!< Bit mask for MPU_RGDAACn_M3UM. */ #define BS_MPU_RGDAACn_M3UM (3U) /*!< Bit field size in bits for MPU_RGDAACn_M3UM. */ /*! @brief Read current value of the MPU_RGDAACn_M3UM field. */ #define BR_MPU_RGDAACn_M3UM(x, n) (HW_MPU_RGDAACn(x, n).B.M3UM) /*! @brief Format value for bitfield MPU_RGDAACn_M3UM. */ #define BF_MPU_RGDAACn_M3UM(v) ((uint32_t)((uint32_t)(v) << BP_MPU_RGDAACn_M3UM) & BM_MPU_RGDAACn_M3UM) /*! @brief Set the M3UM field to a new value. */ #define BW_MPU_RGDAACn_M3UM(x, n, v) (HW_MPU_RGDAACn_WR(x, n, (HW_MPU_RGDAACn_RD(x, n) & ~BM_MPU_RGDAACn_M3UM) | BF_MPU_RGDAACn_M3UM(v))) /*@}*/ /*! * @name Register MPU_RGDAACn, field M3SM[22:21] (RW) * * Defines the access controls for bus master 3 in Supervisor mode. * * Values: * - 00 - r/w/x; read, write and execute allowed * - 01 - r/x; read and execute allowed, but no write * - 10 - r/w; read and write allowed, but no execute * - 11 - Same as User mode defined in M3UM */ /*@{*/ #define BP_MPU_RGDAACn_M3SM (21U) /*!< Bit position for MPU_RGDAACn_M3SM. */ #define BM_MPU_RGDAACn_M3SM (0x00600000U) /*!< Bit mask for MPU_RGDAACn_M3SM. */ #define BS_MPU_RGDAACn_M3SM (2U) /*!< Bit field size in bits for MPU_RGDAACn_M3SM. */ /*! @brief Read current value of the MPU_RGDAACn_M3SM field. */ #define BR_MPU_RGDAACn_M3SM(x, n) (HW_MPU_RGDAACn(x, n).B.M3SM) /*! @brief Format value for bitfield MPU_RGDAACn_M3SM. */ #define BF_MPU_RGDAACn_M3SM(v) ((uint32_t)((uint32_t)(v) << BP_MPU_RGDAACn_M3SM) & BM_MPU_RGDAACn_M3SM) /*! @brief Set the M3SM field to a new value. */ #define BW_MPU_RGDAACn_M3SM(x, n, v) (HW_MPU_RGDAACn_WR(x, n, (HW_MPU_RGDAACn_RD(x, n) & ~BM_MPU_RGDAACn_M3SM) | BF_MPU_RGDAACn_M3SM(v))) /*@}*/ /*! * @name Register MPU_RGDAACn, field M3PE[23] (RW) * * Values: * - 0 - Do not include the process identifier in the evaluation * - 1 - Include the process identifier and mask (RGDn.RGDAAC) in the region hit * evaluation */ /*@{*/ #define BP_MPU_RGDAACn_M3PE (23U) /*!< Bit position for MPU_RGDAACn_M3PE. */ #define BM_MPU_RGDAACn_M3PE (0x00800000U) /*!< Bit mask for MPU_RGDAACn_M3PE. */ #define BS_MPU_RGDAACn_M3PE (1U) /*!< Bit field size in bits for MPU_RGDAACn_M3PE. */ /*! @brief Read current value of the MPU_RGDAACn_M3PE field. */ #define BR_MPU_RGDAACn_M3PE(x, n) (BITBAND_ACCESS32(HW_MPU_RGDAACn_ADDR(x, n), BP_MPU_RGDAACn_M3PE)) /*! @brief Format value for bitfield MPU_RGDAACn_M3PE. */ #define BF_MPU_RGDAACn_M3PE(v) ((uint32_t)((uint32_t)(v) << BP_MPU_RGDAACn_M3PE) & BM_MPU_RGDAACn_M3PE) /*! @brief Set the M3PE field to a new value. */ #define BW_MPU_RGDAACn_M3PE(x, n, v) (BITBAND_ACCESS32(HW_MPU_RGDAACn_ADDR(x, n), BP_MPU_RGDAACn_M3PE) = (v)) /*@}*/ /*! * @name Register MPU_RGDAACn, field M4WE[24] (RW) * * Values: * - 0 - Bus master 4 writes terminate with an access error and the write is not * performed * - 1 - Bus master 4 writes allowed */ /*@{*/ #define BP_MPU_RGDAACn_M4WE (24U) /*!< Bit position for MPU_RGDAACn_M4WE. */ #define BM_MPU_RGDAACn_M4WE (0x01000000U) /*!< Bit mask for MPU_RGDAACn_M4WE. */ #define BS_MPU_RGDAACn_M4WE (1U) /*!< Bit field size in bits for MPU_RGDAACn_M4WE. */ /*! @brief Read current value of the MPU_RGDAACn_M4WE field. */ #define BR_MPU_RGDAACn_M4WE(x, n) (BITBAND_ACCESS32(HW_MPU_RGDAACn_ADDR(x, n), BP_MPU_RGDAACn_M4WE)) /*! @brief Format value for bitfield MPU_RGDAACn_M4WE. */ #define BF_MPU_RGDAACn_M4WE(v) ((uint32_t)((uint32_t)(v) << BP_MPU_RGDAACn_M4WE) & BM_MPU_RGDAACn_M4WE) /*! @brief Set the M4WE field to a new value. */ #define BW_MPU_RGDAACn_M4WE(x, n, v) (BITBAND_ACCESS32(HW_MPU_RGDAACn_ADDR(x, n), BP_MPU_RGDAACn_M4WE) = (v)) /*@}*/ /*! * @name Register MPU_RGDAACn, field M4RE[25] (RW) * * Values: * - 0 - Bus master 4 reads terminate with an access error and the read is not * performed * - 1 - Bus master 4 reads allowed */ /*@{*/ #define BP_MPU_RGDAACn_M4RE (25U) /*!< Bit position for MPU_RGDAACn_M4RE. */ #define BM_MPU_RGDAACn_M4RE (0x02000000U) /*!< Bit mask for MPU_RGDAACn_M4RE. */ #define BS_MPU_RGDAACn_M4RE (1U) /*!< Bit field size in bits for MPU_RGDAACn_M4RE. */ /*! @brief Read current value of the MPU_RGDAACn_M4RE field. */ #define BR_MPU_RGDAACn_M4RE(x, n) (BITBAND_ACCESS32(HW_MPU_RGDAACn_ADDR(x, n), BP_MPU_RGDAACn_M4RE)) /*! @brief Format value for bitfield MPU_RGDAACn_M4RE. */ #define BF_MPU_RGDAACn_M4RE(v) ((uint32_t)((uint32_t)(v) << BP_MPU_RGDAACn_M4RE) & BM_MPU_RGDAACn_M4RE) /*! @brief Set the M4RE field to a new value. */ #define BW_MPU_RGDAACn_M4RE(x, n, v) (BITBAND_ACCESS32(HW_MPU_RGDAACn_ADDR(x, n), BP_MPU_RGDAACn_M4RE) = (v)) /*@}*/ /*! * @name Register MPU_RGDAACn, field M5WE[26] (RW) * * Values: * - 0 - Bus master 5 writes terminate with an access error and the write is not * performed * - 1 - Bus master 5 writes allowed */ /*@{*/ #define BP_MPU_RGDAACn_M5WE (26U) /*!< Bit position for MPU_RGDAACn_M5WE. */ #define BM_MPU_RGDAACn_M5WE (0x04000000U) /*!< Bit mask for MPU_RGDAACn_M5WE. */ #define BS_MPU_RGDAACn_M5WE (1U) /*!< Bit field size in bits for MPU_RGDAACn_M5WE. */ /*! @brief Read current value of the MPU_RGDAACn_M5WE field. */ #define BR_MPU_RGDAACn_M5WE(x, n) (BITBAND_ACCESS32(HW_MPU_RGDAACn_ADDR(x, n), BP_MPU_RGDAACn_M5WE)) /*! @brief Format value for bitfield MPU_RGDAACn_M5WE. */ #define BF_MPU_RGDAACn_M5WE(v) ((uint32_t)((uint32_t)(v) << BP_MPU_RGDAACn_M5WE) & BM_MPU_RGDAACn_M5WE) /*! @brief Set the M5WE field to a new value. */ #define BW_MPU_RGDAACn_M5WE(x, n, v) (BITBAND_ACCESS32(HW_MPU_RGDAACn_ADDR(x, n), BP_MPU_RGDAACn_M5WE) = (v)) /*@}*/ /*! * @name Register MPU_RGDAACn, field M5RE[27] (RW) * * Values: * - 0 - Bus master 5 reads terminate with an access error and the read is not * performed * - 1 - Bus master 5 reads allowed */ /*@{*/ #define BP_MPU_RGDAACn_M5RE (27U) /*!< Bit position for MPU_RGDAACn_M5RE. */ #define BM_MPU_RGDAACn_M5RE (0x08000000U) /*!< Bit mask for MPU_RGDAACn_M5RE. */ #define BS_MPU_RGDAACn_M5RE (1U) /*!< Bit field size in bits for MPU_RGDAACn_M5RE. */ /*! @brief Read current value of the MPU_RGDAACn_M5RE field. */ #define BR_MPU_RGDAACn_M5RE(x, n) (BITBAND_ACCESS32(HW_MPU_RGDAACn_ADDR(x, n), BP_MPU_RGDAACn_M5RE)) /*! @brief Format value for bitfield MPU_RGDAACn_M5RE. */ #define BF_MPU_RGDAACn_M5RE(v) ((uint32_t)((uint32_t)(v) << BP_MPU_RGDAACn_M5RE) & BM_MPU_RGDAACn_M5RE) /*! @brief Set the M5RE field to a new value. */ #define BW_MPU_RGDAACn_M5RE(x, n, v) (BITBAND_ACCESS32(HW_MPU_RGDAACn_ADDR(x, n), BP_MPU_RGDAACn_M5RE) = (v)) /*@}*/ /*! * @name Register MPU_RGDAACn, field M6WE[28] (RW) * * Values: * - 0 - Bus master 6 writes terminate with an access error and the write is not * performed * - 1 - Bus master 6 writes allowed */ /*@{*/ #define BP_MPU_RGDAACn_M6WE (28U) /*!< Bit position for MPU_RGDAACn_M6WE. */ #define BM_MPU_RGDAACn_M6WE (0x10000000U) /*!< Bit mask for MPU_RGDAACn_M6WE. */ #define BS_MPU_RGDAACn_M6WE (1U) /*!< Bit field size in bits for MPU_RGDAACn_M6WE. */ /*! @brief Read current value of the MPU_RGDAACn_M6WE field. */ #define BR_MPU_RGDAACn_M6WE(x, n) (BITBAND_ACCESS32(HW_MPU_RGDAACn_ADDR(x, n), BP_MPU_RGDAACn_M6WE)) /*! @brief Format value for bitfield MPU_RGDAACn_M6WE. */ #define BF_MPU_RGDAACn_M6WE(v) ((uint32_t)((uint32_t)(v) << BP_MPU_RGDAACn_M6WE) & BM_MPU_RGDAACn_M6WE) /*! @brief Set the M6WE field to a new value. */ #define BW_MPU_RGDAACn_M6WE(x, n, v) (BITBAND_ACCESS32(HW_MPU_RGDAACn_ADDR(x, n), BP_MPU_RGDAACn_M6WE) = (v)) /*@}*/ /*! * @name Register MPU_RGDAACn, field M6RE[29] (RW) * * Values: * - 0 - Bus master 6 reads terminate with an access error and the read is not * performed * - 1 - Bus master 6 reads allowed */ /*@{*/ #define BP_MPU_RGDAACn_M6RE (29U) /*!< Bit position for MPU_RGDAACn_M6RE. */ #define BM_MPU_RGDAACn_M6RE (0x20000000U) /*!< Bit mask for MPU_RGDAACn_M6RE. */ #define BS_MPU_RGDAACn_M6RE (1U) /*!< Bit field size in bits for MPU_RGDAACn_M6RE. */ /*! @brief Read current value of the MPU_RGDAACn_M6RE field. */ #define BR_MPU_RGDAACn_M6RE(x, n) (BITBAND_ACCESS32(HW_MPU_RGDAACn_ADDR(x, n), BP_MPU_RGDAACn_M6RE)) /*! @brief Format value for bitfield MPU_RGDAACn_M6RE. */ #define BF_MPU_RGDAACn_M6RE(v) ((uint32_t)((uint32_t)(v) << BP_MPU_RGDAACn_M6RE) & BM_MPU_RGDAACn_M6RE) /*! @brief Set the M6RE field to a new value. */ #define BW_MPU_RGDAACn_M6RE(x, n, v) (BITBAND_ACCESS32(HW_MPU_RGDAACn_ADDR(x, n), BP_MPU_RGDAACn_M6RE) = (v)) /*@}*/ /*! * @name Register MPU_RGDAACn, field M7WE[30] (RW) * * Values: * - 0 - Bus master 7 writes terminate with an access error and the write is not * performed * - 1 - Bus master 7 writes allowed */ /*@{*/ #define BP_MPU_RGDAACn_M7WE (30U) /*!< Bit position for MPU_RGDAACn_M7WE. */ #define BM_MPU_RGDAACn_M7WE (0x40000000U) /*!< Bit mask for MPU_RGDAACn_M7WE. */ #define BS_MPU_RGDAACn_M7WE (1U) /*!< Bit field size in bits for MPU_RGDAACn_M7WE. */ /*! @brief Read current value of the MPU_RGDAACn_M7WE field. */ #define BR_MPU_RGDAACn_M7WE(x, n) (BITBAND_ACCESS32(HW_MPU_RGDAACn_ADDR(x, n), BP_MPU_RGDAACn_M7WE)) /*! @brief Format value for bitfield MPU_RGDAACn_M7WE. */ #define BF_MPU_RGDAACn_M7WE(v) ((uint32_t)((uint32_t)(v) << BP_MPU_RGDAACn_M7WE) & BM_MPU_RGDAACn_M7WE) /*! @brief Set the M7WE field to a new value. */ #define BW_MPU_RGDAACn_M7WE(x, n, v) (BITBAND_ACCESS32(HW_MPU_RGDAACn_ADDR(x, n), BP_MPU_RGDAACn_M7WE) = (v)) /*@}*/ /*! * @name Register MPU_RGDAACn, field M7RE[31] (RW) * * Values: * - 0 - Bus master 7 reads terminate with an access error and the read is not * performed * - 1 - Bus master 7 reads allowed */ /*@{*/ #define BP_MPU_RGDAACn_M7RE (31U) /*!< Bit position for MPU_RGDAACn_M7RE. */ #define BM_MPU_RGDAACn_M7RE (0x80000000U) /*!< Bit mask for MPU_RGDAACn_M7RE. */ #define BS_MPU_RGDAACn_M7RE (1U) /*!< Bit field size in bits for MPU_RGDAACn_M7RE. */ /*! @brief Read current value of the MPU_RGDAACn_M7RE field. */ #define BR_MPU_RGDAACn_M7RE(x, n) (BITBAND_ACCESS32(HW_MPU_RGDAACn_ADDR(x, n), BP_MPU_RGDAACn_M7RE)) /*! @brief Format value for bitfield MPU_RGDAACn_M7RE. */ #define BF_MPU_RGDAACn_M7RE(v) ((uint32_t)((uint32_t)(v) << BP_MPU_RGDAACn_M7RE) & BM_MPU_RGDAACn_M7RE) /*! @brief Set the M7RE field to a new value. */ #define BW_MPU_RGDAACn_M7RE(x, n, v) (BITBAND_ACCESS32(HW_MPU_RGDAACn_ADDR(x, n), BP_MPU_RGDAACn_M7RE) = (v)) /*@}*/ /******************************************************************************* * hw_mpu_t - module struct ******************************************************************************/ /*! * @brief All MPU module registers. */ #pragma pack(1) typedef struct _hw_mpu { __IO hw_mpu_cesr_t CESR; /*!< [0x0] Control/Error Status Register */ uint8_t _reserved0[12]; struct { __I hw_mpu_earn_t EARn; /*!< [0x10] Error Address Register, slave port n */ __I hw_mpu_edrn_t EDRn; /*!< [0x14] Error Detail Register, slave port n */ } SP[5]; uint8_t _reserved1[968]; struct { __IO hw_mpu_rgdn_word0_t RGDn_WORD0; /*!< [0x400] Region Descriptor n, Word 0 */ __IO hw_mpu_rgdn_word1_t RGDn_WORD1; /*!< [0x404] Region Descriptor n, Word 1 */ __IO hw_mpu_rgdn_word2_t RGDn_WORD2; /*!< [0x408] Region Descriptor n, Word 2 */ __IO hw_mpu_rgdn_word3_t RGDn_WORD3; /*!< [0x40C] Region Descriptor n, Word 3 */ } RGD[12]; uint8_t _reserved2[832]; __IO hw_mpu_rgdaacn_t RGDAACn[12]; /*!< [0x800] Region Descriptor Alternate Access Control n */ } hw_mpu_t; #pragma pack() /*! @brief Macro to access all MPU registers. */ /*! @param x MPU module instance base address. */ /*! @return Reference (not a pointer) to the registers struct. To get a pointer to the struct, * use the '&' operator, like &HW_MPU(MPU_BASE). */ #define HW_MPU(x) (*(hw_mpu_t *)(x)) #endif /* __HW_MPU_REGISTERS_H__ */ /* EOF */ ================================================ FILE: Zelig/mbed/TARGET_K64F/TARGET_Freescale/TARGET_KPSDK_MCUS/TARGET_MCU_K64F/device/device/MK64F12/MK64F12_nv.h ================================================ /* ** ################################################################### ** Compilers: Keil ARM C/C++ Compiler ** Freescale C/C++ for Embedded ARM ** GNU C Compiler ** IAR ANSI C/C++ Compiler for ARM ** ** Reference manual: K64P144M120SF5RM, Rev.2, January 2014 ** Version: rev. 2.5, 2014-02-10 ** Build: b140604 ** ** Abstract: ** Extension to the CMSIS register access layer header. ** ** Copyright (c) 2014 Freescale Semiconductor, Inc. ** All rights reserved. ** ** Redistribution and use in source and binary forms, with or without modification, ** are permitted provided that the following conditions are met: ** ** o Redistributions of source code must retain the above copyright notice, this list ** of conditions and the following disclaimer. ** ** o Redistributions in binary form must reproduce the above copyright notice, this ** list of conditions and the following disclaimer in the documentation and/or ** other materials provided with the distribution. ** ** o Neither the name of Freescale Semiconductor, Inc. nor the names of its ** contributors may be used to endorse or promote products derived from this ** software without specific prior written permission. ** ** THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ** ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED ** WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE ** DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT 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. ** ** http: www.freescale.com ** mail: support@freescale.com ** ** Revisions: ** - rev. 1.0 (2013-08-12) ** Initial version. ** - rev. 2.0 (2013-10-29) ** Register accessor macros added to the memory map. ** Symbols for Processor Expert memory map compatibility added to the memory map. ** Startup file for gcc has been updated according to CMSIS 3.2. ** System initialization updated. ** MCG - registers updated. ** PORTA, PORTB, PORTC, PORTE - registers for digital filter removed. ** - rev. 2.1 (2013-10-30) ** Definition of BITBAND macros updated to support peripherals with 32-bit acces disabled. ** - rev. 2.2 (2013-12-09) ** DMA - EARS register removed. ** AIPS0, AIPS1 - MPRA register updated. ** - rev. 2.3 (2014-01-24) ** Update according to reference manual rev. 2 ** ENET, MCG, MCM, SIM, USB - registers updated ** - rev. 2.4 (2014-02-10) ** The declaration of clock configurations has been moved to separate header file system_MK64F12.h ** Update of SystemInit() and SystemCoreClockUpdate() functions. ** - rev. 2.5 (2014-02-10) ** The declaration of clock configurations has been moved to separate header file system_MK64F12.h ** Update of SystemInit() and SystemCoreClockUpdate() functions. ** Module access macro module_BASES replaced by module_BASE_PTRS. ** ** ################################################################### */ /* * WARNING! DO NOT EDIT THIS FILE DIRECTLY! * * This file was generated automatically and any changes may be lost. */ #ifndef __HW_NV_REGISTERS_H__ #define __HW_NV_REGISTERS_H__ #include "MK64F12.h" #include "fsl_bitaccess.h" /* * MK64F12 NV * * Flash configuration field * * Registers defined in this header file: * - HW_NV_BACKKEY3 - Backdoor Comparison Key 3. * - HW_NV_BACKKEY2 - Backdoor Comparison Key 2. * - HW_NV_BACKKEY1 - Backdoor Comparison Key 1. * - HW_NV_BACKKEY0 - Backdoor Comparison Key 0. * - HW_NV_BACKKEY7 - Backdoor Comparison Key 7. * - HW_NV_BACKKEY6 - Backdoor Comparison Key 6. * - HW_NV_BACKKEY5 - Backdoor Comparison Key 5. * - HW_NV_BACKKEY4 - Backdoor Comparison Key 4. * - HW_NV_FPROT3 - Non-volatile P-Flash Protection 1 - Low Register * - HW_NV_FPROT2 - Non-volatile P-Flash Protection 1 - High Register * - HW_NV_FPROT1 - Non-volatile P-Flash Protection 0 - Low Register * - HW_NV_FPROT0 - Non-volatile P-Flash Protection 0 - High Register * - HW_NV_FSEC - Non-volatile Flash Security Register * - HW_NV_FOPT - Non-volatile Flash Option Register * - HW_NV_FEPROT - Non-volatile EERAM Protection Register * - HW_NV_FDPROT - Non-volatile D-Flash Protection Register * * - hw_nv_t - Struct containing all module registers. */ #define HW_NV_INSTANCE_COUNT (1U) /*!< Number of instances of the NV module. */ /******************************************************************************* * HW_NV_BACKKEY3 - Backdoor Comparison Key 3. ******************************************************************************/ /*! * @brief HW_NV_BACKKEY3 - Backdoor Comparison Key 3. (RO) * * Reset value: 0xFFU */ typedef union _hw_nv_backkey3 { uint8_t U; struct _hw_nv_backkey3_bitfields { uint8_t KEY : 8; /*!< [7:0] Backdoor Comparison Key. */ } B; } hw_nv_backkey3_t; /*! * @name Constants and macros for entire NV_BACKKEY3 register */ /*@{*/ #define HW_NV_BACKKEY3_ADDR(x) ((x) + 0x0U) #define HW_NV_BACKKEY3(x) (*(__I hw_nv_backkey3_t *) HW_NV_BACKKEY3_ADDR(x)) #define HW_NV_BACKKEY3_RD(x) (HW_NV_BACKKEY3(x).U) /*@}*/ /* * Constants & macros for individual NV_BACKKEY3 bitfields */ /*! * @name Register NV_BACKKEY3, field KEY[7:0] (RO) */ /*@{*/ #define BP_NV_BACKKEY3_KEY (0U) /*!< Bit position for NV_BACKKEY3_KEY. */ #define BM_NV_BACKKEY3_KEY (0xFFU) /*!< Bit mask for NV_BACKKEY3_KEY. */ #define BS_NV_BACKKEY3_KEY (8U) /*!< Bit field size in bits for NV_BACKKEY3_KEY. */ /*! @brief Read current value of the NV_BACKKEY3_KEY field. */ #define BR_NV_BACKKEY3_KEY(x) (HW_NV_BACKKEY3(x).U) /*@}*/ /******************************************************************************* * HW_NV_BACKKEY2 - Backdoor Comparison Key 2. ******************************************************************************/ /*! * @brief HW_NV_BACKKEY2 - Backdoor Comparison Key 2. (RO) * * Reset value: 0xFFU */ typedef union _hw_nv_backkey2 { uint8_t U; struct _hw_nv_backkey2_bitfields { uint8_t KEY : 8; /*!< [7:0] Backdoor Comparison Key. */ } B; } hw_nv_backkey2_t; /*! * @name Constants and macros for entire NV_BACKKEY2 register */ /*@{*/ #define HW_NV_BACKKEY2_ADDR(x) ((x) + 0x1U) #define HW_NV_BACKKEY2(x) (*(__I hw_nv_backkey2_t *) HW_NV_BACKKEY2_ADDR(x)) #define HW_NV_BACKKEY2_RD(x) (HW_NV_BACKKEY2(x).U) /*@}*/ /* * Constants & macros for individual NV_BACKKEY2 bitfields */ /*! * @name Register NV_BACKKEY2, field KEY[7:0] (RO) */ /*@{*/ #define BP_NV_BACKKEY2_KEY (0U) /*!< Bit position for NV_BACKKEY2_KEY. */ #define BM_NV_BACKKEY2_KEY (0xFFU) /*!< Bit mask for NV_BACKKEY2_KEY. */ #define BS_NV_BACKKEY2_KEY (8U) /*!< Bit field size in bits for NV_BACKKEY2_KEY. */ /*! @brief Read current value of the NV_BACKKEY2_KEY field. */ #define BR_NV_BACKKEY2_KEY(x) (HW_NV_BACKKEY2(x).U) /*@}*/ /******************************************************************************* * HW_NV_BACKKEY1 - Backdoor Comparison Key 1. ******************************************************************************/ /*! * @brief HW_NV_BACKKEY1 - Backdoor Comparison Key 1. (RO) * * Reset value: 0xFFU */ typedef union _hw_nv_backkey1 { uint8_t U; struct _hw_nv_backkey1_bitfields { uint8_t KEY : 8; /*!< [7:0] Backdoor Comparison Key. */ } B; } hw_nv_backkey1_t; /*! * @name Constants and macros for entire NV_BACKKEY1 register */ /*@{*/ #define HW_NV_BACKKEY1_ADDR(x) ((x) + 0x2U) #define HW_NV_BACKKEY1(x) (*(__I hw_nv_backkey1_t *) HW_NV_BACKKEY1_ADDR(x)) #define HW_NV_BACKKEY1_RD(x) (HW_NV_BACKKEY1(x).U) /*@}*/ /* * Constants & macros for individual NV_BACKKEY1 bitfields */ /*! * @name Register NV_BACKKEY1, field KEY[7:0] (RO) */ /*@{*/ #define BP_NV_BACKKEY1_KEY (0U) /*!< Bit position for NV_BACKKEY1_KEY. */ #define BM_NV_BACKKEY1_KEY (0xFFU) /*!< Bit mask for NV_BACKKEY1_KEY. */ #define BS_NV_BACKKEY1_KEY (8U) /*!< Bit field size in bits for NV_BACKKEY1_KEY. */ /*! @brief Read current value of the NV_BACKKEY1_KEY field. */ #define BR_NV_BACKKEY1_KEY(x) (HW_NV_BACKKEY1(x).U) /*@}*/ /******************************************************************************* * HW_NV_BACKKEY0 - Backdoor Comparison Key 0. ******************************************************************************/ /*! * @brief HW_NV_BACKKEY0 - Backdoor Comparison Key 0. (RO) * * Reset value: 0xFFU */ typedef union _hw_nv_backkey0 { uint8_t U; struct _hw_nv_backkey0_bitfields { uint8_t KEY : 8; /*!< [7:0] Backdoor Comparison Key. */ } B; } hw_nv_backkey0_t; /*! * @name Constants and macros for entire NV_BACKKEY0 register */ /*@{*/ #define HW_NV_BACKKEY0_ADDR(x) ((x) + 0x3U) #define HW_NV_BACKKEY0(x) (*(__I hw_nv_backkey0_t *) HW_NV_BACKKEY0_ADDR(x)) #define HW_NV_BACKKEY0_RD(x) (HW_NV_BACKKEY0(x).U) /*@}*/ /* * Constants & macros for individual NV_BACKKEY0 bitfields */ /*! * @name Register NV_BACKKEY0, field KEY[7:0] (RO) */ /*@{*/ #define BP_NV_BACKKEY0_KEY (0U) /*!< Bit position for NV_BACKKEY0_KEY. */ #define BM_NV_BACKKEY0_KEY (0xFFU) /*!< Bit mask for NV_BACKKEY0_KEY. */ #define BS_NV_BACKKEY0_KEY (8U) /*!< Bit field size in bits for NV_BACKKEY0_KEY. */ /*! @brief Read current value of the NV_BACKKEY0_KEY field. */ #define BR_NV_BACKKEY0_KEY(x) (HW_NV_BACKKEY0(x).U) /*@}*/ /******************************************************************************* * HW_NV_BACKKEY7 - Backdoor Comparison Key 7. ******************************************************************************/ /*! * @brief HW_NV_BACKKEY7 - Backdoor Comparison Key 7. (RO) * * Reset value: 0xFFU */ typedef union _hw_nv_backkey7 { uint8_t U; struct _hw_nv_backkey7_bitfields { uint8_t KEY : 8; /*!< [7:0] Backdoor Comparison Key. */ } B; } hw_nv_backkey7_t; /*! * @name Constants and macros for entire NV_BACKKEY7 register */ /*@{*/ #define HW_NV_BACKKEY7_ADDR(x) ((x) + 0x4U) #define HW_NV_BACKKEY7(x) (*(__I hw_nv_backkey7_t *) HW_NV_BACKKEY7_ADDR(x)) #define HW_NV_BACKKEY7_RD(x) (HW_NV_BACKKEY7(x).U) /*@}*/ /* * Constants & macros for individual NV_BACKKEY7 bitfields */ /*! * @name Register NV_BACKKEY7, field KEY[7:0] (RO) */ /*@{*/ #define BP_NV_BACKKEY7_KEY (0U) /*!< Bit position for NV_BACKKEY7_KEY. */ #define BM_NV_BACKKEY7_KEY (0xFFU) /*!< Bit mask for NV_BACKKEY7_KEY. */ #define BS_NV_BACKKEY7_KEY (8U) /*!< Bit field size in bits for NV_BACKKEY7_KEY. */ /*! @brief Read current value of the NV_BACKKEY7_KEY field. */ #define BR_NV_BACKKEY7_KEY(x) (HW_NV_BACKKEY7(x).U) /*@}*/ /******************************************************************************* * HW_NV_BACKKEY6 - Backdoor Comparison Key 6. ******************************************************************************/ /*! * @brief HW_NV_BACKKEY6 - Backdoor Comparison Key 6. (RO) * * Reset value: 0xFFU */ typedef union _hw_nv_backkey6 { uint8_t U; struct _hw_nv_backkey6_bitfields { uint8_t KEY : 8; /*!< [7:0] Backdoor Comparison Key. */ } B; } hw_nv_backkey6_t; /*! * @name Constants and macros for entire NV_BACKKEY6 register */ /*@{*/ #define HW_NV_BACKKEY6_ADDR(x) ((x) + 0x5U) #define HW_NV_BACKKEY6(x) (*(__I hw_nv_backkey6_t *) HW_NV_BACKKEY6_ADDR(x)) #define HW_NV_BACKKEY6_RD(x) (HW_NV_BACKKEY6(x).U) /*@}*/ /* * Constants & macros for individual NV_BACKKEY6 bitfields */ /*! * @name Register NV_BACKKEY6, field KEY[7:0] (RO) */ /*@{*/ #define BP_NV_BACKKEY6_KEY (0U) /*!< Bit position for NV_BACKKEY6_KEY. */ #define BM_NV_BACKKEY6_KEY (0xFFU) /*!< Bit mask for NV_BACKKEY6_KEY. */ #define BS_NV_BACKKEY6_KEY (8U) /*!< Bit field size in bits for NV_BACKKEY6_KEY. */ /*! @brief Read current value of the NV_BACKKEY6_KEY field. */ #define BR_NV_BACKKEY6_KEY(x) (HW_NV_BACKKEY6(x).U) /*@}*/ /******************************************************************************* * HW_NV_BACKKEY5 - Backdoor Comparison Key 5. ******************************************************************************/ /*! * @brief HW_NV_BACKKEY5 - Backdoor Comparison Key 5. (RO) * * Reset value: 0xFFU */ typedef union _hw_nv_backkey5 { uint8_t U; struct _hw_nv_backkey5_bitfields { uint8_t KEY : 8; /*!< [7:0] Backdoor Comparison Key. */ } B; } hw_nv_backkey5_t; /*! * @name Constants and macros for entire NV_BACKKEY5 register */ /*@{*/ #define HW_NV_BACKKEY5_ADDR(x) ((x) + 0x6U) #define HW_NV_BACKKEY5(x) (*(__I hw_nv_backkey5_t *) HW_NV_BACKKEY5_ADDR(x)) #define HW_NV_BACKKEY5_RD(x) (HW_NV_BACKKEY5(x).U) /*@}*/ /* * Constants & macros for individual NV_BACKKEY5 bitfields */ /*! * @name Register NV_BACKKEY5, field KEY[7:0] (RO) */ /*@{*/ #define BP_NV_BACKKEY5_KEY (0U) /*!< Bit position for NV_BACKKEY5_KEY. */ #define BM_NV_BACKKEY5_KEY (0xFFU) /*!< Bit mask for NV_BACKKEY5_KEY. */ #define BS_NV_BACKKEY5_KEY (8U) /*!< Bit field size in bits for NV_BACKKEY5_KEY. */ /*! @brief Read current value of the NV_BACKKEY5_KEY field. */ #define BR_NV_BACKKEY5_KEY(x) (HW_NV_BACKKEY5(x).U) /*@}*/ /******************************************************************************* * HW_NV_BACKKEY4 - Backdoor Comparison Key 4. ******************************************************************************/ /*! * @brief HW_NV_BACKKEY4 - Backdoor Comparison Key 4. (RO) * * Reset value: 0xFFU */ typedef union _hw_nv_backkey4 { uint8_t U; struct _hw_nv_backkey4_bitfields { uint8_t KEY : 8; /*!< [7:0] Backdoor Comparison Key. */ } B; } hw_nv_backkey4_t; /*! * @name Constants and macros for entire NV_BACKKEY4 register */ /*@{*/ #define HW_NV_BACKKEY4_ADDR(x) ((x) + 0x7U) #define HW_NV_BACKKEY4(x) (*(__I hw_nv_backkey4_t *) HW_NV_BACKKEY4_ADDR(x)) #define HW_NV_BACKKEY4_RD(x) (HW_NV_BACKKEY4(x).U) /*@}*/ /* * Constants & macros for individual NV_BACKKEY4 bitfields */ /*! * @name Register NV_BACKKEY4, field KEY[7:0] (RO) */ /*@{*/ #define BP_NV_BACKKEY4_KEY (0U) /*!< Bit position for NV_BACKKEY4_KEY. */ #define BM_NV_BACKKEY4_KEY (0xFFU) /*!< Bit mask for NV_BACKKEY4_KEY. */ #define BS_NV_BACKKEY4_KEY (8U) /*!< Bit field size in bits for NV_BACKKEY4_KEY. */ /*! @brief Read current value of the NV_BACKKEY4_KEY field. */ #define BR_NV_BACKKEY4_KEY(x) (HW_NV_BACKKEY4(x).U) /*@}*/ /******************************************************************************* * HW_NV_FPROT3 - Non-volatile P-Flash Protection 1 - Low Register ******************************************************************************/ /*! * @brief HW_NV_FPROT3 - Non-volatile P-Flash Protection 1 - Low Register (RO) * * Reset value: 0xFFU */ typedef union _hw_nv_fprot3 { uint8_t U; struct _hw_nv_fprot3_bitfields { uint8_t PROT : 8; /*!< [7:0] P-Flash Region Protect */ } B; } hw_nv_fprot3_t; /*! * @name Constants and macros for entire NV_FPROT3 register */ /*@{*/ #define HW_NV_FPROT3_ADDR(x) ((x) + 0x8U) #define HW_NV_FPROT3(x) (*(__I hw_nv_fprot3_t *) HW_NV_FPROT3_ADDR(x)) #define HW_NV_FPROT3_RD(x) (HW_NV_FPROT3(x).U) /*@}*/ /* * Constants & macros for individual NV_FPROT3 bitfields */ /*! * @name Register NV_FPROT3, field PROT[7:0] (RO) */ /*@{*/ #define BP_NV_FPROT3_PROT (0U) /*!< Bit position for NV_FPROT3_PROT. */ #define BM_NV_FPROT3_PROT (0xFFU) /*!< Bit mask for NV_FPROT3_PROT. */ #define BS_NV_FPROT3_PROT (8U) /*!< Bit field size in bits for NV_FPROT3_PROT. */ /*! @brief Read current value of the NV_FPROT3_PROT field. */ #define BR_NV_FPROT3_PROT(x) (HW_NV_FPROT3(x).U) /*@}*/ /******************************************************************************* * HW_NV_FPROT2 - Non-volatile P-Flash Protection 1 - High Register ******************************************************************************/ /*! * @brief HW_NV_FPROT2 - Non-volatile P-Flash Protection 1 - High Register (RO) * * Reset value: 0xFFU */ typedef union _hw_nv_fprot2 { uint8_t U; struct _hw_nv_fprot2_bitfields { uint8_t PROT : 8; /*!< [7:0] P-Flash Region Protect */ } B; } hw_nv_fprot2_t; /*! * @name Constants and macros for entire NV_FPROT2 register */ /*@{*/ #define HW_NV_FPROT2_ADDR(x) ((x) + 0x9U) #define HW_NV_FPROT2(x) (*(__I hw_nv_fprot2_t *) HW_NV_FPROT2_ADDR(x)) #define HW_NV_FPROT2_RD(x) (HW_NV_FPROT2(x).U) /*@}*/ /* * Constants & macros for individual NV_FPROT2 bitfields */ /*! * @name Register NV_FPROT2, field PROT[7:0] (RO) */ /*@{*/ #define BP_NV_FPROT2_PROT (0U) /*!< Bit position for NV_FPROT2_PROT. */ #define BM_NV_FPROT2_PROT (0xFFU) /*!< Bit mask for NV_FPROT2_PROT. */ #define BS_NV_FPROT2_PROT (8U) /*!< Bit field size in bits for NV_FPROT2_PROT. */ /*! @brief Read current value of the NV_FPROT2_PROT field. */ #define BR_NV_FPROT2_PROT(x) (HW_NV_FPROT2(x).U) /*@}*/ /******************************************************************************* * HW_NV_FPROT1 - Non-volatile P-Flash Protection 0 - Low Register ******************************************************************************/ /*! * @brief HW_NV_FPROT1 - Non-volatile P-Flash Protection 0 - Low Register (RO) * * Reset value: 0xFFU */ typedef union _hw_nv_fprot1 { uint8_t U; struct _hw_nv_fprot1_bitfields { uint8_t PROT : 8; /*!< [7:0] P-Flash Region Protect */ } B; } hw_nv_fprot1_t; /*! * @name Constants and macros for entire NV_FPROT1 register */ /*@{*/ #define HW_NV_FPROT1_ADDR(x) ((x) + 0xAU) #define HW_NV_FPROT1(x) (*(__I hw_nv_fprot1_t *) HW_NV_FPROT1_ADDR(x)) #define HW_NV_FPROT1_RD(x) (HW_NV_FPROT1(x).U) /*@}*/ /* * Constants & macros for individual NV_FPROT1 bitfields */ /*! * @name Register NV_FPROT1, field PROT[7:0] (RO) */ /*@{*/ #define BP_NV_FPROT1_PROT (0U) /*!< Bit position for NV_FPROT1_PROT. */ #define BM_NV_FPROT1_PROT (0xFFU) /*!< Bit mask for NV_FPROT1_PROT. */ #define BS_NV_FPROT1_PROT (8U) /*!< Bit field size in bits for NV_FPROT1_PROT. */ /*! @brief Read current value of the NV_FPROT1_PROT field. */ #define BR_NV_FPROT1_PROT(x) (HW_NV_FPROT1(x).U) /*@}*/ /******************************************************************************* * HW_NV_FPROT0 - Non-volatile P-Flash Protection 0 - High Register ******************************************************************************/ /*! * @brief HW_NV_FPROT0 - Non-volatile P-Flash Protection 0 - High Register (RO) * * Reset value: 0xFFU */ typedef union _hw_nv_fprot0 { uint8_t U; struct _hw_nv_fprot0_bitfields { uint8_t PROT : 8; /*!< [7:0] P-Flash Region Protect */ } B; } hw_nv_fprot0_t; /*! * @name Constants and macros for entire NV_FPROT0 register */ /*@{*/ #define HW_NV_FPROT0_ADDR(x) ((x) + 0xBU) #define HW_NV_FPROT0(x) (*(__I hw_nv_fprot0_t *) HW_NV_FPROT0_ADDR(x)) #define HW_NV_FPROT0_RD(x) (HW_NV_FPROT0(x).U) /*@}*/ /* * Constants & macros for individual NV_FPROT0 bitfields */ /*! * @name Register NV_FPROT0, field PROT[7:0] (RO) */ /*@{*/ #define BP_NV_FPROT0_PROT (0U) /*!< Bit position for NV_FPROT0_PROT. */ #define BM_NV_FPROT0_PROT (0xFFU) /*!< Bit mask for NV_FPROT0_PROT. */ #define BS_NV_FPROT0_PROT (8U) /*!< Bit field size in bits for NV_FPROT0_PROT. */ /*! @brief Read current value of the NV_FPROT0_PROT field. */ #define BR_NV_FPROT0_PROT(x) (HW_NV_FPROT0(x).U) /*@}*/ /******************************************************************************* * HW_NV_FSEC - Non-volatile Flash Security Register ******************************************************************************/ /*! * @brief HW_NV_FSEC - Non-volatile Flash Security Register (RO) * * Reset value: 0xFFU * * Allows the user to customize the operation of the MCU at boot time */ typedef union _hw_nv_fsec { uint8_t U; struct _hw_nv_fsec_bitfields { uint8_t SEC : 2; /*!< [1:0] Flash Security */ uint8_t FSLACC : 2; /*!< [3:2] Freescale Failure Analysis Access Code * */ uint8_t MEEN : 2; /*!< [5:4] */ uint8_t KEYEN : 2; /*!< [7:6] Backdoor Key Security Enable */ } B; } hw_nv_fsec_t; /*! * @name Constants and macros for entire NV_FSEC register */ /*@{*/ #define HW_NV_FSEC_ADDR(x) ((x) + 0xCU) #define HW_NV_FSEC(x) (*(__I hw_nv_fsec_t *) HW_NV_FSEC_ADDR(x)) #define HW_NV_FSEC_RD(x) (HW_NV_FSEC(x).U) /*@}*/ /* * Constants & macros for individual NV_FSEC bitfields */ /*! * @name Register NV_FSEC, field SEC[1:0] (RO) * * Values: * - 10 - MCU security status is unsecure * - 11 - MCU security status is secure */ /*@{*/ #define BP_NV_FSEC_SEC (0U) /*!< Bit position for NV_FSEC_SEC. */ #define BM_NV_FSEC_SEC (0x03U) /*!< Bit mask for NV_FSEC_SEC. */ #define BS_NV_FSEC_SEC (2U) /*!< Bit field size in bits for NV_FSEC_SEC. */ /*! @brief Read current value of the NV_FSEC_SEC field. */ #define BR_NV_FSEC_SEC(x) (HW_NV_FSEC(x).B.SEC) /*@}*/ /*! * @name Register NV_FSEC, field FSLACC[3:2] (RO) * * Values: * - 10 - Freescale factory access denied * - 11 - Freescale factory access granted */ /*@{*/ #define BP_NV_FSEC_FSLACC (2U) /*!< Bit position for NV_FSEC_FSLACC. */ #define BM_NV_FSEC_FSLACC (0x0CU) /*!< Bit mask for NV_FSEC_FSLACC. */ #define BS_NV_FSEC_FSLACC (2U) /*!< Bit field size in bits for NV_FSEC_FSLACC. */ /*! @brief Read current value of the NV_FSEC_FSLACC field. */ #define BR_NV_FSEC_FSLACC(x) (HW_NV_FSEC(x).B.FSLACC) /*@}*/ /*! * @name Register NV_FSEC, field MEEN[5:4] (RO) * * Values: * - 10 - Mass erase is disabled * - 11 - Mass erase is enabled */ /*@{*/ #define BP_NV_FSEC_MEEN (4U) /*!< Bit position for NV_FSEC_MEEN. */ #define BM_NV_FSEC_MEEN (0x30U) /*!< Bit mask for NV_FSEC_MEEN. */ #define BS_NV_FSEC_MEEN (2U) /*!< Bit field size in bits for NV_FSEC_MEEN. */ /*! @brief Read current value of the NV_FSEC_MEEN field. */ #define BR_NV_FSEC_MEEN(x) (HW_NV_FSEC(x).B.MEEN) /*@}*/ /*! * @name Register NV_FSEC, field KEYEN[7:6] (RO) * * Values: * - 10 - Backdoor key access enabled * - 11 - Backdoor key access disabled */ /*@{*/ #define BP_NV_FSEC_KEYEN (6U) /*!< Bit position for NV_FSEC_KEYEN. */ #define BM_NV_FSEC_KEYEN (0xC0U) /*!< Bit mask for NV_FSEC_KEYEN. */ #define BS_NV_FSEC_KEYEN (2U) /*!< Bit field size in bits for NV_FSEC_KEYEN. */ /*! @brief Read current value of the NV_FSEC_KEYEN field. */ #define BR_NV_FSEC_KEYEN(x) (HW_NV_FSEC(x).B.KEYEN) /*@}*/ /******************************************************************************* * HW_NV_FOPT - Non-volatile Flash Option Register ******************************************************************************/ /*! * @brief HW_NV_FOPT - Non-volatile Flash Option Register (RO) * * Reset value: 0xFFU */ typedef union _hw_nv_fopt { uint8_t U; struct _hw_nv_fopt_bitfields { uint8_t LPBOOT : 1; /*!< [0] */ uint8_t EZPORT_DIS : 1; /*!< [1] */ uint8_t RESERVED0 : 6; /*!< [7:2] */ } B; } hw_nv_fopt_t; /*! * @name Constants and macros for entire NV_FOPT register */ /*@{*/ #define HW_NV_FOPT_ADDR(x) ((x) + 0xDU) #define HW_NV_FOPT(x) (*(__I hw_nv_fopt_t *) HW_NV_FOPT_ADDR(x)) #define HW_NV_FOPT_RD(x) (HW_NV_FOPT(x).U) /*@}*/ /* * Constants & macros for individual NV_FOPT bitfields */ /*! * @name Register NV_FOPT, field LPBOOT[0] (RO) * * Values: * - 00 - Low-power boot * - 01 - Normal boot */ /*@{*/ #define BP_NV_FOPT_LPBOOT (0U) /*!< Bit position for NV_FOPT_LPBOOT. */ #define BM_NV_FOPT_LPBOOT (0x01U) /*!< Bit mask for NV_FOPT_LPBOOT. */ #define BS_NV_FOPT_LPBOOT (1U) /*!< Bit field size in bits for NV_FOPT_LPBOOT. */ /*! @brief Read current value of the NV_FOPT_LPBOOT field. */ #define BR_NV_FOPT_LPBOOT(x) (BITBAND_ACCESS8(HW_NV_FOPT_ADDR(x), BP_NV_FOPT_LPBOOT)) /*@}*/ /*! * @name Register NV_FOPT, field EZPORT_DIS[1] (RO) */ /*@{*/ #define BP_NV_FOPT_EZPORT_DIS (1U) /*!< Bit position for NV_FOPT_EZPORT_DIS. */ #define BM_NV_FOPT_EZPORT_DIS (0x02U) /*!< Bit mask for NV_FOPT_EZPORT_DIS. */ #define BS_NV_FOPT_EZPORT_DIS (1U) /*!< Bit field size in bits for NV_FOPT_EZPORT_DIS. */ /*! @brief Read current value of the NV_FOPT_EZPORT_DIS field. */ #define BR_NV_FOPT_EZPORT_DIS(x) (BITBAND_ACCESS8(HW_NV_FOPT_ADDR(x), BP_NV_FOPT_EZPORT_DIS)) /*@}*/ /******************************************************************************* * HW_NV_FEPROT - Non-volatile EERAM Protection Register ******************************************************************************/ /*! * @brief HW_NV_FEPROT - Non-volatile EERAM Protection Register (RO) * * Reset value: 0xFFU */ typedef union _hw_nv_feprot { uint8_t U; struct _hw_nv_feprot_bitfields { uint8_t EPROT : 8; /*!< [7:0] */ } B; } hw_nv_feprot_t; /*! * @name Constants and macros for entire NV_FEPROT register */ /*@{*/ #define HW_NV_FEPROT_ADDR(x) ((x) + 0xEU) #define HW_NV_FEPROT(x) (*(__I hw_nv_feprot_t *) HW_NV_FEPROT_ADDR(x)) #define HW_NV_FEPROT_RD(x) (HW_NV_FEPROT(x).U) /*@}*/ /* * Constants & macros for individual NV_FEPROT bitfields */ /*! * @name Register NV_FEPROT, field EPROT[7:0] (RO) */ /*@{*/ #define BP_NV_FEPROT_EPROT (0U) /*!< Bit position for NV_FEPROT_EPROT. */ #define BM_NV_FEPROT_EPROT (0xFFU) /*!< Bit mask for NV_FEPROT_EPROT. */ #define BS_NV_FEPROT_EPROT (8U) /*!< Bit field size in bits for NV_FEPROT_EPROT. */ /*! @brief Read current value of the NV_FEPROT_EPROT field. */ #define BR_NV_FEPROT_EPROT(x) (HW_NV_FEPROT(x).U) /*@}*/ /******************************************************************************* * HW_NV_FDPROT - Non-volatile D-Flash Protection Register ******************************************************************************/ /*! * @brief HW_NV_FDPROT - Non-volatile D-Flash Protection Register (RO) * * Reset value: 0xFFU */ typedef union _hw_nv_fdprot { uint8_t U; struct _hw_nv_fdprot_bitfields { uint8_t DPROT : 8; /*!< [7:0] D-Flash Region Protect */ } B; } hw_nv_fdprot_t; /*! * @name Constants and macros for entire NV_FDPROT register */ /*@{*/ #define HW_NV_FDPROT_ADDR(x) ((x) + 0xFU) #define HW_NV_FDPROT(x) (*(__I hw_nv_fdprot_t *) HW_NV_FDPROT_ADDR(x)) #define HW_NV_FDPROT_RD(x) (HW_NV_FDPROT(x).U) /*@}*/ /* * Constants & macros for individual NV_FDPROT bitfields */ /*! * @name Register NV_FDPROT, field DPROT[7:0] (RO) */ /*@{*/ #define BP_NV_FDPROT_DPROT (0U) /*!< Bit position for NV_FDPROT_DPROT. */ #define BM_NV_FDPROT_DPROT (0xFFU) /*!< Bit mask for NV_FDPROT_DPROT. */ #define BS_NV_FDPROT_DPROT (8U) /*!< Bit field size in bits for NV_FDPROT_DPROT. */ /*! @brief Read current value of the NV_FDPROT_DPROT field. */ #define BR_NV_FDPROT_DPROT(x) (HW_NV_FDPROT(x).U) /*@}*/ /******************************************************************************* * hw_nv_t - module struct ******************************************************************************/ /*! * @brief All NV module registers. */ #pragma pack(1) typedef struct _hw_nv { __I hw_nv_backkey3_t BACKKEY3; /*!< [0x0] Backdoor Comparison Key 3. */ __I hw_nv_backkey2_t BACKKEY2; /*!< [0x1] Backdoor Comparison Key 2. */ __I hw_nv_backkey1_t BACKKEY1; /*!< [0x2] Backdoor Comparison Key 1. */ __I hw_nv_backkey0_t BACKKEY0; /*!< [0x3] Backdoor Comparison Key 0. */ __I hw_nv_backkey7_t BACKKEY7; /*!< [0x4] Backdoor Comparison Key 7. */ __I hw_nv_backkey6_t BACKKEY6; /*!< [0x5] Backdoor Comparison Key 6. */ __I hw_nv_backkey5_t BACKKEY5; /*!< [0x6] Backdoor Comparison Key 5. */ __I hw_nv_backkey4_t BACKKEY4; /*!< [0x7] Backdoor Comparison Key 4. */ __I hw_nv_fprot3_t FPROT3; /*!< [0x8] Non-volatile P-Flash Protection 1 - Low Register */ __I hw_nv_fprot2_t FPROT2; /*!< [0x9] Non-volatile P-Flash Protection 1 - High Register */ __I hw_nv_fprot1_t FPROT1; /*!< [0xA] Non-volatile P-Flash Protection 0 - Low Register */ __I hw_nv_fprot0_t FPROT0; /*!< [0xB] Non-volatile P-Flash Protection 0 - High Register */ __I hw_nv_fsec_t FSEC; /*!< [0xC] Non-volatile Flash Security Register */ __I hw_nv_fopt_t FOPT; /*!< [0xD] Non-volatile Flash Option Register */ __I hw_nv_feprot_t FEPROT; /*!< [0xE] Non-volatile EERAM Protection Register */ __I hw_nv_fdprot_t FDPROT; /*!< [0xF] Non-volatile D-Flash Protection Register */ } hw_nv_t; #pragma pack() /*! @brief Macro to access all NV registers. */ /*! @param x NV module instance base address. */ /*! @return Reference (not a pointer) to the registers struct. To get a pointer to the struct, * use the '&' operator, like &HW_NV(FTFE_FlashConfig_BASE). */ #define HW_NV(x) (*(hw_nv_t *)(x)) #endif /* __HW_NV_REGISTERS_H__ */ /* EOF */ ================================================ FILE: Zelig/mbed/TARGET_K64F/TARGET_Freescale/TARGET_KPSDK_MCUS/TARGET_MCU_K64F/device/device/MK64F12/MK64F12_osc.h ================================================ /* ** ################################################################### ** Compilers: Keil ARM C/C++ Compiler ** Freescale C/C++ for Embedded ARM ** GNU C Compiler ** IAR ANSI C/C++ Compiler for ARM ** ** Reference manual: K64P144M120SF5RM, Rev.2, January 2014 ** Version: rev. 2.5, 2014-02-10 ** Build: b140604 ** ** Abstract: ** Extension to the CMSIS register access layer header. ** ** Copyright (c) 2014 Freescale Semiconductor, Inc. ** All rights reserved. ** ** Redistribution and use in source and binary forms, with or without modification, ** are permitted provided that the following conditions are met: ** ** o Redistributions of source code must retain the above copyright notice, this list ** of conditions and the following disclaimer. ** ** o Redistributions in binary form must reproduce the above copyright notice, this ** list of conditions and the following disclaimer in the documentation and/or ** other materials provided with the distribution. ** ** o Neither the name of Freescale Semiconductor, Inc. nor the names of its ** contributors may be used to endorse or promote products derived from this ** software without specific prior written permission. ** ** THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ** ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED ** WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE ** DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT 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. ** ** http: www.freescale.com ** mail: support@freescale.com ** ** Revisions: ** - rev. 1.0 (2013-08-12) ** Initial version. ** - rev. 2.0 (2013-10-29) ** Register accessor macros added to the memory map. ** Symbols for Processor Expert memory map compatibility added to the memory map. ** Startup file for gcc has been updated according to CMSIS 3.2. ** System initialization updated. ** MCG - registers updated. ** PORTA, PORTB, PORTC, PORTE - registers for digital filter removed. ** - rev. 2.1 (2013-10-30) ** Definition of BITBAND macros updated to support peripherals with 32-bit acces disabled. ** - rev. 2.2 (2013-12-09) ** DMA - EARS register removed. ** AIPS0, AIPS1 - MPRA register updated. ** - rev. 2.3 (2014-01-24) ** Update according to reference manual rev. 2 ** ENET, MCG, MCM, SIM, USB - registers updated ** - rev. 2.4 (2014-02-10) ** The declaration of clock configurations has been moved to separate header file system_MK64F12.h ** Update of SystemInit() and SystemCoreClockUpdate() functions. ** - rev. 2.5 (2014-02-10) ** The declaration of clock configurations has been moved to separate header file system_MK64F12.h ** Update of SystemInit() and SystemCoreClockUpdate() functions. ** Module access macro module_BASES replaced by module_BASE_PTRS. ** ** ################################################################### */ /* * WARNING! DO NOT EDIT THIS FILE DIRECTLY! * * This file was generated automatically and any changes may be lost. */ #ifndef __HW_OSC_REGISTERS_H__ #define __HW_OSC_REGISTERS_H__ #include "MK64F12.h" #include "fsl_bitaccess.h" /* * MK64F12 OSC * * Oscillator * * Registers defined in this header file: * - HW_OSC_CR - OSC Control Register * * - hw_osc_t - Struct containing all module registers. */ #define HW_OSC_INSTANCE_COUNT (1U) /*!< Number of instances of the OSC module. */ /******************************************************************************* * HW_OSC_CR - OSC Control Register ******************************************************************************/ /*! * @brief HW_OSC_CR - OSC Control Register (RW) * * Reset value: 0x00U * * After OSC is enabled and starts generating the clocks, the configurations * such as low power and frequency range, must not be changed. */ typedef union _hw_osc_cr { uint8_t U; struct _hw_osc_cr_bitfields { uint8_t SC16P : 1; /*!< [0] Oscillator 16 pF Capacitor Load Configure * */ uint8_t SC8P : 1; /*!< [1] Oscillator 8 pF Capacitor Load Configure */ uint8_t SC4P : 1; /*!< [2] Oscillator 4 pF Capacitor Load Configure */ uint8_t SC2P : 1; /*!< [3] Oscillator 2 pF Capacitor Load Configure */ uint8_t RESERVED0 : 1; /*!< [4] */ uint8_t EREFSTEN : 1; /*!< [5] External Reference Stop Enable */ uint8_t RESERVED1 : 1; /*!< [6] */ uint8_t ERCLKEN : 1; /*!< [7] External Reference Enable */ } B; } hw_osc_cr_t; /*! * @name Constants and macros for entire OSC_CR register */ /*@{*/ #define HW_OSC_CR_ADDR(x) ((x) + 0x0U) #define HW_OSC_CR(x) (*(__IO hw_osc_cr_t *) HW_OSC_CR_ADDR(x)) #define HW_OSC_CR_RD(x) (HW_OSC_CR(x).U) #define HW_OSC_CR_WR(x, v) (HW_OSC_CR(x).U = (v)) #define HW_OSC_CR_SET(x, v) (HW_OSC_CR_WR(x, HW_OSC_CR_RD(x) | (v))) #define HW_OSC_CR_CLR(x, v) (HW_OSC_CR_WR(x, HW_OSC_CR_RD(x) & ~(v))) #define HW_OSC_CR_TOG(x, v) (HW_OSC_CR_WR(x, HW_OSC_CR_RD(x) ^ (v))) /*@}*/ /* * Constants & macros for individual OSC_CR bitfields */ /*! * @name Register OSC_CR, field SC16P[0] (RW) * * Configures the oscillator load. * * Values: * - 0 - Disable the selection. * - 1 - Add 16 pF capacitor to the oscillator load. */ /*@{*/ #define BP_OSC_CR_SC16P (0U) /*!< Bit position for OSC_CR_SC16P. */ #define BM_OSC_CR_SC16P (0x01U) /*!< Bit mask for OSC_CR_SC16P. */ #define BS_OSC_CR_SC16P (1U) /*!< Bit field size in bits for OSC_CR_SC16P. */ /*! @brief Read current value of the OSC_CR_SC16P field. */ #define BR_OSC_CR_SC16P(x) (BITBAND_ACCESS8(HW_OSC_CR_ADDR(x), BP_OSC_CR_SC16P)) /*! @brief Format value for bitfield OSC_CR_SC16P. */ #define BF_OSC_CR_SC16P(v) ((uint8_t)((uint8_t)(v) << BP_OSC_CR_SC16P) & BM_OSC_CR_SC16P) /*! @brief Set the SC16P field to a new value. */ #define BW_OSC_CR_SC16P(x, v) (BITBAND_ACCESS8(HW_OSC_CR_ADDR(x), BP_OSC_CR_SC16P) = (v)) /*@}*/ /*! * @name Register OSC_CR, field SC8P[1] (RW) * * Configures the oscillator load. * * Values: * - 0 - Disable the selection. * - 1 - Add 8 pF capacitor to the oscillator load. */ /*@{*/ #define BP_OSC_CR_SC8P (1U) /*!< Bit position for OSC_CR_SC8P. */ #define BM_OSC_CR_SC8P (0x02U) /*!< Bit mask for OSC_CR_SC8P. */ #define BS_OSC_CR_SC8P (1U) /*!< Bit field size in bits for OSC_CR_SC8P. */ /*! @brief Read current value of the OSC_CR_SC8P field. */ #define BR_OSC_CR_SC8P(x) (BITBAND_ACCESS8(HW_OSC_CR_ADDR(x), BP_OSC_CR_SC8P)) /*! @brief Format value for bitfield OSC_CR_SC8P. */ #define BF_OSC_CR_SC8P(v) ((uint8_t)((uint8_t)(v) << BP_OSC_CR_SC8P) & BM_OSC_CR_SC8P) /*! @brief Set the SC8P field to a new value. */ #define BW_OSC_CR_SC8P(x, v) (BITBAND_ACCESS8(HW_OSC_CR_ADDR(x), BP_OSC_CR_SC8P) = (v)) /*@}*/ /*! * @name Register OSC_CR, field SC4P[2] (RW) * * Configures the oscillator load. * * Values: * - 0 - Disable the selection. * - 1 - Add 4 pF capacitor to the oscillator load. */ /*@{*/ #define BP_OSC_CR_SC4P (2U) /*!< Bit position for OSC_CR_SC4P. */ #define BM_OSC_CR_SC4P (0x04U) /*!< Bit mask for OSC_CR_SC4P. */ #define BS_OSC_CR_SC4P (1U) /*!< Bit field size in bits for OSC_CR_SC4P. */ /*! @brief Read current value of the OSC_CR_SC4P field. */ #define BR_OSC_CR_SC4P(x) (BITBAND_ACCESS8(HW_OSC_CR_ADDR(x), BP_OSC_CR_SC4P)) /*! @brief Format value for bitfield OSC_CR_SC4P. */ #define BF_OSC_CR_SC4P(v) ((uint8_t)((uint8_t)(v) << BP_OSC_CR_SC4P) & BM_OSC_CR_SC4P) /*! @brief Set the SC4P field to a new value. */ #define BW_OSC_CR_SC4P(x, v) (BITBAND_ACCESS8(HW_OSC_CR_ADDR(x), BP_OSC_CR_SC4P) = (v)) /*@}*/ /*! * @name Register OSC_CR, field SC2P[3] (RW) * * Configures the oscillator load. * * Values: * - 0 - Disable the selection. * - 1 - Add 2 pF capacitor to the oscillator load. */ /*@{*/ #define BP_OSC_CR_SC2P (3U) /*!< Bit position for OSC_CR_SC2P. */ #define BM_OSC_CR_SC2P (0x08U) /*!< Bit mask for OSC_CR_SC2P. */ #define BS_OSC_CR_SC2P (1U) /*!< Bit field size in bits for OSC_CR_SC2P. */ /*! @brief Read current value of the OSC_CR_SC2P field. */ #define BR_OSC_CR_SC2P(x) (BITBAND_ACCESS8(HW_OSC_CR_ADDR(x), BP_OSC_CR_SC2P)) /*! @brief Format value for bitfield OSC_CR_SC2P. */ #define BF_OSC_CR_SC2P(v) ((uint8_t)((uint8_t)(v) << BP_OSC_CR_SC2P) & BM_OSC_CR_SC2P) /*! @brief Set the SC2P field to a new value. */ #define BW_OSC_CR_SC2P(x, v) (BITBAND_ACCESS8(HW_OSC_CR_ADDR(x), BP_OSC_CR_SC2P) = (v)) /*@}*/ /*! * @name Register OSC_CR, field EREFSTEN[5] (RW) * * Controls whether or not the external reference clock (OSCERCLK) remains * enabled when MCU enters Stop mode. * * Values: * - 0 - External reference clock is disabled in Stop mode. * - 1 - External reference clock stays enabled in Stop mode if ERCLKEN is set * before entering Stop mode. */ /*@{*/ #define BP_OSC_CR_EREFSTEN (5U) /*!< Bit position for OSC_CR_EREFSTEN. */ #define BM_OSC_CR_EREFSTEN (0x20U) /*!< Bit mask for OSC_CR_EREFSTEN. */ #define BS_OSC_CR_EREFSTEN (1U) /*!< Bit field size in bits for OSC_CR_EREFSTEN. */ /*! @brief Read current value of the OSC_CR_EREFSTEN field. */ #define BR_OSC_CR_EREFSTEN(x) (BITBAND_ACCESS8(HW_OSC_CR_ADDR(x), BP_OSC_CR_EREFSTEN)) /*! @brief Format value for bitfield OSC_CR_EREFSTEN. */ #define BF_OSC_CR_EREFSTEN(v) ((uint8_t)((uint8_t)(v) << BP_OSC_CR_EREFSTEN) & BM_OSC_CR_EREFSTEN) /*! @brief Set the EREFSTEN field to a new value. */ #define BW_OSC_CR_EREFSTEN(x, v) (BITBAND_ACCESS8(HW_OSC_CR_ADDR(x), BP_OSC_CR_EREFSTEN) = (v)) /*@}*/ /*! * @name Register OSC_CR, field ERCLKEN[7] (RW) * * Enables external reference clock (OSCERCLK). * * Values: * - 0 - External reference clock is inactive. * - 1 - External reference clock is enabled. */ /*@{*/ #define BP_OSC_CR_ERCLKEN (7U) /*!< Bit position for OSC_CR_ERCLKEN. */ #define BM_OSC_CR_ERCLKEN (0x80U) /*!< Bit mask for OSC_CR_ERCLKEN. */ #define BS_OSC_CR_ERCLKEN (1U) /*!< Bit field size in bits for OSC_CR_ERCLKEN. */ /*! @brief Read current value of the OSC_CR_ERCLKEN field. */ #define BR_OSC_CR_ERCLKEN(x) (BITBAND_ACCESS8(HW_OSC_CR_ADDR(x), BP_OSC_CR_ERCLKEN)) /*! @brief Format value for bitfield OSC_CR_ERCLKEN. */ #define BF_OSC_CR_ERCLKEN(v) ((uint8_t)((uint8_t)(v) << BP_OSC_CR_ERCLKEN) & BM_OSC_CR_ERCLKEN) /*! @brief Set the ERCLKEN field to a new value. */ #define BW_OSC_CR_ERCLKEN(x, v) (BITBAND_ACCESS8(HW_OSC_CR_ADDR(x), BP_OSC_CR_ERCLKEN) = (v)) /*@}*/ /******************************************************************************* * hw_osc_t - module struct ******************************************************************************/ /*! * @brief All OSC module registers. */ #pragma pack(1) typedef struct _hw_osc { __IO hw_osc_cr_t CR; /*!< [0x0] OSC Control Register */ } hw_osc_t; #pragma pack() /*! @brief Macro to access all OSC registers. */ /*! @param x OSC module instance base address. */ /*! @return Reference (not a pointer) to the registers struct. To get a pointer to the struct, * use the '&' operator, like &HW_OSC(OSC_BASE). */ #define HW_OSC(x) (*(hw_osc_t *)(x)) #endif /* __HW_OSC_REGISTERS_H__ */ /* EOF */ ================================================ FILE: Zelig/mbed/TARGET_K64F/TARGET_Freescale/TARGET_KPSDK_MCUS/TARGET_MCU_K64F/device/device/MK64F12/MK64F12_pdb.h ================================================ /* ** ################################################################### ** Compilers: Keil ARM C/C++ Compiler ** Freescale C/C++ for Embedded ARM ** GNU C Compiler ** IAR ANSI C/C++ Compiler for ARM ** ** Reference manual: K64P144M120SF5RM, Rev.2, January 2014 ** Version: rev. 2.5, 2014-02-10 ** Build: b140604 ** ** Abstract: ** Extension to the CMSIS register access layer header. ** ** Copyright (c) 2014 Freescale Semiconductor, Inc. ** All rights reserved. ** ** Redistribution and use in source and binary forms, with or without modification, ** are permitted provided that the following conditions are met: ** ** o Redistributions of source code must retain the above copyright notice, this list ** of conditions and the following disclaimer. ** ** o Redistributions in binary form must reproduce the above copyright notice, this ** list of conditions and the following disclaimer in the documentation and/or ** other materials provided with the distribution. ** ** o Neither the name of Freescale Semiconductor, Inc. nor the names of its ** contributors may be used to endorse or promote products derived from this ** software without specific prior written permission. ** ** THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ** ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED ** WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE ** DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT 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. ** ** http: www.freescale.com ** mail: support@freescale.com ** ** Revisions: ** - rev. 1.0 (2013-08-12) ** Initial version. ** - rev. 2.0 (2013-10-29) ** Register accessor macros added to the memory map. ** Symbols for Processor Expert memory map compatibility added to the memory map. ** Startup file for gcc has been updated according to CMSIS 3.2. ** System initialization updated. ** MCG - registers updated. ** PORTA, PORTB, PORTC, PORTE - registers for digital filter removed. ** - rev. 2.1 (2013-10-30) ** Definition of BITBAND macros updated to support peripherals with 32-bit acces disabled. ** - rev. 2.2 (2013-12-09) ** DMA - EARS register removed. ** AIPS0, AIPS1 - MPRA register updated. ** - rev. 2.3 (2014-01-24) ** Update according to reference manual rev. 2 ** ENET, MCG, MCM, SIM, USB - registers updated ** - rev. 2.4 (2014-02-10) ** The declaration of clock configurations has been moved to separate header file system_MK64F12.h ** Update of SystemInit() and SystemCoreClockUpdate() functions. ** - rev. 2.5 (2014-02-10) ** The declaration of clock configurations has been moved to separate header file system_MK64F12.h ** Update of SystemInit() and SystemCoreClockUpdate() functions. ** Module access macro module_BASES replaced by module_BASE_PTRS. ** ** ################################################################### */ /* * WARNING! DO NOT EDIT THIS FILE DIRECTLY! * * This file was generated automatically and any changes may be lost. */ #ifndef __HW_PDB_REGISTERS_H__ #define __HW_PDB_REGISTERS_H__ #include "MK64F12.h" #include "fsl_bitaccess.h" /* * MK64F12 PDB * * Programmable Delay Block * * Registers defined in this header file: * - HW_PDB_SC - Status and Control register * - HW_PDB_MOD - Modulus register * - HW_PDB_CNT - Counter register * - HW_PDB_IDLY - Interrupt Delay register * - HW_PDB_CHnC1 - Channel n Control register 1 * - HW_PDB_CHnS - Channel n Status register * - HW_PDB_CHnDLY0 - Channel n Delay 0 register * - HW_PDB_CHnDLY1 - Channel n Delay 1 register * - HW_PDB_DACINTCn - DAC Interval Trigger n Control register * - HW_PDB_DACINTn - DAC Interval n register * - HW_PDB_POEN - Pulse-Out n Enable register * - HW_PDB_POnDLY - Pulse-Out n Delay register * * - hw_pdb_t - Struct containing all module registers. */ #define HW_PDB_INSTANCE_COUNT (1U) /*!< Number of instances of the PDB module. */ /******************************************************************************* * HW_PDB_SC - Status and Control register ******************************************************************************/ /*! * @brief HW_PDB_SC - Status and Control register (RW) * * Reset value: 0x00000000U */ typedef union _hw_pdb_sc { uint32_t U; struct _hw_pdb_sc_bitfields { uint32_t LDOK : 1; /*!< [0] Load OK */ uint32_t CONT : 1; /*!< [1] Continuous Mode Enable */ uint32_t MULT : 2; /*!< [3:2] Multiplication Factor Select for * Prescaler */ uint32_t RESERVED0 : 1; /*!< [4] */ uint32_t PDBIE : 1; /*!< [5] PDB Interrupt Enable */ uint32_t PDBIF : 1; /*!< [6] PDB Interrupt Flag */ uint32_t PDBEN : 1; /*!< [7] PDB Enable */ uint32_t TRGSEL : 4; /*!< [11:8] Trigger Input Source Select */ uint32_t PRESCALER : 3; /*!< [14:12] Prescaler Divider Select */ uint32_t DMAEN : 1; /*!< [15] DMA Enable */ uint32_t SWTRIG : 1; /*!< [16] Software Trigger */ uint32_t PDBEIE : 1; /*!< [17] PDB Sequence Error Interrupt Enable */ uint32_t LDMOD : 2; /*!< [19:18] Load Mode Select */ uint32_t RESERVED1 : 12; /*!< [31:20] */ } B; } hw_pdb_sc_t; /*! * @name Constants and macros for entire PDB_SC register */ /*@{*/ #define HW_PDB_SC_ADDR(x) ((x) + 0x0U) #define HW_PDB_SC(x) (*(__IO hw_pdb_sc_t *) HW_PDB_SC_ADDR(x)) #define HW_PDB_SC_RD(x) (HW_PDB_SC(x).U) #define HW_PDB_SC_WR(x, v) (HW_PDB_SC(x).U = (v)) #define HW_PDB_SC_SET(x, v) (HW_PDB_SC_WR(x, HW_PDB_SC_RD(x) | (v))) #define HW_PDB_SC_CLR(x, v) (HW_PDB_SC_WR(x, HW_PDB_SC_RD(x) & ~(v))) #define HW_PDB_SC_TOG(x, v) (HW_PDB_SC_WR(x, HW_PDB_SC_RD(x) ^ (v))) /*@}*/ /* * Constants & macros for individual PDB_SC bitfields */ /*! * @name Register PDB_SC, field LDOK[0] (RW) * * Writing 1 to this bit updates the internal registers of MOD, IDLY, CHnDLYm, * DACINTx,and POyDLY with the values written to their buffers. The MOD, IDLY, * CHnDLYm, DACINTx, and POyDLY will take effect according to the LDMOD. After 1 is * written to the LDOK field, the values in the buffers of above registers are * not effective and the buffers cannot be written until the values in buffers are * loaded into their internal registers. LDOK can be written only when PDBEN is * set or it can be written at the same time with PDBEN being written to 1. It is * automatically cleared when the values in buffers are loaded into the internal * registers or the PDBEN is cleared. Writing 0 to it has no effect. */ /*@{*/ #define BP_PDB_SC_LDOK (0U) /*!< Bit position for PDB_SC_LDOK. */ #define BM_PDB_SC_LDOK (0x00000001U) /*!< Bit mask for PDB_SC_LDOK. */ #define BS_PDB_SC_LDOK (1U) /*!< Bit field size in bits for PDB_SC_LDOK. */ /*! @brief Read current value of the PDB_SC_LDOK field. */ #define BR_PDB_SC_LDOK(x) (BITBAND_ACCESS32(HW_PDB_SC_ADDR(x), BP_PDB_SC_LDOK)) /*! @brief Format value for bitfield PDB_SC_LDOK. */ #define BF_PDB_SC_LDOK(v) ((uint32_t)((uint32_t)(v) << BP_PDB_SC_LDOK) & BM_PDB_SC_LDOK) /*! @brief Set the LDOK field to a new value. */ #define BW_PDB_SC_LDOK(x, v) (BITBAND_ACCESS32(HW_PDB_SC_ADDR(x), BP_PDB_SC_LDOK) = (v)) /*@}*/ /*! * @name Register PDB_SC, field CONT[1] (RW) * * Enables the PDB operation in Continuous mode. * * Values: * - 0 - PDB operation in One-Shot mode * - 1 - PDB operation in Continuous mode */ /*@{*/ #define BP_PDB_SC_CONT (1U) /*!< Bit position for PDB_SC_CONT. */ #define BM_PDB_SC_CONT (0x00000002U) /*!< Bit mask for PDB_SC_CONT. */ #define BS_PDB_SC_CONT (1U) /*!< Bit field size in bits for PDB_SC_CONT. */ /*! @brief Read current value of the PDB_SC_CONT field. */ #define BR_PDB_SC_CONT(x) (BITBAND_ACCESS32(HW_PDB_SC_ADDR(x), BP_PDB_SC_CONT)) /*! @brief Format value for bitfield PDB_SC_CONT. */ #define BF_PDB_SC_CONT(v) ((uint32_t)((uint32_t)(v) << BP_PDB_SC_CONT) & BM_PDB_SC_CONT) /*! @brief Set the CONT field to a new value. */ #define BW_PDB_SC_CONT(x, v) (BITBAND_ACCESS32(HW_PDB_SC_ADDR(x), BP_PDB_SC_CONT) = (v)) /*@}*/ /*! * @name Register PDB_SC, field MULT[3:2] (RW) * * Selects the multiplication factor of the prescaler divider for the counter * clock. * * Values: * - 00 - Multiplication factor is 1. * - 01 - Multiplication factor is 10. * - 10 - Multiplication factor is 20. * - 11 - Multiplication factor is 40. */ /*@{*/ #define BP_PDB_SC_MULT (2U) /*!< Bit position for PDB_SC_MULT. */ #define BM_PDB_SC_MULT (0x0000000CU) /*!< Bit mask for PDB_SC_MULT. */ #define BS_PDB_SC_MULT (2U) /*!< Bit field size in bits for PDB_SC_MULT. */ /*! @brief Read current value of the PDB_SC_MULT field. */ #define BR_PDB_SC_MULT(x) (HW_PDB_SC(x).B.MULT) /*! @brief Format value for bitfield PDB_SC_MULT. */ #define BF_PDB_SC_MULT(v) ((uint32_t)((uint32_t)(v) << BP_PDB_SC_MULT) & BM_PDB_SC_MULT) /*! @brief Set the MULT field to a new value. */ #define BW_PDB_SC_MULT(x, v) (HW_PDB_SC_WR(x, (HW_PDB_SC_RD(x) & ~BM_PDB_SC_MULT) | BF_PDB_SC_MULT(v))) /*@}*/ /*! * @name Register PDB_SC, field PDBIE[5] (RW) * * Enables the PDB interrupt. When this field is set and DMAEN is cleared, PDBIF * generates a PDB interrupt. * * Values: * - 0 - PDB interrupt disabled. * - 1 - PDB interrupt enabled. */ /*@{*/ #define BP_PDB_SC_PDBIE (5U) /*!< Bit position for PDB_SC_PDBIE. */ #define BM_PDB_SC_PDBIE (0x00000020U) /*!< Bit mask for PDB_SC_PDBIE. */ #define BS_PDB_SC_PDBIE (1U) /*!< Bit field size in bits for PDB_SC_PDBIE. */ /*! @brief Read current value of the PDB_SC_PDBIE field. */ #define BR_PDB_SC_PDBIE(x) (BITBAND_ACCESS32(HW_PDB_SC_ADDR(x), BP_PDB_SC_PDBIE)) /*! @brief Format value for bitfield PDB_SC_PDBIE. */ #define BF_PDB_SC_PDBIE(v) ((uint32_t)((uint32_t)(v) << BP_PDB_SC_PDBIE) & BM_PDB_SC_PDBIE) /*! @brief Set the PDBIE field to a new value. */ #define BW_PDB_SC_PDBIE(x, v) (BITBAND_ACCESS32(HW_PDB_SC_ADDR(x), BP_PDB_SC_PDBIE) = (v)) /*@}*/ /*! * @name Register PDB_SC, field PDBIF[6] (RW) * * This field is set when the counter value is equal to the IDLY register. * Writing zero clears this field. */ /*@{*/ #define BP_PDB_SC_PDBIF (6U) /*!< Bit position for PDB_SC_PDBIF. */ #define BM_PDB_SC_PDBIF (0x00000040U) /*!< Bit mask for PDB_SC_PDBIF. */ #define BS_PDB_SC_PDBIF (1U) /*!< Bit field size in bits for PDB_SC_PDBIF. */ /*! @brief Read current value of the PDB_SC_PDBIF field. */ #define BR_PDB_SC_PDBIF(x) (BITBAND_ACCESS32(HW_PDB_SC_ADDR(x), BP_PDB_SC_PDBIF)) /*! @brief Format value for bitfield PDB_SC_PDBIF. */ #define BF_PDB_SC_PDBIF(v) ((uint32_t)((uint32_t)(v) << BP_PDB_SC_PDBIF) & BM_PDB_SC_PDBIF) /*! @brief Set the PDBIF field to a new value. */ #define BW_PDB_SC_PDBIF(x, v) (BITBAND_ACCESS32(HW_PDB_SC_ADDR(x), BP_PDB_SC_PDBIF) = (v)) /*@}*/ /*! * @name Register PDB_SC, field PDBEN[7] (RW) * * Values: * - 0 - PDB disabled. Counter is off. * - 1 - PDB enabled. */ /*@{*/ #define BP_PDB_SC_PDBEN (7U) /*!< Bit position for PDB_SC_PDBEN. */ #define BM_PDB_SC_PDBEN (0x00000080U) /*!< Bit mask for PDB_SC_PDBEN. */ #define BS_PDB_SC_PDBEN (1U) /*!< Bit field size in bits for PDB_SC_PDBEN. */ /*! @brief Read current value of the PDB_SC_PDBEN field. */ #define BR_PDB_SC_PDBEN(x) (BITBAND_ACCESS32(HW_PDB_SC_ADDR(x), BP_PDB_SC_PDBEN)) /*! @brief Format value for bitfield PDB_SC_PDBEN. */ #define BF_PDB_SC_PDBEN(v) ((uint32_t)((uint32_t)(v) << BP_PDB_SC_PDBEN) & BM_PDB_SC_PDBEN) /*! @brief Set the PDBEN field to a new value. */ #define BW_PDB_SC_PDBEN(x, v) (BITBAND_ACCESS32(HW_PDB_SC_ADDR(x), BP_PDB_SC_PDBEN) = (v)) /*@}*/ /*! * @name Register PDB_SC, field TRGSEL[11:8] (RW) * * Selects the trigger input source for the PDB. The trigger input source can be * internal or external (EXTRG pin), or the software trigger. Refer to chip * configuration details for the actual PDB input trigger connections. * * Values: * - 0000 - Trigger-In 0 is selected. * - 0001 - Trigger-In 1 is selected. * - 0010 - Trigger-In 2 is selected. * - 0011 - Trigger-In 3 is selected. * - 0100 - Trigger-In 4 is selected. * - 0101 - Trigger-In 5 is selected. * - 0110 - Trigger-In 6 is selected. * - 0111 - Trigger-In 7 is selected. * - 1000 - Trigger-In 8 is selected. * - 1001 - Trigger-In 9 is selected. * - 1010 - Trigger-In 10 is selected. * - 1011 - Trigger-In 11 is selected. * - 1100 - Trigger-In 12 is selected. * - 1101 - Trigger-In 13 is selected. * - 1110 - Trigger-In 14 is selected. * - 1111 - Software trigger is selected. */ /*@{*/ #define BP_PDB_SC_TRGSEL (8U) /*!< Bit position for PDB_SC_TRGSEL. */ #define BM_PDB_SC_TRGSEL (0x00000F00U) /*!< Bit mask for PDB_SC_TRGSEL. */ #define BS_PDB_SC_TRGSEL (4U) /*!< Bit field size in bits for PDB_SC_TRGSEL. */ /*! @brief Read current value of the PDB_SC_TRGSEL field. */ #define BR_PDB_SC_TRGSEL(x) (HW_PDB_SC(x).B.TRGSEL) /*! @brief Format value for bitfield PDB_SC_TRGSEL. */ #define BF_PDB_SC_TRGSEL(v) ((uint32_t)((uint32_t)(v) << BP_PDB_SC_TRGSEL) & BM_PDB_SC_TRGSEL) /*! @brief Set the TRGSEL field to a new value. */ #define BW_PDB_SC_TRGSEL(x, v) (HW_PDB_SC_WR(x, (HW_PDB_SC_RD(x) & ~BM_PDB_SC_TRGSEL) | BF_PDB_SC_TRGSEL(v))) /*@}*/ /*! * @name Register PDB_SC, field PRESCALER[14:12] (RW) * * Values: * - 000 - Counting uses the peripheral clock divided by multiplication factor * selected by MULT. * - 001 - Counting uses the peripheral clock divided by twice of the * multiplication factor selected by MULT. * - 010 - Counting uses the peripheral clock divided by four times of the * multiplication factor selected by MULT. * - 011 - Counting uses the peripheral clock divided by eight times of the * multiplication factor selected by MULT. * - 100 - Counting uses the peripheral clock divided by 16 times of the * multiplication factor selected by MULT. * - 101 - Counting uses the peripheral clock divided by 32 times of the * multiplication factor selected by MULT. * - 110 - Counting uses the peripheral clock divided by 64 times of the * multiplication factor selected by MULT. * - 111 - Counting uses the peripheral clock divided by 128 times of the * multiplication factor selected by MULT. */ /*@{*/ #define BP_PDB_SC_PRESCALER (12U) /*!< Bit position for PDB_SC_PRESCALER. */ #define BM_PDB_SC_PRESCALER (0x00007000U) /*!< Bit mask for PDB_SC_PRESCALER. */ #define BS_PDB_SC_PRESCALER (3U) /*!< Bit field size in bits for PDB_SC_PRESCALER. */ /*! @brief Read current value of the PDB_SC_PRESCALER field. */ #define BR_PDB_SC_PRESCALER(x) (HW_PDB_SC(x).B.PRESCALER) /*! @brief Format value for bitfield PDB_SC_PRESCALER. */ #define BF_PDB_SC_PRESCALER(v) ((uint32_t)((uint32_t)(v) << BP_PDB_SC_PRESCALER) & BM_PDB_SC_PRESCALER) /*! @brief Set the PRESCALER field to a new value. */ #define BW_PDB_SC_PRESCALER(x, v) (HW_PDB_SC_WR(x, (HW_PDB_SC_RD(x) & ~BM_PDB_SC_PRESCALER) | BF_PDB_SC_PRESCALER(v))) /*@}*/ /*! * @name Register PDB_SC, field DMAEN[15] (RW) * * When DMA is enabled, the PDBIF flag generates a DMA request instead of an * interrupt. * * Values: * - 0 - DMA disabled. * - 1 - DMA enabled. */ /*@{*/ #define BP_PDB_SC_DMAEN (15U) /*!< Bit position for PDB_SC_DMAEN. */ #define BM_PDB_SC_DMAEN (0x00008000U) /*!< Bit mask for PDB_SC_DMAEN. */ #define BS_PDB_SC_DMAEN (1U) /*!< Bit field size in bits for PDB_SC_DMAEN. */ /*! @brief Read current value of the PDB_SC_DMAEN field. */ #define BR_PDB_SC_DMAEN(x) (BITBAND_ACCESS32(HW_PDB_SC_ADDR(x), BP_PDB_SC_DMAEN)) /*! @brief Format value for bitfield PDB_SC_DMAEN. */ #define BF_PDB_SC_DMAEN(v) ((uint32_t)((uint32_t)(v) << BP_PDB_SC_DMAEN) & BM_PDB_SC_DMAEN) /*! @brief Set the DMAEN field to a new value. */ #define BW_PDB_SC_DMAEN(x, v) (BITBAND_ACCESS32(HW_PDB_SC_ADDR(x), BP_PDB_SC_DMAEN) = (v)) /*@}*/ /*! * @name Register PDB_SC, field SWTRIG[16] (WORZ) * * When PDB is enabled and the software trigger is selected as the trigger input * source, writing 1 to this field resets and restarts the counter. Writing 0 to * this field has no effect. Reading this field results 0. */ /*@{*/ #define BP_PDB_SC_SWTRIG (16U) /*!< Bit position for PDB_SC_SWTRIG. */ #define BM_PDB_SC_SWTRIG (0x00010000U) /*!< Bit mask for PDB_SC_SWTRIG. */ #define BS_PDB_SC_SWTRIG (1U) /*!< Bit field size in bits for PDB_SC_SWTRIG. */ /*! @brief Format value for bitfield PDB_SC_SWTRIG. */ #define BF_PDB_SC_SWTRIG(v) ((uint32_t)((uint32_t)(v) << BP_PDB_SC_SWTRIG) & BM_PDB_SC_SWTRIG) /*! @brief Set the SWTRIG field to a new value. */ #define BW_PDB_SC_SWTRIG(x, v) (BITBAND_ACCESS32(HW_PDB_SC_ADDR(x), BP_PDB_SC_SWTRIG) = (v)) /*@}*/ /*! * @name Register PDB_SC, field PDBEIE[17] (RW) * * Enables the PDB sequence error interrupt. When this field is set, any of the * PDB channel sequence error flags generates a PDB sequence error interrupt. * * Values: * - 0 - PDB sequence error interrupt disabled. * - 1 - PDB sequence error interrupt enabled. */ /*@{*/ #define BP_PDB_SC_PDBEIE (17U) /*!< Bit position for PDB_SC_PDBEIE. */ #define BM_PDB_SC_PDBEIE (0x00020000U) /*!< Bit mask for PDB_SC_PDBEIE. */ #define BS_PDB_SC_PDBEIE (1U) /*!< Bit field size in bits for PDB_SC_PDBEIE. */ /*! @brief Read current value of the PDB_SC_PDBEIE field. */ #define BR_PDB_SC_PDBEIE(x) (BITBAND_ACCESS32(HW_PDB_SC_ADDR(x), BP_PDB_SC_PDBEIE)) /*! @brief Format value for bitfield PDB_SC_PDBEIE. */ #define BF_PDB_SC_PDBEIE(v) ((uint32_t)((uint32_t)(v) << BP_PDB_SC_PDBEIE) & BM_PDB_SC_PDBEIE) /*! @brief Set the PDBEIE field to a new value. */ #define BW_PDB_SC_PDBEIE(x, v) (BITBAND_ACCESS32(HW_PDB_SC_ADDR(x), BP_PDB_SC_PDBEIE) = (v)) /*@}*/ /*! * @name Register PDB_SC, field LDMOD[19:18] (RW) * * Selects the mode to load the MOD, IDLY, CHnDLYm, INTx, and POyDLY registers, * after 1 is written to LDOK. * * Values: * - 00 - The internal registers are loaded with the values from their buffers * immediately after 1 is written to LDOK. * - 01 - The internal registers are loaded with the values from their buffers * when the PDB counter reaches the MOD register value after 1 is written to * LDOK. * - 10 - The internal registers are loaded with the values from their buffers * when a trigger input event is detected after 1 is written to LDOK. * - 11 - The internal registers are loaded with the values from their buffers * when either the PDB counter reaches the MOD register value or a trigger * input event is detected, after 1 is written to LDOK. */ /*@{*/ #define BP_PDB_SC_LDMOD (18U) /*!< Bit position for PDB_SC_LDMOD. */ #define BM_PDB_SC_LDMOD (0x000C0000U) /*!< Bit mask for PDB_SC_LDMOD. */ #define BS_PDB_SC_LDMOD (2U) /*!< Bit field size in bits for PDB_SC_LDMOD. */ /*! @brief Read current value of the PDB_SC_LDMOD field. */ #define BR_PDB_SC_LDMOD(x) (HW_PDB_SC(x).B.LDMOD) /*! @brief Format value for bitfield PDB_SC_LDMOD. */ #define BF_PDB_SC_LDMOD(v) ((uint32_t)((uint32_t)(v) << BP_PDB_SC_LDMOD) & BM_PDB_SC_LDMOD) /*! @brief Set the LDMOD field to a new value. */ #define BW_PDB_SC_LDMOD(x, v) (HW_PDB_SC_WR(x, (HW_PDB_SC_RD(x) & ~BM_PDB_SC_LDMOD) | BF_PDB_SC_LDMOD(v))) /*@}*/ /******************************************************************************* * HW_PDB_MOD - Modulus register ******************************************************************************/ /*! * @brief HW_PDB_MOD - Modulus register (RW) * * Reset value: 0x0000FFFFU */ typedef union _hw_pdb_mod { uint32_t U; struct _hw_pdb_mod_bitfields { uint32_t MOD : 16; /*!< [15:0] PDB Modulus */ uint32_t RESERVED0 : 16; /*!< [31:16] */ } B; } hw_pdb_mod_t; /*! * @name Constants and macros for entire PDB_MOD register */ /*@{*/ #define HW_PDB_MOD_ADDR(x) ((x) + 0x4U) #define HW_PDB_MOD(x) (*(__IO hw_pdb_mod_t *) HW_PDB_MOD_ADDR(x)) #define HW_PDB_MOD_RD(x) (HW_PDB_MOD(x).U) #define HW_PDB_MOD_WR(x, v) (HW_PDB_MOD(x).U = (v)) #define HW_PDB_MOD_SET(x, v) (HW_PDB_MOD_WR(x, HW_PDB_MOD_RD(x) | (v))) #define HW_PDB_MOD_CLR(x, v) (HW_PDB_MOD_WR(x, HW_PDB_MOD_RD(x) & ~(v))) #define HW_PDB_MOD_TOG(x, v) (HW_PDB_MOD_WR(x, HW_PDB_MOD_RD(x) ^ (v))) /*@}*/ /* * Constants & macros for individual PDB_MOD bitfields */ /*! * @name Register PDB_MOD, field MOD[15:0] (RW) * * Specifies the period of the counter. When the counter reaches this value, it * will be reset back to zero. If the PDB is in Continuous mode, the count begins * anew. Reading this field returns the value of the internal register that is * effective for the current cycle of PDB. */ /*@{*/ #define BP_PDB_MOD_MOD (0U) /*!< Bit position for PDB_MOD_MOD. */ #define BM_PDB_MOD_MOD (0x0000FFFFU) /*!< Bit mask for PDB_MOD_MOD. */ #define BS_PDB_MOD_MOD (16U) /*!< Bit field size in bits for PDB_MOD_MOD. */ /*! @brief Read current value of the PDB_MOD_MOD field. */ #define BR_PDB_MOD_MOD(x) (HW_PDB_MOD(x).B.MOD) /*! @brief Format value for bitfield PDB_MOD_MOD. */ #define BF_PDB_MOD_MOD(v) ((uint32_t)((uint32_t)(v) << BP_PDB_MOD_MOD) & BM_PDB_MOD_MOD) /*! @brief Set the MOD field to a new value. */ #define BW_PDB_MOD_MOD(x, v) (HW_PDB_MOD_WR(x, (HW_PDB_MOD_RD(x) & ~BM_PDB_MOD_MOD) | BF_PDB_MOD_MOD(v))) /*@}*/ /******************************************************************************* * HW_PDB_CNT - Counter register ******************************************************************************/ /*! * @brief HW_PDB_CNT - Counter register (RO) * * Reset value: 0x00000000U */ typedef union _hw_pdb_cnt { uint32_t U; struct _hw_pdb_cnt_bitfields { uint32_t CNT : 16; /*!< [15:0] PDB Counter */ uint32_t RESERVED0 : 16; /*!< [31:16] */ } B; } hw_pdb_cnt_t; /*! * @name Constants and macros for entire PDB_CNT register */ /*@{*/ #define HW_PDB_CNT_ADDR(x) ((x) + 0x8U) #define HW_PDB_CNT(x) (*(__I hw_pdb_cnt_t *) HW_PDB_CNT_ADDR(x)) #define HW_PDB_CNT_RD(x) (HW_PDB_CNT(x).U) /*@}*/ /* * Constants & macros for individual PDB_CNT bitfields */ /*! * @name Register PDB_CNT, field CNT[15:0] (RO) * * Contains the current value of the counter. */ /*@{*/ #define BP_PDB_CNT_CNT (0U) /*!< Bit position for PDB_CNT_CNT. */ #define BM_PDB_CNT_CNT (0x0000FFFFU) /*!< Bit mask for PDB_CNT_CNT. */ #define BS_PDB_CNT_CNT (16U) /*!< Bit field size in bits for PDB_CNT_CNT. */ /*! @brief Read current value of the PDB_CNT_CNT field. */ #define BR_PDB_CNT_CNT(x) (HW_PDB_CNT(x).B.CNT) /*@}*/ /******************************************************************************* * HW_PDB_IDLY - Interrupt Delay register ******************************************************************************/ /*! * @brief HW_PDB_IDLY - Interrupt Delay register (RW) * * Reset value: 0x0000FFFFU */ typedef union _hw_pdb_idly { uint32_t U; struct _hw_pdb_idly_bitfields { uint32_t IDLY : 16; /*!< [15:0] PDB Interrupt Delay */ uint32_t RESERVED0 : 16; /*!< [31:16] */ } B; } hw_pdb_idly_t; /*! * @name Constants and macros for entire PDB_IDLY register */ /*@{*/ #define HW_PDB_IDLY_ADDR(x) ((x) + 0xCU) #define HW_PDB_IDLY(x) (*(__IO hw_pdb_idly_t *) HW_PDB_IDLY_ADDR(x)) #define HW_PDB_IDLY_RD(x) (HW_PDB_IDLY(x).U) #define HW_PDB_IDLY_WR(x, v) (HW_PDB_IDLY(x).U = (v)) #define HW_PDB_IDLY_SET(x, v) (HW_PDB_IDLY_WR(x, HW_PDB_IDLY_RD(x) | (v))) #define HW_PDB_IDLY_CLR(x, v) (HW_PDB_IDLY_WR(x, HW_PDB_IDLY_RD(x) & ~(v))) #define HW_PDB_IDLY_TOG(x, v) (HW_PDB_IDLY_WR(x, HW_PDB_IDLY_RD(x) ^ (v))) /*@}*/ /* * Constants & macros for individual PDB_IDLY bitfields */ /*! * @name Register PDB_IDLY, field IDLY[15:0] (RW) * * Specifies the delay value to schedule the PDB interrupt. It can be used to * schedule an independent interrupt at some point in the PDB cycle. If enabled, a * PDB interrupt is generated, when the counter is equal to the IDLY. Reading * this field returns the value of internal register that is effective for the * current cycle of the PDB. */ /*@{*/ #define BP_PDB_IDLY_IDLY (0U) /*!< Bit position for PDB_IDLY_IDLY. */ #define BM_PDB_IDLY_IDLY (0x0000FFFFU) /*!< Bit mask for PDB_IDLY_IDLY. */ #define BS_PDB_IDLY_IDLY (16U) /*!< Bit field size in bits for PDB_IDLY_IDLY. */ /*! @brief Read current value of the PDB_IDLY_IDLY field. */ #define BR_PDB_IDLY_IDLY(x) (HW_PDB_IDLY(x).B.IDLY) /*! @brief Format value for bitfield PDB_IDLY_IDLY. */ #define BF_PDB_IDLY_IDLY(v) ((uint32_t)((uint32_t)(v) << BP_PDB_IDLY_IDLY) & BM_PDB_IDLY_IDLY) /*! @brief Set the IDLY field to a new value. */ #define BW_PDB_IDLY_IDLY(x, v) (HW_PDB_IDLY_WR(x, (HW_PDB_IDLY_RD(x) & ~BM_PDB_IDLY_IDLY) | BF_PDB_IDLY_IDLY(v))) /*@}*/ /******************************************************************************* * HW_PDB_CHnC1 - Channel n Control register 1 ******************************************************************************/ /*! * @brief HW_PDB_CHnC1 - Channel n Control register 1 (RW) * * Reset value: 0x00000000U * * Each PDB channel has one control register, CHnC1. The bits in this register * control the functionality of each PDB channel operation. */ typedef union _hw_pdb_chnc1 { uint32_t U; struct _hw_pdb_chnc1_bitfields { uint32_t EN : 8; /*!< [7:0] PDB Channel Pre-Trigger Enable */ uint32_t TOS : 8; /*!< [15:8] PDB Channel Pre-Trigger Output Select */ uint32_t BB : 8; /*!< [23:16] PDB Channel Pre-Trigger Back-to-Back * Operation Enable */ uint32_t RESERVED0 : 8; /*!< [31:24] */ } B; } hw_pdb_chnc1_t; /*! * @name Constants and macros for entire PDB_CHnC1 register */ /*@{*/ #define HW_PDB_CHnC1_COUNT (2U) #define HW_PDB_CHnC1_ADDR(x, n) ((x) + 0x10U + (0x28U * (n))) #define HW_PDB_CHnC1(x, n) (*(__IO hw_pdb_chnc1_t *) HW_PDB_CHnC1_ADDR(x, n)) #define HW_PDB_CHnC1_RD(x, n) (HW_PDB_CHnC1(x, n).U) #define HW_PDB_CHnC1_WR(x, n, v) (HW_PDB_CHnC1(x, n).U = (v)) #define HW_PDB_CHnC1_SET(x, n, v) (HW_PDB_CHnC1_WR(x, n, HW_PDB_CHnC1_RD(x, n) | (v))) #define HW_PDB_CHnC1_CLR(x, n, v) (HW_PDB_CHnC1_WR(x, n, HW_PDB_CHnC1_RD(x, n) & ~(v))) #define HW_PDB_CHnC1_TOG(x, n, v) (HW_PDB_CHnC1_WR(x, n, HW_PDB_CHnC1_RD(x, n) ^ (v))) /*@}*/ /* * Constants & macros for individual PDB_CHnC1 bitfields */ /*! * @name Register PDB_CHnC1, field EN[7:0] (RW) * * These bits enable the PDB ADC pre-trigger outputs. Only lower M pre-trigger * bits are implemented in this MCU. * * Values: * - 0 - PDB channel's corresponding pre-trigger disabled. * - 1 - PDB channel's corresponding pre-trigger enabled. */ /*@{*/ #define BP_PDB_CHnC1_EN (0U) /*!< Bit position for PDB_CHnC1_EN. */ #define BM_PDB_CHnC1_EN (0x000000FFU) /*!< Bit mask for PDB_CHnC1_EN. */ #define BS_PDB_CHnC1_EN (8U) /*!< Bit field size in bits for PDB_CHnC1_EN. */ /*! @brief Read current value of the PDB_CHnC1_EN field. */ #define BR_PDB_CHnC1_EN(x, n) (HW_PDB_CHnC1(x, n).B.EN) /*! @brief Format value for bitfield PDB_CHnC1_EN. */ #define BF_PDB_CHnC1_EN(v) ((uint32_t)((uint32_t)(v) << BP_PDB_CHnC1_EN) & BM_PDB_CHnC1_EN) /*! @brief Set the EN field to a new value. */ #define BW_PDB_CHnC1_EN(x, n, v) (HW_PDB_CHnC1_WR(x, n, (HW_PDB_CHnC1_RD(x, n) & ~BM_PDB_CHnC1_EN) | BF_PDB_CHnC1_EN(v))) /*@}*/ /*! * @name Register PDB_CHnC1, field TOS[15:8] (RW) * * Selects the PDB ADC pre-trigger outputs. Only lower M pre-trigger fields are * implemented in this MCU. * * Values: * - 0 - PDB channel's corresponding pre-trigger is in bypassed mode. The * pre-trigger asserts one peripheral clock cycle after a rising edge is detected * on selected trigger input source or software trigger is selected and SWTRIG * is written with 1. * - 1 - PDB channel's corresponding pre-trigger asserts when the counter * reaches the channel delay register and one peripheral clock cycle after a rising * edge is detected on selected trigger input source or software trigger is * selected and SETRIG is written with 1. */ /*@{*/ #define BP_PDB_CHnC1_TOS (8U) /*!< Bit position for PDB_CHnC1_TOS. */ #define BM_PDB_CHnC1_TOS (0x0000FF00U) /*!< Bit mask for PDB_CHnC1_TOS. */ #define BS_PDB_CHnC1_TOS (8U) /*!< Bit field size in bits for PDB_CHnC1_TOS. */ /*! @brief Read current value of the PDB_CHnC1_TOS field. */ #define BR_PDB_CHnC1_TOS(x, n) (HW_PDB_CHnC1(x, n).B.TOS) /*! @brief Format value for bitfield PDB_CHnC1_TOS. */ #define BF_PDB_CHnC1_TOS(v) ((uint32_t)((uint32_t)(v) << BP_PDB_CHnC1_TOS) & BM_PDB_CHnC1_TOS) /*! @brief Set the TOS field to a new value. */ #define BW_PDB_CHnC1_TOS(x, n, v) (HW_PDB_CHnC1_WR(x, n, (HW_PDB_CHnC1_RD(x, n) & ~BM_PDB_CHnC1_TOS) | BF_PDB_CHnC1_TOS(v))) /*@}*/ /*! * @name Register PDB_CHnC1, field BB[23:16] (RW) * * These bits enable the PDB ADC pre-trigger operation as back-to-back mode. * Only lower M pre-trigger bits are implemented in this MCU. Back-to-back operation * enables the ADC conversions complete to trigger the next PDB channel * pre-trigger and trigger output, so that the ADC conversions can be triggered on next * set of configuration and results registers. Application code must only enable * the back-to-back operation of the PDB pre-triggers at the leading of the * back-to-back connection chain. * * Values: * - 0 - PDB channel's corresponding pre-trigger back-to-back operation disabled. * - 1 - PDB channel's corresponding pre-trigger back-to-back operation enabled. */ /*@{*/ #define BP_PDB_CHnC1_BB (16U) /*!< Bit position for PDB_CHnC1_BB. */ #define BM_PDB_CHnC1_BB (0x00FF0000U) /*!< Bit mask for PDB_CHnC1_BB. */ #define BS_PDB_CHnC1_BB (8U) /*!< Bit field size in bits for PDB_CHnC1_BB. */ /*! @brief Read current value of the PDB_CHnC1_BB field. */ #define BR_PDB_CHnC1_BB(x, n) (HW_PDB_CHnC1(x, n).B.BB) /*! @brief Format value for bitfield PDB_CHnC1_BB. */ #define BF_PDB_CHnC1_BB(v) ((uint32_t)((uint32_t)(v) << BP_PDB_CHnC1_BB) & BM_PDB_CHnC1_BB) /*! @brief Set the BB field to a new value. */ #define BW_PDB_CHnC1_BB(x, n, v) (HW_PDB_CHnC1_WR(x, n, (HW_PDB_CHnC1_RD(x, n) & ~BM_PDB_CHnC1_BB) | BF_PDB_CHnC1_BB(v))) /*@}*/ /******************************************************************************* * HW_PDB_CHnS - Channel n Status register ******************************************************************************/ /*! * @brief HW_PDB_CHnS - Channel n Status register (RW) * * Reset value: 0x00000000U */ typedef union _hw_pdb_chns { uint32_t U; struct _hw_pdb_chns_bitfields { uint32_t ERR : 8; /*!< [7:0] PDB Channel Sequence Error Flags */ uint32_t RESERVED0 : 8; /*!< [15:8] */ uint32_t CF : 8; /*!< [23:16] PDB Channel Flags */ uint32_t RESERVED1 : 8; /*!< [31:24] */ } B; } hw_pdb_chns_t; /*! * @name Constants and macros for entire PDB_CHnS register */ /*@{*/ #define HW_PDB_CHnS_COUNT (2U) #define HW_PDB_CHnS_ADDR(x, n) ((x) + 0x14U + (0x28U * (n))) #define HW_PDB_CHnS(x, n) (*(__IO hw_pdb_chns_t *) HW_PDB_CHnS_ADDR(x, n)) #define HW_PDB_CHnS_RD(x, n) (HW_PDB_CHnS(x, n).U) #define HW_PDB_CHnS_WR(x, n, v) (HW_PDB_CHnS(x, n).U = (v)) #define HW_PDB_CHnS_SET(x, n, v) (HW_PDB_CHnS_WR(x, n, HW_PDB_CHnS_RD(x, n) | (v))) #define HW_PDB_CHnS_CLR(x, n, v) (HW_PDB_CHnS_WR(x, n, HW_PDB_CHnS_RD(x, n) & ~(v))) #define HW_PDB_CHnS_TOG(x, n, v) (HW_PDB_CHnS_WR(x, n, HW_PDB_CHnS_RD(x, n) ^ (v))) /*@}*/ /* * Constants & macros for individual PDB_CHnS bitfields */ /*! * @name Register PDB_CHnS, field ERR[7:0] (RW) * * Only the lower M bits are implemented in this MCU. * * Values: * - 0 - Sequence error not detected on PDB channel's corresponding pre-trigger. * - 1 - Sequence error detected on PDB channel's corresponding pre-trigger. * ADCn block can be triggered for a conversion by one pre-trigger from PDB * channel n. When one conversion, which is triggered by one of the pre-triggers * from PDB channel n, is in progress, new trigger from PDB channel's * corresponding pre-trigger m cannot be accepted by ADCn, and ERR[m] is set. * Writing 0's to clear the sequence error flags. */ /*@{*/ #define BP_PDB_CHnS_ERR (0U) /*!< Bit position for PDB_CHnS_ERR. */ #define BM_PDB_CHnS_ERR (0x000000FFU) /*!< Bit mask for PDB_CHnS_ERR. */ #define BS_PDB_CHnS_ERR (8U) /*!< Bit field size in bits for PDB_CHnS_ERR. */ /*! @brief Read current value of the PDB_CHnS_ERR field. */ #define BR_PDB_CHnS_ERR(x, n) (HW_PDB_CHnS(x, n).B.ERR) /*! @brief Format value for bitfield PDB_CHnS_ERR. */ #define BF_PDB_CHnS_ERR(v) ((uint32_t)((uint32_t)(v) << BP_PDB_CHnS_ERR) & BM_PDB_CHnS_ERR) /*! @brief Set the ERR field to a new value. */ #define BW_PDB_CHnS_ERR(x, n, v) (HW_PDB_CHnS_WR(x, n, (HW_PDB_CHnS_RD(x, n) & ~BM_PDB_CHnS_ERR) | BF_PDB_CHnS_ERR(v))) /*@}*/ /*! * @name Register PDB_CHnS, field CF[23:16] (RW) * * The CF[m] bit is set when the PDB counter matches the CHnDLYm. Write 0 to * clear these bits. */ /*@{*/ #define BP_PDB_CHnS_CF (16U) /*!< Bit position for PDB_CHnS_CF. */ #define BM_PDB_CHnS_CF (0x00FF0000U) /*!< Bit mask for PDB_CHnS_CF. */ #define BS_PDB_CHnS_CF (8U) /*!< Bit field size in bits for PDB_CHnS_CF. */ /*! @brief Read current value of the PDB_CHnS_CF field. */ #define BR_PDB_CHnS_CF(x, n) (HW_PDB_CHnS(x, n).B.CF) /*! @brief Format value for bitfield PDB_CHnS_CF. */ #define BF_PDB_CHnS_CF(v) ((uint32_t)((uint32_t)(v) << BP_PDB_CHnS_CF) & BM_PDB_CHnS_CF) /*! @brief Set the CF field to a new value. */ #define BW_PDB_CHnS_CF(x, n, v) (HW_PDB_CHnS_WR(x, n, (HW_PDB_CHnS_RD(x, n) & ~BM_PDB_CHnS_CF) | BF_PDB_CHnS_CF(v))) /*@}*/ /******************************************************************************* * HW_PDB_CHnDLY0 - Channel n Delay 0 register ******************************************************************************/ /*! * @brief HW_PDB_CHnDLY0 - Channel n Delay 0 register (RW) * * Reset value: 0x00000000U */ typedef union _hw_pdb_chndly0 { uint32_t U; struct _hw_pdb_chndly0_bitfields { uint32_t DLY : 16; /*!< [15:0] PDB Channel Delay */ uint32_t RESERVED0 : 16; /*!< [31:16] */ } B; } hw_pdb_chndly0_t; /*! * @name Constants and macros for entire PDB_CHnDLY0 register */ /*@{*/ #define HW_PDB_CHnDLY0_COUNT (2U) #define HW_PDB_CHnDLY0_ADDR(x, n) ((x) + 0x18U + (0x28U * (n))) #define HW_PDB_CHnDLY0(x, n) (*(__IO hw_pdb_chndly0_t *) HW_PDB_CHnDLY0_ADDR(x, n)) #define HW_PDB_CHnDLY0_RD(x, n) (HW_PDB_CHnDLY0(x, n).U) #define HW_PDB_CHnDLY0_WR(x, n, v) (HW_PDB_CHnDLY0(x, n).U = (v)) #define HW_PDB_CHnDLY0_SET(x, n, v) (HW_PDB_CHnDLY0_WR(x, n, HW_PDB_CHnDLY0_RD(x, n) | (v))) #define HW_PDB_CHnDLY0_CLR(x, n, v) (HW_PDB_CHnDLY0_WR(x, n, HW_PDB_CHnDLY0_RD(x, n) & ~(v))) #define HW_PDB_CHnDLY0_TOG(x, n, v) (HW_PDB_CHnDLY0_WR(x, n, HW_PDB_CHnDLY0_RD(x, n) ^ (v))) /*@}*/ /* * Constants & macros for individual PDB_CHnDLY0 bitfields */ /*! * @name Register PDB_CHnDLY0, field DLY[15:0] (RW) * * Specifies the delay value for the channel's corresponding pre-trigger. The * pre-trigger asserts when the counter is equal to DLY. Reading this field returns * the value of internal register that is effective for the current PDB cycle. */ /*@{*/ #define BP_PDB_CHnDLY0_DLY (0U) /*!< Bit position for PDB_CHnDLY0_DLY. */ #define BM_PDB_CHnDLY0_DLY (0x0000FFFFU) /*!< Bit mask for PDB_CHnDLY0_DLY. */ #define BS_PDB_CHnDLY0_DLY (16U) /*!< Bit field size in bits for PDB_CHnDLY0_DLY. */ /*! @brief Read current value of the PDB_CHnDLY0_DLY field. */ #define BR_PDB_CHnDLY0_DLY(x, n) (HW_PDB_CHnDLY0(x, n).B.DLY) /*! @brief Format value for bitfield PDB_CHnDLY0_DLY. */ #define BF_PDB_CHnDLY0_DLY(v) ((uint32_t)((uint32_t)(v) << BP_PDB_CHnDLY0_DLY) & BM_PDB_CHnDLY0_DLY) /*! @brief Set the DLY field to a new value. */ #define BW_PDB_CHnDLY0_DLY(x, n, v) (HW_PDB_CHnDLY0_WR(x, n, (HW_PDB_CHnDLY0_RD(x, n) & ~BM_PDB_CHnDLY0_DLY) | BF_PDB_CHnDLY0_DLY(v))) /*@}*/ /******************************************************************************* * HW_PDB_CHnDLY1 - Channel n Delay 1 register ******************************************************************************/ /*! * @brief HW_PDB_CHnDLY1 - Channel n Delay 1 register (RW) * * Reset value: 0x00000000U */ typedef union _hw_pdb_chndly1 { uint32_t U; struct _hw_pdb_chndly1_bitfields { uint32_t DLY : 16; /*!< [15:0] PDB Channel Delay */ uint32_t RESERVED0 : 16; /*!< [31:16] */ } B; } hw_pdb_chndly1_t; /*! * @name Constants and macros for entire PDB_CHnDLY1 register */ /*@{*/ #define HW_PDB_CHnDLY1_COUNT (2U) #define HW_PDB_CHnDLY1_ADDR(x, n) ((x) + 0x1CU + (0x28U * (n))) #define HW_PDB_CHnDLY1(x, n) (*(__IO hw_pdb_chndly1_t *) HW_PDB_CHnDLY1_ADDR(x, n)) #define HW_PDB_CHnDLY1_RD(x, n) (HW_PDB_CHnDLY1(x, n).U) #define HW_PDB_CHnDLY1_WR(x, n, v) (HW_PDB_CHnDLY1(x, n).U = (v)) #define HW_PDB_CHnDLY1_SET(x, n, v) (HW_PDB_CHnDLY1_WR(x, n, HW_PDB_CHnDLY1_RD(x, n) | (v))) #define HW_PDB_CHnDLY1_CLR(x, n, v) (HW_PDB_CHnDLY1_WR(x, n, HW_PDB_CHnDLY1_RD(x, n) & ~(v))) #define HW_PDB_CHnDLY1_TOG(x, n, v) (HW_PDB_CHnDLY1_WR(x, n, HW_PDB_CHnDLY1_RD(x, n) ^ (v))) /*@}*/ /* * Constants & macros for individual PDB_CHnDLY1 bitfields */ /*! * @name Register PDB_CHnDLY1, field DLY[15:0] (RW) * * These bits specify the delay value for the channel's corresponding * pre-trigger. The pre-trigger asserts when the counter is equal to DLY. Reading these * bits returns the value of internal register that is effective for the current PDB * cycle. */ /*@{*/ #define BP_PDB_CHnDLY1_DLY (0U) /*!< Bit position for PDB_CHnDLY1_DLY. */ #define BM_PDB_CHnDLY1_DLY (0x0000FFFFU) /*!< Bit mask for PDB_CHnDLY1_DLY. */ #define BS_PDB_CHnDLY1_DLY (16U) /*!< Bit field size in bits for PDB_CHnDLY1_DLY. */ /*! @brief Read current value of the PDB_CHnDLY1_DLY field. */ #define BR_PDB_CHnDLY1_DLY(x, n) (HW_PDB_CHnDLY1(x, n).B.DLY) /*! @brief Format value for bitfield PDB_CHnDLY1_DLY. */ #define BF_PDB_CHnDLY1_DLY(v) ((uint32_t)((uint32_t)(v) << BP_PDB_CHnDLY1_DLY) & BM_PDB_CHnDLY1_DLY) /*! @brief Set the DLY field to a new value. */ #define BW_PDB_CHnDLY1_DLY(x, n, v) (HW_PDB_CHnDLY1_WR(x, n, (HW_PDB_CHnDLY1_RD(x, n) & ~BM_PDB_CHnDLY1_DLY) | BF_PDB_CHnDLY1_DLY(v))) /*@}*/ /******************************************************************************* * HW_PDB_DACINTCn - DAC Interval Trigger n Control register ******************************************************************************/ /*! * @brief HW_PDB_DACINTCn - DAC Interval Trigger n Control register (RW) * * Reset value: 0x00000000U */ typedef union _hw_pdb_dacintcn { uint32_t U; struct _hw_pdb_dacintcn_bitfields { uint32_t TOE : 1; /*!< [0] DAC Interval Trigger Enable */ uint32_t EXT : 1; /*!< [1] DAC External Trigger Input Enable */ uint32_t RESERVED0 : 30; /*!< [31:2] */ } B; } hw_pdb_dacintcn_t; /*! * @name Constants and macros for entire PDB_DACINTCn register */ /*@{*/ #define HW_PDB_DACINTCn_COUNT (2U) #define HW_PDB_DACINTCn_ADDR(x, n) ((x) + 0x150U + (0x8U * (n))) #define HW_PDB_DACINTCn(x, n) (*(__IO hw_pdb_dacintcn_t *) HW_PDB_DACINTCn_ADDR(x, n)) #define HW_PDB_DACINTCn_RD(x, n) (HW_PDB_DACINTCn(x, n).U) #define HW_PDB_DACINTCn_WR(x, n, v) (HW_PDB_DACINTCn(x, n).U = (v)) #define HW_PDB_DACINTCn_SET(x, n, v) (HW_PDB_DACINTCn_WR(x, n, HW_PDB_DACINTCn_RD(x, n) | (v))) #define HW_PDB_DACINTCn_CLR(x, n, v) (HW_PDB_DACINTCn_WR(x, n, HW_PDB_DACINTCn_RD(x, n) & ~(v))) #define HW_PDB_DACINTCn_TOG(x, n, v) (HW_PDB_DACINTCn_WR(x, n, HW_PDB_DACINTCn_RD(x, n) ^ (v))) /*@}*/ /* * Constants & macros for individual PDB_DACINTCn bitfields */ /*! * @name Register PDB_DACINTCn, field TOE[0] (RW) * * This bit enables the DAC interval trigger. * * Values: * - 0 - DAC interval trigger disabled. * - 1 - DAC interval trigger enabled. */ /*@{*/ #define BP_PDB_DACINTCn_TOE (0U) /*!< Bit position for PDB_DACINTCn_TOE. */ #define BM_PDB_DACINTCn_TOE (0x00000001U) /*!< Bit mask for PDB_DACINTCn_TOE. */ #define BS_PDB_DACINTCn_TOE (1U) /*!< Bit field size in bits for PDB_DACINTCn_TOE. */ /*! @brief Read current value of the PDB_DACINTCn_TOE field. */ #define BR_PDB_DACINTCn_TOE(x, n) (BITBAND_ACCESS32(HW_PDB_DACINTCn_ADDR(x, n), BP_PDB_DACINTCn_TOE)) /*! @brief Format value for bitfield PDB_DACINTCn_TOE. */ #define BF_PDB_DACINTCn_TOE(v) ((uint32_t)((uint32_t)(v) << BP_PDB_DACINTCn_TOE) & BM_PDB_DACINTCn_TOE) /*! @brief Set the TOE field to a new value. */ #define BW_PDB_DACINTCn_TOE(x, n, v) (BITBAND_ACCESS32(HW_PDB_DACINTCn_ADDR(x, n), BP_PDB_DACINTCn_TOE) = (v)) /*@}*/ /*! * @name Register PDB_DACINTCn, field EXT[1] (RW) * * Enables the external trigger for DAC interval counter. * * Values: * - 0 - DAC external trigger input disabled. DAC interval counter is reset and * counting starts when a rising edge is detected on selected trigger input * source or software trigger is selected and SWTRIG is written with 1. * - 1 - DAC external trigger input enabled. DAC interval counter is bypassed * and DAC external trigger input triggers the DAC interval trigger. */ /*@{*/ #define BP_PDB_DACINTCn_EXT (1U) /*!< Bit position for PDB_DACINTCn_EXT. */ #define BM_PDB_DACINTCn_EXT (0x00000002U) /*!< Bit mask for PDB_DACINTCn_EXT. */ #define BS_PDB_DACINTCn_EXT (1U) /*!< Bit field size in bits for PDB_DACINTCn_EXT. */ /*! @brief Read current value of the PDB_DACINTCn_EXT field. */ #define BR_PDB_DACINTCn_EXT(x, n) (BITBAND_ACCESS32(HW_PDB_DACINTCn_ADDR(x, n), BP_PDB_DACINTCn_EXT)) /*! @brief Format value for bitfield PDB_DACINTCn_EXT. */ #define BF_PDB_DACINTCn_EXT(v) ((uint32_t)((uint32_t)(v) << BP_PDB_DACINTCn_EXT) & BM_PDB_DACINTCn_EXT) /*! @brief Set the EXT field to a new value. */ #define BW_PDB_DACINTCn_EXT(x, n, v) (BITBAND_ACCESS32(HW_PDB_DACINTCn_ADDR(x, n), BP_PDB_DACINTCn_EXT) = (v)) /*@}*/ /******************************************************************************* * HW_PDB_DACINTn - DAC Interval n register ******************************************************************************/ /*! * @brief HW_PDB_DACINTn - DAC Interval n register (RW) * * Reset value: 0x00000000U */ typedef union _hw_pdb_dacintn { uint32_t U; struct _hw_pdb_dacintn_bitfields { uint32_t INT : 16; /*!< [15:0] DAC Interval */ uint32_t RESERVED0 : 16; /*!< [31:16] */ } B; } hw_pdb_dacintn_t; /*! * @name Constants and macros for entire PDB_DACINTn register */ /*@{*/ #define HW_PDB_DACINTn_COUNT (2U) #define HW_PDB_DACINTn_ADDR(x, n) ((x) + 0x154U + (0x8U * (n))) #define HW_PDB_DACINTn(x, n) (*(__IO hw_pdb_dacintn_t *) HW_PDB_DACINTn_ADDR(x, n)) #define HW_PDB_DACINTn_RD(x, n) (HW_PDB_DACINTn(x, n).U) #define HW_PDB_DACINTn_WR(x, n, v) (HW_PDB_DACINTn(x, n).U = (v)) #define HW_PDB_DACINTn_SET(x, n, v) (HW_PDB_DACINTn_WR(x, n, HW_PDB_DACINTn_RD(x, n) | (v))) #define HW_PDB_DACINTn_CLR(x, n, v) (HW_PDB_DACINTn_WR(x, n, HW_PDB_DACINTn_RD(x, n) & ~(v))) #define HW_PDB_DACINTn_TOG(x, n, v) (HW_PDB_DACINTn_WR(x, n, HW_PDB_DACINTn_RD(x, n) ^ (v))) /*@}*/ /* * Constants & macros for individual PDB_DACINTn bitfields */ /*! * @name Register PDB_DACINTn, field INT[15:0] (RW) * * Specifies the interval value for DAC interval trigger. DAC interval trigger * triggers DAC[1:0] update when the DAC interval counter is equal to the DACINT. * Reading this field returns the value of internal register that is effective * for the current PDB cycle. */ /*@{*/ #define BP_PDB_DACINTn_INT (0U) /*!< Bit position for PDB_DACINTn_INT. */ #define BM_PDB_DACINTn_INT (0x0000FFFFU) /*!< Bit mask for PDB_DACINTn_INT. */ #define BS_PDB_DACINTn_INT (16U) /*!< Bit field size in bits for PDB_DACINTn_INT. */ /*! @brief Read current value of the PDB_DACINTn_INT field. */ #define BR_PDB_DACINTn_INT(x, n) (HW_PDB_DACINTn(x, n).B.INT) /*! @brief Format value for bitfield PDB_DACINTn_INT. */ #define BF_PDB_DACINTn_INT(v) ((uint32_t)((uint32_t)(v) << BP_PDB_DACINTn_INT) & BM_PDB_DACINTn_INT) /*! @brief Set the INT field to a new value. */ #define BW_PDB_DACINTn_INT(x, n, v) (HW_PDB_DACINTn_WR(x, n, (HW_PDB_DACINTn_RD(x, n) & ~BM_PDB_DACINTn_INT) | BF_PDB_DACINTn_INT(v))) /*@}*/ /******************************************************************************* * HW_PDB_POEN - Pulse-Out n Enable register ******************************************************************************/ /*! * @brief HW_PDB_POEN - Pulse-Out n Enable register (RW) * * Reset value: 0x00000000U */ typedef union _hw_pdb_poen { uint32_t U; struct _hw_pdb_poen_bitfields { uint32_t POEN : 8; /*!< [7:0] PDB Pulse-Out Enable */ uint32_t RESERVED0 : 24; /*!< [31:8] */ } B; } hw_pdb_poen_t; /*! * @name Constants and macros for entire PDB_POEN register */ /*@{*/ #define HW_PDB_POEN_ADDR(x) ((x) + 0x190U) #define HW_PDB_POEN(x) (*(__IO hw_pdb_poen_t *) HW_PDB_POEN_ADDR(x)) #define HW_PDB_POEN_RD(x) (HW_PDB_POEN(x).U) #define HW_PDB_POEN_WR(x, v) (HW_PDB_POEN(x).U = (v)) #define HW_PDB_POEN_SET(x, v) (HW_PDB_POEN_WR(x, HW_PDB_POEN_RD(x) | (v))) #define HW_PDB_POEN_CLR(x, v) (HW_PDB_POEN_WR(x, HW_PDB_POEN_RD(x) & ~(v))) #define HW_PDB_POEN_TOG(x, v) (HW_PDB_POEN_WR(x, HW_PDB_POEN_RD(x) ^ (v))) /*@}*/ /* * Constants & macros for individual PDB_POEN bitfields */ /*! * @name Register PDB_POEN, field POEN[7:0] (RW) * * Enables the pulse output. Only lower Y bits are implemented in this MCU. * * Values: * - 0 - PDB Pulse-Out disabled * - 1 - PDB Pulse-Out enabled */ /*@{*/ #define BP_PDB_POEN_POEN (0U) /*!< Bit position for PDB_POEN_POEN. */ #define BM_PDB_POEN_POEN (0x000000FFU) /*!< Bit mask for PDB_POEN_POEN. */ #define BS_PDB_POEN_POEN (8U) /*!< Bit field size in bits for PDB_POEN_POEN. */ /*! @brief Read current value of the PDB_POEN_POEN field. */ #define BR_PDB_POEN_POEN(x) (HW_PDB_POEN(x).B.POEN) /*! @brief Format value for bitfield PDB_POEN_POEN. */ #define BF_PDB_POEN_POEN(v) ((uint32_t)((uint32_t)(v) << BP_PDB_POEN_POEN) & BM_PDB_POEN_POEN) /*! @brief Set the POEN field to a new value. */ #define BW_PDB_POEN_POEN(x, v) (HW_PDB_POEN_WR(x, (HW_PDB_POEN_RD(x) & ~BM_PDB_POEN_POEN) | BF_PDB_POEN_POEN(v))) /*@}*/ /******************************************************************************* * HW_PDB_POnDLY - Pulse-Out n Delay register ******************************************************************************/ /*! * @brief HW_PDB_POnDLY - Pulse-Out n Delay register (RW) * * Reset value: 0x00000000U */ typedef union _hw_pdb_pondly { uint32_t U; struct _hw_pdb_pondly_bitfields { uint32_t DLY2 : 16; /*!< [15:0] PDB Pulse-Out Delay 2 */ uint32_t DLY1 : 16; /*!< [31:16] PDB Pulse-Out Delay 1 */ } B; } hw_pdb_pondly_t; /*! * @name Constants and macros for entire PDB_POnDLY register */ /*@{*/ #define HW_PDB_POnDLY_COUNT (3U) #define HW_PDB_POnDLY_ADDR(x, n) ((x) + 0x194U + (0x4U * (n))) #define HW_PDB_POnDLY(x, n) (*(__IO hw_pdb_pondly_t *) HW_PDB_POnDLY_ADDR(x, n)) #define HW_PDB_POnDLY_RD(x, n) (HW_PDB_POnDLY(x, n).U) #define HW_PDB_POnDLY_WR(x, n, v) (HW_PDB_POnDLY(x, n).U = (v)) #define HW_PDB_POnDLY_SET(x, n, v) (HW_PDB_POnDLY_WR(x, n, HW_PDB_POnDLY_RD(x, n) | (v))) #define HW_PDB_POnDLY_CLR(x, n, v) (HW_PDB_POnDLY_WR(x, n, HW_PDB_POnDLY_RD(x, n) & ~(v))) #define HW_PDB_POnDLY_TOG(x, n, v) (HW_PDB_POnDLY_WR(x, n, HW_PDB_POnDLY_RD(x, n) ^ (v))) /*@}*/ /* * Constants & macros for individual PDB_POnDLY bitfields */ /*! * @name Register PDB_POnDLY, field DLY2[15:0] (RW) * * These bits specify the delay 2 value for the PDB Pulse-Out. Pulse-Out goes * low when the PDB counter is equal to the DLY2. Reading these bits returns the * value of internal register that is effective for the current PDB cycle. */ /*@{*/ #define BP_PDB_POnDLY_DLY2 (0U) /*!< Bit position for PDB_POnDLY_DLY2. */ #define BM_PDB_POnDLY_DLY2 (0x0000FFFFU) /*!< Bit mask for PDB_POnDLY_DLY2. */ #define BS_PDB_POnDLY_DLY2 (16U) /*!< Bit field size in bits for PDB_POnDLY_DLY2. */ /*! @brief Read current value of the PDB_POnDLY_DLY2 field. */ #define BR_PDB_POnDLY_DLY2(x, n) (HW_PDB_POnDLY(x, n).B.DLY2) /*! @brief Format value for bitfield PDB_POnDLY_DLY2. */ #define BF_PDB_POnDLY_DLY2(v) ((uint32_t)((uint32_t)(v) << BP_PDB_POnDLY_DLY2) & BM_PDB_POnDLY_DLY2) /*! @brief Set the DLY2 field to a new value. */ #define BW_PDB_POnDLY_DLY2(x, n, v) (HW_PDB_POnDLY_WR(x, n, (HW_PDB_POnDLY_RD(x, n) & ~BM_PDB_POnDLY_DLY2) | BF_PDB_POnDLY_DLY2(v))) /*@}*/ /*! * @name Register PDB_POnDLY, field DLY1[31:16] (RW) * * These bits specify the delay 1 value for the PDB Pulse-Out. Pulse-Out goes * high when the PDB counter is equal to the DLY1. Reading these bits returns the * value of internal register that is effective for the current PDB cycle. */ /*@{*/ #define BP_PDB_POnDLY_DLY1 (16U) /*!< Bit position for PDB_POnDLY_DLY1. */ #define BM_PDB_POnDLY_DLY1 (0xFFFF0000U) /*!< Bit mask for PDB_POnDLY_DLY1. */ #define BS_PDB_POnDLY_DLY1 (16U) /*!< Bit field size in bits for PDB_POnDLY_DLY1. */ /*! @brief Read current value of the PDB_POnDLY_DLY1 field. */ #define BR_PDB_POnDLY_DLY1(x, n) (HW_PDB_POnDLY(x, n).B.DLY1) /*! @brief Format value for bitfield PDB_POnDLY_DLY1. */ #define BF_PDB_POnDLY_DLY1(v) ((uint32_t)((uint32_t)(v) << BP_PDB_POnDLY_DLY1) & BM_PDB_POnDLY_DLY1) /*! @brief Set the DLY1 field to a new value. */ #define BW_PDB_POnDLY_DLY1(x, n, v) (HW_PDB_POnDLY_WR(x, n, (HW_PDB_POnDLY_RD(x, n) & ~BM_PDB_POnDLY_DLY1) | BF_PDB_POnDLY_DLY1(v))) /*@}*/ /******************************************************************************* * hw_pdb_t - module struct ******************************************************************************/ /*! * @brief All PDB module registers. */ #pragma pack(1) typedef struct _hw_pdb { __IO hw_pdb_sc_t SC; /*!< [0x0] Status and Control register */ __IO hw_pdb_mod_t MOD; /*!< [0x4] Modulus register */ __I hw_pdb_cnt_t CNT; /*!< [0x8] Counter register */ __IO hw_pdb_idly_t IDLY; /*!< [0xC] Interrupt Delay register */ struct { __IO hw_pdb_chnc1_t CHnC1; /*!< [0x10] Channel n Control register 1 */ __IO hw_pdb_chns_t CHnS; /*!< [0x14] Channel n Status register */ __IO hw_pdb_chndly0_t CHnDLY0; /*!< [0x18] Channel n Delay 0 register */ __IO hw_pdb_chndly1_t CHnDLY1; /*!< [0x1C] Channel n Delay 1 register */ uint8_t _reserved0[24]; } CH[2]; uint8_t _reserved0[240]; struct { __IO hw_pdb_dacintcn_t DACINTCn; /*!< [0x150] DAC Interval Trigger n Control register */ __IO hw_pdb_dacintn_t DACINTn; /*!< [0x154] DAC Interval n register */ } DAC[2]; uint8_t _reserved1[48]; __IO hw_pdb_poen_t POEN; /*!< [0x190] Pulse-Out n Enable register */ __IO hw_pdb_pondly_t POnDLY[3]; /*!< [0x194] Pulse-Out n Delay register */ } hw_pdb_t; #pragma pack() /*! @brief Macro to access all PDB registers. */ /*! @param x PDB module instance base address. */ /*! @return Reference (not a pointer) to the registers struct. To get a pointer to the struct, * use the '&' operator, like &HW_PDB(PDB0_BASE). */ #define HW_PDB(x) (*(hw_pdb_t *)(x)) #endif /* __HW_PDB_REGISTERS_H__ */ /* EOF */ ================================================ FILE: Zelig/mbed/TARGET_K64F/TARGET_Freescale/TARGET_KPSDK_MCUS/TARGET_MCU_K64F/device/device/MK64F12/MK64F12_pit.h ================================================ /* ** ################################################################### ** Compilers: Keil ARM C/C++ Compiler ** Freescale C/C++ for Embedded ARM ** GNU C Compiler ** IAR ANSI C/C++ Compiler for ARM ** ** Reference manual: K64P144M120SF5RM, Rev.2, January 2014 ** Version: rev. 2.5, 2014-02-10 ** Build: b140604 ** ** Abstract: ** Extension to the CMSIS register access layer header. ** ** Copyright (c) 2014 Freescale Semiconductor, Inc. ** All rights reserved. ** ** Redistribution and use in source and binary forms, with or without modification, ** are permitted provided that the following conditions are met: ** ** o Redistributions of source code must retain the above copyright notice, this list ** of conditions and the following disclaimer. ** ** o Redistributions in binary form must reproduce the above copyright notice, this ** list of conditions and the following disclaimer in the documentation and/or ** other materials provided with the distribution. ** ** o Neither the name of Freescale Semiconductor, Inc. nor the names of its ** contributors may be used to endorse or promote products derived from this ** software without specific prior written permission. ** ** THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ** ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED ** WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE ** DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT 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. ** ** http: www.freescale.com ** mail: support@freescale.com ** ** Revisions: ** - rev. 1.0 (2013-08-12) ** Initial version. ** - rev. 2.0 (2013-10-29) ** Register accessor macros added to the memory map. ** Symbols for Processor Expert memory map compatibility added to the memory map. ** Startup file for gcc has been updated according to CMSIS 3.2. ** System initialization updated. ** MCG - registers updated. ** PORTA, PORTB, PORTC, PORTE - registers for digital filter removed. ** - rev. 2.1 (2013-10-30) ** Definition of BITBAND macros updated to support peripherals with 32-bit acces disabled. ** - rev. 2.2 (2013-12-09) ** DMA - EARS register removed. ** AIPS0, AIPS1 - MPRA register updated. ** - rev. 2.3 (2014-01-24) ** Update according to reference manual rev. 2 ** ENET, MCG, MCM, SIM, USB - registers updated ** - rev. 2.4 (2014-02-10) ** The declaration of clock configurations has been moved to separate header file system_MK64F12.h ** Update of SystemInit() and SystemCoreClockUpdate() functions. ** - rev. 2.5 (2014-02-10) ** The declaration of clock configurations has been moved to separate header file system_MK64F12.h ** Update of SystemInit() and SystemCoreClockUpdate() functions. ** Module access macro module_BASES replaced by module_BASE_PTRS. ** ** ################################################################### */ /* * WARNING! DO NOT EDIT THIS FILE DIRECTLY! * * This file was generated automatically and any changes may be lost. */ #ifndef __HW_PIT_REGISTERS_H__ #define __HW_PIT_REGISTERS_H__ #include "MK64F12.h" #include "fsl_bitaccess.h" /* * MK64F12 PIT * * Periodic Interrupt Timer * * Registers defined in this header file: * - HW_PIT_MCR - PIT Module Control Register * - HW_PIT_LDVALn - Timer Load Value Register * - HW_PIT_CVALn - Current Timer Value Register * - HW_PIT_TCTRLn - Timer Control Register * - HW_PIT_TFLGn - Timer Flag Register * * - hw_pit_t - Struct containing all module registers. */ #define HW_PIT_INSTANCE_COUNT (1U) /*!< Number of instances of the PIT module. */ /******************************************************************************* * HW_PIT_MCR - PIT Module Control Register ******************************************************************************/ /*! * @brief HW_PIT_MCR - PIT Module Control Register (RW) * * Reset value: 0x00000006U * * This register enables or disables the PIT timer clocks and controls the * timers when the PIT enters the Debug mode. */ typedef union _hw_pit_mcr { uint32_t U; struct _hw_pit_mcr_bitfields { uint32_t FRZ : 1; /*!< [0] Freeze */ uint32_t MDIS : 1; /*!< [1] Module Disable - (PIT section) */ uint32_t RESERVED0 : 30; /*!< [31:2] */ } B; } hw_pit_mcr_t; /*! * @name Constants and macros for entire PIT_MCR register */ /*@{*/ #define HW_PIT_MCR_ADDR(x) ((x) + 0x0U) #define HW_PIT_MCR(x) (*(__IO hw_pit_mcr_t *) HW_PIT_MCR_ADDR(x)) #define HW_PIT_MCR_RD(x) (HW_PIT_MCR(x).U) #define HW_PIT_MCR_WR(x, v) (HW_PIT_MCR(x).U = (v)) #define HW_PIT_MCR_SET(x, v) (HW_PIT_MCR_WR(x, HW_PIT_MCR_RD(x) | (v))) #define HW_PIT_MCR_CLR(x, v) (HW_PIT_MCR_WR(x, HW_PIT_MCR_RD(x) & ~(v))) #define HW_PIT_MCR_TOG(x, v) (HW_PIT_MCR_WR(x, HW_PIT_MCR_RD(x) ^ (v))) /*@}*/ /* * Constants & macros for individual PIT_MCR bitfields */ /*! * @name Register PIT_MCR, field FRZ[0] (RW) * * Allows the timers to be stopped when the device enters the Debug mode. * * Values: * - 0 - Timers continue to run in Debug mode. * - 1 - Timers are stopped in Debug mode. */ /*@{*/ #define BP_PIT_MCR_FRZ (0U) /*!< Bit position for PIT_MCR_FRZ. */ #define BM_PIT_MCR_FRZ (0x00000001U) /*!< Bit mask for PIT_MCR_FRZ. */ #define BS_PIT_MCR_FRZ (1U) /*!< Bit field size in bits for PIT_MCR_FRZ. */ /*! @brief Read current value of the PIT_MCR_FRZ field. */ #define BR_PIT_MCR_FRZ(x) (BITBAND_ACCESS32(HW_PIT_MCR_ADDR(x), BP_PIT_MCR_FRZ)) /*! @brief Format value for bitfield PIT_MCR_FRZ. */ #define BF_PIT_MCR_FRZ(v) ((uint32_t)((uint32_t)(v) << BP_PIT_MCR_FRZ) & BM_PIT_MCR_FRZ) /*! @brief Set the FRZ field to a new value. */ #define BW_PIT_MCR_FRZ(x, v) (BITBAND_ACCESS32(HW_PIT_MCR_ADDR(x), BP_PIT_MCR_FRZ) = (v)) /*@}*/ /*! * @name Register PIT_MCR, field MDIS[1] (RW) * * Disables the standard timers. This field must be enabled before any other * setup is done. * * Values: * - 0 - Clock for standard PIT timers is enabled. * - 1 - Clock for standard PIT timers is disabled. */ /*@{*/ #define BP_PIT_MCR_MDIS (1U) /*!< Bit position for PIT_MCR_MDIS. */ #define BM_PIT_MCR_MDIS (0x00000002U) /*!< Bit mask for PIT_MCR_MDIS. */ #define BS_PIT_MCR_MDIS (1U) /*!< Bit field size in bits for PIT_MCR_MDIS. */ /*! @brief Read current value of the PIT_MCR_MDIS field. */ #define BR_PIT_MCR_MDIS(x) (BITBAND_ACCESS32(HW_PIT_MCR_ADDR(x), BP_PIT_MCR_MDIS)) /*! @brief Format value for bitfield PIT_MCR_MDIS. */ #define BF_PIT_MCR_MDIS(v) ((uint32_t)((uint32_t)(v) << BP_PIT_MCR_MDIS) & BM_PIT_MCR_MDIS) /*! @brief Set the MDIS field to a new value. */ #define BW_PIT_MCR_MDIS(x, v) (BITBAND_ACCESS32(HW_PIT_MCR_ADDR(x), BP_PIT_MCR_MDIS) = (v)) /*@}*/ /******************************************************************************* * HW_PIT_LDVALn - Timer Load Value Register ******************************************************************************/ /*! * @brief HW_PIT_LDVALn - Timer Load Value Register (RW) * * Reset value: 0x00000000U * * These registers select the timeout period for the timer interrupts. */ typedef union _hw_pit_ldvaln { uint32_t U; struct _hw_pit_ldvaln_bitfields { uint32_t TSV : 32; /*!< [31:0] Timer Start Value */ } B; } hw_pit_ldvaln_t; /*! * @name Constants and macros for entire PIT_LDVALn register */ /*@{*/ #define HW_PIT_LDVALn_COUNT (4U) #define HW_PIT_LDVALn_ADDR(x, n) ((x) + 0x100U + (0x10U * (n))) #define HW_PIT_LDVALn(x, n) (*(__IO hw_pit_ldvaln_t *) HW_PIT_LDVALn_ADDR(x, n)) #define HW_PIT_LDVALn_RD(x, n) (HW_PIT_LDVALn(x, n).U) #define HW_PIT_LDVALn_WR(x, n, v) (HW_PIT_LDVALn(x, n).U = (v)) #define HW_PIT_LDVALn_SET(x, n, v) (HW_PIT_LDVALn_WR(x, n, HW_PIT_LDVALn_RD(x, n) | (v))) #define HW_PIT_LDVALn_CLR(x, n, v) (HW_PIT_LDVALn_WR(x, n, HW_PIT_LDVALn_RD(x, n) & ~(v))) #define HW_PIT_LDVALn_TOG(x, n, v) (HW_PIT_LDVALn_WR(x, n, HW_PIT_LDVALn_RD(x, n) ^ (v))) /*@}*/ /* * Constants & macros for individual PIT_LDVALn bitfields */ /*! * @name Register PIT_LDVALn, field TSV[31:0] (RW) * * Sets the timer start value. The timer will count down until it reaches 0, * then it will generate an interrupt and load this register value again. Writing a * new value to this register will not restart the timer; instead the value will * be loaded after the timer expires. To abort the current cycle and start a * timer period with the new value, the timer must be disabled and enabled again. */ /*@{*/ #define BP_PIT_LDVALn_TSV (0U) /*!< Bit position for PIT_LDVALn_TSV. */ #define BM_PIT_LDVALn_TSV (0xFFFFFFFFU) /*!< Bit mask for PIT_LDVALn_TSV. */ #define BS_PIT_LDVALn_TSV (32U) /*!< Bit field size in bits for PIT_LDVALn_TSV. */ /*! @brief Read current value of the PIT_LDVALn_TSV field. */ #define BR_PIT_LDVALn_TSV(x, n) (HW_PIT_LDVALn(x, n).U) /*! @brief Format value for bitfield PIT_LDVALn_TSV. */ #define BF_PIT_LDVALn_TSV(v) ((uint32_t)((uint32_t)(v) << BP_PIT_LDVALn_TSV) & BM_PIT_LDVALn_TSV) /*! @brief Set the TSV field to a new value. */ #define BW_PIT_LDVALn_TSV(x, n, v) (HW_PIT_LDVALn_WR(x, n, v)) /*@}*/ /******************************************************************************* * HW_PIT_CVALn - Current Timer Value Register ******************************************************************************/ /*! * @brief HW_PIT_CVALn - Current Timer Value Register (RO) * * Reset value: 0x00000000U * * These registers indicate the current timer position. */ typedef union _hw_pit_cvaln { uint32_t U; struct _hw_pit_cvaln_bitfields { uint32_t TVL : 32; /*!< [31:0] Current Timer Value */ } B; } hw_pit_cvaln_t; /*! * @name Constants and macros for entire PIT_CVALn register */ /*@{*/ #define HW_PIT_CVALn_COUNT (4U) #define HW_PIT_CVALn_ADDR(x, n) ((x) + 0x104U + (0x10U * (n))) #define HW_PIT_CVALn(x, n) (*(__I hw_pit_cvaln_t *) HW_PIT_CVALn_ADDR(x, n)) #define HW_PIT_CVALn_RD(x, n) (HW_PIT_CVALn(x, n).U) /*@}*/ /* * Constants & macros for individual PIT_CVALn bitfields */ /*! * @name Register PIT_CVALn, field TVL[31:0] (RO) * * Represents the current timer value, if the timer is enabled. If the timer is * disabled, do not use this field as its value is unreliable. The timer uses a * downcounter. The timer values are frozen in Debug mode if MCR[FRZ] is set. */ /*@{*/ #define BP_PIT_CVALn_TVL (0U) /*!< Bit position for PIT_CVALn_TVL. */ #define BM_PIT_CVALn_TVL (0xFFFFFFFFU) /*!< Bit mask for PIT_CVALn_TVL. */ #define BS_PIT_CVALn_TVL (32U) /*!< Bit field size in bits for PIT_CVALn_TVL. */ /*! @brief Read current value of the PIT_CVALn_TVL field. */ #define BR_PIT_CVALn_TVL(x, n) (HW_PIT_CVALn(x, n).U) /*@}*/ /******************************************************************************* * HW_PIT_TCTRLn - Timer Control Register ******************************************************************************/ /*! * @brief HW_PIT_TCTRLn - Timer Control Register (RW) * * Reset value: 0x00000000U * * These registers contain the control bits for each timer. */ typedef union _hw_pit_tctrln { uint32_t U; struct _hw_pit_tctrln_bitfields { uint32_t TEN : 1; /*!< [0] Timer Enable */ uint32_t TIE : 1; /*!< [1] Timer Interrupt Enable */ uint32_t CHN : 1; /*!< [2] Chain Mode */ uint32_t RESERVED0 : 29; /*!< [31:3] */ } B; } hw_pit_tctrln_t; /*! * @name Constants and macros for entire PIT_TCTRLn register */ /*@{*/ #define HW_PIT_TCTRLn_COUNT (4U) #define HW_PIT_TCTRLn_ADDR(x, n) ((x) + 0x108U + (0x10U * (n))) #define HW_PIT_TCTRLn(x, n) (*(__IO hw_pit_tctrln_t *) HW_PIT_TCTRLn_ADDR(x, n)) #define HW_PIT_TCTRLn_RD(x, n) (HW_PIT_TCTRLn(x, n).U) #define HW_PIT_TCTRLn_WR(x, n, v) (HW_PIT_TCTRLn(x, n).U = (v)) #define HW_PIT_TCTRLn_SET(x, n, v) (HW_PIT_TCTRLn_WR(x, n, HW_PIT_TCTRLn_RD(x, n) | (v))) #define HW_PIT_TCTRLn_CLR(x, n, v) (HW_PIT_TCTRLn_WR(x, n, HW_PIT_TCTRLn_RD(x, n) & ~(v))) #define HW_PIT_TCTRLn_TOG(x, n, v) (HW_PIT_TCTRLn_WR(x, n, HW_PIT_TCTRLn_RD(x, n) ^ (v))) /*@}*/ /* * Constants & macros for individual PIT_TCTRLn bitfields */ /*! * @name Register PIT_TCTRLn, field TEN[0] (RW) * * Enables or disables the timer. * * Values: * - 0 - Timer n is disabled. * - 1 - Timer n is enabled. */ /*@{*/ #define BP_PIT_TCTRLn_TEN (0U) /*!< Bit position for PIT_TCTRLn_TEN. */ #define BM_PIT_TCTRLn_TEN (0x00000001U) /*!< Bit mask for PIT_TCTRLn_TEN. */ #define BS_PIT_TCTRLn_TEN (1U) /*!< Bit field size in bits for PIT_TCTRLn_TEN. */ /*! @brief Read current value of the PIT_TCTRLn_TEN field. */ #define BR_PIT_TCTRLn_TEN(x, n) (BITBAND_ACCESS32(HW_PIT_TCTRLn_ADDR(x, n), BP_PIT_TCTRLn_TEN)) /*! @brief Format value for bitfield PIT_TCTRLn_TEN. */ #define BF_PIT_TCTRLn_TEN(v) ((uint32_t)((uint32_t)(v) << BP_PIT_TCTRLn_TEN) & BM_PIT_TCTRLn_TEN) /*! @brief Set the TEN field to a new value. */ #define BW_PIT_TCTRLn_TEN(x, n, v) (BITBAND_ACCESS32(HW_PIT_TCTRLn_ADDR(x, n), BP_PIT_TCTRLn_TEN) = (v)) /*@}*/ /*! * @name Register PIT_TCTRLn, field TIE[1] (RW) * * When an interrupt is pending, or, TFLGn[TIF] is set, enabling the interrupt * will immediately cause an interrupt event. To avoid this, the associated * TFLGn[TIF] must be cleared first. * * Values: * - 0 - Interrupt requests from Timer n are disabled. * - 1 - Interrupt will be requested whenever TIF is set. */ /*@{*/ #define BP_PIT_TCTRLn_TIE (1U) /*!< Bit position for PIT_TCTRLn_TIE. */ #define BM_PIT_TCTRLn_TIE (0x00000002U) /*!< Bit mask for PIT_TCTRLn_TIE. */ #define BS_PIT_TCTRLn_TIE (1U) /*!< Bit field size in bits for PIT_TCTRLn_TIE. */ /*! @brief Read current value of the PIT_TCTRLn_TIE field. */ #define BR_PIT_TCTRLn_TIE(x, n) (BITBAND_ACCESS32(HW_PIT_TCTRLn_ADDR(x, n), BP_PIT_TCTRLn_TIE)) /*! @brief Format value for bitfield PIT_TCTRLn_TIE. */ #define BF_PIT_TCTRLn_TIE(v) ((uint32_t)((uint32_t)(v) << BP_PIT_TCTRLn_TIE) & BM_PIT_TCTRLn_TIE) /*! @brief Set the TIE field to a new value. */ #define BW_PIT_TCTRLn_TIE(x, n, v) (BITBAND_ACCESS32(HW_PIT_TCTRLn_ADDR(x, n), BP_PIT_TCTRLn_TIE) = (v)) /*@}*/ /*! * @name Register PIT_TCTRLn, field CHN[2] (RW) * * When activated, Timer n-1 needs to expire before timer n can decrement by 1. * Timer 0 cannot be chained. * * Values: * - 0 - Timer is not chained. * - 1 - Timer is chained to previous timer. For example, for Channel 2, if this * field is set, Timer 2 is chained to Timer 1. */ /*@{*/ #define BP_PIT_TCTRLn_CHN (2U) /*!< Bit position for PIT_TCTRLn_CHN. */ #define BM_PIT_TCTRLn_CHN (0x00000004U) /*!< Bit mask for PIT_TCTRLn_CHN. */ #define BS_PIT_TCTRLn_CHN (1U) /*!< Bit field size in bits for PIT_TCTRLn_CHN. */ /*! @brief Read current value of the PIT_TCTRLn_CHN field. */ #define BR_PIT_TCTRLn_CHN(x, n) (BITBAND_ACCESS32(HW_PIT_TCTRLn_ADDR(x, n), BP_PIT_TCTRLn_CHN)) /*! @brief Format value for bitfield PIT_TCTRLn_CHN. */ #define BF_PIT_TCTRLn_CHN(v) ((uint32_t)((uint32_t)(v) << BP_PIT_TCTRLn_CHN) & BM_PIT_TCTRLn_CHN) /*! @brief Set the CHN field to a new value. */ #define BW_PIT_TCTRLn_CHN(x, n, v) (BITBAND_ACCESS32(HW_PIT_TCTRLn_ADDR(x, n), BP_PIT_TCTRLn_CHN) = (v)) /*@}*/ /******************************************************************************* * HW_PIT_TFLGn - Timer Flag Register ******************************************************************************/ /*! * @brief HW_PIT_TFLGn - Timer Flag Register (RW) * * Reset value: 0x00000000U * * These registers hold the PIT interrupt flags. */ typedef union _hw_pit_tflgn { uint32_t U; struct _hw_pit_tflgn_bitfields { uint32_t TIF : 1; /*!< [0] Timer Interrupt Flag */ uint32_t RESERVED0 : 31; /*!< [31:1] */ } B; } hw_pit_tflgn_t; /*! * @name Constants and macros for entire PIT_TFLGn register */ /*@{*/ #define HW_PIT_TFLGn_COUNT (4U) #define HW_PIT_TFLGn_ADDR(x, n) ((x) + 0x10CU + (0x10U * (n))) #define HW_PIT_TFLGn(x, n) (*(__IO hw_pit_tflgn_t *) HW_PIT_TFLGn_ADDR(x, n)) #define HW_PIT_TFLGn_RD(x, n) (HW_PIT_TFLGn(x, n).U) #define HW_PIT_TFLGn_WR(x, n, v) (HW_PIT_TFLGn(x, n).U = (v)) #define HW_PIT_TFLGn_SET(x, n, v) (HW_PIT_TFLGn_WR(x, n, HW_PIT_TFLGn_RD(x, n) | (v))) #define HW_PIT_TFLGn_CLR(x, n, v) (HW_PIT_TFLGn_WR(x, n, HW_PIT_TFLGn_RD(x, n) & ~(v))) #define HW_PIT_TFLGn_TOG(x, n, v) (HW_PIT_TFLGn_WR(x, n, HW_PIT_TFLGn_RD(x, n) ^ (v))) /*@}*/ /* * Constants & macros for individual PIT_TFLGn bitfields */ /*! * @name Register PIT_TFLGn, field TIF[0] (W1C) * * Sets to 1 at the end of the timer period. Writing 1 to this flag clears it. * Writing 0 has no effect. If enabled, or, when TCTRLn[TIE] = 1, TIF causes an * interrupt request. * * Values: * - 0 - Timeout has not yet occurred. * - 1 - Timeout has occurred. */ /*@{*/ #define BP_PIT_TFLGn_TIF (0U) /*!< Bit position for PIT_TFLGn_TIF. */ #define BM_PIT_TFLGn_TIF (0x00000001U) /*!< Bit mask for PIT_TFLGn_TIF. */ #define BS_PIT_TFLGn_TIF (1U) /*!< Bit field size in bits for PIT_TFLGn_TIF. */ /*! @brief Read current value of the PIT_TFLGn_TIF field. */ #define BR_PIT_TFLGn_TIF(x, n) (BITBAND_ACCESS32(HW_PIT_TFLGn_ADDR(x, n), BP_PIT_TFLGn_TIF)) /*! @brief Format value for bitfield PIT_TFLGn_TIF. */ #define BF_PIT_TFLGn_TIF(v) ((uint32_t)((uint32_t)(v) << BP_PIT_TFLGn_TIF) & BM_PIT_TFLGn_TIF) /*! @brief Set the TIF field to a new value. */ #define BW_PIT_TFLGn_TIF(x, n, v) (BITBAND_ACCESS32(HW_PIT_TFLGn_ADDR(x, n), BP_PIT_TFLGn_TIF) = (v)) /*@}*/ /******************************************************************************* * hw_pit_t - module struct ******************************************************************************/ /*! * @brief All PIT module registers. */ #pragma pack(1) typedef struct _hw_pit { __IO hw_pit_mcr_t MCR; /*!< [0x0] PIT Module Control Register */ uint8_t _reserved0[252]; struct { __IO hw_pit_ldvaln_t LDVALn; /*!< [0x100] Timer Load Value Register */ __I hw_pit_cvaln_t CVALn; /*!< [0x104] Current Timer Value Register */ __IO hw_pit_tctrln_t TCTRLn; /*!< [0x108] Timer Control Register */ __IO hw_pit_tflgn_t TFLGn; /*!< [0x10C] Timer Flag Register */ } CHANNEL[4]; } hw_pit_t; #pragma pack() /*! @brief Macro to access all PIT registers. */ /*! @param x PIT module instance base address. */ /*! @return Reference (not a pointer) to the registers struct. To get a pointer to the struct, * use the '&' operator, like &HW_PIT(PIT_BASE). */ #define HW_PIT(x) (*(hw_pit_t *)(x)) #endif /* __HW_PIT_REGISTERS_H__ */ /* EOF */ ================================================ FILE: Zelig/mbed/TARGET_K64F/TARGET_Freescale/TARGET_KPSDK_MCUS/TARGET_MCU_K64F/device/device/MK64F12/MK64F12_pmc.h ================================================ /* ** ################################################################### ** Compilers: Keil ARM C/C++ Compiler ** Freescale C/C++ for Embedded ARM ** GNU C Compiler ** IAR ANSI C/C++ Compiler for ARM ** ** Reference manual: K64P144M120SF5RM, Rev.2, January 2014 ** Version: rev. 2.5, 2014-02-10 ** Build: b140604 ** ** Abstract: ** Extension to the CMSIS register access layer header. ** ** Copyright (c) 2014 Freescale Semiconductor, Inc. ** All rights reserved. ** ** Redistribution and use in source and binary forms, with or without modification, ** are permitted provided that the following conditions are met: ** ** o Redistributions of source code must retain the above copyright notice, this list ** of conditions and the following disclaimer. ** ** o Redistributions in binary form must reproduce the above copyright notice, this ** list of conditions and the following disclaimer in the documentation and/or ** other materials provided with the distribution. ** ** o Neither the name of Freescale Semiconductor, Inc. nor the names of its ** contributors may be used to endorse or promote products derived from this ** software without specific prior written permission. ** ** THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ** ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED ** WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE ** DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT 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. ** ** http: www.freescale.com ** mail: support@freescale.com ** ** Revisions: ** - rev. 1.0 (2013-08-12) ** Initial version. ** - rev. 2.0 (2013-10-29) ** Register accessor macros added to the memory map. ** Symbols for Processor Expert memory map compatibility added to the memory map. ** Startup file for gcc has been updated according to CMSIS 3.2. ** System initialization updated. ** MCG - registers updated. ** PORTA, PORTB, PORTC, PORTE - registers for digital filter removed. ** - rev. 2.1 (2013-10-30) ** Definition of BITBAND macros updated to support peripherals with 32-bit acces disabled. ** - rev. 2.2 (2013-12-09) ** DMA - EARS register removed. ** AIPS0, AIPS1 - MPRA register updated. ** - rev. 2.3 (2014-01-24) ** Update according to reference manual rev. 2 ** ENET, MCG, MCM, SIM, USB - registers updated ** - rev. 2.4 (2014-02-10) ** The declaration of clock configurations has been moved to separate header file system_MK64F12.h ** Update of SystemInit() and SystemCoreClockUpdate() functions. ** - rev. 2.5 (2014-02-10) ** The declaration of clock configurations has been moved to separate header file system_MK64F12.h ** Update of SystemInit() and SystemCoreClockUpdate() functions. ** Module access macro module_BASES replaced by module_BASE_PTRS. ** ** ################################################################### */ /* * WARNING! DO NOT EDIT THIS FILE DIRECTLY! * * This file was generated automatically and any changes may be lost. */ #ifndef __HW_PMC_REGISTERS_H__ #define __HW_PMC_REGISTERS_H__ #include "MK64F12.h" #include "fsl_bitaccess.h" /* * MK64F12 PMC * * Power Management Controller * * Registers defined in this header file: * - HW_PMC_LVDSC1 - Low Voltage Detect Status And Control 1 register * - HW_PMC_LVDSC2 - Low Voltage Detect Status And Control 2 register * - HW_PMC_REGSC - Regulator Status And Control register * * - hw_pmc_t - Struct containing all module registers. */ #define HW_PMC_INSTANCE_COUNT (1U) /*!< Number of instances of the PMC module. */ /******************************************************************************* * HW_PMC_LVDSC1 - Low Voltage Detect Status And Control 1 register ******************************************************************************/ /*! * @brief HW_PMC_LVDSC1 - Low Voltage Detect Status And Control 1 register (RW) * * Reset value: 0x10U * * This register contains status and control bits to support the low voltage * detect function. This register should be written during the reset initialization * program to set the desired controls even if the desired settings are the same * as the reset settings. While the device is in the very low power or low * leakage modes, the LVD system is disabled regardless of LVDSC1 settings. To protect * systems that must have LVD always on, configure the Power Mode Protection * (PMPROT) register of the SMC module (SMC_PMPROT) to disallow any very low power or * low leakage modes from being enabled. See the device's data sheet for the * exact LVD trip voltages. The LVDV bits are reset solely on a POR Only event. The * register's other bits are reset on Chip Reset Not VLLS. For more information * about these reset types, refer to the Reset section details. */ typedef union _hw_pmc_lvdsc1 { uint8_t U; struct _hw_pmc_lvdsc1_bitfields { uint8_t LVDV : 2; /*!< [1:0] Low-Voltage Detect Voltage Select */ uint8_t RESERVED0 : 2; /*!< [3:2] */ uint8_t LVDRE : 1; /*!< [4] Low-Voltage Detect Reset Enable */ uint8_t LVDIE : 1; /*!< [5] Low-Voltage Detect Interrupt Enable */ uint8_t LVDACK : 1; /*!< [6] Low-Voltage Detect Acknowledge */ uint8_t LVDF : 1; /*!< [7] Low-Voltage Detect Flag */ } B; } hw_pmc_lvdsc1_t; /*! * @name Constants and macros for entire PMC_LVDSC1 register */ /*@{*/ #define HW_PMC_LVDSC1_ADDR(x) ((x) + 0x0U) #define HW_PMC_LVDSC1(x) (*(__IO hw_pmc_lvdsc1_t *) HW_PMC_LVDSC1_ADDR(x)) #define HW_PMC_LVDSC1_RD(x) (HW_PMC_LVDSC1(x).U) #define HW_PMC_LVDSC1_WR(x, v) (HW_PMC_LVDSC1(x).U = (v)) #define HW_PMC_LVDSC1_SET(x, v) (HW_PMC_LVDSC1_WR(x, HW_PMC_LVDSC1_RD(x) | (v))) #define HW_PMC_LVDSC1_CLR(x, v) (HW_PMC_LVDSC1_WR(x, HW_PMC_LVDSC1_RD(x) & ~(v))) #define HW_PMC_LVDSC1_TOG(x, v) (HW_PMC_LVDSC1_WR(x, HW_PMC_LVDSC1_RD(x) ^ (v))) /*@}*/ /* * Constants & macros for individual PMC_LVDSC1 bitfields */ /*! * @name Register PMC_LVDSC1, field LVDV[1:0] (RW) * * Selects the LVD trip point voltage (V LVD ). * * Values: * - 00 - Low trip point selected (V LVD = V LVDL ) * - 01 - High trip point selected (V LVD = V LVDH ) * - 10 - Reserved * - 11 - Reserved */ /*@{*/ #define BP_PMC_LVDSC1_LVDV (0U) /*!< Bit position for PMC_LVDSC1_LVDV. */ #define BM_PMC_LVDSC1_LVDV (0x03U) /*!< Bit mask for PMC_LVDSC1_LVDV. */ #define BS_PMC_LVDSC1_LVDV (2U) /*!< Bit field size in bits for PMC_LVDSC1_LVDV. */ /*! @brief Read current value of the PMC_LVDSC1_LVDV field. */ #define BR_PMC_LVDSC1_LVDV(x) (HW_PMC_LVDSC1(x).B.LVDV) /*! @brief Format value for bitfield PMC_LVDSC1_LVDV. */ #define BF_PMC_LVDSC1_LVDV(v) ((uint8_t)((uint8_t)(v) << BP_PMC_LVDSC1_LVDV) & BM_PMC_LVDSC1_LVDV) /*! @brief Set the LVDV field to a new value. */ #define BW_PMC_LVDSC1_LVDV(x, v) (HW_PMC_LVDSC1_WR(x, (HW_PMC_LVDSC1_RD(x) & ~BM_PMC_LVDSC1_LVDV) | BF_PMC_LVDSC1_LVDV(v))) /*@}*/ /*! * @name Register PMC_LVDSC1, field LVDRE[4] (RW) * * This write-once bit enables LVDF events to generate a hardware reset. * Additional writes are ignored. * * Values: * - 0 - LVDF does not generate hardware resets * - 1 - Force an MCU reset when LVDF = 1 */ /*@{*/ #define BP_PMC_LVDSC1_LVDRE (4U) /*!< Bit position for PMC_LVDSC1_LVDRE. */ #define BM_PMC_LVDSC1_LVDRE (0x10U) /*!< Bit mask for PMC_LVDSC1_LVDRE. */ #define BS_PMC_LVDSC1_LVDRE (1U) /*!< Bit field size in bits for PMC_LVDSC1_LVDRE. */ /*! @brief Read current value of the PMC_LVDSC1_LVDRE field. */ #define BR_PMC_LVDSC1_LVDRE(x) (BITBAND_ACCESS8(HW_PMC_LVDSC1_ADDR(x), BP_PMC_LVDSC1_LVDRE)) /*! @brief Format value for bitfield PMC_LVDSC1_LVDRE. */ #define BF_PMC_LVDSC1_LVDRE(v) ((uint8_t)((uint8_t)(v) << BP_PMC_LVDSC1_LVDRE) & BM_PMC_LVDSC1_LVDRE) /*! @brief Set the LVDRE field to a new value. */ #define BW_PMC_LVDSC1_LVDRE(x, v) (BITBAND_ACCESS8(HW_PMC_LVDSC1_ADDR(x), BP_PMC_LVDSC1_LVDRE) = (v)) /*@}*/ /*! * @name Register PMC_LVDSC1, field LVDIE[5] (RW) * * Enables hardware interrupt requests for LVDF. * * Values: * - 0 - Hardware interrupt disabled (use polling) * - 1 - Request a hardware interrupt when LVDF = 1 */ /*@{*/ #define BP_PMC_LVDSC1_LVDIE (5U) /*!< Bit position for PMC_LVDSC1_LVDIE. */ #define BM_PMC_LVDSC1_LVDIE (0x20U) /*!< Bit mask for PMC_LVDSC1_LVDIE. */ #define BS_PMC_LVDSC1_LVDIE (1U) /*!< Bit field size in bits for PMC_LVDSC1_LVDIE. */ /*! @brief Read current value of the PMC_LVDSC1_LVDIE field. */ #define BR_PMC_LVDSC1_LVDIE(x) (BITBAND_ACCESS8(HW_PMC_LVDSC1_ADDR(x), BP_PMC_LVDSC1_LVDIE)) /*! @brief Format value for bitfield PMC_LVDSC1_LVDIE. */ #define BF_PMC_LVDSC1_LVDIE(v) ((uint8_t)((uint8_t)(v) << BP_PMC_LVDSC1_LVDIE) & BM_PMC_LVDSC1_LVDIE) /*! @brief Set the LVDIE field to a new value. */ #define BW_PMC_LVDSC1_LVDIE(x, v) (BITBAND_ACCESS8(HW_PMC_LVDSC1_ADDR(x), BP_PMC_LVDSC1_LVDIE) = (v)) /*@}*/ /*! * @name Register PMC_LVDSC1, field LVDACK[6] (WORZ) * * This write-only field is used to acknowledge low voltage detection errors. * Write 1 to clear LVDF. Reads always return 0. */ /*@{*/ #define BP_PMC_LVDSC1_LVDACK (6U) /*!< Bit position for PMC_LVDSC1_LVDACK. */ #define BM_PMC_LVDSC1_LVDACK (0x40U) /*!< Bit mask for PMC_LVDSC1_LVDACK. */ #define BS_PMC_LVDSC1_LVDACK (1U) /*!< Bit field size in bits for PMC_LVDSC1_LVDACK. */ /*! @brief Format value for bitfield PMC_LVDSC1_LVDACK. */ #define BF_PMC_LVDSC1_LVDACK(v) ((uint8_t)((uint8_t)(v) << BP_PMC_LVDSC1_LVDACK) & BM_PMC_LVDSC1_LVDACK) /*! @brief Set the LVDACK field to a new value. */ #define BW_PMC_LVDSC1_LVDACK(x, v) (BITBAND_ACCESS8(HW_PMC_LVDSC1_ADDR(x), BP_PMC_LVDSC1_LVDACK) = (v)) /*@}*/ /*! * @name Register PMC_LVDSC1, field LVDF[7] (RO) * * This read-only status field indicates a low-voltage detect event. * * Values: * - 0 - Low-voltage event not detected * - 1 - Low-voltage event detected */ /*@{*/ #define BP_PMC_LVDSC1_LVDF (7U) /*!< Bit position for PMC_LVDSC1_LVDF. */ #define BM_PMC_LVDSC1_LVDF (0x80U) /*!< Bit mask for PMC_LVDSC1_LVDF. */ #define BS_PMC_LVDSC1_LVDF (1U) /*!< Bit field size in bits for PMC_LVDSC1_LVDF. */ /*! @brief Read current value of the PMC_LVDSC1_LVDF field. */ #define BR_PMC_LVDSC1_LVDF(x) (BITBAND_ACCESS8(HW_PMC_LVDSC1_ADDR(x), BP_PMC_LVDSC1_LVDF)) /*@}*/ /******************************************************************************* * HW_PMC_LVDSC2 - Low Voltage Detect Status And Control 2 register ******************************************************************************/ /*! * @brief HW_PMC_LVDSC2 - Low Voltage Detect Status And Control 2 register (RW) * * Reset value: 0x00U * * This register contains status and control bits to support the low voltage * warning function. While the device is in the very low power or low leakage modes, * the LVD system is disabled regardless of LVDSC2 settings. See the device's * data sheet for the exact LVD trip voltages. The LVW trip voltages depend on LVWV * and LVDV. LVWV is reset solely on a POR Only event. The other fields of the * register are reset on Chip Reset Not VLLS. For more information about these * reset types, refer to the Reset section details. */ typedef union _hw_pmc_lvdsc2 { uint8_t U; struct _hw_pmc_lvdsc2_bitfields { uint8_t LVWV : 2; /*!< [1:0] Low-Voltage Warning Voltage Select */ uint8_t RESERVED0 : 3; /*!< [4:2] */ uint8_t LVWIE : 1; /*!< [5] Low-Voltage Warning Interrupt Enable */ uint8_t LVWACK : 1; /*!< [6] Low-Voltage Warning Acknowledge */ uint8_t LVWF : 1; /*!< [7] Low-Voltage Warning Flag */ } B; } hw_pmc_lvdsc2_t; /*! * @name Constants and macros for entire PMC_LVDSC2 register */ /*@{*/ #define HW_PMC_LVDSC2_ADDR(x) ((x) + 0x1U) #define HW_PMC_LVDSC2(x) (*(__IO hw_pmc_lvdsc2_t *) HW_PMC_LVDSC2_ADDR(x)) #define HW_PMC_LVDSC2_RD(x) (HW_PMC_LVDSC2(x).U) #define HW_PMC_LVDSC2_WR(x, v) (HW_PMC_LVDSC2(x).U = (v)) #define HW_PMC_LVDSC2_SET(x, v) (HW_PMC_LVDSC2_WR(x, HW_PMC_LVDSC2_RD(x) | (v))) #define HW_PMC_LVDSC2_CLR(x, v) (HW_PMC_LVDSC2_WR(x, HW_PMC_LVDSC2_RD(x) & ~(v))) #define HW_PMC_LVDSC2_TOG(x, v) (HW_PMC_LVDSC2_WR(x, HW_PMC_LVDSC2_RD(x) ^ (v))) /*@}*/ /* * Constants & macros for individual PMC_LVDSC2 bitfields */ /*! * @name Register PMC_LVDSC2, field LVWV[1:0] (RW) * * Selects the LVW trip point voltage (VLVW). The actual voltage for the warning * depends on LVDSC1[LVDV]. * * Values: * - 00 - Low trip point selected (VLVW = VLVW1) * - 01 - Mid 1 trip point selected (VLVW = VLVW2) * - 10 - Mid 2 trip point selected (VLVW = VLVW3) * - 11 - High trip point selected (VLVW = VLVW4) */ /*@{*/ #define BP_PMC_LVDSC2_LVWV (0U) /*!< Bit position for PMC_LVDSC2_LVWV. */ #define BM_PMC_LVDSC2_LVWV (0x03U) /*!< Bit mask for PMC_LVDSC2_LVWV. */ #define BS_PMC_LVDSC2_LVWV (2U) /*!< Bit field size in bits for PMC_LVDSC2_LVWV. */ /*! @brief Read current value of the PMC_LVDSC2_LVWV field. */ #define BR_PMC_LVDSC2_LVWV(x) (HW_PMC_LVDSC2(x).B.LVWV) /*! @brief Format value for bitfield PMC_LVDSC2_LVWV. */ #define BF_PMC_LVDSC2_LVWV(v) ((uint8_t)((uint8_t)(v) << BP_PMC_LVDSC2_LVWV) & BM_PMC_LVDSC2_LVWV) /*! @brief Set the LVWV field to a new value. */ #define BW_PMC_LVDSC2_LVWV(x, v) (HW_PMC_LVDSC2_WR(x, (HW_PMC_LVDSC2_RD(x) & ~BM_PMC_LVDSC2_LVWV) | BF_PMC_LVDSC2_LVWV(v))) /*@}*/ /*! * @name Register PMC_LVDSC2, field LVWIE[5] (RW) * * Enables hardware interrupt requests for LVWF. * * Values: * - 0 - Hardware interrupt disabled (use polling) * - 1 - Request a hardware interrupt when LVWF = 1 */ /*@{*/ #define BP_PMC_LVDSC2_LVWIE (5U) /*!< Bit position for PMC_LVDSC2_LVWIE. */ #define BM_PMC_LVDSC2_LVWIE (0x20U) /*!< Bit mask for PMC_LVDSC2_LVWIE. */ #define BS_PMC_LVDSC2_LVWIE (1U) /*!< Bit field size in bits for PMC_LVDSC2_LVWIE. */ /*! @brief Read current value of the PMC_LVDSC2_LVWIE field. */ #define BR_PMC_LVDSC2_LVWIE(x) (BITBAND_ACCESS8(HW_PMC_LVDSC2_ADDR(x), BP_PMC_LVDSC2_LVWIE)) /*! @brief Format value for bitfield PMC_LVDSC2_LVWIE. */ #define BF_PMC_LVDSC2_LVWIE(v) ((uint8_t)((uint8_t)(v) << BP_PMC_LVDSC2_LVWIE) & BM_PMC_LVDSC2_LVWIE) /*! @brief Set the LVWIE field to a new value. */ #define BW_PMC_LVDSC2_LVWIE(x, v) (BITBAND_ACCESS8(HW_PMC_LVDSC2_ADDR(x), BP_PMC_LVDSC2_LVWIE) = (v)) /*@}*/ /*! * @name Register PMC_LVDSC2, field LVWACK[6] (WORZ) * * This write-only field is used to acknowledge low voltage warning errors. * Write 1 to clear LVWF. Reads always return 0. */ /*@{*/ #define BP_PMC_LVDSC2_LVWACK (6U) /*!< Bit position for PMC_LVDSC2_LVWACK. */ #define BM_PMC_LVDSC2_LVWACK (0x40U) /*!< Bit mask for PMC_LVDSC2_LVWACK. */ #define BS_PMC_LVDSC2_LVWACK (1U) /*!< Bit field size in bits for PMC_LVDSC2_LVWACK. */ /*! @brief Format value for bitfield PMC_LVDSC2_LVWACK. */ #define BF_PMC_LVDSC2_LVWACK(v) ((uint8_t)((uint8_t)(v) << BP_PMC_LVDSC2_LVWACK) & BM_PMC_LVDSC2_LVWACK) /*! @brief Set the LVWACK field to a new value. */ #define BW_PMC_LVDSC2_LVWACK(x, v) (BITBAND_ACCESS8(HW_PMC_LVDSC2_ADDR(x), BP_PMC_LVDSC2_LVWACK) = (v)) /*@}*/ /*! * @name Register PMC_LVDSC2, field LVWF[7] (RO) * * This read-only status field indicates a low-voltage warning event. LVWF is * set when VSupply transitions below the trip point, or after reset and VSupply is * already below VLVW. LVWF may be 1 after power-on reset, therefore, to use LVW * interrupt function, before enabling LVWIE, LVWF must be cleared by writing * LVWACK first. * * Values: * - 0 - Low-voltage warning event not detected * - 1 - Low-voltage warning event detected */ /*@{*/ #define BP_PMC_LVDSC2_LVWF (7U) /*!< Bit position for PMC_LVDSC2_LVWF. */ #define BM_PMC_LVDSC2_LVWF (0x80U) /*!< Bit mask for PMC_LVDSC2_LVWF. */ #define BS_PMC_LVDSC2_LVWF (1U) /*!< Bit field size in bits for PMC_LVDSC2_LVWF. */ /*! @brief Read current value of the PMC_LVDSC2_LVWF field. */ #define BR_PMC_LVDSC2_LVWF(x) (BITBAND_ACCESS8(HW_PMC_LVDSC2_ADDR(x), BP_PMC_LVDSC2_LVWF)) /*@}*/ /******************************************************************************* * HW_PMC_REGSC - Regulator Status And Control register ******************************************************************************/ /*! * @brief HW_PMC_REGSC - Regulator Status And Control register (RW) * * Reset value: 0x04U * * The PMC contains an internal voltage regulator. The voltage regulator design * uses a bandgap reference that is also available through a buffer as input to * certain internal peripherals, such as the CMP and ADC. The internal regulator * provides a status bit (REGONS) indicating the regulator is in run regulation. * This register is reset on Chip Reset Not VLLS and by reset types that trigger * Chip Reset not VLLS. See the Reset section details for more information. */ typedef union _hw_pmc_regsc { uint8_t U; struct _hw_pmc_regsc_bitfields { uint8_t BGBE : 1; /*!< [0] Bandgap Buffer Enable */ uint8_t RESERVED0 : 1; /*!< [1] */ uint8_t REGONS : 1; /*!< [2] Regulator In Run Regulation Status */ uint8_t ACKISO : 1; /*!< [3] Acknowledge Isolation */ uint8_t BGEN : 1; /*!< [4] Bandgap Enable In VLPx Operation */ uint8_t RESERVED1 : 3; /*!< [7:5] */ } B; } hw_pmc_regsc_t; /*! * @name Constants and macros for entire PMC_REGSC register */ /*@{*/ #define HW_PMC_REGSC_ADDR(x) ((x) + 0x2U) #define HW_PMC_REGSC(x) (*(__IO hw_pmc_regsc_t *) HW_PMC_REGSC_ADDR(x)) #define HW_PMC_REGSC_RD(x) (HW_PMC_REGSC(x).U) #define HW_PMC_REGSC_WR(x, v) (HW_PMC_REGSC(x).U = (v)) #define HW_PMC_REGSC_SET(x, v) (HW_PMC_REGSC_WR(x, HW_PMC_REGSC_RD(x) | (v))) #define HW_PMC_REGSC_CLR(x, v) (HW_PMC_REGSC_WR(x, HW_PMC_REGSC_RD(x) & ~(v))) #define HW_PMC_REGSC_TOG(x, v) (HW_PMC_REGSC_WR(x, HW_PMC_REGSC_RD(x) ^ (v))) /*@}*/ /* * Constants & macros for individual PMC_REGSC bitfields */ /*! * @name Register PMC_REGSC, field BGBE[0] (RW) * * Enables the bandgap buffer. * * Values: * - 0 - Bandgap buffer not enabled * - 1 - Bandgap buffer enabled */ /*@{*/ #define BP_PMC_REGSC_BGBE (0U) /*!< Bit position for PMC_REGSC_BGBE. */ #define BM_PMC_REGSC_BGBE (0x01U) /*!< Bit mask for PMC_REGSC_BGBE. */ #define BS_PMC_REGSC_BGBE (1U) /*!< Bit field size in bits for PMC_REGSC_BGBE. */ /*! @brief Read current value of the PMC_REGSC_BGBE field. */ #define BR_PMC_REGSC_BGBE(x) (BITBAND_ACCESS8(HW_PMC_REGSC_ADDR(x), BP_PMC_REGSC_BGBE)) /*! @brief Format value for bitfield PMC_REGSC_BGBE. */ #define BF_PMC_REGSC_BGBE(v) ((uint8_t)((uint8_t)(v) << BP_PMC_REGSC_BGBE) & BM_PMC_REGSC_BGBE) /*! @brief Set the BGBE field to a new value. */ #define BW_PMC_REGSC_BGBE(x, v) (BITBAND_ACCESS8(HW_PMC_REGSC_ADDR(x), BP_PMC_REGSC_BGBE) = (v)) /*@}*/ /*! * @name Register PMC_REGSC, field REGONS[2] (RO) * * This read-only field provides the current status of the internal voltage * regulator. * * Values: * - 0 - Regulator is in stop regulation or in transition to/from it * - 1 - Regulator is in run regulation */ /*@{*/ #define BP_PMC_REGSC_REGONS (2U) /*!< Bit position for PMC_REGSC_REGONS. */ #define BM_PMC_REGSC_REGONS (0x04U) /*!< Bit mask for PMC_REGSC_REGONS. */ #define BS_PMC_REGSC_REGONS (1U) /*!< Bit field size in bits for PMC_REGSC_REGONS. */ /*! @brief Read current value of the PMC_REGSC_REGONS field. */ #define BR_PMC_REGSC_REGONS(x) (BITBAND_ACCESS8(HW_PMC_REGSC_ADDR(x), BP_PMC_REGSC_REGONS)) /*@}*/ /*! * @name Register PMC_REGSC, field ACKISO[3] (W1C) * * Reading this field indicates whether certain peripherals and the I/O pads are * in a latched state as a result of having been in a VLLS mode. Writing 1 to * this field when it is set releases the I/O pads and certain peripherals to their * normal run mode state. After recovering from a VLLS mode, user should restore * chip configuration before clearing ACKISO. In particular, pin configuration * for enabled LLWU wakeup pins should be restored to avoid any LLWU flag from * being falsely set when ACKISO is cleared. * * Values: * - 0 - Peripherals and I/O pads are in normal run state. * - 1 - Certain peripherals and I/O pads are in an isolated and latched state. */ /*@{*/ #define BP_PMC_REGSC_ACKISO (3U) /*!< Bit position for PMC_REGSC_ACKISO. */ #define BM_PMC_REGSC_ACKISO (0x08U) /*!< Bit mask for PMC_REGSC_ACKISO. */ #define BS_PMC_REGSC_ACKISO (1U) /*!< Bit field size in bits for PMC_REGSC_ACKISO. */ /*! @brief Read current value of the PMC_REGSC_ACKISO field. */ #define BR_PMC_REGSC_ACKISO(x) (BITBAND_ACCESS8(HW_PMC_REGSC_ADDR(x), BP_PMC_REGSC_ACKISO)) /*! @brief Format value for bitfield PMC_REGSC_ACKISO. */ #define BF_PMC_REGSC_ACKISO(v) ((uint8_t)((uint8_t)(v) << BP_PMC_REGSC_ACKISO) & BM_PMC_REGSC_ACKISO) /*! @brief Set the ACKISO field to a new value. */ #define BW_PMC_REGSC_ACKISO(x, v) (BITBAND_ACCESS8(HW_PMC_REGSC_ADDR(x), BP_PMC_REGSC_ACKISO) = (v)) /*@}*/ /*! * @name Register PMC_REGSC, field BGEN[4] (RW) * * BGEN controls whether the bandgap is enabled in lower power modes of * operation (VLPx, LLS, and VLLSx). When on-chip peripherals require the bandgap voltage * reference in low power modes of operation, set BGEN to continue to enable the * bandgap operation. When the bandgap voltage reference is not needed in low * power modes, clear BGEN to avoid excess power consumption. * * Values: * - 0 - Bandgap voltage reference is disabled in VLPx , LLS , and VLLSx modes. * - 1 - Bandgap voltage reference is enabled in VLPx , LLS , and VLLSx modes. */ /*@{*/ #define BP_PMC_REGSC_BGEN (4U) /*!< Bit position for PMC_REGSC_BGEN. */ #define BM_PMC_REGSC_BGEN (0x10U) /*!< Bit mask for PMC_REGSC_BGEN. */ #define BS_PMC_REGSC_BGEN (1U) /*!< Bit field size in bits for PMC_REGSC_BGEN. */ /*! @brief Read current value of the PMC_REGSC_BGEN field. */ #define BR_PMC_REGSC_BGEN(x) (BITBAND_ACCESS8(HW_PMC_REGSC_ADDR(x), BP_PMC_REGSC_BGEN)) /*! @brief Format value for bitfield PMC_REGSC_BGEN. */ #define BF_PMC_REGSC_BGEN(v) ((uint8_t)((uint8_t)(v) << BP_PMC_REGSC_BGEN) & BM_PMC_REGSC_BGEN) /*! @brief Set the BGEN field to a new value. */ #define BW_PMC_REGSC_BGEN(x, v) (BITBAND_ACCESS8(HW_PMC_REGSC_ADDR(x), BP_PMC_REGSC_BGEN) = (v)) /*@}*/ /******************************************************************************* * hw_pmc_t - module struct ******************************************************************************/ /*! * @brief All PMC module registers. */ #pragma pack(1) typedef struct _hw_pmc { __IO hw_pmc_lvdsc1_t LVDSC1; /*!< [0x0] Low Voltage Detect Status And Control 1 register */ __IO hw_pmc_lvdsc2_t LVDSC2; /*!< [0x1] Low Voltage Detect Status And Control 2 register */ __IO hw_pmc_regsc_t REGSC; /*!< [0x2] Regulator Status And Control register */ } hw_pmc_t; #pragma pack() /*! @brief Macro to access all PMC registers. */ /*! @param x PMC module instance base address. */ /*! @return Reference (not a pointer) to the registers struct. To get a pointer to the struct, * use the '&' operator, like &HW_PMC(PMC_BASE). */ #define HW_PMC(x) (*(hw_pmc_t *)(x)) #endif /* __HW_PMC_REGISTERS_H__ */ /* EOF */ ================================================ FILE: Zelig/mbed/TARGET_K64F/TARGET_Freescale/TARGET_KPSDK_MCUS/TARGET_MCU_K64F/device/device/MK64F12/MK64F12_port.h ================================================ /* ** ################################################################### ** Compilers: Keil ARM C/C++ Compiler ** Freescale C/C++ for Embedded ARM ** GNU C Compiler ** IAR ANSI C/C++ Compiler for ARM ** ** Reference manual: K64P144M120SF5RM, Rev.2, January 2014 ** Version: rev. 2.5, 2014-02-10 ** Build: b140604 ** ** Abstract: ** Extension to the CMSIS register access layer header. ** ** Copyright (c) 2014 Freescale Semiconductor, Inc. ** All rights reserved. ** ** Redistribution and use in source and binary forms, with or without modification, ** are permitted provided that the following conditions are met: ** ** o Redistributions of source code must retain the above copyright notice, this list ** of conditions and the following disclaimer. ** ** o Redistributions in binary form must reproduce the above copyright notice, this ** list of conditions and the following disclaimer in the documentation and/or ** other materials provided with the distribution. ** ** o Neither the name of Freescale Semiconductor, Inc. nor the names of its ** contributors may be used to endorse or promote products derived from this ** software without specific prior written permission. ** ** THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ** ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED ** WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE ** DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT 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. ** ** http: www.freescale.com ** mail: support@freescale.com ** ** Revisions: ** - rev. 1.0 (2013-08-12) ** Initial version. ** - rev. 2.0 (2013-10-29) ** Register accessor macros added to the memory map. ** Symbols for Processor Expert memory map compatibility added to the memory map. ** Startup file for gcc has been updated according to CMSIS 3.2. ** System initialization updated. ** MCG - registers updated. ** PORTA, PORTB, PORTC, PORTE - registers for digital filter removed. ** - rev. 2.1 (2013-10-30) ** Definition of BITBAND macros updated to support peripherals with 32-bit acces disabled. ** - rev. 2.2 (2013-12-09) ** DMA - EARS register removed. ** AIPS0, AIPS1 - MPRA register updated. ** - rev. 2.3 (2014-01-24) ** Update according to reference manual rev. 2 ** ENET, MCG, MCM, SIM, USB - registers updated ** - rev. 2.4 (2014-02-10) ** The declaration of clock configurations has been moved to separate header file system_MK64F12.h ** Update of SystemInit() and SystemCoreClockUpdate() functions. ** - rev. 2.5 (2014-02-10) ** The declaration of clock configurations has been moved to separate header file system_MK64F12.h ** Update of SystemInit() and SystemCoreClockUpdate() functions. ** Module access macro module_BASES replaced by module_BASE_PTRS. ** ** ################################################################### */ /* * WARNING! DO NOT EDIT THIS FILE DIRECTLY! * * This file was generated automatically and any changes may be lost. */ #ifndef __HW_PORT_REGISTERS_H__ #define __HW_PORT_REGISTERS_H__ #include "MK64F12.h" #include "fsl_bitaccess.h" /* * MK64F12 PORT * * Pin Control and Interrupts * * Registers defined in this header file: * - HW_PORT_PCRn - Pin Control Register n * - HW_PORT_GPCLR - Global Pin Control Low Register * - HW_PORT_GPCHR - Global Pin Control High Register * - HW_PORT_ISFR - Interrupt Status Flag Register * - HW_PORT_DFER - Digital Filter Enable Register * - HW_PORT_DFCR - Digital Filter Clock Register * - HW_PORT_DFWR - Digital Filter Width Register * * - hw_port_t - Struct containing all module registers. */ #define HW_PORT_INSTANCE_COUNT (5U) /*!< Number of instances of the PORT module. */ #define HW_PORTA (0U) /*!< Instance number for PORTA. */ #define HW_PORTB (1U) /*!< Instance number for PORTB. */ #define HW_PORTC (2U) /*!< Instance number for PORTC. */ #define HW_PORTD (3U) /*!< Instance number for PORTD. */ #define HW_PORTE (4U) /*!< Instance number for PORTE. */ /******************************************************************************* * HW_PORT_PCRn - Pin Control Register n ******************************************************************************/ /*! * @brief HW_PORT_PCRn - Pin Control Register n (RW) * * Reset value: 0x00000742U * * See the Signal Multiplexing and Pin Assignment chapter for the reset value of * this device. See the GPIO Configuration section for details on the available * functions for each pin. Do not modify pin configuration registers associated * with pins not available in your selected package. All unbonded pins not * available in your package will default to DISABLE state for lowest power consumption. */ typedef union _hw_port_pcrn { uint32_t U; struct _hw_port_pcrn_bitfields { uint32_t PS : 1; /*!< [0] Pull Select */ uint32_t PE : 1; /*!< [1] Pull Enable */ uint32_t SRE : 1; /*!< [2] Slew Rate Enable */ uint32_t RESERVED0 : 1; /*!< [3] */ uint32_t PFE : 1; /*!< [4] Passive Filter Enable */ uint32_t ODE : 1; /*!< [5] Open Drain Enable */ uint32_t DSE : 1; /*!< [6] Drive Strength Enable */ uint32_t RESERVED1 : 1; /*!< [7] */ uint32_t MUX : 3; /*!< [10:8] Pin Mux Control */ uint32_t RESERVED2 : 4; /*!< [14:11] */ uint32_t LK : 1; /*!< [15] Lock Register */ uint32_t IRQC : 4; /*!< [19:16] Interrupt Configuration */ uint32_t RESERVED3 : 4; /*!< [23:20] */ uint32_t ISF : 1; /*!< [24] Interrupt Status Flag */ uint32_t RESERVED4 : 7; /*!< [31:25] */ } B; } hw_port_pcrn_t; /*! * @name Constants and macros for entire PORT_PCRn register */ /*@{*/ #define HW_PORT_PCRn_COUNT (32U) #define HW_PORT_PCRn_ADDR(x, n) ((x) + 0x0U + (0x4U * (n))) #define HW_PORT_PCRn(x, n) (*(__IO hw_port_pcrn_t *) HW_PORT_PCRn_ADDR(x, n)) #define HW_PORT_PCRn_RD(x, n) (HW_PORT_PCRn(x, n).U) #define HW_PORT_PCRn_WR(x, n, v) (HW_PORT_PCRn(x, n).U = (v)) #define HW_PORT_PCRn_SET(x, n, v) (HW_PORT_PCRn_WR(x, n, HW_PORT_PCRn_RD(x, n) | (v))) #define HW_PORT_PCRn_CLR(x, n, v) (HW_PORT_PCRn_WR(x, n, HW_PORT_PCRn_RD(x, n) & ~(v))) #define HW_PORT_PCRn_TOG(x, n, v) (HW_PORT_PCRn_WR(x, n, HW_PORT_PCRn_RD(x, n) ^ (v))) /*@}*/ /* * Constants & macros for individual PORT_PCRn bitfields */ /*! * @name Register PORT_PCRn, field PS[0] (RW) * * Pull configuration is valid in all digital pin muxing modes. * * Values: * - 0 - Internal pulldown resistor is enabled on the corresponding pin, if the * corresponding PE field is set. * - 1 - Internal pullup resistor is enabled on the corresponding pin, if the * corresponding PE field is set. */ /*@{*/ #define BP_PORT_PCRn_PS (0U) /*!< Bit position for PORT_PCRn_PS. */ #define BM_PORT_PCRn_PS (0x00000001U) /*!< Bit mask for PORT_PCRn_PS. */ #define BS_PORT_PCRn_PS (1U) /*!< Bit field size in bits for PORT_PCRn_PS. */ /*! @brief Read current value of the PORT_PCRn_PS field. */ #define BR_PORT_PCRn_PS(x, n) (BITBAND_ACCESS32(HW_PORT_PCRn_ADDR(x, n), BP_PORT_PCRn_PS)) /*! @brief Format value for bitfield PORT_PCRn_PS. */ #define BF_PORT_PCRn_PS(v) ((uint32_t)((uint32_t)(v) << BP_PORT_PCRn_PS) & BM_PORT_PCRn_PS) /*! @brief Set the PS field to a new value. */ #define BW_PORT_PCRn_PS(x, n, v) (BITBAND_ACCESS32(HW_PORT_PCRn_ADDR(x, n), BP_PORT_PCRn_PS) = (v)) /*@}*/ /*! * @name Register PORT_PCRn, field PE[1] (RW) * * Pull configuration is valid in all digital pin muxing modes. * * Values: * - 0 - Internal pullup or pulldown resistor is not enabled on the * corresponding pin. * - 1 - Internal pullup or pulldown resistor is enabled on the corresponding * pin, if the pin is configured as a digital input. */ /*@{*/ #define BP_PORT_PCRn_PE (1U) /*!< Bit position for PORT_PCRn_PE. */ #define BM_PORT_PCRn_PE (0x00000002U) /*!< Bit mask for PORT_PCRn_PE. */ #define BS_PORT_PCRn_PE (1U) /*!< Bit field size in bits for PORT_PCRn_PE. */ /*! @brief Read current value of the PORT_PCRn_PE field. */ #define BR_PORT_PCRn_PE(x, n) (BITBAND_ACCESS32(HW_PORT_PCRn_ADDR(x, n), BP_PORT_PCRn_PE)) /*! @brief Format value for bitfield PORT_PCRn_PE. */ #define BF_PORT_PCRn_PE(v) ((uint32_t)((uint32_t)(v) << BP_PORT_PCRn_PE) & BM_PORT_PCRn_PE) /*! @brief Set the PE field to a new value. */ #define BW_PORT_PCRn_PE(x, n, v) (BITBAND_ACCESS32(HW_PORT_PCRn_ADDR(x, n), BP_PORT_PCRn_PE) = (v)) /*@}*/ /*! * @name Register PORT_PCRn, field SRE[2] (RW) * * Slew rate configuration is valid in all digital pin muxing modes. * * Values: * - 0 - Fast slew rate is configured on the corresponding pin, if the pin is * configured as a digital output. * - 1 - Slow slew rate is configured on the corresponding pin, if the pin is * configured as a digital output. */ /*@{*/ #define BP_PORT_PCRn_SRE (2U) /*!< Bit position for PORT_PCRn_SRE. */ #define BM_PORT_PCRn_SRE (0x00000004U) /*!< Bit mask for PORT_PCRn_SRE. */ #define BS_PORT_PCRn_SRE (1U) /*!< Bit field size in bits for PORT_PCRn_SRE. */ /*! @brief Read current value of the PORT_PCRn_SRE field. */ #define BR_PORT_PCRn_SRE(x, n) (BITBAND_ACCESS32(HW_PORT_PCRn_ADDR(x, n), BP_PORT_PCRn_SRE)) /*! @brief Format value for bitfield PORT_PCRn_SRE. */ #define BF_PORT_PCRn_SRE(v) ((uint32_t)((uint32_t)(v) << BP_PORT_PCRn_SRE) & BM_PORT_PCRn_SRE) /*! @brief Set the SRE field to a new value. */ #define BW_PORT_PCRn_SRE(x, n, v) (BITBAND_ACCESS32(HW_PORT_PCRn_ADDR(x, n), BP_PORT_PCRn_SRE) = (v)) /*@}*/ /*! * @name Register PORT_PCRn, field PFE[4] (RW) * * Passive filter configuration is valid in all digital pin muxing modes. * * Values: * - 0 - Passive input filter is disabled on the corresponding pin. * - 1 - Passive input filter is enabled on the corresponding pin, if the pin is * configured as a digital input. Refer to the device data sheet for filter * characteristics. */ /*@{*/ #define BP_PORT_PCRn_PFE (4U) /*!< Bit position for PORT_PCRn_PFE. */ #define BM_PORT_PCRn_PFE (0x00000010U) /*!< Bit mask for PORT_PCRn_PFE. */ #define BS_PORT_PCRn_PFE (1U) /*!< Bit field size in bits for PORT_PCRn_PFE. */ /*! @brief Read current value of the PORT_PCRn_PFE field. */ #define BR_PORT_PCRn_PFE(x, n) (BITBAND_ACCESS32(HW_PORT_PCRn_ADDR(x, n), BP_PORT_PCRn_PFE)) /*! @brief Format value for bitfield PORT_PCRn_PFE. */ #define BF_PORT_PCRn_PFE(v) ((uint32_t)((uint32_t)(v) << BP_PORT_PCRn_PFE) & BM_PORT_PCRn_PFE) /*! @brief Set the PFE field to a new value. */ #define BW_PORT_PCRn_PFE(x, n, v) (BITBAND_ACCESS32(HW_PORT_PCRn_ADDR(x, n), BP_PORT_PCRn_PFE) = (v)) /*@}*/ /*! * @name Register PORT_PCRn, field ODE[5] (RW) * * Open drain configuration is valid in all digital pin muxing modes. * * Values: * - 0 - Open drain output is disabled on the corresponding pin. * - 1 - Open drain output is enabled on the corresponding pin, if the pin is * configured as a digital output. */ /*@{*/ #define BP_PORT_PCRn_ODE (5U) /*!< Bit position for PORT_PCRn_ODE. */ #define BM_PORT_PCRn_ODE (0x00000020U) /*!< Bit mask for PORT_PCRn_ODE. */ #define BS_PORT_PCRn_ODE (1U) /*!< Bit field size in bits for PORT_PCRn_ODE. */ /*! @brief Read current value of the PORT_PCRn_ODE field. */ #define BR_PORT_PCRn_ODE(x, n) (BITBAND_ACCESS32(HW_PORT_PCRn_ADDR(x, n), BP_PORT_PCRn_ODE)) /*! @brief Format value for bitfield PORT_PCRn_ODE. */ #define BF_PORT_PCRn_ODE(v) ((uint32_t)((uint32_t)(v) << BP_PORT_PCRn_ODE) & BM_PORT_PCRn_ODE) /*! @brief Set the ODE field to a new value. */ #define BW_PORT_PCRn_ODE(x, n, v) (BITBAND_ACCESS32(HW_PORT_PCRn_ADDR(x, n), BP_PORT_PCRn_ODE) = (v)) /*@}*/ /*! * @name Register PORT_PCRn, field DSE[6] (RW) * * Drive strength configuration is valid in all digital pin muxing modes. * * Values: * - 0 - Low drive strength is configured on the corresponding pin, if pin is * configured as a digital output. * - 1 - High drive strength is configured on the corresponding pin, if pin is * configured as a digital output. */ /*@{*/ #define BP_PORT_PCRn_DSE (6U) /*!< Bit position for PORT_PCRn_DSE. */ #define BM_PORT_PCRn_DSE (0x00000040U) /*!< Bit mask for PORT_PCRn_DSE. */ #define BS_PORT_PCRn_DSE (1U) /*!< Bit field size in bits for PORT_PCRn_DSE. */ /*! @brief Read current value of the PORT_PCRn_DSE field. */ #define BR_PORT_PCRn_DSE(x, n) (BITBAND_ACCESS32(HW_PORT_PCRn_ADDR(x, n), BP_PORT_PCRn_DSE)) /*! @brief Format value for bitfield PORT_PCRn_DSE. */ #define BF_PORT_PCRn_DSE(v) ((uint32_t)((uint32_t)(v) << BP_PORT_PCRn_DSE) & BM_PORT_PCRn_DSE) /*! @brief Set the DSE field to a new value. */ #define BW_PORT_PCRn_DSE(x, n, v) (BITBAND_ACCESS32(HW_PORT_PCRn_ADDR(x, n), BP_PORT_PCRn_DSE) = (v)) /*@}*/ /*! * @name Register PORT_PCRn, field MUX[10:8] (RW) * * Not all pins support all pin muxing slots. Unimplemented pin muxing slots are * reserved and may result in configuring the pin for a different pin muxing * slot. The corresponding pin is configured in the following pin muxing slot as * follows: * * Values: * - 000 - Pin disabled (analog). * - 001 - Alternative 1 (GPIO). * - 010 - Alternative 2 (chip-specific). * - 011 - Alternative 3 (chip-specific). * - 100 - Alternative 4 (chip-specific). * - 101 - Alternative 5 (chip-specific). * - 110 - Alternative 6 (chip-specific). * - 111 - Alternative 7 (chip-specific). */ /*@{*/ #define BP_PORT_PCRn_MUX (8U) /*!< Bit position for PORT_PCRn_MUX. */ #define BM_PORT_PCRn_MUX (0x00000700U) /*!< Bit mask for PORT_PCRn_MUX. */ #define BS_PORT_PCRn_MUX (3U) /*!< Bit field size in bits for PORT_PCRn_MUX. */ /*! @brief Read current value of the PORT_PCRn_MUX field. */ #define BR_PORT_PCRn_MUX(x, n) (HW_PORT_PCRn(x, n).B.MUX) /*! @brief Format value for bitfield PORT_PCRn_MUX. */ #define BF_PORT_PCRn_MUX(v) ((uint32_t)((uint32_t)(v) << BP_PORT_PCRn_MUX) & BM_PORT_PCRn_MUX) /*! @brief Set the MUX field to a new value. */ #define BW_PORT_PCRn_MUX(x, n, v) (HW_PORT_PCRn_WR(x, n, (HW_PORT_PCRn_RD(x, n) & ~BM_PORT_PCRn_MUX) | BF_PORT_PCRn_MUX(v))) /*@}*/ /*! * @name Register PORT_PCRn, field LK[15] (RW) * * Values: * - 0 - Pin Control Register fields [15:0] are not locked. * - 1 - Pin Control Register fields [15:0] are locked and cannot be updated * until the next system reset. */ /*@{*/ #define BP_PORT_PCRn_LK (15U) /*!< Bit position for PORT_PCRn_LK. */ #define BM_PORT_PCRn_LK (0x00008000U) /*!< Bit mask for PORT_PCRn_LK. */ #define BS_PORT_PCRn_LK (1U) /*!< Bit field size in bits for PORT_PCRn_LK. */ /*! @brief Read current value of the PORT_PCRn_LK field. */ #define BR_PORT_PCRn_LK(x, n) (BITBAND_ACCESS32(HW_PORT_PCRn_ADDR(x, n), BP_PORT_PCRn_LK)) /*! @brief Format value for bitfield PORT_PCRn_LK. */ #define BF_PORT_PCRn_LK(v) ((uint32_t)((uint32_t)(v) << BP_PORT_PCRn_LK) & BM_PORT_PCRn_LK) /*! @brief Set the LK field to a new value. */ #define BW_PORT_PCRn_LK(x, n, v) (BITBAND_ACCESS32(HW_PORT_PCRn_ADDR(x, n), BP_PORT_PCRn_LK) = (v)) /*@}*/ /*! * @name Register PORT_PCRn, field IRQC[19:16] (RW) * * The pin interrupt configuration is valid in all digital pin muxing modes. The * corresponding pin is configured to generate interrupt/DMA request as follows: * * Values: * - 0000 - Interrupt/DMA request disabled. * - 0001 - DMA request on rising edge. * - 0010 - DMA request on falling edge. * - 0011 - DMA request on either edge. * - 1000 - Interrupt when logic 0. * - 1001 - Interrupt on rising-edge. * - 1010 - Interrupt on falling-edge. * - 1011 - Interrupt on either edge. * - 1100 - Interrupt when logic 1. */ /*@{*/ #define BP_PORT_PCRn_IRQC (16U) /*!< Bit position for PORT_PCRn_IRQC. */ #define BM_PORT_PCRn_IRQC (0x000F0000U) /*!< Bit mask for PORT_PCRn_IRQC. */ #define BS_PORT_PCRn_IRQC (4U) /*!< Bit field size in bits for PORT_PCRn_IRQC. */ /*! @brief Read current value of the PORT_PCRn_IRQC field. */ #define BR_PORT_PCRn_IRQC(x, n) (HW_PORT_PCRn(x, n).B.IRQC) /*! @brief Format value for bitfield PORT_PCRn_IRQC. */ #define BF_PORT_PCRn_IRQC(v) ((uint32_t)((uint32_t)(v) << BP_PORT_PCRn_IRQC) & BM_PORT_PCRn_IRQC) /*! @brief Set the IRQC field to a new value. */ #define BW_PORT_PCRn_IRQC(x, n, v) (HW_PORT_PCRn_WR(x, n, (HW_PORT_PCRn_RD(x, n) & ~BM_PORT_PCRn_IRQC) | BF_PORT_PCRn_IRQC(v))) /*@}*/ /*! * @name Register PORT_PCRn, field ISF[24] (W1C) * * The pin interrupt configuration is valid in all digital pin muxing modes. * * Values: * - 0 - Configured interrupt is not detected. * - 1 - Configured interrupt is detected. If the pin is configured to generate * a DMA request, then the corresponding flag will be cleared automatically * at the completion of the requested DMA transfer. Otherwise, the flag * remains set until a logic 1 is written to the flag. If the pin is configured for * a level sensitive interrupt and the pin remains asserted, then the flag * is set again immediately after it is cleared. */ /*@{*/ #define BP_PORT_PCRn_ISF (24U) /*!< Bit position for PORT_PCRn_ISF. */ #define BM_PORT_PCRn_ISF (0x01000000U) /*!< Bit mask for PORT_PCRn_ISF. */ #define BS_PORT_PCRn_ISF (1U) /*!< Bit field size in bits for PORT_PCRn_ISF. */ /*! @brief Read current value of the PORT_PCRn_ISF field. */ #define BR_PORT_PCRn_ISF(x, n) (BITBAND_ACCESS32(HW_PORT_PCRn_ADDR(x, n), BP_PORT_PCRn_ISF)) /*! @brief Format value for bitfield PORT_PCRn_ISF. */ #define BF_PORT_PCRn_ISF(v) ((uint32_t)((uint32_t)(v) << BP_PORT_PCRn_ISF) & BM_PORT_PCRn_ISF) /*! @brief Set the ISF field to a new value. */ #define BW_PORT_PCRn_ISF(x, n, v) (BITBAND_ACCESS32(HW_PORT_PCRn_ADDR(x, n), BP_PORT_PCRn_ISF) = (v)) /*@}*/ /******************************************************************************* * HW_PORT_GPCLR - Global Pin Control Low Register ******************************************************************************/ /*! * @brief HW_PORT_GPCLR - Global Pin Control Low Register (WORZ) * * Reset value: 0x00000000U * * Only 32-bit writes are supported to this register. */ typedef union _hw_port_gpclr { uint32_t U; struct _hw_port_gpclr_bitfields { uint32_t GPWD : 16; /*!< [15:0] Global Pin Write Data */ uint32_t GPWE : 16; /*!< [31:16] Global Pin Write Enable */ } B; } hw_port_gpclr_t; /*! * @name Constants and macros for entire PORT_GPCLR register */ /*@{*/ #define HW_PORT_GPCLR_ADDR(x) ((x) + 0x80U) #define HW_PORT_GPCLR(x) (*(__O hw_port_gpclr_t *) HW_PORT_GPCLR_ADDR(x)) #define HW_PORT_GPCLR_RD(x) (HW_PORT_GPCLR(x).U) #define HW_PORT_GPCLR_WR(x, v) (HW_PORT_GPCLR(x).U = (v)) /*@}*/ /* * Constants & macros for individual PORT_GPCLR bitfields */ /*! * @name Register PORT_GPCLR, field GPWD[15:0] (WORZ) * * Write value that is written to all Pin Control Registers bits [15:0] that are * selected by GPWE. */ /*@{*/ #define BP_PORT_GPCLR_GPWD (0U) /*!< Bit position for PORT_GPCLR_GPWD. */ #define BM_PORT_GPCLR_GPWD (0x0000FFFFU) /*!< Bit mask for PORT_GPCLR_GPWD. */ #define BS_PORT_GPCLR_GPWD (16U) /*!< Bit field size in bits for PORT_GPCLR_GPWD. */ /*! @brief Format value for bitfield PORT_GPCLR_GPWD. */ #define BF_PORT_GPCLR_GPWD(v) ((uint32_t)((uint32_t)(v) << BP_PORT_GPCLR_GPWD) & BM_PORT_GPCLR_GPWD) /*! @brief Set the GPWD field to a new value. */ #define BW_PORT_GPCLR_GPWD(x, v) (HW_PORT_GPCLR_WR(x, (HW_PORT_GPCLR_RD(x) & ~BM_PORT_GPCLR_GPWD) | BF_PORT_GPCLR_GPWD(v))) /*@}*/ /*! * @name Register PORT_GPCLR, field GPWE[31:16] (WORZ) * * Selects which Pin Control Registers (15 through 0) bits [15:0] update with * the value in GPWD. If a selected Pin Control Register is locked then the write * to that register is ignored. * * Values: * - 0 - Corresponding Pin Control Register is not updated with the value in * GPWD. * - 1 - Corresponding Pin Control Register is updated with the value in GPWD. */ /*@{*/ #define BP_PORT_GPCLR_GPWE (16U) /*!< Bit position for PORT_GPCLR_GPWE. */ #define BM_PORT_GPCLR_GPWE (0xFFFF0000U) /*!< Bit mask for PORT_GPCLR_GPWE. */ #define BS_PORT_GPCLR_GPWE (16U) /*!< Bit field size in bits for PORT_GPCLR_GPWE. */ /*! @brief Format value for bitfield PORT_GPCLR_GPWE. */ #define BF_PORT_GPCLR_GPWE(v) ((uint32_t)((uint32_t)(v) << BP_PORT_GPCLR_GPWE) & BM_PORT_GPCLR_GPWE) /*! @brief Set the GPWE field to a new value. */ #define BW_PORT_GPCLR_GPWE(x, v) (HW_PORT_GPCLR_WR(x, (HW_PORT_GPCLR_RD(x) & ~BM_PORT_GPCLR_GPWE) | BF_PORT_GPCLR_GPWE(v))) /*@}*/ /******************************************************************************* * HW_PORT_GPCHR - Global Pin Control High Register ******************************************************************************/ /*! * @brief HW_PORT_GPCHR - Global Pin Control High Register (WORZ) * * Reset value: 0x00000000U * * Only 32-bit writes are supported to this register. */ typedef union _hw_port_gpchr { uint32_t U; struct _hw_port_gpchr_bitfields { uint32_t GPWD : 16; /*!< [15:0] Global Pin Write Data */ uint32_t GPWE : 16; /*!< [31:16] Global Pin Write Enable */ } B; } hw_port_gpchr_t; /*! * @name Constants and macros for entire PORT_GPCHR register */ /*@{*/ #define HW_PORT_GPCHR_ADDR(x) ((x) + 0x84U) #define HW_PORT_GPCHR(x) (*(__O hw_port_gpchr_t *) HW_PORT_GPCHR_ADDR(x)) #define HW_PORT_GPCHR_RD(x) (HW_PORT_GPCHR(x).U) #define HW_PORT_GPCHR_WR(x, v) (HW_PORT_GPCHR(x).U = (v)) /*@}*/ /* * Constants & macros for individual PORT_GPCHR bitfields */ /*! * @name Register PORT_GPCHR, field GPWD[15:0] (WORZ) * * Write value that is written to all Pin Control Registers bits [15:0] that are * selected by GPWE. */ /*@{*/ #define BP_PORT_GPCHR_GPWD (0U) /*!< Bit position for PORT_GPCHR_GPWD. */ #define BM_PORT_GPCHR_GPWD (0x0000FFFFU) /*!< Bit mask for PORT_GPCHR_GPWD. */ #define BS_PORT_GPCHR_GPWD (16U) /*!< Bit field size in bits for PORT_GPCHR_GPWD. */ /*! @brief Format value for bitfield PORT_GPCHR_GPWD. */ #define BF_PORT_GPCHR_GPWD(v) ((uint32_t)((uint32_t)(v) << BP_PORT_GPCHR_GPWD) & BM_PORT_GPCHR_GPWD) /*! @brief Set the GPWD field to a new value. */ #define BW_PORT_GPCHR_GPWD(x, v) (HW_PORT_GPCHR_WR(x, (HW_PORT_GPCHR_RD(x) & ~BM_PORT_GPCHR_GPWD) | BF_PORT_GPCHR_GPWD(v))) /*@}*/ /*! * @name Register PORT_GPCHR, field GPWE[31:16] (WORZ) * * Selects which Pin Control Registers (31 through 16) bits [15:0] update with * the value in GPWD. If a selected Pin Control Register is locked then the write * to that register is ignored. * * Values: * - 0 - Corresponding Pin Control Register is not updated with the value in * GPWD. * - 1 - Corresponding Pin Control Register is updated with the value in GPWD. */ /*@{*/ #define BP_PORT_GPCHR_GPWE (16U) /*!< Bit position for PORT_GPCHR_GPWE. */ #define BM_PORT_GPCHR_GPWE (0xFFFF0000U) /*!< Bit mask for PORT_GPCHR_GPWE. */ #define BS_PORT_GPCHR_GPWE (16U) /*!< Bit field size in bits for PORT_GPCHR_GPWE. */ /*! @brief Format value for bitfield PORT_GPCHR_GPWE. */ #define BF_PORT_GPCHR_GPWE(v) ((uint32_t)((uint32_t)(v) << BP_PORT_GPCHR_GPWE) & BM_PORT_GPCHR_GPWE) /*! @brief Set the GPWE field to a new value. */ #define BW_PORT_GPCHR_GPWE(x, v) (HW_PORT_GPCHR_WR(x, (HW_PORT_GPCHR_RD(x) & ~BM_PORT_GPCHR_GPWE) | BF_PORT_GPCHR_GPWE(v))) /*@}*/ /******************************************************************************* * HW_PORT_ISFR - Interrupt Status Flag Register ******************************************************************************/ /*! * @brief HW_PORT_ISFR - Interrupt Status Flag Register (W1C) * * Reset value: 0x00000000U * * The pin interrupt configuration is valid in all digital pin muxing modes. The * Interrupt Status Flag for each pin is also visible in the corresponding Pin * Control Register, and each flag can be cleared in either location. */ typedef union _hw_port_isfr { uint32_t U; struct _hw_port_isfr_bitfields { uint32_t ISF : 32; /*!< [31:0] Interrupt Status Flag */ } B; } hw_port_isfr_t; /*! * @name Constants and macros for entire PORT_ISFR register */ /*@{*/ #define HW_PORT_ISFR_ADDR(x) ((x) + 0xA0U) #define HW_PORT_ISFR(x) (*(__IO hw_port_isfr_t *) HW_PORT_ISFR_ADDR(x)) #define HW_PORT_ISFR_RD(x) (HW_PORT_ISFR(x).U) #define HW_PORT_ISFR_WR(x, v) (HW_PORT_ISFR(x).U = (v)) #define HW_PORT_ISFR_SET(x, v) (HW_PORT_ISFR_WR(x, HW_PORT_ISFR_RD(x) | (v))) #define HW_PORT_ISFR_CLR(x, v) (HW_PORT_ISFR_WR(x, HW_PORT_ISFR_RD(x) & ~(v))) #define HW_PORT_ISFR_TOG(x, v) (HW_PORT_ISFR_WR(x, HW_PORT_ISFR_RD(x) ^ (v))) /*@}*/ /* * Constants & macros for individual PORT_ISFR bitfields */ /*! * @name Register PORT_ISFR, field ISF[31:0] (W1C) * * Each bit in the field indicates the detection of the configured interrupt of * the same number as the field. * * Values: * - 0 - Configured interrupt is not detected. * - 1 - Configured interrupt is detected. If the pin is configured to generate * a DMA request, then the corresponding flag will be cleared automatically * at the completion of the requested DMA transfer. Otherwise, the flag * remains set until a logic 1 is written to the flag. If the pin is configured for * a level sensitive interrupt and the pin remains asserted, then the flag * is set again immediately after it is cleared. */ /*@{*/ #define BP_PORT_ISFR_ISF (0U) /*!< Bit position for PORT_ISFR_ISF. */ #define BM_PORT_ISFR_ISF (0xFFFFFFFFU) /*!< Bit mask for PORT_ISFR_ISF. */ #define BS_PORT_ISFR_ISF (32U) /*!< Bit field size in bits for PORT_ISFR_ISF. */ /*! @brief Read current value of the PORT_ISFR_ISF field. */ #define BR_PORT_ISFR_ISF(x) (HW_PORT_ISFR(x).U) /*! @brief Format value for bitfield PORT_ISFR_ISF. */ #define BF_PORT_ISFR_ISF(v) ((uint32_t)((uint32_t)(v) << BP_PORT_ISFR_ISF) & BM_PORT_ISFR_ISF) /*! @brief Set the ISF field to a new value. */ #define BW_PORT_ISFR_ISF(x, v) (HW_PORT_ISFR_WR(x, v)) /*@}*/ /******************************************************************************* * HW_PORT_DFER - Digital Filter Enable Register ******************************************************************************/ /*! * @brief HW_PORT_DFER - Digital Filter Enable Register (RW) * * Reset value: 0x00000000U * * The corresponding bit is read only for pins that do not support a digital * filter. Refer to the Chapter of Signal Multiplexing and Signal Descriptions for * the pins that support digital filter. The digital filter configuration is valid * in all digital pin muxing modes. */ typedef union _hw_port_dfer { uint32_t U; struct _hw_port_dfer_bitfields { uint32_t DFE : 32; /*!< [31:0] Digital Filter Enable */ } B; } hw_port_dfer_t; /*! * @name Constants and macros for entire PORT_DFER register */ /*@{*/ #define HW_PORT_DFER_ADDR(x) ((x) + 0xC0U) #define HW_PORT_DFER(x) (*(__IO hw_port_dfer_t *) HW_PORT_DFER_ADDR(x)) #define HW_PORT_DFER_RD(x) (HW_PORT_DFER(x).U) #define HW_PORT_DFER_WR(x, v) (HW_PORT_DFER(x).U = (v)) #define HW_PORT_DFER_SET(x, v) (HW_PORT_DFER_WR(x, HW_PORT_DFER_RD(x) | (v))) #define HW_PORT_DFER_CLR(x, v) (HW_PORT_DFER_WR(x, HW_PORT_DFER_RD(x) & ~(v))) #define HW_PORT_DFER_TOG(x, v) (HW_PORT_DFER_WR(x, HW_PORT_DFER_RD(x) ^ (v))) /*@}*/ /* * Constants & macros for individual PORT_DFER bitfields */ /*! * @name Register PORT_DFER, field DFE[31:0] (RW) * * The digital filter configuration is valid in all digital pin muxing modes. * The output of each digital filter is reset to zero at system reset and whenever * the digital filter is disabled. Each bit in the field enables the digital * filter of the same number as the field. * * Values: * - 0 - Digital filter is disabled on the corresponding pin and output of the * digital filter is reset to zero. * - 1 - Digital filter is enabled on the corresponding pin, if the pin is * configured as a digital input. */ /*@{*/ #define BP_PORT_DFER_DFE (0U) /*!< Bit position for PORT_DFER_DFE. */ #define BM_PORT_DFER_DFE (0xFFFFFFFFU) /*!< Bit mask for PORT_DFER_DFE. */ #define BS_PORT_DFER_DFE (32U) /*!< Bit field size in bits for PORT_DFER_DFE. */ /*! @brief Read current value of the PORT_DFER_DFE field. */ #define BR_PORT_DFER_DFE(x) (HW_PORT_DFER(x).U) /*! @brief Format value for bitfield PORT_DFER_DFE. */ #define BF_PORT_DFER_DFE(v) ((uint32_t)((uint32_t)(v) << BP_PORT_DFER_DFE) & BM_PORT_DFER_DFE) /*! @brief Set the DFE field to a new value. */ #define BW_PORT_DFER_DFE(x, v) (HW_PORT_DFER_WR(x, v)) /*@}*/ /******************************************************************************* * HW_PORT_DFCR - Digital Filter Clock Register ******************************************************************************/ /*! * @brief HW_PORT_DFCR - Digital Filter Clock Register (RW) * * Reset value: 0x00000000U * * This register is read only for ports that do not support a digital filter. * The digital filter configuration is valid in all digital pin muxing modes. */ typedef union _hw_port_dfcr { uint32_t U; struct _hw_port_dfcr_bitfields { uint32_t CS : 1; /*!< [0] Clock Source */ uint32_t RESERVED0 : 31; /*!< [31:1] */ } B; } hw_port_dfcr_t; /*! * @name Constants and macros for entire PORT_DFCR register */ /*@{*/ #define HW_PORT_DFCR_ADDR(x) ((x) + 0xC4U) #define HW_PORT_DFCR(x) (*(__IO hw_port_dfcr_t *) HW_PORT_DFCR_ADDR(x)) #define HW_PORT_DFCR_RD(x) (HW_PORT_DFCR(x).U) #define HW_PORT_DFCR_WR(x, v) (HW_PORT_DFCR(x).U = (v)) #define HW_PORT_DFCR_SET(x, v) (HW_PORT_DFCR_WR(x, HW_PORT_DFCR_RD(x) | (v))) #define HW_PORT_DFCR_CLR(x, v) (HW_PORT_DFCR_WR(x, HW_PORT_DFCR_RD(x) & ~(v))) #define HW_PORT_DFCR_TOG(x, v) (HW_PORT_DFCR_WR(x, HW_PORT_DFCR_RD(x) ^ (v))) /*@}*/ /* * Constants & macros for individual PORT_DFCR bitfields */ /*! * @name Register PORT_DFCR, field CS[0] (RW) * * The digital filter configuration is valid in all digital pin muxing modes. * Configures the clock source for the digital input filters. Changing the filter * clock source must be done only when all digital filters are disabled. * * Values: * - 0 - Digital filters are clocked by the bus clock. * - 1 - Digital filters are clocked by the 1 kHz LPO clock. */ /*@{*/ #define BP_PORT_DFCR_CS (0U) /*!< Bit position for PORT_DFCR_CS. */ #define BM_PORT_DFCR_CS (0x00000001U) /*!< Bit mask for PORT_DFCR_CS. */ #define BS_PORT_DFCR_CS (1U) /*!< Bit field size in bits for PORT_DFCR_CS. */ /*! @brief Read current value of the PORT_DFCR_CS field. */ #define BR_PORT_DFCR_CS(x) (BITBAND_ACCESS32(HW_PORT_DFCR_ADDR(x), BP_PORT_DFCR_CS)) /*! @brief Format value for bitfield PORT_DFCR_CS. */ #define BF_PORT_DFCR_CS(v) ((uint32_t)((uint32_t)(v) << BP_PORT_DFCR_CS) & BM_PORT_DFCR_CS) /*! @brief Set the CS field to a new value. */ #define BW_PORT_DFCR_CS(x, v) (BITBAND_ACCESS32(HW_PORT_DFCR_ADDR(x), BP_PORT_DFCR_CS) = (v)) /*@}*/ /******************************************************************************* * HW_PORT_DFWR - Digital Filter Width Register ******************************************************************************/ /*! * @brief HW_PORT_DFWR - Digital Filter Width Register (RW) * * Reset value: 0x00000000U * * This register is read only for ports that do not support a digital filter. * The digital filter configuration is valid in all digital pin muxing modes. */ typedef union _hw_port_dfwr { uint32_t U; struct _hw_port_dfwr_bitfields { uint32_t FILT : 5; /*!< [4:0] Filter Length */ uint32_t RESERVED0 : 27; /*!< [31:5] */ } B; } hw_port_dfwr_t; /*! * @name Constants and macros for entire PORT_DFWR register */ /*@{*/ #define HW_PORT_DFWR_ADDR(x) ((x) + 0xC8U) #define HW_PORT_DFWR(x) (*(__IO hw_port_dfwr_t *) HW_PORT_DFWR_ADDR(x)) #define HW_PORT_DFWR_RD(x) (HW_PORT_DFWR(x).U) #define HW_PORT_DFWR_WR(x, v) (HW_PORT_DFWR(x).U = (v)) #define HW_PORT_DFWR_SET(x, v) (HW_PORT_DFWR_WR(x, HW_PORT_DFWR_RD(x) | (v))) #define HW_PORT_DFWR_CLR(x, v) (HW_PORT_DFWR_WR(x, HW_PORT_DFWR_RD(x) & ~(v))) #define HW_PORT_DFWR_TOG(x, v) (HW_PORT_DFWR_WR(x, HW_PORT_DFWR_RD(x) ^ (v))) /*@}*/ /* * Constants & macros for individual PORT_DFWR bitfields */ /*! * @name Register PORT_DFWR, field FILT[4:0] (RW) * * The digital filter configuration is valid in all digital pin muxing modes. * Configures the maximum size of the glitches, in clock cycles, that the digital * filter absorbs for the enabled digital filters. Glitches that are longer than * this register setting will pass through the digital filter, and glitches that * are equal to or less than this register setting are filtered. Changing the * filter length must be done only after all filters are disabled. */ /*@{*/ #define BP_PORT_DFWR_FILT (0U) /*!< Bit position for PORT_DFWR_FILT. */ #define BM_PORT_DFWR_FILT (0x0000001FU) /*!< Bit mask for PORT_DFWR_FILT. */ #define BS_PORT_DFWR_FILT (5U) /*!< Bit field size in bits for PORT_DFWR_FILT. */ /*! @brief Read current value of the PORT_DFWR_FILT field. */ #define BR_PORT_DFWR_FILT(x) (HW_PORT_DFWR(x).B.FILT) /*! @brief Format value for bitfield PORT_DFWR_FILT. */ #define BF_PORT_DFWR_FILT(v) ((uint32_t)((uint32_t)(v) << BP_PORT_DFWR_FILT) & BM_PORT_DFWR_FILT) /*! @brief Set the FILT field to a new value. */ #define BW_PORT_DFWR_FILT(x, v) (HW_PORT_DFWR_WR(x, (HW_PORT_DFWR_RD(x) & ~BM_PORT_DFWR_FILT) | BF_PORT_DFWR_FILT(v))) /*@}*/ /******************************************************************************* * hw_port_t - module struct ******************************************************************************/ /*! * @brief All PORT module registers. */ #pragma pack(1) typedef struct _hw_port { __IO hw_port_pcrn_t PCRn[32]; /*!< [0x0] Pin Control Register n */ __O hw_port_gpclr_t GPCLR; /*!< [0x80] Global Pin Control Low Register */ __O hw_port_gpchr_t GPCHR; /*!< [0x84] Global Pin Control High Register */ uint8_t _reserved0[24]; __IO hw_port_isfr_t ISFR; /*!< [0xA0] Interrupt Status Flag Register */ uint8_t _reserved1[28]; __IO hw_port_dfer_t DFER; /*!< [0xC0] Digital Filter Enable Register */ __IO hw_port_dfcr_t DFCR; /*!< [0xC4] Digital Filter Clock Register */ __IO hw_port_dfwr_t DFWR; /*!< [0xC8] Digital Filter Width Register */ } hw_port_t; #pragma pack() /*! @brief Macro to access all PORT registers. */ /*! @param x PORT module instance base address. */ /*! @return Reference (not a pointer) to the registers struct. To get a pointer to the struct, * use the '&' operator, like &HW_PORT(PORTA_BASE). */ #define HW_PORT(x) (*(hw_port_t *)(x)) #endif /* __HW_PORT_REGISTERS_H__ */ /* EOF */ ================================================ FILE: Zelig/mbed/TARGET_K64F/TARGET_Freescale/TARGET_KPSDK_MCUS/TARGET_MCU_K64F/device/device/MK64F12/MK64F12_rcm.h ================================================ /* ** ################################################################### ** Compilers: Keil ARM C/C++ Compiler ** Freescale C/C++ for Embedded ARM ** GNU C Compiler ** IAR ANSI C/C++ Compiler for ARM ** ** Reference manual: K64P144M120SF5RM, Rev.2, January 2014 ** Version: rev. 2.5, 2014-02-10 ** Build: b140604 ** ** Abstract: ** Extension to the CMSIS register access layer header. ** ** Copyright (c) 2014 Freescale Semiconductor, Inc. ** All rights reserved. ** ** Redistribution and use in source and binary forms, with or without modification, ** are permitted provided that the following conditions are met: ** ** o Redistributions of source code must retain the above copyright notice, this list ** of conditions and the following disclaimer. ** ** o Redistributions in binary form must reproduce the above copyright notice, this ** list of conditions and the following disclaimer in the documentation and/or ** other materials provided with the distribution. ** ** o Neither the name of Freescale Semiconductor, Inc. nor the names of its ** contributors may be used to endorse or promote products derived from this ** software without specific prior written permission. ** ** THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ** ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED ** WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE ** DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT 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. ** ** http: www.freescale.com ** mail: support@freescale.com ** ** Revisions: ** - rev. 1.0 (2013-08-12) ** Initial version. ** - rev. 2.0 (2013-10-29) ** Register accessor macros added to the memory map. ** Symbols for Processor Expert memory map compatibility added to the memory map. ** Startup file for gcc has been updated according to CMSIS 3.2. ** System initialization updated. ** MCG - registers updated. ** PORTA, PORTB, PORTC, PORTE - registers for digital filter removed. ** - rev. 2.1 (2013-10-30) ** Definition of BITBAND macros updated to support peripherals with 32-bit acces disabled. ** - rev. 2.2 (2013-12-09) ** DMA - EARS register removed. ** AIPS0, AIPS1 - MPRA register updated. ** - rev. 2.3 (2014-01-24) ** Update according to reference manual rev. 2 ** ENET, MCG, MCM, SIM, USB - registers updated ** - rev. 2.4 (2014-02-10) ** The declaration of clock configurations has been moved to separate header file system_MK64F12.h ** Update of SystemInit() and SystemCoreClockUpdate() functions. ** - rev. 2.5 (2014-02-10) ** The declaration of clock configurations has been moved to separate header file system_MK64F12.h ** Update of SystemInit() and SystemCoreClockUpdate() functions. ** Module access macro module_BASES replaced by module_BASE_PTRS. ** ** ################################################################### */ /* * WARNING! DO NOT EDIT THIS FILE DIRECTLY! * * This file was generated automatically and any changes may be lost. */ #ifndef __HW_RCM_REGISTERS_H__ #define __HW_RCM_REGISTERS_H__ #include "MK64F12.h" #include "fsl_bitaccess.h" /* * MK64F12 RCM * * Reset Control Module * * Registers defined in this header file: * - HW_RCM_SRS0 - System Reset Status Register 0 * - HW_RCM_SRS1 - System Reset Status Register 1 * - HW_RCM_RPFC - Reset Pin Filter Control register * - HW_RCM_RPFW - Reset Pin Filter Width register * - HW_RCM_MR - Mode Register * * - hw_rcm_t - Struct containing all module registers. */ #define HW_RCM_INSTANCE_COUNT (1U) /*!< Number of instances of the RCM module. */ /******************************************************************************* * HW_RCM_SRS0 - System Reset Status Register 0 ******************************************************************************/ /*! * @brief HW_RCM_SRS0 - System Reset Status Register 0 (RO) * * Reset value: 0x82U * * This register includes read-only status flags to indicate the source of the * most recent reset. The reset state of these bits depends on what caused the MCU * to reset. The reset value of this register depends on the reset source: POR * (including LVD) - 0x82 LVD (without POR) - 0x02 VLLS mode wakeup due to RESET * pin assertion - 0x41 VLLS mode wakeup due to other wakeup sources - 0x01 Other * reset - a bit is set if its corresponding reset source caused the reset */ typedef union _hw_rcm_srs0 { uint8_t U; struct _hw_rcm_srs0_bitfields { uint8_t WAKEUP : 1; /*!< [0] Low Leakage Wakeup Reset */ uint8_t LVD : 1; /*!< [1] Low-Voltage Detect Reset */ uint8_t LOC : 1; /*!< [2] Loss-of-Clock Reset */ uint8_t LOL : 1; /*!< [3] Loss-of-Lock Reset */ uint8_t RESERVED0 : 1; /*!< [4] */ uint8_t WDOGb : 1; /*!< [5] Watchdog */ uint8_t PIN : 1; /*!< [6] External Reset Pin */ uint8_t POR : 1; /*!< [7] Power-On Reset */ } B; } hw_rcm_srs0_t; /*! * @name Constants and macros for entire RCM_SRS0 register */ /*@{*/ #define HW_RCM_SRS0_ADDR(x) ((x) + 0x0U) #define HW_RCM_SRS0(x) (*(__I hw_rcm_srs0_t *) HW_RCM_SRS0_ADDR(x)) #define HW_RCM_SRS0_RD(x) (HW_RCM_SRS0(x).U) /*@}*/ /* * Constants & macros for individual RCM_SRS0 bitfields */ /*! * @name Register RCM_SRS0, field WAKEUP[0] (RO) * * Indicates a reset has been caused by an enabled LLWU module wakeup source * while the chip was in a low leakage mode. In LLS mode, the RESET pin is the only * wakeup source that can cause this reset. Any enabled wakeup source in a VLLSx * mode causes a reset. This bit is cleared by any reset except WAKEUP. * * Values: * - 0 - Reset not caused by LLWU module wakeup source * - 1 - Reset caused by LLWU module wakeup source */ /*@{*/ #define BP_RCM_SRS0_WAKEUP (0U) /*!< Bit position for RCM_SRS0_WAKEUP. */ #define BM_RCM_SRS0_WAKEUP (0x01U) /*!< Bit mask for RCM_SRS0_WAKEUP. */ #define BS_RCM_SRS0_WAKEUP (1U) /*!< Bit field size in bits for RCM_SRS0_WAKEUP. */ /*! @brief Read current value of the RCM_SRS0_WAKEUP field. */ #define BR_RCM_SRS0_WAKEUP(x) (BITBAND_ACCESS8(HW_RCM_SRS0_ADDR(x), BP_RCM_SRS0_WAKEUP)) /*@}*/ /*! * @name Register RCM_SRS0, field LVD[1] (RO) * * If PMC_LVDSC1[LVDRE] is set and the supply drops below the LVD trip voltage, * an LVD reset occurs. This field is also set by POR. * * Values: * - 0 - Reset not caused by LVD trip or POR * - 1 - Reset caused by LVD trip or POR */ /*@{*/ #define BP_RCM_SRS0_LVD (1U) /*!< Bit position for RCM_SRS0_LVD. */ #define BM_RCM_SRS0_LVD (0x02U) /*!< Bit mask for RCM_SRS0_LVD. */ #define BS_RCM_SRS0_LVD (1U) /*!< Bit field size in bits for RCM_SRS0_LVD. */ /*! @brief Read current value of the RCM_SRS0_LVD field. */ #define BR_RCM_SRS0_LVD(x) (BITBAND_ACCESS8(HW_RCM_SRS0_ADDR(x), BP_RCM_SRS0_LVD)) /*@}*/ /*! * @name Register RCM_SRS0, field LOC[2] (RO) * * Indicates a reset has been caused by a loss of external clock. The MCG clock * monitor must be enabled for a loss of clock to be detected. Refer to the * detailed MCG description for information on enabling the clock monitor. * * Values: * - 0 - Reset not caused by a loss of external clock. * - 1 - Reset caused by a loss of external clock. */ /*@{*/ #define BP_RCM_SRS0_LOC (2U) /*!< Bit position for RCM_SRS0_LOC. */ #define BM_RCM_SRS0_LOC (0x04U) /*!< Bit mask for RCM_SRS0_LOC. */ #define BS_RCM_SRS0_LOC (1U) /*!< Bit field size in bits for RCM_SRS0_LOC. */ /*! @brief Read current value of the RCM_SRS0_LOC field. */ #define BR_RCM_SRS0_LOC(x) (BITBAND_ACCESS8(HW_RCM_SRS0_ADDR(x), BP_RCM_SRS0_LOC)) /*@}*/ /*! * @name Register RCM_SRS0, field LOL[3] (RO) * * Indicates a reset has been caused by a loss of lock in the MCG PLL. See the * MCG description for information on the loss-of-clock event. * * Values: * - 0 - Reset not caused by a loss of lock in the PLL * - 1 - Reset caused by a loss of lock in the PLL */ /*@{*/ #define BP_RCM_SRS0_LOL (3U) /*!< Bit position for RCM_SRS0_LOL. */ #define BM_RCM_SRS0_LOL (0x08U) /*!< Bit mask for RCM_SRS0_LOL. */ #define BS_RCM_SRS0_LOL (1U) /*!< Bit field size in bits for RCM_SRS0_LOL. */ /*! @brief Read current value of the RCM_SRS0_LOL field. */ #define BR_RCM_SRS0_LOL(x) (BITBAND_ACCESS8(HW_RCM_SRS0_ADDR(x), BP_RCM_SRS0_LOL)) /*@}*/ /*! * @name Register RCM_SRS0, field WDOG[5] (RO) * * Indicates a reset has been caused by the watchdog timer Computer Operating * Properly (COP) timing out. This reset source can be blocked by disabling the COP * watchdog: write 00 to SIM_COPCTRL[COPT]. * * Values: * - 0 - Reset not caused by watchdog timeout * - 1 - Reset caused by watchdog timeout */ /*@{*/ #define BP_RCM_SRS0_WDOG (5U) /*!< Bit position for RCM_SRS0_WDOG. */ #define BM_RCM_SRS0_WDOG (0x20U) /*!< Bit mask for RCM_SRS0_WDOG. */ #define BS_RCM_SRS0_WDOG (1U) /*!< Bit field size in bits for RCM_SRS0_WDOG. */ /*! @brief Read current value of the RCM_SRS0_WDOG field. */ #define BR_RCM_SRS0_WDOG(x) (BITBAND_ACCESS8(HW_RCM_SRS0_ADDR(x), BP_RCM_SRS0_WDOG)) /*@}*/ /*! * @name Register RCM_SRS0, field PIN[6] (RO) * * Indicates a reset has been caused by an active-low level on the external * RESET pin. * * Values: * - 0 - Reset not caused by external reset pin * - 1 - Reset caused by external reset pin */ /*@{*/ #define BP_RCM_SRS0_PIN (6U) /*!< Bit position for RCM_SRS0_PIN. */ #define BM_RCM_SRS0_PIN (0x40U) /*!< Bit mask for RCM_SRS0_PIN. */ #define BS_RCM_SRS0_PIN (1U) /*!< Bit field size in bits for RCM_SRS0_PIN. */ /*! @brief Read current value of the RCM_SRS0_PIN field. */ #define BR_RCM_SRS0_PIN(x) (BITBAND_ACCESS8(HW_RCM_SRS0_ADDR(x), BP_RCM_SRS0_PIN)) /*@}*/ /*! * @name Register RCM_SRS0, field POR[7] (RO) * * Indicates a reset has been caused by the power-on detection logic. Because * the internal supply voltage was ramping up at the time, the low-voltage reset * (LVD) status bit is also set to indicate that the reset occurred while the * internal supply was below the LVD threshold. * * Values: * - 0 - Reset not caused by POR * - 1 - Reset caused by POR */ /*@{*/ #define BP_RCM_SRS0_POR (7U) /*!< Bit position for RCM_SRS0_POR. */ #define BM_RCM_SRS0_POR (0x80U) /*!< Bit mask for RCM_SRS0_POR. */ #define BS_RCM_SRS0_POR (1U) /*!< Bit field size in bits for RCM_SRS0_POR. */ /*! @brief Read current value of the RCM_SRS0_POR field. */ #define BR_RCM_SRS0_POR(x) (BITBAND_ACCESS8(HW_RCM_SRS0_ADDR(x), BP_RCM_SRS0_POR)) /*@}*/ /******************************************************************************* * HW_RCM_SRS1 - System Reset Status Register 1 ******************************************************************************/ /*! * @brief HW_RCM_SRS1 - System Reset Status Register 1 (RO) * * Reset value: 0x00U * * This register includes read-only status flags to indicate the source of the * most recent reset. The reset state of these bits depends on what caused the MCU * to reset. The reset value of this register depends on the reset source: POR * (including LVD) - 0x00 LVD (without POR) - 0x00 VLLS mode wakeup - 0x00 Other * reset - a bit is set if its corresponding reset source caused the reset */ typedef union _hw_rcm_srs1 { uint8_t U; struct _hw_rcm_srs1_bitfields { uint8_t JTAG : 1; /*!< [0] JTAG Generated Reset */ uint8_t LOCKUP : 1; /*!< [1] Core Lockup */ uint8_t SW : 1; /*!< [2] Software */ uint8_t MDM_AP : 1; /*!< [3] MDM-AP System Reset Request */ uint8_t EZPT : 1; /*!< [4] EzPort Reset */ uint8_t SACKERR : 1; /*!< [5] Stop Mode Acknowledge Error Reset */ uint8_t RESERVED0 : 2; /*!< [7:6] */ } B; } hw_rcm_srs1_t; /*! * @name Constants and macros for entire RCM_SRS1 register */ /*@{*/ #define HW_RCM_SRS1_ADDR(x) ((x) + 0x1U) #define HW_RCM_SRS1(x) (*(__I hw_rcm_srs1_t *) HW_RCM_SRS1_ADDR(x)) #define HW_RCM_SRS1_RD(x) (HW_RCM_SRS1(x).U) /*@}*/ /* * Constants & macros for individual RCM_SRS1 bitfields */ /*! * @name Register RCM_SRS1, field JTAG[0] (RO) * * Indicates a reset has been caused by JTAG selection of certain IR codes: * EZPORT, EXTEST, HIGHZ, and CLAMP. * * Values: * - 0 - Reset not caused by JTAG * - 1 - Reset caused by JTAG */ /*@{*/ #define BP_RCM_SRS1_JTAG (0U) /*!< Bit position for RCM_SRS1_JTAG. */ #define BM_RCM_SRS1_JTAG (0x01U) /*!< Bit mask for RCM_SRS1_JTAG. */ #define BS_RCM_SRS1_JTAG (1U) /*!< Bit field size in bits for RCM_SRS1_JTAG. */ /*! @brief Read current value of the RCM_SRS1_JTAG field. */ #define BR_RCM_SRS1_JTAG(x) (BITBAND_ACCESS8(HW_RCM_SRS1_ADDR(x), BP_RCM_SRS1_JTAG)) /*@}*/ /*! * @name Register RCM_SRS1, field LOCKUP[1] (RO) * * Indicates a reset has been caused by the ARM core indication of a LOCKUP * event. * * Values: * - 0 - Reset not caused by core LOCKUP event * - 1 - Reset caused by core LOCKUP event */ /*@{*/ #define BP_RCM_SRS1_LOCKUP (1U) /*!< Bit position for RCM_SRS1_LOCKUP. */ #define BM_RCM_SRS1_LOCKUP (0x02U) /*!< Bit mask for RCM_SRS1_LOCKUP. */ #define BS_RCM_SRS1_LOCKUP (1U) /*!< Bit field size in bits for RCM_SRS1_LOCKUP. */ /*! @brief Read current value of the RCM_SRS1_LOCKUP field. */ #define BR_RCM_SRS1_LOCKUP(x) (BITBAND_ACCESS8(HW_RCM_SRS1_ADDR(x), BP_RCM_SRS1_LOCKUP)) /*@}*/ /*! * @name Register RCM_SRS1, field SW[2] (RO) * * Indicates a reset has been caused by software setting of SYSRESETREQ bit in * Application Interrupt and Reset Control Register in the ARM core. * * Values: * - 0 - Reset not caused by software setting of SYSRESETREQ bit * - 1 - Reset caused by software setting of SYSRESETREQ bit */ /*@{*/ #define BP_RCM_SRS1_SW (2U) /*!< Bit position for RCM_SRS1_SW. */ #define BM_RCM_SRS1_SW (0x04U) /*!< Bit mask for RCM_SRS1_SW. */ #define BS_RCM_SRS1_SW (1U) /*!< Bit field size in bits for RCM_SRS1_SW. */ /*! @brief Read current value of the RCM_SRS1_SW field. */ #define BR_RCM_SRS1_SW(x) (BITBAND_ACCESS8(HW_RCM_SRS1_ADDR(x), BP_RCM_SRS1_SW)) /*@}*/ /*! * @name Register RCM_SRS1, field MDM_AP[3] (RO) * * Indicates a reset has been caused by the host debugger system setting of the * System Reset Request bit in the MDM-AP Control Register. * * Values: * - 0 - Reset not caused by host debugger system setting of the System Reset * Request bit * - 1 - Reset caused by host debugger system setting of the System Reset * Request bit */ /*@{*/ #define BP_RCM_SRS1_MDM_AP (3U) /*!< Bit position for RCM_SRS1_MDM_AP. */ #define BM_RCM_SRS1_MDM_AP (0x08U) /*!< Bit mask for RCM_SRS1_MDM_AP. */ #define BS_RCM_SRS1_MDM_AP (1U) /*!< Bit field size in bits for RCM_SRS1_MDM_AP. */ /*! @brief Read current value of the RCM_SRS1_MDM_AP field. */ #define BR_RCM_SRS1_MDM_AP(x) (BITBAND_ACCESS8(HW_RCM_SRS1_ADDR(x), BP_RCM_SRS1_MDM_AP)) /*@}*/ /*! * @name Register RCM_SRS1, field EZPT[4] (RO) * * Indicates a reset has been caused by EzPort receiving the RESET command while * the device is in EzPort mode. * * Values: * - 0 - Reset not caused by EzPort receiving the RESET command while the device * is in EzPort mode * - 1 - Reset caused by EzPort receiving the RESET command while the device is * in EzPort mode */ /*@{*/ #define BP_RCM_SRS1_EZPT (4U) /*!< Bit position for RCM_SRS1_EZPT. */ #define BM_RCM_SRS1_EZPT (0x10U) /*!< Bit mask for RCM_SRS1_EZPT. */ #define BS_RCM_SRS1_EZPT (1U) /*!< Bit field size in bits for RCM_SRS1_EZPT. */ /*! @brief Read current value of the RCM_SRS1_EZPT field. */ #define BR_RCM_SRS1_EZPT(x) (BITBAND_ACCESS8(HW_RCM_SRS1_ADDR(x), BP_RCM_SRS1_EZPT)) /*@}*/ /*! * @name Register RCM_SRS1, field SACKERR[5] (RO) * * Indicates that after an attempt to enter Stop mode, a reset has been caused * by a failure of one or more peripherals to acknowledge within approximately one * second to enter stop mode. * * Values: * - 0 - Reset not caused by peripheral failure to acknowledge attempt to enter * stop mode * - 1 - Reset caused by peripheral failure to acknowledge attempt to enter stop * mode */ /*@{*/ #define BP_RCM_SRS1_SACKERR (5U) /*!< Bit position for RCM_SRS1_SACKERR. */ #define BM_RCM_SRS1_SACKERR (0x20U) /*!< Bit mask for RCM_SRS1_SACKERR. */ #define BS_RCM_SRS1_SACKERR (1U) /*!< Bit field size in bits for RCM_SRS1_SACKERR. */ /*! @brief Read current value of the RCM_SRS1_SACKERR field. */ #define BR_RCM_SRS1_SACKERR(x) (BITBAND_ACCESS8(HW_RCM_SRS1_ADDR(x), BP_RCM_SRS1_SACKERR)) /*@}*/ /******************************************************************************* * HW_RCM_RPFC - Reset Pin Filter Control register ******************************************************************************/ /*! * @brief HW_RCM_RPFC - Reset Pin Filter Control register (RW) * * Reset value: 0x00U * * The reset values of bits 2-0 are for Chip POR only. They are unaffected by * other reset types. The bus clock filter is reset when disabled or when entering * stop mode. The LPO filter is reset when disabled or when entering any low * leakage stop mode . */ typedef union _hw_rcm_rpfc { uint8_t U; struct _hw_rcm_rpfc_bitfields { uint8_t RSTFLTSRW : 2; /*!< [1:0] Reset Pin Filter Select in Run and * Wait Modes */ uint8_t RSTFLTSS : 1; /*!< [2] Reset Pin Filter Select in Stop Mode */ uint8_t RESERVED0 : 5; /*!< [7:3] */ } B; } hw_rcm_rpfc_t; /*! * @name Constants and macros for entire RCM_RPFC register */ /*@{*/ #define HW_RCM_RPFC_ADDR(x) ((x) + 0x4U) #define HW_RCM_RPFC(x) (*(__IO hw_rcm_rpfc_t *) HW_RCM_RPFC_ADDR(x)) #define HW_RCM_RPFC_RD(x) (HW_RCM_RPFC(x).U) #define HW_RCM_RPFC_WR(x, v) (HW_RCM_RPFC(x).U = (v)) #define HW_RCM_RPFC_SET(x, v) (HW_RCM_RPFC_WR(x, HW_RCM_RPFC_RD(x) | (v))) #define HW_RCM_RPFC_CLR(x, v) (HW_RCM_RPFC_WR(x, HW_RCM_RPFC_RD(x) & ~(v))) #define HW_RCM_RPFC_TOG(x, v) (HW_RCM_RPFC_WR(x, HW_RCM_RPFC_RD(x) ^ (v))) /*@}*/ /* * Constants & macros for individual RCM_RPFC bitfields */ /*! * @name Register RCM_RPFC, field RSTFLTSRW[1:0] (RW) * * Selects how the reset pin filter is enabled in run and wait modes. * * Values: * - 00 - All filtering disabled * - 01 - Bus clock filter enabled for normal operation * - 10 - LPO clock filter enabled for normal operation * - 11 - Reserved */ /*@{*/ #define BP_RCM_RPFC_RSTFLTSRW (0U) /*!< Bit position for RCM_RPFC_RSTFLTSRW. */ #define BM_RCM_RPFC_RSTFLTSRW (0x03U) /*!< Bit mask for RCM_RPFC_RSTFLTSRW. */ #define BS_RCM_RPFC_RSTFLTSRW (2U) /*!< Bit field size in bits for RCM_RPFC_RSTFLTSRW. */ /*! @brief Read current value of the RCM_RPFC_RSTFLTSRW field. */ #define BR_RCM_RPFC_RSTFLTSRW(x) (HW_RCM_RPFC(x).B.RSTFLTSRW) /*! @brief Format value for bitfield RCM_RPFC_RSTFLTSRW. */ #define BF_RCM_RPFC_RSTFLTSRW(v) ((uint8_t)((uint8_t)(v) << BP_RCM_RPFC_RSTFLTSRW) & BM_RCM_RPFC_RSTFLTSRW) /*! @brief Set the RSTFLTSRW field to a new value. */ #define BW_RCM_RPFC_RSTFLTSRW(x, v) (HW_RCM_RPFC_WR(x, (HW_RCM_RPFC_RD(x) & ~BM_RCM_RPFC_RSTFLTSRW) | BF_RCM_RPFC_RSTFLTSRW(v))) /*@}*/ /*! * @name Register RCM_RPFC, field RSTFLTSS[2] (RW) * * Selects how the reset pin filter is enabled in Stop and VLPS modes * * Values: * - 0 - All filtering disabled * - 1 - LPO clock filter enabled */ /*@{*/ #define BP_RCM_RPFC_RSTFLTSS (2U) /*!< Bit position for RCM_RPFC_RSTFLTSS. */ #define BM_RCM_RPFC_RSTFLTSS (0x04U) /*!< Bit mask for RCM_RPFC_RSTFLTSS. */ #define BS_RCM_RPFC_RSTFLTSS (1U) /*!< Bit field size in bits for RCM_RPFC_RSTFLTSS. */ /*! @brief Read current value of the RCM_RPFC_RSTFLTSS field. */ #define BR_RCM_RPFC_RSTFLTSS(x) (BITBAND_ACCESS8(HW_RCM_RPFC_ADDR(x), BP_RCM_RPFC_RSTFLTSS)) /*! @brief Format value for bitfield RCM_RPFC_RSTFLTSS. */ #define BF_RCM_RPFC_RSTFLTSS(v) ((uint8_t)((uint8_t)(v) << BP_RCM_RPFC_RSTFLTSS) & BM_RCM_RPFC_RSTFLTSS) /*! @brief Set the RSTFLTSS field to a new value. */ #define BW_RCM_RPFC_RSTFLTSS(x, v) (BITBAND_ACCESS8(HW_RCM_RPFC_ADDR(x), BP_RCM_RPFC_RSTFLTSS) = (v)) /*@}*/ /******************************************************************************* * HW_RCM_RPFW - Reset Pin Filter Width register ******************************************************************************/ /*! * @brief HW_RCM_RPFW - Reset Pin Filter Width register (RW) * * Reset value: 0x00U * * The reset values of the bits in the RSTFLTSEL field are for Chip POR only. * They are unaffected by other reset types. */ typedef union _hw_rcm_rpfw { uint8_t U; struct _hw_rcm_rpfw_bitfields { uint8_t RSTFLTSEL : 5; /*!< [4:0] Reset Pin Filter Bus Clock Select */ uint8_t RESERVED0 : 3; /*!< [7:5] */ } B; } hw_rcm_rpfw_t; /*! * @name Constants and macros for entire RCM_RPFW register */ /*@{*/ #define HW_RCM_RPFW_ADDR(x) ((x) + 0x5U) #define HW_RCM_RPFW(x) (*(__IO hw_rcm_rpfw_t *) HW_RCM_RPFW_ADDR(x)) #define HW_RCM_RPFW_RD(x) (HW_RCM_RPFW(x).U) #define HW_RCM_RPFW_WR(x, v) (HW_RCM_RPFW(x).U = (v)) #define HW_RCM_RPFW_SET(x, v) (HW_RCM_RPFW_WR(x, HW_RCM_RPFW_RD(x) | (v))) #define HW_RCM_RPFW_CLR(x, v) (HW_RCM_RPFW_WR(x, HW_RCM_RPFW_RD(x) & ~(v))) #define HW_RCM_RPFW_TOG(x, v) (HW_RCM_RPFW_WR(x, HW_RCM_RPFW_RD(x) ^ (v))) /*@}*/ /* * Constants & macros for individual RCM_RPFW bitfields */ /*! * @name Register RCM_RPFW, field RSTFLTSEL[4:0] (RW) * * Selects the reset pin bus clock filter width. * * Values: * - 00000 - Bus clock filter count is 1 * - 00001 - Bus clock filter count is 2 * - 00010 - Bus clock filter count is 3 * - 00011 - Bus clock filter count is 4 * - 00100 - Bus clock filter count is 5 * - 00101 - Bus clock filter count is 6 * - 00110 - Bus clock filter count is 7 * - 00111 - Bus clock filter count is 8 * - 01000 - Bus clock filter count is 9 * - 01001 - Bus clock filter count is 10 * - 01010 - Bus clock filter count is 11 * - 01011 - Bus clock filter count is 12 * - 01100 - Bus clock filter count is 13 * - 01101 - Bus clock filter count is 14 * - 01110 - Bus clock filter count is 15 * - 01111 - Bus clock filter count is 16 * - 10000 - Bus clock filter count is 17 * - 10001 - Bus clock filter count is 18 * - 10010 - Bus clock filter count is 19 * - 10011 - Bus clock filter count is 20 * - 10100 - Bus clock filter count is 21 * - 10101 - Bus clock filter count is 22 * - 10110 - Bus clock filter count is 23 * - 10111 - Bus clock filter count is 24 * - 11000 - Bus clock filter count is 25 * - 11001 - Bus clock filter count is 26 * - 11010 - Bus clock filter count is 27 * - 11011 - Bus clock filter count is 28 * - 11100 - Bus clock filter count is 29 * - 11101 - Bus clock filter count is 30 * - 11110 - Bus clock filter count is 31 * - 11111 - Bus clock filter count is 32 */ /*@{*/ #define BP_RCM_RPFW_RSTFLTSEL (0U) /*!< Bit position for RCM_RPFW_RSTFLTSEL. */ #define BM_RCM_RPFW_RSTFLTSEL (0x1FU) /*!< Bit mask for RCM_RPFW_RSTFLTSEL. */ #define BS_RCM_RPFW_RSTFLTSEL (5U) /*!< Bit field size in bits for RCM_RPFW_RSTFLTSEL. */ /*! @brief Read current value of the RCM_RPFW_RSTFLTSEL field. */ #define BR_RCM_RPFW_RSTFLTSEL(x) (HW_RCM_RPFW(x).B.RSTFLTSEL) /*! @brief Format value for bitfield RCM_RPFW_RSTFLTSEL. */ #define BF_RCM_RPFW_RSTFLTSEL(v) ((uint8_t)((uint8_t)(v) << BP_RCM_RPFW_RSTFLTSEL) & BM_RCM_RPFW_RSTFLTSEL) /*! @brief Set the RSTFLTSEL field to a new value. */ #define BW_RCM_RPFW_RSTFLTSEL(x, v) (HW_RCM_RPFW_WR(x, (HW_RCM_RPFW_RD(x) & ~BM_RCM_RPFW_RSTFLTSEL) | BF_RCM_RPFW_RSTFLTSEL(v))) /*@}*/ /******************************************************************************* * HW_RCM_MR - Mode Register ******************************************************************************/ /*! * @brief HW_RCM_MR - Mode Register (RO) * * Reset value: 0x00U * * This register includes read-only status flags to indicate the state of the * mode pins during the last Chip Reset. */ typedef union _hw_rcm_mr { uint8_t U; struct _hw_rcm_mr_bitfields { uint8_t RESERVED0 : 1; /*!< [0] */ uint8_t EZP_MS : 1; /*!< [1] EZP_MS_B pin state */ uint8_t RESERVED1 : 6; /*!< [7:2] */ } B; } hw_rcm_mr_t; /*! * @name Constants and macros for entire RCM_MR register */ /*@{*/ #define HW_RCM_MR_ADDR(x) ((x) + 0x7U) #define HW_RCM_MR(x) (*(__I hw_rcm_mr_t *) HW_RCM_MR_ADDR(x)) #define HW_RCM_MR_RD(x) (HW_RCM_MR(x).U) /*@}*/ /* * Constants & macros for individual RCM_MR bitfields */ /*! * @name Register RCM_MR, field EZP_MS[1] (RO) * * Reflects the state of the EZP_MS pin during the last Chip Reset * * Values: * - 0 - Pin deasserted (logic 1) * - 1 - Pin asserted (logic 0) */ /*@{*/ #define BP_RCM_MR_EZP_MS (1U) /*!< Bit position for RCM_MR_EZP_MS. */ #define BM_RCM_MR_EZP_MS (0x02U) /*!< Bit mask for RCM_MR_EZP_MS. */ #define BS_RCM_MR_EZP_MS (1U) /*!< Bit field size in bits for RCM_MR_EZP_MS. */ /*! @brief Read current value of the RCM_MR_EZP_MS field. */ #define BR_RCM_MR_EZP_MS(x) (BITBAND_ACCESS8(HW_RCM_MR_ADDR(x), BP_RCM_MR_EZP_MS)) /*@}*/ /******************************************************************************* * hw_rcm_t - module struct ******************************************************************************/ /*! * @brief All RCM module registers. */ #pragma pack(1) typedef struct _hw_rcm { __I hw_rcm_srs0_t SRS0; /*!< [0x0] System Reset Status Register 0 */ __I hw_rcm_srs1_t SRS1; /*!< [0x1] System Reset Status Register 1 */ uint8_t _reserved0[2]; __IO hw_rcm_rpfc_t RPFC; /*!< [0x4] Reset Pin Filter Control register */ __IO hw_rcm_rpfw_t RPFW; /*!< [0x5] Reset Pin Filter Width register */ uint8_t _reserved1[1]; __I hw_rcm_mr_t MR; /*!< [0x7] Mode Register */ } hw_rcm_t; #pragma pack() /*! @brief Macro to access all RCM registers. */ /*! @param x RCM module instance base address. */ /*! @return Reference (not a pointer) to the registers struct. To get a pointer to the struct, * use the '&' operator, like &HW_RCM(RCM_BASE). */ #define HW_RCM(x) (*(hw_rcm_t *)(x)) #endif /* __HW_RCM_REGISTERS_H__ */ /* EOF */ ================================================ FILE: Zelig/mbed/TARGET_K64F/TARGET_Freescale/TARGET_KPSDK_MCUS/TARGET_MCU_K64F/device/device/MK64F12/MK64F12_rfsys.h ================================================ /* ** ################################################################### ** Compilers: Keil ARM C/C++ Compiler ** Freescale C/C++ for Embedded ARM ** GNU C Compiler ** IAR ANSI C/C++ Compiler for ARM ** ** Reference manual: K64P144M120SF5RM, Rev.2, January 2014 ** Version: rev. 2.5, 2014-02-10 ** Build: b140604 ** ** Abstract: ** Extension to the CMSIS register access layer header. ** ** Copyright (c) 2014 Freescale Semiconductor, Inc. ** All rights reserved. ** ** Redistribution and use in source and binary forms, with or without modification, ** are permitted provided that the following conditions are met: ** ** o Redistributions of source code must retain the above copyright notice, this list ** of conditions and the following disclaimer. ** ** o Redistributions in binary form must reproduce the above copyright notice, this ** list of conditions and the following disclaimer in the documentation and/or ** other materials provided with the distribution. ** ** o Neither the name of Freescale Semiconductor, Inc. nor the names of its ** contributors may be used to endorse or promote products derived from this ** software without specific prior written permission. ** ** THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ** ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED ** WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE ** DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT 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. ** ** http: www.freescale.com ** mail: support@freescale.com ** ** Revisions: ** - rev. 1.0 (2013-08-12) ** Initial version. ** - rev. 2.0 (2013-10-29) ** Register accessor macros added to the memory map. ** Symbols for Processor Expert memory map compatibility added to the memory map. ** Startup file for gcc has been updated according to CMSIS 3.2. ** System initialization updated. ** MCG - registers updated. ** PORTA, PORTB, PORTC, PORTE - registers for digital filter removed. ** - rev. 2.1 (2013-10-30) ** Definition of BITBAND macros updated to support peripherals with 32-bit acces disabled. ** - rev. 2.2 (2013-12-09) ** DMA - EARS register removed. ** AIPS0, AIPS1 - MPRA register updated. ** - rev. 2.3 (2014-01-24) ** Update according to reference manual rev. 2 ** ENET, MCG, MCM, SIM, USB - registers updated ** - rev. 2.4 (2014-02-10) ** The declaration of clock configurations has been moved to separate header file system_MK64F12.h ** Update of SystemInit() and SystemCoreClockUpdate() functions. ** - rev. 2.5 (2014-02-10) ** The declaration of clock configurations has been moved to separate header file system_MK64F12.h ** Update of SystemInit() and SystemCoreClockUpdate() functions. ** Module access macro module_BASES replaced by module_BASE_PTRS. ** ** ################################################################### */ /* * WARNING! DO NOT EDIT THIS FILE DIRECTLY! * * This file was generated automatically and any changes may be lost. */ #ifndef __HW_RFSYS_REGISTERS_H__ #define __HW_RFSYS_REGISTERS_H__ #include "MK64F12.h" #include "fsl_bitaccess.h" /* * MK64F12 RFSYS * * System register file * * Registers defined in this header file: * - HW_RFSYS_REGn - Register file register * * - hw_rfsys_t - Struct containing all module registers. */ #define HW_RFSYS_INSTANCE_COUNT (1U) /*!< Number of instances of the RFSYS module. */ /******************************************************************************* * HW_RFSYS_REGn - Register file register ******************************************************************************/ /*! * @brief HW_RFSYS_REGn - Register file register (RW) * * Reset value: 0x00000000U * * Each register can be accessed as 8-, 16-, or 32-bits. */ typedef union _hw_rfsys_regn { uint32_t U; struct _hw_rfsys_regn_bitfields { uint32_t LL : 8; /*!< [7:0] */ uint32_t LH : 8; /*!< [15:8] */ uint32_t HL : 8; /*!< [23:16] */ uint32_t HH : 8; /*!< [31:24] */ } B; } hw_rfsys_regn_t; /*! * @name Constants and macros for entire RFSYS_REGn register */ /*@{*/ #define HW_RFSYS_REGn_COUNT (8U) #define HW_RFSYS_REGn_ADDR(x, n) ((x) + 0x0U + (0x4U * (n))) #define HW_RFSYS_REGn(x, n) (*(__IO hw_rfsys_regn_t *) HW_RFSYS_REGn_ADDR(x, n)) #define HW_RFSYS_REGn_RD(x, n) (HW_RFSYS_REGn(x, n).U) #define HW_RFSYS_REGn_WR(x, n, v) (HW_RFSYS_REGn(x, n).U = (v)) #define HW_RFSYS_REGn_SET(x, n, v) (HW_RFSYS_REGn_WR(x, n, HW_RFSYS_REGn_RD(x, n) | (v))) #define HW_RFSYS_REGn_CLR(x, n, v) (HW_RFSYS_REGn_WR(x, n, HW_RFSYS_REGn_RD(x, n) & ~(v))) #define HW_RFSYS_REGn_TOG(x, n, v) (HW_RFSYS_REGn_WR(x, n, HW_RFSYS_REGn_RD(x, n) ^ (v))) /*@}*/ /* * Constants & macros for individual RFSYS_REGn bitfields */ /*! * @name Register RFSYS_REGn, field LL[7:0] (RW) * * Low lower byte */ /*@{*/ #define BP_RFSYS_REGn_LL (0U) /*!< Bit position for RFSYS_REGn_LL. */ #define BM_RFSYS_REGn_LL (0x000000FFU) /*!< Bit mask for RFSYS_REGn_LL. */ #define BS_RFSYS_REGn_LL (8U) /*!< Bit field size in bits for RFSYS_REGn_LL. */ /*! @brief Read current value of the RFSYS_REGn_LL field. */ #define BR_RFSYS_REGn_LL(x, n) (HW_RFSYS_REGn(x, n).B.LL) /*! @brief Format value for bitfield RFSYS_REGn_LL. */ #define BF_RFSYS_REGn_LL(v) ((uint32_t)((uint32_t)(v) << BP_RFSYS_REGn_LL) & BM_RFSYS_REGn_LL) /*! @brief Set the LL field to a new value. */ #define BW_RFSYS_REGn_LL(x, n, v) (HW_RFSYS_REGn_WR(x, n, (HW_RFSYS_REGn_RD(x, n) & ~BM_RFSYS_REGn_LL) | BF_RFSYS_REGn_LL(v))) /*@}*/ /*! * @name Register RFSYS_REGn, field LH[15:8] (RW) * * Low higher byte */ /*@{*/ #define BP_RFSYS_REGn_LH (8U) /*!< Bit position for RFSYS_REGn_LH. */ #define BM_RFSYS_REGn_LH (0x0000FF00U) /*!< Bit mask for RFSYS_REGn_LH. */ #define BS_RFSYS_REGn_LH (8U) /*!< Bit field size in bits for RFSYS_REGn_LH. */ /*! @brief Read current value of the RFSYS_REGn_LH field. */ #define BR_RFSYS_REGn_LH(x, n) (HW_RFSYS_REGn(x, n).B.LH) /*! @brief Format value for bitfield RFSYS_REGn_LH. */ #define BF_RFSYS_REGn_LH(v) ((uint32_t)((uint32_t)(v) << BP_RFSYS_REGn_LH) & BM_RFSYS_REGn_LH) /*! @brief Set the LH field to a new value. */ #define BW_RFSYS_REGn_LH(x, n, v) (HW_RFSYS_REGn_WR(x, n, (HW_RFSYS_REGn_RD(x, n) & ~BM_RFSYS_REGn_LH) | BF_RFSYS_REGn_LH(v))) /*@}*/ /*! * @name Register RFSYS_REGn, field HL[23:16] (RW) * * High lower byte */ /*@{*/ #define BP_RFSYS_REGn_HL (16U) /*!< Bit position for RFSYS_REGn_HL. */ #define BM_RFSYS_REGn_HL (0x00FF0000U) /*!< Bit mask for RFSYS_REGn_HL. */ #define BS_RFSYS_REGn_HL (8U) /*!< Bit field size in bits for RFSYS_REGn_HL. */ /*! @brief Read current value of the RFSYS_REGn_HL field. */ #define BR_RFSYS_REGn_HL(x, n) (HW_RFSYS_REGn(x, n).B.HL) /*! @brief Format value for bitfield RFSYS_REGn_HL. */ #define BF_RFSYS_REGn_HL(v) ((uint32_t)((uint32_t)(v) << BP_RFSYS_REGn_HL) & BM_RFSYS_REGn_HL) /*! @brief Set the HL field to a new value. */ #define BW_RFSYS_REGn_HL(x, n, v) (HW_RFSYS_REGn_WR(x, n, (HW_RFSYS_REGn_RD(x, n) & ~BM_RFSYS_REGn_HL) | BF_RFSYS_REGn_HL(v))) /*@}*/ /*! * @name Register RFSYS_REGn, field HH[31:24] (RW) * * High higher byte */ /*@{*/ #define BP_RFSYS_REGn_HH (24U) /*!< Bit position for RFSYS_REGn_HH. */ #define BM_RFSYS_REGn_HH (0xFF000000U) /*!< Bit mask for RFSYS_REGn_HH. */ #define BS_RFSYS_REGn_HH (8U) /*!< Bit field size in bits for RFSYS_REGn_HH. */ /*! @brief Read current value of the RFSYS_REGn_HH field. */ #define BR_RFSYS_REGn_HH(x, n) (HW_RFSYS_REGn(x, n).B.HH) /*! @brief Format value for bitfield RFSYS_REGn_HH. */ #define BF_RFSYS_REGn_HH(v) ((uint32_t)((uint32_t)(v) << BP_RFSYS_REGn_HH) & BM_RFSYS_REGn_HH) /*! @brief Set the HH field to a new value. */ #define BW_RFSYS_REGn_HH(x, n, v) (HW_RFSYS_REGn_WR(x, n, (HW_RFSYS_REGn_RD(x, n) & ~BM_RFSYS_REGn_HH) | BF_RFSYS_REGn_HH(v))) /*@}*/ /******************************************************************************* * hw_rfsys_t - module struct ******************************************************************************/ /*! * @brief All RFSYS module registers. */ #pragma pack(1) typedef struct _hw_rfsys { __IO hw_rfsys_regn_t REGn[8]; /*!< [0x0] Register file register */ } hw_rfsys_t; #pragma pack() /*! @brief Macro to access all RFSYS registers. */ /*! @param x RFSYS module instance base address. */ /*! @return Reference (not a pointer) to the registers struct. To get a pointer to the struct, * use the '&' operator, like &HW_RFSYS(RFSYS_BASE). */ #define HW_RFSYS(x) (*(hw_rfsys_t *)(x)) #endif /* __HW_RFSYS_REGISTERS_H__ */ /* EOF */ ================================================ FILE: Zelig/mbed/TARGET_K64F/TARGET_Freescale/TARGET_KPSDK_MCUS/TARGET_MCU_K64F/device/device/MK64F12/MK64F12_rfvbat.h ================================================ /* ** ################################################################### ** Compilers: Keil ARM C/C++ Compiler ** Freescale C/C++ for Embedded ARM ** GNU C Compiler ** IAR ANSI C/C++ Compiler for ARM ** ** Reference manual: K64P144M120SF5RM, Rev.2, January 2014 ** Version: rev. 2.5, 2014-02-10 ** Build: b140604 ** ** Abstract: ** Extension to the CMSIS register access layer header. ** ** Copyright (c) 2014 Freescale Semiconductor, Inc. ** All rights reserved. ** ** Redistribution and use in source and binary forms, with or without modification, ** are permitted provided that the following conditions are met: ** ** o Redistributions of source code must retain the above copyright notice, this list ** of conditions and the following disclaimer. ** ** o Redistributions in binary form must reproduce the above copyright notice, this ** list of conditions and the following disclaimer in the documentation and/or ** other materials provided with the distribution. ** ** o Neither the name of Freescale Semiconductor, Inc. nor the names of its ** contributors may be used to endorse or promote products derived from this ** software without specific prior written permission. ** ** THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ** ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED ** WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE ** DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT 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. ** ** http: www.freescale.com ** mail: support@freescale.com ** ** Revisions: ** - rev. 1.0 (2013-08-12) ** Initial version. ** - rev. 2.0 (2013-10-29) ** Register accessor macros added to the memory map. ** Symbols for Processor Expert memory map compatibility added to the memory map. ** Startup file for gcc has been updated according to CMSIS 3.2. ** System initialization updated. ** MCG - registers updated. ** PORTA, PORTB, PORTC, PORTE - registers for digital filter removed. ** - rev. 2.1 (2013-10-30) ** Definition of BITBAND macros updated to support peripherals with 32-bit acces disabled. ** - rev. 2.2 (2013-12-09) ** DMA - EARS register removed. ** AIPS0, AIPS1 - MPRA register updated. ** - rev. 2.3 (2014-01-24) ** Update according to reference manual rev. 2 ** ENET, MCG, MCM, SIM, USB - registers updated ** - rev. 2.4 (2014-02-10) ** The declaration of clock configurations has been moved to separate header file system_MK64F12.h ** Update of SystemInit() and SystemCoreClockUpdate() functions. ** - rev. 2.5 (2014-02-10) ** The declaration of clock configurations has been moved to separate header file system_MK64F12.h ** Update of SystemInit() and SystemCoreClockUpdate() functions. ** Module access macro module_BASES replaced by module_BASE_PTRS. ** ** ################################################################### */ /* * WARNING! DO NOT EDIT THIS FILE DIRECTLY! * * This file was generated automatically and any changes may be lost. */ #ifndef __HW_RFVBAT_REGISTERS_H__ #define __HW_RFVBAT_REGISTERS_H__ #include "MK64F12.h" #include "fsl_bitaccess.h" /* * MK64F12 RFVBAT * * VBAT register file * * Registers defined in this header file: * - HW_RFVBAT_REGn - VBAT register file register * * - hw_rfvbat_t - Struct containing all module registers. */ #define HW_RFVBAT_INSTANCE_COUNT (1U) /*!< Number of instances of the RFVBAT module. */ /******************************************************************************* * HW_RFVBAT_REGn - VBAT register file register ******************************************************************************/ /*! * @brief HW_RFVBAT_REGn - VBAT register file register (RW) * * Reset value: 0x00000000U * * Each register can be accessed as 8-, 16-, or 32-bits. */ typedef union _hw_rfvbat_regn { uint32_t U; struct _hw_rfvbat_regn_bitfields { uint32_t LL : 8; /*!< [7:0] */ uint32_t LH : 8; /*!< [15:8] */ uint32_t HL : 8; /*!< [23:16] */ uint32_t HH : 8; /*!< [31:24] */ } B; } hw_rfvbat_regn_t; /*! * @name Constants and macros for entire RFVBAT_REGn register */ /*@{*/ #define HW_RFVBAT_REGn_COUNT (8U) #define HW_RFVBAT_REGn_ADDR(x, n) ((x) + 0x0U + (0x4U * (n))) #define HW_RFVBAT_REGn(x, n) (*(__IO hw_rfvbat_regn_t *) HW_RFVBAT_REGn_ADDR(x, n)) #define HW_RFVBAT_REGn_RD(x, n) (HW_RFVBAT_REGn(x, n).U) #define HW_RFVBAT_REGn_WR(x, n, v) (HW_RFVBAT_REGn(x, n).U = (v)) #define HW_RFVBAT_REGn_SET(x, n, v) (HW_RFVBAT_REGn_WR(x, n, HW_RFVBAT_REGn_RD(x, n) | (v))) #define HW_RFVBAT_REGn_CLR(x, n, v) (HW_RFVBAT_REGn_WR(x, n, HW_RFVBAT_REGn_RD(x, n) & ~(v))) #define HW_RFVBAT_REGn_TOG(x, n, v) (HW_RFVBAT_REGn_WR(x, n, HW_RFVBAT_REGn_RD(x, n) ^ (v))) /*@}*/ /* * Constants & macros for individual RFVBAT_REGn bitfields */ /*! * @name Register RFVBAT_REGn, field LL[7:0] (RW) * * Low lower byte */ /*@{*/ #define BP_RFVBAT_REGn_LL (0U) /*!< Bit position for RFVBAT_REGn_LL. */ #define BM_RFVBAT_REGn_LL (0x000000FFU) /*!< Bit mask for RFVBAT_REGn_LL. */ #define BS_RFVBAT_REGn_LL (8U) /*!< Bit field size in bits for RFVBAT_REGn_LL. */ /*! @brief Read current value of the RFVBAT_REGn_LL field. */ #define BR_RFVBAT_REGn_LL(x, n) (HW_RFVBAT_REGn(x, n).B.LL) /*! @brief Format value for bitfield RFVBAT_REGn_LL. */ #define BF_RFVBAT_REGn_LL(v) ((uint32_t)((uint32_t)(v) << BP_RFVBAT_REGn_LL) & BM_RFVBAT_REGn_LL) /*! @brief Set the LL field to a new value. */ #define BW_RFVBAT_REGn_LL(x, n, v) (HW_RFVBAT_REGn_WR(x, n, (HW_RFVBAT_REGn_RD(x, n) & ~BM_RFVBAT_REGn_LL) | BF_RFVBAT_REGn_LL(v))) /*@}*/ /*! * @name Register RFVBAT_REGn, field LH[15:8] (RW) * * Low higher byte */ /*@{*/ #define BP_RFVBAT_REGn_LH (8U) /*!< Bit position for RFVBAT_REGn_LH. */ #define BM_RFVBAT_REGn_LH (0x0000FF00U) /*!< Bit mask for RFVBAT_REGn_LH. */ #define BS_RFVBAT_REGn_LH (8U) /*!< Bit field size in bits for RFVBAT_REGn_LH. */ /*! @brief Read current value of the RFVBAT_REGn_LH field. */ #define BR_RFVBAT_REGn_LH(x, n) (HW_RFVBAT_REGn(x, n).B.LH) /*! @brief Format value for bitfield RFVBAT_REGn_LH. */ #define BF_RFVBAT_REGn_LH(v) ((uint32_t)((uint32_t)(v) << BP_RFVBAT_REGn_LH) & BM_RFVBAT_REGn_LH) /*! @brief Set the LH field to a new value. */ #define BW_RFVBAT_REGn_LH(x, n, v) (HW_RFVBAT_REGn_WR(x, n, (HW_RFVBAT_REGn_RD(x, n) & ~BM_RFVBAT_REGn_LH) | BF_RFVBAT_REGn_LH(v))) /*@}*/ /*! * @name Register RFVBAT_REGn, field HL[23:16] (RW) * * High lower byte */ /*@{*/ #define BP_RFVBAT_REGn_HL (16U) /*!< Bit position for RFVBAT_REGn_HL. */ #define BM_RFVBAT_REGn_HL (0x00FF0000U) /*!< Bit mask for RFVBAT_REGn_HL. */ #define BS_RFVBAT_REGn_HL (8U) /*!< Bit field size in bits for RFVBAT_REGn_HL. */ /*! @brief Read current value of the RFVBAT_REGn_HL field. */ #define BR_RFVBAT_REGn_HL(x, n) (HW_RFVBAT_REGn(x, n).B.HL) /*! @brief Format value for bitfield RFVBAT_REGn_HL. */ #define BF_RFVBAT_REGn_HL(v) ((uint32_t)((uint32_t)(v) << BP_RFVBAT_REGn_HL) & BM_RFVBAT_REGn_HL) /*! @brief Set the HL field to a new value. */ #define BW_RFVBAT_REGn_HL(x, n, v) (HW_RFVBAT_REGn_WR(x, n, (HW_RFVBAT_REGn_RD(x, n) & ~BM_RFVBAT_REGn_HL) | BF_RFVBAT_REGn_HL(v))) /*@}*/ /*! * @name Register RFVBAT_REGn, field HH[31:24] (RW) * * High higher byte */ /*@{*/ #define BP_RFVBAT_REGn_HH (24U) /*!< Bit position for RFVBAT_REGn_HH. */ #define BM_RFVBAT_REGn_HH (0xFF000000U) /*!< Bit mask for RFVBAT_REGn_HH. */ #define BS_RFVBAT_REGn_HH (8U) /*!< Bit field size in bits for RFVBAT_REGn_HH. */ /*! @brief Read current value of the RFVBAT_REGn_HH field. */ #define BR_RFVBAT_REGn_HH(x, n) (HW_RFVBAT_REGn(x, n).B.HH) /*! @brief Format value for bitfield RFVBAT_REGn_HH. */ #define BF_RFVBAT_REGn_HH(v) ((uint32_t)((uint32_t)(v) << BP_RFVBAT_REGn_HH) & BM_RFVBAT_REGn_HH) /*! @brief Set the HH field to a new value. */ #define BW_RFVBAT_REGn_HH(x, n, v) (HW_RFVBAT_REGn_WR(x, n, (HW_RFVBAT_REGn_RD(x, n) & ~BM_RFVBAT_REGn_HH) | BF_RFVBAT_REGn_HH(v))) /*@}*/ /******************************************************************************* * hw_rfvbat_t - module struct ******************************************************************************/ /*! * @brief All RFVBAT module registers. */ #pragma pack(1) typedef struct _hw_rfvbat { __IO hw_rfvbat_regn_t REGn[8]; /*!< [0x0] VBAT register file register */ } hw_rfvbat_t; #pragma pack() /*! @brief Macro to access all RFVBAT registers. */ /*! @param x RFVBAT module instance base address. */ /*! @return Reference (not a pointer) to the registers struct. To get a pointer to the struct, * use the '&' operator, like &HW_RFVBAT(RFVBAT_BASE). */ #define HW_RFVBAT(x) (*(hw_rfvbat_t *)(x)) #endif /* __HW_RFVBAT_REGISTERS_H__ */ /* EOF */ ================================================ FILE: Zelig/mbed/TARGET_K64F/TARGET_Freescale/TARGET_KPSDK_MCUS/TARGET_MCU_K64F/device/device/MK64F12/MK64F12_rng.h ================================================ /* ** ################################################################### ** Compilers: Keil ARM C/C++ Compiler ** Freescale C/C++ for Embedded ARM ** GNU C Compiler ** IAR ANSI C/C++ Compiler for ARM ** ** Reference manual: K64P144M120SF5RM, Rev.2, January 2014 ** Version: rev. 2.5, 2014-02-10 ** Build: b140604 ** ** Abstract: ** Extension to the CMSIS register access layer header. ** ** Copyright (c) 2014 Freescale Semiconductor, Inc. ** All rights reserved. ** ** Redistribution and use in source and binary forms, with or without modification, ** are permitted provided that the following conditions are met: ** ** o Redistributions of source code must retain the above copyright notice, this list ** of conditions and the following disclaimer. ** ** o Redistributions in binary form must reproduce the above copyright notice, this ** list of conditions and the following disclaimer in the documentation and/or ** other materials provided with the distribution. ** ** o Neither the name of Freescale Semiconductor, Inc. nor the names of its ** contributors may be used to endorse or promote products derived from this ** software without specific prior written permission. ** ** THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ** ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED ** WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE ** DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT 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. ** ** http: www.freescale.com ** mail: support@freescale.com ** ** Revisions: ** - rev. 1.0 (2013-08-12) ** Initial version. ** - rev. 2.0 (2013-10-29) ** Register accessor macros added to the memory map. ** Symbols for Processor Expert memory map compatibility added to the memory map. ** Startup file for gcc has been updated according to CMSIS 3.2. ** System initialization updated. ** MCG - registers updated. ** PORTA, PORTB, PORTC, PORTE - registers for digital filter removed. ** - rev. 2.1 (2013-10-30) ** Definition of BITBAND macros updated to support peripherals with 32-bit acces disabled. ** - rev. 2.2 (2013-12-09) ** DMA - EARS register removed. ** AIPS0, AIPS1 - MPRA register updated. ** - rev. 2.3 (2014-01-24) ** Update according to reference manual rev. 2 ** ENET, MCG, MCM, SIM, USB - registers updated ** - rev. 2.4 (2014-02-10) ** The declaration of clock configurations has been moved to separate header file system_MK64F12.h ** Update of SystemInit() and SystemCoreClockUpdate() functions. ** - rev. 2.5 (2014-02-10) ** The declaration of clock configurations has been moved to separate header file system_MK64F12.h ** Update of SystemInit() and SystemCoreClockUpdate() functions. ** Module access macro module_BASES replaced by module_BASE_PTRS. ** ** ################################################################### */ /* * WARNING! DO NOT EDIT THIS FILE DIRECTLY! * * This file was generated automatically and any changes may be lost. */ #ifndef __HW_RNG_REGISTERS_H__ #define __HW_RNG_REGISTERS_H__ #include "MK64F12.h" #include "fsl_bitaccess.h" /* * MK64F12 RNG * * Random Number Generator Accelerator * * Registers defined in this header file: * - HW_RNG_CR - RNGA Control Register * - HW_RNG_SR - RNGA Status Register * - HW_RNG_ER - RNGA Entropy Register * - HW_RNG_OR - RNGA Output Register * * - hw_rng_t - Struct containing all module registers. */ #define HW_RNG_INSTANCE_COUNT (1U) /*!< Number of instances of the RNG module. */ /******************************************************************************* * HW_RNG_CR - RNGA Control Register ******************************************************************************/ /*! * @brief HW_RNG_CR - RNGA Control Register (RW) * * Reset value: 0x00000000U * * Controls the operation of RNGA. */ typedef union _hw_rng_cr { uint32_t U; struct _hw_rng_cr_bitfields { uint32_t GO : 1; /*!< [0] Go */ uint32_t HA : 1; /*!< [1] High Assurance */ uint32_t INTM : 1; /*!< [2] Interrupt Mask */ uint32_t CLRI : 1; /*!< [3] Clear Interrupt */ uint32_t SLP : 1; /*!< [4] Sleep */ uint32_t RESERVED0 : 27; /*!< [31:5] */ } B; } hw_rng_cr_t; /*! * @name Constants and macros for entire RNG_CR register */ /*@{*/ #define HW_RNG_CR_ADDR(x) ((x) + 0x0U) #define HW_RNG_CR(x) (*(__IO hw_rng_cr_t *) HW_RNG_CR_ADDR(x)) #define HW_RNG_CR_RD(x) (HW_RNG_CR(x).U) #define HW_RNG_CR_WR(x, v) (HW_RNG_CR(x).U = (v)) #define HW_RNG_CR_SET(x, v) (HW_RNG_CR_WR(x, HW_RNG_CR_RD(x) | (v))) #define HW_RNG_CR_CLR(x, v) (HW_RNG_CR_WR(x, HW_RNG_CR_RD(x) & ~(v))) #define HW_RNG_CR_TOG(x, v) (HW_RNG_CR_WR(x, HW_RNG_CR_RD(x) ^ (v))) /*@}*/ /* * Constants & macros for individual RNG_CR bitfields */ /*! * @name Register RNG_CR, field GO[0] (RW) * * Specifies whether random-data generation and loading (into OR[RANDOUT]) is * enabled.This field is sticky. You must reset RNGA to stop RNGA from loading * OR[RANDOUT] with data. * * Values: * - 0 - Disabled * - 1 - Enabled */ /*@{*/ #define BP_RNG_CR_GO (0U) /*!< Bit position for RNG_CR_GO. */ #define BM_RNG_CR_GO (0x00000001U) /*!< Bit mask for RNG_CR_GO. */ #define BS_RNG_CR_GO (1U) /*!< Bit field size in bits for RNG_CR_GO. */ /*! @brief Read current value of the RNG_CR_GO field. */ #define BR_RNG_CR_GO(x) (BITBAND_ACCESS32(HW_RNG_CR_ADDR(x), BP_RNG_CR_GO)) /*! @brief Format value for bitfield RNG_CR_GO. */ #define BF_RNG_CR_GO(v) ((uint32_t)((uint32_t)(v) << BP_RNG_CR_GO) & BM_RNG_CR_GO) /*! @brief Set the GO field to a new value. */ #define BW_RNG_CR_GO(x, v) (BITBAND_ACCESS32(HW_RNG_CR_ADDR(x), BP_RNG_CR_GO) = (v)) /*@}*/ /*! * @name Register RNG_CR, field HA[1] (RW) * * Enables notification of security violations (via SR[SECV]). A security * violation occurs when you read OR[RANDOUT] and SR[OREG_LVL]=0. This field is sticky. * After enabling notification of security violations, you must reset RNGA to * disable them again. * * Values: * - 0 - Disabled * - 1 - Enabled */ /*@{*/ #define BP_RNG_CR_HA (1U) /*!< Bit position for RNG_CR_HA. */ #define BM_RNG_CR_HA (0x00000002U) /*!< Bit mask for RNG_CR_HA. */ #define BS_RNG_CR_HA (1U) /*!< Bit field size in bits for RNG_CR_HA. */ /*! @brief Read current value of the RNG_CR_HA field. */ #define BR_RNG_CR_HA(x) (BITBAND_ACCESS32(HW_RNG_CR_ADDR(x), BP_RNG_CR_HA)) /*! @brief Format value for bitfield RNG_CR_HA. */ #define BF_RNG_CR_HA(v) ((uint32_t)((uint32_t)(v) << BP_RNG_CR_HA) & BM_RNG_CR_HA) /*! @brief Set the HA field to a new value. */ #define BW_RNG_CR_HA(x, v) (BITBAND_ACCESS32(HW_RNG_CR_ADDR(x), BP_RNG_CR_HA) = (v)) /*@}*/ /*! * @name Register RNG_CR, field INTM[2] (RW) * * Masks the triggering of an error interrupt to the interrupt controller when * an OR underflow condition occurs. An OR underflow condition occurs when you * read OR[RANDOUT] and SR[OREG_LVL]=0. See the Output Register (OR) description. * * Values: * - 0 - Not masked * - 1 - Masked */ /*@{*/ #define BP_RNG_CR_INTM (2U) /*!< Bit position for RNG_CR_INTM. */ #define BM_RNG_CR_INTM (0x00000004U) /*!< Bit mask for RNG_CR_INTM. */ #define BS_RNG_CR_INTM (1U) /*!< Bit field size in bits for RNG_CR_INTM. */ /*! @brief Read current value of the RNG_CR_INTM field. */ #define BR_RNG_CR_INTM(x) (BITBAND_ACCESS32(HW_RNG_CR_ADDR(x), BP_RNG_CR_INTM)) /*! @brief Format value for bitfield RNG_CR_INTM. */ #define BF_RNG_CR_INTM(v) ((uint32_t)((uint32_t)(v) << BP_RNG_CR_INTM) & BM_RNG_CR_INTM) /*! @brief Set the INTM field to a new value. */ #define BW_RNG_CR_INTM(x, v) (BITBAND_ACCESS32(HW_RNG_CR_ADDR(x), BP_RNG_CR_INTM) = (v)) /*@}*/ /*! * @name Register RNG_CR, field CLRI[3] (WORZ) * * Clears the interrupt by resetting the error-interrupt indicator (SR[ERRI]). * * Values: * - 0 - Do not clear the interrupt. * - 1 - Clear the interrupt. When you write 1 to this field, RNGA then resets * the error-interrupt indicator (SR[ERRI]). This bit always reads as 0. */ /*@{*/ #define BP_RNG_CR_CLRI (3U) /*!< Bit position for RNG_CR_CLRI. */ #define BM_RNG_CR_CLRI (0x00000008U) /*!< Bit mask for RNG_CR_CLRI. */ #define BS_RNG_CR_CLRI (1U) /*!< Bit field size in bits for RNG_CR_CLRI. */ /*! @brief Format value for bitfield RNG_CR_CLRI. */ #define BF_RNG_CR_CLRI(v) ((uint32_t)((uint32_t)(v) << BP_RNG_CR_CLRI) & BM_RNG_CR_CLRI) /*! @brief Set the CLRI field to a new value. */ #define BW_RNG_CR_CLRI(x, v) (BITBAND_ACCESS32(HW_RNG_CR_ADDR(x), BP_RNG_CR_CLRI) = (v)) /*@}*/ /*! * @name Register RNG_CR, field SLP[4] (RW) * * Specifies whether RNGA is in Sleep or Normal mode. You can also enter Sleep * mode by asserting the DOZE signal. * * Values: * - 0 - Normal mode * - 1 - Sleep (low-power) mode */ /*@{*/ #define BP_RNG_CR_SLP (4U) /*!< Bit position for RNG_CR_SLP. */ #define BM_RNG_CR_SLP (0x00000010U) /*!< Bit mask for RNG_CR_SLP. */ #define BS_RNG_CR_SLP (1U) /*!< Bit field size in bits for RNG_CR_SLP. */ /*! @brief Read current value of the RNG_CR_SLP field. */ #define BR_RNG_CR_SLP(x) (BITBAND_ACCESS32(HW_RNG_CR_ADDR(x), BP_RNG_CR_SLP)) /*! @brief Format value for bitfield RNG_CR_SLP. */ #define BF_RNG_CR_SLP(v) ((uint32_t)((uint32_t)(v) << BP_RNG_CR_SLP) & BM_RNG_CR_SLP) /*! @brief Set the SLP field to a new value. */ #define BW_RNG_CR_SLP(x, v) (BITBAND_ACCESS32(HW_RNG_CR_ADDR(x), BP_RNG_CR_SLP) = (v)) /*@}*/ /******************************************************************************* * HW_RNG_SR - RNGA Status Register ******************************************************************************/ /*! * @brief HW_RNG_SR - RNGA Status Register (RO) * * Reset value: 0x00010000U * * Indicates the status of RNGA. This register is read-only. */ typedef union _hw_rng_sr { uint32_t U; struct _hw_rng_sr_bitfields { uint32_t SECV : 1; /*!< [0] Security Violation */ uint32_t LRS : 1; /*!< [1] Last Read Status */ uint32_t ORU : 1; /*!< [2] Output Register Underflow */ uint32_t ERRI : 1; /*!< [3] Error Interrupt */ uint32_t SLP : 1; /*!< [4] Sleep */ uint32_t RESERVED0 : 3; /*!< [7:5] */ uint32_t OREG_LVL : 8; /*!< [15:8] Output Register Level */ uint32_t OREG_SIZE : 8; /*!< [23:16] Output Register Size */ uint32_t RESERVED1 : 8; /*!< [31:24] */ } B; } hw_rng_sr_t; /*! * @name Constants and macros for entire RNG_SR register */ /*@{*/ #define HW_RNG_SR_ADDR(x) ((x) + 0x4U) #define HW_RNG_SR(x) (*(__I hw_rng_sr_t *) HW_RNG_SR_ADDR(x)) #define HW_RNG_SR_RD(x) (HW_RNG_SR(x).U) /*@}*/ /* * Constants & macros for individual RNG_SR bitfields */ /*! * @name Register RNG_SR, field SECV[0] (RO) * * Used only when high assurance is enabled (CR[HA]). Indicates that a security * violation has occurred.This field is sticky. To clear SR[SECV], you must reset * RNGA. * * Values: * - 0 - No security violation * - 1 - Security violation */ /*@{*/ #define BP_RNG_SR_SECV (0U) /*!< Bit position for RNG_SR_SECV. */ #define BM_RNG_SR_SECV (0x00000001U) /*!< Bit mask for RNG_SR_SECV. */ #define BS_RNG_SR_SECV (1U) /*!< Bit field size in bits for RNG_SR_SECV. */ /*! @brief Read current value of the RNG_SR_SECV field. */ #define BR_RNG_SR_SECV(x) (BITBAND_ACCESS32(HW_RNG_SR_ADDR(x), BP_RNG_SR_SECV)) /*@}*/ /*! * @name Register RNG_SR, field LRS[1] (RO) * * Indicates whether the most recent read of OR[RANDOUT] caused an OR underflow * condition, regardless of whether the error interrupt is masked (CR[INTM]). An * OR underflow condition occurs when you read OR[RANDOUT] and SR[OREG_LVL]=0. * After you read this register, RNGA writes 0 to this field. * * Values: * - 0 - No underflow * - 1 - Underflow */ /*@{*/ #define BP_RNG_SR_LRS (1U) /*!< Bit position for RNG_SR_LRS. */ #define BM_RNG_SR_LRS (0x00000002U) /*!< Bit mask for RNG_SR_LRS. */ #define BS_RNG_SR_LRS (1U) /*!< Bit field size in bits for RNG_SR_LRS. */ /*! @brief Read current value of the RNG_SR_LRS field. */ #define BR_RNG_SR_LRS(x) (BITBAND_ACCESS32(HW_RNG_SR_ADDR(x), BP_RNG_SR_LRS)) /*@}*/ /*! * @name Register RNG_SR, field ORU[2] (RO) * * Indicates whether an OR underflow condition has occurred since you last read * this register (SR) or RNGA was reset, regardless of whether the error * interrupt is masked (CR[INTM]). An OR underflow condition occurs when you read * OR[RANDOUT] and SR[OREG_LVL]=0. After you read this register, RNGA writes 0 to this * field. * * Values: * - 0 - No underflow * - 1 - Underflow */ /*@{*/ #define BP_RNG_SR_ORU (2U) /*!< Bit position for RNG_SR_ORU. */ #define BM_RNG_SR_ORU (0x00000004U) /*!< Bit mask for RNG_SR_ORU. */ #define BS_RNG_SR_ORU (1U) /*!< Bit field size in bits for RNG_SR_ORU. */ /*! @brief Read current value of the RNG_SR_ORU field. */ #define BR_RNG_SR_ORU(x) (BITBAND_ACCESS32(HW_RNG_SR_ADDR(x), BP_RNG_SR_ORU)) /*@}*/ /*! * @name Register RNG_SR, field ERRI[3] (RO) * * Indicates whether an OR underflow condition has occurred since you last * cleared the error interrupt (CR[CLRI]) or RNGA was reset, regardless of whether the * error interrupt is masked (CR[INTM]). An OR underflow condition occurs when * you read OR[RANDOUT] and SR[OREG_LVL]=0. After you reset the error-interrupt * indicator (via CR[CLRI]), RNGA writes 0 to this field. * * Values: * - 0 - No underflow * - 1 - Underflow */ /*@{*/ #define BP_RNG_SR_ERRI (3U) /*!< Bit position for RNG_SR_ERRI. */ #define BM_RNG_SR_ERRI (0x00000008U) /*!< Bit mask for RNG_SR_ERRI. */ #define BS_RNG_SR_ERRI (1U) /*!< Bit field size in bits for RNG_SR_ERRI. */ /*! @brief Read current value of the RNG_SR_ERRI field. */ #define BR_RNG_SR_ERRI(x) (BITBAND_ACCESS32(HW_RNG_SR_ADDR(x), BP_RNG_SR_ERRI)) /*@}*/ /*! * @name Register RNG_SR, field SLP[4] (RO) * * Specifies whether RNGA is in Sleep or Normal mode. You can also enter Sleep * mode by asserting the DOZE signal. * * Values: * - 0 - Normal mode * - 1 - Sleep (low-power) mode */ /*@{*/ #define BP_RNG_SR_SLP (4U) /*!< Bit position for RNG_SR_SLP. */ #define BM_RNG_SR_SLP (0x00000010U) /*!< Bit mask for RNG_SR_SLP. */ #define BS_RNG_SR_SLP (1U) /*!< Bit field size in bits for RNG_SR_SLP. */ /*! @brief Read current value of the RNG_SR_SLP field. */ #define BR_RNG_SR_SLP(x) (BITBAND_ACCESS32(HW_RNG_SR_ADDR(x), BP_RNG_SR_SLP)) /*@}*/ /*! * @name Register RNG_SR, field OREG_LVL[15:8] (RO) * * Indicates the number of random-data words that are in OR[RANDOUT], which * indicates whether OR[RANDOUT] is valid.If you read OR[RANDOUT] when SR[OREG_LVL] * is not 0, then the contents of a random number contained in OR[RANDOUT] are * returned, and RNGA writes 0 to both OR[RANDOUT] and SR[OREG_LVL]. * * Values: * - 0 - No words (empty) * - 1 - One word (valid) */ /*@{*/ #define BP_RNG_SR_OREG_LVL (8U) /*!< Bit position for RNG_SR_OREG_LVL. */ #define BM_RNG_SR_OREG_LVL (0x0000FF00U) /*!< Bit mask for RNG_SR_OREG_LVL. */ #define BS_RNG_SR_OREG_LVL (8U) /*!< Bit field size in bits for RNG_SR_OREG_LVL. */ /*! @brief Read current value of the RNG_SR_OREG_LVL field. */ #define BR_RNG_SR_OREG_LVL(x) (HW_RNG_SR(x).B.OREG_LVL) /*@}*/ /*! * @name Register RNG_SR, field OREG_SIZE[23:16] (RO) * * Indicates the size of the Output (OR) register in terms of the number of * 32-bit random-data words it can hold. * * Values: * - 1 - One word (this value is fixed) */ /*@{*/ #define BP_RNG_SR_OREG_SIZE (16U) /*!< Bit position for RNG_SR_OREG_SIZE. */ #define BM_RNG_SR_OREG_SIZE (0x00FF0000U) /*!< Bit mask for RNG_SR_OREG_SIZE. */ #define BS_RNG_SR_OREG_SIZE (8U) /*!< Bit field size in bits for RNG_SR_OREG_SIZE. */ /*! @brief Read current value of the RNG_SR_OREG_SIZE field. */ #define BR_RNG_SR_OREG_SIZE(x) (HW_RNG_SR(x).B.OREG_SIZE) /*@}*/ /******************************************************************************* * HW_RNG_ER - RNGA Entropy Register ******************************************************************************/ /*! * @brief HW_RNG_ER - RNGA Entropy Register (WORZ) * * Reset value: 0x00000000U * * Specifies an entropy value that RNGA uses in addition to its ring oscillators * to seed its pseudorandom algorithm. This is a write-only register; reads * return all zeros. */ typedef union _hw_rng_er { uint32_t U; struct _hw_rng_er_bitfields { uint32_t EXT_ENT : 32; /*!< [31:0] External Entropy */ } B; } hw_rng_er_t; /*! * @name Constants and macros for entire RNG_ER register */ /*@{*/ #define HW_RNG_ER_ADDR(x) ((x) + 0x8U) #define HW_RNG_ER(x) (*(__O hw_rng_er_t *) HW_RNG_ER_ADDR(x)) #define HW_RNG_ER_RD(x) (HW_RNG_ER(x).U) #define HW_RNG_ER_WR(x, v) (HW_RNG_ER(x).U = (v)) /*@}*/ /* * Constants & macros for individual RNG_ER bitfields */ /*! * @name Register RNG_ER, field EXT_ENT[31:0] (WORZ) * * Specifies an entropy value that RNGA uses in addition to its ring oscillators * to seed its pseudorandom algorithm.Specifying a value for this field is * optional but recommended. You can write to this field at any time during operation. */ /*@{*/ #define BP_RNG_ER_EXT_ENT (0U) /*!< Bit position for RNG_ER_EXT_ENT. */ #define BM_RNG_ER_EXT_ENT (0xFFFFFFFFU) /*!< Bit mask for RNG_ER_EXT_ENT. */ #define BS_RNG_ER_EXT_ENT (32U) /*!< Bit field size in bits for RNG_ER_EXT_ENT. */ /*! @brief Format value for bitfield RNG_ER_EXT_ENT. */ #define BF_RNG_ER_EXT_ENT(v) ((uint32_t)((uint32_t)(v) << BP_RNG_ER_EXT_ENT) & BM_RNG_ER_EXT_ENT) /*! @brief Set the EXT_ENT field to a new value. */ #define BW_RNG_ER_EXT_ENT(x, v) (HW_RNG_ER_WR(x, v)) /*@}*/ /******************************************************************************* * HW_RNG_OR - RNGA Output Register ******************************************************************************/ /*! * @brief HW_RNG_OR - RNGA Output Register (RO) * * Reset value: 0x00000000U * * Stores a random-data word generated by RNGA. */ typedef union _hw_rng_or { uint32_t U; struct _hw_rng_or_bitfields { uint32_t RANDOUT : 32; /*!< [31:0] Random Output */ } B; } hw_rng_or_t; /*! * @name Constants and macros for entire RNG_OR register */ /*@{*/ #define HW_RNG_OR_ADDR(x) ((x) + 0xCU) #define HW_RNG_OR(x) (*(__I hw_rng_or_t *) HW_RNG_OR_ADDR(x)) #define HW_RNG_OR_RD(x) (HW_RNG_OR(x).U) /*@}*/ /* * Constants & macros for individual RNG_OR bitfields */ /*! * @name Register RNG_OR, field RANDOUT[31:0] (RO) * * Stores a random-data word generated by RNGA. This is a read-only field.Before * reading RANDOUT, be sure it is valid (SR[OREG_LVL]=1). * * Values: * - 0 - Invalid data (if you read this field when it is 0 and SR[OREG_LVL] is * 0, RNGA then writes 1 to SR[ERRI], SR[ORU], and SR[LRS]; when the error * interrupt is not masked (CR[INTM]=0), RNGA also asserts an error interrupt * request to the interrupt controller). */ /*@{*/ #define BP_RNG_OR_RANDOUT (0U) /*!< Bit position for RNG_OR_RANDOUT. */ #define BM_RNG_OR_RANDOUT (0xFFFFFFFFU) /*!< Bit mask for RNG_OR_RANDOUT. */ #define BS_RNG_OR_RANDOUT (32U) /*!< Bit field size in bits for RNG_OR_RANDOUT. */ /*! @brief Read current value of the RNG_OR_RANDOUT field. */ #define BR_RNG_OR_RANDOUT(x) (HW_RNG_OR(x).U) /*@}*/ /******************************************************************************* * hw_rng_t - module struct ******************************************************************************/ /*! * @brief All RNG module registers. */ #pragma pack(1) typedef struct _hw_rng { __IO hw_rng_cr_t CR; /*!< [0x0] RNGA Control Register */ __I hw_rng_sr_t SR; /*!< [0x4] RNGA Status Register */ __O hw_rng_er_t ER; /*!< [0x8] RNGA Entropy Register */ __I hw_rng_or_t OR; /*!< [0xC] RNGA Output Register */ } hw_rng_t; #pragma pack() /*! @brief Macro to access all RNG registers. */ /*! @param x RNG module instance base address. */ /*! @return Reference (not a pointer) to the registers struct. To get a pointer to the struct, * use the '&' operator, like &HW_RNG(RNG_BASE). */ #define HW_RNG(x) (*(hw_rng_t *)(x)) #endif /* __HW_RNG_REGISTERS_H__ */ /* EOF */ ================================================ FILE: Zelig/mbed/TARGET_K64F/TARGET_Freescale/TARGET_KPSDK_MCUS/TARGET_MCU_K64F/device/device/MK64F12/MK64F12_rtc.h ================================================ /* ** ################################################################### ** Compilers: Keil ARM C/C++ Compiler ** Freescale C/C++ for Embedded ARM ** GNU C Compiler ** IAR ANSI C/C++ Compiler for ARM ** ** Reference manual: K64P144M120SF5RM, Rev.2, January 2014 ** Version: rev. 2.5, 2014-02-10 ** Build: b140604 ** ** Abstract: ** Extension to the CMSIS register access layer header. ** ** Copyright (c) 2014 Freescale Semiconductor, Inc. ** All rights reserved. ** ** Redistribution and use in source and binary forms, with or without modification, ** are permitted provided that the following conditions are met: ** ** o Redistributions of source code must retain the above copyright notice, this list ** of conditions and the following disclaimer. ** ** o Redistributions in binary form must reproduce the above copyright notice, this ** list of conditions and the following disclaimer in the documentation and/or ** other materials provided with the distribution. ** ** o Neither the name of Freescale Semiconductor, Inc. nor the names of its ** contributors may be used to endorse or promote products derived from this ** software without specific prior written permission. ** ** THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ** ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED ** WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE ** DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT 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. ** ** http: www.freescale.com ** mail: support@freescale.com ** ** Revisions: ** - rev. 1.0 (2013-08-12) ** Initial version. ** - rev. 2.0 (2013-10-29) ** Register accessor macros added to the memory map. ** Symbols for Processor Expert memory map compatibility added to the memory map. ** Startup file for gcc has been updated according to CMSIS 3.2. ** System initialization updated. ** MCG - registers updated. ** PORTA, PORTB, PORTC, PORTE - registers for digital filter removed. ** - rev. 2.1 (2013-10-30) ** Definition of BITBAND macros updated to support peripherals with 32-bit acces disabled. ** - rev. 2.2 (2013-12-09) ** DMA - EARS register removed. ** AIPS0, AIPS1 - MPRA register updated. ** - rev. 2.3 (2014-01-24) ** Update according to reference manual rev. 2 ** ENET, MCG, MCM, SIM, USB - registers updated ** - rev. 2.4 (2014-02-10) ** The declaration of clock configurations has been moved to separate header file system_MK64F12.h ** Update of SystemInit() and SystemCoreClockUpdate() functions. ** - rev. 2.5 (2014-02-10) ** The declaration of clock configurations has been moved to separate header file system_MK64F12.h ** Update of SystemInit() and SystemCoreClockUpdate() functions. ** Module access macro module_BASES replaced by module_BASE_PTRS. ** ** ################################################################### */ /* * WARNING! DO NOT EDIT THIS FILE DIRECTLY! * * This file was generated automatically and any changes may be lost. */ #ifndef __HW_RTC_REGISTERS_H__ #define __HW_RTC_REGISTERS_H__ #include "MK64F12.h" #include "fsl_bitaccess.h" /* * MK64F12 RTC * * Secure Real Time Clock * * Registers defined in this header file: * - HW_RTC_TSR - RTC Time Seconds Register * - HW_RTC_TPR - RTC Time Prescaler Register * - HW_RTC_TAR - RTC Time Alarm Register * - HW_RTC_TCR - RTC Time Compensation Register * - HW_RTC_CR - RTC Control Register * - HW_RTC_SR - RTC Status Register * - HW_RTC_LR - RTC Lock Register * - HW_RTC_IER - RTC Interrupt Enable Register * - HW_RTC_WAR - RTC Write Access Register * - HW_RTC_RAR - RTC Read Access Register * * - hw_rtc_t - Struct containing all module registers. */ #define HW_RTC_INSTANCE_COUNT (1U) /*!< Number of instances of the RTC module. */ /******************************************************************************* * HW_RTC_TSR - RTC Time Seconds Register ******************************************************************************/ /*! * @brief HW_RTC_TSR - RTC Time Seconds Register (RW) * * Reset value: 0x00000000U */ typedef union _hw_rtc_tsr { uint32_t U; struct _hw_rtc_tsr_bitfields { uint32_t TSR : 32; /*!< [31:0] Time Seconds Register */ } B; } hw_rtc_tsr_t; /*! * @name Constants and macros for entire RTC_TSR register */ /*@{*/ #define HW_RTC_TSR_ADDR(x) ((x) + 0x0U) #define HW_RTC_TSR(x) (*(__IO hw_rtc_tsr_t *) HW_RTC_TSR_ADDR(x)) #define HW_RTC_TSR_RD(x) (HW_RTC_TSR(x).U) #define HW_RTC_TSR_WR(x, v) (HW_RTC_TSR(x).U = (v)) #define HW_RTC_TSR_SET(x, v) (HW_RTC_TSR_WR(x, HW_RTC_TSR_RD(x) | (v))) #define HW_RTC_TSR_CLR(x, v) (HW_RTC_TSR_WR(x, HW_RTC_TSR_RD(x) & ~(v))) #define HW_RTC_TSR_TOG(x, v) (HW_RTC_TSR_WR(x, HW_RTC_TSR_RD(x) ^ (v))) /*@}*/ /* * Constants & macros for individual RTC_TSR bitfields */ /*! * @name Register RTC_TSR, field TSR[31:0] (RW) * * When the time counter is enabled, the TSR is read only and increments once a * second provided SR[TOF] or SR[TIF] are not set. The time counter will read as * zero when SR[TOF] or SR[TIF] are set. When the time counter is disabled, the * TSR can be read or written. Writing to the TSR when the time counter is * disabled will clear the SR[TOF] and/or the SR[TIF]. Writing to TSR with zero is * supported, but not recommended because TSR will read as zero when SR[TIF] or * SR[TOF] are set (indicating the time is invalid). */ /*@{*/ #define BP_RTC_TSR_TSR (0U) /*!< Bit position for RTC_TSR_TSR. */ #define BM_RTC_TSR_TSR (0xFFFFFFFFU) /*!< Bit mask for RTC_TSR_TSR. */ #define BS_RTC_TSR_TSR (32U) /*!< Bit field size in bits for RTC_TSR_TSR. */ /*! @brief Read current value of the RTC_TSR_TSR field. */ #define BR_RTC_TSR_TSR(x) (HW_RTC_TSR(x).U) /*! @brief Format value for bitfield RTC_TSR_TSR. */ #define BF_RTC_TSR_TSR(v) ((uint32_t)((uint32_t)(v) << BP_RTC_TSR_TSR) & BM_RTC_TSR_TSR) /*! @brief Set the TSR field to a new value. */ #define BW_RTC_TSR_TSR(x, v) (HW_RTC_TSR_WR(x, v)) /*@}*/ /******************************************************************************* * HW_RTC_TPR - RTC Time Prescaler Register ******************************************************************************/ /*! * @brief HW_RTC_TPR - RTC Time Prescaler Register (RW) * * Reset value: 0x00000000U */ typedef union _hw_rtc_tpr { uint32_t U; struct _hw_rtc_tpr_bitfields { uint32_t TPR : 16; /*!< [15:0] Time Prescaler Register */ uint32_t RESERVED0 : 16; /*!< [31:16] */ } B; } hw_rtc_tpr_t; /*! * @name Constants and macros for entire RTC_TPR register */ /*@{*/ #define HW_RTC_TPR_ADDR(x) ((x) + 0x4U) #define HW_RTC_TPR(x) (*(__IO hw_rtc_tpr_t *) HW_RTC_TPR_ADDR(x)) #define HW_RTC_TPR_RD(x) (HW_RTC_TPR(x).U) #define HW_RTC_TPR_WR(x, v) (HW_RTC_TPR(x).U = (v)) #define HW_RTC_TPR_SET(x, v) (HW_RTC_TPR_WR(x, HW_RTC_TPR_RD(x) | (v))) #define HW_RTC_TPR_CLR(x, v) (HW_RTC_TPR_WR(x, HW_RTC_TPR_RD(x) & ~(v))) #define HW_RTC_TPR_TOG(x, v) (HW_RTC_TPR_WR(x, HW_RTC_TPR_RD(x) ^ (v))) /*@}*/ /* * Constants & macros for individual RTC_TPR bitfields */ /*! * @name Register RTC_TPR, field TPR[15:0] (RW) * * When the time counter is enabled, the TPR is read only and increments every * 32.768 kHz clock cycle. The time counter will read as zero when SR[TOF] or * SR[TIF] are set. When the time counter is disabled, the TPR can be read or * written. The TSR[TSR] increments when bit 14 of the TPR transitions from a logic one * to a logic zero. */ /*@{*/ #define BP_RTC_TPR_TPR (0U) /*!< Bit position for RTC_TPR_TPR. */ #define BM_RTC_TPR_TPR (0x0000FFFFU) /*!< Bit mask for RTC_TPR_TPR. */ #define BS_RTC_TPR_TPR (16U) /*!< Bit field size in bits for RTC_TPR_TPR. */ /*! @brief Read current value of the RTC_TPR_TPR field. */ #define BR_RTC_TPR_TPR(x) (HW_RTC_TPR(x).B.TPR) /*! @brief Format value for bitfield RTC_TPR_TPR. */ #define BF_RTC_TPR_TPR(v) ((uint32_t)((uint32_t)(v) << BP_RTC_TPR_TPR) & BM_RTC_TPR_TPR) /*! @brief Set the TPR field to a new value. */ #define BW_RTC_TPR_TPR(x, v) (HW_RTC_TPR_WR(x, (HW_RTC_TPR_RD(x) & ~BM_RTC_TPR_TPR) | BF_RTC_TPR_TPR(v))) /*@}*/ /******************************************************************************* * HW_RTC_TAR - RTC Time Alarm Register ******************************************************************************/ /*! * @brief HW_RTC_TAR - RTC Time Alarm Register (RW) * * Reset value: 0x00000000U */ typedef union _hw_rtc_tar { uint32_t U; struct _hw_rtc_tar_bitfields { uint32_t TAR : 32; /*!< [31:0] Time Alarm Register */ } B; } hw_rtc_tar_t; /*! * @name Constants and macros for entire RTC_TAR register */ /*@{*/ #define HW_RTC_TAR_ADDR(x) ((x) + 0x8U) #define HW_RTC_TAR(x) (*(__IO hw_rtc_tar_t *) HW_RTC_TAR_ADDR(x)) #define HW_RTC_TAR_RD(x) (HW_RTC_TAR(x).U) #define HW_RTC_TAR_WR(x, v) (HW_RTC_TAR(x).U = (v)) #define HW_RTC_TAR_SET(x, v) (HW_RTC_TAR_WR(x, HW_RTC_TAR_RD(x) | (v))) #define HW_RTC_TAR_CLR(x, v) (HW_RTC_TAR_WR(x, HW_RTC_TAR_RD(x) & ~(v))) #define HW_RTC_TAR_TOG(x, v) (HW_RTC_TAR_WR(x, HW_RTC_TAR_RD(x) ^ (v))) /*@}*/ /* * Constants & macros for individual RTC_TAR bitfields */ /*! * @name Register RTC_TAR, field TAR[31:0] (RW) * * When the time counter is enabled, the SR[TAF] is set whenever the TAR[TAR] * equals the TSR[TSR] and the TSR[TSR] increments. Writing to the TAR clears the * SR[TAF]. */ /*@{*/ #define BP_RTC_TAR_TAR (0U) /*!< Bit position for RTC_TAR_TAR. */ #define BM_RTC_TAR_TAR (0xFFFFFFFFU) /*!< Bit mask for RTC_TAR_TAR. */ #define BS_RTC_TAR_TAR (32U) /*!< Bit field size in bits for RTC_TAR_TAR. */ /*! @brief Read current value of the RTC_TAR_TAR field. */ #define BR_RTC_TAR_TAR(x) (HW_RTC_TAR(x).U) /*! @brief Format value for bitfield RTC_TAR_TAR. */ #define BF_RTC_TAR_TAR(v) ((uint32_t)((uint32_t)(v) << BP_RTC_TAR_TAR) & BM_RTC_TAR_TAR) /*! @brief Set the TAR field to a new value. */ #define BW_RTC_TAR_TAR(x, v) (HW_RTC_TAR_WR(x, v)) /*@}*/ /******************************************************************************* * HW_RTC_TCR - RTC Time Compensation Register ******************************************************************************/ /*! * @brief HW_RTC_TCR - RTC Time Compensation Register (RW) * * Reset value: 0x00000000U */ typedef union _hw_rtc_tcr { uint32_t U; struct _hw_rtc_tcr_bitfields { uint32_t TCR : 8; /*!< [7:0] Time Compensation Register */ uint32_t CIR : 8; /*!< [15:8] Compensation Interval Register */ uint32_t TCV : 8; /*!< [23:16] Time Compensation Value */ uint32_t CIC : 8; /*!< [31:24] Compensation Interval Counter */ } B; } hw_rtc_tcr_t; /*! * @name Constants and macros for entire RTC_TCR register */ /*@{*/ #define HW_RTC_TCR_ADDR(x) ((x) + 0xCU) #define HW_RTC_TCR(x) (*(__IO hw_rtc_tcr_t *) HW_RTC_TCR_ADDR(x)) #define HW_RTC_TCR_RD(x) (HW_RTC_TCR(x).U) #define HW_RTC_TCR_WR(x, v) (HW_RTC_TCR(x).U = (v)) #define HW_RTC_TCR_SET(x, v) (HW_RTC_TCR_WR(x, HW_RTC_TCR_RD(x) | (v))) #define HW_RTC_TCR_CLR(x, v) (HW_RTC_TCR_WR(x, HW_RTC_TCR_RD(x) & ~(v))) #define HW_RTC_TCR_TOG(x, v) (HW_RTC_TCR_WR(x, HW_RTC_TCR_RD(x) ^ (v))) /*@}*/ /* * Constants & macros for individual RTC_TCR bitfields */ /*! * @name Register RTC_TCR, field TCR[7:0] (RW) * * Configures the number of 32.768 kHz clock cycles in each second. This * register is double buffered and writes do not take affect until the end of the * current compensation interval. * * Values: * - 10000000 - Time Prescaler Register overflows every 32896 clock cycles. * - 11111111 - Time Prescaler Register overflows every 32769 clock cycles. * - 0 - Time Prescaler Register overflows every 32768 clock cycles. * - 1 - Time Prescaler Register overflows every 32767 clock cycles. * - 1111111 - Time Prescaler Register overflows every 32641 clock cycles. */ /*@{*/ #define BP_RTC_TCR_TCR (0U) /*!< Bit position for RTC_TCR_TCR. */ #define BM_RTC_TCR_TCR (0x000000FFU) /*!< Bit mask for RTC_TCR_TCR. */ #define BS_RTC_TCR_TCR (8U) /*!< Bit field size in bits for RTC_TCR_TCR. */ /*! @brief Read current value of the RTC_TCR_TCR field. */ #define BR_RTC_TCR_TCR(x) (HW_RTC_TCR(x).B.TCR) /*! @brief Format value for bitfield RTC_TCR_TCR. */ #define BF_RTC_TCR_TCR(v) ((uint32_t)((uint32_t)(v) << BP_RTC_TCR_TCR) & BM_RTC_TCR_TCR) /*! @brief Set the TCR field to a new value. */ #define BW_RTC_TCR_TCR(x, v) (HW_RTC_TCR_WR(x, (HW_RTC_TCR_RD(x) & ~BM_RTC_TCR_TCR) | BF_RTC_TCR_TCR(v))) /*@}*/ /*! * @name Register RTC_TCR, field CIR[15:8] (RW) * * Configures the compensation interval in seconds from 1 to 256 to control how * frequently the TCR should adjust the number of 32.768 kHz cycles in each * second. The value written should be one less than the number of seconds. For * example, write zero to configure for a compensation interval of one second. This * register is double buffered and writes do not take affect until the end of the * current compensation interval. */ /*@{*/ #define BP_RTC_TCR_CIR (8U) /*!< Bit position for RTC_TCR_CIR. */ #define BM_RTC_TCR_CIR (0x0000FF00U) /*!< Bit mask for RTC_TCR_CIR. */ #define BS_RTC_TCR_CIR (8U) /*!< Bit field size in bits for RTC_TCR_CIR. */ /*! @brief Read current value of the RTC_TCR_CIR field. */ #define BR_RTC_TCR_CIR(x) (HW_RTC_TCR(x).B.CIR) /*! @brief Format value for bitfield RTC_TCR_CIR. */ #define BF_RTC_TCR_CIR(v) ((uint32_t)((uint32_t)(v) << BP_RTC_TCR_CIR) & BM_RTC_TCR_CIR) /*! @brief Set the CIR field to a new value. */ #define BW_RTC_TCR_CIR(x, v) (HW_RTC_TCR_WR(x, (HW_RTC_TCR_RD(x) & ~BM_RTC_TCR_CIR) | BF_RTC_TCR_CIR(v))) /*@}*/ /*! * @name Register RTC_TCR, field TCV[23:16] (RO) * * Current value used by the compensation logic for the present second interval. * Updated once a second if the CIC equals 0 with the contents of the TCR field. * If the CIC does not equal zero then it is loaded with zero (compensation is * not enabled for that second increment). */ /*@{*/ #define BP_RTC_TCR_TCV (16U) /*!< Bit position for RTC_TCR_TCV. */ #define BM_RTC_TCR_TCV (0x00FF0000U) /*!< Bit mask for RTC_TCR_TCV. */ #define BS_RTC_TCR_TCV (8U) /*!< Bit field size in bits for RTC_TCR_TCV. */ /*! @brief Read current value of the RTC_TCR_TCV field. */ #define BR_RTC_TCR_TCV(x) (HW_RTC_TCR(x).B.TCV) /*@}*/ /*! * @name Register RTC_TCR, field CIC[31:24] (RO) * * Current value of the compensation interval counter. If the compensation * interval counter equals zero then it is loaded with the contents of the CIR. If the * CIC does not equal zero then it is decremented once a second. */ /*@{*/ #define BP_RTC_TCR_CIC (24U) /*!< Bit position for RTC_TCR_CIC. */ #define BM_RTC_TCR_CIC (0xFF000000U) /*!< Bit mask for RTC_TCR_CIC. */ #define BS_RTC_TCR_CIC (8U) /*!< Bit field size in bits for RTC_TCR_CIC. */ /*! @brief Read current value of the RTC_TCR_CIC field. */ #define BR_RTC_TCR_CIC(x) (HW_RTC_TCR(x).B.CIC) /*@}*/ /******************************************************************************* * HW_RTC_CR - RTC Control Register ******************************************************************************/ /*! * @brief HW_RTC_CR - RTC Control Register (RW) * * Reset value: 0x00000000U */ typedef union _hw_rtc_cr { uint32_t U; struct _hw_rtc_cr_bitfields { uint32_t SWR : 1; /*!< [0] Software Reset */ uint32_t WPE : 1; /*!< [1] Wakeup Pin Enable */ uint32_t SUP : 1; /*!< [2] Supervisor Access */ uint32_t UM : 1; /*!< [3] Update Mode */ uint32_t WPS : 1; /*!< [4] Wakeup Pin Select */ uint32_t RESERVED0 : 3; /*!< [7:5] */ uint32_t OSCE : 1; /*!< [8] Oscillator Enable */ uint32_t CLKO : 1; /*!< [9] Clock Output */ uint32_t SC16P : 1; /*!< [10] Oscillator 16pF Load Configure */ uint32_t SC8P : 1; /*!< [11] Oscillator 8pF Load Configure */ uint32_t SC4P : 1; /*!< [12] Oscillator 4pF Load Configure */ uint32_t SC2P : 1; /*!< [13] Oscillator 2pF Load Configure */ uint32_t RESERVED1 : 18; /*!< [31:14] */ } B; } hw_rtc_cr_t; /*! * @name Constants and macros for entire RTC_CR register */ /*@{*/ #define HW_RTC_CR_ADDR(x) ((x) + 0x10U) #define HW_RTC_CR(x) (*(__IO hw_rtc_cr_t *) HW_RTC_CR_ADDR(x)) #define HW_RTC_CR_RD(x) (HW_RTC_CR(x).U) #define HW_RTC_CR_WR(x, v) (HW_RTC_CR(x).U = (v)) #define HW_RTC_CR_SET(x, v) (HW_RTC_CR_WR(x, HW_RTC_CR_RD(x) | (v))) #define HW_RTC_CR_CLR(x, v) (HW_RTC_CR_WR(x, HW_RTC_CR_RD(x) & ~(v))) #define HW_RTC_CR_TOG(x, v) (HW_RTC_CR_WR(x, HW_RTC_CR_RD(x) ^ (v))) /*@}*/ /* * Constants & macros for individual RTC_CR bitfields */ /*! * @name Register RTC_CR, field SWR[0] (RW) * * Values: * - 0 - No effect. * - 1 - Resets all RTC registers except for the SWR bit and the RTC_WAR and * RTC_RAR registers . The SWR bit is cleared by VBAT POR and by software * explicitly clearing it. */ /*@{*/ #define BP_RTC_CR_SWR (0U) /*!< Bit position for RTC_CR_SWR. */ #define BM_RTC_CR_SWR (0x00000001U) /*!< Bit mask for RTC_CR_SWR. */ #define BS_RTC_CR_SWR (1U) /*!< Bit field size in bits for RTC_CR_SWR. */ /*! @brief Read current value of the RTC_CR_SWR field. */ #define BR_RTC_CR_SWR(x) (BITBAND_ACCESS32(HW_RTC_CR_ADDR(x), BP_RTC_CR_SWR)) /*! @brief Format value for bitfield RTC_CR_SWR. */ #define BF_RTC_CR_SWR(v) ((uint32_t)((uint32_t)(v) << BP_RTC_CR_SWR) & BM_RTC_CR_SWR) /*! @brief Set the SWR field to a new value. */ #define BW_RTC_CR_SWR(x, v) (BITBAND_ACCESS32(HW_RTC_CR_ADDR(x), BP_RTC_CR_SWR) = (v)) /*@}*/ /*! * @name Register RTC_CR, field WPE[1] (RW) * * The wakeup pin is optional and not available on all devices. * * Values: * - 0 - Wakeup pin is disabled. * - 1 - Wakeup pin is enabled and wakeup pin asserts if the RTC interrupt * asserts or the wakeup pin is turned on. */ /*@{*/ #define BP_RTC_CR_WPE (1U) /*!< Bit position for RTC_CR_WPE. */ #define BM_RTC_CR_WPE (0x00000002U) /*!< Bit mask for RTC_CR_WPE. */ #define BS_RTC_CR_WPE (1U) /*!< Bit field size in bits for RTC_CR_WPE. */ /*! @brief Read current value of the RTC_CR_WPE field. */ #define BR_RTC_CR_WPE(x) (BITBAND_ACCESS32(HW_RTC_CR_ADDR(x), BP_RTC_CR_WPE)) /*! @brief Format value for bitfield RTC_CR_WPE. */ #define BF_RTC_CR_WPE(v) ((uint32_t)((uint32_t)(v) << BP_RTC_CR_WPE) & BM_RTC_CR_WPE) /*! @brief Set the WPE field to a new value. */ #define BW_RTC_CR_WPE(x, v) (BITBAND_ACCESS32(HW_RTC_CR_ADDR(x), BP_RTC_CR_WPE) = (v)) /*@}*/ /*! * @name Register RTC_CR, field SUP[2] (RW) * * Values: * - 0 - Non-supervisor mode write accesses are not supported and generate a bus * error. * - 1 - Non-supervisor mode write accesses are supported. */ /*@{*/ #define BP_RTC_CR_SUP (2U) /*!< Bit position for RTC_CR_SUP. */ #define BM_RTC_CR_SUP (0x00000004U) /*!< Bit mask for RTC_CR_SUP. */ #define BS_RTC_CR_SUP (1U) /*!< Bit field size in bits for RTC_CR_SUP. */ /*! @brief Read current value of the RTC_CR_SUP field. */ #define BR_RTC_CR_SUP(x) (BITBAND_ACCESS32(HW_RTC_CR_ADDR(x), BP_RTC_CR_SUP)) /*! @brief Format value for bitfield RTC_CR_SUP. */ #define BF_RTC_CR_SUP(v) ((uint32_t)((uint32_t)(v) << BP_RTC_CR_SUP) & BM_RTC_CR_SUP) /*! @brief Set the SUP field to a new value. */ #define BW_RTC_CR_SUP(x, v) (BITBAND_ACCESS32(HW_RTC_CR_ADDR(x), BP_RTC_CR_SUP) = (v)) /*@}*/ /*! * @name Register RTC_CR, field UM[3] (RW) * * Allows SR[TCE] to be written even when the Status Register is locked. When * set, the SR[TCE] can always be written if the SR[TIF] or SR[TOF] are set or if * the SR[TCE] is clear. * * Values: * - 0 - Registers cannot be written when locked. * - 1 - Registers can be written when locked under limited conditions. */ /*@{*/ #define BP_RTC_CR_UM (3U) /*!< Bit position for RTC_CR_UM. */ #define BM_RTC_CR_UM (0x00000008U) /*!< Bit mask for RTC_CR_UM. */ #define BS_RTC_CR_UM (1U) /*!< Bit field size in bits for RTC_CR_UM. */ /*! @brief Read current value of the RTC_CR_UM field. */ #define BR_RTC_CR_UM(x) (BITBAND_ACCESS32(HW_RTC_CR_ADDR(x), BP_RTC_CR_UM)) /*! @brief Format value for bitfield RTC_CR_UM. */ #define BF_RTC_CR_UM(v) ((uint32_t)((uint32_t)(v) << BP_RTC_CR_UM) & BM_RTC_CR_UM) /*! @brief Set the UM field to a new value. */ #define BW_RTC_CR_UM(x, v) (BITBAND_ACCESS32(HW_RTC_CR_ADDR(x), BP_RTC_CR_UM) = (v)) /*@}*/ /*! * @name Register RTC_CR, field WPS[4] (RW) * * The wakeup pin is optional and not available on all devices. * * Values: * - 0 - Wakeup pin asserts (active low, open drain) if the RTC interrupt * asserts or the wakeup pin is turned on. * - 1 - Wakeup pin instead outputs the RTC 32kHz clock, provided the wakeup pin * is turned on and the 32kHz clock is output to other peripherals. */ /*@{*/ #define BP_RTC_CR_WPS (4U) /*!< Bit position for RTC_CR_WPS. */ #define BM_RTC_CR_WPS (0x00000010U) /*!< Bit mask for RTC_CR_WPS. */ #define BS_RTC_CR_WPS (1U) /*!< Bit field size in bits for RTC_CR_WPS. */ /*! @brief Read current value of the RTC_CR_WPS field. */ #define BR_RTC_CR_WPS(x) (BITBAND_ACCESS32(HW_RTC_CR_ADDR(x), BP_RTC_CR_WPS)) /*! @brief Format value for bitfield RTC_CR_WPS. */ #define BF_RTC_CR_WPS(v) ((uint32_t)((uint32_t)(v) << BP_RTC_CR_WPS) & BM_RTC_CR_WPS) /*! @brief Set the WPS field to a new value. */ #define BW_RTC_CR_WPS(x, v) (BITBAND_ACCESS32(HW_RTC_CR_ADDR(x), BP_RTC_CR_WPS) = (v)) /*@}*/ /*! * @name Register RTC_CR, field OSCE[8] (RW) * * Values: * - 0 - 32.768 kHz oscillator is disabled. * - 1 - 32.768 kHz oscillator is enabled. After setting this bit, wait the * oscillator startup time before enabling the time counter to allow the 32.768 * kHz clock time to stabilize. */ /*@{*/ #define BP_RTC_CR_OSCE (8U) /*!< Bit position for RTC_CR_OSCE. */ #define BM_RTC_CR_OSCE (0x00000100U) /*!< Bit mask for RTC_CR_OSCE. */ #define BS_RTC_CR_OSCE (1U) /*!< Bit field size in bits for RTC_CR_OSCE. */ /*! @brief Read current value of the RTC_CR_OSCE field. */ #define BR_RTC_CR_OSCE(x) (BITBAND_ACCESS32(HW_RTC_CR_ADDR(x), BP_RTC_CR_OSCE)) /*! @brief Format value for bitfield RTC_CR_OSCE. */ #define BF_RTC_CR_OSCE(v) ((uint32_t)((uint32_t)(v) << BP_RTC_CR_OSCE) & BM_RTC_CR_OSCE) /*! @brief Set the OSCE field to a new value. */ #define BW_RTC_CR_OSCE(x, v) (BITBAND_ACCESS32(HW_RTC_CR_ADDR(x), BP_RTC_CR_OSCE) = (v)) /*@}*/ /*! * @name Register RTC_CR, field CLKO[9] (RW) * * Values: * - 0 - The 32 kHz clock is output to other peripherals. * - 1 - The 32 kHz clock is not output to other peripherals. */ /*@{*/ #define BP_RTC_CR_CLKO (9U) /*!< Bit position for RTC_CR_CLKO. */ #define BM_RTC_CR_CLKO (0x00000200U) /*!< Bit mask for RTC_CR_CLKO. */ #define BS_RTC_CR_CLKO (1U) /*!< Bit field size in bits for RTC_CR_CLKO. */ /*! @brief Read current value of the RTC_CR_CLKO field. */ #define BR_RTC_CR_CLKO(x) (BITBAND_ACCESS32(HW_RTC_CR_ADDR(x), BP_RTC_CR_CLKO)) /*! @brief Format value for bitfield RTC_CR_CLKO. */ #define BF_RTC_CR_CLKO(v) ((uint32_t)((uint32_t)(v) << BP_RTC_CR_CLKO) & BM_RTC_CR_CLKO) /*! @brief Set the CLKO field to a new value. */ #define BW_RTC_CR_CLKO(x, v) (BITBAND_ACCESS32(HW_RTC_CR_ADDR(x), BP_RTC_CR_CLKO) = (v)) /*@}*/ /*! * @name Register RTC_CR, field SC16P[10] (RW) * * Values: * - 0 - Disable the load. * - 1 - Enable the additional load. */ /*@{*/ #define BP_RTC_CR_SC16P (10U) /*!< Bit position for RTC_CR_SC16P. */ #define BM_RTC_CR_SC16P (0x00000400U) /*!< Bit mask for RTC_CR_SC16P. */ #define BS_RTC_CR_SC16P (1U) /*!< Bit field size in bits for RTC_CR_SC16P. */ /*! @brief Read current value of the RTC_CR_SC16P field. */ #define BR_RTC_CR_SC16P(x) (BITBAND_ACCESS32(HW_RTC_CR_ADDR(x), BP_RTC_CR_SC16P)) /*! @brief Format value for bitfield RTC_CR_SC16P. */ #define BF_RTC_CR_SC16P(v) ((uint32_t)((uint32_t)(v) << BP_RTC_CR_SC16P) & BM_RTC_CR_SC16P) /*! @brief Set the SC16P field to a new value. */ #define BW_RTC_CR_SC16P(x, v) (BITBAND_ACCESS32(HW_RTC_CR_ADDR(x), BP_RTC_CR_SC16P) = (v)) /*@}*/ /*! * @name Register RTC_CR, field SC8P[11] (RW) * * Values: * - 0 - Disable the load. * - 1 - Enable the additional load. */ /*@{*/ #define BP_RTC_CR_SC8P (11U) /*!< Bit position for RTC_CR_SC8P. */ #define BM_RTC_CR_SC8P (0x00000800U) /*!< Bit mask for RTC_CR_SC8P. */ #define BS_RTC_CR_SC8P (1U) /*!< Bit field size in bits for RTC_CR_SC8P. */ /*! @brief Read current value of the RTC_CR_SC8P field. */ #define BR_RTC_CR_SC8P(x) (BITBAND_ACCESS32(HW_RTC_CR_ADDR(x), BP_RTC_CR_SC8P)) /*! @brief Format value for bitfield RTC_CR_SC8P. */ #define BF_RTC_CR_SC8P(v) ((uint32_t)((uint32_t)(v) << BP_RTC_CR_SC8P) & BM_RTC_CR_SC8P) /*! @brief Set the SC8P field to a new value. */ #define BW_RTC_CR_SC8P(x, v) (BITBAND_ACCESS32(HW_RTC_CR_ADDR(x), BP_RTC_CR_SC8P) = (v)) /*@}*/ /*! * @name Register RTC_CR, field SC4P[12] (RW) * * Values: * - 0 - Disable the load. * - 1 - Enable the additional load. */ /*@{*/ #define BP_RTC_CR_SC4P (12U) /*!< Bit position for RTC_CR_SC4P. */ #define BM_RTC_CR_SC4P (0x00001000U) /*!< Bit mask for RTC_CR_SC4P. */ #define BS_RTC_CR_SC4P (1U) /*!< Bit field size in bits for RTC_CR_SC4P. */ /*! @brief Read current value of the RTC_CR_SC4P field. */ #define BR_RTC_CR_SC4P(x) (BITBAND_ACCESS32(HW_RTC_CR_ADDR(x), BP_RTC_CR_SC4P)) /*! @brief Format value for bitfield RTC_CR_SC4P. */ #define BF_RTC_CR_SC4P(v) ((uint32_t)((uint32_t)(v) << BP_RTC_CR_SC4P) & BM_RTC_CR_SC4P) /*! @brief Set the SC4P field to a new value. */ #define BW_RTC_CR_SC4P(x, v) (BITBAND_ACCESS32(HW_RTC_CR_ADDR(x), BP_RTC_CR_SC4P) = (v)) /*@}*/ /*! * @name Register RTC_CR, field SC2P[13] (RW) * * Values: * - 0 - Disable the load. * - 1 - Enable the additional load. */ /*@{*/ #define BP_RTC_CR_SC2P (13U) /*!< Bit position for RTC_CR_SC2P. */ #define BM_RTC_CR_SC2P (0x00002000U) /*!< Bit mask for RTC_CR_SC2P. */ #define BS_RTC_CR_SC2P (1U) /*!< Bit field size in bits for RTC_CR_SC2P. */ /*! @brief Read current value of the RTC_CR_SC2P field. */ #define BR_RTC_CR_SC2P(x) (BITBAND_ACCESS32(HW_RTC_CR_ADDR(x), BP_RTC_CR_SC2P)) /*! @brief Format value for bitfield RTC_CR_SC2P. */ #define BF_RTC_CR_SC2P(v) ((uint32_t)((uint32_t)(v) << BP_RTC_CR_SC2P) & BM_RTC_CR_SC2P) /*! @brief Set the SC2P field to a new value. */ #define BW_RTC_CR_SC2P(x, v) (BITBAND_ACCESS32(HW_RTC_CR_ADDR(x), BP_RTC_CR_SC2P) = (v)) /*@}*/ /******************************************************************************* * HW_RTC_SR - RTC Status Register ******************************************************************************/ /*! * @brief HW_RTC_SR - RTC Status Register (RW) * * Reset value: 0x00000001U */ typedef union _hw_rtc_sr { uint32_t U; struct _hw_rtc_sr_bitfields { uint32_t TIF : 1; /*!< [0] Time Invalid Flag */ uint32_t TOF : 1; /*!< [1] Time Overflow Flag */ uint32_t TAF : 1; /*!< [2] Time Alarm Flag */ uint32_t RESERVED0 : 1; /*!< [3] */ uint32_t TCE : 1; /*!< [4] Time Counter Enable */ uint32_t RESERVED1 : 27; /*!< [31:5] */ } B; } hw_rtc_sr_t; /*! * @name Constants and macros for entire RTC_SR register */ /*@{*/ #define HW_RTC_SR_ADDR(x) ((x) + 0x14U) #define HW_RTC_SR(x) (*(__IO hw_rtc_sr_t *) HW_RTC_SR_ADDR(x)) #define HW_RTC_SR_RD(x) (HW_RTC_SR(x).U) #define HW_RTC_SR_WR(x, v) (HW_RTC_SR(x).U = (v)) #define HW_RTC_SR_SET(x, v) (HW_RTC_SR_WR(x, HW_RTC_SR_RD(x) | (v))) #define HW_RTC_SR_CLR(x, v) (HW_RTC_SR_WR(x, HW_RTC_SR_RD(x) & ~(v))) #define HW_RTC_SR_TOG(x, v) (HW_RTC_SR_WR(x, HW_RTC_SR_RD(x) ^ (v))) /*@}*/ /* * Constants & macros for individual RTC_SR bitfields */ /*! * @name Register RTC_SR, field TIF[0] (RO) * * The time invalid flag is set on VBAT POR or software reset. The TSR and TPR * do not increment and read as zero when this bit is set. This bit is cleared by * writing the TSR register when the time counter is disabled. * * Values: * - 0 - Time is valid. * - 1 - Time is invalid and time counter is read as zero. */ /*@{*/ #define BP_RTC_SR_TIF (0U) /*!< Bit position for RTC_SR_TIF. */ #define BM_RTC_SR_TIF (0x00000001U) /*!< Bit mask for RTC_SR_TIF. */ #define BS_RTC_SR_TIF (1U) /*!< Bit field size in bits for RTC_SR_TIF. */ /*! @brief Read current value of the RTC_SR_TIF field. */ #define BR_RTC_SR_TIF(x) (BITBAND_ACCESS32(HW_RTC_SR_ADDR(x), BP_RTC_SR_TIF)) /*@}*/ /*! * @name Register RTC_SR, field TOF[1] (RO) * * Time overflow flag is set when the time counter is enabled and overflows. The * TSR and TPR do not increment and read as zero when this bit is set. This bit * is cleared by writing the TSR register when the time counter is disabled. * * Values: * - 0 - Time overflow has not occurred. * - 1 - Time overflow has occurred and time counter is read as zero. */ /*@{*/ #define BP_RTC_SR_TOF (1U) /*!< Bit position for RTC_SR_TOF. */ #define BM_RTC_SR_TOF (0x00000002U) /*!< Bit mask for RTC_SR_TOF. */ #define BS_RTC_SR_TOF (1U) /*!< Bit field size in bits for RTC_SR_TOF. */ /*! @brief Read current value of the RTC_SR_TOF field. */ #define BR_RTC_SR_TOF(x) (BITBAND_ACCESS32(HW_RTC_SR_ADDR(x), BP_RTC_SR_TOF)) /*@}*/ /*! * @name Register RTC_SR, field TAF[2] (RO) * * Time alarm flag is set when the TAR[TAR] equals the TSR[TSR] and the TSR[TSR] * increments. This bit is cleared by writing the TAR register. * * Values: * - 0 - Time alarm has not occurred. * - 1 - Time alarm has occurred. */ /*@{*/ #define BP_RTC_SR_TAF (2U) /*!< Bit position for RTC_SR_TAF. */ #define BM_RTC_SR_TAF (0x00000004U) /*!< Bit mask for RTC_SR_TAF. */ #define BS_RTC_SR_TAF (1U) /*!< Bit field size in bits for RTC_SR_TAF. */ /*! @brief Read current value of the RTC_SR_TAF field. */ #define BR_RTC_SR_TAF(x) (BITBAND_ACCESS32(HW_RTC_SR_ADDR(x), BP_RTC_SR_TAF)) /*@}*/ /*! * @name Register RTC_SR, field TCE[4] (RW) * * When time counter is disabled the TSR register and TPR register are * writeable, but do not increment. When time counter is enabled the TSR register and TPR * register are not writeable, but increment. * * Values: * - 0 - Time counter is disabled. * - 1 - Time counter is enabled. */ /*@{*/ #define BP_RTC_SR_TCE (4U) /*!< Bit position for RTC_SR_TCE. */ #define BM_RTC_SR_TCE (0x00000010U) /*!< Bit mask for RTC_SR_TCE. */ #define BS_RTC_SR_TCE (1U) /*!< Bit field size in bits for RTC_SR_TCE. */ /*! @brief Read current value of the RTC_SR_TCE field. */ #define BR_RTC_SR_TCE(x) (BITBAND_ACCESS32(HW_RTC_SR_ADDR(x), BP_RTC_SR_TCE)) /*! @brief Format value for bitfield RTC_SR_TCE. */ #define BF_RTC_SR_TCE(v) ((uint32_t)((uint32_t)(v) << BP_RTC_SR_TCE) & BM_RTC_SR_TCE) /*! @brief Set the TCE field to a new value. */ #define BW_RTC_SR_TCE(x, v) (BITBAND_ACCESS32(HW_RTC_SR_ADDR(x), BP_RTC_SR_TCE) = (v)) /*@}*/ /******************************************************************************* * HW_RTC_LR - RTC Lock Register ******************************************************************************/ /*! * @brief HW_RTC_LR - RTC Lock Register (RW) * * Reset value: 0x000000FFU */ typedef union _hw_rtc_lr { uint32_t U; struct _hw_rtc_lr_bitfields { uint32_t RESERVED0 : 3; /*!< [2:0] */ uint32_t TCL : 1; /*!< [3] Time Compensation Lock */ uint32_t CRL : 1; /*!< [4] Control Register Lock */ uint32_t SRL : 1; /*!< [5] Status Register Lock */ uint32_t LRL : 1; /*!< [6] Lock Register Lock */ uint32_t RESERVED1 : 25; /*!< [31:7] */ } B; } hw_rtc_lr_t; /*! * @name Constants and macros for entire RTC_LR register */ /*@{*/ #define HW_RTC_LR_ADDR(x) ((x) + 0x18U) #define HW_RTC_LR(x) (*(__IO hw_rtc_lr_t *) HW_RTC_LR_ADDR(x)) #define HW_RTC_LR_RD(x) (HW_RTC_LR(x).U) #define HW_RTC_LR_WR(x, v) (HW_RTC_LR(x).U = (v)) #define HW_RTC_LR_SET(x, v) (HW_RTC_LR_WR(x, HW_RTC_LR_RD(x) | (v))) #define HW_RTC_LR_CLR(x, v) (HW_RTC_LR_WR(x, HW_RTC_LR_RD(x) & ~(v))) #define HW_RTC_LR_TOG(x, v) (HW_RTC_LR_WR(x, HW_RTC_LR_RD(x) ^ (v))) /*@}*/ /* * Constants & macros for individual RTC_LR bitfields */ /*! * @name Register RTC_LR, field TCL[3] (RW) * * After being cleared, this bit can be set only by VBAT POR or software reset. * * Values: * - 0 - Time Compensation Register is locked and writes are ignored. * - 1 - Time Compensation Register is not locked and writes complete as normal. */ /*@{*/ #define BP_RTC_LR_TCL (3U) /*!< Bit position for RTC_LR_TCL. */ #define BM_RTC_LR_TCL (0x00000008U) /*!< Bit mask for RTC_LR_TCL. */ #define BS_RTC_LR_TCL (1U) /*!< Bit field size in bits for RTC_LR_TCL. */ /*! @brief Read current value of the RTC_LR_TCL field. */ #define BR_RTC_LR_TCL(x) (BITBAND_ACCESS32(HW_RTC_LR_ADDR(x), BP_RTC_LR_TCL)) /*! @brief Format value for bitfield RTC_LR_TCL. */ #define BF_RTC_LR_TCL(v) ((uint32_t)((uint32_t)(v) << BP_RTC_LR_TCL) & BM_RTC_LR_TCL) /*! @brief Set the TCL field to a new value. */ #define BW_RTC_LR_TCL(x, v) (BITBAND_ACCESS32(HW_RTC_LR_ADDR(x), BP_RTC_LR_TCL) = (v)) /*@}*/ /*! * @name Register RTC_LR, field CRL[4] (RW) * * After being cleared, this bit can only be set by VBAT POR. * * Values: * - 0 - Control Register is locked and writes are ignored. * - 1 - Control Register is not locked and writes complete as normal. */ /*@{*/ #define BP_RTC_LR_CRL (4U) /*!< Bit position for RTC_LR_CRL. */ #define BM_RTC_LR_CRL (0x00000010U) /*!< Bit mask for RTC_LR_CRL. */ #define BS_RTC_LR_CRL (1U) /*!< Bit field size in bits for RTC_LR_CRL. */ /*! @brief Read current value of the RTC_LR_CRL field. */ #define BR_RTC_LR_CRL(x) (BITBAND_ACCESS32(HW_RTC_LR_ADDR(x), BP_RTC_LR_CRL)) /*! @brief Format value for bitfield RTC_LR_CRL. */ #define BF_RTC_LR_CRL(v) ((uint32_t)((uint32_t)(v) << BP_RTC_LR_CRL) & BM_RTC_LR_CRL) /*! @brief Set the CRL field to a new value. */ #define BW_RTC_LR_CRL(x, v) (BITBAND_ACCESS32(HW_RTC_LR_ADDR(x), BP_RTC_LR_CRL) = (v)) /*@}*/ /*! * @name Register RTC_LR, field SRL[5] (RW) * * After being cleared, this bit can be set only by VBAT POR or software reset. * * Values: * - 0 - Status Register is locked and writes are ignored. * - 1 - Status Register is not locked and writes complete as normal. */ /*@{*/ #define BP_RTC_LR_SRL (5U) /*!< Bit position for RTC_LR_SRL. */ #define BM_RTC_LR_SRL (0x00000020U) /*!< Bit mask for RTC_LR_SRL. */ #define BS_RTC_LR_SRL (1U) /*!< Bit field size in bits for RTC_LR_SRL. */ /*! @brief Read current value of the RTC_LR_SRL field. */ #define BR_RTC_LR_SRL(x) (BITBAND_ACCESS32(HW_RTC_LR_ADDR(x), BP_RTC_LR_SRL)) /*! @brief Format value for bitfield RTC_LR_SRL. */ #define BF_RTC_LR_SRL(v) ((uint32_t)((uint32_t)(v) << BP_RTC_LR_SRL) & BM_RTC_LR_SRL) /*! @brief Set the SRL field to a new value. */ #define BW_RTC_LR_SRL(x, v) (BITBAND_ACCESS32(HW_RTC_LR_ADDR(x), BP_RTC_LR_SRL) = (v)) /*@}*/ /*! * @name Register RTC_LR, field LRL[6] (RW) * * After being cleared, this bit can be set only by VBAT POR or software reset. * * Values: * - 0 - Lock Register is locked and writes are ignored. * - 1 - Lock Register is not locked and writes complete as normal. */ /*@{*/ #define BP_RTC_LR_LRL (6U) /*!< Bit position for RTC_LR_LRL. */ #define BM_RTC_LR_LRL (0x00000040U) /*!< Bit mask for RTC_LR_LRL. */ #define BS_RTC_LR_LRL (1U) /*!< Bit field size in bits for RTC_LR_LRL. */ /*! @brief Read current value of the RTC_LR_LRL field. */ #define BR_RTC_LR_LRL(x) (BITBAND_ACCESS32(HW_RTC_LR_ADDR(x), BP_RTC_LR_LRL)) /*! @brief Format value for bitfield RTC_LR_LRL. */ #define BF_RTC_LR_LRL(v) ((uint32_t)((uint32_t)(v) << BP_RTC_LR_LRL) & BM_RTC_LR_LRL) /*! @brief Set the LRL field to a new value. */ #define BW_RTC_LR_LRL(x, v) (BITBAND_ACCESS32(HW_RTC_LR_ADDR(x), BP_RTC_LR_LRL) = (v)) /*@}*/ /******************************************************************************* * HW_RTC_IER - RTC Interrupt Enable Register ******************************************************************************/ /*! * @brief HW_RTC_IER - RTC Interrupt Enable Register (RW) * * Reset value: 0x00000007U */ typedef union _hw_rtc_ier { uint32_t U; struct _hw_rtc_ier_bitfields { uint32_t TIIE : 1; /*!< [0] Time Invalid Interrupt Enable */ uint32_t TOIE : 1; /*!< [1] Time Overflow Interrupt Enable */ uint32_t TAIE : 1; /*!< [2] Time Alarm Interrupt Enable */ uint32_t RESERVED0 : 1; /*!< [3] */ uint32_t TSIE : 1; /*!< [4] Time Seconds Interrupt Enable */ uint32_t RESERVED1 : 2; /*!< [6:5] */ uint32_t WPON : 1; /*!< [7] Wakeup Pin On */ uint32_t RESERVED2 : 24; /*!< [31:8] */ } B; } hw_rtc_ier_t; /*! * @name Constants and macros for entire RTC_IER register */ /*@{*/ #define HW_RTC_IER_ADDR(x) ((x) + 0x1CU) #define HW_RTC_IER(x) (*(__IO hw_rtc_ier_t *) HW_RTC_IER_ADDR(x)) #define HW_RTC_IER_RD(x) (HW_RTC_IER(x).U) #define HW_RTC_IER_WR(x, v) (HW_RTC_IER(x).U = (v)) #define HW_RTC_IER_SET(x, v) (HW_RTC_IER_WR(x, HW_RTC_IER_RD(x) | (v))) #define HW_RTC_IER_CLR(x, v) (HW_RTC_IER_WR(x, HW_RTC_IER_RD(x) & ~(v))) #define HW_RTC_IER_TOG(x, v) (HW_RTC_IER_WR(x, HW_RTC_IER_RD(x) ^ (v))) /*@}*/ /* * Constants & macros for individual RTC_IER bitfields */ /*! * @name Register RTC_IER, field TIIE[0] (RW) * * Values: * - 0 - Time invalid flag does not generate an interrupt. * - 1 - Time invalid flag does generate an interrupt. */ /*@{*/ #define BP_RTC_IER_TIIE (0U) /*!< Bit position for RTC_IER_TIIE. */ #define BM_RTC_IER_TIIE (0x00000001U) /*!< Bit mask for RTC_IER_TIIE. */ #define BS_RTC_IER_TIIE (1U) /*!< Bit field size in bits for RTC_IER_TIIE. */ /*! @brief Read current value of the RTC_IER_TIIE field. */ #define BR_RTC_IER_TIIE(x) (BITBAND_ACCESS32(HW_RTC_IER_ADDR(x), BP_RTC_IER_TIIE)) /*! @brief Format value for bitfield RTC_IER_TIIE. */ #define BF_RTC_IER_TIIE(v) ((uint32_t)((uint32_t)(v) << BP_RTC_IER_TIIE) & BM_RTC_IER_TIIE) /*! @brief Set the TIIE field to a new value. */ #define BW_RTC_IER_TIIE(x, v) (BITBAND_ACCESS32(HW_RTC_IER_ADDR(x), BP_RTC_IER_TIIE) = (v)) /*@}*/ /*! * @name Register RTC_IER, field TOIE[1] (RW) * * Values: * - 0 - Time overflow flag does not generate an interrupt. * - 1 - Time overflow flag does generate an interrupt. */ /*@{*/ #define BP_RTC_IER_TOIE (1U) /*!< Bit position for RTC_IER_TOIE. */ #define BM_RTC_IER_TOIE (0x00000002U) /*!< Bit mask for RTC_IER_TOIE. */ #define BS_RTC_IER_TOIE (1U) /*!< Bit field size in bits for RTC_IER_TOIE. */ /*! @brief Read current value of the RTC_IER_TOIE field. */ #define BR_RTC_IER_TOIE(x) (BITBAND_ACCESS32(HW_RTC_IER_ADDR(x), BP_RTC_IER_TOIE)) /*! @brief Format value for bitfield RTC_IER_TOIE. */ #define BF_RTC_IER_TOIE(v) ((uint32_t)((uint32_t)(v) << BP_RTC_IER_TOIE) & BM_RTC_IER_TOIE) /*! @brief Set the TOIE field to a new value. */ #define BW_RTC_IER_TOIE(x, v) (BITBAND_ACCESS32(HW_RTC_IER_ADDR(x), BP_RTC_IER_TOIE) = (v)) /*@}*/ /*! * @name Register RTC_IER, field TAIE[2] (RW) * * Values: * - 0 - Time alarm flag does not generate an interrupt. * - 1 - Time alarm flag does generate an interrupt. */ /*@{*/ #define BP_RTC_IER_TAIE (2U) /*!< Bit position for RTC_IER_TAIE. */ #define BM_RTC_IER_TAIE (0x00000004U) /*!< Bit mask for RTC_IER_TAIE. */ #define BS_RTC_IER_TAIE (1U) /*!< Bit field size in bits for RTC_IER_TAIE. */ /*! @brief Read current value of the RTC_IER_TAIE field. */ #define BR_RTC_IER_TAIE(x) (BITBAND_ACCESS32(HW_RTC_IER_ADDR(x), BP_RTC_IER_TAIE)) /*! @brief Format value for bitfield RTC_IER_TAIE. */ #define BF_RTC_IER_TAIE(v) ((uint32_t)((uint32_t)(v) << BP_RTC_IER_TAIE) & BM_RTC_IER_TAIE) /*! @brief Set the TAIE field to a new value. */ #define BW_RTC_IER_TAIE(x, v) (BITBAND_ACCESS32(HW_RTC_IER_ADDR(x), BP_RTC_IER_TAIE) = (v)) /*@}*/ /*! * @name Register RTC_IER, field TSIE[4] (RW) * * The seconds interrupt is an edge-sensitive interrupt with a dedicated * interrupt vector. It is generated once a second and requires no software overhead * (there is no corresponding status flag to clear). * * Values: * - 0 - Seconds interrupt is disabled. * - 1 - Seconds interrupt is enabled. */ /*@{*/ #define BP_RTC_IER_TSIE (4U) /*!< Bit position for RTC_IER_TSIE. */ #define BM_RTC_IER_TSIE (0x00000010U) /*!< Bit mask for RTC_IER_TSIE. */ #define BS_RTC_IER_TSIE (1U) /*!< Bit field size in bits for RTC_IER_TSIE. */ /*! @brief Read current value of the RTC_IER_TSIE field. */ #define BR_RTC_IER_TSIE(x) (BITBAND_ACCESS32(HW_RTC_IER_ADDR(x), BP_RTC_IER_TSIE)) /*! @brief Format value for bitfield RTC_IER_TSIE. */ #define BF_RTC_IER_TSIE(v) ((uint32_t)((uint32_t)(v) << BP_RTC_IER_TSIE) & BM_RTC_IER_TSIE) /*! @brief Set the TSIE field to a new value. */ #define BW_RTC_IER_TSIE(x, v) (BITBAND_ACCESS32(HW_RTC_IER_ADDR(x), BP_RTC_IER_TSIE) = (v)) /*@}*/ /*! * @name Register RTC_IER, field WPON[7] (RW) * * The wakeup pin is optional and not available on all devices. Whenever the * wakeup pin is enabled and this bit is set, the wakeup pin will assert. * * Values: * - 0 - No effect. * - 1 - If the wakeup pin is enabled, then the wakeup pin will assert. */ /*@{*/ #define BP_RTC_IER_WPON (7U) /*!< Bit position for RTC_IER_WPON. */ #define BM_RTC_IER_WPON (0x00000080U) /*!< Bit mask for RTC_IER_WPON. */ #define BS_RTC_IER_WPON (1U) /*!< Bit field size in bits for RTC_IER_WPON. */ /*! @brief Read current value of the RTC_IER_WPON field. */ #define BR_RTC_IER_WPON(x) (BITBAND_ACCESS32(HW_RTC_IER_ADDR(x), BP_RTC_IER_WPON)) /*! @brief Format value for bitfield RTC_IER_WPON. */ #define BF_RTC_IER_WPON(v) ((uint32_t)((uint32_t)(v) << BP_RTC_IER_WPON) & BM_RTC_IER_WPON) /*! @brief Set the WPON field to a new value. */ #define BW_RTC_IER_WPON(x, v) (BITBAND_ACCESS32(HW_RTC_IER_ADDR(x), BP_RTC_IER_WPON) = (v)) /*@}*/ /******************************************************************************* * HW_RTC_WAR - RTC Write Access Register ******************************************************************************/ /*! * @brief HW_RTC_WAR - RTC Write Access Register (RW) * * Reset value: 0x000000FFU */ typedef union _hw_rtc_war { uint32_t U; struct _hw_rtc_war_bitfields { uint32_t TSRW : 1; /*!< [0] Time Seconds Register Write */ uint32_t TPRW : 1; /*!< [1] Time Prescaler Register Write */ uint32_t TARW : 1; /*!< [2] Time Alarm Register Write */ uint32_t TCRW : 1; /*!< [3] Time Compensation Register Write */ uint32_t CRW : 1; /*!< [4] Control Register Write */ uint32_t SRW : 1; /*!< [5] Status Register Write */ uint32_t LRW : 1; /*!< [6] Lock Register Write */ uint32_t IERW : 1; /*!< [7] Interrupt Enable Register Write */ uint32_t RESERVED0 : 24; /*!< [31:8] */ } B; } hw_rtc_war_t; /*! * @name Constants and macros for entire RTC_WAR register */ /*@{*/ #define HW_RTC_WAR_ADDR(x) ((x) + 0x800U) #define HW_RTC_WAR(x) (*(__IO hw_rtc_war_t *) HW_RTC_WAR_ADDR(x)) #define HW_RTC_WAR_RD(x) (HW_RTC_WAR(x).U) #define HW_RTC_WAR_WR(x, v) (HW_RTC_WAR(x).U = (v)) #define HW_RTC_WAR_SET(x, v) (HW_RTC_WAR_WR(x, HW_RTC_WAR_RD(x) | (v))) #define HW_RTC_WAR_CLR(x, v) (HW_RTC_WAR_WR(x, HW_RTC_WAR_RD(x) & ~(v))) #define HW_RTC_WAR_TOG(x, v) (HW_RTC_WAR_WR(x, HW_RTC_WAR_RD(x) ^ (v))) /*@}*/ /* * Constants & macros for individual RTC_WAR bitfields */ /*! * @name Register RTC_WAR, field TSRW[0] (RW) * * After being cleared, this bit is set only by system reset. It is not affected * by VBAT POR or software reset. * * Values: * - 0 - Writes to the Time Seconds Register are ignored. * - 1 - Writes to the Time Seconds Register complete as normal. */ /*@{*/ #define BP_RTC_WAR_TSRW (0U) /*!< Bit position for RTC_WAR_TSRW. */ #define BM_RTC_WAR_TSRW (0x00000001U) /*!< Bit mask for RTC_WAR_TSRW. */ #define BS_RTC_WAR_TSRW (1U) /*!< Bit field size in bits for RTC_WAR_TSRW. */ /*! @brief Read current value of the RTC_WAR_TSRW field. */ #define BR_RTC_WAR_TSRW(x) (BITBAND_ACCESS32(HW_RTC_WAR_ADDR(x), BP_RTC_WAR_TSRW)) /*! @brief Format value for bitfield RTC_WAR_TSRW. */ #define BF_RTC_WAR_TSRW(v) ((uint32_t)((uint32_t)(v) << BP_RTC_WAR_TSRW) & BM_RTC_WAR_TSRW) /*! @brief Set the TSRW field to a new value. */ #define BW_RTC_WAR_TSRW(x, v) (BITBAND_ACCESS32(HW_RTC_WAR_ADDR(x), BP_RTC_WAR_TSRW) = (v)) /*@}*/ /*! * @name Register RTC_WAR, field TPRW[1] (RW) * * After being cleared, this bit is set only by system reset. It is not affected * by VBAT POR or software reset. * * Values: * - 0 - Writes to the Time Prescaler Register are ignored. * - 1 - Writes to the Time Prescaler Register complete as normal. */ /*@{*/ #define BP_RTC_WAR_TPRW (1U) /*!< Bit position for RTC_WAR_TPRW. */ #define BM_RTC_WAR_TPRW (0x00000002U) /*!< Bit mask for RTC_WAR_TPRW. */ #define BS_RTC_WAR_TPRW (1U) /*!< Bit field size in bits for RTC_WAR_TPRW. */ /*! @brief Read current value of the RTC_WAR_TPRW field. */ #define BR_RTC_WAR_TPRW(x) (BITBAND_ACCESS32(HW_RTC_WAR_ADDR(x), BP_RTC_WAR_TPRW)) /*! @brief Format value for bitfield RTC_WAR_TPRW. */ #define BF_RTC_WAR_TPRW(v) ((uint32_t)((uint32_t)(v) << BP_RTC_WAR_TPRW) & BM_RTC_WAR_TPRW) /*! @brief Set the TPRW field to a new value. */ #define BW_RTC_WAR_TPRW(x, v) (BITBAND_ACCESS32(HW_RTC_WAR_ADDR(x), BP_RTC_WAR_TPRW) = (v)) /*@}*/ /*! * @name Register RTC_WAR, field TARW[2] (RW) * * After being cleared, this bit is set only by system reset. It is not affected * by VBAT POR or software reset. * * Values: * - 0 - Writes to the Time Alarm Register are ignored. * - 1 - Writes to the Time Alarm Register complete as normal. */ /*@{*/ #define BP_RTC_WAR_TARW (2U) /*!< Bit position for RTC_WAR_TARW. */ #define BM_RTC_WAR_TARW (0x00000004U) /*!< Bit mask for RTC_WAR_TARW. */ #define BS_RTC_WAR_TARW (1U) /*!< Bit field size in bits for RTC_WAR_TARW. */ /*! @brief Read current value of the RTC_WAR_TARW field. */ #define BR_RTC_WAR_TARW(x) (BITBAND_ACCESS32(HW_RTC_WAR_ADDR(x), BP_RTC_WAR_TARW)) /*! @brief Format value for bitfield RTC_WAR_TARW. */ #define BF_RTC_WAR_TARW(v) ((uint32_t)((uint32_t)(v) << BP_RTC_WAR_TARW) & BM_RTC_WAR_TARW) /*! @brief Set the TARW field to a new value. */ #define BW_RTC_WAR_TARW(x, v) (BITBAND_ACCESS32(HW_RTC_WAR_ADDR(x), BP_RTC_WAR_TARW) = (v)) /*@}*/ /*! * @name Register RTC_WAR, field TCRW[3] (RW) * * After being cleared, this bit is set only by system reset. It is not affected * by VBAT POR or software reset. * * Values: * - 0 - Writes to the Time Compensation Register are ignored. * - 1 - Writes to the Time Compensation Register complete as normal. */ /*@{*/ #define BP_RTC_WAR_TCRW (3U) /*!< Bit position for RTC_WAR_TCRW. */ #define BM_RTC_WAR_TCRW (0x00000008U) /*!< Bit mask for RTC_WAR_TCRW. */ #define BS_RTC_WAR_TCRW (1U) /*!< Bit field size in bits for RTC_WAR_TCRW. */ /*! @brief Read current value of the RTC_WAR_TCRW field. */ #define BR_RTC_WAR_TCRW(x) (BITBAND_ACCESS32(HW_RTC_WAR_ADDR(x), BP_RTC_WAR_TCRW)) /*! @brief Format value for bitfield RTC_WAR_TCRW. */ #define BF_RTC_WAR_TCRW(v) ((uint32_t)((uint32_t)(v) << BP_RTC_WAR_TCRW) & BM_RTC_WAR_TCRW) /*! @brief Set the TCRW field to a new value. */ #define BW_RTC_WAR_TCRW(x, v) (BITBAND_ACCESS32(HW_RTC_WAR_ADDR(x), BP_RTC_WAR_TCRW) = (v)) /*@}*/ /*! * @name Register RTC_WAR, field CRW[4] (RW) * * After being cleared, this bit is set only by system reset. It is not affected * by VBAT POR or software reset. * * Values: * - 0 - Writes to the Control Register are ignored. * - 1 - Writes to the Control Register complete as normal. */ /*@{*/ #define BP_RTC_WAR_CRW (4U) /*!< Bit position for RTC_WAR_CRW. */ #define BM_RTC_WAR_CRW (0x00000010U) /*!< Bit mask for RTC_WAR_CRW. */ #define BS_RTC_WAR_CRW (1U) /*!< Bit field size in bits for RTC_WAR_CRW. */ /*! @brief Read current value of the RTC_WAR_CRW field. */ #define BR_RTC_WAR_CRW(x) (BITBAND_ACCESS32(HW_RTC_WAR_ADDR(x), BP_RTC_WAR_CRW)) /*! @brief Format value for bitfield RTC_WAR_CRW. */ #define BF_RTC_WAR_CRW(v) ((uint32_t)((uint32_t)(v) << BP_RTC_WAR_CRW) & BM_RTC_WAR_CRW) /*! @brief Set the CRW field to a new value. */ #define BW_RTC_WAR_CRW(x, v) (BITBAND_ACCESS32(HW_RTC_WAR_ADDR(x), BP_RTC_WAR_CRW) = (v)) /*@}*/ /*! * @name Register RTC_WAR, field SRW[5] (RW) * * After being cleared, this bit is set only by system reset. It is not affected * by VBAT POR or software reset. * * Values: * - 0 - Writes to the Status Register are ignored. * - 1 - Writes to the Status Register complete as normal. */ /*@{*/ #define BP_RTC_WAR_SRW (5U) /*!< Bit position for RTC_WAR_SRW. */ #define BM_RTC_WAR_SRW (0x00000020U) /*!< Bit mask for RTC_WAR_SRW. */ #define BS_RTC_WAR_SRW (1U) /*!< Bit field size in bits for RTC_WAR_SRW. */ /*! @brief Read current value of the RTC_WAR_SRW field. */ #define BR_RTC_WAR_SRW(x) (BITBAND_ACCESS32(HW_RTC_WAR_ADDR(x), BP_RTC_WAR_SRW)) /*! @brief Format value for bitfield RTC_WAR_SRW. */ #define BF_RTC_WAR_SRW(v) ((uint32_t)((uint32_t)(v) << BP_RTC_WAR_SRW) & BM_RTC_WAR_SRW) /*! @brief Set the SRW field to a new value. */ #define BW_RTC_WAR_SRW(x, v) (BITBAND_ACCESS32(HW_RTC_WAR_ADDR(x), BP_RTC_WAR_SRW) = (v)) /*@}*/ /*! * @name Register RTC_WAR, field LRW[6] (RW) * * After being cleared, this bit is set only by system reset. It is not affected * by VBAT POR or software reset. * * Values: * - 0 - Writes to the Lock Register are ignored. * - 1 - Writes to the Lock Register complete as normal. */ /*@{*/ #define BP_RTC_WAR_LRW (6U) /*!< Bit position for RTC_WAR_LRW. */ #define BM_RTC_WAR_LRW (0x00000040U) /*!< Bit mask for RTC_WAR_LRW. */ #define BS_RTC_WAR_LRW (1U) /*!< Bit field size in bits for RTC_WAR_LRW. */ /*! @brief Read current value of the RTC_WAR_LRW field. */ #define BR_RTC_WAR_LRW(x) (BITBAND_ACCESS32(HW_RTC_WAR_ADDR(x), BP_RTC_WAR_LRW)) /*! @brief Format value for bitfield RTC_WAR_LRW. */ #define BF_RTC_WAR_LRW(v) ((uint32_t)((uint32_t)(v) << BP_RTC_WAR_LRW) & BM_RTC_WAR_LRW) /*! @brief Set the LRW field to a new value. */ #define BW_RTC_WAR_LRW(x, v) (BITBAND_ACCESS32(HW_RTC_WAR_ADDR(x), BP_RTC_WAR_LRW) = (v)) /*@}*/ /*! * @name Register RTC_WAR, field IERW[7] (RW) * * After being cleared, this bit is set only by system reset. It is not affected * by VBAT POR or software reset. * * Values: * - 0 - Writes to the Interupt Enable Register are ignored. * - 1 - Writes to the Interrupt Enable Register complete as normal. */ /*@{*/ #define BP_RTC_WAR_IERW (7U) /*!< Bit position for RTC_WAR_IERW. */ #define BM_RTC_WAR_IERW (0x00000080U) /*!< Bit mask for RTC_WAR_IERW. */ #define BS_RTC_WAR_IERW (1U) /*!< Bit field size in bits for RTC_WAR_IERW. */ /*! @brief Read current value of the RTC_WAR_IERW field. */ #define BR_RTC_WAR_IERW(x) (BITBAND_ACCESS32(HW_RTC_WAR_ADDR(x), BP_RTC_WAR_IERW)) /*! @brief Format value for bitfield RTC_WAR_IERW. */ #define BF_RTC_WAR_IERW(v) ((uint32_t)((uint32_t)(v) << BP_RTC_WAR_IERW) & BM_RTC_WAR_IERW) /*! @brief Set the IERW field to a new value. */ #define BW_RTC_WAR_IERW(x, v) (BITBAND_ACCESS32(HW_RTC_WAR_ADDR(x), BP_RTC_WAR_IERW) = (v)) /*@}*/ /******************************************************************************* * HW_RTC_RAR - RTC Read Access Register ******************************************************************************/ /*! * @brief HW_RTC_RAR - RTC Read Access Register (RW) * * Reset value: 0x000000FFU */ typedef union _hw_rtc_rar { uint32_t U; struct _hw_rtc_rar_bitfields { uint32_t TSRR : 1; /*!< [0] Time Seconds Register Read */ uint32_t TPRR : 1; /*!< [1] Time Prescaler Register Read */ uint32_t TARR : 1; /*!< [2] Time Alarm Register Read */ uint32_t TCRR : 1; /*!< [3] Time Compensation Register Read */ uint32_t CRR : 1; /*!< [4] Control Register Read */ uint32_t SRR : 1; /*!< [5] Status Register Read */ uint32_t LRR : 1; /*!< [6] Lock Register Read */ uint32_t IERR : 1; /*!< [7] Interrupt Enable Register Read */ uint32_t RESERVED0 : 24; /*!< [31:8] */ } B; } hw_rtc_rar_t; /*! * @name Constants and macros for entire RTC_RAR register */ /*@{*/ #define HW_RTC_RAR_ADDR(x) ((x) + 0x804U) #define HW_RTC_RAR(x) (*(__IO hw_rtc_rar_t *) HW_RTC_RAR_ADDR(x)) #define HW_RTC_RAR_RD(x) (HW_RTC_RAR(x).U) #define HW_RTC_RAR_WR(x, v) (HW_RTC_RAR(x).U = (v)) #define HW_RTC_RAR_SET(x, v) (HW_RTC_RAR_WR(x, HW_RTC_RAR_RD(x) | (v))) #define HW_RTC_RAR_CLR(x, v) (HW_RTC_RAR_WR(x, HW_RTC_RAR_RD(x) & ~(v))) #define HW_RTC_RAR_TOG(x, v) (HW_RTC_RAR_WR(x, HW_RTC_RAR_RD(x) ^ (v))) /*@}*/ /* * Constants & macros for individual RTC_RAR bitfields */ /*! * @name Register RTC_RAR, field TSRR[0] (RW) * * After being cleared, this bit is set only by system reset. It is not affected * by VBAT POR or software reset. * * Values: * - 0 - Reads to the Time Seconds Register are ignored. * - 1 - Reads to the Time Seconds Register complete as normal. */ /*@{*/ #define BP_RTC_RAR_TSRR (0U) /*!< Bit position for RTC_RAR_TSRR. */ #define BM_RTC_RAR_TSRR (0x00000001U) /*!< Bit mask for RTC_RAR_TSRR. */ #define BS_RTC_RAR_TSRR (1U) /*!< Bit field size in bits for RTC_RAR_TSRR. */ /*! @brief Read current value of the RTC_RAR_TSRR field. */ #define BR_RTC_RAR_TSRR(x) (BITBAND_ACCESS32(HW_RTC_RAR_ADDR(x), BP_RTC_RAR_TSRR)) /*! @brief Format value for bitfield RTC_RAR_TSRR. */ #define BF_RTC_RAR_TSRR(v) ((uint32_t)((uint32_t)(v) << BP_RTC_RAR_TSRR) & BM_RTC_RAR_TSRR) /*! @brief Set the TSRR field to a new value. */ #define BW_RTC_RAR_TSRR(x, v) (BITBAND_ACCESS32(HW_RTC_RAR_ADDR(x), BP_RTC_RAR_TSRR) = (v)) /*@}*/ /*! * @name Register RTC_RAR, field TPRR[1] (RW) * * After being cleared, this bit is set only by system reset. It is not affected * by VBAT POR or software reset. * * Values: * - 0 - Reads to the Time Pprescaler Register are ignored. * - 1 - Reads to the Time Prescaler Register complete as normal. */ /*@{*/ #define BP_RTC_RAR_TPRR (1U) /*!< Bit position for RTC_RAR_TPRR. */ #define BM_RTC_RAR_TPRR (0x00000002U) /*!< Bit mask for RTC_RAR_TPRR. */ #define BS_RTC_RAR_TPRR (1U) /*!< Bit field size in bits for RTC_RAR_TPRR. */ /*! @brief Read current value of the RTC_RAR_TPRR field. */ #define BR_RTC_RAR_TPRR(x) (BITBAND_ACCESS32(HW_RTC_RAR_ADDR(x), BP_RTC_RAR_TPRR)) /*! @brief Format value for bitfield RTC_RAR_TPRR. */ #define BF_RTC_RAR_TPRR(v) ((uint32_t)((uint32_t)(v) << BP_RTC_RAR_TPRR) & BM_RTC_RAR_TPRR) /*! @brief Set the TPRR field to a new value. */ #define BW_RTC_RAR_TPRR(x, v) (BITBAND_ACCESS32(HW_RTC_RAR_ADDR(x), BP_RTC_RAR_TPRR) = (v)) /*@}*/ /*! * @name Register RTC_RAR, field TARR[2] (RW) * * After being cleared, this bit is set only by system reset. It is not affected * by VBAT POR or software reset. * * Values: * - 0 - Reads to the Time Alarm Register are ignored. * - 1 - Reads to the Time Alarm Register complete as normal. */ /*@{*/ #define BP_RTC_RAR_TARR (2U) /*!< Bit position for RTC_RAR_TARR. */ #define BM_RTC_RAR_TARR (0x00000004U) /*!< Bit mask for RTC_RAR_TARR. */ #define BS_RTC_RAR_TARR (1U) /*!< Bit field size in bits for RTC_RAR_TARR. */ /*! @brief Read current value of the RTC_RAR_TARR field. */ #define BR_RTC_RAR_TARR(x) (BITBAND_ACCESS32(HW_RTC_RAR_ADDR(x), BP_RTC_RAR_TARR)) /*! @brief Format value for bitfield RTC_RAR_TARR. */ #define BF_RTC_RAR_TARR(v) ((uint32_t)((uint32_t)(v) << BP_RTC_RAR_TARR) & BM_RTC_RAR_TARR) /*! @brief Set the TARR field to a new value. */ #define BW_RTC_RAR_TARR(x, v) (BITBAND_ACCESS32(HW_RTC_RAR_ADDR(x), BP_RTC_RAR_TARR) = (v)) /*@}*/ /*! * @name Register RTC_RAR, field TCRR[3] (RW) * * After being cleared, this bit is set only by system reset. It is not affected * by VBAT POR or software reset. * * Values: * - 0 - Reads to the Time Compensation Register are ignored. * - 1 - Reads to the Time Compensation Register complete as normal. */ /*@{*/ #define BP_RTC_RAR_TCRR (3U) /*!< Bit position for RTC_RAR_TCRR. */ #define BM_RTC_RAR_TCRR (0x00000008U) /*!< Bit mask for RTC_RAR_TCRR. */ #define BS_RTC_RAR_TCRR (1U) /*!< Bit field size in bits for RTC_RAR_TCRR. */ /*! @brief Read current value of the RTC_RAR_TCRR field. */ #define BR_RTC_RAR_TCRR(x) (BITBAND_ACCESS32(HW_RTC_RAR_ADDR(x), BP_RTC_RAR_TCRR)) /*! @brief Format value for bitfield RTC_RAR_TCRR. */ #define BF_RTC_RAR_TCRR(v) ((uint32_t)((uint32_t)(v) << BP_RTC_RAR_TCRR) & BM_RTC_RAR_TCRR) /*! @brief Set the TCRR field to a new value. */ #define BW_RTC_RAR_TCRR(x, v) (BITBAND_ACCESS32(HW_RTC_RAR_ADDR(x), BP_RTC_RAR_TCRR) = (v)) /*@}*/ /*! * @name Register RTC_RAR, field CRR[4] (RW) * * After being cleared, this bit is set only by system reset. It is not affected * by VBAT POR or software reset. * * Values: * - 0 - Reads to the Control Register are ignored. * - 1 - Reads to the Control Register complete as normal. */ /*@{*/ #define BP_RTC_RAR_CRR (4U) /*!< Bit position for RTC_RAR_CRR. */ #define BM_RTC_RAR_CRR (0x00000010U) /*!< Bit mask for RTC_RAR_CRR. */ #define BS_RTC_RAR_CRR (1U) /*!< Bit field size in bits for RTC_RAR_CRR. */ /*! @brief Read current value of the RTC_RAR_CRR field. */ #define BR_RTC_RAR_CRR(x) (BITBAND_ACCESS32(HW_RTC_RAR_ADDR(x), BP_RTC_RAR_CRR)) /*! @brief Format value for bitfield RTC_RAR_CRR. */ #define BF_RTC_RAR_CRR(v) ((uint32_t)((uint32_t)(v) << BP_RTC_RAR_CRR) & BM_RTC_RAR_CRR) /*! @brief Set the CRR field to a new value. */ #define BW_RTC_RAR_CRR(x, v) (BITBAND_ACCESS32(HW_RTC_RAR_ADDR(x), BP_RTC_RAR_CRR) = (v)) /*@}*/ /*! * @name Register RTC_RAR, field SRR[5] (RW) * * After being cleared, this bit is set only by system reset. It is not affected * by VBAT POR or software reset. * * Values: * - 0 - Reads to the Status Register are ignored. * - 1 - Reads to the Status Register complete as normal. */ /*@{*/ #define BP_RTC_RAR_SRR (5U) /*!< Bit position for RTC_RAR_SRR. */ #define BM_RTC_RAR_SRR (0x00000020U) /*!< Bit mask for RTC_RAR_SRR. */ #define BS_RTC_RAR_SRR (1U) /*!< Bit field size in bits for RTC_RAR_SRR. */ /*! @brief Read current value of the RTC_RAR_SRR field. */ #define BR_RTC_RAR_SRR(x) (BITBAND_ACCESS32(HW_RTC_RAR_ADDR(x), BP_RTC_RAR_SRR)) /*! @brief Format value for bitfield RTC_RAR_SRR. */ #define BF_RTC_RAR_SRR(v) ((uint32_t)((uint32_t)(v) << BP_RTC_RAR_SRR) & BM_RTC_RAR_SRR) /*! @brief Set the SRR field to a new value. */ #define BW_RTC_RAR_SRR(x, v) (BITBAND_ACCESS32(HW_RTC_RAR_ADDR(x), BP_RTC_RAR_SRR) = (v)) /*@}*/ /*! * @name Register RTC_RAR, field LRR[6] (RW) * * After being cleared, this bit is set only by system reset. It is not affected * by VBAT POR or software reset. * * Values: * - 0 - Reads to the Lock Register are ignored. * - 1 - Reads to the Lock Register complete as normal. */ /*@{*/ #define BP_RTC_RAR_LRR (6U) /*!< Bit position for RTC_RAR_LRR. */ #define BM_RTC_RAR_LRR (0x00000040U) /*!< Bit mask for RTC_RAR_LRR. */ #define BS_RTC_RAR_LRR (1U) /*!< Bit field size in bits for RTC_RAR_LRR. */ /*! @brief Read current value of the RTC_RAR_LRR field. */ #define BR_RTC_RAR_LRR(x) (BITBAND_ACCESS32(HW_RTC_RAR_ADDR(x), BP_RTC_RAR_LRR)) /*! @brief Format value for bitfield RTC_RAR_LRR. */ #define BF_RTC_RAR_LRR(v) ((uint32_t)((uint32_t)(v) << BP_RTC_RAR_LRR) & BM_RTC_RAR_LRR) /*! @brief Set the LRR field to a new value. */ #define BW_RTC_RAR_LRR(x, v) (BITBAND_ACCESS32(HW_RTC_RAR_ADDR(x), BP_RTC_RAR_LRR) = (v)) /*@}*/ /*! * @name Register RTC_RAR, field IERR[7] (RW) * * After being cleared, this bit is set only by system reset. It is not affected * by VBAT POR or software reset. * * Values: * - 0 - Reads to the Interrupt Enable Register are ignored. * - 1 - Reads to the Interrupt Enable Register complete as normal. */ /*@{*/ #define BP_RTC_RAR_IERR (7U) /*!< Bit position for RTC_RAR_IERR. */ #define BM_RTC_RAR_IERR (0x00000080U) /*!< Bit mask for RTC_RAR_IERR. */ #define BS_RTC_RAR_IERR (1U) /*!< Bit field size in bits for RTC_RAR_IERR. */ /*! @brief Read current value of the RTC_RAR_IERR field. */ #define BR_RTC_RAR_IERR(x) (BITBAND_ACCESS32(HW_RTC_RAR_ADDR(x), BP_RTC_RAR_IERR)) /*! @brief Format value for bitfield RTC_RAR_IERR. */ #define BF_RTC_RAR_IERR(v) ((uint32_t)((uint32_t)(v) << BP_RTC_RAR_IERR) & BM_RTC_RAR_IERR) /*! @brief Set the IERR field to a new value. */ #define BW_RTC_RAR_IERR(x, v) (BITBAND_ACCESS32(HW_RTC_RAR_ADDR(x), BP_RTC_RAR_IERR) = (v)) /*@}*/ /******************************************************************************* * hw_rtc_t - module struct ******************************************************************************/ /*! * @brief All RTC module registers. */ #pragma pack(1) typedef struct _hw_rtc { __IO hw_rtc_tsr_t TSR; /*!< [0x0] RTC Time Seconds Register */ __IO hw_rtc_tpr_t TPR; /*!< [0x4] RTC Time Prescaler Register */ __IO hw_rtc_tar_t TAR; /*!< [0x8] RTC Time Alarm Register */ __IO hw_rtc_tcr_t TCR; /*!< [0xC] RTC Time Compensation Register */ __IO hw_rtc_cr_t CR; /*!< [0x10] RTC Control Register */ __IO hw_rtc_sr_t SR; /*!< [0x14] RTC Status Register */ __IO hw_rtc_lr_t LR; /*!< [0x18] RTC Lock Register */ __IO hw_rtc_ier_t IER; /*!< [0x1C] RTC Interrupt Enable Register */ uint8_t _reserved0[2016]; __IO hw_rtc_war_t WAR; /*!< [0x800] RTC Write Access Register */ __IO hw_rtc_rar_t RAR; /*!< [0x804] RTC Read Access Register */ } hw_rtc_t; #pragma pack() /*! @brief Macro to access all RTC registers. */ /*! @param x RTC module instance base address. */ /*! @return Reference (not a pointer) to the registers struct. To get a pointer to the struct, * use the '&' operator, like &HW_RTC(RTC_BASE). */ #define HW_RTC(x) (*(hw_rtc_t *)(x)) #endif /* __HW_RTC_REGISTERS_H__ */ /* EOF */ ================================================ FILE: Zelig/mbed/TARGET_K64F/TARGET_Freescale/TARGET_KPSDK_MCUS/TARGET_MCU_K64F/device/device/MK64F12/MK64F12_sdhc.h ================================================ /* ** ################################################################### ** Compilers: Keil ARM C/C++ Compiler ** Freescale C/C++ for Embedded ARM ** GNU C Compiler ** IAR ANSI C/C++ Compiler for ARM ** ** Reference manual: K64P144M120SF5RM, Rev.2, January 2014 ** Version: rev. 2.5, 2014-02-10 ** Build: b140604 ** ** Abstract: ** Extension to the CMSIS register access layer header. ** ** Copyright (c) 2014 Freescale Semiconductor, Inc. ** All rights reserved. ** ** Redistribution and use in source and binary forms, with or without modification, ** are permitted provided that the following conditions are met: ** ** o Redistributions of source code must retain the above copyright notice, this list ** of conditions and the following disclaimer. ** ** o Redistributions in binary form must reproduce the above copyright notice, this ** list of conditions and the following disclaimer in the documentation and/or ** other materials provided with the distribution. ** ** o Neither the name of Freescale Semiconductor, Inc. nor the names of its ** contributors may be used to endorse or promote products derived from this ** software without specific prior written permission. ** ** THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ** ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED ** WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE ** DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT 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. ** ** http: www.freescale.com ** mail: support@freescale.com ** ** Revisions: ** - rev. 1.0 (2013-08-12) ** Initial version. ** - rev. 2.0 (2013-10-29) ** Register accessor macros added to the memory map. ** Symbols for Processor Expert memory map compatibility added to the memory map. ** Startup file for gcc has been updated according to CMSIS 3.2. ** System initialization updated. ** MCG - registers updated. ** PORTA, PORTB, PORTC, PORTE - registers for digital filter removed. ** - rev. 2.1 (2013-10-30) ** Definition of BITBAND macros updated to support peripherals with 32-bit acces disabled. ** - rev. 2.2 (2013-12-09) ** DMA - EARS register removed. ** AIPS0, AIPS1 - MPRA register updated. ** - rev. 2.3 (2014-01-24) ** Update according to reference manual rev. 2 ** ENET, MCG, MCM, SIM, USB - registers updated ** - rev. 2.4 (2014-02-10) ** The declaration of clock configurations has been moved to separate header file system_MK64F12.h ** Update of SystemInit() and SystemCoreClockUpdate() functions. ** - rev. 2.5 (2014-02-10) ** The declaration of clock configurations has been moved to separate header file system_MK64F12.h ** Update of SystemInit() and SystemCoreClockUpdate() functions. ** Module access macro module_BASES replaced by module_BASE_PTRS. ** ** ################################################################### */ /* * WARNING! DO NOT EDIT THIS FILE DIRECTLY! * * This file was generated automatically and any changes may be lost. */ #ifndef __HW_SDHC_REGISTERS_H__ #define __HW_SDHC_REGISTERS_H__ #include "MK64F12.h" #include "fsl_bitaccess.h" /* * MK64F12 SDHC * * Secured Digital Host Controller * * Registers defined in this header file: * - HW_SDHC_DSADDR - DMA System Address register * - HW_SDHC_BLKATTR - Block Attributes register * - HW_SDHC_CMDARG - Command Argument register * - HW_SDHC_XFERTYP - Transfer Type register * - HW_SDHC_CMDRSP0 - Command Response 0 * - HW_SDHC_CMDRSP1 - Command Response 1 * - HW_SDHC_CMDRSP2 - Command Response 2 * - HW_SDHC_CMDRSP3 - Command Response 3 * - HW_SDHC_DATPORT - Buffer Data Port register * - HW_SDHC_PRSSTAT - Present State register * - HW_SDHC_PROCTL - Protocol Control register * - HW_SDHC_SYSCTL - System Control register * - HW_SDHC_IRQSTAT - Interrupt Status register * - HW_SDHC_IRQSTATEN - Interrupt Status Enable register * - HW_SDHC_IRQSIGEN - Interrupt Signal Enable register * - HW_SDHC_AC12ERR - Auto CMD12 Error Status Register * - HW_SDHC_HTCAPBLT - Host Controller Capabilities * - HW_SDHC_WML - Watermark Level Register * - HW_SDHC_FEVT - Force Event register * - HW_SDHC_ADMAES - ADMA Error Status register * - HW_SDHC_ADSADDR - ADMA System Addressregister * - HW_SDHC_VENDOR - Vendor Specific register * - HW_SDHC_MMCBOOT - MMC Boot register * - HW_SDHC_HOSTVER - Host Controller Version * * - hw_sdhc_t - Struct containing all module registers. */ #define HW_SDHC_INSTANCE_COUNT (1U) /*!< Number of instances of the SDHC module. */ /******************************************************************************* * HW_SDHC_DSADDR - DMA System Address register ******************************************************************************/ /*! * @brief HW_SDHC_DSADDR - DMA System Address register (RW) * * Reset value: 0x00000000U * * This register contains the physical system memory address used for DMA * transfers. */ typedef union _hw_sdhc_dsaddr { uint32_t U; struct _hw_sdhc_dsaddr_bitfields { uint32_t RESERVED0 : 2; /*!< [1:0] */ uint32_t DSADDR : 30; /*!< [31:2] DMA System Address */ } B; } hw_sdhc_dsaddr_t; /*! * @name Constants and macros for entire SDHC_DSADDR register */ /*@{*/ #define HW_SDHC_DSADDR_ADDR(x) ((x) + 0x0U) #define HW_SDHC_DSADDR(x) (*(__IO hw_sdhc_dsaddr_t *) HW_SDHC_DSADDR_ADDR(x)) #define HW_SDHC_DSADDR_RD(x) (HW_SDHC_DSADDR(x).U) #define HW_SDHC_DSADDR_WR(x, v) (HW_SDHC_DSADDR(x).U = (v)) #define HW_SDHC_DSADDR_SET(x, v) (HW_SDHC_DSADDR_WR(x, HW_SDHC_DSADDR_RD(x) | (v))) #define HW_SDHC_DSADDR_CLR(x, v) (HW_SDHC_DSADDR_WR(x, HW_SDHC_DSADDR_RD(x) & ~(v))) #define HW_SDHC_DSADDR_TOG(x, v) (HW_SDHC_DSADDR_WR(x, HW_SDHC_DSADDR_RD(x) ^ (v))) /*@}*/ /* * Constants & macros for individual SDHC_DSADDR bitfields */ /*! * @name Register SDHC_DSADDR, field DSADDR[31:2] (RW) * * Contains the 32-bit system memory address for a DMA transfer. Because the * address must be word (4 bytes) align, the least 2 bits are reserved, always 0. * When the SDHC stops a DMA transfer, this register points to the system address * of the next contiguous data position. It can be accessed only when no * transaction is executing, that is, after a transaction has stopped. Read operation * during transfers may return an invalid value. The host driver shall initialize * this register before starting a DMA transaction. After DMA has stopped, the * system address of the next contiguous data position can be read from this register. * This register is protected during a data transfer. When data lines are * active, write to this register is ignored. The host driver shall wait, until * PRSSTAT[DLA] is cleared, before writing to this register. The SDHC internal DMA does * not support a virtual memory system. It supports only continuous physical * memory access. And due to AHB burst limitations, if the burst must cross the 1 KB * boundary, SDHC will automatically change SEQ burst type to NSEQ. Because this * register supports dynamic address reflecting, when IRQSTAT[TC] bit is set, it * automatically alters the value of internal address counter, so SW cannot * change this register when IRQSTAT[TC] is set. */ /*@{*/ #define BP_SDHC_DSADDR_DSADDR (2U) /*!< Bit position for SDHC_DSADDR_DSADDR. */ #define BM_SDHC_DSADDR_DSADDR (0xFFFFFFFCU) /*!< Bit mask for SDHC_DSADDR_DSADDR. */ #define BS_SDHC_DSADDR_DSADDR (30U) /*!< Bit field size in bits for SDHC_DSADDR_DSADDR. */ /*! @brief Read current value of the SDHC_DSADDR_DSADDR field. */ #define BR_SDHC_DSADDR_DSADDR(x) (HW_SDHC_DSADDR(x).B.DSADDR) /*! @brief Format value for bitfield SDHC_DSADDR_DSADDR. */ #define BF_SDHC_DSADDR_DSADDR(v) ((uint32_t)((uint32_t)(v) << BP_SDHC_DSADDR_DSADDR) & BM_SDHC_DSADDR_DSADDR) /*! @brief Set the DSADDR field to a new value. */ #define BW_SDHC_DSADDR_DSADDR(x, v) (HW_SDHC_DSADDR_WR(x, (HW_SDHC_DSADDR_RD(x) & ~BM_SDHC_DSADDR_DSADDR) | BF_SDHC_DSADDR_DSADDR(v))) /*@}*/ /******************************************************************************* * HW_SDHC_BLKATTR - Block Attributes register ******************************************************************************/ /*! * @brief HW_SDHC_BLKATTR - Block Attributes register (RW) * * Reset value: 0x00000000U * * This register is used to configure the number of data blocks and the number * of bytes in each block. */ typedef union _hw_sdhc_blkattr { uint32_t U; struct _hw_sdhc_blkattr_bitfields { uint32_t BLKSIZE : 13; /*!< [12:0] Transfer Block Size */ uint32_t RESERVED0 : 3; /*!< [15:13] */ uint32_t BLKCNT : 16; /*!< [31:16] Blocks Count For Current Transfer * */ } B; } hw_sdhc_blkattr_t; /*! * @name Constants and macros for entire SDHC_BLKATTR register */ /*@{*/ #define HW_SDHC_BLKATTR_ADDR(x) ((x) + 0x4U) #define HW_SDHC_BLKATTR(x) (*(__IO hw_sdhc_blkattr_t *) HW_SDHC_BLKATTR_ADDR(x)) #define HW_SDHC_BLKATTR_RD(x) (HW_SDHC_BLKATTR(x).U) #define HW_SDHC_BLKATTR_WR(x, v) (HW_SDHC_BLKATTR(x).U = (v)) #define HW_SDHC_BLKATTR_SET(x, v) (HW_SDHC_BLKATTR_WR(x, HW_SDHC_BLKATTR_RD(x) | (v))) #define HW_SDHC_BLKATTR_CLR(x, v) (HW_SDHC_BLKATTR_WR(x, HW_SDHC_BLKATTR_RD(x) & ~(v))) #define HW_SDHC_BLKATTR_TOG(x, v) (HW_SDHC_BLKATTR_WR(x, HW_SDHC_BLKATTR_RD(x) ^ (v))) /*@}*/ /* * Constants & macros for individual SDHC_BLKATTR bitfields */ /*! * @name Register SDHC_BLKATTR, field BLKSIZE[12:0] (RW) * * Specifies the block size for block data transfers. Values ranging from 1 byte * up to the maximum buffer size can be set. It can be accessed only when no * transaction is executing, that is, after a transaction has stopped. Read * operations during transfers may return an invalid value, and write operations will be * ignored. * * Values: * - 0 - No data transfer. * - 1 - 1 Byte * - 10 - 2 Bytes * - 11 - 3 Bytes * - 100 - 4 Bytes * - 111111111 - 511 Bytes * - 1000000000 - 512 Bytes * - 100000000000 - 2048 Bytes * - 1000000000000 - 4096 Bytes */ /*@{*/ #define BP_SDHC_BLKATTR_BLKSIZE (0U) /*!< Bit position for SDHC_BLKATTR_BLKSIZE. */ #define BM_SDHC_BLKATTR_BLKSIZE (0x00001FFFU) /*!< Bit mask for SDHC_BLKATTR_BLKSIZE. */ #define BS_SDHC_BLKATTR_BLKSIZE (13U) /*!< Bit field size in bits for SDHC_BLKATTR_BLKSIZE. */ /*! @brief Read current value of the SDHC_BLKATTR_BLKSIZE field. */ #define BR_SDHC_BLKATTR_BLKSIZE(x) (HW_SDHC_BLKATTR(x).B.BLKSIZE) /*! @brief Format value for bitfield SDHC_BLKATTR_BLKSIZE. */ #define BF_SDHC_BLKATTR_BLKSIZE(v) ((uint32_t)((uint32_t)(v) << BP_SDHC_BLKATTR_BLKSIZE) & BM_SDHC_BLKATTR_BLKSIZE) /*! @brief Set the BLKSIZE field to a new value. */ #define BW_SDHC_BLKATTR_BLKSIZE(x, v) (HW_SDHC_BLKATTR_WR(x, (HW_SDHC_BLKATTR_RD(x) & ~BM_SDHC_BLKATTR_BLKSIZE) | BF_SDHC_BLKATTR_BLKSIZE(v))) /*@}*/ /*! * @name Register SDHC_BLKATTR, field BLKCNT[31:16] (RW) * * This register is enabled when XFERTYP[BCEN] is set to 1 and is valid only for * multiple block transfers. For single block transfer, this register will * always read as 1. The host driver shall set this register to a value between 1 and * the maximum block count. The SDHC decrements the block count after each block * transfer and stops when the count reaches zero. Setting the block count to 0 * results in no data blocks being transferred. This register must be accessed * only when no transaction is executing, that is, after transactions are stopped. * During data transfer, read operations on this register may return an invalid * value and write operations are ignored. When saving transfer content as a result * of a suspend command, the number of blocks yet to be transferred can be * determined by reading this register. The reading of this register must be applied * after transfer is paused by stop at block gap operation and before sending the * command marked as suspend. This is because when suspend command is sent out, * SDHC will regard the current transfer as aborted and change BLKCNT back to its * original value instead of keeping the dynamical indicator of remained block * count. When restoring transfer content prior to issuing a resume command, the * host driver shall restore the previously saved block count. Although the BLKCNT * field is 0 after reset, the read of reset value is 0x1. This is because when * XFERTYP[MSBSEL] is 0, indicating a single block transfer, the read value of * BLKCNT is always 1. * * Values: * - 0 - Stop count. * - 1 - 1 block * - 10 - 2 blocks * - 1111111111111111 - 65535 blocks */ /*@{*/ #define BP_SDHC_BLKATTR_BLKCNT (16U) /*!< Bit position for SDHC_BLKATTR_BLKCNT. */ #define BM_SDHC_BLKATTR_BLKCNT (0xFFFF0000U) /*!< Bit mask for SDHC_BLKATTR_BLKCNT. */ #define BS_SDHC_BLKATTR_BLKCNT (16U) /*!< Bit field size in bits for SDHC_BLKATTR_BLKCNT. */ /*! @brief Read current value of the SDHC_BLKATTR_BLKCNT field. */ #define BR_SDHC_BLKATTR_BLKCNT(x) (HW_SDHC_BLKATTR(x).B.BLKCNT) /*! @brief Format value for bitfield SDHC_BLKATTR_BLKCNT. */ #define BF_SDHC_BLKATTR_BLKCNT(v) ((uint32_t)((uint32_t)(v) << BP_SDHC_BLKATTR_BLKCNT) & BM_SDHC_BLKATTR_BLKCNT) /*! @brief Set the BLKCNT field to a new value. */ #define BW_SDHC_BLKATTR_BLKCNT(x, v) (HW_SDHC_BLKATTR_WR(x, (HW_SDHC_BLKATTR_RD(x) & ~BM_SDHC_BLKATTR_BLKCNT) | BF_SDHC_BLKATTR_BLKCNT(v))) /*@}*/ /******************************************************************************* * HW_SDHC_CMDARG - Command Argument register ******************************************************************************/ /*! * @brief HW_SDHC_CMDARG - Command Argument register (RW) * * Reset value: 0x00000000U * * This register contains the SD/MMC command argument. */ typedef union _hw_sdhc_cmdarg { uint32_t U; struct _hw_sdhc_cmdarg_bitfields { uint32_t CMDARG : 32; /*!< [31:0] Command Argument */ } B; } hw_sdhc_cmdarg_t; /*! * @name Constants and macros for entire SDHC_CMDARG register */ /*@{*/ #define HW_SDHC_CMDARG_ADDR(x) ((x) + 0x8U) #define HW_SDHC_CMDARG(x) (*(__IO hw_sdhc_cmdarg_t *) HW_SDHC_CMDARG_ADDR(x)) #define HW_SDHC_CMDARG_RD(x) (HW_SDHC_CMDARG(x).U) #define HW_SDHC_CMDARG_WR(x, v) (HW_SDHC_CMDARG(x).U = (v)) #define HW_SDHC_CMDARG_SET(x, v) (HW_SDHC_CMDARG_WR(x, HW_SDHC_CMDARG_RD(x) | (v))) #define HW_SDHC_CMDARG_CLR(x, v) (HW_SDHC_CMDARG_WR(x, HW_SDHC_CMDARG_RD(x) & ~(v))) #define HW_SDHC_CMDARG_TOG(x, v) (HW_SDHC_CMDARG_WR(x, HW_SDHC_CMDARG_RD(x) ^ (v))) /*@}*/ /* * Constants & macros for individual SDHC_CMDARG bitfields */ /*! * @name Register SDHC_CMDARG, field CMDARG[31:0] (RW) * * The SD/MMC command argument is specified as bits 39-8 of the command format * in the SD or MMC specification. This register is write protected when * PRSSTAT[CDIHB0] is set. */ /*@{*/ #define BP_SDHC_CMDARG_CMDARG (0U) /*!< Bit position for SDHC_CMDARG_CMDARG. */ #define BM_SDHC_CMDARG_CMDARG (0xFFFFFFFFU) /*!< Bit mask for SDHC_CMDARG_CMDARG. */ #define BS_SDHC_CMDARG_CMDARG (32U) /*!< Bit field size in bits for SDHC_CMDARG_CMDARG. */ /*! @brief Read current value of the SDHC_CMDARG_CMDARG field. */ #define BR_SDHC_CMDARG_CMDARG(x) (HW_SDHC_CMDARG(x).U) /*! @brief Format value for bitfield SDHC_CMDARG_CMDARG. */ #define BF_SDHC_CMDARG_CMDARG(v) ((uint32_t)((uint32_t)(v) << BP_SDHC_CMDARG_CMDARG) & BM_SDHC_CMDARG_CMDARG) /*! @brief Set the CMDARG field to a new value. */ #define BW_SDHC_CMDARG_CMDARG(x, v) (HW_SDHC_CMDARG_WR(x, v)) /*@}*/ /******************************************************************************* * HW_SDHC_XFERTYP - Transfer Type register ******************************************************************************/ /*! * @brief HW_SDHC_XFERTYP - Transfer Type register (RW) * * Reset value: 0x00000000U * * This register is used to control the operation of data transfers. The host * driver shall set this register before issuing a command followed by a data * transfer, or before issuing a resume command. To prevent data loss, the SDHC * prevents writing to the bits that are involved in the data transfer of this * register, when data transfer is active. These bits are DPSEL, MBSEL, DTDSEL, AC12EN, * BCEN, and DMAEN. The host driver shall check PRSSTAT[CDIHB] and PRSSTAT[CIHB] * before writing to this register. When PRSSTAT[CDIHB] is set, any attempt to * send a command with data by writing to this register is ignored; when * PRSSTAT[CIHB] bit is set, any write to this register is ignored. On sending commands with * data transfer involved, it is mandatory that the block size is nonzero. * Besides, block count must also be nonzero, or indicated as single block transfer * (bit 5 of this register is 0 when written), or block count is disabled (bit 1 of * this register is 0 when written), otherwise SDHC will ignore the sending of * this command and do nothing. For write command, with all above restrictions, it * is also mandatory that the write protect switch is not active (WPSPL bit of * Present State Register is 1), otherwise SDHC will also ignore the command. If * the commands with data transfer does not receive the response in 64 clock * cycles, that is, response time-out, SDHC will regard the external device does not * accept the command and abort the data transfer. In this scenario, the driver * must issue the command again to retry the transfer. It is also possible that, * for some reason, the card responds to the command but SDHC does not receive the * response, and if it is internal DMA (either simple DMA or ADMA) read * operation, the external system memory is over-written by the internal DMA with data * sent back from the card. The following table shows the summary of how register * settings determine the type of data transfer. Transfer Type register setting for * various transfer types Multi/Single block select Block count enable Block * count Function 0 Don't care Don't care Single transfer 1 0 Don't care Infinite * transfer 1 1 Positive number Multiple transfer 1 1 Zero No data transfer The * following table shows the relationship between XFERTYP[CICEN] and XFERTYP[CCCEN], * in regards to XFERTYP[RSPTYP] as well as the name of the response type. * Relationship between parameters and the name of the response type Response type * (RSPTYP) Index check enable (CICEN) CRC check enable (CCCEN) Name of response * type 00 0 0 No Response 01 0 1 IR2 10 0 0 R3,R4 10 1 1 R1,R5,R6 11 1 1 R1b,R5b In * the SDIO specification, response type notation for R5b is not defined. R5 * includes R5b in the SDIO specification. But R5b is defined in this specification * to specify that the SDHC will check the busy status after receiving a * response. For example, usually CMD52 is used with R5, but the I/O abort command shall * be used with R5b. The CRC field for R3 and R4 is expected to be all 1 bits. * The CRC check shall be disabled for these response types. */ typedef union _hw_sdhc_xfertyp { uint32_t U; struct _hw_sdhc_xfertyp_bitfields { uint32_t DMAEN : 1; /*!< [0] DMA Enable */ uint32_t BCEN : 1; /*!< [1] Block Count Enable */ uint32_t AC12EN : 1; /*!< [2] Auto CMD12 Enable */ uint32_t RESERVED0 : 1; /*!< [3] */ uint32_t DTDSEL : 1; /*!< [4] Data Transfer Direction Select */ uint32_t MSBSEL : 1; /*!< [5] Multi/Single Block Select */ uint32_t RESERVED1 : 10; /*!< [15:6] */ uint32_t RSPTYP : 2; /*!< [17:16] Response Type Select */ uint32_t RESERVED2 : 1; /*!< [18] */ uint32_t CCCEN : 1; /*!< [19] Command CRC Check Enable */ uint32_t CICEN : 1; /*!< [20] Command Index Check Enable */ uint32_t DPSEL : 1; /*!< [21] Data Present Select */ uint32_t CMDTYP : 2; /*!< [23:22] Command Type */ uint32_t CMDINX : 6; /*!< [29:24] Command Index */ uint32_t RESERVED3 : 2; /*!< [31:30] */ } B; } hw_sdhc_xfertyp_t; /*! * @name Constants and macros for entire SDHC_XFERTYP register */ /*@{*/ #define HW_SDHC_XFERTYP_ADDR(x) ((x) + 0xCU) #define HW_SDHC_XFERTYP(x) (*(__IO hw_sdhc_xfertyp_t *) HW_SDHC_XFERTYP_ADDR(x)) #define HW_SDHC_XFERTYP_RD(x) (HW_SDHC_XFERTYP(x).U) #define HW_SDHC_XFERTYP_WR(x, v) (HW_SDHC_XFERTYP(x).U = (v)) #define HW_SDHC_XFERTYP_SET(x, v) (HW_SDHC_XFERTYP_WR(x, HW_SDHC_XFERTYP_RD(x) | (v))) #define HW_SDHC_XFERTYP_CLR(x, v) (HW_SDHC_XFERTYP_WR(x, HW_SDHC_XFERTYP_RD(x) & ~(v))) #define HW_SDHC_XFERTYP_TOG(x, v) (HW_SDHC_XFERTYP_WR(x, HW_SDHC_XFERTYP_RD(x) ^ (v))) /*@}*/ /* * Constants & macros for individual SDHC_XFERTYP bitfields */ /*! * @name Register SDHC_XFERTYP, field DMAEN[0] (RW) * * Enables DMA functionality. If this bit is set to 1, a DMA operation shall * begin when the host driver sets the DPSEL bit of this register. Whether the * simple DMA, or the advanced DMA, is active depends on PROCTL[DMAS]. * * Values: * - 0 - Disable * - 1 - Enable */ /*@{*/ #define BP_SDHC_XFERTYP_DMAEN (0U) /*!< Bit position for SDHC_XFERTYP_DMAEN. */ #define BM_SDHC_XFERTYP_DMAEN (0x00000001U) /*!< Bit mask for SDHC_XFERTYP_DMAEN. */ #define BS_SDHC_XFERTYP_DMAEN (1U) /*!< Bit field size in bits for SDHC_XFERTYP_DMAEN. */ /*! @brief Read current value of the SDHC_XFERTYP_DMAEN field. */ #define BR_SDHC_XFERTYP_DMAEN(x) (BITBAND_ACCESS32(HW_SDHC_XFERTYP_ADDR(x), BP_SDHC_XFERTYP_DMAEN)) /*! @brief Format value for bitfield SDHC_XFERTYP_DMAEN. */ #define BF_SDHC_XFERTYP_DMAEN(v) ((uint32_t)((uint32_t)(v) << BP_SDHC_XFERTYP_DMAEN) & BM_SDHC_XFERTYP_DMAEN) /*! @brief Set the DMAEN field to a new value. */ #define BW_SDHC_XFERTYP_DMAEN(x, v) (BITBAND_ACCESS32(HW_SDHC_XFERTYP_ADDR(x), BP_SDHC_XFERTYP_DMAEN) = (v)) /*@}*/ /*! * @name Register SDHC_XFERTYP, field BCEN[1] (RW) * * Used to enable the Block Count register, which is only relevant for multiple * block transfers. When this bit is 0, the internal counter for block is * disabled, which is useful in executing an infinite transfer. * * Values: * - 0 - Disable * - 1 - Enable */ /*@{*/ #define BP_SDHC_XFERTYP_BCEN (1U) /*!< Bit position for SDHC_XFERTYP_BCEN. */ #define BM_SDHC_XFERTYP_BCEN (0x00000002U) /*!< Bit mask for SDHC_XFERTYP_BCEN. */ #define BS_SDHC_XFERTYP_BCEN (1U) /*!< Bit field size in bits for SDHC_XFERTYP_BCEN. */ /*! @brief Read current value of the SDHC_XFERTYP_BCEN field. */ #define BR_SDHC_XFERTYP_BCEN(x) (BITBAND_ACCESS32(HW_SDHC_XFERTYP_ADDR(x), BP_SDHC_XFERTYP_BCEN)) /*! @brief Format value for bitfield SDHC_XFERTYP_BCEN. */ #define BF_SDHC_XFERTYP_BCEN(v) ((uint32_t)((uint32_t)(v) << BP_SDHC_XFERTYP_BCEN) & BM_SDHC_XFERTYP_BCEN) /*! @brief Set the BCEN field to a new value. */ #define BW_SDHC_XFERTYP_BCEN(x, v) (BITBAND_ACCESS32(HW_SDHC_XFERTYP_ADDR(x), BP_SDHC_XFERTYP_BCEN) = (v)) /*@}*/ /*! * @name Register SDHC_XFERTYP, field AC12EN[2] (RW) * * Multiple block transfers for memory require a CMD12 to stop the transaction. * When this bit is set to 1, the SDHC will issue a CMD12 automatically when the * last block transfer has completed. The host driver shall not set this bit to * issue commands that do not require CMD12 to stop a multiple block data * transfer. In particular, secure commands defined in File Security Specification (see * reference list) do not require CMD12. In single block transfer, the SDHC will * ignore this bit whether it is set or not. * * Values: * - 0 - Disable * - 1 - Enable */ /*@{*/ #define BP_SDHC_XFERTYP_AC12EN (2U) /*!< Bit position for SDHC_XFERTYP_AC12EN. */ #define BM_SDHC_XFERTYP_AC12EN (0x00000004U) /*!< Bit mask for SDHC_XFERTYP_AC12EN. */ #define BS_SDHC_XFERTYP_AC12EN (1U) /*!< Bit field size in bits for SDHC_XFERTYP_AC12EN. */ /*! @brief Read current value of the SDHC_XFERTYP_AC12EN field. */ #define BR_SDHC_XFERTYP_AC12EN(x) (BITBAND_ACCESS32(HW_SDHC_XFERTYP_ADDR(x), BP_SDHC_XFERTYP_AC12EN)) /*! @brief Format value for bitfield SDHC_XFERTYP_AC12EN. */ #define BF_SDHC_XFERTYP_AC12EN(v) ((uint32_t)((uint32_t)(v) << BP_SDHC_XFERTYP_AC12EN) & BM_SDHC_XFERTYP_AC12EN) /*! @brief Set the AC12EN field to a new value. */ #define BW_SDHC_XFERTYP_AC12EN(x, v) (BITBAND_ACCESS32(HW_SDHC_XFERTYP_ADDR(x), BP_SDHC_XFERTYP_AC12EN) = (v)) /*@}*/ /*! * @name Register SDHC_XFERTYP, field DTDSEL[4] (RW) * * Defines the direction of DAT line data transfers. The bit is set to 1 by the * host driver to transfer data from the SD card to the SDHC and is set to 0 for * all other commands. * * Values: * - 0 - Write host to card. * - 1 - Read card to host. */ /*@{*/ #define BP_SDHC_XFERTYP_DTDSEL (4U) /*!< Bit position for SDHC_XFERTYP_DTDSEL. */ #define BM_SDHC_XFERTYP_DTDSEL (0x00000010U) /*!< Bit mask for SDHC_XFERTYP_DTDSEL. */ #define BS_SDHC_XFERTYP_DTDSEL (1U) /*!< Bit field size in bits for SDHC_XFERTYP_DTDSEL. */ /*! @brief Read current value of the SDHC_XFERTYP_DTDSEL field. */ #define BR_SDHC_XFERTYP_DTDSEL(x) (BITBAND_ACCESS32(HW_SDHC_XFERTYP_ADDR(x), BP_SDHC_XFERTYP_DTDSEL)) /*! @brief Format value for bitfield SDHC_XFERTYP_DTDSEL. */ #define BF_SDHC_XFERTYP_DTDSEL(v) ((uint32_t)((uint32_t)(v) << BP_SDHC_XFERTYP_DTDSEL) & BM_SDHC_XFERTYP_DTDSEL) /*! @brief Set the DTDSEL field to a new value. */ #define BW_SDHC_XFERTYP_DTDSEL(x, v) (BITBAND_ACCESS32(HW_SDHC_XFERTYP_ADDR(x), BP_SDHC_XFERTYP_DTDSEL) = (v)) /*@}*/ /*! * @name Register SDHC_XFERTYP, field MSBSEL[5] (RW) * * Enables multiple block DAT line data transfers. For any other commands, this * bit shall be set to 0. If this bit is 0, it is not necessary to set the block * count register. * * Values: * - 0 - Single block. * - 1 - Multiple blocks. */ /*@{*/ #define BP_SDHC_XFERTYP_MSBSEL (5U) /*!< Bit position for SDHC_XFERTYP_MSBSEL. */ #define BM_SDHC_XFERTYP_MSBSEL (0x00000020U) /*!< Bit mask for SDHC_XFERTYP_MSBSEL. */ #define BS_SDHC_XFERTYP_MSBSEL (1U) /*!< Bit field size in bits for SDHC_XFERTYP_MSBSEL. */ /*! @brief Read current value of the SDHC_XFERTYP_MSBSEL field. */ #define BR_SDHC_XFERTYP_MSBSEL(x) (BITBAND_ACCESS32(HW_SDHC_XFERTYP_ADDR(x), BP_SDHC_XFERTYP_MSBSEL)) /*! @brief Format value for bitfield SDHC_XFERTYP_MSBSEL. */ #define BF_SDHC_XFERTYP_MSBSEL(v) ((uint32_t)((uint32_t)(v) << BP_SDHC_XFERTYP_MSBSEL) & BM_SDHC_XFERTYP_MSBSEL) /*! @brief Set the MSBSEL field to a new value. */ #define BW_SDHC_XFERTYP_MSBSEL(x, v) (BITBAND_ACCESS32(HW_SDHC_XFERTYP_ADDR(x), BP_SDHC_XFERTYP_MSBSEL) = (v)) /*@}*/ /*! * @name Register SDHC_XFERTYP, field RSPTYP[17:16] (RW) * * Values: * - 00 - No response. * - 01 - Response length 136. * - 10 - Response length 48. * - 11 - Response length 48, check busy after response. */ /*@{*/ #define BP_SDHC_XFERTYP_RSPTYP (16U) /*!< Bit position for SDHC_XFERTYP_RSPTYP. */ #define BM_SDHC_XFERTYP_RSPTYP (0x00030000U) /*!< Bit mask for SDHC_XFERTYP_RSPTYP. */ #define BS_SDHC_XFERTYP_RSPTYP (2U) /*!< Bit field size in bits for SDHC_XFERTYP_RSPTYP. */ /*! @brief Read current value of the SDHC_XFERTYP_RSPTYP field. */ #define BR_SDHC_XFERTYP_RSPTYP(x) (HW_SDHC_XFERTYP(x).B.RSPTYP) /*! @brief Format value for bitfield SDHC_XFERTYP_RSPTYP. */ #define BF_SDHC_XFERTYP_RSPTYP(v) ((uint32_t)((uint32_t)(v) << BP_SDHC_XFERTYP_RSPTYP) & BM_SDHC_XFERTYP_RSPTYP) /*! @brief Set the RSPTYP field to a new value. */ #define BW_SDHC_XFERTYP_RSPTYP(x, v) (HW_SDHC_XFERTYP_WR(x, (HW_SDHC_XFERTYP_RD(x) & ~BM_SDHC_XFERTYP_RSPTYP) | BF_SDHC_XFERTYP_RSPTYP(v))) /*@}*/ /*! * @name Register SDHC_XFERTYP, field CCCEN[19] (RW) * * If this bit is set to 1, the SDHC shall check the CRC field in the response. * If an error is detected, it is reported as a Command CRC Error. If this bit is * set to 0, the CRC field is not checked. The number of bits checked by the CRC * field value changes according to the length of the response. * * Values: * - 0 - Disable * - 1 - Enable */ /*@{*/ #define BP_SDHC_XFERTYP_CCCEN (19U) /*!< Bit position for SDHC_XFERTYP_CCCEN. */ #define BM_SDHC_XFERTYP_CCCEN (0x00080000U) /*!< Bit mask for SDHC_XFERTYP_CCCEN. */ #define BS_SDHC_XFERTYP_CCCEN (1U) /*!< Bit field size in bits for SDHC_XFERTYP_CCCEN. */ /*! @brief Read current value of the SDHC_XFERTYP_CCCEN field. */ #define BR_SDHC_XFERTYP_CCCEN(x) (BITBAND_ACCESS32(HW_SDHC_XFERTYP_ADDR(x), BP_SDHC_XFERTYP_CCCEN)) /*! @brief Format value for bitfield SDHC_XFERTYP_CCCEN. */ #define BF_SDHC_XFERTYP_CCCEN(v) ((uint32_t)((uint32_t)(v) << BP_SDHC_XFERTYP_CCCEN) & BM_SDHC_XFERTYP_CCCEN) /*! @brief Set the CCCEN field to a new value. */ #define BW_SDHC_XFERTYP_CCCEN(x, v) (BITBAND_ACCESS32(HW_SDHC_XFERTYP_ADDR(x), BP_SDHC_XFERTYP_CCCEN) = (v)) /*@}*/ /*! * @name Register SDHC_XFERTYP, field CICEN[20] (RW) * * If this bit is set to 1, the SDHC will check the index field in the response * to see if it has the same value as the command index. If it is not, it is * reported as a command index error. If this bit is set to 0, the index field is not * checked. * * Values: * - 0 - Disable * - 1 - Enable */ /*@{*/ #define BP_SDHC_XFERTYP_CICEN (20U) /*!< Bit position for SDHC_XFERTYP_CICEN. */ #define BM_SDHC_XFERTYP_CICEN (0x00100000U) /*!< Bit mask for SDHC_XFERTYP_CICEN. */ #define BS_SDHC_XFERTYP_CICEN (1U) /*!< Bit field size in bits for SDHC_XFERTYP_CICEN. */ /*! @brief Read current value of the SDHC_XFERTYP_CICEN field. */ #define BR_SDHC_XFERTYP_CICEN(x) (BITBAND_ACCESS32(HW_SDHC_XFERTYP_ADDR(x), BP_SDHC_XFERTYP_CICEN)) /*! @brief Format value for bitfield SDHC_XFERTYP_CICEN. */ #define BF_SDHC_XFERTYP_CICEN(v) ((uint32_t)((uint32_t)(v) << BP_SDHC_XFERTYP_CICEN) & BM_SDHC_XFERTYP_CICEN) /*! @brief Set the CICEN field to a new value. */ #define BW_SDHC_XFERTYP_CICEN(x, v) (BITBAND_ACCESS32(HW_SDHC_XFERTYP_ADDR(x), BP_SDHC_XFERTYP_CICEN) = (v)) /*@}*/ /*! * @name Register SDHC_XFERTYP, field DPSEL[21] (RW) * * This bit is set to 1 to indicate that data is present and shall be * transferred using the DAT line. It is set to 0 for the following: Commands using only * the CMD line, for example: CMD52. Commands with no data transfer, but using the * busy signal on DAT[0] line, R1b or R5b, for example: CMD38. In resume command, * this bit shall be set, and other bits in this register shall be set the same * as when the transfer was initially launched. When the Write Protect switch is * on, that is, the WPSPL bit is active as 0, any command with a write operation * will be ignored. That is to say, when this bit is set, while the DTDSEL bit is * 0, writes to the register Transfer Type are ignored. * * Values: * - 0 - No data present. * - 1 - Data present. */ /*@{*/ #define BP_SDHC_XFERTYP_DPSEL (21U) /*!< Bit position for SDHC_XFERTYP_DPSEL. */ #define BM_SDHC_XFERTYP_DPSEL (0x00200000U) /*!< Bit mask for SDHC_XFERTYP_DPSEL. */ #define BS_SDHC_XFERTYP_DPSEL (1U) /*!< Bit field size in bits for SDHC_XFERTYP_DPSEL. */ /*! @brief Read current value of the SDHC_XFERTYP_DPSEL field. */ #define BR_SDHC_XFERTYP_DPSEL(x) (BITBAND_ACCESS32(HW_SDHC_XFERTYP_ADDR(x), BP_SDHC_XFERTYP_DPSEL)) /*! @brief Format value for bitfield SDHC_XFERTYP_DPSEL. */ #define BF_SDHC_XFERTYP_DPSEL(v) ((uint32_t)((uint32_t)(v) << BP_SDHC_XFERTYP_DPSEL) & BM_SDHC_XFERTYP_DPSEL) /*! @brief Set the DPSEL field to a new value. */ #define BW_SDHC_XFERTYP_DPSEL(x, v) (BITBAND_ACCESS32(HW_SDHC_XFERTYP_ADDR(x), BP_SDHC_XFERTYP_DPSEL) = (v)) /*@}*/ /*! * @name Register SDHC_XFERTYP, field CMDTYP[23:22] (RW) * * There are three types of special commands: suspend, resume, and abort. These * bits shall be set to 00b for all other commands. Suspend command: If the * suspend command succeeds, the SDHC shall assume that the card bus has been released * and that it is possible to issue the next command which uses the DAT line. * Because the SDHC does not monitor the content of command response, it does not * know if the suspend command succeeded or not. It is the host driver's * responsibility to check the status of the suspend command and send another command * marked as suspend to inform the SDHC that a suspend command was successfully * issued. After the end bit of command is sent, the SDHC deasserts read wait for read * transactions and stops checking busy for write transactions. In 4-bit mode, * the interrupt cycle starts. If the suspend command fails, the SDHC will * maintain its current state, and the host driver shall restart the transfer by setting * PROCTL[CREQ]. Resume command: The host driver restarts the data transfer by * restoring the registers saved before sending the suspend command and then sends * the resume command. The SDHC will check for a pending busy state before * starting write transfers. Abort command: If this command is set when executing a * read transfer, the SDHC will stop reads to the buffer. If this command is set * when executing a write transfer, the SDHC will stop driving the DAT line. After * issuing the abort command, the host driver must issue a software reset (abort * transaction). * * Values: * - 00 - Normal other commands. * - 01 - Suspend CMD52 for writing bus suspend in CCCR. * - 10 - Resume CMD52 for writing function select in CCCR. * - 11 - Abort CMD12, CMD52 for writing I/O abort in CCCR. */ /*@{*/ #define BP_SDHC_XFERTYP_CMDTYP (22U) /*!< Bit position for SDHC_XFERTYP_CMDTYP. */ #define BM_SDHC_XFERTYP_CMDTYP (0x00C00000U) /*!< Bit mask for SDHC_XFERTYP_CMDTYP. */ #define BS_SDHC_XFERTYP_CMDTYP (2U) /*!< Bit field size in bits for SDHC_XFERTYP_CMDTYP. */ /*! @brief Read current value of the SDHC_XFERTYP_CMDTYP field. */ #define BR_SDHC_XFERTYP_CMDTYP(x) (HW_SDHC_XFERTYP(x).B.CMDTYP) /*! @brief Format value for bitfield SDHC_XFERTYP_CMDTYP. */ #define BF_SDHC_XFERTYP_CMDTYP(v) ((uint32_t)((uint32_t)(v) << BP_SDHC_XFERTYP_CMDTYP) & BM_SDHC_XFERTYP_CMDTYP) /*! @brief Set the CMDTYP field to a new value. */ #define BW_SDHC_XFERTYP_CMDTYP(x, v) (HW_SDHC_XFERTYP_WR(x, (HW_SDHC_XFERTYP_RD(x) & ~BM_SDHC_XFERTYP_CMDTYP) | BF_SDHC_XFERTYP_CMDTYP(v))) /*@}*/ /*! * @name Register SDHC_XFERTYP, field CMDINX[29:24] (RW) * * These bits shall be set to the command number that is specified in bits 45-40 * of the command-format in the SD Memory Card Physical Layer Specification and * SDIO Card Specification. */ /*@{*/ #define BP_SDHC_XFERTYP_CMDINX (24U) /*!< Bit position for SDHC_XFERTYP_CMDINX. */ #define BM_SDHC_XFERTYP_CMDINX (0x3F000000U) /*!< Bit mask for SDHC_XFERTYP_CMDINX. */ #define BS_SDHC_XFERTYP_CMDINX (6U) /*!< Bit field size in bits for SDHC_XFERTYP_CMDINX. */ /*! @brief Read current value of the SDHC_XFERTYP_CMDINX field. */ #define BR_SDHC_XFERTYP_CMDINX(x) (HW_SDHC_XFERTYP(x).B.CMDINX) /*! @brief Format value for bitfield SDHC_XFERTYP_CMDINX. */ #define BF_SDHC_XFERTYP_CMDINX(v) ((uint32_t)((uint32_t)(v) << BP_SDHC_XFERTYP_CMDINX) & BM_SDHC_XFERTYP_CMDINX) /*! @brief Set the CMDINX field to a new value. */ #define BW_SDHC_XFERTYP_CMDINX(x, v) (HW_SDHC_XFERTYP_WR(x, (HW_SDHC_XFERTYP_RD(x) & ~BM_SDHC_XFERTYP_CMDINX) | BF_SDHC_XFERTYP_CMDINX(v))) /*@}*/ /******************************************************************************* * HW_SDHC_CMDRSP0 - Command Response 0 ******************************************************************************/ /*! * @brief HW_SDHC_CMDRSP0 - Command Response 0 (RO) * * Reset value: 0x00000000U * * This register is used to store part 0 of the response bits from the card. */ typedef union _hw_sdhc_cmdrsp0 { uint32_t U; struct _hw_sdhc_cmdrsp0_bitfields { uint32_t CMDRSP0 : 32; /*!< [31:0] Command Response 0 */ } B; } hw_sdhc_cmdrsp0_t; /*! * @name Constants and macros for entire SDHC_CMDRSP0 register */ /*@{*/ #define HW_SDHC_CMDRSP0_ADDR(x) ((x) + 0x10U) #define HW_SDHC_CMDRSP0(x) (*(__I hw_sdhc_cmdrsp0_t *) HW_SDHC_CMDRSP0_ADDR(x)) #define HW_SDHC_CMDRSP0_RD(x) (HW_SDHC_CMDRSP0(x).U) /*@}*/ /* * Constants & macros for individual SDHC_CMDRSP0 bitfields */ /*! * @name Register SDHC_CMDRSP0, field CMDRSP0[31:0] (RO) */ /*@{*/ #define BP_SDHC_CMDRSP0_CMDRSP0 (0U) /*!< Bit position for SDHC_CMDRSP0_CMDRSP0. */ #define BM_SDHC_CMDRSP0_CMDRSP0 (0xFFFFFFFFU) /*!< Bit mask for SDHC_CMDRSP0_CMDRSP0. */ #define BS_SDHC_CMDRSP0_CMDRSP0 (32U) /*!< Bit field size in bits for SDHC_CMDRSP0_CMDRSP0. */ /*! @brief Read current value of the SDHC_CMDRSP0_CMDRSP0 field. */ #define BR_SDHC_CMDRSP0_CMDRSP0(x) (HW_SDHC_CMDRSP0(x).U) /*@}*/ /******************************************************************************* * HW_SDHC_CMDRSP1 - Command Response 1 ******************************************************************************/ /*! * @brief HW_SDHC_CMDRSP1 - Command Response 1 (RO) * * Reset value: 0x00000000U * * This register is used to store part 1 of the response bits from the card. */ typedef union _hw_sdhc_cmdrsp1 { uint32_t U; struct _hw_sdhc_cmdrsp1_bitfields { uint32_t CMDRSP1 : 32; /*!< [31:0] Command Response 1 */ } B; } hw_sdhc_cmdrsp1_t; /*! * @name Constants and macros for entire SDHC_CMDRSP1 register */ /*@{*/ #define HW_SDHC_CMDRSP1_ADDR(x) ((x) + 0x14U) #define HW_SDHC_CMDRSP1(x) (*(__I hw_sdhc_cmdrsp1_t *) HW_SDHC_CMDRSP1_ADDR(x)) #define HW_SDHC_CMDRSP1_RD(x) (HW_SDHC_CMDRSP1(x).U) /*@}*/ /* * Constants & macros for individual SDHC_CMDRSP1 bitfields */ /*! * @name Register SDHC_CMDRSP1, field CMDRSP1[31:0] (RO) */ /*@{*/ #define BP_SDHC_CMDRSP1_CMDRSP1 (0U) /*!< Bit position for SDHC_CMDRSP1_CMDRSP1. */ #define BM_SDHC_CMDRSP1_CMDRSP1 (0xFFFFFFFFU) /*!< Bit mask for SDHC_CMDRSP1_CMDRSP1. */ #define BS_SDHC_CMDRSP1_CMDRSP1 (32U) /*!< Bit field size in bits for SDHC_CMDRSP1_CMDRSP1. */ /*! @brief Read current value of the SDHC_CMDRSP1_CMDRSP1 field. */ #define BR_SDHC_CMDRSP1_CMDRSP1(x) (HW_SDHC_CMDRSP1(x).U) /*@}*/ /******************************************************************************* * HW_SDHC_CMDRSP2 - Command Response 2 ******************************************************************************/ /*! * @brief HW_SDHC_CMDRSP2 - Command Response 2 (RO) * * Reset value: 0x00000000U * * This register is used to store part 2 of the response bits from the card. */ typedef union _hw_sdhc_cmdrsp2 { uint32_t U; struct _hw_sdhc_cmdrsp2_bitfields { uint32_t CMDRSP2 : 32; /*!< [31:0] Command Response 2 */ } B; } hw_sdhc_cmdrsp2_t; /*! * @name Constants and macros for entire SDHC_CMDRSP2 register */ /*@{*/ #define HW_SDHC_CMDRSP2_ADDR(x) ((x) + 0x18U) #define HW_SDHC_CMDRSP2(x) (*(__I hw_sdhc_cmdrsp2_t *) HW_SDHC_CMDRSP2_ADDR(x)) #define HW_SDHC_CMDRSP2_RD(x) (HW_SDHC_CMDRSP2(x).U) /*@}*/ /* * Constants & macros for individual SDHC_CMDRSP2 bitfields */ /*! * @name Register SDHC_CMDRSP2, field CMDRSP2[31:0] (RO) */ /*@{*/ #define BP_SDHC_CMDRSP2_CMDRSP2 (0U) /*!< Bit position for SDHC_CMDRSP2_CMDRSP2. */ #define BM_SDHC_CMDRSP2_CMDRSP2 (0xFFFFFFFFU) /*!< Bit mask for SDHC_CMDRSP2_CMDRSP2. */ #define BS_SDHC_CMDRSP2_CMDRSP2 (32U) /*!< Bit field size in bits for SDHC_CMDRSP2_CMDRSP2. */ /*! @brief Read current value of the SDHC_CMDRSP2_CMDRSP2 field. */ #define BR_SDHC_CMDRSP2_CMDRSP2(x) (HW_SDHC_CMDRSP2(x).U) /*@}*/ /******************************************************************************* * HW_SDHC_CMDRSP3 - Command Response 3 ******************************************************************************/ /*! * @brief HW_SDHC_CMDRSP3 - Command Response 3 (RO) * * Reset value: 0x00000000U * * This register is used to store part 3 of the response bits from the card. The * following table describes the mapping of command responses from the SD bus to * command response registers for each response type. In the table, R[ ] refers * to a bit range within the response data as transmitted on the SD bus. Response * bit definition for each response type Response type Meaning of response * Response field Response register R1,R1b (normal response) Card status R[39:8] * CMDRSP0 R1b (Auto CMD12 response) Card status for auto CMD12 R[39:8] CMDRSP3 R2 * (CID, CSD register) CID/CSD register [127:8] R[127:8] {CMDRSP3[23:0], CMDRSP2, * CMDRSP1, CMDRSP0} R3 (OCR register) OCR register for memory R[39:8] CMDRSP0 R4 * (OCR register) OCR register for I/O etc. R[39:8] CMDRSP0 R5, R5b SDIO response * R[39:8] CMDRSP0 R6 (Publish RCA) New published RCA[31:16] and card * status[15:0] R[39:9] CMDRSP0 This table shows that most responses with a length of 48 * (R[47:0]) have 32-bit of the response data (R[39:8]) stored in the CMDRSP0 * register. Responses of type R1b (auto CMD12 responses) have response data bits * (R[39:8]) stored in the CMDRSP3 register. Responses with length 136 (R[135:0]) have * 120-bit of the response data (R[127:8]) stored in the CMDRSP0, 1, 2, and 3 * registers. To be able to read the response status efficiently, the SDHC stores * only a part of the response data in the command response registers. This * enables the host driver to efficiently read 32-bit of response data in one read * cycle on a 32-bit bus system. Parts of the response, the index field and the CRC, * are checked by the SDHC, as specified by XFERTYP[CICEN] and XFERTYP[CCCEN], * and generate an error interrupt if any error is detected. The bit range for the * CRC check depends on the response length. If the response length is 48, the * SDHC will check R[47:1], and if the response length is 136 the SDHC will check * R[119:1]. Because the SDHC may have a multiple block data transfer executing * concurrently with a CMD_wo_DAT command, the SDHC stores the auto CMD12 response * in the CMDRSP3 register. The CMD_wo_DAT response is stored in CMDRSP0. This * allows the SDHC to avoid overwriting the Auto CMD12 response with the CMD_wo_DAT * and vice versa. When the SDHC modifies part of the command response * registers, as shown in the table above, it preserves the unmodified bits. */ typedef union _hw_sdhc_cmdrsp3 { uint32_t U; struct _hw_sdhc_cmdrsp3_bitfields { uint32_t CMDRSP3 : 32; /*!< [31:0] Command Response 3 */ } B; } hw_sdhc_cmdrsp3_t; /*! * @name Constants and macros for entire SDHC_CMDRSP3 register */ /*@{*/ #define HW_SDHC_CMDRSP3_ADDR(x) ((x) + 0x1CU) #define HW_SDHC_CMDRSP3(x) (*(__I hw_sdhc_cmdrsp3_t *) HW_SDHC_CMDRSP3_ADDR(x)) #define HW_SDHC_CMDRSP3_RD(x) (HW_SDHC_CMDRSP3(x).U) /*@}*/ /* * Constants & macros for individual SDHC_CMDRSP3 bitfields */ /*! * @name Register SDHC_CMDRSP3, field CMDRSP3[31:0] (RO) */ /*@{*/ #define BP_SDHC_CMDRSP3_CMDRSP3 (0U) /*!< Bit position for SDHC_CMDRSP3_CMDRSP3. */ #define BM_SDHC_CMDRSP3_CMDRSP3 (0xFFFFFFFFU) /*!< Bit mask for SDHC_CMDRSP3_CMDRSP3. */ #define BS_SDHC_CMDRSP3_CMDRSP3 (32U) /*!< Bit field size in bits for SDHC_CMDRSP3_CMDRSP3. */ /*! @brief Read current value of the SDHC_CMDRSP3_CMDRSP3 field. */ #define BR_SDHC_CMDRSP3_CMDRSP3(x) (HW_SDHC_CMDRSP3(x).U) /*@}*/ /******************************************************************************* * HW_SDHC_DATPORT - Buffer Data Port register ******************************************************************************/ /*! * @brief HW_SDHC_DATPORT - Buffer Data Port register (RW) * * Reset value: 0x00000000U * * This is a 32-bit data port register used to access the internal buffer and it * cannot be updated in Idle mode. */ typedef union _hw_sdhc_datport { uint32_t U; struct _hw_sdhc_datport_bitfields { uint32_t DATCONT : 32; /*!< [31:0] Data Content */ } B; } hw_sdhc_datport_t; /*! * @name Constants and macros for entire SDHC_DATPORT register */ /*@{*/ #define HW_SDHC_DATPORT_ADDR(x) ((x) + 0x20U) #define HW_SDHC_DATPORT(x) (*(__IO hw_sdhc_datport_t *) HW_SDHC_DATPORT_ADDR(x)) #define HW_SDHC_DATPORT_RD(x) (HW_SDHC_DATPORT(x).U) #define HW_SDHC_DATPORT_WR(x, v) (HW_SDHC_DATPORT(x).U = (v)) #define HW_SDHC_DATPORT_SET(x, v) (HW_SDHC_DATPORT_WR(x, HW_SDHC_DATPORT_RD(x) | (v))) #define HW_SDHC_DATPORT_CLR(x, v) (HW_SDHC_DATPORT_WR(x, HW_SDHC_DATPORT_RD(x) & ~(v))) #define HW_SDHC_DATPORT_TOG(x, v) (HW_SDHC_DATPORT_WR(x, HW_SDHC_DATPORT_RD(x) ^ (v))) /*@}*/ /* * Constants & macros for individual SDHC_DATPORT bitfields */ /*! * @name Register SDHC_DATPORT, field DATCONT[31:0] (RW) * * The Buffer Data Port register is for 32-bit data access by the CPU or the * external DMA. When the internal DMA is enabled, any write to this register is * ignored, and any read from this register will always yield 0s. */ /*@{*/ #define BP_SDHC_DATPORT_DATCONT (0U) /*!< Bit position for SDHC_DATPORT_DATCONT. */ #define BM_SDHC_DATPORT_DATCONT (0xFFFFFFFFU) /*!< Bit mask for SDHC_DATPORT_DATCONT. */ #define BS_SDHC_DATPORT_DATCONT (32U) /*!< Bit field size in bits for SDHC_DATPORT_DATCONT. */ /*! @brief Read current value of the SDHC_DATPORT_DATCONT field. */ #define BR_SDHC_DATPORT_DATCONT(x) (HW_SDHC_DATPORT(x).U) /*! @brief Format value for bitfield SDHC_DATPORT_DATCONT. */ #define BF_SDHC_DATPORT_DATCONT(v) ((uint32_t)((uint32_t)(v) << BP_SDHC_DATPORT_DATCONT) & BM_SDHC_DATPORT_DATCONT) /*! @brief Set the DATCONT field to a new value. */ #define BW_SDHC_DATPORT_DATCONT(x, v) (HW_SDHC_DATPORT_WR(x, v)) /*@}*/ /******************************************************************************* * HW_SDHC_PRSSTAT - Present State register ******************************************************************************/ /*! * @brief HW_SDHC_PRSSTAT - Present State register (RO) * * Reset value: 0x00000000U * * The host driver can get status of the SDHC from this 32-bit read-only * register. The host driver can issue CMD0, CMD12, CMD13 (for memory) and CMD52 (for * SDIO) when the DAT lines are busy during a data transfer. These commands can be * issued when Command Inhibit (CIHB) is set to zero. Other commands shall be * issued when Command Inhibit (CDIHB) is set to zero. Possible changes to the SD * Physical Specification may add other commands to this list in the future. */ typedef union _hw_sdhc_prsstat { uint32_t U; struct _hw_sdhc_prsstat_bitfields { uint32_t CIHB : 1; /*!< [0] Command Inhibit (CMD) */ uint32_t CDIHB : 1; /*!< [1] Command Inhibit (DAT) */ uint32_t DLA : 1; /*!< [2] Data Line Active */ uint32_t SDSTB : 1; /*!< [3] SD Clock Stable */ uint32_t IPGOFF : 1; /*!< [4] Bus Clock Gated Off Internally */ uint32_t HCKOFF : 1; /*!< [5] System Clock Gated Off Internally */ uint32_t PEROFF : 1; /*!< [6] SDHC clock Gated Off Internally */ uint32_t SDOFF : 1; /*!< [7] SD Clock Gated Off Internally */ uint32_t WTA : 1; /*!< [8] Write Transfer Active */ uint32_t RTA : 1; /*!< [9] Read Transfer Active */ uint32_t BWEN : 1; /*!< [10] Buffer Write Enable */ uint32_t BREN : 1; /*!< [11] Buffer Read Enable */ uint32_t RESERVED0 : 4; /*!< [15:12] */ uint32_t CINS : 1; /*!< [16] Card Inserted */ uint32_t RESERVED1 : 6; /*!< [22:17] */ uint32_t CLSL : 1; /*!< [23] CMD Line Signal Level */ uint32_t DLSL : 8; /*!< [31:24] DAT Line Signal Level */ } B; } hw_sdhc_prsstat_t; /*! * @name Constants and macros for entire SDHC_PRSSTAT register */ /*@{*/ #define HW_SDHC_PRSSTAT_ADDR(x) ((x) + 0x24U) #define HW_SDHC_PRSSTAT(x) (*(__I hw_sdhc_prsstat_t *) HW_SDHC_PRSSTAT_ADDR(x)) #define HW_SDHC_PRSSTAT_RD(x) (HW_SDHC_PRSSTAT(x).U) /*@}*/ /* * Constants & macros for individual SDHC_PRSSTAT bitfields */ /*! * @name Register SDHC_PRSSTAT, field CIHB[0] (RO) * * If this status bit is 0, it indicates that the CMD line is not in use and the * SDHC can issue a SD/MMC Command using the CMD line. This bit is set also * immediately after the Transfer Type register is written. This bit is cleared when * the command response is received. Even if the CDIHB bit is set to 1, Commands * using only the CMD line can be issued if this bit is 0. Changing from 1 to 0 * generates a command complete interrupt in the interrupt status register. If the * SDHC cannot issue the command because of a command conflict error (see * command CRC error) or because of a command not issued by auto CMD12 error, this bit * will remain 1 and the command complete is not set. The status of issuing an * auto CMD12 does not show on this bit. * * Values: * - 0 - Can issue command using only CMD line. * - 1 - Cannot issue command. */ /*@{*/ #define BP_SDHC_PRSSTAT_CIHB (0U) /*!< Bit position for SDHC_PRSSTAT_CIHB. */ #define BM_SDHC_PRSSTAT_CIHB (0x00000001U) /*!< Bit mask for SDHC_PRSSTAT_CIHB. */ #define BS_SDHC_PRSSTAT_CIHB (1U) /*!< Bit field size in bits for SDHC_PRSSTAT_CIHB. */ /*! @brief Read current value of the SDHC_PRSSTAT_CIHB field. */ #define BR_SDHC_PRSSTAT_CIHB(x) (BITBAND_ACCESS32(HW_SDHC_PRSSTAT_ADDR(x), BP_SDHC_PRSSTAT_CIHB)) /*@}*/ /*! * @name Register SDHC_PRSSTAT, field CDIHB[1] (RO) * * This status bit is generated if either the DLA or the RTA is set to 1. If * this bit is 0, it indicates that the SDHC can issue the next SD/MMC Command. * Commands with a busy signal belong to CDIHB, for example, R1b, R5b type. Except in * the case when the command busy is finished, changing from 1 to 0 generates a * transfer complete interrupt in the Interrupt Status register. The SD host * driver can save registers for a suspend transaction after this bit has changed * from 1 to 0. * * Values: * - 0 - Can issue command which uses the DAT line. * - 1 - Cannot issue command which uses the DAT line. */ /*@{*/ #define BP_SDHC_PRSSTAT_CDIHB (1U) /*!< Bit position for SDHC_PRSSTAT_CDIHB. */ #define BM_SDHC_PRSSTAT_CDIHB (0x00000002U) /*!< Bit mask for SDHC_PRSSTAT_CDIHB. */ #define BS_SDHC_PRSSTAT_CDIHB (1U) /*!< Bit field size in bits for SDHC_PRSSTAT_CDIHB. */ /*! @brief Read current value of the SDHC_PRSSTAT_CDIHB field. */ #define BR_SDHC_PRSSTAT_CDIHB(x) (BITBAND_ACCESS32(HW_SDHC_PRSSTAT_ADDR(x), BP_SDHC_PRSSTAT_CDIHB)) /*@}*/ /*! * @name Register SDHC_PRSSTAT, field DLA[2] (RO) * * Indicates whether one of the DAT lines on the SD bus is in use. In the case * of read transactions: This status indicates whether a read transfer is * executing on the SD bus. Changes in this value from 1 to 0, between data blocks, * generates a block gap event interrupt in the Interrupt Status register. This bit * will be set in either of the following cases: After the end bit of the read * command. When writing a 1 to PROCTL[CREQ] to restart a read transfer. This bit * will be cleared in either of the following cases: When the end bit of the last * data block is sent from the SD bus to the SDHC. When the read wait state is * stopped by a suspend command and the DAT2 line is released. The SDHC will wait at * the next block gap by driving read wait at the start of the interrupt cycle. * If the read wait signal is already driven (data buffer cannot receive data), * the SDHC can wait for a current block gap by continuing to drive the read wait * signal. It is necessary to support read wait to use the suspend / resume * function. This bit will remain 1 during read wait. In the case of write * transactions: This status indicates that a write transfer is executing on the SD bus. * Changes in this value from 1 to 0 generate a transfer complete interrupt in the * interrupt status register. This bit will be set in either of the following * cases: After the end bit of the write command. When writing to 1 to PROCTL[CREQ] to * continue a write transfer. This bit will be cleared in either of the * following cases: When the SD card releases write busy of the last data block, the SDHC * will also detect if the output is not busy. If the SD card does not drive the * busy signal after the CRC status is received, the SDHC shall assume the card * drive "Not busy". When the SD card releases write busy, prior to waiting for * write transfer, and as a result of a stop at block gap request. In the case of * command with busy pending: This status indicates that a busy state follows the * command and the data line is in use. This bit will be cleared when the DAT0 * line is released. * * Values: * - 0 - DAT line inactive. * - 1 - DAT line active. */ /*@{*/ #define BP_SDHC_PRSSTAT_DLA (2U) /*!< Bit position for SDHC_PRSSTAT_DLA. */ #define BM_SDHC_PRSSTAT_DLA (0x00000004U) /*!< Bit mask for SDHC_PRSSTAT_DLA. */ #define BS_SDHC_PRSSTAT_DLA (1U) /*!< Bit field size in bits for SDHC_PRSSTAT_DLA. */ /*! @brief Read current value of the SDHC_PRSSTAT_DLA field. */ #define BR_SDHC_PRSSTAT_DLA(x) (BITBAND_ACCESS32(HW_SDHC_PRSSTAT_ADDR(x), BP_SDHC_PRSSTAT_DLA)) /*@}*/ /*! * @name Register SDHC_PRSSTAT, field SDSTB[3] (RO) * * Indicates that the internal card clock is stable. This bit is for the host * driver to poll clock status when changing the clock frequency. It is recommended * to clear SYSCTL[SDCLKEN] to remove glitch on the card clock when the * frequency is changing. * * Values: * - 0 - Clock is changing frequency and not stable. * - 1 - Clock is stable. */ /*@{*/ #define BP_SDHC_PRSSTAT_SDSTB (3U) /*!< Bit position for SDHC_PRSSTAT_SDSTB. */ #define BM_SDHC_PRSSTAT_SDSTB (0x00000008U) /*!< Bit mask for SDHC_PRSSTAT_SDSTB. */ #define BS_SDHC_PRSSTAT_SDSTB (1U) /*!< Bit field size in bits for SDHC_PRSSTAT_SDSTB. */ /*! @brief Read current value of the SDHC_PRSSTAT_SDSTB field. */ #define BR_SDHC_PRSSTAT_SDSTB(x) (BITBAND_ACCESS32(HW_SDHC_PRSSTAT_ADDR(x), BP_SDHC_PRSSTAT_SDSTB)) /*@}*/ /*! * @name Register SDHC_PRSSTAT, field IPGOFF[4] (RO) * * Indicates that the bus clock is internally gated off. This bit is for the * host driver to debug. * * Values: * - 0 - Bus clock is active. * - 1 - Bus clock is gated off. */ /*@{*/ #define BP_SDHC_PRSSTAT_IPGOFF (4U) /*!< Bit position for SDHC_PRSSTAT_IPGOFF. */ #define BM_SDHC_PRSSTAT_IPGOFF (0x00000010U) /*!< Bit mask for SDHC_PRSSTAT_IPGOFF. */ #define BS_SDHC_PRSSTAT_IPGOFF (1U) /*!< Bit field size in bits for SDHC_PRSSTAT_IPGOFF. */ /*! @brief Read current value of the SDHC_PRSSTAT_IPGOFF field. */ #define BR_SDHC_PRSSTAT_IPGOFF(x) (BITBAND_ACCESS32(HW_SDHC_PRSSTAT_ADDR(x), BP_SDHC_PRSSTAT_IPGOFF)) /*@}*/ /*! * @name Register SDHC_PRSSTAT, field HCKOFF[5] (RO) * * Indicates that the system clock is internally gated off. This bit is for the * host driver to debug during a data transfer. * * Values: * - 0 - System clock is active. * - 1 - System clock is gated off. */ /*@{*/ #define BP_SDHC_PRSSTAT_HCKOFF (5U) /*!< Bit position for SDHC_PRSSTAT_HCKOFF. */ #define BM_SDHC_PRSSTAT_HCKOFF (0x00000020U) /*!< Bit mask for SDHC_PRSSTAT_HCKOFF. */ #define BS_SDHC_PRSSTAT_HCKOFF (1U) /*!< Bit field size in bits for SDHC_PRSSTAT_HCKOFF. */ /*! @brief Read current value of the SDHC_PRSSTAT_HCKOFF field. */ #define BR_SDHC_PRSSTAT_HCKOFF(x) (BITBAND_ACCESS32(HW_SDHC_PRSSTAT_ADDR(x), BP_SDHC_PRSSTAT_HCKOFF)) /*@}*/ /*! * @name Register SDHC_PRSSTAT, field PEROFF[6] (RO) * * Indicates that the is internally gated off. This bit is for the host driver * to debug transaction on the SD bus. When INITA bit is set, SDHC sending 80 * clock cycles to the card, SDCLKEN must be 1 to enable the output card clock, * otherwise the will never be gate off, so and will be always active. SDHC clock SDHC * clock SDHC clock bus clock * * Values: * - 0 - SDHC clock is active. * - 1 - SDHC clock is gated off. */ /*@{*/ #define BP_SDHC_PRSSTAT_PEROFF (6U) /*!< Bit position for SDHC_PRSSTAT_PEROFF. */ #define BM_SDHC_PRSSTAT_PEROFF (0x00000040U) /*!< Bit mask for SDHC_PRSSTAT_PEROFF. */ #define BS_SDHC_PRSSTAT_PEROFF (1U) /*!< Bit field size in bits for SDHC_PRSSTAT_PEROFF. */ /*! @brief Read current value of the SDHC_PRSSTAT_PEROFF field. */ #define BR_SDHC_PRSSTAT_PEROFF(x) (BITBAND_ACCESS32(HW_SDHC_PRSSTAT_ADDR(x), BP_SDHC_PRSSTAT_PEROFF)) /*@}*/ /*! * @name Register SDHC_PRSSTAT, field SDOFF[7] (RO) * * Indicates that the SD clock is internally gated off, because of buffer * over/under-run or read pause without read wait assertion, or the driver has cleared * SYSCTL[SDCLKEN] to stop the SD clock. This bit is for the host driver to debug * data transaction on the SD bus. * * Values: * - 0 - SD clock is active. * - 1 - SD clock is gated off. */ /*@{*/ #define BP_SDHC_PRSSTAT_SDOFF (7U) /*!< Bit position for SDHC_PRSSTAT_SDOFF. */ #define BM_SDHC_PRSSTAT_SDOFF (0x00000080U) /*!< Bit mask for SDHC_PRSSTAT_SDOFF. */ #define BS_SDHC_PRSSTAT_SDOFF (1U) /*!< Bit field size in bits for SDHC_PRSSTAT_SDOFF. */ /*! @brief Read current value of the SDHC_PRSSTAT_SDOFF field. */ #define BR_SDHC_PRSSTAT_SDOFF(x) (BITBAND_ACCESS32(HW_SDHC_PRSSTAT_ADDR(x), BP_SDHC_PRSSTAT_SDOFF)) /*@}*/ /*! * @name Register SDHC_PRSSTAT, field WTA[8] (RO) * * Indicates that a write transfer is active. If this bit is 0, it means no * valid write data exists in the SDHC. This bit is set in either of the following * cases: After the end bit of the write command. When writing 1 to PROCTL[CREQ] to * restart a write transfer. This bit is cleared in either of the following * cases: After getting the CRC status of the last data block as specified by the * transfer count (single and multiple). After getting the CRC status of any block * where data transmission is about to be stopped by a stop at block gap request. * During a write transaction, a block gap event interrupt is generated when this * bit is changed to 0, as result of the stop at block gap request being set. * This status is useful for the host driver in determining when to issue commands * during write busy state. * * Values: * - 0 - No valid data. * - 1 - Transferring data. */ /*@{*/ #define BP_SDHC_PRSSTAT_WTA (8U) /*!< Bit position for SDHC_PRSSTAT_WTA. */ #define BM_SDHC_PRSSTAT_WTA (0x00000100U) /*!< Bit mask for SDHC_PRSSTAT_WTA. */ #define BS_SDHC_PRSSTAT_WTA (1U) /*!< Bit field size in bits for SDHC_PRSSTAT_WTA. */ /*! @brief Read current value of the SDHC_PRSSTAT_WTA field. */ #define BR_SDHC_PRSSTAT_WTA(x) (BITBAND_ACCESS32(HW_SDHC_PRSSTAT_ADDR(x), BP_SDHC_PRSSTAT_WTA)) /*@}*/ /*! * @name Register SDHC_PRSSTAT, field RTA[9] (RO) * * Used for detecting completion of a read transfer. This bit is set for either * of the following conditions: After the end bit of the read command. When * writing a 1 to PROCTL[CREQ] to restart a read transfer. A transfer complete * interrupt is generated when this bit changes to 0. This bit is cleared for either of * the following conditions: When the last data block as specified by block * length is transferred to the system, that is, all data are read away from SDHC * internal buffer. When all valid data blocks have been transferred from SDHC * internal buffer to the system and no current block transfers are being sent as a * result of the stop at block gap request being set to 1. * * Values: * - 0 - No valid data. * - 1 - Transferring data. */ /*@{*/ #define BP_SDHC_PRSSTAT_RTA (9U) /*!< Bit position for SDHC_PRSSTAT_RTA. */ #define BM_SDHC_PRSSTAT_RTA (0x00000200U) /*!< Bit mask for SDHC_PRSSTAT_RTA. */ #define BS_SDHC_PRSSTAT_RTA (1U) /*!< Bit field size in bits for SDHC_PRSSTAT_RTA. */ /*! @brief Read current value of the SDHC_PRSSTAT_RTA field. */ #define BR_SDHC_PRSSTAT_RTA(x) (BITBAND_ACCESS32(HW_SDHC_PRSSTAT_ADDR(x), BP_SDHC_PRSSTAT_RTA)) /*@}*/ /*! * @name Register SDHC_PRSSTAT, field BWEN[10] (RO) * * Used for non-DMA write transfers. The SDHC can implement multiple buffers to * transfer data efficiently. This read-only flag indicates whether space is * available for write data. If this bit is 1, valid data greater than the watermark * level can be written to the buffer. This read-only flag indicates whether * space is available for write data. * * Values: * - 0 - Write disable, the buffer can hold valid data less than the write * watermark level. * - 1 - Write enable, the buffer can hold valid data greater than the write * watermark level. */ /*@{*/ #define BP_SDHC_PRSSTAT_BWEN (10U) /*!< Bit position for SDHC_PRSSTAT_BWEN. */ #define BM_SDHC_PRSSTAT_BWEN (0x00000400U) /*!< Bit mask for SDHC_PRSSTAT_BWEN. */ #define BS_SDHC_PRSSTAT_BWEN (1U) /*!< Bit field size in bits for SDHC_PRSSTAT_BWEN. */ /*! @brief Read current value of the SDHC_PRSSTAT_BWEN field. */ #define BR_SDHC_PRSSTAT_BWEN(x) (BITBAND_ACCESS32(HW_SDHC_PRSSTAT_ADDR(x), BP_SDHC_PRSSTAT_BWEN)) /*@}*/ /*! * @name Register SDHC_PRSSTAT, field BREN[11] (RO) * * Used for non-DMA read transfers. The SDHC may implement multiple buffers to * transfer data efficiently. This read-only flag indicates that valid data exists * in the host side buffer. If this bit is high, valid data greater than the * watermark level exist in the buffer. This read-only flag indicates that valid * data exists in the host side buffer. * * Values: * - 0 - Read disable, valid data less than the watermark level exist in the * buffer. * - 1 - Read enable, valid data greater than the watermark level exist in the * buffer. */ /*@{*/ #define BP_SDHC_PRSSTAT_BREN (11U) /*!< Bit position for SDHC_PRSSTAT_BREN. */ #define BM_SDHC_PRSSTAT_BREN (0x00000800U) /*!< Bit mask for SDHC_PRSSTAT_BREN. */ #define BS_SDHC_PRSSTAT_BREN (1U) /*!< Bit field size in bits for SDHC_PRSSTAT_BREN. */ /*! @brief Read current value of the SDHC_PRSSTAT_BREN field. */ #define BR_SDHC_PRSSTAT_BREN(x) (BITBAND_ACCESS32(HW_SDHC_PRSSTAT_ADDR(x), BP_SDHC_PRSSTAT_BREN)) /*@}*/ /*! * @name Register SDHC_PRSSTAT, field CINS[16] (RO) * * Indicates whether a card has been inserted. The SDHC debounces this signal so * that the host driver will not need to wait for it to stabilize. Changing from * a 0 to 1 generates a card insertion interrupt in the Interrupt Status * register. Changing from a 1 to 0 generates a card removal interrupt in the Interrupt * Status register. A write to the force event register does not effect this bit. * SYSCTL[RSTA] does not effect this bit. A software reset does not effect this * bit. * * Values: * - 0 - Power on reset or no card. * - 1 - Card inserted. */ /*@{*/ #define BP_SDHC_PRSSTAT_CINS (16U) /*!< Bit position for SDHC_PRSSTAT_CINS. */ #define BM_SDHC_PRSSTAT_CINS (0x00010000U) /*!< Bit mask for SDHC_PRSSTAT_CINS. */ #define BS_SDHC_PRSSTAT_CINS (1U) /*!< Bit field size in bits for SDHC_PRSSTAT_CINS. */ /*! @brief Read current value of the SDHC_PRSSTAT_CINS field. */ #define BR_SDHC_PRSSTAT_CINS(x) (BITBAND_ACCESS32(HW_SDHC_PRSSTAT_ADDR(x), BP_SDHC_PRSSTAT_CINS)) /*@}*/ /*! * @name Register SDHC_PRSSTAT, field CLSL[23] (RO) * * Used to check the CMD line level to recover from errors, and for debugging. * The reset value is effected by the external pullup/pulldown resistor, by * default, the read value of this bit after reset is 1b, when the command line is * pulled up. */ /*@{*/ #define BP_SDHC_PRSSTAT_CLSL (23U) /*!< Bit position for SDHC_PRSSTAT_CLSL. */ #define BM_SDHC_PRSSTAT_CLSL (0x00800000U) /*!< Bit mask for SDHC_PRSSTAT_CLSL. */ #define BS_SDHC_PRSSTAT_CLSL (1U) /*!< Bit field size in bits for SDHC_PRSSTAT_CLSL. */ /*! @brief Read current value of the SDHC_PRSSTAT_CLSL field. */ #define BR_SDHC_PRSSTAT_CLSL(x) (BITBAND_ACCESS32(HW_SDHC_PRSSTAT_ADDR(x), BP_SDHC_PRSSTAT_CLSL)) /*@}*/ /*! * @name Register SDHC_PRSSTAT, field DLSL[31:24] (RO) * * Used to check the DAT line level to recover from errors, and for debugging. * This is especially useful in detecting the busy signal level from DAT[0]. The * reset value is effected by the external pullup/pulldown resistors. By default, * the read value of this field after reset is 8'b11110111, when DAT[3] is pulled * down and the other lines are pulled up. */ /*@{*/ #define BP_SDHC_PRSSTAT_DLSL (24U) /*!< Bit position for SDHC_PRSSTAT_DLSL. */ #define BM_SDHC_PRSSTAT_DLSL (0xFF000000U) /*!< Bit mask for SDHC_PRSSTAT_DLSL. */ #define BS_SDHC_PRSSTAT_DLSL (8U) /*!< Bit field size in bits for SDHC_PRSSTAT_DLSL. */ /*! @brief Read current value of the SDHC_PRSSTAT_DLSL field. */ #define BR_SDHC_PRSSTAT_DLSL(x) (HW_SDHC_PRSSTAT(x).B.DLSL) /*@}*/ /******************************************************************************* * HW_SDHC_PROCTL - Protocol Control register ******************************************************************************/ /*! * @brief HW_SDHC_PROCTL - Protocol Control register (RW) * * Reset value: 0x00000020U * * There are three cases to restart the transfer after stop at the block gap. * Which case is appropriate depends on whether the SDHC issues a suspend command * or the SD card accepts the suspend command: If the host driver does not issue a * suspend command, the continue request shall be used to restart the transfer. * If the host driver issues a suspend command and the SD card accepts it, a * resume command shall be used to restart the transfer. If the host driver issues a * suspend command and the SD card does not accept it, the continue request shall * be used to restart the transfer. Any time stop at block gap request stops the * data transfer, the host driver shall wait for a transfer complete (in the * interrupt status register), before attempting to restart the transfer. When * restarting the data transfer by continue request, the host driver shall clear the * stop at block gap request before or simultaneously. */ typedef union _hw_sdhc_proctl { uint32_t U; struct _hw_sdhc_proctl_bitfields { uint32_t LCTL : 1; /*!< [0] LED Control */ uint32_t DTW : 2; /*!< [2:1] Data Transfer Width */ uint32_t D3CD : 1; /*!< [3] DAT3 As Card Detection Pin */ uint32_t EMODE : 2; /*!< [5:4] Endian Mode */ uint32_t CDTL : 1; /*!< [6] Card Detect Test Level */ uint32_t CDSS : 1; /*!< [7] Card Detect Signal Selection */ uint32_t DMAS : 2; /*!< [9:8] DMA Select */ uint32_t RESERVED0 : 6; /*!< [15:10] */ uint32_t SABGREQ : 1; /*!< [16] Stop At Block Gap Request */ uint32_t CREQ : 1; /*!< [17] Continue Request */ uint32_t RWCTL : 1; /*!< [18] Read Wait Control */ uint32_t IABG : 1; /*!< [19] Interrupt At Block Gap */ uint32_t RESERVED1 : 4; /*!< [23:20] */ uint32_t WECINT : 1; /*!< [24] Wakeup Event Enable On Card Interrupt * */ uint32_t WECINS : 1; /*!< [25] Wakeup Event Enable On SD Card * Insertion */ uint32_t WECRM : 1; /*!< [26] Wakeup Event Enable On SD Card Removal * */ uint32_t RESERVED2 : 5; /*!< [31:27] */ } B; } hw_sdhc_proctl_t; /*! * @name Constants and macros for entire SDHC_PROCTL register */ /*@{*/ #define HW_SDHC_PROCTL_ADDR(x) ((x) + 0x28U) #define HW_SDHC_PROCTL(x) (*(__IO hw_sdhc_proctl_t *) HW_SDHC_PROCTL_ADDR(x)) #define HW_SDHC_PROCTL_RD(x) (HW_SDHC_PROCTL(x).U) #define HW_SDHC_PROCTL_WR(x, v) (HW_SDHC_PROCTL(x).U = (v)) #define HW_SDHC_PROCTL_SET(x, v) (HW_SDHC_PROCTL_WR(x, HW_SDHC_PROCTL_RD(x) | (v))) #define HW_SDHC_PROCTL_CLR(x, v) (HW_SDHC_PROCTL_WR(x, HW_SDHC_PROCTL_RD(x) & ~(v))) #define HW_SDHC_PROCTL_TOG(x, v) (HW_SDHC_PROCTL_WR(x, HW_SDHC_PROCTL_RD(x) ^ (v))) /*@}*/ /* * Constants & macros for individual SDHC_PROCTL bitfields */ /*! * @name Register SDHC_PROCTL, field LCTL[0] (RW) * * This bit, fully controlled by the host driver, is used to caution the user * not to remove the card while the card is being accessed. If the software is * going to issue multiple SD commands, this bit can be set during all these * transactions. It is not necessary to change for each transaction. When the software * issues multiple SD commands, setting the bit once before the first command is * sufficient: it is not necessary to reset the bit between commands. * * Values: * - 0 - LED off. * - 1 - LED on. */ /*@{*/ #define BP_SDHC_PROCTL_LCTL (0U) /*!< Bit position for SDHC_PROCTL_LCTL. */ #define BM_SDHC_PROCTL_LCTL (0x00000001U) /*!< Bit mask for SDHC_PROCTL_LCTL. */ #define BS_SDHC_PROCTL_LCTL (1U) /*!< Bit field size in bits for SDHC_PROCTL_LCTL. */ /*! @brief Read current value of the SDHC_PROCTL_LCTL field. */ #define BR_SDHC_PROCTL_LCTL(x) (BITBAND_ACCESS32(HW_SDHC_PROCTL_ADDR(x), BP_SDHC_PROCTL_LCTL)) /*! @brief Format value for bitfield SDHC_PROCTL_LCTL. */ #define BF_SDHC_PROCTL_LCTL(v) ((uint32_t)((uint32_t)(v) << BP_SDHC_PROCTL_LCTL) & BM_SDHC_PROCTL_LCTL) /*! @brief Set the LCTL field to a new value. */ #define BW_SDHC_PROCTL_LCTL(x, v) (BITBAND_ACCESS32(HW_SDHC_PROCTL_ADDR(x), BP_SDHC_PROCTL_LCTL) = (v)) /*@}*/ /*! * @name Register SDHC_PROCTL, field DTW[2:1] (RW) * * Selects the data width of the SD bus for a data transfer. The host driver * shall set it to match the data width of the card. Possible data transfer width is * 1-bit, 4-bits or 8-bits. * * Values: * - 00 - 1-bit mode * - 01 - 4-bit mode * - 10 - 8-bit mode * - 11 - Reserved */ /*@{*/ #define BP_SDHC_PROCTL_DTW (1U) /*!< Bit position for SDHC_PROCTL_DTW. */ #define BM_SDHC_PROCTL_DTW (0x00000006U) /*!< Bit mask for SDHC_PROCTL_DTW. */ #define BS_SDHC_PROCTL_DTW (2U) /*!< Bit field size in bits for SDHC_PROCTL_DTW. */ /*! @brief Read current value of the SDHC_PROCTL_DTW field. */ #define BR_SDHC_PROCTL_DTW(x) (HW_SDHC_PROCTL(x).B.DTW) /*! @brief Format value for bitfield SDHC_PROCTL_DTW. */ #define BF_SDHC_PROCTL_DTW(v) ((uint32_t)((uint32_t)(v) << BP_SDHC_PROCTL_DTW) & BM_SDHC_PROCTL_DTW) /*! @brief Set the DTW field to a new value. */ #define BW_SDHC_PROCTL_DTW(x, v) (HW_SDHC_PROCTL_WR(x, (HW_SDHC_PROCTL_RD(x) & ~BM_SDHC_PROCTL_DTW) | BF_SDHC_PROCTL_DTW(v))) /*@}*/ /*! * @name Register SDHC_PROCTL, field D3CD[3] (RW) * * If this bit is set, DAT3 should be pulled down to act as a card detection * pin. Be cautious when using this feature, because DAT3 is also a chip-select for * the SPI mode. A pulldown on this pin and CMD0 may set the card into the SPI * mode, which the SDHC does not support. Note: Keep this bit set if SDIO interrupt * is used. * * Values: * - 0 - DAT3 does not monitor card Insertion. * - 1 - DAT3 as card detection pin. */ /*@{*/ #define BP_SDHC_PROCTL_D3CD (3U) /*!< Bit position for SDHC_PROCTL_D3CD. */ #define BM_SDHC_PROCTL_D3CD (0x00000008U) /*!< Bit mask for SDHC_PROCTL_D3CD. */ #define BS_SDHC_PROCTL_D3CD (1U) /*!< Bit field size in bits for SDHC_PROCTL_D3CD. */ /*! @brief Read current value of the SDHC_PROCTL_D3CD field. */ #define BR_SDHC_PROCTL_D3CD(x) (BITBAND_ACCESS32(HW_SDHC_PROCTL_ADDR(x), BP_SDHC_PROCTL_D3CD)) /*! @brief Format value for bitfield SDHC_PROCTL_D3CD. */ #define BF_SDHC_PROCTL_D3CD(v) ((uint32_t)((uint32_t)(v) << BP_SDHC_PROCTL_D3CD) & BM_SDHC_PROCTL_D3CD) /*! @brief Set the D3CD field to a new value. */ #define BW_SDHC_PROCTL_D3CD(x, v) (BITBAND_ACCESS32(HW_SDHC_PROCTL_ADDR(x), BP_SDHC_PROCTL_D3CD) = (v)) /*@}*/ /*! * @name Register SDHC_PROCTL, field EMODE[5:4] (RW) * * The SDHC supports all four endian modes in data transfer. * * Values: * - 00 - Big endian mode * - 01 - Half word big endian mode * - 10 - Little endian mode * - 11 - Reserved */ /*@{*/ #define BP_SDHC_PROCTL_EMODE (4U) /*!< Bit position for SDHC_PROCTL_EMODE. */ #define BM_SDHC_PROCTL_EMODE (0x00000030U) /*!< Bit mask for SDHC_PROCTL_EMODE. */ #define BS_SDHC_PROCTL_EMODE (2U) /*!< Bit field size in bits for SDHC_PROCTL_EMODE. */ /*! @brief Read current value of the SDHC_PROCTL_EMODE field. */ #define BR_SDHC_PROCTL_EMODE(x) (HW_SDHC_PROCTL(x).B.EMODE) /*! @brief Format value for bitfield SDHC_PROCTL_EMODE. */ #define BF_SDHC_PROCTL_EMODE(v) ((uint32_t)((uint32_t)(v) << BP_SDHC_PROCTL_EMODE) & BM_SDHC_PROCTL_EMODE) /*! @brief Set the EMODE field to a new value. */ #define BW_SDHC_PROCTL_EMODE(x, v) (HW_SDHC_PROCTL_WR(x, (HW_SDHC_PROCTL_RD(x) & ~BM_SDHC_PROCTL_EMODE) | BF_SDHC_PROCTL_EMODE(v))) /*@}*/ /*! * @name Register SDHC_PROCTL, field CDTL[6] (RW) * * Enabled while the CDSS is set to 1 and it indicates card insertion. * * Values: * - 0 - Card detect test level is 0, no card inserted. * - 1 - Card detect test level is 1, card inserted. */ /*@{*/ #define BP_SDHC_PROCTL_CDTL (6U) /*!< Bit position for SDHC_PROCTL_CDTL. */ #define BM_SDHC_PROCTL_CDTL (0x00000040U) /*!< Bit mask for SDHC_PROCTL_CDTL. */ #define BS_SDHC_PROCTL_CDTL (1U) /*!< Bit field size in bits for SDHC_PROCTL_CDTL. */ /*! @brief Read current value of the SDHC_PROCTL_CDTL field. */ #define BR_SDHC_PROCTL_CDTL(x) (BITBAND_ACCESS32(HW_SDHC_PROCTL_ADDR(x), BP_SDHC_PROCTL_CDTL)) /*! @brief Format value for bitfield SDHC_PROCTL_CDTL. */ #define BF_SDHC_PROCTL_CDTL(v) ((uint32_t)((uint32_t)(v) << BP_SDHC_PROCTL_CDTL) & BM_SDHC_PROCTL_CDTL) /*! @brief Set the CDTL field to a new value. */ #define BW_SDHC_PROCTL_CDTL(x, v) (BITBAND_ACCESS32(HW_SDHC_PROCTL_ADDR(x), BP_SDHC_PROCTL_CDTL) = (v)) /*@}*/ /*! * @name Register SDHC_PROCTL, field CDSS[7] (RW) * * Selects the source for the card detection. * * Values: * - 0 - Card detection level is selected for normal purpose. * - 1 - Card detection test level is selected for test purpose. */ /*@{*/ #define BP_SDHC_PROCTL_CDSS (7U) /*!< Bit position for SDHC_PROCTL_CDSS. */ #define BM_SDHC_PROCTL_CDSS (0x00000080U) /*!< Bit mask for SDHC_PROCTL_CDSS. */ #define BS_SDHC_PROCTL_CDSS (1U) /*!< Bit field size in bits for SDHC_PROCTL_CDSS. */ /*! @brief Read current value of the SDHC_PROCTL_CDSS field. */ #define BR_SDHC_PROCTL_CDSS(x) (BITBAND_ACCESS32(HW_SDHC_PROCTL_ADDR(x), BP_SDHC_PROCTL_CDSS)) /*! @brief Format value for bitfield SDHC_PROCTL_CDSS. */ #define BF_SDHC_PROCTL_CDSS(v) ((uint32_t)((uint32_t)(v) << BP_SDHC_PROCTL_CDSS) & BM_SDHC_PROCTL_CDSS) /*! @brief Set the CDSS field to a new value. */ #define BW_SDHC_PROCTL_CDSS(x, v) (BITBAND_ACCESS32(HW_SDHC_PROCTL_ADDR(x), BP_SDHC_PROCTL_CDSS) = (v)) /*@}*/ /*! * @name Register SDHC_PROCTL, field DMAS[9:8] (RW) * * This field is valid while DMA (SDMA or ADMA) is enabled and selects the DMA * operation. * * Values: * - 00 - No DMA or simple DMA is selected. * - 01 - ADMA1 is selected. * - 10 - ADMA2 is selected. * - 11 - Reserved */ /*@{*/ #define BP_SDHC_PROCTL_DMAS (8U) /*!< Bit position for SDHC_PROCTL_DMAS. */ #define BM_SDHC_PROCTL_DMAS (0x00000300U) /*!< Bit mask for SDHC_PROCTL_DMAS. */ #define BS_SDHC_PROCTL_DMAS (2U) /*!< Bit field size in bits for SDHC_PROCTL_DMAS. */ /*! @brief Read current value of the SDHC_PROCTL_DMAS field. */ #define BR_SDHC_PROCTL_DMAS(x) (HW_SDHC_PROCTL(x).B.DMAS) /*! @brief Format value for bitfield SDHC_PROCTL_DMAS. */ #define BF_SDHC_PROCTL_DMAS(v) ((uint32_t)((uint32_t)(v) << BP_SDHC_PROCTL_DMAS) & BM_SDHC_PROCTL_DMAS) /*! @brief Set the DMAS field to a new value. */ #define BW_SDHC_PROCTL_DMAS(x, v) (HW_SDHC_PROCTL_WR(x, (HW_SDHC_PROCTL_RD(x) & ~BM_SDHC_PROCTL_DMAS) | BF_SDHC_PROCTL_DMAS(v))) /*@}*/ /*! * @name Register SDHC_PROCTL, field SABGREQ[16] (RW) * * Used to stop executing a transaction at the next block gap for both DMA and * non-DMA transfers. Until the IRQSTATEN[TCSEN] is set to 1, indicating a * transfer completion, the host driver shall leave this bit set to 1. Clearing both * PROCTL[SABGREQ] and PROCTL[CREQ] does not cause the transaction to restart. Read * Wait is used to stop the read transaction at the block gap. The SDHC will * honor the PROCTL[SABGREQ] for write transfers, but for read transfers it requires * that SDIO card support read wait. Therefore, the host driver shall not set * this bit during read transfers unless the SDIO card supports read wait and has * set PROCTL[RWCTL] to 1, otherwise the SDHC will stop the SD bus clock to pause * the read operation during block gap. In the case of write transfers in which * the host driver writes data to the data port register, the host driver shall set * this bit after all block data is written. If this bit is set to 1, the host * driver shall not write data to the Data Port register after a block is sent. * Once this bit is set, the host driver shall not clear this bit before * IRQSTATEN[TCSEN] is set, otherwise the SDHC's behavior is undefined. This bit effects * PRSSTAT[RTA], PRSSTAT[WTA], and PRSSTAT[CDIHB]. * * Values: * - 0 - Transfer * - 1 - Stop */ /*@{*/ #define BP_SDHC_PROCTL_SABGREQ (16U) /*!< Bit position for SDHC_PROCTL_SABGREQ. */ #define BM_SDHC_PROCTL_SABGREQ (0x00010000U) /*!< Bit mask for SDHC_PROCTL_SABGREQ. */ #define BS_SDHC_PROCTL_SABGREQ (1U) /*!< Bit field size in bits for SDHC_PROCTL_SABGREQ. */ /*! @brief Read current value of the SDHC_PROCTL_SABGREQ field. */ #define BR_SDHC_PROCTL_SABGREQ(x) (BITBAND_ACCESS32(HW_SDHC_PROCTL_ADDR(x), BP_SDHC_PROCTL_SABGREQ)) /*! @brief Format value for bitfield SDHC_PROCTL_SABGREQ. */ #define BF_SDHC_PROCTL_SABGREQ(v) ((uint32_t)((uint32_t)(v) << BP_SDHC_PROCTL_SABGREQ) & BM_SDHC_PROCTL_SABGREQ) /*! @brief Set the SABGREQ field to a new value. */ #define BW_SDHC_PROCTL_SABGREQ(x, v) (BITBAND_ACCESS32(HW_SDHC_PROCTL_ADDR(x), BP_SDHC_PROCTL_SABGREQ) = (v)) /*@}*/ /*! * @name Register SDHC_PROCTL, field CREQ[17] (RW) * * Used to restart a transaction which was stopped using the PROCTL[SABGREQ]. * When a suspend operation is not accepted by the card, it is also by setting this * bit to restart the paused transfer. To cancel stop at the block gap, set * PROCTL[SABGREQ] to 0 and set this bit to 1 to restart the transfer. The SDHC * automatically clears this bit, therefore it is not necessary for the host driver to * set this bit to 0. If both PROCTL[SABGREQ] and this bit are 1, the continue * request is ignored. * * Values: * - 0 - No effect. * - 1 - Restart */ /*@{*/ #define BP_SDHC_PROCTL_CREQ (17U) /*!< Bit position for SDHC_PROCTL_CREQ. */ #define BM_SDHC_PROCTL_CREQ (0x00020000U) /*!< Bit mask for SDHC_PROCTL_CREQ. */ #define BS_SDHC_PROCTL_CREQ (1U) /*!< Bit field size in bits for SDHC_PROCTL_CREQ. */ /*! @brief Read current value of the SDHC_PROCTL_CREQ field. */ #define BR_SDHC_PROCTL_CREQ(x) (BITBAND_ACCESS32(HW_SDHC_PROCTL_ADDR(x), BP_SDHC_PROCTL_CREQ)) /*! @brief Format value for bitfield SDHC_PROCTL_CREQ. */ #define BF_SDHC_PROCTL_CREQ(v) ((uint32_t)((uint32_t)(v) << BP_SDHC_PROCTL_CREQ) & BM_SDHC_PROCTL_CREQ) /*! @brief Set the CREQ field to a new value. */ #define BW_SDHC_PROCTL_CREQ(x, v) (BITBAND_ACCESS32(HW_SDHC_PROCTL_ADDR(x), BP_SDHC_PROCTL_CREQ) = (v)) /*@}*/ /*! * @name Register SDHC_PROCTL, field RWCTL[18] (RW) * * The read wait function is optional for SDIO cards. If the card supports read * wait, set this bit to enable use of the read wait protocol to stop read data * using the DAT[2] line. Otherwise, the SDHC has to stop the SD Clock to hold * read data, which restricts commands generation. When the host driver detects an * SDIO card insertion, it shall set this bit according to the CCCR of the card. * If the card does not support read wait, this bit shall never be set to 1, * otherwise DAT line conflicts may occur. If this bit is set to 0, stop at block gap * during read operation is also supported, but the SDHC will stop the SD Clock * to pause reading operation. * * Values: * - 0 - Disable read wait control, and stop SD clock at block gap when SABGREQ * is set. * - 1 - Enable read wait control, and assert read wait without stopping SD * clock at block gap when SABGREQ bit is set. */ /*@{*/ #define BP_SDHC_PROCTL_RWCTL (18U) /*!< Bit position for SDHC_PROCTL_RWCTL. */ #define BM_SDHC_PROCTL_RWCTL (0x00040000U) /*!< Bit mask for SDHC_PROCTL_RWCTL. */ #define BS_SDHC_PROCTL_RWCTL (1U) /*!< Bit field size in bits for SDHC_PROCTL_RWCTL. */ /*! @brief Read current value of the SDHC_PROCTL_RWCTL field. */ #define BR_SDHC_PROCTL_RWCTL(x) (BITBAND_ACCESS32(HW_SDHC_PROCTL_ADDR(x), BP_SDHC_PROCTL_RWCTL)) /*! @brief Format value for bitfield SDHC_PROCTL_RWCTL. */ #define BF_SDHC_PROCTL_RWCTL(v) ((uint32_t)((uint32_t)(v) << BP_SDHC_PROCTL_RWCTL) & BM_SDHC_PROCTL_RWCTL) /*! @brief Set the RWCTL field to a new value. */ #define BW_SDHC_PROCTL_RWCTL(x, v) (BITBAND_ACCESS32(HW_SDHC_PROCTL_ADDR(x), BP_SDHC_PROCTL_RWCTL) = (v)) /*@}*/ /*! * @name Register SDHC_PROCTL, field IABG[19] (RW) * * Valid only in 4-bit mode, of the SDIO card, and selects a sample point in the * interrupt cycle. Setting to 1 enables interrupt detection at the block gap * for a multiple block transfer. Setting to 0 disables interrupt detection during * a multiple block transfer. If the SDIO card can't signal an interrupt during a * multiple block transfer, this bit must be set to 0 to avoid an inadvertent * interrupt. When the host driver detects an SDIO card insertion, it shall set * this bit according to the CCCR of the card. * * Values: * - 0 - Disabled * - 1 - Enabled */ /*@{*/ #define BP_SDHC_PROCTL_IABG (19U) /*!< Bit position for SDHC_PROCTL_IABG. */ #define BM_SDHC_PROCTL_IABG (0x00080000U) /*!< Bit mask for SDHC_PROCTL_IABG. */ #define BS_SDHC_PROCTL_IABG (1U) /*!< Bit field size in bits for SDHC_PROCTL_IABG. */ /*! @brief Read current value of the SDHC_PROCTL_IABG field. */ #define BR_SDHC_PROCTL_IABG(x) (BITBAND_ACCESS32(HW_SDHC_PROCTL_ADDR(x), BP_SDHC_PROCTL_IABG)) /*! @brief Format value for bitfield SDHC_PROCTL_IABG. */ #define BF_SDHC_PROCTL_IABG(v) ((uint32_t)((uint32_t)(v) << BP_SDHC_PROCTL_IABG) & BM_SDHC_PROCTL_IABG) /*! @brief Set the IABG field to a new value. */ #define BW_SDHC_PROCTL_IABG(x, v) (BITBAND_ACCESS32(HW_SDHC_PROCTL_ADDR(x), BP_SDHC_PROCTL_IABG) = (v)) /*@}*/ /*! * @name Register SDHC_PROCTL, field WECINT[24] (RW) * * Enables a wakeup event, via IRQSTAT[CINT]. This bit can be set to 1 if FN_WUS * (Wake Up Support) in CIS is set to 1. When this bit is set, the card * interrupt status and the SDHC interrupt can be asserted without SD_CLK toggling. When * the wakeup feature is not enabled, the SD_CLK must be active to assert the * card interrupt status and the SDHC interrupt. * * Values: * - 0 - Disabled * - 1 - Enabled */ /*@{*/ #define BP_SDHC_PROCTL_WECINT (24U) /*!< Bit position for SDHC_PROCTL_WECINT. */ #define BM_SDHC_PROCTL_WECINT (0x01000000U) /*!< Bit mask for SDHC_PROCTL_WECINT. */ #define BS_SDHC_PROCTL_WECINT (1U) /*!< Bit field size in bits for SDHC_PROCTL_WECINT. */ /*! @brief Read current value of the SDHC_PROCTL_WECINT field. */ #define BR_SDHC_PROCTL_WECINT(x) (BITBAND_ACCESS32(HW_SDHC_PROCTL_ADDR(x), BP_SDHC_PROCTL_WECINT)) /*! @brief Format value for bitfield SDHC_PROCTL_WECINT. */ #define BF_SDHC_PROCTL_WECINT(v) ((uint32_t)((uint32_t)(v) << BP_SDHC_PROCTL_WECINT) & BM_SDHC_PROCTL_WECINT) /*! @brief Set the WECINT field to a new value. */ #define BW_SDHC_PROCTL_WECINT(x, v) (BITBAND_ACCESS32(HW_SDHC_PROCTL_ADDR(x), BP_SDHC_PROCTL_WECINT) = (v)) /*@}*/ /*! * @name Register SDHC_PROCTL, field WECINS[25] (RW) * * Enables a wakeup event, via IRQSTAT[CINS]. FN_WUS (Wake Up Support) in CIS * does not effect this bit. When this bit is set, IRQSTATEN[CINSEN] and the SDHC * interrupt can be asserted without SD_CLK toggling. When the wakeup feature is * not enabled, the SD_CLK must be active to assert IRQSTATEN[CINSEN] and the SDHC * interrupt. * * Values: * - 0 - Disabled * - 1 - Enabled */ /*@{*/ #define BP_SDHC_PROCTL_WECINS (25U) /*!< Bit position for SDHC_PROCTL_WECINS. */ #define BM_SDHC_PROCTL_WECINS (0x02000000U) /*!< Bit mask for SDHC_PROCTL_WECINS. */ #define BS_SDHC_PROCTL_WECINS (1U) /*!< Bit field size in bits for SDHC_PROCTL_WECINS. */ /*! @brief Read current value of the SDHC_PROCTL_WECINS field. */ #define BR_SDHC_PROCTL_WECINS(x) (BITBAND_ACCESS32(HW_SDHC_PROCTL_ADDR(x), BP_SDHC_PROCTL_WECINS)) /*! @brief Format value for bitfield SDHC_PROCTL_WECINS. */ #define BF_SDHC_PROCTL_WECINS(v) ((uint32_t)((uint32_t)(v) << BP_SDHC_PROCTL_WECINS) & BM_SDHC_PROCTL_WECINS) /*! @brief Set the WECINS field to a new value. */ #define BW_SDHC_PROCTL_WECINS(x, v) (BITBAND_ACCESS32(HW_SDHC_PROCTL_ADDR(x), BP_SDHC_PROCTL_WECINS) = (v)) /*@}*/ /*! * @name Register SDHC_PROCTL, field WECRM[26] (RW) * * Enables a wakeup event, via IRQSTAT[CRM]. FN_WUS (Wake Up Support) in CIS * does not effect this bit. When this bit is set, IRQSTAT[CRM] and the SDHC * interrupt can be asserted without SD_CLK toggling. When the wakeup feature is not * enabled, the SD_CLK must be active to assert IRQSTAT[CRM] and the SDHC interrupt. * * Values: * - 0 - Disabled * - 1 - Enabled */ /*@{*/ #define BP_SDHC_PROCTL_WECRM (26U) /*!< Bit position for SDHC_PROCTL_WECRM. */ #define BM_SDHC_PROCTL_WECRM (0x04000000U) /*!< Bit mask for SDHC_PROCTL_WECRM. */ #define BS_SDHC_PROCTL_WECRM (1U) /*!< Bit field size in bits for SDHC_PROCTL_WECRM. */ /*! @brief Read current value of the SDHC_PROCTL_WECRM field. */ #define BR_SDHC_PROCTL_WECRM(x) (BITBAND_ACCESS32(HW_SDHC_PROCTL_ADDR(x), BP_SDHC_PROCTL_WECRM)) /*! @brief Format value for bitfield SDHC_PROCTL_WECRM. */ #define BF_SDHC_PROCTL_WECRM(v) ((uint32_t)((uint32_t)(v) << BP_SDHC_PROCTL_WECRM) & BM_SDHC_PROCTL_WECRM) /*! @brief Set the WECRM field to a new value. */ #define BW_SDHC_PROCTL_WECRM(x, v) (BITBAND_ACCESS32(HW_SDHC_PROCTL_ADDR(x), BP_SDHC_PROCTL_WECRM) = (v)) /*@}*/ /******************************************************************************* * HW_SDHC_SYSCTL - System Control register ******************************************************************************/ /*! * @brief HW_SDHC_SYSCTL - System Control register (RW) * * Reset value: 0x00008008U */ typedef union _hw_sdhc_sysctl { uint32_t U; struct _hw_sdhc_sysctl_bitfields { uint32_t IPGEN : 1; /*!< [0] IPG Clock Enable */ uint32_t HCKEN : 1; /*!< [1] System Clock Enable */ uint32_t PEREN : 1; /*!< [2] Peripheral Clock Enable */ uint32_t SDCLKEN : 1; /*!< [3] SD Clock Enable */ uint32_t DVS : 4; /*!< [7:4] Divisor */ uint32_t SDCLKFS : 8; /*!< [15:8] SDCLK Frequency Select */ uint32_t DTOCV : 4; /*!< [19:16] Data Timeout Counter Value */ uint32_t RESERVED0 : 4; /*!< [23:20] */ uint32_t RSTA : 1; /*!< [24] Software Reset For ALL */ uint32_t RSTC : 1; /*!< [25] Software Reset For CMD Line */ uint32_t RSTD : 1; /*!< [26] Software Reset For DAT Line */ uint32_t INITA : 1; /*!< [27] Initialization Active */ uint32_t RESERVED1 : 4; /*!< [31:28] */ } B; } hw_sdhc_sysctl_t; /*! * @name Constants and macros for entire SDHC_SYSCTL register */ /*@{*/ #define HW_SDHC_SYSCTL_ADDR(x) ((x) + 0x2CU) #define HW_SDHC_SYSCTL(x) (*(__IO hw_sdhc_sysctl_t *) HW_SDHC_SYSCTL_ADDR(x)) #define HW_SDHC_SYSCTL_RD(x) (HW_SDHC_SYSCTL(x).U) #define HW_SDHC_SYSCTL_WR(x, v) (HW_SDHC_SYSCTL(x).U = (v)) #define HW_SDHC_SYSCTL_SET(x, v) (HW_SDHC_SYSCTL_WR(x, HW_SDHC_SYSCTL_RD(x) | (v))) #define HW_SDHC_SYSCTL_CLR(x, v) (HW_SDHC_SYSCTL_WR(x, HW_SDHC_SYSCTL_RD(x) & ~(v))) #define HW_SDHC_SYSCTL_TOG(x, v) (HW_SDHC_SYSCTL_WR(x, HW_SDHC_SYSCTL_RD(x) ^ (v))) /*@}*/ /* * Constants & macros for individual SDHC_SYSCTL bitfields */ /*! * @name Register SDHC_SYSCTL, field IPGEN[0] (RW) * * If this bit is set, bus clock will always be active and no automatic gating * is applied. The bus clock will be internally gated off, if none of the * following factors are met: The cmd part is reset, or Data part is reset, or Soft * reset, or The cmd is about to send, or Clock divisor is just updated, or Continue * request is just set, or This bit is set, or Card insertion is detected, or Card * removal is detected, or Card external interrupt is detected, or The SDHC * clock is not gated off The bus clock will not be auto gated off if the SDHC clock * is not gated off. So clearing only this bit has no effect unless the PEREN bit * is also cleared. * * Values: * - 0 - Bus clock will be internally gated off. * - 1 - Bus clock will not be automatically gated off. */ /*@{*/ #define BP_SDHC_SYSCTL_IPGEN (0U) /*!< Bit position for SDHC_SYSCTL_IPGEN. */ #define BM_SDHC_SYSCTL_IPGEN (0x00000001U) /*!< Bit mask for SDHC_SYSCTL_IPGEN. */ #define BS_SDHC_SYSCTL_IPGEN (1U) /*!< Bit field size in bits for SDHC_SYSCTL_IPGEN. */ /*! @brief Read current value of the SDHC_SYSCTL_IPGEN field. */ #define BR_SDHC_SYSCTL_IPGEN(x) (BITBAND_ACCESS32(HW_SDHC_SYSCTL_ADDR(x), BP_SDHC_SYSCTL_IPGEN)) /*! @brief Format value for bitfield SDHC_SYSCTL_IPGEN. */ #define BF_SDHC_SYSCTL_IPGEN(v) ((uint32_t)((uint32_t)(v) << BP_SDHC_SYSCTL_IPGEN) & BM_SDHC_SYSCTL_IPGEN) /*! @brief Set the IPGEN field to a new value. */ #define BW_SDHC_SYSCTL_IPGEN(x, v) (BITBAND_ACCESS32(HW_SDHC_SYSCTL_ADDR(x), BP_SDHC_SYSCTL_IPGEN) = (v)) /*@}*/ /*! * @name Register SDHC_SYSCTL, field HCKEN[1] (RW) * * If this bit is set, system clock will always be active and no automatic * gating is applied. When this bit is cleared, system clock will be automatically off * when no data transfer is on the SD bus. * * Values: * - 0 - System clock will be internally gated off. * - 1 - System clock will not be automatically gated off. */ /*@{*/ #define BP_SDHC_SYSCTL_HCKEN (1U) /*!< Bit position for SDHC_SYSCTL_HCKEN. */ #define BM_SDHC_SYSCTL_HCKEN (0x00000002U) /*!< Bit mask for SDHC_SYSCTL_HCKEN. */ #define BS_SDHC_SYSCTL_HCKEN (1U) /*!< Bit field size in bits for SDHC_SYSCTL_HCKEN. */ /*! @brief Read current value of the SDHC_SYSCTL_HCKEN field. */ #define BR_SDHC_SYSCTL_HCKEN(x) (BITBAND_ACCESS32(HW_SDHC_SYSCTL_ADDR(x), BP_SDHC_SYSCTL_HCKEN)) /*! @brief Format value for bitfield SDHC_SYSCTL_HCKEN. */ #define BF_SDHC_SYSCTL_HCKEN(v) ((uint32_t)((uint32_t)(v) << BP_SDHC_SYSCTL_HCKEN) & BM_SDHC_SYSCTL_HCKEN) /*! @brief Set the HCKEN field to a new value. */ #define BW_SDHC_SYSCTL_HCKEN(x, v) (BITBAND_ACCESS32(HW_SDHC_SYSCTL_ADDR(x), BP_SDHC_SYSCTL_HCKEN) = (v)) /*@}*/ /*! * @name Register SDHC_SYSCTL, field PEREN[2] (RW) * * If this bit is set, SDHC clock will always be active and no automatic gating * is applied. Thus the SDCLK is active except for when auto gating-off during * buffer danger (buffer about to over-run or under-run). When this bit is cleared, * the SDHC clock will be automatically off whenever there is no transaction on * the SD bus. Because this bit is only a feature enabling bit, clearing this bit * does not stop SDCLK immediately. The SDHC clock will be internally gated off, * if none of the following factors are met: The cmd part is reset, or Data part * is reset, or A soft reset, or The cmd is about to send, or Clock divisor is * just updated, or Continue request is just set, or This bit is set, or Card * insertion is detected, or Card removal is detected, or Card external interrupt is * detected, or 80 clocks for initialization phase is ongoing * * Values: * - 0 - SDHC clock will be internally gated off. * - 1 - SDHC clock will not be automatically gated off. */ /*@{*/ #define BP_SDHC_SYSCTL_PEREN (2U) /*!< Bit position for SDHC_SYSCTL_PEREN. */ #define BM_SDHC_SYSCTL_PEREN (0x00000004U) /*!< Bit mask for SDHC_SYSCTL_PEREN. */ #define BS_SDHC_SYSCTL_PEREN (1U) /*!< Bit field size in bits for SDHC_SYSCTL_PEREN. */ /*! @brief Read current value of the SDHC_SYSCTL_PEREN field. */ #define BR_SDHC_SYSCTL_PEREN(x) (BITBAND_ACCESS32(HW_SDHC_SYSCTL_ADDR(x), BP_SDHC_SYSCTL_PEREN)) /*! @brief Format value for bitfield SDHC_SYSCTL_PEREN. */ #define BF_SDHC_SYSCTL_PEREN(v) ((uint32_t)((uint32_t)(v) << BP_SDHC_SYSCTL_PEREN) & BM_SDHC_SYSCTL_PEREN) /*! @brief Set the PEREN field to a new value. */ #define BW_SDHC_SYSCTL_PEREN(x, v) (BITBAND_ACCESS32(HW_SDHC_SYSCTL_ADDR(x), BP_SDHC_SYSCTL_PEREN) = (v)) /*@}*/ /*! * @name Register SDHC_SYSCTL, field SDCLKEN[3] (RW) * * The host controller shall stop SDCLK when writing this bit to 0. SDCLK * frequency can be changed when this bit is 0. Then, the host controller shall * maintain the same clock frequency until SDCLK is stopped (stop at SDCLK = 0). If the * IRQSTAT[CINS] is cleared, this bit must be cleared by the host driver to save * power. */ /*@{*/ #define BP_SDHC_SYSCTL_SDCLKEN (3U) /*!< Bit position for SDHC_SYSCTL_SDCLKEN. */ #define BM_SDHC_SYSCTL_SDCLKEN (0x00000008U) /*!< Bit mask for SDHC_SYSCTL_SDCLKEN. */ #define BS_SDHC_SYSCTL_SDCLKEN (1U) /*!< Bit field size in bits for SDHC_SYSCTL_SDCLKEN. */ /*! @brief Read current value of the SDHC_SYSCTL_SDCLKEN field. */ #define BR_SDHC_SYSCTL_SDCLKEN(x) (BITBAND_ACCESS32(HW_SDHC_SYSCTL_ADDR(x), BP_SDHC_SYSCTL_SDCLKEN)) /*! @brief Format value for bitfield SDHC_SYSCTL_SDCLKEN. */ #define BF_SDHC_SYSCTL_SDCLKEN(v) ((uint32_t)((uint32_t)(v) << BP_SDHC_SYSCTL_SDCLKEN) & BM_SDHC_SYSCTL_SDCLKEN) /*! @brief Set the SDCLKEN field to a new value. */ #define BW_SDHC_SYSCTL_SDCLKEN(x, v) (BITBAND_ACCESS32(HW_SDHC_SYSCTL_ADDR(x), BP_SDHC_SYSCTL_SDCLKEN) = (v)) /*@}*/ /*! * @name Register SDHC_SYSCTL, field DVS[7:4] (RW) * * Used to provide a more exact divisor to generate the desired SD clock * frequency. Note the divider can even support odd divisor without deterioration of * duty cycle. The setting are as following: * * Values: * - 0 - Divisor by 1. * - 1 - Divisor by 2. * - 1110 - Divisor by 15. * - 1111 - Divisor by 16. */ /*@{*/ #define BP_SDHC_SYSCTL_DVS (4U) /*!< Bit position for SDHC_SYSCTL_DVS. */ #define BM_SDHC_SYSCTL_DVS (0x000000F0U) /*!< Bit mask for SDHC_SYSCTL_DVS. */ #define BS_SDHC_SYSCTL_DVS (4U) /*!< Bit field size in bits for SDHC_SYSCTL_DVS. */ /*! @brief Read current value of the SDHC_SYSCTL_DVS field. */ #define BR_SDHC_SYSCTL_DVS(x) (HW_SDHC_SYSCTL(x).B.DVS) /*! @brief Format value for bitfield SDHC_SYSCTL_DVS. */ #define BF_SDHC_SYSCTL_DVS(v) ((uint32_t)((uint32_t)(v) << BP_SDHC_SYSCTL_DVS) & BM_SDHC_SYSCTL_DVS) /*! @brief Set the DVS field to a new value. */ #define BW_SDHC_SYSCTL_DVS(x, v) (HW_SDHC_SYSCTL_WR(x, (HW_SDHC_SYSCTL_RD(x) & ~BM_SDHC_SYSCTL_DVS) | BF_SDHC_SYSCTL_DVS(v))) /*@}*/ /*! * @name Register SDHC_SYSCTL, field SDCLKFS[15:8] (RW) * * Used to select the frequency of the SDCLK pin. The frequency is not * programmed directly. Rather this register holds the prescaler (this register) and * divisor (next register) of the base clock frequency register. Setting 00h bypasses * the frequency prescaler of the SD Clock. Multiple bits must not be set, or the * behavior of this prescaler is undefined. The two default divider values can * be calculated by the frequency of SDHC clock and the following divisor bits. * The frequency of SDCLK is set by the following formula: Clock frequency = (Base * clock) / (prescaler x divisor) For example, if the base clock frequency is 96 * MHz, and the target frequency is 25 MHz, then choosing the prescaler value of * 01h and divisor value of 1h will yield 24 MHz, which is the nearest frequency * less than or equal to the target. Similarly, to approach a clock value of 400 * kHz, the prescaler value of 08h and divisor value of eh yields the exact clock * value of 400 kHz. The reset value of this field is 80h, so if the input base * clock ( SDHC clock ) is about 96 MHz, the default SD clock after reset is 375 * kHz. According to the SD Physical Specification Version 1.1 and the SDIO Card * Specification Version 1.2, the maximum SD clock frequency is 50 MHz and shall * never exceed this limit. Only the following settings are allowed: * * Values: * - 1 - Base clock divided by 2. * - 10 - Base clock divided by 4. * - 100 - Base clock divided by 8. * - 1000 - Base clock divided by 16. * - 10000 - Base clock divided by 32. * - 100000 - Base clock divided by 64. * - 1000000 - Base clock divided by 128. * - 10000000 - Base clock divided by 256. */ /*@{*/ #define BP_SDHC_SYSCTL_SDCLKFS (8U) /*!< Bit position for SDHC_SYSCTL_SDCLKFS. */ #define BM_SDHC_SYSCTL_SDCLKFS (0x0000FF00U) /*!< Bit mask for SDHC_SYSCTL_SDCLKFS. */ #define BS_SDHC_SYSCTL_SDCLKFS (8U) /*!< Bit field size in bits for SDHC_SYSCTL_SDCLKFS. */ /*! @brief Read current value of the SDHC_SYSCTL_SDCLKFS field. */ #define BR_SDHC_SYSCTL_SDCLKFS(x) (HW_SDHC_SYSCTL(x).B.SDCLKFS) /*! @brief Format value for bitfield SDHC_SYSCTL_SDCLKFS. */ #define BF_SDHC_SYSCTL_SDCLKFS(v) ((uint32_t)((uint32_t)(v) << BP_SDHC_SYSCTL_SDCLKFS) & BM_SDHC_SYSCTL_SDCLKFS) /*! @brief Set the SDCLKFS field to a new value. */ #define BW_SDHC_SYSCTL_SDCLKFS(x, v) (HW_SDHC_SYSCTL_WR(x, (HW_SDHC_SYSCTL_RD(x) & ~BM_SDHC_SYSCTL_SDCLKFS) | BF_SDHC_SYSCTL_SDCLKFS(v))) /*@}*/ /*! * @name Register SDHC_SYSCTL, field DTOCV[19:16] (RW) * * Determines the interval by which DAT line timeouts are detected. See * IRQSTAT[DTOE] for information on factors that dictate time-out generation. Time-out * clock frequency will be generated by dividing the base clock SDCLK value by this * value. The host driver can clear IRQSTATEN[DTOESEN] to prevent inadvertent * time-out events. * * Values: * - 0000 - SDCLK x 2 13 * - 0001 - SDCLK x 2 14 * - 1110 - SDCLK x 2 27 * - 1111 - Reserved */ /*@{*/ #define BP_SDHC_SYSCTL_DTOCV (16U) /*!< Bit position for SDHC_SYSCTL_DTOCV. */ #define BM_SDHC_SYSCTL_DTOCV (0x000F0000U) /*!< Bit mask for SDHC_SYSCTL_DTOCV. */ #define BS_SDHC_SYSCTL_DTOCV (4U) /*!< Bit field size in bits for SDHC_SYSCTL_DTOCV. */ /*! @brief Read current value of the SDHC_SYSCTL_DTOCV field. */ #define BR_SDHC_SYSCTL_DTOCV(x) (HW_SDHC_SYSCTL(x).B.DTOCV) /*! @brief Format value for bitfield SDHC_SYSCTL_DTOCV. */ #define BF_SDHC_SYSCTL_DTOCV(v) ((uint32_t)((uint32_t)(v) << BP_SDHC_SYSCTL_DTOCV) & BM_SDHC_SYSCTL_DTOCV) /*! @brief Set the DTOCV field to a new value. */ #define BW_SDHC_SYSCTL_DTOCV(x, v) (HW_SDHC_SYSCTL_WR(x, (HW_SDHC_SYSCTL_RD(x) & ~BM_SDHC_SYSCTL_DTOCV) | BF_SDHC_SYSCTL_DTOCV(v))) /*@}*/ /*! * @name Register SDHC_SYSCTL, field RSTA[24] (WORZ) * * Effects the entire host controller except for the card detection circuit. * Register bits of type ROC, RW, RW1C, RWAC are cleared. During its initialization, * the host driver shall set this bit to 1 to reset the SDHC. The SDHC shall * reset this bit to 0 when the capabilities registers are valid and the host driver * can read them. Additional use of software reset for all does not affect the * value of the capabilities registers. After this bit is set, it is recommended * that the host driver reset the external card and reinitialize it. * * Values: * - 0 - No reset. * - 1 - Reset. */ /*@{*/ #define BP_SDHC_SYSCTL_RSTA (24U) /*!< Bit position for SDHC_SYSCTL_RSTA. */ #define BM_SDHC_SYSCTL_RSTA (0x01000000U) /*!< Bit mask for SDHC_SYSCTL_RSTA. */ #define BS_SDHC_SYSCTL_RSTA (1U) /*!< Bit field size in bits for SDHC_SYSCTL_RSTA. */ /*! @brief Format value for bitfield SDHC_SYSCTL_RSTA. */ #define BF_SDHC_SYSCTL_RSTA(v) ((uint32_t)((uint32_t)(v) << BP_SDHC_SYSCTL_RSTA) & BM_SDHC_SYSCTL_RSTA) /*! @brief Set the RSTA field to a new value. */ #define BW_SDHC_SYSCTL_RSTA(x, v) (BITBAND_ACCESS32(HW_SDHC_SYSCTL_ADDR(x), BP_SDHC_SYSCTL_RSTA) = (v)) /*@}*/ /*! * @name Register SDHC_SYSCTL, field RSTC[25] (WORZ) * * Only part of the command circuit is reset. The following registers and bits * are cleared by this bit: PRSSTAT[CIHB] IRQSTAT[CC] * * Values: * - 0 - No reset. * - 1 - Reset. */ /*@{*/ #define BP_SDHC_SYSCTL_RSTC (25U) /*!< Bit position for SDHC_SYSCTL_RSTC. */ #define BM_SDHC_SYSCTL_RSTC (0x02000000U) /*!< Bit mask for SDHC_SYSCTL_RSTC. */ #define BS_SDHC_SYSCTL_RSTC (1U) /*!< Bit field size in bits for SDHC_SYSCTL_RSTC. */ /*! @brief Format value for bitfield SDHC_SYSCTL_RSTC. */ #define BF_SDHC_SYSCTL_RSTC(v) ((uint32_t)((uint32_t)(v) << BP_SDHC_SYSCTL_RSTC) & BM_SDHC_SYSCTL_RSTC) /*! @brief Set the RSTC field to a new value. */ #define BW_SDHC_SYSCTL_RSTC(x, v) (BITBAND_ACCESS32(HW_SDHC_SYSCTL_ADDR(x), BP_SDHC_SYSCTL_RSTC) = (v)) /*@}*/ /*! * @name Register SDHC_SYSCTL, field RSTD[26] (WORZ) * * Only part of the data circuit is reset. DMA circuit is also reset. The * following registers and bits are cleared by this bit: Data Port register Buffer Is * Cleared And Initialized.Present State register Buffer Read Enable Buffer Write * Enable Read Transfer Active Write Transfer Active DAT Line Active Command * Inhibit (DAT) Protocol Control register Continue Request Stop At Block Gap Request * Interrupt Status register Buffer Read Ready Buffer Write Ready DMA Interrupt * Block Gap Event Transfer Complete * * Values: * - 0 - No reset. * - 1 - Reset. */ /*@{*/ #define BP_SDHC_SYSCTL_RSTD (26U) /*!< Bit position for SDHC_SYSCTL_RSTD. */ #define BM_SDHC_SYSCTL_RSTD (0x04000000U) /*!< Bit mask for SDHC_SYSCTL_RSTD. */ #define BS_SDHC_SYSCTL_RSTD (1U) /*!< Bit field size in bits for SDHC_SYSCTL_RSTD. */ /*! @brief Format value for bitfield SDHC_SYSCTL_RSTD. */ #define BF_SDHC_SYSCTL_RSTD(v) ((uint32_t)((uint32_t)(v) << BP_SDHC_SYSCTL_RSTD) & BM_SDHC_SYSCTL_RSTD) /*! @brief Set the RSTD field to a new value. */ #define BW_SDHC_SYSCTL_RSTD(x, v) (BITBAND_ACCESS32(HW_SDHC_SYSCTL_ADDR(x), BP_SDHC_SYSCTL_RSTD) = (v)) /*@}*/ /*! * @name Register SDHC_SYSCTL, field INITA[27] (RW) * * When this bit is set, 80 SD-clocks are sent to the card. After the 80 clocks * are sent, this bit is self-cleared. This bit is very useful during the card * power-up period when 74 SD-clocks are needed and the clock auto gating feature * is enabled. Writing 1 to this bit when this bit is already 1 has no effect. * Writing 0 to this bit at any time has no effect. When either of the PRSSTAT[CIHB] * and PRSSTAT[CDIHB] bits are set, writing 1 to this bit is ignored, that is, * when command line or data lines are active, write to this bit is not allowed. * On the otherhand, when this bit is set, that is, during intialization active * period, it is allowed to issue command, and the command bit stream will appear * on the CMD pad after all 80 clock cycles are done. So when this command ends, * the driver can make sure the 80 clock cycles are sent out. This is very useful * when the driver needs send 80 cycles to the card and does not want to wait * till this bit is self-cleared. */ /*@{*/ #define BP_SDHC_SYSCTL_INITA (27U) /*!< Bit position for SDHC_SYSCTL_INITA. */ #define BM_SDHC_SYSCTL_INITA (0x08000000U) /*!< Bit mask for SDHC_SYSCTL_INITA. */ #define BS_SDHC_SYSCTL_INITA (1U) /*!< Bit field size in bits for SDHC_SYSCTL_INITA. */ /*! @brief Read current value of the SDHC_SYSCTL_INITA field. */ #define BR_SDHC_SYSCTL_INITA(x) (BITBAND_ACCESS32(HW_SDHC_SYSCTL_ADDR(x), BP_SDHC_SYSCTL_INITA)) /*! @brief Format value for bitfield SDHC_SYSCTL_INITA. */ #define BF_SDHC_SYSCTL_INITA(v) ((uint32_t)((uint32_t)(v) << BP_SDHC_SYSCTL_INITA) & BM_SDHC_SYSCTL_INITA) /*! @brief Set the INITA field to a new value. */ #define BW_SDHC_SYSCTL_INITA(x, v) (BITBAND_ACCESS32(HW_SDHC_SYSCTL_ADDR(x), BP_SDHC_SYSCTL_INITA) = (v)) /*@}*/ /******************************************************************************* * HW_SDHC_IRQSTAT - Interrupt Status register ******************************************************************************/ /*! * @brief HW_SDHC_IRQSTAT - Interrupt Status register (RW) * * Reset value: 0x00000000U * * An interrupt is generated when the Normal Interrupt Signal Enable is enabled * and at least one of the status bits is set to 1. For all bits, writing 1 to a * bit clears it; writing to 0 keeps the bit unchanged. More than one status can * be cleared with a single register write. For Card Interrupt, before writing 1 * to clear, it is required that the card stops asserting the interrupt, meaning * that when the Card Driver services the interrupt condition, otherwise the CINT * bit will be asserted again. The table below shows the relationship between * the CTOE and the CC bits. SDHC status for CTOE/CC bit combinations Command * complete Command timeout error Meaning of the status 0 0 X X 1 Response not * received within 64 SDCLK cycles 1 0 Response received The table below shows the * relationship between the Transfer Complete and the Data Timeout Error. SDHC status * for data timeout error/transfer complete bit combinations Transfer complete * Data timeout error Meaning of the status 0 0 X 0 1 Timeout occurred during * transfer 1 X Data transfer complete The table below shows the relationship between * the command CRC Error (CCE) and Command Timeout Error (CTOE). SDHC status for * CCE/CTOE Bit Combinations Command complete Command timeout error Meaning of * the status 0 0 No error 0 1 Response timeout error 1 0 Response CRC error 1 1 * CMD line conflict */ typedef union _hw_sdhc_irqstat { uint32_t U; struct _hw_sdhc_irqstat_bitfields { uint32_t CC : 1; /*!< [0] Command Complete */ uint32_t TC : 1; /*!< [1] Transfer Complete */ uint32_t BGE : 1; /*!< [2] Block Gap Event */ uint32_t DINT : 1; /*!< [3] DMA Interrupt */ uint32_t BWR : 1; /*!< [4] Buffer Write Ready */ uint32_t BRR : 1; /*!< [5] Buffer Read Ready */ uint32_t CINS : 1; /*!< [6] Card Insertion */ uint32_t CRM : 1; /*!< [7] Card Removal */ uint32_t CINT : 1; /*!< [8] Card Interrupt */ uint32_t RESERVED0 : 7; /*!< [15:9] */ uint32_t CTOE : 1; /*!< [16] Command Timeout Error */ uint32_t CCE : 1; /*!< [17] Command CRC Error */ uint32_t CEBE : 1; /*!< [18] Command End Bit Error */ uint32_t CIE : 1; /*!< [19] Command Index Error */ uint32_t DTOE : 1; /*!< [20] Data Timeout Error */ uint32_t DCE : 1; /*!< [21] Data CRC Error */ uint32_t DEBE : 1; /*!< [22] Data End Bit Error */ uint32_t RESERVED1 : 1; /*!< [23] */ uint32_t AC12E : 1; /*!< [24] Auto CMD12 Error */ uint32_t RESERVED2 : 3; /*!< [27:25] */ uint32_t DMAE : 1; /*!< [28] DMA Error */ uint32_t RESERVED3 : 3; /*!< [31:29] */ } B; } hw_sdhc_irqstat_t; /*! * @name Constants and macros for entire SDHC_IRQSTAT register */ /*@{*/ #define HW_SDHC_IRQSTAT_ADDR(x) ((x) + 0x30U) #define HW_SDHC_IRQSTAT(x) (*(__IO hw_sdhc_irqstat_t *) HW_SDHC_IRQSTAT_ADDR(x)) #define HW_SDHC_IRQSTAT_RD(x) (HW_SDHC_IRQSTAT(x).U) #define HW_SDHC_IRQSTAT_WR(x, v) (HW_SDHC_IRQSTAT(x).U = (v)) #define HW_SDHC_IRQSTAT_SET(x, v) (HW_SDHC_IRQSTAT_WR(x, HW_SDHC_IRQSTAT_RD(x) | (v))) #define HW_SDHC_IRQSTAT_CLR(x, v) (HW_SDHC_IRQSTAT_WR(x, HW_SDHC_IRQSTAT_RD(x) & ~(v))) #define HW_SDHC_IRQSTAT_TOG(x, v) (HW_SDHC_IRQSTAT_WR(x, HW_SDHC_IRQSTAT_RD(x) ^ (v))) /*@}*/ /* * Constants & macros for individual SDHC_IRQSTAT bitfields */ /*! * @name Register SDHC_IRQSTAT, field CC[0] (W1C) * * This bit is set when you receive the end bit of the command response, except * Auto CMD12. See PRSSTAT[CIHB]. * * Values: * - 0 - Command not complete. * - 1 - Command complete. */ /*@{*/ #define BP_SDHC_IRQSTAT_CC (0U) /*!< Bit position for SDHC_IRQSTAT_CC. */ #define BM_SDHC_IRQSTAT_CC (0x00000001U) /*!< Bit mask for SDHC_IRQSTAT_CC. */ #define BS_SDHC_IRQSTAT_CC (1U) /*!< Bit field size in bits for SDHC_IRQSTAT_CC. */ /*! @brief Read current value of the SDHC_IRQSTAT_CC field. */ #define BR_SDHC_IRQSTAT_CC(x) (BITBAND_ACCESS32(HW_SDHC_IRQSTAT_ADDR(x), BP_SDHC_IRQSTAT_CC)) /*! @brief Format value for bitfield SDHC_IRQSTAT_CC. */ #define BF_SDHC_IRQSTAT_CC(v) ((uint32_t)((uint32_t)(v) << BP_SDHC_IRQSTAT_CC) & BM_SDHC_IRQSTAT_CC) /*! @brief Set the CC field to a new value. */ #define BW_SDHC_IRQSTAT_CC(x, v) (BITBAND_ACCESS32(HW_SDHC_IRQSTAT_ADDR(x), BP_SDHC_IRQSTAT_CC) = (v)) /*@}*/ /*! * @name Register SDHC_IRQSTAT, field TC[1] (W1C) * * This bit is set when a read or write transfer is completed. In the case of a * read transaction: This bit is set at the falling edge of the read transfer * active status. There are two cases in which this interrupt is generated. The * first is when a data transfer is completed as specified by the data length, after * the last data has been read to the host system. The second is when data has * stopped at the block gap and completed the data transfer by setting * PROCTL[SABGREQ], after valid data has been read to the host system. In the case of a write * transaction: This bit is set at the falling edge of the DAT line active * status. There are two cases in which this interrupt is generated. The first is when * the last data is written to the SD card as specified by the data length and * the busy signal is released. The second is when data transfers are stopped at * the block gap, by setting PROCTL[SABGREQ], and the data transfers are * completed,after valid data is written to the SD card and the busy signal released. * * Values: * - 0 - Transfer not complete. * - 1 - Transfer complete. */ /*@{*/ #define BP_SDHC_IRQSTAT_TC (1U) /*!< Bit position for SDHC_IRQSTAT_TC. */ #define BM_SDHC_IRQSTAT_TC (0x00000002U) /*!< Bit mask for SDHC_IRQSTAT_TC. */ #define BS_SDHC_IRQSTAT_TC (1U) /*!< Bit field size in bits for SDHC_IRQSTAT_TC. */ /*! @brief Read current value of the SDHC_IRQSTAT_TC field. */ #define BR_SDHC_IRQSTAT_TC(x) (BITBAND_ACCESS32(HW_SDHC_IRQSTAT_ADDR(x), BP_SDHC_IRQSTAT_TC)) /*! @brief Format value for bitfield SDHC_IRQSTAT_TC. */ #define BF_SDHC_IRQSTAT_TC(v) ((uint32_t)((uint32_t)(v) << BP_SDHC_IRQSTAT_TC) & BM_SDHC_IRQSTAT_TC) /*! @brief Set the TC field to a new value. */ #define BW_SDHC_IRQSTAT_TC(x, v) (BITBAND_ACCESS32(HW_SDHC_IRQSTAT_ADDR(x), BP_SDHC_IRQSTAT_TC) = (v)) /*@}*/ /*! * @name Register SDHC_IRQSTAT, field BGE[2] (W1C) * * If PROCTL[SABGREQ] is set, this bit is set when a read or write transaction * is stopped at a block gap. If PROCTL[SABGREQ] is not set to 1, this bit is not * set to 1. In the case of a read transaction: This bit is set at the falling * edge of the DAT line active status, when the transaction is stopped at SD Bus * timing. The read wait must be supported in order to use this function. In the * case of write transaction: This bit is set at the falling edge of write transfer * active status, after getting CRC status at SD bus timing. * * Values: * - 0 - No block gap event. * - 1 - Transaction stopped at block gap. */ /*@{*/ #define BP_SDHC_IRQSTAT_BGE (2U) /*!< Bit position for SDHC_IRQSTAT_BGE. */ #define BM_SDHC_IRQSTAT_BGE (0x00000004U) /*!< Bit mask for SDHC_IRQSTAT_BGE. */ #define BS_SDHC_IRQSTAT_BGE (1U) /*!< Bit field size in bits for SDHC_IRQSTAT_BGE. */ /*! @brief Read current value of the SDHC_IRQSTAT_BGE field. */ #define BR_SDHC_IRQSTAT_BGE(x) (BITBAND_ACCESS32(HW_SDHC_IRQSTAT_ADDR(x), BP_SDHC_IRQSTAT_BGE)) /*! @brief Format value for bitfield SDHC_IRQSTAT_BGE. */ #define BF_SDHC_IRQSTAT_BGE(v) ((uint32_t)((uint32_t)(v) << BP_SDHC_IRQSTAT_BGE) & BM_SDHC_IRQSTAT_BGE) /*! @brief Set the BGE field to a new value. */ #define BW_SDHC_IRQSTAT_BGE(x, v) (BITBAND_ACCESS32(HW_SDHC_IRQSTAT_ADDR(x), BP_SDHC_IRQSTAT_BGE) = (v)) /*@}*/ /*! * @name Register SDHC_IRQSTAT, field DINT[3] (W1C) * * Occurs only when the internal DMA finishes the data transfer successfully. * Whenever errors occur during data transfer, this bit will not be set. Instead, * the DMAE bit will be set. Either Simple DMA or ADMA finishes data transferring, * this bit will be set. * * Values: * - 0 - No DMA Interrupt. * - 1 - DMA Interrupt is generated. */ /*@{*/ #define BP_SDHC_IRQSTAT_DINT (3U) /*!< Bit position for SDHC_IRQSTAT_DINT. */ #define BM_SDHC_IRQSTAT_DINT (0x00000008U) /*!< Bit mask for SDHC_IRQSTAT_DINT. */ #define BS_SDHC_IRQSTAT_DINT (1U) /*!< Bit field size in bits for SDHC_IRQSTAT_DINT. */ /*! @brief Read current value of the SDHC_IRQSTAT_DINT field. */ #define BR_SDHC_IRQSTAT_DINT(x) (BITBAND_ACCESS32(HW_SDHC_IRQSTAT_ADDR(x), BP_SDHC_IRQSTAT_DINT)) /*! @brief Format value for bitfield SDHC_IRQSTAT_DINT. */ #define BF_SDHC_IRQSTAT_DINT(v) ((uint32_t)((uint32_t)(v) << BP_SDHC_IRQSTAT_DINT) & BM_SDHC_IRQSTAT_DINT) /*! @brief Set the DINT field to a new value. */ #define BW_SDHC_IRQSTAT_DINT(x, v) (BITBAND_ACCESS32(HW_SDHC_IRQSTAT_ADDR(x), BP_SDHC_IRQSTAT_DINT) = (v)) /*@}*/ /*! * @name Register SDHC_IRQSTAT, field BWR[4] (W1C) * * This status bit is set if the Buffer Write Enable bit, in the Present State * register, changes from 0 to 1. See the Buffer Write Enable bit in the Present * State register for additional information. * * Values: * - 0 - Not ready to write buffer. * - 1 - Ready to write buffer. */ /*@{*/ #define BP_SDHC_IRQSTAT_BWR (4U) /*!< Bit position for SDHC_IRQSTAT_BWR. */ #define BM_SDHC_IRQSTAT_BWR (0x00000010U) /*!< Bit mask for SDHC_IRQSTAT_BWR. */ #define BS_SDHC_IRQSTAT_BWR (1U) /*!< Bit field size in bits for SDHC_IRQSTAT_BWR. */ /*! @brief Read current value of the SDHC_IRQSTAT_BWR field. */ #define BR_SDHC_IRQSTAT_BWR(x) (BITBAND_ACCESS32(HW_SDHC_IRQSTAT_ADDR(x), BP_SDHC_IRQSTAT_BWR)) /*! @brief Format value for bitfield SDHC_IRQSTAT_BWR. */ #define BF_SDHC_IRQSTAT_BWR(v) ((uint32_t)((uint32_t)(v) << BP_SDHC_IRQSTAT_BWR) & BM_SDHC_IRQSTAT_BWR) /*! @brief Set the BWR field to a new value. */ #define BW_SDHC_IRQSTAT_BWR(x, v) (BITBAND_ACCESS32(HW_SDHC_IRQSTAT_ADDR(x), BP_SDHC_IRQSTAT_BWR) = (v)) /*@}*/ /*! * @name Register SDHC_IRQSTAT, field BRR[5] (W1C) * * This status bit is set if the Buffer Read Enable bit, in the Present State * register, changes from 0 to 1. See the Buffer Read Enable bit in the Present * State register for additional information. * * Values: * - 0 - Not ready to read buffer. * - 1 - Ready to read buffer. */ /*@{*/ #define BP_SDHC_IRQSTAT_BRR (5U) /*!< Bit position for SDHC_IRQSTAT_BRR. */ #define BM_SDHC_IRQSTAT_BRR (0x00000020U) /*!< Bit mask for SDHC_IRQSTAT_BRR. */ #define BS_SDHC_IRQSTAT_BRR (1U) /*!< Bit field size in bits for SDHC_IRQSTAT_BRR. */ /*! @brief Read current value of the SDHC_IRQSTAT_BRR field. */ #define BR_SDHC_IRQSTAT_BRR(x) (BITBAND_ACCESS32(HW_SDHC_IRQSTAT_ADDR(x), BP_SDHC_IRQSTAT_BRR)) /*! @brief Format value for bitfield SDHC_IRQSTAT_BRR. */ #define BF_SDHC_IRQSTAT_BRR(v) ((uint32_t)((uint32_t)(v) << BP_SDHC_IRQSTAT_BRR) & BM_SDHC_IRQSTAT_BRR) /*! @brief Set the BRR field to a new value. */ #define BW_SDHC_IRQSTAT_BRR(x, v) (BITBAND_ACCESS32(HW_SDHC_IRQSTAT_ADDR(x), BP_SDHC_IRQSTAT_BRR) = (v)) /*@}*/ /*! * @name Register SDHC_IRQSTAT, field CINS[6] (W1C) * * This status bit is set if the Card Inserted bit in the Present State register * changes from 0 to 1. When the host driver writes this bit to 1 to clear this * status, the status of the Card Inserted in the Present State register must be * confirmed. Because the card state may possibly be changed when the host driver * clears this bit and the interrupt event may not be generated. When this bit * is cleared, it will be set again if a card is inserted. To leave it cleared, * clear the Card Inserted Status Enable bit in Interrupt Status Enable register. * * Values: * - 0 - Card state unstable or removed. * - 1 - Card inserted. */ /*@{*/ #define BP_SDHC_IRQSTAT_CINS (6U) /*!< Bit position for SDHC_IRQSTAT_CINS. */ #define BM_SDHC_IRQSTAT_CINS (0x00000040U) /*!< Bit mask for SDHC_IRQSTAT_CINS. */ #define BS_SDHC_IRQSTAT_CINS (1U) /*!< Bit field size in bits for SDHC_IRQSTAT_CINS. */ /*! @brief Read current value of the SDHC_IRQSTAT_CINS field. */ #define BR_SDHC_IRQSTAT_CINS(x) (BITBAND_ACCESS32(HW_SDHC_IRQSTAT_ADDR(x), BP_SDHC_IRQSTAT_CINS)) /*! @brief Format value for bitfield SDHC_IRQSTAT_CINS. */ #define BF_SDHC_IRQSTAT_CINS(v) ((uint32_t)((uint32_t)(v) << BP_SDHC_IRQSTAT_CINS) & BM_SDHC_IRQSTAT_CINS) /*! @brief Set the CINS field to a new value. */ #define BW_SDHC_IRQSTAT_CINS(x, v) (BITBAND_ACCESS32(HW_SDHC_IRQSTAT_ADDR(x), BP_SDHC_IRQSTAT_CINS) = (v)) /*@}*/ /*! * @name Register SDHC_IRQSTAT, field CRM[7] (W1C) * * This status bit is set if the Card Inserted bit in the Present State register * changes from 1 to 0. When the host driver writes this bit to 1 to clear this * status, the status of the Card Inserted in the Present State register must be * confirmed. Because the card state may possibly be changed when the host driver * clears this bit and the interrupt event may not be generated. When this bit * is cleared, it will be set again if no card is inserted. To leave it cleared, * clear the Card Removal Status Enable bit in Interrupt Status Enable register. * * Values: * - 0 - Card state unstable or inserted. * - 1 - Card removed. */ /*@{*/ #define BP_SDHC_IRQSTAT_CRM (7U) /*!< Bit position for SDHC_IRQSTAT_CRM. */ #define BM_SDHC_IRQSTAT_CRM (0x00000080U) /*!< Bit mask for SDHC_IRQSTAT_CRM. */ #define BS_SDHC_IRQSTAT_CRM (1U) /*!< Bit field size in bits for SDHC_IRQSTAT_CRM. */ /*! @brief Read current value of the SDHC_IRQSTAT_CRM field. */ #define BR_SDHC_IRQSTAT_CRM(x) (BITBAND_ACCESS32(HW_SDHC_IRQSTAT_ADDR(x), BP_SDHC_IRQSTAT_CRM)) /*! @brief Format value for bitfield SDHC_IRQSTAT_CRM. */ #define BF_SDHC_IRQSTAT_CRM(v) ((uint32_t)((uint32_t)(v) << BP_SDHC_IRQSTAT_CRM) & BM_SDHC_IRQSTAT_CRM) /*! @brief Set the CRM field to a new value. */ #define BW_SDHC_IRQSTAT_CRM(x, v) (BITBAND_ACCESS32(HW_SDHC_IRQSTAT_ADDR(x), BP_SDHC_IRQSTAT_CRM) = (v)) /*@}*/ /*! * @name Register SDHC_IRQSTAT, field CINT[8] (W1C) * * This status bit is set when an interrupt signal is detected from the external * card. In 1-bit mode, the SDHC will detect the Card Interrupt without the SD * Clock to support wakeup. In 4-bit mode, the card interrupt signal is sampled * during the interrupt cycle, so the interrupt from card can only be sampled * during interrupt cycle, introducing some delay between the interrupt signal from * the SDIO card and the interrupt to the host system. Writing this bit to 1 can * clear this bit, but as the interrupt factor from the SDIO card does not clear, * this bit is set again. To clear this bit, it is required to reset the interrupt * factor from the external card followed by a writing 1 to this bit. When this * status has been set, and the host driver needs to service this interrupt, the * Card Interrupt Signal Enable in the Interrupt Signal Enable register should be * 0 to stop driving the interrupt signal to the host system. After completion * of the card interrupt service (it must reset the interrupt factors in the SDIO * card and the interrupt signal may not be asserted), write 1 to clear this bit, * set the Card Interrupt Signal Enable to 1, and start sampling the interrupt * signal again. * * Values: * - 0 - No Card Interrupt. * - 1 - Generate Card Interrupt. */ /*@{*/ #define BP_SDHC_IRQSTAT_CINT (8U) /*!< Bit position for SDHC_IRQSTAT_CINT. */ #define BM_SDHC_IRQSTAT_CINT (0x00000100U) /*!< Bit mask for SDHC_IRQSTAT_CINT. */ #define BS_SDHC_IRQSTAT_CINT (1U) /*!< Bit field size in bits for SDHC_IRQSTAT_CINT. */ /*! @brief Read current value of the SDHC_IRQSTAT_CINT field. */ #define BR_SDHC_IRQSTAT_CINT(x) (BITBAND_ACCESS32(HW_SDHC_IRQSTAT_ADDR(x), BP_SDHC_IRQSTAT_CINT)) /*! @brief Format value for bitfield SDHC_IRQSTAT_CINT. */ #define BF_SDHC_IRQSTAT_CINT(v) ((uint32_t)((uint32_t)(v) << BP_SDHC_IRQSTAT_CINT) & BM_SDHC_IRQSTAT_CINT) /*! @brief Set the CINT field to a new value. */ #define BW_SDHC_IRQSTAT_CINT(x, v) (BITBAND_ACCESS32(HW_SDHC_IRQSTAT_ADDR(x), BP_SDHC_IRQSTAT_CINT) = (v)) /*@}*/ /*! * @name Register SDHC_IRQSTAT, field CTOE[16] (W1C) * * Occurs only if no response is returned within 64 SDCLK cycles from the end * bit of the command. If the SDHC detects a CMD line conflict, in which case a * Command CRC Error shall also be set, this bit shall be set without waiting for 64 * SDCLK cycles. This is because the command will be aborted by the SDHC. * * Values: * - 0 - No error. * - 1 - Time out. */ /*@{*/ #define BP_SDHC_IRQSTAT_CTOE (16U) /*!< Bit position for SDHC_IRQSTAT_CTOE. */ #define BM_SDHC_IRQSTAT_CTOE (0x00010000U) /*!< Bit mask for SDHC_IRQSTAT_CTOE. */ #define BS_SDHC_IRQSTAT_CTOE (1U) /*!< Bit field size in bits for SDHC_IRQSTAT_CTOE. */ /*! @brief Read current value of the SDHC_IRQSTAT_CTOE field. */ #define BR_SDHC_IRQSTAT_CTOE(x) (BITBAND_ACCESS32(HW_SDHC_IRQSTAT_ADDR(x), BP_SDHC_IRQSTAT_CTOE)) /*! @brief Format value for bitfield SDHC_IRQSTAT_CTOE. */ #define BF_SDHC_IRQSTAT_CTOE(v) ((uint32_t)((uint32_t)(v) << BP_SDHC_IRQSTAT_CTOE) & BM_SDHC_IRQSTAT_CTOE) /*! @brief Set the CTOE field to a new value. */ #define BW_SDHC_IRQSTAT_CTOE(x, v) (BITBAND_ACCESS32(HW_SDHC_IRQSTAT_ADDR(x), BP_SDHC_IRQSTAT_CTOE) = (v)) /*@}*/ /*! * @name Register SDHC_IRQSTAT, field CCE[17] (W1C) * * Command CRC Error is generated in two cases. If a response is returned and * the Command Timeout Error is set to 0, indicating no time-out, this bit is set * when detecting a CRC error in the command response. The SDHC detects a CMD line * conflict by monitoring the CMD line when a command is issued. If the SDHC * drives the CMD line to 1, but detects 0 on the CMD line at the next SDCLK edge, * then the SDHC shall abort the command (Stop driving CMD line) and set this bit * to 1. The Command Timeout Error shall also be set to 1 to distinguish CMD line * conflict. * * Values: * - 0 - No error. * - 1 - CRC Error generated. */ /*@{*/ #define BP_SDHC_IRQSTAT_CCE (17U) /*!< Bit position for SDHC_IRQSTAT_CCE. */ #define BM_SDHC_IRQSTAT_CCE (0x00020000U) /*!< Bit mask for SDHC_IRQSTAT_CCE. */ #define BS_SDHC_IRQSTAT_CCE (1U) /*!< Bit field size in bits for SDHC_IRQSTAT_CCE. */ /*! @brief Read current value of the SDHC_IRQSTAT_CCE field. */ #define BR_SDHC_IRQSTAT_CCE(x) (BITBAND_ACCESS32(HW_SDHC_IRQSTAT_ADDR(x), BP_SDHC_IRQSTAT_CCE)) /*! @brief Format value for bitfield SDHC_IRQSTAT_CCE. */ #define BF_SDHC_IRQSTAT_CCE(v) ((uint32_t)((uint32_t)(v) << BP_SDHC_IRQSTAT_CCE) & BM_SDHC_IRQSTAT_CCE) /*! @brief Set the CCE field to a new value. */ #define BW_SDHC_IRQSTAT_CCE(x, v) (BITBAND_ACCESS32(HW_SDHC_IRQSTAT_ADDR(x), BP_SDHC_IRQSTAT_CCE) = (v)) /*@}*/ /*! * @name Register SDHC_IRQSTAT, field CEBE[18] (W1C) * * Occurs when detecting that the end bit of a command response is 0. * * Values: * - 0 - No error. * - 1 - End Bit Error generated. */ /*@{*/ #define BP_SDHC_IRQSTAT_CEBE (18U) /*!< Bit position for SDHC_IRQSTAT_CEBE. */ #define BM_SDHC_IRQSTAT_CEBE (0x00040000U) /*!< Bit mask for SDHC_IRQSTAT_CEBE. */ #define BS_SDHC_IRQSTAT_CEBE (1U) /*!< Bit field size in bits for SDHC_IRQSTAT_CEBE. */ /*! @brief Read current value of the SDHC_IRQSTAT_CEBE field. */ #define BR_SDHC_IRQSTAT_CEBE(x) (BITBAND_ACCESS32(HW_SDHC_IRQSTAT_ADDR(x), BP_SDHC_IRQSTAT_CEBE)) /*! @brief Format value for bitfield SDHC_IRQSTAT_CEBE. */ #define BF_SDHC_IRQSTAT_CEBE(v) ((uint32_t)((uint32_t)(v) << BP_SDHC_IRQSTAT_CEBE) & BM_SDHC_IRQSTAT_CEBE) /*! @brief Set the CEBE field to a new value. */ #define BW_SDHC_IRQSTAT_CEBE(x, v) (BITBAND_ACCESS32(HW_SDHC_IRQSTAT_ADDR(x), BP_SDHC_IRQSTAT_CEBE) = (v)) /*@}*/ /*! * @name Register SDHC_IRQSTAT, field CIE[19] (W1C) * * Occurs if a Command Index error occurs in the command response. * * Values: * - 0 - No error. * - 1 - Error. */ /*@{*/ #define BP_SDHC_IRQSTAT_CIE (19U) /*!< Bit position for SDHC_IRQSTAT_CIE. */ #define BM_SDHC_IRQSTAT_CIE (0x00080000U) /*!< Bit mask for SDHC_IRQSTAT_CIE. */ #define BS_SDHC_IRQSTAT_CIE (1U) /*!< Bit field size in bits for SDHC_IRQSTAT_CIE. */ /*! @brief Read current value of the SDHC_IRQSTAT_CIE field. */ #define BR_SDHC_IRQSTAT_CIE(x) (BITBAND_ACCESS32(HW_SDHC_IRQSTAT_ADDR(x), BP_SDHC_IRQSTAT_CIE)) /*! @brief Format value for bitfield SDHC_IRQSTAT_CIE. */ #define BF_SDHC_IRQSTAT_CIE(v) ((uint32_t)((uint32_t)(v) << BP_SDHC_IRQSTAT_CIE) & BM_SDHC_IRQSTAT_CIE) /*! @brief Set the CIE field to a new value. */ #define BW_SDHC_IRQSTAT_CIE(x, v) (BITBAND_ACCESS32(HW_SDHC_IRQSTAT_ADDR(x), BP_SDHC_IRQSTAT_CIE) = (v)) /*@}*/ /*! * @name Register SDHC_IRQSTAT, field DTOE[20] (W1C) * * Occurs when detecting one of following time-out conditions. Busy time-out for * R1b,R5b type Busy time-out after Write CRC status Read Data time-out * * Values: * - 0 - No error. * - 1 - Time out. */ /*@{*/ #define BP_SDHC_IRQSTAT_DTOE (20U) /*!< Bit position for SDHC_IRQSTAT_DTOE. */ #define BM_SDHC_IRQSTAT_DTOE (0x00100000U) /*!< Bit mask for SDHC_IRQSTAT_DTOE. */ #define BS_SDHC_IRQSTAT_DTOE (1U) /*!< Bit field size in bits for SDHC_IRQSTAT_DTOE. */ /*! @brief Read current value of the SDHC_IRQSTAT_DTOE field. */ #define BR_SDHC_IRQSTAT_DTOE(x) (BITBAND_ACCESS32(HW_SDHC_IRQSTAT_ADDR(x), BP_SDHC_IRQSTAT_DTOE)) /*! @brief Format value for bitfield SDHC_IRQSTAT_DTOE. */ #define BF_SDHC_IRQSTAT_DTOE(v) ((uint32_t)((uint32_t)(v) << BP_SDHC_IRQSTAT_DTOE) & BM_SDHC_IRQSTAT_DTOE) /*! @brief Set the DTOE field to a new value. */ #define BW_SDHC_IRQSTAT_DTOE(x, v) (BITBAND_ACCESS32(HW_SDHC_IRQSTAT_ADDR(x), BP_SDHC_IRQSTAT_DTOE) = (v)) /*@}*/ /*! * @name Register SDHC_IRQSTAT, field DCE[21] (W1C) * * Occurs when detecting a CRC error when transferring read data, which uses the * DAT line, or when detecting the Write CRC status having a value other than * 010. * * Values: * - 0 - No error. * - 1 - Error. */ /*@{*/ #define BP_SDHC_IRQSTAT_DCE (21U) /*!< Bit position for SDHC_IRQSTAT_DCE. */ #define BM_SDHC_IRQSTAT_DCE (0x00200000U) /*!< Bit mask for SDHC_IRQSTAT_DCE. */ #define BS_SDHC_IRQSTAT_DCE (1U) /*!< Bit field size in bits for SDHC_IRQSTAT_DCE. */ /*! @brief Read current value of the SDHC_IRQSTAT_DCE field. */ #define BR_SDHC_IRQSTAT_DCE(x) (BITBAND_ACCESS32(HW_SDHC_IRQSTAT_ADDR(x), BP_SDHC_IRQSTAT_DCE)) /*! @brief Format value for bitfield SDHC_IRQSTAT_DCE. */ #define BF_SDHC_IRQSTAT_DCE(v) ((uint32_t)((uint32_t)(v) << BP_SDHC_IRQSTAT_DCE) & BM_SDHC_IRQSTAT_DCE) /*! @brief Set the DCE field to a new value. */ #define BW_SDHC_IRQSTAT_DCE(x, v) (BITBAND_ACCESS32(HW_SDHC_IRQSTAT_ADDR(x), BP_SDHC_IRQSTAT_DCE) = (v)) /*@}*/ /*! * @name Register SDHC_IRQSTAT, field DEBE[22] (W1C) * * Occurs either when detecting 0 at the end bit position of read data, which * uses the DAT line, or at the end bit position of the CRC. * * Values: * - 0 - No error. * - 1 - Error. */ /*@{*/ #define BP_SDHC_IRQSTAT_DEBE (22U) /*!< Bit position for SDHC_IRQSTAT_DEBE. */ #define BM_SDHC_IRQSTAT_DEBE (0x00400000U) /*!< Bit mask for SDHC_IRQSTAT_DEBE. */ #define BS_SDHC_IRQSTAT_DEBE (1U) /*!< Bit field size in bits for SDHC_IRQSTAT_DEBE. */ /*! @brief Read current value of the SDHC_IRQSTAT_DEBE field. */ #define BR_SDHC_IRQSTAT_DEBE(x) (BITBAND_ACCESS32(HW_SDHC_IRQSTAT_ADDR(x), BP_SDHC_IRQSTAT_DEBE)) /*! @brief Format value for bitfield SDHC_IRQSTAT_DEBE. */ #define BF_SDHC_IRQSTAT_DEBE(v) ((uint32_t)((uint32_t)(v) << BP_SDHC_IRQSTAT_DEBE) & BM_SDHC_IRQSTAT_DEBE) /*! @brief Set the DEBE field to a new value. */ #define BW_SDHC_IRQSTAT_DEBE(x, v) (BITBAND_ACCESS32(HW_SDHC_IRQSTAT_ADDR(x), BP_SDHC_IRQSTAT_DEBE) = (v)) /*@}*/ /*! * @name Register SDHC_IRQSTAT, field AC12E[24] (W1C) * * Occurs when detecting that one of the bits in the Auto CMD12 Error Status * register has changed from 0 to 1. This bit is set to 1, not only when the errors * in Auto CMD12 occur, but also when the Auto CMD12 is not executed due to the * previous command error. * * Values: * - 0 - No error. * - 1 - Error. */ /*@{*/ #define BP_SDHC_IRQSTAT_AC12E (24U) /*!< Bit position for SDHC_IRQSTAT_AC12E. */ #define BM_SDHC_IRQSTAT_AC12E (0x01000000U) /*!< Bit mask for SDHC_IRQSTAT_AC12E. */ #define BS_SDHC_IRQSTAT_AC12E (1U) /*!< Bit field size in bits for SDHC_IRQSTAT_AC12E. */ /*! @brief Read current value of the SDHC_IRQSTAT_AC12E field. */ #define BR_SDHC_IRQSTAT_AC12E(x) (BITBAND_ACCESS32(HW_SDHC_IRQSTAT_ADDR(x), BP_SDHC_IRQSTAT_AC12E)) /*! @brief Format value for bitfield SDHC_IRQSTAT_AC12E. */ #define BF_SDHC_IRQSTAT_AC12E(v) ((uint32_t)((uint32_t)(v) << BP_SDHC_IRQSTAT_AC12E) & BM_SDHC_IRQSTAT_AC12E) /*! @brief Set the AC12E field to a new value. */ #define BW_SDHC_IRQSTAT_AC12E(x, v) (BITBAND_ACCESS32(HW_SDHC_IRQSTAT_ADDR(x), BP_SDHC_IRQSTAT_AC12E) = (v)) /*@}*/ /*! * @name Register SDHC_IRQSTAT, field DMAE[28] (W1C) * * Occurs when an Internal DMA transfer has failed. This bit is set to 1, when * some error occurs in the data transfer. This error can be caused by either * Simple DMA or ADMA, depending on which DMA is in use. The value in DMA System * Address register is the next fetch address where the error occurs. Because any * error corrupts the whole data block, the host driver shall restart the transfer * from the corrupted block boundary. The address of the block boundary can be * calculated either from the current DSADDR value or from the remaining number of * blocks and the block size. * * Values: * - 0 - No error. * - 1 - Error. */ /*@{*/ #define BP_SDHC_IRQSTAT_DMAE (28U) /*!< Bit position for SDHC_IRQSTAT_DMAE. */ #define BM_SDHC_IRQSTAT_DMAE (0x10000000U) /*!< Bit mask for SDHC_IRQSTAT_DMAE. */ #define BS_SDHC_IRQSTAT_DMAE (1U) /*!< Bit field size in bits for SDHC_IRQSTAT_DMAE. */ /*! @brief Read current value of the SDHC_IRQSTAT_DMAE field. */ #define BR_SDHC_IRQSTAT_DMAE(x) (BITBAND_ACCESS32(HW_SDHC_IRQSTAT_ADDR(x), BP_SDHC_IRQSTAT_DMAE)) /*! @brief Format value for bitfield SDHC_IRQSTAT_DMAE. */ #define BF_SDHC_IRQSTAT_DMAE(v) ((uint32_t)((uint32_t)(v) << BP_SDHC_IRQSTAT_DMAE) & BM_SDHC_IRQSTAT_DMAE) /*! @brief Set the DMAE field to a new value. */ #define BW_SDHC_IRQSTAT_DMAE(x, v) (BITBAND_ACCESS32(HW_SDHC_IRQSTAT_ADDR(x), BP_SDHC_IRQSTAT_DMAE) = (v)) /*@}*/ /******************************************************************************* * HW_SDHC_IRQSTATEN - Interrupt Status Enable register ******************************************************************************/ /*! * @brief HW_SDHC_IRQSTATEN - Interrupt Status Enable register (RW) * * Reset value: 0x117F013FU * * Setting the bits in this register to 1 enables the corresponding interrupt * status to be set by the specified event. If any bit is cleared, the * corresponding interrupt status bit is also cleared, that is, when the bit in this register * is cleared, the corresponding bit in interrupt status register is always 0. * Depending on PROCTL[IABG] bit setting, SDHC may be programmed to sample the * card interrupt signal during the interrupt period and hold its value in the * flip-flop. There will be some delays on the card interrupt, asserted from the card, * to the time the host system is informed. To detect a CMD line conflict, the * host driver must set both IRQSTATEN[CTOESEN] and IRQSTATEN[CCESEN] to 1. */ typedef union _hw_sdhc_irqstaten { uint32_t U; struct _hw_sdhc_irqstaten_bitfields { uint32_t CCSEN : 1; /*!< [0] Command Complete Status Enable */ uint32_t TCSEN : 1; /*!< [1] Transfer Complete Status Enable */ uint32_t BGESEN : 1; /*!< [2] Block Gap Event Status Enable */ uint32_t DINTSEN : 1; /*!< [3] DMA Interrupt Status Enable */ uint32_t BWRSEN : 1; /*!< [4] Buffer Write Ready Status Enable */ uint32_t BRRSEN : 1; /*!< [5] Buffer Read Ready Status Enable */ uint32_t CINSEN : 1; /*!< [6] Card Insertion Status Enable */ uint32_t CRMSEN : 1; /*!< [7] Card Removal Status Enable */ uint32_t CINTSEN : 1; /*!< [8] Card Interrupt Status Enable */ uint32_t RESERVED0 : 7; /*!< [15:9] */ uint32_t CTOESEN : 1; /*!< [16] Command Timeout Error Status Enable */ uint32_t CCESEN : 1; /*!< [17] Command CRC Error Status Enable */ uint32_t CEBESEN : 1; /*!< [18] Command End Bit Error Status Enable */ uint32_t CIESEN : 1; /*!< [19] Command Index Error Status Enable */ uint32_t DTOESEN : 1; /*!< [20] Data Timeout Error Status Enable */ uint32_t DCESEN : 1; /*!< [21] Data CRC Error Status Enable */ uint32_t DEBESEN : 1; /*!< [22] Data End Bit Error Status Enable */ uint32_t RESERVED1 : 1; /*!< [23] */ uint32_t AC12ESEN : 1; /*!< [24] Auto CMD12 Error Status Enable */ uint32_t RESERVED2 : 3; /*!< [27:25] */ uint32_t DMAESEN : 1; /*!< [28] DMA Error Status Enable */ uint32_t RESERVED3 : 3; /*!< [31:29] */ } B; } hw_sdhc_irqstaten_t; /*! * @name Constants and macros for entire SDHC_IRQSTATEN register */ /*@{*/ #define HW_SDHC_IRQSTATEN_ADDR(x) ((x) + 0x34U) #define HW_SDHC_IRQSTATEN(x) (*(__IO hw_sdhc_irqstaten_t *) HW_SDHC_IRQSTATEN_ADDR(x)) #define HW_SDHC_IRQSTATEN_RD(x) (HW_SDHC_IRQSTATEN(x).U) #define HW_SDHC_IRQSTATEN_WR(x, v) (HW_SDHC_IRQSTATEN(x).U = (v)) #define HW_SDHC_IRQSTATEN_SET(x, v) (HW_SDHC_IRQSTATEN_WR(x, HW_SDHC_IRQSTATEN_RD(x) | (v))) #define HW_SDHC_IRQSTATEN_CLR(x, v) (HW_SDHC_IRQSTATEN_WR(x, HW_SDHC_IRQSTATEN_RD(x) & ~(v))) #define HW_SDHC_IRQSTATEN_TOG(x, v) (HW_SDHC_IRQSTATEN_WR(x, HW_SDHC_IRQSTATEN_RD(x) ^ (v))) /*@}*/ /* * Constants & macros for individual SDHC_IRQSTATEN bitfields */ /*! * @name Register SDHC_IRQSTATEN, field CCSEN[0] (RW) * * Values: * - 0 - Masked * - 1 - Enabled */ /*@{*/ #define BP_SDHC_IRQSTATEN_CCSEN (0U) /*!< Bit position for SDHC_IRQSTATEN_CCSEN. */ #define BM_SDHC_IRQSTATEN_CCSEN (0x00000001U) /*!< Bit mask for SDHC_IRQSTATEN_CCSEN. */ #define BS_SDHC_IRQSTATEN_CCSEN (1U) /*!< Bit field size in bits for SDHC_IRQSTATEN_CCSEN. */ /*! @brief Read current value of the SDHC_IRQSTATEN_CCSEN field. */ #define BR_SDHC_IRQSTATEN_CCSEN(x) (BITBAND_ACCESS32(HW_SDHC_IRQSTATEN_ADDR(x), BP_SDHC_IRQSTATEN_CCSEN)) /*! @brief Format value for bitfield SDHC_IRQSTATEN_CCSEN. */ #define BF_SDHC_IRQSTATEN_CCSEN(v) ((uint32_t)((uint32_t)(v) << BP_SDHC_IRQSTATEN_CCSEN) & BM_SDHC_IRQSTATEN_CCSEN) /*! @brief Set the CCSEN field to a new value. */ #define BW_SDHC_IRQSTATEN_CCSEN(x, v) (BITBAND_ACCESS32(HW_SDHC_IRQSTATEN_ADDR(x), BP_SDHC_IRQSTATEN_CCSEN) = (v)) /*@}*/ /*! * @name Register SDHC_IRQSTATEN, field TCSEN[1] (RW) * * Values: * - 0 - Masked * - 1 - Enabled */ /*@{*/ #define BP_SDHC_IRQSTATEN_TCSEN (1U) /*!< Bit position for SDHC_IRQSTATEN_TCSEN. */ #define BM_SDHC_IRQSTATEN_TCSEN (0x00000002U) /*!< Bit mask for SDHC_IRQSTATEN_TCSEN. */ #define BS_SDHC_IRQSTATEN_TCSEN (1U) /*!< Bit field size in bits for SDHC_IRQSTATEN_TCSEN. */ /*! @brief Read current value of the SDHC_IRQSTATEN_TCSEN field. */ #define BR_SDHC_IRQSTATEN_TCSEN(x) (BITBAND_ACCESS32(HW_SDHC_IRQSTATEN_ADDR(x), BP_SDHC_IRQSTATEN_TCSEN)) /*! @brief Format value for bitfield SDHC_IRQSTATEN_TCSEN. */ #define BF_SDHC_IRQSTATEN_TCSEN(v) ((uint32_t)((uint32_t)(v) << BP_SDHC_IRQSTATEN_TCSEN) & BM_SDHC_IRQSTATEN_TCSEN) /*! @brief Set the TCSEN field to a new value. */ #define BW_SDHC_IRQSTATEN_TCSEN(x, v) (BITBAND_ACCESS32(HW_SDHC_IRQSTATEN_ADDR(x), BP_SDHC_IRQSTATEN_TCSEN) = (v)) /*@}*/ /*! * @name Register SDHC_IRQSTATEN, field BGESEN[2] (RW) * * Values: * - 0 - Masked * - 1 - Enabled */ /*@{*/ #define BP_SDHC_IRQSTATEN_BGESEN (2U) /*!< Bit position for SDHC_IRQSTATEN_BGESEN. */ #define BM_SDHC_IRQSTATEN_BGESEN (0x00000004U) /*!< Bit mask for SDHC_IRQSTATEN_BGESEN. */ #define BS_SDHC_IRQSTATEN_BGESEN (1U) /*!< Bit field size in bits for SDHC_IRQSTATEN_BGESEN. */ /*! @brief Read current value of the SDHC_IRQSTATEN_BGESEN field. */ #define BR_SDHC_IRQSTATEN_BGESEN(x) (BITBAND_ACCESS32(HW_SDHC_IRQSTATEN_ADDR(x), BP_SDHC_IRQSTATEN_BGESEN)) /*! @brief Format value for bitfield SDHC_IRQSTATEN_BGESEN. */ #define BF_SDHC_IRQSTATEN_BGESEN(v) ((uint32_t)((uint32_t)(v) << BP_SDHC_IRQSTATEN_BGESEN) & BM_SDHC_IRQSTATEN_BGESEN) /*! @brief Set the BGESEN field to a new value. */ #define BW_SDHC_IRQSTATEN_BGESEN(x, v) (BITBAND_ACCESS32(HW_SDHC_IRQSTATEN_ADDR(x), BP_SDHC_IRQSTATEN_BGESEN) = (v)) /*@}*/ /*! * @name Register SDHC_IRQSTATEN, field DINTSEN[3] (RW) * * Values: * - 0 - Masked * - 1 - Enabled */ /*@{*/ #define BP_SDHC_IRQSTATEN_DINTSEN (3U) /*!< Bit position for SDHC_IRQSTATEN_DINTSEN. */ #define BM_SDHC_IRQSTATEN_DINTSEN (0x00000008U) /*!< Bit mask for SDHC_IRQSTATEN_DINTSEN. */ #define BS_SDHC_IRQSTATEN_DINTSEN (1U) /*!< Bit field size in bits for SDHC_IRQSTATEN_DINTSEN. */ /*! @brief Read current value of the SDHC_IRQSTATEN_DINTSEN field. */ #define BR_SDHC_IRQSTATEN_DINTSEN(x) (BITBAND_ACCESS32(HW_SDHC_IRQSTATEN_ADDR(x), BP_SDHC_IRQSTATEN_DINTSEN)) /*! @brief Format value for bitfield SDHC_IRQSTATEN_DINTSEN. */ #define BF_SDHC_IRQSTATEN_DINTSEN(v) ((uint32_t)((uint32_t)(v) << BP_SDHC_IRQSTATEN_DINTSEN) & BM_SDHC_IRQSTATEN_DINTSEN) /*! @brief Set the DINTSEN field to a new value. */ #define BW_SDHC_IRQSTATEN_DINTSEN(x, v) (BITBAND_ACCESS32(HW_SDHC_IRQSTATEN_ADDR(x), BP_SDHC_IRQSTATEN_DINTSEN) = (v)) /*@}*/ /*! * @name Register SDHC_IRQSTATEN, field BWRSEN[4] (RW) * * Values: * - 0 - Masked * - 1 - Enabled */ /*@{*/ #define BP_SDHC_IRQSTATEN_BWRSEN (4U) /*!< Bit position for SDHC_IRQSTATEN_BWRSEN. */ #define BM_SDHC_IRQSTATEN_BWRSEN (0x00000010U) /*!< Bit mask for SDHC_IRQSTATEN_BWRSEN. */ #define BS_SDHC_IRQSTATEN_BWRSEN (1U) /*!< Bit field size in bits for SDHC_IRQSTATEN_BWRSEN. */ /*! @brief Read current value of the SDHC_IRQSTATEN_BWRSEN field. */ #define BR_SDHC_IRQSTATEN_BWRSEN(x) (BITBAND_ACCESS32(HW_SDHC_IRQSTATEN_ADDR(x), BP_SDHC_IRQSTATEN_BWRSEN)) /*! @brief Format value for bitfield SDHC_IRQSTATEN_BWRSEN. */ #define BF_SDHC_IRQSTATEN_BWRSEN(v) ((uint32_t)((uint32_t)(v) << BP_SDHC_IRQSTATEN_BWRSEN) & BM_SDHC_IRQSTATEN_BWRSEN) /*! @brief Set the BWRSEN field to a new value. */ #define BW_SDHC_IRQSTATEN_BWRSEN(x, v) (BITBAND_ACCESS32(HW_SDHC_IRQSTATEN_ADDR(x), BP_SDHC_IRQSTATEN_BWRSEN) = (v)) /*@}*/ /*! * @name Register SDHC_IRQSTATEN, field BRRSEN[5] (RW) * * Values: * - 0 - Masked * - 1 - Enabled */ /*@{*/ #define BP_SDHC_IRQSTATEN_BRRSEN (5U) /*!< Bit position for SDHC_IRQSTATEN_BRRSEN. */ #define BM_SDHC_IRQSTATEN_BRRSEN (0x00000020U) /*!< Bit mask for SDHC_IRQSTATEN_BRRSEN. */ #define BS_SDHC_IRQSTATEN_BRRSEN (1U) /*!< Bit field size in bits for SDHC_IRQSTATEN_BRRSEN. */ /*! @brief Read current value of the SDHC_IRQSTATEN_BRRSEN field. */ #define BR_SDHC_IRQSTATEN_BRRSEN(x) (BITBAND_ACCESS32(HW_SDHC_IRQSTATEN_ADDR(x), BP_SDHC_IRQSTATEN_BRRSEN)) /*! @brief Format value for bitfield SDHC_IRQSTATEN_BRRSEN. */ #define BF_SDHC_IRQSTATEN_BRRSEN(v) ((uint32_t)((uint32_t)(v) << BP_SDHC_IRQSTATEN_BRRSEN) & BM_SDHC_IRQSTATEN_BRRSEN) /*! @brief Set the BRRSEN field to a new value. */ #define BW_SDHC_IRQSTATEN_BRRSEN(x, v) (BITBAND_ACCESS32(HW_SDHC_IRQSTATEN_ADDR(x), BP_SDHC_IRQSTATEN_BRRSEN) = (v)) /*@}*/ /*! * @name Register SDHC_IRQSTATEN, field CINSEN[6] (RW) * * Values: * - 0 - Masked * - 1 - Enabled */ /*@{*/ #define BP_SDHC_IRQSTATEN_CINSEN (6U) /*!< Bit position for SDHC_IRQSTATEN_CINSEN. */ #define BM_SDHC_IRQSTATEN_CINSEN (0x00000040U) /*!< Bit mask for SDHC_IRQSTATEN_CINSEN. */ #define BS_SDHC_IRQSTATEN_CINSEN (1U) /*!< Bit field size in bits for SDHC_IRQSTATEN_CINSEN. */ /*! @brief Read current value of the SDHC_IRQSTATEN_CINSEN field. */ #define BR_SDHC_IRQSTATEN_CINSEN(x) (BITBAND_ACCESS32(HW_SDHC_IRQSTATEN_ADDR(x), BP_SDHC_IRQSTATEN_CINSEN)) /*! @brief Format value for bitfield SDHC_IRQSTATEN_CINSEN. */ #define BF_SDHC_IRQSTATEN_CINSEN(v) ((uint32_t)((uint32_t)(v) << BP_SDHC_IRQSTATEN_CINSEN) & BM_SDHC_IRQSTATEN_CINSEN) /*! @brief Set the CINSEN field to a new value. */ #define BW_SDHC_IRQSTATEN_CINSEN(x, v) (BITBAND_ACCESS32(HW_SDHC_IRQSTATEN_ADDR(x), BP_SDHC_IRQSTATEN_CINSEN) = (v)) /*@}*/ /*! * @name Register SDHC_IRQSTATEN, field CRMSEN[7] (RW) * * Values: * - 0 - Masked * - 1 - Enabled */ /*@{*/ #define BP_SDHC_IRQSTATEN_CRMSEN (7U) /*!< Bit position for SDHC_IRQSTATEN_CRMSEN. */ #define BM_SDHC_IRQSTATEN_CRMSEN (0x00000080U) /*!< Bit mask for SDHC_IRQSTATEN_CRMSEN. */ #define BS_SDHC_IRQSTATEN_CRMSEN (1U) /*!< Bit field size in bits for SDHC_IRQSTATEN_CRMSEN. */ /*! @brief Read current value of the SDHC_IRQSTATEN_CRMSEN field. */ #define BR_SDHC_IRQSTATEN_CRMSEN(x) (BITBAND_ACCESS32(HW_SDHC_IRQSTATEN_ADDR(x), BP_SDHC_IRQSTATEN_CRMSEN)) /*! @brief Format value for bitfield SDHC_IRQSTATEN_CRMSEN. */ #define BF_SDHC_IRQSTATEN_CRMSEN(v) ((uint32_t)((uint32_t)(v) << BP_SDHC_IRQSTATEN_CRMSEN) & BM_SDHC_IRQSTATEN_CRMSEN) /*! @brief Set the CRMSEN field to a new value. */ #define BW_SDHC_IRQSTATEN_CRMSEN(x, v) (BITBAND_ACCESS32(HW_SDHC_IRQSTATEN_ADDR(x), BP_SDHC_IRQSTATEN_CRMSEN) = (v)) /*@}*/ /*! * @name Register SDHC_IRQSTATEN, field CINTSEN[8] (RW) * * If this bit is set to 0, the SDHC will clear the interrupt request to the * system. The card interrupt detection is stopped when this bit is cleared and * restarted when this bit is set to 1. The host driver must clear the this bit * before servicing the card interrupt and must set this bit again after all interrupt * requests from the card are cleared to prevent inadvertent interrupts. * * Values: * - 0 - Masked * - 1 - Enabled */ /*@{*/ #define BP_SDHC_IRQSTATEN_CINTSEN (8U) /*!< Bit position for SDHC_IRQSTATEN_CINTSEN. */ #define BM_SDHC_IRQSTATEN_CINTSEN (0x00000100U) /*!< Bit mask for SDHC_IRQSTATEN_CINTSEN. */ #define BS_SDHC_IRQSTATEN_CINTSEN (1U) /*!< Bit field size in bits for SDHC_IRQSTATEN_CINTSEN. */ /*! @brief Read current value of the SDHC_IRQSTATEN_CINTSEN field. */ #define BR_SDHC_IRQSTATEN_CINTSEN(x) (BITBAND_ACCESS32(HW_SDHC_IRQSTATEN_ADDR(x), BP_SDHC_IRQSTATEN_CINTSEN)) /*! @brief Format value for bitfield SDHC_IRQSTATEN_CINTSEN. */ #define BF_SDHC_IRQSTATEN_CINTSEN(v) ((uint32_t)((uint32_t)(v) << BP_SDHC_IRQSTATEN_CINTSEN) & BM_SDHC_IRQSTATEN_CINTSEN) /*! @brief Set the CINTSEN field to a new value. */ #define BW_SDHC_IRQSTATEN_CINTSEN(x, v) (BITBAND_ACCESS32(HW_SDHC_IRQSTATEN_ADDR(x), BP_SDHC_IRQSTATEN_CINTSEN) = (v)) /*@}*/ /*! * @name Register SDHC_IRQSTATEN, field CTOESEN[16] (RW) * * Values: * - 0 - Masked * - 1 - Enabled */ /*@{*/ #define BP_SDHC_IRQSTATEN_CTOESEN (16U) /*!< Bit position for SDHC_IRQSTATEN_CTOESEN. */ #define BM_SDHC_IRQSTATEN_CTOESEN (0x00010000U) /*!< Bit mask for SDHC_IRQSTATEN_CTOESEN. */ #define BS_SDHC_IRQSTATEN_CTOESEN (1U) /*!< Bit field size in bits for SDHC_IRQSTATEN_CTOESEN. */ /*! @brief Read current value of the SDHC_IRQSTATEN_CTOESEN field. */ #define BR_SDHC_IRQSTATEN_CTOESEN(x) (BITBAND_ACCESS32(HW_SDHC_IRQSTATEN_ADDR(x), BP_SDHC_IRQSTATEN_CTOESEN)) /*! @brief Format value for bitfield SDHC_IRQSTATEN_CTOESEN. */ #define BF_SDHC_IRQSTATEN_CTOESEN(v) ((uint32_t)((uint32_t)(v) << BP_SDHC_IRQSTATEN_CTOESEN) & BM_SDHC_IRQSTATEN_CTOESEN) /*! @brief Set the CTOESEN field to a new value. */ #define BW_SDHC_IRQSTATEN_CTOESEN(x, v) (BITBAND_ACCESS32(HW_SDHC_IRQSTATEN_ADDR(x), BP_SDHC_IRQSTATEN_CTOESEN) = (v)) /*@}*/ /*! * @name Register SDHC_IRQSTATEN, field CCESEN[17] (RW) * * Values: * - 0 - Masked * - 1 - Enabled */ /*@{*/ #define BP_SDHC_IRQSTATEN_CCESEN (17U) /*!< Bit position for SDHC_IRQSTATEN_CCESEN. */ #define BM_SDHC_IRQSTATEN_CCESEN (0x00020000U) /*!< Bit mask for SDHC_IRQSTATEN_CCESEN. */ #define BS_SDHC_IRQSTATEN_CCESEN (1U) /*!< Bit field size in bits for SDHC_IRQSTATEN_CCESEN. */ /*! @brief Read current value of the SDHC_IRQSTATEN_CCESEN field. */ #define BR_SDHC_IRQSTATEN_CCESEN(x) (BITBAND_ACCESS32(HW_SDHC_IRQSTATEN_ADDR(x), BP_SDHC_IRQSTATEN_CCESEN)) /*! @brief Format value for bitfield SDHC_IRQSTATEN_CCESEN. */ #define BF_SDHC_IRQSTATEN_CCESEN(v) ((uint32_t)((uint32_t)(v) << BP_SDHC_IRQSTATEN_CCESEN) & BM_SDHC_IRQSTATEN_CCESEN) /*! @brief Set the CCESEN field to a new value. */ #define BW_SDHC_IRQSTATEN_CCESEN(x, v) (BITBAND_ACCESS32(HW_SDHC_IRQSTATEN_ADDR(x), BP_SDHC_IRQSTATEN_CCESEN) = (v)) /*@}*/ /*! * @name Register SDHC_IRQSTATEN, field CEBESEN[18] (RW) * * Values: * - 0 - Masked * - 1 - Enabled */ /*@{*/ #define BP_SDHC_IRQSTATEN_CEBESEN (18U) /*!< Bit position for SDHC_IRQSTATEN_CEBESEN. */ #define BM_SDHC_IRQSTATEN_CEBESEN (0x00040000U) /*!< Bit mask for SDHC_IRQSTATEN_CEBESEN. */ #define BS_SDHC_IRQSTATEN_CEBESEN (1U) /*!< Bit field size in bits for SDHC_IRQSTATEN_CEBESEN. */ /*! @brief Read current value of the SDHC_IRQSTATEN_CEBESEN field. */ #define BR_SDHC_IRQSTATEN_CEBESEN(x) (BITBAND_ACCESS32(HW_SDHC_IRQSTATEN_ADDR(x), BP_SDHC_IRQSTATEN_CEBESEN)) /*! @brief Format value for bitfield SDHC_IRQSTATEN_CEBESEN. */ #define BF_SDHC_IRQSTATEN_CEBESEN(v) ((uint32_t)((uint32_t)(v) << BP_SDHC_IRQSTATEN_CEBESEN) & BM_SDHC_IRQSTATEN_CEBESEN) /*! @brief Set the CEBESEN field to a new value. */ #define BW_SDHC_IRQSTATEN_CEBESEN(x, v) (BITBAND_ACCESS32(HW_SDHC_IRQSTATEN_ADDR(x), BP_SDHC_IRQSTATEN_CEBESEN) = (v)) /*@}*/ /*! * @name Register SDHC_IRQSTATEN, field CIESEN[19] (RW) * * Values: * - 0 - Masked * - 1 - Enabled */ /*@{*/ #define BP_SDHC_IRQSTATEN_CIESEN (19U) /*!< Bit position for SDHC_IRQSTATEN_CIESEN. */ #define BM_SDHC_IRQSTATEN_CIESEN (0x00080000U) /*!< Bit mask for SDHC_IRQSTATEN_CIESEN. */ #define BS_SDHC_IRQSTATEN_CIESEN (1U) /*!< Bit field size in bits for SDHC_IRQSTATEN_CIESEN. */ /*! @brief Read current value of the SDHC_IRQSTATEN_CIESEN field. */ #define BR_SDHC_IRQSTATEN_CIESEN(x) (BITBAND_ACCESS32(HW_SDHC_IRQSTATEN_ADDR(x), BP_SDHC_IRQSTATEN_CIESEN)) /*! @brief Format value for bitfield SDHC_IRQSTATEN_CIESEN. */ #define BF_SDHC_IRQSTATEN_CIESEN(v) ((uint32_t)((uint32_t)(v) << BP_SDHC_IRQSTATEN_CIESEN) & BM_SDHC_IRQSTATEN_CIESEN) /*! @brief Set the CIESEN field to a new value. */ #define BW_SDHC_IRQSTATEN_CIESEN(x, v) (BITBAND_ACCESS32(HW_SDHC_IRQSTATEN_ADDR(x), BP_SDHC_IRQSTATEN_CIESEN) = (v)) /*@}*/ /*! * @name Register SDHC_IRQSTATEN, field DTOESEN[20] (RW) * * Values: * - 0 - Masked * - 1 - Enabled */ /*@{*/ #define BP_SDHC_IRQSTATEN_DTOESEN (20U) /*!< Bit position for SDHC_IRQSTATEN_DTOESEN. */ #define BM_SDHC_IRQSTATEN_DTOESEN (0x00100000U) /*!< Bit mask for SDHC_IRQSTATEN_DTOESEN. */ #define BS_SDHC_IRQSTATEN_DTOESEN (1U) /*!< Bit field size in bits for SDHC_IRQSTATEN_DTOESEN. */ /*! @brief Read current value of the SDHC_IRQSTATEN_DTOESEN field. */ #define BR_SDHC_IRQSTATEN_DTOESEN(x) (BITBAND_ACCESS32(HW_SDHC_IRQSTATEN_ADDR(x), BP_SDHC_IRQSTATEN_DTOESEN)) /*! @brief Format value for bitfield SDHC_IRQSTATEN_DTOESEN. */ #define BF_SDHC_IRQSTATEN_DTOESEN(v) ((uint32_t)((uint32_t)(v) << BP_SDHC_IRQSTATEN_DTOESEN) & BM_SDHC_IRQSTATEN_DTOESEN) /*! @brief Set the DTOESEN field to a new value. */ #define BW_SDHC_IRQSTATEN_DTOESEN(x, v) (BITBAND_ACCESS32(HW_SDHC_IRQSTATEN_ADDR(x), BP_SDHC_IRQSTATEN_DTOESEN) = (v)) /*@}*/ /*! * @name Register SDHC_IRQSTATEN, field DCESEN[21] (RW) * * Values: * - 0 - Masked * - 1 - Enabled */ /*@{*/ #define BP_SDHC_IRQSTATEN_DCESEN (21U) /*!< Bit position for SDHC_IRQSTATEN_DCESEN. */ #define BM_SDHC_IRQSTATEN_DCESEN (0x00200000U) /*!< Bit mask for SDHC_IRQSTATEN_DCESEN. */ #define BS_SDHC_IRQSTATEN_DCESEN (1U) /*!< Bit field size in bits for SDHC_IRQSTATEN_DCESEN. */ /*! @brief Read current value of the SDHC_IRQSTATEN_DCESEN field. */ #define BR_SDHC_IRQSTATEN_DCESEN(x) (BITBAND_ACCESS32(HW_SDHC_IRQSTATEN_ADDR(x), BP_SDHC_IRQSTATEN_DCESEN)) /*! @brief Format value for bitfield SDHC_IRQSTATEN_DCESEN. */ #define BF_SDHC_IRQSTATEN_DCESEN(v) ((uint32_t)((uint32_t)(v) << BP_SDHC_IRQSTATEN_DCESEN) & BM_SDHC_IRQSTATEN_DCESEN) /*! @brief Set the DCESEN field to a new value. */ #define BW_SDHC_IRQSTATEN_DCESEN(x, v) (BITBAND_ACCESS32(HW_SDHC_IRQSTATEN_ADDR(x), BP_SDHC_IRQSTATEN_DCESEN) = (v)) /*@}*/ /*! * @name Register SDHC_IRQSTATEN, field DEBESEN[22] (RW) * * Values: * - 0 - Masked * - 1 - Enabled */ /*@{*/ #define BP_SDHC_IRQSTATEN_DEBESEN (22U) /*!< Bit position for SDHC_IRQSTATEN_DEBESEN. */ #define BM_SDHC_IRQSTATEN_DEBESEN (0x00400000U) /*!< Bit mask for SDHC_IRQSTATEN_DEBESEN. */ #define BS_SDHC_IRQSTATEN_DEBESEN (1U) /*!< Bit field size in bits for SDHC_IRQSTATEN_DEBESEN. */ /*! @brief Read current value of the SDHC_IRQSTATEN_DEBESEN field. */ #define BR_SDHC_IRQSTATEN_DEBESEN(x) (BITBAND_ACCESS32(HW_SDHC_IRQSTATEN_ADDR(x), BP_SDHC_IRQSTATEN_DEBESEN)) /*! @brief Format value for bitfield SDHC_IRQSTATEN_DEBESEN. */ #define BF_SDHC_IRQSTATEN_DEBESEN(v) ((uint32_t)((uint32_t)(v) << BP_SDHC_IRQSTATEN_DEBESEN) & BM_SDHC_IRQSTATEN_DEBESEN) /*! @brief Set the DEBESEN field to a new value. */ #define BW_SDHC_IRQSTATEN_DEBESEN(x, v) (BITBAND_ACCESS32(HW_SDHC_IRQSTATEN_ADDR(x), BP_SDHC_IRQSTATEN_DEBESEN) = (v)) /*@}*/ /*! * @name Register SDHC_IRQSTATEN, field AC12ESEN[24] (RW) * * Values: * - 0 - Masked * - 1 - Enabled */ /*@{*/ #define BP_SDHC_IRQSTATEN_AC12ESEN (24U) /*!< Bit position for SDHC_IRQSTATEN_AC12ESEN. */ #define BM_SDHC_IRQSTATEN_AC12ESEN (0x01000000U) /*!< Bit mask for SDHC_IRQSTATEN_AC12ESEN. */ #define BS_SDHC_IRQSTATEN_AC12ESEN (1U) /*!< Bit field size in bits for SDHC_IRQSTATEN_AC12ESEN. */ /*! @brief Read current value of the SDHC_IRQSTATEN_AC12ESEN field. */ #define BR_SDHC_IRQSTATEN_AC12ESEN(x) (BITBAND_ACCESS32(HW_SDHC_IRQSTATEN_ADDR(x), BP_SDHC_IRQSTATEN_AC12ESEN)) /*! @brief Format value for bitfield SDHC_IRQSTATEN_AC12ESEN. */ #define BF_SDHC_IRQSTATEN_AC12ESEN(v) ((uint32_t)((uint32_t)(v) << BP_SDHC_IRQSTATEN_AC12ESEN) & BM_SDHC_IRQSTATEN_AC12ESEN) /*! @brief Set the AC12ESEN field to a new value. */ #define BW_SDHC_IRQSTATEN_AC12ESEN(x, v) (BITBAND_ACCESS32(HW_SDHC_IRQSTATEN_ADDR(x), BP_SDHC_IRQSTATEN_AC12ESEN) = (v)) /*@}*/ /*! * @name Register SDHC_IRQSTATEN, field DMAESEN[28] (RW) * * Values: * - 0 - Masked * - 1 - Enabled */ /*@{*/ #define BP_SDHC_IRQSTATEN_DMAESEN (28U) /*!< Bit position for SDHC_IRQSTATEN_DMAESEN. */ #define BM_SDHC_IRQSTATEN_DMAESEN (0x10000000U) /*!< Bit mask for SDHC_IRQSTATEN_DMAESEN. */ #define BS_SDHC_IRQSTATEN_DMAESEN (1U) /*!< Bit field size in bits for SDHC_IRQSTATEN_DMAESEN. */ /*! @brief Read current value of the SDHC_IRQSTATEN_DMAESEN field. */ #define BR_SDHC_IRQSTATEN_DMAESEN(x) (BITBAND_ACCESS32(HW_SDHC_IRQSTATEN_ADDR(x), BP_SDHC_IRQSTATEN_DMAESEN)) /*! @brief Format value for bitfield SDHC_IRQSTATEN_DMAESEN. */ #define BF_SDHC_IRQSTATEN_DMAESEN(v) ((uint32_t)((uint32_t)(v) << BP_SDHC_IRQSTATEN_DMAESEN) & BM_SDHC_IRQSTATEN_DMAESEN) /*! @brief Set the DMAESEN field to a new value. */ #define BW_SDHC_IRQSTATEN_DMAESEN(x, v) (BITBAND_ACCESS32(HW_SDHC_IRQSTATEN_ADDR(x), BP_SDHC_IRQSTATEN_DMAESEN) = (v)) /*@}*/ /******************************************************************************* * HW_SDHC_IRQSIGEN - Interrupt Signal Enable register ******************************************************************************/ /*! * @brief HW_SDHC_IRQSIGEN - Interrupt Signal Enable register (RW) * * Reset value: 0x00000000U * * This register is used to select which interrupt status is indicated to the * host system as the interrupt. All of these status bits share the same interrupt * line. Setting any of these bits to 1 enables interrupt generation. The * corresponding status register bit will generate an interrupt when the corresponding * interrupt signal enable bit is set. */ typedef union _hw_sdhc_irqsigen { uint32_t U; struct _hw_sdhc_irqsigen_bitfields { uint32_t CCIEN : 1; /*!< [0] Command Complete Interrupt Enable */ uint32_t TCIEN : 1; /*!< [1] Transfer Complete Interrupt Enable */ uint32_t BGEIEN : 1; /*!< [2] Block Gap Event Interrupt Enable */ uint32_t DINTIEN : 1; /*!< [3] DMA Interrupt Enable */ uint32_t BWRIEN : 1; /*!< [4] Buffer Write Ready Interrupt Enable */ uint32_t BRRIEN : 1; /*!< [5] Buffer Read Ready Interrupt Enable */ uint32_t CINSIEN : 1; /*!< [6] Card Insertion Interrupt Enable */ uint32_t CRMIEN : 1; /*!< [7] Card Removal Interrupt Enable */ uint32_t CINTIEN : 1; /*!< [8] Card Interrupt Enable */ uint32_t RESERVED0 : 7; /*!< [15:9] */ uint32_t CTOEIEN : 1; /*!< [16] Command Timeout Error Interrupt * Enable */ uint32_t CCEIEN : 1; /*!< [17] Command CRC Error Interrupt Enable */ uint32_t CEBEIEN : 1; /*!< [18] Command End Bit Error Interrupt * Enable */ uint32_t CIEIEN : 1; /*!< [19] Command Index Error Interrupt Enable */ uint32_t DTOEIEN : 1; /*!< [20] Data Timeout Error Interrupt Enable */ uint32_t DCEIEN : 1; /*!< [21] Data CRC Error Interrupt Enable */ uint32_t DEBEIEN : 1; /*!< [22] Data End Bit Error Interrupt Enable */ uint32_t RESERVED1 : 1; /*!< [23] */ uint32_t AC12EIEN : 1; /*!< [24] Auto CMD12 Error Interrupt Enable */ uint32_t RESERVED2 : 3; /*!< [27:25] */ uint32_t DMAEIEN : 1; /*!< [28] DMA Error Interrupt Enable */ uint32_t RESERVED3 : 3; /*!< [31:29] */ } B; } hw_sdhc_irqsigen_t; /*! * @name Constants and macros for entire SDHC_IRQSIGEN register */ /*@{*/ #define HW_SDHC_IRQSIGEN_ADDR(x) ((x) + 0x38U) #define HW_SDHC_IRQSIGEN(x) (*(__IO hw_sdhc_irqsigen_t *) HW_SDHC_IRQSIGEN_ADDR(x)) #define HW_SDHC_IRQSIGEN_RD(x) (HW_SDHC_IRQSIGEN(x).U) #define HW_SDHC_IRQSIGEN_WR(x, v) (HW_SDHC_IRQSIGEN(x).U = (v)) #define HW_SDHC_IRQSIGEN_SET(x, v) (HW_SDHC_IRQSIGEN_WR(x, HW_SDHC_IRQSIGEN_RD(x) | (v))) #define HW_SDHC_IRQSIGEN_CLR(x, v) (HW_SDHC_IRQSIGEN_WR(x, HW_SDHC_IRQSIGEN_RD(x) & ~(v))) #define HW_SDHC_IRQSIGEN_TOG(x, v) (HW_SDHC_IRQSIGEN_WR(x, HW_SDHC_IRQSIGEN_RD(x) ^ (v))) /*@}*/ /* * Constants & macros for individual SDHC_IRQSIGEN bitfields */ /*! * @name Register SDHC_IRQSIGEN, field CCIEN[0] (RW) * * Values: * - 0 - Masked * - 1 - Enabled */ /*@{*/ #define BP_SDHC_IRQSIGEN_CCIEN (0U) /*!< Bit position for SDHC_IRQSIGEN_CCIEN. */ #define BM_SDHC_IRQSIGEN_CCIEN (0x00000001U) /*!< Bit mask for SDHC_IRQSIGEN_CCIEN. */ #define BS_SDHC_IRQSIGEN_CCIEN (1U) /*!< Bit field size in bits for SDHC_IRQSIGEN_CCIEN. */ /*! @brief Read current value of the SDHC_IRQSIGEN_CCIEN field. */ #define BR_SDHC_IRQSIGEN_CCIEN(x) (BITBAND_ACCESS32(HW_SDHC_IRQSIGEN_ADDR(x), BP_SDHC_IRQSIGEN_CCIEN)) /*! @brief Format value for bitfield SDHC_IRQSIGEN_CCIEN. */ #define BF_SDHC_IRQSIGEN_CCIEN(v) ((uint32_t)((uint32_t)(v) << BP_SDHC_IRQSIGEN_CCIEN) & BM_SDHC_IRQSIGEN_CCIEN) /*! @brief Set the CCIEN field to a new value. */ #define BW_SDHC_IRQSIGEN_CCIEN(x, v) (BITBAND_ACCESS32(HW_SDHC_IRQSIGEN_ADDR(x), BP_SDHC_IRQSIGEN_CCIEN) = (v)) /*@}*/ /*! * @name Register SDHC_IRQSIGEN, field TCIEN[1] (RW) * * Values: * - 0 - Masked * - 1 - Enabled */ /*@{*/ #define BP_SDHC_IRQSIGEN_TCIEN (1U) /*!< Bit position for SDHC_IRQSIGEN_TCIEN. */ #define BM_SDHC_IRQSIGEN_TCIEN (0x00000002U) /*!< Bit mask for SDHC_IRQSIGEN_TCIEN. */ #define BS_SDHC_IRQSIGEN_TCIEN (1U) /*!< Bit field size in bits for SDHC_IRQSIGEN_TCIEN. */ /*! @brief Read current value of the SDHC_IRQSIGEN_TCIEN field. */ #define BR_SDHC_IRQSIGEN_TCIEN(x) (BITBAND_ACCESS32(HW_SDHC_IRQSIGEN_ADDR(x), BP_SDHC_IRQSIGEN_TCIEN)) /*! @brief Format value for bitfield SDHC_IRQSIGEN_TCIEN. */ #define BF_SDHC_IRQSIGEN_TCIEN(v) ((uint32_t)((uint32_t)(v) << BP_SDHC_IRQSIGEN_TCIEN) & BM_SDHC_IRQSIGEN_TCIEN) /*! @brief Set the TCIEN field to a new value. */ #define BW_SDHC_IRQSIGEN_TCIEN(x, v) (BITBAND_ACCESS32(HW_SDHC_IRQSIGEN_ADDR(x), BP_SDHC_IRQSIGEN_TCIEN) = (v)) /*@}*/ /*! * @name Register SDHC_IRQSIGEN, field BGEIEN[2] (RW) * * Values: * - 0 - Masked * - 1 - Enabled */ /*@{*/ #define BP_SDHC_IRQSIGEN_BGEIEN (2U) /*!< Bit position for SDHC_IRQSIGEN_BGEIEN. */ #define BM_SDHC_IRQSIGEN_BGEIEN (0x00000004U) /*!< Bit mask for SDHC_IRQSIGEN_BGEIEN. */ #define BS_SDHC_IRQSIGEN_BGEIEN (1U) /*!< Bit field size in bits for SDHC_IRQSIGEN_BGEIEN. */ /*! @brief Read current value of the SDHC_IRQSIGEN_BGEIEN field. */ #define BR_SDHC_IRQSIGEN_BGEIEN(x) (BITBAND_ACCESS32(HW_SDHC_IRQSIGEN_ADDR(x), BP_SDHC_IRQSIGEN_BGEIEN)) /*! @brief Format value for bitfield SDHC_IRQSIGEN_BGEIEN. */ #define BF_SDHC_IRQSIGEN_BGEIEN(v) ((uint32_t)((uint32_t)(v) << BP_SDHC_IRQSIGEN_BGEIEN) & BM_SDHC_IRQSIGEN_BGEIEN) /*! @brief Set the BGEIEN field to a new value. */ #define BW_SDHC_IRQSIGEN_BGEIEN(x, v) (BITBAND_ACCESS32(HW_SDHC_IRQSIGEN_ADDR(x), BP_SDHC_IRQSIGEN_BGEIEN) = (v)) /*@}*/ /*! * @name Register SDHC_IRQSIGEN, field DINTIEN[3] (RW) * * Values: * - 0 - Masked * - 1 - Enabled */ /*@{*/ #define BP_SDHC_IRQSIGEN_DINTIEN (3U) /*!< Bit position for SDHC_IRQSIGEN_DINTIEN. */ #define BM_SDHC_IRQSIGEN_DINTIEN (0x00000008U) /*!< Bit mask for SDHC_IRQSIGEN_DINTIEN. */ #define BS_SDHC_IRQSIGEN_DINTIEN (1U) /*!< Bit field size in bits for SDHC_IRQSIGEN_DINTIEN. */ /*! @brief Read current value of the SDHC_IRQSIGEN_DINTIEN field. */ #define BR_SDHC_IRQSIGEN_DINTIEN(x) (BITBAND_ACCESS32(HW_SDHC_IRQSIGEN_ADDR(x), BP_SDHC_IRQSIGEN_DINTIEN)) /*! @brief Format value for bitfield SDHC_IRQSIGEN_DINTIEN. */ #define BF_SDHC_IRQSIGEN_DINTIEN(v) ((uint32_t)((uint32_t)(v) << BP_SDHC_IRQSIGEN_DINTIEN) & BM_SDHC_IRQSIGEN_DINTIEN) /*! @brief Set the DINTIEN field to a new value. */ #define BW_SDHC_IRQSIGEN_DINTIEN(x, v) (BITBAND_ACCESS32(HW_SDHC_IRQSIGEN_ADDR(x), BP_SDHC_IRQSIGEN_DINTIEN) = (v)) /*@}*/ /*! * @name Register SDHC_IRQSIGEN, field BWRIEN[4] (RW) * * Values: * - 0 - Masked * - 1 - Enabled */ /*@{*/ #define BP_SDHC_IRQSIGEN_BWRIEN (4U) /*!< Bit position for SDHC_IRQSIGEN_BWRIEN. */ #define BM_SDHC_IRQSIGEN_BWRIEN (0x00000010U) /*!< Bit mask for SDHC_IRQSIGEN_BWRIEN. */ #define BS_SDHC_IRQSIGEN_BWRIEN (1U) /*!< Bit field size in bits for SDHC_IRQSIGEN_BWRIEN. */ /*! @brief Read current value of the SDHC_IRQSIGEN_BWRIEN field. */ #define BR_SDHC_IRQSIGEN_BWRIEN(x) (BITBAND_ACCESS32(HW_SDHC_IRQSIGEN_ADDR(x), BP_SDHC_IRQSIGEN_BWRIEN)) /*! @brief Format value for bitfield SDHC_IRQSIGEN_BWRIEN. */ #define BF_SDHC_IRQSIGEN_BWRIEN(v) ((uint32_t)((uint32_t)(v) << BP_SDHC_IRQSIGEN_BWRIEN) & BM_SDHC_IRQSIGEN_BWRIEN) /*! @brief Set the BWRIEN field to a new value. */ #define BW_SDHC_IRQSIGEN_BWRIEN(x, v) (BITBAND_ACCESS32(HW_SDHC_IRQSIGEN_ADDR(x), BP_SDHC_IRQSIGEN_BWRIEN) = (v)) /*@}*/ /*! * @name Register SDHC_IRQSIGEN, field BRRIEN[5] (RW) * * Values: * - 0 - Masked * - 1 - Enabled */ /*@{*/ #define BP_SDHC_IRQSIGEN_BRRIEN (5U) /*!< Bit position for SDHC_IRQSIGEN_BRRIEN. */ #define BM_SDHC_IRQSIGEN_BRRIEN (0x00000020U) /*!< Bit mask for SDHC_IRQSIGEN_BRRIEN. */ #define BS_SDHC_IRQSIGEN_BRRIEN (1U) /*!< Bit field size in bits for SDHC_IRQSIGEN_BRRIEN. */ /*! @brief Read current value of the SDHC_IRQSIGEN_BRRIEN field. */ #define BR_SDHC_IRQSIGEN_BRRIEN(x) (BITBAND_ACCESS32(HW_SDHC_IRQSIGEN_ADDR(x), BP_SDHC_IRQSIGEN_BRRIEN)) /*! @brief Format value for bitfield SDHC_IRQSIGEN_BRRIEN. */ #define BF_SDHC_IRQSIGEN_BRRIEN(v) ((uint32_t)((uint32_t)(v) << BP_SDHC_IRQSIGEN_BRRIEN) & BM_SDHC_IRQSIGEN_BRRIEN) /*! @brief Set the BRRIEN field to a new value. */ #define BW_SDHC_IRQSIGEN_BRRIEN(x, v) (BITBAND_ACCESS32(HW_SDHC_IRQSIGEN_ADDR(x), BP_SDHC_IRQSIGEN_BRRIEN) = (v)) /*@}*/ /*! * @name Register SDHC_IRQSIGEN, field CINSIEN[6] (RW) * * Values: * - 0 - Masked * - 1 - Enabled */ /*@{*/ #define BP_SDHC_IRQSIGEN_CINSIEN (6U) /*!< Bit position for SDHC_IRQSIGEN_CINSIEN. */ #define BM_SDHC_IRQSIGEN_CINSIEN (0x00000040U) /*!< Bit mask for SDHC_IRQSIGEN_CINSIEN. */ #define BS_SDHC_IRQSIGEN_CINSIEN (1U) /*!< Bit field size in bits for SDHC_IRQSIGEN_CINSIEN. */ /*! @brief Read current value of the SDHC_IRQSIGEN_CINSIEN field. */ #define BR_SDHC_IRQSIGEN_CINSIEN(x) (BITBAND_ACCESS32(HW_SDHC_IRQSIGEN_ADDR(x), BP_SDHC_IRQSIGEN_CINSIEN)) /*! @brief Format value for bitfield SDHC_IRQSIGEN_CINSIEN. */ #define BF_SDHC_IRQSIGEN_CINSIEN(v) ((uint32_t)((uint32_t)(v) << BP_SDHC_IRQSIGEN_CINSIEN) & BM_SDHC_IRQSIGEN_CINSIEN) /*! @brief Set the CINSIEN field to a new value. */ #define BW_SDHC_IRQSIGEN_CINSIEN(x, v) (BITBAND_ACCESS32(HW_SDHC_IRQSIGEN_ADDR(x), BP_SDHC_IRQSIGEN_CINSIEN) = (v)) /*@}*/ /*! * @name Register SDHC_IRQSIGEN, field CRMIEN[7] (RW) * * Values: * - 0 - Masked * - 1 - Enabled */ /*@{*/ #define BP_SDHC_IRQSIGEN_CRMIEN (7U) /*!< Bit position for SDHC_IRQSIGEN_CRMIEN. */ #define BM_SDHC_IRQSIGEN_CRMIEN (0x00000080U) /*!< Bit mask for SDHC_IRQSIGEN_CRMIEN. */ #define BS_SDHC_IRQSIGEN_CRMIEN (1U) /*!< Bit field size in bits for SDHC_IRQSIGEN_CRMIEN. */ /*! @brief Read current value of the SDHC_IRQSIGEN_CRMIEN field. */ #define BR_SDHC_IRQSIGEN_CRMIEN(x) (BITBAND_ACCESS32(HW_SDHC_IRQSIGEN_ADDR(x), BP_SDHC_IRQSIGEN_CRMIEN)) /*! @brief Format value for bitfield SDHC_IRQSIGEN_CRMIEN. */ #define BF_SDHC_IRQSIGEN_CRMIEN(v) ((uint32_t)((uint32_t)(v) << BP_SDHC_IRQSIGEN_CRMIEN) & BM_SDHC_IRQSIGEN_CRMIEN) /*! @brief Set the CRMIEN field to a new value. */ #define BW_SDHC_IRQSIGEN_CRMIEN(x, v) (BITBAND_ACCESS32(HW_SDHC_IRQSIGEN_ADDR(x), BP_SDHC_IRQSIGEN_CRMIEN) = (v)) /*@}*/ /*! * @name Register SDHC_IRQSIGEN, field CINTIEN[8] (RW) * * Values: * - 0 - Masked * - 1 - Enabled */ /*@{*/ #define BP_SDHC_IRQSIGEN_CINTIEN (8U) /*!< Bit position for SDHC_IRQSIGEN_CINTIEN. */ #define BM_SDHC_IRQSIGEN_CINTIEN (0x00000100U) /*!< Bit mask for SDHC_IRQSIGEN_CINTIEN. */ #define BS_SDHC_IRQSIGEN_CINTIEN (1U) /*!< Bit field size in bits for SDHC_IRQSIGEN_CINTIEN. */ /*! @brief Read current value of the SDHC_IRQSIGEN_CINTIEN field. */ #define BR_SDHC_IRQSIGEN_CINTIEN(x) (BITBAND_ACCESS32(HW_SDHC_IRQSIGEN_ADDR(x), BP_SDHC_IRQSIGEN_CINTIEN)) /*! @brief Format value for bitfield SDHC_IRQSIGEN_CINTIEN. */ #define BF_SDHC_IRQSIGEN_CINTIEN(v) ((uint32_t)((uint32_t)(v) << BP_SDHC_IRQSIGEN_CINTIEN) & BM_SDHC_IRQSIGEN_CINTIEN) /*! @brief Set the CINTIEN field to a new value. */ #define BW_SDHC_IRQSIGEN_CINTIEN(x, v) (BITBAND_ACCESS32(HW_SDHC_IRQSIGEN_ADDR(x), BP_SDHC_IRQSIGEN_CINTIEN) = (v)) /*@}*/ /*! * @name Register SDHC_IRQSIGEN, field CTOEIEN[16] (RW) * * Values: * - 0 - Masked * - 1 - Enabled */ /*@{*/ #define BP_SDHC_IRQSIGEN_CTOEIEN (16U) /*!< Bit position for SDHC_IRQSIGEN_CTOEIEN. */ #define BM_SDHC_IRQSIGEN_CTOEIEN (0x00010000U) /*!< Bit mask for SDHC_IRQSIGEN_CTOEIEN. */ #define BS_SDHC_IRQSIGEN_CTOEIEN (1U) /*!< Bit field size in bits for SDHC_IRQSIGEN_CTOEIEN. */ /*! @brief Read current value of the SDHC_IRQSIGEN_CTOEIEN field. */ #define BR_SDHC_IRQSIGEN_CTOEIEN(x) (BITBAND_ACCESS32(HW_SDHC_IRQSIGEN_ADDR(x), BP_SDHC_IRQSIGEN_CTOEIEN)) /*! @brief Format value for bitfield SDHC_IRQSIGEN_CTOEIEN. */ #define BF_SDHC_IRQSIGEN_CTOEIEN(v) ((uint32_t)((uint32_t)(v) << BP_SDHC_IRQSIGEN_CTOEIEN) & BM_SDHC_IRQSIGEN_CTOEIEN) /*! @brief Set the CTOEIEN field to a new value. */ #define BW_SDHC_IRQSIGEN_CTOEIEN(x, v) (BITBAND_ACCESS32(HW_SDHC_IRQSIGEN_ADDR(x), BP_SDHC_IRQSIGEN_CTOEIEN) = (v)) /*@}*/ /*! * @name Register SDHC_IRQSIGEN, field CCEIEN[17] (RW) * * Values: * - 0 - Masked * - 1 - Enabled */ /*@{*/ #define BP_SDHC_IRQSIGEN_CCEIEN (17U) /*!< Bit position for SDHC_IRQSIGEN_CCEIEN. */ #define BM_SDHC_IRQSIGEN_CCEIEN (0x00020000U) /*!< Bit mask for SDHC_IRQSIGEN_CCEIEN. */ #define BS_SDHC_IRQSIGEN_CCEIEN (1U) /*!< Bit field size in bits for SDHC_IRQSIGEN_CCEIEN. */ /*! @brief Read current value of the SDHC_IRQSIGEN_CCEIEN field. */ #define BR_SDHC_IRQSIGEN_CCEIEN(x) (BITBAND_ACCESS32(HW_SDHC_IRQSIGEN_ADDR(x), BP_SDHC_IRQSIGEN_CCEIEN)) /*! @brief Format value for bitfield SDHC_IRQSIGEN_CCEIEN. */ #define BF_SDHC_IRQSIGEN_CCEIEN(v) ((uint32_t)((uint32_t)(v) << BP_SDHC_IRQSIGEN_CCEIEN) & BM_SDHC_IRQSIGEN_CCEIEN) /*! @brief Set the CCEIEN field to a new value. */ #define BW_SDHC_IRQSIGEN_CCEIEN(x, v) (BITBAND_ACCESS32(HW_SDHC_IRQSIGEN_ADDR(x), BP_SDHC_IRQSIGEN_CCEIEN) = (v)) /*@}*/ /*! * @name Register SDHC_IRQSIGEN, field CEBEIEN[18] (RW) * * Values: * - 0 - Masked * - 1 - Enabled */ /*@{*/ #define BP_SDHC_IRQSIGEN_CEBEIEN (18U) /*!< Bit position for SDHC_IRQSIGEN_CEBEIEN. */ #define BM_SDHC_IRQSIGEN_CEBEIEN (0x00040000U) /*!< Bit mask for SDHC_IRQSIGEN_CEBEIEN. */ #define BS_SDHC_IRQSIGEN_CEBEIEN (1U) /*!< Bit field size in bits for SDHC_IRQSIGEN_CEBEIEN. */ /*! @brief Read current value of the SDHC_IRQSIGEN_CEBEIEN field. */ #define BR_SDHC_IRQSIGEN_CEBEIEN(x) (BITBAND_ACCESS32(HW_SDHC_IRQSIGEN_ADDR(x), BP_SDHC_IRQSIGEN_CEBEIEN)) /*! @brief Format value for bitfield SDHC_IRQSIGEN_CEBEIEN. */ #define BF_SDHC_IRQSIGEN_CEBEIEN(v) ((uint32_t)((uint32_t)(v) << BP_SDHC_IRQSIGEN_CEBEIEN) & BM_SDHC_IRQSIGEN_CEBEIEN) /*! @brief Set the CEBEIEN field to a new value. */ #define BW_SDHC_IRQSIGEN_CEBEIEN(x, v) (BITBAND_ACCESS32(HW_SDHC_IRQSIGEN_ADDR(x), BP_SDHC_IRQSIGEN_CEBEIEN) = (v)) /*@}*/ /*! * @name Register SDHC_IRQSIGEN, field CIEIEN[19] (RW) * * Values: * - 0 - Masked * - 1 - Enabled */ /*@{*/ #define BP_SDHC_IRQSIGEN_CIEIEN (19U) /*!< Bit position for SDHC_IRQSIGEN_CIEIEN. */ #define BM_SDHC_IRQSIGEN_CIEIEN (0x00080000U) /*!< Bit mask for SDHC_IRQSIGEN_CIEIEN. */ #define BS_SDHC_IRQSIGEN_CIEIEN (1U) /*!< Bit field size in bits for SDHC_IRQSIGEN_CIEIEN. */ /*! @brief Read current value of the SDHC_IRQSIGEN_CIEIEN field. */ #define BR_SDHC_IRQSIGEN_CIEIEN(x) (BITBAND_ACCESS32(HW_SDHC_IRQSIGEN_ADDR(x), BP_SDHC_IRQSIGEN_CIEIEN)) /*! @brief Format value for bitfield SDHC_IRQSIGEN_CIEIEN. */ #define BF_SDHC_IRQSIGEN_CIEIEN(v) ((uint32_t)((uint32_t)(v) << BP_SDHC_IRQSIGEN_CIEIEN) & BM_SDHC_IRQSIGEN_CIEIEN) /*! @brief Set the CIEIEN field to a new value. */ #define BW_SDHC_IRQSIGEN_CIEIEN(x, v) (BITBAND_ACCESS32(HW_SDHC_IRQSIGEN_ADDR(x), BP_SDHC_IRQSIGEN_CIEIEN) = (v)) /*@}*/ /*! * @name Register SDHC_IRQSIGEN, field DTOEIEN[20] (RW) * * Values: * - 0 - Masked * - 1 - Enabled */ /*@{*/ #define BP_SDHC_IRQSIGEN_DTOEIEN (20U) /*!< Bit position for SDHC_IRQSIGEN_DTOEIEN. */ #define BM_SDHC_IRQSIGEN_DTOEIEN (0x00100000U) /*!< Bit mask for SDHC_IRQSIGEN_DTOEIEN. */ #define BS_SDHC_IRQSIGEN_DTOEIEN (1U) /*!< Bit field size in bits for SDHC_IRQSIGEN_DTOEIEN. */ /*! @brief Read current value of the SDHC_IRQSIGEN_DTOEIEN field. */ #define BR_SDHC_IRQSIGEN_DTOEIEN(x) (BITBAND_ACCESS32(HW_SDHC_IRQSIGEN_ADDR(x), BP_SDHC_IRQSIGEN_DTOEIEN)) /*! @brief Format value for bitfield SDHC_IRQSIGEN_DTOEIEN. */ #define BF_SDHC_IRQSIGEN_DTOEIEN(v) ((uint32_t)((uint32_t)(v) << BP_SDHC_IRQSIGEN_DTOEIEN) & BM_SDHC_IRQSIGEN_DTOEIEN) /*! @brief Set the DTOEIEN field to a new value. */ #define BW_SDHC_IRQSIGEN_DTOEIEN(x, v) (BITBAND_ACCESS32(HW_SDHC_IRQSIGEN_ADDR(x), BP_SDHC_IRQSIGEN_DTOEIEN) = (v)) /*@}*/ /*! * @name Register SDHC_IRQSIGEN, field DCEIEN[21] (RW) * * Values: * - 0 - Masked * - 1 - Enabled */ /*@{*/ #define BP_SDHC_IRQSIGEN_DCEIEN (21U) /*!< Bit position for SDHC_IRQSIGEN_DCEIEN. */ #define BM_SDHC_IRQSIGEN_DCEIEN (0x00200000U) /*!< Bit mask for SDHC_IRQSIGEN_DCEIEN. */ #define BS_SDHC_IRQSIGEN_DCEIEN (1U) /*!< Bit field size in bits for SDHC_IRQSIGEN_DCEIEN. */ /*! @brief Read current value of the SDHC_IRQSIGEN_DCEIEN field. */ #define BR_SDHC_IRQSIGEN_DCEIEN(x) (BITBAND_ACCESS32(HW_SDHC_IRQSIGEN_ADDR(x), BP_SDHC_IRQSIGEN_DCEIEN)) /*! @brief Format value for bitfield SDHC_IRQSIGEN_DCEIEN. */ #define BF_SDHC_IRQSIGEN_DCEIEN(v) ((uint32_t)((uint32_t)(v) << BP_SDHC_IRQSIGEN_DCEIEN) & BM_SDHC_IRQSIGEN_DCEIEN) /*! @brief Set the DCEIEN field to a new value. */ #define BW_SDHC_IRQSIGEN_DCEIEN(x, v) (BITBAND_ACCESS32(HW_SDHC_IRQSIGEN_ADDR(x), BP_SDHC_IRQSIGEN_DCEIEN) = (v)) /*@}*/ /*! * @name Register SDHC_IRQSIGEN, field DEBEIEN[22] (RW) * * Values: * - 0 - Masked * - 1 - Enabled */ /*@{*/ #define BP_SDHC_IRQSIGEN_DEBEIEN (22U) /*!< Bit position for SDHC_IRQSIGEN_DEBEIEN. */ #define BM_SDHC_IRQSIGEN_DEBEIEN (0x00400000U) /*!< Bit mask for SDHC_IRQSIGEN_DEBEIEN. */ #define BS_SDHC_IRQSIGEN_DEBEIEN (1U) /*!< Bit field size in bits for SDHC_IRQSIGEN_DEBEIEN. */ /*! @brief Read current value of the SDHC_IRQSIGEN_DEBEIEN field. */ #define BR_SDHC_IRQSIGEN_DEBEIEN(x) (BITBAND_ACCESS32(HW_SDHC_IRQSIGEN_ADDR(x), BP_SDHC_IRQSIGEN_DEBEIEN)) /*! @brief Format value for bitfield SDHC_IRQSIGEN_DEBEIEN. */ #define BF_SDHC_IRQSIGEN_DEBEIEN(v) ((uint32_t)((uint32_t)(v) << BP_SDHC_IRQSIGEN_DEBEIEN) & BM_SDHC_IRQSIGEN_DEBEIEN) /*! @brief Set the DEBEIEN field to a new value. */ #define BW_SDHC_IRQSIGEN_DEBEIEN(x, v) (BITBAND_ACCESS32(HW_SDHC_IRQSIGEN_ADDR(x), BP_SDHC_IRQSIGEN_DEBEIEN) = (v)) /*@}*/ /*! * @name Register SDHC_IRQSIGEN, field AC12EIEN[24] (RW) * * Values: * - 0 - Masked * - 1 - Enabled */ /*@{*/ #define BP_SDHC_IRQSIGEN_AC12EIEN (24U) /*!< Bit position for SDHC_IRQSIGEN_AC12EIEN. */ #define BM_SDHC_IRQSIGEN_AC12EIEN (0x01000000U) /*!< Bit mask for SDHC_IRQSIGEN_AC12EIEN. */ #define BS_SDHC_IRQSIGEN_AC12EIEN (1U) /*!< Bit field size in bits for SDHC_IRQSIGEN_AC12EIEN. */ /*! @brief Read current value of the SDHC_IRQSIGEN_AC12EIEN field. */ #define BR_SDHC_IRQSIGEN_AC12EIEN(x) (BITBAND_ACCESS32(HW_SDHC_IRQSIGEN_ADDR(x), BP_SDHC_IRQSIGEN_AC12EIEN)) /*! @brief Format value for bitfield SDHC_IRQSIGEN_AC12EIEN. */ #define BF_SDHC_IRQSIGEN_AC12EIEN(v) ((uint32_t)((uint32_t)(v) << BP_SDHC_IRQSIGEN_AC12EIEN) & BM_SDHC_IRQSIGEN_AC12EIEN) /*! @brief Set the AC12EIEN field to a new value. */ #define BW_SDHC_IRQSIGEN_AC12EIEN(x, v) (BITBAND_ACCESS32(HW_SDHC_IRQSIGEN_ADDR(x), BP_SDHC_IRQSIGEN_AC12EIEN) = (v)) /*@}*/ /*! * @name Register SDHC_IRQSIGEN, field DMAEIEN[28] (RW) * * Values: * - 0 - Masked * - 1 - Enabled */ /*@{*/ #define BP_SDHC_IRQSIGEN_DMAEIEN (28U) /*!< Bit position for SDHC_IRQSIGEN_DMAEIEN. */ #define BM_SDHC_IRQSIGEN_DMAEIEN (0x10000000U) /*!< Bit mask for SDHC_IRQSIGEN_DMAEIEN. */ #define BS_SDHC_IRQSIGEN_DMAEIEN (1U) /*!< Bit field size in bits for SDHC_IRQSIGEN_DMAEIEN. */ /*! @brief Read current value of the SDHC_IRQSIGEN_DMAEIEN field. */ #define BR_SDHC_IRQSIGEN_DMAEIEN(x) (BITBAND_ACCESS32(HW_SDHC_IRQSIGEN_ADDR(x), BP_SDHC_IRQSIGEN_DMAEIEN)) /*! @brief Format value for bitfield SDHC_IRQSIGEN_DMAEIEN. */ #define BF_SDHC_IRQSIGEN_DMAEIEN(v) ((uint32_t)((uint32_t)(v) << BP_SDHC_IRQSIGEN_DMAEIEN) & BM_SDHC_IRQSIGEN_DMAEIEN) /*! @brief Set the DMAEIEN field to a new value. */ #define BW_SDHC_IRQSIGEN_DMAEIEN(x, v) (BITBAND_ACCESS32(HW_SDHC_IRQSIGEN_ADDR(x), BP_SDHC_IRQSIGEN_DMAEIEN) = (v)) /*@}*/ /******************************************************************************* * HW_SDHC_AC12ERR - Auto CMD12 Error Status Register ******************************************************************************/ /*! * @brief HW_SDHC_AC12ERR - Auto CMD12 Error Status Register (RO) * * Reset value: 0x00000000U * * When the AC12ESEN bit in the Status register is set, the host driver shall * check this register to identify what kind of error the Auto CMD12 indicated. * This register is valid only when the Auto CMD12 Error status bit is set. The * following table shows the relationship between the Auto CMGD12 CRC error and the * Auto CMD12 command timeout error. Relationship between Command CRC Error and * Command Timeout Error For Auto CMD12 Auto CMD12 CRC error Auto CMD12 timeout * error Type of error 0 0 No error 0 1 Response timeout error 1 0 Response CRC * error 1 1 CMD line conflict Changes in Auto CMD12 Error Status register can be * classified in three scenarios: When the SDHC is going to issue an Auto CMD12: Set * bit 0 to 1 if the Auto CMD12 can't be issued due to an error in the previous * command. Set bit 0 to 0 if the auto CMD12 is issued. At the end bit of an auto * CMD12 response: Check errors corresponding to bits 1-4. Set bits 1-4 * corresponding to detected errors. Clear bits 1-4 corresponding to detected errors. * Before reading the Auto CMD12 error status bit 7: Set bit 7 to 1 if there is a * command that can't be issued. Clear bit 7 if there is no command to issue. The * timing for generating the auto CMD12 error and writing to the command register * are asynchronous. After that, bit 7 shall be sampled when the driver is not * writing to the command register. So it is suggested to read this register only * when IRQSTAT[AC12E] is set. An Auto CMD12 error interrupt is generated when one * of the error bits (0-4) is set to 1. The command not issued by auto CMD12 * error does not generate an interrupt. */ typedef union _hw_sdhc_ac12err { uint32_t U; struct _hw_sdhc_ac12err_bitfields { uint32_t AC12NE : 1; /*!< [0] Auto CMD12 Not Executed */ uint32_t AC12TOE : 1; /*!< [1] Auto CMD12 Timeout Error */ uint32_t AC12EBE : 1; /*!< [2] Auto CMD12 End Bit Error */ uint32_t AC12CE : 1; /*!< [3] Auto CMD12 CRC Error */ uint32_t AC12IE : 1; /*!< [4] Auto CMD12 Index Error */ uint32_t RESERVED0 : 2; /*!< [6:5] */ uint32_t CNIBAC12E : 1; /*!< [7] Command Not Issued By Auto CMD12 * Error */ uint32_t RESERVED1 : 24; /*!< [31:8] */ } B; } hw_sdhc_ac12err_t; /*! * @name Constants and macros for entire SDHC_AC12ERR register */ /*@{*/ #define HW_SDHC_AC12ERR_ADDR(x) ((x) + 0x3CU) #define HW_SDHC_AC12ERR(x) (*(__I hw_sdhc_ac12err_t *) HW_SDHC_AC12ERR_ADDR(x)) #define HW_SDHC_AC12ERR_RD(x) (HW_SDHC_AC12ERR(x).U) /*@}*/ /* * Constants & macros for individual SDHC_AC12ERR bitfields */ /*! * @name Register SDHC_AC12ERR, field AC12NE[0] (RO) * * If memory multiple block data transfer is not started, due to a command * error, this bit is not set because it is not necessary to issue an auto CMD12. * Setting this bit to 1 means the SDHC cannot issue the auto CMD12 to stop a memory * multiple block data transfer due to some error. If this bit is set to 1, other * error status bits (1-4) have no meaning. * * Values: * - 0 - Executed. * - 1 - Not executed. */ /*@{*/ #define BP_SDHC_AC12ERR_AC12NE (0U) /*!< Bit position for SDHC_AC12ERR_AC12NE. */ #define BM_SDHC_AC12ERR_AC12NE (0x00000001U) /*!< Bit mask for SDHC_AC12ERR_AC12NE. */ #define BS_SDHC_AC12ERR_AC12NE (1U) /*!< Bit field size in bits for SDHC_AC12ERR_AC12NE. */ /*! @brief Read current value of the SDHC_AC12ERR_AC12NE field. */ #define BR_SDHC_AC12ERR_AC12NE(x) (BITBAND_ACCESS32(HW_SDHC_AC12ERR_ADDR(x), BP_SDHC_AC12ERR_AC12NE)) /*@}*/ /*! * @name Register SDHC_AC12ERR, field AC12TOE[1] (RO) * * Occurs if no response is returned within 64 SDCLK cycles from the end bit of * the command. If this bit is set to 1, the other error status bits (2-4) have * no meaning. * * Values: * - 0 - No error. * - 1 - Time out. */ /*@{*/ #define BP_SDHC_AC12ERR_AC12TOE (1U) /*!< Bit position for SDHC_AC12ERR_AC12TOE. */ #define BM_SDHC_AC12ERR_AC12TOE (0x00000002U) /*!< Bit mask for SDHC_AC12ERR_AC12TOE. */ #define BS_SDHC_AC12ERR_AC12TOE (1U) /*!< Bit field size in bits for SDHC_AC12ERR_AC12TOE. */ /*! @brief Read current value of the SDHC_AC12ERR_AC12TOE field. */ #define BR_SDHC_AC12ERR_AC12TOE(x) (BITBAND_ACCESS32(HW_SDHC_AC12ERR_ADDR(x), BP_SDHC_AC12ERR_AC12TOE)) /*@}*/ /*! * @name Register SDHC_AC12ERR, field AC12EBE[2] (RO) * * Occurs when detecting that the end bit of command response is 0 which must be * 1. * * Values: * - 0 - No error. * - 1 - End bit error generated. */ /*@{*/ #define BP_SDHC_AC12ERR_AC12EBE (2U) /*!< Bit position for SDHC_AC12ERR_AC12EBE. */ #define BM_SDHC_AC12ERR_AC12EBE (0x00000004U) /*!< Bit mask for SDHC_AC12ERR_AC12EBE. */ #define BS_SDHC_AC12ERR_AC12EBE (1U) /*!< Bit field size in bits for SDHC_AC12ERR_AC12EBE. */ /*! @brief Read current value of the SDHC_AC12ERR_AC12EBE field. */ #define BR_SDHC_AC12ERR_AC12EBE(x) (BITBAND_ACCESS32(HW_SDHC_AC12ERR_ADDR(x), BP_SDHC_AC12ERR_AC12EBE)) /*@}*/ /*! * @name Register SDHC_AC12ERR, field AC12CE[3] (RO) * * Occurs when detecting a CRC error in the command response. * * Values: * - 0 - No CRC error. * - 1 - CRC error met in Auto CMD12 response. */ /*@{*/ #define BP_SDHC_AC12ERR_AC12CE (3U) /*!< Bit position for SDHC_AC12ERR_AC12CE. */ #define BM_SDHC_AC12ERR_AC12CE (0x00000008U) /*!< Bit mask for SDHC_AC12ERR_AC12CE. */ #define BS_SDHC_AC12ERR_AC12CE (1U) /*!< Bit field size in bits for SDHC_AC12ERR_AC12CE. */ /*! @brief Read current value of the SDHC_AC12ERR_AC12CE field. */ #define BR_SDHC_AC12ERR_AC12CE(x) (BITBAND_ACCESS32(HW_SDHC_AC12ERR_ADDR(x), BP_SDHC_AC12ERR_AC12CE)) /*@}*/ /*! * @name Register SDHC_AC12ERR, field AC12IE[4] (RO) * * Occurs if the command index error occurs in response to a command. * * Values: * - 0 - No error. * - 1 - Error, the CMD index in response is not CMD12. */ /*@{*/ #define BP_SDHC_AC12ERR_AC12IE (4U) /*!< Bit position for SDHC_AC12ERR_AC12IE. */ #define BM_SDHC_AC12ERR_AC12IE (0x00000010U) /*!< Bit mask for SDHC_AC12ERR_AC12IE. */ #define BS_SDHC_AC12ERR_AC12IE (1U) /*!< Bit field size in bits for SDHC_AC12ERR_AC12IE. */ /*! @brief Read current value of the SDHC_AC12ERR_AC12IE field. */ #define BR_SDHC_AC12ERR_AC12IE(x) (BITBAND_ACCESS32(HW_SDHC_AC12ERR_ADDR(x), BP_SDHC_AC12ERR_AC12IE)) /*@}*/ /*! * @name Register SDHC_AC12ERR, field CNIBAC12E[7] (RO) * * Setting this bit to 1 means CMD_wo_DAT is not executed due to an auto CMD12 * error (D04-D01) in this register. * * Values: * - 0 - No error. * - 1 - Not issued. */ /*@{*/ #define BP_SDHC_AC12ERR_CNIBAC12E (7U) /*!< Bit position for SDHC_AC12ERR_CNIBAC12E. */ #define BM_SDHC_AC12ERR_CNIBAC12E (0x00000080U) /*!< Bit mask for SDHC_AC12ERR_CNIBAC12E. */ #define BS_SDHC_AC12ERR_CNIBAC12E (1U) /*!< Bit field size in bits for SDHC_AC12ERR_CNIBAC12E. */ /*! @brief Read current value of the SDHC_AC12ERR_CNIBAC12E field. */ #define BR_SDHC_AC12ERR_CNIBAC12E(x) (BITBAND_ACCESS32(HW_SDHC_AC12ERR_ADDR(x), BP_SDHC_AC12ERR_CNIBAC12E)) /*@}*/ /******************************************************************************* * HW_SDHC_HTCAPBLT - Host Controller Capabilities ******************************************************************************/ /*! * @brief HW_SDHC_HTCAPBLT - Host Controller Capabilities (RO) * * Reset value: 0x07F30000U * * This register provides the host driver with information specific to the SDHC * implementation. The value in this register is the power-on-reset value, and * does not change with a software reset. Any write to this register is ignored. */ typedef union _hw_sdhc_htcapblt { uint32_t U; struct _hw_sdhc_htcapblt_bitfields { uint32_t RESERVED0 : 16; /*!< [15:0] */ uint32_t MBL : 3; /*!< [18:16] Max Block Length */ uint32_t RESERVED1 : 1; /*!< [19] */ uint32_t ADMAS : 1; /*!< [20] ADMA Support */ uint32_t HSS : 1; /*!< [21] High Speed Support */ uint32_t DMAS : 1; /*!< [22] DMA Support */ uint32_t SRS : 1; /*!< [23] Suspend/Resume Support */ uint32_t VS33 : 1; /*!< [24] Voltage Support 3.3 V */ uint32_t RESERVED2 : 7; /*!< [31:25] */ } B; } hw_sdhc_htcapblt_t; /*! * @name Constants and macros for entire SDHC_HTCAPBLT register */ /*@{*/ #define HW_SDHC_HTCAPBLT_ADDR(x) ((x) + 0x40U) #define HW_SDHC_HTCAPBLT(x) (*(__I hw_sdhc_htcapblt_t *) HW_SDHC_HTCAPBLT_ADDR(x)) #define HW_SDHC_HTCAPBLT_RD(x) (HW_SDHC_HTCAPBLT(x).U) /*@}*/ /* * Constants & macros for individual SDHC_HTCAPBLT bitfields */ /*! * @name Register SDHC_HTCAPBLT, field MBL[18:16] (RO) * * This value indicates the maximum block size that the host driver can read and * write to the buffer in the SDHC. The buffer shall transfer block size without * wait cycles. * * Values: * - 000 - 512 bytes * - 001 - 1024 bytes * - 010 - 2048 bytes * - 011 - 4096 bytes */ /*@{*/ #define BP_SDHC_HTCAPBLT_MBL (16U) /*!< Bit position for SDHC_HTCAPBLT_MBL. */ #define BM_SDHC_HTCAPBLT_MBL (0x00070000U) /*!< Bit mask for SDHC_HTCAPBLT_MBL. */ #define BS_SDHC_HTCAPBLT_MBL (3U) /*!< Bit field size in bits for SDHC_HTCAPBLT_MBL. */ /*! @brief Read current value of the SDHC_HTCAPBLT_MBL field. */ #define BR_SDHC_HTCAPBLT_MBL(x) (HW_SDHC_HTCAPBLT(x).B.MBL) /*@}*/ /*! * @name Register SDHC_HTCAPBLT, field ADMAS[20] (RO) * * This bit indicates whether the SDHC supports the ADMA feature. * * Values: * - 0 - Advanced DMA not supported. * - 1 - Advanced DMA supported. */ /*@{*/ #define BP_SDHC_HTCAPBLT_ADMAS (20U) /*!< Bit position for SDHC_HTCAPBLT_ADMAS. */ #define BM_SDHC_HTCAPBLT_ADMAS (0x00100000U) /*!< Bit mask for SDHC_HTCAPBLT_ADMAS. */ #define BS_SDHC_HTCAPBLT_ADMAS (1U) /*!< Bit field size in bits for SDHC_HTCAPBLT_ADMAS. */ /*! @brief Read current value of the SDHC_HTCAPBLT_ADMAS field. */ #define BR_SDHC_HTCAPBLT_ADMAS(x) (BITBAND_ACCESS32(HW_SDHC_HTCAPBLT_ADDR(x), BP_SDHC_HTCAPBLT_ADMAS)) /*@}*/ /*! * @name Register SDHC_HTCAPBLT, field HSS[21] (RO) * * This bit indicates whether the SDHC supports high speed mode and the host * system can supply a SD Clock frequency from 25 MHz to 50 MHz. * * Values: * - 0 - High speed not supported. * - 1 - High speed supported. */ /*@{*/ #define BP_SDHC_HTCAPBLT_HSS (21U) /*!< Bit position for SDHC_HTCAPBLT_HSS. */ #define BM_SDHC_HTCAPBLT_HSS (0x00200000U) /*!< Bit mask for SDHC_HTCAPBLT_HSS. */ #define BS_SDHC_HTCAPBLT_HSS (1U) /*!< Bit field size in bits for SDHC_HTCAPBLT_HSS. */ /*! @brief Read current value of the SDHC_HTCAPBLT_HSS field. */ #define BR_SDHC_HTCAPBLT_HSS(x) (BITBAND_ACCESS32(HW_SDHC_HTCAPBLT_ADDR(x), BP_SDHC_HTCAPBLT_HSS)) /*@}*/ /*! * @name Register SDHC_HTCAPBLT, field DMAS[22] (RO) * * This bit indicates whether the SDHC is capable of using the internal DMA to * transfer data between system memory and the data buffer directly. * * Values: * - 0 - DMA not supported. * - 1 - DMA supported. */ /*@{*/ #define BP_SDHC_HTCAPBLT_DMAS (22U) /*!< Bit position for SDHC_HTCAPBLT_DMAS. */ #define BM_SDHC_HTCAPBLT_DMAS (0x00400000U) /*!< Bit mask for SDHC_HTCAPBLT_DMAS. */ #define BS_SDHC_HTCAPBLT_DMAS (1U) /*!< Bit field size in bits for SDHC_HTCAPBLT_DMAS. */ /*! @brief Read current value of the SDHC_HTCAPBLT_DMAS field. */ #define BR_SDHC_HTCAPBLT_DMAS(x) (BITBAND_ACCESS32(HW_SDHC_HTCAPBLT_ADDR(x), BP_SDHC_HTCAPBLT_DMAS)) /*@}*/ /*! * @name Register SDHC_HTCAPBLT, field SRS[23] (RO) * * This bit indicates whether the SDHC supports suspend / resume functionality. * If this bit is 0, the suspend and resume mechanism, as well as the read Wwait, * are not supported, and the host driver shall not issue either suspend or * resume commands. * * Values: * - 0 - Not supported. * - 1 - Supported. */ /*@{*/ #define BP_SDHC_HTCAPBLT_SRS (23U) /*!< Bit position for SDHC_HTCAPBLT_SRS. */ #define BM_SDHC_HTCAPBLT_SRS (0x00800000U) /*!< Bit mask for SDHC_HTCAPBLT_SRS. */ #define BS_SDHC_HTCAPBLT_SRS (1U) /*!< Bit field size in bits for SDHC_HTCAPBLT_SRS. */ /*! @brief Read current value of the SDHC_HTCAPBLT_SRS field. */ #define BR_SDHC_HTCAPBLT_SRS(x) (BITBAND_ACCESS32(HW_SDHC_HTCAPBLT_ADDR(x), BP_SDHC_HTCAPBLT_SRS)) /*@}*/ /*! * @name Register SDHC_HTCAPBLT, field VS33[24] (RO) * * This bit shall depend on the host system ability. * * Values: * - 0 - 3.3 V not supported. * - 1 - 3.3 V supported. */ /*@{*/ #define BP_SDHC_HTCAPBLT_VS33 (24U) /*!< Bit position for SDHC_HTCAPBLT_VS33. */ #define BM_SDHC_HTCAPBLT_VS33 (0x01000000U) /*!< Bit mask for SDHC_HTCAPBLT_VS33. */ #define BS_SDHC_HTCAPBLT_VS33 (1U) /*!< Bit field size in bits for SDHC_HTCAPBLT_VS33. */ /*! @brief Read current value of the SDHC_HTCAPBLT_VS33 field. */ #define BR_SDHC_HTCAPBLT_VS33(x) (BITBAND_ACCESS32(HW_SDHC_HTCAPBLT_ADDR(x), BP_SDHC_HTCAPBLT_VS33)) /*@}*/ /******************************************************************************* * HW_SDHC_WML - Watermark Level Register ******************************************************************************/ /*! * @brief HW_SDHC_WML - Watermark Level Register (RW) * * Reset value: 0x00100010U * * Both write and read watermark levels (FIFO threshold) are configurable. There * value can range from 1 to 128 words. Both write and read burst lengths are * also configurable. There value can range from 1 to 31 words. */ typedef union _hw_sdhc_wml { uint32_t U; struct _hw_sdhc_wml_bitfields { uint32_t RDWML : 8; /*!< [7:0] Read Watermark Level */ uint32_t RESERVED0 : 8; /*!< [15:8] */ uint32_t WRWML : 8; /*!< [23:16] Write Watermark Level */ uint32_t RESERVED1 : 8; /*!< [31:24] */ } B; } hw_sdhc_wml_t; /*! * @name Constants and macros for entire SDHC_WML register */ /*@{*/ #define HW_SDHC_WML_ADDR(x) ((x) + 0x44U) #define HW_SDHC_WML(x) (*(__IO hw_sdhc_wml_t *) HW_SDHC_WML_ADDR(x)) #define HW_SDHC_WML_RD(x) (HW_SDHC_WML(x).U) #define HW_SDHC_WML_WR(x, v) (HW_SDHC_WML(x).U = (v)) #define HW_SDHC_WML_SET(x, v) (HW_SDHC_WML_WR(x, HW_SDHC_WML_RD(x) | (v))) #define HW_SDHC_WML_CLR(x, v) (HW_SDHC_WML_WR(x, HW_SDHC_WML_RD(x) & ~(v))) #define HW_SDHC_WML_TOG(x, v) (HW_SDHC_WML_WR(x, HW_SDHC_WML_RD(x) ^ (v))) /*@}*/ /* * Constants & macros for individual SDHC_WML bitfields */ /*! * @name Register SDHC_WML, field RDWML[7:0] (RW) * * The number of words used as the watermark level (FIFO threshold) in a DMA * read operation. Also the number of words as a sequence of read bursts in * back-to-back mode. The maximum legal value for the read water mark level is 128. */ /*@{*/ #define BP_SDHC_WML_RDWML (0U) /*!< Bit position for SDHC_WML_RDWML. */ #define BM_SDHC_WML_RDWML (0x000000FFU) /*!< Bit mask for SDHC_WML_RDWML. */ #define BS_SDHC_WML_RDWML (8U) /*!< Bit field size in bits for SDHC_WML_RDWML. */ /*! @brief Read current value of the SDHC_WML_RDWML field. */ #define BR_SDHC_WML_RDWML(x) (HW_SDHC_WML(x).B.RDWML) /*! @brief Format value for bitfield SDHC_WML_RDWML. */ #define BF_SDHC_WML_RDWML(v) ((uint32_t)((uint32_t)(v) << BP_SDHC_WML_RDWML) & BM_SDHC_WML_RDWML) /*! @brief Set the RDWML field to a new value. */ #define BW_SDHC_WML_RDWML(x, v) (HW_SDHC_WML_WR(x, (HW_SDHC_WML_RD(x) & ~BM_SDHC_WML_RDWML) | BF_SDHC_WML_RDWML(v))) /*@}*/ /*! * @name Register SDHC_WML, field WRWML[23:16] (RW) * * The number of words used as the watermark level (FIFO threshold) in a DMA * write operation. Also the number of words as a sequence of write bursts in * back-to-back mode. The maximum legal value for the write watermark level is 128. */ /*@{*/ #define BP_SDHC_WML_WRWML (16U) /*!< Bit position for SDHC_WML_WRWML. */ #define BM_SDHC_WML_WRWML (0x00FF0000U) /*!< Bit mask for SDHC_WML_WRWML. */ #define BS_SDHC_WML_WRWML (8U) /*!< Bit field size in bits for SDHC_WML_WRWML. */ /*! @brief Read current value of the SDHC_WML_WRWML field. */ #define BR_SDHC_WML_WRWML(x) (HW_SDHC_WML(x).B.WRWML) /*! @brief Format value for bitfield SDHC_WML_WRWML. */ #define BF_SDHC_WML_WRWML(v) ((uint32_t)((uint32_t)(v) << BP_SDHC_WML_WRWML) & BM_SDHC_WML_WRWML) /*! @brief Set the WRWML field to a new value. */ #define BW_SDHC_WML_WRWML(x, v) (HW_SDHC_WML_WR(x, (HW_SDHC_WML_RD(x) & ~BM_SDHC_WML_WRWML) | BF_SDHC_WML_WRWML(v))) /*@}*/ /******************************************************************************* * HW_SDHC_FEVT - Force Event register ******************************************************************************/ /*! * @brief HW_SDHC_FEVT - Force Event register (WO) * * Reset value: 0x00000000U * * The Force Event (FEVT) register is not a physically implemented register. * Rather, it is an address at which the Interrupt Status register can be written if * the corresponding bit of the Interrupt Status Enable register is set. This * register is a write only register and writing 0 to it has no effect. Writing 1 * to this register actually sets the corresponding bit of Interrupt Status * register. A read from this register always results in 0's. To change the * corresponding status bits in the interrupt status register, make sure to set * SYSCTL[IPGEN] so that bus clock is always active. Forcing a card interrupt will generate a * short pulse on the DAT[1] line, and the driver may treat this interrupt as a * normal interrupt. The interrupt service routine may skip polling the card * interrupt factor as the interrupt is selfcleared. */ typedef union _hw_sdhc_fevt { uint32_t U; struct _hw_sdhc_fevt_bitfields { uint32_t AC12NE : 1; /*!< [0] Force Event Auto Command 12 Not * Executed */ uint32_t AC12TOE : 1; /*!< [1] Force Event Auto Command 12 Time Out * Error */ uint32_t AC12CE : 1; /*!< [2] Force Event Auto Command 12 CRC Error */ uint32_t AC12EBE : 1; /*!< [3] Force Event Auto Command 12 End Bit * Error */ uint32_t AC12IE : 1; /*!< [4] Force Event Auto Command 12 Index Error * */ uint32_t RESERVED0 : 2; /*!< [6:5] */ uint32_t CNIBAC12E : 1; /*!< [7] Force Event Command Not Executed By * Auto Command 12 Error */ uint32_t RESERVED1 : 8; /*!< [15:8] */ uint32_t CTOE : 1; /*!< [16] Force Event Command Time Out Error */ uint32_t CCE : 1; /*!< [17] Force Event Command CRC Error */ uint32_t CEBE : 1; /*!< [18] Force Event Command End Bit Error */ uint32_t CIE : 1; /*!< [19] Force Event Command Index Error */ uint32_t DTOE : 1; /*!< [20] Force Event Data Time Out Error */ uint32_t DCE : 1; /*!< [21] Force Event Data CRC Error */ uint32_t DEBE : 1; /*!< [22] Force Event Data End Bit Error */ uint32_t RESERVED2 : 1; /*!< [23] */ uint32_t AC12E : 1; /*!< [24] Force Event Auto Command 12 Error */ uint32_t RESERVED3 : 3; /*!< [27:25] */ uint32_t DMAE : 1; /*!< [28] Force Event DMA Error */ uint32_t RESERVED4 : 2; /*!< [30:29] */ uint32_t CINT : 1; /*!< [31] Force Event Card Interrupt */ } B; } hw_sdhc_fevt_t; /*! * @name Constants and macros for entire SDHC_FEVT register */ /*@{*/ #define HW_SDHC_FEVT_ADDR(x) ((x) + 0x50U) #define HW_SDHC_FEVT(x) (*(__O hw_sdhc_fevt_t *) HW_SDHC_FEVT_ADDR(x)) #define HW_SDHC_FEVT_RD(x) (HW_SDHC_FEVT(x).U) #define HW_SDHC_FEVT_WR(x, v) (HW_SDHC_FEVT(x).U = (v)) /*@}*/ /* * Constants & macros for individual SDHC_FEVT bitfields */ /*! * @name Register SDHC_FEVT, field AC12NE[0] (WORZ) * * Forces AC12ERR[AC12NE] to be set. */ /*@{*/ #define BP_SDHC_FEVT_AC12NE (0U) /*!< Bit position for SDHC_FEVT_AC12NE. */ #define BM_SDHC_FEVT_AC12NE (0x00000001U) /*!< Bit mask for SDHC_FEVT_AC12NE. */ #define BS_SDHC_FEVT_AC12NE (1U) /*!< Bit field size in bits for SDHC_FEVT_AC12NE. */ /*! @brief Format value for bitfield SDHC_FEVT_AC12NE. */ #define BF_SDHC_FEVT_AC12NE(v) ((uint32_t)((uint32_t)(v) << BP_SDHC_FEVT_AC12NE) & BM_SDHC_FEVT_AC12NE) /*! @brief Set the AC12NE field to a new value. */ #define BW_SDHC_FEVT_AC12NE(x, v) (BITBAND_ACCESS32(HW_SDHC_FEVT_ADDR(x), BP_SDHC_FEVT_AC12NE) = (v)) /*@}*/ /*! * @name Register SDHC_FEVT, field AC12TOE[1] (WORZ) * * Forces AC12ERR[AC12TOE] to be set. */ /*@{*/ #define BP_SDHC_FEVT_AC12TOE (1U) /*!< Bit position for SDHC_FEVT_AC12TOE. */ #define BM_SDHC_FEVT_AC12TOE (0x00000002U) /*!< Bit mask for SDHC_FEVT_AC12TOE. */ #define BS_SDHC_FEVT_AC12TOE (1U) /*!< Bit field size in bits for SDHC_FEVT_AC12TOE. */ /*! @brief Format value for bitfield SDHC_FEVT_AC12TOE. */ #define BF_SDHC_FEVT_AC12TOE(v) ((uint32_t)((uint32_t)(v) << BP_SDHC_FEVT_AC12TOE) & BM_SDHC_FEVT_AC12TOE) /*! @brief Set the AC12TOE field to a new value. */ #define BW_SDHC_FEVT_AC12TOE(x, v) (BITBAND_ACCESS32(HW_SDHC_FEVT_ADDR(x), BP_SDHC_FEVT_AC12TOE) = (v)) /*@}*/ /*! * @name Register SDHC_FEVT, field AC12CE[2] (WORZ) * * Forces AC12ERR[AC12CE] to be set. */ /*@{*/ #define BP_SDHC_FEVT_AC12CE (2U) /*!< Bit position for SDHC_FEVT_AC12CE. */ #define BM_SDHC_FEVT_AC12CE (0x00000004U) /*!< Bit mask for SDHC_FEVT_AC12CE. */ #define BS_SDHC_FEVT_AC12CE (1U) /*!< Bit field size in bits for SDHC_FEVT_AC12CE. */ /*! @brief Format value for bitfield SDHC_FEVT_AC12CE. */ #define BF_SDHC_FEVT_AC12CE(v) ((uint32_t)((uint32_t)(v) << BP_SDHC_FEVT_AC12CE) & BM_SDHC_FEVT_AC12CE) /*! @brief Set the AC12CE field to a new value. */ #define BW_SDHC_FEVT_AC12CE(x, v) (BITBAND_ACCESS32(HW_SDHC_FEVT_ADDR(x), BP_SDHC_FEVT_AC12CE) = (v)) /*@}*/ /*! * @name Register SDHC_FEVT, field AC12EBE[3] (WORZ) * * Forces AC12ERR[AC12EBE] to be set. */ /*@{*/ #define BP_SDHC_FEVT_AC12EBE (3U) /*!< Bit position for SDHC_FEVT_AC12EBE. */ #define BM_SDHC_FEVT_AC12EBE (0x00000008U) /*!< Bit mask for SDHC_FEVT_AC12EBE. */ #define BS_SDHC_FEVT_AC12EBE (1U) /*!< Bit field size in bits for SDHC_FEVT_AC12EBE. */ /*! @brief Format value for bitfield SDHC_FEVT_AC12EBE. */ #define BF_SDHC_FEVT_AC12EBE(v) ((uint32_t)((uint32_t)(v) << BP_SDHC_FEVT_AC12EBE) & BM_SDHC_FEVT_AC12EBE) /*! @brief Set the AC12EBE field to a new value. */ #define BW_SDHC_FEVT_AC12EBE(x, v) (BITBAND_ACCESS32(HW_SDHC_FEVT_ADDR(x), BP_SDHC_FEVT_AC12EBE) = (v)) /*@}*/ /*! * @name Register SDHC_FEVT, field AC12IE[4] (WORZ) * * Forces AC12ERR[AC12IE] to be set. */ /*@{*/ #define BP_SDHC_FEVT_AC12IE (4U) /*!< Bit position for SDHC_FEVT_AC12IE. */ #define BM_SDHC_FEVT_AC12IE (0x00000010U) /*!< Bit mask for SDHC_FEVT_AC12IE. */ #define BS_SDHC_FEVT_AC12IE (1U) /*!< Bit field size in bits for SDHC_FEVT_AC12IE. */ /*! @brief Format value for bitfield SDHC_FEVT_AC12IE. */ #define BF_SDHC_FEVT_AC12IE(v) ((uint32_t)((uint32_t)(v) << BP_SDHC_FEVT_AC12IE) & BM_SDHC_FEVT_AC12IE) /*! @brief Set the AC12IE field to a new value. */ #define BW_SDHC_FEVT_AC12IE(x, v) (BITBAND_ACCESS32(HW_SDHC_FEVT_ADDR(x), BP_SDHC_FEVT_AC12IE) = (v)) /*@}*/ /*! * @name Register SDHC_FEVT, field CNIBAC12E[7] (WORZ) * * Forces AC12ERR[CNIBAC12E] to be set. */ /*@{*/ #define BP_SDHC_FEVT_CNIBAC12E (7U) /*!< Bit position for SDHC_FEVT_CNIBAC12E. */ #define BM_SDHC_FEVT_CNIBAC12E (0x00000080U) /*!< Bit mask for SDHC_FEVT_CNIBAC12E. */ #define BS_SDHC_FEVT_CNIBAC12E (1U) /*!< Bit field size in bits for SDHC_FEVT_CNIBAC12E. */ /*! @brief Format value for bitfield SDHC_FEVT_CNIBAC12E. */ #define BF_SDHC_FEVT_CNIBAC12E(v) ((uint32_t)((uint32_t)(v) << BP_SDHC_FEVT_CNIBAC12E) & BM_SDHC_FEVT_CNIBAC12E) /*! @brief Set the CNIBAC12E field to a new value. */ #define BW_SDHC_FEVT_CNIBAC12E(x, v) (BITBAND_ACCESS32(HW_SDHC_FEVT_ADDR(x), BP_SDHC_FEVT_CNIBAC12E) = (v)) /*@}*/ /*! * @name Register SDHC_FEVT, field CTOE[16] (WORZ) * * Forces IRQSTAT[CTOE] to be set. */ /*@{*/ #define BP_SDHC_FEVT_CTOE (16U) /*!< Bit position for SDHC_FEVT_CTOE. */ #define BM_SDHC_FEVT_CTOE (0x00010000U) /*!< Bit mask for SDHC_FEVT_CTOE. */ #define BS_SDHC_FEVT_CTOE (1U) /*!< Bit field size in bits for SDHC_FEVT_CTOE. */ /*! @brief Format value for bitfield SDHC_FEVT_CTOE. */ #define BF_SDHC_FEVT_CTOE(v) ((uint32_t)((uint32_t)(v) << BP_SDHC_FEVT_CTOE) & BM_SDHC_FEVT_CTOE) /*! @brief Set the CTOE field to a new value. */ #define BW_SDHC_FEVT_CTOE(x, v) (BITBAND_ACCESS32(HW_SDHC_FEVT_ADDR(x), BP_SDHC_FEVT_CTOE) = (v)) /*@}*/ /*! * @name Register SDHC_FEVT, field CCE[17] (WORZ) * * Forces IRQSTAT[CCE] to be set. */ /*@{*/ #define BP_SDHC_FEVT_CCE (17U) /*!< Bit position for SDHC_FEVT_CCE. */ #define BM_SDHC_FEVT_CCE (0x00020000U) /*!< Bit mask for SDHC_FEVT_CCE. */ #define BS_SDHC_FEVT_CCE (1U) /*!< Bit field size in bits for SDHC_FEVT_CCE. */ /*! @brief Format value for bitfield SDHC_FEVT_CCE. */ #define BF_SDHC_FEVT_CCE(v) ((uint32_t)((uint32_t)(v) << BP_SDHC_FEVT_CCE) & BM_SDHC_FEVT_CCE) /*! @brief Set the CCE field to a new value. */ #define BW_SDHC_FEVT_CCE(x, v) (BITBAND_ACCESS32(HW_SDHC_FEVT_ADDR(x), BP_SDHC_FEVT_CCE) = (v)) /*@}*/ /*! * @name Register SDHC_FEVT, field CEBE[18] (WORZ) * * Forces IRQSTAT[CEBE] to be set. */ /*@{*/ #define BP_SDHC_FEVT_CEBE (18U) /*!< Bit position for SDHC_FEVT_CEBE. */ #define BM_SDHC_FEVT_CEBE (0x00040000U) /*!< Bit mask for SDHC_FEVT_CEBE. */ #define BS_SDHC_FEVT_CEBE (1U) /*!< Bit field size in bits for SDHC_FEVT_CEBE. */ /*! @brief Format value for bitfield SDHC_FEVT_CEBE. */ #define BF_SDHC_FEVT_CEBE(v) ((uint32_t)((uint32_t)(v) << BP_SDHC_FEVT_CEBE) & BM_SDHC_FEVT_CEBE) /*! @brief Set the CEBE field to a new value. */ #define BW_SDHC_FEVT_CEBE(x, v) (BITBAND_ACCESS32(HW_SDHC_FEVT_ADDR(x), BP_SDHC_FEVT_CEBE) = (v)) /*@}*/ /*! * @name Register SDHC_FEVT, field CIE[19] (WORZ) * * Forces IRQSTAT[CCE] to be set. */ /*@{*/ #define BP_SDHC_FEVT_CIE (19U) /*!< Bit position for SDHC_FEVT_CIE. */ #define BM_SDHC_FEVT_CIE (0x00080000U) /*!< Bit mask for SDHC_FEVT_CIE. */ #define BS_SDHC_FEVT_CIE (1U) /*!< Bit field size in bits for SDHC_FEVT_CIE. */ /*! @brief Format value for bitfield SDHC_FEVT_CIE. */ #define BF_SDHC_FEVT_CIE(v) ((uint32_t)((uint32_t)(v) << BP_SDHC_FEVT_CIE) & BM_SDHC_FEVT_CIE) /*! @brief Set the CIE field to a new value. */ #define BW_SDHC_FEVT_CIE(x, v) (BITBAND_ACCESS32(HW_SDHC_FEVT_ADDR(x), BP_SDHC_FEVT_CIE) = (v)) /*@}*/ /*! * @name Register SDHC_FEVT, field DTOE[20] (WORZ) * * Forces IRQSTAT[DTOE] to be set. */ /*@{*/ #define BP_SDHC_FEVT_DTOE (20U) /*!< Bit position for SDHC_FEVT_DTOE. */ #define BM_SDHC_FEVT_DTOE (0x00100000U) /*!< Bit mask for SDHC_FEVT_DTOE. */ #define BS_SDHC_FEVT_DTOE (1U) /*!< Bit field size in bits for SDHC_FEVT_DTOE. */ /*! @brief Format value for bitfield SDHC_FEVT_DTOE. */ #define BF_SDHC_FEVT_DTOE(v) ((uint32_t)((uint32_t)(v) << BP_SDHC_FEVT_DTOE) & BM_SDHC_FEVT_DTOE) /*! @brief Set the DTOE field to a new value. */ #define BW_SDHC_FEVT_DTOE(x, v) (BITBAND_ACCESS32(HW_SDHC_FEVT_ADDR(x), BP_SDHC_FEVT_DTOE) = (v)) /*@}*/ /*! * @name Register SDHC_FEVT, field DCE[21] (WORZ) * * Forces IRQSTAT[DCE] to be set. */ /*@{*/ #define BP_SDHC_FEVT_DCE (21U) /*!< Bit position for SDHC_FEVT_DCE. */ #define BM_SDHC_FEVT_DCE (0x00200000U) /*!< Bit mask for SDHC_FEVT_DCE. */ #define BS_SDHC_FEVT_DCE (1U) /*!< Bit field size in bits for SDHC_FEVT_DCE. */ /*! @brief Format value for bitfield SDHC_FEVT_DCE. */ #define BF_SDHC_FEVT_DCE(v) ((uint32_t)((uint32_t)(v) << BP_SDHC_FEVT_DCE) & BM_SDHC_FEVT_DCE) /*! @brief Set the DCE field to a new value. */ #define BW_SDHC_FEVT_DCE(x, v) (BITBAND_ACCESS32(HW_SDHC_FEVT_ADDR(x), BP_SDHC_FEVT_DCE) = (v)) /*@}*/ /*! * @name Register SDHC_FEVT, field DEBE[22] (WORZ) * * Forces IRQSTAT[DEBE] to be set. */ /*@{*/ #define BP_SDHC_FEVT_DEBE (22U) /*!< Bit position for SDHC_FEVT_DEBE. */ #define BM_SDHC_FEVT_DEBE (0x00400000U) /*!< Bit mask for SDHC_FEVT_DEBE. */ #define BS_SDHC_FEVT_DEBE (1U) /*!< Bit field size in bits for SDHC_FEVT_DEBE. */ /*! @brief Format value for bitfield SDHC_FEVT_DEBE. */ #define BF_SDHC_FEVT_DEBE(v) ((uint32_t)((uint32_t)(v) << BP_SDHC_FEVT_DEBE) & BM_SDHC_FEVT_DEBE) /*! @brief Set the DEBE field to a new value. */ #define BW_SDHC_FEVT_DEBE(x, v) (BITBAND_ACCESS32(HW_SDHC_FEVT_ADDR(x), BP_SDHC_FEVT_DEBE) = (v)) /*@}*/ /*! * @name Register SDHC_FEVT, field AC12E[24] (WORZ) * * Forces IRQSTAT[AC12E] to be set. */ /*@{*/ #define BP_SDHC_FEVT_AC12E (24U) /*!< Bit position for SDHC_FEVT_AC12E. */ #define BM_SDHC_FEVT_AC12E (0x01000000U) /*!< Bit mask for SDHC_FEVT_AC12E. */ #define BS_SDHC_FEVT_AC12E (1U) /*!< Bit field size in bits for SDHC_FEVT_AC12E. */ /*! @brief Format value for bitfield SDHC_FEVT_AC12E. */ #define BF_SDHC_FEVT_AC12E(v) ((uint32_t)((uint32_t)(v) << BP_SDHC_FEVT_AC12E) & BM_SDHC_FEVT_AC12E) /*! @brief Set the AC12E field to a new value. */ #define BW_SDHC_FEVT_AC12E(x, v) (BITBAND_ACCESS32(HW_SDHC_FEVT_ADDR(x), BP_SDHC_FEVT_AC12E) = (v)) /*@}*/ /*! * @name Register SDHC_FEVT, field DMAE[28] (WORZ) * * Forces the DMAE bit of Interrupt Status Register to be set. */ /*@{*/ #define BP_SDHC_FEVT_DMAE (28U) /*!< Bit position for SDHC_FEVT_DMAE. */ #define BM_SDHC_FEVT_DMAE (0x10000000U) /*!< Bit mask for SDHC_FEVT_DMAE. */ #define BS_SDHC_FEVT_DMAE (1U) /*!< Bit field size in bits for SDHC_FEVT_DMAE. */ /*! @brief Format value for bitfield SDHC_FEVT_DMAE. */ #define BF_SDHC_FEVT_DMAE(v) ((uint32_t)((uint32_t)(v) << BP_SDHC_FEVT_DMAE) & BM_SDHC_FEVT_DMAE) /*! @brief Set the DMAE field to a new value. */ #define BW_SDHC_FEVT_DMAE(x, v) (BITBAND_ACCESS32(HW_SDHC_FEVT_ADDR(x), BP_SDHC_FEVT_DMAE) = (v)) /*@}*/ /*! * @name Register SDHC_FEVT, field CINT[31] (WORZ) * * Writing 1 to this bit generates a short low-level pulse on the internal * DAT[1] line, as if a self-clearing interrupt was received from the external card. * If enabled, the CINT bit will be set and the interrupt service routine may * treat this interrupt as a normal interrupt from the external card. */ /*@{*/ #define BP_SDHC_FEVT_CINT (31U) /*!< Bit position for SDHC_FEVT_CINT. */ #define BM_SDHC_FEVT_CINT (0x80000000U) /*!< Bit mask for SDHC_FEVT_CINT. */ #define BS_SDHC_FEVT_CINT (1U) /*!< Bit field size in bits for SDHC_FEVT_CINT. */ /*! @brief Format value for bitfield SDHC_FEVT_CINT. */ #define BF_SDHC_FEVT_CINT(v) ((uint32_t)((uint32_t)(v) << BP_SDHC_FEVT_CINT) & BM_SDHC_FEVT_CINT) /*! @brief Set the CINT field to a new value. */ #define BW_SDHC_FEVT_CINT(x, v) (BITBAND_ACCESS32(HW_SDHC_FEVT_ADDR(x), BP_SDHC_FEVT_CINT) = (v)) /*@}*/ /******************************************************************************* * HW_SDHC_ADMAES - ADMA Error Status register ******************************************************************************/ /*! * @brief HW_SDHC_ADMAES - ADMA Error Status register (RO) * * Reset value: 0x00000000U * * When an ADMA error interrupt has occurred, the ADMA Error States field in * this register holds the ADMA state and the ADMA System Address register holds the * address around the error descriptor. For recovering from this error, the host * driver requires the ADMA state to identify the error descriptor address as * follows: ST_STOP: Previous location set in the ADMA System Address register is * the error descriptor address. ST_FDS: Current location set in the ADMA System * Address register is the error descriptor address. ST_CADR: This state is never * set because it only increments the descriptor pointer and doesn't generate an * ADMA error. ST_TFR: Previous location set in the ADMA System Address register * is the error descriptor address. In case of a write operation, the host driver * must use the ACMD22 to get the number of the written block, rather than using * this information, because unwritten data may exist in the host controller. * The host controller generates the ADMA error interrupt when it detects invalid * descriptor data (valid = 0) in the ST_FDS state. The host driver can * distinguish this error by reading the valid bit of the error descriptor. ADMA Error * State coding D01-D00 ADMA Error State when error has occurred Contents of ADMA * System Address register 00 ST_STOP (Stop DMA) Holds the address of the next * executable descriptor command 01 ST_FDS (fetch descriptor) Holds the valid * descriptor address 10 ST_CADR (change address) No ADMA error is generated 11 ST_TFR * (Transfer Data) Holds the address of the next executable descriptor command */ typedef union _hw_sdhc_admaes { uint32_t U; struct _hw_sdhc_admaes_bitfields { uint32_t ADMAES : 2; /*!< [1:0] ADMA Error State (When ADMA Error Is * Occurred.) */ uint32_t ADMALME : 1; /*!< [2] ADMA Length Mismatch Error */ uint32_t ADMADCE : 1; /*!< [3] ADMA Descriptor Error */ uint32_t RESERVED0 : 28; /*!< [31:4] */ } B; } hw_sdhc_admaes_t; /*! * @name Constants and macros for entire SDHC_ADMAES register */ /*@{*/ #define HW_SDHC_ADMAES_ADDR(x) ((x) + 0x54U) #define HW_SDHC_ADMAES(x) (*(__I hw_sdhc_admaes_t *) HW_SDHC_ADMAES_ADDR(x)) #define HW_SDHC_ADMAES_RD(x) (HW_SDHC_ADMAES(x).U) /*@}*/ /* * Constants & macros for individual SDHC_ADMAES bitfields */ /*! * @name Register SDHC_ADMAES, field ADMAES[1:0] (RO) * * Indicates the state of the ADMA when an error has occurred during an ADMA * data transfer. */ /*@{*/ #define BP_SDHC_ADMAES_ADMAES (0U) /*!< Bit position for SDHC_ADMAES_ADMAES. */ #define BM_SDHC_ADMAES_ADMAES (0x00000003U) /*!< Bit mask for SDHC_ADMAES_ADMAES. */ #define BS_SDHC_ADMAES_ADMAES (2U) /*!< Bit field size in bits for SDHC_ADMAES_ADMAES. */ /*! @brief Read current value of the SDHC_ADMAES_ADMAES field. */ #define BR_SDHC_ADMAES_ADMAES(x) (HW_SDHC_ADMAES(x).B.ADMAES) /*@}*/ /*! * @name Register SDHC_ADMAES, field ADMALME[2] (RO) * * This error occurs in the following 2 cases: While the block count enable is * being set, the total data length specified by the descriptor table is different * from that specified by the block count and block length. Total data length * can not be divided by the block length. * * Values: * - 0 - No error. * - 1 - Error. */ /*@{*/ #define BP_SDHC_ADMAES_ADMALME (2U) /*!< Bit position for SDHC_ADMAES_ADMALME. */ #define BM_SDHC_ADMAES_ADMALME (0x00000004U) /*!< Bit mask for SDHC_ADMAES_ADMALME. */ #define BS_SDHC_ADMAES_ADMALME (1U) /*!< Bit field size in bits for SDHC_ADMAES_ADMALME. */ /*! @brief Read current value of the SDHC_ADMAES_ADMALME field. */ #define BR_SDHC_ADMAES_ADMALME(x) (BITBAND_ACCESS32(HW_SDHC_ADMAES_ADDR(x), BP_SDHC_ADMAES_ADMALME)) /*@}*/ /*! * @name Register SDHC_ADMAES, field ADMADCE[3] (RO) * * This error occurs when an invalid descriptor is fetched by ADMA. * * Values: * - 0 - No error. * - 1 - Error. */ /*@{*/ #define BP_SDHC_ADMAES_ADMADCE (3U) /*!< Bit position for SDHC_ADMAES_ADMADCE. */ #define BM_SDHC_ADMAES_ADMADCE (0x00000008U) /*!< Bit mask for SDHC_ADMAES_ADMADCE. */ #define BS_SDHC_ADMAES_ADMADCE (1U) /*!< Bit field size in bits for SDHC_ADMAES_ADMADCE. */ /*! @brief Read current value of the SDHC_ADMAES_ADMADCE field. */ #define BR_SDHC_ADMAES_ADMADCE(x) (BITBAND_ACCESS32(HW_SDHC_ADMAES_ADDR(x), BP_SDHC_ADMAES_ADMADCE)) /*@}*/ /******************************************************************************* * HW_SDHC_ADSADDR - ADMA System Addressregister ******************************************************************************/ /*! * @brief HW_SDHC_ADSADDR - ADMA System Addressregister (RW) * * Reset value: 0x00000000U * * This register contains the physical system memory address used for ADMA * transfers. */ typedef union _hw_sdhc_adsaddr { uint32_t U; struct _hw_sdhc_adsaddr_bitfields { uint32_t RESERVED0 : 2; /*!< [1:0] */ uint32_t ADSADDR : 30; /*!< [31:2] ADMA System Address */ } B; } hw_sdhc_adsaddr_t; /*! * @name Constants and macros for entire SDHC_ADSADDR register */ /*@{*/ #define HW_SDHC_ADSADDR_ADDR(x) ((x) + 0x58U) #define HW_SDHC_ADSADDR(x) (*(__IO hw_sdhc_adsaddr_t *) HW_SDHC_ADSADDR_ADDR(x)) #define HW_SDHC_ADSADDR_RD(x) (HW_SDHC_ADSADDR(x).U) #define HW_SDHC_ADSADDR_WR(x, v) (HW_SDHC_ADSADDR(x).U = (v)) #define HW_SDHC_ADSADDR_SET(x, v) (HW_SDHC_ADSADDR_WR(x, HW_SDHC_ADSADDR_RD(x) | (v))) #define HW_SDHC_ADSADDR_CLR(x, v) (HW_SDHC_ADSADDR_WR(x, HW_SDHC_ADSADDR_RD(x) & ~(v))) #define HW_SDHC_ADSADDR_TOG(x, v) (HW_SDHC_ADSADDR_WR(x, HW_SDHC_ADSADDR_RD(x) ^ (v))) /*@}*/ /* * Constants & macros for individual SDHC_ADSADDR bitfields */ /*! * @name Register SDHC_ADSADDR, field ADSADDR[31:2] (RW) * * Holds the word address of the executing command in the descriptor table. At * the start of ADMA, the host driver shall set the start address of the * Descriptor table. The ADMA engine increments this register address whenever fetching a * descriptor command. When the ADMA is stopped at the block gap, this register * indicates the address of the next executable descriptor command. When the ADMA * error interrupt is generated, this register shall hold the valid descriptor * address depending on the ADMA state. The lower 2 bits of this register is tied * to '0' so the ADMA address is always word-aligned. Because this register * supports dynamic address reflecting, when TC bit is set, it automatically alters the * value of internal address counter, so SW cannot change this register when TC * bit is set. */ /*@{*/ #define BP_SDHC_ADSADDR_ADSADDR (2U) /*!< Bit position for SDHC_ADSADDR_ADSADDR. */ #define BM_SDHC_ADSADDR_ADSADDR (0xFFFFFFFCU) /*!< Bit mask for SDHC_ADSADDR_ADSADDR. */ #define BS_SDHC_ADSADDR_ADSADDR (30U) /*!< Bit field size in bits for SDHC_ADSADDR_ADSADDR. */ /*! @brief Read current value of the SDHC_ADSADDR_ADSADDR field. */ #define BR_SDHC_ADSADDR_ADSADDR(x) (HW_SDHC_ADSADDR(x).B.ADSADDR) /*! @brief Format value for bitfield SDHC_ADSADDR_ADSADDR. */ #define BF_SDHC_ADSADDR_ADSADDR(v) ((uint32_t)((uint32_t)(v) << BP_SDHC_ADSADDR_ADSADDR) & BM_SDHC_ADSADDR_ADSADDR) /*! @brief Set the ADSADDR field to a new value. */ #define BW_SDHC_ADSADDR_ADSADDR(x, v) (HW_SDHC_ADSADDR_WR(x, (HW_SDHC_ADSADDR_RD(x) & ~BM_SDHC_ADSADDR_ADSADDR) | BF_SDHC_ADSADDR_ADSADDR(v))) /*@}*/ /******************************************************************************* * HW_SDHC_VENDOR - Vendor Specific register ******************************************************************************/ /*! * @brief HW_SDHC_VENDOR - Vendor Specific register (RW) * * Reset value: 0x00000001U * * This register contains the vendor-specific control/status register. */ typedef union _hw_sdhc_vendor { uint32_t U; struct _hw_sdhc_vendor_bitfields { uint32_t EXTDMAEN : 1; /*!< [0] External DMA Request Enable */ uint32_t EXBLKNU : 1; /*!< [1] Exact Block Number Block Read Enable * For SDIO CMD53 */ uint32_t RESERVED0 : 14; /*!< [15:2] */ uint32_t INTSTVAL : 8; /*!< [23:16] Internal State Value */ uint32_t RESERVED1 : 8; /*!< [31:24] */ } B; } hw_sdhc_vendor_t; /*! * @name Constants and macros for entire SDHC_VENDOR register */ /*@{*/ #define HW_SDHC_VENDOR_ADDR(x) ((x) + 0xC0U) #define HW_SDHC_VENDOR(x) (*(__IO hw_sdhc_vendor_t *) HW_SDHC_VENDOR_ADDR(x)) #define HW_SDHC_VENDOR_RD(x) (HW_SDHC_VENDOR(x).U) #define HW_SDHC_VENDOR_WR(x, v) (HW_SDHC_VENDOR(x).U = (v)) #define HW_SDHC_VENDOR_SET(x, v) (HW_SDHC_VENDOR_WR(x, HW_SDHC_VENDOR_RD(x) | (v))) #define HW_SDHC_VENDOR_CLR(x, v) (HW_SDHC_VENDOR_WR(x, HW_SDHC_VENDOR_RD(x) & ~(v))) #define HW_SDHC_VENDOR_TOG(x, v) (HW_SDHC_VENDOR_WR(x, HW_SDHC_VENDOR_RD(x) ^ (v))) /*@}*/ /* * Constants & macros for individual SDHC_VENDOR bitfields */ /*! * @name Register SDHC_VENDOR, field EXTDMAEN[0] (RW) * * Enables the request to external DMA. When the internal DMA (either simple DMA * or advanced DMA) is not in use, and this bit is set, SDHC will send out DMA * request when the internal buffer is ready. This bit is particularly useful when * transferring data by CPU polling mode, and it is not allowed to send out the * external DMA request. By default, this bit is set. * * Values: * - 0 - In any scenario, SDHC does not send out the external DMA request. * - 1 - When internal DMA is not active, the external DMA request will be sent * out. */ /*@{*/ #define BP_SDHC_VENDOR_EXTDMAEN (0U) /*!< Bit position for SDHC_VENDOR_EXTDMAEN. */ #define BM_SDHC_VENDOR_EXTDMAEN (0x00000001U) /*!< Bit mask for SDHC_VENDOR_EXTDMAEN. */ #define BS_SDHC_VENDOR_EXTDMAEN (1U) /*!< Bit field size in bits for SDHC_VENDOR_EXTDMAEN. */ /*! @brief Read current value of the SDHC_VENDOR_EXTDMAEN field. */ #define BR_SDHC_VENDOR_EXTDMAEN(x) (BITBAND_ACCESS32(HW_SDHC_VENDOR_ADDR(x), BP_SDHC_VENDOR_EXTDMAEN)) /*! @brief Format value for bitfield SDHC_VENDOR_EXTDMAEN. */ #define BF_SDHC_VENDOR_EXTDMAEN(v) ((uint32_t)((uint32_t)(v) << BP_SDHC_VENDOR_EXTDMAEN) & BM_SDHC_VENDOR_EXTDMAEN) /*! @brief Set the EXTDMAEN field to a new value. */ #define BW_SDHC_VENDOR_EXTDMAEN(x, v) (BITBAND_ACCESS32(HW_SDHC_VENDOR_ADDR(x), BP_SDHC_VENDOR_EXTDMAEN) = (v)) /*@}*/ /*! * @name Register SDHC_VENDOR, field EXBLKNU[1] (RW) * * This bit must be set before S/W issues CMD53 multi-block read with exact * block number. This bit must not be set if the CMD53 multi-block read is not exact * block number. * * Values: * - 0 - None exact block read. * - 1 - Exact block read for SDIO CMD53. */ /*@{*/ #define BP_SDHC_VENDOR_EXBLKNU (1U) /*!< Bit position for SDHC_VENDOR_EXBLKNU. */ #define BM_SDHC_VENDOR_EXBLKNU (0x00000002U) /*!< Bit mask for SDHC_VENDOR_EXBLKNU. */ #define BS_SDHC_VENDOR_EXBLKNU (1U) /*!< Bit field size in bits for SDHC_VENDOR_EXBLKNU. */ /*! @brief Read current value of the SDHC_VENDOR_EXBLKNU field. */ #define BR_SDHC_VENDOR_EXBLKNU(x) (BITBAND_ACCESS32(HW_SDHC_VENDOR_ADDR(x), BP_SDHC_VENDOR_EXBLKNU)) /*! @brief Format value for bitfield SDHC_VENDOR_EXBLKNU. */ #define BF_SDHC_VENDOR_EXBLKNU(v) ((uint32_t)((uint32_t)(v) << BP_SDHC_VENDOR_EXBLKNU) & BM_SDHC_VENDOR_EXBLKNU) /*! @brief Set the EXBLKNU field to a new value. */ #define BW_SDHC_VENDOR_EXBLKNU(x, v) (BITBAND_ACCESS32(HW_SDHC_VENDOR_ADDR(x), BP_SDHC_VENDOR_EXBLKNU) = (v)) /*@}*/ /*! * @name Register SDHC_VENDOR, field INTSTVAL[23:16] (RO) * * Internal state value, reflecting the corresponding state value selected by * Debug Select field. This field is read-only and write to this field does not * have effect. */ /*@{*/ #define BP_SDHC_VENDOR_INTSTVAL (16U) /*!< Bit position for SDHC_VENDOR_INTSTVAL. */ #define BM_SDHC_VENDOR_INTSTVAL (0x00FF0000U) /*!< Bit mask for SDHC_VENDOR_INTSTVAL. */ #define BS_SDHC_VENDOR_INTSTVAL (8U) /*!< Bit field size in bits for SDHC_VENDOR_INTSTVAL. */ /*! @brief Read current value of the SDHC_VENDOR_INTSTVAL field. */ #define BR_SDHC_VENDOR_INTSTVAL(x) (HW_SDHC_VENDOR(x).B.INTSTVAL) /*@}*/ /******************************************************************************* * HW_SDHC_MMCBOOT - MMC Boot register ******************************************************************************/ /*! * @brief HW_SDHC_MMCBOOT - MMC Boot register (RW) * * Reset value: 0x00000000U * * This register contains the MMC fast boot control register. */ typedef union _hw_sdhc_mmcboot { uint32_t U; struct _hw_sdhc_mmcboot_bitfields { uint32_t DTOCVACK : 4; /*!< [3:0] Boot ACK Time Out Counter Value */ uint32_t BOOTACK : 1; /*!< [4] Boot Ack Mode Select */ uint32_t BOOTMODE : 1; /*!< [5] Boot Mode Select */ uint32_t BOOTEN : 1; /*!< [6] Boot Mode Enable */ uint32_t AUTOSABGEN : 1; /*!< [7] */ uint32_t RESERVED0 : 8; /*!< [15:8] */ uint32_t BOOTBLKCNT : 16; /*!< [31:16] */ } B; } hw_sdhc_mmcboot_t; /*! * @name Constants and macros for entire SDHC_MMCBOOT register */ /*@{*/ #define HW_SDHC_MMCBOOT_ADDR(x) ((x) + 0xC4U) #define HW_SDHC_MMCBOOT(x) (*(__IO hw_sdhc_mmcboot_t *) HW_SDHC_MMCBOOT_ADDR(x)) #define HW_SDHC_MMCBOOT_RD(x) (HW_SDHC_MMCBOOT(x).U) #define HW_SDHC_MMCBOOT_WR(x, v) (HW_SDHC_MMCBOOT(x).U = (v)) #define HW_SDHC_MMCBOOT_SET(x, v) (HW_SDHC_MMCBOOT_WR(x, HW_SDHC_MMCBOOT_RD(x) | (v))) #define HW_SDHC_MMCBOOT_CLR(x, v) (HW_SDHC_MMCBOOT_WR(x, HW_SDHC_MMCBOOT_RD(x) & ~(v))) #define HW_SDHC_MMCBOOT_TOG(x, v) (HW_SDHC_MMCBOOT_WR(x, HW_SDHC_MMCBOOT_RD(x) ^ (v))) /*@}*/ /* * Constants & macros for individual SDHC_MMCBOOT bitfields */ /*! * @name Register SDHC_MMCBOOT, field DTOCVACK[3:0] (RW) * * Values: * - 0000 - SDCLK x 2^8 * - 0001 - SDCLK x 2^9 * - 0010 - SDCLK x 2^10 * - 0011 - SDCLK x 2^11 * - 0100 - SDCLK x 2^12 * - 0101 - SDCLK x 2^13 * - 0110 - SDCLK x 2^14 * - 0111 - SDCLK x 2^15 * - 1110 - SDCLK x 2^22 * - 1111 - Reserved */ /*@{*/ #define BP_SDHC_MMCBOOT_DTOCVACK (0U) /*!< Bit position for SDHC_MMCBOOT_DTOCVACK. */ #define BM_SDHC_MMCBOOT_DTOCVACK (0x0000000FU) /*!< Bit mask for SDHC_MMCBOOT_DTOCVACK. */ #define BS_SDHC_MMCBOOT_DTOCVACK (4U) /*!< Bit field size in bits for SDHC_MMCBOOT_DTOCVACK. */ /*! @brief Read current value of the SDHC_MMCBOOT_DTOCVACK field. */ #define BR_SDHC_MMCBOOT_DTOCVACK(x) (HW_SDHC_MMCBOOT(x).B.DTOCVACK) /*! @brief Format value for bitfield SDHC_MMCBOOT_DTOCVACK. */ #define BF_SDHC_MMCBOOT_DTOCVACK(v) ((uint32_t)((uint32_t)(v) << BP_SDHC_MMCBOOT_DTOCVACK) & BM_SDHC_MMCBOOT_DTOCVACK) /*! @brief Set the DTOCVACK field to a new value. */ #define BW_SDHC_MMCBOOT_DTOCVACK(x, v) (HW_SDHC_MMCBOOT_WR(x, (HW_SDHC_MMCBOOT_RD(x) & ~BM_SDHC_MMCBOOT_DTOCVACK) | BF_SDHC_MMCBOOT_DTOCVACK(v))) /*@}*/ /*! * @name Register SDHC_MMCBOOT, field BOOTACK[4] (RW) * * Values: * - 0 - No ack. * - 1 - Ack. */ /*@{*/ #define BP_SDHC_MMCBOOT_BOOTACK (4U) /*!< Bit position for SDHC_MMCBOOT_BOOTACK. */ #define BM_SDHC_MMCBOOT_BOOTACK (0x00000010U) /*!< Bit mask for SDHC_MMCBOOT_BOOTACK. */ #define BS_SDHC_MMCBOOT_BOOTACK (1U) /*!< Bit field size in bits for SDHC_MMCBOOT_BOOTACK. */ /*! @brief Read current value of the SDHC_MMCBOOT_BOOTACK field. */ #define BR_SDHC_MMCBOOT_BOOTACK(x) (BITBAND_ACCESS32(HW_SDHC_MMCBOOT_ADDR(x), BP_SDHC_MMCBOOT_BOOTACK)) /*! @brief Format value for bitfield SDHC_MMCBOOT_BOOTACK. */ #define BF_SDHC_MMCBOOT_BOOTACK(v) ((uint32_t)((uint32_t)(v) << BP_SDHC_MMCBOOT_BOOTACK) & BM_SDHC_MMCBOOT_BOOTACK) /*! @brief Set the BOOTACK field to a new value. */ #define BW_SDHC_MMCBOOT_BOOTACK(x, v) (BITBAND_ACCESS32(HW_SDHC_MMCBOOT_ADDR(x), BP_SDHC_MMCBOOT_BOOTACK) = (v)) /*@}*/ /*! * @name Register SDHC_MMCBOOT, field BOOTMODE[5] (RW) * * Values: * - 0 - Normal boot. * - 1 - Alternative boot. */ /*@{*/ #define BP_SDHC_MMCBOOT_BOOTMODE (5U) /*!< Bit position for SDHC_MMCBOOT_BOOTMODE. */ #define BM_SDHC_MMCBOOT_BOOTMODE (0x00000020U) /*!< Bit mask for SDHC_MMCBOOT_BOOTMODE. */ #define BS_SDHC_MMCBOOT_BOOTMODE (1U) /*!< Bit field size in bits for SDHC_MMCBOOT_BOOTMODE. */ /*! @brief Read current value of the SDHC_MMCBOOT_BOOTMODE field. */ #define BR_SDHC_MMCBOOT_BOOTMODE(x) (BITBAND_ACCESS32(HW_SDHC_MMCBOOT_ADDR(x), BP_SDHC_MMCBOOT_BOOTMODE)) /*! @brief Format value for bitfield SDHC_MMCBOOT_BOOTMODE. */ #define BF_SDHC_MMCBOOT_BOOTMODE(v) ((uint32_t)((uint32_t)(v) << BP_SDHC_MMCBOOT_BOOTMODE) & BM_SDHC_MMCBOOT_BOOTMODE) /*! @brief Set the BOOTMODE field to a new value. */ #define BW_SDHC_MMCBOOT_BOOTMODE(x, v) (BITBAND_ACCESS32(HW_SDHC_MMCBOOT_ADDR(x), BP_SDHC_MMCBOOT_BOOTMODE) = (v)) /*@}*/ /*! * @name Register SDHC_MMCBOOT, field BOOTEN[6] (RW) * * Values: * - 0 - Fast boot disable. * - 1 - Fast boot enable. */ /*@{*/ #define BP_SDHC_MMCBOOT_BOOTEN (6U) /*!< Bit position for SDHC_MMCBOOT_BOOTEN. */ #define BM_SDHC_MMCBOOT_BOOTEN (0x00000040U) /*!< Bit mask for SDHC_MMCBOOT_BOOTEN. */ #define BS_SDHC_MMCBOOT_BOOTEN (1U) /*!< Bit field size in bits for SDHC_MMCBOOT_BOOTEN. */ /*! @brief Read current value of the SDHC_MMCBOOT_BOOTEN field. */ #define BR_SDHC_MMCBOOT_BOOTEN(x) (BITBAND_ACCESS32(HW_SDHC_MMCBOOT_ADDR(x), BP_SDHC_MMCBOOT_BOOTEN)) /*! @brief Format value for bitfield SDHC_MMCBOOT_BOOTEN. */ #define BF_SDHC_MMCBOOT_BOOTEN(v) ((uint32_t)((uint32_t)(v) << BP_SDHC_MMCBOOT_BOOTEN) & BM_SDHC_MMCBOOT_BOOTEN) /*! @brief Set the BOOTEN field to a new value. */ #define BW_SDHC_MMCBOOT_BOOTEN(x, v) (BITBAND_ACCESS32(HW_SDHC_MMCBOOT_ADDR(x), BP_SDHC_MMCBOOT_BOOTEN) = (v)) /*@}*/ /*! * @name Register SDHC_MMCBOOT, field AUTOSABGEN[7] (RW) * * When boot, enable auto stop at block gap function. This function will be * triggered, and host will stop at block gap when received card block cnt is equal * to BOOTBLKCNT. */ /*@{*/ #define BP_SDHC_MMCBOOT_AUTOSABGEN (7U) /*!< Bit position for SDHC_MMCBOOT_AUTOSABGEN. */ #define BM_SDHC_MMCBOOT_AUTOSABGEN (0x00000080U) /*!< Bit mask for SDHC_MMCBOOT_AUTOSABGEN. */ #define BS_SDHC_MMCBOOT_AUTOSABGEN (1U) /*!< Bit field size in bits for SDHC_MMCBOOT_AUTOSABGEN. */ /*! @brief Read current value of the SDHC_MMCBOOT_AUTOSABGEN field. */ #define BR_SDHC_MMCBOOT_AUTOSABGEN(x) (BITBAND_ACCESS32(HW_SDHC_MMCBOOT_ADDR(x), BP_SDHC_MMCBOOT_AUTOSABGEN)) /*! @brief Format value for bitfield SDHC_MMCBOOT_AUTOSABGEN. */ #define BF_SDHC_MMCBOOT_AUTOSABGEN(v) ((uint32_t)((uint32_t)(v) << BP_SDHC_MMCBOOT_AUTOSABGEN) & BM_SDHC_MMCBOOT_AUTOSABGEN) /*! @brief Set the AUTOSABGEN field to a new value. */ #define BW_SDHC_MMCBOOT_AUTOSABGEN(x, v) (BITBAND_ACCESS32(HW_SDHC_MMCBOOT_ADDR(x), BP_SDHC_MMCBOOT_AUTOSABGEN) = (v)) /*@}*/ /*! * @name Register SDHC_MMCBOOT, field BOOTBLKCNT[31:16] (RW) * * Defines the stop at block gap value of automatic mode. When received card * block cnt is equal to BOOTBLKCNT and AUTOSABGEN is 1, then stop at block gap. */ /*@{*/ #define BP_SDHC_MMCBOOT_BOOTBLKCNT (16U) /*!< Bit position for SDHC_MMCBOOT_BOOTBLKCNT. */ #define BM_SDHC_MMCBOOT_BOOTBLKCNT (0xFFFF0000U) /*!< Bit mask for SDHC_MMCBOOT_BOOTBLKCNT. */ #define BS_SDHC_MMCBOOT_BOOTBLKCNT (16U) /*!< Bit field size in bits for SDHC_MMCBOOT_BOOTBLKCNT. */ /*! @brief Read current value of the SDHC_MMCBOOT_BOOTBLKCNT field. */ #define BR_SDHC_MMCBOOT_BOOTBLKCNT(x) (HW_SDHC_MMCBOOT(x).B.BOOTBLKCNT) /*! @brief Format value for bitfield SDHC_MMCBOOT_BOOTBLKCNT. */ #define BF_SDHC_MMCBOOT_BOOTBLKCNT(v) ((uint32_t)((uint32_t)(v) << BP_SDHC_MMCBOOT_BOOTBLKCNT) & BM_SDHC_MMCBOOT_BOOTBLKCNT) /*! @brief Set the BOOTBLKCNT field to a new value. */ #define BW_SDHC_MMCBOOT_BOOTBLKCNT(x, v) (HW_SDHC_MMCBOOT_WR(x, (HW_SDHC_MMCBOOT_RD(x) & ~BM_SDHC_MMCBOOT_BOOTBLKCNT) | BF_SDHC_MMCBOOT_BOOTBLKCNT(v))) /*@}*/ /******************************************************************************* * HW_SDHC_HOSTVER - Host Controller Version ******************************************************************************/ /*! * @brief HW_SDHC_HOSTVER - Host Controller Version (RO) * * Reset value: 0x00001201U * * This register contains the vendor host controller version information. All * bits are read only and will read the same as the power-reset value. */ typedef union _hw_sdhc_hostver { uint32_t U; struct _hw_sdhc_hostver_bitfields { uint32_t SVN : 8; /*!< [7:0] Specification Version Number */ uint32_t VVN : 8; /*!< [15:8] Vendor Version Number */ uint32_t RESERVED0 : 16; /*!< [31:16] */ } B; } hw_sdhc_hostver_t; /*! * @name Constants and macros for entire SDHC_HOSTVER register */ /*@{*/ #define HW_SDHC_HOSTVER_ADDR(x) ((x) + 0xFCU) #define HW_SDHC_HOSTVER(x) (*(__I hw_sdhc_hostver_t *) HW_SDHC_HOSTVER_ADDR(x)) #define HW_SDHC_HOSTVER_RD(x) (HW_SDHC_HOSTVER(x).U) /*@}*/ /* * Constants & macros for individual SDHC_HOSTVER bitfields */ /*! * @name Register SDHC_HOSTVER, field SVN[7:0] (RO) * * These status bits indicate the host controller specification version. * * Values: * - 1 - SD host specification version 2.0, supports test event register and * ADMA. */ /*@{*/ #define BP_SDHC_HOSTVER_SVN (0U) /*!< Bit position for SDHC_HOSTVER_SVN. */ #define BM_SDHC_HOSTVER_SVN (0x000000FFU) /*!< Bit mask for SDHC_HOSTVER_SVN. */ #define BS_SDHC_HOSTVER_SVN (8U) /*!< Bit field size in bits for SDHC_HOSTVER_SVN. */ /*! @brief Read current value of the SDHC_HOSTVER_SVN field. */ #define BR_SDHC_HOSTVER_SVN(x) (HW_SDHC_HOSTVER(x).B.SVN) /*@}*/ /*! * @name Register SDHC_HOSTVER, field VVN[15:8] (RO) * * These status bits are reserved for the vendor version number. The host driver * shall not use this status. * * Values: * - 0 - Freescale SDHC version 1.0 * - 10000 - Freescale SDHC version 2.0 * - 10001 - Freescale SDHC version 2.1 * - 10010 - Freescale SDHC version 2.2 */ /*@{*/ #define BP_SDHC_HOSTVER_VVN (8U) /*!< Bit position for SDHC_HOSTVER_VVN. */ #define BM_SDHC_HOSTVER_VVN (0x0000FF00U) /*!< Bit mask for SDHC_HOSTVER_VVN. */ #define BS_SDHC_HOSTVER_VVN (8U) /*!< Bit field size in bits for SDHC_HOSTVER_VVN. */ /*! @brief Read current value of the SDHC_HOSTVER_VVN field. */ #define BR_SDHC_HOSTVER_VVN(x) (HW_SDHC_HOSTVER(x).B.VVN) /*@}*/ /******************************************************************************* * hw_sdhc_t - module struct ******************************************************************************/ /*! * @brief All SDHC module registers. */ #pragma pack(1) typedef struct _hw_sdhc { __IO hw_sdhc_dsaddr_t DSADDR; /*!< [0x0] DMA System Address register */ __IO hw_sdhc_blkattr_t BLKATTR; /*!< [0x4] Block Attributes register */ __IO hw_sdhc_cmdarg_t CMDARG; /*!< [0x8] Command Argument register */ __IO hw_sdhc_xfertyp_t XFERTYP; /*!< [0xC] Transfer Type register */ __I hw_sdhc_cmdrsp0_t CMDRSP0; /*!< [0x10] Command Response 0 */ __I hw_sdhc_cmdrsp1_t CMDRSP1; /*!< [0x14] Command Response 1 */ __I hw_sdhc_cmdrsp2_t CMDRSP2; /*!< [0x18] Command Response 2 */ __I hw_sdhc_cmdrsp3_t CMDRSP3; /*!< [0x1C] Command Response 3 */ __IO hw_sdhc_datport_t DATPORT; /*!< [0x20] Buffer Data Port register */ __I hw_sdhc_prsstat_t PRSSTAT; /*!< [0x24] Present State register */ __IO hw_sdhc_proctl_t PROCTL; /*!< [0x28] Protocol Control register */ __IO hw_sdhc_sysctl_t SYSCTL; /*!< [0x2C] System Control register */ __IO hw_sdhc_irqstat_t IRQSTAT; /*!< [0x30] Interrupt Status register */ __IO hw_sdhc_irqstaten_t IRQSTATEN; /*!< [0x34] Interrupt Status Enable register */ __IO hw_sdhc_irqsigen_t IRQSIGEN; /*!< [0x38] Interrupt Signal Enable register */ __I hw_sdhc_ac12err_t AC12ERR; /*!< [0x3C] Auto CMD12 Error Status Register */ __I hw_sdhc_htcapblt_t HTCAPBLT; /*!< [0x40] Host Controller Capabilities */ __IO hw_sdhc_wml_t WML; /*!< [0x44] Watermark Level Register */ uint8_t _reserved0[8]; __O hw_sdhc_fevt_t FEVT; /*!< [0x50] Force Event register */ __I hw_sdhc_admaes_t ADMAES; /*!< [0x54] ADMA Error Status register */ __IO hw_sdhc_adsaddr_t ADSADDR; /*!< [0x58] ADMA System Addressregister */ uint8_t _reserved1[100]; __IO hw_sdhc_vendor_t VENDOR; /*!< [0xC0] Vendor Specific register */ __IO hw_sdhc_mmcboot_t MMCBOOT; /*!< [0xC4] MMC Boot register */ uint8_t _reserved2[52]; __I hw_sdhc_hostver_t HOSTVER; /*!< [0xFC] Host Controller Version */ } hw_sdhc_t; #pragma pack() /*! @brief Macro to access all SDHC registers. */ /*! @param x SDHC module instance base address. */ /*! @return Reference (not a pointer) to the registers struct. To get a pointer to the struct, * use the '&' operator, like &HW_SDHC(SDHC_BASE). */ #define HW_SDHC(x) (*(hw_sdhc_t *)(x)) #endif /* __HW_SDHC_REGISTERS_H__ */ /* EOF */ ================================================ FILE: Zelig/mbed/TARGET_K64F/TARGET_Freescale/TARGET_KPSDK_MCUS/TARGET_MCU_K64F/device/device/MK64F12/MK64F12_sim.h ================================================ /* ** ################################################################### ** Compilers: Keil ARM C/C++ Compiler ** Freescale C/C++ for Embedded ARM ** GNU C Compiler ** IAR ANSI C/C++ Compiler for ARM ** ** Reference manual: K64P144M120SF5RM, Rev.2, January 2014 ** Version: rev. 2.5, 2014-02-10 ** Build: b140604 ** ** Abstract: ** Extension to the CMSIS register access layer header. ** ** Copyright (c) 2014 Freescale Semiconductor, Inc. ** All rights reserved. ** ** Redistribution and use in source and binary forms, with or without modification, ** are permitted provided that the following conditions are met: ** ** o Redistributions of source code must retain the above copyright notice, this list ** of conditions and the following disclaimer. ** ** o Redistributions in binary form must reproduce the above copyright notice, this ** list of conditions and the following disclaimer in the documentation and/or ** other materials provided with the distribution. ** ** o Neither the name of Freescale Semiconductor, Inc. nor the names of its ** contributors may be used to endorse or promote products derived from this ** software without specific prior written permission. ** ** THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ** ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED ** WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE ** DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT 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. ** ** http: www.freescale.com ** mail: support@freescale.com ** ** Revisions: ** - rev. 1.0 (2013-08-12) ** Initial version. ** - rev. 2.0 (2013-10-29) ** Register accessor macros added to the memory map. ** Symbols for Processor Expert memory map compatibility added to the memory map. ** Startup file for gcc has been updated according to CMSIS 3.2. ** System initialization updated. ** MCG - registers updated. ** PORTA, PORTB, PORTC, PORTE - registers for digital filter removed. ** - rev. 2.1 (2013-10-30) ** Definition of BITBAND macros updated to support peripherals with 32-bit acces disabled. ** - rev. 2.2 (2013-12-09) ** DMA - EARS register removed. ** AIPS0, AIPS1 - MPRA register updated. ** - rev. 2.3 (2014-01-24) ** Update according to reference manual rev. 2 ** ENET, MCG, MCM, SIM, USB - registers updated ** - rev. 2.4 (2014-02-10) ** The declaration of clock configurations has been moved to separate header file system_MK64F12.h ** Update of SystemInit() and SystemCoreClockUpdate() functions. ** - rev. 2.5 (2014-02-10) ** The declaration of clock configurations has been moved to separate header file system_MK64F12.h ** Update of SystemInit() and SystemCoreClockUpdate() functions. ** Module access macro module_BASES replaced by module_BASE_PTRS. ** ** ################################################################### */ /* * WARNING! DO NOT EDIT THIS FILE DIRECTLY! * * This file was generated automatically and any changes may be lost. */ #ifndef __HW_SIM_REGISTERS_H__ #define __HW_SIM_REGISTERS_H__ #include "MK64F12.h" #include "fsl_bitaccess.h" /* * MK64F12 SIM * * System Integration Module * * Registers defined in this header file: * - HW_SIM_SOPT1 - System Options Register 1 * - HW_SIM_SOPT1CFG - SOPT1 Configuration Register * - HW_SIM_SOPT2 - System Options Register 2 * - HW_SIM_SOPT4 - System Options Register 4 * - HW_SIM_SOPT5 - System Options Register 5 * - HW_SIM_SOPT7 - System Options Register 7 * - HW_SIM_SDID - System Device Identification Register * - HW_SIM_SCGC1 - System Clock Gating Control Register 1 * - HW_SIM_SCGC2 - System Clock Gating Control Register 2 * - HW_SIM_SCGC3 - System Clock Gating Control Register 3 * - HW_SIM_SCGC4 - System Clock Gating Control Register 4 * - HW_SIM_SCGC5 - System Clock Gating Control Register 5 * - HW_SIM_SCGC6 - System Clock Gating Control Register 6 * - HW_SIM_SCGC7 - System Clock Gating Control Register 7 * - HW_SIM_CLKDIV1 - System Clock Divider Register 1 * - HW_SIM_CLKDIV2 - System Clock Divider Register 2 * - HW_SIM_FCFG1 - Flash Configuration Register 1 * - HW_SIM_FCFG2 - Flash Configuration Register 2 * - HW_SIM_UIDH - Unique Identification Register High * - HW_SIM_UIDMH - Unique Identification Register Mid-High * - HW_SIM_UIDML - Unique Identification Register Mid Low * - HW_SIM_UIDL - Unique Identification Register Low * * - hw_sim_t - Struct containing all module registers. */ #define HW_SIM_INSTANCE_COUNT (1U) /*!< Number of instances of the SIM module. */ /******************************************************************************* * HW_SIM_SOPT1 - System Options Register 1 ******************************************************************************/ /*! * @brief HW_SIM_SOPT1 - System Options Register 1 (RW) * * Reset value: 0x80000000U * * The SOPT1 register is only reset on POR or LVD. */ typedef union _hw_sim_sopt1 { uint32_t U; struct _hw_sim_sopt1_bitfields { uint32_t RESERVED0 : 12; /*!< [11:0] */ uint32_t RAMSIZE : 4; /*!< [15:12] RAM size */ uint32_t RESERVED1 : 2; /*!< [17:16] */ uint32_t OSC32KSEL : 2; /*!< [19:18] 32K oscillator clock select */ uint32_t RESERVED2 : 9; /*!< [28:20] */ uint32_t USBVSTBY : 1; /*!< [29] USB voltage regulator in standby * mode during VLPR and VLPW modes */ uint32_t USBSSTBY : 1; /*!< [30] USB voltage regulator in standby * mode during Stop, VLPS, LLS and VLLS modes. */ uint32_t USBREGEN : 1; /*!< [31] USB voltage regulator enable */ } B; } hw_sim_sopt1_t; /*! * @name Constants and macros for entire SIM_SOPT1 register */ /*@{*/ #define HW_SIM_SOPT1_ADDR(x) ((x) + 0x0U) #define HW_SIM_SOPT1(x) (*(__IO hw_sim_sopt1_t *) HW_SIM_SOPT1_ADDR(x)) #define HW_SIM_SOPT1_RD(x) (HW_SIM_SOPT1(x).U) #define HW_SIM_SOPT1_WR(x, v) (HW_SIM_SOPT1(x).U = (v)) #define HW_SIM_SOPT1_SET(x, v) (HW_SIM_SOPT1_WR(x, HW_SIM_SOPT1_RD(x) | (v))) #define HW_SIM_SOPT1_CLR(x, v) (HW_SIM_SOPT1_WR(x, HW_SIM_SOPT1_RD(x) & ~(v))) #define HW_SIM_SOPT1_TOG(x, v) (HW_SIM_SOPT1_WR(x, HW_SIM_SOPT1_RD(x) ^ (v))) /*@}*/ /* * Constants & macros for individual SIM_SOPT1 bitfields */ /*! * @name Register SIM_SOPT1, field RAMSIZE[15:12] (RO) * * This field specifies the amount of system RAM available on the device. * * Values: * - 0001 - 8 KB * - 0011 - 16 KB * - 0100 - 24 KB * - 0101 - 32 KB * - 0110 - 48 KB * - 0111 - 64 KB * - 1000 - 96 KB * - 1001 - 128 KB * - 1011 - 256 KB */ /*@{*/ #define BP_SIM_SOPT1_RAMSIZE (12U) /*!< Bit position for SIM_SOPT1_RAMSIZE. */ #define BM_SIM_SOPT1_RAMSIZE (0x0000F000U) /*!< Bit mask for SIM_SOPT1_RAMSIZE. */ #define BS_SIM_SOPT1_RAMSIZE (4U) /*!< Bit field size in bits for SIM_SOPT1_RAMSIZE. */ /*! @brief Read current value of the SIM_SOPT1_RAMSIZE field. */ #define BR_SIM_SOPT1_RAMSIZE(x) (HW_SIM_SOPT1(x).B.RAMSIZE) /*@}*/ /*! * @name Register SIM_SOPT1, field OSC32KSEL[19:18] (RW) * * Selects the 32 kHz clock source (ERCLK32K) for LPTMR. This field is reset * only on POR/LVD. * * Values: * - 00 - System oscillator (OSC32KCLK) * - 01 - Reserved * - 10 - RTC 32.768kHz oscillator * - 11 - LPO 1 kHz */ /*@{*/ #define BP_SIM_SOPT1_OSC32KSEL (18U) /*!< Bit position for SIM_SOPT1_OSC32KSEL. */ #define BM_SIM_SOPT1_OSC32KSEL (0x000C0000U) /*!< Bit mask for SIM_SOPT1_OSC32KSEL. */ #define BS_SIM_SOPT1_OSC32KSEL (2U) /*!< Bit field size in bits for SIM_SOPT1_OSC32KSEL. */ /*! @brief Read current value of the SIM_SOPT1_OSC32KSEL field. */ #define BR_SIM_SOPT1_OSC32KSEL(x) (HW_SIM_SOPT1(x).B.OSC32KSEL) /*! @brief Format value for bitfield SIM_SOPT1_OSC32KSEL. */ #define BF_SIM_SOPT1_OSC32KSEL(v) ((uint32_t)((uint32_t)(v) << BP_SIM_SOPT1_OSC32KSEL) & BM_SIM_SOPT1_OSC32KSEL) /*! @brief Set the OSC32KSEL field to a new value. */ #define BW_SIM_SOPT1_OSC32KSEL(x, v) (HW_SIM_SOPT1_WR(x, (HW_SIM_SOPT1_RD(x) & ~BM_SIM_SOPT1_OSC32KSEL) | BF_SIM_SOPT1_OSC32KSEL(v))) /*@}*/ /*! * @name Register SIM_SOPT1, field USBVSTBY[29] (RW) * * Controls whether the USB voltage regulator is placed in standby mode during * VLPR and VLPW modes. * * Values: * - 0 - USB voltage regulator not in standby during VLPR and VLPW modes. * - 1 - USB voltage regulator in standby during VLPR and VLPW modes. */ /*@{*/ #define BP_SIM_SOPT1_USBVSTBY (29U) /*!< Bit position for SIM_SOPT1_USBVSTBY. */ #define BM_SIM_SOPT1_USBVSTBY (0x20000000U) /*!< Bit mask for SIM_SOPT1_USBVSTBY. */ #define BS_SIM_SOPT1_USBVSTBY (1U) /*!< Bit field size in bits for SIM_SOPT1_USBVSTBY. */ /*! @brief Read current value of the SIM_SOPT1_USBVSTBY field. */ #define BR_SIM_SOPT1_USBVSTBY(x) (BITBAND_ACCESS32(HW_SIM_SOPT1_ADDR(x), BP_SIM_SOPT1_USBVSTBY)) /*! @brief Format value for bitfield SIM_SOPT1_USBVSTBY. */ #define BF_SIM_SOPT1_USBVSTBY(v) ((uint32_t)((uint32_t)(v) << BP_SIM_SOPT1_USBVSTBY) & BM_SIM_SOPT1_USBVSTBY) /*! @brief Set the USBVSTBY field to a new value. */ #define BW_SIM_SOPT1_USBVSTBY(x, v) (BITBAND_ACCESS32(HW_SIM_SOPT1_ADDR(x), BP_SIM_SOPT1_USBVSTBY) = (v)) /*@}*/ /*! * @name Register SIM_SOPT1, field USBSSTBY[30] (RW) * * Controls whether the USB voltage regulator is placed in standby mode during * Stop, VLPS, LLS and VLLS modes. * * Values: * - 0 - USB voltage regulator not in standby during Stop, VLPS, LLS and VLLS * modes. * - 1 - USB voltage regulator in standby during Stop, VLPS, LLS and VLLS modes. */ /*@{*/ #define BP_SIM_SOPT1_USBSSTBY (30U) /*!< Bit position for SIM_SOPT1_USBSSTBY. */ #define BM_SIM_SOPT1_USBSSTBY (0x40000000U) /*!< Bit mask for SIM_SOPT1_USBSSTBY. */ #define BS_SIM_SOPT1_USBSSTBY (1U) /*!< Bit field size in bits for SIM_SOPT1_USBSSTBY. */ /*! @brief Read current value of the SIM_SOPT1_USBSSTBY field. */ #define BR_SIM_SOPT1_USBSSTBY(x) (BITBAND_ACCESS32(HW_SIM_SOPT1_ADDR(x), BP_SIM_SOPT1_USBSSTBY)) /*! @brief Format value for bitfield SIM_SOPT1_USBSSTBY. */ #define BF_SIM_SOPT1_USBSSTBY(v) ((uint32_t)((uint32_t)(v) << BP_SIM_SOPT1_USBSSTBY) & BM_SIM_SOPT1_USBSSTBY) /*! @brief Set the USBSSTBY field to a new value. */ #define BW_SIM_SOPT1_USBSSTBY(x, v) (BITBAND_ACCESS32(HW_SIM_SOPT1_ADDR(x), BP_SIM_SOPT1_USBSSTBY) = (v)) /*@}*/ /*! * @name Register SIM_SOPT1, field USBREGEN[31] (RW) * * Controls whether the USB voltage regulator is enabled. * * Values: * - 0 - USB voltage regulator is disabled. * - 1 - USB voltage regulator is enabled. */ /*@{*/ #define BP_SIM_SOPT1_USBREGEN (31U) /*!< Bit position for SIM_SOPT1_USBREGEN. */ #define BM_SIM_SOPT1_USBREGEN (0x80000000U) /*!< Bit mask for SIM_SOPT1_USBREGEN. */ #define BS_SIM_SOPT1_USBREGEN (1U) /*!< Bit field size in bits for SIM_SOPT1_USBREGEN. */ /*! @brief Read current value of the SIM_SOPT1_USBREGEN field. */ #define BR_SIM_SOPT1_USBREGEN(x) (BITBAND_ACCESS32(HW_SIM_SOPT1_ADDR(x), BP_SIM_SOPT1_USBREGEN)) /*! @brief Format value for bitfield SIM_SOPT1_USBREGEN. */ #define BF_SIM_SOPT1_USBREGEN(v) ((uint32_t)((uint32_t)(v) << BP_SIM_SOPT1_USBREGEN) & BM_SIM_SOPT1_USBREGEN) /*! @brief Set the USBREGEN field to a new value. */ #define BW_SIM_SOPT1_USBREGEN(x, v) (BITBAND_ACCESS32(HW_SIM_SOPT1_ADDR(x), BP_SIM_SOPT1_USBREGEN) = (v)) /*@}*/ /******************************************************************************* * HW_SIM_SOPT1CFG - SOPT1 Configuration Register ******************************************************************************/ /*! * @brief HW_SIM_SOPT1CFG - SOPT1 Configuration Register (RW) * * Reset value: 0x00000000U * * The SOPT1CFG register is reset on System Reset not VLLS. */ typedef union _hw_sim_sopt1cfg { uint32_t U; struct _hw_sim_sopt1cfg_bitfields { uint32_t RESERVED0 : 24; /*!< [23:0] */ uint32_t URWE : 1; /*!< [24] USB voltage regulator enable write * enable */ uint32_t UVSWE : 1; /*!< [25] USB voltage regulator VLP standby write * enable */ uint32_t USSWE : 1; /*!< [26] USB voltage regulator stop standby * write enable */ uint32_t RESERVED1 : 5; /*!< [31:27] */ } B; } hw_sim_sopt1cfg_t; /*! * @name Constants and macros for entire SIM_SOPT1CFG register */ /*@{*/ #define HW_SIM_SOPT1CFG_ADDR(x) ((x) + 0x4U) #define HW_SIM_SOPT1CFG(x) (*(__IO hw_sim_sopt1cfg_t *) HW_SIM_SOPT1CFG_ADDR(x)) #define HW_SIM_SOPT1CFG_RD(x) (HW_SIM_SOPT1CFG(x).U) #define HW_SIM_SOPT1CFG_WR(x, v) (HW_SIM_SOPT1CFG(x).U = (v)) #define HW_SIM_SOPT1CFG_SET(x, v) (HW_SIM_SOPT1CFG_WR(x, HW_SIM_SOPT1CFG_RD(x) | (v))) #define HW_SIM_SOPT1CFG_CLR(x, v) (HW_SIM_SOPT1CFG_WR(x, HW_SIM_SOPT1CFG_RD(x) & ~(v))) #define HW_SIM_SOPT1CFG_TOG(x, v) (HW_SIM_SOPT1CFG_WR(x, HW_SIM_SOPT1CFG_RD(x) ^ (v))) /*@}*/ /* * Constants & macros for individual SIM_SOPT1CFG bitfields */ /*! * @name Register SIM_SOPT1CFG, field URWE[24] (RW) * * Writing one to the URWE bit allows the SOPT1 USBREGEN bit to be written. This * register bit clears after a write to USBREGEN. * * Values: * - 0 - SOPT1 USBREGEN cannot be written. * - 1 - SOPT1 USBREGEN can be written. */ /*@{*/ #define BP_SIM_SOPT1CFG_URWE (24U) /*!< Bit position for SIM_SOPT1CFG_URWE. */ #define BM_SIM_SOPT1CFG_URWE (0x01000000U) /*!< Bit mask for SIM_SOPT1CFG_URWE. */ #define BS_SIM_SOPT1CFG_URWE (1U) /*!< Bit field size in bits for SIM_SOPT1CFG_URWE. */ /*! @brief Read current value of the SIM_SOPT1CFG_URWE field. */ #define BR_SIM_SOPT1CFG_URWE(x) (BITBAND_ACCESS32(HW_SIM_SOPT1CFG_ADDR(x), BP_SIM_SOPT1CFG_URWE)) /*! @brief Format value for bitfield SIM_SOPT1CFG_URWE. */ #define BF_SIM_SOPT1CFG_URWE(v) ((uint32_t)((uint32_t)(v) << BP_SIM_SOPT1CFG_URWE) & BM_SIM_SOPT1CFG_URWE) /*! @brief Set the URWE field to a new value. */ #define BW_SIM_SOPT1CFG_URWE(x, v) (BITBAND_ACCESS32(HW_SIM_SOPT1CFG_ADDR(x), BP_SIM_SOPT1CFG_URWE) = (v)) /*@}*/ /*! * @name Register SIM_SOPT1CFG, field UVSWE[25] (RW) * * Writing one to the UVSWE bit allows the SOPT1 USBVSTBY bit to be written. * This register bit clears after a write to USBVSTBY. * * Values: * - 0 - SOPT1 USBVSTBY cannot be written. * - 1 - SOPT1 USBVSTBY can be written. */ /*@{*/ #define BP_SIM_SOPT1CFG_UVSWE (25U) /*!< Bit position for SIM_SOPT1CFG_UVSWE. */ #define BM_SIM_SOPT1CFG_UVSWE (0x02000000U) /*!< Bit mask for SIM_SOPT1CFG_UVSWE. */ #define BS_SIM_SOPT1CFG_UVSWE (1U) /*!< Bit field size in bits for SIM_SOPT1CFG_UVSWE. */ /*! @brief Read current value of the SIM_SOPT1CFG_UVSWE field. */ #define BR_SIM_SOPT1CFG_UVSWE(x) (BITBAND_ACCESS32(HW_SIM_SOPT1CFG_ADDR(x), BP_SIM_SOPT1CFG_UVSWE)) /*! @brief Format value for bitfield SIM_SOPT1CFG_UVSWE. */ #define BF_SIM_SOPT1CFG_UVSWE(v) ((uint32_t)((uint32_t)(v) << BP_SIM_SOPT1CFG_UVSWE) & BM_SIM_SOPT1CFG_UVSWE) /*! @brief Set the UVSWE field to a new value. */ #define BW_SIM_SOPT1CFG_UVSWE(x, v) (BITBAND_ACCESS32(HW_SIM_SOPT1CFG_ADDR(x), BP_SIM_SOPT1CFG_UVSWE) = (v)) /*@}*/ /*! * @name Register SIM_SOPT1CFG, field USSWE[26] (RW) * * Writing one to the USSWE bit allows the SOPT1 USBSSTBY bit to be written. * This register bit clears after a write to USBSSTBY. * * Values: * - 0 - SOPT1 USBSSTBY cannot be written. * - 1 - SOPT1 USBSSTBY can be written. */ /*@{*/ #define BP_SIM_SOPT1CFG_USSWE (26U) /*!< Bit position for SIM_SOPT1CFG_USSWE. */ #define BM_SIM_SOPT1CFG_USSWE (0x04000000U) /*!< Bit mask for SIM_SOPT1CFG_USSWE. */ #define BS_SIM_SOPT1CFG_USSWE (1U) /*!< Bit field size in bits for SIM_SOPT1CFG_USSWE. */ /*! @brief Read current value of the SIM_SOPT1CFG_USSWE field. */ #define BR_SIM_SOPT1CFG_USSWE(x) (BITBAND_ACCESS32(HW_SIM_SOPT1CFG_ADDR(x), BP_SIM_SOPT1CFG_USSWE)) /*! @brief Format value for bitfield SIM_SOPT1CFG_USSWE. */ #define BF_SIM_SOPT1CFG_USSWE(v) ((uint32_t)((uint32_t)(v) << BP_SIM_SOPT1CFG_USSWE) & BM_SIM_SOPT1CFG_USSWE) /*! @brief Set the USSWE field to a new value. */ #define BW_SIM_SOPT1CFG_USSWE(x, v) (BITBAND_ACCESS32(HW_SIM_SOPT1CFG_ADDR(x), BP_SIM_SOPT1CFG_USSWE) = (v)) /*@}*/ /******************************************************************************* * HW_SIM_SOPT2 - System Options Register 2 ******************************************************************************/ /*! * @brief HW_SIM_SOPT2 - System Options Register 2 (RW) * * Reset value: 0x00001000U * * SOPT2 contains the controls for selecting many of the module clock source * options on this device. See the Clock Distribution chapter for more information * including clocking diagrams and definitions of device clocks. */ typedef union _hw_sim_sopt2 { uint32_t U; struct _hw_sim_sopt2_bitfields { uint32_t RESERVED0 : 4; /*!< [3:0] */ uint32_t RTCCLKOUTSEL : 1; /*!< [4] RTC clock out select */ uint32_t CLKOUTSEL : 3; /*!< [7:5] CLKOUT select */ uint32_t FBSL : 2; /*!< [9:8] FlexBus security level */ uint32_t RESERVED1 : 1; /*!< [10] */ uint32_t PTD7PAD : 1; /*!< [11] PTD7 pad drive strength */ uint32_t TRACECLKSEL : 1; /*!< [12] Debug trace clock select */ uint32_t RESERVED2 : 3; /*!< [15:13] */ uint32_t PLLFLLSEL : 2; /*!< [17:16] PLL/FLL clock select */ uint32_t USBSRC : 1; /*!< [18] USB clock source select */ uint32_t RMIISRC : 1; /*!< [19] RMII clock source select */ uint32_t TIMESRC : 2; /*!< [21:20] IEEE 1588 timestamp clock source * select */ uint32_t RESERVED3 : 6; /*!< [27:22] */ uint32_t SDHCSRC : 2; /*!< [29:28] SDHC clock source select */ uint32_t RESERVED4 : 2; /*!< [31:30] */ } B; } hw_sim_sopt2_t; /*! * @name Constants and macros for entire SIM_SOPT2 register */ /*@{*/ #define HW_SIM_SOPT2_ADDR(x) ((x) + 0x1004U) #define HW_SIM_SOPT2(x) (*(__IO hw_sim_sopt2_t *) HW_SIM_SOPT2_ADDR(x)) #define HW_SIM_SOPT2_RD(x) (HW_SIM_SOPT2(x).U) #define HW_SIM_SOPT2_WR(x, v) (HW_SIM_SOPT2(x).U = (v)) #define HW_SIM_SOPT2_SET(x, v) (HW_SIM_SOPT2_WR(x, HW_SIM_SOPT2_RD(x) | (v))) #define HW_SIM_SOPT2_CLR(x, v) (HW_SIM_SOPT2_WR(x, HW_SIM_SOPT2_RD(x) & ~(v))) #define HW_SIM_SOPT2_TOG(x, v) (HW_SIM_SOPT2_WR(x, HW_SIM_SOPT2_RD(x) ^ (v))) /*@}*/ /* * Constants & macros for individual SIM_SOPT2 bitfields */ /*! * @name Register SIM_SOPT2, field RTCCLKOUTSEL[4] (RW) * * Selects either the RTC 1 Hz clock or the 32.768kHz clock to be output on the * RTC_CLKOUT pin. * * Values: * - 0 - RTC 1 Hz clock is output on the RTC_CLKOUT pin. * - 1 - RTC 32.768kHz clock is output on the RTC_CLKOUT pin. */ /*@{*/ #define BP_SIM_SOPT2_RTCCLKOUTSEL (4U) /*!< Bit position for SIM_SOPT2_RTCCLKOUTSEL. */ #define BM_SIM_SOPT2_RTCCLKOUTSEL (0x00000010U) /*!< Bit mask for SIM_SOPT2_RTCCLKOUTSEL. */ #define BS_SIM_SOPT2_RTCCLKOUTSEL (1U) /*!< Bit field size in bits for SIM_SOPT2_RTCCLKOUTSEL. */ /*! @brief Read current value of the SIM_SOPT2_RTCCLKOUTSEL field. */ #define BR_SIM_SOPT2_RTCCLKOUTSEL(x) (BITBAND_ACCESS32(HW_SIM_SOPT2_ADDR(x), BP_SIM_SOPT2_RTCCLKOUTSEL)) /*! @brief Format value for bitfield SIM_SOPT2_RTCCLKOUTSEL. */ #define BF_SIM_SOPT2_RTCCLKOUTSEL(v) ((uint32_t)((uint32_t)(v) << BP_SIM_SOPT2_RTCCLKOUTSEL) & BM_SIM_SOPT2_RTCCLKOUTSEL) /*! @brief Set the RTCCLKOUTSEL field to a new value. */ #define BW_SIM_SOPT2_RTCCLKOUTSEL(x, v) (BITBAND_ACCESS32(HW_SIM_SOPT2_ADDR(x), BP_SIM_SOPT2_RTCCLKOUTSEL) = (v)) /*@}*/ /*! * @name Register SIM_SOPT2, field CLKOUTSEL[7:5] (RW) * * Selects the clock to output on the CLKOUT pin. * * Values: * - 000 - FlexBus CLKOUT * - 001 - Reserved * - 010 - Flash clock * - 011 - LPO clock (1 kHz) * - 100 - MCGIRCLK * - 101 - RTC 32.768kHz clock * - 110 - OSCERCLK0 * - 111 - IRC 48 MHz clock */ /*@{*/ #define BP_SIM_SOPT2_CLKOUTSEL (5U) /*!< Bit position for SIM_SOPT2_CLKOUTSEL. */ #define BM_SIM_SOPT2_CLKOUTSEL (0x000000E0U) /*!< Bit mask for SIM_SOPT2_CLKOUTSEL. */ #define BS_SIM_SOPT2_CLKOUTSEL (3U) /*!< Bit field size in bits for SIM_SOPT2_CLKOUTSEL. */ /*! @brief Read current value of the SIM_SOPT2_CLKOUTSEL field. */ #define BR_SIM_SOPT2_CLKOUTSEL(x) (HW_SIM_SOPT2(x).B.CLKOUTSEL) /*! @brief Format value for bitfield SIM_SOPT2_CLKOUTSEL. */ #define BF_SIM_SOPT2_CLKOUTSEL(v) ((uint32_t)((uint32_t)(v) << BP_SIM_SOPT2_CLKOUTSEL) & BM_SIM_SOPT2_CLKOUTSEL) /*! @brief Set the CLKOUTSEL field to a new value. */ #define BW_SIM_SOPT2_CLKOUTSEL(x, v) (HW_SIM_SOPT2_WR(x, (HW_SIM_SOPT2_RD(x) & ~BM_SIM_SOPT2_CLKOUTSEL) | BF_SIM_SOPT2_CLKOUTSEL(v))) /*@}*/ /*! * @name Register SIM_SOPT2, field FBSL[9:8] (RW) * * If flash security is enabled, then this field affects what CPU operations can * access off-chip via the FlexBus interface. This field has no effect if flash * security is not enabled. * * Values: * - 00 - All off-chip accesses (instruction and data) via the FlexBus are * disallowed. * - 01 - All off-chip accesses (instruction and data) via the FlexBus are * disallowed. * - 10 - Off-chip instruction accesses are disallowed. Data accesses are * allowed. * - 11 - Off-chip instruction accesses and data accesses are allowed. */ /*@{*/ #define BP_SIM_SOPT2_FBSL (8U) /*!< Bit position for SIM_SOPT2_FBSL. */ #define BM_SIM_SOPT2_FBSL (0x00000300U) /*!< Bit mask for SIM_SOPT2_FBSL. */ #define BS_SIM_SOPT2_FBSL (2U) /*!< Bit field size in bits for SIM_SOPT2_FBSL. */ /*! @brief Read current value of the SIM_SOPT2_FBSL field. */ #define BR_SIM_SOPT2_FBSL(x) (HW_SIM_SOPT2(x).B.FBSL) /*! @brief Format value for bitfield SIM_SOPT2_FBSL. */ #define BF_SIM_SOPT2_FBSL(v) ((uint32_t)((uint32_t)(v) << BP_SIM_SOPT2_FBSL) & BM_SIM_SOPT2_FBSL) /*! @brief Set the FBSL field to a new value. */ #define BW_SIM_SOPT2_FBSL(x, v) (HW_SIM_SOPT2_WR(x, (HW_SIM_SOPT2_RD(x) & ~BM_SIM_SOPT2_FBSL) | BF_SIM_SOPT2_FBSL(v))) /*@}*/ /*! * @name Register SIM_SOPT2, field PTD7PAD[11] (RW) * * Controls the output drive strength of the PTD7 pin by selecting either one or * two pads to drive it. * * Values: * - 0 - Single-pad drive strength for PTD7. * - 1 - Double pad drive strength for PTD7. */ /*@{*/ #define BP_SIM_SOPT2_PTD7PAD (11U) /*!< Bit position for SIM_SOPT2_PTD7PAD. */ #define BM_SIM_SOPT2_PTD7PAD (0x00000800U) /*!< Bit mask for SIM_SOPT2_PTD7PAD. */ #define BS_SIM_SOPT2_PTD7PAD (1U) /*!< Bit field size in bits for SIM_SOPT2_PTD7PAD. */ /*! @brief Read current value of the SIM_SOPT2_PTD7PAD field. */ #define BR_SIM_SOPT2_PTD7PAD(x) (BITBAND_ACCESS32(HW_SIM_SOPT2_ADDR(x), BP_SIM_SOPT2_PTD7PAD)) /*! @brief Format value for bitfield SIM_SOPT2_PTD7PAD. */ #define BF_SIM_SOPT2_PTD7PAD(v) ((uint32_t)((uint32_t)(v) << BP_SIM_SOPT2_PTD7PAD) & BM_SIM_SOPT2_PTD7PAD) /*! @brief Set the PTD7PAD field to a new value. */ #define BW_SIM_SOPT2_PTD7PAD(x, v) (BITBAND_ACCESS32(HW_SIM_SOPT2_ADDR(x), BP_SIM_SOPT2_PTD7PAD) = (v)) /*@}*/ /*! * @name Register SIM_SOPT2, field TRACECLKSEL[12] (RW) * * Selects the core/system clock or MCG output clock (MCGOUTCLK) as the trace * clock source. * * Values: * - 0 - MCGOUTCLK * - 1 - Core/system clock */ /*@{*/ #define BP_SIM_SOPT2_TRACECLKSEL (12U) /*!< Bit position for SIM_SOPT2_TRACECLKSEL. */ #define BM_SIM_SOPT2_TRACECLKSEL (0x00001000U) /*!< Bit mask for SIM_SOPT2_TRACECLKSEL. */ #define BS_SIM_SOPT2_TRACECLKSEL (1U) /*!< Bit field size in bits for SIM_SOPT2_TRACECLKSEL. */ /*! @brief Read current value of the SIM_SOPT2_TRACECLKSEL field. */ #define BR_SIM_SOPT2_TRACECLKSEL(x) (BITBAND_ACCESS32(HW_SIM_SOPT2_ADDR(x), BP_SIM_SOPT2_TRACECLKSEL)) /*! @brief Format value for bitfield SIM_SOPT2_TRACECLKSEL. */ #define BF_SIM_SOPT2_TRACECLKSEL(v) ((uint32_t)((uint32_t)(v) << BP_SIM_SOPT2_TRACECLKSEL) & BM_SIM_SOPT2_TRACECLKSEL) /*! @brief Set the TRACECLKSEL field to a new value. */ #define BW_SIM_SOPT2_TRACECLKSEL(x, v) (BITBAND_ACCESS32(HW_SIM_SOPT2_ADDR(x), BP_SIM_SOPT2_TRACECLKSEL) = (v)) /*@}*/ /*! * @name Register SIM_SOPT2, field PLLFLLSEL[17:16] (RW) * * Selects the high frequency clock for various peripheral clocking options. * * Values: * - 00 - MCGFLLCLK clock * - 01 - MCGPLLCLK clock * - 10 - Reserved * - 11 - IRC48 MHz clock */ /*@{*/ #define BP_SIM_SOPT2_PLLFLLSEL (16U) /*!< Bit position for SIM_SOPT2_PLLFLLSEL. */ #define BM_SIM_SOPT2_PLLFLLSEL (0x00030000U) /*!< Bit mask for SIM_SOPT2_PLLFLLSEL. */ #define BS_SIM_SOPT2_PLLFLLSEL (2U) /*!< Bit field size in bits for SIM_SOPT2_PLLFLLSEL. */ /*! @brief Read current value of the SIM_SOPT2_PLLFLLSEL field. */ #define BR_SIM_SOPT2_PLLFLLSEL(x) (HW_SIM_SOPT2(x).B.PLLFLLSEL) /*! @brief Format value for bitfield SIM_SOPT2_PLLFLLSEL. */ #define BF_SIM_SOPT2_PLLFLLSEL(v) ((uint32_t)((uint32_t)(v) << BP_SIM_SOPT2_PLLFLLSEL) & BM_SIM_SOPT2_PLLFLLSEL) /*! @brief Set the PLLFLLSEL field to a new value. */ #define BW_SIM_SOPT2_PLLFLLSEL(x, v) (HW_SIM_SOPT2_WR(x, (HW_SIM_SOPT2_RD(x) & ~BM_SIM_SOPT2_PLLFLLSEL) | BF_SIM_SOPT2_PLLFLLSEL(v))) /*@}*/ /*! * @name Register SIM_SOPT2, field USBSRC[18] (RW) * * Selects the clock source for the USB 48 MHz clock. * * Values: * - 0 - External bypass clock (USB_CLKIN). * - 1 - MCGFLLCLK , or MCGPLLCLK , or IRC48M clock as selected by * SOPT2[PLLFLLSEL], and then divided by the USB fractional divider as configured by * SIM_CLKDIV2[USBFRAC, USBDIV]. */ /*@{*/ #define BP_SIM_SOPT2_USBSRC (18U) /*!< Bit position for SIM_SOPT2_USBSRC. */ #define BM_SIM_SOPT2_USBSRC (0x00040000U) /*!< Bit mask for SIM_SOPT2_USBSRC. */ #define BS_SIM_SOPT2_USBSRC (1U) /*!< Bit field size in bits for SIM_SOPT2_USBSRC. */ /*! @brief Read current value of the SIM_SOPT2_USBSRC field. */ #define BR_SIM_SOPT2_USBSRC(x) (BITBAND_ACCESS32(HW_SIM_SOPT2_ADDR(x), BP_SIM_SOPT2_USBSRC)) /*! @brief Format value for bitfield SIM_SOPT2_USBSRC. */ #define BF_SIM_SOPT2_USBSRC(v) ((uint32_t)((uint32_t)(v) << BP_SIM_SOPT2_USBSRC) & BM_SIM_SOPT2_USBSRC) /*! @brief Set the USBSRC field to a new value. */ #define BW_SIM_SOPT2_USBSRC(x, v) (BITBAND_ACCESS32(HW_SIM_SOPT2_ADDR(x), BP_SIM_SOPT2_USBSRC) = (v)) /*@}*/ /*! * @name Register SIM_SOPT2, field RMIISRC[19] (RW) * * Selects the clock source for the Ethernet RMII interface * * Values: * - 0 - EXTAL clock * - 1 - External bypass clock (ENET_1588_CLKIN). */ /*@{*/ #define BP_SIM_SOPT2_RMIISRC (19U) /*!< Bit position for SIM_SOPT2_RMIISRC. */ #define BM_SIM_SOPT2_RMIISRC (0x00080000U) /*!< Bit mask for SIM_SOPT2_RMIISRC. */ #define BS_SIM_SOPT2_RMIISRC (1U) /*!< Bit field size in bits for SIM_SOPT2_RMIISRC. */ /*! @brief Read current value of the SIM_SOPT2_RMIISRC field. */ #define BR_SIM_SOPT2_RMIISRC(x) (BITBAND_ACCESS32(HW_SIM_SOPT2_ADDR(x), BP_SIM_SOPT2_RMIISRC)) /*! @brief Format value for bitfield SIM_SOPT2_RMIISRC. */ #define BF_SIM_SOPT2_RMIISRC(v) ((uint32_t)((uint32_t)(v) << BP_SIM_SOPT2_RMIISRC) & BM_SIM_SOPT2_RMIISRC) /*! @brief Set the RMIISRC field to a new value. */ #define BW_SIM_SOPT2_RMIISRC(x, v) (BITBAND_ACCESS32(HW_SIM_SOPT2_ADDR(x), BP_SIM_SOPT2_RMIISRC) = (v)) /*@}*/ /*! * @name Register SIM_SOPT2, field TIMESRC[21:20] (RW) * * Selects the clock source for the Ethernet timestamp clock. * * Values: * - 00 - Core/system clock. * - 01 - MCGFLLCLK , or MCGPLLCLK , or IRC48M clock as selected by * SOPT2[PLLFLLSEL]. * - 10 - OSCERCLK clock * - 11 - External bypass clock (ENET_1588_CLKIN). */ /*@{*/ #define BP_SIM_SOPT2_TIMESRC (20U) /*!< Bit position for SIM_SOPT2_TIMESRC. */ #define BM_SIM_SOPT2_TIMESRC (0x00300000U) /*!< Bit mask for SIM_SOPT2_TIMESRC. */ #define BS_SIM_SOPT2_TIMESRC (2U) /*!< Bit field size in bits for SIM_SOPT2_TIMESRC. */ /*! @brief Read current value of the SIM_SOPT2_TIMESRC field. */ #define BR_SIM_SOPT2_TIMESRC(x) (HW_SIM_SOPT2(x).B.TIMESRC) /*! @brief Format value for bitfield SIM_SOPT2_TIMESRC. */ #define BF_SIM_SOPT2_TIMESRC(v) ((uint32_t)((uint32_t)(v) << BP_SIM_SOPT2_TIMESRC) & BM_SIM_SOPT2_TIMESRC) /*! @brief Set the TIMESRC field to a new value. */ #define BW_SIM_SOPT2_TIMESRC(x, v) (HW_SIM_SOPT2_WR(x, (HW_SIM_SOPT2_RD(x) & ~BM_SIM_SOPT2_TIMESRC) | BF_SIM_SOPT2_TIMESRC(v))) /*@}*/ /*! * @name Register SIM_SOPT2, field SDHCSRC[29:28] (RW) * * Selects the clock source for the SDHC clock . * * Values: * - 00 - Core/system clock. * - 01 - MCGFLLCLK, or MCGPLLCLK , or IRC48M clock as selected by * SOPT2[PLLFLLSEL]. * - 10 - OSCERCLK clock * - 11 - External bypass clock (SDHC0_CLKIN) */ /*@{*/ #define BP_SIM_SOPT2_SDHCSRC (28U) /*!< Bit position for SIM_SOPT2_SDHCSRC. */ #define BM_SIM_SOPT2_SDHCSRC (0x30000000U) /*!< Bit mask for SIM_SOPT2_SDHCSRC. */ #define BS_SIM_SOPT2_SDHCSRC (2U) /*!< Bit field size in bits for SIM_SOPT2_SDHCSRC. */ /*! @brief Read current value of the SIM_SOPT2_SDHCSRC field. */ #define BR_SIM_SOPT2_SDHCSRC(x) (HW_SIM_SOPT2(x).B.SDHCSRC) /*! @brief Format value for bitfield SIM_SOPT2_SDHCSRC. */ #define BF_SIM_SOPT2_SDHCSRC(v) ((uint32_t)((uint32_t)(v) << BP_SIM_SOPT2_SDHCSRC) & BM_SIM_SOPT2_SDHCSRC) /*! @brief Set the SDHCSRC field to a new value. */ #define BW_SIM_SOPT2_SDHCSRC(x, v) (HW_SIM_SOPT2_WR(x, (HW_SIM_SOPT2_RD(x) & ~BM_SIM_SOPT2_SDHCSRC) | BF_SIM_SOPT2_SDHCSRC(v))) /*@}*/ /******************************************************************************* * HW_SIM_SOPT4 - System Options Register 4 ******************************************************************************/ /*! * @brief HW_SIM_SOPT4 - System Options Register 4 (RW) * * Reset value: 0x00000000U */ typedef union _hw_sim_sopt4 { uint32_t U; struct _hw_sim_sopt4_bitfields { uint32_t FTM0FLT0 : 1; /*!< [0] FTM0 Fault 0 Select */ uint32_t FTM0FLT1 : 1; /*!< [1] FTM0 Fault 1 Select */ uint32_t FTM0FLT2 : 1; /*!< [2] FTM0 Fault 2 Select */ uint32_t RESERVED0 : 1; /*!< [3] */ uint32_t FTM1FLT0 : 1; /*!< [4] FTM1 Fault 0 Select */ uint32_t RESERVED1 : 3; /*!< [7:5] */ uint32_t FTM2FLT0 : 1; /*!< [8] FTM2 Fault 0 Select */ uint32_t RESERVED2 : 3; /*!< [11:9] */ uint32_t FTM3FLT0 : 1; /*!< [12] FTM3 Fault 0 Select */ uint32_t RESERVED3 : 5; /*!< [17:13] */ uint32_t FTM1CH0SRC : 2; /*!< [19:18] FTM1 channel 0 input capture * source select */ uint32_t FTM2CH0SRC : 2; /*!< [21:20] FTM2 channel 0 input capture * source select */ uint32_t RESERVED4 : 2; /*!< [23:22] */ uint32_t FTM0CLKSEL : 1; /*!< [24] FlexTimer 0 External Clock Pin * Select */ uint32_t FTM1CLKSEL : 1; /*!< [25] FTM1 External Clock Pin Select */ uint32_t FTM2CLKSEL : 1; /*!< [26] FlexTimer 2 External Clock Pin * Select */ uint32_t FTM3CLKSEL : 1; /*!< [27] FlexTimer 3 External Clock Pin * Select */ uint32_t FTM0TRG0SRC : 1; /*!< [28] FlexTimer 0 Hardware Trigger 0 * Source Select */ uint32_t FTM0TRG1SRC : 1; /*!< [29] FlexTimer 0 Hardware Trigger 1 * Source Select */ uint32_t FTM3TRG0SRC : 1; /*!< [30] FlexTimer 3 Hardware Trigger 0 * Source Select */ uint32_t FTM3TRG1SRC : 1; /*!< [31] FlexTimer 3 Hardware Trigger 1 * Source Select */ } B; } hw_sim_sopt4_t; /*! * @name Constants and macros for entire SIM_SOPT4 register */ /*@{*/ #define HW_SIM_SOPT4_ADDR(x) ((x) + 0x100CU) #define HW_SIM_SOPT4(x) (*(__IO hw_sim_sopt4_t *) HW_SIM_SOPT4_ADDR(x)) #define HW_SIM_SOPT4_RD(x) (HW_SIM_SOPT4(x).U) #define HW_SIM_SOPT4_WR(x, v) (HW_SIM_SOPT4(x).U = (v)) #define HW_SIM_SOPT4_SET(x, v) (HW_SIM_SOPT4_WR(x, HW_SIM_SOPT4_RD(x) | (v))) #define HW_SIM_SOPT4_CLR(x, v) (HW_SIM_SOPT4_WR(x, HW_SIM_SOPT4_RD(x) & ~(v))) #define HW_SIM_SOPT4_TOG(x, v) (HW_SIM_SOPT4_WR(x, HW_SIM_SOPT4_RD(x) ^ (v))) /*@}*/ /* * Constants & macros for individual SIM_SOPT4 bitfields */ /*! * @name Register SIM_SOPT4, field FTM0FLT0[0] (RW) * * Selects the source of FTM0 fault 0. The pin source for fault 0 must be * configured for the FTM module fault function through the appropriate pin control * register in the port control module. * * Values: * - 0 - FTM0_FLT0 pin * - 1 - CMP0 out */ /*@{*/ #define BP_SIM_SOPT4_FTM0FLT0 (0U) /*!< Bit position for SIM_SOPT4_FTM0FLT0. */ #define BM_SIM_SOPT4_FTM0FLT0 (0x00000001U) /*!< Bit mask for SIM_SOPT4_FTM0FLT0. */ #define BS_SIM_SOPT4_FTM0FLT0 (1U) /*!< Bit field size in bits for SIM_SOPT4_FTM0FLT0. */ /*! @brief Read current value of the SIM_SOPT4_FTM0FLT0 field. */ #define BR_SIM_SOPT4_FTM0FLT0(x) (BITBAND_ACCESS32(HW_SIM_SOPT4_ADDR(x), BP_SIM_SOPT4_FTM0FLT0)) /*! @brief Format value for bitfield SIM_SOPT4_FTM0FLT0. */ #define BF_SIM_SOPT4_FTM0FLT0(v) ((uint32_t)((uint32_t)(v) << BP_SIM_SOPT4_FTM0FLT0) & BM_SIM_SOPT4_FTM0FLT0) /*! @brief Set the FTM0FLT0 field to a new value. */ #define BW_SIM_SOPT4_FTM0FLT0(x, v) (BITBAND_ACCESS32(HW_SIM_SOPT4_ADDR(x), BP_SIM_SOPT4_FTM0FLT0) = (v)) /*@}*/ /*! * @name Register SIM_SOPT4, field FTM0FLT1[1] (RW) * * Selects the source of FTM0 fault 1. The pin source for fault 1 must be * configured for the FTM module fault function through the appropriate pin control * register in the port control module. * * Values: * - 0 - FTM0_FLT1 pin * - 1 - CMP1 out */ /*@{*/ #define BP_SIM_SOPT4_FTM0FLT1 (1U) /*!< Bit position for SIM_SOPT4_FTM0FLT1. */ #define BM_SIM_SOPT4_FTM0FLT1 (0x00000002U) /*!< Bit mask for SIM_SOPT4_FTM0FLT1. */ #define BS_SIM_SOPT4_FTM0FLT1 (1U) /*!< Bit field size in bits for SIM_SOPT4_FTM0FLT1. */ /*! @brief Read current value of the SIM_SOPT4_FTM0FLT1 field. */ #define BR_SIM_SOPT4_FTM0FLT1(x) (BITBAND_ACCESS32(HW_SIM_SOPT4_ADDR(x), BP_SIM_SOPT4_FTM0FLT1)) /*! @brief Format value for bitfield SIM_SOPT4_FTM0FLT1. */ #define BF_SIM_SOPT4_FTM0FLT1(v) ((uint32_t)((uint32_t)(v) << BP_SIM_SOPT4_FTM0FLT1) & BM_SIM_SOPT4_FTM0FLT1) /*! @brief Set the FTM0FLT1 field to a new value. */ #define BW_SIM_SOPT4_FTM0FLT1(x, v) (BITBAND_ACCESS32(HW_SIM_SOPT4_ADDR(x), BP_SIM_SOPT4_FTM0FLT1) = (v)) /*@}*/ /*! * @name Register SIM_SOPT4, field FTM0FLT2[2] (RW) * * Selects the source of FTM0 fault 2. The pin source for fault 2 must be * configured for the FTM module fault function through the appropriate pin control * register in the port control module. * * Values: * - 0 - FTM0_FLT2 pin * - 1 - CMP2 out */ /*@{*/ #define BP_SIM_SOPT4_FTM0FLT2 (2U) /*!< Bit position for SIM_SOPT4_FTM0FLT2. */ #define BM_SIM_SOPT4_FTM0FLT2 (0x00000004U) /*!< Bit mask for SIM_SOPT4_FTM0FLT2. */ #define BS_SIM_SOPT4_FTM0FLT2 (1U) /*!< Bit field size in bits for SIM_SOPT4_FTM0FLT2. */ /*! @brief Read current value of the SIM_SOPT4_FTM0FLT2 field. */ #define BR_SIM_SOPT4_FTM0FLT2(x) (BITBAND_ACCESS32(HW_SIM_SOPT4_ADDR(x), BP_SIM_SOPT4_FTM0FLT2)) /*! @brief Format value for bitfield SIM_SOPT4_FTM0FLT2. */ #define BF_SIM_SOPT4_FTM0FLT2(v) ((uint32_t)((uint32_t)(v) << BP_SIM_SOPT4_FTM0FLT2) & BM_SIM_SOPT4_FTM0FLT2) /*! @brief Set the FTM0FLT2 field to a new value. */ #define BW_SIM_SOPT4_FTM0FLT2(x, v) (BITBAND_ACCESS32(HW_SIM_SOPT4_ADDR(x), BP_SIM_SOPT4_FTM0FLT2) = (v)) /*@}*/ /*! * @name Register SIM_SOPT4, field FTM1FLT0[4] (RW) * * Selects the source of FTM1 fault 0. The pin source for fault 0 must be * configured for the FTM module fault function through the appropriate pin control * register in the port control module. * * Values: * - 0 - FTM1_FLT0 pin * - 1 - CMP0 out */ /*@{*/ #define BP_SIM_SOPT4_FTM1FLT0 (4U) /*!< Bit position for SIM_SOPT4_FTM1FLT0. */ #define BM_SIM_SOPT4_FTM1FLT0 (0x00000010U) /*!< Bit mask for SIM_SOPT4_FTM1FLT0. */ #define BS_SIM_SOPT4_FTM1FLT0 (1U) /*!< Bit field size in bits for SIM_SOPT4_FTM1FLT0. */ /*! @brief Read current value of the SIM_SOPT4_FTM1FLT0 field. */ #define BR_SIM_SOPT4_FTM1FLT0(x) (BITBAND_ACCESS32(HW_SIM_SOPT4_ADDR(x), BP_SIM_SOPT4_FTM1FLT0)) /*! @brief Format value for bitfield SIM_SOPT4_FTM1FLT0. */ #define BF_SIM_SOPT4_FTM1FLT0(v) ((uint32_t)((uint32_t)(v) << BP_SIM_SOPT4_FTM1FLT0) & BM_SIM_SOPT4_FTM1FLT0) /*! @brief Set the FTM1FLT0 field to a new value. */ #define BW_SIM_SOPT4_FTM1FLT0(x, v) (BITBAND_ACCESS32(HW_SIM_SOPT4_ADDR(x), BP_SIM_SOPT4_FTM1FLT0) = (v)) /*@}*/ /*! * @name Register SIM_SOPT4, field FTM2FLT0[8] (RW) * * Selects the source of FTM2 fault 0. The pin source for fault 0 must be * configured for the FTM module fault function through the appropriate PORTx pin * control register. * * Values: * - 0 - FTM2_FLT0 pin * - 1 - CMP0 out */ /*@{*/ #define BP_SIM_SOPT4_FTM2FLT0 (8U) /*!< Bit position for SIM_SOPT4_FTM2FLT0. */ #define BM_SIM_SOPT4_FTM2FLT0 (0x00000100U) /*!< Bit mask for SIM_SOPT4_FTM2FLT0. */ #define BS_SIM_SOPT4_FTM2FLT0 (1U) /*!< Bit field size in bits for SIM_SOPT4_FTM2FLT0. */ /*! @brief Read current value of the SIM_SOPT4_FTM2FLT0 field. */ #define BR_SIM_SOPT4_FTM2FLT0(x) (BITBAND_ACCESS32(HW_SIM_SOPT4_ADDR(x), BP_SIM_SOPT4_FTM2FLT0)) /*! @brief Format value for bitfield SIM_SOPT4_FTM2FLT0. */ #define BF_SIM_SOPT4_FTM2FLT0(v) ((uint32_t)((uint32_t)(v) << BP_SIM_SOPT4_FTM2FLT0) & BM_SIM_SOPT4_FTM2FLT0) /*! @brief Set the FTM2FLT0 field to a new value. */ #define BW_SIM_SOPT4_FTM2FLT0(x, v) (BITBAND_ACCESS32(HW_SIM_SOPT4_ADDR(x), BP_SIM_SOPT4_FTM2FLT0) = (v)) /*@}*/ /*! * @name Register SIM_SOPT4, field FTM3FLT0[12] (RW) * * Selects the source of FTM3 fault 0. The pin source for fault 0 must be * configured for the FTM module fault function through the appropriate PORTx pin * control register. * * Values: * - 0 - FTM3_FLT0 pin * - 1 - CMP0 out */ /*@{*/ #define BP_SIM_SOPT4_FTM3FLT0 (12U) /*!< Bit position for SIM_SOPT4_FTM3FLT0. */ #define BM_SIM_SOPT4_FTM3FLT0 (0x00001000U) /*!< Bit mask for SIM_SOPT4_FTM3FLT0. */ #define BS_SIM_SOPT4_FTM3FLT0 (1U) /*!< Bit field size in bits for SIM_SOPT4_FTM3FLT0. */ /*! @brief Read current value of the SIM_SOPT4_FTM3FLT0 field. */ #define BR_SIM_SOPT4_FTM3FLT0(x) (BITBAND_ACCESS32(HW_SIM_SOPT4_ADDR(x), BP_SIM_SOPT4_FTM3FLT0)) /*! @brief Format value for bitfield SIM_SOPT4_FTM3FLT0. */ #define BF_SIM_SOPT4_FTM3FLT0(v) ((uint32_t)((uint32_t)(v) << BP_SIM_SOPT4_FTM3FLT0) & BM_SIM_SOPT4_FTM3FLT0) /*! @brief Set the FTM3FLT0 field to a new value. */ #define BW_SIM_SOPT4_FTM3FLT0(x, v) (BITBAND_ACCESS32(HW_SIM_SOPT4_ADDR(x), BP_SIM_SOPT4_FTM3FLT0) = (v)) /*@}*/ /*! * @name Register SIM_SOPT4, field FTM1CH0SRC[19:18] (RW) * * Selects the source for FTM1 channel 0 input capture. When the FTM is not in * input capture mode, clear this field. * * Values: * - 00 - FTM1_CH0 signal * - 01 - CMP0 output * - 10 - CMP1 output * - 11 - USB start of frame pulse */ /*@{*/ #define BP_SIM_SOPT4_FTM1CH0SRC (18U) /*!< Bit position for SIM_SOPT4_FTM1CH0SRC. */ #define BM_SIM_SOPT4_FTM1CH0SRC (0x000C0000U) /*!< Bit mask for SIM_SOPT4_FTM1CH0SRC. */ #define BS_SIM_SOPT4_FTM1CH0SRC (2U) /*!< Bit field size in bits for SIM_SOPT4_FTM1CH0SRC. */ /*! @brief Read current value of the SIM_SOPT4_FTM1CH0SRC field. */ #define BR_SIM_SOPT4_FTM1CH0SRC(x) (HW_SIM_SOPT4(x).B.FTM1CH0SRC) /*! @brief Format value for bitfield SIM_SOPT4_FTM1CH0SRC. */ #define BF_SIM_SOPT4_FTM1CH0SRC(v) ((uint32_t)((uint32_t)(v) << BP_SIM_SOPT4_FTM1CH0SRC) & BM_SIM_SOPT4_FTM1CH0SRC) /*! @brief Set the FTM1CH0SRC field to a new value. */ #define BW_SIM_SOPT4_FTM1CH0SRC(x, v) (HW_SIM_SOPT4_WR(x, (HW_SIM_SOPT4_RD(x) & ~BM_SIM_SOPT4_FTM1CH0SRC) | BF_SIM_SOPT4_FTM1CH0SRC(v))) /*@}*/ /*! * @name Register SIM_SOPT4, field FTM2CH0SRC[21:20] (RW) * * Selects the source for FTM2 channel 0 input capture. When the FTM is not in * input capture mode, clear this field. * * Values: * - 00 - FTM2_CH0 signal * - 01 - CMP0 output * - 10 - CMP1 output * - 11 - Reserved */ /*@{*/ #define BP_SIM_SOPT4_FTM2CH0SRC (20U) /*!< Bit position for SIM_SOPT4_FTM2CH0SRC. */ #define BM_SIM_SOPT4_FTM2CH0SRC (0x00300000U) /*!< Bit mask for SIM_SOPT4_FTM2CH0SRC. */ #define BS_SIM_SOPT4_FTM2CH0SRC (2U) /*!< Bit field size in bits for SIM_SOPT4_FTM2CH0SRC. */ /*! @brief Read current value of the SIM_SOPT4_FTM2CH0SRC field. */ #define BR_SIM_SOPT4_FTM2CH0SRC(x) (HW_SIM_SOPT4(x).B.FTM2CH0SRC) /*! @brief Format value for bitfield SIM_SOPT4_FTM2CH0SRC. */ #define BF_SIM_SOPT4_FTM2CH0SRC(v) ((uint32_t)((uint32_t)(v) << BP_SIM_SOPT4_FTM2CH0SRC) & BM_SIM_SOPT4_FTM2CH0SRC) /*! @brief Set the FTM2CH0SRC field to a new value. */ #define BW_SIM_SOPT4_FTM2CH0SRC(x, v) (HW_SIM_SOPT4_WR(x, (HW_SIM_SOPT4_RD(x) & ~BM_SIM_SOPT4_FTM2CH0SRC) | BF_SIM_SOPT4_FTM2CH0SRC(v))) /*@}*/ /*! * @name Register SIM_SOPT4, field FTM0CLKSEL[24] (RW) * * Selects the external pin used to drive the clock to the FTM0 module. The * selected pin must also be configured for the FTM external clock function through * the appropriate pin control register in the port control module. * * Values: * - 0 - FTM_CLK0 pin * - 1 - FTM_CLK1 pin */ /*@{*/ #define BP_SIM_SOPT4_FTM0CLKSEL (24U) /*!< Bit position for SIM_SOPT4_FTM0CLKSEL. */ #define BM_SIM_SOPT4_FTM0CLKSEL (0x01000000U) /*!< Bit mask for SIM_SOPT4_FTM0CLKSEL. */ #define BS_SIM_SOPT4_FTM0CLKSEL (1U) /*!< Bit field size in bits for SIM_SOPT4_FTM0CLKSEL. */ /*! @brief Read current value of the SIM_SOPT4_FTM0CLKSEL field. */ #define BR_SIM_SOPT4_FTM0CLKSEL(x) (BITBAND_ACCESS32(HW_SIM_SOPT4_ADDR(x), BP_SIM_SOPT4_FTM0CLKSEL)) /*! @brief Format value for bitfield SIM_SOPT4_FTM0CLKSEL. */ #define BF_SIM_SOPT4_FTM0CLKSEL(v) ((uint32_t)((uint32_t)(v) << BP_SIM_SOPT4_FTM0CLKSEL) & BM_SIM_SOPT4_FTM0CLKSEL) /*! @brief Set the FTM0CLKSEL field to a new value. */ #define BW_SIM_SOPT4_FTM0CLKSEL(x, v) (BITBAND_ACCESS32(HW_SIM_SOPT4_ADDR(x), BP_SIM_SOPT4_FTM0CLKSEL) = (v)) /*@}*/ /*! * @name Register SIM_SOPT4, field FTM1CLKSEL[25] (RW) * * Selects the external pin used to drive the clock to the FTM1 module. The * selected pin must also be configured for the FTM external clock function through * the appropriate pin control register in the port control module. * * Values: * - 0 - FTM_CLK0 pin * - 1 - FTM_CLK1 pin */ /*@{*/ #define BP_SIM_SOPT4_FTM1CLKSEL (25U) /*!< Bit position for SIM_SOPT4_FTM1CLKSEL. */ #define BM_SIM_SOPT4_FTM1CLKSEL (0x02000000U) /*!< Bit mask for SIM_SOPT4_FTM1CLKSEL. */ #define BS_SIM_SOPT4_FTM1CLKSEL (1U) /*!< Bit field size in bits for SIM_SOPT4_FTM1CLKSEL. */ /*! @brief Read current value of the SIM_SOPT4_FTM1CLKSEL field. */ #define BR_SIM_SOPT4_FTM1CLKSEL(x) (BITBAND_ACCESS32(HW_SIM_SOPT4_ADDR(x), BP_SIM_SOPT4_FTM1CLKSEL)) /*! @brief Format value for bitfield SIM_SOPT4_FTM1CLKSEL. */ #define BF_SIM_SOPT4_FTM1CLKSEL(v) ((uint32_t)((uint32_t)(v) << BP_SIM_SOPT4_FTM1CLKSEL) & BM_SIM_SOPT4_FTM1CLKSEL) /*! @brief Set the FTM1CLKSEL field to a new value. */ #define BW_SIM_SOPT4_FTM1CLKSEL(x, v) (BITBAND_ACCESS32(HW_SIM_SOPT4_ADDR(x), BP_SIM_SOPT4_FTM1CLKSEL) = (v)) /*@}*/ /*! * @name Register SIM_SOPT4, field FTM2CLKSEL[26] (RW) * * Selects the external pin used to drive the clock to the FTM2 module. The * selected pin must also be configured for the FTM2 module external clock function * through the appropriate pin control register in the port control module. * * Values: * - 0 - FTM2 external clock driven by FTM_CLK0 pin. * - 1 - FTM2 external clock driven by FTM_CLK1 pin. */ /*@{*/ #define BP_SIM_SOPT4_FTM2CLKSEL (26U) /*!< Bit position for SIM_SOPT4_FTM2CLKSEL. */ #define BM_SIM_SOPT4_FTM2CLKSEL (0x04000000U) /*!< Bit mask for SIM_SOPT4_FTM2CLKSEL. */ #define BS_SIM_SOPT4_FTM2CLKSEL (1U) /*!< Bit field size in bits for SIM_SOPT4_FTM2CLKSEL. */ /*! @brief Read current value of the SIM_SOPT4_FTM2CLKSEL field. */ #define BR_SIM_SOPT4_FTM2CLKSEL(x) (BITBAND_ACCESS32(HW_SIM_SOPT4_ADDR(x), BP_SIM_SOPT4_FTM2CLKSEL)) /*! @brief Format value for bitfield SIM_SOPT4_FTM2CLKSEL. */ #define BF_SIM_SOPT4_FTM2CLKSEL(v) ((uint32_t)((uint32_t)(v) << BP_SIM_SOPT4_FTM2CLKSEL) & BM_SIM_SOPT4_FTM2CLKSEL) /*! @brief Set the FTM2CLKSEL field to a new value. */ #define BW_SIM_SOPT4_FTM2CLKSEL(x, v) (BITBAND_ACCESS32(HW_SIM_SOPT4_ADDR(x), BP_SIM_SOPT4_FTM2CLKSEL) = (v)) /*@}*/ /*! * @name Register SIM_SOPT4, field FTM3CLKSEL[27] (RW) * * Selects the external pin used to drive the clock to the FTM3 module. The * selected pin must also be configured for the FTM3 module external clock function * through the appropriate pin control register in the port control module. * * Values: * - 0 - FTM3 external clock driven by FTM_CLK0 pin. * - 1 - FTM3 external clock driven by FTM_CLK1 pin. */ /*@{*/ #define BP_SIM_SOPT4_FTM3CLKSEL (27U) /*!< Bit position for SIM_SOPT4_FTM3CLKSEL. */ #define BM_SIM_SOPT4_FTM3CLKSEL (0x08000000U) /*!< Bit mask for SIM_SOPT4_FTM3CLKSEL. */ #define BS_SIM_SOPT4_FTM3CLKSEL (1U) /*!< Bit field size in bits for SIM_SOPT4_FTM3CLKSEL. */ /*! @brief Read current value of the SIM_SOPT4_FTM3CLKSEL field. */ #define BR_SIM_SOPT4_FTM3CLKSEL(x) (BITBAND_ACCESS32(HW_SIM_SOPT4_ADDR(x), BP_SIM_SOPT4_FTM3CLKSEL)) /*! @brief Format value for bitfield SIM_SOPT4_FTM3CLKSEL. */ #define BF_SIM_SOPT4_FTM3CLKSEL(v) ((uint32_t)((uint32_t)(v) << BP_SIM_SOPT4_FTM3CLKSEL) & BM_SIM_SOPT4_FTM3CLKSEL) /*! @brief Set the FTM3CLKSEL field to a new value. */ #define BW_SIM_SOPT4_FTM3CLKSEL(x, v) (BITBAND_ACCESS32(HW_SIM_SOPT4_ADDR(x), BP_SIM_SOPT4_FTM3CLKSEL) = (v)) /*@}*/ /*! * @name Register SIM_SOPT4, field FTM0TRG0SRC[28] (RW) * * Selects the source of FTM0 hardware trigger 0. * * Values: * - 0 - HSCMP0 output drives FTM0 hardware trigger 0 * - 1 - FTM1 channel match drives FTM0 hardware trigger 0 */ /*@{*/ #define BP_SIM_SOPT4_FTM0TRG0SRC (28U) /*!< Bit position for SIM_SOPT4_FTM0TRG0SRC. */ #define BM_SIM_SOPT4_FTM0TRG0SRC (0x10000000U) /*!< Bit mask for SIM_SOPT4_FTM0TRG0SRC. */ #define BS_SIM_SOPT4_FTM0TRG0SRC (1U) /*!< Bit field size in bits for SIM_SOPT4_FTM0TRG0SRC. */ /*! @brief Read current value of the SIM_SOPT4_FTM0TRG0SRC field. */ #define BR_SIM_SOPT4_FTM0TRG0SRC(x) (BITBAND_ACCESS32(HW_SIM_SOPT4_ADDR(x), BP_SIM_SOPT4_FTM0TRG0SRC)) /*! @brief Format value for bitfield SIM_SOPT4_FTM0TRG0SRC. */ #define BF_SIM_SOPT4_FTM0TRG0SRC(v) ((uint32_t)((uint32_t)(v) << BP_SIM_SOPT4_FTM0TRG0SRC) & BM_SIM_SOPT4_FTM0TRG0SRC) /*! @brief Set the FTM0TRG0SRC field to a new value. */ #define BW_SIM_SOPT4_FTM0TRG0SRC(x, v) (BITBAND_ACCESS32(HW_SIM_SOPT4_ADDR(x), BP_SIM_SOPT4_FTM0TRG0SRC) = (v)) /*@}*/ /*! * @name Register SIM_SOPT4, field FTM0TRG1SRC[29] (RW) * * Selects the source of FTM0 hardware trigger 1. * * Values: * - 0 - PDB output trigger 1 drives FTM0 hardware trigger 1 * - 1 - FTM2 channel match drives FTM0 hardware trigger 1 */ /*@{*/ #define BP_SIM_SOPT4_FTM0TRG1SRC (29U) /*!< Bit position for SIM_SOPT4_FTM0TRG1SRC. */ #define BM_SIM_SOPT4_FTM0TRG1SRC (0x20000000U) /*!< Bit mask for SIM_SOPT4_FTM0TRG1SRC. */ #define BS_SIM_SOPT4_FTM0TRG1SRC (1U) /*!< Bit field size in bits for SIM_SOPT4_FTM0TRG1SRC. */ /*! @brief Read current value of the SIM_SOPT4_FTM0TRG1SRC field. */ #define BR_SIM_SOPT4_FTM0TRG1SRC(x) (BITBAND_ACCESS32(HW_SIM_SOPT4_ADDR(x), BP_SIM_SOPT4_FTM0TRG1SRC)) /*! @brief Format value for bitfield SIM_SOPT4_FTM0TRG1SRC. */ #define BF_SIM_SOPT4_FTM0TRG1SRC(v) ((uint32_t)((uint32_t)(v) << BP_SIM_SOPT4_FTM0TRG1SRC) & BM_SIM_SOPT4_FTM0TRG1SRC) /*! @brief Set the FTM0TRG1SRC field to a new value. */ #define BW_SIM_SOPT4_FTM0TRG1SRC(x, v) (BITBAND_ACCESS32(HW_SIM_SOPT4_ADDR(x), BP_SIM_SOPT4_FTM0TRG1SRC) = (v)) /*@}*/ /*! * @name Register SIM_SOPT4, field FTM3TRG0SRC[30] (RW) * * Selects the source of FTM3 hardware trigger 0. * * Values: * - 0 - Reserved * - 1 - FTM1 channel match drives FTM3 hardware trigger 0 */ /*@{*/ #define BP_SIM_SOPT4_FTM3TRG0SRC (30U) /*!< Bit position for SIM_SOPT4_FTM3TRG0SRC. */ #define BM_SIM_SOPT4_FTM3TRG0SRC (0x40000000U) /*!< Bit mask for SIM_SOPT4_FTM3TRG0SRC. */ #define BS_SIM_SOPT4_FTM3TRG0SRC (1U) /*!< Bit field size in bits for SIM_SOPT4_FTM3TRG0SRC. */ /*! @brief Read current value of the SIM_SOPT4_FTM3TRG0SRC field. */ #define BR_SIM_SOPT4_FTM3TRG0SRC(x) (BITBAND_ACCESS32(HW_SIM_SOPT4_ADDR(x), BP_SIM_SOPT4_FTM3TRG0SRC)) /*! @brief Format value for bitfield SIM_SOPT4_FTM3TRG0SRC. */ #define BF_SIM_SOPT4_FTM3TRG0SRC(v) ((uint32_t)((uint32_t)(v) << BP_SIM_SOPT4_FTM3TRG0SRC) & BM_SIM_SOPT4_FTM3TRG0SRC) /*! @brief Set the FTM3TRG0SRC field to a new value. */ #define BW_SIM_SOPT4_FTM3TRG0SRC(x, v) (BITBAND_ACCESS32(HW_SIM_SOPT4_ADDR(x), BP_SIM_SOPT4_FTM3TRG0SRC) = (v)) /*@}*/ /*! * @name Register SIM_SOPT4, field FTM3TRG1SRC[31] (RW) * * Selects the source of FTM3 hardware trigger 1. * * Values: * - 0 - Reserved * - 1 - FTM2 channel match drives FTM3 hardware trigger 1 */ /*@{*/ #define BP_SIM_SOPT4_FTM3TRG1SRC (31U) /*!< Bit position for SIM_SOPT4_FTM3TRG1SRC. */ #define BM_SIM_SOPT4_FTM3TRG1SRC (0x80000000U) /*!< Bit mask for SIM_SOPT4_FTM3TRG1SRC. */ #define BS_SIM_SOPT4_FTM3TRG1SRC (1U) /*!< Bit field size in bits for SIM_SOPT4_FTM3TRG1SRC. */ /*! @brief Read current value of the SIM_SOPT4_FTM3TRG1SRC field. */ #define BR_SIM_SOPT4_FTM3TRG1SRC(x) (BITBAND_ACCESS32(HW_SIM_SOPT4_ADDR(x), BP_SIM_SOPT4_FTM3TRG1SRC)) /*! @brief Format value for bitfield SIM_SOPT4_FTM3TRG1SRC. */ #define BF_SIM_SOPT4_FTM3TRG1SRC(v) ((uint32_t)((uint32_t)(v) << BP_SIM_SOPT4_FTM3TRG1SRC) & BM_SIM_SOPT4_FTM3TRG1SRC) /*! @brief Set the FTM3TRG1SRC field to a new value. */ #define BW_SIM_SOPT4_FTM3TRG1SRC(x, v) (BITBAND_ACCESS32(HW_SIM_SOPT4_ADDR(x), BP_SIM_SOPT4_FTM3TRG1SRC) = (v)) /*@}*/ /******************************************************************************* * HW_SIM_SOPT5 - System Options Register 5 ******************************************************************************/ /*! * @brief HW_SIM_SOPT5 - System Options Register 5 (RW) * * Reset value: 0x00000000U */ typedef union _hw_sim_sopt5 { uint32_t U; struct _hw_sim_sopt5_bitfields { uint32_t UART0TXSRC : 2; /*!< [1:0] UART 0 transmit data source * select */ uint32_t UART0RXSRC : 2; /*!< [3:2] UART 0 receive data source select * */ uint32_t UART1TXSRC : 2; /*!< [5:4] UART 1 transmit data source * select */ uint32_t UART1RXSRC : 2; /*!< [7:6] UART 1 receive data source select * */ uint32_t RESERVED0 : 24; /*!< [31:8] */ } B; } hw_sim_sopt5_t; /*! * @name Constants and macros for entire SIM_SOPT5 register */ /*@{*/ #define HW_SIM_SOPT5_ADDR(x) ((x) + 0x1010U) #define HW_SIM_SOPT5(x) (*(__IO hw_sim_sopt5_t *) HW_SIM_SOPT5_ADDR(x)) #define HW_SIM_SOPT5_RD(x) (HW_SIM_SOPT5(x).U) #define HW_SIM_SOPT5_WR(x, v) (HW_SIM_SOPT5(x).U = (v)) #define HW_SIM_SOPT5_SET(x, v) (HW_SIM_SOPT5_WR(x, HW_SIM_SOPT5_RD(x) | (v))) #define HW_SIM_SOPT5_CLR(x, v) (HW_SIM_SOPT5_WR(x, HW_SIM_SOPT5_RD(x) & ~(v))) #define HW_SIM_SOPT5_TOG(x, v) (HW_SIM_SOPT5_WR(x, HW_SIM_SOPT5_RD(x) ^ (v))) /*@}*/ /* * Constants & macros for individual SIM_SOPT5 bitfields */ /*! * @name Register SIM_SOPT5, field UART0TXSRC[1:0] (RW) * * Selects the source for the UART 0 transmit data. * * Values: * - 00 - UART0_TX pin * - 01 - UART0_TX pin modulated with FTM1 channel 0 output * - 10 - UART0_TX pin modulated with FTM2 channel 0 output * - 11 - Reserved */ /*@{*/ #define BP_SIM_SOPT5_UART0TXSRC (0U) /*!< Bit position for SIM_SOPT5_UART0TXSRC. */ #define BM_SIM_SOPT5_UART0TXSRC (0x00000003U) /*!< Bit mask for SIM_SOPT5_UART0TXSRC. */ #define BS_SIM_SOPT5_UART0TXSRC (2U) /*!< Bit field size in bits for SIM_SOPT5_UART0TXSRC. */ /*! @brief Read current value of the SIM_SOPT5_UART0TXSRC field. */ #define BR_SIM_SOPT5_UART0TXSRC(x) (HW_SIM_SOPT5(x).B.UART0TXSRC) /*! @brief Format value for bitfield SIM_SOPT5_UART0TXSRC. */ #define BF_SIM_SOPT5_UART0TXSRC(v) ((uint32_t)((uint32_t)(v) << BP_SIM_SOPT5_UART0TXSRC) & BM_SIM_SOPT5_UART0TXSRC) /*! @brief Set the UART0TXSRC field to a new value. */ #define BW_SIM_SOPT5_UART0TXSRC(x, v) (HW_SIM_SOPT5_WR(x, (HW_SIM_SOPT5_RD(x) & ~BM_SIM_SOPT5_UART0TXSRC) | BF_SIM_SOPT5_UART0TXSRC(v))) /*@}*/ /*! * @name Register SIM_SOPT5, field UART0RXSRC[3:2] (RW) * * Selects the source for the UART 0 receive data. * * Values: * - 00 - UART0_RX pin * - 01 - CMP0 * - 10 - CMP1 * - 11 - Reserved */ /*@{*/ #define BP_SIM_SOPT5_UART0RXSRC (2U) /*!< Bit position for SIM_SOPT5_UART0RXSRC. */ #define BM_SIM_SOPT5_UART0RXSRC (0x0000000CU) /*!< Bit mask for SIM_SOPT5_UART0RXSRC. */ #define BS_SIM_SOPT5_UART0RXSRC (2U) /*!< Bit field size in bits for SIM_SOPT5_UART0RXSRC. */ /*! @brief Read current value of the SIM_SOPT5_UART0RXSRC field. */ #define BR_SIM_SOPT5_UART0RXSRC(x) (HW_SIM_SOPT5(x).B.UART0RXSRC) /*! @brief Format value for bitfield SIM_SOPT5_UART0RXSRC. */ #define BF_SIM_SOPT5_UART0RXSRC(v) ((uint32_t)((uint32_t)(v) << BP_SIM_SOPT5_UART0RXSRC) & BM_SIM_SOPT5_UART0RXSRC) /*! @brief Set the UART0RXSRC field to a new value. */ #define BW_SIM_SOPT5_UART0RXSRC(x, v) (HW_SIM_SOPT5_WR(x, (HW_SIM_SOPT5_RD(x) & ~BM_SIM_SOPT5_UART0RXSRC) | BF_SIM_SOPT5_UART0RXSRC(v))) /*@}*/ /*! * @name Register SIM_SOPT5, field UART1TXSRC[5:4] (RW) * * Selects the source for the UART 1 transmit data. * * Values: * - 00 - UART1_TX pin * - 01 - UART1_TX pin modulated with FTM1 channel 0 output * - 10 - UART1_TX pin modulated with FTM2 channel 0 output * - 11 - Reserved */ /*@{*/ #define BP_SIM_SOPT5_UART1TXSRC (4U) /*!< Bit position for SIM_SOPT5_UART1TXSRC. */ #define BM_SIM_SOPT5_UART1TXSRC (0x00000030U) /*!< Bit mask for SIM_SOPT5_UART1TXSRC. */ #define BS_SIM_SOPT5_UART1TXSRC (2U) /*!< Bit field size in bits for SIM_SOPT5_UART1TXSRC. */ /*! @brief Read current value of the SIM_SOPT5_UART1TXSRC field. */ #define BR_SIM_SOPT5_UART1TXSRC(x) (HW_SIM_SOPT5(x).B.UART1TXSRC) /*! @brief Format value for bitfield SIM_SOPT5_UART1TXSRC. */ #define BF_SIM_SOPT5_UART1TXSRC(v) ((uint32_t)((uint32_t)(v) << BP_SIM_SOPT5_UART1TXSRC) & BM_SIM_SOPT5_UART1TXSRC) /*! @brief Set the UART1TXSRC field to a new value. */ #define BW_SIM_SOPT5_UART1TXSRC(x, v) (HW_SIM_SOPT5_WR(x, (HW_SIM_SOPT5_RD(x) & ~BM_SIM_SOPT5_UART1TXSRC) | BF_SIM_SOPT5_UART1TXSRC(v))) /*@}*/ /*! * @name Register SIM_SOPT5, field UART1RXSRC[7:6] (RW) * * Selects the source for the UART 1 receive data. * * Values: * - 00 - UART1_RX pin * - 01 - CMP0 * - 10 - CMP1 * - 11 - Reserved */ /*@{*/ #define BP_SIM_SOPT5_UART1RXSRC (6U) /*!< Bit position for SIM_SOPT5_UART1RXSRC. */ #define BM_SIM_SOPT5_UART1RXSRC (0x000000C0U) /*!< Bit mask for SIM_SOPT5_UART1RXSRC. */ #define BS_SIM_SOPT5_UART1RXSRC (2U) /*!< Bit field size in bits for SIM_SOPT5_UART1RXSRC. */ /*! @brief Read current value of the SIM_SOPT5_UART1RXSRC field. */ #define BR_SIM_SOPT5_UART1RXSRC(x) (HW_SIM_SOPT5(x).B.UART1RXSRC) /*! @brief Format value for bitfield SIM_SOPT5_UART1RXSRC. */ #define BF_SIM_SOPT5_UART1RXSRC(v) ((uint32_t)((uint32_t)(v) << BP_SIM_SOPT5_UART1RXSRC) & BM_SIM_SOPT5_UART1RXSRC) /*! @brief Set the UART1RXSRC field to a new value. */ #define BW_SIM_SOPT5_UART1RXSRC(x, v) (HW_SIM_SOPT5_WR(x, (HW_SIM_SOPT5_RD(x) & ~BM_SIM_SOPT5_UART1RXSRC) | BF_SIM_SOPT5_UART1RXSRC(v))) /*@}*/ /******************************************************************************* * HW_SIM_SOPT7 - System Options Register 7 ******************************************************************************/ /*! * @brief HW_SIM_SOPT7 - System Options Register 7 (RW) * * Reset value: 0x00000000U */ typedef union _hw_sim_sopt7 { uint32_t U; struct _hw_sim_sopt7_bitfields { uint32_t ADC0TRGSEL : 4; /*!< [3:0] ADC0 trigger select */ uint32_t ADC0PRETRGSEL : 1; /*!< [4] ADC0 pretrigger select */ uint32_t RESERVED0 : 2; /*!< [6:5] */ uint32_t ADC0ALTTRGEN : 1; /*!< [7] ADC0 alternate trigger enable */ uint32_t ADC1TRGSEL : 4; /*!< [11:8] ADC1 trigger select */ uint32_t ADC1PRETRGSEL : 1; /*!< [12] ADC1 pre-trigger select */ uint32_t RESERVED1 : 2; /*!< [14:13] */ uint32_t ADC1ALTTRGEN : 1; /*!< [15] ADC1 alternate trigger enable */ uint32_t RESERVED2 : 16; /*!< [31:16] */ } B; } hw_sim_sopt7_t; /*! * @name Constants and macros for entire SIM_SOPT7 register */ /*@{*/ #define HW_SIM_SOPT7_ADDR(x) ((x) + 0x1018U) #define HW_SIM_SOPT7(x) (*(__IO hw_sim_sopt7_t *) HW_SIM_SOPT7_ADDR(x)) #define HW_SIM_SOPT7_RD(x) (HW_SIM_SOPT7(x).U) #define HW_SIM_SOPT7_WR(x, v) (HW_SIM_SOPT7(x).U = (v)) #define HW_SIM_SOPT7_SET(x, v) (HW_SIM_SOPT7_WR(x, HW_SIM_SOPT7_RD(x) | (v))) #define HW_SIM_SOPT7_CLR(x, v) (HW_SIM_SOPT7_WR(x, HW_SIM_SOPT7_RD(x) & ~(v))) #define HW_SIM_SOPT7_TOG(x, v) (HW_SIM_SOPT7_WR(x, HW_SIM_SOPT7_RD(x) ^ (v))) /*@}*/ /* * Constants & macros for individual SIM_SOPT7 bitfields */ /*! * @name Register SIM_SOPT7, field ADC0TRGSEL[3:0] (RW) * * Selects the ADC0 trigger source when alternative triggers are functional in * stop and VLPS modes. . * * Values: * - 0000 - PDB external trigger pin input (PDB0_EXTRG) * - 0001 - High speed comparator 0 output * - 0010 - High speed comparator 1 output * - 0011 - High speed comparator 2 output * - 0100 - PIT trigger 0 * - 0101 - PIT trigger 1 * - 0110 - PIT trigger 2 * - 0111 - PIT trigger 3 * - 1000 - FTM0 trigger * - 1001 - FTM1 trigger * - 1010 - FTM2 trigger * - 1011 - FTM3 trigger * - 1100 - RTC alarm * - 1101 - RTC seconds * - 1110 - Low-power timer (LPTMR) trigger * - 1111 - Reserved */ /*@{*/ #define BP_SIM_SOPT7_ADC0TRGSEL (0U) /*!< Bit position for SIM_SOPT7_ADC0TRGSEL. */ #define BM_SIM_SOPT7_ADC0TRGSEL (0x0000000FU) /*!< Bit mask for SIM_SOPT7_ADC0TRGSEL. */ #define BS_SIM_SOPT7_ADC0TRGSEL (4U) /*!< Bit field size in bits for SIM_SOPT7_ADC0TRGSEL. */ /*! @brief Read current value of the SIM_SOPT7_ADC0TRGSEL field. */ #define BR_SIM_SOPT7_ADC0TRGSEL(x) (HW_SIM_SOPT7(x).B.ADC0TRGSEL) /*! @brief Format value for bitfield SIM_SOPT7_ADC0TRGSEL. */ #define BF_SIM_SOPT7_ADC0TRGSEL(v) ((uint32_t)((uint32_t)(v) << BP_SIM_SOPT7_ADC0TRGSEL) & BM_SIM_SOPT7_ADC0TRGSEL) /*! @brief Set the ADC0TRGSEL field to a new value. */ #define BW_SIM_SOPT7_ADC0TRGSEL(x, v) (HW_SIM_SOPT7_WR(x, (HW_SIM_SOPT7_RD(x) & ~BM_SIM_SOPT7_ADC0TRGSEL) | BF_SIM_SOPT7_ADC0TRGSEL(v))) /*@}*/ /*! * @name Register SIM_SOPT7, field ADC0PRETRGSEL[4] (RW) * * Selects the ADC0 pre-trigger source when alternative triggers are enabled * through ADC0ALTTRGEN. * * Values: * - 0 - Pre-trigger A * - 1 - Pre-trigger B */ /*@{*/ #define BP_SIM_SOPT7_ADC0PRETRGSEL (4U) /*!< Bit position for SIM_SOPT7_ADC0PRETRGSEL. */ #define BM_SIM_SOPT7_ADC0PRETRGSEL (0x00000010U) /*!< Bit mask for SIM_SOPT7_ADC0PRETRGSEL. */ #define BS_SIM_SOPT7_ADC0PRETRGSEL (1U) /*!< Bit field size in bits for SIM_SOPT7_ADC0PRETRGSEL. */ /*! @brief Read current value of the SIM_SOPT7_ADC0PRETRGSEL field. */ #define BR_SIM_SOPT7_ADC0PRETRGSEL(x) (BITBAND_ACCESS32(HW_SIM_SOPT7_ADDR(x), BP_SIM_SOPT7_ADC0PRETRGSEL)) /*! @brief Format value for bitfield SIM_SOPT7_ADC0PRETRGSEL. */ #define BF_SIM_SOPT7_ADC0PRETRGSEL(v) ((uint32_t)((uint32_t)(v) << BP_SIM_SOPT7_ADC0PRETRGSEL) & BM_SIM_SOPT7_ADC0PRETRGSEL) /*! @brief Set the ADC0PRETRGSEL field to a new value. */ #define BW_SIM_SOPT7_ADC0PRETRGSEL(x, v) (BITBAND_ACCESS32(HW_SIM_SOPT7_ADDR(x), BP_SIM_SOPT7_ADC0PRETRGSEL) = (v)) /*@}*/ /*! * @name Register SIM_SOPT7, field ADC0ALTTRGEN[7] (RW) * * Enable alternative conversion triggers for ADC0. * * Values: * - 0 - PDB trigger selected for ADC0. * - 1 - Alternate trigger selected for ADC0. */ /*@{*/ #define BP_SIM_SOPT7_ADC0ALTTRGEN (7U) /*!< Bit position for SIM_SOPT7_ADC0ALTTRGEN. */ #define BM_SIM_SOPT7_ADC0ALTTRGEN (0x00000080U) /*!< Bit mask for SIM_SOPT7_ADC0ALTTRGEN. */ #define BS_SIM_SOPT7_ADC0ALTTRGEN (1U) /*!< Bit field size in bits for SIM_SOPT7_ADC0ALTTRGEN. */ /*! @brief Read current value of the SIM_SOPT7_ADC0ALTTRGEN field. */ #define BR_SIM_SOPT7_ADC0ALTTRGEN(x) (BITBAND_ACCESS32(HW_SIM_SOPT7_ADDR(x), BP_SIM_SOPT7_ADC0ALTTRGEN)) /*! @brief Format value for bitfield SIM_SOPT7_ADC0ALTTRGEN. */ #define BF_SIM_SOPT7_ADC0ALTTRGEN(v) ((uint32_t)((uint32_t)(v) << BP_SIM_SOPT7_ADC0ALTTRGEN) & BM_SIM_SOPT7_ADC0ALTTRGEN) /*! @brief Set the ADC0ALTTRGEN field to a new value. */ #define BW_SIM_SOPT7_ADC0ALTTRGEN(x, v) (BITBAND_ACCESS32(HW_SIM_SOPT7_ADDR(x), BP_SIM_SOPT7_ADC0ALTTRGEN) = (v)) /*@}*/ /*! * @name Register SIM_SOPT7, field ADC1TRGSEL[11:8] (RW) * * Selects the ADC1 trigger source when alternative triggers are functional in * stop and VLPS modes. * * Values: * - 0000 - PDB external trigger pin input (PDB0_EXTRG) * - 0001 - High speed comparator 0 output * - 0010 - High speed comparator 1 output * - 0011 - High speed comparator 2 output * - 0100 - PIT trigger 0 * - 0101 - PIT trigger 1 * - 0110 - PIT trigger 2 * - 0111 - PIT trigger 3 * - 1000 - FTM0 trigger * - 1001 - FTM1 trigger * - 1010 - FTM2 trigger * - 1011 - FTM3 trigger * - 1100 - RTC alarm * - 1101 - RTC seconds * - 1110 - Low-power timer (LPTMR) trigger * - 1111 - Reserved */ /*@{*/ #define BP_SIM_SOPT7_ADC1TRGSEL (8U) /*!< Bit position for SIM_SOPT7_ADC1TRGSEL. */ #define BM_SIM_SOPT7_ADC1TRGSEL (0x00000F00U) /*!< Bit mask for SIM_SOPT7_ADC1TRGSEL. */ #define BS_SIM_SOPT7_ADC1TRGSEL (4U) /*!< Bit field size in bits for SIM_SOPT7_ADC1TRGSEL. */ /*! @brief Read current value of the SIM_SOPT7_ADC1TRGSEL field. */ #define BR_SIM_SOPT7_ADC1TRGSEL(x) (HW_SIM_SOPT7(x).B.ADC1TRGSEL) /*! @brief Format value for bitfield SIM_SOPT7_ADC1TRGSEL. */ #define BF_SIM_SOPT7_ADC1TRGSEL(v) ((uint32_t)((uint32_t)(v) << BP_SIM_SOPT7_ADC1TRGSEL) & BM_SIM_SOPT7_ADC1TRGSEL) /*! @brief Set the ADC1TRGSEL field to a new value. */ #define BW_SIM_SOPT7_ADC1TRGSEL(x, v) (HW_SIM_SOPT7_WR(x, (HW_SIM_SOPT7_RD(x) & ~BM_SIM_SOPT7_ADC1TRGSEL) | BF_SIM_SOPT7_ADC1TRGSEL(v))) /*@}*/ /*! * @name Register SIM_SOPT7, field ADC1PRETRGSEL[12] (RW) * * Selects the ADC1 pre-trigger source when alternative triggers are enabled * through ADC1ALTTRGEN. * * Values: * - 0 - Pre-trigger A selected for ADC1. * - 1 - Pre-trigger B selected for ADC1. */ /*@{*/ #define BP_SIM_SOPT7_ADC1PRETRGSEL (12U) /*!< Bit position for SIM_SOPT7_ADC1PRETRGSEL. */ #define BM_SIM_SOPT7_ADC1PRETRGSEL (0x00001000U) /*!< Bit mask for SIM_SOPT7_ADC1PRETRGSEL. */ #define BS_SIM_SOPT7_ADC1PRETRGSEL (1U) /*!< Bit field size in bits for SIM_SOPT7_ADC1PRETRGSEL. */ /*! @brief Read current value of the SIM_SOPT7_ADC1PRETRGSEL field. */ #define BR_SIM_SOPT7_ADC1PRETRGSEL(x) (BITBAND_ACCESS32(HW_SIM_SOPT7_ADDR(x), BP_SIM_SOPT7_ADC1PRETRGSEL)) /*! @brief Format value for bitfield SIM_SOPT7_ADC1PRETRGSEL. */ #define BF_SIM_SOPT7_ADC1PRETRGSEL(v) ((uint32_t)((uint32_t)(v) << BP_SIM_SOPT7_ADC1PRETRGSEL) & BM_SIM_SOPT7_ADC1PRETRGSEL) /*! @brief Set the ADC1PRETRGSEL field to a new value. */ #define BW_SIM_SOPT7_ADC1PRETRGSEL(x, v) (BITBAND_ACCESS32(HW_SIM_SOPT7_ADDR(x), BP_SIM_SOPT7_ADC1PRETRGSEL) = (v)) /*@}*/ /*! * @name Register SIM_SOPT7, field ADC1ALTTRGEN[15] (RW) * * Enable alternative conversion triggers for ADC1. * * Values: * - 0 - PDB trigger selected for ADC1 * - 1 - Alternate trigger selected for ADC1 as defined by ADC1TRGSEL. */ /*@{*/ #define BP_SIM_SOPT7_ADC1ALTTRGEN (15U) /*!< Bit position for SIM_SOPT7_ADC1ALTTRGEN. */ #define BM_SIM_SOPT7_ADC1ALTTRGEN (0x00008000U) /*!< Bit mask for SIM_SOPT7_ADC1ALTTRGEN. */ #define BS_SIM_SOPT7_ADC1ALTTRGEN (1U) /*!< Bit field size in bits for SIM_SOPT7_ADC1ALTTRGEN. */ /*! @brief Read current value of the SIM_SOPT7_ADC1ALTTRGEN field. */ #define BR_SIM_SOPT7_ADC1ALTTRGEN(x) (BITBAND_ACCESS32(HW_SIM_SOPT7_ADDR(x), BP_SIM_SOPT7_ADC1ALTTRGEN)) /*! @brief Format value for bitfield SIM_SOPT7_ADC1ALTTRGEN. */ #define BF_SIM_SOPT7_ADC1ALTTRGEN(v) ((uint32_t)((uint32_t)(v) << BP_SIM_SOPT7_ADC1ALTTRGEN) & BM_SIM_SOPT7_ADC1ALTTRGEN) /*! @brief Set the ADC1ALTTRGEN field to a new value. */ #define BW_SIM_SOPT7_ADC1ALTTRGEN(x, v) (BITBAND_ACCESS32(HW_SIM_SOPT7_ADDR(x), BP_SIM_SOPT7_ADC1ALTTRGEN) = (v)) /*@}*/ /******************************************************************************* * HW_SIM_SDID - System Device Identification Register ******************************************************************************/ /*! * @brief HW_SIM_SDID - System Device Identification Register (RO) * * Reset value: 0x00000380U */ typedef union _hw_sim_sdid { uint32_t U; struct _hw_sim_sdid_bitfields { uint32_t PINID : 4; /*!< [3:0] Pincount identification */ uint32_t FAMID : 3; /*!< [6:4] Kinetis family identification */ uint32_t DIEID : 5; /*!< [11:7] Device Die ID */ uint32_t REVID : 4; /*!< [15:12] Device revision number */ uint32_t RESERVED0 : 4; /*!< [19:16] */ uint32_t SERIESID : 4; /*!< [23:20] Kinetis Series ID */ uint32_t SUBFAMID : 4; /*!< [27:24] Kinetis Sub-Family ID */ uint32_t FAMILYID : 4; /*!< [31:28] Kinetis Family ID */ } B; } hw_sim_sdid_t; /*! * @name Constants and macros for entire SIM_SDID register */ /*@{*/ #define HW_SIM_SDID_ADDR(x) ((x) + 0x1024U) #define HW_SIM_SDID(x) (*(__I hw_sim_sdid_t *) HW_SIM_SDID_ADDR(x)) #define HW_SIM_SDID_RD(x) (HW_SIM_SDID(x).U) /*@}*/ /* * Constants & macros for individual SIM_SDID bitfields */ /*! * @name Register SIM_SDID, field PINID[3:0] (RO) * * Specifies the pincount of the device. * * Values: * - 0000 - Reserved * - 0001 - Reserved * - 0010 - 32-pin * - 0011 - Reserved * - 0100 - 48-pin * - 0101 - 64-pin * - 0110 - 80-pin * - 0111 - 81-pin or 121-pin * - 1000 - 100-pin * - 1001 - 121-pin * - 1010 - 144-pin * - 1011 - Custom pinout (WLCSP) * - 1100 - 169-pin * - 1101 - Reserved * - 1110 - 256-pin * - 1111 - Reserved */ /*@{*/ #define BP_SIM_SDID_PINID (0U) /*!< Bit position for SIM_SDID_PINID. */ #define BM_SIM_SDID_PINID (0x0000000FU) /*!< Bit mask for SIM_SDID_PINID. */ #define BS_SIM_SDID_PINID (4U) /*!< Bit field size in bits for SIM_SDID_PINID. */ /*! @brief Read current value of the SIM_SDID_PINID field. */ #define BR_SIM_SDID_PINID(x) (HW_SIM_SDID(x).B.PINID) /*@}*/ /*! * @name Register SIM_SDID, field FAMID[6:4] (RO) * * This field is maintained for compatibility only, but has been superceded by * the SERIESID, FAMILYID and SUBFAMID fields in this register. * * Values: * - 000 - K1x Family (without tamper) * - 001 - K2x Family (without tamper) * - 010 - K3x Family or K1x/K6x Family (with tamper) * - 011 - K4x Family or K2x Family (with tamper) * - 100 - K6x Family (without tamper) * - 101 - K7x Family * - 110 - Reserved * - 111 - Reserved */ /*@{*/ #define BP_SIM_SDID_FAMID (4U) /*!< Bit position for SIM_SDID_FAMID. */ #define BM_SIM_SDID_FAMID (0x00000070U) /*!< Bit mask for SIM_SDID_FAMID. */ #define BS_SIM_SDID_FAMID (3U) /*!< Bit field size in bits for SIM_SDID_FAMID. */ /*! @brief Read current value of the SIM_SDID_FAMID field. */ #define BR_SIM_SDID_FAMID(x) (HW_SIM_SDID(x).B.FAMID) /*@}*/ /*! * @name Register SIM_SDID, field DIEID[11:7] (RO) * * Specifies the silicon feature set identication number for the device. */ /*@{*/ #define BP_SIM_SDID_DIEID (7U) /*!< Bit position for SIM_SDID_DIEID. */ #define BM_SIM_SDID_DIEID (0x00000F80U) /*!< Bit mask for SIM_SDID_DIEID. */ #define BS_SIM_SDID_DIEID (5U) /*!< Bit field size in bits for SIM_SDID_DIEID. */ /*! @brief Read current value of the SIM_SDID_DIEID field. */ #define BR_SIM_SDID_DIEID(x) (HW_SIM_SDID(x).B.DIEID) /*@}*/ /*! * @name Register SIM_SDID, field REVID[15:12] (RO) * * Specifies the silicon implementation number for the device. */ /*@{*/ #define BP_SIM_SDID_REVID (12U) /*!< Bit position for SIM_SDID_REVID. */ #define BM_SIM_SDID_REVID (0x0000F000U) /*!< Bit mask for SIM_SDID_REVID. */ #define BS_SIM_SDID_REVID (4U) /*!< Bit field size in bits for SIM_SDID_REVID. */ /*! @brief Read current value of the SIM_SDID_REVID field. */ #define BR_SIM_SDID_REVID(x) (HW_SIM_SDID(x).B.REVID) /*@}*/ /*! * @name Register SIM_SDID, field SERIESID[23:20] (RO) * * Specifies the Kinetis series of the device. * * Values: * - 0000 - Kinetis K series * - 0001 - Kinetis L series * - 0101 - Kinetis W series * - 0110 - Kinetis V series */ /*@{*/ #define BP_SIM_SDID_SERIESID (20U) /*!< Bit position for SIM_SDID_SERIESID. */ #define BM_SIM_SDID_SERIESID (0x00F00000U) /*!< Bit mask for SIM_SDID_SERIESID. */ #define BS_SIM_SDID_SERIESID (4U) /*!< Bit field size in bits for SIM_SDID_SERIESID. */ /*! @brief Read current value of the SIM_SDID_SERIESID field. */ #define BR_SIM_SDID_SERIESID(x) (HW_SIM_SDID(x).B.SERIESID) /*@}*/ /*! * @name Register SIM_SDID, field SUBFAMID[27:24] (RO) * * Specifies the Kinetis sub-family of the device. * * Values: * - 0000 - Kx0 Subfamily * - 0001 - Kx1 Subfamily (tamper detect) * - 0010 - Kx2 Subfamily * - 0011 - Kx3 Subfamily (tamper detect) * - 0100 - Kx4 Subfamily * - 0101 - Kx5 Subfamily (tamper detect) * - 0110 - Kx6 Subfamily */ /*@{*/ #define BP_SIM_SDID_SUBFAMID (24U) /*!< Bit position for SIM_SDID_SUBFAMID. */ #define BM_SIM_SDID_SUBFAMID (0x0F000000U) /*!< Bit mask for SIM_SDID_SUBFAMID. */ #define BS_SIM_SDID_SUBFAMID (4U) /*!< Bit field size in bits for SIM_SDID_SUBFAMID. */ /*! @brief Read current value of the SIM_SDID_SUBFAMID field. */ #define BR_SIM_SDID_SUBFAMID(x) (HW_SIM_SDID(x).B.SUBFAMID) /*@}*/ /*! * @name Register SIM_SDID, field FAMILYID[31:28] (RO) * * Specifies the Kinetis family of the device. * * Values: * - 0001 - K1x Family * - 0010 - K2x Family * - 0011 - K3x Family * - 0100 - K4x Family * - 0110 - K6x Family * - 0111 - K7x Family */ /*@{*/ #define BP_SIM_SDID_FAMILYID (28U) /*!< Bit position for SIM_SDID_FAMILYID. */ #define BM_SIM_SDID_FAMILYID (0xF0000000U) /*!< Bit mask for SIM_SDID_FAMILYID. */ #define BS_SIM_SDID_FAMILYID (4U) /*!< Bit field size in bits for SIM_SDID_FAMILYID. */ /*! @brief Read current value of the SIM_SDID_FAMILYID field. */ #define BR_SIM_SDID_FAMILYID(x) (HW_SIM_SDID(x).B.FAMILYID) /*@}*/ /******************************************************************************* * HW_SIM_SCGC1 - System Clock Gating Control Register 1 ******************************************************************************/ /*! * @brief HW_SIM_SCGC1 - System Clock Gating Control Register 1 (RW) * * Reset value: 0x00000000U */ typedef union _hw_sim_scgc1 { uint32_t U; struct _hw_sim_scgc1_bitfields { uint32_t RESERVED0 : 6; /*!< [5:0] */ uint32_t I2C2b : 1; /*!< [6] I2C2 Clock Gate Control */ uint32_t RESERVED1 : 3; /*!< [9:7] */ uint32_t UART4b : 1; /*!< [10] UART4 Clock Gate Control */ uint32_t UART5b : 1; /*!< [11] UART5 Clock Gate Control */ uint32_t RESERVED2 : 20; /*!< [31:12] */ } B; } hw_sim_scgc1_t; /*! * @name Constants and macros for entire SIM_SCGC1 register */ /*@{*/ #define HW_SIM_SCGC1_ADDR(x) ((x) + 0x1028U) #define HW_SIM_SCGC1(x) (*(__IO hw_sim_scgc1_t *) HW_SIM_SCGC1_ADDR(x)) #define HW_SIM_SCGC1_RD(x) (HW_SIM_SCGC1(x).U) #define HW_SIM_SCGC1_WR(x, v) (HW_SIM_SCGC1(x).U = (v)) #define HW_SIM_SCGC1_SET(x, v) (HW_SIM_SCGC1_WR(x, HW_SIM_SCGC1_RD(x) | (v))) #define HW_SIM_SCGC1_CLR(x, v) (HW_SIM_SCGC1_WR(x, HW_SIM_SCGC1_RD(x) & ~(v))) #define HW_SIM_SCGC1_TOG(x, v) (HW_SIM_SCGC1_WR(x, HW_SIM_SCGC1_RD(x) ^ (v))) /*@}*/ /* * Constants & macros for individual SIM_SCGC1 bitfields */ /*! * @name Register SIM_SCGC1, field I2C2[6] (RW) * * This bit controls the clock gate to the I2C2 module. * * Values: * - 0 - Clock disabled * - 1 - Clock enabled */ /*@{*/ #define BP_SIM_SCGC1_I2C2 (6U) /*!< Bit position for SIM_SCGC1_I2C2. */ #define BM_SIM_SCGC1_I2C2 (0x00000040U) /*!< Bit mask for SIM_SCGC1_I2C2. */ #define BS_SIM_SCGC1_I2C2 (1U) /*!< Bit field size in bits for SIM_SCGC1_I2C2. */ /*! @brief Read current value of the SIM_SCGC1_I2C2 field. */ #define BR_SIM_SCGC1_I2C2(x) (BITBAND_ACCESS32(HW_SIM_SCGC1_ADDR(x), BP_SIM_SCGC1_I2C2)) /*! @brief Format value for bitfield SIM_SCGC1_I2C2. */ #define BF_SIM_SCGC1_I2C2(v) ((uint32_t)((uint32_t)(v) << BP_SIM_SCGC1_I2C2) & BM_SIM_SCGC1_I2C2) /*! @brief Set the I2C2 field to a new value. */ #define BW_SIM_SCGC1_I2C2(x, v) (BITBAND_ACCESS32(HW_SIM_SCGC1_ADDR(x), BP_SIM_SCGC1_I2C2) = (v)) /*@}*/ /*! * @name Register SIM_SCGC1, field UART4[10] (RW) * * This bit controls the clock gate to the UART4 module. * * Values: * - 0 - Clock disabled * - 1 - Clock enabled */ /*@{*/ #define BP_SIM_SCGC1_UART4 (10U) /*!< Bit position for SIM_SCGC1_UART4. */ #define BM_SIM_SCGC1_UART4 (0x00000400U) /*!< Bit mask for SIM_SCGC1_UART4. */ #define BS_SIM_SCGC1_UART4 (1U) /*!< Bit field size in bits for SIM_SCGC1_UART4. */ /*! @brief Read current value of the SIM_SCGC1_UART4 field. */ #define BR_SIM_SCGC1_UART4(x) (BITBAND_ACCESS32(HW_SIM_SCGC1_ADDR(x), BP_SIM_SCGC1_UART4)) /*! @brief Format value for bitfield SIM_SCGC1_UART4. */ #define BF_SIM_SCGC1_UART4(v) ((uint32_t)((uint32_t)(v) << BP_SIM_SCGC1_UART4) & BM_SIM_SCGC1_UART4) /*! @brief Set the UART4 field to a new value. */ #define BW_SIM_SCGC1_UART4(x, v) (BITBAND_ACCESS32(HW_SIM_SCGC1_ADDR(x), BP_SIM_SCGC1_UART4) = (v)) /*@}*/ /*! * @name Register SIM_SCGC1, field UART5[11] (RW) * * This bit controls the clock gate to the UART5 module. * * Values: * - 0 - Clock disabled * - 1 - Clock enabled */ /*@{*/ #define BP_SIM_SCGC1_UART5 (11U) /*!< Bit position for SIM_SCGC1_UART5. */ #define BM_SIM_SCGC1_UART5 (0x00000800U) /*!< Bit mask for SIM_SCGC1_UART5. */ #define BS_SIM_SCGC1_UART5 (1U) /*!< Bit field size in bits for SIM_SCGC1_UART5. */ /*! @brief Read current value of the SIM_SCGC1_UART5 field. */ #define BR_SIM_SCGC1_UART5(x) (BITBAND_ACCESS32(HW_SIM_SCGC1_ADDR(x), BP_SIM_SCGC1_UART5)) /*! @brief Format value for bitfield SIM_SCGC1_UART5. */ #define BF_SIM_SCGC1_UART5(v) ((uint32_t)((uint32_t)(v) << BP_SIM_SCGC1_UART5) & BM_SIM_SCGC1_UART5) /*! @brief Set the UART5 field to a new value. */ #define BW_SIM_SCGC1_UART5(x, v) (BITBAND_ACCESS32(HW_SIM_SCGC1_ADDR(x), BP_SIM_SCGC1_UART5) = (v)) /*@}*/ /******************************************************************************* * HW_SIM_SCGC2 - System Clock Gating Control Register 2 ******************************************************************************/ /*! * @brief HW_SIM_SCGC2 - System Clock Gating Control Register 2 (RW) * * Reset value: 0x00000000U * * DAC0 can be accessed through both AIPS0 and AIPS1. When accessing through * AIPS1, define the clock gate control bits in the SCGC2. When accessing through * AIPS0, define the clock gate control bits in SCGC6. */ typedef union _hw_sim_scgc2 { uint32_t U; struct _hw_sim_scgc2_bitfields { uint32_t ENETb : 1; /*!< [0] ENET Clock Gate Control */ uint32_t RESERVED0 : 11; /*!< [11:1] */ uint32_t DAC0b : 1; /*!< [12] DAC0 Clock Gate Control */ uint32_t DAC1b : 1; /*!< [13] DAC1 Clock Gate Control */ uint32_t RESERVED1 : 18; /*!< [31:14] */ } B; } hw_sim_scgc2_t; /*! * @name Constants and macros for entire SIM_SCGC2 register */ /*@{*/ #define HW_SIM_SCGC2_ADDR(x) ((x) + 0x102CU) #define HW_SIM_SCGC2(x) (*(__IO hw_sim_scgc2_t *) HW_SIM_SCGC2_ADDR(x)) #define HW_SIM_SCGC2_RD(x) (HW_SIM_SCGC2(x).U) #define HW_SIM_SCGC2_WR(x, v) (HW_SIM_SCGC2(x).U = (v)) #define HW_SIM_SCGC2_SET(x, v) (HW_SIM_SCGC2_WR(x, HW_SIM_SCGC2_RD(x) | (v))) #define HW_SIM_SCGC2_CLR(x, v) (HW_SIM_SCGC2_WR(x, HW_SIM_SCGC2_RD(x) & ~(v))) #define HW_SIM_SCGC2_TOG(x, v) (HW_SIM_SCGC2_WR(x, HW_SIM_SCGC2_RD(x) ^ (v))) /*@}*/ /* * Constants & macros for individual SIM_SCGC2 bitfields */ /*! * @name Register SIM_SCGC2, field ENET[0] (RW) * * This bit controls the clock gate to the ENET module. * * Values: * - 0 - Clock disabled * - 1 - Clock enabled */ /*@{*/ #define BP_SIM_SCGC2_ENET (0U) /*!< Bit position for SIM_SCGC2_ENET. */ #define BM_SIM_SCGC2_ENET (0x00000001U) /*!< Bit mask for SIM_SCGC2_ENET. */ #define BS_SIM_SCGC2_ENET (1U) /*!< Bit field size in bits for SIM_SCGC2_ENET. */ /*! @brief Read current value of the SIM_SCGC2_ENET field. */ #define BR_SIM_SCGC2_ENET(x) (BITBAND_ACCESS32(HW_SIM_SCGC2_ADDR(x), BP_SIM_SCGC2_ENET)) /*! @brief Format value for bitfield SIM_SCGC2_ENET. */ #define BF_SIM_SCGC2_ENET(v) ((uint32_t)((uint32_t)(v) << BP_SIM_SCGC2_ENET) & BM_SIM_SCGC2_ENET) /*! @brief Set the ENET field to a new value. */ #define BW_SIM_SCGC2_ENET(x, v) (BITBAND_ACCESS32(HW_SIM_SCGC2_ADDR(x), BP_SIM_SCGC2_ENET) = (v)) /*@}*/ /*! * @name Register SIM_SCGC2, field DAC0[12] (RW) * * This bit controls the clock gate to the DAC0 module. * * Values: * - 0 - Clock disabled * - 1 - Clock enabled */ /*@{*/ #define BP_SIM_SCGC2_DAC0 (12U) /*!< Bit position for SIM_SCGC2_DAC0. */ #define BM_SIM_SCGC2_DAC0 (0x00001000U) /*!< Bit mask for SIM_SCGC2_DAC0. */ #define BS_SIM_SCGC2_DAC0 (1U) /*!< Bit field size in bits for SIM_SCGC2_DAC0. */ /*! @brief Read current value of the SIM_SCGC2_DAC0 field. */ #define BR_SIM_SCGC2_DAC0(x) (BITBAND_ACCESS32(HW_SIM_SCGC2_ADDR(x), BP_SIM_SCGC2_DAC0)) /*! @brief Format value for bitfield SIM_SCGC2_DAC0. */ #define BF_SIM_SCGC2_DAC0(v) ((uint32_t)((uint32_t)(v) << BP_SIM_SCGC2_DAC0) & BM_SIM_SCGC2_DAC0) /*! @brief Set the DAC0 field to a new value. */ #define BW_SIM_SCGC2_DAC0(x, v) (BITBAND_ACCESS32(HW_SIM_SCGC2_ADDR(x), BP_SIM_SCGC2_DAC0) = (v)) /*@}*/ /*! * @name Register SIM_SCGC2, field DAC1[13] (RW) * * This bit controls the clock gate to the DAC1 module. * * Values: * - 0 - Clock disabled * - 1 - Clock enabled */ /*@{*/ #define BP_SIM_SCGC2_DAC1 (13U) /*!< Bit position for SIM_SCGC2_DAC1. */ #define BM_SIM_SCGC2_DAC1 (0x00002000U) /*!< Bit mask for SIM_SCGC2_DAC1. */ #define BS_SIM_SCGC2_DAC1 (1U) /*!< Bit field size in bits for SIM_SCGC2_DAC1. */ /*! @brief Read current value of the SIM_SCGC2_DAC1 field. */ #define BR_SIM_SCGC2_DAC1(x) (BITBAND_ACCESS32(HW_SIM_SCGC2_ADDR(x), BP_SIM_SCGC2_DAC1)) /*! @brief Format value for bitfield SIM_SCGC2_DAC1. */ #define BF_SIM_SCGC2_DAC1(v) ((uint32_t)((uint32_t)(v) << BP_SIM_SCGC2_DAC1) & BM_SIM_SCGC2_DAC1) /*! @brief Set the DAC1 field to a new value. */ #define BW_SIM_SCGC2_DAC1(x, v) (BITBAND_ACCESS32(HW_SIM_SCGC2_ADDR(x), BP_SIM_SCGC2_DAC1) = (v)) /*@}*/ /******************************************************************************* * HW_SIM_SCGC3 - System Clock Gating Control Register 3 ******************************************************************************/ /*! * @brief HW_SIM_SCGC3 - System Clock Gating Control Register 3 (RW) * * Reset value: 0x00000000U * * FTM2 and RNGA can be accessed through both AIPS0 and AIPS1. When accessing * through AIPS1, define the clock gate control bits in the SCGC3. When accessing * through AIPS0, define the clock gate control bits in SCGC6. */ typedef union _hw_sim_scgc3 { uint32_t U; struct _hw_sim_scgc3_bitfields { uint32_t RNGA : 1; /*!< [0] RNGA Clock Gate Control */ uint32_t RESERVED0 : 11; /*!< [11:1] */ uint32_t SPI2b : 1; /*!< [12] SPI2 Clock Gate Control */ uint32_t RESERVED1 : 4; /*!< [16:13] */ uint32_t SDHCb : 1; /*!< [17] SDHC Clock Gate Control */ uint32_t RESERVED2 : 6; /*!< [23:18] */ uint32_t FTM2b : 1; /*!< [24] FTM2 Clock Gate Control */ uint32_t FTM3b : 1; /*!< [25] FTM3 Clock Gate Control */ uint32_t RESERVED3 : 1; /*!< [26] */ uint32_t ADC1b : 1; /*!< [27] ADC1 Clock Gate Control */ uint32_t RESERVED4 : 4; /*!< [31:28] */ } B; } hw_sim_scgc3_t; /*! * @name Constants and macros for entire SIM_SCGC3 register */ /*@{*/ #define HW_SIM_SCGC3_ADDR(x) ((x) + 0x1030U) #define HW_SIM_SCGC3(x) (*(__IO hw_sim_scgc3_t *) HW_SIM_SCGC3_ADDR(x)) #define HW_SIM_SCGC3_RD(x) (HW_SIM_SCGC3(x).U) #define HW_SIM_SCGC3_WR(x, v) (HW_SIM_SCGC3(x).U = (v)) #define HW_SIM_SCGC3_SET(x, v) (HW_SIM_SCGC3_WR(x, HW_SIM_SCGC3_RD(x) | (v))) #define HW_SIM_SCGC3_CLR(x, v) (HW_SIM_SCGC3_WR(x, HW_SIM_SCGC3_RD(x) & ~(v))) #define HW_SIM_SCGC3_TOG(x, v) (HW_SIM_SCGC3_WR(x, HW_SIM_SCGC3_RD(x) ^ (v))) /*@}*/ /* * Constants & macros for individual SIM_SCGC3 bitfields */ /*! * @name Register SIM_SCGC3, field RNGA[0] (RW) * * This bit controls the clock gate to the RNGA module. * * Values: * - 0 - Clock disabled * - 1 - Clock enabled */ /*@{*/ #define BP_SIM_SCGC3_RNGA (0U) /*!< Bit position for SIM_SCGC3_RNGA. */ #define BM_SIM_SCGC3_RNGA (0x00000001U) /*!< Bit mask for SIM_SCGC3_RNGA. */ #define BS_SIM_SCGC3_RNGA (1U) /*!< Bit field size in bits for SIM_SCGC3_RNGA. */ /*! @brief Read current value of the SIM_SCGC3_RNGA field. */ #define BR_SIM_SCGC3_RNGA(x) (BITBAND_ACCESS32(HW_SIM_SCGC3_ADDR(x), BP_SIM_SCGC3_RNGA)) /*! @brief Format value for bitfield SIM_SCGC3_RNGA. */ #define BF_SIM_SCGC3_RNGA(v) ((uint32_t)((uint32_t)(v) << BP_SIM_SCGC3_RNGA) & BM_SIM_SCGC3_RNGA) /*! @brief Set the RNGA field to a new value. */ #define BW_SIM_SCGC3_RNGA(x, v) (BITBAND_ACCESS32(HW_SIM_SCGC3_ADDR(x), BP_SIM_SCGC3_RNGA) = (v)) /*@}*/ /*! * @name Register SIM_SCGC3, field SPI2[12] (RW) * * This bit controls the clock gate to the SPI2 module. * * Values: * - 0 - Clock disabled * - 1 - Clock enabled */ /*@{*/ #define BP_SIM_SCGC3_SPI2 (12U) /*!< Bit position for SIM_SCGC3_SPI2. */ #define BM_SIM_SCGC3_SPI2 (0x00001000U) /*!< Bit mask for SIM_SCGC3_SPI2. */ #define BS_SIM_SCGC3_SPI2 (1U) /*!< Bit field size in bits for SIM_SCGC3_SPI2. */ /*! @brief Read current value of the SIM_SCGC3_SPI2 field. */ #define BR_SIM_SCGC3_SPI2(x) (BITBAND_ACCESS32(HW_SIM_SCGC3_ADDR(x), BP_SIM_SCGC3_SPI2)) /*! @brief Format value for bitfield SIM_SCGC3_SPI2. */ #define BF_SIM_SCGC3_SPI2(v) ((uint32_t)((uint32_t)(v) << BP_SIM_SCGC3_SPI2) & BM_SIM_SCGC3_SPI2) /*! @brief Set the SPI2 field to a new value. */ #define BW_SIM_SCGC3_SPI2(x, v) (BITBAND_ACCESS32(HW_SIM_SCGC3_ADDR(x), BP_SIM_SCGC3_SPI2) = (v)) /*@}*/ /*! * @name Register SIM_SCGC3, field SDHC[17] (RW) * * This bit controls the clock gate to the SDHC module. * * Values: * - 0 - Clock disabled * - 1 - Clock enabled */ /*@{*/ #define BP_SIM_SCGC3_SDHC (17U) /*!< Bit position for SIM_SCGC3_SDHC. */ #define BM_SIM_SCGC3_SDHC (0x00020000U) /*!< Bit mask for SIM_SCGC3_SDHC. */ #define BS_SIM_SCGC3_SDHC (1U) /*!< Bit field size in bits for SIM_SCGC3_SDHC. */ /*! @brief Read current value of the SIM_SCGC3_SDHC field. */ #define BR_SIM_SCGC3_SDHC(x) (BITBAND_ACCESS32(HW_SIM_SCGC3_ADDR(x), BP_SIM_SCGC3_SDHC)) /*! @brief Format value for bitfield SIM_SCGC3_SDHC. */ #define BF_SIM_SCGC3_SDHC(v) ((uint32_t)((uint32_t)(v) << BP_SIM_SCGC3_SDHC) & BM_SIM_SCGC3_SDHC) /*! @brief Set the SDHC field to a new value. */ #define BW_SIM_SCGC3_SDHC(x, v) (BITBAND_ACCESS32(HW_SIM_SCGC3_ADDR(x), BP_SIM_SCGC3_SDHC) = (v)) /*@}*/ /*! * @name Register SIM_SCGC3, field FTM2[24] (RW) * * This bit controls the clock gate to the FTM2 module. * * Values: * - 0 - Clock disabled * - 1 - Clock enabled */ /*@{*/ #define BP_SIM_SCGC3_FTM2 (24U) /*!< Bit position for SIM_SCGC3_FTM2. */ #define BM_SIM_SCGC3_FTM2 (0x01000000U) /*!< Bit mask for SIM_SCGC3_FTM2. */ #define BS_SIM_SCGC3_FTM2 (1U) /*!< Bit field size in bits for SIM_SCGC3_FTM2. */ /*! @brief Read current value of the SIM_SCGC3_FTM2 field. */ #define BR_SIM_SCGC3_FTM2(x) (BITBAND_ACCESS32(HW_SIM_SCGC3_ADDR(x), BP_SIM_SCGC3_FTM2)) /*! @brief Format value for bitfield SIM_SCGC3_FTM2. */ #define BF_SIM_SCGC3_FTM2(v) ((uint32_t)((uint32_t)(v) << BP_SIM_SCGC3_FTM2) & BM_SIM_SCGC3_FTM2) /*! @brief Set the FTM2 field to a new value. */ #define BW_SIM_SCGC3_FTM2(x, v) (BITBAND_ACCESS32(HW_SIM_SCGC3_ADDR(x), BP_SIM_SCGC3_FTM2) = (v)) /*@}*/ /*! * @name Register SIM_SCGC3, field FTM3[25] (RW) * * This bit controls the clock gate to the FTM3 module. * * Values: * - 0 - Clock disabled * - 1 - Clock enabled */ /*@{*/ #define BP_SIM_SCGC3_FTM3 (25U) /*!< Bit position for SIM_SCGC3_FTM3. */ #define BM_SIM_SCGC3_FTM3 (0x02000000U) /*!< Bit mask for SIM_SCGC3_FTM3. */ #define BS_SIM_SCGC3_FTM3 (1U) /*!< Bit field size in bits for SIM_SCGC3_FTM3. */ /*! @brief Read current value of the SIM_SCGC3_FTM3 field. */ #define BR_SIM_SCGC3_FTM3(x) (BITBAND_ACCESS32(HW_SIM_SCGC3_ADDR(x), BP_SIM_SCGC3_FTM3)) /*! @brief Format value for bitfield SIM_SCGC3_FTM3. */ #define BF_SIM_SCGC3_FTM3(v) ((uint32_t)((uint32_t)(v) << BP_SIM_SCGC3_FTM3) & BM_SIM_SCGC3_FTM3) /*! @brief Set the FTM3 field to a new value. */ #define BW_SIM_SCGC3_FTM3(x, v) (BITBAND_ACCESS32(HW_SIM_SCGC3_ADDR(x), BP_SIM_SCGC3_FTM3) = (v)) /*@}*/ /*! * @name Register SIM_SCGC3, field ADC1[27] (RW) * * This bit controls the clock gate to the ADC1 module. * * Values: * - 0 - Clock disabled * - 1 - Clock enabled */ /*@{*/ #define BP_SIM_SCGC3_ADC1 (27U) /*!< Bit position for SIM_SCGC3_ADC1. */ #define BM_SIM_SCGC3_ADC1 (0x08000000U) /*!< Bit mask for SIM_SCGC3_ADC1. */ #define BS_SIM_SCGC3_ADC1 (1U) /*!< Bit field size in bits for SIM_SCGC3_ADC1. */ /*! @brief Read current value of the SIM_SCGC3_ADC1 field. */ #define BR_SIM_SCGC3_ADC1(x) (BITBAND_ACCESS32(HW_SIM_SCGC3_ADDR(x), BP_SIM_SCGC3_ADC1)) /*! @brief Format value for bitfield SIM_SCGC3_ADC1. */ #define BF_SIM_SCGC3_ADC1(v) ((uint32_t)((uint32_t)(v) << BP_SIM_SCGC3_ADC1) & BM_SIM_SCGC3_ADC1) /*! @brief Set the ADC1 field to a new value. */ #define BW_SIM_SCGC3_ADC1(x, v) (BITBAND_ACCESS32(HW_SIM_SCGC3_ADDR(x), BP_SIM_SCGC3_ADC1) = (v)) /*@}*/ /******************************************************************************* * HW_SIM_SCGC4 - System Clock Gating Control Register 4 ******************************************************************************/ /*! * @brief HW_SIM_SCGC4 - System Clock Gating Control Register 4 (RW) * * Reset value: 0xF0100030U */ typedef union _hw_sim_scgc4 { uint32_t U; struct _hw_sim_scgc4_bitfields { uint32_t RESERVED0 : 1; /*!< [0] */ uint32_t EWMb : 1; /*!< [1] EWM Clock Gate Control */ uint32_t CMTb : 1; /*!< [2] CMT Clock Gate Control */ uint32_t RESERVED1 : 3; /*!< [5:3] */ uint32_t I2C0b : 1; /*!< [6] I2C0 Clock Gate Control */ uint32_t I2C1b : 1; /*!< [7] I2C1 Clock Gate Control */ uint32_t RESERVED2 : 2; /*!< [9:8] */ uint32_t UART0b : 1; /*!< [10] UART0 Clock Gate Control */ uint32_t UART1b : 1; /*!< [11] UART1 Clock Gate Control */ uint32_t UART2b : 1; /*!< [12] UART2 Clock Gate Control */ uint32_t UART3b : 1; /*!< [13] UART3 Clock Gate Control */ uint32_t RESERVED3 : 4; /*!< [17:14] */ uint32_t USBOTG : 1; /*!< [18] USB Clock Gate Control */ uint32_t CMP : 1; /*!< [19] Comparator Clock Gate Control */ uint32_t VREFb : 1; /*!< [20] VREF Clock Gate Control */ uint32_t RESERVED4 : 11; /*!< [31:21] */ } B; } hw_sim_scgc4_t; /*! * @name Constants and macros for entire SIM_SCGC4 register */ /*@{*/ #define HW_SIM_SCGC4_ADDR(x) ((x) + 0x1034U) #define HW_SIM_SCGC4(x) (*(__IO hw_sim_scgc4_t *) HW_SIM_SCGC4_ADDR(x)) #define HW_SIM_SCGC4_RD(x) (HW_SIM_SCGC4(x).U) #define HW_SIM_SCGC4_WR(x, v) (HW_SIM_SCGC4(x).U = (v)) #define HW_SIM_SCGC4_SET(x, v) (HW_SIM_SCGC4_WR(x, HW_SIM_SCGC4_RD(x) | (v))) #define HW_SIM_SCGC4_CLR(x, v) (HW_SIM_SCGC4_WR(x, HW_SIM_SCGC4_RD(x) & ~(v))) #define HW_SIM_SCGC4_TOG(x, v) (HW_SIM_SCGC4_WR(x, HW_SIM_SCGC4_RD(x) ^ (v))) /*@}*/ /* * Constants & macros for individual SIM_SCGC4 bitfields */ /*! * @name Register SIM_SCGC4, field EWM[1] (RW) * * This bit controls the clock gate to the EWM module. * * Values: * - 0 - Clock disabled * - 1 - Clock enabled */ /*@{*/ #define BP_SIM_SCGC4_EWM (1U) /*!< Bit position for SIM_SCGC4_EWM. */ #define BM_SIM_SCGC4_EWM (0x00000002U) /*!< Bit mask for SIM_SCGC4_EWM. */ #define BS_SIM_SCGC4_EWM (1U) /*!< Bit field size in bits for SIM_SCGC4_EWM. */ /*! @brief Read current value of the SIM_SCGC4_EWM field. */ #define BR_SIM_SCGC4_EWM(x) (BITBAND_ACCESS32(HW_SIM_SCGC4_ADDR(x), BP_SIM_SCGC4_EWM)) /*! @brief Format value for bitfield SIM_SCGC4_EWM. */ #define BF_SIM_SCGC4_EWM(v) ((uint32_t)((uint32_t)(v) << BP_SIM_SCGC4_EWM) & BM_SIM_SCGC4_EWM) /*! @brief Set the EWM field to a new value. */ #define BW_SIM_SCGC4_EWM(x, v) (BITBAND_ACCESS32(HW_SIM_SCGC4_ADDR(x), BP_SIM_SCGC4_EWM) = (v)) /*@}*/ /*! * @name Register SIM_SCGC4, field CMT[2] (RW) * * This bit controls the clock gate to the CMT module. * * Values: * - 0 - Clock disabled * - 1 - Clock enabled */ /*@{*/ #define BP_SIM_SCGC4_CMT (2U) /*!< Bit position for SIM_SCGC4_CMT. */ #define BM_SIM_SCGC4_CMT (0x00000004U) /*!< Bit mask for SIM_SCGC4_CMT. */ #define BS_SIM_SCGC4_CMT (1U) /*!< Bit field size in bits for SIM_SCGC4_CMT. */ /*! @brief Read current value of the SIM_SCGC4_CMT field. */ #define BR_SIM_SCGC4_CMT(x) (BITBAND_ACCESS32(HW_SIM_SCGC4_ADDR(x), BP_SIM_SCGC4_CMT)) /*! @brief Format value for bitfield SIM_SCGC4_CMT. */ #define BF_SIM_SCGC4_CMT(v) ((uint32_t)((uint32_t)(v) << BP_SIM_SCGC4_CMT) & BM_SIM_SCGC4_CMT) /*! @brief Set the CMT field to a new value. */ #define BW_SIM_SCGC4_CMT(x, v) (BITBAND_ACCESS32(HW_SIM_SCGC4_ADDR(x), BP_SIM_SCGC4_CMT) = (v)) /*@}*/ /*! * @name Register SIM_SCGC4, field I2C0[6] (RW) * * This bit controls the clock gate to the I 2 C0 module. * * Values: * - 0 - Clock disabled * - 1 - Clock enabled */ /*@{*/ #define BP_SIM_SCGC4_I2C0 (6U) /*!< Bit position for SIM_SCGC4_I2C0. */ #define BM_SIM_SCGC4_I2C0 (0x00000040U) /*!< Bit mask for SIM_SCGC4_I2C0. */ #define BS_SIM_SCGC4_I2C0 (1U) /*!< Bit field size in bits for SIM_SCGC4_I2C0. */ /*! @brief Read current value of the SIM_SCGC4_I2C0 field. */ #define BR_SIM_SCGC4_I2C0(x) (BITBAND_ACCESS32(HW_SIM_SCGC4_ADDR(x), BP_SIM_SCGC4_I2C0)) /*! @brief Format value for bitfield SIM_SCGC4_I2C0. */ #define BF_SIM_SCGC4_I2C0(v) ((uint32_t)((uint32_t)(v) << BP_SIM_SCGC4_I2C0) & BM_SIM_SCGC4_I2C0) /*! @brief Set the I2C0 field to a new value. */ #define BW_SIM_SCGC4_I2C0(x, v) (BITBAND_ACCESS32(HW_SIM_SCGC4_ADDR(x), BP_SIM_SCGC4_I2C0) = (v)) /*@}*/ /*! * @name Register SIM_SCGC4, field I2C1[7] (RW) * * This bit controls the clock gate to the I 2 C1 module. * * Values: * - 0 - Clock disabled * - 1 - Clock enabled */ /*@{*/ #define BP_SIM_SCGC4_I2C1 (7U) /*!< Bit position for SIM_SCGC4_I2C1. */ #define BM_SIM_SCGC4_I2C1 (0x00000080U) /*!< Bit mask for SIM_SCGC4_I2C1. */ #define BS_SIM_SCGC4_I2C1 (1U) /*!< Bit field size in bits for SIM_SCGC4_I2C1. */ /*! @brief Read current value of the SIM_SCGC4_I2C1 field. */ #define BR_SIM_SCGC4_I2C1(x) (BITBAND_ACCESS32(HW_SIM_SCGC4_ADDR(x), BP_SIM_SCGC4_I2C1)) /*! @brief Format value for bitfield SIM_SCGC4_I2C1. */ #define BF_SIM_SCGC4_I2C1(v) ((uint32_t)((uint32_t)(v) << BP_SIM_SCGC4_I2C1) & BM_SIM_SCGC4_I2C1) /*! @brief Set the I2C1 field to a new value. */ #define BW_SIM_SCGC4_I2C1(x, v) (BITBAND_ACCESS32(HW_SIM_SCGC4_ADDR(x), BP_SIM_SCGC4_I2C1) = (v)) /*@}*/ /*! * @name Register SIM_SCGC4, field UART0[10] (RW) * * This bit controls the clock gate to the UART0 module. * * Values: * - 0 - Clock disabled * - 1 - Clock enabled */ /*@{*/ #define BP_SIM_SCGC4_UART0 (10U) /*!< Bit position for SIM_SCGC4_UART0. */ #define BM_SIM_SCGC4_UART0 (0x00000400U) /*!< Bit mask for SIM_SCGC4_UART0. */ #define BS_SIM_SCGC4_UART0 (1U) /*!< Bit field size in bits for SIM_SCGC4_UART0. */ /*! @brief Read current value of the SIM_SCGC4_UART0 field. */ #define BR_SIM_SCGC4_UART0(x) (BITBAND_ACCESS32(HW_SIM_SCGC4_ADDR(x), BP_SIM_SCGC4_UART0)) /*! @brief Format value for bitfield SIM_SCGC4_UART0. */ #define BF_SIM_SCGC4_UART0(v) ((uint32_t)((uint32_t)(v) << BP_SIM_SCGC4_UART0) & BM_SIM_SCGC4_UART0) /*! @brief Set the UART0 field to a new value. */ #define BW_SIM_SCGC4_UART0(x, v) (BITBAND_ACCESS32(HW_SIM_SCGC4_ADDR(x), BP_SIM_SCGC4_UART0) = (v)) /*@}*/ /*! * @name Register SIM_SCGC4, field UART1[11] (RW) * * This bit controls the clock gate to the UART1 module. * * Values: * - 0 - Clock disabled * - 1 - Clock enabled */ /*@{*/ #define BP_SIM_SCGC4_UART1 (11U) /*!< Bit position for SIM_SCGC4_UART1. */ #define BM_SIM_SCGC4_UART1 (0x00000800U) /*!< Bit mask for SIM_SCGC4_UART1. */ #define BS_SIM_SCGC4_UART1 (1U) /*!< Bit field size in bits for SIM_SCGC4_UART1. */ /*! @brief Read current value of the SIM_SCGC4_UART1 field. */ #define BR_SIM_SCGC4_UART1(x) (BITBAND_ACCESS32(HW_SIM_SCGC4_ADDR(x), BP_SIM_SCGC4_UART1)) /*! @brief Format value for bitfield SIM_SCGC4_UART1. */ #define BF_SIM_SCGC4_UART1(v) ((uint32_t)((uint32_t)(v) << BP_SIM_SCGC4_UART1) & BM_SIM_SCGC4_UART1) /*! @brief Set the UART1 field to a new value. */ #define BW_SIM_SCGC4_UART1(x, v) (BITBAND_ACCESS32(HW_SIM_SCGC4_ADDR(x), BP_SIM_SCGC4_UART1) = (v)) /*@}*/ /*! * @name Register SIM_SCGC4, field UART2[12] (RW) * * This bit controls the clock gate to the UART2 module. * * Values: * - 0 - Clock disabled * - 1 - Clock enabled */ /*@{*/ #define BP_SIM_SCGC4_UART2 (12U) /*!< Bit position for SIM_SCGC4_UART2. */ #define BM_SIM_SCGC4_UART2 (0x00001000U) /*!< Bit mask for SIM_SCGC4_UART2. */ #define BS_SIM_SCGC4_UART2 (1U) /*!< Bit field size in bits for SIM_SCGC4_UART2. */ /*! @brief Read current value of the SIM_SCGC4_UART2 field. */ #define BR_SIM_SCGC4_UART2(x) (BITBAND_ACCESS32(HW_SIM_SCGC4_ADDR(x), BP_SIM_SCGC4_UART2)) /*! @brief Format value for bitfield SIM_SCGC4_UART2. */ #define BF_SIM_SCGC4_UART2(v) ((uint32_t)((uint32_t)(v) << BP_SIM_SCGC4_UART2) & BM_SIM_SCGC4_UART2) /*! @brief Set the UART2 field to a new value. */ #define BW_SIM_SCGC4_UART2(x, v) (BITBAND_ACCESS32(HW_SIM_SCGC4_ADDR(x), BP_SIM_SCGC4_UART2) = (v)) /*@}*/ /*! * @name Register SIM_SCGC4, field UART3[13] (RW) * * This bit controls the clock gate to the UART3 module. * * Values: * - 0 - Clock disabled * - 1 - Clock enabled */ /*@{*/ #define BP_SIM_SCGC4_UART3 (13U) /*!< Bit position for SIM_SCGC4_UART3. */ #define BM_SIM_SCGC4_UART3 (0x00002000U) /*!< Bit mask for SIM_SCGC4_UART3. */ #define BS_SIM_SCGC4_UART3 (1U) /*!< Bit field size in bits for SIM_SCGC4_UART3. */ /*! @brief Read current value of the SIM_SCGC4_UART3 field. */ #define BR_SIM_SCGC4_UART3(x) (BITBAND_ACCESS32(HW_SIM_SCGC4_ADDR(x), BP_SIM_SCGC4_UART3)) /*! @brief Format value for bitfield SIM_SCGC4_UART3. */ #define BF_SIM_SCGC4_UART3(v) ((uint32_t)((uint32_t)(v) << BP_SIM_SCGC4_UART3) & BM_SIM_SCGC4_UART3) /*! @brief Set the UART3 field to a new value. */ #define BW_SIM_SCGC4_UART3(x, v) (BITBAND_ACCESS32(HW_SIM_SCGC4_ADDR(x), BP_SIM_SCGC4_UART3) = (v)) /*@}*/ /*! * @name Register SIM_SCGC4, field USBOTG[18] (RW) * * This bit controls the clock gate to the USB module. * * Values: * - 0 - Clock disabled * - 1 - Clock enabled */ /*@{*/ #define BP_SIM_SCGC4_USBOTG (18U) /*!< Bit position for SIM_SCGC4_USBOTG. */ #define BM_SIM_SCGC4_USBOTG (0x00040000U) /*!< Bit mask for SIM_SCGC4_USBOTG. */ #define BS_SIM_SCGC4_USBOTG (1U) /*!< Bit field size in bits for SIM_SCGC4_USBOTG. */ /*! @brief Read current value of the SIM_SCGC4_USBOTG field. */ #define BR_SIM_SCGC4_USBOTG(x) (BITBAND_ACCESS32(HW_SIM_SCGC4_ADDR(x), BP_SIM_SCGC4_USBOTG)) /*! @brief Format value for bitfield SIM_SCGC4_USBOTG. */ #define BF_SIM_SCGC4_USBOTG(v) ((uint32_t)((uint32_t)(v) << BP_SIM_SCGC4_USBOTG) & BM_SIM_SCGC4_USBOTG) /*! @brief Set the USBOTG field to a new value. */ #define BW_SIM_SCGC4_USBOTG(x, v) (BITBAND_ACCESS32(HW_SIM_SCGC4_ADDR(x), BP_SIM_SCGC4_USBOTG) = (v)) /*@}*/ /*! * @name Register SIM_SCGC4, field CMP[19] (RW) * * This bit controls the clock gate to the comparator module. * * Values: * - 0 - Clock disabled * - 1 - Clock enabled */ /*@{*/ #define BP_SIM_SCGC4_CMP (19U) /*!< Bit position for SIM_SCGC4_CMP. */ #define BM_SIM_SCGC4_CMP (0x00080000U) /*!< Bit mask for SIM_SCGC4_CMP. */ #define BS_SIM_SCGC4_CMP (1U) /*!< Bit field size in bits for SIM_SCGC4_CMP. */ /*! @brief Read current value of the SIM_SCGC4_CMP field. */ #define BR_SIM_SCGC4_CMP(x) (BITBAND_ACCESS32(HW_SIM_SCGC4_ADDR(x), BP_SIM_SCGC4_CMP)) /*! @brief Format value for bitfield SIM_SCGC4_CMP. */ #define BF_SIM_SCGC4_CMP(v) ((uint32_t)((uint32_t)(v) << BP_SIM_SCGC4_CMP) & BM_SIM_SCGC4_CMP) /*! @brief Set the CMP field to a new value. */ #define BW_SIM_SCGC4_CMP(x, v) (BITBAND_ACCESS32(HW_SIM_SCGC4_ADDR(x), BP_SIM_SCGC4_CMP) = (v)) /*@}*/ /*! * @name Register SIM_SCGC4, field VREF[20] (RW) * * This bit controls the clock gate to the VREF module. * * Values: * - 0 - Clock disabled * - 1 - Clock enabled */ /*@{*/ #define BP_SIM_SCGC4_VREF (20U) /*!< Bit position for SIM_SCGC4_VREF. */ #define BM_SIM_SCGC4_VREF (0x00100000U) /*!< Bit mask for SIM_SCGC4_VREF. */ #define BS_SIM_SCGC4_VREF (1U) /*!< Bit field size in bits for SIM_SCGC4_VREF. */ /*! @brief Read current value of the SIM_SCGC4_VREF field. */ #define BR_SIM_SCGC4_VREF(x) (BITBAND_ACCESS32(HW_SIM_SCGC4_ADDR(x), BP_SIM_SCGC4_VREF)) /*! @brief Format value for bitfield SIM_SCGC4_VREF. */ #define BF_SIM_SCGC4_VREF(v) ((uint32_t)((uint32_t)(v) << BP_SIM_SCGC4_VREF) & BM_SIM_SCGC4_VREF) /*! @brief Set the VREF field to a new value. */ #define BW_SIM_SCGC4_VREF(x, v) (BITBAND_ACCESS32(HW_SIM_SCGC4_ADDR(x), BP_SIM_SCGC4_VREF) = (v)) /*@}*/ /******************************************************************************* * HW_SIM_SCGC5 - System Clock Gating Control Register 5 ******************************************************************************/ /*! * @brief HW_SIM_SCGC5 - System Clock Gating Control Register 5 (RW) * * Reset value: 0x00040182U */ typedef union _hw_sim_scgc5 { uint32_t U; struct _hw_sim_scgc5_bitfields { uint32_t LPTMR : 1; /*!< [0] Low Power Timer Access Control */ uint32_t RESERVED0 : 8; /*!< [8:1] */ uint32_t PORTAb : 1; /*!< [9] Port A Clock Gate Control */ uint32_t PORTBb : 1; /*!< [10] Port B Clock Gate Control */ uint32_t PORTCb : 1; /*!< [11] Port C Clock Gate Control */ uint32_t PORTDb : 1; /*!< [12] Port D Clock Gate Control */ uint32_t PORTEb : 1; /*!< [13] Port E Clock Gate Control */ uint32_t RESERVED1 : 18; /*!< [31:14] */ } B; } hw_sim_scgc5_t; /*! * @name Constants and macros for entire SIM_SCGC5 register */ /*@{*/ #define HW_SIM_SCGC5_ADDR(x) ((x) + 0x1038U) #define HW_SIM_SCGC5(x) (*(__IO hw_sim_scgc5_t *) HW_SIM_SCGC5_ADDR(x)) #define HW_SIM_SCGC5_RD(x) (HW_SIM_SCGC5(x).U) #define HW_SIM_SCGC5_WR(x, v) (HW_SIM_SCGC5(x).U = (v)) #define HW_SIM_SCGC5_SET(x, v) (HW_SIM_SCGC5_WR(x, HW_SIM_SCGC5_RD(x) | (v))) #define HW_SIM_SCGC5_CLR(x, v) (HW_SIM_SCGC5_WR(x, HW_SIM_SCGC5_RD(x) & ~(v))) #define HW_SIM_SCGC5_TOG(x, v) (HW_SIM_SCGC5_WR(x, HW_SIM_SCGC5_RD(x) ^ (v))) /*@}*/ /* * Constants & macros for individual SIM_SCGC5 bitfields */ /*! * @name Register SIM_SCGC5, field LPTMR[0] (RW) * * This bit controls software access to the Low Power Timer module. * * Values: * - 0 - Access disabled * - 1 - Access enabled */ /*@{*/ #define BP_SIM_SCGC5_LPTMR (0U) /*!< Bit position for SIM_SCGC5_LPTMR. */ #define BM_SIM_SCGC5_LPTMR (0x00000001U) /*!< Bit mask for SIM_SCGC5_LPTMR. */ #define BS_SIM_SCGC5_LPTMR (1U) /*!< Bit field size in bits for SIM_SCGC5_LPTMR. */ /*! @brief Read current value of the SIM_SCGC5_LPTMR field. */ #define BR_SIM_SCGC5_LPTMR(x) (BITBAND_ACCESS32(HW_SIM_SCGC5_ADDR(x), BP_SIM_SCGC5_LPTMR)) /*! @brief Format value for bitfield SIM_SCGC5_LPTMR. */ #define BF_SIM_SCGC5_LPTMR(v) ((uint32_t)((uint32_t)(v) << BP_SIM_SCGC5_LPTMR) & BM_SIM_SCGC5_LPTMR) /*! @brief Set the LPTMR field to a new value. */ #define BW_SIM_SCGC5_LPTMR(x, v) (BITBAND_ACCESS32(HW_SIM_SCGC5_ADDR(x), BP_SIM_SCGC5_LPTMR) = (v)) /*@}*/ /*! * @name Register SIM_SCGC5, field PORTA[9] (RW) * * This bit controls the clock gate to the Port A module. * * Values: * - 0 - Clock disabled * - 1 - Clock enabled */ /*@{*/ #define BP_SIM_SCGC5_PORTA (9U) /*!< Bit position for SIM_SCGC5_PORTA. */ #define BM_SIM_SCGC5_PORTA (0x00000200U) /*!< Bit mask for SIM_SCGC5_PORTA. */ #define BS_SIM_SCGC5_PORTA (1U) /*!< Bit field size in bits for SIM_SCGC5_PORTA. */ /*! @brief Read current value of the SIM_SCGC5_PORTA field. */ #define BR_SIM_SCGC5_PORTA(x) (BITBAND_ACCESS32(HW_SIM_SCGC5_ADDR(x), BP_SIM_SCGC5_PORTA)) /*! @brief Format value for bitfield SIM_SCGC5_PORTA. */ #define BF_SIM_SCGC5_PORTA(v) ((uint32_t)((uint32_t)(v) << BP_SIM_SCGC5_PORTA) & BM_SIM_SCGC5_PORTA) /*! @brief Set the PORTA field to a new value. */ #define BW_SIM_SCGC5_PORTA(x, v) (BITBAND_ACCESS32(HW_SIM_SCGC5_ADDR(x), BP_SIM_SCGC5_PORTA) = (v)) /*@}*/ /*! * @name Register SIM_SCGC5, field PORTB[10] (RW) * * This bit controls the clock gate to the Port B module. * * Values: * - 0 - Clock disabled * - 1 - Clock enabled */ /*@{*/ #define BP_SIM_SCGC5_PORTB (10U) /*!< Bit position for SIM_SCGC5_PORTB. */ #define BM_SIM_SCGC5_PORTB (0x00000400U) /*!< Bit mask for SIM_SCGC5_PORTB. */ #define BS_SIM_SCGC5_PORTB (1U) /*!< Bit field size in bits for SIM_SCGC5_PORTB. */ /*! @brief Read current value of the SIM_SCGC5_PORTB field. */ #define BR_SIM_SCGC5_PORTB(x) (BITBAND_ACCESS32(HW_SIM_SCGC5_ADDR(x), BP_SIM_SCGC5_PORTB)) /*! @brief Format value for bitfield SIM_SCGC5_PORTB. */ #define BF_SIM_SCGC5_PORTB(v) ((uint32_t)((uint32_t)(v) << BP_SIM_SCGC5_PORTB) & BM_SIM_SCGC5_PORTB) /*! @brief Set the PORTB field to a new value. */ #define BW_SIM_SCGC5_PORTB(x, v) (BITBAND_ACCESS32(HW_SIM_SCGC5_ADDR(x), BP_SIM_SCGC5_PORTB) = (v)) /*@}*/ /*! * @name Register SIM_SCGC5, field PORTC[11] (RW) * * This bit controls the clock gate to the Port C module. * * Values: * - 0 - Clock disabled * - 1 - Clock enabled */ /*@{*/ #define BP_SIM_SCGC5_PORTC (11U) /*!< Bit position for SIM_SCGC5_PORTC. */ #define BM_SIM_SCGC5_PORTC (0x00000800U) /*!< Bit mask for SIM_SCGC5_PORTC. */ #define BS_SIM_SCGC5_PORTC (1U) /*!< Bit field size in bits for SIM_SCGC5_PORTC. */ /*! @brief Read current value of the SIM_SCGC5_PORTC field. */ #define BR_SIM_SCGC5_PORTC(x) (BITBAND_ACCESS32(HW_SIM_SCGC5_ADDR(x), BP_SIM_SCGC5_PORTC)) /*! @brief Format value for bitfield SIM_SCGC5_PORTC. */ #define BF_SIM_SCGC5_PORTC(v) ((uint32_t)((uint32_t)(v) << BP_SIM_SCGC5_PORTC) & BM_SIM_SCGC5_PORTC) /*! @brief Set the PORTC field to a new value. */ #define BW_SIM_SCGC5_PORTC(x, v) (BITBAND_ACCESS32(HW_SIM_SCGC5_ADDR(x), BP_SIM_SCGC5_PORTC) = (v)) /*@}*/ /*! * @name Register SIM_SCGC5, field PORTD[12] (RW) * * This bit controls the clock gate to the Port D module. * * Values: * - 0 - Clock disabled * - 1 - Clock enabled */ /*@{*/ #define BP_SIM_SCGC5_PORTD (12U) /*!< Bit position for SIM_SCGC5_PORTD. */ #define BM_SIM_SCGC5_PORTD (0x00001000U) /*!< Bit mask for SIM_SCGC5_PORTD. */ #define BS_SIM_SCGC5_PORTD (1U) /*!< Bit field size in bits for SIM_SCGC5_PORTD. */ /*! @brief Read current value of the SIM_SCGC5_PORTD field. */ #define BR_SIM_SCGC5_PORTD(x) (BITBAND_ACCESS32(HW_SIM_SCGC5_ADDR(x), BP_SIM_SCGC5_PORTD)) /*! @brief Format value for bitfield SIM_SCGC5_PORTD. */ #define BF_SIM_SCGC5_PORTD(v) ((uint32_t)((uint32_t)(v) << BP_SIM_SCGC5_PORTD) & BM_SIM_SCGC5_PORTD) /*! @brief Set the PORTD field to a new value. */ #define BW_SIM_SCGC5_PORTD(x, v) (BITBAND_ACCESS32(HW_SIM_SCGC5_ADDR(x), BP_SIM_SCGC5_PORTD) = (v)) /*@}*/ /*! * @name Register SIM_SCGC5, field PORTE[13] (RW) * * This bit controls the clock gate to the Port E module. * * Values: * - 0 - Clock disabled * - 1 - Clock enabled */ /*@{*/ #define BP_SIM_SCGC5_PORTE (13U) /*!< Bit position for SIM_SCGC5_PORTE. */ #define BM_SIM_SCGC5_PORTE (0x00002000U) /*!< Bit mask for SIM_SCGC5_PORTE. */ #define BS_SIM_SCGC5_PORTE (1U) /*!< Bit field size in bits for SIM_SCGC5_PORTE. */ /*! @brief Read current value of the SIM_SCGC5_PORTE field. */ #define BR_SIM_SCGC5_PORTE(x) (BITBAND_ACCESS32(HW_SIM_SCGC5_ADDR(x), BP_SIM_SCGC5_PORTE)) /*! @brief Format value for bitfield SIM_SCGC5_PORTE. */ #define BF_SIM_SCGC5_PORTE(v) ((uint32_t)((uint32_t)(v) << BP_SIM_SCGC5_PORTE) & BM_SIM_SCGC5_PORTE) /*! @brief Set the PORTE field to a new value. */ #define BW_SIM_SCGC5_PORTE(x, v) (BITBAND_ACCESS32(HW_SIM_SCGC5_ADDR(x), BP_SIM_SCGC5_PORTE) = (v)) /*@}*/ /******************************************************************************* * HW_SIM_SCGC6 - System Clock Gating Control Register 6 ******************************************************************************/ /*! * @brief HW_SIM_SCGC6 - System Clock Gating Control Register 6 (RW) * * Reset value: 0x40000001U * * DAC0, FTM2, and RNGA can be accessed through both AIPS0 and AIPS1. When * accessing through AIPS1, define the clock gate control bits in the SCGC2 and SCGC3. * When accessing through AIPS0, define the clock gate control bits in SCGC6. */ typedef union _hw_sim_scgc6 { uint32_t U; struct _hw_sim_scgc6_bitfields { uint32_t FTF : 1; /*!< [0] Flash Memory Clock Gate Control */ uint32_t DMAMUXb : 1; /*!< [1] DMA Mux Clock Gate Control */ uint32_t RESERVED0 : 2; /*!< [3:2] */ uint32_t FLEXCAN0 : 1; /*!< [4] FlexCAN0 Clock Gate Control */ uint32_t RESERVED1 : 4; /*!< [8:5] */ uint32_t RNGA : 1; /*!< [9] RNGA Clock Gate Control */ uint32_t RESERVED2 : 2; /*!< [11:10] */ uint32_t SPI0b : 1; /*!< [12] SPI0 Clock Gate Control */ uint32_t SPI1b : 1; /*!< [13] SPI1 Clock Gate Control */ uint32_t RESERVED3 : 1; /*!< [14] */ uint32_t I2S : 1; /*!< [15] I2S Clock Gate Control */ uint32_t RESERVED4 : 2; /*!< [17:16] */ uint32_t CRC : 1; /*!< [18] CRC Clock Gate Control */ uint32_t RESERVED5 : 2; /*!< [20:19] */ uint32_t USBDCDb : 1; /*!< [21] USB DCD Clock Gate Control */ uint32_t PDB : 1; /*!< [22] PDB Clock Gate Control */ uint32_t PITb : 1; /*!< [23] PIT Clock Gate Control */ uint32_t FTM0b : 1; /*!< [24] FTM0 Clock Gate Control */ uint32_t FTM1b : 1; /*!< [25] FTM1 Clock Gate Control */ uint32_t FTM2b : 1; /*!< [26] FTM2 Clock Gate Control */ uint32_t ADC0b : 1; /*!< [27] ADC0 Clock Gate Control */ uint32_t RESERVED6 : 1; /*!< [28] */ uint32_t RTCb : 1; /*!< [29] RTC Access Control */ uint32_t RESERVED7 : 1; /*!< [30] */ uint32_t DAC0b : 1; /*!< [31] DAC0 Clock Gate Control */ } B; } hw_sim_scgc6_t; /*! * @name Constants and macros for entire SIM_SCGC6 register */ /*@{*/ #define HW_SIM_SCGC6_ADDR(x) ((x) + 0x103CU) #define HW_SIM_SCGC6(x) (*(__IO hw_sim_scgc6_t *) HW_SIM_SCGC6_ADDR(x)) #define HW_SIM_SCGC6_RD(x) (HW_SIM_SCGC6(x).U) #define HW_SIM_SCGC6_WR(x, v) (HW_SIM_SCGC6(x).U = (v)) #define HW_SIM_SCGC6_SET(x, v) (HW_SIM_SCGC6_WR(x, HW_SIM_SCGC6_RD(x) | (v))) #define HW_SIM_SCGC6_CLR(x, v) (HW_SIM_SCGC6_WR(x, HW_SIM_SCGC6_RD(x) & ~(v))) #define HW_SIM_SCGC6_TOG(x, v) (HW_SIM_SCGC6_WR(x, HW_SIM_SCGC6_RD(x) ^ (v))) /*@}*/ /* * Constants & macros for individual SIM_SCGC6 bitfields */ /*! * @name Register SIM_SCGC6, field FTF[0] (RW) * * This bit controls the clock gate to the flash memory. Flash reads are still * supported while the flash memory is clock gated, but entry into low power modes * is blocked. * * Values: * - 0 - Clock disabled * - 1 - Clock enabled */ /*@{*/ #define BP_SIM_SCGC6_FTF (0U) /*!< Bit position for SIM_SCGC6_FTF. */ #define BM_SIM_SCGC6_FTF (0x00000001U) /*!< Bit mask for SIM_SCGC6_FTF. */ #define BS_SIM_SCGC6_FTF (1U) /*!< Bit field size in bits for SIM_SCGC6_FTF. */ /*! @brief Read current value of the SIM_SCGC6_FTF field. */ #define BR_SIM_SCGC6_FTF(x) (BITBAND_ACCESS32(HW_SIM_SCGC6_ADDR(x), BP_SIM_SCGC6_FTF)) /*! @brief Format value for bitfield SIM_SCGC6_FTF. */ #define BF_SIM_SCGC6_FTF(v) ((uint32_t)((uint32_t)(v) << BP_SIM_SCGC6_FTF) & BM_SIM_SCGC6_FTF) /*! @brief Set the FTF field to a new value. */ #define BW_SIM_SCGC6_FTF(x, v) (BITBAND_ACCESS32(HW_SIM_SCGC6_ADDR(x), BP_SIM_SCGC6_FTF) = (v)) /*@}*/ /*! * @name Register SIM_SCGC6, field DMAMUX[1] (RW) * * This bit controls the clock gate to the DMA Mux module. * * Values: * - 0 - Clock disabled * - 1 - Clock enabled */ /*@{*/ #define BP_SIM_SCGC6_DMAMUX (1U) /*!< Bit position for SIM_SCGC6_DMAMUX. */ #define BM_SIM_SCGC6_DMAMUX (0x00000002U) /*!< Bit mask for SIM_SCGC6_DMAMUX. */ #define BS_SIM_SCGC6_DMAMUX (1U) /*!< Bit field size in bits for SIM_SCGC6_DMAMUX. */ /*! @brief Read current value of the SIM_SCGC6_DMAMUX field. */ #define BR_SIM_SCGC6_DMAMUX(x) (BITBAND_ACCESS32(HW_SIM_SCGC6_ADDR(x), BP_SIM_SCGC6_DMAMUX)) /*! @brief Format value for bitfield SIM_SCGC6_DMAMUX. */ #define BF_SIM_SCGC6_DMAMUX(v) ((uint32_t)((uint32_t)(v) << BP_SIM_SCGC6_DMAMUX) & BM_SIM_SCGC6_DMAMUX) /*! @brief Set the DMAMUX field to a new value. */ #define BW_SIM_SCGC6_DMAMUX(x, v) (BITBAND_ACCESS32(HW_SIM_SCGC6_ADDR(x), BP_SIM_SCGC6_DMAMUX) = (v)) /*@}*/ /*! * @name Register SIM_SCGC6, field FLEXCAN0[4] (RW) * * This bit controls the clock gate to the FlexCAN0 module. * * Values: * - 0 - Clock disabled * - 1 - Clock enabled */ /*@{*/ #define BP_SIM_SCGC6_FLEXCAN0 (4U) /*!< Bit position for SIM_SCGC6_FLEXCAN0. */ #define BM_SIM_SCGC6_FLEXCAN0 (0x00000010U) /*!< Bit mask for SIM_SCGC6_FLEXCAN0. */ #define BS_SIM_SCGC6_FLEXCAN0 (1U) /*!< Bit field size in bits for SIM_SCGC6_FLEXCAN0. */ /*! @brief Read current value of the SIM_SCGC6_FLEXCAN0 field. */ #define BR_SIM_SCGC6_FLEXCAN0(x) (BITBAND_ACCESS32(HW_SIM_SCGC6_ADDR(x), BP_SIM_SCGC6_FLEXCAN0)) /*! @brief Format value for bitfield SIM_SCGC6_FLEXCAN0. */ #define BF_SIM_SCGC6_FLEXCAN0(v) ((uint32_t)((uint32_t)(v) << BP_SIM_SCGC6_FLEXCAN0) & BM_SIM_SCGC6_FLEXCAN0) /*! @brief Set the FLEXCAN0 field to a new value. */ #define BW_SIM_SCGC6_FLEXCAN0(x, v) (BITBAND_ACCESS32(HW_SIM_SCGC6_ADDR(x), BP_SIM_SCGC6_FLEXCAN0) = (v)) /*@}*/ /*! * @name Register SIM_SCGC6, field RNGA[9] (RW) * * This bit controls the clock gate to the RNGA module. */ /*@{*/ #define BP_SIM_SCGC6_RNGA (9U) /*!< Bit position for SIM_SCGC6_RNGA. */ #define BM_SIM_SCGC6_RNGA (0x00000200U) /*!< Bit mask for SIM_SCGC6_RNGA. */ #define BS_SIM_SCGC6_RNGA (1U) /*!< Bit field size in bits for SIM_SCGC6_RNGA. */ /*! @brief Read current value of the SIM_SCGC6_RNGA field. */ #define BR_SIM_SCGC6_RNGA(x) (BITBAND_ACCESS32(HW_SIM_SCGC6_ADDR(x), BP_SIM_SCGC6_RNGA)) /*! @brief Format value for bitfield SIM_SCGC6_RNGA. */ #define BF_SIM_SCGC6_RNGA(v) ((uint32_t)((uint32_t)(v) << BP_SIM_SCGC6_RNGA) & BM_SIM_SCGC6_RNGA) /*! @brief Set the RNGA field to a new value. */ #define BW_SIM_SCGC6_RNGA(x, v) (BITBAND_ACCESS32(HW_SIM_SCGC6_ADDR(x), BP_SIM_SCGC6_RNGA) = (v)) /*@}*/ /*! * @name Register SIM_SCGC6, field SPI0[12] (RW) * * This bit controls the clock gate to the SPI0 module. * * Values: * - 0 - Clock disabled * - 1 - Clock enabled */ /*@{*/ #define BP_SIM_SCGC6_SPI0 (12U) /*!< Bit position for SIM_SCGC6_SPI0. */ #define BM_SIM_SCGC6_SPI0 (0x00001000U) /*!< Bit mask for SIM_SCGC6_SPI0. */ #define BS_SIM_SCGC6_SPI0 (1U) /*!< Bit field size in bits for SIM_SCGC6_SPI0. */ /*! @brief Read current value of the SIM_SCGC6_SPI0 field. */ #define BR_SIM_SCGC6_SPI0(x) (BITBAND_ACCESS32(HW_SIM_SCGC6_ADDR(x), BP_SIM_SCGC6_SPI0)) /*! @brief Format value for bitfield SIM_SCGC6_SPI0. */ #define BF_SIM_SCGC6_SPI0(v) ((uint32_t)((uint32_t)(v) << BP_SIM_SCGC6_SPI0) & BM_SIM_SCGC6_SPI0) /*! @brief Set the SPI0 field to a new value. */ #define BW_SIM_SCGC6_SPI0(x, v) (BITBAND_ACCESS32(HW_SIM_SCGC6_ADDR(x), BP_SIM_SCGC6_SPI0) = (v)) /*@}*/ /*! * @name Register SIM_SCGC6, field SPI1[13] (RW) * * This bit controls the clock gate to the SPI1 module. * * Values: * - 0 - Clock disabled * - 1 - Clock enabled */ /*@{*/ #define BP_SIM_SCGC6_SPI1 (13U) /*!< Bit position for SIM_SCGC6_SPI1. */ #define BM_SIM_SCGC6_SPI1 (0x00002000U) /*!< Bit mask for SIM_SCGC6_SPI1. */ #define BS_SIM_SCGC6_SPI1 (1U) /*!< Bit field size in bits for SIM_SCGC6_SPI1. */ /*! @brief Read current value of the SIM_SCGC6_SPI1 field. */ #define BR_SIM_SCGC6_SPI1(x) (BITBAND_ACCESS32(HW_SIM_SCGC6_ADDR(x), BP_SIM_SCGC6_SPI1)) /*! @brief Format value for bitfield SIM_SCGC6_SPI1. */ #define BF_SIM_SCGC6_SPI1(v) ((uint32_t)((uint32_t)(v) << BP_SIM_SCGC6_SPI1) & BM_SIM_SCGC6_SPI1) /*! @brief Set the SPI1 field to a new value. */ #define BW_SIM_SCGC6_SPI1(x, v) (BITBAND_ACCESS32(HW_SIM_SCGC6_ADDR(x), BP_SIM_SCGC6_SPI1) = (v)) /*@}*/ /*! * @name Register SIM_SCGC6, field I2S[15] (RW) * * This bit controls the clock gate to the I 2 S module. * * Values: * - 0 - Clock disabled * - 1 - Clock enabled */ /*@{*/ #define BP_SIM_SCGC6_I2S (15U) /*!< Bit position for SIM_SCGC6_I2S. */ #define BM_SIM_SCGC6_I2S (0x00008000U) /*!< Bit mask for SIM_SCGC6_I2S. */ #define BS_SIM_SCGC6_I2S (1U) /*!< Bit field size in bits for SIM_SCGC6_I2S. */ /*! @brief Read current value of the SIM_SCGC6_I2S field. */ #define BR_SIM_SCGC6_I2S(x) (BITBAND_ACCESS32(HW_SIM_SCGC6_ADDR(x), BP_SIM_SCGC6_I2S)) /*! @brief Format value for bitfield SIM_SCGC6_I2S. */ #define BF_SIM_SCGC6_I2S(v) ((uint32_t)((uint32_t)(v) << BP_SIM_SCGC6_I2S) & BM_SIM_SCGC6_I2S) /*! @brief Set the I2S field to a new value. */ #define BW_SIM_SCGC6_I2S(x, v) (BITBAND_ACCESS32(HW_SIM_SCGC6_ADDR(x), BP_SIM_SCGC6_I2S) = (v)) /*@}*/ /*! * @name Register SIM_SCGC6, field CRC[18] (RW) * * This bit controls the clock gate to the CRC module. * * Values: * - 0 - Clock disabled * - 1 - Clock enabled */ /*@{*/ #define BP_SIM_SCGC6_CRC (18U) /*!< Bit position for SIM_SCGC6_CRC. */ #define BM_SIM_SCGC6_CRC (0x00040000U) /*!< Bit mask for SIM_SCGC6_CRC. */ #define BS_SIM_SCGC6_CRC (1U) /*!< Bit field size in bits for SIM_SCGC6_CRC. */ /*! @brief Read current value of the SIM_SCGC6_CRC field. */ #define BR_SIM_SCGC6_CRC(x) (BITBAND_ACCESS32(HW_SIM_SCGC6_ADDR(x), BP_SIM_SCGC6_CRC)) /*! @brief Format value for bitfield SIM_SCGC6_CRC. */ #define BF_SIM_SCGC6_CRC(v) ((uint32_t)((uint32_t)(v) << BP_SIM_SCGC6_CRC) & BM_SIM_SCGC6_CRC) /*! @brief Set the CRC field to a new value. */ #define BW_SIM_SCGC6_CRC(x, v) (BITBAND_ACCESS32(HW_SIM_SCGC6_ADDR(x), BP_SIM_SCGC6_CRC) = (v)) /*@}*/ /*! * @name Register SIM_SCGC6, field USBDCD[21] (RW) * * This bit controls the clock gate to the USB DCD module. * * Values: * - 0 - Clock disabled * - 1 - Clock enabled */ /*@{*/ #define BP_SIM_SCGC6_USBDCD (21U) /*!< Bit position for SIM_SCGC6_USBDCD. */ #define BM_SIM_SCGC6_USBDCD (0x00200000U) /*!< Bit mask for SIM_SCGC6_USBDCD. */ #define BS_SIM_SCGC6_USBDCD (1U) /*!< Bit field size in bits for SIM_SCGC6_USBDCD. */ /*! @brief Read current value of the SIM_SCGC6_USBDCD field. */ #define BR_SIM_SCGC6_USBDCD(x) (BITBAND_ACCESS32(HW_SIM_SCGC6_ADDR(x), BP_SIM_SCGC6_USBDCD)) /*! @brief Format value for bitfield SIM_SCGC6_USBDCD. */ #define BF_SIM_SCGC6_USBDCD(v) ((uint32_t)((uint32_t)(v) << BP_SIM_SCGC6_USBDCD) & BM_SIM_SCGC6_USBDCD) /*! @brief Set the USBDCD field to a new value. */ #define BW_SIM_SCGC6_USBDCD(x, v) (BITBAND_ACCESS32(HW_SIM_SCGC6_ADDR(x), BP_SIM_SCGC6_USBDCD) = (v)) /*@}*/ /*! * @name Register SIM_SCGC6, field PDB[22] (RW) * * This bit controls the clock gate to the PDB module. * * Values: * - 0 - Clock disabled * - 1 - Clock enabled */ /*@{*/ #define BP_SIM_SCGC6_PDB (22U) /*!< Bit position for SIM_SCGC6_PDB. */ #define BM_SIM_SCGC6_PDB (0x00400000U) /*!< Bit mask for SIM_SCGC6_PDB. */ #define BS_SIM_SCGC6_PDB (1U) /*!< Bit field size in bits for SIM_SCGC6_PDB. */ /*! @brief Read current value of the SIM_SCGC6_PDB field. */ #define BR_SIM_SCGC6_PDB(x) (BITBAND_ACCESS32(HW_SIM_SCGC6_ADDR(x), BP_SIM_SCGC6_PDB)) /*! @brief Format value for bitfield SIM_SCGC6_PDB. */ #define BF_SIM_SCGC6_PDB(v) ((uint32_t)((uint32_t)(v) << BP_SIM_SCGC6_PDB) & BM_SIM_SCGC6_PDB) /*! @brief Set the PDB field to a new value. */ #define BW_SIM_SCGC6_PDB(x, v) (BITBAND_ACCESS32(HW_SIM_SCGC6_ADDR(x), BP_SIM_SCGC6_PDB) = (v)) /*@}*/ /*! * @name Register SIM_SCGC6, field PIT[23] (RW) * * This bit controls the clock gate to the PIT module. * * Values: * - 0 - Clock disabled * - 1 - Clock enabled */ /*@{*/ #define BP_SIM_SCGC6_PIT (23U) /*!< Bit position for SIM_SCGC6_PIT. */ #define BM_SIM_SCGC6_PIT (0x00800000U) /*!< Bit mask for SIM_SCGC6_PIT. */ #define BS_SIM_SCGC6_PIT (1U) /*!< Bit field size in bits for SIM_SCGC6_PIT. */ /*! @brief Read current value of the SIM_SCGC6_PIT field. */ #define BR_SIM_SCGC6_PIT(x) (BITBAND_ACCESS32(HW_SIM_SCGC6_ADDR(x), BP_SIM_SCGC6_PIT)) /*! @brief Format value for bitfield SIM_SCGC6_PIT. */ #define BF_SIM_SCGC6_PIT(v) ((uint32_t)((uint32_t)(v) << BP_SIM_SCGC6_PIT) & BM_SIM_SCGC6_PIT) /*! @brief Set the PIT field to a new value. */ #define BW_SIM_SCGC6_PIT(x, v) (BITBAND_ACCESS32(HW_SIM_SCGC6_ADDR(x), BP_SIM_SCGC6_PIT) = (v)) /*@}*/ /*! * @name Register SIM_SCGC6, field FTM0[24] (RW) * * This bit controls the clock gate to the FTM0 module. * * Values: * - 0 - Clock disabled * - 1 - Clock enabled */ /*@{*/ #define BP_SIM_SCGC6_FTM0 (24U) /*!< Bit position for SIM_SCGC6_FTM0. */ #define BM_SIM_SCGC6_FTM0 (0x01000000U) /*!< Bit mask for SIM_SCGC6_FTM0. */ #define BS_SIM_SCGC6_FTM0 (1U) /*!< Bit field size in bits for SIM_SCGC6_FTM0. */ /*! @brief Read current value of the SIM_SCGC6_FTM0 field. */ #define BR_SIM_SCGC6_FTM0(x) (BITBAND_ACCESS32(HW_SIM_SCGC6_ADDR(x), BP_SIM_SCGC6_FTM0)) /*! @brief Format value for bitfield SIM_SCGC6_FTM0. */ #define BF_SIM_SCGC6_FTM0(v) ((uint32_t)((uint32_t)(v) << BP_SIM_SCGC6_FTM0) & BM_SIM_SCGC6_FTM0) /*! @brief Set the FTM0 field to a new value. */ #define BW_SIM_SCGC6_FTM0(x, v) (BITBAND_ACCESS32(HW_SIM_SCGC6_ADDR(x), BP_SIM_SCGC6_FTM0) = (v)) /*@}*/ /*! * @name Register SIM_SCGC6, field FTM1[25] (RW) * * This bit controls the clock gate to the FTM1 module. * * Values: * - 0 - Clock disabled * - 1 - Clock enabled */ /*@{*/ #define BP_SIM_SCGC6_FTM1 (25U) /*!< Bit position for SIM_SCGC6_FTM1. */ #define BM_SIM_SCGC6_FTM1 (0x02000000U) /*!< Bit mask for SIM_SCGC6_FTM1. */ #define BS_SIM_SCGC6_FTM1 (1U) /*!< Bit field size in bits for SIM_SCGC6_FTM1. */ /*! @brief Read current value of the SIM_SCGC6_FTM1 field. */ #define BR_SIM_SCGC6_FTM1(x) (BITBAND_ACCESS32(HW_SIM_SCGC6_ADDR(x), BP_SIM_SCGC6_FTM1)) /*! @brief Format value for bitfield SIM_SCGC6_FTM1. */ #define BF_SIM_SCGC6_FTM1(v) ((uint32_t)((uint32_t)(v) << BP_SIM_SCGC6_FTM1) & BM_SIM_SCGC6_FTM1) /*! @brief Set the FTM1 field to a new value. */ #define BW_SIM_SCGC6_FTM1(x, v) (BITBAND_ACCESS32(HW_SIM_SCGC6_ADDR(x), BP_SIM_SCGC6_FTM1) = (v)) /*@}*/ /*! * @name Register SIM_SCGC6, field FTM2[26] (RW) * * This bit controls the clock gate to the FTM2 module. * * Values: * - 0 - Clock disabled * - 1 - Clock enabled */ /*@{*/ #define BP_SIM_SCGC6_FTM2 (26U) /*!< Bit position for SIM_SCGC6_FTM2. */ #define BM_SIM_SCGC6_FTM2 (0x04000000U) /*!< Bit mask for SIM_SCGC6_FTM2. */ #define BS_SIM_SCGC6_FTM2 (1U) /*!< Bit field size in bits for SIM_SCGC6_FTM2. */ /*! @brief Read current value of the SIM_SCGC6_FTM2 field. */ #define BR_SIM_SCGC6_FTM2(x) (BITBAND_ACCESS32(HW_SIM_SCGC6_ADDR(x), BP_SIM_SCGC6_FTM2)) /*! @brief Format value for bitfield SIM_SCGC6_FTM2. */ #define BF_SIM_SCGC6_FTM2(v) ((uint32_t)((uint32_t)(v) << BP_SIM_SCGC6_FTM2) & BM_SIM_SCGC6_FTM2) /*! @brief Set the FTM2 field to a new value. */ #define BW_SIM_SCGC6_FTM2(x, v) (BITBAND_ACCESS32(HW_SIM_SCGC6_ADDR(x), BP_SIM_SCGC6_FTM2) = (v)) /*@}*/ /*! * @name Register SIM_SCGC6, field ADC0[27] (RW) * * This bit controls the clock gate to the ADC0 module. * * Values: * - 0 - Clock disabled * - 1 - Clock enabled */ /*@{*/ #define BP_SIM_SCGC6_ADC0 (27U) /*!< Bit position for SIM_SCGC6_ADC0. */ #define BM_SIM_SCGC6_ADC0 (0x08000000U) /*!< Bit mask for SIM_SCGC6_ADC0. */ #define BS_SIM_SCGC6_ADC0 (1U) /*!< Bit field size in bits for SIM_SCGC6_ADC0. */ /*! @brief Read current value of the SIM_SCGC6_ADC0 field. */ #define BR_SIM_SCGC6_ADC0(x) (BITBAND_ACCESS32(HW_SIM_SCGC6_ADDR(x), BP_SIM_SCGC6_ADC0)) /*! @brief Format value for bitfield SIM_SCGC6_ADC0. */ #define BF_SIM_SCGC6_ADC0(v) ((uint32_t)((uint32_t)(v) << BP_SIM_SCGC6_ADC0) & BM_SIM_SCGC6_ADC0) /*! @brief Set the ADC0 field to a new value. */ #define BW_SIM_SCGC6_ADC0(x, v) (BITBAND_ACCESS32(HW_SIM_SCGC6_ADDR(x), BP_SIM_SCGC6_ADC0) = (v)) /*@}*/ /*! * @name Register SIM_SCGC6, field RTC[29] (RW) * * This bit controls software access and interrupts to the RTC module. * * Values: * - 0 - Access and interrupts disabled * - 1 - Access and interrupts enabled */ /*@{*/ #define BP_SIM_SCGC6_RTC (29U) /*!< Bit position for SIM_SCGC6_RTC. */ #define BM_SIM_SCGC6_RTC (0x20000000U) /*!< Bit mask for SIM_SCGC6_RTC. */ #define BS_SIM_SCGC6_RTC (1U) /*!< Bit field size in bits for SIM_SCGC6_RTC. */ /*! @brief Read current value of the SIM_SCGC6_RTC field. */ #define BR_SIM_SCGC6_RTC(x) (BITBAND_ACCESS32(HW_SIM_SCGC6_ADDR(x), BP_SIM_SCGC6_RTC)) /*! @brief Format value for bitfield SIM_SCGC6_RTC. */ #define BF_SIM_SCGC6_RTC(v) ((uint32_t)((uint32_t)(v) << BP_SIM_SCGC6_RTC) & BM_SIM_SCGC6_RTC) /*! @brief Set the RTC field to a new value. */ #define BW_SIM_SCGC6_RTC(x, v) (BITBAND_ACCESS32(HW_SIM_SCGC6_ADDR(x), BP_SIM_SCGC6_RTC) = (v)) /*@}*/ /*! * @name Register SIM_SCGC6, field DAC0[31] (RW) * * This bit controls the clock gate to the DAC0 module. * * Values: * - 0 - Clock disabled * - 1 - Clock enabled */ /*@{*/ #define BP_SIM_SCGC6_DAC0 (31U) /*!< Bit position for SIM_SCGC6_DAC0. */ #define BM_SIM_SCGC6_DAC0 (0x80000000U) /*!< Bit mask for SIM_SCGC6_DAC0. */ #define BS_SIM_SCGC6_DAC0 (1U) /*!< Bit field size in bits for SIM_SCGC6_DAC0. */ /*! @brief Read current value of the SIM_SCGC6_DAC0 field. */ #define BR_SIM_SCGC6_DAC0(x) (BITBAND_ACCESS32(HW_SIM_SCGC6_ADDR(x), BP_SIM_SCGC6_DAC0)) /*! @brief Format value for bitfield SIM_SCGC6_DAC0. */ #define BF_SIM_SCGC6_DAC0(v) ((uint32_t)((uint32_t)(v) << BP_SIM_SCGC6_DAC0) & BM_SIM_SCGC6_DAC0) /*! @brief Set the DAC0 field to a new value. */ #define BW_SIM_SCGC6_DAC0(x, v) (BITBAND_ACCESS32(HW_SIM_SCGC6_ADDR(x), BP_SIM_SCGC6_DAC0) = (v)) /*@}*/ /******************************************************************************* * HW_SIM_SCGC7 - System Clock Gating Control Register 7 ******************************************************************************/ /*! * @brief HW_SIM_SCGC7 - System Clock Gating Control Register 7 (RW) * * Reset value: 0x00000006U */ typedef union _hw_sim_scgc7 { uint32_t U; struct _hw_sim_scgc7_bitfields { uint32_t FLEXBUS : 1; /*!< [0] FlexBus Clock Gate Control */ uint32_t DMA : 1; /*!< [1] DMA Clock Gate Control */ uint32_t MPUb : 1; /*!< [2] MPU Clock Gate Control */ uint32_t RESERVED0 : 29; /*!< [31:3] */ } B; } hw_sim_scgc7_t; /*! * @name Constants and macros for entire SIM_SCGC7 register */ /*@{*/ #define HW_SIM_SCGC7_ADDR(x) ((x) + 0x1040U) #define HW_SIM_SCGC7(x) (*(__IO hw_sim_scgc7_t *) HW_SIM_SCGC7_ADDR(x)) #define HW_SIM_SCGC7_RD(x) (HW_SIM_SCGC7(x).U) #define HW_SIM_SCGC7_WR(x, v) (HW_SIM_SCGC7(x).U = (v)) #define HW_SIM_SCGC7_SET(x, v) (HW_SIM_SCGC7_WR(x, HW_SIM_SCGC7_RD(x) | (v))) #define HW_SIM_SCGC7_CLR(x, v) (HW_SIM_SCGC7_WR(x, HW_SIM_SCGC7_RD(x) & ~(v))) #define HW_SIM_SCGC7_TOG(x, v) (HW_SIM_SCGC7_WR(x, HW_SIM_SCGC7_RD(x) ^ (v))) /*@}*/ /* * Constants & macros for individual SIM_SCGC7 bitfields */ /*! * @name Register SIM_SCGC7, field FLEXBUS[0] (RW) * * This bit controls the clock gate to the FlexBus module. * * Values: * - 0 - Clock disabled * - 1 - Clock enabled */ /*@{*/ #define BP_SIM_SCGC7_FLEXBUS (0U) /*!< Bit position for SIM_SCGC7_FLEXBUS. */ #define BM_SIM_SCGC7_FLEXBUS (0x00000001U) /*!< Bit mask for SIM_SCGC7_FLEXBUS. */ #define BS_SIM_SCGC7_FLEXBUS (1U) /*!< Bit field size in bits for SIM_SCGC7_FLEXBUS. */ /*! @brief Read current value of the SIM_SCGC7_FLEXBUS field. */ #define BR_SIM_SCGC7_FLEXBUS(x) (BITBAND_ACCESS32(HW_SIM_SCGC7_ADDR(x), BP_SIM_SCGC7_FLEXBUS)) /*! @brief Format value for bitfield SIM_SCGC7_FLEXBUS. */ #define BF_SIM_SCGC7_FLEXBUS(v) ((uint32_t)((uint32_t)(v) << BP_SIM_SCGC7_FLEXBUS) & BM_SIM_SCGC7_FLEXBUS) /*! @brief Set the FLEXBUS field to a new value. */ #define BW_SIM_SCGC7_FLEXBUS(x, v) (BITBAND_ACCESS32(HW_SIM_SCGC7_ADDR(x), BP_SIM_SCGC7_FLEXBUS) = (v)) /*@}*/ /*! * @name Register SIM_SCGC7, field DMA[1] (RW) * * This bit controls the clock gate to the DMA module. * * Values: * - 0 - Clock disabled * - 1 - Clock enabled */ /*@{*/ #define BP_SIM_SCGC7_DMA (1U) /*!< Bit position for SIM_SCGC7_DMA. */ #define BM_SIM_SCGC7_DMA (0x00000002U) /*!< Bit mask for SIM_SCGC7_DMA. */ #define BS_SIM_SCGC7_DMA (1U) /*!< Bit field size in bits for SIM_SCGC7_DMA. */ /*! @brief Read current value of the SIM_SCGC7_DMA field. */ #define BR_SIM_SCGC7_DMA(x) (BITBAND_ACCESS32(HW_SIM_SCGC7_ADDR(x), BP_SIM_SCGC7_DMA)) /*! @brief Format value for bitfield SIM_SCGC7_DMA. */ #define BF_SIM_SCGC7_DMA(v) ((uint32_t)((uint32_t)(v) << BP_SIM_SCGC7_DMA) & BM_SIM_SCGC7_DMA) /*! @brief Set the DMA field to a new value. */ #define BW_SIM_SCGC7_DMA(x, v) (BITBAND_ACCESS32(HW_SIM_SCGC7_ADDR(x), BP_SIM_SCGC7_DMA) = (v)) /*@}*/ /*! * @name Register SIM_SCGC7, field MPU[2] (RW) * * This bit controls the clock gate to the MPU module. * * Values: * - 0 - Clock disabled * - 1 - Clock enabled */ /*@{*/ #define BP_SIM_SCGC7_MPU (2U) /*!< Bit position for SIM_SCGC7_MPU. */ #define BM_SIM_SCGC7_MPU (0x00000004U) /*!< Bit mask for SIM_SCGC7_MPU. */ #define BS_SIM_SCGC7_MPU (1U) /*!< Bit field size in bits for SIM_SCGC7_MPU. */ /*! @brief Read current value of the SIM_SCGC7_MPU field. */ #define BR_SIM_SCGC7_MPU(x) (BITBAND_ACCESS32(HW_SIM_SCGC7_ADDR(x), BP_SIM_SCGC7_MPU)) /*! @brief Format value for bitfield SIM_SCGC7_MPU. */ #define BF_SIM_SCGC7_MPU(v) ((uint32_t)((uint32_t)(v) << BP_SIM_SCGC7_MPU) & BM_SIM_SCGC7_MPU) /*! @brief Set the MPU field to a new value. */ #define BW_SIM_SCGC7_MPU(x, v) (BITBAND_ACCESS32(HW_SIM_SCGC7_ADDR(x), BP_SIM_SCGC7_MPU) = (v)) /*@}*/ /******************************************************************************* * HW_SIM_CLKDIV1 - System Clock Divider Register 1 ******************************************************************************/ /*! * @brief HW_SIM_CLKDIV1 - System Clock Divider Register 1 (RW) * * Reset value: 0x00010000U * * When updating CLKDIV1, update all fields using the one write command. * Attempting to write an invalid clock ratio to the CLKDIV1 register will cause the * write to be ignored. The maximum divide ratio that can be programmed between * core/system clock and the other divided clocks is divide by 8. When OUTDIV1 equals * 0000 (divide by 1), the other dividers cannot be set higher than 0111 (divide * by 8). The CLKDIV1 register cannot be written to when the device is in VLPR * mode. */ typedef union _hw_sim_clkdiv1 { uint32_t U; struct _hw_sim_clkdiv1_bitfields { uint32_t RESERVED0 : 16; /*!< [15:0] */ uint32_t OUTDIV4 : 4; /*!< [19:16] Clock 4 output divider value */ uint32_t OUTDIV3 : 4; /*!< [23:20] Clock 3 output divider value */ uint32_t OUTDIV2 : 4; /*!< [27:24] Clock 2 output divider value */ uint32_t OUTDIV1 : 4; /*!< [31:28] Clock 1 output divider value */ } B; } hw_sim_clkdiv1_t; /*! * @name Constants and macros for entire SIM_CLKDIV1 register */ /*@{*/ #define HW_SIM_CLKDIV1_ADDR(x) ((x) + 0x1044U) #define HW_SIM_CLKDIV1(x) (*(__IO hw_sim_clkdiv1_t *) HW_SIM_CLKDIV1_ADDR(x)) #define HW_SIM_CLKDIV1_RD(x) (HW_SIM_CLKDIV1(x).U) #define HW_SIM_CLKDIV1_WR(x, v) (HW_SIM_CLKDIV1(x).U = (v)) #define HW_SIM_CLKDIV1_SET(x, v) (HW_SIM_CLKDIV1_WR(x, HW_SIM_CLKDIV1_RD(x) | (v))) #define HW_SIM_CLKDIV1_CLR(x, v) (HW_SIM_CLKDIV1_WR(x, HW_SIM_CLKDIV1_RD(x) & ~(v))) #define HW_SIM_CLKDIV1_TOG(x, v) (HW_SIM_CLKDIV1_WR(x, HW_SIM_CLKDIV1_RD(x) ^ (v))) /*@}*/ /* * Constants & macros for individual SIM_CLKDIV1 bitfields */ /*! * @name Register SIM_CLKDIV1, field OUTDIV4[19:16] (RW) * * This field sets the divide value for the flash clock from MCGOUTCLK. At the * end of reset, it is loaded with either 0001 or 1111 depending on * FTF_FOPT[LPBOOT]. The flash clock frequency must be an integer divide of the system clock * frequency. * * Values: * - 0000 - Divide-by-1. * - 0001 - Divide-by-2. * - 0010 - Divide-by-3. * - 0011 - Divide-by-4. * - 0100 - Divide-by-5. * - 0101 - Divide-by-6. * - 0110 - Divide-by-7. * - 0111 - Divide-by-8. * - 1000 - Divide-by-9. * - 1001 - Divide-by-10. * - 1010 - Divide-by-11. * - 1011 - Divide-by-12. * - 1100 - Divide-by-13. * - 1101 - Divide-by-14. * - 1110 - Divide-by-15. * - 1111 - Divide-by-16. */ /*@{*/ #define BP_SIM_CLKDIV1_OUTDIV4 (16U) /*!< Bit position for SIM_CLKDIV1_OUTDIV4. */ #define BM_SIM_CLKDIV1_OUTDIV4 (0x000F0000U) /*!< Bit mask for SIM_CLKDIV1_OUTDIV4. */ #define BS_SIM_CLKDIV1_OUTDIV4 (4U) /*!< Bit field size in bits for SIM_CLKDIV1_OUTDIV4. */ /*! @brief Read current value of the SIM_CLKDIV1_OUTDIV4 field. */ #define BR_SIM_CLKDIV1_OUTDIV4(x) (HW_SIM_CLKDIV1(x).B.OUTDIV4) /*! @brief Format value for bitfield SIM_CLKDIV1_OUTDIV4. */ #define BF_SIM_CLKDIV1_OUTDIV4(v) ((uint32_t)((uint32_t)(v) << BP_SIM_CLKDIV1_OUTDIV4) & BM_SIM_CLKDIV1_OUTDIV4) /*! @brief Set the OUTDIV4 field to a new value. */ #define BW_SIM_CLKDIV1_OUTDIV4(x, v) (HW_SIM_CLKDIV1_WR(x, (HW_SIM_CLKDIV1_RD(x) & ~BM_SIM_CLKDIV1_OUTDIV4) | BF_SIM_CLKDIV1_OUTDIV4(v))) /*@}*/ /*! * @name Register SIM_CLKDIV1, field OUTDIV3[23:20] (RW) * * This field sets the divide value for the FlexBus clock (external pin FB_CLK) * from MCGOUTCLK. At the end of reset, it is loaded with either 0001 or 1111 * depending on FTF_FOPT[LPBOOT]. The FlexBus clock frequency must be an integer * divide of the system clock frequency. * * Values: * - 0000 - Divide-by-1. * - 0001 - Divide-by-2. * - 0010 - Divide-by-3. * - 0011 - Divide-by-4. * - 0100 - Divide-by-5. * - 0101 - Divide-by-6. * - 0110 - Divide-by-7. * - 0111 - Divide-by-8. * - 1000 - Divide-by-9. * - 1001 - Divide-by-10. * - 1010 - Divide-by-11. * - 1011 - Divide-by-12. * - 1100 - Divide-by-13. * - 1101 - Divide-by-14. * - 1110 - Divide-by-15. * - 1111 - Divide-by-16. */ /*@{*/ #define BP_SIM_CLKDIV1_OUTDIV3 (20U) /*!< Bit position for SIM_CLKDIV1_OUTDIV3. */ #define BM_SIM_CLKDIV1_OUTDIV3 (0x00F00000U) /*!< Bit mask for SIM_CLKDIV1_OUTDIV3. */ #define BS_SIM_CLKDIV1_OUTDIV3 (4U) /*!< Bit field size in bits for SIM_CLKDIV1_OUTDIV3. */ /*! @brief Read current value of the SIM_CLKDIV1_OUTDIV3 field. */ #define BR_SIM_CLKDIV1_OUTDIV3(x) (HW_SIM_CLKDIV1(x).B.OUTDIV3) /*! @brief Format value for bitfield SIM_CLKDIV1_OUTDIV3. */ #define BF_SIM_CLKDIV1_OUTDIV3(v) ((uint32_t)((uint32_t)(v) << BP_SIM_CLKDIV1_OUTDIV3) & BM_SIM_CLKDIV1_OUTDIV3) /*! @brief Set the OUTDIV3 field to a new value. */ #define BW_SIM_CLKDIV1_OUTDIV3(x, v) (HW_SIM_CLKDIV1_WR(x, (HW_SIM_CLKDIV1_RD(x) & ~BM_SIM_CLKDIV1_OUTDIV3) | BF_SIM_CLKDIV1_OUTDIV3(v))) /*@}*/ /*! * @name Register SIM_CLKDIV1, field OUTDIV2[27:24] (RW) * * This field sets the divide value for the bus clock from MCGOUTCLK. At the end * of reset, it is loaded with either 0000 or 0111 depending on * FTF_FOPT[LPBOOT]. The bus clock frequency must be an integer divide of the core/system clock * frequency. * * Values: * - 0000 - Divide-by-1. * - 0001 - Divide-by-2. * - 0010 - Divide-by-3. * - 0011 - Divide-by-4. * - 0100 - Divide-by-5. * - 0101 - Divide-by-6. * - 0110 - Divide-by-7. * - 0111 - Divide-by-8. * - 1000 - Divide-by-9. * - 1001 - Divide-by-10. * - 1010 - Divide-by-11. * - 1011 - Divide-by-12. * - 1100 - Divide-by-13. * - 1101 - Divide-by-14. * - 1110 - Divide-by-15. * - 1111 - Divide-by-16. */ /*@{*/ #define BP_SIM_CLKDIV1_OUTDIV2 (24U) /*!< Bit position for SIM_CLKDIV1_OUTDIV2. */ #define BM_SIM_CLKDIV1_OUTDIV2 (0x0F000000U) /*!< Bit mask for SIM_CLKDIV1_OUTDIV2. */ #define BS_SIM_CLKDIV1_OUTDIV2 (4U) /*!< Bit field size in bits for SIM_CLKDIV1_OUTDIV2. */ /*! @brief Read current value of the SIM_CLKDIV1_OUTDIV2 field. */ #define BR_SIM_CLKDIV1_OUTDIV2(x) (HW_SIM_CLKDIV1(x).B.OUTDIV2) /*! @brief Format value for bitfield SIM_CLKDIV1_OUTDIV2. */ #define BF_SIM_CLKDIV1_OUTDIV2(v) ((uint32_t)((uint32_t)(v) << BP_SIM_CLKDIV1_OUTDIV2) & BM_SIM_CLKDIV1_OUTDIV2) /*! @brief Set the OUTDIV2 field to a new value. */ #define BW_SIM_CLKDIV1_OUTDIV2(x, v) (HW_SIM_CLKDIV1_WR(x, (HW_SIM_CLKDIV1_RD(x) & ~BM_SIM_CLKDIV1_OUTDIV2) | BF_SIM_CLKDIV1_OUTDIV2(v))) /*@}*/ /*! * @name Register SIM_CLKDIV1, field OUTDIV1[31:28] (RW) * * This field sets the divide value for the core/system clock from MCGOUTCLK. At * the end of reset, it is loaded with either 0000 or 0111 depending on * FTF_FOPT[LPBOOT]. * * Values: * - 0000 - Divide-by-1. * - 0001 - Divide-by-2. * - 0010 - Divide-by-3. * - 0011 - Divide-by-4. * - 0100 - Divide-by-5. * - 0101 - Divide-by-6. * - 0110 - Divide-by-7. * - 0111 - Divide-by-8. * - 1000 - Divide-by-9. * - 1001 - Divide-by-10. * - 1010 - Divide-by-11. * - 1011 - Divide-by-12. * - 1100 - Divide-by-13. * - 1101 - Divide-by-14. * - 1110 - Divide-by-15. * - 1111 - Divide-by-16. */ /*@{*/ #define BP_SIM_CLKDIV1_OUTDIV1 (28U) /*!< Bit position for SIM_CLKDIV1_OUTDIV1. */ #define BM_SIM_CLKDIV1_OUTDIV1 (0xF0000000U) /*!< Bit mask for SIM_CLKDIV1_OUTDIV1. */ #define BS_SIM_CLKDIV1_OUTDIV1 (4U) /*!< Bit field size in bits for SIM_CLKDIV1_OUTDIV1. */ /*! @brief Read current value of the SIM_CLKDIV1_OUTDIV1 field. */ #define BR_SIM_CLKDIV1_OUTDIV1(x) (HW_SIM_CLKDIV1(x).B.OUTDIV1) /*! @brief Format value for bitfield SIM_CLKDIV1_OUTDIV1. */ #define BF_SIM_CLKDIV1_OUTDIV1(v) ((uint32_t)((uint32_t)(v) << BP_SIM_CLKDIV1_OUTDIV1) & BM_SIM_CLKDIV1_OUTDIV1) /*! @brief Set the OUTDIV1 field to a new value. */ #define BW_SIM_CLKDIV1_OUTDIV1(x, v) (HW_SIM_CLKDIV1_WR(x, (HW_SIM_CLKDIV1_RD(x) & ~BM_SIM_CLKDIV1_OUTDIV1) | BF_SIM_CLKDIV1_OUTDIV1(v))) /*@}*/ /******************************************************************************* * HW_SIM_CLKDIV2 - System Clock Divider Register 2 ******************************************************************************/ /*! * @brief HW_SIM_CLKDIV2 - System Clock Divider Register 2 (RW) * * Reset value: 0x00000000U */ typedef union _hw_sim_clkdiv2 { uint32_t U; struct _hw_sim_clkdiv2_bitfields { uint32_t USBFRAC : 1; /*!< [0] USB clock divider fraction */ uint32_t USBDIV : 3; /*!< [3:1] USB clock divider divisor */ uint32_t RESERVED0 : 28; /*!< [31:4] */ } B; } hw_sim_clkdiv2_t; /*! * @name Constants and macros for entire SIM_CLKDIV2 register */ /*@{*/ #define HW_SIM_CLKDIV2_ADDR(x) ((x) + 0x1048U) #define HW_SIM_CLKDIV2(x) (*(__IO hw_sim_clkdiv2_t *) HW_SIM_CLKDIV2_ADDR(x)) #define HW_SIM_CLKDIV2_RD(x) (HW_SIM_CLKDIV2(x).U) #define HW_SIM_CLKDIV2_WR(x, v) (HW_SIM_CLKDIV2(x).U = (v)) #define HW_SIM_CLKDIV2_SET(x, v) (HW_SIM_CLKDIV2_WR(x, HW_SIM_CLKDIV2_RD(x) | (v))) #define HW_SIM_CLKDIV2_CLR(x, v) (HW_SIM_CLKDIV2_WR(x, HW_SIM_CLKDIV2_RD(x) & ~(v))) #define HW_SIM_CLKDIV2_TOG(x, v) (HW_SIM_CLKDIV2_WR(x, HW_SIM_CLKDIV2_RD(x) ^ (v))) /*@}*/ /* * Constants & macros for individual SIM_CLKDIV2 bitfields */ /*! * @name Register SIM_CLKDIV2, field USBFRAC[0] (RW) * * This field sets the fraction multiply value for the fractional clock divider * when the MCGFLLCLK/MCGPLLCLK clock is the USB clock source (SOPT2[USBSRC] = * 1). Divider output clock = Divider input clock * [ (USBFRAC+1) / (USBDIV+1) ] */ /*@{*/ #define BP_SIM_CLKDIV2_USBFRAC (0U) /*!< Bit position for SIM_CLKDIV2_USBFRAC. */ #define BM_SIM_CLKDIV2_USBFRAC (0x00000001U) /*!< Bit mask for SIM_CLKDIV2_USBFRAC. */ #define BS_SIM_CLKDIV2_USBFRAC (1U) /*!< Bit field size in bits for SIM_CLKDIV2_USBFRAC. */ /*! @brief Read current value of the SIM_CLKDIV2_USBFRAC field. */ #define BR_SIM_CLKDIV2_USBFRAC(x) (BITBAND_ACCESS32(HW_SIM_CLKDIV2_ADDR(x), BP_SIM_CLKDIV2_USBFRAC)) /*! @brief Format value for bitfield SIM_CLKDIV2_USBFRAC. */ #define BF_SIM_CLKDIV2_USBFRAC(v) ((uint32_t)((uint32_t)(v) << BP_SIM_CLKDIV2_USBFRAC) & BM_SIM_CLKDIV2_USBFRAC) /*! @brief Set the USBFRAC field to a new value. */ #define BW_SIM_CLKDIV2_USBFRAC(x, v) (BITBAND_ACCESS32(HW_SIM_CLKDIV2_ADDR(x), BP_SIM_CLKDIV2_USBFRAC) = (v)) /*@}*/ /*! * @name Register SIM_CLKDIV2, field USBDIV[3:1] (RW) * * This field sets the divide value for the fractional clock divider when the * MCGFLLCLK/MCGPLLCLK clock is the USB clock source (SOPT2[USBSRC] = 1). Divider * output clock = Divider input clock * [ (USBFRAC+1) / (USBDIV+1) ] */ /*@{*/ #define BP_SIM_CLKDIV2_USBDIV (1U) /*!< Bit position for SIM_CLKDIV2_USBDIV. */ #define BM_SIM_CLKDIV2_USBDIV (0x0000000EU) /*!< Bit mask for SIM_CLKDIV2_USBDIV. */ #define BS_SIM_CLKDIV2_USBDIV (3U) /*!< Bit field size in bits for SIM_CLKDIV2_USBDIV. */ /*! @brief Read current value of the SIM_CLKDIV2_USBDIV field. */ #define BR_SIM_CLKDIV2_USBDIV(x) (HW_SIM_CLKDIV2(x).B.USBDIV) /*! @brief Format value for bitfield SIM_CLKDIV2_USBDIV. */ #define BF_SIM_CLKDIV2_USBDIV(v) ((uint32_t)((uint32_t)(v) << BP_SIM_CLKDIV2_USBDIV) & BM_SIM_CLKDIV2_USBDIV) /*! @brief Set the USBDIV field to a new value. */ #define BW_SIM_CLKDIV2_USBDIV(x, v) (HW_SIM_CLKDIV2_WR(x, (HW_SIM_CLKDIV2_RD(x) & ~BM_SIM_CLKDIV2_USBDIV) | BF_SIM_CLKDIV2_USBDIV(v))) /*@}*/ /******************************************************************************* * HW_SIM_FCFG1 - Flash Configuration Register 1 ******************************************************************************/ /*! * @brief HW_SIM_FCFG1 - Flash Configuration Register 1 (RW) * * Reset value: 0xFF0F0F00U * * For devices with FlexNVM: The reset value of EESIZE and DEPART are based on * user programming in user IFR via the PGMPART flash command. For devices with * program flash only: */ typedef union _hw_sim_fcfg1 { uint32_t U; struct _hw_sim_fcfg1_bitfields { uint32_t FLASHDIS : 1; /*!< [0] Flash Disable */ uint32_t FLASHDOZE : 1; /*!< [1] Flash Doze */ uint32_t RESERVED0 : 6; /*!< [7:2] */ uint32_t DEPART : 4; /*!< [11:8] FlexNVM partition */ uint32_t RESERVED1 : 4; /*!< [15:12] */ uint32_t EESIZE : 4; /*!< [19:16] EEPROM size */ uint32_t RESERVED2 : 4; /*!< [23:20] */ uint32_t PFSIZE : 4; /*!< [27:24] Program flash size */ uint32_t NVMSIZE : 4; /*!< [31:28] FlexNVM size */ } B; } hw_sim_fcfg1_t; /*! * @name Constants and macros for entire SIM_FCFG1 register */ /*@{*/ #define HW_SIM_FCFG1_ADDR(x) ((x) + 0x104CU) #define HW_SIM_FCFG1(x) (*(__IO hw_sim_fcfg1_t *) HW_SIM_FCFG1_ADDR(x)) #define HW_SIM_FCFG1_RD(x) (HW_SIM_FCFG1(x).U) #define HW_SIM_FCFG1_WR(x, v) (HW_SIM_FCFG1(x).U = (v)) #define HW_SIM_FCFG1_SET(x, v) (HW_SIM_FCFG1_WR(x, HW_SIM_FCFG1_RD(x) | (v))) #define HW_SIM_FCFG1_CLR(x, v) (HW_SIM_FCFG1_WR(x, HW_SIM_FCFG1_RD(x) & ~(v))) #define HW_SIM_FCFG1_TOG(x, v) (HW_SIM_FCFG1_WR(x, HW_SIM_FCFG1_RD(x) ^ (v))) /*@}*/ /* * Constants & macros for individual SIM_FCFG1 bitfields */ /*! * @name Register SIM_FCFG1, field FLASHDIS[0] (RW) * * Flash accesses are disabled (and generate a bus error) and the Flash memory * is placed in a low power state. This bit should not be changed during VLP * modes. Relocate the interrupt vectors out of Flash memory before disabling the * Flash. * * Values: * - 0 - Flash is enabled * - 1 - Flash is disabled */ /*@{*/ #define BP_SIM_FCFG1_FLASHDIS (0U) /*!< Bit position for SIM_FCFG1_FLASHDIS. */ #define BM_SIM_FCFG1_FLASHDIS (0x00000001U) /*!< Bit mask for SIM_FCFG1_FLASHDIS. */ #define BS_SIM_FCFG1_FLASHDIS (1U) /*!< Bit field size in bits for SIM_FCFG1_FLASHDIS. */ /*! @brief Read current value of the SIM_FCFG1_FLASHDIS field. */ #define BR_SIM_FCFG1_FLASHDIS(x) (BITBAND_ACCESS32(HW_SIM_FCFG1_ADDR(x), BP_SIM_FCFG1_FLASHDIS)) /*! @brief Format value for bitfield SIM_FCFG1_FLASHDIS. */ #define BF_SIM_FCFG1_FLASHDIS(v) ((uint32_t)((uint32_t)(v) << BP_SIM_FCFG1_FLASHDIS) & BM_SIM_FCFG1_FLASHDIS) /*! @brief Set the FLASHDIS field to a new value. */ #define BW_SIM_FCFG1_FLASHDIS(x, v) (BITBAND_ACCESS32(HW_SIM_FCFG1_ADDR(x), BP_SIM_FCFG1_FLASHDIS) = (v)) /*@}*/ /*! * @name Register SIM_FCFG1, field FLASHDOZE[1] (RW) * * When set, Flash memory is disabled for the duration of Wait mode. An attempt * by the DMA or other bus master to access the Flash when the Flash is disabled * will result in a bus error. This bit should be clear during VLP modes. The * Flash will be automatically enabled again at the end of Wait mode so interrupt * vectors do not need to be relocated out of Flash memory. The wakeup time from * Wait mode is extended when this bit is set. * * Values: * - 0 - Flash remains enabled during Wait mode * - 1 - Flash is disabled for the duration of Wait mode */ /*@{*/ #define BP_SIM_FCFG1_FLASHDOZE (1U) /*!< Bit position for SIM_FCFG1_FLASHDOZE. */ #define BM_SIM_FCFG1_FLASHDOZE (0x00000002U) /*!< Bit mask for SIM_FCFG1_FLASHDOZE. */ #define BS_SIM_FCFG1_FLASHDOZE (1U) /*!< Bit field size in bits for SIM_FCFG1_FLASHDOZE. */ /*! @brief Read current value of the SIM_FCFG1_FLASHDOZE field. */ #define BR_SIM_FCFG1_FLASHDOZE(x) (BITBAND_ACCESS32(HW_SIM_FCFG1_ADDR(x), BP_SIM_FCFG1_FLASHDOZE)) /*! @brief Format value for bitfield SIM_FCFG1_FLASHDOZE. */ #define BF_SIM_FCFG1_FLASHDOZE(v) ((uint32_t)((uint32_t)(v) << BP_SIM_FCFG1_FLASHDOZE) & BM_SIM_FCFG1_FLASHDOZE) /*! @brief Set the FLASHDOZE field to a new value. */ #define BW_SIM_FCFG1_FLASHDOZE(x, v) (BITBAND_ACCESS32(HW_SIM_FCFG1_ADDR(x), BP_SIM_FCFG1_FLASHDOZE) = (v)) /*@}*/ /*! * @name Register SIM_FCFG1, field DEPART[11:8] (RO) * * For devices with FlexNVM: Data flash / EEPROM backup split . See DEPART bit * description in FTFE chapter. For devices without FlexNVM: Reserved */ /*@{*/ #define BP_SIM_FCFG1_DEPART (8U) /*!< Bit position for SIM_FCFG1_DEPART. */ #define BM_SIM_FCFG1_DEPART (0x00000F00U) /*!< Bit mask for SIM_FCFG1_DEPART. */ #define BS_SIM_FCFG1_DEPART (4U) /*!< Bit field size in bits for SIM_FCFG1_DEPART. */ /*! @brief Read current value of the SIM_FCFG1_DEPART field. */ #define BR_SIM_FCFG1_DEPART(x) (HW_SIM_FCFG1(x).B.DEPART) /*@}*/ /*! * @name Register SIM_FCFG1, field EESIZE[19:16] (RO) * * EEPROM data size . * * Values: * - 0000 - 16 KB * - 0001 - 8 KB * - 0010 - 4 KB * - 0011 - 2 KB * - 0100 - 1 KB * - 0101 - 512 Bytes * - 0110 - 256 Bytes * - 0111 - 128 Bytes * - 1000 - 64 Bytes * - 1001 - 32 Bytes * - 1111 - 0 Bytes */ /*@{*/ #define BP_SIM_FCFG1_EESIZE (16U) /*!< Bit position for SIM_FCFG1_EESIZE. */ #define BM_SIM_FCFG1_EESIZE (0x000F0000U) /*!< Bit mask for SIM_FCFG1_EESIZE. */ #define BS_SIM_FCFG1_EESIZE (4U) /*!< Bit field size in bits for SIM_FCFG1_EESIZE. */ /*! @brief Read current value of the SIM_FCFG1_EESIZE field. */ #define BR_SIM_FCFG1_EESIZE(x) (HW_SIM_FCFG1(x).B.EESIZE) /*@}*/ /*! * @name Register SIM_FCFG1, field PFSIZE[27:24] (RO) * * This field specifies the amount of program flash memory available on the * device . Undefined values are reserved. * * Values: * - 0011 - 32 KB of program flash memory * - 0101 - 64 KB of program flash memory * - 0111 - 128 KB of program flash memory * - 1001 - 256 KB of program flash memory * - 1011 - 512 KB of program flash memory * - 1101 - 1024 KB of program flash memory * - 1111 - 1024 KB of program flash memory */ /*@{*/ #define BP_SIM_FCFG1_PFSIZE (24U) /*!< Bit position for SIM_FCFG1_PFSIZE. */ #define BM_SIM_FCFG1_PFSIZE (0x0F000000U) /*!< Bit mask for SIM_FCFG1_PFSIZE. */ #define BS_SIM_FCFG1_PFSIZE (4U) /*!< Bit field size in bits for SIM_FCFG1_PFSIZE. */ /*! @brief Read current value of the SIM_FCFG1_PFSIZE field. */ #define BR_SIM_FCFG1_PFSIZE(x) (HW_SIM_FCFG1(x).B.PFSIZE) /*@}*/ /*! * @name Register SIM_FCFG1, field NVMSIZE[31:28] (RO) * * This field specifies the amount of FlexNVM memory available on the device . * Undefined values are reserved. * * Values: * - 0000 - 0 KB of FlexNVM * - 0011 - 32 KB of FlexNVM * - 0101 - 64 KB of FlexNVM * - 0111 - 128 KB of FlexNVM * - 1001 - 256 KB of FlexNVM * - 1011 - 512 KB of FlexNVM * - 1111 - 512 KB of FlexNVM */ /*@{*/ #define BP_SIM_FCFG1_NVMSIZE (28U) /*!< Bit position for SIM_FCFG1_NVMSIZE. */ #define BM_SIM_FCFG1_NVMSIZE (0xF0000000U) /*!< Bit mask for SIM_FCFG1_NVMSIZE. */ #define BS_SIM_FCFG1_NVMSIZE (4U) /*!< Bit field size in bits for SIM_FCFG1_NVMSIZE. */ /*! @brief Read current value of the SIM_FCFG1_NVMSIZE field. */ #define BR_SIM_FCFG1_NVMSIZE(x) (HW_SIM_FCFG1(x).B.NVMSIZE) /*@}*/ /******************************************************************************* * HW_SIM_FCFG2 - Flash Configuration Register 2 ******************************************************************************/ /*! * @brief HW_SIM_FCFG2 - Flash Configuration Register 2 (RO) * * Reset value: 0x7F7F0000U */ typedef union _hw_sim_fcfg2 { uint32_t U; struct _hw_sim_fcfg2_bitfields { uint32_t RESERVED0 : 16; /*!< [15:0] */ uint32_t MAXADDR1 : 7; /*!< [22:16] Max address block 1 */ uint32_t PFLSH : 1; /*!< [23] Program flash only */ uint32_t MAXADDR0 : 7; /*!< [30:24] Max address block 0 */ uint32_t RESERVED1 : 1; /*!< [31] */ } B; } hw_sim_fcfg2_t; /*! * @name Constants and macros for entire SIM_FCFG2 register */ /*@{*/ #define HW_SIM_FCFG2_ADDR(x) ((x) + 0x1050U) #define HW_SIM_FCFG2(x) (*(__I hw_sim_fcfg2_t *) HW_SIM_FCFG2_ADDR(x)) #define HW_SIM_FCFG2_RD(x) (HW_SIM_FCFG2(x).U) /*@}*/ /* * Constants & macros for individual SIM_FCFG2 bitfields */ /*! * @name Register SIM_FCFG2, field MAXADDR1[22:16] (RO) * * For devices with FlexNVM: This field concatenated with 13 trailing zeros plus * the FlexNVM base address indicates the first invalid address of the FlexNVM * flash block. For example, if MAXADDR1 = 0x20 the first invalid address of * FlexNVM flash block is 0x4_0000 + 0x1000_0000 . This would be the MAXADDR1 value * for a device with 256 KB FlexNVM. For devices with program flash only: This * field equals zero if there is only one program flash block, otherwise it equals * the value of the MAXADDR0 field. For example, with MAXADDR0 = MAXADDR1 = 0x20 * the first invalid address of flash block 1 is 0x4_0000 + 0x4_0000. This would be * the MAXADDR1 value for a device with 512 KB program flash memory across two * flash blocks and no FlexNVM. */ /*@{*/ #define BP_SIM_FCFG2_MAXADDR1 (16U) /*!< Bit position for SIM_FCFG2_MAXADDR1. */ #define BM_SIM_FCFG2_MAXADDR1 (0x007F0000U) /*!< Bit mask for SIM_FCFG2_MAXADDR1. */ #define BS_SIM_FCFG2_MAXADDR1 (7U) /*!< Bit field size in bits for SIM_FCFG2_MAXADDR1. */ /*! @brief Read current value of the SIM_FCFG2_MAXADDR1 field. */ #define BR_SIM_FCFG2_MAXADDR1(x) (HW_SIM_FCFG2(x).B.MAXADDR1) /*@}*/ /*! * @name Register SIM_FCFG2, field PFLSH[23] (RO) * * For devices with FlexNVM, this bit is always clear. For devices without * FlexNVM, this bit is always set. * * Values: * - 0 - Device supports FlexNVM * - 1 - Program Flash only, device does not support FlexNVM */ /*@{*/ #define BP_SIM_FCFG2_PFLSH (23U) /*!< Bit position for SIM_FCFG2_PFLSH. */ #define BM_SIM_FCFG2_PFLSH (0x00800000U) /*!< Bit mask for SIM_FCFG2_PFLSH. */ #define BS_SIM_FCFG2_PFLSH (1U) /*!< Bit field size in bits for SIM_FCFG2_PFLSH. */ /*! @brief Read current value of the SIM_FCFG2_PFLSH field. */ #define BR_SIM_FCFG2_PFLSH(x) (BITBAND_ACCESS32(HW_SIM_FCFG2_ADDR(x), BP_SIM_FCFG2_PFLSH)) /*@}*/ /*! * @name Register SIM_FCFG2, field MAXADDR0[30:24] (RO) * * This field concatenated with 13 trailing zeros indicates the first invalid * address of each program flash block. For example, if MAXADDR0 = 0x20 the first * invalid address of flash block 0 is 0x0004_0000. This would be the MAXADDR0 * value for a device with 256 KB program flash in flash block 0. */ /*@{*/ #define BP_SIM_FCFG2_MAXADDR0 (24U) /*!< Bit position for SIM_FCFG2_MAXADDR0. */ #define BM_SIM_FCFG2_MAXADDR0 (0x7F000000U) /*!< Bit mask for SIM_FCFG2_MAXADDR0. */ #define BS_SIM_FCFG2_MAXADDR0 (7U) /*!< Bit field size in bits for SIM_FCFG2_MAXADDR0. */ /*! @brief Read current value of the SIM_FCFG2_MAXADDR0 field. */ #define BR_SIM_FCFG2_MAXADDR0(x) (HW_SIM_FCFG2(x).B.MAXADDR0) /*@}*/ /******************************************************************************* * HW_SIM_UIDH - Unique Identification Register High ******************************************************************************/ /*! * @brief HW_SIM_UIDH - Unique Identification Register High (RO) * * Reset value: 0x00000000U */ typedef union _hw_sim_uidh { uint32_t U; struct _hw_sim_uidh_bitfields { uint32_t UID : 32; /*!< [31:0] Unique Identification */ } B; } hw_sim_uidh_t; /*! * @name Constants and macros for entire SIM_UIDH register */ /*@{*/ #define HW_SIM_UIDH_ADDR(x) ((x) + 0x1054U) #define HW_SIM_UIDH(x) (*(__I hw_sim_uidh_t *) HW_SIM_UIDH_ADDR(x)) #define HW_SIM_UIDH_RD(x) (HW_SIM_UIDH(x).U) /*@}*/ /* * Constants & macros for individual SIM_UIDH bitfields */ /*! * @name Register SIM_UIDH, field UID[31:0] (RO) * * Unique identification for the device. */ /*@{*/ #define BP_SIM_UIDH_UID (0U) /*!< Bit position for SIM_UIDH_UID. */ #define BM_SIM_UIDH_UID (0xFFFFFFFFU) /*!< Bit mask for SIM_UIDH_UID. */ #define BS_SIM_UIDH_UID (32U) /*!< Bit field size in bits for SIM_UIDH_UID. */ /*! @brief Read current value of the SIM_UIDH_UID field. */ #define BR_SIM_UIDH_UID(x) (HW_SIM_UIDH(x).U) /*@}*/ /******************************************************************************* * HW_SIM_UIDMH - Unique Identification Register Mid-High ******************************************************************************/ /*! * @brief HW_SIM_UIDMH - Unique Identification Register Mid-High (RO) * * Reset value: 0x00000000U */ typedef union _hw_sim_uidmh { uint32_t U; struct _hw_sim_uidmh_bitfields { uint32_t UID : 32; /*!< [31:0] Unique Identification */ } B; } hw_sim_uidmh_t; /*! * @name Constants and macros for entire SIM_UIDMH register */ /*@{*/ #define HW_SIM_UIDMH_ADDR(x) ((x) + 0x1058U) #define HW_SIM_UIDMH(x) (*(__I hw_sim_uidmh_t *) HW_SIM_UIDMH_ADDR(x)) #define HW_SIM_UIDMH_RD(x) (HW_SIM_UIDMH(x).U) /*@}*/ /* * Constants & macros for individual SIM_UIDMH bitfields */ /*! * @name Register SIM_UIDMH, field UID[31:0] (RO) * * Unique identification for the device. */ /*@{*/ #define BP_SIM_UIDMH_UID (0U) /*!< Bit position for SIM_UIDMH_UID. */ #define BM_SIM_UIDMH_UID (0xFFFFFFFFU) /*!< Bit mask for SIM_UIDMH_UID. */ #define BS_SIM_UIDMH_UID (32U) /*!< Bit field size in bits for SIM_UIDMH_UID. */ /*! @brief Read current value of the SIM_UIDMH_UID field. */ #define BR_SIM_UIDMH_UID(x) (HW_SIM_UIDMH(x).U) /*@}*/ /******************************************************************************* * HW_SIM_UIDML - Unique Identification Register Mid Low ******************************************************************************/ /*! * @brief HW_SIM_UIDML - Unique Identification Register Mid Low (RO) * * Reset value: 0x00000000U */ typedef union _hw_sim_uidml { uint32_t U; struct _hw_sim_uidml_bitfields { uint32_t UID : 32; /*!< [31:0] Unique Identification */ } B; } hw_sim_uidml_t; /*! * @name Constants and macros for entire SIM_UIDML register */ /*@{*/ #define HW_SIM_UIDML_ADDR(x) ((x) + 0x105CU) #define HW_SIM_UIDML(x) (*(__I hw_sim_uidml_t *) HW_SIM_UIDML_ADDR(x)) #define HW_SIM_UIDML_RD(x) (HW_SIM_UIDML(x).U) /*@}*/ /* * Constants & macros for individual SIM_UIDML bitfields */ /*! * @name Register SIM_UIDML, field UID[31:0] (RO) * * Unique identification for the device. */ /*@{*/ #define BP_SIM_UIDML_UID (0U) /*!< Bit position for SIM_UIDML_UID. */ #define BM_SIM_UIDML_UID (0xFFFFFFFFU) /*!< Bit mask for SIM_UIDML_UID. */ #define BS_SIM_UIDML_UID (32U) /*!< Bit field size in bits for SIM_UIDML_UID. */ /*! @brief Read current value of the SIM_UIDML_UID field. */ #define BR_SIM_UIDML_UID(x) (HW_SIM_UIDML(x).U) /*@}*/ /******************************************************************************* * HW_SIM_UIDL - Unique Identification Register Low ******************************************************************************/ /*! * @brief HW_SIM_UIDL - Unique Identification Register Low (RO) * * Reset value: 0x00000000U */ typedef union _hw_sim_uidl { uint32_t U; struct _hw_sim_uidl_bitfields { uint32_t UID : 32; /*!< [31:0] Unique Identification */ } B; } hw_sim_uidl_t; /*! * @name Constants and macros for entire SIM_UIDL register */ /*@{*/ #define HW_SIM_UIDL_ADDR(x) ((x) + 0x1060U) #define HW_SIM_UIDL(x) (*(__I hw_sim_uidl_t *) HW_SIM_UIDL_ADDR(x)) #define HW_SIM_UIDL_RD(x) (HW_SIM_UIDL(x).U) /*@}*/ /* * Constants & macros for individual SIM_UIDL bitfields */ /*! * @name Register SIM_UIDL, field UID[31:0] (RO) * * Unique identification for the device. */ /*@{*/ #define BP_SIM_UIDL_UID (0U) /*!< Bit position for SIM_UIDL_UID. */ #define BM_SIM_UIDL_UID (0xFFFFFFFFU) /*!< Bit mask for SIM_UIDL_UID. */ #define BS_SIM_UIDL_UID (32U) /*!< Bit field size in bits for SIM_UIDL_UID. */ /*! @brief Read current value of the SIM_UIDL_UID field. */ #define BR_SIM_UIDL_UID(x) (HW_SIM_UIDL(x).U) /*@}*/ /******************************************************************************* * hw_sim_t - module struct ******************************************************************************/ /*! * @brief All SIM module registers. */ #pragma pack(1) typedef struct _hw_sim { __IO hw_sim_sopt1_t SOPT1; /*!< [0x0] System Options Register 1 */ __IO hw_sim_sopt1cfg_t SOPT1CFG; /*!< [0x4] SOPT1 Configuration Register */ uint8_t _reserved0[4092]; __IO hw_sim_sopt2_t SOPT2; /*!< [0x1004] System Options Register 2 */ uint8_t _reserved1[4]; __IO hw_sim_sopt4_t SOPT4; /*!< [0x100C] System Options Register 4 */ __IO hw_sim_sopt5_t SOPT5; /*!< [0x1010] System Options Register 5 */ uint8_t _reserved2[4]; __IO hw_sim_sopt7_t SOPT7; /*!< [0x1018] System Options Register 7 */ uint8_t _reserved3[8]; __I hw_sim_sdid_t SDID; /*!< [0x1024] System Device Identification Register */ __IO hw_sim_scgc1_t SCGC1; /*!< [0x1028] System Clock Gating Control Register 1 */ __IO hw_sim_scgc2_t SCGC2; /*!< [0x102C] System Clock Gating Control Register 2 */ __IO hw_sim_scgc3_t SCGC3; /*!< [0x1030] System Clock Gating Control Register 3 */ __IO hw_sim_scgc4_t SCGC4; /*!< [0x1034] System Clock Gating Control Register 4 */ __IO hw_sim_scgc5_t SCGC5; /*!< [0x1038] System Clock Gating Control Register 5 */ __IO hw_sim_scgc6_t SCGC6; /*!< [0x103C] System Clock Gating Control Register 6 */ __IO hw_sim_scgc7_t SCGC7; /*!< [0x1040] System Clock Gating Control Register 7 */ __IO hw_sim_clkdiv1_t CLKDIV1; /*!< [0x1044] System Clock Divider Register 1 */ __IO hw_sim_clkdiv2_t CLKDIV2; /*!< [0x1048] System Clock Divider Register 2 */ __IO hw_sim_fcfg1_t FCFG1; /*!< [0x104C] Flash Configuration Register 1 */ __I hw_sim_fcfg2_t FCFG2; /*!< [0x1050] Flash Configuration Register 2 */ __I hw_sim_uidh_t UIDH; /*!< [0x1054] Unique Identification Register High */ __I hw_sim_uidmh_t UIDMH; /*!< [0x1058] Unique Identification Register Mid-High */ __I hw_sim_uidml_t UIDML; /*!< [0x105C] Unique Identification Register Mid Low */ __I hw_sim_uidl_t UIDL; /*!< [0x1060] Unique Identification Register Low */ } hw_sim_t; #pragma pack() /*! @brief Macro to access all SIM registers. */ /*! @param x SIM module instance base address. */ /*! @return Reference (not a pointer) to the registers struct. To get a pointer to the struct, * use the '&' operator, like &HW_SIM(SIM_BASE). */ #define HW_SIM(x) (*(hw_sim_t *)(x)) #endif /* __HW_SIM_REGISTERS_H__ */ /* EOF */ ================================================ FILE: Zelig/mbed/TARGET_K64F/TARGET_Freescale/TARGET_KPSDK_MCUS/TARGET_MCU_K64F/device/device/MK64F12/MK64F12_smc.h ================================================ /* ** ################################################################### ** Compilers: Keil ARM C/C++ Compiler ** Freescale C/C++ for Embedded ARM ** GNU C Compiler ** IAR ANSI C/C++ Compiler for ARM ** ** Reference manual: K64P144M120SF5RM, Rev.2, January 2014 ** Version: rev. 2.5, 2014-02-10 ** Build: b140604 ** ** Abstract: ** Extension to the CMSIS register access layer header. ** ** Copyright (c) 2014 Freescale Semiconductor, Inc. ** All rights reserved. ** ** Redistribution and use in source and binary forms, with or without modification, ** are permitted provided that the following conditions are met: ** ** o Redistributions of source code must retain the above copyright notice, this list ** of conditions and the following disclaimer. ** ** o Redistributions in binary form must reproduce the above copyright notice, this ** list of conditions and the following disclaimer in the documentation and/or ** other materials provided with the distribution. ** ** o Neither the name of Freescale Semiconductor, Inc. nor the names of its ** contributors may be used to endorse or promote products derived from this ** software without specific prior written permission. ** ** THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ** ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED ** WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE ** DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT 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. ** ** http: www.freescale.com ** mail: support@freescale.com ** ** Revisions: ** - rev. 1.0 (2013-08-12) ** Initial version. ** - rev. 2.0 (2013-10-29) ** Register accessor macros added to the memory map. ** Symbols for Processor Expert memory map compatibility added to the memory map. ** Startup file for gcc has been updated according to CMSIS 3.2. ** System initialization updated. ** MCG - registers updated. ** PORTA, PORTB, PORTC, PORTE - registers for digital filter removed. ** - rev. 2.1 (2013-10-30) ** Definition of BITBAND macros updated to support peripherals with 32-bit acces disabled. ** - rev. 2.2 (2013-12-09) ** DMA - EARS register removed. ** AIPS0, AIPS1 - MPRA register updated. ** - rev. 2.3 (2014-01-24) ** Update according to reference manual rev. 2 ** ENET, MCG, MCM, SIM, USB - registers updated ** - rev. 2.4 (2014-02-10) ** The declaration of clock configurations has been moved to separate header file system_MK64F12.h ** Update of SystemInit() and SystemCoreClockUpdate() functions. ** - rev. 2.5 (2014-02-10) ** The declaration of clock configurations has been moved to separate header file system_MK64F12.h ** Update of SystemInit() and SystemCoreClockUpdate() functions. ** Module access macro module_BASES replaced by module_BASE_PTRS. ** ** ################################################################### */ /* * WARNING! DO NOT EDIT THIS FILE DIRECTLY! * * This file was generated automatically and any changes may be lost. */ #ifndef __HW_SMC_REGISTERS_H__ #define __HW_SMC_REGISTERS_H__ #include "MK64F12.h" #include "fsl_bitaccess.h" /* * MK64F12 SMC * * System Mode Controller * * Registers defined in this header file: * - HW_SMC_PMPROT - Power Mode Protection register * - HW_SMC_PMCTRL - Power Mode Control register * - HW_SMC_VLLSCTRL - VLLS Control register * - HW_SMC_PMSTAT - Power Mode Status register * * - hw_smc_t - Struct containing all module registers. */ #define HW_SMC_INSTANCE_COUNT (1U) /*!< Number of instances of the SMC module. */ /******************************************************************************* * HW_SMC_PMPROT - Power Mode Protection register ******************************************************************************/ /*! * @brief HW_SMC_PMPROT - Power Mode Protection register (RW) * * Reset value: 0x00U * * This register provides protection for entry into any low-power run or stop * mode. The enabling of the low-power run or stop mode occurs by configuring the * Power Mode Control register (PMCTRL). The PMPROT register can be written only * once after any system reset. If the MCU is configured for a disallowed or * reserved power mode, the MCU remains in its current power mode. For example, if the * MCU is in normal RUN mode and AVLP is 0, an attempt to enter VLPR mode using * PMCTRL[RUNM] is blocked and PMCTRL[RUNM] remains 00b, indicating the MCU is * still in Normal Run mode. This register is reset on Chip Reset not VLLS and by * reset types that trigger Chip Reset not VLLS. It is unaffected by reset types * that do not trigger Chip Reset not VLLS. See the Reset section details for more * information. */ typedef union _hw_smc_pmprot { uint8_t U; struct _hw_smc_pmprot_bitfields { uint8_t RESERVED0 : 1; /*!< [0] */ uint8_t AVLLS : 1; /*!< [1] Allow Very-Low-Leakage Stop Mode */ uint8_t RESERVED1 : 1; /*!< [2] */ uint8_t ALLS : 1; /*!< [3] Allow Low-Leakage Stop Mode */ uint8_t RESERVED2 : 1; /*!< [4] */ uint8_t AVLP : 1; /*!< [5] Allow Very-Low-Power Modes */ uint8_t RESERVED3 : 2; /*!< [7:6] */ } B; } hw_smc_pmprot_t; /*! * @name Constants and macros for entire SMC_PMPROT register */ /*@{*/ #define HW_SMC_PMPROT_ADDR(x) ((x) + 0x0U) #define HW_SMC_PMPROT(x) (*(__IO hw_smc_pmprot_t *) HW_SMC_PMPROT_ADDR(x)) #define HW_SMC_PMPROT_RD(x) (HW_SMC_PMPROT(x).U) #define HW_SMC_PMPROT_WR(x, v) (HW_SMC_PMPROT(x).U = (v)) #define HW_SMC_PMPROT_SET(x, v) (HW_SMC_PMPROT_WR(x, HW_SMC_PMPROT_RD(x) | (v))) #define HW_SMC_PMPROT_CLR(x, v) (HW_SMC_PMPROT_WR(x, HW_SMC_PMPROT_RD(x) & ~(v))) #define HW_SMC_PMPROT_TOG(x, v) (HW_SMC_PMPROT_WR(x, HW_SMC_PMPROT_RD(x) ^ (v))) /*@}*/ /* * Constants & macros for individual SMC_PMPROT bitfields */ /*! * @name Register SMC_PMPROT, field AVLLS[1] (RW) * * Provided the appropriate control bits are set up in PMCTRL, this write once * bit allows the MCU to enter any very-low-leakage stop mode (VLLSx). * * Values: * - 0 - Any VLLSx mode is not allowed * - 1 - Any VLLSx mode is allowed */ /*@{*/ #define BP_SMC_PMPROT_AVLLS (1U) /*!< Bit position for SMC_PMPROT_AVLLS. */ #define BM_SMC_PMPROT_AVLLS (0x02U) /*!< Bit mask for SMC_PMPROT_AVLLS. */ #define BS_SMC_PMPROT_AVLLS (1U) /*!< Bit field size in bits for SMC_PMPROT_AVLLS. */ /*! @brief Read current value of the SMC_PMPROT_AVLLS field. */ #define BR_SMC_PMPROT_AVLLS(x) (BITBAND_ACCESS8(HW_SMC_PMPROT_ADDR(x), BP_SMC_PMPROT_AVLLS)) /*! @brief Format value for bitfield SMC_PMPROT_AVLLS. */ #define BF_SMC_PMPROT_AVLLS(v) ((uint8_t)((uint8_t)(v) << BP_SMC_PMPROT_AVLLS) & BM_SMC_PMPROT_AVLLS) /*! @brief Set the AVLLS field to a new value. */ #define BW_SMC_PMPROT_AVLLS(x, v) (BITBAND_ACCESS8(HW_SMC_PMPROT_ADDR(x), BP_SMC_PMPROT_AVLLS) = (v)) /*@}*/ /*! * @name Register SMC_PMPROT, field ALLS[3] (RW) * * Provided the appropriate control bits are set up in PMCTRL, this write-once * field allows the MCU to enter any low-leakage stop mode (LLS). * * Values: * - 0 - LLS is not allowed * - 1 - LLS is allowed */ /*@{*/ #define BP_SMC_PMPROT_ALLS (3U) /*!< Bit position for SMC_PMPROT_ALLS. */ #define BM_SMC_PMPROT_ALLS (0x08U) /*!< Bit mask for SMC_PMPROT_ALLS. */ #define BS_SMC_PMPROT_ALLS (1U) /*!< Bit field size in bits for SMC_PMPROT_ALLS. */ /*! @brief Read current value of the SMC_PMPROT_ALLS field. */ #define BR_SMC_PMPROT_ALLS(x) (BITBAND_ACCESS8(HW_SMC_PMPROT_ADDR(x), BP_SMC_PMPROT_ALLS)) /*! @brief Format value for bitfield SMC_PMPROT_ALLS. */ #define BF_SMC_PMPROT_ALLS(v) ((uint8_t)((uint8_t)(v) << BP_SMC_PMPROT_ALLS) & BM_SMC_PMPROT_ALLS) /*! @brief Set the ALLS field to a new value. */ #define BW_SMC_PMPROT_ALLS(x, v) (BITBAND_ACCESS8(HW_SMC_PMPROT_ADDR(x), BP_SMC_PMPROT_ALLS) = (v)) /*@}*/ /*! * @name Register SMC_PMPROT, field AVLP[5] (RW) * * Provided the appropriate control bits are set up in PMCTRL, this write-once * field allows the MCU to enter any very-low-power mode (VLPR, VLPW, and VLPS). * * Values: * - 0 - VLPR, VLPW, and VLPS are not allowed. * - 1 - VLPR, VLPW, and VLPS are allowed. */ /*@{*/ #define BP_SMC_PMPROT_AVLP (5U) /*!< Bit position for SMC_PMPROT_AVLP. */ #define BM_SMC_PMPROT_AVLP (0x20U) /*!< Bit mask for SMC_PMPROT_AVLP. */ #define BS_SMC_PMPROT_AVLP (1U) /*!< Bit field size in bits for SMC_PMPROT_AVLP. */ /*! @brief Read current value of the SMC_PMPROT_AVLP field. */ #define BR_SMC_PMPROT_AVLP(x) (BITBAND_ACCESS8(HW_SMC_PMPROT_ADDR(x), BP_SMC_PMPROT_AVLP)) /*! @brief Format value for bitfield SMC_PMPROT_AVLP. */ #define BF_SMC_PMPROT_AVLP(v) ((uint8_t)((uint8_t)(v) << BP_SMC_PMPROT_AVLP) & BM_SMC_PMPROT_AVLP) /*! @brief Set the AVLP field to a new value. */ #define BW_SMC_PMPROT_AVLP(x, v) (BITBAND_ACCESS8(HW_SMC_PMPROT_ADDR(x), BP_SMC_PMPROT_AVLP) = (v)) /*@}*/ /******************************************************************************* * HW_SMC_PMCTRL - Power Mode Control register ******************************************************************************/ /*! * @brief HW_SMC_PMCTRL - Power Mode Control register (RW) * * Reset value: 0x00U * * The PMCTRL register controls entry into low-power Run and Stop modes, * provided that the selected power mode is allowed via an appropriate setting of the * protection (PMPROT) register. This register is reset on Chip POR not VLLS and by * reset types that trigger Chip POR not VLLS. It is unaffected by reset types * that do not trigger Chip POR not VLLS. See the Reset section details for more * information. */ typedef union _hw_smc_pmctrl { uint8_t U; struct _hw_smc_pmctrl_bitfields { uint8_t STOPM : 3; /*!< [2:0] Stop Mode Control */ uint8_t STOPA : 1; /*!< [3] Stop Aborted */ uint8_t RESERVED0 : 1; /*!< [4] */ uint8_t RUNM : 2; /*!< [6:5] Run Mode Control */ uint8_t LPWUI : 1; /*!< [7] Low-Power Wake Up On Interrupt */ } B; } hw_smc_pmctrl_t; /*! * @name Constants and macros for entire SMC_PMCTRL register */ /*@{*/ #define HW_SMC_PMCTRL_ADDR(x) ((x) + 0x1U) #define HW_SMC_PMCTRL(x) (*(__IO hw_smc_pmctrl_t *) HW_SMC_PMCTRL_ADDR(x)) #define HW_SMC_PMCTRL_RD(x) (HW_SMC_PMCTRL(x).U) #define HW_SMC_PMCTRL_WR(x, v) (HW_SMC_PMCTRL(x).U = (v)) #define HW_SMC_PMCTRL_SET(x, v) (HW_SMC_PMCTRL_WR(x, HW_SMC_PMCTRL_RD(x) | (v))) #define HW_SMC_PMCTRL_CLR(x, v) (HW_SMC_PMCTRL_WR(x, HW_SMC_PMCTRL_RD(x) & ~(v))) #define HW_SMC_PMCTRL_TOG(x, v) (HW_SMC_PMCTRL_WR(x, HW_SMC_PMCTRL_RD(x) ^ (v))) /*@}*/ /* * Constants & macros for individual SMC_PMCTRL bitfields */ /*! * @name Register SMC_PMCTRL, field STOPM[2:0] (RW) * * When written, controls entry into the selected stop mode when Sleep-Now or * Sleep-On-Exit mode is entered with SLEEPDEEP=1 . Writes to this field are * blocked if the protection level has not been enabled using the PMPROT register. * After any system reset, this field is cleared by hardware on any successful write * to the PMPROT register. When set to VLLSx, the VLLSM field in the VLLSCTRL * register is used to further select the particular VLLS submode which will be * entered. * * Values: * - 000 - Normal Stop (STOP) * - 001 - Reserved * - 010 - Very-Low-Power Stop (VLPS) * - 011 - Low-Leakage Stop (LLS) * - 100 - Very-Low-Leakage Stop (VLLSx) * - 101 - Reserved * - 110 - Reseved * - 111 - Reserved */ /*@{*/ #define BP_SMC_PMCTRL_STOPM (0U) /*!< Bit position for SMC_PMCTRL_STOPM. */ #define BM_SMC_PMCTRL_STOPM (0x07U) /*!< Bit mask for SMC_PMCTRL_STOPM. */ #define BS_SMC_PMCTRL_STOPM (3U) /*!< Bit field size in bits for SMC_PMCTRL_STOPM. */ /*! @brief Read current value of the SMC_PMCTRL_STOPM field. */ #define BR_SMC_PMCTRL_STOPM(x) (HW_SMC_PMCTRL(x).B.STOPM) /*! @brief Format value for bitfield SMC_PMCTRL_STOPM. */ #define BF_SMC_PMCTRL_STOPM(v) ((uint8_t)((uint8_t)(v) << BP_SMC_PMCTRL_STOPM) & BM_SMC_PMCTRL_STOPM) /*! @brief Set the STOPM field to a new value. */ #define BW_SMC_PMCTRL_STOPM(x, v) (HW_SMC_PMCTRL_WR(x, (HW_SMC_PMCTRL_RD(x) & ~BM_SMC_PMCTRL_STOPM) | BF_SMC_PMCTRL_STOPM(v))) /*@}*/ /*! * @name Register SMC_PMCTRL, field STOPA[3] (RO) * * When set, this read-only status bit indicates an interrupt or reset occured * during the previous stop mode entry sequence, preventing the system from * entering that mode. This field is cleared by hardware at the beginning of any stop * mode entry sequence and is set if the sequence was aborted. * * Values: * - 0 - The previous stop mode entry was successsful. * - 1 - The previous stop mode entry was aborted. */ /*@{*/ #define BP_SMC_PMCTRL_STOPA (3U) /*!< Bit position for SMC_PMCTRL_STOPA. */ #define BM_SMC_PMCTRL_STOPA (0x08U) /*!< Bit mask for SMC_PMCTRL_STOPA. */ #define BS_SMC_PMCTRL_STOPA (1U) /*!< Bit field size in bits for SMC_PMCTRL_STOPA. */ /*! @brief Read current value of the SMC_PMCTRL_STOPA field. */ #define BR_SMC_PMCTRL_STOPA(x) (BITBAND_ACCESS8(HW_SMC_PMCTRL_ADDR(x), BP_SMC_PMCTRL_STOPA)) /*@}*/ /*! * @name Register SMC_PMCTRL, field RUNM[6:5] (RW) * * When written, causes entry into the selected run mode. Writes to this field * are blocked if the protection level has not been enabled using the PMPROT * register. RUNM may be set to VLPR only when PMSTAT=RUN. After being written to * VLPR, RUNM should not be written back to RUN until PMSTAT=VLPR. * * Values: * - 00 - Normal Run mode (RUN) * - 01 - Reserved * - 10 - Very-Low-Power Run mode (VLPR) * - 11 - Reserved */ /*@{*/ #define BP_SMC_PMCTRL_RUNM (5U) /*!< Bit position for SMC_PMCTRL_RUNM. */ #define BM_SMC_PMCTRL_RUNM (0x60U) /*!< Bit mask for SMC_PMCTRL_RUNM. */ #define BS_SMC_PMCTRL_RUNM (2U) /*!< Bit field size in bits for SMC_PMCTRL_RUNM. */ /*! @brief Read current value of the SMC_PMCTRL_RUNM field. */ #define BR_SMC_PMCTRL_RUNM(x) (HW_SMC_PMCTRL(x).B.RUNM) /*! @brief Format value for bitfield SMC_PMCTRL_RUNM. */ #define BF_SMC_PMCTRL_RUNM(v) ((uint8_t)((uint8_t)(v) << BP_SMC_PMCTRL_RUNM) & BM_SMC_PMCTRL_RUNM) /*! @brief Set the RUNM field to a new value. */ #define BW_SMC_PMCTRL_RUNM(x, v) (HW_SMC_PMCTRL_WR(x, (HW_SMC_PMCTRL_RD(x) & ~BM_SMC_PMCTRL_RUNM) | BF_SMC_PMCTRL_RUNM(v))) /*@}*/ /*! * @name Register SMC_PMCTRL, field LPWUI[7] (RW) * * Causes the SMC to exit to normal RUN mode when any active MCU interrupt * occurs while in a VLP mode (VLPR, VLPW or VLPS). If VLPS mode was entered directly * from RUN mode, the SMC will always exit back to normal RUN mode regardless of * the LPWUI setting. LPWUI must be modified only while the system is in RUN * mode, that is, when PMSTAT=RUN. * * Values: * - 0 - The system remains in a VLP mode on an interrupt * - 1 - The system exits to Normal RUN mode on an interrupt */ /*@{*/ #define BP_SMC_PMCTRL_LPWUI (7U) /*!< Bit position for SMC_PMCTRL_LPWUI. */ #define BM_SMC_PMCTRL_LPWUI (0x80U) /*!< Bit mask for SMC_PMCTRL_LPWUI. */ #define BS_SMC_PMCTRL_LPWUI (1U) /*!< Bit field size in bits for SMC_PMCTRL_LPWUI. */ /*! @brief Read current value of the SMC_PMCTRL_LPWUI field. */ #define BR_SMC_PMCTRL_LPWUI(x) (BITBAND_ACCESS8(HW_SMC_PMCTRL_ADDR(x), BP_SMC_PMCTRL_LPWUI)) /*! @brief Format value for bitfield SMC_PMCTRL_LPWUI. */ #define BF_SMC_PMCTRL_LPWUI(v) ((uint8_t)((uint8_t)(v) << BP_SMC_PMCTRL_LPWUI) & BM_SMC_PMCTRL_LPWUI) /*! @brief Set the LPWUI field to a new value. */ #define BW_SMC_PMCTRL_LPWUI(x, v) (BITBAND_ACCESS8(HW_SMC_PMCTRL_ADDR(x), BP_SMC_PMCTRL_LPWUI) = (v)) /*@}*/ /******************************************************************************* * HW_SMC_VLLSCTRL - VLLS Control register ******************************************************************************/ /*! * @brief HW_SMC_VLLSCTRL - VLLS Control register (RW) * * Reset value: 0x03U * * The VLLSCTRL register controls features related to VLLS modes. This register * is reset on Chip POR not VLLS and by reset types that trigger Chip POR not * VLLS. It is unaffected by reset types that do not trigger Chip POR not VLLS. See * the Reset section details for more information. */ typedef union _hw_smc_vllsctrl { uint8_t U; struct _hw_smc_vllsctrl_bitfields { uint8_t VLLSM : 3; /*!< [2:0] VLLS Mode Control */ uint8_t RESERVED0 : 2; /*!< [4:3] */ uint8_t PORPO : 1; /*!< [5] POR Power Option */ uint8_t RESERVED1 : 2; /*!< [7:6] */ } B; } hw_smc_vllsctrl_t; /*! * @name Constants and macros for entire SMC_VLLSCTRL register */ /*@{*/ #define HW_SMC_VLLSCTRL_ADDR(x) ((x) + 0x2U) #define HW_SMC_VLLSCTRL(x) (*(__IO hw_smc_vllsctrl_t *) HW_SMC_VLLSCTRL_ADDR(x)) #define HW_SMC_VLLSCTRL_RD(x) (HW_SMC_VLLSCTRL(x).U) #define HW_SMC_VLLSCTRL_WR(x, v) (HW_SMC_VLLSCTRL(x).U = (v)) #define HW_SMC_VLLSCTRL_SET(x, v) (HW_SMC_VLLSCTRL_WR(x, HW_SMC_VLLSCTRL_RD(x) | (v))) #define HW_SMC_VLLSCTRL_CLR(x, v) (HW_SMC_VLLSCTRL_WR(x, HW_SMC_VLLSCTRL_RD(x) & ~(v))) #define HW_SMC_VLLSCTRL_TOG(x, v) (HW_SMC_VLLSCTRL_WR(x, HW_SMC_VLLSCTRL_RD(x) ^ (v))) /*@}*/ /* * Constants & macros for individual SMC_VLLSCTRL bitfields */ /*! * @name Register SMC_VLLSCTRL, field VLLSM[2:0] (RW) * * Controls which VLLS sub-mode to enter if STOPM=VLLS. * * Values: * - 000 - VLLS0 * - 001 - VLLS1 * - 010 - VLLS2 * - 011 - VLLS3 * - 100 - Reserved * - 101 - Reserved * - 110 - Reserved * - 111 - Reserved */ /*@{*/ #define BP_SMC_VLLSCTRL_VLLSM (0U) /*!< Bit position for SMC_VLLSCTRL_VLLSM. */ #define BM_SMC_VLLSCTRL_VLLSM (0x07U) /*!< Bit mask for SMC_VLLSCTRL_VLLSM. */ #define BS_SMC_VLLSCTRL_VLLSM (3U) /*!< Bit field size in bits for SMC_VLLSCTRL_VLLSM. */ /*! @brief Read current value of the SMC_VLLSCTRL_VLLSM field. */ #define BR_SMC_VLLSCTRL_VLLSM(x) (HW_SMC_VLLSCTRL(x).B.VLLSM) /*! @brief Format value for bitfield SMC_VLLSCTRL_VLLSM. */ #define BF_SMC_VLLSCTRL_VLLSM(v) ((uint8_t)((uint8_t)(v) << BP_SMC_VLLSCTRL_VLLSM) & BM_SMC_VLLSCTRL_VLLSM) /*! @brief Set the VLLSM field to a new value. */ #define BW_SMC_VLLSCTRL_VLLSM(x, v) (HW_SMC_VLLSCTRL_WR(x, (HW_SMC_VLLSCTRL_RD(x) & ~BM_SMC_VLLSCTRL_VLLSM) | BF_SMC_VLLSCTRL_VLLSM(v))) /*@}*/ /*! * @name Register SMC_VLLSCTRL, field PORPO[5] (RW) * * Controls whether the POR detect circuit (for brown-out detection) is enabled * in VLLS0 mode. * * Values: * - 0 - POR detect circuit is enabled in VLLS0. * - 1 - POR detect circuit is disabled in VLLS0. */ /*@{*/ #define BP_SMC_VLLSCTRL_PORPO (5U) /*!< Bit position for SMC_VLLSCTRL_PORPO. */ #define BM_SMC_VLLSCTRL_PORPO (0x20U) /*!< Bit mask for SMC_VLLSCTRL_PORPO. */ #define BS_SMC_VLLSCTRL_PORPO (1U) /*!< Bit field size in bits for SMC_VLLSCTRL_PORPO. */ /*! @brief Read current value of the SMC_VLLSCTRL_PORPO field. */ #define BR_SMC_VLLSCTRL_PORPO(x) (BITBAND_ACCESS8(HW_SMC_VLLSCTRL_ADDR(x), BP_SMC_VLLSCTRL_PORPO)) /*! @brief Format value for bitfield SMC_VLLSCTRL_PORPO. */ #define BF_SMC_VLLSCTRL_PORPO(v) ((uint8_t)((uint8_t)(v) << BP_SMC_VLLSCTRL_PORPO) & BM_SMC_VLLSCTRL_PORPO) /*! @brief Set the PORPO field to a new value. */ #define BW_SMC_VLLSCTRL_PORPO(x, v) (BITBAND_ACCESS8(HW_SMC_VLLSCTRL_ADDR(x), BP_SMC_VLLSCTRL_PORPO) = (v)) /*@}*/ /******************************************************************************* * HW_SMC_PMSTAT - Power Mode Status register ******************************************************************************/ /*! * @brief HW_SMC_PMSTAT - Power Mode Status register (RO) * * Reset value: 0x01U * * PMSTAT is a read-only, one-hot register which indicates the current power * mode of the system. This register is reset on Chip POR not VLLS and by reset * types that trigger Chip POR not VLLS. It is unaffected by reset types that do not * trigger Chip POR not VLLS. See the Reset section details for more information. */ typedef union _hw_smc_pmstat { uint8_t U; struct _hw_smc_pmstat_bitfields { uint8_t PMSTAT : 7; /*!< [6:0] */ uint8_t RESERVED0 : 1; /*!< [7] */ } B; } hw_smc_pmstat_t; /*! * @name Constants and macros for entire SMC_PMSTAT register */ /*@{*/ #define HW_SMC_PMSTAT_ADDR(x) ((x) + 0x3U) #define HW_SMC_PMSTAT(x) (*(__I hw_smc_pmstat_t *) HW_SMC_PMSTAT_ADDR(x)) #define HW_SMC_PMSTAT_RD(x) (HW_SMC_PMSTAT(x).U) /*@}*/ /* * Constants & macros for individual SMC_PMSTAT bitfields */ /*! * @name Register SMC_PMSTAT, field PMSTAT[6:0] (RO) * * When debug is enabled, the PMSTAT will not update to STOP or VLPS */ /*@{*/ #define BP_SMC_PMSTAT_PMSTAT (0U) /*!< Bit position for SMC_PMSTAT_PMSTAT. */ #define BM_SMC_PMSTAT_PMSTAT (0x7FU) /*!< Bit mask for SMC_PMSTAT_PMSTAT. */ #define BS_SMC_PMSTAT_PMSTAT (7U) /*!< Bit field size in bits for SMC_PMSTAT_PMSTAT. */ /*! @brief Read current value of the SMC_PMSTAT_PMSTAT field. */ #define BR_SMC_PMSTAT_PMSTAT(x) (HW_SMC_PMSTAT(x).B.PMSTAT) /*@}*/ /******************************************************************************* * hw_smc_t - module struct ******************************************************************************/ /*! * @brief All SMC module registers. */ #pragma pack(1) typedef struct _hw_smc { __IO hw_smc_pmprot_t PMPROT; /*!< [0x0] Power Mode Protection register */ __IO hw_smc_pmctrl_t PMCTRL; /*!< [0x1] Power Mode Control register */ __IO hw_smc_vllsctrl_t VLLSCTRL; /*!< [0x2] VLLS Control register */ __I hw_smc_pmstat_t PMSTAT; /*!< [0x3] Power Mode Status register */ } hw_smc_t; #pragma pack() /*! @brief Macro to access all SMC registers. */ /*! @param x SMC module instance base address. */ /*! @return Reference (not a pointer) to the registers struct. To get a pointer to the struct, * use the '&' operator, like &HW_SMC(SMC_BASE). */ #define HW_SMC(x) (*(hw_smc_t *)(x)) #endif /* __HW_SMC_REGISTERS_H__ */ /* EOF */ ================================================ FILE: Zelig/mbed/TARGET_K64F/TARGET_Freescale/TARGET_KPSDK_MCUS/TARGET_MCU_K64F/device/device/MK64F12/MK64F12_spi.h ================================================ /* ** ################################################################### ** Compilers: Keil ARM C/C++ Compiler ** Freescale C/C++ for Embedded ARM ** GNU C Compiler ** IAR ANSI C/C++ Compiler for ARM ** ** Reference manual: K64P144M120SF5RM, Rev.2, January 2014 ** Version: rev. 2.5, 2014-02-10 ** Build: b140604 ** ** Abstract: ** Extension to the CMSIS register access layer header. ** ** Copyright (c) 2014 Freescale Semiconductor, Inc. ** All rights reserved. ** ** Redistribution and use in source and binary forms, with or without modification, ** are permitted provided that the following conditions are met: ** ** o Redistributions of source code must retain the above copyright notice, this list ** of conditions and the following disclaimer. ** ** o Redistributions in binary form must reproduce the above copyright notice, this ** list of conditions and the following disclaimer in the documentation and/or ** other materials provided with the distribution. ** ** o Neither the name of Freescale Semiconductor, Inc. nor the names of its ** contributors may be used to endorse or promote products derived from this ** software without specific prior written permission. ** ** THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ** ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED ** WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE ** DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT 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. ** ** http: www.freescale.com ** mail: support@freescale.com ** ** Revisions: ** - rev. 1.0 (2013-08-12) ** Initial version. ** - rev. 2.0 (2013-10-29) ** Register accessor macros added to the memory map. ** Symbols for Processor Expert memory map compatibility added to the memory map. ** Startup file for gcc has been updated according to CMSIS 3.2. ** System initialization updated. ** MCG - registers updated. ** PORTA, PORTB, PORTC, PORTE - registers for digital filter removed. ** - rev. 2.1 (2013-10-30) ** Definition of BITBAND macros updated to support peripherals with 32-bit acces disabled. ** - rev. 2.2 (2013-12-09) ** DMA - EARS register removed. ** AIPS0, AIPS1 - MPRA register updated. ** - rev. 2.3 (2014-01-24) ** Update according to reference manual rev. 2 ** ENET, MCG, MCM, SIM, USB - registers updated ** - rev. 2.4 (2014-02-10) ** The declaration of clock configurations has been moved to separate header file system_MK64F12.h ** Update of SystemInit() and SystemCoreClockUpdate() functions. ** - rev. 2.5 (2014-02-10) ** The declaration of clock configurations has been moved to separate header file system_MK64F12.h ** Update of SystemInit() and SystemCoreClockUpdate() functions. ** Module access macro module_BASES replaced by module_BASE_PTRS. ** ** ################################################################### */ /* * WARNING! DO NOT EDIT THIS FILE DIRECTLY! * * This file was generated automatically and any changes may be lost. */ #ifndef __HW_SPI_REGISTERS_H__ #define __HW_SPI_REGISTERS_H__ #include "MK64F12.h" #include "fsl_bitaccess.h" /* * MK64F12 SPI * * Serial Peripheral Interface * * Registers defined in this header file: * - HW_SPI_MCR - Module Configuration Register * - HW_SPI_TCR - Transfer Count Register * - HW_SPI_CTARn - Clock and Transfer Attributes Register (In Master Mode) * - HW_SPI_CTARn_SLAVE - Clock and Transfer Attributes Register (In Slave Mode) * - HW_SPI_SR - Status Register * - HW_SPI_RSER - DMA/Interrupt Request Select and Enable Register * - HW_SPI_PUSHR - PUSH TX FIFO Register In Master Mode * - HW_SPI_PUSHR_SLAVE - PUSH TX FIFO Register In Slave Mode * - HW_SPI_POPR - POP RX FIFO Register * - HW_SPI_TXFRn - Transmit FIFO Registers * - HW_SPI_RXFRn - Receive FIFO Registers * * - hw_spi_t - Struct containing all module registers. */ #define HW_SPI_INSTANCE_COUNT (3U) /*!< Number of instances of the SPI module. */ #define HW_SPI0 (0U) /*!< Instance number for SPI0. */ #define HW_SPI1 (1U) /*!< Instance number for SPI1. */ #define HW_SPI2 (2U) /*!< Instance number for SPI2. */ /******************************************************************************* * HW_SPI_MCR - Module Configuration Register ******************************************************************************/ /*! * @brief HW_SPI_MCR - Module Configuration Register (RW) * * Reset value: 0x00004001U * * Contains bits to configure various attributes associated with the module * operations. The HALT and MDIS bits can be changed at any time, but the effect * takes place only on the next frame boundary. Only the HALT and MDIS bits in the * MCR can be changed, while the module is in the Running state. */ typedef union _hw_spi_mcr { uint32_t U; struct _hw_spi_mcr_bitfields { uint32_t HALT : 1; /*!< [0] Halt */ uint32_t RESERVED0 : 7; /*!< [7:1] */ uint32_t SMPL_PT : 2; /*!< [9:8] Sample Point */ uint32_t CLR_RXF : 1; /*!< [10] */ uint32_t CLR_TXF : 1; /*!< [11] Clear TX FIFO */ uint32_t DIS_RXF : 1; /*!< [12] Disable Receive FIFO */ uint32_t DIS_TXF : 1; /*!< [13] Disable Transmit FIFO */ uint32_t MDIS : 1; /*!< [14] Module Disable */ uint32_t DOZE : 1; /*!< [15] Doze Enable */ uint32_t PCSIS : 6; /*!< [21:16] Peripheral Chip Select x Inactive * State */ uint32_t RESERVED1 : 2; /*!< [23:22] */ uint32_t ROOE : 1; /*!< [24] Receive FIFO Overflow Overwrite Enable */ uint32_t PCSSE : 1; /*!< [25] Peripheral Chip Select Strobe Enable */ uint32_t MTFE : 1; /*!< [26] Modified Timing Format Enable */ uint32_t FRZ : 1; /*!< [27] Freeze */ uint32_t DCONF : 2; /*!< [29:28] SPI Configuration. */ uint32_t CONT_SCKE : 1; /*!< [30] Continuous SCK Enable */ uint32_t MSTR : 1; /*!< [31] Master/Slave Mode Select */ } B; } hw_spi_mcr_t; /*! * @name Constants and macros for entire SPI_MCR register */ /*@{*/ #define HW_SPI_MCR_ADDR(x) ((x) + 0x0U) #define HW_SPI_MCR(x) (*(__IO hw_spi_mcr_t *) HW_SPI_MCR_ADDR(x)) #define HW_SPI_MCR_RD(x) (HW_SPI_MCR(x).U) #define HW_SPI_MCR_WR(x, v) (HW_SPI_MCR(x).U = (v)) #define HW_SPI_MCR_SET(x, v) (HW_SPI_MCR_WR(x, HW_SPI_MCR_RD(x) | (v))) #define HW_SPI_MCR_CLR(x, v) (HW_SPI_MCR_WR(x, HW_SPI_MCR_RD(x) & ~(v))) #define HW_SPI_MCR_TOG(x, v) (HW_SPI_MCR_WR(x, HW_SPI_MCR_RD(x) ^ (v))) /*@}*/ /* * Constants & macros for individual SPI_MCR bitfields */ /*! * @name Register SPI_MCR, field HALT[0] (RW) * * The HALT bit starts and stops frame transfers. See Start and Stop of Module * transfers * * Values: * - 0 - Start transfers. * - 1 - Stop transfers. */ /*@{*/ #define BP_SPI_MCR_HALT (0U) /*!< Bit position for SPI_MCR_HALT. */ #define BM_SPI_MCR_HALT (0x00000001U) /*!< Bit mask for SPI_MCR_HALT. */ #define BS_SPI_MCR_HALT (1U) /*!< Bit field size in bits for SPI_MCR_HALT. */ /*! @brief Read current value of the SPI_MCR_HALT field. */ #define BR_SPI_MCR_HALT(x) (BITBAND_ACCESS32(HW_SPI_MCR_ADDR(x), BP_SPI_MCR_HALT)) /*! @brief Format value for bitfield SPI_MCR_HALT. */ #define BF_SPI_MCR_HALT(v) ((uint32_t)((uint32_t)(v) << BP_SPI_MCR_HALT) & BM_SPI_MCR_HALT) /*! @brief Set the HALT field to a new value. */ #define BW_SPI_MCR_HALT(x, v) (BITBAND_ACCESS32(HW_SPI_MCR_ADDR(x), BP_SPI_MCR_HALT) = (v)) /*@}*/ /*! * @name Register SPI_MCR, field SMPL_PT[9:8] (RW) * * Controls when the module master samples SIN in Modified Transfer Format. This * field is valid only when CPHA bit in CTARn[CPHA] is 0. * * Values: * - 00 - 0 protocol clock cycles between SCK edge and SIN sample * - 01 - 1 protocol clock cycle between SCK edge and SIN sample * - 10 - 2 protocol clock cycles between SCK edge and SIN sample * - 11 - Reserved */ /*@{*/ #define BP_SPI_MCR_SMPL_PT (8U) /*!< Bit position for SPI_MCR_SMPL_PT. */ #define BM_SPI_MCR_SMPL_PT (0x00000300U) /*!< Bit mask for SPI_MCR_SMPL_PT. */ #define BS_SPI_MCR_SMPL_PT (2U) /*!< Bit field size in bits for SPI_MCR_SMPL_PT. */ /*! @brief Read current value of the SPI_MCR_SMPL_PT field. */ #define BR_SPI_MCR_SMPL_PT(x) (HW_SPI_MCR(x).B.SMPL_PT) /*! @brief Format value for bitfield SPI_MCR_SMPL_PT. */ #define BF_SPI_MCR_SMPL_PT(v) ((uint32_t)((uint32_t)(v) << BP_SPI_MCR_SMPL_PT) & BM_SPI_MCR_SMPL_PT) /*! @brief Set the SMPL_PT field to a new value. */ #define BW_SPI_MCR_SMPL_PT(x, v) (HW_SPI_MCR_WR(x, (HW_SPI_MCR_RD(x) & ~BM_SPI_MCR_SMPL_PT) | BF_SPI_MCR_SMPL_PT(v))) /*@}*/ /*! * @name Register SPI_MCR, field CLR_RXF[10] (WORZ) * * Flushes the RX FIFO. Writing a 1 to CLR_RXF clears the RX Counter. The * CLR_RXF bit is always read as zero. * * Values: * - 0 - Do not clear the RX FIFO counter. * - 1 - Clear the RX FIFO counter. */ /*@{*/ #define BP_SPI_MCR_CLR_RXF (10U) /*!< Bit position for SPI_MCR_CLR_RXF. */ #define BM_SPI_MCR_CLR_RXF (0x00000400U) /*!< Bit mask for SPI_MCR_CLR_RXF. */ #define BS_SPI_MCR_CLR_RXF (1U) /*!< Bit field size in bits for SPI_MCR_CLR_RXF. */ /*! @brief Format value for bitfield SPI_MCR_CLR_RXF. */ #define BF_SPI_MCR_CLR_RXF(v) ((uint32_t)((uint32_t)(v) << BP_SPI_MCR_CLR_RXF) & BM_SPI_MCR_CLR_RXF) /*! @brief Set the CLR_RXF field to a new value. */ #define BW_SPI_MCR_CLR_RXF(x, v) (BITBAND_ACCESS32(HW_SPI_MCR_ADDR(x), BP_SPI_MCR_CLR_RXF) = (v)) /*@}*/ /*! * @name Register SPI_MCR, field CLR_TXF[11] (WORZ) * * Flushes the TX FIFO. Writing a 1 to CLR_TXF clears the TX FIFO Counter. The * CLR_TXF bit is always read as zero. * * Values: * - 0 - Do not clear the TX FIFO counter. * - 1 - Clear the TX FIFO counter. */ /*@{*/ #define BP_SPI_MCR_CLR_TXF (11U) /*!< Bit position for SPI_MCR_CLR_TXF. */ #define BM_SPI_MCR_CLR_TXF (0x00000800U) /*!< Bit mask for SPI_MCR_CLR_TXF. */ #define BS_SPI_MCR_CLR_TXF (1U) /*!< Bit field size in bits for SPI_MCR_CLR_TXF. */ /*! @brief Format value for bitfield SPI_MCR_CLR_TXF. */ #define BF_SPI_MCR_CLR_TXF(v) ((uint32_t)((uint32_t)(v) << BP_SPI_MCR_CLR_TXF) & BM_SPI_MCR_CLR_TXF) /*! @brief Set the CLR_TXF field to a new value. */ #define BW_SPI_MCR_CLR_TXF(x, v) (BITBAND_ACCESS32(HW_SPI_MCR_ADDR(x), BP_SPI_MCR_CLR_TXF) = (v)) /*@}*/ /*! * @name Register SPI_MCR, field DIS_RXF[12] (RW) * * When the RX FIFO is disabled, the receive part of the module operates as a * simplified double-buffered SPI. This bit can only be written when the MDIS bit * is cleared. * * Values: * - 0 - RX FIFO is enabled. * - 1 - RX FIFO is disabled. */ /*@{*/ #define BP_SPI_MCR_DIS_RXF (12U) /*!< Bit position for SPI_MCR_DIS_RXF. */ #define BM_SPI_MCR_DIS_RXF (0x00001000U) /*!< Bit mask for SPI_MCR_DIS_RXF. */ #define BS_SPI_MCR_DIS_RXF (1U) /*!< Bit field size in bits for SPI_MCR_DIS_RXF. */ /*! @brief Read current value of the SPI_MCR_DIS_RXF field. */ #define BR_SPI_MCR_DIS_RXF(x) (BITBAND_ACCESS32(HW_SPI_MCR_ADDR(x), BP_SPI_MCR_DIS_RXF)) /*! @brief Format value for bitfield SPI_MCR_DIS_RXF. */ #define BF_SPI_MCR_DIS_RXF(v) ((uint32_t)((uint32_t)(v) << BP_SPI_MCR_DIS_RXF) & BM_SPI_MCR_DIS_RXF) /*! @brief Set the DIS_RXF field to a new value. */ #define BW_SPI_MCR_DIS_RXF(x, v) (BITBAND_ACCESS32(HW_SPI_MCR_ADDR(x), BP_SPI_MCR_DIS_RXF) = (v)) /*@}*/ /*! * @name Register SPI_MCR, field DIS_TXF[13] (RW) * * When the TX FIFO is disabled, the transmit part of the module operates as a * simplified double-buffered SPI. This bit can be written only when the MDIS bit * is cleared. * * Values: * - 0 - TX FIFO is enabled. * - 1 - TX FIFO is disabled. */ /*@{*/ #define BP_SPI_MCR_DIS_TXF (13U) /*!< Bit position for SPI_MCR_DIS_TXF. */ #define BM_SPI_MCR_DIS_TXF (0x00002000U) /*!< Bit mask for SPI_MCR_DIS_TXF. */ #define BS_SPI_MCR_DIS_TXF (1U) /*!< Bit field size in bits for SPI_MCR_DIS_TXF. */ /*! @brief Read current value of the SPI_MCR_DIS_TXF field. */ #define BR_SPI_MCR_DIS_TXF(x) (BITBAND_ACCESS32(HW_SPI_MCR_ADDR(x), BP_SPI_MCR_DIS_TXF)) /*! @brief Format value for bitfield SPI_MCR_DIS_TXF. */ #define BF_SPI_MCR_DIS_TXF(v) ((uint32_t)((uint32_t)(v) << BP_SPI_MCR_DIS_TXF) & BM_SPI_MCR_DIS_TXF) /*! @brief Set the DIS_TXF field to a new value. */ #define BW_SPI_MCR_DIS_TXF(x, v) (BITBAND_ACCESS32(HW_SPI_MCR_ADDR(x), BP_SPI_MCR_DIS_TXF) = (v)) /*@}*/ /*! * @name Register SPI_MCR, field MDIS[14] (RW) * * Allows the clock to be stopped to the non-memory mapped logic in the module * effectively putting it in a software-controlled power-saving state. The reset * value of the MDIS bit is parameterized, with a default reset value of 0. When * the module is used in Slave Mode, we recommend leaving this bit 0, because a * slave doesn't have control over master transactions. * * Values: * - 0 - Enables the module clocks. * - 1 - Allows external logic to disable the module clocks. */ /*@{*/ #define BP_SPI_MCR_MDIS (14U) /*!< Bit position for SPI_MCR_MDIS. */ #define BM_SPI_MCR_MDIS (0x00004000U) /*!< Bit mask for SPI_MCR_MDIS. */ #define BS_SPI_MCR_MDIS (1U) /*!< Bit field size in bits for SPI_MCR_MDIS. */ /*! @brief Read current value of the SPI_MCR_MDIS field. */ #define BR_SPI_MCR_MDIS(x) (BITBAND_ACCESS32(HW_SPI_MCR_ADDR(x), BP_SPI_MCR_MDIS)) /*! @brief Format value for bitfield SPI_MCR_MDIS. */ #define BF_SPI_MCR_MDIS(v) ((uint32_t)((uint32_t)(v) << BP_SPI_MCR_MDIS) & BM_SPI_MCR_MDIS) /*! @brief Set the MDIS field to a new value. */ #define BW_SPI_MCR_MDIS(x, v) (BITBAND_ACCESS32(HW_SPI_MCR_ADDR(x), BP_SPI_MCR_MDIS) = (v)) /*@}*/ /*! * @name Register SPI_MCR, field DOZE[15] (RW) * * Provides support for an externally controlled Doze mode power-saving * mechanism. * * Values: * - 0 - Doze mode has no effect on the module. * - 1 - Doze mode disables the module. */ /*@{*/ #define BP_SPI_MCR_DOZE (15U) /*!< Bit position for SPI_MCR_DOZE. */ #define BM_SPI_MCR_DOZE (0x00008000U) /*!< Bit mask for SPI_MCR_DOZE. */ #define BS_SPI_MCR_DOZE (1U) /*!< Bit field size in bits for SPI_MCR_DOZE. */ /*! @brief Read current value of the SPI_MCR_DOZE field. */ #define BR_SPI_MCR_DOZE(x) (BITBAND_ACCESS32(HW_SPI_MCR_ADDR(x), BP_SPI_MCR_DOZE)) /*! @brief Format value for bitfield SPI_MCR_DOZE. */ #define BF_SPI_MCR_DOZE(v) ((uint32_t)((uint32_t)(v) << BP_SPI_MCR_DOZE) & BM_SPI_MCR_DOZE) /*! @brief Set the DOZE field to a new value. */ #define BW_SPI_MCR_DOZE(x, v) (BITBAND_ACCESS32(HW_SPI_MCR_ADDR(x), BP_SPI_MCR_DOZE) = (v)) /*@}*/ /*! * @name Register SPI_MCR, field PCSIS[21:16] (RW) * * Determines the inactive state of PCSx. * * Values: * - 0 - The inactive state of PCSx is low. * - 1 - The inactive state of PCSx is high. */ /*@{*/ #define BP_SPI_MCR_PCSIS (16U) /*!< Bit position for SPI_MCR_PCSIS. */ #define BM_SPI_MCR_PCSIS (0x003F0000U) /*!< Bit mask for SPI_MCR_PCSIS. */ #define BS_SPI_MCR_PCSIS (6U) /*!< Bit field size in bits for SPI_MCR_PCSIS. */ /*! @brief Read current value of the SPI_MCR_PCSIS field. */ #define BR_SPI_MCR_PCSIS(x) (HW_SPI_MCR(x).B.PCSIS) /*! @brief Format value for bitfield SPI_MCR_PCSIS. */ #define BF_SPI_MCR_PCSIS(v) ((uint32_t)((uint32_t)(v) << BP_SPI_MCR_PCSIS) & BM_SPI_MCR_PCSIS) /*! @brief Set the PCSIS field to a new value. */ #define BW_SPI_MCR_PCSIS(x, v) (HW_SPI_MCR_WR(x, (HW_SPI_MCR_RD(x) & ~BM_SPI_MCR_PCSIS) | BF_SPI_MCR_PCSIS(v))) /*@}*/ /*! * @name Register SPI_MCR, field ROOE[24] (RW) * * In the RX FIFO overflow condition, configures the module to ignore the * incoming serial data or overwrite existing data. If the RX FIFO is full and new data * is received, the data from the transfer, generating the overflow, is ignored * or shifted into the shift register. * * Values: * - 0 - Incoming data is ignored. * - 1 - Incoming data is shifted into the shift register. */ /*@{*/ #define BP_SPI_MCR_ROOE (24U) /*!< Bit position for SPI_MCR_ROOE. */ #define BM_SPI_MCR_ROOE (0x01000000U) /*!< Bit mask for SPI_MCR_ROOE. */ #define BS_SPI_MCR_ROOE (1U) /*!< Bit field size in bits for SPI_MCR_ROOE. */ /*! @brief Read current value of the SPI_MCR_ROOE field. */ #define BR_SPI_MCR_ROOE(x) (BITBAND_ACCESS32(HW_SPI_MCR_ADDR(x), BP_SPI_MCR_ROOE)) /*! @brief Format value for bitfield SPI_MCR_ROOE. */ #define BF_SPI_MCR_ROOE(v) ((uint32_t)((uint32_t)(v) << BP_SPI_MCR_ROOE) & BM_SPI_MCR_ROOE) /*! @brief Set the ROOE field to a new value. */ #define BW_SPI_MCR_ROOE(x, v) (BITBAND_ACCESS32(HW_SPI_MCR_ADDR(x), BP_SPI_MCR_ROOE) = (v)) /*@}*/ /*! * @name Register SPI_MCR, field PCSSE[25] (RW) * * Enables the PCS5/ PCSS to operate as a PCS Strobe output signal. * * Values: * - 0 - PCS5/ PCSS is used as the Peripheral Chip Select[5] signal. * - 1 - PCS5/ PCSS is used as an active-low PCS Strobe signal. */ /*@{*/ #define BP_SPI_MCR_PCSSE (25U) /*!< Bit position for SPI_MCR_PCSSE. */ #define BM_SPI_MCR_PCSSE (0x02000000U) /*!< Bit mask for SPI_MCR_PCSSE. */ #define BS_SPI_MCR_PCSSE (1U) /*!< Bit field size in bits for SPI_MCR_PCSSE. */ /*! @brief Read current value of the SPI_MCR_PCSSE field. */ #define BR_SPI_MCR_PCSSE(x) (BITBAND_ACCESS32(HW_SPI_MCR_ADDR(x), BP_SPI_MCR_PCSSE)) /*! @brief Format value for bitfield SPI_MCR_PCSSE. */ #define BF_SPI_MCR_PCSSE(v) ((uint32_t)((uint32_t)(v) << BP_SPI_MCR_PCSSE) & BM_SPI_MCR_PCSSE) /*! @brief Set the PCSSE field to a new value. */ #define BW_SPI_MCR_PCSSE(x, v) (BITBAND_ACCESS32(HW_SPI_MCR_ADDR(x), BP_SPI_MCR_PCSSE) = (v)) /*@}*/ /*! * @name Register SPI_MCR, field MTFE[26] (RW) * * Enables a modified transfer format to be used. * * Values: * - 0 - Modified SPI transfer format disabled. * - 1 - Modified SPI transfer format enabled. */ /*@{*/ #define BP_SPI_MCR_MTFE (26U) /*!< Bit position for SPI_MCR_MTFE. */ #define BM_SPI_MCR_MTFE (0x04000000U) /*!< Bit mask for SPI_MCR_MTFE. */ #define BS_SPI_MCR_MTFE (1U) /*!< Bit field size in bits for SPI_MCR_MTFE. */ /*! @brief Read current value of the SPI_MCR_MTFE field. */ #define BR_SPI_MCR_MTFE(x) (BITBAND_ACCESS32(HW_SPI_MCR_ADDR(x), BP_SPI_MCR_MTFE)) /*! @brief Format value for bitfield SPI_MCR_MTFE. */ #define BF_SPI_MCR_MTFE(v) ((uint32_t)((uint32_t)(v) << BP_SPI_MCR_MTFE) & BM_SPI_MCR_MTFE) /*! @brief Set the MTFE field to a new value. */ #define BW_SPI_MCR_MTFE(x, v) (BITBAND_ACCESS32(HW_SPI_MCR_ADDR(x), BP_SPI_MCR_MTFE) = (v)) /*@}*/ /*! * @name Register SPI_MCR, field FRZ[27] (RW) * * Enables transfers to be stopped on the next frame boundary when the device * enters Debug mode. * * Values: * - 0 - Do not halt serial transfers in Debug mode. * - 1 - Halt serial transfers in Debug mode. */ /*@{*/ #define BP_SPI_MCR_FRZ (27U) /*!< Bit position for SPI_MCR_FRZ. */ #define BM_SPI_MCR_FRZ (0x08000000U) /*!< Bit mask for SPI_MCR_FRZ. */ #define BS_SPI_MCR_FRZ (1U) /*!< Bit field size in bits for SPI_MCR_FRZ. */ /*! @brief Read current value of the SPI_MCR_FRZ field. */ #define BR_SPI_MCR_FRZ(x) (BITBAND_ACCESS32(HW_SPI_MCR_ADDR(x), BP_SPI_MCR_FRZ)) /*! @brief Format value for bitfield SPI_MCR_FRZ. */ #define BF_SPI_MCR_FRZ(v) ((uint32_t)((uint32_t)(v) << BP_SPI_MCR_FRZ) & BM_SPI_MCR_FRZ) /*! @brief Set the FRZ field to a new value. */ #define BW_SPI_MCR_FRZ(x, v) (BITBAND_ACCESS32(HW_SPI_MCR_ADDR(x), BP_SPI_MCR_FRZ) = (v)) /*@}*/ /*! * @name Register SPI_MCR, field DCONF[29:28] (RO) * * Selects among the different configurations of the module. * * Values: * - 00 - SPI * - 01 - Reserved * - 10 - Reserved * - 11 - Reserved */ /*@{*/ #define BP_SPI_MCR_DCONF (28U) /*!< Bit position for SPI_MCR_DCONF. */ #define BM_SPI_MCR_DCONF (0x30000000U) /*!< Bit mask for SPI_MCR_DCONF. */ #define BS_SPI_MCR_DCONF (2U) /*!< Bit field size in bits for SPI_MCR_DCONF. */ /*! @brief Read current value of the SPI_MCR_DCONF field. */ #define BR_SPI_MCR_DCONF(x) (HW_SPI_MCR(x).B.DCONF) /*@}*/ /*! * @name Register SPI_MCR, field CONT_SCKE[30] (RW) * * Enables the Serial Communication Clock (SCK) to run continuously. * * Values: * - 0 - Continuous SCK disabled. * - 1 - Continuous SCK enabled. */ /*@{*/ #define BP_SPI_MCR_CONT_SCKE (30U) /*!< Bit position for SPI_MCR_CONT_SCKE. */ #define BM_SPI_MCR_CONT_SCKE (0x40000000U) /*!< Bit mask for SPI_MCR_CONT_SCKE. */ #define BS_SPI_MCR_CONT_SCKE (1U) /*!< Bit field size in bits for SPI_MCR_CONT_SCKE. */ /*! @brief Read current value of the SPI_MCR_CONT_SCKE field. */ #define BR_SPI_MCR_CONT_SCKE(x) (BITBAND_ACCESS32(HW_SPI_MCR_ADDR(x), BP_SPI_MCR_CONT_SCKE)) /*! @brief Format value for bitfield SPI_MCR_CONT_SCKE. */ #define BF_SPI_MCR_CONT_SCKE(v) ((uint32_t)((uint32_t)(v) << BP_SPI_MCR_CONT_SCKE) & BM_SPI_MCR_CONT_SCKE) /*! @brief Set the CONT_SCKE field to a new value. */ #define BW_SPI_MCR_CONT_SCKE(x, v) (BITBAND_ACCESS32(HW_SPI_MCR_ADDR(x), BP_SPI_MCR_CONT_SCKE) = (v)) /*@}*/ /*! * @name Register SPI_MCR, field MSTR[31] (RW) * * Enables either Master mode (if supported) or Slave mode (if supported) * operation. * * Values: * - 0 - Enables Slave mode * - 1 - Enables Master mode */ /*@{*/ #define BP_SPI_MCR_MSTR (31U) /*!< Bit position for SPI_MCR_MSTR. */ #define BM_SPI_MCR_MSTR (0x80000000U) /*!< Bit mask for SPI_MCR_MSTR. */ #define BS_SPI_MCR_MSTR (1U) /*!< Bit field size in bits for SPI_MCR_MSTR. */ /*! @brief Read current value of the SPI_MCR_MSTR field. */ #define BR_SPI_MCR_MSTR(x) (BITBAND_ACCESS32(HW_SPI_MCR_ADDR(x), BP_SPI_MCR_MSTR)) /*! @brief Format value for bitfield SPI_MCR_MSTR. */ #define BF_SPI_MCR_MSTR(v) ((uint32_t)((uint32_t)(v) << BP_SPI_MCR_MSTR) & BM_SPI_MCR_MSTR) /*! @brief Set the MSTR field to a new value. */ #define BW_SPI_MCR_MSTR(x, v) (BITBAND_ACCESS32(HW_SPI_MCR_ADDR(x), BP_SPI_MCR_MSTR) = (v)) /*@}*/ /******************************************************************************* * HW_SPI_TCR - Transfer Count Register ******************************************************************************/ /*! * @brief HW_SPI_TCR - Transfer Count Register (RW) * * Reset value: 0x00000000U * * TCR contains a counter that indicates the number of SPI transfers made. The * transfer counter is intended to assist in queue management. Do not write the * TCR when the module is in the Running state. */ typedef union _hw_spi_tcr { uint32_t U; struct _hw_spi_tcr_bitfields { uint32_t RESERVED0 : 16; /*!< [15:0] */ uint32_t SPI_TCNT : 16; /*!< [31:16] SPI Transfer Counter */ } B; } hw_spi_tcr_t; /*! * @name Constants and macros for entire SPI_TCR register */ /*@{*/ #define HW_SPI_TCR_ADDR(x) ((x) + 0x8U) #define HW_SPI_TCR(x) (*(__IO hw_spi_tcr_t *) HW_SPI_TCR_ADDR(x)) #define HW_SPI_TCR_RD(x) (HW_SPI_TCR(x).U) #define HW_SPI_TCR_WR(x, v) (HW_SPI_TCR(x).U = (v)) #define HW_SPI_TCR_SET(x, v) (HW_SPI_TCR_WR(x, HW_SPI_TCR_RD(x) | (v))) #define HW_SPI_TCR_CLR(x, v) (HW_SPI_TCR_WR(x, HW_SPI_TCR_RD(x) & ~(v))) #define HW_SPI_TCR_TOG(x, v) (HW_SPI_TCR_WR(x, HW_SPI_TCR_RD(x) ^ (v))) /*@}*/ /* * Constants & macros for individual SPI_TCR bitfields */ /*! * @name Register SPI_TCR, field SPI_TCNT[31:16] (RW) * * Counts the number of SPI transfers the module makes. The SPI_TCNT field * increments every time the last bit of an SPI frame is transmitted. A value written * to SPI_TCNT presets the counter to that value. SPI_TCNT is reset to zero at * the beginning of the frame when the CTCNT field is set in the executing SPI * command. The Transfer Counter wraps around; incrementing the counter past 65535 * resets the counter to zero. */ /*@{*/ #define BP_SPI_TCR_SPI_TCNT (16U) /*!< Bit position for SPI_TCR_SPI_TCNT. */ #define BM_SPI_TCR_SPI_TCNT (0xFFFF0000U) /*!< Bit mask for SPI_TCR_SPI_TCNT. */ #define BS_SPI_TCR_SPI_TCNT (16U) /*!< Bit field size in bits for SPI_TCR_SPI_TCNT. */ /*! @brief Read current value of the SPI_TCR_SPI_TCNT field. */ #define BR_SPI_TCR_SPI_TCNT(x) (HW_SPI_TCR(x).B.SPI_TCNT) /*! @brief Format value for bitfield SPI_TCR_SPI_TCNT. */ #define BF_SPI_TCR_SPI_TCNT(v) ((uint32_t)((uint32_t)(v) << BP_SPI_TCR_SPI_TCNT) & BM_SPI_TCR_SPI_TCNT) /*! @brief Set the SPI_TCNT field to a new value. */ #define BW_SPI_TCR_SPI_TCNT(x, v) (HW_SPI_TCR_WR(x, (HW_SPI_TCR_RD(x) & ~BM_SPI_TCR_SPI_TCNT) | BF_SPI_TCR_SPI_TCNT(v))) /*@}*/ /******************************************************************************* * HW_SPI_CTARn - Clock and Transfer Attributes Register (In Master Mode) ******************************************************************************/ /*! * @brief HW_SPI_CTARn - Clock and Transfer Attributes Register (In Master Mode) (RW) * * Reset value: 0x78000000U * * CTAR registers are used to define different transfer attributes. Do not write * to the CTAR registers while the module is in the Running state. In Master * mode, the CTAR registers define combinations of transfer attributes such as frame * size, clock phase and polarity, data bit ordering, baud rate, and various * delays. In slave mode, a subset of the bitfields in CTAR0 are used to set the * slave transfer attributes. When the module is configured as an SPI master, the * CTAS field in the command portion of the TX FIFO entry selects which of the CTAR * registers is used. When the module is configured as an SPI bus slave, it uses * the CTAR0 register. */ typedef union _hw_spi_ctarn { uint32_t U; struct _hw_spi_ctarn_bitfields { uint32_t BR : 4; /*!< [3:0] Baud Rate Scaler */ uint32_t DT : 4; /*!< [7:4] Delay After Transfer Scaler */ uint32_t ASC : 4; /*!< [11:8] After SCK Delay Scaler */ uint32_t CSSCK : 4; /*!< [15:12] PCS to SCK Delay Scaler */ uint32_t PBR : 2; /*!< [17:16] Baud Rate Prescaler */ uint32_t PDT : 2; /*!< [19:18] Delay after Transfer Prescaler */ uint32_t PASC : 2; /*!< [21:20] After SCK Delay Prescaler */ uint32_t PCSSCK : 2; /*!< [23:22] PCS to SCK Delay Prescaler */ uint32_t LSBFE : 1; /*!< [24] LSB First */ uint32_t CPHA : 1; /*!< [25] Clock Phase */ uint32_t CPOL : 1; /*!< [26] Clock Polarity */ uint32_t FMSZ : 4; /*!< [30:27] Frame Size */ uint32_t DBR : 1; /*!< [31] Double Baud Rate */ } B; } hw_spi_ctarn_t; /*! * @name Constants and macros for entire SPI_CTARn register */ /*@{*/ #define HW_SPI_CTARn_COUNT (2U) #define HW_SPI_CTARn_ADDR(x, n) ((x) + 0xCU + (0x4U * (n))) #define HW_SPI_CTARn(x, n) (*(__IO hw_spi_ctarn_t *) HW_SPI_CTARn_ADDR(x, n)) #define HW_SPI_CTARn_RD(x, n) (HW_SPI_CTARn(x, n).U) #define HW_SPI_CTARn_WR(x, n, v) (HW_SPI_CTARn(x, n).U = (v)) #define HW_SPI_CTARn_SET(x, n, v) (HW_SPI_CTARn_WR(x, n, HW_SPI_CTARn_RD(x, n) | (v))) #define HW_SPI_CTARn_CLR(x, n, v) (HW_SPI_CTARn_WR(x, n, HW_SPI_CTARn_RD(x, n) & ~(v))) #define HW_SPI_CTARn_TOG(x, n, v) (HW_SPI_CTARn_WR(x, n, HW_SPI_CTARn_RD(x, n) ^ (v))) /*@}*/ /* * Constants & macros for individual SPI_CTARn bitfields */ /*! * @name Register SPI_CTARn, field BR[3:0] (RW) * * Selects the scaler value for the baud rate. This field is used only in master * mode. The prescaled protocol clock is divided by the Baud Rate Scaler to * generate the frequency of the SCK. The baud rate is computed according to the * following equation: SCK baud rate = (fP /PBR) x [(1+DBR)/BR] The following table * lists the baud rate scaler values. Baud Rate Scaler CTARn[BR] Baud Rate Scaler * Value 0000 2 0001 4 0010 6 0011 8 0100 16 0101 32 0110 64 0111 128 1000 256 * 1001 512 1010 1024 1011 2048 1100 4096 1101 8192 1110 16384 1111 32768 */ /*@{*/ #define BP_SPI_CTARn_BR (0U) /*!< Bit position for SPI_CTARn_BR. */ #define BM_SPI_CTARn_BR (0x0000000FU) /*!< Bit mask for SPI_CTARn_BR. */ #define BS_SPI_CTARn_BR (4U) /*!< Bit field size in bits for SPI_CTARn_BR. */ /*! @brief Read current value of the SPI_CTARn_BR field. */ #define BR_SPI_CTARn_BR(x, n) (HW_SPI_CTARn(x, n).B.BR) /*! @brief Format value for bitfield SPI_CTARn_BR. */ #define BF_SPI_CTARn_BR(v) ((uint32_t)((uint32_t)(v) << BP_SPI_CTARn_BR) & BM_SPI_CTARn_BR) /*! @brief Set the BR field to a new value. */ #define BW_SPI_CTARn_BR(x, n, v) (HW_SPI_CTARn_WR(x, n, (HW_SPI_CTARn_RD(x, n) & ~BM_SPI_CTARn_BR) | BF_SPI_CTARn_BR(v))) /*@}*/ /*! * @name Register SPI_CTARn, field DT[7:4] (RW) * * Selects the Delay after Transfer Scaler. This field is used only in master * mode. The Delay after Transfer is the time between the negation of the PCS * signal at the end of a frame and the assertion of PCS at the beginning of the next * frame. In the Continuous Serial Communications Clock operation, the DT value * is fixed to one SCK clock period, The Delay after Transfer is a multiple of the * protocol clock period, and it is computed according to the following * equation: tDT = (1/fP ) x PDT x DT See Delay Scaler Encoding table in CTARn[CSSCK] bit * field description for scaler values. */ /*@{*/ #define BP_SPI_CTARn_DT (4U) /*!< Bit position for SPI_CTARn_DT. */ #define BM_SPI_CTARn_DT (0x000000F0U) /*!< Bit mask for SPI_CTARn_DT. */ #define BS_SPI_CTARn_DT (4U) /*!< Bit field size in bits for SPI_CTARn_DT. */ /*! @brief Read current value of the SPI_CTARn_DT field. */ #define BR_SPI_CTARn_DT(x, n) (HW_SPI_CTARn(x, n).B.DT) /*! @brief Format value for bitfield SPI_CTARn_DT. */ #define BF_SPI_CTARn_DT(v) ((uint32_t)((uint32_t)(v) << BP_SPI_CTARn_DT) & BM_SPI_CTARn_DT) /*! @brief Set the DT field to a new value. */ #define BW_SPI_CTARn_DT(x, n, v) (HW_SPI_CTARn_WR(x, n, (HW_SPI_CTARn_RD(x, n) & ~BM_SPI_CTARn_DT) | BF_SPI_CTARn_DT(v))) /*@}*/ /*! * @name Register SPI_CTARn, field ASC[11:8] (RW) * * Selects the scaler value for the After SCK Delay. This field is used only in * master mode. The After SCK Delay is the delay between the last edge of SCK and * the negation of PCS. The delay is a multiple of the protocol clock period, * and it is computed according to the following equation: t ASC = (1/fP) x PASC x * ASC See Delay Scaler Encoding table in CTARn[CSSCK] bit field description for * scaler values. Refer After SCK Delay (tASC ) for more details. */ /*@{*/ #define BP_SPI_CTARn_ASC (8U) /*!< Bit position for SPI_CTARn_ASC. */ #define BM_SPI_CTARn_ASC (0x00000F00U) /*!< Bit mask for SPI_CTARn_ASC. */ #define BS_SPI_CTARn_ASC (4U) /*!< Bit field size in bits for SPI_CTARn_ASC. */ /*! @brief Read current value of the SPI_CTARn_ASC field. */ #define BR_SPI_CTARn_ASC(x, n) (HW_SPI_CTARn(x, n).B.ASC) /*! @brief Format value for bitfield SPI_CTARn_ASC. */ #define BF_SPI_CTARn_ASC(v) ((uint32_t)((uint32_t)(v) << BP_SPI_CTARn_ASC) & BM_SPI_CTARn_ASC) /*! @brief Set the ASC field to a new value. */ #define BW_SPI_CTARn_ASC(x, n, v) (HW_SPI_CTARn_WR(x, n, (HW_SPI_CTARn_RD(x, n) & ~BM_SPI_CTARn_ASC) | BF_SPI_CTARn_ASC(v))) /*@}*/ /*! * @name Register SPI_CTARn, field CSSCK[15:12] (RW) * * Selects the scaler value for the PCS to SCK delay. This field is used only in * master mode. The PCS to SCK Delay is the delay between the assertion of PCS * and the first edge of the SCK. The delay is a multiple of the protocol clock * period, and it is computed according to the following equation: t CSC = (1/fP ) * x PCSSCK x CSSCK. The following table lists the delay scaler values. Delay * Scaler Encoding Field Value Delay Scaler Value 0000 2 0001 4 0010 8 0011 16 0100 * 32 0101 64 0110 128 0111 256 1000 512 1001 1024 1010 2048 1011 4096 1100 8192 * 1101 16384 1110 32768 1111 65536 Refer PCS to SCK Delay (tCSC ) for more * details. */ /*@{*/ #define BP_SPI_CTARn_CSSCK (12U) /*!< Bit position for SPI_CTARn_CSSCK. */ #define BM_SPI_CTARn_CSSCK (0x0000F000U) /*!< Bit mask for SPI_CTARn_CSSCK. */ #define BS_SPI_CTARn_CSSCK (4U) /*!< Bit field size in bits for SPI_CTARn_CSSCK. */ /*! @brief Read current value of the SPI_CTARn_CSSCK field. */ #define BR_SPI_CTARn_CSSCK(x, n) (HW_SPI_CTARn(x, n).B.CSSCK) /*! @brief Format value for bitfield SPI_CTARn_CSSCK. */ #define BF_SPI_CTARn_CSSCK(v) ((uint32_t)((uint32_t)(v) << BP_SPI_CTARn_CSSCK) & BM_SPI_CTARn_CSSCK) /*! @brief Set the CSSCK field to a new value. */ #define BW_SPI_CTARn_CSSCK(x, n, v) (HW_SPI_CTARn_WR(x, n, (HW_SPI_CTARn_RD(x, n) & ~BM_SPI_CTARn_CSSCK) | BF_SPI_CTARn_CSSCK(v))) /*@}*/ /*! * @name Register SPI_CTARn, field PBR[17:16] (RW) * * Selects the prescaler value for the baud rate. This field is used only in * master mode. The baud rate is the frequency of the SCK. The protocol clock is * divided by the prescaler value before the baud rate selection takes place. See * the BR field description for details on how to compute the baud rate. * * Values: * - 00 - Baud Rate Prescaler value is 2. * - 01 - Baud Rate Prescaler value is 3. * - 10 - Baud Rate Prescaler value is 5. * - 11 - Baud Rate Prescaler value is 7. */ /*@{*/ #define BP_SPI_CTARn_PBR (16U) /*!< Bit position for SPI_CTARn_PBR. */ #define BM_SPI_CTARn_PBR (0x00030000U) /*!< Bit mask for SPI_CTARn_PBR. */ #define BS_SPI_CTARn_PBR (2U) /*!< Bit field size in bits for SPI_CTARn_PBR. */ /*! @brief Read current value of the SPI_CTARn_PBR field. */ #define BR_SPI_CTARn_PBR(x, n) (HW_SPI_CTARn(x, n).B.PBR) /*! @brief Format value for bitfield SPI_CTARn_PBR. */ #define BF_SPI_CTARn_PBR(v) ((uint32_t)((uint32_t)(v) << BP_SPI_CTARn_PBR) & BM_SPI_CTARn_PBR) /*! @brief Set the PBR field to a new value. */ #define BW_SPI_CTARn_PBR(x, n, v) (HW_SPI_CTARn_WR(x, n, (HW_SPI_CTARn_RD(x, n) & ~BM_SPI_CTARn_PBR) | BF_SPI_CTARn_PBR(v))) /*@}*/ /*! * @name Register SPI_CTARn, field PDT[19:18] (RW) * * Selects the prescaler value for the delay between the negation of the PCS * signal at the end of a frame and the assertion of PCS at the beginning of the * next frame. The PDT field is only used in master mode. See the DT field * description for details on how to compute the Delay after Transfer. Refer Delay after * Transfer (tDT ) for more details. * * Values: * - 00 - Delay after Transfer Prescaler value is 1. * - 01 - Delay after Transfer Prescaler value is 3. * - 10 - Delay after Transfer Prescaler value is 5. * - 11 - Delay after Transfer Prescaler value is 7. */ /*@{*/ #define BP_SPI_CTARn_PDT (18U) /*!< Bit position for SPI_CTARn_PDT. */ #define BM_SPI_CTARn_PDT (0x000C0000U) /*!< Bit mask for SPI_CTARn_PDT. */ #define BS_SPI_CTARn_PDT (2U) /*!< Bit field size in bits for SPI_CTARn_PDT. */ /*! @brief Read current value of the SPI_CTARn_PDT field. */ #define BR_SPI_CTARn_PDT(x, n) (HW_SPI_CTARn(x, n).B.PDT) /*! @brief Format value for bitfield SPI_CTARn_PDT. */ #define BF_SPI_CTARn_PDT(v) ((uint32_t)((uint32_t)(v) << BP_SPI_CTARn_PDT) & BM_SPI_CTARn_PDT) /*! @brief Set the PDT field to a new value. */ #define BW_SPI_CTARn_PDT(x, n, v) (HW_SPI_CTARn_WR(x, n, (HW_SPI_CTARn_RD(x, n) & ~BM_SPI_CTARn_PDT) | BF_SPI_CTARn_PDT(v))) /*@}*/ /*! * @name Register SPI_CTARn, field PASC[21:20] (RW) * * Selects the prescaler value for the delay between the last edge of SCK and * the negation of PCS. See the ASC field description for information on how to * compute the After SCK Delay. Refer After SCK Delay (tASC ) for more details. * * Values: * - 00 - Delay after Transfer Prescaler value is 1. * - 01 - Delay after Transfer Prescaler value is 3. * - 10 - Delay after Transfer Prescaler value is 5. * - 11 - Delay after Transfer Prescaler value is 7. */ /*@{*/ #define BP_SPI_CTARn_PASC (20U) /*!< Bit position for SPI_CTARn_PASC. */ #define BM_SPI_CTARn_PASC (0x00300000U) /*!< Bit mask for SPI_CTARn_PASC. */ #define BS_SPI_CTARn_PASC (2U) /*!< Bit field size in bits for SPI_CTARn_PASC. */ /*! @brief Read current value of the SPI_CTARn_PASC field. */ #define BR_SPI_CTARn_PASC(x, n) (HW_SPI_CTARn(x, n).B.PASC) /*! @brief Format value for bitfield SPI_CTARn_PASC. */ #define BF_SPI_CTARn_PASC(v) ((uint32_t)((uint32_t)(v) << BP_SPI_CTARn_PASC) & BM_SPI_CTARn_PASC) /*! @brief Set the PASC field to a new value. */ #define BW_SPI_CTARn_PASC(x, n, v) (HW_SPI_CTARn_WR(x, n, (HW_SPI_CTARn_RD(x, n) & ~BM_SPI_CTARn_PASC) | BF_SPI_CTARn_PASC(v))) /*@}*/ /*! * @name Register SPI_CTARn, field PCSSCK[23:22] (RW) * * Selects the prescaler value for the delay between assertion of PCS and the * first edge of the SCK. See the CSSCK field description for information on how to * compute the PCS to SCK Delay. Refer PCS to SCK Delay (tCSC ) for more details. * * Values: * - 00 - PCS to SCK Prescaler value is 1. * - 01 - PCS to SCK Prescaler value is 3. * - 10 - PCS to SCK Prescaler value is 5. * - 11 - PCS to SCK Prescaler value is 7. */ /*@{*/ #define BP_SPI_CTARn_PCSSCK (22U) /*!< Bit position for SPI_CTARn_PCSSCK. */ #define BM_SPI_CTARn_PCSSCK (0x00C00000U) /*!< Bit mask for SPI_CTARn_PCSSCK. */ #define BS_SPI_CTARn_PCSSCK (2U) /*!< Bit field size in bits for SPI_CTARn_PCSSCK. */ /*! @brief Read current value of the SPI_CTARn_PCSSCK field. */ #define BR_SPI_CTARn_PCSSCK(x, n) (HW_SPI_CTARn(x, n).B.PCSSCK) /*! @brief Format value for bitfield SPI_CTARn_PCSSCK. */ #define BF_SPI_CTARn_PCSSCK(v) ((uint32_t)((uint32_t)(v) << BP_SPI_CTARn_PCSSCK) & BM_SPI_CTARn_PCSSCK) /*! @brief Set the PCSSCK field to a new value. */ #define BW_SPI_CTARn_PCSSCK(x, n, v) (HW_SPI_CTARn_WR(x, n, (HW_SPI_CTARn_RD(x, n) & ~BM_SPI_CTARn_PCSSCK) | BF_SPI_CTARn_PCSSCK(v))) /*@}*/ /*! * @name Register SPI_CTARn, field LSBFE[24] (RW) * * Specifies whether the LSB or MSB of the frame is transferred first. * * Values: * - 0 - Data is transferred MSB first. * - 1 - Data is transferred LSB first. */ /*@{*/ #define BP_SPI_CTARn_LSBFE (24U) /*!< Bit position for SPI_CTARn_LSBFE. */ #define BM_SPI_CTARn_LSBFE (0x01000000U) /*!< Bit mask for SPI_CTARn_LSBFE. */ #define BS_SPI_CTARn_LSBFE (1U) /*!< Bit field size in bits for SPI_CTARn_LSBFE. */ /*! @brief Read current value of the SPI_CTARn_LSBFE field. */ #define BR_SPI_CTARn_LSBFE(x, n) (BITBAND_ACCESS32(HW_SPI_CTARn_ADDR(x, n), BP_SPI_CTARn_LSBFE)) /*! @brief Format value for bitfield SPI_CTARn_LSBFE. */ #define BF_SPI_CTARn_LSBFE(v) ((uint32_t)((uint32_t)(v) << BP_SPI_CTARn_LSBFE) & BM_SPI_CTARn_LSBFE) /*! @brief Set the LSBFE field to a new value. */ #define BW_SPI_CTARn_LSBFE(x, n, v) (BITBAND_ACCESS32(HW_SPI_CTARn_ADDR(x, n), BP_SPI_CTARn_LSBFE) = (v)) /*@}*/ /*! * @name Register SPI_CTARn, field CPHA[25] (RW) * * Selects which edge of SCK causes data to change and which edge causes data to * be captured. This bit is used in both master and slave mode. For successful * communication between serial devices, the devices must have identical clock * phase settings. In Continuous SCK mode, the bit value is ignored and the * transfers are done as if the CPHA bit is set to 1. * * Values: * - 0 - Data is captured on the leading edge of SCK and changed on the * following edge. * - 1 - Data is changed on the leading edge of SCK and captured on the * following edge. */ /*@{*/ #define BP_SPI_CTARn_CPHA (25U) /*!< Bit position for SPI_CTARn_CPHA. */ #define BM_SPI_CTARn_CPHA (0x02000000U) /*!< Bit mask for SPI_CTARn_CPHA. */ #define BS_SPI_CTARn_CPHA (1U) /*!< Bit field size in bits for SPI_CTARn_CPHA. */ /*! @brief Read current value of the SPI_CTARn_CPHA field. */ #define BR_SPI_CTARn_CPHA(x, n) (BITBAND_ACCESS32(HW_SPI_CTARn_ADDR(x, n), BP_SPI_CTARn_CPHA)) /*! @brief Format value for bitfield SPI_CTARn_CPHA. */ #define BF_SPI_CTARn_CPHA(v) ((uint32_t)((uint32_t)(v) << BP_SPI_CTARn_CPHA) & BM_SPI_CTARn_CPHA) /*! @brief Set the CPHA field to a new value. */ #define BW_SPI_CTARn_CPHA(x, n, v) (BITBAND_ACCESS32(HW_SPI_CTARn_ADDR(x, n), BP_SPI_CTARn_CPHA) = (v)) /*@}*/ /*! * @name Register SPI_CTARn, field CPOL[26] (RW) * * Selects the inactive state of the Serial Communications Clock (SCK). This bit * is used in both master and slave mode. For successful communication between * serial devices, the devices must have identical clock polarities. When the * Continuous Selection Format is selected, switching between clock polarities * without stopping the module can cause errors in the transfer due to the peripheral * device interpreting the switch of clock polarity as a valid clock edge. In case * of continous sck mode, when the module goes in low power mode(disabled), * inactive state of sck is not guaranted. * * Values: * - 0 - The inactive state value of SCK is low. * - 1 - The inactive state value of SCK is high. */ /*@{*/ #define BP_SPI_CTARn_CPOL (26U) /*!< Bit position for SPI_CTARn_CPOL. */ #define BM_SPI_CTARn_CPOL (0x04000000U) /*!< Bit mask for SPI_CTARn_CPOL. */ #define BS_SPI_CTARn_CPOL (1U) /*!< Bit field size in bits for SPI_CTARn_CPOL. */ /*! @brief Read current value of the SPI_CTARn_CPOL field. */ #define BR_SPI_CTARn_CPOL(x, n) (BITBAND_ACCESS32(HW_SPI_CTARn_ADDR(x, n), BP_SPI_CTARn_CPOL)) /*! @brief Format value for bitfield SPI_CTARn_CPOL. */ #define BF_SPI_CTARn_CPOL(v) ((uint32_t)((uint32_t)(v) << BP_SPI_CTARn_CPOL) & BM_SPI_CTARn_CPOL) /*! @brief Set the CPOL field to a new value. */ #define BW_SPI_CTARn_CPOL(x, n, v) (BITBAND_ACCESS32(HW_SPI_CTARn_ADDR(x, n), BP_SPI_CTARn_CPOL) = (v)) /*@}*/ /*! * @name Register SPI_CTARn, field FMSZ[30:27] (RW) * * The number of bits transferred per frame is equal to the FMSZ value plus 1. * Regardless of the transmission mode, the minimum valid frame size value is 4. */ /*@{*/ #define BP_SPI_CTARn_FMSZ (27U) /*!< Bit position for SPI_CTARn_FMSZ. */ #define BM_SPI_CTARn_FMSZ (0x78000000U) /*!< Bit mask for SPI_CTARn_FMSZ. */ #define BS_SPI_CTARn_FMSZ (4U) /*!< Bit field size in bits for SPI_CTARn_FMSZ. */ /*! @brief Read current value of the SPI_CTARn_FMSZ field. */ #define BR_SPI_CTARn_FMSZ(x, n) (HW_SPI_CTARn(x, n).B.FMSZ) /*! @brief Format value for bitfield SPI_CTARn_FMSZ. */ #define BF_SPI_CTARn_FMSZ(v) ((uint32_t)((uint32_t)(v) << BP_SPI_CTARn_FMSZ) & BM_SPI_CTARn_FMSZ) /*! @brief Set the FMSZ field to a new value. */ #define BW_SPI_CTARn_FMSZ(x, n, v) (HW_SPI_CTARn_WR(x, n, (HW_SPI_CTARn_RD(x, n) & ~BM_SPI_CTARn_FMSZ) | BF_SPI_CTARn_FMSZ(v))) /*@}*/ /*! * @name Register SPI_CTARn, field DBR[31] (RW) * * Doubles the effective baud rate of the Serial Communications Clock (SCK). * This field is used only in master mode. It effectively halves the Baud Rate * division ratio, supporting faster frequencies, and odd division ratios for the * Serial Communications Clock (SCK). When the DBR bit is set, the duty cycle of the * Serial Communications Clock (SCK) depends on the value in the Baud Rate * Prescaler and the Clock Phase bit as listed in the following table. See the BR field * description for details on how to compute the baud rate. SPI SCK Duty Cycle * DBR CPHA PBR SCK Duty Cycle 0 any any 50/50 1 0 00 50/50 1 0 01 33/66 1 0 10 * 40/60 1 0 11 43/57 1 1 00 50/50 1 1 01 66/33 1 1 10 60/40 1 1 11 57/43 * * Values: * - 0 - The baud rate is computed normally with a 50/50 duty cycle. * - 1 - The baud rate is doubled with the duty cycle depending on the Baud Rate * Prescaler. */ /*@{*/ #define BP_SPI_CTARn_DBR (31U) /*!< Bit position for SPI_CTARn_DBR. */ #define BM_SPI_CTARn_DBR (0x80000000U) /*!< Bit mask for SPI_CTARn_DBR. */ #define BS_SPI_CTARn_DBR (1U) /*!< Bit field size in bits for SPI_CTARn_DBR. */ /*! @brief Read current value of the SPI_CTARn_DBR field. */ #define BR_SPI_CTARn_DBR(x, n) (BITBAND_ACCESS32(HW_SPI_CTARn_ADDR(x, n), BP_SPI_CTARn_DBR)) /*! @brief Format value for bitfield SPI_CTARn_DBR. */ #define BF_SPI_CTARn_DBR(v) ((uint32_t)((uint32_t)(v) << BP_SPI_CTARn_DBR) & BM_SPI_CTARn_DBR) /*! @brief Set the DBR field to a new value. */ #define BW_SPI_CTARn_DBR(x, n, v) (BITBAND_ACCESS32(HW_SPI_CTARn_ADDR(x, n), BP_SPI_CTARn_DBR) = (v)) /*@}*/ /******************************************************************************* * HW_SPI_CTARn_SLAVE - Clock and Transfer Attributes Register (In Slave Mode) ******************************************************************************/ /*! * @brief HW_SPI_CTARn_SLAVE - Clock and Transfer Attributes Register (In Slave Mode) (RW) * * Reset value: 0x78000000U * * When the module is configured as an SPI bus slave, the CTAR0 register is used. */ typedef union _hw_spi_ctarn_slave { uint32_t U; struct _hw_spi_ctarn_slave_bitfields { uint32_t RESERVED0 : 25; /*!< [24:0] */ uint32_t CPHA : 1; /*!< [25] Clock Phase */ uint32_t CPOL : 1; /*!< [26] Clock Polarity */ uint32_t FMSZ : 5; /*!< [31:27] Frame Size */ } B; } hw_spi_ctarn_slave_t; /*! * @name Constants and macros for entire SPI_CTARn_SLAVE register */ /*@{*/ #define HW_SPI_CTARn_SLAVE_COUNT (1U) #define HW_SPI_CTARn_SLAVE_ADDR(x, n) ((x) + 0xCU + (0x4U * (n))) #define HW_SPI_CTARn_SLAVE(x, n) (*(__IO hw_spi_ctarn_slave_t *) HW_SPI_CTARn_SLAVE_ADDR(x, n)) #define HW_SPI_CTARn_SLAVE_RD(x, n) (HW_SPI_CTARn_SLAVE(x, n).U) #define HW_SPI_CTARn_SLAVE_WR(x, n, v) (HW_SPI_CTARn_SLAVE(x, n).U = (v)) #define HW_SPI_CTARn_SLAVE_SET(x, n, v) (HW_SPI_CTARn_SLAVE_WR(x, n, HW_SPI_CTARn_SLAVE_RD(x, n) | (v))) #define HW_SPI_CTARn_SLAVE_CLR(x, n, v) (HW_SPI_CTARn_SLAVE_WR(x, n, HW_SPI_CTARn_SLAVE_RD(x, n) & ~(v))) #define HW_SPI_CTARn_SLAVE_TOG(x, n, v) (HW_SPI_CTARn_SLAVE_WR(x, n, HW_SPI_CTARn_SLAVE_RD(x, n) ^ (v))) /*@}*/ /* * Constants & macros for individual SPI_CTARn_SLAVE bitfields */ /*! * @name Register SPI_CTARn_SLAVE, field CPHA[25] (RW) * * Selects which edge of SCK causes data to change and which edge causes data to * be captured. This bit is used in both master and slave mode. For successful * communication between serial devices, the devices must have identical clock * phase settings. In Continuous SCK mode, the bit value is ignored and the * transfers are done as if the CPHA bit is set to 1. * * Values: * - 0 - Data is captured on the leading edge of SCK and changed on the * following edge. * - 1 - Data is changed on the leading edge of SCK and captured on the * following edge. */ /*@{*/ #define BP_SPI_CTARn_SLAVE_CPHA (25U) /*!< Bit position for SPI_CTARn_SLAVE_CPHA. */ #define BM_SPI_CTARn_SLAVE_CPHA (0x02000000U) /*!< Bit mask for SPI_CTARn_SLAVE_CPHA. */ #define BS_SPI_CTARn_SLAVE_CPHA (1U) /*!< Bit field size in bits for SPI_CTARn_SLAVE_CPHA. */ /*! @brief Read current value of the SPI_CTARn_SLAVE_CPHA field. */ #define BR_SPI_CTARn_SLAVE_CPHA(x, n) (BITBAND_ACCESS32(HW_SPI_CTARn_SLAVE_ADDR(x, n), BP_SPI_CTARn_SLAVE_CPHA)) /*! @brief Format value for bitfield SPI_CTARn_SLAVE_CPHA. */ #define BF_SPI_CTARn_SLAVE_CPHA(v) ((uint32_t)((uint32_t)(v) << BP_SPI_CTARn_SLAVE_CPHA) & BM_SPI_CTARn_SLAVE_CPHA) /*! @brief Set the CPHA field to a new value. */ #define BW_SPI_CTARn_SLAVE_CPHA(x, n, v) (BITBAND_ACCESS32(HW_SPI_CTARn_SLAVE_ADDR(x, n), BP_SPI_CTARn_SLAVE_CPHA) = (v)) /*@}*/ /*! * @name Register SPI_CTARn_SLAVE, field CPOL[26] (RW) * * Selects the inactive state of the Serial Communications Clock (SCK). In case * of continous sck mode, when the module goes in low power mode(disabled), * inactive state of sck is not guaranted. * * Values: * - 0 - The inactive state value of SCK is low. * - 1 - The inactive state value of SCK is high. */ /*@{*/ #define BP_SPI_CTARn_SLAVE_CPOL (26U) /*!< Bit position for SPI_CTARn_SLAVE_CPOL. */ #define BM_SPI_CTARn_SLAVE_CPOL (0x04000000U) /*!< Bit mask for SPI_CTARn_SLAVE_CPOL. */ #define BS_SPI_CTARn_SLAVE_CPOL (1U) /*!< Bit field size in bits for SPI_CTARn_SLAVE_CPOL. */ /*! @brief Read current value of the SPI_CTARn_SLAVE_CPOL field. */ #define BR_SPI_CTARn_SLAVE_CPOL(x, n) (BITBAND_ACCESS32(HW_SPI_CTARn_SLAVE_ADDR(x, n), BP_SPI_CTARn_SLAVE_CPOL)) /*! @brief Format value for bitfield SPI_CTARn_SLAVE_CPOL. */ #define BF_SPI_CTARn_SLAVE_CPOL(v) ((uint32_t)((uint32_t)(v) << BP_SPI_CTARn_SLAVE_CPOL) & BM_SPI_CTARn_SLAVE_CPOL) /*! @brief Set the CPOL field to a new value. */ #define BW_SPI_CTARn_SLAVE_CPOL(x, n, v) (BITBAND_ACCESS32(HW_SPI_CTARn_SLAVE_ADDR(x, n), BP_SPI_CTARn_SLAVE_CPOL) = (v)) /*@}*/ /*! * @name Register SPI_CTARn_SLAVE, field FMSZ[31:27] (RW) * * The number of bits transfered per frame is equal to the FMSZ field value plus * 1. Note that the minimum valid value of frame size is 4. */ /*@{*/ #define BP_SPI_CTARn_SLAVE_FMSZ (27U) /*!< Bit position for SPI_CTARn_SLAVE_FMSZ. */ #define BM_SPI_CTARn_SLAVE_FMSZ (0xF8000000U) /*!< Bit mask for SPI_CTARn_SLAVE_FMSZ. */ #define BS_SPI_CTARn_SLAVE_FMSZ (5U) /*!< Bit field size in bits for SPI_CTARn_SLAVE_FMSZ. */ /*! @brief Read current value of the SPI_CTARn_SLAVE_FMSZ field. */ #define BR_SPI_CTARn_SLAVE_FMSZ(x, n) (HW_SPI_CTARn_SLAVE(x, n).B.FMSZ) /*! @brief Format value for bitfield SPI_CTARn_SLAVE_FMSZ. */ #define BF_SPI_CTARn_SLAVE_FMSZ(v) ((uint32_t)((uint32_t)(v) << BP_SPI_CTARn_SLAVE_FMSZ) & BM_SPI_CTARn_SLAVE_FMSZ) /*! @brief Set the FMSZ field to a new value. */ #define BW_SPI_CTARn_SLAVE_FMSZ(x, n, v) (HW_SPI_CTARn_SLAVE_WR(x, n, (HW_SPI_CTARn_SLAVE_RD(x, n) & ~BM_SPI_CTARn_SLAVE_FMSZ) | BF_SPI_CTARn_SLAVE_FMSZ(v))) /*@}*/ /******************************************************************************* * HW_SPI_SR - Status Register ******************************************************************************/ /*! * @brief HW_SPI_SR - Status Register (RW) * * Reset value: 0x02000000U * * SR contains status and flag bits. The bits reflect the status of the module * and indicate the occurrence of events that can generate interrupt or DMA * requests. Software can clear flag bits in the SR by writing a 1 to them. Writing a 0 * to a flag bit has no effect. This register may not be writable in Module * Disable mode due to the use of power saving mechanisms. */ typedef union _hw_spi_sr { uint32_t U; struct _hw_spi_sr_bitfields { uint32_t POPNXTPTR : 4; /*!< [3:0] Pop Next Pointer */ uint32_t RXCTR : 4; /*!< [7:4] RX FIFO Counter */ uint32_t TXNXTPTR : 4; /*!< [11:8] Transmit Next Pointer */ uint32_t TXCTR : 4; /*!< [15:12] TX FIFO Counter */ uint32_t RESERVED0 : 1; /*!< [16] */ uint32_t RFDF : 1; /*!< [17] Receive FIFO Drain Flag */ uint32_t RESERVED1 : 1; /*!< [18] */ uint32_t RFOF : 1; /*!< [19] Receive FIFO Overflow Flag */ uint32_t RESERVED2 : 5; /*!< [24:20] */ uint32_t TFFF : 1; /*!< [25] Transmit FIFO Fill Flag */ uint32_t RESERVED3 : 1; /*!< [26] */ uint32_t TFUF : 1; /*!< [27] Transmit FIFO Underflow Flag */ uint32_t EOQF : 1; /*!< [28] End of Queue Flag */ uint32_t RESERVED4 : 1; /*!< [29] */ uint32_t TXRXS : 1; /*!< [30] TX and RX Status */ uint32_t TCF : 1; /*!< [31] Transfer Complete Flag */ } B; } hw_spi_sr_t; /*! * @name Constants and macros for entire SPI_SR register */ /*@{*/ #define HW_SPI_SR_ADDR(x) ((x) + 0x2CU) #define HW_SPI_SR(x) (*(__IO hw_spi_sr_t *) HW_SPI_SR_ADDR(x)) #define HW_SPI_SR_RD(x) (HW_SPI_SR(x).U) #define HW_SPI_SR_WR(x, v) (HW_SPI_SR(x).U = (v)) #define HW_SPI_SR_SET(x, v) (HW_SPI_SR_WR(x, HW_SPI_SR_RD(x) | (v))) #define HW_SPI_SR_CLR(x, v) (HW_SPI_SR_WR(x, HW_SPI_SR_RD(x) & ~(v))) #define HW_SPI_SR_TOG(x, v) (HW_SPI_SR_WR(x, HW_SPI_SR_RD(x) ^ (v))) /*@}*/ /* * Constants & macros for individual SPI_SR bitfields */ /*! * @name Register SPI_SR, field POPNXTPTR[3:0] (RO) * * Contains a pointer to the RX FIFO entry to be returned when the POPR is read. * The POPNXTPTR is updated when the POPR is read. */ /*@{*/ #define BP_SPI_SR_POPNXTPTR (0U) /*!< Bit position for SPI_SR_POPNXTPTR. */ #define BM_SPI_SR_POPNXTPTR (0x0000000FU) /*!< Bit mask for SPI_SR_POPNXTPTR. */ #define BS_SPI_SR_POPNXTPTR (4U) /*!< Bit field size in bits for SPI_SR_POPNXTPTR. */ /*! @brief Read current value of the SPI_SR_POPNXTPTR field. */ #define BR_SPI_SR_POPNXTPTR(x) (HW_SPI_SR(x).B.POPNXTPTR) /*@}*/ /*! * @name Register SPI_SR, field RXCTR[7:4] (RO) * * Indicates the number of entries in the RX FIFO. The RXCTR is decremented * every time the POPR is read. The RXCTR is incremented every time data is * transferred from the shift register to the RX FIFO. */ /*@{*/ #define BP_SPI_SR_RXCTR (4U) /*!< Bit position for SPI_SR_RXCTR. */ #define BM_SPI_SR_RXCTR (0x000000F0U) /*!< Bit mask for SPI_SR_RXCTR. */ #define BS_SPI_SR_RXCTR (4U) /*!< Bit field size in bits for SPI_SR_RXCTR. */ /*! @brief Read current value of the SPI_SR_RXCTR field. */ #define BR_SPI_SR_RXCTR(x) (HW_SPI_SR(x).B.RXCTR) /*@}*/ /*! * @name Register SPI_SR, field TXNXTPTR[11:8] (RO) * * Indicates which TX FIFO entry is transmitted during the next transfer. The * TXNXTPTR field is updated every time SPI data is transferred from the TX FIFO to * the shift register. */ /*@{*/ #define BP_SPI_SR_TXNXTPTR (8U) /*!< Bit position for SPI_SR_TXNXTPTR. */ #define BM_SPI_SR_TXNXTPTR (0x00000F00U) /*!< Bit mask for SPI_SR_TXNXTPTR. */ #define BS_SPI_SR_TXNXTPTR (4U) /*!< Bit field size in bits for SPI_SR_TXNXTPTR. */ /*! @brief Read current value of the SPI_SR_TXNXTPTR field. */ #define BR_SPI_SR_TXNXTPTR(x) (HW_SPI_SR(x).B.TXNXTPTR) /*@}*/ /*! * @name Register SPI_SR, field TXCTR[15:12] (RO) * * Indicates the number of valid entries in the TX FIFO. The TXCTR is * incremented every time the PUSHR is written. The TXCTR is decremented every time an SPI * command is executed and the SPI data is transferred to the shift register. */ /*@{*/ #define BP_SPI_SR_TXCTR (12U) /*!< Bit position for SPI_SR_TXCTR. */ #define BM_SPI_SR_TXCTR (0x0000F000U) /*!< Bit mask for SPI_SR_TXCTR. */ #define BS_SPI_SR_TXCTR (4U) /*!< Bit field size in bits for SPI_SR_TXCTR. */ /*! @brief Read current value of the SPI_SR_TXCTR field. */ #define BR_SPI_SR_TXCTR(x) (HW_SPI_SR(x).B.TXCTR) /*@}*/ /*! * @name Register SPI_SR, field RFDF[17] (W1C) * * Provides a method for the module to request that entries be removed from the * RX FIFO. The bit is set while the RX FIFO is not empty. The RFDF bit can be * cleared by writing 1 to it or by acknowledgement from the DMA controller when * the RX FIFO is empty. * * Values: * - 0 - RX FIFO is empty. * - 1 - RX FIFO is not empty. */ /*@{*/ #define BP_SPI_SR_RFDF (17U) /*!< Bit position for SPI_SR_RFDF. */ #define BM_SPI_SR_RFDF (0x00020000U) /*!< Bit mask for SPI_SR_RFDF. */ #define BS_SPI_SR_RFDF (1U) /*!< Bit field size in bits for SPI_SR_RFDF. */ /*! @brief Read current value of the SPI_SR_RFDF field. */ #define BR_SPI_SR_RFDF(x) (BITBAND_ACCESS32(HW_SPI_SR_ADDR(x), BP_SPI_SR_RFDF)) /*! @brief Format value for bitfield SPI_SR_RFDF. */ #define BF_SPI_SR_RFDF(v) ((uint32_t)((uint32_t)(v) << BP_SPI_SR_RFDF) & BM_SPI_SR_RFDF) /*! @brief Set the RFDF field to a new value. */ #define BW_SPI_SR_RFDF(x, v) (BITBAND_ACCESS32(HW_SPI_SR_ADDR(x), BP_SPI_SR_RFDF) = (v)) /*@}*/ /*! * @name Register SPI_SR, field RFOF[19] (W1C) * * Indicates an overflow condition in the RX FIFO. The field is set when the RX * FIFO and shift register are full and a transfer is initiated. The bit remains * set until it is cleared by writing a 1 to it. * * Values: * - 0 - No Rx FIFO overflow. * - 1 - Rx FIFO overflow has occurred. */ /*@{*/ #define BP_SPI_SR_RFOF (19U) /*!< Bit position for SPI_SR_RFOF. */ #define BM_SPI_SR_RFOF (0x00080000U) /*!< Bit mask for SPI_SR_RFOF. */ #define BS_SPI_SR_RFOF (1U) /*!< Bit field size in bits for SPI_SR_RFOF. */ /*! @brief Read current value of the SPI_SR_RFOF field. */ #define BR_SPI_SR_RFOF(x) (BITBAND_ACCESS32(HW_SPI_SR_ADDR(x), BP_SPI_SR_RFOF)) /*! @brief Format value for bitfield SPI_SR_RFOF. */ #define BF_SPI_SR_RFOF(v) ((uint32_t)((uint32_t)(v) << BP_SPI_SR_RFOF) & BM_SPI_SR_RFOF) /*! @brief Set the RFOF field to a new value. */ #define BW_SPI_SR_RFOF(x, v) (BITBAND_ACCESS32(HW_SPI_SR_ADDR(x), BP_SPI_SR_RFOF) = (v)) /*@}*/ /*! * @name Register SPI_SR, field TFFF[25] (W1C) * * Provides a method for the module to request more entries to be added to the * TX FIFO. The TFFF bit is set while the TX FIFO is not full. The TFFF bit can be * cleared by writing 1 to it or by acknowledgement from the DMA controller to * the TX FIFO full request. * * Values: * - 0 - TX FIFO is full. * - 1 - TX FIFO is not full. */ /*@{*/ #define BP_SPI_SR_TFFF (25U) /*!< Bit position for SPI_SR_TFFF. */ #define BM_SPI_SR_TFFF (0x02000000U) /*!< Bit mask for SPI_SR_TFFF. */ #define BS_SPI_SR_TFFF (1U) /*!< Bit field size in bits for SPI_SR_TFFF. */ /*! @brief Read current value of the SPI_SR_TFFF field. */ #define BR_SPI_SR_TFFF(x) (BITBAND_ACCESS32(HW_SPI_SR_ADDR(x), BP_SPI_SR_TFFF)) /*! @brief Format value for bitfield SPI_SR_TFFF. */ #define BF_SPI_SR_TFFF(v) ((uint32_t)((uint32_t)(v) << BP_SPI_SR_TFFF) & BM_SPI_SR_TFFF) /*! @brief Set the TFFF field to a new value. */ #define BW_SPI_SR_TFFF(x, v) (BITBAND_ACCESS32(HW_SPI_SR_ADDR(x), BP_SPI_SR_TFFF) = (v)) /*@}*/ /*! * @name Register SPI_SR, field TFUF[27] (W1C) * * Indicates an underflow condition in the TX FIFO. The transmit underflow * condition is detected only for SPI blocks operating in Slave mode and SPI * configuration. TFUF is set when the TX FIFO of the module operating in SPI Slave mode * is empty and an external SPI master initiates a transfer. The TFUF bit remains * set until cleared by writing 1 to it. * * Values: * - 0 - No TX FIFO underflow. * - 1 - TX FIFO underflow has occurred. */ /*@{*/ #define BP_SPI_SR_TFUF (27U) /*!< Bit position for SPI_SR_TFUF. */ #define BM_SPI_SR_TFUF (0x08000000U) /*!< Bit mask for SPI_SR_TFUF. */ #define BS_SPI_SR_TFUF (1U) /*!< Bit field size in bits for SPI_SR_TFUF. */ /*! @brief Read current value of the SPI_SR_TFUF field. */ #define BR_SPI_SR_TFUF(x) (BITBAND_ACCESS32(HW_SPI_SR_ADDR(x), BP_SPI_SR_TFUF)) /*! @brief Format value for bitfield SPI_SR_TFUF. */ #define BF_SPI_SR_TFUF(v) ((uint32_t)((uint32_t)(v) << BP_SPI_SR_TFUF) & BM_SPI_SR_TFUF) /*! @brief Set the TFUF field to a new value. */ #define BW_SPI_SR_TFUF(x, v) (BITBAND_ACCESS32(HW_SPI_SR_ADDR(x), BP_SPI_SR_TFUF) = (v)) /*@}*/ /*! * @name Register SPI_SR, field EOQF[28] (W1C) * * Indicates that the last entry in a queue has been transmitted when the module * is in Master mode. The EOQF bit is set when the TX FIFO entry has the EOQ bit * set in the command halfword and the end of the transfer is reached. The EOQF * bit remains set until cleared by writing a 1 to it. When the EOQF bit is set, * the TXRXS bit is automatically cleared. * * Values: * - 0 - EOQ is not set in the executing command. * - 1 - EOQ is set in the executing SPI command. */ /*@{*/ #define BP_SPI_SR_EOQF (28U) /*!< Bit position for SPI_SR_EOQF. */ #define BM_SPI_SR_EOQF (0x10000000U) /*!< Bit mask for SPI_SR_EOQF. */ #define BS_SPI_SR_EOQF (1U) /*!< Bit field size in bits for SPI_SR_EOQF. */ /*! @brief Read current value of the SPI_SR_EOQF field. */ #define BR_SPI_SR_EOQF(x) (BITBAND_ACCESS32(HW_SPI_SR_ADDR(x), BP_SPI_SR_EOQF)) /*! @brief Format value for bitfield SPI_SR_EOQF. */ #define BF_SPI_SR_EOQF(v) ((uint32_t)((uint32_t)(v) << BP_SPI_SR_EOQF) & BM_SPI_SR_EOQF) /*! @brief Set the EOQF field to a new value. */ #define BW_SPI_SR_EOQF(x, v) (BITBAND_ACCESS32(HW_SPI_SR_ADDR(x), BP_SPI_SR_EOQF) = (v)) /*@}*/ /*! * @name Register SPI_SR, field TXRXS[30] (W1C) * * Reflects the run status of the module. * * Values: * - 0 - Transmit and receive operations are disabled (The module is in Stopped * state). * - 1 - Transmit and receive operations are enabled (The module is in Running * state). */ /*@{*/ #define BP_SPI_SR_TXRXS (30U) /*!< Bit position for SPI_SR_TXRXS. */ #define BM_SPI_SR_TXRXS (0x40000000U) /*!< Bit mask for SPI_SR_TXRXS. */ #define BS_SPI_SR_TXRXS (1U) /*!< Bit field size in bits for SPI_SR_TXRXS. */ /*! @brief Read current value of the SPI_SR_TXRXS field. */ #define BR_SPI_SR_TXRXS(x) (BITBAND_ACCESS32(HW_SPI_SR_ADDR(x), BP_SPI_SR_TXRXS)) /*! @brief Format value for bitfield SPI_SR_TXRXS. */ #define BF_SPI_SR_TXRXS(v) ((uint32_t)((uint32_t)(v) << BP_SPI_SR_TXRXS) & BM_SPI_SR_TXRXS) /*! @brief Set the TXRXS field to a new value. */ #define BW_SPI_SR_TXRXS(x, v) (BITBAND_ACCESS32(HW_SPI_SR_ADDR(x), BP_SPI_SR_TXRXS) = (v)) /*@}*/ /*! * @name Register SPI_SR, field TCF[31] (W1C) * * Indicates that all bits in a frame have been shifted out. TCF remains set * until it is cleared by writing a 1 to it. * * Values: * - 0 - Transfer not complete. * - 1 - Transfer complete. */ /*@{*/ #define BP_SPI_SR_TCF (31U) /*!< Bit position for SPI_SR_TCF. */ #define BM_SPI_SR_TCF (0x80000000U) /*!< Bit mask for SPI_SR_TCF. */ #define BS_SPI_SR_TCF (1U) /*!< Bit field size in bits for SPI_SR_TCF. */ /*! @brief Read current value of the SPI_SR_TCF field. */ #define BR_SPI_SR_TCF(x) (BITBAND_ACCESS32(HW_SPI_SR_ADDR(x), BP_SPI_SR_TCF)) /*! @brief Format value for bitfield SPI_SR_TCF. */ #define BF_SPI_SR_TCF(v) ((uint32_t)((uint32_t)(v) << BP_SPI_SR_TCF) & BM_SPI_SR_TCF) /*! @brief Set the TCF field to a new value. */ #define BW_SPI_SR_TCF(x, v) (BITBAND_ACCESS32(HW_SPI_SR_ADDR(x), BP_SPI_SR_TCF) = (v)) /*@}*/ /******************************************************************************* * HW_SPI_RSER - DMA/Interrupt Request Select and Enable Register ******************************************************************************/ /*! * @brief HW_SPI_RSER - DMA/Interrupt Request Select and Enable Register (RW) * * Reset value: 0x00000000U * * RSER controls DMA and interrupt requests. Do not write to the RSER while the * module is in the Running state. */ typedef union _hw_spi_rser { uint32_t U; struct _hw_spi_rser_bitfields { uint32_t RESERVED0 : 16; /*!< [15:0] */ uint32_t RFDF_DIRS : 1; /*!< [16] Receive FIFO Drain DMA or Interrupt * Request Select */ uint32_t RFDF_RE : 1; /*!< [17] Receive FIFO Drain Request Enable */ uint32_t RESERVED1 : 1; /*!< [18] */ uint32_t RFOF_RE : 1; /*!< [19] Receive FIFO Overflow Request Enable * */ uint32_t RESERVED2 : 4; /*!< [23:20] */ uint32_t TFFF_DIRS : 1; /*!< [24] Transmit FIFO Fill DMA or Interrupt * Request Select */ uint32_t TFFF_RE : 1; /*!< [25] Transmit FIFO Fill Request Enable */ uint32_t RESERVED3 : 1; /*!< [26] */ uint32_t TFUF_RE : 1; /*!< [27] Transmit FIFO Underflow Request * Enable */ uint32_t EOQF_RE : 1; /*!< [28] Finished Request Enable */ uint32_t RESERVED4 : 2; /*!< [30:29] */ uint32_t TCF_RE : 1; /*!< [31] Transmission Complete Request Enable */ } B; } hw_spi_rser_t; /*! * @name Constants and macros for entire SPI_RSER register */ /*@{*/ #define HW_SPI_RSER_ADDR(x) ((x) + 0x30U) #define HW_SPI_RSER(x) (*(__IO hw_spi_rser_t *) HW_SPI_RSER_ADDR(x)) #define HW_SPI_RSER_RD(x) (HW_SPI_RSER(x).U) #define HW_SPI_RSER_WR(x, v) (HW_SPI_RSER(x).U = (v)) #define HW_SPI_RSER_SET(x, v) (HW_SPI_RSER_WR(x, HW_SPI_RSER_RD(x) | (v))) #define HW_SPI_RSER_CLR(x, v) (HW_SPI_RSER_WR(x, HW_SPI_RSER_RD(x) & ~(v))) #define HW_SPI_RSER_TOG(x, v) (HW_SPI_RSER_WR(x, HW_SPI_RSER_RD(x) ^ (v))) /*@}*/ /* * Constants & macros for individual SPI_RSER bitfields */ /*! * @name Register SPI_RSER, field RFDF_DIRS[16] (RW) * * Selects between generating a DMA request or an interrupt request. When the * RFDF flag bit in the SR is set, and the RFDF_RE bit in the RSER is set, the * RFDF_DIRS bit selects between generating an interrupt request or a DMA request. * * Values: * - 0 - Interrupt request. * - 1 - DMA request. */ /*@{*/ #define BP_SPI_RSER_RFDF_DIRS (16U) /*!< Bit position for SPI_RSER_RFDF_DIRS. */ #define BM_SPI_RSER_RFDF_DIRS (0x00010000U) /*!< Bit mask for SPI_RSER_RFDF_DIRS. */ #define BS_SPI_RSER_RFDF_DIRS (1U) /*!< Bit field size in bits for SPI_RSER_RFDF_DIRS. */ /*! @brief Read current value of the SPI_RSER_RFDF_DIRS field. */ #define BR_SPI_RSER_RFDF_DIRS(x) (BITBAND_ACCESS32(HW_SPI_RSER_ADDR(x), BP_SPI_RSER_RFDF_DIRS)) /*! @brief Format value for bitfield SPI_RSER_RFDF_DIRS. */ #define BF_SPI_RSER_RFDF_DIRS(v) ((uint32_t)((uint32_t)(v) << BP_SPI_RSER_RFDF_DIRS) & BM_SPI_RSER_RFDF_DIRS) /*! @brief Set the RFDF_DIRS field to a new value. */ #define BW_SPI_RSER_RFDF_DIRS(x, v) (BITBAND_ACCESS32(HW_SPI_RSER_ADDR(x), BP_SPI_RSER_RFDF_DIRS) = (v)) /*@}*/ /*! * @name Register SPI_RSER, field RFDF_RE[17] (RW) * * Enables the RFDF flag in the SR to generate a request. The RFDF_DIRS bit * selects between generating an interrupt request or a DMA request. * * Values: * - 0 - RFDF interrupt or DMA requests are disabled. * - 1 - RFDF interrupt or DMA requests are enabled. */ /*@{*/ #define BP_SPI_RSER_RFDF_RE (17U) /*!< Bit position for SPI_RSER_RFDF_RE. */ #define BM_SPI_RSER_RFDF_RE (0x00020000U) /*!< Bit mask for SPI_RSER_RFDF_RE. */ #define BS_SPI_RSER_RFDF_RE (1U) /*!< Bit field size in bits for SPI_RSER_RFDF_RE. */ /*! @brief Read current value of the SPI_RSER_RFDF_RE field. */ #define BR_SPI_RSER_RFDF_RE(x) (BITBAND_ACCESS32(HW_SPI_RSER_ADDR(x), BP_SPI_RSER_RFDF_RE)) /*! @brief Format value for bitfield SPI_RSER_RFDF_RE. */ #define BF_SPI_RSER_RFDF_RE(v) ((uint32_t)((uint32_t)(v) << BP_SPI_RSER_RFDF_RE) & BM_SPI_RSER_RFDF_RE) /*! @brief Set the RFDF_RE field to a new value. */ #define BW_SPI_RSER_RFDF_RE(x, v) (BITBAND_ACCESS32(HW_SPI_RSER_ADDR(x), BP_SPI_RSER_RFDF_RE) = (v)) /*@}*/ /*! * @name Register SPI_RSER, field RFOF_RE[19] (RW) * * Enables the RFOF flag in the SR to generate an interrupt request. * * Values: * - 0 - RFOF interrupt requests are disabled. * - 1 - RFOF interrupt requests are enabled. */ /*@{*/ #define BP_SPI_RSER_RFOF_RE (19U) /*!< Bit position for SPI_RSER_RFOF_RE. */ #define BM_SPI_RSER_RFOF_RE (0x00080000U) /*!< Bit mask for SPI_RSER_RFOF_RE. */ #define BS_SPI_RSER_RFOF_RE (1U) /*!< Bit field size in bits for SPI_RSER_RFOF_RE. */ /*! @brief Read current value of the SPI_RSER_RFOF_RE field. */ #define BR_SPI_RSER_RFOF_RE(x) (BITBAND_ACCESS32(HW_SPI_RSER_ADDR(x), BP_SPI_RSER_RFOF_RE)) /*! @brief Format value for bitfield SPI_RSER_RFOF_RE. */ #define BF_SPI_RSER_RFOF_RE(v) ((uint32_t)((uint32_t)(v) << BP_SPI_RSER_RFOF_RE) & BM_SPI_RSER_RFOF_RE) /*! @brief Set the RFOF_RE field to a new value. */ #define BW_SPI_RSER_RFOF_RE(x, v) (BITBAND_ACCESS32(HW_SPI_RSER_ADDR(x), BP_SPI_RSER_RFOF_RE) = (v)) /*@}*/ /*! * @name Register SPI_RSER, field TFFF_DIRS[24] (RW) * * Selects between generating a DMA request or an interrupt request. When * SR[TFFF] and RSER[TFFF_RE] are set, this field selects between generating an * interrupt request or a DMA request. * * Values: * - 0 - TFFF flag generates interrupt requests. * - 1 - TFFF flag generates DMA requests. */ /*@{*/ #define BP_SPI_RSER_TFFF_DIRS (24U) /*!< Bit position for SPI_RSER_TFFF_DIRS. */ #define BM_SPI_RSER_TFFF_DIRS (0x01000000U) /*!< Bit mask for SPI_RSER_TFFF_DIRS. */ #define BS_SPI_RSER_TFFF_DIRS (1U) /*!< Bit field size in bits for SPI_RSER_TFFF_DIRS. */ /*! @brief Read current value of the SPI_RSER_TFFF_DIRS field. */ #define BR_SPI_RSER_TFFF_DIRS(x) (BITBAND_ACCESS32(HW_SPI_RSER_ADDR(x), BP_SPI_RSER_TFFF_DIRS)) /*! @brief Format value for bitfield SPI_RSER_TFFF_DIRS. */ #define BF_SPI_RSER_TFFF_DIRS(v) ((uint32_t)((uint32_t)(v) << BP_SPI_RSER_TFFF_DIRS) & BM_SPI_RSER_TFFF_DIRS) /*! @brief Set the TFFF_DIRS field to a new value. */ #define BW_SPI_RSER_TFFF_DIRS(x, v) (BITBAND_ACCESS32(HW_SPI_RSER_ADDR(x), BP_SPI_RSER_TFFF_DIRS) = (v)) /*@}*/ /*! * @name Register SPI_RSER, field TFFF_RE[25] (RW) * * Enables the TFFF flag in the SR to generate a request. The TFFF_DIRS bit * selects between generating an interrupt request or a DMA request. * * Values: * - 0 - TFFF interrupts or DMA requests are disabled. * - 1 - TFFF interrupts or DMA requests are enabled. */ /*@{*/ #define BP_SPI_RSER_TFFF_RE (25U) /*!< Bit position for SPI_RSER_TFFF_RE. */ #define BM_SPI_RSER_TFFF_RE (0x02000000U) /*!< Bit mask for SPI_RSER_TFFF_RE. */ #define BS_SPI_RSER_TFFF_RE (1U) /*!< Bit field size in bits for SPI_RSER_TFFF_RE. */ /*! @brief Read current value of the SPI_RSER_TFFF_RE field. */ #define BR_SPI_RSER_TFFF_RE(x) (BITBAND_ACCESS32(HW_SPI_RSER_ADDR(x), BP_SPI_RSER_TFFF_RE)) /*! @brief Format value for bitfield SPI_RSER_TFFF_RE. */ #define BF_SPI_RSER_TFFF_RE(v) ((uint32_t)((uint32_t)(v) << BP_SPI_RSER_TFFF_RE) & BM_SPI_RSER_TFFF_RE) /*! @brief Set the TFFF_RE field to a new value. */ #define BW_SPI_RSER_TFFF_RE(x, v) (BITBAND_ACCESS32(HW_SPI_RSER_ADDR(x), BP_SPI_RSER_TFFF_RE) = (v)) /*@}*/ /*! * @name Register SPI_RSER, field TFUF_RE[27] (RW) * * Enables the TFUF flag in the SR to generate an interrupt request. * * Values: * - 0 - TFUF interrupt requests are disabled. * - 1 - TFUF interrupt requests are enabled. */ /*@{*/ #define BP_SPI_RSER_TFUF_RE (27U) /*!< Bit position for SPI_RSER_TFUF_RE. */ #define BM_SPI_RSER_TFUF_RE (0x08000000U) /*!< Bit mask for SPI_RSER_TFUF_RE. */ #define BS_SPI_RSER_TFUF_RE (1U) /*!< Bit field size in bits for SPI_RSER_TFUF_RE. */ /*! @brief Read current value of the SPI_RSER_TFUF_RE field. */ #define BR_SPI_RSER_TFUF_RE(x) (BITBAND_ACCESS32(HW_SPI_RSER_ADDR(x), BP_SPI_RSER_TFUF_RE)) /*! @brief Format value for bitfield SPI_RSER_TFUF_RE. */ #define BF_SPI_RSER_TFUF_RE(v) ((uint32_t)((uint32_t)(v) << BP_SPI_RSER_TFUF_RE) & BM_SPI_RSER_TFUF_RE) /*! @brief Set the TFUF_RE field to a new value. */ #define BW_SPI_RSER_TFUF_RE(x, v) (BITBAND_ACCESS32(HW_SPI_RSER_ADDR(x), BP_SPI_RSER_TFUF_RE) = (v)) /*@}*/ /*! * @name Register SPI_RSER, field EOQF_RE[28] (RW) * * Enables the EOQF flag in the SR to generate an interrupt request. * * Values: * - 0 - EOQF interrupt requests are disabled. * - 1 - EOQF interrupt requests are enabled. */ /*@{*/ #define BP_SPI_RSER_EOQF_RE (28U) /*!< Bit position for SPI_RSER_EOQF_RE. */ #define BM_SPI_RSER_EOQF_RE (0x10000000U) /*!< Bit mask for SPI_RSER_EOQF_RE. */ #define BS_SPI_RSER_EOQF_RE (1U) /*!< Bit field size in bits for SPI_RSER_EOQF_RE. */ /*! @brief Read current value of the SPI_RSER_EOQF_RE field. */ #define BR_SPI_RSER_EOQF_RE(x) (BITBAND_ACCESS32(HW_SPI_RSER_ADDR(x), BP_SPI_RSER_EOQF_RE)) /*! @brief Format value for bitfield SPI_RSER_EOQF_RE. */ #define BF_SPI_RSER_EOQF_RE(v) ((uint32_t)((uint32_t)(v) << BP_SPI_RSER_EOQF_RE) & BM_SPI_RSER_EOQF_RE) /*! @brief Set the EOQF_RE field to a new value. */ #define BW_SPI_RSER_EOQF_RE(x, v) (BITBAND_ACCESS32(HW_SPI_RSER_ADDR(x), BP_SPI_RSER_EOQF_RE) = (v)) /*@}*/ /*! * @name Register SPI_RSER, field TCF_RE[31] (RW) * * Enables TCF flag in the SR to generate an interrupt request. * * Values: * - 0 - TCF interrupt requests are disabled. * - 1 - TCF interrupt requests are enabled. */ /*@{*/ #define BP_SPI_RSER_TCF_RE (31U) /*!< Bit position for SPI_RSER_TCF_RE. */ #define BM_SPI_RSER_TCF_RE (0x80000000U) /*!< Bit mask for SPI_RSER_TCF_RE. */ #define BS_SPI_RSER_TCF_RE (1U) /*!< Bit field size in bits for SPI_RSER_TCF_RE. */ /*! @brief Read current value of the SPI_RSER_TCF_RE field. */ #define BR_SPI_RSER_TCF_RE(x) (BITBAND_ACCESS32(HW_SPI_RSER_ADDR(x), BP_SPI_RSER_TCF_RE)) /*! @brief Format value for bitfield SPI_RSER_TCF_RE. */ #define BF_SPI_RSER_TCF_RE(v) ((uint32_t)((uint32_t)(v) << BP_SPI_RSER_TCF_RE) & BM_SPI_RSER_TCF_RE) /*! @brief Set the TCF_RE field to a new value. */ #define BW_SPI_RSER_TCF_RE(x, v) (BITBAND_ACCESS32(HW_SPI_RSER_ADDR(x), BP_SPI_RSER_TCF_RE) = (v)) /*@}*/ /******************************************************************************* * HW_SPI_PUSHR - PUSH TX FIFO Register In Master Mode ******************************************************************************/ /*! * @brief HW_SPI_PUSHR - PUSH TX FIFO Register In Master Mode (RW) * * Reset value: 0x00000000U * * Specifies data to be transferred to the TX FIFO. An 8- or 16-bit write access * transfers all 32 bits to the TX FIFO. In Master mode, the register transfers * 16 bits of data and 16 bits of command information. In Slave mode, all 32 bits * can be used as data, supporting up to 32-bit frame operation. A read access * of PUSHR returns the topmost TX FIFO entry. When the module is disabled, * writing to this register does not update the FIFO. Therefore, any reads performed * while the module is disabled return the last PUSHR write performed while the * module was still enabled. */ typedef union _hw_spi_pushr { uint32_t U; struct _hw_spi_pushr_bitfields { uint32_t TXDATA : 16; /*!< [15:0] Transmit Data */ uint32_t PCS : 6; /*!< [21:16] */ uint32_t RESERVED0 : 4; /*!< [25:22] */ uint32_t CTCNT : 1; /*!< [26] Clear Transfer Counter */ uint32_t EOQ : 1; /*!< [27] End Of Queue */ uint32_t CTAS : 3; /*!< [30:28] Clock and Transfer Attributes Select * */ uint32_t CONT : 1; /*!< [31] Continuous Peripheral Chip Select Enable * */ } B; } hw_spi_pushr_t; /*! * @name Constants and macros for entire SPI_PUSHR register */ /*@{*/ #define HW_SPI_PUSHR_ADDR(x) ((x) + 0x34U) #define HW_SPI_PUSHR(x) (*(__IO hw_spi_pushr_t *) HW_SPI_PUSHR_ADDR(x)) #define HW_SPI_PUSHR_RD(x) (HW_SPI_PUSHR(x).U) #define HW_SPI_PUSHR_WR(x, v) (HW_SPI_PUSHR(x).U = (v)) #define HW_SPI_PUSHR_SET(x, v) (HW_SPI_PUSHR_WR(x, HW_SPI_PUSHR_RD(x) | (v))) #define HW_SPI_PUSHR_CLR(x, v) (HW_SPI_PUSHR_WR(x, HW_SPI_PUSHR_RD(x) & ~(v))) #define HW_SPI_PUSHR_TOG(x, v) (HW_SPI_PUSHR_WR(x, HW_SPI_PUSHR_RD(x) ^ (v))) /*@}*/ /* * Constants & macros for individual SPI_PUSHR bitfields */ /*! * @name Register SPI_PUSHR, field TXDATA[15:0] (RW) * * Holds SPI data to be transferred according to the associated SPI command. */ /*@{*/ #define BP_SPI_PUSHR_TXDATA (0U) /*!< Bit position for SPI_PUSHR_TXDATA. */ #define BM_SPI_PUSHR_TXDATA (0x0000FFFFU) /*!< Bit mask for SPI_PUSHR_TXDATA. */ #define BS_SPI_PUSHR_TXDATA (16U) /*!< Bit field size in bits for SPI_PUSHR_TXDATA. */ /*! @brief Read current value of the SPI_PUSHR_TXDATA field. */ #define BR_SPI_PUSHR_TXDATA(x) (HW_SPI_PUSHR(x).B.TXDATA) /*! @brief Format value for bitfield SPI_PUSHR_TXDATA. */ #define BF_SPI_PUSHR_TXDATA(v) ((uint32_t)((uint32_t)(v) << BP_SPI_PUSHR_TXDATA) & BM_SPI_PUSHR_TXDATA) /*! @brief Set the TXDATA field to a new value. */ #define BW_SPI_PUSHR_TXDATA(x, v) (HW_SPI_PUSHR_WR(x, (HW_SPI_PUSHR_RD(x) & ~BM_SPI_PUSHR_TXDATA) | BF_SPI_PUSHR_TXDATA(v))) /*@}*/ /*! * @name Register SPI_PUSHR, field PCS[21:16] (RW) * * Select which PCS signals are to be asserted for the transfer. Refer to the * chip configuration details for the number of PCS signals used in this MCU. * * Values: * - 0 - Negate the PCS[x] signal. * - 1 - Assert the PCS[x] signal. */ /*@{*/ #define BP_SPI_PUSHR_PCS (16U) /*!< Bit position for SPI_PUSHR_PCS. */ #define BM_SPI_PUSHR_PCS (0x003F0000U) /*!< Bit mask for SPI_PUSHR_PCS. */ #define BS_SPI_PUSHR_PCS (6U) /*!< Bit field size in bits for SPI_PUSHR_PCS. */ /*! @brief Read current value of the SPI_PUSHR_PCS field. */ #define BR_SPI_PUSHR_PCS(x) (HW_SPI_PUSHR(x).B.PCS) /*! @brief Format value for bitfield SPI_PUSHR_PCS. */ #define BF_SPI_PUSHR_PCS(v) ((uint32_t)((uint32_t)(v) << BP_SPI_PUSHR_PCS) & BM_SPI_PUSHR_PCS) /*! @brief Set the PCS field to a new value. */ #define BW_SPI_PUSHR_PCS(x, v) (HW_SPI_PUSHR_WR(x, (HW_SPI_PUSHR_RD(x) & ~BM_SPI_PUSHR_PCS) | BF_SPI_PUSHR_PCS(v))) /*@}*/ /*! * @name Register SPI_PUSHR, field CTCNT[26] (RW) * * Clears the TCNT field in the TCR register. The TCNT field is cleared before * the module starts transmitting the current SPI frame. * * Values: * - 0 - Do not clear the TCR[TCNT] field. * - 1 - Clear the TCR[TCNT] field. */ /*@{*/ #define BP_SPI_PUSHR_CTCNT (26U) /*!< Bit position for SPI_PUSHR_CTCNT. */ #define BM_SPI_PUSHR_CTCNT (0x04000000U) /*!< Bit mask for SPI_PUSHR_CTCNT. */ #define BS_SPI_PUSHR_CTCNT (1U) /*!< Bit field size in bits for SPI_PUSHR_CTCNT. */ /*! @brief Read current value of the SPI_PUSHR_CTCNT field. */ #define BR_SPI_PUSHR_CTCNT(x) (BITBAND_ACCESS32(HW_SPI_PUSHR_ADDR(x), BP_SPI_PUSHR_CTCNT)) /*! @brief Format value for bitfield SPI_PUSHR_CTCNT. */ #define BF_SPI_PUSHR_CTCNT(v) ((uint32_t)((uint32_t)(v) << BP_SPI_PUSHR_CTCNT) & BM_SPI_PUSHR_CTCNT) /*! @brief Set the CTCNT field to a new value. */ #define BW_SPI_PUSHR_CTCNT(x, v) (BITBAND_ACCESS32(HW_SPI_PUSHR_ADDR(x), BP_SPI_PUSHR_CTCNT) = (v)) /*@}*/ /*! * @name Register SPI_PUSHR, field EOQ[27] (RW) * * Host software uses this bit to signal to the module that the current SPI * transfer is the last in a queue. At the end of the transfer, the EOQF bit in the * SR is set. * * Values: * - 0 - The SPI data is not the last data to transfer. * - 1 - The SPI data is the last data to transfer. */ /*@{*/ #define BP_SPI_PUSHR_EOQ (27U) /*!< Bit position for SPI_PUSHR_EOQ. */ #define BM_SPI_PUSHR_EOQ (0x08000000U) /*!< Bit mask for SPI_PUSHR_EOQ. */ #define BS_SPI_PUSHR_EOQ (1U) /*!< Bit field size in bits for SPI_PUSHR_EOQ. */ /*! @brief Read current value of the SPI_PUSHR_EOQ field. */ #define BR_SPI_PUSHR_EOQ(x) (BITBAND_ACCESS32(HW_SPI_PUSHR_ADDR(x), BP_SPI_PUSHR_EOQ)) /*! @brief Format value for bitfield SPI_PUSHR_EOQ. */ #define BF_SPI_PUSHR_EOQ(v) ((uint32_t)((uint32_t)(v) << BP_SPI_PUSHR_EOQ) & BM_SPI_PUSHR_EOQ) /*! @brief Set the EOQ field to a new value. */ #define BW_SPI_PUSHR_EOQ(x, v) (BITBAND_ACCESS32(HW_SPI_PUSHR_ADDR(x), BP_SPI_PUSHR_EOQ) = (v)) /*@}*/ /*! * @name Register SPI_PUSHR, field CTAS[30:28] (RW) * * Selects which CTAR to use in master mode to specify the transfer attributes * for the associated SPI frame. In SPI Slave mode, CTAR0 is used. See the chip * configuration details to determine how many CTARs this device has. You should * not program a value in this field for a register that is not present. * * Values: * - 000 - CTAR0 * - 001 - CTAR1 * - 010 - Reserved * - 011 - Reserved * - 100 - Reserved * - 101 - Reserved * - 110 - Reserved * - 111 - Reserved */ /*@{*/ #define BP_SPI_PUSHR_CTAS (28U) /*!< Bit position for SPI_PUSHR_CTAS. */ #define BM_SPI_PUSHR_CTAS (0x70000000U) /*!< Bit mask for SPI_PUSHR_CTAS. */ #define BS_SPI_PUSHR_CTAS (3U) /*!< Bit field size in bits for SPI_PUSHR_CTAS. */ /*! @brief Read current value of the SPI_PUSHR_CTAS field. */ #define BR_SPI_PUSHR_CTAS(x) (HW_SPI_PUSHR(x).B.CTAS) /*! @brief Format value for bitfield SPI_PUSHR_CTAS. */ #define BF_SPI_PUSHR_CTAS(v) ((uint32_t)((uint32_t)(v) << BP_SPI_PUSHR_CTAS) & BM_SPI_PUSHR_CTAS) /*! @brief Set the CTAS field to a new value. */ #define BW_SPI_PUSHR_CTAS(x, v) (HW_SPI_PUSHR_WR(x, (HW_SPI_PUSHR_RD(x) & ~BM_SPI_PUSHR_CTAS) | BF_SPI_PUSHR_CTAS(v))) /*@}*/ /*! * @name Register SPI_PUSHR, field CONT[31] (RW) * * Selects a continuous selection format. The bit is used in SPI Master mode. * The bit enables the selected PCS signals to remain asserted between transfers. * * Values: * - 0 - Return PCSn signals to their inactive state between transfers. * - 1 - Keep PCSn signals asserted between transfers. */ /*@{*/ #define BP_SPI_PUSHR_CONT (31U) /*!< Bit position for SPI_PUSHR_CONT. */ #define BM_SPI_PUSHR_CONT (0x80000000U) /*!< Bit mask for SPI_PUSHR_CONT. */ #define BS_SPI_PUSHR_CONT (1U) /*!< Bit field size in bits for SPI_PUSHR_CONT. */ /*! @brief Read current value of the SPI_PUSHR_CONT field. */ #define BR_SPI_PUSHR_CONT(x) (BITBAND_ACCESS32(HW_SPI_PUSHR_ADDR(x), BP_SPI_PUSHR_CONT)) /*! @brief Format value for bitfield SPI_PUSHR_CONT. */ #define BF_SPI_PUSHR_CONT(v) ((uint32_t)((uint32_t)(v) << BP_SPI_PUSHR_CONT) & BM_SPI_PUSHR_CONT) /*! @brief Set the CONT field to a new value. */ #define BW_SPI_PUSHR_CONT(x, v) (BITBAND_ACCESS32(HW_SPI_PUSHR_ADDR(x), BP_SPI_PUSHR_CONT) = (v)) /*@}*/ /******************************************************************************* * HW_SPI_PUSHR_SLAVE - PUSH TX FIFO Register In Slave Mode ******************************************************************************/ /*! * @brief HW_SPI_PUSHR_SLAVE - PUSH TX FIFO Register In Slave Mode (RW) * * Reset value: 0x00000000U * * Specifies data to be transferred to the TX FIFO. An 8- or 16-bit write access * to PUSHR transfers all 32 bits to the TX FIFO. In master mode, the register * transfers 16 bits of data and 16 bits of command information to the TX FIFO. In * slave mode, all 32 register bits can be used as data, supporting up to 32-bit * SPI Frame operation. */ typedef union _hw_spi_pushr_slave { uint32_t U; struct _hw_spi_pushr_slave_bitfields { uint32_t TXDATA : 32; /*!< [31:0] Transmit Data */ } B; } hw_spi_pushr_slave_t; /*! * @name Constants and macros for entire SPI_PUSHR_SLAVE register */ /*@{*/ #define HW_SPI_PUSHR_SLAVE_ADDR(x) ((x) + 0x34U) #define HW_SPI_PUSHR_SLAVE(x) (*(__IO hw_spi_pushr_slave_t *) HW_SPI_PUSHR_SLAVE_ADDR(x)) #define HW_SPI_PUSHR_SLAVE_RD(x) (HW_SPI_PUSHR_SLAVE(x).U) #define HW_SPI_PUSHR_SLAVE_WR(x, v) (HW_SPI_PUSHR_SLAVE(x).U = (v)) #define HW_SPI_PUSHR_SLAVE_SET(x, v) (HW_SPI_PUSHR_SLAVE_WR(x, HW_SPI_PUSHR_SLAVE_RD(x) | (v))) #define HW_SPI_PUSHR_SLAVE_CLR(x, v) (HW_SPI_PUSHR_SLAVE_WR(x, HW_SPI_PUSHR_SLAVE_RD(x) & ~(v))) #define HW_SPI_PUSHR_SLAVE_TOG(x, v) (HW_SPI_PUSHR_SLAVE_WR(x, HW_SPI_PUSHR_SLAVE_RD(x) ^ (v))) /*@}*/ /* * Constants & macros for individual SPI_PUSHR_SLAVE bitfields */ /*! * @name Register SPI_PUSHR_SLAVE, field TXDATA[31:0] (RW) * * Holds SPI data to be transferred according to the associated SPI command. */ /*@{*/ #define BP_SPI_PUSHR_SLAVE_TXDATA (0U) /*!< Bit position for SPI_PUSHR_SLAVE_TXDATA. */ #define BM_SPI_PUSHR_SLAVE_TXDATA (0xFFFFFFFFU) /*!< Bit mask for SPI_PUSHR_SLAVE_TXDATA. */ #define BS_SPI_PUSHR_SLAVE_TXDATA (32U) /*!< Bit field size in bits for SPI_PUSHR_SLAVE_TXDATA. */ /*! @brief Read current value of the SPI_PUSHR_SLAVE_TXDATA field. */ #define BR_SPI_PUSHR_SLAVE_TXDATA(x) (HW_SPI_PUSHR_SLAVE(x).U) /*! @brief Format value for bitfield SPI_PUSHR_SLAVE_TXDATA. */ #define BF_SPI_PUSHR_SLAVE_TXDATA(v) ((uint32_t)((uint32_t)(v) << BP_SPI_PUSHR_SLAVE_TXDATA) & BM_SPI_PUSHR_SLAVE_TXDATA) /*! @brief Set the TXDATA field to a new value. */ #define BW_SPI_PUSHR_SLAVE_TXDATA(x, v) (HW_SPI_PUSHR_SLAVE_WR(x, v)) /*@}*/ /******************************************************************************* * HW_SPI_POPR - POP RX FIFO Register ******************************************************************************/ /*! * @brief HW_SPI_POPR - POP RX FIFO Register (RO) * * Reset value: 0x00000000U * * POPR is used to read the RX FIFO. Eight- or sixteen-bit read accesses to the * POPR have the same effect on the RX FIFO as 32-bit read accesses. A write to * this register will generate a Transfer Error. */ typedef union _hw_spi_popr { uint32_t U; struct _hw_spi_popr_bitfields { uint32_t RXDATA : 32; /*!< [31:0] Received Data */ } B; } hw_spi_popr_t; /*! * @name Constants and macros for entire SPI_POPR register */ /*@{*/ #define HW_SPI_POPR_ADDR(x) ((x) + 0x38U) #define HW_SPI_POPR(x) (*(__I hw_spi_popr_t *) HW_SPI_POPR_ADDR(x)) #define HW_SPI_POPR_RD(x) (HW_SPI_POPR(x).U) /*@}*/ /* * Constants & macros for individual SPI_POPR bitfields */ /*! * @name Register SPI_POPR, field RXDATA[31:0] (RO) * * Contains the SPI data from the RX FIFO entry to which the Pop Next Data * Pointer points. */ /*@{*/ #define BP_SPI_POPR_RXDATA (0U) /*!< Bit position for SPI_POPR_RXDATA. */ #define BM_SPI_POPR_RXDATA (0xFFFFFFFFU) /*!< Bit mask for SPI_POPR_RXDATA. */ #define BS_SPI_POPR_RXDATA (32U) /*!< Bit field size in bits for SPI_POPR_RXDATA. */ /*! @brief Read current value of the SPI_POPR_RXDATA field. */ #define BR_SPI_POPR_RXDATA(x) (HW_SPI_POPR(x).U) /*@}*/ /******************************************************************************* * HW_SPI_TXFRn - Transmit FIFO Registers ******************************************************************************/ /*! * @brief HW_SPI_TXFRn - Transmit FIFO Registers (RO) * * Reset value: 0x00000000U * * TXFRn registers provide visibility into the TX FIFO for debugging purposes. * Each register is an entry in the TX FIFO. The registers are read-only and * cannot be modified. Reading the TXFRx registers does not alter the state of the TX * FIFO. */ typedef union _hw_spi_txfrn { uint32_t U; struct _hw_spi_txfrn_bitfields { uint32_t TXDATA : 16; /*!< [15:0] Transmit Data */ uint32_t TXCMD_TXDATA : 16; /*!< [31:16] Transmit Command or Transmit * Data */ } B; } hw_spi_txfrn_t; /*! * @name Constants and macros for entire SPI_TXFRn register */ /*@{*/ #define HW_SPI_TXFRn_COUNT (4U) #define HW_SPI_TXFRn_ADDR(x, n) ((x) + 0x3CU + (0x4U * (n))) #define HW_SPI_TXFRn(x, n) (*(__I hw_spi_txfrn_t *) HW_SPI_TXFRn_ADDR(x, n)) #define HW_SPI_TXFRn_RD(x, n) (HW_SPI_TXFRn(x, n).U) /*@}*/ /* * Constants & macros for individual SPI_TXFRn bitfields */ /*! * @name Register SPI_TXFRn, field TXDATA[15:0] (RO) * * Contains the SPI data to be shifted out. */ /*@{*/ #define BP_SPI_TXFRn_TXDATA (0U) /*!< Bit position for SPI_TXFRn_TXDATA. */ #define BM_SPI_TXFRn_TXDATA (0x0000FFFFU) /*!< Bit mask for SPI_TXFRn_TXDATA. */ #define BS_SPI_TXFRn_TXDATA (16U) /*!< Bit field size in bits for SPI_TXFRn_TXDATA. */ /*! @brief Read current value of the SPI_TXFRn_TXDATA field. */ #define BR_SPI_TXFRn_TXDATA(x, n) (HW_SPI_TXFRn(x, n).B.TXDATA) /*@}*/ /*! * @name Register SPI_TXFRn, field TXCMD_TXDATA[31:16] (RO) * * In Master mode the TXCMD field contains the command that sets the transfer * attributes for the SPI data. In Slave mode, the TXDATA contains 16 MSB bits of * the SPI data to be shifted out. */ /*@{*/ #define BP_SPI_TXFRn_TXCMD_TXDATA (16U) /*!< Bit position for SPI_TXFRn_TXCMD_TXDATA. */ #define BM_SPI_TXFRn_TXCMD_TXDATA (0xFFFF0000U) /*!< Bit mask for SPI_TXFRn_TXCMD_TXDATA. */ #define BS_SPI_TXFRn_TXCMD_TXDATA (16U) /*!< Bit field size in bits for SPI_TXFRn_TXCMD_TXDATA. */ /*! @brief Read current value of the SPI_TXFRn_TXCMD_TXDATA field. */ #define BR_SPI_TXFRn_TXCMD_TXDATA(x, n) (HW_SPI_TXFRn(x, n).B.TXCMD_TXDATA) /*@}*/ /******************************************************************************* * HW_SPI_RXFRn - Receive FIFO Registers ******************************************************************************/ /*! * @brief HW_SPI_RXFRn - Receive FIFO Registers (RO) * * Reset value: 0x00000000U * * RXFRn provide visibility into the RX FIFO for debugging purposes. Each * register is an entry in the RX FIFO. The RXFR registers are read-only. Reading the * RXFRx registers does not alter the state of the RX FIFO. */ typedef union _hw_spi_rxfrn { uint32_t U; struct _hw_spi_rxfrn_bitfields { uint32_t RXDATA : 32; /*!< [31:0] Receive Data */ } B; } hw_spi_rxfrn_t; /*! * @name Constants and macros for entire SPI_RXFRn register */ /*@{*/ #define HW_SPI_RXFRn_COUNT (4U) #define HW_SPI_RXFRn_ADDR(x, n) ((x) + 0x7CU + (0x4U * (n))) #define HW_SPI_RXFRn(x, n) (*(__I hw_spi_rxfrn_t *) HW_SPI_RXFRn_ADDR(x, n)) #define HW_SPI_RXFRn_RD(x, n) (HW_SPI_RXFRn(x, n).U) /*@}*/ /* * Constants & macros for individual SPI_RXFRn bitfields */ /*! * @name Register SPI_RXFRn, field RXDATA[31:0] (RO) * * Contains the received SPI data. */ /*@{*/ #define BP_SPI_RXFRn_RXDATA (0U) /*!< Bit position for SPI_RXFRn_RXDATA. */ #define BM_SPI_RXFRn_RXDATA (0xFFFFFFFFU) /*!< Bit mask for SPI_RXFRn_RXDATA. */ #define BS_SPI_RXFRn_RXDATA (32U) /*!< Bit field size in bits for SPI_RXFRn_RXDATA. */ /*! @brief Read current value of the SPI_RXFRn_RXDATA field. */ #define BR_SPI_RXFRn_RXDATA(x, n) (HW_SPI_RXFRn(x, n).U) /*@}*/ /* ** Start of section using anonymous unions */ #if defined(__ARMCC_VERSION) #pragma push #pragma anon_unions #elif defined(__CWCC__) #pragma push #pragma cpp_extensions on #elif defined(__GNUC__) /* anonymous unions are enabled by default */ #elif defined(__IAR_SYSTEMS_ICC__) #pragma language=extended #else #error Not supported compiler type #endif /******************************************************************************* * hw_spi_t - module struct ******************************************************************************/ /*! * @brief All SPI module registers. */ #pragma pack(1) typedef struct _hw_spi { __IO hw_spi_mcr_t MCR; /*!< [0x0] Module Configuration Register */ uint8_t _reserved0[4]; __IO hw_spi_tcr_t TCR; /*!< [0x8] Transfer Count Register */ union { __IO hw_spi_ctarn_t CTARn[2]; /*!< [0xC] Clock and Transfer Attributes Register (In Master Mode) */ __IO hw_spi_ctarn_slave_t CTARn_SLAVE[1]; /*!< [0xC] Clock and Transfer Attributes Register (In Slave Mode) */ }; uint8_t _reserved1[24]; __IO hw_spi_sr_t SR; /*!< [0x2C] Status Register */ __IO hw_spi_rser_t RSER; /*!< [0x30] DMA/Interrupt Request Select and Enable Register */ union { __IO hw_spi_pushr_t PUSHR; /*!< [0x34] PUSH TX FIFO Register In Master Mode */ __IO hw_spi_pushr_slave_t PUSHR_SLAVE; /*!< [0x34] PUSH TX FIFO Register In Slave Mode */ }; __I hw_spi_popr_t POPR; /*!< [0x38] POP RX FIFO Register */ __I hw_spi_txfrn_t TXFRn[4]; /*!< [0x3C] Transmit FIFO Registers */ uint8_t _reserved2[48]; __I hw_spi_rxfrn_t RXFRn[4]; /*!< [0x7C] Receive FIFO Registers */ } hw_spi_t; #pragma pack() /*! @brief Macro to access all SPI registers. */ /*! @param x SPI module instance base address. */ /*! @return Reference (not a pointer) to the registers struct. To get a pointer to the struct, * use the '&' operator, like &HW_SPI(SPI0_BASE). */ #define HW_SPI(x) (*(hw_spi_t *)(x)) /* ** End of section using anonymous unions */ #if defined(__ARMCC_VERSION) #pragma pop #elif defined(__CWCC__) #pragma pop #elif defined(__GNUC__) /* leave anonymous unions enabled */ #elif defined(__IAR_SYSTEMS_ICC__) #pragma language=default #else #error Not supported compiler type #endif #endif /* __HW_SPI_REGISTERS_H__ */ /* EOF */ ================================================ FILE: Zelig/mbed/TARGET_K64F/TARGET_Freescale/TARGET_KPSDK_MCUS/TARGET_MCU_K64F/device/device/MK64F12/MK64F12_uart.h ================================================ /* ** ################################################################### ** Compilers: Keil ARM C/C++ Compiler ** Freescale C/C++ for Embedded ARM ** GNU C Compiler ** IAR ANSI C/C++ Compiler for ARM ** ** Reference manual: K64P144M120SF5RM, Rev.2, January 2014 ** Version: rev. 2.5, 2014-02-10 ** Build: b140604 ** ** Abstract: ** Extension to the CMSIS register access layer header. ** ** Copyright (c) 2014 Freescale Semiconductor, Inc. ** All rights reserved. ** ** Redistribution and use in source and binary forms, with or without modification, ** are permitted provided that the following conditions are met: ** ** o Redistributions of source code must retain the above copyright notice, this list ** of conditions and the following disclaimer. ** ** o Redistributions in binary form must reproduce the above copyright notice, this ** list of conditions and the following disclaimer in the documentation and/or ** other materials provided with the distribution. ** ** o Neither the name of Freescale Semiconductor, Inc. nor the names of its ** contributors may be used to endorse or promote products derived from this ** software without specific prior written permission. ** ** THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ** ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED ** WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE ** DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT 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. ** ** http: www.freescale.com ** mail: support@freescale.com ** ** Revisions: ** - rev. 1.0 (2013-08-12) ** Initial version. ** - rev. 2.0 (2013-10-29) ** Register accessor macros added to the memory map. ** Symbols for Processor Expert memory map compatibility added to the memory map. ** Startup file for gcc has been updated according to CMSIS 3.2. ** System initialization updated. ** MCG - registers updated. ** PORTA, PORTB, PORTC, PORTE - registers for digital filter removed. ** - rev. 2.1 (2013-10-30) ** Definition of BITBAND macros updated to support peripherals with 32-bit acces disabled. ** - rev. 2.2 (2013-12-09) ** DMA - EARS register removed. ** AIPS0, AIPS1 - MPRA register updated. ** - rev. 2.3 (2014-01-24) ** Update according to reference manual rev. 2 ** ENET, MCG, MCM, SIM, USB - registers updated ** - rev. 2.4 (2014-02-10) ** The declaration of clock configurations has been moved to separate header file system_MK64F12.h ** Update of SystemInit() and SystemCoreClockUpdate() functions. ** - rev. 2.5 (2014-02-10) ** The declaration of clock configurations has been moved to separate header file system_MK64F12.h ** Update of SystemInit() and SystemCoreClockUpdate() functions. ** Module access macro module_BASES replaced by module_BASE_PTRS. ** ** ################################################################### */ /* * WARNING! DO NOT EDIT THIS FILE DIRECTLY! * * This file was generated automatically and any changes may be lost. */ #ifndef __HW_UART_REGISTERS_H__ #define __HW_UART_REGISTERS_H__ #include "MK64F12.h" #include "fsl_bitaccess.h" /* * MK64F12 UART * * Serial Communication Interface * * Registers defined in this header file: * - HW_UART_BDH - UART Baud Rate Registers: High * - HW_UART_BDL - UART Baud Rate Registers: Low * - HW_UART_C1 - UART Control Register 1 * - HW_UART_C2 - UART Control Register 2 * - HW_UART_S1 - UART Status Register 1 * - HW_UART_S2 - UART Status Register 2 * - HW_UART_C3 - UART Control Register 3 * - HW_UART_D - UART Data Register * - HW_UART_MA1 - UART Match Address Registers 1 * - HW_UART_MA2 - UART Match Address Registers 2 * - HW_UART_C4 - UART Control Register 4 * - HW_UART_C5 - UART Control Register 5 * - HW_UART_ED - UART Extended Data Register * - HW_UART_MODEM - UART Modem Register * - HW_UART_IR - UART Infrared Register * - HW_UART_PFIFO - UART FIFO Parameters * - HW_UART_CFIFO - UART FIFO Control Register * - HW_UART_SFIFO - UART FIFO Status Register * - HW_UART_TWFIFO - UART FIFO Transmit Watermark * - HW_UART_TCFIFO - UART FIFO Transmit Count * - HW_UART_RWFIFO - UART FIFO Receive Watermark * - HW_UART_RCFIFO - UART FIFO Receive Count * - HW_UART_C7816 - UART 7816 Control Register * - HW_UART_IE7816 - UART 7816 Interrupt Enable Register * - HW_UART_IS7816 - UART 7816 Interrupt Status Register * - HW_UART_WP7816T0 - UART 7816 Wait Parameter Register * - HW_UART_WP7816T1 - UART 7816 Wait Parameter Register * - HW_UART_WN7816 - UART 7816 Wait N Register * - HW_UART_WF7816 - UART 7816 Wait FD Register * - HW_UART_ET7816 - UART 7816 Error Threshold Register * - HW_UART_TL7816 - UART 7816 Transmit Length Register * * - hw_uart_t - Struct containing all module registers. */ #define HW_UART_INSTANCE_COUNT (6U) /*!< Number of instances of the UART module. */ #define HW_UART0 (0U) /*!< Instance number for UART0. */ #define HW_UART1 (1U) /*!< Instance number for UART1. */ #define HW_UART2 (2U) /*!< Instance number for UART2. */ #define HW_UART3 (3U) /*!< Instance number for UART3. */ #define HW_UART4 (4U) /*!< Instance number for UART4. */ #define HW_UART5 (5U) /*!< Instance number for UART5. */ /******************************************************************************* * HW_UART_BDH - UART Baud Rate Registers: High ******************************************************************************/ /*! * @brief HW_UART_BDH - UART Baud Rate Registers: High (RW) * * Reset value: 0x00U * * This register, along with the BDL register, controls the prescale divisor for * UART baud rate generation. To update the 13-bit baud rate setting * (SBR[12:0]), first write to BDH to buffer the high half of the new value and then write * to BDL. The working value in BDH does not change until BDL is written. BDL is * reset to a nonzero value, but after reset, the baud rate generator remains * disabled until the first time the receiver or transmitter is enabled, that is, * when C2[RE] or C2[TE] is set. */ typedef union _hw_uart_bdh { uint8_t U; struct _hw_uart_bdh_bitfields { uint8_t SBR : 5; /*!< [4:0] UART Baud Rate Bits */ uint8_t SBNS : 1; /*!< [5] Stop Bit Number Select */ uint8_t RXEDGIE : 1; /*!< [6] RxD Input Active Edge Interrupt Enable * */ uint8_t LBKDIE : 1; /*!< [7] LIN Break Detect Interrupt or DMA * Request Enable */ } B; } hw_uart_bdh_t; /*! * @name Constants and macros for entire UART_BDH register */ /*@{*/ #define HW_UART_BDH_ADDR(x) ((x) + 0x0U) #define HW_UART_BDH(x) (*(__IO hw_uart_bdh_t *) HW_UART_BDH_ADDR(x)) #define HW_UART_BDH_RD(x) (HW_UART_BDH(x).U) #define HW_UART_BDH_WR(x, v) (HW_UART_BDH(x).U = (v)) #define HW_UART_BDH_SET(x, v) (HW_UART_BDH_WR(x, HW_UART_BDH_RD(x) | (v))) #define HW_UART_BDH_CLR(x, v) (HW_UART_BDH_WR(x, HW_UART_BDH_RD(x) & ~(v))) #define HW_UART_BDH_TOG(x, v) (HW_UART_BDH_WR(x, HW_UART_BDH_RD(x) ^ (v))) /*@}*/ /* * Constants & macros for individual UART_BDH bitfields */ /*! * @name Register UART_BDH, field SBR[4:0] (RW) * * The baud rate for the UART is determined by the 13 SBR fields. See Baud rate * generation for details. The baud rate generator is disabled until C2[TE] or * C2[RE] is set for the first time after reset.The baud rate generator is disabled * when SBR = 0. Writing to BDH has no effect without writing to BDL, because * writing to BDH puts the data in a temporary location until BDL is written. */ /*@{*/ #define BP_UART_BDH_SBR (0U) /*!< Bit position for UART_BDH_SBR. */ #define BM_UART_BDH_SBR (0x1FU) /*!< Bit mask for UART_BDH_SBR. */ #define BS_UART_BDH_SBR (5U) /*!< Bit field size in bits for UART_BDH_SBR. */ /*! @brief Read current value of the UART_BDH_SBR field. */ #define BR_UART_BDH_SBR(x) (HW_UART_BDH(x).B.SBR) /*! @brief Format value for bitfield UART_BDH_SBR. */ #define BF_UART_BDH_SBR(v) ((uint8_t)((uint8_t)(v) << BP_UART_BDH_SBR) & BM_UART_BDH_SBR) /*! @brief Set the SBR field to a new value. */ #define BW_UART_BDH_SBR(x, v) (HW_UART_BDH_WR(x, (HW_UART_BDH_RD(x) & ~BM_UART_BDH_SBR) | BF_UART_BDH_SBR(v))) /*@}*/ /*! * @name Register UART_BDH, field SBNS[5] (RW) * * SBNS selects the number of stop bits present in a data frame. This field * valid for all 8, 9 and 10 bit data formats available. This field is not valid when * C7816[ISO7816E] is enabled. * * Values: * - 0 - Data frame consists of a single stop bit. * - 1 - Data frame consists of two stop bits. */ /*@{*/ #define BP_UART_BDH_SBNS (5U) /*!< Bit position for UART_BDH_SBNS. */ #define BM_UART_BDH_SBNS (0x20U) /*!< Bit mask for UART_BDH_SBNS. */ #define BS_UART_BDH_SBNS (1U) /*!< Bit field size in bits for UART_BDH_SBNS. */ /*! @brief Read current value of the UART_BDH_SBNS field. */ #define BR_UART_BDH_SBNS(x) (BITBAND_ACCESS8(HW_UART_BDH_ADDR(x), BP_UART_BDH_SBNS)) /*! @brief Format value for bitfield UART_BDH_SBNS. */ #define BF_UART_BDH_SBNS(v) ((uint8_t)((uint8_t)(v) << BP_UART_BDH_SBNS) & BM_UART_BDH_SBNS) /*! @brief Set the SBNS field to a new value. */ #define BW_UART_BDH_SBNS(x, v) (BITBAND_ACCESS8(HW_UART_BDH_ADDR(x), BP_UART_BDH_SBNS) = (v)) /*@}*/ /*! * @name Register UART_BDH, field RXEDGIE[6] (RW) * * Enables the receive input active edge, RXEDGIF, to generate interrupt * requests. * * Values: * - 0 - Hardware interrupts from RXEDGIF disabled using polling. * - 1 - RXEDGIF interrupt request enabled. */ /*@{*/ #define BP_UART_BDH_RXEDGIE (6U) /*!< Bit position for UART_BDH_RXEDGIE. */ #define BM_UART_BDH_RXEDGIE (0x40U) /*!< Bit mask for UART_BDH_RXEDGIE. */ #define BS_UART_BDH_RXEDGIE (1U) /*!< Bit field size in bits for UART_BDH_RXEDGIE. */ /*! @brief Read current value of the UART_BDH_RXEDGIE field. */ #define BR_UART_BDH_RXEDGIE(x) (BITBAND_ACCESS8(HW_UART_BDH_ADDR(x), BP_UART_BDH_RXEDGIE)) /*! @brief Format value for bitfield UART_BDH_RXEDGIE. */ #define BF_UART_BDH_RXEDGIE(v) ((uint8_t)((uint8_t)(v) << BP_UART_BDH_RXEDGIE) & BM_UART_BDH_RXEDGIE) /*! @brief Set the RXEDGIE field to a new value. */ #define BW_UART_BDH_RXEDGIE(x, v) (BITBAND_ACCESS8(HW_UART_BDH_ADDR(x), BP_UART_BDH_RXEDGIE) = (v)) /*@}*/ /*! * @name Register UART_BDH, field LBKDIE[7] (RW) * * Enables the LIN break detect flag, LBKDIF, to generate interrupt requests * based on the state of LBKDDMAS. or DMA transfer requests, * * Values: * - 0 - LBKDIF interrupt and DMA transfer requests disabled. * - 1 - LBKDIF interrupt or DMA transfer requests enabled. */ /*@{*/ #define BP_UART_BDH_LBKDIE (7U) /*!< Bit position for UART_BDH_LBKDIE. */ #define BM_UART_BDH_LBKDIE (0x80U) /*!< Bit mask for UART_BDH_LBKDIE. */ #define BS_UART_BDH_LBKDIE (1U) /*!< Bit field size in bits for UART_BDH_LBKDIE. */ /*! @brief Read current value of the UART_BDH_LBKDIE field. */ #define BR_UART_BDH_LBKDIE(x) (BITBAND_ACCESS8(HW_UART_BDH_ADDR(x), BP_UART_BDH_LBKDIE)) /*! @brief Format value for bitfield UART_BDH_LBKDIE. */ #define BF_UART_BDH_LBKDIE(v) ((uint8_t)((uint8_t)(v) << BP_UART_BDH_LBKDIE) & BM_UART_BDH_LBKDIE) /*! @brief Set the LBKDIE field to a new value. */ #define BW_UART_BDH_LBKDIE(x, v) (BITBAND_ACCESS8(HW_UART_BDH_ADDR(x), BP_UART_BDH_LBKDIE) = (v)) /*@}*/ /******************************************************************************* * HW_UART_BDL - UART Baud Rate Registers: Low ******************************************************************************/ /*! * @brief HW_UART_BDL - UART Baud Rate Registers: Low (RW) * * Reset value: 0x04U * * This register, along with the BDH register, controls the prescale divisor for * UART baud rate generation. To update the 13-bit baud rate setting, SBR[12:0], * first write to BDH to buffer the high half of the new value and then write to * BDL. The working value in BDH does not change until BDL is written. BDL is * reset to a nonzero value, but after reset, the baud rate generator remains * disabled until the first time the receiver or transmitter is enabled, that is, when * C2[RE] or C2[TE] is set. */ typedef union _hw_uart_bdl { uint8_t U; struct _hw_uart_bdl_bitfields { uint8_t SBR : 8; /*!< [7:0] UART Baud Rate Bits */ } B; } hw_uart_bdl_t; /*! * @name Constants and macros for entire UART_BDL register */ /*@{*/ #define HW_UART_BDL_ADDR(x) ((x) + 0x1U) #define HW_UART_BDL(x) (*(__IO hw_uart_bdl_t *) HW_UART_BDL_ADDR(x)) #define HW_UART_BDL_RD(x) (HW_UART_BDL(x).U) #define HW_UART_BDL_WR(x, v) (HW_UART_BDL(x).U = (v)) #define HW_UART_BDL_SET(x, v) (HW_UART_BDL_WR(x, HW_UART_BDL_RD(x) | (v))) #define HW_UART_BDL_CLR(x, v) (HW_UART_BDL_WR(x, HW_UART_BDL_RD(x) & ~(v))) #define HW_UART_BDL_TOG(x, v) (HW_UART_BDL_WR(x, HW_UART_BDL_RD(x) ^ (v))) /*@}*/ /* * Constants & macros for individual UART_BDL bitfields */ /*! * @name Register UART_BDL, field SBR[7:0] (RW) * * The baud rate for the UART is determined by the 13 SBR fields. See Baud rate * generation for details. The baud rate generator is disabled until C2[TE] or * C2[RE] is set for the first time after reset.The baud rate generator is disabled * when SBR = 0. Writing to BDH has no effect without writing to BDL, because * writing to BDH puts the data in a temporary location until BDL is written. When * the 1/32 narrow pulse width is selected for infrared (IrDA), the baud rate * fields must be even, the least significant bit is 0. See MODEM register for more * details. */ /*@{*/ #define BP_UART_BDL_SBR (0U) /*!< Bit position for UART_BDL_SBR. */ #define BM_UART_BDL_SBR (0xFFU) /*!< Bit mask for UART_BDL_SBR. */ #define BS_UART_BDL_SBR (8U) /*!< Bit field size in bits for UART_BDL_SBR. */ /*! @brief Read current value of the UART_BDL_SBR field. */ #define BR_UART_BDL_SBR(x) (HW_UART_BDL(x).U) /*! @brief Format value for bitfield UART_BDL_SBR. */ #define BF_UART_BDL_SBR(v) ((uint8_t)((uint8_t)(v) << BP_UART_BDL_SBR) & BM_UART_BDL_SBR) /*! @brief Set the SBR field to a new value. */ #define BW_UART_BDL_SBR(x, v) (HW_UART_BDL_WR(x, v)) /*@}*/ /******************************************************************************* * HW_UART_C1 - UART Control Register 1 ******************************************************************************/ /*! * @brief HW_UART_C1 - UART Control Register 1 (RW) * * Reset value: 0x00U * * This read/write register controls various optional features of the UART * system. */ typedef union _hw_uart_c1 { uint8_t U; struct _hw_uart_c1_bitfields { uint8_t PT : 1; /*!< [0] Parity Type */ uint8_t PE : 1; /*!< [1] Parity Enable */ uint8_t ILT : 1; /*!< [2] Idle Line Type Select */ uint8_t WAKE : 1; /*!< [3] Receiver Wakeup Method Select */ uint8_t M : 1; /*!< [4] 9-bit or 8-bit Mode Select */ uint8_t RSRC : 1; /*!< [5] Receiver Source Select */ uint8_t UARTSWAI : 1; /*!< [6] UART Stops in Wait Mode */ uint8_t LOOPS : 1; /*!< [7] Loop Mode Select */ } B; } hw_uart_c1_t; /*! * @name Constants and macros for entire UART_C1 register */ /*@{*/ #define HW_UART_C1_ADDR(x) ((x) + 0x2U) #define HW_UART_C1(x) (*(__IO hw_uart_c1_t *) HW_UART_C1_ADDR(x)) #define HW_UART_C1_RD(x) (HW_UART_C1(x).U) #define HW_UART_C1_WR(x, v) (HW_UART_C1(x).U = (v)) #define HW_UART_C1_SET(x, v) (HW_UART_C1_WR(x, HW_UART_C1_RD(x) | (v))) #define HW_UART_C1_CLR(x, v) (HW_UART_C1_WR(x, HW_UART_C1_RD(x) & ~(v))) #define HW_UART_C1_TOG(x, v) (HW_UART_C1_WR(x, HW_UART_C1_RD(x) ^ (v))) /*@}*/ /* * Constants & macros for individual UART_C1 bitfields */ /*! * @name Register UART_C1, field PT[0] (RW) * * Determines whether the UART generates and checks for even parity or odd * parity. With even parity, an even number of 1s clears the parity bit and an odd * number of 1s sets the parity bit. With odd parity, an odd number of 1s clears the * parity bit and an even number of 1s sets the parity bit. This field must be * cleared when C7816[ISO_7816E] is set/enabled. * * Values: * - 0 - Even parity. * - 1 - Odd parity. */ /*@{*/ #define BP_UART_C1_PT (0U) /*!< Bit position for UART_C1_PT. */ #define BM_UART_C1_PT (0x01U) /*!< Bit mask for UART_C1_PT. */ #define BS_UART_C1_PT (1U) /*!< Bit field size in bits for UART_C1_PT. */ /*! @brief Read current value of the UART_C1_PT field. */ #define BR_UART_C1_PT(x) (BITBAND_ACCESS8(HW_UART_C1_ADDR(x), BP_UART_C1_PT)) /*! @brief Format value for bitfield UART_C1_PT. */ #define BF_UART_C1_PT(v) ((uint8_t)((uint8_t)(v) << BP_UART_C1_PT) & BM_UART_C1_PT) /*! @brief Set the PT field to a new value. */ #define BW_UART_C1_PT(x, v) (BITBAND_ACCESS8(HW_UART_C1_ADDR(x), BP_UART_C1_PT) = (v)) /*@}*/ /*! * @name Register UART_C1, field PE[1] (RW) * * Enables the parity function. When parity is enabled, parity function inserts * a parity bit in the bit position immediately preceding the stop bit. This * field must be set when C7816[ISO_7816E] is set/enabled. * * Values: * - 0 - Parity function disabled. * - 1 - Parity function enabled. */ /*@{*/ #define BP_UART_C1_PE (1U) /*!< Bit position for UART_C1_PE. */ #define BM_UART_C1_PE (0x02U) /*!< Bit mask for UART_C1_PE. */ #define BS_UART_C1_PE (1U) /*!< Bit field size in bits for UART_C1_PE. */ /*! @brief Read current value of the UART_C1_PE field. */ #define BR_UART_C1_PE(x) (BITBAND_ACCESS8(HW_UART_C1_ADDR(x), BP_UART_C1_PE)) /*! @brief Format value for bitfield UART_C1_PE. */ #define BF_UART_C1_PE(v) ((uint8_t)((uint8_t)(v) << BP_UART_C1_PE) & BM_UART_C1_PE) /*! @brief Set the PE field to a new value. */ #define BW_UART_C1_PE(x, v) (BITBAND_ACCESS8(HW_UART_C1_ADDR(x), BP_UART_C1_PE) = (v)) /*@}*/ /*! * @name Register UART_C1, field ILT[2] (RW) * * Determines when the receiver starts counting logic 1s as idle character bits. * The count begins either after a valid start bit or after the stop bit. If the * count begins after the start bit, then a string of logic 1s preceding the * stop bit can cause false recognition of an idle character. Beginning the count * after the stop bit avoids false idle character recognition, but requires * properly synchronized transmissions. In case the UART is programmed with ILT = 1, a * logic of 1'b0 is automatically shifted after a received stop bit, therefore * resetting the idle count. In case the UART is programmed for IDLE line wakeup * (RWU = 1 and WAKE = 0), ILT has no effect on when the receiver starts counting * logic 1s as idle character bits. In idle line wakeup, an idle character is * recognized at anytime the receiver sees 10, 11, or 12 1s depending on the M, PE, * and C4[M10] fields. * * Values: * - 0 - Idle character bit count starts after start bit. * - 1 - Idle character bit count starts after stop bit. */ /*@{*/ #define BP_UART_C1_ILT (2U) /*!< Bit position for UART_C1_ILT. */ #define BM_UART_C1_ILT (0x04U) /*!< Bit mask for UART_C1_ILT. */ #define BS_UART_C1_ILT (1U) /*!< Bit field size in bits for UART_C1_ILT. */ /*! @brief Read current value of the UART_C1_ILT field. */ #define BR_UART_C1_ILT(x) (BITBAND_ACCESS8(HW_UART_C1_ADDR(x), BP_UART_C1_ILT)) /*! @brief Format value for bitfield UART_C1_ILT. */ #define BF_UART_C1_ILT(v) ((uint8_t)((uint8_t)(v) << BP_UART_C1_ILT) & BM_UART_C1_ILT) /*! @brief Set the ILT field to a new value. */ #define BW_UART_C1_ILT(x, v) (BITBAND_ACCESS8(HW_UART_C1_ADDR(x), BP_UART_C1_ILT) = (v)) /*@}*/ /*! * @name Register UART_C1, field WAKE[3] (RW) * * Determines which condition wakes the UART: Address mark in the most * significant bit position of a received data character, or An idle condition on the * receive pin input signal. * * Values: * - 0 - Idle line wakeup. * - 1 - Address mark wakeup. */ /*@{*/ #define BP_UART_C1_WAKE (3U) /*!< Bit position for UART_C1_WAKE. */ #define BM_UART_C1_WAKE (0x08U) /*!< Bit mask for UART_C1_WAKE. */ #define BS_UART_C1_WAKE (1U) /*!< Bit field size in bits for UART_C1_WAKE. */ /*! @brief Read current value of the UART_C1_WAKE field. */ #define BR_UART_C1_WAKE(x) (BITBAND_ACCESS8(HW_UART_C1_ADDR(x), BP_UART_C1_WAKE)) /*! @brief Format value for bitfield UART_C1_WAKE. */ #define BF_UART_C1_WAKE(v) ((uint8_t)((uint8_t)(v) << BP_UART_C1_WAKE) & BM_UART_C1_WAKE) /*! @brief Set the WAKE field to a new value. */ #define BW_UART_C1_WAKE(x, v) (BITBAND_ACCESS8(HW_UART_C1_ADDR(x), BP_UART_C1_WAKE) = (v)) /*@}*/ /*! * @name Register UART_C1, field M[4] (RW) * * This field must be set when C7816[ISO_7816E] is set/enabled. * * Values: * - 0 - Normal-start + 8 data bits (MSB/LSB first as determined by MSBF) + stop. * - 1 - Use-start + 9 data bits (MSB/LSB first as determined by MSBF) + stop. */ /*@{*/ #define BP_UART_C1_M (4U) /*!< Bit position for UART_C1_M. */ #define BM_UART_C1_M (0x10U) /*!< Bit mask for UART_C1_M. */ #define BS_UART_C1_M (1U) /*!< Bit field size in bits for UART_C1_M. */ /*! @brief Read current value of the UART_C1_M field. */ #define BR_UART_C1_M(x) (BITBAND_ACCESS8(HW_UART_C1_ADDR(x), BP_UART_C1_M)) /*! @brief Format value for bitfield UART_C1_M. */ #define BF_UART_C1_M(v) ((uint8_t)((uint8_t)(v) << BP_UART_C1_M) & BM_UART_C1_M) /*! @brief Set the M field to a new value. */ #define BW_UART_C1_M(x, v) (BITBAND_ACCESS8(HW_UART_C1_ADDR(x), BP_UART_C1_M) = (v)) /*@}*/ /*! * @name Register UART_C1, field RSRC[5] (RW) * * This field has no meaning or effect unless the LOOPS field is set. When LOOPS * is set, the RSRC field determines the source for the receiver shift register * input. * * Values: * - 0 - Selects internal loop back mode. The receiver input is internally * connected to transmitter output. * - 1 - Single wire UART mode where the receiver input is connected to the * transmit pin input signal. */ /*@{*/ #define BP_UART_C1_RSRC (5U) /*!< Bit position for UART_C1_RSRC. */ #define BM_UART_C1_RSRC (0x20U) /*!< Bit mask for UART_C1_RSRC. */ #define BS_UART_C1_RSRC (1U) /*!< Bit field size in bits for UART_C1_RSRC. */ /*! @brief Read current value of the UART_C1_RSRC field. */ #define BR_UART_C1_RSRC(x) (BITBAND_ACCESS8(HW_UART_C1_ADDR(x), BP_UART_C1_RSRC)) /*! @brief Format value for bitfield UART_C1_RSRC. */ #define BF_UART_C1_RSRC(v) ((uint8_t)((uint8_t)(v) << BP_UART_C1_RSRC) & BM_UART_C1_RSRC) /*! @brief Set the RSRC field to a new value. */ #define BW_UART_C1_RSRC(x, v) (BITBAND_ACCESS8(HW_UART_C1_ADDR(x), BP_UART_C1_RSRC) = (v)) /*@}*/ /*! * @name Register UART_C1, field UARTSWAI[6] (RW) * * Values: * - 0 - UART clock continues to run in Wait mode. * - 1 - UART clock freezes while CPU is in Wait mode. */ /*@{*/ #define BP_UART_C1_UARTSWAI (6U) /*!< Bit position for UART_C1_UARTSWAI. */ #define BM_UART_C1_UARTSWAI (0x40U) /*!< Bit mask for UART_C1_UARTSWAI. */ #define BS_UART_C1_UARTSWAI (1U) /*!< Bit field size in bits for UART_C1_UARTSWAI. */ /*! @brief Read current value of the UART_C1_UARTSWAI field. */ #define BR_UART_C1_UARTSWAI(x) (BITBAND_ACCESS8(HW_UART_C1_ADDR(x), BP_UART_C1_UARTSWAI)) /*! @brief Format value for bitfield UART_C1_UARTSWAI. */ #define BF_UART_C1_UARTSWAI(v) ((uint8_t)((uint8_t)(v) << BP_UART_C1_UARTSWAI) & BM_UART_C1_UARTSWAI) /*! @brief Set the UARTSWAI field to a new value. */ #define BW_UART_C1_UARTSWAI(x, v) (BITBAND_ACCESS8(HW_UART_C1_ADDR(x), BP_UART_C1_UARTSWAI) = (v)) /*@}*/ /*! * @name Register UART_C1, field LOOPS[7] (RW) * * When LOOPS is set, the RxD pin is disconnected from the UART and the * transmitter output is internally connected to the receiver input. The transmitter and * the receiver must be enabled to use the loop function. * * Values: * - 0 - Normal operation. * - 1 - Loop mode where transmitter output is internally connected to receiver * input. The receiver input is determined by RSRC. */ /*@{*/ #define BP_UART_C1_LOOPS (7U) /*!< Bit position for UART_C1_LOOPS. */ #define BM_UART_C1_LOOPS (0x80U) /*!< Bit mask for UART_C1_LOOPS. */ #define BS_UART_C1_LOOPS (1U) /*!< Bit field size in bits for UART_C1_LOOPS. */ /*! @brief Read current value of the UART_C1_LOOPS field. */ #define BR_UART_C1_LOOPS(x) (BITBAND_ACCESS8(HW_UART_C1_ADDR(x), BP_UART_C1_LOOPS)) /*! @brief Format value for bitfield UART_C1_LOOPS. */ #define BF_UART_C1_LOOPS(v) ((uint8_t)((uint8_t)(v) << BP_UART_C1_LOOPS) & BM_UART_C1_LOOPS) /*! @brief Set the LOOPS field to a new value. */ #define BW_UART_C1_LOOPS(x, v) (BITBAND_ACCESS8(HW_UART_C1_ADDR(x), BP_UART_C1_LOOPS) = (v)) /*@}*/ /******************************************************************************* * HW_UART_C2 - UART Control Register 2 ******************************************************************************/ /*! * @brief HW_UART_C2 - UART Control Register 2 (RW) * * Reset value: 0x00U * * This register can be read or written at any time. */ typedef union _hw_uart_c2 { uint8_t U; struct _hw_uart_c2_bitfields { uint8_t SBK : 1; /*!< [0] Send Break */ uint8_t RWU : 1; /*!< [1] Receiver Wakeup Control */ uint8_t RE : 1; /*!< [2] Receiver Enable */ uint8_t TE : 1; /*!< [3] Transmitter Enable */ uint8_t ILIE : 1; /*!< [4] Idle Line Interrupt DMA Transfer Enable */ uint8_t RIE : 1; /*!< [5] Receiver Full Interrupt or DMA Transfer * Enable */ uint8_t TCIE : 1; /*!< [6] Transmission Complete Interrupt or DMA * Transfer Enable */ uint8_t TIE : 1; /*!< [7] Transmitter Interrupt or DMA Transfer * Enable. */ } B; } hw_uart_c2_t; /*! * @name Constants and macros for entire UART_C2 register */ /*@{*/ #define HW_UART_C2_ADDR(x) ((x) + 0x3U) #define HW_UART_C2(x) (*(__IO hw_uart_c2_t *) HW_UART_C2_ADDR(x)) #define HW_UART_C2_RD(x) (HW_UART_C2(x).U) #define HW_UART_C2_WR(x, v) (HW_UART_C2(x).U = (v)) #define HW_UART_C2_SET(x, v) (HW_UART_C2_WR(x, HW_UART_C2_RD(x) | (v))) #define HW_UART_C2_CLR(x, v) (HW_UART_C2_WR(x, HW_UART_C2_RD(x) & ~(v))) #define HW_UART_C2_TOG(x, v) (HW_UART_C2_WR(x, HW_UART_C2_RD(x) ^ (v))) /*@}*/ /* * Constants & macros for individual UART_C2 bitfields */ /*! * @name Register UART_C2, field SBK[0] (RW) * * Toggling SBK sends one break character from the following: See Transmitting * break characters for the number of logic 0s for the different configurations. * Toggling implies clearing the SBK field before the break character has finished * transmitting. As long as SBK is set, the transmitter continues to send * complete break characters (10, 11, or 12 bits, or 13 or 14 bits, or 15 or 16 bits). * Ensure that C2[TE] is asserted atleast 1 clock before assertion of this bit. * 10, 11, or 12 logic 0s if S2[BRK13] is cleared 13 or 14 logic 0s if S2[BRK13] * is set. 15 or 16 logic 0s if BDH[SBNS] is set. This field must be cleared when * C7816[ISO_7816E] is set. * * Values: * - 0 - Normal transmitter operation. * - 1 - Queue break characters to be sent. */ /*@{*/ #define BP_UART_C2_SBK (0U) /*!< Bit position for UART_C2_SBK. */ #define BM_UART_C2_SBK (0x01U) /*!< Bit mask for UART_C2_SBK. */ #define BS_UART_C2_SBK (1U) /*!< Bit field size in bits for UART_C2_SBK. */ /*! @brief Read current value of the UART_C2_SBK field. */ #define BR_UART_C2_SBK(x) (BITBAND_ACCESS8(HW_UART_C2_ADDR(x), BP_UART_C2_SBK)) /*! @brief Format value for bitfield UART_C2_SBK. */ #define BF_UART_C2_SBK(v) ((uint8_t)((uint8_t)(v) << BP_UART_C2_SBK) & BM_UART_C2_SBK) /*! @brief Set the SBK field to a new value. */ #define BW_UART_C2_SBK(x, v) (BITBAND_ACCESS8(HW_UART_C2_ADDR(x), BP_UART_C2_SBK) = (v)) /*@}*/ /*! * @name Register UART_C2, field RWU[1] (RW) * * This field can be set to place the UART receiver in a standby state. RWU * automatically clears when an RWU event occurs, that is, an IDLE event when * C1[WAKE] is clear or an address match when C1[WAKE] is set. This field must be * cleared when C7816[ISO_7816E] is set. RWU must be set only with C1[WAKE] = 0 (wakeup * on idle) if the channel is currently not idle. This can be determined by * S2[RAF]. If the flag is set to wake up an IDLE event and the channel is already * idle, it is possible that the UART will discard data. This is because the data * must be received or a LIN break detected after an IDLE is detected before IDLE * is allowed to reasserted. * * Values: * - 0 - Normal operation. * - 1 - RWU enables the wakeup function and inhibits further receiver interrupt * requests. Normally, hardware wakes the receiver by automatically clearing * RWU. */ /*@{*/ #define BP_UART_C2_RWU (1U) /*!< Bit position for UART_C2_RWU. */ #define BM_UART_C2_RWU (0x02U) /*!< Bit mask for UART_C2_RWU. */ #define BS_UART_C2_RWU (1U) /*!< Bit field size in bits for UART_C2_RWU. */ /*! @brief Read current value of the UART_C2_RWU field. */ #define BR_UART_C2_RWU(x) (BITBAND_ACCESS8(HW_UART_C2_ADDR(x), BP_UART_C2_RWU)) /*! @brief Format value for bitfield UART_C2_RWU. */ #define BF_UART_C2_RWU(v) ((uint8_t)((uint8_t)(v) << BP_UART_C2_RWU) & BM_UART_C2_RWU) /*! @brief Set the RWU field to a new value. */ #define BW_UART_C2_RWU(x, v) (BITBAND_ACCESS8(HW_UART_C2_ADDR(x), BP_UART_C2_RWU) = (v)) /*@}*/ /*! * @name Register UART_C2, field RE[2] (RW) * * Enables the UART receiver. * * Values: * - 0 - Receiver off. * - 1 - Receiver on. */ /*@{*/ #define BP_UART_C2_RE (2U) /*!< Bit position for UART_C2_RE. */ #define BM_UART_C2_RE (0x04U) /*!< Bit mask for UART_C2_RE. */ #define BS_UART_C2_RE (1U) /*!< Bit field size in bits for UART_C2_RE. */ /*! @brief Read current value of the UART_C2_RE field. */ #define BR_UART_C2_RE(x) (BITBAND_ACCESS8(HW_UART_C2_ADDR(x), BP_UART_C2_RE)) /*! @brief Format value for bitfield UART_C2_RE. */ #define BF_UART_C2_RE(v) ((uint8_t)((uint8_t)(v) << BP_UART_C2_RE) & BM_UART_C2_RE) /*! @brief Set the RE field to a new value. */ #define BW_UART_C2_RE(x, v) (BITBAND_ACCESS8(HW_UART_C2_ADDR(x), BP_UART_C2_RE) = (v)) /*@}*/ /*! * @name Register UART_C2, field TE[3] (RW) * * Enables the UART transmitter. TE can be used to queue an idle preamble by * clearing and then setting TE. When C7816[ISO_7816E] is set/enabled and * C7816[TTYPE] = 1, this field is automatically cleared after the requested block has been * transmitted. This condition is detected when TL7816[TLEN] = 0 and four * additional characters are transmitted. * * Values: * - 0 - Transmitter off. * - 1 - Transmitter on. */ /*@{*/ #define BP_UART_C2_TE (3U) /*!< Bit position for UART_C2_TE. */ #define BM_UART_C2_TE (0x08U) /*!< Bit mask for UART_C2_TE. */ #define BS_UART_C2_TE (1U) /*!< Bit field size in bits for UART_C2_TE. */ /*! @brief Read current value of the UART_C2_TE field. */ #define BR_UART_C2_TE(x) (BITBAND_ACCESS8(HW_UART_C2_ADDR(x), BP_UART_C2_TE)) /*! @brief Format value for bitfield UART_C2_TE. */ #define BF_UART_C2_TE(v) ((uint8_t)((uint8_t)(v) << BP_UART_C2_TE) & BM_UART_C2_TE) /*! @brief Set the TE field to a new value. */ #define BW_UART_C2_TE(x, v) (BITBAND_ACCESS8(HW_UART_C2_ADDR(x), BP_UART_C2_TE) = (v)) /*@}*/ /*! * @name Register UART_C2, field ILIE[4] (RW) * * Enables the idle line flag, S1[IDLE], to generate interrupt requestsor DMA * transfer requests based on the state of C5[ILDMAS]. * * Values: * - 0 - IDLE interrupt requests disabled. and DMA transfer * - 1 - IDLE interrupt requests enabled. or DMA transfer */ /*@{*/ #define BP_UART_C2_ILIE (4U) /*!< Bit position for UART_C2_ILIE. */ #define BM_UART_C2_ILIE (0x10U) /*!< Bit mask for UART_C2_ILIE. */ #define BS_UART_C2_ILIE (1U) /*!< Bit field size in bits for UART_C2_ILIE. */ /*! @brief Read current value of the UART_C2_ILIE field. */ #define BR_UART_C2_ILIE(x) (BITBAND_ACCESS8(HW_UART_C2_ADDR(x), BP_UART_C2_ILIE)) /*! @brief Format value for bitfield UART_C2_ILIE. */ #define BF_UART_C2_ILIE(v) ((uint8_t)((uint8_t)(v) << BP_UART_C2_ILIE) & BM_UART_C2_ILIE) /*! @brief Set the ILIE field to a new value. */ #define BW_UART_C2_ILIE(x, v) (BITBAND_ACCESS8(HW_UART_C2_ADDR(x), BP_UART_C2_ILIE) = (v)) /*@}*/ /*! * @name Register UART_C2, field RIE[5] (RW) * * Enables S1[RDRF] to generate interrupt requests or DMA transfer requests, * based on the state of C5[RDMAS]. * * Values: * - 0 - RDRF interrupt and DMA transfer requests disabled. * - 1 - RDRF interrupt or DMA transfer requests enabled. */ /*@{*/ #define BP_UART_C2_RIE (5U) /*!< Bit position for UART_C2_RIE. */ #define BM_UART_C2_RIE (0x20U) /*!< Bit mask for UART_C2_RIE. */ #define BS_UART_C2_RIE (1U) /*!< Bit field size in bits for UART_C2_RIE. */ /*! @brief Read current value of the UART_C2_RIE field. */ #define BR_UART_C2_RIE(x) (BITBAND_ACCESS8(HW_UART_C2_ADDR(x), BP_UART_C2_RIE)) /*! @brief Format value for bitfield UART_C2_RIE. */ #define BF_UART_C2_RIE(v) ((uint8_t)((uint8_t)(v) << BP_UART_C2_RIE) & BM_UART_C2_RIE) /*! @brief Set the RIE field to a new value. */ #define BW_UART_C2_RIE(x, v) (BITBAND_ACCESS8(HW_UART_C2_ADDR(x), BP_UART_C2_RIE) = (v)) /*@}*/ /*! * @name Register UART_C2, field TCIE[6] (RW) * * Enables the transmission complete flag, S1[TC], to generate interrupt * requests . or DMA transfer requests based on the state of C5[TCDMAS] If C2[TCIE] and * C5[TCDMAS] are both set, then TIE must be cleared, and D[D] must not be * written unless servicing a DMA request. * * Values: * - 0 - TC interrupt and DMA transfer requests disabled. * - 1 - TC interrupt or DMA transfer requests enabled. */ /*@{*/ #define BP_UART_C2_TCIE (6U) /*!< Bit position for UART_C2_TCIE. */ #define BM_UART_C2_TCIE (0x40U) /*!< Bit mask for UART_C2_TCIE. */ #define BS_UART_C2_TCIE (1U) /*!< Bit field size in bits for UART_C2_TCIE. */ /*! @brief Read current value of the UART_C2_TCIE field. */ #define BR_UART_C2_TCIE(x) (BITBAND_ACCESS8(HW_UART_C2_ADDR(x), BP_UART_C2_TCIE)) /*! @brief Format value for bitfield UART_C2_TCIE. */ #define BF_UART_C2_TCIE(v) ((uint8_t)((uint8_t)(v) << BP_UART_C2_TCIE) & BM_UART_C2_TCIE) /*! @brief Set the TCIE field to a new value. */ #define BW_UART_C2_TCIE(x, v) (BITBAND_ACCESS8(HW_UART_C2_ADDR(x), BP_UART_C2_TCIE) = (v)) /*@}*/ /*! * @name Register UART_C2, field TIE[7] (RW) * * Enables S1[TDRE] to generate interrupt requests or DMA transfer requests, * based on the state of C5[TDMAS]. If C2[TIE] and C5[TDMAS] are both set, then TCIE * must be cleared, and D[D] must not be written unless servicing a DMA request. * * Values: * - 0 - TDRE interrupt and DMA transfer requests disabled. * - 1 - TDRE interrupt or DMA transfer requests enabled. */ /*@{*/ #define BP_UART_C2_TIE (7U) /*!< Bit position for UART_C2_TIE. */ #define BM_UART_C2_TIE (0x80U) /*!< Bit mask for UART_C2_TIE. */ #define BS_UART_C2_TIE (1U) /*!< Bit field size in bits for UART_C2_TIE. */ /*! @brief Read current value of the UART_C2_TIE field. */ #define BR_UART_C2_TIE(x) (BITBAND_ACCESS8(HW_UART_C2_ADDR(x), BP_UART_C2_TIE)) /*! @brief Format value for bitfield UART_C2_TIE. */ #define BF_UART_C2_TIE(v) ((uint8_t)((uint8_t)(v) << BP_UART_C2_TIE) & BM_UART_C2_TIE) /*! @brief Set the TIE field to a new value. */ #define BW_UART_C2_TIE(x, v) (BITBAND_ACCESS8(HW_UART_C2_ADDR(x), BP_UART_C2_TIE) = (v)) /*@}*/ /******************************************************************************* * HW_UART_S1 - UART Status Register 1 ******************************************************************************/ /*! * @brief HW_UART_S1 - UART Status Register 1 (RO) * * Reset value: 0xC0U * * The S1 register provides inputs to the MCU for generation of UART interrupts * or DMA requests. This register can also be polled by the MCU to check the * status of its fields. To clear a flag, the status register should be read followed * by a read or write to D register, depending on the interrupt flag type. Other * instructions can be executed between the two steps as long the handling of * I/O is not compromised, but the order of operations is important for flag * clearing. When a flag is configured to trigger a DMA request, assertion of the * associated DMA done signal from the DMA controller clears the flag. If the * condition that results in the assertion of the flag, interrupt, or DMA request is not * resolved prior to clearing the flag, the flag, and interrupt/DMA request, * reasserts. For example, if the DMA or interrupt service routine fails to write * sufficient data to the transmit buffer to raise it above the watermark level, the * flag reasserts and generates another interrupt or DMA request. Reading an * empty data register to clear one of the flags of the S1 register causes the FIFO * pointers to become misaligned. A receive FIFO flush reinitializes the * pointers. A better way to prevent this situation is to always leave one byte in FIFO * and this byte will be read eventually in clearing the flag bit. */ typedef union _hw_uart_s1 { uint8_t U; struct _hw_uart_s1_bitfields { uint8_t PF : 1; /*!< [0] Parity Error Flag */ uint8_t FE : 1; /*!< [1] Framing Error Flag */ uint8_t NF : 1; /*!< [2] Noise Flag */ uint8_t OR : 1; /*!< [3] Receiver Overrun Flag */ uint8_t IDLE : 1; /*!< [4] Idle Line Flag */ uint8_t RDRF : 1; /*!< [5] Receive Data Register Full Flag */ uint8_t TC : 1; /*!< [6] Transmit Complete Flag */ uint8_t TDRE : 1; /*!< [7] Transmit Data Register Empty Flag */ } B; } hw_uart_s1_t; /*! * @name Constants and macros for entire UART_S1 register */ /*@{*/ #define HW_UART_S1_ADDR(x) ((x) + 0x4U) #define HW_UART_S1(x) (*(__I hw_uart_s1_t *) HW_UART_S1_ADDR(x)) #define HW_UART_S1_RD(x) (HW_UART_S1(x).U) /*@}*/ /* * Constants & macros for individual UART_S1 bitfields */ /*! * @name Register UART_S1, field PF[0] (RO) * * PF is set when PE is set and the parity of the received data does not match * its parity bit. The PF is not set in the case of an overrun condition. When PF * is set, it indicates only that a dataword was received with parity error since * the last time it was cleared. There is no guarantee that the first dataword * read from the receive buffer has a parity error or that there is only one * dataword in the buffer that was received with a parity error, unless the receive * buffer has a depth of one. To clear PF, read S1 and then read D., S2[LBKDE] is * disabled, Within the receive buffer structure the received dataword is tagged * if it is received with a parity error. This information is available by reading * the ED register prior to reading the D register. * * Values: * - 0 - No parity error detected since the last time this flag was cleared. If * the receive buffer has a depth greater than 1, then there may be data in * the receive buffer what was received with a parity error. * - 1 - At least one dataword was received with a parity error since the last * time this flag was cleared. */ /*@{*/ #define BP_UART_S1_PF (0U) /*!< Bit position for UART_S1_PF. */ #define BM_UART_S1_PF (0x01U) /*!< Bit mask for UART_S1_PF. */ #define BS_UART_S1_PF (1U) /*!< Bit field size in bits for UART_S1_PF. */ /*! @brief Read current value of the UART_S1_PF field. */ #define BR_UART_S1_PF(x) (BITBAND_ACCESS8(HW_UART_S1_ADDR(x), BP_UART_S1_PF)) /*@}*/ /*! * @name Register UART_S1, field FE[1] (RO) * * FE is set when a logic 0 is accepted as the stop bit. When BDH[SBNS] is set, * then FE will set when a logic 0 is accepted for either of the two stop bits. * FE does not set in the case of an overrun or while the LIN break detect feature * is enabled (S2[LBKDE] = 1). FE inhibits further data reception until it is * cleared. To clear FE, read S1 with FE set and then read D. The last data in the * receive buffer represents the data that was received with the frame error * enabled. Framing errors are not supported when 7816E is set/enabled. However, if * this flag is set, data is still not received in 7816 mode. * * Values: * - 0 - No framing error detected. * - 1 - Framing error. */ /*@{*/ #define BP_UART_S1_FE (1U) /*!< Bit position for UART_S1_FE. */ #define BM_UART_S1_FE (0x02U) /*!< Bit mask for UART_S1_FE. */ #define BS_UART_S1_FE (1U) /*!< Bit field size in bits for UART_S1_FE. */ /*! @brief Read current value of the UART_S1_FE field. */ #define BR_UART_S1_FE(x) (BITBAND_ACCESS8(HW_UART_S1_ADDR(x), BP_UART_S1_FE)) /*@}*/ /*! * @name Register UART_S1, field NF[2] (RO) * * NF is set when the UART detects noise on the receiver input. NF does not * become set in the case of an overrun or while the LIN break detect feature is * enabled (S2[LBKDE] = 1). When NF is set, it indicates only that a dataword has * been received with noise since the last time it was cleared. There is no * guarantee that the first dataword read from the receive buffer has noise or that there * is only one dataword in the buffer that was received with noise unless the * receive buffer has a depth of one. To clear NF, read S1 and then read D. * * Values: * - 0 - No noise detected since the last time this flag was cleared. If the * receive buffer has a depth greater than 1 then there may be data in the * receiver buffer that was received with noise. * - 1 - At least one dataword was received with noise detected since the last * time the flag was cleared. */ /*@{*/ #define BP_UART_S1_NF (2U) /*!< Bit position for UART_S1_NF. */ #define BM_UART_S1_NF (0x04U) /*!< Bit mask for UART_S1_NF. */ #define BS_UART_S1_NF (1U) /*!< Bit field size in bits for UART_S1_NF. */ /*! @brief Read current value of the UART_S1_NF field. */ #define BR_UART_S1_NF(x) (BITBAND_ACCESS8(HW_UART_S1_ADDR(x), BP_UART_S1_NF)) /*@}*/ /*! * @name Register UART_S1, field OR[3] (RO) * * OR is set when software fails to prevent the receive data register from * overflowing with data. The OR bit is set immediately after the stop bit has been * completely received for the dataword that overflows the buffer and all the other * error flags (FE, NF, and PF) are prevented from setting. The data in the * shift register is lost, but the data already in the UART data registers is not * affected. If the OR flag is set, no data is stored in the data buffer even if * sufficient room exists. Additionally, while the OR flag is set, the RDRF and IDLE * flags are blocked from asserting, that is, transition from an inactive to an * active state. To clear OR, read S1 when OR is set and then read D. See * functional description for more details regarding the operation of the OR bit.If * LBKDE is enabled and a LIN Break is detected, the OR field asserts if S2[LBKDIF] * is not cleared before the next data character is received. In 7816 mode, it is * possible to configure a NACK to be returned by programing C7816[ONACK]. * * Values: * - 0 - No overrun has occurred since the last time the flag was cleared. * - 1 - Overrun has occurred or the overrun flag has not been cleared since the * last overrun occured. */ /*@{*/ #define BP_UART_S1_OR (3U) /*!< Bit position for UART_S1_OR. */ #define BM_UART_S1_OR (0x08U) /*!< Bit mask for UART_S1_OR. */ #define BS_UART_S1_OR (1U) /*!< Bit field size in bits for UART_S1_OR. */ /*! @brief Read current value of the UART_S1_OR field. */ #define BR_UART_S1_OR(x) (BITBAND_ACCESS8(HW_UART_S1_ADDR(x), BP_UART_S1_OR)) /*@}*/ /*! * @name Register UART_S1, field IDLE[4] (RO) * * After the IDLE flag is cleared, a frame must be received (although not * necessarily stored in the data buffer, for example if C2[RWU] is set), or a LIN * break character must set the S2[LBKDIF] flag before an idle condition can set the * IDLE flag. To clear IDLE, read UART status S1 with IDLE set and then read D. * IDLE is set when either of the following appear on the receiver input: 10 * consecutive logic 1s if C1[M] = 0 11 consecutive logic 1s if C1[M] = 1 and C4[M10] * = 0 12 consecutive logic 1s if C1[M] = 1, C4[M10] = 1, and C1[PE] = 1 Idle * detection is not supported when 7816E is set/enabled and hence this flag is * ignored. When RWU is set and WAKE is cleared, an idle line condition sets the IDLE * flag if RWUID is set, else the IDLE flag does not become set. * * Values: * - 0 - Receiver input is either active now or has never become active since * the IDLE flag was last cleared. * - 1 - Receiver input has become idle or the flag has not been cleared since * it last asserted. */ /*@{*/ #define BP_UART_S1_IDLE (4U) /*!< Bit position for UART_S1_IDLE. */ #define BM_UART_S1_IDLE (0x10U) /*!< Bit mask for UART_S1_IDLE. */ #define BS_UART_S1_IDLE (1U) /*!< Bit field size in bits for UART_S1_IDLE. */ /*! @brief Read current value of the UART_S1_IDLE field. */ #define BR_UART_S1_IDLE(x) (BITBAND_ACCESS8(HW_UART_S1_ADDR(x), BP_UART_S1_IDLE)) /*@}*/ /*! * @name Register UART_S1, field RDRF[5] (RO) * * RDRF is set when the number of datawords in the receive buffer is equal to or * more than the number indicated by RWFIFO[RXWATER]. A dataword that is in the * process of being received is not included in the count. To clear RDRF, read S1 * when RDRF is set and then read D. For more efficient interrupt and DMA * operation, read all data except the final value from the buffer, using D/C3[T8]/ED. * Then read S1 and the final data value, resulting in the clearing of the RDRF * flag. Even if RDRF is set, data will continue to be received until an overrun * condition occurs.RDRF is prevented from setting while S2[LBKDE] is set. * Additionally, when S2[LBKDE] is set, the received datawords are stored in the receive * buffer but over-write each other. * * Values: * - 0 - The number of datawords in the receive buffer is less than the number * indicated by RXWATER. * - 1 - The number of datawords in the receive buffer is equal to or greater * than the number indicated by RXWATER at some point in time since this flag * was last cleared. */ /*@{*/ #define BP_UART_S1_RDRF (5U) /*!< Bit position for UART_S1_RDRF. */ #define BM_UART_S1_RDRF (0x20U) /*!< Bit mask for UART_S1_RDRF. */ #define BS_UART_S1_RDRF (1U) /*!< Bit field size in bits for UART_S1_RDRF. */ /*! @brief Read current value of the UART_S1_RDRF field. */ #define BR_UART_S1_RDRF(x) (BITBAND_ACCESS8(HW_UART_S1_ADDR(x), BP_UART_S1_RDRF)) /*@}*/ /*! * @name Register UART_S1, field TC[6] (RO) * * TC is set when the transmit buffer is empty and no data, preamble, or break * character is being transmitted. When TC is set, the transmit data output signal * becomes idle (logic 1). TC is cleared by reading S1 with TC set and then * doing one of the following: When C7816[ISO_7816E] is set/enabled, this field is * set after any NACK signal has been received, but prior to any corresponding * guard times expiring. Writing to D to transmit new data. Queuing a preamble by * clearing and then setting C2[TE]. Queuing a break character by writing 1 to SBK * in C2. * * Values: * - 0 - Transmitter active (sending data, a preamble, or a break). * - 1 - Transmitter idle (transmission activity complete). */ /*@{*/ #define BP_UART_S1_TC (6U) /*!< Bit position for UART_S1_TC. */ #define BM_UART_S1_TC (0x40U) /*!< Bit mask for UART_S1_TC. */ #define BS_UART_S1_TC (1U) /*!< Bit field size in bits for UART_S1_TC. */ /*! @brief Read current value of the UART_S1_TC field. */ #define BR_UART_S1_TC(x) (BITBAND_ACCESS8(HW_UART_S1_ADDR(x), BP_UART_S1_TC)) /*@}*/ /*! * @name Register UART_S1, field TDRE[7] (RO) * * TDRE will set when the number of datawords in the transmit buffer (D and * C3[T8])is equal to or less than the number indicated by TWFIFO[TXWATER]. A * character that is in the process of being transmitted is not included in the count. * To clear TDRE, read S1 when TDRE is set and then write to the UART data * register (D). For more efficient interrupt servicing, all data except the final value * to be written to the buffer must be written to D/C3[T8]. Then S1 can be read * before writing the final data value, resulting in the clearing of the TRDE * flag. This is more efficient because the TDRE reasserts until the watermark has * been exceeded. So, attempting to clear the TDRE with every write will be * ineffective until sufficient data has been written. * * Values: * - 0 - The amount of data in the transmit buffer is greater than the value * indicated by TWFIFO[TXWATER]. * - 1 - The amount of data in the transmit buffer is less than or equal to the * value indicated by TWFIFO[TXWATER] at some point in time since the flag * has been cleared. */ /*@{*/ #define BP_UART_S1_TDRE (7U) /*!< Bit position for UART_S1_TDRE. */ #define BM_UART_S1_TDRE (0x80U) /*!< Bit mask for UART_S1_TDRE. */ #define BS_UART_S1_TDRE (1U) /*!< Bit field size in bits for UART_S1_TDRE. */ /*! @brief Read current value of the UART_S1_TDRE field. */ #define BR_UART_S1_TDRE(x) (BITBAND_ACCESS8(HW_UART_S1_ADDR(x), BP_UART_S1_TDRE)) /*@}*/ /******************************************************************************* * HW_UART_S2 - UART Status Register 2 ******************************************************************************/ /*! * @brief HW_UART_S2 - UART Status Register 2 (RW) * * Reset value: 0x00U * * The S2 register provides inputs to the MCU for generation of UART interrupts * or DMA requests. Also, this register can be polled by the MCU to check the * status of these bits. This register can be read or written at any time, with the * exception of the MSBF and RXINV bits, which should be changed by the user only * between transmit and receive packets. */ typedef union _hw_uart_s2 { uint8_t U; struct _hw_uart_s2_bitfields { uint8_t RAF : 1; /*!< [0] Receiver Active Flag */ uint8_t LBKDE : 1; /*!< [1] LIN Break Detection Enable */ uint8_t BRK13 : 1; /*!< [2] Break Transmit Character Length */ uint8_t RWUID : 1; /*!< [3] Receive Wakeup Idle Detect */ uint8_t RXINV : 1; /*!< [4] Receive Data Inversion */ uint8_t MSBF : 1; /*!< [5] Most Significant Bit First */ uint8_t RXEDGIF : 1; /*!< [6] RxD Pin Active Edge Interrupt Flag */ uint8_t LBKDIF : 1; /*!< [7] LIN Break Detect Interrupt Flag */ } B; } hw_uart_s2_t; /*! * @name Constants and macros for entire UART_S2 register */ /*@{*/ #define HW_UART_S2_ADDR(x) ((x) + 0x5U) #define HW_UART_S2(x) (*(__IO hw_uart_s2_t *) HW_UART_S2_ADDR(x)) #define HW_UART_S2_RD(x) (HW_UART_S2(x).U) #define HW_UART_S2_WR(x, v) (HW_UART_S2(x).U = (v)) #define HW_UART_S2_SET(x, v) (HW_UART_S2_WR(x, HW_UART_S2_RD(x) | (v))) #define HW_UART_S2_CLR(x, v) (HW_UART_S2_WR(x, HW_UART_S2_RD(x) & ~(v))) #define HW_UART_S2_TOG(x, v) (HW_UART_S2_WR(x, HW_UART_S2_RD(x) ^ (v))) /*@}*/ /* * Constants & macros for individual UART_S2 bitfields */ /*! * @name Register UART_S2, field RAF[0] (RO) * * RAF is set when the UART receiver detects a logic 0 during the RT1 time * period of the start bit search. RAF is cleared when the receiver detects an idle * character when C7816[ISO7816E] is cleared/disabled. When C7816[ISO7816E] is * enabled, the RAF is cleared if the C7816[TTYPE] = 0 expires or the C7816[TTYPE] = * 1 expires.In case C7816[ISO7816E] is set and C7816[TTYPE] = 0, it is possible * to configure the guard time to 12. However, if a NACK is required to be * transmitted, the data transfer actually takes 13 ETU with the 13th ETU slot being a * inactive buffer. Therefore, in this situation, the RAF may deassert one ETU * prior to actually being inactive. * * Values: * - 0 - UART receiver idle/inactive waiting for a start bit. * - 1 - UART receiver active, RxD input not idle. */ /*@{*/ #define BP_UART_S2_RAF (0U) /*!< Bit position for UART_S2_RAF. */ #define BM_UART_S2_RAF (0x01U) /*!< Bit mask for UART_S2_RAF. */ #define BS_UART_S2_RAF (1U) /*!< Bit field size in bits for UART_S2_RAF. */ /*! @brief Read current value of the UART_S2_RAF field. */ #define BR_UART_S2_RAF(x) (BITBAND_ACCESS8(HW_UART_S2_ADDR(x), BP_UART_S2_RAF)) /*@}*/ /*! * @name Register UART_S2, field LBKDE[1] (RW) * * Enables the LIN Break detection feature. While LBKDE is set, S1[RDRF], * S1[NF], S1[FE], and S1[PF] are prevented from setting. When LBKDE is set, see . * Overrun operation LBKDE must be cleared when C7816[ISO7816E] is set. * * Values: * - 0 - Break character detection is disabled. * - 1 - Break character is detected at length of 11 bit times if C1[M] = 0 or * 12 bits time if C1[M] = 1. */ /*@{*/ #define BP_UART_S2_LBKDE (1U) /*!< Bit position for UART_S2_LBKDE. */ #define BM_UART_S2_LBKDE (0x02U) /*!< Bit mask for UART_S2_LBKDE. */ #define BS_UART_S2_LBKDE (1U) /*!< Bit field size in bits for UART_S2_LBKDE. */ /*! @brief Read current value of the UART_S2_LBKDE field. */ #define BR_UART_S2_LBKDE(x) (BITBAND_ACCESS8(HW_UART_S2_ADDR(x), BP_UART_S2_LBKDE)) /*! @brief Format value for bitfield UART_S2_LBKDE. */ #define BF_UART_S2_LBKDE(v) ((uint8_t)((uint8_t)(v) << BP_UART_S2_LBKDE) & BM_UART_S2_LBKDE) /*! @brief Set the LBKDE field to a new value. */ #define BW_UART_S2_LBKDE(x, v) (BITBAND_ACCESS8(HW_UART_S2_ADDR(x), BP_UART_S2_LBKDE) = (v)) /*@}*/ /*! * @name Register UART_S2, field BRK13[2] (RW) * * Determines whether the transmit break character is 10, 11, or 12 bits long, * or 13 or 14 bits long. See for the length of the break character for the * different configurations. The detection of a framing error is not affected by this * field. Transmitting break characters * * Values: * - 0 - Break character is 10, 11, or 12 bits long. * - 1 - Break character is 13 or 14 bits long. */ /*@{*/ #define BP_UART_S2_BRK13 (2U) /*!< Bit position for UART_S2_BRK13. */ #define BM_UART_S2_BRK13 (0x04U) /*!< Bit mask for UART_S2_BRK13. */ #define BS_UART_S2_BRK13 (1U) /*!< Bit field size in bits for UART_S2_BRK13. */ /*! @brief Read current value of the UART_S2_BRK13 field. */ #define BR_UART_S2_BRK13(x) (BITBAND_ACCESS8(HW_UART_S2_ADDR(x), BP_UART_S2_BRK13)) /*! @brief Format value for bitfield UART_S2_BRK13. */ #define BF_UART_S2_BRK13(v) ((uint8_t)((uint8_t)(v) << BP_UART_S2_BRK13) & BM_UART_S2_BRK13) /*! @brief Set the BRK13 field to a new value. */ #define BW_UART_S2_BRK13(x, v) (BITBAND_ACCESS8(HW_UART_S2_ADDR(x), BP_UART_S2_BRK13) = (v)) /*@}*/ /*! * @name Register UART_S2, field RWUID[3] (RW) * * When RWU is set and WAKE is cleared, this field controls whether the idle * character that wakes the receiver sets S1[IDLE]. This field must be cleared when * C7816[ISO7816E] is set/enabled. * * Values: * - 0 - S1[IDLE] is not set upon detection of an idle character. * - 1 - S1[IDLE] is set upon detection of an idle character. */ /*@{*/ #define BP_UART_S2_RWUID (3U) /*!< Bit position for UART_S2_RWUID. */ #define BM_UART_S2_RWUID (0x08U) /*!< Bit mask for UART_S2_RWUID. */ #define BS_UART_S2_RWUID (1U) /*!< Bit field size in bits for UART_S2_RWUID. */ /*! @brief Read current value of the UART_S2_RWUID field. */ #define BR_UART_S2_RWUID(x) (BITBAND_ACCESS8(HW_UART_S2_ADDR(x), BP_UART_S2_RWUID)) /*! @brief Format value for bitfield UART_S2_RWUID. */ #define BF_UART_S2_RWUID(v) ((uint8_t)((uint8_t)(v) << BP_UART_S2_RWUID) & BM_UART_S2_RWUID) /*! @brief Set the RWUID field to a new value. */ #define BW_UART_S2_RWUID(x, v) (BITBAND_ACCESS8(HW_UART_S2_ADDR(x), BP_UART_S2_RWUID) = (v)) /*@}*/ /*! * @name Register UART_S2, field RXINV[4] (RW) * * Setting this field reverses the polarity of the received data input. In NRZ * format, a one is represented by a mark and a zero is represented by a space for * normal polarity, and the opposite for inverted polarity. In IrDA format, a * zero is represented by short high pulse in the middle of a bit time remaining * idle low for a one for normal polarity. A zero is represented by a short low * pulse in the middle of a bit time remaining idle high for a one for inverted * polarity. This field is automatically set when C7816[INIT] and C7816[ISO7816E] are * enabled and an initial character is detected in T = 0 protocol mode. Setting * RXINV inverts the RxD input for data bits, start and stop bits, break, and * idle. When C7816[ISO7816E] is set/enabled, only the data bits and the parity bit * are inverted. * * Values: * - 0 - Receive data is not inverted. * - 1 - Receive data is inverted. */ /*@{*/ #define BP_UART_S2_RXINV (4U) /*!< Bit position for UART_S2_RXINV. */ #define BM_UART_S2_RXINV (0x10U) /*!< Bit mask for UART_S2_RXINV. */ #define BS_UART_S2_RXINV (1U) /*!< Bit field size in bits for UART_S2_RXINV. */ /*! @brief Read current value of the UART_S2_RXINV field. */ #define BR_UART_S2_RXINV(x) (BITBAND_ACCESS8(HW_UART_S2_ADDR(x), BP_UART_S2_RXINV)) /*! @brief Format value for bitfield UART_S2_RXINV. */ #define BF_UART_S2_RXINV(v) ((uint8_t)((uint8_t)(v) << BP_UART_S2_RXINV) & BM_UART_S2_RXINV) /*! @brief Set the RXINV field to a new value. */ #define BW_UART_S2_RXINV(x, v) (BITBAND_ACCESS8(HW_UART_S2_ADDR(x), BP_UART_S2_RXINV) = (v)) /*@}*/ /*! * @name Register UART_S2, field MSBF[5] (RW) * * Setting this field reverses the order of the bits that are transmitted and * received on the wire. This field does not affect the polarity of the bits, the * location of the parity bit, or the location of the start or stop bits. This * field is automatically set when C7816[INIT] and C7816[ISO7816E] are enabled and * an initial character is detected in T = 0 protocol mode. * * Values: * - 0 - LSB (bit0) is the first bit that is transmitted following the start * bit. Further, the first bit received after the start bit is identified as * bit0. * - 1 - MSB (bit8, bit7 or bit6) is the first bit that is transmitted following * the start bit, depending on the setting of C1[M] and C1[PE]. Further, the * first bit received after the start bit is identified as bit8, bit7, or * bit6, depending on the setting of C1[M] and C1[PE]. */ /*@{*/ #define BP_UART_S2_MSBF (5U) /*!< Bit position for UART_S2_MSBF. */ #define BM_UART_S2_MSBF (0x20U) /*!< Bit mask for UART_S2_MSBF. */ #define BS_UART_S2_MSBF (1U) /*!< Bit field size in bits for UART_S2_MSBF. */ /*! @brief Read current value of the UART_S2_MSBF field. */ #define BR_UART_S2_MSBF(x) (BITBAND_ACCESS8(HW_UART_S2_ADDR(x), BP_UART_S2_MSBF)) /*! @brief Format value for bitfield UART_S2_MSBF. */ #define BF_UART_S2_MSBF(v) ((uint8_t)((uint8_t)(v) << BP_UART_S2_MSBF) & BM_UART_S2_MSBF) /*! @brief Set the MSBF field to a new value. */ #define BW_UART_S2_MSBF(x, v) (BITBAND_ACCESS8(HW_UART_S2_ADDR(x), BP_UART_S2_MSBF) = (v)) /*@}*/ /*! * @name Register UART_S2, field RXEDGIF[6] (W1C) * * RXEDGIF is set when an active edge occurs on the RxD pin. The active edge is * falling if RXINV = 0, and rising if RXINV=1. RXEDGIF is cleared by writing a 1 * to it. See for additional details. RXEDGIF description The active edge is * detected only in two wire mode and on receiving data coming from the RxD pin. * * Values: * - 0 - No active edge on the receive pin has occurred. * - 1 - An active edge on the receive pin has occurred. */ /*@{*/ #define BP_UART_S2_RXEDGIF (6U) /*!< Bit position for UART_S2_RXEDGIF. */ #define BM_UART_S2_RXEDGIF (0x40U) /*!< Bit mask for UART_S2_RXEDGIF. */ #define BS_UART_S2_RXEDGIF (1U) /*!< Bit field size in bits for UART_S2_RXEDGIF. */ /*! @brief Read current value of the UART_S2_RXEDGIF field. */ #define BR_UART_S2_RXEDGIF(x) (BITBAND_ACCESS8(HW_UART_S2_ADDR(x), BP_UART_S2_RXEDGIF)) /*! @brief Format value for bitfield UART_S2_RXEDGIF. */ #define BF_UART_S2_RXEDGIF(v) ((uint8_t)((uint8_t)(v) << BP_UART_S2_RXEDGIF) & BM_UART_S2_RXEDGIF) /*! @brief Set the RXEDGIF field to a new value. */ #define BW_UART_S2_RXEDGIF(x, v) (BITBAND_ACCESS8(HW_UART_S2_ADDR(x), BP_UART_S2_RXEDGIF) = (v)) /*@}*/ /*! * @name Register UART_S2, field LBKDIF[7] (W1C) * * LBKDIF is set when LBKDE is set and a LIN break character is detected on the * receiver input. The LIN break characters are 11 consecutive logic 0s if C1[M] * = 0 or 12 consecutive logic 0s if C1[M] = 1. LBKDIF is set after receiving the * last LIN break character. LBKDIF is cleared by writing a 1 to it. * * Values: * - 0 - No LIN break character detected. * - 1 - LIN break character detected. */ /*@{*/ #define BP_UART_S2_LBKDIF (7U) /*!< Bit position for UART_S2_LBKDIF. */ #define BM_UART_S2_LBKDIF (0x80U) /*!< Bit mask for UART_S2_LBKDIF. */ #define BS_UART_S2_LBKDIF (1U) /*!< Bit field size in bits for UART_S2_LBKDIF. */ /*! @brief Read current value of the UART_S2_LBKDIF field. */ #define BR_UART_S2_LBKDIF(x) (BITBAND_ACCESS8(HW_UART_S2_ADDR(x), BP_UART_S2_LBKDIF)) /*! @brief Format value for bitfield UART_S2_LBKDIF. */ #define BF_UART_S2_LBKDIF(v) ((uint8_t)((uint8_t)(v) << BP_UART_S2_LBKDIF) & BM_UART_S2_LBKDIF) /*! @brief Set the LBKDIF field to a new value. */ #define BW_UART_S2_LBKDIF(x, v) (BITBAND_ACCESS8(HW_UART_S2_ADDR(x), BP_UART_S2_LBKDIF) = (v)) /*@}*/ /******************************************************************************* * HW_UART_C3 - UART Control Register 3 ******************************************************************************/ /*! * @brief HW_UART_C3 - UART Control Register 3 (RW) * * Reset value: 0x00U * * Writing R8 does not have any effect. TXDIR and TXINV can be changed only * between transmit and receive packets. */ typedef union _hw_uart_c3 { uint8_t U; struct _hw_uart_c3_bitfields { uint8_t PEIE : 1; /*!< [0] Parity Error Interrupt Enable */ uint8_t FEIE : 1; /*!< [1] Framing Error Interrupt Enable */ uint8_t NEIE : 1; /*!< [2] Noise Error Interrupt Enable */ uint8_t ORIE : 1; /*!< [3] Overrun Error Interrupt Enable */ uint8_t TXINV : 1; /*!< [4] Transmit Data Inversion. */ uint8_t TXDIR : 1; /*!< [5] Transmitter Pin Data Direction in * Single-Wire mode */ uint8_t T8 : 1; /*!< [6] Transmit Bit 8 */ uint8_t R8 : 1; /*!< [7] Received Bit 8 */ } B; } hw_uart_c3_t; /*! * @name Constants and macros for entire UART_C3 register */ /*@{*/ #define HW_UART_C3_ADDR(x) ((x) + 0x6U) #define HW_UART_C3(x) (*(__IO hw_uart_c3_t *) HW_UART_C3_ADDR(x)) #define HW_UART_C3_RD(x) (HW_UART_C3(x).U) #define HW_UART_C3_WR(x, v) (HW_UART_C3(x).U = (v)) #define HW_UART_C3_SET(x, v) (HW_UART_C3_WR(x, HW_UART_C3_RD(x) | (v))) #define HW_UART_C3_CLR(x, v) (HW_UART_C3_WR(x, HW_UART_C3_RD(x) & ~(v))) #define HW_UART_C3_TOG(x, v) (HW_UART_C3_WR(x, HW_UART_C3_RD(x) ^ (v))) /*@}*/ /* * Constants & macros for individual UART_C3 bitfields */ /*! * @name Register UART_C3, field PEIE[0] (RW) * * Enables the parity error flag, S1[PF], to generate interrupt requests. * * Values: * - 0 - PF interrupt requests are disabled. * - 1 - PF interrupt requests are enabled. */ /*@{*/ #define BP_UART_C3_PEIE (0U) /*!< Bit position for UART_C3_PEIE. */ #define BM_UART_C3_PEIE (0x01U) /*!< Bit mask for UART_C3_PEIE. */ #define BS_UART_C3_PEIE (1U) /*!< Bit field size in bits for UART_C3_PEIE. */ /*! @brief Read current value of the UART_C3_PEIE field. */ #define BR_UART_C3_PEIE(x) (BITBAND_ACCESS8(HW_UART_C3_ADDR(x), BP_UART_C3_PEIE)) /*! @brief Format value for bitfield UART_C3_PEIE. */ #define BF_UART_C3_PEIE(v) ((uint8_t)((uint8_t)(v) << BP_UART_C3_PEIE) & BM_UART_C3_PEIE) /*! @brief Set the PEIE field to a new value. */ #define BW_UART_C3_PEIE(x, v) (BITBAND_ACCESS8(HW_UART_C3_ADDR(x), BP_UART_C3_PEIE) = (v)) /*@}*/ /*! * @name Register UART_C3, field FEIE[1] (RW) * * Enables the framing error flag, S1[FE], to generate interrupt requests. * * Values: * - 0 - FE interrupt requests are disabled. * - 1 - FE interrupt requests are enabled. */ /*@{*/ #define BP_UART_C3_FEIE (1U) /*!< Bit position for UART_C3_FEIE. */ #define BM_UART_C3_FEIE (0x02U) /*!< Bit mask for UART_C3_FEIE. */ #define BS_UART_C3_FEIE (1U) /*!< Bit field size in bits for UART_C3_FEIE. */ /*! @brief Read current value of the UART_C3_FEIE field. */ #define BR_UART_C3_FEIE(x) (BITBAND_ACCESS8(HW_UART_C3_ADDR(x), BP_UART_C3_FEIE)) /*! @brief Format value for bitfield UART_C3_FEIE. */ #define BF_UART_C3_FEIE(v) ((uint8_t)((uint8_t)(v) << BP_UART_C3_FEIE) & BM_UART_C3_FEIE) /*! @brief Set the FEIE field to a new value. */ #define BW_UART_C3_FEIE(x, v) (BITBAND_ACCESS8(HW_UART_C3_ADDR(x), BP_UART_C3_FEIE) = (v)) /*@}*/ /*! * @name Register UART_C3, field NEIE[2] (RW) * * Enables the noise flag, S1[NF], to generate interrupt requests. * * Values: * - 0 - NF interrupt requests are disabled. * - 1 - NF interrupt requests are enabled. */ /*@{*/ #define BP_UART_C3_NEIE (2U) /*!< Bit position for UART_C3_NEIE. */ #define BM_UART_C3_NEIE (0x04U) /*!< Bit mask for UART_C3_NEIE. */ #define BS_UART_C3_NEIE (1U) /*!< Bit field size in bits for UART_C3_NEIE. */ /*! @brief Read current value of the UART_C3_NEIE field. */ #define BR_UART_C3_NEIE(x) (BITBAND_ACCESS8(HW_UART_C3_ADDR(x), BP_UART_C3_NEIE)) /*! @brief Format value for bitfield UART_C3_NEIE. */ #define BF_UART_C3_NEIE(v) ((uint8_t)((uint8_t)(v) << BP_UART_C3_NEIE) & BM_UART_C3_NEIE) /*! @brief Set the NEIE field to a new value. */ #define BW_UART_C3_NEIE(x, v) (BITBAND_ACCESS8(HW_UART_C3_ADDR(x), BP_UART_C3_NEIE) = (v)) /*@}*/ /*! * @name Register UART_C3, field ORIE[3] (RW) * * Enables the overrun error flag, S1[OR], to generate interrupt requests. * * Values: * - 0 - OR interrupts are disabled. * - 1 - OR interrupt requests are enabled. */ /*@{*/ #define BP_UART_C3_ORIE (3U) /*!< Bit position for UART_C3_ORIE. */ #define BM_UART_C3_ORIE (0x08U) /*!< Bit mask for UART_C3_ORIE. */ #define BS_UART_C3_ORIE (1U) /*!< Bit field size in bits for UART_C3_ORIE. */ /*! @brief Read current value of the UART_C3_ORIE field. */ #define BR_UART_C3_ORIE(x) (BITBAND_ACCESS8(HW_UART_C3_ADDR(x), BP_UART_C3_ORIE)) /*! @brief Format value for bitfield UART_C3_ORIE. */ #define BF_UART_C3_ORIE(v) ((uint8_t)((uint8_t)(v) << BP_UART_C3_ORIE) & BM_UART_C3_ORIE) /*! @brief Set the ORIE field to a new value. */ #define BW_UART_C3_ORIE(x, v) (BITBAND_ACCESS8(HW_UART_C3_ADDR(x), BP_UART_C3_ORIE) = (v)) /*@}*/ /*! * @name Register UART_C3, field TXINV[4] (RW) * * Setting this field reverses the polarity of the transmitted data output. In * NRZ format, a one is represented by a mark and a zero is represented by a space * for normal polarity, and the opposite for inverted polarity. In IrDA format, * a zero is represented by short high pulse in the middle of a bit time * remaining idle low for a one for normal polarity, and a zero is represented by short * low pulse in the middle of a bit time remaining idle high for a one for * inverted polarity. This field is automatically set when C7816[INIT] and * C7816[ISO7816E] are enabled and an initial character is detected in T = 0 protocol mode. * Setting TXINV inverts all transmitted values, including idle, break, start, and * stop bits. In loop mode, if TXINV is set, the receiver gets the transmit * inversion bit when RXINV is disabled. When C7816[ISO7816E] is set/enabled then only * the transmitted data bits and parity bit are inverted. * * Values: * - 0 - Transmit data is not inverted. * - 1 - Transmit data is inverted. */ /*@{*/ #define BP_UART_C3_TXINV (4U) /*!< Bit position for UART_C3_TXINV. */ #define BM_UART_C3_TXINV (0x10U) /*!< Bit mask for UART_C3_TXINV. */ #define BS_UART_C3_TXINV (1U) /*!< Bit field size in bits for UART_C3_TXINV. */ /*! @brief Read current value of the UART_C3_TXINV field. */ #define BR_UART_C3_TXINV(x) (BITBAND_ACCESS8(HW_UART_C3_ADDR(x), BP_UART_C3_TXINV)) /*! @brief Format value for bitfield UART_C3_TXINV. */ #define BF_UART_C3_TXINV(v) ((uint8_t)((uint8_t)(v) << BP_UART_C3_TXINV) & BM_UART_C3_TXINV) /*! @brief Set the TXINV field to a new value. */ #define BW_UART_C3_TXINV(x, v) (BITBAND_ACCESS8(HW_UART_C3_ADDR(x), BP_UART_C3_TXINV) = (v)) /*@}*/ /*! * @name Register UART_C3, field TXDIR[5] (RW) * * Determines whether the TXD pin is used as an input or output in the * single-wire mode of operation. This field is relevant only to the single wire mode. * When C7816[ISO7816E] is set/enabled and C7816[TTYPE] = 1, this field is * automatically cleared after the requested block is transmitted. This condition is * detected when TL7816[TLEN] = 0 and 4 additional characters are transmitted. * Additionally, if C7816[ISO7816E] is set/enabled and C7816[TTYPE] = 0 and a NACK is * being transmitted, the hardware automatically overrides this field as needed. In * this situation, TXDIR does not reflect the temporary state associated with * the NACK. * * Values: * - 0 - TXD pin is an input in single wire mode. * - 1 - TXD pin is an output in single wire mode. */ /*@{*/ #define BP_UART_C3_TXDIR (5U) /*!< Bit position for UART_C3_TXDIR. */ #define BM_UART_C3_TXDIR (0x20U) /*!< Bit mask for UART_C3_TXDIR. */ #define BS_UART_C3_TXDIR (1U) /*!< Bit field size in bits for UART_C3_TXDIR. */ /*! @brief Read current value of the UART_C3_TXDIR field. */ #define BR_UART_C3_TXDIR(x) (BITBAND_ACCESS8(HW_UART_C3_ADDR(x), BP_UART_C3_TXDIR)) /*! @brief Format value for bitfield UART_C3_TXDIR. */ #define BF_UART_C3_TXDIR(v) ((uint8_t)((uint8_t)(v) << BP_UART_C3_TXDIR) & BM_UART_C3_TXDIR) /*! @brief Set the TXDIR field to a new value. */ #define BW_UART_C3_TXDIR(x, v) (BITBAND_ACCESS8(HW_UART_C3_ADDR(x), BP_UART_C3_TXDIR) = (v)) /*@}*/ /*! * @name Register UART_C3, field T8[6] (RW) * * T8 is the ninth data bit transmitted when the UART is configured for 9-bit * data format, that is, if C1[M] = 1 or C4[M10] = 1. If the value of T8 is the * same as in the previous transmission, T8 does not have to be rewritten. The same * value is transmitted until T8 is rewritten. To correctly transmit the 9th bit, * write UARTx_C3[T8] to the desired value, then write the UARTx_D register with * the remaining data. */ /*@{*/ #define BP_UART_C3_T8 (6U) /*!< Bit position for UART_C3_T8. */ #define BM_UART_C3_T8 (0x40U) /*!< Bit mask for UART_C3_T8. */ #define BS_UART_C3_T8 (1U) /*!< Bit field size in bits for UART_C3_T8. */ /*! @brief Read current value of the UART_C3_T8 field. */ #define BR_UART_C3_T8(x) (BITBAND_ACCESS8(HW_UART_C3_ADDR(x), BP_UART_C3_T8)) /*! @brief Format value for bitfield UART_C3_T8. */ #define BF_UART_C3_T8(v) ((uint8_t)((uint8_t)(v) << BP_UART_C3_T8) & BM_UART_C3_T8) /*! @brief Set the T8 field to a new value. */ #define BW_UART_C3_T8(x, v) (BITBAND_ACCESS8(HW_UART_C3_ADDR(x), BP_UART_C3_T8) = (v)) /*@}*/ /*! * @name Register UART_C3, field R8[7] (RO) * * R8 is the ninth data bit received when the UART is configured for 9-bit data * format, that is, if C1[M] = 1 or C4[M10] = 1. The R8 value corresponds to the * current data value in the UARTx_D register. To read the 9th bit, read the * value of UARTx_C3[R8], then read the UARTx_D register. */ /*@{*/ #define BP_UART_C3_R8 (7U) /*!< Bit position for UART_C3_R8. */ #define BM_UART_C3_R8 (0x80U) /*!< Bit mask for UART_C3_R8. */ #define BS_UART_C3_R8 (1U) /*!< Bit field size in bits for UART_C3_R8. */ /*! @brief Read current value of the UART_C3_R8 field. */ #define BR_UART_C3_R8(x) (BITBAND_ACCESS8(HW_UART_C3_ADDR(x), BP_UART_C3_R8)) /*@}*/ /******************************************************************************* * HW_UART_D - UART Data Register ******************************************************************************/ /*! * @brief HW_UART_D - UART Data Register (RW) * * Reset value: 0x00U * * This register is actually two separate registers. Reads return the contents * of the read-only receive data register and writes go to the write-only transmit * data register. In 8-bit or 9-bit data format, only UART data register (D) * needs to be accessed to clear the S1[RDRF] bit (assuming receiver buffer level is * less than RWFIFO[RXWATER]). The C3 register needs to be read, prior to the D * register, only if the ninth bit of data needs to be captured. Similarly, the * ED register needs to be read, prior to the D register, only if the additional * flag data for the dataword needs to be captured. In the normal 8-bit mode (M * bit cleared) if the parity is enabled, you get seven data bits and one parity * bit. That one parity bit is loaded into the D register. So, for the data bits, * mask off the parity bit from the value you read out of this register. When * transmitting in 9-bit data format and using 8-bit write instructions, write first * to transmit bit 8 in UART control register 3 (C3[T8]), then D. A write to * C3[T8] stores the data in a temporary register. If D register is written first, * and then the new data on data bus is stored in D, the temporary value written by * the last write to C3[T8] gets stored in the C3[T8] register. */ typedef union _hw_uart_d { uint8_t U; struct _hw_uart_d_bitfields { uint8_t RT : 8; /*!< [7:0] */ } B; } hw_uart_d_t; /*! * @name Constants and macros for entire UART_D register */ /*@{*/ #define HW_UART_D_ADDR(x) ((x) + 0x7U) #define HW_UART_D(x) (*(__IO hw_uart_d_t *) HW_UART_D_ADDR(x)) #define HW_UART_D_RD(x) (HW_UART_D(x).U) #define HW_UART_D_WR(x, v) (HW_UART_D(x).U = (v)) #define HW_UART_D_SET(x, v) (HW_UART_D_WR(x, HW_UART_D_RD(x) | (v))) #define HW_UART_D_CLR(x, v) (HW_UART_D_WR(x, HW_UART_D_RD(x) & ~(v))) #define HW_UART_D_TOG(x, v) (HW_UART_D_WR(x, HW_UART_D_RD(x) ^ (v))) /*@}*/ /* * Constants & macros for individual UART_D bitfields */ /*! * @name Register UART_D, field RT[7:0] (RW) * * Reads return the contents of the read-only receive data register and writes * go to the write-only transmit data register. */ /*@{*/ #define BP_UART_D_RT (0U) /*!< Bit position for UART_D_RT. */ #define BM_UART_D_RT (0xFFU) /*!< Bit mask for UART_D_RT. */ #define BS_UART_D_RT (8U) /*!< Bit field size in bits for UART_D_RT. */ /*! @brief Read current value of the UART_D_RT field. */ #define BR_UART_D_RT(x) (HW_UART_D(x).U) /*! @brief Format value for bitfield UART_D_RT. */ #define BF_UART_D_RT(v) ((uint8_t)((uint8_t)(v) << BP_UART_D_RT) & BM_UART_D_RT) /*! @brief Set the RT field to a new value. */ #define BW_UART_D_RT(x, v) (HW_UART_D_WR(x, v)) /*@}*/ /******************************************************************************* * HW_UART_MA1 - UART Match Address Registers 1 ******************************************************************************/ /*! * @brief HW_UART_MA1 - UART Match Address Registers 1 (RW) * * Reset value: 0x00U * * The MA1 and MA2 registers are compared to input data addresses when the most * significant bit is set and the associated C4[MAEN] field is set. If a match * occurs, the following data is transferred to the data register. If a match * fails, the following data is discarded. These registers can be read and written at * anytime. */ typedef union _hw_uart_ma1 { uint8_t U; struct _hw_uart_ma1_bitfields { uint8_t MA : 8; /*!< [7:0] Match Address */ } B; } hw_uart_ma1_t; /*! * @name Constants and macros for entire UART_MA1 register */ /*@{*/ #define HW_UART_MA1_ADDR(x) ((x) + 0x8U) #define HW_UART_MA1(x) (*(__IO hw_uart_ma1_t *) HW_UART_MA1_ADDR(x)) #define HW_UART_MA1_RD(x) (HW_UART_MA1(x).U) #define HW_UART_MA1_WR(x, v) (HW_UART_MA1(x).U = (v)) #define HW_UART_MA1_SET(x, v) (HW_UART_MA1_WR(x, HW_UART_MA1_RD(x) | (v))) #define HW_UART_MA1_CLR(x, v) (HW_UART_MA1_WR(x, HW_UART_MA1_RD(x) & ~(v))) #define HW_UART_MA1_TOG(x, v) (HW_UART_MA1_WR(x, HW_UART_MA1_RD(x) ^ (v))) /*@}*/ /* * Constants & macros for individual UART_MA1 bitfields */ /*! * @name Register UART_MA1, field MA[7:0] (RW) */ /*@{*/ #define BP_UART_MA1_MA (0U) /*!< Bit position for UART_MA1_MA. */ #define BM_UART_MA1_MA (0xFFU) /*!< Bit mask for UART_MA1_MA. */ #define BS_UART_MA1_MA (8U) /*!< Bit field size in bits for UART_MA1_MA. */ /*! @brief Read current value of the UART_MA1_MA field. */ #define BR_UART_MA1_MA(x) (HW_UART_MA1(x).U) /*! @brief Format value for bitfield UART_MA1_MA. */ #define BF_UART_MA1_MA(v) ((uint8_t)((uint8_t)(v) << BP_UART_MA1_MA) & BM_UART_MA1_MA) /*! @brief Set the MA field to a new value. */ #define BW_UART_MA1_MA(x, v) (HW_UART_MA1_WR(x, v)) /*@}*/ /******************************************************************************* * HW_UART_MA2 - UART Match Address Registers 2 ******************************************************************************/ /*! * @brief HW_UART_MA2 - UART Match Address Registers 2 (RW) * * Reset value: 0x00U * * These registers can be read and written at anytime. The MA1 and MA2 registers * are compared to input data addresses when the most significant bit is set and * the associated C4[MAEN] field is set. If a match occurs, the following data * is transferred to the data register. If a match fails, the following data is * discarded. */ typedef union _hw_uart_ma2 { uint8_t U; struct _hw_uart_ma2_bitfields { uint8_t MA : 8; /*!< [7:0] Match Address */ } B; } hw_uart_ma2_t; /*! * @name Constants and macros for entire UART_MA2 register */ /*@{*/ #define HW_UART_MA2_ADDR(x) ((x) + 0x9U) #define HW_UART_MA2(x) (*(__IO hw_uart_ma2_t *) HW_UART_MA2_ADDR(x)) #define HW_UART_MA2_RD(x) (HW_UART_MA2(x).U) #define HW_UART_MA2_WR(x, v) (HW_UART_MA2(x).U = (v)) #define HW_UART_MA2_SET(x, v) (HW_UART_MA2_WR(x, HW_UART_MA2_RD(x) | (v))) #define HW_UART_MA2_CLR(x, v) (HW_UART_MA2_WR(x, HW_UART_MA2_RD(x) & ~(v))) #define HW_UART_MA2_TOG(x, v) (HW_UART_MA2_WR(x, HW_UART_MA2_RD(x) ^ (v))) /*@}*/ /* * Constants & macros for individual UART_MA2 bitfields */ /*! * @name Register UART_MA2, field MA[7:0] (RW) */ /*@{*/ #define BP_UART_MA2_MA (0U) /*!< Bit position for UART_MA2_MA. */ #define BM_UART_MA2_MA (0xFFU) /*!< Bit mask for UART_MA2_MA. */ #define BS_UART_MA2_MA (8U) /*!< Bit field size in bits for UART_MA2_MA. */ /*! @brief Read current value of the UART_MA2_MA field. */ #define BR_UART_MA2_MA(x) (HW_UART_MA2(x).U) /*! @brief Format value for bitfield UART_MA2_MA. */ #define BF_UART_MA2_MA(v) ((uint8_t)((uint8_t)(v) << BP_UART_MA2_MA) & BM_UART_MA2_MA) /*! @brief Set the MA field to a new value. */ #define BW_UART_MA2_MA(x, v) (HW_UART_MA2_WR(x, v)) /*@}*/ /******************************************************************************* * HW_UART_C4 - UART Control Register 4 ******************************************************************************/ /*! * @brief HW_UART_C4 - UART Control Register 4 (RW) * * Reset value: 0x00U */ typedef union _hw_uart_c4 { uint8_t U; struct _hw_uart_c4_bitfields { uint8_t BRFA : 5; /*!< [4:0] Baud Rate Fine Adjust */ uint8_t M10 : 1; /*!< [5] 10-bit Mode select */ uint8_t MAEN2 : 1; /*!< [6] Match Address Mode Enable 2 */ uint8_t MAEN1 : 1; /*!< [7] Match Address Mode Enable 1 */ } B; } hw_uart_c4_t; /*! * @name Constants and macros for entire UART_C4 register */ /*@{*/ #define HW_UART_C4_ADDR(x) ((x) + 0xAU) #define HW_UART_C4(x) (*(__IO hw_uart_c4_t *) HW_UART_C4_ADDR(x)) #define HW_UART_C4_RD(x) (HW_UART_C4(x).U) #define HW_UART_C4_WR(x, v) (HW_UART_C4(x).U = (v)) #define HW_UART_C4_SET(x, v) (HW_UART_C4_WR(x, HW_UART_C4_RD(x) | (v))) #define HW_UART_C4_CLR(x, v) (HW_UART_C4_WR(x, HW_UART_C4_RD(x) & ~(v))) #define HW_UART_C4_TOG(x, v) (HW_UART_C4_WR(x, HW_UART_C4_RD(x) ^ (v))) /*@}*/ /* * Constants & macros for individual UART_C4 bitfields */ /*! * @name Register UART_C4, field BRFA[4:0] (RW) * * This bit field is used to add more timing resolution to the average baud * frequency, in increments of 1/32. See Baud rate generation for more information. */ /*@{*/ #define BP_UART_C4_BRFA (0U) /*!< Bit position for UART_C4_BRFA. */ #define BM_UART_C4_BRFA (0x1FU) /*!< Bit mask for UART_C4_BRFA. */ #define BS_UART_C4_BRFA (5U) /*!< Bit field size in bits for UART_C4_BRFA. */ /*! @brief Read current value of the UART_C4_BRFA field. */ #define BR_UART_C4_BRFA(x) (HW_UART_C4(x).B.BRFA) /*! @brief Format value for bitfield UART_C4_BRFA. */ #define BF_UART_C4_BRFA(v) ((uint8_t)((uint8_t)(v) << BP_UART_C4_BRFA) & BM_UART_C4_BRFA) /*! @brief Set the BRFA field to a new value. */ #define BW_UART_C4_BRFA(x, v) (HW_UART_C4_WR(x, (HW_UART_C4_RD(x) & ~BM_UART_C4_BRFA) | BF_UART_C4_BRFA(v))) /*@}*/ /*! * @name Register UART_C4, field M10[5] (RW) * * Causes a tenth, non-memory mapped bit to be part of the serial transmission. * This tenth bit is generated and interpreted as a parity bit. The M10 field * does not affect the LIN send or detect break behavior. If M10 is set, then both * C1[M] and C1[PE] must also be set. This field must be cleared when * C7816[ISO7816E] is set/enabled. See Data format (non ISO-7816) for more information. * * Values: * - 0 - The parity bit is the ninth bit in the serial transmission. * - 1 - The parity bit is the tenth bit in the serial transmission. */ /*@{*/ #define BP_UART_C4_M10 (5U) /*!< Bit position for UART_C4_M10. */ #define BM_UART_C4_M10 (0x20U) /*!< Bit mask for UART_C4_M10. */ #define BS_UART_C4_M10 (1U) /*!< Bit field size in bits for UART_C4_M10. */ /*! @brief Read current value of the UART_C4_M10 field. */ #define BR_UART_C4_M10(x) (BITBAND_ACCESS8(HW_UART_C4_ADDR(x), BP_UART_C4_M10)) /*! @brief Format value for bitfield UART_C4_M10. */ #define BF_UART_C4_M10(v) ((uint8_t)((uint8_t)(v) << BP_UART_C4_M10) & BM_UART_C4_M10) /*! @brief Set the M10 field to a new value. */ #define BW_UART_C4_M10(x, v) (BITBAND_ACCESS8(HW_UART_C4_ADDR(x), BP_UART_C4_M10) = (v)) /*@}*/ /*! * @name Register UART_C4, field MAEN2[6] (RW) * * See Match address operation for more information. * * Values: * - 0 - All data received is transferred to the data buffer if MAEN1 is cleared. * - 1 - All data received with the most significant bit cleared, is discarded. * All data received with the most significant bit set, is compared with * contents of MA2 register. If no match occurs, the data is discarded. If a * match occurs, data is transferred to the data buffer. This field must be * cleared when C7816[ISO7816E] is set/enabled. */ /*@{*/ #define BP_UART_C4_MAEN2 (6U) /*!< Bit position for UART_C4_MAEN2. */ #define BM_UART_C4_MAEN2 (0x40U) /*!< Bit mask for UART_C4_MAEN2. */ #define BS_UART_C4_MAEN2 (1U) /*!< Bit field size in bits for UART_C4_MAEN2. */ /*! @brief Read current value of the UART_C4_MAEN2 field. */ #define BR_UART_C4_MAEN2(x) (BITBAND_ACCESS8(HW_UART_C4_ADDR(x), BP_UART_C4_MAEN2)) /*! @brief Format value for bitfield UART_C4_MAEN2. */ #define BF_UART_C4_MAEN2(v) ((uint8_t)((uint8_t)(v) << BP_UART_C4_MAEN2) & BM_UART_C4_MAEN2) /*! @brief Set the MAEN2 field to a new value. */ #define BW_UART_C4_MAEN2(x, v) (BITBAND_ACCESS8(HW_UART_C4_ADDR(x), BP_UART_C4_MAEN2) = (v)) /*@}*/ /*! * @name Register UART_C4, field MAEN1[7] (RW) * * See Match address operation for more information. * * Values: * - 0 - All data received is transferred to the data buffer if MAEN2 is cleared. * - 1 - All data received with the most significant bit cleared, is discarded. * All data received with the most significant bit set, is compared with * contents of MA1 register. If no match occurs, the data is discarded. If match * occurs, data is transferred to the data buffer. This field must be cleared * when C7816[ISO7816E] is set/enabled. */ /*@{*/ #define BP_UART_C4_MAEN1 (7U) /*!< Bit position for UART_C4_MAEN1. */ #define BM_UART_C4_MAEN1 (0x80U) /*!< Bit mask for UART_C4_MAEN1. */ #define BS_UART_C4_MAEN1 (1U) /*!< Bit field size in bits for UART_C4_MAEN1. */ /*! @brief Read current value of the UART_C4_MAEN1 field. */ #define BR_UART_C4_MAEN1(x) (BITBAND_ACCESS8(HW_UART_C4_ADDR(x), BP_UART_C4_MAEN1)) /*! @brief Format value for bitfield UART_C4_MAEN1. */ #define BF_UART_C4_MAEN1(v) ((uint8_t)((uint8_t)(v) << BP_UART_C4_MAEN1) & BM_UART_C4_MAEN1) /*! @brief Set the MAEN1 field to a new value. */ #define BW_UART_C4_MAEN1(x, v) (BITBAND_ACCESS8(HW_UART_C4_ADDR(x), BP_UART_C4_MAEN1) = (v)) /*@}*/ /******************************************************************************* * HW_UART_C5 - UART Control Register 5 ******************************************************************************/ /*! * @brief HW_UART_C5 - UART Control Register 5 (RW) * * Reset value: 0x00U */ typedef union _hw_uart_c5 { uint8_t U; struct _hw_uart_c5_bitfields { uint8_t RESERVED0 : 3; /*!< [2:0] */ uint8_t LBKDDMAS : 1; /*!< [3] LIN Break Detect DMA Select Bit */ uint8_t ILDMAS : 1; /*!< [4] Idle Line DMA Select */ uint8_t RDMAS : 1; /*!< [5] Receiver Full DMA Select */ uint8_t TCDMAS : 1; /*!< [6] Transmission Complete DMA Select */ uint8_t TDMAS : 1; /*!< [7] Transmitter DMA Select */ } B; } hw_uart_c5_t; /*! * @name Constants and macros for entire UART_C5 register */ /*@{*/ #define HW_UART_C5_ADDR(x) ((x) + 0xBU) #define HW_UART_C5(x) (*(__IO hw_uart_c5_t *) HW_UART_C5_ADDR(x)) #define HW_UART_C5_RD(x) (HW_UART_C5(x).U) #define HW_UART_C5_WR(x, v) (HW_UART_C5(x).U = (v)) #define HW_UART_C5_SET(x, v) (HW_UART_C5_WR(x, HW_UART_C5_RD(x) | (v))) #define HW_UART_C5_CLR(x, v) (HW_UART_C5_WR(x, HW_UART_C5_RD(x) & ~(v))) #define HW_UART_C5_TOG(x, v) (HW_UART_C5_WR(x, HW_UART_C5_RD(x) ^ (v))) /*@}*/ /* * Constants & macros for individual UART_C5 bitfields */ /*! * @name Register UART_C5, field LBKDDMAS[3] (RW) * * Configures the LIN break detect flag, S2[LBKDIF], to generate interrupt or * DMA requests if BDH[LBKDIE] is set. If BDH[LBKDIE] is cleared, and S2[LBKDIF] is * set, the LBKDIF DMA and LBKDIF interrupt signals are not asserted, regardless * of the state of LBKDDMAS. * * Values: * - 0 - If BDH[LBKDIE] and S2[LBKDIF] are set, the LBKDIF interrupt signal is * asserted to request an interrupt service. * - 1 - If BDH[LBKDIE] and S2[LBKDIF] are set, the LBKDIF DMA request signal is * asserted to request a DMA transfer. */ /*@{*/ #define BP_UART_C5_LBKDDMAS (3U) /*!< Bit position for UART_C5_LBKDDMAS. */ #define BM_UART_C5_LBKDDMAS (0x08U) /*!< Bit mask for UART_C5_LBKDDMAS. */ #define BS_UART_C5_LBKDDMAS (1U) /*!< Bit field size in bits for UART_C5_LBKDDMAS. */ /*! @brief Read current value of the UART_C5_LBKDDMAS field. */ #define BR_UART_C5_LBKDDMAS(x) (BITBAND_ACCESS8(HW_UART_C5_ADDR(x), BP_UART_C5_LBKDDMAS)) /*! @brief Format value for bitfield UART_C5_LBKDDMAS. */ #define BF_UART_C5_LBKDDMAS(v) ((uint8_t)((uint8_t)(v) << BP_UART_C5_LBKDDMAS) & BM_UART_C5_LBKDDMAS) /*! @brief Set the LBKDDMAS field to a new value. */ #define BW_UART_C5_LBKDDMAS(x, v) (BITBAND_ACCESS8(HW_UART_C5_ADDR(x), BP_UART_C5_LBKDDMAS) = (v)) /*@}*/ /*! * @name Register UART_C5, field ILDMAS[4] (RW) * * Configures the idle line flag, S1[IDLE], to generate interrupt or DMA * requests if C2[ILIE] is set. If C2[ILIE] is cleared, and S1[IDLE] is set, the IDLE * DMA and IDLE interrupt request signals are not asserted, regardless of the state * of ILDMAS. * * Values: * - 0 - If C2[ILIE] and S1[IDLE] are set, the IDLE interrupt request signal is * asserted to request an interrupt service. * - 1 - If C2[ILIE] and S1[IDLE] are set, the IDLE DMA request signal is * asserted to request a DMA transfer. */ /*@{*/ #define BP_UART_C5_ILDMAS (4U) /*!< Bit position for UART_C5_ILDMAS. */ #define BM_UART_C5_ILDMAS (0x10U) /*!< Bit mask for UART_C5_ILDMAS. */ #define BS_UART_C5_ILDMAS (1U) /*!< Bit field size in bits for UART_C5_ILDMAS. */ /*! @brief Read current value of the UART_C5_ILDMAS field. */ #define BR_UART_C5_ILDMAS(x) (BITBAND_ACCESS8(HW_UART_C5_ADDR(x), BP_UART_C5_ILDMAS)) /*! @brief Format value for bitfield UART_C5_ILDMAS. */ #define BF_UART_C5_ILDMAS(v) ((uint8_t)((uint8_t)(v) << BP_UART_C5_ILDMAS) & BM_UART_C5_ILDMAS) /*! @brief Set the ILDMAS field to a new value. */ #define BW_UART_C5_ILDMAS(x, v) (BITBAND_ACCESS8(HW_UART_C5_ADDR(x), BP_UART_C5_ILDMAS) = (v)) /*@}*/ /*! * @name Register UART_C5, field RDMAS[5] (RW) * * Configures the receiver data register full flag, S1[RDRF], to generate * interrupt or DMA requests if C2[RIE] is set. If C2[RIE] is cleared, and S1[RDRF] is * set, the RDRF DMA and RDFR interrupt request signals are not asserted, * regardless of the state of RDMAS. * * Values: * - 0 - If C2[RIE] and S1[RDRF] are set, the RDFR interrupt request signal is * asserted to request an interrupt service. * - 1 - If C2[RIE] and S1[RDRF] are set, the RDRF DMA request signal is * asserted to request a DMA transfer. */ /*@{*/ #define BP_UART_C5_RDMAS (5U) /*!< Bit position for UART_C5_RDMAS. */ #define BM_UART_C5_RDMAS (0x20U) /*!< Bit mask for UART_C5_RDMAS. */ #define BS_UART_C5_RDMAS (1U) /*!< Bit field size in bits for UART_C5_RDMAS. */ /*! @brief Read current value of the UART_C5_RDMAS field. */ #define BR_UART_C5_RDMAS(x) (BITBAND_ACCESS8(HW_UART_C5_ADDR(x), BP_UART_C5_RDMAS)) /*! @brief Format value for bitfield UART_C5_RDMAS. */ #define BF_UART_C5_RDMAS(v) ((uint8_t)((uint8_t)(v) << BP_UART_C5_RDMAS) & BM_UART_C5_RDMAS) /*! @brief Set the RDMAS field to a new value. */ #define BW_UART_C5_RDMAS(x, v) (BITBAND_ACCESS8(HW_UART_C5_ADDR(x), BP_UART_C5_RDMAS) = (v)) /*@}*/ /*! * @name Register UART_C5, field TCDMAS[6] (RW) * * Configures the transmission complete flag, S1[TC], to generate interrupt or * DMA requests if C2[TCIE] is set. If C2[TCIE] is cleared, the TC DMA and TC * interrupt request signals are not asserted when the S1[TC] flag is set, regardless * of the state of TCDMAS. If C2[TCIE] and TCDMAS are both set, then C2[TIE] * must be cleared, and D must not be written unless a DMA request is being serviced. * * Values: * - 0 - If C2[TCIE] is set and the S1[TC] flag is set, the TC interrupt request * signal is asserted to request an interrupt service. * - 1 - If C2[TCIE] is set and the S1[TC] flag is set, the TC DMA request * signal is asserted to request a DMA transfer. */ /*@{*/ #define BP_UART_C5_TCDMAS (6U) /*!< Bit position for UART_C5_TCDMAS. */ #define BM_UART_C5_TCDMAS (0x40U) /*!< Bit mask for UART_C5_TCDMAS. */ #define BS_UART_C5_TCDMAS (1U) /*!< Bit field size in bits for UART_C5_TCDMAS. */ /*! @brief Read current value of the UART_C5_TCDMAS field. */ #define BR_UART_C5_TCDMAS(x) (BITBAND_ACCESS8(HW_UART_C5_ADDR(x), BP_UART_C5_TCDMAS)) /*! @brief Format value for bitfield UART_C5_TCDMAS. */ #define BF_UART_C5_TCDMAS(v) ((uint8_t)((uint8_t)(v) << BP_UART_C5_TCDMAS) & BM_UART_C5_TCDMAS) /*! @brief Set the TCDMAS field to a new value. */ #define BW_UART_C5_TCDMAS(x, v) (BITBAND_ACCESS8(HW_UART_C5_ADDR(x), BP_UART_C5_TCDMAS) = (v)) /*@}*/ /*! * @name Register UART_C5, field TDMAS[7] (RW) * * Configures the transmit data register empty flag, S1[TDRE], to generate * interrupt or DMA requests if C2[TIE] is set. If C2[TIE] is cleared, TDRE DMA and * TDRE interrupt request signals are not asserted when the TDRE flag is set, * regardless of the state of TDMAS. If C2[TIE] and TDMAS are both set, then C2[TCIE] * must be cleared, and D must not be written unless a DMA request is being * serviced. * * Values: * - 0 - If C2[TIE] is set and the S1[TDRE] flag is set, the TDRE interrupt * request signal is asserted to request interrupt service. * - 1 - If C2[TIE] is set and the S1[TDRE] flag is set, the TDRE DMA request * signal is asserted to request a DMA transfer. */ /*@{*/ #define BP_UART_C5_TDMAS (7U) /*!< Bit position for UART_C5_TDMAS. */ #define BM_UART_C5_TDMAS (0x80U) /*!< Bit mask for UART_C5_TDMAS. */ #define BS_UART_C5_TDMAS (1U) /*!< Bit field size in bits for UART_C5_TDMAS. */ /*! @brief Read current value of the UART_C5_TDMAS field. */ #define BR_UART_C5_TDMAS(x) (BITBAND_ACCESS8(HW_UART_C5_ADDR(x), BP_UART_C5_TDMAS)) /*! @brief Format value for bitfield UART_C5_TDMAS. */ #define BF_UART_C5_TDMAS(v) ((uint8_t)((uint8_t)(v) << BP_UART_C5_TDMAS) & BM_UART_C5_TDMAS) /*! @brief Set the TDMAS field to a new value. */ #define BW_UART_C5_TDMAS(x, v) (BITBAND_ACCESS8(HW_UART_C5_ADDR(x), BP_UART_C5_TDMAS) = (v)) /*@}*/ /******************************************************************************* * HW_UART_ED - UART Extended Data Register ******************************************************************************/ /*! * @brief HW_UART_ED - UART Extended Data Register (RO) * * Reset value: 0x00U * * This register contains additional information flags that are stored with a * received dataword. This register may be read at any time but contains valid data * only if there is a dataword in the receive FIFO. The data contained in this * register represents additional information regarding the conditions on which a * dataword was received. The importance of this data varies with the * application, and in some cases maybe completely optional. These fields automatically * update to reflect the conditions of the next dataword whenever D is read. If * S1[NF] and S1[PF] have not been set since the last time the receive buffer was * empty, the NOISY and PARITYE fields will be zero. */ typedef union _hw_uart_ed { uint8_t U; struct _hw_uart_ed_bitfields { uint8_t RESERVED0 : 6; /*!< [5:0] */ uint8_t PARITYE : 1; /*!< [6] */ uint8_t NOISY : 1; /*!< [7] */ } B; } hw_uart_ed_t; /*! * @name Constants and macros for entire UART_ED register */ /*@{*/ #define HW_UART_ED_ADDR(x) ((x) + 0xCU) #define HW_UART_ED(x) (*(__I hw_uart_ed_t *) HW_UART_ED_ADDR(x)) #define HW_UART_ED_RD(x) (HW_UART_ED(x).U) /*@}*/ /* * Constants & macros for individual UART_ED bitfields */ /*! * @name Register UART_ED, field PARITYE[6] (RO) * * The current received dataword contained in D and C3[R8] was received with a * parity error. * * Values: * - 0 - The dataword was received without a parity error. * - 1 - The dataword was received with a parity error. */ /*@{*/ #define BP_UART_ED_PARITYE (6U) /*!< Bit position for UART_ED_PARITYE. */ #define BM_UART_ED_PARITYE (0x40U) /*!< Bit mask for UART_ED_PARITYE. */ #define BS_UART_ED_PARITYE (1U) /*!< Bit field size in bits for UART_ED_PARITYE. */ /*! @brief Read current value of the UART_ED_PARITYE field. */ #define BR_UART_ED_PARITYE(x) (BITBAND_ACCESS8(HW_UART_ED_ADDR(x), BP_UART_ED_PARITYE)) /*@}*/ /*! * @name Register UART_ED, field NOISY[7] (RO) * * The current received dataword contained in D and C3[R8] was received with * noise. * * Values: * - 0 - The dataword was received without noise. * - 1 - The data was received with noise. */ /*@{*/ #define BP_UART_ED_NOISY (7U) /*!< Bit position for UART_ED_NOISY. */ #define BM_UART_ED_NOISY (0x80U) /*!< Bit mask for UART_ED_NOISY. */ #define BS_UART_ED_NOISY (1U) /*!< Bit field size in bits for UART_ED_NOISY. */ /*! @brief Read current value of the UART_ED_NOISY field. */ #define BR_UART_ED_NOISY(x) (BITBAND_ACCESS8(HW_UART_ED_ADDR(x), BP_UART_ED_NOISY)) /*@}*/ /******************************************************************************* * HW_UART_MODEM - UART Modem Register ******************************************************************************/ /*! * @brief HW_UART_MODEM - UART Modem Register (RW) * * Reset value: 0x00U * * The MODEM register controls options for setting the modem configuration. * RXRTSE, TXRTSPOL, TXRTSE, and TXCTSE must all be cleared when C7816[ISO7816EN] is * enabled. This will cause the RTS to deassert during ISO-7816 wait times. The * ISO-7816 protocol does not use the RTS and CTS signals. */ typedef union _hw_uart_modem { uint8_t U; struct _hw_uart_modem_bitfields { uint8_t TXCTSE : 1; /*!< [0] Transmitter clear-to-send enable */ uint8_t TXRTSE : 1; /*!< [1] Transmitter request-to-send enable */ uint8_t TXRTSPOL : 1; /*!< [2] Transmitter request-to-send polarity */ uint8_t RXRTSE : 1; /*!< [3] Receiver request-to-send enable */ uint8_t RESERVED0 : 4; /*!< [7:4] */ } B; } hw_uart_modem_t; /*! * @name Constants and macros for entire UART_MODEM register */ /*@{*/ #define HW_UART_MODEM_ADDR(x) ((x) + 0xDU) #define HW_UART_MODEM(x) (*(__IO hw_uart_modem_t *) HW_UART_MODEM_ADDR(x)) #define HW_UART_MODEM_RD(x) (HW_UART_MODEM(x).U) #define HW_UART_MODEM_WR(x, v) (HW_UART_MODEM(x).U = (v)) #define HW_UART_MODEM_SET(x, v) (HW_UART_MODEM_WR(x, HW_UART_MODEM_RD(x) | (v))) #define HW_UART_MODEM_CLR(x, v) (HW_UART_MODEM_WR(x, HW_UART_MODEM_RD(x) & ~(v))) #define HW_UART_MODEM_TOG(x, v) (HW_UART_MODEM_WR(x, HW_UART_MODEM_RD(x) ^ (v))) /*@}*/ /* * Constants & macros for individual UART_MODEM bitfields */ /*! * @name Register UART_MODEM, field TXCTSE[0] (RW) * * TXCTSE controls the operation of the transmitter. TXCTSE can be set * independently from the state of TXRTSE and RXRTSE. * * Values: * - 0 - CTS has no effect on the transmitter. * - 1 - Enables clear-to-send operation. The transmitter checks the state of * CTS each time it is ready to send a character. If CTS is asserted, the * character is sent. If CTS is deasserted, the signal TXD remains in the mark * state and transmission is delayed until CTS is asserted. Changes in CTS as a * character is being sent do not affect its transmission. */ /*@{*/ #define BP_UART_MODEM_TXCTSE (0U) /*!< Bit position for UART_MODEM_TXCTSE. */ #define BM_UART_MODEM_TXCTSE (0x01U) /*!< Bit mask for UART_MODEM_TXCTSE. */ #define BS_UART_MODEM_TXCTSE (1U) /*!< Bit field size in bits for UART_MODEM_TXCTSE. */ /*! @brief Read current value of the UART_MODEM_TXCTSE field. */ #define BR_UART_MODEM_TXCTSE(x) (BITBAND_ACCESS8(HW_UART_MODEM_ADDR(x), BP_UART_MODEM_TXCTSE)) /*! @brief Format value for bitfield UART_MODEM_TXCTSE. */ #define BF_UART_MODEM_TXCTSE(v) ((uint8_t)((uint8_t)(v) << BP_UART_MODEM_TXCTSE) & BM_UART_MODEM_TXCTSE) /*! @brief Set the TXCTSE field to a new value. */ #define BW_UART_MODEM_TXCTSE(x, v) (BITBAND_ACCESS8(HW_UART_MODEM_ADDR(x), BP_UART_MODEM_TXCTSE) = (v)) /*@}*/ /*! * @name Register UART_MODEM, field TXRTSE[1] (RW) * * Controls RTS before and after a transmission. * * Values: * - 0 - The transmitter has no effect on RTS. * - 1 - When a character is placed into an empty transmitter data buffer , RTS * asserts one bit time before the start bit is transmitted. RTS deasserts * one bit time after all characters in the transmitter data buffer and shift * register are completely sent, including the last stop bit. (FIFO) (FIFO) */ /*@{*/ #define BP_UART_MODEM_TXRTSE (1U) /*!< Bit position for UART_MODEM_TXRTSE. */ #define BM_UART_MODEM_TXRTSE (0x02U) /*!< Bit mask for UART_MODEM_TXRTSE. */ #define BS_UART_MODEM_TXRTSE (1U) /*!< Bit field size in bits for UART_MODEM_TXRTSE. */ /*! @brief Read current value of the UART_MODEM_TXRTSE field. */ #define BR_UART_MODEM_TXRTSE(x) (BITBAND_ACCESS8(HW_UART_MODEM_ADDR(x), BP_UART_MODEM_TXRTSE)) /*! @brief Format value for bitfield UART_MODEM_TXRTSE. */ #define BF_UART_MODEM_TXRTSE(v) ((uint8_t)((uint8_t)(v) << BP_UART_MODEM_TXRTSE) & BM_UART_MODEM_TXRTSE) /*! @brief Set the TXRTSE field to a new value. */ #define BW_UART_MODEM_TXRTSE(x, v) (BITBAND_ACCESS8(HW_UART_MODEM_ADDR(x), BP_UART_MODEM_TXRTSE) = (v)) /*@}*/ /*! * @name Register UART_MODEM, field TXRTSPOL[2] (RW) * * Controls the polarity of the transmitter RTS. TXRTSPOL does not affect the * polarity of the receiver RTS. RTS will remain negated in the active low state * unless TXRTSE is set. * * Values: * - 0 - Transmitter RTS is active low. * - 1 - Transmitter RTS is active high. */ /*@{*/ #define BP_UART_MODEM_TXRTSPOL (2U) /*!< Bit position for UART_MODEM_TXRTSPOL. */ #define BM_UART_MODEM_TXRTSPOL (0x04U) /*!< Bit mask for UART_MODEM_TXRTSPOL. */ #define BS_UART_MODEM_TXRTSPOL (1U) /*!< Bit field size in bits for UART_MODEM_TXRTSPOL. */ /*! @brief Read current value of the UART_MODEM_TXRTSPOL field. */ #define BR_UART_MODEM_TXRTSPOL(x) (BITBAND_ACCESS8(HW_UART_MODEM_ADDR(x), BP_UART_MODEM_TXRTSPOL)) /*! @brief Format value for bitfield UART_MODEM_TXRTSPOL. */ #define BF_UART_MODEM_TXRTSPOL(v) ((uint8_t)((uint8_t)(v) << BP_UART_MODEM_TXRTSPOL) & BM_UART_MODEM_TXRTSPOL) /*! @brief Set the TXRTSPOL field to a new value. */ #define BW_UART_MODEM_TXRTSPOL(x, v) (BITBAND_ACCESS8(HW_UART_MODEM_ADDR(x), BP_UART_MODEM_TXRTSPOL) = (v)) /*@}*/ /*! * @name Register UART_MODEM, field RXRTSE[3] (RW) * * Allows the RTS output to control the CTS input of the transmitting device to * prevent receiver overrun. Do not set both RXRTSE and TXRTSE. * * Values: * - 0 - The receiver has no effect on RTS. * - 1 - RTS is deasserted if the number of characters in the receiver data * register (FIFO) is equal to or greater than RWFIFO[RXWATER]. RTS is asserted * when the number of characters in the receiver data register (FIFO) is less * than RWFIFO[RXWATER]. */ /*@{*/ #define BP_UART_MODEM_RXRTSE (3U) /*!< Bit position for UART_MODEM_RXRTSE. */ #define BM_UART_MODEM_RXRTSE (0x08U) /*!< Bit mask for UART_MODEM_RXRTSE. */ #define BS_UART_MODEM_RXRTSE (1U) /*!< Bit field size in bits for UART_MODEM_RXRTSE. */ /*! @brief Read current value of the UART_MODEM_RXRTSE field. */ #define BR_UART_MODEM_RXRTSE(x) (BITBAND_ACCESS8(HW_UART_MODEM_ADDR(x), BP_UART_MODEM_RXRTSE)) /*! @brief Format value for bitfield UART_MODEM_RXRTSE. */ #define BF_UART_MODEM_RXRTSE(v) ((uint8_t)((uint8_t)(v) << BP_UART_MODEM_RXRTSE) & BM_UART_MODEM_RXRTSE) /*! @brief Set the RXRTSE field to a new value. */ #define BW_UART_MODEM_RXRTSE(x, v) (BITBAND_ACCESS8(HW_UART_MODEM_ADDR(x), BP_UART_MODEM_RXRTSE) = (v)) /*@}*/ /******************************************************************************* * HW_UART_IR - UART Infrared Register ******************************************************************************/ /*! * @brief HW_UART_IR - UART Infrared Register (RW) * * Reset value: 0x00U * * The IR register controls options for setting the infrared configuration. */ typedef union _hw_uart_ir { uint8_t U; struct _hw_uart_ir_bitfields { uint8_t TNP : 2; /*!< [1:0] Transmitter narrow pulse */ uint8_t IREN : 1; /*!< [2] Infrared enable */ uint8_t RESERVED0 : 5; /*!< [7:3] */ } B; } hw_uart_ir_t; /*! * @name Constants and macros for entire UART_IR register */ /*@{*/ #define HW_UART_IR_ADDR(x) ((x) + 0xEU) #define HW_UART_IR(x) (*(__IO hw_uart_ir_t *) HW_UART_IR_ADDR(x)) #define HW_UART_IR_RD(x) (HW_UART_IR(x).U) #define HW_UART_IR_WR(x, v) (HW_UART_IR(x).U = (v)) #define HW_UART_IR_SET(x, v) (HW_UART_IR_WR(x, HW_UART_IR_RD(x) | (v))) #define HW_UART_IR_CLR(x, v) (HW_UART_IR_WR(x, HW_UART_IR_RD(x) & ~(v))) #define HW_UART_IR_TOG(x, v) (HW_UART_IR_WR(x, HW_UART_IR_RD(x) ^ (v))) /*@}*/ /* * Constants & macros for individual UART_IR bitfields */ /*! * @name Register UART_IR, field TNP[1:0] (RW) * * Enables whether the UART transmits a 1/16, 3/16, 1/32, or 1/4 narrow pulse. * * Values: * - 00 - 3/16. * - 01 - 1/16. * - 10 - 1/32. * - 11 - 1/4. */ /*@{*/ #define BP_UART_IR_TNP (0U) /*!< Bit position for UART_IR_TNP. */ #define BM_UART_IR_TNP (0x03U) /*!< Bit mask for UART_IR_TNP. */ #define BS_UART_IR_TNP (2U) /*!< Bit field size in bits for UART_IR_TNP. */ /*! @brief Read current value of the UART_IR_TNP field. */ #define BR_UART_IR_TNP(x) (HW_UART_IR(x).B.TNP) /*! @brief Format value for bitfield UART_IR_TNP. */ #define BF_UART_IR_TNP(v) ((uint8_t)((uint8_t)(v) << BP_UART_IR_TNP) & BM_UART_IR_TNP) /*! @brief Set the TNP field to a new value. */ #define BW_UART_IR_TNP(x, v) (HW_UART_IR_WR(x, (HW_UART_IR_RD(x) & ~BM_UART_IR_TNP) | BF_UART_IR_TNP(v))) /*@}*/ /*! * @name Register UART_IR, field IREN[2] (RW) * * Enables/disables the infrared modulation/demodulation. * * Values: * - 0 - IR disabled. * - 1 - IR enabled. */ /*@{*/ #define BP_UART_IR_IREN (2U) /*!< Bit position for UART_IR_IREN. */ #define BM_UART_IR_IREN (0x04U) /*!< Bit mask for UART_IR_IREN. */ #define BS_UART_IR_IREN (1U) /*!< Bit field size in bits for UART_IR_IREN. */ /*! @brief Read current value of the UART_IR_IREN field. */ #define BR_UART_IR_IREN(x) (BITBAND_ACCESS8(HW_UART_IR_ADDR(x), BP_UART_IR_IREN)) /*! @brief Format value for bitfield UART_IR_IREN. */ #define BF_UART_IR_IREN(v) ((uint8_t)((uint8_t)(v) << BP_UART_IR_IREN) & BM_UART_IR_IREN) /*! @brief Set the IREN field to a new value. */ #define BW_UART_IR_IREN(x, v) (BITBAND_ACCESS8(HW_UART_IR_ADDR(x), BP_UART_IR_IREN) = (v)) /*@}*/ /******************************************************************************* * HW_UART_PFIFO - UART FIFO Parameters ******************************************************************************/ /*! * @brief HW_UART_PFIFO - UART FIFO Parameters (RW) * * Reset value: 0x00U * * This register provides the ability for the programmer to turn on and off FIFO * functionality. It also provides the size of the FIFO that has been * implemented. This register may be read at any time. This register must be written only * when C2[RE] and C2[TE] are cleared/not set and when the data buffer/FIFO is * empty. */ typedef union _hw_uart_pfifo { uint8_t U; struct _hw_uart_pfifo_bitfields { uint8_t RXFIFOSIZE : 3; /*!< [2:0] Receive FIFO. Buffer Depth */ uint8_t RXFE : 1; /*!< [3] Receive FIFO Enable */ uint8_t TXFIFOSIZE : 3; /*!< [6:4] Transmit FIFO. Buffer Depth */ uint8_t TXFE : 1; /*!< [7] Transmit FIFO Enable */ } B; } hw_uart_pfifo_t; /*! * @name Constants and macros for entire UART_PFIFO register */ /*@{*/ #define HW_UART_PFIFO_ADDR(x) ((x) + 0x10U) #define HW_UART_PFIFO(x) (*(__IO hw_uart_pfifo_t *) HW_UART_PFIFO_ADDR(x)) #define HW_UART_PFIFO_RD(x) (HW_UART_PFIFO(x).U) #define HW_UART_PFIFO_WR(x, v) (HW_UART_PFIFO(x).U = (v)) #define HW_UART_PFIFO_SET(x, v) (HW_UART_PFIFO_WR(x, HW_UART_PFIFO_RD(x) | (v))) #define HW_UART_PFIFO_CLR(x, v) (HW_UART_PFIFO_WR(x, HW_UART_PFIFO_RD(x) & ~(v))) #define HW_UART_PFIFO_TOG(x, v) (HW_UART_PFIFO_WR(x, HW_UART_PFIFO_RD(x) ^ (v))) /*@}*/ /* * Constants & macros for individual UART_PFIFO bitfields */ /*! * @name Register UART_PFIFO, field RXFIFOSIZE[2:0] (RO) * * The maximum number of receive datawords that can be stored in the receive * buffer before an overrun occurs. This field is read only. * * Values: * - 000 - Receive FIFO/Buffer depth = 1 dataword. * - 001 - Receive FIFO/Buffer depth = 4 datawords. * - 010 - Receive FIFO/Buffer depth = 8 datawords. * - 011 - Receive FIFO/Buffer depth = 16 datawords. * - 100 - Receive FIFO/Buffer depth = 32 datawords. * - 101 - Receive FIFO/Buffer depth = 64 datawords. * - 110 - Receive FIFO/Buffer depth = 128 datawords. * - 111 - Reserved. */ /*@{*/ #define BP_UART_PFIFO_RXFIFOSIZE (0U) /*!< Bit position for UART_PFIFO_RXFIFOSIZE. */ #define BM_UART_PFIFO_RXFIFOSIZE (0x07U) /*!< Bit mask for UART_PFIFO_RXFIFOSIZE. */ #define BS_UART_PFIFO_RXFIFOSIZE (3U) /*!< Bit field size in bits for UART_PFIFO_RXFIFOSIZE. */ /*! @brief Read current value of the UART_PFIFO_RXFIFOSIZE field. */ #define BR_UART_PFIFO_RXFIFOSIZE(x) (HW_UART_PFIFO(x).B.RXFIFOSIZE) /*@}*/ /*! * @name Register UART_PFIFO, field RXFE[3] (RW) * * When this field is set, the built in FIFO structure for the receive buffer is * enabled. The size of the FIFO structure is indicated by the RXFIFOSIZE field. * If this field is not set, the receive buffer operates as a FIFO of depth one * dataword regardless of the value in RXFIFOSIZE. Both C2[TE] and C2[RE] must be * cleared prior to changing this field. Additionally, TXFLUSH and RXFLUSH * commands must be issued immediately after changing this field. * * Values: * - 0 - Receive FIFO is not enabled. Buffer is depth 1. (Legacy support) * - 1 - Receive FIFO is enabled. Buffer is depth indicted by RXFIFOSIZE. */ /*@{*/ #define BP_UART_PFIFO_RXFE (3U) /*!< Bit position for UART_PFIFO_RXFE. */ #define BM_UART_PFIFO_RXFE (0x08U) /*!< Bit mask for UART_PFIFO_RXFE. */ #define BS_UART_PFIFO_RXFE (1U) /*!< Bit field size in bits for UART_PFIFO_RXFE. */ /*! @brief Read current value of the UART_PFIFO_RXFE field. */ #define BR_UART_PFIFO_RXFE(x) (BITBAND_ACCESS8(HW_UART_PFIFO_ADDR(x), BP_UART_PFIFO_RXFE)) /*! @brief Format value for bitfield UART_PFIFO_RXFE. */ #define BF_UART_PFIFO_RXFE(v) ((uint8_t)((uint8_t)(v) << BP_UART_PFIFO_RXFE) & BM_UART_PFIFO_RXFE) /*! @brief Set the RXFE field to a new value. */ #define BW_UART_PFIFO_RXFE(x, v) (BITBAND_ACCESS8(HW_UART_PFIFO_ADDR(x), BP_UART_PFIFO_RXFE) = (v)) /*@}*/ /*! * @name Register UART_PFIFO, field TXFIFOSIZE[6:4] (RO) * * The maximum number of transmit datawords that can be stored in the transmit * buffer. This field is read only. * * Values: * - 000 - Transmit FIFO/Buffer depth = 1 dataword. * - 001 - Transmit FIFO/Buffer depth = 4 datawords. * - 010 - Transmit FIFO/Buffer depth = 8 datawords. * - 011 - Transmit FIFO/Buffer depth = 16 datawords. * - 100 - Transmit FIFO/Buffer depth = 32 datawords. * - 101 - Transmit FIFO/Buffer depth = 64 datawords. * - 110 - Transmit FIFO/Buffer depth = 128 datawords. * - 111 - Reserved. */ /*@{*/ #define BP_UART_PFIFO_TXFIFOSIZE (4U) /*!< Bit position for UART_PFIFO_TXFIFOSIZE. */ #define BM_UART_PFIFO_TXFIFOSIZE (0x70U) /*!< Bit mask for UART_PFIFO_TXFIFOSIZE. */ #define BS_UART_PFIFO_TXFIFOSIZE (3U) /*!< Bit field size in bits for UART_PFIFO_TXFIFOSIZE. */ /*! @brief Read current value of the UART_PFIFO_TXFIFOSIZE field. */ #define BR_UART_PFIFO_TXFIFOSIZE(x) (HW_UART_PFIFO(x).B.TXFIFOSIZE) /*@}*/ /*! * @name Register UART_PFIFO, field TXFE[7] (RW) * * When this field is set, the built in FIFO structure for the transmit buffer * is enabled. The size of the FIFO structure is indicated by TXFIFOSIZE. If this * field is not set, the transmit buffer operates as a FIFO of depth one dataword * regardless of the value in TXFIFOSIZE. Both C2[TE] and C2[RE] must be cleared * prior to changing this field. Additionally, TXFLUSH and RXFLUSH commands must * be issued immediately after changing this field. * * Values: * - 0 - Transmit FIFO is not enabled. Buffer is depth 1. (Legacy support). * - 1 - Transmit FIFO is enabled. Buffer is depth indicated by TXFIFOSIZE. */ /*@{*/ #define BP_UART_PFIFO_TXFE (7U) /*!< Bit position for UART_PFIFO_TXFE. */ #define BM_UART_PFIFO_TXFE (0x80U) /*!< Bit mask for UART_PFIFO_TXFE. */ #define BS_UART_PFIFO_TXFE (1U) /*!< Bit field size in bits for UART_PFIFO_TXFE. */ /*! @brief Read current value of the UART_PFIFO_TXFE field. */ #define BR_UART_PFIFO_TXFE(x) (BITBAND_ACCESS8(HW_UART_PFIFO_ADDR(x), BP_UART_PFIFO_TXFE)) /*! @brief Format value for bitfield UART_PFIFO_TXFE. */ #define BF_UART_PFIFO_TXFE(v) ((uint8_t)((uint8_t)(v) << BP_UART_PFIFO_TXFE) & BM_UART_PFIFO_TXFE) /*! @brief Set the TXFE field to a new value. */ #define BW_UART_PFIFO_TXFE(x, v) (BITBAND_ACCESS8(HW_UART_PFIFO_ADDR(x), BP_UART_PFIFO_TXFE) = (v)) /*@}*/ /******************************************************************************* * HW_UART_CFIFO - UART FIFO Control Register ******************************************************************************/ /*! * @brief HW_UART_CFIFO - UART FIFO Control Register (RW) * * Reset value: 0x00U * * This register provides the ability to program various control fields for FIFO * operation. This register may be read or written at any time. Note that * writing to TXFLUSH and RXFLUSH may result in data loss and requires careful action * to prevent unintended/unpredictable behavior. Therefore, it is recommended that * TE and RE be cleared prior to flushing the corresponding FIFO. */ typedef union _hw_uart_cfifo { uint8_t U; struct _hw_uart_cfifo_bitfields { uint8_t RXUFE : 1; /*!< [0] Receive FIFO Underflow Interrupt Enable */ uint8_t TXOFE : 1; /*!< [1] Transmit FIFO Overflow Interrupt Enable */ uint8_t RXOFE : 1; /*!< [2] Receive FIFO Overflow Interrupt Enable */ uint8_t RESERVED0 : 3; /*!< [5:3] */ uint8_t RXFLUSH : 1; /*!< [6] Receive FIFO/Buffer Flush */ uint8_t TXFLUSH : 1; /*!< [7] Transmit FIFO/Buffer Flush */ } B; } hw_uart_cfifo_t; /*! * @name Constants and macros for entire UART_CFIFO register */ /*@{*/ #define HW_UART_CFIFO_ADDR(x) ((x) + 0x11U) #define HW_UART_CFIFO(x) (*(__IO hw_uart_cfifo_t *) HW_UART_CFIFO_ADDR(x)) #define HW_UART_CFIFO_RD(x) (HW_UART_CFIFO(x).U) #define HW_UART_CFIFO_WR(x, v) (HW_UART_CFIFO(x).U = (v)) #define HW_UART_CFIFO_SET(x, v) (HW_UART_CFIFO_WR(x, HW_UART_CFIFO_RD(x) | (v))) #define HW_UART_CFIFO_CLR(x, v) (HW_UART_CFIFO_WR(x, HW_UART_CFIFO_RD(x) & ~(v))) #define HW_UART_CFIFO_TOG(x, v) (HW_UART_CFIFO_WR(x, HW_UART_CFIFO_RD(x) ^ (v))) /*@}*/ /* * Constants & macros for individual UART_CFIFO bitfields */ /*! * @name Register UART_CFIFO, field RXUFE[0] (RW) * * When this field is set, the RXUF flag generates an interrupt to the host. * * Values: * - 0 - RXUF flag does not generate an interrupt to the host. * - 1 - RXUF flag generates an interrupt to the host. */ /*@{*/ #define BP_UART_CFIFO_RXUFE (0U) /*!< Bit position for UART_CFIFO_RXUFE. */ #define BM_UART_CFIFO_RXUFE (0x01U) /*!< Bit mask for UART_CFIFO_RXUFE. */ #define BS_UART_CFIFO_RXUFE (1U) /*!< Bit field size in bits for UART_CFIFO_RXUFE. */ /*! @brief Read current value of the UART_CFIFO_RXUFE field. */ #define BR_UART_CFIFO_RXUFE(x) (BITBAND_ACCESS8(HW_UART_CFIFO_ADDR(x), BP_UART_CFIFO_RXUFE)) /*! @brief Format value for bitfield UART_CFIFO_RXUFE. */ #define BF_UART_CFIFO_RXUFE(v) ((uint8_t)((uint8_t)(v) << BP_UART_CFIFO_RXUFE) & BM_UART_CFIFO_RXUFE) /*! @brief Set the RXUFE field to a new value. */ #define BW_UART_CFIFO_RXUFE(x, v) (BITBAND_ACCESS8(HW_UART_CFIFO_ADDR(x), BP_UART_CFIFO_RXUFE) = (v)) /*@}*/ /*! * @name Register UART_CFIFO, field TXOFE[1] (RW) * * When this field is set, the TXOF flag generates an interrupt to the host. * * Values: * - 0 - TXOF flag does not generate an interrupt to the host. * - 1 - TXOF flag generates an interrupt to the host. */ /*@{*/ #define BP_UART_CFIFO_TXOFE (1U) /*!< Bit position for UART_CFIFO_TXOFE. */ #define BM_UART_CFIFO_TXOFE (0x02U) /*!< Bit mask for UART_CFIFO_TXOFE. */ #define BS_UART_CFIFO_TXOFE (1U) /*!< Bit field size in bits for UART_CFIFO_TXOFE. */ /*! @brief Read current value of the UART_CFIFO_TXOFE field. */ #define BR_UART_CFIFO_TXOFE(x) (BITBAND_ACCESS8(HW_UART_CFIFO_ADDR(x), BP_UART_CFIFO_TXOFE)) /*! @brief Format value for bitfield UART_CFIFO_TXOFE. */ #define BF_UART_CFIFO_TXOFE(v) ((uint8_t)((uint8_t)(v) << BP_UART_CFIFO_TXOFE) & BM_UART_CFIFO_TXOFE) /*! @brief Set the TXOFE field to a new value. */ #define BW_UART_CFIFO_TXOFE(x, v) (BITBAND_ACCESS8(HW_UART_CFIFO_ADDR(x), BP_UART_CFIFO_TXOFE) = (v)) /*@}*/ /*! * @name Register UART_CFIFO, field RXOFE[2] (RW) * * When this field is set, the RXOF flag generates an interrupt to the host. * * Values: * - 0 - RXOF flag does not generate an interrupt to the host. * - 1 - RXOF flag generates an interrupt to the host. */ /*@{*/ #define BP_UART_CFIFO_RXOFE (2U) /*!< Bit position for UART_CFIFO_RXOFE. */ #define BM_UART_CFIFO_RXOFE (0x04U) /*!< Bit mask for UART_CFIFO_RXOFE. */ #define BS_UART_CFIFO_RXOFE (1U) /*!< Bit field size in bits for UART_CFIFO_RXOFE. */ /*! @brief Read current value of the UART_CFIFO_RXOFE field. */ #define BR_UART_CFIFO_RXOFE(x) (BITBAND_ACCESS8(HW_UART_CFIFO_ADDR(x), BP_UART_CFIFO_RXOFE)) /*! @brief Format value for bitfield UART_CFIFO_RXOFE. */ #define BF_UART_CFIFO_RXOFE(v) ((uint8_t)((uint8_t)(v) << BP_UART_CFIFO_RXOFE) & BM_UART_CFIFO_RXOFE) /*! @brief Set the RXOFE field to a new value. */ #define BW_UART_CFIFO_RXOFE(x, v) (BITBAND_ACCESS8(HW_UART_CFIFO_ADDR(x), BP_UART_CFIFO_RXOFE) = (v)) /*@}*/ /*! * @name Register UART_CFIFO, field RXFLUSH[6] (WORZ) * * Writing to this field causes all data that is stored in the receive * FIFO/buffer to be flushed. This does not affect data that is in the receive shift * register. * * Values: * - 0 - No flush operation occurs. * - 1 - All data in the receive FIFO/buffer is cleared out. */ /*@{*/ #define BP_UART_CFIFO_RXFLUSH (6U) /*!< Bit position for UART_CFIFO_RXFLUSH. */ #define BM_UART_CFIFO_RXFLUSH (0x40U) /*!< Bit mask for UART_CFIFO_RXFLUSH. */ #define BS_UART_CFIFO_RXFLUSH (1U) /*!< Bit field size in bits for UART_CFIFO_RXFLUSH. */ /*! @brief Format value for bitfield UART_CFIFO_RXFLUSH. */ #define BF_UART_CFIFO_RXFLUSH(v) ((uint8_t)((uint8_t)(v) << BP_UART_CFIFO_RXFLUSH) & BM_UART_CFIFO_RXFLUSH) /*! @brief Set the RXFLUSH field to a new value. */ #define BW_UART_CFIFO_RXFLUSH(x, v) (BITBAND_ACCESS8(HW_UART_CFIFO_ADDR(x), BP_UART_CFIFO_RXFLUSH) = (v)) /*@}*/ /*! * @name Register UART_CFIFO, field TXFLUSH[7] (WORZ) * * Writing to this field causes all data that is stored in the transmit * FIFO/buffer to be flushed. This does not affect data that is in the transmit shift * register. * * Values: * - 0 - No flush operation occurs. * - 1 - All data in the transmit FIFO/Buffer is cleared out. */ /*@{*/ #define BP_UART_CFIFO_TXFLUSH (7U) /*!< Bit position for UART_CFIFO_TXFLUSH. */ #define BM_UART_CFIFO_TXFLUSH (0x80U) /*!< Bit mask for UART_CFIFO_TXFLUSH. */ #define BS_UART_CFIFO_TXFLUSH (1U) /*!< Bit field size in bits for UART_CFIFO_TXFLUSH. */ /*! @brief Format value for bitfield UART_CFIFO_TXFLUSH. */ #define BF_UART_CFIFO_TXFLUSH(v) ((uint8_t)((uint8_t)(v) << BP_UART_CFIFO_TXFLUSH) & BM_UART_CFIFO_TXFLUSH) /*! @brief Set the TXFLUSH field to a new value. */ #define BW_UART_CFIFO_TXFLUSH(x, v) (BITBAND_ACCESS8(HW_UART_CFIFO_ADDR(x), BP_UART_CFIFO_TXFLUSH) = (v)) /*@}*/ /******************************************************************************* * HW_UART_SFIFO - UART FIFO Status Register ******************************************************************************/ /*! * @brief HW_UART_SFIFO - UART FIFO Status Register (RW) * * Reset value: 0xC0U * * This register provides status information regarding the transmit and receiver * buffers/FIFOs, including interrupt information. This register may be written * to or read at any time. */ typedef union _hw_uart_sfifo { uint8_t U; struct _hw_uart_sfifo_bitfields { uint8_t RXUF : 1; /*!< [0] Receiver Buffer Underflow Flag */ uint8_t TXOF : 1; /*!< [1] Transmitter Buffer Overflow Flag */ uint8_t RXOF : 1; /*!< [2] Receiver Buffer Overflow Flag */ uint8_t RESERVED0 : 3; /*!< [5:3] */ uint8_t RXEMPT : 1; /*!< [6] Receive Buffer/FIFO Empty */ uint8_t TXEMPT : 1; /*!< [7] Transmit Buffer/FIFO Empty */ } B; } hw_uart_sfifo_t; /*! * @name Constants and macros for entire UART_SFIFO register */ /*@{*/ #define HW_UART_SFIFO_ADDR(x) ((x) + 0x12U) #define HW_UART_SFIFO(x) (*(__IO hw_uart_sfifo_t *) HW_UART_SFIFO_ADDR(x)) #define HW_UART_SFIFO_RD(x) (HW_UART_SFIFO(x).U) #define HW_UART_SFIFO_WR(x, v) (HW_UART_SFIFO(x).U = (v)) #define HW_UART_SFIFO_SET(x, v) (HW_UART_SFIFO_WR(x, HW_UART_SFIFO_RD(x) | (v))) #define HW_UART_SFIFO_CLR(x, v) (HW_UART_SFIFO_WR(x, HW_UART_SFIFO_RD(x) & ~(v))) #define HW_UART_SFIFO_TOG(x, v) (HW_UART_SFIFO_WR(x, HW_UART_SFIFO_RD(x) ^ (v))) /*@}*/ /* * Constants & macros for individual UART_SFIFO bitfields */ /*! * @name Register UART_SFIFO, field RXUF[0] (W1C) * * Indicates that more data has been read from the receive buffer than was * present. This field will assert regardless of the value of CFIFO[RXUFE]. However, * an interrupt will be issued to the host only if CFIFO[RXUFE] is set. This flag * is cleared by writing a 1. * * Values: * - 0 - No receive buffer underflow has occurred since the last time the flag * was cleared. * - 1 - At least one receive buffer underflow has occurred since the last time * the flag was cleared. */ /*@{*/ #define BP_UART_SFIFO_RXUF (0U) /*!< Bit position for UART_SFIFO_RXUF. */ #define BM_UART_SFIFO_RXUF (0x01U) /*!< Bit mask for UART_SFIFO_RXUF. */ #define BS_UART_SFIFO_RXUF (1U) /*!< Bit field size in bits for UART_SFIFO_RXUF. */ /*! @brief Read current value of the UART_SFIFO_RXUF field. */ #define BR_UART_SFIFO_RXUF(x) (BITBAND_ACCESS8(HW_UART_SFIFO_ADDR(x), BP_UART_SFIFO_RXUF)) /*! @brief Format value for bitfield UART_SFIFO_RXUF. */ #define BF_UART_SFIFO_RXUF(v) ((uint8_t)((uint8_t)(v) << BP_UART_SFIFO_RXUF) & BM_UART_SFIFO_RXUF) /*! @brief Set the RXUF field to a new value. */ #define BW_UART_SFIFO_RXUF(x, v) (BITBAND_ACCESS8(HW_UART_SFIFO_ADDR(x), BP_UART_SFIFO_RXUF) = (v)) /*@}*/ /*! * @name Register UART_SFIFO, field TXOF[1] (W1C) * * Indicates that more data has been written to the transmit buffer than it can * hold. This field will assert regardless of the value of CFIFO[TXOFE]. However, * an interrupt will be issued to the host only if CFIFO[TXOFE] is set. This * flag is cleared by writing a 1. * * Values: * - 0 - No transmit buffer overflow has occurred since the last time the flag * was cleared. * - 1 - At least one transmit buffer overflow has occurred since the last time * the flag was cleared. */ /*@{*/ #define BP_UART_SFIFO_TXOF (1U) /*!< Bit position for UART_SFIFO_TXOF. */ #define BM_UART_SFIFO_TXOF (0x02U) /*!< Bit mask for UART_SFIFO_TXOF. */ #define BS_UART_SFIFO_TXOF (1U) /*!< Bit field size in bits for UART_SFIFO_TXOF. */ /*! @brief Read current value of the UART_SFIFO_TXOF field. */ #define BR_UART_SFIFO_TXOF(x) (BITBAND_ACCESS8(HW_UART_SFIFO_ADDR(x), BP_UART_SFIFO_TXOF)) /*! @brief Format value for bitfield UART_SFIFO_TXOF. */ #define BF_UART_SFIFO_TXOF(v) ((uint8_t)((uint8_t)(v) << BP_UART_SFIFO_TXOF) & BM_UART_SFIFO_TXOF) /*! @brief Set the TXOF field to a new value. */ #define BW_UART_SFIFO_TXOF(x, v) (BITBAND_ACCESS8(HW_UART_SFIFO_ADDR(x), BP_UART_SFIFO_TXOF) = (v)) /*@}*/ /*! * @name Register UART_SFIFO, field RXOF[2] (W1C) * * Indicates that more data has been written to the receive buffer than it can * hold. This field will assert regardless of the value of CFIFO[RXOFE]. However, * an interrupt will be issued to the host only if CFIFO[RXOFE] is set. This flag * is cleared by writing a 1. * * Values: * - 0 - No receive buffer overflow has occurred since the last time the flag * was cleared. * - 1 - At least one receive buffer overflow has occurred since the last time * the flag was cleared. */ /*@{*/ #define BP_UART_SFIFO_RXOF (2U) /*!< Bit position for UART_SFIFO_RXOF. */ #define BM_UART_SFIFO_RXOF (0x04U) /*!< Bit mask for UART_SFIFO_RXOF. */ #define BS_UART_SFIFO_RXOF (1U) /*!< Bit field size in bits for UART_SFIFO_RXOF. */ /*! @brief Read current value of the UART_SFIFO_RXOF field. */ #define BR_UART_SFIFO_RXOF(x) (BITBAND_ACCESS8(HW_UART_SFIFO_ADDR(x), BP_UART_SFIFO_RXOF)) /*! @brief Format value for bitfield UART_SFIFO_RXOF. */ #define BF_UART_SFIFO_RXOF(v) ((uint8_t)((uint8_t)(v) << BP_UART_SFIFO_RXOF) & BM_UART_SFIFO_RXOF) /*! @brief Set the RXOF field to a new value. */ #define BW_UART_SFIFO_RXOF(x, v) (BITBAND_ACCESS8(HW_UART_SFIFO_ADDR(x), BP_UART_SFIFO_RXOF) = (v)) /*@}*/ /*! * @name Register UART_SFIFO, field RXEMPT[6] (RO) * * Asserts when there is no data in the receive FIFO/Buffer. This field does not * take into account data that is in the receive shift register. * * Values: * - 0 - Receive buffer is not empty. * - 1 - Receive buffer is empty. */ /*@{*/ #define BP_UART_SFIFO_RXEMPT (6U) /*!< Bit position for UART_SFIFO_RXEMPT. */ #define BM_UART_SFIFO_RXEMPT (0x40U) /*!< Bit mask for UART_SFIFO_RXEMPT. */ #define BS_UART_SFIFO_RXEMPT (1U) /*!< Bit field size in bits for UART_SFIFO_RXEMPT. */ /*! @brief Read current value of the UART_SFIFO_RXEMPT field. */ #define BR_UART_SFIFO_RXEMPT(x) (BITBAND_ACCESS8(HW_UART_SFIFO_ADDR(x), BP_UART_SFIFO_RXEMPT)) /*@}*/ /*! * @name Register UART_SFIFO, field TXEMPT[7] (RO) * * Asserts when there is no data in the Transmit FIFO/buffer. This field does * not take into account data that is in the transmit shift register. * * Values: * - 0 - Transmit buffer is not empty. * - 1 - Transmit buffer is empty. */ /*@{*/ #define BP_UART_SFIFO_TXEMPT (7U) /*!< Bit position for UART_SFIFO_TXEMPT. */ #define BM_UART_SFIFO_TXEMPT (0x80U) /*!< Bit mask for UART_SFIFO_TXEMPT. */ #define BS_UART_SFIFO_TXEMPT (1U) /*!< Bit field size in bits for UART_SFIFO_TXEMPT. */ /*! @brief Read current value of the UART_SFIFO_TXEMPT field. */ #define BR_UART_SFIFO_TXEMPT(x) (BITBAND_ACCESS8(HW_UART_SFIFO_ADDR(x), BP_UART_SFIFO_TXEMPT)) /*@}*/ /******************************************************************************* * HW_UART_TWFIFO - UART FIFO Transmit Watermark ******************************************************************************/ /*! * @brief HW_UART_TWFIFO - UART FIFO Transmit Watermark (RW) * * Reset value: 0x00U * * This register provides the ability to set a programmable threshold for * notification of needing additional transmit data. This register may be read at any * time but must be written only when C2[TE] is not set. Changing the value of the * watermark will not clear the S1[TDRE] flag. */ typedef union _hw_uart_twfifo { uint8_t U; struct _hw_uart_twfifo_bitfields { uint8_t TXWATER : 8; /*!< [7:0] Transmit Watermark */ } B; } hw_uart_twfifo_t; /*! * @name Constants and macros for entire UART_TWFIFO register */ /*@{*/ #define HW_UART_TWFIFO_ADDR(x) ((x) + 0x13U) #define HW_UART_TWFIFO(x) (*(__IO hw_uart_twfifo_t *) HW_UART_TWFIFO_ADDR(x)) #define HW_UART_TWFIFO_RD(x) (HW_UART_TWFIFO(x).U) #define HW_UART_TWFIFO_WR(x, v) (HW_UART_TWFIFO(x).U = (v)) #define HW_UART_TWFIFO_SET(x, v) (HW_UART_TWFIFO_WR(x, HW_UART_TWFIFO_RD(x) | (v))) #define HW_UART_TWFIFO_CLR(x, v) (HW_UART_TWFIFO_WR(x, HW_UART_TWFIFO_RD(x) & ~(v))) #define HW_UART_TWFIFO_TOG(x, v) (HW_UART_TWFIFO_WR(x, HW_UART_TWFIFO_RD(x) ^ (v))) /*@}*/ /* * Constants & macros for individual UART_TWFIFO bitfields */ /*! * @name Register UART_TWFIFO, field TXWATER[7:0] (RW) * * When the number of datawords in the transmit FIFO/buffer is equal to or less * than the value in this register field, an interrupt via S1[TDRE] or a DMA * request via C5[TDMAS] is generated as determined by C5[TDMAS] and C2[TIE]. For * proper operation, the value in TXWATER must be set to be less than the size of * the transmit buffer/FIFO size as indicated by PFIFO[TXFIFOSIZE] and PFIFO[TXFE]. */ /*@{*/ #define BP_UART_TWFIFO_TXWATER (0U) /*!< Bit position for UART_TWFIFO_TXWATER. */ #define BM_UART_TWFIFO_TXWATER (0xFFU) /*!< Bit mask for UART_TWFIFO_TXWATER. */ #define BS_UART_TWFIFO_TXWATER (8U) /*!< Bit field size in bits for UART_TWFIFO_TXWATER. */ /*! @brief Read current value of the UART_TWFIFO_TXWATER field. */ #define BR_UART_TWFIFO_TXWATER(x) (HW_UART_TWFIFO(x).U) /*! @brief Format value for bitfield UART_TWFIFO_TXWATER. */ #define BF_UART_TWFIFO_TXWATER(v) ((uint8_t)((uint8_t)(v) << BP_UART_TWFIFO_TXWATER) & BM_UART_TWFIFO_TXWATER) /*! @brief Set the TXWATER field to a new value. */ #define BW_UART_TWFIFO_TXWATER(x, v) (HW_UART_TWFIFO_WR(x, v)) /*@}*/ /******************************************************************************* * HW_UART_TCFIFO - UART FIFO Transmit Count ******************************************************************************/ /*! * @brief HW_UART_TCFIFO - UART FIFO Transmit Count (RO) * * Reset value: 0x00U * * This is a read only register that indicates how many datawords are currently * in the transmit buffer/FIFO. It may be read at any time. */ typedef union _hw_uart_tcfifo { uint8_t U; struct _hw_uart_tcfifo_bitfields { uint8_t TXCOUNT : 8; /*!< [7:0] Transmit Counter */ } B; } hw_uart_tcfifo_t; /*! * @name Constants and macros for entire UART_TCFIFO register */ /*@{*/ #define HW_UART_TCFIFO_ADDR(x) ((x) + 0x14U) #define HW_UART_TCFIFO(x) (*(__I hw_uart_tcfifo_t *) HW_UART_TCFIFO_ADDR(x)) #define HW_UART_TCFIFO_RD(x) (HW_UART_TCFIFO(x).U) /*@}*/ /* * Constants & macros for individual UART_TCFIFO bitfields */ /*! * @name Register UART_TCFIFO, field TXCOUNT[7:0] (RO) * * The value in this register indicates the number of datawords that are in the * transmit FIFO/buffer. If a dataword is being transmitted, that is, in the * transmit shift register, it is not included in the count. This value may be used * in conjunction with PFIFO[TXFIFOSIZE] to calculate how much room is left in the * transmit FIFO/buffer. */ /*@{*/ #define BP_UART_TCFIFO_TXCOUNT (0U) /*!< Bit position for UART_TCFIFO_TXCOUNT. */ #define BM_UART_TCFIFO_TXCOUNT (0xFFU) /*!< Bit mask for UART_TCFIFO_TXCOUNT. */ #define BS_UART_TCFIFO_TXCOUNT (8U) /*!< Bit field size in bits for UART_TCFIFO_TXCOUNT. */ /*! @brief Read current value of the UART_TCFIFO_TXCOUNT field. */ #define BR_UART_TCFIFO_TXCOUNT(x) (HW_UART_TCFIFO(x).U) /*@}*/ /******************************************************************************* * HW_UART_RWFIFO - UART FIFO Receive Watermark ******************************************************************************/ /*! * @brief HW_UART_RWFIFO - UART FIFO Receive Watermark (RW) * * Reset value: 0x01U * * This register provides the ability to set a programmable threshold for * notification of the need to remove data from the receiver FIFO/buffer. This register * may be read at any time but must be written only when C2[RE] is not asserted. * Changing the value in this register will not clear S1[RDRF]. */ typedef union _hw_uart_rwfifo { uint8_t U; struct _hw_uart_rwfifo_bitfields { uint8_t RXWATER : 8; /*!< [7:0] Receive Watermark */ } B; } hw_uart_rwfifo_t; /*! * @name Constants and macros for entire UART_RWFIFO register */ /*@{*/ #define HW_UART_RWFIFO_ADDR(x) ((x) + 0x15U) #define HW_UART_RWFIFO(x) (*(__IO hw_uart_rwfifo_t *) HW_UART_RWFIFO_ADDR(x)) #define HW_UART_RWFIFO_RD(x) (HW_UART_RWFIFO(x).U) #define HW_UART_RWFIFO_WR(x, v) (HW_UART_RWFIFO(x).U = (v)) #define HW_UART_RWFIFO_SET(x, v) (HW_UART_RWFIFO_WR(x, HW_UART_RWFIFO_RD(x) | (v))) #define HW_UART_RWFIFO_CLR(x, v) (HW_UART_RWFIFO_WR(x, HW_UART_RWFIFO_RD(x) & ~(v))) #define HW_UART_RWFIFO_TOG(x, v) (HW_UART_RWFIFO_WR(x, HW_UART_RWFIFO_RD(x) ^ (v))) /*@}*/ /* * Constants & macros for individual UART_RWFIFO bitfields */ /*! * @name Register UART_RWFIFO, field RXWATER[7:0] (RW) * * When the number of datawords in the receive FIFO/buffer is equal to or * greater than the value in this register field, an interrupt via S1[RDRF] or a DMA * request via C5[RDMAS] is generated as determined by C5[RDMAS] and C2[RIE]. For * proper operation, the value in RXWATER must be set to be less than the receive * FIFO/buffer size as indicated by PFIFO[RXFIFOSIZE] and PFIFO[RXFE] and must be * greater than 0. */ /*@{*/ #define BP_UART_RWFIFO_RXWATER (0U) /*!< Bit position for UART_RWFIFO_RXWATER. */ #define BM_UART_RWFIFO_RXWATER (0xFFU) /*!< Bit mask for UART_RWFIFO_RXWATER. */ #define BS_UART_RWFIFO_RXWATER (8U) /*!< Bit field size in bits for UART_RWFIFO_RXWATER. */ /*! @brief Read current value of the UART_RWFIFO_RXWATER field. */ #define BR_UART_RWFIFO_RXWATER(x) (HW_UART_RWFIFO(x).U) /*! @brief Format value for bitfield UART_RWFIFO_RXWATER. */ #define BF_UART_RWFIFO_RXWATER(v) ((uint8_t)((uint8_t)(v) << BP_UART_RWFIFO_RXWATER) & BM_UART_RWFIFO_RXWATER) /*! @brief Set the RXWATER field to a new value. */ #define BW_UART_RWFIFO_RXWATER(x, v) (HW_UART_RWFIFO_WR(x, v)) /*@}*/ /******************************************************************************* * HW_UART_RCFIFO - UART FIFO Receive Count ******************************************************************************/ /*! * @brief HW_UART_RCFIFO - UART FIFO Receive Count (RO) * * Reset value: 0x00U * * This is a read only register that indicates how many datawords are currently * in the receive FIFO/buffer. It may be read at any time. */ typedef union _hw_uart_rcfifo { uint8_t U; struct _hw_uart_rcfifo_bitfields { uint8_t RXCOUNT : 8; /*!< [7:0] Receive Counter */ } B; } hw_uart_rcfifo_t; /*! * @name Constants and macros for entire UART_RCFIFO register */ /*@{*/ #define HW_UART_RCFIFO_ADDR(x) ((x) + 0x16U) #define HW_UART_RCFIFO(x) (*(__I hw_uart_rcfifo_t *) HW_UART_RCFIFO_ADDR(x)) #define HW_UART_RCFIFO_RD(x) (HW_UART_RCFIFO(x).U) /*@}*/ /* * Constants & macros for individual UART_RCFIFO bitfields */ /*! * @name Register UART_RCFIFO, field RXCOUNT[7:0] (RO) * * The value in this register indicates the number of datawords that are in the * receive FIFO/buffer. If a dataword is being received, that is, in the receive * shift register, it is not included in the count. This value may be used in * conjunction with PFIFO[RXFIFOSIZE] to calculate how much room is left in the * receive FIFO/buffer. */ /*@{*/ #define BP_UART_RCFIFO_RXCOUNT (0U) /*!< Bit position for UART_RCFIFO_RXCOUNT. */ #define BM_UART_RCFIFO_RXCOUNT (0xFFU) /*!< Bit mask for UART_RCFIFO_RXCOUNT. */ #define BS_UART_RCFIFO_RXCOUNT (8U) /*!< Bit field size in bits for UART_RCFIFO_RXCOUNT. */ /*! @brief Read current value of the UART_RCFIFO_RXCOUNT field. */ #define BR_UART_RCFIFO_RXCOUNT(x) (HW_UART_RCFIFO(x).U) /*@}*/ /******************************************************************************* * HW_UART_C7816 - UART 7816 Control Register ******************************************************************************/ /*! * @brief HW_UART_C7816 - UART 7816 Control Register (RW) * * Reset value: 0x00U * * The C7816 register is the primary control register for ISO-7816 specific * functionality. This register is specific to 7816 functionality and the values in * this register have no effect on UART operation and should be ignored if * ISO_7816E is not set/enabled. This register may be read at any time but values must * be changed only when ISO_7816E is not set. */ typedef union _hw_uart_c7816 { uint8_t U; struct _hw_uart_c7816_bitfields { uint8_t ISO_7816E : 1; /*!< [0] ISO-7816 Functionality Enabled */ uint8_t TTYPE : 1; /*!< [1] Transfer Type */ uint8_t INIT : 1; /*!< [2] Detect Initial Character */ uint8_t ANACK : 1; /*!< [3] Generate NACK on Error */ uint8_t ONACK : 1; /*!< [4] Generate NACK on Overflow */ uint8_t RESERVED0 : 3; /*!< [7:5] */ } B; } hw_uart_c7816_t; /*! * @name Constants and macros for entire UART_C7816 register */ /*@{*/ #define HW_UART_C7816_ADDR(x) ((x) + 0x18U) #define HW_UART_C7816(x) (*(__IO hw_uart_c7816_t *) HW_UART_C7816_ADDR(x)) #define HW_UART_C7816_RD(x) (HW_UART_C7816(x).U) #define HW_UART_C7816_WR(x, v) (HW_UART_C7816(x).U = (v)) #define HW_UART_C7816_SET(x, v) (HW_UART_C7816_WR(x, HW_UART_C7816_RD(x) | (v))) #define HW_UART_C7816_CLR(x, v) (HW_UART_C7816_WR(x, HW_UART_C7816_RD(x) & ~(v))) #define HW_UART_C7816_TOG(x, v) (HW_UART_C7816_WR(x, HW_UART_C7816_RD(x) ^ (v))) /*@}*/ /* * Constants & macros for individual UART_C7816 bitfields */ /*! * @name Register UART_C7816, field ISO_7816E[0] (RW) * * Indicates that the UART is operating according to the ISO-7816 protocol. This * field must be modified only when no transmit or receive is occurring. If this * field is changed during a data transfer, the data being transmitted or * received may be transferred incorrectly. * * Values: * - 0 - ISO-7816 functionality is turned off/not enabled. * - 1 - ISO-7816 functionality is turned on/enabled. */ /*@{*/ #define BP_UART_C7816_ISO_7816E (0U) /*!< Bit position for UART_C7816_ISO_7816E. */ #define BM_UART_C7816_ISO_7816E (0x01U) /*!< Bit mask for UART_C7816_ISO_7816E. */ #define BS_UART_C7816_ISO_7816E (1U) /*!< Bit field size in bits for UART_C7816_ISO_7816E. */ /*! @brief Read current value of the UART_C7816_ISO_7816E field. */ #define BR_UART_C7816_ISO_7816E(x) (BITBAND_ACCESS8(HW_UART_C7816_ADDR(x), BP_UART_C7816_ISO_7816E)) /*! @brief Format value for bitfield UART_C7816_ISO_7816E. */ #define BF_UART_C7816_ISO_7816E(v) ((uint8_t)((uint8_t)(v) << BP_UART_C7816_ISO_7816E) & BM_UART_C7816_ISO_7816E) /*! @brief Set the ISO_7816E field to a new value. */ #define BW_UART_C7816_ISO_7816E(x, v) (BITBAND_ACCESS8(HW_UART_C7816_ADDR(x), BP_UART_C7816_ISO_7816E) = (v)) /*@}*/ /*! * @name Register UART_C7816, field TTYPE[1] (RW) * * Indicates the transfer protocol being used. See ISO-7816 / smartcard support * for more details. * * Values: * - 0 - T = 0 per the ISO-7816 specification. * - 1 - T = 1 per the ISO-7816 specification. */ /*@{*/ #define BP_UART_C7816_TTYPE (1U) /*!< Bit position for UART_C7816_TTYPE. */ #define BM_UART_C7816_TTYPE (0x02U) /*!< Bit mask for UART_C7816_TTYPE. */ #define BS_UART_C7816_TTYPE (1U) /*!< Bit field size in bits for UART_C7816_TTYPE. */ /*! @brief Read current value of the UART_C7816_TTYPE field. */ #define BR_UART_C7816_TTYPE(x) (BITBAND_ACCESS8(HW_UART_C7816_ADDR(x), BP_UART_C7816_TTYPE)) /*! @brief Format value for bitfield UART_C7816_TTYPE. */ #define BF_UART_C7816_TTYPE(v) ((uint8_t)((uint8_t)(v) << BP_UART_C7816_TTYPE) & BM_UART_C7816_TTYPE) /*! @brief Set the TTYPE field to a new value. */ #define BW_UART_C7816_TTYPE(x, v) (BITBAND_ACCESS8(HW_UART_C7816_ADDR(x), BP_UART_C7816_TTYPE) = (v)) /*@}*/ /*! * @name Register UART_C7816, field INIT[2] (RW) * * When this field is set, all received characters are searched for a valid * initial character. If an invalid initial character is identified, and ANACK is * set, a NACK is sent. All received data is discarded and error flags blocked * (S1[NF], S1[OR], S1[FE], S1[PF], IS7816[WT], IS7816[CWT], IS7816[BWT], IS7816[GTV]) * until a valid initial character is detected. Upon detecting a valid initial * character, the configuration values S2[MSBF], C3[TXINV], and S2[RXINV] are * automatically updated to reflect the initial character that was received. The * actual INIT data value is not stored in the receive buffer. Additionally, upon * detection of a valid initial character, IS7816[INITD] is set and an interrupt * issued as programmed by IE7816[INITDE]. When a valid initial character is * detected, INIT is automatically cleared. This Initial Character Detect feature is * supported only in T = 0 protocol mode. * * Values: * - 0 - Normal operating mode. Receiver does not seek to identify initial * character. * - 1 - Receiver searches for initial character. */ /*@{*/ #define BP_UART_C7816_INIT (2U) /*!< Bit position for UART_C7816_INIT. */ #define BM_UART_C7816_INIT (0x04U) /*!< Bit mask for UART_C7816_INIT. */ #define BS_UART_C7816_INIT (1U) /*!< Bit field size in bits for UART_C7816_INIT. */ /*! @brief Read current value of the UART_C7816_INIT field. */ #define BR_UART_C7816_INIT(x) (BITBAND_ACCESS8(HW_UART_C7816_ADDR(x), BP_UART_C7816_INIT)) /*! @brief Format value for bitfield UART_C7816_INIT. */ #define BF_UART_C7816_INIT(v) ((uint8_t)((uint8_t)(v) << BP_UART_C7816_INIT) & BM_UART_C7816_INIT) /*! @brief Set the INIT field to a new value. */ #define BW_UART_C7816_INIT(x, v) (BITBAND_ACCESS8(HW_UART_C7816_ADDR(x), BP_UART_C7816_INIT) = (v)) /*@}*/ /*! * @name Register UART_C7816, field ANACK[3] (RW) * * When this field is set, the receiver automatically generates a NACK response * if a parity error occurs or if INIT is set and an invalid initial character is * detected. A NACK is generated only if TTYPE = 0. If ANACK is set, the UART * attempts to retransmit the data indefinitely. To stop retransmission attempts, * clear C2[TE] or ISO_7816E and do not set until S1[TC] sets C2[TE] again. * * Values: * - 0 - No NACK is automatically generated. * - 1 - A NACK is automatically generated if a parity error is detected or if * an invalid initial character is detected. */ /*@{*/ #define BP_UART_C7816_ANACK (3U) /*!< Bit position for UART_C7816_ANACK. */ #define BM_UART_C7816_ANACK (0x08U) /*!< Bit mask for UART_C7816_ANACK. */ #define BS_UART_C7816_ANACK (1U) /*!< Bit field size in bits for UART_C7816_ANACK. */ /*! @brief Read current value of the UART_C7816_ANACK field. */ #define BR_UART_C7816_ANACK(x) (BITBAND_ACCESS8(HW_UART_C7816_ADDR(x), BP_UART_C7816_ANACK)) /*! @brief Format value for bitfield UART_C7816_ANACK. */ #define BF_UART_C7816_ANACK(v) ((uint8_t)((uint8_t)(v) << BP_UART_C7816_ANACK) & BM_UART_C7816_ANACK) /*! @brief Set the ANACK field to a new value. */ #define BW_UART_C7816_ANACK(x, v) (BITBAND_ACCESS8(HW_UART_C7816_ADDR(x), BP_UART_C7816_ANACK) = (v)) /*@}*/ /*! * @name Register UART_C7816, field ONACK[4] (RW) * * When this field is set, the receiver automatically generates a NACK response * if a receive buffer overrun occurs, as indicated by S1[OR]. In many systems, * this results in the transmitter resending the packet that overflowed until the * retransmit threshold for that transmitter is reached. A NACK is generated only * if TTYPE=0. This field operates independently of ANACK. See . Overrun NACK * considerations * * Values: * - 0 - The received data does not generate a NACK when the receipt of the data * results in an overflow event. * - 1 - If the receiver buffer overflows, a NACK is automatically sent on a * received character. */ /*@{*/ #define BP_UART_C7816_ONACK (4U) /*!< Bit position for UART_C7816_ONACK. */ #define BM_UART_C7816_ONACK (0x10U) /*!< Bit mask for UART_C7816_ONACK. */ #define BS_UART_C7816_ONACK (1U) /*!< Bit field size in bits for UART_C7816_ONACK. */ /*! @brief Read current value of the UART_C7816_ONACK field. */ #define BR_UART_C7816_ONACK(x) (BITBAND_ACCESS8(HW_UART_C7816_ADDR(x), BP_UART_C7816_ONACK)) /*! @brief Format value for bitfield UART_C7816_ONACK. */ #define BF_UART_C7816_ONACK(v) ((uint8_t)((uint8_t)(v) << BP_UART_C7816_ONACK) & BM_UART_C7816_ONACK) /*! @brief Set the ONACK field to a new value. */ #define BW_UART_C7816_ONACK(x, v) (BITBAND_ACCESS8(HW_UART_C7816_ADDR(x), BP_UART_C7816_ONACK) = (v)) /*@}*/ /******************************************************************************* * HW_UART_IE7816 - UART 7816 Interrupt Enable Register ******************************************************************************/ /*! * @brief HW_UART_IE7816 - UART 7816 Interrupt Enable Register (RW) * * Reset value: 0x00U * * The IE7816 register controls which flags result in an interrupt being issued. * This register is specific to 7816 functionality, the corresponding flags that * drive the interrupts are not asserted when 7816E is not set/enabled. However, * these flags may remain set if they are asserted while 7816E was set and not * subsequently cleared. This register may be read or written to at any time. */ typedef union _hw_uart_ie7816 { uint8_t U; struct _hw_uart_ie7816_bitfields { uint8_t RXTE : 1; /*!< [0] Receive Threshold Exceeded Interrupt * Enable */ uint8_t TXTE : 1; /*!< [1] Transmit Threshold Exceeded Interrupt * Enable */ uint8_t GTVE : 1; /*!< [2] Guard Timer Violated Interrupt Enable */ uint8_t RESERVED0 : 1; /*!< [3] */ uint8_t INITDE : 1; /*!< [4] Initial Character Detected Interrupt * Enable */ uint8_t BWTE : 1; /*!< [5] Block Wait Timer Interrupt Enable */ uint8_t CWTE : 1; /*!< [6] Character Wait Timer Interrupt Enable */ uint8_t WTE : 1; /*!< [7] Wait Timer Interrupt Enable */ } B; } hw_uart_ie7816_t; /*! * @name Constants and macros for entire UART_IE7816 register */ /*@{*/ #define HW_UART_IE7816_ADDR(x) ((x) + 0x19U) #define HW_UART_IE7816(x) (*(__IO hw_uart_ie7816_t *) HW_UART_IE7816_ADDR(x)) #define HW_UART_IE7816_RD(x) (HW_UART_IE7816(x).U) #define HW_UART_IE7816_WR(x, v) (HW_UART_IE7816(x).U = (v)) #define HW_UART_IE7816_SET(x, v) (HW_UART_IE7816_WR(x, HW_UART_IE7816_RD(x) | (v))) #define HW_UART_IE7816_CLR(x, v) (HW_UART_IE7816_WR(x, HW_UART_IE7816_RD(x) & ~(v))) #define HW_UART_IE7816_TOG(x, v) (HW_UART_IE7816_WR(x, HW_UART_IE7816_RD(x) ^ (v))) /*@}*/ /* * Constants & macros for individual UART_IE7816 bitfields */ /*! * @name Register UART_IE7816, field RXTE[0] (RW) * * Values: * - 0 - The assertion of IS7816[RXT] does not result in the generation of an * interrupt. * - 1 - The assertion of IS7816[RXT] results in the generation of an interrupt. */ /*@{*/ #define BP_UART_IE7816_RXTE (0U) /*!< Bit position for UART_IE7816_RXTE. */ #define BM_UART_IE7816_RXTE (0x01U) /*!< Bit mask for UART_IE7816_RXTE. */ #define BS_UART_IE7816_RXTE (1U) /*!< Bit field size in bits for UART_IE7816_RXTE. */ /*! @brief Read current value of the UART_IE7816_RXTE field. */ #define BR_UART_IE7816_RXTE(x) (BITBAND_ACCESS8(HW_UART_IE7816_ADDR(x), BP_UART_IE7816_RXTE)) /*! @brief Format value for bitfield UART_IE7816_RXTE. */ #define BF_UART_IE7816_RXTE(v) ((uint8_t)((uint8_t)(v) << BP_UART_IE7816_RXTE) & BM_UART_IE7816_RXTE) /*! @brief Set the RXTE field to a new value. */ #define BW_UART_IE7816_RXTE(x, v) (BITBAND_ACCESS8(HW_UART_IE7816_ADDR(x), BP_UART_IE7816_RXTE) = (v)) /*@}*/ /*! * @name Register UART_IE7816, field TXTE[1] (RW) * * Values: * - 0 - The assertion of IS7816[TXT] does not result in the generation of an * interrupt. * - 1 - The assertion of IS7816[TXT] results in the generation of an interrupt. */ /*@{*/ #define BP_UART_IE7816_TXTE (1U) /*!< Bit position for UART_IE7816_TXTE. */ #define BM_UART_IE7816_TXTE (0x02U) /*!< Bit mask for UART_IE7816_TXTE. */ #define BS_UART_IE7816_TXTE (1U) /*!< Bit field size in bits for UART_IE7816_TXTE. */ /*! @brief Read current value of the UART_IE7816_TXTE field. */ #define BR_UART_IE7816_TXTE(x) (BITBAND_ACCESS8(HW_UART_IE7816_ADDR(x), BP_UART_IE7816_TXTE)) /*! @brief Format value for bitfield UART_IE7816_TXTE. */ #define BF_UART_IE7816_TXTE(v) ((uint8_t)((uint8_t)(v) << BP_UART_IE7816_TXTE) & BM_UART_IE7816_TXTE) /*! @brief Set the TXTE field to a new value. */ #define BW_UART_IE7816_TXTE(x, v) (BITBAND_ACCESS8(HW_UART_IE7816_ADDR(x), BP_UART_IE7816_TXTE) = (v)) /*@}*/ /*! * @name Register UART_IE7816, field GTVE[2] (RW) * * Values: * - 0 - The assertion of IS7816[GTV] does not result in the generation of an * interrupt. * - 1 - The assertion of IS7816[GTV] results in the generation of an interrupt. */ /*@{*/ #define BP_UART_IE7816_GTVE (2U) /*!< Bit position for UART_IE7816_GTVE. */ #define BM_UART_IE7816_GTVE (0x04U) /*!< Bit mask for UART_IE7816_GTVE. */ #define BS_UART_IE7816_GTVE (1U) /*!< Bit field size in bits for UART_IE7816_GTVE. */ /*! @brief Read current value of the UART_IE7816_GTVE field. */ #define BR_UART_IE7816_GTVE(x) (BITBAND_ACCESS8(HW_UART_IE7816_ADDR(x), BP_UART_IE7816_GTVE)) /*! @brief Format value for bitfield UART_IE7816_GTVE. */ #define BF_UART_IE7816_GTVE(v) ((uint8_t)((uint8_t)(v) << BP_UART_IE7816_GTVE) & BM_UART_IE7816_GTVE) /*! @brief Set the GTVE field to a new value. */ #define BW_UART_IE7816_GTVE(x, v) (BITBAND_ACCESS8(HW_UART_IE7816_ADDR(x), BP_UART_IE7816_GTVE) = (v)) /*@}*/ /*! * @name Register UART_IE7816, field INITDE[4] (RW) * * Values: * - 0 - The assertion of IS7816[INITD] does not result in the generation of an * interrupt. * - 1 - The assertion of IS7816[INITD] results in the generation of an * interrupt. */ /*@{*/ #define BP_UART_IE7816_INITDE (4U) /*!< Bit position for UART_IE7816_INITDE. */ #define BM_UART_IE7816_INITDE (0x10U) /*!< Bit mask for UART_IE7816_INITDE. */ #define BS_UART_IE7816_INITDE (1U) /*!< Bit field size in bits for UART_IE7816_INITDE. */ /*! @brief Read current value of the UART_IE7816_INITDE field. */ #define BR_UART_IE7816_INITDE(x) (BITBAND_ACCESS8(HW_UART_IE7816_ADDR(x), BP_UART_IE7816_INITDE)) /*! @brief Format value for bitfield UART_IE7816_INITDE. */ #define BF_UART_IE7816_INITDE(v) ((uint8_t)((uint8_t)(v) << BP_UART_IE7816_INITDE) & BM_UART_IE7816_INITDE) /*! @brief Set the INITDE field to a new value. */ #define BW_UART_IE7816_INITDE(x, v) (BITBAND_ACCESS8(HW_UART_IE7816_ADDR(x), BP_UART_IE7816_INITDE) = (v)) /*@}*/ /*! * @name Register UART_IE7816, field BWTE[5] (RW) * * Values: * - 0 - The assertion of IS7816[BWT] does not result in the generation of an * interrupt. * - 1 - The assertion of IS7816[BWT] results in the generation of an interrupt. */ /*@{*/ #define BP_UART_IE7816_BWTE (5U) /*!< Bit position for UART_IE7816_BWTE. */ #define BM_UART_IE7816_BWTE (0x20U) /*!< Bit mask for UART_IE7816_BWTE. */ #define BS_UART_IE7816_BWTE (1U) /*!< Bit field size in bits for UART_IE7816_BWTE. */ /*! @brief Read current value of the UART_IE7816_BWTE field. */ #define BR_UART_IE7816_BWTE(x) (BITBAND_ACCESS8(HW_UART_IE7816_ADDR(x), BP_UART_IE7816_BWTE)) /*! @brief Format value for bitfield UART_IE7816_BWTE. */ #define BF_UART_IE7816_BWTE(v) ((uint8_t)((uint8_t)(v) << BP_UART_IE7816_BWTE) & BM_UART_IE7816_BWTE) /*! @brief Set the BWTE field to a new value. */ #define BW_UART_IE7816_BWTE(x, v) (BITBAND_ACCESS8(HW_UART_IE7816_ADDR(x), BP_UART_IE7816_BWTE) = (v)) /*@}*/ /*! * @name Register UART_IE7816, field CWTE[6] (RW) * * Values: * - 0 - The assertion of IS7816[CWT] does not result in the generation of an * interrupt. * - 1 - The assertion of IS7816[CWT] results in the generation of an interrupt. */ /*@{*/ #define BP_UART_IE7816_CWTE (6U) /*!< Bit position for UART_IE7816_CWTE. */ #define BM_UART_IE7816_CWTE (0x40U) /*!< Bit mask for UART_IE7816_CWTE. */ #define BS_UART_IE7816_CWTE (1U) /*!< Bit field size in bits for UART_IE7816_CWTE. */ /*! @brief Read current value of the UART_IE7816_CWTE field. */ #define BR_UART_IE7816_CWTE(x) (BITBAND_ACCESS8(HW_UART_IE7816_ADDR(x), BP_UART_IE7816_CWTE)) /*! @brief Format value for bitfield UART_IE7816_CWTE. */ #define BF_UART_IE7816_CWTE(v) ((uint8_t)((uint8_t)(v) << BP_UART_IE7816_CWTE) & BM_UART_IE7816_CWTE) /*! @brief Set the CWTE field to a new value. */ #define BW_UART_IE7816_CWTE(x, v) (BITBAND_ACCESS8(HW_UART_IE7816_ADDR(x), BP_UART_IE7816_CWTE) = (v)) /*@}*/ /*! * @name Register UART_IE7816, field WTE[7] (RW) * * Values: * - 0 - The assertion of IS7816[WT] does not result in the generation of an * interrupt. * - 1 - The assertion of IS7816[WT] results in the generation of an interrupt. */ /*@{*/ #define BP_UART_IE7816_WTE (7U) /*!< Bit position for UART_IE7816_WTE. */ #define BM_UART_IE7816_WTE (0x80U) /*!< Bit mask for UART_IE7816_WTE. */ #define BS_UART_IE7816_WTE (1U) /*!< Bit field size in bits for UART_IE7816_WTE. */ /*! @brief Read current value of the UART_IE7816_WTE field. */ #define BR_UART_IE7816_WTE(x) (BITBAND_ACCESS8(HW_UART_IE7816_ADDR(x), BP_UART_IE7816_WTE)) /*! @brief Format value for bitfield UART_IE7816_WTE. */ #define BF_UART_IE7816_WTE(v) ((uint8_t)((uint8_t)(v) << BP_UART_IE7816_WTE) & BM_UART_IE7816_WTE) /*! @brief Set the WTE field to a new value. */ #define BW_UART_IE7816_WTE(x, v) (BITBAND_ACCESS8(HW_UART_IE7816_ADDR(x), BP_UART_IE7816_WTE) = (v)) /*@}*/ /******************************************************************************* * HW_UART_IS7816 - UART 7816 Interrupt Status Register ******************************************************************************/ /*! * @brief HW_UART_IS7816 - UART 7816 Interrupt Status Register (RW) * * Reset value: 0x00U * * The IS7816 register provides a mechanism to read and clear the interrupt * flags. All flags/interrupts are cleared by writing a 1 to the field location. * Writing a 0 has no effect. All bits are "sticky", meaning they indicate that only * the flag condition that occurred since the last time the bit was cleared, not * that the condition currently exists. The status flags are set regardless of * whether the corresponding field in the IE7816 is set or cleared. The IE7816 * controls only if an interrupt is issued to the host processor. This register is * specific to 7816 functionality and the values in this register have no affect on * UART operation and should be ignored if 7816E is not set/enabled. This * register may be read or written at anytime. */ typedef union _hw_uart_is7816 { uint8_t U; struct _hw_uart_is7816_bitfields { uint8_t RXT : 1; /*!< [0] Receive Threshold Exceeded Interrupt */ uint8_t TXT : 1; /*!< [1] Transmit Threshold Exceeded Interrupt */ uint8_t GTV : 1; /*!< [2] Guard Timer Violated Interrupt */ uint8_t RESERVED0 : 1; /*!< [3] */ uint8_t INITD : 1; /*!< [4] Initial Character Detected Interrupt */ uint8_t BWT : 1; /*!< [5] Block Wait Timer Interrupt */ uint8_t CWT : 1; /*!< [6] Character Wait Timer Interrupt */ uint8_t WT : 1; /*!< [7] Wait Timer Interrupt */ } B; } hw_uart_is7816_t; /*! * @name Constants and macros for entire UART_IS7816 register */ /*@{*/ #define HW_UART_IS7816_ADDR(x) ((x) + 0x1AU) #define HW_UART_IS7816(x) (*(__IO hw_uart_is7816_t *) HW_UART_IS7816_ADDR(x)) #define HW_UART_IS7816_RD(x) (HW_UART_IS7816(x).U) #define HW_UART_IS7816_WR(x, v) (HW_UART_IS7816(x).U = (v)) #define HW_UART_IS7816_SET(x, v) (HW_UART_IS7816_WR(x, HW_UART_IS7816_RD(x) | (v))) #define HW_UART_IS7816_CLR(x, v) (HW_UART_IS7816_WR(x, HW_UART_IS7816_RD(x) & ~(v))) #define HW_UART_IS7816_TOG(x, v) (HW_UART_IS7816_WR(x, HW_UART_IS7816_RD(x) ^ (v))) /*@}*/ /* * Constants & macros for individual UART_IS7816 bitfields */ /*! * @name Register UART_IS7816, field RXT[0] (W1C) * * Indicates that there are more than ET7816[RXTHRESHOLD] consecutive NACKS * generated in response to parity errors on received data. This flag requires ANACK * to be set. Additionally, this flag asserts only when C7816[TTYPE] = 0. * Clearing this field also resets the counter keeping track of consecutive NACKS. The * UART will continue to attempt to receive data regardless of whether this flag * is set. If 7816E is cleared/disabled, RE is cleared/disabled, C7816[TTYPE] = 1, * or packet is received without needing to issue a NACK, the internal NACK * detection counter is cleared and the count restarts from zero on the next * transmitted NACK. This interrupt is cleared by writing 1. * * Values: * - 0 - The number of consecutive NACKS generated as a result of parity errors * and buffer overruns is less than or equal to the value in * ET7816[RXTHRESHOLD]. * - 1 - The number of consecutive NACKS generated as a result of parity errors * and buffer overruns is greater than the value in ET7816[RXTHRESHOLD]. */ /*@{*/ #define BP_UART_IS7816_RXT (0U) /*!< Bit position for UART_IS7816_RXT. */ #define BM_UART_IS7816_RXT (0x01U) /*!< Bit mask for UART_IS7816_RXT. */ #define BS_UART_IS7816_RXT (1U) /*!< Bit field size in bits for UART_IS7816_RXT. */ /*! @brief Read current value of the UART_IS7816_RXT field. */ #define BR_UART_IS7816_RXT(x) (BITBAND_ACCESS8(HW_UART_IS7816_ADDR(x), BP_UART_IS7816_RXT)) /*! @brief Format value for bitfield UART_IS7816_RXT. */ #define BF_UART_IS7816_RXT(v) ((uint8_t)((uint8_t)(v) << BP_UART_IS7816_RXT) & BM_UART_IS7816_RXT) /*! @brief Set the RXT field to a new value. */ #define BW_UART_IS7816_RXT(x, v) (BITBAND_ACCESS8(HW_UART_IS7816_ADDR(x), BP_UART_IS7816_RXT) = (v)) /*@}*/ /*! * @name Register UART_IS7816, field TXT[1] (W1C) * * Indicates that the transmit NACK threshold has been exceeded as indicated by * ET7816[TXTHRESHOLD]. Regardless of whether this flag is set, the UART * continues to retransmit indefinitely. This flag asserts only when C7816[TTYPE] = 0. If * 7816E is cleared/disabled, ANACK is cleared/disabled, C2[TE] is * cleared/disabled, C7816[TTYPE] = 1, or packet is transferred without receiving a NACK, the * internal NACK detection counter is cleared and the count restarts from zero on * the next received NACK. This interrupt is cleared by writing 1. * * Values: * - 0 - The number of retries and corresponding NACKS does not exceed the value * in ET7816[TXTHRESHOLD]. * - 1 - The number of retries and corresponding NACKS exceeds the value in * ET7816[TXTHRESHOLD]. */ /*@{*/ #define BP_UART_IS7816_TXT (1U) /*!< Bit position for UART_IS7816_TXT. */ #define BM_UART_IS7816_TXT (0x02U) /*!< Bit mask for UART_IS7816_TXT. */ #define BS_UART_IS7816_TXT (1U) /*!< Bit field size in bits for UART_IS7816_TXT. */ /*! @brief Read current value of the UART_IS7816_TXT field. */ #define BR_UART_IS7816_TXT(x) (BITBAND_ACCESS8(HW_UART_IS7816_ADDR(x), BP_UART_IS7816_TXT)) /*! @brief Format value for bitfield UART_IS7816_TXT. */ #define BF_UART_IS7816_TXT(v) ((uint8_t)((uint8_t)(v) << BP_UART_IS7816_TXT) & BM_UART_IS7816_TXT) /*! @brief Set the TXT field to a new value. */ #define BW_UART_IS7816_TXT(x, v) (BITBAND_ACCESS8(HW_UART_IS7816_ADDR(x), BP_UART_IS7816_TXT) = (v)) /*@}*/ /*! * @name Register UART_IS7816, field GTV[2] (W1C) * * Indicates that one or more of the character guard time, block guard time, or * guard time are violated. This interrupt is cleared by writing 1. * * Values: * - 0 - A guard time (GT, CGT, or BGT) has not been violated. * - 1 - A guard time (GT, CGT, or BGT) has been violated. */ /*@{*/ #define BP_UART_IS7816_GTV (2U) /*!< Bit position for UART_IS7816_GTV. */ #define BM_UART_IS7816_GTV (0x04U) /*!< Bit mask for UART_IS7816_GTV. */ #define BS_UART_IS7816_GTV (1U) /*!< Bit field size in bits for UART_IS7816_GTV. */ /*! @brief Read current value of the UART_IS7816_GTV field. */ #define BR_UART_IS7816_GTV(x) (BITBAND_ACCESS8(HW_UART_IS7816_ADDR(x), BP_UART_IS7816_GTV)) /*! @brief Format value for bitfield UART_IS7816_GTV. */ #define BF_UART_IS7816_GTV(v) ((uint8_t)((uint8_t)(v) << BP_UART_IS7816_GTV) & BM_UART_IS7816_GTV) /*! @brief Set the GTV field to a new value. */ #define BW_UART_IS7816_GTV(x, v) (BITBAND_ACCESS8(HW_UART_IS7816_ADDR(x), BP_UART_IS7816_GTV) = (v)) /*@}*/ /*! * @name Register UART_IS7816, field INITD[4] (W1C) * * Indicates that a valid initial character is received. This interrupt is * cleared by writing 1. * * Values: * - 0 - A valid initial character has not been received. * - 1 - A valid initial character has been received. */ /*@{*/ #define BP_UART_IS7816_INITD (4U) /*!< Bit position for UART_IS7816_INITD. */ #define BM_UART_IS7816_INITD (0x10U) /*!< Bit mask for UART_IS7816_INITD. */ #define BS_UART_IS7816_INITD (1U) /*!< Bit field size in bits for UART_IS7816_INITD. */ /*! @brief Read current value of the UART_IS7816_INITD field. */ #define BR_UART_IS7816_INITD(x) (BITBAND_ACCESS8(HW_UART_IS7816_ADDR(x), BP_UART_IS7816_INITD)) /*! @brief Format value for bitfield UART_IS7816_INITD. */ #define BF_UART_IS7816_INITD(v) ((uint8_t)((uint8_t)(v) << BP_UART_IS7816_INITD) & BM_UART_IS7816_INITD) /*! @brief Set the INITD field to a new value. */ #define BW_UART_IS7816_INITD(x, v) (BITBAND_ACCESS8(HW_UART_IS7816_ADDR(x), BP_UART_IS7816_INITD) = (v)) /*@}*/ /*! * @name Register UART_IS7816, field BWT[5] (W1C) * * Indicates that the block wait time, the time between the leading edge of * first received character of a block and the leading edge of the last character the * previously transmitted block, has exceeded the programmed value. This flag * asserts only when C7816[TTYPE] = 1.This interrupt is cleared by writing 1. * * Values: * - 0 - Block wait time (BWT) has not been violated. * - 1 - Block wait time (BWT) has been violated. */ /*@{*/ #define BP_UART_IS7816_BWT (5U) /*!< Bit position for UART_IS7816_BWT. */ #define BM_UART_IS7816_BWT (0x20U) /*!< Bit mask for UART_IS7816_BWT. */ #define BS_UART_IS7816_BWT (1U) /*!< Bit field size in bits for UART_IS7816_BWT. */ /*! @brief Read current value of the UART_IS7816_BWT field. */ #define BR_UART_IS7816_BWT(x) (BITBAND_ACCESS8(HW_UART_IS7816_ADDR(x), BP_UART_IS7816_BWT)) /*! @brief Format value for bitfield UART_IS7816_BWT. */ #define BF_UART_IS7816_BWT(v) ((uint8_t)((uint8_t)(v) << BP_UART_IS7816_BWT) & BM_UART_IS7816_BWT) /*! @brief Set the BWT field to a new value. */ #define BW_UART_IS7816_BWT(x, v) (BITBAND_ACCESS8(HW_UART_IS7816_ADDR(x), BP_UART_IS7816_BWT) = (v)) /*@}*/ /*! * @name Register UART_IS7816, field CWT[6] (W1C) * * Indicates that the character wait time, the time between the leading edges of * two consecutive characters in a block, has exceeded the programmed value. * This flag asserts only when C7816[TTYPE] = 1. This interrupt is cleared by * writing 1. * * Values: * - 0 - Character wait time (CWT) has not been violated. * - 1 - Character wait time (CWT) has been violated. */ /*@{*/ #define BP_UART_IS7816_CWT (6U) /*!< Bit position for UART_IS7816_CWT. */ #define BM_UART_IS7816_CWT (0x40U) /*!< Bit mask for UART_IS7816_CWT. */ #define BS_UART_IS7816_CWT (1U) /*!< Bit field size in bits for UART_IS7816_CWT. */ /*! @brief Read current value of the UART_IS7816_CWT field. */ #define BR_UART_IS7816_CWT(x) (BITBAND_ACCESS8(HW_UART_IS7816_ADDR(x), BP_UART_IS7816_CWT)) /*! @brief Format value for bitfield UART_IS7816_CWT. */ #define BF_UART_IS7816_CWT(v) ((uint8_t)((uint8_t)(v) << BP_UART_IS7816_CWT) & BM_UART_IS7816_CWT) /*! @brief Set the CWT field to a new value. */ #define BW_UART_IS7816_CWT(x, v) (BITBAND_ACCESS8(HW_UART_IS7816_ADDR(x), BP_UART_IS7816_CWT) = (v)) /*@}*/ /*! * @name Register UART_IS7816, field WT[7] (W1C) * * Indicates that the wait time, the time between the leading edge of a * character being transmitted and the leading edge of the next response character, has * exceeded the programmed value. This flag asserts only when C7816[TTYPE] = 0. * This interrupt is cleared by writing 1. * * Values: * - 0 - Wait time (WT) has not been violated. * - 1 - Wait time (WT) has been violated. */ /*@{*/ #define BP_UART_IS7816_WT (7U) /*!< Bit position for UART_IS7816_WT. */ #define BM_UART_IS7816_WT (0x80U) /*!< Bit mask for UART_IS7816_WT. */ #define BS_UART_IS7816_WT (1U) /*!< Bit field size in bits for UART_IS7816_WT. */ /*! @brief Read current value of the UART_IS7816_WT field. */ #define BR_UART_IS7816_WT(x) (BITBAND_ACCESS8(HW_UART_IS7816_ADDR(x), BP_UART_IS7816_WT)) /*! @brief Format value for bitfield UART_IS7816_WT. */ #define BF_UART_IS7816_WT(v) ((uint8_t)((uint8_t)(v) << BP_UART_IS7816_WT) & BM_UART_IS7816_WT) /*! @brief Set the WT field to a new value. */ #define BW_UART_IS7816_WT(x, v) (BITBAND_ACCESS8(HW_UART_IS7816_ADDR(x), BP_UART_IS7816_WT) = (v)) /*@}*/ /******************************************************************************* * HW_UART_WP7816T0 - UART 7816 Wait Parameter Register ******************************************************************************/ /*! * @brief HW_UART_WP7816T0 - UART 7816 Wait Parameter Register (RW) * * Reset value: 0x0AU * * The WP7816 register contains constants used in the generation of various wait * timer counters. To save register space, this register is used differently * when C7816[TTYPE] = 0 and C7816[TTYPE] = 1. This register may be read at any * time. This register must be written to only when C7816[ISO_7816E] is not set. */ typedef union _hw_uart_wp7816t0 { uint8_t U; struct _hw_uart_wp7816t0_bitfields { uint8_t WI : 8; /*!< [7:0] Wait Time Integer (C7816[TTYPE] = 0) */ } B; } hw_uart_wp7816t0_t; /*! * @name Constants and macros for entire UART_WP7816T0 register */ /*@{*/ #define HW_UART_WP7816T0_ADDR(x) ((x) + 0x1BU) #define HW_UART_WP7816T0(x) (*(__IO hw_uart_wp7816t0_t *) HW_UART_WP7816T0_ADDR(x)) #define HW_UART_WP7816T0_RD(x) (HW_UART_WP7816T0(x).U) #define HW_UART_WP7816T0_WR(x, v) (HW_UART_WP7816T0(x).U = (v)) #define HW_UART_WP7816T0_SET(x, v) (HW_UART_WP7816T0_WR(x, HW_UART_WP7816T0_RD(x) | (v))) #define HW_UART_WP7816T0_CLR(x, v) (HW_UART_WP7816T0_WR(x, HW_UART_WP7816T0_RD(x) & ~(v))) #define HW_UART_WP7816T0_TOG(x, v) (HW_UART_WP7816T0_WR(x, HW_UART_WP7816T0_RD(x) ^ (v))) /*@}*/ /* * Constants & macros for individual UART_WP7816T0 bitfields */ /*! * @name Register UART_WP7816T0, field WI[7:0] (RW) * * Used to calculate the value used for the WT counter. It represents a value * between 1 and 255. The value of zero is not valid. This value is used only when * C7816[TTYPE] = 0. See Wait time and guard time parameters. */ /*@{*/ #define BP_UART_WP7816T0_WI (0U) /*!< Bit position for UART_WP7816T0_WI. */ #define BM_UART_WP7816T0_WI (0xFFU) /*!< Bit mask for UART_WP7816T0_WI. */ #define BS_UART_WP7816T0_WI (8U) /*!< Bit field size in bits for UART_WP7816T0_WI. */ /*! @brief Read current value of the UART_WP7816T0_WI field. */ #define BR_UART_WP7816T0_WI(x) (HW_UART_WP7816T0(x).U) /*! @brief Format value for bitfield UART_WP7816T0_WI. */ #define BF_UART_WP7816T0_WI(v) ((uint8_t)((uint8_t)(v) << BP_UART_WP7816T0_WI) & BM_UART_WP7816T0_WI) /*! @brief Set the WI field to a new value. */ #define BW_UART_WP7816T0_WI(x, v) (HW_UART_WP7816T0_WR(x, v)) /*@}*/ /******************************************************************************* * HW_UART_WP7816T1 - UART 7816 Wait Parameter Register ******************************************************************************/ /*! * @brief HW_UART_WP7816T1 - UART 7816 Wait Parameter Register (RW) * * Reset value: 0x0AU * * The WP7816 register contains constants used in the generation of various wait * timer counters. To save register space, this register is used differently * when C7816[TTYPE] = 0 and C7816[TTYPE] = 1. This register may be read at any * time. This register must be written to only when C7816[ISO_7816E] is not set. */ typedef union _hw_uart_wp7816t1 { uint8_t U; struct _hw_uart_wp7816t1_bitfields { uint8_t BWI : 4; /*!< [3:0] Block Wait Time Integer(C7816[TTYPE] = 1) * */ uint8_t CWI : 4; /*!< [7:4] Character Wait Time Integer (C7816[TTYPE] * = 1) */ } B; } hw_uart_wp7816t1_t; /*! * @name Constants and macros for entire UART_WP7816T1 register */ /*@{*/ #define HW_UART_WP7816T1_ADDR(x) ((x) + 0x1BU) #define HW_UART_WP7816T1(x) (*(__IO hw_uart_wp7816t1_t *) HW_UART_WP7816T1_ADDR(x)) #define HW_UART_WP7816T1_RD(x) (HW_UART_WP7816T1(x).U) #define HW_UART_WP7816T1_WR(x, v) (HW_UART_WP7816T1(x).U = (v)) #define HW_UART_WP7816T1_SET(x, v) (HW_UART_WP7816T1_WR(x, HW_UART_WP7816T1_RD(x) | (v))) #define HW_UART_WP7816T1_CLR(x, v) (HW_UART_WP7816T1_WR(x, HW_UART_WP7816T1_RD(x) & ~(v))) #define HW_UART_WP7816T1_TOG(x, v) (HW_UART_WP7816T1_WR(x, HW_UART_WP7816T1_RD(x) ^ (v))) /*@}*/ /* * Constants & macros for individual UART_WP7816T1 bitfields */ /*! * @name Register UART_WP7816T1, field BWI[3:0] (RW) * * Used to calculate the value used for the BWT counter. It represent a value * between 0 and 15. This value is used only when C7816[TTYPE] = 1. See Wait time * and guard time parameters . */ /*@{*/ #define BP_UART_WP7816T1_BWI (0U) /*!< Bit position for UART_WP7816T1_BWI. */ #define BM_UART_WP7816T1_BWI (0x0FU) /*!< Bit mask for UART_WP7816T1_BWI. */ #define BS_UART_WP7816T1_BWI (4U) /*!< Bit field size in bits for UART_WP7816T1_BWI. */ /*! @brief Read current value of the UART_WP7816T1_BWI field. */ #define BR_UART_WP7816T1_BWI(x) (HW_UART_WP7816T1(x).B.BWI) /*! @brief Format value for bitfield UART_WP7816T1_BWI. */ #define BF_UART_WP7816T1_BWI(v) ((uint8_t)((uint8_t)(v) << BP_UART_WP7816T1_BWI) & BM_UART_WP7816T1_BWI) /*! @brief Set the BWI field to a new value. */ #define BW_UART_WP7816T1_BWI(x, v) (HW_UART_WP7816T1_WR(x, (HW_UART_WP7816T1_RD(x) & ~BM_UART_WP7816T1_BWI) | BF_UART_WP7816T1_BWI(v))) /*@}*/ /*! * @name Register UART_WP7816T1, field CWI[7:4] (RW) * * Used to calculate the value used for the CWT counter. It represents a value * between 0 and 15. This value is used only when C7816[TTYPE] = 1. See Wait time * and guard time parameters . */ /*@{*/ #define BP_UART_WP7816T1_CWI (4U) /*!< Bit position for UART_WP7816T1_CWI. */ #define BM_UART_WP7816T1_CWI (0xF0U) /*!< Bit mask for UART_WP7816T1_CWI. */ #define BS_UART_WP7816T1_CWI (4U) /*!< Bit field size in bits for UART_WP7816T1_CWI. */ /*! @brief Read current value of the UART_WP7816T1_CWI field. */ #define BR_UART_WP7816T1_CWI(x) (HW_UART_WP7816T1(x).B.CWI) /*! @brief Format value for bitfield UART_WP7816T1_CWI. */ #define BF_UART_WP7816T1_CWI(v) ((uint8_t)((uint8_t)(v) << BP_UART_WP7816T1_CWI) & BM_UART_WP7816T1_CWI) /*! @brief Set the CWI field to a new value. */ #define BW_UART_WP7816T1_CWI(x, v) (HW_UART_WP7816T1_WR(x, (HW_UART_WP7816T1_RD(x) & ~BM_UART_WP7816T1_CWI) | BF_UART_WP7816T1_CWI(v))) /*@}*/ /******************************************************************************* * HW_UART_WN7816 - UART 7816 Wait N Register ******************************************************************************/ /*! * @brief HW_UART_WN7816 - UART 7816 Wait N Register (RW) * * Reset value: 0x00U * * The WN7816 register contains a parameter that is used in the calculation of * the guard time counter. This register may be read at any time. This register * must be written to only when C7816[ISO_7816E] is not set. */ typedef union _hw_uart_wn7816 { uint8_t U; struct _hw_uart_wn7816_bitfields { uint8_t GTN : 8; /*!< [7:0] Guard Band N */ } B; } hw_uart_wn7816_t; /*! * @name Constants and macros for entire UART_WN7816 register */ /*@{*/ #define HW_UART_WN7816_ADDR(x) ((x) + 0x1CU) #define HW_UART_WN7816(x) (*(__IO hw_uart_wn7816_t *) HW_UART_WN7816_ADDR(x)) #define HW_UART_WN7816_RD(x) (HW_UART_WN7816(x).U) #define HW_UART_WN7816_WR(x, v) (HW_UART_WN7816(x).U = (v)) #define HW_UART_WN7816_SET(x, v) (HW_UART_WN7816_WR(x, HW_UART_WN7816_RD(x) | (v))) #define HW_UART_WN7816_CLR(x, v) (HW_UART_WN7816_WR(x, HW_UART_WN7816_RD(x) & ~(v))) #define HW_UART_WN7816_TOG(x, v) (HW_UART_WN7816_WR(x, HW_UART_WN7816_RD(x) ^ (v))) /*@}*/ /* * Constants & macros for individual UART_WN7816 bitfields */ /*! * @name Register UART_WN7816, field GTN[7:0] (RW) * * Defines a parameter used in the calculation of GT, CGT, and BGT counters. The * value represents an integer number between 0 and 255. See Wait time and guard * time parameters . */ /*@{*/ #define BP_UART_WN7816_GTN (0U) /*!< Bit position for UART_WN7816_GTN. */ #define BM_UART_WN7816_GTN (0xFFU) /*!< Bit mask for UART_WN7816_GTN. */ #define BS_UART_WN7816_GTN (8U) /*!< Bit field size in bits for UART_WN7816_GTN. */ /*! @brief Read current value of the UART_WN7816_GTN field. */ #define BR_UART_WN7816_GTN(x) (HW_UART_WN7816(x).U) /*! @brief Format value for bitfield UART_WN7816_GTN. */ #define BF_UART_WN7816_GTN(v) ((uint8_t)((uint8_t)(v) << BP_UART_WN7816_GTN) & BM_UART_WN7816_GTN) /*! @brief Set the GTN field to a new value. */ #define BW_UART_WN7816_GTN(x, v) (HW_UART_WN7816_WR(x, v)) /*@}*/ /******************************************************************************* * HW_UART_WF7816 - UART 7816 Wait FD Register ******************************************************************************/ /*! * @brief HW_UART_WF7816 - UART 7816 Wait FD Register (RW) * * Reset value: 0x01U * * The WF7816 contains parameters that are used in the generation of various * counters including GT, CGT, BGT, WT, and BWT. This register may be read at any * time. This register must be written to only when C7816[ISO_7816E] is not set. */ typedef union _hw_uart_wf7816 { uint8_t U; struct _hw_uart_wf7816_bitfields { uint8_t GTFD : 8; /*!< [7:0] FD Multiplier */ } B; } hw_uart_wf7816_t; /*! * @name Constants and macros for entire UART_WF7816 register */ /*@{*/ #define HW_UART_WF7816_ADDR(x) ((x) + 0x1DU) #define HW_UART_WF7816(x) (*(__IO hw_uart_wf7816_t *) HW_UART_WF7816_ADDR(x)) #define HW_UART_WF7816_RD(x) (HW_UART_WF7816(x).U) #define HW_UART_WF7816_WR(x, v) (HW_UART_WF7816(x).U = (v)) #define HW_UART_WF7816_SET(x, v) (HW_UART_WF7816_WR(x, HW_UART_WF7816_RD(x) | (v))) #define HW_UART_WF7816_CLR(x, v) (HW_UART_WF7816_WR(x, HW_UART_WF7816_RD(x) & ~(v))) #define HW_UART_WF7816_TOG(x, v) (HW_UART_WF7816_WR(x, HW_UART_WF7816_RD(x) ^ (v))) /*@}*/ /* * Constants & macros for individual UART_WF7816 bitfields */ /*! * @name Register UART_WF7816, field GTFD[7:0] (RW) * * Used as another multiplier in the calculation of WT and BWT. This value * represents a number between 1 and 255. The value of 0 is invalid. This value is not * used in baud rate generation. See Wait time and guard time parameters and * Baud rate generation . */ /*@{*/ #define BP_UART_WF7816_GTFD (0U) /*!< Bit position for UART_WF7816_GTFD. */ #define BM_UART_WF7816_GTFD (0xFFU) /*!< Bit mask for UART_WF7816_GTFD. */ #define BS_UART_WF7816_GTFD (8U) /*!< Bit field size in bits for UART_WF7816_GTFD. */ /*! @brief Read current value of the UART_WF7816_GTFD field. */ #define BR_UART_WF7816_GTFD(x) (HW_UART_WF7816(x).U) /*! @brief Format value for bitfield UART_WF7816_GTFD. */ #define BF_UART_WF7816_GTFD(v) ((uint8_t)((uint8_t)(v) << BP_UART_WF7816_GTFD) & BM_UART_WF7816_GTFD) /*! @brief Set the GTFD field to a new value. */ #define BW_UART_WF7816_GTFD(x, v) (HW_UART_WF7816_WR(x, v)) /*@}*/ /******************************************************************************* * HW_UART_ET7816 - UART 7816 Error Threshold Register ******************************************************************************/ /*! * @brief HW_UART_ET7816 - UART 7816 Error Threshold Register (RW) * * Reset value: 0x00U * * The ET7816 register contains fields that determine the number of NACKs that * must be received or transmitted before the host processor is notified. This * register may be read at anytime. This register must be written to only when * C7816[ISO_7816E] is not set. */ typedef union _hw_uart_et7816 { uint8_t U; struct _hw_uart_et7816_bitfields { uint8_t RXTHRESHOLD : 4; /*!< [3:0] Receive NACK Threshold */ uint8_t TXTHRESHOLD : 4; /*!< [7:4] Transmit NACK Threshold */ } B; } hw_uart_et7816_t; /*! * @name Constants and macros for entire UART_ET7816 register */ /*@{*/ #define HW_UART_ET7816_ADDR(x) ((x) + 0x1EU) #define HW_UART_ET7816(x) (*(__IO hw_uart_et7816_t *) HW_UART_ET7816_ADDR(x)) #define HW_UART_ET7816_RD(x) (HW_UART_ET7816(x).U) #define HW_UART_ET7816_WR(x, v) (HW_UART_ET7816(x).U = (v)) #define HW_UART_ET7816_SET(x, v) (HW_UART_ET7816_WR(x, HW_UART_ET7816_RD(x) | (v))) #define HW_UART_ET7816_CLR(x, v) (HW_UART_ET7816_WR(x, HW_UART_ET7816_RD(x) & ~(v))) #define HW_UART_ET7816_TOG(x, v) (HW_UART_ET7816_WR(x, HW_UART_ET7816_RD(x) ^ (v))) /*@}*/ /* * Constants & macros for individual UART_ET7816 bitfields */ /*! * @name Register UART_ET7816, field RXTHRESHOLD[3:0] (RW) * * The value written to this field indicates the maximum number of consecutive * NACKs generated as a result of a parity error or receiver buffer overruns * before the host processor is notified. After the counter exceeds that value in the * field, the IS7816[RXT] is asserted. This field is meaningful only when * C7816[TTYPE] = 0. The value read from this field represents the number of consecutive * NACKs that have been transmitted since the last successful reception. This * counter saturates at 4'hF and does not wrap around. Regardless of the number of * NACKs sent, the UART continues to receive valid packets indefinitely. For * additional information, see IS7816[RXT] field description. */ /*@{*/ #define BP_UART_ET7816_RXTHRESHOLD (0U) /*!< Bit position for UART_ET7816_RXTHRESHOLD. */ #define BM_UART_ET7816_RXTHRESHOLD (0x0FU) /*!< Bit mask for UART_ET7816_RXTHRESHOLD. */ #define BS_UART_ET7816_RXTHRESHOLD (4U) /*!< Bit field size in bits for UART_ET7816_RXTHRESHOLD. */ /*! @brief Read current value of the UART_ET7816_RXTHRESHOLD field. */ #define BR_UART_ET7816_RXTHRESHOLD(x) (HW_UART_ET7816(x).B.RXTHRESHOLD) /*! @brief Format value for bitfield UART_ET7816_RXTHRESHOLD. */ #define BF_UART_ET7816_RXTHRESHOLD(v) ((uint8_t)((uint8_t)(v) << BP_UART_ET7816_RXTHRESHOLD) & BM_UART_ET7816_RXTHRESHOLD) /*! @brief Set the RXTHRESHOLD field to a new value. */ #define BW_UART_ET7816_RXTHRESHOLD(x, v) (HW_UART_ET7816_WR(x, (HW_UART_ET7816_RD(x) & ~BM_UART_ET7816_RXTHRESHOLD) | BF_UART_ET7816_RXTHRESHOLD(v))) /*@}*/ /*! * @name Register UART_ET7816, field TXTHRESHOLD[7:4] (RW) * * The value written to this field indicates the maximum number of failed * attempts (NACKs) a transmitted character can have before the host processor is * notified. This field is meaningful only when C7816[TTYPE] = 0 and C7816[ANACK] = 1. * The value read from this field represents the number of consecutive NACKs * that have been received since the last successful transmission. This counter * saturates at 4'hF and does not wrap around. Regardless of how many NACKs that are * received, the UART continues to retransmit indefinitely. This flag only * asserts when C7816[TTYPE] = 0. For additional information see the IS7816[TXT] field * description. * * Values: * - 0 - TXT asserts on the first NACK that is received. * - 1 - TXT asserts on the second NACK that is received. */ /*@{*/ #define BP_UART_ET7816_TXTHRESHOLD (4U) /*!< Bit position for UART_ET7816_TXTHRESHOLD. */ #define BM_UART_ET7816_TXTHRESHOLD (0xF0U) /*!< Bit mask for UART_ET7816_TXTHRESHOLD. */ #define BS_UART_ET7816_TXTHRESHOLD (4U) /*!< Bit field size in bits for UART_ET7816_TXTHRESHOLD. */ /*! @brief Read current value of the UART_ET7816_TXTHRESHOLD field. */ #define BR_UART_ET7816_TXTHRESHOLD(x) (HW_UART_ET7816(x).B.TXTHRESHOLD) /*! @brief Format value for bitfield UART_ET7816_TXTHRESHOLD. */ #define BF_UART_ET7816_TXTHRESHOLD(v) ((uint8_t)((uint8_t)(v) << BP_UART_ET7816_TXTHRESHOLD) & BM_UART_ET7816_TXTHRESHOLD) /*! @brief Set the TXTHRESHOLD field to a new value. */ #define BW_UART_ET7816_TXTHRESHOLD(x, v) (HW_UART_ET7816_WR(x, (HW_UART_ET7816_RD(x) & ~BM_UART_ET7816_TXTHRESHOLD) | BF_UART_ET7816_TXTHRESHOLD(v))) /*@}*/ /******************************************************************************* * HW_UART_TL7816 - UART 7816 Transmit Length Register ******************************************************************************/ /*! * @brief HW_UART_TL7816 - UART 7816 Transmit Length Register (RW) * * Reset value: 0x00U * * The TL7816 register is used to indicate the number of characters contained in * the block being transmitted. This register is used only when C7816[TTYPE] = * 1. This register may be read at anytime. This register must be written only * when C2[TE] is not enabled. */ typedef union _hw_uart_tl7816 { uint8_t U; struct _hw_uart_tl7816_bitfields { uint8_t TLEN : 8; /*!< [7:0] Transmit Length */ } B; } hw_uart_tl7816_t; /*! * @name Constants and macros for entire UART_TL7816 register */ /*@{*/ #define HW_UART_TL7816_ADDR(x) ((x) + 0x1FU) #define HW_UART_TL7816(x) (*(__IO hw_uart_tl7816_t *) HW_UART_TL7816_ADDR(x)) #define HW_UART_TL7816_RD(x) (HW_UART_TL7816(x).U) #define HW_UART_TL7816_WR(x, v) (HW_UART_TL7816(x).U = (v)) #define HW_UART_TL7816_SET(x, v) (HW_UART_TL7816_WR(x, HW_UART_TL7816_RD(x) | (v))) #define HW_UART_TL7816_CLR(x, v) (HW_UART_TL7816_WR(x, HW_UART_TL7816_RD(x) & ~(v))) #define HW_UART_TL7816_TOG(x, v) (HW_UART_TL7816_WR(x, HW_UART_TL7816_RD(x) ^ (v))) /*@}*/ /* * Constants & macros for individual UART_TL7816 bitfields */ /*! * @name Register UART_TL7816, field TLEN[7:0] (RW) * * This value plus four indicates the number of characters contained in the * block being transmitted. This register is automatically decremented by 1 for each * character in the information field portion of the block. Additionally, this * register is automatically decremented by 1 for the first character of a CRC in * the epilogue field. Therefore, this register must be programmed with the number * of bytes in the data packet if an LRC is being transmitted, and the number of * bytes + 1 if a CRC is being transmitted. This register is not decremented for * characters that are assumed to be part of the Prologue field, that is, the * first three characters transmitted in a block, or the LRC or last CRC character * in the Epilogue field, that is, the last character transmitted. This field * must be programed or adjusted only when C2[TE] is cleared. */ /*@{*/ #define BP_UART_TL7816_TLEN (0U) /*!< Bit position for UART_TL7816_TLEN. */ #define BM_UART_TL7816_TLEN (0xFFU) /*!< Bit mask for UART_TL7816_TLEN. */ #define BS_UART_TL7816_TLEN (8U) /*!< Bit field size in bits for UART_TL7816_TLEN. */ /*! @brief Read current value of the UART_TL7816_TLEN field. */ #define BR_UART_TL7816_TLEN(x) (HW_UART_TL7816(x).U) /*! @brief Format value for bitfield UART_TL7816_TLEN. */ #define BF_UART_TL7816_TLEN(v) ((uint8_t)((uint8_t)(v) << BP_UART_TL7816_TLEN) & BM_UART_TL7816_TLEN) /*! @brief Set the TLEN field to a new value. */ #define BW_UART_TL7816_TLEN(x, v) (HW_UART_TL7816_WR(x, v)) /*@}*/ /* ** Start of section using anonymous unions */ #if defined(__ARMCC_VERSION) #pragma push #pragma anon_unions #elif defined(__CWCC__) #pragma push #pragma cpp_extensions on #elif defined(__GNUC__) /* anonymous unions are enabled by default */ #elif defined(__IAR_SYSTEMS_ICC__) #pragma language=extended #else #error Not supported compiler type #endif /******************************************************************************* * hw_uart_t - module struct ******************************************************************************/ /*! * @brief All UART module registers. */ #pragma pack(1) typedef struct _hw_uart { __IO hw_uart_bdh_t BDH; /*!< [0x0] UART Baud Rate Registers: High */ __IO hw_uart_bdl_t BDL; /*!< [0x1] UART Baud Rate Registers: Low */ __IO hw_uart_c1_t C1; /*!< [0x2] UART Control Register 1 */ __IO hw_uart_c2_t C2; /*!< [0x3] UART Control Register 2 */ __I hw_uart_s1_t S1; /*!< [0x4] UART Status Register 1 */ __IO hw_uart_s2_t S2; /*!< [0x5] UART Status Register 2 */ __IO hw_uart_c3_t C3; /*!< [0x6] UART Control Register 3 */ __IO hw_uart_d_t D; /*!< [0x7] UART Data Register */ __IO hw_uart_ma1_t MA1; /*!< [0x8] UART Match Address Registers 1 */ __IO hw_uart_ma2_t MA2; /*!< [0x9] UART Match Address Registers 2 */ __IO hw_uart_c4_t C4; /*!< [0xA] UART Control Register 4 */ __IO hw_uart_c5_t C5; /*!< [0xB] UART Control Register 5 */ __I hw_uart_ed_t ED; /*!< [0xC] UART Extended Data Register */ __IO hw_uart_modem_t MODEM; /*!< [0xD] UART Modem Register */ __IO hw_uart_ir_t IR; /*!< [0xE] UART Infrared Register */ uint8_t _reserved0[1]; __IO hw_uart_pfifo_t PFIFO; /*!< [0x10] UART FIFO Parameters */ __IO hw_uart_cfifo_t CFIFO; /*!< [0x11] UART FIFO Control Register */ __IO hw_uart_sfifo_t SFIFO; /*!< [0x12] UART FIFO Status Register */ __IO hw_uart_twfifo_t TWFIFO; /*!< [0x13] UART FIFO Transmit Watermark */ __I hw_uart_tcfifo_t TCFIFO; /*!< [0x14] UART FIFO Transmit Count */ __IO hw_uart_rwfifo_t RWFIFO; /*!< [0x15] UART FIFO Receive Watermark */ __I hw_uart_rcfifo_t RCFIFO; /*!< [0x16] UART FIFO Receive Count */ uint8_t _reserved1[1]; __IO hw_uart_c7816_t C7816; /*!< [0x18] UART 7816 Control Register */ __IO hw_uart_ie7816_t IE7816; /*!< [0x19] UART 7816 Interrupt Enable Register */ __IO hw_uart_is7816_t IS7816; /*!< [0x1A] UART 7816 Interrupt Status Register */ union { __IO hw_uart_wp7816t0_t WP7816T0; /*!< [0x1B] UART 7816 Wait Parameter Register */ __IO hw_uart_wp7816t1_t WP7816T1; /*!< [0x1B] UART 7816 Wait Parameter Register */ }; __IO hw_uart_wn7816_t WN7816; /*!< [0x1C] UART 7816 Wait N Register */ __IO hw_uart_wf7816_t WF7816; /*!< [0x1D] UART 7816 Wait FD Register */ __IO hw_uart_et7816_t ET7816; /*!< [0x1E] UART 7816 Error Threshold Register */ __IO hw_uart_tl7816_t TL7816; /*!< [0x1F] UART 7816 Transmit Length Register */ } hw_uart_t; #pragma pack() /*! @brief Macro to access all UART registers. */ /*! @param x UART module instance base address. */ /*! @return Reference (not a pointer) to the registers struct. To get a pointer to the struct, * use the '&' operator, like &HW_UART(UART0_BASE). */ #define HW_UART(x) (*(hw_uart_t *)(x)) /* ** End of section using anonymous unions */ #if defined(__ARMCC_VERSION) #pragma pop #elif defined(__CWCC__) #pragma pop #elif defined(__GNUC__) /* leave anonymous unions enabled */ #elif defined(__IAR_SYSTEMS_ICC__) #pragma language=default #else #error Not supported compiler type #endif #endif /* __HW_UART_REGISTERS_H__ */ /* EOF */ ================================================ FILE: Zelig/mbed/TARGET_K64F/TARGET_Freescale/TARGET_KPSDK_MCUS/TARGET_MCU_K64F/device/device/MK64F12/MK64F12_usb.h ================================================ /* ** ################################################################### ** Compilers: Keil ARM C/C++ Compiler ** Freescale C/C++ for Embedded ARM ** GNU C Compiler ** IAR ANSI C/C++ Compiler for ARM ** ** Reference manual: K64P144M120SF5RM, Rev.2, January 2014 ** Version: rev. 2.5, 2014-02-10 ** Build: b140604 ** ** Abstract: ** Extension to the CMSIS register access layer header. ** ** Copyright (c) 2014 Freescale Semiconductor, Inc. ** All rights reserved. ** ** Redistribution and use in source and binary forms, with or without modification, ** are permitted provided that the following conditions are met: ** ** o Redistributions of source code must retain the above copyright notice, this list ** of conditions and the following disclaimer. ** ** o Redistributions in binary form must reproduce the above copyright notice, this ** list of conditions and the following disclaimer in the documentation and/or ** other materials provided with the distribution. ** ** o Neither the name of Freescale Semiconductor, Inc. nor the names of its ** contributors may be used to endorse or promote products derived from this ** software without specific prior written permission. ** ** THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ** ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED ** WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE ** DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT 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. ** ** http: www.freescale.com ** mail: support@freescale.com ** ** Revisions: ** - rev. 1.0 (2013-08-12) ** Initial version. ** - rev. 2.0 (2013-10-29) ** Register accessor macros added to the memory map. ** Symbols for Processor Expert memory map compatibility added to the memory map. ** Startup file for gcc has been updated according to CMSIS 3.2. ** System initialization updated. ** MCG - registers updated. ** PORTA, PORTB, PORTC, PORTE - registers for digital filter removed. ** - rev. 2.1 (2013-10-30) ** Definition of BITBAND macros updated to support peripherals with 32-bit acces disabled. ** - rev. 2.2 (2013-12-09) ** DMA - EARS register removed. ** AIPS0, AIPS1 - MPRA register updated. ** - rev. 2.3 (2014-01-24) ** Update according to reference manual rev. 2 ** ENET, MCG, MCM, SIM, USB - registers updated ** - rev. 2.4 (2014-02-10) ** The declaration of clock configurations has been moved to separate header file system_MK64F12.h ** Update of SystemInit() and SystemCoreClockUpdate() functions. ** - rev. 2.5 (2014-02-10) ** The declaration of clock configurations has been moved to separate header file system_MK64F12.h ** Update of SystemInit() and SystemCoreClockUpdate() functions. ** Module access macro module_BASES replaced by module_BASE_PTRS. ** ** ################################################################### */ /* * WARNING! DO NOT EDIT THIS FILE DIRECTLY! * * This file was generated automatically and any changes may be lost. */ #ifndef __HW_USB_REGISTERS_H__ #define __HW_USB_REGISTERS_H__ #include "MK64F12.h" #include "fsl_bitaccess.h" /* * MK64F12 USB * * Universal Serial Bus, OTG Capable Controller * * Registers defined in this header file: * - HW_USB_PERID - Peripheral ID register * - HW_USB_IDCOMP - Peripheral ID Complement register * - HW_USB_REV - Peripheral Revision register * - HW_USB_ADDINFO - Peripheral Additional Info register * - HW_USB_OTGISTAT - OTG Interrupt Status register * - HW_USB_OTGICR - OTG Interrupt Control register * - HW_USB_OTGSTAT - OTG Status register * - HW_USB_OTGCTL - OTG Control register * - HW_USB_ISTAT - Interrupt Status register * - HW_USB_INTEN - Interrupt Enable register * - HW_USB_ERRSTAT - Error Interrupt Status register * - HW_USB_ERREN - Error Interrupt Enable register * - HW_USB_STAT - Status register * - HW_USB_CTL - Control register * - HW_USB_ADDR - Address register * - HW_USB_BDTPAGE1 - BDT Page register 1 * - HW_USB_FRMNUML - Frame Number register Low * - HW_USB_FRMNUMH - Frame Number register High * - HW_USB_TOKEN - Token register * - HW_USB_SOFTHLD - SOF Threshold register * - HW_USB_BDTPAGE2 - BDT Page Register 2 * - HW_USB_BDTPAGE3 - BDT Page Register 3 * - HW_USB_ENDPTn - Endpoint Control register * - HW_USB_USBCTRL - USB Control register * - HW_USB_OBSERVE - USB OTG Observe register * - HW_USB_CONTROL - USB OTG Control register * - HW_USB_USBTRC0 - USB Transceiver Control register 0 * - HW_USB_USBFRMADJUST - Frame Adjust Register * - HW_USB_CLK_RECOVER_CTRL - USB Clock recovery control * - HW_USB_CLK_RECOVER_IRC_EN - IRC48M oscillator enable register * - HW_USB_CLK_RECOVER_INT_STATUS - Clock recovery separated interrupt status * * - hw_usb_t - Struct containing all module registers. */ #define HW_USB_INSTANCE_COUNT (1U) /*!< Number of instances of the USB module. */ /******************************************************************************* * HW_USB_PERID - Peripheral ID register ******************************************************************************/ /*! * @brief HW_USB_PERID - Peripheral ID register (RO) * * Reset value: 0x04U * * Reads back the value of 0x04. This value is defined for the USB peripheral. */ typedef union _hw_usb_perid { uint8_t U; struct _hw_usb_perid_bitfields { uint8_t ID : 6; /*!< [5:0] Peripheral Identification */ uint8_t RESERVED0 : 2; /*!< [7:6] */ } B; } hw_usb_perid_t; /*! * @name Constants and macros for entire USB_PERID register */ /*@{*/ #define HW_USB_PERID_ADDR(x) ((x) + 0x0U) #define HW_USB_PERID(x) (*(__I hw_usb_perid_t *) HW_USB_PERID_ADDR(x)) #define HW_USB_PERID_RD(x) (HW_USB_PERID(x).U) /*@}*/ /* * Constants & macros for individual USB_PERID bitfields */ /*! * @name Register USB_PERID, field ID[5:0] (RO) * * This field always reads 0x4h. */ /*@{*/ #define BP_USB_PERID_ID (0U) /*!< Bit position for USB_PERID_ID. */ #define BM_USB_PERID_ID (0x3FU) /*!< Bit mask for USB_PERID_ID. */ #define BS_USB_PERID_ID (6U) /*!< Bit field size in bits for USB_PERID_ID. */ /*! @brief Read current value of the USB_PERID_ID field. */ #define BR_USB_PERID_ID(x) (HW_USB_PERID(x).B.ID) /*@}*/ /******************************************************************************* * HW_USB_IDCOMP - Peripheral ID Complement register ******************************************************************************/ /*! * @brief HW_USB_IDCOMP - Peripheral ID Complement register (RO) * * Reset value: 0xFBU * * Reads back the complement of the Peripheral ID register. For the USB * peripheral, the value is 0xFB. */ typedef union _hw_usb_idcomp { uint8_t U; struct _hw_usb_idcomp_bitfields { uint8_t NID : 6; /*!< [5:0] */ uint8_t RESERVED0 : 2; /*!< [7:6] */ } B; } hw_usb_idcomp_t; /*! * @name Constants and macros for entire USB_IDCOMP register */ /*@{*/ #define HW_USB_IDCOMP_ADDR(x) ((x) + 0x4U) #define HW_USB_IDCOMP(x) (*(__I hw_usb_idcomp_t *) HW_USB_IDCOMP_ADDR(x)) #define HW_USB_IDCOMP_RD(x) (HW_USB_IDCOMP(x).U) /*@}*/ /* * Constants & macros for individual USB_IDCOMP bitfields */ /*! * @name Register USB_IDCOMP, field NID[5:0] (RO) * * Ones' complement of PERID[ID]. bits. */ /*@{*/ #define BP_USB_IDCOMP_NID (0U) /*!< Bit position for USB_IDCOMP_NID. */ #define BM_USB_IDCOMP_NID (0x3FU) /*!< Bit mask for USB_IDCOMP_NID. */ #define BS_USB_IDCOMP_NID (6U) /*!< Bit field size in bits for USB_IDCOMP_NID. */ /*! @brief Read current value of the USB_IDCOMP_NID field. */ #define BR_USB_IDCOMP_NID(x) (HW_USB_IDCOMP(x).B.NID) /*@}*/ /******************************************************************************* * HW_USB_REV - Peripheral Revision register ******************************************************************************/ /*! * @brief HW_USB_REV - Peripheral Revision register (RO) * * Reset value: 0x33U * * Contains the revision number of the USB module. */ typedef union _hw_usb_rev { uint8_t U; struct _hw_usb_rev_bitfields { uint8_t REV : 8; /*!< [7:0] Revision */ } B; } hw_usb_rev_t; /*! * @name Constants and macros for entire USB_REV register */ /*@{*/ #define HW_USB_REV_ADDR(x) ((x) + 0x8U) #define HW_USB_REV(x) (*(__I hw_usb_rev_t *) HW_USB_REV_ADDR(x)) #define HW_USB_REV_RD(x) (HW_USB_REV(x).U) /*@}*/ /* * Constants & macros for individual USB_REV bitfields */ /*! * @name Register USB_REV, field REV[7:0] (RO) * * Indicates the revision number of the USB Core. */ /*@{*/ #define BP_USB_REV_REV (0U) /*!< Bit position for USB_REV_REV. */ #define BM_USB_REV_REV (0xFFU) /*!< Bit mask for USB_REV_REV. */ #define BS_USB_REV_REV (8U) /*!< Bit field size in bits for USB_REV_REV. */ /*! @brief Read current value of the USB_REV_REV field. */ #define BR_USB_REV_REV(x) (HW_USB_REV(x).U) /*@}*/ /******************************************************************************* * HW_USB_ADDINFO - Peripheral Additional Info register ******************************************************************************/ /*! * @brief HW_USB_ADDINFO - Peripheral Additional Info register (RO) * * Reset value: 0x01U * * Reads back the value of the fixed Interrupt Request Level (IRQNUM) along with * the Host Enable bit. */ typedef union _hw_usb_addinfo { uint8_t U; struct _hw_usb_addinfo_bitfields { uint8_t IEHOST : 1; /*!< [0] */ uint8_t RESERVED0 : 2; /*!< [2:1] */ uint8_t IRQNUM : 5; /*!< [7:3] Assigned Interrupt Request Number */ } B; } hw_usb_addinfo_t; /*! * @name Constants and macros for entire USB_ADDINFO register */ /*@{*/ #define HW_USB_ADDINFO_ADDR(x) ((x) + 0xCU) #define HW_USB_ADDINFO(x) (*(__I hw_usb_addinfo_t *) HW_USB_ADDINFO_ADDR(x)) #define HW_USB_ADDINFO_RD(x) (HW_USB_ADDINFO(x).U) /*@}*/ /* * Constants & macros for individual USB_ADDINFO bitfields */ /*! * @name Register USB_ADDINFO, field IEHOST[0] (RO) * * This bit is set if host mode is enabled. */ /*@{*/ #define BP_USB_ADDINFO_IEHOST (0U) /*!< Bit position for USB_ADDINFO_IEHOST. */ #define BM_USB_ADDINFO_IEHOST (0x01U) /*!< Bit mask for USB_ADDINFO_IEHOST. */ #define BS_USB_ADDINFO_IEHOST (1U) /*!< Bit field size in bits for USB_ADDINFO_IEHOST. */ /*! @brief Read current value of the USB_ADDINFO_IEHOST field. */ #define BR_USB_ADDINFO_IEHOST(x) (BITBAND_ACCESS8(HW_USB_ADDINFO_ADDR(x), BP_USB_ADDINFO_IEHOST)) /*@}*/ /*! * @name Register USB_ADDINFO, field IRQNUM[7:3] (RO) */ /*@{*/ #define BP_USB_ADDINFO_IRQNUM (3U) /*!< Bit position for USB_ADDINFO_IRQNUM. */ #define BM_USB_ADDINFO_IRQNUM (0xF8U) /*!< Bit mask for USB_ADDINFO_IRQNUM. */ #define BS_USB_ADDINFO_IRQNUM (5U) /*!< Bit field size in bits for USB_ADDINFO_IRQNUM. */ /*! @brief Read current value of the USB_ADDINFO_IRQNUM field. */ #define BR_USB_ADDINFO_IRQNUM(x) (HW_USB_ADDINFO(x).B.IRQNUM) /*@}*/ /******************************************************************************* * HW_USB_OTGISTAT - OTG Interrupt Status register ******************************************************************************/ /*! * @brief HW_USB_OTGISTAT - OTG Interrupt Status register (RW) * * Reset value: 0x00U * * Records changes of the ID sense and VBUS signals. Software can read this * register to determine the event that triggers an interrupt. Only bits that have * changed since the last software read are set. Writing a one to a bit clears the * associated interrupt. */ typedef union _hw_usb_otgistat { uint8_t U; struct _hw_usb_otgistat_bitfields { uint8_t AVBUSCHG : 1; /*!< [0] */ uint8_t RESERVED0 : 1; /*!< [1] */ uint8_t B_SESS_CHG : 1; /*!< [2] */ uint8_t SESSVLDCHG : 1; /*!< [3] */ uint8_t RESERVED1 : 1; /*!< [4] */ uint8_t LINE_STATE_CHG : 1; /*!< [5] */ uint8_t ONEMSEC : 1; /*!< [6] */ uint8_t IDCHG : 1; /*!< [7] */ } B; } hw_usb_otgistat_t; /*! * @name Constants and macros for entire USB_OTGISTAT register */ /*@{*/ #define HW_USB_OTGISTAT_ADDR(x) ((x) + 0x10U) #define HW_USB_OTGISTAT(x) (*(__IO hw_usb_otgistat_t *) HW_USB_OTGISTAT_ADDR(x)) #define HW_USB_OTGISTAT_RD(x) (HW_USB_OTGISTAT(x).U) #define HW_USB_OTGISTAT_WR(x, v) (HW_USB_OTGISTAT(x).U = (v)) #define HW_USB_OTGISTAT_SET(x, v) (HW_USB_OTGISTAT_WR(x, HW_USB_OTGISTAT_RD(x) | (v))) #define HW_USB_OTGISTAT_CLR(x, v) (HW_USB_OTGISTAT_WR(x, HW_USB_OTGISTAT_RD(x) & ~(v))) #define HW_USB_OTGISTAT_TOG(x, v) (HW_USB_OTGISTAT_WR(x, HW_USB_OTGISTAT_RD(x) ^ (v))) /*@}*/ /* * Constants & macros for individual USB_OTGISTAT bitfields */ /*! * @name Register USB_OTGISTAT, field AVBUSCHG[0] (RW) * * This bit is set when a change in VBUS is detected on an A device. */ /*@{*/ #define BP_USB_OTGISTAT_AVBUSCHG (0U) /*!< Bit position for USB_OTGISTAT_AVBUSCHG. */ #define BM_USB_OTGISTAT_AVBUSCHG (0x01U) /*!< Bit mask for USB_OTGISTAT_AVBUSCHG. */ #define BS_USB_OTGISTAT_AVBUSCHG (1U) /*!< Bit field size in bits for USB_OTGISTAT_AVBUSCHG. */ /*! @brief Read current value of the USB_OTGISTAT_AVBUSCHG field. */ #define BR_USB_OTGISTAT_AVBUSCHG(x) (BITBAND_ACCESS8(HW_USB_OTGISTAT_ADDR(x), BP_USB_OTGISTAT_AVBUSCHG)) /*! @brief Format value for bitfield USB_OTGISTAT_AVBUSCHG. */ #define BF_USB_OTGISTAT_AVBUSCHG(v) ((uint8_t)((uint8_t)(v) << BP_USB_OTGISTAT_AVBUSCHG) & BM_USB_OTGISTAT_AVBUSCHG) /*! @brief Set the AVBUSCHG field to a new value. */ #define BW_USB_OTGISTAT_AVBUSCHG(x, v) (BITBAND_ACCESS8(HW_USB_OTGISTAT_ADDR(x), BP_USB_OTGISTAT_AVBUSCHG) = (v)) /*@}*/ /*! * @name Register USB_OTGISTAT, field B_SESS_CHG[2] (RW) * * This bit is set when a change in VBUS is detected on a B device. */ /*@{*/ #define BP_USB_OTGISTAT_B_SESS_CHG (2U) /*!< Bit position for USB_OTGISTAT_B_SESS_CHG. */ #define BM_USB_OTGISTAT_B_SESS_CHG (0x04U) /*!< Bit mask for USB_OTGISTAT_B_SESS_CHG. */ #define BS_USB_OTGISTAT_B_SESS_CHG (1U) /*!< Bit field size in bits for USB_OTGISTAT_B_SESS_CHG. */ /*! @brief Read current value of the USB_OTGISTAT_B_SESS_CHG field. */ #define BR_USB_OTGISTAT_B_SESS_CHG(x) (BITBAND_ACCESS8(HW_USB_OTGISTAT_ADDR(x), BP_USB_OTGISTAT_B_SESS_CHG)) /*! @brief Format value for bitfield USB_OTGISTAT_B_SESS_CHG. */ #define BF_USB_OTGISTAT_B_SESS_CHG(v) ((uint8_t)((uint8_t)(v) << BP_USB_OTGISTAT_B_SESS_CHG) & BM_USB_OTGISTAT_B_SESS_CHG) /*! @brief Set the B_SESS_CHG field to a new value. */ #define BW_USB_OTGISTAT_B_SESS_CHG(x, v) (BITBAND_ACCESS8(HW_USB_OTGISTAT_ADDR(x), BP_USB_OTGISTAT_B_SESS_CHG) = (v)) /*@}*/ /*! * @name Register USB_OTGISTAT, field SESSVLDCHG[3] (RW) * * This bit is set when a change in VBUS is detected indicating a session valid * or a session no longer valid. */ /*@{*/ #define BP_USB_OTGISTAT_SESSVLDCHG (3U) /*!< Bit position for USB_OTGISTAT_SESSVLDCHG. */ #define BM_USB_OTGISTAT_SESSVLDCHG (0x08U) /*!< Bit mask for USB_OTGISTAT_SESSVLDCHG. */ #define BS_USB_OTGISTAT_SESSVLDCHG (1U) /*!< Bit field size in bits for USB_OTGISTAT_SESSVLDCHG. */ /*! @brief Read current value of the USB_OTGISTAT_SESSVLDCHG field. */ #define BR_USB_OTGISTAT_SESSVLDCHG(x) (BITBAND_ACCESS8(HW_USB_OTGISTAT_ADDR(x), BP_USB_OTGISTAT_SESSVLDCHG)) /*! @brief Format value for bitfield USB_OTGISTAT_SESSVLDCHG. */ #define BF_USB_OTGISTAT_SESSVLDCHG(v) ((uint8_t)((uint8_t)(v) << BP_USB_OTGISTAT_SESSVLDCHG) & BM_USB_OTGISTAT_SESSVLDCHG) /*! @brief Set the SESSVLDCHG field to a new value. */ #define BW_USB_OTGISTAT_SESSVLDCHG(x, v) (BITBAND_ACCESS8(HW_USB_OTGISTAT_ADDR(x), BP_USB_OTGISTAT_SESSVLDCHG) = (v)) /*@}*/ /*! * @name Register USB_OTGISTAT, field LINE_STATE_CHG[5] (RW) * * This interrupt is set when the USB line state (CTL[SE0] and CTL[JSTATE] bits) * are stable without change for 1 millisecond, and the value of the line state * is different from the last time when the line state was stable. It is set on * transitions between SE0 and J-state, SE0 and K-state, and J-state and K-state. * Changes in J-state while SE0 is true do not cause an interrupt. This interrupt * can be used in detecting Reset, Resume, Connect, and Data Line Pulse * signaling. */ /*@{*/ #define BP_USB_OTGISTAT_LINE_STATE_CHG (5U) /*!< Bit position for USB_OTGISTAT_LINE_STATE_CHG. */ #define BM_USB_OTGISTAT_LINE_STATE_CHG (0x20U) /*!< Bit mask for USB_OTGISTAT_LINE_STATE_CHG. */ #define BS_USB_OTGISTAT_LINE_STATE_CHG (1U) /*!< Bit field size in bits for USB_OTGISTAT_LINE_STATE_CHG. */ /*! @brief Read current value of the USB_OTGISTAT_LINE_STATE_CHG field. */ #define BR_USB_OTGISTAT_LINE_STATE_CHG(x) (BITBAND_ACCESS8(HW_USB_OTGISTAT_ADDR(x), BP_USB_OTGISTAT_LINE_STATE_CHG)) /*! @brief Format value for bitfield USB_OTGISTAT_LINE_STATE_CHG. */ #define BF_USB_OTGISTAT_LINE_STATE_CHG(v) ((uint8_t)((uint8_t)(v) << BP_USB_OTGISTAT_LINE_STATE_CHG) & BM_USB_OTGISTAT_LINE_STATE_CHG) /*! @brief Set the LINE_STATE_CHG field to a new value. */ #define BW_USB_OTGISTAT_LINE_STATE_CHG(x, v) (BITBAND_ACCESS8(HW_USB_OTGISTAT_ADDR(x), BP_USB_OTGISTAT_LINE_STATE_CHG) = (v)) /*@}*/ /*! * @name Register USB_OTGISTAT, field ONEMSEC[6] (RW) * * This bit is set when the 1 millisecond timer expires. This bit stays asserted * until cleared by software. The interrupt must be serviced every millisecond * to avoid losing 1msec counts. */ /*@{*/ #define BP_USB_OTGISTAT_ONEMSEC (6U) /*!< Bit position for USB_OTGISTAT_ONEMSEC. */ #define BM_USB_OTGISTAT_ONEMSEC (0x40U) /*!< Bit mask for USB_OTGISTAT_ONEMSEC. */ #define BS_USB_OTGISTAT_ONEMSEC (1U) /*!< Bit field size in bits for USB_OTGISTAT_ONEMSEC. */ /*! @brief Read current value of the USB_OTGISTAT_ONEMSEC field. */ #define BR_USB_OTGISTAT_ONEMSEC(x) (BITBAND_ACCESS8(HW_USB_OTGISTAT_ADDR(x), BP_USB_OTGISTAT_ONEMSEC)) /*! @brief Format value for bitfield USB_OTGISTAT_ONEMSEC. */ #define BF_USB_OTGISTAT_ONEMSEC(v) ((uint8_t)((uint8_t)(v) << BP_USB_OTGISTAT_ONEMSEC) & BM_USB_OTGISTAT_ONEMSEC) /*! @brief Set the ONEMSEC field to a new value. */ #define BW_USB_OTGISTAT_ONEMSEC(x, v) (BITBAND_ACCESS8(HW_USB_OTGISTAT_ADDR(x), BP_USB_OTGISTAT_ONEMSEC) = (v)) /*@}*/ /*! * @name Register USB_OTGISTAT, field IDCHG[7] (RW) * * This bit is set when a change in the ID Signal from the USB connector is * sensed. */ /*@{*/ #define BP_USB_OTGISTAT_IDCHG (7U) /*!< Bit position for USB_OTGISTAT_IDCHG. */ #define BM_USB_OTGISTAT_IDCHG (0x80U) /*!< Bit mask for USB_OTGISTAT_IDCHG. */ #define BS_USB_OTGISTAT_IDCHG (1U) /*!< Bit field size in bits for USB_OTGISTAT_IDCHG. */ /*! @brief Read current value of the USB_OTGISTAT_IDCHG field. */ #define BR_USB_OTGISTAT_IDCHG(x) (BITBAND_ACCESS8(HW_USB_OTGISTAT_ADDR(x), BP_USB_OTGISTAT_IDCHG)) /*! @brief Format value for bitfield USB_OTGISTAT_IDCHG. */ #define BF_USB_OTGISTAT_IDCHG(v) ((uint8_t)((uint8_t)(v) << BP_USB_OTGISTAT_IDCHG) & BM_USB_OTGISTAT_IDCHG) /*! @brief Set the IDCHG field to a new value. */ #define BW_USB_OTGISTAT_IDCHG(x, v) (BITBAND_ACCESS8(HW_USB_OTGISTAT_ADDR(x), BP_USB_OTGISTAT_IDCHG) = (v)) /*@}*/ /******************************************************************************* * HW_USB_OTGICR - OTG Interrupt Control register ******************************************************************************/ /*! * @brief HW_USB_OTGICR - OTG Interrupt Control register (RW) * * Reset value: 0x00U * * Enables the corresponding interrupt status bits defined in the OTG Interrupt * Status Register. */ typedef union _hw_usb_otgicr { uint8_t U; struct _hw_usb_otgicr_bitfields { uint8_t AVBUSEN : 1; /*!< [0] A VBUS Valid Interrupt Enable */ uint8_t RESERVED0 : 1; /*!< [1] */ uint8_t BSESSEN : 1; /*!< [2] B Session END Interrupt Enable */ uint8_t SESSVLDEN : 1; /*!< [3] Session Valid Interrupt Enable */ uint8_t RESERVED1 : 1; /*!< [4] */ uint8_t LINESTATEEN : 1; /*!< [5] Line State Change Interrupt Enable * */ uint8_t ONEMSECEN : 1; /*!< [6] One Millisecond Interrupt Enable */ uint8_t IDEN : 1; /*!< [7] ID Interrupt Enable */ } B; } hw_usb_otgicr_t; /*! * @name Constants and macros for entire USB_OTGICR register */ /*@{*/ #define HW_USB_OTGICR_ADDR(x) ((x) + 0x14U) #define HW_USB_OTGICR(x) (*(__IO hw_usb_otgicr_t *) HW_USB_OTGICR_ADDR(x)) #define HW_USB_OTGICR_RD(x) (HW_USB_OTGICR(x).U) #define HW_USB_OTGICR_WR(x, v) (HW_USB_OTGICR(x).U = (v)) #define HW_USB_OTGICR_SET(x, v) (HW_USB_OTGICR_WR(x, HW_USB_OTGICR_RD(x) | (v))) #define HW_USB_OTGICR_CLR(x, v) (HW_USB_OTGICR_WR(x, HW_USB_OTGICR_RD(x) & ~(v))) #define HW_USB_OTGICR_TOG(x, v) (HW_USB_OTGICR_WR(x, HW_USB_OTGICR_RD(x) ^ (v))) /*@}*/ /* * Constants & macros for individual USB_OTGICR bitfields */ /*! * @name Register USB_OTGICR, field AVBUSEN[0] (RW) * * Values: * - 0 - Disables the AVBUSCHG interrupt. * - 1 - Enables the AVBUSCHG interrupt. */ /*@{*/ #define BP_USB_OTGICR_AVBUSEN (0U) /*!< Bit position for USB_OTGICR_AVBUSEN. */ #define BM_USB_OTGICR_AVBUSEN (0x01U) /*!< Bit mask for USB_OTGICR_AVBUSEN. */ #define BS_USB_OTGICR_AVBUSEN (1U) /*!< Bit field size in bits for USB_OTGICR_AVBUSEN. */ /*! @brief Read current value of the USB_OTGICR_AVBUSEN field. */ #define BR_USB_OTGICR_AVBUSEN(x) (BITBAND_ACCESS8(HW_USB_OTGICR_ADDR(x), BP_USB_OTGICR_AVBUSEN)) /*! @brief Format value for bitfield USB_OTGICR_AVBUSEN. */ #define BF_USB_OTGICR_AVBUSEN(v) ((uint8_t)((uint8_t)(v) << BP_USB_OTGICR_AVBUSEN) & BM_USB_OTGICR_AVBUSEN) /*! @brief Set the AVBUSEN field to a new value. */ #define BW_USB_OTGICR_AVBUSEN(x, v) (BITBAND_ACCESS8(HW_USB_OTGICR_ADDR(x), BP_USB_OTGICR_AVBUSEN) = (v)) /*@}*/ /*! * @name Register USB_OTGICR, field BSESSEN[2] (RW) * * Values: * - 0 - Disables the B_SESS_CHG interrupt. * - 1 - Enables the B_SESS_CHG interrupt. */ /*@{*/ #define BP_USB_OTGICR_BSESSEN (2U) /*!< Bit position for USB_OTGICR_BSESSEN. */ #define BM_USB_OTGICR_BSESSEN (0x04U) /*!< Bit mask for USB_OTGICR_BSESSEN. */ #define BS_USB_OTGICR_BSESSEN (1U) /*!< Bit field size in bits for USB_OTGICR_BSESSEN. */ /*! @brief Read current value of the USB_OTGICR_BSESSEN field. */ #define BR_USB_OTGICR_BSESSEN(x) (BITBAND_ACCESS8(HW_USB_OTGICR_ADDR(x), BP_USB_OTGICR_BSESSEN)) /*! @brief Format value for bitfield USB_OTGICR_BSESSEN. */ #define BF_USB_OTGICR_BSESSEN(v) ((uint8_t)((uint8_t)(v) << BP_USB_OTGICR_BSESSEN) & BM_USB_OTGICR_BSESSEN) /*! @brief Set the BSESSEN field to a new value. */ #define BW_USB_OTGICR_BSESSEN(x, v) (BITBAND_ACCESS8(HW_USB_OTGICR_ADDR(x), BP_USB_OTGICR_BSESSEN) = (v)) /*@}*/ /*! * @name Register USB_OTGICR, field SESSVLDEN[3] (RW) * * Values: * - 0 - Disables the SESSVLDCHG interrupt. * - 1 - Enables the SESSVLDCHG interrupt. */ /*@{*/ #define BP_USB_OTGICR_SESSVLDEN (3U) /*!< Bit position for USB_OTGICR_SESSVLDEN. */ #define BM_USB_OTGICR_SESSVLDEN (0x08U) /*!< Bit mask for USB_OTGICR_SESSVLDEN. */ #define BS_USB_OTGICR_SESSVLDEN (1U) /*!< Bit field size in bits for USB_OTGICR_SESSVLDEN. */ /*! @brief Read current value of the USB_OTGICR_SESSVLDEN field. */ #define BR_USB_OTGICR_SESSVLDEN(x) (BITBAND_ACCESS8(HW_USB_OTGICR_ADDR(x), BP_USB_OTGICR_SESSVLDEN)) /*! @brief Format value for bitfield USB_OTGICR_SESSVLDEN. */ #define BF_USB_OTGICR_SESSVLDEN(v) ((uint8_t)((uint8_t)(v) << BP_USB_OTGICR_SESSVLDEN) & BM_USB_OTGICR_SESSVLDEN) /*! @brief Set the SESSVLDEN field to a new value. */ #define BW_USB_OTGICR_SESSVLDEN(x, v) (BITBAND_ACCESS8(HW_USB_OTGICR_ADDR(x), BP_USB_OTGICR_SESSVLDEN) = (v)) /*@}*/ /*! * @name Register USB_OTGICR, field LINESTATEEN[5] (RW) * * Values: * - 0 - Disables the LINE_STAT_CHG interrupt. * - 1 - Enables the LINE_STAT_CHG interrupt. */ /*@{*/ #define BP_USB_OTGICR_LINESTATEEN (5U) /*!< Bit position for USB_OTGICR_LINESTATEEN. */ #define BM_USB_OTGICR_LINESTATEEN (0x20U) /*!< Bit mask for USB_OTGICR_LINESTATEEN. */ #define BS_USB_OTGICR_LINESTATEEN (1U) /*!< Bit field size in bits for USB_OTGICR_LINESTATEEN. */ /*! @brief Read current value of the USB_OTGICR_LINESTATEEN field. */ #define BR_USB_OTGICR_LINESTATEEN(x) (BITBAND_ACCESS8(HW_USB_OTGICR_ADDR(x), BP_USB_OTGICR_LINESTATEEN)) /*! @brief Format value for bitfield USB_OTGICR_LINESTATEEN. */ #define BF_USB_OTGICR_LINESTATEEN(v) ((uint8_t)((uint8_t)(v) << BP_USB_OTGICR_LINESTATEEN) & BM_USB_OTGICR_LINESTATEEN) /*! @brief Set the LINESTATEEN field to a new value. */ #define BW_USB_OTGICR_LINESTATEEN(x, v) (BITBAND_ACCESS8(HW_USB_OTGICR_ADDR(x), BP_USB_OTGICR_LINESTATEEN) = (v)) /*@}*/ /*! * @name Register USB_OTGICR, field ONEMSECEN[6] (RW) * * Values: * - 0 - Diables the 1ms timer interrupt. * - 1 - Enables the 1ms timer interrupt. */ /*@{*/ #define BP_USB_OTGICR_ONEMSECEN (6U) /*!< Bit position for USB_OTGICR_ONEMSECEN. */ #define BM_USB_OTGICR_ONEMSECEN (0x40U) /*!< Bit mask for USB_OTGICR_ONEMSECEN. */ #define BS_USB_OTGICR_ONEMSECEN (1U) /*!< Bit field size in bits for USB_OTGICR_ONEMSECEN. */ /*! @brief Read current value of the USB_OTGICR_ONEMSECEN field. */ #define BR_USB_OTGICR_ONEMSECEN(x) (BITBAND_ACCESS8(HW_USB_OTGICR_ADDR(x), BP_USB_OTGICR_ONEMSECEN)) /*! @brief Format value for bitfield USB_OTGICR_ONEMSECEN. */ #define BF_USB_OTGICR_ONEMSECEN(v) ((uint8_t)((uint8_t)(v) << BP_USB_OTGICR_ONEMSECEN) & BM_USB_OTGICR_ONEMSECEN) /*! @brief Set the ONEMSECEN field to a new value. */ #define BW_USB_OTGICR_ONEMSECEN(x, v) (BITBAND_ACCESS8(HW_USB_OTGICR_ADDR(x), BP_USB_OTGICR_ONEMSECEN) = (v)) /*@}*/ /*! * @name Register USB_OTGICR, field IDEN[7] (RW) * * Values: * - 0 - The ID interrupt is disabled * - 1 - The ID interrupt is enabled */ /*@{*/ #define BP_USB_OTGICR_IDEN (7U) /*!< Bit position for USB_OTGICR_IDEN. */ #define BM_USB_OTGICR_IDEN (0x80U) /*!< Bit mask for USB_OTGICR_IDEN. */ #define BS_USB_OTGICR_IDEN (1U) /*!< Bit field size in bits for USB_OTGICR_IDEN. */ /*! @brief Read current value of the USB_OTGICR_IDEN field. */ #define BR_USB_OTGICR_IDEN(x) (BITBAND_ACCESS8(HW_USB_OTGICR_ADDR(x), BP_USB_OTGICR_IDEN)) /*! @brief Format value for bitfield USB_OTGICR_IDEN. */ #define BF_USB_OTGICR_IDEN(v) ((uint8_t)((uint8_t)(v) << BP_USB_OTGICR_IDEN) & BM_USB_OTGICR_IDEN) /*! @brief Set the IDEN field to a new value. */ #define BW_USB_OTGICR_IDEN(x, v) (BITBAND_ACCESS8(HW_USB_OTGICR_ADDR(x), BP_USB_OTGICR_IDEN) = (v)) /*@}*/ /******************************************************************************* * HW_USB_OTGSTAT - OTG Status register ******************************************************************************/ /*! * @brief HW_USB_OTGSTAT - OTG Status register (RW) * * Reset value: 0x00U * * Displays the actual value from the external comparator outputs of the ID pin * and VBUS. */ typedef union _hw_usb_otgstat { uint8_t U; struct _hw_usb_otgstat_bitfields { uint8_t AVBUSVLD : 1; /*!< [0] A VBUS Valid */ uint8_t RESERVED0 : 1; /*!< [1] */ uint8_t BSESSEND : 1; /*!< [2] B Session End */ uint8_t SESS_VLD : 1; /*!< [3] Session Valid */ uint8_t RESERVED1 : 1; /*!< [4] */ uint8_t LINESTATESTABLE : 1; /*!< [5] */ uint8_t ONEMSECEN : 1; /*!< [6] */ uint8_t ID : 1; /*!< [7] */ } B; } hw_usb_otgstat_t; /*! * @name Constants and macros for entire USB_OTGSTAT register */ /*@{*/ #define HW_USB_OTGSTAT_ADDR(x) ((x) + 0x18U) #define HW_USB_OTGSTAT(x) (*(__IO hw_usb_otgstat_t *) HW_USB_OTGSTAT_ADDR(x)) #define HW_USB_OTGSTAT_RD(x) (HW_USB_OTGSTAT(x).U) #define HW_USB_OTGSTAT_WR(x, v) (HW_USB_OTGSTAT(x).U = (v)) #define HW_USB_OTGSTAT_SET(x, v) (HW_USB_OTGSTAT_WR(x, HW_USB_OTGSTAT_RD(x) | (v))) #define HW_USB_OTGSTAT_CLR(x, v) (HW_USB_OTGSTAT_WR(x, HW_USB_OTGSTAT_RD(x) & ~(v))) #define HW_USB_OTGSTAT_TOG(x, v) (HW_USB_OTGSTAT_WR(x, HW_USB_OTGSTAT_RD(x) ^ (v))) /*@}*/ /* * Constants & macros for individual USB_OTGSTAT bitfields */ /*! * @name Register USB_OTGSTAT, field AVBUSVLD[0] (RW) * * Values: * - 0 - The VBUS voltage is below the A VBUS Valid threshold. * - 1 - The VBUS voltage is above the A VBUS Valid threshold. */ /*@{*/ #define BP_USB_OTGSTAT_AVBUSVLD (0U) /*!< Bit position for USB_OTGSTAT_AVBUSVLD. */ #define BM_USB_OTGSTAT_AVBUSVLD (0x01U) /*!< Bit mask for USB_OTGSTAT_AVBUSVLD. */ #define BS_USB_OTGSTAT_AVBUSVLD (1U) /*!< Bit field size in bits for USB_OTGSTAT_AVBUSVLD. */ /*! @brief Read current value of the USB_OTGSTAT_AVBUSVLD field. */ #define BR_USB_OTGSTAT_AVBUSVLD(x) (BITBAND_ACCESS8(HW_USB_OTGSTAT_ADDR(x), BP_USB_OTGSTAT_AVBUSVLD)) /*! @brief Format value for bitfield USB_OTGSTAT_AVBUSVLD. */ #define BF_USB_OTGSTAT_AVBUSVLD(v) ((uint8_t)((uint8_t)(v) << BP_USB_OTGSTAT_AVBUSVLD) & BM_USB_OTGSTAT_AVBUSVLD) /*! @brief Set the AVBUSVLD field to a new value. */ #define BW_USB_OTGSTAT_AVBUSVLD(x, v) (BITBAND_ACCESS8(HW_USB_OTGSTAT_ADDR(x), BP_USB_OTGSTAT_AVBUSVLD) = (v)) /*@}*/ /*! * @name Register USB_OTGSTAT, field BSESSEND[2] (RW) * * Values: * - 0 - The VBUS voltage is above the B session end threshold. * - 1 - The VBUS voltage is below the B session end threshold. */ /*@{*/ #define BP_USB_OTGSTAT_BSESSEND (2U) /*!< Bit position for USB_OTGSTAT_BSESSEND. */ #define BM_USB_OTGSTAT_BSESSEND (0x04U) /*!< Bit mask for USB_OTGSTAT_BSESSEND. */ #define BS_USB_OTGSTAT_BSESSEND (1U) /*!< Bit field size in bits for USB_OTGSTAT_BSESSEND. */ /*! @brief Read current value of the USB_OTGSTAT_BSESSEND field. */ #define BR_USB_OTGSTAT_BSESSEND(x) (BITBAND_ACCESS8(HW_USB_OTGSTAT_ADDR(x), BP_USB_OTGSTAT_BSESSEND)) /*! @brief Format value for bitfield USB_OTGSTAT_BSESSEND. */ #define BF_USB_OTGSTAT_BSESSEND(v) ((uint8_t)((uint8_t)(v) << BP_USB_OTGSTAT_BSESSEND) & BM_USB_OTGSTAT_BSESSEND) /*! @brief Set the BSESSEND field to a new value. */ #define BW_USB_OTGSTAT_BSESSEND(x, v) (BITBAND_ACCESS8(HW_USB_OTGSTAT_ADDR(x), BP_USB_OTGSTAT_BSESSEND) = (v)) /*@}*/ /*! * @name Register USB_OTGSTAT, field SESS_VLD[3] (RW) * * Values: * - 0 - The VBUS voltage is below the B session valid threshold * - 1 - The VBUS voltage is above the B session valid threshold. */ /*@{*/ #define BP_USB_OTGSTAT_SESS_VLD (3U) /*!< Bit position for USB_OTGSTAT_SESS_VLD. */ #define BM_USB_OTGSTAT_SESS_VLD (0x08U) /*!< Bit mask for USB_OTGSTAT_SESS_VLD. */ #define BS_USB_OTGSTAT_SESS_VLD (1U) /*!< Bit field size in bits for USB_OTGSTAT_SESS_VLD. */ /*! @brief Read current value of the USB_OTGSTAT_SESS_VLD field. */ #define BR_USB_OTGSTAT_SESS_VLD(x) (BITBAND_ACCESS8(HW_USB_OTGSTAT_ADDR(x), BP_USB_OTGSTAT_SESS_VLD)) /*! @brief Format value for bitfield USB_OTGSTAT_SESS_VLD. */ #define BF_USB_OTGSTAT_SESS_VLD(v) ((uint8_t)((uint8_t)(v) << BP_USB_OTGSTAT_SESS_VLD) & BM_USB_OTGSTAT_SESS_VLD) /*! @brief Set the SESS_VLD field to a new value. */ #define BW_USB_OTGSTAT_SESS_VLD(x, v) (BITBAND_ACCESS8(HW_USB_OTGSTAT_ADDR(x), BP_USB_OTGSTAT_SESS_VLD) = (v)) /*@}*/ /*! * @name Register USB_OTGSTAT, field LINESTATESTABLE[5] (RW) * * Indicates that the internal signals that control the LINE_STATE_CHG field of * OTGISTAT are stable for at least 1 millisecond. First read LINE_STATE_CHG * field and then read this field. If this field reads as 1, then the value of * LINE_STATE_CHG can be considered stable. * * Values: * - 0 - The LINE_STAT_CHG bit is not yet stable. * - 1 - The LINE_STAT_CHG bit has been debounced and is stable. */ /*@{*/ #define BP_USB_OTGSTAT_LINESTATESTABLE (5U) /*!< Bit position for USB_OTGSTAT_LINESTATESTABLE. */ #define BM_USB_OTGSTAT_LINESTATESTABLE (0x20U) /*!< Bit mask for USB_OTGSTAT_LINESTATESTABLE. */ #define BS_USB_OTGSTAT_LINESTATESTABLE (1U) /*!< Bit field size in bits for USB_OTGSTAT_LINESTATESTABLE. */ /*! @brief Read current value of the USB_OTGSTAT_LINESTATESTABLE field. */ #define BR_USB_OTGSTAT_LINESTATESTABLE(x) (BITBAND_ACCESS8(HW_USB_OTGSTAT_ADDR(x), BP_USB_OTGSTAT_LINESTATESTABLE)) /*! @brief Format value for bitfield USB_OTGSTAT_LINESTATESTABLE. */ #define BF_USB_OTGSTAT_LINESTATESTABLE(v) ((uint8_t)((uint8_t)(v) << BP_USB_OTGSTAT_LINESTATESTABLE) & BM_USB_OTGSTAT_LINESTATESTABLE) /*! @brief Set the LINESTATESTABLE field to a new value. */ #define BW_USB_OTGSTAT_LINESTATESTABLE(x, v) (BITBAND_ACCESS8(HW_USB_OTGSTAT_ADDR(x), BP_USB_OTGSTAT_LINESTATESTABLE) = (v)) /*@}*/ /*! * @name Register USB_OTGSTAT, field ONEMSECEN[6] (RW) * * This bit is reserved for the 1ms count, but it is not useful to software. */ /*@{*/ #define BP_USB_OTGSTAT_ONEMSECEN (6U) /*!< Bit position for USB_OTGSTAT_ONEMSECEN. */ #define BM_USB_OTGSTAT_ONEMSECEN (0x40U) /*!< Bit mask for USB_OTGSTAT_ONEMSECEN. */ #define BS_USB_OTGSTAT_ONEMSECEN (1U) /*!< Bit field size in bits for USB_OTGSTAT_ONEMSECEN. */ /*! @brief Read current value of the USB_OTGSTAT_ONEMSECEN field. */ #define BR_USB_OTGSTAT_ONEMSECEN(x) (BITBAND_ACCESS8(HW_USB_OTGSTAT_ADDR(x), BP_USB_OTGSTAT_ONEMSECEN)) /*! @brief Format value for bitfield USB_OTGSTAT_ONEMSECEN. */ #define BF_USB_OTGSTAT_ONEMSECEN(v) ((uint8_t)((uint8_t)(v) << BP_USB_OTGSTAT_ONEMSECEN) & BM_USB_OTGSTAT_ONEMSECEN) /*! @brief Set the ONEMSECEN field to a new value. */ #define BW_USB_OTGSTAT_ONEMSECEN(x, v) (BITBAND_ACCESS8(HW_USB_OTGSTAT_ADDR(x), BP_USB_OTGSTAT_ONEMSECEN) = (v)) /*@}*/ /*! * @name Register USB_OTGSTAT, field ID[7] (RW) * * Indicates the current state of the ID pin on the USB connector * * Values: * - 0 - Indicates a Type A cable is plugged into the USB connector. * - 1 - Indicates no cable is attached or a Type B cable is plugged into the * USB connector. */ /*@{*/ #define BP_USB_OTGSTAT_ID (7U) /*!< Bit position for USB_OTGSTAT_ID. */ #define BM_USB_OTGSTAT_ID (0x80U) /*!< Bit mask for USB_OTGSTAT_ID. */ #define BS_USB_OTGSTAT_ID (1U) /*!< Bit field size in bits for USB_OTGSTAT_ID. */ /*! @brief Read current value of the USB_OTGSTAT_ID field. */ #define BR_USB_OTGSTAT_ID(x) (BITBAND_ACCESS8(HW_USB_OTGSTAT_ADDR(x), BP_USB_OTGSTAT_ID)) /*! @brief Format value for bitfield USB_OTGSTAT_ID. */ #define BF_USB_OTGSTAT_ID(v) ((uint8_t)((uint8_t)(v) << BP_USB_OTGSTAT_ID) & BM_USB_OTGSTAT_ID) /*! @brief Set the ID field to a new value. */ #define BW_USB_OTGSTAT_ID(x, v) (BITBAND_ACCESS8(HW_USB_OTGSTAT_ADDR(x), BP_USB_OTGSTAT_ID) = (v)) /*@}*/ /******************************************************************************* * HW_USB_OTGCTL - OTG Control register ******************************************************************************/ /*! * @brief HW_USB_OTGCTL - OTG Control register (RW) * * Reset value: 0x00U * * Controls the operation of VBUS and Data Line termination resistors. */ typedef union _hw_usb_otgctl { uint8_t U; struct _hw_usb_otgctl_bitfields { uint8_t RESERVED0 : 2; /*!< [1:0] */ uint8_t OTGEN : 1; /*!< [2] On-The-Go pullup/pulldown resistor enable * */ uint8_t RESERVED1 : 1; /*!< [3] */ uint8_t DMLOW : 1; /*!< [4] D- Data Line pull-down resistor enable */ uint8_t DPLOW : 1; /*!< [5] D+ Data Line pull-down resistor enable */ uint8_t RESERVED2 : 1; /*!< [6] */ uint8_t DPHIGH : 1; /*!< [7] D+ Data Line pullup resistor enable */ } B; } hw_usb_otgctl_t; /*! * @name Constants and macros for entire USB_OTGCTL register */ /*@{*/ #define HW_USB_OTGCTL_ADDR(x) ((x) + 0x1CU) #define HW_USB_OTGCTL(x) (*(__IO hw_usb_otgctl_t *) HW_USB_OTGCTL_ADDR(x)) #define HW_USB_OTGCTL_RD(x) (HW_USB_OTGCTL(x).U) #define HW_USB_OTGCTL_WR(x, v) (HW_USB_OTGCTL(x).U = (v)) #define HW_USB_OTGCTL_SET(x, v) (HW_USB_OTGCTL_WR(x, HW_USB_OTGCTL_RD(x) | (v))) #define HW_USB_OTGCTL_CLR(x, v) (HW_USB_OTGCTL_WR(x, HW_USB_OTGCTL_RD(x) & ~(v))) #define HW_USB_OTGCTL_TOG(x, v) (HW_USB_OTGCTL_WR(x, HW_USB_OTGCTL_RD(x) ^ (v))) /*@}*/ /* * Constants & macros for individual USB_OTGCTL bitfields */ /*! * @name Register USB_OTGCTL, field OTGEN[2] (RW) * * Values: * - 0 - If USB_EN is 1 and HOST_MODE is 0 in the Control Register (CTL), then * the D+ Data Line pull-up resistors are enabled. If HOST_MODE is 1 the D+ * and D- Data Line pull-down resistors are engaged. * - 1 - The pull-up and pull-down controls in this register are used. */ /*@{*/ #define BP_USB_OTGCTL_OTGEN (2U) /*!< Bit position for USB_OTGCTL_OTGEN. */ #define BM_USB_OTGCTL_OTGEN (0x04U) /*!< Bit mask for USB_OTGCTL_OTGEN. */ #define BS_USB_OTGCTL_OTGEN (1U) /*!< Bit field size in bits for USB_OTGCTL_OTGEN. */ /*! @brief Read current value of the USB_OTGCTL_OTGEN field. */ #define BR_USB_OTGCTL_OTGEN(x) (BITBAND_ACCESS8(HW_USB_OTGCTL_ADDR(x), BP_USB_OTGCTL_OTGEN)) /*! @brief Format value for bitfield USB_OTGCTL_OTGEN. */ #define BF_USB_OTGCTL_OTGEN(v) ((uint8_t)((uint8_t)(v) << BP_USB_OTGCTL_OTGEN) & BM_USB_OTGCTL_OTGEN) /*! @brief Set the OTGEN field to a new value. */ #define BW_USB_OTGCTL_OTGEN(x, v) (BITBAND_ACCESS8(HW_USB_OTGCTL_ADDR(x), BP_USB_OTGCTL_OTGEN) = (v)) /*@}*/ /*! * @name Register USB_OTGCTL, field DMLOW[4] (RW) * * Values: * - 0 - D- pulldown resistor is not enabled. * - 1 - D- pulldown resistor is enabled. */ /*@{*/ #define BP_USB_OTGCTL_DMLOW (4U) /*!< Bit position for USB_OTGCTL_DMLOW. */ #define BM_USB_OTGCTL_DMLOW (0x10U) /*!< Bit mask for USB_OTGCTL_DMLOW. */ #define BS_USB_OTGCTL_DMLOW (1U) /*!< Bit field size in bits for USB_OTGCTL_DMLOW. */ /*! @brief Read current value of the USB_OTGCTL_DMLOW field. */ #define BR_USB_OTGCTL_DMLOW(x) (BITBAND_ACCESS8(HW_USB_OTGCTL_ADDR(x), BP_USB_OTGCTL_DMLOW)) /*! @brief Format value for bitfield USB_OTGCTL_DMLOW. */ #define BF_USB_OTGCTL_DMLOW(v) ((uint8_t)((uint8_t)(v) << BP_USB_OTGCTL_DMLOW) & BM_USB_OTGCTL_DMLOW) /*! @brief Set the DMLOW field to a new value. */ #define BW_USB_OTGCTL_DMLOW(x, v) (BITBAND_ACCESS8(HW_USB_OTGCTL_ADDR(x), BP_USB_OTGCTL_DMLOW) = (v)) /*@}*/ /*! * @name Register USB_OTGCTL, field DPLOW[5] (RW) * * This bit should always be enabled together with bit 4 (DMLOW) * * Values: * - 0 - D+ pulldown resistor is not enabled. * - 1 - D+ pulldown resistor is enabled. */ /*@{*/ #define BP_USB_OTGCTL_DPLOW (5U) /*!< Bit position for USB_OTGCTL_DPLOW. */ #define BM_USB_OTGCTL_DPLOW (0x20U) /*!< Bit mask for USB_OTGCTL_DPLOW. */ #define BS_USB_OTGCTL_DPLOW (1U) /*!< Bit field size in bits for USB_OTGCTL_DPLOW. */ /*! @brief Read current value of the USB_OTGCTL_DPLOW field. */ #define BR_USB_OTGCTL_DPLOW(x) (BITBAND_ACCESS8(HW_USB_OTGCTL_ADDR(x), BP_USB_OTGCTL_DPLOW)) /*! @brief Format value for bitfield USB_OTGCTL_DPLOW. */ #define BF_USB_OTGCTL_DPLOW(v) ((uint8_t)((uint8_t)(v) << BP_USB_OTGCTL_DPLOW) & BM_USB_OTGCTL_DPLOW) /*! @brief Set the DPLOW field to a new value. */ #define BW_USB_OTGCTL_DPLOW(x, v) (BITBAND_ACCESS8(HW_USB_OTGCTL_ADDR(x), BP_USB_OTGCTL_DPLOW) = (v)) /*@}*/ /*! * @name Register USB_OTGCTL, field DPHIGH[7] (RW) * * Values: * - 0 - D+ pullup resistor is not enabled * - 1 - D+ pullup resistor is enabled */ /*@{*/ #define BP_USB_OTGCTL_DPHIGH (7U) /*!< Bit position for USB_OTGCTL_DPHIGH. */ #define BM_USB_OTGCTL_DPHIGH (0x80U) /*!< Bit mask for USB_OTGCTL_DPHIGH. */ #define BS_USB_OTGCTL_DPHIGH (1U) /*!< Bit field size in bits for USB_OTGCTL_DPHIGH. */ /*! @brief Read current value of the USB_OTGCTL_DPHIGH field. */ #define BR_USB_OTGCTL_DPHIGH(x) (BITBAND_ACCESS8(HW_USB_OTGCTL_ADDR(x), BP_USB_OTGCTL_DPHIGH)) /*! @brief Format value for bitfield USB_OTGCTL_DPHIGH. */ #define BF_USB_OTGCTL_DPHIGH(v) ((uint8_t)((uint8_t)(v) << BP_USB_OTGCTL_DPHIGH) & BM_USB_OTGCTL_DPHIGH) /*! @brief Set the DPHIGH field to a new value. */ #define BW_USB_OTGCTL_DPHIGH(x, v) (BITBAND_ACCESS8(HW_USB_OTGCTL_ADDR(x), BP_USB_OTGCTL_DPHIGH) = (v)) /*@}*/ /******************************************************************************* * HW_USB_ISTAT - Interrupt Status register ******************************************************************************/ /*! * @brief HW_USB_ISTAT - Interrupt Status register (W1C) * * Reset value: 0x00U * * Contains fields for each of the interrupt sources within the USB Module. Each * of these fields are qualified with their respective interrupt enable bits. * All fields of this register are logically OR'd together along with the OTG * Interrupt Status Register (OTGSTAT) to form a single interrupt source for the * processor's interrupt controller. After an interrupt bit has been set it may only * be cleared by writing a one to the respective interrupt bit. This register * contains the value of 0x00 after a reset. */ typedef union _hw_usb_istat { uint8_t U; struct _hw_usb_istat_bitfields { uint8_t USBRST : 1; /*!< [0] */ uint8_t ERROR : 1; /*!< [1] */ uint8_t SOFTOK : 1; /*!< [2] */ uint8_t TOKDNE : 1; /*!< [3] */ uint8_t SLEEP : 1; /*!< [4] */ uint8_t RESUME : 1; /*!< [5] */ uint8_t ATTACH : 1; /*!< [6] Attach Interrupt */ uint8_t STALL : 1; /*!< [7] Stall Interrupt */ } B; } hw_usb_istat_t; /*! * @name Constants and macros for entire USB_ISTAT register */ /*@{*/ #define HW_USB_ISTAT_ADDR(x) ((x) + 0x80U) #define HW_USB_ISTAT(x) (*(__IO hw_usb_istat_t *) HW_USB_ISTAT_ADDR(x)) #define HW_USB_ISTAT_RD(x) (HW_USB_ISTAT(x).U) #define HW_USB_ISTAT_WR(x, v) (HW_USB_ISTAT(x).U = (v)) #define HW_USB_ISTAT_SET(x, v) (HW_USB_ISTAT_WR(x, HW_USB_ISTAT_RD(x) | (v))) #define HW_USB_ISTAT_CLR(x, v) (HW_USB_ISTAT_WR(x, HW_USB_ISTAT_RD(x) & ~(v))) #define HW_USB_ISTAT_TOG(x, v) (HW_USB_ISTAT_WR(x, HW_USB_ISTAT_RD(x) ^ (v))) /*@}*/ /* * Constants & macros for individual USB_ISTAT bitfields */ /*! * @name Register USB_ISTAT, field USBRST[0] (W1C) * * This bit is set when the USB Module has decoded a valid USB reset. This * informs the processor that it should write 0x00 into the address register and * enable endpoint 0. USBRST is set after a USB reset has been detected for 2.5 * microseconds. It is not asserted again until the USB reset condition has been * removed and then reasserted. */ /*@{*/ #define BP_USB_ISTAT_USBRST (0U) /*!< Bit position for USB_ISTAT_USBRST. */ #define BM_USB_ISTAT_USBRST (0x01U) /*!< Bit mask for USB_ISTAT_USBRST. */ #define BS_USB_ISTAT_USBRST (1U) /*!< Bit field size in bits for USB_ISTAT_USBRST. */ /*! @brief Read current value of the USB_ISTAT_USBRST field. */ #define BR_USB_ISTAT_USBRST(x) (BITBAND_ACCESS8(HW_USB_ISTAT_ADDR(x), BP_USB_ISTAT_USBRST)) /*! @brief Format value for bitfield USB_ISTAT_USBRST. */ #define BF_USB_ISTAT_USBRST(v) ((uint8_t)((uint8_t)(v) << BP_USB_ISTAT_USBRST) & BM_USB_ISTAT_USBRST) /*! @brief Set the USBRST field to a new value. */ #define BW_USB_ISTAT_USBRST(x, v) (BITBAND_ACCESS8(HW_USB_ISTAT_ADDR(x), BP_USB_ISTAT_USBRST) = (v)) /*@}*/ /*! * @name Register USB_ISTAT, field ERROR[1] (W1C) * * This bit is set when any of the error conditions within Error Interrupt * Status (ERRSTAT) register occur. The processor must then read the ERRSTAT register * to determine the source of the error. */ /*@{*/ #define BP_USB_ISTAT_ERROR (1U) /*!< Bit position for USB_ISTAT_ERROR. */ #define BM_USB_ISTAT_ERROR (0x02U) /*!< Bit mask for USB_ISTAT_ERROR. */ #define BS_USB_ISTAT_ERROR (1U) /*!< Bit field size in bits for USB_ISTAT_ERROR. */ /*! @brief Read current value of the USB_ISTAT_ERROR field. */ #define BR_USB_ISTAT_ERROR(x) (BITBAND_ACCESS8(HW_USB_ISTAT_ADDR(x), BP_USB_ISTAT_ERROR)) /*! @brief Format value for bitfield USB_ISTAT_ERROR. */ #define BF_USB_ISTAT_ERROR(v) ((uint8_t)((uint8_t)(v) << BP_USB_ISTAT_ERROR) & BM_USB_ISTAT_ERROR) /*! @brief Set the ERROR field to a new value. */ #define BW_USB_ISTAT_ERROR(x, v) (BITBAND_ACCESS8(HW_USB_ISTAT_ADDR(x), BP_USB_ISTAT_ERROR) = (v)) /*@}*/ /*! * @name Register USB_ISTAT, field SOFTOK[2] (W1C) * * This bit is set when the USB Module receives a Start Of Frame (SOF) token. In * Host mode this field is set when the SOF threshold is reached, so that * software can prepare for the next SOF. */ /*@{*/ #define BP_USB_ISTAT_SOFTOK (2U) /*!< Bit position for USB_ISTAT_SOFTOK. */ #define BM_USB_ISTAT_SOFTOK (0x04U) /*!< Bit mask for USB_ISTAT_SOFTOK. */ #define BS_USB_ISTAT_SOFTOK (1U) /*!< Bit field size in bits for USB_ISTAT_SOFTOK. */ /*! @brief Read current value of the USB_ISTAT_SOFTOK field. */ #define BR_USB_ISTAT_SOFTOK(x) (BITBAND_ACCESS8(HW_USB_ISTAT_ADDR(x), BP_USB_ISTAT_SOFTOK)) /*! @brief Format value for bitfield USB_ISTAT_SOFTOK. */ #define BF_USB_ISTAT_SOFTOK(v) ((uint8_t)((uint8_t)(v) << BP_USB_ISTAT_SOFTOK) & BM_USB_ISTAT_SOFTOK) /*! @brief Set the SOFTOK field to a new value. */ #define BW_USB_ISTAT_SOFTOK(x, v) (BITBAND_ACCESS8(HW_USB_ISTAT_ADDR(x), BP_USB_ISTAT_SOFTOK) = (v)) /*@}*/ /*! * @name Register USB_ISTAT, field TOKDNE[3] (W1C) * * This bit is set when the current token being processed has completed. The * processor must immediately read the STATUS (STAT) register to determine the * EndPoint and BD used for this token. Clearing this bit (by writing a one) causes * STAT to be cleared or the STAT holding register to be loaded into the STAT * register. */ /*@{*/ #define BP_USB_ISTAT_TOKDNE (3U) /*!< Bit position for USB_ISTAT_TOKDNE. */ #define BM_USB_ISTAT_TOKDNE (0x08U) /*!< Bit mask for USB_ISTAT_TOKDNE. */ #define BS_USB_ISTAT_TOKDNE (1U) /*!< Bit field size in bits for USB_ISTAT_TOKDNE. */ /*! @brief Read current value of the USB_ISTAT_TOKDNE field. */ #define BR_USB_ISTAT_TOKDNE(x) (BITBAND_ACCESS8(HW_USB_ISTAT_ADDR(x), BP_USB_ISTAT_TOKDNE)) /*! @brief Format value for bitfield USB_ISTAT_TOKDNE. */ #define BF_USB_ISTAT_TOKDNE(v) ((uint8_t)((uint8_t)(v) << BP_USB_ISTAT_TOKDNE) & BM_USB_ISTAT_TOKDNE) /*! @brief Set the TOKDNE field to a new value. */ #define BW_USB_ISTAT_TOKDNE(x, v) (BITBAND_ACCESS8(HW_USB_ISTAT_ADDR(x), BP_USB_ISTAT_TOKDNE) = (v)) /*@}*/ /*! * @name Register USB_ISTAT, field SLEEP[4] (W1C) * * This bit is set when the USB Module detects a constant idle on the USB bus * for 3 ms. The sleep timer is reset by activity on the USB bus. */ /*@{*/ #define BP_USB_ISTAT_SLEEP (4U) /*!< Bit position for USB_ISTAT_SLEEP. */ #define BM_USB_ISTAT_SLEEP (0x10U) /*!< Bit mask for USB_ISTAT_SLEEP. */ #define BS_USB_ISTAT_SLEEP (1U) /*!< Bit field size in bits for USB_ISTAT_SLEEP. */ /*! @brief Read current value of the USB_ISTAT_SLEEP field. */ #define BR_USB_ISTAT_SLEEP(x) (BITBAND_ACCESS8(HW_USB_ISTAT_ADDR(x), BP_USB_ISTAT_SLEEP)) /*! @brief Format value for bitfield USB_ISTAT_SLEEP. */ #define BF_USB_ISTAT_SLEEP(v) ((uint8_t)((uint8_t)(v) << BP_USB_ISTAT_SLEEP) & BM_USB_ISTAT_SLEEP) /*! @brief Set the SLEEP field to a new value. */ #define BW_USB_ISTAT_SLEEP(x, v) (BITBAND_ACCESS8(HW_USB_ISTAT_ADDR(x), BP_USB_ISTAT_SLEEP) = (v)) /*@}*/ /*! * @name Register USB_ISTAT, field RESUME[5] (W1C) * * This bit is set when a K-state is observed on the DP/DM signals for 2.5 us. * When not in suspend mode this interrupt must be disabled. */ /*@{*/ #define BP_USB_ISTAT_RESUME (5U) /*!< Bit position for USB_ISTAT_RESUME. */ #define BM_USB_ISTAT_RESUME (0x20U) /*!< Bit mask for USB_ISTAT_RESUME. */ #define BS_USB_ISTAT_RESUME (1U) /*!< Bit field size in bits for USB_ISTAT_RESUME. */ /*! @brief Read current value of the USB_ISTAT_RESUME field. */ #define BR_USB_ISTAT_RESUME(x) (BITBAND_ACCESS8(HW_USB_ISTAT_ADDR(x), BP_USB_ISTAT_RESUME)) /*! @brief Format value for bitfield USB_ISTAT_RESUME. */ #define BF_USB_ISTAT_RESUME(v) ((uint8_t)((uint8_t)(v) << BP_USB_ISTAT_RESUME) & BM_USB_ISTAT_RESUME) /*! @brief Set the RESUME field to a new value. */ #define BW_USB_ISTAT_RESUME(x, v) (BITBAND_ACCESS8(HW_USB_ISTAT_ADDR(x), BP_USB_ISTAT_RESUME) = (v)) /*@}*/ /*! * @name Register USB_ISTAT, field ATTACH[6] (W1C) * * This bit is set when the USB Module detects an attach of a USB device. This * signal is only valid if HOSTMODEEN is true. This interrupt signifies that a * peripheral is now present and must be configured; it is asserted if there have * been no transitions on the USB for 2.5 us and the current bus state is not SE0." */ /*@{*/ #define BP_USB_ISTAT_ATTACH (6U) /*!< Bit position for USB_ISTAT_ATTACH. */ #define BM_USB_ISTAT_ATTACH (0x40U) /*!< Bit mask for USB_ISTAT_ATTACH. */ #define BS_USB_ISTAT_ATTACH (1U) /*!< Bit field size in bits for USB_ISTAT_ATTACH. */ /*! @brief Read current value of the USB_ISTAT_ATTACH field. */ #define BR_USB_ISTAT_ATTACH(x) (BITBAND_ACCESS8(HW_USB_ISTAT_ADDR(x), BP_USB_ISTAT_ATTACH)) /*! @brief Format value for bitfield USB_ISTAT_ATTACH. */ #define BF_USB_ISTAT_ATTACH(v) ((uint8_t)((uint8_t)(v) << BP_USB_ISTAT_ATTACH) & BM_USB_ISTAT_ATTACH) /*! @brief Set the ATTACH field to a new value. */ #define BW_USB_ISTAT_ATTACH(x, v) (BITBAND_ACCESS8(HW_USB_ISTAT_ADDR(x), BP_USB_ISTAT_ATTACH) = (v)) /*@}*/ /*! * @name Register USB_ISTAT, field STALL[7] (W1C) * * In Target mode this bit is asserted when a STALL handshake is sent by the * SIE. In Host mode this bit is set when the USB Module detects a STALL acknowledge * during the handshake phase of a USB transaction.This interrupt can be used to * determine whether the last USB transaction was completed successfully or * stalled. */ /*@{*/ #define BP_USB_ISTAT_STALL (7U) /*!< Bit position for USB_ISTAT_STALL. */ #define BM_USB_ISTAT_STALL (0x80U) /*!< Bit mask for USB_ISTAT_STALL. */ #define BS_USB_ISTAT_STALL (1U) /*!< Bit field size in bits for USB_ISTAT_STALL. */ /*! @brief Read current value of the USB_ISTAT_STALL field. */ #define BR_USB_ISTAT_STALL(x) (BITBAND_ACCESS8(HW_USB_ISTAT_ADDR(x), BP_USB_ISTAT_STALL)) /*! @brief Format value for bitfield USB_ISTAT_STALL. */ #define BF_USB_ISTAT_STALL(v) ((uint8_t)((uint8_t)(v) << BP_USB_ISTAT_STALL) & BM_USB_ISTAT_STALL) /*! @brief Set the STALL field to a new value. */ #define BW_USB_ISTAT_STALL(x, v) (BITBAND_ACCESS8(HW_USB_ISTAT_ADDR(x), BP_USB_ISTAT_STALL) = (v)) /*@}*/ /******************************************************************************* * HW_USB_INTEN - Interrupt Enable register ******************************************************************************/ /*! * @brief HW_USB_INTEN - Interrupt Enable register (RW) * * Reset value: 0x00U * * Contains enable fields for each of the interrupt sources within the USB * Module. Setting any of these bits enables the respective interrupt source in the * ISTAT register. This register contains the value of 0x00 after a reset. */ typedef union _hw_usb_inten { uint8_t U; struct _hw_usb_inten_bitfields { uint8_t USBRSTEN : 1; /*!< [0] USBRST Interrupt Enable */ uint8_t ERROREN : 1; /*!< [1] ERROR Interrupt Enable */ uint8_t SOFTOKEN : 1; /*!< [2] SOFTOK Interrupt Enable */ uint8_t TOKDNEEN : 1; /*!< [3] TOKDNE Interrupt Enable */ uint8_t SLEEPEN : 1; /*!< [4] SLEEP Interrupt Enable */ uint8_t RESUMEEN : 1; /*!< [5] RESUME Interrupt Enable */ uint8_t ATTACHEN : 1; /*!< [6] ATTACH Interrupt Enable */ uint8_t STALLEN : 1; /*!< [7] STALL Interrupt Enable */ } B; } hw_usb_inten_t; /*! * @name Constants and macros for entire USB_INTEN register */ /*@{*/ #define HW_USB_INTEN_ADDR(x) ((x) + 0x84U) #define HW_USB_INTEN(x) (*(__IO hw_usb_inten_t *) HW_USB_INTEN_ADDR(x)) #define HW_USB_INTEN_RD(x) (HW_USB_INTEN(x).U) #define HW_USB_INTEN_WR(x, v) (HW_USB_INTEN(x).U = (v)) #define HW_USB_INTEN_SET(x, v) (HW_USB_INTEN_WR(x, HW_USB_INTEN_RD(x) | (v))) #define HW_USB_INTEN_CLR(x, v) (HW_USB_INTEN_WR(x, HW_USB_INTEN_RD(x) & ~(v))) #define HW_USB_INTEN_TOG(x, v) (HW_USB_INTEN_WR(x, HW_USB_INTEN_RD(x) ^ (v))) /*@}*/ /* * Constants & macros for individual USB_INTEN bitfields */ /*! * @name Register USB_INTEN, field USBRSTEN[0] (RW) * * Values: * - 0 - Disables the USBRST interrupt. * - 1 - Enables the USBRST interrupt. */ /*@{*/ #define BP_USB_INTEN_USBRSTEN (0U) /*!< Bit position for USB_INTEN_USBRSTEN. */ #define BM_USB_INTEN_USBRSTEN (0x01U) /*!< Bit mask for USB_INTEN_USBRSTEN. */ #define BS_USB_INTEN_USBRSTEN (1U) /*!< Bit field size in bits for USB_INTEN_USBRSTEN. */ /*! @brief Read current value of the USB_INTEN_USBRSTEN field. */ #define BR_USB_INTEN_USBRSTEN(x) (BITBAND_ACCESS8(HW_USB_INTEN_ADDR(x), BP_USB_INTEN_USBRSTEN)) /*! @brief Format value for bitfield USB_INTEN_USBRSTEN. */ #define BF_USB_INTEN_USBRSTEN(v) ((uint8_t)((uint8_t)(v) << BP_USB_INTEN_USBRSTEN) & BM_USB_INTEN_USBRSTEN) /*! @brief Set the USBRSTEN field to a new value. */ #define BW_USB_INTEN_USBRSTEN(x, v) (BITBAND_ACCESS8(HW_USB_INTEN_ADDR(x), BP_USB_INTEN_USBRSTEN) = (v)) /*@}*/ /*! * @name Register USB_INTEN, field ERROREN[1] (RW) * * Values: * - 0 - Disables the ERROR interrupt. * - 1 - Enables the ERROR interrupt. */ /*@{*/ #define BP_USB_INTEN_ERROREN (1U) /*!< Bit position for USB_INTEN_ERROREN. */ #define BM_USB_INTEN_ERROREN (0x02U) /*!< Bit mask for USB_INTEN_ERROREN. */ #define BS_USB_INTEN_ERROREN (1U) /*!< Bit field size in bits for USB_INTEN_ERROREN. */ /*! @brief Read current value of the USB_INTEN_ERROREN field. */ #define BR_USB_INTEN_ERROREN(x) (BITBAND_ACCESS8(HW_USB_INTEN_ADDR(x), BP_USB_INTEN_ERROREN)) /*! @brief Format value for bitfield USB_INTEN_ERROREN. */ #define BF_USB_INTEN_ERROREN(v) ((uint8_t)((uint8_t)(v) << BP_USB_INTEN_ERROREN) & BM_USB_INTEN_ERROREN) /*! @brief Set the ERROREN field to a new value. */ #define BW_USB_INTEN_ERROREN(x, v) (BITBAND_ACCESS8(HW_USB_INTEN_ADDR(x), BP_USB_INTEN_ERROREN) = (v)) /*@}*/ /*! * @name Register USB_INTEN, field SOFTOKEN[2] (RW) * * Values: * - 0 - Disbles the SOFTOK interrupt. * - 1 - Enables the SOFTOK interrupt. */ /*@{*/ #define BP_USB_INTEN_SOFTOKEN (2U) /*!< Bit position for USB_INTEN_SOFTOKEN. */ #define BM_USB_INTEN_SOFTOKEN (0x04U) /*!< Bit mask for USB_INTEN_SOFTOKEN. */ #define BS_USB_INTEN_SOFTOKEN (1U) /*!< Bit field size in bits for USB_INTEN_SOFTOKEN. */ /*! @brief Read current value of the USB_INTEN_SOFTOKEN field. */ #define BR_USB_INTEN_SOFTOKEN(x) (BITBAND_ACCESS8(HW_USB_INTEN_ADDR(x), BP_USB_INTEN_SOFTOKEN)) /*! @brief Format value for bitfield USB_INTEN_SOFTOKEN. */ #define BF_USB_INTEN_SOFTOKEN(v) ((uint8_t)((uint8_t)(v) << BP_USB_INTEN_SOFTOKEN) & BM_USB_INTEN_SOFTOKEN) /*! @brief Set the SOFTOKEN field to a new value. */ #define BW_USB_INTEN_SOFTOKEN(x, v) (BITBAND_ACCESS8(HW_USB_INTEN_ADDR(x), BP_USB_INTEN_SOFTOKEN) = (v)) /*@}*/ /*! * @name Register USB_INTEN, field TOKDNEEN[3] (RW) * * Values: * - 0 - Disables the TOKDNE interrupt. * - 1 - Enables the TOKDNE interrupt. */ /*@{*/ #define BP_USB_INTEN_TOKDNEEN (3U) /*!< Bit position for USB_INTEN_TOKDNEEN. */ #define BM_USB_INTEN_TOKDNEEN (0x08U) /*!< Bit mask for USB_INTEN_TOKDNEEN. */ #define BS_USB_INTEN_TOKDNEEN (1U) /*!< Bit field size in bits for USB_INTEN_TOKDNEEN. */ /*! @brief Read current value of the USB_INTEN_TOKDNEEN field. */ #define BR_USB_INTEN_TOKDNEEN(x) (BITBAND_ACCESS8(HW_USB_INTEN_ADDR(x), BP_USB_INTEN_TOKDNEEN)) /*! @brief Format value for bitfield USB_INTEN_TOKDNEEN. */ #define BF_USB_INTEN_TOKDNEEN(v) ((uint8_t)((uint8_t)(v) << BP_USB_INTEN_TOKDNEEN) & BM_USB_INTEN_TOKDNEEN) /*! @brief Set the TOKDNEEN field to a new value. */ #define BW_USB_INTEN_TOKDNEEN(x, v) (BITBAND_ACCESS8(HW_USB_INTEN_ADDR(x), BP_USB_INTEN_TOKDNEEN) = (v)) /*@}*/ /*! * @name Register USB_INTEN, field SLEEPEN[4] (RW) * * Values: * - 0 - Disables the SLEEP interrupt. * - 1 - Enables the SLEEP interrupt. */ /*@{*/ #define BP_USB_INTEN_SLEEPEN (4U) /*!< Bit position for USB_INTEN_SLEEPEN. */ #define BM_USB_INTEN_SLEEPEN (0x10U) /*!< Bit mask for USB_INTEN_SLEEPEN. */ #define BS_USB_INTEN_SLEEPEN (1U) /*!< Bit field size in bits for USB_INTEN_SLEEPEN. */ /*! @brief Read current value of the USB_INTEN_SLEEPEN field. */ #define BR_USB_INTEN_SLEEPEN(x) (BITBAND_ACCESS8(HW_USB_INTEN_ADDR(x), BP_USB_INTEN_SLEEPEN)) /*! @brief Format value for bitfield USB_INTEN_SLEEPEN. */ #define BF_USB_INTEN_SLEEPEN(v) ((uint8_t)((uint8_t)(v) << BP_USB_INTEN_SLEEPEN) & BM_USB_INTEN_SLEEPEN) /*! @brief Set the SLEEPEN field to a new value. */ #define BW_USB_INTEN_SLEEPEN(x, v) (BITBAND_ACCESS8(HW_USB_INTEN_ADDR(x), BP_USB_INTEN_SLEEPEN) = (v)) /*@}*/ /*! * @name Register USB_INTEN, field RESUMEEN[5] (RW) * * Values: * - 0 - Disables the RESUME interrupt. * - 1 - Enables the RESUME interrupt. */ /*@{*/ #define BP_USB_INTEN_RESUMEEN (5U) /*!< Bit position for USB_INTEN_RESUMEEN. */ #define BM_USB_INTEN_RESUMEEN (0x20U) /*!< Bit mask for USB_INTEN_RESUMEEN. */ #define BS_USB_INTEN_RESUMEEN (1U) /*!< Bit field size in bits for USB_INTEN_RESUMEEN. */ /*! @brief Read current value of the USB_INTEN_RESUMEEN field. */ #define BR_USB_INTEN_RESUMEEN(x) (BITBAND_ACCESS8(HW_USB_INTEN_ADDR(x), BP_USB_INTEN_RESUMEEN)) /*! @brief Format value for bitfield USB_INTEN_RESUMEEN. */ #define BF_USB_INTEN_RESUMEEN(v) ((uint8_t)((uint8_t)(v) << BP_USB_INTEN_RESUMEEN) & BM_USB_INTEN_RESUMEEN) /*! @brief Set the RESUMEEN field to a new value. */ #define BW_USB_INTEN_RESUMEEN(x, v) (BITBAND_ACCESS8(HW_USB_INTEN_ADDR(x), BP_USB_INTEN_RESUMEEN) = (v)) /*@}*/ /*! * @name Register USB_INTEN, field ATTACHEN[6] (RW) * * Values: * - 0 - Disables the ATTACH interrupt. * - 1 - Enables the ATTACH interrupt. */ /*@{*/ #define BP_USB_INTEN_ATTACHEN (6U) /*!< Bit position for USB_INTEN_ATTACHEN. */ #define BM_USB_INTEN_ATTACHEN (0x40U) /*!< Bit mask for USB_INTEN_ATTACHEN. */ #define BS_USB_INTEN_ATTACHEN (1U) /*!< Bit field size in bits for USB_INTEN_ATTACHEN. */ /*! @brief Read current value of the USB_INTEN_ATTACHEN field. */ #define BR_USB_INTEN_ATTACHEN(x) (BITBAND_ACCESS8(HW_USB_INTEN_ADDR(x), BP_USB_INTEN_ATTACHEN)) /*! @brief Format value for bitfield USB_INTEN_ATTACHEN. */ #define BF_USB_INTEN_ATTACHEN(v) ((uint8_t)((uint8_t)(v) << BP_USB_INTEN_ATTACHEN) & BM_USB_INTEN_ATTACHEN) /*! @brief Set the ATTACHEN field to a new value. */ #define BW_USB_INTEN_ATTACHEN(x, v) (BITBAND_ACCESS8(HW_USB_INTEN_ADDR(x), BP_USB_INTEN_ATTACHEN) = (v)) /*@}*/ /*! * @name Register USB_INTEN, field STALLEN[7] (RW) * * Values: * - 0 - Diasbles the STALL interrupt. * - 1 - Enables the STALL interrupt. */ /*@{*/ #define BP_USB_INTEN_STALLEN (7U) /*!< Bit position for USB_INTEN_STALLEN. */ #define BM_USB_INTEN_STALLEN (0x80U) /*!< Bit mask for USB_INTEN_STALLEN. */ #define BS_USB_INTEN_STALLEN (1U) /*!< Bit field size in bits for USB_INTEN_STALLEN. */ /*! @brief Read current value of the USB_INTEN_STALLEN field. */ #define BR_USB_INTEN_STALLEN(x) (BITBAND_ACCESS8(HW_USB_INTEN_ADDR(x), BP_USB_INTEN_STALLEN)) /*! @brief Format value for bitfield USB_INTEN_STALLEN. */ #define BF_USB_INTEN_STALLEN(v) ((uint8_t)((uint8_t)(v) << BP_USB_INTEN_STALLEN) & BM_USB_INTEN_STALLEN) /*! @brief Set the STALLEN field to a new value. */ #define BW_USB_INTEN_STALLEN(x, v) (BITBAND_ACCESS8(HW_USB_INTEN_ADDR(x), BP_USB_INTEN_STALLEN) = (v)) /*@}*/ /******************************************************************************* * HW_USB_ERRSTAT - Error Interrupt Status register ******************************************************************************/ /*! * @brief HW_USB_ERRSTAT - Error Interrupt Status register (RW) * * Reset value: 0x00U * * Contains enable bits for each of the error sources within the USB Module. * Each of these bits are qualified with their respective error enable bits. All * bits of this register are logically OR'd together and the result placed in the * ERROR bit of the ISTAT register. After an interrupt bit has been set it may only * be cleared by writing a one to the respective interrupt bit. Each bit is set * as soon as the error condition is detected. Therefore, the interrupt does not * typically correspond with the end of a token being processed. This register * contains the value of 0x00 after a reset. */ typedef union _hw_usb_errstat { uint8_t U; struct _hw_usb_errstat_bitfields { uint8_t PIDERR : 1; /*!< [0] */ uint8_t CRC5EOF : 1; /*!< [1] */ uint8_t CRC16 : 1; /*!< [2] */ uint8_t DFN8 : 1; /*!< [3] */ uint8_t BTOERR : 1; /*!< [4] */ uint8_t DMAERR : 1; /*!< [5] */ uint8_t RESERVED0 : 1; /*!< [6] */ uint8_t BTSERR : 1; /*!< [7] */ } B; } hw_usb_errstat_t; /*! * @name Constants and macros for entire USB_ERRSTAT register */ /*@{*/ #define HW_USB_ERRSTAT_ADDR(x) ((x) + 0x88U) #define HW_USB_ERRSTAT(x) (*(__IO hw_usb_errstat_t *) HW_USB_ERRSTAT_ADDR(x)) #define HW_USB_ERRSTAT_RD(x) (HW_USB_ERRSTAT(x).U) #define HW_USB_ERRSTAT_WR(x, v) (HW_USB_ERRSTAT(x).U = (v)) #define HW_USB_ERRSTAT_SET(x, v) (HW_USB_ERRSTAT_WR(x, HW_USB_ERRSTAT_RD(x) | (v))) #define HW_USB_ERRSTAT_CLR(x, v) (HW_USB_ERRSTAT_WR(x, HW_USB_ERRSTAT_RD(x) & ~(v))) #define HW_USB_ERRSTAT_TOG(x, v) (HW_USB_ERRSTAT_WR(x, HW_USB_ERRSTAT_RD(x) ^ (v))) /*@}*/ /* * Constants & macros for individual USB_ERRSTAT bitfields */ /*! * @name Register USB_ERRSTAT, field PIDERR[0] (W1C) * * This bit is set when the PID check field fails. */ /*@{*/ #define BP_USB_ERRSTAT_PIDERR (0U) /*!< Bit position for USB_ERRSTAT_PIDERR. */ #define BM_USB_ERRSTAT_PIDERR (0x01U) /*!< Bit mask for USB_ERRSTAT_PIDERR. */ #define BS_USB_ERRSTAT_PIDERR (1U) /*!< Bit field size in bits for USB_ERRSTAT_PIDERR. */ /*! @brief Read current value of the USB_ERRSTAT_PIDERR field. */ #define BR_USB_ERRSTAT_PIDERR(x) (BITBAND_ACCESS8(HW_USB_ERRSTAT_ADDR(x), BP_USB_ERRSTAT_PIDERR)) /*! @brief Format value for bitfield USB_ERRSTAT_PIDERR. */ #define BF_USB_ERRSTAT_PIDERR(v) ((uint8_t)((uint8_t)(v) << BP_USB_ERRSTAT_PIDERR) & BM_USB_ERRSTAT_PIDERR) /*! @brief Set the PIDERR field to a new value. */ #define BW_USB_ERRSTAT_PIDERR(x, v) (BITBAND_ACCESS8(HW_USB_ERRSTAT_ADDR(x), BP_USB_ERRSTAT_PIDERR) = (v)) /*@}*/ /*! * @name Register USB_ERRSTAT, field CRC5EOF[1] (W1C) * * This error interrupt has two functions. When the USB Module is operating in * peripheral mode (HOSTMODEEN=0), this interrupt detects CRC5 errors in the token * packets generated by the host. If set the token packet was rejected due to a * CRC5 error. When the USB Module is operating in host mode (HOSTMODEEN=1), this * interrupt detects End Of Frame (EOF) error conditions. This occurs when the * USB Module is transmitting or receiving data and the SOF counter reaches zero. * This interrupt is useful when developing USB packet scheduling software to * ensure that no USB transactions cross the start of the next frame. */ /*@{*/ #define BP_USB_ERRSTAT_CRC5EOF (1U) /*!< Bit position for USB_ERRSTAT_CRC5EOF. */ #define BM_USB_ERRSTAT_CRC5EOF (0x02U) /*!< Bit mask for USB_ERRSTAT_CRC5EOF. */ #define BS_USB_ERRSTAT_CRC5EOF (1U) /*!< Bit field size in bits for USB_ERRSTAT_CRC5EOF. */ /*! @brief Read current value of the USB_ERRSTAT_CRC5EOF field. */ #define BR_USB_ERRSTAT_CRC5EOF(x) (BITBAND_ACCESS8(HW_USB_ERRSTAT_ADDR(x), BP_USB_ERRSTAT_CRC5EOF)) /*! @brief Format value for bitfield USB_ERRSTAT_CRC5EOF. */ #define BF_USB_ERRSTAT_CRC5EOF(v) ((uint8_t)((uint8_t)(v) << BP_USB_ERRSTAT_CRC5EOF) & BM_USB_ERRSTAT_CRC5EOF) /*! @brief Set the CRC5EOF field to a new value. */ #define BW_USB_ERRSTAT_CRC5EOF(x, v) (BITBAND_ACCESS8(HW_USB_ERRSTAT_ADDR(x), BP_USB_ERRSTAT_CRC5EOF) = (v)) /*@}*/ /*! * @name Register USB_ERRSTAT, field CRC16[2] (W1C) * * This bit is set when a data packet is rejected due to a CRC16 error. */ /*@{*/ #define BP_USB_ERRSTAT_CRC16 (2U) /*!< Bit position for USB_ERRSTAT_CRC16. */ #define BM_USB_ERRSTAT_CRC16 (0x04U) /*!< Bit mask for USB_ERRSTAT_CRC16. */ #define BS_USB_ERRSTAT_CRC16 (1U) /*!< Bit field size in bits for USB_ERRSTAT_CRC16. */ /*! @brief Read current value of the USB_ERRSTAT_CRC16 field. */ #define BR_USB_ERRSTAT_CRC16(x) (BITBAND_ACCESS8(HW_USB_ERRSTAT_ADDR(x), BP_USB_ERRSTAT_CRC16)) /*! @brief Format value for bitfield USB_ERRSTAT_CRC16. */ #define BF_USB_ERRSTAT_CRC16(v) ((uint8_t)((uint8_t)(v) << BP_USB_ERRSTAT_CRC16) & BM_USB_ERRSTAT_CRC16) /*! @brief Set the CRC16 field to a new value. */ #define BW_USB_ERRSTAT_CRC16(x, v) (BITBAND_ACCESS8(HW_USB_ERRSTAT_ADDR(x), BP_USB_ERRSTAT_CRC16) = (v)) /*@}*/ /*! * @name Register USB_ERRSTAT, field DFN8[3] (W1C) * * This bit is set if the data field received was not 8 bits in length. USB * Specification 1.0 requires that data fields be an integral number of bytes. If the * data field was not an integral number of bytes, this bit is set. */ /*@{*/ #define BP_USB_ERRSTAT_DFN8 (3U) /*!< Bit position for USB_ERRSTAT_DFN8. */ #define BM_USB_ERRSTAT_DFN8 (0x08U) /*!< Bit mask for USB_ERRSTAT_DFN8. */ #define BS_USB_ERRSTAT_DFN8 (1U) /*!< Bit field size in bits for USB_ERRSTAT_DFN8. */ /*! @brief Read current value of the USB_ERRSTAT_DFN8 field. */ #define BR_USB_ERRSTAT_DFN8(x) (BITBAND_ACCESS8(HW_USB_ERRSTAT_ADDR(x), BP_USB_ERRSTAT_DFN8)) /*! @brief Format value for bitfield USB_ERRSTAT_DFN8. */ #define BF_USB_ERRSTAT_DFN8(v) ((uint8_t)((uint8_t)(v) << BP_USB_ERRSTAT_DFN8) & BM_USB_ERRSTAT_DFN8) /*! @brief Set the DFN8 field to a new value. */ #define BW_USB_ERRSTAT_DFN8(x, v) (BITBAND_ACCESS8(HW_USB_ERRSTAT_ADDR(x), BP_USB_ERRSTAT_DFN8) = (v)) /*@}*/ /*! * @name Register USB_ERRSTAT, field BTOERR[4] (W1C) * * This bit is set when a bus turnaround timeout error occurs. The USB module * contains a bus turnaround timer that keeps track of the amount of time elapsed * between the token and data phases of a SETUP or OUT TOKEN or the data and * handshake phases of a IN TOKEN. If more than 16 bit times are counted from the * previous EOP before a transition from IDLE, a bus turnaround timeout error occurs. */ /*@{*/ #define BP_USB_ERRSTAT_BTOERR (4U) /*!< Bit position for USB_ERRSTAT_BTOERR. */ #define BM_USB_ERRSTAT_BTOERR (0x10U) /*!< Bit mask for USB_ERRSTAT_BTOERR. */ #define BS_USB_ERRSTAT_BTOERR (1U) /*!< Bit field size in bits for USB_ERRSTAT_BTOERR. */ /*! @brief Read current value of the USB_ERRSTAT_BTOERR field. */ #define BR_USB_ERRSTAT_BTOERR(x) (BITBAND_ACCESS8(HW_USB_ERRSTAT_ADDR(x), BP_USB_ERRSTAT_BTOERR)) /*! @brief Format value for bitfield USB_ERRSTAT_BTOERR. */ #define BF_USB_ERRSTAT_BTOERR(v) ((uint8_t)((uint8_t)(v) << BP_USB_ERRSTAT_BTOERR) & BM_USB_ERRSTAT_BTOERR) /*! @brief Set the BTOERR field to a new value. */ #define BW_USB_ERRSTAT_BTOERR(x, v) (BITBAND_ACCESS8(HW_USB_ERRSTAT_ADDR(x), BP_USB_ERRSTAT_BTOERR) = (v)) /*@}*/ /*! * @name Register USB_ERRSTAT, field DMAERR[5] (W1C) * * This bit is set if the USB Module has requested a DMA access to read a new * BDT but has not been given the bus before it needs to receive or transmit data. * If processing a TX transfer this would cause a transmit data underflow * condition. If processing a RX transfer this would cause a receive data overflow * condition. This interrupt is useful when developing device arbitration hardware for * the microprocessor and the USB module to minimize bus request and bus grant * latency. This bit is also set if a data packet to or from the host is larger * than the buffer size allocated in the BDT. In this case the data packet is * truncated as it is put in buffer memory. */ /*@{*/ #define BP_USB_ERRSTAT_DMAERR (5U) /*!< Bit position for USB_ERRSTAT_DMAERR. */ #define BM_USB_ERRSTAT_DMAERR (0x20U) /*!< Bit mask for USB_ERRSTAT_DMAERR. */ #define BS_USB_ERRSTAT_DMAERR (1U) /*!< Bit field size in bits for USB_ERRSTAT_DMAERR. */ /*! @brief Read current value of the USB_ERRSTAT_DMAERR field. */ #define BR_USB_ERRSTAT_DMAERR(x) (BITBAND_ACCESS8(HW_USB_ERRSTAT_ADDR(x), BP_USB_ERRSTAT_DMAERR)) /*! @brief Format value for bitfield USB_ERRSTAT_DMAERR. */ #define BF_USB_ERRSTAT_DMAERR(v) ((uint8_t)((uint8_t)(v) << BP_USB_ERRSTAT_DMAERR) & BM_USB_ERRSTAT_DMAERR) /*! @brief Set the DMAERR field to a new value. */ #define BW_USB_ERRSTAT_DMAERR(x, v) (BITBAND_ACCESS8(HW_USB_ERRSTAT_ADDR(x), BP_USB_ERRSTAT_DMAERR) = (v)) /*@}*/ /*! * @name Register USB_ERRSTAT, field BTSERR[7] (W1C) * * This bit is set when a bit stuff error is detected. If set, the corresponding * packet is rejected due to the error. */ /*@{*/ #define BP_USB_ERRSTAT_BTSERR (7U) /*!< Bit position for USB_ERRSTAT_BTSERR. */ #define BM_USB_ERRSTAT_BTSERR (0x80U) /*!< Bit mask for USB_ERRSTAT_BTSERR. */ #define BS_USB_ERRSTAT_BTSERR (1U) /*!< Bit field size in bits for USB_ERRSTAT_BTSERR. */ /*! @brief Read current value of the USB_ERRSTAT_BTSERR field. */ #define BR_USB_ERRSTAT_BTSERR(x) (BITBAND_ACCESS8(HW_USB_ERRSTAT_ADDR(x), BP_USB_ERRSTAT_BTSERR)) /*! @brief Format value for bitfield USB_ERRSTAT_BTSERR. */ #define BF_USB_ERRSTAT_BTSERR(v) ((uint8_t)((uint8_t)(v) << BP_USB_ERRSTAT_BTSERR) & BM_USB_ERRSTAT_BTSERR) /*! @brief Set the BTSERR field to a new value. */ #define BW_USB_ERRSTAT_BTSERR(x, v) (BITBAND_ACCESS8(HW_USB_ERRSTAT_ADDR(x), BP_USB_ERRSTAT_BTSERR) = (v)) /*@}*/ /******************************************************************************* * HW_USB_ERREN - Error Interrupt Enable register ******************************************************************************/ /*! * @brief HW_USB_ERREN - Error Interrupt Enable register (RW) * * Reset value: 0x00U * * Contains enable bits for each of the error interrupt sources within the USB * module. Setting any of these bits enables the respective interrupt source in * ERRSTAT. Each bit is set as soon as the error condition is detected. Therefore, * the interrupt does not typically correspond with the end of a token being * processed. This register contains the value of 0x00 after a reset. */ typedef union _hw_usb_erren { uint8_t U; struct _hw_usb_erren_bitfields { uint8_t PIDERREN : 1; /*!< [0] PIDERR Interrupt Enable */ uint8_t CRC5EOFEN : 1; /*!< [1] CRC5/EOF Interrupt Enable */ uint8_t CRC16EN : 1; /*!< [2] CRC16 Interrupt Enable */ uint8_t DFN8EN : 1; /*!< [3] DFN8 Interrupt Enable */ uint8_t BTOERREN : 1; /*!< [4] BTOERR Interrupt Enable */ uint8_t DMAERREN : 1; /*!< [5] DMAERR Interrupt Enable */ uint8_t RESERVED0 : 1; /*!< [6] */ uint8_t BTSERREN : 1; /*!< [7] BTSERR Interrupt Enable */ } B; } hw_usb_erren_t; /*! * @name Constants and macros for entire USB_ERREN register */ /*@{*/ #define HW_USB_ERREN_ADDR(x) ((x) + 0x8CU) #define HW_USB_ERREN(x) (*(__IO hw_usb_erren_t *) HW_USB_ERREN_ADDR(x)) #define HW_USB_ERREN_RD(x) (HW_USB_ERREN(x).U) #define HW_USB_ERREN_WR(x, v) (HW_USB_ERREN(x).U = (v)) #define HW_USB_ERREN_SET(x, v) (HW_USB_ERREN_WR(x, HW_USB_ERREN_RD(x) | (v))) #define HW_USB_ERREN_CLR(x, v) (HW_USB_ERREN_WR(x, HW_USB_ERREN_RD(x) & ~(v))) #define HW_USB_ERREN_TOG(x, v) (HW_USB_ERREN_WR(x, HW_USB_ERREN_RD(x) ^ (v))) /*@}*/ /* * Constants & macros for individual USB_ERREN bitfields */ /*! * @name Register USB_ERREN, field PIDERREN[0] (RW) * * Values: * - 0 - Disables the PIDERR interrupt. * - 1 - Enters the PIDERR interrupt. */ /*@{*/ #define BP_USB_ERREN_PIDERREN (0U) /*!< Bit position for USB_ERREN_PIDERREN. */ #define BM_USB_ERREN_PIDERREN (0x01U) /*!< Bit mask for USB_ERREN_PIDERREN. */ #define BS_USB_ERREN_PIDERREN (1U) /*!< Bit field size in bits for USB_ERREN_PIDERREN. */ /*! @brief Read current value of the USB_ERREN_PIDERREN field. */ #define BR_USB_ERREN_PIDERREN(x) (BITBAND_ACCESS8(HW_USB_ERREN_ADDR(x), BP_USB_ERREN_PIDERREN)) /*! @brief Format value for bitfield USB_ERREN_PIDERREN. */ #define BF_USB_ERREN_PIDERREN(v) ((uint8_t)((uint8_t)(v) << BP_USB_ERREN_PIDERREN) & BM_USB_ERREN_PIDERREN) /*! @brief Set the PIDERREN field to a new value. */ #define BW_USB_ERREN_PIDERREN(x, v) (BITBAND_ACCESS8(HW_USB_ERREN_ADDR(x), BP_USB_ERREN_PIDERREN) = (v)) /*@}*/ /*! * @name Register USB_ERREN, field CRC5EOFEN[1] (RW) * * Values: * - 0 - Disables the CRC5/EOF interrupt. * - 1 - Enables the CRC5/EOF interrupt. */ /*@{*/ #define BP_USB_ERREN_CRC5EOFEN (1U) /*!< Bit position for USB_ERREN_CRC5EOFEN. */ #define BM_USB_ERREN_CRC5EOFEN (0x02U) /*!< Bit mask for USB_ERREN_CRC5EOFEN. */ #define BS_USB_ERREN_CRC5EOFEN (1U) /*!< Bit field size in bits for USB_ERREN_CRC5EOFEN. */ /*! @brief Read current value of the USB_ERREN_CRC5EOFEN field. */ #define BR_USB_ERREN_CRC5EOFEN(x) (BITBAND_ACCESS8(HW_USB_ERREN_ADDR(x), BP_USB_ERREN_CRC5EOFEN)) /*! @brief Format value for bitfield USB_ERREN_CRC5EOFEN. */ #define BF_USB_ERREN_CRC5EOFEN(v) ((uint8_t)((uint8_t)(v) << BP_USB_ERREN_CRC5EOFEN) & BM_USB_ERREN_CRC5EOFEN) /*! @brief Set the CRC5EOFEN field to a new value. */ #define BW_USB_ERREN_CRC5EOFEN(x, v) (BITBAND_ACCESS8(HW_USB_ERREN_ADDR(x), BP_USB_ERREN_CRC5EOFEN) = (v)) /*@}*/ /*! * @name Register USB_ERREN, field CRC16EN[2] (RW) * * Values: * - 0 - Disables the CRC16 interrupt. * - 1 - Enables the CRC16 interrupt. */ /*@{*/ #define BP_USB_ERREN_CRC16EN (2U) /*!< Bit position for USB_ERREN_CRC16EN. */ #define BM_USB_ERREN_CRC16EN (0x04U) /*!< Bit mask for USB_ERREN_CRC16EN. */ #define BS_USB_ERREN_CRC16EN (1U) /*!< Bit field size in bits for USB_ERREN_CRC16EN. */ /*! @brief Read current value of the USB_ERREN_CRC16EN field. */ #define BR_USB_ERREN_CRC16EN(x) (BITBAND_ACCESS8(HW_USB_ERREN_ADDR(x), BP_USB_ERREN_CRC16EN)) /*! @brief Format value for bitfield USB_ERREN_CRC16EN. */ #define BF_USB_ERREN_CRC16EN(v) ((uint8_t)((uint8_t)(v) << BP_USB_ERREN_CRC16EN) & BM_USB_ERREN_CRC16EN) /*! @brief Set the CRC16EN field to a new value. */ #define BW_USB_ERREN_CRC16EN(x, v) (BITBAND_ACCESS8(HW_USB_ERREN_ADDR(x), BP_USB_ERREN_CRC16EN) = (v)) /*@}*/ /*! * @name Register USB_ERREN, field DFN8EN[3] (RW) * * Values: * - 0 - Disables the DFN8 interrupt. * - 1 - Enables the DFN8 interrupt. */ /*@{*/ #define BP_USB_ERREN_DFN8EN (3U) /*!< Bit position for USB_ERREN_DFN8EN. */ #define BM_USB_ERREN_DFN8EN (0x08U) /*!< Bit mask for USB_ERREN_DFN8EN. */ #define BS_USB_ERREN_DFN8EN (1U) /*!< Bit field size in bits for USB_ERREN_DFN8EN. */ /*! @brief Read current value of the USB_ERREN_DFN8EN field. */ #define BR_USB_ERREN_DFN8EN(x) (BITBAND_ACCESS8(HW_USB_ERREN_ADDR(x), BP_USB_ERREN_DFN8EN)) /*! @brief Format value for bitfield USB_ERREN_DFN8EN. */ #define BF_USB_ERREN_DFN8EN(v) ((uint8_t)((uint8_t)(v) << BP_USB_ERREN_DFN8EN) & BM_USB_ERREN_DFN8EN) /*! @brief Set the DFN8EN field to a new value. */ #define BW_USB_ERREN_DFN8EN(x, v) (BITBAND_ACCESS8(HW_USB_ERREN_ADDR(x), BP_USB_ERREN_DFN8EN) = (v)) /*@}*/ /*! * @name Register USB_ERREN, field BTOERREN[4] (RW) * * Values: * - 0 - Disables the BTOERR interrupt. * - 1 - Enables the BTOERR interrupt. */ /*@{*/ #define BP_USB_ERREN_BTOERREN (4U) /*!< Bit position for USB_ERREN_BTOERREN. */ #define BM_USB_ERREN_BTOERREN (0x10U) /*!< Bit mask for USB_ERREN_BTOERREN. */ #define BS_USB_ERREN_BTOERREN (1U) /*!< Bit field size in bits for USB_ERREN_BTOERREN. */ /*! @brief Read current value of the USB_ERREN_BTOERREN field. */ #define BR_USB_ERREN_BTOERREN(x) (BITBAND_ACCESS8(HW_USB_ERREN_ADDR(x), BP_USB_ERREN_BTOERREN)) /*! @brief Format value for bitfield USB_ERREN_BTOERREN. */ #define BF_USB_ERREN_BTOERREN(v) ((uint8_t)((uint8_t)(v) << BP_USB_ERREN_BTOERREN) & BM_USB_ERREN_BTOERREN) /*! @brief Set the BTOERREN field to a new value. */ #define BW_USB_ERREN_BTOERREN(x, v) (BITBAND_ACCESS8(HW_USB_ERREN_ADDR(x), BP_USB_ERREN_BTOERREN) = (v)) /*@}*/ /*! * @name Register USB_ERREN, field DMAERREN[5] (RW) * * Values: * - 0 - Disables the DMAERR interrupt. * - 1 - Enables the DMAERR interrupt. */ /*@{*/ #define BP_USB_ERREN_DMAERREN (5U) /*!< Bit position for USB_ERREN_DMAERREN. */ #define BM_USB_ERREN_DMAERREN (0x20U) /*!< Bit mask for USB_ERREN_DMAERREN. */ #define BS_USB_ERREN_DMAERREN (1U) /*!< Bit field size in bits for USB_ERREN_DMAERREN. */ /*! @brief Read current value of the USB_ERREN_DMAERREN field. */ #define BR_USB_ERREN_DMAERREN(x) (BITBAND_ACCESS8(HW_USB_ERREN_ADDR(x), BP_USB_ERREN_DMAERREN)) /*! @brief Format value for bitfield USB_ERREN_DMAERREN. */ #define BF_USB_ERREN_DMAERREN(v) ((uint8_t)((uint8_t)(v) << BP_USB_ERREN_DMAERREN) & BM_USB_ERREN_DMAERREN) /*! @brief Set the DMAERREN field to a new value. */ #define BW_USB_ERREN_DMAERREN(x, v) (BITBAND_ACCESS8(HW_USB_ERREN_ADDR(x), BP_USB_ERREN_DMAERREN) = (v)) /*@}*/ /*! * @name Register USB_ERREN, field BTSERREN[7] (RW) * * Values: * - 0 - Disables the BTSERR interrupt. * - 1 - Enables the BTSERR interrupt. */ /*@{*/ #define BP_USB_ERREN_BTSERREN (7U) /*!< Bit position for USB_ERREN_BTSERREN. */ #define BM_USB_ERREN_BTSERREN (0x80U) /*!< Bit mask for USB_ERREN_BTSERREN. */ #define BS_USB_ERREN_BTSERREN (1U) /*!< Bit field size in bits for USB_ERREN_BTSERREN. */ /*! @brief Read current value of the USB_ERREN_BTSERREN field. */ #define BR_USB_ERREN_BTSERREN(x) (BITBAND_ACCESS8(HW_USB_ERREN_ADDR(x), BP_USB_ERREN_BTSERREN)) /*! @brief Format value for bitfield USB_ERREN_BTSERREN. */ #define BF_USB_ERREN_BTSERREN(v) ((uint8_t)((uint8_t)(v) << BP_USB_ERREN_BTSERREN) & BM_USB_ERREN_BTSERREN) /*! @brief Set the BTSERREN field to a new value. */ #define BW_USB_ERREN_BTSERREN(x, v) (BITBAND_ACCESS8(HW_USB_ERREN_ADDR(x), BP_USB_ERREN_BTSERREN) = (v)) /*@}*/ /******************************************************************************* * HW_USB_STAT - Status register ******************************************************************************/ /*! * @brief HW_USB_STAT - Status register (RO) * * Reset value: 0x00U * * Reports the transaction status within the USB module. When the processor's * interrupt controller has received a TOKDNE, interrupt the Status Register must * be read to determine the status of the previous endpoint communication. The * data in the status register is valid when TOKDNE interrupt is asserted. The * Status register is actually a read window into a status FIFO maintained by the USB * module. When the USB module uses a BD, it updates the Status register. If * another USB transaction is performed before the TOKDNE interrupt is serviced, the * USB module stores the status of the next transaction in the STAT FIFO. Thus * STAT is actually a four byte FIFO that allows the processor core to process one * transaction while the SIE is processing the next transaction. Clearing the * TOKDNE bit in the ISTAT register causes the SIE to update STAT with the contents * of the next STAT value. If the data in the STAT holding register is valid, the * SIE immediately reasserts to TOKDNE interrupt. */ typedef union _hw_usb_stat { uint8_t U; struct _hw_usb_stat_bitfields { uint8_t RESERVED0 : 2; /*!< [1:0] */ uint8_t ODD : 1; /*!< [2] */ uint8_t TX : 1; /*!< [3] Transmit Indicator */ uint8_t ENDP : 4; /*!< [7:4] */ } B; } hw_usb_stat_t; /*! * @name Constants and macros for entire USB_STAT register */ /*@{*/ #define HW_USB_STAT_ADDR(x) ((x) + 0x90U) #define HW_USB_STAT(x) (*(__I hw_usb_stat_t *) HW_USB_STAT_ADDR(x)) #define HW_USB_STAT_RD(x) (HW_USB_STAT(x).U) /*@}*/ /* * Constants & macros for individual USB_STAT bitfields */ /*! * @name Register USB_STAT, field ODD[2] (RO) * * This bit is set if the last buffer descriptor updated was in the odd bank of * the BDT. */ /*@{*/ #define BP_USB_STAT_ODD (2U) /*!< Bit position for USB_STAT_ODD. */ #define BM_USB_STAT_ODD (0x04U) /*!< Bit mask for USB_STAT_ODD. */ #define BS_USB_STAT_ODD (1U) /*!< Bit field size in bits for USB_STAT_ODD. */ /*! @brief Read current value of the USB_STAT_ODD field. */ #define BR_USB_STAT_ODD(x) (BITBAND_ACCESS8(HW_USB_STAT_ADDR(x), BP_USB_STAT_ODD)) /*@}*/ /*! * @name Register USB_STAT, field TX[3] (RO) * * Values: * - 0 - The most recent transaction was a receive operation. * - 1 - The most recent transaction was a transmit operation. */ /*@{*/ #define BP_USB_STAT_TX (3U) /*!< Bit position for USB_STAT_TX. */ #define BM_USB_STAT_TX (0x08U) /*!< Bit mask for USB_STAT_TX. */ #define BS_USB_STAT_TX (1U) /*!< Bit field size in bits for USB_STAT_TX. */ /*! @brief Read current value of the USB_STAT_TX field. */ #define BR_USB_STAT_TX(x) (BITBAND_ACCESS8(HW_USB_STAT_ADDR(x), BP_USB_STAT_TX)) /*@}*/ /*! * @name Register USB_STAT, field ENDP[7:4] (RO) * * This four-bit field encodes the endpoint address that received or transmitted * the previous token. This allows the processor core to determine the BDT entry * that was updated by the last USB transaction. */ /*@{*/ #define BP_USB_STAT_ENDP (4U) /*!< Bit position for USB_STAT_ENDP. */ #define BM_USB_STAT_ENDP (0xF0U) /*!< Bit mask for USB_STAT_ENDP. */ #define BS_USB_STAT_ENDP (4U) /*!< Bit field size in bits for USB_STAT_ENDP. */ /*! @brief Read current value of the USB_STAT_ENDP field. */ #define BR_USB_STAT_ENDP(x) (HW_USB_STAT(x).B.ENDP) /*@}*/ /******************************************************************************* * HW_USB_CTL - Control register ******************************************************************************/ /*! * @brief HW_USB_CTL - Control register (RW) * * Reset value: 0x00U * * Provides various control and configuration information for the USB module. */ typedef union _hw_usb_ctl { uint8_t U; struct _hw_usb_ctl_bitfields { uint8_t USBENSOFEN : 1; /*!< [0] USB Enable */ uint8_t ODDRST : 1; /*!< [1] */ uint8_t RESUME : 1; /*!< [2] */ uint8_t HOSTMODEEN : 1; /*!< [3] */ uint8_t RESET : 1; /*!< [4] */ uint8_t TXSUSPENDTOKENBUSY : 1; /*!< [5] */ uint8_t SE0 : 1; /*!< [6] Live USB Single Ended Zero signal */ uint8_t JSTATE : 1; /*!< [7] Live USB differential receiver JSTATE * signal */ } B; } hw_usb_ctl_t; /*! * @name Constants and macros for entire USB_CTL register */ /*@{*/ #define HW_USB_CTL_ADDR(x) ((x) + 0x94U) #define HW_USB_CTL(x) (*(__IO hw_usb_ctl_t *) HW_USB_CTL_ADDR(x)) #define HW_USB_CTL_RD(x) (HW_USB_CTL(x).U) #define HW_USB_CTL_WR(x, v) (HW_USB_CTL(x).U = (v)) #define HW_USB_CTL_SET(x, v) (HW_USB_CTL_WR(x, HW_USB_CTL_RD(x) | (v))) #define HW_USB_CTL_CLR(x, v) (HW_USB_CTL_WR(x, HW_USB_CTL_RD(x) & ~(v))) #define HW_USB_CTL_TOG(x, v) (HW_USB_CTL_WR(x, HW_USB_CTL_RD(x) ^ (v))) /*@}*/ /* * Constants & macros for individual USB_CTL bitfields */ /*! * @name Register USB_CTL, field USBENSOFEN[0] (RW) * * Setting this bit enables the USB-FS to operate; clearing it disables the * USB-FS. Setting the bit causes the SIE to reset all of its ODD bits to the BDTs. * Therefore, setting this bit resets much of the logic in the SIE. When host mode * is enabled, clearing this bit causes the SIE to stop sending SOF tokens. * * Values: * - 0 - Disables the USB Module. * - 1 - Enables the USB Module. */ /*@{*/ #define BP_USB_CTL_USBENSOFEN (0U) /*!< Bit position for USB_CTL_USBENSOFEN. */ #define BM_USB_CTL_USBENSOFEN (0x01U) /*!< Bit mask for USB_CTL_USBENSOFEN. */ #define BS_USB_CTL_USBENSOFEN (1U) /*!< Bit field size in bits for USB_CTL_USBENSOFEN. */ /*! @brief Read current value of the USB_CTL_USBENSOFEN field. */ #define BR_USB_CTL_USBENSOFEN(x) (BITBAND_ACCESS8(HW_USB_CTL_ADDR(x), BP_USB_CTL_USBENSOFEN)) /*! @brief Format value for bitfield USB_CTL_USBENSOFEN. */ #define BF_USB_CTL_USBENSOFEN(v) ((uint8_t)((uint8_t)(v) << BP_USB_CTL_USBENSOFEN) & BM_USB_CTL_USBENSOFEN) /*! @brief Set the USBENSOFEN field to a new value. */ #define BW_USB_CTL_USBENSOFEN(x, v) (BITBAND_ACCESS8(HW_USB_CTL_ADDR(x), BP_USB_CTL_USBENSOFEN) = (v)) /*@}*/ /*! * @name Register USB_CTL, field ODDRST[1] (RW) * * Setting this bit to 1 resets all the BDT ODD ping/pong fields to 0, which * then specifies the EVEN BDT bank. */ /*@{*/ #define BP_USB_CTL_ODDRST (1U) /*!< Bit position for USB_CTL_ODDRST. */ #define BM_USB_CTL_ODDRST (0x02U) /*!< Bit mask for USB_CTL_ODDRST. */ #define BS_USB_CTL_ODDRST (1U) /*!< Bit field size in bits for USB_CTL_ODDRST. */ /*! @brief Read current value of the USB_CTL_ODDRST field. */ #define BR_USB_CTL_ODDRST(x) (BITBAND_ACCESS8(HW_USB_CTL_ADDR(x), BP_USB_CTL_ODDRST)) /*! @brief Format value for bitfield USB_CTL_ODDRST. */ #define BF_USB_CTL_ODDRST(v) ((uint8_t)((uint8_t)(v) << BP_USB_CTL_ODDRST) & BM_USB_CTL_ODDRST) /*! @brief Set the ODDRST field to a new value. */ #define BW_USB_CTL_ODDRST(x, v) (BITBAND_ACCESS8(HW_USB_CTL_ADDR(x), BP_USB_CTL_ODDRST) = (v)) /*@}*/ /*! * @name Register USB_CTL, field RESUME[2] (RW) * * When set to 1 this bit enables the USB Module to execute resume signaling. * This allows the USB Module to perform remote wake-up. Software must set RESUME * to 1 for the required amount of time and then clear it to 0. If the HOSTMODEEN * bit is set, the USB module appends a Low Speed End of Packet to the Resume * signaling when the RESUME bit is cleared. For more information on RESUME * signaling see Section 7.1.4.5 of the USB specification version 1.0. */ /*@{*/ #define BP_USB_CTL_RESUME (2U) /*!< Bit position for USB_CTL_RESUME. */ #define BM_USB_CTL_RESUME (0x04U) /*!< Bit mask for USB_CTL_RESUME. */ #define BS_USB_CTL_RESUME (1U) /*!< Bit field size in bits for USB_CTL_RESUME. */ /*! @brief Read current value of the USB_CTL_RESUME field. */ #define BR_USB_CTL_RESUME(x) (BITBAND_ACCESS8(HW_USB_CTL_ADDR(x), BP_USB_CTL_RESUME)) /*! @brief Format value for bitfield USB_CTL_RESUME. */ #define BF_USB_CTL_RESUME(v) ((uint8_t)((uint8_t)(v) << BP_USB_CTL_RESUME) & BM_USB_CTL_RESUME) /*! @brief Set the RESUME field to a new value. */ #define BW_USB_CTL_RESUME(x, v) (BITBAND_ACCESS8(HW_USB_CTL_ADDR(x), BP_USB_CTL_RESUME) = (v)) /*@}*/ /*! * @name Register USB_CTL, field HOSTMODEEN[3] (RW) * * When set to 1, this bit enables the USB Module to operate in Host mode. In * host mode, the USB module performs USB transactions under the programmed control * of the host processor. */ /*@{*/ #define BP_USB_CTL_HOSTMODEEN (3U) /*!< Bit position for USB_CTL_HOSTMODEEN. */ #define BM_USB_CTL_HOSTMODEEN (0x08U) /*!< Bit mask for USB_CTL_HOSTMODEEN. */ #define BS_USB_CTL_HOSTMODEEN (1U) /*!< Bit field size in bits for USB_CTL_HOSTMODEEN. */ /*! @brief Read current value of the USB_CTL_HOSTMODEEN field. */ #define BR_USB_CTL_HOSTMODEEN(x) (BITBAND_ACCESS8(HW_USB_CTL_ADDR(x), BP_USB_CTL_HOSTMODEEN)) /*! @brief Format value for bitfield USB_CTL_HOSTMODEEN. */ #define BF_USB_CTL_HOSTMODEEN(v) ((uint8_t)((uint8_t)(v) << BP_USB_CTL_HOSTMODEEN) & BM_USB_CTL_HOSTMODEEN) /*! @brief Set the HOSTMODEEN field to a new value. */ #define BW_USB_CTL_HOSTMODEEN(x, v) (BITBAND_ACCESS8(HW_USB_CTL_ADDR(x), BP_USB_CTL_HOSTMODEEN) = (v)) /*@}*/ /*! * @name Register USB_CTL, field RESET[4] (RW) * * Setting this bit enables the USB Module to generate USB reset signaling. This * allows the USB Module to reset USB peripherals. This control signal is only * valid in Host mode (HOSTMODEEN=1). Software must set RESET to 1 for the * required amount of time and then clear it to 0 to end reset signaling. For more * information on reset signaling see Section 7.1.4.3 of the USB specification version * 1.0. */ /*@{*/ #define BP_USB_CTL_RESET (4U) /*!< Bit position for USB_CTL_RESET. */ #define BM_USB_CTL_RESET (0x10U) /*!< Bit mask for USB_CTL_RESET. */ #define BS_USB_CTL_RESET (1U) /*!< Bit field size in bits for USB_CTL_RESET. */ /*! @brief Read current value of the USB_CTL_RESET field. */ #define BR_USB_CTL_RESET(x) (BITBAND_ACCESS8(HW_USB_CTL_ADDR(x), BP_USB_CTL_RESET)) /*! @brief Format value for bitfield USB_CTL_RESET. */ #define BF_USB_CTL_RESET(v) ((uint8_t)((uint8_t)(v) << BP_USB_CTL_RESET) & BM_USB_CTL_RESET) /*! @brief Set the RESET field to a new value. */ #define BW_USB_CTL_RESET(x, v) (BITBAND_ACCESS8(HW_USB_CTL_ADDR(x), BP_USB_CTL_RESET) = (v)) /*@}*/ /*! * @name Register USB_CTL, field TXSUSPENDTOKENBUSY[5] (RW) * * In Host mode, TOKEN_BUSY is set when the USB module is busy executing a USB * token. Software must not write more token commands to the Token Register when * TOKEN_BUSY is set. Software should check this field before writing any tokens * to the Token Register to ensure that token commands are not lost. In Target * mode, TXD_SUSPEND is set when the SIE has disabled packet transmission and * reception. Clearing this bit allows the SIE to continue token processing. This bit * is set by the SIE when a SETUP Token is received allowing software to dequeue * any pending packet transactions in the BDT before resuming token processing. */ /*@{*/ #define BP_USB_CTL_TXSUSPENDTOKENBUSY (5U) /*!< Bit position for USB_CTL_TXSUSPENDTOKENBUSY. */ #define BM_USB_CTL_TXSUSPENDTOKENBUSY (0x20U) /*!< Bit mask for USB_CTL_TXSUSPENDTOKENBUSY. */ #define BS_USB_CTL_TXSUSPENDTOKENBUSY (1U) /*!< Bit field size in bits for USB_CTL_TXSUSPENDTOKENBUSY. */ /*! @brief Read current value of the USB_CTL_TXSUSPENDTOKENBUSY field. */ #define BR_USB_CTL_TXSUSPENDTOKENBUSY(x) (BITBAND_ACCESS8(HW_USB_CTL_ADDR(x), BP_USB_CTL_TXSUSPENDTOKENBUSY)) /*! @brief Format value for bitfield USB_CTL_TXSUSPENDTOKENBUSY. */ #define BF_USB_CTL_TXSUSPENDTOKENBUSY(v) ((uint8_t)((uint8_t)(v) << BP_USB_CTL_TXSUSPENDTOKENBUSY) & BM_USB_CTL_TXSUSPENDTOKENBUSY) /*! @brief Set the TXSUSPENDTOKENBUSY field to a new value. */ #define BW_USB_CTL_TXSUSPENDTOKENBUSY(x, v) (BITBAND_ACCESS8(HW_USB_CTL_ADDR(x), BP_USB_CTL_TXSUSPENDTOKENBUSY) = (v)) /*@}*/ /*! * @name Register USB_CTL, field SE0[6] (RW) */ /*@{*/ #define BP_USB_CTL_SE0 (6U) /*!< Bit position for USB_CTL_SE0. */ #define BM_USB_CTL_SE0 (0x40U) /*!< Bit mask for USB_CTL_SE0. */ #define BS_USB_CTL_SE0 (1U) /*!< Bit field size in bits for USB_CTL_SE0. */ /*! @brief Read current value of the USB_CTL_SE0 field. */ #define BR_USB_CTL_SE0(x) (BITBAND_ACCESS8(HW_USB_CTL_ADDR(x), BP_USB_CTL_SE0)) /*! @brief Format value for bitfield USB_CTL_SE0. */ #define BF_USB_CTL_SE0(v) ((uint8_t)((uint8_t)(v) << BP_USB_CTL_SE0) & BM_USB_CTL_SE0) /*! @brief Set the SE0 field to a new value. */ #define BW_USB_CTL_SE0(x, v) (BITBAND_ACCESS8(HW_USB_CTL_ADDR(x), BP_USB_CTL_SE0) = (v)) /*@}*/ /*! * @name Register USB_CTL, field JSTATE[7] (RW) * * The polarity of this signal is affected by the current state of LSEN . */ /*@{*/ #define BP_USB_CTL_JSTATE (7U) /*!< Bit position for USB_CTL_JSTATE. */ #define BM_USB_CTL_JSTATE (0x80U) /*!< Bit mask for USB_CTL_JSTATE. */ #define BS_USB_CTL_JSTATE (1U) /*!< Bit field size in bits for USB_CTL_JSTATE. */ /*! @brief Read current value of the USB_CTL_JSTATE field. */ #define BR_USB_CTL_JSTATE(x) (BITBAND_ACCESS8(HW_USB_CTL_ADDR(x), BP_USB_CTL_JSTATE)) /*! @brief Format value for bitfield USB_CTL_JSTATE. */ #define BF_USB_CTL_JSTATE(v) ((uint8_t)((uint8_t)(v) << BP_USB_CTL_JSTATE) & BM_USB_CTL_JSTATE) /*! @brief Set the JSTATE field to a new value. */ #define BW_USB_CTL_JSTATE(x, v) (BITBAND_ACCESS8(HW_USB_CTL_ADDR(x), BP_USB_CTL_JSTATE) = (v)) /*@}*/ /******************************************************************************* * HW_USB_ADDR - Address register ******************************************************************************/ /*! * @brief HW_USB_ADDR - Address register (RW) * * Reset value: 0x00U * * Holds the unique USB address that the USB module decodes when in Peripheral * mode (HOSTMODEEN=0). When operating in Host mode (HOSTMODEEN=1) the USB module * transmits this address with a TOKEN packet. This enables the USB module to * uniquely address any USB peripheral. In either mode, CTL[USBENSOFEN] must be 1. * The Address register is reset to 0x00 after the reset input becomes active or * the USB module decodes a USB reset signal. This action initializes the Address * register to decode address 0x00 as required by the USB specification. */ typedef union _hw_usb_addr { uint8_t U; struct _hw_usb_addr_bitfields { uint8_t ADDR : 7; /*!< [6:0] USB Address */ uint8_t LSEN : 1; /*!< [7] Low Speed Enable bit */ } B; } hw_usb_addr_t; /*! * @name Constants and macros for entire USB_ADDR register */ /*@{*/ #define HW_USB_ADDR_ADDR(x) ((x) + 0x98U) #define HW_USB_ADDR(x) (*(__IO hw_usb_addr_t *) HW_USB_ADDR_ADDR(x)) #define HW_USB_ADDR_RD(x) (HW_USB_ADDR(x).U) #define HW_USB_ADDR_WR(x, v) (HW_USB_ADDR(x).U = (v)) #define HW_USB_ADDR_SET(x, v) (HW_USB_ADDR_WR(x, HW_USB_ADDR_RD(x) | (v))) #define HW_USB_ADDR_CLR(x, v) (HW_USB_ADDR_WR(x, HW_USB_ADDR_RD(x) & ~(v))) #define HW_USB_ADDR_TOG(x, v) (HW_USB_ADDR_WR(x, HW_USB_ADDR_RD(x) ^ (v))) /*@}*/ /* * Constants & macros for individual USB_ADDR bitfields */ /*! * @name Register USB_ADDR, field ADDR[6:0] (RW) * * Defines the USB address that the USB module decodes in peripheral mode, or * transmits when in host mode. */ /*@{*/ #define BP_USB_ADDR_ADDR (0U) /*!< Bit position for USB_ADDR_ADDR. */ #define BM_USB_ADDR_ADDR (0x7FU) /*!< Bit mask for USB_ADDR_ADDR. */ #define BS_USB_ADDR_ADDR (7U) /*!< Bit field size in bits for USB_ADDR_ADDR. */ /*! @brief Read current value of the USB_ADDR_ADDR field. */ #define BR_USB_ADDR_ADDR(x) (HW_USB_ADDR(x).B.ADDR) /*! @brief Format value for bitfield USB_ADDR_ADDR. */ #define BF_USB_ADDR_ADDR(v) ((uint8_t)((uint8_t)(v) << BP_USB_ADDR_ADDR) & BM_USB_ADDR_ADDR) /*! @brief Set the ADDR field to a new value. */ #define BW_USB_ADDR_ADDR(x, v) (HW_USB_ADDR_WR(x, (HW_USB_ADDR_RD(x) & ~BM_USB_ADDR_ADDR) | BF_USB_ADDR_ADDR(v))) /*@}*/ /*! * @name Register USB_ADDR, field LSEN[7] (RW) * * Informs the USB module that the next token command written to the token * register must be performed at low speed. This enables the USB module to perform the * necessary preamble required for low-speed data transmissions. */ /*@{*/ #define BP_USB_ADDR_LSEN (7U) /*!< Bit position for USB_ADDR_LSEN. */ #define BM_USB_ADDR_LSEN (0x80U) /*!< Bit mask for USB_ADDR_LSEN. */ #define BS_USB_ADDR_LSEN (1U) /*!< Bit field size in bits for USB_ADDR_LSEN. */ /*! @brief Read current value of the USB_ADDR_LSEN field. */ #define BR_USB_ADDR_LSEN(x) (BITBAND_ACCESS8(HW_USB_ADDR_ADDR(x), BP_USB_ADDR_LSEN)) /*! @brief Format value for bitfield USB_ADDR_LSEN. */ #define BF_USB_ADDR_LSEN(v) ((uint8_t)((uint8_t)(v) << BP_USB_ADDR_LSEN) & BM_USB_ADDR_LSEN) /*! @brief Set the LSEN field to a new value. */ #define BW_USB_ADDR_LSEN(x, v) (BITBAND_ACCESS8(HW_USB_ADDR_ADDR(x), BP_USB_ADDR_LSEN) = (v)) /*@}*/ /******************************************************************************* * HW_USB_BDTPAGE1 - BDT Page register 1 ******************************************************************************/ /*! * @brief HW_USB_BDTPAGE1 - BDT Page register 1 (RW) * * Reset value: 0x00U * * Provides address bits 15 through 9 of the base address where the current * Buffer Descriptor Table (BDT) resides in system memory. See Buffer Descriptor * Table. The 32-bit BDT Base Address is always aligned on 512-byte boundaries, so * bits 8 through 0 of the base address are always zero. */ typedef union _hw_usb_bdtpage1 { uint8_t U; struct _hw_usb_bdtpage1_bitfields { uint8_t RESERVED0 : 1; /*!< [0] */ uint8_t BDTBA : 7; /*!< [7:1] */ } B; } hw_usb_bdtpage1_t; /*! * @name Constants and macros for entire USB_BDTPAGE1 register */ /*@{*/ #define HW_USB_BDTPAGE1_ADDR(x) ((x) + 0x9CU) #define HW_USB_BDTPAGE1(x) (*(__IO hw_usb_bdtpage1_t *) HW_USB_BDTPAGE1_ADDR(x)) #define HW_USB_BDTPAGE1_RD(x) (HW_USB_BDTPAGE1(x).U) #define HW_USB_BDTPAGE1_WR(x, v) (HW_USB_BDTPAGE1(x).U = (v)) #define HW_USB_BDTPAGE1_SET(x, v) (HW_USB_BDTPAGE1_WR(x, HW_USB_BDTPAGE1_RD(x) | (v))) #define HW_USB_BDTPAGE1_CLR(x, v) (HW_USB_BDTPAGE1_WR(x, HW_USB_BDTPAGE1_RD(x) & ~(v))) #define HW_USB_BDTPAGE1_TOG(x, v) (HW_USB_BDTPAGE1_WR(x, HW_USB_BDTPAGE1_RD(x) ^ (v))) /*@}*/ /* * Constants & macros for individual USB_BDTPAGE1 bitfields */ /*! * @name Register USB_BDTPAGE1, field BDTBA[7:1] (RW) * * Provides address bits 15 through 9 of the BDT base address. */ /*@{*/ #define BP_USB_BDTPAGE1_BDTBA (1U) /*!< Bit position for USB_BDTPAGE1_BDTBA. */ #define BM_USB_BDTPAGE1_BDTBA (0xFEU) /*!< Bit mask for USB_BDTPAGE1_BDTBA. */ #define BS_USB_BDTPAGE1_BDTBA (7U) /*!< Bit field size in bits for USB_BDTPAGE1_BDTBA. */ /*! @brief Read current value of the USB_BDTPAGE1_BDTBA field. */ #define BR_USB_BDTPAGE1_BDTBA(x) (HW_USB_BDTPAGE1(x).B.BDTBA) /*! @brief Format value for bitfield USB_BDTPAGE1_BDTBA. */ #define BF_USB_BDTPAGE1_BDTBA(v) ((uint8_t)((uint8_t)(v) << BP_USB_BDTPAGE1_BDTBA) & BM_USB_BDTPAGE1_BDTBA) /*! @brief Set the BDTBA field to a new value. */ #define BW_USB_BDTPAGE1_BDTBA(x, v) (HW_USB_BDTPAGE1_WR(x, (HW_USB_BDTPAGE1_RD(x) & ~BM_USB_BDTPAGE1_BDTBA) | BF_USB_BDTPAGE1_BDTBA(v))) /*@}*/ /******************************************************************************* * HW_USB_FRMNUML - Frame Number register Low ******************************************************************************/ /*! * @brief HW_USB_FRMNUML - Frame Number register Low (RW) * * Reset value: 0x00U * * The Frame Number registers (low and high) contain the 11-bit frame number. * These registers are updated with the current frame number whenever a SOF TOKEN * is received. */ typedef union _hw_usb_frmnuml { uint8_t U; struct _hw_usb_frmnuml_bitfields { uint8_t FRM : 8; /*!< [7:0] */ } B; } hw_usb_frmnuml_t; /*! * @name Constants and macros for entire USB_FRMNUML register */ /*@{*/ #define HW_USB_FRMNUML_ADDR(x) ((x) + 0xA0U) #define HW_USB_FRMNUML(x) (*(__IO hw_usb_frmnuml_t *) HW_USB_FRMNUML_ADDR(x)) #define HW_USB_FRMNUML_RD(x) (HW_USB_FRMNUML(x).U) #define HW_USB_FRMNUML_WR(x, v) (HW_USB_FRMNUML(x).U = (v)) #define HW_USB_FRMNUML_SET(x, v) (HW_USB_FRMNUML_WR(x, HW_USB_FRMNUML_RD(x) | (v))) #define HW_USB_FRMNUML_CLR(x, v) (HW_USB_FRMNUML_WR(x, HW_USB_FRMNUML_RD(x) & ~(v))) #define HW_USB_FRMNUML_TOG(x, v) (HW_USB_FRMNUML_WR(x, HW_USB_FRMNUML_RD(x) ^ (v))) /*@}*/ /* * Constants & macros for individual USB_FRMNUML bitfields */ /*! * @name Register USB_FRMNUML, field FRM[7:0] (RW) * * This 8-bit field and the 3-bit field in the Frame Number Register High are * used to compute the address where the current Buffer Descriptor Table (BDT) * resides in system memory. */ /*@{*/ #define BP_USB_FRMNUML_FRM (0U) /*!< Bit position for USB_FRMNUML_FRM. */ #define BM_USB_FRMNUML_FRM (0xFFU) /*!< Bit mask for USB_FRMNUML_FRM. */ #define BS_USB_FRMNUML_FRM (8U) /*!< Bit field size in bits for USB_FRMNUML_FRM. */ /*! @brief Read current value of the USB_FRMNUML_FRM field. */ #define BR_USB_FRMNUML_FRM(x) (HW_USB_FRMNUML(x).U) /*! @brief Format value for bitfield USB_FRMNUML_FRM. */ #define BF_USB_FRMNUML_FRM(v) ((uint8_t)((uint8_t)(v) << BP_USB_FRMNUML_FRM) & BM_USB_FRMNUML_FRM) /*! @brief Set the FRM field to a new value. */ #define BW_USB_FRMNUML_FRM(x, v) (HW_USB_FRMNUML_WR(x, v)) /*@}*/ /******************************************************************************* * HW_USB_FRMNUMH - Frame Number register High ******************************************************************************/ /*! * @brief HW_USB_FRMNUMH - Frame Number register High (RW) * * Reset value: 0x00U * * The Frame Number registers (low and high) contain the 11-bit frame number. * These registers are updated with the current frame number whenever a SOF TOKEN * is received. */ typedef union _hw_usb_frmnumh { uint8_t U; struct _hw_usb_frmnumh_bitfields { uint8_t FRM : 3; /*!< [2:0] */ uint8_t RESERVED0 : 5; /*!< [7:3] */ } B; } hw_usb_frmnumh_t; /*! * @name Constants and macros for entire USB_FRMNUMH register */ /*@{*/ #define HW_USB_FRMNUMH_ADDR(x) ((x) + 0xA4U) #define HW_USB_FRMNUMH(x) (*(__IO hw_usb_frmnumh_t *) HW_USB_FRMNUMH_ADDR(x)) #define HW_USB_FRMNUMH_RD(x) (HW_USB_FRMNUMH(x).U) #define HW_USB_FRMNUMH_WR(x, v) (HW_USB_FRMNUMH(x).U = (v)) #define HW_USB_FRMNUMH_SET(x, v) (HW_USB_FRMNUMH_WR(x, HW_USB_FRMNUMH_RD(x) | (v))) #define HW_USB_FRMNUMH_CLR(x, v) (HW_USB_FRMNUMH_WR(x, HW_USB_FRMNUMH_RD(x) & ~(v))) #define HW_USB_FRMNUMH_TOG(x, v) (HW_USB_FRMNUMH_WR(x, HW_USB_FRMNUMH_RD(x) ^ (v))) /*@}*/ /* * Constants & macros for individual USB_FRMNUMH bitfields */ /*! * @name Register USB_FRMNUMH, field FRM[2:0] (RW) * * This 3-bit field and the 8-bit field in the Frame Number Register Low are * used to compute the address where the current Buffer Descriptor Table (BDT) * resides in system memory. */ /*@{*/ #define BP_USB_FRMNUMH_FRM (0U) /*!< Bit position for USB_FRMNUMH_FRM. */ #define BM_USB_FRMNUMH_FRM (0x07U) /*!< Bit mask for USB_FRMNUMH_FRM. */ #define BS_USB_FRMNUMH_FRM (3U) /*!< Bit field size in bits for USB_FRMNUMH_FRM. */ /*! @brief Read current value of the USB_FRMNUMH_FRM field. */ #define BR_USB_FRMNUMH_FRM(x) (HW_USB_FRMNUMH(x).B.FRM) /*! @brief Format value for bitfield USB_FRMNUMH_FRM. */ #define BF_USB_FRMNUMH_FRM(v) ((uint8_t)((uint8_t)(v) << BP_USB_FRMNUMH_FRM) & BM_USB_FRMNUMH_FRM) /*! @brief Set the FRM field to a new value. */ #define BW_USB_FRMNUMH_FRM(x, v) (HW_USB_FRMNUMH_WR(x, (HW_USB_FRMNUMH_RD(x) & ~BM_USB_FRMNUMH_FRM) | BF_USB_FRMNUMH_FRM(v))) /*@}*/ /******************************************************************************* * HW_USB_TOKEN - Token register ******************************************************************************/ /*! * @brief HW_USB_TOKEN - Token register (RW) * * Reset value: 0x00U * * Used to initiate USB transactions when in host mode (HOSTMODEEN=1). When the * software needs to execute a USB transaction to a peripheral, it writes the * TOKEN type and endpoint to this register. After this register has been written, * the USB module begins the specified USB transaction to the address contained in * the address register. The processor core must always check that the * TOKEN_BUSY bit in the control register is not 1 before writing to the Token Register. * This ensures that the token commands are not overwritten before they can be * executed. The address register and endpoint control register 0 are also used when * performing a token command and therefore must also be written before the * Token Register. The address register is used to select the USB peripheral address * transmitted by the token command. The endpoint control register determines the * handshake and retry policies used during the transfer. */ typedef union _hw_usb_token { uint8_t U; struct _hw_usb_token_bitfields { uint8_t TOKENENDPT : 4; /*!< [3:0] */ uint8_t TOKENPID : 4; /*!< [7:4] */ } B; } hw_usb_token_t; /*! * @name Constants and macros for entire USB_TOKEN register */ /*@{*/ #define HW_USB_TOKEN_ADDR(x) ((x) + 0xA8U) #define HW_USB_TOKEN(x) (*(__IO hw_usb_token_t *) HW_USB_TOKEN_ADDR(x)) #define HW_USB_TOKEN_RD(x) (HW_USB_TOKEN(x).U) #define HW_USB_TOKEN_WR(x, v) (HW_USB_TOKEN(x).U = (v)) #define HW_USB_TOKEN_SET(x, v) (HW_USB_TOKEN_WR(x, HW_USB_TOKEN_RD(x) | (v))) #define HW_USB_TOKEN_CLR(x, v) (HW_USB_TOKEN_WR(x, HW_USB_TOKEN_RD(x) & ~(v))) #define HW_USB_TOKEN_TOG(x, v) (HW_USB_TOKEN_WR(x, HW_USB_TOKEN_RD(x) ^ (v))) /*@}*/ /* * Constants & macros for individual USB_TOKEN bitfields */ /*! * @name Register USB_TOKEN, field TOKENENDPT[3:0] (RW) * * Holds the Endpoint address for the token command. The four bit value written * must be a valid endpoint. */ /*@{*/ #define BP_USB_TOKEN_TOKENENDPT (0U) /*!< Bit position for USB_TOKEN_TOKENENDPT. */ #define BM_USB_TOKEN_TOKENENDPT (0x0FU) /*!< Bit mask for USB_TOKEN_TOKENENDPT. */ #define BS_USB_TOKEN_TOKENENDPT (4U) /*!< Bit field size in bits for USB_TOKEN_TOKENENDPT. */ /*! @brief Read current value of the USB_TOKEN_TOKENENDPT field. */ #define BR_USB_TOKEN_TOKENENDPT(x) (HW_USB_TOKEN(x).B.TOKENENDPT) /*! @brief Format value for bitfield USB_TOKEN_TOKENENDPT. */ #define BF_USB_TOKEN_TOKENENDPT(v) ((uint8_t)((uint8_t)(v) << BP_USB_TOKEN_TOKENENDPT) & BM_USB_TOKEN_TOKENENDPT) /*! @brief Set the TOKENENDPT field to a new value. */ #define BW_USB_TOKEN_TOKENENDPT(x, v) (HW_USB_TOKEN_WR(x, (HW_USB_TOKEN_RD(x) & ~BM_USB_TOKEN_TOKENENDPT) | BF_USB_TOKEN_TOKENENDPT(v))) /*@}*/ /*! * @name Register USB_TOKEN, field TOKENPID[7:4] (RW) * * Contains the token type executed by the USB module. * * Values: * - 0001 - OUT Token. USB Module performs an OUT (TX) transaction. * - 1001 - IN Token. USB Module performs an In (RX) transaction. * - 1101 - SETUP Token. USB Module performs a SETUP (TX) transaction */ /*@{*/ #define BP_USB_TOKEN_TOKENPID (4U) /*!< Bit position for USB_TOKEN_TOKENPID. */ #define BM_USB_TOKEN_TOKENPID (0xF0U) /*!< Bit mask for USB_TOKEN_TOKENPID. */ #define BS_USB_TOKEN_TOKENPID (4U) /*!< Bit field size in bits for USB_TOKEN_TOKENPID. */ /*! @brief Read current value of the USB_TOKEN_TOKENPID field. */ #define BR_USB_TOKEN_TOKENPID(x) (HW_USB_TOKEN(x).B.TOKENPID) /*! @brief Format value for bitfield USB_TOKEN_TOKENPID. */ #define BF_USB_TOKEN_TOKENPID(v) ((uint8_t)((uint8_t)(v) << BP_USB_TOKEN_TOKENPID) & BM_USB_TOKEN_TOKENPID) /*! @brief Set the TOKENPID field to a new value. */ #define BW_USB_TOKEN_TOKENPID(x, v) (HW_USB_TOKEN_WR(x, (HW_USB_TOKEN_RD(x) & ~BM_USB_TOKEN_TOKENPID) | BF_USB_TOKEN_TOKENPID(v))) /*@}*/ /******************************************************************************* * HW_USB_SOFTHLD - SOF Threshold register ******************************************************************************/ /*! * @brief HW_USB_SOFTHLD - SOF Threshold register (RW) * * Reset value: 0x00U * * The SOF Threshold Register is used only in Host mode (HOSTMODEEN=1). When in * Host mode, the 14-bit SOF counter counts the interval between SOF frames. The * SOF must be transmitted every 1ms so therefore the SOF counter is loaded with * a value of 12000. When the SOF counter reaches zero, a Start Of Frame (SOF) * token is transmitted. The SOF threshold register is used to program the number * of USB byte times before the SOF to stop initiating token packet transactions. * This register must be set to a value that ensures that other packets are not * actively being transmitted when the SOF time counts to zero. When the SOF * counter reaches the threshold value, no more tokens are transmitted until after the * SOF has been transmitted. The value programmed into the threshold register * must reserve enough time to ensure the worst case transaction completes. In * general the worst case transaction is an IN token followed by a data packet from * the target followed by the response from the host. The actual time required is * a function of the maximum packet size on the bus. Typical values for the SOF * threshold are: 64-byte packets=74; 32-byte packets=42; 16-byte packets=26; * 8-byte packets=18. */ typedef union _hw_usb_softhld { uint8_t U; struct _hw_usb_softhld_bitfields { uint8_t CNT : 8; /*!< [7:0] */ } B; } hw_usb_softhld_t; /*! * @name Constants and macros for entire USB_SOFTHLD register */ /*@{*/ #define HW_USB_SOFTHLD_ADDR(x) ((x) + 0xACU) #define HW_USB_SOFTHLD(x) (*(__IO hw_usb_softhld_t *) HW_USB_SOFTHLD_ADDR(x)) #define HW_USB_SOFTHLD_RD(x) (HW_USB_SOFTHLD(x).U) #define HW_USB_SOFTHLD_WR(x, v) (HW_USB_SOFTHLD(x).U = (v)) #define HW_USB_SOFTHLD_SET(x, v) (HW_USB_SOFTHLD_WR(x, HW_USB_SOFTHLD_RD(x) | (v))) #define HW_USB_SOFTHLD_CLR(x, v) (HW_USB_SOFTHLD_WR(x, HW_USB_SOFTHLD_RD(x) & ~(v))) #define HW_USB_SOFTHLD_TOG(x, v) (HW_USB_SOFTHLD_WR(x, HW_USB_SOFTHLD_RD(x) ^ (v))) /*@}*/ /* * Constants & macros for individual USB_SOFTHLD bitfields */ /*! * @name Register USB_SOFTHLD, field CNT[7:0] (RW) * * Represents the SOF count threshold in byte times. */ /*@{*/ #define BP_USB_SOFTHLD_CNT (0U) /*!< Bit position for USB_SOFTHLD_CNT. */ #define BM_USB_SOFTHLD_CNT (0xFFU) /*!< Bit mask for USB_SOFTHLD_CNT. */ #define BS_USB_SOFTHLD_CNT (8U) /*!< Bit field size in bits for USB_SOFTHLD_CNT. */ /*! @brief Read current value of the USB_SOFTHLD_CNT field. */ #define BR_USB_SOFTHLD_CNT(x) (HW_USB_SOFTHLD(x).U) /*! @brief Format value for bitfield USB_SOFTHLD_CNT. */ #define BF_USB_SOFTHLD_CNT(v) ((uint8_t)((uint8_t)(v) << BP_USB_SOFTHLD_CNT) & BM_USB_SOFTHLD_CNT) /*! @brief Set the CNT field to a new value. */ #define BW_USB_SOFTHLD_CNT(x, v) (HW_USB_SOFTHLD_WR(x, v)) /*@}*/ /******************************************************************************* * HW_USB_BDTPAGE2 - BDT Page Register 2 ******************************************************************************/ /*! * @brief HW_USB_BDTPAGE2 - BDT Page Register 2 (RW) * * Reset value: 0x00U * * Contains an 8-bit value used to compute the address where the current Buffer * Descriptor Table (BDT) resides in system memory. See Buffer Descriptor Table. */ typedef union _hw_usb_bdtpage2 { uint8_t U; struct _hw_usb_bdtpage2_bitfields { uint8_t BDTBA : 8; /*!< [7:0] */ } B; } hw_usb_bdtpage2_t; /*! * @name Constants and macros for entire USB_BDTPAGE2 register */ /*@{*/ #define HW_USB_BDTPAGE2_ADDR(x) ((x) + 0xB0U) #define HW_USB_BDTPAGE2(x) (*(__IO hw_usb_bdtpage2_t *) HW_USB_BDTPAGE2_ADDR(x)) #define HW_USB_BDTPAGE2_RD(x) (HW_USB_BDTPAGE2(x).U) #define HW_USB_BDTPAGE2_WR(x, v) (HW_USB_BDTPAGE2(x).U = (v)) #define HW_USB_BDTPAGE2_SET(x, v) (HW_USB_BDTPAGE2_WR(x, HW_USB_BDTPAGE2_RD(x) | (v))) #define HW_USB_BDTPAGE2_CLR(x, v) (HW_USB_BDTPAGE2_WR(x, HW_USB_BDTPAGE2_RD(x) & ~(v))) #define HW_USB_BDTPAGE2_TOG(x, v) (HW_USB_BDTPAGE2_WR(x, HW_USB_BDTPAGE2_RD(x) ^ (v))) /*@}*/ /* * Constants & macros for individual USB_BDTPAGE2 bitfields */ /*! * @name Register USB_BDTPAGE2, field BDTBA[7:0] (RW) * * Provides address bits 23 through 16 of the BDT base address that defines the * location of Buffer Descriptor Table resides in system memory. */ /*@{*/ #define BP_USB_BDTPAGE2_BDTBA (0U) /*!< Bit position for USB_BDTPAGE2_BDTBA. */ #define BM_USB_BDTPAGE2_BDTBA (0xFFU) /*!< Bit mask for USB_BDTPAGE2_BDTBA. */ #define BS_USB_BDTPAGE2_BDTBA (8U) /*!< Bit field size in bits for USB_BDTPAGE2_BDTBA. */ /*! @brief Read current value of the USB_BDTPAGE2_BDTBA field. */ #define BR_USB_BDTPAGE2_BDTBA(x) (HW_USB_BDTPAGE2(x).U) /*! @brief Format value for bitfield USB_BDTPAGE2_BDTBA. */ #define BF_USB_BDTPAGE2_BDTBA(v) ((uint8_t)((uint8_t)(v) << BP_USB_BDTPAGE2_BDTBA) & BM_USB_BDTPAGE2_BDTBA) /*! @brief Set the BDTBA field to a new value. */ #define BW_USB_BDTPAGE2_BDTBA(x, v) (HW_USB_BDTPAGE2_WR(x, v)) /*@}*/ /******************************************************************************* * HW_USB_BDTPAGE3 - BDT Page Register 3 ******************************************************************************/ /*! * @brief HW_USB_BDTPAGE3 - BDT Page Register 3 (RW) * * Reset value: 0x00U * * Contains an 8-bit value used to compute the address where the current Buffer * Descriptor Table (BDT) resides in system memory. See Buffer Descriptor Table. */ typedef union _hw_usb_bdtpage3 { uint8_t U; struct _hw_usb_bdtpage3_bitfields { uint8_t BDTBA : 8; /*!< [7:0] */ } B; } hw_usb_bdtpage3_t; /*! * @name Constants and macros for entire USB_BDTPAGE3 register */ /*@{*/ #define HW_USB_BDTPAGE3_ADDR(x) ((x) + 0xB4U) #define HW_USB_BDTPAGE3(x) (*(__IO hw_usb_bdtpage3_t *) HW_USB_BDTPAGE3_ADDR(x)) #define HW_USB_BDTPAGE3_RD(x) (HW_USB_BDTPAGE3(x).U) #define HW_USB_BDTPAGE3_WR(x, v) (HW_USB_BDTPAGE3(x).U = (v)) #define HW_USB_BDTPAGE3_SET(x, v) (HW_USB_BDTPAGE3_WR(x, HW_USB_BDTPAGE3_RD(x) | (v))) #define HW_USB_BDTPAGE3_CLR(x, v) (HW_USB_BDTPAGE3_WR(x, HW_USB_BDTPAGE3_RD(x) & ~(v))) #define HW_USB_BDTPAGE3_TOG(x, v) (HW_USB_BDTPAGE3_WR(x, HW_USB_BDTPAGE3_RD(x) ^ (v))) /*@}*/ /* * Constants & macros for individual USB_BDTPAGE3 bitfields */ /*! * @name Register USB_BDTPAGE3, field BDTBA[7:0] (RW) * * Provides address bits 31 through 24 of the BDT base address that defines the * location of Buffer Descriptor Table resides in system memory. */ /*@{*/ #define BP_USB_BDTPAGE3_BDTBA (0U) /*!< Bit position for USB_BDTPAGE3_BDTBA. */ #define BM_USB_BDTPAGE3_BDTBA (0xFFU) /*!< Bit mask for USB_BDTPAGE3_BDTBA. */ #define BS_USB_BDTPAGE3_BDTBA (8U) /*!< Bit field size in bits for USB_BDTPAGE3_BDTBA. */ /*! @brief Read current value of the USB_BDTPAGE3_BDTBA field. */ #define BR_USB_BDTPAGE3_BDTBA(x) (HW_USB_BDTPAGE3(x).U) /*! @brief Format value for bitfield USB_BDTPAGE3_BDTBA. */ #define BF_USB_BDTPAGE3_BDTBA(v) ((uint8_t)((uint8_t)(v) << BP_USB_BDTPAGE3_BDTBA) & BM_USB_BDTPAGE3_BDTBA) /*! @brief Set the BDTBA field to a new value. */ #define BW_USB_BDTPAGE3_BDTBA(x, v) (HW_USB_BDTPAGE3_WR(x, v)) /*@}*/ /******************************************************************************* * HW_USB_ENDPTn - Endpoint Control register ******************************************************************************/ /*! * @brief HW_USB_ENDPTn - Endpoint Control register (RW) * * Reset value: 0x00U * * Contains the endpoint control bits for each of the 16 endpoints available * within the USB module for a decoded address. The format for these registers is * shown in the following figure. Endpoint 0 (ENDPT0) is associated with control * pipe 0, which is required for all USB functions. Therefore, after a USBRST * interrupt occurs the processor core should set ENDPT0 to contain 0x0D. In Host mode * ENDPT0 is used to determine the handshake, retry and low speed * characteristics of the host transfer. For Control, Bulk and Interrupt transfers, the EPHSHK * bit should be 1. For Isochronous transfers it should be 0. Common values to * use for ENDPT0 in host mode are 0x4D for Control, Bulk, and Interrupt transfers, * and 0x4C for Isochronous transfers. The three bits EPCTLDIS, EPRXEN, and * EPTXEN define if an endpoint is enabled and define the direction of the endpoint. * The endpoint enable/direction control is defined in the following table. * Endpoint enable and direction control EPCTLDIS EPRXEN EPTXEN Endpoint * enable/direction control X 0 0 Disable endpoint X 0 1 Enable endpoint for Tx transfers only * X 1 0 Enable endpoint for Rx transfers only 1 1 1 Enable endpoint for Rx and * Tx transfers 0 1 1 Enable Endpoint for RX and TX as well as control (SETUP) * transfers. */ typedef union _hw_usb_endptn { uint8_t U; struct _hw_usb_endptn_bitfields { uint8_t EPHSHK : 1; /*!< [0] */ uint8_t EPSTALL : 1; /*!< [1] */ uint8_t EPTXEN : 1; /*!< [2] */ uint8_t EPRXEN : 1; /*!< [3] */ uint8_t EPCTLDIS : 1; /*!< [4] */ uint8_t RESERVED0 : 1; /*!< [5] */ uint8_t RETRYDIS : 1; /*!< [6] */ uint8_t HOSTWOHUB : 1; /*!< [7] */ } B; } hw_usb_endptn_t; /*! * @name Constants and macros for entire USB_ENDPTn register */ /*@{*/ #define HW_USB_ENDPTn_COUNT (16U) #define HW_USB_ENDPTn_ADDR(x, n) ((x) + 0xC0U + (0x4U * (n))) #define HW_USB_ENDPTn(x, n) (*(__IO hw_usb_endptn_t *) HW_USB_ENDPTn_ADDR(x, n)) #define HW_USB_ENDPTn_RD(x, n) (HW_USB_ENDPTn(x, n).U) #define HW_USB_ENDPTn_WR(x, n, v) (HW_USB_ENDPTn(x, n).U = (v)) #define HW_USB_ENDPTn_SET(x, n, v) (HW_USB_ENDPTn_WR(x, n, HW_USB_ENDPTn_RD(x, n) | (v))) #define HW_USB_ENDPTn_CLR(x, n, v) (HW_USB_ENDPTn_WR(x, n, HW_USB_ENDPTn_RD(x, n) & ~(v))) #define HW_USB_ENDPTn_TOG(x, n, v) (HW_USB_ENDPTn_WR(x, n, HW_USB_ENDPTn_RD(x, n) ^ (v))) /*@}*/ /* * Constants & macros for individual USB_ENDPTn bitfields */ /*! * @name Register USB_ENDPTn, field EPHSHK[0] (RW) * * When set this bit enables an endpoint to perform handshaking during a * transaction to this endpoint. This bit is generally 1 unless the endpoint is * Isochronous. */ /*@{*/ #define BP_USB_ENDPTn_EPHSHK (0U) /*!< Bit position for USB_ENDPTn_EPHSHK. */ #define BM_USB_ENDPTn_EPHSHK (0x01U) /*!< Bit mask for USB_ENDPTn_EPHSHK. */ #define BS_USB_ENDPTn_EPHSHK (1U) /*!< Bit field size in bits for USB_ENDPTn_EPHSHK. */ /*! @brief Read current value of the USB_ENDPTn_EPHSHK field. */ #define BR_USB_ENDPTn_EPHSHK(x, n) (BITBAND_ACCESS8(HW_USB_ENDPTn_ADDR(x, n), BP_USB_ENDPTn_EPHSHK)) /*! @brief Format value for bitfield USB_ENDPTn_EPHSHK. */ #define BF_USB_ENDPTn_EPHSHK(v) ((uint8_t)((uint8_t)(v) << BP_USB_ENDPTn_EPHSHK) & BM_USB_ENDPTn_EPHSHK) /*! @brief Set the EPHSHK field to a new value. */ #define BW_USB_ENDPTn_EPHSHK(x, n, v) (BITBAND_ACCESS8(HW_USB_ENDPTn_ADDR(x, n), BP_USB_ENDPTn_EPHSHK) = (v)) /*@}*/ /*! * @name Register USB_ENDPTn, field EPSTALL[1] (RW) * * When set this bit indicates that the endpoint is called. This bit has * priority over all other control bits in the EndPoint Enable Register, but it is only * valid if EPTXEN=1 or EPRXEN=1. Any access to this endpoint causes the USB * Module to return a STALL handshake. After an endpoint is stalled it requires * intervention from the Host Controller. */ /*@{*/ #define BP_USB_ENDPTn_EPSTALL (1U) /*!< Bit position for USB_ENDPTn_EPSTALL. */ #define BM_USB_ENDPTn_EPSTALL (0x02U) /*!< Bit mask for USB_ENDPTn_EPSTALL. */ #define BS_USB_ENDPTn_EPSTALL (1U) /*!< Bit field size in bits for USB_ENDPTn_EPSTALL. */ /*! @brief Read current value of the USB_ENDPTn_EPSTALL field. */ #define BR_USB_ENDPTn_EPSTALL(x, n) (BITBAND_ACCESS8(HW_USB_ENDPTn_ADDR(x, n), BP_USB_ENDPTn_EPSTALL)) /*! @brief Format value for bitfield USB_ENDPTn_EPSTALL. */ #define BF_USB_ENDPTn_EPSTALL(v) ((uint8_t)((uint8_t)(v) << BP_USB_ENDPTn_EPSTALL) & BM_USB_ENDPTn_EPSTALL) /*! @brief Set the EPSTALL field to a new value. */ #define BW_USB_ENDPTn_EPSTALL(x, n, v) (BITBAND_ACCESS8(HW_USB_ENDPTn_ADDR(x, n), BP_USB_ENDPTn_EPSTALL) = (v)) /*@}*/ /*! * @name Register USB_ENDPTn, field EPTXEN[2] (RW) * * This bit, when set, enables the endpoint for TX transfers. */ /*@{*/ #define BP_USB_ENDPTn_EPTXEN (2U) /*!< Bit position for USB_ENDPTn_EPTXEN. */ #define BM_USB_ENDPTn_EPTXEN (0x04U) /*!< Bit mask for USB_ENDPTn_EPTXEN. */ #define BS_USB_ENDPTn_EPTXEN (1U) /*!< Bit field size in bits for USB_ENDPTn_EPTXEN. */ /*! @brief Read current value of the USB_ENDPTn_EPTXEN field. */ #define BR_USB_ENDPTn_EPTXEN(x, n) (BITBAND_ACCESS8(HW_USB_ENDPTn_ADDR(x, n), BP_USB_ENDPTn_EPTXEN)) /*! @brief Format value for bitfield USB_ENDPTn_EPTXEN. */ #define BF_USB_ENDPTn_EPTXEN(v) ((uint8_t)((uint8_t)(v) << BP_USB_ENDPTn_EPTXEN) & BM_USB_ENDPTn_EPTXEN) /*! @brief Set the EPTXEN field to a new value. */ #define BW_USB_ENDPTn_EPTXEN(x, n, v) (BITBAND_ACCESS8(HW_USB_ENDPTn_ADDR(x, n), BP_USB_ENDPTn_EPTXEN) = (v)) /*@}*/ /*! * @name Register USB_ENDPTn, field EPRXEN[3] (RW) * * This bit, when set, enables the endpoint for RX transfers. */ /*@{*/ #define BP_USB_ENDPTn_EPRXEN (3U) /*!< Bit position for USB_ENDPTn_EPRXEN. */ #define BM_USB_ENDPTn_EPRXEN (0x08U) /*!< Bit mask for USB_ENDPTn_EPRXEN. */ #define BS_USB_ENDPTn_EPRXEN (1U) /*!< Bit field size in bits for USB_ENDPTn_EPRXEN. */ /*! @brief Read current value of the USB_ENDPTn_EPRXEN field. */ #define BR_USB_ENDPTn_EPRXEN(x, n) (BITBAND_ACCESS8(HW_USB_ENDPTn_ADDR(x, n), BP_USB_ENDPTn_EPRXEN)) /*! @brief Format value for bitfield USB_ENDPTn_EPRXEN. */ #define BF_USB_ENDPTn_EPRXEN(v) ((uint8_t)((uint8_t)(v) << BP_USB_ENDPTn_EPRXEN) & BM_USB_ENDPTn_EPRXEN) /*! @brief Set the EPRXEN field to a new value. */ #define BW_USB_ENDPTn_EPRXEN(x, n, v) (BITBAND_ACCESS8(HW_USB_ENDPTn_ADDR(x, n), BP_USB_ENDPTn_EPRXEN) = (v)) /*@}*/ /*! * @name Register USB_ENDPTn, field EPCTLDIS[4] (RW) * * This bit, when set, disables control (SETUP) transfers. When cleared, control * transfers are enabled. This applies if and only if the EPRXEN and EPTXEN bits * are also set. */ /*@{*/ #define BP_USB_ENDPTn_EPCTLDIS (4U) /*!< Bit position for USB_ENDPTn_EPCTLDIS. */ #define BM_USB_ENDPTn_EPCTLDIS (0x10U) /*!< Bit mask for USB_ENDPTn_EPCTLDIS. */ #define BS_USB_ENDPTn_EPCTLDIS (1U) /*!< Bit field size in bits for USB_ENDPTn_EPCTLDIS. */ /*! @brief Read current value of the USB_ENDPTn_EPCTLDIS field. */ #define BR_USB_ENDPTn_EPCTLDIS(x, n) (BITBAND_ACCESS8(HW_USB_ENDPTn_ADDR(x, n), BP_USB_ENDPTn_EPCTLDIS)) /*! @brief Format value for bitfield USB_ENDPTn_EPCTLDIS. */ #define BF_USB_ENDPTn_EPCTLDIS(v) ((uint8_t)((uint8_t)(v) << BP_USB_ENDPTn_EPCTLDIS) & BM_USB_ENDPTn_EPCTLDIS) /*! @brief Set the EPCTLDIS field to a new value. */ #define BW_USB_ENDPTn_EPCTLDIS(x, n, v) (BITBAND_ACCESS8(HW_USB_ENDPTn_ADDR(x, n), BP_USB_ENDPTn_EPCTLDIS) = (v)) /*@}*/ /*! * @name Register USB_ENDPTn, field RETRYDIS[6] (RW) * * This is a Host mode only bit and is present in the control register for * endpoint 0 (ENDPT0) only. When set this bit causes the host to not retry NAK'ed * (Negative Acknowledgement) transactions. When a transaction is NAKed, the BDT PID * field is updated with the NAK PID, and the TOKEN_DNE interrupt is set. When * this bit is cleared, NAKed transactions are retried in hardware. This bit must * be set when the host is attempting to poll an interrupt endpoint. */ /*@{*/ #define BP_USB_ENDPTn_RETRYDIS (6U) /*!< Bit position for USB_ENDPTn_RETRYDIS. */ #define BM_USB_ENDPTn_RETRYDIS (0x40U) /*!< Bit mask for USB_ENDPTn_RETRYDIS. */ #define BS_USB_ENDPTn_RETRYDIS (1U) /*!< Bit field size in bits for USB_ENDPTn_RETRYDIS. */ /*! @brief Read current value of the USB_ENDPTn_RETRYDIS field. */ #define BR_USB_ENDPTn_RETRYDIS(x, n) (BITBAND_ACCESS8(HW_USB_ENDPTn_ADDR(x, n), BP_USB_ENDPTn_RETRYDIS)) /*! @brief Format value for bitfield USB_ENDPTn_RETRYDIS. */ #define BF_USB_ENDPTn_RETRYDIS(v) ((uint8_t)((uint8_t)(v) << BP_USB_ENDPTn_RETRYDIS) & BM_USB_ENDPTn_RETRYDIS) /*! @brief Set the RETRYDIS field to a new value. */ #define BW_USB_ENDPTn_RETRYDIS(x, n, v) (BITBAND_ACCESS8(HW_USB_ENDPTn_ADDR(x, n), BP_USB_ENDPTn_RETRYDIS) = (v)) /*@}*/ /*! * @name Register USB_ENDPTn, field HOSTWOHUB[7] (RW) * * This is a Host mode only field and is present in the control register for * endpoint 0 (ENDPT0) only. When set this bit allows the host to communicate to a * directly connected low speed device. When cleared, the host produces the * PRE_PID. It then switches to low-speed signaling when sending a token to a low speed * device as required to communicate with a low speed device through a hub. */ /*@{*/ #define BP_USB_ENDPTn_HOSTWOHUB (7U) /*!< Bit position for USB_ENDPTn_HOSTWOHUB. */ #define BM_USB_ENDPTn_HOSTWOHUB (0x80U) /*!< Bit mask for USB_ENDPTn_HOSTWOHUB. */ #define BS_USB_ENDPTn_HOSTWOHUB (1U) /*!< Bit field size in bits for USB_ENDPTn_HOSTWOHUB. */ /*! @brief Read current value of the USB_ENDPTn_HOSTWOHUB field. */ #define BR_USB_ENDPTn_HOSTWOHUB(x, n) (BITBAND_ACCESS8(HW_USB_ENDPTn_ADDR(x, n), BP_USB_ENDPTn_HOSTWOHUB)) /*! @brief Format value for bitfield USB_ENDPTn_HOSTWOHUB. */ #define BF_USB_ENDPTn_HOSTWOHUB(v) ((uint8_t)((uint8_t)(v) << BP_USB_ENDPTn_HOSTWOHUB) & BM_USB_ENDPTn_HOSTWOHUB) /*! @brief Set the HOSTWOHUB field to a new value. */ #define BW_USB_ENDPTn_HOSTWOHUB(x, n, v) (BITBAND_ACCESS8(HW_USB_ENDPTn_ADDR(x, n), BP_USB_ENDPTn_HOSTWOHUB) = (v)) /*@}*/ /******************************************************************************* * HW_USB_USBCTRL - USB Control register ******************************************************************************/ /*! * @brief HW_USB_USBCTRL - USB Control register (RW) * * Reset value: 0xC0U */ typedef union _hw_usb_usbctrl { uint8_t U; struct _hw_usb_usbctrl_bitfields { uint8_t RESERVED0 : 6; /*!< [5:0] */ uint8_t PDE : 1; /*!< [6] */ uint8_t SUSP : 1; /*!< [7] */ } B; } hw_usb_usbctrl_t; /*! * @name Constants and macros for entire USB_USBCTRL register */ /*@{*/ #define HW_USB_USBCTRL_ADDR(x) ((x) + 0x100U) #define HW_USB_USBCTRL(x) (*(__IO hw_usb_usbctrl_t *) HW_USB_USBCTRL_ADDR(x)) #define HW_USB_USBCTRL_RD(x) (HW_USB_USBCTRL(x).U) #define HW_USB_USBCTRL_WR(x, v) (HW_USB_USBCTRL(x).U = (v)) #define HW_USB_USBCTRL_SET(x, v) (HW_USB_USBCTRL_WR(x, HW_USB_USBCTRL_RD(x) | (v))) #define HW_USB_USBCTRL_CLR(x, v) (HW_USB_USBCTRL_WR(x, HW_USB_USBCTRL_RD(x) & ~(v))) #define HW_USB_USBCTRL_TOG(x, v) (HW_USB_USBCTRL_WR(x, HW_USB_USBCTRL_RD(x) ^ (v))) /*@}*/ /* * Constants & macros for individual USB_USBCTRL bitfields */ /*! * @name Register USB_USBCTRL, field PDE[6] (RW) * * Enables the weak pulldowns on the USB transceiver. * * Values: * - 0 - Weak pulldowns are disabled on D+ and D-. * - 1 - Weak pulldowns are enabled on D+ and D-. */ /*@{*/ #define BP_USB_USBCTRL_PDE (6U) /*!< Bit position for USB_USBCTRL_PDE. */ #define BM_USB_USBCTRL_PDE (0x40U) /*!< Bit mask for USB_USBCTRL_PDE. */ #define BS_USB_USBCTRL_PDE (1U) /*!< Bit field size in bits for USB_USBCTRL_PDE. */ /*! @brief Read current value of the USB_USBCTRL_PDE field. */ #define BR_USB_USBCTRL_PDE(x) (BITBAND_ACCESS8(HW_USB_USBCTRL_ADDR(x), BP_USB_USBCTRL_PDE)) /*! @brief Format value for bitfield USB_USBCTRL_PDE. */ #define BF_USB_USBCTRL_PDE(v) ((uint8_t)((uint8_t)(v) << BP_USB_USBCTRL_PDE) & BM_USB_USBCTRL_PDE) /*! @brief Set the PDE field to a new value. */ #define BW_USB_USBCTRL_PDE(x, v) (BITBAND_ACCESS8(HW_USB_USBCTRL_ADDR(x), BP_USB_USBCTRL_PDE) = (v)) /*@}*/ /*! * @name Register USB_USBCTRL, field SUSP[7] (RW) * * Places the USB transceiver into the suspend state. * * Values: * - 0 - USB transceiver is not in suspend state. * - 1 - USB transceiver is in suspend state. */ /*@{*/ #define BP_USB_USBCTRL_SUSP (7U) /*!< Bit position for USB_USBCTRL_SUSP. */ #define BM_USB_USBCTRL_SUSP (0x80U) /*!< Bit mask for USB_USBCTRL_SUSP. */ #define BS_USB_USBCTRL_SUSP (1U) /*!< Bit field size in bits for USB_USBCTRL_SUSP. */ /*! @brief Read current value of the USB_USBCTRL_SUSP field. */ #define BR_USB_USBCTRL_SUSP(x) (BITBAND_ACCESS8(HW_USB_USBCTRL_ADDR(x), BP_USB_USBCTRL_SUSP)) /*! @brief Format value for bitfield USB_USBCTRL_SUSP. */ #define BF_USB_USBCTRL_SUSP(v) ((uint8_t)((uint8_t)(v) << BP_USB_USBCTRL_SUSP) & BM_USB_USBCTRL_SUSP) /*! @brief Set the SUSP field to a new value. */ #define BW_USB_USBCTRL_SUSP(x, v) (BITBAND_ACCESS8(HW_USB_USBCTRL_ADDR(x), BP_USB_USBCTRL_SUSP) = (v)) /*@}*/ /******************************************************************************* * HW_USB_OBSERVE - USB OTG Observe register ******************************************************************************/ /*! * @brief HW_USB_OBSERVE - USB OTG Observe register (RO) * * Reset value: 0x50U * * Provides visibility on the state of the pull-ups and pull-downs at the * transceiver. Useful when interfacing to an external OTG control module via a serial * interface. */ typedef union _hw_usb_observe { uint8_t U; struct _hw_usb_observe_bitfields { uint8_t RESERVED0 : 4; /*!< [3:0] */ uint8_t DMPD : 1; /*!< [4] */ uint8_t RESERVED1 : 1; /*!< [5] */ uint8_t DPPD : 1; /*!< [6] */ uint8_t DPPU : 1; /*!< [7] */ } B; } hw_usb_observe_t; /*! * @name Constants and macros for entire USB_OBSERVE register */ /*@{*/ #define HW_USB_OBSERVE_ADDR(x) ((x) + 0x104U) #define HW_USB_OBSERVE(x) (*(__I hw_usb_observe_t *) HW_USB_OBSERVE_ADDR(x)) #define HW_USB_OBSERVE_RD(x) (HW_USB_OBSERVE(x).U) /*@}*/ /* * Constants & macros for individual USB_OBSERVE bitfields */ /*! * @name Register USB_OBSERVE, field DMPD[4] (RO) * * Provides observability of the D- Pulldown enable at the USB transceiver. * * Values: * - 0 - D- pulldown disabled. * - 1 - D- pulldown enabled. */ /*@{*/ #define BP_USB_OBSERVE_DMPD (4U) /*!< Bit position for USB_OBSERVE_DMPD. */ #define BM_USB_OBSERVE_DMPD (0x10U) /*!< Bit mask for USB_OBSERVE_DMPD. */ #define BS_USB_OBSERVE_DMPD (1U) /*!< Bit field size in bits for USB_OBSERVE_DMPD. */ /*! @brief Read current value of the USB_OBSERVE_DMPD field. */ #define BR_USB_OBSERVE_DMPD(x) (BITBAND_ACCESS8(HW_USB_OBSERVE_ADDR(x), BP_USB_OBSERVE_DMPD)) /*@}*/ /*! * @name Register USB_OBSERVE, field DPPD[6] (RO) * * Provides observability of the D+ Pulldown enable at the USB transceiver. * * Values: * - 0 - D+ pulldown disabled. * - 1 - D+ pulldown enabled. */ /*@{*/ #define BP_USB_OBSERVE_DPPD (6U) /*!< Bit position for USB_OBSERVE_DPPD. */ #define BM_USB_OBSERVE_DPPD (0x40U) /*!< Bit mask for USB_OBSERVE_DPPD. */ #define BS_USB_OBSERVE_DPPD (1U) /*!< Bit field size in bits for USB_OBSERVE_DPPD. */ /*! @brief Read current value of the USB_OBSERVE_DPPD field. */ #define BR_USB_OBSERVE_DPPD(x) (BITBAND_ACCESS8(HW_USB_OBSERVE_ADDR(x), BP_USB_OBSERVE_DPPD)) /*@}*/ /*! * @name Register USB_OBSERVE, field DPPU[7] (RO) * * Provides observability of the D+ Pullup enable at the USB transceiver. * * Values: * - 0 - D+ pullup disabled. * - 1 - D+ pullup enabled. */ /*@{*/ #define BP_USB_OBSERVE_DPPU (7U) /*!< Bit position for USB_OBSERVE_DPPU. */ #define BM_USB_OBSERVE_DPPU (0x80U) /*!< Bit mask for USB_OBSERVE_DPPU. */ #define BS_USB_OBSERVE_DPPU (1U) /*!< Bit field size in bits for USB_OBSERVE_DPPU. */ /*! @brief Read current value of the USB_OBSERVE_DPPU field. */ #define BR_USB_OBSERVE_DPPU(x) (BITBAND_ACCESS8(HW_USB_OBSERVE_ADDR(x), BP_USB_OBSERVE_DPPU)) /*@}*/ /******************************************************************************* * HW_USB_CONTROL - USB OTG Control register ******************************************************************************/ /*! * @brief HW_USB_CONTROL - USB OTG Control register (RW) * * Reset value: 0x00U */ typedef union _hw_usb_control { uint8_t U; struct _hw_usb_control_bitfields { uint8_t RESERVED0 : 4; /*!< [3:0] */ uint8_t DPPULLUPNONOTG : 1; /*!< [4] */ uint8_t RESERVED1 : 3; /*!< [7:5] */ } B; } hw_usb_control_t; /*! * @name Constants and macros for entire USB_CONTROL register */ /*@{*/ #define HW_USB_CONTROL_ADDR(x) ((x) + 0x108U) #define HW_USB_CONTROL(x) (*(__IO hw_usb_control_t *) HW_USB_CONTROL_ADDR(x)) #define HW_USB_CONTROL_RD(x) (HW_USB_CONTROL(x).U) #define HW_USB_CONTROL_WR(x, v) (HW_USB_CONTROL(x).U = (v)) #define HW_USB_CONTROL_SET(x, v) (HW_USB_CONTROL_WR(x, HW_USB_CONTROL_RD(x) | (v))) #define HW_USB_CONTROL_CLR(x, v) (HW_USB_CONTROL_WR(x, HW_USB_CONTROL_RD(x) & ~(v))) #define HW_USB_CONTROL_TOG(x, v) (HW_USB_CONTROL_WR(x, HW_USB_CONTROL_RD(x) ^ (v))) /*@}*/ /* * Constants & macros for individual USB_CONTROL bitfields */ /*! * @name Register USB_CONTROL, field DPPULLUPNONOTG[4] (RW) * * Provides control of the DP Pullup in USBOTG, if USB is configured in non-OTG * device mode. * * Values: * - 0 - DP Pullup in non-OTG device mode is not enabled. * - 1 - DP Pullup in non-OTG device mode is enabled. */ /*@{*/ #define BP_USB_CONTROL_DPPULLUPNONOTG (4U) /*!< Bit position for USB_CONTROL_DPPULLUPNONOTG. */ #define BM_USB_CONTROL_DPPULLUPNONOTG (0x10U) /*!< Bit mask for USB_CONTROL_DPPULLUPNONOTG. */ #define BS_USB_CONTROL_DPPULLUPNONOTG (1U) /*!< Bit field size in bits for USB_CONTROL_DPPULLUPNONOTG. */ /*! @brief Read current value of the USB_CONTROL_DPPULLUPNONOTG field. */ #define BR_USB_CONTROL_DPPULLUPNONOTG(x) (BITBAND_ACCESS8(HW_USB_CONTROL_ADDR(x), BP_USB_CONTROL_DPPULLUPNONOTG)) /*! @brief Format value for bitfield USB_CONTROL_DPPULLUPNONOTG. */ #define BF_USB_CONTROL_DPPULLUPNONOTG(v) ((uint8_t)((uint8_t)(v) << BP_USB_CONTROL_DPPULLUPNONOTG) & BM_USB_CONTROL_DPPULLUPNONOTG) /*! @brief Set the DPPULLUPNONOTG field to a new value. */ #define BW_USB_CONTROL_DPPULLUPNONOTG(x, v) (BITBAND_ACCESS8(HW_USB_CONTROL_ADDR(x), BP_USB_CONTROL_DPPULLUPNONOTG) = (v)) /*@}*/ /******************************************************************************* * HW_USB_USBTRC0 - USB Transceiver Control register 0 ******************************************************************************/ /*! * @brief HW_USB_USBTRC0 - USB Transceiver Control register 0 (RW) * * Reset value: 0x00U * * Includes signals for basic operation of the on-chip USB Full Speed * transceiver and configuration of the USB data connection that are not otherwise included * in the USB Full Speed controller registers. */ typedef union _hw_usb_usbtrc0 { uint8_t U; struct _hw_usb_usbtrc0_bitfields { uint8_t USB_RESUME_INT : 1; /*!< [0] USB Asynchronous Interrupt */ uint8_t SYNC_DET : 1; /*!< [1] Synchronous USB Interrupt Detect */ uint8_t USB_CLK_RECOVERY_INT : 1; /*!< [2] Combined USB Clock * Recovery interrupt status */ uint8_t RESERVED0 : 2; /*!< [4:3] */ uint8_t USBRESMEN : 1; /*!< [5] Asynchronous Resume Interrupt Enable * */ uint8_t RESERVED1 : 1; /*!< [6] */ uint8_t USBRESET : 1; /*!< [7] USB Reset */ } B; } hw_usb_usbtrc0_t; /*! * @name Constants and macros for entire USB_USBTRC0 register */ /*@{*/ #define HW_USB_USBTRC0_ADDR(x) ((x) + 0x10CU) #define HW_USB_USBTRC0(x) (*(__IO hw_usb_usbtrc0_t *) HW_USB_USBTRC0_ADDR(x)) #define HW_USB_USBTRC0_RD(x) (HW_USB_USBTRC0(x).U) #define HW_USB_USBTRC0_WR(x, v) (HW_USB_USBTRC0(x).U = (v)) #define HW_USB_USBTRC0_SET(x, v) (HW_USB_USBTRC0_WR(x, HW_USB_USBTRC0_RD(x) | (v))) #define HW_USB_USBTRC0_CLR(x, v) (HW_USB_USBTRC0_WR(x, HW_USB_USBTRC0_RD(x) & ~(v))) #define HW_USB_USBTRC0_TOG(x, v) (HW_USB_USBTRC0_WR(x, HW_USB_USBTRC0_RD(x) ^ (v))) /*@}*/ /* * Constants & macros for individual USB_USBTRC0 bitfields */ /*! * @name Register USB_USBTRC0, field USB_RESUME_INT[0] (RO) * * Values: * - 0 - No interrupt was generated. * - 1 - Interrupt was generated because of the USB asynchronous interrupt. */ /*@{*/ #define BP_USB_USBTRC0_USB_RESUME_INT (0U) /*!< Bit position for USB_USBTRC0_USB_RESUME_INT. */ #define BM_USB_USBTRC0_USB_RESUME_INT (0x01U) /*!< Bit mask for USB_USBTRC0_USB_RESUME_INT. */ #define BS_USB_USBTRC0_USB_RESUME_INT (1U) /*!< Bit field size in bits for USB_USBTRC0_USB_RESUME_INT. */ /*! @brief Read current value of the USB_USBTRC0_USB_RESUME_INT field. */ #define BR_USB_USBTRC0_USB_RESUME_INT(x) (BITBAND_ACCESS8(HW_USB_USBTRC0_ADDR(x), BP_USB_USBTRC0_USB_RESUME_INT)) /*@}*/ /*! * @name Register USB_USBTRC0, field SYNC_DET[1] (RO) * * Values: * - 0 - Synchronous interrupt has not been detected. * - 1 - Synchronous interrupt has been detected. */ /*@{*/ #define BP_USB_USBTRC0_SYNC_DET (1U) /*!< Bit position for USB_USBTRC0_SYNC_DET. */ #define BM_USB_USBTRC0_SYNC_DET (0x02U) /*!< Bit mask for USB_USBTRC0_SYNC_DET. */ #define BS_USB_USBTRC0_SYNC_DET (1U) /*!< Bit field size in bits for USB_USBTRC0_SYNC_DET. */ /*! @brief Read current value of the USB_USBTRC0_SYNC_DET field. */ #define BR_USB_USBTRC0_SYNC_DET(x) (BITBAND_ACCESS8(HW_USB_USBTRC0_ADDR(x), BP_USB_USBTRC0_SYNC_DET)) /*@}*/ /*! * @name Register USB_USBTRC0, field USB_CLK_RECOVERY_INT[2] (RO) * * This read-only field will be set to value high at 1'b1 when any of USB clock * recovery interrupt conditions are detected and those interrupts are unmasked. * For customer use the only unmasked USB clock recovery interrupt condition * results from an overflow of the frequency trim setting values indicating that the * frequency trim calculated is out of the adjustment range of the IRC48M output * clock. To clear this bit after it has been set, Write 0xFF to register * USB_CLK_RECOVER_INT_STATUS. */ /*@{*/ #define BP_USB_USBTRC0_USB_CLK_RECOVERY_INT (2U) /*!< Bit position for USB_USBTRC0_USB_CLK_RECOVERY_INT. */ #define BM_USB_USBTRC0_USB_CLK_RECOVERY_INT (0x04U) /*!< Bit mask for USB_USBTRC0_USB_CLK_RECOVERY_INT. */ #define BS_USB_USBTRC0_USB_CLK_RECOVERY_INT (1U) /*!< Bit field size in bits for USB_USBTRC0_USB_CLK_RECOVERY_INT. */ /*! @brief Read current value of the USB_USBTRC0_USB_CLK_RECOVERY_INT field. */ #define BR_USB_USBTRC0_USB_CLK_RECOVERY_INT(x) (BITBAND_ACCESS8(HW_USB_USBTRC0_ADDR(x), BP_USB_USBTRC0_USB_CLK_RECOVERY_INT)) /*@}*/ /*! * @name Register USB_USBTRC0, field USBRESMEN[5] (RW) * * This bit, when set, allows the USB module to send an asynchronous wakeup * event to the MCU upon detection of resume signaling on the USB bus. The MCU then * re-enables clocks to the USB module. It is used for low-power suspend mode when * USB module clocks are stopped or the USB transceiver is in Suspend mode. * Async wakeup only works in device mode. * * Values: * - 0 - USB asynchronous wakeup from suspend mode disabled. * - 1 - USB asynchronous wakeup from suspend mode enabled. The asynchronous * resume interrupt differs from the synchronous resume interrupt in that it * asynchronously detects K-state using the unfiltered state of the D+ and D- * pins. This interrupt should only be enabled when the Transceiver is * suspended. */ /*@{*/ #define BP_USB_USBTRC0_USBRESMEN (5U) /*!< Bit position for USB_USBTRC0_USBRESMEN. */ #define BM_USB_USBTRC0_USBRESMEN (0x20U) /*!< Bit mask for USB_USBTRC0_USBRESMEN. */ #define BS_USB_USBTRC0_USBRESMEN (1U) /*!< Bit field size in bits for USB_USBTRC0_USBRESMEN. */ /*! @brief Read current value of the USB_USBTRC0_USBRESMEN field. */ #define BR_USB_USBTRC0_USBRESMEN(x) (BITBAND_ACCESS8(HW_USB_USBTRC0_ADDR(x), BP_USB_USBTRC0_USBRESMEN)) /*! @brief Format value for bitfield USB_USBTRC0_USBRESMEN. */ #define BF_USB_USBTRC0_USBRESMEN(v) ((uint8_t)((uint8_t)(v) << BP_USB_USBTRC0_USBRESMEN) & BM_USB_USBTRC0_USBRESMEN) /*! @brief Set the USBRESMEN field to a new value. */ #define BW_USB_USBTRC0_USBRESMEN(x, v) (BITBAND_ACCESS8(HW_USB_USBTRC0_ADDR(x), BP_USB_USBTRC0_USBRESMEN) = (v)) /*@}*/ /*! * @name Register USB_USBTRC0, field USBRESET[7] (WO) * * Generates a hard reset to USBOTG. After this bit is set and the reset occurs, * this bit is automatically cleared. This bit is always read as zero. Wait two * USB clock cycles after setting this bit. * * Values: * - 0 - Normal USB module operation. * - 1 - Returns the USB module to its reset state. */ /*@{*/ #define BP_USB_USBTRC0_USBRESET (7U) /*!< Bit position for USB_USBTRC0_USBRESET. */ #define BM_USB_USBTRC0_USBRESET (0x80U) /*!< Bit mask for USB_USBTRC0_USBRESET. */ #define BS_USB_USBTRC0_USBRESET (1U) /*!< Bit field size in bits for USB_USBTRC0_USBRESET. */ /*! @brief Format value for bitfield USB_USBTRC0_USBRESET. */ #define BF_USB_USBTRC0_USBRESET(v) ((uint8_t)((uint8_t)(v) << BP_USB_USBTRC0_USBRESET) & BM_USB_USBTRC0_USBRESET) /*@}*/ /******************************************************************************* * HW_USB_USBFRMADJUST - Frame Adjust Register ******************************************************************************/ /*! * @brief HW_USB_USBFRMADJUST - Frame Adjust Register (RW) * * Reset value: 0x00U */ typedef union _hw_usb_usbfrmadjust { uint8_t U; struct _hw_usb_usbfrmadjust_bitfields { uint8_t ADJ : 8; /*!< [7:0] Frame Adjustment */ } B; } hw_usb_usbfrmadjust_t; /*! * @name Constants and macros for entire USB_USBFRMADJUST register */ /*@{*/ #define HW_USB_USBFRMADJUST_ADDR(x) ((x) + 0x114U) #define HW_USB_USBFRMADJUST(x) (*(__IO hw_usb_usbfrmadjust_t *) HW_USB_USBFRMADJUST_ADDR(x)) #define HW_USB_USBFRMADJUST_RD(x) (HW_USB_USBFRMADJUST(x).U) #define HW_USB_USBFRMADJUST_WR(x, v) (HW_USB_USBFRMADJUST(x).U = (v)) #define HW_USB_USBFRMADJUST_SET(x, v) (HW_USB_USBFRMADJUST_WR(x, HW_USB_USBFRMADJUST_RD(x) | (v))) #define HW_USB_USBFRMADJUST_CLR(x, v) (HW_USB_USBFRMADJUST_WR(x, HW_USB_USBFRMADJUST_RD(x) & ~(v))) #define HW_USB_USBFRMADJUST_TOG(x, v) (HW_USB_USBFRMADJUST_WR(x, HW_USB_USBFRMADJUST_RD(x) ^ (v))) /*@}*/ /* * Constants & macros for individual USB_USBFRMADJUST bitfields */ /*! * @name Register USB_USBFRMADJUST, field ADJ[7:0] (RW) * * In Host mode, the frame adjustment is a twos complement number that adjusts * the period of each USB frame in 12-MHz clock periods. A SOF is normally * generated every 12,000 12-MHz clock cycles. The Frame Adjust Register can adjust this * by -128 to +127 to compensate for inaccuracies in the USB 48-MHz clock. * Changes to the ADJ bit take effect at the next start of the next frame. */ /*@{*/ #define BP_USB_USBFRMADJUST_ADJ (0U) /*!< Bit position for USB_USBFRMADJUST_ADJ. */ #define BM_USB_USBFRMADJUST_ADJ (0xFFU) /*!< Bit mask for USB_USBFRMADJUST_ADJ. */ #define BS_USB_USBFRMADJUST_ADJ (8U) /*!< Bit field size in bits for USB_USBFRMADJUST_ADJ. */ /*! @brief Read current value of the USB_USBFRMADJUST_ADJ field. */ #define BR_USB_USBFRMADJUST_ADJ(x) (HW_USB_USBFRMADJUST(x).U) /*! @brief Format value for bitfield USB_USBFRMADJUST_ADJ. */ #define BF_USB_USBFRMADJUST_ADJ(v) ((uint8_t)((uint8_t)(v) << BP_USB_USBFRMADJUST_ADJ) & BM_USB_USBFRMADJUST_ADJ) /*! @brief Set the ADJ field to a new value. */ #define BW_USB_USBFRMADJUST_ADJ(x, v) (HW_USB_USBFRMADJUST_WR(x, v)) /*@}*/ /******************************************************************************* * HW_USB_CLK_RECOVER_CTRL - USB Clock recovery control ******************************************************************************/ /*! * @brief HW_USB_CLK_RECOVER_CTRL - USB Clock recovery control (RW) * * Reset value: 0x00U * * Signals in this register control the crystal-less USB clock mode in which the * internal IRC48M oscillator is tuned to match the clock extracted from the * incoming USB data stream. The IRC48M internal oscillator module must be enabled * in register USB_CLK_RECOVER_IRC_EN for this mode. */ typedef union _hw_usb_clk_recover_ctrl { uint8_t U; struct _hw_usb_clk_recover_ctrl_bitfields { uint8_t RESERVED0 : 5; /*!< [4:0] */ uint8_t RESTART_IFRTRIM_EN : 1; /*!< [5] Restart from IFR trim value * */ uint8_t RESET_RESUME_ROUGH_EN : 1; /*!< [6] Reset/resume to rough * phase enable */ uint8_t CLOCK_RECOVER_EN : 1; /*!< [7] Crystal-less USB enable */ } B; } hw_usb_clk_recover_ctrl_t; /*! * @name Constants and macros for entire USB_CLK_RECOVER_CTRL register */ /*@{*/ #define HW_USB_CLK_RECOVER_CTRL_ADDR(x) ((x) + 0x140U) #define HW_USB_CLK_RECOVER_CTRL(x) (*(__IO hw_usb_clk_recover_ctrl_t *) HW_USB_CLK_RECOVER_CTRL_ADDR(x)) #define HW_USB_CLK_RECOVER_CTRL_RD(x) (HW_USB_CLK_RECOVER_CTRL(x).U) #define HW_USB_CLK_RECOVER_CTRL_WR(x, v) (HW_USB_CLK_RECOVER_CTRL(x).U = (v)) #define HW_USB_CLK_RECOVER_CTRL_SET(x, v) (HW_USB_CLK_RECOVER_CTRL_WR(x, HW_USB_CLK_RECOVER_CTRL_RD(x) | (v))) #define HW_USB_CLK_RECOVER_CTRL_CLR(x, v) (HW_USB_CLK_RECOVER_CTRL_WR(x, HW_USB_CLK_RECOVER_CTRL_RD(x) & ~(v))) #define HW_USB_CLK_RECOVER_CTRL_TOG(x, v) (HW_USB_CLK_RECOVER_CTRL_WR(x, HW_USB_CLK_RECOVER_CTRL_RD(x) ^ (v))) /*@}*/ /* * Constants & macros for individual USB_CLK_RECOVER_CTRL bitfields */ /*! * @name Register USB_CLK_RECOVER_CTRL, field RESTART_IFRTRIM_EN[5] (RW) * * IRC48 has a default trim fine value whose default value is factory trimmed * (the IFR trim value). Clock recover block tracks the accuracy of the clock 48Mhz * and keeps updating the trim fine value accordingly * * Values: * - 0 - Trim fine adjustment always works based on the previous updated trim * fine value (default) * - 1 - Trim fine restarts from the IFR trim value whenever * bus_reset/bus_resume is detected or module enable is desasserted */ /*@{*/ #define BP_USB_CLK_RECOVER_CTRL_RESTART_IFRTRIM_EN (5U) /*!< Bit position for USB_CLK_RECOVER_CTRL_RESTART_IFRTRIM_EN. */ #define BM_USB_CLK_RECOVER_CTRL_RESTART_IFRTRIM_EN (0x20U) /*!< Bit mask for USB_CLK_RECOVER_CTRL_RESTART_IFRTRIM_EN. */ #define BS_USB_CLK_RECOVER_CTRL_RESTART_IFRTRIM_EN (1U) /*!< Bit field size in bits for USB_CLK_RECOVER_CTRL_RESTART_IFRTRIM_EN. */ /*! @brief Read current value of the USB_CLK_RECOVER_CTRL_RESTART_IFRTRIM_EN field. */ #define BR_USB_CLK_RECOVER_CTRL_RESTART_IFRTRIM_EN(x) (BITBAND_ACCESS8(HW_USB_CLK_RECOVER_CTRL_ADDR(x), BP_USB_CLK_RECOVER_CTRL_RESTART_IFRTRIM_EN)) /*! @brief Format value for bitfield USB_CLK_RECOVER_CTRL_RESTART_IFRTRIM_EN. */ #define BF_USB_CLK_RECOVER_CTRL_RESTART_IFRTRIM_EN(v) ((uint8_t)((uint8_t)(v) << BP_USB_CLK_RECOVER_CTRL_RESTART_IFRTRIM_EN) & BM_USB_CLK_RECOVER_CTRL_RESTART_IFRTRIM_EN) /*! @brief Set the RESTART_IFRTRIM_EN field to a new value. */ #define BW_USB_CLK_RECOVER_CTRL_RESTART_IFRTRIM_EN(x, v) (BITBAND_ACCESS8(HW_USB_CLK_RECOVER_CTRL_ADDR(x), BP_USB_CLK_RECOVER_CTRL_RESTART_IFRTRIM_EN) = (v)) /*@}*/ /*! * @name Register USB_CLK_RECOVER_CTRL, field RESET_RESUME_ROUGH_EN[6] (RW) * * The clock recovery block tracks the IRC48Mhz to get an accurate 48Mhz clock. * It has two phases after user enables clock_recover_en bit, rough phase and * tracking phase. The step to fine tune the IRC 48Mhz by adjusting the trim fine * value is different during these two phases. The step in rough phase is larger * than that in tracking phase. Switch back to rough stage whenever USB bus reset * or bus resume occurs. * * Values: * - 0 - Always works in tracking phase after the 1st time rough to track * transition (default) * - 1 - Go back to rough stage whenever bus reset or bus resume occurs */ /*@{*/ #define BP_USB_CLK_RECOVER_CTRL_RESET_RESUME_ROUGH_EN (6U) /*!< Bit position for USB_CLK_RECOVER_CTRL_RESET_RESUME_ROUGH_EN. */ #define BM_USB_CLK_RECOVER_CTRL_RESET_RESUME_ROUGH_EN (0x40U) /*!< Bit mask for USB_CLK_RECOVER_CTRL_RESET_RESUME_ROUGH_EN. */ #define BS_USB_CLK_RECOVER_CTRL_RESET_RESUME_ROUGH_EN (1U) /*!< Bit field size in bits for USB_CLK_RECOVER_CTRL_RESET_RESUME_ROUGH_EN. */ /*! @brief Read current value of the USB_CLK_RECOVER_CTRL_RESET_RESUME_ROUGH_EN field. */ #define BR_USB_CLK_RECOVER_CTRL_RESET_RESUME_ROUGH_EN(x) (BITBAND_ACCESS8(HW_USB_CLK_RECOVER_CTRL_ADDR(x), BP_USB_CLK_RECOVER_CTRL_RESET_RESUME_ROUGH_EN)) /*! @brief Format value for bitfield USB_CLK_RECOVER_CTRL_RESET_RESUME_ROUGH_EN. */ #define BF_USB_CLK_RECOVER_CTRL_RESET_RESUME_ROUGH_EN(v) ((uint8_t)((uint8_t)(v) << BP_USB_CLK_RECOVER_CTRL_RESET_RESUME_ROUGH_EN) & BM_USB_CLK_RECOVER_CTRL_RESET_RESUME_ROUGH_EN) /*! @brief Set the RESET_RESUME_ROUGH_EN field to a new value. */ #define BW_USB_CLK_RECOVER_CTRL_RESET_RESUME_ROUGH_EN(x, v) (BITBAND_ACCESS8(HW_USB_CLK_RECOVER_CTRL_ADDR(x), BP_USB_CLK_RECOVER_CTRL_RESET_RESUME_ROUGH_EN) = (v)) /*@}*/ /*! * @name Register USB_CLK_RECOVER_CTRL, field CLOCK_RECOVER_EN[7] (RW) * * This bit must be enabled if user wants to use the crystal-less USB mode for * the Full Speed USB controller and transceiver. This bit should not be set for * USB host mode or OTG. * * Values: * - 0 - Disable clock recovery block (default) * - 1 - Enable clock recovery block */ /*@{*/ #define BP_USB_CLK_RECOVER_CTRL_CLOCK_RECOVER_EN (7U) /*!< Bit position for USB_CLK_RECOVER_CTRL_CLOCK_RECOVER_EN. */ #define BM_USB_CLK_RECOVER_CTRL_CLOCK_RECOVER_EN (0x80U) /*!< Bit mask for USB_CLK_RECOVER_CTRL_CLOCK_RECOVER_EN. */ #define BS_USB_CLK_RECOVER_CTRL_CLOCK_RECOVER_EN (1U) /*!< Bit field size in bits for USB_CLK_RECOVER_CTRL_CLOCK_RECOVER_EN. */ /*! @brief Read current value of the USB_CLK_RECOVER_CTRL_CLOCK_RECOVER_EN field. */ #define BR_USB_CLK_RECOVER_CTRL_CLOCK_RECOVER_EN(x) (BITBAND_ACCESS8(HW_USB_CLK_RECOVER_CTRL_ADDR(x), BP_USB_CLK_RECOVER_CTRL_CLOCK_RECOVER_EN)) /*! @brief Format value for bitfield USB_CLK_RECOVER_CTRL_CLOCK_RECOVER_EN. */ #define BF_USB_CLK_RECOVER_CTRL_CLOCK_RECOVER_EN(v) ((uint8_t)((uint8_t)(v) << BP_USB_CLK_RECOVER_CTRL_CLOCK_RECOVER_EN) & BM_USB_CLK_RECOVER_CTRL_CLOCK_RECOVER_EN) /*! @brief Set the CLOCK_RECOVER_EN field to a new value. */ #define BW_USB_CLK_RECOVER_CTRL_CLOCK_RECOVER_EN(x, v) (BITBAND_ACCESS8(HW_USB_CLK_RECOVER_CTRL_ADDR(x), BP_USB_CLK_RECOVER_CTRL_CLOCK_RECOVER_EN) = (v)) /*@}*/ /******************************************************************************* * HW_USB_CLK_RECOVER_IRC_EN - IRC48M oscillator enable register ******************************************************************************/ /*! * @brief HW_USB_CLK_RECOVER_IRC_EN - IRC48M oscillator enable register (RW) * * Reset value: 0x01U * * Controls basic operation of the on-chip IRC48M module used to produce nominal * 48MHz clocks for USB crystal-less operation and other functions. See * additional information about the IRC48M operation in the Clock Distribution chapter. */ typedef union _hw_usb_clk_recover_irc_en { uint8_t U; struct _hw_usb_clk_recover_irc_en_bitfields { uint8_t REG_EN : 1; /*!< [0] IRC48M regulator enable */ uint8_t IRC_EN : 1; /*!< [1] IRC48M enable */ uint8_t RESERVED0 : 6; /*!< [7:2] */ } B; } hw_usb_clk_recover_irc_en_t; /*! * @name Constants and macros for entire USB_CLK_RECOVER_IRC_EN register */ /*@{*/ #define HW_USB_CLK_RECOVER_IRC_EN_ADDR(x) ((x) + 0x144U) #define HW_USB_CLK_RECOVER_IRC_EN(x) (*(__IO hw_usb_clk_recover_irc_en_t *) HW_USB_CLK_RECOVER_IRC_EN_ADDR(x)) #define HW_USB_CLK_RECOVER_IRC_EN_RD(x) (HW_USB_CLK_RECOVER_IRC_EN(x).U) #define HW_USB_CLK_RECOVER_IRC_EN_WR(x, v) (HW_USB_CLK_RECOVER_IRC_EN(x).U = (v)) #define HW_USB_CLK_RECOVER_IRC_EN_SET(x, v) (HW_USB_CLK_RECOVER_IRC_EN_WR(x, HW_USB_CLK_RECOVER_IRC_EN_RD(x) | (v))) #define HW_USB_CLK_RECOVER_IRC_EN_CLR(x, v) (HW_USB_CLK_RECOVER_IRC_EN_WR(x, HW_USB_CLK_RECOVER_IRC_EN_RD(x) & ~(v))) #define HW_USB_CLK_RECOVER_IRC_EN_TOG(x, v) (HW_USB_CLK_RECOVER_IRC_EN_WR(x, HW_USB_CLK_RECOVER_IRC_EN_RD(x) ^ (v))) /*@}*/ /* * Constants & macros for individual USB_CLK_RECOVER_IRC_EN bitfields */ /*! * @name Register USB_CLK_RECOVER_IRC_EN, field REG_EN[0] (RW) * * This bit is used to enable the local analog regulator for IRC48Mhz module. * This bit must be set if user wants to use the crystal-less USB clock * configuration. * * Values: * - 0 - IRC48M local regulator is disabled * - 1 - IRC48M local regulator is enabled (default) */ /*@{*/ #define BP_USB_CLK_RECOVER_IRC_EN_REG_EN (0U) /*!< Bit position for USB_CLK_RECOVER_IRC_EN_REG_EN. */ #define BM_USB_CLK_RECOVER_IRC_EN_REG_EN (0x01U) /*!< Bit mask for USB_CLK_RECOVER_IRC_EN_REG_EN. */ #define BS_USB_CLK_RECOVER_IRC_EN_REG_EN (1U) /*!< Bit field size in bits for USB_CLK_RECOVER_IRC_EN_REG_EN. */ /*! @brief Read current value of the USB_CLK_RECOVER_IRC_EN_REG_EN field. */ #define BR_USB_CLK_RECOVER_IRC_EN_REG_EN(x) (BITBAND_ACCESS8(HW_USB_CLK_RECOVER_IRC_EN_ADDR(x), BP_USB_CLK_RECOVER_IRC_EN_REG_EN)) /*! @brief Format value for bitfield USB_CLK_RECOVER_IRC_EN_REG_EN. */ #define BF_USB_CLK_RECOVER_IRC_EN_REG_EN(v) ((uint8_t)((uint8_t)(v) << BP_USB_CLK_RECOVER_IRC_EN_REG_EN) & BM_USB_CLK_RECOVER_IRC_EN_REG_EN) /*! @brief Set the REG_EN field to a new value. */ #define BW_USB_CLK_RECOVER_IRC_EN_REG_EN(x, v) (BITBAND_ACCESS8(HW_USB_CLK_RECOVER_IRC_EN_ADDR(x), BP_USB_CLK_RECOVER_IRC_EN_REG_EN) = (v)) /*@}*/ /*! * @name Register USB_CLK_RECOVER_IRC_EN, field IRC_EN[1] (RW) * * This bit is used to enable the on-chip IRC48Mhz module to generate clocks for * crystal-less USB. It can only be used for FS USB device mode operation. This * bit must be set before using the crystal-less USB clock configuration. * * Values: * - 0 - Disable the IRC48M module (default) * - 1 - Enable the IRC48M module */ /*@{*/ #define BP_USB_CLK_RECOVER_IRC_EN_IRC_EN (1U) /*!< Bit position for USB_CLK_RECOVER_IRC_EN_IRC_EN. */ #define BM_USB_CLK_RECOVER_IRC_EN_IRC_EN (0x02U) /*!< Bit mask for USB_CLK_RECOVER_IRC_EN_IRC_EN. */ #define BS_USB_CLK_RECOVER_IRC_EN_IRC_EN (1U) /*!< Bit field size in bits for USB_CLK_RECOVER_IRC_EN_IRC_EN. */ /*! @brief Read current value of the USB_CLK_RECOVER_IRC_EN_IRC_EN field. */ #define BR_USB_CLK_RECOVER_IRC_EN_IRC_EN(x) (BITBAND_ACCESS8(HW_USB_CLK_RECOVER_IRC_EN_ADDR(x), BP_USB_CLK_RECOVER_IRC_EN_IRC_EN)) /*! @brief Format value for bitfield USB_CLK_RECOVER_IRC_EN_IRC_EN. */ #define BF_USB_CLK_RECOVER_IRC_EN_IRC_EN(v) ((uint8_t)((uint8_t)(v) << BP_USB_CLK_RECOVER_IRC_EN_IRC_EN) & BM_USB_CLK_RECOVER_IRC_EN_IRC_EN) /*! @brief Set the IRC_EN field to a new value. */ #define BW_USB_CLK_RECOVER_IRC_EN_IRC_EN(x, v) (BITBAND_ACCESS8(HW_USB_CLK_RECOVER_IRC_EN_ADDR(x), BP_USB_CLK_RECOVER_IRC_EN_IRC_EN) = (v)) /*@}*/ /******************************************************************************* * HW_USB_CLK_RECOVER_INT_STATUS - Clock recovery separated interrupt status ******************************************************************************/ /*! * @brief HW_USB_CLK_RECOVER_INT_STATUS - Clock recovery separated interrupt status (W1C) * * Reset value: 0x00U * * A Write operation with value high at 1'b1 on any combination of individual * bits will clear those bits. */ typedef union _hw_usb_clk_recover_int_status { uint8_t U; struct _hw_usb_clk_recover_int_status_bitfields { uint8_t RESERVED0 : 4; /*!< [3:0] */ uint8_t OVF_ERROR : 1; /*!< [4] */ uint8_t RESERVED1 : 3; /*!< [7:5] */ } B; } hw_usb_clk_recover_int_status_t; /*! * @name Constants and macros for entire USB_CLK_RECOVER_INT_STATUS register */ /*@{*/ #define HW_USB_CLK_RECOVER_INT_STATUS_ADDR(x) ((x) + 0x15CU) #define HW_USB_CLK_RECOVER_INT_STATUS(x) (*(__IO hw_usb_clk_recover_int_status_t *) HW_USB_CLK_RECOVER_INT_STATUS_ADDR(x)) #define HW_USB_CLK_RECOVER_INT_STATUS_RD(x) (HW_USB_CLK_RECOVER_INT_STATUS(x).U) #define HW_USB_CLK_RECOVER_INT_STATUS_WR(x, v) (HW_USB_CLK_RECOVER_INT_STATUS(x).U = (v)) #define HW_USB_CLK_RECOVER_INT_STATUS_SET(x, v) (HW_USB_CLK_RECOVER_INT_STATUS_WR(x, HW_USB_CLK_RECOVER_INT_STATUS_RD(x) | (v))) #define HW_USB_CLK_RECOVER_INT_STATUS_CLR(x, v) (HW_USB_CLK_RECOVER_INT_STATUS_WR(x, HW_USB_CLK_RECOVER_INT_STATUS_RD(x) & ~(v))) #define HW_USB_CLK_RECOVER_INT_STATUS_TOG(x, v) (HW_USB_CLK_RECOVER_INT_STATUS_WR(x, HW_USB_CLK_RECOVER_INT_STATUS_RD(x) ^ (v))) /*@}*/ /* * Constants & macros for individual USB_CLK_RECOVER_INT_STATUS bitfields */ /*! * @name Register USB_CLK_RECOVER_INT_STATUS, field OVF_ERROR[4] (W1C) * * Indicates that the USB clock recovery algorithm has detected that the * frequency trim adjustment needed for the IRC48M output clock is outside the available * TRIM_FINE adjustment range for the IRC48M module. * * Values: * - 0 - No interrupt is reported * - 1 - Unmasked interrupt has been generated */ /*@{*/ #define BP_USB_CLK_RECOVER_INT_STATUS_OVF_ERROR (4U) /*!< Bit position for USB_CLK_RECOVER_INT_STATUS_OVF_ERROR. */ #define BM_USB_CLK_RECOVER_INT_STATUS_OVF_ERROR (0x10U) /*!< Bit mask for USB_CLK_RECOVER_INT_STATUS_OVF_ERROR. */ #define BS_USB_CLK_RECOVER_INT_STATUS_OVF_ERROR (1U) /*!< Bit field size in bits for USB_CLK_RECOVER_INT_STATUS_OVF_ERROR. */ /*! @brief Read current value of the USB_CLK_RECOVER_INT_STATUS_OVF_ERROR field. */ #define BR_USB_CLK_RECOVER_INT_STATUS_OVF_ERROR(x) (BITBAND_ACCESS8(HW_USB_CLK_RECOVER_INT_STATUS_ADDR(x), BP_USB_CLK_RECOVER_INT_STATUS_OVF_ERROR)) /*! @brief Format value for bitfield USB_CLK_RECOVER_INT_STATUS_OVF_ERROR. */ #define BF_USB_CLK_RECOVER_INT_STATUS_OVF_ERROR(v) ((uint8_t)((uint8_t)(v) << BP_USB_CLK_RECOVER_INT_STATUS_OVF_ERROR) & BM_USB_CLK_RECOVER_INT_STATUS_OVF_ERROR) /*! @brief Set the OVF_ERROR field to a new value. */ #define BW_USB_CLK_RECOVER_INT_STATUS_OVF_ERROR(x, v) (BITBAND_ACCESS8(HW_USB_CLK_RECOVER_INT_STATUS_ADDR(x), BP_USB_CLK_RECOVER_INT_STATUS_OVF_ERROR) = (v)) /*@}*/ /******************************************************************************* * hw_usb_t - module struct ******************************************************************************/ /*! * @brief All USB module registers. */ #pragma pack(1) typedef struct _hw_usb { __I hw_usb_perid_t PERID; /*!< [0x0] Peripheral ID register */ uint8_t _reserved0[3]; __I hw_usb_idcomp_t IDCOMP; /*!< [0x4] Peripheral ID Complement register */ uint8_t _reserved1[3]; __I hw_usb_rev_t REV; /*!< [0x8] Peripheral Revision register */ uint8_t _reserved2[3]; __I hw_usb_addinfo_t ADDINFO; /*!< [0xC] Peripheral Additional Info register */ uint8_t _reserved3[3]; __IO hw_usb_otgistat_t OTGISTAT; /*!< [0x10] OTG Interrupt Status register */ uint8_t _reserved4[3]; __IO hw_usb_otgicr_t OTGICR; /*!< [0x14] OTG Interrupt Control register */ uint8_t _reserved5[3]; __IO hw_usb_otgstat_t OTGSTAT; /*!< [0x18] OTG Status register */ uint8_t _reserved6[3]; __IO hw_usb_otgctl_t OTGCTL; /*!< [0x1C] OTG Control register */ uint8_t _reserved7[99]; __IO hw_usb_istat_t ISTAT; /*!< [0x80] Interrupt Status register */ uint8_t _reserved8[3]; __IO hw_usb_inten_t INTEN; /*!< [0x84] Interrupt Enable register */ uint8_t _reserved9[3]; __IO hw_usb_errstat_t ERRSTAT; /*!< [0x88] Error Interrupt Status register */ uint8_t _reserved10[3]; __IO hw_usb_erren_t ERREN; /*!< [0x8C] Error Interrupt Enable register */ uint8_t _reserved11[3]; __I hw_usb_stat_t STAT; /*!< [0x90] Status register */ uint8_t _reserved12[3]; __IO hw_usb_ctl_t CTL; /*!< [0x94] Control register */ uint8_t _reserved13[3]; __IO hw_usb_addr_t ADDR; /*!< [0x98] Address register */ uint8_t _reserved14[3]; __IO hw_usb_bdtpage1_t BDTPAGE1; /*!< [0x9C] BDT Page register 1 */ uint8_t _reserved15[3]; __IO hw_usb_frmnuml_t FRMNUML; /*!< [0xA0] Frame Number register Low */ uint8_t _reserved16[3]; __IO hw_usb_frmnumh_t FRMNUMH; /*!< [0xA4] Frame Number register High */ uint8_t _reserved17[3]; __IO hw_usb_token_t TOKEN; /*!< [0xA8] Token register */ uint8_t _reserved18[3]; __IO hw_usb_softhld_t SOFTHLD; /*!< [0xAC] SOF Threshold register */ uint8_t _reserved19[3]; __IO hw_usb_bdtpage2_t BDTPAGE2; /*!< [0xB0] BDT Page Register 2 */ uint8_t _reserved20[3]; __IO hw_usb_bdtpage3_t BDTPAGE3; /*!< [0xB4] BDT Page Register 3 */ uint8_t _reserved21[11]; struct { __IO hw_usb_endptn_t ENDPTn; /*!< [0xC0] Endpoint Control register */ uint8_t _reserved0[3]; } ENDPOINT[16]; __IO hw_usb_usbctrl_t USBCTRL; /*!< [0x100] USB Control register */ uint8_t _reserved22[3]; __I hw_usb_observe_t OBSERVE; /*!< [0x104] USB OTG Observe register */ uint8_t _reserved23[3]; __IO hw_usb_control_t CONTROL; /*!< [0x108] USB OTG Control register */ uint8_t _reserved24[3]; __IO hw_usb_usbtrc0_t USBTRC0; /*!< [0x10C] USB Transceiver Control register 0 */ uint8_t _reserved25[7]; __IO hw_usb_usbfrmadjust_t USBFRMADJUST; /*!< [0x114] Frame Adjust Register */ uint8_t _reserved26[43]; __IO hw_usb_clk_recover_ctrl_t CLK_RECOVER_CTRL; /*!< [0x140] USB Clock recovery control */ uint8_t _reserved27[3]; __IO hw_usb_clk_recover_irc_en_t CLK_RECOVER_IRC_EN; /*!< [0x144] IRC48M oscillator enable register */ uint8_t _reserved28[23]; __IO hw_usb_clk_recover_int_status_t CLK_RECOVER_INT_STATUS; /*!< [0x15C] Clock recovery separated interrupt status */ } hw_usb_t; #pragma pack() /*! @brief Macro to access all USB registers. */ /*! @param x USB module instance base address. */ /*! @return Reference (not a pointer) to the registers struct. To get a pointer to the struct, * use the '&' operator, like &HW_USB(USB0_BASE). */ #define HW_USB(x) (*(hw_usb_t *)(x)) #endif /* __HW_USB_REGISTERS_H__ */ /* EOF */ ================================================ FILE: Zelig/mbed/TARGET_K64F/TARGET_Freescale/TARGET_KPSDK_MCUS/TARGET_MCU_K64F/device/device/MK64F12/MK64F12_usbdcd.h ================================================ /* ** ################################################################### ** Compilers: Keil ARM C/C++ Compiler ** Freescale C/C++ for Embedded ARM ** GNU C Compiler ** IAR ANSI C/C++ Compiler for ARM ** ** Reference manual: K64P144M120SF5RM, Rev.2, January 2014 ** Version: rev. 2.5, 2014-02-10 ** Build: b140604 ** ** Abstract: ** Extension to the CMSIS register access layer header. ** ** Copyright (c) 2014 Freescale Semiconductor, Inc. ** All rights reserved. ** ** Redistribution and use in source and binary forms, with or without modification, ** are permitted provided that the following conditions are met: ** ** o Redistributions of source code must retain the above copyright notice, this list ** of conditions and the following disclaimer. ** ** o Redistributions in binary form must reproduce the above copyright notice, this ** list of conditions and the following disclaimer in the documentation and/or ** other materials provided with the distribution. ** ** o Neither the name of Freescale Semiconductor, Inc. nor the names of its ** contributors may be used to endorse or promote products derived from this ** software without specific prior written permission. ** ** THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ** ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED ** WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE ** DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT 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. ** ** http: www.freescale.com ** mail: support@freescale.com ** ** Revisions: ** - rev. 1.0 (2013-08-12) ** Initial version. ** - rev. 2.0 (2013-10-29) ** Register accessor macros added to the memory map. ** Symbols for Processor Expert memory map compatibility added to the memory map. ** Startup file for gcc has been updated according to CMSIS 3.2. ** System initialization updated. ** MCG - registers updated. ** PORTA, PORTB, PORTC, PORTE - registers for digital filter removed. ** - rev. 2.1 (2013-10-30) ** Definition of BITBAND macros updated to support peripherals with 32-bit acces disabled. ** - rev. 2.2 (2013-12-09) ** DMA - EARS register removed. ** AIPS0, AIPS1 - MPRA register updated. ** - rev. 2.3 (2014-01-24) ** Update according to reference manual rev. 2 ** ENET, MCG, MCM, SIM, USB - registers updated ** - rev. 2.4 (2014-02-10) ** The declaration of clock configurations has been moved to separate header file system_MK64F12.h ** Update of SystemInit() and SystemCoreClockUpdate() functions. ** - rev. 2.5 (2014-02-10) ** The declaration of clock configurations has been moved to separate header file system_MK64F12.h ** Update of SystemInit() and SystemCoreClockUpdate() functions. ** Module access macro module_BASES replaced by module_BASE_PTRS. ** ** ################################################################### */ /* * WARNING! DO NOT EDIT THIS FILE DIRECTLY! * * This file was generated automatically and any changes may be lost. */ #ifndef __HW_USBDCD_REGISTERS_H__ #define __HW_USBDCD_REGISTERS_H__ #include "MK64F12.h" #include "fsl_bitaccess.h" /* * MK64F12 USBDCD * * USB Device Charger Detection module * * Registers defined in this header file: * - HW_USBDCD_CONTROL - Control register * - HW_USBDCD_CLOCK - Clock register * - HW_USBDCD_STATUS - Status register * - HW_USBDCD_TIMER0 - TIMER0 register * - HW_USBDCD_TIMER1 - TIMER1 register * - HW_USBDCD_TIMER2_BC11 - TIMER2_BC11 register * - HW_USBDCD_TIMER2_BC12 - TIMER2_BC12 register * * - hw_usbdcd_t - Struct containing all module registers. */ #define HW_USBDCD_INSTANCE_COUNT (1U) /*!< Number of instances of the USBDCD module. */ /******************************************************************************* * HW_USBDCD_CONTROL - Control register ******************************************************************************/ /*! * @brief HW_USBDCD_CONTROL - Control register (RW) * * Reset value: 0x00010000U * * Contains the control and interrupt bit fields. */ typedef union _hw_usbdcd_control { uint32_t U; struct _hw_usbdcd_control_bitfields { uint32_t IACK : 1; /*!< [0] Interrupt Acknowledge */ uint32_t RESERVED0 : 7; /*!< [7:1] */ uint32_t IF : 1; /*!< [8] Interrupt Flag */ uint32_t RESERVED1 : 7; /*!< [15:9] */ uint32_t IE : 1; /*!< [16] Interrupt Enable */ uint32_t BC12 : 1; /*!< [17] */ uint32_t RESERVED2 : 6; /*!< [23:18] */ uint32_t START : 1; /*!< [24] Start Change Detection Sequence */ uint32_t SR : 1; /*!< [25] Software Reset */ uint32_t RESERVED3 : 6; /*!< [31:26] */ } B; } hw_usbdcd_control_t; /*! * @name Constants and macros for entire USBDCD_CONTROL register */ /*@{*/ #define HW_USBDCD_CONTROL_ADDR(x) ((x) + 0x0U) #define HW_USBDCD_CONTROL(x) (*(__IO hw_usbdcd_control_t *) HW_USBDCD_CONTROL_ADDR(x)) #define HW_USBDCD_CONTROL_RD(x) (HW_USBDCD_CONTROL(x).U) #define HW_USBDCD_CONTROL_WR(x, v) (HW_USBDCD_CONTROL(x).U = (v)) #define HW_USBDCD_CONTROL_SET(x, v) (HW_USBDCD_CONTROL_WR(x, HW_USBDCD_CONTROL_RD(x) | (v))) #define HW_USBDCD_CONTROL_CLR(x, v) (HW_USBDCD_CONTROL_WR(x, HW_USBDCD_CONTROL_RD(x) & ~(v))) #define HW_USBDCD_CONTROL_TOG(x, v) (HW_USBDCD_CONTROL_WR(x, HW_USBDCD_CONTROL_RD(x) ^ (v))) /*@}*/ /* * Constants & macros for individual USBDCD_CONTROL bitfields */ /*! * @name Register USBDCD_CONTROL, field IACK[0] (WORZ) * * Determines whether the interrupt is cleared. * * Values: * - 0 - Do not clear the interrupt. * - 1 - Clear the IF bit (interrupt flag). */ /*@{*/ #define BP_USBDCD_CONTROL_IACK (0U) /*!< Bit position for USBDCD_CONTROL_IACK. */ #define BM_USBDCD_CONTROL_IACK (0x00000001U) /*!< Bit mask for USBDCD_CONTROL_IACK. */ #define BS_USBDCD_CONTROL_IACK (1U) /*!< Bit field size in bits for USBDCD_CONTROL_IACK. */ /*! @brief Format value for bitfield USBDCD_CONTROL_IACK. */ #define BF_USBDCD_CONTROL_IACK(v) ((uint32_t)((uint32_t)(v) << BP_USBDCD_CONTROL_IACK) & BM_USBDCD_CONTROL_IACK) /*! @brief Set the IACK field to a new value. */ #define BW_USBDCD_CONTROL_IACK(x, v) (BITBAND_ACCESS32(HW_USBDCD_CONTROL_ADDR(x), BP_USBDCD_CONTROL_IACK) = (v)) /*@}*/ /*! * @name Register USBDCD_CONTROL, field IF[8] (RO) * * Determines whether an interrupt is pending. * * Values: * - 0 - No interrupt is pending. * - 1 - An interrupt is pending. */ /*@{*/ #define BP_USBDCD_CONTROL_IF (8U) /*!< Bit position for USBDCD_CONTROL_IF. */ #define BM_USBDCD_CONTROL_IF (0x00000100U) /*!< Bit mask for USBDCD_CONTROL_IF. */ #define BS_USBDCD_CONTROL_IF (1U) /*!< Bit field size in bits for USBDCD_CONTROL_IF. */ /*! @brief Read current value of the USBDCD_CONTROL_IF field. */ #define BR_USBDCD_CONTROL_IF(x) (BITBAND_ACCESS32(HW_USBDCD_CONTROL_ADDR(x), BP_USBDCD_CONTROL_IF)) /*@}*/ /*! * @name Register USBDCD_CONTROL, field IE[16] (RW) * * Enables/disables interrupts to the system. * * Values: * - 0 - Disable interrupts to the system. * - 1 - Enable interrupts to the system. */ /*@{*/ #define BP_USBDCD_CONTROL_IE (16U) /*!< Bit position for USBDCD_CONTROL_IE. */ #define BM_USBDCD_CONTROL_IE (0x00010000U) /*!< Bit mask for USBDCD_CONTROL_IE. */ #define BS_USBDCD_CONTROL_IE (1U) /*!< Bit field size in bits for USBDCD_CONTROL_IE. */ /*! @brief Read current value of the USBDCD_CONTROL_IE field. */ #define BR_USBDCD_CONTROL_IE(x) (BITBAND_ACCESS32(HW_USBDCD_CONTROL_ADDR(x), BP_USBDCD_CONTROL_IE)) /*! @brief Format value for bitfield USBDCD_CONTROL_IE. */ #define BF_USBDCD_CONTROL_IE(v) ((uint32_t)((uint32_t)(v) << BP_USBDCD_CONTROL_IE) & BM_USBDCD_CONTROL_IE) /*! @brief Set the IE field to a new value. */ #define BW_USBDCD_CONTROL_IE(x, v) (BITBAND_ACCESS32(HW_USBDCD_CONTROL_ADDR(x), BP_USBDCD_CONTROL_IE) = (v)) /*@}*/ /*! * @name Register USBDCD_CONTROL, field BC12[17] (RW) * * BC1.2 compatibility. This bit cannot be changed after start detection. * * Values: * - 0 - Compatible with BC1.1 (default) * - 1 - Compatible with BC1.2 */ /*@{*/ #define BP_USBDCD_CONTROL_BC12 (17U) /*!< Bit position for USBDCD_CONTROL_BC12. */ #define BM_USBDCD_CONTROL_BC12 (0x00020000U) /*!< Bit mask for USBDCD_CONTROL_BC12. */ #define BS_USBDCD_CONTROL_BC12 (1U) /*!< Bit field size in bits for USBDCD_CONTROL_BC12. */ /*! @brief Read current value of the USBDCD_CONTROL_BC12 field. */ #define BR_USBDCD_CONTROL_BC12(x) (BITBAND_ACCESS32(HW_USBDCD_CONTROL_ADDR(x), BP_USBDCD_CONTROL_BC12)) /*! @brief Format value for bitfield USBDCD_CONTROL_BC12. */ #define BF_USBDCD_CONTROL_BC12(v) ((uint32_t)((uint32_t)(v) << BP_USBDCD_CONTROL_BC12) & BM_USBDCD_CONTROL_BC12) /*! @brief Set the BC12 field to a new value. */ #define BW_USBDCD_CONTROL_BC12(x, v) (BITBAND_ACCESS32(HW_USBDCD_CONTROL_ADDR(x), BP_USBDCD_CONTROL_BC12) = (v)) /*@}*/ /*! * @name Register USBDCD_CONTROL, field START[24] (WORZ) * * Determines whether the charger detection sequence is initiated. * * Values: * - 0 - Do not start the sequence. Writes of this value have no effect. * - 1 - Initiate the charger detection sequence. If the sequence is already * running, writes of this value have no effect. */ /*@{*/ #define BP_USBDCD_CONTROL_START (24U) /*!< Bit position for USBDCD_CONTROL_START. */ #define BM_USBDCD_CONTROL_START (0x01000000U) /*!< Bit mask for USBDCD_CONTROL_START. */ #define BS_USBDCD_CONTROL_START (1U) /*!< Bit field size in bits for USBDCD_CONTROL_START. */ /*! @brief Format value for bitfield USBDCD_CONTROL_START. */ #define BF_USBDCD_CONTROL_START(v) ((uint32_t)((uint32_t)(v) << BP_USBDCD_CONTROL_START) & BM_USBDCD_CONTROL_START) /*! @brief Set the START field to a new value. */ #define BW_USBDCD_CONTROL_START(x, v) (BITBAND_ACCESS32(HW_USBDCD_CONTROL_ADDR(x), BP_USBDCD_CONTROL_START) = (v)) /*@}*/ /*! * @name Register USBDCD_CONTROL, field SR[25] (WORZ) * * Determines whether a software reset is performed. * * Values: * - 0 - Do not perform a software reset. * - 1 - Perform a software reset. */ /*@{*/ #define BP_USBDCD_CONTROL_SR (25U) /*!< Bit position for USBDCD_CONTROL_SR. */ #define BM_USBDCD_CONTROL_SR (0x02000000U) /*!< Bit mask for USBDCD_CONTROL_SR. */ #define BS_USBDCD_CONTROL_SR (1U) /*!< Bit field size in bits for USBDCD_CONTROL_SR. */ /*! @brief Format value for bitfield USBDCD_CONTROL_SR. */ #define BF_USBDCD_CONTROL_SR(v) ((uint32_t)((uint32_t)(v) << BP_USBDCD_CONTROL_SR) & BM_USBDCD_CONTROL_SR) /*! @brief Set the SR field to a new value. */ #define BW_USBDCD_CONTROL_SR(x, v) (BITBAND_ACCESS32(HW_USBDCD_CONTROL_ADDR(x), BP_USBDCD_CONTROL_SR) = (v)) /*@}*/ /******************************************************************************* * HW_USBDCD_CLOCK - Clock register ******************************************************************************/ /*! * @brief HW_USBDCD_CLOCK - Clock register (RW) * * Reset value: 0x000000C1U */ typedef union _hw_usbdcd_clock { uint32_t U; struct _hw_usbdcd_clock_bitfields { uint32_t CLOCK_UNIT : 1; /*!< [0] Unit of Measurement Encoding for * Clock Speed */ uint32_t RESERVED0 : 1; /*!< [1] */ uint32_t CLOCK_SPEED : 10; /*!< [11:2] Numerical Value of Clock Speed * in Binary */ uint32_t RESERVED1 : 20; /*!< [31:12] */ } B; } hw_usbdcd_clock_t; /*! * @name Constants and macros for entire USBDCD_CLOCK register */ /*@{*/ #define HW_USBDCD_CLOCK_ADDR(x) ((x) + 0x4U) #define HW_USBDCD_CLOCK(x) (*(__IO hw_usbdcd_clock_t *) HW_USBDCD_CLOCK_ADDR(x)) #define HW_USBDCD_CLOCK_RD(x) (HW_USBDCD_CLOCK(x).U) #define HW_USBDCD_CLOCK_WR(x, v) (HW_USBDCD_CLOCK(x).U = (v)) #define HW_USBDCD_CLOCK_SET(x, v) (HW_USBDCD_CLOCK_WR(x, HW_USBDCD_CLOCK_RD(x) | (v))) #define HW_USBDCD_CLOCK_CLR(x, v) (HW_USBDCD_CLOCK_WR(x, HW_USBDCD_CLOCK_RD(x) & ~(v))) #define HW_USBDCD_CLOCK_TOG(x, v) (HW_USBDCD_CLOCK_WR(x, HW_USBDCD_CLOCK_RD(x) ^ (v))) /*@}*/ /* * Constants & macros for individual USBDCD_CLOCK bitfields */ /*! * @name Register USBDCD_CLOCK, field CLOCK_UNIT[0] (RW) * * Specifies the unit of measure for the clock speed. * * Values: * - 0 - kHz Speed (between 1 kHz and 1023 kHz) * - 1 - MHz Speed (between 1 MHz and 1023 MHz) */ /*@{*/ #define BP_USBDCD_CLOCK_CLOCK_UNIT (0U) /*!< Bit position for USBDCD_CLOCK_CLOCK_UNIT. */ #define BM_USBDCD_CLOCK_CLOCK_UNIT (0x00000001U) /*!< Bit mask for USBDCD_CLOCK_CLOCK_UNIT. */ #define BS_USBDCD_CLOCK_CLOCK_UNIT (1U) /*!< Bit field size in bits for USBDCD_CLOCK_CLOCK_UNIT. */ /*! @brief Read current value of the USBDCD_CLOCK_CLOCK_UNIT field. */ #define BR_USBDCD_CLOCK_CLOCK_UNIT(x) (BITBAND_ACCESS32(HW_USBDCD_CLOCK_ADDR(x), BP_USBDCD_CLOCK_CLOCK_UNIT)) /*! @brief Format value for bitfield USBDCD_CLOCK_CLOCK_UNIT. */ #define BF_USBDCD_CLOCK_CLOCK_UNIT(v) ((uint32_t)((uint32_t)(v) << BP_USBDCD_CLOCK_CLOCK_UNIT) & BM_USBDCD_CLOCK_CLOCK_UNIT) /*! @brief Set the CLOCK_UNIT field to a new value. */ #define BW_USBDCD_CLOCK_CLOCK_UNIT(x, v) (BITBAND_ACCESS32(HW_USBDCD_CLOCK_ADDR(x), BP_USBDCD_CLOCK_CLOCK_UNIT) = (v)) /*@}*/ /*! * @name Register USBDCD_CLOCK, field CLOCK_SPEED[11:2] (RW) * * The unit of measure is programmed in CLOCK_UNIT. The valid range is from 1 to * 1023 when clock unit is MHz and 4 to 1023 when clock unit is kHz. Examples * with CLOCK_UNIT = 1: For 48 MHz: 0b00_0011_0000 (48) (Default) For 24 MHz: * 0b00_0001_1000 (24) Examples with CLOCK_UNIT = 0: For 100 kHz: 0b00_0110_0100 (100) * For 500 kHz: 0b01_1111_0100 (500) */ /*@{*/ #define BP_USBDCD_CLOCK_CLOCK_SPEED (2U) /*!< Bit position for USBDCD_CLOCK_CLOCK_SPEED. */ #define BM_USBDCD_CLOCK_CLOCK_SPEED (0x00000FFCU) /*!< Bit mask for USBDCD_CLOCK_CLOCK_SPEED. */ #define BS_USBDCD_CLOCK_CLOCK_SPEED (10U) /*!< Bit field size in bits for USBDCD_CLOCK_CLOCK_SPEED. */ /*! @brief Read current value of the USBDCD_CLOCK_CLOCK_SPEED field. */ #define BR_USBDCD_CLOCK_CLOCK_SPEED(x) (HW_USBDCD_CLOCK(x).B.CLOCK_SPEED) /*! @brief Format value for bitfield USBDCD_CLOCK_CLOCK_SPEED. */ #define BF_USBDCD_CLOCK_CLOCK_SPEED(v) ((uint32_t)((uint32_t)(v) << BP_USBDCD_CLOCK_CLOCK_SPEED) & BM_USBDCD_CLOCK_CLOCK_SPEED) /*! @brief Set the CLOCK_SPEED field to a new value. */ #define BW_USBDCD_CLOCK_CLOCK_SPEED(x, v) (HW_USBDCD_CLOCK_WR(x, (HW_USBDCD_CLOCK_RD(x) & ~BM_USBDCD_CLOCK_CLOCK_SPEED) | BF_USBDCD_CLOCK_CLOCK_SPEED(v))) /*@}*/ /******************************************************************************* * HW_USBDCD_STATUS - Status register ******************************************************************************/ /*! * @brief HW_USBDCD_STATUS - Status register (RO) * * Reset value: 0x00000000U * * Provides the current state of the module for system software monitoring. */ typedef union _hw_usbdcd_status { uint32_t U; struct _hw_usbdcd_status_bitfields { uint32_t RESERVED0 : 16; /*!< [15:0] */ uint32_t SEQ_RES : 2; /*!< [17:16] Charger Detection Sequence Results * */ uint32_t SEQ_STAT : 2; /*!< [19:18] Charger Detection Sequence Status * */ uint32_t ERR : 1; /*!< [20] Error Flag */ uint32_t TO : 1; /*!< [21] Timeout Flag */ uint32_t ACTIVE : 1; /*!< [22] Active Status Indicator */ uint32_t RESERVED1 : 9; /*!< [31:23] */ } B; } hw_usbdcd_status_t; /*! * @name Constants and macros for entire USBDCD_STATUS register */ /*@{*/ #define HW_USBDCD_STATUS_ADDR(x) ((x) + 0x8U) #define HW_USBDCD_STATUS(x) (*(__I hw_usbdcd_status_t *) HW_USBDCD_STATUS_ADDR(x)) #define HW_USBDCD_STATUS_RD(x) (HW_USBDCD_STATUS(x).U) /*@}*/ /* * Constants & macros for individual USBDCD_STATUS bitfields */ /*! * @name Register USBDCD_STATUS, field SEQ_RES[17:16] (RO) * * Reports how the charger detection is attached. * * Values: * - 00 - No results to report. * - 01 - Attached to a standard host. Must comply with USB 2.0 by drawing only * 2.5 mA (max) until connected. * - 10 - Attached to a charging port. The exact meaning depends on bit 18: 0: * Attached to either a charging host or a dedicated charger. The charger type * detection has not completed. 1: Attached to a charging host. The charger * type detection has completed. * - 11 - Attached to a dedicated charger. */ /*@{*/ #define BP_USBDCD_STATUS_SEQ_RES (16U) /*!< Bit position for USBDCD_STATUS_SEQ_RES. */ #define BM_USBDCD_STATUS_SEQ_RES (0x00030000U) /*!< Bit mask for USBDCD_STATUS_SEQ_RES. */ #define BS_USBDCD_STATUS_SEQ_RES (2U) /*!< Bit field size in bits for USBDCD_STATUS_SEQ_RES. */ /*! @brief Read current value of the USBDCD_STATUS_SEQ_RES field. */ #define BR_USBDCD_STATUS_SEQ_RES(x) (HW_USBDCD_STATUS(x).B.SEQ_RES) /*@}*/ /*! * @name Register USBDCD_STATUS, field SEQ_STAT[19:18] (RO) * * Indicates the status of the charger detection sequence. * * Values: * - 00 - The module is either not enabled, or the module is enabled but the * data pins have not yet been detected. * - 01 - Data pin contact detection is complete. * - 10 - Charging port detection is complete. * - 11 - Charger type detection is complete. */ /*@{*/ #define BP_USBDCD_STATUS_SEQ_STAT (18U) /*!< Bit position for USBDCD_STATUS_SEQ_STAT. */ #define BM_USBDCD_STATUS_SEQ_STAT (0x000C0000U) /*!< Bit mask for USBDCD_STATUS_SEQ_STAT. */ #define BS_USBDCD_STATUS_SEQ_STAT (2U) /*!< Bit field size in bits for USBDCD_STATUS_SEQ_STAT. */ /*! @brief Read current value of the USBDCD_STATUS_SEQ_STAT field. */ #define BR_USBDCD_STATUS_SEQ_STAT(x) (HW_USBDCD_STATUS(x).B.SEQ_STAT) /*@}*/ /*! * @name Register USBDCD_STATUS, field ERR[20] (RO) * * Indicates whether there is an error in the detection sequence. * * Values: * - 0 - No sequence errors. * - 1 - Error in the detection sequence. See the SEQ_STAT field to determine * the phase in which the error occurred. */ /*@{*/ #define BP_USBDCD_STATUS_ERR (20U) /*!< Bit position for USBDCD_STATUS_ERR. */ #define BM_USBDCD_STATUS_ERR (0x00100000U) /*!< Bit mask for USBDCD_STATUS_ERR. */ #define BS_USBDCD_STATUS_ERR (1U) /*!< Bit field size in bits for USBDCD_STATUS_ERR. */ /*! @brief Read current value of the USBDCD_STATUS_ERR field. */ #define BR_USBDCD_STATUS_ERR(x) (BITBAND_ACCESS32(HW_USBDCD_STATUS_ADDR(x), BP_USBDCD_STATUS_ERR)) /*@}*/ /*! * @name Register USBDCD_STATUS, field TO[21] (RO) * * Indicates whether the detection sequence has passed the timeout threshhold. * * Values: * - 0 - The detection sequence has not been running for over 1 s. * - 1 - It has been over 1 s since the data pin contact was detected and * debounced. */ /*@{*/ #define BP_USBDCD_STATUS_TO (21U) /*!< Bit position for USBDCD_STATUS_TO. */ #define BM_USBDCD_STATUS_TO (0x00200000U) /*!< Bit mask for USBDCD_STATUS_TO. */ #define BS_USBDCD_STATUS_TO (1U) /*!< Bit field size in bits for USBDCD_STATUS_TO. */ /*! @brief Read current value of the USBDCD_STATUS_TO field. */ #define BR_USBDCD_STATUS_TO(x) (BITBAND_ACCESS32(HW_USBDCD_STATUS_ADDR(x), BP_USBDCD_STATUS_TO)) /*@}*/ /*! * @name Register USBDCD_STATUS, field ACTIVE[22] (RO) * * Indicates whether the sequence is running. * * Values: * - 0 - The sequence is not running. * - 1 - The sequence is running. */ /*@{*/ #define BP_USBDCD_STATUS_ACTIVE (22U) /*!< Bit position for USBDCD_STATUS_ACTIVE. */ #define BM_USBDCD_STATUS_ACTIVE (0x00400000U) /*!< Bit mask for USBDCD_STATUS_ACTIVE. */ #define BS_USBDCD_STATUS_ACTIVE (1U) /*!< Bit field size in bits for USBDCD_STATUS_ACTIVE. */ /*! @brief Read current value of the USBDCD_STATUS_ACTIVE field. */ #define BR_USBDCD_STATUS_ACTIVE(x) (BITBAND_ACCESS32(HW_USBDCD_STATUS_ADDR(x), BP_USBDCD_STATUS_ACTIVE)) /*@}*/ /******************************************************************************* * HW_USBDCD_TIMER0 - TIMER0 register ******************************************************************************/ /*! * @brief HW_USBDCD_TIMER0 - TIMER0 register (RW) * * Reset value: 0x00100000U * * TIMER0 has an TSEQ_INIT field that represents the system latency in ms. * Latency is measured from the time when VBUS goes active until the time system * software initiates charger detection sequence in USBDCD module. When software sets * the CONTROL[START] bit, the Unit Connection Timer (TUNITCON) is initialized * with the value of TSEQ_INIT. Valid values are 0-1023, however the USB Battery * Charging Specification requires the entire sequence, including TSEQ_INIT, to be * completed in 1s or less. */ typedef union _hw_usbdcd_timer0 { uint32_t U; struct _hw_usbdcd_timer0_bitfields { uint32_t TUNITCON : 12; /*!< [11:0] Unit Connection Timer Elapse (in * ms) */ uint32_t RESERVED0 : 4; /*!< [15:12] */ uint32_t TSEQ_INIT : 10; /*!< [25:16] Sequence Initiation Time */ uint32_t RESERVED1 : 6; /*!< [31:26] */ } B; } hw_usbdcd_timer0_t; /*! * @name Constants and macros for entire USBDCD_TIMER0 register */ /*@{*/ #define HW_USBDCD_TIMER0_ADDR(x) ((x) + 0x10U) #define HW_USBDCD_TIMER0(x) (*(__IO hw_usbdcd_timer0_t *) HW_USBDCD_TIMER0_ADDR(x)) #define HW_USBDCD_TIMER0_RD(x) (HW_USBDCD_TIMER0(x).U) #define HW_USBDCD_TIMER0_WR(x, v) (HW_USBDCD_TIMER0(x).U = (v)) #define HW_USBDCD_TIMER0_SET(x, v) (HW_USBDCD_TIMER0_WR(x, HW_USBDCD_TIMER0_RD(x) | (v))) #define HW_USBDCD_TIMER0_CLR(x, v) (HW_USBDCD_TIMER0_WR(x, HW_USBDCD_TIMER0_RD(x) & ~(v))) #define HW_USBDCD_TIMER0_TOG(x, v) (HW_USBDCD_TIMER0_WR(x, HW_USBDCD_TIMER0_RD(x) ^ (v))) /*@}*/ /* * Constants & macros for individual USBDCD_TIMER0 bitfields */ /*! * @name Register USBDCD_TIMER0, field TUNITCON[11:0] (RO) * * Displays the amount of elapsed time since the event of setting the START bit * plus the value of TSEQ_INIT. The timer is automatically initialized with the * value of TSEQ_INIT before starting to count. This timer enables compliance with * the maximum time allowed to connect T UNIT_CON under the USB Battery Charging * Specification. If the timer reaches the one second limit, the module triggers * an interrupt and sets the error flag STATUS[ERR]. The timer continues * counting throughout the charger detection sequence, even when control has been passed * to software. As long as the module is active, the timer continues to count * until it reaches the maximum value of 0xFFF (4095 ms). The timer does not * rollover to zero. A software reset clears the timer. */ /*@{*/ #define BP_USBDCD_TIMER0_TUNITCON (0U) /*!< Bit position for USBDCD_TIMER0_TUNITCON. */ #define BM_USBDCD_TIMER0_TUNITCON (0x00000FFFU) /*!< Bit mask for USBDCD_TIMER0_TUNITCON. */ #define BS_USBDCD_TIMER0_TUNITCON (12U) /*!< Bit field size in bits for USBDCD_TIMER0_TUNITCON. */ /*! @brief Read current value of the USBDCD_TIMER0_TUNITCON field. */ #define BR_USBDCD_TIMER0_TUNITCON(x) (HW_USBDCD_TIMER0(x).B.TUNITCON) /*@}*/ /*! * @name Register USBDCD_TIMER0, field TSEQ_INIT[25:16] (RW) * * TSEQ_INIT represents the system latency (in ms) measured from the time VBUS * goes active to the time system software initiates the charger detection * sequence in the USBDCD module. When software sets the CONTROL[START] bit, the Unit * Connection Timer (TUNITCON) is initialized with the value of TSEQ_INIT. Valid * values are 0-1023, but the USB Battery Charging Specification requires the * entire sequence, including TSEQ_INIT, to be completed in 1s or less. */ /*@{*/ #define BP_USBDCD_TIMER0_TSEQ_INIT (16U) /*!< Bit position for USBDCD_TIMER0_TSEQ_INIT. */ #define BM_USBDCD_TIMER0_TSEQ_INIT (0x03FF0000U) /*!< Bit mask for USBDCD_TIMER0_TSEQ_INIT. */ #define BS_USBDCD_TIMER0_TSEQ_INIT (10U) /*!< Bit field size in bits for USBDCD_TIMER0_TSEQ_INIT. */ /*! @brief Read current value of the USBDCD_TIMER0_TSEQ_INIT field. */ #define BR_USBDCD_TIMER0_TSEQ_INIT(x) (HW_USBDCD_TIMER0(x).B.TSEQ_INIT) /*! @brief Format value for bitfield USBDCD_TIMER0_TSEQ_INIT. */ #define BF_USBDCD_TIMER0_TSEQ_INIT(v) ((uint32_t)((uint32_t)(v) << BP_USBDCD_TIMER0_TSEQ_INIT) & BM_USBDCD_TIMER0_TSEQ_INIT) /*! @brief Set the TSEQ_INIT field to a new value. */ #define BW_USBDCD_TIMER0_TSEQ_INIT(x, v) (HW_USBDCD_TIMER0_WR(x, (HW_USBDCD_TIMER0_RD(x) & ~BM_USBDCD_TIMER0_TSEQ_INIT) | BF_USBDCD_TIMER0_TSEQ_INIT(v))) /*@}*/ /******************************************************************************* * HW_USBDCD_TIMER1 - TIMER1 register ******************************************************************************/ /*! * @brief HW_USBDCD_TIMER1 - TIMER1 register (RW) * * Reset value: 0x000A0028U * * TIMER1 contains timing parameters. Note that register values can be written * that are not compliant with the USB Battery Charging Specification, so care * should be taken when overwriting the default values. */ typedef union _hw_usbdcd_timer1 { uint32_t U; struct _hw_usbdcd_timer1_bitfields { uint32_t TVDPSRC_ON : 10; /*!< [9:0] Time Period Comparator Enabled */ uint32_t RESERVED0 : 6; /*!< [15:10] */ uint32_t TDCD_DBNC : 10; /*!< [25:16] Time Period to Debounce D+ * Signal */ uint32_t RESERVED1 : 6; /*!< [31:26] */ } B; } hw_usbdcd_timer1_t; /*! * @name Constants and macros for entire USBDCD_TIMER1 register */ /*@{*/ #define HW_USBDCD_TIMER1_ADDR(x) ((x) + 0x14U) #define HW_USBDCD_TIMER1(x) (*(__IO hw_usbdcd_timer1_t *) HW_USBDCD_TIMER1_ADDR(x)) #define HW_USBDCD_TIMER1_RD(x) (HW_USBDCD_TIMER1(x).U) #define HW_USBDCD_TIMER1_WR(x, v) (HW_USBDCD_TIMER1(x).U = (v)) #define HW_USBDCD_TIMER1_SET(x, v) (HW_USBDCD_TIMER1_WR(x, HW_USBDCD_TIMER1_RD(x) | (v))) #define HW_USBDCD_TIMER1_CLR(x, v) (HW_USBDCD_TIMER1_WR(x, HW_USBDCD_TIMER1_RD(x) & ~(v))) #define HW_USBDCD_TIMER1_TOG(x, v) (HW_USBDCD_TIMER1_WR(x, HW_USBDCD_TIMER1_RD(x) ^ (v))) /*@}*/ /* * Constants & macros for individual USBDCD_TIMER1 bitfields */ /*! * @name Register USBDCD_TIMER1, field TVDPSRC_ON[9:0] (RW) * * This timing parameter is used after detection of the data pin. See "Charging * Port Detection". Valid values are 1-1023, but the USB Battery Charging * Specification requires a minimum value of 40 ms. */ /*@{*/ #define BP_USBDCD_TIMER1_TVDPSRC_ON (0U) /*!< Bit position for USBDCD_TIMER1_TVDPSRC_ON. */ #define BM_USBDCD_TIMER1_TVDPSRC_ON (0x000003FFU) /*!< Bit mask for USBDCD_TIMER1_TVDPSRC_ON. */ #define BS_USBDCD_TIMER1_TVDPSRC_ON (10U) /*!< Bit field size in bits for USBDCD_TIMER1_TVDPSRC_ON. */ /*! @brief Read current value of the USBDCD_TIMER1_TVDPSRC_ON field. */ #define BR_USBDCD_TIMER1_TVDPSRC_ON(x) (HW_USBDCD_TIMER1(x).B.TVDPSRC_ON) /*! @brief Format value for bitfield USBDCD_TIMER1_TVDPSRC_ON. */ #define BF_USBDCD_TIMER1_TVDPSRC_ON(v) ((uint32_t)((uint32_t)(v) << BP_USBDCD_TIMER1_TVDPSRC_ON) & BM_USBDCD_TIMER1_TVDPSRC_ON) /*! @brief Set the TVDPSRC_ON field to a new value. */ #define BW_USBDCD_TIMER1_TVDPSRC_ON(x, v) (HW_USBDCD_TIMER1_WR(x, (HW_USBDCD_TIMER1_RD(x) & ~BM_USBDCD_TIMER1_TVDPSRC_ON) | BF_USBDCD_TIMER1_TVDPSRC_ON(v))) /*@}*/ /*! * @name Register USBDCD_TIMER1, field TDCD_DBNC[25:16] (RW) * * Sets the time period (ms) to debounce the D+ signal during the data pin * contact detection phase. See "Debouncing the data pin contact" Valid values are * 1-1023, but the USB Battery Charging Specification requires a minimum value of 10 * ms. */ /*@{*/ #define BP_USBDCD_TIMER1_TDCD_DBNC (16U) /*!< Bit position for USBDCD_TIMER1_TDCD_DBNC. */ #define BM_USBDCD_TIMER1_TDCD_DBNC (0x03FF0000U) /*!< Bit mask for USBDCD_TIMER1_TDCD_DBNC. */ #define BS_USBDCD_TIMER1_TDCD_DBNC (10U) /*!< Bit field size in bits for USBDCD_TIMER1_TDCD_DBNC. */ /*! @brief Read current value of the USBDCD_TIMER1_TDCD_DBNC field. */ #define BR_USBDCD_TIMER1_TDCD_DBNC(x) (HW_USBDCD_TIMER1(x).B.TDCD_DBNC) /*! @brief Format value for bitfield USBDCD_TIMER1_TDCD_DBNC. */ #define BF_USBDCD_TIMER1_TDCD_DBNC(v) ((uint32_t)((uint32_t)(v) << BP_USBDCD_TIMER1_TDCD_DBNC) & BM_USBDCD_TIMER1_TDCD_DBNC) /*! @brief Set the TDCD_DBNC field to a new value. */ #define BW_USBDCD_TIMER1_TDCD_DBNC(x, v) (HW_USBDCD_TIMER1_WR(x, (HW_USBDCD_TIMER1_RD(x) & ~BM_USBDCD_TIMER1_TDCD_DBNC) | BF_USBDCD_TIMER1_TDCD_DBNC(v))) /*@}*/ /******************************************************************************* * HW_USBDCD_TIMER2_BC11 - TIMER2_BC11 register ******************************************************************************/ /*! * @brief HW_USBDCD_TIMER2_BC11 - TIMER2_BC11 register (RW) * * Reset value: 0x00280001U * * TIMER2_BC11 contains timing parameters for USB Battery Charging * Specification, v1.1. Register values can be written that are not compliant with the USB * Battery Charging Specification, so care should be taken when overwriting the * default values. */ typedef union _hw_usbdcd_timer2_bc11 { uint32_t U; struct _hw_usbdcd_timer2_bc11_bitfields { uint32_t CHECK_DM : 4; /*!< [3:0] Time Before Check of D- Line */ uint32_t RESERVED0 : 12; /*!< [15:4] */ uint32_t TVDPSRC_CON : 10; /*!< [25:16] Time Period Before Enabling * D+ Pullup */ uint32_t RESERVED1 : 6; /*!< [31:26] */ } B; } hw_usbdcd_timer2_bc11_t; /*! * @name Constants and macros for entire USBDCD_TIMER2_BC11 register */ /*@{*/ #define HW_USBDCD_TIMER2_BC11_ADDR(x) ((x) + 0x18U) #define HW_USBDCD_TIMER2_BC11(x) (*(__IO hw_usbdcd_timer2_bc11_t *) HW_USBDCD_TIMER2_BC11_ADDR(x)) #define HW_USBDCD_TIMER2_BC11_RD(x) (HW_USBDCD_TIMER2_BC11(x).U) #define HW_USBDCD_TIMER2_BC11_WR(x, v) (HW_USBDCD_TIMER2_BC11(x).U = (v)) #define HW_USBDCD_TIMER2_BC11_SET(x, v) (HW_USBDCD_TIMER2_BC11_WR(x, HW_USBDCD_TIMER2_BC11_RD(x) | (v))) #define HW_USBDCD_TIMER2_BC11_CLR(x, v) (HW_USBDCD_TIMER2_BC11_WR(x, HW_USBDCD_TIMER2_BC11_RD(x) & ~(v))) #define HW_USBDCD_TIMER2_BC11_TOG(x, v) (HW_USBDCD_TIMER2_BC11_WR(x, HW_USBDCD_TIMER2_BC11_RD(x) ^ (v))) /*@}*/ /* * Constants & macros for individual USBDCD_TIMER2_BC11 bitfields */ /*! * @name Register USBDCD_TIMER2_BC11, field CHECK_DM[3:0] (RW) * * Sets the amount of time (in ms) that the module waits after the device * connects to the USB bus until checking the state of the D- line to determine the * type of charging port. See "Charger Type Detection." Valid values are 1-15ms. */ /*@{*/ #define BP_USBDCD_TIMER2_BC11_CHECK_DM (0U) /*!< Bit position for USBDCD_TIMER2_BC11_CHECK_DM. */ #define BM_USBDCD_TIMER2_BC11_CHECK_DM (0x0000000FU) /*!< Bit mask for USBDCD_TIMER2_BC11_CHECK_DM. */ #define BS_USBDCD_TIMER2_BC11_CHECK_DM (4U) /*!< Bit field size in bits for USBDCD_TIMER2_BC11_CHECK_DM. */ /*! @brief Read current value of the USBDCD_TIMER2_BC11_CHECK_DM field. */ #define BR_USBDCD_TIMER2_BC11_CHECK_DM(x) (HW_USBDCD_TIMER2_BC11(x).B.CHECK_DM) /*! @brief Format value for bitfield USBDCD_TIMER2_BC11_CHECK_DM. */ #define BF_USBDCD_TIMER2_BC11_CHECK_DM(v) ((uint32_t)((uint32_t)(v) << BP_USBDCD_TIMER2_BC11_CHECK_DM) & BM_USBDCD_TIMER2_BC11_CHECK_DM) /*! @brief Set the CHECK_DM field to a new value. */ #define BW_USBDCD_TIMER2_BC11_CHECK_DM(x, v) (HW_USBDCD_TIMER2_BC11_WR(x, (HW_USBDCD_TIMER2_BC11_RD(x) & ~BM_USBDCD_TIMER2_BC11_CHECK_DM) | BF_USBDCD_TIMER2_BC11_CHECK_DM(v))) /*@}*/ /*! * @name Register USBDCD_TIMER2_BC11, field TVDPSRC_CON[25:16] (RW) * * Sets the time period (ms) that the module waits after charging port detection * before system software must enable the D+ pullup to connect to the USB host. * Valid values are 1-1023, but the USB Battery Charging Specification requires a * minimum value of 40 ms. */ /*@{*/ #define BP_USBDCD_TIMER2_BC11_TVDPSRC_CON (16U) /*!< Bit position for USBDCD_TIMER2_BC11_TVDPSRC_CON. */ #define BM_USBDCD_TIMER2_BC11_TVDPSRC_CON (0x03FF0000U) /*!< Bit mask for USBDCD_TIMER2_BC11_TVDPSRC_CON. */ #define BS_USBDCD_TIMER2_BC11_TVDPSRC_CON (10U) /*!< Bit field size in bits for USBDCD_TIMER2_BC11_TVDPSRC_CON. */ /*! @brief Read current value of the USBDCD_TIMER2_BC11_TVDPSRC_CON field. */ #define BR_USBDCD_TIMER2_BC11_TVDPSRC_CON(x) (HW_USBDCD_TIMER2_BC11(x).B.TVDPSRC_CON) /*! @brief Format value for bitfield USBDCD_TIMER2_BC11_TVDPSRC_CON. */ #define BF_USBDCD_TIMER2_BC11_TVDPSRC_CON(v) ((uint32_t)((uint32_t)(v) << BP_USBDCD_TIMER2_BC11_TVDPSRC_CON) & BM_USBDCD_TIMER2_BC11_TVDPSRC_CON) /*! @brief Set the TVDPSRC_CON field to a new value. */ #define BW_USBDCD_TIMER2_BC11_TVDPSRC_CON(x, v) (HW_USBDCD_TIMER2_BC11_WR(x, (HW_USBDCD_TIMER2_BC11_RD(x) & ~BM_USBDCD_TIMER2_BC11_TVDPSRC_CON) | BF_USBDCD_TIMER2_BC11_TVDPSRC_CON(v))) /*@}*/ /******************************************************************************* * HW_USBDCD_TIMER2_BC12 - TIMER2_BC12 register ******************************************************************************/ /*! * @brief HW_USBDCD_TIMER2_BC12 - TIMER2_BC12 register (RW) * * Reset value: 0x00010028U * * TIMER2_BC12 contains timing parameters for USB Battery Charging * Specification, v1.2. Register values can be written that are not compliant with the USB * Battery Charging Specification, so care should be taken when overwriting the * default values. */ typedef union _hw_usbdcd_timer2_bc12 { uint32_t U; struct _hw_usbdcd_timer2_bc12_bitfields { uint32_t TVDMSRC_ON : 10; /*!< [9:0] */ uint32_t RESERVED0 : 6; /*!< [15:10] */ uint32_t TWAIT_AFTER_PRD : 10; /*!< [25:16] */ uint32_t RESERVED1 : 6; /*!< [31:26] */ } B; } hw_usbdcd_timer2_bc12_t; /*! * @name Constants and macros for entire USBDCD_TIMER2_BC12 register */ /*@{*/ #define HW_USBDCD_TIMER2_BC12_ADDR(x) ((x) + 0x18U) #define HW_USBDCD_TIMER2_BC12(x) (*(__IO hw_usbdcd_timer2_bc12_t *) HW_USBDCD_TIMER2_BC12_ADDR(x)) #define HW_USBDCD_TIMER2_BC12_RD(x) (HW_USBDCD_TIMER2_BC12(x).U) #define HW_USBDCD_TIMER2_BC12_WR(x, v) (HW_USBDCD_TIMER2_BC12(x).U = (v)) #define HW_USBDCD_TIMER2_BC12_SET(x, v) (HW_USBDCD_TIMER2_BC12_WR(x, HW_USBDCD_TIMER2_BC12_RD(x) | (v))) #define HW_USBDCD_TIMER2_BC12_CLR(x, v) (HW_USBDCD_TIMER2_BC12_WR(x, HW_USBDCD_TIMER2_BC12_RD(x) & ~(v))) #define HW_USBDCD_TIMER2_BC12_TOG(x, v) (HW_USBDCD_TIMER2_BC12_WR(x, HW_USBDCD_TIMER2_BC12_RD(x) ^ (v))) /*@}*/ /* * Constants & macros for individual USBDCD_TIMER2_BC12 bitfields */ /*! * @name Register USBDCD_TIMER2_BC12, field TVDMSRC_ON[9:0] (RW) * * Sets the amount of time (in ms) that the module enables the VDM_SRC. Valid * values are 0-40ms. */ /*@{*/ #define BP_USBDCD_TIMER2_BC12_TVDMSRC_ON (0U) /*!< Bit position for USBDCD_TIMER2_BC12_TVDMSRC_ON. */ #define BM_USBDCD_TIMER2_BC12_TVDMSRC_ON (0x000003FFU) /*!< Bit mask for USBDCD_TIMER2_BC12_TVDMSRC_ON. */ #define BS_USBDCD_TIMER2_BC12_TVDMSRC_ON (10U) /*!< Bit field size in bits for USBDCD_TIMER2_BC12_TVDMSRC_ON. */ /*! @brief Read current value of the USBDCD_TIMER2_BC12_TVDMSRC_ON field. */ #define BR_USBDCD_TIMER2_BC12_TVDMSRC_ON(x) (HW_USBDCD_TIMER2_BC12(x).B.TVDMSRC_ON) /*! @brief Format value for bitfield USBDCD_TIMER2_BC12_TVDMSRC_ON. */ #define BF_USBDCD_TIMER2_BC12_TVDMSRC_ON(v) ((uint32_t)((uint32_t)(v) << BP_USBDCD_TIMER2_BC12_TVDMSRC_ON) & BM_USBDCD_TIMER2_BC12_TVDMSRC_ON) /*! @brief Set the TVDMSRC_ON field to a new value. */ #define BW_USBDCD_TIMER2_BC12_TVDMSRC_ON(x, v) (HW_USBDCD_TIMER2_BC12_WR(x, (HW_USBDCD_TIMER2_BC12_RD(x) & ~BM_USBDCD_TIMER2_BC12_TVDMSRC_ON) | BF_USBDCD_TIMER2_BC12_TVDMSRC_ON(v))) /*@}*/ /*! * @name Register USBDCD_TIMER2_BC12, field TWAIT_AFTER_PRD[25:16] (RW) * * Sets the amount of time (in ms) that the module waits after primary detection * before start to secondary detection. Valid values are 1-1023ms. Default is * 1ms. */ /*@{*/ #define BP_USBDCD_TIMER2_BC12_TWAIT_AFTER_PRD (16U) /*!< Bit position for USBDCD_TIMER2_BC12_TWAIT_AFTER_PRD. */ #define BM_USBDCD_TIMER2_BC12_TWAIT_AFTER_PRD (0x03FF0000U) /*!< Bit mask for USBDCD_TIMER2_BC12_TWAIT_AFTER_PRD. */ #define BS_USBDCD_TIMER2_BC12_TWAIT_AFTER_PRD (10U) /*!< Bit field size in bits for USBDCD_TIMER2_BC12_TWAIT_AFTER_PRD. */ /*! @brief Read current value of the USBDCD_TIMER2_BC12_TWAIT_AFTER_PRD field. */ #define BR_USBDCD_TIMER2_BC12_TWAIT_AFTER_PRD(x) (HW_USBDCD_TIMER2_BC12(x).B.TWAIT_AFTER_PRD) /*! @brief Format value for bitfield USBDCD_TIMER2_BC12_TWAIT_AFTER_PRD. */ #define BF_USBDCD_TIMER2_BC12_TWAIT_AFTER_PRD(v) ((uint32_t)((uint32_t)(v) << BP_USBDCD_TIMER2_BC12_TWAIT_AFTER_PRD) & BM_USBDCD_TIMER2_BC12_TWAIT_AFTER_PRD) /*! @brief Set the TWAIT_AFTER_PRD field to a new value. */ #define BW_USBDCD_TIMER2_BC12_TWAIT_AFTER_PRD(x, v) (HW_USBDCD_TIMER2_BC12_WR(x, (HW_USBDCD_TIMER2_BC12_RD(x) & ~BM_USBDCD_TIMER2_BC12_TWAIT_AFTER_PRD) | BF_USBDCD_TIMER2_BC12_TWAIT_AFTER_PRD(v))) /*@}*/ /* ** Start of section using anonymous unions */ #if defined(__ARMCC_VERSION) #pragma push #pragma anon_unions #elif defined(__CWCC__) #pragma push #pragma cpp_extensions on #elif defined(__GNUC__) /* anonymous unions are enabled by default */ #elif defined(__IAR_SYSTEMS_ICC__) #pragma language=extended #else #error Not supported compiler type #endif /******************************************************************************* * hw_usbdcd_t - module struct ******************************************************************************/ /*! * @brief All USBDCD module registers. */ #pragma pack(1) typedef struct _hw_usbdcd { __IO hw_usbdcd_control_t CONTROL; /*!< [0x0] Control register */ __IO hw_usbdcd_clock_t CLOCK; /*!< [0x4] Clock register */ __I hw_usbdcd_status_t STATUS; /*!< [0x8] Status register */ uint8_t _reserved0[4]; __IO hw_usbdcd_timer0_t TIMER0; /*!< [0x10] TIMER0 register */ __IO hw_usbdcd_timer1_t TIMER1; /*!< [0x14] TIMER1 register */ union { __IO hw_usbdcd_timer2_bc11_t TIMER2_BC11; /*!< [0x18] TIMER2_BC11 register */ __IO hw_usbdcd_timer2_bc12_t TIMER2_BC12; /*!< [0x18] TIMER2_BC12 register */ }; } hw_usbdcd_t; #pragma pack() /*! @brief Macro to access all USBDCD registers. */ /*! @param x USBDCD module instance base address. */ /*! @return Reference (not a pointer) to the registers struct. To get a pointer to the struct, * use the '&' operator, like &HW_USBDCD(USBDCD_BASE). */ #define HW_USBDCD(x) (*(hw_usbdcd_t *)(x)) /* ** End of section using anonymous unions */ #if defined(__ARMCC_VERSION) #pragma pop #elif defined(__CWCC__) #pragma pop #elif defined(__GNUC__) /* leave anonymous unions enabled */ #elif defined(__IAR_SYSTEMS_ICC__) #pragma language=default #else #error Not supported compiler type #endif #endif /* __HW_USBDCD_REGISTERS_H__ */ /* EOF */ ================================================ FILE: Zelig/mbed/TARGET_K64F/TARGET_Freescale/TARGET_KPSDK_MCUS/TARGET_MCU_K64F/device/device/MK64F12/MK64F12_vref.h ================================================ /* ** ################################################################### ** Compilers: Keil ARM C/C++ Compiler ** Freescale C/C++ for Embedded ARM ** GNU C Compiler ** IAR ANSI C/C++ Compiler for ARM ** ** Reference manual: K64P144M120SF5RM, Rev.2, January 2014 ** Version: rev. 2.5, 2014-02-10 ** Build: b140604 ** ** Abstract: ** Extension to the CMSIS register access layer header. ** ** Copyright (c) 2014 Freescale Semiconductor, Inc. ** All rights reserved. ** ** Redistribution and use in source and binary forms, with or without modification, ** are permitted provided that the following conditions are met: ** ** o Redistributions of source code must retain the above copyright notice, this list ** of conditions and the following disclaimer. ** ** o Redistributions in binary form must reproduce the above copyright notice, this ** list of conditions and the following disclaimer in the documentation and/or ** other materials provided with the distribution. ** ** o Neither the name of Freescale Semiconductor, Inc. nor the names of its ** contributors may be used to endorse or promote products derived from this ** software without specific prior written permission. ** ** THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ** ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED ** WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE ** DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT 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. ** ** http: www.freescale.com ** mail: support@freescale.com ** ** Revisions: ** - rev. 1.0 (2013-08-12) ** Initial version. ** - rev. 2.0 (2013-10-29) ** Register accessor macros added to the memory map. ** Symbols for Processor Expert memory map compatibility added to the memory map. ** Startup file for gcc has been updated according to CMSIS 3.2. ** System initialization updated. ** MCG - registers updated. ** PORTA, PORTB, PORTC, PORTE - registers for digital filter removed. ** - rev. 2.1 (2013-10-30) ** Definition of BITBAND macros updated to support peripherals with 32-bit acces disabled. ** - rev. 2.2 (2013-12-09) ** DMA - EARS register removed. ** AIPS0, AIPS1 - MPRA register updated. ** - rev. 2.3 (2014-01-24) ** Update according to reference manual rev. 2 ** ENET, MCG, MCM, SIM, USB - registers updated ** - rev. 2.4 (2014-02-10) ** The declaration of clock configurations has been moved to separate header file system_MK64F12.h ** Update of SystemInit() and SystemCoreClockUpdate() functions. ** - rev. 2.5 (2014-02-10) ** The declaration of clock configurations has been moved to separate header file system_MK64F12.h ** Update of SystemInit() and SystemCoreClockUpdate() functions. ** Module access macro module_BASES replaced by module_BASE_PTRS. ** ** ################################################################### */ /* * WARNING! DO NOT EDIT THIS FILE DIRECTLY! * * This file was generated automatically and any changes may be lost. */ #ifndef __HW_VREF_REGISTERS_H__ #define __HW_VREF_REGISTERS_H__ #include "MK64F12.h" #include "fsl_bitaccess.h" /* * MK64F12 VREF * * Voltage Reference * * Registers defined in this header file: * - HW_VREF_TRM - VREF Trim Register * - HW_VREF_SC - VREF Status and Control Register * * - hw_vref_t - Struct containing all module registers. */ #define HW_VREF_INSTANCE_COUNT (1U) /*!< Number of instances of the VREF module. */ /******************************************************************************* * HW_VREF_TRM - VREF Trim Register ******************************************************************************/ /*! * @brief HW_VREF_TRM - VREF Trim Register (RW) * * Reset value: 0x00U * * This register contains bits that contain the trim data for the Voltage * Reference. */ typedef union _hw_vref_trm { uint8_t U; struct _hw_vref_trm_bitfields { uint8_t TRIM : 6; /*!< [5:0] Trim bits */ uint8_t CHOPEN : 1; /*!< [6] Chop oscillator enable. When set, * internal chopping operation is enabled and the internal analog offset will be * minimized. */ uint8_t RESERVED0 : 1; /*!< [7] */ } B; } hw_vref_trm_t; /*! * @name Constants and macros for entire VREF_TRM register */ /*@{*/ #define HW_VREF_TRM_ADDR(x) ((x) + 0x0U) #define HW_VREF_TRM(x) (*(__IO hw_vref_trm_t *) HW_VREF_TRM_ADDR(x)) #define HW_VREF_TRM_RD(x) (HW_VREF_TRM(x).U) #define HW_VREF_TRM_WR(x, v) (HW_VREF_TRM(x).U = (v)) #define HW_VREF_TRM_SET(x, v) (HW_VREF_TRM_WR(x, HW_VREF_TRM_RD(x) | (v))) #define HW_VREF_TRM_CLR(x, v) (HW_VREF_TRM_WR(x, HW_VREF_TRM_RD(x) & ~(v))) #define HW_VREF_TRM_TOG(x, v) (HW_VREF_TRM_WR(x, HW_VREF_TRM_RD(x) ^ (v))) /*@}*/ /* * Constants & macros for individual VREF_TRM bitfields */ /*! * @name Register VREF_TRM, field TRIM[5:0] (RW) * * These bits change the resulting VREF by approximately +/- 0.5 mV for each * step. Min = minimum and max = maximum voltage reference output. For minimum and * maximum voltage reference output values, refer to the Data Sheet for this chip. * * Values: * - 000000 - Min * - 111111 - Max */ /*@{*/ #define BP_VREF_TRM_TRIM (0U) /*!< Bit position for VREF_TRM_TRIM. */ #define BM_VREF_TRM_TRIM (0x3FU) /*!< Bit mask for VREF_TRM_TRIM. */ #define BS_VREF_TRM_TRIM (6U) /*!< Bit field size in bits for VREF_TRM_TRIM. */ /*! @brief Read current value of the VREF_TRM_TRIM field. */ #define BR_VREF_TRM_TRIM(x) (HW_VREF_TRM(x).B.TRIM) /*! @brief Format value for bitfield VREF_TRM_TRIM. */ #define BF_VREF_TRM_TRIM(v) ((uint8_t)((uint8_t)(v) << BP_VREF_TRM_TRIM) & BM_VREF_TRM_TRIM) /*! @brief Set the TRIM field to a new value. */ #define BW_VREF_TRM_TRIM(x, v) (HW_VREF_TRM_WR(x, (HW_VREF_TRM_RD(x) & ~BM_VREF_TRM_TRIM) | BF_VREF_TRM_TRIM(v))) /*@}*/ /*! * @name Register VREF_TRM, field CHOPEN[6] (RW) * * This bit is set during factory trimming of the VREF voltage. This bit should * be written to 1 to achieve the performance stated in the data sheet. * * Values: * - 0 - Chop oscillator is disabled. * - 1 - Chop oscillator is enabled. */ /*@{*/ #define BP_VREF_TRM_CHOPEN (6U) /*!< Bit position for VREF_TRM_CHOPEN. */ #define BM_VREF_TRM_CHOPEN (0x40U) /*!< Bit mask for VREF_TRM_CHOPEN. */ #define BS_VREF_TRM_CHOPEN (1U) /*!< Bit field size in bits for VREF_TRM_CHOPEN. */ /*! @brief Read current value of the VREF_TRM_CHOPEN field. */ #define BR_VREF_TRM_CHOPEN(x) (BITBAND_ACCESS8(HW_VREF_TRM_ADDR(x), BP_VREF_TRM_CHOPEN)) /*! @brief Format value for bitfield VREF_TRM_CHOPEN. */ #define BF_VREF_TRM_CHOPEN(v) ((uint8_t)((uint8_t)(v) << BP_VREF_TRM_CHOPEN) & BM_VREF_TRM_CHOPEN) /*! @brief Set the CHOPEN field to a new value. */ #define BW_VREF_TRM_CHOPEN(x, v) (BITBAND_ACCESS8(HW_VREF_TRM_ADDR(x), BP_VREF_TRM_CHOPEN) = (v)) /*@}*/ /******************************************************************************* * HW_VREF_SC - VREF Status and Control Register ******************************************************************************/ /*! * @brief HW_VREF_SC - VREF Status and Control Register (RW) * * Reset value: 0x00U * * This register contains the control bits used to enable the internal voltage * reference and to select the buffer mode to be used. */ typedef union _hw_vref_sc { uint8_t U; struct _hw_vref_sc_bitfields { uint8_t MODE_LV : 2; /*!< [1:0] Buffer Mode selection */ uint8_t VREFST : 1; /*!< [2] Internal Voltage Reference stable */ uint8_t RESERVED0 : 2; /*!< [4:3] */ uint8_t ICOMPEN : 1; /*!< [5] Second order curvature compensation * enable */ uint8_t REGEN : 1; /*!< [6] Regulator enable */ uint8_t VREFEN : 1; /*!< [7] Internal Voltage Reference enable */ } B; } hw_vref_sc_t; /*! * @name Constants and macros for entire VREF_SC register */ /*@{*/ #define HW_VREF_SC_ADDR(x) ((x) + 0x1U) #define HW_VREF_SC(x) (*(__IO hw_vref_sc_t *) HW_VREF_SC_ADDR(x)) #define HW_VREF_SC_RD(x) (HW_VREF_SC(x).U) #define HW_VREF_SC_WR(x, v) (HW_VREF_SC(x).U = (v)) #define HW_VREF_SC_SET(x, v) (HW_VREF_SC_WR(x, HW_VREF_SC_RD(x) | (v))) #define HW_VREF_SC_CLR(x, v) (HW_VREF_SC_WR(x, HW_VREF_SC_RD(x) & ~(v))) #define HW_VREF_SC_TOG(x, v) (HW_VREF_SC_WR(x, HW_VREF_SC_RD(x) ^ (v))) /*@}*/ /* * Constants & macros for individual VREF_SC bitfields */ /*! * @name Register VREF_SC, field MODE_LV[1:0] (RW) * * These bits select the buffer modes for the Voltage Reference module. * * Values: * - 00 - Bandgap on only, for stabilization and startup * - 01 - High power buffer mode enabled * - 10 - Low-power buffer mode enabled * - 11 - Reserved */ /*@{*/ #define BP_VREF_SC_MODE_LV (0U) /*!< Bit position for VREF_SC_MODE_LV. */ #define BM_VREF_SC_MODE_LV (0x03U) /*!< Bit mask for VREF_SC_MODE_LV. */ #define BS_VREF_SC_MODE_LV (2U) /*!< Bit field size in bits for VREF_SC_MODE_LV. */ /*! @brief Read current value of the VREF_SC_MODE_LV field. */ #define BR_VREF_SC_MODE_LV(x) (HW_VREF_SC(x).B.MODE_LV) /*! @brief Format value for bitfield VREF_SC_MODE_LV. */ #define BF_VREF_SC_MODE_LV(v) ((uint8_t)((uint8_t)(v) << BP_VREF_SC_MODE_LV) & BM_VREF_SC_MODE_LV) /*! @brief Set the MODE_LV field to a new value. */ #define BW_VREF_SC_MODE_LV(x, v) (HW_VREF_SC_WR(x, (HW_VREF_SC_RD(x) & ~BM_VREF_SC_MODE_LV) | BF_VREF_SC_MODE_LV(v))) /*@}*/ /*! * @name Register VREF_SC, field VREFST[2] (RO) * * This bit indicates that the bandgap reference within the Voltage Reference * module has completed its startup and stabilization. * * Values: * - 0 - The module is disabled or not stable. * - 1 - The module is stable. */ /*@{*/ #define BP_VREF_SC_VREFST (2U) /*!< Bit position for VREF_SC_VREFST. */ #define BM_VREF_SC_VREFST (0x04U) /*!< Bit mask for VREF_SC_VREFST. */ #define BS_VREF_SC_VREFST (1U) /*!< Bit field size in bits for VREF_SC_VREFST. */ /*! @brief Read current value of the VREF_SC_VREFST field. */ #define BR_VREF_SC_VREFST(x) (BITBAND_ACCESS8(HW_VREF_SC_ADDR(x), BP_VREF_SC_VREFST)) /*@}*/ /*! * @name Register VREF_SC, field ICOMPEN[5] (RW) * * This bit is set during factory trimming of the VREF voltage. This bit should * be written to 1 to achieve the performance stated in the data sheet. * * Values: * - 0 - Disabled * - 1 - Enabled */ /*@{*/ #define BP_VREF_SC_ICOMPEN (5U) /*!< Bit position for VREF_SC_ICOMPEN. */ #define BM_VREF_SC_ICOMPEN (0x20U) /*!< Bit mask for VREF_SC_ICOMPEN. */ #define BS_VREF_SC_ICOMPEN (1U) /*!< Bit field size in bits for VREF_SC_ICOMPEN. */ /*! @brief Read current value of the VREF_SC_ICOMPEN field. */ #define BR_VREF_SC_ICOMPEN(x) (BITBAND_ACCESS8(HW_VREF_SC_ADDR(x), BP_VREF_SC_ICOMPEN)) /*! @brief Format value for bitfield VREF_SC_ICOMPEN. */ #define BF_VREF_SC_ICOMPEN(v) ((uint8_t)((uint8_t)(v) << BP_VREF_SC_ICOMPEN) & BM_VREF_SC_ICOMPEN) /*! @brief Set the ICOMPEN field to a new value. */ #define BW_VREF_SC_ICOMPEN(x, v) (BITBAND_ACCESS8(HW_VREF_SC_ADDR(x), BP_VREF_SC_ICOMPEN) = (v)) /*@}*/ /*! * @name Register VREF_SC, field REGEN[6] (RW) * * This bit is used to enable the internal 1.75 V regulator to produce a * constant internal voltage supply in order to reduce the sensitivity to external * supply noise and variation. If it is desired to keep the regulator enabled in very * low power modes, refer to the Chip Configuration details for a description on * how this can be achieved. This bit is set during factory trimming of the VREF * voltage. This bit should be written to 1 to achieve the performance stated in * the data sheet. * * Values: * - 0 - Internal 1.75 V regulator is disabled. * - 1 - Internal 1.75 V regulator is enabled. */ /*@{*/ #define BP_VREF_SC_REGEN (6U) /*!< Bit position for VREF_SC_REGEN. */ #define BM_VREF_SC_REGEN (0x40U) /*!< Bit mask for VREF_SC_REGEN. */ #define BS_VREF_SC_REGEN (1U) /*!< Bit field size in bits for VREF_SC_REGEN. */ /*! @brief Read current value of the VREF_SC_REGEN field. */ #define BR_VREF_SC_REGEN(x) (BITBAND_ACCESS8(HW_VREF_SC_ADDR(x), BP_VREF_SC_REGEN)) /*! @brief Format value for bitfield VREF_SC_REGEN. */ #define BF_VREF_SC_REGEN(v) ((uint8_t)((uint8_t)(v) << BP_VREF_SC_REGEN) & BM_VREF_SC_REGEN) /*! @brief Set the REGEN field to a new value. */ #define BW_VREF_SC_REGEN(x, v) (BITBAND_ACCESS8(HW_VREF_SC_ADDR(x), BP_VREF_SC_REGEN) = (v)) /*@}*/ /*! * @name Register VREF_SC, field VREFEN[7] (RW) * * This bit is used to enable the bandgap reference within the Voltage Reference * module. After the VREF is enabled, turning off the clock to the VREF module * via the corresponding clock gate register will not disable the VREF. VREF must * be disabled via this VREFEN bit. * * Values: * - 0 - The module is disabled. * - 1 - The module is enabled. */ /*@{*/ #define BP_VREF_SC_VREFEN (7U) /*!< Bit position for VREF_SC_VREFEN. */ #define BM_VREF_SC_VREFEN (0x80U) /*!< Bit mask for VREF_SC_VREFEN. */ #define BS_VREF_SC_VREFEN (1U) /*!< Bit field size in bits for VREF_SC_VREFEN. */ /*! @brief Read current value of the VREF_SC_VREFEN field. */ #define BR_VREF_SC_VREFEN(x) (BITBAND_ACCESS8(HW_VREF_SC_ADDR(x), BP_VREF_SC_VREFEN)) /*! @brief Format value for bitfield VREF_SC_VREFEN. */ #define BF_VREF_SC_VREFEN(v) ((uint8_t)((uint8_t)(v) << BP_VREF_SC_VREFEN) & BM_VREF_SC_VREFEN) /*! @brief Set the VREFEN field to a new value. */ #define BW_VREF_SC_VREFEN(x, v) (BITBAND_ACCESS8(HW_VREF_SC_ADDR(x), BP_VREF_SC_VREFEN) = (v)) /*@}*/ /******************************************************************************* * hw_vref_t - module struct ******************************************************************************/ /*! * @brief All VREF module registers. */ #pragma pack(1) typedef struct _hw_vref { __IO hw_vref_trm_t TRM; /*!< [0x0] VREF Trim Register */ __IO hw_vref_sc_t SC; /*!< [0x1] VREF Status and Control Register */ } hw_vref_t; #pragma pack() /*! @brief Macro to access all VREF registers. */ /*! @param x VREF module instance base address. */ /*! @return Reference (not a pointer) to the registers struct. To get a pointer to the struct, * use the '&' operator, like &HW_VREF(VREF_BASE). */ #define HW_VREF(x) (*(hw_vref_t *)(x)) #endif /* __HW_VREF_REGISTERS_H__ */ /* EOF */ ================================================ FILE: Zelig/mbed/TARGET_K64F/TARGET_Freescale/TARGET_KPSDK_MCUS/TARGET_MCU_K64F/device/device/MK64F12/MK64F12_wdog.h ================================================ /* ** ################################################################### ** Compilers: Keil ARM C/C++ Compiler ** Freescale C/C++ for Embedded ARM ** GNU C Compiler ** IAR ANSI C/C++ Compiler for ARM ** ** Reference manual: K64P144M120SF5RM, Rev.2, January 2014 ** Version: rev. 2.5, 2014-02-10 ** Build: b140604 ** ** Abstract: ** Extension to the CMSIS register access layer header. ** ** Copyright (c) 2014 Freescale Semiconductor, Inc. ** All rights reserved. ** ** Redistribution and use in source and binary forms, with or without modification, ** are permitted provided that the following conditions are met: ** ** o Redistributions of source code must retain the above copyright notice, this list ** of conditions and the following disclaimer. ** ** o Redistributions in binary form must reproduce the above copyright notice, this ** list of conditions and the following disclaimer in the documentation and/or ** other materials provided with the distribution. ** ** o Neither the name of Freescale Semiconductor, Inc. nor the names of its ** contributors may be used to endorse or promote products derived from this ** software without specific prior written permission. ** ** THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ** ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED ** WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE ** DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT 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. ** ** http: www.freescale.com ** mail: support@freescale.com ** ** Revisions: ** - rev. 1.0 (2013-08-12) ** Initial version. ** - rev. 2.0 (2013-10-29) ** Register accessor macros added to the memory map. ** Symbols for Processor Expert memory map compatibility added to the memory map. ** Startup file for gcc has been updated according to CMSIS 3.2. ** System initialization updated. ** MCG - registers updated. ** PORTA, PORTB, PORTC, PORTE - registers for digital filter removed. ** - rev. 2.1 (2013-10-30) ** Definition of BITBAND macros updated to support peripherals with 32-bit acces disabled. ** - rev. 2.2 (2013-12-09) ** DMA - EARS register removed. ** AIPS0, AIPS1 - MPRA register updated. ** - rev. 2.3 (2014-01-24) ** Update according to reference manual rev. 2 ** ENET, MCG, MCM, SIM, USB - registers updated ** - rev. 2.4 (2014-02-10) ** The declaration of clock configurations has been moved to separate header file system_MK64F12.h ** Update of SystemInit() and SystemCoreClockUpdate() functions. ** - rev. 2.5 (2014-02-10) ** The declaration of clock configurations has been moved to separate header file system_MK64F12.h ** Update of SystemInit() and SystemCoreClockUpdate() functions. ** Module access macro module_BASES replaced by module_BASE_PTRS. ** ** ################################################################### */ /* * WARNING! DO NOT EDIT THIS FILE DIRECTLY! * * This file was generated automatically and any changes may be lost. */ #ifndef __HW_WDOG_REGISTERS_H__ #define __HW_WDOG_REGISTERS_H__ #include "MK64F12.h" #include "fsl_bitaccess.h" /* * MK64F12 WDOG * * Generation 2008 Watchdog Timer * * Registers defined in this header file: * - HW_WDOG_STCTRLH - Watchdog Status and Control Register High * - HW_WDOG_STCTRLL - Watchdog Status and Control Register Low * - HW_WDOG_TOVALH - Watchdog Time-out Value Register High * - HW_WDOG_TOVALL - Watchdog Time-out Value Register Low * - HW_WDOG_WINH - Watchdog Window Register High * - HW_WDOG_WINL - Watchdog Window Register Low * - HW_WDOG_REFRESH - Watchdog Refresh register * - HW_WDOG_UNLOCK - Watchdog Unlock register * - HW_WDOG_TMROUTH - Watchdog Timer Output Register High * - HW_WDOG_TMROUTL - Watchdog Timer Output Register Low * - HW_WDOG_RSTCNT - Watchdog Reset Count register * - HW_WDOG_PRESC - Watchdog Prescaler register * * - hw_wdog_t - Struct containing all module registers. */ #define HW_WDOG_INSTANCE_COUNT (1U) /*!< Number of instances of the WDOG module. */ /******************************************************************************* * HW_WDOG_STCTRLH - Watchdog Status and Control Register High ******************************************************************************/ /*! * @brief HW_WDOG_STCTRLH - Watchdog Status and Control Register High (RW) * * Reset value: 0x01D3U */ typedef union _hw_wdog_stctrlh { uint16_t U; struct _hw_wdog_stctrlh_bitfields { uint16_t WDOGEN : 1; /*!< [0] */ uint16_t CLKSRC : 1; /*!< [1] */ uint16_t IRQRSTEN : 1; /*!< [2] */ uint16_t WINEN : 1; /*!< [3] */ uint16_t ALLOWUPDATE : 1; /*!< [4] */ uint16_t DBGEN : 1; /*!< [5] */ uint16_t STOPEN : 1; /*!< [6] */ uint16_t WAITEN : 1; /*!< [7] */ uint16_t RESERVED0 : 2; /*!< [9:8] */ uint16_t TESTWDOG : 1; /*!< [10] */ uint16_t TESTSEL : 1; /*!< [11] */ uint16_t BYTESEL : 2; /*!< [13:12] */ uint16_t DISTESTWDOG : 1; /*!< [14] */ uint16_t RESERVED1 : 1; /*!< [15] */ } B; } hw_wdog_stctrlh_t; /*! * @name Constants and macros for entire WDOG_STCTRLH register */ /*@{*/ #define HW_WDOG_STCTRLH_ADDR(x) ((x) + 0x0U) #define HW_WDOG_STCTRLH(x) (*(__IO hw_wdog_stctrlh_t *) HW_WDOG_STCTRLH_ADDR(x)) #define HW_WDOG_STCTRLH_RD(x) (HW_WDOG_STCTRLH(x).U) #define HW_WDOG_STCTRLH_WR(x, v) (HW_WDOG_STCTRLH(x).U = (v)) #define HW_WDOG_STCTRLH_SET(x, v) (HW_WDOG_STCTRLH_WR(x, HW_WDOG_STCTRLH_RD(x) | (v))) #define HW_WDOG_STCTRLH_CLR(x, v) (HW_WDOG_STCTRLH_WR(x, HW_WDOG_STCTRLH_RD(x) & ~(v))) #define HW_WDOG_STCTRLH_TOG(x, v) (HW_WDOG_STCTRLH_WR(x, HW_WDOG_STCTRLH_RD(x) ^ (v))) /*@}*/ /* * Constants & macros for individual WDOG_STCTRLH bitfields */ /*! * @name Register WDOG_STCTRLH, field WDOGEN[0] (RW) * * Enables or disables the WDOG's operation. In the disabled state, the watchdog * timer is kept in the reset state, but the other exception conditions can * still trigger a reset/interrupt. A change in the value of this bit must be held * for more than one WDOG_CLK cycle for the WDOG to be enabled or disabled. * * Values: * - 0 - WDOG is disabled. * - 1 - WDOG is enabled. */ /*@{*/ #define BP_WDOG_STCTRLH_WDOGEN (0U) /*!< Bit position for WDOG_STCTRLH_WDOGEN. */ #define BM_WDOG_STCTRLH_WDOGEN (0x0001U) /*!< Bit mask for WDOG_STCTRLH_WDOGEN. */ #define BS_WDOG_STCTRLH_WDOGEN (1U) /*!< Bit field size in bits for WDOG_STCTRLH_WDOGEN. */ /*! @brief Read current value of the WDOG_STCTRLH_WDOGEN field. */ #define BR_WDOG_STCTRLH_WDOGEN(x) (BITBAND_ACCESS16(HW_WDOG_STCTRLH_ADDR(x), BP_WDOG_STCTRLH_WDOGEN)) /*! @brief Format value for bitfield WDOG_STCTRLH_WDOGEN. */ #define BF_WDOG_STCTRLH_WDOGEN(v) ((uint16_t)((uint16_t)(v) << BP_WDOG_STCTRLH_WDOGEN) & BM_WDOG_STCTRLH_WDOGEN) /*! @brief Set the WDOGEN field to a new value. */ #define BW_WDOG_STCTRLH_WDOGEN(x, v) (BITBAND_ACCESS16(HW_WDOG_STCTRLH_ADDR(x), BP_WDOG_STCTRLH_WDOGEN) = (v)) /*@}*/ /*! * @name Register WDOG_STCTRLH, field CLKSRC[1] (RW) * * Selects clock source for the WDOG timer and other internal timing operations. * * Values: * - 0 - WDOG clock sourced from LPO . * - 1 - WDOG clock sourced from alternate clock source. */ /*@{*/ #define BP_WDOG_STCTRLH_CLKSRC (1U) /*!< Bit position for WDOG_STCTRLH_CLKSRC. */ #define BM_WDOG_STCTRLH_CLKSRC (0x0002U) /*!< Bit mask for WDOG_STCTRLH_CLKSRC. */ #define BS_WDOG_STCTRLH_CLKSRC (1U) /*!< Bit field size in bits for WDOG_STCTRLH_CLKSRC. */ /*! @brief Read current value of the WDOG_STCTRLH_CLKSRC field. */ #define BR_WDOG_STCTRLH_CLKSRC(x) (BITBAND_ACCESS16(HW_WDOG_STCTRLH_ADDR(x), BP_WDOG_STCTRLH_CLKSRC)) /*! @brief Format value for bitfield WDOG_STCTRLH_CLKSRC. */ #define BF_WDOG_STCTRLH_CLKSRC(v) ((uint16_t)((uint16_t)(v) << BP_WDOG_STCTRLH_CLKSRC) & BM_WDOG_STCTRLH_CLKSRC) /*! @brief Set the CLKSRC field to a new value. */ #define BW_WDOG_STCTRLH_CLKSRC(x, v) (BITBAND_ACCESS16(HW_WDOG_STCTRLH_ADDR(x), BP_WDOG_STCTRLH_CLKSRC) = (v)) /*@}*/ /*! * @name Register WDOG_STCTRLH, field IRQRSTEN[2] (RW) * * Used to enable the debug breadcrumbs feature. A change in this bit is updated * immediately, as opposed to updating after WCT. * * Values: * - 0 - WDOG time-out generates reset only. * - 1 - WDOG time-out initially generates an interrupt. After WCT, it generates * a reset. */ /*@{*/ #define BP_WDOG_STCTRLH_IRQRSTEN (2U) /*!< Bit position for WDOG_STCTRLH_IRQRSTEN. */ #define BM_WDOG_STCTRLH_IRQRSTEN (0x0004U) /*!< Bit mask for WDOG_STCTRLH_IRQRSTEN. */ #define BS_WDOG_STCTRLH_IRQRSTEN (1U) /*!< Bit field size in bits for WDOG_STCTRLH_IRQRSTEN. */ /*! @brief Read current value of the WDOG_STCTRLH_IRQRSTEN field. */ #define BR_WDOG_STCTRLH_IRQRSTEN(x) (BITBAND_ACCESS16(HW_WDOG_STCTRLH_ADDR(x), BP_WDOG_STCTRLH_IRQRSTEN)) /*! @brief Format value for bitfield WDOG_STCTRLH_IRQRSTEN. */ #define BF_WDOG_STCTRLH_IRQRSTEN(v) ((uint16_t)((uint16_t)(v) << BP_WDOG_STCTRLH_IRQRSTEN) & BM_WDOG_STCTRLH_IRQRSTEN) /*! @brief Set the IRQRSTEN field to a new value. */ #define BW_WDOG_STCTRLH_IRQRSTEN(x, v) (BITBAND_ACCESS16(HW_WDOG_STCTRLH_ADDR(x), BP_WDOG_STCTRLH_IRQRSTEN) = (v)) /*@}*/ /*! * @name Register WDOG_STCTRLH, field WINEN[3] (RW) * * Enables Windowing mode. * * Values: * - 0 - Windowing mode is disabled. * - 1 - Windowing mode is enabled. */ /*@{*/ #define BP_WDOG_STCTRLH_WINEN (3U) /*!< Bit position for WDOG_STCTRLH_WINEN. */ #define BM_WDOG_STCTRLH_WINEN (0x0008U) /*!< Bit mask for WDOG_STCTRLH_WINEN. */ #define BS_WDOG_STCTRLH_WINEN (1U) /*!< Bit field size in bits for WDOG_STCTRLH_WINEN. */ /*! @brief Read current value of the WDOG_STCTRLH_WINEN field. */ #define BR_WDOG_STCTRLH_WINEN(x) (BITBAND_ACCESS16(HW_WDOG_STCTRLH_ADDR(x), BP_WDOG_STCTRLH_WINEN)) /*! @brief Format value for bitfield WDOG_STCTRLH_WINEN. */ #define BF_WDOG_STCTRLH_WINEN(v) ((uint16_t)((uint16_t)(v) << BP_WDOG_STCTRLH_WINEN) & BM_WDOG_STCTRLH_WINEN) /*! @brief Set the WINEN field to a new value. */ #define BW_WDOG_STCTRLH_WINEN(x, v) (BITBAND_ACCESS16(HW_WDOG_STCTRLH_ADDR(x), BP_WDOG_STCTRLH_WINEN) = (v)) /*@}*/ /*! * @name Register WDOG_STCTRLH, field ALLOWUPDATE[4] (RW) * * Enables updates to watchdog write-once registers, after the reset-triggered * initial configuration window (WCT) closes, through unlock sequence. * * Values: * - 0 - No further updates allowed to WDOG write-once registers. * - 1 - WDOG write-once registers can be unlocked for updating. */ /*@{*/ #define BP_WDOG_STCTRLH_ALLOWUPDATE (4U) /*!< Bit position for WDOG_STCTRLH_ALLOWUPDATE. */ #define BM_WDOG_STCTRLH_ALLOWUPDATE (0x0010U) /*!< Bit mask for WDOG_STCTRLH_ALLOWUPDATE. */ #define BS_WDOG_STCTRLH_ALLOWUPDATE (1U) /*!< Bit field size in bits for WDOG_STCTRLH_ALLOWUPDATE. */ /*! @brief Read current value of the WDOG_STCTRLH_ALLOWUPDATE field. */ #define BR_WDOG_STCTRLH_ALLOWUPDATE(x) (BITBAND_ACCESS16(HW_WDOG_STCTRLH_ADDR(x), BP_WDOG_STCTRLH_ALLOWUPDATE)) /*! @brief Format value for bitfield WDOG_STCTRLH_ALLOWUPDATE. */ #define BF_WDOG_STCTRLH_ALLOWUPDATE(v) ((uint16_t)((uint16_t)(v) << BP_WDOG_STCTRLH_ALLOWUPDATE) & BM_WDOG_STCTRLH_ALLOWUPDATE) /*! @brief Set the ALLOWUPDATE field to a new value. */ #define BW_WDOG_STCTRLH_ALLOWUPDATE(x, v) (BITBAND_ACCESS16(HW_WDOG_STCTRLH_ADDR(x), BP_WDOG_STCTRLH_ALLOWUPDATE) = (v)) /*@}*/ /*! * @name Register WDOG_STCTRLH, field DBGEN[5] (RW) * * Enables or disables WDOG in Debug mode. * * Values: * - 0 - WDOG is disabled in CPU Debug mode. * - 1 - WDOG is enabled in CPU Debug mode. */ /*@{*/ #define BP_WDOG_STCTRLH_DBGEN (5U) /*!< Bit position for WDOG_STCTRLH_DBGEN. */ #define BM_WDOG_STCTRLH_DBGEN (0x0020U) /*!< Bit mask for WDOG_STCTRLH_DBGEN. */ #define BS_WDOG_STCTRLH_DBGEN (1U) /*!< Bit field size in bits for WDOG_STCTRLH_DBGEN. */ /*! @brief Read current value of the WDOG_STCTRLH_DBGEN field. */ #define BR_WDOG_STCTRLH_DBGEN(x) (BITBAND_ACCESS16(HW_WDOG_STCTRLH_ADDR(x), BP_WDOG_STCTRLH_DBGEN)) /*! @brief Format value for bitfield WDOG_STCTRLH_DBGEN. */ #define BF_WDOG_STCTRLH_DBGEN(v) ((uint16_t)((uint16_t)(v) << BP_WDOG_STCTRLH_DBGEN) & BM_WDOG_STCTRLH_DBGEN) /*! @brief Set the DBGEN field to a new value. */ #define BW_WDOG_STCTRLH_DBGEN(x, v) (BITBAND_ACCESS16(HW_WDOG_STCTRLH_ADDR(x), BP_WDOG_STCTRLH_DBGEN) = (v)) /*@}*/ /*! * @name Register WDOG_STCTRLH, field STOPEN[6] (RW) * * Enables or disables WDOG in Stop mode. * * Values: * - 0 - WDOG is disabled in CPU Stop mode. * - 1 - WDOG is enabled in CPU Stop mode. */ /*@{*/ #define BP_WDOG_STCTRLH_STOPEN (6U) /*!< Bit position for WDOG_STCTRLH_STOPEN. */ #define BM_WDOG_STCTRLH_STOPEN (0x0040U) /*!< Bit mask for WDOG_STCTRLH_STOPEN. */ #define BS_WDOG_STCTRLH_STOPEN (1U) /*!< Bit field size in bits for WDOG_STCTRLH_STOPEN. */ /*! @brief Read current value of the WDOG_STCTRLH_STOPEN field. */ #define BR_WDOG_STCTRLH_STOPEN(x) (BITBAND_ACCESS16(HW_WDOG_STCTRLH_ADDR(x), BP_WDOG_STCTRLH_STOPEN)) /*! @brief Format value for bitfield WDOG_STCTRLH_STOPEN. */ #define BF_WDOG_STCTRLH_STOPEN(v) ((uint16_t)((uint16_t)(v) << BP_WDOG_STCTRLH_STOPEN) & BM_WDOG_STCTRLH_STOPEN) /*! @brief Set the STOPEN field to a new value. */ #define BW_WDOG_STCTRLH_STOPEN(x, v) (BITBAND_ACCESS16(HW_WDOG_STCTRLH_ADDR(x), BP_WDOG_STCTRLH_STOPEN) = (v)) /*@}*/ /*! * @name Register WDOG_STCTRLH, field WAITEN[7] (RW) * * Enables or disables WDOG in Wait mode. * * Values: * - 0 - WDOG is disabled in CPU Wait mode. * - 1 - WDOG is enabled in CPU Wait mode. */ /*@{*/ #define BP_WDOG_STCTRLH_WAITEN (7U) /*!< Bit position for WDOG_STCTRLH_WAITEN. */ #define BM_WDOG_STCTRLH_WAITEN (0x0080U) /*!< Bit mask for WDOG_STCTRLH_WAITEN. */ #define BS_WDOG_STCTRLH_WAITEN (1U) /*!< Bit field size in bits for WDOG_STCTRLH_WAITEN. */ /*! @brief Read current value of the WDOG_STCTRLH_WAITEN field. */ #define BR_WDOG_STCTRLH_WAITEN(x) (BITBAND_ACCESS16(HW_WDOG_STCTRLH_ADDR(x), BP_WDOG_STCTRLH_WAITEN)) /*! @brief Format value for bitfield WDOG_STCTRLH_WAITEN. */ #define BF_WDOG_STCTRLH_WAITEN(v) ((uint16_t)((uint16_t)(v) << BP_WDOG_STCTRLH_WAITEN) & BM_WDOG_STCTRLH_WAITEN) /*! @brief Set the WAITEN field to a new value. */ #define BW_WDOG_STCTRLH_WAITEN(x, v) (BITBAND_ACCESS16(HW_WDOG_STCTRLH_ADDR(x), BP_WDOG_STCTRLH_WAITEN) = (v)) /*@}*/ /*! * @name Register WDOG_STCTRLH, field TESTWDOG[10] (RW) * * Puts the watchdog in the functional test mode. In this mode, the watchdog * timer and the associated compare and reset generation logic is tested for correct * operation. The clock for the timer is switched from the main watchdog clock * to the fast clock input for watchdog functional test. The TESTSEL bit selects * the test to be run. */ /*@{*/ #define BP_WDOG_STCTRLH_TESTWDOG (10U) /*!< Bit position for WDOG_STCTRLH_TESTWDOG. */ #define BM_WDOG_STCTRLH_TESTWDOG (0x0400U) /*!< Bit mask for WDOG_STCTRLH_TESTWDOG. */ #define BS_WDOG_STCTRLH_TESTWDOG (1U) /*!< Bit field size in bits for WDOG_STCTRLH_TESTWDOG. */ /*! @brief Read current value of the WDOG_STCTRLH_TESTWDOG field. */ #define BR_WDOG_STCTRLH_TESTWDOG(x) (BITBAND_ACCESS16(HW_WDOG_STCTRLH_ADDR(x), BP_WDOG_STCTRLH_TESTWDOG)) /*! @brief Format value for bitfield WDOG_STCTRLH_TESTWDOG. */ #define BF_WDOG_STCTRLH_TESTWDOG(v) ((uint16_t)((uint16_t)(v) << BP_WDOG_STCTRLH_TESTWDOG) & BM_WDOG_STCTRLH_TESTWDOG) /*! @brief Set the TESTWDOG field to a new value. */ #define BW_WDOG_STCTRLH_TESTWDOG(x, v) (BITBAND_ACCESS16(HW_WDOG_STCTRLH_ADDR(x), BP_WDOG_STCTRLH_TESTWDOG) = (v)) /*@}*/ /*! * @name Register WDOG_STCTRLH, field TESTSEL[11] (RW) * * Effective only if TESTWDOG is set. Selects the test to be run on the watchdog * timer. * * Values: * - 0 - Quick test. The timer runs in normal operation. You can load a small * time-out value to do a quick test. * - 1 - Byte test. Puts the timer in the byte test mode where individual bytes * of the timer are enabled for operation and are compared for time-out * against the corresponding byte of the programmed time-out value. Select the * byte through BYTESEL[1:0] for testing. */ /*@{*/ #define BP_WDOG_STCTRLH_TESTSEL (11U) /*!< Bit position for WDOG_STCTRLH_TESTSEL. */ #define BM_WDOG_STCTRLH_TESTSEL (0x0800U) /*!< Bit mask for WDOG_STCTRLH_TESTSEL. */ #define BS_WDOG_STCTRLH_TESTSEL (1U) /*!< Bit field size in bits for WDOG_STCTRLH_TESTSEL. */ /*! @brief Read current value of the WDOG_STCTRLH_TESTSEL field. */ #define BR_WDOG_STCTRLH_TESTSEL(x) (BITBAND_ACCESS16(HW_WDOG_STCTRLH_ADDR(x), BP_WDOG_STCTRLH_TESTSEL)) /*! @brief Format value for bitfield WDOG_STCTRLH_TESTSEL. */ #define BF_WDOG_STCTRLH_TESTSEL(v) ((uint16_t)((uint16_t)(v) << BP_WDOG_STCTRLH_TESTSEL) & BM_WDOG_STCTRLH_TESTSEL) /*! @brief Set the TESTSEL field to a new value. */ #define BW_WDOG_STCTRLH_TESTSEL(x, v) (BITBAND_ACCESS16(HW_WDOG_STCTRLH_ADDR(x), BP_WDOG_STCTRLH_TESTSEL) = (v)) /*@}*/ /*! * @name Register WDOG_STCTRLH, field BYTESEL[13:12] (RW) * * This 2-bit field selects the byte to be tested when the watchdog is in the * byte test mode. * * Values: * - 00 - Byte 0 selected * - 01 - Byte 1 selected * - 10 - Byte 2 selected * - 11 - Byte 3 selected */ /*@{*/ #define BP_WDOG_STCTRLH_BYTESEL (12U) /*!< Bit position for WDOG_STCTRLH_BYTESEL. */ #define BM_WDOG_STCTRLH_BYTESEL (0x3000U) /*!< Bit mask for WDOG_STCTRLH_BYTESEL. */ #define BS_WDOG_STCTRLH_BYTESEL (2U) /*!< Bit field size in bits for WDOG_STCTRLH_BYTESEL. */ /*! @brief Read current value of the WDOG_STCTRLH_BYTESEL field. */ #define BR_WDOG_STCTRLH_BYTESEL(x) (HW_WDOG_STCTRLH(x).B.BYTESEL) /*! @brief Format value for bitfield WDOG_STCTRLH_BYTESEL. */ #define BF_WDOG_STCTRLH_BYTESEL(v) ((uint16_t)((uint16_t)(v) << BP_WDOG_STCTRLH_BYTESEL) & BM_WDOG_STCTRLH_BYTESEL) /*! @brief Set the BYTESEL field to a new value. */ #define BW_WDOG_STCTRLH_BYTESEL(x, v) (HW_WDOG_STCTRLH_WR(x, (HW_WDOG_STCTRLH_RD(x) & ~BM_WDOG_STCTRLH_BYTESEL) | BF_WDOG_STCTRLH_BYTESEL(v))) /*@}*/ /*! * @name Register WDOG_STCTRLH, field DISTESTWDOG[14] (RW) * * Allows the WDOG's functional test mode to be disabled permanently. After it * is set, it can only be cleared by a reset. It cannot be unlocked for editing * after it is set. * * Values: * - 0 - WDOG functional test mode is not disabled. * - 1 - WDOG functional test mode is disabled permanently until reset. */ /*@{*/ #define BP_WDOG_STCTRLH_DISTESTWDOG (14U) /*!< Bit position for WDOG_STCTRLH_DISTESTWDOG. */ #define BM_WDOG_STCTRLH_DISTESTWDOG (0x4000U) /*!< Bit mask for WDOG_STCTRLH_DISTESTWDOG. */ #define BS_WDOG_STCTRLH_DISTESTWDOG (1U) /*!< Bit field size in bits for WDOG_STCTRLH_DISTESTWDOG. */ /*! @brief Read current value of the WDOG_STCTRLH_DISTESTWDOG field. */ #define BR_WDOG_STCTRLH_DISTESTWDOG(x) (BITBAND_ACCESS16(HW_WDOG_STCTRLH_ADDR(x), BP_WDOG_STCTRLH_DISTESTWDOG)) /*! @brief Format value for bitfield WDOG_STCTRLH_DISTESTWDOG. */ #define BF_WDOG_STCTRLH_DISTESTWDOG(v) ((uint16_t)((uint16_t)(v) << BP_WDOG_STCTRLH_DISTESTWDOG) & BM_WDOG_STCTRLH_DISTESTWDOG) /*! @brief Set the DISTESTWDOG field to a new value. */ #define BW_WDOG_STCTRLH_DISTESTWDOG(x, v) (BITBAND_ACCESS16(HW_WDOG_STCTRLH_ADDR(x), BP_WDOG_STCTRLH_DISTESTWDOG) = (v)) /*@}*/ /******************************************************************************* * HW_WDOG_STCTRLL - Watchdog Status and Control Register Low ******************************************************************************/ /*! * @brief HW_WDOG_STCTRLL - Watchdog Status and Control Register Low (RW) * * Reset value: 0x0001U */ typedef union _hw_wdog_stctrll { uint16_t U; struct _hw_wdog_stctrll_bitfields { uint16_t RESERVED0 : 15; /*!< [14:0] */ uint16_t INTFLG : 1; /*!< [15] */ } B; } hw_wdog_stctrll_t; /*! * @name Constants and macros for entire WDOG_STCTRLL register */ /*@{*/ #define HW_WDOG_STCTRLL_ADDR(x) ((x) + 0x2U) #define HW_WDOG_STCTRLL(x) (*(__IO hw_wdog_stctrll_t *) HW_WDOG_STCTRLL_ADDR(x)) #define HW_WDOG_STCTRLL_RD(x) (HW_WDOG_STCTRLL(x).U) #define HW_WDOG_STCTRLL_WR(x, v) (HW_WDOG_STCTRLL(x).U = (v)) #define HW_WDOG_STCTRLL_SET(x, v) (HW_WDOG_STCTRLL_WR(x, HW_WDOG_STCTRLL_RD(x) | (v))) #define HW_WDOG_STCTRLL_CLR(x, v) (HW_WDOG_STCTRLL_WR(x, HW_WDOG_STCTRLL_RD(x) & ~(v))) #define HW_WDOG_STCTRLL_TOG(x, v) (HW_WDOG_STCTRLL_WR(x, HW_WDOG_STCTRLL_RD(x) ^ (v))) /*@}*/ /* * Constants & macros for individual WDOG_STCTRLL bitfields */ /*! * @name Register WDOG_STCTRLL, field INTFLG[15] (RW) * * Interrupt flag. It is set when an exception occurs. IRQRSTEN = 1 is a * precondition to set this flag. INTFLG = 1 results in an interrupt being issued * followed by a reset, WCT later. The interrupt can be cleared by writing 1 to this * bit. It also gets cleared on a system reset. */ /*@{*/ #define BP_WDOG_STCTRLL_INTFLG (15U) /*!< Bit position for WDOG_STCTRLL_INTFLG. */ #define BM_WDOG_STCTRLL_INTFLG (0x8000U) /*!< Bit mask for WDOG_STCTRLL_INTFLG. */ #define BS_WDOG_STCTRLL_INTFLG (1U) /*!< Bit field size in bits for WDOG_STCTRLL_INTFLG. */ /*! @brief Read current value of the WDOG_STCTRLL_INTFLG field. */ #define BR_WDOG_STCTRLL_INTFLG(x) (BITBAND_ACCESS16(HW_WDOG_STCTRLL_ADDR(x), BP_WDOG_STCTRLL_INTFLG)) /*! @brief Format value for bitfield WDOG_STCTRLL_INTFLG. */ #define BF_WDOG_STCTRLL_INTFLG(v) ((uint16_t)((uint16_t)(v) << BP_WDOG_STCTRLL_INTFLG) & BM_WDOG_STCTRLL_INTFLG) /*! @brief Set the INTFLG field to a new value. */ #define BW_WDOG_STCTRLL_INTFLG(x, v) (BITBAND_ACCESS16(HW_WDOG_STCTRLL_ADDR(x), BP_WDOG_STCTRLL_INTFLG) = (v)) /*@}*/ /******************************************************************************* * HW_WDOG_TOVALH - Watchdog Time-out Value Register High ******************************************************************************/ /*! * @brief HW_WDOG_TOVALH - Watchdog Time-out Value Register High (RW) * * Reset value: 0x004CU */ typedef union _hw_wdog_tovalh { uint16_t U; struct _hw_wdog_tovalh_bitfields { uint16_t TOVALHIGH : 16; /*!< [15:0] */ } B; } hw_wdog_tovalh_t; /*! * @name Constants and macros for entire WDOG_TOVALH register */ /*@{*/ #define HW_WDOG_TOVALH_ADDR(x) ((x) + 0x4U) #define HW_WDOG_TOVALH(x) (*(__IO hw_wdog_tovalh_t *) HW_WDOG_TOVALH_ADDR(x)) #define HW_WDOG_TOVALH_RD(x) (HW_WDOG_TOVALH(x).U) #define HW_WDOG_TOVALH_WR(x, v) (HW_WDOG_TOVALH(x).U = (v)) #define HW_WDOG_TOVALH_SET(x, v) (HW_WDOG_TOVALH_WR(x, HW_WDOG_TOVALH_RD(x) | (v))) #define HW_WDOG_TOVALH_CLR(x, v) (HW_WDOG_TOVALH_WR(x, HW_WDOG_TOVALH_RD(x) & ~(v))) #define HW_WDOG_TOVALH_TOG(x, v) (HW_WDOG_TOVALH_WR(x, HW_WDOG_TOVALH_RD(x) ^ (v))) /*@}*/ /* * Constants & macros for individual WDOG_TOVALH bitfields */ /*! * @name Register WDOG_TOVALH, field TOVALHIGH[15:0] (RW) * * Defines the upper 16 bits of the 32-bit time-out value for the watchdog * timer. It is defined in terms of cycles of the watchdog clock. */ /*@{*/ #define BP_WDOG_TOVALH_TOVALHIGH (0U) /*!< Bit position for WDOG_TOVALH_TOVALHIGH. */ #define BM_WDOG_TOVALH_TOVALHIGH (0xFFFFU) /*!< Bit mask for WDOG_TOVALH_TOVALHIGH. */ #define BS_WDOG_TOVALH_TOVALHIGH (16U) /*!< Bit field size in bits for WDOG_TOVALH_TOVALHIGH. */ /*! @brief Read current value of the WDOG_TOVALH_TOVALHIGH field. */ #define BR_WDOG_TOVALH_TOVALHIGH(x) (HW_WDOG_TOVALH(x).U) /*! @brief Format value for bitfield WDOG_TOVALH_TOVALHIGH. */ #define BF_WDOG_TOVALH_TOVALHIGH(v) ((uint16_t)((uint16_t)(v) << BP_WDOG_TOVALH_TOVALHIGH) & BM_WDOG_TOVALH_TOVALHIGH) /*! @brief Set the TOVALHIGH field to a new value. */ #define BW_WDOG_TOVALH_TOVALHIGH(x, v) (HW_WDOG_TOVALH_WR(x, v)) /*@}*/ /******************************************************************************* * HW_WDOG_TOVALL - Watchdog Time-out Value Register Low ******************************************************************************/ /*! * @brief HW_WDOG_TOVALL - Watchdog Time-out Value Register Low (RW) * * Reset value: 0x4B4CU * * The time-out value of the watchdog must be set to a minimum of four watchdog * clock cycles. This is to take into account the delay in new settings taking * effect in the watchdog clock domain. */ typedef union _hw_wdog_tovall { uint16_t U; struct _hw_wdog_tovall_bitfields { uint16_t TOVALLOW : 16; /*!< [15:0] */ } B; } hw_wdog_tovall_t; /*! * @name Constants and macros for entire WDOG_TOVALL register */ /*@{*/ #define HW_WDOG_TOVALL_ADDR(x) ((x) + 0x6U) #define HW_WDOG_TOVALL(x) (*(__IO hw_wdog_tovall_t *) HW_WDOG_TOVALL_ADDR(x)) #define HW_WDOG_TOVALL_RD(x) (HW_WDOG_TOVALL(x).U) #define HW_WDOG_TOVALL_WR(x, v) (HW_WDOG_TOVALL(x).U = (v)) #define HW_WDOG_TOVALL_SET(x, v) (HW_WDOG_TOVALL_WR(x, HW_WDOG_TOVALL_RD(x) | (v))) #define HW_WDOG_TOVALL_CLR(x, v) (HW_WDOG_TOVALL_WR(x, HW_WDOG_TOVALL_RD(x) & ~(v))) #define HW_WDOG_TOVALL_TOG(x, v) (HW_WDOG_TOVALL_WR(x, HW_WDOG_TOVALL_RD(x) ^ (v))) /*@}*/ /* * Constants & macros for individual WDOG_TOVALL bitfields */ /*! * @name Register WDOG_TOVALL, field TOVALLOW[15:0] (RW) * * Defines the lower 16 bits of the 32-bit time-out value for the watchdog * timer. It is defined in terms of cycles of the watchdog clock. */ /*@{*/ #define BP_WDOG_TOVALL_TOVALLOW (0U) /*!< Bit position for WDOG_TOVALL_TOVALLOW. */ #define BM_WDOG_TOVALL_TOVALLOW (0xFFFFU) /*!< Bit mask for WDOG_TOVALL_TOVALLOW. */ #define BS_WDOG_TOVALL_TOVALLOW (16U) /*!< Bit field size in bits for WDOG_TOVALL_TOVALLOW. */ /*! @brief Read current value of the WDOG_TOVALL_TOVALLOW field. */ #define BR_WDOG_TOVALL_TOVALLOW(x) (HW_WDOG_TOVALL(x).U) /*! @brief Format value for bitfield WDOG_TOVALL_TOVALLOW. */ #define BF_WDOG_TOVALL_TOVALLOW(v) ((uint16_t)((uint16_t)(v) << BP_WDOG_TOVALL_TOVALLOW) & BM_WDOG_TOVALL_TOVALLOW) /*! @brief Set the TOVALLOW field to a new value. */ #define BW_WDOG_TOVALL_TOVALLOW(x, v) (HW_WDOG_TOVALL_WR(x, v)) /*@}*/ /******************************************************************************* * HW_WDOG_WINH - Watchdog Window Register High ******************************************************************************/ /*! * @brief HW_WDOG_WINH - Watchdog Window Register High (RW) * * Reset value: 0x0000U * * You must set the Window Register value lower than the Time-out Value Register. */ typedef union _hw_wdog_winh { uint16_t U; struct _hw_wdog_winh_bitfields { uint16_t WINHIGH : 16; /*!< [15:0] */ } B; } hw_wdog_winh_t; /*! * @name Constants and macros for entire WDOG_WINH register */ /*@{*/ #define HW_WDOG_WINH_ADDR(x) ((x) + 0x8U) #define HW_WDOG_WINH(x) (*(__IO hw_wdog_winh_t *) HW_WDOG_WINH_ADDR(x)) #define HW_WDOG_WINH_RD(x) (HW_WDOG_WINH(x).U) #define HW_WDOG_WINH_WR(x, v) (HW_WDOG_WINH(x).U = (v)) #define HW_WDOG_WINH_SET(x, v) (HW_WDOG_WINH_WR(x, HW_WDOG_WINH_RD(x) | (v))) #define HW_WDOG_WINH_CLR(x, v) (HW_WDOG_WINH_WR(x, HW_WDOG_WINH_RD(x) & ~(v))) #define HW_WDOG_WINH_TOG(x, v) (HW_WDOG_WINH_WR(x, HW_WDOG_WINH_RD(x) ^ (v))) /*@}*/ /* * Constants & macros for individual WDOG_WINH bitfields */ /*! * @name Register WDOG_WINH, field WINHIGH[15:0] (RW) * * Defines the upper 16 bits of the 32-bit window for the windowed mode of * operation of the watchdog. It is defined in terms of cycles of the watchdog clock. * In this mode, the watchdog can be refreshed only when the timer has reached a * value greater than or equal to this window length. A refresh outside this * window resets the system or if IRQRSTEN is set, it interrupts and then resets the * system. */ /*@{*/ #define BP_WDOG_WINH_WINHIGH (0U) /*!< Bit position for WDOG_WINH_WINHIGH. */ #define BM_WDOG_WINH_WINHIGH (0xFFFFU) /*!< Bit mask for WDOG_WINH_WINHIGH. */ #define BS_WDOG_WINH_WINHIGH (16U) /*!< Bit field size in bits for WDOG_WINH_WINHIGH. */ /*! @brief Read current value of the WDOG_WINH_WINHIGH field. */ #define BR_WDOG_WINH_WINHIGH(x) (HW_WDOG_WINH(x).U) /*! @brief Format value for bitfield WDOG_WINH_WINHIGH. */ #define BF_WDOG_WINH_WINHIGH(v) ((uint16_t)((uint16_t)(v) << BP_WDOG_WINH_WINHIGH) & BM_WDOG_WINH_WINHIGH) /*! @brief Set the WINHIGH field to a new value. */ #define BW_WDOG_WINH_WINHIGH(x, v) (HW_WDOG_WINH_WR(x, v)) /*@}*/ /******************************************************************************* * HW_WDOG_WINL - Watchdog Window Register Low ******************************************************************************/ /*! * @brief HW_WDOG_WINL - Watchdog Window Register Low (RW) * * Reset value: 0x0010U * * You must set the Window Register value lower than the Time-out Value Register. */ typedef union _hw_wdog_winl { uint16_t U; struct _hw_wdog_winl_bitfields { uint16_t WINLOW : 16; /*!< [15:0] */ } B; } hw_wdog_winl_t; /*! * @name Constants and macros for entire WDOG_WINL register */ /*@{*/ #define HW_WDOG_WINL_ADDR(x) ((x) + 0xAU) #define HW_WDOG_WINL(x) (*(__IO hw_wdog_winl_t *) HW_WDOG_WINL_ADDR(x)) #define HW_WDOG_WINL_RD(x) (HW_WDOG_WINL(x).U) #define HW_WDOG_WINL_WR(x, v) (HW_WDOG_WINL(x).U = (v)) #define HW_WDOG_WINL_SET(x, v) (HW_WDOG_WINL_WR(x, HW_WDOG_WINL_RD(x) | (v))) #define HW_WDOG_WINL_CLR(x, v) (HW_WDOG_WINL_WR(x, HW_WDOG_WINL_RD(x) & ~(v))) #define HW_WDOG_WINL_TOG(x, v) (HW_WDOG_WINL_WR(x, HW_WDOG_WINL_RD(x) ^ (v))) /*@}*/ /* * Constants & macros for individual WDOG_WINL bitfields */ /*! * @name Register WDOG_WINL, field WINLOW[15:0] (RW) * * Defines the lower 16 bits of the 32-bit window for the windowed mode of * operation of the watchdog. It is defined in terms of cycles of the pre-scaled * watchdog clock. In this mode, the watchdog can be refreshed only when the timer * reaches a value greater than or equal to this window length value. A refresh * outside of this window resets the system or if IRQRSTEN is set, it interrupts and * then resets the system. */ /*@{*/ #define BP_WDOG_WINL_WINLOW (0U) /*!< Bit position for WDOG_WINL_WINLOW. */ #define BM_WDOG_WINL_WINLOW (0xFFFFU) /*!< Bit mask for WDOG_WINL_WINLOW. */ #define BS_WDOG_WINL_WINLOW (16U) /*!< Bit field size in bits for WDOG_WINL_WINLOW. */ /*! @brief Read current value of the WDOG_WINL_WINLOW field. */ #define BR_WDOG_WINL_WINLOW(x) (HW_WDOG_WINL(x).U) /*! @brief Format value for bitfield WDOG_WINL_WINLOW. */ #define BF_WDOG_WINL_WINLOW(v) ((uint16_t)((uint16_t)(v) << BP_WDOG_WINL_WINLOW) & BM_WDOG_WINL_WINLOW) /*! @brief Set the WINLOW field to a new value. */ #define BW_WDOG_WINL_WINLOW(x, v) (HW_WDOG_WINL_WR(x, v)) /*@}*/ /******************************************************************************* * HW_WDOG_REFRESH - Watchdog Refresh register ******************************************************************************/ /*! * @brief HW_WDOG_REFRESH - Watchdog Refresh register (RW) * * Reset value: 0xB480U */ typedef union _hw_wdog_refresh { uint16_t U; struct _hw_wdog_refresh_bitfields { uint16_t WDOGREFRESH : 16; /*!< [15:0] */ } B; } hw_wdog_refresh_t; /*! * @name Constants and macros for entire WDOG_REFRESH register */ /*@{*/ #define HW_WDOG_REFRESH_ADDR(x) ((x) + 0xCU) #define HW_WDOG_REFRESH(x) (*(__IO hw_wdog_refresh_t *) HW_WDOG_REFRESH_ADDR(x)) #define HW_WDOG_REFRESH_RD(x) (HW_WDOG_REFRESH(x).U) #define HW_WDOG_REFRESH_WR(x, v) (HW_WDOG_REFRESH(x).U = (v)) #define HW_WDOG_REFRESH_SET(x, v) (HW_WDOG_REFRESH_WR(x, HW_WDOG_REFRESH_RD(x) | (v))) #define HW_WDOG_REFRESH_CLR(x, v) (HW_WDOG_REFRESH_WR(x, HW_WDOG_REFRESH_RD(x) & ~(v))) #define HW_WDOG_REFRESH_TOG(x, v) (HW_WDOG_REFRESH_WR(x, HW_WDOG_REFRESH_RD(x) ^ (v))) /*@}*/ /* * Constants & macros for individual WDOG_REFRESH bitfields */ /*! * @name Register WDOG_REFRESH, field WDOGREFRESH[15:0] (RW) * * Watchdog refresh register. A sequence of 0xA602 followed by 0xB480 within 20 * bus clock cycles written to this register refreshes the WDOG and prevents it * from resetting the system. Writing a value other than the above mentioned * sequence or if the sequence is longer than 20 bus cycles, resets the system, or if * IRQRSTEN is set, it interrupts and then resets the system. */ /*@{*/ #define BP_WDOG_REFRESH_WDOGREFRESH (0U) /*!< Bit position for WDOG_REFRESH_WDOGREFRESH. */ #define BM_WDOG_REFRESH_WDOGREFRESH (0xFFFFU) /*!< Bit mask for WDOG_REFRESH_WDOGREFRESH. */ #define BS_WDOG_REFRESH_WDOGREFRESH (16U) /*!< Bit field size in bits for WDOG_REFRESH_WDOGREFRESH. */ /*! @brief Read current value of the WDOG_REFRESH_WDOGREFRESH field. */ #define BR_WDOG_REFRESH_WDOGREFRESH(x) (HW_WDOG_REFRESH(x).U) /*! @brief Format value for bitfield WDOG_REFRESH_WDOGREFRESH. */ #define BF_WDOG_REFRESH_WDOGREFRESH(v) ((uint16_t)((uint16_t)(v) << BP_WDOG_REFRESH_WDOGREFRESH) & BM_WDOG_REFRESH_WDOGREFRESH) /*! @brief Set the WDOGREFRESH field to a new value. */ #define BW_WDOG_REFRESH_WDOGREFRESH(x, v) (HW_WDOG_REFRESH_WR(x, v)) /*@}*/ /******************************************************************************* * HW_WDOG_UNLOCK - Watchdog Unlock register ******************************************************************************/ /*! * @brief HW_WDOG_UNLOCK - Watchdog Unlock register (RW) * * Reset value: 0xD928U */ typedef union _hw_wdog_unlock { uint16_t U; struct _hw_wdog_unlock_bitfields { uint16_t WDOGUNLOCK : 16; /*!< [15:0] */ } B; } hw_wdog_unlock_t; /*! * @name Constants and macros for entire WDOG_UNLOCK register */ /*@{*/ #define HW_WDOG_UNLOCK_ADDR(x) ((x) + 0xEU) #define HW_WDOG_UNLOCK(x) (*(__IO hw_wdog_unlock_t *) HW_WDOG_UNLOCK_ADDR(x)) #define HW_WDOG_UNLOCK_RD(x) (HW_WDOG_UNLOCK(x).U) #define HW_WDOG_UNLOCK_WR(x, v) (HW_WDOG_UNLOCK(x).U = (v)) #define HW_WDOG_UNLOCK_SET(x, v) (HW_WDOG_UNLOCK_WR(x, HW_WDOG_UNLOCK_RD(x) | (v))) #define HW_WDOG_UNLOCK_CLR(x, v) (HW_WDOG_UNLOCK_WR(x, HW_WDOG_UNLOCK_RD(x) & ~(v))) #define HW_WDOG_UNLOCK_TOG(x, v) (HW_WDOG_UNLOCK_WR(x, HW_WDOG_UNLOCK_RD(x) ^ (v))) /*@}*/ /* * Constants & macros for individual WDOG_UNLOCK bitfields */ /*! * @name Register WDOG_UNLOCK, field WDOGUNLOCK[15:0] (RW) * * Writing the unlock sequence values to this register to makes the watchdog * write-once registers writable again. The required unlock sequence is 0xC520 * followed by 0xD928 within 20 bus clock cycles. A valid unlock sequence opens a * window equal in length to the WCT within which you can update the registers. * Writing a value other than the above mentioned sequence or if the sequence is * longer than 20 bus cycles, resets the system or if IRQRSTEN is set, it interrupts * and then resets the system. The unlock sequence is effective only if * ALLOWUPDATE is set. */ /*@{*/ #define BP_WDOG_UNLOCK_WDOGUNLOCK (0U) /*!< Bit position for WDOG_UNLOCK_WDOGUNLOCK. */ #define BM_WDOG_UNLOCK_WDOGUNLOCK (0xFFFFU) /*!< Bit mask for WDOG_UNLOCK_WDOGUNLOCK. */ #define BS_WDOG_UNLOCK_WDOGUNLOCK (16U) /*!< Bit field size in bits for WDOG_UNLOCK_WDOGUNLOCK. */ /*! @brief Read current value of the WDOG_UNLOCK_WDOGUNLOCK field. */ #define BR_WDOG_UNLOCK_WDOGUNLOCK(x) (HW_WDOG_UNLOCK(x).U) /*! @brief Format value for bitfield WDOG_UNLOCK_WDOGUNLOCK. */ #define BF_WDOG_UNLOCK_WDOGUNLOCK(v) ((uint16_t)((uint16_t)(v) << BP_WDOG_UNLOCK_WDOGUNLOCK) & BM_WDOG_UNLOCK_WDOGUNLOCK) /*! @brief Set the WDOGUNLOCK field to a new value. */ #define BW_WDOG_UNLOCK_WDOGUNLOCK(x, v) (HW_WDOG_UNLOCK_WR(x, v)) /*@}*/ /******************************************************************************* * HW_WDOG_TMROUTH - Watchdog Timer Output Register High ******************************************************************************/ /*! * @brief HW_WDOG_TMROUTH - Watchdog Timer Output Register High (RW) * * Reset value: 0x0000U */ typedef union _hw_wdog_tmrouth { uint16_t U; struct _hw_wdog_tmrouth_bitfields { uint16_t TIMEROUTHIGH : 16; /*!< [15:0] */ } B; } hw_wdog_tmrouth_t; /*! * @name Constants and macros for entire WDOG_TMROUTH register */ /*@{*/ #define HW_WDOG_TMROUTH_ADDR(x) ((x) + 0x10U) #define HW_WDOG_TMROUTH(x) (*(__IO hw_wdog_tmrouth_t *) HW_WDOG_TMROUTH_ADDR(x)) #define HW_WDOG_TMROUTH_RD(x) (HW_WDOG_TMROUTH(x).U) #define HW_WDOG_TMROUTH_WR(x, v) (HW_WDOG_TMROUTH(x).U = (v)) #define HW_WDOG_TMROUTH_SET(x, v) (HW_WDOG_TMROUTH_WR(x, HW_WDOG_TMROUTH_RD(x) | (v))) #define HW_WDOG_TMROUTH_CLR(x, v) (HW_WDOG_TMROUTH_WR(x, HW_WDOG_TMROUTH_RD(x) & ~(v))) #define HW_WDOG_TMROUTH_TOG(x, v) (HW_WDOG_TMROUTH_WR(x, HW_WDOG_TMROUTH_RD(x) ^ (v))) /*@}*/ /* * Constants & macros for individual WDOG_TMROUTH bitfields */ /*! * @name Register WDOG_TMROUTH, field TIMEROUTHIGH[15:0] (RW) * * Shows the value of the upper 16 bits of the watchdog timer. */ /*@{*/ #define BP_WDOG_TMROUTH_TIMEROUTHIGH (0U) /*!< Bit position for WDOG_TMROUTH_TIMEROUTHIGH. */ #define BM_WDOG_TMROUTH_TIMEROUTHIGH (0xFFFFU) /*!< Bit mask for WDOG_TMROUTH_TIMEROUTHIGH. */ #define BS_WDOG_TMROUTH_TIMEROUTHIGH (16U) /*!< Bit field size in bits for WDOG_TMROUTH_TIMEROUTHIGH. */ /*! @brief Read current value of the WDOG_TMROUTH_TIMEROUTHIGH field. */ #define BR_WDOG_TMROUTH_TIMEROUTHIGH(x) (HW_WDOG_TMROUTH(x).U) /*! @brief Format value for bitfield WDOG_TMROUTH_TIMEROUTHIGH. */ #define BF_WDOG_TMROUTH_TIMEROUTHIGH(v) ((uint16_t)((uint16_t)(v) << BP_WDOG_TMROUTH_TIMEROUTHIGH) & BM_WDOG_TMROUTH_TIMEROUTHIGH) /*! @brief Set the TIMEROUTHIGH field to a new value. */ #define BW_WDOG_TMROUTH_TIMEROUTHIGH(x, v) (HW_WDOG_TMROUTH_WR(x, v)) /*@}*/ /******************************************************************************* * HW_WDOG_TMROUTL - Watchdog Timer Output Register Low ******************************************************************************/ /*! * @brief HW_WDOG_TMROUTL - Watchdog Timer Output Register Low (RW) * * Reset value: 0x0000U * * During Stop mode, the WDOG_TIMER_OUT will be caught at the pre-stop value of * the watchdog timer. After exiting Stop mode, a maximum delay of 1 WDOG_CLK * cycle + 3 bus clock cycles will occur before the WDOG_TIMER_OUT starts following * the watchdog timer. */ typedef union _hw_wdog_tmroutl { uint16_t U; struct _hw_wdog_tmroutl_bitfields { uint16_t TIMEROUTLOW : 16; /*!< [15:0] */ } B; } hw_wdog_tmroutl_t; /*! * @name Constants and macros for entire WDOG_TMROUTL register */ /*@{*/ #define HW_WDOG_TMROUTL_ADDR(x) ((x) + 0x12U) #define HW_WDOG_TMROUTL(x) (*(__IO hw_wdog_tmroutl_t *) HW_WDOG_TMROUTL_ADDR(x)) #define HW_WDOG_TMROUTL_RD(x) (HW_WDOG_TMROUTL(x).U) #define HW_WDOG_TMROUTL_WR(x, v) (HW_WDOG_TMROUTL(x).U = (v)) #define HW_WDOG_TMROUTL_SET(x, v) (HW_WDOG_TMROUTL_WR(x, HW_WDOG_TMROUTL_RD(x) | (v))) #define HW_WDOG_TMROUTL_CLR(x, v) (HW_WDOG_TMROUTL_WR(x, HW_WDOG_TMROUTL_RD(x) & ~(v))) #define HW_WDOG_TMROUTL_TOG(x, v) (HW_WDOG_TMROUTL_WR(x, HW_WDOG_TMROUTL_RD(x) ^ (v))) /*@}*/ /* * Constants & macros for individual WDOG_TMROUTL bitfields */ /*! * @name Register WDOG_TMROUTL, field TIMEROUTLOW[15:0] (RW) * * Shows the value of the lower 16 bits of the watchdog timer. */ /*@{*/ #define BP_WDOG_TMROUTL_TIMEROUTLOW (0U) /*!< Bit position for WDOG_TMROUTL_TIMEROUTLOW. */ #define BM_WDOG_TMROUTL_TIMEROUTLOW (0xFFFFU) /*!< Bit mask for WDOG_TMROUTL_TIMEROUTLOW. */ #define BS_WDOG_TMROUTL_TIMEROUTLOW (16U) /*!< Bit field size in bits for WDOG_TMROUTL_TIMEROUTLOW. */ /*! @brief Read current value of the WDOG_TMROUTL_TIMEROUTLOW field. */ #define BR_WDOG_TMROUTL_TIMEROUTLOW(x) (HW_WDOG_TMROUTL(x).U) /*! @brief Format value for bitfield WDOG_TMROUTL_TIMEROUTLOW. */ #define BF_WDOG_TMROUTL_TIMEROUTLOW(v) ((uint16_t)((uint16_t)(v) << BP_WDOG_TMROUTL_TIMEROUTLOW) & BM_WDOG_TMROUTL_TIMEROUTLOW) /*! @brief Set the TIMEROUTLOW field to a new value. */ #define BW_WDOG_TMROUTL_TIMEROUTLOW(x, v) (HW_WDOG_TMROUTL_WR(x, v)) /*@}*/ /******************************************************************************* * HW_WDOG_RSTCNT - Watchdog Reset Count register ******************************************************************************/ /*! * @brief HW_WDOG_RSTCNT - Watchdog Reset Count register (RW) * * Reset value: 0x0000U */ typedef union _hw_wdog_rstcnt { uint16_t U; struct _hw_wdog_rstcnt_bitfields { uint16_t RSTCNT : 16; /*!< [15:0] */ } B; } hw_wdog_rstcnt_t; /*! * @name Constants and macros for entire WDOG_RSTCNT register */ /*@{*/ #define HW_WDOG_RSTCNT_ADDR(x) ((x) + 0x14U) #define HW_WDOG_RSTCNT(x) (*(__IO hw_wdog_rstcnt_t *) HW_WDOG_RSTCNT_ADDR(x)) #define HW_WDOG_RSTCNT_RD(x) (HW_WDOG_RSTCNT(x).U) #define HW_WDOG_RSTCNT_WR(x, v) (HW_WDOG_RSTCNT(x).U = (v)) #define HW_WDOG_RSTCNT_SET(x, v) (HW_WDOG_RSTCNT_WR(x, HW_WDOG_RSTCNT_RD(x) | (v))) #define HW_WDOG_RSTCNT_CLR(x, v) (HW_WDOG_RSTCNT_WR(x, HW_WDOG_RSTCNT_RD(x) & ~(v))) #define HW_WDOG_RSTCNT_TOG(x, v) (HW_WDOG_RSTCNT_WR(x, HW_WDOG_RSTCNT_RD(x) ^ (v))) /*@}*/ /* * Constants & macros for individual WDOG_RSTCNT bitfields */ /*! * @name Register WDOG_RSTCNT, field RSTCNT[15:0] (RW) * * Counts the number of times the watchdog resets the system. This register is * reset only on a POR. Writing 1 to the bit to be cleared enables you to clear * the contents of this register. */ /*@{*/ #define BP_WDOG_RSTCNT_RSTCNT (0U) /*!< Bit position for WDOG_RSTCNT_RSTCNT. */ #define BM_WDOG_RSTCNT_RSTCNT (0xFFFFU) /*!< Bit mask for WDOG_RSTCNT_RSTCNT. */ #define BS_WDOG_RSTCNT_RSTCNT (16U) /*!< Bit field size in bits for WDOG_RSTCNT_RSTCNT. */ /*! @brief Read current value of the WDOG_RSTCNT_RSTCNT field. */ #define BR_WDOG_RSTCNT_RSTCNT(x) (HW_WDOG_RSTCNT(x).U) /*! @brief Format value for bitfield WDOG_RSTCNT_RSTCNT. */ #define BF_WDOG_RSTCNT_RSTCNT(v) ((uint16_t)((uint16_t)(v) << BP_WDOG_RSTCNT_RSTCNT) & BM_WDOG_RSTCNT_RSTCNT) /*! @brief Set the RSTCNT field to a new value. */ #define BW_WDOG_RSTCNT_RSTCNT(x, v) (HW_WDOG_RSTCNT_WR(x, v)) /*@}*/ /******************************************************************************* * HW_WDOG_PRESC - Watchdog Prescaler register ******************************************************************************/ /*! * @brief HW_WDOG_PRESC - Watchdog Prescaler register (RW) * * Reset value: 0x0400U */ typedef union _hw_wdog_presc { uint16_t U; struct _hw_wdog_presc_bitfields { uint16_t RESERVED0 : 8; /*!< [7:0] */ uint16_t PRESCVAL : 3; /*!< [10:8] */ uint16_t RESERVED1 : 5; /*!< [15:11] */ } B; } hw_wdog_presc_t; /*! * @name Constants and macros for entire WDOG_PRESC register */ /*@{*/ #define HW_WDOG_PRESC_ADDR(x) ((x) + 0x16U) #define HW_WDOG_PRESC(x) (*(__IO hw_wdog_presc_t *) HW_WDOG_PRESC_ADDR(x)) #define HW_WDOG_PRESC_RD(x) (HW_WDOG_PRESC(x).U) #define HW_WDOG_PRESC_WR(x, v) (HW_WDOG_PRESC(x).U = (v)) #define HW_WDOG_PRESC_SET(x, v) (HW_WDOG_PRESC_WR(x, HW_WDOG_PRESC_RD(x) | (v))) #define HW_WDOG_PRESC_CLR(x, v) (HW_WDOG_PRESC_WR(x, HW_WDOG_PRESC_RD(x) & ~(v))) #define HW_WDOG_PRESC_TOG(x, v) (HW_WDOG_PRESC_WR(x, HW_WDOG_PRESC_RD(x) ^ (v))) /*@}*/ /* * Constants & macros for individual WDOG_PRESC bitfields */ /*! * @name Register WDOG_PRESC, field PRESCVAL[10:8] (RW) * * 3-bit prescaler for the watchdog clock source. A value of zero indicates no * division of the input WDOG clock. The watchdog clock is divided by (PRESCVAL + * 1) to provide the prescaled WDOG_CLK. */ /*@{*/ #define BP_WDOG_PRESC_PRESCVAL (8U) /*!< Bit position for WDOG_PRESC_PRESCVAL. */ #define BM_WDOG_PRESC_PRESCVAL (0x0700U) /*!< Bit mask for WDOG_PRESC_PRESCVAL. */ #define BS_WDOG_PRESC_PRESCVAL (3U) /*!< Bit field size in bits for WDOG_PRESC_PRESCVAL. */ /*! @brief Read current value of the WDOG_PRESC_PRESCVAL field. */ #define BR_WDOG_PRESC_PRESCVAL(x) (HW_WDOG_PRESC(x).B.PRESCVAL) /*! @brief Format value for bitfield WDOG_PRESC_PRESCVAL. */ #define BF_WDOG_PRESC_PRESCVAL(v) ((uint16_t)((uint16_t)(v) << BP_WDOG_PRESC_PRESCVAL) & BM_WDOG_PRESC_PRESCVAL) /*! @brief Set the PRESCVAL field to a new value. */ #define BW_WDOG_PRESC_PRESCVAL(x, v) (HW_WDOG_PRESC_WR(x, (HW_WDOG_PRESC_RD(x) & ~BM_WDOG_PRESC_PRESCVAL) | BF_WDOG_PRESC_PRESCVAL(v))) /*@}*/ /******************************************************************************* * hw_wdog_t - module struct ******************************************************************************/ /*! * @brief All WDOG module registers. */ #pragma pack(1) typedef struct _hw_wdog { __IO hw_wdog_stctrlh_t STCTRLH; /*!< [0x0] Watchdog Status and Control Register High */ __IO hw_wdog_stctrll_t STCTRLL; /*!< [0x2] Watchdog Status and Control Register Low */ __IO hw_wdog_tovalh_t TOVALH; /*!< [0x4] Watchdog Time-out Value Register High */ __IO hw_wdog_tovall_t TOVALL; /*!< [0x6] Watchdog Time-out Value Register Low */ __IO hw_wdog_winh_t WINH; /*!< [0x8] Watchdog Window Register High */ __IO hw_wdog_winl_t WINL; /*!< [0xA] Watchdog Window Register Low */ __IO hw_wdog_refresh_t REFRESH; /*!< [0xC] Watchdog Refresh register */ __IO hw_wdog_unlock_t UNLOCK; /*!< [0xE] Watchdog Unlock register */ __IO hw_wdog_tmrouth_t TMROUTH; /*!< [0x10] Watchdog Timer Output Register High */ __IO hw_wdog_tmroutl_t TMROUTL; /*!< [0x12] Watchdog Timer Output Register Low */ __IO hw_wdog_rstcnt_t RSTCNT; /*!< [0x14] Watchdog Reset Count register */ __IO hw_wdog_presc_t PRESC; /*!< [0x16] Watchdog Prescaler register */ } hw_wdog_t; #pragma pack() /*! @brief Macro to access all WDOG registers. */ /*! @param x WDOG module instance base address. */ /*! @return Reference (not a pointer) to the registers struct. To get a pointer to the struct, * use the '&' operator, like &HW_WDOG(WDOG_BASE). */ #define HW_WDOG(x) (*(hw_wdog_t *)(x)) #endif /* __HW_WDOG_REGISTERS_H__ */ /* EOF */ ================================================ FILE: Zelig/mbed/TARGET_K64F/TARGET_Freescale/TARGET_KPSDK_MCUS/TARGET_MCU_K64F/device/device/fsl_device_registers.h ================================================ /* * Copyright (c) 2014, Freescale Semiconductor, Inc. * All rights reserved. * * Redistribution and use in source and binary forms, with or without modification, * are permitted provided that the following conditions are met: * * o Redistributions of source code must retain the above copyright notice, this list * of conditions and the following disclaimer. * * o Redistributions in binary form must reproduce the above copyright notice, this * list of conditions and the following disclaimer in the documentation and/or * other materials provided with the distribution. * * o Neither the name of Freescale Semiconductor, Inc. nor the names of its * contributors may be used to endorse or promote products derived from this * software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT 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. */ #ifndef __FSL_DEVICE_REGISTERS_H__ #define __FSL_DEVICE_REGISTERS_H__ /* * Include the cpu specific register header files. * * The CPU macro should be declared in the project or makefile. */ #if (defined(CPU_MK02FN128VFM10) || defined(CPU_MK02FN64VFM10) || defined(CPU_MK02FN128VLF10) || \ defined(CPU_MK02FN64VLF10) || defined(CPU_MK02FN128VLH10) || defined(CPU_MK02FN64VLH10)) #define K02F12810_SERIES /* CMSIS-style register definitions */ #include "device/MK02F12810/MK02F12810.h" /* Extension register headers. (These will eventually be merged into the CMSIS-style header.) */ #include "device/MK02F12810/MK02F12810_adc.h" #include "device/MK02F12810/MK02F12810_cmp.h" #include "device/MK02F12810/MK02F12810_crc.h" #include "device/MK02F12810/MK02F12810_dac.h" #include "device/MK02F12810/MK02F12810_dma.h" #include "device/MK02F12810/MK02F12810_dmamux.h" #include "device/MK02F12810/MK02F12810_ewm.h" #include "device/MK02F12810/MK02F12810_fmc.h" #include "device/MK02F12810/MK02F12810_ftfa.h" #include "device/MK02F12810/MK02F12810_ftm.h" #include "device/MK02F12810/MK02F12810_gpio.h" #include "device/MK02F12810/MK02F12810_i2c.h" #include "device/MK02F12810/MK02F12810_llwu.h" #include "device/MK02F12810/MK02F12810_lptmr.h" #include "device/MK02F12810/MK02F12810_mcg.h" #include "device/MK02F12810/MK02F12810_mcm.h" #include "device/MK02F12810/MK02F12810_nv.h" #include "device/MK02F12810/MK02F12810_osc.h" #include "device/MK02F12810/MK02F12810_pdb.h" #include "device/MK02F12810/MK02F12810_pit.h" #include "device/MK02F12810/MK02F12810_pmc.h" #include "device/MK02F12810/MK02F12810_port.h" #include "device/MK02F12810/MK02F12810_rcm.h" #include "device/MK02F12810/MK02F12810_sim.h" #include "device/MK02F12810/MK02F12810_smc.h" #include "device/MK02F12810/MK02F12810_spi.h" #include "device/MK02F12810/MK02F12810_uart.h" #include "device/MK02F12810/MK02F12810_vref.h" #include "device/MK02F12810/MK02F12810_wdog.h" #elif (defined(CPU_MK20DX128VMP5) || defined(CPU_MK20DN128VMP5) || defined(CPU_MK20DX64VMP5) || \ defined(CPU_MK20DN64VMP5) || defined(CPU_MK20DX32VMP5) || defined(CPU_MK20DN32VMP5) || \ defined(CPU_MK20DX128VLH5) || defined(CPU_MK20DN128VLH5) || defined(CPU_MK20DX64VLH5) || \ defined(CPU_MK20DN64VLH5) || defined(CPU_MK20DX32VLH5) || defined(CPU_MK20DN32VLH5) || \ defined(CPU_MK20DX128VFM5) || defined(CPU_MK20DN128VFM5) || defined(CPU_MK20DX64VFM5) || \ defined(CPU_MK20DN64VFM5) || defined(CPU_MK20DX32VFM5) || defined(CPU_MK20DN32VFM5) || \ defined(CPU_MK20DX128VFT5) || defined(CPU_MK20DN128VFT5) || defined(CPU_MK20DX64VFT5) || \ defined(CPU_MK20DN64VFT5) || defined(CPU_MK20DX32VFT5) || defined(CPU_MK20DN32VFT5) || \ defined(CPU_MK20DX128VLF5) || defined(CPU_MK20DN128VLF5) || defined(CPU_MK20DX64VLF5) || \ defined(CPU_MK20DN64VLF5) || defined(CPU_MK20DX32VLF5) || defined(CPU_MK20DN32VLF5)) #define K20D5_SERIES /* CMSIS-style register definitions */ #include "device/MK20D5/MK20D5.h" /* Extension register headers. (These will eventually be merged into the CMSIS-style header.) */ #include "device/MK20D5/MK20D5_adc.h" #include "device/MK20D5/MK20D5_cmp.h" #include "device/MK20D5/MK20D5_cmt.h" #include "device/MK20D5/MK20D5_crc.h" #include "device/MK20D5/MK20D5_dma.h" #include "device/MK20D5/MK20D5_dmamux.h" #include "device/MK20D5/MK20D5_ewm.h" #include "device/MK20D5/MK20D5_fmc.h" #include "device/MK20D5/MK20D5_ftfl.h" #include "device/MK20D5/MK20D5_ftm.h" #include "device/MK20D5/MK20D5_gpio.h" #include "device/MK20D5/MK20D5_i2c.h" #include "device/MK20D5/MK20D5_i2s.h" #include "device/MK20D5/MK20D5_llwu.h" #include "device/MK20D5/MK20D5_lptmr.h" #include "device/MK20D5/MK20D5_mcg.h" #include "device/MK20D5/MK20D5_nv.h" #include "device/MK20D5/MK20D5_osc.h" #include "device/MK20D5/MK20D5_pdb.h" #include "device/MK20D5/MK20D5_pit.h" #include "device/MK20D5/MK20D5_pmc.h" #include "device/MK20D5/MK20D5_port.h" #include "device/MK20D5/MK20D5_rcm.h" #include "device/MK20D5/MK20D5_rfsys.h" #include "device/MK20D5/MK20D5_rfvbat.h" #include "device/MK20D5/MK20D5_rtc.h" #include "device/MK20D5/MK20D5_sim.h" #include "device/MK20D5/MK20D5_smc.h" #include "device/MK20D5/MK20D5_spi.h" #include "device/MK20D5/MK20D5_tsi.h" #include "device/MK20D5/MK20D5_uart.h" #include "device/MK20D5/MK20D5_usb.h" #include "device/MK20D5/MK20D5_usbdcd.h" #include "device/MK20D5/MK20D5_vref.h" #include "device/MK20D5/MK20D5_wdog.h" #elif (defined(CPU_MK22FN128VDC10) || defined(CPU_MK22FN128VLH10) || defined(CPU_MK22FN128VLL10) || \ defined(CPU_MK22FN128VMP10)) #define K22F12810_SERIES /* CMSIS-style register definitions */ #include "device/MK22F12810/MK22F12810.h" /* Extension register headers. (These will eventually be merged into the CMSIS-style header.) */ #include "device/MK22F12810/MK22F12810_adc.h" #include "device/MK22F12810/MK22F12810_cmp.h" #include "device/MK22F12810/MK22F12810_crc.h" #include "device/MK22F12810/MK22F12810_dac.h" #include "device/MK22F12810/MK22F12810_dma.h" #include "device/MK22F12810/MK22F12810_dmamux.h" #include "device/MK22F12810/MK22F12810_ewm.h" #include "device/MK22F12810/MK22F12810_fmc.h" #include "device/MK22F12810/MK22F12810_ftfa.h" #include "device/MK22F12810/MK22F12810_ftm.h" #include "device/MK22F12810/MK22F12810_gpio.h" #include "device/MK22F12810/MK22F12810_i2c.h" #include "device/MK22F12810/MK22F12810_i2s.h" #include "device/MK22F12810/MK22F12810_llwu.h" #include "device/MK22F12810/MK22F12810_lptmr.h" #include "device/MK22F12810/MK22F12810_lpuart.h" #include "device/MK22F12810/MK22F12810_mcg.h" #include "device/MK22F12810/MK22F12810_mcm.h" #include "device/MK22F12810/MK22F12810_nv.h" #include "device/MK22F12810/MK22F12810_osc.h" #include "device/MK22F12810/MK22F12810_pdb.h" #include "device/MK22F12810/MK22F12810_pit.h" #include "device/MK22F12810/MK22F12810_pmc.h" #include "device/MK22F12810/MK22F12810_port.h" #include "device/MK22F12810/MK22F12810_rcm.h" #include "device/MK22F12810/MK22F12810_rfsys.h" #include "device/MK22F12810/MK22F12810_rfvbat.h" #include "device/MK22F12810/MK22F12810_rtc.h" #include "device/MK22F12810/MK22F12810_sim.h" #include "device/MK22F12810/MK22F12810_smc.h" #include "device/MK22F12810/MK22F12810_spi.h" #include "device/MK22F12810/MK22F12810_uart.h" #include "device/MK22F12810/MK22F12810_usb.h" #include "device/MK22F12810/MK22F12810_vref.h" #include "device/MK22F12810/MK22F12810_wdog.h" #elif (defined(CPU_MK22FN256VDC12) || defined(CPU_MK22FN256VLH12) || defined(CPU_MK22FN256VLL12) || \ defined(CPU_MK22FN256VMP12)) #define K22F25612_SERIES /* CMSIS-style register definitions */ #include "device/MK22F25612/MK22F25612.h" /* Extension register headers. (These will eventually be merged into the CMSIS-style header.) */ #include "device/MK22F25612/MK22F25612_adc.h" #include "device/MK22F25612/MK22F25612_cmp.h" #include "device/MK22F25612/MK22F25612_crc.h" #include "device/MK22F25612/MK22F25612_dac.h" #include "device/MK22F25612/MK22F25612_dma.h" #include "device/MK22F25612/MK22F25612_dmamux.h" #include "device/MK22F25612/MK22F25612_ewm.h" #include "device/MK22F25612/MK22F25612_fmc.h" #include "device/MK22F25612/MK22F25612_ftfa.h" #include "device/MK22F25612/MK22F25612_ftm.h" #include "device/MK22F25612/MK22F25612_gpio.h" #include "device/MK22F25612/MK22F25612_i2c.h" #include "device/MK22F25612/MK22F25612_i2s.h" #include "device/MK22F25612/MK22F25612_llwu.h" #include "device/MK22F25612/MK22F25612_lptmr.h" #include "device/MK22F25612/MK22F25612_lpuart.h" #include "device/MK22F25612/MK22F25612_mcg.h" #include "device/MK22F25612/MK22F25612_mcm.h" #include "device/MK22F25612/MK22F25612_nv.h" #include "device/MK22F25612/MK22F25612_osc.h" #include "device/MK22F25612/MK22F25612_pdb.h" #include "device/MK22F25612/MK22F25612_pit.h" #include "device/MK22F25612/MK22F25612_pmc.h" #include "device/MK22F25612/MK22F25612_port.h" #include "device/MK22F25612/MK22F25612_rcm.h" #include "device/MK22F25612/MK22F25612_rfsys.h" #include "device/MK22F25612/MK22F25612_rfvbat.h" #include "device/MK22F25612/MK22F25612_rng.h" #include "device/MK22F25612/MK22F25612_rtc.h" #include "device/MK22F25612/MK22F25612_sim.h" #include "device/MK22F25612/MK22F25612_smc.h" #include "device/MK22F25612/MK22F25612_spi.h" #include "device/MK22F25612/MK22F25612_uart.h" #include "device/MK22F25612/MK22F25612_usb.h" #include "device/MK22F25612/MK22F25612_vref.h" #include "device/MK22F25612/MK22F25612_wdog.h" #elif (defined(CPU_MK22FN512VDC12) || defined(CPU_MK22FN512VLH12) || defined(CPU_MK22FN512VLL12)) #define K22F51212_SERIES /* CMSIS-style register definitions */ #include "device/MK22F51212/MK22F51212.h" /* Extension register headers. (These will eventually be merged into the CMSIS-style header.) */ #include "device/MK22F51212/MK22F51212_adc.h" #include "device/MK22F51212/MK22F51212_cmp.h" #include "device/MK22F51212/MK22F51212_crc.h" #include "device/MK22F51212/MK22F51212_dac.h" #include "device/MK22F51212/MK22F51212_dma.h" #include "device/MK22F51212/MK22F51212_dmamux.h" #include "device/MK22F51212/MK22F51212_ewm.h" #include "device/MK22F51212/MK22F51212_fb.h" #include "device/MK22F51212/MK22F51212_fmc.h" #include "device/MK22F51212/MK22F51212_ftfa.h" #include "device/MK22F51212/MK22F51212_ftm.h" #include "device/MK22F51212/MK22F51212_gpio.h" #include "device/MK22F51212/MK22F51212_i2c.h" #include "device/MK22F51212/MK22F51212_i2s.h" #include "device/MK22F51212/MK22F51212_llwu.h" #include "device/MK22F51212/MK22F51212_lptmr.h" #include "device/MK22F51212/MK22F51212_lpuart.h" #include "device/MK22F51212/MK22F51212_mcg.h" #include "device/MK22F51212/MK22F51212_mcm.h" #include "device/MK22F51212/MK22F51212_nv.h" #include "device/MK22F51212/MK22F51212_osc.h" #include "device/MK22F51212/MK22F51212_pdb.h" #include "device/MK22F51212/MK22F51212_pit.h" #include "device/MK22F51212/MK22F51212_pmc.h" #include "device/MK22F51212/MK22F51212_port.h" #include "device/MK22F51212/MK22F51212_rcm.h" #include "device/MK22F51212/MK22F51212_rfsys.h" #include "device/MK22F51212/MK22F51212_rfvbat.h" #include "device/MK22F51212/MK22F51212_rng.h" #include "device/MK22F51212/MK22F51212_rtc.h" #include "device/MK22F51212/MK22F51212_sim.h" #include "device/MK22F51212/MK22F51212_smc.h" #include "device/MK22F51212/MK22F51212_spi.h" #include "device/MK22F51212/MK22F51212_uart.h" #include "device/MK22F51212/MK22F51212_usb.h" #include "device/MK22F51212/MK22F51212_vref.h" #include "device/MK22F51212/MK22F51212_wdog.h" #elif (defined(CPU_MK24FN1M0VDC12) || defined(CPU_MK24FN1M0VLQ12)) #define K24F12_SERIES /* CMSIS-style register definitions */ #include "device/MK24F12/MK24F12.h" /* Extension register headers. (These will eventually be merged into the CMSIS-style header.) */ #include "device/MK24F12/MK24F12_adc.h" #include "device/MK24F12/MK24F12_aips.h" #include "device/MK24F12/MK24F12_axbs.h" #include "device/MK24F12/MK24F12_can.h" #include "device/MK24F12/MK24F12_cau.h" #include "device/MK24F12/MK24F12_cmp.h" #include "device/MK24F12/MK24F12_cmt.h" #include "device/MK24F12/MK24F12_crc.h" #include "device/MK24F12/MK24F12_dac.h" #include "device/MK24F12/MK24F12_dma.h" #include "device/MK24F12/MK24F12_dmamux.h" #include "device/MK24F12/MK24F12_ewm.h" #include "device/MK24F12/MK24F12_fb.h" #include "device/MK24F12/MK24F12_fmc.h" #include "device/MK24F12/MK24F12_ftfe.h" #include "device/MK24F12/MK24F12_ftm.h" #include "device/MK24F12/MK24F12_gpio.h" #include "device/MK24F12/MK24F12_i2c.h" #include "device/MK24F12/MK24F12_i2s.h" #include "device/MK24F12/MK24F12_llwu.h" #include "device/MK24F12/MK24F12_lptmr.h" #include "device/MK24F12/MK24F12_mcg.h" #include "device/MK24F12/MK24F12_mcm.h" #include "device/MK24F12/MK24F12_mpu.h" #include "device/MK24F12/MK24F12_nv.h" #include "device/MK24F12/MK24F12_osc.h" #include "device/MK24F12/MK24F12_pdb.h" #include "device/MK24F12/MK24F12_pit.h" #include "device/MK24F12/MK24F12_pmc.h" #include "device/MK24F12/MK24F12_port.h" #include "device/MK24F12/MK24F12_rcm.h" #include "device/MK24F12/MK24F12_rfsys.h" #include "device/MK24F12/MK24F12_rfvbat.h" #include "device/MK24F12/MK24F12_rng.h" #include "device/MK24F12/MK24F12_rtc.h" #include "device/MK24F12/MK24F12_sdhc.h" #include "device/MK24F12/MK24F12_sim.h" #include "device/MK24F12/MK24F12_smc.h" #include "device/MK24F12/MK24F12_spi.h" #include "device/MK24F12/MK24F12_uart.h" #include "device/MK24F12/MK24F12_usb.h" #include "device/MK24F12/MK24F12_usbdcd.h" #include "device/MK24F12/MK24F12_vref.h" #include "device/MK24F12/MK24F12_wdog.h" #elif (defined(CPU_MK24FN256VDC12)) #define K24F25612_SERIES /* CMSIS-style register definitions */ #include "device/MK24F25612/MK24F25612.h" /* Extension register headers. (These will eventually be merged into the CMSIS-style header.) */ #include "device/MK24F25612/MK24F25612_adc.h" #include "device/MK24F25612/MK24F25612_aips.h" #include "device/MK24F25612/MK24F25612_cmp.h" #include "device/MK24F25612/MK24F25612_cmt.h" #include "device/MK24F25612/MK24F25612_crc.h" #include "device/MK24F25612/MK24F25612_dac.h" #include "device/MK24F25612/MK24F25612_dma.h" #include "device/MK24F25612/MK24F25612_dmamux.h" #include "device/MK24F25612/MK24F25612_ewm.h" #include "device/MK24F25612/MK24F25612_fmc.h" #include "device/MK24F25612/MK24F25612_ftfa.h" #include "device/MK24F25612/MK24F25612_ftm.h" #include "device/MK24F25612/MK24F25612_gpio.h" #include "device/MK24F25612/MK24F25612_i2c.h" #include "device/MK24F25612/MK24F25612_i2s.h" #include "device/MK24F25612/MK24F25612_llwu.h" #include "device/MK24F25612/MK24F25612_lptmr.h" #include "device/MK24F25612/MK24F25612_mcg.h" #include "device/MK24F25612/MK24F25612_mcm.h" #include "device/MK24F25612/MK24F25612_osc.h" #include "device/MK24F25612/MK24F25612_pdb.h" #include "device/MK24F25612/MK24F25612_pit.h" #include "device/MK24F25612/MK24F25612_pmc.h" #include "device/MK24F25612/MK24F25612_port.h" #include "device/MK24F25612/MK24F25612_rcm.h" #include "device/MK24F25612/MK24F25612_rfsys.h" #include "device/MK24F25612/MK24F25612_rfvbat.h" #include "device/MK24F25612/MK24F25612_rng.h" #include "device/MK24F25612/MK24F25612_rtc.h" #include "device/MK24F25612/MK24F25612_sim.h" #include "device/MK24F25612/MK24F25612_smc.h" #include "device/MK24F25612/MK24F25612_spi.h" #include "device/MK24F25612/MK24F25612_uart.h" #include "device/MK24F25612/MK24F25612_usb.h" #include "device/MK24F25612/MK24F25612_usbdcd.h" #include "device/MK24F25612/MK24F25612_vref.h" #include "device/MK24F25612/MK24F25612_wdog.h" #elif (defined(CPU_MK63FN1M0VLQ12) || defined(CPU_MK63FN1M0VMD12)) #define K63F12_SERIES /* CMSIS-style register definitions */ #include "device/MK63F12/MK63F12.h" /* Extension register headers. (These will eventually be merged into the CMSIS-style header.) */ #include "device/MK63F12/MK63F12_adc.h" #include "device/MK63F12/MK63F12_aips.h" #include "device/MK63F12/MK63F12_axbs.h" #include "device/MK63F12/MK63F12_can.h" #include "device/MK63F12/MK63F12_cau.h" #include "device/MK63F12/MK63F12_cmp.h" #include "device/MK63F12/MK63F12_cmt.h" #include "device/MK63F12/MK63F12_crc.h" #include "device/MK63F12/MK63F12_dac.h" #include "device/MK63F12/MK63F12_dma.h" #include "device/MK63F12/MK63F12_dmamux.h" #include "device/MK63F12/MK63F12_enet.h" #include "device/MK63F12/MK63F12_ewm.h" #include "device/MK63F12/MK63F12_fb.h" #include "device/MK63F12/MK63F12_fmc.h" #include "device/MK63F12/MK63F12_ftfe.h" #include "device/MK63F12/MK63F12_ftm.h" #include "device/MK63F12/MK63F12_gpio.h" #include "device/MK63F12/MK63F12_i2c.h" #include "device/MK63F12/MK63F12_i2s.h" #include "device/MK63F12/MK63F12_llwu.h" #include "device/MK63F12/MK63F12_lptmr.h" #include "device/MK63F12/MK63F12_mcg.h" #include "device/MK63F12/MK63F12_mcm.h" #include "device/MK63F12/MK63F12_mpu.h" #include "device/MK63F12/MK63F12_nv.h" #include "device/MK63F12/MK63F12_osc.h" #include "device/MK63F12/MK63F12_pdb.h" #include "device/MK63F12/MK63F12_pit.h" #include "device/MK63F12/MK63F12_pmc.h" #include "device/MK63F12/MK63F12_port.h" #include "device/MK63F12/MK63F12_rcm.h" #include "device/MK63F12/MK63F12_rfsys.h" #include "device/MK63F12/MK63F12_rfvbat.h" #include "device/MK63F12/MK63F12_rng.h" #include "device/MK63F12/MK63F12_rtc.h" #include "device/MK63F12/MK63F12_sdhc.h" #include "device/MK63F12/MK63F12_sim.h" #include "device/MK63F12/MK63F12_smc.h" #include "device/MK63F12/MK63F12_spi.h" #include "device/MK63F12/MK63F12_uart.h" #include "device/MK63F12/MK63F12_usb.h" #include "device/MK63F12/MK63F12_usbdcd.h" #include "device/MK63F12/MK63F12_vref.h" #include "device/MK63F12/MK63F12_wdog.h" #elif (defined(CPU_MK64FX512VDC12) || defined(CPU_MK64FN1M0VDC12) || defined(CPU_MK64FX512VLL12) || \ defined(CPU_MK64FN1M0VLL12) || defined(CPU_MK64FX512VLQ12) || defined(CPU_MK64FN1M0VLQ12) || \ defined(CPU_MK64FX512VMD12) || defined(CPU_MK64FN1M0VMD12)) #define K64F12_SERIES /* CMSIS-style register definitions */ #include "device/MK64F12/MK64F12.h" /* Extension register headers. (These will eventually be merged into the CMSIS-style header.) */ #include "device/MK64F12/MK64F12_adc.h" #include "device/MK64F12/MK64F12_aips.h" #include "device/MK64F12/MK64F12_axbs.h" #include "device/MK64F12/MK64F12_can.h" #include "device/MK64F12/MK64F12_cau.h" #include "device/MK64F12/MK64F12_cmp.h" #include "device/MK64F12/MK64F12_cmt.h" #include "device/MK64F12/MK64F12_crc.h" #include "device/MK64F12/MK64F12_dac.h" #include "device/MK64F12/MK64F12_dma.h" #include "device/MK64F12/MK64F12_dmamux.h" #include "device/MK64F12/MK64F12_enet.h" #include "device/MK64F12/MK64F12_ewm.h" #include "device/MK64F12/MK64F12_fb.h" #include "device/MK64F12/MK64F12_fmc.h" #include "device/MK64F12/MK64F12_ftfe.h" #include "device/MK64F12/MK64F12_ftm.h" #include "device/MK64F12/MK64F12_gpio.h" #include "device/MK64F12/MK64F12_i2c.h" #include "device/MK64F12/MK64F12_i2s.h" #include "device/MK64F12/MK64F12_llwu.h" #include "device/MK64F12/MK64F12_lptmr.h" #include "device/MK64F12/MK64F12_mcg.h" #include "device/MK64F12/MK64F12_mcm.h" #include "device/MK64F12/MK64F12_mpu.h" #include "device/MK64F12/MK64F12_nv.h" #include "device/MK64F12/MK64F12_osc.h" #include "device/MK64F12/MK64F12_pdb.h" #include "device/MK64F12/MK64F12_pit.h" #include "device/MK64F12/MK64F12_pmc.h" #include "device/MK64F12/MK64F12_port.h" #include "device/MK64F12/MK64F12_rcm.h" #include "device/MK64F12/MK64F12_rfsys.h" #include "device/MK64F12/MK64F12_rfvbat.h" #include "device/MK64F12/MK64F12_rng.h" #include "device/MK64F12/MK64F12_rtc.h" #include "device/MK64F12/MK64F12_sdhc.h" #include "device/MK64F12/MK64F12_sim.h" #include "device/MK64F12/MK64F12_smc.h" #include "device/MK64F12/MK64F12_spi.h" #include "device/MK64F12/MK64F12_uart.h" #include "device/MK64F12/MK64F12_usb.h" #include "device/MK64F12/MK64F12_usbdcd.h" #include "device/MK64F12/MK64F12_vref.h" #include "device/MK64F12/MK64F12_wdog.h" #elif (defined(CPU_MK65FN2M0CAC18) || defined(CPU_MK65FX1M0CAC18) || defined(CPU_MK65FN2M0VMI18) || \ defined(CPU_MK65FX1M0VMI18)) #define K65F18_SERIES /* CMSIS-style register definitions */ #include "device/MK65F18/MK65F18.h" /* Extension register headers. (These will eventually be merged into the CMSIS-style header.) */ #include "device/MK65F18/MK65F18_adc.h" #include "device/MK65F18/MK65F18_aips.h" #include "device/MK65F18/MK65F18_axbs.h" #include "device/MK65F18/MK65F18_can.h" #include "device/MK65F18/MK65F18_cau.h" #include "device/MK65F18/MK65F18_cmp.h" #include "device/MK65F18/MK65F18_cmt.h" #include "device/MK65F18/MK65F18_crc.h" #include "device/MK65F18/MK65F18_dac.h" #include "device/MK65F18/MK65F18_dma.h" #include "device/MK65F18/MK65F18_dmamux.h" #include "device/MK65F18/MK65F18_enet.h" #include "device/MK65F18/MK65F18_ewm.h" #include "device/MK65F18/MK65F18_fb.h" #include "device/MK65F18/MK65F18_fmc.h" #include "device/MK65F18/MK65F18_ftfe.h" #include "device/MK65F18/MK65F18_ftm.h" #include "device/MK65F18/MK65F18_gpio.h" #include "device/MK65F18/MK65F18_i2c.h" #include "device/MK65F18/MK65F18_i2s.h" #include "device/MK65F18/MK65F18_llwu.h" #include "device/MK65F18/MK65F18_lmem.h" #include "device/MK65F18/MK65F18_lptmr.h" #include "device/MK65F18/MK65F18_lpuart.h" #include "device/MK65F18/MK65F18_mcg.h" #include "device/MK65F18/MK65F18_mcm.h" #include "device/MK65F18/MK65F18_mpu.h" #include "device/MK65F18/MK65F18_nv.h" #include "device/MK65F18/MK65F18_osc.h" #include "device/MK65F18/MK65F18_pdb.h" #include "device/MK65F18/MK65F18_pit.h" #include "device/MK65F18/MK65F18_pmc.h" #include "device/MK65F18/MK65F18_port.h" #include "device/MK65F18/MK65F18_rcm.h" #include "device/MK65F18/MK65F18_rfsys.h" #include "device/MK65F18/MK65F18_rfvbat.h" #include "device/MK65F18/MK65F18_rng.h" #include "device/MK65F18/MK65F18_rtc.h" #include "device/MK65F18/MK65F18_sdhc.h" #include "device/MK65F18/MK65F18_sdram.h" #include "device/MK65F18/MK65F18_sim.h" #include "device/MK65F18/MK65F18_smc.h" #include "device/MK65F18/MK65F18_spi.h" #include "device/MK65F18/MK65F18_tpm.h" #include "device/MK65F18/MK65F18_tsi.h" #include "device/MK65F18/MK65F18_uart.h" #include "device/MK65F18/MK65F18_usb.h" #include "device/MK65F18/MK65F18_usbdcd.h" #include "device/MK65F18/MK65F18_usbhs.h" #include "device/MK65F18/MK65F18_usbhsdcd.h" #include "device/MK65F18/MK65F18_usbphy.h" #include "device/MK65F18/MK65F18_vref.h" #include "device/MK65F18/MK65F18_wdog.h" #elif (defined(CPU_MK66FN2M0VLQ18) || defined(CPU_MK66FX1M0VLQ18) || defined(CPU_MK66FN2M0VMD18) || \ defined(CPU_MK66FX1M0VMD18)) #define K66F18_SERIES /* CMSIS-style register definitions */ #include "device/MK66F18/MK66F18.h" /* Extension register headers. (These will eventually be merged into the CMSIS-style header.) */ #include "device/MK66F18/MK66F18_adc.h" #include "device/MK66F18/MK66F18_aips.h" #include "device/MK66F18/MK66F18_axbs.h" #include "device/MK66F18/MK66F18_can.h" #include "device/MK66F18/MK66F18_cau.h" #include "device/MK66F18/MK66F18_cmp.h" #include "device/MK66F18/MK66F18_cmt.h" #include "device/MK66F18/MK66F18_crc.h" #include "device/MK66F18/MK66F18_dac.h" #include "device/MK66F18/MK66F18_dma.h" #include "device/MK66F18/MK66F18_dmamux.h" #include "device/MK66F18/MK66F18_enet.h" #include "device/MK66F18/MK66F18_ewm.h" #include "device/MK66F18/MK66F18_fb.h" #include "device/MK66F18/MK66F18_fmc.h" #include "device/MK66F18/MK66F18_ftfe.h" #include "device/MK66F18/MK66F18_ftm.h" #include "device/MK66F18/MK66F18_gpio.h" #include "device/MK66F18/MK66F18_i2c.h" #include "device/MK66F18/MK66F18_i2s.h" #include "device/MK66F18/MK66F18_llwu.h" #include "device/MK66F18/MK66F18_lmem.h" #include "device/MK66F18/MK66F18_lptmr.h" #include "device/MK66F18/MK66F18_lpuart.h" #include "device/MK66F18/MK66F18_mcg.h" #include "device/MK66F18/MK66F18_mcm.h" #include "device/MK66F18/MK66F18_mpu.h" #include "device/MK66F18/MK66F18_nv.h" #include "device/MK66F18/MK66F18_osc.h" #include "device/MK66F18/MK66F18_pdb.h" #include "device/MK66F18/MK66F18_pit.h" #include "device/MK66F18/MK66F18_pmc.h" #include "device/MK66F18/MK66F18_port.h" #include "device/MK66F18/MK66F18_rcm.h" #include "device/MK66F18/MK66F18_rfsys.h" #include "device/MK66F18/MK66F18_rfvbat.h" #include "device/MK66F18/MK66F18_rng.h" #include "device/MK66F18/MK66F18_rtc.h" #include "device/MK66F18/MK66F18_sdhc.h" #include "device/MK66F18/MK66F18_sdram.h" #include "device/MK66F18/MK66F18_sim.h" #include "device/MK66F18/MK66F18_smc.h" #include "device/MK66F18/MK66F18_spi.h" #include "device/MK66F18/MK66F18_tpm.h" #include "device/MK66F18/MK66F18_tsi.h" #include "device/MK66F18/MK66F18_uart.h" #include "device/MK66F18/MK66F18_usb.h" #include "device/MK66F18/MK66F18_usbdcd.h" #include "device/MK66F18/MK66F18_usbhs.h" #include "device/MK66F18/MK66F18_usbhsdcd.h" #include "device/MK66F18/MK66F18_usbphy.h" #include "device/MK66F18/MK66F18_vref.h" #include "device/MK66F18/MK66F18_wdog.h" #elif (defined(CPU_MK70FN1M0VMF12) || defined(CPU_MK70FX512VMF12) || defined(CPU_MK70FN1M0VMF15) || \ defined(CPU_MK70FX512VMF15) || defined(CPU_MK70FN1M0VMJ12) || defined(CPU_MK70FX512VMJ12) || \ defined(CPU_MK70FN1M0VMJ15) || defined(CPU_MK70FX512VMJ15)) #define K70F12_SERIES /* CMSIS-style register definitions */ #include "device/MK70F12/MK70F12.h" /* Extension register headers. (These will eventually be merged into the CMSIS-style header.) */ #include "device/MK70F12/MK70F12_adc.h" #include "device/MK70F12/MK70F12_aips.h" #include "device/MK70F12/MK70F12_axbs.h" #include "device/MK70F12/MK70F12_can.h" #include "device/MK70F12/MK70F12_cau.h" #include "device/MK70F12/MK70F12_cmp.h" #include "device/MK70F12/MK70F12_cmt.h" #include "device/MK70F12/MK70F12_crc.h" #include "device/MK70F12/MK70F12_dac.h" #include "device/MK70F12/MK70F12_ddr.h" #include "device/MK70F12/MK70F12_dma.h" #include "device/MK70F12/MK70F12_dmamux.h" #include "device/MK70F12/MK70F12_enet.h" #include "device/MK70F12/MK70F12_ewm.h" #include "device/MK70F12/MK70F12_fb.h" #include "device/MK70F12/MK70F12_fmc.h" #include "device/MK70F12/MK70F12_ftfe.h" #include "device/MK70F12/MK70F12_ftm.h" #include "device/MK70F12/MK70F12_gpio.h" #include "device/MK70F12/MK70F12_i2c.h" #include "device/MK70F12/MK70F12_i2s.h" #include "device/MK70F12/MK70F12_lcdc.h" #include "device/MK70F12/MK70F12_llwu.h" #include "device/MK70F12/MK70F12_lmem.h" #include "device/MK70F12/MK70F12_lptmr.h" #include "device/MK70F12/MK70F12_mcg.h" #include "device/MK70F12/MK70F12_mcm.h" #include "device/MK70F12/MK70F12_mpu.h" #include "device/MK70F12/MK70F12_nfc.h" #include "device/MK70F12/MK70F12_nv.h" #include "device/MK70F12/MK70F12_osc.h" #include "device/MK70F12/MK70F12_pdb.h" #include "device/MK70F12/MK70F12_pit.h" #include "device/MK70F12/MK70F12_pmc.h" #include "device/MK70F12/MK70F12_port.h" #include "device/MK70F12/MK70F12_rcm.h" #include "device/MK70F12/MK70F12_rfsys.h" #include "device/MK70F12/MK70F12_rfvbat.h" #include "device/MK70F12/MK70F12_rng.h" #include "device/MK70F12/MK70F12_rtc.h" #include "device/MK70F12/MK70F12_sdhc.h" #include "device/MK70F12/MK70F12_sim.h" #include "device/MK70F12/MK70F12_smc.h" #include "device/MK70F12/MK70F12_spi.h" #include "device/MK70F12/MK70F12_tsi.h" #include "device/MK70F12/MK70F12_uart.h" #include "device/MK70F12/MK70F12_usb.h" #include "device/MK70F12/MK70F12_usbdcd.h" #include "device/MK70F12/MK70F12_usbhs.h" #include "device/MK70F12/MK70F12_vref.h" #include "device/MK70F12/MK70F12_wdog.h" #elif (defined(CPU_MK70FN1M0VMF12) || defined(CPU_MK70FX512VMF12) || defined(CPU_MK70FN1M0VMF15) || \ defined(CPU_MK70FX512VMF15) || defined(CPU_MK70FN1M0VMJ12) || defined(CPU_MK70FX512VMJ12) || \ defined(CPU_MK70FN1M0VMJ15) || defined(CPU_MK70FX512VMJ15)) #define K70F15_SERIES /* CMSIS-style register definitions */ #include "device/MK70F15/MK70F15.h" /* Extension register headers. (These will eventually be merged into the CMSIS-style header.) */ #include "device/MK70F15/MK70F15_adc.h" #include "device/MK70F15/MK70F15_aips.h" #include "device/MK70F15/MK70F15_axbs.h" #include "device/MK70F15/MK70F15_can.h" #include "device/MK70F15/MK70F15_cau.h" #include "device/MK70F15/MK70F15_cmp.h" #include "device/MK70F15/MK70F15_cmt.h" #include "device/MK70F15/MK70F15_crc.h" #include "device/MK70F15/MK70F15_dac.h" #include "device/MK70F15/MK70F15_ddr.h" #include "device/MK70F15/MK70F15_dma.h" #include "device/MK70F15/MK70F15_dmamux.h" #include "device/MK70F15/MK70F15_enet.h" #include "device/MK70F15/MK70F15_ewm.h" #include "device/MK70F15/MK70F15_fb.h" #include "device/MK70F15/MK70F15_fmc.h" #include "device/MK70F15/MK70F15_ftfe.h" #include "device/MK70F15/MK70F15_ftm.h" #include "device/MK70F15/MK70F15_gpio.h" #include "device/MK70F15/MK70F15_i2c.h" #include "device/MK70F15/MK70F15_i2s.h" #include "device/MK70F15/MK70F15_lcdc.h" #include "device/MK70F15/MK70F15_llwu.h" #include "device/MK70F15/MK70F15_lmem.h" #include "device/MK70F15/MK70F15_lptmr.h" #include "device/MK70F15/MK70F15_mcg.h" #include "device/MK70F15/MK70F15_mcm.h" #include "device/MK70F15/MK70F15_mpu.h" #include "device/MK70F15/MK70F15_nfc.h" #include "device/MK70F15/MK70F15_nv.h" #include "device/MK70F15/MK70F15_osc.h" #include "device/MK70F15/MK70F15_pdb.h" #include "device/MK70F15/MK70F15_pit.h" #include "device/MK70F15/MK70F15_pmc.h" #include "device/MK70F15/MK70F15_port.h" #include "device/MK70F15/MK70F15_rcm.h" #include "device/MK70F15/MK70F15_rfsys.h" #include "device/MK70F15/MK70F15_rfvbat.h" #include "device/MK70F15/MK70F15_rng.h" #include "device/MK70F15/MK70F15_rtc.h" #include "device/MK70F15/MK70F15_sdhc.h" #include "device/MK70F15/MK70F15_sim.h" #include "device/MK70F15/MK70F15_smc.h" #include "device/MK70F15/MK70F15_spi.h" #include "device/MK70F15/MK70F15_tsi.h" #include "device/MK70F15/MK70F15_uart.h" #include "device/MK70F15/MK70F15_usb.h" #include "device/MK70F15/MK70F15_usbdcd.h" #include "device/MK70F15/MK70F15_usbhs.h" #include "device/MK70F15/MK70F15_vref.h" #include "device/MK70F15/MK70F15_wdog.h" #elif (defined(CPU_MKL02Z32CAF4) || defined(CPU_MKL02Z8VFG4) || defined(CPU_MKL02Z16VFG4) || \ defined(CPU_MKL02Z32VFG4) || defined(CPU_MKL02Z16VFK4) || defined(CPU_MKL02Z32VFK4) || \ defined(CPU_MKL02Z16VFM4) || defined(CPU_MKL02Z32VFM4)) #define KL02Z4_SERIES /* CMSIS-style register definitions */ #include "device/MKL02Z4/MKL02Z4.h" /* Extension register headers. (These will eventually be merged into the CMSIS-style header.) */ #include "device/MKL02Z4/MKL02Z4_adc.h" #include "device/MKL02Z4/MKL02Z4_cmp.h" #include "device/MKL02Z4/MKL02Z4_fgpio.h" #include "device/MKL02Z4/MKL02Z4_ftfa.h" #include "device/MKL02Z4/MKL02Z4_gpio.h" #include "device/MKL02Z4/MKL02Z4_i2c.h" #include "device/MKL02Z4/MKL02Z4_lptmr.h" #include "device/MKL02Z4/MKL02Z4_mcg.h" #include "device/MKL02Z4/MKL02Z4_mcm.h" #include "device/MKL02Z4/MKL02Z4_mtb.h" #include "device/MKL02Z4/MKL02Z4_mtbdwt.h" #include "device/MKL02Z4/MKL02Z4_nv.h" #include "device/MKL02Z4/MKL02Z4_osc.h" #include "device/MKL02Z4/MKL02Z4_pmc.h" #include "device/MKL02Z4/MKL02Z4_port.h" #include "device/MKL02Z4/MKL02Z4_rcm.h" #include "device/MKL02Z4/MKL02Z4_rom.h" #include "device/MKL02Z4/MKL02Z4_sim.h" #include "device/MKL02Z4/MKL02Z4_smc.h" #include "device/MKL02Z4/MKL02Z4_spi.h" #include "device/MKL02Z4/MKL02Z4_tpm.h" #include "device/MKL02Z4/MKL02Z4_uart0.h" #elif (defined(CPU_MKL03Z32CAF4) || defined(CPU_MKL03Z8VFG4) || defined(CPU_MKL03Z16VFG4) || \ defined(CPU_MKL03Z32VFG4) || defined(CPU_MKL03Z8VFK4) || defined(CPU_MKL03Z16VFK4) || \ defined(CPU_MKL03Z32VFK4)) #define KL03Z4_SERIES /* CMSIS-style register definitions */ #include "device/MKL03Z4/MKL03Z4.h" /* Extension register headers. (These will eventually be merged into the CMSIS-style header.) */ #include "device/MKL03Z4/MKL03Z4_adc.h" #include "device/MKL03Z4/MKL03Z4_cmp.h" #include "device/MKL03Z4/MKL03Z4_fgpio.h" #include "device/MKL03Z4/MKL03Z4_ftfa.h" #include "device/MKL03Z4/MKL03Z4_gpio.h" #include "device/MKL03Z4/MKL03Z4_i2c.h" #include "device/MKL03Z4/MKL03Z4_llwu.h" #include "device/MKL03Z4/MKL03Z4_lptmr.h" #include "device/MKL03Z4/MKL03Z4_lpuart.h" #include "device/MKL03Z4/MKL03Z4_mcg.h" #include "device/MKL03Z4/MKL03Z4_mcm.h" #include "device/MKL03Z4/MKL03Z4_mtb.h" #include "device/MKL03Z4/MKL03Z4_mtbdwt.h" #include "device/MKL03Z4/MKL03Z4_nv.h" #include "device/MKL03Z4/MKL03Z4_osc.h" #include "device/MKL03Z4/MKL03Z4_pmc.h" #include "device/MKL03Z4/MKL03Z4_port.h" #include "device/MKL03Z4/MKL03Z4_rcm.h" #include "device/MKL03Z4/MKL03Z4_rfsys.h" #include "device/MKL03Z4/MKL03Z4_rom.h" #include "device/MKL03Z4/MKL03Z4_rtc.h" #include "device/MKL03Z4/MKL03Z4_sim.h" #include "device/MKL03Z4/MKL03Z4_smc.h" #include "device/MKL03Z4/MKL03Z4_spi.h" #include "device/MKL03Z4/MKL03Z4_tpm.h" #include "device/MKL03Z4/MKL03Z4_vref.h" #elif (defined(CPU_MKL05Z8VFK4) || defined(CPU_MKL05Z16VFK4) || defined(CPU_MKL05Z32VFK4) || \ defined(CPU_MKL05Z8VLC4) || defined(CPU_MKL05Z16VLC4) || defined(CPU_MKL05Z32VLC4) || \ defined(CPU_MKL05Z8VFM4) || defined(CPU_MKL05Z16VFM4) || defined(CPU_MKL05Z32VFM4) || \ defined(CPU_MKL05Z16VLF4) || defined(CPU_MKL05Z32VLF4)) #define KL05Z4_SERIES /* CMSIS-style register definitions */ #include "device/MKL05Z4/MKL05Z4.h" /* Extension register headers. (These will eventually be merged into the CMSIS-style header.) */ #include "device/MKL05Z4/MKL05Z4_adc.h" #include "device/MKL05Z4/MKL05Z4_cmp.h" #include "device/MKL05Z4/MKL05Z4_dac.h" #include "device/MKL05Z4/MKL05Z4_dma.h" #include "device/MKL05Z4/MKL05Z4_dmamux.h" #include "device/MKL05Z4/MKL05Z4_fgpio.h" #include "device/MKL05Z4/MKL05Z4_ftfa.h" #include "device/MKL05Z4/MKL05Z4_gpio.h" #include "device/MKL05Z4/MKL05Z4_i2c.h" #include "device/MKL05Z4/MKL05Z4_llwu.h" #include "device/MKL05Z4/MKL05Z4_lptmr.h" #include "device/MKL05Z4/MKL05Z4_mcg.h" #include "device/MKL05Z4/MKL05Z4_mcm.h" #include "device/MKL05Z4/MKL05Z4_mtb.h" #include "device/MKL05Z4/MKL05Z4_mtbdwt.h" #include "device/MKL05Z4/MKL05Z4_nv.h" #include "device/MKL05Z4/MKL05Z4_osc.h" #include "device/MKL05Z4/MKL05Z4_pit.h" #include "device/MKL05Z4/MKL05Z4_pmc.h" #include "device/MKL05Z4/MKL05Z4_port.h" #include "device/MKL05Z4/MKL05Z4_rcm.h" #include "device/MKL05Z4/MKL05Z4_rom.h" #include "device/MKL05Z4/MKL05Z4_rtc.h" #include "device/MKL05Z4/MKL05Z4_sim.h" #include "device/MKL05Z4/MKL05Z4_smc.h" #include "device/MKL05Z4/MKL05Z4_spi.h" #include "device/MKL05Z4/MKL05Z4_tpm.h" #include "device/MKL05Z4/MKL05Z4_tsi.h" #include "device/MKL05Z4/MKL05Z4_uart0.h" #elif (defined(CPU_MKL13Z64VFM4) || defined(CPU_MKL13Z128VFM4) || defined(CPU_MKL13Z256VFM4) || \ defined(CPU_MKL13Z64VFT4) || defined(CPU_MKL13Z128VFT4) || defined(CPU_MKL13Z256VFT4) || \ defined(CPU_MKL13Z64VLH4) || defined(CPU_MKL13Z128VLH4) || defined(CPU_MKL13Z256VLH4) || \ defined(CPU_MKL13Z64VMP4) || defined(CPU_MKL13Z128VMP4) || defined(CPU_MKL13Z256VMP4)) #define KL13Z4_SERIES /* CMSIS-style register definitions */ #include "device/MKL13Z4/MKL13Z4.h" /* Extension register headers. (These will eventually be merged into the CMSIS-style header.) */ #include "device/MKL13Z4/MKL13Z4_adc.h" #include "device/MKL13Z4/MKL13Z4_cmp.h" #include "device/MKL13Z4/MKL13Z4_dac.h" #include "device/MKL13Z4/MKL13Z4_dma.h" #include "device/MKL13Z4/MKL13Z4_dmamux.h" #include "device/MKL13Z4/MKL13Z4_flexio.h" #include "device/MKL13Z4/MKL13Z4_ftfa.h" #include "device/MKL13Z4/MKL13Z4_gpio.h" #include "device/MKL13Z4/MKL13Z4_i2c.h" #include "device/MKL13Z4/MKL13Z4_i2s.h" #include "device/MKL13Z4/MKL13Z4_llwu.h" #include "device/MKL13Z4/MKL13Z4_lptmr.h" #include "device/MKL13Z4/MKL13Z4_lpuart.h" #include "device/MKL13Z4/MKL13Z4_mcg.h" #include "device/MKL13Z4/MKL13Z4_mcm.h" #include "device/MKL13Z4/MKL13Z4_mtb.h" #include "device/MKL13Z4/MKL13Z4_mtbdwt.h" #include "device/MKL13Z4/MKL13Z4_nv.h" #include "device/MKL13Z4/MKL13Z4_osc.h" #include "device/MKL13Z4/MKL13Z4_pit.h" #include "device/MKL13Z4/MKL13Z4_pmc.h" #include "device/MKL13Z4/MKL13Z4_port.h" #include "device/MKL13Z4/MKL13Z4_rcm.h" #include "device/MKL13Z4/MKL13Z4_rom.h" #include "device/MKL13Z4/MKL13Z4_rtc.h" #include "device/MKL13Z4/MKL13Z4_sim.h" #include "device/MKL13Z4/MKL13Z4_smc.h" #include "device/MKL13Z4/MKL13Z4_spi.h" #include "device/MKL13Z4/MKL13Z4_tpm.h" #include "device/MKL13Z4/MKL13Z4_uart.h" #include "device/MKL13Z4/MKL13Z4_vref.h" #elif (defined(CPU_MKL23Z64VFM4) || defined(CPU_MKL23Z128VFM4) || defined(CPU_MKL23Z256VFM4) || \ defined(CPU_MKL23Z64VFT4) || defined(CPU_MKL23Z128VFT4) || defined(CPU_MKL23Z256VFT4) || \ defined(CPU_MKL23Z64VLH4) || defined(CPU_MKL23Z128VLH4) || defined(CPU_MKL23Z256VLH4) || \ defined(CPU_MKL23Z64VMP4) || defined(CPU_MKL23Z128VMP4) || defined(CPU_MKL23Z256VMP4)) #define KL23Z4_SERIES /* CMSIS-style register definitions */ #include "device/MKL23Z4/MKL23Z4.h" /* Extension register headers. (These will eventually be merged into the CMSIS-style header.) */ #include "device/MKL23Z4/MKL23Z4_adc.h" #include "device/MKL23Z4/MKL23Z4_cmp.h" #include "device/MKL23Z4/MKL23Z4_dac.h" #include "device/MKL23Z4/MKL23Z4_dma.h" #include "device/MKL23Z4/MKL23Z4_dmamux.h" #include "device/MKL23Z4/MKL23Z4_flexio.h" #include "device/MKL23Z4/MKL23Z4_ftfa.h" #include "device/MKL23Z4/MKL23Z4_gpio.h" #include "device/MKL23Z4/MKL23Z4_i2c.h" #include "device/MKL23Z4/MKL23Z4_i2s.h" #include "device/MKL23Z4/MKL23Z4_llwu.h" #include "device/MKL23Z4/MKL23Z4_lptmr.h" #include "device/MKL23Z4/MKL23Z4_lpuart.h" #include "device/MKL23Z4/MKL23Z4_mcg.h" #include "device/MKL23Z4/MKL23Z4_mcm.h" #include "device/MKL23Z4/MKL23Z4_mtb.h" #include "device/MKL23Z4/MKL23Z4_mtbdwt.h" #include "device/MKL23Z4/MKL23Z4_nv.h" #include "device/MKL23Z4/MKL23Z4_osc.h" #include "device/MKL23Z4/MKL23Z4_pit.h" #include "device/MKL23Z4/MKL23Z4_pmc.h" #include "device/MKL23Z4/MKL23Z4_port.h" #include "device/MKL23Z4/MKL23Z4_rcm.h" #include "device/MKL23Z4/MKL23Z4_rom.h" #include "device/MKL23Z4/MKL23Z4_rtc.h" #include "device/MKL23Z4/MKL23Z4_sim.h" #include "device/MKL23Z4/MKL23Z4_smc.h" #include "device/MKL23Z4/MKL23Z4_spi.h" #include "device/MKL23Z4/MKL23Z4_tpm.h" #include "device/MKL23Z4/MKL23Z4_uart.h" #include "device/MKL23Z4/MKL23Z4_usb.h" #include "device/MKL23Z4/MKL23Z4_vref.h" #elif (defined(CPU_MKL25Z32VFM4) || defined(CPU_MKL25Z64VFM4) || defined(CPU_MKL25Z128VFM4) || \ defined(CPU_MKL25Z32VFT4) || defined(CPU_MKL25Z64VFT4) || defined(CPU_MKL25Z128VFT4) || \ defined(CPU_MKL25Z32VLH4) || defined(CPU_MKL25Z64VLH4) || defined(CPU_MKL25Z128VLH4) || \ defined(CPU_MKL25Z32VLK4) || defined(CPU_MKL25Z64VLK4) || defined(CPU_MKL25Z128VLK4)) #define KL25Z4_SERIES /* CMSIS-style register definitions */ #include "device/MKL25Z4/MKL25Z4.h" /* Extension register headers. (These will eventually be merged into the CMSIS-style header.) */ #include "device/MKL25Z4/MKL25Z4_adc.h" #include "device/MKL25Z4/MKL25Z4_cmp.h" #include "device/MKL25Z4/MKL25Z4_dac.h" #include "device/MKL25Z4/MKL25Z4_dma.h" #include "device/MKL25Z4/MKL25Z4_dmamux.h" #include "device/MKL25Z4/MKL25Z4_fgpio.h" #include "device/MKL25Z4/MKL25Z4_ftfa.h" #include "device/MKL25Z4/MKL25Z4_gpio.h" #include "device/MKL25Z4/MKL25Z4_i2c.h" #include "device/MKL25Z4/MKL25Z4_llwu.h" #include "device/MKL25Z4/MKL25Z4_lptmr.h" #include "device/MKL25Z4/MKL25Z4_mcg.h" #include "device/MKL25Z4/MKL25Z4_mcm.h" #include "device/MKL25Z4/MKL25Z4_mtb.h" #include "device/MKL25Z4/MKL25Z4_mtbdwt.h" #include "device/MKL25Z4/MKL25Z4_nv.h" #include "device/MKL25Z4/MKL25Z4_osc.h" #include "device/MKL25Z4/MKL25Z4_pit.h" #include "device/MKL25Z4/MKL25Z4_pmc.h" #include "device/MKL25Z4/MKL25Z4_port.h" #include "device/MKL25Z4/MKL25Z4_rcm.h" #include "device/MKL25Z4/MKL25Z4_rom.h" #include "device/MKL25Z4/MKL25Z4_rtc.h" #include "device/MKL25Z4/MKL25Z4_sim.h" #include "device/MKL25Z4/MKL25Z4_smc.h" #include "device/MKL25Z4/MKL25Z4_spi.h" #include "device/MKL25Z4/MKL25Z4_tpm.h" #include "device/MKL25Z4/MKL25Z4_tsi.h" #include "device/MKL25Z4/MKL25Z4_uart.h" #include "device/MKL25Z4/MKL25Z4_uart0.h" #include "device/MKL25Z4/MKL25Z4_usb.h" #elif (defined(CPU_MKL26Z32VFM4) || defined(CPU_MKL26Z64VFM4) || defined(CPU_MKL26Z128VFM4) || \ defined(CPU_MKL26Z32VFT4) || defined(CPU_MKL26Z64VFT4) || defined(CPU_MKL26Z128VFT4) || \ defined(CPU_MKL26Z32VLH4) || defined(CPU_MKL26Z64VLH4) || defined(CPU_MKL26Z128VLH4) || \ defined(CPU_MKL26Z256VLH4) || defined(CPU_MKL26Z256VLK4) || defined(CPU_MKL26Z128VLL4) || \ defined(CPU_MKL26Z256VLL4) || defined(CPU_MKL26Z128VMC4) || defined(CPU_MKL26Z256VMC4)) #define KL26Z4_SERIES /* CMSIS-style register definitions */ #include "device/MKL26Z4/MKL26Z4.h" /* Extension register headers. (These will eventually be merged into the CMSIS-style header.) */ #include "device/MKL26Z4/MKL26Z4_adc.h" #include "device/MKL26Z4/MKL26Z4_cmp.h" #include "device/MKL26Z4/MKL26Z4_dac.h" #include "device/MKL26Z4/MKL26Z4_dma.h" #include "device/MKL26Z4/MKL26Z4_dmamux.h" #include "device/MKL26Z4/MKL26Z4_fgpio.h" #include "device/MKL26Z4/MKL26Z4_ftfa.h" #include "device/MKL26Z4/MKL26Z4_gpio.h" #include "device/MKL26Z4/MKL26Z4_i2c.h" #include "device/MKL26Z4/MKL26Z4_i2s.h" #include "device/MKL26Z4/MKL26Z4_llwu.h" #include "device/MKL26Z4/MKL26Z4_lptmr.h" #include "device/MKL26Z4/MKL26Z4_mcg.h" #include "device/MKL26Z4/MKL26Z4_mcm.h" #include "device/MKL26Z4/MKL26Z4_mtb.h" #include "device/MKL26Z4/MKL26Z4_mtbdwt.h" #include "device/MKL26Z4/MKL26Z4_nv.h" #include "device/MKL26Z4/MKL26Z4_osc.h" #include "device/MKL26Z4/MKL26Z4_pit.h" #include "device/MKL26Z4/MKL26Z4_pmc.h" #include "device/MKL26Z4/MKL26Z4_port.h" #include "device/MKL26Z4/MKL26Z4_rcm.h" #include "device/MKL26Z4/MKL26Z4_rom.h" #include "device/MKL26Z4/MKL26Z4_rtc.h" #include "device/MKL26Z4/MKL26Z4_sim.h" #include "device/MKL26Z4/MKL26Z4_smc.h" #include "device/MKL26Z4/MKL26Z4_spi.h" #include "device/MKL26Z4/MKL26Z4_tpm.h" #include "device/MKL26Z4/MKL26Z4_tsi.h" #include "device/MKL26Z4/MKL26Z4_uart.h" #include "device/MKL26Z4/MKL26Z4_uart0.h" #include "device/MKL26Z4/MKL26Z4_usb.h" #elif (defined(CPU_MKL33Z128VLH4) || defined(CPU_MKL33Z256VLH4) || defined(CPU_MKL33Z128VMP4) || \ defined(CPU_MKL33Z256VMP4)) #define KL33Z4_SERIES /* CMSIS-style register definitions */ #include "device/MKL33Z4/MKL33Z4.h" /* Extension register headers. (These will eventually be merged into the CMSIS-style header.) */ #include "device/MKL33Z4/MKL33Z4_adc.h" #include "device/MKL33Z4/MKL33Z4_cmp.h" #include "device/MKL33Z4/MKL33Z4_dac.h" #include "device/MKL33Z4/MKL33Z4_dma.h" #include "device/MKL33Z4/MKL33Z4_dmamux.h" #include "device/MKL33Z4/MKL33Z4_flexio.h" #include "device/MKL33Z4/MKL33Z4_ftfa.h" #include "device/MKL33Z4/MKL33Z4_gpio.h" #include "device/MKL33Z4/MKL33Z4_i2c.h" #include "device/MKL33Z4/MKL33Z4_i2s.h" #include "device/MKL33Z4/MKL33Z4_lcd.h" #include "device/MKL33Z4/MKL33Z4_llwu.h" #include "device/MKL33Z4/MKL33Z4_lptmr.h" #include "device/MKL33Z4/MKL33Z4_lpuart.h" #include "device/MKL33Z4/MKL33Z4_mcg.h" #include "device/MKL33Z4/MKL33Z4_mcm.h" #include "device/MKL33Z4/MKL33Z4_mtb.h" #include "device/MKL33Z4/MKL33Z4_mtbdwt.h" #include "device/MKL33Z4/MKL33Z4_nv.h" #include "device/MKL33Z4/MKL33Z4_osc.h" #include "device/MKL33Z4/MKL33Z4_pit.h" #include "device/MKL33Z4/MKL33Z4_pmc.h" #include "device/MKL33Z4/MKL33Z4_port.h" #include "device/MKL33Z4/MKL33Z4_rcm.h" #include "device/MKL33Z4/MKL33Z4_rom.h" #include "device/MKL33Z4/MKL33Z4_rtc.h" #include "device/MKL33Z4/MKL33Z4_sim.h" #include "device/MKL33Z4/MKL33Z4_smc.h" #include "device/MKL33Z4/MKL33Z4_spi.h" #include "device/MKL33Z4/MKL33Z4_tpm.h" #include "device/MKL33Z4/MKL33Z4_uart.h" #include "device/MKL33Z4/MKL33Z4_vref.h" #elif (defined(CPU_MKL43Z64VLH4) || defined(CPU_MKL43Z128VLH4) || defined(CPU_MKL43Z256VLH4) || \ defined(CPU_MKL43Z64VMP4) || defined(CPU_MKL43Z128VMP4) || defined(CPU_MKL43Z256VMP4)) #define KL43Z4_SERIES /* CMSIS-style register definitions */ #include "device/MKL43Z4/MKL43Z4.h" /* Extension register headers. (These will eventually be merged into the CMSIS-style header.) */ #include "device/MKL43Z4/MKL43Z4_adc.h" #include "device/MKL43Z4/MKL43Z4_cmp.h" #include "device/MKL43Z4/MKL43Z4_dac.h" #include "device/MKL43Z4/MKL43Z4_dma.h" #include "device/MKL43Z4/MKL43Z4_dmamux.h" #include "device/MKL43Z4/MKL43Z4_flexio.h" #include "device/MKL43Z4/MKL43Z4_ftfa.h" #include "device/MKL43Z4/MKL43Z4_gpio.h" #include "device/MKL43Z4/MKL43Z4_i2c.h" #include "device/MKL43Z4/MKL43Z4_i2s.h" #include "device/MKL43Z4/MKL43Z4_lcd.h" #include "device/MKL43Z4/MKL43Z4_llwu.h" #include "device/MKL43Z4/MKL43Z4_lptmr.h" #include "device/MKL43Z4/MKL43Z4_lpuart.h" #include "device/MKL43Z4/MKL43Z4_mcg.h" #include "device/MKL43Z4/MKL43Z4_mcm.h" #include "device/MKL43Z4/MKL43Z4_mtb.h" #include "device/MKL43Z4/MKL43Z4_mtbdwt.h" #include "device/MKL43Z4/MKL43Z4_nv.h" #include "device/MKL43Z4/MKL43Z4_osc.h" #include "device/MKL43Z4/MKL43Z4_pit.h" #include "device/MKL43Z4/MKL43Z4_pmc.h" #include "device/MKL43Z4/MKL43Z4_port.h" #include "device/MKL43Z4/MKL43Z4_rcm.h" #include "device/MKL43Z4/MKL43Z4_rom.h" #include "device/MKL43Z4/MKL43Z4_rtc.h" #include "device/MKL43Z4/MKL43Z4_sim.h" #include "device/MKL43Z4/MKL43Z4_smc.h" #include "device/MKL43Z4/MKL43Z4_spi.h" #include "device/MKL43Z4/MKL43Z4_tpm.h" #include "device/MKL43Z4/MKL43Z4_uart.h" #include "device/MKL43Z4/MKL43Z4_usb.h" #include "device/MKL43Z4/MKL43Z4_vref.h" #elif (defined(CPU_MKL46Z128VLH4) || defined(CPU_MKL46Z256VLH4) || defined(CPU_MKL46Z128VLL4) || \ defined(CPU_MKL46Z256VLL4) || defined(CPU_MKL46Z128VMC4) || defined(CPU_MKL46Z256VMC4)) #define KL46Z4_SERIES /* CMSIS-style register definitions */ #include "device/MKL46Z4/MKL46Z4.h" /* Extension register headers. (These will eventually be merged into the CMSIS-style header.) */ #include "device/MKL46Z4/MKL46Z4_adc.h" #include "device/MKL46Z4/MKL46Z4_cmp.h" #include "device/MKL46Z4/MKL46Z4_dac.h" #include "device/MKL46Z4/MKL46Z4_dma.h" #include "device/MKL46Z4/MKL46Z4_dmamux.h" #include "device/MKL46Z4/MKL46Z4_fgpio.h" #include "device/MKL46Z4/MKL46Z4_ftfa.h" #include "device/MKL46Z4/MKL46Z4_gpio.h" #include "device/MKL46Z4/MKL46Z4_i2c.h" #include "device/MKL46Z4/MKL46Z4_i2s.h" #include "device/MKL46Z4/MKL46Z4_lcd.h" #include "device/MKL46Z4/MKL46Z4_llwu.h" #include "device/MKL46Z4/MKL46Z4_lptmr.h" #include "device/MKL46Z4/MKL46Z4_mcg.h" #include "device/MKL46Z4/MKL46Z4_mcm.h" #include "device/MKL46Z4/MKL46Z4_mtb.h" #include "device/MKL46Z4/MKL46Z4_mtbdwt.h" #include "device/MKL46Z4/MKL46Z4_nv.h" #include "device/MKL46Z4/MKL46Z4_osc.h" #include "device/MKL46Z4/MKL46Z4_pit.h" #include "device/MKL46Z4/MKL46Z4_pmc.h" #include "device/MKL46Z4/MKL46Z4_port.h" #include "device/MKL46Z4/MKL46Z4_rcm.h" #include "device/MKL46Z4/MKL46Z4_rom.h" #include "device/MKL46Z4/MKL46Z4_rtc.h" #include "device/MKL46Z4/MKL46Z4_sim.h" #include "device/MKL46Z4/MKL46Z4_smc.h" #include "device/MKL46Z4/MKL46Z4_spi.h" #include "device/MKL46Z4/MKL46Z4_tpm.h" #include "device/MKL46Z4/MKL46Z4_tsi.h" #include "device/MKL46Z4/MKL46Z4_uart.h" #include "device/MKL46Z4/MKL46Z4_uart0.h" #include "device/MKL46Z4/MKL46Z4_usb.h" #elif (defined(CPU_MKV30F128VFM10) || defined(CPU_MKV30F64VFM10) || defined(CPU_MKV30F128VLF10) || \ defined(CPU_MKV30F64VLF10) || defined(CPU_MKV30F128VLH10) || defined(CPU_MKV30F64VLH10)) #define KV30F12810_SERIES /* CMSIS-style register definitions */ #include "device/MKV30F12810/MKV30F12810.h" /* Extension register headers. (These will eventually be merged into the CMSIS-style header.) */ #include "device/MKV30F12810/MKV30F12810_adc.h" #include "device/MKV30F12810/MKV30F12810_cmp.h" #include "device/MKV30F12810/MKV30F12810_crc.h" #include "device/MKV30F12810/MKV30F12810_dac.h" #include "device/MKV30F12810/MKV30F12810_dma.h" #include "device/MKV30F12810/MKV30F12810_dmamux.h" #include "device/MKV30F12810/MKV30F12810_ewm.h" #include "device/MKV30F12810/MKV30F12810_fmc.h" #include "device/MKV30F12810/MKV30F12810_ftfa.h" #include "device/MKV30F12810/MKV30F12810_ftm.h" #include "device/MKV30F12810/MKV30F12810_gpio.h" #include "device/MKV30F12810/MKV30F12810_i2c.h" #include "device/MKV30F12810/MKV30F12810_llwu.h" #include "device/MKV30F12810/MKV30F12810_lptmr.h" #include "device/MKV30F12810/MKV30F12810_mcg.h" #include "device/MKV30F12810/MKV30F12810_mcm.h" #include "device/MKV30F12810/MKV30F12810_nv.h" #include "device/MKV30F12810/MKV30F12810_osc.h" #include "device/MKV30F12810/MKV30F12810_pdb.h" #include "device/MKV30F12810/MKV30F12810_pit.h" #include "device/MKV30F12810/MKV30F12810_pmc.h" #include "device/MKV30F12810/MKV30F12810_port.h" #include "device/MKV30F12810/MKV30F12810_rcm.h" #include "device/MKV30F12810/MKV30F12810_sim.h" #include "device/MKV30F12810/MKV30F12810_smc.h" #include "device/MKV30F12810/MKV30F12810_spi.h" #include "device/MKV30F12810/MKV30F12810_uart.h" #include "device/MKV30F12810/MKV30F12810_vref.h" #include "device/MKV30F12810/MKV30F12810_wdog.h" #elif (defined(CPU_MKV31F128VLH10) || defined(CPU_MKV31F128VLL10)) #define KV31F12810_SERIES /* CMSIS-style register definitions */ #include "device/MKV31F12810/MKV31F12810.h" /* Extension register headers. (These will eventually be merged into the CMSIS-style header.) */ #include "device/MKV31F12810/MKV31F12810_adc.h" #include "device/MKV31F12810/MKV31F12810_cmp.h" #include "device/MKV31F12810/MKV31F12810_crc.h" #include "device/MKV31F12810/MKV31F12810_dac.h" #include "device/MKV31F12810/MKV31F12810_dma.h" #include "device/MKV31F12810/MKV31F12810_dmamux.h" #include "device/MKV31F12810/MKV31F12810_ewm.h" #include "device/MKV31F12810/MKV31F12810_fmc.h" #include "device/MKV31F12810/MKV31F12810_ftfa.h" #include "device/MKV31F12810/MKV31F12810_ftm.h" #include "device/MKV31F12810/MKV31F12810_gpio.h" #include "device/MKV31F12810/MKV31F12810_i2c.h" #include "device/MKV31F12810/MKV31F12810_llwu.h" #include "device/MKV31F12810/MKV31F12810_lptmr.h" #include "device/MKV31F12810/MKV31F12810_lpuart.h" #include "device/MKV31F12810/MKV31F12810_mcg.h" #include "device/MKV31F12810/MKV31F12810_mcm.h" #include "device/MKV31F12810/MKV31F12810_nv.h" #include "device/MKV31F12810/MKV31F12810_osc.h" #include "device/MKV31F12810/MKV31F12810_pdb.h" #include "device/MKV31F12810/MKV31F12810_pit.h" #include "device/MKV31F12810/MKV31F12810_pmc.h" #include "device/MKV31F12810/MKV31F12810_port.h" #include "device/MKV31F12810/MKV31F12810_rcm.h" #include "device/MKV31F12810/MKV31F12810_rfsys.h" #include "device/MKV31F12810/MKV31F12810_sim.h" #include "device/MKV31F12810/MKV31F12810_smc.h" #include "device/MKV31F12810/MKV31F12810_spi.h" #include "device/MKV31F12810/MKV31F12810_uart.h" #include "device/MKV31F12810/MKV31F12810_vref.h" #include "device/MKV31F12810/MKV31F12810_wdog.h" #elif (defined(CPU_MKV31F256VLH12) || defined(CPU_MKV31F256VLL12)) #define KV31F25612_SERIES /* CMSIS-style register definitions */ #include "device/MKV31F25612/MKV31F25612.h" /* Extension register headers. (These will eventually be merged into the CMSIS-style header.) */ #include "device/MKV31F25612/MKV31F25612_adc.h" #include "device/MKV31F25612/MKV31F25612_cmp.h" #include "device/MKV31F25612/MKV31F25612_crc.h" #include "device/MKV31F25612/MKV31F25612_dac.h" #include "device/MKV31F25612/MKV31F25612_dma.h" #include "device/MKV31F25612/MKV31F25612_dmamux.h" #include "device/MKV31F25612/MKV31F25612_ewm.h" #include "device/MKV31F25612/MKV31F25612_fmc.h" #include "device/MKV31F25612/MKV31F25612_ftfa.h" #include "device/MKV31F25612/MKV31F25612_ftm.h" #include "device/MKV31F25612/MKV31F25612_gpio.h" #include "device/MKV31F25612/MKV31F25612_i2c.h" #include "device/MKV31F25612/MKV31F25612_llwu.h" #include "device/MKV31F25612/MKV31F25612_lptmr.h" #include "device/MKV31F25612/MKV31F25612_lpuart.h" #include "device/MKV31F25612/MKV31F25612_mcg.h" #include "device/MKV31F25612/MKV31F25612_mcm.h" #include "device/MKV31F25612/MKV31F25612_nv.h" #include "device/MKV31F25612/MKV31F25612_osc.h" #include "device/MKV31F25612/MKV31F25612_pdb.h" #include "device/MKV31F25612/MKV31F25612_pit.h" #include "device/MKV31F25612/MKV31F25612_pmc.h" #include "device/MKV31F25612/MKV31F25612_port.h" #include "device/MKV31F25612/MKV31F25612_rcm.h" #include "device/MKV31F25612/MKV31F25612_rfsys.h" #include "device/MKV31F25612/MKV31F25612_rng.h" #include "device/MKV31F25612/MKV31F25612_sim.h" #include "device/MKV31F25612/MKV31F25612_smc.h" #include "device/MKV31F25612/MKV31F25612_spi.h" #include "device/MKV31F25612/MKV31F25612_uart.h" #include "device/MKV31F25612/MKV31F25612_vref.h" #include "device/MKV31F25612/MKV31F25612_wdog.h" #elif (defined(CPU_MKV31F512VLH12) || defined(CPU_MKV31F512VLL12)) #define KV31F51212_SERIES /* CMSIS-style register definitions */ #include "device/MKV31F51212/MKV31F51212.h" /* Extension register headers. (These will eventually be merged into the CMSIS-style header.) */ #include "device/MKV31F51212/MKV31F51212_adc.h" #include "device/MKV31F51212/MKV31F51212_cmp.h" #include "device/MKV31F51212/MKV31F51212_crc.h" #include "device/MKV31F51212/MKV31F51212_dac.h" #include "device/MKV31F51212/MKV31F51212_dma.h" #include "device/MKV31F51212/MKV31F51212_dmamux.h" #include "device/MKV31F51212/MKV31F51212_ewm.h" #include "device/MKV31F51212/MKV31F51212_fb.h" #include "device/MKV31F51212/MKV31F51212_fmc.h" #include "device/MKV31F51212/MKV31F51212_ftfa.h" #include "device/MKV31F51212/MKV31F51212_ftm.h" #include "device/MKV31F51212/MKV31F51212_gpio.h" #include "device/MKV31F51212/MKV31F51212_i2c.h" #include "device/MKV31F51212/MKV31F51212_llwu.h" #include "device/MKV31F51212/MKV31F51212_lptmr.h" #include "device/MKV31F51212/MKV31F51212_lpuart.h" #include "device/MKV31F51212/MKV31F51212_mcg.h" #include "device/MKV31F51212/MKV31F51212_mcm.h" #include "device/MKV31F51212/MKV31F51212_nv.h" #include "device/MKV31F51212/MKV31F51212_osc.h" #include "device/MKV31F51212/MKV31F51212_pdb.h" #include "device/MKV31F51212/MKV31F51212_pit.h" #include "device/MKV31F51212/MKV31F51212_pmc.h" #include "device/MKV31F51212/MKV31F51212_port.h" #include "device/MKV31F51212/MKV31F51212_rcm.h" #include "device/MKV31F51212/MKV31F51212_rfsys.h" #include "device/MKV31F51212/MKV31F51212_rng.h" #include "device/MKV31F51212/MKV31F51212_sim.h" #include "device/MKV31F51212/MKV31F51212_smc.h" #include "device/MKV31F51212/MKV31F51212_spi.h" #include "device/MKV31F51212/MKV31F51212_uart.h" #include "device/MKV31F51212/MKV31F51212_vref.h" #include "device/MKV31F51212/MKV31F51212_wdog.h" #elif (defined(CPU_MKV40F128VLH15) || defined(CPU_MKV40F128VLL15) || defined(CPU_MKV40F256VLH15) || \ defined(CPU_MKV40F256VLL15) || defined(CPU_MKV40F64VLH15)) #define KV40F15_SERIES /* CMSIS-style register definitions */ #include "device/MKV40F15/MKV40F15.h" /* Extension register headers. (These will eventually be merged into the CMSIS-style header.) */ #include "device/MKV40F15/MKV40F15_adc.h" #include "device/MKV40F15/MKV40F15_aoi.h" #include "device/MKV40F15/MKV40F15_can.h" #include "device/MKV40F15/MKV40F15_cmp.h" #include "device/MKV40F15/MKV40F15_crc.h" #include "device/MKV40F15/MKV40F15_dma.h" #include "device/MKV40F15/MKV40F15_dmamux.h" #include "device/MKV40F15/MKV40F15_enc.h" #include "device/MKV40F15/MKV40F15_ewm.h" #include "device/MKV40F15/MKV40F15_fmc.h" #include "device/MKV40F15/MKV40F15_ftfa.h" #include "device/MKV40F15/MKV40F15_ftm.h" #include "device/MKV40F15/MKV40F15_gpio.h" #include "device/MKV40F15/MKV40F15_i2c.h" #include "device/MKV40F15/MKV40F15_llwu.h" #include "device/MKV40F15/MKV40F15_lptmr.h" #include "device/MKV40F15/MKV40F15_mcg.h" #include "device/MKV40F15/MKV40F15_mcm.h" #include "device/MKV40F15/MKV40F15_nv.h" #include "device/MKV40F15/MKV40F15_osc.h" #include "device/MKV40F15/MKV40F15_pdb.h" #include "device/MKV40F15/MKV40F15_pit.h" #include "device/MKV40F15/MKV40F15_pmc.h" #include "device/MKV40F15/MKV40F15_port.h" #include "device/MKV40F15/MKV40F15_rcm.h" #include "device/MKV40F15/MKV40F15_sim.h" #include "device/MKV40F15/MKV40F15_smc.h" #include "device/MKV40F15/MKV40F15_spi.h" #include "device/MKV40F15/MKV40F15_uart.h" #include "device/MKV40F15/MKV40F15_vref.h" #include "device/MKV40F15/MKV40F15_wdog.h" #include "device/MKV40F15/MKV40F15_xbara.h" #include "device/MKV40F15/MKV40F15_xbarb.h" #elif (defined(CPU_MKV43F128VLH15) || defined(CPU_MKV43F128VLL15) || defined(CPU_MKV43F64VLH15)) #define KV43F15_SERIES /* CMSIS-style register definitions */ #include "device/MKV43F15/MKV43F15.h" /* Extension register headers. (These will eventually be merged into the CMSIS-style header.) */ #include "device/MKV43F15/MKV43F15_adc.h" #include "device/MKV43F15/MKV43F15_aoi.h" #include "device/MKV43F15/MKV43F15_can.h" #include "device/MKV43F15/MKV43F15_cmp.h" #include "device/MKV43F15/MKV43F15_crc.h" #include "device/MKV43F15/MKV43F15_dma.h" #include "device/MKV43F15/MKV43F15_dmamux.h" #include "device/MKV43F15/MKV43F15_enc.h" #include "device/MKV43F15/MKV43F15_ewm.h" #include "device/MKV43F15/MKV43F15_fmc.h" #include "device/MKV43F15/MKV43F15_ftfa.h" #include "device/MKV43F15/MKV43F15_gpio.h" #include "device/MKV43F15/MKV43F15_i2c.h" #include "device/MKV43F15/MKV43F15_llwu.h" #include "device/MKV43F15/MKV43F15_lptmr.h" #include "device/MKV43F15/MKV43F15_mcg.h" #include "device/MKV43F15/MKV43F15_mcm.h" #include "device/MKV43F15/MKV43F15_nv.h" #include "device/MKV43F15/MKV43F15_osc.h" #include "device/MKV43F15/MKV43F15_pdb.h" #include "device/MKV43F15/MKV43F15_pit.h" #include "device/MKV43F15/MKV43F15_pmc.h" #include "device/MKV43F15/MKV43F15_port.h" #include "device/MKV43F15/MKV43F15_pwm.h" #include "device/MKV43F15/MKV43F15_rcm.h" #include "device/MKV43F15/MKV43F15_sim.h" #include "device/MKV43F15/MKV43F15_smc.h" #include "device/MKV43F15/MKV43F15_spi.h" #include "device/MKV43F15/MKV43F15_uart.h" #include "device/MKV43F15/MKV43F15_vref.h" #include "device/MKV43F15/MKV43F15_wdog.h" #include "device/MKV43F15/MKV43F15_xbara.h" #include "device/MKV43F15/MKV43F15_xbarb.h" #elif (defined(CPU_MKV44F128VLH15) || defined(CPU_MKV44F128VLL15) || defined(CPU_MKV44F64VLH15)) #define KV44F15_SERIES /* CMSIS-style register definitions */ #include "device/MKV44F15/MKV44F15.h" /* Extension register headers. (These will eventually be merged into the CMSIS-style header.) */ #include "device/MKV44F15/MKV44F15_adc.h" #include "device/MKV44F15/MKV44F15_aoi.h" #include "device/MKV44F15/MKV44F15_can.h" #include "device/MKV44F15/MKV44F15_cmp.h" #include "device/MKV44F15/MKV44F15_crc.h" #include "device/MKV44F15/MKV44F15_dac.h" #include "device/MKV44F15/MKV44F15_dma.h" #include "device/MKV44F15/MKV44F15_dmamux.h" #include "device/MKV44F15/MKV44F15_enc.h" #include "device/MKV44F15/MKV44F15_ewm.h" #include "device/MKV44F15/MKV44F15_fmc.h" #include "device/MKV44F15/MKV44F15_ftfa.h" #include "device/MKV44F15/MKV44F15_gpio.h" #include "device/MKV44F15/MKV44F15_i2c.h" #include "device/MKV44F15/MKV44F15_llwu.h" #include "device/MKV44F15/MKV44F15_lptmr.h" #include "device/MKV44F15/MKV44F15_mcg.h" #include "device/MKV44F15/MKV44F15_mcm.h" #include "device/MKV44F15/MKV44F15_nv.h" #include "device/MKV44F15/MKV44F15_osc.h" #include "device/MKV44F15/MKV44F15_pdb.h" #include "device/MKV44F15/MKV44F15_pit.h" #include "device/MKV44F15/MKV44F15_pmc.h" #include "device/MKV44F15/MKV44F15_port.h" #include "device/MKV44F15/MKV44F15_pwm.h" #include "device/MKV44F15/MKV44F15_rcm.h" #include "device/MKV44F15/MKV44F15_sim.h" #include "device/MKV44F15/MKV44F15_smc.h" #include "device/MKV44F15/MKV44F15_spi.h" #include "device/MKV44F15/MKV44F15_uart.h" #include "device/MKV44F15/MKV44F15_vref.h" #include "device/MKV44F15/MKV44F15_wdog.h" #include "device/MKV44F15/MKV44F15_xbara.h" #include "device/MKV44F15/MKV44F15_xbarb.h" #elif (defined(CPU_MKV45F128VLH15) || defined(CPU_MKV45F128VLL15) || defined(CPU_MKV45F256VLH15) || \ defined(CPU_MKV45F256VLL15)) #define KV45F15_SERIES /* CMSIS-style register definitions */ #include "device/MKV45F15/MKV45F15.h" /* Extension register headers. (These will eventually be merged into the CMSIS-style header.) */ #include "device/MKV45F15/MKV45F15_adc.h" #include "device/MKV45F15/MKV45F15_aoi.h" #include "device/MKV45F15/MKV45F15_can.h" #include "device/MKV45F15/MKV45F15_cmp.h" #include "device/MKV45F15/MKV45F15_crc.h" #include "device/MKV45F15/MKV45F15_dma.h" #include "device/MKV45F15/MKV45F15_dmamux.h" #include "device/MKV45F15/MKV45F15_enc.h" #include "device/MKV45F15/MKV45F15_ewm.h" #include "device/MKV45F15/MKV45F15_fmc.h" #include "device/MKV45F15/MKV45F15_ftfa.h" #include "device/MKV45F15/MKV45F15_ftm.h" #include "device/MKV45F15/MKV45F15_gpio.h" #include "device/MKV45F15/MKV45F15_i2c.h" #include "device/MKV45F15/MKV45F15_llwu.h" #include "device/MKV45F15/MKV45F15_lptmr.h" #include "device/MKV45F15/MKV45F15_mcg.h" #include "device/MKV45F15/MKV45F15_mcm.h" #include "device/MKV45F15/MKV45F15_nv.h" #include "device/MKV45F15/MKV45F15_osc.h" #include "device/MKV45F15/MKV45F15_pdb.h" #include "device/MKV45F15/MKV45F15_pit.h" #include "device/MKV45F15/MKV45F15_pmc.h" #include "device/MKV45F15/MKV45F15_port.h" #include "device/MKV45F15/MKV45F15_pwm.h" #include "device/MKV45F15/MKV45F15_rcm.h" #include "device/MKV45F15/MKV45F15_sim.h" #include "device/MKV45F15/MKV45F15_smc.h" #include "device/MKV45F15/MKV45F15_spi.h" #include "device/MKV45F15/MKV45F15_uart.h" #include "device/MKV45F15/MKV45F15_vref.h" #include "device/MKV45F15/MKV45F15_wdog.h" #include "device/MKV45F15/MKV45F15_xbara.h" #include "device/MKV45F15/MKV45F15_xbarb.h" #elif (defined(CPU_MKV46F128VLH15) || defined(CPU_MKV46F128VLL15) || defined(CPU_MKV46F256VLH15) || \ defined(CPU_MKV46F256VLL15)) #define KV46F15_SERIES /* CMSIS-style register definitions */ #include "device/MKV46F15/MKV46F15.h" /* Extension register headers. (These will eventually be merged into the CMSIS-style header.) */ #include "device/MKV46F15/MKV46F15_adc.h" #include "device/MKV46F15/MKV46F15_aoi.h" #include "device/MKV46F15/MKV46F15_can.h" #include "device/MKV46F15/MKV46F15_cmp.h" #include "device/MKV46F15/MKV46F15_crc.h" #include "device/MKV46F15/MKV46F15_dac.h" #include "device/MKV46F15/MKV46F15_dma.h" #include "device/MKV46F15/MKV46F15_dmamux.h" #include "device/MKV46F15/MKV46F15_enc.h" #include "device/MKV46F15/MKV46F15_ewm.h" #include "device/MKV46F15/MKV46F15_fmc.h" #include "device/MKV46F15/MKV46F15_ftfa.h" #include "device/MKV46F15/MKV46F15_ftm.h" #include "device/MKV46F15/MKV46F15_gpio.h" #include "device/MKV46F15/MKV46F15_i2c.h" #include "device/MKV46F15/MKV46F15_llwu.h" #include "device/MKV46F15/MKV46F15_lptmr.h" #include "device/MKV46F15/MKV46F15_mcg.h" #include "device/MKV46F15/MKV46F15_mcm.h" #include "device/MKV46F15/MKV46F15_nv.h" #include "device/MKV46F15/MKV46F15_osc.h" #include "device/MKV46F15/MKV46F15_pdb.h" #include "device/MKV46F15/MKV46F15_pit.h" #include "device/MKV46F15/MKV46F15_pmc.h" #include "device/MKV46F15/MKV46F15_port.h" #include "device/MKV46F15/MKV46F15_pwm.h" #include "device/MKV46F15/MKV46F15_rcm.h" #include "device/MKV46F15/MKV46F15_sim.h" #include "device/MKV46F15/MKV46F15_smc.h" #include "device/MKV46F15/MKV46F15_spi.h" #include "device/MKV46F15/MKV46F15_uart.h" #include "device/MKV46F15/MKV46F15_vref.h" #include "device/MKV46F15/MKV46F15_wdog.h" #include "device/MKV46F15/MKV46F15_xbara.h" #include "device/MKV46F15/MKV46F15_xbarb.h" #else #error "No valid CPU defined!" #endif #endif /* __FSL_DEVICE_REGISTERS_H__ */ /******************************************************************************* * EOF ******************************************************************************/ ================================================ FILE: Zelig/mbed/TARGET_K64F/TARGET_Freescale/TARGET_KPSDK_MCUS/gpio_object.h ================================================ /* mbed Microcontroller Library * Copyright (c) 2006-2013 ARM Limited * * 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 MBED_GPIO_OBJECT_H #define MBED_GPIO_OBJECT_H #include "mbed_assert.h" #include "fsl_gpio_hal.h" // #include "cmsis.h" #ifdef __cplusplus extern "C" { #endif typedef struct { PinName pin; } gpio_t; static inline void gpio_write(gpio_t *obj, int value) { MBED_ASSERT(obj->pin != (PinName)NC); uint32_t port = obj->pin >> GPIO_PORT_SHIFT; uint32_t pin = obj->pin & 0xFF; uint32_t gpio_addrs[] = GPIO_BASE_ADDRS; GPIO_HAL_WritePinOutput(gpio_addrs[port], pin, value); } static inline int gpio_read(gpio_t *obj) { MBED_ASSERT(obj->pin != (PinName)NC); uint32_t port = obj->pin >> GPIO_PORT_SHIFT; uint32_t pin = obj->pin & 0xFF; uint32_t gpio_addrs[] = GPIO_BASE_ADDRS; return (int)GPIO_HAL_ReadPinInput(gpio_addrs[port], pin); } static inline int gpio_is_connected(const gpio_t *obj) { return obj->pin != (PinName)NC; } #ifdef __cplusplus } #endif #endif ================================================ FILE: Zelig/mbed/TARGET_K64F/TARGET_Freescale/TARGET_KPSDK_MCUS/objects.h ================================================ /* mbed Microcontroller Library * Copyright (c) 2006-2013 ARM Limited * * 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 MBED_OBJECTS_H #define MBED_OBJECTS_H #include "cmsis.h" #include "PortNames.h" #include "PeripheralNames.h" #include "PinNames.h" #ifdef __cplusplus extern "C" { #endif struct gpio_irq_s { uint32_t port; uint32_t pin; uint32_t ch; }; struct port_s { PortName port; uint32_t mask; }; struct pwmout_s { PWMName pwm_name; }; struct serial_s { int index; }; struct analogin_s { ADCName adc; }; struct i2c_s { uint32_t instance; }; struct spi_s { uint32_t instance; }; struct dac_s { DACName dac; }; #include "gpio_object.h" #ifdef __cplusplus } #endif #endif ================================================ FILE: Zelig/mbed/TARGET_K64F/TOOLCHAIN_GCC_ARM/K64FN1M0xxx12.ld ================================================ /* * K64F ARM GCC linker script file */ MEMORY { VECTORS (rx) : ORIGIN = 0x00000000, LENGTH = 0x00000400 FLASH_PROTECTION (rx) : ORIGIN = 0x00000400, LENGTH = 0x00000010 FLASH (rx) : ORIGIN = 0x00000410, LENGTH = 0x00100000 - 0x00000410 RAM (rwx) : ORIGIN = 0x1FFF0198, LENGTH = 0x00040000 - 0x00000198 } /* Linker script to place sections and symbol values. Should be used together * with other linker script that defines memory regions FLASH and RAM. * It references following symbols, which must be defined in code: * _reset_init : Entry of reset handler * * It defines following symbols, which code can use without definition: * __exidx_start * __exidx_end * __etext * __data_start__ * __preinit_array_start * __preinit_array_end * __init_array_start * __init_array_end * __fini_array_start * __fini_array_end * __data_end__ * __bss_start__ * __bss_end__ * __end__ * end * __HeapLimit * __StackLimit * __StackTop * __stack */ ENTRY(Reset_Handler) SECTIONS { .isr_vector : { __vector_table = .; KEEP(*(.vector_table)) *(.text.Reset_Handler) *(.text.System_Init) . = ALIGN(4); } > VECTORS .flash_protect : { KEEP(*(.kinetis_flash_config_field)) . = ALIGN(4); } > FLASH_PROTECTION .text : { *(.text*) KEEP(*(.init)) KEEP(*(.fini)) /* .ctors */ *crtbegin.o(.ctors) *crtbegin?.o(.ctors) *(EXCLUDE_FILE(*crtend?.o *crtend.o) .ctors) *(SORT(.ctors.*)) *(.ctors) /* .dtors */ *crtbegin.o(.dtors) *crtbegin?.o(.dtors) *(EXCLUDE_FILE(*crtend?.o *crtend.o) .dtors) *(SORT(.dtors.*)) *(.dtors) *(.rodata*) KEEP(*(.eh_frame*)) } > FLASH .ARM.extab : { *(.ARM.extab* .gnu.linkonce.armextab.*) } > FLASH __exidx_start = .; .ARM.exidx : { *(.ARM.exidx* .gnu.linkonce.armexidx.*) } > FLASH __exidx_end = .; __etext = .; .data : AT (__etext) { __data_start__ = .; *(vtable) *(.data*) . = ALIGN(4); /* preinit data */ PROVIDE_HIDDEN (__preinit_array_start = .); KEEP(*(.preinit_array)) PROVIDE_HIDDEN (__preinit_array_end = .); . = ALIGN(4); /* init data */ PROVIDE_HIDDEN (__init_array_start = .); KEEP(*(SORT(.init_array.*))) KEEP(*(.init_array)) PROVIDE_HIDDEN (__init_array_end = .); . = ALIGN(4); /* finit data */ PROVIDE_HIDDEN (__fini_array_start = .); KEEP(*(SORT(.fini_array.*))) KEEP(*(.fini_array)) PROVIDE_HIDDEN (__fini_array_end = .); . = ALIGN(4); /* All data end */ __data_end__ = .; } > RAM .bss : { __bss_start__ = .; *(.bss*) *(COMMON) __bss_end__ = .; } > RAM .heap : { __end__ = .; end = __end__; *(.heap*) __HeapLimit = .; } > RAM /* .stack_dummy section doesn't contains any symbols. It is only * used for linker to calculate size of stack sections, and assign * values to stack symbols later */ .stack_dummy : { *(.stack) } > RAM /* * The section '.managed_exception_thread' is a LLILUM Specific addition to pad * the stack space at the bottom with enough space to build a managed array. * Assuming that the stack bottom (_StackLimit) is 8 bytes aligned, we add * 16 bytes that will contain the array ObjectHeader and the length member (see * ArrayImpl.cs). This way we do preserve stack alignment. */ .stack_dummy_managed_exception_thread : { *(.managed_exception_thread) } > RAM /* Set stack top to end of RAM, and stack limit move down by * size of stack_dummy section */ __StackTop = ORIGIN(RAM) + LENGTH(RAM); __StackLimit = __StackTop - SIZEOF(.stack_dummy) + SIZEOF(.stack_dummy_managed_exception_thread); PROVIDE(__stack = __StackTop); /* Check if data + heap + stack exceeds RAM limit */ ASSERT(__StackLimit >= __HeapLimit, "region RAM overflowed with stack") } ================================================ FILE: Zelig/mbed/TARGET_K64F/cmsis.h ================================================ /* mbed Microcontroller Library - CMSIS * Copyright (C) 2009-2011 ARM Limited. All rights reserved. * * A generic CMSIS include header, pulling in LPC11U24 specifics */ #ifndef MBED_CMSIS_H #define MBED_CMSIS_H #include "MK64F12.h" #include "cmsis_nvic.h" #endif ================================================ FILE: Zelig/mbed/TARGET_K64F/cmsis_nvic.h ================================================ /* mbed Microcontroller Library * CMSIS-style functionality to support dynamic vectors ******************************************************************************* * Copyright (c) 2011 ARM Limited. All rights reserved. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * 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 ARM Limited 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. ******************************************************************************* */ #ifndef MBED_CMSIS_NVIC_H #define MBED_CMSIS_NVIC_H #define NVIC_NUM_VECTORS (16 + 86) // CORE + MCU Peripherals #define NVIC_USER_IRQ_OFFSET 16 #include "cmsis.h" #ifdef __cplusplus extern "C" { #endif void NVIC_SetVector(IRQn_Type IRQn, uint32_t vector); uint32_t NVIC_GetVector(IRQn_Type IRQn); #ifdef __cplusplus } #endif #endif ================================================ FILE: Zelig/mbed/TARGET_K64F/core_ca9.h ================================================ /**************************************************************************//** * @file core_ca9.h * @brief CMSIS Cortex-A9 Core Peripheral Access Layer Header File * @version * @date 25 March 2013 * * @note * ******************************************************************************/ /* Copyright (c) 2009 - 2012 ARM LIMITED All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: - Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. - Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. - Neither the name of ARM 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 COPYRIGHT HOLDERS AND 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. ---------------------------------------------------------------------------*/ #if defined ( __ICCARM__ ) #pragma system_include /* treat file as system include file for MISRA check */ #endif #ifdef __cplusplus extern "C" { #endif #ifndef __CORE_CA9_H_GENERIC #define __CORE_CA9_H_GENERIC /** \page CMSIS_MISRA_Exceptions MISRA-C:2004 Compliance Exceptions CMSIS violates the following MISRA-C:2004 rules: \li Required Rule 8.5, object/function definition in header file.
Function definitions in header files are used to allow 'inlining'. \li Required Rule 18.4, declaration of union type or object of union type: '{...}'.
Unions are used for effective representation of core registers. \li Advisory Rule 19.7, Function-like macro defined.
Function-like macros are used to allow more efficient code. */ /******************************************************************************* * CMSIS definitions ******************************************************************************/ /** \ingroup Cortex_A9 @{ */ /* CMSIS CA9 definitions */ #define __CA9_CMSIS_VERSION_MAIN (0x03) /*!< [31:16] CMSIS HAL main version */ #define __CA9_CMSIS_VERSION_SUB (0x10) /*!< [15:0] CMSIS HAL sub version */ #define __CA9_CMSIS_VERSION ((__CA9_CMSIS_VERSION_MAIN << 16) | \ __CA9_CMSIS_VERSION_SUB ) /*!< CMSIS HAL version number */ #define __CORTEX_A (0x09) /*!< Cortex-A Core */ #if defined ( __CC_ARM ) #define __ASM __asm /*!< asm keyword for ARM Compiler */ #define __INLINE __inline /*!< inline keyword for ARM Compiler */ #define __STATIC_INLINE static __inline #define __STATIC_ASM static __asm #elif defined ( __ICCARM__ ) #define __ASM __asm /*!< asm keyword for IAR Compiler */ #define __INLINE inline /*!< inline keyword for IAR Compiler. Only available in High optimization mode! */ #define __STATIC_INLINE static inline #define __STATIC_ASM static __asm #elif defined ( __TMS470__ ) #define __ASM __asm /*!< asm keyword for TI CCS Compiler */ #define __STATIC_INLINE static inline #define __STATIC_ASM static __asm #elif defined ( __GNUC__ ) #define __ASM __asm /*!< asm keyword for GNU Compiler */ #define __INLINE inline /*!< inline keyword for GNU Compiler */ #define __STATIC_INLINE static inline #define __STATIC_ASM static __asm #elif defined ( __TASKING__ ) #define __ASM __asm /*!< asm keyword for TASKING Compiler */ #define __INLINE inline /*!< inline keyword for TASKING Compiler */ #define __STATIC_INLINE static inline #define __STATIC_ASM static __asm #endif /** __FPU_USED indicates whether an FPU is used or not. For this, __FPU_PRESENT has to be checked prior to making use of FPU specific registers and functions. */ #if defined ( __CC_ARM ) #if defined __TARGET_FPU_VFP #if (__FPU_PRESENT == 1) #define __FPU_USED 1 #else #warning "Compiler generates FPU instructions for a device without an FPU (check __FPU_PRESENT)" #define __FPU_USED 0 #endif #else #define __FPU_USED 0 #endif #elif defined ( __ICCARM__ ) #if defined __ARMVFP__ #if (__FPU_PRESENT == 1) #define __FPU_USED 1 #else #warning "Compiler generates FPU instructions for a device without an FPU (check __FPU_PRESENT)" #define __FPU_USED 0 #endif #else #define __FPU_USED 0 #endif #elif defined ( __TMS470__ ) #if defined __TI_VFP_SUPPORT__ #if (__FPU_PRESENT == 1) #define __FPU_USED 1 #else #warning "Compiler generates FPU instructions for a device without an FPU (check __FPU_PRESENT)" #define __FPU_USED 0 #endif #else #define __FPU_USED 0 #endif #elif defined ( __GNUC__ ) #if defined (__VFP_FP__) && !defined(__SOFTFP__) #if (__FPU_PRESENT == 1) #define __FPU_USED 1 #else #warning "Compiler generates FPU instructions for a device without an FPU (check __FPU_PRESENT)" #define __FPU_USED 0 #endif #else #define __FPU_USED 0 #endif #elif defined ( __TASKING__ ) #if defined __FPU_VFP__ #if (__FPU_PRESENT == 1) #define __FPU_USED 1 #else #error "Compiler generates FPU instructions for a device without an FPU (check __FPU_PRESENT)" #define __FPU_USED 0 #endif #else #define __FPU_USED 0 #endif #endif #include /*!< standard types definitions */ #include "core_caInstr.h" /*!< Core Instruction Access */ #include "core_caFunc.h" /*!< Core Function Access */ #include "core_cm4_simd.h" /*!< Compiler specific SIMD Intrinsics */ #endif /* __CORE_CA9_H_GENERIC */ #ifndef __CMSIS_GENERIC #ifndef __CORE_CA9_H_DEPENDANT #define __CORE_CA9_H_DEPENDANT /* check device defines and use defaults */ #if defined __CHECK_DEVICE_DEFINES #ifndef __CA9_REV #define __CA9_REV 0x0000 #warning "__CA9_REV not defined in device header file; using default!" #endif #ifndef __FPU_PRESENT #define __FPU_PRESENT 1 #warning "__FPU_PRESENT not defined in device header file; using default!" #endif #ifndef __Vendor_SysTickConfig #define __Vendor_SysTickConfig 1 #endif #if __Vendor_SysTickConfig == 0 #error "__Vendor_SysTickConfig set to 0, but vendor systick timer must be supplied for Cortex-A9" #endif #endif /* IO definitions (access restrictions to peripheral registers) */ /** \defgroup CMSIS_glob_defs CMSIS Global Defines IO Type Qualifiers are used \li to specify the access to peripheral variables. \li for automatic generation of peripheral register debug information. */ #ifdef __cplusplus #define __I volatile /*!< Defines 'read only' permissions */ #else #define __I volatile const /*!< Defines 'read only' permissions */ #endif #define __O volatile /*!< Defines 'write only' permissions */ #define __IO volatile /*!< Defines 'read / write' permissions */ /*@} end of group Cortex_A9 */ /******************************************************************************* * Register Abstraction ******************************************************************************/ /** \defgroup CMSIS_core_register Defines and Type Definitions \brief Type definitions and defines for Cortex-A processor based devices. */ /** \ingroup CMSIS_core_register \defgroup CMSIS_CORE Status and Control Registers \brief Core Register type definitions. @{ */ /** \brief Union type to access the Application Program Status Register (APSR). */ typedef union { struct { uint32_t _reserved0:16; /*!< bit: 0..15 Reserved */ uint32_t GE:4; /*!< bit: 16..19 Greater than or Equal flags */ uint32_t reserved1:7; /*!< bit: 20..23 Reserved */ uint32_t Q:1; /*!< bit: 27 Saturation condition flag */ uint32_t V:1; /*!< bit: 28 Overflow condition code flag */ uint32_t C:1; /*!< bit: 29 Carry condition code flag */ uint32_t Z:1; /*!< bit: 30 Zero condition code flag */ uint32_t N:1; /*!< bit: 31 Negative condition code flag */ } b; /*!< Structure used for bit access */ uint32_t w; /*!< Type used for word access */ } APSR_Type; /*@} end of group CMSIS_CORE */ /*@} end of CMSIS_Core_FPUFunctions */ #endif /* __CORE_CA9_H_GENERIC */ #endif /* __CMSIS_GENERIC */ #ifdef __cplusplus } #endif ================================================ FILE: Zelig/mbed/TARGET_K64F/core_caFunc.h ================================================ /**************************************************************************//** * @file core_caFunc.h * @brief CMSIS Cortex-A Core Function Access Header File * @version V3.10 * @date 9 May 2013 * * @note * ******************************************************************************/ /* Copyright (c) 2009 - 2012 ARM LIMITED All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: - Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. - Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. - Neither the name of ARM 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 COPYRIGHT HOLDERS AND 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. ---------------------------------------------------------------------------*/ #ifndef __CORE_CAFUNC_H__ #define __CORE_CAFUNC_H__ /* ########################### Core Function Access ########################### */ /** \ingroup CMSIS_Core_FunctionInterface \defgroup CMSIS_Core_RegAccFunctions CMSIS Core Register Access Functions @{ */ #if defined ( __CC_ARM ) /*------------------RealView Compiler -----------------*/ /* ARM armcc specific functions */ #if (__ARMCC_VERSION < 400677) #error "Please use ARM Compiler Toolchain V4.0.677 or later!" #endif #define MODE_USR 0x10 #define MODE_FIQ 0x11 #define MODE_IRQ 0x12 #define MODE_SVC 0x13 #define MODE_MON 0x16 #define MODE_ABT 0x17 #define MODE_HYP 0x1A #define MODE_UND 0x1B #define MODE_SYS 0x1F /** \brief Get APSR Register This function returns the content of the APSR Register. \return APSR Register value */ __STATIC_INLINE uint32_t __get_APSR(void) { register uint32_t __regAPSR __ASM("apsr"); return(__regAPSR); } /** \brief Get CPSR Register This function returns the content of the CPSR Register. \return CPSR Register value */ __STATIC_INLINE uint32_t __get_CPSR(void) { register uint32_t __regCPSR __ASM("cpsr"); return(__regCPSR); } /** \brief Set Stack Pointer This function assigns the given value to the current stack pointer. \param [in] topOfStack Stack Pointer value to set */ register uint32_t __regSP __ASM("sp"); __STATIC_INLINE void __set_SP(uint32_t topOfStack) { __regSP = topOfStack; } /** \brief Get link register This function returns the value of the link register \return Value of link register */ register uint32_t __reglr __ASM("lr"); __STATIC_INLINE uint32_t __get_LR(void) { return(__reglr); } /** \brief Set link register This function sets the value of the link register \param [in] lr LR value to set */ __STATIC_INLINE void __set_LR(uint32_t lr) { __reglr = lr; } /** \brief Set Process Stack Pointer This function assigns the given value to the USR/SYS Stack Pointer (PSP). \param [in] topOfProcStack USR/SYS Stack Pointer value to set */ __STATIC_ASM void __set_PSP(uint32_t topOfProcStack) { ARM PRESERVE8 BIC R0, R0, #7 ;ensure stack is 8-byte aligned MRS R1, CPSR CPS #MODE_SYS ;no effect in USR mode MOV SP, R0 MSR CPSR_c, R1 ;no effect in USR mode ISB BX LR } /** \brief Set User Mode This function changes the processor state to User Mode \param [in] topOfProcStack USR/SYS Stack Pointer value to set */ __STATIC_ASM void __set_CPS_USR(void) { ARM CPS #MODE_USR BX LR } /** \brief Enable FIQ This function enables FIQ interrupts by clearing the F-bit in the CPSR. Can only be executed in Privileged modes. */ #define __enable_fault_irq __enable_fiq /** \brief Disable FIQ This function disables FIQ interrupts by setting the F-bit in the CPSR. Can only be executed in Privileged modes. */ #define __disable_fault_irq __disable_fiq /** \brief Get FPSCR This function returns the current value of the Floating Point Status/Control register. \return Floating Point Status/Control register value */ __STATIC_INLINE uint32_t __get_FPSCR(void) { #if (__FPU_PRESENT == 1) && (__FPU_USED == 1) register uint32_t __regfpscr __ASM("fpscr"); return(__regfpscr); #else return(0); #endif } /** \brief Set FPSCR This function assigns the given value to the Floating Point Status/Control register. \param [in] fpscr Floating Point Status/Control value to set */ __STATIC_INLINE void __set_FPSCR(uint32_t fpscr) { #if (__FPU_PRESENT == 1) && (__FPU_USED == 1) register uint32_t __regfpscr __ASM("fpscr"); __regfpscr = (fpscr); #endif } /** \brief Get FPEXC This function returns the current value of the Floating Point Exception Control register. \return Floating Point Exception Control register value */ __STATIC_INLINE uint32_t __get_FPEXC(void) { #if (__FPU_PRESENT == 1) register uint32_t __regfpexc __ASM("fpexc"); return(__regfpexc); #else return(0); #endif } /** \brief Set FPEXC This function assigns the given value to the Floating Point Exception Control register. \param [in] fpscr Floating Point Exception Control value to set */ __STATIC_INLINE void __set_FPEXC(uint32_t fpexc) { #if (__FPU_PRESENT == 1) register uint32_t __regfpexc __ASM("fpexc"); __regfpexc = (fpexc); #endif } /** \brief Get CPACR This function returns the current value of the Coprocessor Access Control register. \return Coprocessor Access Control register value */ __STATIC_INLINE uint32_t __get_CPACR(void) { register uint32_t __regCPACR __ASM("cp15:0:c1:c0:2"); return __regCPACR; } /** \brief Set CPACR This function assigns the given value to the Coprocessor Access Control register. \param [in] cpacr Coporcessor Acccess Control value to set */ __STATIC_INLINE void __set_CPACR(uint32_t cpacr) { register uint32_t __regCPACR __ASM("cp15:0:c1:c0:2"); __regCPACR = cpacr; __ISB(); } /** \brief Get CBAR This function returns the value of the Configuration Base Address register. \return Configuration Base Address register value */ __STATIC_INLINE uint32_t __get_CBAR() { register uint32_t __regCBAR __ASM("cp15:4:c15:c0:0"); return(__regCBAR); } /** \brief Get TTBR0 This function returns the value of the Configuration Base Address register. \return Translation Table Base Register 0 value */ __STATIC_INLINE uint32_t __get_TTBR0() { register uint32_t __regTTBR0 __ASM("cp15:0:c2:c0:0"); return(__regTTBR0); } /** \brief Set TTBR0 This function assigns the given value to the Coprocessor Access Control register. \param [in] ttbr0 Translation Table Base Register 0 value to set */ __STATIC_INLINE void __set_TTBR0(uint32_t ttbr0) { register uint32_t __regTTBR0 __ASM("cp15:0:c2:c0:0"); __regTTBR0 = ttbr0; __ISB(); } /** \brief Get DACR This function returns the value of the Domain Access Control Register. \return Domain Access Control Register value */ __STATIC_INLINE uint32_t __get_DACR() { register uint32_t __regDACR __ASM("cp15:0:c3:c0:0"); return(__regDACR); } /** \brief Set DACR This function assigns the given value to the Coprocessor Access Control register. \param [in] dacr Domain Access Control Register value to set */ __STATIC_INLINE void __set_DACR(uint32_t dacr) { register uint32_t __regDACR __ASM("cp15:0:c3:c0:0"); __regDACR = dacr; __ISB(); } /******************************** Cache and BTAC enable ****************************************************/ /** \brief Set SCTLR This function assigns the given value to the System Control Register. \param [in] sctlr System Control Register, value to set */ __STATIC_INLINE void __set_SCTLR(uint32_t sctlr) { register uint32_t __regSCTLR __ASM("cp15:0:c1:c0:0"); __regSCTLR = sctlr; } /** \brief Get SCTLR This function returns the value of the System Control Register. \return System Control Register value */ __STATIC_INLINE uint32_t __get_SCTLR() { register uint32_t __regSCTLR __ASM("cp15:0:c1:c0:0"); return(__regSCTLR); } /** \brief Enable Caches Enable Caches */ __STATIC_INLINE void __enable_caches(void) { // Set I bit 12 to enable I Cache // Set C bit 2 to enable D Cache __set_SCTLR( __get_SCTLR() | (1 << 12) | (1 << 2)); } /** \brief Disable Caches Disable Caches */ __STATIC_INLINE void __disable_caches(void) { // Clear I bit 12 to disable I Cache // Clear C bit 2 to disable D Cache __set_SCTLR( __get_SCTLR() & ~(1 << 12) & ~(1 << 2)); __ISB(); } /** \brief Enable BTAC Enable BTAC */ __STATIC_INLINE void __enable_btac(void) { // Set Z bit 11 to enable branch prediction __set_SCTLR( __get_SCTLR() | (1 << 11)); __ISB(); } /** \brief Disable BTAC Disable BTAC */ __STATIC_INLINE void __disable_btac(void) { // Clear Z bit 11 to disable branch prediction __set_SCTLR( __get_SCTLR() & ~(1 << 11)); } /** \brief Enable MMU Enable MMU */ __STATIC_INLINE void __enable_mmu(void) { // Set M bit 0 to enable the MMU // Set AFE bit to enable simplified access permissions model // Clear TRE bit to disable TEX remap and A bit to disable strict alignment fault checking __set_SCTLR( (__get_SCTLR() & ~(1 << 28) & ~(1 << 1)) | 1 | (1 << 29)); __ISB(); } /** \brief Enable MMU Enable MMU */ __STATIC_INLINE void __disable_mmu(void) { // Clear M bit 0 to disable the MMU __set_SCTLR( __get_SCTLR() & ~1); __ISB(); } /******************************** TLB maintenance operations ************************************************/ /** \brief Invalidate the whole tlb TLBIALL. Invalidate the whole tlb */ __STATIC_INLINE void __ca9u_inv_tlb_all(void) { register uint32_t __TLBIALL __ASM("cp15:0:c8:c7:0"); __TLBIALL = 0; __DSB(); __ISB(); } /******************************** BTB maintenance operations ************************************************/ /** \brief Invalidate entire branch predictor array BPIALL. Branch Predictor Invalidate All. */ __STATIC_INLINE void __v7_inv_btac(void) { register uint32_t __BPIALL __ASM("cp15:0:c7:c5:6"); __BPIALL = 0; __DSB(); //ensure completion of the invalidation __ISB(); //ensure instruction fetch path sees new state } /******************************** L1 cache operations ******************************************************/ /** \brief Invalidate the whole I$ ICIALLU. Instruction Cache Invalidate All to PoU */ __STATIC_INLINE void __v7_inv_icache_all(void) { register uint32_t __ICIALLU __ASM("cp15:0:c7:c5:0"); __ICIALLU = 0; __DSB(); //ensure completion of the invalidation __ISB(); //ensure instruction fetch path sees new I cache state } /** \brief Clean D$ by MVA DCCMVAC. Data cache clean by MVA to PoC */ __STATIC_INLINE void __v7_clean_dcache_mva(void *va) { register uint32_t __DCCMVAC __ASM("cp15:0:c7:c10:1"); __DCCMVAC = (uint32_t)va; __DMB(); //ensure the ordering of data cache maintenance operations and their effects } /** \brief Invalidate D$ by MVA DCIMVAC. Data cache invalidate by MVA to PoC */ __STATIC_INLINE void __v7_inv_dcache_mva(void *va) { register uint32_t __DCIMVAC __ASM("cp15:0:c7:c6:1"); __DCIMVAC = (uint32_t)va; __DMB(); //ensure the ordering of data cache maintenance operations and their effects } /** \brief Clean and Invalidate D$ by MVA DCCIMVAC. Data cache clean and invalidate by MVA to PoC */ __STATIC_INLINE void __v7_clean_inv_dcache_mva(void *va) { register uint32_t __DCCIMVAC __ASM("cp15:0:c7:c14:1"); __DCCIMVAC = (uint32_t)va; __DMB(); //ensure the ordering of data cache maintenance operations and their effects } /** \brief * Generic mechanism for cleaning/invalidating the entire data or unified cache to the point of coherency. */ #pragma push #pragma arm __STATIC_ASM void __v7_all_cache(uint32_t op) { ARM PUSH {R4-R11} MRC p15, 1, R6, c0, c0, 1 // Read CLIDR ANDS R3, R6, #0x07000000 // Extract coherency level MOV R3, R3, LSR #23 // Total cache levels << 1 BEQ Finished // If 0, no need to clean MOV R10, #0 // R10 holds current cache level << 1 Loop1 ADD R2, R10, R10, LSR #1 // R2 holds cache "Set" position MOV R1, R6, LSR R2 // Bottom 3 bits are the Cache-type for this level AND R1, R1, #7 // Isolate those lower 3 bits CMP R1, #2 BLT Skip // No cache or only instruction cache at this level MCR p15, 2, R10, c0, c0, 0 // Write the Cache Size selection register ISB // ISB to sync the change to the CacheSizeID reg MRC p15, 1, R1, c0, c0, 0 // Reads current Cache Size ID register AND R2, R1, #7 // Extract the line length field ADD R2, R2, #4 // Add 4 for the line length offset (log2 16 bytes) LDR R4, =0x3FF ANDS R4, R4, R1, LSR #3 // R4 is the max number on the way size (right aligned) CLZ R5, R4 // R5 is the bit position of the way size increment LDR R7, =0x7FFF ANDS R7, R7, R1, LSR #13 // R7 is the max number of the index size (right aligned) Loop2 MOV R9, R4 // R9 working copy of the max way size (right aligned) Loop3 ORR R11, R10, R9, LSL R5 // Factor in the Way number and cache number into R11 ORR R11, R11, R7, LSL R2 // Factor in the Set number CMP R0, #0 BNE Dccsw MCR p15, 0, R11, c7, c6, 2 // DCISW. Invalidate by Set/Way B cont Dccsw CMP R0, #1 BNE Dccisw MCR p15, 0, R11, c7, c10, 2 // DCCSW. Clean by Set/Way B cont Dccisw MCR p15, 0, R11, c7, c14, 2 // DCCISW, Clean and Invalidate by Set/Way cont SUBS R9, R9, #1 // Decrement the Way number BGE Loop3 SUBS R7, R7, #1 // Decrement the Set number BGE Loop2 Skip ADD R10, R10, #2 // increment the cache number CMP R3, R10 BGT Loop1 Finished DSB POP {R4-R11} BX lr } #pragma pop /** \brief __v7_all_cache - helper function */ /** \brief Invalidate the whole D$ DCISW. Invalidate by Set/Way */ __STATIC_INLINE void __v7_inv_dcache_all(void) { __v7_all_cache(0); } /** \brief Clean the whole D$ DCCSW. Clean by Set/Way */ __STATIC_INLINE void __v7_clean_dcache_all(void) { __v7_all_cache(1); } /** \brief Clean and invalidate the whole D$ DCCISW. Clean and Invalidate by Set/Way */ __STATIC_INLINE void __v7_clean_inv_dcache_all(void) { __v7_all_cache(2); } #include "core_ca_mmu.h" #elif (defined (__ICCARM__)) /*---------------- ICC Compiler ---------------------*/ #error IAR Compiler support not implemented for Cortex-A #elif (defined (__GNUC__)) /*------------------ GNU Compiler ---------------------*/ /* GNU gcc specific functions */ #define MODE_USR 0x10 #define MODE_FIQ 0x11 #define MODE_IRQ 0x12 #define MODE_SVC 0x13 #define MODE_MON 0x16 #define MODE_ABT 0x17 #define MODE_HYP 0x1A #define MODE_UND 0x1B #define MODE_SYS 0x1F __attribute__( ( always_inline ) ) __STATIC_INLINE void __enable_irq(void) { __ASM volatile ("cpsie i"); } /** \brief Disable IRQ Interrupts This function disables IRQ interrupts by setting the I-bit in the CPSR. Can only be executed in Privileged modes. */ __attribute__( ( always_inline ) ) __STATIC_INLINE uint32_t __disable_irq(void) { uint32_t result; __ASM volatile ("mrs %0, cpsr" : "=r" (result)); __ASM volatile ("cpsid i"); return(result & 0x80); } /** \brief Get APSR Register This function returns the content of the APSR Register. \return APSR Register value */ __attribute__( ( always_inline ) ) __STATIC_INLINE uint32_t __get_APSR(void) { #if 1 uint32_t result; __ASM volatile ("mrs %0, apsr" : "=r" (result) ); return (result); #else register uint32_t __regAPSR __ASM("apsr"); return(__regAPSR); #endif } /** \brief Get CPSR Register This function returns the content of the CPSR Register. \return CPSR Register value */ __attribute__( ( always_inline ) ) __STATIC_INLINE uint32_t __get_CPSR(void) { #if 1 register uint32_t __regCPSR; __ASM volatile ("mrs %0, cpsr" : "=r" (__regCPSR)); #else register uint32_t __regCPSR __ASM("cpsr"); #endif return(__regCPSR); } #if 0 /** \brief Set Stack Pointer This function assigns the given value to the current stack pointer. \param [in] topOfStack Stack Pointer value to set */ __attribute__( ( always_inline ) ) __STATIC_INLINE void __set_SP(uint32_t topOfStack) { register uint32_t __regSP __ASM("sp"); __regSP = topOfStack; } #endif /** \brief Get link register This function returns the value of the link register \return Value of link register */ __attribute__( ( always_inline ) ) __STATIC_INLINE uint32_t __get_LR(void) { register uint32_t __reglr __ASM("lr"); return(__reglr); } #if 0 /** \brief Set link register This function sets the value of the link register \param [in] lr LR value to set */ __attribute__( ( always_inline ) ) __STATIC_INLINE void __set_LR(uint32_t lr) { register uint32_t __reglr __ASM("lr"); __reglr = lr; } #endif /** \brief Set Process Stack Pointer This function assigns the given value to the USR/SYS Stack Pointer (PSP). \param [in] topOfProcStack USR/SYS Stack Pointer value to set */ extern void __set_PSP(uint32_t topOfProcStack); /** \brief Set User Mode This function changes the processor state to User Mode \param [in] topOfProcStack USR/SYS Stack Pointer value to set */ extern void __set_CPS_USR(void); /** \brief Enable FIQ This function enables FIQ interrupts by clearing the F-bit in the CPSR. Can only be executed in Privileged modes. */ #define __enable_fault_irq __enable_fiq /** \brief Disable FIQ This function disables FIQ interrupts by setting the F-bit in the CPSR. Can only be executed in Privileged modes. */ #define __disable_fault_irq __disable_fiq /** \brief Get FPSCR This function returns the current value of the Floating Point Status/Control register. \return Floating Point Status/Control register value */ __attribute__( ( always_inline ) ) __STATIC_INLINE uint32_t __get_FPSCR(void) { #if (__FPU_PRESENT == 1) && (__FPU_USED == 1) #if 1 uint32_t result; __ASM volatile ("vmrs %0, fpscr" : "=r" (result) ); return (result); #else register uint32_t __regfpscr __ASM("fpscr"); return(__regfpscr); #endif #else return(0); #endif } /** \brief Set FPSCR This function assigns the given value to the Floating Point Status/Control register. \param [in] fpscr Floating Point Status/Control value to set */ __attribute__( ( always_inline ) ) __STATIC_INLINE void __set_FPSCR(uint32_t fpscr) { #if (__FPU_PRESENT == 1) && (__FPU_USED == 1) #if 1 __ASM volatile ("vmsr fpscr, %0" : : "r" (fpscr) ); #else register uint32_t __regfpscr __ASM("fpscr"); __regfpscr = (fpscr); #endif #endif } /** \brief Get FPEXC This function returns the current value of the Floating Point Exception Control register. \return Floating Point Exception Control register value */ __attribute__( ( always_inline ) ) __STATIC_INLINE uint32_t __get_FPEXC(void) { #if (__FPU_PRESENT == 1) #if 1 uint32_t result; __ASM volatile ("vmrs %0, fpexc" : "=r" (result)); return (result); #else register uint32_t __regfpexc __ASM("fpexc"); return(__regfpexc); #endif #else return(0); #endif } /** \brief Set FPEXC This function assigns the given value to the Floating Point Exception Control register. \param [in] fpscr Floating Point Exception Control value to set */ __attribute__( ( always_inline ) ) __STATIC_INLINE void __set_FPEXC(uint32_t fpexc) { #if (__FPU_PRESENT == 1) #if 1 __ASM volatile ("vmsr fpexc, %0" : : "r" (fpexc)); #else register uint32_t __regfpexc __ASM("fpexc"); __regfpexc = (fpexc); #endif #endif } /** \brief Get CPACR This function returns the current value of the Coprocessor Access Control register. \return Coprocessor Access Control register value */ __attribute__( ( always_inline ) ) __STATIC_INLINE uint32_t __get_CPACR(void) { #if 1 register uint32_t __regCPACR; __ASM volatile ("mrc p15, 0, %0, c1, c0, 2" : "=r" (__regCPACR)); #else register uint32_t __regCPACR __ASM("cp15:0:c1:c0:2"); #endif return __regCPACR; } /** \brief Set CPACR This function assigns the given value to the Coprocessor Access Control register. \param [in] cpacr Coporcessor Acccess Control value to set */ __attribute__( ( always_inline ) ) __STATIC_INLINE void __set_CPACR(uint32_t cpacr) { #if 1 __ASM volatile ("mcr p15, 0, %0, c1, c0, 2" : : "r" (cpacr)); #else register uint32_t __regCPACR __ASM("cp15:0:c1:c0:2"); __regCPACR = cpacr; #endif __ISB(); } /** \brief Get CBAR This function returns the value of the Configuration Base Address register. \return Configuration Base Address register value */ __attribute__( ( always_inline ) ) __STATIC_INLINE uint32_t __get_CBAR() { #if 1 register uint32_t __regCBAR; __ASM volatile ("mrc p15, 4, %0, c15, c0, 0" : "=r" (__regCBAR)); #else register uint32_t __regCBAR __ASM("cp15:4:c15:c0:0"); #endif return(__regCBAR); } /** \brief Get TTBR0 This function returns the value of the Configuration Base Address register. \return Translation Table Base Register 0 value */ __attribute__( ( always_inline ) ) __STATIC_INLINE uint32_t __get_TTBR0() { #if 1 register uint32_t __regTTBR0; __ASM volatile ("mrc p15, 0, %0, c2, c0, 0" : "=r" (__regTTBR0)); #else register uint32_t __regTTBR0 __ASM("cp15:0:c2:c0:0"); #endif return(__regTTBR0); } /** \brief Set TTBR0 This function assigns the given value to the Coprocessor Access Control register. \param [in] ttbr0 Translation Table Base Register 0 value to set */ __attribute__( ( always_inline ) ) __STATIC_INLINE void __set_TTBR0(uint32_t ttbr0) { #if 1 __ASM volatile ("mcr p15, 0, %0, c2, c0, 0" : : "r" (ttbr0)); #else register uint32_t __regTTBR0 __ASM("cp15:0:c2:c0:0"); __regTTBR0 = ttbr0; #endif __ISB(); } /** \brief Get DACR This function returns the value of the Domain Access Control Register. \return Domain Access Control Register value */ __attribute__( ( always_inline ) ) __STATIC_INLINE uint32_t __get_DACR() { #if 1 register uint32_t __regDACR; __ASM volatile ("mrc p15, 0, %0, c3, c0, 0" : "=r" (__regDACR)); #else register uint32_t __regDACR __ASM("cp15:0:c3:c0:0"); #endif return(__regDACR); } /** \brief Set DACR This function assigns the given value to the Coprocessor Access Control register. \param [in] dacr Domain Access Control Register value to set */ __attribute__( ( always_inline ) ) __STATIC_INLINE void __set_DACR(uint32_t dacr) { #if 1 __ASM volatile ("mcr p15, 0, %0, c3, c0, 0" : : "r" (dacr)); #else register uint32_t __regDACR __ASM("cp15:0:c3:c0:0"); __regDACR = dacr; #endif __ISB(); } /******************************** Cache and BTAC enable ****************************************************/ /** \brief Set SCTLR This function assigns the given value to the System Control Register. \param [in] sctlr System Control Register, value to set */ __attribute__( ( always_inline ) ) __STATIC_INLINE void __set_SCTLR(uint32_t sctlr) { #if 1 __ASM volatile ("mcr p15, 0, %0, c1, c0, 0" : : "r" (sctlr)); #else register uint32_t __regSCTLR __ASM("cp15:0:c1:c0:0"); __regSCTLR = sctlr; #endif } /** \brief Get SCTLR This function returns the value of the System Control Register. \return System Control Register value */ __attribute__( ( always_inline ) ) __STATIC_INLINE uint32_t __get_SCTLR() { #if 1 register uint32_t __regSCTLR; __ASM volatile ("mrc p15, 0, %0, c1, c0, 0" : "=r" (__regSCTLR)); #else register uint32_t __regSCTLR __ASM("cp15:0:c1:c0:0"); #endif return(__regSCTLR); } /** \brief Enable Caches Enable Caches */ __attribute__( ( always_inline ) ) __STATIC_INLINE void __enable_caches(void) { // Set I bit 12 to enable I Cache // Set C bit 2 to enable D Cache __set_SCTLR( __get_SCTLR() | (1 << 12) | (1 << 2)); } /** \brief Disable Caches Disable Caches */ __attribute__( ( always_inline ) ) __STATIC_INLINE void __disable_caches(void) { // Clear I bit 12 to disable I Cache // Clear C bit 2 to disable D Cache __set_SCTLR( __get_SCTLR() & ~(1 << 12) & ~(1 << 2)); __ISB(); } /** \brief Enable BTAC Enable BTAC */ __attribute__( ( always_inline ) ) __STATIC_INLINE void __enable_btac(void) { // Set Z bit 11 to enable branch prediction __set_SCTLR( __get_SCTLR() | (1 << 11)); __ISB(); } /** \brief Disable BTAC Disable BTAC */ __attribute__( ( always_inline ) ) __STATIC_INLINE void __disable_btac(void) { // Clear Z bit 11 to disable branch prediction __set_SCTLR( __get_SCTLR() & ~(1 << 11)); } /** \brief Enable MMU Enable MMU */ __attribute__( ( always_inline ) ) __STATIC_INLINE void __enable_mmu(void) { // Set M bit 0 to enable the MMU // Set AFE bit to enable simplified access permissions model // Clear TRE bit to disable TEX remap and A bit to disable strict alignment fault checking __set_SCTLR( (__get_SCTLR() & ~(1 << 28) & ~(1 << 1)) | 1 | (1 << 29)); __ISB(); } /** \brief Enable MMU Enable MMU */ __attribute__( ( always_inline ) ) __STATIC_INLINE void __disable_mmu(void) { // Clear M bit 0 to disable the MMU __set_SCTLR( __get_SCTLR() & ~1); __ISB(); } /******************************** TLB maintenance operations ************************************************/ /** \brief Invalidate the whole tlb TLBIALL. Invalidate the whole tlb */ __attribute__( ( always_inline ) ) __STATIC_INLINE void __ca9u_inv_tlb_all(void) { #if 1 __ASM volatile ("mcr p15, 0, %0, c8, c7, 0" : : "r" (0)); #else register uint32_t __TLBIALL __ASM("cp15:0:c8:c7:0"); __TLBIALL = 0; #endif __DSB(); __ISB(); } /******************************** BTB maintenance operations ************************************************/ /** \brief Invalidate entire branch predictor array BPIALL. Branch Predictor Invalidate All. */ __attribute__( ( always_inline ) ) __STATIC_INLINE void __v7_inv_btac(void) { #if 1 __ASM volatile ("mcr p15, 0, %0, c7, c5, 6" : : "r" (0)); #else register uint32_t __BPIALL __ASM("cp15:0:c7:c5:6"); __BPIALL = 0; #endif __DSB(); //ensure completion of the invalidation __ISB(); //ensure instruction fetch path sees new state } /******************************** L1 cache operations ******************************************************/ /** \brief Invalidate the whole I$ ICIALLU. Instruction Cache Invalidate All to PoU */ __attribute__( ( always_inline ) ) __STATIC_INLINE void __v7_inv_icache_all(void) { #if 1 __ASM volatile ("mcr p15, 0, %0, c7, c5, 0" : : "r" (0)); #else register uint32_t __ICIALLU __ASM("cp15:0:c7:c5:0"); __ICIALLU = 0; #endif __DSB(); //ensure completion of the invalidation __ISB(); //ensure instruction fetch path sees new I cache state } /** \brief Clean D$ by MVA DCCMVAC. Data cache clean by MVA to PoC */ __attribute__( ( always_inline ) ) __STATIC_INLINE void __v7_clean_dcache_mva(void *va) { #if 1 __ASM volatile ("mcr p15, 0, %0, c7, c10, 1" : : "r" ((uint32_t)va)); #else register uint32_t __DCCMVAC __ASM("cp15:0:c7:c10:1"); __DCCMVAC = (uint32_t)va; #endif __DMB(); //ensure the ordering of data cache maintenance operations and their effects } /** \brief Invalidate D$ by MVA DCIMVAC. Data cache invalidate by MVA to PoC */ __attribute__( ( always_inline ) ) __STATIC_INLINE void __v7_inv_dcache_mva(void *va) { #if 1 __ASM volatile ("mcr p15, 0, %0, c7, c6, 1" : : "r" ((uint32_t)va)); #else register uint32_t __DCIMVAC __ASM("cp15:0:c7:c6:1"); __DCIMVAC = (uint32_t)va; #endif __DMB(); //ensure the ordering of data cache maintenance operations and their effects } /** \brief Clean and Invalidate D$ by MVA DCCIMVAC. Data cache clean and invalidate by MVA to PoC */ __attribute__( ( always_inline ) ) __STATIC_INLINE void __v7_clean_inv_dcache_mva(void *va) { #if 1 __ASM volatile ("mcr p15, 0, %0, c7, c14, 1" : : "r" ((uint32_t)va)); #else register uint32_t __DCCIMVAC __ASM("cp15:0:c7:c14:1"); __DCCIMVAC = (uint32_t)va; #endif __DMB(); //ensure the ordering of data cache maintenance operations and their effects } /** \brief * Generic mechanism for cleaning/invalidating the entire data or unified cache to the point of coherency. */ /** \brief __v7_all_cache - helper function */ extern void __v7_all_cache(uint32_t op); /** \brief Invalidate the whole D$ DCISW. Invalidate by Set/Way */ __attribute__( ( always_inline ) ) __STATIC_INLINE void __v7_inv_dcache_all(void) { __v7_all_cache(0); } /** \brief Clean the whole D$ DCCSW. Clean by Set/Way */ __attribute__( ( always_inline ) ) __STATIC_INLINE void __v7_clean_dcache_all(void) { __v7_all_cache(1); } /** \brief Clean and invalidate the whole D$ DCCISW. Clean and Invalidate by Set/Way */ __attribute__( ( always_inline ) ) __STATIC_INLINE void __v7_clean_inv_dcache_all(void) { __v7_all_cache(2); } #include "core_ca_mmu.h" #elif (defined (__TASKING__)) /*--------------- TASKING Compiler -----------------*/ #error TASKING Compiler support not implemented for Cortex-A #endif /*@} end of CMSIS_Core_RegAccFunctions */ #endif /* __CORE_CAFUNC_H__ */ ================================================ FILE: Zelig/mbed/TARGET_K64F/core_caInstr.h ================================================ /**************************************************************************//** * @file core_caInstr.h * @brief CMSIS Cortex-A9 Core Peripheral Access Layer Header File * @version * @date 04. December 2012 * * @note * ******************************************************************************/ /* Copyright (c) 2009 - 2012 ARM LIMITED All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: - Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. - Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. - Neither the name of ARM 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 COPYRIGHT HOLDERS AND 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. ---------------------------------------------------------------------------*/ #ifndef __CORE_CAINSTR_H__ #define __CORE_CAINSTR_H__ #define __CORTEX_M 0x3 #include "core_cmInstr.h" #undef __CORTEX_M #endif ================================================ FILE: Zelig/mbed/TARGET_K64F/core_ca_mmu.h ================================================ ;/**************************************************************************//** ; * @file core_ca_mmu.h ; * @brief MMU Startup File for ; * VE_A9_MP Device Series ; * @version V1.01 ; * @date 25 March 2013 ; * ; * @note ; * ; ******************************************************************************/ ;/* Copyright (c) 2012 ARM LIMITED ; ; All rights reserved. ; Redistribution and use in source and binary forms, with or without ; modification, are permitted provided that the following conditions are met: ; - Redistributions of source code must retain the above copyright ; notice, this list of conditions and the following disclaimer. ; - Redistributions in binary form must reproduce the above copyright ; notice, this list of conditions and the following disclaimer in the ; documentation and/or other materials provided with the distribution. ; - Neither the name of ARM 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 COPYRIGHT HOLDERS AND CONTRIBUTORS BE ; LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR ; CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF ; SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS ; INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN ; CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ; ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE ; POSSIBILITY OF SUCH DAMAGE. ; ---------------------------------------------------------------------------*/ #ifdef __cplusplus extern "C" { #endif #ifndef _MMU_FUNC_H #define _MMU_FUNC_H #define SECTION_DESCRIPTOR (0x2) #define SECTION_MASK (0xFFFFFFFC) #define SECTION_TEXCB_MASK (0xFFFF8FF3) #define SECTION_B_SHIFT (2) #define SECTION_C_SHIFT (3) #define SECTION_TEX0_SHIFT (12) #define SECTION_TEX1_SHIFT (13) #define SECTION_TEX2_SHIFT (14) #define SECTION_XN_MASK (0xFFFFFFEF) #define SECTION_XN_SHIFT (4) #define SECTION_DOMAIN_MASK (0xFFFFFE1F) #define SECTION_DOMAIN_SHIFT (5) #define SECTION_P_MASK (0xFFFFFDFF) #define SECTION_P_SHIFT (9) #define SECTION_AP_MASK (0xFFFF73FF) #define SECTION_AP_SHIFT (10) #define SECTION_AP2_SHIFT (15) #define SECTION_S_MASK (0xFFFEFFFF) #define SECTION_S_SHIFT (16) #define SECTION_NG_MASK (0xFFFDFFFF) #define SECTION_NG_SHIFT (17) #define SECTION_NS_MASK (0xFFF7FFFF) #define SECTION_NS_SHIFT (19) #define PAGE_L1_DESCRIPTOR (0x1) #define PAGE_L1_MASK (0xFFFFFFFC) #define PAGE_L2_4K_DESC (0x2) #define PAGE_L2_4K_MASK (0xFFFFFFFD) #define PAGE_L2_64K_DESC (0x1) #define PAGE_L2_64K_MASK (0xFFFFFFFC) #define PAGE_4K_TEXCB_MASK (0xFFFFFE33) #define PAGE_4K_B_SHIFT (2) #define PAGE_4K_C_SHIFT (3) #define PAGE_4K_TEX0_SHIFT (6) #define PAGE_4K_TEX1_SHIFT (7) #define PAGE_4K_TEX2_SHIFT (8) #define PAGE_64K_TEXCB_MASK (0xFFFF8FF3) #define PAGE_64K_B_SHIFT (2) #define PAGE_64K_C_SHIFT (3) #define PAGE_64K_TEX0_SHIFT (12) #define PAGE_64K_TEX1_SHIFT (13) #define PAGE_64K_TEX2_SHIFT (14) #define PAGE_TEXCB_MASK (0xFFFF8FF3) #define PAGE_B_SHIFT (2) #define PAGE_C_SHIFT (3) #define PAGE_TEX_SHIFT (12) #define PAGE_XN_4K_MASK (0xFFFFFFFE) #define PAGE_XN_4K_SHIFT (0) #define PAGE_XN_64K_MASK (0xFFFF7FFF) #define PAGE_XN_64K_SHIFT (15) #define PAGE_DOMAIN_MASK (0xFFFFFE1F) #define PAGE_DOMAIN_SHIFT (5) #define PAGE_P_MASK (0xFFFFFDFF) #define PAGE_P_SHIFT (9) #define PAGE_AP_MASK (0xFFFFFDCF) #define PAGE_AP_SHIFT (4) #define PAGE_AP2_SHIFT (9) #define PAGE_S_MASK (0xFFFFFBFF) #define PAGE_S_SHIFT (10) #define PAGE_NG_MASK (0xFFFFF7FF) #define PAGE_NG_SHIFT (11) #define PAGE_NS_MASK (0xFFFFFFF7) #define PAGE_NS_SHIFT (3) #define OFFSET_1M (0x00100000) #define OFFSET_64K (0x00010000) #define OFFSET_4K (0x00001000) #define DESCRIPTOR_FAULT (0x00000000) /* ########################### MMU Function Access ########################### */ /** \ingroup MMU_FunctionInterface \defgroup MMU_Functions MMU Functions Interface @{ */ /* Attributes enumerations */ /* Region size attributes */ typedef enum { SECTION, PAGE_4k, PAGE_64k, } mmu_region_size_Type; /* Region type attributes */ typedef enum { NORMAL, DEVICE, SHARED_DEVICE, NON_SHARED_DEVICE, STRONGLY_ORDERED } mmu_memory_Type; /* Region cacheability attributes */ typedef enum { NON_CACHEABLE, WB_WA, WT, WB_NO_WA, } mmu_cacheability_Type; /* Region parity check attributes */ typedef enum { ECC_DISABLED, ECC_ENABLED, } mmu_ecc_check_Type; /* Region execution attributes */ typedef enum { EXECUTE, NON_EXECUTE, } mmu_execute_Type; /* Region global attributes */ typedef enum { GLOBAL, NON_GLOBAL, } mmu_global_Type; /* Region shareability attributes */ typedef enum { NON_SHARED, SHARED, } mmu_shared_Type; /* Region security attributes */ typedef enum { SECURE, NON_SECURE, } mmu_secure_Type; /* Region access attributes */ typedef enum { NO_ACCESS, RW, READ, } mmu_access_Type; /* Memory Region definition */ typedef struct RegionStruct { mmu_region_size_Type rg_t; mmu_memory_Type mem_t; uint8_t domain; mmu_cacheability_Type inner_norm_t; mmu_cacheability_Type outer_norm_t; mmu_ecc_check_Type e_t; mmu_execute_Type xn_t; mmu_global_Type g_t; mmu_secure_Type sec_t; mmu_access_Type priv_t; mmu_access_Type user_t; mmu_shared_Type sh_t; } mmu_region_attributes_Type; /** \brief Set section execution-never attribute The function sets section execution-never attribute \param [out] descriptor_l1 L1 descriptor. \param [in] xn Section execution-never attribute : EXECUTE , NON_EXECUTE. \return 0 */ __STATIC_INLINE int __xn_section(uint32_t *descriptor_l1, mmu_execute_Type xn) { *descriptor_l1 &= SECTION_XN_MASK; *descriptor_l1 |= ((xn & 0x1) << SECTION_XN_SHIFT); return 0; } /** \brief Set section domain The function sets section domain \param [out] descriptor_l1 L1 descriptor. \param [in] domain Section domain \return 0 */ __STATIC_INLINE int __domain_section(uint32_t *descriptor_l1, uint8_t domain) { *descriptor_l1 &= SECTION_DOMAIN_MASK; *descriptor_l1 |= ((domain & 0xF) << SECTION_DOMAIN_SHIFT); return 0; } /** \brief Set section parity check The function sets section parity check \param [out] descriptor_l1 L1 descriptor. \param [in] p_bit Parity check: ECC_DISABLED, ECC_ENABLED \return 0 */ __STATIC_INLINE int __p_section(uint32_t *descriptor_l1, mmu_ecc_check_Type p_bit) { *descriptor_l1 &= SECTION_P_MASK; *descriptor_l1 |= ((p_bit & 0x1) << SECTION_P_SHIFT); return 0; } /** \brief Set section access privileges The function sets section access privileges \param [out] descriptor_l1 L1 descriptor. \param [in] user User Level Access: NO_ACCESS, RW, READ \param [in] priv Privilege Level Access: NO_ACCESS, RW, READ \param [in] afe Access flag enable \return 0 */ __STATIC_INLINE int __ap_section(uint32_t *descriptor_l1, mmu_access_Type user, mmu_access_Type priv, uint32_t afe) { uint32_t ap = 0; if (afe == 0) { //full access if ((priv == NO_ACCESS) && (user == NO_ACCESS)) { ap = 0x0; } else if ((priv == RW) && (user == NO_ACCESS)) { ap = 0x1; } else if ((priv == RW) && (user == READ)) { ap = 0x2; } else if ((priv == RW) && (user == RW)) { ap = 0x3; } else if ((priv == READ) && (user == NO_ACCESS)) { ap = 0x5; } else if ((priv == READ) && (user == READ)) { ap = 0x6; } } else { //Simplified access if ((priv == RW) && (user == NO_ACCESS)) { ap = 0x1; } else if ((priv == RW) && (user == RW)) { ap = 0x3; } else if ((priv == READ) && (user == NO_ACCESS)) { ap = 0x5; } else if ((priv == READ) && (user == READ)) { ap = 0x7; } } *descriptor_l1 &= SECTION_AP_MASK; *descriptor_l1 |= (ap & 0x3) << SECTION_AP_SHIFT; *descriptor_l1 |= ((ap & 0x4)>>2) << SECTION_AP2_SHIFT; return 0; } /** \brief Set section shareability The function sets section shareability \param [out] descriptor_l1 L1 descriptor. \param [in] s_bit Section shareability: NON_SHARED, SHARED \return 0 */ __STATIC_INLINE int __shared_section(uint32_t *descriptor_l1, mmu_shared_Type s_bit) { *descriptor_l1 &= SECTION_S_MASK; *descriptor_l1 |= ((s_bit & 0x1) << SECTION_S_SHIFT); return 0; } /** \brief Set section Global attribute The function sets section Global attribute \param [out] descriptor_l1 L1 descriptor. \param [in] g_bit Section attribute: GLOBAL, NON_GLOBAL \return 0 */ __STATIC_INLINE int __global_section(uint32_t *descriptor_l1, mmu_global_Type g_bit) { *descriptor_l1 &= SECTION_NG_MASK; *descriptor_l1 |= ((g_bit & 0x1) << SECTION_NG_SHIFT); return 0; } /** \brief Set section Security attribute The function sets section Global attribute \param [out] descriptor_l1 L1 descriptor. \param [in] s_bit Section Security attribute: SECURE, NON_SECURE \return 0 */ __STATIC_INLINE int __secure_section(uint32_t *descriptor_l1, mmu_secure_Type s_bit) { *descriptor_l1 &= SECTION_NS_MASK; *descriptor_l1 |= ((s_bit & 0x1) << SECTION_NS_SHIFT); return 0; } /* Page 4k or 64k */ /** \brief Set 4k/64k page execution-never attribute The function sets 4k/64k page execution-never attribute \param [out] descriptor_l2 L2 descriptor. \param [in] xn Page execution-never attribute : EXECUTE , NON_EXECUTE. \param [in] page Page size: PAGE_4k, PAGE_64k, \return 0 */ __STATIC_INLINE int __xn_page(uint32_t *descriptor_l2, mmu_execute_Type xn, mmu_region_size_Type page) { if (page == PAGE_4k) { *descriptor_l2 &= PAGE_XN_4K_MASK; *descriptor_l2 |= ((xn & 0x1) << PAGE_XN_4K_SHIFT); } else { *descriptor_l2 &= PAGE_XN_64K_MASK; *descriptor_l2 |= ((xn & 0x1) << PAGE_XN_64K_SHIFT); } return 0; } /** \brief Set 4k/64k page domain The function sets 4k/64k page domain \param [out] descriptor_l1 L1 descriptor. \param [in] domain Page domain \return 0 */ __STATIC_INLINE int __domain_page(uint32_t *descriptor_l1, uint8_t domain) { *descriptor_l1 &= PAGE_DOMAIN_MASK; *descriptor_l1 |= ((domain & 0xf) << PAGE_DOMAIN_SHIFT); return 0; } /** \brief Set 4k/64k page parity check The function sets 4k/64k page parity check \param [out] descriptor_l1 L1 descriptor. \param [in] p_bit Parity check: ECC_DISABLED, ECC_ENABLED \return 0 */ __STATIC_INLINE int __p_page(uint32_t *descriptor_l1, mmu_ecc_check_Type p_bit) { *descriptor_l1 &= SECTION_P_MASK; *descriptor_l1 |= ((p_bit & 0x1) << SECTION_P_SHIFT); return 0; } /** \brief Set 4k/64k page access privileges The function sets 4k/64k page access privileges \param [out] descriptor_l2 L2 descriptor. \param [in] user User Level Access: NO_ACCESS, RW, READ \param [in] priv Privilege Level Access: NO_ACCESS, RW, READ \param [in] afe Access flag enable \return 0 */ __STATIC_INLINE int __ap_page(uint32_t *descriptor_l2, mmu_access_Type user, mmu_access_Type priv, uint32_t afe) { uint32_t ap = 0; if (afe == 0) { //full access if ((priv == NO_ACCESS) && (user == NO_ACCESS)) { ap = 0x0; } else if ((priv == RW) && (user == NO_ACCESS)) { ap = 0x1; } else if ((priv == RW) && (user == READ)) { ap = 0x2; } else if ((priv == RW) && (user == RW)) { ap = 0x3; } else if ((priv == READ) && (user == NO_ACCESS)) { ap = 0x5; } else if ((priv == READ) && (user == READ)) { ap = 0x6; } } else { //Simplified access if ((priv == RW) && (user == NO_ACCESS)) { ap = 0x1; } else if ((priv == RW) && (user == RW)) { ap = 0x3; } else if ((priv == READ) && (user == NO_ACCESS)) { ap = 0x5; } else if ((priv == READ) && (user == READ)) { ap = 0x7; } } *descriptor_l2 &= PAGE_AP_MASK; *descriptor_l2 |= (ap & 0x3) << PAGE_AP_SHIFT; *descriptor_l2 |= ((ap & 0x4)>>2) << PAGE_AP2_SHIFT; return 0; } /** \brief Set 4k/64k page shareability The function sets 4k/64k page shareability \param [out] descriptor_l2 L2 descriptor. \param [in] s_bit 4k/64k page shareability: NON_SHARED, SHARED \return 0 */ __STATIC_INLINE int __shared_page(uint32_t *descriptor_l2, mmu_shared_Type s_bit) { *descriptor_l2 &= PAGE_S_MASK; *descriptor_l2 |= ((s_bit & 0x1) << PAGE_S_SHIFT); return 0; } /** \brief Set 4k/64k page Global attribute The function sets 4k/64k page Global attribute \param [out] descriptor_l2 L2 descriptor. \param [in] g_bit 4k/64k page attribute: GLOBAL, NON_GLOBAL \return 0 */ __STATIC_INLINE int __global_page(uint32_t *descriptor_l2, mmu_global_Type g_bit) { *descriptor_l2 &= PAGE_NG_MASK; *descriptor_l2 |= ((g_bit & 0x1) << PAGE_NG_SHIFT); return 0; } /** \brief Set 4k/64k page Security attribute The function sets 4k/64k page Global attribute \param [out] descriptor_l1 L1 descriptor. \param [in] s_bit 4k/64k page Security attribute: SECURE, NON_SECURE \return 0 */ __STATIC_INLINE int __secure_page(uint32_t *descriptor_l1, mmu_secure_Type s_bit) { *descriptor_l1 &= PAGE_NS_MASK; *descriptor_l1 |= ((s_bit & 0x1) << PAGE_NS_SHIFT); return 0; } /** \brief Set Section memory attributes The function sets section memory attributes \param [out] descriptor_l1 L1 descriptor. \param [in] mem Section memory type: NORMAL, DEVICE, SHARED_DEVICE, NON_SHARED_DEVICE, STRONGLY_ORDERED \param [in] outer Outer cacheability: NON_CACHEABLE, WB_WA, WT, WB_NO_WA, \param [in] inner Inner cacheability: NON_CACHEABLE, WB_WA, WT, WB_NO_WA, \return 0 */ __STATIC_INLINE int __memory_section(uint32_t *descriptor_l1, mmu_memory_Type mem, mmu_cacheability_Type outer, mmu_cacheability_Type inner) { *descriptor_l1 &= SECTION_TEXCB_MASK; if (STRONGLY_ORDERED == mem) { return 0; } else if (SHARED_DEVICE == mem) { *descriptor_l1 |= (1 << SECTION_B_SHIFT); } else if (NON_SHARED_DEVICE == mem) { *descriptor_l1 |= (1 << SECTION_TEX1_SHIFT); } else if (NORMAL == mem) { *descriptor_l1 |= 1 << SECTION_TEX2_SHIFT; switch(inner) { case NON_CACHEABLE: break; case WB_WA: *descriptor_l1 |= (1 << SECTION_B_SHIFT); break; case WT: *descriptor_l1 |= 1 << SECTION_C_SHIFT; break; case WB_NO_WA: *descriptor_l1 |= (1 << SECTION_B_SHIFT) | (1 << SECTION_C_SHIFT); break; } switch(outer) { case NON_CACHEABLE: break; case WB_WA: *descriptor_l1 |= (1 << SECTION_TEX0_SHIFT); break; case WT: *descriptor_l1 |= 1 << SECTION_TEX1_SHIFT; break; case WB_NO_WA: *descriptor_l1 |= (1 << SECTION_TEX0_SHIFT) | (1 << SECTION_TEX0_SHIFT); break; } } return 0; } /** \brief Set 4k/64k page memory attributes The function sets 4k/64k page memory attributes \param [out] descriptor_l2 L2 descriptor. \param [in] mem 4k/64k page memory type: NORMAL, DEVICE, SHARED_DEVICE, NON_SHARED_DEVICE, STRONGLY_ORDERED \param [in] outer Outer cacheability: NON_CACHEABLE, WB_WA, WT, WB_NO_WA, \param [in] inner Inner cacheability: NON_CACHEABLE, WB_WA, WT, WB_NO_WA, \return 0 */ __STATIC_INLINE int __memory_page(uint32_t *descriptor_l2, mmu_memory_Type mem, mmu_cacheability_Type outer, mmu_cacheability_Type inner, mmu_region_size_Type page) { *descriptor_l2 &= PAGE_4K_TEXCB_MASK; if (page == PAGE_64k) { //same as section __memory_section(descriptor_l2, mem, outer, inner); } else { if (STRONGLY_ORDERED == mem) { return 0; } else if (SHARED_DEVICE == mem) { *descriptor_l2 |= (1 << PAGE_4K_B_SHIFT); } else if (NON_SHARED_DEVICE == mem) { *descriptor_l2 |= (1 << PAGE_4K_TEX1_SHIFT); } else if (NORMAL == mem) { *descriptor_l2 |= 1 << PAGE_4K_TEX2_SHIFT; switch(inner) { case NON_CACHEABLE: break; case WB_WA: *descriptor_l2 |= (1 << PAGE_4K_B_SHIFT); break; case WT: *descriptor_l2 |= 1 << PAGE_4K_C_SHIFT; break; case WB_NO_WA: *descriptor_l2 |= (1 << PAGE_4K_B_SHIFT) | (1 << PAGE_4K_C_SHIFT); break; } switch(outer) { case NON_CACHEABLE: break; case WB_WA: *descriptor_l2 |= (1 << PAGE_4K_TEX0_SHIFT); break; case WT: *descriptor_l2 |= 1 << PAGE_4K_TEX1_SHIFT; break; case WB_NO_WA: *descriptor_l2 |= (1 << PAGE_4K_TEX0_SHIFT) | (1 << PAGE_4K_TEX0_SHIFT); break; } } } return 0; } /** \brief Create a L1 section descriptor The function creates a section descriptor. Assumptions: - 16MB super sections not suported - TEX remap disabled, so memory type and attributes are described directly by bits in the descriptor - Functions always return 0 \param [out] descriptor L1 descriptor \param [out] descriptor2 L2 descriptor \param [in] reg Section attributes \return 0 */ __STATIC_INLINE int __get_section_descriptor(uint32_t *descriptor, mmu_region_attributes_Type reg) { *descriptor = 0; __memory_section(descriptor, reg.mem_t, reg.outer_norm_t, reg.inner_norm_t); __xn_section(descriptor,reg.xn_t); __domain_section(descriptor, reg.domain); __p_section(descriptor, reg.e_t); __ap_section(descriptor, reg.priv_t, reg.user_t, 1); __shared_section(descriptor,reg.sh_t); __global_section(descriptor,reg.g_t); __secure_section(descriptor,reg.sec_t); *descriptor &= SECTION_MASK; *descriptor |= SECTION_DESCRIPTOR; return 0; } /** \brief Create a L1 and L2 4k/64k page descriptor The function creates a 4k/64k page descriptor. Assumptions: - TEX remap disabled, so memory type and attributes are described directly by bits in the descriptor - Functions always return 0 \param [out] descriptor L1 descriptor \param [out] descriptor2 L2 descriptor \param [in] reg 4k/64k page attributes \return 0 */ __STATIC_INLINE int __get_page_descriptor(uint32_t *descriptor, uint32_t *descriptor2, mmu_region_attributes_Type reg) { *descriptor = 0; *descriptor2 = 0; switch (reg.rg_t) { case PAGE_4k: __memory_page(descriptor2, reg.mem_t, reg.outer_norm_t, reg.inner_norm_t, PAGE_4k); __xn_page(descriptor2, reg.xn_t, PAGE_4k); __domain_page(descriptor, reg.domain); __p_page(descriptor, reg.e_t); __ap_page(descriptor2, reg.priv_t, reg.user_t, 1); __shared_page(descriptor2,reg.sh_t); __global_page(descriptor2,reg.g_t); __secure_page(descriptor,reg.sec_t); *descriptor &= PAGE_L1_MASK; *descriptor |= PAGE_L1_DESCRIPTOR; *descriptor2 &= PAGE_L2_4K_MASK; *descriptor2 |= PAGE_L2_4K_DESC; break; case PAGE_64k: __memory_page(descriptor2, reg.mem_t, reg.outer_norm_t, reg.inner_norm_t, PAGE_64k); __xn_page(descriptor2, reg.xn_t, PAGE_64k); __domain_page(descriptor, reg.domain); __p_page(descriptor, reg.e_t); __ap_page(descriptor2, reg.priv_t, reg.user_t, 1); __shared_page(descriptor2,reg.sh_t); __global_page(descriptor2,reg.g_t); __secure_page(descriptor,reg.sec_t); *descriptor &= PAGE_L1_MASK; *descriptor |= PAGE_L1_DESCRIPTOR; *descriptor2 &= PAGE_L2_64K_MASK; *descriptor2 |= PAGE_L2_64K_DESC; break; case SECTION: //error break; } return 0; } /** \brief Create a 1MB Section \param [in] ttb Translation table base address \param [in] base_address Section base address \param [in] count Number of sections to create \param [in] descriptor_l1 L1 descriptor (region attributes) */ __STATIC_INLINE void __TTSection(uint32_t *ttb, uint32_t base_address, uint32_t count, uint32_t descriptor_l1) { uint32_t offset; uint32_t entry; uint32_t i; offset = base_address >> 20; entry = (base_address & 0xFFF00000) | descriptor_l1; //4 bytes aligned ttb = ttb + offset; for (i = 0; i < count; i++ ) { //4 bytes aligned *ttb++ = entry; entry += OFFSET_1M; } } /** \brief Create a 4k page entry \param [in] ttb L1 table base address \param [in] base_address 4k base address \param [in] count Number of 4k pages to create \param [in] descriptor_l1 L1 descriptor (region attributes) \param [in] ttb_l2 L2 table base address \param [in] descriptor_l2 L2 descriptor (region attributes) */ __STATIC_INLINE void __TTPage_4k(uint32_t *ttb, uint32_t base_address, uint32_t count, uint32_t descriptor_l1, uint32_t *ttb_l2, uint32_t descriptor_l2 ) { uint32_t offset, offset2; uint32_t entry, entry2; uint32_t i; offset = base_address >> 20; entry = ((int)ttb_l2 & 0xFFFFFC00) | descriptor_l1; //4 bytes aligned ttb += offset; //create l1_entry *ttb = entry; offset2 = (base_address & 0xff000) >> 12; ttb_l2 += offset2; entry2 = (base_address & 0xFFFFF000) | descriptor_l2; for (i = 0; i < count; i++ ) { //4 bytes aligned *ttb_l2++ = entry2; entry2 += OFFSET_4K; } } /** \brief Create a 64k page entry \param [in] ttb L1 table base address \param [in] base_address 64k base address \param [in] count Number of 64k pages to create \param [in] descriptor_l1 L1 descriptor (region attributes) \param [in] ttb_l2 L2 table base address \param [in] descriptor_l2 L2 descriptor (region attributes) */ __STATIC_INLINE void __TTPage_64k(uint32_t *ttb, uint32_t base_address, uint32_t count, uint32_t descriptor_l1, uint32_t *ttb_l2, uint32_t descriptor_l2 ) { uint32_t offset, offset2; uint32_t entry, entry2; uint32_t i,j; offset = base_address >> 20; entry = ((int)ttb_l2 & 0xFFFFFC00) | descriptor_l1; //4 bytes aligned ttb += offset; //create l1_entry *ttb = entry; offset2 = (base_address & 0xff000) >> 12; ttb_l2 += offset2; entry2 = (base_address & 0xFFFF0000) | descriptor_l2; for (i = 0; i < count; i++ ) { //create 16 entries for (j = 0; j < 16; j++) //4 bytes aligned *ttb_l2++ = entry2; entry2 += OFFSET_64K; } } /*@} end of MMU_Functions */ #endif #ifdef __cplusplus } #endif ================================================ FILE: Zelig/mbed/TARGET_K64F/core_cm0.h ================================================ /**************************************************************************//** * @file core_cm0.h * @brief CMSIS Cortex-M0 Core Peripheral Access Layer Header File * @version V3.20 * @date 25. February 2013 * * @note * ******************************************************************************/ /* Copyright (c) 2009 - 2013 ARM LIMITED All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: - Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. - Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. - Neither the name of ARM 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 COPYRIGHT HOLDERS AND 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. ---------------------------------------------------------------------------*/ #if defined ( __ICCARM__ ) #pragma system_include /* treat file as system include file for MISRA check */ #endif #ifdef __cplusplus extern "C" { #endif #ifndef __CORE_CM0_H_GENERIC #define __CORE_CM0_H_GENERIC /** \page CMSIS_MISRA_Exceptions MISRA-C:2004 Compliance Exceptions CMSIS violates the following MISRA-C:2004 rules: \li Required Rule 8.5, object/function definition in header file.
Function definitions in header files are used to allow 'inlining'. \li Required Rule 18.4, declaration of union type or object of union type: '{...}'.
Unions are used for effective representation of core registers. \li Advisory Rule 19.7, Function-like macro defined.
Function-like macros are used to allow more efficient code. */ /******************************************************************************* * CMSIS definitions ******************************************************************************/ /** \ingroup Cortex_M0 @{ */ /* CMSIS CM0 definitions */ #define __CM0_CMSIS_VERSION_MAIN (0x03) /*!< [31:16] CMSIS HAL main version */ #define __CM0_CMSIS_VERSION_SUB (0x20) /*!< [15:0] CMSIS HAL sub version */ #define __CM0_CMSIS_VERSION ((__CM0_CMSIS_VERSION_MAIN << 16) | \ __CM0_CMSIS_VERSION_SUB ) /*!< CMSIS HAL version number */ #define __CORTEX_M (0x00) /*!< Cortex-M Core */ #if defined ( __CC_ARM ) #define __ASM __asm /*!< asm keyword for ARM Compiler */ #define __INLINE __inline /*!< inline keyword for ARM Compiler */ #define __STATIC_INLINE static __inline #elif defined ( __ICCARM__ ) #define __ASM __asm /*!< asm keyword for IAR Compiler */ #define __INLINE inline /*!< inline keyword for IAR Compiler. Only available in High optimization mode! */ #define __STATIC_INLINE static inline #elif defined ( __GNUC__ ) #define __ASM __asm /*!< asm keyword for GNU Compiler */ #define __INLINE inline /*!< inline keyword for GNU Compiler */ #define __STATIC_INLINE static inline #elif defined ( __TASKING__ ) #define __ASM __asm /*!< asm keyword for TASKING Compiler */ #define __INLINE inline /*!< inline keyword for TASKING Compiler */ #define __STATIC_INLINE static inline #endif /** __FPU_USED indicates whether an FPU is used or not. This core does not support an FPU at all */ #define __FPU_USED 0 #if defined ( __CC_ARM ) #if defined __TARGET_FPU_VFP #warning "Compiler generates FPU instructions for a device without an FPU (check __FPU_PRESENT)" #endif #elif defined ( __ICCARM__ ) #if defined __ARMVFP__ #warning "Compiler generates FPU instructions for a device without an FPU (check __FPU_PRESENT)" #endif #elif defined ( __GNUC__ ) #if defined (__VFP_FP__) && !defined(__SOFTFP__) #warning "Compiler generates FPU instructions for a device without an FPU (check __FPU_PRESENT)" #endif #elif defined ( __TASKING__ ) #if defined __FPU_VFP__ #error "Compiler generates FPU instructions for a device without an FPU (check __FPU_PRESENT)" #endif #endif #include /* standard types definitions */ #include /* Core Instruction Access */ #include /* Core Function Access */ #endif /* __CORE_CM0_H_GENERIC */ #ifndef __CMSIS_GENERIC #ifndef __CORE_CM0_H_DEPENDANT #define __CORE_CM0_H_DEPENDANT /* check device defines and use defaults */ #if defined __CHECK_DEVICE_DEFINES #ifndef __CM0_REV #define __CM0_REV 0x0000 #warning "__CM0_REV not defined in device header file; using default!" #endif #ifndef __NVIC_PRIO_BITS #define __NVIC_PRIO_BITS 2 #warning "__NVIC_PRIO_BITS not defined in device header file; using default!" #endif #ifndef __Vendor_SysTickConfig #define __Vendor_SysTickConfig 0 #warning "__Vendor_SysTickConfig not defined in device header file; using default!" #endif #endif /* IO definitions (access restrictions to peripheral registers) */ /** \defgroup CMSIS_glob_defs CMSIS Global Defines IO Type Qualifiers are used \li to specify the access to peripheral variables. \li for automatic generation of peripheral register debug information. */ #ifdef __cplusplus #define __I volatile /*!< Defines 'read only' permissions */ #else #define __I volatile const /*!< Defines 'read only' permissions */ #endif #define __O volatile /*!< Defines 'write only' permissions */ #define __IO volatile /*!< Defines 'read / write' permissions */ /*@} end of group Cortex_M0 */ /******************************************************************************* * Register Abstraction Core Register contain: - Core Register - Core NVIC Register - Core SCB Register - Core SysTick Register ******************************************************************************/ /** \defgroup CMSIS_core_register Defines and Type Definitions \brief Type definitions and defines for Cortex-M processor based devices. */ /** \ingroup CMSIS_core_register \defgroup CMSIS_CORE Status and Control Registers \brief Core Register type definitions. @{ */ /** \brief Union type to access the Application Program Status Register (APSR). */ typedef union { struct { #if (__CORTEX_M != 0x04) uint32_t _reserved0:27; /*!< bit: 0..26 Reserved */ #else uint32_t _reserved0:16; /*!< bit: 0..15 Reserved */ uint32_t GE:4; /*!< bit: 16..19 Greater than or Equal flags */ uint32_t _reserved1:7; /*!< bit: 20..26 Reserved */ #endif uint32_t Q:1; /*!< bit: 27 Saturation condition flag */ uint32_t V:1; /*!< bit: 28 Overflow condition code flag */ uint32_t C:1; /*!< bit: 29 Carry condition code flag */ uint32_t Z:1; /*!< bit: 30 Zero condition code flag */ uint32_t N:1; /*!< bit: 31 Negative condition code flag */ } b; /*!< Structure used for bit access */ uint32_t w; /*!< Type used for word access */ } APSR_Type; /** \brief Union type to access the Interrupt Program Status Register (IPSR). */ typedef union { struct { uint32_t ISR:9; /*!< bit: 0.. 8 Exception number */ uint32_t _reserved0:23; /*!< bit: 9..31 Reserved */ } b; /*!< Structure used for bit access */ uint32_t w; /*!< Type used for word access */ } IPSR_Type; /** \brief Union type to access the Special-Purpose Program Status Registers (xPSR). */ typedef union { struct { uint32_t ISR:9; /*!< bit: 0.. 8 Exception number */ #if (__CORTEX_M != 0x04) uint32_t _reserved0:15; /*!< bit: 9..23 Reserved */ #else uint32_t _reserved0:7; /*!< bit: 9..15 Reserved */ uint32_t GE:4; /*!< bit: 16..19 Greater than or Equal flags */ uint32_t _reserved1:4; /*!< bit: 20..23 Reserved */ #endif uint32_t T:1; /*!< bit: 24 Thumb bit (read 0) */ uint32_t IT:2; /*!< bit: 25..26 saved IT state (read 0) */ uint32_t Q:1; /*!< bit: 27 Saturation condition flag */ uint32_t V:1; /*!< bit: 28 Overflow condition code flag */ uint32_t C:1; /*!< bit: 29 Carry condition code flag */ uint32_t Z:1; /*!< bit: 30 Zero condition code flag */ uint32_t N:1; /*!< bit: 31 Negative condition code flag */ } b; /*!< Structure used for bit access */ uint32_t w; /*!< Type used for word access */ } xPSR_Type; /** \brief Union type to access the Control Registers (CONTROL). */ typedef union { struct { uint32_t nPRIV:1; /*!< bit: 0 Execution privilege in Thread mode */ uint32_t SPSEL:1; /*!< bit: 1 Stack to be used */ uint32_t FPCA:1; /*!< bit: 2 FP extension active flag */ uint32_t _reserved0:29; /*!< bit: 3..31 Reserved */ } b; /*!< Structure used for bit access */ uint32_t w; /*!< Type used for word access */ } CONTROL_Type; /*@} end of group CMSIS_CORE */ /** \ingroup CMSIS_core_register \defgroup CMSIS_NVIC Nested Vectored Interrupt Controller (NVIC) \brief Type definitions for the NVIC Registers @{ */ /** \brief Structure type to access the Nested Vectored Interrupt Controller (NVIC). */ typedef struct { __IO uint32_t ISER[1]; /*!< Offset: 0x000 (R/W) Interrupt Set Enable Register */ uint32_t RESERVED0[31]; __IO uint32_t ICER[1]; /*!< Offset: 0x080 (R/W) Interrupt Clear Enable Register */ uint32_t RSERVED1[31]; __IO uint32_t ISPR[1]; /*!< Offset: 0x100 (R/W) Interrupt Set Pending Register */ uint32_t RESERVED2[31]; __IO uint32_t ICPR[1]; /*!< Offset: 0x180 (R/W) Interrupt Clear Pending Register */ uint32_t RESERVED3[31]; uint32_t RESERVED4[64]; __IO uint32_t IP[8]; /*!< Offset: 0x300 (R/W) Interrupt Priority Register */ } NVIC_Type; /*@} end of group CMSIS_NVIC */ /** \ingroup CMSIS_core_register \defgroup CMSIS_SCB System Control Block (SCB) \brief Type definitions for the System Control Block Registers @{ */ /** \brief Structure type to access the System Control Block (SCB). */ typedef struct { __I uint32_t CPUID; /*!< Offset: 0x000 (R/ ) CPUID Base Register */ __IO uint32_t ICSR; /*!< Offset: 0x004 (R/W) Interrupt Control and State Register */ uint32_t RESERVED0; __IO uint32_t AIRCR; /*!< Offset: 0x00C (R/W) Application Interrupt and Reset Control Register */ __IO uint32_t SCR; /*!< Offset: 0x010 (R/W) System Control Register */ __IO uint32_t CCR; /*!< Offset: 0x014 (R/W) Configuration Control Register */ uint32_t RESERVED1; __IO uint32_t SHP[2]; /*!< Offset: 0x01C (R/W) System Handlers Priority Registers. [0] is RESERVED */ __IO uint32_t SHCSR; /*!< Offset: 0x024 (R/W) System Handler Control and State Register */ } SCB_Type; /* SCB CPUID Register Definitions */ #define SCB_CPUID_IMPLEMENTER_Pos 24 /*!< SCB CPUID: IMPLEMENTER Position */ #define SCB_CPUID_IMPLEMENTER_Msk (0xFFUL << SCB_CPUID_IMPLEMENTER_Pos) /*!< SCB CPUID: IMPLEMENTER Mask */ #define SCB_CPUID_VARIANT_Pos 20 /*!< SCB CPUID: VARIANT Position */ #define SCB_CPUID_VARIANT_Msk (0xFUL << SCB_CPUID_VARIANT_Pos) /*!< SCB CPUID: VARIANT Mask */ #define SCB_CPUID_ARCHITECTURE_Pos 16 /*!< SCB CPUID: ARCHITECTURE Position */ #define SCB_CPUID_ARCHITECTURE_Msk (0xFUL << SCB_CPUID_ARCHITECTURE_Pos) /*!< SCB CPUID: ARCHITECTURE Mask */ #define SCB_CPUID_PARTNO_Pos 4 /*!< SCB CPUID: PARTNO Position */ #define SCB_CPUID_PARTNO_Msk (0xFFFUL << SCB_CPUID_PARTNO_Pos) /*!< SCB CPUID: PARTNO Mask */ #define SCB_CPUID_REVISION_Pos 0 /*!< SCB CPUID: REVISION Position */ #define SCB_CPUID_REVISION_Msk (0xFUL << SCB_CPUID_REVISION_Pos) /*!< SCB CPUID: REVISION Mask */ /* SCB Interrupt Control State Register Definitions */ #define SCB_ICSR_NMIPENDSET_Pos 31 /*!< SCB ICSR: NMIPENDSET Position */ #define SCB_ICSR_NMIPENDSET_Msk (1UL << SCB_ICSR_NMIPENDSET_Pos) /*!< SCB ICSR: NMIPENDSET Mask */ #define SCB_ICSR_PENDSVSET_Pos 28 /*!< SCB ICSR: PENDSVSET Position */ #define SCB_ICSR_PENDSVSET_Msk (1UL << SCB_ICSR_PENDSVSET_Pos) /*!< SCB ICSR: PENDSVSET Mask */ #define SCB_ICSR_PENDSVCLR_Pos 27 /*!< SCB ICSR: PENDSVCLR Position */ #define SCB_ICSR_PENDSVCLR_Msk (1UL << SCB_ICSR_PENDSVCLR_Pos) /*!< SCB ICSR: PENDSVCLR Mask */ #define SCB_ICSR_PENDSTSET_Pos 26 /*!< SCB ICSR: PENDSTSET Position */ #define SCB_ICSR_PENDSTSET_Msk (1UL << SCB_ICSR_PENDSTSET_Pos) /*!< SCB ICSR: PENDSTSET Mask */ #define SCB_ICSR_PENDSTCLR_Pos 25 /*!< SCB ICSR: PENDSTCLR Position */ #define SCB_ICSR_PENDSTCLR_Msk (1UL << SCB_ICSR_PENDSTCLR_Pos) /*!< SCB ICSR: PENDSTCLR Mask */ #define SCB_ICSR_ISRPREEMPT_Pos 23 /*!< SCB ICSR: ISRPREEMPT Position */ #define SCB_ICSR_ISRPREEMPT_Msk (1UL << SCB_ICSR_ISRPREEMPT_Pos) /*!< SCB ICSR: ISRPREEMPT Mask */ #define SCB_ICSR_ISRPENDING_Pos 22 /*!< SCB ICSR: ISRPENDING Position */ #define SCB_ICSR_ISRPENDING_Msk (1UL << SCB_ICSR_ISRPENDING_Pos) /*!< SCB ICSR: ISRPENDING Mask */ #define SCB_ICSR_VECTPENDING_Pos 12 /*!< SCB ICSR: VECTPENDING Position */ #define SCB_ICSR_VECTPENDING_Msk (0x1FFUL << SCB_ICSR_VECTPENDING_Pos) /*!< SCB ICSR: VECTPENDING Mask */ #define SCB_ICSR_VECTACTIVE_Pos 0 /*!< SCB ICSR: VECTACTIVE Position */ #define SCB_ICSR_VECTACTIVE_Msk (0x1FFUL << SCB_ICSR_VECTACTIVE_Pos) /*!< SCB ICSR: VECTACTIVE Mask */ /* SCB Application Interrupt and Reset Control Register Definitions */ #define SCB_AIRCR_VECTKEY_Pos 16 /*!< SCB AIRCR: VECTKEY Position */ #define SCB_AIRCR_VECTKEY_Msk (0xFFFFUL << SCB_AIRCR_VECTKEY_Pos) /*!< SCB AIRCR: VECTKEY Mask */ #define SCB_AIRCR_VECTKEYSTAT_Pos 16 /*!< SCB AIRCR: VECTKEYSTAT Position */ #define SCB_AIRCR_VECTKEYSTAT_Msk (0xFFFFUL << SCB_AIRCR_VECTKEYSTAT_Pos) /*!< SCB AIRCR: VECTKEYSTAT Mask */ #define SCB_AIRCR_ENDIANESS_Pos 15 /*!< SCB AIRCR: ENDIANESS Position */ #define SCB_AIRCR_ENDIANESS_Msk (1UL << SCB_AIRCR_ENDIANESS_Pos) /*!< SCB AIRCR: ENDIANESS Mask */ #define SCB_AIRCR_SYSRESETREQ_Pos 2 /*!< SCB AIRCR: SYSRESETREQ Position */ #define SCB_AIRCR_SYSRESETREQ_Msk (1UL << SCB_AIRCR_SYSRESETREQ_Pos) /*!< SCB AIRCR: SYSRESETREQ Mask */ #define SCB_AIRCR_VECTCLRACTIVE_Pos 1 /*!< SCB AIRCR: VECTCLRACTIVE Position */ #define SCB_AIRCR_VECTCLRACTIVE_Msk (1UL << SCB_AIRCR_VECTCLRACTIVE_Pos) /*!< SCB AIRCR: VECTCLRACTIVE Mask */ /* SCB System Control Register Definitions */ #define SCB_SCR_SEVONPEND_Pos 4 /*!< SCB SCR: SEVONPEND Position */ #define SCB_SCR_SEVONPEND_Msk (1UL << SCB_SCR_SEVONPEND_Pos) /*!< SCB SCR: SEVONPEND Mask */ #define SCB_SCR_SLEEPDEEP_Pos 2 /*!< SCB SCR: SLEEPDEEP Position */ #define SCB_SCR_SLEEPDEEP_Msk (1UL << SCB_SCR_SLEEPDEEP_Pos) /*!< SCB SCR: SLEEPDEEP Mask */ #define SCB_SCR_SLEEPONEXIT_Pos 1 /*!< SCB SCR: SLEEPONEXIT Position */ #define SCB_SCR_SLEEPONEXIT_Msk (1UL << SCB_SCR_SLEEPONEXIT_Pos) /*!< SCB SCR: SLEEPONEXIT Mask */ /* SCB Configuration Control Register Definitions */ #define SCB_CCR_STKALIGN_Pos 9 /*!< SCB CCR: STKALIGN Position */ #define SCB_CCR_STKALIGN_Msk (1UL << SCB_CCR_STKALIGN_Pos) /*!< SCB CCR: STKALIGN Mask */ #define SCB_CCR_UNALIGN_TRP_Pos 3 /*!< SCB CCR: UNALIGN_TRP Position */ #define SCB_CCR_UNALIGN_TRP_Msk (1UL << SCB_CCR_UNALIGN_TRP_Pos) /*!< SCB CCR: UNALIGN_TRP Mask */ /* SCB System Handler Control and State Register Definitions */ #define SCB_SHCSR_SVCALLPENDED_Pos 15 /*!< SCB SHCSR: SVCALLPENDED Position */ #define SCB_SHCSR_SVCALLPENDED_Msk (1UL << SCB_SHCSR_SVCALLPENDED_Pos) /*!< SCB SHCSR: SVCALLPENDED Mask */ /*@} end of group CMSIS_SCB */ /** \ingroup CMSIS_core_register \defgroup CMSIS_SysTick System Tick Timer (SysTick) \brief Type definitions for the System Timer Registers. @{ */ /** \brief Structure type to access the System Timer (SysTick). */ typedef struct { __IO uint32_t CTRL; /*!< Offset: 0x000 (R/W) SysTick Control and Status Register */ __IO uint32_t LOAD; /*!< Offset: 0x004 (R/W) SysTick Reload Value Register */ __IO uint32_t VAL; /*!< Offset: 0x008 (R/W) SysTick Current Value Register */ __I uint32_t CALIB; /*!< Offset: 0x00C (R/ ) SysTick Calibration Register */ } SysTick_Type; /* SysTick Control / Status Register Definitions */ #define SysTick_CTRL_COUNTFLAG_Pos 16 /*!< SysTick CTRL: COUNTFLAG Position */ #define SysTick_CTRL_COUNTFLAG_Msk (1UL << SysTick_CTRL_COUNTFLAG_Pos) /*!< SysTick CTRL: COUNTFLAG Mask */ #define SysTick_CTRL_CLKSOURCE_Pos 2 /*!< SysTick CTRL: CLKSOURCE Position */ #define SysTick_CTRL_CLKSOURCE_Msk (1UL << SysTick_CTRL_CLKSOURCE_Pos) /*!< SysTick CTRL: CLKSOURCE Mask */ #define SysTick_CTRL_TICKINT_Pos 1 /*!< SysTick CTRL: TICKINT Position */ #define SysTick_CTRL_TICKINT_Msk (1UL << SysTick_CTRL_TICKINT_Pos) /*!< SysTick CTRL: TICKINT Mask */ #define SysTick_CTRL_ENABLE_Pos 0 /*!< SysTick CTRL: ENABLE Position */ #define SysTick_CTRL_ENABLE_Msk (1UL << SysTick_CTRL_ENABLE_Pos) /*!< SysTick CTRL: ENABLE Mask */ /* SysTick Reload Register Definitions */ #define SysTick_LOAD_RELOAD_Pos 0 /*!< SysTick LOAD: RELOAD Position */ #define SysTick_LOAD_RELOAD_Msk (0xFFFFFFUL << SysTick_LOAD_RELOAD_Pos) /*!< SysTick LOAD: RELOAD Mask */ /* SysTick Current Register Definitions */ #define SysTick_VAL_CURRENT_Pos 0 /*!< SysTick VAL: CURRENT Position */ #define SysTick_VAL_CURRENT_Msk (0xFFFFFFUL << SysTick_VAL_CURRENT_Pos) /*!< SysTick VAL: CURRENT Mask */ /* SysTick Calibration Register Definitions */ #define SysTick_CALIB_NOREF_Pos 31 /*!< SysTick CALIB: NOREF Position */ #define SysTick_CALIB_NOREF_Msk (1UL << SysTick_CALIB_NOREF_Pos) /*!< SysTick CALIB: NOREF Mask */ #define SysTick_CALIB_SKEW_Pos 30 /*!< SysTick CALIB: SKEW Position */ #define SysTick_CALIB_SKEW_Msk (1UL << SysTick_CALIB_SKEW_Pos) /*!< SysTick CALIB: SKEW Mask */ #define SysTick_CALIB_TENMS_Pos 0 /*!< SysTick CALIB: TENMS Position */ #define SysTick_CALIB_TENMS_Msk (0xFFFFFFUL << SysTick_VAL_CURRENT_Pos) /*!< SysTick CALIB: TENMS Mask */ /*@} end of group CMSIS_SysTick */ /** \ingroup CMSIS_core_register \defgroup CMSIS_CoreDebug Core Debug Registers (CoreDebug) \brief Cortex-M0 Core Debug Registers (DCB registers, SHCSR, and DFSR) are only accessible over DAP and not via processor. Therefore they are not covered by the Cortex-M0 header file. @{ */ /*@} end of group CMSIS_CoreDebug */ /** \ingroup CMSIS_core_register \defgroup CMSIS_core_base Core Definitions \brief Definitions for base addresses, unions, and structures. @{ */ /* Memory mapping of Cortex-M0 Hardware */ #define SCS_BASE (0xE000E000UL) /*!< System Control Space Base Address */ #define SysTick_BASE (SCS_BASE + 0x0010UL) /*!< SysTick Base Address */ #define NVIC_BASE (SCS_BASE + 0x0100UL) /*!< NVIC Base Address */ #define SCB_BASE (SCS_BASE + 0x0D00UL) /*!< System Control Block Base Address */ #define SCB ((SCB_Type *) SCB_BASE ) /*!< SCB configuration struct */ #define SysTick ((SysTick_Type *) SysTick_BASE ) /*!< SysTick configuration struct */ #define NVIC ((NVIC_Type *) NVIC_BASE ) /*!< NVIC configuration struct */ /*@} */ /******************************************************************************* * Hardware Abstraction Layer Core Function Interface contains: - Core NVIC Functions - Core SysTick Functions - Core Register Access Functions ******************************************************************************/ /** \defgroup CMSIS_Core_FunctionInterface Functions and Instructions Reference */ /* ########################## NVIC functions #################################### */ /** \ingroup CMSIS_Core_FunctionInterface \defgroup CMSIS_Core_NVICFunctions NVIC Functions \brief Functions that manage interrupts and exceptions via the NVIC. @{ */ /* Interrupt Priorities are WORD accessible only under ARMv6M */ /* The following MACROS handle generation of the register offset and byte masks */ #define _BIT_SHIFT(IRQn) ( (((uint32_t)(IRQn) ) & 0x03) * 8 ) #define _SHP_IDX(IRQn) ( ((((uint32_t)(IRQn) & 0x0F)-8) >> 2) ) #define _IP_IDX(IRQn) ( ((uint32_t)(IRQn) >> 2) ) /** \brief Enable External Interrupt The function enables a device-specific interrupt in the NVIC interrupt controller. \param [in] IRQn External interrupt number. Value cannot be negative. */ __STATIC_INLINE void NVIC_EnableIRQ(IRQn_Type IRQn) { NVIC->ISER[0] = (1 << ((uint32_t)(IRQn) & 0x1F)); } /** \brief Disable External Interrupt The function disables a device-specific interrupt in the NVIC interrupt controller. \param [in] IRQn External interrupt number. Value cannot be negative. */ __STATIC_INLINE void NVIC_DisableIRQ(IRQn_Type IRQn) { NVIC->ICER[0] = (1 << ((uint32_t)(IRQn) & 0x1F)); } /** \brief Get Pending Interrupt The function reads the pending register in the NVIC and returns the pending bit for the specified interrupt. \param [in] IRQn Interrupt number. \return 0 Interrupt status is not pending. \return 1 Interrupt status is pending. */ __STATIC_INLINE uint32_t NVIC_GetPendingIRQ(IRQn_Type IRQn) { return((uint32_t) ((NVIC->ISPR[0] & (1 << ((uint32_t)(IRQn) & 0x1F)))?1:0)); } /** \brief Set Pending Interrupt The function sets the pending bit of an external interrupt. \param [in] IRQn Interrupt number. Value cannot be negative. */ __STATIC_INLINE void NVIC_SetPendingIRQ(IRQn_Type IRQn) { NVIC->ISPR[0] = (1 << ((uint32_t)(IRQn) & 0x1F)); } /** \brief Clear Pending Interrupt The function clears the pending bit of an external interrupt. \param [in] IRQn External interrupt number. Value cannot be negative. */ __STATIC_INLINE void NVIC_ClearPendingIRQ(IRQn_Type IRQn) { NVIC->ICPR[0] = (1 << ((uint32_t)(IRQn) & 0x1F)); /* Clear pending interrupt */ } /** \brief Set Interrupt Priority The function sets the priority of an interrupt. \note The priority cannot be set for every core interrupt. \param [in] IRQn Interrupt number. \param [in] priority Priority to set. */ __STATIC_INLINE void NVIC_SetPriority(IRQn_Type IRQn, uint32_t priority) { if(IRQn < 0) { SCB->SHP[_SHP_IDX(IRQn)] = (SCB->SHP[_SHP_IDX(IRQn)] & ~(0xFF << _BIT_SHIFT(IRQn))) | (((priority << (8 - __NVIC_PRIO_BITS)) & 0xFF) << _BIT_SHIFT(IRQn)); } else { NVIC->IP[_IP_IDX(IRQn)] = (NVIC->IP[_IP_IDX(IRQn)] & ~(0xFF << _BIT_SHIFT(IRQn))) | (((priority << (8 - __NVIC_PRIO_BITS)) & 0xFF) << _BIT_SHIFT(IRQn)); } } /** \brief Get Interrupt Priority The function reads the priority of an interrupt. The interrupt number can be positive to specify an external (device specific) interrupt, or negative to specify an internal (core) interrupt. \param [in] IRQn Interrupt number. \return Interrupt Priority. Value is aligned automatically to the implemented priority bits of the microcontroller. */ __STATIC_INLINE uint32_t NVIC_GetPriority(IRQn_Type IRQn) { if(IRQn < 0) { return((uint32_t)(((SCB->SHP[_SHP_IDX(IRQn)] >> _BIT_SHIFT(IRQn) ) & 0xFF) >> (8 - __NVIC_PRIO_BITS))); } /* get priority for Cortex-M0 system interrupts */ else { return((uint32_t)(((NVIC->IP[ _IP_IDX(IRQn)] >> _BIT_SHIFT(IRQn) ) & 0xFF) >> (8 - __NVIC_PRIO_BITS))); } /* get priority for device specific interrupts */ } /** \brief System Reset The function initiates a system reset request to reset the MCU. */ __STATIC_INLINE void NVIC_SystemReset(void) { __DSB(); /* Ensure all outstanding memory accesses included buffered write are completed before reset */ SCB->AIRCR = ((0x5FA << SCB_AIRCR_VECTKEY_Pos) | SCB_AIRCR_SYSRESETREQ_Msk); __DSB(); /* Ensure completion of memory access */ while(1); /* wait until reset */ } /*@} end of CMSIS_Core_NVICFunctions */ /* ################################## SysTick function ############################################ */ /** \ingroup CMSIS_Core_FunctionInterface \defgroup CMSIS_Core_SysTickFunctions SysTick Functions \brief Functions that configure the System. @{ */ #if (__Vendor_SysTickConfig == 0) /** \brief System Tick Configuration The function initializes the System Timer and its interrupt, and starts the System Tick Timer. Counter is in free running mode to generate periodic interrupts. \param [in] ticks Number of ticks between two interrupts. \return 0 Function succeeded. \return 1 Function failed. \note When the variable __Vendor_SysTickConfig is set to 1, then the function SysTick_Config is not included. In this case, the file device.h must contain a vendor-specific implementation of this function. */ __STATIC_INLINE uint32_t SysTick_Config(uint32_t ticks) { if ((ticks - 1) > SysTick_LOAD_RELOAD_Msk) return (1); /* Reload value impossible */ SysTick->LOAD = ticks - 1; /* set reload register */ NVIC_SetPriority (SysTick_IRQn, (1<<__NVIC_PRIO_BITS) - 1); /* set Priority for Systick Interrupt */ SysTick->VAL = 0; /* Load the SysTick Counter Value */ SysTick->CTRL = SysTick_CTRL_CLKSOURCE_Msk | SysTick_CTRL_TICKINT_Msk | SysTick_CTRL_ENABLE_Msk; /* Enable SysTick IRQ and SysTick Timer */ return (0); /* Function successful */ } #endif /*@} end of CMSIS_Core_SysTickFunctions */ #endif /* __CORE_CM0_H_DEPENDANT */ #endif /* __CMSIS_GENERIC */ #ifdef __cplusplus } #endif ================================================ FILE: Zelig/mbed/TARGET_K64F/core_cm0plus.h ================================================ /**************************************************************************//** * @file core_cm0plus.h * @brief CMSIS Cortex-M0+ Core Peripheral Access Layer Header File * @version V3.20 * @date 25. February 2013 * * @note * ******************************************************************************/ /* Copyright (c) 2009 - 2013 ARM LIMITED All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: - Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. - Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. - Neither the name of ARM 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 COPYRIGHT HOLDERS AND 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. ---------------------------------------------------------------------------*/ #if defined ( __ICCARM__ ) #pragma system_include /* treat file as system include file for MISRA check */ #endif #ifdef __cplusplus extern "C" { #endif #ifndef __CORE_CM0PLUS_H_GENERIC #define __CORE_CM0PLUS_H_GENERIC /** \page CMSIS_MISRA_Exceptions MISRA-C:2004 Compliance Exceptions CMSIS violates the following MISRA-C:2004 rules: \li Required Rule 8.5, object/function definition in header file.
Function definitions in header files are used to allow 'inlining'. \li Required Rule 18.4, declaration of union type or object of union type: '{...}'.
Unions are used for effective representation of core registers. \li Advisory Rule 19.7, Function-like macro defined.
Function-like macros are used to allow more efficient code. */ /******************************************************************************* * CMSIS definitions ******************************************************************************/ /** \ingroup Cortex-M0+ @{ */ /* CMSIS CM0P definitions */ #define __CM0PLUS_CMSIS_VERSION_MAIN (0x03) /*!< [31:16] CMSIS HAL main version */ #define __CM0PLUS_CMSIS_VERSION_SUB (0x20) /*!< [15:0] CMSIS HAL sub version */ #define __CM0PLUS_CMSIS_VERSION ((__CM0PLUS_CMSIS_VERSION_MAIN << 16) | \ __CM0PLUS_CMSIS_VERSION_SUB) /*!< CMSIS HAL version number */ #define __CORTEX_M (0x00) /*!< Cortex-M Core */ #if defined ( __CC_ARM ) #define __ASM __asm /*!< asm keyword for ARM Compiler */ #define __INLINE __inline /*!< inline keyword for ARM Compiler */ #define __STATIC_INLINE static __inline #elif defined ( __ICCARM__ ) #define __ASM __asm /*!< asm keyword for IAR Compiler */ #define __INLINE inline /*!< inline keyword for IAR Compiler. Only available in High optimization mode! */ #define __STATIC_INLINE static inline #elif defined ( __GNUC__ ) #define __ASM __asm /*!< asm keyword for GNU Compiler */ #define __INLINE inline /*!< inline keyword for GNU Compiler */ #define __STATIC_INLINE static inline #elif defined ( __TASKING__ ) #define __ASM __asm /*!< asm keyword for TASKING Compiler */ #define __INLINE inline /*!< inline keyword for TASKING Compiler */ #define __STATIC_INLINE static inline #endif /** __FPU_USED indicates whether an FPU is used or not. This core does not support an FPU at all */ #define __FPU_USED 0 #if defined ( __CC_ARM ) #if defined __TARGET_FPU_VFP #warning "Compiler generates FPU instructions for a device without an FPU (check __FPU_PRESENT)" #endif #elif defined ( __ICCARM__ ) #if defined __ARMVFP__ #warning "Compiler generates FPU instructions for a device without an FPU (check __FPU_PRESENT)" #endif #elif defined ( __GNUC__ ) #if defined (__VFP_FP__) && !defined(__SOFTFP__) #warning "Compiler generates FPU instructions for a device without an FPU (check __FPU_PRESENT)" #endif #elif defined ( __TASKING__ ) #if defined __FPU_VFP__ #error "Compiler generates FPU instructions for a device without an FPU (check __FPU_PRESENT)" #endif #endif #include /* standard types definitions */ #include /* Core Instruction Access */ #include /* Core Function Access */ #endif /* __CORE_CM0PLUS_H_GENERIC */ #ifndef __CMSIS_GENERIC #ifndef __CORE_CM0PLUS_H_DEPENDANT #define __CORE_CM0PLUS_H_DEPENDANT /* check device defines and use defaults */ #if defined __CHECK_DEVICE_DEFINES #ifndef __CM0PLUS_REV #define __CM0PLUS_REV 0x0000 #warning "__CM0PLUS_REV not defined in device header file; using default!" #endif #ifndef __MPU_PRESENT #define __MPU_PRESENT 0 #warning "__MPU_PRESENT not defined in device header file; using default!" #endif #ifndef __VTOR_PRESENT #define __VTOR_PRESENT 0 #warning "__VTOR_PRESENT not defined in device header file; using default!" #endif #ifndef __NVIC_PRIO_BITS #define __NVIC_PRIO_BITS 2 #warning "__NVIC_PRIO_BITS not defined in device header file; using default!" #endif #ifndef __Vendor_SysTickConfig #define __Vendor_SysTickConfig 0 #warning "__Vendor_SysTickConfig not defined in device header file; using default!" #endif #endif /* IO definitions (access restrictions to peripheral registers) */ /** \defgroup CMSIS_glob_defs CMSIS Global Defines IO Type Qualifiers are used \li to specify the access to peripheral variables. \li for automatic generation of peripheral register debug information. */ #ifdef __cplusplus #define __I volatile /*!< Defines 'read only' permissions */ #else #define __I volatile const /*!< Defines 'read only' permissions */ #endif #define __O volatile /*!< Defines 'write only' permissions */ #define __IO volatile /*!< Defines 'read / write' permissions */ /*@} end of group Cortex-M0+ */ /******************************************************************************* * Register Abstraction Core Register contain: - Core Register - Core NVIC Register - Core SCB Register - Core SysTick Register - Core MPU Register ******************************************************************************/ /** \defgroup CMSIS_core_register Defines and Type Definitions \brief Type definitions and defines for Cortex-M processor based devices. */ /** \ingroup CMSIS_core_register \defgroup CMSIS_CORE Status and Control Registers \brief Core Register type definitions. @{ */ /** \brief Union type to access the Application Program Status Register (APSR). */ typedef union { struct { #if (__CORTEX_M != 0x04) uint32_t _reserved0:27; /*!< bit: 0..26 Reserved */ #else uint32_t _reserved0:16; /*!< bit: 0..15 Reserved */ uint32_t GE:4; /*!< bit: 16..19 Greater than or Equal flags */ uint32_t _reserved1:7; /*!< bit: 20..26 Reserved */ #endif uint32_t Q:1; /*!< bit: 27 Saturation condition flag */ uint32_t V:1; /*!< bit: 28 Overflow condition code flag */ uint32_t C:1; /*!< bit: 29 Carry condition code flag */ uint32_t Z:1; /*!< bit: 30 Zero condition code flag */ uint32_t N:1; /*!< bit: 31 Negative condition code flag */ } b; /*!< Structure used for bit access */ uint32_t w; /*!< Type used for word access */ } APSR_Type; /** \brief Union type to access the Interrupt Program Status Register (IPSR). */ typedef union { struct { uint32_t ISR:9; /*!< bit: 0.. 8 Exception number */ uint32_t _reserved0:23; /*!< bit: 9..31 Reserved */ } b; /*!< Structure used for bit access */ uint32_t w; /*!< Type used for word access */ } IPSR_Type; /** \brief Union type to access the Special-Purpose Program Status Registers (xPSR). */ typedef union { struct { uint32_t ISR:9; /*!< bit: 0.. 8 Exception number */ #if (__CORTEX_M != 0x04) uint32_t _reserved0:15; /*!< bit: 9..23 Reserved */ #else uint32_t _reserved0:7; /*!< bit: 9..15 Reserved */ uint32_t GE:4; /*!< bit: 16..19 Greater than or Equal flags */ uint32_t _reserved1:4; /*!< bit: 20..23 Reserved */ #endif uint32_t T:1; /*!< bit: 24 Thumb bit (read 0) */ uint32_t IT:2; /*!< bit: 25..26 saved IT state (read 0) */ uint32_t Q:1; /*!< bit: 27 Saturation condition flag */ uint32_t V:1; /*!< bit: 28 Overflow condition code flag */ uint32_t C:1; /*!< bit: 29 Carry condition code flag */ uint32_t Z:1; /*!< bit: 30 Zero condition code flag */ uint32_t N:1; /*!< bit: 31 Negative condition code flag */ } b; /*!< Structure used for bit access */ uint32_t w; /*!< Type used for word access */ } xPSR_Type; /** \brief Union type to access the Control Registers (CONTROL). */ typedef union { struct { uint32_t nPRIV:1; /*!< bit: 0 Execution privilege in Thread mode */ uint32_t SPSEL:1; /*!< bit: 1 Stack to be used */ uint32_t FPCA:1; /*!< bit: 2 FP extension active flag */ uint32_t _reserved0:29; /*!< bit: 3..31 Reserved */ } b; /*!< Structure used for bit access */ uint32_t w; /*!< Type used for word access */ } CONTROL_Type; /*@} end of group CMSIS_CORE */ /** \ingroup CMSIS_core_register \defgroup CMSIS_NVIC Nested Vectored Interrupt Controller (NVIC) \brief Type definitions for the NVIC Registers @{ */ /** \brief Structure type to access the Nested Vectored Interrupt Controller (NVIC). */ typedef struct { __IO uint32_t ISER[1]; /*!< Offset: 0x000 (R/W) Interrupt Set Enable Register */ uint32_t RESERVED0[31]; __IO uint32_t ICER[1]; /*!< Offset: 0x080 (R/W) Interrupt Clear Enable Register */ uint32_t RSERVED1[31]; __IO uint32_t ISPR[1]; /*!< Offset: 0x100 (R/W) Interrupt Set Pending Register */ uint32_t RESERVED2[31]; __IO uint32_t ICPR[1]; /*!< Offset: 0x180 (R/W) Interrupt Clear Pending Register */ uint32_t RESERVED3[31]; uint32_t RESERVED4[64]; __IO uint32_t IP[8]; /*!< Offset: 0x300 (R/W) Interrupt Priority Register */ } NVIC_Type; /*@} end of group CMSIS_NVIC */ /** \ingroup CMSIS_core_register \defgroup CMSIS_SCB System Control Block (SCB) \brief Type definitions for the System Control Block Registers @{ */ /** \brief Structure type to access the System Control Block (SCB). */ typedef struct { __I uint32_t CPUID; /*!< Offset: 0x000 (R/ ) CPUID Base Register */ __IO uint32_t ICSR; /*!< Offset: 0x004 (R/W) Interrupt Control and State Register */ #if (__VTOR_PRESENT == 1) __IO uint32_t VTOR; /*!< Offset: 0x008 (R/W) Vector Table Offset Register */ #else uint32_t RESERVED0; #endif __IO uint32_t AIRCR; /*!< Offset: 0x00C (R/W) Application Interrupt and Reset Control Register */ __IO uint32_t SCR; /*!< Offset: 0x010 (R/W) System Control Register */ __IO uint32_t CCR; /*!< Offset: 0x014 (R/W) Configuration Control Register */ uint32_t RESERVED1; __IO uint32_t SHP[2]; /*!< Offset: 0x01C (R/W) System Handlers Priority Registers. [0] is RESERVED */ __IO uint32_t SHCSR; /*!< Offset: 0x024 (R/W) System Handler Control and State Register */ } SCB_Type; /* SCB CPUID Register Definitions */ #define SCB_CPUID_IMPLEMENTER_Pos 24 /*!< SCB CPUID: IMPLEMENTER Position */ #define SCB_CPUID_IMPLEMENTER_Msk (0xFFUL << SCB_CPUID_IMPLEMENTER_Pos) /*!< SCB CPUID: IMPLEMENTER Mask */ #define SCB_CPUID_VARIANT_Pos 20 /*!< SCB CPUID: VARIANT Position */ #define SCB_CPUID_VARIANT_Msk (0xFUL << SCB_CPUID_VARIANT_Pos) /*!< SCB CPUID: VARIANT Mask */ #define SCB_CPUID_ARCHITECTURE_Pos 16 /*!< SCB CPUID: ARCHITECTURE Position */ #define SCB_CPUID_ARCHITECTURE_Msk (0xFUL << SCB_CPUID_ARCHITECTURE_Pos) /*!< SCB CPUID: ARCHITECTURE Mask */ #define SCB_CPUID_PARTNO_Pos 4 /*!< SCB CPUID: PARTNO Position */ #define SCB_CPUID_PARTNO_Msk (0xFFFUL << SCB_CPUID_PARTNO_Pos) /*!< SCB CPUID: PARTNO Mask */ #define SCB_CPUID_REVISION_Pos 0 /*!< SCB CPUID: REVISION Position */ #define SCB_CPUID_REVISION_Msk (0xFUL << SCB_CPUID_REVISION_Pos) /*!< SCB CPUID: REVISION Mask */ /* SCB Interrupt Control State Register Definitions */ #define SCB_ICSR_NMIPENDSET_Pos 31 /*!< SCB ICSR: NMIPENDSET Position */ #define SCB_ICSR_NMIPENDSET_Msk (1UL << SCB_ICSR_NMIPENDSET_Pos) /*!< SCB ICSR: NMIPENDSET Mask */ #define SCB_ICSR_PENDSVSET_Pos 28 /*!< SCB ICSR: PENDSVSET Position */ #define SCB_ICSR_PENDSVSET_Msk (1UL << SCB_ICSR_PENDSVSET_Pos) /*!< SCB ICSR: PENDSVSET Mask */ #define SCB_ICSR_PENDSVCLR_Pos 27 /*!< SCB ICSR: PENDSVCLR Position */ #define SCB_ICSR_PENDSVCLR_Msk (1UL << SCB_ICSR_PENDSVCLR_Pos) /*!< SCB ICSR: PENDSVCLR Mask */ #define SCB_ICSR_PENDSTSET_Pos 26 /*!< SCB ICSR: PENDSTSET Position */ #define SCB_ICSR_PENDSTSET_Msk (1UL << SCB_ICSR_PENDSTSET_Pos) /*!< SCB ICSR: PENDSTSET Mask */ #define SCB_ICSR_PENDSTCLR_Pos 25 /*!< SCB ICSR: PENDSTCLR Position */ #define SCB_ICSR_PENDSTCLR_Msk (1UL << SCB_ICSR_PENDSTCLR_Pos) /*!< SCB ICSR: PENDSTCLR Mask */ #define SCB_ICSR_ISRPREEMPT_Pos 23 /*!< SCB ICSR: ISRPREEMPT Position */ #define SCB_ICSR_ISRPREEMPT_Msk (1UL << SCB_ICSR_ISRPREEMPT_Pos) /*!< SCB ICSR: ISRPREEMPT Mask */ #define SCB_ICSR_ISRPENDING_Pos 22 /*!< SCB ICSR: ISRPENDING Position */ #define SCB_ICSR_ISRPENDING_Msk (1UL << SCB_ICSR_ISRPENDING_Pos) /*!< SCB ICSR: ISRPENDING Mask */ #define SCB_ICSR_VECTPENDING_Pos 12 /*!< SCB ICSR: VECTPENDING Position */ #define SCB_ICSR_VECTPENDING_Msk (0x1FFUL << SCB_ICSR_VECTPENDING_Pos) /*!< SCB ICSR: VECTPENDING Mask */ #define SCB_ICSR_VECTACTIVE_Pos 0 /*!< SCB ICSR: VECTACTIVE Position */ #define SCB_ICSR_VECTACTIVE_Msk (0x1FFUL << SCB_ICSR_VECTACTIVE_Pos) /*!< SCB ICSR: VECTACTIVE Mask */ #if (__VTOR_PRESENT == 1) /* SCB Interrupt Control State Register Definitions */ #define SCB_VTOR_TBLOFF_Pos 8 /*!< SCB VTOR: TBLOFF Position */ #define SCB_VTOR_TBLOFF_Msk (0xFFFFFFUL << SCB_VTOR_TBLOFF_Pos) /*!< SCB VTOR: TBLOFF Mask */ #endif /* SCB Application Interrupt and Reset Control Register Definitions */ #define SCB_AIRCR_VECTKEY_Pos 16 /*!< SCB AIRCR: VECTKEY Position */ #define SCB_AIRCR_VECTKEY_Msk (0xFFFFUL << SCB_AIRCR_VECTKEY_Pos) /*!< SCB AIRCR: VECTKEY Mask */ #define SCB_AIRCR_VECTKEYSTAT_Pos 16 /*!< SCB AIRCR: VECTKEYSTAT Position */ #define SCB_AIRCR_VECTKEYSTAT_Msk (0xFFFFUL << SCB_AIRCR_VECTKEYSTAT_Pos) /*!< SCB AIRCR: VECTKEYSTAT Mask */ #define SCB_AIRCR_ENDIANESS_Pos 15 /*!< SCB AIRCR: ENDIANESS Position */ #define SCB_AIRCR_ENDIANESS_Msk (1UL << SCB_AIRCR_ENDIANESS_Pos) /*!< SCB AIRCR: ENDIANESS Mask */ #define SCB_AIRCR_SYSRESETREQ_Pos 2 /*!< SCB AIRCR: SYSRESETREQ Position */ #define SCB_AIRCR_SYSRESETREQ_Msk (1UL << SCB_AIRCR_SYSRESETREQ_Pos) /*!< SCB AIRCR: SYSRESETREQ Mask */ #define SCB_AIRCR_VECTCLRACTIVE_Pos 1 /*!< SCB AIRCR: VECTCLRACTIVE Position */ #define SCB_AIRCR_VECTCLRACTIVE_Msk (1UL << SCB_AIRCR_VECTCLRACTIVE_Pos) /*!< SCB AIRCR: VECTCLRACTIVE Mask */ /* SCB System Control Register Definitions */ #define SCB_SCR_SEVONPEND_Pos 4 /*!< SCB SCR: SEVONPEND Position */ #define SCB_SCR_SEVONPEND_Msk (1UL << SCB_SCR_SEVONPEND_Pos) /*!< SCB SCR: SEVONPEND Mask */ #define SCB_SCR_SLEEPDEEP_Pos 2 /*!< SCB SCR: SLEEPDEEP Position */ #define SCB_SCR_SLEEPDEEP_Msk (1UL << SCB_SCR_SLEEPDEEP_Pos) /*!< SCB SCR: SLEEPDEEP Mask */ #define SCB_SCR_SLEEPONEXIT_Pos 1 /*!< SCB SCR: SLEEPONEXIT Position */ #define SCB_SCR_SLEEPONEXIT_Msk (1UL << SCB_SCR_SLEEPONEXIT_Pos) /*!< SCB SCR: SLEEPONEXIT Mask */ /* SCB Configuration Control Register Definitions */ #define SCB_CCR_STKALIGN_Pos 9 /*!< SCB CCR: STKALIGN Position */ #define SCB_CCR_STKALIGN_Msk (1UL << SCB_CCR_STKALIGN_Pos) /*!< SCB CCR: STKALIGN Mask */ #define SCB_CCR_UNALIGN_TRP_Pos 3 /*!< SCB CCR: UNALIGN_TRP Position */ #define SCB_CCR_UNALIGN_TRP_Msk (1UL << SCB_CCR_UNALIGN_TRP_Pos) /*!< SCB CCR: UNALIGN_TRP Mask */ /* SCB System Handler Control and State Register Definitions */ #define SCB_SHCSR_SVCALLPENDED_Pos 15 /*!< SCB SHCSR: SVCALLPENDED Position */ #define SCB_SHCSR_SVCALLPENDED_Msk (1UL << SCB_SHCSR_SVCALLPENDED_Pos) /*!< SCB SHCSR: SVCALLPENDED Mask */ /*@} end of group CMSIS_SCB */ /** \ingroup CMSIS_core_register \defgroup CMSIS_SysTick System Tick Timer (SysTick) \brief Type definitions for the System Timer Registers. @{ */ /** \brief Structure type to access the System Timer (SysTick). */ typedef struct { __IO uint32_t CTRL; /*!< Offset: 0x000 (R/W) SysTick Control and Status Register */ __IO uint32_t LOAD; /*!< Offset: 0x004 (R/W) SysTick Reload Value Register */ __IO uint32_t VAL; /*!< Offset: 0x008 (R/W) SysTick Current Value Register */ __I uint32_t CALIB; /*!< Offset: 0x00C (R/ ) SysTick Calibration Register */ } SysTick_Type; /* SysTick Control / Status Register Definitions */ #define SysTick_CTRL_COUNTFLAG_Pos 16 /*!< SysTick CTRL: COUNTFLAG Position */ #define SysTick_CTRL_COUNTFLAG_Msk (1UL << SysTick_CTRL_COUNTFLAG_Pos) /*!< SysTick CTRL: COUNTFLAG Mask */ #define SysTick_CTRL_CLKSOURCE_Pos 2 /*!< SysTick CTRL: CLKSOURCE Position */ #define SysTick_CTRL_CLKSOURCE_Msk (1UL << SysTick_CTRL_CLKSOURCE_Pos) /*!< SysTick CTRL: CLKSOURCE Mask */ #define SysTick_CTRL_TICKINT_Pos 1 /*!< SysTick CTRL: TICKINT Position */ #define SysTick_CTRL_TICKINT_Msk (1UL << SysTick_CTRL_TICKINT_Pos) /*!< SysTick CTRL: TICKINT Mask */ #define SysTick_CTRL_ENABLE_Pos 0 /*!< SysTick CTRL: ENABLE Position */ #define SysTick_CTRL_ENABLE_Msk (1UL << SysTick_CTRL_ENABLE_Pos) /*!< SysTick CTRL: ENABLE Mask */ /* SysTick Reload Register Definitions */ #define SysTick_LOAD_RELOAD_Pos 0 /*!< SysTick LOAD: RELOAD Position */ #define SysTick_LOAD_RELOAD_Msk (0xFFFFFFUL << SysTick_LOAD_RELOAD_Pos) /*!< SysTick LOAD: RELOAD Mask */ /* SysTick Current Register Definitions */ #define SysTick_VAL_CURRENT_Pos 0 /*!< SysTick VAL: CURRENT Position */ #define SysTick_VAL_CURRENT_Msk (0xFFFFFFUL << SysTick_VAL_CURRENT_Pos) /*!< SysTick VAL: CURRENT Mask */ /* SysTick Calibration Register Definitions */ #define SysTick_CALIB_NOREF_Pos 31 /*!< SysTick CALIB: NOREF Position */ #define SysTick_CALIB_NOREF_Msk (1UL << SysTick_CALIB_NOREF_Pos) /*!< SysTick CALIB: NOREF Mask */ #define SysTick_CALIB_SKEW_Pos 30 /*!< SysTick CALIB: SKEW Position */ #define SysTick_CALIB_SKEW_Msk (1UL << SysTick_CALIB_SKEW_Pos) /*!< SysTick CALIB: SKEW Mask */ #define SysTick_CALIB_TENMS_Pos 0 /*!< SysTick CALIB: TENMS Position */ #define SysTick_CALIB_TENMS_Msk (0xFFFFFFUL << SysTick_VAL_CURRENT_Pos) /*!< SysTick CALIB: TENMS Mask */ /*@} end of group CMSIS_SysTick */ #if (__MPU_PRESENT == 1) /** \ingroup CMSIS_core_register \defgroup CMSIS_MPU Memory Protection Unit (MPU) \brief Type definitions for the Memory Protection Unit (MPU) @{ */ /** \brief Structure type to access the Memory Protection Unit (MPU). */ typedef struct { __I uint32_t TYPE; /*!< Offset: 0x000 (R/ ) MPU Type Register */ __IO uint32_t CTRL; /*!< Offset: 0x004 (R/W) MPU Control Register */ __IO uint32_t RNR; /*!< Offset: 0x008 (R/W) MPU Region RNRber Register */ __IO uint32_t RBAR; /*!< Offset: 0x00C (R/W) MPU Region Base Address Register */ __IO uint32_t RASR; /*!< Offset: 0x010 (R/W) MPU Region Attribute and Size Register */ } MPU_Type; /* MPU Type Register */ #define MPU_TYPE_IREGION_Pos 16 /*!< MPU TYPE: IREGION Position */ #define MPU_TYPE_IREGION_Msk (0xFFUL << MPU_TYPE_IREGION_Pos) /*!< MPU TYPE: IREGION Mask */ #define MPU_TYPE_DREGION_Pos 8 /*!< MPU TYPE: DREGION Position */ #define MPU_TYPE_DREGION_Msk (0xFFUL << MPU_TYPE_DREGION_Pos) /*!< MPU TYPE: DREGION Mask */ #define MPU_TYPE_SEPARATE_Pos 0 /*!< MPU TYPE: SEPARATE Position */ #define MPU_TYPE_SEPARATE_Msk (1UL << MPU_TYPE_SEPARATE_Pos) /*!< MPU TYPE: SEPARATE Mask */ /* MPU Control Register */ #define MPU_CTRL_PRIVDEFENA_Pos 2 /*!< MPU CTRL: PRIVDEFENA Position */ #define MPU_CTRL_PRIVDEFENA_Msk (1UL << MPU_CTRL_PRIVDEFENA_Pos) /*!< MPU CTRL: PRIVDEFENA Mask */ #define MPU_CTRL_HFNMIENA_Pos 1 /*!< MPU CTRL: HFNMIENA Position */ #define MPU_CTRL_HFNMIENA_Msk (1UL << MPU_CTRL_HFNMIENA_Pos) /*!< MPU CTRL: HFNMIENA Mask */ #define MPU_CTRL_ENABLE_Pos 0 /*!< MPU CTRL: ENABLE Position */ #define MPU_CTRL_ENABLE_Msk (1UL << MPU_CTRL_ENABLE_Pos) /*!< MPU CTRL: ENABLE Mask */ /* MPU Region Number Register */ #define MPU_RNR_REGION_Pos 0 /*!< MPU RNR: REGION Position */ #define MPU_RNR_REGION_Msk (0xFFUL << MPU_RNR_REGION_Pos) /*!< MPU RNR: REGION Mask */ /* MPU Region Base Address Register */ #define MPU_RBAR_ADDR_Pos 8 /*!< MPU RBAR: ADDR Position */ #define MPU_RBAR_ADDR_Msk (0xFFFFFFUL << MPU_RBAR_ADDR_Pos) /*!< MPU RBAR: ADDR Mask */ #define MPU_RBAR_VALID_Pos 4 /*!< MPU RBAR: VALID Position */ #define MPU_RBAR_VALID_Msk (1UL << MPU_RBAR_VALID_Pos) /*!< MPU RBAR: VALID Mask */ #define MPU_RBAR_REGION_Pos 0 /*!< MPU RBAR: REGION Position */ #define MPU_RBAR_REGION_Msk (0xFUL << MPU_RBAR_REGION_Pos) /*!< MPU RBAR: REGION Mask */ /* MPU Region Attribute and Size Register */ #define MPU_RASR_ATTRS_Pos 16 /*!< MPU RASR: MPU Region Attribute field Position */ #define MPU_RASR_ATTRS_Msk (0xFFFFUL << MPU_RASR_ATTRS_Pos) /*!< MPU RASR: MPU Region Attribute field Mask */ #define MPU_RASR_XN_Pos 28 /*!< MPU RASR: ATTRS.XN Position */ #define MPU_RASR_XN_Msk (1UL << MPU_RASR_XN_Pos) /*!< MPU RASR: ATTRS.XN Mask */ #define MPU_RASR_AP_Pos 24 /*!< MPU RASR: ATTRS.AP Position */ #define MPU_RASR_AP_Msk (0x7UL << MPU_RASR_AP_Pos) /*!< MPU RASR: ATTRS.AP Mask */ #define MPU_RASR_TEX_Pos 19 /*!< MPU RASR: ATTRS.TEX Position */ #define MPU_RASR_TEX_Msk (0x7UL << MPU_RASR_TEX_Pos) /*!< MPU RASR: ATTRS.TEX Mask */ #define MPU_RASR_S_Pos 18 /*!< MPU RASR: ATTRS.S Position */ #define MPU_RASR_S_Msk (1UL << MPU_RASR_S_Pos) /*!< MPU RASR: ATTRS.S Mask */ #define MPU_RASR_C_Pos 17 /*!< MPU RASR: ATTRS.C Position */ #define MPU_RASR_C_Msk (1UL << MPU_RASR_C_Pos) /*!< MPU RASR: ATTRS.C Mask */ #define MPU_RASR_B_Pos 16 /*!< MPU RASR: ATTRS.B Position */ #define MPU_RASR_B_Msk (1UL << MPU_RASR_B_Pos) /*!< MPU RASR: ATTRS.B Mask */ #define MPU_RASR_SRD_Pos 8 /*!< MPU RASR: Sub-Region Disable Position */ #define MPU_RASR_SRD_Msk (0xFFUL << MPU_RASR_SRD_Pos) /*!< MPU RASR: Sub-Region Disable Mask */ #define MPU_RASR_SIZE_Pos 1 /*!< MPU RASR: Region Size Field Position */ #define MPU_RASR_SIZE_Msk (0x1FUL << MPU_RASR_SIZE_Pos) /*!< MPU RASR: Region Size Field Mask */ #define MPU_RASR_ENABLE_Pos 0 /*!< MPU RASR: Region enable bit Position */ #define MPU_RASR_ENABLE_Msk (1UL << MPU_RASR_ENABLE_Pos) /*!< MPU RASR: Region enable bit Disable Mask */ /*@} end of group CMSIS_MPU */ #endif /** \ingroup CMSIS_core_register \defgroup CMSIS_CoreDebug Core Debug Registers (CoreDebug) \brief Cortex-M0+ Core Debug Registers (DCB registers, SHCSR, and DFSR) are only accessible over DAP and not via processor. Therefore they are not covered by the Cortex-M0 header file. @{ */ /*@} end of group CMSIS_CoreDebug */ /** \ingroup CMSIS_core_register \defgroup CMSIS_core_base Core Definitions \brief Definitions for base addresses, unions, and structures. @{ */ /* Memory mapping of Cortex-M0+ Hardware */ #define SCS_BASE (0xE000E000UL) /*!< System Control Space Base Address */ #define SysTick_BASE (SCS_BASE + 0x0010UL) /*!< SysTick Base Address */ #define NVIC_BASE (SCS_BASE + 0x0100UL) /*!< NVIC Base Address */ #define SCB_BASE (SCS_BASE + 0x0D00UL) /*!< System Control Block Base Address */ #define SCB ((SCB_Type *) SCB_BASE ) /*!< SCB configuration struct */ #define SysTick ((SysTick_Type *) SysTick_BASE ) /*!< SysTick configuration struct */ #define NVIC ((NVIC_Type *) NVIC_BASE ) /*!< NVIC configuration struct */ #if (__MPU_PRESENT == 1) #define MPU_BASE (SCS_BASE + 0x0D90UL) /*!< Memory Protection Unit */ #define MPU ((MPU_Type *) MPU_BASE ) /*!< Memory Protection Unit */ #endif /*@} */ /******************************************************************************* * Hardware Abstraction Layer Core Function Interface contains: - Core NVIC Functions - Core SysTick Functions - Core Register Access Functions ******************************************************************************/ /** \defgroup CMSIS_Core_FunctionInterface Functions and Instructions Reference */ /* ########################## NVIC functions #################################### */ /** \ingroup CMSIS_Core_FunctionInterface \defgroup CMSIS_Core_NVICFunctions NVIC Functions \brief Functions that manage interrupts and exceptions via the NVIC. @{ */ /* Interrupt Priorities are WORD accessible only under ARMv6M */ /* The following MACROS handle generation of the register offset and byte masks */ #define _BIT_SHIFT(IRQn) ( (((uint32_t)(IRQn) ) & 0x03) * 8 ) #define _SHP_IDX(IRQn) ( ((((uint32_t)(IRQn) & 0x0F)-8) >> 2) ) #define _IP_IDX(IRQn) ( ((uint32_t)(IRQn) >> 2) ) /** \brief Enable External Interrupt The function enables a device-specific interrupt in the NVIC interrupt controller. \param [in] IRQn External interrupt number. Value cannot be negative. */ __STATIC_INLINE void NVIC_EnableIRQ(IRQn_Type IRQn) { NVIC->ISER[0] = (1 << ((uint32_t)(IRQn) & 0x1F)); } /** \brief Disable External Interrupt The function disables a device-specific interrupt in the NVIC interrupt controller. \param [in] IRQn External interrupt number. Value cannot be negative. */ __STATIC_INLINE void NVIC_DisableIRQ(IRQn_Type IRQn) { NVIC->ICER[0] = (1 << ((uint32_t)(IRQn) & 0x1F)); } /** \brief Get Pending Interrupt The function reads the pending register in the NVIC and returns the pending bit for the specified interrupt. \param [in] IRQn Interrupt number. \return 0 Interrupt status is not pending. \return 1 Interrupt status is pending. */ __STATIC_INLINE uint32_t NVIC_GetPendingIRQ(IRQn_Type IRQn) { return((uint32_t) ((NVIC->ISPR[0] & (1 << ((uint32_t)(IRQn) & 0x1F)))?1:0)); } /** \brief Set Pending Interrupt The function sets the pending bit of an external interrupt. \param [in] IRQn Interrupt number. Value cannot be negative. */ __STATIC_INLINE void NVIC_SetPendingIRQ(IRQn_Type IRQn) { NVIC->ISPR[0] = (1 << ((uint32_t)(IRQn) & 0x1F)); } /** \brief Clear Pending Interrupt The function clears the pending bit of an external interrupt. \param [in] IRQn External interrupt number. Value cannot be negative. */ __STATIC_INLINE void NVIC_ClearPendingIRQ(IRQn_Type IRQn) { NVIC->ICPR[0] = (1 << ((uint32_t)(IRQn) & 0x1F)); /* Clear pending interrupt */ } /** \brief Set Interrupt Priority The function sets the priority of an interrupt. \note The priority cannot be set for every core interrupt. \param [in] IRQn Interrupt number. \param [in] priority Priority to set. */ __STATIC_INLINE void NVIC_SetPriority(IRQn_Type IRQn, uint32_t priority) { if(IRQn < 0) { SCB->SHP[_SHP_IDX(IRQn)] = (SCB->SHP[_SHP_IDX(IRQn)] & ~(0xFF << _BIT_SHIFT(IRQn))) | (((priority << (8 - __NVIC_PRIO_BITS)) & 0xFF) << _BIT_SHIFT(IRQn)); } else { NVIC->IP[_IP_IDX(IRQn)] = (NVIC->IP[_IP_IDX(IRQn)] & ~(0xFF << _BIT_SHIFT(IRQn))) | (((priority << (8 - __NVIC_PRIO_BITS)) & 0xFF) << _BIT_SHIFT(IRQn)); } } /** \brief Get Interrupt Priority The function reads the priority of an interrupt. The interrupt number can be positive to specify an external (device specific) interrupt, or negative to specify an internal (core) interrupt. \param [in] IRQn Interrupt number. \return Interrupt Priority. Value is aligned automatically to the implemented priority bits of the microcontroller. */ __STATIC_INLINE uint32_t NVIC_GetPriority(IRQn_Type IRQn) { if(IRQn < 0) { return((uint32_t)(((SCB->SHP[_SHP_IDX(IRQn)] >> _BIT_SHIFT(IRQn) ) & 0xFF) >> (8 - __NVIC_PRIO_BITS))); } /* get priority for Cortex-M0 system interrupts */ else { return((uint32_t)(((NVIC->IP[ _IP_IDX(IRQn)] >> _BIT_SHIFT(IRQn) ) & 0xFF) >> (8 - __NVIC_PRIO_BITS))); } /* get priority for device specific interrupts */ } /** \brief System Reset The function initiates a system reset request to reset the MCU. */ __STATIC_INLINE void NVIC_SystemReset(void) { __DSB(); /* Ensure all outstanding memory accesses included buffered write are completed before reset */ SCB->AIRCR = ((0x5FA << SCB_AIRCR_VECTKEY_Pos) | SCB_AIRCR_SYSRESETREQ_Msk); __DSB(); /* Ensure completion of memory access */ while(1); /* wait until reset */ } /*@} end of CMSIS_Core_NVICFunctions */ /* ################################## SysTick function ############################################ */ /** \ingroup CMSIS_Core_FunctionInterface \defgroup CMSIS_Core_SysTickFunctions SysTick Functions \brief Functions that configure the System. @{ */ #if (__Vendor_SysTickConfig == 0) /** \brief System Tick Configuration The function initializes the System Timer and its interrupt, and starts the System Tick Timer. Counter is in free running mode to generate periodic interrupts. \param [in] ticks Number of ticks between two interrupts. \return 0 Function succeeded. \return 1 Function failed. \note When the variable __Vendor_SysTickConfig is set to 1, then the function SysTick_Config is not included. In this case, the file device.h must contain a vendor-specific implementation of this function. */ __STATIC_INLINE uint32_t SysTick_Config(uint32_t ticks) { if ((ticks - 1) > SysTick_LOAD_RELOAD_Msk) return (1); /* Reload value impossible */ SysTick->LOAD = ticks - 1; /* set reload register */ NVIC_SetPriority (SysTick_IRQn, (1<<__NVIC_PRIO_BITS) - 1); /* set Priority for Systick Interrupt */ SysTick->VAL = 0; /* Load the SysTick Counter Value */ SysTick->CTRL = SysTick_CTRL_CLKSOURCE_Msk | SysTick_CTRL_TICKINT_Msk | SysTick_CTRL_ENABLE_Msk; /* Enable SysTick IRQ and SysTick Timer */ return (0); /* Function successful */ } #endif /*@} end of CMSIS_Core_SysTickFunctions */ #endif /* __CORE_CM0PLUS_H_DEPENDANT */ #endif /* __CMSIS_GENERIC */ #ifdef __cplusplus } #endif ================================================ FILE: Zelig/mbed/TARGET_K64F/core_cm3.h ================================================ /**************************************************************************//** * @file core_cm3.h * @brief CMSIS Cortex-M3 Core Peripheral Access Layer Header File * @version V3.20 * @date 25. February 2013 * * @note * ******************************************************************************/ /* Copyright (c) 2009 - 2013 ARM LIMITED All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: - Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. - Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. - Neither the name of ARM 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 COPYRIGHT HOLDERS AND 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. ---------------------------------------------------------------------------*/ #if defined ( __ICCARM__ ) #pragma system_include /* treat file as system include file for MISRA check */ #endif #ifdef __cplusplus extern "C" { #endif #ifndef __CORE_CM3_H_GENERIC #define __CORE_CM3_H_GENERIC /** \page CMSIS_MISRA_Exceptions MISRA-C:2004 Compliance Exceptions CMSIS violates the following MISRA-C:2004 rules: \li Required Rule 8.5, object/function definition in header file.
Function definitions in header files are used to allow 'inlining'. \li Required Rule 18.4, declaration of union type or object of union type: '{...}'.
Unions are used for effective representation of core registers. \li Advisory Rule 19.7, Function-like macro defined.
Function-like macros are used to allow more efficient code. */ /******************************************************************************* * CMSIS definitions ******************************************************************************/ /** \ingroup Cortex_M3 @{ */ /* CMSIS CM3 definitions */ #define __CM3_CMSIS_VERSION_MAIN (0x03) /*!< [31:16] CMSIS HAL main version */ #define __CM3_CMSIS_VERSION_SUB (0x20) /*!< [15:0] CMSIS HAL sub version */ #define __CM3_CMSIS_VERSION ((__CM3_CMSIS_VERSION_MAIN << 16) | \ __CM3_CMSIS_VERSION_SUB ) /*!< CMSIS HAL version number */ #define __CORTEX_M (0x03) /*!< Cortex-M Core */ #if defined ( __CC_ARM ) #define __ASM __asm /*!< asm keyword for ARM Compiler */ #define __INLINE __inline /*!< inline keyword for ARM Compiler */ #define __STATIC_INLINE static __inline #elif defined ( __ICCARM__ ) #define __ASM __asm /*!< asm keyword for IAR Compiler */ #define __INLINE inline /*!< inline keyword for IAR Compiler. Only available in High optimization mode! */ #define __STATIC_INLINE static inline #elif defined ( __TMS470__ ) #define __ASM __asm /*!< asm keyword for TI CCS Compiler */ #define __STATIC_INLINE static inline #elif defined ( __GNUC__ ) #define __ASM __asm /*!< asm keyword for GNU Compiler */ #define __INLINE inline /*!< inline keyword for GNU Compiler */ #define __STATIC_INLINE static inline #elif defined ( __TASKING__ ) #define __ASM __asm /*!< asm keyword for TASKING Compiler */ #define __INLINE inline /*!< inline keyword for TASKING Compiler */ #define __STATIC_INLINE static inline #endif /** __FPU_USED indicates whether an FPU is used or not. This core does not support an FPU at all */ #define __FPU_USED 0 #if defined ( __CC_ARM ) #if defined __TARGET_FPU_VFP #warning "Compiler generates FPU instructions for a device without an FPU (check __FPU_PRESENT)" #endif #elif defined ( __ICCARM__ ) #if defined __ARMVFP__ #warning "Compiler generates FPU instructions for a device without an FPU (check __FPU_PRESENT)" #endif #elif defined ( __TMS470__ ) #if defined __TI__VFP_SUPPORT____ #warning "Compiler generates FPU instructions for a device without an FPU (check __FPU_PRESENT)" #endif #elif defined ( __GNUC__ ) #if defined (__VFP_FP__) && !defined(__SOFTFP__) #warning "Compiler generates FPU instructions for a device without an FPU (check __FPU_PRESENT)" #endif #elif defined ( __TASKING__ ) #if defined __FPU_VFP__ #error "Compiler generates FPU instructions for a device without an FPU (check __FPU_PRESENT)" #endif #endif #include /* standard types definitions */ #include /* Core Instruction Access */ #include /* Core Function Access */ #endif /* __CORE_CM3_H_GENERIC */ #ifndef __CMSIS_GENERIC #ifndef __CORE_CM3_H_DEPENDANT #define __CORE_CM3_H_DEPENDANT /* check device defines and use defaults */ #if defined __CHECK_DEVICE_DEFINES #ifndef __CM3_REV #define __CM3_REV 0x0200 #warning "__CM3_REV not defined in device header file; using default!" #endif #ifndef __MPU_PRESENT #define __MPU_PRESENT 0 #warning "__MPU_PRESENT not defined in device header file; using default!" #endif #ifndef __NVIC_PRIO_BITS #define __NVIC_PRIO_BITS 4 #warning "__NVIC_PRIO_BITS not defined in device header file; using default!" #endif #ifndef __Vendor_SysTickConfig #define __Vendor_SysTickConfig 0 #warning "__Vendor_SysTickConfig not defined in device header file; using default!" #endif #endif /* IO definitions (access restrictions to peripheral registers) */ /** \defgroup CMSIS_glob_defs CMSIS Global Defines IO Type Qualifiers are used \li to specify the access to peripheral variables. \li for automatic generation of peripheral register debug information. */ #ifdef __cplusplus #define __I volatile /*!< Defines 'read only' permissions */ #else #define __I volatile const /*!< Defines 'read only' permissions */ #endif #define __O volatile /*!< Defines 'write only' permissions */ #define __IO volatile /*!< Defines 'read / write' permissions */ /*@} end of group Cortex_M3 */ /******************************************************************************* * Register Abstraction Core Register contain: - Core Register - Core NVIC Register - Core SCB Register - Core SysTick Register - Core Debug Register - Core MPU Register ******************************************************************************/ /** \defgroup CMSIS_core_register Defines and Type Definitions \brief Type definitions and defines for Cortex-M processor based devices. */ /** \ingroup CMSIS_core_register \defgroup CMSIS_CORE Status and Control Registers \brief Core Register type definitions. @{ */ /** \brief Union type to access the Application Program Status Register (APSR). */ typedef union { struct { #if (__CORTEX_M != 0x04) uint32_t _reserved0:27; /*!< bit: 0..26 Reserved */ #else uint32_t _reserved0:16; /*!< bit: 0..15 Reserved */ uint32_t GE:4; /*!< bit: 16..19 Greater than or Equal flags */ uint32_t _reserved1:7; /*!< bit: 20..26 Reserved */ #endif uint32_t Q:1; /*!< bit: 27 Saturation condition flag */ uint32_t V:1; /*!< bit: 28 Overflow condition code flag */ uint32_t C:1; /*!< bit: 29 Carry condition code flag */ uint32_t Z:1; /*!< bit: 30 Zero condition code flag */ uint32_t N:1; /*!< bit: 31 Negative condition code flag */ } b; /*!< Structure used for bit access */ uint32_t w; /*!< Type used for word access */ } APSR_Type; /** \brief Union type to access the Interrupt Program Status Register (IPSR). */ typedef union { struct { uint32_t ISR:9; /*!< bit: 0.. 8 Exception number */ uint32_t _reserved0:23; /*!< bit: 9..31 Reserved */ } b; /*!< Structure used for bit access */ uint32_t w; /*!< Type used for word access */ } IPSR_Type; /** \brief Union type to access the Special-Purpose Program Status Registers (xPSR). */ typedef union { struct { uint32_t ISR:9; /*!< bit: 0.. 8 Exception number */ #if (__CORTEX_M != 0x04) uint32_t _reserved0:15; /*!< bit: 9..23 Reserved */ #else uint32_t _reserved0:7; /*!< bit: 9..15 Reserved */ uint32_t GE:4; /*!< bit: 16..19 Greater than or Equal flags */ uint32_t _reserved1:4; /*!< bit: 20..23 Reserved */ #endif uint32_t T:1; /*!< bit: 24 Thumb bit (read 0) */ uint32_t IT:2; /*!< bit: 25..26 saved IT state (read 0) */ uint32_t Q:1; /*!< bit: 27 Saturation condition flag */ uint32_t V:1; /*!< bit: 28 Overflow condition code flag */ uint32_t C:1; /*!< bit: 29 Carry condition code flag */ uint32_t Z:1; /*!< bit: 30 Zero condition code flag */ uint32_t N:1; /*!< bit: 31 Negative condition code flag */ } b; /*!< Structure used for bit access */ uint32_t w; /*!< Type used for word access */ } xPSR_Type; /** \brief Union type to access the Control Registers (CONTROL). */ typedef union { struct { uint32_t nPRIV:1; /*!< bit: 0 Execution privilege in Thread mode */ uint32_t SPSEL:1; /*!< bit: 1 Stack to be used */ uint32_t FPCA:1; /*!< bit: 2 FP extension active flag */ uint32_t _reserved0:29; /*!< bit: 3..31 Reserved */ } b; /*!< Structure used for bit access */ uint32_t w; /*!< Type used for word access */ } CONTROL_Type; /*@} end of group CMSIS_CORE */ /** \ingroup CMSIS_core_register \defgroup CMSIS_NVIC Nested Vectored Interrupt Controller (NVIC) \brief Type definitions for the NVIC Registers @{ */ /** \brief Structure type to access the Nested Vectored Interrupt Controller (NVIC). */ typedef struct { __IO uint32_t ISER[8]; /*!< Offset: 0x000 (R/W) Interrupt Set Enable Register */ uint32_t RESERVED0[24]; __IO uint32_t ICER[8]; /*!< Offset: 0x080 (R/W) Interrupt Clear Enable Register */ uint32_t RSERVED1[24]; __IO uint32_t ISPR[8]; /*!< Offset: 0x100 (R/W) Interrupt Set Pending Register */ uint32_t RESERVED2[24]; __IO uint32_t ICPR[8]; /*!< Offset: 0x180 (R/W) Interrupt Clear Pending Register */ uint32_t RESERVED3[24]; __IO uint32_t IABR[8]; /*!< Offset: 0x200 (R/W) Interrupt Active bit Register */ uint32_t RESERVED4[56]; __IO uint8_t IP[240]; /*!< Offset: 0x300 (R/W) Interrupt Priority Register (8Bit wide) */ uint32_t RESERVED5[644]; __O uint32_t STIR; /*!< Offset: 0xE00 ( /W) Software Trigger Interrupt Register */ } NVIC_Type; /* Software Triggered Interrupt Register Definitions */ #define NVIC_STIR_INTID_Pos 0 /*!< STIR: INTLINESNUM Position */ #define NVIC_STIR_INTID_Msk (0x1FFUL << NVIC_STIR_INTID_Pos) /*!< STIR: INTLINESNUM Mask */ /*@} end of group CMSIS_NVIC */ /** \ingroup CMSIS_core_register \defgroup CMSIS_SCB System Control Block (SCB) \brief Type definitions for the System Control Block Registers @{ */ /** \brief Structure type to access the System Control Block (SCB). */ typedef struct { __I uint32_t CPUID; /*!< Offset: 0x000 (R/ ) CPUID Base Register */ __IO uint32_t ICSR; /*!< Offset: 0x004 (R/W) Interrupt Control and State Register */ __IO uint32_t VTOR; /*!< Offset: 0x008 (R/W) Vector Table Offset Register */ __IO uint32_t AIRCR; /*!< Offset: 0x00C (R/W) Application Interrupt and Reset Control Register */ __IO uint32_t SCR; /*!< Offset: 0x010 (R/W) System Control Register */ __IO uint32_t CCR; /*!< Offset: 0x014 (R/W) Configuration Control Register */ __IO uint8_t SHP[12]; /*!< Offset: 0x018 (R/W) System Handlers Priority Registers (4-7, 8-11, 12-15) */ __IO uint32_t SHCSR; /*!< Offset: 0x024 (R/W) System Handler Control and State Register */ __IO uint32_t CFSR; /*!< Offset: 0x028 (R/W) Configurable Fault Status Register */ __IO uint32_t HFSR; /*!< Offset: 0x02C (R/W) HardFault Status Register */ __IO uint32_t DFSR; /*!< Offset: 0x030 (R/W) Debug Fault Status Register */ __IO uint32_t MMFAR; /*!< Offset: 0x034 (R/W) MemManage Fault Address Register */ __IO uint32_t BFAR; /*!< Offset: 0x038 (R/W) BusFault Address Register */ __IO uint32_t AFSR; /*!< Offset: 0x03C (R/W) Auxiliary Fault Status Register */ __I uint32_t PFR[2]; /*!< Offset: 0x040 (R/ ) Processor Feature Register */ __I uint32_t DFR; /*!< Offset: 0x048 (R/ ) Debug Feature Register */ __I uint32_t ADR; /*!< Offset: 0x04C (R/ ) Auxiliary Feature Register */ __I uint32_t MMFR[4]; /*!< Offset: 0x050 (R/ ) Memory Model Feature Register */ __I uint32_t ISAR[5]; /*!< Offset: 0x060 (R/ ) Instruction Set Attributes Register */ uint32_t RESERVED0[5]; __IO uint32_t CPACR; /*!< Offset: 0x088 (R/W) Coprocessor Access Control Register */ } SCB_Type; /* SCB CPUID Register Definitions */ #define SCB_CPUID_IMPLEMENTER_Pos 24 /*!< SCB CPUID: IMPLEMENTER Position */ #define SCB_CPUID_IMPLEMENTER_Msk (0xFFUL << SCB_CPUID_IMPLEMENTER_Pos) /*!< SCB CPUID: IMPLEMENTER Mask */ #define SCB_CPUID_VARIANT_Pos 20 /*!< SCB CPUID: VARIANT Position */ #define SCB_CPUID_VARIANT_Msk (0xFUL << SCB_CPUID_VARIANT_Pos) /*!< SCB CPUID: VARIANT Mask */ #define SCB_CPUID_ARCHITECTURE_Pos 16 /*!< SCB CPUID: ARCHITECTURE Position */ #define SCB_CPUID_ARCHITECTURE_Msk (0xFUL << SCB_CPUID_ARCHITECTURE_Pos) /*!< SCB CPUID: ARCHITECTURE Mask */ #define SCB_CPUID_PARTNO_Pos 4 /*!< SCB CPUID: PARTNO Position */ #define SCB_CPUID_PARTNO_Msk (0xFFFUL << SCB_CPUID_PARTNO_Pos) /*!< SCB CPUID: PARTNO Mask */ #define SCB_CPUID_REVISION_Pos 0 /*!< SCB CPUID: REVISION Position */ #define SCB_CPUID_REVISION_Msk (0xFUL << SCB_CPUID_REVISION_Pos) /*!< SCB CPUID: REVISION Mask */ /* SCB Interrupt Control State Register Definitions */ #define SCB_ICSR_NMIPENDSET_Pos 31 /*!< SCB ICSR: NMIPENDSET Position */ #define SCB_ICSR_NMIPENDSET_Msk (1UL << SCB_ICSR_NMIPENDSET_Pos) /*!< SCB ICSR: NMIPENDSET Mask */ #define SCB_ICSR_PENDSVSET_Pos 28 /*!< SCB ICSR: PENDSVSET Position */ #define SCB_ICSR_PENDSVSET_Msk (1UL << SCB_ICSR_PENDSVSET_Pos) /*!< SCB ICSR: PENDSVSET Mask */ #define SCB_ICSR_PENDSVCLR_Pos 27 /*!< SCB ICSR: PENDSVCLR Position */ #define SCB_ICSR_PENDSVCLR_Msk (1UL << SCB_ICSR_PENDSVCLR_Pos) /*!< SCB ICSR: PENDSVCLR Mask */ #define SCB_ICSR_PENDSTSET_Pos 26 /*!< SCB ICSR: PENDSTSET Position */ #define SCB_ICSR_PENDSTSET_Msk (1UL << SCB_ICSR_PENDSTSET_Pos) /*!< SCB ICSR: PENDSTSET Mask */ #define SCB_ICSR_PENDSTCLR_Pos 25 /*!< SCB ICSR: PENDSTCLR Position */ #define SCB_ICSR_PENDSTCLR_Msk (1UL << SCB_ICSR_PENDSTCLR_Pos) /*!< SCB ICSR: PENDSTCLR Mask */ #define SCB_ICSR_ISRPREEMPT_Pos 23 /*!< SCB ICSR: ISRPREEMPT Position */ #define SCB_ICSR_ISRPREEMPT_Msk (1UL << SCB_ICSR_ISRPREEMPT_Pos) /*!< SCB ICSR: ISRPREEMPT Mask */ #define SCB_ICSR_ISRPENDING_Pos 22 /*!< SCB ICSR: ISRPENDING Position */ #define SCB_ICSR_ISRPENDING_Msk (1UL << SCB_ICSR_ISRPENDING_Pos) /*!< SCB ICSR: ISRPENDING Mask */ #define SCB_ICSR_VECTPENDING_Pos 12 /*!< SCB ICSR: VECTPENDING Position */ #define SCB_ICSR_VECTPENDING_Msk (0x1FFUL << SCB_ICSR_VECTPENDING_Pos) /*!< SCB ICSR: VECTPENDING Mask */ #define SCB_ICSR_RETTOBASE_Pos 11 /*!< SCB ICSR: RETTOBASE Position */ #define SCB_ICSR_RETTOBASE_Msk (1UL << SCB_ICSR_RETTOBASE_Pos) /*!< SCB ICSR: RETTOBASE Mask */ #define SCB_ICSR_VECTACTIVE_Pos 0 /*!< SCB ICSR: VECTACTIVE Position */ #define SCB_ICSR_VECTACTIVE_Msk (0x1FFUL << SCB_ICSR_VECTACTIVE_Pos) /*!< SCB ICSR: VECTACTIVE Mask */ /* SCB Vector Table Offset Register Definitions */ #if (__CM3_REV < 0x0201) /* core r2p1 */ #define SCB_VTOR_TBLBASE_Pos 29 /*!< SCB VTOR: TBLBASE Position */ #define SCB_VTOR_TBLBASE_Msk (1UL << SCB_VTOR_TBLBASE_Pos) /*!< SCB VTOR: TBLBASE Mask */ #define SCB_VTOR_TBLOFF_Pos 7 /*!< SCB VTOR: TBLOFF Position */ #define SCB_VTOR_TBLOFF_Msk (0x3FFFFFUL << SCB_VTOR_TBLOFF_Pos) /*!< SCB VTOR: TBLOFF Mask */ #else #define SCB_VTOR_TBLOFF_Pos 7 /*!< SCB VTOR: TBLOFF Position */ #define SCB_VTOR_TBLOFF_Msk (0x1FFFFFFUL << SCB_VTOR_TBLOFF_Pos) /*!< SCB VTOR: TBLOFF Mask */ #endif /* SCB Application Interrupt and Reset Control Register Definitions */ #define SCB_AIRCR_VECTKEY_Pos 16 /*!< SCB AIRCR: VECTKEY Position */ #define SCB_AIRCR_VECTKEY_Msk (0xFFFFUL << SCB_AIRCR_VECTKEY_Pos) /*!< SCB AIRCR: VECTKEY Mask */ #define SCB_AIRCR_VECTKEYSTAT_Pos 16 /*!< SCB AIRCR: VECTKEYSTAT Position */ #define SCB_AIRCR_VECTKEYSTAT_Msk (0xFFFFUL << SCB_AIRCR_VECTKEYSTAT_Pos) /*!< SCB AIRCR: VECTKEYSTAT Mask */ #define SCB_AIRCR_ENDIANESS_Pos 15 /*!< SCB AIRCR: ENDIANESS Position */ #define SCB_AIRCR_ENDIANESS_Msk (1UL << SCB_AIRCR_ENDIANESS_Pos) /*!< SCB AIRCR: ENDIANESS Mask */ #define SCB_AIRCR_PRIGROUP_Pos 8 /*!< SCB AIRCR: PRIGROUP Position */ #define SCB_AIRCR_PRIGROUP_Msk (7UL << SCB_AIRCR_PRIGROUP_Pos) /*!< SCB AIRCR: PRIGROUP Mask */ #define SCB_AIRCR_SYSRESETREQ_Pos 2 /*!< SCB AIRCR: SYSRESETREQ Position */ #define SCB_AIRCR_SYSRESETREQ_Msk (1UL << SCB_AIRCR_SYSRESETREQ_Pos) /*!< SCB AIRCR: SYSRESETREQ Mask */ #define SCB_AIRCR_VECTCLRACTIVE_Pos 1 /*!< SCB AIRCR: VECTCLRACTIVE Position */ #define SCB_AIRCR_VECTCLRACTIVE_Msk (1UL << SCB_AIRCR_VECTCLRACTIVE_Pos) /*!< SCB AIRCR: VECTCLRACTIVE Mask */ #define SCB_AIRCR_VECTRESET_Pos 0 /*!< SCB AIRCR: VECTRESET Position */ #define SCB_AIRCR_VECTRESET_Msk (1UL << SCB_AIRCR_VECTRESET_Pos) /*!< SCB AIRCR: VECTRESET Mask */ /* SCB System Control Register Definitions */ #define SCB_SCR_SEVONPEND_Pos 4 /*!< SCB SCR: SEVONPEND Position */ #define SCB_SCR_SEVONPEND_Msk (1UL << SCB_SCR_SEVONPEND_Pos) /*!< SCB SCR: SEVONPEND Mask */ #define SCB_SCR_SLEEPDEEP_Pos 2 /*!< SCB SCR: SLEEPDEEP Position */ #define SCB_SCR_SLEEPDEEP_Msk (1UL << SCB_SCR_SLEEPDEEP_Pos) /*!< SCB SCR: SLEEPDEEP Mask */ #define SCB_SCR_SLEEPONEXIT_Pos 1 /*!< SCB SCR: SLEEPONEXIT Position */ #define SCB_SCR_SLEEPONEXIT_Msk (1UL << SCB_SCR_SLEEPONEXIT_Pos) /*!< SCB SCR: SLEEPONEXIT Mask */ /* SCB Configuration Control Register Definitions */ #define SCB_CCR_STKALIGN_Pos 9 /*!< SCB CCR: STKALIGN Position */ #define SCB_CCR_STKALIGN_Msk (1UL << SCB_CCR_STKALIGN_Pos) /*!< SCB CCR: STKALIGN Mask */ #define SCB_CCR_BFHFNMIGN_Pos 8 /*!< SCB CCR: BFHFNMIGN Position */ #define SCB_CCR_BFHFNMIGN_Msk (1UL << SCB_CCR_BFHFNMIGN_Pos) /*!< SCB CCR: BFHFNMIGN Mask */ #define SCB_CCR_DIV_0_TRP_Pos 4 /*!< SCB CCR: DIV_0_TRP Position */ #define SCB_CCR_DIV_0_TRP_Msk (1UL << SCB_CCR_DIV_0_TRP_Pos) /*!< SCB CCR: DIV_0_TRP Mask */ #define SCB_CCR_UNALIGN_TRP_Pos 3 /*!< SCB CCR: UNALIGN_TRP Position */ #define SCB_CCR_UNALIGN_TRP_Msk (1UL << SCB_CCR_UNALIGN_TRP_Pos) /*!< SCB CCR: UNALIGN_TRP Mask */ #define SCB_CCR_USERSETMPEND_Pos 1 /*!< SCB CCR: USERSETMPEND Position */ #define SCB_CCR_USERSETMPEND_Msk (1UL << SCB_CCR_USERSETMPEND_Pos) /*!< SCB CCR: USERSETMPEND Mask */ #define SCB_CCR_NONBASETHRDENA_Pos 0 /*!< SCB CCR: NONBASETHRDENA Position */ #define SCB_CCR_NONBASETHRDENA_Msk (1UL << SCB_CCR_NONBASETHRDENA_Pos) /*!< SCB CCR: NONBASETHRDENA Mask */ /* SCB System Handler Control and State Register Definitions */ #define SCB_SHCSR_USGFAULTENA_Pos 18 /*!< SCB SHCSR: USGFAULTENA Position */ #define SCB_SHCSR_USGFAULTENA_Msk (1UL << SCB_SHCSR_USGFAULTENA_Pos) /*!< SCB SHCSR: USGFAULTENA Mask */ #define SCB_SHCSR_BUSFAULTENA_Pos 17 /*!< SCB SHCSR: BUSFAULTENA Position */ #define SCB_SHCSR_BUSFAULTENA_Msk (1UL << SCB_SHCSR_BUSFAULTENA_Pos) /*!< SCB SHCSR: BUSFAULTENA Mask */ #define SCB_SHCSR_MEMFAULTENA_Pos 16 /*!< SCB SHCSR: MEMFAULTENA Position */ #define SCB_SHCSR_MEMFAULTENA_Msk (1UL << SCB_SHCSR_MEMFAULTENA_Pos) /*!< SCB SHCSR: MEMFAULTENA Mask */ #define SCB_SHCSR_SVCALLPENDED_Pos 15 /*!< SCB SHCSR: SVCALLPENDED Position */ #define SCB_SHCSR_SVCALLPENDED_Msk (1UL << SCB_SHCSR_SVCALLPENDED_Pos) /*!< SCB SHCSR: SVCALLPENDED Mask */ #define SCB_SHCSR_BUSFAULTPENDED_Pos 14 /*!< SCB SHCSR: BUSFAULTPENDED Position */ #define SCB_SHCSR_BUSFAULTPENDED_Msk (1UL << SCB_SHCSR_BUSFAULTPENDED_Pos) /*!< SCB SHCSR: BUSFAULTPENDED Mask */ #define SCB_SHCSR_MEMFAULTPENDED_Pos 13 /*!< SCB SHCSR: MEMFAULTPENDED Position */ #define SCB_SHCSR_MEMFAULTPENDED_Msk (1UL << SCB_SHCSR_MEMFAULTPENDED_Pos) /*!< SCB SHCSR: MEMFAULTPENDED Mask */ #define SCB_SHCSR_USGFAULTPENDED_Pos 12 /*!< SCB SHCSR: USGFAULTPENDED Position */ #define SCB_SHCSR_USGFAULTPENDED_Msk (1UL << SCB_SHCSR_USGFAULTPENDED_Pos) /*!< SCB SHCSR: USGFAULTPENDED Mask */ #define SCB_SHCSR_SYSTICKACT_Pos 11 /*!< SCB SHCSR: SYSTICKACT Position */ #define SCB_SHCSR_SYSTICKACT_Msk (1UL << SCB_SHCSR_SYSTICKACT_Pos) /*!< SCB SHCSR: SYSTICKACT Mask */ #define SCB_SHCSR_PENDSVACT_Pos 10 /*!< SCB SHCSR: PENDSVACT Position */ #define SCB_SHCSR_PENDSVACT_Msk (1UL << SCB_SHCSR_PENDSVACT_Pos) /*!< SCB SHCSR: PENDSVACT Mask */ #define SCB_SHCSR_MONITORACT_Pos 8 /*!< SCB SHCSR: MONITORACT Position */ #define SCB_SHCSR_MONITORACT_Msk (1UL << SCB_SHCSR_MONITORACT_Pos) /*!< SCB SHCSR: MONITORACT Mask */ #define SCB_SHCSR_SVCALLACT_Pos 7 /*!< SCB SHCSR: SVCALLACT Position */ #define SCB_SHCSR_SVCALLACT_Msk (1UL << SCB_SHCSR_SVCALLACT_Pos) /*!< SCB SHCSR: SVCALLACT Mask */ #define SCB_SHCSR_USGFAULTACT_Pos 3 /*!< SCB SHCSR: USGFAULTACT Position */ #define SCB_SHCSR_USGFAULTACT_Msk (1UL << SCB_SHCSR_USGFAULTACT_Pos) /*!< SCB SHCSR: USGFAULTACT Mask */ #define SCB_SHCSR_BUSFAULTACT_Pos 1 /*!< SCB SHCSR: BUSFAULTACT Position */ #define SCB_SHCSR_BUSFAULTACT_Msk (1UL << SCB_SHCSR_BUSFAULTACT_Pos) /*!< SCB SHCSR: BUSFAULTACT Mask */ #define SCB_SHCSR_MEMFAULTACT_Pos 0 /*!< SCB SHCSR: MEMFAULTACT Position */ #define SCB_SHCSR_MEMFAULTACT_Msk (1UL << SCB_SHCSR_MEMFAULTACT_Pos) /*!< SCB SHCSR: MEMFAULTACT Mask */ /* SCB Configurable Fault Status Registers Definitions */ #define SCB_CFSR_USGFAULTSR_Pos 16 /*!< SCB CFSR: Usage Fault Status Register Position */ #define SCB_CFSR_USGFAULTSR_Msk (0xFFFFUL << SCB_CFSR_USGFAULTSR_Pos) /*!< SCB CFSR: Usage Fault Status Register Mask */ #define SCB_CFSR_BUSFAULTSR_Pos 8 /*!< SCB CFSR: Bus Fault Status Register Position */ #define SCB_CFSR_BUSFAULTSR_Msk (0xFFUL << SCB_CFSR_BUSFAULTSR_Pos) /*!< SCB CFSR: Bus Fault Status Register Mask */ #define SCB_CFSR_MEMFAULTSR_Pos 0 /*!< SCB CFSR: Memory Manage Fault Status Register Position */ #define SCB_CFSR_MEMFAULTSR_Msk (0xFFUL << SCB_CFSR_MEMFAULTSR_Pos) /*!< SCB CFSR: Memory Manage Fault Status Register Mask */ /* SCB Hard Fault Status Registers Definitions */ #define SCB_HFSR_DEBUGEVT_Pos 31 /*!< SCB HFSR: DEBUGEVT Position */ #define SCB_HFSR_DEBUGEVT_Msk (1UL << SCB_HFSR_DEBUGEVT_Pos) /*!< SCB HFSR: DEBUGEVT Mask */ #define SCB_HFSR_FORCED_Pos 30 /*!< SCB HFSR: FORCED Position */ #define SCB_HFSR_FORCED_Msk (1UL << SCB_HFSR_FORCED_Pos) /*!< SCB HFSR: FORCED Mask */ #define SCB_HFSR_VECTTBL_Pos 1 /*!< SCB HFSR: VECTTBL Position */ #define SCB_HFSR_VECTTBL_Msk (1UL << SCB_HFSR_VECTTBL_Pos) /*!< SCB HFSR: VECTTBL Mask */ /* SCB Debug Fault Status Register Definitions */ #define SCB_DFSR_EXTERNAL_Pos 4 /*!< SCB DFSR: EXTERNAL Position */ #define SCB_DFSR_EXTERNAL_Msk (1UL << SCB_DFSR_EXTERNAL_Pos) /*!< SCB DFSR: EXTERNAL Mask */ #define SCB_DFSR_VCATCH_Pos 3 /*!< SCB DFSR: VCATCH Position */ #define SCB_DFSR_VCATCH_Msk (1UL << SCB_DFSR_VCATCH_Pos) /*!< SCB DFSR: VCATCH Mask */ #define SCB_DFSR_DWTTRAP_Pos 2 /*!< SCB DFSR: DWTTRAP Position */ #define SCB_DFSR_DWTTRAP_Msk (1UL << SCB_DFSR_DWTTRAP_Pos) /*!< SCB DFSR: DWTTRAP Mask */ #define SCB_DFSR_BKPT_Pos 1 /*!< SCB DFSR: BKPT Position */ #define SCB_DFSR_BKPT_Msk (1UL << SCB_DFSR_BKPT_Pos) /*!< SCB DFSR: BKPT Mask */ #define SCB_DFSR_HALTED_Pos 0 /*!< SCB DFSR: HALTED Position */ #define SCB_DFSR_HALTED_Msk (1UL << SCB_DFSR_HALTED_Pos) /*!< SCB DFSR: HALTED Mask */ /*@} end of group CMSIS_SCB */ /** \ingroup CMSIS_core_register \defgroup CMSIS_SCnSCB System Controls not in SCB (SCnSCB) \brief Type definitions for the System Control and ID Register not in the SCB @{ */ /** \brief Structure type to access the System Control and ID Register not in the SCB. */ typedef struct { uint32_t RESERVED0[1]; __I uint32_t ICTR; /*!< Offset: 0x004 (R/ ) Interrupt Controller Type Register */ #if ((defined __CM3_REV) && (__CM3_REV >= 0x200)) __IO uint32_t ACTLR; /*!< Offset: 0x008 (R/W) Auxiliary Control Register */ #else uint32_t RESERVED1[1]; #endif } SCnSCB_Type; /* Interrupt Controller Type Register Definitions */ #define SCnSCB_ICTR_INTLINESNUM_Pos 0 /*!< ICTR: INTLINESNUM Position */ #define SCnSCB_ICTR_INTLINESNUM_Msk (0xFUL << SCnSCB_ICTR_INTLINESNUM_Pos) /*!< ICTR: INTLINESNUM Mask */ /* Auxiliary Control Register Definitions */ #define SCnSCB_ACTLR_DISFOLD_Pos 2 /*!< ACTLR: DISFOLD Position */ #define SCnSCB_ACTLR_DISFOLD_Msk (1UL << SCnSCB_ACTLR_DISFOLD_Pos) /*!< ACTLR: DISFOLD Mask */ #define SCnSCB_ACTLR_DISDEFWBUF_Pos 1 /*!< ACTLR: DISDEFWBUF Position */ #define SCnSCB_ACTLR_DISDEFWBUF_Msk (1UL << SCnSCB_ACTLR_DISDEFWBUF_Pos) /*!< ACTLR: DISDEFWBUF Mask */ #define SCnSCB_ACTLR_DISMCYCINT_Pos 0 /*!< ACTLR: DISMCYCINT Position */ #define SCnSCB_ACTLR_DISMCYCINT_Msk (1UL << SCnSCB_ACTLR_DISMCYCINT_Pos) /*!< ACTLR: DISMCYCINT Mask */ /*@} end of group CMSIS_SCnotSCB */ /** \ingroup CMSIS_core_register \defgroup CMSIS_SysTick System Tick Timer (SysTick) \brief Type definitions for the System Timer Registers. @{ */ /** \brief Structure type to access the System Timer (SysTick). */ typedef struct { __IO uint32_t CTRL; /*!< Offset: 0x000 (R/W) SysTick Control and Status Register */ __IO uint32_t LOAD; /*!< Offset: 0x004 (R/W) SysTick Reload Value Register */ __IO uint32_t VAL; /*!< Offset: 0x008 (R/W) SysTick Current Value Register */ __I uint32_t CALIB; /*!< Offset: 0x00C (R/ ) SysTick Calibration Register */ } SysTick_Type; /* SysTick Control / Status Register Definitions */ #define SysTick_CTRL_COUNTFLAG_Pos 16 /*!< SysTick CTRL: COUNTFLAG Position */ #define SysTick_CTRL_COUNTFLAG_Msk (1UL << SysTick_CTRL_COUNTFLAG_Pos) /*!< SysTick CTRL: COUNTFLAG Mask */ #define SysTick_CTRL_CLKSOURCE_Pos 2 /*!< SysTick CTRL: CLKSOURCE Position */ #define SysTick_CTRL_CLKSOURCE_Msk (1UL << SysTick_CTRL_CLKSOURCE_Pos) /*!< SysTick CTRL: CLKSOURCE Mask */ #define SysTick_CTRL_TICKINT_Pos 1 /*!< SysTick CTRL: TICKINT Position */ #define SysTick_CTRL_TICKINT_Msk (1UL << SysTick_CTRL_TICKINT_Pos) /*!< SysTick CTRL: TICKINT Mask */ #define SysTick_CTRL_ENABLE_Pos 0 /*!< SysTick CTRL: ENABLE Position */ #define SysTick_CTRL_ENABLE_Msk (1UL << SysTick_CTRL_ENABLE_Pos) /*!< SysTick CTRL: ENABLE Mask */ /* SysTick Reload Register Definitions */ #define SysTick_LOAD_RELOAD_Pos 0 /*!< SysTick LOAD: RELOAD Position */ #define SysTick_LOAD_RELOAD_Msk (0xFFFFFFUL << SysTick_LOAD_RELOAD_Pos) /*!< SysTick LOAD: RELOAD Mask */ /* SysTick Current Register Definitions */ #define SysTick_VAL_CURRENT_Pos 0 /*!< SysTick VAL: CURRENT Position */ #define SysTick_VAL_CURRENT_Msk (0xFFFFFFUL << SysTick_VAL_CURRENT_Pos) /*!< SysTick VAL: CURRENT Mask */ /* SysTick Calibration Register Definitions */ #define SysTick_CALIB_NOREF_Pos 31 /*!< SysTick CALIB: NOREF Position */ #define SysTick_CALIB_NOREF_Msk (1UL << SysTick_CALIB_NOREF_Pos) /*!< SysTick CALIB: NOREF Mask */ #define SysTick_CALIB_SKEW_Pos 30 /*!< SysTick CALIB: SKEW Position */ #define SysTick_CALIB_SKEW_Msk (1UL << SysTick_CALIB_SKEW_Pos) /*!< SysTick CALIB: SKEW Mask */ #define SysTick_CALIB_TENMS_Pos 0 /*!< SysTick CALIB: TENMS Position */ #define SysTick_CALIB_TENMS_Msk (0xFFFFFFUL << SysTick_VAL_CURRENT_Pos) /*!< SysTick CALIB: TENMS Mask */ /*@} end of group CMSIS_SysTick */ /** \ingroup CMSIS_core_register \defgroup CMSIS_ITM Instrumentation Trace Macrocell (ITM) \brief Type definitions for the Instrumentation Trace Macrocell (ITM) @{ */ /** \brief Structure type to access the Instrumentation Trace Macrocell Register (ITM). */ typedef struct { __O union { __O uint8_t u8; /*!< Offset: 0x000 ( /W) ITM Stimulus Port 8-bit */ __O uint16_t u16; /*!< Offset: 0x000 ( /W) ITM Stimulus Port 16-bit */ __O uint32_t u32; /*!< Offset: 0x000 ( /W) ITM Stimulus Port 32-bit */ } PORT [32]; /*!< Offset: 0x000 ( /W) ITM Stimulus Port Registers */ uint32_t RESERVED0[864]; __IO uint32_t TER; /*!< Offset: 0xE00 (R/W) ITM Trace Enable Register */ uint32_t RESERVED1[15]; __IO uint32_t TPR; /*!< Offset: 0xE40 (R/W) ITM Trace Privilege Register */ uint32_t RESERVED2[15]; __IO uint32_t TCR; /*!< Offset: 0xE80 (R/W) ITM Trace Control Register */ uint32_t RESERVED3[29]; __O uint32_t IWR; /*!< Offset: 0xEF8 ( /W) ITM Integration Write Register */ __I uint32_t IRR; /*!< Offset: 0xEFC (R/ ) ITM Integration Read Register */ __IO uint32_t IMCR; /*!< Offset: 0xF00 (R/W) ITM Integration Mode Control Register */ uint32_t RESERVED4[43]; __O uint32_t LAR; /*!< Offset: 0xFB0 ( /W) ITM Lock Access Register */ __I uint32_t LSR; /*!< Offset: 0xFB4 (R/ ) ITM Lock Status Register */ uint32_t RESERVED5[6]; __I uint32_t PID4; /*!< Offset: 0xFD0 (R/ ) ITM Peripheral Identification Register #4 */ __I uint32_t PID5; /*!< Offset: 0xFD4 (R/ ) ITM Peripheral Identification Register #5 */ __I uint32_t PID6; /*!< Offset: 0xFD8 (R/ ) ITM Peripheral Identification Register #6 */ __I uint32_t PID7; /*!< Offset: 0xFDC (R/ ) ITM Peripheral Identification Register #7 */ __I uint32_t PID0; /*!< Offset: 0xFE0 (R/ ) ITM Peripheral Identification Register #0 */ __I uint32_t PID1; /*!< Offset: 0xFE4 (R/ ) ITM Peripheral Identification Register #1 */ __I uint32_t PID2; /*!< Offset: 0xFE8 (R/ ) ITM Peripheral Identification Register #2 */ __I uint32_t PID3; /*!< Offset: 0xFEC (R/ ) ITM Peripheral Identification Register #3 */ __I uint32_t CID0; /*!< Offset: 0xFF0 (R/ ) ITM Component Identification Register #0 */ __I uint32_t CID1; /*!< Offset: 0xFF4 (R/ ) ITM Component Identification Register #1 */ __I uint32_t CID2; /*!< Offset: 0xFF8 (R/ ) ITM Component Identification Register #2 */ __I uint32_t CID3; /*!< Offset: 0xFFC (R/ ) ITM Component Identification Register #3 */ } ITM_Type; /* ITM Trace Privilege Register Definitions */ #define ITM_TPR_PRIVMASK_Pos 0 /*!< ITM TPR: PRIVMASK Position */ #define ITM_TPR_PRIVMASK_Msk (0xFUL << ITM_TPR_PRIVMASK_Pos) /*!< ITM TPR: PRIVMASK Mask */ /* ITM Trace Control Register Definitions */ #define ITM_TCR_BUSY_Pos 23 /*!< ITM TCR: BUSY Position */ #define ITM_TCR_BUSY_Msk (1UL << ITM_TCR_BUSY_Pos) /*!< ITM TCR: BUSY Mask */ #define ITM_TCR_TraceBusID_Pos 16 /*!< ITM TCR: ATBID Position */ #define ITM_TCR_TraceBusID_Msk (0x7FUL << ITM_TCR_TraceBusID_Pos) /*!< ITM TCR: ATBID Mask */ #define ITM_TCR_GTSFREQ_Pos 10 /*!< ITM TCR: Global timestamp frequency Position */ #define ITM_TCR_GTSFREQ_Msk (3UL << ITM_TCR_GTSFREQ_Pos) /*!< ITM TCR: Global timestamp frequency Mask */ #define ITM_TCR_TSPrescale_Pos 8 /*!< ITM TCR: TSPrescale Position */ #define ITM_TCR_TSPrescale_Msk (3UL << ITM_TCR_TSPrescale_Pos) /*!< ITM TCR: TSPrescale Mask */ #define ITM_TCR_SWOENA_Pos 4 /*!< ITM TCR: SWOENA Position */ #define ITM_TCR_SWOENA_Msk (1UL << ITM_TCR_SWOENA_Pos) /*!< ITM TCR: SWOENA Mask */ #define ITM_TCR_DWTENA_Pos 3 /*!< ITM TCR: DWTENA Position */ #define ITM_TCR_DWTENA_Msk (1UL << ITM_TCR_DWTENA_Pos) /*!< ITM TCR: DWTENA Mask */ #define ITM_TCR_SYNCENA_Pos 2 /*!< ITM TCR: SYNCENA Position */ #define ITM_TCR_SYNCENA_Msk (1UL << ITM_TCR_SYNCENA_Pos) /*!< ITM TCR: SYNCENA Mask */ #define ITM_TCR_TSENA_Pos 1 /*!< ITM TCR: TSENA Position */ #define ITM_TCR_TSENA_Msk (1UL << ITM_TCR_TSENA_Pos) /*!< ITM TCR: TSENA Mask */ #define ITM_TCR_ITMENA_Pos 0 /*!< ITM TCR: ITM Enable bit Position */ #define ITM_TCR_ITMENA_Msk (1UL << ITM_TCR_ITMENA_Pos) /*!< ITM TCR: ITM Enable bit Mask */ /* ITM Integration Write Register Definitions */ #define ITM_IWR_ATVALIDM_Pos 0 /*!< ITM IWR: ATVALIDM Position */ #define ITM_IWR_ATVALIDM_Msk (1UL << ITM_IWR_ATVALIDM_Pos) /*!< ITM IWR: ATVALIDM Mask */ /* ITM Integration Read Register Definitions */ #define ITM_IRR_ATREADYM_Pos 0 /*!< ITM IRR: ATREADYM Position */ #define ITM_IRR_ATREADYM_Msk (1UL << ITM_IRR_ATREADYM_Pos) /*!< ITM IRR: ATREADYM Mask */ /* ITM Integration Mode Control Register Definitions */ #define ITM_IMCR_INTEGRATION_Pos 0 /*!< ITM IMCR: INTEGRATION Position */ #define ITM_IMCR_INTEGRATION_Msk (1UL << ITM_IMCR_INTEGRATION_Pos) /*!< ITM IMCR: INTEGRATION Mask */ /* ITM Lock Status Register Definitions */ #define ITM_LSR_ByteAcc_Pos 2 /*!< ITM LSR: ByteAcc Position */ #define ITM_LSR_ByteAcc_Msk (1UL << ITM_LSR_ByteAcc_Pos) /*!< ITM LSR: ByteAcc Mask */ #define ITM_LSR_Access_Pos 1 /*!< ITM LSR: Access Position */ #define ITM_LSR_Access_Msk (1UL << ITM_LSR_Access_Pos) /*!< ITM LSR: Access Mask */ #define ITM_LSR_Present_Pos 0 /*!< ITM LSR: Present Position */ #define ITM_LSR_Present_Msk (1UL << ITM_LSR_Present_Pos) /*!< ITM LSR: Present Mask */ /*@}*/ /* end of group CMSIS_ITM */ /** \ingroup CMSIS_core_register \defgroup CMSIS_DWT Data Watchpoint and Trace (DWT) \brief Type definitions for the Data Watchpoint and Trace (DWT) @{ */ /** \brief Structure type to access the Data Watchpoint and Trace Register (DWT). */ typedef struct { __IO uint32_t CTRL; /*!< Offset: 0x000 (R/W) Control Register */ __IO uint32_t CYCCNT; /*!< Offset: 0x004 (R/W) Cycle Count Register */ __IO uint32_t CPICNT; /*!< Offset: 0x008 (R/W) CPI Count Register */ __IO uint32_t EXCCNT; /*!< Offset: 0x00C (R/W) Exception Overhead Count Register */ __IO uint32_t SLEEPCNT; /*!< Offset: 0x010 (R/W) Sleep Count Register */ __IO uint32_t LSUCNT; /*!< Offset: 0x014 (R/W) LSU Count Register */ __IO uint32_t FOLDCNT; /*!< Offset: 0x018 (R/W) Folded-instruction Count Register */ __I uint32_t PCSR; /*!< Offset: 0x01C (R/ ) Program Counter Sample Register */ __IO uint32_t COMP0; /*!< Offset: 0x020 (R/W) Comparator Register 0 */ __IO uint32_t MASK0; /*!< Offset: 0x024 (R/W) Mask Register 0 */ __IO uint32_t FUNCTION0; /*!< Offset: 0x028 (R/W) Function Register 0 */ uint32_t RESERVED0[1]; __IO uint32_t COMP1; /*!< Offset: 0x030 (R/W) Comparator Register 1 */ __IO uint32_t MASK1; /*!< Offset: 0x034 (R/W) Mask Register 1 */ __IO uint32_t FUNCTION1; /*!< Offset: 0x038 (R/W) Function Register 1 */ uint32_t RESERVED1[1]; __IO uint32_t COMP2; /*!< Offset: 0x040 (R/W) Comparator Register 2 */ __IO uint32_t MASK2; /*!< Offset: 0x044 (R/W) Mask Register 2 */ __IO uint32_t FUNCTION2; /*!< Offset: 0x048 (R/W) Function Register 2 */ uint32_t RESERVED2[1]; __IO uint32_t COMP3; /*!< Offset: 0x050 (R/W) Comparator Register 3 */ __IO uint32_t MASK3; /*!< Offset: 0x054 (R/W) Mask Register 3 */ __IO uint32_t FUNCTION3; /*!< Offset: 0x058 (R/W) Function Register 3 */ } DWT_Type; /* DWT Control Register Definitions */ #define DWT_CTRL_NUMCOMP_Pos 28 /*!< DWT CTRL: NUMCOMP Position */ #define DWT_CTRL_NUMCOMP_Msk (0xFUL << DWT_CTRL_NUMCOMP_Pos) /*!< DWT CTRL: NUMCOMP Mask */ #define DWT_CTRL_NOTRCPKT_Pos 27 /*!< DWT CTRL: NOTRCPKT Position */ #define DWT_CTRL_NOTRCPKT_Msk (0x1UL << DWT_CTRL_NOTRCPKT_Pos) /*!< DWT CTRL: NOTRCPKT Mask */ #define DWT_CTRL_NOEXTTRIG_Pos 26 /*!< DWT CTRL: NOEXTTRIG Position */ #define DWT_CTRL_NOEXTTRIG_Msk (0x1UL << DWT_CTRL_NOEXTTRIG_Pos) /*!< DWT CTRL: NOEXTTRIG Mask */ #define DWT_CTRL_NOCYCCNT_Pos 25 /*!< DWT CTRL: NOCYCCNT Position */ #define DWT_CTRL_NOCYCCNT_Msk (0x1UL << DWT_CTRL_NOCYCCNT_Pos) /*!< DWT CTRL: NOCYCCNT Mask */ #define DWT_CTRL_NOPRFCNT_Pos 24 /*!< DWT CTRL: NOPRFCNT Position */ #define DWT_CTRL_NOPRFCNT_Msk (0x1UL << DWT_CTRL_NOPRFCNT_Pos) /*!< DWT CTRL: NOPRFCNT Mask */ #define DWT_CTRL_CYCEVTENA_Pos 22 /*!< DWT CTRL: CYCEVTENA Position */ #define DWT_CTRL_CYCEVTENA_Msk (0x1UL << DWT_CTRL_CYCEVTENA_Pos) /*!< DWT CTRL: CYCEVTENA Mask */ #define DWT_CTRL_FOLDEVTENA_Pos 21 /*!< DWT CTRL: FOLDEVTENA Position */ #define DWT_CTRL_FOLDEVTENA_Msk (0x1UL << DWT_CTRL_FOLDEVTENA_Pos) /*!< DWT CTRL: FOLDEVTENA Mask */ #define DWT_CTRL_LSUEVTENA_Pos 20 /*!< DWT CTRL: LSUEVTENA Position */ #define DWT_CTRL_LSUEVTENA_Msk (0x1UL << DWT_CTRL_LSUEVTENA_Pos) /*!< DWT CTRL: LSUEVTENA Mask */ #define DWT_CTRL_SLEEPEVTENA_Pos 19 /*!< DWT CTRL: SLEEPEVTENA Position */ #define DWT_CTRL_SLEEPEVTENA_Msk (0x1UL << DWT_CTRL_SLEEPEVTENA_Pos) /*!< DWT CTRL: SLEEPEVTENA Mask */ #define DWT_CTRL_EXCEVTENA_Pos 18 /*!< DWT CTRL: EXCEVTENA Position */ #define DWT_CTRL_EXCEVTENA_Msk (0x1UL << DWT_CTRL_EXCEVTENA_Pos) /*!< DWT CTRL: EXCEVTENA Mask */ #define DWT_CTRL_CPIEVTENA_Pos 17 /*!< DWT CTRL: CPIEVTENA Position */ #define DWT_CTRL_CPIEVTENA_Msk (0x1UL << DWT_CTRL_CPIEVTENA_Pos) /*!< DWT CTRL: CPIEVTENA Mask */ #define DWT_CTRL_EXCTRCENA_Pos 16 /*!< DWT CTRL: EXCTRCENA Position */ #define DWT_CTRL_EXCTRCENA_Msk (0x1UL << DWT_CTRL_EXCTRCENA_Pos) /*!< DWT CTRL: EXCTRCENA Mask */ #define DWT_CTRL_PCSAMPLENA_Pos 12 /*!< DWT CTRL: PCSAMPLENA Position */ #define DWT_CTRL_PCSAMPLENA_Msk (0x1UL << DWT_CTRL_PCSAMPLENA_Pos) /*!< DWT CTRL: PCSAMPLENA Mask */ #define DWT_CTRL_SYNCTAP_Pos 10 /*!< DWT CTRL: SYNCTAP Position */ #define DWT_CTRL_SYNCTAP_Msk (0x3UL << DWT_CTRL_SYNCTAP_Pos) /*!< DWT CTRL: SYNCTAP Mask */ #define DWT_CTRL_CYCTAP_Pos 9 /*!< DWT CTRL: CYCTAP Position */ #define DWT_CTRL_CYCTAP_Msk (0x1UL << DWT_CTRL_CYCTAP_Pos) /*!< DWT CTRL: CYCTAP Mask */ #define DWT_CTRL_POSTINIT_Pos 5 /*!< DWT CTRL: POSTINIT Position */ #define DWT_CTRL_POSTINIT_Msk (0xFUL << DWT_CTRL_POSTINIT_Pos) /*!< DWT CTRL: POSTINIT Mask */ #define DWT_CTRL_POSTPRESET_Pos 1 /*!< DWT CTRL: POSTPRESET Position */ #define DWT_CTRL_POSTPRESET_Msk (0xFUL << DWT_CTRL_POSTPRESET_Pos) /*!< DWT CTRL: POSTPRESET Mask */ #define DWT_CTRL_CYCCNTENA_Pos 0 /*!< DWT CTRL: CYCCNTENA Position */ #define DWT_CTRL_CYCCNTENA_Msk (0x1UL << DWT_CTRL_CYCCNTENA_Pos) /*!< DWT CTRL: CYCCNTENA Mask */ /* DWT CPI Count Register Definitions */ #define DWT_CPICNT_CPICNT_Pos 0 /*!< DWT CPICNT: CPICNT Position */ #define DWT_CPICNT_CPICNT_Msk (0xFFUL << DWT_CPICNT_CPICNT_Pos) /*!< DWT CPICNT: CPICNT Mask */ /* DWT Exception Overhead Count Register Definitions */ #define DWT_EXCCNT_EXCCNT_Pos 0 /*!< DWT EXCCNT: EXCCNT Position */ #define DWT_EXCCNT_EXCCNT_Msk (0xFFUL << DWT_EXCCNT_EXCCNT_Pos) /*!< DWT EXCCNT: EXCCNT Mask */ /* DWT Sleep Count Register Definitions */ #define DWT_SLEEPCNT_SLEEPCNT_Pos 0 /*!< DWT SLEEPCNT: SLEEPCNT Position */ #define DWT_SLEEPCNT_SLEEPCNT_Msk (0xFFUL << DWT_SLEEPCNT_SLEEPCNT_Pos) /*!< DWT SLEEPCNT: SLEEPCNT Mask */ /* DWT LSU Count Register Definitions */ #define DWT_LSUCNT_LSUCNT_Pos 0 /*!< DWT LSUCNT: LSUCNT Position */ #define DWT_LSUCNT_LSUCNT_Msk (0xFFUL << DWT_LSUCNT_LSUCNT_Pos) /*!< DWT LSUCNT: LSUCNT Mask */ /* DWT Folded-instruction Count Register Definitions */ #define DWT_FOLDCNT_FOLDCNT_Pos 0 /*!< DWT FOLDCNT: FOLDCNT Position */ #define DWT_FOLDCNT_FOLDCNT_Msk (0xFFUL << DWT_FOLDCNT_FOLDCNT_Pos) /*!< DWT FOLDCNT: FOLDCNT Mask */ /* DWT Comparator Mask Register Definitions */ #define DWT_MASK_MASK_Pos 0 /*!< DWT MASK: MASK Position */ #define DWT_MASK_MASK_Msk (0x1FUL << DWT_MASK_MASK_Pos) /*!< DWT MASK: MASK Mask */ /* DWT Comparator Function Register Definitions */ #define DWT_FUNCTION_MATCHED_Pos 24 /*!< DWT FUNCTION: MATCHED Position */ #define DWT_FUNCTION_MATCHED_Msk (0x1UL << DWT_FUNCTION_MATCHED_Pos) /*!< DWT FUNCTION: MATCHED Mask */ #define DWT_FUNCTION_DATAVADDR1_Pos 16 /*!< DWT FUNCTION: DATAVADDR1 Position */ #define DWT_FUNCTION_DATAVADDR1_Msk (0xFUL << DWT_FUNCTION_DATAVADDR1_Pos) /*!< DWT FUNCTION: DATAVADDR1 Mask */ #define DWT_FUNCTION_DATAVADDR0_Pos 12 /*!< DWT FUNCTION: DATAVADDR0 Position */ #define DWT_FUNCTION_DATAVADDR0_Msk (0xFUL << DWT_FUNCTION_DATAVADDR0_Pos) /*!< DWT FUNCTION: DATAVADDR0 Mask */ #define DWT_FUNCTION_DATAVSIZE_Pos 10 /*!< DWT FUNCTION: DATAVSIZE Position */ #define DWT_FUNCTION_DATAVSIZE_Msk (0x3UL << DWT_FUNCTION_DATAVSIZE_Pos) /*!< DWT FUNCTION: DATAVSIZE Mask */ #define DWT_FUNCTION_LNK1ENA_Pos 9 /*!< DWT FUNCTION: LNK1ENA Position */ #define DWT_FUNCTION_LNK1ENA_Msk (0x1UL << DWT_FUNCTION_LNK1ENA_Pos) /*!< DWT FUNCTION: LNK1ENA Mask */ #define DWT_FUNCTION_DATAVMATCH_Pos 8 /*!< DWT FUNCTION: DATAVMATCH Position */ #define DWT_FUNCTION_DATAVMATCH_Msk (0x1UL << DWT_FUNCTION_DATAVMATCH_Pos) /*!< DWT FUNCTION: DATAVMATCH Mask */ #define DWT_FUNCTION_CYCMATCH_Pos 7 /*!< DWT FUNCTION: CYCMATCH Position */ #define DWT_FUNCTION_CYCMATCH_Msk (0x1UL << DWT_FUNCTION_CYCMATCH_Pos) /*!< DWT FUNCTION: CYCMATCH Mask */ #define DWT_FUNCTION_EMITRANGE_Pos 5 /*!< DWT FUNCTION: EMITRANGE Position */ #define DWT_FUNCTION_EMITRANGE_Msk (0x1UL << DWT_FUNCTION_EMITRANGE_Pos) /*!< DWT FUNCTION: EMITRANGE Mask */ #define DWT_FUNCTION_FUNCTION_Pos 0 /*!< DWT FUNCTION: FUNCTION Position */ #define DWT_FUNCTION_FUNCTION_Msk (0xFUL << DWT_FUNCTION_FUNCTION_Pos) /*!< DWT FUNCTION: FUNCTION Mask */ /*@}*/ /* end of group CMSIS_DWT */ /** \ingroup CMSIS_core_register \defgroup CMSIS_TPI Trace Port Interface (TPI) \brief Type definitions for the Trace Port Interface (TPI) @{ */ /** \brief Structure type to access the Trace Port Interface Register (TPI). */ typedef struct { __IO uint32_t SSPSR; /*!< Offset: 0x000 (R/ ) Supported Parallel Port Size Register */ __IO uint32_t CSPSR; /*!< Offset: 0x004 (R/W) Current Parallel Port Size Register */ uint32_t RESERVED0[2]; __IO uint32_t ACPR; /*!< Offset: 0x010 (R/W) Asynchronous Clock Prescaler Register */ uint32_t RESERVED1[55]; __IO uint32_t SPPR; /*!< Offset: 0x0F0 (R/W) Selected Pin Protocol Register */ uint32_t RESERVED2[131]; __I uint32_t FFSR; /*!< Offset: 0x300 (R/ ) Formatter and Flush Status Register */ __IO uint32_t FFCR; /*!< Offset: 0x304 (R/W) Formatter and Flush Control Register */ __I uint32_t FSCR; /*!< Offset: 0x308 (R/ ) Formatter Synchronization Counter Register */ uint32_t RESERVED3[759]; __I uint32_t TRIGGER; /*!< Offset: 0xEE8 (R/ ) TRIGGER */ __I uint32_t FIFO0; /*!< Offset: 0xEEC (R/ ) Integration ETM Data */ __I uint32_t ITATBCTR2; /*!< Offset: 0xEF0 (R/ ) ITATBCTR2 */ uint32_t RESERVED4[1]; __I uint32_t ITATBCTR0; /*!< Offset: 0xEF8 (R/ ) ITATBCTR0 */ __I uint32_t FIFO1; /*!< Offset: 0xEFC (R/ ) Integration ITM Data */ __IO uint32_t ITCTRL; /*!< Offset: 0xF00 (R/W) Integration Mode Control */ uint32_t RESERVED5[39]; __IO uint32_t CLAIMSET; /*!< Offset: 0xFA0 (R/W) Claim tag set */ __IO uint32_t CLAIMCLR; /*!< Offset: 0xFA4 (R/W) Claim tag clear */ uint32_t RESERVED7[8]; __I uint32_t DEVID; /*!< Offset: 0xFC8 (R/ ) TPIU_DEVID */ __I uint32_t DEVTYPE; /*!< Offset: 0xFCC (R/ ) TPIU_DEVTYPE */ } TPI_Type; /* TPI Asynchronous Clock Prescaler Register Definitions */ #define TPI_ACPR_PRESCALER_Pos 0 /*!< TPI ACPR: PRESCALER Position */ #define TPI_ACPR_PRESCALER_Msk (0x1FFFUL << TPI_ACPR_PRESCALER_Pos) /*!< TPI ACPR: PRESCALER Mask */ /* TPI Selected Pin Protocol Register Definitions */ #define TPI_SPPR_TXMODE_Pos 0 /*!< TPI SPPR: TXMODE Position */ #define TPI_SPPR_TXMODE_Msk (0x3UL << TPI_SPPR_TXMODE_Pos) /*!< TPI SPPR: TXMODE Mask */ /* TPI Formatter and Flush Status Register Definitions */ #define TPI_FFSR_FtNonStop_Pos 3 /*!< TPI FFSR: FtNonStop Position */ #define TPI_FFSR_FtNonStop_Msk (0x1UL << TPI_FFSR_FtNonStop_Pos) /*!< TPI FFSR: FtNonStop Mask */ #define TPI_FFSR_TCPresent_Pos 2 /*!< TPI FFSR: TCPresent Position */ #define TPI_FFSR_TCPresent_Msk (0x1UL << TPI_FFSR_TCPresent_Pos) /*!< TPI FFSR: TCPresent Mask */ #define TPI_FFSR_FtStopped_Pos 1 /*!< TPI FFSR: FtStopped Position */ #define TPI_FFSR_FtStopped_Msk (0x1UL << TPI_FFSR_FtStopped_Pos) /*!< TPI FFSR: FtStopped Mask */ #define TPI_FFSR_FlInProg_Pos 0 /*!< TPI FFSR: FlInProg Position */ #define TPI_FFSR_FlInProg_Msk (0x1UL << TPI_FFSR_FlInProg_Pos) /*!< TPI FFSR: FlInProg Mask */ /* TPI Formatter and Flush Control Register Definitions */ #define TPI_FFCR_TrigIn_Pos 8 /*!< TPI FFCR: TrigIn Position */ #define TPI_FFCR_TrigIn_Msk (0x1UL << TPI_FFCR_TrigIn_Pos) /*!< TPI FFCR: TrigIn Mask */ #define TPI_FFCR_EnFCont_Pos 1 /*!< TPI FFCR: EnFCont Position */ #define TPI_FFCR_EnFCont_Msk (0x1UL << TPI_FFCR_EnFCont_Pos) /*!< TPI FFCR: EnFCont Mask */ /* TPI TRIGGER Register Definitions */ #define TPI_TRIGGER_TRIGGER_Pos 0 /*!< TPI TRIGGER: TRIGGER Position */ #define TPI_TRIGGER_TRIGGER_Msk (0x1UL << TPI_TRIGGER_TRIGGER_Pos) /*!< TPI TRIGGER: TRIGGER Mask */ /* TPI Integration ETM Data Register Definitions (FIFO0) */ #define TPI_FIFO0_ITM_ATVALID_Pos 29 /*!< TPI FIFO0: ITM_ATVALID Position */ #define TPI_FIFO0_ITM_ATVALID_Msk (0x3UL << TPI_FIFO0_ITM_ATVALID_Pos) /*!< TPI FIFO0: ITM_ATVALID Mask */ #define TPI_FIFO0_ITM_bytecount_Pos 27 /*!< TPI FIFO0: ITM_bytecount Position */ #define TPI_FIFO0_ITM_bytecount_Msk (0x3UL << TPI_FIFO0_ITM_bytecount_Pos) /*!< TPI FIFO0: ITM_bytecount Mask */ #define TPI_FIFO0_ETM_ATVALID_Pos 26 /*!< TPI FIFO0: ETM_ATVALID Position */ #define TPI_FIFO0_ETM_ATVALID_Msk (0x3UL << TPI_FIFO0_ETM_ATVALID_Pos) /*!< TPI FIFO0: ETM_ATVALID Mask */ #define TPI_FIFO0_ETM_bytecount_Pos 24 /*!< TPI FIFO0: ETM_bytecount Position */ #define TPI_FIFO0_ETM_bytecount_Msk (0x3UL << TPI_FIFO0_ETM_bytecount_Pos) /*!< TPI FIFO0: ETM_bytecount Mask */ #define TPI_FIFO0_ETM2_Pos 16 /*!< TPI FIFO0: ETM2 Position */ #define TPI_FIFO0_ETM2_Msk (0xFFUL << TPI_FIFO0_ETM2_Pos) /*!< TPI FIFO0: ETM2 Mask */ #define TPI_FIFO0_ETM1_Pos 8 /*!< TPI FIFO0: ETM1 Position */ #define TPI_FIFO0_ETM1_Msk (0xFFUL << TPI_FIFO0_ETM1_Pos) /*!< TPI FIFO0: ETM1 Mask */ #define TPI_FIFO0_ETM0_Pos 0 /*!< TPI FIFO0: ETM0 Position */ #define TPI_FIFO0_ETM0_Msk (0xFFUL << TPI_FIFO0_ETM0_Pos) /*!< TPI FIFO0: ETM0 Mask */ /* TPI ITATBCTR2 Register Definitions */ #define TPI_ITATBCTR2_ATREADY_Pos 0 /*!< TPI ITATBCTR2: ATREADY Position */ #define TPI_ITATBCTR2_ATREADY_Msk (0x1UL << TPI_ITATBCTR2_ATREADY_Pos) /*!< TPI ITATBCTR2: ATREADY Mask */ /* TPI Integration ITM Data Register Definitions (FIFO1) */ #define TPI_FIFO1_ITM_ATVALID_Pos 29 /*!< TPI FIFO1: ITM_ATVALID Position */ #define TPI_FIFO1_ITM_ATVALID_Msk (0x3UL << TPI_FIFO1_ITM_ATVALID_Pos) /*!< TPI FIFO1: ITM_ATVALID Mask */ #define TPI_FIFO1_ITM_bytecount_Pos 27 /*!< TPI FIFO1: ITM_bytecount Position */ #define TPI_FIFO1_ITM_bytecount_Msk (0x3UL << TPI_FIFO1_ITM_bytecount_Pos) /*!< TPI FIFO1: ITM_bytecount Mask */ #define TPI_FIFO1_ETM_ATVALID_Pos 26 /*!< TPI FIFO1: ETM_ATVALID Position */ #define TPI_FIFO1_ETM_ATVALID_Msk (0x3UL << TPI_FIFO1_ETM_ATVALID_Pos) /*!< TPI FIFO1: ETM_ATVALID Mask */ #define TPI_FIFO1_ETM_bytecount_Pos 24 /*!< TPI FIFO1: ETM_bytecount Position */ #define TPI_FIFO1_ETM_bytecount_Msk (0x3UL << TPI_FIFO1_ETM_bytecount_Pos) /*!< TPI FIFO1: ETM_bytecount Mask */ #define TPI_FIFO1_ITM2_Pos 16 /*!< TPI FIFO1: ITM2 Position */ #define TPI_FIFO1_ITM2_Msk (0xFFUL << TPI_FIFO1_ITM2_Pos) /*!< TPI FIFO1: ITM2 Mask */ #define TPI_FIFO1_ITM1_Pos 8 /*!< TPI FIFO1: ITM1 Position */ #define TPI_FIFO1_ITM1_Msk (0xFFUL << TPI_FIFO1_ITM1_Pos) /*!< TPI FIFO1: ITM1 Mask */ #define TPI_FIFO1_ITM0_Pos 0 /*!< TPI FIFO1: ITM0 Position */ #define TPI_FIFO1_ITM0_Msk (0xFFUL << TPI_FIFO1_ITM0_Pos) /*!< TPI FIFO1: ITM0 Mask */ /* TPI ITATBCTR0 Register Definitions */ #define TPI_ITATBCTR0_ATREADY_Pos 0 /*!< TPI ITATBCTR0: ATREADY Position */ #define TPI_ITATBCTR0_ATREADY_Msk (0x1UL << TPI_ITATBCTR0_ATREADY_Pos) /*!< TPI ITATBCTR0: ATREADY Mask */ /* TPI Integration Mode Control Register Definitions */ #define TPI_ITCTRL_Mode_Pos 0 /*!< TPI ITCTRL: Mode Position */ #define TPI_ITCTRL_Mode_Msk (0x1UL << TPI_ITCTRL_Mode_Pos) /*!< TPI ITCTRL: Mode Mask */ /* TPI DEVID Register Definitions */ #define TPI_DEVID_NRZVALID_Pos 11 /*!< TPI DEVID: NRZVALID Position */ #define TPI_DEVID_NRZVALID_Msk (0x1UL << TPI_DEVID_NRZVALID_Pos) /*!< TPI DEVID: NRZVALID Mask */ #define TPI_DEVID_MANCVALID_Pos 10 /*!< TPI DEVID: MANCVALID Position */ #define TPI_DEVID_MANCVALID_Msk (0x1UL << TPI_DEVID_MANCVALID_Pos) /*!< TPI DEVID: MANCVALID Mask */ #define TPI_DEVID_PTINVALID_Pos 9 /*!< TPI DEVID: PTINVALID Position */ #define TPI_DEVID_PTINVALID_Msk (0x1UL << TPI_DEVID_PTINVALID_Pos) /*!< TPI DEVID: PTINVALID Mask */ #define TPI_DEVID_MinBufSz_Pos 6 /*!< TPI DEVID: MinBufSz Position */ #define TPI_DEVID_MinBufSz_Msk (0x7UL << TPI_DEVID_MinBufSz_Pos) /*!< TPI DEVID: MinBufSz Mask */ #define TPI_DEVID_AsynClkIn_Pos 5 /*!< TPI DEVID: AsynClkIn Position */ #define TPI_DEVID_AsynClkIn_Msk (0x1UL << TPI_DEVID_AsynClkIn_Pos) /*!< TPI DEVID: AsynClkIn Mask */ #define TPI_DEVID_NrTraceInput_Pos 0 /*!< TPI DEVID: NrTraceInput Position */ #define TPI_DEVID_NrTraceInput_Msk (0x1FUL << TPI_DEVID_NrTraceInput_Pos) /*!< TPI DEVID: NrTraceInput Mask */ /* TPI DEVTYPE Register Definitions */ #define TPI_DEVTYPE_SubType_Pos 0 /*!< TPI DEVTYPE: SubType Position */ #define TPI_DEVTYPE_SubType_Msk (0xFUL << TPI_DEVTYPE_SubType_Pos) /*!< TPI DEVTYPE: SubType Mask */ #define TPI_DEVTYPE_MajorType_Pos 4 /*!< TPI DEVTYPE: MajorType Position */ #define TPI_DEVTYPE_MajorType_Msk (0xFUL << TPI_DEVTYPE_MajorType_Pos) /*!< TPI DEVTYPE: MajorType Mask */ /*@}*/ /* end of group CMSIS_TPI */ #if (__MPU_PRESENT == 1) /** \ingroup CMSIS_core_register \defgroup CMSIS_MPU Memory Protection Unit (MPU) \brief Type definitions for the Memory Protection Unit (MPU) @{ */ /** \brief Structure type to access the Memory Protection Unit (MPU). */ typedef struct { __I uint32_t TYPE; /*!< Offset: 0x000 (R/ ) MPU Type Register */ __IO uint32_t CTRL; /*!< Offset: 0x004 (R/W) MPU Control Register */ __IO uint32_t RNR; /*!< Offset: 0x008 (R/W) MPU Region RNRber Register */ __IO uint32_t RBAR; /*!< Offset: 0x00C (R/W) MPU Region Base Address Register */ __IO uint32_t RASR; /*!< Offset: 0x010 (R/W) MPU Region Attribute and Size Register */ __IO uint32_t RBAR_A1; /*!< Offset: 0x014 (R/W) MPU Alias 1 Region Base Address Register */ __IO uint32_t RASR_A1; /*!< Offset: 0x018 (R/W) MPU Alias 1 Region Attribute and Size Register */ __IO uint32_t RBAR_A2; /*!< Offset: 0x01C (R/W) MPU Alias 2 Region Base Address Register */ __IO uint32_t RASR_A2; /*!< Offset: 0x020 (R/W) MPU Alias 2 Region Attribute and Size Register */ __IO uint32_t RBAR_A3; /*!< Offset: 0x024 (R/W) MPU Alias 3 Region Base Address Register */ __IO uint32_t RASR_A3; /*!< Offset: 0x028 (R/W) MPU Alias 3 Region Attribute and Size Register */ } MPU_Type; /* MPU Type Register */ #define MPU_TYPE_IREGION_Pos 16 /*!< MPU TYPE: IREGION Position */ #define MPU_TYPE_IREGION_Msk (0xFFUL << MPU_TYPE_IREGION_Pos) /*!< MPU TYPE: IREGION Mask */ #define MPU_TYPE_DREGION_Pos 8 /*!< MPU TYPE: DREGION Position */ #define MPU_TYPE_DREGION_Msk (0xFFUL << MPU_TYPE_DREGION_Pos) /*!< MPU TYPE: DREGION Mask */ #define MPU_TYPE_SEPARATE_Pos 0 /*!< MPU TYPE: SEPARATE Position */ #define MPU_TYPE_SEPARATE_Msk (1UL << MPU_TYPE_SEPARATE_Pos) /*!< MPU TYPE: SEPARATE Mask */ /* MPU Control Register */ #define MPU_CTRL_PRIVDEFENA_Pos 2 /*!< MPU CTRL: PRIVDEFENA Position */ #define MPU_CTRL_PRIVDEFENA_Msk (1UL << MPU_CTRL_PRIVDEFENA_Pos) /*!< MPU CTRL: PRIVDEFENA Mask */ #define MPU_CTRL_HFNMIENA_Pos 1 /*!< MPU CTRL: HFNMIENA Position */ #define MPU_CTRL_HFNMIENA_Msk (1UL << MPU_CTRL_HFNMIENA_Pos) /*!< MPU CTRL: HFNMIENA Mask */ #define MPU_CTRL_ENABLE_Pos 0 /*!< MPU CTRL: ENABLE Position */ #define MPU_CTRL_ENABLE_Msk (1UL << MPU_CTRL_ENABLE_Pos) /*!< MPU CTRL: ENABLE Mask */ /* MPU Region Number Register */ #define MPU_RNR_REGION_Pos 0 /*!< MPU RNR: REGION Position */ #define MPU_RNR_REGION_Msk (0xFFUL << MPU_RNR_REGION_Pos) /*!< MPU RNR: REGION Mask */ /* MPU Region Base Address Register */ #define MPU_RBAR_ADDR_Pos 5 /*!< MPU RBAR: ADDR Position */ #define MPU_RBAR_ADDR_Msk (0x7FFFFFFUL << MPU_RBAR_ADDR_Pos) /*!< MPU RBAR: ADDR Mask */ #define MPU_RBAR_VALID_Pos 4 /*!< MPU RBAR: VALID Position */ #define MPU_RBAR_VALID_Msk (1UL << MPU_RBAR_VALID_Pos) /*!< MPU RBAR: VALID Mask */ #define MPU_RBAR_REGION_Pos 0 /*!< MPU RBAR: REGION Position */ #define MPU_RBAR_REGION_Msk (0xFUL << MPU_RBAR_REGION_Pos) /*!< MPU RBAR: REGION Mask */ /* MPU Region Attribute and Size Register */ #define MPU_RASR_ATTRS_Pos 16 /*!< MPU RASR: MPU Region Attribute field Position */ #define MPU_RASR_ATTRS_Msk (0xFFFFUL << MPU_RASR_ATTRS_Pos) /*!< MPU RASR: MPU Region Attribute field Mask */ #define MPU_RASR_XN_Pos 28 /*!< MPU RASR: ATTRS.XN Position */ #define MPU_RASR_XN_Msk (1UL << MPU_RASR_XN_Pos) /*!< MPU RASR: ATTRS.XN Mask */ #define MPU_RASR_AP_Pos 24 /*!< MPU RASR: ATTRS.AP Position */ #define MPU_RASR_AP_Msk (0x7UL << MPU_RASR_AP_Pos) /*!< MPU RASR: ATTRS.AP Mask */ #define MPU_RASR_TEX_Pos 19 /*!< MPU RASR: ATTRS.TEX Position */ #define MPU_RASR_TEX_Msk (0x7UL << MPU_RASR_TEX_Pos) /*!< MPU RASR: ATTRS.TEX Mask */ #define MPU_RASR_S_Pos 18 /*!< MPU RASR: ATTRS.S Position */ #define MPU_RASR_S_Msk (1UL << MPU_RASR_S_Pos) /*!< MPU RASR: ATTRS.S Mask */ #define MPU_RASR_C_Pos 17 /*!< MPU RASR: ATTRS.C Position */ #define MPU_RASR_C_Msk (1UL << MPU_RASR_C_Pos) /*!< MPU RASR: ATTRS.C Mask */ #define MPU_RASR_B_Pos 16 /*!< MPU RASR: ATTRS.B Position */ #define MPU_RASR_B_Msk (1UL << MPU_RASR_B_Pos) /*!< MPU RASR: ATTRS.B Mask */ #define MPU_RASR_SRD_Pos 8 /*!< MPU RASR: Sub-Region Disable Position */ #define MPU_RASR_SRD_Msk (0xFFUL << MPU_RASR_SRD_Pos) /*!< MPU RASR: Sub-Region Disable Mask */ #define MPU_RASR_SIZE_Pos 1 /*!< MPU RASR: Region Size Field Position */ #define MPU_RASR_SIZE_Msk (0x1FUL << MPU_RASR_SIZE_Pos) /*!< MPU RASR: Region Size Field Mask */ #define MPU_RASR_ENABLE_Pos 0 /*!< MPU RASR: Region enable bit Position */ #define MPU_RASR_ENABLE_Msk (1UL << MPU_RASR_ENABLE_Pos) /*!< MPU RASR: Region enable bit Disable Mask */ /*@} end of group CMSIS_MPU */ #endif /** \ingroup CMSIS_core_register \defgroup CMSIS_CoreDebug Core Debug Registers (CoreDebug) \brief Type definitions for the Core Debug Registers @{ */ /** \brief Structure type to access the Core Debug Register (CoreDebug). */ typedef struct { __IO uint32_t DHCSR; /*!< Offset: 0x000 (R/W) Debug Halting Control and Status Register */ __O uint32_t DCRSR; /*!< Offset: 0x004 ( /W) Debug Core Register Selector Register */ __IO uint32_t DCRDR; /*!< Offset: 0x008 (R/W) Debug Core Register Data Register */ __IO uint32_t DEMCR; /*!< Offset: 0x00C (R/W) Debug Exception and Monitor Control Register */ } CoreDebug_Type; /* Debug Halting Control and Status Register */ #define CoreDebug_DHCSR_DBGKEY_Pos 16 /*!< CoreDebug DHCSR: DBGKEY Position */ #define CoreDebug_DHCSR_DBGKEY_Msk (0xFFFFUL << CoreDebug_DHCSR_DBGKEY_Pos) /*!< CoreDebug DHCSR: DBGKEY Mask */ #define CoreDebug_DHCSR_S_RESET_ST_Pos 25 /*!< CoreDebug DHCSR: S_RESET_ST Position */ #define CoreDebug_DHCSR_S_RESET_ST_Msk (1UL << CoreDebug_DHCSR_S_RESET_ST_Pos) /*!< CoreDebug DHCSR: S_RESET_ST Mask */ #define CoreDebug_DHCSR_S_RETIRE_ST_Pos 24 /*!< CoreDebug DHCSR: S_RETIRE_ST Position */ #define CoreDebug_DHCSR_S_RETIRE_ST_Msk (1UL << CoreDebug_DHCSR_S_RETIRE_ST_Pos) /*!< CoreDebug DHCSR: S_RETIRE_ST Mask */ #define CoreDebug_DHCSR_S_LOCKUP_Pos 19 /*!< CoreDebug DHCSR: S_LOCKUP Position */ #define CoreDebug_DHCSR_S_LOCKUP_Msk (1UL << CoreDebug_DHCSR_S_LOCKUP_Pos) /*!< CoreDebug DHCSR: S_LOCKUP Mask */ #define CoreDebug_DHCSR_S_SLEEP_Pos 18 /*!< CoreDebug DHCSR: S_SLEEP Position */ #define CoreDebug_DHCSR_S_SLEEP_Msk (1UL << CoreDebug_DHCSR_S_SLEEP_Pos) /*!< CoreDebug DHCSR: S_SLEEP Mask */ #define CoreDebug_DHCSR_S_HALT_Pos 17 /*!< CoreDebug DHCSR: S_HALT Position */ #define CoreDebug_DHCSR_S_HALT_Msk (1UL << CoreDebug_DHCSR_S_HALT_Pos) /*!< CoreDebug DHCSR: S_HALT Mask */ #define CoreDebug_DHCSR_S_REGRDY_Pos 16 /*!< CoreDebug DHCSR: S_REGRDY Position */ #define CoreDebug_DHCSR_S_REGRDY_Msk (1UL << CoreDebug_DHCSR_S_REGRDY_Pos) /*!< CoreDebug DHCSR: S_REGRDY Mask */ #define CoreDebug_DHCSR_C_SNAPSTALL_Pos 5 /*!< CoreDebug DHCSR: C_SNAPSTALL Position */ #define CoreDebug_DHCSR_C_SNAPSTALL_Msk (1UL << CoreDebug_DHCSR_C_SNAPSTALL_Pos) /*!< CoreDebug DHCSR: C_SNAPSTALL Mask */ #define CoreDebug_DHCSR_C_MASKINTS_Pos 3 /*!< CoreDebug DHCSR: C_MASKINTS Position */ #define CoreDebug_DHCSR_C_MASKINTS_Msk (1UL << CoreDebug_DHCSR_C_MASKINTS_Pos) /*!< CoreDebug DHCSR: C_MASKINTS Mask */ #define CoreDebug_DHCSR_C_STEP_Pos 2 /*!< CoreDebug DHCSR: C_STEP Position */ #define CoreDebug_DHCSR_C_STEP_Msk (1UL << CoreDebug_DHCSR_C_STEP_Pos) /*!< CoreDebug DHCSR: C_STEP Mask */ #define CoreDebug_DHCSR_C_HALT_Pos 1 /*!< CoreDebug DHCSR: C_HALT Position */ #define CoreDebug_DHCSR_C_HALT_Msk (1UL << CoreDebug_DHCSR_C_HALT_Pos) /*!< CoreDebug DHCSR: C_HALT Mask */ #define CoreDebug_DHCSR_C_DEBUGEN_Pos 0 /*!< CoreDebug DHCSR: C_DEBUGEN Position */ #define CoreDebug_DHCSR_C_DEBUGEN_Msk (1UL << CoreDebug_DHCSR_C_DEBUGEN_Pos) /*!< CoreDebug DHCSR: C_DEBUGEN Mask */ /* Debug Core Register Selector Register */ #define CoreDebug_DCRSR_REGWnR_Pos 16 /*!< CoreDebug DCRSR: REGWnR Position */ #define CoreDebug_DCRSR_REGWnR_Msk (1UL << CoreDebug_DCRSR_REGWnR_Pos) /*!< CoreDebug DCRSR: REGWnR Mask */ #define CoreDebug_DCRSR_REGSEL_Pos 0 /*!< CoreDebug DCRSR: REGSEL Position */ #define CoreDebug_DCRSR_REGSEL_Msk (0x1FUL << CoreDebug_DCRSR_REGSEL_Pos) /*!< CoreDebug DCRSR: REGSEL Mask */ /* Debug Exception and Monitor Control Register */ #define CoreDebug_DEMCR_TRCENA_Pos 24 /*!< CoreDebug DEMCR: TRCENA Position */ #define CoreDebug_DEMCR_TRCENA_Msk (1UL << CoreDebug_DEMCR_TRCENA_Pos) /*!< CoreDebug DEMCR: TRCENA Mask */ #define CoreDebug_DEMCR_MON_REQ_Pos 19 /*!< CoreDebug DEMCR: MON_REQ Position */ #define CoreDebug_DEMCR_MON_REQ_Msk (1UL << CoreDebug_DEMCR_MON_REQ_Pos) /*!< CoreDebug DEMCR: MON_REQ Mask */ #define CoreDebug_DEMCR_MON_STEP_Pos 18 /*!< CoreDebug DEMCR: MON_STEP Position */ #define CoreDebug_DEMCR_MON_STEP_Msk (1UL << CoreDebug_DEMCR_MON_STEP_Pos) /*!< CoreDebug DEMCR: MON_STEP Mask */ #define CoreDebug_DEMCR_MON_PEND_Pos 17 /*!< CoreDebug DEMCR: MON_PEND Position */ #define CoreDebug_DEMCR_MON_PEND_Msk (1UL << CoreDebug_DEMCR_MON_PEND_Pos) /*!< CoreDebug DEMCR: MON_PEND Mask */ #define CoreDebug_DEMCR_MON_EN_Pos 16 /*!< CoreDebug DEMCR: MON_EN Position */ #define CoreDebug_DEMCR_MON_EN_Msk (1UL << CoreDebug_DEMCR_MON_EN_Pos) /*!< CoreDebug DEMCR: MON_EN Mask */ #define CoreDebug_DEMCR_VC_HARDERR_Pos 10 /*!< CoreDebug DEMCR: VC_HARDERR Position */ #define CoreDebug_DEMCR_VC_HARDERR_Msk (1UL << CoreDebug_DEMCR_VC_HARDERR_Pos) /*!< CoreDebug DEMCR: VC_HARDERR Mask */ #define CoreDebug_DEMCR_VC_INTERR_Pos 9 /*!< CoreDebug DEMCR: VC_INTERR Position */ #define CoreDebug_DEMCR_VC_INTERR_Msk (1UL << CoreDebug_DEMCR_VC_INTERR_Pos) /*!< CoreDebug DEMCR: VC_INTERR Mask */ #define CoreDebug_DEMCR_VC_BUSERR_Pos 8 /*!< CoreDebug DEMCR: VC_BUSERR Position */ #define CoreDebug_DEMCR_VC_BUSERR_Msk (1UL << CoreDebug_DEMCR_VC_BUSERR_Pos) /*!< CoreDebug DEMCR: VC_BUSERR Mask */ #define CoreDebug_DEMCR_VC_STATERR_Pos 7 /*!< CoreDebug DEMCR: VC_STATERR Position */ #define CoreDebug_DEMCR_VC_STATERR_Msk (1UL << CoreDebug_DEMCR_VC_STATERR_Pos) /*!< CoreDebug DEMCR: VC_STATERR Mask */ #define CoreDebug_DEMCR_VC_CHKERR_Pos 6 /*!< CoreDebug DEMCR: VC_CHKERR Position */ #define CoreDebug_DEMCR_VC_CHKERR_Msk (1UL << CoreDebug_DEMCR_VC_CHKERR_Pos) /*!< CoreDebug DEMCR: VC_CHKERR Mask */ #define CoreDebug_DEMCR_VC_NOCPERR_Pos 5 /*!< CoreDebug DEMCR: VC_NOCPERR Position */ #define CoreDebug_DEMCR_VC_NOCPERR_Msk (1UL << CoreDebug_DEMCR_VC_NOCPERR_Pos) /*!< CoreDebug DEMCR: VC_NOCPERR Mask */ #define CoreDebug_DEMCR_VC_MMERR_Pos 4 /*!< CoreDebug DEMCR: VC_MMERR Position */ #define CoreDebug_DEMCR_VC_MMERR_Msk (1UL << CoreDebug_DEMCR_VC_MMERR_Pos) /*!< CoreDebug DEMCR: VC_MMERR Mask */ #define CoreDebug_DEMCR_VC_CORERESET_Pos 0 /*!< CoreDebug DEMCR: VC_CORERESET Position */ #define CoreDebug_DEMCR_VC_CORERESET_Msk (1UL << CoreDebug_DEMCR_VC_CORERESET_Pos) /*!< CoreDebug DEMCR: VC_CORERESET Mask */ /*@} end of group CMSIS_CoreDebug */ /** \ingroup CMSIS_core_register \defgroup CMSIS_core_base Core Definitions \brief Definitions for base addresses, unions, and structures. @{ */ /* Memory mapping of Cortex-M3 Hardware */ #define SCS_BASE (0xE000E000UL) /*!< System Control Space Base Address */ #define ITM_BASE (0xE0000000UL) /*!< ITM Base Address */ #define DWT_BASE (0xE0001000UL) /*!< DWT Base Address */ #define TPI_BASE (0xE0040000UL) /*!< TPI Base Address */ #define CoreDebug_BASE (0xE000EDF0UL) /*!< Core Debug Base Address */ #define SysTick_BASE (SCS_BASE + 0x0010UL) /*!< SysTick Base Address */ #define NVIC_BASE (SCS_BASE + 0x0100UL) /*!< NVIC Base Address */ #define SCB_BASE (SCS_BASE + 0x0D00UL) /*!< System Control Block Base Address */ #define SCnSCB ((SCnSCB_Type *) SCS_BASE ) /*!< System control Register not in SCB */ #define SCB ((SCB_Type *) SCB_BASE ) /*!< SCB configuration struct */ #define SysTick ((SysTick_Type *) SysTick_BASE ) /*!< SysTick configuration struct */ #define NVIC ((NVIC_Type *) NVIC_BASE ) /*!< NVIC configuration struct */ #define ITM ((ITM_Type *) ITM_BASE ) /*!< ITM configuration struct */ #define DWT ((DWT_Type *) DWT_BASE ) /*!< DWT configuration struct */ #define TPI ((TPI_Type *) TPI_BASE ) /*!< TPI configuration struct */ #define CoreDebug ((CoreDebug_Type *) CoreDebug_BASE) /*!< Core Debug configuration struct */ #if (__MPU_PRESENT == 1) #define MPU_BASE (SCS_BASE + 0x0D90UL) /*!< Memory Protection Unit */ #define MPU ((MPU_Type *) MPU_BASE ) /*!< Memory Protection Unit */ #endif /*@} */ /******************************************************************************* * Hardware Abstraction Layer Core Function Interface contains: - Core NVIC Functions - Core SysTick Functions - Core Debug Functions - Core Register Access Functions ******************************************************************************/ /** \defgroup CMSIS_Core_FunctionInterface Functions and Instructions Reference */ /* ########################## NVIC functions #################################### */ /** \ingroup CMSIS_Core_FunctionInterface \defgroup CMSIS_Core_NVICFunctions NVIC Functions \brief Functions that manage interrupts and exceptions via the NVIC. @{ */ /** \brief Set Priority Grouping The function sets the priority grouping field using the required unlock sequence. The parameter PriorityGroup is assigned to the field SCB->AIRCR [10:8] PRIGROUP field. Only values from 0..7 are used. In case of a conflict between priority grouping and available priority bits (__NVIC_PRIO_BITS), the smallest possible priority group is set. \param [in] PriorityGroup Priority grouping field. */ __STATIC_INLINE void NVIC_SetPriorityGrouping(uint32_t PriorityGroup) { uint32_t reg_value; uint32_t PriorityGroupTmp = (PriorityGroup & (uint32_t)0x07); /* only values 0..7 are used */ reg_value = SCB->AIRCR; /* read old register configuration */ reg_value &= ~(SCB_AIRCR_VECTKEY_Msk | SCB_AIRCR_PRIGROUP_Msk); /* clear bits to change */ reg_value = (reg_value | ((uint32_t)0x5FA << SCB_AIRCR_VECTKEY_Pos) | (PriorityGroupTmp << 8)); /* Insert write key and priorty group */ SCB->AIRCR = reg_value; } /** \brief Get Priority Grouping The function reads the priority grouping field from the NVIC Interrupt Controller. \return Priority grouping field (SCB->AIRCR [10:8] PRIGROUP field). */ __STATIC_INLINE uint32_t NVIC_GetPriorityGrouping(void) { return ((SCB->AIRCR & SCB_AIRCR_PRIGROUP_Msk) >> SCB_AIRCR_PRIGROUP_Pos); /* read priority grouping field */ } /** \brief Enable External Interrupt The function enables a device-specific interrupt in the NVIC interrupt controller. \param [in] IRQn External interrupt number. Value cannot be negative. */ __STATIC_INLINE void NVIC_EnableIRQ(IRQn_Type IRQn) { NVIC->ISER[((uint32_t)(IRQn) >> 5)] = (1 << ((uint32_t)(IRQn) & 0x1F)); /* enable interrupt */ } /** \brief Disable External Interrupt The function disables a device-specific interrupt in the NVIC interrupt controller. \param [in] IRQn External interrupt number. Value cannot be negative. */ __STATIC_INLINE void NVIC_DisableIRQ(IRQn_Type IRQn) { NVIC->ICER[((uint32_t)(IRQn) >> 5)] = (1 << ((uint32_t)(IRQn) & 0x1F)); /* disable interrupt */ } /** \brief Get Pending Interrupt The function reads the pending register in the NVIC and returns the pending bit for the specified interrupt. \param [in] IRQn Interrupt number. \return 0 Interrupt status is not pending. \return 1 Interrupt status is pending. */ __STATIC_INLINE uint32_t NVIC_GetPendingIRQ(IRQn_Type IRQn) { return((uint32_t) ((NVIC->ISPR[(uint32_t)(IRQn) >> 5] & (1 << ((uint32_t)(IRQn) & 0x1F)))?1:0)); /* Return 1 if pending else 0 */ } /** \brief Set Pending Interrupt The function sets the pending bit of an external interrupt. \param [in] IRQn Interrupt number. Value cannot be negative. */ __STATIC_INLINE void NVIC_SetPendingIRQ(IRQn_Type IRQn) { NVIC->ISPR[((uint32_t)(IRQn) >> 5)] = (1 << ((uint32_t)(IRQn) & 0x1F)); /* set interrupt pending */ } /** \brief Clear Pending Interrupt The function clears the pending bit of an external interrupt. \param [in] IRQn External interrupt number. Value cannot be negative. */ __STATIC_INLINE void NVIC_ClearPendingIRQ(IRQn_Type IRQn) { NVIC->ICPR[((uint32_t)(IRQn) >> 5)] = (1 << ((uint32_t)(IRQn) & 0x1F)); /* Clear pending interrupt */ } /** \brief Get Active Interrupt The function reads the active register in NVIC and returns the active bit. \param [in] IRQn Interrupt number. \return 0 Interrupt status is not active. \return 1 Interrupt status is active. */ __STATIC_INLINE uint32_t NVIC_GetActive(IRQn_Type IRQn) { return((uint32_t)((NVIC->IABR[(uint32_t)(IRQn) >> 5] & (1 << ((uint32_t)(IRQn) & 0x1F)))?1:0)); /* Return 1 if active else 0 */ } /** \brief Set Interrupt Priority The function sets the priority of an interrupt. \note The priority cannot be set for every core interrupt. \param [in] IRQn Interrupt number. \param [in] priority Priority to set. */ __STATIC_INLINE void NVIC_SetPriority(IRQn_Type IRQn, uint32_t priority) { if(IRQn < 0) { SCB->SHP[((uint32_t)(IRQn) & 0xF)-4] = ((priority << (8 - __NVIC_PRIO_BITS)) & 0xff); } /* set Priority for Cortex-M System Interrupts */ else { NVIC->IP[(uint32_t)(IRQn)] = ((priority << (8 - __NVIC_PRIO_BITS)) & 0xff); } /* set Priority for device specific Interrupts */ } /** \brief Get Interrupt Priority The function reads the priority of an interrupt. The interrupt number can be positive to specify an external (device specific) interrupt, or negative to specify an internal (core) interrupt. \param [in] IRQn Interrupt number. \return Interrupt Priority. Value is aligned automatically to the implemented priority bits of the microcontroller. */ __STATIC_INLINE uint32_t NVIC_GetPriority(IRQn_Type IRQn) { if(IRQn < 0) { return((uint32_t)(SCB->SHP[((uint32_t)(IRQn) & 0xF)-4] >> (8 - __NVIC_PRIO_BITS))); } /* get priority for Cortex-M system interrupts */ else { return((uint32_t)(NVIC->IP[(uint32_t)(IRQn)] >> (8 - __NVIC_PRIO_BITS))); } /* get priority for device specific interrupts */ } /** \brief Encode Priority The function encodes the priority for an interrupt with the given priority group, preemptive priority value, and subpriority value. In case of a conflict between priority grouping and available priority bits (__NVIC_PRIO_BITS), the samllest possible priority group is set. \param [in] PriorityGroup Used priority group. \param [in] PreemptPriority Preemptive priority value (starting from 0). \param [in] SubPriority Subpriority value (starting from 0). \return Encoded priority. Value can be used in the function \ref NVIC_SetPriority(). */ __STATIC_INLINE uint32_t NVIC_EncodePriority (uint32_t PriorityGroup, uint32_t PreemptPriority, uint32_t SubPriority) { uint32_t PriorityGroupTmp = (PriorityGroup & 0x07); /* only values 0..7 are used */ uint32_t PreemptPriorityBits; uint32_t SubPriorityBits; PreemptPriorityBits = ((7 - PriorityGroupTmp) > __NVIC_PRIO_BITS) ? __NVIC_PRIO_BITS : 7 - PriorityGroupTmp; SubPriorityBits = ((PriorityGroupTmp + __NVIC_PRIO_BITS) < 7) ? 0 : PriorityGroupTmp - 7 + __NVIC_PRIO_BITS; return ( ((PreemptPriority & ((1 << (PreemptPriorityBits)) - 1)) << SubPriorityBits) | ((SubPriority & ((1 << (SubPriorityBits )) - 1))) ); } /** \brief Decode Priority The function decodes an interrupt priority value with a given priority group to preemptive priority value and subpriority value. In case of a conflict between priority grouping and available priority bits (__NVIC_PRIO_BITS) the samllest possible priority group is set. \param [in] Priority Priority value, which can be retrieved with the function \ref NVIC_GetPriority(). \param [in] PriorityGroup Used priority group. \param [out] pPreemptPriority Preemptive priority value (starting from 0). \param [out] pSubPriority Subpriority value (starting from 0). */ __STATIC_INLINE void NVIC_DecodePriority (uint32_t Priority, uint32_t PriorityGroup, uint32_t* pPreemptPriority, uint32_t* pSubPriority) { uint32_t PriorityGroupTmp = (PriorityGroup & 0x07); /* only values 0..7 are used */ uint32_t PreemptPriorityBits; uint32_t SubPriorityBits; PreemptPriorityBits = ((7 - PriorityGroupTmp) > __NVIC_PRIO_BITS) ? __NVIC_PRIO_BITS : 7 - PriorityGroupTmp; SubPriorityBits = ((PriorityGroupTmp + __NVIC_PRIO_BITS) < 7) ? 0 : PriorityGroupTmp - 7 + __NVIC_PRIO_BITS; *pPreemptPriority = (Priority >> SubPriorityBits) & ((1 << (PreemptPriorityBits)) - 1); *pSubPriority = (Priority ) & ((1 << (SubPriorityBits )) - 1); } /** \brief System Reset The function initiates a system reset request to reset the MCU. */ __STATIC_INLINE void NVIC_SystemReset(void) { __DSB(); /* Ensure all outstanding memory accesses included buffered write are completed before reset */ SCB->AIRCR = ((0x5FA << SCB_AIRCR_VECTKEY_Pos) | (SCB->AIRCR & SCB_AIRCR_PRIGROUP_Msk) | SCB_AIRCR_SYSRESETREQ_Msk); /* Keep priority group unchanged */ __DSB(); /* Ensure completion of memory access */ while(1); /* wait until reset */ } /*@} end of CMSIS_Core_NVICFunctions */ /* ################################## SysTick function ############################################ */ /** \ingroup CMSIS_Core_FunctionInterface \defgroup CMSIS_Core_SysTickFunctions SysTick Functions \brief Functions that configure the System. @{ */ #if (__Vendor_SysTickConfig == 0) /** \brief System Tick Configuration The function initializes the System Timer and its interrupt, and starts the System Tick Timer. Counter is in free running mode to generate periodic interrupts. \param [in] ticks Number of ticks between two interrupts. \return 0 Function succeeded. \return 1 Function failed. \note When the variable __Vendor_SysTickConfig is set to 1, then the function SysTick_Config is not included. In this case, the file device.h must contain a vendor-specific implementation of this function. */ __STATIC_INLINE uint32_t SysTick_Config(uint32_t ticks) { if ((ticks - 1) > SysTick_LOAD_RELOAD_Msk) return (1); /* Reload value impossible */ SysTick->LOAD = ticks - 1; /* set reload register */ NVIC_SetPriority (SysTick_IRQn, (1<<__NVIC_PRIO_BITS) - 1); /* set Priority for Systick Interrupt */ SysTick->VAL = 0; /* Load the SysTick Counter Value */ SysTick->CTRL = SysTick_CTRL_CLKSOURCE_Msk | SysTick_CTRL_TICKINT_Msk | SysTick_CTRL_ENABLE_Msk; /* Enable SysTick IRQ and SysTick Timer */ return (0); /* Function successful */ } #endif /*@} end of CMSIS_Core_SysTickFunctions */ /* ##################################### Debug In/Output function ########################################### */ /** \ingroup CMSIS_Core_FunctionInterface \defgroup CMSIS_core_DebugFunctions ITM Functions \brief Functions that access the ITM debug interface. @{ */ extern volatile int32_t ITM_RxBuffer; /*!< External variable to receive characters. */ #define ITM_RXBUFFER_EMPTY 0x5AA55AA5 /*!< Value identifying \ref ITM_RxBuffer is ready for next character. */ /** \brief ITM Send Character The function transmits a character via the ITM channel 0, and \li Just returns when no debugger is connected that has booked the output. \li Is blocking when a debugger is connected, but the previous character sent has not been transmitted. \param [in] ch Character to transmit. \returns Character to transmit. */ __STATIC_INLINE uint32_t ITM_SendChar (uint32_t ch) { if ((ITM->TCR & ITM_TCR_ITMENA_Msk) && /* ITM enabled */ (ITM->TER & (1UL << 0) ) ) /* ITM Port #0 enabled */ { while (ITM->PORT[0].u32 == 0); ITM->PORT[0].u8 = (uint8_t) ch; } return (ch); } /** \brief ITM Receive Character The function inputs a character via the external variable \ref ITM_RxBuffer. \return Received character. \return -1 No character pending. */ __STATIC_INLINE int32_t ITM_ReceiveChar (void) { int32_t ch = -1; /* no character available */ if (ITM_RxBuffer != ITM_RXBUFFER_EMPTY) { ch = ITM_RxBuffer; ITM_RxBuffer = ITM_RXBUFFER_EMPTY; /* ready for next character */ } return (ch); } /** \brief ITM Check Character The function checks whether a character is pending for reading in the variable \ref ITM_RxBuffer. \return 0 No character available. \return 1 Character available. */ __STATIC_INLINE int32_t ITM_CheckChar (void) { if (ITM_RxBuffer == ITM_RXBUFFER_EMPTY) { return (0); /* no character available */ } else { return (1); /* character available */ } } /*@} end of CMSIS_core_DebugFunctions */ #endif /* __CORE_CM3_H_DEPENDANT */ #endif /* __CMSIS_GENERIC */ #ifdef __cplusplus } #endif ================================================ FILE: Zelig/mbed/TARGET_K64F/core_cm4.h ================================================ /**************************************************************************//** * @file core_cm4.h * @brief CMSIS Cortex-M4 Core Peripheral Access Layer Header File * @version V3.20 * @date 25. February 2013 * * @note * ******************************************************************************/ /* Copyright (c) 2009 - 2013 ARM LIMITED All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: - Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. - Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. - Neither the name of ARM 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 COPYRIGHT HOLDERS AND 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. ---------------------------------------------------------------------------*/ #if defined ( __ICCARM__ ) #pragma system_include /* treat file as system include file for MISRA check */ #endif #ifdef __cplusplus extern "C" { #endif #ifndef __CORE_CM4_H_GENERIC #define __CORE_CM4_H_GENERIC /** \page CMSIS_MISRA_Exceptions MISRA-C:2004 Compliance Exceptions CMSIS violates the following MISRA-C:2004 rules: \li Required Rule 8.5, object/function definition in header file.
Function definitions in header files are used to allow 'inlining'. \li Required Rule 18.4, declaration of union type or object of union type: '{...}'.
Unions are used for effective representation of core registers. \li Advisory Rule 19.7, Function-like macro defined.
Function-like macros are used to allow more efficient code. */ /******************************************************************************* * CMSIS definitions ******************************************************************************/ /** \ingroup Cortex_M4 @{ */ /* CMSIS CM4 definitions */ #define __CM4_CMSIS_VERSION_MAIN (0x03) /*!< [31:16] CMSIS HAL main version */ #define __CM4_CMSIS_VERSION_SUB (0x20) /*!< [15:0] CMSIS HAL sub version */ #define __CM4_CMSIS_VERSION ((__CM4_CMSIS_VERSION_MAIN << 16) | \ __CM4_CMSIS_VERSION_SUB ) /*!< CMSIS HAL version number */ #define __CORTEX_M (0x04) /*!< Cortex-M Core */ #if defined ( __CC_ARM ) #define __ASM __asm /*!< asm keyword for ARM Compiler */ #define __INLINE __inline /*!< inline keyword for ARM Compiler */ #define __STATIC_INLINE static __inline #elif defined ( __ICCARM__ ) #define __ASM __asm /*!< asm keyword for IAR Compiler */ #define __INLINE inline /*!< inline keyword for IAR Compiler. Only available in High optimization mode! */ #define __STATIC_INLINE static inline #elif defined ( __TMS470__ ) #define __ASM __asm /*!< asm keyword for TI CCS Compiler */ #define __STATIC_INLINE static inline #elif defined ( __GNUC__ ) #define __ASM __asm /*!< asm keyword for GNU Compiler */ #define __INLINE inline /*!< inline keyword for GNU Compiler */ #define __STATIC_INLINE static inline #elif defined ( __TASKING__ ) #define __ASM __asm /*!< asm keyword for TASKING Compiler */ #define __INLINE inline /*!< inline keyword for TASKING Compiler */ #define __STATIC_INLINE static inline #endif /** __FPU_USED indicates whether an FPU is used or not. For this, __FPU_PRESENT has to be checked prior to making use of FPU specific registers and functions. */ #if defined ( __CC_ARM ) #if defined __TARGET_FPU_VFP #if (__FPU_PRESENT == 1) #define __FPU_USED 1 #else #warning "Compiler generates FPU instructions for a device without an FPU (check __FPU_PRESENT)" #define __FPU_USED 0 #endif #else #define __FPU_USED 0 #endif #elif defined ( __ICCARM__ ) #if defined __ARMVFP__ #if (__FPU_PRESENT == 1) #define __FPU_USED 1 #else #warning "Compiler generates FPU instructions for a device without an FPU (check __FPU_PRESENT)" #define __FPU_USED 0 #endif #else #define __FPU_USED 0 #endif #elif defined ( __TMS470__ ) #if defined __TI_VFP_SUPPORT__ #if (__FPU_PRESENT == 1) #define __FPU_USED 1 #else #warning "Compiler generates FPU instructions for a device without an FPU (check __FPU_PRESENT)" #define __FPU_USED 0 #endif #else #define __FPU_USED 0 #endif #elif defined ( __GNUC__ ) #if defined (__VFP_FP__) && !defined(__SOFTFP__) #if (__FPU_PRESENT == 1) #define __FPU_USED 1 #else #warning "Compiler generates FPU instructions for a device without an FPU (check __FPU_PRESENT)" #define __FPU_USED 0 #endif #else #define __FPU_USED 0 #endif #elif defined ( __TASKING__ ) #if defined __FPU_VFP__ #if (__FPU_PRESENT == 1) #define __FPU_USED 1 #else #error "Compiler generates FPU instructions for a device without an FPU (check __FPU_PRESENT)" #define __FPU_USED 0 #endif #else #define __FPU_USED 0 #endif #endif #include /* standard types definitions */ #include /* Core Instruction Access */ #include /* Core Function Access */ #include /* Compiler specific SIMD Intrinsics */ #endif /* __CORE_CM4_H_GENERIC */ #ifndef __CMSIS_GENERIC #ifndef __CORE_CM4_H_DEPENDANT #define __CORE_CM4_H_DEPENDANT /* check device defines and use defaults */ #if defined __CHECK_DEVICE_DEFINES #ifndef __CM4_REV #define __CM4_REV 0x0000 #warning "__CM4_REV not defined in device header file; using default!" #endif #ifndef __FPU_PRESENT #define __FPU_PRESENT 0 #warning "__FPU_PRESENT not defined in device header file; using default!" #endif #ifndef __MPU_PRESENT #define __MPU_PRESENT 0 #warning "__MPU_PRESENT not defined in device header file; using default!" #endif #ifndef __NVIC_PRIO_BITS #define __NVIC_PRIO_BITS 4 #warning "__NVIC_PRIO_BITS not defined in device header file; using default!" #endif #ifndef __Vendor_SysTickConfig #define __Vendor_SysTickConfig 0 #warning "__Vendor_SysTickConfig not defined in device header file; using default!" #endif #endif /* IO definitions (access restrictions to peripheral registers) */ /** \defgroup CMSIS_glob_defs CMSIS Global Defines IO Type Qualifiers are used \li to specify the access to peripheral variables. \li for automatic generation of peripheral register debug information. */ #ifdef __cplusplus #define __I volatile /*!< Defines 'read only' permissions */ #else #define __I volatile const /*!< Defines 'read only' permissions */ #endif #define __O volatile /*!< Defines 'write only' permissions */ #define __IO volatile /*!< Defines 'read / write' permissions */ /*@} end of group Cortex_M4 */ /******************************************************************************* * Register Abstraction Core Register contain: - Core Register - Core NVIC Register - Core SCB Register - Core SysTick Register - Core Debug Register - Core MPU Register - Core FPU Register ******************************************************************************/ /** \defgroup CMSIS_core_register Defines and Type Definitions \brief Type definitions and defines for Cortex-M processor based devices. */ /** \ingroup CMSIS_core_register \defgroup CMSIS_CORE Status and Control Registers \brief Core Register type definitions. @{ */ /** \brief Union type to access the Application Program Status Register (APSR). */ typedef union { struct { #if (__CORTEX_M != 0x04) uint32_t _reserved0:27; /*!< bit: 0..26 Reserved */ #else uint32_t _reserved0:16; /*!< bit: 0..15 Reserved */ uint32_t GE:4; /*!< bit: 16..19 Greater than or Equal flags */ uint32_t _reserved1:7; /*!< bit: 20..26 Reserved */ #endif uint32_t Q:1; /*!< bit: 27 Saturation condition flag */ uint32_t V:1; /*!< bit: 28 Overflow condition code flag */ uint32_t C:1; /*!< bit: 29 Carry condition code flag */ uint32_t Z:1; /*!< bit: 30 Zero condition code flag */ uint32_t N:1; /*!< bit: 31 Negative condition code flag */ } b; /*!< Structure used for bit access */ uint32_t w; /*!< Type used for word access */ } APSR_Type; /** \brief Union type to access the Interrupt Program Status Register (IPSR). */ typedef union { struct { uint32_t ISR:9; /*!< bit: 0.. 8 Exception number */ uint32_t _reserved0:23; /*!< bit: 9..31 Reserved */ } b; /*!< Structure used for bit access */ uint32_t w; /*!< Type used for word access */ } IPSR_Type; /** \brief Union type to access the Special-Purpose Program Status Registers (xPSR). */ typedef union { struct { uint32_t ISR:9; /*!< bit: 0.. 8 Exception number */ #if (__CORTEX_M != 0x04) uint32_t _reserved0:15; /*!< bit: 9..23 Reserved */ #else uint32_t _reserved0:7; /*!< bit: 9..15 Reserved */ uint32_t GE:4; /*!< bit: 16..19 Greater than or Equal flags */ uint32_t _reserved1:4; /*!< bit: 20..23 Reserved */ #endif uint32_t T:1; /*!< bit: 24 Thumb bit (read 0) */ uint32_t IT:2; /*!< bit: 25..26 saved IT state (read 0) */ uint32_t Q:1; /*!< bit: 27 Saturation condition flag */ uint32_t V:1; /*!< bit: 28 Overflow condition code flag */ uint32_t C:1; /*!< bit: 29 Carry condition code flag */ uint32_t Z:1; /*!< bit: 30 Zero condition code flag */ uint32_t N:1; /*!< bit: 31 Negative condition code flag */ } b; /*!< Structure used for bit access */ uint32_t w; /*!< Type used for word access */ } xPSR_Type; /** \brief Union type to access the Control Registers (CONTROL). */ typedef union { struct { uint32_t nPRIV:1; /*!< bit: 0 Execution privilege in Thread mode */ uint32_t SPSEL:1; /*!< bit: 1 Stack to be used */ uint32_t FPCA:1; /*!< bit: 2 FP extension active flag */ uint32_t _reserved0:29; /*!< bit: 3..31 Reserved */ } b; /*!< Structure used for bit access */ uint32_t w; /*!< Type used for word access */ } CONTROL_Type; /*@} end of group CMSIS_CORE */ /** \ingroup CMSIS_core_register \defgroup CMSIS_NVIC Nested Vectored Interrupt Controller (NVIC) \brief Type definitions for the NVIC Registers @{ */ /** \brief Structure type to access the Nested Vectored Interrupt Controller (NVIC). */ typedef struct { __IO uint32_t ISER[8]; /*!< Offset: 0x000 (R/W) Interrupt Set Enable Register */ uint32_t RESERVED0[24]; __IO uint32_t ICER[8]; /*!< Offset: 0x080 (R/W) Interrupt Clear Enable Register */ uint32_t RSERVED1[24]; __IO uint32_t ISPR[8]; /*!< Offset: 0x100 (R/W) Interrupt Set Pending Register */ uint32_t RESERVED2[24]; __IO uint32_t ICPR[8]; /*!< Offset: 0x180 (R/W) Interrupt Clear Pending Register */ uint32_t RESERVED3[24]; __IO uint32_t IABR[8]; /*!< Offset: 0x200 (R/W) Interrupt Active bit Register */ uint32_t RESERVED4[56]; __IO uint8_t IP[240]; /*!< Offset: 0x300 (R/W) Interrupt Priority Register (8Bit wide) */ uint32_t RESERVED5[644]; __O uint32_t STIR; /*!< Offset: 0xE00 ( /W) Software Trigger Interrupt Register */ } NVIC_Type; /* Software Triggered Interrupt Register Definitions */ #define NVIC_STIR_INTID_Pos 0 /*!< STIR: INTLINESNUM Position */ #define NVIC_STIR_INTID_Msk (0x1FFUL << NVIC_STIR_INTID_Pos) /*!< STIR: INTLINESNUM Mask */ /*@} end of group CMSIS_NVIC */ /** \ingroup CMSIS_core_register \defgroup CMSIS_SCB System Control Block (SCB) \brief Type definitions for the System Control Block Registers @{ */ /** \brief Structure type to access the System Control Block (SCB). */ typedef struct { __I uint32_t CPUID; /*!< Offset: 0x000 (R/ ) CPUID Base Register */ __IO uint32_t ICSR; /*!< Offset: 0x004 (R/W) Interrupt Control and State Register */ __IO uint32_t VTOR; /*!< Offset: 0x008 (R/W) Vector Table Offset Register */ __IO uint32_t AIRCR; /*!< Offset: 0x00C (R/W) Application Interrupt and Reset Control Register */ __IO uint32_t SCR; /*!< Offset: 0x010 (R/W) System Control Register */ __IO uint32_t CCR; /*!< Offset: 0x014 (R/W) Configuration Control Register */ __IO uint8_t SHP[12]; /*!< Offset: 0x018 (R/W) System Handlers Priority Registers (4-7, 8-11, 12-15) */ __IO uint32_t SHCSR; /*!< Offset: 0x024 (R/W) System Handler Control and State Register */ __IO uint32_t CFSR; /*!< Offset: 0x028 (R/W) Configurable Fault Status Register */ __IO uint32_t HFSR; /*!< Offset: 0x02C (R/W) HardFault Status Register */ __IO uint32_t DFSR; /*!< Offset: 0x030 (R/W) Debug Fault Status Register */ __IO uint32_t MMFAR; /*!< Offset: 0x034 (R/W) MemManage Fault Address Register */ __IO uint32_t BFAR; /*!< Offset: 0x038 (R/W) BusFault Address Register */ __IO uint32_t AFSR; /*!< Offset: 0x03C (R/W) Auxiliary Fault Status Register */ __I uint32_t PFR[2]; /*!< Offset: 0x040 (R/ ) Processor Feature Register */ __I uint32_t DFR; /*!< Offset: 0x048 (R/ ) Debug Feature Register */ __I uint32_t ADR; /*!< Offset: 0x04C (R/ ) Auxiliary Feature Register */ __I uint32_t MMFR[4]; /*!< Offset: 0x050 (R/ ) Memory Model Feature Register */ __I uint32_t ISAR[5]; /*!< Offset: 0x060 (R/ ) Instruction Set Attributes Register */ uint32_t RESERVED0[5]; __IO uint32_t CPACR; /*!< Offset: 0x088 (R/W) Coprocessor Access Control Register */ } SCB_Type; /* SCB CPUID Register Definitions */ #define SCB_CPUID_IMPLEMENTER_Pos 24 /*!< SCB CPUID: IMPLEMENTER Position */ #define SCB_CPUID_IMPLEMENTER_Msk (0xFFUL << SCB_CPUID_IMPLEMENTER_Pos) /*!< SCB CPUID: IMPLEMENTER Mask */ #define SCB_CPUID_VARIANT_Pos 20 /*!< SCB CPUID: VARIANT Position */ #define SCB_CPUID_VARIANT_Msk (0xFUL << SCB_CPUID_VARIANT_Pos) /*!< SCB CPUID: VARIANT Mask */ #define SCB_CPUID_ARCHITECTURE_Pos 16 /*!< SCB CPUID: ARCHITECTURE Position */ #define SCB_CPUID_ARCHITECTURE_Msk (0xFUL << SCB_CPUID_ARCHITECTURE_Pos) /*!< SCB CPUID: ARCHITECTURE Mask */ #define SCB_CPUID_PARTNO_Pos 4 /*!< SCB CPUID: PARTNO Position */ #define SCB_CPUID_PARTNO_Msk (0xFFFUL << SCB_CPUID_PARTNO_Pos) /*!< SCB CPUID: PARTNO Mask */ #define SCB_CPUID_REVISION_Pos 0 /*!< SCB CPUID: REVISION Position */ #define SCB_CPUID_REVISION_Msk (0xFUL << SCB_CPUID_REVISION_Pos) /*!< SCB CPUID: REVISION Mask */ /* SCB Interrupt Control State Register Definitions */ #define SCB_ICSR_NMIPENDSET_Pos 31 /*!< SCB ICSR: NMIPENDSET Position */ #define SCB_ICSR_NMIPENDSET_Msk (1UL << SCB_ICSR_NMIPENDSET_Pos) /*!< SCB ICSR: NMIPENDSET Mask */ #define SCB_ICSR_PENDSVSET_Pos 28 /*!< SCB ICSR: PENDSVSET Position */ #define SCB_ICSR_PENDSVSET_Msk (1UL << SCB_ICSR_PENDSVSET_Pos) /*!< SCB ICSR: PENDSVSET Mask */ #define SCB_ICSR_PENDSVCLR_Pos 27 /*!< SCB ICSR: PENDSVCLR Position */ #define SCB_ICSR_PENDSVCLR_Msk (1UL << SCB_ICSR_PENDSVCLR_Pos) /*!< SCB ICSR: PENDSVCLR Mask */ #define SCB_ICSR_PENDSTSET_Pos 26 /*!< SCB ICSR: PENDSTSET Position */ #define SCB_ICSR_PENDSTSET_Msk (1UL << SCB_ICSR_PENDSTSET_Pos) /*!< SCB ICSR: PENDSTSET Mask */ #define SCB_ICSR_PENDSTCLR_Pos 25 /*!< SCB ICSR: PENDSTCLR Position */ #define SCB_ICSR_PENDSTCLR_Msk (1UL << SCB_ICSR_PENDSTCLR_Pos) /*!< SCB ICSR: PENDSTCLR Mask */ #define SCB_ICSR_ISRPREEMPT_Pos 23 /*!< SCB ICSR: ISRPREEMPT Position */ #define SCB_ICSR_ISRPREEMPT_Msk (1UL << SCB_ICSR_ISRPREEMPT_Pos) /*!< SCB ICSR: ISRPREEMPT Mask */ #define SCB_ICSR_ISRPENDING_Pos 22 /*!< SCB ICSR: ISRPENDING Position */ #define SCB_ICSR_ISRPENDING_Msk (1UL << SCB_ICSR_ISRPENDING_Pos) /*!< SCB ICSR: ISRPENDING Mask */ #define SCB_ICSR_VECTPENDING_Pos 12 /*!< SCB ICSR: VECTPENDING Position */ #define SCB_ICSR_VECTPENDING_Msk (0x1FFUL << SCB_ICSR_VECTPENDING_Pos) /*!< SCB ICSR: VECTPENDING Mask */ #define SCB_ICSR_RETTOBASE_Pos 11 /*!< SCB ICSR: RETTOBASE Position */ #define SCB_ICSR_RETTOBASE_Msk (1UL << SCB_ICSR_RETTOBASE_Pos) /*!< SCB ICSR: RETTOBASE Mask */ #define SCB_ICSR_VECTACTIVE_Pos 0 /*!< SCB ICSR: VECTACTIVE Position */ #define SCB_ICSR_VECTACTIVE_Msk (0x1FFUL << SCB_ICSR_VECTACTIVE_Pos) /*!< SCB ICSR: VECTACTIVE Mask */ /* SCB Vector Table Offset Register Definitions */ #define SCB_VTOR_TBLOFF_Pos 7 /*!< SCB VTOR: TBLOFF Position */ #define SCB_VTOR_TBLOFF_Msk (0x1FFFFFFUL << SCB_VTOR_TBLOFF_Pos) /*!< SCB VTOR: TBLOFF Mask */ /* SCB Application Interrupt and Reset Control Register Definitions */ #define SCB_AIRCR_VECTKEY_Pos 16 /*!< SCB AIRCR: VECTKEY Position */ #define SCB_AIRCR_VECTKEY_Msk (0xFFFFUL << SCB_AIRCR_VECTKEY_Pos) /*!< SCB AIRCR: VECTKEY Mask */ #define SCB_AIRCR_VECTKEYSTAT_Pos 16 /*!< SCB AIRCR: VECTKEYSTAT Position */ #define SCB_AIRCR_VECTKEYSTAT_Msk (0xFFFFUL << SCB_AIRCR_VECTKEYSTAT_Pos) /*!< SCB AIRCR: VECTKEYSTAT Mask */ #define SCB_AIRCR_ENDIANESS_Pos 15 /*!< SCB AIRCR: ENDIANESS Position */ #define SCB_AIRCR_ENDIANESS_Msk (1UL << SCB_AIRCR_ENDIANESS_Pos) /*!< SCB AIRCR: ENDIANESS Mask */ #define SCB_AIRCR_PRIGROUP_Pos 8 /*!< SCB AIRCR: PRIGROUP Position */ #define SCB_AIRCR_PRIGROUP_Msk (7UL << SCB_AIRCR_PRIGROUP_Pos) /*!< SCB AIRCR: PRIGROUP Mask */ #define SCB_AIRCR_SYSRESETREQ_Pos 2 /*!< SCB AIRCR: SYSRESETREQ Position */ #define SCB_AIRCR_SYSRESETREQ_Msk (1UL << SCB_AIRCR_SYSRESETREQ_Pos) /*!< SCB AIRCR: SYSRESETREQ Mask */ #define SCB_AIRCR_VECTCLRACTIVE_Pos 1 /*!< SCB AIRCR: VECTCLRACTIVE Position */ #define SCB_AIRCR_VECTCLRACTIVE_Msk (1UL << SCB_AIRCR_VECTCLRACTIVE_Pos) /*!< SCB AIRCR: VECTCLRACTIVE Mask */ #define SCB_AIRCR_VECTRESET_Pos 0 /*!< SCB AIRCR: VECTRESET Position */ #define SCB_AIRCR_VECTRESET_Msk (1UL << SCB_AIRCR_VECTRESET_Pos) /*!< SCB AIRCR: VECTRESET Mask */ /* SCB System Control Register Definitions */ #define SCB_SCR_SEVONPEND_Pos 4 /*!< SCB SCR: SEVONPEND Position */ #define SCB_SCR_SEVONPEND_Msk (1UL << SCB_SCR_SEVONPEND_Pos) /*!< SCB SCR: SEVONPEND Mask */ #define SCB_SCR_SLEEPDEEP_Pos 2 /*!< SCB SCR: SLEEPDEEP Position */ #define SCB_SCR_SLEEPDEEP_Msk (1UL << SCB_SCR_SLEEPDEEP_Pos) /*!< SCB SCR: SLEEPDEEP Mask */ #define SCB_SCR_SLEEPONEXIT_Pos 1 /*!< SCB SCR: SLEEPONEXIT Position */ #define SCB_SCR_SLEEPONEXIT_Msk (1UL << SCB_SCR_SLEEPONEXIT_Pos) /*!< SCB SCR: SLEEPONEXIT Mask */ /* SCB Configuration Control Register Definitions */ #define SCB_CCR_STKALIGN_Pos 9 /*!< SCB CCR: STKALIGN Position */ #define SCB_CCR_STKALIGN_Msk (1UL << SCB_CCR_STKALIGN_Pos) /*!< SCB CCR: STKALIGN Mask */ #define SCB_CCR_BFHFNMIGN_Pos 8 /*!< SCB CCR: BFHFNMIGN Position */ #define SCB_CCR_BFHFNMIGN_Msk (1UL << SCB_CCR_BFHFNMIGN_Pos) /*!< SCB CCR: BFHFNMIGN Mask */ #define SCB_CCR_DIV_0_TRP_Pos 4 /*!< SCB CCR: DIV_0_TRP Position */ #define SCB_CCR_DIV_0_TRP_Msk (1UL << SCB_CCR_DIV_0_TRP_Pos) /*!< SCB CCR: DIV_0_TRP Mask */ #define SCB_CCR_UNALIGN_TRP_Pos 3 /*!< SCB CCR: UNALIGN_TRP Position */ #define SCB_CCR_UNALIGN_TRP_Msk (1UL << SCB_CCR_UNALIGN_TRP_Pos) /*!< SCB CCR: UNALIGN_TRP Mask */ #define SCB_CCR_USERSETMPEND_Pos 1 /*!< SCB CCR: USERSETMPEND Position */ #define SCB_CCR_USERSETMPEND_Msk (1UL << SCB_CCR_USERSETMPEND_Pos) /*!< SCB CCR: USERSETMPEND Mask */ #define SCB_CCR_NONBASETHRDENA_Pos 0 /*!< SCB CCR: NONBASETHRDENA Position */ #define SCB_CCR_NONBASETHRDENA_Msk (1UL << SCB_CCR_NONBASETHRDENA_Pos) /*!< SCB CCR: NONBASETHRDENA Mask */ /* SCB System Handler Control and State Register Definitions */ #define SCB_SHCSR_USGFAULTENA_Pos 18 /*!< SCB SHCSR: USGFAULTENA Position */ #define SCB_SHCSR_USGFAULTENA_Msk (1UL << SCB_SHCSR_USGFAULTENA_Pos) /*!< SCB SHCSR: USGFAULTENA Mask */ #define SCB_SHCSR_BUSFAULTENA_Pos 17 /*!< SCB SHCSR: BUSFAULTENA Position */ #define SCB_SHCSR_BUSFAULTENA_Msk (1UL << SCB_SHCSR_BUSFAULTENA_Pos) /*!< SCB SHCSR: BUSFAULTENA Mask */ #define SCB_SHCSR_MEMFAULTENA_Pos 16 /*!< SCB SHCSR: MEMFAULTENA Position */ #define SCB_SHCSR_MEMFAULTENA_Msk (1UL << SCB_SHCSR_MEMFAULTENA_Pos) /*!< SCB SHCSR: MEMFAULTENA Mask */ #define SCB_SHCSR_SVCALLPENDED_Pos 15 /*!< SCB SHCSR: SVCALLPENDED Position */ #define SCB_SHCSR_SVCALLPENDED_Msk (1UL << SCB_SHCSR_SVCALLPENDED_Pos) /*!< SCB SHCSR: SVCALLPENDED Mask */ #define SCB_SHCSR_BUSFAULTPENDED_Pos 14 /*!< SCB SHCSR: BUSFAULTPENDED Position */ #define SCB_SHCSR_BUSFAULTPENDED_Msk (1UL << SCB_SHCSR_BUSFAULTPENDED_Pos) /*!< SCB SHCSR: BUSFAULTPENDED Mask */ #define SCB_SHCSR_MEMFAULTPENDED_Pos 13 /*!< SCB SHCSR: MEMFAULTPENDED Position */ #define SCB_SHCSR_MEMFAULTPENDED_Msk (1UL << SCB_SHCSR_MEMFAULTPENDED_Pos) /*!< SCB SHCSR: MEMFAULTPENDED Mask */ #define SCB_SHCSR_USGFAULTPENDED_Pos 12 /*!< SCB SHCSR: USGFAULTPENDED Position */ #define SCB_SHCSR_USGFAULTPENDED_Msk (1UL << SCB_SHCSR_USGFAULTPENDED_Pos) /*!< SCB SHCSR: USGFAULTPENDED Mask */ #define SCB_SHCSR_SYSTICKACT_Pos 11 /*!< SCB SHCSR: SYSTICKACT Position */ #define SCB_SHCSR_SYSTICKACT_Msk (1UL << SCB_SHCSR_SYSTICKACT_Pos) /*!< SCB SHCSR: SYSTICKACT Mask */ #define SCB_SHCSR_PENDSVACT_Pos 10 /*!< SCB SHCSR: PENDSVACT Position */ #define SCB_SHCSR_PENDSVACT_Msk (1UL << SCB_SHCSR_PENDSVACT_Pos) /*!< SCB SHCSR: PENDSVACT Mask */ #define SCB_SHCSR_MONITORACT_Pos 8 /*!< SCB SHCSR: MONITORACT Position */ #define SCB_SHCSR_MONITORACT_Msk (1UL << SCB_SHCSR_MONITORACT_Pos) /*!< SCB SHCSR: MONITORACT Mask */ #define SCB_SHCSR_SVCALLACT_Pos 7 /*!< SCB SHCSR: SVCALLACT Position */ #define SCB_SHCSR_SVCALLACT_Msk (1UL << SCB_SHCSR_SVCALLACT_Pos) /*!< SCB SHCSR: SVCALLACT Mask */ #define SCB_SHCSR_USGFAULTACT_Pos 3 /*!< SCB SHCSR: USGFAULTACT Position */ #define SCB_SHCSR_USGFAULTACT_Msk (1UL << SCB_SHCSR_USGFAULTACT_Pos) /*!< SCB SHCSR: USGFAULTACT Mask */ #define SCB_SHCSR_BUSFAULTACT_Pos 1 /*!< SCB SHCSR: BUSFAULTACT Position */ #define SCB_SHCSR_BUSFAULTACT_Msk (1UL << SCB_SHCSR_BUSFAULTACT_Pos) /*!< SCB SHCSR: BUSFAULTACT Mask */ #define SCB_SHCSR_MEMFAULTACT_Pos 0 /*!< SCB SHCSR: MEMFAULTACT Position */ #define SCB_SHCSR_MEMFAULTACT_Msk (1UL << SCB_SHCSR_MEMFAULTACT_Pos) /*!< SCB SHCSR: MEMFAULTACT Mask */ /* SCB Configurable Fault Status Registers Definitions */ #define SCB_CFSR_USGFAULTSR_Pos 16 /*!< SCB CFSR: Usage Fault Status Register Position */ #define SCB_CFSR_USGFAULTSR_Msk (0xFFFFUL << SCB_CFSR_USGFAULTSR_Pos) /*!< SCB CFSR: Usage Fault Status Register Mask */ #define SCB_CFSR_BUSFAULTSR_Pos 8 /*!< SCB CFSR: Bus Fault Status Register Position */ #define SCB_CFSR_BUSFAULTSR_Msk (0xFFUL << SCB_CFSR_BUSFAULTSR_Pos) /*!< SCB CFSR: Bus Fault Status Register Mask */ #define SCB_CFSR_MEMFAULTSR_Pos 0 /*!< SCB CFSR: Memory Manage Fault Status Register Position */ #define SCB_CFSR_MEMFAULTSR_Msk (0xFFUL << SCB_CFSR_MEMFAULTSR_Pos) /*!< SCB CFSR: Memory Manage Fault Status Register Mask */ /* SCB Hard Fault Status Registers Definitions */ #define SCB_HFSR_DEBUGEVT_Pos 31 /*!< SCB HFSR: DEBUGEVT Position */ #define SCB_HFSR_DEBUGEVT_Msk (1UL << SCB_HFSR_DEBUGEVT_Pos) /*!< SCB HFSR: DEBUGEVT Mask */ #define SCB_HFSR_FORCED_Pos 30 /*!< SCB HFSR: FORCED Position */ #define SCB_HFSR_FORCED_Msk (1UL << SCB_HFSR_FORCED_Pos) /*!< SCB HFSR: FORCED Mask */ #define SCB_HFSR_VECTTBL_Pos 1 /*!< SCB HFSR: VECTTBL Position */ #define SCB_HFSR_VECTTBL_Msk (1UL << SCB_HFSR_VECTTBL_Pos) /*!< SCB HFSR: VECTTBL Mask */ /* SCB Debug Fault Status Register Definitions */ #define SCB_DFSR_EXTERNAL_Pos 4 /*!< SCB DFSR: EXTERNAL Position */ #define SCB_DFSR_EXTERNAL_Msk (1UL << SCB_DFSR_EXTERNAL_Pos) /*!< SCB DFSR: EXTERNAL Mask */ #define SCB_DFSR_VCATCH_Pos 3 /*!< SCB DFSR: VCATCH Position */ #define SCB_DFSR_VCATCH_Msk (1UL << SCB_DFSR_VCATCH_Pos) /*!< SCB DFSR: VCATCH Mask */ #define SCB_DFSR_DWTTRAP_Pos 2 /*!< SCB DFSR: DWTTRAP Position */ #define SCB_DFSR_DWTTRAP_Msk (1UL << SCB_DFSR_DWTTRAP_Pos) /*!< SCB DFSR: DWTTRAP Mask */ #define SCB_DFSR_BKPT_Pos 1 /*!< SCB DFSR: BKPT Position */ #define SCB_DFSR_BKPT_Msk (1UL << SCB_DFSR_BKPT_Pos) /*!< SCB DFSR: BKPT Mask */ #define SCB_DFSR_HALTED_Pos 0 /*!< SCB DFSR: HALTED Position */ #define SCB_DFSR_HALTED_Msk (1UL << SCB_DFSR_HALTED_Pos) /*!< SCB DFSR: HALTED Mask */ /*@} end of group CMSIS_SCB */ /** \ingroup CMSIS_core_register \defgroup CMSIS_SCnSCB System Controls not in SCB (SCnSCB) \brief Type definitions for the System Control and ID Register not in the SCB @{ */ /** \brief Structure type to access the System Control and ID Register not in the SCB. */ typedef struct { uint32_t RESERVED0[1]; __I uint32_t ICTR; /*!< Offset: 0x004 (R/ ) Interrupt Controller Type Register */ __IO uint32_t ACTLR; /*!< Offset: 0x008 (R/W) Auxiliary Control Register */ } SCnSCB_Type; /* Interrupt Controller Type Register Definitions */ #define SCnSCB_ICTR_INTLINESNUM_Pos 0 /*!< ICTR: INTLINESNUM Position */ #define SCnSCB_ICTR_INTLINESNUM_Msk (0xFUL << SCnSCB_ICTR_INTLINESNUM_Pos) /*!< ICTR: INTLINESNUM Mask */ /* Auxiliary Control Register Definitions */ #define SCnSCB_ACTLR_DISOOFP_Pos 9 /*!< ACTLR: DISOOFP Position */ #define SCnSCB_ACTLR_DISOOFP_Msk (1UL << SCnSCB_ACTLR_DISOOFP_Pos) /*!< ACTLR: DISOOFP Mask */ #define SCnSCB_ACTLR_DISFPCA_Pos 8 /*!< ACTLR: DISFPCA Position */ #define SCnSCB_ACTLR_DISFPCA_Msk (1UL << SCnSCB_ACTLR_DISFPCA_Pos) /*!< ACTLR: DISFPCA Mask */ #define SCnSCB_ACTLR_DISFOLD_Pos 2 /*!< ACTLR: DISFOLD Position */ #define SCnSCB_ACTLR_DISFOLD_Msk (1UL << SCnSCB_ACTLR_DISFOLD_Pos) /*!< ACTLR: DISFOLD Mask */ #define SCnSCB_ACTLR_DISDEFWBUF_Pos 1 /*!< ACTLR: DISDEFWBUF Position */ #define SCnSCB_ACTLR_DISDEFWBUF_Msk (1UL << SCnSCB_ACTLR_DISDEFWBUF_Pos) /*!< ACTLR: DISDEFWBUF Mask */ #define SCnSCB_ACTLR_DISMCYCINT_Pos 0 /*!< ACTLR: DISMCYCINT Position */ #define SCnSCB_ACTLR_DISMCYCINT_Msk (1UL << SCnSCB_ACTLR_DISMCYCINT_Pos) /*!< ACTLR: DISMCYCINT Mask */ /*@} end of group CMSIS_SCnotSCB */ /** \ingroup CMSIS_core_register \defgroup CMSIS_SysTick System Tick Timer (SysTick) \brief Type definitions for the System Timer Registers. @{ */ /** \brief Structure type to access the System Timer (SysTick). */ typedef struct { __IO uint32_t CTRL; /*!< Offset: 0x000 (R/W) SysTick Control and Status Register */ __IO uint32_t LOAD; /*!< Offset: 0x004 (R/W) SysTick Reload Value Register */ __IO uint32_t VAL; /*!< Offset: 0x008 (R/W) SysTick Current Value Register */ __I uint32_t CALIB; /*!< Offset: 0x00C (R/ ) SysTick Calibration Register */ } SysTick_Type; /* SysTick Control / Status Register Definitions */ #define SysTick_CTRL_COUNTFLAG_Pos 16 /*!< SysTick CTRL: COUNTFLAG Position */ #define SysTick_CTRL_COUNTFLAG_Msk (1UL << SysTick_CTRL_COUNTFLAG_Pos) /*!< SysTick CTRL: COUNTFLAG Mask */ #define SysTick_CTRL_CLKSOURCE_Pos 2 /*!< SysTick CTRL: CLKSOURCE Position */ #define SysTick_CTRL_CLKSOURCE_Msk (1UL << SysTick_CTRL_CLKSOURCE_Pos) /*!< SysTick CTRL: CLKSOURCE Mask */ #define SysTick_CTRL_TICKINT_Pos 1 /*!< SysTick CTRL: TICKINT Position */ #define SysTick_CTRL_TICKINT_Msk (1UL << SysTick_CTRL_TICKINT_Pos) /*!< SysTick CTRL: TICKINT Mask */ #define SysTick_CTRL_ENABLE_Pos 0 /*!< SysTick CTRL: ENABLE Position */ #define SysTick_CTRL_ENABLE_Msk (1UL << SysTick_CTRL_ENABLE_Pos) /*!< SysTick CTRL: ENABLE Mask */ /* SysTick Reload Register Definitions */ #define SysTick_LOAD_RELOAD_Pos 0 /*!< SysTick LOAD: RELOAD Position */ #define SysTick_LOAD_RELOAD_Msk (0xFFFFFFUL << SysTick_LOAD_RELOAD_Pos) /*!< SysTick LOAD: RELOAD Mask */ /* SysTick Current Register Definitions */ #define SysTick_VAL_CURRENT_Pos 0 /*!< SysTick VAL: CURRENT Position */ #define SysTick_VAL_CURRENT_Msk (0xFFFFFFUL << SysTick_VAL_CURRENT_Pos) /*!< SysTick VAL: CURRENT Mask */ /* SysTick Calibration Register Definitions */ #define SysTick_CALIB_NOREF_Pos 31 /*!< SysTick CALIB: NOREF Position */ #define SysTick_CALIB_NOREF_Msk (1UL << SysTick_CALIB_NOREF_Pos) /*!< SysTick CALIB: NOREF Mask */ #define SysTick_CALIB_SKEW_Pos 30 /*!< SysTick CALIB: SKEW Position */ #define SysTick_CALIB_SKEW_Msk (1UL << SysTick_CALIB_SKEW_Pos) /*!< SysTick CALIB: SKEW Mask */ #define SysTick_CALIB_TENMS_Pos 0 /*!< SysTick CALIB: TENMS Position */ #define SysTick_CALIB_TENMS_Msk (0xFFFFFFUL << SysTick_VAL_CURRENT_Pos) /*!< SysTick CALIB: TENMS Mask */ /*@} end of group CMSIS_SysTick */ /** \ingroup CMSIS_core_register \defgroup CMSIS_ITM Instrumentation Trace Macrocell (ITM) \brief Type definitions for the Instrumentation Trace Macrocell (ITM) @{ */ /** \brief Structure type to access the Instrumentation Trace Macrocell Register (ITM). */ typedef struct { __O union { __O uint8_t u8; /*!< Offset: 0x000 ( /W) ITM Stimulus Port 8-bit */ __O uint16_t u16; /*!< Offset: 0x000 ( /W) ITM Stimulus Port 16-bit */ __O uint32_t u32; /*!< Offset: 0x000 ( /W) ITM Stimulus Port 32-bit */ } PORT [32]; /*!< Offset: 0x000 ( /W) ITM Stimulus Port Registers */ uint32_t RESERVED0[864]; __IO uint32_t TER; /*!< Offset: 0xE00 (R/W) ITM Trace Enable Register */ uint32_t RESERVED1[15]; __IO uint32_t TPR; /*!< Offset: 0xE40 (R/W) ITM Trace Privilege Register */ uint32_t RESERVED2[15]; __IO uint32_t TCR; /*!< Offset: 0xE80 (R/W) ITM Trace Control Register */ uint32_t RESERVED3[29]; __O uint32_t IWR; /*!< Offset: 0xEF8 ( /W) ITM Integration Write Register */ __I uint32_t IRR; /*!< Offset: 0xEFC (R/ ) ITM Integration Read Register */ __IO uint32_t IMCR; /*!< Offset: 0xF00 (R/W) ITM Integration Mode Control Register */ uint32_t RESERVED4[43]; __O uint32_t LAR; /*!< Offset: 0xFB0 ( /W) ITM Lock Access Register */ __I uint32_t LSR; /*!< Offset: 0xFB4 (R/ ) ITM Lock Status Register */ uint32_t RESERVED5[6]; __I uint32_t PID4; /*!< Offset: 0xFD0 (R/ ) ITM Peripheral Identification Register #4 */ __I uint32_t PID5; /*!< Offset: 0xFD4 (R/ ) ITM Peripheral Identification Register #5 */ __I uint32_t PID6; /*!< Offset: 0xFD8 (R/ ) ITM Peripheral Identification Register #6 */ __I uint32_t PID7; /*!< Offset: 0xFDC (R/ ) ITM Peripheral Identification Register #7 */ __I uint32_t PID0; /*!< Offset: 0xFE0 (R/ ) ITM Peripheral Identification Register #0 */ __I uint32_t PID1; /*!< Offset: 0xFE4 (R/ ) ITM Peripheral Identification Register #1 */ __I uint32_t PID2; /*!< Offset: 0xFE8 (R/ ) ITM Peripheral Identification Register #2 */ __I uint32_t PID3; /*!< Offset: 0xFEC (R/ ) ITM Peripheral Identification Register #3 */ __I uint32_t CID0; /*!< Offset: 0xFF0 (R/ ) ITM Component Identification Register #0 */ __I uint32_t CID1; /*!< Offset: 0xFF4 (R/ ) ITM Component Identification Register #1 */ __I uint32_t CID2; /*!< Offset: 0xFF8 (R/ ) ITM Component Identification Register #2 */ __I uint32_t CID3; /*!< Offset: 0xFFC (R/ ) ITM Component Identification Register #3 */ } ITM_Type; /* ITM Trace Privilege Register Definitions */ #define ITM_TPR_PRIVMASK_Pos 0 /*!< ITM TPR: PRIVMASK Position */ #define ITM_TPR_PRIVMASK_Msk (0xFUL << ITM_TPR_PRIVMASK_Pos) /*!< ITM TPR: PRIVMASK Mask */ /* ITM Trace Control Register Definitions */ #define ITM_TCR_BUSY_Pos 23 /*!< ITM TCR: BUSY Position */ #define ITM_TCR_BUSY_Msk (1UL << ITM_TCR_BUSY_Pos) /*!< ITM TCR: BUSY Mask */ #define ITM_TCR_TraceBusID_Pos 16 /*!< ITM TCR: ATBID Position */ #define ITM_TCR_TraceBusID_Msk (0x7FUL << ITM_TCR_TraceBusID_Pos) /*!< ITM TCR: ATBID Mask */ #define ITM_TCR_GTSFREQ_Pos 10 /*!< ITM TCR: Global timestamp frequency Position */ #define ITM_TCR_GTSFREQ_Msk (3UL << ITM_TCR_GTSFREQ_Pos) /*!< ITM TCR: Global timestamp frequency Mask */ #define ITM_TCR_TSPrescale_Pos 8 /*!< ITM TCR: TSPrescale Position */ #define ITM_TCR_TSPrescale_Msk (3UL << ITM_TCR_TSPrescale_Pos) /*!< ITM TCR: TSPrescale Mask */ #define ITM_TCR_SWOENA_Pos 4 /*!< ITM TCR: SWOENA Position */ #define ITM_TCR_SWOENA_Msk (1UL << ITM_TCR_SWOENA_Pos) /*!< ITM TCR: SWOENA Mask */ #define ITM_TCR_DWTENA_Pos 3 /*!< ITM TCR: DWTENA Position */ #define ITM_TCR_DWTENA_Msk (1UL << ITM_TCR_DWTENA_Pos) /*!< ITM TCR: DWTENA Mask */ #define ITM_TCR_SYNCENA_Pos 2 /*!< ITM TCR: SYNCENA Position */ #define ITM_TCR_SYNCENA_Msk (1UL << ITM_TCR_SYNCENA_Pos) /*!< ITM TCR: SYNCENA Mask */ #define ITM_TCR_TSENA_Pos 1 /*!< ITM TCR: TSENA Position */ #define ITM_TCR_TSENA_Msk (1UL << ITM_TCR_TSENA_Pos) /*!< ITM TCR: TSENA Mask */ #define ITM_TCR_ITMENA_Pos 0 /*!< ITM TCR: ITM Enable bit Position */ #define ITM_TCR_ITMENA_Msk (1UL << ITM_TCR_ITMENA_Pos) /*!< ITM TCR: ITM Enable bit Mask */ /* ITM Integration Write Register Definitions */ #define ITM_IWR_ATVALIDM_Pos 0 /*!< ITM IWR: ATVALIDM Position */ #define ITM_IWR_ATVALIDM_Msk (1UL << ITM_IWR_ATVALIDM_Pos) /*!< ITM IWR: ATVALIDM Mask */ /* ITM Integration Read Register Definitions */ #define ITM_IRR_ATREADYM_Pos 0 /*!< ITM IRR: ATREADYM Position */ #define ITM_IRR_ATREADYM_Msk (1UL << ITM_IRR_ATREADYM_Pos) /*!< ITM IRR: ATREADYM Mask */ /* ITM Integration Mode Control Register Definitions */ #define ITM_IMCR_INTEGRATION_Pos 0 /*!< ITM IMCR: INTEGRATION Position */ #define ITM_IMCR_INTEGRATION_Msk (1UL << ITM_IMCR_INTEGRATION_Pos) /*!< ITM IMCR: INTEGRATION Mask */ /* ITM Lock Status Register Definitions */ #define ITM_LSR_ByteAcc_Pos 2 /*!< ITM LSR: ByteAcc Position */ #define ITM_LSR_ByteAcc_Msk (1UL << ITM_LSR_ByteAcc_Pos) /*!< ITM LSR: ByteAcc Mask */ #define ITM_LSR_Access_Pos 1 /*!< ITM LSR: Access Position */ #define ITM_LSR_Access_Msk (1UL << ITM_LSR_Access_Pos) /*!< ITM LSR: Access Mask */ #define ITM_LSR_Present_Pos 0 /*!< ITM LSR: Present Position */ #define ITM_LSR_Present_Msk (1UL << ITM_LSR_Present_Pos) /*!< ITM LSR: Present Mask */ /*@}*/ /* end of group CMSIS_ITM */ /** \ingroup CMSIS_core_register \defgroup CMSIS_DWT Data Watchpoint and Trace (DWT) \brief Type definitions for the Data Watchpoint and Trace (DWT) @{ */ /** \brief Structure type to access the Data Watchpoint and Trace Register (DWT). */ typedef struct { __IO uint32_t CTRL; /*!< Offset: 0x000 (R/W) Control Register */ __IO uint32_t CYCCNT; /*!< Offset: 0x004 (R/W) Cycle Count Register */ __IO uint32_t CPICNT; /*!< Offset: 0x008 (R/W) CPI Count Register */ __IO uint32_t EXCCNT; /*!< Offset: 0x00C (R/W) Exception Overhead Count Register */ __IO uint32_t SLEEPCNT; /*!< Offset: 0x010 (R/W) Sleep Count Register */ __IO uint32_t LSUCNT; /*!< Offset: 0x014 (R/W) LSU Count Register */ __IO uint32_t FOLDCNT; /*!< Offset: 0x018 (R/W) Folded-instruction Count Register */ __I uint32_t PCSR; /*!< Offset: 0x01C (R/ ) Program Counter Sample Register */ __IO uint32_t COMP0; /*!< Offset: 0x020 (R/W) Comparator Register 0 */ __IO uint32_t MASK0; /*!< Offset: 0x024 (R/W) Mask Register 0 */ __IO uint32_t FUNCTION0; /*!< Offset: 0x028 (R/W) Function Register 0 */ uint32_t RESERVED0[1]; __IO uint32_t COMP1; /*!< Offset: 0x030 (R/W) Comparator Register 1 */ __IO uint32_t MASK1; /*!< Offset: 0x034 (R/W) Mask Register 1 */ __IO uint32_t FUNCTION1; /*!< Offset: 0x038 (R/W) Function Register 1 */ uint32_t RESERVED1[1]; __IO uint32_t COMP2; /*!< Offset: 0x040 (R/W) Comparator Register 2 */ __IO uint32_t MASK2; /*!< Offset: 0x044 (R/W) Mask Register 2 */ __IO uint32_t FUNCTION2; /*!< Offset: 0x048 (R/W) Function Register 2 */ uint32_t RESERVED2[1]; __IO uint32_t COMP3; /*!< Offset: 0x050 (R/W) Comparator Register 3 */ __IO uint32_t MASK3; /*!< Offset: 0x054 (R/W) Mask Register 3 */ __IO uint32_t FUNCTION3; /*!< Offset: 0x058 (R/W) Function Register 3 */ } DWT_Type; /* DWT Control Register Definitions */ #define DWT_CTRL_NUMCOMP_Pos 28 /*!< DWT CTRL: NUMCOMP Position */ #define DWT_CTRL_NUMCOMP_Msk (0xFUL << DWT_CTRL_NUMCOMP_Pos) /*!< DWT CTRL: NUMCOMP Mask */ #define DWT_CTRL_NOTRCPKT_Pos 27 /*!< DWT CTRL: NOTRCPKT Position */ #define DWT_CTRL_NOTRCPKT_Msk (0x1UL << DWT_CTRL_NOTRCPKT_Pos) /*!< DWT CTRL: NOTRCPKT Mask */ #define DWT_CTRL_NOEXTTRIG_Pos 26 /*!< DWT CTRL: NOEXTTRIG Position */ #define DWT_CTRL_NOEXTTRIG_Msk (0x1UL << DWT_CTRL_NOEXTTRIG_Pos) /*!< DWT CTRL: NOEXTTRIG Mask */ #define DWT_CTRL_NOCYCCNT_Pos 25 /*!< DWT CTRL: NOCYCCNT Position */ #define DWT_CTRL_NOCYCCNT_Msk (0x1UL << DWT_CTRL_NOCYCCNT_Pos) /*!< DWT CTRL: NOCYCCNT Mask */ #define DWT_CTRL_NOPRFCNT_Pos 24 /*!< DWT CTRL: NOPRFCNT Position */ #define DWT_CTRL_NOPRFCNT_Msk (0x1UL << DWT_CTRL_NOPRFCNT_Pos) /*!< DWT CTRL: NOPRFCNT Mask */ #define DWT_CTRL_CYCEVTENA_Pos 22 /*!< DWT CTRL: CYCEVTENA Position */ #define DWT_CTRL_CYCEVTENA_Msk (0x1UL << DWT_CTRL_CYCEVTENA_Pos) /*!< DWT CTRL: CYCEVTENA Mask */ #define DWT_CTRL_FOLDEVTENA_Pos 21 /*!< DWT CTRL: FOLDEVTENA Position */ #define DWT_CTRL_FOLDEVTENA_Msk (0x1UL << DWT_CTRL_FOLDEVTENA_Pos) /*!< DWT CTRL: FOLDEVTENA Mask */ #define DWT_CTRL_LSUEVTENA_Pos 20 /*!< DWT CTRL: LSUEVTENA Position */ #define DWT_CTRL_LSUEVTENA_Msk (0x1UL << DWT_CTRL_LSUEVTENA_Pos) /*!< DWT CTRL: LSUEVTENA Mask */ #define DWT_CTRL_SLEEPEVTENA_Pos 19 /*!< DWT CTRL: SLEEPEVTENA Position */ #define DWT_CTRL_SLEEPEVTENA_Msk (0x1UL << DWT_CTRL_SLEEPEVTENA_Pos) /*!< DWT CTRL: SLEEPEVTENA Mask */ #define DWT_CTRL_EXCEVTENA_Pos 18 /*!< DWT CTRL: EXCEVTENA Position */ #define DWT_CTRL_EXCEVTENA_Msk (0x1UL << DWT_CTRL_EXCEVTENA_Pos) /*!< DWT CTRL: EXCEVTENA Mask */ #define DWT_CTRL_CPIEVTENA_Pos 17 /*!< DWT CTRL: CPIEVTENA Position */ #define DWT_CTRL_CPIEVTENA_Msk (0x1UL << DWT_CTRL_CPIEVTENA_Pos) /*!< DWT CTRL: CPIEVTENA Mask */ #define DWT_CTRL_EXCTRCENA_Pos 16 /*!< DWT CTRL: EXCTRCENA Position */ #define DWT_CTRL_EXCTRCENA_Msk (0x1UL << DWT_CTRL_EXCTRCENA_Pos) /*!< DWT CTRL: EXCTRCENA Mask */ #define DWT_CTRL_PCSAMPLENA_Pos 12 /*!< DWT CTRL: PCSAMPLENA Position */ #define DWT_CTRL_PCSAMPLENA_Msk (0x1UL << DWT_CTRL_PCSAMPLENA_Pos) /*!< DWT CTRL: PCSAMPLENA Mask */ #define DWT_CTRL_SYNCTAP_Pos 10 /*!< DWT CTRL: SYNCTAP Position */ #define DWT_CTRL_SYNCTAP_Msk (0x3UL << DWT_CTRL_SYNCTAP_Pos) /*!< DWT CTRL: SYNCTAP Mask */ #define DWT_CTRL_CYCTAP_Pos 9 /*!< DWT CTRL: CYCTAP Position */ #define DWT_CTRL_CYCTAP_Msk (0x1UL << DWT_CTRL_CYCTAP_Pos) /*!< DWT CTRL: CYCTAP Mask */ #define DWT_CTRL_POSTINIT_Pos 5 /*!< DWT CTRL: POSTINIT Position */ #define DWT_CTRL_POSTINIT_Msk (0xFUL << DWT_CTRL_POSTINIT_Pos) /*!< DWT CTRL: POSTINIT Mask */ #define DWT_CTRL_POSTPRESET_Pos 1 /*!< DWT CTRL: POSTPRESET Position */ #define DWT_CTRL_POSTPRESET_Msk (0xFUL << DWT_CTRL_POSTPRESET_Pos) /*!< DWT CTRL: POSTPRESET Mask */ #define DWT_CTRL_CYCCNTENA_Pos 0 /*!< DWT CTRL: CYCCNTENA Position */ #define DWT_CTRL_CYCCNTENA_Msk (0x1UL << DWT_CTRL_CYCCNTENA_Pos) /*!< DWT CTRL: CYCCNTENA Mask */ /* DWT CPI Count Register Definitions */ #define DWT_CPICNT_CPICNT_Pos 0 /*!< DWT CPICNT: CPICNT Position */ #define DWT_CPICNT_CPICNT_Msk (0xFFUL << DWT_CPICNT_CPICNT_Pos) /*!< DWT CPICNT: CPICNT Mask */ /* DWT Exception Overhead Count Register Definitions */ #define DWT_EXCCNT_EXCCNT_Pos 0 /*!< DWT EXCCNT: EXCCNT Position */ #define DWT_EXCCNT_EXCCNT_Msk (0xFFUL << DWT_EXCCNT_EXCCNT_Pos) /*!< DWT EXCCNT: EXCCNT Mask */ /* DWT Sleep Count Register Definitions */ #define DWT_SLEEPCNT_SLEEPCNT_Pos 0 /*!< DWT SLEEPCNT: SLEEPCNT Position */ #define DWT_SLEEPCNT_SLEEPCNT_Msk (0xFFUL << DWT_SLEEPCNT_SLEEPCNT_Pos) /*!< DWT SLEEPCNT: SLEEPCNT Mask */ /* DWT LSU Count Register Definitions */ #define DWT_LSUCNT_LSUCNT_Pos 0 /*!< DWT LSUCNT: LSUCNT Position */ #define DWT_LSUCNT_LSUCNT_Msk (0xFFUL << DWT_LSUCNT_LSUCNT_Pos) /*!< DWT LSUCNT: LSUCNT Mask */ /* DWT Folded-instruction Count Register Definitions */ #define DWT_FOLDCNT_FOLDCNT_Pos 0 /*!< DWT FOLDCNT: FOLDCNT Position */ #define DWT_FOLDCNT_FOLDCNT_Msk (0xFFUL << DWT_FOLDCNT_FOLDCNT_Pos) /*!< DWT FOLDCNT: FOLDCNT Mask */ /* DWT Comparator Mask Register Definitions */ #define DWT_MASK_MASK_Pos 0 /*!< DWT MASK: MASK Position */ #define DWT_MASK_MASK_Msk (0x1FUL << DWT_MASK_MASK_Pos) /*!< DWT MASK: MASK Mask */ /* DWT Comparator Function Register Definitions */ #define DWT_FUNCTION_MATCHED_Pos 24 /*!< DWT FUNCTION: MATCHED Position */ #define DWT_FUNCTION_MATCHED_Msk (0x1UL << DWT_FUNCTION_MATCHED_Pos) /*!< DWT FUNCTION: MATCHED Mask */ #define DWT_FUNCTION_DATAVADDR1_Pos 16 /*!< DWT FUNCTION: DATAVADDR1 Position */ #define DWT_FUNCTION_DATAVADDR1_Msk (0xFUL << DWT_FUNCTION_DATAVADDR1_Pos) /*!< DWT FUNCTION: DATAVADDR1 Mask */ #define DWT_FUNCTION_DATAVADDR0_Pos 12 /*!< DWT FUNCTION: DATAVADDR0 Position */ #define DWT_FUNCTION_DATAVADDR0_Msk (0xFUL << DWT_FUNCTION_DATAVADDR0_Pos) /*!< DWT FUNCTION: DATAVADDR0 Mask */ #define DWT_FUNCTION_DATAVSIZE_Pos 10 /*!< DWT FUNCTION: DATAVSIZE Position */ #define DWT_FUNCTION_DATAVSIZE_Msk (0x3UL << DWT_FUNCTION_DATAVSIZE_Pos) /*!< DWT FUNCTION: DATAVSIZE Mask */ #define DWT_FUNCTION_LNK1ENA_Pos 9 /*!< DWT FUNCTION: LNK1ENA Position */ #define DWT_FUNCTION_LNK1ENA_Msk (0x1UL << DWT_FUNCTION_LNK1ENA_Pos) /*!< DWT FUNCTION: LNK1ENA Mask */ #define DWT_FUNCTION_DATAVMATCH_Pos 8 /*!< DWT FUNCTION: DATAVMATCH Position */ #define DWT_FUNCTION_DATAVMATCH_Msk (0x1UL << DWT_FUNCTION_DATAVMATCH_Pos) /*!< DWT FUNCTION: DATAVMATCH Mask */ #define DWT_FUNCTION_CYCMATCH_Pos 7 /*!< DWT FUNCTION: CYCMATCH Position */ #define DWT_FUNCTION_CYCMATCH_Msk (0x1UL << DWT_FUNCTION_CYCMATCH_Pos) /*!< DWT FUNCTION: CYCMATCH Mask */ #define DWT_FUNCTION_EMITRANGE_Pos 5 /*!< DWT FUNCTION: EMITRANGE Position */ #define DWT_FUNCTION_EMITRANGE_Msk (0x1UL << DWT_FUNCTION_EMITRANGE_Pos) /*!< DWT FUNCTION: EMITRANGE Mask */ #define DWT_FUNCTION_FUNCTION_Pos 0 /*!< DWT FUNCTION: FUNCTION Position */ #define DWT_FUNCTION_FUNCTION_Msk (0xFUL << DWT_FUNCTION_FUNCTION_Pos) /*!< DWT FUNCTION: FUNCTION Mask */ /*@}*/ /* end of group CMSIS_DWT */ /** \ingroup CMSIS_core_register \defgroup CMSIS_TPI Trace Port Interface (TPI) \brief Type definitions for the Trace Port Interface (TPI) @{ */ /** \brief Structure type to access the Trace Port Interface Register (TPI). */ typedef struct { __IO uint32_t SSPSR; /*!< Offset: 0x000 (R/ ) Supported Parallel Port Size Register */ __IO uint32_t CSPSR; /*!< Offset: 0x004 (R/W) Current Parallel Port Size Register */ uint32_t RESERVED0[2]; __IO uint32_t ACPR; /*!< Offset: 0x010 (R/W) Asynchronous Clock Prescaler Register */ uint32_t RESERVED1[55]; __IO uint32_t SPPR; /*!< Offset: 0x0F0 (R/W) Selected Pin Protocol Register */ uint32_t RESERVED2[131]; __I uint32_t FFSR; /*!< Offset: 0x300 (R/ ) Formatter and Flush Status Register */ __IO uint32_t FFCR; /*!< Offset: 0x304 (R/W) Formatter and Flush Control Register */ __I uint32_t FSCR; /*!< Offset: 0x308 (R/ ) Formatter Synchronization Counter Register */ uint32_t RESERVED3[759]; __I uint32_t TRIGGER; /*!< Offset: 0xEE8 (R/ ) TRIGGER */ __I uint32_t FIFO0; /*!< Offset: 0xEEC (R/ ) Integration ETM Data */ __I uint32_t ITATBCTR2; /*!< Offset: 0xEF0 (R/ ) ITATBCTR2 */ uint32_t RESERVED4[1]; __I uint32_t ITATBCTR0; /*!< Offset: 0xEF8 (R/ ) ITATBCTR0 */ __I uint32_t FIFO1; /*!< Offset: 0xEFC (R/ ) Integration ITM Data */ __IO uint32_t ITCTRL; /*!< Offset: 0xF00 (R/W) Integration Mode Control */ uint32_t RESERVED5[39]; __IO uint32_t CLAIMSET; /*!< Offset: 0xFA0 (R/W) Claim tag set */ __IO uint32_t CLAIMCLR; /*!< Offset: 0xFA4 (R/W) Claim tag clear */ uint32_t RESERVED7[8]; __I uint32_t DEVID; /*!< Offset: 0xFC8 (R/ ) TPIU_DEVID */ __I uint32_t DEVTYPE; /*!< Offset: 0xFCC (R/ ) TPIU_DEVTYPE */ } TPI_Type; /* TPI Asynchronous Clock Prescaler Register Definitions */ #define TPI_ACPR_PRESCALER_Pos 0 /*!< TPI ACPR: PRESCALER Position */ #define TPI_ACPR_PRESCALER_Msk (0x1FFFUL << TPI_ACPR_PRESCALER_Pos) /*!< TPI ACPR: PRESCALER Mask */ /* TPI Selected Pin Protocol Register Definitions */ #define TPI_SPPR_TXMODE_Pos 0 /*!< TPI SPPR: TXMODE Position */ #define TPI_SPPR_TXMODE_Msk (0x3UL << TPI_SPPR_TXMODE_Pos) /*!< TPI SPPR: TXMODE Mask */ /* TPI Formatter and Flush Status Register Definitions */ #define TPI_FFSR_FtNonStop_Pos 3 /*!< TPI FFSR: FtNonStop Position */ #define TPI_FFSR_FtNonStop_Msk (0x1UL << TPI_FFSR_FtNonStop_Pos) /*!< TPI FFSR: FtNonStop Mask */ #define TPI_FFSR_TCPresent_Pos 2 /*!< TPI FFSR: TCPresent Position */ #define TPI_FFSR_TCPresent_Msk (0x1UL << TPI_FFSR_TCPresent_Pos) /*!< TPI FFSR: TCPresent Mask */ #define TPI_FFSR_FtStopped_Pos 1 /*!< TPI FFSR: FtStopped Position */ #define TPI_FFSR_FtStopped_Msk (0x1UL << TPI_FFSR_FtStopped_Pos) /*!< TPI FFSR: FtStopped Mask */ #define TPI_FFSR_FlInProg_Pos 0 /*!< TPI FFSR: FlInProg Position */ #define TPI_FFSR_FlInProg_Msk (0x1UL << TPI_FFSR_FlInProg_Pos) /*!< TPI FFSR: FlInProg Mask */ /* TPI Formatter and Flush Control Register Definitions */ #define TPI_FFCR_TrigIn_Pos 8 /*!< TPI FFCR: TrigIn Position */ #define TPI_FFCR_TrigIn_Msk (0x1UL << TPI_FFCR_TrigIn_Pos) /*!< TPI FFCR: TrigIn Mask */ #define TPI_FFCR_EnFCont_Pos 1 /*!< TPI FFCR: EnFCont Position */ #define TPI_FFCR_EnFCont_Msk (0x1UL << TPI_FFCR_EnFCont_Pos) /*!< TPI FFCR: EnFCont Mask */ /* TPI TRIGGER Register Definitions */ #define TPI_TRIGGER_TRIGGER_Pos 0 /*!< TPI TRIGGER: TRIGGER Position */ #define TPI_TRIGGER_TRIGGER_Msk (0x1UL << TPI_TRIGGER_TRIGGER_Pos) /*!< TPI TRIGGER: TRIGGER Mask */ /* TPI Integration ETM Data Register Definitions (FIFO0) */ #define TPI_FIFO0_ITM_ATVALID_Pos 29 /*!< TPI FIFO0: ITM_ATVALID Position */ #define TPI_FIFO0_ITM_ATVALID_Msk (0x3UL << TPI_FIFO0_ITM_ATVALID_Pos) /*!< TPI FIFO0: ITM_ATVALID Mask */ #define TPI_FIFO0_ITM_bytecount_Pos 27 /*!< TPI FIFO0: ITM_bytecount Position */ #define TPI_FIFO0_ITM_bytecount_Msk (0x3UL << TPI_FIFO0_ITM_bytecount_Pos) /*!< TPI FIFO0: ITM_bytecount Mask */ #define TPI_FIFO0_ETM_ATVALID_Pos 26 /*!< TPI FIFO0: ETM_ATVALID Position */ #define TPI_FIFO0_ETM_ATVALID_Msk (0x3UL << TPI_FIFO0_ETM_ATVALID_Pos) /*!< TPI FIFO0: ETM_ATVALID Mask */ #define TPI_FIFO0_ETM_bytecount_Pos 24 /*!< TPI FIFO0: ETM_bytecount Position */ #define TPI_FIFO0_ETM_bytecount_Msk (0x3UL << TPI_FIFO0_ETM_bytecount_Pos) /*!< TPI FIFO0: ETM_bytecount Mask */ #define TPI_FIFO0_ETM2_Pos 16 /*!< TPI FIFO0: ETM2 Position */ #define TPI_FIFO0_ETM2_Msk (0xFFUL << TPI_FIFO0_ETM2_Pos) /*!< TPI FIFO0: ETM2 Mask */ #define TPI_FIFO0_ETM1_Pos 8 /*!< TPI FIFO0: ETM1 Position */ #define TPI_FIFO0_ETM1_Msk (0xFFUL << TPI_FIFO0_ETM1_Pos) /*!< TPI FIFO0: ETM1 Mask */ #define TPI_FIFO0_ETM0_Pos 0 /*!< TPI FIFO0: ETM0 Position */ #define TPI_FIFO0_ETM0_Msk (0xFFUL << TPI_FIFO0_ETM0_Pos) /*!< TPI FIFO0: ETM0 Mask */ /* TPI ITATBCTR2 Register Definitions */ #define TPI_ITATBCTR2_ATREADY_Pos 0 /*!< TPI ITATBCTR2: ATREADY Position */ #define TPI_ITATBCTR2_ATREADY_Msk (0x1UL << TPI_ITATBCTR2_ATREADY_Pos) /*!< TPI ITATBCTR2: ATREADY Mask */ /* TPI Integration ITM Data Register Definitions (FIFO1) */ #define TPI_FIFO1_ITM_ATVALID_Pos 29 /*!< TPI FIFO1: ITM_ATVALID Position */ #define TPI_FIFO1_ITM_ATVALID_Msk (0x3UL << TPI_FIFO1_ITM_ATVALID_Pos) /*!< TPI FIFO1: ITM_ATVALID Mask */ #define TPI_FIFO1_ITM_bytecount_Pos 27 /*!< TPI FIFO1: ITM_bytecount Position */ #define TPI_FIFO1_ITM_bytecount_Msk (0x3UL << TPI_FIFO1_ITM_bytecount_Pos) /*!< TPI FIFO1: ITM_bytecount Mask */ #define TPI_FIFO1_ETM_ATVALID_Pos 26 /*!< TPI FIFO1: ETM_ATVALID Position */ #define TPI_FIFO1_ETM_ATVALID_Msk (0x3UL << TPI_FIFO1_ETM_ATVALID_Pos) /*!< TPI FIFO1: ETM_ATVALID Mask */ #define TPI_FIFO1_ETM_bytecount_Pos 24 /*!< TPI FIFO1: ETM_bytecount Position */ #define TPI_FIFO1_ETM_bytecount_Msk (0x3UL << TPI_FIFO1_ETM_bytecount_Pos) /*!< TPI FIFO1: ETM_bytecount Mask */ #define TPI_FIFO1_ITM2_Pos 16 /*!< TPI FIFO1: ITM2 Position */ #define TPI_FIFO1_ITM2_Msk (0xFFUL << TPI_FIFO1_ITM2_Pos) /*!< TPI FIFO1: ITM2 Mask */ #define TPI_FIFO1_ITM1_Pos 8 /*!< TPI FIFO1: ITM1 Position */ #define TPI_FIFO1_ITM1_Msk (0xFFUL << TPI_FIFO1_ITM1_Pos) /*!< TPI FIFO1: ITM1 Mask */ #define TPI_FIFO1_ITM0_Pos 0 /*!< TPI FIFO1: ITM0 Position */ #define TPI_FIFO1_ITM0_Msk (0xFFUL << TPI_FIFO1_ITM0_Pos) /*!< TPI FIFO1: ITM0 Mask */ /* TPI ITATBCTR0 Register Definitions */ #define TPI_ITATBCTR0_ATREADY_Pos 0 /*!< TPI ITATBCTR0: ATREADY Position */ #define TPI_ITATBCTR0_ATREADY_Msk (0x1UL << TPI_ITATBCTR0_ATREADY_Pos) /*!< TPI ITATBCTR0: ATREADY Mask */ /* TPI Integration Mode Control Register Definitions */ #define TPI_ITCTRL_Mode_Pos 0 /*!< TPI ITCTRL: Mode Position */ #define TPI_ITCTRL_Mode_Msk (0x1UL << TPI_ITCTRL_Mode_Pos) /*!< TPI ITCTRL: Mode Mask */ /* TPI DEVID Register Definitions */ #define TPI_DEVID_NRZVALID_Pos 11 /*!< TPI DEVID: NRZVALID Position */ #define TPI_DEVID_NRZVALID_Msk (0x1UL << TPI_DEVID_NRZVALID_Pos) /*!< TPI DEVID: NRZVALID Mask */ #define TPI_DEVID_MANCVALID_Pos 10 /*!< TPI DEVID: MANCVALID Position */ #define TPI_DEVID_MANCVALID_Msk (0x1UL << TPI_DEVID_MANCVALID_Pos) /*!< TPI DEVID: MANCVALID Mask */ #define TPI_DEVID_PTINVALID_Pos 9 /*!< TPI DEVID: PTINVALID Position */ #define TPI_DEVID_PTINVALID_Msk (0x1UL << TPI_DEVID_PTINVALID_Pos) /*!< TPI DEVID: PTINVALID Mask */ #define TPI_DEVID_MinBufSz_Pos 6 /*!< TPI DEVID: MinBufSz Position */ #define TPI_DEVID_MinBufSz_Msk (0x7UL << TPI_DEVID_MinBufSz_Pos) /*!< TPI DEVID: MinBufSz Mask */ #define TPI_DEVID_AsynClkIn_Pos 5 /*!< TPI DEVID: AsynClkIn Position */ #define TPI_DEVID_AsynClkIn_Msk (0x1UL << TPI_DEVID_AsynClkIn_Pos) /*!< TPI DEVID: AsynClkIn Mask */ #define TPI_DEVID_NrTraceInput_Pos 0 /*!< TPI DEVID: NrTraceInput Position */ #define TPI_DEVID_NrTraceInput_Msk (0x1FUL << TPI_DEVID_NrTraceInput_Pos) /*!< TPI DEVID: NrTraceInput Mask */ /* TPI DEVTYPE Register Definitions */ #define TPI_DEVTYPE_SubType_Pos 0 /*!< TPI DEVTYPE: SubType Position */ #define TPI_DEVTYPE_SubType_Msk (0xFUL << TPI_DEVTYPE_SubType_Pos) /*!< TPI DEVTYPE: SubType Mask */ #define TPI_DEVTYPE_MajorType_Pos 4 /*!< TPI DEVTYPE: MajorType Position */ #define TPI_DEVTYPE_MajorType_Msk (0xFUL << TPI_DEVTYPE_MajorType_Pos) /*!< TPI DEVTYPE: MajorType Mask */ /*@}*/ /* end of group CMSIS_TPI */ #if (__MPU_PRESENT == 1) /** \ingroup CMSIS_core_register \defgroup CMSIS_MPU Memory Protection Unit (MPU) \brief Type definitions for the Memory Protection Unit (MPU) @{ */ /** \brief Structure type to access the Memory Protection Unit (MPU). */ typedef struct { __I uint32_t TYPE; /*!< Offset: 0x000 (R/ ) MPU Type Register */ __IO uint32_t CTRL; /*!< Offset: 0x004 (R/W) MPU Control Register */ __IO uint32_t RNR; /*!< Offset: 0x008 (R/W) MPU Region RNRber Register */ __IO uint32_t RBAR; /*!< Offset: 0x00C (R/W) MPU Region Base Address Register */ __IO uint32_t RASR; /*!< Offset: 0x010 (R/W) MPU Region Attribute and Size Register */ __IO uint32_t RBAR_A1; /*!< Offset: 0x014 (R/W) MPU Alias 1 Region Base Address Register */ __IO uint32_t RASR_A1; /*!< Offset: 0x018 (R/W) MPU Alias 1 Region Attribute and Size Register */ __IO uint32_t RBAR_A2; /*!< Offset: 0x01C (R/W) MPU Alias 2 Region Base Address Register */ __IO uint32_t RASR_A2; /*!< Offset: 0x020 (R/W) MPU Alias 2 Region Attribute and Size Register */ __IO uint32_t RBAR_A3; /*!< Offset: 0x024 (R/W) MPU Alias 3 Region Base Address Register */ __IO uint32_t RASR_A3; /*!< Offset: 0x028 (R/W) MPU Alias 3 Region Attribute and Size Register */ } MPU_Type; /* MPU Type Register */ #define MPU_TYPE_IREGION_Pos 16 /*!< MPU TYPE: IREGION Position */ #define MPU_TYPE_IREGION_Msk (0xFFUL << MPU_TYPE_IREGION_Pos) /*!< MPU TYPE: IREGION Mask */ #define MPU_TYPE_DREGION_Pos 8 /*!< MPU TYPE: DREGION Position */ #define MPU_TYPE_DREGION_Msk (0xFFUL << MPU_TYPE_DREGION_Pos) /*!< MPU TYPE: DREGION Mask */ #define MPU_TYPE_SEPARATE_Pos 0 /*!< MPU TYPE: SEPARATE Position */ #define MPU_TYPE_SEPARATE_Msk (1UL << MPU_TYPE_SEPARATE_Pos) /*!< MPU TYPE: SEPARATE Mask */ /* MPU Control Register */ #define MPU_CTRL_PRIVDEFENA_Pos 2 /*!< MPU CTRL: PRIVDEFENA Position */ #define MPU_CTRL_PRIVDEFENA_Msk (1UL << MPU_CTRL_PRIVDEFENA_Pos) /*!< MPU CTRL: PRIVDEFENA Mask */ #define MPU_CTRL_HFNMIENA_Pos 1 /*!< MPU CTRL: HFNMIENA Position */ #define MPU_CTRL_HFNMIENA_Msk (1UL << MPU_CTRL_HFNMIENA_Pos) /*!< MPU CTRL: HFNMIENA Mask */ #define MPU_CTRL_ENABLE_Pos 0 /*!< MPU CTRL: ENABLE Position */ #define MPU_CTRL_ENABLE_Msk (1UL << MPU_CTRL_ENABLE_Pos) /*!< MPU CTRL: ENABLE Mask */ /* MPU Region Number Register */ #define MPU_RNR_REGION_Pos 0 /*!< MPU RNR: REGION Position */ #define MPU_RNR_REGION_Msk (0xFFUL << MPU_RNR_REGION_Pos) /*!< MPU RNR: REGION Mask */ /* MPU Region Base Address Register */ #define MPU_RBAR_ADDR_Pos 5 /*!< MPU RBAR: ADDR Position */ #define MPU_RBAR_ADDR_Msk (0x7FFFFFFUL << MPU_RBAR_ADDR_Pos) /*!< MPU RBAR: ADDR Mask */ #define MPU_RBAR_VALID_Pos 4 /*!< MPU RBAR: VALID Position */ #define MPU_RBAR_VALID_Msk (1UL << MPU_RBAR_VALID_Pos) /*!< MPU RBAR: VALID Mask */ #define MPU_RBAR_REGION_Pos 0 /*!< MPU RBAR: REGION Position */ #define MPU_RBAR_REGION_Msk (0xFUL << MPU_RBAR_REGION_Pos) /*!< MPU RBAR: REGION Mask */ /* MPU Region Attribute and Size Register */ #define MPU_RASR_ATTRS_Pos 16 /*!< MPU RASR: MPU Region Attribute field Position */ #define MPU_RASR_ATTRS_Msk (0xFFFFUL << MPU_RASR_ATTRS_Pos) /*!< MPU RASR: MPU Region Attribute field Mask */ #define MPU_RASR_XN_Pos 28 /*!< MPU RASR: ATTRS.XN Position */ #define MPU_RASR_XN_Msk (1UL << MPU_RASR_XN_Pos) /*!< MPU RASR: ATTRS.XN Mask */ #define MPU_RASR_AP_Pos 24 /*!< MPU RASR: ATTRS.AP Position */ #define MPU_RASR_AP_Msk (0x7UL << MPU_RASR_AP_Pos) /*!< MPU RASR: ATTRS.AP Mask */ #define MPU_RASR_TEX_Pos 19 /*!< MPU RASR: ATTRS.TEX Position */ #define MPU_RASR_TEX_Msk (0x7UL << MPU_RASR_TEX_Pos) /*!< MPU RASR: ATTRS.TEX Mask */ #define MPU_RASR_S_Pos 18 /*!< MPU RASR: ATTRS.S Position */ #define MPU_RASR_S_Msk (1UL << MPU_RASR_S_Pos) /*!< MPU RASR: ATTRS.S Mask */ #define MPU_RASR_C_Pos 17 /*!< MPU RASR: ATTRS.C Position */ #define MPU_RASR_C_Msk (1UL << MPU_RASR_C_Pos) /*!< MPU RASR: ATTRS.C Mask */ #define MPU_RASR_B_Pos 16 /*!< MPU RASR: ATTRS.B Position */ #define MPU_RASR_B_Msk (1UL << MPU_RASR_B_Pos) /*!< MPU RASR: ATTRS.B Mask */ #define MPU_RASR_SRD_Pos 8 /*!< MPU RASR: Sub-Region Disable Position */ #define MPU_RASR_SRD_Msk (0xFFUL << MPU_RASR_SRD_Pos) /*!< MPU RASR: Sub-Region Disable Mask */ #define MPU_RASR_SIZE_Pos 1 /*!< MPU RASR: Region Size Field Position */ #define MPU_RASR_SIZE_Msk (0x1FUL << MPU_RASR_SIZE_Pos) /*!< MPU RASR: Region Size Field Mask */ #define MPU_RASR_ENABLE_Pos 0 /*!< MPU RASR: Region enable bit Position */ #define MPU_RASR_ENABLE_Msk (1UL << MPU_RASR_ENABLE_Pos) /*!< MPU RASR: Region enable bit Disable Mask */ /*@} end of group CMSIS_MPU */ #endif #if (__FPU_PRESENT == 1) /** \ingroup CMSIS_core_register \defgroup CMSIS_FPU Floating Point Unit (FPU) \brief Type definitions for the Floating Point Unit (FPU) @{ */ /** \brief Structure type to access the Floating Point Unit (FPU). */ typedef struct { uint32_t RESERVED0[1]; __IO uint32_t FPCCR; /*!< Offset: 0x004 (R/W) Floating-Point Context Control Register */ __IO uint32_t FPCAR; /*!< Offset: 0x008 (R/W) Floating-Point Context Address Register */ __IO uint32_t FPDSCR; /*!< Offset: 0x00C (R/W) Floating-Point Default Status Control Register */ __I uint32_t MVFR0; /*!< Offset: 0x010 (R/ ) Media and FP Feature Register 0 */ __I uint32_t MVFR1; /*!< Offset: 0x014 (R/ ) Media and FP Feature Register 1 */ } FPU_Type; /* Floating-Point Context Control Register */ #define FPU_FPCCR_ASPEN_Pos 31 /*!< FPCCR: ASPEN bit Position */ #define FPU_FPCCR_ASPEN_Msk (1UL << FPU_FPCCR_ASPEN_Pos) /*!< FPCCR: ASPEN bit Mask */ #define FPU_FPCCR_LSPEN_Pos 30 /*!< FPCCR: LSPEN Position */ #define FPU_FPCCR_LSPEN_Msk (1UL << FPU_FPCCR_LSPEN_Pos) /*!< FPCCR: LSPEN bit Mask */ #define FPU_FPCCR_MONRDY_Pos 8 /*!< FPCCR: MONRDY Position */ #define FPU_FPCCR_MONRDY_Msk (1UL << FPU_FPCCR_MONRDY_Pos) /*!< FPCCR: MONRDY bit Mask */ #define FPU_FPCCR_BFRDY_Pos 6 /*!< FPCCR: BFRDY Position */ #define FPU_FPCCR_BFRDY_Msk (1UL << FPU_FPCCR_BFRDY_Pos) /*!< FPCCR: BFRDY bit Mask */ #define FPU_FPCCR_MMRDY_Pos 5 /*!< FPCCR: MMRDY Position */ #define FPU_FPCCR_MMRDY_Msk (1UL << FPU_FPCCR_MMRDY_Pos) /*!< FPCCR: MMRDY bit Mask */ #define FPU_FPCCR_HFRDY_Pos 4 /*!< FPCCR: HFRDY Position */ #define FPU_FPCCR_HFRDY_Msk (1UL << FPU_FPCCR_HFRDY_Pos) /*!< FPCCR: HFRDY bit Mask */ #define FPU_FPCCR_THREAD_Pos 3 /*!< FPCCR: processor mode bit Position */ #define FPU_FPCCR_THREAD_Msk (1UL << FPU_FPCCR_THREAD_Pos) /*!< FPCCR: processor mode active bit Mask */ #define FPU_FPCCR_USER_Pos 1 /*!< FPCCR: privilege level bit Position */ #define FPU_FPCCR_USER_Msk (1UL << FPU_FPCCR_USER_Pos) /*!< FPCCR: privilege level bit Mask */ #define FPU_FPCCR_LSPACT_Pos 0 /*!< FPCCR: Lazy state preservation active bit Position */ #define FPU_FPCCR_LSPACT_Msk (1UL << FPU_FPCCR_LSPACT_Pos) /*!< FPCCR: Lazy state preservation active bit Mask */ /* Floating-Point Context Address Register */ #define FPU_FPCAR_ADDRESS_Pos 3 /*!< FPCAR: ADDRESS bit Position */ #define FPU_FPCAR_ADDRESS_Msk (0x1FFFFFFFUL << FPU_FPCAR_ADDRESS_Pos) /*!< FPCAR: ADDRESS bit Mask */ /* Floating-Point Default Status Control Register */ #define FPU_FPDSCR_AHP_Pos 26 /*!< FPDSCR: AHP bit Position */ #define FPU_FPDSCR_AHP_Msk (1UL << FPU_FPDSCR_AHP_Pos) /*!< FPDSCR: AHP bit Mask */ #define FPU_FPDSCR_DN_Pos 25 /*!< FPDSCR: DN bit Position */ #define FPU_FPDSCR_DN_Msk (1UL << FPU_FPDSCR_DN_Pos) /*!< FPDSCR: DN bit Mask */ #define FPU_FPDSCR_FZ_Pos 24 /*!< FPDSCR: FZ bit Position */ #define FPU_FPDSCR_FZ_Msk (1UL << FPU_FPDSCR_FZ_Pos) /*!< FPDSCR: FZ bit Mask */ #define FPU_FPDSCR_RMode_Pos 22 /*!< FPDSCR: RMode bit Position */ #define FPU_FPDSCR_RMode_Msk (3UL << FPU_FPDSCR_RMode_Pos) /*!< FPDSCR: RMode bit Mask */ /* Media and FP Feature Register 0 */ #define FPU_MVFR0_FP_rounding_modes_Pos 28 /*!< MVFR0: FP rounding modes bits Position */ #define FPU_MVFR0_FP_rounding_modes_Msk (0xFUL << FPU_MVFR0_FP_rounding_modes_Pos) /*!< MVFR0: FP rounding modes bits Mask */ #define FPU_MVFR0_Short_vectors_Pos 24 /*!< MVFR0: Short vectors bits Position */ #define FPU_MVFR0_Short_vectors_Msk (0xFUL << FPU_MVFR0_Short_vectors_Pos) /*!< MVFR0: Short vectors bits Mask */ #define FPU_MVFR0_Square_root_Pos 20 /*!< MVFR0: Square root bits Position */ #define FPU_MVFR0_Square_root_Msk (0xFUL << FPU_MVFR0_Square_root_Pos) /*!< MVFR0: Square root bits Mask */ #define FPU_MVFR0_Divide_Pos 16 /*!< MVFR0: Divide bits Position */ #define FPU_MVFR0_Divide_Msk (0xFUL << FPU_MVFR0_Divide_Pos) /*!< MVFR0: Divide bits Mask */ #define FPU_MVFR0_FP_excep_trapping_Pos 12 /*!< MVFR0: FP exception trapping bits Position */ #define FPU_MVFR0_FP_excep_trapping_Msk (0xFUL << FPU_MVFR0_FP_excep_trapping_Pos) /*!< MVFR0: FP exception trapping bits Mask */ #define FPU_MVFR0_Double_precision_Pos 8 /*!< MVFR0: Double-precision bits Position */ #define FPU_MVFR0_Double_precision_Msk (0xFUL << FPU_MVFR0_Double_precision_Pos) /*!< MVFR0: Double-precision bits Mask */ #define FPU_MVFR0_Single_precision_Pos 4 /*!< MVFR0: Single-precision bits Position */ #define FPU_MVFR0_Single_precision_Msk (0xFUL << FPU_MVFR0_Single_precision_Pos) /*!< MVFR0: Single-precision bits Mask */ #define FPU_MVFR0_A_SIMD_registers_Pos 0 /*!< MVFR0: A_SIMD registers bits Position */ #define FPU_MVFR0_A_SIMD_registers_Msk (0xFUL << FPU_MVFR0_A_SIMD_registers_Pos) /*!< MVFR0: A_SIMD registers bits Mask */ /* Media and FP Feature Register 1 */ #define FPU_MVFR1_FP_fused_MAC_Pos 28 /*!< MVFR1: FP fused MAC bits Position */ #define FPU_MVFR1_FP_fused_MAC_Msk (0xFUL << FPU_MVFR1_FP_fused_MAC_Pos) /*!< MVFR1: FP fused MAC bits Mask */ #define FPU_MVFR1_FP_HPFP_Pos 24 /*!< MVFR1: FP HPFP bits Position */ #define FPU_MVFR1_FP_HPFP_Msk (0xFUL << FPU_MVFR1_FP_HPFP_Pos) /*!< MVFR1: FP HPFP bits Mask */ #define FPU_MVFR1_D_NaN_mode_Pos 4 /*!< MVFR1: D_NaN mode bits Position */ #define FPU_MVFR1_D_NaN_mode_Msk (0xFUL << FPU_MVFR1_D_NaN_mode_Pos) /*!< MVFR1: D_NaN mode bits Mask */ #define FPU_MVFR1_FtZ_mode_Pos 0 /*!< MVFR1: FtZ mode bits Position */ #define FPU_MVFR1_FtZ_mode_Msk (0xFUL << FPU_MVFR1_FtZ_mode_Pos) /*!< MVFR1: FtZ mode bits Mask */ /*@} end of group CMSIS_FPU */ #endif /** \ingroup CMSIS_core_register \defgroup CMSIS_CoreDebug Core Debug Registers (CoreDebug) \brief Type definitions for the Core Debug Registers @{ */ /** \brief Structure type to access the Core Debug Register (CoreDebug). */ typedef struct { __IO uint32_t DHCSR; /*!< Offset: 0x000 (R/W) Debug Halting Control and Status Register */ __O uint32_t DCRSR; /*!< Offset: 0x004 ( /W) Debug Core Register Selector Register */ __IO uint32_t DCRDR; /*!< Offset: 0x008 (R/W) Debug Core Register Data Register */ __IO uint32_t DEMCR; /*!< Offset: 0x00C (R/W) Debug Exception and Monitor Control Register */ } CoreDebug_Type; /* Debug Halting Control and Status Register */ #define CoreDebug_DHCSR_DBGKEY_Pos 16 /*!< CoreDebug DHCSR: DBGKEY Position */ #define CoreDebug_DHCSR_DBGKEY_Msk (0xFFFFUL << CoreDebug_DHCSR_DBGKEY_Pos) /*!< CoreDebug DHCSR: DBGKEY Mask */ #define CoreDebug_DHCSR_S_RESET_ST_Pos 25 /*!< CoreDebug DHCSR: S_RESET_ST Position */ #define CoreDebug_DHCSR_S_RESET_ST_Msk (1UL << CoreDebug_DHCSR_S_RESET_ST_Pos) /*!< CoreDebug DHCSR: S_RESET_ST Mask */ #define CoreDebug_DHCSR_S_RETIRE_ST_Pos 24 /*!< CoreDebug DHCSR: S_RETIRE_ST Position */ #define CoreDebug_DHCSR_S_RETIRE_ST_Msk (1UL << CoreDebug_DHCSR_S_RETIRE_ST_Pos) /*!< CoreDebug DHCSR: S_RETIRE_ST Mask */ #define CoreDebug_DHCSR_S_LOCKUP_Pos 19 /*!< CoreDebug DHCSR: S_LOCKUP Position */ #define CoreDebug_DHCSR_S_LOCKUP_Msk (1UL << CoreDebug_DHCSR_S_LOCKUP_Pos) /*!< CoreDebug DHCSR: S_LOCKUP Mask */ #define CoreDebug_DHCSR_S_SLEEP_Pos 18 /*!< CoreDebug DHCSR: S_SLEEP Position */ #define CoreDebug_DHCSR_S_SLEEP_Msk (1UL << CoreDebug_DHCSR_S_SLEEP_Pos) /*!< CoreDebug DHCSR: S_SLEEP Mask */ #define CoreDebug_DHCSR_S_HALT_Pos 17 /*!< CoreDebug DHCSR: S_HALT Position */ #define CoreDebug_DHCSR_S_HALT_Msk (1UL << CoreDebug_DHCSR_S_HALT_Pos) /*!< CoreDebug DHCSR: S_HALT Mask */ #define CoreDebug_DHCSR_S_REGRDY_Pos 16 /*!< CoreDebug DHCSR: S_REGRDY Position */ #define CoreDebug_DHCSR_S_REGRDY_Msk (1UL << CoreDebug_DHCSR_S_REGRDY_Pos) /*!< CoreDebug DHCSR: S_REGRDY Mask */ #define CoreDebug_DHCSR_C_SNAPSTALL_Pos 5 /*!< CoreDebug DHCSR: C_SNAPSTALL Position */ #define CoreDebug_DHCSR_C_SNAPSTALL_Msk (1UL << CoreDebug_DHCSR_C_SNAPSTALL_Pos) /*!< CoreDebug DHCSR: C_SNAPSTALL Mask */ #define CoreDebug_DHCSR_C_MASKINTS_Pos 3 /*!< CoreDebug DHCSR: C_MASKINTS Position */ #define CoreDebug_DHCSR_C_MASKINTS_Msk (1UL << CoreDebug_DHCSR_C_MASKINTS_Pos) /*!< CoreDebug DHCSR: C_MASKINTS Mask */ #define CoreDebug_DHCSR_C_STEP_Pos 2 /*!< CoreDebug DHCSR: C_STEP Position */ #define CoreDebug_DHCSR_C_STEP_Msk (1UL << CoreDebug_DHCSR_C_STEP_Pos) /*!< CoreDebug DHCSR: C_STEP Mask */ #define CoreDebug_DHCSR_C_HALT_Pos 1 /*!< CoreDebug DHCSR: C_HALT Position */ #define CoreDebug_DHCSR_C_HALT_Msk (1UL << CoreDebug_DHCSR_C_HALT_Pos) /*!< CoreDebug DHCSR: C_HALT Mask */ #define CoreDebug_DHCSR_C_DEBUGEN_Pos 0 /*!< CoreDebug DHCSR: C_DEBUGEN Position */ #define CoreDebug_DHCSR_C_DEBUGEN_Msk (1UL << CoreDebug_DHCSR_C_DEBUGEN_Pos) /*!< CoreDebug DHCSR: C_DEBUGEN Mask */ /* Debug Core Register Selector Register */ #define CoreDebug_DCRSR_REGWnR_Pos 16 /*!< CoreDebug DCRSR: REGWnR Position */ #define CoreDebug_DCRSR_REGWnR_Msk (1UL << CoreDebug_DCRSR_REGWnR_Pos) /*!< CoreDebug DCRSR: REGWnR Mask */ #define CoreDebug_DCRSR_REGSEL_Pos 0 /*!< CoreDebug DCRSR: REGSEL Position */ #define CoreDebug_DCRSR_REGSEL_Msk (0x1FUL << CoreDebug_DCRSR_REGSEL_Pos) /*!< CoreDebug DCRSR: REGSEL Mask */ /* Debug Exception and Monitor Control Register */ #define CoreDebug_DEMCR_TRCENA_Pos 24 /*!< CoreDebug DEMCR: TRCENA Position */ #define CoreDebug_DEMCR_TRCENA_Msk (1UL << CoreDebug_DEMCR_TRCENA_Pos) /*!< CoreDebug DEMCR: TRCENA Mask */ #define CoreDebug_DEMCR_MON_REQ_Pos 19 /*!< CoreDebug DEMCR: MON_REQ Position */ #define CoreDebug_DEMCR_MON_REQ_Msk (1UL << CoreDebug_DEMCR_MON_REQ_Pos) /*!< CoreDebug DEMCR: MON_REQ Mask */ #define CoreDebug_DEMCR_MON_STEP_Pos 18 /*!< CoreDebug DEMCR: MON_STEP Position */ #define CoreDebug_DEMCR_MON_STEP_Msk (1UL << CoreDebug_DEMCR_MON_STEP_Pos) /*!< CoreDebug DEMCR: MON_STEP Mask */ #define CoreDebug_DEMCR_MON_PEND_Pos 17 /*!< CoreDebug DEMCR: MON_PEND Position */ #define CoreDebug_DEMCR_MON_PEND_Msk (1UL << CoreDebug_DEMCR_MON_PEND_Pos) /*!< CoreDebug DEMCR: MON_PEND Mask */ #define CoreDebug_DEMCR_MON_EN_Pos 16 /*!< CoreDebug DEMCR: MON_EN Position */ #define CoreDebug_DEMCR_MON_EN_Msk (1UL << CoreDebug_DEMCR_MON_EN_Pos) /*!< CoreDebug DEMCR: MON_EN Mask */ #define CoreDebug_DEMCR_VC_HARDERR_Pos 10 /*!< CoreDebug DEMCR: VC_HARDERR Position */ #define CoreDebug_DEMCR_VC_HARDERR_Msk (1UL << CoreDebug_DEMCR_VC_HARDERR_Pos) /*!< CoreDebug DEMCR: VC_HARDERR Mask */ #define CoreDebug_DEMCR_VC_INTERR_Pos 9 /*!< CoreDebug DEMCR: VC_INTERR Position */ #define CoreDebug_DEMCR_VC_INTERR_Msk (1UL << CoreDebug_DEMCR_VC_INTERR_Pos) /*!< CoreDebug DEMCR: VC_INTERR Mask */ #define CoreDebug_DEMCR_VC_BUSERR_Pos 8 /*!< CoreDebug DEMCR: VC_BUSERR Position */ #define CoreDebug_DEMCR_VC_BUSERR_Msk (1UL << CoreDebug_DEMCR_VC_BUSERR_Pos) /*!< CoreDebug DEMCR: VC_BUSERR Mask */ #define CoreDebug_DEMCR_VC_STATERR_Pos 7 /*!< CoreDebug DEMCR: VC_STATERR Position */ #define CoreDebug_DEMCR_VC_STATERR_Msk (1UL << CoreDebug_DEMCR_VC_STATERR_Pos) /*!< CoreDebug DEMCR: VC_STATERR Mask */ #define CoreDebug_DEMCR_VC_CHKERR_Pos 6 /*!< CoreDebug DEMCR: VC_CHKERR Position */ #define CoreDebug_DEMCR_VC_CHKERR_Msk (1UL << CoreDebug_DEMCR_VC_CHKERR_Pos) /*!< CoreDebug DEMCR: VC_CHKERR Mask */ #define CoreDebug_DEMCR_VC_NOCPERR_Pos 5 /*!< CoreDebug DEMCR: VC_NOCPERR Position */ #define CoreDebug_DEMCR_VC_NOCPERR_Msk (1UL << CoreDebug_DEMCR_VC_NOCPERR_Pos) /*!< CoreDebug DEMCR: VC_NOCPERR Mask */ #define CoreDebug_DEMCR_VC_MMERR_Pos 4 /*!< CoreDebug DEMCR: VC_MMERR Position */ #define CoreDebug_DEMCR_VC_MMERR_Msk (1UL << CoreDebug_DEMCR_VC_MMERR_Pos) /*!< CoreDebug DEMCR: VC_MMERR Mask */ #define CoreDebug_DEMCR_VC_CORERESET_Pos 0 /*!< CoreDebug DEMCR: VC_CORERESET Position */ #define CoreDebug_DEMCR_VC_CORERESET_Msk (1UL << CoreDebug_DEMCR_VC_CORERESET_Pos) /*!< CoreDebug DEMCR: VC_CORERESET Mask */ /*@} end of group CMSIS_CoreDebug */ /** \ingroup CMSIS_core_register \defgroup CMSIS_core_base Core Definitions \brief Definitions for base addresses, unions, and structures. @{ */ /* Memory mapping of Cortex-M4 Hardware */ #define SCS_BASE (0xE000E000UL) /*!< System Control Space Base Address */ #define ITM_BASE (0xE0000000UL) /*!< ITM Base Address */ #define DWT_BASE (0xE0001000UL) /*!< DWT Base Address */ #define TPI_BASE (0xE0040000UL) /*!< TPI Base Address */ #define CoreDebug_BASE (0xE000EDF0UL) /*!< Core Debug Base Address */ #define SysTick_BASE (SCS_BASE + 0x0010UL) /*!< SysTick Base Address */ #define NVIC_BASE (SCS_BASE + 0x0100UL) /*!< NVIC Base Address */ #define SCB_BASE (SCS_BASE + 0x0D00UL) /*!< System Control Block Base Address */ #define SCnSCB ((SCnSCB_Type *) SCS_BASE ) /*!< System control Register not in SCB */ #define SCB ((SCB_Type *) SCB_BASE ) /*!< SCB configuration struct */ #define SysTick ((SysTick_Type *) SysTick_BASE ) /*!< SysTick configuration struct */ #define NVIC ((NVIC_Type *) NVIC_BASE ) /*!< NVIC configuration struct */ #define ITM ((ITM_Type *) ITM_BASE ) /*!< ITM configuration struct */ #define DWT ((DWT_Type *) DWT_BASE ) /*!< DWT configuration struct */ #define TPI ((TPI_Type *) TPI_BASE ) /*!< TPI configuration struct */ #define CoreDebug ((CoreDebug_Type *) CoreDebug_BASE) /*!< Core Debug configuration struct */ #if (__MPU_PRESENT == 1) #define MPU_BASE (SCS_BASE + 0x0D90UL) /*!< Memory Protection Unit */ #define MPU ((MPU_Type *) MPU_BASE ) /*!< Memory Protection Unit */ #endif #if (__FPU_PRESENT == 1) #define FPU_BASE (SCS_BASE + 0x0F30UL) /*!< Floating Point Unit */ #define FPU ((FPU_Type *) FPU_BASE ) /*!< Floating Point Unit */ #endif /*@} */ /******************************************************************************* * Hardware Abstraction Layer Core Function Interface contains: - Core NVIC Functions - Core SysTick Functions - Core Debug Functions - Core Register Access Functions ******************************************************************************/ /** \defgroup CMSIS_Core_FunctionInterface Functions and Instructions Reference */ /* ########################## NVIC functions #################################### */ /** \ingroup CMSIS_Core_FunctionInterface \defgroup CMSIS_Core_NVICFunctions NVIC Functions \brief Functions that manage interrupts and exceptions via the NVIC. @{ */ /** \brief Set Priority Grouping The function sets the priority grouping field using the required unlock sequence. The parameter PriorityGroup is assigned to the field SCB->AIRCR [10:8] PRIGROUP field. Only values from 0..7 are used. In case of a conflict between priority grouping and available priority bits (__NVIC_PRIO_BITS), the smallest possible priority group is set. \param [in] PriorityGroup Priority grouping field. */ __STATIC_INLINE void NVIC_SetPriorityGrouping(uint32_t PriorityGroup) { uint32_t reg_value; uint32_t PriorityGroupTmp = (PriorityGroup & (uint32_t)0x07); /* only values 0..7 are used */ reg_value = SCB->AIRCR; /* read old register configuration */ reg_value &= ~(SCB_AIRCR_VECTKEY_Msk | SCB_AIRCR_PRIGROUP_Msk); /* clear bits to change */ reg_value = (reg_value | ((uint32_t)0x5FA << SCB_AIRCR_VECTKEY_Pos) | (PriorityGroupTmp << 8)); /* Insert write key and priorty group */ SCB->AIRCR = reg_value; } /** \brief Get Priority Grouping The function reads the priority grouping field from the NVIC Interrupt Controller. \return Priority grouping field (SCB->AIRCR [10:8] PRIGROUP field). */ __STATIC_INLINE uint32_t NVIC_GetPriorityGrouping(void) { return ((SCB->AIRCR & SCB_AIRCR_PRIGROUP_Msk) >> SCB_AIRCR_PRIGROUP_Pos); /* read priority grouping field */ } /** \brief Enable External Interrupt The function enables a device-specific interrupt in the NVIC interrupt controller. \param [in] IRQn External interrupt number. Value cannot be negative. */ __STATIC_INLINE void NVIC_EnableIRQ(IRQn_Type IRQn) { /* NVIC->ISER[((uint32_t)(IRQn) >> 5)] = (1 << ((uint32_t)(IRQn) & 0x1F)); enable interrupt */ NVIC->ISER[(uint32_t)((int32_t)IRQn) >> 5] = (uint32_t)(1 << ((uint32_t)((int32_t)IRQn) & (uint32_t)0x1F)); /* enable interrupt */ } /** \brief Disable External Interrupt The function disables a device-specific interrupt in the NVIC interrupt controller. \param [in] IRQn External interrupt number. Value cannot be negative. */ __STATIC_INLINE void NVIC_DisableIRQ(IRQn_Type IRQn) { NVIC->ICER[((uint32_t)(IRQn) >> 5)] = (1 << ((uint32_t)(IRQn) & 0x1F)); /* disable interrupt */ } /** \brief Get Pending Interrupt The function reads the pending register in the NVIC and returns the pending bit for the specified interrupt. \param [in] IRQn Interrupt number. \return 0 Interrupt status is not pending. \return 1 Interrupt status is pending. */ __STATIC_INLINE uint32_t NVIC_GetPendingIRQ(IRQn_Type IRQn) { return((uint32_t) ((NVIC->ISPR[(uint32_t)(IRQn) >> 5] & (1 << ((uint32_t)(IRQn) & 0x1F)))?1:0)); /* Return 1 if pending else 0 */ } /** \brief Set Pending Interrupt The function sets the pending bit of an external interrupt. \param [in] IRQn Interrupt number. Value cannot be negative. */ __STATIC_INLINE void NVIC_SetPendingIRQ(IRQn_Type IRQn) { NVIC->ISPR[((uint32_t)(IRQn) >> 5)] = (1 << ((uint32_t)(IRQn) & 0x1F)); /* set interrupt pending */ } /** \brief Clear Pending Interrupt The function clears the pending bit of an external interrupt. \param [in] IRQn External interrupt number. Value cannot be negative. */ __STATIC_INLINE void NVIC_ClearPendingIRQ(IRQn_Type IRQn) { NVIC->ICPR[((uint32_t)(IRQn) >> 5)] = (1 << ((uint32_t)(IRQn) & 0x1F)); /* Clear pending interrupt */ } /** \brief Get Active Interrupt The function reads the active register in NVIC and returns the active bit. \param [in] IRQn Interrupt number. \return 0 Interrupt status is not active. \return 1 Interrupt status is active. */ __STATIC_INLINE uint32_t NVIC_GetActive(IRQn_Type IRQn) { return((uint32_t)((NVIC->IABR[(uint32_t)(IRQn) >> 5] & (1 << ((uint32_t)(IRQn) & 0x1F)))?1:0)); /* Return 1 if active else 0 */ } /** \brief Set Interrupt Priority The function sets the priority of an interrupt. \note The priority cannot be set for every core interrupt. \param [in] IRQn Interrupt number. \param [in] priority Priority to set. */ __STATIC_INLINE void NVIC_SetPriority(IRQn_Type IRQn, uint32_t priority) { if(IRQn < 0) { SCB->SHP[((uint32_t)(IRQn) & 0xF)-4] = ((priority << (8 - __NVIC_PRIO_BITS)) & 0xff); } /* set Priority for Cortex-M System Interrupts */ else { NVIC->IP[(uint32_t)(IRQn)] = ((priority << (8 - __NVIC_PRIO_BITS)) & 0xff); } /* set Priority for device specific Interrupts */ } /** \brief Get Interrupt Priority The function reads the priority of an interrupt. The interrupt number can be positive to specify an external (device specific) interrupt, or negative to specify an internal (core) interrupt. \param [in] IRQn Interrupt number. \return Interrupt Priority. Value is aligned automatically to the implemented priority bits of the microcontroller. */ __STATIC_INLINE uint32_t NVIC_GetPriority(IRQn_Type IRQn) { if(IRQn < 0) { return((uint32_t)(SCB->SHP[((uint32_t)(IRQn) & 0xF)-4] >> (8 - __NVIC_PRIO_BITS))); } /* get priority for Cortex-M system interrupts */ else { return((uint32_t)(NVIC->IP[(uint32_t)(IRQn)] >> (8 - __NVIC_PRIO_BITS))); } /* get priority for device specific interrupts */ } /** \brief Encode Priority The function encodes the priority for an interrupt with the given priority group, preemptive priority value, and subpriority value. In case of a conflict between priority grouping and available priority bits (__NVIC_PRIO_BITS), the samllest possible priority group is set. \param [in] PriorityGroup Used priority group. \param [in] PreemptPriority Preemptive priority value (starting from 0). \param [in] SubPriority Subpriority value (starting from 0). \return Encoded priority. Value can be used in the function \ref NVIC_SetPriority(). */ __STATIC_INLINE uint32_t NVIC_EncodePriority (uint32_t PriorityGroup, uint32_t PreemptPriority, uint32_t SubPriority) { uint32_t PriorityGroupTmp = (PriorityGroup & 0x07); /* only values 0..7 are used */ uint32_t PreemptPriorityBits; uint32_t SubPriorityBits; PreemptPriorityBits = ((7 - PriorityGroupTmp) > __NVIC_PRIO_BITS) ? __NVIC_PRIO_BITS : 7 - PriorityGroupTmp; SubPriorityBits = ((PriorityGroupTmp + __NVIC_PRIO_BITS) < 7) ? 0 : PriorityGroupTmp - 7 + __NVIC_PRIO_BITS; return ( ((PreemptPriority & ((1 << (PreemptPriorityBits)) - 1)) << SubPriorityBits) | ((SubPriority & ((1 << (SubPriorityBits )) - 1))) ); } /** \brief Decode Priority The function decodes an interrupt priority value with a given priority group to preemptive priority value and subpriority value. In case of a conflict between priority grouping and available priority bits (__NVIC_PRIO_BITS) the samllest possible priority group is set. \param [in] Priority Priority value, which can be retrieved with the function \ref NVIC_GetPriority(). \param [in] PriorityGroup Used priority group. \param [out] pPreemptPriority Preemptive priority value (starting from 0). \param [out] pSubPriority Subpriority value (starting from 0). */ __STATIC_INLINE void NVIC_DecodePriority (uint32_t Priority, uint32_t PriorityGroup, uint32_t* pPreemptPriority, uint32_t* pSubPriority) { uint32_t PriorityGroupTmp = (PriorityGroup & 0x07); /* only values 0..7 are used */ uint32_t PreemptPriorityBits; uint32_t SubPriorityBits; PreemptPriorityBits = ((7 - PriorityGroupTmp) > __NVIC_PRIO_BITS) ? __NVIC_PRIO_BITS : 7 - PriorityGroupTmp; SubPriorityBits = ((PriorityGroupTmp + __NVIC_PRIO_BITS) < 7) ? 0 : PriorityGroupTmp - 7 + __NVIC_PRIO_BITS; *pPreemptPriority = (Priority >> SubPriorityBits) & ((1 << (PreemptPriorityBits)) - 1); *pSubPriority = (Priority ) & ((1 << (SubPriorityBits )) - 1); } /** \brief System Reset The function initiates a system reset request to reset the MCU. */ __STATIC_INLINE void NVIC_SystemReset(void) { __DSB(); /* Ensure all outstanding memory accesses included buffered write are completed before reset */ SCB->AIRCR = ((0x5FA << SCB_AIRCR_VECTKEY_Pos) | (SCB->AIRCR & SCB_AIRCR_PRIGROUP_Msk) | SCB_AIRCR_SYSRESETREQ_Msk); /* Keep priority group unchanged */ __DSB(); /* Ensure completion of memory access */ while(1); /* wait until reset */ } /*@} end of CMSIS_Core_NVICFunctions */ /* ################################## SysTick function ############################################ */ /** \ingroup CMSIS_Core_FunctionInterface \defgroup CMSIS_Core_SysTickFunctions SysTick Functions \brief Functions that configure the System. @{ */ #if (__Vendor_SysTickConfig == 0) /** \brief System Tick Configuration The function initializes the System Timer and its interrupt, and starts the System Tick Timer. Counter is in free running mode to generate periodic interrupts. \param [in] ticks Number of ticks between two interrupts. \return 0 Function succeeded. \return 1 Function failed. \note When the variable __Vendor_SysTickConfig is set to 1, then the function SysTick_Config is not included. In this case, the file device.h must contain a vendor-specific implementation of this function. */ __STATIC_INLINE uint32_t SysTick_Config(uint32_t ticks) { if ((ticks - 1) > SysTick_LOAD_RELOAD_Msk) return (1); /* Reload value impossible */ SysTick->LOAD = ticks - 1; /* set reload register */ NVIC_SetPriority (SysTick_IRQn, (1<<__NVIC_PRIO_BITS) - 1); /* set Priority for Systick Interrupt */ SysTick->VAL = 0; /* Load the SysTick Counter Value */ SysTick->CTRL = SysTick_CTRL_CLKSOURCE_Msk | SysTick_CTRL_TICKINT_Msk | SysTick_CTRL_ENABLE_Msk; /* Enable SysTick IRQ and SysTick Timer */ return (0); /* Function successful */ } #endif /*@} end of CMSIS_Core_SysTickFunctions */ /* ##################################### Debug In/Output function ########################################### */ /** \ingroup CMSIS_Core_FunctionInterface \defgroup CMSIS_core_DebugFunctions ITM Functions \brief Functions that access the ITM debug interface. @{ */ extern volatile int32_t ITM_RxBuffer; /*!< External variable to receive characters. */ #define ITM_RXBUFFER_EMPTY 0x5AA55AA5 /*!< Value identifying \ref ITM_RxBuffer is ready for next character. */ /** \brief ITM Send Character The function transmits a character via the ITM channel 0, and \li Just returns when no debugger is connected that has booked the output. \li Is blocking when a debugger is connected, but the previous character sent has not been transmitted. \param [in] ch Character to transmit. \returns Character to transmit. */ __STATIC_INLINE uint32_t ITM_SendChar (uint32_t ch) { if ((ITM->TCR & ITM_TCR_ITMENA_Msk) && /* ITM enabled */ (ITM->TER & (1UL << 0) ) ) /* ITM Port #0 enabled */ { while (ITM->PORT[0].u32 == 0); ITM->PORT[0].u8 = (uint8_t) ch; } return (ch); } /** \brief ITM Receive Character The function inputs a character via the external variable \ref ITM_RxBuffer. \return Received character. \return -1 No character pending. */ __STATIC_INLINE int32_t ITM_ReceiveChar (void) { int32_t ch = -1; /* no character available */ if (ITM_RxBuffer != ITM_RXBUFFER_EMPTY) { ch = ITM_RxBuffer; ITM_RxBuffer = ITM_RXBUFFER_EMPTY; /* ready for next character */ } return (ch); } /** \brief ITM Check Character The function checks whether a character is pending for reading in the variable \ref ITM_RxBuffer. \return 0 No character available. \return 1 Character available. */ __STATIC_INLINE int32_t ITM_CheckChar (void) { if (ITM_RxBuffer == ITM_RXBUFFER_EMPTY) { return (0); /* no character available */ } else { return (1); /* character available */ } } /*@} end of CMSIS_core_DebugFunctions */ #endif /* __CORE_CM4_H_DEPENDANT */ #endif /* __CMSIS_GENERIC */ #ifdef __cplusplus } #endif ================================================ FILE: Zelig/mbed/TARGET_K64F/core_cm4_simd.h ================================================ /**************************************************************************//** * @file core_cm4_simd.h * @brief CMSIS Cortex-M4 SIMD Header File * @version V3.20 * @date 25. February 2013 * * @note * ******************************************************************************/ /* Copyright (c) 2009 - 2013 ARM LIMITED All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: - Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. - Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. - Neither the name of ARM 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 COPYRIGHT HOLDERS AND CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. ---------------------------------------------------------------------------*/ #ifdef __cplusplus extern "C" { #endif #ifndef __CORE_CM4_SIMD_H #define __CORE_CM4_SIMD_H /******************************************************************************* * Hardware Abstraction Layer ******************************************************************************/ /* ################### Compiler specific Intrinsics ########################### */ /** \defgroup CMSIS_SIMD_intrinsics CMSIS SIMD Intrinsics Access to dedicated SIMD instructions @{ */ #if defined ( __CC_ARM ) /*------------------RealView Compiler -----------------*/ /* ARM armcc specific functions */ /*------ CM4 SIMD Intrinsics -----------------------------------------------------*/ #define __SADD8 __sadd8 #define __QADD8 __qadd8 #define __SHADD8 __shadd8 #define __UADD8 __uadd8 #define __UQADD8 __uqadd8 #define __UHADD8 __uhadd8 #define __SSUB8 __ssub8 #define __QSUB8 __qsub8 #define __SHSUB8 __shsub8 #define __USUB8 __usub8 #define __UQSUB8 __uqsub8 #define __UHSUB8 __uhsub8 #define __SADD16 __sadd16 #define __QADD16 __qadd16 #define __SHADD16 __shadd16 #define __UADD16 __uadd16 #define __UQADD16 __uqadd16 #define __UHADD16 __uhadd16 #define __SSUB16 __ssub16 #define __QSUB16 __qsub16 #define __SHSUB16 __shsub16 #define __USUB16 __usub16 #define __UQSUB16 __uqsub16 #define __UHSUB16 __uhsub16 #define __SASX __sasx #define __QASX __qasx #define __SHASX __shasx #define __UASX __uasx #define __UQASX __uqasx #define __UHASX __uhasx #define __SSAX __ssax #define __QSAX __qsax #define __SHSAX __shsax #define __USAX __usax #define __UQSAX __uqsax #define __UHSAX __uhsax #define __USAD8 __usad8 #define __USADA8 __usada8 #define __SSAT16 __ssat16 #define __USAT16 __usat16 #define __UXTB16 __uxtb16 #define __UXTAB16 __uxtab16 #define __SXTB16 __sxtb16 #define __SXTAB16 __sxtab16 #define __SMUAD __smuad #define __SMUADX __smuadx #define __SMLAD __smlad #define __SMLADX __smladx #define __SMLALD __smlald #define __SMLALDX __smlaldx #define __SMUSD __smusd #define __SMUSDX __smusdx #define __SMLSD __smlsd #define __SMLSDX __smlsdx #define __SMLSLD __smlsld #define __SMLSLDX __smlsldx #define __SEL __sel #define __QADD __qadd #define __QSUB __qsub #define __PKHBT(ARG1,ARG2,ARG3) ( ((((uint32_t)(ARG1)) ) & 0x0000FFFFUL) | \ ((((uint32_t)(ARG2)) << (ARG3)) & 0xFFFF0000UL) ) #define __PKHTB(ARG1,ARG2,ARG3) ( ((((uint32_t)(ARG1)) ) & 0xFFFF0000UL) | \ ((((uint32_t)(ARG2)) >> (ARG3)) & 0x0000FFFFUL) ) #define __SMMLA(ARG1,ARG2,ARG3) ( (int32_t)((((int64_t)(ARG1) * (ARG2)) + \ ((int64_t)(ARG3) << 32) ) >> 32)) /*-- End CM4 SIMD Intrinsics -----------------------------------------------------*/ #elif defined ( __ICCARM__ ) /*------------------ ICC Compiler -------------------*/ /* IAR iccarm specific functions */ /*------ CM4 SIMD Intrinsics -----------------------------------------------------*/ #include /*-- End CM4 SIMD Intrinsics -----------------------------------------------------*/ #elif defined ( __TMS470__ ) /*---------------- TI CCS Compiler ------------------*/ /* TI CCS specific functions */ /*------ CM4 SIMD Intrinsics -----------------------------------------------------*/ #include /*-- End CM4 SIMD Intrinsics -----------------------------------------------------*/ #elif defined ( __GNUC__ ) /*------------------ GNU Compiler ---------------------*/ /* GNU gcc specific functions */ /*------ CM4 SIMD Intrinsics -----------------------------------------------------*/ __attribute__( ( always_inline ) ) __STATIC_INLINE uint32_t __SADD8(uint32_t op1, uint32_t op2) { uint32_t result; __ASM volatile ("sadd8 %0, %1, %2" : "=r" (result) : "r" (op1), "r" (op2) ); return(result); } __attribute__( ( always_inline ) ) __STATIC_INLINE uint32_t __QADD8(uint32_t op1, uint32_t op2) { uint32_t result; __ASM volatile ("qadd8 %0, %1, %2" : "=r" (result) : "r" (op1), "r" (op2) ); return(result); } __attribute__( ( always_inline ) ) __STATIC_INLINE uint32_t __SHADD8(uint32_t op1, uint32_t op2) { uint32_t result; __ASM volatile ("shadd8 %0, %1, %2" : "=r" (result) : "r" (op1), "r" (op2) ); return(result); } __attribute__( ( always_inline ) ) __STATIC_INLINE uint32_t __UADD8(uint32_t op1, uint32_t op2) { uint32_t result; __ASM volatile ("uadd8 %0, %1, %2" : "=r" (result) : "r" (op1), "r" (op2) ); return(result); } __attribute__( ( always_inline ) ) __STATIC_INLINE uint32_t __UQADD8(uint32_t op1, uint32_t op2) { uint32_t result; __ASM volatile ("uqadd8 %0, %1, %2" : "=r" (result) : "r" (op1), "r" (op2) ); return(result); } __attribute__( ( always_inline ) ) __STATIC_INLINE uint32_t __UHADD8(uint32_t op1, uint32_t op2) { uint32_t result; __ASM volatile ("uhadd8 %0, %1, %2" : "=r" (result) : "r" (op1), "r" (op2) ); return(result); } __attribute__( ( always_inline ) ) __STATIC_INLINE uint32_t __SSUB8(uint32_t op1, uint32_t op2) { uint32_t result; __ASM volatile ("ssub8 %0, %1, %2" : "=r" (result) : "r" (op1), "r" (op2) ); return(result); } __attribute__( ( always_inline ) ) __STATIC_INLINE uint32_t __QSUB8(uint32_t op1, uint32_t op2) { uint32_t result; __ASM volatile ("qsub8 %0, %1, %2" : "=r" (result) : "r" (op1), "r" (op2) ); return(result); } __attribute__( ( always_inline ) ) __STATIC_INLINE uint32_t __SHSUB8(uint32_t op1, uint32_t op2) { uint32_t result; __ASM volatile ("shsub8 %0, %1, %2" : "=r" (result) : "r" (op1), "r" (op2) ); return(result); } __attribute__( ( always_inline ) ) __STATIC_INLINE uint32_t __USUB8(uint32_t op1, uint32_t op2) { uint32_t result; __ASM volatile ("usub8 %0, %1, %2" : "=r" (result) : "r" (op1), "r" (op2) ); return(result); } __attribute__( ( always_inline ) ) __STATIC_INLINE uint32_t __UQSUB8(uint32_t op1, uint32_t op2) { uint32_t result; __ASM volatile ("uqsub8 %0, %1, %2" : "=r" (result) : "r" (op1), "r" (op2) ); return(result); } __attribute__( ( always_inline ) ) __STATIC_INLINE uint32_t __UHSUB8(uint32_t op1, uint32_t op2) { uint32_t result; __ASM volatile ("uhsub8 %0, %1, %2" : "=r" (result) : "r" (op1), "r" (op2) ); return(result); } __attribute__( ( always_inline ) ) __STATIC_INLINE uint32_t __SADD16(uint32_t op1, uint32_t op2) { uint32_t result; __ASM volatile ("sadd16 %0, %1, %2" : "=r" (result) : "r" (op1), "r" (op2) ); return(result); } __attribute__( ( always_inline ) ) __STATIC_INLINE uint32_t __QADD16(uint32_t op1, uint32_t op2) { uint32_t result; __ASM volatile ("qadd16 %0, %1, %2" : "=r" (result) : "r" (op1), "r" (op2) ); return(result); } __attribute__( ( always_inline ) ) __STATIC_INLINE uint32_t __SHADD16(uint32_t op1, uint32_t op2) { uint32_t result; __ASM volatile ("shadd16 %0, %1, %2" : "=r" (result) : "r" (op1), "r" (op2) ); return(result); } __attribute__( ( always_inline ) ) __STATIC_INLINE uint32_t __UADD16(uint32_t op1, uint32_t op2) { uint32_t result; __ASM volatile ("uadd16 %0, %1, %2" : "=r" (result) : "r" (op1), "r" (op2) ); return(result); } __attribute__( ( always_inline ) ) __STATIC_INLINE uint32_t __UQADD16(uint32_t op1, uint32_t op2) { uint32_t result; __ASM volatile ("uqadd16 %0, %1, %2" : "=r" (result) : "r" (op1), "r" (op2) ); return(result); } __attribute__( ( always_inline ) ) __STATIC_INLINE uint32_t __UHADD16(uint32_t op1, uint32_t op2) { uint32_t result; __ASM volatile ("uhadd16 %0, %1, %2" : "=r" (result) : "r" (op1), "r" (op2) ); return(result); } __attribute__( ( always_inline ) ) __STATIC_INLINE uint32_t __SSUB16(uint32_t op1, uint32_t op2) { uint32_t result; __ASM volatile ("ssub16 %0, %1, %2" : "=r" (result) : "r" (op1), "r" (op2) ); return(result); } __attribute__( ( always_inline ) ) __STATIC_INLINE uint32_t __QSUB16(uint32_t op1, uint32_t op2) { uint32_t result; __ASM volatile ("qsub16 %0, %1, %2" : "=r" (result) : "r" (op1), "r" (op2) ); return(result); } __attribute__( ( always_inline ) ) __STATIC_INLINE uint32_t __SHSUB16(uint32_t op1, uint32_t op2) { uint32_t result; __ASM volatile ("shsub16 %0, %1, %2" : "=r" (result) : "r" (op1), "r" (op2) ); return(result); } __attribute__( ( always_inline ) ) __STATIC_INLINE uint32_t __USUB16(uint32_t op1, uint32_t op2) { uint32_t result; __ASM volatile ("usub16 %0, %1, %2" : "=r" (result) : "r" (op1), "r" (op2) ); return(result); } __attribute__( ( always_inline ) ) __STATIC_INLINE uint32_t __UQSUB16(uint32_t op1, uint32_t op2) { uint32_t result; __ASM volatile ("uqsub16 %0, %1, %2" : "=r" (result) : "r" (op1), "r" (op2) ); return(result); } __attribute__( ( always_inline ) ) __STATIC_INLINE uint32_t __UHSUB16(uint32_t op1, uint32_t op2) { uint32_t result; __ASM volatile ("uhsub16 %0, %1, %2" : "=r" (result) : "r" (op1), "r" (op2) ); return(result); } __attribute__( ( always_inline ) ) __STATIC_INLINE uint32_t __SASX(uint32_t op1, uint32_t op2) { uint32_t result; __ASM volatile ("sasx %0, %1, %2" : "=r" (result) : "r" (op1), "r" (op2) ); return(result); } __attribute__( ( always_inline ) ) __STATIC_INLINE uint32_t __QASX(uint32_t op1, uint32_t op2) { uint32_t result; __ASM volatile ("qasx %0, %1, %2" : "=r" (result) : "r" (op1), "r" (op2) ); return(result); } __attribute__( ( always_inline ) ) __STATIC_INLINE uint32_t __SHASX(uint32_t op1, uint32_t op2) { uint32_t result; __ASM volatile ("shasx %0, %1, %2" : "=r" (result) : "r" (op1), "r" (op2) ); return(result); } __attribute__( ( always_inline ) ) __STATIC_INLINE uint32_t __UASX(uint32_t op1, uint32_t op2) { uint32_t result; __ASM volatile ("uasx %0, %1, %2" : "=r" (result) : "r" (op1), "r" (op2) ); return(result); } __attribute__( ( always_inline ) ) __STATIC_INLINE uint32_t __UQASX(uint32_t op1, uint32_t op2) { uint32_t result; __ASM volatile ("uqasx %0, %1, %2" : "=r" (result) : "r" (op1), "r" (op2) ); return(result); } __attribute__( ( always_inline ) ) __STATIC_INLINE uint32_t __UHASX(uint32_t op1, uint32_t op2) { uint32_t result; __ASM volatile ("uhasx %0, %1, %2" : "=r" (result) : "r" (op1), "r" (op2) ); return(result); } __attribute__( ( always_inline ) ) __STATIC_INLINE uint32_t __SSAX(uint32_t op1, uint32_t op2) { uint32_t result; __ASM volatile ("ssax %0, %1, %2" : "=r" (result) : "r" (op1), "r" (op2) ); return(result); } __attribute__( ( always_inline ) ) __STATIC_INLINE uint32_t __QSAX(uint32_t op1, uint32_t op2) { uint32_t result; __ASM volatile ("qsax %0, %1, %2" : "=r" (result) : "r" (op1), "r" (op2) ); return(result); } __attribute__( ( always_inline ) ) __STATIC_INLINE uint32_t __SHSAX(uint32_t op1, uint32_t op2) { uint32_t result; __ASM volatile ("shsax %0, %1, %2" : "=r" (result) : "r" (op1), "r" (op2) ); return(result); } __attribute__( ( always_inline ) ) __STATIC_INLINE uint32_t __USAX(uint32_t op1, uint32_t op2) { uint32_t result; __ASM volatile ("usax %0, %1, %2" : "=r" (result) : "r" (op1), "r" (op2) ); return(result); } __attribute__( ( always_inline ) ) __STATIC_INLINE uint32_t __UQSAX(uint32_t op1, uint32_t op2) { uint32_t result; __ASM volatile ("uqsax %0, %1, %2" : "=r" (result) : "r" (op1), "r" (op2) ); return(result); } __attribute__( ( always_inline ) ) __STATIC_INLINE uint32_t __UHSAX(uint32_t op1, uint32_t op2) { uint32_t result; __ASM volatile ("uhsax %0, %1, %2" : "=r" (result) : "r" (op1), "r" (op2) ); return(result); } __attribute__( ( always_inline ) ) __STATIC_INLINE uint32_t __USAD8(uint32_t op1, uint32_t op2) { uint32_t result; __ASM volatile ("usad8 %0, %1, %2" : "=r" (result) : "r" (op1), "r" (op2) ); return(result); } __attribute__( ( always_inline ) ) __STATIC_INLINE uint32_t __USADA8(uint32_t op1, uint32_t op2, uint32_t op3) { uint32_t result; __ASM volatile ("usada8 %0, %1, %2, %3" : "=r" (result) : "r" (op1), "r" (op2), "r" (op3) ); return(result); } #define __SSAT16(ARG1,ARG2) \ ({ \ uint32_t __RES, __ARG1 = (ARG1); \ __ASM ("ssat16 %0, %1, %2" : "=r" (__RES) : "I" (ARG2), "r" (__ARG1) ); \ __RES; \ }) #define __USAT16(ARG1,ARG2) \ ({ \ uint32_t __RES, __ARG1 = (ARG1); \ __ASM ("usat16 %0, %1, %2" : "=r" (__RES) : "I" (ARG2), "r" (__ARG1) ); \ __RES; \ }) __attribute__( ( always_inline ) ) __STATIC_INLINE uint32_t __UXTB16(uint32_t op1) { uint32_t result; __ASM volatile ("uxtb16 %0, %1" : "=r" (result) : "r" (op1)); return(result); } __attribute__( ( always_inline ) ) __STATIC_INLINE uint32_t __UXTAB16(uint32_t op1, uint32_t op2) { uint32_t result; __ASM volatile ("uxtab16 %0, %1, %2" : "=r" (result) : "r" (op1), "r" (op2) ); return(result); } __attribute__( ( always_inline ) ) __STATIC_INLINE uint32_t __SXTB16(uint32_t op1) { uint32_t result; __ASM volatile ("sxtb16 %0, %1" : "=r" (result) : "r" (op1)); return(result); } __attribute__( ( always_inline ) ) __STATIC_INLINE uint32_t __SXTAB16(uint32_t op1, uint32_t op2) { uint32_t result; __ASM volatile ("sxtab16 %0, %1, %2" : "=r" (result) : "r" (op1), "r" (op2) ); return(result); } __attribute__( ( always_inline ) ) __STATIC_INLINE uint32_t __SMUAD (uint32_t op1, uint32_t op2) { uint32_t result; __ASM volatile ("smuad %0, %1, %2" : "=r" (result) : "r" (op1), "r" (op2) ); return(result); } __attribute__( ( always_inline ) ) __STATIC_INLINE uint32_t __SMUADX (uint32_t op1, uint32_t op2) { uint32_t result; __ASM volatile ("smuadx %0, %1, %2" : "=r" (result) : "r" (op1), "r" (op2) ); return(result); } __attribute__( ( always_inline ) ) __STATIC_INLINE uint32_t __SMLAD (uint32_t op1, uint32_t op2, uint32_t op3) { uint32_t result; __ASM volatile ("smlad %0, %1, %2, %3" : "=r" (result) : "r" (op1), "r" (op2), "r" (op3) ); return(result); } __attribute__( ( always_inline ) ) __STATIC_INLINE uint32_t __SMLADX (uint32_t op1, uint32_t op2, uint32_t op3) { uint32_t result; __ASM volatile ("smladx %0, %1, %2, %3" : "=r" (result) : "r" (op1), "r" (op2), "r" (op3) ); return(result); } #define __SMLALD(ARG1,ARG2,ARG3) \ ({ \ uint32_t __ARG1 = (ARG1), __ARG2 = (ARG2), __ARG3_H = (uint32_t)((uint64_t)(ARG3) >> 32), __ARG3_L = (uint32_t)((uint64_t)(ARG3) & 0xFFFFFFFFUL); \ __ASM volatile ("smlald %0, %1, %2, %3" : "=r" (__ARG3_L), "=r" (__ARG3_H) : "r" (__ARG1), "r" (__ARG2), "0" (__ARG3_L), "1" (__ARG3_H) ); \ (uint64_t)(((uint64_t)__ARG3_H << 32) | __ARG3_L); \ }) #define __SMLALDX(ARG1,ARG2,ARG3) \ ({ \ uint32_t __ARG1 = (ARG1), __ARG2 = (ARG2), __ARG3_H = (uint32_t)((uint64_t)(ARG3) >> 32), __ARG3_L = (uint32_t)((uint64_t)(ARG3) & 0xFFFFFFFFUL); \ __ASM volatile ("smlaldx %0, %1, %2, %3" : "=r" (__ARG3_L), "=r" (__ARG3_H) : "r" (__ARG1), "r" (__ARG2), "0" (__ARG3_L), "1" (__ARG3_H) ); \ (uint64_t)(((uint64_t)__ARG3_H << 32) | __ARG3_L); \ }) __attribute__( ( always_inline ) ) __STATIC_INLINE uint32_t __SMUSD (uint32_t op1, uint32_t op2) { uint32_t result; __ASM volatile ("smusd %0, %1, %2" : "=r" (result) : "r" (op1), "r" (op2) ); return(result); } __attribute__( ( always_inline ) ) __STATIC_INLINE uint32_t __SMUSDX (uint32_t op1, uint32_t op2) { uint32_t result; __ASM volatile ("smusdx %0, %1, %2" : "=r" (result) : "r" (op1), "r" (op2) ); return(result); } __attribute__( ( always_inline ) ) __STATIC_INLINE uint32_t __SMLSD (uint32_t op1, uint32_t op2, uint32_t op3) { uint32_t result; __ASM volatile ("smlsd %0, %1, %2, %3" : "=r" (result) : "r" (op1), "r" (op2), "r" (op3) ); return(result); } __attribute__( ( always_inline ) ) __STATIC_INLINE uint32_t __SMLSDX (uint32_t op1, uint32_t op2, uint32_t op3) { uint32_t result; __ASM volatile ("smlsdx %0, %1, %2, %3" : "=r" (result) : "r" (op1), "r" (op2), "r" (op3) ); return(result); } #define __SMLSLD(ARG1,ARG2,ARG3) \ ({ \ uint32_t __ARG1 = (ARG1), __ARG2 = (ARG2), __ARG3_H = (uint32_t)((ARG3) >> 32), __ARG3_L = (uint32_t)((ARG3) & 0xFFFFFFFFUL); \ __ASM volatile ("smlsld %0, %1, %2, %3" : "=r" (__ARG3_L), "=r" (__ARG3_H) : "r" (__ARG1), "r" (__ARG2), "0" (__ARG3_L), "1" (__ARG3_H) ); \ (uint64_t)(((uint64_t)__ARG3_H << 32) | __ARG3_L); \ }) #define __SMLSLDX(ARG1,ARG2,ARG3) \ ({ \ uint32_t __ARG1 = (ARG1), __ARG2 = (ARG2), __ARG3_H = (uint32_t)((ARG3) >> 32), __ARG3_L = (uint32_t)((ARG3) & 0xFFFFFFFFUL); \ __ASM volatile ("smlsldx %0, %1, %2, %3" : "=r" (__ARG3_L), "=r" (__ARG3_H) : "r" (__ARG1), "r" (__ARG2), "0" (__ARG3_L), "1" (__ARG3_H) ); \ (uint64_t)(((uint64_t)__ARG3_H << 32) | __ARG3_L); \ }) __attribute__( ( always_inline ) ) __STATIC_INLINE uint32_t __SEL (uint32_t op1, uint32_t op2) { uint32_t result; __ASM volatile ("sel %0, %1, %2" : "=r" (result) : "r" (op1), "r" (op2) ); return(result); } __attribute__( ( always_inline ) ) __STATIC_INLINE uint32_t __QADD(uint32_t op1, uint32_t op2) { uint32_t result; __ASM volatile ("qadd %0, %1, %2" : "=r" (result) : "r" (op1), "r" (op2) ); return(result); } __attribute__( ( always_inline ) ) __STATIC_INLINE uint32_t __QSUB(uint32_t op1, uint32_t op2) { uint32_t result; __ASM volatile ("qsub %0, %1, %2" : "=r" (result) : "r" (op1), "r" (op2) ); return(result); } #define __PKHBT(ARG1,ARG2,ARG3) \ ({ \ uint32_t __RES, __ARG1 = (ARG1), __ARG2 = (ARG2); \ __ASM ("pkhbt %0, %1, %2, lsl %3" : "=r" (__RES) : "r" (__ARG1), "r" (__ARG2), "I" (ARG3) ); \ __RES; \ }) #define __PKHTB(ARG1,ARG2,ARG3) \ ({ \ uint32_t __RES, __ARG1 = (ARG1), __ARG2 = (ARG2); \ if (ARG3 == 0) \ __ASM ("pkhtb %0, %1, %2" : "=r" (__RES) : "r" (__ARG1), "r" (__ARG2) ); \ else \ __ASM ("pkhtb %0, %1, %2, asr %3" : "=r" (__RES) : "r" (__ARG1), "r" (__ARG2), "I" (ARG3) ); \ __RES; \ }) __attribute__( ( always_inline ) ) __STATIC_INLINE uint32_t __SMMLA (int32_t op1, int32_t op2, int32_t op3) { int32_t result; __ASM volatile ("smmla %0, %1, %2, %3" : "=r" (result): "r" (op1), "r" (op2), "r" (op3) ); return(result); } /*-- End CM4 SIMD Intrinsics -----------------------------------------------------*/ #elif defined ( __TASKING__ ) /*------------------ TASKING Compiler --------------*/ /* TASKING carm specific functions */ /*------ CM4 SIMD Intrinsics -----------------------------------------------------*/ /* not yet supported */ /*-- End CM4 SIMD Intrinsics -----------------------------------------------------*/ #endif /*@} end of group CMSIS_SIMD_intrinsics */ #endif /* __CORE_CM4_SIMD_H */ #ifdef __cplusplus } #endif ================================================ FILE: Zelig/mbed/TARGET_K64F/core_cm7.h ================================================ /**************************************************************************//** * @file core_cm7.h * @brief CMSIS Cortex-M7 Core Peripheral Access Layer Header File * @version V4.10 * @date 18. March 2015 * * @note * ******************************************************************************/ /* Copyright (c) 2009 - 2015 ARM LIMITED All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: - Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. - Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. - Neither the name of ARM 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 COPYRIGHT HOLDERS AND 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. ---------------------------------------------------------------------------*/ #if defined ( __ICCARM__ ) #pragma system_include /* treat file as system include file for MISRA check */ #endif #ifndef __CORE_CM7_H_GENERIC #define __CORE_CM7_H_GENERIC #ifdef __cplusplus extern "C" { #endif /** \page CMSIS_MISRA_Exceptions MISRA-C:2004 Compliance Exceptions CMSIS violates the following MISRA-C:2004 rules: \li Required Rule 8.5, object/function definition in header file.
Function definitions in header files are used to allow 'inlining'. \li Required Rule 18.4, declaration of union type or object of union type: '{...}'.
Unions are used for effective representation of core registers. \li Advisory Rule 19.7, Function-like macro defined.
Function-like macros are used to allow more efficient code. */ /******************************************************************************* * CMSIS definitions ******************************************************************************/ /** \ingroup Cortex_M7 @{ */ /* CMSIS CM7 definitions */ #define __CM7_CMSIS_VERSION_MAIN (0x04) /*!< [31:16] CMSIS HAL main version */ #define __CM7_CMSIS_VERSION_SUB (0x00) /*!< [15:0] CMSIS HAL sub version */ #define __CM7_CMSIS_VERSION ((__CM7_CMSIS_VERSION_MAIN << 16) | \ __CM7_CMSIS_VERSION_SUB ) /*!< CMSIS HAL version number */ #define __CORTEX_M (0x07) /*!< Cortex-M Core */ #if defined ( __CC_ARM ) #define __ASM __asm /*!< asm keyword for ARM Compiler */ #define __INLINE __inline /*!< inline keyword for ARM Compiler */ #define __STATIC_INLINE static __inline #elif defined ( __GNUC__ ) #define __ASM __asm /*!< asm keyword for GNU Compiler */ #define __INLINE inline /*!< inline keyword for GNU Compiler */ #define __STATIC_INLINE static inline #elif defined ( __ICCARM__ ) #define __ASM __asm /*!< asm keyword for IAR Compiler */ #define __INLINE inline /*!< inline keyword for IAR Compiler. Only available in High optimization mode! */ #define __STATIC_INLINE static inline #elif defined ( __TMS470__ ) #define __ASM __asm /*!< asm keyword for TI CCS Compiler */ #define __STATIC_INLINE static inline #elif defined ( __TASKING__ ) #define __ASM __asm /*!< asm keyword for TASKING Compiler */ #define __INLINE inline /*!< inline keyword for TASKING Compiler */ #define __STATIC_INLINE static inline #elif defined ( __CSMC__ ) #define __packed #define __ASM _asm /*!< asm keyword for COSMIC Compiler */ #define __INLINE inline /*use -pc99 on compile line !< inline keyword for COSMIC Compiler */ #define __STATIC_INLINE static inline #endif /** __FPU_USED indicates whether an FPU is used or not. For this, __FPU_PRESENT has to be checked prior to making use of FPU specific registers and functions. */ #if defined ( __CC_ARM ) #if defined __TARGET_FPU_VFP #if (__FPU_PRESENT == 1) #define __FPU_USED 1 #else #warning "Compiler generates FPU instructions for a device without an FPU (check __FPU_PRESENT)" #define __FPU_USED 0 #endif #else #define __FPU_USED 0 #endif #elif defined ( __GNUC__ ) #if defined (__VFP_FP__) && !defined(__SOFTFP__) #if (__FPU_PRESENT == 1) #define __FPU_USED 1 #else #warning "Compiler generates FPU instructions for a device without an FPU (check __FPU_PRESENT)" #define __FPU_USED 0 #endif #else #define __FPU_USED 0 #endif #elif defined ( __ICCARM__ ) #if defined __ARMVFP__ #if (__FPU_PRESENT == 1) #define __FPU_USED 1 #else #warning "Compiler generates FPU instructions for a device without an FPU (check __FPU_PRESENT)" #define __FPU_USED 0 #endif #else #define __FPU_USED 0 #endif #elif defined ( __TMS470__ ) #if defined __TI_VFP_SUPPORT__ #if (__FPU_PRESENT == 1) #define __FPU_USED 1 #else #warning "Compiler generates FPU instructions for a device without an FPU (check __FPU_PRESENT)" #define __FPU_USED 0 #endif #else #define __FPU_USED 0 #endif #elif defined ( __TASKING__ ) #if defined __FPU_VFP__ #if (__FPU_PRESENT == 1) #define __FPU_USED 1 #else #error "Compiler generates FPU instructions for a device without an FPU (check __FPU_PRESENT)" #define __FPU_USED 0 #endif #else #define __FPU_USED 0 #endif #elif defined ( __CSMC__ ) /* Cosmic */ #if ( __CSMC__ & 0x400) // FPU present for parser #if (__FPU_PRESENT == 1) #define __FPU_USED 1 #else #error "Compiler generates FPU instructions for a device without an FPU (check __FPU_PRESENT)" #define __FPU_USED 0 #endif #else #define __FPU_USED 0 #endif #endif #include /* standard types definitions */ #include /* Core Instruction Access */ #include /* Core Function Access */ #include /* Compiler specific SIMD Intrinsics */ #ifdef __cplusplus } #endif #endif /* __CORE_CM7_H_GENERIC */ #ifndef __CMSIS_GENERIC #ifndef __CORE_CM7_H_DEPENDANT #define __CORE_CM7_H_DEPENDANT #ifdef __cplusplus extern "C" { #endif /* check device defines and use defaults */ #if defined __CHECK_DEVICE_DEFINES #ifndef __CM7_REV #define __CM7_REV 0x0000 #warning "__CM7_REV not defined in device header file; using default!" #endif #ifndef __FPU_PRESENT #define __FPU_PRESENT 0 #warning "__FPU_PRESENT not defined in device header file; using default!" #endif #ifndef __MPU_PRESENT #define __MPU_PRESENT 0 #warning "__MPU_PRESENT not defined in device header file; using default!" #endif #ifndef __ICACHE_PRESENT #define __ICACHE_PRESENT 0 #warning "__ICACHE_PRESENT not defined in device header file; using default!" #endif #ifndef __DCACHE_PRESENT #define __DCACHE_PRESENT 0 #warning "__DCACHE_PRESENT not defined in device header file; using default!" #endif #ifndef __DTCM_PRESENT #define __DTCM_PRESENT 0 #warning "__DTCM_PRESENT not defined in device header file; using default!" #endif #ifndef __NVIC_PRIO_BITS #define __NVIC_PRIO_BITS 3 #warning "__NVIC_PRIO_BITS not defined in device header file; using default!" #endif #ifndef __Vendor_SysTickConfig #define __Vendor_SysTickConfig 0 #warning "__Vendor_SysTickConfig not defined in device header file; using default!" #endif #endif /* IO definitions (access restrictions to peripheral registers) */ /** \defgroup CMSIS_glob_defs CMSIS Global Defines IO Type Qualifiers are used \li to specify the access to peripheral variables. \li for automatic generation of peripheral register debug information. */ #ifdef __cplusplus #define __I volatile /*!< Defines 'read only' permissions */ #else #define __I volatile const /*!< Defines 'read only' permissions */ #endif #define __O volatile /*!< Defines 'write only' permissions */ #define __IO volatile /*!< Defines 'read / write' permissions */ /*@} end of group Cortex_M7 */ /******************************************************************************* * Register Abstraction Core Register contain: - Core Register - Core NVIC Register - Core SCB Register - Core SysTick Register - Core Debug Register - Core MPU Register - Core FPU Register ******************************************************************************/ /** \defgroup CMSIS_core_register Defines and Type Definitions \brief Type definitions and defines for Cortex-M processor based devices. */ /** \ingroup CMSIS_core_register \defgroup CMSIS_CORE Status and Control Registers \brief Core Register type definitions. @{ */ /** \brief Union type to access the Application Program Status Register (APSR). */ typedef union { struct { uint32_t _reserved0:16; /*!< bit: 0..15 Reserved */ uint32_t GE:4; /*!< bit: 16..19 Greater than or Equal flags */ uint32_t _reserved1:7; /*!< bit: 20..26 Reserved */ uint32_t Q:1; /*!< bit: 27 Saturation condition flag */ uint32_t V:1; /*!< bit: 28 Overflow condition code flag */ uint32_t C:1; /*!< bit: 29 Carry condition code flag */ uint32_t Z:1; /*!< bit: 30 Zero condition code flag */ uint32_t N:1; /*!< bit: 31 Negative condition code flag */ } b; /*!< Structure used for bit access */ uint32_t w; /*!< Type used for word access */ } APSR_Type; /* APSR Register Definitions */ #define APSR_N_Pos 31 /*!< APSR: N Position */ #define APSR_N_Msk (1UL << APSR_N_Pos) /*!< APSR: N Mask */ #define APSR_Z_Pos 30 /*!< APSR: Z Position */ #define APSR_Z_Msk (1UL << APSR_Z_Pos) /*!< APSR: Z Mask */ #define APSR_C_Pos 29 /*!< APSR: C Position */ #define APSR_C_Msk (1UL << APSR_C_Pos) /*!< APSR: C Mask */ #define APSR_V_Pos 28 /*!< APSR: V Position */ #define APSR_V_Msk (1UL << APSR_V_Pos) /*!< APSR: V Mask */ #define APSR_Q_Pos 27 /*!< APSR: Q Position */ #define APSR_Q_Msk (1UL << APSR_Q_Pos) /*!< APSR: Q Mask */ #define APSR_GE_Pos 16 /*!< APSR: GE Position */ #define APSR_GE_Msk (0xFUL << APSR_GE_Pos) /*!< APSR: GE Mask */ /** \brief Union type to access the Interrupt Program Status Register (IPSR). */ typedef union { struct { uint32_t ISR:9; /*!< bit: 0.. 8 Exception number */ uint32_t _reserved0:23; /*!< bit: 9..31 Reserved */ } b; /*!< Structure used for bit access */ uint32_t w; /*!< Type used for word access */ } IPSR_Type; /* IPSR Register Definitions */ #define IPSR_ISR_Pos 0 /*!< IPSR: ISR Position */ #define IPSR_ISR_Msk (0x1FFUL /*<< IPSR_ISR_Pos*/) /*!< IPSR: ISR Mask */ /** \brief Union type to access the Special-Purpose Program Status Registers (xPSR). */ typedef union { struct { uint32_t ISR:9; /*!< bit: 0.. 8 Exception number */ uint32_t _reserved0:7; /*!< bit: 9..15 Reserved */ uint32_t GE:4; /*!< bit: 16..19 Greater than or Equal flags */ uint32_t _reserved1:4; /*!< bit: 20..23 Reserved */ uint32_t T:1; /*!< bit: 24 Thumb bit (read 0) */ uint32_t IT:2; /*!< bit: 25..26 saved IT state (read 0) */ uint32_t Q:1; /*!< bit: 27 Saturation condition flag */ uint32_t V:1; /*!< bit: 28 Overflow condition code flag */ uint32_t C:1; /*!< bit: 29 Carry condition code flag */ uint32_t Z:1; /*!< bit: 30 Zero condition code flag */ uint32_t N:1; /*!< bit: 31 Negative condition code flag */ } b; /*!< Structure used for bit access */ uint32_t w; /*!< Type used for word access */ } xPSR_Type; /* xPSR Register Definitions */ #define xPSR_N_Pos 31 /*!< xPSR: N Position */ #define xPSR_N_Msk (1UL << xPSR_N_Pos) /*!< xPSR: N Mask */ #define xPSR_Z_Pos 30 /*!< xPSR: Z Position */ #define xPSR_Z_Msk (1UL << xPSR_Z_Pos) /*!< xPSR: Z Mask */ #define xPSR_C_Pos 29 /*!< xPSR: C Position */ #define xPSR_C_Msk (1UL << xPSR_C_Pos) /*!< xPSR: C Mask */ #define xPSR_V_Pos 28 /*!< xPSR: V Position */ #define xPSR_V_Msk (1UL << xPSR_V_Pos) /*!< xPSR: V Mask */ #define xPSR_Q_Pos 27 /*!< xPSR: Q Position */ #define xPSR_Q_Msk (1UL << xPSR_Q_Pos) /*!< xPSR: Q Mask */ #define xPSR_IT_Pos 25 /*!< xPSR: IT Position */ #define xPSR_IT_Msk (3UL << xPSR_IT_Pos) /*!< xPSR: IT Mask */ #define xPSR_T_Pos 24 /*!< xPSR: T Position */ #define xPSR_T_Msk (1UL << xPSR_T_Pos) /*!< xPSR: T Mask */ #define xPSR_GE_Pos 16 /*!< xPSR: GE Position */ #define xPSR_GE_Msk (0xFUL << xPSR_GE_Pos) /*!< xPSR: GE Mask */ #define xPSR_ISR_Pos 0 /*!< xPSR: ISR Position */ #define xPSR_ISR_Msk (0x1FFUL /*<< xPSR_ISR_Pos*/) /*!< xPSR: ISR Mask */ /** \brief Union type to access the Control Registers (CONTROL). */ typedef union { struct { uint32_t nPRIV:1; /*!< bit: 0 Execution privilege in Thread mode */ uint32_t SPSEL:1; /*!< bit: 1 Stack to be used */ uint32_t FPCA:1; /*!< bit: 2 FP extension active flag */ uint32_t _reserved0:29; /*!< bit: 3..31 Reserved */ } b; /*!< Structure used for bit access */ uint32_t w; /*!< Type used for word access */ } CONTROL_Type; /* CONTROL Register Definitions */ #define CONTROL_FPCA_Pos 2 /*!< CONTROL: FPCA Position */ #define CONTROL_FPCA_Msk (1UL << CONTROL_FPCA_Pos) /*!< CONTROL: FPCA Mask */ #define CONTROL_SPSEL_Pos 1 /*!< CONTROL: SPSEL Position */ #define CONTROL_SPSEL_Msk (1UL << CONTROL_SPSEL_Pos) /*!< CONTROL: SPSEL Mask */ #define CONTROL_nPRIV_Pos 0 /*!< CONTROL: nPRIV Position */ #define CONTROL_nPRIV_Msk (1UL /*<< CONTROL_nPRIV_Pos*/) /*!< CONTROL: nPRIV Mask */ /*@} end of group CMSIS_CORE */ /** \ingroup CMSIS_core_register \defgroup CMSIS_NVIC Nested Vectored Interrupt Controller (NVIC) \brief Type definitions for the NVIC Registers @{ */ /** \brief Structure type to access the Nested Vectored Interrupt Controller (NVIC). */ typedef struct { __IO uint32_t ISER[8]; /*!< Offset: 0x000 (R/W) Interrupt Set Enable Register */ uint32_t RESERVED0[24]; __IO uint32_t ICER[8]; /*!< Offset: 0x080 (R/W) Interrupt Clear Enable Register */ uint32_t RSERVED1[24]; __IO uint32_t ISPR[8]; /*!< Offset: 0x100 (R/W) Interrupt Set Pending Register */ uint32_t RESERVED2[24]; __IO uint32_t ICPR[8]; /*!< Offset: 0x180 (R/W) Interrupt Clear Pending Register */ uint32_t RESERVED3[24]; __IO uint32_t IABR[8]; /*!< Offset: 0x200 (R/W) Interrupt Active bit Register */ uint32_t RESERVED4[56]; __IO uint8_t IP[240]; /*!< Offset: 0x300 (R/W) Interrupt Priority Register (8Bit wide) */ uint32_t RESERVED5[644]; __O uint32_t STIR; /*!< Offset: 0xE00 ( /W) Software Trigger Interrupt Register */ } NVIC_Type; /* Software Triggered Interrupt Register Definitions */ #define NVIC_STIR_INTID_Pos 0 /*!< STIR: INTLINESNUM Position */ #define NVIC_STIR_INTID_Msk (0x1FFUL /*<< NVIC_STIR_INTID_Pos*/) /*!< STIR: INTLINESNUM Mask */ /*@} end of group CMSIS_NVIC */ /** \ingroup CMSIS_core_register \defgroup CMSIS_SCB System Control Block (SCB) \brief Type definitions for the System Control Block Registers @{ */ /** \brief Structure type to access the System Control Block (SCB). */ typedef struct { __I uint32_t CPUID; /*!< Offset: 0x000 (R/ ) CPUID Base Register */ __IO uint32_t ICSR; /*!< Offset: 0x004 (R/W) Interrupt Control and State Register */ __IO uint32_t VTOR; /*!< Offset: 0x008 (R/W) Vector Table Offset Register */ __IO uint32_t AIRCR; /*!< Offset: 0x00C (R/W) Application Interrupt and Reset Control Register */ __IO uint32_t SCR; /*!< Offset: 0x010 (R/W) System Control Register */ __IO uint32_t CCR; /*!< Offset: 0x014 (R/W) Configuration Control Register */ __IO uint8_t SHPR[12]; /*!< Offset: 0x018 (R/W) System Handlers Priority Registers (4-7, 8-11, 12-15) */ __IO uint32_t SHCSR; /*!< Offset: 0x024 (R/W) System Handler Control and State Register */ __IO uint32_t CFSR; /*!< Offset: 0x028 (R/W) Configurable Fault Status Register */ __IO uint32_t HFSR; /*!< Offset: 0x02C (R/W) HardFault Status Register */ __IO uint32_t DFSR; /*!< Offset: 0x030 (R/W) Debug Fault Status Register */ __IO uint32_t MMFAR; /*!< Offset: 0x034 (R/W) MemManage Fault Address Register */ __IO uint32_t BFAR; /*!< Offset: 0x038 (R/W) BusFault Address Register */ __IO uint32_t AFSR; /*!< Offset: 0x03C (R/W) Auxiliary Fault Status Register */ __I uint32_t ID_PFR[2]; /*!< Offset: 0x040 (R/ ) Processor Feature Register */ __I uint32_t ID_DFR; /*!< Offset: 0x048 (R/ ) Debug Feature Register */ __I uint32_t ID_AFR; /*!< Offset: 0x04C (R/ ) Auxiliary Feature Register */ __I uint32_t ID_MFR[4]; /*!< Offset: 0x050 (R/ ) Memory Model Feature Register */ __I uint32_t ID_ISAR[5]; /*!< Offset: 0x060 (R/ ) Instruction Set Attributes Register */ uint32_t RESERVED0[1]; __I uint32_t CLIDR; /*!< Offset: 0x078 (R/ ) Cache Level ID register */ __I uint32_t CTR; /*!< Offset: 0x07C (R/ ) Cache Type register */ __I uint32_t CCSIDR; /*!< Offset: 0x080 (R/ ) Cache Size ID Register */ __IO uint32_t CSSELR; /*!< Offset: 0x084 (R/W) Cache Size Selection Register */ __IO uint32_t CPACR; /*!< Offset: 0x088 (R/W) Coprocessor Access Control Register */ uint32_t RESERVED3[93]; __O uint32_t STIR; /*!< Offset: 0x200 ( /W) Software Triggered Interrupt Register */ uint32_t RESERVED4[15]; __I uint32_t MVFR0; /*!< Offset: 0x240 (R/ ) Media and VFP Feature Register 0 */ __I uint32_t MVFR1; /*!< Offset: 0x244 (R/ ) Media and VFP Feature Register 1 */ __I uint32_t MVFR2; /*!< Offset: 0x248 (R/ ) Media and VFP Feature Register 1 */ uint32_t RESERVED5[1]; __O uint32_t ICIALLU; /*!< Offset: 0x250 ( /W) I-Cache Invalidate All to PoU */ uint32_t RESERVED6[1]; __O uint32_t ICIMVAU; /*!< Offset: 0x258 ( /W) I-Cache Invalidate by MVA to PoU */ __O uint32_t DCIMVAC; /*!< Offset: 0x25C ( /W) D-Cache Invalidate by MVA to PoC */ __O uint32_t DCISW; /*!< Offset: 0x260 ( /W) D-Cache Invalidate by Set-way */ __O uint32_t DCCMVAU; /*!< Offset: 0x264 ( /W) D-Cache Clean by MVA to PoU */ __O uint32_t DCCMVAC; /*!< Offset: 0x268 ( /W) D-Cache Clean by MVA to PoC */ __O uint32_t DCCSW; /*!< Offset: 0x26C ( /W) D-Cache Clean by Set-way */ __O uint32_t DCCIMVAC; /*!< Offset: 0x270 ( /W) D-Cache Clean and Invalidate by MVA to PoC */ __O uint32_t DCCISW; /*!< Offset: 0x274 ( /W) D-Cache Clean and Invalidate by Set-way */ uint32_t RESERVED7[6]; __IO uint32_t ITCMCR; /*!< Offset: 0x290 (R/W) Instruction Tightly-Coupled Memory Control Register */ __IO uint32_t DTCMCR; /*!< Offset: 0x294 (R/W) Data Tightly-Coupled Memory Control Registers */ __IO uint32_t AHBPCR; /*!< Offset: 0x298 (R/W) AHBP Control Register */ __IO uint32_t CACR; /*!< Offset: 0x29C (R/W) L1 Cache Control Register */ __IO uint32_t AHBSCR; /*!< Offset: 0x2A0 (R/W) AHB Slave Control Register */ uint32_t RESERVED8[1]; __IO uint32_t ABFSR; /*!< Offset: 0x2A8 (R/W) Auxiliary Bus Fault Status Register */ } SCB_Type; /* SCB CPUID Register Definitions */ #define SCB_CPUID_IMPLEMENTER_Pos 24 /*!< SCB CPUID: IMPLEMENTER Position */ #define SCB_CPUID_IMPLEMENTER_Msk (0xFFUL << SCB_CPUID_IMPLEMENTER_Pos) /*!< SCB CPUID: IMPLEMENTER Mask */ #define SCB_CPUID_VARIANT_Pos 20 /*!< SCB CPUID: VARIANT Position */ #define SCB_CPUID_VARIANT_Msk (0xFUL << SCB_CPUID_VARIANT_Pos) /*!< SCB CPUID: VARIANT Mask */ #define SCB_CPUID_ARCHITECTURE_Pos 16 /*!< SCB CPUID: ARCHITECTURE Position */ #define SCB_CPUID_ARCHITECTURE_Msk (0xFUL << SCB_CPUID_ARCHITECTURE_Pos) /*!< SCB CPUID: ARCHITECTURE Mask */ #define SCB_CPUID_PARTNO_Pos 4 /*!< SCB CPUID: PARTNO Position */ #define SCB_CPUID_PARTNO_Msk (0xFFFUL << SCB_CPUID_PARTNO_Pos) /*!< SCB CPUID: PARTNO Mask */ #define SCB_CPUID_REVISION_Pos 0 /*!< SCB CPUID: REVISION Position */ #define SCB_CPUID_REVISION_Msk (0xFUL /*<< SCB_CPUID_REVISION_Pos*/) /*!< SCB CPUID: REVISION Mask */ /* SCB Interrupt Control State Register Definitions */ #define SCB_ICSR_NMIPENDSET_Pos 31 /*!< SCB ICSR: NMIPENDSET Position */ #define SCB_ICSR_NMIPENDSET_Msk (1UL << SCB_ICSR_NMIPENDSET_Pos) /*!< SCB ICSR: NMIPENDSET Mask */ #define SCB_ICSR_PENDSVSET_Pos 28 /*!< SCB ICSR: PENDSVSET Position */ #define SCB_ICSR_PENDSVSET_Msk (1UL << SCB_ICSR_PENDSVSET_Pos) /*!< SCB ICSR: PENDSVSET Mask */ #define SCB_ICSR_PENDSVCLR_Pos 27 /*!< SCB ICSR: PENDSVCLR Position */ #define SCB_ICSR_PENDSVCLR_Msk (1UL << SCB_ICSR_PENDSVCLR_Pos) /*!< SCB ICSR: PENDSVCLR Mask */ #define SCB_ICSR_PENDSTSET_Pos 26 /*!< SCB ICSR: PENDSTSET Position */ #define SCB_ICSR_PENDSTSET_Msk (1UL << SCB_ICSR_PENDSTSET_Pos) /*!< SCB ICSR: PENDSTSET Mask */ #define SCB_ICSR_PENDSTCLR_Pos 25 /*!< SCB ICSR: PENDSTCLR Position */ #define SCB_ICSR_PENDSTCLR_Msk (1UL << SCB_ICSR_PENDSTCLR_Pos) /*!< SCB ICSR: PENDSTCLR Mask */ #define SCB_ICSR_ISRPREEMPT_Pos 23 /*!< SCB ICSR: ISRPREEMPT Position */ #define SCB_ICSR_ISRPREEMPT_Msk (1UL << SCB_ICSR_ISRPREEMPT_Pos) /*!< SCB ICSR: ISRPREEMPT Mask */ #define SCB_ICSR_ISRPENDING_Pos 22 /*!< SCB ICSR: ISRPENDING Position */ #define SCB_ICSR_ISRPENDING_Msk (1UL << SCB_ICSR_ISRPENDING_Pos) /*!< SCB ICSR: ISRPENDING Mask */ #define SCB_ICSR_VECTPENDING_Pos 12 /*!< SCB ICSR: VECTPENDING Position */ #define SCB_ICSR_VECTPENDING_Msk (0x1FFUL << SCB_ICSR_VECTPENDING_Pos) /*!< SCB ICSR: VECTPENDING Mask */ #define SCB_ICSR_RETTOBASE_Pos 11 /*!< SCB ICSR: RETTOBASE Position */ #define SCB_ICSR_RETTOBASE_Msk (1UL << SCB_ICSR_RETTOBASE_Pos) /*!< SCB ICSR: RETTOBASE Mask */ #define SCB_ICSR_VECTACTIVE_Pos 0 /*!< SCB ICSR: VECTACTIVE Position */ #define SCB_ICSR_VECTACTIVE_Msk (0x1FFUL /*<< SCB_ICSR_VECTACTIVE_Pos*/) /*!< SCB ICSR: VECTACTIVE Mask */ /* SCB Vector Table Offset Register Definitions */ #define SCB_VTOR_TBLOFF_Pos 7 /*!< SCB VTOR: TBLOFF Position */ #define SCB_VTOR_TBLOFF_Msk (0x1FFFFFFUL << SCB_VTOR_TBLOFF_Pos) /*!< SCB VTOR: TBLOFF Mask */ /* SCB Application Interrupt and Reset Control Register Definitions */ #define SCB_AIRCR_VECTKEY_Pos 16 /*!< SCB AIRCR: VECTKEY Position */ #define SCB_AIRCR_VECTKEY_Msk (0xFFFFUL << SCB_AIRCR_VECTKEY_Pos) /*!< SCB AIRCR: VECTKEY Mask */ #define SCB_AIRCR_VECTKEYSTAT_Pos 16 /*!< SCB AIRCR: VECTKEYSTAT Position */ #define SCB_AIRCR_VECTKEYSTAT_Msk (0xFFFFUL << SCB_AIRCR_VECTKEYSTAT_Pos) /*!< SCB AIRCR: VECTKEYSTAT Mask */ #define SCB_AIRCR_ENDIANESS_Pos 15 /*!< SCB AIRCR: ENDIANESS Position */ #define SCB_AIRCR_ENDIANESS_Msk (1UL << SCB_AIRCR_ENDIANESS_Pos) /*!< SCB AIRCR: ENDIANESS Mask */ #define SCB_AIRCR_PRIGROUP_Pos 8 /*!< SCB AIRCR: PRIGROUP Position */ #define SCB_AIRCR_PRIGROUP_Msk (7UL << SCB_AIRCR_PRIGROUP_Pos) /*!< SCB AIRCR: PRIGROUP Mask */ #define SCB_AIRCR_SYSRESETREQ_Pos 2 /*!< SCB AIRCR: SYSRESETREQ Position */ #define SCB_AIRCR_SYSRESETREQ_Msk (1UL << SCB_AIRCR_SYSRESETREQ_Pos) /*!< SCB AIRCR: SYSRESETREQ Mask */ #define SCB_AIRCR_VECTCLRACTIVE_Pos 1 /*!< SCB AIRCR: VECTCLRACTIVE Position */ #define SCB_AIRCR_VECTCLRACTIVE_Msk (1UL << SCB_AIRCR_VECTCLRACTIVE_Pos) /*!< SCB AIRCR: VECTCLRACTIVE Mask */ #define SCB_AIRCR_VECTRESET_Pos 0 /*!< SCB AIRCR: VECTRESET Position */ #define SCB_AIRCR_VECTRESET_Msk (1UL /*<< SCB_AIRCR_VECTRESET_Pos*/) /*!< SCB AIRCR: VECTRESET Mask */ /* SCB System Control Register Definitions */ #define SCB_SCR_SEVONPEND_Pos 4 /*!< SCB SCR: SEVONPEND Position */ #define SCB_SCR_SEVONPEND_Msk (1UL << SCB_SCR_SEVONPEND_Pos) /*!< SCB SCR: SEVONPEND Mask */ #define SCB_SCR_SLEEPDEEP_Pos 2 /*!< SCB SCR: SLEEPDEEP Position */ #define SCB_SCR_SLEEPDEEP_Msk (1UL << SCB_SCR_SLEEPDEEP_Pos) /*!< SCB SCR: SLEEPDEEP Mask */ #define SCB_SCR_SLEEPONEXIT_Pos 1 /*!< SCB SCR: SLEEPONEXIT Position */ #define SCB_SCR_SLEEPONEXIT_Msk (1UL << SCB_SCR_SLEEPONEXIT_Pos) /*!< SCB SCR: SLEEPONEXIT Mask */ /* SCB Configuration Control Register Definitions */ #define SCB_CCR_BP_Pos 18 /*!< SCB CCR: Branch prediction enable bit Position */ #define SCB_CCR_BP_Msk (1UL << SCB_CCR_BP_Pos) /*!< SCB CCR: Branch prediction enable bit Mask */ #define SCB_CCR_IC_Pos 17 /*!< SCB CCR: Instruction cache enable bit Position */ #define SCB_CCR_IC_Msk (1UL << SCB_CCR_IC_Pos) /*!< SCB CCR: Instruction cache enable bit Mask */ #define SCB_CCR_DC_Pos 16 /*!< SCB CCR: Cache enable bit Position */ #define SCB_CCR_DC_Msk (1UL << SCB_CCR_DC_Pos) /*!< SCB CCR: Cache enable bit Mask */ #define SCB_CCR_STKALIGN_Pos 9 /*!< SCB CCR: STKALIGN Position */ #define SCB_CCR_STKALIGN_Msk (1UL << SCB_CCR_STKALIGN_Pos) /*!< SCB CCR: STKALIGN Mask */ #define SCB_CCR_BFHFNMIGN_Pos 8 /*!< SCB CCR: BFHFNMIGN Position */ #define SCB_CCR_BFHFNMIGN_Msk (1UL << SCB_CCR_BFHFNMIGN_Pos) /*!< SCB CCR: BFHFNMIGN Mask */ #define SCB_CCR_DIV_0_TRP_Pos 4 /*!< SCB CCR: DIV_0_TRP Position */ #define SCB_CCR_DIV_0_TRP_Msk (1UL << SCB_CCR_DIV_0_TRP_Pos) /*!< SCB CCR: DIV_0_TRP Mask */ #define SCB_CCR_UNALIGN_TRP_Pos 3 /*!< SCB CCR: UNALIGN_TRP Position */ #define SCB_CCR_UNALIGN_TRP_Msk (1UL << SCB_CCR_UNALIGN_TRP_Pos) /*!< SCB CCR: UNALIGN_TRP Mask */ #define SCB_CCR_USERSETMPEND_Pos 1 /*!< SCB CCR: USERSETMPEND Position */ #define SCB_CCR_USERSETMPEND_Msk (1UL << SCB_CCR_USERSETMPEND_Pos) /*!< SCB CCR: USERSETMPEND Mask */ #define SCB_CCR_NONBASETHRDENA_Pos 0 /*!< SCB CCR: NONBASETHRDENA Position */ #define SCB_CCR_NONBASETHRDENA_Msk (1UL /*<< SCB_CCR_NONBASETHRDENA_Pos*/) /*!< SCB CCR: NONBASETHRDENA Mask */ /* SCB System Handler Control and State Register Definitions */ #define SCB_SHCSR_USGFAULTENA_Pos 18 /*!< SCB SHCSR: USGFAULTENA Position */ #define SCB_SHCSR_USGFAULTENA_Msk (1UL << SCB_SHCSR_USGFAULTENA_Pos) /*!< SCB SHCSR: USGFAULTENA Mask */ #define SCB_SHCSR_BUSFAULTENA_Pos 17 /*!< SCB SHCSR: BUSFAULTENA Position */ #define SCB_SHCSR_BUSFAULTENA_Msk (1UL << SCB_SHCSR_BUSFAULTENA_Pos) /*!< SCB SHCSR: BUSFAULTENA Mask */ #define SCB_SHCSR_MEMFAULTENA_Pos 16 /*!< SCB SHCSR: MEMFAULTENA Position */ #define SCB_SHCSR_MEMFAULTENA_Msk (1UL << SCB_SHCSR_MEMFAULTENA_Pos) /*!< SCB SHCSR: MEMFAULTENA Mask */ #define SCB_SHCSR_SVCALLPENDED_Pos 15 /*!< SCB SHCSR: SVCALLPENDED Position */ #define SCB_SHCSR_SVCALLPENDED_Msk (1UL << SCB_SHCSR_SVCALLPENDED_Pos) /*!< SCB SHCSR: SVCALLPENDED Mask */ #define SCB_SHCSR_BUSFAULTPENDED_Pos 14 /*!< SCB SHCSR: BUSFAULTPENDED Position */ #define SCB_SHCSR_BUSFAULTPENDED_Msk (1UL << SCB_SHCSR_BUSFAULTPENDED_Pos) /*!< SCB SHCSR: BUSFAULTPENDED Mask */ #define SCB_SHCSR_MEMFAULTPENDED_Pos 13 /*!< SCB SHCSR: MEMFAULTPENDED Position */ #define SCB_SHCSR_MEMFAULTPENDED_Msk (1UL << SCB_SHCSR_MEMFAULTPENDED_Pos) /*!< SCB SHCSR: MEMFAULTPENDED Mask */ #define SCB_SHCSR_USGFAULTPENDED_Pos 12 /*!< SCB SHCSR: USGFAULTPENDED Position */ #define SCB_SHCSR_USGFAULTPENDED_Msk (1UL << SCB_SHCSR_USGFAULTPENDED_Pos) /*!< SCB SHCSR: USGFAULTPENDED Mask */ #define SCB_SHCSR_SYSTICKACT_Pos 11 /*!< SCB SHCSR: SYSTICKACT Position */ #define SCB_SHCSR_SYSTICKACT_Msk (1UL << SCB_SHCSR_SYSTICKACT_Pos) /*!< SCB SHCSR: SYSTICKACT Mask */ #define SCB_SHCSR_PENDSVACT_Pos 10 /*!< SCB SHCSR: PENDSVACT Position */ #define SCB_SHCSR_PENDSVACT_Msk (1UL << SCB_SHCSR_PENDSVACT_Pos) /*!< SCB SHCSR: PENDSVACT Mask */ #define SCB_SHCSR_MONITORACT_Pos 8 /*!< SCB SHCSR: MONITORACT Position */ #define SCB_SHCSR_MONITORACT_Msk (1UL << SCB_SHCSR_MONITORACT_Pos) /*!< SCB SHCSR: MONITORACT Mask */ #define SCB_SHCSR_SVCALLACT_Pos 7 /*!< SCB SHCSR: SVCALLACT Position */ #define SCB_SHCSR_SVCALLACT_Msk (1UL << SCB_SHCSR_SVCALLACT_Pos) /*!< SCB SHCSR: SVCALLACT Mask */ #define SCB_SHCSR_USGFAULTACT_Pos 3 /*!< SCB SHCSR: USGFAULTACT Position */ #define SCB_SHCSR_USGFAULTACT_Msk (1UL << SCB_SHCSR_USGFAULTACT_Pos) /*!< SCB SHCSR: USGFAULTACT Mask */ #define SCB_SHCSR_BUSFAULTACT_Pos 1 /*!< SCB SHCSR: BUSFAULTACT Position */ #define SCB_SHCSR_BUSFAULTACT_Msk (1UL << SCB_SHCSR_BUSFAULTACT_Pos) /*!< SCB SHCSR: BUSFAULTACT Mask */ #define SCB_SHCSR_MEMFAULTACT_Pos 0 /*!< SCB SHCSR: MEMFAULTACT Position */ #define SCB_SHCSR_MEMFAULTACT_Msk (1UL /*<< SCB_SHCSR_MEMFAULTACT_Pos*/) /*!< SCB SHCSR: MEMFAULTACT Mask */ /* SCB Configurable Fault Status Registers Definitions */ #define SCB_CFSR_USGFAULTSR_Pos 16 /*!< SCB CFSR: Usage Fault Status Register Position */ #define SCB_CFSR_USGFAULTSR_Msk (0xFFFFUL << SCB_CFSR_USGFAULTSR_Pos) /*!< SCB CFSR: Usage Fault Status Register Mask */ #define SCB_CFSR_BUSFAULTSR_Pos 8 /*!< SCB CFSR: Bus Fault Status Register Position */ #define SCB_CFSR_BUSFAULTSR_Msk (0xFFUL << SCB_CFSR_BUSFAULTSR_Pos) /*!< SCB CFSR: Bus Fault Status Register Mask */ #define SCB_CFSR_MEMFAULTSR_Pos 0 /*!< SCB CFSR: Memory Manage Fault Status Register Position */ #define SCB_CFSR_MEMFAULTSR_Msk (0xFFUL /*<< SCB_CFSR_MEMFAULTSR_Pos*/) /*!< SCB CFSR: Memory Manage Fault Status Register Mask */ /* SCB Hard Fault Status Registers Definitions */ #define SCB_HFSR_DEBUGEVT_Pos 31 /*!< SCB HFSR: DEBUGEVT Position */ #define SCB_HFSR_DEBUGEVT_Msk (1UL << SCB_HFSR_DEBUGEVT_Pos) /*!< SCB HFSR: DEBUGEVT Mask */ #define SCB_HFSR_FORCED_Pos 30 /*!< SCB HFSR: FORCED Position */ #define SCB_HFSR_FORCED_Msk (1UL << SCB_HFSR_FORCED_Pos) /*!< SCB HFSR: FORCED Mask */ #define SCB_HFSR_VECTTBL_Pos 1 /*!< SCB HFSR: VECTTBL Position */ #define SCB_HFSR_VECTTBL_Msk (1UL << SCB_HFSR_VECTTBL_Pos) /*!< SCB HFSR: VECTTBL Mask */ /* SCB Debug Fault Status Register Definitions */ #define SCB_DFSR_EXTERNAL_Pos 4 /*!< SCB DFSR: EXTERNAL Position */ #define SCB_DFSR_EXTERNAL_Msk (1UL << SCB_DFSR_EXTERNAL_Pos) /*!< SCB DFSR: EXTERNAL Mask */ #define SCB_DFSR_VCATCH_Pos 3 /*!< SCB DFSR: VCATCH Position */ #define SCB_DFSR_VCATCH_Msk (1UL << SCB_DFSR_VCATCH_Pos) /*!< SCB DFSR: VCATCH Mask */ #define SCB_DFSR_DWTTRAP_Pos 2 /*!< SCB DFSR: DWTTRAP Position */ #define SCB_DFSR_DWTTRAP_Msk (1UL << SCB_DFSR_DWTTRAP_Pos) /*!< SCB DFSR: DWTTRAP Mask */ #define SCB_DFSR_BKPT_Pos 1 /*!< SCB DFSR: BKPT Position */ #define SCB_DFSR_BKPT_Msk (1UL << SCB_DFSR_BKPT_Pos) /*!< SCB DFSR: BKPT Mask */ #define SCB_DFSR_HALTED_Pos 0 /*!< SCB DFSR: HALTED Position */ #define SCB_DFSR_HALTED_Msk (1UL /*<< SCB_DFSR_HALTED_Pos*/) /*!< SCB DFSR: HALTED Mask */ /* Cache Level ID register */ #define SCB_CLIDR_LOUU_Pos 27 /*!< SCB CLIDR: LoUU Position */ #define SCB_CLIDR_LOUU_Msk (7UL << SCB_CLIDR_LOUU_Pos) /*!< SCB CLIDR: LoUU Mask */ #define SCB_CLIDR_LOC_Pos 24 /*!< SCB CLIDR: LoC Position */ #define SCB_CLIDR_LOC_Msk (7UL << SCB_CLIDR_FORMAT_Pos) /*!< SCB CLIDR: LoC Mask */ /* Cache Type register */ #define SCB_CTR_FORMAT_Pos 29 /*!< SCB CTR: Format Position */ #define SCB_CTR_FORMAT_Msk (7UL << SCB_CTR_FORMAT_Pos) /*!< SCB CTR: Format Mask */ #define SCB_CTR_CWG_Pos 24 /*!< SCB CTR: CWG Position */ #define SCB_CTR_CWG_Msk (0xFUL << SCB_CTR_CWG_Pos) /*!< SCB CTR: CWG Mask */ #define SCB_CTR_ERG_Pos 20 /*!< SCB CTR: ERG Position */ #define SCB_CTR_ERG_Msk (0xFUL << SCB_CTR_ERG_Pos) /*!< SCB CTR: ERG Mask */ #define SCB_CTR_DMINLINE_Pos 16 /*!< SCB CTR: DminLine Position */ #define SCB_CTR_DMINLINE_Msk (0xFUL << SCB_CTR_DMINLINE_Pos) /*!< SCB CTR: DminLine Mask */ #define SCB_CTR_IMINLINE_Pos 0 /*!< SCB CTR: ImInLine Position */ #define SCB_CTR_IMINLINE_Msk (0xFUL /*<< SCB_CTR_IMINLINE_Pos*/) /*!< SCB CTR: ImInLine Mask */ /* Cache Size ID Register */ #define SCB_CCSIDR_WT_Pos 31 /*!< SCB CCSIDR: WT Position */ #define SCB_CCSIDR_WT_Msk (7UL << SCB_CCSIDR_WT_Pos) /*!< SCB CCSIDR: WT Mask */ #define SCB_CCSIDR_WB_Pos 30 /*!< SCB CCSIDR: WB Position */ #define SCB_CCSIDR_WB_Msk (7UL << SCB_CCSIDR_WB_Pos) /*!< SCB CCSIDR: WB Mask */ #define SCB_CCSIDR_RA_Pos 29 /*!< SCB CCSIDR: RA Position */ #define SCB_CCSIDR_RA_Msk (7UL << SCB_CCSIDR_RA_Pos) /*!< SCB CCSIDR: RA Mask */ #define SCB_CCSIDR_WA_Pos 28 /*!< SCB CCSIDR: WA Position */ #define SCB_CCSIDR_WA_Msk (7UL << SCB_CCSIDR_WA_Pos) /*!< SCB CCSIDR: WA Mask */ #define SCB_CCSIDR_NUMSETS_Pos 13 /*!< SCB CCSIDR: NumSets Position */ #define SCB_CCSIDR_NUMSETS_Msk (0x7FFFUL << SCB_CCSIDR_NUMSETS_Pos) /*!< SCB CCSIDR: NumSets Mask */ #define SCB_CCSIDR_ASSOCIATIVITY_Pos 3 /*!< SCB CCSIDR: Associativity Position */ #define SCB_CCSIDR_ASSOCIATIVITY_Msk (0x3FFUL << SCB_CCSIDR_ASSOCIATIVITY_Pos) /*!< SCB CCSIDR: Associativity Mask */ #define SCB_CCSIDR_LINESIZE_Pos 0 /*!< SCB CCSIDR: LineSize Position */ #define SCB_CCSIDR_LINESIZE_Msk (7UL /*<< SCB_CCSIDR_LINESIZE_Pos*/) /*!< SCB CCSIDR: LineSize Mask */ /* Cache Size Selection Register */ #define SCB_CSSELR_LEVEL_Pos 1 /*!< SCB CSSELR: Level Position */ #define SCB_CSSELR_LEVEL_Msk (7UL << SCB_CSSELR_LEVEL_Pos) /*!< SCB CSSELR: Level Mask */ #define SCB_CSSELR_IND_Pos 0 /*!< SCB CSSELR: InD Position */ #define SCB_CSSELR_IND_Msk (1UL /*<< SCB_CSSELR_IND_Pos*/) /*!< SCB CSSELR: InD Mask */ /* SCB Software Triggered Interrupt Register */ #define SCB_STIR_INTID_Pos 0 /*!< SCB STIR: INTID Position */ #define SCB_STIR_INTID_Msk (0x1FFUL /*<< SCB_STIR_INTID_Pos*/) /*!< SCB STIR: INTID Mask */ /* Instruction Tightly-Coupled Memory Control Register*/ #define SCB_ITCMCR_SZ_Pos 3 /*!< SCB ITCMCR: SZ Position */ #define SCB_ITCMCR_SZ_Msk (0xFUL << SCB_ITCMCR_SZ_Pos) /*!< SCB ITCMCR: SZ Mask */ #define SCB_ITCMCR_RETEN_Pos 2 /*!< SCB ITCMCR: RETEN Position */ #define SCB_ITCMCR_RETEN_Msk (1UL << SCB_ITCMCR_RETEN_Pos) /*!< SCB ITCMCR: RETEN Mask */ #define SCB_ITCMCR_RMW_Pos 1 /*!< SCB ITCMCR: RMW Position */ #define SCB_ITCMCR_RMW_Msk (1UL << SCB_ITCMCR_RMW_Pos) /*!< SCB ITCMCR: RMW Mask */ #define SCB_ITCMCR_EN_Pos 0 /*!< SCB ITCMCR: EN Position */ #define SCB_ITCMCR_EN_Msk (1UL /*<< SCB_ITCMCR_EN_Pos*/) /*!< SCB ITCMCR: EN Mask */ /* Data Tightly-Coupled Memory Control Registers */ #define SCB_DTCMCR_SZ_Pos 3 /*!< SCB DTCMCR: SZ Position */ #define SCB_DTCMCR_SZ_Msk (0xFUL << SCB_DTCMCR_SZ_Pos) /*!< SCB DTCMCR: SZ Mask */ #define SCB_DTCMCR_RETEN_Pos 2 /*!< SCB DTCMCR: RETEN Position */ #define SCB_DTCMCR_RETEN_Msk (1UL << SCB_DTCMCR_RETEN_Pos) /*!< SCB DTCMCR: RETEN Mask */ #define SCB_DTCMCR_RMW_Pos 1 /*!< SCB DTCMCR: RMW Position */ #define SCB_DTCMCR_RMW_Msk (1UL << SCB_DTCMCR_RMW_Pos) /*!< SCB DTCMCR: RMW Mask */ #define SCB_DTCMCR_EN_Pos 0 /*!< SCB DTCMCR: EN Position */ #define SCB_DTCMCR_EN_Msk (1UL /*<< SCB_DTCMCR_EN_Pos*/) /*!< SCB DTCMCR: EN Mask */ /* AHBP Control Register */ #define SCB_AHBPCR_SZ_Pos 1 /*!< SCB AHBPCR: SZ Position */ #define SCB_AHBPCR_SZ_Msk (7UL << SCB_AHBPCR_SZ_Pos) /*!< SCB AHBPCR: SZ Mask */ #define SCB_AHBPCR_EN_Pos 0 /*!< SCB AHBPCR: EN Position */ #define SCB_AHBPCR_EN_Msk (1UL /*<< SCB_AHBPCR_EN_Pos*/) /*!< SCB AHBPCR: EN Mask */ /* L1 Cache Control Register */ #define SCB_CACR_FORCEWT_Pos 2 /*!< SCB CACR: FORCEWT Position */ #define SCB_CACR_FORCEWT_Msk (1UL << SCB_CACR_FORCEWT_Pos) /*!< SCB CACR: FORCEWT Mask */ #define SCB_CACR_ECCEN_Pos 1 /*!< SCB CACR: ECCEN Position */ #define SCB_CACR_ECCEN_Msk (1UL << SCB_CACR_ECCEN_Pos) /*!< SCB CACR: ECCEN Mask */ #define SCB_CACR_SIWT_Pos 0 /*!< SCB CACR: SIWT Position */ #define SCB_CACR_SIWT_Msk (1UL /*<< SCB_CACR_SIWT_Pos*/) /*!< SCB CACR: SIWT Mask */ /* AHBS control register */ #define SCB_AHBSCR_INITCOUNT_Pos 11 /*!< SCB AHBSCR: INITCOUNT Position */ #define SCB_AHBSCR_INITCOUNT_Msk (0x1FUL << SCB_AHBPCR_INITCOUNT_Pos) /*!< SCB AHBSCR: INITCOUNT Mask */ #define SCB_AHBSCR_TPRI_Pos 2 /*!< SCB AHBSCR: TPRI Position */ #define SCB_AHBSCR_TPRI_Msk (0x1FFUL << SCB_AHBPCR_TPRI_Pos) /*!< SCB AHBSCR: TPRI Mask */ #define SCB_AHBSCR_CTL_Pos 0 /*!< SCB AHBSCR: CTL Position*/ #define SCB_AHBSCR_CTL_Msk (3UL /*<< SCB_AHBPCR_CTL_Pos*/) /*!< SCB AHBSCR: CTL Mask */ /* Auxiliary Bus Fault Status Register */ #define SCB_ABFSR_AXIMTYPE_Pos 8 /*!< SCB ABFSR: AXIMTYPE Position*/ #define SCB_ABFSR_AXIMTYPE_Msk (3UL << SCB_ABFSR_AXIMTYPE_Pos) /*!< SCB ABFSR: AXIMTYPE Mask */ #define SCB_ABFSR_EPPB_Pos 4 /*!< SCB ABFSR: EPPB Position*/ #define SCB_ABFSR_EPPB_Msk (1UL << SCB_ABFSR_EPPB_Pos) /*!< SCB ABFSR: EPPB Mask */ #define SCB_ABFSR_AXIM_Pos 3 /*!< SCB ABFSR: AXIM Position*/ #define SCB_ABFSR_AXIM_Msk (1UL << SCB_ABFSR_AXIM_Pos) /*!< SCB ABFSR: AXIM Mask */ #define SCB_ABFSR_AHBP_Pos 2 /*!< SCB ABFSR: AHBP Position*/ #define SCB_ABFSR_AHBP_Msk (1UL << SCB_ABFSR_AHBP_Pos) /*!< SCB ABFSR: AHBP Mask */ #define SCB_ABFSR_DTCM_Pos 1 /*!< SCB ABFSR: DTCM Position*/ #define SCB_ABFSR_DTCM_Msk (1UL << SCB_ABFSR_DTCM_Pos) /*!< SCB ABFSR: DTCM Mask */ #define SCB_ABFSR_ITCM_Pos 0 /*!< SCB ABFSR: ITCM Position*/ #define SCB_ABFSR_ITCM_Msk (1UL /*<< SCB_ABFSR_ITCM_Pos*/) /*!< SCB ABFSR: ITCM Mask */ /*@} end of group CMSIS_SCB */ /** \ingroup CMSIS_core_register \defgroup CMSIS_SCnSCB System Controls not in SCB (SCnSCB) \brief Type definitions for the System Control and ID Register not in the SCB @{ */ /** \brief Structure type to access the System Control and ID Register not in the SCB. */ typedef struct { uint32_t RESERVED0[1]; __I uint32_t ICTR; /*!< Offset: 0x004 (R/ ) Interrupt Controller Type Register */ __IO uint32_t ACTLR; /*!< Offset: 0x008 (R/W) Auxiliary Control Register */ } SCnSCB_Type; /* Interrupt Controller Type Register Definitions */ #define SCnSCB_ICTR_INTLINESNUM_Pos 0 /*!< ICTR: INTLINESNUM Position */ #define SCnSCB_ICTR_INTLINESNUM_Msk (0xFUL /*<< SCnSCB_ICTR_INTLINESNUM_Pos*/) /*!< ICTR: INTLINESNUM Mask */ /* Auxiliary Control Register Definitions */ #define SCnSCB_ACTLR_DISITMATBFLUSH_Pos 12 /*!< ACTLR: DISITMATBFLUSH Position */ #define SCnSCB_ACTLR_DISITMATBFLUSH_Msk (1UL << SCnSCB_ACTLR_DISITMATBFLUSH_Pos) /*!< ACTLR: DISITMATBFLUSH Mask */ #define SCnSCB_ACTLR_DISRAMODE_Pos 11 /*!< ACTLR: DISRAMODE Position */ #define SCnSCB_ACTLR_DISRAMODE_Msk (1UL << SCnSCB_ACTLR_DISRAMODE_Pos) /*!< ACTLR: DISRAMODE Mask */ #define SCnSCB_ACTLR_FPEXCODIS_Pos 10 /*!< ACTLR: FPEXCODIS Position */ #define SCnSCB_ACTLR_FPEXCODIS_Msk (1UL << SCnSCB_ACTLR_FPEXCODIS_Pos) /*!< ACTLR: FPEXCODIS Mask */ #define SCnSCB_ACTLR_DISFOLD_Pos 2 /*!< ACTLR: DISFOLD Position */ #define SCnSCB_ACTLR_DISFOLD_Msk (1UL << SCnSCB_ACTLR_DISFOLD_Pos) /*!< ACTLR: DISFOLD Mask */ #define SCnSCB_ACTLR_DISMCYCINT_Pos 0 /*!< ACTLR: DISMCYCINT Position */ #define SCnSCB_ACTLR_DISMCYCINT_Msk (1UL /*<< SCnSCB_ACTLR_DISMCYCINT_Pos*/) /*!< ACTLR: DISMCYCINT Mask */ /*@} end of group CMSIS_SCnotSCB */ /** \ingroup CMSIS_core_register \defgroup CMSIS_SysTick System Tick Timer (SysTick) \brief Type definitions for the System Timer Registers. @{ */ /** \brief Structure type to access the System Timer (SysTick). */ typedef struct { __IO uint32_t CTRL; /*!< Offset: 0x000 (R/W) SysTick Control and Status Register */ __IO uint32_t LOAD; /*!< Offset: 0x004 (R/W) SysTick Reload Value Register */ __IO uint32_t VAL; /*!< Offset: 0x008 (R/W) SysTick Current Value Register */ __I uint32_t CALIB; /*!< Offset: 0x00C (R/ ) SysTick Calibration Register */ } SysTick_Type; /* SysTick Control / Status Register Definitions */ #define SysTick_CTRL_COUNTFLAG_Pos 16 /*!< SysTick CTRL: COUNTFLAG Position */ #define SysTick_CTRL_COUNTFLAG_Msk (1UL << SysTick_CTRL_COUNTFLAG_Pos) /*!< SysTick CTRL: COUNTFLAG Mask */ #define SysTick_CTRL_CLKSOURCE_Pos 2 /*!< SysTick CTRL: CLKSOURCE Position */ #define SysTick_CTRL_CLKSOURCE_Msk (1UL << SysTick_CTRL_CLKSOURCE_Pos) /*!< SysTick CTRL: CLKSOURCE Mask */ #define SysTick_CTRL_TICKINT_Pos 1 /*!< SysTick CTRL: TICKINT Position */ #define SysTick_CTRL_TICKINT_Msk (1UL << SysTick_CTRL_TICKINT_Pos) /*!< SysTick CTRL: TICKINT Mask */ #define SysTick_CTRL_ENABLE_Pos 0 /*!< SysTick CTRL: ENABLE Position */ #define SysTick_CTRL_ENABLE_Msk (1UL /*<< SysTick_CTRL_ENABLE_Pos*/) /*!< SysTick CTRL: ENABLE Mask */ /* SysTick Reload Register Definitions */ #define SysTick_LOAD_RELOAD_Pos 0 /*!< SysTick LOAD: RELOAD Position */ #define SysTick_LOAD_RELOAD_Msk (0xFFFFFFUL /*<< SysTick_LOAD_RELOAD_Pos*/) /*!< SysTick LOAD: RELOAD Mask */ /* SysTick Current Register Definitions */ #define SysTick_VAL_CURRENT_Pos 0 /*!< SysTick VAL: CURRENT Position */ #define SysTick_VAL_CURRENT_Msk (0xFFFFFFUL /*<< SysTick_VAL_CURRENT_Pos*/) /*!< SysTick VAL: CURRENT Mask */ /* SysTick Calibration Register Definitions */ #define SysTick_CALIB_NOREF_Pos 31 /*!< SysTick CALIB: NOREF Position */ #define SysTick_CALIB_NOREF_Msk (1UL << SysTick_CALIB_NOREF_Pos) /*!< SysTick CALIB: NOREF Mask */ #define SysTick_CALIB_SKEW_Pos 30 /*!< SysTick CALIB: SKEW Position */ #define SysTick_CALIB_SKEW_Msk (1UL << SysTick_CALIB_SKEW_Pos) /*!< SysTick CALIB: SKEW Mask */ #define SysTick_CALIB_TENMS_Pos 0 /*!< SysTick CALIB: TENMS Position */ #define SysTick_CALIB_TENMS_Msk (0xFFFFFFUL /*<< SysTick_CALIB_TENMS_Pos*/) /*!< SysTick CALIB: TENMS Mask */ /*@} end of group CMSIS_SysTick */ /** \ingroup CMSIS_core_register \defgroup CMSIS_ITM Instrumentation Trace Macrocell (ITM) \brief Type definitions for the Instrumentation Trace Macrocell (ITM) @{ */ /** \brief Structure type to access the Instrumentation Trace Macrocell Register (ITM). */ typedef struct { __O union { __O uint8_t u8; /*!< Offset: 0x000 ( /W) ITM Stimulus Port 8-bit */ __O uint16_t u16; /*!< Offset: 0x000 ( /W) ITM Stimulus Port 16-bit */ __O uint32_t u32; /*!< Offset: 0x000 ( /W) ITM Stimulus Port 32-bit */ } PORT [32]; /*!< Offset: 0x000 ( /W) ITM Stimulus Port Registers */ uint32_t RESERVED0[864]; __IO uint32_t TER; /*!< Offset: 0xE00 (R/W) ITM Trace Enable Register */ uint32_t RESERVED1[15]; __IO uint32_t TPR; /*!< Offset: 0xE40 (R/W) ITM Trace Privilege Register */ uint32_t RESERVED2[15]; __IO uint32_t TCR; /*!< Offset: 0xE80 (R/W) ITM Trace Control Register */ uint32_t RESERVED3[29]; __O uint32_t IWR; /*!< Offset: 0xEF8 ( /W) ITM Integration Write Register */ __I uint32_t IRR; /*!< Offset: 0xEFC (R/ ) ITM Integration Read Register */ __IO uint32_t IMCR; /*!< Offset: 0xF00 (R/W) ITM Integration Mode Control Register */ uint32_t RESERVED4[43]; __O uint32_t LAR; /*!< Offset: 0xFB0 ( /W) ITM Lock Access Register */ __I uint32_t LSR; /*!< Offset: 0xFB4 (R/ ) ITM Lock Status Register */ uint32_t RESERVED5[6]; __I uint32_t PID4; /*!< Offset: 0xFD0 (R/ ) ITM Peripheral Identification Register #4 */ __I uint32_t PID5; /*!< Offset: 0xFD4 (R/ ) ITM Peripheral Identification Register #5 */ __I uint32_t PID6; /*!< Offset: 0xFD8 (R/ ) ITM Peripheral Identification Register #6 */ __I uint32_t PID7; /*!< Offset: 0xFDC (R/ ) ITM Peripheral Identification Register #7 */ __I uint32_t PID0; /*!< Offset: 0xFE0 (R/ ) ITM Peripheral Identification Register #0 */ __I uint32_t PID1; /*!< Offset: 0xFE4 (R/ ) ITM Peripheral Identification Register #1 */ __I uint32_t PID2; /*!< Offset: 0xFE8 (R/ ) ITM Peripheral Identification Register #2 */ __I uint32_t PID3; /*!< Offset: 0xFEC (R/ ) ITM Peripheral Identification Register #3 */ __I uint32_t CID0; /*!< Offset: 0xFF0 (R/ ) ITM Component Identification Register #0 */ __I uint32_t CID1; /*!< Offset: 0xFF4 (R/ ) ITM Component Identification Register #1 */ __I uint32_t CID2; /*!< Offset: 0xFF8 (R/ ) ITM Component Identification Register #2 */ __I uint32_t CID3; /*!< Offset: 0xFFC (R/ ) ITM Component Identification Register #3 */ } ITM_Type; /* ITM Trace Privilege Register Definitions */ #define ITM_TPR_PRIVMASK_Pos 0 /*!< ITM TPR: PRIVMASK Position */ #define ITM_TPR_PRIVMASK_Msk (0xFUL /*<< ITM_TPR_PRIVMASK_Pos*/) /*!< ITM TPR: PRIVMASK Mask */ /* ITM Trace Control Register Definitions */ #define ITM_TCR_BUSY_Pos 23 /*!< ITM TCR: BUSY Position */ #define ITM_TCR_BUSY_Msk (1UL << ITM_TCR_BUSY_Pos) /*!< ITM TCR: BUSY Mask */ #define ITM_TCR_TraceBusID_Pos 16 /*!< ITM TCR: ATBID Position */ #define ITM_TCR_TraceBusID_Msk (0x7FUL << ITM_TCR_TraceBusID_Pos) /*!< ITM TCR: ATBID Mask */ #define ITM_TCR_GTSFREQ_Pos 10 /*!< ITM TCR: Global timestamp frequency Position */ #define ITM_TCR_GTSFREQ_Msk (3UL << ITM_TCR_GTSFREQ_Pos) /*!< ITM TCR: Global timestamp frequency Mask */ #define ITM_TCR_TSPrescale_Pos 8 /*!< ITM TCR: TSPrescale Position */ #define ITM_TCR_TSPrescale_Msk (3UL << ITM_TCR_TSPrescale_Pos) /*!< ITM TCR: TSPrescale Mask */ #define ITM_TCR_SWOENA_Pos 4 /*!< ITM TCR: SWOENA Position */ #define ITM_TCR_SWOENA_Msk (1UL << ITM_TCR_SWOENA_Pos) /*!< ITM TCR: SWOENA Mask */ #define ITM_TCR_DWTENA_Pos 3 /*!< ITM TCR: DWTENA Position */ #define ITM_TCR_DWTENA_Msk (1UL << ITM_TCR_DWTENA_Pos) /*!< ITM TCR: DWTENA Mask */ #define ITM_TCR_SYNCENA_Pos 2 /*!< ITM TCR: SYNCENA Position */ #define ITM_TCR_SYNCENA_Msk (1UL << ITM_TCR_SYNCENA_Pos) /*!< ITM TCR: SYNCENA Mask */ #define ITM_TCR_TSENA_Pos 1 /*!< ITM TCR: TSENA Position */ #define ITM_TCR_TSENA_Msk (1UL << ITM_TCR_TSENA_Pos) /*!< ITM TCR: TSENA Mask */ #define ITM_TCR_ITMENA_Pos 0 /*!< ITM TCR: ITM Enable bit Position */ #define ITM_TCR_ITMENA_Msk (1UL /*<< ITM_TCR_ITMENA_Pos*/) /*!< ITM TCR: ITM Enable bit Mask */ /* ITM Integration Write Register Definitions */ #define ITM_IWR_ATVALIDM_Pos 0 /*!< ITM IWR: ATVALIDM Position */ #define ITM_IWR_ATVALIDM_Msk (1UL /*<< ITM_IWR_ATVALIDM_Pos*/) /*!< ITM IWR: ATVALIDM Mask */ /* ITM Integration Read Register Definitions */ #define ITM_IRR_ATREADYM_Pos 0 /*!< ITM IRR: ATREADYM Position */ #define ITM_IRR_ATREADYM_Msk (1UL /*<< ITM_IRR_ATREADYM_Pos*/) /*!< ITM IRR: ATREADYM Mask */ /* ITM Integration Mode Control Register Definitions */ #define ITM_IMCR_INTEGRATION_Pos 0 /*!< ITM IMCR: INTEGRATION Position */ #define ITM_IMCR_INTEGRATION_Msk (1UL /*<< ITM_IMCR_INTEGRATION_Pos*/) /*!< ITM IMCR: INTEGRATION Mask */ /* ITM Lock Status Register Definitions */ #define ITM_LSR_ByteAcc_Pos 2 /*!< ITM LSR: ByteAcc Position */ #define ITM_LSR_ByteAcc_Msk (1UL << ITM_LSR_ByteAcc_Pos) /*!< ITM LSR: ByteAcc Mask */ #define ITM_LSR_Access_Pos 1 /*!< ITM LSR: Access Position */ #define ITM_LSR_Access_Msk (1UL << ITM_LSR_Access_Pos) /*!< ITM LSR: Access Mask */ #define ITM_LSR_Present_Pos 0 /*!< ITM LSR: Present Position */ #define ITM_LSR_Present_Msk (1UL /*<< ITM_LSR_Present_Pos*/) /*!< ITM LSR: Present Mask */ /*@}*/ /* end of group CMSIS_ITM */ /** \ingroup CMSIS_core_register \defgroup CMSIS_DWT Data Watchpoint and Trace (DWT) \brief Type definitions for the Data Watchpoint and Trace (DWT) @{ */ /** \brief Structure type to access the Data Watchpoint and Trace Register (DWT). */ typedef struct { __IO uint32_t CTRL; /*!< Offset: 0x000 (R/W) Control Register */ __IO uint32_t CYCCNT; /*!< Offset: 0x004 (R/W) Cycle Count Register */ __IO uint32_t CPICNT; /*!< Offset: 0x008 (R/W) CPI Count Register */ __IO uint32_t EXCCNT; /*!< Offset: 0x00C (R/W) Exception Overhead Count Register */ __IO uint32_t SLEEPCNT; /*!< Offset: 0x010 (R/W) Sleep Count Register */ __IO uint32_t LSUCNT; /*!< Offset: 0x014 (R/W) LSU Count Register */ __IO uint32_t FOLDCNT; /*!< Offset: 0x018 (R/W) Folded-instruction Count Register */ __I uint32_t PCSR; /*!< Offset: 0x01C (R/ ) Program Counter Sample Register */ __IO uint32_t COMP0; /*!< Offset: 0x020 (R/W) Comparator Register 0 */ __IO uint32_t MASK0; /*!< Offset: 0x024 (R/W) Mask Register 0 */ __IO uint32_t FUNCTION0; /*!< Offset: 0x028 (R/W) Function Register 0 */ uint32_t RESERVED0[1]; __IO uint32_t COMP1; /*!< Offset: 0x030 (R/W) Comparator Register 1 */ __IO uint32_t MASK1; /*!< Offset: 0x034 (R/W) Mask Register 1 */ __IO uint32_t FUNCTION1; /*!< Offset: 0x038 (R/W) Function Register 1 */ uint32_t RESERVED1[1]; __IO uint32_t COMP2; /*!< Offset: 0x040 (R/W) Comparator Register 2 */ __IO uint32_t MASK2; /*!< Offset: 0x044 (R/W) Mask Register 2 */ __IO uint32_t FUNCTION2; /*!< Offset: 0x048 (R/W) Function Register 2 */ uint32_t RESERVED2[1]; __IO uint32_t COMP3; /*!< Offset: 0x050 (R/W) Comparator Register 3 */ __IO uint32_t MASK3; /*!< Offset: 0x054 (R/W) Mask Register 3 */ __IO uint32_t FUNCTION3; /*!< Offset: 0x058 (R/W) Function Register 3 */ uint32_t RESERVED3[981]; __O uint32_t LAR; /*!< Offset: 0xFB0 ( W) Lock Access Register */ __I uint32_t LSR; /*!< Offset: 0xFB4 (R ) Lock Status Register */ } DWT_Type; /* DWT Control Register Definitions */ #define DWT_CTRL_NUMCOMP_Pos 28 /*!< DWT CTRL: NUMCOMP Position */ #define DWT_CTRL_NUMCOMP_Msk (0xFUL << DWT_CTRL_NUMCOMP_Pos) /*!< DWT CTRL: NUMCOMP Mask */ #define DWT_CTRL_NOTRCPKT_Pos 27 /*!< DWT CTRL: NOTRCPKT Position */ #define DWT_CTRL_NOTRCPKT_Msk (0x1UL << DWT_CTRL_NOTRCPKT_Pos) /*!< DWT CTRL: NOTRCPKT Mask */ #define DWT_CTRL_NOEXTTRIG_Pos 26 /*!< DWT CTRL: NOEXTTRIG Position */ #define DWT_CTRL_NOEXTTRIG_Msk (0x1UL << DWT_CTRL_NOEXTTRIG_Pos) /*!< DWT CTRL: NOEXTTRIG Mask */ #define DWT_CTRL_NOCYCCNT_Pos 25 /*!< DWT CTRL: NOCYCCNT Position */ #define DWT_CTRL_NOCYCCNT_Msk (0x1UL << DWT_CTRL_NOCYCCNT_Pos) /*!< DWT CTRL: NOCYCCNT Mask */ #define DWT_CTRL_NOPRFCNT_Pos 24 /*!< DWT CTRL: NOPRFCNT Position */ #define DWT_CTRL_NOPRFCNT_Msk (0x1UL << DWT_CTRL_NOPRFCNT_Pos) /*!< DWT CTRL: NOPRFCNT Mask */ #define DWT_CTRL_CYCEVTENA_Pos 22 /*!< DWT CTRL: CYCEVTENA Position */ #define DWT_CTRL_CYCEVTENA_Msk (0x1UL << DWT_CTRL_CYCEVTENA_Pos) /*!< DWT CTRL: CYCEVTENA Mask */ #define DWT_CTRL_FOLDEVTENA_Pos 21 /*!< DWT CTRL: FOLDEVTENA Position */ #define DWT_CTRL_FOLDEVTENA_Msk (0x1UL << DWT_CTRL_FOLDEVTENA_Pos) /*!< DWT CTRL: FOLDEVTENA Mask */ #define DWT_CTRL_LSUEVTENA_Pos 20 /*!< DWT CTRL: LSUEVTENA Position */ #define DWT_CTRL_LSUEVTENA_Msk (0x1UL << DWT_CTRL_LSUEVTENA_Pos) /*!< DWT CTRL: LSUEVTENA Mask */ #define DWT_CTRL_SLEEPEVTENA_Pos 19 /*!< DWT CTRL: SLEEPEVTENA Position */ #define DWT_CTRL_SLEEPEVTENA_Msk (0x1UL << DWT_CTRL_SLEEPEVTENA_Pos) /*!< DWT CTRL: SLEEPEVTENA Mask */ #define DWT_CTRL_EXCEVTENA_Pos 18 /*!< DWT CTRL: EXCEVTENA Position */ #define DWT_CTRL_EXCEVTENA_Msk (0x1UL << DWT_CTRL_EXCEVTENA_Pos) /*!< DWT CTRL: EXCEVTENA Mask */ #define DWT_CTRL_CPIEVTENA_Pos 17 /*!< DWT CTRL: CPIEVTENA Position */ #define DWT_CTRL_CPIEVTENA_Msk (0x1UL << DWT_CTRL_CPIEVTENA_Pos) /*!< DWT CTRL: CPIEVTENA Mask */ #define DWT_CTRL_EXCTRCENA_Pos 16 /*!< DWT CTRL: EXCTRCENA Position */ #define DWT_CTRL_EXCTRCENA_Msk (0x1UL << DWT_CTRL_EXCTRCENA_Pos) /*!< DWT CTRL: EXCTRCENA Mask */ #define DWT_CTRL_PCSAMPLENA_Pos 12 /*!< DWT CTRL: PCSAMPLENA Position */ #define DWT_CTRL_PCSAMPLENA_Msk (0x1UL << DWT_CTRL_PCSAMPLENA_Pos) /*!< DWT CTRL: PCSAMPLENA Mask */ #define DWT_CTRL_SYNCTAP_Pos 10 /*!< DWT CTRL: SYNCTAP Position */ #define DWT_CTRL_SYNCTAP_Msk (0x3UL << DWT_CTRL_SYNCTAP_Pos) /*!< DWT CTRL: SYNCTAP Mask */ #define DWT_CTRL_CYCTAP_Pos 9 /*!< DWT CTRL: CYCTAP Position */ #define DWT_CTRL_CYCTAP_Msk (0x1UL << DWT_CTRL_CYCTAP_Pos) /*!< DWT CTRL: CYCTAP Mask */ #define DWT_CTRL_POSTINIT_Pos 5 /*!< DWT CTRL: POSTINIT Position */ #define DWT_CTRL_POSTINIT_Msk (0xFUL << DWT_CTRL_POSTINIT_Pos) /*!< DWT CTRL: POSTINIT Mask */ #define DWT_CTRL_POSTPRESET_Pos 1 /*!< DWT CTRL: POSTPRESET Position */ #define DWT_CTRL_POSTPRESET_Msk (0xFUL << DWT_CTRL_POSTPRESET_Pos) /*!< DWT CTRL: POSTPRESET Mask */ #define DWT_CTRL_CYCCNTENA_Pos 0 /*!< DWT CTRL: CYCCNTENA Position */ #define DWT_CTRL_CYCCNTENA_Msk (0x1UL /*<< DWT_CTRL_CYCCNTENA_Pos*/) /*!< DWT CTRL: CYCCNTENA Mask */ /* DWT CPI Count Register Definitions */ #define DWT_CPICNT_CPICNT_Pos 0 /*!< DWT CPICNT: CPICNT Position */ #define DWT_CPICNT_CPICNT_Msk (0xFFUL /*<< DWT_CPICNT_CPICNT_Pos*/) /*!< DWT CPICNT: CPICNT Mask */ /* DWT Exception Overhead Count Register Definitions */ #define DWT_EXCCNT_EXCCNT_Pos 0 /*!< DWT EXCCNT: EXCCNT Position */ #define DWT_EXCCNT_EXCCNT_Msk (0xFFUL /*<< DWT_EXCCNT_EXCCNT_Pos*/) /*!< DWT EXCCNT: EXCCNT Mask */ /* DWT Sleep Count Register Definitions */ #define DWT_SLEEPCNT_SLEEPCNT_Pos 0 /*!< DWT SLEEPCNT: SLEEPCNT Position */ #define DWT_SLEEPCNT_SLEEPCNT_Msk (0xFFUL /*<< DWT_SLEEPCNT_SLEEPCNT_Pos*/) /*!< DWT SLEEPCNT: SLEEPCNT Mask */ /* DWT LSU Count Register Definitions */ #define DWT_LSUCNT_LSUCNT_Pos 0 /*!< DWT LSUCNT: LSUCNT Position */ #define DWT_LSUCNT_LSUCNT_Msk (0xFFUL /*<< DWT_LSUCNT_LSUCNT_Pos*/) /*!< DWT LSUCNT: LSUCNT Mask */ /* DWT Folded-instruction Count Register Definitions */ #define DWT_FOLDCNT_FOLDCNT_Pos 0 /*!< DWT FOLDCNT: FOLDCNT Position */ #define DWT_FOLDCNT_FOLDCNT_Msk (0xFFUL /*<< DWT_FOLDCNT_FOLDCNT_Pos*/) /*!< DWT FOLDCNT: FOLDCNT Mask */ /* DWT Comparator Mask Register Definitions */ #define DWT_MASK_MASK_Pos 0 /*!< DWT MASK: MASK Position */ #define DWT_MASK_MASK_Msk (0x1FUL /*<< DWT_MASK_MASK_Pos*/) /*!< DWT MASK: MASK Mask */ /* DWT Comparator Function Register Definitions */ #define DWT_FUNCTION_MATCHED_Pos 24 /*!< DWT FUNCTION: MATCHED Position */ #define DWT_FUNCTION_MATCHED_Msk (0x1UL << DWT_FUNCTION_MATCHED_Pos) /*!< DWT FUNCTION: MATCHED Mask */ #define DWT_FUNCTION_DATAVADDR1_Pos 16 /*!< DWT FUNCTION: DATAVADDR1 Position */ #define DWT_FUNCTION_DATAVADDR1_Msk (0xFUL << DWT_FUNCTION_DATAVADDR1_Pos) /*!< DWT FUNCTION: DATAVADDR1 Mask */ #define DWT_FUNCTION_DATAVADDR0_Pos 12 /*!< DWT FUNCTION: DATAVADDR0 Position */ #define DWT_FUNCTION_DATAVADDR0_Msk (0xFUL << DWT_FUNCTION_DATAVADDR0_Pos) /*!< DWT FUNCTION: DATAVADDR0 Mask */ #define DWT_FUNCTION_DATAVSIZE_Pos 10 /*!< DWT FUNCTION: DATAVSIZE Position */ #define DWT_FUNCTION_DATAVSIZE_Msk (0x3UL << DWT_FUNCTION_DATAVSIZE_Pos) /*!< DWT FUNCTION: DATAVSIZE Mask */ #define DWT_FUNCTION_LNK1ENA_Pos 9 /*!< DWT FUNCTION: LNK1ENA Position */ #define DWT_FUNCTION_LNK1ENA_Msk (0x1UL << DWT_FUNCTION_LNK1ENA_Pos) /*!< DWT FUNCTION: LNK1ENA Mask */ #define DWT_FUNCTION_DATAVMATCH_Pos 8 /*!< DWT FUNCTION: DATAVMATCH Position */ #define DWT_FUNCTION_DATAVMATCH_Msk (0x1UL << DWT_FUNCTION_DATAVMATCH_Pos) /*!< DWT FUNCTION: DATAVMATCH Mask */ #define DWT_FUNCTION_CYCMATCH_Pos 7 /*!< DWT FUNCTION: CYCMATCH Position */ #define DWT_FUNCTION_CYCMATCH_Msk (0x1UL << DWT_FUNCTION_CYCMATCH_Pos) /*!< DWT FUNCTION: CYCMATCH Mask */ #define DWT_FUNCTION_EMITRANGE_Pos 5 /*!< DWT FUNCTION: EMITRANGE Position */ #define DWT_FUNCTION_EMITRANGE_Msk (0x1UL << DWT_FUNCTION_EMITRANGE_Pos) /*!< DWT FUNCTION: EMITRANGE Mask */ #define DWT_FUNCTION_FUNCTION_Pos 0 /*!< DWT FUNCTION: FUNCTION Position */ #define DWT_FUNCTION_FUNCTION_Msk (0xFUL /*<< DWT_FUNCTION_FUNCTION_Pos*/) /*!< DWT FUNCTION: FUNCTION Mask */ /*@}*/ /* end of group CMSIS_DWT */ /** \ingroup CMSIS_core_register \defgroup CMSIS_TPI Trace Port Interface (TPI) \brief Type definitions for the Trace Port Interface (TPI) @{ */ /** \brief Structure type to access the Trace Port Interface Register (TPI). */ typedef struct { __IO uint32_t SSPSR; /*!< Offset: 0x000 (R/ ) Supported Parallel Port Size Register */ __IO uint32_t CSPSR; /*!< Offset: 0x004 (R/W) Current Parallel Port Size Register */ uint32_t RESERVED0[2]; __IO uint32_t ACPR; /*!< Offset: 0x010 (R/W) Asynchronous Clock Prescaler Register */ uint32_t RESERVED1[55]; __IO uint32_t SPPR; /*!< Offset: 0x0F0 (R/W) Selected Pin Protocol Register */ uint32_t RESERVED2[131]; __I uint32_t FFSR; /*!< Offset: 0x300 (R/ ) Formatter and Flush Status Register */ __IO uint32_t FFCR; /*!< Offset: 0x304 (R/W) Formatter and Flush Control Register */ __I uint32_t FSCR; /*!< Offset: 0x308 (R/ ) Formatter Synchronization Counter Register */ uint32_t RESERVED3[759]; __I uint32_t TRIGGER; /*!< Offset: 0xEE8 (R/ ) TRIGGER */ __I uint32_t FIFO0; /*!< Offset: 0xEEC (R/ ) Integration ETM Data */ __I uint32_t ITATBCTR2; /*!< Offset: 0xEF0 (R/ ) ITATBCTR2 */ uint32_t RESERVED4[1]; __I uint32_t ITATBCTR0; /*!< Offset: 0xEF8 (R/ ) ITATBCTR0 */ __I uint32_t FIFO1; /*!< Offset: 0xEFC (R/ ) Integration ITM Data */ __IO uint32_t ITCTRL; /*!< Offset: 0xF00 (R/W) Integration Mode Control */ uint32_t RESERVED5[39]; __IO uint32_t CLAIMSET; /*!< Offset: 0xFA0 (R/W) Claim tag set */ __IO uint32_t CLAIMCLR; /*!< Offset: 0xFA4 (R/W) Claim tag clear */ uint32_t RESERVED7[8]; __I uint32_t DEVID; /*!< Offset: 0xFC8 (R/ ) TPIU_DEVID */ __I uint32_t DEVTYPE; /*!< Offset: 0xFCC (R/ ) TPIU_DEVTYPE */ } TPI_Type; /* TPI Asynchronous Clock Prescaler Register Definitions */ #define TPI_ACPR_PRESCALER_Pos 0 /*!< TPI ACPR: PRESCALER Position */ #define TPI_ACPR_PRESCALER_Msk (0x1FFFUL /*<< TPI_ACPR_PRESCALER_Pos*/) /*!< TPI ACPR: PRESCALER Mask */ /* TPI Selected Pin Protocol Register Definitions */ #define TPI_SPPR_TXMODE_Pos 0 /*!< TPI SPPR: TXMODE Position */ #define TPI_SPPR_TXMODE_Msk (0x3UL /*<< TPI_SPPR_TXMODE_Pos*/) /*!< TPI SPPR: TXMODE Mask */ /* TPI Formatter and Flush Status Register Definitions */ #define TPI_FFSR_FtNonStop_Pos 3 /*!< TPI FFSR: FtNonStop Position */ #define TPI_FFSR_FtNonStop_Msk (0x1UL << TPI_FFSR_FtNonStop_Pos) /*!< TPI FFSR: FtNonStop Mask */ #define TPI_FFSR_TCPresent_Pos 2 /*!< TPI FFSR: TCPresent Position */ #define TPI_FFSR_TCPresent_Msk (0x1UL << TPI_FFSR_TCPresent_Pos) /*!< TPI FFSR: TCPresent Mask */ #define TPI_FFSR_FtStopped_Pos 1 /*!< TPI FFSR: FtStopped Position */ #define TPI_FFSR_FtStopped_Msk (0x1UL << TPI_FFSR_FtStopped_Pos) /*!< TPI FFSR: FtStopped Mask */ #define TPI_FFSR_FlInProg_Pos 0 /*!< TPI FFSR: FlInProg Position */ #define TPI_FFSR_FlInProg_Msk (0x1UL /*<< TPI_FFSR_FlInProg_Pos*/) /*!< TPI FFSR: FlInProg Mask */ /* TPI Formatter and Flush Control Register Definitions */ #define TPI_FFCR_TrigIn_Pos 8 /*!< TPI FFCR: TrigIn Position */ #define TPI_FFCR_TrigIn_Msk (0x1UL << TPI_FFCR_TrigIn_Pos) /*!< TPI FFCR: TrigIn Mask */ #define TPI_FFCR_EnFCont_Pos 1 /*!< TPI FFCR: EnFCont Position */ #define TPI_FFCR_EnFCont_Msk (0x1UL << TPI_FFCR_EnFCont_Pos) /*!< TPI FFCR: EnFCont Mask */ /* TPI TRIGGER Register Definitions */ #define TPI_TRIGGER_TRIGGER_Pos 0 /*!< TPI TRIGGER: TRIGGER Position */ #define TPI_TRIGGER_TRIGGER_Msk (0x1UL /*<< TPI_TRIGGER_TRIGGER_Pos*/) /*!< TPI TRIGGER: TRIGGER Mask */ /* TPI Integration ETM Data Register Definitions (FIFO0) */ #define TPI_FIFO0_ITM_ATVALID_Pos 29 /*!< TPI FIFO0: ITM_ATVALID Position */ #define TPI_FIFO0_ITM_ATVALID_Msk (0x3UL << TPI_FIFO0_ITM_ATVALID_Pos) /*!< TPI FIFO0: ITM_ATVALID Mask */ #define TPI_FIFO0_ITM_bytecount_Pos 27 /*!< TPI FIFO0: ITM_bytecount Position */ #define TPI_FIFO0_ITM_bytecount_Msk (0x3UL << TPI_FIFO0_ITM_bytecount_Pos) /*!< TPI FIFO0: ITM_bytecount Mask */ #define TPI_FIFO0_ETM_ATVALID_Pos 26 /*!< TPI FIFO0: ETM_ATVALID Position */ #define TPI_FIFO0_ETM_ATVALID_Msk (0x3UL << TPI_FIFO0_ETM_ATVALID_Pos) /*!< TPI FIFO0: ETM_ATVALID Mask */ #define TPI_FIFO0_ETM_bytecount_Pos 24 /*!< TPI FIFO0: ETM_bytecount Position */ #define TPI_FIFO0_ETM_bytecount_Msk (0x3UL << TPI_FIFO0_ETM_bytecount_Pos) /*!< TPI FIFO0: ETM_bytecount Mask */ #define TPI_FIFO0_ETM2_Pos 16 /*!< TPI FIFO0: ETM2 Position */ #define TPI_FIFO0_ETM2_Msk (0xFFUL << TPI_FIFO0_ETM2_Pos) /*!< TPI FIFO0: ETM2 Mask */ #define TPI_FIFO0_ETM1_Pos 8 /*!< TPI FIFO0: ETM1 Position */ #define TPI_FIFO0_ETM1_Msk (0xFFUL << TPI_FIFO0_ETM1_Pos) /*!< TPI FIFO0: ETM1 Mask */ #define TPI_FIFO0_ETM0_Pos 0 /*!< TPI FIFO0: ETM0 Position */ #define TPI_FIFO0_ETM0_Msk (0xFFUL /*<< TPI_FIFO0_ETM0_Pos*/) /*!< TPI FIFO0: ETM0 Mask */ /* TPI ITATBCTR2 Register Definitions */ #define TPI_ITATBCTR2_ATREADY_Pos 0 /*!< TPI ITATBCTR2: ATREADY Position */ #define TPI_ITATBCTR2_ATREADY_Msk (0x1UL /*<< TPI_ITATBCTR2_ATREADY_Pos*/) /*!< TPI ITATBCTR2: ATREADY Mask */ /* TPI Integration ITM Data Register Definitions (FIFO1) */ #define TPI_FIFO1_ITM_ATVALID_Pos 29 /*!< TPI FIFO1: ITM_ATVALID Position */ #define TPI_FIFO1_ITM_ATVALID_Msk (0x3UL << TPI_FIFO1_ITM_ATVALID_Pos) /*!< TPI FIFO1: ITM_ATVALID Mask */ #define TPI_FIFO1_ITM_bytecount_Pos 27 /*!< TPI FIFO1: ITM_bytecount Position */ #define TPI_FIFO1_ITM_bytecount_Msk (0x3UL << TPI_FIFO1_ITM_bytecount_Pos) /*!< TPI FIFO1: ITM_bytecount Mask */ #define TPI_FIFO1_ETM_ATVALID_Pos 26 /*!< TPI FIFO1: ETM_ATVALID Position */ #define TPI_FIFO1_ETM_ATVALID_Msk (0x3UL << TPI_FIFO1_ETM_ATVALID_Pos) /*!< TPI FIFO1: ETM_ATVALID Mask */ #define TPI_FIFO1_ETM_bytecount_Pos 24 /*!< TPI FIFO1: ETM_bytecount Position */ #define TPI_FIFO1_ETM_bytecount_Msk (0x3UL << TPI_FIFO1_ETM_bytecount_Pos) /*!< TPI FIFO1: ETM_bytecount Mask */ #define TPI_FIFO1_ITM2_Pos 16 /*!< TPI FIFO1: ITM2 Position */ #define TPI_FIFO1_ITM2_Msk (0xFFUL << TPI_FIFO1_ITM2_Pos) /*!< TPI FIFO1: ITM2 Mask */ #define TPI_FIFO1_ITM1_Pos 8 /*!< TPI FIFO1: ITM1 Position */ #define TPI_FIFO1_ITM1_Msk (0xFFUL << TPI_FIFO1_ITM1_Pos) /*!< TPI FIFO1: ITM1 Mask */ #define TPI_FIFO1_ITM0_Pos 0 /*!< TPI FIFO1: ITM0 Position */ #define TPI_FIFO1_ITM0_Msk (0xFFUL /*<< TPI_FIFO1_ITM0_Pos*/) /*!< TPI FIFO1: ITM0 Mask */ /* TPI ITATBCTR0 Register Definitions */ #define TPI_ITATBCTR0_ATREADY_Pos 0 /*!< TPI ITATBCTR0: ATREADY Position */ #define TPI_ITATBCTR0_ATREADY_Msk (0x1UL /*<< TPI_ITATBCTR0_ATREADY_Pos*/) /*!< TPI ITATBCTR0: ATREADY Mask */ /* TPI Integration Mode Control Register Definitions */ #define TPI_ITCTRL_Mode_Pos 0 /*!< TPI ITCTRL: Mode Position */ #define TPI_ITCTRL_Mode_Msk (0x1UL /*<< TPI_ITCTRL_Mode_Pos*/) /*!< TPI ITCTRL: Mode Mask */ /* TPI DEVID Register Definitions */ #define TPI_DEVID_NRZVALID_Pos 11 /*!< TPI DEVID: NRZVALID Position */ #define TPI_DEVID_NRZVALID_Msk (0x1UL << TPI_DEVID_NRZVALID_Pos) /*!< TPI DEVID: NRZVALID Mask */ #define TPI_DEVID_MANCVALID_Pos 10 /*!< TPI DEVID: MANCVALID Position */ #define TPI_DEVID_MANCVALID_Msk (0x1UL << TPI_DEVID_MANCVALID_Pos) /*!< TPI DEVID: MANCVALID Mask */ #define TPI_DEVID_PTINVALID_Pos 9 /*!< TPI DEVID: PTINVALID Position */ #define TPI_DEVID_PTINVALID_Msk (0x1UL << TPI_DEVID_PTINVALID_Pos) /*!< TPI DEVID: PTINVALID Mask */ #define TPI_DEVID_MinBufSz_Pos 6 /*!< TPI DEVID: MinBufSz Position */ #define TPI_DEVID_MinBufSz_Msk (0x7UL << TPI_DEVID_MinBufSz_Pos) /*!< TPI DEVID: MinBufSz Mask */ #define TPI_DEVID_AsynClkIn_Pos 5 /*!< TPI DEVID: AsynClkIn Position */ #define TPI_DEVID_AsynClkIn_Msk (0x1UL << TPI_DEVID_AsynClkIn_Pos) /*!< TPI DEVID: AsynClkIn Mask */ #define TPI_DEVID_NrTraceInput_Pos 0 /*!< TPI DEVID: NrTraceInput Position */ #define TPI_DEVID_NrTraceInput_Msk (0x1FUL /*<< TPI_DEVID_NrTraceInput_Pos*/) /*!< TPI DEVID: NrTraceInput Mask */ /* TPI DEVTYPE Register Definitions */ #define TPI_DEVTYPE_MajorType_Pos 4 /*!< TPI DEVTYPE: MajorType Position */ #define TPI_DEVTYPE_MajorType_Msk (0xFUL << TPI_DEVTYPE_MajorType_Pos) /*!< TPI DEVTYPE: MajorType Mask */ #define TPI_DEVTYPE_SubType_Pos 0 /*!< TPI DEVTYPE: SubType Position */ #define TPI_DEVTYPE_SubType_Msk (0xFUL /*<< TPI_DEVTYPE_SubType_Pos*/) /*!< TPI DEVTYPE: SubType Mask */ /*@}*/ /* end of group CMSIS_TPI */ #if (__MPU_PRESENT == 1) /** \ingroup CMSIS_core_register \defgroup CMSIS_MPU Memory Protection Unit (MPU) \brief Type definitions for the Memory Protection Unit (MPU) @{ */ /** \brief Structure type to access the Memory Protection Unit (MPU). */ typedef struct { __I uint32_t TYPE; /*!< Offset: 0x000 (R/ ) MPU Type Register */ __IO uint32_t CTRL; /*!< Offset: 0x004 (R/W) MPU Control Register */ __IO uint32_t RNR; /*!< Offset: 0x008 (R/W) MPU Region RNRber Register */ __IO uint32_t RBAR; /*!< Offset: 0x00C (R/W) MPU Region Base Address Register */ __IO uint32_t RASR; /*!< Offset: 0x010 (R/W) MPU Region Attribute and Size Register */ __IO uint32_t RBAR_A1; /*!< Offset: 0x014 (R/W) MPU Alias 1 Region Base Address Register */ __IO uint32_t RASR_A1; /*!< Offset: 0x018 (R/W) MPU Alias 1 Region Attribute and Size Register */ __IO uint32_t RBAR_A2; /*!< Offset: 0x01C (R/W) MPU Alias 2 Region Base Address Register */ __IO uint32_t RASR_A2; /*!< Offset: 0x020 (R/W) MPU Alias 2 Region Attribute and Size Register */ __IO uint32_t RBAR_A3; /*!< Offset: 0x024 (R/W) MPU Alias 3 Region Base Address Register */ __IO uint32_t RASR_A3; /*!< Offset: 0x028 (R/W) MPU Alias 3 Region Attribute and Size Register */ } MPU_Type; /* MPU Type Register */ #define MPU_TYPE_IREGION_Pos 16 /*!< MPU TYPE: IREGION Position */ #define MPU_TYPE_IREGION_Msk (0xFFUL << MPU_TYPE_IREGION_Pos) /*!< MPU TYPE: IREGION Mask */ #define MPU_TYPE_DREGION_Pos 8 /*!< MPU TYPE: DREGION Position */ #define MPU_TYPE_DREGION_Msk (0xFFUL << MPU_TYPE_DREGION_Pos) /*!< MPU TYPE: DREGION Mask */ #define MPU_TYPE_SEPARATE_Pos 0 /*!< MPU TYPE: SEPARATE Position */ #define MPU_TYPE_SEPARATE_Msk (1UL /*<< MPU_TYPE_SEPARATE_Pos*/) /*!< MPU TYPE: SEPARATE Mask */ /* MPU Control Register */ #define MPU_CTRL_PRIVDEFENA_Pos 2 /*!< MPU CTRL: PRIVDEFENA Position */ #define MPU_CTRL_PRIVDEFENA_Msk (1UL << MPU_CTRL_PRIVDEFENA_Pos) /*!< MPU CTRL: PRIVDEFENA Mask */ #define MPU_CTRL_HFNMIENA_Pos 1 /*!< MPU CTRL: HFNMIENA Position */ #define MPU_CTRL_HFNMIENA_Msk (1UL << MPU_CTRL_HFNMIENA_Pos) /*!< MPU CTRL: HFNMIENA Mask */ #define MPU_CTRL_ENABLE_Pos 0 /*!< MPU CTRL: ENABLE Position */ #define MPU_CTRL_ENABLE_Msk (1UL /*<< MPU_CTRL_ENABLE_Pos*/) /*!< MPU CTRL: ENABLE Mask */ /* MPU Region Number Register */ #define MPU_RNR_REGION_Pos 0 /*!< MPU RNR: REGION Position */ #define MPU_RNR_REGION_Msk (0xFFUL /*<< MPU_RNR_REGION_Pos*/) /*!< MPU RNR: REGION Mask */ /* MPU Region Base Address Register */ #define MPU_RBAR_ADDR_Pos 5 /*!< MPU RBAR: ADDR Position */ #define MPU_RBAR_ADDR_Msk (0x7FFFFFFUL << MPU_RBAR_ADDR_Pos) /*!< MPU RBAR: ADDR Mask */ #define MPU_RBAR_VALID_Pos 4 /*!< MPU RBAR: VALID Position */ #define MPU_RBAR_VALID_Msk (1UL << MPU_RBAR_VALID_Pos) /*!< MPU RBAR: VALID Mask */ #define MPU_RBAR_REGION_Pos 0 /*!< MPU RBAR: REGION Position */ #define MPU_RBAR_REGION_Msk (0xFUL /*<< MPU_RBAR_REGION_Pos*/) /*!< MPU RBAR: REGION Mask */ /* MPU Region Attribute and Size Register */ #define MPU_RASR_ATTRS_Pos 16 /*!< MPU RASR: MPU Region Attribute field Position */ #define MPU_RASR_ATTRS_Msk (0xFFFFUL << MPU_RASR_ATTRS_Pos) /*!< MPU RASR: MPU Region Attribute field Mask */ #define MPU_RASR_XN_Pos 28 /*!< MPU RASR: ATTRS.XN Position */ #define MPU_RASR_XN_Msk (1UL << MPU_RASR_XN_Pos) /*!< MPU RASR: ATTRS.XN Mask */ #define MPU_RASR_AP_Pos 24 /*!< MPU RASR: ATTRS.AP Position */ #define MPU_RASR_AP_Msk (0x7UL << MPU_RASR_AP_Pos) /*!< MPU RASR: ATTRS.AP Mask */ #define MPU_RASR_TEX_Pos 19 /*!< MPU RASR: ATTRS.TEX Position */ #define MPU_RASR_TEX_Msk (0x7UL << MPU_RASR_TEX_Pos) /*!< MPU RASR: ATTRS.TEX Mask */ #define MPU_RASR_S_Pos 18 /*!< MPU RASR: ATTRS.S Position */ #define MPU_RASR_S_Msk (1UL << MPU_RASR_S_Pos) /*!< MPU RASR: ATTRS.S Mask */ #define MPU_RASR_C_Pos 17 /*!< MPU RASR: ATTRS.C Position */ #define MPU_RASR_C_Msk (1UL << MPU_RASR_C_Pos) /*!< MPU RASR: ATTRS.C Mask */ #define MPU_RASR_B_Pos 16 /*!< MPU RASR: ATTRS.B Position */ #define MPU_RASR_B_Msk (1UL << MPU_RASR_B_Pos) /*!< MPU RASR: ATTRS.B Mask */ #define MPU_RASR_SRD_Pos 8 /*!< MPU RASR: Sub-Region Disable Position */ #define MPU_RASR_SRD_Msk (0xFFUL << MPU_RASR_SRD_Pos) /*!< MPU RASR: Sub-Region Disable Mask */ #define MPU_RASR_SIZE_Pos 1 /*!< MPU RASR: Region Size Field Position */ #define MPU_RASR_SIZE_Msk (0x1FUL << MPU_RASR_SIZE_Pos) /*!< MPU RASR: Region Size Field Mask */ #define MPU_RASR_ENABLE_Pos 0 /*!< MPU RASR: Region enable bit Position */ #define MPU_RASR_ENABLE_Msk (1UL /*<< MPU_RASR_ENABLE_Pos*/) /*!< MPU RASR: Region enable bit Disable Mask */ /*@} end of group CMSIS_MPU */ #endif #if (__FPU_PRESENT == 1) /** \ingroup CMSIS_core_register \defgroup CMSIS_FPU Floating Point Unit (FPU) \brief Type definitions for the Floating Point Unit (FPU) @{ */ /** \brief Structure type to access the Floating Point Unit (FPU). */ typedef struct { uint32_t RESERVED0[1]; __IO uint32_t FPCCR; /*!< Offset: 0x004 (R/W) Floating-Point Context Control Register */ __IO uint32_t FPCAR; /*!< Offset: 0x008 (R/W) Floating-Point Context Address Register */ __IO uint32_t FPDSCR; /*!< Offset: 0x00C (R/W) Floating-Point Default Status Control Register */ __I uint32_t MVFR0; /*!< Offset: 0x010 (R/ ) Media and FP Feature Register 0 */ __I uint32_t MVFR1; /*!< Offset: 0x014 (R/ ) Media and FP Feature Register 1 */ __I uint32_t MVFR2; /*!< Offset: 0x018 (R/ ) Media and FP Feature Register 2 */ } FPU_Type; /* Floating-Point Context Control Register */ #define FPU_FPCCR_ASPEN_Pos 31 /*!< FPCCR: ASPEN bit Position */ #define FPU_FPCCR_ASPEN_Msk (1UL << FPU_FPCCR_ASPEN_Pos) /*!< FPCCR: ASPEN bit Mask */ #define FPU_FPCCR_LSPEN_Pos 30 /*!< FPCCR: LSPEN Position */ #define FPU_FPCCR_LSPEN_Msk (1UL << FPU_FPCCR_LSPEN_Pos) /*!< FPCCR: LSPEN bit Mask */ #define FPU_FPCCR_MONRDY_Pos 8 /*!< FPCCR: MONRDY Position */ #define FPU_FPCCR_MONRDY_Msk (1UL << FPU_FPCCR_MONRDY_Pos) /*!< FPCCR: MONRDY bit Mask */ #define FPU_FPCCR_BFRDY_Pos 6 /*!< FPCCR: BFRDY Position */ #define FPU_FPCCR_BFRDY_Msk (1UL << FPU_FPCCR_BFRDY_Pos) /*!< FPCCR: BFRDY bit Mask */ #define FPU_FPCCR_MMRDY_Pos 5 /*!< FPCCR: MMRDY Position */ #define FPU_FPCCR_MMRDY_Msk (1UL << FPU_FPCCR_MMRDY_Pos) /*!< FPCCR: MMRDY bit Mask */ #define FPU_FPCCR_HFRDY_Pos 4 /*!< FPCCR: HFRDY Position */ #define FPU_FPCCR_HFRDY_Msk (1UL << FPU_FPCCR_HFRDY_Pos) /*!< FPCCR: HFRDY bit Mask */ #define FPU_FPCCR_THREAD_Pos 3 /*!< FPCCR: processor mode bit Position */ #define FPU_FPCCR_THREAD_Msk (1UL << FPU_FPCCR_THREAD_Pos) /*!< FPCCR: processor mode active bit Mask */ #define FPU_FPCCR_USER_Pos 1 /*!< FPCCR: privilege level bit Position */ #define FPU_FPCCR_USER_Msk (1UL << FPU_FPCCR_USER_Pos) /*!< FPCCR: privilege level bit Mask */ #define FPU_FPCCR_LSPACT_Pos 0 /*!< FPCCR: Lazy state preservation active bit Position */ #define FPU_FPCCR_LSPACT_Msk (1UL /*<< FPU_FPCCR_LSPACT_Pos*/) /*!< FPCCR: Lazy state preservation active bit Mask */ /* Floating-Point Context Address Register */ #define FPU_FPCAR_ADDRESS_Pos 3 /*!< FPCAR: ADDRESS bit Position */ #define FPU_FPCAR_ADDRESS_Msk (0x1FFFFFFFUL << FPU_FPCAR_ADDRESS_Pos) /*!< FPCAR: ADDRESS bit Mask */ /* Floating-Point Default Status Control Register */ #define FPU_FPDSCR_AHP_Pos 26 /*!< FPDSCR: AHP bit Position */ #define FPU_FPDSCR_AHP_Msk (1UL << FPU_FPDSCR_AHP_Pos) /*!< FPDSCR: AHP bit Mask */ #define FPU_FPDSCR_DN_Pos 25 /*!< FPDSCR: DN bit Position */ #define FPU_FPDSCR_DN_Msk (1UL << FPU_FPDSCR_DN_Pos) /*!< FPDSCR: DN bit Mask */ #define FPU_FPDSCR_FZ_Pos 24 /*!< FPDSCR: FZ bit Position */ #define FPU_FPDSCR_FZ_Msk (1UL << FPU_FPDSCR_FZ_Pos) /*!< FPDSCR: FZ bit Mask */ #define FPU_FPDSCR_RMode_Pos 22 /*!< FPDSCR: RMode bit Position */ #define FPU_FPDSCR_RMode_Msk (3UL << FPU_FPDSCR_RMode_Pos) /*!< FPDSCR: RMode bit Mask */ /* Media and FP Feature Register 0 */ #define FPU_MVFR0_FP_rounding_modes_Pos 28 /*!< MVFR0: FP rounding modes bits Position */ #define FPU_MVFR0_FP_rounding_modes_Msk (0xFUL << FPU_MVFR0_FP_rounding_modes_Pos) /*!< MVFR0: FP rounding modes bits Mask */ #define FPU_MVFR0_Short_vectors_Pos 24 /*!< MVFR0: Short vectors bits Position */ #define FPU_MVFR0_Short_vectors_Msk (0xFUL << FPU_MVFR0_Short_vectors_Pos) /*!< MVFR0: Short vectors bits Mask */ #define FPU_MVFR0_Square_root_Pos 20 /*!< MVFR0: Square root bits Position */ #define FPU_MVFR0_Square_root_Msk (0xFUL << FPU_MVFR0_Square_root_Pos) /*!< MVFR0: Square root bits Mask */ #define FPU_MVFR0_Divide_Pos 16 /*!< MVFR0: Divide bits Position */ #define FPU_MVFR0_Divide_Msk (0xFUL << FPU_MVFR0_Divide_Pos) /*!< MVFR0: Divide bits Mask */ #define FPU_MVFR0_FP_excep_trapping_Pos 12 /*!< MVFR0: FP exception trapping bits Position */ #define FPU_MVFR0_FP_excep_trapping_Msk (0xFUL << FPU_MVFR0_FP_excep_trapping_Pos) /*!< MVFR0: FP exception trapping bits Mask */ #define FPU_MVFR0_Double_precision_Pos 8 /*!< MVFR0: Double-precision bits Position */ #define FPU_MVFR0_Double_precision_Msk (0xFUL << FPU_MVFR0_Double_precision_Pos) /*!< MVFR0: Double-precision bits Mask */ #define FPU_MVFR0_Single_precision_Pos 4 /*!< MVFR0: Single-precision bits Position */ #define FPU_MVFR0_Single_precision_Msk (0xFUL << FPU_MVFR0_Single_precision_Pos) /*!< MVFR0: Single-precision bits Mask */ #define FPU_MVFR0_A_SIMD_registers_Pos 0 /*!< MVFR0: A_SIMD registers bits Position */ #define FPU_MVFR0_A_SIMD_registers_Msk (0xFUL /*<< FPU_MVFR0_A_SIMD_registers_Pos*/) /*!< MVFR0: A_SIMD registers bits Mask */ /* Media and FP Feature Register 1 */ #define FPU_MVFR1_FP_fused_MAC_Pos 28 /*!< MVFR1: FP fused MAC bits Position */ #define FPU_MVFR1_FP_fused_MAC_Msk (0xFUL << FPU_MVFR1_FP_fused_MAC_Pos) /*!< MVFR1: FP fused MAC bits Mask */ #define FPU_MVFR1_FP_HPFP_Pos 24 /*!< MVFR1: FP HPFP bits Position */ #define FPU_MVFR1_FP_HPFP_Msk (0xFUL << FPU_MVFR1_FP_HPFP_Pos) /*!< MVFR1: FP HPFP bits Mask */ #define FPU_MVFR1_D_NaN_mode_Pos 4 /*!< MVFR1: D_NaN mode bits Position */ #define FPU_MVFR1_D_NaN_mode_Msk (0xFUL << FPU_MVFR1_D_NaN_mode_Pos) /*!< MVFR1: D_NaN mode bits Mask */ #define FPU_MVFR1_FtZ_mode_Pos 0 /*!< MVFR1: FtZ mode bits Position */ #define FPU_MVFR1_FtZ_mode_Msk (0xFUL /*<< FPU_MVFR1_FtZ_mode_Pos*/) /*!< MVFR1: FtZ mode bits Mask */ /* Media and FP Feature Register 2 */ /*@} end of group CMSIS_FPU */ #endif /** \ingroup CMSIS_core_register \defgroup CMSIS_CoreDebug Core Debug Registers (CoreDebug) \brief Type definitions for the Core Debug Registers @{ */ /** \brief Structure type to access the Core Debug Register (CoreDebug). */ typedef struct { __IO uint32_t DHCSR; /*!< Offset: 0x000 (R/W) Debug Halting Control and Status Register */ __O uint32_t DCRSR; /*!< Offset: 0x004 ( /W) Debug Core Register Selector Register */ __IO uint32_t DCRDR; /*!< Offset: 0x008 (R/W) Debug Core Register Data Register */ __IO uint32_t DEMCR; /*!< Offset: 0x00C (R/W) Debug Exception and Monitor Control Register */ } CoreDebug_Type; /* Debug Halting Control and Status Register */ #define CoreDebug_DHCSR_DBGKEY_Pos 16 /*!< CoreDebug DHCSR: DBGKEY Position */ #define CoreDebug_DHCSR_DBGKEY_Msk (0xFFFFUL << CoreDebug_DHCSR_DBGKEY_Pos) /*!< CoreDebug DHCSR: DBGKEY Mask */ #define CoreDebug_DHCSR_S_RESET_ST_Pos 25 /*!< CoreDebug DHCSR: S_RESET_ST Position */ #define CoreDebug_DHCSR_S_RESET_ST_Msk (1UL << CoreDebug_DHCSR_S_RESET_ST_Pos) /*!< CoreDebug DHCSR: S_RESET_ST Mask */ #define CoreDebug_DHCSR_S_RETIRE_ST_Pos 24 /*!< CoreDebug DHCSR: S_RETIRE_ST Position */ #define CoreDebug_DHCSR_S_RETIRE_ST_Msk (1UL << CoreDebug_DHCSR_S_RETIRE_ST_Pos) /*!< CoreDebug DHCSR: S_RETIRE_ST Mask */ #define CoreDebug_DHCSR_S_LOCKUP_Pos 19 /*!< CoreDebug DHCSR: S_LOCKUP Position */ #define CoreDebug_DHCSR_S_LOCKUP_Msk (1UL << CoreDebug_DHCSR_S_LOCKUP_Pos) /*!< CoreDebug DHCSR: S_LOCKUP Mask */ #define CoreDebug_DHCSR_S_SLEEP_Pos 18 /*!< CoreDebug DHCSR: S_SLEEP Position */ #define CoreDebug_DHCSR_S_SLEEP_Msk (1UL << CoreDebug_DHCSR_S_SLEEP_Pos) /*!< CoreDebug DHCSR: S_SLEEP Mask */ #define CoreDebug_DHCSR_S_HALT_Pos 17 /*!< CoreDebug DHCSR: S_HALT Position */ #define CoreDebug_DHCSR_S_HALT_Msk (1UL << CoreDebug_DHCSR_S_HALT_Pos) /*!< CoreDebug DHCSR: S_HALT Mask */ #define CoreDebug_DHCSR_S_REGRDY_Pos 16 /*!< CoreDebug DHCSR: S_REGRDY Position */ #define CoreDebug_DHCSR_S_REGRDY_Msk (1UL << CoreDebug_DHCSR_S_REGRDY_Pos) /*!< CoreDebug DHCSR: S_REGRDY Mask */ #define CoreDebug_DHCSR_C_SNAPSTALL_Pos 5 /*!< CoreDebug DHCSR: C_SNAPSTALL Position */ #define CoreDebug_DHCSR_C_SNAPSTALL_Msk (1UL << CoreDebug_DHCSR_C_SNAPSTALL_Pos) /*!< CoreDebug DHCSR: C_SNAPSTALL Mask */ #define CoreDebug_DHCSR_C_MASKINTS_Pos 3 /*!< CoreDebug DHCSR: C_MASKINTS Position */ #define CoreDebug_DHCSR_C_MASKINTS_Msk (1UL << CoreDebug_DHCSR_C_MASKINTS_Pos) /*!< CoreDebug DHCSR: C_MASKINTS Mask */ #define CoreDebug_DHCSR_C_STEP_Pos 2 /*!< CoreDebug DHCSR: C_STEP Position */ #define CoreDebug_DHCSR_C_STEP_Msk (1UL << CoreDebug_DHCSR_C_STEP_Pos) /*!< CoreDebug DHCSR: C_STEP Mask */ #define CoreDebug_DHCSR_C_HALT_Pos 1 /*!< CoreDebug DHCSR: C_HALT Position */ #define CoreDebug_DHCSR_C_HALT_Msk (1UL << CoreDebug_DHCSR_C_HALT_Pos) /*!< CoreDebug DHCSR: C_HALT Mask */ #define CoreDebug_DHCSR_C_DEBUGEN_Pos 0 /*!< CoreDebug DHCSR: C_DEBUGEN Position */ #define CoreDebug_DHCSR_C_DEBUGEN_Msk (1UL /*<< CoreDebug_DHCSR_C_DEBUGEN_Pos*/) /*!< CoreDebug DHCSR: C_DEBUGEN Mask */ /* Debug Core Register Selector Register */ #define CoreDebug_DCRSR_REGWnR_Pos 16 /*!< CoreDebug DCRSR: REGWnR Position */ #define CoreDebug_DCRSR_REGWnR_Msk (1UL << CoreDebug_DCRSR_REGWnR_Pos) /*!< CoreDebug DCRSR: REGWnR Mask */ #define CoreDebug_DCRSR_REGSEL_Pos 0 /*!< CoreDebug DCRSR: REGSEL Position */ #define CoreDebug_DCRSR_REGSEL_Msk (0x1FUL /*<< CoreDebug_DCRSR_REGSEL_Pos*/) /*!< CoreDebug DCRSR: REGSEL Mask */ /* Debug Exception and Monitor Control Register */ #define CoreDebug_DEMCR_TRCENA_Pos 24 /*!< CoreDebug DEMCR: TRCENA Position */ #define CoreDebug_DEMCR_TRCENA_Msk (1UL << CoreDebug_DEMCR_TRCENA_Pos) /*!< CoreDebug DEMCR: TRCENA Mask */ #define CoreDebug_DEMCR_MON_REQ_Pos 19 /*!< CoreDebug DEMCR: MON_REQ Position */ #define CoreDebug_DEMCR_MON_REQ_Msk (1UL << CoreDebug_DEMCR_MON_REQ_Pos) /*!< CoreDebug DEMCR: MON_REQ Mask */ #define CoreDebug_DEMCR_MON_STEP_Pos 18 /*!< CoreDebug DEMCR: MON_STEP Position */ #define CoreDebug_DEMCR_MON_STEP_Msk (1UL << CoreDebug_DEMCR_MON_STEP_Pos) /*!< CoreDebug DEMCR: MON_STEP Mask */ #define CoreDebug_DEMCR_MON_PEND_Pos 17 /*!< CoreDebug DEMCR: MON_PEND Position */ #define CoreDebug_DEMCR_MON_PEND_Msk (1UL << CoreDebug_DEMCR_MON_PEND_Pos) /*!< CoreDebug DEMCR: MON_PEND Mask */ #define CoreDebug_DEMCR_MON_EN_Pos 16 /*!< CoreDebug DEMCR: MON_EN Position */ #define CoreDebug_DEMCR_MON_EN_Msk (1UL << CoreDebug_DEMCR_MON_EN_Pos) /*!< CoreDebug DEMCR: MON_EN Mask */ #define CoreDebug_DEMCR_VC_HARDERR_Pos 10 /*!< CoreDebug DEMCR: VC_HARDERR Position */ #define CoreDebug_DEMCR_VC_HARDERR_Msk (1UL << CoreDebug_DEMCR_VC_HARDERR_Pos) /*!< CoreDebug DEMCR: VC_HARDERR Mask */ #define CoreDebug_DEMCR_VC_INTERR_Pos 9 /*!< CoreDebug DEMCR: VC_INTERR Position */ #define CoreDebug_DEMCR_VC_INTERR_Msk (1UL << CoreDebug_DEMCR_VC_INTERR_Pos) /*!< CoreDebug DEMCR: VC_INTERR Mask */ #define CoreDebug_DEMCR_VC_BUSERR_Pos 8 /*!< CoreDebug DEMCR: VC_BUSERR Position */ #define CoreDebug_DEMCR_VC_BUSERR_Msk (1UL << CoreDebug_DEMCR_VC_BUSERR_Pos) /*!< CoreDebug DEMCR: VC_BUSERR Mask */ #define CoreDebug_DEMCR_VC_STATERR_Pos 7 /*!< CoreDebug DEMCR: VC_STATERR Position */ #define CoreDebug_DEMCR_VC_STATERR_Msk (1UL << CoreDebug_DEMCR_VC_STATERR_Pos) /*!< CoreDebug DEMCR: VC_STATERR Mask */ #define CoreDebug_DEMCR_VC_CHKERR_Pos 6 /*!< CoreDebug DEMCR: VC_CHKERR Position */ #define CoreDebug_DEMCR_VC_CHKERR_Msk (1UL << CoreDebug_DEMCR_VC_CHKERR_Pos) /*!< CoreDebug DEMCR: VC_CHKERR Mask */ #define CoreDebug_DEMCR_VC_NOCPERR_Pos 5 /*!< CoreDebug DEMCR: VC_NOCPERR Position */ #define CoreDebug_DEMCR_VC_NOCPERR_Msk (1UL << CoreDebug_DEMCR_VC_NOCPERR_Pos) /*!< CoreDebug DEMCR: VC_NOCPERR Mask */ #define CoreDebug_DEMCR_VC_MMERR_Pos 4 /*!< CoreDebug DEMCR: VC_MMERR Position */ #define CoreDebug_DEMCR_VC_MMERR_Msk (1UL << CoreDebug_DEMCR_VC_MMERR_Pos) /*!< CoreDebug DEMCR: VC_MMERR Mask */ #define CoreDebug_DEMCR_VC_CORERESET_Pos 0 /*!< CoreDebug DEMCR: VC_CORERESET Position */ #define CoreDebug_DEMCR_VC_CORERESET_Msk (1UL /*<< CoreDebug_DEMCR_VC_CORERESET_Pos*/) /*!< CoreDebug DEMCR: VC_CORERESET Mask */ /*@} end of group CMSIS_CoreDebug */ /** \ingroup CMSIS_core_register \defgroup CMSIS_core_base Core Definitions \brief Definitions for base addresses, unions, and structures. @{ */ /* Memory mapping of Cortex-M4 Hardware */ #define SCS_BASE (0xE000E000UL) /*!< System Control Space Base Address */ #define ITM_BASE (0xE0000000UL) /*!< ITM Base Address */ #define DWT_BASE (0xE0001000UL) /*!< DWT Base Address */ #define TPI_BASE (0xE0040000UL) /*!< TPI Base Address */ #define CoreDebug_BASE (0xE000EDF0UL) /*!< Core Debug Base Address */ #define SysTick_BASE (SCS_BASE + 0x0010UL) /*!< SysTick Base Address */ #define NVIC_BASE (SCS_BASE + 0x0100UL) /*!< NVIC Base Address */ #define SCB_BASE (SCS_BASE + 0x0D00UL) /*!< System Control Block Base Address */ #define SCnSCB ((SCnSCB_Type *) SCS_BASE ) /*!< System control Register not in SCB */ #define SCB ((SCB_Type *) SCB_BASE ) /*!< SCB configuration struct */ #define SysTick ((SysTick_Type *) SysTick_BASE ) /*!< SysTick configuration struct */ #define NVIC ((NVIC_Type *) NVIC_BASE ) /*!< NVIC configuration struct */ #define ITM ((ITM_Type *) ITM_BASE ) /*!< ITM configuration struct */ #define DWT ((DWT_Type *) DWT_BASE ) /*!< DWT configuration struct */ #define TPI ((TPI_Type *) TPI_BASE ) /*!< TPI configuration struct */ #define CoreDebug ((CoreDebug_Type *) CoreDebug_BASE) /*!< Core Debug configuration struct */ #if (__MPU_PRESENT == 1) #define MPU_BASE (SCS_BASE + 0x0D90UL) /*!< Memory Protection Unit */ #define MPU ((MPU_Type *) MPU_BASE ) /*!< Memory Protection Unit */ #endif #if (__FPU_PRESENT == 1) #define FPU_BASE (SCS_BASE + 0x0F30UL) /*!< Floating Point Unit */ #define FPU ((FPU_Type *) FPU_BASE ) /*!< Floating Point Unit */ #endif /*@} */ /******************************************************************************* * Hardware Abstraction Layer Core Function Interface contains: - Core NVIC Functions - Core SysTick Functions - Core Debug Functions - Core Register Access Functions ******************************************************************************/ /** \defgroup CMSIS_Core_FunctionInterface Functions and Instructions Reference */ /* ########################## NVIC functions #################################### */ /** \ingroup CMSIS_Core_FunctionInterface \defgroup CMSIS_Core_NVICFunctions NVIC Functions \brief Functions that manage interrupts and exceptions via the NVIC. @{ */ /** \brief Set Priority Grouping The function sets the priority grouping field using the required unlock sequence. The parameter PriorityGroup is assigned to the field SCB->AIRCR [10:8] PRIGROUP field. Only values from 0..7 are used. In case of a conflict between priority grouping and available priority bits (__NVIC_PRIO_BITS), the smallest possible priority group is set. \param [in] PriorityGroup Priority grouping field. */ __STATIC_INLINE void NVIC_SetPriorityGrouping(uint32_t PriorityGroup) { uint32_t reg_value; uint32_t PriorityGroupTmp = (PriorityGroup & (uint32_t)0x07UL); /* only values 0..7 are used */ reg_value = SCB->AIRCR; /* read old register configuration */ reg_value &= ~((uint32_t)(SCB_AIRCR_VECTKEY_Msk | SCB_AIRCR_PRIGROUP_Msk)); /* clear bits to change */ reg_value = (reg_value | ((uint32_t)0x5FAUL << SCB_AIRCR_VECTKEY_Pos) | (PriorityGroupTmp << 8) ); /* Insert write key and priorty group */ SCB->AIRCR = reg_value; } /** \brief Get Priority Grouping The function reads the priority grouping field from the NVIC Interrupt Controller. \return Priority grouping field (SCB->AIRCR [10:8] PRIGROUP field). */ __STATIC_INLINE uint32_t NVIC_GetPriorityGrouping(void) { return ((uint32_t)((SCB->AIRCR & SCB_AIRCR_PRIGROUP_Msk) >> SCB_AIRCR_PRIGROUP_Pos)); } /** \brief Enable External Interrupt The function enables a device-specific interrupt in the NVIC interrupt controller. \param [in] IRQn External interrupt number. Value cannot be negative. */ __STATIC_INLINE void NVIC_EnableIRQ(IRQn_Type IRQn) { NVIC->ISER[(((uint32_t)(int32_t)IRQn) >> 5UL)] = (uint32_t)(1UL << (((uint32_t)(int32_t)IRQn) & 0x1FUL)); } /** \brief Disable External Interrupt The function disables a device-specific interrupt in the NVIC interrupt controller. \param [in] IRQn External interrupt number. Value cannot be negative. */ __STATIC_INLINE void NVIC_DisableIRQ(IRQn_Type IRQn) { NVIC->ICER[(((uint32_t)(int32_t)IRQn) >> 5UL)] = (uint32_t)(1UL << (((uint32_t)(int32_t)IRQn) & 0x1FUL)); } /** \brief Get Pending Interrupt The function reads the pending register in the NVIC and returns the pending bit for the specified interrupt. \param [in] IRQn Interrupt number. \return 0 Interrupt status is not pending. \return 1 Interrupt status is pending. */ __STATIC_INLINE uint32_t NVIC_GetPendingIRQ(IRQn_Type IRQn) { return((uint32_t)(((NVIC->ISPR[(((uint32_t)(int32_t)IRQn) >> 5UL)] & (1UL << (((uint32_t)(int32_t)IRQn) & 0x1FUL))) != 0UL) ? 1UL : 0UL)); } /** \brief Set Pending Interrupt The function sets the pending bit of an external interrupt. \param [in] IRQn Interrupt number. Value cannot be negative. */ __STATIC_INLINE void NVIC_SetPendingIRQ(IRQn_Type IRQn) { NVIC->ISPR[(((uint32_t)(int32_t)IRQn) >> 5UL)] = (uint32_t)(1UL << (((uint32_t)(int32_t)IRQn) & 0x1FUL)); } /** \brief Clear Pending Interrupt The function clears the pending bit of an external interrupt. \param [in] IRQn External interrupt number. Value cannot be negative. */ __STATIC_INLINE void NVIC_ClearPendingIRQ(IRQn_Type IRQn) { NVIC->ICPR[(((uint32_t)(int32_t)IRQn) >> 5UL)] = (uint32_t)(1UL << (((uint32_t)(int32_t)IRQn) & 0x1FUL)); } /** \brief Get Active Interrupt The function reads the active register in NVIC and returns the active bit. \param [in] IRQn Interrupt number. \return 0 Interrupt status is not active. \return 1 Interrupt status is active. */ __STATIC_INLINE uint32_t NVIC_GetActive(IRQn_Type IRQn) { return((uint32_t)(((NVIC->IABR[(((uint32_t)(int32_t)IRQn) >> 5UL)] & (1UL << (((uint32_t)(int32_t)IRQn) & 0x1FUL))) != 0UL) ? 1UL : 0UL)); } /** \brief Set Interrupt Priority The function sets the priority of an interrupt. \note The priority cannot be set for every core interrupt. \param [in] IRQn Interrupt number. \param [in] priority Priority to set. */ __STATIC_INLINE void NVIC_SetPriority(IRQn_Type IRQn, uint32_t priority) { if((int32_t)IRQn < 0) { SCB->SHPR[(((uint32_t)(int32_t)IRQn) & 0xFUL)-4UL] = (uint8_t)((priority << (8 - __NVIC_PRIO_BITS)) & (uint32_t)0xFFUL); } else { NVIC->IP[((uint32_t)(int32_t)IRQn)] = (uint8_t)((priority << (8 - __NVIC_PRIO_BITS)) & (uint32_t)0xFFUL); } } /** \brief Get Interrupt Priority The function reads the priority of an interrupt. The interrupt number can be positive to specify an external (device specific) interrupt, or negative to specify an internal (core) interrupt. \param [in] IRQn Interrupt number. \return Interrupt Priority. Value is aligned automatically to the implemented priority bits of the microcontroller. */ __STATIC_INLINE uint32_t NVIC_GetPriority(IRQn_Type IRQn) { if((int32_t)IRQn < 0) { return(((uint32_t)SCB->SHPR[(((uint32_t)(int32_t)IRQn) & 0xFUL)-4UL] >> (8 - __NVIC_PRIO_BITS))); } else { return(((uint32_t)NVIC->IP[((uint32_t)(int32_t)IRQn)] >> (8 - __NVIC_PRIO_BITS))); } } /** \brief Encode Priority The function encodes the priority for an interrupt with the given priority group, preemptive priority value, and subpriority value. In case of a conflict between priority grouping and available priority bits (__NVIC_PRIO_BITS), the smallest possible priority group is set. \param [in] PriorityGroup Used priority group. \param [in] PreemptPriority Preemptive priority value (starting from 0). \param [in] SubPriority Subpriority value (starting from 0). \return Encoded priority. Value can be used in the function \ref NVIC_SetPriority(). */ __STATIC_INLINE uint32_t NVIC_EncodePriority (uint32_t PriorityGroup, uint32_t PreemptPriority, uint32_t SubPriority) { uint32_t PriorityGroupTmp = (PriorityGroup & (uint32_t)0x07UL); /* only values 0..7 are used */ uint32_t PreemptPriorityBits; uint32_t SubPriorityBits; PreemptPriorityBits = ((7UL - PriorityGroupTmp) > (uint32_t)(__NVIC_PRIO_BITS)) ? (uint32_t)(__NVIC_PRIO_BITS) : (uint32_t)(7UL - PriorityGroupTmp); SubPriorityBits = ((PriorityGroupTmp + (uint32_t)(__NVIC_PRIO_BITS)) < (uint32_t)7UL) ? (uint32_t)0UL : (uint32_t)((PriorityGroupTmp - 7UL) + (uint32_t)(__NVIC_PRIO_BITS)); return ( ((PreemptPriority & (uint32_t)((1UL << (PreemptPriorityBits)) - 1UL)) << SubPriorityBits) | ((SubPriority & (uint32_t)((1UL << (SubPriorityBits )) - 1UL))) ); } /** \brief Decode Priority The function decodes an interrupt priority value with a given priority group to preemptive priority value and subpriority value. In case of a conflict between priority grouping and available priority bits (__NVIC_PRIO_BITS) the smallest possible priority group is set. \param [in] Priority Priority value, which can be retrieved with the function \ref NVIC_GetPriority(). \param [in] PriorityGroup Used priority group. \param [out] pPreemptPriority Preemptive priority value (starting from 0). \param [out] pSubPriority Subpriority value (starting from 0). */ __STATIC_INLINE void NVIC_DecodePriority (uint32_t Priority, uint32_t PriorityGroup, uint32_t* pPreemptPriority, uint32_t* pSubPriority) { uint32_t PriorityGroupTmp = (PriorityGroup & (uint32_t)0x07UL); /* only values 0..7 are used */ uint32_t PreemptPriorityBits; uint32_t SubPriorityBits; PreemptPriorityBits = ((7UL - PriorityGroupTmp) > (uint32_t)(__NVIC_PRIO_BITS)) ? (uint32_t)(__NVIC_PRIO_BITS) : (uint32_t)(7UL - PriorityGroupTmp); SubPriorityBits = ((PriorityGroupTmp + (uint32_t)(__NVIC_PRIO_BITS)) < (uint32_t)7UL) ? (uint32_t)0UL : (uint32_t)((PriorityGroupTmp - 7UL) + (uint32_t)(__NVIC_PRIO_BITS)); *pPreemptPriority = (Priority >> SubPriorityBits) & (uint32_t)((1UL << (PreemptPriorityBits)) - 1UL); *pSubPriority = (Priority ) & (uint32_t)((1UL << (SubPriorityBits )) - 1UL); } /** \brief System Reset The function initiates a system reset request to reset the MCU. */ __STATIC_INLINE void NVIC_SystemReset(void) { __DSB(); /* Ensure all outstanding memory accesses included buffered write are completed before reset */ SCB->AIRCR = (uint32_t)((0x5FAUL << SCB_AIRCR_VECTKEY_Pos) | (SCB->AIRCR & SCB_AIRCR_PRIGROUP_Msk) | SCB_AIRCR_SYSRESETREQ_Msk ); /* Keep priority group unchanged */ __DSB(); /* Ensure completion of memory access */ while(1) { __NOP(); } /* wait until reset */ } /*@} end of CMSIS_Core_NVICFunctions */ /* ########################## FPU functions #################################### */ /** \ingroup CMSIS_Core_FunctionInterface \defgroup CMSIS_Core_FpuFunctions FPU Functions \brief Function that provides FPU type. @{ */ /** \fn uint32_t SCB_GetFPUType(void) \brief get FPU type \returns - \b 0: No FPU - \b 1: Single precision FPU - \b 2: Double + Single precision FPU */ __STATIC_INLINE uint32_t SCB_GetFPUType(void) { uint32_t mvfr0; mvfr0 = SCB->MVFR0; if ((mvfr0 & 0x00000FF0UL) == 0x220UL) { return 2UL; // Double + Single precision FPU } else if ((mvfr0 & 0x00000FF0UL) == 0x020UL) { return 1UL; // Single precision FPU } else { return 0UL; // No FPU } } /*@} end of CMSIS_Core_FpuFunctions */ /* ########################## Cache functions #################################### */ /** \ingroup CMSIS_Core_FunctionInterface \defgroup CMSIS_Core_CacheFunctions Cache Functions \brief Functions that configure Instruction and Data cache. @{ */ /* Cache Size ID Register Macros */ #define CCSIDR_WAYS(x) (((x) & SCB_CCSIDR_ASSOCIATIVITY_Msk) >> SCB_CCSIDR_ASSOCIATIVITY_Pos) #define CCSIDR_SETS(x) (((x) & SCB_CCSIDR_NUMSETS_Msk ) >> SCB_CCSIDR_NUMSETS_Pos ) #define CCSIDR_LSSHIFT(x) (((x) & SCB_CCSIDR_LINESIZE_Msk ) /*>> SCB_CCSIDR_LINESIZE_Pos*/ ) /** \brief Enable I-Cache The function turns on I-Cache */ __STATIC_INLINE void SCB_EnableICache (void) { #if (__ICACHE_PRESENT == 1) __DSB(); __ISB(); SCB->ICIALLU = 0UL; // invalidate I-Cache SCB->CCR |= (uint32_t)SCB_CCR_IC_Msk; // enable I-Cache __DSB(); __ISB(); #endif } /** \brief Disable I-Cache The function turns off I-Cache */ __STATIC_INLINE void SCB_DisableICache (void) { #if (__ICACHE_PRESENT == 1) __DSB(); __ISB(); SCB->CCR &= ~(uint32_t)SCB_CCR_IC_Msk; // disable I-Cache SCB->ICIALLU = 0UL; // invalidate I-Cache __DSB(); __ISB(); #endif } /** \brief Invalidate I-Cache The function invalidates I-Cache */ __STATIC_INLINE void SCB_InvalidateICache (void) { #if (__ICACHE_PRESENT == 1) __DSB(); __ISB(); SCB->ICIALLU = 0UL; __DSB(); __ISB(); #endif } /** \brief Enable D-Cache The function turns on D-Cache */ __STATIC_INLINE void SCB_EnableDCache (void) { #if (__DCACHE_PRESENT == 1) uint32_t ccsidr, sshift, wshift, sw; uint32_t sets, ways; SCB->CSSELR = (0UL << 1) | 0UL; // Level 1 data cache ccsidr = SCB->CCSIDR; sets = (uint32_t)(CCSIDR_SETS(ccsidr)); sshift = (uint32_t)(CCSIDR_LSSHIFT(ccsidr) + 4UL); ways = (uint32_t)(CCSIDR_WAYS(ccsidr)); wshift = (uint32_t)((uint32_t)__CLZ(ways) & 0x1FUL); __DSB(); do { // invalidate D-Cache uint32_t tmpways = ways; do { sw = ((tmpways << wshift) | (sets << sshift)); SCB->DCISW = sw; } while(tmpways--); } while(sets--); __DSB(); SCB->CCR |= (uint32_t)SCB_CCR_DC_Msk; // enable D-Cache __DSB(); __ISB(); #endif } /** \brief Disable D-Cache The function turns off D-Cache */ __STATIC_INLINE void SCB_DisableDCache (void) { #if (__DCACHE_PRESENT == 1) uint32_t ccsidr, sshift, wshift, sw; uint32_t sets, ways; SCB->CSSELR = (0UL << 1) | 0UL; // Level 1 data cache ccsidr = SCB->CCSIDR; sets = (uint32_t)(CCSIDR_SETS(ccsidr)); sshift = (uint32_t)(CCSIDR_LSSHIFT(ccsidr) + 4UL); ways = (uint32_t)(CCSIDR_WAYS(ccsidr)); wshift = (uint32_t)((uint32_t)__CLZ(ways) & 0x1FUL); __DSB(); SCB->CCR &= ~(uint32_t)SCB_CCR_DC_Msk; // disable D-Cache do { // clean & invalidate D-Cache uint32_t tmpways = ways; do { sw = ((tmpways << wshift) | (sets << sshift)); SCB->DCCISW = sw; } while(tmpways--); } while(sets--); __DSB(); __ISB(); #endif } /** \brief Invalidate D-Cache The function invalidates D-Cache */ __STATIC_INLINE void SCB_InvalidateDCache (void) { #if (__DCACHE_PRESENT == 1) uint32_t ccsidr, sshift, wshift, sw; uint32_t sets, ways; SCB->CSSELR = (0UL << 1) | 0UL; // Level 1 data cache ccsidr = SCB->CCSIDR; sets = (uint32_t)(CCSIDR_SETS(ccsidr)); sshift = (uint32_t)(CCSIDR_LSSHIFT(ccsidr) + 4UL); ways = (uint32_t)(CCSIDR_WAYS(ccsidr)); wshift = (uint32_t)((uint32_t)__CLZ(ways) & 0x1FUL); __DSB(); do { // invalidate D-Cache uint32_t tmpways = ways; do { sw = ((tmpways << wshift) | (sets << sshift)); SCB->DCISW = sw; } while(tmpways--); } while(sets--); __DSB(); __ISB(); #endif } /** \brief Clean D-Cache The function cleans D-Cache */ __STATIC_INLINE void SCB_CleanDCache (void) { #if (__DCACHE_PRESENT == 1) uint32_t ccsidr, sshift, wshift, sw; uint32_t sets, ways; SCB->CSSELR = (0UL << 1) | 0UL; // Level 1 data cache ccsidr = SCB->CCSIDR; sets = (uint32_t)(CCSIDR_SETS(ccsidr)); sshift = (uint32_t)(CCSIDR_LSSHIFT(ccsidr) + 4UL); ways = (uint32_t)(CCSIDR_WAYS(ccsidr)); wshift = (uint32_t)((uint32_t)__CLZ(ways) & 0x1FUL); __DSB(); do { // clean D-Cache uint32_t tmpways = ways; do { sw = ((tmpways << wshift) | (sets << sshift)); SCB->DCCSW = sw; } while(tmpways--); } while(sets--); __DSB(); __ISB(); #endif } /** \brief Clean & Invalidate D-Cache The function cleans and Invalidates D-Cache */ __STATIC_INLINE void SCB_CleanInvalidateDCache (void) { #if (__DCACHE_PRESENT == 1) uint32_t ccsidr, sshift, wshift, sw; uint32_t sets, ways; SCB->CSSELR = (0UL << 1) | 0UL; // Level 1 data cache ccsidr = SCB->CCSIDR; sets = (uint32_t)(CCSIDR_SETS(ccsidr)); sshift = (uint32_t)(CCSIDR_LSSHIFT(ccsidr) + 4UL); ways = (uint32_t)(CCSIDR_WAYS(ccsidr)); wshift = (uint32_t)((uint32_t)__CLZ(ways) & 0x1FUL); __DSB(); do { // clean & invalidate D-Cache uint32_t tmpways = ways; do { sw = ((tmpways << wshift) | (sets << sshift)); SCB->DCCISW = sw; } while(tmpways--); } while(sets--); __DSB(); __ISB(); #endif } /** \fn void SCB_InvalidateDCache_by_Addr(volatile uint32_t *addr, int32_t dsize) \brief D-Cache Invalidate by address \param[in] addr address (aligned to 32-byte boundary) \param[in] dsize size of memory block (in number of bytes) */ __STATIC_INLINE void SCB_InvalidateDCache_by_Addr (uint32_t *addr, int32_t dsize) { #if (__DCACHE_PRESENT == 1) int32_t op_size = dsize; uint32_t op_addr = (uint32_t)addr; uint32_t linesize = 32UL; // in Cortex-M7 size of cache line is fixed to 8 words (32 bytes) __DSB(); while (op_size > 0) { SCB->DCIMVAC = op_addr; op_addr += linesize; op_size -= (int32_t)linesize; } __DSB(); __ISB(); #endif } /** \fn void SCB_CleanDCache_by_Addr(volatile uint32_t *addr, int32_t dsize) \brief D-Cache Clean by address \param[in] addr address (aligned to 32-byte boundary) \param[in] dsize size of memory block (in number of bytes) */ __STATIC_INLINE void SCB_CleanDCache_by_Addr (uint32_t *addr, int32_t dsize) { #if (__DCACHE_PRESENT == 1) int32_t op_size = dsize; uint32_t op_addr = (uint32_t) addr; uint32_t linesize = 32UL; // in Cortex-M7 size of cache line is fixed to 8 words (32 bytes) __DSB(); while (op_size > 0) { SCB->DCCMVAC = op_addr; op_addr += linesize; op_size -= (int32_t)linesize; } __DSB(); __ISB(); #endif } /** \fn void SCB_CleanInvalidateDCache_by_Addr(volatile uint32_t *addr, int32_t dsize) \brief D-Cache Clean and Invalidate by address \param[in] addr address (aligned to 32-byte boundary) \param[in] dsize size of memory block (in number of bytes) */ __STATIC_INLINE void SCB_CleanInvalidateDCache_by_Addr (uint32_t *addr, int32_t dsize) { #if (__DCACHE_PRESENT == 1) int32_t op_size = dsize; uint32_t op_addr = (uint32_t) addr; uint32_t linesize = 32UL; // in Cortex-M7 size of cache line is fixed to 8 words (32 bytes) __DSB(); while (op_size > 0) { SCB->DCCIMVAC = op_addr; op_addr += linesize; op_size -= (int32_t)linesize; } __DSB(); __ISB(); #endif } /*@} end of CMSIS_Core_CacheFunctions */ /* ################################## SysTick function ############################################ */ /** \ingroup CMSIS_Core_FunctionInterface \defgroup CMSIS_Core_SysTickFunctions SysTick Functions \brief Functions that configure the System. @{ */ #if (__Vendor_SysTickConfig == 0) /** \brief System Tick Configuration The function initializes the System Timer and its interrupt, and starts the System Tick Timer. Counter is in free running mode to generate periodic interrupts. \param [in] ticks Number of ticks between two interrupts. \return 0 Function succeeded. \return 1 Function failed. \note When the variable __Vendor_SysTickConfig is set to 1, then the function SysTick_Config is not included. In this case, the file device.h must contain a vendor-specific implementation of this function. */ __STATIC_INLINE uint32_t SysTick_Config(uint32_t ticks) { if ((ticks - 1UL) > SysTick_LOAD_RELOAD_Msk) { return (1UL); } /* Reload value impossible */ SysTick->LOAD = (uint32_t)(ticks - 1UL); /* set reload register */ NVIC_SetPriority (SysTick_IRQn, (1UL << __NVIC_PRIO_BITS) - 1UL); /* set Priority for Systick Interrupt */ SysTick->VAL = 0UL; /* Load the SysTick Counter Value */ SysTick->CTRL = SysTick_CTRL_CLKSOURCE_Msk | SysTick_CTRL_TICKINT_Msk | SysTick_CTRL_ENABLE_Msk; /* Enable SysTick IRQ and SysTick Timer */ return (0UL); /* Function successful */ } #endif /*@} end of CMSIS_Core_SysTickFunctions */ /* ##################################### Debug In/Output function ########################################### */ /** \ingroup CMSIS_Core_FunctionInterface \defgroup CMSIS_core_DebugFunctions ITM Functions \brief Functions that access the ITM debug interface. @{ */ extern volatile int32_t ITM_RxBuffer; /*!< External variable to receive characters. */ #define ITM_RXBUFFER_EMPTY 0x5AA55AA5 /*!< Value identifying \ref ITM_RxBuffer is ready for next character. */ /** \brief ITM Send Character The function transmits a character via the ITM channel 0, and \li Just returns when no debugger is connected that has booked the output. \li Is blocking when a debugger is connected, but the previous character sent has not been transmitted. \param [in] ch Character to transmit. \returns Character to transmit. */ __STATIC_INLINE uint32_t ITM_SendChar (uint32_t ch) { if (((ITM->TCR & ITM_TCR_ITMENA_Msk) != 0UL) && /* ITM enabled */ ((ITM->TER & 1UL ) != 0UL) ) /* ITM Port #0 enabled */ { while (ITM->PORT[0].u32 == 0UL) { __NOP(); } ITM->PORT[0].u8 = (uint8_t)ch; } return (ch); } /** \brief ITM Receive Character The function inputs a character via the external variable \ref ITM_RxBuffer. \return Received character. \return -1 No character pending. */ __STATIC_INLINE int32_t ITM_ReceiveChar (void) { int32_t ch = -1; /* no character available */ if (ITM_RxBuffer != ITM_RXBUFFER_EMPTY) { ch = ITM_RxBuffer; ITM_RxBuffer = ITM_RXBUFFER_EMPTY; /* ready for next character */ } return (ch); } /** \brief ITM Check Character The function checks whether a character is pending for reading in the variable \ref ITM_RxBuffer. \return 0 No character available. \return 1 Character available. */ __STATIC_INLINE int32_t ITM_CheckChar (void) { if (ITM_RxBuffer == ITM_RXBUFFER_EMPTY) { return (0); /* no character available */ } else { return (1); /* character available */ } } /*@} end of CMSIS_core_DebugFunctions */ #ifdef __cplusplus } #endif #endif /* __CORE_CM7_H_DEPENDANT */ #endif /* __CMSIS_GENERIC */ ================================================ FILE: Zelig/mbed/TARGET_K64F/core_cmFunc.h ================================================ /**************************************************************************//** * @file core_cmFunc.h * @brief CMSIS Cortex-M Core Function Access Header File * @version V3.20 * @date 25. February 2013 * * @note * ******************************************************************************/ /* Copyright (c) 2009 - 2013 ARM LIMITED All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: - Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. - Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. - Neither the name of ARM 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 COPYRIGHT HOLDERS AND 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. ---------------------------------------------------------------------------*/ #ifndef __CORE_CMFUNC_H #define __CORE_CMFUNC_H /* ########################### Core Function Access ########################### */ /** \ingroup CMSIS_Core_FunctionInterface \defgroup CMSIS_Core_RegAccFunctions CMSIS Core Register Access Functions @{ */ #if defined ( __CC_ARM ) /*------------------RealView Compiler -----------------*/ /* ARM armcc specific functions */ #if (__ARMCC_VERSION < 400677) #error "Please use ARM Compiler Toolchain V4.0.677 or later!" #endif /* intrinsic void __enable_irq(); */ /* intrinsic void __disable_irq(); */ /** \brief Get Control Register This function returns the content of the Control Register. \return Control Register value */ __STATIC_INLINE uint32_t __get_CONTROL(void) { register uint32_t __regControl __ASM("control"); return(__regControl); } /** \brief Set Control Register This function writes the given value to the Control Register. \param [in] control Control Register value to set */ __STATIC_INLINE void __set_CONTROL(uint32_t control) { register uint32_t __regControl __ASM("control"); __regControl = control; } /** \brief Get IPSR Register This function returns the content of the IPSR Register. \return IPSR Register value */ __STATIC_INLINE uint32_t __get_IPSR(void) { register uint32_t __regIPSR __ASM("ipsr"); return(__regIPSR); } /** \brief Get APSR Register This function returns the content of the APSR Register. \return APSR Register value */ __STATIC_INLINE uint32_t __get_APSR(void) { register uint32_t __regAPSR __ASM("apsr"); return(__regAPSR); } /** \brief Get xPSR Register This function returns the content of the xPSR Register. \return xPSR Register value */ __STATIC_INLINE uint32_t __get_xPSR(void) { register uint32_t __regXPSR __ASM("xpsr"); return(__regXPSR); } /** \brief Get Process Stack Pointer This function returns the current value of the Process Stack Pointer (PSP). \return PSP Register value */ __STATIC_INLINE uint32_t __get_PSP(void) { register uint32_t __regProcessStackPointer __ASM("psp"); return(__regProcessStackPointer); } /** \brief Set Process Stack Pointer This function assigns the given value to the Process Stack Pointer (PSP). \param [in] topOfProcStack Process Stack Pointer value to set */ __STATIC_INLINE void __set_PSP(uint32_t topOfProcStack) { register uint32_t __regProcessStackPointer __ASM("psp"); __regProcessStackPointer = topOfProcStack; } /** \brief Get Main Stack Pointer This function returns the current value of the Main Stack Pointer (MSP). \return MSP Register value */ __STATIC_INLINE uint32_t __get_MSP(void) { register uint32_t __regMainStackPointer __ASM("msp"); return(__regMainStackPointer); } /** \brief Set Main Stack Pointer This function assigns the given value to the Main Stack Pointer (MSP). \param [in] topOfMainStack Main Stack Pointer value to set */ __STATIC_INLINE void __set_MSP(uint32_t topOfMainStack) { register uint32_t __regMainStackPointer __ASM("msp"); __regMainStackPointer = topOfMainStack; } /** \brief Get Priority Mask This function returns the current state of the priority mask bit from the Priority Mask Register. \return Priority Mask value */ __STATIC_INLINE uint32_t __get_PRIMASK(void) { register uint32_t __regPriMask __ASM("primask"); return(__regPriMask); } /** \brief Set Priority Mask This function assigns the given value to the Priority Mask Register. \param [in] priMask Priority Mask */ __STATIC_INLINE void __set_PRIMASK(uint32_t priMask) { register uint32_t __regPriMask __ASM("primask"); __regPriMask = (priMask); } #if (__CORTEX_M >= 0x03) /** \brief Enable FIQ This function enables FIQ interrupts by clearing the F-bit in the CPSR. Can only be executed in Privileged modes. */ #define __enable_fault_irq __enable_fiq /** \brief Disable FIQ This function disables FIQ interrupts by setting the F-bit in the CPSR. Can only be executed in Privileged modes. */ #define __disable_fault_irq __disable_fiq /** \brief Get Base Priority This function returns the current value of the Base Priority register. \return Base Priority register value */ __STATIC_INLINE uint32_t __get_BASEPRI(void) { register uint32_t __regBasePri __ASM("basepri"); return(__regBasePri); } /** \brief Set Base Priority This function assigns the given value to the Base Priority register. \param [in] basePri Base Priority value to set */ __STATIC_INLINE void __set_BASEPRI(uint32_t basePri) { register uint32_t __regBasePri __ASM("basepri"); __regBasePri = (basePri & 0xff); } /** \brief Get Fault Mask This function returns the current value of the Fault Mask register. \return Fault Mask register value */ __STATIC_INLINE uint32_t __get_FAULTMASK(void) { register uint32_t __regFaultMask __ASM("faultmask"); return(__regFaultMask); } /** \brief Set Fault Mask This function assigns the given value to the Fault Mask register. \param [in] faultMask Fault Mask value to set */ __STATIC_INLINE void __set_FAULTMASK(uint32_t faultMask) { register uint32_t __regFaultMask __ASM("faultmask"); __regFaultMask = (faultMask & (uint32_t)1); } #endif /* (__CORTEX_M >= 0x03) */ #if (__CORTEX_M == 0x04) /** \brief Get FPSCR This function returns the current value of the Floating Point Status/Control register. \return Floating Point Status/Control register value */ __STATIC_INLINE uint32_t __get_FPSCR(void) { #if (__FPU_PRESENT == 1) && (__FPU_USED == 1) register uint32_t __regfpscr __ASM("fpscr"); return(__regfpscr); #else return(0); #endif } /** \brief Set FPSCR This function assigns the given value to the Floating Point Status/Control register. \param [in] fpscr Floating Point Status/Control value to set */ __STATIC_INLINE void __set_FPSCR(uint32_t fpscr) { #if (__FPU_PRESENT == 1) && (__FPU_USED == 1) register uint32_t __regfpscr __ASM("fpscr"); __regfpscr = (fpscr); #endif } #endif /* (__CORTEX_M == 0x04) */ #elif defined ( __ICCARM__ ) /*------------------ ICC Compiler -------------------*/ /* IAR iccarm specific functions */ #include #elif defined ( __TMS470__ ) /*---------------- TI CCS Compiler ------------------*/ /* TI CCS specific functions */ #include #elif defined ( __GNUC__ ) /*------------------ GNU Compiler ---------------------*/ /* GNU gcc specific functions */ /** \brief Enable IRQ Interrupts This function enables IRQ interrupts by clearing the I-bit in the CPSR. Can only be executed in Privileged modes. */ __attribute__( ( always_inline ) ) __STATIC_INLINE void __enable_irq(void) { __ASM volatile ("cpsie i" : : : "memory"); } /** \brief Disable IRQ Interrupts This function disables IRQ interrupts by setting the I-bit in the CPSR. Can only be executed in Privileged modes. */ __attribute__( ( always_inline ) ) __STATIC_INLINE void __disable_irq(void) { __ASM volatile ("cpsid i" : : : "memory"); } /** \brief Get Control Register This function returns the content of the Control Register. \return Control Register value */ __attribute__( ( always_inline ) ) __STATIC_INLINE uint32_t __get_CONTROL(void) { uint32_t result; __ASM volatile ("MRS %0, control" : "=r" (result) ); return(result); } /** \brief Set Control Register This function writes the given value to the Control Register. \param [in] control Control Register value to set */ __attribute__( ( always_inline ) ) __STATIC_INLINE void __set_CONTROL(uint32_t control) { __ASM volatile ("MSR control, %0" : : "r" (control) : "memory"); } /** \brief Get IPSR Register This function returns the content of the IPSR Register. \return IPSR Register value */ __attribute__( ( always_inline ) ) __STATIC_INLINE uint32_t __get_IPSR(void) { uint32_t result; __ASM volatile ("MRS %0, ipsr" : "=r" (result) ); return(result); } /** \brief Get APSR Register This function returns the content of the APSR Register. \return APSR Register value */ __attribute__( ( always_inline ) ) __STATIC_INLINE uint32_t __get_APSR(void) { uint32_t result; __ASM volatile ("MRS %0, apsr" : "=r" (result) ); return(result); } /** \brief Get xPSR Register This function returns the content of the xPSR Register. \return xPSR Register value */ __attribute__( ( always_inline ) ) __STATIC_INLINE uint32_t __get_xPSR(void) { uint32_t result; __ASM volatile ("MRS %0, xpsr" : "=r" (result) ); return(result); } /** \brief Get Process Stack Pointer This function returns the current value of the Process Stack Pointer (PSP). \return PSP Register value */ __attribute__( ( always_inline ) ) __STATIC_INLINE uint32_t __get_PSP(void) { register uint32_t result; __ASM volatile ("MRS %0, psp\n" : "=r" (result) ); return(result); } /** \brief Set Process Stack Pointer This function assigns the given value to the Process Stack Pointer (PSP). \param [in] topOfProcStack Process Stack Pointer value to set */ __attribute__( ( always_inline ) ) __STATIC_INLINE void __set_PSP(uint32_t topOfProcStack) { __ASM volatile ("MSR psp, %0\n" : : "r" (topOfProcStack) : "sp"); } /** \brief Get Main Stack Pointer This function returns the current value of the Main Stack Pointer (MSP). \return MSP Register value */ __attribute__( ( always_inline ) ) __STATIC_INLINE uint32_t __get_MSP(void) { register uint32_t result; __ASM volatile ("MRS %0, msp\n" : "=r" (result) ); return(result); } /** \brief Set Main Stack Pointer This function assigns the given value to the Main Stack Pointer (MSP). \param [in] topOfMainStack Main Stack Pointer value to set */ __attribute__( ( always_inline ) ) __STATIC_INLINE void __set_MSP(uint32_t topOfMainStack) { __ASM volatile ("MSR msp, %0\n" : : "r" (topOfMainStack) : "sp"); } /** \brief Get Priority Mask This function returns the current state of the priority mask bit from the Priority Mask Register. \return Priority Mask value */ __attribute__( ( always_inline ) ) __STATIC_INLINE uint32_t __get_PRIMASK(void) { uint32_t result; __ASM volatile ("MRS %0, primask" : "=r" (result) ); return(result); } /** \brief Set Priority Mask This function assigns the given value to the Priority Mask Register. \param [in] priMask Priority Mask */ __attribute__( ( always_inline ) ) __STATIC_INLINE void __set_PRIMASK(uint32_t priMask) { __ASM volatile ("MSR primask, %0" : : "r" (priMask) : "memory"); } #if (__CORTEX_M >= 0x03) /** \brief Enable FIQ This function enables FIQ interrupts by clearing the F-bit in the CPSR. Can only be executed in Privileged modes. */ __attribute__( ( always_inline ) ) __STATIC_INLINE void __enable_fault_irq(void) { __ASM volatile ("cpsie f" : : : "memory"); } /** \brief Disable FIQ This function disables FIQ interrupts by setting the F-bit in the CPSR. Can only be executed in Privileged modes. */ __attribute__( ( always_inline ) ) __STATIC_INLINE void __disable_fault_irq(void) { __ASM volatile ("cpsid f" : : : "memory"); } /** \brief Get Base Priority This function returns the current value of the Base Priority register. \return Base Priority register value */ __attribute__( ( always_inline ) ) __STATIC_INLINE uint32_t __get_BASEPRI(void) { uint32_t result; __ASM volatile ("MRS %0, basepri_max" : "=r" (result) ); return(result); } /** \brief Set Base Priority This function assigns the given value to the Base Priority register. \param [in] basePri Base Priority value to set */ __attribute__( ( always_inline ) ) __STATIC_INLINE void __set_BASEPRI(uint32_t value) { __ASM volatile ("MSR basepri, %0" : : "r" (value) : "memory"); } /** \brief Get Fault Mask This function returns the current value of the Fault Mask register. \return Fault Mask register value */ __attribute__( ( always_inline ) ) __STATIC_INLINE uint32_t __get_FAULTMASK(void) { uint32_t result; __ASM volatile ("MRS %0, faultmask" : "=r" (result) ); return(result); } /** \brief Set Fault Mask This function assigns the given value to the Fault Mask register. \param [in] faultMask Fault Mask value to set */ __attribute__( ( always_inline ) ) __STATIC_INLINE void __set_FAULTMASK(uint32_t faultMask) { __ASM volatile ("MSR faultmask, %0" : : "r" (faultMask) : "memory"); } #endif /* (__CORTEX_M >= 0x03) */ #if (__CORTEX_M == 0x04) /** \brief Get FPSCR This function returns the current value of the Floating Point Status/Control register. \return Floating Point Status/Control register value */ __attribute__( ( always_inline ) ) __STATIC_INLINE uint32_t __get_FPSCR(void) { #if (__FPU_PRESENT == 1) && (__FPU_USED == 1) uint32_t result; /* Empty asm statement works as a scheduling barrier */ __ASM volatile (""); __ASM volatile ("VMRS %0, fpscr" : "=r" (result) ); __ASM volatile (""); return(result); #else return(0); #endif } /** \brief Set FPSCR This function assigns the given value to the Floating Point Status/Control register. \param [in] fpscr Floating Point Status/Control value to set */ __attribute__( ( always_inline ) ) __STATIC_INLINE void __set_FPSCR(uint32_t fpscr) { #if (__FPU_PRESENT == 1) && (__FPU_USED == 1) /* Empty asm statement works as a scheduling barrier */ __ASM volatile (""); __ASM volatile ("VMSR fpscr, %0" : : "r" (fpscr) : "vfpcc"); __ASM volatile (""); #endif } #endif /* (__CORTEX_M == 0x04) */ #elif defined ( __TASKING__ ) /*------------------ TASKING Compiler --------------*/ /* TASKING carm specific functions */ /* * The CMSIS functions have been implemented as intrinsics in the compiler. * Please use "carm -?i" to get an up to date list of all instrinsics, * Including the CMSIS ones. */ #endif /*@} end of CMSIS_Core_RegAccFunctions */ #endif /* __CORE_CMFUNC_H */ ================================================ FILE: Zelig/mbed/TARGET_K64F/core_cmInstr.h ================================================ /**************************************************************************//** * @file core_cmInstr.h * @brief CMSIS Cortex-M Core Instruction Access Header File * @version V3.20 * @date 05. March 2013 * * @note * ******************************************************************************/ /* Copyright (c) 2009 - 2013 ARM LIMITED All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: - Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. - Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. - Neither the name of ARM 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 COPYRIGHT HOLDERS AND 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. ---------------------------------------------------------------------------*/ #ifndef __CORE_CMINSTR_H #define __CORE_CMINSTR_H /* ########################## Core Instruction Access ######################### */ /** \defgroup CMSIS_Core_InstructionInterface CMSIS Core Instruction Interface Access to dedicated instructions @{ */ #if defined ( __CC_ARM ) /*------------------RealView Compiler -----------------*/ /* ARM armcc specific functions */ #if (__ARMCC_VERSION < 400677) #error "Please use ARM Compiler Toolchain V4.0.677 or later!" #endif /** \brief No Operation No Operation does nothing. This instruction can be used for code alignment purposes. */ #define __NOP __nop /** \brief Wait For Interrupt Wait For Interrupt is a hint instruction that suspends execution until one of a number of events occurs. */ #define __WFI __wfi /** \brief Wait For Event Wait For Event is a hint instruction that permits the processor to enter a low-power state until one of a number of events occurs. */ #define __WFE __wfe /** \brief Send Event Send Event is a hint instruction. It causes an event to be signaled to the CPU. */ #define __SEV __sev /** \brief Instruction Synchronization Barrier Instruction Synchronization Barrier flushes the pipeline in the processor, so that all instructions following the ISB are fetched from cache or memory, after the instruction has been completed. */ #define __ISB() __isb(0xF) /** \brief Data Synchronization Barrier This function acts as a special kind of Data Memory Barrier. It completes when all explicit memory accesses before this instruction complete. */ #define __DSB() __dsb(0xF) /** \brief Data Memory Barrier This function ensures the apparent order of the explicit memory operations before and after the instruction, without ensuring their completion. */ #define __DMB() __dmb(0xF) /** \brief Reverse byte order (32 bit) This function reverses the byte order in integer value. \param [in] value Value to reverse \return Reversed value */ #define __REV __rev /** \brief Reverse byte order (16 bit) This function reverses the byte order in two unsigned short values. \param [in] value Value to reverse \return Reversed value */ #ifndef __NO_EMBEDDED_ASM __attribute__((section(".rev16_text"))) __STATIC_INLINE __ASM uint32_t __REV16(uint32_t value) { rev16 r0, r0 bx lr } #endif /** \brief Reverse byte order in signed short value This function reverses the byte order in a signed short value with sign extension to integer. \param [in] value Value to reverse \return Reversed value */ #ifndef __NO_EMBEDDED_ASM __attribute__((section(".revsh_text"))) __STATIC_INLINE __ASM int32_t __REVSH(int32_t value) { revsh r0, r0 bx lr } #endif /** \brief Rotate Right in unsigned value (32 bit) This function Rotate Right (immediate) provides the value of the contents of a register rotated by a variable number of bits. \param [in] value Value to rotate \param [in] value Number of Bits to rotate \return Rotated value */ #define __ROR __ror /** \brief Breakpoint This function causes the processor to enter Debug state. Debug tools can use this to investigate system state when the instruction at a particular address is reached. \param [in] value is ignored by the processor. If required, a debugger can use it to store additional information about the breakpoint. */ #define __BKPT(value) __breakpoint(value) #if (__CORTEX_M >= 0x03) /** \brief Reverse bit order of value This function reverses the bit order of the given value. \param [in] value Value to reverse \return Reversed value */ #define __RBIT __rbit /** \brief LDR Exclusive (8 bit) This function performs a exclusive LDR command for 8 bit value. \param [in] ptr Pointer to data \return value of type uint8_t at (*ptr) */ #define __LDREXB(ptr) ((uint8_t ) __ldrex(ptr)) /** \brief LDR Exclusive (16 bit) This function performs a exclusive LDR command for 16 bit values. \param [in] ptr Pointer to data \return value of type uint16_t at (*ptr) */ #define __LDREXH(ptr) ((uint16_t) __ldrex(ptr)) /** \brief LDR Exclusive (32 bit) This function performs a exclusive LDR command for 32 bit values. \param [in] ptr Pointer to data \return value of type uint32_t at (*ptr) */ #define __LDREXW(ptr) ((uint32_t ) __ldrex(ptr)) /** \brief STR Exclusive (8 bit) This function performs a exclusive STR command for 8 bit values. \param [in] value Value to store \param [in] ptr Pointer to location \return 0 Function succeeded \return 1 Function failed */ #define __STREXB(value, ptr) __strex(value, ptr) /** \brief STR Exclusive (16 bit) This function performs a exclusive STR command for 16 bit values. \param [in] value Value to store \param [in] ptr Pointer to location \return 0 Function succeeded \return 1 Function failed */ #define __STREXH(value, ptr) __strex(value, ptr) /** \brief STR Exclusive (32 bit) This function performs a exclusive STR command for 32 bit values. \param [in] value Value to store \param [in] ptr Pointer to location \return 0 Function succeeded \return 1 Function failed */ #define __STREXW(value, ptr) __strex(value, ptr) /** \brief Remove the exclusive lock This function removes the exclusive lock which is created by LDREX. */ #define __CLREX __clrex /** \brief Signed Saturate This function saturates a signed value. \param [in] value Value to be saturated \param [in] sat Bit position to saturate to (1..32) \return Saturated value */ #define __SSAT __ssat /** \brief Unsigned Saturate This function saturates an unsigned value. \param [in] value Value to be saturated \param [in] sat Bit position to saturate to (0..31) \return Saturated value */ #define __USAT __usat /** \brief Count leading zeros This function counts the number of leading zeros of a data value. \param [in] value Value to count the leading zeros \return number of leading zeros in value */ #define __CLZ __clz #endif /* (__CORTEX_M >= 0x03) */ #elif defined ( __ICCARM__ ) /*------------------ ICC Compiler -------------------*/ /* IAR iccarm specific functions */ #include #elif defined ( __TMS470__ ) /*---------------- TI CCS Compiler ------------------*/ /* TI CCS specific functions */ #include #elif defined ( __GNUC__ ) /*------------------ GNU Compiler ---------------------*/ /* GNU gcc specific functions */ /* Define macros for porting to both thumb1 and thumb2. * For thumb1, use low register (r0-r7), specified by constrant "l" * Otherwise, use general registers, specified by constrant "r" */ #if defined (__thumb__) && !defined (__thumb2__) #define __CMSIS_GCC_OUT_REG(r) "=l" (r) #define __CMSIS_GCC_USE_REG(r) "l" (r) #else #define __CMSIS_GCC_OUT_REG(r) "=r" (r) #define __CMSIS_GCC_USE_REG(r) "r" (r) #endif /** \brief No Operation No Operation does nothing. This instruction can be used for code alignment purposes. */ __attribute__( ( always_inline ) ) __STATIC_INLINE void __NOP(void) { __ASM volatile ("nop"); } /** \brief Wait For Interrupt Wait For Interrupt is a hint instruction that suspends execution until one of a number of events occurs. */ __attribute__( ( always_inline ) ) __STATIC_INLINE void __WFI(void) { __ASM volatile ("wfi"); } /** \brief Wait For Event Wait For Event is a hint instruction that permits the processor to enter a low-power state until one of a number of events occurs. */ __attribute__( ( always_inline ) ) __STATIC_INLINE void __WFE(void) { __ASM volatile ("wfe"); } /** \brief Send Event Send Event is a hint instruction. It causes an event to be signaled to the CPU. */ __attribute__( ( always_inline ) ) __STATIC_INLINE void __SEV(void) { __ASM volatile ("sev"); } /** \brief Instruction Synchronization Barrier Instruction Synchronization Barrier flushes the pipeline in the processor, so that all instructions following the ISB are fetched from cache or memory, after the instruction has been completed. */ __attribute__( ( always_inline ) ) __STATIC_INLINE void __ISB(void) { __ASM volatile ("isb"); } /** \brief Data Synchronization Barrier This function acts as a special kind of Data Memory Barrier. It completes when all explicit memory accesses before this instruction complete. */ __attribute__( ( always_inline ) ) __STATIC_INLINE void __DSB(void) { __ASM volatile ("dsb"); } /** \brief Data Memory Barrier This function ensures the apparent order of the explicit memory operations before and after the instruction, without ensuring their completion. */ __attribute__( ( always_inline ) ) __STATIC_INLINE void __DMB(void) { __ASM volatile ("dmb"); } /** \brief Reverse byte order (32 bit) This function reverses the byte order in integer value. \param [in] value Value to reverse \return Reversed value */ __attribute__( ( always_inline ) ) __STATIC_INLINE uint32_t __REV(uint32_t value) { #if (__GNUC__ > 4) || (__GNUC__ == 4 && __GNUC_MINOR__ >= 5) return __builtin_bswap32(value); #else uint32_t result; __ASM volatile ("rev %0, %1" : __CMSIS_GCC_OUT_REG (result) : __CMSIS_GCC_USE_REG (value) ); return(result); #endif } /** \brief Reverse byte order (16 bit) This function reverses the byte order in two unsigned short values. \param [in] value Value to reverse \return Reversed value */ __attribute__( ( always_inline ) ) __STATIC_INLINE uint32_t __REV16(uint32_t value) { uint32_t result; __ASM volatile ("rev16 %0, %1" : __CMSIS_GCC_OUT_REG (result) : __CMSIS_GCC_USE_REG (value) ); return(result); } /** \brief Reverse byte order in signed short value This function reverses the byte order in a signed short value with sign extension to integer. \param [in] value Value to reverse \return Reversed value */ __attribute__( ( always_inline ) ) __STATIC_INLINE int32_t __REVSH(int32_t value) { #if (__GNUC__ > 4) || (__GNUC__ == 4 && __GNUC_MINOR__ >= 8) return (short)__builtin_bswap16(value); #else uint32_t result; __ASM volatile ("revsh %0, %1" : __CMSIS_GCC_OUT_REG (result) : __CMSIS_GCC_USE_REG (value) ); return(result); #endif } /** \brief Rotate Right in unsigned value (32 bit) This function Rotate Right (immediate) provides the value of the contents of a register rotated by a variable number of bits. \param [in] value Value to rotate \param [in] value Number of Bits to rotate \return Rotated value */ __attribute__( ( always_inline ) ) __STATIC_INLINE uint32_t __ROR(uint32_t op1, uint32_t op2) { return (op1 >> op2) | (op1 << (32 - op2)); } /** \brief Breakpoint This function causes the processor to enter Debug state. Debug tools can use this to investigate system state when the instruction at a particular address is reached. \param [in] value is ignored by the processor. If required, a debugger can use it to store additional information about the breakpoint. */ #define __BKPT(value) __ASM volatile ("bkpt "#value) #if (__CORTEX_M >= 0x03) /** \brief Reverse bit order of value This function reverses the bit order of the given value. \param [in] value Value to reverse \return Reversed value */ __attribute__( ( always_inline ) ) __STATIC_INLINE uint32_t __RBIT(uint32_t value) { uint32_t result; __ASM volatile ("rbit %0, %1" : "=r" (result) : "r" (value) ); return(result); } /** \brief LDR Exclusive (8 bit) This function performs a exclusive LDR command for 8 bit value. \param [in] ptr Pointer to data \return value of type uint8_t at (*ptr) */ __attribute__( ( always_inline ) ) __STATIC_INLINE uint8_t __LDREXB(volatile uint8_t *addr) { uint32_t result; #if (__GNUC__ > 4) || (__GNUC__ == 4 && __GNUC_MINOR__ >= 8) __ASM volatile ("ldrexb %0, %1" : "=r" (result) : "Q" (*addr) ); #else /* Prior to GCC 4.8, "Q" will be expanded to [rx, #0] which is not accepted by assembler. So has to use following less efficient pattern. */ __ASM volatile ("ldrexb %0, [%1]" : "=r" (result) : "r" (addr) : "memory" ); #endif return(result); } /** \brief LDR Exclusive (16 bit) This function performs a exclusive LDR command for 16 bit values. \param [in] ptr Pointer to data \return value of type uint16_t at (*ptr) */ __attribute__( ( always_inline ) ) __STATIC_INLINE uint16_t __LDREXH(volatile uint16_t *addr) { uint32_t result; #if (__GNUC__ > 4) || (__GNUC__ == 4 && __GNUC_MINOR__ >= 8) __ASM volatile ("ldrexh %0, %1" : "=r" (result) : "Q" (*addr) ); #else /* Prior to GCC 4.8, "Q" will be expanded to [rx, #0] which is not accepted by assembler. So has to use following less efficient pattern. */ __ASM volatile ("ldrexh %0, [%1]" : "=r" (result) : "r" (addr) : "memory" ); #endif return(result); } /** \brief LDR Exclusive (32 bit) This function performs a exclusive LDR command for 32 bit values. \param [in] ptr Pointer to data \return value of type uint32_t at (*ptr) */ __attribute__( ( always_inline ) ) __STATIC_INLINE uint32_t __LDREXW(volatile uint32_t *addr) { uint32_t result; __ASM volatile ("ldrex %0, %1" : "=r" (result) : "Q" (*addr) ); return(result); } /** \brief STR Exclusive (8 bit) This function performs a exclusive STR command for 8 bit values. \param [in] value Value to store \param [in] ptr Pointer to location \return 0 Function succeeded \return 1 Function failed */ __attribute__( ( always_inline ) ) __STATIC_INLINE uint32_t __STREXB(uint8_t value, volatile uint8_t *addr) { uint32_t result; __ASM volatile ("strexb %0, %2, %1" : "=&r" (result), "=Q" (*addr) : "r" (value) ); return(result); } /** \brief STR Exclusive (16 bit) This function performs a exclusive STR command for 16 bit values. \param [in] value Value to store \param [in] ptr Pointer to location \return 0 Function succeeded \return 1 Function failed */ __attribute__( ( always_inline ) ) __STATIC_INLINE uint32_t __STREXH(uint16_t value, volatile uint16_t *addr) { uint32_t result; __ASM volatile ("strexh %0, %2, %1" : "=&r" (result), "=Q" (*addr) : "r" (value) ); return(result); } /** \brief STR Exclusive (32 bit) This function performs a exclusive STR command for 32 bit values. \param [in] value Value to store \param [in] ptr Pointer to location \return 0 Function succeeded \return 1 Function failed */ __attribute__( ( always_inline ) ) __STATIC_INLINE uint32_t __STREXW(uint32_t value, volatile uint32_t *addr) { uint32_t result; __ASM volatile ("strex %0, %2, %1" : "=&r" (result), "=Q" (*addr) : "r" (value) ); return(result); } /** \brief Remove the exclusive lock This function removes the exclusive lock which is created by LDREX. */ __attribute__( ( always_inline ) ) __STATIC_INLINE void __CLREX(void) { __ASM volatile ("clrex" ::: "memory"); } /** \brief Signed Saturate This function saturates a signed value. \param [in] value Value to be saturated \param [in] sat Bit position to saturate to (1..32) \return Saturated value */ #define __SSAT(ARG1,ARG2) \ ({ \ uint32_t __RES, __ARG1 = (ARG1); \ __ASM ("ssat %0, %1, %2" : "=r" (__RES) : "I" (ARG2), "r" (__ARG1) ); \ __RES; \ }) /** \brief Unsigned Saturate This function saturates an unsigned value. \param [in] value Value to be saturated \param [in] sat Bit position to saturate to (0..31) \return Saturated value */ #define __USAT(ARG1,ARG2) \ ({ \ uint32_t __RES, __ARG1 = (ARG1); \ __ASM ("usat %0, %1, %2" : "=r" (__RES) : "I" (ARG2), "r" (__ARG1) ); \ __RES; \ }) /** \brief Count leading zeros This function counts the number of leading zeros of a data value. \param [in] value Value to count the leading zeros \return number of leading zeros in value */ __attribute__( ( always_inline ) ) __STATIC_INLINE uint8_t __CLZ(uint32_t value) { uint32_t result; __ASM volatile ("clz %0, %1" : "=r" (result) : "r" (value) ); return(result); } #endif /* (__CORTEX_M >= 0x03) */ #elif defined ( __TASKING__ ) /*------------------ TASKING Compiler --------------*/ /* TASKING carm specific functions */ /* * The CMSIS functions have been implemented as intrinsics in the compiler. * Please use "carm -?i" to get an up to date list of all intrinsics, * Including the CMSIS ones. */ #endif /*@}*/ /* end of group CMSIS_Core_InstructionInterface */ #endif /* __CORE_CMINSTR_H */ ================================================ FILE: Zelig/mbed/TARGET_K64F/core_cmSimd.h ================================================ /**************************************************************************//** * @file core_cmSimd.h * @brief CMSIS Cortex-M SIMD Header File * @version V4.10 * @date 18. March 2015 * * @note * ******************************************************************************/ /* Copyright (c) 2009 - 2014 ARM LIMITED All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: - Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. - Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. - Neither the name of ARM 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 COPYRIGHT HOLDERS AND 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. ---------------------------------------------------------------------------*/ #if defined ( __ICCARM__ ) #pragma system_include /* treat file as system include file for MISRA check */ #endif #ifndef __CORE_CMSIMD_H #define __CORE_CMSIMD_H #ifdef __cplusplus extern "C" { #endif /******************************************************************************* * Hardware Abstraction Layer ******************************************************************************/ /* ################### Compiler specific Intrinsics ########################### */ /** \defgroup CMSIS_SIMD_intrinsics CMSIS SIMD Intrinsics Access to dedicated SIMD instructions @{ */ #if defined ( __CC_ARM ) /*------------------RealView Compiler -----------------*/ /* ARM armcc specific functions */ #define __SADD8 __sadd8 #define __QADD8 __qadd8 #define __SHADD8 __shadd8 #define __UADD8 __uadd8 #define __UQADD8 __uqadd8 #define __UHADD8 __uhadd8 #define __SSUB8 __ssub8 #define __QSUB8 __qsub8 #define __SHSUB8 __shsub8 #define __USUB8 __usub8 #define __UQSUB8 __uqsub8 #define __UHSUB8 __uhsub8 #define __SADD16 __sadd16 #define __QADD16 __qadd16 #define __SHADD16 __shadd16 #define __UADD16 __uadd16 #define __UQADD16 __uqadd16 #define __UHADD16 __uhadd16 #define __SSUB16 __ssub16 #define __QSUB16 __qsub16 #define __SHSUB16 __shsub16 #define __USUB16 __usub16 #define __UQSUB16 __uqsub16 #define __UHSUB16 __uhsub16 #define __SASX __sasx #define __QASX __qasx #define __SHASX __shasx #define __UASX __uasx #define __UQASX __uqasx #define __UHASX __uhasx #define __SSAX __ssax #define __QSAX __qsax #define __SHSAX __shsax #define __USAX __usax #define __UQSAX __uqsax #define __UHSAX __uhsax #define __USAD8 __usad8 #define __USADA8 __usada8 #define __SSAT16 __ssat16 #define __USAT16 __usat16 #define __UXTB16 __uxtb16 #define __UXTAB16 __uxtab16 #define __SXTB16 __sxtb16 #define __SXTAB16 __sxtab16 #define __SMUAD __smuad #define __SMUADX __smuadx #define __SMLAD __smlad #define __SMLADX __smladx #define __SMLALD __smlald #define __SMLALDX __smlaldx #define __SMUSD __smusd #define __SMUSDX __smusdx #define __SMLSD __smlsd #define __SMLSDX __smlsdx #define __SMLSLD __smlsld #define __SMLSLDX __smlsldx #define __SEL __sel #define __QADD __qadd #define __QSUB __qsub #define __PKHBT(ARG1,ARG2,ARG3) ( ((((uint32_t)(ARG1)) ) & 0x0000FFFFUL) | \ ((((uint32_t)(ARG2)) << (ARG3)) & 0xFFFF0000UL) ) #define __PKHTB(ARG1,ARG2,ARG3) ( ((((uint32_t)(ARG1)) ) & 0xFFFF0000UL) | \ ((((uint32_t)(ARG2)) >> (ARG3)) & 0x0000FFFFUL) ) #define __SMMLA(ARG1,ARG2,ARG3) ( (int32_t)((((int64_t)(ARG1) * (ARG2)) + \ ((int64_t)(ARG3) << 32) ) >> 32)) #elif defined ( __GNUC__ ) /*------------------ GNU Compiler ---------------------*/ /* GNU gcc specific functions */ __attribute__( ( always_inline ) ) __STATIC_INLINE uint32_t __SADD8(uint32_t op1, uint32_t op2) { uint32_t result; __ASM volatile ("sadd8 %0, %1, %2" : "=r" (result) : "r" (op1), "r" (op2) ); return(result); } __attribute__( ( always_inline ) ) __STATIC_INLINE uint32_t __QADD8(uint32_t op1, uint32_t op2) { uint32_t result; __ASM volatile ("qadd8 %0, %1, %2" : "=r" (result) : "r" (op1), "r" (op2) ); return(result); } __attribute__( ( always_inline ) ) __STATIC_INLINE uint32_t __SHADD8(uint32_t op1, uint32_t op2) { uint32_t result; __ASM volatile ("shadd8 %0, %1, %2" : "=r" (result) : "r" (op1), "r" (op2) ); return(result); } __attribute__( ( always_inline ) ) __STATIC_INLINE uint32_t __UADD8(uint32_t op1, uint32_t op2) { uint32_t result; __ASM volatile ("uadd8 %0, %1, %2" : "=r" (result) : "r" (op1), "r" (op2) ); return(result); } __attribute__( ( always_inline ) ) __STATIC_INLINE uint32_t __UQADD8(uint32_t op1, uint32_t op2) { uint32_t result; __ASM volatile ("uqadd8 %0, %1, %2" : "=r" (result) : "r" (op1), "r" (op2) ); return(result); } __attribute__( ( always_inline ) ) __STATIC_INLINE uint32_t __UHADD8(uint32_t op1, uint32_t op2) { uint32_t result; __ASM volatile ("uhadd8 %0, %1, %2" : "=r" (result) : "r" (op1), "r" (op2) ); return(result); } __attribute__( ( always_inline ) ) __STATIC_INLINE uint32_t __SSUB8(uint32_t op1, uint32_t op2) { uint32_t result; __ASM volatile ("ssub8 %0, %1, %2" : "=r" (result) : "r" (op1), "r" (op2) ); return(result); } __attribute__( ( always_inline ) ) __STATIC_INLINE uint32_t __QSUB8(uint32_t op1, uint32_t op2) { uint32_t result; __ASM volatile ("qsub8 %0, %1, %2" : "=r" (result) : "r" (op1), "r" (op2) ); return(result); } __attribute__( ( always_inline ) ) __STATIC_INLINE uint32_t __SHSUB8(uint32_t op1, uint32_t op2) { uint32_t result; __ASM volatile ("shsub8 %0, %1, %2" : "=r" (result) : "r" (op1), "r" (op2) ); return(result); } __attribute__( ( always_inline ) ) __STATIC_INLINE uint32_t __USUB8(uint32_t op1, uint32_t op2) { uint32_t result; __ASM volatile ("usub8 %0, %1, %2" : "=r" (result) : "r" (op1), "r" (op2) ); return(result); } __attribute__( ( always_inline ) ) __STATIC_INLINE uint32_t __UQSUB8(uint32_t op1, uint32_t op2) { uint32_t result; __ASM volatile ("uqsub8 %0, %1, %2" : "=r" (result) : "r" (op1), "r" (op2) ); return(result); } __attribute__( ( always_inline ) ) __STATIC_INLINE uint32_t __UHSUB8(uint32_t op1, uint32_t op2) { uint32_t result; __ASM volatile ("uhsub8 %0, %1, %2" : "=r" (result) : "r" (op1), "r" (op2) ); return(result); } __attribute__( ( always_inline ) ) __STATIC_INLINE uint32_t __SADD16(uint32_t op1, uint32_t op2) { uint32_t result; __ASM volatile ("sadd16 %0, %1, %2" : "=r" (result) : "r" (op1), "r" (op2) ); return(result); } __attribute__( ( always_inline ) ) __STATIC_INLINE uint32_t __QADD16(uint32_t op1, uint32_t op2) { uint32_t result; __ASM volatile ("qadd16 %0, %1, %2" : "=r" (result) : "r" (op1), "r" (op2) ); return(result); } __attribute__( ( always_inline ) ) __STATIC_INLINE uint32_t __SHADD16(uint32_t op1, uint32_t op2) { uint32_t result; __ASM volatile ("shadd16 %0, %1, %2" : "=r" (result) : "r" (op1), "r" (op2) ); return(result); } __attribute__( ( always_inline ) ) __STATIC_INLINE uint32_t __UADD16(uint32_t op1, uint32_t op2) { uint32_t result; __ASM volatile ("uadd16 %0, %1, %2" : "=r" (result) : "r" (op1), "r" (op2) ); return(result); } __attribute__( ( always_inline ) ) __STATIC_INLINE uint32_t __UQADD16(uint32_t op1, uint32_t op2) { uint32_t result; __ASM volatile ("uqadd16 %0, %1, %2" : "=r" (result) : "r" (op1), "r" (op2) ); return(result); } __attribute__( ( always_inline ) ) __STATIC_INLINE uint32_t __UHADD16(uint32_t op1, uint32_t op2) { uint32_t result; __ASM volatile ("uhadd16 %0, %1, %2" : "=r" (result) : "r" (op1), "r" (op2) ); return(result); } __attribute__( ( always_inline ) ) __STATIC_INLINE uint32_t __SSUB16(uint32_t op1, uint32_t op2) { uint32_t result; __ASM volatile ("ssub16 %0, %1, %2" : "=r" (result) : "r" (op1), "r" (op2) ); return(result); } __attribute__( ( always_inline ) ) __STATIC_INLINE uint32_t __QSUB16(uint32_t op1, uint32_t op2) { uint32_t result; __ASM volatile ("qsub16 %0, %1, %2" : "=r" (result) : "r" (op1), "r" (op2) ); return(result); } __attribute__( ( always_inline ) ) __STATIC_INLINE uint32_t __SHSUB16(uint32_t op1, uint32_t op2) { uint32_t result; __ASM volatile ("shsub16 %0, %1, %2" : "=r" (result) : "r" (op1), "r" (op2) ); return(result); } __attribute__( ( always_inline ) ) __STATIC_INLINE uint32_t __USUB16(uint32_t op1, uint32_t op2) { uint32_t result; __ASM volatile ("usub16 %0, %1, %2" : "=r" (result) : "r" (op1), "r" (op2) ); return(result); } __attribute__( ( always_inline ) ) __STATIC_INLINE uint32_t __UQSUB16(uint32_t op1, uint32_t op2) { uint32_t result; __ASM volatile ("uqsub16 %0, %1, %2" : "=r" (result) : "r" (op1), "r" (op2) ); return(result); } __attribute__( ( always_inline ) ) __STATIC_INLINE uint32_t __UHSUB16(uint32_t op1, uint32_t op2) { uint32_t result; __ASM volatile ("uhsub16 %0, %1, %2" : "=r" (result) : "r" (op1), "r" (op2) ); return(result); } __attribute__( ( always_inline ) ) __STATIC_INLINE uint32_t __SASX(uint32_t op1, uint32_t op2) { uint32_t result; __ASM volatile ("sasx %0, %1, %2" : "=r" (result) : "r" (op1), "r" (op2) ); return(result); } __attribute__( ( always_inline ) ) __STATIC_INLINE uint32_t __QASX(uint32_t op1, uint32_t op2) { uint32_t result; __ASM volatile ("qasx %0, %1, %2" : "=r" (result) : "r" (op1), "r" (op2) ); return(result); } __attribute__( ( always_inline ) ) __STATIC_INLINE uint32_t __SHASX(uint32_t op1, uint32_t op2) { uint32_t result; __ASM volatile ("shasx %0, %1, %2" : "=r" (result) : "r" (op1), "r" (op2) ); return(result); } __attribute__( ( always_inline ) ) __STATIC_INLINE uint32_t __UASX(uint32_t op1, uint32_t op2) { uint32_t result; __ASM volatile ("uasx %0, %1, %2" : "=r" (result) : "r" (op1), "r" (op2) ); return(result); } __attribute__( ( always_inline ) ) __STATIC_INLINE uint32_t __UQASX(uint32_t op1, uint32_t op2) { uint32_t result; __ASM volatile ("uqasx %0, %1, %2" : "=r" (result) : "r" (op1), "r" (op2) ); return(result); } __attribute__( ( always_inline ) ) __STATIC_INLINE uint32_t __UHASX(uint32_t op1, uint32_t op2) { uint32_t result; __ASM volatile ("uhasx %0, %1, %2" : "=r" (result) : "r" (op1), "r" (op2) ); return(result); } __attribute__( ( always_inline ) ) __STATIC_INLINE uint32_t __SSAX(uint32_t op1, uint32_t op2) { uint32_t result; __ASM volatile ("ssax %0, %1, %2" : "=r" (result) : "r" (op1), "r" (op2) ); return(result); } __attribute__( ( always_inline ) ) __STATIC_INLINE uint32_t __QSAX(uint32_t op1, uint32_t op2) { uint32_t result; __ASM volatile ("qsax %0, %1, %2" : "=r" (result) : "r" (op1), "r" (op2) ); return(result); } __attribute__( ( always_inline ) ) __STATIC_INLINE uint32_t __SHSAX(uint32_t op1, uint32_t op2) { uint32_t result; __ASM volatile ("shsax %0, %1, %2" : "=r" (result) : "r" (op1), "r" (op2) ); return(result); } __attribute__( ( always_inline ) ) __STATIC_INLINE uint32_t __USAX(uint32_t op1, uint32_t op2) { uint32_t result; __ASM volatile ("usax %0, %1, %2" : "=r" (result) : "r" (op1), "r" (op2) ); return(result); } __attribute__( ( always_inline ) ) __STATIC_INLINE uint32_t __UQSAX(uint32_t op1, uint32_t op2) { uint32_t result; __ASM volatile ("uqsax %0, %1, %2" : "=r" (result) : "r" (op1), "r" (op2) ); return(result); } __attribute__( ( always_inline ) ) __STATIC_INLINE uint32_t __UHSAX(uint32_t op1, uint32_t op2) { uint32_t result; __ASM volatile ("uhsax %0, %1, %2" : "=r" (result) : "r" (op1), "r" (op2) ); return(result); } __attribute__( ( always_inline ) ) __STATIC_INLINE uint32_t __USAD8(uint32_t op1, uint32_t op2) { uint32_t result; __ASM volatile ("usad8 %0, %1, %2" : "=r" (result) : "r" (op1), "r" (op2) ); return(result); } __attribute__( ( always_inline ) ) __STATIC_INLINE uint32_t __USADA8(uint32_t op1, uint32_t op2, uint32_t op3) { uint32_t result; __ASM volatile ("usada8 %0, %1, %2, %3" : "=r" (result) : "r" (op1), "r" (op2), "r" (op3) ); return(result); } #define __SSAT16(ARG1,ARG2) \ ({ \ uint32_t __RES, __ARG1 = (ARG1); \ __ASM ("ssat16 %0, %1, %2" : "=r" (__RES) : "I" (ARG2), "r" (__ARG1) ); \ __RES; \ }) #define __USAT16(ARG1,ARG2) \ ({ \ uint32_t __RES, __ARG1 = (ARG1); \ __ASM ("usat16 %0, %1, %2" : "=r" (__RES) : "I" (ARG2), "r" (__ARG1) ); \ __RES; \ }) __attribute__( ( always_inline ) ) __STATIC_INLINE uint32_t __UXTB16(uint32_t op1) { uint32_t result; __ASM volatile ("uxtb16 %0, %1" : "=r" (result) : "r" (op1)); return(result); } __attribute__( ( always_inline ) ) __STATIC_INLINE uint32_t __UXTAB16(uint32_t op1, uint32_t op2) { uint32_t result; __ASM volatile ("uxtab16 %0, %1, %2" : "=r" (result) : "r" (op1), "r" (op2) ); return(result); } __attribute__( ( always_inline ) ) __STATIC_INLINE uint32_t __SXTB16(uint32_t op1) { uint32_t result; __ASM volatile ("sxtb16 %0, %1" : "=r" (result) : "r" (op1)); return(result); } __attribute__( ( always_inline ) ) __STATIC_INLINE uint32_t __SXTAB16(uint32_t op1, uint32_t op2) { uint32_t result; __ASM volatile ("sxtab16 %0, %1, %2" : "=r" (result) : "r" (op1), "r" (op2) ); return(result); } __attribute__( ( always_inline ) ) __STATIC_INLINE uint32_t __SMUAD (uint32_t op1, uint32_t op2) { uint32_t result; __ASM volatile ("smuad %0, %1, %2" : "=r" (result) : "r" (op1), "r" (op2) ); return(result); } __attribute__( ( always_inline ) ) __STATIC_INLINE uint32_t __SMUADX (uint32_t op1, uint32_t op2) { uint32_t result; __ASM volatile ("smuadx %0, %1, %2" : "=r" (result) : "r" (op1), "r" (op2) ); return(result); } __attribute__( ( always_inline ) ) __STATIC_INLINE uint32_t __SMLAD (uint32_t op1, uint32_t op2, uint32_t op3) { uint32_t result; __ASM volatile ("smlad %0, %1, %2, %3" : "=r" (result) : "r" (op1), "r" (op2), "r" (op3) ); return(result); } __attribute__( ( always_inline ) ) __STATIC_INLINE uint32_t __SMLADX (uint32_t op1, uint32_t op2, uint32_t op3) { uint32_t result; __ASM volatile ("smladx %0, %1, %2, %3" : "=r" (result) : "r" (op1), "r" (op2), "r" (op3) ); return(result); } __attribute__( ( always_inline ) ) __STATIC_INLINE uint64_t __SMLALD (uint32_t op1, uint32_t op2, uint64_t acc) { union llreg_u{ uint32_t w32[2]; uint64_t w64; } llr; llr.w64 = acc; #ifndef __ARMEB__ // Little endian __ASM volatile ("smlald %0, %1, %2, %3" : "=r" (llr.w32[0]), "=r" (llr.w32[1]): "r" (op1), "r" (op2) , "0" (llr.w32[0]), "1" (llr.w32[1]) ); #else // Big endian __ASM volatile ("smlald %0, %1, %2, %3" : "=r" (llr.w32[1]), "=r" (llr.w32[0]): "r" (op1), "r" (op2) , "0" (llr.w32[1]), "1" (llr.w32[0]) ); #endif return(llr.w64); } __attribute__( ( always_inline ) ) __STATIC_INLINE uint64_t __SMLALDX (uint32_t op1, uint32_t op2, uint64_t acc) { union llreg_u{ uint32_t w32[2]; uint64_t w64; } llr; llr.w64 = acc; #ifndef __ARMEB__ // Little endian __ASM volatile ("smlaldx %0, %1, %2, %3" : "=r" (llr.w32[0]), "=r" (llr.w32[1]): "r" (op1), "r" (op2) , "0" (llr.w32[0]), "1" (llr.w32[1]) ); #else // Big endian __ASM volatile ("smlaldx %0, %1, %2, %3" : "=r" (llr.w32[1]), "=r" (llr.w32[0]): "r" (op1), "r" (op2) , "0" (llr.w32[1]), "1" (llr.w32[0]) ); #endif return(llr.w64); } __attribute__( ( always_inline ) ) __STATIC_INLINE uint32_t __SMUSD (uint32_t op1, uint32_t op2) { uint32_t result; __ASM volatile ("smusd %0, %1, %2" : "=r" (result) : "r" (op1), "r" (op2) ); return(result); } __attribute__( ( always_inline ) ) __STATIC_INLINE uint32_t __SMUSDX (uint32_t op1, uint32_t op2) { uint32_t result; __ASM volatile ("smusdx %0, %1, %2" : "=r" (result) : "r" (op1), "r" (op2) ); return(result); } __attribute__( ( always_inline ) ) __STATIC_INLINE uint32_t __SMLSD (uint32_t op1, uint32_t op2, uint32_t op3) { uint32_t result; __ASM volatile ("smlsd %0, %1, %2, %3" : "=r" (result) : "r" (op1), "r" (op2), "r" (op3) ); return(result); } __attribute__( ( always_inline ) ) __STATIC_INLINE uint32_t __SMLSDX (uint32_t op1, uint32_t op2, uint32_t op3) { uint32_t result; __ASM volatile ("smlsdx %0, %1, %2, %3" : "=r" (result) : "r" (op1), "r" (op2), "r" (op3) ); return(result); } __attribute__( ( always_inline ) ) __STATIC_INLINE uint64_t __SMLSLD (uint32_t op1, uint32_t op2, uint64_t acc) { union llreg_u{ uint32_t w32[2]; uint64_t w64; } llr; llr.w64 = acc; #ifndef __ARMEB__ // Little endian __ASM volatile ("smlsld %0, %1, %2, %3" : "=r" (llr.w32[0]), "=r" (llr.w32[1]): "r" (op1), "r" (op2) , "0" (llr.w32[0]), "1" (llr.w32[1]) ); #else // Big endian __ASM volatile ("smlsld %0, %1, %2, %3" : "=r" (llr.w32[1]), "=r" (llr.w32[0]): "r" (op1), "r" (op2) , "0" (llr.w32[1]), "1" (llr.w32[0]) ); #endif return(llr.w64); } __attribute__( ( always_inline ) ) __STATIC_INLINE uint64_t __SMLSLDX (uint32_t op1, uint32_t op2, uint64_t acc) { union llreg_u{ uint32_t w32[2]; uint64_t w64; } llr; llr.w64 = acc; #ifndef __ARMEB__ // Little endian __ASM volatile ("smlsldx %0, %1, %2, %3" : "=r" (llr.w32[0]), "=r" (llr.w32[1]): "r" (op1), "r" (op2) , "0" (llr.w32[0]), "1" (llr.w32[1]) ); #else // Big endian __ASM volatile ("smlsldx %0, %1, %2, %3" : "=r" (llr.w32[1]), "=r" (llr.w32[0]): "r" (op1), "r" (op2) , "0" (llr.w32[1]), "1" (llr.w32[0]) ); #endif return(llr.w64); } __attribute__( ( always_inline ) ) __STATIC_INLINE uint32_t __SEL (uint32_t op1, uint32_t op2) { uint32_t result; __ASM volatile ("sel %0, %1, %2" : "=r" (result) : "r" (op1), "r" (op2) ); return(result); } __attribute__( ( always_inline ) ) __STATIC_INLINE uint32_t __QADD(uint32_t op1, uint32_t op2) { uint32_t result; __ASM volatile ("qadd %0, %1, %2" : "=r" (result) : "r" (op1), "r" (op2) ); return(result); } __attribute__( ( always_inline ) ) __STATIC_INLINE uint32_t __QSUB(uint32_t op1, uint32_t op2) { uint32_t result; __ASM volatile ("qsub %0, %1, %2" : "=r" (result) : "r" (op1), "r" (op2) ); return(result); } #define __PKHBT(ARG1,ARG2,ARG3) \ ({ \ uint32_t __RES, __ARG1 = (ARG1), __ARG2 = (ARG2); \ __ASM ("pkhbt %0, %1, %2, lsl %3" : "=r" (__RES) : "r" (__ARG1), "r" (__ARG2), "I" (ARG3) ); \ __RES; \ }) #define __PKHTB(ARG1,ARG2,ARG3) \ ({ \ uint32_t __RES, __ARG1 = (ARG1), __ARG2 = (ARG2); \ if (ARG3 == 0) \ __ASM ("pkhtb %0, %1, %2" : "=r" (__RES) : "r" (__ARG1), "r" (__ARG2) ); \ else \ __ASM ("pkhtb %0, %1, %2, asr %3" : "=r" (__RES) : "r" (__ARG1), "r" (__ARG2), "I" (ARG3) ); \ __RES; \ }) __attribute__( ( always_inline ) ) __STATIC_INLINE uint32_t __SMMLA (int32_t op1, int32_t op2, int32_t op3) { int32_t result; __ASM volatile ("smmla %0, %1, %2, %3" : "=r" (result): "r" (op1), "r" (op2), "r" (op3) ); return(result); } #elif defined ( __ICCARM__ ) /*------------------ ICC Compiler -------------------*/ /* IAR iccarm specific functions */ #include #elif defined ( __TMS470__ ) /*---------------- TI CCS Compiler ------------------*/ /* TI CCS specific functions */ #include #elif defined ( __TASKING__ ) /*------------------ TASKING Compiler --------------*/ /* TASKING carm specific functions */ /* not yet supported */ #elif defined ( __CSMC__ ) /*------------------ COSMIC Compiler -------------------*/ /* Cosmic specific functions */ #include #endif /*@} end of group CMSIS_SIMD_intrinsics */ #ifdef __cplusplus } #endif #endif /* __CORE_CMSIMD_H */ ================================================ FILE: Zelig/mbed/TARGET_K64F/system_MK64F12.h ================================================ /* ** ################################################################### ** Processor: MK64FN1M0VMD12 ** Compilers: Keil ARM C/C++ Compiler ** Freescale C/C++ for Embedded ARM ** GNU C Compiler ** GNU C Compiler - CodeSourcery Sourcery G++ ** IAR ANSI C/C++ Compiler for ARM ** ** Reference manual: K64P144M120SF5RM, Rev.2, January 2014 ** Version: rev. 2.5, 2014-02-10 ** Build: b140611 ** ** Abstract: ** Provides a system configuration function and a global variable that ** contains the system frequency. It configures the device and initializes ** the oscillator (PLL) that is part of the microcontroller device. ** ** Copyright (c) 2014 Freescale Semiconductor, Inc. ** All rights reserved. ** ** Redistribution and use in source and binary forms, with or without modification, ** are permitted provided that the following conditions are met: ** ** o Redistributions of source code must retain the above copyright notice, this list ** of conditions and the following disclaimer. ** ** o Redistributions in binary form must reproduce the above copyright notice, this ** list of conditions and the following disclaimer in the documentation and/or ** other materials provided with the distribution. ** ** o Neither the name of Freescale Semiconductor, Inc. nor the names of its ** contributors may be used to endorse or promote products derived from this ** software without specific prior written permission. ** ** THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ** ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED ** WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE ** DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT 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. ** ** http: www.freescale.com ** mail: support@freescale.com ** ** Revisions: ** - rev. 1.0 (2013-08-12) ** Initial version. ** - rev. 2.0 (2013-10-29) ** Register accessor macros added to the memory map. ** Symbols for Processor Expert memory map compatibility added to the memory map. ** Startup file for gcc has been updated according to CMSIS 3.2. ** System initialization updated. ** MCG - registers updated. ** PORTA, PORTB, PORTC, PORTE - registers for digital filter removed. ** - rev. 2.1 (2013-10-30) ** Definition of BITBAND macros updated to support peripherals with 32-bit acces disabled. ** - rev. 2.2 (2013-12-09) ** DMA - EARS register removed. ** AIPS0, AIPS1 - MPRA register updated. ** - rev. 2.3 (2014-01-24) ** Update according to reference manual rev. 2 ** ENET, MCG, MCM, SIM, USB - registers updated ** - rev. 2.4 (2014-02-10) ** The declaration of clock configurations has been moved to separate header file system_MK64F12.h ** Update of SystemInit() and SystemCoreClockUpdate() functions. ** - rev. 2.5 (2014-02-10) ** The declaration of clock configurations has been moved to separate header file system_MK64F12.h ** Update of SystemInit() and SystemCoreClockUpdate() functions. ** Module access macro module_BASES replaced by module_BASE_PTRS. ** ** ################################################################### */ /*! * @file MK64F12 * @version 2.5 * @date 2014-02-10 * @brief Device specific configuration file for MK64F12 (header file) * * Provides a system configuration function and a global variable that contains * the system frequency. It configures the device and initializes the oscillator * (PLL) that is part of the microcontroller device. */ #ifndef SYSTEM_MK64F12_H_ #define SYSTEM_MK64F12_H_ /**< Symbol preventing repeated inclusion */ #ifdef __cplusplus extern "C" { #endif #include #define DISABLE_WDOG 1 #ifndef CLOCK_SETUP #define CLOCK_SETUP 4 #endif /* MCG mode constants */ #define MCG_MODE_FEI 0U #define MCG_MODE_FBI 1U #define MCG_MODE_BLPI 2U #define MCG_MODE_FEE 3U #define MCG_MODE_FBE 4U #define MCG_MODE_BLPE 5U #define MCG_MODE_PBE 6U #define MCG_MODE_PEE 7U /* Predefined clock setups 0 ... Default part configuration Multipurpose Clock Generator (MCG) in FEI mode. Reference clock source for MCG module: Slow internal reference clock Core clock = 20.97152MHz Bus clock = 20.97152MHz 1 ... Maximum achievable clock frequency configuration Multipurpose Clock Generator (MCG) in PEE mode. Reference clock source for MCG module: System oscillator 0 reference clock Core clock = 120MHz Bus clock = 60MHz 2 ... Chip internaly clocked, ready for Very Low Power Run mode. Multipurpose Clock Generator (MCG) in BLPI mode. Reference clock source for MCG module: Fast internal reference clock Core clock = 4MHz Bus clock = 4MHz 3 ... Chip externally clocked, ready for Very Low Power Run mode. Multipurpose Clock Generator (MCG) in BLPE mode. Reference clock source for MCG module: RTC oscillator reference clock Core clock = 0.032768MHz Bus clock = 0.032768MHz 4 ... USB clock setup Multipurpose Clock Generator (MCG) in PEE mode. Reference clock source for MCG module: System oscillator 0 reference clock Core clock = 120MHz Bus clock = 60MHz */ /* Define clock source values */ #define CPU_XTAL_CLK_HZ 50000000u /* Value of the external crystal or oscillator clock frequency in Hz */ #define CPU_XTAL32k_CLK_HZ 32768u /* Value of the external 32k crystal or oscillator clock frequency in Hz */ #define CPU_INT_SLOW_CLK_HZ 32768u /* Value of the slow internal oscillator clock frequency in Hz */ #define CPU_INT_FAST_CLK_HZ 4000000u /* Value of the fast internal oscillator clock frequency in Hz */ #define CPU_INT_IRC_CLK_HZ 48000000u /* Value of the 48M internal oscillator clock frequency in Hz */ /* RTC oscillator setting */ /* RTC_CR: SC2P=0,SC4P=0,SC8P=0,SC16P=0,CLKO=1,OSCE=1,WPS=0,UM=0,SUP=0,WPE=0,SWR=0 */ #define SYSTEM_RTC_CR_VALUE 0x0300U /* RTC_CR */ /* Low power mode enable */ /* SMC_PMPROT: AVLP=1,ALLS=1,AVLLS=1 */ #define SYSTEM_SMC_PMPROT_VALUE 0x2AU /* SMC_PMPROT */ /* Internal reference clock trim */ /* #undef SLOW_TRIM_ADDRESS */ /* Slow oscillator not trimmed. Commented out for MISRA compliance. */ /* #undef SLOW_FINE_TRIM_ADDRESS */ /* Slow oscillator not trimmed. Commented out for MISRA compliance. */ /* #undef FAST_TRIM_ADDRESS */ /* Fast oscillator not trimmed. Commented out for MISRA compliance. */ /* #undef FAST_FINE_TRIM_ADDRESS */ /* Fast oscillator not trimmed. Commented out for MISRA compliance. */ #if (CLOCK_SETUP == 0) #define DEFAULT_SYSTEM_CLOCK 20971520u /* Default System clock value */ #define MCG_MODE MCG_MODE_FEI /* Clock generator mode */ /* MCG_C1: CLKS=0,FRDIV=0,IREFS=1,IRCLKEN=1,IREFSTEN=0 */ #define SYSTEM_MCG_C1_VALUE 0x06U /* MCG_C1 */ /* MCG_C2: LOCRE0=0,FCFTRIM=0,RANGE=2,HGO=0,EREFS=0,LP=0,IRCS=0 */ #define SYSTEM_MCG_C2_VALUE 0x20U /* MCG_C2 */ /* MCG_C4: DMX32=0,DRST_DRS=0,FCTRIM=0,SCFTRIM=0 */ #define SYSTEM_MCG_C4_VALUE 0x00U /* MCG_C4 */ /* MCG_SC: ATME=0,ATMS=0,ATMF=0,FLTPRSRV=0,FCRDIV=0,LOCS0=0 */ #define SYSTEM_MCG_SC_VALUE 0x00U /* MCG_SC */ /* MCG_C5: PLLCLKEN0=0,PLLSTEN0=0,PRDIV0=0 */ #define SYSTEM_MCG_C5_VALUE 0x00U /* MCG_C5 */ /* MCG_C6: LOLIE0=0,PLLS=0,CME0=0,VDIV0=0 */ #define SYSTEM_MCG_C6_VALUE 0x00U /* MCG_C6 */ /* MCG_C7: OSCSEL=0 */ #define SYSTEM_MCG_C7_VALUE 0x00U /* MCG_C7 */ /* OSC_CR: ERCLKEN=0,EREFSTEN=0,SC2P=0,SC4P=0,SC8P=0,SC16P=0 */ #define SYSTEM_OSC_CR_VALUE 0x00U /* OSC_CR */ /* SMC_PMCTRL: LPWUI=0,RUNM=0,STOPA=0,STOPM=0 */ #define SYSTEM_SMC_PMCTRL_VALUE 0x00U /* SMC_PMCTRL */ /* SIM_CLKDIV1: OUTDIV1=0,OUTDIV2=0,OUTDIV3=1,OUTDIV4=1 */ #define SYSTEM_SIM_CLKDIV1_VALUE 0x00110000U /* SIM_CLKDIV1 */ /* SIM_SOPT1: USBREGEN=0,USBSSTBY=0,USBVSTBY=0,OSC32KSEL=2,RAMSIZE=0 */ #define SYSTEM_SIM_SOPT1_VALUE 0x00080000U /* SIM_SOPT1 */ /* SIM_SOPT2: SDHCSRC=0,TIMESRC=0,RMIISRC=0,USBSRC=0,PLLFLLSEL=0,TRACECLKSEL=0,PTD7PAD=0,FBSL=0,CLKOUTSEL=0,RTCCLKOUTSEL=0 */ #define SYSTEM_SIM_SOPT2_VALUE 0x00U /* SIM_SOPT2 */ #elif (CLOCK_SETUP == 1) #define DEFAULT_SYSTEM_CLOCK 120000000u /* Default System clock value */ #define MCG_MODE MCG_MODE_PEE /* Clock generator mode */ /* MCG_C1: CLKS=0,FRDIV=7,IREFS=0,IRCLKEN=1,IREFSTEN=0 */ #define SYSTEM_MCG_C1_VALUE 0x3AU /* MCG_C1 */ /* MCG_C2: LOCRE0=0,FCFTRIM=0,RANGE=2,HGO=0,EREFS=0,LP=0,IRCS=0 */ #define SYSTEM_MCG_C2_VALUE 0x20U /* MCG_C2 */ /* MCG_C4: DMX32=0,DRST_DRS=0,FCTRIM=0,SCFTRIM=0 */ #define SYSTEM_MCG_C4_VALUE 0x00U /* MCG_C4 */ /* MCG_SC: ATME=0,ATMS=0,ATMF=0,FLTPRSRV=0,FCRDIV=0,LOCS0=0 */ #define SYSTEM_MCG_SC_VALUE 0x00U /* MCG_SC */ /* MCG_C5: PLLCLKEN0=0,PLLSTEN0=0,PRDIV0=0x13 */ #define SYSTEM_MCG_C5_VALUE 0x13U /* MCG_C5 */ /* MCG_C6: LOLIE0=0,PLLS=1,CME0=0,VDIV0=0x18 */ #define SYSTEM_MCG_C6_VALUE 0x58U /* MCG_C6 */ /* MCG_C7: OSCSEL=0 */ #define SYSTEM_MCG_C7_VALUE 0x00U /* MCG_C7 */ /* OSC_CR: ERCLKEN=1,EREFSTEN=0,SC2P=0,SC4P=0,SC8P=0,SC16P=0 */ #define SYSTEM_OSC_CR_VALUE 0x80U /* OSC_CR */ /* SMC_PMCTRL: LPWUI=0,RUNM=0,STOPA=0,STOPM=0 */ #define SYSTEM_SMC_PMCTRL_VALUE 0x00U /* SMC_PMCTRL */ /* SIM_CLKDIV1: OUTDIV1=0,OUTDIV2=1,OUTDIV3=1,OUTDIV4=4 */ #define SYSTEM_SIM_CLKDIV1_VALUE 0x01140000U /* SIM_CLKDIV1 */ /* SIM_SOPT1: USBREGEN=0,USBSSTBY=0,USBVSTBY=0,OSC32KSEL=2,RAMSIZE=0 */ #define SYSTEM_SIM_SOPT1_VALUE 0x00080000U /* SIM_SOPT1 */ /* SIM_SOPT2: SDHCSRC=0,TIMESRC=0,RMIISRC=0,USBSRC=0,PLLFLLSEL=1,TRACECLKSEL=0,PTD7PAD=0,FBSL=0,CLKOUTSEL=0,RTCCLKOUTSEL=0 */ #define SYSTEM_SIM_SOPT2_VALUE 0x00010000U /* SIM_SOPT2 */ #elif (CLOCK_SETUP == 2) #define DEFAULT_SYSTEM_CLOCK 4000000u /* Default System clock value */ #define MCG_MODE MCG_MODE_BLPI /* Clock generator mode */ /* MCG_C1: CLKS=1,FRDIV=0,IREFS=1,IRCLKEN=1,IREFSTEN=0 */ #define SYSTEM_MCG_C1_VALUE 0x46U /* MCG_C1 */ /* MCG_C2: LOCRE0=0,FCFTRIM=0,RANGE=2,HGO=0,EREFS=0,LP=1,IRCS=1 */ #define SYSTEM_MCG_C2_VALUE 0x23U /* MCG_C2 */ /* MCG_C4: DMX32=0,DRST_DRS=0,FCTRIM=0,SCFTRIM=0 */ #define SYSTEM_MCG_C4_VALUE 0x00U /* MCG_C4 */ /* MCG_SC: ATME=0,ATMS=0,ATMF=0,FLTPRSRV=0,FCRDIV=0,LOCS0=0 */ #define SYSTEM_MCG_SC_VALUE 0x00U /* MCG_SC */ /* MCG_C5: PLLCLKEN0=0,PLLSTEN0=0,PRDIV0=0 */ #define SYSTEM_MCG_C5_VALUE 0x00U /* MCG_C5 */ /* MCG_C6: LOLIE0=0,PLLS=0,CME0=0,VDIV0=0 */ #define SYSTEM_MCG_C6_VALUE 0x00U /* MCG_C6 */ /* MCG_C7: OSCSEL=0 */ #define SYSTEM_MCG_C7_VALUE 0x00U /* MCG_C7 */ /* OSC_CR: ERCLKEN=1,EREFSTEN=0,SC2P=0,SC4P=0,SC8P=0,SC16P=0 */ #define SYSTEM_OSC_CR_VALUE 0x80U /* OSC_CR */ /* SMC_PMCTRL: LPWUI=0,RUNM=0,STOPA=0,STOPM=0 */ #define SYSTEM_SMC_PMCTRL_VALUE 0x00U /* SMC_PMCTRL */ /* SIM_CLKDIV1: OUTDIV1=0,OUTDIV2=0,OUTDIV3=0,OUTDIV4=4 */ #define SYSTEM_SIM_CLKDIV1_VALUE 0x00040000U /* SIM_CLKDIV1 */ /* SIM_SOPT1: USBREGEN=0,USBSSTBY=0,USBVSTBY=0,OSC32KSEL=2,RAMSIZE=0 */ #define SYSTEM_SIM_SOPT1_VALUE 0x00080000U /* SIM_SOPT1 */ /* SIM_SOPT2: SDHCSRC=0,TIMESRC=0,RMIISRC=0,USBSRC=0,PLLFLLSEL=3,TRACECLKSEL=0,PTD7PAD=0,FBSL=0,CLKOUTSEL=0,RTCCLKOUTSEL=0 */ #define SYSTEM_SIM_SOPT2_VALUE 0x00030000U /* SIM_SOPT2 */ #elif (CLOCK_SETUP == 3) #define DEFAULT_SYSTEM_CLOCK 32768u /* Default System clock value */ #define MCG_MODE MCG_MODE_BLPE /* Clock generator mode */ /* MCG_C1: CLKS=2,FRDIV=0,IREFS=0,IRCLKEN=1,IREFSTEN=0 */ #define SYSTEM_MCG_C1_VALUE 0x82U /* MCG_C1 */ /* MCG_C2: LOCRE0=0,FCFTRIM=0,RANGE=2,HGO=0,EREFS=0,LP=1,IRCS=1 */ #define SYSTEM_MCG_C2_VALUE 0x23U /* MCG_C2 */ /* MCG_C4: DMX32=0,DRST_DRS=0,FCTRIM=0,SCFTRIM=0 */ #define SYSTEM_MCG_C4_VALUE 0x00U /* MCG_C4 */ /* MCG_SC: ATME=0,ATMS=0,ATMF=0,FLTPRSRV=0,FCRDIV=1,LOCS0=0 */ #define SYSTEM_MCG_SC_VALUE 0x02U /* MCG_SC */ /* MCG_C5: PLLCLKEN0=0,PLLSTEN0=0,PRDIV0=0 */ #define SYSTEM_MCG_C5_VALUE 0x00U /* MCG_C5 */ /* MCG_C6: LOLIE0=0,PLLS=0,CME0=0,VDIV0=0 */ #define SYSTEM_MCG_C6_VALUE 0x00U /* MCG_C6 */ /* MCG_C7: OSCSEL=1 */ #define SYSTEM_MCG_C7_VALUE 0x01U /* MCG_C7 */ /* OSC_CR: ERCLKEN=0,EREFSTEN=0,SC2P=0,SC4P=0,SC8P=0,SC16P=0 */ #define SYSTEM_OSC_CR_VALUE 0x00U /* OSC_CR */ /* SMC_PMCTRL: LPWUI=0,RUNM=0,STOPA=0,STOPM=0 */ #define SYSTEM_SMC_PMCTRL_VALUE 0x00U /* SMC_PMCTRL */ /* SIM_CLKDIV1: OUTDIV1=0,OUTDIV2=0,OUTDIV3=0,OUTDIV4=0 */ #define SYSTEM_SIM_CLKDIV1_VALUE 0x00U /* SIM_CLKDIV1 */ /* SIM_SOPT1: USBREGEN=0,USBSSTBY=0,USBVSTBY=0,OSC32KSEL=2,RAMSIZE=0 */ #define SYSTEM_SIM_SOPT1_VALUE 0x00080000U /* SIM_SOPT1 */ /* SIM_SOPT2: SDHCSRC=0,TIMESRC=0,RMIISRC=0,USBSRC=0,PLLFLLSEL=3,TRACECLKSEL=0,PTD7PAD=0,FBSL=0,CLKOUTSEL=0,RTCCLKOUTSEL=0 */ #define SYSTEM_SIM_SOPT2_VALUE 0x00030000U /* SIM_SOPT2 */ #elif (CLOCK_SETUP == 4) #define DEFAULT_SYSTEM_CLOCK 120000000u /* Default System clock value */ #define MCG_MODE MCG_MODE_PEE /* Clock generator mode */ /* MCG_C1: CLKS=0,FRDIV=7,IREFS=0,IRCLKEN=1,IREFSTEN=0 */ #define SYSTEM_MCG_C1_VALUE 0x3AU /* MCG_C1 */ /* MCG_C2: LOCRE0=0,FCFTRIM=0,RANGE=2,HGO=0,EREFS=0,LP=0,IRCS=0 */ #define SYSTEM_MCG_C2_VALUE 0x20U /* MCG_C2 */ /* MCG_C4: DMX32=0,DRST_DRS=0,FCTRIM=0,SCFTRIM=0 */ #define SYSTEM_MCG_C4_VALUE 0x00U /* MCG_C4 */ /* MCG_SC: ATME=0,ATMS=0,ATMF=0,FLTPRSRV=0,FCRDIV=0,LOCS0=0 */ #define SYSTEM_MCG_SC_VALUE 0x00U /* MCG_SC */ /* MCG_C5: PLLCLKEN0=0,PLLSTEN0=0,PRDIV0=0x13 */ #define SYSTEM_MCG_C5_VALUE 0x13U /* MCG_C5 */ /* MCG_C6: LOLIE0=0,PLLS=1,CME0=0,VDIV0=0x18 */ #define SYSTEM_MCG_C6_VALUE 0x58U /* MCG_C6 */ /* MCG_C7: OSCSEL=0 */ #define SYSTEM_MCG_C7_VALUE 0x00U /* MCG_C7 */ /* OSC_CR: ERCLKEN=1,EREFSTEN=0,SC2P=0,SC4P=0,SC8P=0,SC16P=0 */ #define SYSTEM_OSC_CR_VALUE 0x80U /* OSC_CR */ /* SMC_PMCTRL: LPWUI=0,RUNM=0,STOPA=0,STOPM=0 */ #define SYSTEM_SMC_PMCTRL_VALUE 0x00U /* SMC_PMCTRL */ /* SIM_CLKDIV1: OUTDIV1=0,OUTDIV2=1,OUTDIV3=1,OUTDIV4=4 */ #define SYSTEM_SIM_CLKDIV1_VALUE 0x01140000U /* SIM_CLKDIV1 */ /* SIM_CLKDIV2: USBDIV=4,USBFRAC=1 */ #define SYSTEM_SIM_CLKDIV2_VALUE 0x09U /* SIM_CLKDIV2 */ /* SIM_SOPT1: USBREGEN=0,USBSSTBY=0,USBVSTBY=0,OSC32KSEL=2,RAMSIZE=0 */ #define SYSTEM_SIM_SOPT1_VALUE 0x00080000U /* SIM_SOPT1 */ /* SIM_SOPT2: SDHCSRC=0,TIMESRC=0,RMIISRC=0,USBSRC=0,PLLFLLSEL=1,TRACECLKSEL=0,PTD7PAD=0,FBSL=0,CLKOUTSEL=0,RTCCLKOUTSEL=0 */ #define SYSTEM_SIM_SOPT2_VALUE 0x00010000U /* SIM_SOPT2 */ #endif /** * @brief System clock frequency (core clock) * * The system clock frequency supplied to the SysTick timer and the processor * core clock. This variable can be used by the user application to setup the * SysTick timer or configure other parameters. It may also be used by debugger to * query the frequency of the debug timer or configure the trace clock speed * SystemCoreClock is initialized with a correct predefined value. */ extern uint32_t SystemCoreClock; /** * @brief Setup the microcontroller system. * * Typically this function configures the oscillator (PLL) that is part of the * microcontroller device. For systems with variable clock speed it also updates * the variable SystemCoreClock. SystemInit is called from startup_device file. */ void SystemInit (void); /** * @brief Updates the SystemCoreClock variable. * * It must be called whenever the core clock is changed during program * execution. SystemCoreClockUpdate() evaluates the clock register settings and calculates * the current core clock. */ void SystemCoreClockUpdate (void); #ifdef __cplusplus } #endif #endif /* #if !defined(SYSTEM_MK64F12_H_) */ ================================================ FILE: Zelig/mbed/TARGET_LPC1768/LPC17xx.h ================================================ /**************************************************************************//** * @file LPC17xx.h * @brief CMSIS Cortex-M3 Core Peripheral Access Layer Header File for * NXP LPC17xx Device Series * @version: V1.09 * @date: 17. March 2010 * * @note * Copyright (C) 2009 ARM Limited. All rights reserved. * * @par * ARM Limited (ARM) is supplying this software for use with Cortex-M * processor based microcontrollers. This file can be freely distributed * within development tools that are supporting such ARM based processors. * * @par * THIS SOFTWARE IS PROVIDED "AS IS". NO WARRANTIES, WHETHER EXPRESS, IMPLIED * OR STATUTORY, INCLUDING, BUT NOT LIMITED TO, IMPLIED WARRANTIES OF * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE APPLY TO THIS SOFTWARE. * ARM SHALL NOT, IN ANY CIRCUMSTANCES, BE LIABLE FOR SPECIAL, INCIDENTAL, OR * CONSEQUENTIAL DAMAGES, FOR ANY REASON WHATSOEVER. * ******************************************************************************/ #ifndef __LPC17xx_H__ #define __LPC17xx_H__ /* * ========================================================================== * ---------- Interrupt Number Definition ----------------------------------- * ========================================================================== */ typedef enum IRQn { /****** Cortex-M3 Processor Exceptions Numbers ***************************************************/ NonMaskableInt_IRQn = -14, /*!< 2 Non Maskable Interrupt */ MemoryManagement_IRQn = -12, /*!< 4 Cortex-M3 Memory Management Interrupt */ BusFault_IRQn = -11, /*!< 5 Cortex-M3 Bus Fault Interrupt */ UsageFault_IRQn = -10, /*!< 6 Cortex-M3 Usage Fault Interrupt */ SVCall_IRQn = -5, /*!< 11 Cortex-M3 SV Call Interrupt */ DebugMonitor_IRQn = -4, /*!< 12 Cortex-M3 Debug Monitor Interrupt */ PendSV_IRQn = -2, /*!< 14 Cortex-M3 Pend SV Interrupt */ SysTick_IRQn = -1, /*!< 15 Cortex-M3 System Tick Interrupt */ /****** LPC17xx Specific Interrupt Numbers *******************************************************/ WDT_IRQn = 0, /*!< Watchdog Timer Interrupt */ TIMER0_IRQn = 1, /*!< Timer0 Interrupt */ TIMER1_IRQn = 2, /*!< Timer1 Interrupt */ TIMER2_IRQn = 3, /*!< Timer2 Interrupt */ TIMER3_IRQn = 4, /*!< Timer3 Interrupt */ UART0_IRQn = 5, /*!< UART0 Interrupt */ UART1_IRQn = 6, /*!< UART1 Interrupt */ UART2_IRQn = 7, /*!< UART2 Interrupt */ UART3_IRQn = 8, /*!< UART3 Interrupt */ PWM1_IRQn = 9, /*!< PWM1 Interrupt */ I2C0_IRQn = 10, /*!< I2C0 Interrupt */ I2C1_IRQn = 11, /*!< I2C1 Interrupt */ I2C2_IRQn = 12, /*!< I2C2 Interrupt */ SPI_IRQn = 13, /*!< SPI Interrupt */ SSP0_IRQn = 14, /*!< SSP0 Interrupt */ SSP1_IRQn = 15, /*!< SSP1 Interrupt */ PLL0_IRQn = 16, /*!< PLL0 Lock (Main PLL) Interrupt */ RTC_IRQn = 17, /*!< Real Time Clock Interrupt */ EINT0_IRQn = 18, /*!< External Interrupt 0 Interrupt */ EINT1_IRQn = 19, /*!< External Interrupt 1 Interrupt */ EINT2_IRQn = 20, /*!< External Interrupt 2 Interrupt */ EINT3_IRQn = 21, /*!< External Interrupt 3 Interrupt */ ADC_IRQn = 22, /*!< A/D Converter Interrupt */ BOD_IRQn = 23, /*!< Brown-Out Detect Interrupt */ USB_IRQn = 24, /*!< USB Interrupt */ CAN_IRQn = 25, /*!< CAN Interrupt */ DMA_IRQn = 26, /*!< General Purpose DMA Interrupt */ I2S_IRQn = 27, /*!< I2S Interrupt */ ENET_IRQn = 28, /*!< Ethernet Interrupt */ RIT_IRQn = 29, /*!< Repetitive Interrupt Timer Interrupt */ MCPWM_IRQn = 30, /*!< Motor Control PWM Interrupt */ QEI_IRQn = 31, /*!< Quadrature Encoder Interface Interrupt */ PLL1_IRQn = 32, /*!< PLL1 Lock (USB PLL) Interrupt */ USBActivity_IRQn = 33, /* USB Activity interrupt */ CANActivity_IRQn = 34, /* CAN Activity interrupt */ } IRQn_Type; /* * ========================================================================== * ----------- Processor and Core Peripheral Section ------------------------ * ========================================================================== */ /* Configuration of the Cortex-M3 Processor and Core Peripherals */ #define __MPU_PRESENT 1 /*!< MPU present or not */ #define __NVIC_PRIO_BITS 5 /*!< Number of Bits used for Priority Levels */ #define __Vendor_SysTickConfig 0 /*!< Set to 1 if different SysTick Config is used */ #include "core_cm3.h" /* Cortex-M3 processor and core peripherals */ #include "system_LPC17xx.h" /* System Header */ /******************************************************************************/ /* Device Specific Peripheral registers structures */ /******************************************************************************/ #if defined ( __CC_ARM ) #pragma anon_unions #endif /*------------- System Control (SC) ------------------------------------------*/ typedef struct { __IO uint32_t FLASHCFG; /* Flash Accelerator Module */ uint32_t RESERVED0[31]; __IO uint32_t PLL0CON; /* Clocking and Power Control */ __IO uint32_t PLL0CFG; __I uint32_t PLL0STAT; __O uint32_t PLL0FEED; uint32_t RESERVED1[4]; __IO uint32_t PLL1CON; __IO uint32_t PLL1CFG; __I uint32_t PLL1STAT; __O uint32_t PLL1FEED; uint32_t RESERVED2[4]; __IO uint32_t PCON; __IO uint32_t PCONP; uint32_t RESERVED3[15]; __IO uint32_t CCLKCFG; __IO uint32_t USBCLKCFG; __IO uint32_t CLKSRCSEL; __IO uint32_t CANSLEEPCLR; __IO uint32_t CANWAKEFLAGS; uint32_t RESERVED4[10]; __IO uint32_t EXTINT; /* External Interrupts */ uint32_t RESERVED5; __IO uint32_t EXTMODE; __IO uint32_t EXTPOLAR; uint32_t RESERVED6[12]; __IO uint32_t RSID; /* Reset */ uint32_t RESERVED7[7]; __IO uint32_t SCS; /* Syscon Miscellaneous Registers */ __IO uint32_t IRCTRIM; /* Clock Dividers */ __IO uint32_t PCLKSEL0; __IO uint32_t PCLKSEL1; uint32_t RESERVED8[4]; __IO uint32_t USBIntSt; /* USB Device/OTG Interrupt Register */ __IO uint32_t DMAREQSEL; __IO uint32_t CLKOUTCFG; /* Clock Output Configuration */ } LPC_SC_TypeDef; /*------------- Pin Connect Block (PINCON) -----------------------------------*/ typedef struct { __IO uint32_t PINSEL0; __IO uint32_t PINSEL1; __IO uint32_t PINSEL2; __IO uint32_t PINSEL3; __IO uint32_t PINSEL4; __IO uint32_t PINSEL5; __IO uint32_t PINSEL6; __IO uint32_t PINSEL7; __IO uint32_t PINSEL8; __IO uint32_t PINSEL9; __IO uint32_t PINSEL10; uint32_t RESERVED0[5]; __IO uint32_t PINMODE0; __IO uint32_t PINMODE1; __IO uint32_t PINMODE2; __IO uint32_t PINMODE3; __IO uint32_t PINMODE4; __IO uint32_t PINMODE5; __IO uint32_t PINMODE6; __IO uint32_t PINMODE7; __IO uint32_t PINMODE8; __IO uint32_t PINMODE9; __IO uint32_t PINMODE_OD0; __IO uint32_t PINMODE_OD1; __IO uint32_t PINMODE_OD2; __IO uint32_t PINMODE_OD3; __IO uint32_t PINMODE_OD4; __IO uint32_t I2CPADCFG; } LPC_PINCON_TypeDef; /*------------- General Purpose Input/Output (GPIO) --------------------------*/ typedef struct { union { __IO uint32_t FIODIR; struct { __IO uint16_t FIODIRL; __IO uint16_t FIODIRH; }; struct { __IO uint8_t FIODIR0; __IO uint8_t FIODIR1; __IO uint8_t FIODIR2; __IO uint8_t FIODIR3; }; }; uint32_t RESERVED0[3]; union { __IO uint32_t FIOMASK; struct { __IO uint16_t FIOMASKL; __IO uint16_t FIOMASKH; }; struct { __IO uint8_t FIOMASK0; __IO uint8_t FIOMASK1; __IO uint8_t FIOMASK2; __IO uint8_t FIOMASK3; }; }; union { __IO uint32_t FIOPIN; struct { __IO uint16_t FIOPINL; __IO uint16_t FIOPINH; }; struct { __IO uint8_t FIOPIN0; __IO uint8_t FIOPIN1; __IO uint8_t FIOPIN2; __IO uint8_t FIOPIN3; }; }; union { __IO uint32_t FIOSET; struct { __IO uint16_t FIOSETL; __IO uint16_t FIOSETH; }; struct { __IO uint8_t FIOSET0; __IO uint8_t FIOSET1; __IO uint8_t FIOSET2; __IO uint8_t FIOSET3; }; }; union { __O uint32_t FIOCLR; struct { __O uint16_t FIOCLRL; __O uint16_t FIOCLRH; }; struct { __O uint8_t FIOCLR0; __O uint8_t FIOCLR1; __O uint8_t FIOCLR2; __O uint8_t FIOCLR3; }; }; } LPC_GPIO_TypeDef; typedef struct { __I uint32_t IntStatus; __I uint32_t IO0IntStatR; __I uint32_t IO0IntStatF; __O uint32_t IO0IntClr; __IO uint32_t IO0IntEnR; __IO uint32_t IO0IntEnF; uint32_t RESERVED0[3]; __I uint32_t IO2IntStatR; __I uint32_t IO2IntStatF; __O uint32_t IO2IntClr; __IO uint32_t IO2IntEnR; __IO uint32_t IO2IntEnF; } LPC_GPIOINT_TypeDef; /*------------- Timer (TIM) --------------------------------------------------*/ typedef struct { __IO uint32_t IR; __IO uint32_t TCR; __IO uint32_t TC; __IO uint32_t PR; __IO uint32_t PC; __IO uint32_t MCR; __IO uint32_t MR0; __IO uint32_t MR1; __IO uint32_t MR2; __IO uint32_t MR3; __IO uint32_t CCR; __I uint32_t CR0; __I uint32_t CR1; uint32_t RESERVED0[2]; __IO uint32_t EMR; uint32_t RESERVED1[12]; __IO uint32_t CTCR; } LPC_TIM_TypeDef; /*------------- Pulse-Width Modulation (PWM) ---------------------------------*/ typedef struct { __IO uint32_t IR; __IO uint32_t TCR; __IO uint32_t TC; __IO uint32_t PR; __IO uint32_t PC; __IO uint32_t MCR; __IO uint32_t MR0; __IO uint32_t MR1; __IO uint32_t MR2; __IO uint32_t MR3; __IO uint32_t CCR; __I uint32_t CR0; __I uint32_t CR1; __I uint32_t CR2; __I uint32_t CR3; uint32_t RESERVED0; __IO uint32_t MR4; __IO uint32_t MR5; __IO uint32_t MR6; __IO uint32_t PCR; __IO uint32_t LER; uint32_t RESERVED1[7]; __IO uint32_t CTCR; } LPC_PWM_TypeDef; /*------------- Universal Asynchronous Receiver Transmitter (UART) -----------*/ typedef struct { union { __I uint8_t RBR; __O uint8_t THR; __IO uint8_t DLL; uint32_t RESERVED0; }; union { __IO uint8_t DLM; __IO uint32_t IER; }; union { __I uint32_t IIR; __O uint8_t FCR; }; __IO uint8_t LCR; uint8_t RESERVED1[7]; __I uint8_t LSR; uint8_t RESERVED2[7]; __IO uint8_t SCR; uint8_t RESERVED3[3]; __IO uint32_t ACR; __IO uint8_t ICR; uint8_t RESERVED4[3]; __IO uint8_t FDR; uint8_t RESERVED5[7]; __IO uint8_t TER; uint8_t RESERVED6[39]; __IO uint32_t FIFOLVL; } LPC_UART_TypeDef; typedef struct { union { __I uint8_t RBR; __O uint8_t THR; __IO uint8_t DLL; uint32_t RESERVED0; }; union { __IO uint8_t DLM; __IO uint32_t IER; }; union { __I uint32_t IIR; __O uint8_t FCR; }; __IO uint8_t LCR; uint8_t RESERVED1[7]; __I uint8_t LSR; uint8_t RESERVED2[7]; __IO uint8_t SCR; uint8_t RESERVED3[3]; __IO uint32_t ACR; __IO uint8_t ICR; uint8_t RESERVED4[3]; __IO uint8_t FDR; uint8_t RESERVED5[7]; __IO uint8_t TER; uint8_t RESERVED6[39]; __IO uint32_t FIFOLVL; } LPC_UART0_TypeDef; typedef struct { union { __I uint8_t RBR; __O uint8_t THR; __IO uint8_t DLL; uint32_t RESERVED0; }; union { __IO uint8_t DLM; __IO uint32_t IER; }; union { __I uint32_t IIR; __O uint8_t FCR; }; __IO uint8_t LCR; uint8_t RESERVED1[3]; __IO uint8_t MCR; uint8_t RESERVED2[3]; __I uint8_t LSR; uint8_t RESERVED3[3]; __I uint8_t MSR; uint8_t RESERVED4[3]; __IO uint8_t SCR; uint8_t RESERVED5[3]; __IO uint32_t ACR; uint32_t RESERVED6; __IO uint32_t FDR; uint32_t RESERVED7; __IO uint8_t TER; uint8_t RESERVED8[27]; __IO uint8_t RS485CTRL; uint8_t RESERVED9[3]; __IO uint8_t ADRMATCH; uint8_t RESERVED10[3]; __IO uint8_t RS485DLY; uint8_t RESERVED11[3]; __IO uint32_t FIFOLVL; } LPC_UART1_TypeDef; /*------------- Serial Peripheral Interface (SPI) ----------------------------*/ typedef struct { __IO uint32_t SPCR; __I uint32_t SPSR; __IO uint32_t SPDR; __IO uint32_t SPCCR; uint32_t RESERVED0[3]; __IO uint32_t SPINT; } LPC_SPI_TypeDef; /*------------- Synchronous Serial Communication (SSP) -----------------------*/ typedef struct { __IO uint32_t CR0; __IO uint32_t CR1; __IO uint32_t DR; __I uint32_t SR; __IO uint32_t CPSR; __IO uint32_t IMSC; __IO uint32_t RIS; __IO uint32_t MIS; __IO uint32_t ICR; __IO uint32_t DMACR; } LPC_SSP_TypeDef; /*------------- Inter-Integrated Circuit (I2C) -------------------------------*/ typedef struct { __IO uint32_t I2CONSET; __I uint32_t I2STAT; __IO uint32_t I2DAT; __IO uint32_t I2ADR0; __IO uint32_t I2SCLH; __IO uint32_t I2SCLL; __O uint32_t I2CONCLR; __IO uint32_t MMCTRL; __IO uint32_t I2ADR1; __IO uint32_t I2ADR2; __IO uint32_t I2ADR3; __I uint32_t I2DATA_BUFFER; __IO uint32_t I2MASK0; __IO uint32_t I2MASK1; __IO uint32_t I2MASK2; __IO uint32_t I2MASK3; } LPC_I2C_TypeDef; /*------------- Inter IC Sound (I2S) -----------------------------------------*/ typedef struct { __IO uint32_t I2SDAO; __IO uint32_t I2SDAI; __O uint32_t I2STXFIFO; __I uint32_t I2SRXFIFO; __I uint32_t I2SSTATE; __IO uint32_t I2SDMA1; __IO uint32_t I2SDMA2; __IO uint32_t I2SIRQ; __IO uint32_t I2STXRATE; __IO uint32_t I2SRXRATE; __IO uint32_t I2STXBITRATE; __IO uint32_t I2SRXBITRATE; __IO uint32_t I2STXMODE; __IO uint32_t I2SRXMODE; } LPC_I2S_TypeDef; /*------------- Repetitive Interrupt Timer (RIT) -----------------------------*/ typedef struct { __IO uint32_t RICOMPVAL; __IO uint32_t RIMASK; __IO uint8_t RICTRL; uint8_t RESERVED0[3]; __IO uint32_t RICOUNTER; } LPC_RIT_TypeDef; /*------------- Real-Time Clock (RTC) ----------------------------------------*/ typedef struct { __IO uint8_t ILR; uint8_t RESERVED0[7]; __IO uint8_t CCR; uint8_t RESERVED1[3]; __IO uint8_t CIIR; uint8_t RESERVED2[3]; __IO uint8_t AMR; uint8_t RESERVED3[3]; __I uint32_t CTIME0; __I uint32_t CTIME1; __I uint32_t CTIME2; __IO uint8_t SEC; uint8_t RESERVED4[3]; __IO uint8_t MIN; uint8_t RESERVED5[3]; __IO uint8_t HOUR; uint8_t RESERVED6[3]; __IO uint8_t DOM; uint8_t RESERVED7[3]; __IO uint8_t DOW; uint8_t RESERVED8[3]; __IO uint16_t DOY; uint16_t RESERVED9; __IO uint8_t MONTH; uint8_t RESERVED10[3]; __IO uint16_t YEAR; uint16_t RESERVED11; __IO uint32_t CALIBRATION; __IO uint32_t GPREG0; __IO uint32_t GPREG1; __IO uint32_t GPREG2; __IO uint32_t GPREG3; __IO uint32_t GPREG4; __IO uint8_t RTC_AUXEN; uint8_t RESERVED12[3]; __IO uint8_t RTC_AUX; uint8_t RESERVED13[3]; __IO uint8_t ALSEC; uint8_t RESERVED14[3]; __IO uint8_t ALMIN; uint8_t RESERVED15[3]; __IO uint8_t ALHOUR; uint8_t RESERVED16[3]; __IO uint8_t ALDOM; uint8_t RESERVED17[3]; __IO uint8_t ALDOW; uint8_t RESERVED18[3]; __IO uint16_t ALDOY; uint16_t RESERVED19; __IO uint8_t ALMON; uint8_t RESERVED20[3]; __IO uint16_t ALYEAR; uint16_t RESERVED21; } LPC_RTC_TypeDef; /*------------- Watchdog Timer (WDT) -----------------------------------------*/ typedef struct { __IO uint8_t WDMOD; uint8_t RESERVED0[3]; __IO uint32_t WDTC; __O uint8_t WDFEED; uint8_t RESERVED1[3]; __I uint32_t WDTV; __IO uint32_t WDCLKSEL; } LPC_WDT_TypeDef; /*------------- Analog-to-Digital Converter (ADC) ----------------------------*/ typedef struct { __IO uint32_t ADCR; __IO uint32_t ADGDR; uint32_t RESERVED0; __IO uint32_t ADINTEN; __I uint32_t ADDR0; __I uint32_t ADDR1; __I uint32_t ADDR2; __I uint32_t ADDR3; __I uint32_t ADDR4; __I uint32_t ADDR5; __I uint32_t ADDR6; __I uint32_t ADDR7; __I uint32_t ADSTAT; __IO uint32_t ADTRM; } LPC_ADC_TypeDef; /*------------- Digital-to-Analog Converter (DAC) ----------------------------*/ typedef struct { __IO uint32_t DACR; __IO uint32_t DACCTRL; __IO uint16_t DACCNTVAL; } LPC_DAC_TypeDef; /*------------- Motor Control Pulse-Width Modulation (MCPWM) -----------------*/ typedef struct { __I uint32_t MCCON; __O uint32_t MCCON_SET; __O uint32_t MCCON_CLR; __I uint32_t MCCAPCON; __O uint32_t MCCAPCON_SET; __O uint32_t MCCAPCON_CLR; __IO uint32_t MCTIM0; __IO uint32_t MCTIM1; __IO uint32_t MCTIM2; __IO uint32_t MCPER0; __IO uint32_t MCPER1; __IO uint32_t MCPER2; __IO uint32_t MCPW0; __IO uint32_t MCPW1; __IO uint32_t MCPW2; __IO uint32_t MCDEADTIME; __IO uint32_t MCCCP; __IO uint32_t MCCR0; __IO uint32_t MCCR1; __IO uint32_t MCCR2; __I uint32_t MCINTEN; __O uint32_t MCINTEN_SET; __O uint32_t MCINTEN_CLR; __I uint32_t MCCNTCON; __O uint32_t MCCNTCON_SET; __O uint32_t MCCNTCON_CLR; __I uint32_t MCINTFLAG; __O uint32_t MCINTFLAG_SET; __O uint32_t MCINTFLAG_CLR; __O uint32_t MCCAP_CLR; } LPC_MCPWM_TypeDef; /*------------- Quadrature Encoder Interface (QEI) ---------------------------*/ typedef struct { __O uint32_t QEICON; __I uint32_t QEISTAT; __IO uint32_t QEICONF; __I uint32_t QEIPOS; __IO uint32_t QEIMAXPOS; __IO uint32_t CMPOS0; __IO uint32_t CMPOS1; __IO uint32_t CMPOS2; __I uint32_t INXCNT; __IO uint32_t INXCMP; __IO uint32_t QEILOAD; __I uint32_t QEITIME; __I uint32_t QEIVEL; __I uint32_t QEICAP; __IO uint32_t VELCOMP; __IO uint32_t FILTER; uint32_t RESERVED0[998]; __O uint32_t QEIIEC; __O uint32_t QEIIES; __I uint32_t QEIINTSTAT; __I uint32_t QEIIE; __O uint32_t QEICLR; __O uint32_t QEISET; } LPC_QEI_TypeDef; /*------------- Controller Area Network (CAN) --------------------------------*/ typedef struct { __IO uint32_t mask[512]; /* ID Masks */ } LPC_CANAF_RAM_TypeDef; typedef struct /* Acceptance Filter Registers */ { __IO uint32_t AFMR; __IO uint32_t SFF_sa; __IO uint32_t SFF_GRP_sa; __IO uint32_t EFF_sa; __IO uint32_t EFF_GRP_sa; __IO uint32_t ENDofTable; __I uint32_t LUTerrAd; __I uint32_t LUTerr; __IO uint32_t FCANIE; __IO uint32_t FCANIC0; __IO uint32_t FCANIC1; } LPC_CANAF_TypeDef; typedef struct /* Central Registers */ { __I uint32_t CANTxSR; __I uint32_t CANRxSR; __I uint32_t CANMSR; } LPC_CANCR_TypeDef; typedef struct /* Controller Registers */ { __IO uint32_t MOD; __O uint32_t CMR; __IO uint32_t GSR; __I uint32_t ICR; __IO uint32_t IER; __IO uint32_t BTR; __IO uint32_t EWL; __I uint32_t SR; __IO uint32_t RFS; __IO uint32_t RID; __IO uint32_t RDA; __IO uint32_t RDB; __IO uint32_t TFI1; __IO uint32_t TID1; __IO uint32_t TDA1; __IO uint32_t TDB1; __IO uint32_t TFI2; __IO uint32_t TID2; __IO uint32_t TDA2; __IO uint32_t TDB2; __IO uint32_t TFI3; __IO uint32_t TID3; __IO uint32_t TDA3; __IO uint32_t TDB3; } LPC_CAN_TypeDef; /*------------- General Purpose Direct Memory Access (GPDMA) -----------------*/ typedef struct /* Common Registers */ { __I uint32_t DMACIntStat; __I uint32_t DMACIntTCStat; __O uint32_t DMACIntTCClear; __I uint32_t DMACIntErrStat; __O uint32_t DMACIntErrClr; __I uint32_t DMACRawIntTCStat; __I uint32_t DMACRawIntErrStat; __I uint32_t DMACEnbldChns; __IO uint32_t DMACSoftBReq; __IO uint32_t DMACSoftSReq; __IO uint32_t DMACSoftLBReq; __IO uint32_t DMACSoftLSReq; __IO uint32_t DMACConfig; __IO uint32_t DMACSync; } LPC_GPDMA_TypeDef; typedef struct /* Channel Registers */ { __IO uint32_t DMACCSrcAddr; __IO uint32_t DMACCDestAddr; __IO uint32_t DMACCLLI; __IO uint32_t DMACCControl; __IO uint32_t DMACCConfig; } LPC_GPDMACH_TypeDef; /*------------- Universal Serial Bus (USB) -----------------------------------*/ typedef struct { __I uint32_t HcRevision; /* USB Host Registers */ __IO uint32_t HcControl; __IO uint32_t HcCommandStatus; __IO uint32_t HcInterruptStatus; __IO uint32_t HcInterruptEnable; __IO uint32_t HcInterruptDisable; __IO uint32_t HcHCCA; __I uint32_t HcPeriodCurrentED; __IO uint32_t HcControlHeadED; __IO uint32_t HcControlCurrentED; __IO uint32_t HcBulkHeadED; __IO uint32_t HcBulkCurrentED; __I uint32_t HcDoneHead; __IO uint32_t HcFmInterval; __I uint32_t HcFmRemaining; __I uint32_t HcFmNumber; __IO uint32_t HcPeriodicStart; __IO uint32_t HcLSTreshold; __IO uint32_t HcRhDescriptorA; __IO uint32_t HcRhDescriptorB; __IO uint32_t HcRhStatus; __IO uint32_t HcRhPortStatus1; __IO uint32_t HcRhPortStatus2; uint32_t RESERVED0[40]; __I uint32_t Module_ID; __I uint32_t OTGIntSt; /* USB On-The-Go Registers */ __IO uint32_t OTGIntEn; __O uint32_t OTGIntSet; __O uint32_t OTGIntClr; __IO uint32_t OTGStCtrl; __IO uint32_t OTGTmr; uint32_t RESERVED1[58]; __I uint32_t USBDevIntSt; /* USB Device Interrupt Registers */ __IO uint32_t USBDevIntEn; __O uint32_t USBDevIntClr; __O uint32_t USBDevIntSet; __O uint32_t USBCmdCode; /* USB Device SIE Command Registers */ __I uint32_t USBCmdData; __I uint32_t USBRxData; /* USB Device Transfer Registers */ __O uint32_t USBTxData; __I uint32_t USBRxPLen; __O uint32_t USBTxPLen; __IO uint32_t USBCtrl; __O uint32_t USBDevIntPri; __I uint32_t USBEpIntSt; /* USB Device Endpoint Interrupt Regs */ __IO uint32_t USBEpIntEn; __O uint32_t USBEpIntClr; __O uint32_t USBEpIntSet; __O uint32_t USBEpIntPri; __IO uint32_t USBReEp; /* USB Device Endpoint Realization Reg*/ __O uint32_t USBEpInd; __IO uint32_t USBMaxPSize; __I uint32_t USBDMARSt; /* USB Device DMA Registers */ __O uint32_t USBDMARClr; __O uint32_t USBDMARSet; uint32_t RESERVED2[9]; __IO uint32_t USBUDCAH; __I uint32_t USBEpDMASt; __O uint32_t USBEpDMAEn; __O uint32_t USBEpDMADis; __I uint32_t USBDMAIntSt; __IO uint32_t USBDMAIntEn; uint32_t RESERVED3[2]; __I uint32_t USBEoTIntSt; __O uint32_t USBEoTIntClr; __O uint32_t USBEoTIntSet; __I uint32_t USBNDDRIntSt; __O uint32_t USBNDDRIntClr; __O uint32_t USBNDDRIntSet; __I uint32_t USBSysErrIntSt; __O uint32_t USBSysErrIntClr; __O uint32_t USBSysErrIntSet; uint32_t RESERVED4[15]; union { __I uint32_t I2C_RX; /* USB OTG I2C Registers */ __O uint32_t I2C_TX; }; __I uint32_t I2C_STS; __IO uint32_t I2C_CTL; __IO uint32_t I2C_CLKHI; __O uint32_t I2C_CLKLO; uint32_t RESERVED5[824]; union { __IO uint32_t USBClkCtrl; /* USB Clock Control Registers */ __IO uint32_t OTGClkCtrl; }; union { __I uint32_t USBClkSt; __I uint32_t OTGClkSt; }; } LPC_USB_TypeDef; /*------------- Ethernet Media Access Controller (EMAC) ----------------------*/ typedef struct { __IO uint32_t MAC1; /* MAC Registers */ __IO uint32_t MAC2; __IO uint32_t IPGT; __IO uint32_t IPGR; __IO uint32_t CLRT; __IO uint32_t MAXF; __IO uint32_t SUPP; __IO uint32_t TEST; __IO uint32_t MCFG; __IO uint32_t MCMD; __IO uint32_t MADR; __O uint32_t MWTD; __I uint32_t MRDD; __I uint32_t MIND; uint32_t RESERVED0[2]; __IO uint32_t SA0; __IO uint32_t SA1; __IO uint32_t SA2; uint32_t RESERVED1[45]; __IO uint32_t Command; /* Control Registers */ __I uint32_t Status; __IO uint32_t RxDescriptor; __IO uint32_t RxStatus; __IO uint32_t RxDescriptorNumber; __I uint32_t RxProduceIndex; __IO uint32_t RxConsumeIndex; __IO uint32_t TxDescriptor; __IO uint32_t TxStatus; __IO uint32_t TxDescriptorNumber; __IO uint32_t TxProduceIndex; __I uint32_t TxConsumeIndex; uint32_t RESERVED2[10]; __I uint32_t TSV0; __I uint32_t TSV1; __I uint32_t RSV; uint32_t RESERVED3[3]; __IO uint32_t FlowControlCounter; __I uint32_t FlowControlStatus; uint32_t RESERVED4[34]; __IO uint32_t RxFilterCtrl; /* Rx Filter Registers */ __IO uint32_t RxFilterWoLStatus; __IO uint32_t RxFilterWoLClear; uint32_t RESERVED5; __IO uint32_t HashFilterL; __IO uint32_t HashFilterH; uint32_t RESERVED6[882]; __I uint32_t IntStatus; /* Module Control Registers */ __IO uint32_t IntEnable; __O uint32_t IntClear; __O uint32_t IntSet; uint32_t RESERVED7; __IO uint32_t PowerDown; uint32_t RESERVED8; __IO uint32_t Module_ID; } LPC_EMAC_TypeDef; #if defined ( __CC_ARM ) #pragma no_anon_unions #endif /******************************************************************************/ /* Peripheral memory map */ /******************************************************************************/ /* Base addresses */ #define LPC_FLASH_BASE (0x00000000UL) #define LPC_RAM_BASE (0x10000000UL) #define LPC_GPIO_BASE (0x2009C000UL) #define LPC_APB0_BASE (0x40000000UL) #define LPC_APB1_BASE (0x40080000UL) #define LPC_AHB_BASE (0x50000000UL) #define LPC_CM3_BASE (0xE0000000UL) /* APB0 peripherals */ #define LPC_WDT_BASE (LPC_APB0_BASE + 0x00000) #define LPC_TIM0_BASE (LPC_APB0_BASE + 0x04000) #define LPC_TIM1_BASE (LPC_APB0_BASE + 0x08000) #define LPC_UART0_BASE (LPC_APB0_BASE + 0x0C000) #define LPC_UART1_BASE (LPC_APB0_BASE + 0x10000) #define LPC_PWM1_BASE (LPC_APB0_BASE + 0x18000) #define LPC_I2C0_BASE (LPC_APB0_BASE + 0x1C000) #define LPC_SPI_BASE (LPC_APB0_BASE + 0x20000) #define LPC_RTC_BASE (LPC_APB0_BASE + 0x24000) #define LPC_GPIOINT_BASE (LPC_APB0_BASE + 0x28080) #define LPC_PINCON_BASE (LPC_APB0_BASE + 0x2C000) #define LPC_SSP1_BASE (LPC_APB0_BASE + 0x30000) #define LPC_ADC_BASE (LPC_APB0_BASE + 0x34000) #define LPC_CANAF_RAM_BASE (LPC_APB0_BASE + 0x38000) #define LPC_CANAF_BASE (LPC_APB0_BASE + 0x3C000) #define LPC_CANCR_BASE (LPC_APB0_BASE + 0x40000) #define LPC_CAN1_BASE (LPC_APB0_BASE + 0x44000) #define LPC_CAN2_BASE (LPC_APB0_BASE + 0x48000) #define LPC_I2C1_BASE (LPC_APB0_BASE + 0x5C000) /* APB1 peripherals */ #define LPC_SSP0_BASE (LPC_APB1_BASE + 0x08000) #define LPC_DAC_BASE (LPC_APB1_BASE + 0x0C000) #define LPC_TIM2_BASE (LPC_APB1_BASE + 0x10000) #define LPC_TIM3_BASE (LPC_APB1_BASE + 0x14000) #define LPC_UART2_BASE (LPC_APB1_BASE + 0x18000) #define LPC_UART3_BASE (LPC_APB1_BASE + 0x1C000) #define LPC_I2C2_BASE (LPC_APB1_BASE + 0x20000) #define LPC_I2S_BASE (LPC_APB1_BASE + 0x28000) #define LPC_RIT_BASE (LPC_APB1_BASE + 0x30000) #define LPC_MCPWM_BASE (LPC_APB1_BASE + 0x38000) #define LPC_QEI_BASE (LPC_APB1_BASE + 0x3C000) #define LPC_SC_BASE (LPC_APB1_BASE + 0x7C000) /* AHB peripherals */ #define LPC_EMAC_BASE (LPC_AHB_BASE + 0x00000) #define LPC_GPDMA_BASE (LPC_AHB_BASE + 0x04000) #define LPC_GPDMACH0_BASE (LPC_AHB_BASE + 0x04100) #define LPC_GPDMACH1_BASE (LPC_AHB_BASE + 0x04120) #define LPC_GPDMACH2_BASE (LPC_AHB_BASE + 0x04140) #define LPC_GPDMACH3_BASE (LPC_AHB_BASE + 0x04160) #define LPC_GPDMACH4_BASE (LPC_AHB_BASE + 0x04180) #define LPC_GPDMACH5_BASE (LPC_AHB_BASE + 0x041A0) #define LPC_GPDMACH6_BASE (LPC_AHB_BASE + 0x041C0) #define LPC_GPDMACH7_BASE (LPC_AHB_BASE + 0x041E0) #define LPC_USB_BASE (LPC_AHB_BASE + 0x0C000) /* GPIOs */ #define LPC_GPIO0_BASE (LPC_GPIO_BASE + 0x00000) #define LPC_GPIO1_BASE (LPC_GPIO_BASE + 0x00020) #define LPC_GPIO2_BASE (LPC_GPIO_BASE + 0x00040) #define LPC_GPIO3_BASE (LPC_GPIO_BASE + 0x00060) #define LPC_GPIO4_BASE (LPC_GPIO_BASE + 0x00080) /******************************************************************************/ /* Peripheral declaration */ /******************************************************************************/ #define LPC_SC ((LPC_SC_TypeDef *) LPC_SC_BASE ) #define LPC_GPIO0 ((LPC_GPIO_TypeDef *) LPC_GPIO0_BASE ) #define LPC_GPIO1 ((LPC_GPIO_TypeDef *) LPC_GPIO1_BASE ) #define LPC_GPIO2 ((LPC_GPIO_TypeDef *) LPC_GPIO2_BASE ) #define LPC_GPIO3 ((LPC_GPIO_TypeDef *) LPC_GPIO3_BASE ) #define LPC_GPIO4 ((LPC_GPIO_TypeDef *) LPC_GPIO4_BASE ) #define LPC_WDT ((LPC_WDT_TypeDef *) LPC_WDT_BASE ) #define LPC_TIM0 ((LPC_TIM_TypeDef *) LPC_TIM0_BASE ) #define LPC_TIM1 ((LPC_TIM_TypeDef *) LPC_TIM1_BASE ) #define LPC_TIM2 ((LPC_TIM_TypeDef *) LPC_TIM2_BASE ) #define LPC_TIM3 ((LPC_TIM_TypeDef *) LPC_TIM3_BASE ) #define LPC_RIT ((LPC_RIT_TypeDef *) LPC_RIT_BASE ) #define LPC_UART0 ((LPC_UART0_TypeDef *) LPC_UART0_BASE ) #define LPC_UART1 ((LPC_UART1_TypeDef *) LPC_UART1_BASE ) #define LPC_UART2 ((LPC_UART_TypeDef *) LPC_UART2_BASE ) #define LPC_UART3 ((LPC_UART_TypeDef *) LPC_UART3_BASE ) #define LPC_PWM1 ((LPC_PWM_TypeDef *) LPC_PWM1_BASE ) #define LPC_I2C0 ((LPC_I2C_TypeDef *) LPC_I2C0_BASE ) #define LPC_I2C1 ((LPC_I2C_TypeDef *) LPC_I2C1_BASE ) #define LPC_I2C2 ((LPC_I2C_TypeDef *) LPC_I2C2_BASE ) #define LPC_I2S ((LPC_I2S_TypeDef *) LPC_I2S_BASE ) #define LPC_SPI ((LPC_SPI_TypeDef *) LPC_SPI_BASE ) #define LPC_RTC ((LPC_RTC_TypeDef *) LPC_RTC_BASE ) #define LPC_GPIOINT ((LPC_GPIOINT_TypeDef *) LPC_GPIOINT_BASE ) #define LPC_PINCON ((LPC_PINCON_TypeDef *) LPC_PINCON_BASE ) #define LPC_SSP0 ((LPC_SSP_TypeDef *) LPC_SSP0_BASE ) #define LPC_SSP1 ((LPC_SSP_TypeDef *) LPC_SSP1_BASE ) #define LPC_ADC ((LPC_ADC_TypeDef *) LPC_ADC_BASE ) #define LPC_DAC ((LPC_DAC_TypeDef *) LPC_DAC_BASE ) #define LPC_CANAF_RAM ((LPC_CANAF_RAM_TypeDef *) LPC_CANAF_RAM_BASE) #define LPC_CANAF ((LPC_CANAF_TypeDef *) LPC_CANAF_BASE ) #define LPC_CANCR ((LPC_CANCR_TypeDef *) LPC_CANCR_BASE ) #define LPC_CAN1 ((LPC_CAN_TypeDef *) LPC_CAN1_BASE ) #define LPC_CAN2 ((LPC_CAN_TypeDef *) LPC_CAN2_BASE ) #define LPC_MCPWM ((LPC_MCPWM_TypeDef *) LPC_MCPWM_BASE ) #define LPC_QEI ((LPC_QEI_TypeDef *) LPC_QEI_BASE ) #define LPC_EMAC ((LPC_EMAC_TypeDef *) LPC_EMAC_BASE ) #define LPC_GPDMA ((LPC_GPDMA_TypeDef *) LPC_GPDMA_BASE ) #define LPC_GPDMACH0 ((LPC_GPDMACH_TypeDef *) LPC_GPDMACH0_BASE ) #define LPC_GPDMACH1 ((LPC_GPDMACH_TypeDef *) LPC_GPDMACH1_BASE ) #define LPC_GPDMACH2 ((LPC_GPDMACH_TypeDef *) LPC_GPDMACH2_BASE ) #define LPC_GPDMACH3 ((LPC_GPDMACH_TypeDef *) LPC_GPDMACH3_BASE ) #define LPC_GPDMACH4 ((LPC_GPDMACH_TypeDef *) LPC_GPDMACH4_BASE ) #define LPC_GPDMACH5 ((LPC_GPDMACH_TypeDef *) LPC_GPDMACH5_BASE ) #define LPC_GPDMACH6 ((LPC_GPDMACH_TypeDef *) LPC_GPDMACH6_BASE ) #define LPC_GPDMACH7 ((LPC_GPDMACH_TypeDef *) LPC_GPDMACH7_BASE ) #define LPC_USB ((LPC_USB_TypeDef *) LPC_USB_BASE ) #endif // __LPC17xx_H__ ================================================ FILE: Zelig/mbed/TARGET_LPC1768/TARGET_NXP/TARGET_LPC176X/PeripheralNames.h ================================================ /* mbed Microcontroller Library * Copyright (c) 2006-2013 ARM Limited * * 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 MBED_PERIPHERALNAMES_H #define MBED_PERIPHERALNAMES_H #include "cmsis.h" #include "PinNames.h" #ifdef __cplusplus extern "C" { #endif typedef enum { UART_0 = (int)LPC_UART0_BASE, UART_1 = (int)LPC_UART1_BASE, UART_2 = (int)LPC_UART2_BASE, UART_3 = (int)LPC_UART3_BASE } UARTName; typedef enum { ADC0_0 = 0, ADC0_1, ADC0_2, ADC0_3, ADC0_4, ADC0_5, ADC0_6, ADC0_7 } ADCName; typedef enum { DAC_0 = 0 } DACName; typedef enum { SPI_0 = (int)LPC_SSP0_BASE, SPI_1 = (int)LPC_SSP1_BASE } SPIName; typedef enum { I2C_0 = (int)LPC_I2C0_BASE, I2C_1 = (int)LPC_I2C1_BASE, I2C_2 = (int)LPC_I2C2_BASE } I2CName; typedef enum { PWM_1 = 1, PWM_2, PWM_3, PWM_4, PWM_5, PWM_6 } PWMName; typedef enum { CAN_1 = (int)LPC_CAN1_BASE, CAN_2 = (int)LPC_CAN2_BASE } CANName; #define STDIO_UART_TX USBTX #define STDIO_UART_RX USBRX #define STDIO_UART UART_0 // Default peripherals #define MBED_SPI0 p5, p6, p7, p8 #define MBED_SPI1 p11, p12, p13, p14 #define MBED_UART0 p9, p10 #define MBED_UART1 p13, p14 #define MBED_UART2 p28, p27 #define MBED_UARTUSB USBTX, USBRX #define MBED_I2C0 p28, p27 #define MBED_I2C1 p9, p10 #define MBED_CAN0 p30, p29 #define MBED_ANALOGOUT0 p18 #define MBED_ANALOGIN0 p15 #define MBED_ANALOGIN1 p16 #define MBED_ANALOGIN2 p17 #define MBED_ANALOGIN3 p18 #define MBED_ANALOGIN4 p19 #define MBED_ANALOGIN5 p20 #define MBED_PWMOUT0 p26 #define MBED_PWMOUT1 p25 #define MBED_PWMOUT2 p24 #define MBED_PWMOUT3 p23 #define MBED_PWMOUT4 p22 #define MBED_PWMOUT5 p21 #ifdef __cplusplus } #endif #endif ================================================ FILE: Zelig/mbed/TARGET_LPC1768/TARGET_NXP/TARGET_LPC176X/PortNames.h ================================================ /* mbed Microcontroller Library * Copyright (c) 2006-2013 ARM Limited * * 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 MBED_PORTNAMES_H #define MBED_PORTNAMES_H #ifdef __cplusplus extern "C" { #endif typedef enum { Port0 = 0, Port1 = 1, Port2 = 2, Port3 = 3, Port4 = 4 } PortName; #ifdef __cplusplus } #endif #endif ================================================ FILE: Zelig/mbed/TARGET_LPC1768/TARGET_NXP/TARGET_LPC176X/TARGET_MBED_LPC1768/PinNames.h ================================================ /* mbed Microcontroller Library * Copyright (c) 2006-2013 ARM Limited * * 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 MBED_PINNAMES_H #define MBED_PINNAMES_H #include "cmsis.h" #ifdef __cplusplus extern "C" { #endif typedef enum { PIN_INPUT, PIN_OUTPUT } PinDirection; #define PORT_SHIFT 5 typedef enum { // LPC Pin Names P0_0 = LPC_GPIO0_BASE, P0_1, P0_2, P0_3, P0_4, P0_5, P0_6, P0_7, P0_8, P0_9, P0_10, P0_11, P0_12, P0_13, P0_14, P0_15, P0_16, P0_17, P0_18, P0_19, P0_20, P0_21, P0_22, P0_23, P0_24, P0_25, P0_26, P0_27, P0_28, P0_29, P0_30, P0_31, P1_0, P1_1, P1_2, P1_3, P1_4, P1_5, P1_6, P1_7, P1_8, P1_9, P1_10, P1_11, P1_12, P1_13, P1_14, P1_15, P1_16, P1_17, P1_18, P1_19, P1_20, P1_21, P1_22, P1_23, P1_24, P1_25, P1_26, P1_27, P1_28, P1_29, P1_30, P1_31, P2_0, P2_1, P2_2, P2_3, P2_4, P2_5, P2_6, P2_7, P2_8, P2_9, P2_10, P2_11, P2_12, P2_13, P2_14, P2_15, P2_16, P2_17, P2_18, P2_19, P2_20, P2_21, P2_22, P2_23, P2_24, P2_25, P2_26, P2_27, P2_28, P2_29, P2_30, P2_31, P3_0, P3_1, P3_2, P3_3, P3_4, P3_5, P3_6, P3_7, P3_8, P3_9, P3_10, P3_11, P3_12, P3_13, P3_14, P3_15, P3_16, P3_17, P3_18, P3_19, P3_20, P3_21, P3_22, P3_23, P3_24, P3_25, P3_26, P3_27, P3_28, P3_29, P3_30, P3_31, P4_0, P4_1, P4_2, P4_3, P4_4, P4_5, P4_6, P4_7, P4_8, P4_9, P4_10, P4_11, P4_12, P4_13, P4_14, P4_15, P4_16, P4_17, P4_18, P4_19, P4_20, P4_21, P4_22, P4_23, P4_24, P4_25, P4_26, P4_27, P4_28, P4_29, P4_30, P4_31, // mbed DIP Pin Names p5 = P0_9, p6 = P0_8, p7 = P0_7, p8 = P0_6, p9 = P0_0, p10 = P0_1, p11 = P0_18, p12 = P0_17, p13 = P0_15, p14 = P0_16, p15 = P0_23, p16 = P0_24, p17 = P0_25, p18 = P0_26, p19 = P1_30, p20 = P1_31, p21 = P2_5, p22 = P2_4, p23 = P2_3, p24 = P2_2, p25 = P2_1, p26 = P2_0, p27 = P0_11, p28 = P0_10, p29 = P0_5, p30 = P0_4, // Other mbed Pin Names #ifdef MCB1700 LED1 = P1_28, LED2 = P1_29, LED3 = P1_31, LED4 = P2_2, #else LED1 = P1_18, LED2 = P1_20, LED3 = P1_21, LED4 = P1_23, #endif USBTX = P0_2, USBRX = P0_3, // Arch Pro Pin Names D0 = P4_29, D1 = P4_28, D2 = P0_4, D3 = P0_5, D4 = P2_2, D5 = P2_3, D6 = P2_4, D7 = P2_5, D8 = P0_0, D9 = P0_1, D10 = P0_6, D11 = P0_9, D12 = P0_8, D13 = P0_7, D14 = P0_27, D15 = P0_28, A0 = P0_23, A1 = P0_24, A2 = P0_25, A3 = P0_26, A4 = P1_30, A5 = P1_31, I2C_SCL = D15, I2C_SDA = D14, // Not connected NC = (int)0xFFFFFFFF } PinName; typedef enum { PullUp = 0, PullDown = 3, PullNone = 2, Repeater = 1, OpenDrain = 4, PullDefault = PullDown } PinMode; // version of PINCON_TypeDef using register arrays typedef struct { __IO uint32_t PINSEL[11]; uint32_t RESERVED0[5]; __IO uint32_t PINMODE[10]; __IO uint32_t PINMODE_OD[5]; } PINCONARRAY_TypeDef; #define PINCONARRAY ((PINCONARRAY_TypeDef *)LPC_PINCON_BASE) #ifdef __cplusplus } #endif #endif ================================================ FILE: Zelig/mbed/TARGET_LPC1768/TARGET_NXP/TARGET_LPC176X/TARGET_MBED_LPC1768/device.h ================================================ /* mbed Microcontroller Library * Copyright (c) 2006-2013 ARM Limited * * 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 MBED_DEVICE_H #define MBED_DEVICE_H #define DEVICE_PORTIN 1 #define DEVICE_PORTOUT 1 #define DEVICE_PORTINOUT 1 #define DEVICE_INTERRUPTIN 1 #define DEVICE_ANALOGIN 1 #define DEVICE_ANALOGOUT 1 #define DEVICE_SERIAL 1 #define DEVICE_SERIAL_FC 1 #define DEVICE_I2C 1 #define DEVICE_I2CSLAVE 1 #define DEVICE_SPI 1 #define DEVICE_SPISLAVE 1 #define DEVICE_CAN 1 #define DEVICE_RTC 1 #define DEVICE_ETHERNET 1 #define DEVICE_PWMOUT 1 #define DEVICE_SEMIHOST 1 #define DEVICE_LOCALFILESYSTEM 1 #define DEVICE_ID_LENGTH 32 #define DEVICE_MAC_OFFSET 20 #define DEVICE_SLEEP 1 #define DEVICE_DEBUG_AWARENESS 1 #define DEVICE_STDIO_MESSAGES 1 #define DEVICE_ERROR_PATTERN 1 #include "objects.h" #endif ================================================ FILE: Zelig/mbed/TARGET_LPC1768/TARGET_NXP/TARGET_LPC176X/TARGET_MBED_LPC1768/reserved_pins.h ================================================ // List of reserved pins for MBED LPC1768 #ifndef RESERVED_PINS_H #define RESERVED_PINS_H #define TARGET_RESERVED_PINS {} #endif ================================================ FILE: Zelig/mbed/TARGET_LPC1768/TARGET_NXP/TARGET_LPC176X/gpio_object.h ================================================ /* mbed Microcontroller Library * Copyright (c) 2006-2013 ARM Limited * * 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 MBED_GPIO_OBJECT_H #define MBED_GPIO_OBJECT_H #include "mbed_assert.h" #ifdef __cplusplus extern "C" { #endif typedef struct { PinName pin; uint32_t mask; __IO uint32_t *reg_dir; __IO uint32_t *reg_set; __IO uint32_t *reg_clr; __I uint32_t *reg_in; } gpio_t; static inline void gpio_write(gpio_t *obj, int value) { MBED_ASSERT(obj->pin != (PinName)NC); if (value) *obj->reg_set = obj->mask; else *obj->reg_clr = obj->mask; } static inline int gpio_read(gpio_t *obj) { MBED_ASSERT(obj->pin != (PinName)NC); return ((*obj->reg_in & obj->mask) ? 1 : 0); } static inline int gpio_is_connected(const gpio_t *obj) { return obj->pin != (PinName)NC; } #ifdef __cplusplus } #endif #endif ================================================ FILE: Zelig/mbed/TARGET_LPC1768/TARGET_NXP/TARGET_LPC176X/objects.h ================================================ /* mbed Microcontroller Library * Copyright (c) 2006-2013 ARM Limited * * 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 MBED_OBJECTS_H #define MBED_OBJECTS_H #include "cmsis.h" #include "PortNames.h" #include "PeripheralNames.h" #include "PinNames.h" #include "gpio_object.h" #ifdef __cplusplus extern "C" { #endif struct gpio_irq_s { uint32_t port; uint32_t pin; uint32_t ch; }; struct port_s { __IO uint32_t *reg_dir; __IO uint32_t *reg_out; __I uint32_t *reg_in; PortName port; uint32_t mask; }; struct pwmout_s { __IO uint32_t *MR; PWMName pwm; }; struct serial_s { LPC_UART_TypeDef *uart; int index; }; struct analogin_s { ADCName adc; }; struct dac_s { DACName dac; }; struct can_s { LPC_CAN_TypeDef *dev; int index; }; struct i2c_s { LPC_I2C_TypeDef *i2c; }; struct spi_s { LPC_SSP_TypeDef *spi; }; #ifdef __cplusplus } #endif #endif ================================================ FILE: Zelig/mbed/TARGET_LPC1768/TOOLCHAIN_GCC_ARM/LPC1768.ld ================================================ /* Linker script for mbed LPC1768 */ /* Linker script to configure memory regions. */ MEMORY { FLASH (rx) : ORIGIN = 0x00000000, LENGTH = 512K RAM (rwx) : ORIGIN = 0x100000C8, LENGTH = (32K - 0xC8) USB_RAM(rwx) : ORIGIN = 0x2007C000, LENGTH = 16K ETH_RAM(rwx) : ORIGIN = 0x20080000, LENGTH = 16K } /* Linker script to place sections and symbol values. Should be used together * with other linker script that defines memory regions FLASH and RAM. * It references following symbols, which must be defined in code: * Reset_Handler : Entry of reset handler * * It defines following symbols, which code can use without definition: * __exidx_start * __exidx_end * __etext * __data_start__ * __preinit_array_start * __preinit_array_end * __init_array_start * __init_array_end * __fini_array_start * __fini_array_end * __data_end__ * __bss_start__ * __bss_end__ * __end__ * end * __HeapLimit * __StackLimit * __StackTop * __stack */ ENTRY(Reset_Handler) SECTIONS { .text : { KEEP(*(.isr_vector)) *(.text*) KEEP(*(.init)) KEEP(*(.fini)) /* .ctors */ *crtbegin.o(.ctors) *crtbegin?.o(.ctors) *(EXCLUDE_FILE(*crtend?.o *crtend.o) .ctors) *(SORT(.ctors.*)) *(.ctors) /* .dtors */ *crtbegin.o(.dtors) *crtbegin?.o(.dtors) *(EXCLUDE_FILE(*crtend?.o *crtend.o) .dtors) *(SORT(.dtors.*)) *(.dtors) *(.rodata*) KEEP(*(.eh_frame*)) } > FLASH .ARM.extab : { *(.ARM.extab* .gnu.linkonce.armextab.*) } > FLASH __exidx_start = .; .ARM.exidx : { *(.ARM.exidx* .gnu.linkonce.armexidx.*) } > FLASH __exidx_end = .; __etext = .; .data : AT (__etext) { __data_start__ = .; Image$$RW_IRAM1$$Base = .; *(vtable) *(.data*) . = ALIGN(4); /* preinit data */ PROVIDE (__preinit_array_start = .); KEEP(*(.preinit_array)) PROVIDE (__preinit_array_end = .); . = ALIGN(4); /* init data */ PROVIDE (__init_array_start = .); KEEP(*(SORT(.init_array.*))) KEEP(*(.init_array)) PROVIDE (__init_array_end = .); . = ALIGN(4); /* finit data */ PROVIDE (__fini_array_start = .); KEEP(*(SORT(.fini_array.*))) KEEP(*(.fini_array)) PROVIDE (__fini_array_end = .); . = ALIGN(4); /* All data end */ __data_end__ = .; } > RAM .bss : { __bss_start__ = .; *(.bss*) *(COMMON) __bss_end__ = .; Image$$RW_IRAM1$$ZI$$Limit = . ; } > RAM .heap : { __end__ = .; end = __end__; *(.heap*) __HeapLimit = .; } > RAM /* .stack_dummy section doesn't contains any symbols. It is only * used for linker to calculate size of stack sections, and assign * values to stack symbols later */ .stack_dummy : { *(.stack) } > RAM /* * The section '.managed_exception_thread' is a LLILUM Specific addition to pad * the stack space at the bottom with enough space to build a managed array. * Assuming that the stack bottom (_StackLimit) is 8 bytes aligned, we add * 16 bytes that will contain the array ObjectHeader and the length member (see * ArrayImpl.cs). This way we do preserve stack alignment. */ .stack_dummy_managed_exception_thread : { *(.managed_exception_thread) } > RAM /* Set stack top to end of RAM, and stack limit move down by * size of stack_dummy section */ __StackTop = ORIGIN(RAM) + LENGTH(RAM); __StackLimit = __StackTop - SIZEOF(.stack_dummy) + SIZEOF(.stack_dummy_managed_exception_thread); PROVIDE(__stack = __StackTop); /* Check if data + heap + stack exceeds RAM limit */ ASSERT(__StackLimit >= __HeapLimit, "region RAM overflowed with stack") /* Code can explicitly ask for data to be placed in these higher RAM banks where they will be left uninitialized. */ .AHBSRAM0 (NOLOAD): { Image$$RW_IRAM2$$Base = . ; *(AHBSRAM0) Image$$RW_IRAM2$$ZI$$Limit = .; } > USB_RAM .AHBSRAM1 (NOLOAD): { Image$$RW_IRAM3$$Base = . ; *(AHBSRAM1) Image$$RW_IRAM3$$ZI$$Limit = .; } > ETH_RAM } ================================================ FILE: Zelig/mbed/TARGET_LPC1768/cmsis.h ================================================ /* mbed Microcontroller Library - CMSIS * Copyright (C) 2009-2011 ARM Limited. All rights reserved. * * A generic CMSIS include header, pulling in LPC1768 specifics */ #ifndef MBED_CMSIS_H #define MBED_CMSIS_H #include "LPC17xx.h" #include "cmsis_nvic.h" #endif ================================================ FILE: Zelig/mbed/TARGET_LPC1768/cmsis_nvic.h ================================================ /* mbed Microcontroller Library * CMSIS-style functionality to support dynamic vectors ******************************************************************************* * Copyright (c) 2011 ARM Limited. All rights reserved. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * 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 ARM Limited 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. ******************************************************************************* */ #ifndef MBED_CMSIS_NVIC_H #define MBED_CMSIS_NVIC_H #include "cmsis.h" #define NVIC_NUM_VECTORS (16 + 33) #define NVIC_USER_IRQ_OFFSET 16 #ifdef __cplusplus extern "C" { #endif void NVIC_SetVector(IRQn_Type IRQn, uint32_t vector); uint32_t NVIC_GetVector(IRQn_Type IRQn); #ifdef __cplusplus } #endif #endif ================================================ FILE: Zelig/mbed/TARGET_LPC1768/core_ca9.h ================================================ /**************************************************************************//** * @file core_ca9.h * @brief CMSIS Cortex-A9 Core Peripheral Access Layer Header File * @version * @date 25 March 2013 * * @note * ******************************************************************************/ /* Copyright (c) 2009 - 2012 ARM LIMITED All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: - Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. - Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. - Neither the name of ARM 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 COPYRIGHT HOLDERS AND 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. ---------------------------------------------------------------------------*/ #if defined ( __ICCARM__ ) #pragma system_include /* treat file as system include file for MISRA check */ #endif #ifdef __cplusplus extern "C" { #endif #ifndef __CORE_CA9_H_GENERIC #define __CORE_CA9_H_GENERIC /** \page CMSIS_MISRA_Exceptions MISRA-C:2004 Compliance Exceptions CMSIS violates the following MISRA-C:2004 rules: \li Required Rule 8.5, object/function definition in header file.
Function definitions in header files are used to allow 'inlining'. \li Required Rule 18.4, declaration of union type or object of union type: '{...}'.
Unions are used for effective representation of core registers. \li Advisory Rule 19.7, Function-like macro defined.
Function-like macros are used to allow more efficient code. */ /******************************************************************************* * CMSIS definitions ******************************************************************************/ /** \ingroup Cortex_A9 @{ */ /* CMSIS CA9 definitions */ #define __CA9_CMSIS_VERSION_MAIN (0x03) /*!< [31:16] CMSIS HAL main version */ #define __CA9_CMSIS_VERSION_SUB (0x10) /*!< [15:0] CMSIS HAL sub version */ #define __CA9_CMSIS_VERSION ((__CA9_CMSIS_VERSION_MAIN << 16) | \ __CA9_CMSIS_VERSION_SUB ) /*!< CMSIS HAL version number */ #define __CORTEX_A (0x09) /*!< Cortex-A Core */ #if defined ( __CC_ARM ) #define __ASM __asm /*!< asm keyword for ARM Compiler */ #define __INLINE __inline /*!< inline keyword for ARM Compiler */ #define __STATIC_INLINE static __inline #define __STATIC_ASM static __asm #elif defined ( __ICCARM__ ) #define __ASM __asm /*!< asm keyword for IAR Compiler */ #define __INLINE inline /*!< inline keyword for IAR Compiler. Only available in High optimization mode! */ #define __STATIC_INLINE static inline #define __STATIC_ASM static __asm #elif defined ( __TMS470__ ) #define __ASM __asm /*!< asm keyword for TI CCS Compiler */ #define __STATIC_INLINE static inline #define __STATIC_ASM static __asm #elif defined ( __GNUC__ ) #define __ASM __asm /*!< asm keyword for GNU Compiler */ #define __INLINE inline /*!< inline keyword for GNU Compiler */ #define __STATIC_INLINE static inline #define __STATIC_ASM static __asm #elif defined ( __TASKING__ ) #define __ASM __asm /*!< asm keyword for TASKING Compiler */ #define __INLINE inline /*!< inline keyword for TASKING Compiler */ #define __STATIC_INLINE static inline #define __STATIC_ASM static __asm #endif /** __FPU_USED indicates whether an FPU is used or not. For this, __FPU_PRESENT has to be checked prior to making use of FPU specific registers and functions. */ #if defined ( __CC_ARM ) #if defined __TARGET_FPU_VFP #if (__FPU_PRESENT == 1) #define __FPU_USED 1 #else #warning "Compiler generates FPU instructions for a device without an FPU (check __FPU_PRESENT)" #define __FPU_USED 0 #endif #else #define __FPU_USED 0 #endif #elif defined ( __ICCARM__ ) #if defined __ARMVFP__ #if (__FPU_PRESENT == 1) #define __FPU_USED 1 #else #warning "Compiler generates FPU instructions for a device without an FPU (check __FPU_PRESENT)" #define __FPU_USED 0 #endif #else #define __FPU_USED 0 #endif #elif defined ( __TMS470__ ) #if defined __TI_VFP_SUPPORT__ #if (__FPU_PRESENT == 1) #define __FPU_USED 1 #else #warning "Compiler generates FPU instructions for a device without an FPU (check __FPU_PRESENT)" #define __FPU_USED 0 #endif #else #define __FPU_USED 0 #endif #elif defined ( __GNUC__ ) #if defined (__VFP_FP__) && !defined(__SOFTFP__) #if (__FPU_PRESENT == 1) #define __FPU_USED 1 #else #warning "Compiler generates FPU instructions for a device without an FPU (check __FPU_PRESENT)" #define __FPU_USED 0 #endif #else #define __FPU_USED 0 #endif #elif defined ( __TASKING__ ) #if defined __FPU_VFP__ #if (__FPU_PRESENT == 1) #define __FPU_USED 1 #else #error "Compiler generates FPU instructions for a device without an FPU (check __FPU_PRESENT)" #define __FPU_USED 0 #endif #else #define __FPU_USED 0 #endif #endif #include /*!< standard types definitions */ #include "core_caInstr.h" /*!< Core Instruction Access */ #include "core_caFunc.h" /*!< Core Function Access */ #include "core_cm4_simd.h" /*!< Compiler specific SIMD Intrinsics */ #endif /* __CORE_CA9_H_GENERIC */ #ifndef __CMSIS_GENERIC #ifndef __CORE_CA9_H_DEPENDANT #define __CORE_CA9_H_DEPENDANT /* check device defines and use defaults */ #if defined __CHECK_DEVICE_DEFINES #ifndef __CA9_REV #define __CA9_REV 0x0000 #warning "__CA9_REV not defined in device header file; using default!" #endif #ifndef __FPU_PRESENT #define __FPU_PRESENT 1 #warning "__FPU_PRESENT not defined in device header file; using default!" #endif #ifndef __Vendor_SysTickConfig #define __Vendor_SysTickConfig 1 #endif #if __Vendor_SysTickConfig == 0 #error "__Vendor_SysTickConfig set to 0, but vendor systick timer must be supplied for Cortex-A9" #endif #endif /* IO definitions (access restrictions to peripheral registers) */ /** \defgroup CMSIS_glob_defs CMSIS Global Defines IO Type Qualifiers are used \li to specify the access to peripheral variables. \li for automatic generation of peripheral register debug information. */ #ifdef __cplusplus #define __I volatile /*!< Defines 'read only' permissions */ #else #define __I volatile const /*!< Defines 'read only' permissions */ #endif #define __O volatile /*!< Defines 'write only' permissions */ #define __IO volatile /*!< Defines 'read / write' permissions */ /*@} end of group Cortex_A9 */ /******************************************************************************* * Register Abstraction ******************************************************************************/ /** \defgroup CMSIS_core_register Defines and Type Definitions \brief Type definitions and defines for Cortex-A processor based devices. */ /** \ingroup CMSIS_core_register \defgroup CMSIS_CORE Status and Control Registers \brief Core Register type definitions. @{ */ /** \brief Union type to access the Application Program Status Register (APSR). */ typedef union { struct { uint32_t _reserved0:16; /*!< bit: 0..15 Reserved */ uint32_t GE:4; /*!< bit: 16..19 Greater than or Equal flags */ uint32_t reserved1:7; /*!< bit: 20..23 Reserved */ uint32_t Q:1; /*!< bit: 27 Saturation condition flag */ uint32_t V:1; /*!< bit: 28 Overflow condition code flag */ uint32_t C:1; /*!< bit: 29 Carry condition code flag */ uint32_t Z:1; /*!< bit: 30 Zero condition code flag */ uint32_t N:1; /*!< bit: 31 Negative condition code flag */ } b; /*!< Structure used for bit access */ uint32_t w; /*!< Type used for word access */ } APSR_Type; /*@} end of group CMSIS_CORE */ /*@} end of CMSIS_Core_FPUFunctions */ #endif /* __CORE_CA9_H_GENERIC */ #endif /* __CMSIS_GENERIC */ #ifdef __cplusplus } #endif ================================================ FILE: Zelig/mbed/TARGET_LPC1768/core_caFunc.h ================================================ /**************************************************************************//** * @file core_caFunc.h * @brief CMSIS Cortex-A Core Function Access Header File * @version V3.10 * @date 9 May 2013 * * @note * ******************************************************************************/ /* Copyright (c) 2009 - 2012 ARM LIMITED All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: - Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. - Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. - Neither the name of ARM 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 COPYRIGHT HOLDERS AND 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. ---------------------------------------------------------------------------*/ #ifndef __CORE_CAFUNC_H__ #define __CORE_CAFUNC_H__ /* ########################### Core Function Access ########################### */ /** \ingroup CMSIS_Core_FunctionInterface \defgroup CMSIS_Core_RegAccFunctions CMSIS Core Register Access Functions @{ */ #if defined ( __CC_ARM ) /*------------------RealView Compiler -----------------*/ /* ARM armcc specific functions */ #if (__ARMCC_VERSION < 400677) #error "Please use ARM Compiler Toolchain V4.0.677 or later!" #endif #define MODE_USR 0x10 #define MODE_FIQ 0x11 #define MODE_IRQ 0x12 #define MODE_SVC 0x13 #define MODE_MON 0x16 #define MODE_ABT 0x17 #define MODE_HYP 0x1A #define MODE_UND 0x1B #define MODE_SYS 0x1F /** \brief Get APSR Register This function returns the content of the APSR Register. \return APSR Register value */ __STATIC_INLINE uint32_t __get_APSR(void) { register uint32_t __regAPSR __ASM("apsr"); return(__regAPSR); } /** \brief Get CPSR Register This function returns the content of the CPSR Register. \return CPSR Register value */ __STATIC_INLINE uint32_t __get_CPSR(void) { register uint32_t __regCPSR __ASM("cpsr"); return(__regCPSR); } /** \brief Set Stack Pointer This function assigns the given value to the current stack pointer. \param [in] topOfStack Stack Pointer value to set */ register uint32_t __regSP __ASM("sp"); __STATIC_INLINE void __set_SP(uint32_t topOfStack) { __regSP = topOfStack; } /** \brief Get link register This function returns the value of the link register \return Value of link register */ register uint32_t __reglr __ASM("lr"); __STATIC_INLINE uint32_t __get_LR(void) { return(__reglr); } /** \brief Set link register This function sets the value of the link register \param [in] lr LR value to set */ __STATIC_INLINE void __set_LR(uint32_t lr) { __reglr = lr; } /** \brief Set Process Stack Pointer This function assigns the given value to the USR/SYS Stack Pointer (PSP). \param [in] topOfProcStack USR/SYS Stack Pointer value to set */ __STATIC_ASM void __set_PSP(uint32_t topOfProcStack) { ARM PRESERVE8 BIC R0, R0, #7 ;ensure stack is 8-byte aligned MRS R1, CPSR CPS #MODE_SYS ;no effect in USR mode MOV SP, R0 MSR CPSR_c, R1 ;no effect in USR mode ISB BX LR } /** \brief Set User Mode This function changes the processor state to User Mode \param [in] topOfProcStack USR/SYS Stack Pointer value to set */ __STATIC_ASM void __set_CPS_USR(void) { ARM CPS #MODE_USR BX LR } /** \brief Enable FIQ This function enables FIQ interrupts by clearing the F-bit in the CPSR. Can only be executed in Privileged modes. */ #define __enable_fault_irq __enable_fiq /** \brief Disable FIQ This function disables FIQ interrupts by setting the F-bit in the CPSR. Can only be executed in Privileged modes. */ #define __disable_fault_irq __disable_fiq /** \brief Get FPSCR This function returns the current value of the Floating Point Status/Control register. \return Floating Point Status/Control register value */ __STATIC_INLINE uint32_t __get_FPSCR(void) { #if (__FPU_PRESENT == 1) && (__FPU_USED == 1) register uint32_t __regfpscr __ASM("fpscr"); return(__regfpscr); #else return(0); #endif } /** \brief Set FPSCR This function assigns the given value to the Floating Point Status/Control register. \param [in] fpscr Floating Point Status/Control value to set */ __STATIC_INLINE void __set_FPSCR(uint32_t fpscr) { #if (__FPU_PRESENT == 1) && (__FPU_USED == 1) register uint32_t __regfpscr __ASM("fpscr"); __regfpscr = (fpscr); #endif } /** \brief Get FPEXC This function returns the current value of the Floating Point Exception Control register. \return Floating Point Exception Control register value */ __STATIC_INLINE uint32_t __get_FPEXC(void) { #if (__FPU_PRESENT == 1) register uint32_t __regfpexc __ASM("fpexc"); return(__regfpexc); #else return(0); #endif } /** \brief Set FPEXC This function assigns the given value to the Floating Point Exception Control register. \param [in] fpscr Floating Point Exception Control value to set */ __STATIC_INLINE void __set_FPEXC(uint32_t fpexc) { #if (__FPU_PRESENT == 1) register uint32_t __regfpexc __ASM("fpexc"); __regfpexc = (fpexc); #endif } /** \brief Get CPACR This function returns the current value of the Coprocessor Access Control register. \return Coprocessor Access Control register value */ __STATIC_INLINE uint32_t __get_CPACR(void) { register uint32_t __regCPACR __ASM("cp15:0:c1:c0:2"); return __regCPACR; } /** \brief Set CPACR This function assigns the given value to the Coprocessor Access Control register. \param [in] cpacr Coporcessor Acccess Control value to set */ __STATIC_INLINE void __set_CPACR(uint32_t cpacr) { register uint32_t __regCPACR __ASM("cp15:0:c1:c0:2"); __regCPACR = cpacr; __ISB(); } /** \brief Get CBAR This function returns the value of the Configuration Base Address register. \return Configuration Base Address register value */ __STATIC_INLINE uint32_t __get_CBAR() { register uint32_t __regCBAR __ASM("cp15:4:c15:c0:0"); return(__regCBAR); } /** \brief Get TTBR0 This function returns the value of the Configuration Base Address register. \return Translation Table Base Register 0 value */ __STATIC_INLINE uint32_t __get_TTBR0() { register uint32_t __regTTBR0 __ASM("cp15:0:c2:c0:0"); return(__regTTBR0); } /** \brief Set TTBR0 This function assigns the given value to the Coprocessor Access Control register. \param [in] ttbr0 Translation Table Base Register 0 value to set */ __STATIC_INLINE void __set_TTBR0(uint32_t ttbr0) { register uint32_t __regTTBR0 __ASM("cp15:0:c2:c0:0"); __regTTBR0 = ttbr0; __ISB(); } /** \brief Get DACR This function returns the value of the Domain Access Control Register. \return Domain Access Control Register value */ __STATIC_INLINE uint32_t __get_DACR() { register uint32_t __regDACR __ASM("cp15:0:c3:c0:0"); return(__regDACR); } /** \brief Set DACR This function assigns the given value to the Coprocessor Access Control register. \param [in] dacr Domain Access Control Register value to set */ __STATIC_INLINE void __set_DACR(uint32_t dacr) { register uint32_t __regDACR __ASM("cp15:0:c3:c0:0"); __regDACR = dacr; __ISB(); } /******************************** Cache and BTAC enable ****************************************************/ /** \brief Set SCTLR This function assigns the given value to the System Control Register. \param [in] sctlr System Control Register, value to set */ __STATIC_INLINE void __set_SCTLR(uint32_t sctlr) { register uint32_t __regSCTLR __ASM("cp15:0:c1:c0:0"); __regSCTLR = sctlr; } /** \brief Get SCTLR This function returns the value of the System Control Register. \return System Control Register value */ __STATIC_INLINE uint32_t __get_SCTLR() { register uint32_t __regSCTLR __ASM("cp15:0:c1:c0:0"); return(__regSCTLR); } /** \brief Enable Caches Enable Caches */ __STATIC_INLINE void __enable_caches(void) { // Set I bit 12 to enable I Cache // Set C bit 2 to enable D Cache __set_SCTLR( __get_SCTLR() | (1 << 12) | (1 << 2)); } /** \brief Disable Caches Disable Caches */ __STATIC_INLINE void __disable_caches(void) { // Clear I bit 12 to disable I Cache // Clear C bit 2 to disable D Cache __set_SCTLR( __get_SCTLR() & ~(1 << 12) & ~(1 << 2)); __ISB(); } /** \brief Enable BTAC Enable BTAC */ __STATIC_INLINE void __enable_btac(void) { // Set Z bit 11 to enable branch prediction __set_SCTLR( __get_SCTLR() | (1 << 11)); __ISB(); } /** \brief Disable BTAC Disable BTAC */ __STATIC_INLINE void __disable_btac(void) { // Clear Z bit 11 to disable branch prediction __set_SCTLR( __get_SCTLR() & ~(1 << 11)); } /** \brief Enable MMU Enable MMU */ __STATIC_INLINE void __enable_mmu(void) { // Set M bit 0 to enable the MMU // Set AFE bit to enable simplified access permissions model // Clear TRE bit to disable TEX remap and A bit to disable strict alignment fault checking __set_SCTLR( (__get_SCTLR() & ~(1 << 28) & ~(1 << 1)) | 1 | (1 << 29)); __ISB(); } /** \brief Enable MMU Enable MMU */ __STATIC_INLINE void __disable_mmu(void) { // Clear M bit 0 to disable the MMU __set_SCTLR( __get_SCTLR() & ~1); __ISB(); } /******************************** TLB maintenance operations ************************************************/ /** \brief Invalidate the whole tlb TLBIALL. Invalidate the whole tlb */ __STATIC_INLINE void __ca9u_inv_tlb_all(void) { register uint32_t __TLBIALL __ASM("cp15:0:c8:c7:0"); __TLBIALL = 0; __DSB(); __ISB(); } /******************************** BTB maintenance operations ************************************************/ /** \brief Invalidate entire branch predictor array BPIALL. Branch Predictor Invalidate All. */ __STATIC_INLINE void __v7_inv_btac(void) { register uint32_t __BPIALL __ASM("cp15:0:c7:c5:6"); __BPIALL = 0; __DSB(); //ensure completion of the invalidation __ISB(); //ensure instruction fetch path sees new state } /******************************** L1 cache operations ******************************************************/ /** \brief Invalidate the whole I$ ICIALLU. Instruction Cache Invalidate All to PoU */ __STATIC_INLINE void __v7_inv_icache_all(void) { register uint32_t __ICIALLU __ASM("cp15:0:c7:c5:0"); __ICIALLU = 0; __DSB(); //ensure completion of the invalidation __ISB(); //ensure instruction fetch path sees new I cache state } /** \brief Clean D$ by MVA DCCMVAC. Data cache clean by MVA to PoC */ __STATIC_INLINE void __v7_clean_dcache_mva(void *va) { register uint32_t __DCCMVAC __ASM("cp15:0:c7:c10:1"); __DCCMVAC = (uint32_t)va; __DMB(); //ensure the ordering of data cache maintenance operations and their effects } /** \brief Invalidate D$ by MVA DCIMVAC. Data cache invalidate by MVA to PoC */ __STATIC_INLINE void __v7_inv_dcache_mva(void *va) { register uint32_t __DCIMVAC __ASM("cp15:0:c7:c6:1"); __DCIMVAC = (uint32_t)va; __DMB(); //ensure the ordering of data cache maintenance operations and their effects } /** \brief Clean and Invalidate D$ by MVA DCCIMVAC. Data cache clean and invalidate by MVA to PoC */ __STATIC_INLINE void __v7_clean_inv_dcache_mva(void *va) { register uint32_t __DCCIMVAC __ASM("cp15:0:c7:c14:1"); __DCCIMVAC = (uint32_t)va; __DMB(); //ensure the ordering of data cache maintenance operations and their effects } /** \brief * Generic mechanism for cleaning/invalidating the entire data or unified cache to the point of coherency. */ #pragma push #pragma arm __STATIC_ASM void __v7_all_cache(uint32_t op) { ARM PUSH {R4-R11} MRC p15, 1, R6, c0, c0, 1 // Read CLIDR ANDS R3, R6, #0x07000000 // Extract coherency level MOV R3, R3, LSR #23 // Total cache levels << 1 BEQ Finished // If 0, no need to clean MOV R10, #0 // R10 holds current cache level << 1 Loop1 ADD R2, R10, R10, LSR #1 // R2 holds cache "Set" position MOV R1, R6, LSR R2 // Bottom 3 bits are the Cache-type for this level AND R1, R1, #7 // Isolate those lower 3 bits CMP R1, #2 BLT Skip // No cache or only instruction cache at this level MCR p15, 2, R10, c0, c0, 0 // Write the Cache Size selection register ISB // ISB to sync the change to the CacheSizeID reg MRC p15, 1, R1, c0, c0, 0 // Reads current Cache Size ID register AND R2, R1, #7 // Extract the line length field ADD R2, R2, #4 // Add 4 for the line length offset (log2 16 bytes) LDR R4, =0x3FF ANDS R4, R4, R1, LSR #3 // R4 is the max number on the way size (right aligned) CLZ R5, R4 // R5 is the bit position of the way size increment LDR R7, =0x7FFF ANDS R7, R7, R1, LSR #13 // R7 is the max number of the index size (right aligned) Loop2 MOV R9, R4 // R9 working copy of the max way size (right aligned) Loop3 ORR R11, R10, R9, LSL R5 // Factor in the Way number and cache number into R11 ORR R11, R11, R7, LSL R2 // Factor in the Set number CMP R0, #0 BNE Dccsw MCR p15, 0, R11, c7, c6, 2 // DCISW. Invalidate by Set/Way B cont Dccsw CMP R0, #1 BNE Dccisw MCR p15, 0, R11, c7, c10, 2 // DCCSW. Clean by Set/Way B cont Dccisw MCR p15, 0, R11, c7, c14, 2 // DCCISW, Clean and Invalidate by Set/Way cont SUBS R9, R9, #1 // Decrement the Way number BGE Loop3 SUBS R7, R7, #1 // Decrement the Set number BGE Loop2 Skip ADD R10, R10, #2 // increment the cache number CMP R3, R10 BGT Loop1 Finished DSB POP {R4-R11} BX lr } #pragma pop /** \brief __v7_all_cache - helper function */ /** \brief Invalidate the whole D$ DCISW. Invalidate by Set/Way */ __STATIC_INLINE void __v7_inv_dcache_all(void) { __v7_all_cache(0); } /** \brief Clean the whole D$ DCCSW. Clean by Set/Way */ __STATIC_INLINE void __v7_clean_dcache_all(void) { __v7_all_cache(1); } /** \brief Clean and invalidate the whole D$ DCCISW. Clean and Invalidate by Set/Way */ __STATIC_INLINE void __v7_clean_inv_dcache_all(void) { __v7_all_cache(2); } #include "core_ca_mmu.h" #elif (defined (__ICCARM__)) /*---------------- ICC Compiler ---------------------*/ #error IAR Compiler support not implemented for Cortex-A #elif (defined (__GNUC__)) /*------------------ GNU Compiler ---------------------*/ /* GNU gcc specific functions */ #define MODE_USR 0x10 #define MODE_FIQ 0x11 #define MODE_IRQ 0x12 #define MODE_SVC 0x13 #define MODE_MON 0x16 #define MODE_ABT 0x17 #define MODE_HYP 0x1A #define MODE_UND 0x1B #define MODE_SYS 0x1F __attribute__( ( always_inline ) ) __STATIC_INLINE void __enable_irq(void) { __ASM volatile ("cpsie i"); } /** \brief Disable IRQ Interrupts This function disables IRQ interrupts by setting the I-bit in the CPSR. Can only be executed in Privileged modes. */ __attribute__( ( always_inline ) ) __STATIC_INLINE uint32_t __disable_irq(void) { uint32_t result; __ASM volatile ("mrs %0, cpsr" : "=r" (result)); __ASM volatile ("cpsid i"); return(result & 0x80); } /** \brief Get APSR Register This function returns the content of the APSR Register. \return APSR Register value */ __attribute__( ( always_inline ) ) __STATIC_INLINE uint32_t __get_APSR(void) { #if 1 uint32_t result; __ASM volatile ("mrs %0, apsr" : "=r" (result) ); return (result); #else register uint32_t __regAPSR __ASM("apsr"); return(__regAPSR); #endif } /** \brief Get CPSR Register This function returns the content of the CPSR Register. \return CPSR Register value */ __attribute__( ( always_inline ) ) __STATIC_INLINE uint32_t __get_CPSR(void) { #if 1 register uint32_t __regCPSR; __ASM volatile ("mrs %0, cpsr" : "=r" (__regCPSR)); #else register uint32_t __regCPSR __ASM("cpsr"); #endif return(__regCPSR); } #if 0 /** \brief Set Stack Pointer This function assigns the given value to the current stack pointer. \param [in] topOfStack Stack Pointer value to set */ __attribute__( ( always_inline ) ) __STATIC_INLINE void __set_SP(uint32_t topOfStack) { register uint32_t __regSP __ASM("sp"); __regSP = topOfStack; } #endif /** \brief Get link register This function returns the value of the link register \return Value of link register */ __attribute__( ( always_inline ) ) __STATIC_INLINE uint32_t __get_LR(void) { register uint32_t __reglr __ASM("lr"); return(__reglr); } #if 0 /** \brief Set link register This function sets the value of the link register \param [in] lr LR value to set */ __attribute__( ( always_inline ) ) __STATIC_INLINE void __set_LR(uint32_t lr) { register uint32_t __reglr __ASM("lr"); __reglr = lr; } #endif /** \brief Set Process Stack Pointer This function assigns the given value to the USR/SYS Stack Pointer (PSP). \param [in] topOfProcStack USR/SYS Stack Pointer value to set */ extern void __set_PSP(uint32_t topOfProcStack); /** \brief Set User Mode This function changes the processor state to User Mode \param [in] topOfProcStack USR/SYS Stack Pointer value to set */ extern void __set_CPS_USR(void); /** \brief Enable FIQ This function enables FIQ interrupts by clearing the F-bit in the CPSR. Can only be executed in Privileged modes. */ #define __enable_fault_irq __enable_fiq /** \brief Disable FIQ This function disables FIQ interrupts by setting the F-bit in the CPSR. Can only be executed in Privileged modes. */ #define __disable_fault_irq __disable_fiq /** \brief Get FPSCR This function returns the current value of the Floating Point Status/Control register. \return Floating Point Status/Control register value */ __attribute__( ( always_inline ) ) __STATIC_INLINE uint32_t __get_FPSCR(void) { #if (__FPU_PRESENT == 1) && (__FPU_USED == 1) #if 1 uint32_t result; __ASM volatile ("vmrs %0, fpscr" : "=r" (result) ); return (result); #else register uint32_t __regfpscr __ASM("fpscr"); return(__regfpscr); #endif #else return(0); #endif } /** \brief Set FPSCR This function assigns the given value to the Floating Point Status/Control register. \param [in] fpscr Floating Point Status/Control value to set */ __attribute__( ( always_inline ) ) __STATIC_INLINE void __set_FPSCR(uint32_t fpscr) { #if (__FPU_PRESENT == 1) && (__FPU_USED == 1) #if 1 __ASM volatile ("vmsr fpscr, %0" : : "r" (fpscr) ); #else register uint32_t __regfpscr __ASM("fpscr"); __regfpscr = (fpscr); #endif #endif } /** \brief Get FPEXC This function returns the current value of the Floating Point Exception Control register. \return Floating Point Exception Control register value */ __attribute__( ( always_inline ) ) __STATIC_INLINE uint32_t __get_FPEXC(void) { #if (__FPU_PRESENT == 1) #if 1 uint32_t result; __ASM volatile ("vmrs %0, fpexc" : "=r" (result)); return (result); #else register uint32_t __regfpexc __ASM("fpexc"); return(__regfpexc); #endif #else return(0); #endif } /** \brief Set FPEXC This function assigns the given value to the Floating Point Exception Control register. \param [in] fpscr Floating Point Exception Control value to set */ __attribute__( ( always_inline ) ) __STATIC_INLINE void __set_FPEXC(uint32_t fpexc) { #if (__FPU_PRESENT == 1) #if 1 __ASM volatile ("vmsr fpexc, %0" : : "r" (fpexc)); #else register uint32_t __regfpexc __ASM("fpexc"); __regfpexc = (fpexc); #endif #endif } /** \brief Get CPACR This function returns the current value of the Coprocessor Access Control register. \return Coprocessor Access Control register value */ __attribute__( ( always_inline ) ) __STATIC_INLINE uint32_t __get_CPACR(void) { #if 1 register uint32_t __regCPACR; __ASM volatile ("mrc p15, 0, %0, c1, c0, 2" : "=r" (__regCPACR)); #else register uint32_t __regCPACR __ASM("cp15:0:c1:c0:2"); #endif return __regCPACR; } /** \brief Set CPACR This function assigns the given value to the Coprocessor Access Control register. \param [in] cpacr Coporcessor Acccess Control value to set */ __attribute__( ( always_inline ) ) __STATIC_INLINE void __set_CPACR(uint32_t cpacr) { #if 1 __ASM volatile ("mcr p15, 0, %0, c1, c0, 2" : : "r" (cpacr)); #else register uint32_t __regCPACR __ASM("cp15:0:c1:c0:2"); __regCPACR = cpacr; #endif __ISB(); } /** \brief Get CBAR This function returns the value of the Configuration Base Address register. \return Configuration Base Address register value */ __attribute__( ( always_inline ) ) __STATIC_INLINE uint32_t __get_CBAR() { #if 1 register uint32_t __regCBAR; __ASM volatile ("mrc p15, 4, %0, c15, c0, 0" : "=r" (__regCBAR)); #else register uint32_t __regCBAR __ASM("cp15:4:c15:c0:0"); #endif return(__regCBAR); } /** \brief Get TTBR0 This function returns the value of the Configuration Base Address register. \return Translation Table Base Register 0 value */ __attribute__( ( always_inline ) ) __STATIC_INLINE uint32_t __get_TTBR0() { #if 1 register uint32_t __regTTBR0; __ASM volatile ("mrc p15, 0, %0, c2, c0, 0" : "=r" (__regTTBR0)); #else register uint32_t __regTTBR0 __ASM("cp15:0:c2:c0:0"); #endif return(__regTTBR0); } /** \brief Set TTBR0 This function assigns the given value to the Coprocessor Access Control register. \param [in] ttbr0 Translation Table Base Register 0 value to set */ __attribute__( ( always_inline ) ) __STATIC_INLINE void __set_TTBR0(uint32_t ttbr0) { #if 1 __ASM volatile ("mcr p15, 0, %0, c2, c0, 0" : : "r" (ttbr0)); #else register uint32_t __regTTBR0 __ASM("cp15:0:c2:c0:0"); __regTTBR0 = ttbr0; #endif __ISB(); } /** \brief Get DACR This function returns the value of the Domain Access Control Register. \return Domain Access Control Register value */ __attribute__( ( always_inline ) ) __STATIC_INLINE uint32_t __get_DACR() { #if 1 register uint32_t __regDACR; __ASM volatile ("mrc p15, 0, %0, c3, c0, 0" : "=r" (__regDACR)); #else register uint32_t __regDACR __ASM("cp15:0:c3:c0:0"); #endif return(__regDACR); } /** \brief Set DACR This function assigns the given value to the Coprocessor Access Control register. \param [in] dacr Domain Access Control Register value to set */ __attribute__( ( always_inline ) ) __STATIC_INLINE void __set_DACR(uint32_t dacr) { #if 1 __ASM volatile ("mcr p15, 0, %0, c3, c0, 0" : : "r" (dacr)); #else register uint32_t __regDACR __ASM("cp15:0:c3:c0:0"); __regDACR = dacr; #endif __ISB(); } /******************************** Cache and BTAC enable ****************************************************/ /** \brief Set SCTLR This function assigns the given value to the System Control Register. \param [in] sctlr System Control Register, value to set */ __attribute__( ( always_inline ) ) __STATIC_INLINE void __set_SCTLR(uint32_t sctlr) { #if 1 __ASM volatile ("mcr p15, 0, %0, c1, c0, 0" : : "r" (sctlr)); #else register uint32_t __regSCTLR __ASM("cp15:0:c1:c0:0"); __regSCTLR = sctlr; #endif } /** \brief Get SCTLR This function returns the value of the System Control Register. \return System Control Register value */ __attribute__( ( always_inline ) ) __STATIC_INLINE uint32_t __get_SCTLR() { #if 1 register uint32_t __regSCTLR; __ASM volatile ("mrc p15, 0, %0, c1, c0, 0" : "=r" (__regSCTLR)); #else register uint32_t __regSCTLR __ASM("cp15:0:c1:c0:0"); #endif return(__regSCTLR); } /** \brief Enable Caches Enable Caches */ __attribute__( ( always_inline ) ) __STATIC_INLINE void __enable_caches(void) { // Set I bit 12 to enable I Cache // Set C bit 2 to enable D Cache __set_SCTLR( __get_SCTLR() | (1 << 12) | (1 << 2)); } /** \brief Disable Caches Disable Caches */ __attribute__( ( always_inline ) ) __STATIC_INLINE void __disable_caches(void) { // Clear I bit 12 to disable I Cache // Clear C bit 2 to disable D Cache __set_SCTLR( __get_SCTLR() & ~(1 << 12) & ~(1 << 2)); __ISB(); } /** \brief Enable BTAC Enable BTAC */ __attribute__( ( always_inline ) ) __STATIC_INLINE void __enable_btac(void) { // Set Z bit 11 to enable branch prediction __set_SCTLR( __get_SCTLR() | (1 << 11)); __ISB(); } /** \brief Disable BTAC Disable BTAC */ __attribute__( ( always_inline ) ) __STATIC_INLINE void __disable_btac(void) { // Clear Z bit 11 to disable branch prediction __set_SCTLR( __get_SCTLR() & ~(1 << 11)); } /** \brief Enable MMU Enable MMU */ __attribute__( ( always_inline ) ) __STATIC_INLINE void __enable_mmu(void) { // Set M bit 0 to enable the MMU // Set AFE bit to enable simplified access permissions model // Clear TRE bit to disable TEX remap and A bit to disable strict alignment fault checking __set_SCTLR( (__get_SCTLR() & ~(1 << 28) & ~(1 << 1)) | 1 | (1 << 29)); __ISB(); } /** \brief Enable MMU Enable MMU */ __attribute__( ( always_inline ) ) __STATIC_INLINE void __disable_mmu(void) { // Clear M bit 0 to disable the MMU __set_SCTLR( __get_SCTLR() & ~1); __ISB(); } /******************************** TLB maintenance operations ************************************************/ /** \brief Invalidate the whole tlb TLBIALL. Invalidate the whole tlb */ __attribute__( ( always_inline ) ) __STATIC_INLINE void __ca9u_inv_tlb_all(void) { #if 1 __ASM volatile ("mcr p15, 0, %0, c8, c7, 0" : : "r" (0)); #else register uint32_t __TLBIALL __ASM("cp15:0:c8:c7:0"); __TLBIALL = 0; #endif __DSB(); __ISB(); } /******************************** BTB maintenance operations ************************************************/ /** \brief Invalidate entire branch predictor array BPIALL. Branch Predictor Invalidate All. */ __attribute__( ( always_inline ) ) __STATIC_INLINE void __v7_inv_btac(void) { #if 1 __ASM volatile ("mcr p15, 0, %0, c7, c5, 6" : : "r" (0)); #else register uint32_t __BPIALL __ASM("cp15:0:c7:c5:6"); __BPIALL = 0; #endif __DSB(); //ensure completion of the invalidation __ISB(); //ensure instruction fetch path sees new state } /******************************** L1 cache operations ******************************************************/ /** \brief Invalidate the whole I$ ICIALLU. Instruction Cache Invalidate All to PoU */ __attribute__( ( always_inline ) ) __STATIC_INLINE void __v7_inv_icache_all(void) { #if 1 __ASM volatile ("mcr p15, 0, %0, c7, c5, 0" : : "r" (0)); #else register uint32_t __ICIALLU __ASM("cp15:0:c7:c5:0"); __ICIALLU = 0; #endif __DSB(); //ensure completion of the invalidation __ISB(); //ensure instruction fetch path sees new I cache state } /** \brief Clean D$ by MVA DCCMVAC. Data cache clean by MVA to PoC */ __attribute__( ( always_inline ) ) __STATIC_INLINE void __v7_clean_dcache_mva(void *va) { #if 1 __ASM volatile ("mcr p15, 0, %0, c7, c10, 1" : : "r" ((uint32_t)va)); #else register uint32_t __DCCMVAC __ASM("cp15:0:c7:c10:1"); __DCCMVAC = (uint32_t)va; #endif __DMB(); //ensure the ordering of data cache maintenance operations and their effects } /** \brief Invalidate D$ by MVA DCIMVAC. Data cache invalidate by MVA to PoC */ __attribute__( ( always_inline ) ) __STATIC_INLINE void __v7_inv_dcache_mva(void *va) { #if 1 __ASM volatile ("mcr p15, 0, %0, c7, c6, 1" : : "r" ((uint32_t)va)); #else register uint32_t __DCIMVAC __ASM("cp15:0:c7:c6:1"); __DCIMVAC = (uint32_t)va; #endif __DMB(); //ensure the ordering of data cache maintenance operations and their effects } /** \brief Clean and Invalidate D$ by MVA DCCIMVAC. Data cache clean and invalidate by MVA to PoC */ __attribute__( ( always_inline ) ) __STATIC_INLINE void __v7_clean_inv_dcache_mva(void *va) { #if 1 __ASM volatile ("mcr p15, 0, %0, c7, c14, 1" : : "r" ((uint32_t)va)); #else register uint32_t __DCCIMVAC __ASM("cp15:0:c7:c14:1"); __DCCIMVAC = (uint32_t)va; #endif __DMB(); //ensure the ordering of data cache maintenance operations and their effects } /** \brief * Generic mechanism for cleaning/invalidating the entire data or unified cache to the point of coherency. */ /** \brief __v7_all_cache - helper function */ extern void __v7_all_cache(uint32_t op); /** \brief Invalidate the whole D$ DCISW. Invalidate by Set/Way */ __attribute__( ( always_inline ) ) __STATIC_INLINE void __v7_inv_dcache_all(void) { __v7_all_cache(0); } /** \brief Clean the whole D$ DCCSW. Clean by Set/Way */ __attribute__( ( always_inline ) ) __STATIC_INLINE void __v7_clean_dcache_all(void) { __v7_all_cache(1); } /** \brief Clean and invalidate the whole D$ DCCISW. Clean and Invalidate by Set/Way */ __attribute__( ( always_inline ) ) __STATIC_INLINE void __v7_clean_inv_dcache_all(void) { __v7_all_cache(2); } #include "core_ca_mmu.h" #elif (defined (__TASKING__)) /*--------------- TASKING Compiler -----------------*/ #error TASKING Compiler support not implemented for Cortex-A #endif /*@} end of CMSIS_Core_RegAccFunctions */ #endif /* __CORE_CAFUNC_H__ */ ================================================ FILE: Zelig/mbed/TARGET_LPC1768/core_caInstr.h ================================================ /**************************************************************************//** * @file core_caInstr.h * @brief CMSIS Cortex-A9 Core Peripheral Access Layer Header File * @version * @date 04. December 2012 * * @note * ******************************************************************************/ /* Copyright (c) 2009 - 2012 ARM LIMITED All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: - Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. - Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. - Neither the name of ARM 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 COPYRIGHT HOLDERS AND 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. ---------------------------------------------------------------------------*/ #ifndef __CORE_CAINSTR_H__ #define __CORE_CAINSTR_H__ #define __CORTEX_M 0x3 #include "core_cmInstr.h" #undef __CORTEX_M #endif ================================================ FILE: Zelig/mbed/TARGET_LPC1768/core_ca_mmu.h ================================================ ;/**************************************************************************//** ; * @file core_ca_mmu.h ; * @brief MMU Startup File for ; * VE_A9_MP Device Series ; * @version V1.01 ; * @date 25 March 2013 ; * ; * @note ; * ; ******************************************************************************/ ;/* Copyright (c) 2012 ARM LIMITED ; ; All rights reserved. ; Redistribution and use in source and binary forms, with or without ; modification, are permitted provided that the following conditions are met: ; - Redistributions of source code must retain the above copyright ; notice, this list of conditions and the following disclaimer. ; - Redistributions in binary form must reproduce the above copyright ; notice, this list of conditions and the following disclaimer in the ; documentation and/or other materials provided with the distribution. ; - Neither the name of ARM 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 COPYRIGHT HOLDERS AND CONTRIBUTORS BE ; LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR ; CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF ; SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS ; INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN ; CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ; ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE ; POSSIBILITY OF SUCH DAMAGE. ; ---------------------------------------------------------------------------*/ #ifdef __cplusplus extern "C" { #endif #ifndef _MMU_FUNC_H #define _MMU_FUNC_H #define SECTION_DESCRIPTOR (0x2) #define SECTION_MASK (0xFFFFFFFC) #define SECTION_TEXCB_MASK (0xFFFF8FF3) #define SECTION_B_SHIFT (2) #define SECTION_C_SHIFT (3) #define SECTION_TEX0_SHIFT (12) #define SECTION_TEX1_SHIFT (13) #define SECTION_TEX2_SHIFT (14) #define SECTION_XN_MASK (0xFFFFFFEF) #define SECTION_XN_SHIFT (4) #define SECTION_DOMAIN_MASK (0xFFFFFE1F) #define SECTION_DOMAIN_SHIFT (5) #define SECTION_P_MASK (0xFFFFFDFF) #define SECTION_P_SHIFT (9) #define SECTION_AP_MASK (0xFFFF73FF) #define SECTION_AP_SHIFT (10) #define SECTION_AP2_SHIFT (15) #define SECTION_S_MASK (0xFFFEFFFF) #define SECTION_S_SHIFT (16) #define SECTION_NG_MASK (0xFFFDFFFF) #define SECTION_NG_SHIFT (17) #define SECTION_NS_MASK (0xFFF7FFFF) #define SECTION_NS_SHIFT (19) #define PAGE_L1_DESCRIPTOR (0x1) #define PAGE_L1_MASK (0xFFFFFFFC) #define PAGE_L2_4K_DESC (0x2) #define PAGE_L2_4K_MASK (0xFFFFFFFD) #define PAGE_L2_64K_DESC (0x1) #define PAGE_L2_64K_MASK (0xFFFFFFFC) #define PAGE_4K_TEXCB_MASK (0xFFFFFE33) #define PAGE_4K_B_SHIFT (2) #define PAGE_4K_C_SHIFT (3) #define PAGE_4K_TEX0_SHIFT (6) #define PAGE_4K_TEX1_SHIFT (7) #define PAGE_4K_TEX2_SHIFT (8) #define PAGE_64K_TEXCB_MASK (0xFFFF8FF3) #define PAGE_64K_B_SHIFT (2) #define PAGE_64K_C_SHIFT (3) #define PAGE_64K_TEX0_SHIFT (12) #define PAGE_64K_TEX1_SHIFT (13) #define PAGE_64K_TEX2_SHIFT (14) #define PAGE_TEXCB_MASK (0xFFFF8FF3) #define PAGE_B_SHIFT (2) #define PAGE_C_SHIFT (3) #define PAGE_TEX_SHIFT (12) #define PAGE_XN_4K_MASK (0xFFFFFFFE) #define PAGE_XN_4K_SHIFT (0) #define PAGE_XN_64K_MASK (0xFFFF7FFF) #define PAGE_XN_64K_SHIFT (15) #define PAGE_DOMAIN_MASK (0xFFFFFE1F) #define PAGE_DOMAIN_SHIFT (5) #define PAGE_P_MASK (0xFFFFFDFF) #define PAGE_P_SHIFT (9) #define PAGE_AP_MASK (0xFFFFFDCF) #define PAGE_AP_SHIFT (4) #define PAGE_AP2_SHIFT (9) #define PAGE_S_MASK (0xFFFFFBFF) #define PAGE_S_SHIFT (10) #define PAGE_NG_MASK (0xFFFFF7FF) #define PAGE_NG_SHIFT (11) #define PAGE_NS_MASK (0xFFFFFFF7) #define PAGE_NS_SHIFT (3) #define OFFSET_1M (0x00100000) #define OFFSET_64K (0x00010000) #define OFFSET_4K (0x00001000) #define DESCRIPTOR_FAULT (0x00000000) /* ########################### MMU Function Access ########################### */ /** \ingroup MMU_FunctionInterface \defgroup MMU_Functions MMU Functions Interface @{ */ /* Attributes enumerations */ /* Region size attributes */ typedef enum { SECTION, PAGE_4k, PAGE_64k, } mmu_region_size_Type; /* Region type attributes */ typedef enum { NORMAL, DEVICE, SHARED_DEVICE, NON_SHARED_DEVICE, STRONGLY_ORDERED } mmu_memory_Type; /* Region cacheability attributes */ typedef enum { NON_CACHEABLE, WB_WA, WT, WB_NO_WA, } mmu_cacheability_Type; /* Region parity check attributes */ typedef enum { ECC_DISABLED, ECC_ENABLED, } mmu_ecc_check_Type; /* Region execution attributes */ typedef enum { EXECUTE, NON_EXECUTE, } mmu_execute_Type; /* Region global attributes */ typedef enum { GLOBAL, NON_GLOBAL, } mmu_global_Type; /* Region shareability attributes */ typedef enum { NON_SHARED, SHARED, } mmu_shared_Type; /* Region security attributes */ typedef enum { SECURE, NON_SECURE, } mmu_secure_Type; /* Region access attributes */ typedef enum { NO_ACCESS, RW, READ, } mmu_access_Type; /* Memory Region definition */ typedef struct RegionStruct { mmu_region_size_Type rg_t; mmu_memory_Type mem_t; uint8_t domain; mmu_cacheability_Type inner_norm_t; mmu_cacheability_Type outer_norm_t; mmu_ecc_check_Type e_t; mmu_execute_Type xn_t; mmu_global_Type g_t; mmu_secure_Type sec_t; mmu_access_Type priv_t; mmu_access_Type user_t; mmu_shared_Type sh_t; } mmu_region_attributes_Type; /** \brief Set section execution-never attribute The function sets section execution-never attribute \param [out] descriptor_l1 L1 descriptor. \param [in] xn Section execution-never attribute : EXECUTE , NON_EXECUTE. \return 0 */ __STATIC_INLINE int __xn_section(uint32_t *descriptor_l1, mmu_execute_Type xn) { *descriptor_l1 &= SECTION_XN_MASK; *descriptor_l1 |= ((xn & 0x1) << SECTION_XN_SHIFT); return 0; } /** \brief Set section domain The function sets section domain \param [out] descriptor_l1 L1 descriptor. \param [in] domain Section domain \return 0 */ __STATIC_INLINE int __domain_section(uint32_t *descriptor_l1, uint8_t domain) { *descriptor_l1 &= SECTION_DOMAIN_MASK; *descriptor_l1 |= ((domain & 0xF) << SECTION_DOMAIN_SHIFT); return 0; } /** \brief Set section parity check The function sets section parity check \param [out] descriptor_l1 L1 descriptor. \param [in] p_bit Parity check: ECC_DISABLED, ECC_ENABLED \return 0 */ __STATIC_INLINE int __p_section(uint32_t *descriptor_l1, mmu_ecc_check_Type p_bit) { *descriptor_l1 &= SECTION_P_MASK; *descriptor_l1 |= ((p_bit & 0x1) << SECTION_P_SHIFT); return 0; } /** \brief Set section access privileges The function sets section access privileges \param [out] descriptor_l1 L1 descriptor. \param [in] user User Level Access: NO_ACCESS, RW, READ \param [in] priv Privilege Level Access: NO_ACCESS, RW, READ \param [in] afe Access flag enable \return 0 */ __STATIC_INLINE int __ap_section(uint32_t *descriptor_l1, mmu_access_Type user, mmu_access_Type priv, uint32_t afe) { uint32_t ap = 0; if (afe == 0) { //full access if ((priv == NO_ACCESS) && (user == NO_ACCESS)) { ap = 0x0; } else if ((priv == RW) && (user == NO_ACCESS)) { ap = 0x1; } else if ((priv == RW) && (user == READ)) { ap = 0x2; } else if ((priv == RW) && (user == RW)) { ap = 0x3; } else if ((priv == READ) && (user == NO_ACCESS)) { ap = 0x5; } else if ((priv == READ) && (user == READ)) { ap = 0x6; } } else { //Simplified access if ((priv == RW) && (user == NO_ACCESS)) { ap = 0x1; } else if ((priv == RW) && (user == RW)) { ap = 0x3; } else if ((priv == READ) && (user == NO_ACCESS)) { ap = 0x5; } else if ((priv == READ) && (user == READ)) { ap = 0x7; } } *descriptor_l1 &= SECTION_AP_MASK; *descriptor_l1 |= (ap & 0x3) << SECTION_AP_SHIFT; *descriptor_l1 |= ((ap & 0x4)>>2) << SECTION_AP2_SHIFT; return 0; } /** \brief Set section shareability The function sets section shareability \param [out] descriptor_l1 L1 descriptor. \param [in] s_bit Section shareability: NON_SHARED, SHARED \return 0 */ __STATIC_INLINE int __shared_section(uint32_t *descriptor_l1, mmu_shared_Type s_bit) { *descriptor_l1 &= SECTION_S_MASK; *descriptor_l1 |= ((s_bit & 0x1) << SECTION_S_SHIFT); return 0; } /** \brief Set section Global attribute The function sets section Global attribute \param [out] descriptor_l1 L1 descriptor. \param [in] g_bit Section attribute: GLOBAL, NON_GLOBAL \return 0 */ __STATIC_INLINE int __global_section(uint32_t *descriptor_l1, mmu_global_Type g_bit) { *descriptor_l1 &= SECTION_NG_MASK; *descriptor_l1 |= ((g_bit & 0x1) << SECTION_NG_SHIFT); return 0; } /** \brief Set section Security attribute The function sets section Global attribute \param [out] descriptor_l1 L1 descriptor. \param [in] s_bit Section Security attribute: SECURE, NON_SECURE \return 0 */ __STATIC_INLINE int __secure_section(uint32_t *descriptor_l1, mmu_secure_Type s_bit) { *descriptor_l1 &= SECTION_NS_MASK; *descriptor_l1 |= ((s_bit & 0x1) << SECTION_NS_SHIFT); return 0; } /* Page 4k or 64k */ /** \brief Set 4k/64k page execution-never attribute The function sets 4k/64k page execution-never attribute \param [out] descriptor_l2 L2 descriptor. \param [in] xn Page execution-never attribute : EXECUTE , NON_EXECUTE. \param [in] page Page size: PAGE_4k, PAGE_64k, \return 0 */ __STATIC_INLINE int __xn_page(uint32_t *descriptor_l2, mmu_execute_Type xn, mmu_region_size_Type page) { if (page == PAGE_4k) { *descriptor_l2 &= PAGE_XN_4K_MASK; *descriptor_l2 |= ((xn & 0x1) << PAGE_XN_4K_SHIFT); } else { *descriptor_l2 &= PAGE_XN_64K_MASK; *descriptor_l2 |= ((xn & 0x1) << PAGE_XN_64K_SHIFT); } return 0; } /** \brief Set 4k/64k page domain The function sets 4k/64k page domain \param [out] descriptor_l1 L1 descriptor. \param [in] domain Page domain \return 0 */ __STATIC_INLINE int __domain_page(uint32_t *descriptor_l1, uint8_t domain) { *descriptor_l1 &= PAGE_DOMAIN_MASK; *descriptor_l1 |= ((domain & 0xf) << PAGE_DOMAIN_SHIFT); return 0; } /** \brief Set 4k/64k page parity check The function sets 4k/64k page parity check \param [out] descriptor_l1 L1 descriptor. \param [in] p_bit Parity check: ECC_DISABLED, ECC_ENABLED \return 0 */ __STATIC_INLINE int __p_page(uint32_t *descriptor_l1, mmu_ecc_check_Type p_bit) { *descriptor_l1 &= SECTION_P_MASK; *descriptor_l1 |= ((p_bit & 0x1) << SECTION_P_SHIFT); return 0; } /** \brief Set 4k/64k page access privileges The function sets 4k/64k page access privileges \param [out] descriptor_l2 L2 descriptor. \param [in] user User Level Access: NO_ACCESS, RW, READ \param [in] priv Privilege Level Access: NO_ACCESS, RW, READ \param [in] afe Access flag enable \return 0 */ __STATIC_INLINE int __ap_page(uint32_t *descriptor_l2, mmu_access_Type user, mmu_access_Type priv, uint32_t afe) { uint32_t ap = 0; if (afe == 0) { //full access if ((priv == NO_ACCESS) && (user == NO_ACCESS)) { ap = 0x0; } else if ((priv == RW) && (user == NO_ACCESS)) { ap = 0x1; } else if ((priv == RW) && (user == READ)) { ap = 0x2; } else if ((priv == RW) && (user == RW)) { ap = 0x3; } else if ((priv == READ) && (user == NO_ACCESS)) { ap = 0x5; } else if ((priv == READ) && (user == READ)) { ap = 0x6; } } else { //Simplified access if ((priv == RW) && (user == NO_ACCESS)) { ap = 0x1; } else if ((priv == RW) && (user == RW)) { ap = 0x3; } else if ((priv == READ) && (user == NO_ACCESS)) { ap = 0x5; } else if ((priv == READ) && (user == READ)) { ap = 0x7; } } *descriptor_l2 &= PAGE_AP_MASK; *descriptor_l2 |= (ap & 0x3) << PAGE_AP_SHIFT; *descriptor_l2 |= ((ap & 0x4)>>2) << PAGE_AP2_SHIFT; return 0; } /** \brief Set 4k/64k page shareability The function sets 4k/64k page shareability \param [out] descriptor_l2 L2 descriptor. \param [in] s_bit 4k/64k page shareability: NON_SHARED, SHARED \return 0 */ __STATIC_INLINE int __shared_page(uint32_t *descriptor_l2, mmu_shared_Type s_bit) { *descriptor_l2 &= PAGE_S_MASK; *descriptor_l2 |= ((s_bit & 0x1) << PAGE_S_SHIFT); return 0; } /** \brief Set 4k/64k page Global attribute The function sets 4k/64k page Global attribute \param [out] descriptor_l2 L2 descriptor. \param [in] g_bit 4k/64k page attribute: GLOBAL, NON_GLOBAL \return 0 */ __STATIC_INLINE int __global_page(uint32_t *descriptor_l2, mmu_global_Type g_bit) { *descriptor_l2 &= PAGE_NG_MASK; *descriptor_l2 |= ((g_bit & 0x1) << PAGE_NG_SHIFT); return 0; } /** \brief Set 4k/64k page Security attribute The function sets 4k/64k page Global attribute \param [out] descriptor_l1 L1 descriptor. \param [in] s_bit 4k/64k page Security attribute: SECURE, NON_SECURE \return 0 */ __STATIC_INLINE int __secure_page(uint32_t *descriptor_l1, mmu_secure_Type s_bit) { *descriptor_l1 &= PAGE_NS_MASK; *descriptor_l1 |= ((s_bit & 0x1) << PAGE_NS_SHIFT); return 0; } /** \brief Set Section memory attributes The function sets section memory attributes \param [out] descriptor_l1 L1 descriptor. \param [in] mem Section memory type: NORMAL, DEVICE, SHARED_DEVICE, NON_SHARED_DEVICE, STRONGLY_ORDERED \param [in] outer Outer cacheability: NON_CACHEABLE, WB_WA, WT, WB_NO_WA, \param [in] inner Inner cacheability: NON_CACHEABLE, WB_WA, WT, WB_NO_WA, \return 0 */ __STATIC_INLINE int __memory_section(uint32_t *descriptor_l1, mmu_memory_Type mem, mmu_cacheability_Type outer, mmu_cacheability_Type inner) { *descriptor_l1 &= SECTION_TEXCB_MASK; if (STRONGLY_ORDERED == mem) { return 0; } else if (SHARED_DEVICE == mem) { *descriptor_l1 |= (1 << SECTION_B_SHIFT); } else if (NON_SHARED_DEVICE == mem) { *descriptor_l1 |= (1 << SECTION_TEX1_SHIFT); } else if (NORMAL == mem) { *descriptor_l1 |= 1 << SECTION_TEX2_SHIFT; switch(inner) { case NON_CACHEABLE: break; case WB_WA: *descriptor_l1 |= (1 << SECTION_B_SHIFT); break; case WT: *descriptor_l1 |= 1 << SECTION_C_SHIFT; break; case WB_NO_WA: *descriptor_l1 |= (1 << SECTION_B_SHIFT) | (1 << SECTION_C_SHIFT); break; } switch(outer) { case NON_CACHEABLE: break; case WB_WA: *descriptor_l1 |= (1 << SECTION_TEX0_SHIFT); break; case WT: *descriptor_l1 |= 1 << SECTION_TEX1_SHIFT; break; case WB_NO_WA: *descriptor_l1 |= (1 << SECTION_TEX0_SHIFT) | (1 << SECTION_TEX0_SHIFT); break; } } return 0; } /** \brief Set 4k/64k page memory attributes The function sets 4k/64k page memory attributes \param [out] descriptor_l2 L2 descriptor. \param [in] mem 4k/64k page memory type: NORMAL, DEVICE, SHARED_DEVICE, NON_SHARED_DEVICE, STRONGLY_ORDERED \param [in] outer Outer cacheability: NON_CACHEABLE, WB_WA, WT, WB_NO_WA, \param [in] inner Inner cacheability: NON_CACHEABLE, WB_WA, WT, WB_NO_WA, \return 0 */ __STATIC_INLINE int __memory_page(uint32_t *descriptor_l2, mmu_memory_Type mem, mmu_cacheability_Type outer, mmu_cacheability_Type inner, mmu_region_size_Type page) { *descriptor_l2 &= PAGE_4K_TEXCB_MASK; if (page == PAGE_64k) { //same as section __memory_section(descriptor_l2, mem, outer, inner); } else { if (STRONGLY_ORDERED == mem) { return 0; } else if (SHARED_DEVICE == mem) { *descriptor_l2 |= (1 << PAGE_4K_B_SHIFT); } else if (NON_SHARED_DEVICE == mem) { *descriptor_l2 |= (1 << PAGE_4K_TEX1_SHIFT); } else if (NORMAL == mem) { *descriptor_l2 |= 1 << PAGE_4K_TEX2_SHIFT; switch(inner) { case NON_CACHEABLE: break; case WB_WA: *descriptor_l2 |= (1 << PAGE_4K_B_SHIFT); break; case WT: *descriptor_l2 |= 1 << PAGE_4K_C_SHIFT; break; case WB_NO_WA: *descriptor_l2 |= (1 << PAGE_4K_B_SHIFT) | (1 << PAGE_4K_C_SHIFT); break; } switch(outer) { case NON_CACHEABLE: break; case WB_WA: *descriptor_l2 |= (1 << PAGE_4K_TEX0_SHIFT); break; case WT: *descriptor_l2 |= 1 << PAGE_4K_TEX1_SHIFT; break; case WB_NO_WA: *descriptor_l2 |= (1 << PAGE_4K_TEX0_SHIFT) | (1 << PAGE_4K_TEX0_SHIFT); break; } } } return 0; } /** \brief Create a L1 section descriptor The function creates a section descriptor. Assumptions: - 16MB super sections not suported - TEX remap disabled, so memory type and attributes are described directly by bits in the descriptor - Functions always return 0 \param [out] descriptor L1 descriptor \param [out] descriptor2 L2 descriptor \param [in] reg Section attributes \return 0 */ __STATIC_INLINE int __get_section_descriptor(uint32_t *descriptor, mmu_region_attributes_Type reg) { *descriptor = 0; __memory_section(descriptor, reg.mem_t, reg.outer_norm_t, reg.inner_norm_t); __xn_section(descriptor,reg.xn_t); __domain_section(descriptor, reg.domain); __p_section(descriptor, reg.e_t); __ap_section(descriptor, reg.priv_t, reg.user_t, 1); __shared_section(descriptor,reg.sh_t); __global_section(descriptor,reg.g_t); __secure_section(descriptor,reg.sec_t); *descriptor &= SECTION_MASK; *descriptor |= SECTION_DESCRIPTOR; return 0; } /** \brief Create a L1 and L2 4k/64k page descriptor The function creates a 4k/64k page descriptor. Assumptions: - TEX remap disabled, so memory type and attributes are described directly by bits in the descriptor - Functions always return 0 \param [out] descriptor L1 descriptor \param [out] descriptor2 L2 descriptor \param [in] reg 4k/64k page attributes \return 0 */ __STATIC_INLINE int __get_page_descriptor(uint32_t *descriptor, uint32_t *descriptor2, mmu_region_attributes_Type reg) { *descriptor = 0; *descriptor2 = 0; switch (reg.rg_t) { case PAGE_4k: __memory_page(descriptor2, reg.mem_t, reg.outer_norm_t, reg.inner_norm_t, PAGE_4k); __xn_page(descriptor2, reg.xn_t, PAGE_4k); __domain_page(descriptor, reg.domain); __p_page(descriptor, reg.e_t); __ap_page(descriptor2, reg.priv_t, reg.user_t, 1); __shared_page(descriptor2,reg.sh_t); __global_page(descriptor2,reg.g_t); __secure_page(descriptor,reg.sec_t); *descriptor &= PAGE_L1_MASK; *descriptor |= PAGE_L1_DESCRIPTOR; *descriptor2 &= PAGE_L2_4K_MASK; *descriptor2 |= PAGE_L2_4K_DESC; break; case PAGE_64k: __memory_page(descriptor2, reg.mem_t, reg.outer_norm_t, reg.inner_norm_t, PAGE_64k); __xn_page(descriptor2, reg.xn_t, PAGE_64k); __domain_page(descriptor, reg.domain); __p_page(descriptor, reg.e_t); __ap_page(descriptor2, reg.priv_t, reg.user_t, 1); __shared_page(descriptor2,reg.sh_t); __global_page(descriptor2,reg.g_t); __secure_page(descriptor,reg.sec_t); *descriptor &= PAGE_L1_MASK; *descriptor |= PAGE_L1_DESCRIPTOR; *descriptor2 &= PAGE_L2_64K_MASK; *descriptor2 |= PAGE_L2_64K_DESC; break; case SECTION: //error break; } return 0; } /** \brief Create a 1MB Section \param [in] ttb Translation table base address \param [in] base_address Section base address \param [in] count Number of sections to create \param [in] descriptor_l1 L1 descriptor (region attributes) */ __STATIC_INLINE void __TTSection(uint32_t *ttb, uint32_t base_address, uint32_t count, uint32_t descriptor_l1) { uint32_t offset; uint32_t entry; uint32_t i; offset = base_address >> 20; entry = (base_address & 0xFFF00000) | descriptor_l1; //4 bytes aligned ttb = ttb + offset; for (i = 0; i < count; i++ ) { //4 bytes aligned *ttb++ = entry; entry += OFFSET_1M; } } /** \brief Create a 4k page entry \param [in] ttb L1 table base address \param [in] base_address 4k base address \param [in] count Number of 4k pages to create \param [in] descriptor_l1 L1 descriptor (region attributes) \param [in] ttb_l2 L2 table base address \param [in] descriptor_l2 L2 descriptor (region attributes) */ __STATIC_INLINE void __TTPage_4k(uint32_t *ttb, uint32_t base_address, uint32_t count, uint32_t descriptor_l1, uint32_t *ttb_l2, uint32_t descriptor_l2 ) { uint32_t offset, offset2; uint32_t entry, entry2; uint32_t i; offset = base_address >> 20; entry = ((int)ttb_l2 & 0xFFFFFC00) | descriptor_l1; //4 bytes aligned ttb += offset; //create l1_entry *ttb = entry; offset2 = (base_address & 0xff000) >> 12; ttb_l2 += offset2; entry2 = (base_address & 0xFFFFF000) | descriptor_l2; for (i = 0; i < count; i++ ) { //4 bytes aligned *ttb_l2++ = entry2; entry2 += OFFSET_4K; } } /** \brief Create a 64k page entry \param [in] ttb L1 table base address \param [in] base_address 64k base address \param [in] count Number of 64k pages to create \param [in] descriptor_l1 L1 descriptor (region attributes) \param [in] ttb_l2 L2 table base address \param [in] descriptor_l2 L2 descriptor (region attributes) */ __STATIC_INLINE void __TTPage_64k(uint32_t *ttb, uint32_t base_address, uint32_t count, uint32_t descriptor_l1, uint32_t *ttb_l2, uint32_t descriptor_l2 ) { uint32_t offset, offset2; uint32_t entry, entry2; uint32_t i,j; offset = base_address >> 20; entry = ((int)ttb_l2 & 0xFFFFFC00) | descriptor_l1; //4 bytes aligned ttb += offset; //create l1_entry *ttb = entry; offset2 = (base_address & 0xff000) >> 12; ttb_l2 += offset2; entry2 = (base_address & 0xFFFF0000) | descriptor_l2; for (i = 0; i < count; i++ ) { //create 16 entries for (j = 0; j < 16; j++) //4 bytes aligned *ttb_l2++ = entry2; entry2 += OFFSET_64K; } } /*@} end of MMU_Functions */ #endif #ifdef __cplusplus } #endif ================================================ FILE: Zelig/mbed/TARGET_LPC1768/core_cm0.h ================================================ /**************************************************************************//** * @file core_cm0.h * @brief CMSIS Cortex-M0 Core Peripheral Access Layer Header File * @version V3.20 * @date 25. February 2013 * * @note * ******************************************************************************/ /* Copyright (c) 2009 - 2013 ARM LIMITED All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: - Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. - Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. - Neither the name of ARM 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 COPYRIGHT HOLDERS AND 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. ---------------------------------------------------------------------------*/ #if defined ( __ICCARM__ ) #pragma system_include /* treat file as system include file for MISRA check */ #endif #ifdef __cplusplus extern "C" { #endif #ifndef __CORE_CM0_H_GENERIC #define __CORE_CM0_H_GENERIC /** \page CMSIS_MISRA_Exceptions MISRA-C:2004 Compliance Exceptions CMSIS violates the following MISRA-C:2004 rules: \li Required Rule 8.5, object/function definition in header file.
Function definitions in header files are used to allow 'inlining'. \li Required Rule 18.4, declaration of union type or object of union type: '{...}'.
Unions are used for effective representation of core registers. \li Advisory Rule 19.7, Function-like macro defined.
Function-like macros are used to allow more efficient code. */ /******************************************************************************* * CMSIS definitions ******************************************************************************/ /** \ingroup Cortex_M0 @{ */ /* CMSIS CM0 definitions */ #define __CM0_CMSIS_VERSION_MAIN (0x03) /*!< [31:16] CMSIS HAL main version */ #define __CM0_CMSIS_VERSION_SUB (0x20) /*!< [15:0] CMSIS HAL sub version */ #define __CM0_CMSIS_VERSION ((__CM0_CMSIS_VERSION_MAIN << 16) | \ __CM0_CMSIS_VERSION_SUB ) /*!< CMSIS HAL version number */ #define __CORTEX_M (0x00) /*!< Cortex-M Core */ #if defined ( __CC_ARM ) #define __ASM __asm /*!< asm keyword for ARM Compiler */ #define __INLINE __inline /*!< inline keyword for ARM Compiler */ #define __STATIC_INLINE static __inline #elif defined ( __ICCARM__ ) #define __ASM __asm /*!< asm keyword for IAR Compiler */ #define __INLINE inline /*!< inline keyword for IAR Compiler. Only available in High optimization mode! */ #define __STATIC_INLINE static inline #elif defined ( __GNUC__ ) #define __ASM __asm /*!< asm keyword for GNU Compiler */ #define __INLINE inline /*!< inline keyword for GNU Compiler */ #define __STATIC_INLINE static inline #elif defined ( __TASKING__ ) #define __ASM __asm /*!< asm keyword for TASKING Compiler */ #define __INLINE inline /*!< inline keyword for TASKING Compiler */ #define __STATIC_INLINE static inline #endif /** __FPU_USED indicates whether an FPU is used or not. This core does not support an FPU at all */ #define __FPU_USED 0 #if defined ( __CC_ARM ) #if defined __TARGET_FPU_VFP #warning "Compiler generates FPU instructions for a device without an FPU (check __FPU_PRESENT)" #endif #elif defined ( __ICCARM__ ) #if defined __ARMVFP__ #warning "Compiler generates FPU instructions for a device without an FPU (check __FPU_PRESENT)" #endif #elif defined ( __GNUC__ ) #if defined (__VFP_FP__) && !defined(__SOFTFP__) #warning "Compiler generates FPU instructions for a device without an FPU (check __FPU_PRESENT)" #endif #elif defined ( __TASKING__ ) #if defined __FPU_VFP__ #error "Compiler generates FPU instructions for a device without an FPU (check __FPU_PRESENT)" #endif #endif #include /* standard types definitions */ #include /* Core Instruction Access */ #include /* Core Function Access */ #endif /* __CORE_CM0_H_GENERIC */ #ifndef __CMSIS_GENERIC #ifndef __CORE_CM0_H_DEPENDANT #define __CORE_CM0_H_DEPENDANT /* check device defines and use defaults */ #if defined __CHECK_DEVICE_DEFINES #ifndef __CM0_REV #define __CM0_REV 0x0000 #warning "__CM0_REV not defined in device header file; using default!" #endif #ifndef __NVIC_PRIO_BITS #define __NVIC_PRIO_BITS 2 #warning "__NVIC_PRIO_BITS not defined in device header file; using default!" #endif #ifndef __Vendor_SysTickConfig #define __Vendor_SysTickConfig 0 #warning "__Vendor_SysTickConfig not defined in device header file; using default!" #endif #endif /* IO definitions (access restrictions to peripheral registers) */ /** \defgroup CMSIS_glob_defs CMSIS Global Defines IO Type Qualifiers are used \li to specify the access to peripheral variables. \li for automatic generation of peripheral register debug information. */ #ifdef __cplusplus #define __I volatile /*!< Defines 'read only' permissions */ #else #define __I volatile const /*!< Defines 'read only' permissions */ #endif #define __O volatile /*!< Defines 'write only' permissions */ #define __IO volatile /*!< Defines 'read / write' permissions */ /*@} end of group Cortex_M0 */ /******************************************************************************* * Register Abstraction Core Register contain: - Core Register - Core NVIC Register - Core SCB Register - Core SysTick Register ******************************************************************************/ /** \defgroup CMSIS_core_register Defines and Type Definitions \brief Type definitions and defines for Cortex-M processor based devices. */ /** \ingroup CMSIS_core_register \defgroup CMSIS_CORE Status and Control Registers \brief Core Register type definitions. @{ */ /** \brief Union type to access the Application Program Status Register (APSR). */ typedef union { struct { #if (__CORTEX_M != 0x04) uint32_t _reserved0:27; /*!< bit: 0..26 Reserved */ #else uint32_t _reserved0:16; /*!< bit: 0..15 Reserved */ uint32_t GE:4; /*!< bit: 16..19 Greater than or Equal flags */ uint32_t _reserved1:7; /*!< bit: 20..26 Reserved */ #endif uint32_t Q:1; /*!< bit: 27 Saturation condition flag */ uint32_t V:1; /*!< bit: 28 Overflow condition code flag */ uint32_t C:1; /*!< bit: 29 Carry condition code flag */ uint32_t Z:1; /*!< bit: 30 Zero condition code flag */ uint32_t N:1; /*!< bit: 31 Negative condition code flag */ } b; /*!< Structure used for bit access */ uint32_t w; /*!< Type used for word access */ } APSR_Type; /** \brief Union type to access the Interrupt Program Status Register (IPSR). */ typedef union { struct { uint32_t ISR:9; /*!< bit: 0.. 8 Exception number */ uint32_t _reserved0:23; /*!< bit: 9..31 Reserved */ } b; /*!< Structure used for bit access */ uint32_t w; /*!< Type used for word access */ } IPSR_Type; /** \brief Union type to access the Special-Purpose Program Status Registers (xPSR). */ typedef union { struct { uint32_t ISR:9; /*!< bit: 0.. 8 Exception number */ #if (__CORTEX_M != 0x04) uint32_t _reserved0:15; /*!< bit: 9..23 Reserved */ #else uint32_t _reserved0:7; /*!< bit: 9..15 Reserved */ uint32_t GE:4; /*!< bit: 16..19 Greater than or Equal flags */ uint32_t _reserved1:4; /*!< bit: 20..23 Reserved */ #endif uint32_t T:1; /*!< bit: 24 Thumb bit (read 0) */ uint32_t IT:2; /*!< bit: 25..26 saved IT state (read 0) */ uint32_t Q:1; /*!< bit: 27 Saturation condition flag */ uint32_t V:1; /*!< bit: 28 Overflow condition code flag */ uint32_t C:1; /*!< bit: 29 Carry condition code flag */ uint32_t Z:1; /*!< bit: 30 Zero condition code flag */ uint32_t N:1; /*!< bit: 31 Negative condition code flag */ } b; /*!< Structure used for bit access */ uint32_t w; /*!< Type used for word access */ } xPSR_Type; /** \brief Union type to access the Control Registers (CONTROL). */ typedef union { struct { uint32_t nPRIV:1; /*!< bit: 0 Execution privilege in Thread mode */ uint32_t SPSEL:1; /*!< bit: 1 Stack to be used */ uint32_t FPCA:1; /*!< bit: 2 FP extension active flag */ uint32_t _reserved0:29; /*!< bit: 3..31 Reserved */ } b; /*!< Structure used for bit access */ uint32_t w; /*!< Type used for word access */ } CONTROL_Type; /*@} end of group CMSIS_CORE */ /** \ingroup CMSIS_core_register \defgroup CMSIS_NVIC Nested Vectored Interrupt Controller (NVIC) \brief Type definitions for the NVIC Registers @{ */ /** \brief Structure type to access the Nested Vectored Interrupt Controller (NVIC). */ typedef struct { __IO uint32_t ISER[1]; /*!< Offset: 0x000 (R/W) Interrupt Set Enable Register */ uint32_t RESERVED0[31]; __IO uint32_t ICER[1]; /*!< Offset: 0x080 (R/W) Interrupt Clear Enable Register */ uint32_t RSERVED1[31]; __IO uint32_t ISPR[1]; /*!< Offset: 0x100 (R/W) Interrupt Set Pending Register */ uint32_t RESERVED2[31]; __IO uint32_t ICPR[1]; /*!< Offset: 0x180 (R/W) Interrupt Clear Pending Register */ uint32_t RESERVED3[31]; uint32_t RESERVED4[64]; __IO uint32_t IP[8]; /*!< Offset: 0x300 (R/W) Interrupt Priority Register */ } NVIC_Type; /*@} end of group CMSIS_NVIC */ /** \ingroup CMSIS_core_register \defgroup CMSIS_SCB System Control Block (SCB) \brief Type definitions for the System Control Block Registers @{ */ /** \brief Structure type to access the System Control Block (SCB). */ typedef struct { __I uint32_t CPUID; /*!< Offset: 0x000 (R/ ) CPUID Base Register */ __IO uint32_t ICSR; /*!< Offset: 0x004 (R/W) Interrupt Control and State Register */ uint32_t RESERVED0; __IO uint32_t AIRCR; /*!< Offset: 0x00C (R/W) Application Interrupt and Reset Control Register */ __IO uint32_t SCR; /*!< Offset: 0x010 (R/W) System Control Register */ __IO uint32_t CCR; /*!< Offset: 0x014 (R/W) Configuration Control Register */ uint32_t RESERVED1; __IO uint32_t SHP[2]; /*!< Offset: 0x01C (R/W) System Handlers Priority Registers. [0] is RESERVED */ __IO uint32_t SHCSR; /*!< Offset: 0x024 (R/W) System Handler Control and State Register */ } SCB_Type; /* SCB CPUID Register Definitions */ #define SCB_CPUID_IMPLEMENTER_Pos 24 /*!< SCB CPUID: IMPLEMENTER Position */ #define SCB_CPUID_IMPLEMENTER_Msk (0xFFUL << SCB_CPUID_IMPLEMENTER_Pos) /*!< SCB CPUID: IMPLEMENTER Mask */ #define SCB_CPUID_VARIANT_Pos 20 /*!< SCB CPUID: VARIANT Position */ #define SCB_CPUID_VARIANT_Msk (0xFUL << SCB_CPUID_VARIANT_Pos) /*!< SCB CPUID: VARIANT Mask */ #define SCB_CPUID_ARCHITECTURE_Pos 16 /*!< SCB CPUID: ARCHITECTURE Position */ #define SCB_CPUID_ARCHITECTURE_Msk (0xFUL << SCB_CPUID_ARCHITECTURE_Pos) /*!< SCB CPUID: ARCHITECTURE Mask */ #define SCB_CPUID_PARTNO_Pos 4 /*!< SCB CPUID: PARTNO Position */ #define SCB_CPUID_PARTNO_Msk (0xFFFUL << SCB_CPUID_PARTNO_Pos) /*!< SCB CPUID: PARTNO Mask */ #define SCB_CPUID_REVISION_Pos 0 /*!< SCB CPUID: REVISION Position */ #define SCB_CPUID_REVISION_Msk (0xFUL << SCB_CPUID_REVISION_Pos) /*!< SCB CPUID: REVISION Mask */ /* SCB Interrupt Control State Register Definitions */ #define SCB_ICSR_NMIPENDSET_Pos 31 /*!< SCB ICSR: NMIPENDSET Position */ #define SCB_ICSR_NMIPENDSET_Msk (1UL << SCB_ICSR_NMIPENDSET_Pos) /*!< SCB ICSR: NMIPENDSET Mask */ #define SCB_ICSR_PENDSVSET_Pos 28 /*!< SCB ICSR: PENDSVSET Position */ #define SCB_ICSR_PENDSVSET_Msk (1UL << SCB_ICSR_PENDSVSET_Pos) /*!< SCB ICSR: PENDSVSET Mask */ #define SCB_ICSR_PENDSVCLR_Pos 27 /*!< SCB ICSR: PENDSVCLR Position */ #define SCB_ICSR_PENDSVCLR_Msk (1UL << SCB_ICSR_PENDSVCLR_Pos) /*!< SCB ICSR: PENDSVCLR Mask */ #define SCB_ICSR_PENDSTSET_Pos 26 /*!< SCB ICSR: PENDSTSET Position */ #define SCB_ICSR_PENDSTSET_Msk (1UL << SCB_ICSR_PENDSTSET_Pos) /*!< SCB ICSR: PENDSTSET Mask */ #define SCB_ICSR_PENDSTCLR_Pos 25 /*!< SCB ICSR: PENDSTCLR Position */ #define SCB_ICSR_PENDSTCLR_Msk (1UL << SCB_ICSR_PENDSTCLR_Pos) /*!< SCB ICSR: PENDSTCLR Mask */ #define SCB_ICSR_ISRPREEMPT_Pos 23 /*!< SCB ICSR: ISRPREEMPT Position */ #define SCB_ICSR_ISRPREEMPT_Msk (1UL << SCB_ICSR_ISRPREEMPT_Pos) /*!< SCB ICSR: ISRPREEMPT Mask */ #define SCB_ICSR_ISRPENDING_Pos 22 /*!< SCB ICSR: ISRPENDING Position */ #define SCB_ICSR_ISRPENDING_Msk (1UL << SCB_ICSR_ISRPENDING_Pos) /*!< SCB ICSR: ISRPENDING Mask */ #define SCB_ICSR_VECTPENDING_Pos 12 /*!< SCB ICSR: VECTPENDING Position */ #define SCB_ICSR_VECTPENDING_Msk (0x1FFUL << SCB_ICSR_VECTPENDING_Pos) /*!< SCB ICSR: VECTPENDING Mask */ #define SCB_ICSR_VECTACTIVE_Pos 0 /*!< SCB ICSR: VECTACTIVE Position */ #define SCB_ICSR_VECTACTIVE_Msk (0x1FFUL << SCB_ICSR_VECTACTIVE_Pos) /*!< SCB ICSR: VECTACTIVE Mask */ /* SCB Application Interrupt and Reset Control Register Definitions */ #define SCB_AIRCR_VECTKEY_Pos 16 /*!< SCB AIRCR: VECTKEY Position */ #define SCB_AIRCR_VECTKEY_Msk (0xFFFFUL << SCB_AIRCR_VECTKEY_Pos) /*!< SCB AIRCR: VECTKEY Mask */ #define SCB_AIRCR_VECTKEYSTAT_Pos 16 /*!< SCB AIRCR: VECTKEYSTAT Position */ #define SCB_AIRCR_VECTKEYSTAT_Msk (0xFFFFUL << SCB_AIRCR_VECTKEYSTAT_Pos) /*!< SCB AIRCR: VECTKEYSTAT Mask */ #define SCB_AIRCR_ENDIANESS_Pos 15 /*!< SCB AIRCR: ENDIANESS Position */ #define SCB_AIRCR_ENDIANESS_Msk (1UL << SCB_AIRCR_ENDIANESS_Pos) /*!< SCB AIRCR: ENDIANESS Mask */ #define SCB_AIRCR_SYSRESETREQ_Pos 2 /*!< SCB AIRCR: SYSRESETREQ Position */ #define SCB_AIRCR_SYSRESETREQ_Msk (1UL << SCB_AIRCR_SYSRESETREQ_Pos) /*!< SCB AIRCR: SYSRESETREQ Mask */ #define SCB_AIRCR_VECTCLRACTIVE_Pos 1 /*!< SCB AIRCR: VECTCLRACTIVE Position */ #define SCB_AIRCR_VECTCLRACTIVE_Msk (1UL << SCB_AIRCR_VECTCLRACTIVE_Pos) /*!< SCB AIRCR: VECTCLRACTIVE Mask */ /* SCB System Control Register Definitions */ #define SCB_SCR_SEVONPEND_Pos 4 /*!< SCB SCR: SEVONPEND Position */ #define SCB_SCR_SEVONPEND_Msk (1UL << SCB_SCR_SEVONPEND_Pos) /*!< SCB SCR: SEVONPEND Mask */ #define SCB_SCR_SLEEPDEEP_Pos 2 /*!< SCB SCR: SLEEPDEEP Position */ #define SCB_SCR_SLEEPDEEP_Msk (1UL << SCB_SCR_SLEEPDEEP_Pos) /*!< SCB SCR: SLEEPDEEP Mask */ #define SCB_SCR_SLEEPONEXIT_Pos 1 /*!< SCB SCR: SLEEPONEXIT Position */ #define SCB_SCR_SLEEPONEXIT_Msk (1UL << SCB_SCR_SLEEPONEXIT_Pos) /*!< SCB SCR: SLEEPONEXIT Mask */ /* SCB Configuration Control Register Definitions */ #define SCB_CCR_STKALIGN_Pos 9 /*!< SCB CCR: STKALIGN Position */ #define SCB_CCR_STKALIGN_Msk (1UL << SCB_CCR_STKALIGN_Pos) /*!< SCB CCR: STKALIGN Mask */ #define SCB_CCR_UNALIGN_TRP_Pos 3 /*!< SCB CCR: UNALIGN_TRP Position */ #define SCB_CCR_UNALIGN_TRP_Msk (1UL << SCB_CCR_UNALIGN_TRP_Pos) /*!< SCB CCR: UNALIGN_TRP Mask */ /* SCB System Handler Control and State Register Definitions */ #define SCB_SHCSR_SVCALLPENDED_Pos 15 /*!< SCB SHCSR: SVCALLPENDED Position */ #define SCB_SHCSR_SVCALLPENDED_Msk (1UL << SCB_SHCSR_SVCALLPENDED_Pos) /*!< SCB SHCSR: SVCALLPENDED Mask */ /*@} end of group CMSIS_SCB */ /** \ingroup CMSIS_core_register \defgroup CMSIS_SysTick System Tick Timer (SysTick) \brief Type definitions for the System Timer Registers. @{ */ /** \brief Structure type to access the System Timer (SysTick). */ typedef struct { __IO uint32_t CTRL; /*!< Offset: 0x000 (R/W) SysTick Control and Status Register */ __IO uint32_t LOAD; /*!< Offset: 0x004 (R/W) SysTick Reload Value Register */ __IO uint32_t VAL; /*!< Offset: 0x008 (R/W) SysTick Current Value Register */ __I uint32_t CALIB; /*!< Offset: 0x00C (R/ ) SysTick Calibration Register */ } SysTick_Type; /* SysTick Control / Status Register Definitions */ #define SysTick_CTRL_COUNTFLAG_Pos 16 /*!< SysTick CTRL: COUNTFLAG Position */ #define SysTick_CTRL_COUNTFLAG_Msk (1UL << SysTick_CTRL_COUNTFLAG_Pos) /*!< SysTick CTRL: COUNTFLAG Mask */ #define SysTick_CTRL_CLKSOURCE_Pos 2 /*!< SysTick CTRL: CLKSOURCE Position */ #define SysTick_CTRL_CLKSOURCE_Msk (1UL << SysTick_CTRL_CLKSOURCE_Pos) /*!< SysTick CTRL: CLKSOURCE Mask */ #define SysTick_CTRL_TICKINT_Pos 1 /*!< SysTick CTRL: TICKINT Position */ #define SysTick_CTRL_TICKINT_Msk (1UL << SysTick_CTRL_TICKINT_Pos) /*!< SysTick CTRL: TICKINT Mask */ #define SysTick_CTRL_ENABLE_Pos 0 /*!< SysTick CTRL: ENABLE Position */ #define SysTick_CTRL_ENABLE_Msk (1UL << SysTick_CTRL_ENABLE_Pos) /*!< SysTick CTRL: ENABLE Mask */ /* SysTick Reload Register Definitions */ #define SysTick_LOAD_RELOAD_Pos 0 /*!< SysTick LOAD: RELOAD Position */ #define SysTick_LOAD_RELOAD_Msk (0xFFFFFFUL << SysTick_LOAD_RELOAD_Pos) /*!< SysTick LOAD: RELOAD Mask */ /* SysTick Current Register Definitions */ #define SysTick_VAL_CURRENT_Pos 0 /*!< SysTick VAL: CURRENT Position */ #define SysTick_VAL_CURRENT_Msk (0xFFFFFFUL << SysTick_VAL_CURRENT_Pos) /*!< SysTick VAL: CURRENT Mask */ /* SysTick Calibration Register Definitions */ #define SysTick_CALIB_NOREF_Pos 31 /*!< SysTick CALIB: NOREF Position */ #define SysTick_CALIB_NOREF_Msk (1UL << SysTick_CALIB_NOREF_Pos) /*!< SysTick CALIB: NOREF Mask */ #define SysTick_CALIB_SKEW_Pos 30 /*!< SysTick CALIB: SKEW Position */ #define SysTick_CALIB_SKEW_Msk (1UL << SysTick_CALIB_SKEW_Pos) /*!< SysTick CALIB: SKEW Mask */ #define SysTick_CALIB_TENMS_Pos 0 /*!< SysTick CALIB: TENMS Position */ #define SysTick_CALIB_TENMS_Msk (0xFFFFFFUL << SysTick_VAL_CURRENT_Pos) /*!< SysTick CALIB: TENMS Mask */ /*@} end of group CMSIS_SysTick */ /** \ingroup CMSIS_core_register \defgroup CMSIS_CoreDebug Core Debug Registers (CoreDebug) \brief Cortex-M0 Core Debug Registers (DCB registers, SHCSR, and DFSR) are only accessible over DAP and not via processor. Therefore they are not covered by the Cortex-M0 header file. @{ */ /*@} end of group CMSIS_CoreDebug */ /** \ingroup CMSIS_core_register \defgroup CMSIS_core_base Core Definitions \brief Definitions for base addresses, unions, and structures. @{ */ /* Memory mapping of Cortex-M0 Hardware */ #define SCS_BASE (0xE000E000UL) /*!< System Control Space Base Address */ #define SysTick_BASE (SCS_BASE + 0x0010UL) /*!< SysTick Base Address */ #define NVIC_BASE (SCS_BASE + 0x0100UL) /*!< NVIC Base Address */ #define SCB_BASE (SCS_BASE + 0x0D00UL) /*!< System Control Block Base Address */ #define SCB ((SCB_Type *) SCB_BASE ) /*!< SCB configuration struct */ #define SysTick ((SysTick_Type *) SysTick_BASE ) /*!< SysTick configuration struct */ #define NVIC ((NVIC_Type *) NVIC_BASE ) /*!< NVIC configuration struct */ /*@} */ /******************************************************************************* * Hardware Abstraction Layer Core Function Interface contains: - Core NVIC Functions - Core SysTick Functions - Core Register Access Functions ******************************************************************************/ /** \defgroup CMSIS_Core_FunctionInterface Functions and Instructions Reference */ /* ########################## NVIC functions #################################### */ /** \ingroup CMSIS_Core_FunctionInterface \defgroup CMSIS_Core_NVICFunctions NVIC Functions \brief Functions that manage interrupts and exceptions via the NVIC. @{ */ /* Interrupt Priorities are WORD accessible only under ARMv6M */ /* The following MACROS handle generation of the register offset and byte masks */ #define _BIT_SHIFT(IRQn) ( (((uint32_t)(IRQn) ) & 0x03) * 8 ) #define _SHP_IDX(IRQn) ( ((((uint32_t)(IRQn) & 0x0F)-8) >> 2) ) #define _IP_IDX(IRQn) ( ((uint32_t)(IRQn) >> 2) ) /** \brief Enable External Interrupt The function enables a device-specific interrupt in the NVIC interrupt controller. \param [in] IRQn External interrupt number. Value cannot be negative. */ __STATIC_INLINE void NVIC_EnableIRQ(IRQn_Type IRQn) { NVIC->ISER[0] = (1 << ((uint32_t)(IRQn) & 0x1F)); } /** \brief Disable External Interrupt The function disables a device-specific interrupt in the NVIC interrupt controller. \param [in] IRQn External interrupt number. Value cannot be negative. */ __STATIC_INLINE void NVIC_DisableIRQ(IRQn_Type IRQn) { NVIC->ICER[0] = (1 << ((uint32_t)(IRQn) & 0x1F)); } /** \brief Get Pending Interrupt The function reads the pending register in the NVIC and returns the pending bit for the specified interrupt. \param [in] IRQn Interrupt number. \return 0 Interrupt status is not pending. \return 1 Interrupt status is pending. */ __STATIC_INLINE uint32_t NVIC_GetPendingIRQ(IRQn_Type IRQn) { return((uint32_t) ((NVIC->ISPR[0] & (1 << ((uint32_t)(IRQn) & 0x1F)))?1:0)); } /** \brief Set Pending Interrupt The function sets the pending bit of an external interrupt. \param [in] IRQn Interrupt number. Value cannot be negative. */ __STATIC_INLINE void NVIC_SetPendingIRQ(IRQn_Type IRQn) { NVIC->ISPR[0] = (1 << ((uint32_t)(IRQn) & 0x1F)); } /** \brief Clear Pending Interrupt The function clears the pending bit of an external interrupt. \param [in] IRQn External interrupt number. Value cannot be negative. */ __STATIC_INLINE void NVIC_ClearPendingIRQ(IRQn_Type IRQn) { NVIC->ICPR[0] = (1 << ((uint32_t)(IRQn) & 0x1F)); /* Clear pending interrupt */ } /** \brief Set Interrupt Priority The function sets the priority of an interrupt. \note The priority cannot be set for every core interrupt. \param [in] IRQn Interrupt number. \param [in] priority Priority to set. */ __STATIC_INLINE void NVIC_SetPriority(IRQn_Type IRQn, uint32_t priority) { if(IRQn < 0) { SCB->SHP[_SHP_IDX(IRQn)] = (SCB->SHP[_SHP_IDX(IRQn)] & ~(0xFF << _BIT_SHIFT(IRQn))) | (((priority << (8 - __NVIC_PRIO_BITS)) & 0xFF) << _BIT_SHIFT(IRQn)); } else { NVIC->IP[_IP_IDX(IRQn)] = (NVIC->IP[_IP_IDX(IRQn)] & ~(0xFF << _BIT_SHIFT(IRQn))) | (((priority << (8 - __NVIC_PRIO_BITS)) & 0xFF) << _BIT_SHIFT(IRQn)); } } /** \brief Get Interrupt Priority The function reads the priority of an interrupt. The interrupt number can be positive to specify an external (device specific) interrupt, or negative to specify an internal (core) interrupt. \param [in] IRQn Interrupt number. \return Interrupt Priority. Value is aligned automatically to the implemented priority bits of the microcontroller. */ __STATIC_INLINE uint32_t NVIC_GetPriority(IRQn_Type IRQn) { if(IRQn < 0) { return((uint32_t)(((SCB->SHP[_SHP_IDX(IRQn)] >> _BIT_SHIFT(IRQn) ) & 0xFF) >> (8 - __NVIC_PRIO_BITS))); } /* get priority for Cortex-M0 system interrupts */ else { return((uint32_t)(((NVIC->IP[ _IP_IDX(IRQn)] >> _BIT_SHIFT(IRQn) ) & 0xFF) >> (8 - __NVIC_PRIO_BITS))); } /* get priority for device specific interrupts */ } /** \brief System Reset The function initiates a system reset request to reset the MCU. */ __STATIC_INLINE void NVIC_SystemReset(void) { __DSB(); /* Ensure all outstanding memory accesses included buffered write are completed before reset */ SCB->AIRCR = ((0x5FA << SCB_AIRCR_VECTKEY_Pos) | SCB_AIRCR_SYSRESETREQ_Msk); __DSB(); /* Ensure completion of memory access */ while(1); /* wait until reset */ } /*@} end of CMSIS_Core_NVICFunctions */ /* ################################## SysTick function ############################################ */ /** \ingroup CMSIS_Core_FunctionInterface \defgroup CMSIS_Core_SysTickFunctions SysTick Functions \brief Functions that configure the System. @{ */ #if (__Vendor_SysTickConfig == 0) /** \brief System Tick Configuration The function initializes the System Timer and its interrupt, and starts the System Tick Timer. Counter is in free running mode to generate periodic interrupts. \param [in] ticks Number of ticks between two interrupts. \return 0 Function succeeded. \return 1 Function failed. \note When the variable __Vendor_SysTickConfig is set to 1, then the function SysTick_Config is not included. In this case, the file device.h must contain a vendor-specific implementation of this function. */ __STATIC_INLINE uint32_t SysTick_Config(uint32_t ticks) { if ((ticks - 1) > SysTick_LOAD_RELOAD_Msk) return (1); /* Reload value impossible */ SysTick->LOAD = ticks - 1; /* set reload register */ NVIC_SetPriority (SysTick_IRQn, (1<<__NVIC_PRIO_BITS) - 1); /* set Priority for Systick Interrupt */ SysTick->VAL = 0; /* Load the SysTick Counter Value */ SysTick->CTRL = SysTick_CTRL_CLKSOURCE_Msk | SysTick_CTRL_TICKINT_Msk | SysTick_CTRL_ENABLE_Msk; /* Enable SysTick IRQ and SysTick Timer */ return (0); /* Function successful */ } #endif /*@} end of CMSIS_Core_SysTickFunctions */ #endif /* __CORE_CM0_H_DEPENDANT */ #endif /* __CMSIS_GENERIC */ #ifdef __cplusplus } #endif ================================================ FILE: Zelig/mbed/TARGET_LPC1768/core_cm0plus.h ================================================ /**************************************************************************//** * @file core_cm0plus.h * @brief CMSIS Cortex-M0+ Core Peripheral Access Layer Header File * @version V3.20 * @date 25. February 2013 * * @note * ******************************************************************************/ /* Copyright (c) 2009 - 2013 ARM LIMITED All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: - Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. - Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. - Neither the name of ARM 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 COPYRIGHT HOLDERS AND 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. ---------------------------------------------------------------------------*/ #if defined ( __ICCARM__ ) #pragma system_include /* treat file as system include file for MISRA check */ #endif #ifdef __cplusplus extern "C" { #endif #ifndef __CORE_CM0PLUS_H_GENERIC #define __CORE_CM0PLUS_H_GENERIC /** \page CMSIS_MISRA_Exceptions MISRA-C:2004 Compliance Exceptions CMSIS violates the following MISRA-C:2004 rules: \li Required Rule 8.5, object/function definition in header file.
Function definitions in header files are used to allow 'inlining'. \li Required Rule 18.4, declaration of union type or object of union type: '{...}'.
Unions are used for effective representation of core registers. \li Advisory Rule 19.7, Function-like macro defined.
Function-like macros are used to allow more efficient code. */ /******************************************************************************* * CMSIS definitions ******************************************************************************/ /** \ingroup Cortex-M0+ @{ */ /* CMSIS CM0P definitions */ #define __CM0PLUS_CMSIS_VERSION_MAIN (0x03) /*!< [31:16] CMSIS HAL main version */ #define __CM0PLUS_CMSIS_VERSION_SUB (0x20) /*!< [15:0] CMSIS HAL sub version */ #define __CM0PLUS_CMSIS_VERSION ((__CM0PLUS_CMSIS_VERSION_MAIN << 16) | \ __CM0PLUS_CMSIS_VERSION_SUB) /*!< CMSIS HAL version number */ #define __CORTEX_M (0x00) /*!< Cortex-M Core */ #if defined ( __CC_ARM ) #define __ASM __asm /*!< asm keyword for ARM Compiler */ #define __INLINE __inline /*!< inline keyword for ARM Compiler */ #define __STATIC_INLINE static __inline #elif defined ( __ICCARM__ ) #define __ASM __asm /*!< asm keyword for IAR Compiler */ #define __INLINE inline /*!< inline keyword for IAR Compiler. Only available in High optimization mode! */ #define __STATIC_INLINE static inline #elif defined ( __GNUC__ ) #define __ASM __asm /*!< asm keyword for GNU Compiler */ #define __INLINE inline /*!< inline keyword for GNU Compiler */ #define __STATIC_INLINE static inline #elif defined ( __TASKING__ ) #define __ASM __asm /*!< asm keyword for TASKING Compiler */ #define __INLINE inline /*!< inline keyword for TASKING Compiler */ #define __STATIC_INLINE static inline #endif /** __FPU_USED indicates whether an FPU is used or not. This core does not support an FPU at all */ #define __FPU_USED 0 #if defined ( __CC_ARM ) #if defined __TARGET_FPU_VFP #warning "Compiler generates FPU instructions for a device without an FPU (check __FPU_PRESENT)" #endif #elif defined ( __ICCARM__ ) #if defined __ARMVFP__ #warning "Compiler generates FPU instructions for a device without an FPU (check __FPU_PRESENT)" #endif #elif defined ( __GNUC__ ) #if defined (__VFP_FP__) && !defined(__SOFTFP__) #warning "Compiler generates FPU instructions for a device without an FPU (check __FPU_PRESENT)" #endif #elif defined ( __TASKING__ ) #if defined __FPU_VFP__ #error "Compiler generates FPU instructions for a device without an FPU (check __FPU_PRESENT)" #endif #endif #include /* standard types definitions */ #include /* Core Instruction Access */ #include /* Core Function Access */ #endif /* __CORE_CM0PLUS_H_GENERIC */ #ifndef __CMSIS_GENERIC #ifndef __CORE_CM0PLUS_H_DEPENDANT #define __CORE_CM0PLUS_H_DEPENDANT /* check device defines and use defaults */ #if defined __CHECK_DEVICE_DEFINES #ifndef __CM0PLUS_REV #define __CM0PLUS_REV 0x0000 #warning "__CM0PLUS_REV not defined in device header file; using default!" #endif #ifndef __MPU_PRESENT #define __MPU_PRESENT 0 #warning "__MPU_PRESENT not defined in device header file; using default!" #endif #ifndef __VTOR_PRESENT #define __VTOR_PRESENT 0 #warning "__VTOR_PRESENT not defined in device header file; using default!" #endif #ifndef __NVIC_PRIO_BITS #define __NVIC_PRIO_BITS 2 #warning "__NVIC_PRIO_BITS not defined in device header file; using default!" #endif #ifndef __Vendor_SysTickConfig #define __Vendor_SysTickConfig 0 #warning "__Vendor_SysTickConfig not defined in device header file; using default!" #endif #endif /* IO definitions (access restrictions to peripheral registers) */ /** \defgroup CMSIS_glob_defs CMSIS Global Defines IO Type Qualifiers are used \li to specify the access to peripheral variables. \li for automatic generation of peripheral register debug information. */ #ifdef __cplusplus #define __I volatile /*!< Defines 'read only' permissions */ #else #define __I volatile const /*!< Defines 'read only' permissions */ #endif #define __O volatile /*!< Defines 'write only' permissions */ #define __IO volatile /*!< Defines 'read / write' permissions */ /*@} end of group Cortex-M0+ */ /******************************************************************************* * Register Abstraction Core Register contain: - Core Register - Core NVIC Register - Core SCB Register - Core SysTick Register - Core MPU Register ******************************************************************************/ /** \defgroup CMSIS_core_register Defines and Type Definitions \brief Type definitions and defines for Cortex-M processor based devices. */ /** \ingroup CMSIS_core_register \defgroup CMSIS_CORE Status and Control Registers \brief Core Register type definitions. @{ */ /** \brief Union type to access the Application Program Status Register (APSR). */ typedef union { struct { #if (__CORTEX_M != 0x04) uint32_t _reserved0:27; /*!< bit: 0..26 Reserved */ #else uint32_t _reserved0:16; /*!< bit: 0..15 Reserved */ uint32_t GE:4; /*!< bit: 16..19 Greater than or Equal flags */ uint32_t _reserved1:7; /*!< bit: 20..26 Reserved */ #endif uint32_t Q:1; /*!< bit: 27 Saturation condition flag */ uint32_t V:1; /*!< bit: 28 Overflow condition code flag */ uint32_t C:1; /*!< bit: 29 Carry condition code flag */ uint32_t Z:1; /*!< bit: 30 Zero condition code flag */ uint32_t N:1; /*!< bit: 31 Negative condition code flag */ } b; /*!< Structure used for bit access */ uint32_t w; /*!< Type used for word access */ } APSR_Type; /** \brief Union type to access the Interrupt Program Status Register (IPSR). */ typedef union { struct { uint32_t ISR:9; /*!< bit: 0.. 8 Exception number */ uint32_t _reserved0:23; /*!< bit: 9..31 Reserved */ } b; /*!< Structure used for bit access */ uint32_t w; /*!< Type used for word access */ } IPSR_Type; /** \brief Union type to access the Special-Purpose Program Status Registers (xPSR). */ typedef union { struct { uint32_t ISR:9; /*!< bit: 0.. 8 Exception number */ #if (__CORTEX_M != 0x04) uint32_t _reserved0:15; /*!< bit: 9..23 Reserved */ #else uint32_t _reserved0:7; /*!< bit: 9..15 Reserved */ uint32_t GE:4; /*!< bit: 16..19 Greater than or Equal flags */ uint32_t _reserved1:4; /*!< bit: 20..23 Reserved */ #endif uint32_t T:1; /*!< bit: 24 Thumb bit (read 0) */ uint32_t IT:2; /*!< bit: 25..26 saved IT state (read 0) */ uint32_t Q:1; /*!< bit: 27 Saturation condition flag */ uint32_t V:1; /*!< bit: 28 Overflow condition code flag */ uint32_t C:1; /*!< bit: 29 Carry condition code flag */ uint32_t Z:1; /*!< bit: 30 Zero condition code flag */ uint32_t N:1; /*!< bit: 31 Negative condition code flag */ } b; /*!< Structure used for bit access */ uint32_t w; /*!< Type used for word access */ } xPSR_Type; /** \brief Union type to access the Control Registers (CONTROL). */ typedef union { struct { uint32_t nPRIV:1; /*!< bit: 0 Execution privilege in Thread mode */ uint32_t SPSEL:1; /*!< bit: 1 Stack to be used */ uint32_t FPCA:1; /*!< bit: 2 FP extension active flag */ uint32_t _reserved0:29; /*!< bit: 3..31 Reserved */ } b; /*!< Structure used for bit access */ uint32_t w; /*!< Type used for word access */ } CONTROL_Type; /*@} end of group CMSIS_CORE */ /** \ingroup CMSIS_core_register \defgroup CMSIS_NVIC Nested Vectored Interrupt Controller (NVIC) \brief Type definitions for the NVIC Registers @{ */ /** \brief Structure type to access the Nested Vectored Interrupt Controller (NVIC). */ typedef struct { __IO uint32_t ISER[1]; /*!< Offset: 0x000 (R/W) Interrupt Set Enable Register */ uint32_t RESERVED0[31]; __IO uint32_t ICER[1]; /*!< Offset: 0x080 (R/W) Interrupt Clear Enable Register */ uint32_t RSERVED1[31]; __IO uint32_t ISPR[1]; /*!< Offset: 0x100 (R/W) Interrupt Set Pending Register */ uint32_t RESERVED2[31]; __IO uint32_t ICPR[1]; /*!< Offset: 0x180 (R/W) Interrupt Clear Pending Register */ uint32_t RESERVED3[31]; uint32_t RESERVED4[64]; __IO uint32_t IP[8]; /*!< Offset: 0x300 (R/W) Interrupt Priority Register */ } NVIC_Type; /*@} end of group CMSIS_NVIC */ /** \ingroup CMSIS_core_register \defgroup CMSIS_SCB System Control Block (SCB) \brief Type definitions for the System Control Block Registers @{ */ /** \brief Structure type to access the System Control Block (SCB). */ typedef struct { __I uint32_t CPUID; /*!< Offset: 0x000 (R/ ) CPUID Base Register */ __IO uint32_t ICSR; /*!< Offset: 0x004 (R/W) Interrupt Control and State Register */ #if (__VTOR_PRESENT == 1) __IO uint32_t VTOR; /*!< Offset: 0x008 (R/W) Vector Table Offset Register */ #else uint32_t RESERVED0; #endif __IO uint32_t AIRCR; /*!< Offset: 0x00C (R/W) Application Interrupt and Reset Control Register */ __IO uint32_t SCR; /*!< Offset: 0x010 (R/W) System Control Register */ __IO uint32_t CCR; /*!< Offset: 0x014 (R/W) Configuration Control Register */ uint32_t RESERVED1; __IO uint32_t SHP[2]; /*!< Offset: 0x01C (R/W) System Handlers Priority Registers. [0] is RESERVED */ __IO uint32_t SHCSR; /*!< Offset: 0x024 (R/W) System Handler Control and State Register */ } SCB_Type; /* SCB CPUID Register Definitions */ #define SCB_CPUID_IMPLEMENTER_Pos 24 /*!< SCB CPUID: IMPLEMENTER Position */ #define SCB_CPUID_IMPLEMENTER_Msk (0xFFUL << SCB_CPUID_IMPLEMENTER_Pos) /*!< SCB CPUID: IMPLEMENTER Mask */ #define SCB_CPUID_VARIANT_Pos 20 /*!< SCB CPUID: VARIANT Position */ #define SCB_CPUID_VARIANT_Msk (0xFUL << SCB_CPUID_VARIANT_Pos) /*!< SCB CPUID: VARIANT Mask */ #define SCB_CPUID_ARCHITECTURE_Pos 16 /*!< SCB CPUID: ARCHITECTURE Position */ #define SCB_CPUID_ARCHITECTURE_Msk (0xFUL << SCB_CPUID_ARCHITECTURE_Pos) /*!< SCB CPUID: ARCHITECTURE Mask */ #define SCB_CPUID_PARTNO_Pos 4 /*!< SCB CPUID: PARTNO Position */ #define SCB_CPUID_PARTNO_Msk (0xFFFUL << SCB_CPUID_PARTNO_Pos) /*!< SCB CPUID: PARTNO Mask */ #define SCB_CPUID_REVISION_Pos 0 /*!< SCB CPUID: REVISION Position */ #define SCB_CPUID_REVISION_Msk (0xFUL << SCB_CPUID_REVISION_Pos) /*!< SCB CPUID: REVISION Mask */ /* SCB Interrupt Control State Register Definitions */ #define SCB_ICSR_NMIPENDSET_Pos 31 /*!< SCB ICSR: NMIPENDSET Position */ #define SCB_ICSR_NMIPENDSET_Msk (1UL << SCB_ICSR_NMIPENDSET_Pos) /*!< SCB ICSR: NMIPENDSET Mask */ #define SCB_ICSR_PENDSVSET_Pos 28 /*!< SCB ICSR: PENDSVSET Position */ #define SCB_ICSR_PENDSVSET_Msk (1UL << SCB_ICSR_PENDSVSET_Pos) /*!< SCB ICSR: PENDSVSET Mask */ #define SCB_ICSR_PENDSVCLR_Pos 27 /*!< SCB ICSR: PENDSVCLR Position */ #define SCB_ICSR_PENDSVCLR_Msk (1UL << SCB_ICSR_PENDSVCLR_Pos) /*!< SCB ICSR: PENDSVCLR Mask */ #define SCB_ICSR_PENDSTSET_Pos 26 /*!< SCB ICSR: PENDSTSET Position */ #define SCB_ICSR_PENDSTSET_Msk (1UL << SCB_ICSR_PENDSTSET_Pos) /*!< SCB ICSR: PENDSTSET Mask */ #define SCB_ICSR_PENDSTCLR_Pos 25 /*!< SCB ICSR: PENDSTCLR Position */ #define SCB_ICSR_PENDSTCLR_Msk (1UL << SCB_ICSR_PENDSTCLR_Pos) /*!< SCB ICSR: PENDSTCLR Mask */ #define SCB_ICSR_ISRPREEMPT_Pos 23 /*!< SCB ICSR: ISRPREEMPT Position */ #define SCB_ICSR_ISRPREEMPT_Msk (1UL << SCB_ICSR_ISRPREEMPT_Pos) /*!< SCB ICSR: ISRPREEMPT Mask */ #define SCB_ICSR_ISRPENDING_Pos 22 /*!< SCB ICSR: ISRPENDING Position */ #define SCB_ICSR_ISRPENDING_Msk (1UL << SCB_ICSR_ISRPENDING_Pos) /*!< SCB ICSR: ISRPENDING Mask */ #define SCB_ICSR_VECTPENDING_Pos 12 /*!< SCB ICSR: VECTPENDING Position */ #define SCB_ICSR_VECTPENDING_Msk (0x1FFUL << SCB_ICSR_VECTPENDING_Pos) /*!< SCB ICSR: VECTPENDING Mask */ #define SCB_ICSR_VECTACTIVE_Pos 0 /*!< SCB ICSR: VECTACTIVE Position */ #define SCB_ICSR_VECTACTIVE_Msk (0x1FFUL << SCB_ICSR_VECTACTIVE_Pos) /*!< SCB ICSR: VECTACTIVE Mask */ #if (__VTOR_PRESENT == 1) /* SCB Interrupt Control State Register Definitions */ #define SCB_VTOR_TBLOFF_Pos 8 /*!< SCB VTOR: TBLOFF Position */ #define SCB_VTOR_TBLOFF_Msk (0xFFFFFFUL << SCB_VTOR_TBLOFF_Pos) /*!< SCB VTOR: TBLOFF Mask */ #endif /* SCB Application Interrupt and Reset Control Register Definitions */ #define SCB_AIRCR_VECTKEY_Pos 16 /*!< SCB AIRCR: VECTKEY Position */ #define SCB_AIRCR_VECTKEY_Msk (0xFFFFUL << SCB_AIRCR_VECTKEY_Pos) /*!< SCB AIRCR: VECTKEY Mask */ #define SCB_AIRCR_VECTKEYSTAT_Pos 16 /*!< SCB AIRCR: VECTKEYSTAT Position */ #define SCB_AIRCR_VECTKEYSTAT_Msk (0xFFFFUL << SCB_AIRCR_VECTKEYSTAT_Pos) /*!< SCB AIRCR: VECTKEYSTAT Mask */ #define SCB_AIRCR_ENDIANESS_Pos 15 /*!< SCB AIRCR: ENDIANESS Position */ #define SCB_AIRCR_ENDIANESS_Msk (1UL << SCB_AIRCR_ENDIANESS_Pos) /*!< SCB AIRCR: ENDIANESS Mask */ #define SCB_AIRCR_SYSRESETREQ_Pos 2 /*!< SCB AIRCR: SYSRESETREQ Position */ #define SCB_AIRCR_SYSRESETREQ_Msk (1UL << SCB_AIRCR_SYSRESETREQ_Pos) /*!< SCB AIRCR: SYSRESETREQ Mask */ #define SCB_AIRCR_VECTCLRACTIVE_Pos 1 /*!< SCB AIRCR: VECTCLRACTIVE Position */ #define SCB_AIRCR_VECTCLRACTIVE_Msk (1UL << SCB_AIRCR_VECTCLRACTIVE_Pos) /*!< SCB AIRCR: VECTCLRACTIVE Mask */ /* SCB System Control Register Definitions */ #define SCB_SCR_SEVONPEND_Pos 4 /*!< SCB SCR: SEVONPEND Position */ #define SCB_SCR_SEVONPEND_Msk (1UL << SCB_SCR_SEVONPEND_Pos) /*!< SCB SCR: SEVONPEND Mask */ #define SCB_SCR_SLEEPDEEP_Pos 2 /*!< SCB SCR: SLEEPDEEP Position */ #define SCB_SCR_SLEEPDEEP_Msk (1UL << SCB_SCR_SLEEPDEEP_Pos) /*!< SCB SCR: SLEEPDEEP Mask */ #define SCB_SCR_SLEEPONEXIT_Pos 1 /*!< SCB SCR: SLEEPONEXIT Position */ #define SCB_SCR_SLEEPONEXIT_Msk (1UL << SCB_SCR_SLEEPONEXIT_Pos) /*!< SCB SCR: SLEEPONEXIT Mask */ /* SCB Configuration Control Register Definitions */ #define SCB_CCR_STKALIGN_Pos 9 /*!< SCB CCR: STKALIGN Position */ #define SCB_CCR_STKALIGN_Msk (1UL << SCB_CCR_STKALIGN_Pos) /*!< SCB CCR: STKALIGN Mask */ #define SCB_CCR_UNALIGN_TRP_Pos 3 /*!< SCB CCR: UNALIGN_TRP Position */ #define SCB_CCR_UNALIGN_TRP_Msk (1UL << SCB_CCR_UNALIGN_TRP_Pos) /*!< SCB CCR: UNALIGN_TRP Mask */ /* SCB System Handler Control and State Register Definitions */ #define SCB_SHCSR_SVCALLPENDED_Pos 15 /*!< SCB SHCSR: SVCALLPENDED Position */ #define SCB_SHCSR_SVCALLPENDED_Msk (1UL << SCB_SHCSR_SVCALLPENDED_Pos) /*!< SCB SHCSR: SVCALLPENDED Mask */ /*@} end of group CMSIS_SCB */ /** \ingroup CMSIS_core_register \defgroup CMSIS_SysTick System Tick Timer (SysTick) \brief Type definitions for the System Timer Registers. @{ */ /** \brief Structure type to access the System Timer (SysTick). */ typedef struct { __IO uint32_t CTRL; /*!< Offset: 0x000 (R/W) SysTick Control and Status Register */ __IO uint32_t LOAD; /*!< Offset: 0x004 (R/W) SysTick Reload Value Register */ __IO uint32_t VAL; /*!< Offset: 0x008 (R/W) SysTick Current Value Register */ __I uint32_t CALIB; /*!< Offset: 0x00C (R/ ) SysTick Calibration Register */ } SysTick_Type; /* SysTick Control / Status Register Definitions */ #define SysTick_CTRL_COUNTFLAG_Pos 16 /*!< SysTick CTRL: COUNTFLAG Position */ #define SysTick_CTRL_COUNTFLAG_Msk (1UL << SysTick_CTRL_COUNTFLAG_Pos) /*!< SysTick CTRL: COUNTFLAG Mask */ #define SysTick_CTRL_CLKSOURCE_Pos 2 /*!< SysTick CTRL: CLKSOURCE Position */ #define SysTick_CTRL_CLKSOURCE_Msk (1UL << SysTick_CTRL_CLKSOURCE_Pos) /*!< SysTick CTRL: CLKSOURCE Mask */ #define SysTick_CTRL_TICKINT_Pos 1 /*!< SysTick CTRL: TICKINT Position */ #define SysTick_CTRL_TICKINT_Msk (1UL << SysTick_CTRL_TICKINT_Pos) /*!< SysTick CTRL: TICKINT Mask */ #define SysTick_CTRL_ENABLE_Pos 0 /*!< SysTick CTRL: ENABLE Position */ #define SysTick_CTRL_ENABLE_Msk (1UL << SysTick_CTRL_ENABLE_Pos) /*!< SysTick CTRL: ENABLE Mask */ /* SysTick Reload Register Definitions */ #define SysTick_LOAD_RELOAD_Pos 0 /*!< SysTick LOAD: RELOAD Position */ #define SysTick_LOAD_RELOAD_Msk (0xFFFFFFUL << SysTick_LOAD_RELOAD_Pos) /*!< SysTick LOAD: RELOAD Mask */ /* SysTick Current Register Definitions */ #define SysTick_VAL_CURRENT_Pos 0 /*!< SysTick VAL: CURRENT Position */ #define SysTick_VAL_CURRENT_Msk (0xFFFFFFUL << SysTick_VAL_CURRENT_Pos) /*!< SysTick VAL: CURRENT Mask */ /* SysTick Calibration Register Definitions */ #define SysTick_CALIB_NOREF_Pos 31 /*!< SysTick CALIB: NOREF Position */ #define SysTick_CALIB_NOREF_Msk (1UL << SysTick_CALIB_NOREF_Pos) /*!< SysTick CALIB: NOREF Mask */ #define SysTick_CALIB_SKEW_Pos 30 /*!< SysTick CALIB: SKEW Position */ #define SysTick_CALIB_SKEW_Msk (1UL << SysTick_CALIB_SKEW_Pos) /*!< SysTick CALIB: SKEW Mask */ #define SysTick_CALIB_TENMS_Pos 0 /*!< SysTick CALIB: TENMS Position */ #define SysTick_CALIB_TENMS_Msk (0xFFFFFFUL << SysTick_VAL_CURRENT_Pos) /*!< SysTick CALIB: TENMS Mask */ /*@} end of group CMSIS_SysTick */ #if (__MPU_PRESENT == 1) /** \ingroup CMSIS_core_register \defgroup CMSIS_MPU Memory Protection Unit (MPU) \brief Type definitions for the Memory Protection Unit (MPU) @{ */ /** \brief Structure type to access the Memory Protection Unit (MPU). */ typedef struct { __I uint32_t TYPE; /*!< Offset: 0x000 (R/ ) MPU Type Register */ __IO uint32_t CTRL; /*!< Offset: 0x004 (R/W) MPU Control Register */ __IO uint32_t RNR; /*!< Offset: 0x008 (R/W) MPU Region RNRber Register */ __IO uint32_t RBAR; /*!< Offset: 0x00C (R/W) MPU Region Base Address Register */ __IO uint32_t RASR; /*!< Offset: 0x010 (R/W) MPU Region Attribute and Size Register */ } MPU_Type; /* MPU Type Register */ #define MPU_TYPE_IREGION_Pos 16 /*!< MPU TYPE: IREGION Position */ #define MPU_TYPE_IREGION_Msk (0xFFUL << MPU_TYPE_IREGION_Pos) /*!< MPU TYPE: IREGION Mask */ #define MPU_TYPE_DREGION_Pos 8 /*!< MPU TYPE: DREGION Position */ #define MPU_TYPE_DREGION_Msk (0xFFUL << MPU_TYPE_DREGION_Pos) /*!< MPU TYPE: DREGION Mask */ #define MPU_TYPE_SEPARATE_Pos 0 /*!< MPU TYPE: SEPARATE Position */ #define MPU_TYPE_SEPARATE_Msk (1UL << MPU_TYPE_SEPARATE_Pos) /*!< MPU TYPE: SEPARATE Mask */ /* MPU Control Register */ #define MPU_CTRL_PRIVDEFENA_Pos 2 /*!< MPU CTRL: PRIVDEFENA Position */ #define MPU_CTRL_PRIVDEFENA_Msk (1UL << MPU_CTRL_PRIVDEFENA_Pos) /*!< MPU CTRL: PRIVDEFENA Mask */ #define MPU_CTRL_HFNMIENA_Pos 1 /*!< MPU CTRL: HFNMIENA Position */ #define MPU_CTRL_HFNMIENA_Msk (1UL << MPU_CTRL_HFNMIENA_Pos) /*!< MPU CTRL: HFNMIENA Mask */ #define MPU_CTRL_ENABLE_Pos 0 /*!< MPU CTRL: ENABLE Position */ #define MPU_CTRL_ENABLE_Msk (1UL << MPU_CTRL_ENABLE_Pos) /*!< MPU CTRL: ENABLE Mask */ /* MPU Region Number Register */ #define MPU_RNR_REGION_Pos 0 /*!< MPU RNR: REGION Position */ #define MPU_RNR_REGION_Msk (0xFFUL << MPU_RNR_REGION_Pos) /*!< MPU RNR: REGION Mask */ /* MPU Region Base Address Register */ #define MPU_RBAR_ADDR_Pos 8 /*!< MPU RBAR: ADDR Position */ #define MPU_RBAR_ADDR_Msk (0xFFFFFFUL << MPU_RBAR_ADDR_Pos) /*!< MPU RBAR: ADDR Mask */ #define MPU_RBAR_VALID_Pos 4 /*!< MPU RBAR: VALID Position */ #define MPU_RBAR_VALID_Msk (1UL << MPU_RBAR_VALID_Pos) /*!< MPU RBAR: VALID Mask */ #define MPU_RBAR_REGION_Pos 0 /*!< MPU RBAR: REGION Position */ #define MPU_RBAR_REGION_Msk (0xFUL << MPU_RBAR_REGION_Pos) /*!< MPU RBAR: REGION Mask */ /* MPU Region Attribute and Size Register */ #define MPU_RASR_ATTRS_Pos 16 /*!< MPU RASR: MPU Region Attribute field Position */ #define MPU_RASR_ATTRS_Msk (0xFFFFUL << MPU_RASR_ATTRS_Pos) /*!< MPU RASR: MPU Region Attribute field Mask */ #define MPU_RASR_XN_Pos 28 /*!< MPU RASR: ATTRS.XN Position */ #define MPU_RASR_XN_Msk (1UL << MPU_RASR_XN_Pos) /*!< MPU RASR: ATTRS.XN Mask */ #define MPU_RASR_AP_Pos 24 /*!< MPU RASR: ATTRS.AP Position */ #define MPU_RASR_AP_Msk (0x7UL << MPU_RASR_AP_Pos) /*!< MPU RASR: ATTRS.AP Mask */ #define MPU_RASR_TEX_Pos 19 /*!< MPU RASR: ATTRS.TEX Position */ #define MPU_RASR_TEX_Msk (0x7UL << MPU_RASR_TEX_Pos) /*!< MPU RASR: ATTRS.TEX Mask */ #define MPU_RASR_S_Pos 18 /*!< MPU RASR: ATTRS.S Position */ #define MPU_RASR_S_Msk (1UL << MPU_RASR_S_Pos) /*!< MPU RASR: ATTRS.S Mask */ #define MPU_RASR_C_Pos 17 /*!< MPU RASR: ATTRS.C Position */ #define MPU_RASR_C_Msk (1UL << MPU_RASR_C_Pos) /*!< MPU RASR: ATTRS.C Mask */ #define MPU_RASR_B_Pos 16 /*!< MPU RASR: ATTRS.B Position */ #define MPU_RASR_B_Msk (1UL << MPU_RASR_B_Pos) /*!< MPU RASR: ATTRS.B Mask */ #define MPU_RASR_SRD_Pos 8 /*!< MPU RASR: Sub-Region Disable Position */ #define MPU_RASR_SRD_Msk (0xFFUL << MPU_RASR_SRD_Pos) /*!< MPU RASR: Sub-Region Disable Mask */ #define MPU_RASR_SIZE_Pos 1 /*!< MPU RASR: Region Size Field Position */ #define MPU_RASR_SIZE_Msk (0x1FUL << MPU_RASR_SIZE_Pos) /*!< MPU RASR: Region Size Field Mask */ #define MPU_RASR_ENABLE_Pos 0 /*!< MPU RASR: Region enable bit Position */ #define MPU_RASR_ENABLE_Msk (1UL << MPU_RASR_ENABLE_Pos) /*!< MPU RASR: Region enable bit Disable Mask */ /*@} end of group CMSIS_MPU */ #endif /** \ingroup CMSIS_core_register \defgroup CMSIS_CoreDebug Core Debug Registers (CoreDebug) \brief Cortex-M0+ Core Debug Registers (DCB registers, SHCSR, and DFSR) are only accessible over DAP and not via processor. Therefore they are not covered by the Cortex-M0 header file. @{ */ /*@} end of group CMSIS_CoreDebug */ /** \ingroup CMSIS_core_register \defgroup CMSIS_core_base Core Definitions \brief Definitions for base addresses, unions, and structures. @{ */ /* Memory mapping of Cortex-M0+ Hardware */ #define SCS_BASE (0xE000E000UL) /*!< System Control Space Base Address */ #define SysTick_BASE (SCS_BASE + 0x0010UL) /*!< SysTick Base Address */ #define NVIC_BASE (SCS_BASE + 0x0100UL) /*!< NVIC Base Address */ #define SCB_BASE (SCS_BASE + 0x0D00UL) /*!< System Control Block Base Address */ #define SCB ((SCB_Type *) SCB_BASE ) /*!< SCB configuration struct */ #define SysTick ((SysTick_Type *) SysTick_BASE ) /*!< SysTick configuration struct */ #define NVIC ((NVIC_Type *) NVIC_BASE ) /*!< NVIC configuration struct */ #if (__MPU_PRESENT == 1) #define MPU_BASE (SCS_BASE + 0x0D90UL) /*!< Memory Protection Unit */ #define MPU ((MPU_Type *) MPU_BASE ) /*!< Memory Protection Unit */ #endif /*@} */ /******************************************************************************* * Hardware Abstraction Layer Core Function Interface contains: - Core NVIC Functions - Core SysTick Functions - Core Register Access Functions ******************************************************************************/ /** \defgroup CMSIS_Core_FunctionInterface Functions and Instructions Reference */ /* ########################## NVIC functions #################################### */ /** \ingroup CMSIS_Core_FunctionInterface \defgroup CMSIS_Core_NVICFunctions NVIC Functions \brief Functions that manage interrupts and exceptions via the NVIC. @{ */ /* Interrupt Priorities are WORD accessible only under ARMv6M */ /* The following MACROS handle generation of the register offset and byte masks */ #define _BIT_SHIFT(IRQn) ( (((uint32_t)(IRQn) ) & 0x03) * 8 ) #define _SHP_IDX(IRQn) ( ((((uint32_t)(IRQn) & 0x0F)-8) >> 2) ) #define _IP_IDX(IRQn) ( ((uint32_t)(IRQn) >> 2) ) /** \brief Enable External Interrupt The function enables a device-specific interrupt in the NVIC interrupt controller. \param [in] IRQn External interrupt number. Value cannot be negative. */ __STATIC_INLINE void NVIC_EnableIRQ(IRQn_Type IRQn) { NVIC->ISER[0] = (1 << ((uint32_t)(IRQn) & 0x1F)); } /** \brief Disable External Interrupt The function disables a device-specific interrupt in the NVIC interrupt controller. \param [in] IRQn External interrupt number. Value cannot be negative. */ __STATIC_INLINE void NVIC_DisableIRQ(IRQn_Type IRQn) { NVIC->ICER[0] = (1 << ((uint32_t)(IRQn) & 0x1F)); } /** \brief Get Pending Interrupt The function reads the pending register in the NVIC and returns the pending bit for the specified interrupt. \param [in] IRQn Interrupt number. \return 0 Interrupt status is not pending. \return 1 Interrupt status is pending. */ __STATIC_INLINE uint32_t NVIC_GetPendingIRQ(IRQn_Type IRQn) { return((uint32_t) ((NVIC->ISPR[0] & (1 << ((uint32_t)(IRQn) & 0x1F)))?1:0)); } /** \brief Set Pending Interrupt The function sets the pending bit of an external interrupt. \param [in] IRQn Interrupt number. Value cannot be negative. */ __STATIC_INLINE void NVIC_SetPendingIRQ(IRQn_Type IRQn) { NVIC->ISPR[0] = (1 << ((uint32_t)(IRQn) & 0x1F)); } /** \brief Clear Pending Interrupt The function clears the pending bit of an external interrupt. \param [in] IRQn External interrupt number. Value cannot be negative. */ __STATIC_INLINE void NVIC_ClearPendingIRQ(IRQn_Type IRQn) { NVIC->ICPR[0] = (1 << ((uint32_t)(IRQn) & 0x1F)); /* Clear pending interrupt */ } /** \brief Set Interrupt Priority The function sets the priority of an interrupt. \note The priority cannot be set for every core interrupt. \param [in] IRQn Interrupt number. \param [in] priority Priority to set. */ __STATIC_INLINE void NVIC_SetPriority(IRQn_Type IRQn, uint32_t priority) { if(IRQn < 0) { SCB->SHP[_SHP_IDX(IRQn)] = (SCB->SHP[_SHP_IDX(IRQn)] & ~(0xFF << _BIT_SHIFT(IRQn))) | (((priority << (8 - __NVIC_PRIO_BITS)) & 0xFF) << _BIT_SHIFT(IRQn)); } else { NVIC->IP[_IP_IDX(IRQn)] = (NVIC->IP[_IP_IDX(IRQn)] & ~(0xFF << _BIT_SHIFT(IRQn))) | (((priority << (8 - __NVIC_PRIO_BITS)) & 0xFF) << _BIT_SHIFT(IRQn)); } } /** \brief Get Interrupt Priority The function reads the priority of an interrupt. The interrupt number can be positive to specify an external (device specific) interrupt, or negative to specify an internal (core) interrupt. \param [in] IRQn Interrupt number. \return Interrupt Priority. Value is aligned automatically to the implemented priority bits of the microcontroller. */ __STATIC_INLINE uint32_t NVIC_GetPriority(IRQn_Type IRQn) { if(IRQn < 0) { return((uint32_t)(((SCB->SHP[_SHP_IDX(IRQn)] >> _BIT_SHIFT(IRQn) ) & 0xFF) >> (8 - __NVIC_PRIO_BITS))); } /* get priority for Cortex-M0 system interrupts */ else { return((uint32_t)(((NVIC->IP[ _IP_IDX(IRQn)] >> _BIT_SHIFT(IRQn) ) & 0xFF) >> (8 - __NVIC_PRIO_BITS))); } /* get priority for device specific interrupts */ } /** \brief System Reset The function initiates a system reset request to reset the MCU. */ __STATIC_INLINE void NVIC_SystemReset(void) { __DSB(); /* Ensure all outstanding memory accesses included buffered write are completed before reset */ SCB->AIRCR = ((0x5FA << SCB_AIRCR_VECTKEY_Pos) | SCB_AIRCR_SYSRESETREQ_Msk); __DSB(); /* Ensure completion of memory access */ while(1); /* wait until reset */ } /*@} end of CMSIS_Core_NVICFunctions */ /* ################################## SysTick function ############################################ */ /** \ingroup CMSIS_Core_FunctionInterface \defgroup CMSIS_Core_SysTickFunctions SysTick Functions \brief Functions that configure the System. @{ */ #if (__Vendor_SysTickConfig == 0) /** \brief System Tick Configuration The function initializes the System Timer and its interrupt, and starts the System Tick Timer. Counter is in free running mode to generate periodic interrupts. \param [in] ticks Number of ticks between two interrupts. \return 0 Function succeeded. \return 1 Function failed. \note When the variable __Vendor_SysTickConfig is set to 1, then the function SysTick_Config is not included. In this case, the file device.h must contain a vendor-specific implementation of this function. */ __STATIC_INLINE uint32_t SysTick_Config(uint32_t ticks) { if ((ticks - 1) > SysTick_LOAD_RELOAD_Msk) return (1); /* Reload value impossible */ SysTick->LOAD = ticks - 1; /* set reload register */ NVIC_SetPriority (SysTick_IRQn, (1<<__NVIC_PRIO_BITS) - 1); /* set Priority for Systick Interrupt */ SysTick->VAL = 0; /* Load the SysTick Counter Value */ SysTick->CTRL = SysTick_CTRL_CLKSOURCE_Msk | SysTick_CTRL_TICKINT_Msk | SysTick_CTRL_ENABLE_Msk; /* Enable SysTick IRQ and SysTick Timer */ return (0); /* Function successful */ } #endif /*@} end of CMSIS_Core_SysTickFunctions */ #endif /* __CORE_CM0PLUS_H_DEPENDANT */ #endif /* __CMSIS_GENERIC */ #ifdef __cplusplus } #endif ================================================ FILE: Zelig/mbed/TARGET_LPC1768/core_cm3.h ================================================ /**************************************************************************//** * @file core_cm3.h * @brief CMSIS Cortex-M3 Core Peripheral Access Layer Header File * @version V3.20 * @date 25. February 2013 * * @note * ******************************************************************************/ /* Copyright (c) 2009 - 2013 ARM LIMITED All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: - Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. - Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. - Neither the name of ARM 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 COPYRIGHT HOLDERS AND 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. ---------------------------------------------------------------------------*/ #if defined ( __ICCARM__ ) #pragma system_include /* treat file as system include file for MISRA check */ #endif #ifdef __cplusplus extern "C" { #endif #ifndef __CORE_CM3_H_GENERIC #define __CORE_CM3_H_GENERIC /** \page CMSIS_MISRA_Exceptions MISRA-C:2004 Compliance Exceptions CMSIS violates the following MISRA-C:2004 rules: \li Required Rule 8.5, object/function definition in header file.
Function definitions in header files are used to allow 'inlining'. \li Required Rule 18.4, declaration of union type or object of union type: '{...}'.
Unions are used for effective representation of core registers. \li Advisory Rule 19.7, Function-like macro defined.
Function-like macros are used to allow more efficient code. */ /******************************************************************************* * CMSIS definitions ******************************************************************************/ /** \ingroup Cortex_M3 @{ */ /* CMSIS CM3 definitions */ #define __CM3_CMSIS_VERSION_MAIN (0x03) /*!< [31:16] CMSIS HAL main version */ #define __CM3_CMSIS_VERSION_SUB (0x20) /*!< [15:0] CMSIS HAL sub version */ #define __CM3_CMSIS_VERSION ((__CM3_CMSIS_VERSION_MAIN << 16) | \ __CM3_CMSIS_VERSION_SUB ) /*!< CMSIS HAL version number */ #define __CORTEX_M (0x03) /*!< Cortex-M Core */ #if defined ( __CC_ARM ) #define __ASM __asm /*!< asm keyword for ARM Compiler */ #define __INLINE __inline /*!< inline keyword for ARM Compiler */ #define __STATIC_INLINE static __inline #elif defined ( __ICCARM__ ) #define __ASM __asm /*!< asm keyword for IAR Compiler */ #define __INLINE inline /*!< inline keyword for IAR Compiler. Only available in High optimization mode! */ #define __STATIC_INLINE static inline #elif defined ( __TMS470__ ) #define __ASM __asm /*!< asm keyword for TI CCS Compiler */ #define __STATIC_INLINE static inline #elif defined ( __GNUC__ ) #define __ASM __asm /*!< asm keyword for GNU Compiler */ #define __INLINE inline /*!< inline keyword for GNU Compiler */ #define __STATIC_INLINE static inline #elif defined ( __TASKING__ ) #define __ASM __asm /*!< asm keyword for TASKING Compiler */ #define __INLINE inline /*!< inline keyword for TASKING Compiler */ #define __STATIC_INLINE static inline #endif /** __FPU_USED indicates whether an FPU is used or not. This core does not support an FPU at all */ #define __FPU_USED 0 #if defined ( __CC_ARM ) #if defined __TARGET_FPU_VFP #warning "Compiler generates FPU instructions for a device without an FPU (check __FPU_PRESENT)" #endif #elif defined ( __ICCARM__ ) #if defined __ARMVFP__ #warning "Compiler generates FPU instructions for a device without an FPU (check __FPU_PRESENT)" #endif #elif defined ( __TMS470__ ) #if defined __TI__VFP_SUPPORT____ #warning "Compiler generates FPU instructions for a device without an FPU (check __FPU_PRESENT)" #endif #elif defined ( __GNUC__ ) #if defined (__VFP_FP__) && !defined(__SOFTFP__) #warning "Compiler generates FPU instructions for a device without an FPU (check __FPU_PRESENT)" #endif #elif defined ( __TASKING__ ) #if defined __FPU_VFP__ #error "Compiler generates FPU instructions for a device without an FPU (check __FPU_PRESENT)" #endif #endif #include /* standard types definitions */ #include /* Core Instruction Access */ #include /* Core Function Access */ #endif /* __CORE_CM3_H_GENERIC */ #ifndef __CMSIS_GENERIC #ifndef __CORE_CM3_H_DEPENDANT #define __CORE_CM3_H_DEPENDANT /* check device defines and use defaults */ #if defined __CHECK_DEVICE_DEFINES #ifndef __CM3_REV #define __CM3_REV 0x0200 #warning "__CM3_REV not defined in device header file; using default!" #endif #ifndef __MPU_PRESENT #define __MPU_PRESENT 0 #warning "__MPU_PRESENT not defined in device header file; using default!" #endif #ifndef __NVIC_PRIO_BITS #define __NVIC_PRIO_BITS 4 #warning "__NVIC_PRIO_BITS not defined in device header file; using default!" #endif #ifndef __Vendor_SysTickConfig #define __Vendor_SysTickConfig 0 #warning "__Vendor_SysTickConfig not defined in device header file; using default!" #endif #endif /* IO definitions (access restrictions to peripheral registers) */ /** \defgroup CMSIS_glob_defs CMSIS Global Defines IO Type Qualifiers are used \li to specify the access to peripheral variables. \li for automatic generation of peripheral register debug information. */ #ifdef __cplusplus #define __I volatile /*!< Defines 'read only' permissions */ #else #define __I volatile const /*!< Defines 'read only' permissions */ #endif #define __O volatile /*!< Defines 'write only' permissions */ #define __IO volatile /*!< Defines 'read / write' permissions */ /*@} end of group Cortex_M3 */ /******************************************************************************* * Register Abstraction Core Register contain: - Core Register - Core NVIC Register - Core SCB Register - Core SysTick Register - Core Debug Register - Core MPU Register ******************************************************************************/ /** \defgroup CMSIS_core_register Defines and Type Definitions \brief Type definitions and defines for Cortex-M processor based devices. */ /** \ingroup CMSIS_core_register \defgroup CMSIS_CORE Status and Control Registers \brief Core Register type definitions. @{ */ /** \brief Union type to access the Application Program Status Register (APSR). */ typedef union { struct { #if (__CORTEX_M != 0x04) uint32_t _reserved0:27; /*!< bit: 0..26 Reserved */ #else uint32_t _reserved0:16; /*!< bit: 0..15 Reserved */ uint32_t GE:4; /*!< bit: 16..19 Greater than or Equal flags */ uint32_t _reserved1:7; /*!< bit: 20..26 Reserved */ #endif uint32_t Q:1; /*!< bit: 27 Saturation condition flag */ uint32_t V:1; /*!< bit: 28 Overflow condition code flag */ uint32_t C:1; /*!< bit: 29 Carry condition code flag */ uint32_t Z:1; /*!< bit: 30 Zero condition code flag */ uint32_t N:1; /*!< bit: 31 Negative condition code flag */ } b; /*!< Structure used for bit access */ uint32_t w; /*!< Type used for word access */ } APSR_Type; /** \brief Union type to access the Interrupt Program Status Register (IPSR). */ typedef union { struct { uint32_t ISR:9; /*!< bit: 0.. 8 Exception number */ uint32_t _reserved0:23; /*!< bit: 9..31 Reserved */ } b; /*!< Structure used for bit access */ uint32_t w; /*!< Type used for word access */ } IPSR_Type; /** \brief Union type to access the Special-Purpose Program Status Registers (xPSR). */ typedef union { struct { uint32_t ISR:9; /*!< bit: 0.. 8 Exception number */ #if (__CORTEX_M != 0x04) uint32_t _reserved0:15; /*!< bit: 9..23 Reserved */ #else uint32_t _reserved0:7; /*!< bit: 9..15 Reserved */ uint32_t GE:4; /*!< bit: 16..19 Greater than or Equal flags */ uint32_t _reserved1:4; /*!< bit: 20..23 Reserved */ #endif uint32_t T:1; /*!< bit: 24 Thumb bit (read 0) */ uint32_t IT:2; /*!< bit: 25..26 saved IT state (read 0) */ uint32_t Q:1; /*!< bit: 27 Saturation condition flag */ uint32_t V:1; /*!< bit: 28 Overflow condition code flag */ uint32_t C:1; /*!< bit: 29 Carry condition code flag */ uint32_t Z:1; /*!< bit: 30 Zero condition code flag */ uint32_t N:1; /*!< bit: 31 Negative condition code flag */ } b; /*!< Structure used for bit access */ uint32_t w; /*!< Type used for word access */ } xPSR_Type; /** \brief Union type to access the Control Registers (CONTROL). */ typedef union { struct { uint32_t nPRIV:1; /*!< bit: 0 Execution privilege in Thread mode */ uint32_t SPSEL:1; /*!< bit: 1 Stack to be used */ uint32_t FPCA:1; /*!< bit: 2 FP extension active flag */ uint32_t _reserved0:29; /*!< bit: 3..31 Reserved */ } b; /*!< Structure used for bit access */ uint32_t w; /*!< Type used for word access */ } CONTROL_Type; /*@} end of group CMSIS_CORE */ /** \ingroup CMSIS_core_register \defgroup CMSIS_NVIC Nested Vectored Interrupt Controller (NVIC) \brief Type definitions for the NVIC Registers @{ */ /** \brief Structure type to access the Nested Vectored Interrupt Controller (NVIC). */ typedef struct { __IO uint32_t ISER[8]; /*!< Offset: 0x000 (R/W) Interrupt Set Enable Register */ uint32_t RESERVED0[24]; __IO uint32_t ICER[8]; /*!< Offset: 0x080 (R/W) Interrupt Clear Enable Register */ uint32_t RSERVED1[24]; __IO uint32_t ISPR[8]; /*!< Offset: 0x100 (R/W) Interrupt Set Pending Register */ uint32_t RESERVED2[24]; __IO uint32_t ICPR[8]; /*!< Offset: 0x180 (R/W) Interrupt Clear Pending Register */ uint32_t RESERVED3[24]; __IO uint32_t IABR[8]; /*!< Offset: 0x200 (R/W) Interrupt Active bit Register */ uint32_t RESERVED4[56]; __IO uint8_t IP[240]; /*!< Offset: 0x300 (R/W) Interrupt Priority Register (8Bit wide) */ uint32_t RESERVED5[644]; __O uint32_t STIR; /*!< Offset: 0xE00 ( /W) Software Trigger Interrupt Register */ } NVIC_Type; /* Software Triggered Interrupt Register Definitions */ #define NVIC_STIR_INTID_Pos 0 /*!< STIR: INTLINESNUM Position */ #define NVIC_STIR_INTID_Msk (0x1FFUL << NVIC_STIR_INTID_Pos) /*!< STIR: INTLINESNUM Mask */ /*@} end of group CMSIS_NVIC */ /** \ingroup CMSIS_core_register \defgroup CMSIS_SCB System Control Block (SCB) \brief Type definitions for the System Control Block Registers @{ */ /** \brief Structure type to access the System Control Block (SCB). */ typedef struct { __I uint32_t CPUID; /*!< Offset: 0x000 (R/ ) CPUID Base Register */ __IO uint32_t ICSR; /*!< Offset: 0x004 (R/W) Interrupt Control and State Register */ __IO uint32_t VTOR; /*!< Offset: 0x008 (R/W) Vector Table Offset Register */ __IO uint32_t AIRCR; /*!< Offset: 0x00C (R/W) Application Interrupt and Reset Control Register */ __IO uint32_t SCR; /*!< Offset: 0x010 (R/W) System Control Register */ __IO uint32_t CCR; /*!< Offset: 0x014 (R/W) Configuration Control Register */ __IO uint8_t SHP[12]; /*!< Offset: 0x018 (R/W) System Handlers Priority Registers (4-7, 8-11, 12-15) */ __IO uint32_t SHCSR; /*!< Offset: 0x024 (R/W) System Handler Control and State Register */ __IO uint32_t CFSR; /*!< Offset: 0x028 (R/W) Configurable Fault Status Register */ __IO uint32_t HFSR; /*!< Offset: 0x02C (R/W) HardFault Status Register */ __IO uint32_t DFSR; /*!< Offset: 0x030 (R/W) Debug Fault Status Register */ __IO uint32_t MMFAR; /*!< Offset: 0x034 (R/W) MemManage Fault Address Register */ __IO uint32_t BFAR; /*!< Offset: 0x038 (R/W) BusFault Address Register */ __IO uint32_t AFSR; /*!< Offset: 0x03C (R/W) Auxiliary Fault Status Register */ __I uint32_t PFR[2]; /*!< Offset: 0x040 (R/ ) Processor Feature Register */ __I uint32_t DFR; /*!< Offset: 0x048 (R/ ) Debug Feature Register */ __I uint32_t ADR; /*!< Offset: 0x04C (R/ ) Auxiliary Feature Register */ __I uint32_t MMFR[4]; /*!< Offset: 0x050 (R/ ) Memory Model Feature Register */ __I uint32_t ISAR[5]; /*!< Offset: 0x060 (R/ ) Instruction Set Attributes Register */ uint32_t RESERVED0[5]; __IO uint32_t CPACR; /*!< Offset: 0x088 (R/W) Coprocessor Access Control Register */ } SCB_Type; /* SCB CPUID Register Definitions */ #define SCB_CPUID_IMPLEMENTER_Pos 24 /*!< SCB CPUID: IMPLEMENTER Position */ #define SCB_CPUID_IMPLEMENTER_Msk (0xFFUL << SCB_CPUID_IMPLEMENTER_Pos) /*!< SCB CPUID: IMPLEMENTER Mask */ #define SCB_CPUID_VARIANT_Pos 20 /*!< SCB CPUID: VARIANT Position */ #define SCB_CPUID_VARIANT_Msk (0xFUL << SCB_CPUID_VARIANT_Pos) /*!< SCB CPUID: VARIANT Mask */ #define SCB_CPUID_ARCHITECTURE_Pos 16 /*!< SCB CPUID: ARCHITECTURE Position */ #define SCB_CPUID_ARCHITECTURE_Msk (0xFUL << SCB_CPUID_ARCHITECTURE_Pos) /*!< SCB CPUID: ARCHITECTURE Mask */ #define SCB_CPUID_PARTNO_Pos 4 /*!< SCB CPUID: PARTNO Position */ #define SCB_CPUID_PARTNO_Msk (0xFFFUL << SCB_CPUID_PARTNO_Pos) /*!< SCB CPUID: PARTNO Mask */ #define SCB_CPUID_REVISION_Pos 0 /*!< SCB CPUID: REVISION Position */ #define SCB_CPUID_REVISION_Msk (0xFUL << SCB_CPUID_REVISION_Pos) /*!< SCB CPUID: REVISION Mask */ /* SCB Interrupt Control State Register Definitions */ #define SCB_ICSR_NMIPENDSET_Pos 31 /*!< SCB ICSR: NMIPENDSET Position */ #define SCB_ICSR_NMIPENDSET_Msk (1UL << SCB_ICSR_NMIPENDSET_Pos) /*!< SCB ICSR: NMIPENDSET Mask */ #define SCB_ICSR_PENDSVSET_Pos 28 /*!< SCB ICSR: PENDSVSET Position */ #define SCB_ICSR_PENDSVSET_Msk (1UL << SCB_ICSR_PENDSVSET_Pos) /*!< SCB ICSR: PENDSVSET Mask */ #define SCB_ICSR_PENDSVCLR_Pos 27 /*!< SCB ICSR: PENDSVCLR Position */ #define SCB_ICSR_PENDSVCLR_Msk (1UL << SCB_ICSR_PENDSVCLR_Pos) /*!< SCB ICSR: PENDSVCLR Mask */ #define SCB_ICSR_PENDSTSET_Pos 26 /*!< SCB ICSR: PENDSTSET Position */ #define SCB_ICSR_PENDSTSET_Msk (1UL << SCB_ICSR_PENDSTSET_Pos) /*!< SCB ICSR: PENDSTSET Mask */ #define SCB_ICSR_PENDSTCLR_Pos 25 /*!< SCB ICSR: PENDSTCLR Position */ #define SCB_ICSR_PENDSTCLR_Msk (1UL << SCB_ICSR_PENDSTCLR_Pos) /*!< SCB ICSR: PENDSTCLR Mask */ #define SCB_ICSR_ISRPREEMPT_Pos 23 /*!< SCB ICSR: ISRPREEMPT Position */ #define SCB_ICSR_ISRPREEMPT_Msk (1UL << SCB_ICSR_ISRPREEMPT_Pos) /*!< SCB ICSR: ISRPREEMPT Mask */ #define SCB_ICSR_ISRPENDING_Pos 22 /*!< SCB ICSR: ISRPENDING Position */ #define SCB_ICSR_ISRPENDING_Msk (1UL << SCB_ICSR_ISRPENDING_Pos) /*!< SCB ICSR: ISRPENDING Mask */ #define SCB_ICSR_VECTPENDING_Pos 12 /*!< SCB ICSR: VECTPENDING Position */ #define SCB_ICSR_VECTPENDING_Msk (0x1FFUL << SCB_ICSR_VECTPENDING_Pos) /*!< SCB ICSR: VECTPENDING Mask */ #define SCB_ICSR_RETTOBASE_Pos 11 /*!< SCB ICSR: RETTOBASE Position */ #define SCB_ICSR_RETTOBASE_Msk (1UL << SCB_ICSR_RETTOBASE_Pos) /*!< SCB ICSR: RETTOBASE Mask */ #define SCB_ICSR_VECTACTIVE_Pos 0 /*!< SCB ICSR: VECTACTIVE Position */ #define SCB_ICSR_VECTACTIVE_Msk (0x1FFUL << SCB_ICSR_VECTACTIVE_Pos) /*!< SCB ICSR: VECTACTIVE Mask */ /* SCB Vector Table Offset Register Definitions */ #if (__CM3_REV < 0x0201) /* core r2p1 */ #define SCB_VTOR_TBLBASE_Pos 29 /*!< SCB VTOR: TBLBASE Position */ #define SCB_VTOR_TBLBASE_Msk (1UL << SCB_VTOR_TBLBASE_Pos) /*!< SCB VTOR: TBLBASE Mask */ #define SCB_VTOR_TBLOFF_Pos 7 /*!< SCB VTOR: TBLOFF Position */ #define SCB_VTOR_TBLOFF_Msk (0x3FFFFFUL << SCB_VTOR_TBLOFF_Pos) /*!< SCB VTOR: TBLOFF Mask */ #else #define SCB_VTOR_TBLOFF_Pos 7 /*!< SCB VTOR: TBLOFF Position */ #define SCB_VTOR_TBLOFF_Msk (0x1FFFFFFUL << SCB_VTOR_TBLOFF_Pos) /*!< SCB VTOR: TBLOFF Mask */ #endif /* SCB Application Interrupt and Reset Control Register Definitions */ #define SCB_AIRCR_VECTKEY_Pos 16 /*!< SCB AIRCR: VECTKEY Position */ #define SCB_AIRCR_VECTKEY_Msk (0xFFFFUL << SCB_AIRCR_VECTKEY_Pos) /*!< SCB AIRCR: VECTKEY Mask */ #define SCB_AIRCR_VECTKEYSTAT_Pos 16 /*!< SCB AIRCR: VECTKEYSTAT Position */ #define SCB_AIRCR_VECTKEYSTAT_Msk (0xFFFFUL << SCB_AIRCR_VECTKEYSTAT_Pos) /*!< SCB AIRCR: VECTKEYSTAT Mask */ #define SCB_AIRCR_ENDIANESS_Pos 15 /*!< SCB AIRCR: ENDIANESS Position */ #define SCB_AIRCR_ENDIANESS_Msk (1UL << SCB_AIRCR_ENDIANESS_Pos) /*!< SCB AIRCR: ENDIANESS Mask */ #define SCB_AIRCR_PRIGROUP_Pos 8 /*!< SCB AIRCR: PRIGROUP Position */ #define SCB_AIRCR_PRIGROUP_Msk (7UL << SCB_AIRCR_PRIGROUP_Pos) /*!< SCB AIRCR: PRIGROUP Mask */ #define SCB_AIRCR_SYSRESETREQ_Pos 2 /*!< SCB AIRCR: SYSRESETREQ Position */ #define SCB_AIRCR_SYSRESETREQ_Msk (1UL << SCB_AIRCR_SYSRESETREQ_Pos) /*!< SCB AIRCR: SYSRESETREQ Mask */ #define SCB_AIRCR_VECTCLRACTIVE_Pos 1 /*!< SCB AIRCR: VECTCLRACTIVE Position */ #define SCB_AIRCR_VECTCLRACTIVE_Msk (1UL << SCB_AIRCR_VECTCLRACTIVE_Pos) /*!< SCB AIRCR: VECTCLRACTIVE Mask */ #define SCB_AIRCR_VECTRESET_Pos 0 /*!< SCB AIRCR: VECTRESET Position */ #define SCB_AIRCR_VECTRESET_Msk (1UL << SCB_AIRCR_VECTRESET_Pos) /*!< SCB AIRCR: VECTRESET Mask */ /* SCB System Control Register Definitions */ #define SCB_SCR_SEVONPEND_Pos 4 /*!< SCB SCR: SEVONPEND Position */ #define SCB_SCR_SEVONPEND_Msk (1UL << SCB_SCR_SEVONPEND_Pos) /*!< SCB SCR: SEVONPEND Mask */ #define SCB_SCR_SLEEPDEEP_Pos 2 /*!< SCB SCR: SLEEPDEEP Position */ #define SCB_SCR_SLEEPDEEP_Msk (1UL << SCB_SCR_SLEEPDEEP_Pos) /*!< SCB SCR: SLEEPDEEP Mask */ #define SCB_SCR_SLEEPONEXIT_Pos 1 /*!< SCB SCR: SLEEPONEXIT Position */ #define SCB_SCR_SLEEPONEXIT_Msk (1UL << SCB_SCR_SLEEPONEXIT_Pos) /*!< SCB SCR: SLEEPONEXIT Mask */ /* SCB Configuration Control Register Definitions */ #define SCB_CCR_STKALIGN_Pos 9 /*!< SCB CCR: STKALIGN Position */ #define SCB_CCR_STKALIGN_Msk (1UL << SCB_CCR_STKALIGN_Pos) /*!< SCB CCR: STKALIGN Mask */ #define SCB_CCR_BFHFNMIGN_Pos 8 /*!< SCB CCR: BFHFNMIGN Position */ #define SCB_CCR_BFHFNMIGN_Msk (1UL << SCB_CCR_BFHFNMIGN_Pos) /*!< SCB CCR: BFHFNMIGN Mask */ #define SCB_CCR_DIV_0_TRP_Pos 4 /*!< SCB CCR: DIV_0_TRP Position */ #define SCB_CCR_DIV_0_TRP_Msk (1UL << SCB_CCR_DIV_0_TRP_Pos) /*!< SCB CCR: DIV_0_TRP Mask */ #define SCB_CCR_UNALIGN_TRP_Pos 3 /*!< SCB CCR: UNALIGN_TRP Position */ #define SCB_CCR_UNALIGN_TRP_Msk (1UL << SCB_CCR_UNALIGN_TRP_Pos) /*!< SCB CCR: UNALIGN_TRP Mask */ #define SCB_CCR_USERSETMPEND_Pos 1 /*!< SCB CCR: USERSETMPEND Position */ #define SCB_CCR_USERSETMPEND_Msk (1UL << SCB_CCR_USERSETMPEND_Pos) /*!< SCB CCR: USERSETMPEND Mask */ #define SCB_CCR_NONBASETHRDENA_Pos 0 /*!< SCB CCR: NONBASETHRDENA Position */ #define SCB_CCR_NONBASETHRDENA_Msk (1UL << SCB_CCR_NONBASETHRDENA_Pos) /*!< SCB CCR: NONBASETHRDENA Mask */ /* SCB System Handler Control and State Register Definitions */ #define SCB_SHCSR_USGFAULTENA_Pos 18 /*!< SCB SHCSR: USGFAULTENA Position */ #define SCB_SHCSR_USGFAULTENA_Msk (1UL << SCB_SHCSR_USGFAULTENA_Pos) /*!< SCB SHCSR: USGFAULTENA Mask */ #define SCB_SHCSR_BUSFAULTENA_Pos 17 /*!< SCB SHCSR: BUSFAULTENA Position */ #define SCB_SHCSR_BUSFAULTENA_Msk (1UL << SCB_SHCSR_BUSFAULTENA_Pos) /*!< SCB SHCSR: BUSFAULTENA Mask */ #define SCB_SHCSR_MEMFAULTENA_Pos 16 /*!< SCB SHCSR: MEMFAULTENA Position */ #define SCB_SHCSR_MEMFAULTENA_Msk (1UL << SCB_SHCSR_MEMFAULTENA_Pos) /*!< SCB SHCSR: MEMFAULTENA Mask */ #define SCB_SHCSR_SVCALLPENDED_Pos 15 /*!< SCB SHCSR: SVCALLPENDED Position */ #define SCB_SHCSR_SVCALLPENDED_Msk (1UL << SCB_SHCSR_SVCALLPENDED_Pos) /*!< SCB SHCSR: SVCALLPENDED Mask */ #define SCB_SHCSR_BUSFAULTPENDED_Pos 14 /*!< SCB SHCSR: BUSFAULTPENDED Position */ #define SCB_SHCSR_BUSFAULTPENDED_Msk (1UL << SCB_SHCSR_BUSFAULTPENDED_Pos) /*!< SCB SHCSR: BUSFAULTPENDED Mask */ #define SCB_SHCSR_MEMFAULTPENDED_Pos 13 /*!< SCB SHCSR: MEMFAULTPENDED Position */ #define SCB_SHCSR_MEMFAULTPENDED_Msk (1UL << SCB_SHCSR_MEMFAULTPENDED_Pos) /*!< SCB SHCSR: MEMFAULTPENDED Mask */ #define SCB_SHCSR_USGFAULTPENDED_Pos 12 /*!< SCB SHCSR: USGFAULTPENDED Position */ #define SCB_SHCSR_USGFAULTPENDED_Msk (1UL << SCB_SHCSR_USGFAULTPENDED_Pos) /*!< SCB SHCSR: USGFAULTPENDED Mask */ #define SCB_SHCSR_SYSTICKACT_Pos 11 /*!< SCB SHCSR: SYSTICKACT Position */ #define SCB_SHCSR_SYSTICKACT_Msk (1UL << SCB_SHCSR_SYSTICKACT_Pos) /*!< SCB SHCSR: SYSTICKACT Mask */ #define SCB_SHCSR_PENDSVACT_Pos 10 /*!< SCB SHCSR: PENDSVACT Position */ #define SCB_SHCSR_PENDSVACT_Msk (1UL << SCB_SHCSR_PENDSVACT_Pos) /*!< SCB SHCSR: PENDSVACT Mask */ #define SCB_SHCSR_MONITORACT_Pos 8 /*!< SCB SHCSR: MONITORACT Position */ #define SCB_SHCSR_MONITORACT_Msk (1UL << SCB_SHCSR_MONITORACT_Pos) /*!< SCB SHCSR: MONITORACT Mask */ #define SCB_SHCSR_SVCALLACT_Pos 7 /*!< SCB SHCSR: SVCALLACT Position */ #define SCB_SHCSR_SVCALLACT_Msk (1UL << SCB_SHCSR_SVCALLACT_Pos) /*!< SCB SHCSR: SVCALLACT Mask */ #define SCB_SHCSR_USGFAULTACT_Pos 3 /*!< SCB SHCSR: USGFAULTACT Position */ #define SCB_SHCSR_USGFAULTACT_Msk (1UL << SCB_SHCSR_USGFAULTACT_Pos) /*!< SCB SHCSR: USGFAULTACT Mask */ #define SCB_SHCSR_BUSFAULTACT_Pos 1 /*!< SCB SHCSR: BUSFAULTACT Position */ #define SCB_SHCSR_BUSFAULTACT_Msk (1UL << SCB_SHCSR_BUSFAULTACT_Pos) /*!< SCB SHCSR: BUSFAULTACT Mask */ #define SCB_SHCSR_MEMFAULTACT_Pos 0 /*!< SCB SHCSR: MEMFAULTACT Position */ #define SCB_SHCSR_MEMFAULTACT_Msk (1UL << SCB_SHCSR_MEMFAULTACT_Pos) /*!< SCB SHCSR: MEMFAULTACT Mask */ /* SCB Configurable Fault Status Registers Definitions */ #define SCB_CFSR_USGFAULTSR_Pos 16 /*!< SCB CFSR: Usage Fault Status Register Position */ #define SCB_CFSR_USGFAULTSR_Msk (0xFFFFUL << SCB_CFSR_USGFAULTSR_Pos) /*!< SCB CFSR: Usage Fault Status Register Mask */ #define SCB_CFSR_BUSFAULTSR_Pos 8 /*!< SCB CFSR: Bus Fault Status Register Position */ #define SCB_CFSR_BUSFAULTSR_Msk (0xFFUL << SCB_CFSR_BUSFAULTSR_Pos) /*!< SCB CFSR: Bus Fault Status Register Mask */ #define SCB_CFSR_MEMFAULTSR_Pos 0 /*!< SCB CFSR: Memory Manage Fault Status Register Position */ #define SCB_CFSR_MEMFAULTSR_Msk (0xFFUL << SCB_CFSR_MEMFAULTSR_Pos) /*!< SCB CFSR: Memory Manage Fault Status Register Mask */ /* SCB Hard Fault Status Registers Definitions */ #define SCB_HFSR_DEBUGEVT_Pos 31 /*!< SCB HFSR: DEBUGEVT Position */ #define SCB_HFSR_DEBUGEVT_Msk (1UL << SCB_HFSR_DEBUGEVT_Pos) /*!< SCB HFSR: DEBUGEVT Mask */ #define SCB_HFSR_FORCED_Pos 30 /*!< SCB HFSR: FORCED Position */ #define SCB_HFSR_FORCED_Msk (1UL << SCB_HFSR_FORCED_Pos) /*!< SCB HFSR: FORCED Mask */ #define SCB_HFSR_VECTTBL_Pos 1 /*!< SCB HFSR: VECTTBL Position */ #define SCB_HFSR_VECTTBL_Msk (1UL << SCB_HFSR_VECTTBL_Pos) /*!< SCB HFSR: VECTTBL Mask */ /* SCB Debug Fault Status Register Definitions */ #define SCB_DFSR_EXTERNAL_Pos 4 /*!< SCB DFSR: EXTERNAL Position */ #define SCB_DFSR_EXTERNAL_Msk (1UL << SCB_DFSR_EXTERNAL_Pos) /*!< SCB DFSR: EXTERNAL Mask */ #define SCB_DFSR_VCATCH_Pos 3 /*!< SCB DFSR: VCATCH Position */ #define SCB_DFSR_VCATCH_Msk (1UL << SCB_DFSR_VCATCH_Pos) /*!< SCB DFSR: VCATCH Mask */ #define SCB_DFSR_DWTTRAP_Pos 2 /*!< SCB DFSR: DWTTRAP Position */ #define SCB_DFSR_DWTTRAP_Msk (1UL << SCB_DFSR_DWTTRAP_Pos) /*!< SCB DFSR: DWTTRAP Mask */ #define SCB_DFSR_BKPT_Pos 1 /*!< SCB DFSR: BKPT Position */ #define SCB_DFSR_BKPT_Msk (1UL << SCB_DFSR_BKPT_Pos) /*!< SCB DFSR: BKPT Mask */ #define SCB_DFSR_HALTED_Pos 0 /*!< SCB DFSR: HALTED Position */ #define SCB_DFSR_HALTED_Msk (1UL << SCB_DFSR_HALTED_Pos) /*!< SCB DFSR: HALTED Mask */ /*@} end of group CMSIS_SCB */ /** \ingroup CMSIS_core_register \defgroup CMSIS_SCnSCB System Controls not in SCB (SCnSCB) \brief Type definitions for the System Control and ID Register not in the SCB @{ */ /** \brief Structure type to access the System Control and ID Register not in the SCB. */ typedef struct { uint32_t RESERVED0[1]; __I uint32_t ICTR; /*!< Offset: 0x004 (R/ ) Interrupt Controller Type Register */ #if ((defined __CM3_REV) && (__CM3_REV >= 0x200)) __IO uint32_t ACTLR; /*!< Offset: 0x008 (R/W) Auxiliary Control Register */ #else uint32_t RESERVED1[1]; #endif } SCnSCB_Type; /* Interrupt Controller Type Register Definitions */ #define SCnSCB_ICTR_INTLINESNUM_Pos 0 /*!< ICTR: INTLINESNUM Position */ #define SCnSCB_ICTR_INTLINESNUM_Msk (0xFUL << SCnSCB_ICTR_INTLINESNUM_Pos) /*!< ICTR: INTLINESNUM Mask */ /* Auxiliary Control Register Definitions */ #define SCnSCB_ACTLR_DISFOLD_Pos 2 /*!< ACTLR: DISFOLD Position */ #define SCnSCB_ACTLR_DISFOLD_Msk (1UL << SCnSCB_ACTLR_DISFOLD_Pos) /*!< ACTLR: DISFOLD Mask */ #define SCnSCB_ACTLR_DISDEFWBUF_Pos 1 /*!< ACTLR: DISDEFWBUF Position */ #define SCnSCB_ACTLR_DISDEFWBUF_Msk (1UL << SCnSCB_ACTLR_DISDEFWBUF_Pos) /*!< ACTLR: DISDEFWBUF Mask */ #define SCnSCB_ACTLR_DISMCYCINT_Pos 0 /*!< ACTLR: DISMCYCINT Position */ #define SCnSCB_ACTLR_DISMCYCINT_Msk (1UL << SCnSCB_ACTLR_DISMCYCINT_Pos) /*!< ACTLR: DISMCYCINT Mask */ /*@} end of group CMSIS_SCnotSCB */ /** \ingroup CMSIS_core_register \defgroup CMSIS_SysTick System Tick Timer (SysTick) \brief Type definitions for the System Timer Registers. @{ */ /** \brief Structure type to access the System Timer (SysTick). */ typedef struct { __IO uint32_t CTRL; /*!< Offset: 0x000 (R/W) SysTick Control and Status Register */ __IO uint32_t LOAD; /*!< Offset: 0x004 (R/W) SysTick Reload Value Register */ __IO uint32_t VAL; /*!< Offset: 0x008 (R/W) SysTick Current Value Register */ __I uint32_t CALIB; /*!< Offset: 0x00C (R/ ) SysTick Calibration Register */ } SysTick_Type; /* SysTick Control / Status Register Definitions */ #define SysTick_CTRL_COUNTFLAG_Pos 16 /*!< SysTick CTRL: COUNTFLAG Position */ #define SysTick_CTRL_COUNTFLAG_Msk (1UL << SysTick_CTRL_COUNTFLAG_Pos) /*!< SysTick CTRL: COUNTFLAG Mask */ #define SysTick_CTRL_CLKSOURCE_Pos 2 /*!< SysTick CTRL: CLKSOURCE Position */ #define SysTick_CTRL_CLKSOURCE_Msk (1UL << SysTick_CTRL_CLKSOURCE_Pos) /*!< SysTick CTRL: CLKSOURCE Mask */ #define SysTick_CTRL_TICKINT_Pos 1 /*!< SysTick CTRL: TICKINT Position */ #define SysTick_CTRL_TICKINT_Msk (1UL << SysTick_CTRL_TICKINT_Pos) /*!< SysTick CTRL: TICKINT Mask */ #define SysTick_CTRL_ENABLE_Pos 0 /*!< SysTick CTRL: ENABLE Position */ #define SysTick_CTRL_ENABLE_Msk (1UL << SysTick_CTRL_ENABLE_Pos) /*!< SysTick CTRL: ENABLE Mask */ /* SysTick Reload Register Definitions */ #define SysTick_LOAD_RELOAD_Pos 0 /*!< SysTick LOAD: RELOAD Position */ #define SysTick_LOAD_RELOAD_Msk (0xFFFFFFUL << SysTick_LOAD_RELOAD_Pos) /*!< SysTick LOAD: RELOAD Mask */ /* SysTick Current Register Definitions */ #define SysTick_VAL_CURRENT_Pos 0 /*!< SysTick VAL: CURRENT Position */ #define SysTick_VAL_CURRENT_Msk (0xFFFFFFUL << SysTick_VAL_CURRENT_Pos) /*!< SysTick VAL: CURRENT Mask */ /* SysTick Calibration Register Definitions */ #define SysTick_CALIB_NOREF_Pos 31 /*!< SysTick CALIB: NOREF Position */ #define SysTick_CALIB_NOREF_Msk (1UL << SysTick_CALIB_NOREF_Pos) /*!< SysTick CALIB: NOREF Mask */ #define SysTick_CALIB_SKEW_Pos 30 /*!< SysTick CALIB: SKEW Position */ #define SysTick_CALIB_SKEW_Msk (1UL << SysTick_CALIB_SKEW_Pos) /*!< SysTick CALIB: SKEW Mask */ #define SysTick_CALIB_TENMS_Pos 0 /*!< SysTick CALIB: TENMS Position */ #define SysTick_CALIB_TENMS_Msk (0xFFFFFFUL << SysTick_VAL_CURRENT_Pos) /*!< SysTick CALIB: TENMS Mask */ /*@} end of group CMSIS_SysTick */ /** \ingroup CMSIS_core_register \defgroup CMSIS_ITM Instrumentation Trace Macrocell (ITM) \brief Type definitions for the Instrumentation Trace Macrocell (ITM) @{ */ /** \brief Structure type to access the Instrumentation Trace Macrocell Register (ITM). */ typedef struct { __O union { __O uint8_t u8; /*!< Offset: 0x000 ( /W) ITM Stimulus Port 8-bit */ __O uint16_t u16; /*!< Offset: 0x000 ( /W) ITM Stimulus Port 16-bit */ __O uint32_t u32; /*!< Offset: 0x000 ( /W) ITM Stimulus Port 32-bit */ } PORT [32]; /*!< Offset: 0x000 ( /W) ITM Stimulus Port Registers */ uint32_t RESERVED0[864]; __IO uint32_t TER; /*!< Offset: 0xE00 (R/W) ITM Trace Enable Register */ uint32_t RESERVED1[15]; __IO uint32_t TPR; /*!< Offset: 0xE40 (R/W) ITM Trace Privilege Register */ uint32_t RESERVED2[15]; __IO uint32_t TCR; /*!< Offset: 0xE80 (R/W) ITM Trace Control Register */ uint32_t RESERVED3[29]; __O uint32_t IWR; /*!< Offset: 0xEF8 ( /W) ITM Integration Write Register */ __I uint32_t IRR; /*!< Offset: 0xEFC (R/ ) ITM Integration Read Register */ __IO uint32_t IMCR; /*!< Offset: 0xF00 (R/W) ITM Integration Mode Control Register */ uint32_t RESERVED4[43]; __O uint32_t LAR; /*!< Offset: 0xFB0 ( /W) ITM Lock Access Register */ __I uint32_t LSR; /*!< Offset: 0xFB4 (R/ ) ITM Lock Status Register */ uint32_t RESERVED5[6]; __I uint32_t PID4; /*!< Offset: 0xFD0 (R/ ) ITM Peripheral Identification Register #4 */ __I uint32_t PID5; /*!< Offset: 0xFD4 (R/ ) ITM Peripheral Identification Register #5 */ __I uint32_t PID6; /*!< Offset: 0xFD8 (R/ ) ITM Peripheral Identification Register #6 */ __I uint32_t PID7; /*!< Offset: 0xFDC (R/ ) ITM Peripheral Identification Register #7 */ __I uint32_t PID0; /*!< Offset: 0xFE0 (R/ ) ITM Peripheral Identification Register #0 */ __I uint32_t PID1; /*!< Offset: 0xFE4 (R/ ) ITM Peripheral Identification Register #1 */ __I uint32_t PID2; /*!< Offset: 0xFE8 (R/ ) ITM Peripheral Identification Register #2 */ __I uint32_t PID3; /*!< Offset: 0xFEC (R/ ) ITM Peripheral Identification Register #3 */ __I uint32_t CID0; /*!< Offset: 0xFF0 (R/ ) ITM Component Identification Register #0 */ __I uint32_t CID1; /*!< Offset: 0xFF4 (R/ ) ITM Component Identification Register #1 */ __I uint32_t CID2; /*!< Offset: 0xFF8 (R/ ) ITM Component Identification Register #2 */ __I uint32_t CID3; /*!< Offset: 0xFFC (R/ ) ITM Component Identification Register #3 */ } ITM_Type; /* ITM Trace Privilege Register Definitions */ #define ITM_TPR_PRIVMASK_Pos 0 /*!< ITM TPR: PRIVMASK Position */ #define ITM_TPR_PRIVMASK_Msk (0xFUL << ITM_TPR_PRIVMASK_Pos) /*!< ITM TPR: PRIVMASK Mask */ /* ITM Trace Control Register Definitions */ #define ITM_TCR_BUSY_Pos 23 /*!< ITM TCR: BUSY Position */ #define ITM_TCR_BUSY_Msk (1UL << ITM_TCR_BUSY_Pos) /*!< ITM TCR: BUSY Mask */ #define ITM_TCR_TraceBusID_Pos 16 /*!< ITM TCR: ATBID Position */ #define ITM_TCR_TraceBusID_Msk (0x7FUL << ITM_TCR_TraceBusID_Pos) /*!< ITM TCR: ATBID Mask */ #define ITM_TCR_GTSFREQ_Pos 10 /*!< ITM TCR: Global timestamp frequency Position */ #define ITM_TCR_GTSFREQ_Msk (3UL << ITM_TCR_GTSFREQ_Pos) /*!< ITM TCR: Global timestamp frequency Mask */ #define ITM_TCR_TSPrescale_Pos 8 /*!< ITM TCR: TSPrescale Position */ #define ITM_TCR_TSPrescale_Msk (3UL << ITM_TCR_TSPrescale_Pos) /*!< ITM TCR: TSPrescale Mask */ #define ITM_TCR_SWOENA_Pos 4 /*!< ITM TCR: SWOENA Position */ #define ITM_TCR_SWOENA_Msk (1UL << ITM_TCR_SWOENA_Pos) /*!< ITM TCR: SWOENA Mask */ #define ITM_TCR_DWTENA_Pos 3 /*!< ITM TCR: DWTENA Position */ #define ITM_TCR_DWTENA_Msk (1UL << ITM_TCR_DWTENA_Pos) /*!< ITM TCR: DWTENA Mask */ #define ITM_TCR_SYNCENA_Pos 2 /*!< ITM TCR: SYNCENA Position */ #define ITM_TCR_SYNCENA_Msk (1UL << ITM_TCR_SYNCENA_Pos) /*!< ITM TCR: SYNCENA Mask */ #define ITM_TCR_TSENA_Pos 1 /*!< ITM TCR: TSENA Position */ #define ITM_TCR_TSENA_Msk (1UL << ITM_TCR_TSENA_Pos) /*!< ITM TCR: TSENA Mask */ #define ITM_TCR_ITMENA_Pos 0 /*!< ITM TCR: ITM Enable bit Position */ #define ITM_TCR_ITMENA_Msk (1UL << ITM_TCR_ITMENA_Pos) /*!< ITM TCR: ITM Enable bit Mask */ /* ITM Integration Write Register Definitions */ #define ITM_IWR_ATVALIDM_Pos 0 /*!< ITM IWR: ATVALIDM Position */ #define ITM_IWR_ATVALIDM_Msk (1UL << ITM_IWR_ATVALIDM_Pos) /*!< ITM IWR: ATVALIDM Mask */ /* ITM Integration Read Register Definitions */ #define ITM_IRR_ATREADYM_Pos 0 /*!< ITM IRR: ATREADYM Position */ #define ITM_IRR_ATREADYM_Msk (1UL << ITM_IRR_ATREADYM_Pos) /*!< ITM IRR: ATREADYM Mask */ /* ITM Integration Mode Control Register Definitions */ #define ITM_IMCR_INTEGRATION_Pos 0 /*!< ITM IMCR: INTEGRATION Position */ #define ITM_IMCR_INTEGRATION_Msk (1UL << ITM_IMCR_INTEGRATION_Pos) /*!< ITM IMCR: INTEGRATION Mask */ /* ITM Lock Status Register Definitions */ #define ITM_LSR_ByteAcc_Pos 2 /*!< ITM LSR: ByteAcc Position */ #define ITM_LSR_ByteAcc_Msk (1UL << ITM_LSR_ByteAcc_Pos) /*!< ITM LSR: ByteAcc Mask */ #define ITM_LSR_Access_Pos 1 /*!< ITM LSR: Access Position */ #define ITM_LSR_Access_Msk (1UL << ITM_LSR_Access_Pos) /*!< ITM LSR: Access Mask */ #define ITM_LSR_Present_Pos 0 /*!< ITM LSR: Present Position */ #define ITM_LSR_Present_Msk (1UL << ITM_LSR_Present_Pos) /*!< ITM LSR: Present Mask */ /*@}*/ /* end of group CMSIS_ITM */ /** \ingroup CMSIS_core_register \defgroup CMSIS_DWT Data Watchpoint and Trace (DWT) \brief Type definitions for the Data Watchpoint and Trace (DWT) @{ */ /** \brief Structure type to access the Data Watchpoint and Trace Register (DWT). */ typedef struct { __IO uint32_t CTRL; /*!< Offset: 0x000 (R/W) Control Register */ __IO uint32_t CYCCNT; /*!< Offset: 0x004 (R/W) Cycle Count Register */ __IO uint32_t CPICNT; /*!< Offset: 0x008 (R/W) CPI Count Register */ __IO uint32_t EXCCNT; /*!< Offset: 0x00C (R/W) Exception Overhead Count Register */ __IO uint32_t SLEEPCNT; /*!< Offset: 0x010 (R/W) Sleep Count Register */ __IO uint32_t LSUCNT; /*!< Offset: 0x014 (R/W) LSU Count Register */ __IO uint32_t FOLDCNT; /*!< Offset: 0x018 (R/W) Folded-instruction Count Register */ __I uint32_t PCSR; /*!< Offset: 0x01C (R/ ) Program Counter Sample Register */ __IO uint32_t COMP0; /*!< Offset: 0x020 (R/W) Comparator Register 0 */ __IO uint32_t MASK0; /*!< Offset: 0x024 (R/W) Mask Register 0 */ __IO uint32_t FUNCTION0; /*!< Offset: 0x028 (R/W) Function Register 0 */ uint32_t RESERVED0[1]; __IO uint32_t COMP1; /*!< Offset: 0x030 (R/W) Comparator Register 1 */ __IO uint32_t MASK1; /*!< Offset: 0x034 (R/W) Mask Register 1 */ __IO uint32_t FUNCTION1; /*!< Offset: 0x038 (R/W) Function Register 1 */ uint32_t RESERVED1[1]; __IO uint32_t COMP2; /*!< Offset: 0x040 (R/W) Comparator Register 2 */ __IO uint32_t MASK2; /*!< Offset: 0x044 (R/W) Mask Register 2 */ __IO uint32_t FUNCTION2; /*!< Offset: 0x048 (R/W) Function Register 2 */ uint32_t RESERVED2[1]; __IO uint32_t COMP3; /*!< Offset: 0x050 (R/W) Comparator Register 3 */ __IO uint32_t MASK3; /*!< Offset: 0x054 (R/W) Mask Register 3 */ __IO uint32_t FUNCTION3; /*!< Offset: 0x058 (R/W) Function Register 3 */ } DWT_Type; /* DWT Control Register Definitions */ #define DWT_CTRL_NUMCOMP_Pos 28 /*!< DWT CTRL: NUMCOMP Position */ #define DWT_CTRL_NUMCOMP_Msk (0xFUL << DWT_CTRL_NUMCOMP_Pos) /*!< DWT CTRL: NUMCOMP Mask */ #define DWT_CTRL_NOTRCPKT_Pos 27 /*!< DWT CTRL: NOTRCPKT Position */ #define DWT_CTRL_NOTRCPKT_Msk (0x1UL << DWT_CTRL_NOTRCPKT_Pos) /*!< DWT CTRL: NOTRCPKT Mask */ #define DWT_CTRL_NOEXTTRIG_Pos 26 /*!< DWT CTRL: NOEXTTRIG Position */ #define DWT_CTRL_NOEXTTRIG_Msk (0x1UL << DWT_CTRL_NOEXTTRIG_Pos) /*!< DWT CTRL: NOEXTTRIG Mask */ #define DWT_CTRL_NOCYCCNT_Pos 25 /*!< DWT CTRL: NOCYCCNT Position */ #define DWT_CTRL_NOCYCCNT_Msk (0x1UL << DWT_CTRL_NOCYCCNT_Pos) /*!< DWT CTRL: NOCYCCNT Mask */ #define DWT_CTRL_NOPRFCNT_Pos 24 /*!< DWT CTRL: NOPRFCNT Position */ #define DWT_CTRL_NOPRFCNT_Msk (0x1UL << DWT_CTRL_NOPRFCNT_Pos) /*!< DWT CTRL: NOPRFCNT Mask */ #define DWT_CTRL_CYCEVTENA_Pos 22 /*!< DWT CTRL: CYCEVTENA Position */ #define DWT_CTRL_CYCEVTENA_Msk (0x1UL << DWT_CTRL_CYCEVTENA_Pos) /*!< DWT CTRL: CYCEVTENA Mask */ #define DWT_CTRL_FOLDEVTENA_Pos 21 /*!< DWT CTRL: FOLDEVTENA Position */ #define DWT_CTRL_FOLDEVTENA_Msk (0x1UL << DWT_CTRL_FOLDEVTENA_Pos) /*!< DWT CTRL: FOLDEVTENA Mask */ #define DWT_CTRL_LSUEVTENA_Pos 20 /*!< DWT CTRL: LSUEVTENA Position */ #define DWT_CTRL_LSUEVTENA_Msk (0x1UL << DWT_CTRL_LSUEVTENA_Pos) /*!< DWT CTRL: LSUEVTENA Mask */ #define DWT_CTRL_SLEEPEVTENA_Pos 19 /*!< DWT CTRL: SLEEPEVTENA Position */ #define DWT_CTRL_SLEEPEVTENA_Msk (0x1UL << DWT_CTRL_SLEEPEVTENA_Pos) /*!< DWT CTRL: SLEEPEVTENA Mask */ #define DWT_CTRL_EXCEVTENA_Pos 18 /*!< DWT CTRL: EXCEVTENA Position */ #define DWT_CTRL_EXCEVTENA_Msk (0x1UL << DWT_CTRL_EXCEVTENA_Pos) /*!< DWT CTRL: EXCEVTENA Mask */ #define DWT_CTRL_CPIEVTENA_Pos 17 /*!< DWT CTRL: CPIEVTENA Position */ #define DWT_CTRL_CPIEVTENA_Msk (0x1UL << DWT_CTRL_CPIEVTENA_Pos) /*!< DWT CTRL: CPIEVTENA Mask */ #define DWT_CTRL_EXCTRCENA_Pos 16 /*!< DWT CTRL: EXCTRCENA Position */ #define DWT_CTRL_EXCTRCENA_Msk (0x1UL << DWT_CTRL_EXCTRCENA_Pos) /*!< DWT CTRL: EXCTRCENA Mask */ #define DWT_CTRL_PCSAMPLENA_Pos 12 /*!< DWT CTRL: PCSAMPLENA Position */ #define DWT_CTRL_PCSAMPLENA_Msk (0x1UL << DWT_CTRL_PCSAMPLENA_Pos) /*!< DWT CTRL: PCSAMPLENA Mask */ #define DWT_CTRL_SYNCTAP_Pos 10 /*!< DWT CTRL: SYNCTAP Position */ #define DWT_CTRL_SYNCTAP_Msk (0x3UL << DWT_CTRL_SYNCTAP_Pos) /*!< DWT CTRL: SYNCTAP Mask */ #define DWT_CTRL_CYCTAP_Pos 9 /*!< DWT CTRL: CYCTAP Position */ #define DWT_CTRL_CYCTAP_Msk (0x1UL << DWT_CTRL_CYCTAP_Pos) /*!< DWT CTRL: CYCTAP Mask */ #define DWT_CTRL_POSTINIT_Pos 5 /*!< DWT CTRL: POSTINIT Position */ #define DWT_CTRL_POSTINIT_Msk (0xFUL << DWT_CTRL_POSTINIT_Pos) /*!< DWT CTRL: POSTINIT Mask */ #define DWT_CTRL_POSTPRESET_Pos 1 /*!< DWT CTRL: POSTPRESET Position */ #define DWT_CTRL_POSTPRESET_Msk (0xFUL << DWT_CTRL_POSTPRESET_Pos) /*!< DWT CTRL: POSTPRESET Mask */ #define DWT_CTRL_CYCCNTENA_Pos 0 /*!< DWT CTRL: CYCCNTENA Position */ #define DWT_CTRL_CYCCNTENA_Msk (0x1UL << DWT_CTRL_CYCCNTENA_Pos) /*!< DWT CTRL: CYCCNTENA Mask */ /* DWT CPI Count Register Definitions */ #define DWT_CPICNT_CPICNT_Pos 0 /*!< DWT CPICNT: CPICNT Position */ #define DWT_CPICNT_CPICNT_Msk (0xFFUL << DWT_CPICNT_CPICNT_Pos) /*!< DWT CPICNT: CPICNT Mask */ /* DWT Exception Overhead Count Register Definitions */ #define DWT_EXCCNT_EXCCNT_Pos 0 /*!< DWT EXCCNT: EXCCNT Position */ #define DWT_EXCCNT_EXCCNT_Msk (0xFFUL << DWT_EXCCNT_EXCCNT_Pos) /*!< DWT EXCCNT: EXCCNT Mask */ /* DWT Sleep Count Register Definitions */ #define DWT_SLEEPCNT_SLEEPCNT_Pos 0 /*!< DWT SLEEPCNT: SLEEPCNT Position */ #define DWT_SLEEPCNT_SLEEPCNT_Msk (0xFFUL << DWT_SLEEPCNT_SLEEPCNT_Pos) /*!< DWT SLEEPCNT: SLEEPCNT Mask */ /* DWT LSU Count Register Definitions */ #define DWT_LSUCNT_LSUCNT_Pos 0 /*!< DWT LSUCNT: LSUCNT Position */ #define DWT_LSUCNT_LSUCNT_Msk (0xFFUL << DWT_LSUCNT_LSUCNT_Pos) /*!< DWT LSUCNT: LSUCNT Mask */ /* DWT Folded-instruction Count Register Definitions */ #define DWT_FOLDCNT_FOLDCNT_Pos 0 /*!< DWT FOLDCNT: FOLDCNT Position */ #define DWT_FOLDCNT_FOLDCNT_Msk (0xFFUL << DWT_FOLDCNT_FOLDCNT_Pos) /*!< DWT FOLDCNT: FOLDCNT Mask */ /* DWT Comparator Mask Register Definitions */ #define DWT_MASK_MASK_Pos 0 /*!< DWT MASK: MASK Position */ #define DWT_MASK_MASK_Msk (0x1FUL << DWT_MASK_MASK_Pos) /*!< DWT MASK: MASK Mask */ /* DWT Comparator Function Register Definitions */ #define DWT_FUNCTION_MATCHED_Pos 24 /*!< DWT FUNCTION: MATCHED Position */ #define DWT_FUNCTION_MATCHED_Msk (0x1UL << DWT_FUNCTION_MATCHED_Pos) /*!< DWT FUNCTION: MATCHED Mask */ #define DWT_FUNCTION_DATAVADDR1_Pos 16 /*!< DWT FUNCTION: DATAVADDR1 Position */ #define DWT_FUNCTION_DATAVADDR1_Msk (0xFUL << DWT_FUNCTION_DATAVADDR1_Pos) /*!< DWT FUNCTION: DATAVADDR1 Mask */ #define DWT_FUNCTION_DATAVADDR0_Pos 12 /*!< DWT FUNCTION: DATAVADDR0 Position */ #define DWT_FUNCTION_DATAVADDR0_Msk (0xFUL << DWT_FUNCTION_DATAVADDR0_Pos) /*!< DWT FUNCTION: DATAVADDR0 Mask */ #define DWT_FUNCTION_DATAVSIZE_Pos 10 /*!< DWT FUNCTION: DATAVSIZE Position */ #define DWT_FUNCTION_DATAVSIZE_Msk (0x3UL << DWT_FUNCTION_DATAVSIZE_Pos) /*!< DWT FUNCTION: DATAVSIZE Mask */ #define DWT_FUNCTION_LNK1ENA_Pos 9 /*!< DWT FUNCTION: LNK1ENA Position */ #define DWT_FUNCTION_LNK1ENA_Msk (0x1UL << DWT_FUNCTION_LNK1ENA_Pos) /*!< DWT FUNCTION: LNK1ENA Mask */ #define DWT_FUNCTION_DATAVMATCH_Pos 8 /*!< DWT FUNCTION: DATAVMATCH Position */ #define DWT_FUNCTION_DATAVMATCH_Msk (0x1UL << DWT_FUNCTION_DATAVMATCH_Pos) /*!< DWT FUNCTION: DATAVMATCH Mask */ #define DWT_FUNCTION_CYCMATCH_Pos 7 /*!< DWT FUNCTION: CYCMATCH Position */ #define DWT_FUNCTION_CYCMATCH_Msk (0x1UL << DWT_FUNCTION_CYCMATCH_Pos) /*!< DWT FUNCTION: CYCMATCH Mask */ #define DWT_FUNCTION_EMITRANGE_Pos 5 /*!< DWT FUNCTION: EMITRANGE Position */ #define DWT_FUNCTION_EMITRANGE_Msk (0x1UL << DWT_FUNCTION_EMITRANGE_Pos) /*!< DWT FUNCTION: EMITRANGE Mask */ #define DWT_FUNCTION_FUNCTION_Pos 0 /*!< DWT FUNCTION: FUNCTION Position */ #define DWT_FUNCTION_FUNCTION_Msk (0xFUL << DWT_FUNCTION_FUNCTION_Pos) /*!< DWT FUNCTION: FUNCTION Mask */ /*@}*/ /* end of group CMSIS_DWT */ /** \ingroup CMSIS_core_register \defgroup CMSIS_TPI Trace Port Interface (TPI) \brief Type definitions for the Trace Port Interface (TPI) @{ */ /** \brief Structure type to access the Trace Port Interface Register (TPI). */ typedef struct { __IO uint32_t SSPSR; /*!< Offset: 0x000 (R/ ) Supported Parallel Port Size Register */ __IO uint32_t CSPSR; /*!< Offset: 0x004 (R/W) Current Parallel Port Size Register */ uint32_t RESERVED0[2]; __IO uint32_t ACPR; /*!< Offset: 0x010 (R/W) Asynchronous Clock Prescaler Register */ uint32_t RESERVED1[55]; __IO uint32_t SPPR; /*!< Offset: 0x0F0 (R/W) Selected Pin Protocol Register */ uint32_t RESERVED2[131]; __I uint32_t FFSR; /*!< Offset: 0x300 (R/ ) Formatter and Flush Status Register */ __IO uint32_t FFCR; /*!< Offset: 0x304 (R/W) Formatter and Flush Control Register */ __I uint32_t FSCR; /*!< Offset: 0x308 (R/ ) Formatter Synchronization Counter Register */ uint32_t RESERVED3[759]; __I uint32_t TRIGGER; /*!< Offset: 0xEE8 (R/ ) TRIGGER */ __I uint32_t FIFO0; /*!< Offset: 0xEEC (R/ ) Integration ETM Data */ __I uint32_t ITATBCTR2; /*!< Offset: 0xEF0 (R/ ) ITATBCTR2 */ uint32_t RESERVED4[1]; __I uint32_t ITATBCTR0; /*!< Offset: 0xEF8 (R/ ) ITATBCTR0 */ __I uint32_t FIFO1; /*!< Offset: 0xEFC (R/ ) Integration ITM Data */ __IO uint32_t ITCTRL; /*!< Offset: 0xF00 (R/W) Integration Mode Control */ uint32_t RESERVED5[39]; __IO uint32_t CLAIMSET; /*!< Offset: 0xFA0 (R/W) Claim tag set */ __IO uint32_t CLAIMCLR; /*!< Offset: 0xFA4 (R/W) Claim tag clear */ uint32_t RESERVED7[8]; __I uint32_t DEVID; /*!< Offset: 0xFC8 (R/ ) TPIU_DEVID */ __I uint32_t DEVTYPE; /*!< Offset: 0xFCC (R/ ) TPIU_DEVTYPE */ } TPI_Type; /* TPI Asynchronous Clock Prescaler Register Definitions */ #define TPI_ACPR_PRESCALER_Pos 0 /*!< TPI ACPR: PRESCALER Position */ #define TPI_ACPR_PRESCALER_Msk (0x1FFFUL << TPI_ACPR_PRESCALER_Pos) /*!< TPI ACPR: PRESCALER Mask */ /* TPI Selected Pin Protocol Register Definitions */ #define TPI_SPPR_TXMODE_Pos 0 /*!< TPI SPPR: TXMODE Position */ #define TPI_SPPR_TXMODE_Msk (0x3UL << TPI_SPPR_TXMODE_Pos) /*!< TPI SPPR: TXMODE Mask */ /* TPI Formatter and Flush Status Register Definitions */ #define TPI_FFSR_FtNonStop_Pos 3 /*!< TPI FFSR: FtNonStop Position */ #define TPI_FFSR_FtNonStop_Msk (0x1UL << TPI_FFSR_FtNonStop_Pos) /*!< TPI FFSR: FtNonStop Mask */ #define TPI_FFSR_TCPresent_Pos 2 /*!< TPI FFSR: TCPresent Position */ #define TPI_FFSR_TCPresent_Msk (0x1UL << TPI_FFSR_TCPresent_Pos) /*!< TPI FFSR: TCPresent Mask */ #define TPI_FFSR_FtStopped_Pos 1 /*!< TPI FFSR: FtStopped Position */ #define TPI_FFSR_FtStopped_Msk (0x1UL << TPI_FFSR_FtStopped_Pos) /*!< TPI FFSR: FtStopped Mask */ #define TPI_FFSR_FlInProg_Pos 0 /*!< TPI FFSR: FlInProg Position */ #define TPI_FFSR_FlInProg_Msk (0x1UL << TPI_FFSR_FlInProg_Pos) /*!< TPI FFSR: FlInProg Mask */ /* TPI Formatter and Flush Control Register Definitions */ #define TPI_FFCR_TrigIn_Pos 8 /*!< TPI FFCR: TrigIn Position */ #define TPI_FFCR_TrigIn_Msk (0x1UL << TPI_FFCR_TrigIn_Pos) /*!< TPI FFCR: TrigIn Mask */ #define TPI_FFCR_EnFCont_Pos 1 /*!< TPI FFCR: EnFCont Position */ #define TPI_FFCR_EnFCont_Msk (0x1UL << TPI_FFCR_EnFCont_Pos) /*!< TPI FFCR: EnFCont Mask */ /* TPI TRIGGER Register Definitions */ #define TPI_TRIGGER_TRIGGER_Pos 0 /*!< TPI TRIGGER: TRIGGER Position */ #define TPI_TRIGGER_TRIGGER_Msk (0x1UL << TPI_TRIGGER_TRIGGER_Pos) /*!< TPI TRIGGER: TRIGGER Mask */ /* TPI Integration ETM Data Register Definitions (FIFO0) */ #define TPI_FIFO0_ITM_ATVALID_Pos 29 /*!< TPI FIFO0: ITM_ATVALID Position */ #define TPI_FIFO0_ITM_ATVALID_Msk (0x3UL << TPI_FIFO0_ITM_ATVALID_Pos) /*!< TPI FIFO0: ITM_ATVALID Mask */ #define TPI_FIFO0_ITM_bytecount_Pos 27 /*!< TPI FIFO0: ITM_bytecount Position */ #define TPI_FIFO0_ITM_bytecount_Msk (0x3UL << TPI_FIFO0_ITM_bytecount_Pos) /*!< TPI FIFO0: ITM_bytecount Mask */ #define TPI_FIFO0_ETM_ATVALID_Pos 26 /*!< TPI FIFO0: ETM_ATVALID Position */ #define TPI_FIFO0_ETM_ATVALID_Msk (0x3UL << TPI_FIFO0_ETM_ATVALID_Pos) /*!< TPI FIFO0: ETM_ATVALID Mask */ #define TPI_FIFO0_ETM_bytecount_Pos 24 /*!< TPI FIFO0: ETM_bytecount Position */ #define TPI_FIFO0_ETM_bytecount_Msk (0x3UL << TPI_FIFO0_ETM_bytecount_Pos) /*!< TPI FIFO0: ETM_bytecount Mask */ #define TPI_FIFO0_ETM2_Pos 16 /*!< TPI FIFO0: ETM2 Position */ #define TPI_FIFO0_ETM2_Msk (0xFFUL << TPI_FIFO0_ETM2_Pos) /*!< TPI FIFO0: ETM2 Mask */ #define TPI_FIFO0_ETM1_Pos 8 /*!< TPI FIFO0: ETM1 Position */ #define TPI_FIFO0_ETM1_Msk (0xFFUL << TPI_FIFO0_ETM1_Pos) /*!< TPI FIFO0: ETM1 Mask */ #define TPI_FIFO0_ETM0_Pos 0 /*!< TPI FIFO0: ETM0 Position */ #define TPI_FIFO0_ETM0_Msk (0xFFUL << TPI_FIFO0_ETM0_Pos) /*!< TPI FIFO0: ETM0 Mask */ /* TPI ITATBCTR2 Register Definitions */ #define TPI_ITATBCTR2_ATREADY_Pos 0 /*!< TPI ITATBCTR2: ATREADY Position */ #define TPI_ITATBCTR2_ATREADY_Msk (0x1UL << TPI_ITATBCTR2_ATREADY_Pos) /*!< TPI ITATBCTR2: ATREADY Mask */ /* TPI Integration ITM Data Register Definitions (FIFO1) */ #define TPI_FIFO1_ITM_ATVALID_Pos 29 /*!< TPI FIFO1: ITM_ATVALID Position */ #define TPI_FIFO1_ITM_ATVALID_Msk (0x3UL << TPI_FIFO1_ITM_ATVALID_Pos) /*!< TPI FIFO1: ITM_ATVALID Mask */ #define TPI_FIFO1_ITM_bytecount_Pos 27 /*!< TPI FIFO1: ITM_bytecount Position */ #define TPI_FIFO1_ITM_bytecount_Msk (0x3UL << TPI_FIFO1_ITM_bytecount_Pos) /*!< TPI FIFO1: ITM_bytecount Mask */ #define TPI_FIFO1_ETM_ATVALID_Pos 26 /*!< TPI FIFO1: ETM_ATVALID Position */ #define TPI_FIFO1_ETM_ATVALID_Msk (0x3UL << TPI_FIFO1_ETM_ATVALID_Pos) /*!< TPI FIFO1: ETM_ATVALID Mask */ #define TPI_FIFO1_ETM_bytecount_Pos 24 /*!< TPI FIFO1: ETM_bytecount Position */ #define TPI_FIFO1_ETM_bytecount_Msk (0x3UL << TPI_FIFO1_ETM_bytecount_Pos) /*!< TPI FIFO1: ETM_bytecount Mask */ #define TPI_FIFO1_ITM2_Pos 16 /*!< TPI FIFO1: ITM2 Position */ #define TPI_FIFO1_ITM2_Msk (0xFFUL << TPI_FIFO1_ITM2_Pos) /*!< TPI FIFO1: ITM2 Mask */ #define TPI_FIFO1_ITM1_Pos 8 /*!< TPI FIFO1: ITM1 Position */ #define TPI_FIFO1_ITM1_Msk (0xFFUL << TPI_FIFO1_ITM1_Pos) /*!< TPI FIFO1: ITM1 Mask */ #define TPI_FIFO1_ITM0_Pos 0 /*!< TPI FIFO1: ITM0 Position */ #define TPI_FIFO1_ITM0_Msk (0xFFUL << TPI_FIFO1_ITM0_Pos) /*!< TPI FIFO1: ITM0 Mask */ /* TPI ITATBCTR0 Register Definitions */ #define TPI_ITATBCTR0_ATREADY_Pos 0 /*!< TPI ITATBCTR0: ATREADY Position */ #define TPI_ITATBCTR0_ATREADY_Msk (0x1UL << TPI_ITATBCTR0_ATREADY_Pos) /*!< TPI ITATBCTR0: ATREADY Mask */ /* TPI Integration Mode Control Register Definitions */ #define TPI_ITCTRL_Mode_Pos 0 /*!< TPI ITCTRL: Mode Position */ #define TPI_ITCTRL_Mode_Msk (0x1UL << TPI_ITCTRL_Mode_Pos) /*!< TPI ITCTRL: Mode Mask */ /* TPI DEVID Register Definitions */ #define TPI_DEVID_NRZVALID_Pos 11 /*!< TPI DEVID: NRZVALID Position */ #define TPI_DEVID_NRZVALID_Msk (0x1UL << TPI_DEVID_NRZVALID_Pos) /*!< TPI DEVID: NRZVALID Mask */ #define TPI_DEVID_MANCVALID_Pos 10 /*!< TPI DEVID: MANCVALID Position */ #define TPI_DEVID_MANCVALID_Msk (0x1UL << TPI_DEVID_MANCVALID_Pos) /*!< TPI DEVID: MANCVALID Mask */ #define TPI_DEVID_PTINVALID_Pos 9 /*!< TPI DEVID: PTINVALID Position */ #define TPI_DEVID_PTINVALID_Msk (0x1UL << TPI_DEVID_PTINVALID_Pos) /*!< TPI DEVID: PTINVALID Mask */ #define TPI_DEVID_MinBufSz_Pos 6 /*!< TPI DEVID: MinBufSz Position */ #define TPI_DEVID_MinBufSz_Msk (0x7UL << TPI_DEVID_MinBufSz_Pos) /*!< TPI DEVID: MinBufSz Mask */ #define TPI_DEVID_AsynClkIn_Pos 5 /*!< TPI DEVID: AsynClkIn Position */ #define TPI_DEVID_AsynClkIn_Msk (0x1UL << TPI_DEVID_AsynClkIn_Pos) /*!< TPI DEVID: AsynClkIn Mask */ #define TPI_DEVID_NrTraceInput_Pos 0 /*!< TPI DEVID: NrTraceInput Position */ #define TPI_DEVID_NrTraceInput_Msk (0x1FUL << TPI_DEVID_NrTraceInput_Pos) /*!< TPI DEVID: NrTraceInput Mask */ /* TPI DEVTYPE Register Definitions */ #define TPI_DEVTYPE_SubType_Pos 0 /*!< TPI DEVTYPE: SubType Position */ #define TPI_DEVTYPE_SubType_Msk (0xFUL << TPI_DEVTYPE_SubType_Pos) /*!< TPI DEVTYPE: SubType Mask */ #define TPI_DEVTYPE_MajorType_Pos 4 /*!< TPI DEVTYPE: MajorType Position */ #define TPI_DEVTYPE_MajorType_Msk (0xFUL << TPI_DEVTYPE_MajorType_Pos) /*!< TPI DEVTYPE: MajorType Mask */ /*@}*/ /* end of group CMSIS_TPI */ #if (__MPU_PRESENT == 1) /** \ingroup CMSIS_core_register \defgroup CMSIS_MPU Memory Protection Unit (MPU) \brief Type definitions for the Memory Protection Unit (MPU) @{ */ /** \brief Structure type to access the Memory Protection Unit (MPU). */ typedef struct { __I uint32_t TYPE; /*!< Offset: 0x000 (R/ ) MPU Type Register */ __IO uint32_t CTRL; /*!< Offset: 0x004 (R/W) MPU Control Register */ __IO uint32_t RNR; /*!< Offset: 0x008 (R/W) MPU Region RNRber Register */ __IO uint32_t RBAR; /*!< Offset: 0x00C (R/W) MPU Region Base Address Register */ __IO uint32_t RASR; /*!< Offset: 0x010 (R/W) MPU Region Attribute and Size Register */ __IO uint32_t RBAR_A1; /*!< Offset: 0x014 (R/W) MPU Alias 1 Region Base Address Register */ __IO uint32_t RASR_A1; /*!< Offset: 0x018 (R/W) MPU Alias 1 Region Attribute and Size Register */ __IO uint32_t RBAR_A2; /*!< Offset: 0x01C (R/W) MPU Alias 2 Region Base Address Register */ __IO uint32_t RASR_A2; /*!< Offset: 0x020 (R/W) MPU Alias 2 Region Attribute and Size Register */ __IO uint32_t RBAR_A3; /*!< Offset: 0x024 (R/W) MPU Alias 3 Region Base Address Register */ __IO uint32_t RASR_A3; /*!< Offset: 0x028 (R/W) MPU Alias 3 Region Attribute and Size Register */ } MPU_Type; /* MPU Type Register */ #define MPU_TYPE_IREGION_Pos 16 /*!< MPU TYPE: IREGION Position */ #define MPU_TYPE_IREGION_Msk (0xFFUL << MPU_TYPE_IREGION_Pos) /*!< MPU TYPE: IREGION Mask */ #define MPU_TYPE_DREGION_Pos 8 /*!< MPU TYPE: DREGION Position */ #define MPU_TYPE_DREGION_Msk (0xFFUL << MPU_TYPE_DREGION_Pos) /*!< MPU TYPE: DREGION Mask */ #define MPU_TYPE_SEPARATE_Pos 0 /*!< MPU TYPE: SEPARATE Position */ #define MPU_TYPE_SEPARATE_Msk (1UL << MPU_TYPE_SEPARATE_Pos) /*!< MPU TYPE: SEPARATE Mask */ /* MPU Control Register */ #define MPU_CTRL_PRIVDEFENA_Pos 2 /*!< MPU CTRL: PRIVDEFENA Position */ #define MPU_CTRL_PRIVDEFENA_Msk (1UL << MPU_CTRL_PRIVDEFENA_Pos) /*!< MPU CTRL: PRIVDEFENA Mask */ #define MPU_CTRL_HFNMIENA_Pos 1 /*!< MPU CTRL: HFNMIENA Position */ #define MPU_CTRL_HFNMIENA_Msk (1UL << MPU_CTRL_HFNMIENA_Pos) /*!< MPU CTRL: HFNMIENA Mask */ #define MPU_CTRL_ENABLE_Pos 0 /*!< MPU CTRL: ENABLE Position */ #define MPU_CTRL_ENABLE_Msk (1UL << MPU_CTRL_ENABLE_Pos) /*!< MPU CTRL: ENABLE Mask */ /* MPU Region Number Register */ #define MPU_RNR_REGION_Pos 0 /*!< MPU RNR: REGION Position */ #define MPU_RNR_REGION_Msk (0xFFUL << MPU_RNR_REGION_Pos) /*!< MPU RNR: REGION Mask */ /* MPU Region Base Address Register */ #define MPU_RBAR_ADDR_Pos 5 /*!< MPU RBAR: ADDR Position */ #define MPU_RBAR_ADDR_Msk (0x7FFFFFFUL << MPU_RBAR_ADDR_Pos) /*!< MPU RBAR: ADDR Mask */ #define MPU_RBAR_VALID_Pos 4 /*!< MPU RBAR: VALID Position */ #define MPU_RBAR_VALID_Msk (1UL << MPU_RBAR_VALID_Pos) /*!< MPU RBAR: VALID Mask */ #define MPU_RBAR_REGION_Pos 0 /*!< MPU RBAR: REGION Position */ #define MPU_RBAR_REGION_Msk (0xFUL << MPU_RBAR_REGION_Pos) /*!< MPU RBAR: REGION Mask */ /* MPU Region Attribute and Size Register */ #define MPU_RASR_ATTRS_Pos 16 /*!< MPU RASR: MPU Region Attribute field Position */ #define MPU_RASR_ATTRS_Msk (0xFFFFUL << MPU_RASR_ATTRS_Pos) /*!< MPU RASR: MPU Region Attribute field Mask */ #define MPU_RASR_XN_Pos 28 /*!< MPU RASR: ATTRS.XN Position */ #define MPU_RASR_XN_Msk (1UL << MPU_RASR_XN_Pos) /*!< MPU RASR: ATTRS.XN Mask */ #define MPU_RASR_AP_Pos 24 /*!< MPU RASR: ATTRS.AP Position */ #define MPU_RASR_AP_Msk (0x7UL << MPU_RASR_AP_Pos) /*!< MPU RASR: ATTRS.AP Mask */ #define MPU_RASR_TEX_Pos 19 /*!< MPU RASR: ATTRS.TEX Position */ #define MPU_RASR_TEX_Msk (0x7UL << MPU_RASR_TEX_Pos) /*!< MPU RASR: ATTRS.TEX Mask */ #define MPU_RASR_S_Pos 18 /*!< MPU RASR: ATTRS.S Position */ #define MPU_RASR_S_Msk (1UL << MPU_RASR_S_Pos) /*!< MPU RASR: ATTRS.S Mask */ #define MPU_RASR_C_Pos 17 /*!< MPU RASR: ATTRS.C Position */ #define MPU_RASR_C_Msk (1UL << MPU_RASR_C_Pos) /*!< MPU RASR: ATTRS.C Mask */ #define MPU_RASR_B_Pos 16 /*!< MPU RASR: ATTRS.B Position */ #define MPU_RASR_B_Msk (1UL << MPU_RASR_B_Pos) /*!< MPU RASR: ATTRS.B Mask */ #define MPU_RASR_SRD_Pos 8 /*!< MPU RASR: Sub-Region Disable Position */ #define MPU_RASR_SRD_Msk (0xFFUL << MPU_RASR_SRD_Pos) /*!< MPU RASR: Sub-Region Disable Mask */ #define MPU_RASR_SIZE_Pos 1 /*!< MPU RASR: Region Size Field Position */ #define MPU_RASR_SIZE_Msk (0x1FUL << MPU_RASR_SIZE_Pos) /*!< MPU RASR: Region Size Field Mask */ #define MPU_RASR_ENABLE_Pos 0 /*!< MPU RASR: Region enable bit Position */ #define MPU_RASR_ENABLE_Msk (1UL << MPU_RASR_ENABLE_Pos) /*!< MPU RASR: Region enable bit Disable Mask */ /*@} end of group CMSIS_MPU */ #endif /** \ingroup CMSIS_core_register \defgroup CMSIS_CoreDebug Core Debug Registers (CoreDebug) \brief Type definitions for the Core Debug Registers @{ */ /** \brief Structure type to access the Core Debug Register (CoreDebug). */ typedef struct { __IO uint32_t DHCSR; /*!< Offset: 0x000 (R/W) Debug Halting Control and Status Register */ __O uint32_t DCRSR; /*!< Offset: 0x004 ( /W) Debug Core Register Selector Register */ __IO uint32_t DCRDR; /*!< Offset: 0x008 (R/W) Debug Core Register Data Register */ __IO uint32_t DEMCR; /*!< Offset: 0x00C (R/W) Debug Exception and Monitor Control Register */ } CoreDebug_Type; /* Debug Halting Control and Status Register */ #define CoreDebug_DHCSR_DBGKEY_Pos 16 /*!< CoreDebug DHCSR: DBGKEY Position */ #define CoreDebug_DHCSR_DBGKEY_Msk (0xFFFFUL << CoreDebug_DHCSR_DBGKEY_Pos) /*!< CoreDebug DHCSR: DBGKEY Mask */ #define CoreDebug_DHCSR_S_RESET_ST_Pos 25 /*!< CoreDebug DHCSR: S_RESET_ST Position */ #define CoreDebug_DHCSR_S_RESET_ST_Msk (1UL << CoreDebug_DHCSR_S_RESET_ST_Pos) /*!< CoreDebug DHCSR: S_RESET_ST Mask */ #define CoreDebug_DHCSR_S_RETIRE_ST_Pos 24 /*!< CoreDebug DHCSR: S_RETIRE_ST Position */ #define CoreDebug_DHCSR_S_RETIRE_ST_Msk (1UL << CoreDebug_DHCSR_S_RETIRE_ST_Pos) /*!< CoreDebug DHCSR: S_RETIRE_ST Mask */ #define CoreDebug_DHCSR_S_LOCKUP_Pos 19 /*!< CoreDebug DHCSR: S_LOCKUP Position */ #define CoreDebug_DHCSR_S_LOCKUP_Msk (1UL << CoreDebug_DHCSR_S_LOCKUP_Pos) /*!< CoreDebug DHCSR: S_LOCKUP Mask */ #define CoreDebug_DHCSR_S_SLEEP_Pos 18 /*!< CoreDebug DHCSR: S_SLEEP Position */ #define CoreDebug_DHCSR_S_SLEEP_Msk (1UL << CoreDebug_DHCSR_S_SLEEP_Pos) /*!< CoreDebug DHCSR: S_SLEEP Mask */ #define CoreDebug_DHCSR_S_HALT_Pos 17 /*!< CoreDebug DHCSR: S_HALT Position */ #define CoreDebug_DHCSR_S_HALT_Msk (1UL << CoreDebug_DHCSR_S_HALT_Pos) /*!< CoreDebug DHCSR: S_HALT Mask */ #define CoreDebug_DHCSR_S_REGRDY_Pos 16 /*!< CoreDebug DHCSR: S_REGRDY Position */ #define CoreDebug_DHCSR_S_REGRDY_Msk (1UL << CoreDebug_DHCSR_S_REGRDY_Pos) /*!< CoreDebug DHCSR: S_REGRDY Mask */ #define CoreDebug_DHCSR_C_SNAPSTALL_Pos 5 /*!< CoreDebug DHCSR: C_SNAPSTALL Position */ #define CoreDebug_DHCSR_C_SNAPSTALL_Msk (1UL << CoreDebug_DHCSR_C_SNAPSTALL_Pos) /*!< CoreDebug DHCSR: C_SNAPSTALL Mask */ #define CoreDebug_DHCSR_C_MASKINTS_Pos 3 /*!< CoreDebug DHCSR: C_MASKINTS Position */ #define CoreDebug_DHCSR_C_MASKINTS_Msk (1UL << CoreDebug_DHCSR_C_MASKINTS_Pos) /*!< CoreDebug DHCSR: C_MASKINTS Mask */ #define CoreDebug_DHCSR_C_STEP_Pos 2 /*!< CoreDebug DHCSR: C_STEP Position */ #define CoreDebug_DHCSR_C_STEP_Msk (1UL << CoreDebug_DHCSR_C_STEP_Pos) /*!< CoreDebug DHCSR: C_STEP Mask */ #define CoreDebug_DHCSR_C_HALT_Pos 1 /*!< CoreDebug DHCSR: C_HALT Position */ #define CoreDebug_DHCSR_C_HALT_Msk (1UL << CoreDebug_DHCSR_C_HALT_Pos) /*!< CoreDebug DHCSR: C_HALT Mask */ #define CoreDebug_DHCSR_C_DEBUGEN_Pos 0 /*!< CoreDebug DHCSR: C_DEBUGEN Position */ #define CoreDebug_DHCSR_C_DEBUGEN_Msk (1UL << CoreDebug_DHCSR_C_DEBUGEN_Pos) /*!< CoreDebug DHCSR: C_DEBUGEN Mask */ /* Debug Core Register Selector Register */ #define CoreDebug_DCRSR_REGWnR_Pos 16 /*!< CoreDebug DCRSR: REGWnR Position */ #define CoreDebug_DCRSR_REGWnR_Msk (1UL << CoreDebug_DCRSR_REGWnR_Pos) /*!< CoreDebug DCRSR: REGWnR Mask */ #define CoreDebug_DCRSR_REGSEL_Pos 0 /*!< CoreDebug DCRSR: REGSEL Position */ #define CoreDebug_DCRSR_REGSEL_Msk (0x1FUL << CoreDebug_DCRSR_REGSEL_Pos) /*!< CoreDebug DCRSR: REGSEL Mask */ /* Debug Exception and Monitor Control Register */ #define CoreDebug_DEMCR_TRCENA_Pos 24 /*!< CoreDebug DEMCR: TRCENA Position */ #define CoreDebug_DEMCR_TRCENA_Msk (1UL << CoreDebug_DEMCR_TRCENA_Pos) /*!< CoreDebug DEMCR: TRCENA Mask */ #define CoreDebug_DEMCR_MON_REQ_Pos 19 /*!< CoreDebug DEMCR: MON_REQ Position */ #define CoreDebug_DEMCR_MON_REQ_Msk (1UL << CoreDebug_DEMCR_MON_REQ_Pos) /*!< CoreDebug DEMCR: MON_REQ Mask */ #define CoreDebug_DEMCR_MON_STEP_Pos 18 /*!< CoreDebug DEMCR: MON_STEP Position */ #define CoreDebug_DEMCR_MON_STEP_Msk (1UL << CoreDebug_DEMCR_MON_STEP_Pos) /*!< CoreDebug DEMCR: MON_STEP Mask */ #define CoreDebug_DEMCR_MON_PEND_Pos 17 /*!< CoreDebug DEMCR: MON_PEND Position */ #define CoreDebug_DEMCR_MON_PEND_Msk (1UL << CoreDebug_DEMCR_MON_PEND_Pos) /*!< CoreDebug DEMCR: MON_PEND Mask */ #define CoreDebug_DEMCR_MON_EN_Pos 16 /*!< CoreDebug DEMCR: MON_EN Position */ #define CoreDebug_DEMCR_MON_EN_Msk (1UL << CoreDebug_DEMCR_MON_EN_Pos) /*!< CoreDebug DEMCR: MON_EN Mask */ #define CoreDebug_DEMCR_VC_HARDERR_Pos 10 /*!< CoreDebug DEMCR: VC_HARDERR Position */ #define CoreDebug_DEMCR_VC_HARDERR_Msk (1UL << CoreDebug_DEMCR_VC_HARDERR_Pos) /*!< CoreDebug DEMCR: VC_HARDERR Mask */ #define CoreDebug_DEMCR_VC_INTERR_Pos 9 /*!< CoreDebug DEMCR: VC_INTERR Position */ #define CoreDebug_DEMCR_VC_INTERR_Msk (1UL << CoreDebug_DEMCR_VC_INTERR_Pos) /*!< CoreDebug DEMCR: VC_INTERR Mask */ #define CoreDebug_DEMCR_VC_BUSERR_Pos 8 /*!< CoreDebug DEMCR: VC_BUSERR Position */ #define CoreDebug_DEMCR_VC_BUSERR_Msk (1UL << CoreDebug_DEMCR_VC_BUSERR_Pos) /*!< CoreDebug DEMCR: VC_BUSERR Mask */ #define CoreDebug_DEMCR_VC_STATERR_Pos 7 /*!< CoreDebug DEMCR: VC_STATERR Position */ #define CoreDebug_DEMCR_VC_STATERR_Msk (1UL << CoreDebug_DEMCR_VC_STATERR_Pos) /*!< CoreDebug DEMCR: VC_STATERR Mask */ #define CoreDebug_DEMCR_VC_CHKERR_Pos 6 /*!< CoreDebug DEMCR: VC_CHKERR Position */ #define CoreDebug_DEMCR_VC_CHKERR_Msk (1UL << CoreDebug_DEMCR_VC_CHKERR_Pos) /*!< CoreDebug DEMCR: VC_CHKERR Mask */ #define CoreDebug_DEMCR_VC_NOCPERR_Pos 5 /*!< CoreDebug DEMCR: VC_NOCPERR Position */ #define CoreDebug_DEMCR_VC_NOCPERR_Msk (1UL << CoreDebug_DEMCR_VC_NOCPERR_Pos) /*!< CoreDebug DEMCR: VC_NOCPERR Mask */ #define CoreDebug_DEMCR_VC_MMERR_Pos 4 /*!< CoreDebug DEMCR: VC_MMERR Position */ #define CoreDebug_DEMCR_VC_MMERR_Msk (1UL << CoreDebug_DEMCR_VC_MMERR_Pos) /*!< CoreDebug DEMCR: VC_MMERR Mask */ #define CoreDebug_DEMCR_VC_CORERESET_Pos 0 /*!< CoreDebug DEMCR: VC_CORERESET Position */ #define CoreDebug_DEMCR_VC_CORERESET_Msk (1UL << CoreDebug_DEMCR_VC_CORERESET_Pos) /*!< CoreDebug DEMCR: VC_CORERESET Mask */ /*@} end of group CMSIS_CoreDebug */ /** \ingroup CMSIS_core_register \defgroup CMSIS_core_base Core Definitions \brief Definitions for base addresses, unions, and structures. @{ */ /* Memory mapping of Cortex-M3 Hardware */ #define SCS_BASE (0xE000E000UL) /*!< System Control Space Base Address */ #define ITM_BASE (0xE0000000UL) /*!< ITM Base Address */ #define DWT_BASE (0xE0001000UL) /*!< DWT Base Address */ #define TPI_BASE (0xE0040000UL) /*!< TPI Base Address */ #define CoreDebug_BASE (0xE000EDF0UL) /*!< Core Debug Base Address */ #define SysTick_BASE (SCS_BASE + 0x0010UL) /*!< SysTick Base Address */ #define NVIC_BASE (SCS_BASE + 0x0100UL) /*!< NVIC Base Address */ #define SCB_BASE (SCS_BASE + 0x0D00UL) /*!< System Control Block Base Address */ #define SCnSCB ((SCnSCB_Type *) SCS_BASE ) /*!< System control Register not in SCB */ #define SCB ((SCB_Type *) SCB_BASE ) /*!< SCB configuration struct */ #define SysTick ((SysTick_Type *) SysTick_BASE ) /*!< SysTick configuration struct */ #define NVIC ((NVIC_Type *) NVIC_BASE ) /*!< NVIC configuration struct */ #define ITM ((ITM_Type *) ITM_BASE ) /*!< ITM configuration struct */ #define DWT ((DWT_Type *) DWT_BASE ) /*!< DWT configuration struct */ #define TPI ((TPI_Type *) TPI_BASE ) /*!< TPI configuration struct */ #define CoreDebug ((CoreDebug_Type *) CoreDebug_BASE) /*!< Core Debug configuration struct */ #if (__MPU_PRESENT == 1) #define MPU_BASE (SCS_BASE + 0x0D90UL) /*!< Memory Protection Unit */ #define MPU ((MPU_Type *) MPU_BASE ) /*!< Memory Protection Unit */ #endif /*@} */ /******************************************************************************* * Hardware Abstraction Layer Core Function Interface contains: - Core NVIC Functions - Core SysTick Functions - Core Debug Functions - Core Register Access Functions ******************************************************************************/ /** \defgroup CMSIS_Core_FunctionInterface Functions and Instructions Reference */ /* ########################## NVIC functions #################################### */ /** \ingroup CMSIS_Core_FunctionInterface \defgroup CMSIS_Core_NVICFunctions NVIC Functions \brief Functions that manage interrupts and exceptions via the NVIC. @{ */ /** \brief Set Priority Grouping The function sets the priority grouping field using the required unlock sequence. The parameter PriorityGroup is assigned to the field SCB->AIRCR [10:8] PRIGROUP field. Only values from 0..7 are used. In case of a conflict between priority grouping and available priority bits (__NVIC_PRIO_BITS), the smallest possible priority group is set. \param [in] PriorityGroup Priority grouping field. */ __STATIC_INLINE void NVIC_SetPriorityGrouping(uint32_t PriorityGroup) { uint32_t reg_value; uint32_t PriorityGroupTmp = (PriorityGroup & (uint32_t)0x07); /* only values 0..7 are used */ reg_value = SCB->AIRCR; /* read old register configuration */ reg_value &= ~(SCB_AIRCR_VECTKEY_Msk | SCB_AIRCR_PRIGROUP_Msk); /* clear bits to change */ reg_value = (reg_value | ((uint32_t)0x5FA << SCB_AIRCR_VECTKEY_Pos) | (PriorityGroupTmp << 8)); /* Insert write key and priorty group */ SCB->AIRCR = reg_value; } /** \brief Get Priority Grouping The function reads the priority grouping field from the NVIC Interrupt Controller. \return Priority grouping field (SCB->AIRCR [10:8] PRIGROUP field). */ __STATIC_INLINE uint32_t NVIC_GetPriorityGrouping(void) { return ((SCB->AIRCR & SCB_AIRCR_PRIGROUP_Msk) >> SCB_AIRCR_PRIGROUP_Pos); /* read priority grouping field */ } /** \brief Enable External Interrupt The function enables a device-specific interrupt in the NVIC interrupt controller. \param [in] IRQn External interrupt number. Value cannot be negative. */ __STATIC_INLINE void NVIC_EnableIRQ(IRQn_Type IRQn) { NVIC->ISER[((uint32_t)(IRQn) >> 5)] = (1 << ((uint32_t)(IRQn) & 0x1F)); /* enable interrupt */ } /** \brief Disable External Interrupt The function disables a device-specific interrupt in the NVIC interrupt controller. \param [in] IRQn External interrupt number. Value cannot be negative. */ __STATIC_INLINE void NVIC_DisableIRQ(IRQn_Type IRQn) { NVIC->ICER[((uint32_t)(IRQn) >> 5)] = (1 << ((uint32_t)(IRQn) & 0x1F)); /* disable interrupt */ } /** \brief Get Pending Interrupt The function reads the pending register in the NVIC and returns the pending bit for the specified interrupt. \param [in] IRQn Interrupt number. \return 0 Interrupt status is not pending. \return 1 Interrupt status is pending. */ __STATIC_INLINE uint32_t NVIC_GetPendingIRQ(IRQn_Type IRQn) { return((uint32_t) ((NVIC->ISPR[(uint32_t)(IRQn) >> 5] & (1 << ((uint32_t)(IRQn) & 0x1F)))?1:0)); /* Return 1 if pending else 0 */ } /** \brief Set Pending Interrupt The function sets the pending bit of an external interrupt. \param [in] IRQn Interrupt number. Value cannot be negative. */ __STATIC_INLINE void NVIC_SetPendingIRQ(IRQn_Type IRQn) { NVIC->ISPR[((uint32_t)(IRQn) >> 5)] = (1 << ((uint32_t)(IRQn) & 0x1F)); /* set interrupt pending */ } /** \brief Clear Pending Interrupt The function clears the pending bit of an external interrupt. \param [in] IRQn External interrupt number. Value cannot be negative. */ __STATIC_INLINE void NVIC_ClearPendingIRQ(IRQn_Type IRQn) { NVIC->ICPR[((uint32_t)(IRQn) >> 5)] = (1 << ((uint32_t)(IRQn) & 0x1F)); /* Clear pending interrupt */ } /** \brief Get Active Interrupt The function reads the active register in NVIC and returns the active bit. \param [in] IRQn Interrupt number. \return 0 Interrupt status is not active. \return 1 Interrupt status is active. */ __STATIC_INLINE uint32_t NVIC_GetActive(IRQn_Type IRQn) { return((uint32_t)((NVIC->IABR[(uint32_t)(IRQn) >> 5] & (1 << ((uint32_t)(IRQn) & 0x1F)))?1:0)); /* Return 1 if active else 0 */ } /** \brief Set Interrupt Priority The function sets the priority of an interrupt. \note The priority cannot be set for every core interrupt. \param [in] IRQn Interrupt number. \param [in] priority Priority to set. */ __STATIC_INLINE void NVIC_SetPriority(IRQn_Type IRQn, uint32_t priority) { if(IRQn < 0) { SCB->SHP[((uint32_t)(IRQn) & 0xF)-4] = ((priority << (8 - __NVIC_PRIO_BITS)) & 0xff); } /* set Priority for Cortex-M System Interrupts */ else { NVIC->IP[(uint32_t)(IRQn)] = ((priority << (8 - __NVIC_PRIO_BITS)) & 0xff); } /* set Priority for device specific Interrupts */ } /** \brief Get Interrupt Priority The function reads the priority of an interrupt. The interrupt number can be positive to specify an external (device specific) interrupt, or negative to specify an internal (core) interrupt. \param [in] IRQn Interrupt number. \return Interrupt Priority. Value is aligned automatically to the implemented priority bits of the microcontroller. */ __STATIC_INLINE uint32_t NVIC_GetPriority(IRQn_Type IRQn) { if(IRQn < 0) { return((uint32_t)(SCB->SHP[((uint32_t)(IRQn) & 0xF)-4] >> (8 - __NVIC_PRIO_BITS))); } /* get priority for Cortex-M system interrupts */ else { return((uint32_t)(NVIC->IP[(uint32_t)(IRQn)] >> (8 - __NVIC_PRIO_BITS))); } /* get priority for device specific interrupts */ } /** \brief Encode Priority The function encodes the priority for an interrupt with the given priority group, preemptive priority value, and subpriority value. In case of a conflict between priority grouping and available priority bits (__NVIC_PRIO_BITS), the samllest possible priority group is set. \param [in] PriorityGroup Used priority group. \param [in] PreemptPriority Preemptive priority value (starting from 0). \param [in] SubPriority Subpriority value (starting from 0). \return Encoded priority. Value can be used in the function \ref NVIC_SetPriority(). */ __STATIC_INLINE uint32_t NVIC_EncodePriority (uint32_t PriorityGroup, uint32_t PreemptPriority, uint32_t SubPriority) { uint32_t PriorityGroupTmp = (PriorityGroup & 0x07); /* only values 0..7 are used */ uint32_t PreemptPriorityBits; uint32_t SubPriorityBits; PreemptPriorityBits = ((7 - PriorityGroupTmp) > __NVIC_PRIO_BITS) ? __NVIC_PRIO_BITS : 7 - PriorityGroupTmp; SubPriorityBits = ((PriorityGroupTmp + __NVIC_PRIO_BITS) < 7) ? 0 : PriorityGroupTmp - 7 + __NVIC_PRIO_BITS; return ( ((PreemptPriority & ((1 << (PreemptPriorityBits)) - 1)) << SubPriorityBits) | ((SubPriority & ((1 << (SubPriorityBits )) - 1))) ); } /** \brief Decode Priority The function decodes an interrupt priority value with a given priority group to preemptive priority value and subpriority value. In case of a conflict between priority grouping and available priority bits (__NVIC_PRIO_BITS) the samllest possible priority group is set. \param [in] Priority Priority value, which can be retrieved with the function \ref NVIC_GetPriority(). \param [in] PriorityGroup Used priority group. \param [out] pPreemptPriority Preemptive priority value (starting from 0). \param [out] pSubPriority Subpriority value (starting from 0). */ __STATIC_INLINE void NVIC_DecodePriority (uint32_t Priority, uint32_t PriorityGroup, uint32_t* pPreemptPriority, uint32_t* pSubPriority) { uint32_t PriorityGroupTmp = (PriorityGroup & 0x07); /* only values 0..7 are used */ uint32_t PreemptPriorityBits; uint32_t SubPriorityBits; PreemptPriorityBits = ((7 - PriorityGroupTmp) > __NVIC_PRIO_BITS) ? __NVIC_PRIO_BITS : 7 - PriorityGroupTmp; SubPriorityBits = ((PriorityGroupTmp + __NVIC_PRIO_BITS) < 7) ? 0 : PriorityGroupTmp - 7 + __NVIC_PRIO_BITS; *pPreemptPriority = (Priority >> SubPriorityBits) & ((1 << (PreemptPriorityBits)) - 1); *pSubPriority = (Priority ) & ((1 << (SubPriorityBits )) - 1); } /** \brief System Reset The function initiates a system reset request to reset the MCU. */ __STATIC_INLINE void NVIC_SystemReset(void) { __DSB(); /* Ensure all outstanding memory accesses included buffered write are completed before reset */ SCB->AIRCR = ((0x5FA << SCB_AIRCR_VECTKEY_Pos) | (SCB->AIRCR & SCB_AIRCR_PRIGROUP_Msk) | SCB_AIRCR_SYSRESETREQ_Msk); /* Keep priority group unchanged */ __DSB(); /* Ensure completion of memory access */ while(1); /* wait until reset */ } /*@} end of CMSIS_Core_NVICFunctions */ /* ################################## SysTick function ############################################ */ /** \ingroup CMSIS_Core_FunctionInterface \defgroup CMSIS_Core_SysTickFunctions SysTick Functions \brief Functions that configure the System. @{ */ #if (__Vendor_SysTickConfig == 0) /** \brief System Tick Configuration The function initializes the System Timer and its interrupt, and starts the System Tick Timer. Counter is in free running mode to generate periodic interrupts. \param [in] ticks Number of ticks between two interrupts. \return 0 Function succeeded. \return 1 Function failed. \note When the variable __Vendor_SysTickConfig is set to 1, then the function SysTick_Config is not included. In this case, the file device.h must contain a vendor-specific implementation of this function. */ __STATIC_INLINE uint32_t SysTick_Config(uint32_t ticks) { if ((ticks - 1) > SysTick_LOAD_RELOAD_Msk) return (1); /* Reload value impossible */ SysTick->LOAD = ticks - 1; /* set reload register */ NVIC_SetPriority (SysTick_IRQn, (1<<__NVIC_PRIO_BITS) - 1); /* set Priority for Systick Interrupt */ SysTick->VAL = 0; /* Load the SysTick Counter Value */ SysTick->CTRL = SysTick_CTRL_CLKSOURCE_Msk | SysTick_CTRL_TICKINT_Msk | SysTick_CTRL_ENABLE_Msk; /* Enable SysTick IRQ and SysTick Timer */ return (0); /* Function successful */ } #endif /*@} end of CMSIS_Core_SysTickFunctions */ /* ##################################### Debug In/Output function ########################################### */ /** \ingroup CMSIS_Core_FunctionInterface \defgroup CMSIS_core_DebugFunctions ITM Functions \brief Functions that access the ITM debug interface. @{ */ extern volatile int32_t ITM_RxBuffer; /*!< External variable to receive characters. */ #define ITM_RXBUFFER_EMPTY 0x5AA55AA5 /*!< Value identifying \ref ITM_RxBuffer is ready for next character. */ /** \brief ITM Send Character The function transmits a character via the ITM channel 0, and \li Just returns when no debugger is connected that has booked the output. \li Is blocking when a debugger is connected, but the previous character sent has not been transmitted. \param [in] ch Character to transmit. \returns Character to transmit. */ __STATIC_INLINE uint32_t ITM_SendChar (uint32_t ch) { if ((ITM->TCR & ITM_TCR_ITMENA_Msk) && /* ITM enabled */ (ITM->TER & (1UL << 0) ) ) /* ITM Port #0 enabled */ { while (ITM->PORT[0].u32 == 0); ITM->PORT[0].u8 = (uint8_t) ch; } return (ch); } /** \brief ITM Receive Character The function inputs a character via the external variable \ref ITM_RxBuffer. \return Received character. \return -1 No character pending. */ __STATIC_INLINE int32_t ITM_ReceiveChar (void) { int32_t ch = -1; /* no character available */ if (ITM_RxBuffer != ITM_RXBUFFER_EMPTY) { ch = ITM_RxBuffer; ITM_RxBuffer = ITM_RXBUFFER_EMPTY; /* ready for next character */ } return (ch); } /** \brief ITM Check Character The function checks whether a character is pending for reading in the variable \ref ITM_RxBuffer. \return 0 No character available. \return 1 Character available. */ __STATIC_INLINE int32_t ITM_CheckChar (void) { if (ITM_RxBuffer == ITM_RXBUFFER_EMPTY) { return (0); /* no character available */ } else { return (1); /* character available */ } } /*@} end of CMSIS_core_DebugFunctions */ #endif /* __CORE_CM3_H_DEPENDANT */ #endif /* __CMSIS_GENERIC */ #ifdef __cplusplus } #endif ================================================ FILE: Zelig/mbed/TARGET_LPC1768/core_cm4.h ================================================ /**************************************************************************//** * @file core_cm4.h * @brief CMSIS Cortex-M4 Core Peripheral Access Layer Header File * @version V3.20 * @date 25. February 2013 * * @note * ******************************************************************************/ /* Copyright (c) 2009 - 2013 ARM LIMITED All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: - Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. - Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. - Neither the name of ARM 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 COPYRIGHT HOLDERS AND 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. ---------------------------------------------------------------------------*/ #if defined ( __ICCARM__ ) #pragma system_include /* treat file as system include file for MISRA check */ #endif #ifdef __cplusplus extern "C" { #endif #ifndef __CORE_CM4_H_GENERIC #define __CORE_CM4_H_GENERIC /** \page CMSIS_MISRA_Exceptions MISRA-C:2004 Compliance Exceptions CMSIS violates the following MISRA-C:2004 rules: \li Required Rule 8.5, object/function definition in header file.
Function definitions in header files are used to allow 'inlining'. \li Required Rule 18.4, declaration of union type or object of union type: '{...}'.
Unions are used for effective representation of core registers. \li Advisory Rule 19.7, Function-like macro defined.
Function-like macros are used to allow more efficient code. */ /******************************************************************************* * CMSIS definitions ******************************************************************************/ /** \ingroup Cortex_M4 @{ */ /* CMSIS CM4 definitions */ #define __CM4_CMSIS_VERSION_MAIN (0x03) /*!< [31:16] CMSIS HAL main version */ #define __CM4_CMSIS_VERSION_SUB (0x20) /*!< [15:0] CMSIS HAL sub version */ #define __CM4_CMSIS_VERSION ((__CM4_CMSIS_VERSION_MAIN << 16) | \ __CM4_CMSIS_VERSION_SUB ) /*!< CMSIS HAL version number */ #define __CORTEX_M (0x04) /*!< Cortex-M Core */ #if defined ( __CC_ARM ) #define __ASM __asm /*!< asm keyword for ARM Compiler */ #define __INLINE __inline /*!< inline keyword for ARM Compiler */ #define __STATIC_INLINE static __inline #elif defined ( __ICCARM__ ) #define __ASM __asm /*!< asm keyword for IAR Compiler */ #define __INLINE inline /*!< inline keyword for IAR Compiler. Only available in High optimization mode! */ #define __STATIC_INLINE static inline #elif defined ( __TMS470__ ) #define __ASM __asm /*!< asm keyword for TI CCS Compiler */ #define __STATIC_INLINE static inline #elif defined ( __GNUC__ ) #define __ASM __asm /*!< asm keyword for GNU Compiler */ #define __INLINE inline /*!< inline keyword for GNU Compiler */ #define __STATIC_INLINE static inline #elif defined ( __TASKING__ ) #define __ASM __asm /*!< asm keyword for TASKING Compiler */ #define __INLINE inline /*!< inline keyword for TASKING Compiler */ #define __STATIC_INLINE static inline #endif /** __FPU_USED indicates whether an FPU is used or not. For this, __FPU_PRESENT has to be checked prior to making use of FPU specific registers and functions. */ #if defined ( __CC_ARM ) #if defined __TARGET_FPU_VFP #if (__FPU_PRESENT == 1) #define __FPU_USED 1 #else #warning "Compiler generates FPU instructions for a device without an FPU (check __FPU_PRESENT)" #define __FPU_USED 0 #endif #else #define __FPU_USED 0 #endif #elif defined ( __ICCARM__ ) #if defined __ARMVFP__ #if (__FPU_PRESENT == 1) #define __FPU_USED 1 #else #warning "Compiler generates FPU instructions for a device without an FPU (check __FPU_PRESENT)" #define __FPU_USED 0 #endif #else #define __FPU_USED 0 #endif #elif defined ( __TMS470__ ) #if defined __TI_VFP_SUPPORT__ #if (__FPU_PRESENT == 1) #define __FPU_USED 1 #else #warning "Compiler generates FPU instructions for a device without an FPU (check __FPU_PRESENT)" #define __FPU_USED 0 #endif #else #define __FPU_USED 0 #endif #elif defined ( __GNUC__ ) #if defined (__VFP_FP__) && !defined(__SOFTFP__) #if (__FPU_PRESENT == 1) #define __FPU_USED 1 #else #warning "Compiler generates FPU instructions for a device without an FPU (check __FPU_PRESENT)" #define __FPU_USED 0 #endif #else #define __FPU_USED 0 #endif #elif defined ( __TASKING__ ) #if defined __FPU_VFP__ #if (__FPU_PRESENT == 1) #define __FPU_USED 1 #else #error "Compiler generates FPU instructions for a device without an FPU (check __FPU_PRESENT)" #define __FPU_USED 0 #endif #else #define __FPU_USED 0 #endif #endif #include /* standard types definitions */ #include /* Core Instruction Access */ #include /* Core Function Access */ #include /* Compiler specific SIMD Intrinsics */ #endif /* __CORE_CM4_H_GENERIC */ #ifndef __CMSIS_GENERIC #ifndef __CORE_CM4_H_DEPENDANT #define __CORE_CM4_H_DEPENDANT /* check device defines and use defaults */ #if defined __CHECK_DEVICE_DEFINES #ifndef __CM4_REV #define __CM4_REV 0x0000 #warning "__CM4_REV not defined in device header file; using default!" #endif #ifndef __FPU_PRESENT #define __FPU_PRESENT 0 #warning "__FPU_PRESENT not defined in device header file; using default!" #endif #ifndef __MPU_PRESENT #define __MPU_PRESENT 0 #warning "__MPU_PRESENT not defined in device header file; using default!" #endif #ifndef __NVIC_PRIO_BITS #define __NVIC_PRIO_BITS 4 #warning "__NVIC_PRIO_BITS not defined in device header file; using default!" #endif #ifndef __Vendor_SysTickConfig #define __Vendor_SysTickConfig 0 #warning "__Vendor_SysTickConfig not defined in device header file; using default!" #endif #endif /* IO definitions (access restrictions to peripheral registers) */ /** \defgroup CMSIS_glob_defs CMSIS Global Defines IO Type Qualifiers are used \li to specify the access to peripheral variables. \li for automatic generation of peripheral register debug information. */ #ifdef __cplusplus #define __I volatile /*!< Defines 'read only' permissions */ #else #define __I volatile const /*!< Defines 'read only' permissions */ #endif #define __O volatile /*!< Defines 'write only' permissions */ #define __IO volatile /*!< Defines 'read / write' permissions */ /*@} end of group Cortex_M4 */ /******************************************************************************* * Register Abstraction Core Register contain: - Core Register - Core NVIC Register - Core SCB Register - Core SysTick Register - Core Debug Register - Core MPU Register - Core FPU Register ******************************************************************************/ /** \defgroup CMSIS_core_register Defines and Type Definitions \brief Type definitions and defines for Cortex-M processor based devices. */ /** \ingroup CMSIS_core_register \defgroup CMSIS_CORE Status and Control Registers \brief Core Register type definitions. @{ */ /** \brief Union type to access the Application Program Status Register (APSR). */ typedef union { struct { #if (__CORTEX_M != 0x04) uint32_t _reserved0:27; /*!< bit: 0..26 Reserved */ #else uint32_t _reserved0:16; /*!< bit: 0..15 Reserved */ uint32_t GE:4; /*!< bit: 16..19 Greater than or Equal flags */ uint32_t _reserved1:7; /*!< bit: 20..26 Reserved */ #endif uint32_t Q:1; /*!< bit: 27 Saturation condition flag */ uint32_t V:1; /*!< bit: 28 Overflow condition code flag */ uint32_t C:1; /*!< bit: 29 Carry condition code flag */ uint32_t Z:1; /*!< bit: 30 Zero condition code flag */ uint32_t N:1; /*!< bit: 31 Negative condition code flag */ } b; /*!< Structure used for bit access */ uint32_t w; /*!< Type used for word access */ } APSR_Type; /** \brief Union type to access the Interrupt Program Status Register (IPSR). */ typedef union { struct { uint32_t ISR:9; /*!< bit: 0.. 8 Exception number */ uint32_t _reserved0:23; /*!< bit: 9..31 Reserved */ } b; /*!< Structure used for bit access */ uint32_t w; /*!< Type used for word access */ } IPSR_Type; /** \brief Union type to access the Special-Purpose Program Status Registers (xPSR). */ typedef union { struct { uint32_t ISR:9; /*!< bit: 0.. 8 Exception number */ #if (__CORTEX_M != 0x04) uint32_t _reserved0:15; /*!< bit: 9..23 Reserved */ #else uint32_t _reserved0:7; /*!< bit: 9..15 Reserved */ uint32_t GE:4; /*!< bit: 16..19 Greater than or Equal flags */ uint32_t _reserved1:4; /*!< bit: 20..23 Reserved */ #endif uint32_t T:1; /*!< bit: 24 Thumb bit (read 0) */ uint32_t IT:2; /*!< bit: 25..26 saved IT state (read 0) */ uint32_t Q:1; /*!< bit: 27 Saturation condition flag */ uint32_t V:1; /*!< bit: 28 Overflow condition code flag */ uint32_t C:1; /*!< bit: 29 Carry condition code flag */ uint32_t Z:1; /*!< bit: 30 Zero condition code flag */ uint32_t N:1; /*!< bit: 31 Negative condition code flag */ } b; /*!< Structure used for bit access */ uint32_t w; /*!< Type used for word access */ } xPSR_Type; /** \brief Union type to access the Control Registers (CONTROL). */ typedef union { struct { uint32_t nPRIV:1; /*!< bit: 0 Execution privilege in Thread mode */ uint32_t SPSEL:1; /*!< bit: 1 Stack to be used */ uint32_t FPCA:1; /*!< bit: 2 FP extension active flag */ uint32_t _reserved0:29; /*!< bit: 3..31 Reserved */ } b; /*!< Structure used for bit access */ uint32_t w; /*!< Type used for word access */ } CONTROL_Type; /*@} end of group CMSIS_CORE */ /** \ingroup CMSIS_core_register \defgroup CMSIS_NVIC Nested Vectored Interrupt Controller (NVIC) \brief Type definitions for the NVIC Registers @{ */ /** \brief Structure type to access the Nested Vectored Interrupt Controller (NVIC). */ typedef struct { __IO uint32_t ISER[8]; /*!< Offset: 0x000 (R/W) Interrupt Set Enable Register */ uint32_t RESERVED0[24]; __IO uint32_t ICER[8]; /*!< Offset: 0x080 (R/W) Interrupt Clear Enable Register */ uint32_t RSERVED1[24]; __IO uint32_t ISPR[8]; /*!< Offset: 0x100 (R/W) Interrupt Set Pending Register */ uint32_t RESERVED2[24]; __IO uint32_t ICPR[8]; /*!< Offset: 0x180 (R/W) Interrupt Clear Pending Register */ uint32_t RESERVED3[24]; __IO uint32_t IABR[8]; /*!< Offset: 0x200 (R/W) Interrupt Active bit Register */ uint32_t RESERVED4[56]; __IO uint8_t IP[240]; /*!< Offset: 0x300 (R/W) Interrupt Priority Register (8Bit wide) */ uint32_t RESERVED5[644]; __O uint32_t STIR; /*!< Offset: 0xE00 ( /W) Software Trigger Interrupt Register */ } NVIC_Type; /* Software Triggered Interrupt Register Definitions */ #define NVIC_STIR_INTID_Pos 0 /*!< STIR: INTLINESNUM Position */ #define NVIC_STIR_INTID_Msk (0x1FFUL << NVIC_STIR_INTID_Pos) /*!< STIR: INTLINESNUM Mask */ /*@} end of group CMSIS_NVIC */ /** \ingroup CMSIS_core_register \defgroup CMSIS_SCB System Control Block (SCB) \brief Type definitions for the System Control Block Registers @{ */ /** \brief Structure type to access the System Control Block (SCB). */ typedef struct { __I uint32_t CPUID; /*!< Offset: 0x000 (R/ ) CPUID Base Register */ __IO uint32_t ICSR; /*!< Offset: 0x004 (R/W) Interrupt Control and State Register */ __IO uint32_t VTOR; /*!< Offset: 0x008 (R/W) Vector Table Offset Register */ __IO uint32_t AIRCR; /*!< Offset: 0x00C (R/W) Application Interrupt and Reset Control Register */ __IO uint32_t SCR; /*!< Offset: 0x010 (R/W) System Control Register */ __IO uint32_t CCR; /*!< Offset: 0x014 (R/W) Configuration Control Register */ __IO uint8_t SHP[12]; /*!< Offset: 0x018 (R/W) System Handlers Priority Registers (4-7, 8-11, 12-15) */ __IO uint32_t SHCSR; /*!< Offset: 0x024 (R/W) System Handler Control and State Register */ __IO uint32_t CFSR; /*!< Offset: 0x028 (R/W) Configurable Fault Status Register */ __IO uint32_t HFSR; /*!< Offset: 0x02C (R/W) HardFault Status Register */ __IO uint32_t DFSR; /*!< Offset: 0x030 (R/W) Debug Fault Status Register */ __IO uint32_t MMFAR; /*!< Offset: 0x034 (R/W) MemManage Fault Address Register */ __IO uint32_t BFAR; /*!< Offset: 0x038 (R/W) BusFault Address Register */ __IO uint32_t AFSR; /*!< Offset: 0x03C (R/W) Auxiliary Fault Status Register */ __I uint32_t PFR[2]; /*!< Offset: 0x040 (R/ ) Processor Feature Register */ __I uint32_t DFR; /*!< Offset: 0x048 (R/ ) Debug Feature Register */ __I uint32_t ADR; /*!< Offset: 0x04C (R/ ) Auxiliary Feature Register */ __I uint32_t MMFR[4]; /*!< Offset: 0x050 (R/ ) Memory Model Feature Register */ __I uint32_t ISAR[5]; /*!< Offset: 0x060 (R/ ) Instruction Set Attributes Register */ uint32_t RESERVED0[5]; __IO uint32_t CPACR; /*!< Offset: 0x088 (R/W) Coprocessor Access Control Register */ } SCB_Type; /* SCB CPUID Register Definitions */ #define SCB_CPUID_IMPLEMENTER_Pos 24 /*!< SCB CPUID: IMPLEMENTER Position */ #define SCB_CPUID_IMPLEMENTER_Msk (0xFFUL << SCB_CPUID_IMPLEMENTER_Pos) /*!< SCB CPUID: IMPLEMENTER Mask */ #define SCB_CPUID_VARIANT_Pos 20 /*!< SCB CPUID: VARIANT Position */ #define SCB_CPUID_VARIANT_Msk (0xFUL << SCB_CPUID_VARIANT_Pos) /*!< SCB CPUID: VARIANT Mask */ #define SCB_CPUID_ARCHITECTURE_Pos 16 /*!< SCB CPUID: ARCHITECTURE Position */ #define SCB_CPUID_ARCHITECTURE_Msk (0xFUL << SCB_CPUID_ARCHITECTURE_Pos) /*!< SCB CPUID: ARCHITECTURE Mask */ #define SCB_CPUID_PARTNO_Pos 4 /*!< SCB CPUID: PARTNO Position */ #define SCB_CPUID_PARTNO_Msk (0xFFFUL << SCB_CPUID_PARTNO_Pos) /*!< SCB CPUID: PARTNO Mask */ #define SCB_CPUID_REVISION_Pos 0 /*!< SCB CPUID: REVISION Position */ #define SCB_CPUID_REVISION_Msk (0xFUL << SCB_CPUID_REVISION_Pos) /*!< SCB CPUID: REVISION Mask */ /* SCB Interrupt Control State Register Definitions */ #define SCB_ICSR_NMIPENDSET_Pos 31 /*!< SCB ICSR: NMIPENDSET Position */ #define SCB_ICSR_NMIPENDSET_Msk (1UL << SCB_ICSR_NMIPENDSET_Pos) /*!< SCB ICSR: NMIPENDSET Mask */ #define SCB_ICSR_PENDSVSET_Pos 28 /*!< SCB ICSR: PENDSVSET Position */ #define SCB_ICSR_PENDSVSET_Msk (1UL << SCB_ICSR_PENDSVSET_Pos) /*!< SCB ICSR: PENDSVSET Mask */ #define SCB_ICSR_PENDSVCLR_Pos 27 /*!< SCB ICSR: PENDSVCLR Position */ #define SCB_ICSR_PENDSVCLR_Msk (1UL << SCB_ICSR_PENDSVCLR_Pos) /*!< SCB ICSR: PENDSVCLR Mask */ #define SCB_ICSR_PENDSTSET_Pos 26 /*!< SCB ICSR: PENDSTSET Position */ #define SCB_ICSR_PENDSTSET_Msk (1UL << SCB_ICSR_PENDSTSET_Pos) /*!< SCB ICSR: PENDSTSET Mask */ #define SCB_ICSR_PENDSTCLR_Pos 25 /*!< SCB ICSR: PENDSTCLR Position */ #define SCB_ICSR_PENDSTCLR_Msk (1UL << SCB_ICSR_PENDSTCLR_Pos) /*!< SCB ICSR: PENDSTCLR Mask */ #define SCB_ICSR_ISRPREEMPT_Pos 23 /*!< SCB ICSR: ISRPREEMPT Position */ #define SCB_ICSR_ISRPREEMPT_Msk (1UL << SCB_ICSR_ISRPREEMPT_Pos) /*!< SCB ICSR: ISRPREEMPT Mask */ #define SCB_ICSR_ISRPENDING_Pos 22 /*!< SCB ICSR: ISRPENDING Position */ #define SCB_ICSR_ISRPENDING_Msk (1UL << SCB_ICSR_ISRPENDING_Pos) /*!< SCB ICSR: ISRPENDING Mask */ #define SCB_ICSR_VECTPENDING_Pos 12 /*!< SCB ICSR: VECTPENDING Position */ #define SCB_ICSR_VECTPENDING_Msk (0x1FFUL << SCB_ICSR_VECTPENDING_Pos) /*!< SCB ICSR: VECTPENDING Mask */ #define SCB_ICSR_RETTOBASE_Pos 11 /*!< SCB ICSR: RETTOBASE Position */ #define SCB_ICSR_RETTOBASE_Msk (1UL << SCB_ICSR_RETTOBASE_Pos) /*!< SCB ICSR: RETTOBASE Mask */ #define SCB_ICSR_VECTACTIVE_Pos 0 /*!< SCB ICSR: VECTACTIVE Position */ #define SCB_ICSR_VECTACTIVE_Msk (0x1FFUL << SCB_ICSR_VECTACTIVE_Pos) /*!< SCB ICSR: VECTACTIVE Mask */ /* SCB Vector Table Offset Register Definitions */ #define SCB_VTOR_TBLOFF_Pos 7 /*!< SCB VTOR: TBLOFF Position */ #define SCB_VTOR_TBLOFF_Msk (0x1FFFFFFUL << SCB_VTOR_TBLOFF_Pos) /*!< SCB VTOR: TBLOFF Mask */ /* SCB Application Interrupt and Reset Control Register Definitions */ #define SCB_AIRCR_VECTKEY_Pos 16 /*!< SCB AIRCR: VECTKEY Position */ #define SCB_AIRCR_VECTKEY_Msk (0xFFFFUL << SCB_AIRCR_VECTKEY_Pos) /*!< SCB AIRCR: VECTKEY Mask */ #define SCB_AIRCR_VECTKEYSTAT_Pos 16 /*!< SCB AIRCR: VECTKEYSTAT Position */ #define SCB_AIRCR_VECTKEYSTAT_Msk (0xFFFFUL << SCB_AIRCR_VECTKEYSTAT_Pos) /*!< SCB AIRCR: VECTKEYSTAT Mask */ #define SCB_AIRCR_ENDIANESS_Pos 15 /*!< SCB AIRCR: ENDIANESS Position */ #define SCB_AIRCR_ENDIANESS_Msk (1UL << SCB_AIRCR_ENDIANESS_Pos) /*!< SCB AIRCR: ENDIANESS Mask */ #define SCB_AIRCR_PRIGROUP_Pos 8 /*!< SCB AIRCR: PRIGROUP Position */ #define SCB_AIRCR_PRIGROUP_Msk (7UL << SCB_AIRCR_PRIGROUP_Pos) /*!< SCB AIRCR: PRIGROUP Mask */ #define SCB_AIRCR_SYSRESETREQ_Pos 2 /*!< SCB AIRCR: SYSRESETREQ Position */ #define SCB_AIRCR_SYSRESETREQ_Msk (1UL << SCB_AIRCR_SYSRESETREQ_Pos) /*!< SCB AIRCR: SYSRESETREQ Mask */ #define SCB_AIRCR_VECTCLRACTIVE_Pos 1 /*!< SCB AIRCR: VECTCLRACTIVE Position */ #define SCB_AIRCR_VECTCLRACTIVE_Msk (1UL << SCB_AIRCR_VECTCLRACTIVE_Pos) /*!< SCB AIRCR: VECTCLRACTIVE Mask */ #define SCB_AIRCR_VECTRESET_Pos 0 /*!< SCB AIRCR: VECTRESET Position */ #define SCB_AIRCR_VECTRESET_Msk (1UL << SCB_AIRCR_VECTRESET_Pos) /*!< SCB AIRCR: VECTRESET Mask */ /* SCB System Control Register Definitions */ #define SCB_SCR_SEVONPEND_Pos 4 /*!< SCB SCR: SEVONPEND Position */ #define SCB_SCR_SEVONPEND_Msk (1UL << SCB_SCR_SEVONPEND_Pos) /*!< SCB SCR: SEVONPEND Mask */ #define SCB_SCR_SLEEPDEEP_Pos 2 /*!< SCB SCR: SLEEPDEEP Position */ #define SCB_SCR_SLEEPDEEP_Msk (1UL << SCB_SCR_SLEEPDEEP_Pos) /*!< SCB SCR: SLEEPDEEP Mask */ #define SCB_SCR_SLEEPONEXIT_Pos 1 /*!< SCB SCR: SLEEPONEXIT Position */ #define SCB_SCR_SLEEPONEXIT_Msk (1UL << SCB_SCR_SLEEPONEXIT_Pos) /*!< SCB SCR: SLEEPONEXIT Mask */ /* SCB Configuration Control Register Definitions */ #define SCB_CCR_STKALIGN_Pos 9 /*!< SCB CCR: STKALIGN Position */ #define SCB_CCR_STKALIGN_Msk (1UL << SCB_CCR_STKALIGN_Pos) /*!< SCB CCR: STKALIGN Mask */ #define SCB_CCR_BFHFNMIGN_Pos 8 /*!< SCB CCR: BFHFNMIGN Position */ #define SCB_CCR_BFHFNMIGN_Msk (1UL << SCB_CCR_BFHFNMIGN_Pos) /*!< SCB CCR: BFHFNMIGN Mask */ #define SCB_CCR_DIV_0_TRP_Pos 4 /*!< SCB CCR: DIV_0_TRP Position */ #define SCB_CCR_DIV_0_TRP_Msk (1UL << SCB_CCR_DIV_0_TRP_Pos) /*!< SCB CCR: DIV_0_TRP Mask */ #define SCB_CCR_UNALIGN_TRP_Pos 3 /*!< SCB CCR: UNALIGN_TRP Position */ #define SCB_CCR_UNALIGN_TRP_Msk (1UL << SCB_CCR_UNALIGN_TRP_Pos) /*!< SCB CCR: UNALIGN_TRP Mask */ #define SCB_CCR_USERSETMPEND_Pos 1 /*!< SCB CCR: USERSETMPEND Position */ #define SCB_CCR_USERSETMPEND_Msk (1UL << SCB_CCR_USERSETMPEND_Pos) /*!< SCB CCR: USERSETMPEND Mask */ #define SCB_CCR_NONBASETHRDENA_Pos 0 /*!< SCB CCR: NONBASETHRDENA Position */ #define SCB_CCR_NONBASETHRDENA_Msk (1UL << SCB_CCR_NONBASETHRDENA_Pos) /*!< SCB CCR: NONBASETHRDENA Mask */ /* SCB System Handler Control and State Register Definitions */ #define SCB_SHCSR_USGFAULTENA_Pos 18 /*!< SCB SHCSR: USGFAULTENA Position */ #define SCB_SHCSR_USGFAULTENA_Msk (1UL << SCB_SHCSR_USGFAULTENA_Pos) /*!< SCB SHCSR: USGFAULTENA Mask */ #define SCB_SHCSR_BUSFAULTENA_Pos 17 /*!< SCB SHCSR: BUSFAULTENA Position */ #define SCB_SHCSR_BUSFAULTENA_Msk (1UL << SCB_SHCSR_BUSFAULTENA_Pos) /*!< SCB SHCSR: BUSFAULTENA Mask */ #define SCB_SHCSR_MEMFAULTENA_Pos 16 /*!< SCB SHCSR: MEMFAULTENA Position */ #define SCB_SHCSR_MEMFAULTENA_Msk (1UL << SCB_SHCSR_MEMFAULTENA_Pos) /*!< SCB SHCSR: MEMFAULTENA Mask */ #define SCB_SHCSR_SVCALLPENDED_Pos 15 /*!< SCB SHCSR: SVCALLPENDED Position */ #define SCB_SHCSR_SVCALLPENDED_Msk (1UL << SCB_SHCSR_SVCALLPENDED_Pos) /*!< SCB SHCSR: SVCALLPENDED Mask */ #define SCB_SHCSR_BUSFAULTPENDED_Pos 14 /*!< SCB SHCSR: BUSFAULTPENDED Position */ #define SCB_SHCSR_BUSFAULTPENDED_Msk (1UL << SCB_SHCSR_BUSFAULTPENDED_Pos) /*!< SCB SHCSR: BUSFAULTPENDED Mask */ #define SCB_SHCSR_MEMFAULTPENDED_Pos 13 /*!< SCB SHCSR: MEMFAULTPENDED Position */ #define SCB_SHCSR_MEMFAULTPENDED_Msk (1UL << SCB_SHCSR_MEMFAULTPENDED_Pos) /*!< SCB SHCSR: MEMFAULTPENDED Mask */ #define SCB_SHCSR_USGFAULTPENDED_Pos 12 /*!< SCB SHCSR: USGFAULTPENDED Position */ #define SCB_SHCSR_USGFAULTPENDED_Msk (1UL << SCB_SHCSR_USGFAULTPENDED_Pos) /*!< SCB SHCSR: USGFAULTPENDED Mask */ #define SCB_SHCSR_SYSTICKACT_Pos 11 /*!< SCB SHCSR: SYSTICKACT Position */ #define SCB_SHCSR_SYSTICKACT_Msk (1UL << SCB_SHCSR_SYSTICKACT_Pos) /*!< SCB SHCSR: SYSTICKACT Mask */ #define SCB_SHCSR_PENDSVACT_Pos 10 /*!< SCB SHCSR: PENDSVACT Position */ #define SCB_SHCSR_PENDSVACT_Msk (1UL << SCB_SHCSR_PENDSVACT_Pos) /*!< SCB SHCSR: PENDSVACT Mask */ #define SCB_SHCSR_MONITORACT_Pos 8 /*!< SCB SHCSR: MONITORACT Position */ #define SCB_SHCSR_MONITORACT_Msk (1UL << SCB_SHCSR_MONITORACT_Pos) /*!< SCB SHCSR: MONITORACT Mask */ #define SCB_SHCSR_SVCALLACT_Pos 7 /*!< SCB SHCSR: SVCALLACT Position */ #define SCB_SHCSR_SVCALLACT_Msk (1UL << SCB_SHCSR_SVCALLACT_Pos) /*!< SCB SHCSR: SVCALLACT Mask */ #define SCB_SHCSR_USGFAULTACT_Pos 3 /*!< SCB SHCSR: USGFAULTACT Position */ #define SCB_SHCSR_USGFAULTACT_Msk (1UL << SCB_SHCSR_USGFAULTACT_Pos) /*!< SCB SHCSR: USGFAULTACT Mask */ #define SCB_SHCSR_BUSFAULTACT_Pos 1 /*!< SCB SHCSR: BUSFAULTACT Position */ #define SCB_SHCSR_BUSFAULTACT_Msk (1UL << SCB_SHCSR_BUSFAULTACT_Pos) /*!< SCB SHCSR: BUSFAULTACT Mask */ #define SCB_SHCSR_MEMFAULTACT_Pos 0 /*!< SCB SHCSR: MEMFAULTACT Position */ #define SCB_SHCSR_MEMFAULTACT_Msk (1UL << SCB_SHCSR_MEMFAULTACT_Pos) /*!< SCB SHCSR: MEMFAULTACT Mask */ /* SCB Configurable Fault Status Registers Definitions */ #define SCB_CFSR_USGFAULTSR_Pos 16 /*!< SCB CFSR: Usage Fault Status Register Position */ #define SCB_CFSR_USGFAULTSR_Msk (0xFFFFUL << SCB_CFSR_USGFAULTSR_Pos) /*!< SCB CFSR: Usage Fault Status Register Mask */ #define SCB_CFSR_BUSFAULTSR_Pos 8 /*!< SCB CFSR: Bus Fault Status Register Position */ #define SCB_CFSR_BUSFAULTSR_Msk (0xFFUL << SCB_CFSR_BUSFAULTSR_Pos) /*!< SCB CFSR: Bus Fault Status Register Mask */ #define SCB_CFSR_MEMFAULTSR_Pos 0 /*!< SCB CFSR: Memory Manage Fault Status Register Position */ #define SCB_CFSR_MEMFAULTSR_Msk (0xFFUL << SCB_CFSR_MEMFAULTSR_Pos) /*!< SCB CFSR: Memory Manage Fault Status Register Mask */ /* SCB Hard Fault Status Registers Definitions */ #define SCB_HFSR_DEBUGEVT_Pos 31 /*!< SCB HFSR: DEBUGEVT Position */ #define SCB_HFSR_DEBUGEVT_Msk (1UL << SCB_HFSR_DEBUGEVT_Pos) /*!< SCB HFSR: DEBUGEVT Mask */ #define SCB_HFSR_FORCED_Pos 30 /*!< SCB HFSR: FORCED Position */ #define SCB_HFSR_FORCED_Msk (1UL << SCB_HFSR_FORCED_Pos) /*!< SCB HFSR: FORCED Mask */ #define SCB_HFSR_VECTTBL_Pos 1 /*!< SCB HFSR: VECTTBL Position */ #define SCB_HFSR_VECTTBL_Msk (1UL << SCB_HFSR_VECTTBL_Pos) /*!< SCB HFSR: VECTTBL Mask */ /* SCB Debug Fault Status Register Definitions */ #define SCB_DFSR_EXTERNAL_Pos 4 /*!< SCB DFSR: EXTERNAL Position */ #define SCB_DFSR_EXTERNAL_Msk (1UL << SCB_DFSR_EXTERNAL_Pos) /*!< SCB DFSR: EXTERNAL Mask */ #define SCB_DFSR_VCATCH_Pos 3 /*!< SCB DFSR: VCATCH Position */ #define SCB_DFSR_VCATCH_Msk (1UL << SCB_DFSR_VCATCH_Pos) /*!< SCB DFSR: VCATCH Mask */ #define SCB_DFSR_DWTTRAP_Pos 2 /*!< SCB DFSR: DWTTRAP Position */ #define SCB_DFSR_DWTTRAP_Msk (1UL << SCB_DFSR_DWTTRAP_Pos) /*!< SCB DFSR: DWTTRAP Mask */ #define SCB_DFSR_BKPT_Pos 1 /*!< SCB DFSR: BKPT Position */ #define SCB_DFSR_BKPT_Msk (1UL << SCB_DFSR_BKPT_Pos) /*!< SCB DFSR: BKPT Mask */ #define SCB_DFSR_HALTED_Pos 0 /*!< SCB DFSR: HALTED Position */ #define SCB_DFSR_HALTED_Msk (1UL << SCB_DFSR_HALTED_Pos) /*!< SCB DFSR: HALTED Mask */ /*@} end of group CMSIS_SCB */ /** \ingroup CMSIS_core_register \defgroup CMSIS_SCnSCB System Controls not in SCB (SCnSCB) \brief Type definitions for the System Control and ID Register not in the SCB @{ */ /** \brief Structure type to access the System Control and ID Register not in the SCB. */ typedef struct { uint32_t RESERVED0[1]; __I uint32_t ICTR; /*!< Offset: 0x004 (R/ ) Interrupt Controller Type Register */ __IO uint32_t ACTLR; /*!< Offset: 0x008 (R/W) Auxiliary Control Register */ } SCnSCB_Type; /* Interrupt Controller Type Register Definitions */ #define SCnSCB_ICTR_INTLINESNUM_Pos 0 /*!< ICTR: INTLINESNUM Position */ #define SCnSCB_ICTR_INTLINESNUM_Msk (0xFUL << SCnSCB_ICTR_INTLINESNUM_Pos) /*!< ICTR: INTLINESNUM Mask */ /* Auxiliary Control Register Definitions */ #define SCnSCB_ACTLR_DISOOFP_Pos 9 /*!< ACTLR: DISOOFP Position */ #define SCnSCB_ACTLR_DISOOFP_Msk (1UL << SCnSCB_ACTLR_DISOOFP_Pos) /*!< ACTLR: DISOOFP Mask */ #define SCnSCB_ACTLR_DISFPCA_Pos 8 /*!< ACTLR: DISFPCA Position */ #define SCnSCB_ACTLR_DISFPCA_Msk (1UL << SCnSCB_ACTLR_DISFPCA_Pos) /*!< ACTLR: DISFPCA Mask */ #define SCnSCB_ACTLR_DISFOLD_Pos 2 /*!< ACTLR: DISFOLD Position */ #define SCnSCB_ACTLR_DISFOLD_Msk (1UL << SCnSCB_ACTLR_DISFOLD_Pos) /*!< ACTLR: DISFOLD Mask */ #define SCnSCB_ACTLR_DISDEFWBUF_Pos 1 /*!< ACTLR: DISDEFWBUF Position */ #define SCnSCB_ACTLR_DISDEFWBUF_Msk (1UL << SCnSCB_ACTLR_DISDEFWBUF_Pos) /*!< ACTLR: DISDEFWBUF Mask */ #define SCnSCB_ACTLR_DISMCYCINT_Pos 0 /*!< ACTLR: DISMCYCINT Position */ #define SCnSCB_ACTLR_DISMCYCINT_Msk (1UL << SCnSCB_ACTLR_DISMCYCINT_Pos) /*!< ACTLR: DISMCYCINT Mask */ /*@} end of group CMSIS_SCnotSCB */ /** \ingroup CMSIS_core_register \defgroup CMSIS_SysTick System Tick Timer (SysTick) \brief Type definitions for the System Timer Registers. @{ */ /** \brief Structure type to access the System Timer (SysTick). */ typedef struct { __IO uint32_t CTRL; /*!< Offset: 0x000 (R/W) SysTick Control and Status Register */ __IO uint32_t LOAD; /*!< Offset: 0x004 (R/W) SysTick Reload Value Register */ __IO uint32_t VAL; /*!< Offset: 0x008 (R/W) SysTick Current Value Register */ __I uint32_t CALIB; /*!< Offset: 0x00C (R/ ) SysTick Calibration Register */ } SysTick_Type; /* SysTick Control / Status Register Definitions */ #define SysTick_CTRL_COUNTFLAG_Pos 16 /*!< SysTick CTRL: COUNTFLAG Position */ #define SysTick_CTRL_COUNTFLAG_Msk (1UL << SysTick_CTRL_COUNTFLAG_Pos) /*!< SysTick CTRL: COUNTFLAG Mask */ #define SysTick_CTRL_CLKSOURCE_Pos 2 /*!< SysTick CTRL: CLKSOURCE Position */ #define SysTick_CTRL_CLKSOURCE_Msk (1UL << SysTick_CTRL_CLKSOURCE_Pos) /*!< SysTick CTRL: CLKSOURCE Mask */ #define SysTick_CTRL_TICKINT_Pos 1 /*!< SysTick CTRL: TICKINT Position */ #define SysTick_CTRL_TICKINT_Msk (1UL << SysTick_CTRL_TICKINT_Pos) /*!< SysTick CTRL: TICKINT Mask */ #define SysTick_CTRL_ENABLE_Pos 0 /*!< SysTick CTRL: ENABLE Position */ #define SysTick_CTRL_ENABLE_Msk (1UL << SysTick_CTRL_ENABLE_Pos) /*!< SysTick CTRL: ENABLE Mask */ /* SysTick Reload Register Definitions */ #define SysTick_LOAD_RELOAD_Pos 0 /*!< SysTick LOAD: RELOAD Position */ #define SysTick_LOAD_RELOAD_Msk (0xFFFFFFUL << SysTick_LOAD_RELOAD_Pos) /*!< SysTick LOAD: RELOAD Mask */ /* SysTick Current Register Definitions */ #define SysTick_VAL_CURRENT_Pos 0 /*!< SysTick VAL: CURRENT Position */ #define SysTick_VAL_CURRENT_Msk (0xFFFFFFUL << SysTick_VAL_CURRENT_Pos) /*!< SysTick VAL: CURRENT Mask */ /* SysTick Calibration Register Definitions */ #define SysTick_CALIB_NOREF_Pos 31 /*!< SysTick CALIB: NOREF Position */ #define SysTick_CALIB_NOREF_Msk (1UL << SysTick_CALIB_NOREF_Pos) /*!< SysTick CALIB: NOREF Mask */ #define SysTick_CALIB_SKEW_Pos 30 /*!< SysTick CALIB: SKEW Position */ #define SysTick_CALIB_SKEW_Msk (1UL << SysTick_CALIB_SKEW_Pos) /*!< SysTick CALIB: SKEW Mask */ #define SysTick_CALIB_TENMS_Pos 0 /*!< SysTick CALIB: TENMS Position */ #define SysTick_CALIB_TENMS_Msk (0xFFFFFFUL << SysTick_VAL_CURRENT_Pos) /*!< SysTick CALIB: TENMS Mask */ /*@} end of group CMSIS_SysTick */ /** \ingroup CMSIS_core_register \defgroup CMSIS_ITM Instrumentation Trace Macrocell (ITM) \brief Type definitions for the Instrumentation Trace Macrocell (ITM) @{ */ /** \brief Structure type to access the Instrumentation Trace Macrocell Register (ITM). */ typedef struct { __O union { __O uint8_t u8; /*!< Offset: 0x000 ( /W) ITM Stimulus Port 8-bit */ __O uint16_t u16; /*!< Offset: 0x000 ( /W) ITM Stimulus Port 16-bit */ __O uint32_t u32; /*!< Offset: 0x000 ( /W) ITM Stimulus Port 32-bit */ } PORT [32]; /*!< Offset: 0x000 ( /W) ITM Stimulus Port Registers */ uint32_t RESERVED0[864]; __IO uint32_t TER; /*!< Offset: 0xE00 (R/W) ITM Trace Enable Register */ uint32_t RESERVED1[15]; __IO uint32_t TPR; /*!< Offset: 0xE40 (R/W) ITM Trace Privilege Register */ uint32_t RESERVED2[15]; __IO uint32_t TCR; /*!< Offset: 0xE80 (R/W) ITM Trace Control Register */ uint32_t RESERVED3[29]; __O uint32_t IWR; /*!< Offset: 0xEF8 ( /W) ITM Integration Write Register */ __I uint32_t IRR; /*!< Offset: 0xEFC (R/ ) ITM Integration Read Register */ __IO uint32_t IMCR; /*!< Offset: 0xF00 (R/W) ITM Integration Mode Control Register */ uint32_t RESERVED4[43]; __O uint32_t LAR; /*!< Offset: 0xFB0 ( /W) ITM Lock Access Register */ __I uint32_t LSR; /*!< Offset: 0xFB4 (R/ ) ITM Lock Status Register */ uint32_t RESERVED5[6]; __I uint32_t PID4; /*!< Offset: 0xFD0 (R/ ) ITM Peripheral Identification Register #4 */ __I uint32_t PID5; /*!< Offset: 0xFD4 (R/ ) ITM Peripheral Identification Register #5 */ __I uint32_t PID6; /*!< Offset: 0xFD8 (R/ ) ITM Peripheral Identification Register #6 */ __I uint32_t PID7; /*!< Offset: 0xFDC (R/ ) ITM Peripheral Identification Register #7 */ __I uint32_t PID0; /*!< Offset: 0xFE0 (R/ ) ITM Peripheral Identification Register #0 */ __I uint32_t PID1; /*!< Offset: 0xFE4 (R/ ) ITM Peripheral Identification Register #1 */ __I uint32_t PID2; /*!< Offset: 0xFE8 (R/ ) ITM Peripheral Identification Register #2 */ __I uint32_t PID3; /*!< Offset: 0xFEC (R/ ) ITM Peripheral Identification Register #3 */ __I uint32_t CID0; /*!< Offset: 0xFF0 (R/ ) ITM Component Identification Register #0 */ __I uint32_t CID1; /*!< Offset: 0xFF4 (R/ ) ITM Component Identification Register #1 */ __I uint32_t CID2; /*!< Offset: 0xFF8 (R/ ) ITM Component Identification Register #2 */ __I uint32_t CID3; /*!< Offset: 0xFFC (R/ ) ITM Component Identification Register #3 */ } ITM_Type; /* ITM Trace Privilege Register Definitions */ #define ITM_TPR_PRIVMASK_Pos 0 /*!< ITM TPR: PRIVMASK Position */ #define ITM_TPR_PRIVMASK_Msk (0xFUL << ITM_TPR_PRIVMASK_Pos) /*!< ITM TPR: PRIVMASK Mask */ /* ITM Trace Control Register Definitions */ #define ITM_TCR_BUSY_Pos 23 /*!< ITM TCR: BUSY Position */ #define ITM_TCR_BUSY_Msk (1UL << ITM_TCR_BUSY_Pos) /*!< ITM TCR: BUSY Mask */ #define ITM_TCR_TraceBusID_Pos 16 /*!< ITM TCR: ATBID Position */ #define ITM_TCR_TraceBusID_Msk (0x7FUL << ITM_TCR_TraceBusID_Pos) /*!< ITM TCR: ATBID Mask */ #define ITM_TCR_GTSFREQ_Pos 10 /*!< ITM TCR: Global timestamp frequency Position */ #define ITM_TCR_GTSFREQ_Msk (3UL << ITM_TCR_GTSFREQ_Pos) /*!< ITM TCR: Global timestamp frequency Mask */ #define ITM_TCR_TSPrescale_Pos 8 /*!< ITM TCR: TSPrescale Position */ #define ITM_TCR_TSPrescale_Msk (3UL << ITM_TCR_TSPrescale_Pos) /*!< ITM TCR: TSPrescale Mask */ #define ITM_TCR_SWOENA_Pos 4 /*!< ITM TCR: SWOENA Position */ #define ITM_TCR_SWOENA_Msk (1UL << ITM_TCR_SWOENA_Pos) /*!< ITM TCR: SWOENA Mask */ #define ITM_TCR_DWTENA_Pos 3 /*!< ITM TCR: DWTENA Position */ #define ITM_TCR_DWTENA_Msk (1UL << ITM_TCR_DWTENA_Pos) /*!< ITM TCR: DWTENA Mask */ #define ITM_TCR_SYNCENA_Pos 2 /*!< ITM TCR: SYNCENA Position */ #define ITM_TCR_SYNCENA_Msk (1UL << ITM_TCR_SYNCENA_Pos) /*!< ITM TCR: SYNCENA Mask */ #define ITM_TCR_TSENA_Pos 1 /*!< ITM TCR: TSENA Position */ #define ITM_TCR_TSENA_Msk (1UL << ITM_TCR_TSENA_Pos) /*!< ITM TCR: TSENA Mask */ #define ITM_TCR_ITMENA_Pos 0 /*!< ITM TCR: ITM Enable bit Position */ #define ITM_TCR_ITMENA_Msk (1UL << ITM_TCR_ITMENA_Pos) /*!< ITM TCR: ITM Enable bit Mask */ /* ITM Integration Write Register Definitions */ #define ITM_IWR_ATVALIDM_Pos 0 /*!< ITM IWR: ATVALIDM Position */ #define ITM_IWR_ATVALIDM_Msk (1UL << ITM_IWR_ATVALIDM_Pos) /*!< ITM IWR: ATVALIDM Mask */ /* ITM Integration Read Register Definitions */ #define ITM_IRR_ATREADYM_Pos 0 /*!< ITM IRR: ATREADYM Position */ #define ITM_IRR_ATREADYM_Msk (1UL << ITM_IRR_ATREADYM_Pos) /*!< ITM IRR: ATREADYM Mask */ /* ITM Integration Mode Control Register Definitions */ #define ITM_IMCR_INTEGRATION_Pos 0 /*!< ITM IMCR: INTEGRATION Position */ #define ITM_IMCR_INTEGRATION_Msk (1UL << ITM_IMCR_INTEGRATION_Pos) /*!< ITM IMCR: INTEGRATION Mask */ /* ITM Lock Status Register Definitions */ #define ITM_LSR_ByteAcc_Pos 2 /*!< ITM LSR: ByteAcc Position */ #define ITM_LSR_ByteAcc_Msk (1UL << ITM_LSR_ByteAcc_Pos) /*!< ITM LSR: ByteAcc Mask */ #define ITM_LSR_Access_Pos 1 /*!< ITM LSR: Access Position */ #define ITM_LSR_Access_Msk (1UL << ITM_LSR_Access_Pos) /*!< ITM LSR: Access Mask */ #define ITM_LSR_Present_Pos 0 /*!< ITM LSR: Present Position */ #define ITM_LSR_Present_Msk (1UL << ITM_LSR_Present_Pos) /*!< ITM LSR: Present Mask */ /*@}*/ /* end of group CMSIS_ITM */ /** \ingroup CMSIS_core_register \defgroup CMSIS_DWT Data Watchpoint and Trace (DWT) \brief Type definitions for the Data Watchpoint and Trace (DWT) @{ */ /** \brief Structure type to access the Data Watchpoint and Trace Register (DWT). */ typedef struct { __IO uint32_t CTRL; /*!< Offset: 0x000 (R/W) Control Register */ __IO uint32_t CYCCNT; /*!< Offset: 0x004 (R/W) Cycle Count Register */ __IO uint32_t CPICNT; /*!< Offset: 0x008 (R/W) CPI Count Register */ __IO uint32_t EXCCNT; /*!< Offset: 0x00C (R/W) Exception Overhead Count Register */ __IO uint32_t SLEEPCNT; /*!< Offset: 0x010 (R/W) Sleep Count Register */ __IO uint32_t LSUCNT; /*!< Offset: 0x014 (R/W) LSU Count Register */ __IO uint32_t FOLDCNT; /*!< Offset: 0x018 (R/W) Folded-instruction Count Register */ __I uint32_t PCSR; /*!< Offset: 0x01C (R/ ) Program Counter Sample Register */ __IO uint32_t COMP0; /*!< Offset: 0x020 (R/W) Comparator Register 0 */ __IO uint32_t MASK0; /*!< Offset: 0x024 (R/W) Mask Register 0 */ __IO uint32_t FUNCTION0; /*!< Offset: 0x028 (R/W) Function Register 0 */ uint32_t RESERVED0[1]; __IO uint32_t COMP1; /*!< Offset: 0x030 (R/W) Comparator Register 1 */ __IO uint32_t MASK1; /*!< Offset: 0x034 (R/W) Mask Register 1 */ __IO uint32_t FUNCTION1; /*!< Offset: 0x038 (R/W) Function Register 1 */ uint32_t RESERVED1[1]; __IO uint32_t COMP2; /*!< Offset: 0x040 (R/W) Comparator Register 2 */ __IO uint32_t MASK2; /*!< Offset: 0x044 (R/W) Mask Register 2 */ __IO uint32_t FUNCTION2; /*!< Offset: 0x048 (R/W) Function Register 2 */ uint32_t RESERVED2[1]; __IO uint32_t COMP3; /*!< Offset: 0x050 (R/W) Comparator Register 3 */ __IO uint32_t MASK3; /*!< Offset: 0x054 (R/W) Mask Register 3 */ __IO uint32_t FUNCTION3; /*!< Offset: 0x058 (R/W) Function Register 3 */ } DWT_Type; /* DWT Control Register Definitions */ #define DWT_CTRL_NUMCOMP_Pos 28 /*!< DWT CTRL: NUMCOMP Position */ #define DWT_CTRL_NUMCOMP_Msk (0xFUL << DWT_CTRL_NUMCOMP_Pos) /*!< DWT CTRL: NUMCOMP Mask */ #define DWT_CTRL_NOTRCPKT_Pos 27 /*!< DWT CTRL: NOTRCPKT Position */ #define DWT_CTRL_NOTRCPKT_Msk (0x1UL << DWT_CTRL_NOTRCPKT_Pos) /*!< DWT CTRL: NOTRCPKT Mask */ #define DWT_CTRL_NOEXTTRIG_Pos 26 /*!< DWT CTRL: NOEXTTRIG Position */ #define DWT_CTRL_NOEXTTRIG_Msk (0x1UL << DWT_CTRL_NOEXTTRIG_Pos) /*!< DWT CTRL: NOEXTTRIG Mask */ #define DWT_CTRL_NOCYCCNT_Pos 25 /*!< DWT CTRL: NOCYCCNT Position */ #define DWT_CTRL_NOCYCCNT_Msk (0x1UL << DWT_CTRL_NOCYCCNT_Pos) /*!< DWT CTRL: NOCYCCNT Mask */ #define DWT_CTRL_NOPRFCNT_Pos 24 /*!< DWT CTRL: NOPRFCNT Position */ #define DWT_CTRL_NOPRFCNT_Msk (0x1UL << DWT_CTRL_NOPRFCNT_Pos) /*!< DWT CTRL: NOPRFCNT Mask */ #define DWT_CTRL_CYCEVTENA_Pos 22 /*!< DWT CTRL: CYCEVTENA Position */ #define DWT_CTRL_CYCEVTENA_Msk (0x1UL << DWT_CTRL_CYCEVTENA_Pos) /*!< DWT CTRL: CYCEVTENA Mask */ #define DWT_CTRL_FOLDEVTENA_Pos 21 /*!< DWT CTRL: FOLDEVTENA Position */ #define DWT_CTRL_FOLDEVTENA_Msk (0x1UL << DWT_CTRL_FOLDEVTENA_Pos) /*!< DWT CTRL: FOLDEVTENA Mask */ #define DWT_CTRL_LSUEVTENA_Pos 20 /*!< DWT CTRL: LSUEVTENA Position */ #define DWT_CTRL_LSUEVTENA_Msk (0x1UL << DWT_CTRL_LSUEVTENA_Pos) /*!< DWT CTRL: LSUEVTENA Mask */ #define DWT_CTRL_SLEEPEVTENA_Pos 19 /*!< DWT CTRL: SLEEPEVTENA Position */ #define DWT_CTRL_SLEEPEVTENA_Msk (0x1UL << DWT_CTRL_SLEEPEVTENA_Pos) /*!< DWT CTRL: SLEEPEVTENA Mask */ #define DWT_CTRL_EXCEVTENA_Pos 18 /*!< DWT CTRL: EXCEVTENA Position */ #define DWT_CTRL_EXCEVTENA_Msk (0x1UL << DWT_CTRL_EXCEVTENA_Pos) /*!< DWT CTRL: EXCEVTENA Mask */ #define DWT_CTRL_CPIEVTENA_Pos 17 /*!< DWT CTRL: CPIEVTENA Position */ #define DWT_CTRL_CPIEVTENA_Msk (0x1UL << DWT_CTRL_CPIEVTENA_Pos) /*!< DWT CTRL: CPIEVTENA Mask */ #define DWT_CTRL_EXCTRCENA_Pos 16 /*!< DWT CTRL: EXCTRCENA Position */ #define DWT_CTRL_EXCTRCENA_Msk (0x1UL << DWT_CTRL_EXCTRCENA_Pos) /*!< DWT CTRL: EXCTRCENA Mask */ #define DWT_CTRL_PCSAMPLENA_Pos 12 /*!< DWT CTRL: PCSAMPLENA Position */ #define DWT_CTRL_PCSAMPLENA_Msk (0x1UL << DWT_CTRL_PCSAMPLENA_Pos) /*!< DWT CTRL: PCSAMPLENA Mask */ #define DWT_CTRL_SYNCTAP_Pos 10 /*!< DWT CTRL: SYNCTAP Position */ #define DWT_CTRL_SYNCTAP_Msk (0x3UL << DWT_CTRL_SYNCTAP_Pos) /*!< DWT CTRL: SYNCTAP Mask */ #define DWT_CTRL_CYCTAP_Pos 9 /*!< DWT CTRL: CYCTAP Position */ #define DWT_CTRL_CYCTAP_Msk (0x1UL << DWT_CTRL_CYCTAP_Pos) /*!< DWT CTRL: CYCTAP Mask */ #define DWT_CTRL_POSTINIT_Pos 5 /*!< DWT CTRL: POSTINIT Position */ #define DWT_CTRL_POSTINIT_Msk (0xFUL << DWT_CTRL_POSTINIT_Pos) /*!< DWT CTRL: POSTINIT Mask */ #define DWT_CTRL_POSTPRESET_Pos 1 /*!< DWT CTRL: POSTPRESET Position */ #define DWT_CTRL_POSTPRESET_Msk (0xFUL << DWT_CTRL_POSTPRESET_Pos) /*!< DWT CTRL: POSTPRESET Mask */ #define DWT_CTRL_CYCCNTENA_Pos 0 /*!< DWT CTRL: CYCCNTENA Position */ #define DWT_CTRL_CYCCNTENA_Msk (0x1UL << DWT_CTRL_CYCCNTENA_Pos) /*!< DWT CTRL: CYCCNTENA Mask */ /* DWT CPI Count Register Definitions */ #define DWT_CPICNT_CPICNT_Pos 0 /*!< DWT CPICNT: CPICNT Position */ #define DWT_CPICNT_CPICNT_Msk (0xFFUL << DWT_CPICNT_CPICNT_Pos) /*!< DWT CPICNT: CPICNT Mask */ /* DWT Exception Overhead Count Register Definitions */ #define DWT_EXCCNT_EXCCNT_Pos 0 /*!< DWT EXCCNT: EXCCNT Position */ #define DWT_EXCCNT_EXCCNT_Msk (0xFFUL << DWT_EXCCNT_EXCCNT_Pos) /*!< DWT EXCCNT: EXCCNT Mask */ /* DWT Sleep Count Register Definitions */ #define DWT_SLEEPCNT_SLEEPCNT_Pos 0 /*!< DWT SLEEPCNT: SLEEPCNT Position */ #define DWT_SLEEPCNT_SLEEPCNT_Msk (0xFFUL << DWT_SLEEPCNT_SLEEPCNT_Pos) /*!< DWT SLEEPCNT: SLEEPCNT Mask */ /* DWT LSU Count Register Definitions */ #define DWT_LSUCNT_LSUCNT_Pos 0 /*!< DWT LSUCNT: LSUCNT Position */ #define DWT_LSUCNT_LSUCNT_Msk (0xFFUL << DWT_LSUCNT_LSUCNT_Pos) /*!< DWT LSUCNT: LSUCNT Mask */ /* DWT Folded-instruction Count Register Definitions */ #define DWT_FOLDCNT_FOLDCNT_Pos 0 /*!< DWT FOLDCNT: FOLDCNT Position */ #define DWT_FOLDCNT_FOLDCNT_Msk (0xFFUL << DWT_FOLDCNT_FOLDCNT_Pos) /*!< DWT FOLDCNT: FOLDCNT Mask */ /* DWT Comparator Mask Register Definitions */ #define DWT_MASK_MASK_Pos 0 /*!< DWT MASK: MASK Position */ #define DWT_MASK_MASK_Msk (0x1FUL << DWT_MASK_MASK_Pos) /*!< DWT MASK: MASK Mask */ /* DWT Comparator Function Register Definitions */ #define DWT_FUNCTION_MATCHED_Pos 24 /*!< DWT FUNCTION: MATCHED Position */ #define DWT_FUNCTION_MATCHED_Msk (0x1UL << DWT_FUNCTION_MATCHED_Pos) /*!< DWT FUNCTION: MATCHED Mask */ #define DWT_FUNCTION_DATAVADDR1_Pos 16 /*!< DWT FUNCTION: DATAVADDR1 Position */ #define DWT_FUNCTION_DATAVADDR1_Msk (0xFUL << DWT_FUNCTION_DATAVADDR1_Pos) /*!< DWT FUNCTION: DATAVADDR1 Mask */ #define DWT_FUNCTION_DATAVADDR0_Pos 12 /*!< DWT FUNCTION: DATAVADDR0 Position */ #define DWT_FUNCTION_DATAVADDR0_Msk (0xFUL << DWT_FUNCTION_DATAVADDR0_Pos) /*!< DWT FUNCTION: DATAVADDR0 Mask */ #define DWT_FUNCTION_DATAVSIZE_Pos 10 /*!< DWT FUNCTION: DATAVSIZE Position */ #define DWT_FUNCTION_DATAVSIZE_Msk (0x3UL << DWT_FUNCTION_DATAVSIZE_Pos) /*!< DWT FUNCTION: DATAVSIZE Mask */ #define DWT_FUNCTION_LNK1ENA_Pos 9 /*!< DWT FUNCTION: LNK1ENA Position */ #define DWT_FUNCTION_LNK1ENA_Msk (0x1UL << DWT_FUNCTION_LNK1ENA_Pos) /*!< DWT FUNCTION: LNK1ENA Mask */ #define DWT_FUNCTION_DATAVMATCH_Pos 8 /*!< DWT FUNCTION: DATAVMATCH Position */ #define DWT_FUNCTION_DATAVMATCH_Msk (0x1UL << DWT_FUNCTION_DATAVMATCH_Pos) /*!< DWT FUNCTION: DATAVMATCH Mask */ #define DWT_FUNCTION_CYCMATCH_Pos 7 /*!< DWT FUNCTION: CYCMATCH Position */ #define DWT_FUNCTION_CYCMATCH_Msk (0x1UL << DWT_FUNCTION_CYCMATCH_Pos) /*!< DWT FUNCTION: CYCMATCH Mask */ #define DWT_FUNCTION_EMITRANGE_Pos 5 /*!< DWT FUNCTION: EMITRANGE Position */ #define DWT_FUNCTION_EMITRANGE_Msk (0x1UL << DWT_FUNCTION_EMITRANGE_Pos) /*!< DWT FUNCTION: EMITRANGE Mask */ #define DWT_FUNCTION_FUNCTION_Pos 0 /*!< DWT FUNCTION: FUNCTION Position */ #define DWT_FUNCTION_FUNCTION_Msk (0xFUL << DWT_FUNCTION_FUNCTION_Pos) /*!< DWT FUNCTION: FUNCTION Mask */ /*@}*/ /* end of group CMSIS_DWT */ /** \ingroup CMSIS_core_register \defgroup CMSIS_TPI Trace Port Interface (TPI) \brief Type definitions for the Trace Port Interface (TPI) @{ */ /** \brief Structure type to access the Trace Port Interface Register (TPI). */ typedef struct { __IO uint32_t SSPSR; /*!< Offset: 0x000 (R/ ) Supported Parallel Port Size Register */ __IO uint32_t CSPSR; /*!< Offset: 0x004 (R/W) Current Parallel Port Size Register */ uint32_t RESERVED0[2]; __IO uint32_t ACPR; /*!< Offset: 0x010 (R/W) Asynchronous Clock Prescaler Register */ uint32_t RESERVED1[55]; __IO uint32_t SPPR; /*!< Offset: 0x0F0 (R/W) Selected Pin Protocol Register */ uint32_t RESERVED2[131]; __I uint32_t FFSR; /*!< Offset: 0x300 (R/ ) Formatter and Flush Status Register */ __IO uint32_t FFCR; /*!< Offset: 0x304 (R/W) Formatter and Flush Control Register */ __I uint32_t FSCR; /*!< Offset: 0x308 (R/ ) Formatter Synchronization Counter Register */ uint32_t RESERVED3[759]; __I uint32_t TRIGGER; /*!< Offset: 0xEE8 (R/ ) TRIGGER */ __I uint32_t FIFO0; /*!< Offset: 0xEEC (R/ ) Integration ETM Data */ __I uint32_t ITATBCTR2; /*!< Offset: 0xEF0 (R/ ) ITATBCTR2 */ uint32_t RESERVED4[1]; __I uint32_t ITATBCTR0; /*!< Offset: 0xEF8 (R/ ) ITATBCTR0 */ __I uint32_t FIFO1; /*!< Offset: 0xEFC (R/ ) Integration ITM Data */ __IO uint32_t ITCTRL; /*!< Offset: 0xF00 (R/W) Integration Mode Control */ uint32_t RESERVED5[39]; __IO uint32_t CLAIMSET; /*!< Offset: 0xFA0 (R/W) Claim tag set */ __IO uint32_t CLAIMCLR; /*!< Offset: 0xFA4 (R/W) Claim tag clear */ uint32_t RESERVED7[8]; __I uint32_t DEVID; /*!< Offset: 0xFC8 (R/ ) TPIU_DEVID */ __I uint32_t DEVTYPE; /*!< Offset: 0xFCC (R/ ) TPIU_DEVTYPE */ } TPI_Type; /* TPI Asynchronous Clock Prescaler Register Definitions */ #define TPI_ACPR_PRESCALER_Pos 0 /*!< TPI ACPR: PRESCALER Position */ #define TPI_ACPR_PRESCALER_Msk (0x1FFFUL << TPI_ACPR_PRESCALER_Pos) /*!< TPI ACPR: PRESCALER Mask */ /* TPI Selected Pin Protocol Register Definitions */ #define TPI_SPPR_TXMODE_Pos 0 /*!< TPI SPPR: TXMODE Position */ #define TPI_SPPR_TXMODE_Msk (0x3UL << TPI_SPPR_TXMODE_Pos) /*!< TPI SPPR: TXMODE Mask */ /* TPI Formatter and Flush Status Register Definitions */ #define TPI_FFSR_FtNonStop_Pos 3 /*!< TPI FFSR: FtNonStop Position */ #define TPI_FFSR_FtNonStop_Msk (0x1UL << TPI_FFSR_FtNonStop_Pos) /*!< TPI FFSR: FtNonStop Mask */ #define TPI_FFSR_TCPresent_Pos 2 /*!< TPI FFSR: TCPresent Position */ #define TPI_FFSR_TCPresent_Msk (0x1UL << TPI_FFSR_TCPresent_Pos) /*!< TPI FFSR: TCPresent Mask */ #define TPI_FFSR_FtStopped_Pos 1 /*!< TPI FFSR: FtStopped Position */ #define TPI_FFSR_FtStopped_Msk (0x1UL << TPI_FFSR_FtStopped_Pos) /*!< TPI FFSR: FtStopped Mask */ #define TPI_FFSR_FlInProg_Pos 0 /*!< TPI FFSR: FlInProg Position */ #define TPI_FFSR_FlInProg_Msk (0x1UL << TPI_FFSR_FlInProg_Pos) /*!< TPI FFSR: FlInProg Mask */ /* TPI Formatter and Flush Control Register Definitions */ #define TPI_FFCR_TrigIn_Pos 8 /*!< TPI FFCR: TrigIn Position */ #define TPI_FFCR_TrigIn_Msk (0x1UL << TPI_FFCR_TrigIn_Pos) /*!< TPI FFCR: TrigIn Mask */ #define TPI_FFCR_EnFCont_Pos 1 /*!< TPI FFCR: EnFCont Position */ #define TPI_FFCR_EnFCont_Msk (0x1UL << TPI_FFCR_EnFCont_Pos) /*!< TPI FFCR: EnFCont Mask */ /* TPI TRIGGER Register Definitions */ #define TPI_TRIGGER_TRIGGER_Pos 0 /*!< TPI TRIGGER: TRIGGER Position */ #define TPI_TRIGGER_TRIGGER_Msk (0x1UL << TPI_TRIGGER_TRIGGER_Pos) /*!< TPI TRIGGER: TRIGGER Mask */ /* TPI Integration ETM Data Register Definitions (FIFO0) */ #define TPI_FIFO0_ITM_ATVALID_Pos 29 /*!< TPI FIFO0: ITM_ATVALID Position */ #define TPI_FIFO0_ITM_ATVALID_Msk (0x3UL << TPI_FIFO0_ITM_ATVALID_Pos) /*!< TPI FIFO0: ITM_ATVALID Mask */ #define TPI_FIFO0_ITM_bytecount_Pos 27 /*!< TPI FIFO0: ITM_bytecount Position */ #define TPI_FIFO0_ITM_bytecount_Msk (0x3UL << TPI_FIFO0_ITM_bytecount_Pos) /*!< TPI FIFO0: ITM_bytecount Mask */ #define TPI_FIFO0_ETM_ATVALID_Pos 26 /*!< TPI FIFO0: ETM_ATVALID Position */ #define TPI_FIFO0_ETM_ATVALID_Msk (0x3UL << TPI_FIFO0_ETM_ATVALID_Pos) /*!< TPI FIFO0: ETM_ATVALID Mask */ #define TPI_FIFO0_ETM_bytecount_Pos 24 /*!< TPI FIFO0: ETM_bytecount Position */ #define TPI_FIFO0_ETM_bytecount_Msk (0x3UL << TPI_FIFO0_ETM_bytecount_Pos) /*!< TPI FIFO0: ETM_bytecount Mask */ #define TPI_FIFO0_ETM2_Pos 16 /*!< TPI FIFO0: ETM2 Position */ #define TPI_FIFO0_ETM2_Msk (0xFFUL << TPI_FIFO0_ETM2_Pos) /*!< TPI FIFO0: ETM2 Mask */ #define TPI_FIFO0_ETM1_Pos 8 /*!< TPI FIFO0: ETM1 Position */ #define TPI_FIFO0_ETM1_Msk (0xFFUL << TPI_FIFO0_ETM1_Pos) /*!< TPI FIFO0: ETM1 Mask */ #define TPI_FIFO0_ETM0_Pos 0 /*!< TPI FIFO0: ETM0 Position */ #define TPI_FIFO0_ETM0_Msk (0xFFUL << TPI_FIFO0_ETM0_Pos) /*!< TPI FIFO0: ETM0 Mask */ /* TPI ITATBCTR2 Register Definitions */ #define TPI_ITATBCTR2_ATREADY_Pos 0 /*!< TPI ITATBCTR2: ATREADY Position */ #define TPI_ITATBCTR2_ATREADY_Msk (0x1UL << TPI_ITATBCTR2_ATREADY_Pos) /*!< TPI ITATBCTR2: ATREADY Mask */ /* TPI Integration ITM Data Register Definitions (FIFO1) */ #define TPI_FIFO1_ITM_ATVALID_Pos 29 /*!< TPI FIFO1: ITM_ATVALID Position */ #define TPI_FIFO1_ITM_ATVALID_Msk (0x3UL << TPI_FIFO1_ITM_ATVALID_Pos) /*!< TPI FIFO1: ITM_ATVALID Mask */ #define TPI_FIFO1_ITM_bytecount_Pos 27 /*!< TPI FIFO1: ITM_bytecount Position */ #define TPI_FIFO1_ITM_bytecount_Msk (0x3UL << TPI_FIFO1_ITM_bytecount_Pos) /*!< TPI FIFO1: ITM_bytecount Mask */ #define TPI_FIFO1_ETM_ATVALID_Pos 26 /*!< TPI FIFO1: ETM_ATVALID Position */ #define TPI_FIFO1_ETM_ATVALID_Msk (0x3UL << TPI_FIFO1_ETM_ATVALID_Pos) /*!< TPI FIFO1: ETM_ATVALID Mask */ #define TPI_FIFO1_ETM_bytecount_Pos 24 /*!< TPI FIFO1: ETM_bytecount Position */ #define TPI_FIFO1_ETM_bytecount_Msk (0x3UL << TPI_FIFO1_ETM_bytecount_Pos) /*!< TPI FIFO1: ETM_bytecount Mask */ #define TPI_FIFO1_ITM2_Pos 16 /*!< TPI FIFO1: ITM2 Position */ #define TPI_FIFO1_ITM2_Msk (0xFFUL << TPI_FIFO1_ITM2_Pos) /*!< TPI FIFO1: ITM2 Mask */ #define TPI_FIFO1_ITM1_Pos 8 /*!< TPI FIFO1: ITM1 Position */ #define TPI_FIFO1_ITM1_Msk (0xFFUL << TPI_FIFO1_ITM1_Pos) /*!< TPI FIFO1: ITM1 Mask */ #define TPI_FIFO1_ITM0_Pos 0 /*!< TPI FIFO1: ITM0 Position */ #define TPI_FIFO1_ITM0_Msk (0xFFUL << TPI_FIFO1_ITM0_Pos) /*!< TPI FIFO1: ITM0 Mask */ /* TPI ITATBCTR0 Register Definitions */ #define TPI_ITATBCTR0_ATREADY_Pos 0 /*!< TPI ITATBCTR0: ATREADY Position */ #define TPI_ITATBCTR0_ATREADY_Msk (0x1UL << TPI_ITATBCTR0_ATREADY_Pos) /*!< TPI ITATBCTR0: ATREADY Mask */ /* TPI Integration Mode Control Register Definitions */ #define TPI_ITCTRL_Mode_Pos 0 /*!< TPI ITCTRL: Mode Position */ #define TPI_ITCTRL_Mode_Msk (0x1UL << TPI_ITCTRL_Mode_Pos) /*!< TPI ITCTRL: Mode Mask */ /* TPI DEVID Register Definitions */ #define TPI_DEVID_NRZVALID_Pos 11 /*!< TPI DEVID: NRZVALID Position */ #define TPI_DEVID_NRZVALID_Msk (0x1UL << TPI_DEVID_NRZVALID_Pos) /*!< TPI DEVID: NRZVALID Mask */ #define TPI_DEVID_MANCVALID_Pos 10 /*!< TPI DEVID: MANCVALID Position */ #define TPI_DEVID_MANCVALID_Msk (0x1UL << TPI_DEVID_MANCVALID_Pos) /*!< TPI DEVID: MANCVALID Mask */ #define TPI_DEVID_PTINVALID_Pos 9 /*!< TPI DEVID: PTINVALID Position */ #define TPI_DEVID_PTINVALID_Msk (0x1UL << TPI_DEVID_PTINVALID_Pos) /*!< TPI DEVID: PTINVALID Mask */ #define TPI_DEVID_MinBufSz_Pos 6 /*!< TPI DEVID: MinBufSz Position */ #define TPI_DEVID_MinBufSz_Msk (0x7UL << TPI_DEVID_MinBufSz_Pos) /*!< TPI DEVID: MinBufSz Mask */ #define TPI_DEVID_AsynClkIn_Pos 5 /*!< TPI DEVID: AsynClkIn Position */ #define TPI_DEVID_AsynClkIn_Msk (0x1UL << TPI_DEVID_AsynClkIn_Pos) /*!< TPI DEVID: AsynClkIn Mask */ #define TPI_DEVID_NrTraceInput_Pos 0 /*!< TPI DEVID: NrTraceInput Position */ #define TPI_DEVID_NrTraceInput_Msk (0x1FUL << TPI_DEVID_NrTraceInput_Pos) /*!< TPI DEVID: NrTraceInput Mask */ /* TPI DEVTYPE Register Definitions */ #define TPI_DEVTYPE_SubType_Pos 0 /*!< TPI DEVTYPE: SubType Position */ #define TPI_DEVTYPE_SubType_Msk (0xFUL << TPI_DEVTYPE_SubType_Pos) /*!< TPI DEVTYPE: SubType Mask */ #define TPI_DEVTYPE_MajorType_Pos 4 /*!< TPI DEVTYPE: MajorType Position */ #define TPI_DEVTYPE_MajorType_Msk (0xFUL << TPI_DEVTYPE_MajorType_Pos) /*!< TPI DEVTYPE: MajorType Mask */ /*@}*/ /* end of group CMSIS_TPI */ #if (__MPU_PRESENT == 1) /** \ingroup CMSIS_core_register \defgroup CMSIS_MPU Memory Protection Unit (MPU) \brief Type definitions for the Memory Protection Unit (MPU) @{ */ /** \brief Structure type to access the Memory Protection Unit (MPU). */ typedef struct { __I uint32_t TYPE; /*!< Offset: 0x000 (R/ ) MPU Type Register */ __IO uint32_t CTRL; /*!< Offset: 0x004 (R/W) MPU Control Register */ __IO uint32_t RNR; /*!< Offset: 0x008 (R/W) MPU Region RNRber Register */ __IO uint32_t RBAR; /*!< Offset: 0x00C (R/W) MPU Region Base Address Register */ __IO uint32_t RASR; /*!< Offset: 0x010 (R/W) MPU Region Attribute and Size Register */ __IO uint32_t RBAR_A1; /*!< Offset: 0x014 (R/W) MPU Alias 1 Region Base Address Register */ __IO uint32_t RASR_A1; /*!< Offset: 0x018 (R/W) MPU Alias 1 Region Attribute and Size Register */ __IO uint32_t RBAR_A2; /*!< Offset: 0x01C (R/W) MPU Alias 2 Region Base Address Register */ __IO uint32_t RASR_A2; /*!< Offset: 0x020 (R/W) MPU Alias 2 Region Attribute and Size Register */ __IO uint32_t RBAR_A3; /*!< Offset: 0x024 (R/W) MPU Alias 3 Region Base Address Register */ __IO uint32_t RASR_A3; /*!< Offset: 0x028 (R/W) MPU Alias 3 Region Attribute and Size Register */ } MPU_Type; /* MPU Type Register */ #define MPU_TYPE_IREGION_Pos 16 /*!< MPU TYPE: IREGION Position */ #define MPU_TYPE_IREGION_Msk (0xFFUL << MPU_TYPE_IREGION_Pos) /*!< MPU TYPE: IREGION Mask */ #define MPU_TYPE_DREGION_Pos 8 /*!< MPU TYPE: DREGION Position */ #define MPU_TYPE_DREGION_Msk (0xFFUL << MPU_TYPE_DREGION_Pos) /*!< MPU TYPE: DREGION Mask */ #define MPU_TYPE_SEPARATE_Pos 0 /*!< MPU TYPE: SEPARATE Position */ #define MPU_TYPE_SEPARATE_Msk (1UL << MPU_TYPE_SEPARATE_Pos) /*!< MPU TYPE: SEPARATE Mask */ /* MPU Control Register */ #define MPU_CTRL_PRIVDEFENA_Pos 2 /*!< MPU CTRL: PRIVDEFENA Position */ #define MPU_CTRL_PRIVDEFENA_Msk (1UL << MPU_CTRL_PRIVDEFENA_Pos) /*!< MPU CTRL: PRIVDEFENA Mask */ #define MPU_CTRL_HFNMIENA_Pos 1 /*!< MPU CTRL: HFNMIENA Position */ #define MPU_CTRL_HFNMIENA_Msk (1UL << MPU_CTRL_HFNMIENA_Pos) /*!< MPU CTRL: HFNMIENA Mask */ #define MPU_CTRL_ENABLE_Pos 0 /*!< MPU CTRL: ENABLE Position */ #define MPU_CTRL_ENABLE_Msk (1UL << MPU_CTRL_ENABLE_Pos) /*!< MPU CTRL: ENABLE Mask */ /* MPU Region Number Register */ #define MPU_RNR_REGION_Pos 0 /*!< MPU RNR: REGION Position */ #define MPU_RNR_REGION_Msk (0xFFUL << MPU_RNR_REGION_Pos) /*!< MPU RNR: REGION Mask */ /* MPU Region Base Address Register */ #define MPU_RBAR_ADDR_Pos 5 /*!< MPU RBAR: ADDR Position */ #define MPU_RBAR_ADDR_Msk (0x7FFFFFFUL << MPU_RBAR_ADDR_Pos) /*!< MPU RBAR: ADDR Mask */ #define MPU_RBAR_VALID_Pos 4 /*!< MPU RBAR: VALID Position */ #define MPU_RBAR_VALID_Msk (1UL << MPU_RBAR_VALID_Pos) /*!< MPU RBAR: VALID Mask */ #define MPU_RBAR_REGION_Pos 0 /*!< MPU RBAR: REGION Position */ #define MPU_RBAR_REGION_Msk (0xFUL << MPU_RBAR_REGION_Pos) /*!< MPU RBAR: REGION Mask */ /* MPU Region Attribute and Size Register */ #define MPU_RASR_ATTRS_Pos 16 /*!< MPU RASR: MPU Region Attribute field Position */ #define MPU_RASR_ATTRS_Msk (0xFFFFUL << MPU_RASR_ATTRS_Pos) /*!< MPU RASR: MPU Region Attribute field Mask */ #define MPU_RASR_XN_Pos 28 /*!< MPU RASR: ATTRS.XN Position */ #define MPU_RASR_XN_Msk (1UL << MPU_RASR_XN_Pos) /*!< MPU RASR: ATTRS.XN Mask */ #define MPU_RASR_AP_Pos 24 /*!< MPU RASR: ATTRS.AP Position */ #define MPU_RASR_AP_Msk (0x7UL << MPU_RASR_AP_Pos) /*!< MPU RASR: ATTRS.AP Mask */ #define MPU_RASR_TEX_Pos 19 /*!< MPU RASR: ATTRS.TEX Position */ #define MPU_RASR_TEX_Msk (0x7UL << MPU_RASR_TEX_Pos) /*!< MPU RASR: ATTRS.TEX Mask */ #define MPU_RASR_S_Pos 18 /*!< MPU RASR: ATTRS.S Position */ #define MPU_RASR_S_Msk (1UL << MPU_RASR_S_Pos) /*!< MPU RASR: ATTRS.S Mask */ #define MPU_RASR_C_Pos 17 /*!< MPU RASR: ATTRS.C Position */ #define MPU_RASR_C_Msk (1UL << MPU_RASR_C_Pos) /*!< MPU RASR: ATTRS.C Mask */ #define MPU_RASR_B_Pos 16 /*!< MPU RASR: ATTRS.B Position */ #define MPU_RASR_B_Msk (1UL << MPU_RASR_B_Pos) /*!< MPU RASR: ATTRS.B Mask */ #define MPU_RASR_SRD_Pos 8 /*!< MPU RASR: Sub-Region Disable Position */ #define MPU_RASR_SRD_Msk (0xFFUL << MPU_RASR_SRD_Pos) /*!< MPU RASR: Sub-Region Disable Mask */ #define MPU_RASR_SIZE_Pos 1 /*!< MPU RASR: Region Size Field Position */ #define MPU_RASR_SIZE_Msk (0x1FUL << MPU_RASR_SIZE_Pos) /*!< MPU RASR: Region Size Field Mask */ #define MPU_RASR_ENABLE_Pos 0 /*!< MPU RASR: Region enable bit Position */ #define MPU_RASR_ENABLE_Msk (1UL << MPU_RASR_ENABLE_Pos) /*!< MPU RASR: Region enable bit Disable Mask */ /*@} end of group CMSIS_MPU */ #endif #if (__FPU_PRESENT == 1) /** \ingroup CMSIS_core_register \defgroup CMSIS_FPU Floating Point Unit (FPU) \brief Type definitions for the Floating Point Unit (FPU) @{ */ /** \brief Structure type to access the Floating Point Unit (FPU). */ typedef struct { uint32_t RESERVED0[1]; __IO uint32_t FPCCR; /*!< Offset: 0x004 (R/W) Floating-Point Context Control Register */ __IO uint32_t FPCAR; /*!< Offset: 0x008 (R/W) Floating-Point Context Address Register */ __IO uint32_t FPDSCR; /*!< Offset: 0x00C (R/W) Floating-Point Default Status Control Register */ __I uint32_t MVFR0; /*!< Offset: 0x010 (R/ ) Media and FP Feature Register 0 */ __I uint32_t MVFR1; /*!< Offset: 0x014 (R/ ) Media and FP Feature Register 1 */ } FPU_Type; /* Floating-Point Context Control Register */ #define FPU_FPCCR_ASPEN_Pos 31 /*!< FPCCR: ASPEN bit Position */ #define FPU_FPCCR_ASPEN_Msk (1UL << FPU_FPCCR_ASPEN_Pos) /*!< FPCCR: ASPEN bit Mask */ #define FPU_FPCCR_LSPEN_Pos 30 /*!< FPCCR: LSPEN Position */ #define FPU_FPCCR_LSPEN_Msk (1UL << FPU_FPCCR_LSPEN_Pos) /*!< FPCCR: LSPEN bit Mask */ #define FPU_FPCCR_MONRDY_Pos 8 /*!< FPCCR: MONRDY Position */ #define FPU_FPCCR_MONRDY_Msk (1UL << FPU_FPCCR_MONRDY_Pos) /*!< FPCCR: MONRDY bit Mask */ #define FPU_FPCCR_BFRDY_Pos 6 /*!< FPCCR: BFRDY Position */ #define FPU_FPCCR_BFRDY_Msk (1UL << FPU_FPCCR_BFRDY_Pos) /*!< FPCCR: BFRDY bit Mask */ #define FPU_FPCCR_MMRDY_Pos 5 /*!< FPCCR: MMRDY Position */ #define FPU_FPCCR_MMRDY_Msk (1UL << FPU_FPCCR_MMRDY_Pos) /*!< FPCCR: MMRDY bit Mask */ #define FPU_FPCCR_HFRDY_Pos 4 /*!< FPCCR: HFRDY Position */ #define FPU_FPCCR_HFRDY_Msk (1UL << FPU_FPCCR_HFRDY_Pos) /*!< FPCCR: HFRDY bit Mask */ #define FPU_FPCCR_THREAD_Pos 3 /*!< FPCCR: processor mode bit Position */ #define FPU_FPCCR_THREAD_Msk (1UL << FPU_FPCCR_THREAD_Pos) /*!< FPCCR: processor mode active bit Mask */ #define FPU_FPCCR_USER_Pos 1 /*!< FPCCR: privilege level bit Position */ #define FPU_FPCCR_USER_Msk (1UL << FPU_FPCCR_USER_Pos) /*!< FPCCR: privilege level bit Mask */ #define FPU_FPCCR_LSPACT_Pos 0 /*!< FPCCR: Lazy state preservation active bit Position */ #define FPU_FPCCR_LSPACT_Msk (1UL << FPU_FPCCR_LSPACT_Pos) /*!< FPCCR: Lazy state preservation active bit Mask */ /* Floating-Point Context Address Register */ #define FPU_FPCAR_ADDRESS_Pos 3 /*!< FPCAR: ADDRESS bit Position */ #define FPU_FPCAR_ADDRESS_Msk (0x1FFFFFFFUL << FPU_FPCAR_ADDRESS_Pos) /*!< FPCAR: ADDRESS bit Mask */ /* Floating-Point Default Status Control Register */ #define FPU_FPDSCR_AHP_Pos 26 /*!< FPDSCR: AHP bit Position */ #define FPU_FPDSCR_AHP_Msk (1UL << FPU_FPDSCR_AHP_Pos) /*!< FPDSCR: AHP bit Mask */ #define FPU_FPDSCR_DN_Pos 25 /*!< FPDSCR: DN bit Position */ #define FPU_FPDSCR_DN_Msk (1UL << FPU_FPDSCR_DN_Pos) /*!< FPDSCR: DN bit Mask */ #define FPU_FPDSCR_FZ_Pos 24 /*!< FPDSCR: FZ bit Position */ #define FPU_FPDSCR_FZ_Msk (1UL << FPU_FPDSCR_FZ_Pos) /*!< FPDSCR: FZ bit Mask */ #define FPU_FPDSCR_RMode_Pos 22 /*!< FPDSCR: RMode bit Position */ #define FPU_FPDSCR_RMode_Msk (3UL << FPU_FPDSCR_RMode_Pos) /*!< FPDSCR: RMode bit Mask */ /* Media and FP Feature Register 0 */ #define FPU_MVFR0_FP_rounding_modes_Pos 28 /*!< MVFR0: FP rounding modes bits Position */ #define FPU_MVFR0_FP_rounding_modes_Msk (0xFUL << FPU_MVFR0_FP_rounding_modes_Pos) /*!< MVFR0: FP rounding modes bits Mask */ #define FPU_MVFR0_Short_vectors_Pos 24 /*!< MVFR0: Short vectors bits Position */ #define FPU_MVFR0_Short_vectors_Msk (0xFUL << FPU_MVFR0_Short_vectors_Pos) /*!< MVFR0: Short vectors bits Mask */ #define FPU_MVFR0_Square_root_Pos 20 /*!< MVFR0: Square root bits Position */ #define FPU_MVFR0_Square_root_Msk (0xFUL << FPU_MVFR0_Square_root_Pos) /*!< MVFR0: Square root bits Mask */ #define FPU_MVFR0_Divide_Pos 16 /*!< MVFR0: Divide bits Position */ #define FPU_MVFR0_Divide_Msk (0xFUL << FPU_MVFR0_Divide_Pos) /*!< MVFR0: Divide bits Mask */ #define FPU_MVFR0_FP_excep_trapping_Pos 12 /*!< MVFR0: FP exception trapping bits Position */ #define FPU_MVFR0_FP_excep_trapping_Msk (0xFUL << FPU_MVFR0_FP_excep_trapping_Pos) /*!< MVFR0: FP exception trapping bits Mask */ #define FPU_MVFR0_Double_precision_Pos 8 /*!< MVFR0: Double-precision bits Position */ #define FPU_MVFR0_Double_precision_Msk (0xFUL << FPU_MVFR0_Double_precision_Pos) /*!< MVFR0: Double-precision bits Mask */ #define FPU_MVFR0_Single_precision_Pos 4 /*!< MVFR0: Single-precision bits Position */ #define FPU_MVFR0_Single_precision_Msk (0xFUL << FPU_MVFR0_Single_precision_Pos) /*!< MVFR0: Single-precision bits Mask */ #define FPU_MVFR0_A_SIMD_registers_Pos 0 /*!< MVFR0: A_SIMD registers bits Position */ #define FPU_MVFR0_A_SIMD_registers_Msk (0xFUL << FPU_MVFR0_A_SIMD_registers_Pos) /*!< MVFR0: A_SIMD registers bits Mask */ /* Media and FP Feature Register 1 */ #define FPU_MVFR1_FP_fused_MAC_Pos 28 /*!< MVFR1: FP fused MAC bits Position */ #define FPU_MVFR1_FP_fused_MAC_Msk (0xFUL << FPU_MVFR1_FP_fused_MAC_Pos) /*!< MVFR1: FP fused MAC bits Mask */ #define FPU_MVFR1_FP_HPFP_Pos 24 /*!< MVFR1: FP HPFP bits Position */ #define FPU_MVFR1_FP_HPFP_Msk (0xFUL << FPU_MVFR1_FP_HPFP_Pos) /*!< MVFR1: FP HPFP bits Mask */ #define FPU_MVFR1_D_NaN_mode_Pos 4 /*!< MVFR1: D_NaN mode bits Position */ #define FPU_MVFR1_D_NaN_mode_Msk (0xFUL << FPU_MVFR1_D_NaN_mode_Pos) /*!< MVFR1: D_NaN mode bits Mask */ #define FPU_MVFR1_FtZ_mode_Pos 0 /*!< MVFR1: FtZ mode bits Position */ #define FPU_MVFR1_FtZ_mode_Msk (0xFUL << FPU_MVFR1_FtZ_mode_Pos) /*!< MVFR1: FtZ mode bits Mask */ /*@} end of group CMSIS_FPU */ #endif /** \ingroup CMSIS_core_register \defgroup CMSIS_CoreDebug Core Debug Registers (CoreDebug) \brief Type definitions for the Core Debug Registers @{ */ /** \brief Structure type to access the Core Debug Register (CoreDebug). */ typedef struct { __IO uint32_t DHCSR; /*!< Offset: 0x000 (R/W) Debug Halting Control and Status Register */ __O uint32_t DCRSR; /*!< Offset: 0x004 ( /W) Debug Core Register Selector Register */ __IO uint32_t DCRDR; /*!< Offset: 0x008 (R/W) Debug Core Register Data Register */ __IO uint32_t DEMCR; /*!< Offset: 0x00C (R/W) Debug Exception and Monitor Control Register */ } CoreDebug_Type; /* Debug Halting Control and Status Register */ #define CoreDebug_DHCSR_DBGKEY_Pos 16 /*!< CoreDebug DHCSR: DBGKEY Position */ #define CoreDebug_DHCSR_DBGKEY_Msk (0xFFFFUL << CoreDebug_DHCSR_DBGKEY_Pos) /*!< CoreDebug DHCSR: DBGKEY Mask */ #define CoreDebug_DHCSR_S_RESET_ST_Pos 25 /*!< CoreDebug DHCSR: S_RESET_ST Position */ #define CoreDebug_DHCSR_S_RESET_ST_Msk (1UL << CoreDebug_DHCSR_S_RESET_ST_Pos) /*!< CoreDebug DHCSR: S_RESET_ST Mask */ #define CoreDebug_DHCSR_S_RETIRE_ST_Pos 24 /*!< CoreDebug DHCSR: S_RETIRE_ST Position */ #define CoreDebug_DHCSR_S_RETIRE_ST_Msk (1UL << CoreDebug_DHCSR_S_RETIRE_ST_Pos) /*!< CoreDebug DHCSR: S_RETIRE_ST Mask */ #define CoreDebug_DHCSR_S_LOCKUP_Pos 19 /*!< CoreDebug DHCSR: S_LOCKUP Position */ #define CoreDebug_DHCSR_S_LOCKUP_Msk (1UL << CoreDebug_DHCSR_S_LOCKUP_Pos) /*!< CoreDebug DHCSR: S_LOCKUP Mask */ #define CoreDebug_DHCSR_S_SLEEP_Pos 18 /*!< CoreDebug DHCSR: S_SLEEP Position */ #define CoreDebug_DHCSR_S_SLEEP_Msk (1UL << CoreDebug_DHCSR_S_SLEEP_Pos) /*!< CoreDebug DHCSR: S_SLEEP Mask */ #define CoreDebug_DHCSR_S_HALT_Pos 17 /*!< CoreDebug DHCSR: S_HALT Position */ #define CoreDebug_DHCSR_S_HALT_Msk (1UL << CoreDebug_DHCSR_S_HALT_Pos) /*!< CoreDebug DHCSR: S_HALT Mask */ #define CoreDebug_DHCSR_S_REGRDY_Pos 16 /*!< CoreDebug DHCSR: S_REGRDY Position */ #define CoreDebug_DHCSR_S_REGRDY_Msk (1UL << CoreDebug_DHCSR_S_REGRDY_Pos) /*!< CoreDebug DHCSR: S_REGRDY Mask */ #define CoreDebug_DHCSR_C_SNAPSTALL_Pos 5 /*!< CoreDebug DHCSR: C_SNAPSTALL Position */ #define CoreDebug_DHCSR_C_SNAPSTALL_Msk (1UL << CoreDebug_DHCSR_C_SNAPSTALL_Pos) /*!< CoreDebug DHCSR: C_SNAPSTALL Mask */ #define CoreDebug_DHCSR_C_MASKINTS_Pos 3 /*!< CoreDebug DHCSR: C_MASKINTS Position */ #define CoreDebug_DHCSR_C_MASKINTS_Msk (1UL << CoreDebug_DHCSR_C_MASKINTS_Pos) /*!< CoreDebug DHCSR: C_MASKINTS Mask */ #define CoreDebug_DHCSR_C_STEP_Pos 2 /*!< CoreDebug DHCSR: C_STEP Position */ #define CoreDebug_DHCSR_C_STEP_Msk (1UL << CoreDebug_DHCSR_C_STEP_Pos) /*!< CoreDebug DHCSR: C_STEP Mask */ #define CoreDebug_DHCSR_C_HALT_Pos 1 /*!< CoreDebug DHCSR: C_HALT Position */ #define CoreDebug_DHCSR_C_HALT_Msk (1UL << CoreDebug_DHCSR_C_HALT_Pos) /*!< CoreDebug DHCSR: C_HALT Mask */ #define CoreDebug_DHCSR_C_DEBUGEN_Pos 0 /*!< CoreDebug DHCSR: C_DEBUGEN Position */ #define CoreDebug_DHCSR_C_DEBUGEN_Msk (1UL << CoreDebug_DHCSR_C_DEBUGEN_Pos) /*!< CoreDebug DHCSR: C_DEBUGEN Mask */ /* Debug Core Register Selector Register */ #define CoreDebug_DCRSR_REGWnR_Pos 16 /*!< CoreDebug DCRSR: REGWnR Position */ #define CoreDebug_DCRSR_REGWnR_Msk (1UL << CoreDebug_DCRSR_REGWnR_Pos) /*!< CoreDebug DCRSR: REGWnR Mask */ #define CoreDebug_DCRSR_REGSEL_Pos 0 /*!< CoreDebug DCRSR: REGSEL Position */ #define CoreDebug_DCRSR_REGSEL_Msk (0x1FUL << CoreDebug_DCRSR_REGSEL_Pos) /*!< CoreDebug DCRSR: REGSEL Mask */ /* Debug Exception and Monitor Control Register */ #define CoreDebug_DEMCR_TRCENA_Pos 24 /*!< CoreDebug DEMCR: TRCENA Position */ #define CoreDebug_DEMCR_TRCENA_Msk (1UL << CoreDebug_DEMCR_TRCENA_Pos) /*!< CoreDebug DEMCR: TRCENA Mask */ #define CoreDebug_DEMCR_MON_REQ_Pos 19 /*!< CoreDebug DEMCR: MON_REQ Position */ #define CoreDebug_DEMCR_MON_REQ_Msk (1UL << CoreDebug_DEMCR_MON_REQ_Pos) /*!< CoreDebug DEMCR: MON_REQ Mask */ #define CoreDebug_DEMCR_MON_STEP_Pos 18 /*!< CoreDebug DEMCR: MON_STEP Position */ #define CoreDebug_DEMCR_MON_STEP_Msk (1UL << CoreDebug_DEMCR_MON_STEP_Pos) /*!< CoreDebug DEMCR: MON_STEP Mask */ #define CoreDebug_DEMCR_MON_PEND_Pos 17 /*!< CoreDebug DEMCR: MON_PEND Position */ #define CoreDebug_DEMCR_MON_PEND_Msk (1UL << CoreDebug_DEMCR_MON_PEND_Pos) /*!< CoreDebug DEMCR: MON_PEND Mask */ #define CoreDebug_DEMCR_MON_EN_Pos 16 /*!< CoreDebug DEMCR: MON_EN Position */ #define CoreDebug_DEMCR_MON_EN_Msk (1UL << CoreDebug_DEMCR_MON_EN_Pos) /*!< CoreDebug DEMCR: MON_EN Mask */ #define CoreDebug_DEMCR_VC_HARDERR_Pos 10 /*!< CoreDebug DEMCR: VC_HARDERR Position */ #define CoreDebug_DEMCR_VC_HARDERR_Msk (1UL << CoreDebug_DEMCR_VC_HARDERR_Pos) /*!< CoreDebug DEMCR: VC_HARDERR Mask */ #define CoreDebug_DEMCR_VC_INTERR_Pos 9 /*!< CoreDebug DEMCR: VC_INTERR Position */ #define CoreDebug_DEMCR_VC_INTERR_Msk (1UL << CoreDebug_DEMCR_VC_INTERR_Pos) /*!< CoreDebug DEMCR: VC_INTERR Mask */ #define CoreDebug_DEMCR_VC_BUSERR_Pos 8 /*!< CoreDebug DEMCR: VC_BUSERR Position */ #define CoreDebug_DEMCR_VC_BUSERR_Msk (1UL << CoreDebug_DEMCR_VC_BUSERR_Pos) /*!< CoreDebug DEMCR: VC_BUSERR Mask */ #define CoreDebug_DEMCR_VC_STATERR_Pos 7 /*!< CoreDebug DEMCR: VC_STATERR Position */ #define CoreDebug_DEMCR_VC_STATERR_Msk (1UL << CoreDebug_DEMCR_VC_STATERR_Pos) /*!< CoreDebug DEMCR: VC_STATERR Mask */ #define CoreDebug_DEMCR_VC_CHKERR_Pos 6 /*!< CoreDebug DEMCR: VC_CHKERR Position */ #define CoreDebug_DEMCR_VC_CHKERR_Msk (1UL << CoreDebug_DEMCR_VC_CHKERR_Pos) /*!< CoreDebug DEMCR: VC_CHKERR Mask */ #define CoreDebug_DEMCR_VC_NOCPERR_Pos 5 /*!< CoreDebug DEMCR: VC_NOCPERR Position */ #define CoreDebug_DEMCR_VC_NOCPERR_Msk (1UL << CoreDebug_DEMCR_VC_NOCPERR_Pos) /*!< CoreDebug DEMCR: VC_NOCPERR Mask */ #define CoreDebug_DEMCR_VC_MMERR_Pos 4 /*!< CoreDebug DEMCR: VC_MMERR Position */ #define CoreDebug_DEMCR_VC_MMERR_Msk (1UL << CoreDebug_DEMCR_VC_MMERR_Pos) /*!< CoreDebug DEMCR: VC_MMERR Mask */ #define CoreDebug_DEMCR_VC_CORERESET_Pos 0 /*!< CoreDebug DEMCR: VC_CORERESET Position */ #define CoreDebug_DEMCR_VC_CORERESET_Msk (1UL << CoreDebug_DEMCR_VC_CORERESET_Pos) /*!< CoreDebug DEMCR: VC_CORERESET Mask */ /*@} end of group CMSIS_CoreDebug */ /** \ingroup CMSIS_core_register \defgroup CMSIS_core_base Core Definitions \brief Definitions for base addresses, unions, and structures. @{ */ /* Memory mapping of Cortex-M4 Hardware */ #define SCS_BASE (0xE000E000UL) /*!< System Control Space Base Address */ #define ITM_BASE (0xE0000000UL) /*!< ITM Base Address */ #define DWT_BASE (0xE0001000UL) /*!< DWT Base Address */ #define TPI_BASE (0xE0040000UL) /*!< TPI Base Address */ #define CoreDebug_BASE (0xE000EDF0UL) /*!< Core Debug Base Address */ #define SysTick_BASE (SCS_BASE + 0x0010UL) /*!< SysTick Base Address */ #define NVIC_BASE (SCS_BASE + 0x0100UL) /*!< NVIC Base Address */ #define SCB_BASE (SCS_BASE + 0x0D00UL) /*!< System Control Block Base Address */ #define SCnSCB ((SCnSCB_Type *) SCS_BASE ) /*!< System control Register not in SCB */ #define SCB ((SCB_Type *) SCB_BASE ) /*!< SCB configuration struct */ #define SysTick ((SysTick_Type *) SysTick_BASE ) /*!< SysTick configuration struct */ #define NVIC ((NVIC_Type *) NVIC_BASE ) /*!< NVIC configuration struct */ #define ITM ((ITM_Type *) ITM_BASE ) /*!< ITM configuration struct */ #define DWT ((DWT_Type *) DWT_BASE ) /*!< DWT configuration struct */ #define TPI ((TPI_Type *) TPI_BASE ) /*!< TPI configuration struct */ #define CoreDebug ((CoreDebug_Type *) CoreDebug_BASE) /*!< Core Debug configuration struct */ #if (__MPU_PRESENT == 1) #define MPU_BASE (SCS_BASE + 0x0D90UL) /*!< Memory Protection Unit */ #define MPU ((MPU_Type *) MPU_BASE ) /*!< Memory Protection Unit */ #endif #if (__FPU_PRESENT == 1) #define FPU_BASE (SCS_BASE + 0x0F30UL) /*!< Floating Point Unit */ #define FPU ((FPU_Type *) FPU_BASE ) /*!< Floating Point Unit */ #endif /*@} */ /******************************************************************************* * Hardware Abstraction Layer Core Function Interface contains: - Core NVIC Functions - Core SysTick Functions - Core Debug Functions - Core Register Access Functions ******************************************************************************/ /** \defgroup CMSIS_Core_FunctionInterface Functions and Instructions Reference */ /* ########################## NVIC functions #################################### */ /** \ingroup CMSIS_Core_FunctionInterface \defgroup CMSIS_Core_NVICFunctions NVIC Functions \brief Functions that manage interrupts and exceptions via the NVIC. @{ */ /** \brief Set Priority Grouping The function sets the priority grouping field using the required unlock sequence. The parameter PriorityGroup is assigned to the field SCB->AIRCR [10:8] PRIGROUP field. Only values from 0..7 are used. In case of a conflict between priority grouping and available priority bits (__NVIC_PRIO_BITS), the smallest possible priority group is set. \param [in] PriorityGroup Priority grouping field. */ __STATIC_INLINE void NVIC_SetPriorityGrouping(uint32_t PriorityGroup) { uint32_t reg_value; uint32_t PriorityGroupTmp = (PriorityGroup & (uint32_t)0x07); /* only values 0..7 are used */ reg_value = SCB->AIRCR; /* read old register configuration */ reg_value &= ~(SCB_AIRCR_VECTKEY_Msk | SCB_AIRCR_PRIGROUP_Msk); /* clear bits to change */ reg_value = (reg_value | ((uint32_t)0x5FA << SCB_AIRCR_VECTKEY_Pos) | (PriorityGroupTmp << 8)); /* Insert write key and priorty group */ SCB->AIRCR = reg_value; } /** \brief Get Priority Grouping The function reads the priority grouping field from the NVIC Interrupt Controller. \return Priority grouping field (SCB->AIRCR [10:8] PRIGROUP field). */ __STATIC_INLINE uint32_t NVIC_GetPriorityGrouping(void) { return ((SCB->AIRCR & SCB_AIRCR_PRIGROUP_Msk) >> SCB_AIRCR_PRIGROUP_Pos); /* read priority grouping field */ } /** \brief Enable External Interrupt The function enables a device-specific interrupt in the NVIC interrupt controller. \param [in] IRQn External interrupt number. Value cannot be negative. */ __STATIC_INLINE void NVIC_EnableIRQ(IRQn_Type IRQn) { /* NVIC->ISER[((uint32_t)(IRQn) >> 5)] = (1 << ((uint32_t)(IRQn) & 0x1F)); enable interrupt */ NVIC->ISER[(uint32_t)((int32_t)IRQn) >> 5] = (uint32_t)(1 << ((uint32_t)((int32_t)IRQn) & (uint32_t)0x1F)); /* enable interrupt */ } /** \brief Disable External Interrupt The function disables a device-specific interrupt in the NVIC interrupt controller. \param [in] IRQn External interrupt number. Value cannot be negative. */ __STATIC_INLINE void NVIC_DisableIRQ(IRQn_Type IRQn) { NVIC->ICER[((uint32_t)(IRQn) >> 5)] = (1 << ((uint32_t)(IRQn) & 0x1F)); /* disable interrupt */ } /** \brief Get Pending Interrupt The function reads the pending register in the NVIC and returns the pending bit for the specified interrupt. \param [in] IRQn Interrupt number. \return 0 Interrupt status is not pending. \return 1 Interrupt status is pending. */ __STATIC_INLINE uint32_t NVIC_GetPendingIRQ(IRQn_Type IRQn) { return((uint32_t) ((NVIC->ISPR[(uint32_t)(IRQn) >> 5] & (1 << ((uint32_t)(IRQn) & 0x1F)))?1:0)); /* Return 1 if pending else 0 */ } /** \brief Set Pending Interrupt The function sets the pending bit of an external interrupt. \param [in] IRQn Interrupt number. Value cannot be negative. */ __STATIC_INLINE void NVIC_SetPendingIRQ(IRQn_Type IRQn) { NVIC->ISPR[((uint32_t)(IRQn) >> 5)] = (1 << ((uint32_t)(IRQn) & 0x1F)); /* set interrupt pending */ } /** \brief Clear Pending Interrupt The function clears the pending bit of an external interrupt. \param [in] IRQn External interrupt number. Value cannot be negative. */ __STATIC_INLINE void NVIC_ClearPendingIRQ(IRQn_Type IRQn) { NVIC->ICPR[((uint32_t)(IRQn) >> 5)] = (1 << ((uint32_t)(IRQn) & 0x1F)); /* Clear pending interrupt */ } /** \brief Get Active Interrupt The function reads the active register in NVIC and returns the active bit. \param [in] IRQn Interrupt number. \return 0 Interrupt status is not active. \return 1 Interrupt status is active. */ __STATIC_INLINE uint32_t NVIC_GetActive(IRQn_Type IRQn) { return((uint32_t)((NVIC->IABR[(uint32_t)(IRQn) >> 5] & (1 << ((uint32_t)(IRQn) & 0x1F)))?1:0)); /* Return 1 if active else 0 */ } /** \brief Set Interrupt Priority The function sets the priority of an interrupt. \note The priority cannot be set for every core interrupt. \param [in] IRQn Interrupt number. \param [in] priority Priority to set. */ __STATIC_INLINE void NVIC_SetPriority(IRQn_Type IRQn, uint32_t priority) { if(IRQn < 0) { SCB->SHP[((uint32_t)(IRQn) & 0xF)-4] = ((priority << (8 - __NVIC_PRIO_BITS)) & 0xff); } /* set Priority for Cortex-M System Interrupts */ else { NVIC->IP[(uint32_t)(IRQn)] = ((priority << (8 - __NVIC_PRIO_BITS)) & 0xff); } /* set Priority for device specific Interrupts */ } /** \brief Get Interrupt Priority The function reads the priority of an interrupt. The interrupt number can be positive to specify an external (device specific) interrupt, or negative to specify an internal (core) interrupt. \param [in] IRQn Interrupt number. \return Interrupt Priority. Value is aligned automatically to the implemented priority bits of the microcontroller. */ __STATIC_INLINE uint32_t NVIC_GetPriority(IRQn_Type IRQn) { if(IRQn < 0) { return((uint32_t)(SCB->SHP[((uint32_t)(IRQn) & 0xF)-4] >> (8 - __NVIC_PRIO_BITS))); } /* get priority for Cortex-M system interrupts */ else { return((uint32_t)(NVIC->IP[(uint32_t)(IRQn)] >> (8 - __NVIC_PRIO_BITS))); } /* get priority for device specific interrupts */ } /** \brief Encode Priority The function encodes the priority for an interrupt with the given priority group, preemptive priority value, and subpriority value. In case of a conflict between priority grouping and available priority bits (__NVIC_PRIO_BITS), the samllest possible priority group is set. \param [in] PriorityGroup Used priority group. \param [in] PreemptPriority Preemptive priority value (starting from 0). \param [in] SubPriority Subpriority value (starting from 0). \return Encoded priority. Value can be used in the function \ref NVIC_SetPriority(). */ __STATIC_INLINE uint32_t NVIC_EncodePriority (uint32_t PriorityGroup, uint32_t PreemptPriority, uint32_t SubPriority) { uint32_t PriorityGroupTmp = (PriorityGroup & 0x07); /* only values 0..7 are used */ uint32_t PreemptPriorityBits; uint32_t SubPriorityBits; PreemptPriorityBits = ((7 - PriorityGroupTmp) > __NVIC_PRIO_BITS) ? __NVIC_PRIO_BITS : 7 - PriorityGroupTmp; SubPriorityBits = ((PriorityGroupTmp + __NVIC_PRIO_BITS) < 7) ? 0 : PriorityGroupTmp - 7 + __NVIC_PRIO_BITS; return ( ((PreemptPriority & ((1 << (PreemptPriorityBits)) - 1)) << SubPriorityBits) | ((SubPriority & ((1 << (SubPriorityBits )) - 1))) ); } /** \brief Decode Priority The function decodes an interrupt priority value with a given priority group to preemptive priority value and subpriority value. In case of a conflict between priority grouping and available priority bits (__NVIC_PRIO_BITS) the samllest possible priority group is set. \param [in] Priority Priority value, which can be retrieved with the function \ref NVIC_GetPriority(). \param [in] PriorityGroup Used priority group. \param [out] pPreemptPriority Preemptive priority value (starting from 0). \param [out] pSubPriority Subpriority value (starting from 0). */ __STATIC_INLINE void NVIC_DecodePriority (uint32_t Priority, uint32_t PriorityGroup, uint32_t* pPreemptPriority, uint32_t* pSubPriority) { uint32_t PriorityGroupTmp = (PriorityGroup & 0x07); /* only values 0..7 are used */ uint32_t PreemptPriorityBits; uint32_t SubPriorityBits; PreemptPriorityBits = ((7 - PriorityGroupTmp) > __NVIC_PRIO_BITS) ? __NVIC_PRIO_BITS : 7 - PriorityGroupTmp; SubPriorityBits = ((PriorityGroupTmp + __NVIC_PRIO_BITS) < 7) ? 0 : PriorityGroupTmp - 7 + __NVIC_PRIO_BITS; *pPreemptPriority = (Priority >> SubPriorityBits) & ((1 << (PreemptPriorityBits)) - 1); *pSubPriority = (Priority ) & ((1 << (SubPriorityBits )) - 1); } /** \brief System Reset The function initiates a system reset request to reset the MCU. */ __STATIC_INLINE void NVIC_SystemReset(void) { __DSB(); /* Ensure all outstanding memory accesses included buffered write are completed before reset */ SCB->AIRCR = ((0x5FA << SCB_AIRCR_VECTKEY_Pos) | (SCB->AIRCR & SCB_AIRCR_PRIGROUP_Msk) | SCB_AIRCR_SYSRESETREQ_Msk); /* Keep priority group unchanged */ __DSB(); /* Ensure completion of memory access */ while(1); /* wait until reset */ } /*@} end of CMSIS_Core_NVICFunctions */ /* ################################## SysTick function ############################################ */ /** \ingroup CMSIS_Core_FunctionInterface \defgroup CMSIS_Core_SysTickFunctions SysTick Functions \brief Functions that configure the System. @{ */ #if (__Vendor_SysTickConfig == 0) /** \brief System Tick Configuration The function initializes the System Timer and its interrupt, and starts the System Tick Timer. Counter is in free running mode to generate periodic interrupts. \param [in] ticks Number of ticks between two interrupts. \return 0 Function succeeded. \return 1 Function failed. \note When the variable __Vendor_SysTickConfig is set to 1, then the function SysTick_Config is not included. In this case, the file device.h must contain a vendor-specific implementation of this function. */ __STATIC_INLINE uint32_t SysTick_Config(uint32_t ticks) { if ((ticks - 1) > SysTick_LOAD_RELOAD_Msk) return (1); /* Reload value impossible */ SysTick->LOAD = ticks - 1; /* set reload register */ NVIC_SetPriority (SysTick_IRQn, (1<<__NVIC_PRIO_BITS) - 1); /* set Priority for Systick Interrupt */ SysTick->VAL = 0; /* Load the SysTick Counter Value */ SysTick->CTRL = SysTick_CTRL_CLKSOURCE_Msk | SysTick_CTRL_TICKINT_Msk | SysTick_CTRL_ENABLE_Msk; /* Enable SysTick IRQ and SysTick Timer */ return (0); /* Function successful */ } #endif /*@} end of CMSIS_Core_SysTickFunctions */ /* ##################################### Debug In/Output function ########################################### */ /** \ingroup CMSIS_Core_FunctionInterface \defgroup CMSIS_core_DebugFunctions ITM Functions \brief Functions that access the ITM debug interface. @{ */ extern volatile int32_t ITM_RxBuffer; /*!< External variable to receive characters. */ #define ITM_RXBUFFER_EMPTY 0x5AA55AA5 /*!< Value identifying \ref ITM_RxBuffer is ready for next character. */ /** \brief ITM Send Character The function transmits a character via the ITM channel 0, and \li Just returns when no debugger is connected that has booked the output. \li Is blocking when a debugger is connected, but the previous character sent has not been transmitted. \param [in] ch Character to transmit. \returns Character to transmit. */ __STATIC_INLINE uint32_t ITM_SendChar (uint32_t ch) { if ((ITM->TCR & ITM_TCR_ITMENA_Msk) && /* ITM enabled */ (ITM->TER & (1UL << 0) ) ) /* ITM Port #0 enabled */ { while (ITM->PORT[0].u32 == 0); ITM->PORT[0].u8 = (uint8_t) ch; } return (ch); } /** \brief ITM Receive Character The function inputs a character via the external variable \ref ITM_RxBuffer. \return Received character. \return -1 No character pending. */ __STATIC_INLINE int32_t ITM_ReceiveChar (void) { int32_t ch = -1; /* no character available */ if (ITM_RxBuffer != ITM_RXBUFFER_EMPTY) { ch = ITM_RxBuffer; ITM_RxBuffer = ITM_RXBUFFER_EMPTY; /* ready for next character */ } return (ch); } /** \brief ITM Check Character The function checks whether a character is pending for reading in the variable \ref ITM_RxBuffer. \return 0 No character available. \return 1 Character available. */ __STATIC_INLINE int32_t ITM_CheckChar (void) { if (ITM_RxBuffer == ITM_RXBUFFER_EMPTY) { return (0); /* no character available */ } else { return (1); /* character available */ } } /*@} end of CMSIS_core_DebugFunctions */ #endif /* __CORE_CM4_H_DEPENDANT */ #endif /* __CMSIS_GENERIC */ #ifdef __cplusplus } #endif ================================================ FILE: Zelig/mbed/TARGET_LPC1768/core_cm4_simd.h ================================================ /**************************************************************************//** * @file core_cm4_simd.h * @brief CMSIS Cortex-M4 SIMD Header File * @version V3.20 * @date 25. February 2013 * * @note * ******************************************************************************/ /* Copyright (c) 2009 - 2013 ARM LIMITED All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: - Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. - Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. - Neither the name of ARM 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 COPYRIGHT HOLDERS AND CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. ---------------------------------------------------------------------------*/ #ifdef __cplusplus extern "C" { #endif #ifndef __CORE_CM4_SIMD_H #define __CORE_CM4_SIMD_H /******************************************************************************* * Hardware Abstraction Layer ******************************************************************************/ /* ################### Compiler specific Intrinsics ########################### */ /** \defgroup CMSIS_SIMD_intrinsics CMSIS SIMD Intrinsics Access to dedicated SIMD instructions @{ */ #if defined ( __CC_ARM ) /*------------------RealView Compiler -----------------*/ /* ARM armcc specific functions */ /*------ CM4 SIMD Intrinsics -----------------------------------------------------*/ #define __SADD8 __sadd8 #define __QADD8 __qadd8 #define __SHADD8 __shadd8 #define __UADD8 __uadd8 #define __UQADD8 __uqadd8 #define __UHADD8 __uhadd8 #define __SSUB8 __ssub8 #define __QSUB8 __qsub8 #define __SHSUB8 __shsub8 #define __USUB8 __usub8 #define __UQSUB8 __uqsub8 #define __UHSUB8 __uhsub8 #define __SADD16 __sadd16 #define __QADD16 __qadd16 #define __SHADD16 __shadd16 #define __UADD16 __uadd16 #define __UQADD16 __uqadd16 #define __UHADD16 __uhadd16 #define __SSUB16 __ssub16 #define __QSUB16 __qsub16 #define __SHSUB16 __shsub16 #define __USUB16 __usub16 #define __UQSUB16 __uqsub16 #define __UHSUB16 __uhsub16 #define __SASX __sasx #define __QASX __qasx #define __SHASX __shasx #define __UASX __uasx #define __UQASX __uqasx #define __UHASX __uhasx #define __SSAX __ssax #define __QSAX __qsax #define __SHSAX __shsax #define __USAX __usax #define __UQSAX __uqsax #define __UHSAX __uhsax #define __USAD8 __usad8 #define __USADA8 __usada8 #define __SSAT16 __ssat16 #define __USAT16 __usat16 #define __UXTB16 __uxtb16 #define __UXTAB16 __uxtab16 #define __SXTB16 __sxtb16 #define __SXTAB16 __sxtab16 #define __SMUAD __smuad #define __SMUADX __smuadx #define __SMLAD __smlad #define __SMLADX __smladx #define __SMLALD __smlald #define __SMLALDX __smlaldx #define __SMUSD __smusd #define __SMUSDX __smusdx #define __SMLSD __smlsd #define __SMLSDX __smlsdx #define __SMLSLD __smlsld #define __SMLSLDX __smlsldx #define __SEL __sel #define __QADD __qadd #define __QSUB __qsub #define __PKHBT(ARG1,ARG2,ARG3) ( ((((uint32_t)(ARG1)) ) & 0x0000FFFFUL) | \ ((((uint32_t)(ARG2)) << (ARG3)) & 0xFFFF0000UL) ) #define __PKHTB(ARG1,ARG2,ARG3) ( ((((uint32_t)(ARG1)) ) & 0xFFFF0000UL) | \ ((((uint32_t)(ARG2)) >> (ARG3)) & 0x0000FFFFUL) ) #define __SMMLA(ARG1,ARG2,ARG3) ( (int32_t)((((int64_t)(ARG1) * (ARG2)) + \ ((int64_t)(ARG3) << 32) ) >> 32)) /*-- End CM4 SIMD Intrinsics -----------------------------------------------------*/ #elif defined ( __ICCARM__ ) /*------------------ ICC Compiler -------------------*/ /* IAR iccarm specific functions */ /*------ CM4 SIMD Intrinsics -----------------------------------------------------*/ #include /*-- End CM4 SIMD Intrinsics -----------------------------------------------------*/ #elif defined ( __TMS470__ ) /*---------------- TI CCS Compiler ------------------*/ /* TI CCS specific functions */ /*------ CM4 SIMD Intrinsics -----------------------------------------------------*/ #include /*-- End CM4 SIMD Intrinsics -----------------------------------------------------*/ #elif defined ( __GNUC__ ) /*------------------ GNU Compiler ---------------------*/ /* GNU gcc specific functions */ /*------ CM4 SIMD Intrinsics -----------------------------------------------------*/ __attribute__( ( always_inline ) ) __STATIC_INLINE uint32_t __SADD8(uint32_t op1, uint32_t op2) { uint32_t result; __ASM volatile ("sadd8 %0, %1, %2" : "=r" (result) : "r" (op1), "r" (op2) ); return(result); } __attribute__( ( always_inline ) ) __STATIC_INLINE uint32_t __QADD8(uint32_t op1, uint32_t op2) { uint32_t result; __ASM volatile ("qadd8 %0, %1, %2" : "=r" (result) : "r" (op1), "r" (op2) ); return(result); } __attribute__( ( always_inline ) ) __STATIC_INLINE uint32_t __SHADD8(uint32_t op1, uint32_t op2) { uint32_t result; __ASM volatile ("shadd8 %0, %1, %2" : "=r" (result) : "r" (op1), "r" (op2) ); return(result); } __attribute__( ( always_inline ) ) __STATIC_INLINE uint32_t __UADD8(uint32_t op1, uint32_t op2) { uint32_t result; __ASM volatile ("uadd8 %0, %1, %2" : "=r" (result) : "r" (op1), "r" (op2) ); return(result); } __attribute__( ( always_inline ) ) __STATIC_INLINE uint32_t __UQADD8(uint32_t op1, uint32_t op2) { uint32_t result; __ASM volatile ("uqadd8 %0, %1, %2" : "=r" (result) : "r" (op1), "r" (op2) ); return(result); } __attribute__( ( always_inline ) ) __STATIC_INLINE uint32_t __UHADD8(uint32_t op1, uint32_t op2) { uint32_t result; __ASM volatile ("uhadd8 %0, %1, %2" : "=r" (result) : "r" (op1), "r" (op2) ); return(result); } __attribute__( ( always_inline ) ) __STATIC_INLINE uint32_t __SSUB8(uint32_t op1, uint32_t op2) { uint32_t result; __ASM volatile ("ssub8 %0, %1, %2" : "=r" (result) : "r" (op1), "r" (op2) ); return(result); } __attribute__( ( always_inline ) ) __STATIC_INLINE uint32_t __QSUB8(uint32_t op1, uint32_t op2) { uint32_t result; __ASM volatile ("qsub8 %0, %1, %2" : "=r" (result) : "r" (op1), "r" (op2) ); return(result); } __attribute__( ( always_inline ) ) __STATIC_INLINE uint32_t __SHSUB8(uint32_t op1, uint32_t op2) { uint32_t result; __ASM volatile ("shsub8 %0, %1, %2" : "=r" (result) : "r" (op1), "r" (op2) ); return(result); } __attribute__( ( always_inline ) ) __STATIC_INLINE uint32_t __USUB8(uint32_t op1, uint32_t op2) { uint32_t result; __ASM volatile ("usub8 %0, %1, %2" : "=r" (result) : "r" (op1), "r" (op2) ); return(result); } __attribute__( ( always_inline ) ) __STATIC_INLINE uint32_t __UQSUB8(uint32_t op1, uint32_t op2) { uint32_t result; __ASM volatile ("uqsub8 %0, %1, %2" : "=r" (result) : "r" (op1), "r" (op2) ); return(result); } __attribute__( ( always_inline ) ) __STATIC_INLINE uint32_t __UHSUB8(uint32_t op1, uint32_t op2) { uint32_t result; __ASM volatile ("uhsub8 %0, %1, %2" : "=r" (result) : "r" (op1), "r" (op2) ); return(result); } __attribute__( ( always_inline ) ) __STATIC_INLINE uint32_t __SADD16(uint32_t op1, uint32_t op2) { uint32_t result; __ASM volatile ("sadd16 %0, %1, %2" : "=r" (result) : "r" (op1), "r" (op2) ); return(result); } __attribute__( ( always_inline ) ) __STATIC_INLINE uint32_t __QADD16(uint32_t op1, uint32_t op2) { uint32_t result; __ASM volatile ("qadd16 %0, %1, %2" : "=r" (result) : "r" (op1), "r" (op2) ); return(result); } __attribute__( ( always_inline ) ) __STATIC_INLINE uint32_t __SHADD16(uint32_t op1, uint32_t op2) { uint32_t result; __ASM volatile ("shadd16 %0, %1, %2" : "=r" (result) : "r" (op1), "r" (op2) ); return(result); } __attribute__( ( always_inline ) ) __STATIC_INLINE uint32_t __UADD16(uint32_t op1, uint32_t op2) { uint32_t result; __ASM volatile ("uadd16 %0, %1, %2" : "=r" (result) : "r" (op1), "r" (op2) ); return(result); } __attribute__( ( always_inline ) ) __STATIC_INLINE uint32_t __UQADD16(uint32_t op1, uint32_t op2) { uint32_t result; __ASM volatile ("uqadd16 %0, %1, %2" : "=r" (result) : "r" (op1), "r" (op2) ); return(result); } __attribute__( ( always_inline ) ) __STATIC_INLINE uint32_t __UHADD16(uint32_t op1, uint32_t op2) { uint32_t result; __ASM volatile ("uhadd16 %0, %1, %2" : "=r" (result) : "r" (op1), "r" (op2) ); return(result); } __attribute__( ( always_inline ) ) __STATIC_INLINE uint32_t __SSUB16(uint32_t op1, uint32_t op2) { uint32_t result; __ASM volatile ("ssub16 %0, %1, %2" : "=r" (result) : "r" (op1), "r" (op2) ); return(result); } __attribute__( ( always_inline ) ) __STATIC_INLINE uint32_t __QSUB16(uint32_t op1, uint32_t op2) { uint32_t result; __ASM volatile ("qsub16 %0, %1, %2" : "=r" (result) : "r" (op1), "r" (op2) ); return(result); } __attribute__( ( always_inline ) ) __STATIC_INLINE uint32_t __SHSUB16(uint32_t op1, uint32_t op2) { uint32_t result; __ASM volatile ("shsub16 %0, %1, %2" : "=r" (result) : "r" (op1), "r" (op2) ); return(result); } __attribute__( ( always_inline ) ) __STATIC_INLINE uint32_t __USUB16(uint32_t op1, uint32_t op2) { uint32_t result; __ASM volatile ("usub16 %0, %1, %2" : "=r" (result) : "r" (op1), "r" (op2) ); return(result); } __attribute__( ( always_inline ) ) __STATIC_INLINE uint32_t __UQSUB16(uint32_t op1, uint32_t op2) { uint32_t result; __ASM volatile ("uqsub16 %0, %1, %2" : "=r" (result) : "r" (op1), "r" (op2) ); return(result); } __attribute__( ( always_inline ) ) __STATIC_INLINE uint32_t __UHSUB16(uint32_t op1, uint32_t op2) { uint32_t result; __ASM volatile ("uhsub16 %0, %1, %2" : "=r" (result) : "r" (op1), "r" (op2) ); return(result); } __attribute__( ( always_inline ) ) __STATIC_INLINE uint32_t __SASX(uint32_t op1, uint32_t op2) { uint32_t result; __ASM volatile ("sasx %0, %1, %2" : "=r" (result) : "r" (op1), "r" (op2) ); return(result); } __attribute__( ( always_inline ) ) __STATIC_INLINE uint32_t __QASX(uint32_t op1, uint32_t op2) { uint32_t result; __ASM volatile ("qasx %0, %1, %2" : "=r" (result) : "r" (op1), "r" (op2) ); return(result); } __attribute__( ( always_inline ) ) __STATIC_INLINE uint32_t __SHASX(uint32_t op1, uint32_t op2) { uint32_t result; __ASM volatile ("shasx %0, %1, %2" : "=r" (result) : "r" (op1), "r" (op2) ); return(result); } __attribute__( ( always_inline ) ) __STATIC_INLINE uint32_t __UASX(uint32_t op1, uint32_t op2) { uint32_t result; __ASM volatile ("uasx %0, %1, %2" : "=r" (result) : "r" (op1), "r" (op2) ); return(result); } __attribute__( ( always_inline ) ) __STATIC_INLINE uint32_t __UQASX(uint32_t op1, uint32_t op2) { uint32_t result; __ASM volatile ("uqasx %0, %1, %2" : "=r" (result) : "r" (op1), "r" (op2) ); return(result); } __attribute__( ( always_inline ) ) __STATIC_INLINE uint32_t __UHASX(uint32_t op1, uint32_t op2) { uint32_t result; __ASM volatile ("uhasx %0, %1, %2" : "=r" (result) : "r" (op1), "r" (op2) ); return(result); } __attribute__( ( always_inline ) ) __STATIC_INLINE uint32_t __SSAX(uint32_t op1, uint32_t op2) { uint32_t result; __ASM volatile ("ssax %0, %1, %2" : "=r" (result) : "r" (op1), "r" (op2) ); return(result); } __attribute__( ( always_inline ) ) __STATIC_INLINE uint32_t __QSAX(uint32_t op1, uint32_t op2) { uint32_t result; __ASM volatile ("qsax %0, %1, %2" : "=r" (result) : "r" (op1), "r" (op2) ); return(result); } __attribute__( ( always_inline ) ) __STATIC_INLINE uint32_t __SHSAX(uint32_t op1, uint32_t op2) { uint32_t result; __ASM volatile ("shsax %0, %1, %2" : "=r" (result) : "r" (op1), "r" (op2) ); return(result); } __attribute__( ( always_inline ) ) __STATIC_INLINE uint32_t __USAX(uint32_t op1, uint32_t op2) { uint32_t result; __ASM volatile ("usax %0, %1, %2" : "=r" (result) : "r" (op1), "r" (op2) ); return(result); } __attribute__( ( always_inline ) ) __STATIC_INLINE uint32_t __UQSAX(uint32_t op1, uint32_t op2) { uint32_t result; __ASM volatile ("uqsax %0, %1, %2" : "=r" (result) : "r" (op1), "r" (op2) ); return(result); } __attribute__( ( always_inline ) ) __STATIC_INLINE uint32_t __UHSAX(uint32_t op1, uint32_t op2) { uint32_t result; __ASM volatile ("uhsax %0, %1, %2" : "=r" (result) : "r" (op1), "r" (op2) ); return(result); } __attribute__( ( always_inline ) ) __STATIC_INLINE uint32_t __USAD8(uint32_t op1, uint32_t op2) { uint32_t result; __ASM volatile ("usad8 %0, %1, %2" : "=r" (result) : "r" (op1), "r" (op2) ); return(result); } __attribute__( ( always_inline ) ) __STATIC_INLINE uint32_t __USADA8(uint32_t op1, uint32_t op2, uint32_t op3) { uint32_t result; __ASM volatile ("usada8 %0, %1, %2, %3" : "=r" (result) : "r" (op1), "r" (op2), "r" (op3) ); return(result); } #define __SSAT16(ARG1,ARG2) \ ({ \ uint32_t __RES, __ARG1 = (ARG1); \ __ASM ("ssat16 %0, %1, %2" : "=r" (__RES) : "I" (ARG2), "r" (__ARG1) ); \ __RES; \ }) #define __USAT16(ARG1,ARG2) \ ({ \ uint32_t __RES, __ARG1 = (ARG1); \ __ASM ("usat16 %0, %1, %2" : "=r" (__RES) : "I" (ARG2), "r" (__ARG1) ); \ __RES; \ }) __attribute__( ( always_inline ) ) __STATIC_INLINE uint32_t __UXTB16(uint32_t op1) { uint32_t result; __ASM volatile ("uxtb16 %0, %1" : "=r" (result) : "r" (op1)); return(result); } __attribute__( ( always_inline ) ) __STATIC_INLINE uint32_t __UXTAB16(uint32_t op1, uint32_t op2) { uint32_t result; __ASM volatile ("uxtab16 %0, %1, %2" : "=r" (result) : "r" (op1), "r" (op2) ); return(result); } __attribute__( ( always_inline ) ) __STATIC_INLINE uint32_t __SXTB16(uint32_t op1) { uint32_t result; __ASM volatile ("sxtb16 %0, %1" : "=r" (result) : "r" (op1)); return(result); } __attribute__( ( always_inline ) ) __STATIC_INLINE uint32_t __SXTAB16(uint32_t op1, uint32_t op2) { uint32_t result; __ASM volatile ("sxtab16 %0, %1, %2" : "=r" (result) : "r" (op1), "r" (op2) ); return(result); } __attribute__( ( always_inline ) ) __STATIC_INLINE uint32_t __SMUAD (uint32_t op1, uint32_t op2) { uint32_t result; __ASM volatile ("smuad %0, %1, %2" : "=r" (result) : "r" (op1), "r" (op2) ); return(result); } __attribute__( ( always_inline ) ) __STATIC_INLINE uint32_t __SMUADX (uint32_t op1, uint32_t op2) { uint32_t result; __ASM volatile ("smuadx %0, %1, %2" : "=r" (result) : "r" (op1), "r" (op2) ); return(result); } __attribute__( ( always_inline ) ) __STATIC_INLINE uint32_t __SMLAD (uint32_t op1, uint32_t op2, uint32_t op3) { uint32_t result; __ASM volatile ("smlad %0, %1, %2, %3" : "=r" (result) : "r" (op1), "r" (op2), "r" (op3) ); return(result); } __attribute__( ( always_inline ) ) __STATIC_INLINE uint32_t __SMLADX (uint32_t op1, uint32_t op2, uint32_t op3) { uint32_t result; __ASM volatile ("smladx %0, %1, %2, %3" : "=r" (result) : "r" (op1), "r" (op2), "r" (op3) ); return(result); } #define __SMLALD(ARG1,ARG2,ARG3) \ ({ \ uint32_t __ARG1 = (ARG1), __ARG2 = (ARG2), __ARG3_H = (uint32_t)((uint64_t)(ARG3) >> 32), __ARG3_L = (uint32_t)((uint64_t)(ARG3) & 0xFFFFFFFFUL); \ __ASM volatile ("smlald %0, %1, %2, %3" : "=r" (__ARG3_L), "=r" (__ARG3_H) : "r" (__ARG1), "r" (__ARG2), "0" (__ARG3_L), "1" (__ARG3_H) ); \ (uint64_t)(((uint64_t)__ARG3_H << 32) | __ARG3_L); \ }) #define __SMLALDX(ARG1,ARG2,ARG3) \ ({ \ uint32_t __ARG1 = (ARG1), __ARG2 = (ARG2), __ARG3_H = (uint32_t)((uint64_t)(ARG3) >> 32), __ARG3_L = (uint32_t)((uint64_t)(ARG3) & 0xFFFFFFFFUL); \ __ASM volatile ("smlaldx %0, %1, %2, %3" : "=r" (__ARG3_L), "=r" (__ARG3_H) : "r" (__ARG1), "r" (__ARG2), "0" (__ARG3_L), "1" (__ARG3_H) ); \ (uint64_t)(((uint64_t)__ARG3_H << 32) | __ARG3_L); \ }) __attribute__( ( always_inline ) ) __STATIC_INLINE uint32_t __SMUSD (uint32_t op1, uint32_t op2) { uint32_t result; __ASM volatile ("smusd %0, %1, %2" : "=r" (result) : "r" (op1), "r" (op2) ); return(result); } __attribute__( ( always_inline ) ) __STATIC_INLINE uint32_t __SMUSDX (uint32_t op1, uint32_t op2) { uint32_t result; __ASM volatile ("smusdx %0, %1, %2" : "=r" (result) : "r" (op1), "r" (op2) ); return(result); } __attribute__( ( always_inline ) ) __STATIC_INLINE uint32_t __SMLSD (uint32_t op1, uint32_t op2, uint32_t op3) { uint32_t result; __ASM volatile ("smlsd %0, %1, %2, %3" : "=r" (result) : "r" (op1), "r" (op2), "r" (op3) ); return(result); } __attribute__( ( always_inline ) ) __STATIC_INLINE uint32_t __SMLSDX (uint32_t op1, uint32_t op2, uint32_t op3) { uint32_t result; __ASM volatile ("smlsdx %0, %1, %2, %3" : "=r" (result) : "r" (op1), "r" (op2), "r" (op3) ); return(result); } #define __SMLSLD(ARG1,ARG2,ARG3) \ ({ \ uint32_t __ARG1 = (ARG1), __ARG2 = (ARG2), __ARG3_H = (uint32_t)((ARG3) >> 32), __ARG3_L = (uint32_t)((ARG3) & 0xFFFFFFFFUL); \ __ASM volatile ("smlsld %0, %1, %2, %3" : "=r" (__ARG3_L), "=r" (__ARG3_H) : "r" (__ARG1), "r" (__ARG2), "0" (__ARG3_L), "1" (__ARG3_H) ); \ (uint64_t)(((uint64_t)__ARG3_H << 32) | __ARG3_L); \ }) #define __SMLSLDX(ARG1,ARG2,ARG3) \ ({ \ uint32_t __ARG1 = (ARG1), __ARG2 = (ARG2), __ARG3_H = (uint32_t)((ARG3) >> 32), __ARG3_L = (uint32_t)((ARG3) & 0xFFFFFFFFUL); \ __ASM volatile ("smlsldx %0, %1, %2, %3" : "=r" (__ARG3_L), "=r" (__ARG3_H) : "r" (__ARG1), "r" (__ARG2), "0" (__ARG3_L), "1" (__ARG3_H) ); \ (uint64_t)(((uint64_t)__ARG3_H << 32) | __ARG3_L); \ }) __attribute__( ( always_inline ) ) __STATIC_INLINE uint32_t __SEL (uint32_t op1, uint32_t op2) { uint32_t result; __ASM volatile ("sel %0, %1, %2" : "=r" (result) : "r" (op1), "r" (op2) ); return(result); } __attribute__( ( always_inline ) ) __STATIC_INLINE uint32_t __QADD(uint32_t op1, uint32_t op2) { uint32_t result; __ASM volatile ("qadd %0, %1, %2" : "=r" (result) : "r" (op1), "r" (op2) ); return(result); } __attribute__( ( always_inline ) ) __STATIC_INLINE uint32_t __QSUB(uint32_t op1, uint32_t op2) { uint32_t result; __ASM volatile ("qsub %0, %1, %2" : "=r" (result) : "r" (op1), "r" (op2) ); return(result); } #define __PKHBT(ARG1,ARG2,ARG3) \ ({ \ uint32_t __RES, __ARG1 = (ARG1), __ARG2 = (ARG2); \ __ASM ("pkhbt %0, %1, %2, lsl %3" : "=r" (__RES) : "r" (__ARG1), "r" (__ARG2), "I" (ARG3) ); \ __RES; \ }) #define __PKHTB(ARG1,ARG2,ARG3) \ ({ \ uint32_t __RES, __ARG1 = (ARG1), __ARG2 = (ARG2); \ if (ARG3 == 0) \ __ASM ("pkhtb %0, %1, %2" : "=r" (__RES) : "r" (__ARG1), "r" (__ARG2) ); \ else \ __ASM ("pkhtb %0, %1, %2, asr %3" : "=r" (__RES) : "r" (__ARG1), "r" (__ARG2), "I" (ARG3) ); \ __RES; \ }) __attribute__( ( always_inline ) ) __STATIC_INLINE uint32_t __SMMLA (int32_t op1, int32_t op2, int32_t op3) { int32_t result; __ASM volatile ("smmla %0, %1, %2, %3" : "=r" (result): "r" (op1), "r" (op2), "r" (op3) ); return(result); } /*-- End CM4 SIMD Intrinsics -----------------------------------------------------*/ #elif defined ( __TASKING__ ) /*------------------ TASKING Compiler --------------*/ /* TASKING carm specific functions */ /*------ CM4 SIMD Intrinsics -----------------------------------------------------*/ /* not yet supported */ /*-- End CM4 SIMD Intrinsics -----------------------------------------------------*/ #endif /*@} end of group CMSIS_SIMD_intrinsics */ #endif /* __CORE_CM4_SIMD_H */ #ifdef __cplusplus } #endif ================================================ FILE: Zelig/mbed/TARGET_LPC1768/core_cm7.h ================================================ /**************************************************************************//** * @file core_cm7.h * @brief CMSIS Cortex-M7 Core Peripheral Access Layer Header File * @version V4.10 * @date 18. March 2015 * * @note * ******************************************************************************/ /* Copyright (c) 2009 - 2015 ARM LIMITED All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: - Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. - Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. - Neither the name of ARM 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 COPYRIGHT HOLDERS AND 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. ---------------------------------------------------------------------------*/ #if defined ( __ICCARM__ ) #pragma system_include /* treat file as system include file for MISRA check */ #endif #ifndef __CORE_CM7_H_GENERIC #define __CORE_CM7_H_GENERIC #ifdef __cplusplus extern "C" { #endif /** \page CMSIS_MISRA_Exceptions MISRA-C:2004 Compliance Exceptions CMSIS violates the following MISRA-C:2004 rules: \li Required Rule 8.5, object/function definition in header file.
Function definitions in header files are used to allow 'inlining'. \li Required Rule 18.4, declaration of union type or object of union type: '{...}'.
Unions are used for effective representation of core registers. \li Advisory Rule 19.7, Function-like macro defined.
Function-like macros are used to allow more efficient code. */ /******************************************************************************* * CMSIS definitions ******************************************************************************/ /** \ingroup Cortex_M7 @{ */ /* CMSIS CM7 definitions */ #define __CM7_CMSIS_VERSION_MAIN (0x04) /*!< [31:16] CMSIS HAL main version */ #define __CM7_CMSIS_VERSION_SUB (0x00) /*!< [15:0] CMSIS HAL sub version */ #define __CM7_CMSIS_VERSION ((__CM7_CMSIS_VERSION_MAIN << 16) | \ __CM7_CMSIS_VERSION_SUB ) /*!< CMSIS HAL version number */ #define __CORTEX_M (0x07) /*!< Cortex-M Core */ #if defined ( __CC_ARM ) #define __ASM __asm /*!< asm keyword for ARM Compiler */ #define __INLINE __inline /*!< inline keyword for ARM Compiler */ #define __STATIC_INLINE static __inline #elif defined ( __GNUC__ ) #define __ASM __asm /*!< asm keyword for GNU Compiler */ #define __INLINE inline /*!< inline keyword for GNU Compiler */ #define __STATIC_INLINE static inline #elif defined ( __ICCARM__ ) #define __ASM __asm /*!< asm keyword for IAR Compiler */ #define __INLINE inline /*!< inline keyword for IAR Compiler. Only available in High optimization mode! */ #define __STATIC_INLINE static inline #elif defined ( __TMS470__ ) #define __ASM __asm /*!< asm keyword for TI CCS Compiler */ #define __STATIC_INLINE static inline #elif defined ( __TASKING__ ) #define __ASM __asm /*!< asm keyword for TASKING Compiler */ #define __INLINE inline /*!< inline keyword for TASKING Compiler */ #define __STATIC_INLINE static inline #elif defined ( __CSMC__ ) #define __packed #define __ASM _asm /*!< asm keyword for COSMIC Compiler */ #define __INLINE inline /*use -pc99 on compile line !< inline keyword for COSMIC Compiler */ #define __STATIC_INLINE static inline #endif /** __FPU_USED indicates whether an FPU is used or not. For this, __FPU_PRESENT has to be checked prior to making use of FPU specific registers and functions. */ #if defined ( __CC_ARM ) #if defined __TARGET_FPU_VFP #if (__FPU_PRESENT == 1) #define __FPU_USED 1 #else #warning "Compiler generates FPU instructions for a device without an FPU (check __FPU_PRESENT)" #define __FPU_USED 0 #endif #else #define __FPU_USED 0 #endif #elif defined ( __GNUC__ ) #if defined (__VFP_FP__) && !defined(__SOFTFP__) #if (__FPU_PRESENT == 1) #define __FPU_USED 1 #else #warning "Compiler generates FPU instructions for a device without an FPU (check __FPU_PRESENT)" #define __FPU_USED 0 #endif #else #define __FPU_USED 0 #endif #elif defined ( __ICCARM__ ) #if defined __ARMVFP__ #if (__FPU_PRESENT == 1) #define __FPU_USED 1 #else #warning "Compiler generates FPU instructions for a device without an FPU (check __FPU_PRESENT)" #define __FPU_USED 0 #endif #else #define __FPU_USED 0 #endif #elif defined ( __TMS470__ ) #if defined __TI_VFP_SUPPORT__ #if (__FPU_PRESENT == 1) #define __FPU_USED 1 #else #warning "Compiler generates FPU instructions for a device without an FPU (check __FPU_PRESENT)" #define __FPU_USED 0 #endif #else #define __FPU_USED 0 #endif #elif defined ( __TASKING__ ) #if defined __FPU_VFP__ #if (__FPU_PRESENT == 1) #define __FPU_USED 1 #else #error "Compiler generates FPU instructions for a device without an FPU (check __FPU_PRESENT)" #define __FPU_USED 0 #endif #else #define __FPU_USED 0 #endif #elif defined ( __CSMC__ ) /* Cosmic */ #if ( __CSMC__ & 0x400) // FPU present for parser #if (__FPU_PRESENT == 1) #define __FPU_USED 1 #else #error "Compiler generates FPU instructions for a device without an FPU (check __FPU_PRESENT)" #define __FPU_USED 0 #endif #else #define __FPU_USED 0 #endif #endif #include /* standard types definitions */ #include /* Core Instruction Access */ #include /* Core Function Access */ #include /* Compiler specific SIMD Intrinsics */ #ifdef __cplusplus } #endif #endif /* __CORE_CM7_H_GENERIC */ #ifndef __CMSIS_GENERIC #ifndef __CORE_CM7_H_DEPENDANT #define __CORE_CM7_H_DEPENDANT #ifdef __cplusplus extern "C" { #endif /* check device defines and use defaults */ #if defined __CHECK_DEVICE_DEFINES #ifndef __CM7_REV #define __CM7_REV 0x0000 #warning "__CM7_REV not defined in device header file; using default!" #endif #ifndef __FPU_PRESENT #define __FPU_PRESENT 0 #warning "__FPU_PRESENT not defined in device header file; using default!" #endif #ifndef __MPU_PRESENT #define __MPU_PRESENT 0 #warning "__MPU_PRESENT not defined in device header file; using default!" #endif #ifndef __ICACHE_PRESENT #define __ICACHE_PRESENT 0 #warning "__ICACHE_PRESENT not defined in device header file; using default!" #endif #ifndef __DCACHE_PRESENT #define __DCACHE_PRESENT 0 #warning "__DCACHE_PRESENT not defined in device header file; using default!" #endif #ifndef __DTCM_PRESENT #define __DTCM_PRESENT 0 #warning "__DTCM_PRESENT not defined in device header file; using default!" #endif #ifndef __NVIC_PRIO_BITS #define __NVIC_PRIO_BITS 3 #warning "__NVIC_PRIO_BITS not defined in device header file; using default!" #endif #ifndef __Vendor_SysTickConfig #define __Vendor_SysTickConfig 0 #warning "__Vendor_SysTickConfig not defined in device header file; using default!" #endif #endif /* IO definitions (access restrictions to peripheral registers) */ /** \defgroup CMSIS_glob_defs CMSIS Global Defines IO Type Qualifiers are used \li to specify the access to peripheral variables. \li for automatic generation of peripheral register debug information. */ #ifdef __cplusplus #define __I volatile /*!< Defines 'read only' permissions */ #else #define __I volatile const /*!< Defines 'read only' permissions */ #endif #define __O volatile /*!< Defines 'write only' permissions */ #define __IO volatile /*!< Defines 'read / write' permissions */ /*@} end of group Cortex_M7 */ /******************************************************************************* * Register Abstraction Core Register contain: - Core Register - Core NVIC Register - Core SCB Register - Core SysTick Register - Core Debug Register - Core MPU Register - Core FPU Register ******************************************************************************/ /** \defgroup CMSIS_core_register Defines and Type Definitions \brief Type definitions and defines for Cortex-M processor based devices. */ /** \ingroup CMSIS_core_register \defgroup CMSIS_CORE Status and Control Registers \brief Core Register type definitions. @{ */ /** \brief Union type to access the Application Program Status Register (APSR). */ typedef union { struct { uint32_t _reserved0:16; /*!< bit: 0..15 Reserved */ uint32_t GE:4; /*!< bit: 16..19 Greater than or Equal flags */ uint32_t _reserved1:7; /*!< bit: 20..26 Reserved */ uint32_t Q:1; /*!< bit: 27 Saturation condition flag */ uint32_t V:1; /*!< bit: 28 Overflow condition code flag */ uint32_t C:1; /*!< bit: 29 Carry condition code flag */ uint32_t Z:1; /*!< bit: 30 Zero condition code flag */ uint32_t N:1; /*!< bit: 31 Negative condition code flag */ } b; /*!< Structure used for bit access */ uint32_t w; /*!< Type used for word access */ } APSR_Type; /* APSR Register Definitions */ #define APSR_N_Pos 31 /*!< APSR: N Position */ #define APSR_N_Msk (1UL << APSR_N_Pos) /*!< APSR: N Mask */ #define APSR_Z_Pos 30 /*!< APSR: Z Position */ #define APSR_Z_Msk (1UL << APSR_Z_Pos) /*!< APSR: Z Mask */ #define APSR_C_Pos 29 /*!< APSR: C Position */ #define APSR_C_Msk (1UL << APSR_C_Pos) /*!< APSR: C Mask */ #define APSR_V_Pos 28 /*!< APSR: V Position */ #define APSR_V_Msk (1UL << APSR_V_Pos) /*!< APSR: V Mask */ #define APSR_Q_Pos 27 /*!< APSR: Q Position */ #define APSR_Q_Msk (1UL << APSR_Q_Pos) /*!< APSR: Q Mask */ #define APSR_GE_Pos 16 /*!< APSR: GE Position */ #define APSR_GE_Msk (0xFUL << APSR_GE_Pos) /*!< APSR: GE Mask */ /** \brief Union type to access the Interrupt Program Status Register (IPSR). */ typedef union { struct { uint32_t ISR:9; /*!< bit: 0.. 8 Exception number */ uint32_t _reserved0:23; /*!< bit: 9..31 Reserved */ } b; /*!< Structure used for bit access */ uint32_t w; /*!< Type used for word access */ } IPSR_Type; /* IPSR Register Definitions */ #define IPSR_ISR_Pos 0 /*!< IPSR: ISR Position */ #define IPSR_ISR_Msk (0x1FFUL /*<< IPSR_ISR_Pos*/) /*!< IPSR: ISR Mask */ /** \brief Union type to access the Special-Purpose Program Status Registers (xPSR). */ typedef union { struct { uint32_t ISR:9; /*!< bit: 0.. 8 Exception number */ uint32_t _reserved0:7; /*!< bit: 9..15 Reserved */ uint32_t GE:4; /*!< bit: 16..19 Greater than or Equal flags */ uint32_t _reserved1:4; /*!< bit: 20..23 Reserved */ uint32_t T:1; /*!< bit: 24 Thumb bit (read 0) */ uint32_t IT:2; /*!< bit: 25..26 saved IT state (read 0) */ uint32_t Q:1; /*!< bit: 27 Saturation condition flag */ uint32_t V:1; /*!< bit: 28 Overflow condition code flag */ uint32_t C:1; /*!< bit: 29 Carry condition code flag */ uint32_t Z:1; /*!< bit: 30 Zero condition code flag */ uint32_t N:1; /*!< bit: 31 Negative condition code flag */ } b; /*!< Structure used for bit access */ uint32_t w; /*!< Type used for word access */ } xPSR_Type; /* xPSR Register Definitions */ #define xPSR_N_Pos 31 /*!< xPSR: N Position */ #define xPSR_N_Msk (1UL << xPSR_N_Pos) /*!< xPSR: N Mask */ #define xPSR_Z_Pos 30 /*!< xPSR: Z Position */ #define xPSR_Z_Msk (1UL << xPSR_Z_Pos) /*!< xPSR: Z Mask */ #define xPSR_C_Pos 29 /*!< xPSR: C Position */ #define xPSR_C_Msk (1UL << xPSR_C_Pos) /*!< xPSR: C Mask */ #define xPSR_V_Pos 28 /*!< xPSR: V Position */ #define xPSR_V_Msk (1UL << xPSR_V_Pos) /*!< xPSR: V Mask */ #define xPSR_Q_Pos 27 /*!< xPSR: Q Position */ #define xPSR_Q_Msk (1UL << xPSR_Q_Pos) /*!< xPSR: Q Mask */ #define xPSR_IT_Pos 25 /*!< xPSR: IT Position */ #define xPSR_IT_Msk (3UL << xPSR_IT_Pos) /*!< xPSR: IT Mask */ #define xPSR_T_Pos 24 /*!< xPSR: T Position */ #define xPSR_T_Msk (1UL << xPSR_T_Pos) /*!< xPSR: T Mask */ #define xPSR_GE_Pos 16 /*!< xPSR: GE Position */ #define xPSR_GE_Msk (0xFUL << xPSR_GE_Pos) /*!< xPSR: GE Mask */ #define xPSR_ISR_Pos 0 /*!< xPSR: ISR Position */ #define xPSR_ISR_Msk (0x1FFUL /*<< xPSR_ISR_Pos*/) /*!< xPSR: ISR Mask */ /** \brief Union type to access the Control Registers (CONTROL). */ typedef union { struct { uint32_t nPRIV:1; /*!< bit: 0 Execution privilege in Thread mode */ uint32_t SPSEL:1; /*!< bit: 1 Stack to be used */ uint32_t FPCA:1; /*!< bit: 2 FP extension active flag */ uint32_t _reserved0:29; /*!< bit: 3..31 Reserved */ } b; /*!< Structure used for bit access */ uint32_t w; /*!< Type used for word access */ } CONTROL_Type; /* CONTROL Register Definitions */ #define CONTROL_FPCA_Pos 2 /*!< CONTROL: FPCA Position */ #define CONTROL_FPCA_Msk (1UL << CONTROL_FPCA_Pos) /*!< CONTROL: FPCA Mask */ #define CONTROL_SPSEL_Pos 1 /*!< CONTROL: SPSEL Position */ #define CONTROL_SPSEL_Msk (1UL << CONTROL_SPSEL_Pos) /*!< CONTROL: SPSEL Mask */ #define CONTROL_nPRIV_Pos 0 /*!< CONTROL: nPRIV Position */ #define CONTROL_nPRIV_Msk (1UL /*<< CONTROL_nPRIV_Pos*/) /*!< CONTROL: nPRIV Mask */ /*@} end of group CMSIS_CORE */ /** \ingroup CMSIS_core_register \defgroup CMSIS_NVIC Nested Vectored Interrupt Controller (NVIC) \brief Type definitions for the NVIC Registers @{ */ /** \brief Structure type to access the Nested Vectored Interrupt Controller (NVIC). */ typedef struct { __IO uint32_t ISER[8]; /*!< Offset: 0x000 (R/W) Interrupt Set Enable Register */ uint32_t RESERVED0[24]; __IO uint32_t ICER[8]; /*!< Offset: 0x080 (R/W) Interrupt Clear Enable Register */ uint32_t RSERVED1[24]; __IO uint32_t ISPR[8]; /*!< Offset: 0x100 (R/W) Interrupt Set Pending Register */ uint32_t RESERVED2[24]; __IO uint32_t ICPR[8]; /*!< Offset: 0x180 (R/W) Interrupt Clear Pending Register */ uint32_t RESERVED3[24]; __IO uint32_t IABR[8]; /*!< Offset: 0x200 (R/W) Interrupt Active bit Register */ uint32_t RESERVED4[56]; __IO uint8_t IP[240]; /*!< Offset: 0x300 (R/W) Interrupt Priority Register (8Bit wide) */ uint32_t RESERVED5[644]; __O uint32_t STIR; /*!< Offset: 0xE00 ( /W) Software Trigger Interrupt Register */ } NVIC_Type; /* Software Triggered Interrupt Register Definitions */ #define NVIC_STIR_INTID_Pos 0 /*!< STIR: INTLINESNUM Position */ #define NVIC_STIR_INTID_Msk (0x1FFUL /*<< NVIC_STIR_INTID_Pos*/) /*!< STIR: INTLINESNUM Mask */ /*@} end of group CMSIS_NVIC */ /** \ingroup CMSIS_core_register \defgroup CMSIS_SCB System Control Block (SCB) \brief Type definitions for the System Control Block Registers @{ */ /** \brief Structure type to access the System Control Block (SCB). */ typedef struct { __I uint32_t CPUID; /*!< Offset: 0x000 (R/ ) CPUID Base Register */ __IO uint32_t ICSR; /*!< Offset: 0x004 (R/W) Interrupt Control and State Register */ __IO uint32_t VTOR; /*!< Offset: 0x008 (R/W) Vector Table Offset Register */ __IO uint32_t AIRCR; /*!< Offset: 0x00C (R/W) Application Interrupt and Reset Control Register */ __IO uint32_t SCR; /*!< Offset: 0x010 (R/W) System Control Register */ __IO uint32_t CCR; /*!< Offset: 0x014 (R/W) Configuration Control Register */ __IO uint8_t SHPR[12]; /*!< Offset: 0x018 (R/W) System Handlers Priority Registers (4-7, 8-11, 12-15) */ __IO uint32_t SHCSR; /*!< Offset: 0x024 (R/W) System Handler Control and State Register */ __IO uint32_t CFSR; /*!< Offset: 0x028 (R/W) Configurable Fault Status Register */ __IO uint32_t HFSR; /*!< Offset: 0x02C (R/W) HardFault Status Register */ __IO uint32_t DFSR; /*!< Offset: 0x030 (R/W) Debug Fault Status Register */ __IO uint32_t MMFAR; /*!< Offset: 0x034 (R/W) MemManage Fault Address Register */ __IO uint32_t BFAR; /*!< Offset: 0x038 (R/W) BusFault Address Register */ __IO uint32_t AFSR; /*!< Offset: 0x03C (R/W) Auxiliary Fault Status Register */ __I uint32_t ID_PFR[2]; /*!< Offset: 0x040 (R/ ) Processor Feature Register */ __I uint32_t ID_DFR; /*!< Offset: 0x048 (R/ ) Debug Feature Register */ __I uint32_t ID_AFR; /*!< Offset: 0x04C (R/ ) Auxiliary Feature Register */ __I uint32_t ID_MFR[4]; /*!< Offset: 0x050 (R/ ) Memory Model Feature Register */ __I uint32_t ID_ISAR[5]; /*!< Offset: 0x060 (R/ ) Instruction Set Attributes Register */ uint32_t RESERVED0[1]; __I uint32_t CLIDR; /*!< Offset: 0x078 (R/ ) Cache Level ID register */ __I uint32_t CTR; /*!< Offset: 0x07C (R/ ) Cache Type register */ __I uint32_t CCSIDR; /*!< Offset: 0x080 (R/ ) Cache Size ID Register */ __IO uint32_t CSSELR; /*!< Offset: 0x084 (R/W) Cache Size Selection Register */ __IO uint32_t CPACR; /*!< Offset: 0x088 (R/W) Coprocessor Access Control Register */ uint32_t RESERVED3[93]; __O uint32_t STIR; /*!< Offset: 0x200 ( /W) Software Triggered Interrupt Register */ uint32_t RESERVED4[15]; __I uint32_t MVFR0; /*!< Offset: 0x240 (R/ ) Media and VFP Feature Register 0 */ __I uint32_t MVFR1; /*!< Offset: 0x244 (R/ ) Media and VFP Feature Register 1 */ __I uint32_t MVFR2; /*!< Offset: 0x248 (R/ ) Media and VFP Feature Register 1 */ uint32_t RESERVED5[1]; __O uint32_t ICIALLU; /*!< Offset: 0x250 ( /W) I-Cache Invalidate All to PoU */ uint32_t RESERVED6[1]; __O uint32_t ICIMVAU; /*!< Offset: 0x258 ( /W) I-Cache Invalidate by MVA to PoU */ __O uint32_t DCIMVAC; /*!< Offset: 0x25C ( /W) D-Cache Invalidate by MVA to PoC */ __O uint32_t DCISW; /*!< Offset: 0x260 ( /W) D-Cache Invalidate by Set-way */ __O uint32_t DCCMVAU; /*!< Offset: 0x264 ( /W) D-Cache Clean by MVA to PoU */ __O uint32_t DCCMVAC; /*!< Offset: 0x268 ( /W) D-Cache Clean by MVA to PoC */ __O uint32_t DCCSW; /*!< Offset: 0x26C ( /W) D-Cache Clean by Set-way */ __O uint32_t DCCIMVAC; /*!< Offset: 0x270 ( /W) D-Cache Clean and Invalidate by MVA to PoC */ __O uint32_t DCCISW; /*!< Offset: 0x274 ( /W) D-Cache Clean and Invalidate by Set-way */ uint32_t RESERVED7[6]; __IO uint32_t ITCMCR; /*!< Offset: 0x290 (R/W) Instruction Tightly-Coupled Memory Control Register */ __IO uint32_t DTCMCR; /*!< Offset: 0x294 (R/W) Data Tightly-Coupled Memory Control Registers */ __IO uint32_t AHBPCR; /*!< Offset: 0x298 (R/W) AHBP Control Register */ __IO uint32_t CACR; /*!< Offset: 0x29C (R/W) L1 Cache Control Register */ __IO uint32_t AHBSCR; /*!< Offset: 0x2A0 (R/W) AHB Slave Control Register */ uint32_t RESERVED8[1]; __IO uint32_t ABFSR; /*!< Offset: 0x2A8 (R/W) Auxiliary Bus Fault Status Register */ } SCB_Type; /* SCB CPUID Register Definitions */ #define SCB_CPUID_IMPLEMENTER_Pos 24 /*!< SCB CPUID: IMPLEMENTER Position */ #define SCB_CPUID_IMPLEMENTER_Msk (0xFFUL << SCB_CPUID_IMPLEMENTER_Pos) /*!< SCB CPUID: IMPLEMENTER Mask */ #define SCB_CPUID_VARIANT_Pos 20 /*!< SCB CPUID: VARIANT Position */ #define SCB_CPUID_VARIANT_Msk (0xFUL << SCB_CPUID_VARIANT_Pos) /*!< SCB CPUID: VARIANT Mask */ #define SCB_CPUID_ARCHITECTURE_Pos 16 /*!< SCB CPUID: ARCHITECTURE Position */ #define SCB_CPUID_ARCHITECTURE_Msk (0xFUL << SCB_CPUID_ARCHITECTURE_Pos) /*!< SCB CPUID: ARCHITECTURE Mask */ #define SCB_CPUID_PARTNO_Pos 4 /*!< SCB CPUID: PARTNO Position */ #define SCB_CPUID_PARTNO_Msk (0xFFFUL << SCB_CPUID_PARTNO_Pos) /*!< SCB CPUID: PARTNO Mask */ #define SCB_CPUID_REVISION_Pos 0 /*!< SCB CPUID: REVISION Position */ #define SCB_CPUID_REVISION_Msk (0xFUL /*<< SCB_CPUID_REVISION_Pos*/) /*!< SCB CPUID: REVISION Mask */ /* SCB Interrupt Control State Register Definitions */ #define SCB_ICSR_NMIPENDSET_Pos 31 /*!< SCB ICSR: NMIPENDSET Position */ #define SCB_ICSR_NMIPENDSET_Msk (1UL << SCB_ICSR_NMIPENDSET_Pos) /*!< SCB ICSR: NMIPENDSET Mask */ #define SCB_ICSR_PENDSVSET_Pos 28 /*!< SCB ICSR: PENDSVSET Position */ #define SCB_ICSR_PENDSVSET_Msk (1UL << SCB_ICSR_PENDSVSET_Pos) /*!< SCB ICSR: PENDSVSET Mask */ #define SCB_ICSR_PENDSVCLR_Pos 27 /*!< SCB ICSR: PENDSVCLR Position */ #define SCB_ICSR_PENDSVCLR_Msk (1UL << SCB_ICSR_PENDSVCLR_Pos) /*!< SCB ICSR: PENDSVCLR Mask */ #define SCB_ICSR_PENDSTSET_Pos 26 /*!< SCB ICSR: PENDSTSET Position */ #define SCB_ICSR_PENDSTSET_Msk (1UL << SCB_ICSR_PENDSTSET_Pos) /*!< SCB ICSR: PENDSTSET Mask */ #define SCB_ICSR_PENDSTCLR_Pos 25 /*!< SCB ICSR: PENDSTCLR Position */ #define SCB_ICSR_PENDSTCLR_Msk (1UL << SCB_ICSR_PENDSTCLR_Pos) /*!< SCB ICSR: PENDSTCLR Mask */ #define SCB_ICSR_ISRPREEMPT_Pos 23 /*!< SCB ICSR: ISRPREEMPT Position */ #define SCB_ICSR_ISRPREEMPT_Msk (1UL << SCB_ICSR_ISRPREEMPT_Pos) /*!< SCB ICSR: ISRPREEMPT Mask */ #define SCB_ICSR_ISRPENDING_Pos 22 /*!< SCB ICSR: ISRPENDING Position */ #define SCB_ICSR_ISRPENDING_Msk (1UL << SCB_ICSR_ISRPENDING_Pos) /*!< SCB ICSR: ISRPENDING Mask */ #define SCB_ICSR_VECTPENDING_Pos 12 /*!< SCB ICSR: VECTPENDING Position */ #define SCB_ICSR_VECTPENDING_Msk (0x1FFUL << SCB_ICSR_VECTPENDING_Pos) /*!< SCB ICSR: VECTPENDING Mask */ #define SCB_ICSR_RETTOBASE_Pos 11 /*!< SCB ICSR: RETTOBASE Position */ #define SCB_ICSR_RETTOBASE_Msk (1UL << SCB_ICSR_RETTOBASE_Pos) /*!< SCB ICSR: RETTOBASE Mask */ #define SCB_ICSR_VECTACTIVE_Pos 0 /*!< SCB ICSR: VECTACTIVE Position */ #define SCB_ICSR_VECTACTIVE_Msk (0x1FFUL /*<< SCB_ICSR_VECTACTIVE_Pos*/) /*!< SCB ICSR: VECTACTIVE Mask */ /* SCB Vector Table Offset Register Definitions */ #define SCB_VTOR_TBLOFF_Pos 7 /*!< SCB VTOR: TBLOFF Position */ #define SCB_VTOR_TBLOFF_Msk (0x1FFFFFFUL << SCB_VTOR_TBLOFF_Pos) /*!< SCB VTOR: TBLOFF Mask */ /* SCB Application Interrupt and Reset Control Register Definitions */ #define SCB_AIRCR_VECTKEY_Pos 16 /*!< SCB AIRCR: VECTKEY Position */ #define SCB_AIRCR_VECTKEY_Msk (0xFFFFUL << SCB_AIRCR_VECTKEY_Pos) /*!< SCB AIRCR: VECTKEY Mask */ #define SCB_AIRCR_VECTKEYSTAT_Pos 16 /*!< SCB AIRCR: VECTKEYSTAT Position */ #define SCB_AIRCR_VECTKEYSTAT_Msk (0xFFFFUL << SCB_AIRCR_VECTKEYSTAT_Pos) /*!< SCB AIRCR: VECTKEYSTAT Mask */ #define SCB_AIRCR_ENDIANESS_Pos 15 /*!< SCB AIRCR: ENDIANESS Position */ #define SCB_AIRCR_ENDIANESS_Msk (1UL << SCB_AIRCR_ENDIANESS_Pos) /*!< SCB AIRCR: ENDIANESS Mask */ #define SCB_AIRCR_PRIGROUP_Pos 8 /*!< SCB AIRCR: PRIGROUP Position */ #define SCB_AIRCR_PRIGROUP_Msk (7UL << SCB_AIRCR_PRIGROUP_Pos) /*!< SCB AIRCR: PRIGROUP Mask */ #define SCB_AIRCR_SYSRESETREQ_Pos 2 /*!< SCB AIRCR: SYSRESETREQ Position */ #define SCB_AIRCR_SYSRESETREQ_Msk (1UL << SCB_AIRCR_SYSRESETREQ_Pos) /*!< SCB AIRCR: SYSRESETREQ Mask */ #define SCB_AIRCR_VECTCLRACTIVE_Pos 1 /*!< SCB AIRCR: VECTCLRACTIVE Position */ #define SCB_AIRCR_VECTCLRACTIVE_Msk (1UL << SCB_AIRCR_VECTCLRACTIVE_Pos) /*!< SCB AIRCR: VECTCLRACTIVE Mask */ #define SCB_AIRCR_VECTRESET_Pos 0 /*!< SCB AIRCR: VECTRESET Position */ #define SCB_AIRCR_VECTRESET_Msk (1UL /*<< SCB_AIRCR_VECTRESET_Pos*/) /*!< SCB AIRCR: VECTRESET Mask */ /* SCB System Control Register Definitions */ #define SCB_SCR_SEVONPEND_Pos 4 /*!< SCB SCR: SEVONPEND Position */ #define SCB_SCR_SEVONPEND_Msk (1UL << SCB_SCR_SEVONPEND_Pos) /*!< SCB SCR: SEVONPEND Mask */ #define SCB_SCR_SLEEPDEEP_Pos 2 /*!< SCB SCR: SLEEPDEEP Position */ #define SCB_SCR_SLEEPDEEP_Msk (1UL << SCB_SCR_SLEEPDEEP_Pos) /*!< SCB SCR: SLEEPDEEP Mask */ #define SCB_SCR_SLEEPONEXIT_Pos 1 /*!< SCB SCR: SLEEPONEXIT Position */ #define SCB_SCR_SLEEPONEXIT_Msk (1UL << SCB_SCR_SLEEPONEXIT_Pos) /*!< SCB SCR: SLEEPONEXIT Mask */ /* SCB Configuration Control Register Definitions */ #define SCB_CCR_BP_Pos 18 /*!< SCB CCR: Branch prediction enable bit Position */ #define SCB_CCR_BP_Msk (1UL << SCB_CCR_BP_Pos) /*!< SCB CCR: Branch prediction enable bit Mask */ #define SCB_CCR_IC_Pos 17 /*!< SCB CCR: Instruction cache enable bit Position */ #define SCB_CCR_IC_Msk (1UL << SCB_CCR_IC_Pos) /*!< SCB CCR: Instruction cache enable bit Mask */ #define SCB_CCR_DC_Pos 16 /*!< SCB CCR: Cache enable bit Position */ #define SCB_CCR_DC_Msk (1UL << SCB_CCR_DC_Pos) /*!< SCB CCR: Cache enable bit Mask */ #define SCB_CCR_STKALIGN_Pos 9 /*!< SCB CCR: STKALIGN Position */ #define SCB_CCR_STKALIGN_Msk (1UL << SCB_CCR_STKALIGN_Pos) /*!< SCB CCR: STKALIGN Mask */ #define SCB_CCR_BFHFNMIGN_Pos 8 /*!< SCB CCR: BFHFNMIGN Position */ #define SCB_CCR_BFHFNMIGN_Msk (1UL << SCB_CCR_BFHFNMIGN_Pos) /*!< SCB CCR: BFHFNMIGN Mask */ #define SCB_CCR_DIV_0_TRP_Pos 4 /*!< SCB CCR: DIV_0_TRP Position */ #define SCB_CCR_DIV_0_TRP_Msk (1UL << SCB_CCR_DIV_0_TRP_Pos) /*!< SCB CCR: DIV_0_TRP Mask */ #define SCB_CCR_UNALIGN_TRP_Pos 3 /*!< SCB CCR: UNALIGN_TRP Position */ #define SCB_CCR_UNALIGN_TRP_Msk (1UL << SCB_CCR_UNALIGN_TRP_Pos) /*!< SCB CCR: UNALIGN_TRP Mask */ #define SCB_CCR_USERSETMPEND_Pos 1 /*!< SCB CCR: USERSETMPEND Position */ #define SCB_CCR_USERSETMPEND_Msk (1UL << SCB_CCR_USERSETMPEND_Pos) /*!< SCB CCR: USERSETMPEND Mask */ #define SCB_CCR_NONBASETHRDENA_Pos 0 /*!< SCB CCR: NONBASETHRDENA Position */ #define SCB_CCR_NONBASETHRDENA_Msk (1UL /*<< SCB_CCR_NONBASETHRDENA_Pos*/) /*!< SCB CCR: NONBASETHRDENA Mask */ /* SCB System Handler Control and State Register Definitions */ #define SCB_SHCSR_USGFAULTENA_Pos 18 /*!< SCB SHCSR: USGFAULTENA Position */ #define SCB_SHCSR_USGFAULTENA_Msk (1UL << SCB_SHCSR_USGFAULTENA_Pos) /*!< SCB SHCSR: USGFAULTENA Mask */ #define SCB_SHCSR_BUSFAULTENA_Pos 17 /*!< SCB SHCSR: BUSFAULTENA Position */ #define SCB_SHCSR_BUSFAULTENA_Msk (1UL << SCB_SHCSR_BUSFAULTENA_Pos) /*!< SCB SHCSR: BUSFAULTENA Mask */ #define SCB_SHCSR_MEMFAULTENA_Pos 16 /*!< SCB SHCSR: MEMFAULTENA Position */ #define SCB_SHCSR_MEMFAULTENA_Msk (1UL << SCB_SHCSR_MEMFAULTENA_Pos) /*!< SCB SHCSR: MEMFAULTENA Mask */ #define SCB_SHCSR_SVCALLPENDED_Pos 15 /*!< SCB SHCSR: SVCALLPENDED Position */ #define SCB_SHCSR_SVCALLPENDED_Msk (1UL << SCB_SHCSR_SVCALLPENDED_Pos) /*!< SCB SHCSR: SVCALLPENDED Mask */ #define SCB_SHCSR_BUSFAULTPENDED_Pos 14 /*!< SCB SHCSR: BUSFAULTPENDED Position */ #define SCB_SHCSR_BUSFAULTPENDED_Msk (1UL << SCB_SHCSR_BUSFAULTPENDED_Pos) /*!< SCB SHCSR: BUSFAULTPENDED Mask */ #define SCB_SHCSR_MEMFAULTPENDED_Pos 13 /*!< SCB SHCSR: MEMFAULTPENDED Position */ #define SCB_SHCSR_MEMFAULTPENDED_Msk (1UL << SCB_SHCSR_MEMFAULTPENDED_Pos) /*!< SCB SHCSR: MEMFAULTPENDED Mask */ #define SCB_SHCSR_USGFAULTPENDED_Pos 12 /*!< SCB SHCSR: USGFAULTPENDED Position */ #define SCB_SHCSR_USGFAULTPENDED_Msk (1UL << SCB_SHCSR_USGFAULTPENDED_Pos) /*!< SCB SHCSR: USGFAULTPENDED Mask */ #define SCB_SHCSR_SYSTICKACT_Pos 11 /*!< SCB SHCSR: SYSTICKACT Position */ #define SCB_SHCSR_SYSTICKACT_Msk (1UL << SCB_SHCSR_SYSTICKACT_Pos) /*!< SCB SHCSR: SYSTICKACT Mask */ #define SCB_SHCSR_PENDSVACT_Pos 10 /*!< SCB SHCSR: PENDSVACT Position */ #define SCB_SHCSR_PENDSVACT_Msk (1UL << SCB_SHCSR_PENDSVACT_Pos) /*!< SCB SHCSR: PENDSVACT Mask */ #define SCB_SHCSR_MONITORACT_Pos 8 /*!< SCB SHCSR: MONITORACT Position */ #define SCB_SHCSR_MONITORACT_Msk (1UL << SCB_SHCSR_MONITORACT_Pos) /*!< SCB SHCSR: MONITORACT Mask */ #define SCB_SHCSR_SVCALLACT_Pos 7 /*!< SCB SHCSR: SVCALLACT Position */ #define SCB_SHCSR_SVCALLACT_Msk (1UL << SCB_SHCSR_SVCALLACT_Pos) /*!< SCB SHCSR: SVCALLACT Mask */ #define SCB_SHCSR_USGFAULTACT_Pos 3 /*!< SCB SHCSR: USGFAULTACT Position */ #define SCB_SHCSR_USGFAULTACT_Msk (1UL << SCB_SHCSR_USGFAULTACT_Pos) /*!< SCB SHCSR: USGFAULTACT Mask */ #define SCB_SHCSR_BUSFAULTACT_Pos 1 /*!< SCB SHCSR: BUSFAULTACT Position */ #define SCB_SHCSR_BUSFAULTACT_Msk (1UL << SCB_SHCSR_BUSFAULTACT_Pos) /*!< SCB SHCSR: BUSFAULTACT Mask */ #define SCB_SHCSR_MEMFAULTACT_Pos 0 /*!< SCB SHCSR: MEMFAULTACT Position */ #define SCB_SHCSR_MEMFAULTACT_Msk (1UL /*<< SCB_SHCSR_MEMFAULTACT_Pos*/) /*!< SCB SHCSR: MEMFAULTACT Mask */ /* SCB Configurable Fault Status Registers Definitions */ #define SCB_CFSR_USGFAULTSR_Pos 16 /*!< SCB CFSR: Usage Fault Status Register Position */ #define SCB_CFSR_USGFAULTSR_Msk (0xFFFFUL << SCB_CFSR_USGFAULTSR_Pos) /*!< SCB CFSR: Usage Fault Status Register Mask */ #define SCB_CFSR_BUSFAULTSR_Pos 8 /*!< SCB CFSR: Bus Fault Status Register Position */ #define SCB_CFSR_BUSFAULTSR_Msk (0xFFUL << SCB_CFSR_BUSFAULTSR_Pos) /*!< SCB CFSR: Bus Fault Status Register Mask */ #define SCB_CFSR_MEMFAULTSR_Pos 0 /*!< SCB CFSR: Memory Manage Fault Status Register Position */ #define SCB_CFSR_MEMFAULTSR_Msk (0xFFUL /*<< SCB_CFSR_MEMFAULTSR_Pos*/) /*!< SCB CFSR: Memory Manage Fault Status Register Mask */ /* SCB Hard Fault Status Registers Definitions */ #define SCB_HFSR_DEBUGEVT_Pos 31 /*!< SCB HFSR: DEBUGEVT Position */ #define SCB_HFSR_DEBUGEVT_Msk (1UL << SCB_HFSR_DEBUGEVT_Pos) /*!< SCB HFSR: DEBUGEVT Mask */ #define SCB_HFSR_FORCED_Pos 30 /*!< SCB HFSR: FORCED Position */ #define SCB_HFSR_FORCED_Msk (1UL << SCB_HFSR_FORCED_Pos) /*!< SCB HFSR: FORCED Mask */ #define SCB_HFSR_VECTTBL_Pos 1 /*!< SCB HFSR: VECTTBL Position */ #define SCB_HFSR_VECTTBL_Msk (1UL << SCB_HFSR_VECTTBL_Pos) /*!< SCB HFSR: VECTTBL Mask */ /* SCB Debug Fault Status Register Definitions */ #define SCB_DFSR_EXTERNAL_Pos 4 /*!< SCB DFSR: EXTERNAL Position */ #define SCB_DFSR_EXTERNAL_Msk (1UL << SCB_DFSR_EXTERNAL_Pos) /*!< SCB DFSR: EXTERNAL Mask */ #define SCB_DFSR_VCATCH_Pos 3 /*!< SCB DFSR: VCATCH Position */ #define SCB_DFSR_VCATCH_Msk (1UL << SCB_DFSR_VCATCH_Pos) /*!< SCB DFSR: VCATCH Mask */ #define SCB_DFSR_DWTTRAP_Pos 2 /*!< SCB DFSR: DWTTRAP Position */ #define SCB_DFSR_DWTTRAP_Msk (1UL << SCB_DFSR_DWTTRAP_Pos) /*!< SCB DFSR: DWTTRAP Mask */ #define SCB_DFSR_BKPT_Pos 1 /*!< SCB DFSR: BKPT Position */ #define SCB_DFSR_BKPT_Msk (1UL << SCB_DFSR_BKPT_Pos) /*!< SCB DFSR: BKPT Mask */ #define SCB_DFSR_HALTED_Pos 0 /*!< SCB DFSR: HALTED Position */ #define SCB_DFSR_HALTED_Msk (1UL /*<< SCB_DFSR_HALTED_Pos*/) /*!< SCB DFSR: HALTED Mask */ /* Cache Level ID register */ #define SCB_CLIDR_LOUU_Pos 27 /*!< SCB CLIDR: LoUU Position */ #define SCB_CLIDR_LOUU_Msk (7UL << SCB_CLIDR_LOUU_Pos) /*!< SCB CLIDR: LoUU Mask */ #define SCB_CLIDR_LOC_Pos 24 /*!< SCB CLIDR: LoC Position */ #define SCB_CLIDR_LOC_Msk (7UL << SCB_CLIDR_FORMAT_Pos) /*!< SCB CLIDR: LoC Mask */ /* Cache Type register */ #define SCB_CTR_FORMAT_Pos 29 /*!< SCB CTR: Format Position */ #define SCB_CTR_FORMAT_Msk (7UL << SCB_CTR_FORMAT_Pos) /*!< SCB CTR: Format Mask */ #define SCB_CTR_CWG_Pos 24 /*!< SCB CTR: CWG Position */ #define SCB_CTR_CWG_Msk (0xFUL << SCB_CTR_CWG_Pos) /*!< SCB CTR: CWG Mask */ #define SCB_CTR_ERG_Pos 20 /*!< SCB CTR: ERG Position */ #define SCB_CTR_ERG_Msk (0xFUL << SCB_CTR_ERG_Pos) /*!< SCB CTR: ERG Mask */ #define SCB_CTR_DMINLINE_Pos 16 /*!< SCB CTR: DminLine Position */ #define SCB_CTR_DMINLINE_Msk (0xFUL << SCB_CTR_DMINLINE_Pos) /*!< SCB CTR: DminLine Mask */ #define SCB_CTR_IMINLINE_Pos 0 /*!< SCB CTR: ImInLine Position */ #define SCB_CTR_IMINLINE_Msk (0xFUL /*<< SCB_CTR_IMINLINE_Pos*/) /*!< SCB CTR: ImInLine Mask */ /* Cache Size ID Register */ #define SCB_CCSIDR_WT_Pos 31 /*!< SCB CCSIDR: WT Position */ #define SCB_CCSIDR_WT_Msk (7UL << SCB_CCSIDR_WT_Pos) /*!< SCB CCSIDR: WT Mask */ #define SCB_CCSIDR_WB_Pos 30 /*!< SCB CCSIDR: WB Position */ #define SCB_CCSIDR_WB_Msk (7UL << SCB_CCSIDR_WB_Pos) /*!< SCB CCSIDR: WB Mask */ #define SCB_CCSIDR_RA_Pos 29 /*!< SCB CCSIDR: RA Position */ #define SCB_CCSIDR_RA_Msk (7UL << SCB_CCSIDR_RA_Pos) /*!< SCB CCSIDR: RA Mask */ #define SCB_CCSIDR_WA_Pos 28 /*!< SCB CCSIDR: WA Position */ #define SCB_CCSIDR_WA_Msk (7UL << SCB_CCSIDR_WA_Pos) /*!< SCB CCSIDR: WA Mask */ #define SCB_CCSIDR_NUMSETS_Pos 13 /*!< SCB CCSIDR: NumSets Position */ #define SCB_CCSIDR_NUMSETS_Msk (0x7FFFUL << SCB_CCSIDR_NUMSETS_Pos) /*!< SCB CCSIDR: NumSets Mask */ #define SCB_CCSIDR_ASSOCIATIVITY_Pos 3 /*!< SCB CCSIDR: Associativity Position */ #define SCB_CCSIDR_ASSOCIATIVITY_Msk (0x3FFUL << SCB_CCSIDR_ASSOCIATIVITY_Pos) /*!< SCB CCSIDR: Associativity Mask */ #define SCB_CCSIDR_LINESIZE_Pos 0 /*!< SCB CCSIDR: LineSize Position */ #define SCB_CCSIDR_LINESIZE_Msk (7UL /*<< SCB_CCSIDR_LINESIZE_Pos*/) /*!< SCB CCSIDR: LineSize Mask */ /* Cache Size Selection Register */ #define SCB_CSSELR_LEVEL_Pos 1 /*!< SCB CSSELR: Level Position */ #define SCB_CSSELR_LEVEL_Msk (7UL << SCB_CSSELR_LEVEL_Pos) /*!< SCB CSSELR: Level Mask */ #define SCB_CSSELR_IND_Pos 0 /*!< SCB CSSELR: InD Position */ #define SCB_CSSELR_IND_Msk (1UL /*<< SCB_CSSELR_IND_Pos*/) /*!< SCB CSSELR: InD Mask */ /* SCB Software Triggered Interrupt Register */ #define SCB_STIR_INTID_Pos 0 /*!< SCB STIR: INTID Position */ #define SCB_STIR_INTID_Msk (0x1FFUL /*<< SCB_STIR_INTID_Pos*/) /*!< SCB STIR: INTID Mask */ /* Instruction Tightly-Coupled Memory Control Register*/ #define SCB_ITCMCR_SZ_Pos 3 /*!< SCB ITCMCR: SZ Position */ #define SCB_ITCMCR_SZ_Msk (0xFUL << SCB_ITCMCR_SZ_Pos) /*!< SCB ITCMCR: SZ Mask */ #define SCB_ITCMCR_RETEN_Pos 2 /*!< SCB ITCMCR: RETEN Position */ #define SCB_ITCMCR_RETEN_Msk (1UL << SCB_ITCMCR_RETEN_Pos) /*!< SCB ITCMCR: RETEN Mask */ #define SCB_ITCMCR_RMW_Pos 1 /*!< SCB ITCMCR: RMW Position */ #define SCB_ITCMCR_RMW_Msk (1UL << SCB_ITCMCR_RMW_Pos) /*!< SCB ITCMCR: RMW Mask */ #define SCB_ITCMCR_EN_Pos 0 /*!< SCB ITCMCR: EN Position */ #define SCB_ITCMCR_EN_Msk (1UL /*<< SCB_ITCMCR_EN_Pos*/) /*!< SCB ITCMCR: EN Mask */ /* Data Tightly-Coupled Memory Control Registers */ #define SCB_DTCMCR_SZ_Pos 3 /*!< SCB DTCMCR: SZ Position */ #define SCB_DTCMCR_SZ_Msk (0xFUL << SCB_DTCMCR_SZ_Pos) /*!< SCB DTCMCR: SZ Mask */ #define SCB_DTCMCR_RETEN_Pos 2 /*!< SCB DTCMCR: RETEN Position */ #define SCB_DTCMCR_RETEN_Msk (1UL << SCB_DTCMCR_RETEN_Pos) /*!< SCB DTCMCR: RETEN Mask */ #define SCB_DTCMCR_RMW_Pos 1 /*!< SCB DTCMCR: RMW Position */ #define SCB_DTCMCR_RMW_Msk (1UL << SCB_DTCMCR_RMW_Pos) /*!< SCB DTCMCR: RMW Mask */ #define SCB_DTCMCR_EN_Pos 0 /*!< SCB DTCMCR: EN Position */ #define SCB_DTCMCR_EN_Msk (1UL /*<< SCB_DTCMCR_EN_Pos*/) /*!< SCB DTCMCR: EN Mask */ /* AHBP Control Register */ #define SCB_AHBPCR_SZ_Pos 1 /*!< SCB AHBPCR: SZ Position */ #define SCB_AHBPCR_SZ_Msk (7UL << SCB_AHBPCR_SZ_Pos) /*!< SCB AHBPCR: SZ Mask */ #define SCB_AHBPCR_EN_Pos 0 /*!< SCB AHBPCR: EN Position */ #define SCB_AHBPCR_EN_Msk (1UL /*<< SCB_AHBPCR_EN_Pos*/) /*!< SCB AHBPCR: EN Mask */ /* L1 Cache Control Register */ #define SCB_CACR_FORCEWT_Pos 2 /*!< SCB CACR: FORCEWT Position */ #define SCB_CACR_FORCEWT_Msk (1UL << SCB_CACR_FORCEWT_Pos) /*!< SCB CACR: FORCEWT Mask */ #define SCB_CACR_ECCEN_Pos 1 /*!< SCB CACR: ECCEN Position */ #define SCB_CACR_ECCEN_Msk (1UL << SCB_CACR_ECCEN_Pos) /*!< SCB CACR: ECCEN Mask */ #define SCB_CACR_SIWT_Pos 0 /*!< SCB CACR: SIWT Position */ #define SCB_CACR_SIWT_Msk (1UL /*<< SCB_CACR_SIWT_Pos*/) /*!< SCB CACR: SIWT Mask */ /* AHBS control register */ #define SCB_AHBSCR_INITCOUNT_Pos 11 /*!< SCB AHBSCR: INITCOUNT Position */ #define SCB_AHBSCR_INITCOUNT_Msk (0x1FUL << SCB_AHBPCR_INITCOUNT_Pos) /*!< SCB AHBSCR: INITCOUNT Mask */ #define SCB_AHBSCR_TPRI_Pos 2 /*!< SCB AHBSCR: TPRI Position */ #define SCB_AHBSCR_TPRI_Msk (0x1FFUL << SCB_AHBPCR_TPRI_Pos) /*!< SCB AHBSCR: TPRI Mask */ #define SCB_AHBSCR_CTL_Pos 0 /*!< SCB AHBSCR: CTL Position*/ #define SCB_AHBSCR_CTL_Msk (3UL /*<< SCB_AHBPCR_CTL_Pos*/) /*!< SCB AHBSCR: CTL Mask */ /* Auxiliary Bus Fault Status Register */ #define SCB_ABFSR_AXIMTYPE_Pos 8 /*!< SCB ABFSR: AXIMTYPE Position*/ #define SCB_ABFSR_AXIMTYPE_Msk (3UL << SCB_ABFSR_AXIMTYPE_Pos) /*!< SCB ABFSR: AXIMTYPE Mask */ #define SCB_ABFSR_EPPB_Pos 4 /*!< SCB ABFSR: EPPB Position*/ #define SCB_ABFSR_EPPB_Msk (1UL << SCB_ABFSR_EPPB_Pos) /*!< SCB ABFSR: EPPB Mask */ #define SCB_ABFSR_AXIM_Pos 3 /*!< SCB ABFSR: AXIM Position*/ #define SCB_ABFSR_AXIM_Msk (1UL << SCB_ABFSR_AXIM_Pos) /*!< SCB ABFSR: AXIM Mask */ #define SCB_ABFSR_AHBP_Pos 2 /*!< SCB ABFSR: AHBP Position*/ #define SCB_ABFSR_AHBP_Msk (1UL << SCB_ABFSR_AHBP_Pos) /*!< SCB ABFSR: AHBP Mask */ #define SCB_ABFSR_DTCM_Pos 1 /*!< SCB ABFSR: DTCM Position*/ #define SCB_ABFSR_DTCM_Msk (1UL << SCB_ABFSR_DTCM_Pos) /*!< SCB ABFSR: DTCM Mask */ #define SCB_ABFSR_ITCM_Pos 0 /*!< SCB ABFSR: ITCM Position*/ #define SCB_ABFSR_ITCM_Msk (1UL /*<< SCB_ABFSR_ITCM_Pos*/) /*!< SCB ABFSR: ITCM Mask */ /*@} end of group CMSIS_SCB */ /** \ingroup CMSIS_core_register \defgroup CMSIS_SCnSCB System Controls not in SCB (SCnSCB) \brief Type definitions for the System Control and ID Register not in the SCB @{ */ /** \brief Structure type to access the System Control and ID Register not in the SCB. */ typedef struct { uint32_t RESERVED0[1]; __I uint32_t ICTR; /*!< Offset: 0x004 (R/ ) Interrupt Controller Type Register */ __IO uint32_t ACTLR; /*!< Offset: 0x008 (R/W) Auxiliary Control Register */ } SCnSCB_Type; /* Interrupt Controller Type Register Definitions */ #define SCnSCB_ICTR_INTLINESNUM_Pos 0 /*!< ICTR: INTLINESNUM Position */ #define SCnSCB_ICTR_INTLINESNUM_Msk (0xFUL /*<< SCnSCB_ICTR_INTLINESNUM_Pos*/) /*!< ICTR: INTLINESNUM Mask */ /* Auxiliary Control Register Definitions */ #define SCnSCB_ACTLR_DISITMATBFLUSH_Pos 12 /*!< ACTLR: DISITMATBFLUSH Position */ #define SCnSCB_ACTLR_DISITMATBFLUSH_Msk (1UL << SCnSCB_ACTLR_DISITMATBFLUSH_Pos) /*!< ACTLR: DISITMATBFLUSH Mask */ #define SCnSCB_ACTLR_DISRAMODE_Pos 11 /*!< ACTLR: DISRAMODE Position */ #define SCnSCB_ACTLR_DISRAMODE_Msk (1UL << SCnSCB_ACTLR_DISRAMODE_Pos) /*!< ACTLR: DISRAMODE Mask */ #define SCnSCB_ACTLR_FPEXCODIS_Pos 10 /*!< ACTLR: FPEXCODIS Position */ #define SCnSCB_ACTLR_FPEXCODIS_Msk (1UL << SCnSCB_ACTLR_FPEXCODIS_Pos) /*!< ACTLR: FPEXCODIS Mask */ #define SCnSCB_ACTLR_DISFOLD_Pos 2 /*!< ACTLR: DISFOLD Position */ #define SCnSCB_ACTLR_DISFOLD_Msk (1UL << SCnSCB_ACTLR_DISFOLD_Pos) /*!< ACTLR: DISFOLD Mask */ #define SCnSCB_ACTLR_DISMCYCINT_Pos 0 /*!< ACTLR: DISMCYCINT Position */ #define SCnSCB_ACTLR_DISMCYCINT_Msk (1UL /*<< SCnSCB_ACTLR_DISMCYCINT_Pos*/) /*!< ACTLR: DISMCYCINT Mask */ /*@} end of group CMSIS_SCnotSCB */ /** \ingroup CMSIS_core_register \defgroup CMSIS_SysTick System Tick Timer (SysTick) \brief Type definitions for the System Timer Registers. @{ */ /** \brief Structure type to access the System Timer (SysTick). */ typedef struct { __IO uint32_t CTRL; /*!< Offset: 0x000 (R/W) SysTick Control and Status Register */ __IO uint32_t LOAD; /*!< Offset: 0x004 (R/W) SysTick Reload Value Register */ __IO uint32_t VAL; /*!< Offset: 0x008 (R/W) SysTick Current Value Register */ __I uint32_t CALIB; /*!< Offset: 0x00C (R/ ) SysTick Calibration Register */ } SysTick_Type; /* SysTick Control / Status Register Definitions */ #define SysTick_CTRL_COUNTFLAG_Pos 16 /*!< SysTick CTRL: COUNTFLAG Position */ #define SysTick_CTRL_COUNTFLAG_Msk (1UL << SysTick_CTRL_COUNTFLAG_Pos) /*!< SysTick CTRL: COUNTFLAG Mask */ #define SysTick_CTRL_CLKSOURCE_Pos 2 /*!< SysTick CTRL: CLKSOURCE Position */ #define SysTick_CTRL_CLKSOURCE_Msk (1UL << SysTick_CTRL_CLKSOURCE_Pos) /*!< SysTick CTRL: CLKSOURCE Mask */ #define SysTick_CTRL_TICKINT_Pos 1 /*!< SysTick CTRL: TICKINT Position */ #define SysTick_CTRL_TICKINT_Msk (1UL << SysTick_CTRL_TICKINT_Pos) /*!< SysTick CTRL: TICKINT Mask */ #define SysTick_CTRL_ENABLE_Pos 0 /*!< SysTick CTRL: ENABLE Position */ #define SysTick_CTRL_ENABLE_Msk (1UL /*<< SysTick_CTRL_ENABLE_Pos*/) /*!< SysTick CTRL: ENABLE Mask */ /* SysTick Reload Register Definitions */ #define SysTick_LOAD_RELOAD_Pos 0 /*!< SysTick LOAD: RELOAD Position */ #define SysTick_LOAD_RELOAD_Msk (0xFFFFFFUL /*<< SysTick_LOAD_RELOAD_Pos*/) /*!< SysTick LOAD: RELOAD Mask */ /* SysTick Current Register Definitions */ #define SysTick_VAL_CURRENT_Pos 0 /*!< SysTick VAL: CURRENT Position */ #define SysTick_VAL_CURRENT_Msk (0xFFFFFFUL /*<< SysTick_VAL_CURRENT_Pos*/) /*!< SysTick VAL: CURRENT Mask */ /* SysTick Calibration Register Definitions */ #define SysTick_CALIB_NOREF_Pos 31 /*!< SysTick CALIB: NOREF Position */ #define SysTick_CALIB_NOREF_Msk (1UL << SysTick_CALIB_NOREF_Pos) /*!< SysTick CALIB: NOREF Mask */ #define SysTick_CALIB_SKEW_Pos 30 /*!< SysTick CALIB: SKEW Position */ #define SysTick_CALIB_SKEW_Msk (1UL << SysTick_CALIB_SKEW_Pos) /*!< SysTick CALIB: SKEW Mask */ #define SysTick_CALIB_TENMS_Pos 0 /*!< SysTick CALIB: TENMS Position */ #define SysTick_CALIB_TENMS_Msk (0xFFFFFFUL /*<< SysTick_CALIB_TENMS_Pos*/) /*!< SysTick CALIB: TENMS Mask */ /*@} end of group CMSIS_SysTick */ /** \ingroup CMSIS_core_register \defgroup CMSIS_ITM Instrumentation Trace Macrocell (ITM) \brief Type definitions for the Instrumentation Trace Macrocell (ITM) @{ */ /** \brief Structure type to access the Instrumentation Trace Macrocell Register (ITM). */ typedef struct { __O union { __O uint8_t u8; /*!< Offset: 0x000 ( /W) ITM Stimulus Port 8-bit */ __O uint16_t u16; /*!< Offset: 0x000 ( /W) ITM Stimulus Port 16-bit */ __O uint32_t u32; /*!< Offset: 0x000 ( /W) ITM Stimulus Port 32-bit */ } PORT [32]; /*!< Offset: 0x000 ( /W) ITM Stimulus Port Registers */ uint32_t RESERVED0[864]; __IO uint32_t TER; /*!< Offset: 0xE00 (R/W) ITM Trace Enable Register */ uint32_t RESERVED1[15]; __IO uint32_t TPR; /*!< Offset: 0xE40 (R/W) ITM Trace Privilege Register */ uint32_t RESERVED2[15]; __IO uint32_t TCR; /*!< Offset: 0xE80 (R/W) ITM Trace Control Register */ uint32_t RESERVED3[29]; __O uint32_t IWR; /*!< Offset: 0xEF8 ( /W) ITM Integration Write Register */ __I uint32_t IRR; /*!< Offset: 0xEFC (R/ ) ITM Integration Read Register */ __IO uint32_t IMCR; /*!< Offset: 0xF00 (R/W) ITM Integration Mode Control Register */ uint32_t RESERVED4[43]; __O uint32_t LAR; /*!< Offset: 0xFB0 ( /W) ITM Lock Access Register */ __I uint32_t LSR; /*!< Offset: 0xFB4 (R/ ) ITM Lock Status Register */ uint32_t RESERVED5[6]; __I uint32_t PID4; /*!< Offset: 0xFD0 (R/ ) ITM Peripheral Identification Register #4 */ __I uint32_t PID5; /*!< Offset: 0xFD4 (R/ ) ITM Peripheral Identification Register #5 */ __I uint32_t PID6; /*!< Offset: 0xFD8 (R/ ) ITM Peripheral Identification Register #6 */ __I uint32_t PID7; /*!< Offset: 0xFDC (R/ ) ITM Peripheral Identification Register #7 */ __I uint32_t PID0; /*!< Offset: 0xFE0 (R/ ) ITM Peripheral Identification Register #0 */ __I uint32_t PID1; /*!< Offset: 0xFE4 (R/ ) ITM Peripheral Identification Register #1 */ __I uint32_t PID2; /*!< Offset: 0xFE8 (R/ ) ITM Peripheral Identification Register #2 */ __I uint32_t PID3; /*!< Offset: 0xFEC (R/ ) ITM Peripheral Identification Register #3 */ __I uint32_t CID0; /*!< Offset: 0xFF0 (R/ ) ITM Component Identification Register #0 */ __I uint32_t CID1; /*!< Offset: 0xFF4 (R/ ) ITM Component Identification Register #1 */ __I uint32_t CID2; /*!< Offset: 0xFF8 (R/ ) ITM Component Identification Register #2 */ __I uint32_t CID3; /*!< Offset: 0xFFC (R/ ) ITM Component Identification Register #3 */ } ITM_Type; /* ITM Trace Privilege Register Definitions */ #define ITM_TPR_PRIVMASK_Pos 0 /*!< ITM TPR: PRIVMASK Position */ #define ITM_TPR_PRIVMASK_Msk (0xFUL /*<< ITM_TPR_PRIVMASK_Pos*/) /*!< ITM TPR: PRIVMASK Mask */ /* ITM Trace Control Register Definitions */ #define ITM_TCR_BUSY_Pos 23 /*!< ITM TCR: BUSY Position */ #define ITM_TCR_BUSY_Msk (1UL << ITM_TCR_BUSY_Pos) /*!< ITM TCR: BUSY Mask */ #define ITM_TCR_TraceBusID_Pos 16 /*!< ITM TCR: ATBID Position */ #define ITM_TCR_TraceBusID_Msk (0x7FUL << ITM_TCR_TraceBusID_Pos) /*!< ITM TCR: ATBID Mask */ #define ITM_TCR_GTSFREQ_Pos 10 /*!< ITM TCR: Global timestamp frequency Position */ #define ITM_TCR_GTSFREQ_Msk (3UL << ITM_TCR_GTSFREQ_Pos) /*!< ITM TCR: Global timestamp frequency Mask */ #define ITM_TCR_TSPrescale_Pos 8 /*!< ITM TCR: TSPrescale Position */ #define ITM_TCR_TSPrescale_Msk (3UL << ITM_TCR_TSPrescale_Pos) /*!< ITM TCR: TSPrescale Mask */ #define ITM_TCR_SWOENA_Pos 4 /*!< ITM TCR: SWOENA Position */ #define ITM_TCR_SWOENA_Msk (1UL << ITM_TCR_SWOENA_Pos) /*!< ITM TCR: SWOENA Mask */ #define ITM_TCR_DWTENA_Pos 3 /*!< ITM TCR: DWTENA Position */ #define ITM_TCR_DWTENA_Msk (1UL << ITM_TCR_DWTENA_Pos) /*!< ITM TCR: DWTENA Mask */ #define ITM_TCR_SYNCENA_Pos 2 /*!< ITM TCR: SYNCENA Position */ #define ITM_TCR_SYNCENA_Msk (1UL << ITM_TCR_SYNCENA_Pos) /*!< ITM TCR: SYNCENA Mask */ #define ITM_TCR_TSENA_Pos 1 /*!< ITM TCR: TSENA Position */ #define ITM_TCR_TSENA_Msk (1UL << ITM_TCR_TSENA_Pos) /*!< ITM TCR: TSENA Mask */ #define ITM_TCR_ITMENA_Pos 0 /*!< ITM TCR: ITM Enable bit Position */ #define ITM_TCR_ITMENA_Msk (1UL /*<< ITM_TCR_ITMENA_Pos*/) /*!< ITM TCR: ITM Enable bit Mask */ /* ITM Integration Write Register Definitions */ #define ITM_IWR_ATVALIDM_Pos 0 /*!< ITM IWR: ATVALIDM Position */ #define ITM_IWR_ATVALIDM_Msk (1UL /*<< ITM_IWR_ATVALIDM_Pos*/) /*!< ITM IWR: ATVALIDM Mask */ /* ITM Integration Read Register Definitions */ #define ITM_IRR_ATREADYM_Pos 0 /*!< ITM IRR: ATREADYM Position */ #define ITM_IRR_ATREADYM_Msk (1UL /*<< ITM_IRR_ATREADYM_Pos*/) /*!< ITM IRR: ATREADYM Mask */ /* ITM Integration Mode Control Register Definitions */ #define ITM_IMCR_INTEGRATION_Pos 0 /*!< ITM IMCR: INTEGRATION Position */ #define ITM_IMCR_INTEGRATION_Msk (1UL /*<< ITM_IMCR_INTEGRATION_Pos*/) /*!< ITM IMCR: INTEGRATION Mask */ /* ITM Lock Status Register Definitions */ #define ITM_LSR_ByteAcc_Pos 2 /*!< ITM LSR: ByteAcc Position */ #define ITM_LSR_ByteAcc_Msk (1UL << ITM_LSR_ByteAcc_Pos) /*!< ITM LSR: ByteAcc Mask */ #define ITM_LSR_Access_Pos 1 /*!< ITM LSR: Access Position */ #define ITM_LSR_Access_Msk (1UL << ITM_LSR_Access_Pos) /*!< ITM LSR: Access Mask */ #define ITM_LSR_Present_Pos 0 /*!< ITM LSR: Present Position */ #define ITM_LSR_Present_Msk (1UL /*<< ITM_LSR_Present_Pos*/) /*!< ITM LSR: Present Mask */ /*@}*/ /* end of group CMSIS_ITM */ /** \ingroup CMSIS_core_register \defgroup CMSIS_DWT Data Watchpoint and Trace (DWT) \brief Type definitions for the Data Watchpoint and Trace (DWT) @{ */ /** \brief Structure type to access the Data Watchpoint and Trace Register (DWT). */ typedef struct { __IO uint32_t CTRL; /*!< Offset: 0x000 (R/W) Control Register */ __IO uint32_t CYCCNT; /*!< Offset: 0x004 (R/W) Cycle Count Register */ __IO uint32_t CPICNT; /*!< Offset: 0x008 (R/W) CPI Count Register */ __IO uint32_t EXCCNT; /*!< Offset: 0x00C (R/W) Exception Overhead Count Register */ __IO uint32_t SLEEPCNT; /*!< Offset: 0x010 (R/W) Sleep Count Register */ __IO uint32_t LSUCNT; /*!< Offset: 0x014 (R/W) LSU Count Register */ __IO uint32_t FOLDCNT; /*!< Offset: 0x018 (R/W) Folded-instruction Count Register */ __I uint32_t PCSR; /*!< Offset: 0x01C (R/ ) Program Counter Sample Register */ __IO uint32_t COMP0; /*!< Offset: 0x020 (R/W) Comparator Register 0 */ __IO uint32_t MASK0; /*!< Offset: 0x024 (R/W) Mask Register 0 */ __IO uint32_t FUNCTION0; /*!< Offset: 0x028 (R/W) Function Register 0 */ uint32_t RESERVED0[1]; __IO uint32_t COMP1; /*!< Offset: 0x030 (R/W) Comparator Register 1 */ __IO uint32_t MASK1; /*!< Offset: 0x034 (R/W) Mask Register 1 */ __IO uint32_t FUNCTION1; /*!< Offset: 0x038 (R/W) Function Register 1 */ uint32_t RESERVED1[1]; __IO uint32_t COMP2; /*!< Offset: 0x040 (R/W) Comparator Register 2 */ __IO uint32_t MASK2; /*!< Offset: 0x044 (R/W) Mask Register 2 */ __IO uint32_t FUNCTION2; /*!< Offset: 0x048 (R/W) Function Register 2 */ uint32_t RESERVED2[1]; __IO uint32_t COMP3; /*!< Offset: 0x050 (R/W) Comparator Register 3 */ __IO uint32_t MASK3; /*!< Offset: 0x054 (R/W) Mask Register 3 */ __IO uint32_t FUNCTION3; /*!< Offset: 0x058 (R/W) Function Register 3 */ uint32_t RESERVED3[981]; __O uint32_t LAR; /*!< Offset: 0xFB0 ( W) Lock Access Register */ __I uint32_t LSR; /*!< Offset: 0xFB4 (R ) Lock Status Register */ } DWT_Type; /* DWT Control Register Definitions */ #define DWT_CTRL_NUMCOMP_Pos 28 /*!< DWT CTRL: NUMCOMP Position */ #define DWT_CTRL_NUMCOMP_Msk (0xFUL << DWT_CTRL_NUMCOMP_Pos) /*!< DWT CTRL: NUMCOMP Mask */ #define DWT_CTRL_NOTRCPKT_Pos 27 /*!< DWT CTRL: NOTRCPKT Position */ #define DWT_CTRL_NOTRCPKT_Msk (0x1UL << DWT_CTRL_NOTRCPKT_Pos) /*!< DWT CTRL: NOTRCPKT Mask */ #define DWT_CTRL_NOEXTTRIG_Pos 26 /*!< DWT CTRL: NOEXTTRIG Position */ #define DWT_CTRL_NOEXTTRIG_Msk (0x1UL << DWT_CTRL_NOEXTTRIG_Pos) /*!< DWT CTRL: NOEXTTRIG Mask */ #define DWT_CTRL_NOCYCCNT_Pos 25 /*!< DWT CTRL: NOCYCCNT Position */ #define DWT_CTRL_NOCYCCNT_Msk (0x1UL << DWT_CTRL_NOCYCCNT_Pos) /*!< DWT CTRL: NOCYCCNT Mask */ #define DWT_CTRL_NOPRFCNT_Pos 24 /*!< DWT CTRL: NOPRFCNT Position */ #define DWT_CTRL_NOPRFCNT_Msk (0x1UL << DWT_CTRL_NOPRFCNT_Pos) /*!< DWT CTRL: NOPRFCNT Mask */ #define DWT_CTRL_CYCEVTENA_Pos 22 /*!< DWT CTRL: CYCEVTENA Position */ #define DWT_CTRL_CYCEVTENA_Msk (0x1UL << DWT_CTRL_CYCEVTENA_Pos) /*!< DWT CTRL: CYCEVTENA Mask */ #define DWT_CTRL_FOLDEVTENA_Pos 21 /*!< DWT CTRL: FOLDEVTENA Position */ #define DWT_CTRL_FOLDEVTENA_Msk (0x1UL << DWT_CTRL_FOLDEVTENA_Pos) /*!< DWT CTRL: FOLDEVTENA Mask */ #define DWT_CTRL_LSUEVTENA_Pos 20 /*!< DWT CTRL: LSUEVTENA Position */ #define DWT_CTRL_LSUEVTENA_Msk (0x1UL << DWT_CTRL_LSUEVTENA_Pos) /*!< DWT CTRL: LSUEVTENA Mask */ #define DWT_CTRL_SLEEPEVTENA_Pos 19 /*!< DWT CTRL: SLEEPEVTENA Position */ #define DWT_CTRL_SLEEPEVTENA_Msk (0x1UL << DWT_CTRL_SLEEPEVTENA_Pos) /*!< DWT CTRL: SLEEPEVTENA Mask */ #define DWT_CTRL_EXCEVTENA_Pos 18 /*!< DWT CTRL: EXCEVTENA Position */ #define DWT_CTRL_EXCEVTENA_Msk (0x1UL << DWT_CTRL_EXCEVTENA_Pos) /*!< DWT CTRL: EXCEVTENA Mask */ #define DWT_CTRL_CPIEVTENA_Pos 17 /*!< DWT CTRL: CPIEVTENA Position */ #define DWT_CTRL_CPIEVTENA_Msk (0x1UL << DWT_CTRL_CPIEVTENA_Pos) /*!< DWT CTRL: CPIEVTENA Mask */ #define DWT_CTRL_EXCTRCENA_Pos 16 /*!< DWT CTRL: EXCTRCENA Position */ #define DWT_CTRL_EXCTRCENA_Msk (0x1UL << DWT_CTRL_EXCTRCENA_Pos) /*!< DWT CTRL: EXCTRCENA Mask */ #define DWT_CTRL_PCSAMPLENA_Pos 12 /*!< DWT CTRL: PCSAMPLENA Position */ #define DWT_CTRL_PCSAMPLENA_Msk (0x1UL << DWT_CTRL_PCSAMPLENA_Pos) /*!< DWT CTRL: PCSAMPLENA Mask */ #define DWT_CTRL_SYNCTAP_Pos 10 /*!< DWT CTRL: SYNCTAP Position */ #define DWT_CTRL_SYNCTAP_Msk (0x3UL << DWT_CTRL_SYNCTAP_Pos) /*!< DWT CTRL: SYNCTAP Mask */ #define DWT_CTRL_CYCTAP_Pos 9 /*!< DWT CTRL: CYCTAP Position */ #define DWT_CTRL_CYCTAP_Msk (0x1UL << DWT_CTRL_CYCTAP_Pos) /*!< DWT CTRL: CYCTAP Mask */ #define DWT_CTRL_POSTINIT_Pos 5 /*!< DWT CTRL: POSTINIT Position */ #define DWT_CTRL_POSTINIT_Msk (0xFUL << DWT_CTRL_POSTINIT_Pos) /*!< DWT CTRL: POSTINIT Mask */ #define DWT_CTRL_POSTPRESET_Pos 1 /*!< DWT CTRL: POSTPRESET Position */ #define DWT_CTRL_POSTPRESET_Msk (0xFUL << DWT_CTRL_POSTPRESET_Pos) /*!< DWT CTRL: POSTPRESET Mask */ #define DWT_CTRL_CYCCNTENA_Pos 0 /*!< DWT CTRL: CYCCNTENA Position */ #define DWT_CTRL_CYCCNTENA_Msk (0x1UL /*<< DWT_CTRL_CYCCNTENA_Pos*/) /*!< DWT CTRL: CYCCNTENA Mask */ /* DWT CPI Count Register Definitions */ #define DWT_CPICNT_CPICNT_Pos 0 /*!< DWT CPICNT: CPICNT Position */ #define DWT_CPICNT_CPICNT_Msk (0xFFUL /*<< DWT_CPICNT_CPICNT_Pos*/) /*!< DWT CPICNT: CPICNT Mask */ /* DWT Exception Overhead Count Register Definitions */ #define DWT_EXCCNT_EXCCNT_Pos 0 /*!< DWT EXCCNT: EXCCNT Position */ #define DWT_EXCCNT_EXCCNT_Msk (0xFFUL /*<< DWT_EXCCNT_EXCCNT_Pos*/) /*!< DWT EXCCNT: EXCCNT Mask */ /* DWT Sleep Count Register Definitions */ #define DWT_SLEEPCNT_SLEEPCNT_Pos 0 /*!< DWT SLEEPCNT: SLEEPCNT Position */ #define DWT_SLEEPCNT_SLEEPCNT_Msk (0xFFUL /*<< DWT_SLEEPCNT_SLEEPCNT_Pos*/) /*!< DWT SLEEPCNT: SLEEPCNT Mask */ /* DWT LSU Count Register Definitions */ #define DWT_LSUCNT_LSUCNT_Pos 0 /*!< DWT LSUCNT: LSUCNT Position */ #define DWT_LSUCNT_LSUCNT_Msk (0xFFUL /*<< DWT_LSUCNT_LSUCNT_Pos*/) /*!< DWT LSUCNT: LSUCNT Mask */ /* DWT Folded-instruction Count Register Definitions */ #define DWT_FOLDCNT_FOLDCNT_Pos 0 /*!< DWT FOLDCNT: FOLDCNT Position */ #define DWT_FOLDCNT_FOLDCNT_Msk (0xFFUL /*<< DWT_FOLDCNT_FOLDCNT_Pos*/) /*!< DWT FOLDCNT: FOLDCNT Mask */ /* DWT Comparator Mask Register Definitions */ #define DWT_MASK_MASK_Pos 0 /*!< DWT MASK: MASK Position */ #define DWT_MASK_MASK_Msk (0x1FUL /*<< DWT_MASK_MASK_Pos*/) /*!< DWT MASK: MASK Mask */ /* DWT Comparator Function Register Definitions */ #define DWT_FUNCTION_MATCHED_Pos 24 /*!< DWT FUNCTION: MATCHED Position */ #define DWT_FUNCTION_MATCHED_Msk (0x1UL << DWT_FUNCTION_MATCHED_Pos) /*!< DWT FUNCTION: MATCHED Mask */ #define DWT_FUNCTION_DATAVADDR1_Pos 16 /*!< DWT FUNCTION: DATAVADDR1 Position */ #define DWT_FUNCTION_DATAVADDR1_Msk (0xFUL << DWT_FUNCTION_DATAVADDR1_Pos) /*!< DWT FUNCTION: DATAVADDR1 Mask */ #define DWT_FUNCTION_DATAVADDR0_Pos 12 /*!< DWT FUNCTION: DATAVADDR0 Position */ #define DWT_FUNCTION_DATAVADDR0_Msk (0xFUL << DWT_FUNCTION_DATAVADDR0_Pos) /*!< DWT FUNCTION: DATAVADDR0 Mask */ #define DWT_FUNCTION_DATAVSIZE_Pos 10 /*!< DWT FUNCTION: DATAVSIZE Position */ #define DWT_FUNCTION_DATAVSIZE_Msk (0x3UL << DWT_FUNCTION_DATAVSIZE_Pos) /*!< DWT FUNCTION: DATAVSIZE Mask */ #define DWT_FUNCTION_LNK1ENA_Pos 9 /*!< DWT FUNCTION: LNK1ENA Position */ #define DWT_FUNCTION_LNK1ENA_Msk (0x1UL << DWT_FUNCTION_LNK1ENA_Pos) /*!< DWT FUNCTION: LNK1ENA Mask */ #define DWT_FUNCTION_DATAVMATCH_Pos 8 /*!< DWT FUNCTION: DATAVMATCH Position */ #define DWT_FUNCTION_DATAVMATCH_Msk (0x1UL << DWT_FUNCTION_DATAVMATCH_Pos) /*!< DWT FUNCTION: DATAVMATCH Mask */ #define DWT_FUNCTION_CYCMATCH_Pos 7 /*!< DWT FUNCTION: CYCMATCH Position */ #define DWT_FUNCTION_CYCMATCH_Msk (0x1UL << DWT_FUNCTION_CYCMATCH_Pos) /*!< DWT FUNCTION: CYCMATCH Mask */ #define DWT_FUNCTION_EMITRANGE_Pos 5 /*!< DWT FUNCTION: EMITRANGE Position */ #define DWT_FUNCTION_EMITRANGE_Msk (0x1UL << DWT_FUNCTION_EMITRANGE_Pos) /*!< DWT FUNCTION: EMITRANGE Mask */ #define DWT_FUNCTION_FUNCTION_Pos 0 /*!< DWT FUNCTION: FUNCTION Position */ #define DWT_FUNCTION_FUNCTION_Msk (0xFUL /*<< DWT_FUNCTION_FUNCTION_Pos*/) /*!< DWT FUNCTION: FUNCTION Mask */ /*@}*/ /* end of group CMSIS_DWT */ /** \ingroup CMSIS_core_register \defgroup CMSIS_TPI Trace Port Interface (TPI) \brief Type definitions for the Trace Port Interface (TPI) @{ */ /** \brief Structure type to access the Trace Port Interface Register (TPI). */ typedef struct { __IO uint32_t SSPSR; /*!< Offset: 0x000 (R/ ) Supported Parallel Port Size Register */ __IO uint32_t CSPSR; /*!< Offset: 0x004 (R/W) Current Parallel Port Size Register */ uint32_t RESERVED0[2]; __IO uint32_t ACPR; /*!< Offset: 0x010 (R/W) Asynchronous Clock Prescaler Register */ uint32_t RESERVED1[55]; __IO uint32_t SPPR; /*!< Offset: 0x0F0 (R/W) Selected Pin Protocol Register */ uint32_t RESERVED2[131]; __I uint32_t FFSR; /*!< Offset: 0x300 (R/ ) Formatter and Flush Status Register */ __IO uint32_t FFCR; /*!< Offset: 0x304 (R/W) Formatter and Flush Control Register */ __I uint32_t FSCR; /*!< Offset: 0x308 (R/ ) Formatter Synchronization Counter Register */ uint32_t RESERVED3[759]; __I uint32_t TRIGGER; /*!< Offset: 0xEE8 (R/ ) TRIGGER */ __I uint32_t FIFO0; /*!< Offset: 0xEEC (R/ ) Integration ETM Data */ __I uint32_t ITATBCTR2; /*!< Offset: 0xEF0 (R/ ) ITATBCTR2 */ uint32_t RESERVED4[1]; __I uint32_t ITATBCTR0; /*!< Offset: 0xEF8 (R/ ) ITATBCTR0 */ __I uint32_t FIFO1; /*!< Offset: 0xEFC (R/ ) Integration ITM Data */ __IO uint32_t ITCTRL; /*!< Offset: 0xF00 (R/W) Integration Mode Control */ uint32_t RESERVED5[39]; __IO uint32_t CLAIMSET; /*!< Offset: 0xFA0 (R/W) Claim tag set */ __IO uint32_t CLAIMCLR; /*!< Offset: 0xFA4 (R/W) Claim tag clear */ uint32_t RESERVED7[8]; __I uint32_t DEVID; /*!< Offset: 0xFC8 (R/ ) TPIU_DEVID */ __I uint32_t DEVTYPE; /*!< Offset: 0xFCC (R/ ) TPIU_DEVTYPE */ } TPI_Type; /* TPI Asynchronous Clock Prescaler Register Definitions */ #define TPI_ACPR_PRESCALER_Pos 0 /*!< TPI ACPR: PRESCALER Position */ #define TPI_ACPR_PRESCALER_Msk (0x1FFFUL /*<< TPI_ACPR_PRESCALER_Pos*/) /*!< TPI ACPR: PRESCALER Mask */ /* TPI Selected Pin Protocol Register Definitions */ #define TPI_SPPR_TXMODE_Pos 0 /*!< TPI SPPR: TXMODE Position */ #define TPI_SPPR_TXMODE_Msk (0x3UL /*<< TPI_SPPR_TXMODE_Pos*/) /*!< TPI SPPR: TXMODE Mask */ /* TPI Formatter and Flush Status Register Definitions */ #define TPI_FFSR_FtNonStop_Pos 3 /*!< TPI FFSR: FtNonStop Position */ #define TPI_FFSR_FtNonStop_Msk (0x1UL << TPI_FFSR_FtNonStop_Pos) /*!< TPI FFSR: FtNonStop Mask */ #define TPI_FFSR_TCPresent_Pos 2 /*!< TPI FFSR: TCPresent Position */ #define TPI_FFSR_TCPresent_Msk (0x1UL << TPI_FFSR_TCPresent_Pos) /*!< TPI FFSR: TCPresent Mask */ #define TPI_FFSR_FtStopped_Pos 1 /*!< TPI FFSR: FtStopped Position */ #define TPI_FFSR_FtStopped_Msk (0x1UL << TPI_FFSR_FtStopped_Pos) /*!< TPI FFSR: FtStopped Mask */ #define TPI_FFSR_FlInProg_Pos 0 /*!< TPI FFSR: FlInProg Position */ #define TPI_FFSR_FlInProg_Msk (0x1UL /*<< TPI_FFSR_FlInProg_Pos*/) /*!< TPI FFSR: FlInProg Mask */ /* TPI Formatter and Flush Control Register Definitions */ #define TPI_FFCR_TrigIn_Pos 8 /*!< TPI FFCR: TrigIn Position */ #define TPI_FFCR_TrigIn_Msk (0x1UL << TPI_FFCR_TrigIn_Pos) /*!< TPI FFCR: TrigIn Mask */ #define TPI_FFCR_EnFCont_Pos 1 /*!< TPI FFCR: EnFCont Position */ #define TPI_FFCR_EnFCont_Msk (0x1UL << TPI_FFCR_EnFCont_Pos) /*!< TPI FFCR: EnFCont Mask */ /* TPI TRIGGER Register Definitions */ #define TPI_TRIGGER_TRIGGER_Pos 0 /*!< TPI TRIGGER: TRIGGER Position */ #define TPI_TRIGGER_TRIGGER_Msk (0x1UL /*<< TPI_TRIGGER_TRIGGER_Pos*/) /*!< TPI TRIGGER: TRIGGER Mask */ /* TPI Integration ETM Data Register Definitions (FIFO0) */ #define TPI_FIFO0_ITM_ATVALID_Pos 29 /*!< TPI FIFO0: ITM_ATVALID Position */ #define TPI_FIFO0_ITM_ATVALID_Msk (0x3UL << TPI_FIFO0_ITM_ATVALID_Pos) /*!< TPI FIFO0: ITM_ATVALID Mask */ #define TPI_FIFO0_ITM_bytecount_Pos 27 /*!< TPI FIFO0: ITM_bytecount Position */ #define TPI_FIFO0_ITM_bytecount_Msk (0x3UL << TPI_FIFO0_ITM_bytecount_Pos) /*!< TPI FIFO0: ITM_bytecount Mask */ #define TPI_FIFO0_ETM_ATVALID_Pos 26 /*!< TPI FIFO0: ETM_ATVALID Position */ #define TPI_FIFO0_ETM_ATVALID_Msk (0x3UL << TPI_FIFO0_ETM_ATVALID_Pos) /*!< TPI FIFO0: ETM_ATVALID Mask */ #define TPI_FIFO0_ETM_bytecount_Pos 24 /*!< TPI FIFO0: ETM_bytecount Position */ #define TPI_FIFO0_ETM_bytecount_Msk (0x3UL << TPI_FIFO0_ETM_bytecount_Pos) /*!< TPI FIFO0: ETM_bytecount Mask */ #define TPI_FIFO0_ETM2_Pos 16 /*!< TPI FIFO0: ETM2 Position */ #define TPI_FIFO0_ETM2_Msk (0xFFUL << TPI_FIFO0_ETM2_Pos) /*!< TPI FIFO0: ETM2 Mask */ #define TPI_FIFO0_ETM1_Pos 8 /*!< TPI FIFO0: ETM1 Position */ #define TPI_FIFO0_ETM1_Msk (0xFFUL << TPI_FIFO0_ETM1_Pos) /*!< TPI FIFO0: ETM1 Mask */ #define TPI_FIFO0_ETM0_Pos 0 /*!< TPI FIFO0: ETM0 Position */ #define TPI_FIFO0_ETM0_Msk (0xFFUL /*<< TPI_FIFO0_ETM0_Pos*/) /*!< TPI FIFO0: ETM0 Mask */ /* TPI ITATBCTR2 Register Definitions */ #define TPI_ITATBCTR2_ATREADY_Pos 0 /*!< TPI ITATBCTR2: ATREADY Position */ #define TPI_ITATBCTR2_ATREADY_Msk (0x1UL /*<< TPI_ITATBCTR2_ATREADY_Pos*/) /*!< TPI ITATBCTR2: ATREADY Mask */ /* TPI Integration ITM Data Register Definitions (FIFO1) */ #define TPI_FIFO1_ITM_ATVALID_Pos 29 /*!< TPI FIFO1: ITM_ATVALID Position */ #define TPI_FIFO1_ITM_ATVALID_Msk (0x3UL << TPI_FIFO1_ITM_ATVALID_Pos) /*!< TPI FIFO1: ITM_ATVALID Mask */ #define TPI_FIFO1_ITM_bytecount_Pos 27 /*!< TPI FIFO1: ITM_bytecount Position */ #define TPI_FIFO1_ITM_bytecount_Msk (0x3UL << TPI_FIFO1_ITM_bytecount_Pos) /*!< TPI FIFO1: ITM_bytecount Mask */ #define TPI_FIFO1_ETM_ATVALID_Pos 26 /*!< TPI FIFO1: ETM_ATVALID Position */ #define TPI_FIFO1_ETM_ATVALID_Msk (0x3UL << TPI_FIFO1_ETM_ATVALID_Pos) /*!< TPI FIFO1: ETM_ATVALID Mask */ #define TPI_FIFO1_ETM_bytecount_Pos 24 /*!< TPI FIFO1: ETM_bytecount Position */ #define TPI_FIFO1_ETM_bytecount_Msk (0x3UL << TPI_FIFO1_ETM_bytecount_Pos) /*!< TPI FIFO1: ETM_bytecount Mask */ #define TPI_FIFO1_ITM2_Pos 16 /*!< TPI FIFO1: ITM2 Position */ #define TPI_FIFO1_ITM2_Msk (0xFFUL << TPI_FIFO1_ITM2_Pos) /*!< TPI FIFO1: ITM2 Mask */ #define TPI_FIFO1_ITM1_Pos 8 /*!< TPI FIFO1: ITM1 Position */ #define TPI_FIFO1_ITM1_Msk (0xFFUL << TPI_FIFO1_ITM1_Pos) /*!< TPI FIFO1: ITM1 Mask */ #define TPI_FIFO1_ITM0_Pos 0 /*!< TPI FIFO1: ITM0 Position */ #define TPI_FIFO1_ITM0_Msk (0xFFUL /*<< TPI_FIFO1_ITM0_Pos*/) /*!< TPI FIFO1: ITM0 Mask */ /* TPI ITATBCTR0 Register Definitions */ #define TPI_ITATBCTR0_ATREADY_Pos 0 /*!< TPI ITATBCTR0: ATREADY Position */ #define TPI_ITATBCTR0_ATREADY_Msk (0x1UL /*<< TPI_ITATBCTR0_ATREADY_Pos*/) /*!< TPI ITATBCTR0: ATREADY Mask */ /* TPI Integration Mode Control Register Definitions */ #define TPI_ITCTRL_Mode_Pos 0 /*!< TPI ITCTRL: Mode Position */ #define TPI_ITCTRL_Mode_Msk (0x1UL /*<< TPI_ITCTRL_Mode_Pos*/) /*!< TPI ITCTRL: Mode Mask */ /* TPI DEVID Register Definitions */ #define TPI_DEVID_NRZVALID_Pos 11 /*!< TPI DEVID: NRZVALID Position */ #define TPI_DEVID_NRZVALID_Msk (0x1UL << TPI_DEVID_NRZVALID_Pos) /*!< TPI DEVID: NRZVALID Mask */ #define TPI_DEVID_MANCVALID_Pos 10 /*!< TPI DEVID: MANCVALID Position */ #define TPI_DEVID_MANCVALID_Msk (0x1UL << TPI_DEVID_MANCVALID_Pos) /*!< TPI DEVID: MANCVALID Mask */ #define TPI_DEVID_PTINVALID_Pos 9 /*!< TPI DEVID: PTINVALID Position */ #define TPI_DEVID_PTINVALID_Msk (0x1UL << TPI_DEVID_PTINVALID_Pos) /*!< TPI DEVID: PTINVALID Mask */ #define TPI_DEVID_MinBufSz_Pos 6 /*!< TPI DEVID: MinBufSz Position */ #define TPI_DEVID_MinBufSz_Msk (0x7UL << TPI_DEVID_MinBufSz_Pos) /*!< TPI DEVID: MinBufSz Mask */ #define TPI_DEVID_AsynClkIn_Pos 5 /*!< TPI DEVID: AsynClkIn Position */ #define TPI_DEVID_AsynClkIn_Msk (0x1UL << TPI_DEVID_AsynClkIn_Pos) /*!< TPI DEVID: AsynClkIn Mask */ #define TPI_DEVID_NrTraceInput_Pos 0 /*!< TPI DEVID: NrTraceInput Position */ #define TPI_DEVID_NrTraceInput_Msk (0x1FUL /*<< TPI_DEVID_NrTraceInput_Pos*/) /*!< TPI DEVID: NrTraceInput Mask */ /* TPI DEVTYPE Register Definitions */ #define TPI_DEVTYPE_MajorType_Pos 4 /*!< TPI DEVTYPE: MajorType Position */ #define TPI_DEVTYPE_MajorType_Msk (0xFUL << TPI_DEVTYPE_MajorType_Pos) /*!< TPI DEVTYPE: MajorType Mask */ #define TPI_DEVTYPE_SubType_Pos 0 /*!< TPI DEVTYPE: SubType Position */ #define TPI_DEVTYPE_SubType_Msk (0xFUL /*<< TPI_DEVTYPE_SubType_Pos*/) /*!< TPI DEVTYPE: SubType Mask */ /*@}*/ /* end of group CMSIS_TPI */ #if (__MPU_PRESENT == 1) /** \ingroup CMSIS_core_register \defgroup CMSIS_MPU Memory Protection Unit (MPU) \brief Type definitions for the Memory Protection Unit (MPU) @{ */ /** \brief Structure type to access the Memory Protection Unit (MPU). */ typedef struct { __I uint32_t TYPE; /*!< Offset: 0x000 (R/ ) MPU Type Register */ __IO uint32_t CTRL; /*!< Offset: 0x004 (R/W) MPU Control Register */ __IO uint32_t RNR; /*!< Offset: 0x008 (R/W) MPU Region RNRber Register */ __IO uint32_t RBAR; /*!< Offset: 0x00C (R/W) MPU Region Base Address Register */ __IO uint32_t RASR; /*!< Offset: 0x010 (R/W) MPU Region Attribute and Size Register */ __IO uint32_t RBAR_A1; /*!< Offset: 0x014 (R/W) MPU Alias 1 Region Base Address Register */ __IO uint32_t RASR_A1; /*!< Offset: 0x018 (R/W) MPU Alias 1 Region Attribute and Size Register */ __IO uint32_t RBAR_A2; /*!< Offset: 0x01C (R/W) MPU Alias 2 Region Base Address Register */ __IO uint32_t RASR_A2; /*!< Offset: 0x020 (R/W) MPU Alias 2 Region Attribute and Size Register */ __IO uint32_t RBAR_A3; /*!< Offset: 0x024 (R/W) MPU Alias 3 Region Base Address Register */ __IO uint32_t RASR_A3; /*!< Offset: 0x028 (R/W) MPU Alias 3 Region Attribute and Size Register */ } MPU_Type; /* MPU Type Register */ #define MPU_TYPE_IREGION_Pos 16 /*!< MPU TYPE: IREGION Position */ #define MPU_TYPE_IREGION_Msk (0xFFUL << MPU_TYPE_IREGION_Pos) /*!< MPU TYPE: IREGION Mask */ #define MPU_TYPE_DREGION_Pos 8 /*!< MPU TYPE: DREGION Position */ #define MPU_TYPE_DREGION_Msk (0xFFUL << MPU_TYPE_DREGION_Pos) /*!< MPU TYPE: DREGION Mask */ #define MPU_TYPE_SEPARATE_Pos 0 /*!< MPU TYPE: SEPARATE Position */ #define MPU_TYPE_SEPARATE_Msk (1UL /*<< MPU_TYPE_SEPARATE_Pos*/) /*!< MPU TYPE: SEPARATE Mask */ /* MPU Control Register */ #define MPU_CTRL_PRIVDEFENA_Pos 2 /*!< MPU CTRL: PRIVDEFENA Position */ #define MPU_CTRL_PRIVDEFENA_Msk (1UL << MPU_CTRL_PRIVDEFENA_Pos) /*!< MPU CTRL: PRIVDEFENA Mask */ #define MPU_CTRL_HFNMIENA_Pos 1 /*!< MPU CTRL: HFNMIENA Position */ #define MPU_CTRL_HFNMIENA_Msk (1UL << MPU_CTRL_HFNMIENA_Pos) /*!< MPU CTRL: HFNMIENA Mask */ #define MPU_CTRL_ENABLE_Pos 0 /*!< MPU CTRL: ENABLE Position */ #define MPU_CTRL_ENABLE_Msk (1UL /*<< MPU_CTRL_ENABLE_Pos*/) /*!< MPU CTRL: ENABLE Mask */ /* MPU Region Number Register */ #define MPU_RNR_REGION_Pos 0 /*!< MPU RNR: REGION Position */ #define MPU_RNR_REGION_Msk (0xFFUL /*<< MPU_RNR_REGION_Pos*/) /*!< MPU RNR: REGION Mask */ /* MPU Region Base Address Register */ #define MPU_RBAR_ADDR_Pos 5 /*!< MPU RBAR: ADDR Position */ #define MPU_RBAR_ADDR_Msk (0x7FFFFFFUL << MPU_RBAR_ADDR_Pos) /*!< MPU RBAR: ADDR Mask */ #define MPU_RBAR_VALID_Pos 4 /*!< MPU RBAR: VALID Position */ #define MPU_RBAR_VALID_Msk (1UL << MPU_RBAR_VALID_Pos) /*!< MPU RBAR: VALID Mask */ #define MPU_RBAR_REGION_Pos 0 /*!< MPU RBAR: REGION Position */ #define MPU_RBAR_REGION_Msk (0xFUL /*<< MPU_RBAR_REGION_Pos*/) /*!< MPU RBAR: REGION Mask */ /* MPU Region Attribute and Size Register */ #define MPU_RASR_ATTRS_Pos 16 /*!< MPU RASR: MPU Region Attribute field Position */ #define MPU_RASR_ATTRS_Msk (0xFFFFUL << MPU_RASR_ATTRS_Pos) /*!< MPU RASR: MPU Region Attribute field Mask */ #define MPU_RASR_XN_Pos 28 /*!< MPU RASR: ATTRS.XN Position */ #define MPU_RASR_XN_Msk (1UL << MPU_RASR_XN_Pos) /*!< MPU RASR: ATTRS.XN Mask */ #define MPU_RASR_AP_Pos 24 /*!< MPU RASR: ATTRS.AP Position */ #define MPU_RASR_AP_Msk (0x7UL << MPU_RASR_AP_Pos) /*!< MPU RASR: ATTRS.AP Mask */ #define MPU_RASR_TEX_Pos 19 /*!< MPU RASR: ATTRS.TEX Position */ #define MPU_RASR_TEX_Msk (0x7UL << MPU_RASR_TEX_Pos) /*!< MPU RASR: ATTRS.TEX Mask */ #define MPU_RASR_S_Pos 18 /*!< MPU RASR: ATTRS.S Position */ #define MPU_RASR_S_Msk (1UL << MPU_RASR_S_Pos) /*!< MPU RASR: ATTRS.S Mask */ #define MPU_RASR_C_Pos 17 /*!< MPU RASR: ATTRS.C Position */ #define MPU_RASR_C_Msk (1UL << MPU_RASR_C_Pos) /*!< MPU RASR: ATTRS.C Mask */ #define MPU_RASR_B_Pos 16 /*!< MPU RASR: ATTRS.B Position */ #define MPU_RASR_B_Msk (1UL << MPU_RASR_B_Pos) /*!< MPU RASR: ATTRS.B Mask */ #define MPU_RASR_SRD_Pos 8 /*!< MPU RASR: Sub-Region Disable Position */ #define MPU_RASR_SRD_Msk (0xFFUL << MPU_RASR_SRD_Pos) /*!< MPU RASR: Sub-Region Disable Mask */ #define MPU_RASR_SIZE_Pos 1 /*!< MPU RASR: Region Size Field Position */ #define MPU_RASR_SIZE_Msk (0x1FUL << MPU_RASR_SIZE_Pos) /*!< MPU RASR: Region Size Field Mask */ #define MPU_RASR_ENABLE_Pos 0 /*!< MPU RASR: Region enable bit Position */ #define MPU_RASR_ENABLE_Msk (1UL /*<< MPU_RASR_ENABLE_Pos*/) /*!< MPU RASR: Region enable bit Disable Mask */ /*@} end of group CMSIS_MPU */ #endif #if (__FPU_PRESENT == 1) /** \ingroup CMSIS_core_register \defgroup CMSIS_FPU Floating Point Unit (FPU) \brief Type definitions for the Floating Point Unit (FPU) @{ */ /** \brief Structure type to access the Floating Point Unit (FPU). */ typedef struct { uint32_t RESERVED0[1]; __IO uint32_t FPCCR; /*!< Offset: 0x004 (R/W) Floating-Point Context Control Register */ __IO uint32_t FPCAR; /*!< Offset: 0x008 (R/W) Floating-Point Context Address Register */ __IO uint32_t FPDSCR; /*!< Offset: 0x00C (R/W) Floating-Point Default Status Control Register */ __I uint32_t MVFR0; /*!< Offset: 0x010 (R/ ) Media and FP Feature Register 0 */ __I uint32_t MVFR1; /*!< Offset: 0x014 (R/ ) Media and FP Feature Register 1 */ __I uint32_t MVFR2; /*!< Offset: 0x018 (R/ ) Media and FP Feature Register 2 */ } FPU_Type; /* Floating-Point Context Control Register */ #define FPU_FPCCR_ASPEN_Pos 31 /*!< FPCCR: ASPEN bit Position */ #define FPU_FPCCR_ASPEN_Msk (1UL << FPU_FPCCR_ASPEN_Pos) /*!< FPCCR: ASPEN bit Mask */ #define FPU_FPCCR_LSPEN_Pos 30 /*!< FPCCR: LSPEN Position */ #define FPU_FPCCR_LSPEN_Msk (1UL << FPU_FPCCR_LSPEN_Pos) /*!< FPCCR: LSPEN bit Mask */ #define FPU_FPCCR_MONRDY_Pos 8 /*!< FPCCR: MONRDY Position */ #define FPU_FPCCR_MONRDY_Msk (1UL << FPU_FPCCR_MONRDY_Pos) /*!< FPCCR: MONRDY bit Mask */ #define FPU_FPCCR_BFRDY_Pos 6 /*!< FPCCR: BFRDY Position */ #define FPU_FPCCR_BFRDY_Msk (1UL << FPU_FPCCR_BFRDY_Pos) /*!< FPCCR: BFRDY bit Mask */ #define FPU_FPCCR_MMRDY_Pos 5 /*!< FPCCR: MMRDY Position */ #define FPU_FPCCR_MMRDY_Msk (1UL << FPU_FPCCR_MMRDY_Pos) /*!< FPCCR: MMRDY bit Mask */ #define FPU_FPCCR_HFRDY_Pos 4 /*!< FPCCR: HFRDY Position */ #define FPU_FPCCR_HFRDY_Msk (1UL << FPU_FPCCR_HFRDY_Pos) /*!< FPCCR: HFRDY bit Mask */ #define FPU_FPCCR_THREAD_Pos 3 /*!< FPCCR: processor mode bit Position */ #define FPU_FPCCR_THREAD_Msk (1UL << FPU_FPCCR_THREAD_Pos) /*!< FPCCR: processor mode active bit Mask */ #define FPU_FPCCR_USER_Pos 1 /*!< FPCCR: privilege level bit Position */ #define FPU_FPCCR_USER_Msk (1UL << FPU_FPCCR_USER_Pos) /*!< FPCCR: privilege level bit Mask */ #define FPU_FPCCR_LSPACT_Pos 0 /*!< FPCCR: Lazy state preservation active bit Position */ #define FPU_FPCCR_LSPACT_Msk (1UL /*<< FPU_FPCCR_LSPACT_Pos*/) /*!< FPCCR: Lazy state preservation active bit Mask */ /* Floating-Point Context Address Register */ #define FPU_FPCAR_ADDRESS_Pos 3 /*!< FPCAR: ADDRESS bit Position */ #define FPU_FPCAR_ADDRESS_Msk (0x1FFFFFFFUL << FPU_FPCAR_ADDRESS_Pos) /*!< FPCAR: ADDRESS bit Mask */ /* Floating-Point Default Status Control Register */ #define FPU_FPDSCR_AHP_Pos 26 /*!< FPDSCR: AHP bit Position */ #define FPU_FPDSCR_AHP_Msk (1UL << FPU_FPDSCR_AHP_Pos) /*!< FPDSCR: AHP bit Mask */ #define FPU_FPDSCR_DN_Pos 25 /*!< FPDSCR: DN bit Position */ #define FPU_FPDSCR_DN_Msk (1UL << FPU_FPDSCR_DN_Pos) /*!< FPDSCR: DN bit Mask */ #define FPU_FPDSCR_FZ_Pos 24 /*!< FPDSCR: FZ bit Position */ #define FPU_FPDSCR_FZ_Msk (1UL << FPU_FPDSCR_FZ_Pos) /*!< FPDSCR: FZ bit Mask */ #define FPU_FPDSCR_RMode_Pos 22 /*!< FPDSCR: RMode bit Position */ #define FPU_FPDSCR_RMode_Msk (3UL << FPU_FPDSCR_RMode_Pos) /*!< FPDSCR: RMode bit Mask */ /* Media and FP Feature Register 0 */ #define FPU_MVFR0_FP_rounding_modes_Pos 28 /*!< MVFR0: FP rounding modes bits Position */ #define FPU_MVFR0_FP_rounding_modes_Msk (0xFUL << FPU_MVFR0_FP_rounding_modes_Pos) /*!< MVFR0: FP rounding modes bits Mask */ #define FPU_MVFR0_Short_vectors_Pos 24 /*!< MVFR0: Short vectors bits Position */ #define FPU_MVFR0_Short_vectors_Msk (0xFUL << FPU_MVFR0_Short_vectors_Pos) /*!< MVFR0: Short vectors bits Mask */ #define FPU_MVFR0_Square_root_Pos 20 /*!< MVFR0: Square root bits Position */ #define FPU_MVFR0_Square_root_Msk (0xFUL << FPU_MVFR0_Square_root_Pos) /*!< MVFR0: Square root bits Mask */ #define FPU_MVFR0_Divide_Pos 16 /*!< MVFR0: Divide bits Position */ #define FPU_MVFR0_Divide_Msk (0xFUL << FPU_MVFR0_Divide_Pos) /*!< MVFR0: Divide bits Mask */ #define FPU_MVFR0_FP_excep_trapping_Pos 12 /*!< MVFR0: FP exception trapping bits Position */ #define FPU_MVFR0_FP_excep_trapping_Msk (0xFUL << FPU_MVFR0_FP_excep_trapping_Pos) /*!< MVFR0: FP exception trapping bits Mask */ #define FPU_MVFR0_Double_precision_Pos 8 /*!< MVFR0: Double-precision bits Position */ #define FPU_MVFR0_Double_precision_Msk (0xFUL << FPU_MVFR0_Double_precision_Pos) /*!< MVFR0: Double-precision bits Mask */ #define FPU_MVFR0_Single_precision_Pos 4 /*!< MVFR0: Single-precision bits Position */ #define FPU_MVFR0_Single_precision_Msk (0xFUL << FPU_MVFR0_Single_precision_Pos) /*!< MVFR0: Single-precision bits Mask */ #define FPU_MVFR0_A_SIMD_registers_Pos 0 /*!< MVFR0: A_SIMD registers bits Position */ #define FPU_MVFR0_A_SIMD_registers_Msk (0xFUL /*<< FPU_MVFR0_A_SIMD_registers_Pos*/) /*!< MVFR0: A_SIMD registers bits Mask */ /* Media and FP Feature Register 1 */ #define FPU_MVFR1_FP_fused_MAC_Pos 28 /*!< MVFR1: FP fused MAC bits Position */ #define FPU_MVFR1_FP_fused_MAC_Msk (0xFUL << FPU_MVFR1_FP_fused_MAC_Pos) /*!< MVFR1: FP fused MAC bits Mask */ #define FPU_MVFR1_FP_HPFP_Pos 24 /*!< MVFR1: FP HPFP bits Position */ #define FPU_MVFR1_FP_HPFP_Msk (0xFUL << FPU_MVFR1_FP_HPFP_Pos) /*!< MVFR1: FP HPFP bits Mask */ #define FPU_MVFR1_D_NaN_mode_Pos 4 /*!< MVFR1: D_NaN mode bits Position */ #define FPU_MVFR1_D_NaN_mode_Msk (0xFUL << FPU_MVFR1_D_NaN_mode_Pos) /*!< MVFR1: D_NaN mode bits Mask */ #define FPU_MVFR1_FtZ_mode_Pos 0 /*!< MVFR1: FtZ mode bits Position */ #define FPU_MVFR1_FtZ_mode_Msk (0xFUL /*<< FPU_MVFR1_FtZ_mode_Pos*/) /*!< MVFR1: FtZ mode bits Mask */ /* Media and FP Feature Register 2 */ /*@} end of group CMSIS_FPU */ #endif /** \ingroup CMSIS_core_register \defgroup CMSIS_CoreDebug Core Debug Registers (CoreDebug) \brief Type definitions for the Core Debug Registers @{ */ /** \brief Structure type to access the Core Debug Register (CoreDebug). */ typedef struct { __IO uint32_t DHCSR; /*!< Offset: 0x000 (R/W) Debug Halting Control and Status Register */ __O uint32_t DCRSR; /*!< Offset: 0x004 ( /W) Debug Core Register Selector Register */ __IO uint32_t DCRDR; /*!< Offset: 0x008 (R/W) Debug Core Register Data Register */ __IO uint32_t DEMCR; /*!< Offset: 0x00C (R/W) Debug Exception and Monitor Control Register */ } CoreDebug_Type; /* Debug Halting Control and Status Register */ #define CoreDebug_DHCSR_DBGKEY_Pos 16 /*!< CoreDebug DHCSR: DBGKEY Position */ #define CoreDebug_DHCSR_DBGKEY_Msk (0xFFFFUL << CoreDebug_DHCSR_DBGKEY_Pos) /*!< CoreDebug DHCSR: DBGKEY Mask */ #define CoreDebug_DHCSR_S_RESET_ST_Pos 25 /*!< CoreDebug DHCSR: S_RESET_ST Position */ #define CoreDebug_DHCSR_S_RESET_ST_Msk (1UL << CoreDebug_DHCSR_S_RESET_ST_Pos) /*!< CoreDebug DHCSR: S_RESET_ST Mask */ #define CoreDebug_DHCSR_S_RETIRE_ST_Pos 24 /*!< CoreDebug DHCSR: S_RETIRE_ST Position */ #define CoreDebug_DHCSR_S_RETIRE_ST_Msk (1UL << CoreDebug_DHCSR_S_RETIRE_ST_Pos) /*!< CoreDebug DHCSR: S_RETIRE_ST Mask */ #define CoreDebug_DHCSR_S_LOCKUP_Pos 19 /*!< CoreDebug DHCSR: S_LOCKUP Position */ #define CoreDebug_DHCSR_S_LOCKUP_Msk (1UL << CoreDebug_DHCSR_S_LOCKUP_Pos) /*!< CoreDebug DHCSR: S_LOCKUP Mask */ #define CoreDebug_DHCSR_S_SLEEP_Pos 18 /*!< CoreDebug DHCSR: S_SLEEP Position */ #define CoreDebug_DHCSR_S_SLEEP_Msk (1UL << CoreDebug_DHCSR_S_SLEEP_Pos) /*!< CoreDebug DHCSR: S_SLEEP Mask */ #define CoreDebug_DHCSR_S_HALT_Pos 17 /*!< CoreDebug DHCSR: S_HALT Position */ #define CoreDebug_DHCSR_S_HALT_Msk (1UL << CoreDebug_DHCSR_S_HALT_Pos) /*!< CoreDebug DHCSR: S_HALT Mask */ #define CoreDebug_DHCSR_S_REGRDY_Pos 16 /*!< CoreDebug DHCSR: S_REGRDY Position */ #define CoreDebug_DHCSR_S_REGRDY_Msk (1UL << CoreDebug_DHCSR_S_REGRDY_Pos) /*!< CoreDebug DHCSR: S_REGRDY Mask */ #define CoreDebug_DHCSR_C_SNAPSTALL_Pos 5 /*!< CoreDebug DHCSR: C_SNAPSTALL Position */ #define CoreDebug_DHCSR_C_SNAPSTALL_Msk (1UL << CoreDebug_DHCSR_C_SNAPSTALL_Pos) /*!< CoreDebug DHCSR: C_SNAPSTALL Mask */ #define CoreDebug_DHCSR_C_MASKINTS_Pos 3 /*!< CoreDebug DHCSR: C_MASKINTS Position */ #define CoreDebug_DHCSR_C_MASKINTS_Msk (1UL << CoreDebug_DHCSR_C_MASKINTS_Pos) /*!< CoreDebug DHCSR: C_MASKINTS Mask */ #define CoreDebug_DHCSR_C_STEP_Pos 2 /*!< CoreDebug DHCSR: C_STEP Position */ #define CoreDebug_DHCSR_C_STEP_Msk (1UL << CoreDebug_DHCSR_C_STEP_Pos) /*!< CoreDebug DHCSR: C_STEP Mask */ #define CoreDebug_DHCSR_C_HALT_Pos 1 /*!< CoreDebug DHCSR: C_HALT Position */ #define CoreDebug_DHCSR_C_HALT_Msk (1UL << CoreDebug_DHCSR_C_HALT_Pos) /*!< CoreDebug DHCSR: C_HALT Mask */ #define CoreDebug_DHCSR_C_DEBUGEN_Pos 0 /*!< CoreDebug DHCSR: C_DEBUGEN Position */ #define CoreDebug_DHCSR_C_DEBUGEN_Msk (1UL /*<< CoreDebug_DHCSR_C_DEBUGEN_Pos*/) /*!< CoreDebug DHCSR: C_DEBUGEN Mask */ /* Debug Core Register Selector Register */ #define CoreDebug_DCRSR_REGWnR_Pos 16 /*!< CoreDebug DCRSR: REGWnR Position */ #define CoreDebug_DCRSR_REGWnR_Msk (1UL << CoreDebug_DCRSR_REGWnR_Pos) /*!< CoreDebug DCRSR: REGWnR Mask */ #define CoreDebug_DCRSR_REGSEL_Pos 0 /*!< CoreDebug DCRSR: REGSEL Position */ #define CoreDebug_DCRSR_REGSEL_Msk (0x1FUL /*<< CoreDebug_DCRSR_REGSEL_Pos*/) /*!< CoreDebug DCRSR: REGSEL Mask */ /* Debug Exception and Monitor Control Register */ #define CoreDebug_DEMCR_TRCENA_Pos 24 /*!< CoreDebug DEMCR: TRCENA Position */ #define CoreDebug_DEMCR_TRCENA_Msk (1UL << CoreDebug_DEMCR_TRCENA_Pos) /*!< CoreDebug DEMCR: TRCENA Mask */ #define CoreDebug_DEMCR_MON_REQ_Pos 19 /*!< CoreDebug DEMCR: MON_REQ Position */ #define CoreDebug_DEMCR_MON_REQ_Msk (1UL << CoreDebug_DEMCR_MON_REQ_Pos) /*!< CoreDebug DEMCR: MON_REQ Mask */ #define CoreDebug_DEMCR_MON_STEP_Pos 18 /*!< CoreDebug DEMCR: MON_STEP Position */ #define CoreDebug_DEMCR_MON_STEP_Msk (1UL << CoreDebug_DEMCR_MON_STEP_Pos) /*!< CoreDebug DEMCR: MON_STEP Mask */ #define CoreDebug_DEMCR_MON_PEND_Pos 17 /*!< CoreDebug DEMCR: MON_PEND Position */ #define CoreDebug_DEMCR_MON_PEND_Msk (1UL << CoreDebug_DEMCR_MON_PEND_Pos) /*!< CoreDebug DEMCR: MON_PEND Mask */ #define CoreDebug_DEMCR_MON_EN_Pos 16 /*!< CoreDebug DEMCR: MON_EN Position */ #define CoreDebug_DEMCR_MON_EN_Msk (1UL << CoreDebug_DEMCR_MON_EN_Pos) /*!< CoreDebug DEMCR: MON_EN Mask */ #define CoreDebug_DEMCR_VC_HARDERR_Pos 10 /*!< CoreDebug DEMCR: VC_HARDERR Position */ #define CoreDebug_DEMCR_VC_HARDERR_Msk (1UL << CoreDebug_DEMCR_VC_HARDERR_Pos) /*!< CoreDebug DEMCR: VC_HARDERR Mask */ #define CoreDebug_DEMCR_VC_INTERR_Pos 9 /*!< CoreDebug DEMCR: VC_INTERR Position */ #define CoreDebug_DEMCR_VC_INTERR_Msk (1UL << CoreDebug_DEMCR_VC_INTERR_Pos) /*!< CoreDebug DEMCR: VC_INTERR Mask */ #define CoreDebug_DEMCR_VC_BUSERR_Pos 8 /*!< CoreDebug DEMCR: VC_BUSERR Position */ #define CoreDebug_DEMCR_VC_BUSERR_Msk (1UL << CoreDebug_DEMCR_VC_BUSERR_Pos) /*!< CoreDebug DEMCR: VC_BUSERR Mask */ #define CoreDebug_DEMCR_VC_STATERR_Pos 7 /*!< CoreDebug DEMCR: VC_STATERR Position */ #define CoreDebug_DEMCR_VC_STATERR_Msk (1UL << CoreDebug_DEMCR_VC_STATERR_Pos) /*!< CoreDebug DEMCR: VC_STATERR Mask */ #define CoreDebug_DEMCR_VC_CHKERR_Pos 6 /*!< CoreDebug DEMCR: VC_CHKERR Position */ #define CoreDebug_DEMCR_VC_CHKERR_Msk (1UL << CoreDebug_DEMCR_VC_CHKERR_Pos) /*!< CoreDebug DEMCR: VC_CHKERR Mask */ #define CoreDebug_DEMCR_VC_NOCPERR_Pos 5 /*!< CoreDebug DEMCR: VC_NOCPERR Position */ #define CoreDebug_DEMCR_VC_NOCPERR_Msk (1UL << CoreDebug_DEMCR_VC_NOCPERR_Pos) /*!< CoreDebug DEMCR: VC_NOCPERR Mask */ #define CoreDebug_DEMCR_VC_MMERR_Pos 4 /*!< CoreDebug DEMCR: VC_MMERR Position */ #define CoreDebug_DEMCR_VC_MMERR_Msk (1UL << CoreDebug_DEMCR_VC_MMERR_Pos) /*!< CoreDebug DEMCR: VC_MMERR Mask */ #define CoreDebug_DEMCR_VC_CORERESET_Pos 0 /*!< CoreDebug DEMCR: VC_CORERESET Position */ #define CoreDebug_DEMCR_VC_CORERESET_Msk (1UL /*<< CoreDebug_DEMCR_VC_CORERESET_Pos*/) /*!< CoreDebug DEMCR: VC_CORERESET Mask */ /*@} end of group CMSIS_CoreDebug */ /** \ingroup CMSIS_core_register \defgroup CMSIS_core_base Core Definitions \brief Definitions for base addresses, unions, and structures. @{ */ /* Memory mapping of Cortex-M4 Hardware */ #define SCS_BASE (0xE000E000UL) /*!< System Control Space Base Address */ #define ITM_BASE (0xE0000000UL) /*!< ITM Base Address */ #define DWT_BASE (0xE0001000UL) /*!< DWT Base Address */ #define TPI_BASE (0xE0040000UL) /*!< TPI Base Address */ #define CoreDebug_BASE (0xE000EDF0UL) /*!< Core Debug Base Address */ #define SysTick_BASE (SCS_BASE + 0x0010UL) /*!< SysTick Base Address */ #define NVIC_BASE (SCS_BASE + 0x0100UL) /*!< NVIC Base Address */ #define SCB_BASE (SCS_BASE + 0x0D00UL) /*!< System Control Block Base Address */ #define SCnSCB ((SCnSCB_Type *) SCS_BASE ) /*!< System control Register not in SCB */ #define SCB ((SCB_Type *) SCB_BASE ) /*!< SCB configuration struct */ #define SysTick ((SysTick_Type *) SysTick_BASE ) /*!< SysTick configuration struct */ #define NVIC ((NVIC_Type *) NVIC_BASE ) /*!< NVIC configuration struct */ #define ITM ((ITM_Type *) ITM_BASE ) /*!< ITM configuration struct */ #define DWT ((DWT_Type *) DWT_BASE ) /*!< DWT configuration struct */ #define TPI ((TPI_Type *) TPI_BASE ) /*!< TPI configuration struct */ #define CoreDebug ((CoreDebug_Type *) CoreDebug_BASE) /*!< Core Debug configuration struct */ #if (__MPU_PRESENT == 1) #define MPU_BASE (SCS_BASE + 0x0D90UL) /*!< Memory Protection Unit */ #define MPU ((MPU_Type *) MPU_BASE ) /*!< Memory Protection Unit */ #endif #if (__FPU_PRESENT == 1) #define FPU_BASE (SCS_BASE + 0x0F30UL) /*!< Floating Point Unit */ #define FPU ((FPU_Type *) FPU_BASE ) /*!< Floating Point Unit */ #endif /*@} */ /******************************************************************************* * Hardware Abstraction Layer Core Function Interface contains: - Core NVIC Functions - Core SysTick Functions - Core Debug Functions - Core Register Access Functions ******************************************************************************/ /** \defgroup CMSIS_Core_FunctionInterface Functions and Instructions Reference */ /* ########################## NVIC functions #################################### */ /** \ingroup CMSIS_Core_FunctionInterface \defgroup CMSIS_Core_NVICFunctions NVIC Functions \brief Functions that manage interrupts and exceptions via the NVIC. @{ */ /** \brief Set Priority Grouping The function sets the priority grouping field using the required unlock sequence. The parameter PriorityGroup is assigned to the field SCB->AIRCR [10:8] PRIGROUP field. Only values from 0..7 are used. In case of a conflict between priority grouping and available priority bits (__NVIC_PRIO_BITS), the smallest possible priority group is set. \param [in] PriorityGroup Priority grouping field. */ __STATIC_INLINE void NVIC_SetPriorityGrouping(uint32_t PriorityGroup) { uint32_t reg_value; uint32_t PriorityGroupTmp = (PriorityGroup & (uint32_t)0x07UL); /* only values 0..7 are used */ reg_value = SCB->AIRCR; /* read old register configuration */ reg_value &= ~((uint32_t)(SCB_AIRCR_VECTKEY_Msk | SCB_AIRCR_PRIGROUP_Msk)); /* clear bits to change */ reg_value = (reg_value | ((uint32_t)0x5FAUL << SCB_AIRCR_VECTKEY_Pos) | (PriorityGroupTmp << 8) ); /* Insert write key and priorty group */ SCB->AIRCR = reg_value; } /** \brief Get Priority Grouping The function reads the priority grouping field from the NVIC Interrupt Controller. \return Priority grouping field (SCB->AIRCR [10:8] PRIGROUP field). */ __STATIC_INLINE uint32_t NVIC_GetPriorityGrouping(void) { return ((uint32_t)((SCB->AIRCR & SCB_AIRCR_PRIGROUP_Msk) >> SCB_AIRCR_PRIGROUP_Pos)); } /** \brief Enable External Interrupt The function enables a device-specific interrupt in the NVIC interrupt controller. \param [in] IRQn External interrupt number. Value cannot be negative. */ __STATIC_INLINE void NVIC_EnableIRQ(IRQn_Type IRQn) { NVIC->ISER[(((uint32_t)(int32_t)IRQn) >> 5UL)] = (uint32_t)(1UL << (((uint32_t)(int32_t)IRQn) & 0x1FUL)); } /** \brief Disable External Interrupt The function disables a device-specific interrupt in the NVIC interrupt controller. \param [in] IRQn External interrupt number. Value cannot be negative. */ __STATIC_INLINE void NVIC_DisableIRQ(IRQn_Type IRQn) { NVIC->ICER[(((uint32_t)(int32_t)IRQn) >> 5UL)] = (uint32_t)(1UL << (((uint32_t)(int32_t)IRQn) & 0x1FUL)); } /** \brief Get Pending Interrupt The function reads the pending register in the NVIC and returns the pending bit for the specified interrupt. \param [in] IRQn Interrupt number. \return 0 Interrupt status is not pending. \return 1 Interrupt status is pending. */ __STATIC_INLINE uint32_t NVIC_GetPendingIRQ(IRQn_Type IRQn) { return((uint32_t)(((NVIC->ISPR[(((uint32_t)(int32_t)IRQn) >> 5UL)] & (1UL << (((uint32_t)(int32_t)IRQn) & 0x1FUL))) != 0UL) ? 1UL : 0UL)); } /** \brief Set Pending Interrupt The function sets the pending bit of an external interrupt. \param [in] IRQn Interrupt number. Value cannot be negative. */ __STATIC_INLINE void NVIC_SetPendingIRQ(IRQn_Type IRQn) { NVIC->ISPR[(((uint32_t)(int32_t)IRQn) >> 5UL)] = (uint32_t)(1UL << (((uint32_t)(int32_t)IRQn) & 0x1FUL)); } /** \brief Clear Pending Interrupt The function clears the pending bit of an external interrupt. \param [in] IRQn External interrupt number. Value cannot be negative. */ __STATIC_INLINE void NVIC_ClearPendingIRQ(IRQn_Type IRQn) { NVIC->ICPR[(((uint32_t)(int32_t)IRQn) >> 5UL)] = (uint32_t)(1UL << (((uint32_t)(int32_t)IRQn) & 0x1FUL)); } /** \brief Get Active Interrupt The function reads the active register in NVIC and returns the active bit. \param [in] IRQn Interrupt number. \return 0 Interrupt status is not active. \return 1 Interrupt status is active. */ __STATIC_INLINE uint32_t NVIC_GetActive(IRQn_Type IRQn) { return((uint32_t)(((NVIC->IABR[(((uint32_t)(int32_t)IRQn) >> 5UL)] & (1UL << (((uint32_t)(int32_t)IRQn) & 0x1FUL))) != 0UL) ? 1UL : 0UL)); } /** \brief Set Interrupt Priority The function sets the priority of an interrupt. \note The priority cannot be set for every core interrupt. \param [in] IRQn Interrupt number. \param [in] priority Priority to set. */ __STATIC_INLINE void NVIC_SetPriority(IRQn_Type IRQn, uint32_t priority) { if((int32_t)IRQn < 0) { SCB->SHPR[(((uint32_t)(int32_t)IRQn) & 0xFUL)-4UL] = (uint8_t)((priority << (8 - __NVIC_PRIO_BITS)) & (uint32_t)0xFFUL); } else { NVIC->IP[((uint32_t)(int32_t)IRQn)] = (uint8_t)((priority << (8 - __NVIC_PRIO_BITS)) & (uint32_t)0xFFUL); } } /** \brief Get Interrupt Priority The function reads the priority of an interrupt. The interrupt number can be positive to specify an external (device specific) interrupt, or negative to specify an internal (core) interrupt. \param [in] IRQn Interrupt number. \return Interrupt Priority. Value is aligned automatically to the implemented priority bits of the microcontroller. */ __STATIC_INLINE uint32_t NVIC_GetPriority(IRQn_Type IRQn) { if((int32_t)IRQn < 0) { return(((uint32_t)SCB->SHPR[(((uint32_t)(int32_t)IRQn) & 0xFUL)-4UL] >> (8 - __NVIC_PRIO_BITS))); } else { return(((uint32_t)NVIC->IP[((uint32_t)(int32_t)IRQn)] >> (8 - __NVIC_PRIO_BITS))); } } /** \brief Encode Priority The function encodes the priority for an interrupt with the given priority group, preemptive priority value, and subpriority value. In case of a conflict between priority grouping and available priority bits (__NVIC_PRIO_BITS), the smallest possible priority group is set. \param [in] PriorityGroup Used priority group. \param [in] PreemptPriority Preemptive priority value (starting from 0). \param [in] SubPriority Subpriority value (starting from 0). \return Encoded priority. Value can be used in the function \ref NVIC_SetPriority(). */ __STATIC_INLINE uint32_t NVIC_EncodePriority (uint32_t PriorityGroup, uint32_t PreemptPriority, uint32_t SubPriority) { uint32_t PriorityGroupTmp = (PriorityGroup & (uint32_t)0x07UL); /* only values 0..7 are used */ uint32_t PreemptPriorityBits; uint32_t SubPriorityBits; PreemptPriorityBits = ((7UL - PriorityGroupTmp) > (uint32_t)(__NVIC_PRIO_BITS)) ? (uint32_t)(__NVIC_PRIO_BITS) : (uint32_t)(7UL - PriorityGroupTmp); SubPriorityBits = ((PriorityGroupTmp + (uint32_t)(__NVIC_PRIO_BITS)) < (uint32_t)7UL) ? (uint32_t)0UL : (uint32_t)((PriorityGroupTmp - 7UL) + (uint32_t)(__NVIC_PRIO_BITS)); return ( ((PreemptPriority & (uint32_t)((1UL << (PreemptPriorityBits)) - 1UL)) << SubPriorityBits) | ((SubPriority & (uint32_t)((1UL << (SubPriorityBits )) - 1UL))) ); } /** \brief Decode Priority The function decodes an interrupt priority value with a given priority group to preemptive priority value and subpriority value. In case of a conflict between priority grouping and available priority bits (__NVIC_PRIO_BITS) the smallest possible priority group is set. \param [in] Priority Priority value, which can be retrieved with the function \ref NVIC_GetPriority(). \param [in] PriorityGroup Used priority group. \param [out] pPreemptPriority Preemptive priority value (starting from 0). \param [out] pSubPriority Subpriority value (starting from 0). */ __STATIC_INLINE void NVIC_DecodePriority (uint32_t Priority, uint32_t PriorityGroup, uint32_t* pPreemptPriority, uint32_t* pSubPriority) { uint32_t PriorityGroupTmp = (PriorityGroup & (uint32_t)0x07UL); /* only values 0..7 are used */ uint32_t PreemptPriorityBits; uint32_t SubPriorityBits; PreemptPriorityBits = ((7UL - PriorityGroupTmp) > (uint32_t)(__NVIC_PRIO_BITS)) ? (uint32_t)(__NVIC_PRIO_BITS) : (uint32_t)(7UL - PriorityGroupTmp); SubPriorityBits = ((PriorityGroupTmp + (uint32_t)(__NVIC_PRIO_BITS)) < (uint32_t)7UL) ? (uint32_t)0UL : (uint32_t)((PriorityGroupTmp - 7UL) + (uint32_t)(__NVIC_PRIO_BITS)); *pPreemptPriority = (Priority >> SubPriorityBits) & (uint32_t)((1UL << (PreemptPriorityBits)) - 1UL); *pSubPriority = (Priority ) & (uint32_t)((1UL << (SubPriorityBits )) - 1UL); } /** \brief System Reset The function initiates a system reset request to reset the MCU. */ __STATIC_INLINE void NVIC_SystemReset(void) { __DSB(); /* Ensure all outstanding memory accesses included buffered write are completed before reset */ SCB->AIRCR = (uint32_t)((0x5FAUL << SCB_AIRCR_VECTKEY_Pos) | (SCB->AIRCR & SCB_AIRCR_PRIGROUP_Msk) | SCB_AIRCR_SYSRESETREQ_Msk ); /* Keep priority group unchanged */ __DSB(); /* Ensure completion of memory access */ while(1) { __NOP(); } /* wait until reset */ } /*@} end of CMSIS_Core_NVICFunctions */ /* ########################## FPU functions #################################### */ /** \ingroup CMSIS_Core_FunctionInterface \defgroup CMSIS_Core_FpuFunctions FPU Functions \brief Function that provides FPU type. @{ */ /** \fn uint32_t SCB_GetFPUType(void) \brief get FPU type \returns - \b 0: No FPU - \b 1: Single precision FPU - \b 2: Double + Single precision FPU */ __STATIC_INLINE uint32_t SCB_GetFPUType(void) { uint32_t mvfr0; mvfr0 = SCB->MVFR0; if ((mvfr0 & 0x00000FF0UL) == 0x220UL) { return 2UL; // Double + Single precision FPU } else if ((mvfr0 & 0x00000FF0UL) == 0x020UL) { return 1UL; // Single precision FPU } else { return 0UL; // No FPU } } /*@} end of CMSIS_Core_FpuFunctions */ /* ########################## Cache functions #################################### */ /** \ingroup CMSIS_Core_FunctionInterface \defgroup CMSIS_Core_CacheFunctions Cache Functions \brief Functions that configure Instruction and Data cache. @{ */ /* Cache Size ID Register Macros */ #define CCSIDR_WAYS(x) (((x) & SCB_CCSIDR_ASSOCIATIVITY_Msk) >> SCB_CCSIDR_ASSOCIATIVITY_Pos) #define CCSIDR_SETS(x) (((x) & SCB_CCSIDR_NUMSETS_Msk ) >> SCB_CCSIDR_NUMSETS_Pos ) #define CCSIDR_LSSHIFT(x) (((x) & SCB_CCSIDR_LINESIZE_Msk ) /*>> SCB_CCSIDR_LINESIZE_Pos*/ ) /** \brief Enable I-Cache The function turns on I-Cache */ __STATIC_INLINE void SCB_EnableICache (void) { #if (__ICACHE_PRESENT == 1) __DSB(); __ISB(); SCB->ICIALLU = 0UL; // invalidate I-Cache SCB->CCR |= (uint32_t)SCB_CCR_IC_Msk; // enable I-Cache __DSB(); __ISB(); #endif } /** \brief Disable I-Cache The function turns off I-Cache */ __STATIC_INLINE void SCB_DisableICache (void) { #if (__ICACHE_PRESENT == 1) __DSB(); __ISB(); SCB->CCR &= ~(uint32_t)SCB_CCR_IC_Msk; // disable I-Cache SCB->ICIALLU = 0UL; // invalidate I-Cache __DSB(); __ISB(); #endif } /** \brief Invalidate I-Cache The function invalidates I-Cache */ __STATIC_INLINE void SCB_InvalidateICache (void) { #if (__ICACHE_PRESENT == 1) __DSB(); __ISB(); SCB->ICIALLU = 0UL; __DSB(); __ISB(); #endif } /** \brief Enable D-Cache The function turns on D-Cache */ __STATIC_INLINE void SCB_EnableDCache (void) { #if (__DCACHE_PRESENT == 1) uint32_t ccsidr, sshift, wshift, sw; uint32_t sets, ways; SCB->CSSELR = (0UL << 1) | 0UL; // Level 1 data cache ccsidr = SCB->CCSIDR; sets = (uint32_t)(CCSIDR_SETS(ccsidr)); sshift = (uint32_t)(CCSIDR_LSSHIFT(ccsidr) + 4UL); ways = (uint32_t)(CCSIDR_WAYS(ccsidr)); wshift = (uint32_t)((uint32_t)__CLZ(ways) & 0x1FUL); __DSB(); do { // invalidate D-Cache uint32_t tmpways = ways; do { sw = ((tmpways << wshift) | (sets << sshift)); SCB->DCISW = sw; } while(tmpways--); } while(sets--); __DSB(); SCB->CCR |= (uint32_t)SCB_CCR_DC_Msk; // enable D-Cache __DSB(); __ISB(); #endif } /** \brief Disable D-Cache The function turns off D-Cache */ __STATIC_INLINE void SCB_DisableDCache (void) { #if (__DCACHE_PRESENT == 1) uint32_t ccsidr, sshift, wshift, sw; uint32_t sets, ways; SCB->CSSELR = (0UL << 1) | 0UL; // Level 1 data cache ccsidr = SCB->CCSIDR; sets = (uint32_t)(CCSIDR_SETS(ccsidr)); sshift = (uint32_t)(CCSIDR_LSSHIFT(ccsidr) + 4UL); ways = (uint32_t)(CCSIDR_WAYS(ccsidr)); wshift = (uint32_t)((uint32_t)__CLZ(ways) & 0x1FUL); __DSB(); SCB->CCR &= ~(uint32_t)SCB_CCR_DC_Msk; // disable D-Cache do { // clean & invalidate D-Cache uint32_t tmpways = ways; do { sw = ((tmpways << wshift) | (sets << sshift)); SCB->DCCISW = sw; } while(tmpways--); } while(sets--); __DSB(); __ISB(); #endif } /** \brief Invalidate D-Cache The function invalidates D-Cache */ __STATIC_INLINE void SCB_InvalidateDCache (void) { #if (__DCACHE_PRESENT == 1) uint32_t ccsidr, sshift, wshift, sw; uint32_t sets, ways; SCB->CSSELR = (0UL << 1) | 0UL; // Level 1 data cache ccsidr = SCB->CCSIDR; sets = (uint32_t)(CCSIDR_SETS(ccsidr)); sshift = (uint32_t)(CCSIDR_LSSHIFT(ccsidr) + 4UL); ways = (uint32_t)(CCSIDR_WAYS(ccsidr)); wshift = (uint32_t)((uint32_t)__CLZ(ways) & 0x1FUL); __DSB(); do { // invalidate D-Cache uint32_t tmpways = ways; do { sw = ((tmpways << wshift) | (sets << sshift)); SCB->DCISW = sw; } while(tmpways--); } while(sets--); __DSB(); __ISB(); #endif } /** \brief Clean D-Cache The function cleans D-Cache */ __STATIC_INLINE void SCB_CleanDCache (void) { #if (__DCACHE_PRESENT == 1) uint32_t ccsidr, sshift, wshift, sw; uint32_t sets, ways; SCB->CSSELR = (0UL << 1) | 0UL; // Level 1 data cache ccsidr = SCB->CCSIDR; sets = (uint32_t)(CCSIDR_SETS(ccsidr)); sshift = (uint32_t)(CCSIDR_LSSHIFT(ccsidr) + 4UL); ways = (uint32_t)(CCSIDR_WAYS(ccsidr)); wshift = (uint32_t)((uint32_t)__CLZ(ways) & 0x1FUL); __DSB(); do { // clean D-Cache uint32_t tmpways = ways; do { sw = ((tmpways << wshift) | (sets << sshift)); SCB->DCCSW = sw; } while(tmpways--); } while(sets--); __DSB(); __ISB(); #endif } /** \brief Clean & Invalidate D-Cache The function cleans and Invalidates D-Cache */ __STATIC_INLINE void SCB_CleanInvalidateDCache (void) { #if (__DCACHE_PRESENT == 1) uint32_t ccsidr, sshift, wshift, sw; uint32_t sets, ways; SCB->CSSELR = (0UL << 1) | 0UL; // Level 1 data cache ccsidr = SCB->CCSIDR; sets = (uint32_t)(CCSIDR_SETS(ccsidr)); sshift = (uint32_t)(CCSIDR_LSSHIFT(ccsidr) + 4UL); ways = (uint32_t)(CCSIDR_WAYS(ccsidr)); wshift = (uint32_t)((uint32_t)__CLZ(ways) & 0x1FUL); __DSB(); do { // clean & invalidate D-Cache uint32_t tmpways = ways; do { sw = ((tmpways << wshift) | (sets << sshift)); SCB->DCCISW = sw; } while(tmpways--); } while(sets--); __DSB(); __ISB(); #endif } /** \fn void SCB_InvalidateDCache_by_Addr(volatile uint32_t *addr, int32_t dsize) \brief D-Cache Invalidate by address \param[in] addr address (aligned to 32-byte boundary) \param[in] dsize size of memory block (in number of bytes) */ __STATIC_INLINE void SCB_InvalidateDCache_by_Addr (uint32_t *addr, int32_t dsize) { #if (__DCACHE_PRESENT == 1) int32_t op_size = dsize; uint32_t op_addr = (uint32_t)addr; uint32_t linesize = 32UL; // in Cortex-M7 size of cache line is fixed to 8 words (32 bytes) __DSB(); while (op_size > 0) { SCB->DCIMVAC = op_addr; op_addr += linesize; op_size -= (int32_t)linesize; } __DSB(); __ISB(); #endif } /** \fn void SCB_CleanDCache_by_Addr(volatile uint32_t *addr, int32_t dsize) \brief D-Cache Clean by address \param[in] addr address (aligned to 32-byte boundary) \param[in] dsize size of memory block (in number of bytes) */ __STATIC_INLINE void SCB_CleanDCache_by_Addr (uint32_t *addr, int32_t dsize) { #if (__DCACHE_PRESENT == 1) int32_t op_size = dsize; uint32_t op_addr = (uint32_t) addr; uint32_t linesize = 32UL; // in Cortex-M7 size of cache line is fixed to 8 words (32 bytes) __DSB(); while (op_size > 0) { SCB->DCCMVAC = op_addr; op_addr += linesize; op_size -= (int32_t)linesize; } __DSB(); __ISB(); #endif } /** \fn void SCB_CleanInvalidateDCache_by_Addr(volatile uint32_t *addr, int32_t dsize) \brief D-Cache Clean and Invalidate by address \param[in] addr address (aligned to 32-byte boundary) \param[in] dsize size of memory block (in number of bytes) */ __STATIC_INLINE void SCB_CleanInvalidateDCache_by_Addr (uint32_t *addr, int32_t dsize) { #if (__DCACHE_PRESENT == 1) int32_t op_size = dsize; uint32_t op_addr = (uint32_t) addr; uint32_t linesize = 32UL; // in Cortex-M7 size of cache line is fixed to 8 words (32 bytes) __DSB(); while (op_size > 0) { SCB->DCCIMVAC = op_addr; op_addr += linesize; op_size -= (int32_t)linesize; } __DSB(); __ISB(); #endif } /*@} end of CMSIS_Core_CacheFunctions */ /* ################################## SysTick function ############################################ */ /** \ingroup CMSIS_Core_FunctionInterface \defgroup CMSIS_Core_SysTickFunctions SysTick Functions \brief Functions that configure the System. @{ */ #if (__Vendor_SysTickConfig == 0) /** \brief System Tick Configuration The function initializes the System Timer and its interrupt, and starts the System Tick Timer. Counter is in free running mode to generate periodic interrupts. \param [in] ticks Number of ticks between two interrupts. \return 0 Function succeeded. \return 1 Function failed. \note When the variable __Vendor_SysTickConfig is set to 1, then the function SysTick_Config is not included. In this case, the file device.h must contain a vendor-specific implementation of this function. */ __STATIC_INLINE uint32_t SysTick_Config(uint32_t ticks) { if ((ticks - 1UL) > SysTick_LOAD_RELOAD_Msk) { return (1UL); } /* Reload value impossible */ SysTick->LOAD = (uint32_t)(ticks - 1UL); /* set reload register */ NVIC_SetPriority (SysTick_IRQn, (1UL << __NVIC_PRIO_BITS) - 1UL); /* set Priority for Systick Interrupt */ SysTick->VAL = 0UL; /* Load the SysTick Counter Value */ SysTick->CTRL = SysTick_CTRL_CLKSOURCE_Msk | SysTick_CTRL_TICKINT_Msk | SysTick_CTRL_ENABLE_Msk; /* Enable SysTick IRQ and SysTick Timer */ return (0UL); /* Function successful */ } #endif /*@} end of CMSIS_Core_SysTickFunctions */ /* ##################################### Debug In/Output function ########################################### */ /** \ingroup CMSIS_Core_FunctionInterface \defgroup CMSIS_core_DebugFunctions ITM Functions \brief Functions that access the ITM debug interface. @{ */ extern volatile int32_t ITM_RxBuffer; /*!< External variable to receive characters. */ #define ITM_RXBUFFER_EMPTY 0x5AA55AA5 /*!< Value identifying \ref ITM_RxBuffer is ready for next character. */ /** \brief ITM Send Character The function transmits a character via the ITM channel 0, and \li Just returns when no debugger is connected that has booked the output. \li Is blocking when a debugger is connected, but the previous character sent has not been transmitted. \param [in] ch Character to transmit. \returns Character to transmit. */ __STATIC_INLINE uint32_t ITM_SendChar (uint32_t ch) { if (((ITM->TCR & ITM_TCR_ITMENA_Msk) != 0UL) && /* ITM enabled */ ((ITM->TER & 1UL ) != 0UL) ) /* ITM Port #0 enabled */ { while (ITM->PORT[0].u32 == 0UL) { __NOP(); } ITM->PORT[0].u8 = (uint8_t)ch; } return (ch); } /** \brief ITM Receive Character The function inputs a character via the external variable \ref ITM_RxBuffer. \return Received character. \return -1 No character pending. */ __STATIC_INLINE int32_t ITM_ReceiveChar (void) { int32_t ch = -1; /* no character available */ if (ITM_RxBuffer != ITM_RXBUFFER_EMPTY) { ch = ITM_RxBuffer; ITM_RxBuffer = ITM_RXBUFFER_EMPTY; /* ready for next character */ } return (ch); } /** \brief ITM Check Character The function checks whether a character is pending for reading in the variable \ref ITM_RxBuffer. \return 0 No character available. \return 1 Character available. */ __STATIC_INLINE int32_t ITM_CheckChar (void) { if (ITM_RxBuffer == ITM_RXBUFFER_EMPTY) { return (0); /* no character available */ } else { return (1); /* character available */ } } /*@} end of CMSIS_core_DebugFunctions */ #ifdef __cplusplus } #endif #endif /* __CORE_CM7_H_DEPENDANT */ #endif /* __CMSIS_GENERIC */ ================================================ FILE: Zelig/mbed/TARGET_LPC1768/core_cmFunc.h ================================================ /**************************************************************************//** * @file core_cmFunc.h * @brief CMSIS Cortex-M Core Function Access Header File * @version V3.20 * @date 25. February 2013 * * @note * ******************************************************************************/ /* Copyright (c) 2009 - 2013 ARM LIMITED All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: - Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. - Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. - Neither the name of ARM 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 COPYRIGHT HOLDERS AND 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. ---------------------------------------------------------------------------*/ #ifndef __CORE_CMFUNC_H #define __CORE_CMFUNC_H /* ########################### Core Function Access ########################### */ /** \ingroup CMSIS_Core_FunctionInterface \defgroup CMSIS_Core_RegAccFunctions CMSIS Core Register Access Functions @{ */ #if defined ( __CC_ARM ) /*------------------RealView Compiler -----------------*/ /* ARM armcc specific functions */ #if (__ARMCC_VERSION < 400677) #error "Please use ARM Compiler Toolchain V4.0.677 or later!" #endif /* intrinsic void __enable_irq(); */ /* intrinsic void __disable_irq(); */ /** \brief Get Control Register This function returns the content of the Control Register. \return Control Register value */ __STATIC_INLINE uint32_t __get_CONTROL(void) { register uint32_t __regControl __ASM("control"); return(__regControl); } /** \brief Set Control Register This function writes the given value to the Control Register. \param [in] control Control Register value to set */ __STATIC_INLINE void __set_CONTROL(uint32_t control) { register uint32_t __regControl __ASM("control"); __regControl = control; } /** \brief Get IPSR Register This function returns the content of the IPSR Register. \return IPSR Register value */ __STATIC_INLINE uint32_t __get_IPSR(void) { register uint32_t __regIPSR __ASM("ipsr"); return(__regIPSR); } /** \brief Get APSR Register This function returns the content of the APSR Register. \return APSR Register value */ __STATIC_INLINE uint32_t __get_APSR(void) { register uint32_t __regAPSR __ASM("apsr"); return(__regAPSR); } /** \brief Get xPSR Register This function returns the content of the xPSR Register. \return xPSR Register value */ __STATIC_INLINE uint32_t __get_xPSR(void) { register uint32_t __regXPSR __ASM("xpsr"); return(__regXPSR); } /** \brief Get Process Stack Pointer This function returns the current value of the Process Stack Pointer (PSP). \return PSP Register value */ __STATIC_INLINE uint32_t __get_PSP(void) { register uint32_t __regProcessStackPointer __ASM("psp"); return(__regProcessStackPointer); } /** \brief Set Process Stack Pointer This function assigns the given value to the Process Stack Pointer (PSP). \param [in] topOfProcStack Process Stack Pointer value to set */ __STATIC_INLINE void __set_PSP(uint32_t topOfProcStack) { register uint32_t __regProcessStackPointer __ASM("psp"); __regProcessStackPointer = topOfProcStack; } /** \brief Get Main Stack Pointer This function returns the current value of the Main Stack Pointer (MSP). \return MSP Register value */ __STATIC_INLINE uint32_t __get_MSP(void) { register uint32_t __regMainStackPointer __ASM("msp"); return(__regMainStackPointer); } /** \brief Set Main Stack Pointer This function assigns the given value to the Main Stack Pointer (MSP). \param [in] topOfMainStack Main Stack Pointer value to set */ __STATIC_INLINE void __set_MSP(uint32_t topOfMainStack) { register uint32_t __regMainStackPointer __ASM("msp"); __regMainStackPointer = topOfMainStack; } /** \brief Get Priority Mask This function returns the current state of the priority mask bit from the Priority Mask Register. \return Priority Mask value */ __STATIC_INLINE uint32_t __get_PRIMASK(void) { register uint32_t __regPriMask __ASM("primask"); return(__regPriMask); } /** \brief Set Priority Mask This function assigns the given value to the Priority Mask Register. \param [in] priMask Priority Mask */ __STATIC_INLINE void __set_PRIMASK(uint32_t priMask) { register uint32_t __regPriMask __ASM("primask"); __regPriMask = (priMask); } #if (__CORTEX_M >= 0x03) /** \brief Enable FIQ This function enables FIQ interrupts by clearing the F-bit in the CPSR. Can only be executed in Privileged modes. */ #define __enable_fault_irq __enable_fiq /** \brief Disable FIQ This function disables FIQ interrupts by setting the F-bit in the CPSR. Can only be executed in Privileged modes. */ #define __disable_fault_irq __disable_fiq /** \brief Get Base Priority This function returns the current value of the Base Priority register. \return Base Priority register value */ __STATIC_INLINE uint32_t __get_BASEPRI(void) { register uint32_t __regBasePri __ASM("basepri"); return(__regBasePri); } /** \brief Set Base Priority This function assigns the given value to the Base Priority register. \param [in] basePri Base Priority value to set */ __STATIC_INLINE void __set_BASEPRI(uint32_t basePri) { register uint32_t __regBasePri __ASM("basepri"); __regBasePri = (basePri & 0xff); } /** \brief Get Fault Mask This function returns the current value of the Fault Mask register. \return Fault Mask register value */ __STATIC_INLINE uint32_t __get_FAULTMASK(void) { register uint32_t __regFaultMask __ASM("faultmask"); return(__regFaultMask); } /** \brief Set Fault Mask This function assigns the given value to the Fault Mask register. \param [in] faultMask Fault Mask value to set */ __STATIC_INLINE void __set_FAULTMASK(uint32_t faultMask) { register uint32_t __regFaultMask __ASM("faultmask"); __regFaultMask = (faultMask & (uint32_t)1); } #endif /* (__CORTEX_M >= 0x03) */ #if (__CORTEX_M == 0x04) /** \brief Get FPSCR This function returns the current value of the Floating Point Status/Control register. \return Floating Point Status/Control register value */ __STATIC_INLINE uint32_t __get_FPSCR(void) { #if (__FPU_PRESENT == 1) && (__FPU_USED == 1) register uint32_t __regfpscr __ASM("fpscr"); return(__regfpscr); #else return(0); #endif } /** \brief Set FPSCR This function assigns the given value to the Floating Point Status/Control register. \param [in] fpscr Floating Point Status/Control value to set */ __STATIC_INLINE void __set_FPSCR(uint32_t fpscr) { #if (__FPU_PRESENT == 1) && (__FPU_USED == 1) register uint32_t __regfpscr __ASM("fpscr"); __regfpscr = (fpscr); #endif } #endif /* (__CORTEX_M == 0x04) */ #elif defined ( __ICCARM__ ) /*------------------ ICC Compiler -------------------*/ /* IAR iccarm specific functions */ #include #elif defined ( __TMS470__ ) /*---------------- TI CCS Compiler ------------------*/ /* TI CCS specific functions */ #include #elif defined ( __GNUC__ ) /*------------------ GNU Compiler ---------------------*/ /* GNU gcc specific functions */ /** \brief Enable IRQ Interrupts This function enables IRQ interrupts by clearing the I-bit in the CPSR. Can only be executed in Privileged modes. */ __attribute__( ( always_inline ) ) __STATIC_INLINE void __enable_irq(void) { __ASM volatile ("cpsie i" : : : "memory"); } /** \brief Disable IRQ Interrupts This function disables IRQ interrupts by setting the I-bit in the CPSR. Can only be executed in Privileged modes. */ __attribute__( ( always_inline ) ) __STATIC_INLINE void __disable_irq(void) { __ASM volatile ("cpsid i" : : : "memory"); } /** \brief Get Control Register This function returns the content of the Control Register. \return Control Register value */ __attribute__( ( always_inline ) ) __STATIC_INLINE uint32_t __get_CONTROL(void) { uint32_t result; __ASM volatile ("MRS %0, control" : "=r" (result) ); return(result); } /** \brief Set Control Register This function writes the given value to the Control Register. \param [in] control Control Register value to set */ __attribute__( ( always_inline ) ) __STATIC_INLINE void __set_CONTROL(uint32_t control) { __ASM volatile ("MSR control, %0" : : "r" (control) : "memory"); } /** \brief Get IPSR Register This function returns the content of the IPSR Register. \return IPSR Register value */ __attribute__( ( always_inline ) ) __STATIC_INLINE uint32_t __get_IPSR(void) { uint32_t result; __ASM volatile ("MRS %0, ipsr" : "=r" (result) ); return(result); } /** \brief Get APSR Register This function returns the content of the APSR Register. \return APSR Register value */ __attribute__( ( always_inline ) ) __STATIC_INLINE uint32_t __get_APSR(void) { uint32_t result; __ASM volatile ("MRS %0, apsr" : "=r" (result) ); return(result); } /** \brief Get xPSR Register This function returns the content of the xPSR Register. \return xPSR Register value */ __attribute__( ( always_inline ) ) __STATIC_INLINE uint32_t __get_xPSR(void) { uint32_t result; __ASM volatile ("MRS %0, xpsr" : "=r" (result) ); return(result); } /** \brief Get Process Stack Pointer This function returns the current value of the Process Stack Pointer (PSP). \return PSP Register value */ __attribute__( ( always_inline ) ) __STATIC_INLINE uint32_t __get_PSP(void) { register uint32_t result; __ASM volatile ("MRS %0, psp\n" : "=r" (result) ); return(result); } /** \brief Set Process Stack Pointer This function assigns the given value to the Process Stack Pointer (PSP). \param [in] topOfProcStack Process Stack Pointer value to set */ __attribute__( ( always_inline ) ) __STATIC_INLINE void __set_PSP(uint32_t topOfProcStack) { __ASM volatile ("MSR psp, %0\n" : : "r" (topOfProcStack) : "sp"); } /** \brief Get Main Stack Pointer This function returns the current value of the Main Stack Pointer (MSP). \return MSP Register value */ __attribute__( ( always_inline ) ) __STATIC_INLINE uint32_t __get_MSP(void) { register uint32_t result; __ASM volatile ("MRS %0, msp\n" : "=r" (result) ); return(result); } /** \brief Set Main Stack Pointer This function assigns the given value to the Main Stack Pointer (MSP). \param [in] topOfMainStack Main Stack Pointer value to set */ __attribute__( ( always_inline ) ) __STATIC_INLINE void __set_MSP(uint32_t topOfMainStack) { __ASM volatile ("MSR msp, %0\n" : : "r" (topOfMainStack) : "sp"); } /** \brief Get Priority Mask This function returns the current state of the priority mask bit from the Priority Mask Register. \return Priority Mask value */ __attribute__( ( always_inline ) ) __STATIC_INLINE uint32_t __get_PRIMASK(void) { uint32_t result; __ASM volatile ("MRS %0, primask" : "=r" (result) ); return(result); } /** \brief Set Priority Mask This function assigns the given value to the Priority Mask Register. \param [in] priMask Priority Mask */ __attribute__( ( always_inline ) ) __STATIC_INLINE void __set_PRIMASK(uint32_t priMask) { __ASM volatile ("MSR primask, %0" : : "r" (priMask) : "memory"); } #if (__CORTEX_M >= 0x03) /** \brief Enable FIQ This function enables FIQ interrupts by clearing the F-bit in the CPSR. Can only be executed in Privileged modes. */ __attribute__( ( always_inline ) ) __STATIC_INLINE void __enable_fault_irq(void) { __ASM volatile ("cpsie f" : : : "memory"); } /** \brief Disable FIQ This function disables FIQ interrupts by setting the F-bit in the CPSR. Can only be executed in Privileged modes. */ __attribute__( ( always_inline ) ) __STATIC_INLINE void __disable_fault_irq(void) { __ASM volatile ("cpsid f" : : : "memory"); } /** \brief Get Base Priority This function returns the current value of the Base Priority register. \return Base Priority register value */ __attribute__( ( always_inline ) ) __STATIC_INLINE uint32_t __get_BASEPRI(void) { uint32_t result; __ASM volatile ("MRS %0, basepri_max" : "=r" (result) ); return(result); } /** \brief Set Base Priority This function assigns the given value to the Base Priority register. \param [in] basePri Base Priority value to set */ __attribute__( ( always_inline ) ) __STATIC_INLINE void __set_BASEPRI(uint32_t value) { __ASM volatile ("MSR basepri, %0" : : "r" (value) : "memory"); } /** \brief Get Fault Mask This function returns the current value of the Fault Mask register. \return Fault Mask register value */ __attribute__( ( always_inline ) ) __STATIC_INLINE uint32_t __get_FAULTMASK(void) { uint32_t result; __ASM volatile ("MRS %0, faultmask" : "=r" (result) ); return(result); } /** \brief Set Fault Mask This function assigns the given value to the Fault Mask register. \param [in] faultMask Fault Mask value to set */ __attribute__( ( always_inline ) ) __STATIC_INLINE void __set_FAULTMASK(uint32_t faultMask) { __ASM volatile ("MSR faultmask, %0" : : "r" (faultMask) : "memory"); } #endif /* (__CORTEX_M >= 0x03) */ #if (__CORTEX_M == 0x04) /** \brief Get FPSCR This function returns the current value of the Floating Point Status/Control register. \return Floating Point Status/Control register value */ __attribute__( ( always_inline ) ) __STATIC_INLINE uint32_t __get_FPSCR(void) { #if (__FPU_PRESENT == 1) && (__FPU_USED == 1) uint32_t result; /* Empty asm statement works as a scheduling barrier */ __ASM volatile (""); __ASM volatile ("VMRS %0, fpscr" : "=r" (result) ); __ASM volatile (""); return(result); #else return(0); #endif } /** \brief Set FPSCR This function assigns the given value to the Floating Point Status/Control register. \param [in] fpscr Floating Point Status/Control value to set */ __attribute__( ( always_inline ) ) __STATIC_INLINE void __set_FPSCR(uint32_t fpscr) { #if (__FPU_PRESENT == 1) && (__FPU_USED == 1) /* Empty asm statement works as a scheduling barrier */ __ASM volatile (""); __ASM volatile ("VMSR fpscr, %0" : : "r" (fpscr) : "vfpcc"); __ASM volatile (""); #endif } #endif /* (__CORTEX_M == 0x04) */ #elif defined ( __TASKING__ ) /*------------------ TASKING Compiler --------------*/ /* TASKING carm specific functions */ /* * The CMSIS functions have been implemented as intrinsics in the compiler. * Please use "carm -?i" to get an up to date list of all instrinsics, * Including the CMSIS ones. */ #endif /*@} end of CMSIS_Core_RegAccFunctions */ #endif /* __CORE_CMFUNC_H */ ================================================ FILE: Zelig/mbed/TARGET_LPC1768/core_cmInstr.h ================================================ /**************************************************************************//** * @file core_cmInstr.h * @brief CMSIS Cortex-M Core Instruction Access Header File * @version V3.20 * @date 05. March 2013 * * @note * ******************************************************************************/ /* Copyright (c) 2009 - 2013 ARM LIMITED All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: - Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. - Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. - Neither the name of ARM 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 COPYRIGHT HOLDERS AND 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. ---------------------------------------------------------------------------*/ #ifndef __CORE_CMINSTR_H #define __CORE_CMINSTR_H /* ########################## Core Instruction Access ######################### */ /** \defgroup CMSIS_Core_InstructionInterface CMSIS Core Instruction Interface Access to dedicated instructions @{ */ #if defined ( __CC_ARM ) /*------------------RealView Compiler -----------------*/ /* ARM armcc specific functions */ #if (__ARMCC_VERSION < 400677) #error "Please use ARM Compiler Toolchain V4.0.677 or later!" #endif /** \brief No Operation No Operation does nothing. This instruction can be used for code alignment purposes. */ #define __NOP __nop /** \brief Wait For Interrupt Wait For Interrupt is a hint instruction that suspends execution until one of a number of events occurs. */ #define __WFI __wfi /** \brief Wait For Event Wait For Event is a hint instruction that permits the processor to enter a low-power state until one of a number of events occurs. */ #define __WFE __wfe /** \brief Send Event Send Event is a hint instruction. It causes an event to be signaled to the CPU. */ #define __SEV __sev /** \brief Instruction Synchronization Barrier Instruction Synchronization Barrier flushes the pipeline in the processor, so that all instructions following the ISB are fetched from cache or memory, after the instruction has been completed. */ #define __ISB() __isb(0xF) /** \brief Data Synchronization Barrier This function acts as a special kind of Data Memory Barrier. It completes when all explicit memory accesses before this instruction complete. */ #define __DSB() __dsb(0xF) /** \brief Data Memory Barrier This function ensures the apparent order of the explicit memory operations before and after the instruction, without ensuring their completion. */ #define __DMB() __dmb(0xF) /** \brief Reverse byte order (32 bit) This function reverses the byte order in integer value. \param [in] value Value to reverse \return Reversed value */ #define __REV __rev /** \brief Reverse byte order (16 bit) This function reverses the byte order in two unsigned short values. \param [in] value Value to reverse \return Reversed value */ #ifndef __NO_EMBEDDED_ASM __attribute__((section(".rev16_text"))) __STATIC_INLINE __ASM uint32_t __REV16(uint32_t value) { rev16 r0, r0 bx lr } #endif /** \brief Reverse byte order in signed short value This function reverses the byte order in a signed short value with sign extension to integer. \param [in] value Value to reverse \return Reversed value */ #ifndef __NO_EMBEDDED_ASM __attribute__((section(".revsh_text"))) __STATIC_INLINE __ASM int32_t __REVSH(int32_t value) { revsh r0, r0 bx lr } #endif /** \brief Rotate Right in unsigned value (32 bit) This function Rotate Right (immediate) provides the value of the contents of a register rotated by a variable number of bits. \param [in] value Value to rotate \param [in] value Number of Bits to rotate \return Rotated value */ #define __ROR __ror /** \brief Breakpoint This function causes the processor to enter Debug state. Debug tools can use this to investigate system state when the instruction at a particular address is reached. \param [in] value is ignored by the processor. If required, a debugger can use it to store additional information about the breakpoint. */ #define __BKPT(value) __breakpoint(value) #if (__CORTEX_M >= 0x03) /** \brief Reverse bit order of value This function reverses the bit order of the given value. \param [in] value Value to reverse \return Reversed value */ #define __RBIT __rbit /** \brief LDR Exclusive (8 bit) This function performs a exclusive LDR command for 8 bit value. \param [in] ptr Pointer to data \return value of type uint8_t at (*ptr) */ #define __LDREXB(ptr) ((uint8_t ) __ldrex(ptr)) /** \brief LDR Exclusive (16 bit) This function performs a exclusive LDR command for 16 bit values. \param [in] ptr Pointer to data \return value of type uint16_t at (*ptr) */ #define __LDREXH(ptr) ((uint16_t) __ldrex(ptr)) /** \brief LDR Exclusive (32 bit) This function performs a exclusive LDR command for 32 bit values. \param [in] ptr Pointer to data \return value of type uint32_t at (*ptr) */ #define __LDREXW(ptr) ((uint32_t ) __ldrex(ptr)) /** \brief STR Exclusive (8 bit) This function performs a exclusive STR command for 8 bit values. \param [in] value Value to store \param [in] ptr Pointer to location \return 0 Function succeeded \return 1 Function failed */ #define __STREXB(value, ptr) __strex(value, ptr) /** \brief STR Exclusive (16 bit) This function performs a exclusive STR command for 16 bit values. \param [in] value Value to store \param [in] ptr Pointer to location \return 0 Function succeeded \return 1 Function failed */ #define __STREXH(value, ptr) __strex(value, ptr) /** \brief STR Exclusive (32 bit) This function performs a exclusive STR command for 32 bit values. \param [in] value Value to store \param [in] ptr Pointer to location \return 0 Function succeeded \return 1 Function failed */ #define __STREXW(value, ptr) __strex(value, ptr) /** \brief Remove the exclusive lock This function removes the exclusive lock which is created by LDREX. */ #define __CLREX __clrex /** \brief Signed Saturate This function saturates a signed value. \param [in] value Value to be saturated \param [in] sat Bit position to saturate to (1..32) \return Saturated value */ #define __SSAT __ssat /** \brief Unsigned Saturate This function saturates an unsigned value. \param [in] value Value to be saturated \param [in] sat Bit position to saturate to (0..31) \return Saturated value */ #define __USAT __usat /** \brief Count leading zeros This function counts the number of leading zeros of a data value. \param [in] value Value to count the leading zeros \return number of leading zeros in value */ #define __CLZ __clz #endif /* (__CORTEX_M >= 0x03) */ #elif defined ( __ICCARM__ ) /*------------------ ICC Compiler -------------------*/ /* IAR iccarm specific functions */ #include #elif defined ( __TMS470__ ) /*---------------- TI CCS Compiler ------------------*/ /* TI CCS specific functions */ #include #elif defined ( __GNUC__ ) /*------------------ GNU Compiler ---------------------*/ /* GNU gcc specific functions */ /* Define macros for porting to both thumb1 and thumb2. * For thumb1, use low register (r0-r7), specified by constrant "l" * Otherwise, use general registers, specified by constrant "r" */ #if defined (__thumb__) && !defined (__thumb2__) #define __CMSIS_GCC_OUT_REG(r) "=l" (r) #define __CMSIS_GCC_USE_REG(r) "l" (r) #else #define __CMSIS_GCC_OUT_REG(r) "=r" (r) #define __CMSIS_GCC_USE_REG(r) "r" (r) #endif /** \brief No Operation No Operation does nothing. This instruction can be used for code alignment purposes. */ __attribute__( ( always_inline ) ) __STATIC_INLINE void __NOP(void) { __ASM volatile ("nop"); } /** \brief Wait For Interrupt Wait For Interrupt is a hint instruction that suspends execution until one of a number of events occurs. */ __attribute__( ( always_inline ) ) __STATIC_INLINE void __WFI(void) { __ASM volatile ("wfi"); } /** \brief Wait For Event Wait For Event is a hint instruction that permits the processor to enter a low-power state until one of a number of events occurs. */ __attribute__( ( always_inline ) ) __STATIC_INLINE void __WFE(void) { __ASM volatile ("wfe"); } /** \brief Send Event Send Event is a hint instruction. It causes an event to be signaled to the CPU. */ __attribute__( ( always_inline ) ) __STATIC_INLINE void __SEV(void) { __ASM volatile ("sev"); } /** \brief Instruction Synchronization Barrier Instruction Synchronization Barrier flushes the pipeline in the processor, so that all instructions following the ISB are fetched from cache or memory, after the instruction has been completed. */ __attribute__( ( always_inline ) ) __STATIC_INLINE void __ISB(void) { __ASM volatile ("isb"); } /** \brief Data Synchronization Barrier This function acts as a special kind of Data Memory Barrier. It completes when all explicit memory accesses before this instruction complete. */ __attribute__( ( always_inline ) ) __STATIC_INLINE void __DSB(void) { __ASM volatile ("dsb"); } /** \brief Data Memory Barrier This function ensures the apparent order of the explicit memory operations before and after the instruction, without ensuring their completion. */ __attribute__( ( always_inline ) ) __STATIC_INLINE void __DMB(void) { __ASM volatile ("dmb"); } /** \brief Reverse byte order (32 bit) This function reverses the byte order in integer value. \param [in] value Value to reverse \return Reversed value */ __attribute__( ( always_inline ) ) __STATIC_INLINE uint32_t __REV(uint32_t value) { #if (__GNUC__ > 4) || (__GNUC__ == 4 && __GNUC_MINOR__ >= 5) return __builtin_bswap32(value); #else uint32_t result; __ASM volatile ("rev %0, %1" : __CMSIS_GCC_OUT_REG (result) : __CMSIS_GCC_USE_REG (value) ); return(result); #endif } /** \brief Reverse byte order (16 bit) This function reverses the byte order in two unsigned short values. \param [in] value Value to reverse \return Reversed value */ __attribute__( ( always_inline ) ) __STATIC_INLINE uint32_t __REV16(uint32_t value) { uint32_t result; __ASM volatile ("rev16 %0, %1" : __CMSIS_GCC_OUT_REG (result) : __CMSIS_GCC_USE_REG (value) ); return(result); } /** \brief Reverse byte order in signed short value This function reverses the byte order in a signed short value with sign extension to integer. \param [in] value Value to reverse \return Reversed value */ __attribute__( ( always_inline ) ) __STATIC_INLINE int32_t __REVSH(int32_t value) { #if (__GNUC__ > 4) || (__GNUC__ == 4 && __GNUC_MINOR__ >= 8) return (short)__builtin_bswap16(value); #else uint32_t result; __ASM volatile ("revsh %0, %1" : __CMSIS_GCC_OUT_REG (result) : __CMSIS_GCC_USE_REG (value) ); return(result); #endif } /** \brief Rotate Right in unsigned value (32 bit) This function Rotate Right (immediate) provides the value of the contents of a register rotated by a variable number of bits. \param [in] value Value to rotate \param [in] value Number of Bits to rotate \return Rotated value */ __attribute__( ( always_inline ) ) __STATIC_INLINE uint32_t __ROR(uint32_t op1, uint32_t op2) { return (op1 >> op2) | (op1 << (32 - op2)); } /** \brief Breakpoint This function causes the processor to enter Debug state. Debug tools can use this to investigate system state when the instruction at a particular address is reached. \param [in] value is ignored by the processor. If required, a debugger can use it to store additional information about the breakpoint. */ #define __BKPT(value) __ASM volatile ("bkpt "#value) #if (__CORTEX_M >= 0x03) /** \brief Reverse bit order of value This function reverses the bit order of the given value. \param [in] value Value to reverse \return Reversed value */ __attribute__( ( always_inline ) ) __STATIC_INLINE uint32_t __RBIT(uint32_t value) { uint32_t result; __ASM volatile ("rbit %0, %1" : "=r" (result) : "r" (value) ); return(result); } /** \brief LDR Exclusive (8 bit) This function performs a exclusive LDR command for 8 bit value. \param [in] ptr Pointer to data \return value of type uint8_t at (*ptr) */ __attribute__( ( always_inline ) ) __STATIC_INLINE uint8_t __LDREXB(volatile uint8_t *addr) { uint32_t result; #if (__GNUC__ > 4) || (__GNUC__ == 4 && __GNUC_MINOR__ >= 8) __ASM volatile ("ldrexb %0, %1" : "=r" (result) : "Q" (*addr) ); #else /* Prior to GCC 4.8, "Q" will be expanded to [rx, #0] which is not accepted by assembler. So has to use following less efficient pattern. */ __ASM volatile ("ldrexb %0, [%1]" : "=r" (result) : "r" (addr) : "memory" ); #endif return(result); } /** \brief LDR Exclusive (16 bit) This function performs a exclusive LDR command for 16 bit values. \param [in] ptr Pointer to data \return value of type uint16_t at (*ptr) */ __attribute__( ( always_inline ) ) __STATIC_INLINE uint16_t __LDREXH(volatile uint16_t *addr) { uint32_t result; #if (__GNUC__ > 4) || (__GNUC__ == 4 && __GNUC_MINOR__ >= 8) __ASM volatile ("ldrexh %0, %1" : "=r" (result) : "Q" (*addr) ); #else /* Prior to GCC 4.8, "Q" will be expanded to [rx, #0] which is not accepted by assembler. So has to use following less efficient pattern. */ __ASM volatile ("ldrexh %0, [%1]" : "=r" (result) : "r" (addr) : "memory" ); #endif return(result); } /** \brief LDR Exclusive (32 bit) This function performs a exclusive LDR command for 32 bit values. \param [in] ptr Pointer to data \return value of type uint32_t at (*ptr) */ __attribute__( ( always_inline ) ) __STATIC_INLINE uint32_t __LDREXW(volatile uint32_t *addr) { uint32_t result; __ASM volatile ("ldrex %0, %1" : "=r" (result) : "Q" (*addr) ); return(result); } /** \brief STR Exclusive (8 bit) This function performs a exclusive STR command for 8 bit values. \param [in] value Value to store \param [in] ptr Pointer to location \return 0 Function succeeded \return 1 Function failed */ __attribute__( ( always_inline ) ) __STATIC_INLINE uint32_t __STREXB(uint8_t value, volatile uint8_t *addr) { uint32_t result; __ASM volatile ("strexb %0, %2, %1" : "=&r" (result), "=Q" (*addr) : "r" (value) ); return(result); } /** \brief STR Exclusive (16 bit) This function performs a exclusive STR command for 16 bit values. \param [in] value Value to store \param [in] ptr Pointer to location \return 0 Function succeeded \return 1 Function failed */ __attribute__( ( always_inline ) ) __STATIC_INLINE uint32_t __STREXH(uint16_t value, volatile uint16_t *addr) { uint32_t result; __ASM volatile ("strexh %0, %2, %1" : "=&r" (result), "=Q" (*addr) : "r" (value) ); return(result); } /** \brief STR Exclusive (32 bit) This function performs a exclusive STR command for 32 bit values. \param [in] value Value to store \param [in] ptr Pointer to location \return 0 Function succeeded \return 1 Function failed */ __attribute__( ( always_inline ) ) __STATIC_INLINE uint32_t __STREXW(uint32_t value, volatile uint32_t *addr) { uint32_t result; __ASM volatile ("strex %0, %2, %1" : "=&r" (result), "=Q" (*addr) : "r" (value) ); return(result); } /** \brief Remove the exclusive lock This function removes the exclusive lock which is created by LDREX. */ __attribute__( ( always_inline ) ) __STATIC_INLINE void __CLREX(void) { __ASM volatile ("clrex" ::: "memory"); } /** \brief Signed Saturate This function saturates a signed value. \param [in] value Value to be saturated \param [in] sat Bit position to saturate to (1..32) \return Saturated value */ #define __SSAT(ARG1,ARG2) \ ({ \ uint32_t __RES, __ARG1 = (ARG1); \ __ASM ("ssat %0, %1, %2" : "=r" (__RES) : "I" (ARG2), "r" (__ARG1) ); \ __RES; \ }) /** \brief Unsigned Saturate This function saturates an unsigned value. \param [in] value Value to be saturated \param [in] sat Bit position to saturate to (0..31) \return Saturated value */ #define __USAT(ARG1,ARG2) \ ({ \ uint32_t __RES, __ARG1 = (ARG1); \ __ASM ("usat %0, %1, %2" : "=r" (__RES) : "I" (ARG2), "r" (__ARG1) ); \ __RES; \ }) /** \brief Count leading zeros This function counts the number of leading zeros of a data value. \param [in] value Value to count the leading zeros \return number of leading zeros in value */ __attribute__( ( always_inline ) ) __STATIC_INLINE uint8_t __CLZ(uint32_t value) { uint32_t result; __ASM volatile ("clz %0, %1" : "=r" (result) : "r" (value) ); return(result); } #endif /* (__CORTEX_M >= 0x03) */ #elif defined ( __TASKING__ ) /*------------------ TASKING Compiler --------------*/ /* TASKING carm specific functions */ /* * The CMSIS functions have been implemented as intrinsics in the compiler. * Please use "carm -?i" to get an up to date list of all intrinsics, * Including the CMSIS ones. */ #endif /*@}*/ /* end of group CMSIS_Core_InstructionInterface */ #endif /* __CORE_CMINSTR_H */ ================================================ FILE: Zelig/mbed/TARGET_LPC1768/core_cmSimd.h ================================================ /**************************************************************************//** * @file core_cmSimd.h * @brief CMSIS Cortex-M SIMD Header File * @version V4.10 * @date 18. March 2015 * * @note * ******************************************************************************/ /* Copyright (c) 2009 - 2014 ARM LIMITED All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: - Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. - Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. - Neither the name of ARM 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 COPYRIGHT HOLDERS AND 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. ---------------------------------------------------------------------------*/ #if defined ( __ICCARM__ ) #pragma system_include /* treat file as system include file for MISRA check */ #endif #ifndef __CORE_CMSIMD_H #define __CORE_CMSIMD_H #ifdef __cplusplus extern "C" { #endif /******************************************************************************* * Hardware Abstraction Layer ******************************************************************************/ /* ################### Compiler specific Intrinsics ########################### */ /** \defgroup CMSIS_SIMD_intrinsics CMSIS SIMD Intrinsics Access to dedicated SIMD instructions @{ */ #if defined ( __CC_ARM ) /*------------------RealView Compiler -----------------*/ /* ARM armcc specific functions */ #define __SADD8 __sadd8 #define __QADD8 __qadd8 #define __SHADD8 __shadd8 #define __UADD8 __uadd8 #define __UQADD8 __uqadd8 #define __UHADD8 __uhadd8 #define __SSUB8 __ssub8 #define __QSUB8 __qsub8 #define __SHSUB8 __shsub8 #define __USUB8 __usub8 #define __UQSUB8 __uqsub8 #define __UHSUB8 __uhsub8 #define __SADD16 __sadd16 #define __QADD16 __qadd16 #define __SHADD16 __shadd16 #define __UADD16 __uadd16 #define __UQADD16 __uqadd16 #define __UHADD16 __uhadd16 #define __SSUB16 __ssub16 #define __QSUB16 __qsub16 #define __SHSUB16 __shsub16 #define __USUB16 __usub16 #define __UQSUB16 __uqsub16 #define __UHSUB16 __uhsub16 #define __SASX __sasx #define __QASX __qasx #define __SHASX __shasx #define __UASX __uasx #define __UQASX __uqasx #define __UHASX __uhasx #define __SSAX __ssax #define __QSAX __qsax #define __SHSAX __shsax #define __USAX __usax #define __UQSAX __uqsax #define __UHSAX __uhsax #define __USAD8 __usad8 #define __USADA8 __usada8 #define __SSAT16 __ssat16 #define __USAT16 __usat16 #define __UXTB16 __uxtb16 #define __UXTAB16 __uxtab16 #define __SXTB16 __sxtb16 #define __SXTAB16 __sxtab16 #define __SMUAD __smuad #define __SMUADX __smuadx #define __SMLAD __smlad #define __SMLADX __smladx #define __SMLALD __smlald #define __SMLALDX __smlaldx #define __SMUSD __smusd #define __SMUSDX __smusdx #define __SMLSD __smlsd #define __SMLSDX __smlsdx #define __SMLSLD __smlsld #define __SMLSLDX __smlsldx #define __SEL __sel #define __QADD __qadd #define __QSUB __qsub #define __PKHBT(ARG1,ARG2,ARG3) ( ((((uint32_t)(ARG1)) ) & 0x0000FFFFUL) | \ ((((uint32_t)(ARG2)) << (ARG3)) & 0xFFFF0000UL) ) #define __PKHTB(ARG1,ARG2,ARG3) ( ((((uint32_t)(ARG1)) ) & 0xFFFF0000UL) | \ ((((uint32_t)(ARG2)) >> (ARG3)) & 0x0000FFFFUL) ) #define __SMMLA(ARG1,ARG2,ARG3) ( (int32_t)((((int64_t)(ARG1) * (ARG2)) + \ ((int64_t)(ARG3) << 32) ) >> 32)) #elif defined ( __GNUC__ ) /*------------------ GNU Compiler ---------------------*/ /* GNU gcc specific functions */ __attribute__( ( always_inline ) ) __STATIC_INLINE uint32_t __SADD8(uint32_t op1, uint32_t op2) { uint32_t result; __ASM volatile ("sadd8 %0, %1, %2" : "=r" (result) : "r" (op1), "r" (op2) ); return(result); } __attribute__( ( always_inline ) ) __STATIC_INLINE uint32_t __QADD8(uint32_t op1, uint32_t op2) { uint32_t result; __ASM volatile ("qadd8 %0, %1, %2" : "=r" (result) : "r" (op1), "r" (op2) ); return(result); } __attribute__( ( always_inline ) ) __STATIC_INLINE uint32_t __SHADD8(uint32_t op1, uint32_t op2) { uint32_t result; __ASM volatile ("shadd8 %0, %1, %2" : "=r" (result) : "r" (op1), "r" (op2) ); return(result); } __attribute__( ( always_inline ) ) __STATIC_INLINE uint32_t __UADD8(uint32_t op1, uint32_t op2) { uint32_t result; __ASM volatile ("uadd8 %0, %1, %2" : "=r" (result) : "r" (op1), "r" (op2) ); return(result); } __attribute__( ( always_inline ) ) __STATIC_INLINE uint32_t __UQADD8(uint32_t op1, uint32_t op2) { uint32_t result; __ASM volatile ("uqadd8 %0, %1, %2" : "=r" (result) : "r" (op1), "r" (op2) ); return(result); } __attribute__( ( always_inline ) ) __STATIC_INLINE uint32_t __UHADD8(uint32_t op1, uint32_t op2) { uint32_t result; __ASM volatile ("uhadd8 %0, %1, %2" : "=r" (result) : "r" (op1), "r" (op2) ); return(result); } __attribute__( ( always_inline ) ) __STATIC_INLINE uint32_t __SSUB8(uint32_t op1, uint32_t op2) { uint32_t result; __ASM volatile ("ssub8 %0, %1, %2" : "=r" (result) : "r" (op1), "r" (op2) ); return(result); } __attribute__( ( always_inline ) ) __STATIC_INLINE uint32_t __QSUB8(uint32_t op1, uint32_t op2) { uint32_t result; __ASM volatile ("qsub8 %0, %1, %2" : "=r" (result) : "r" (op1), "r" (op2) ); return(result); } __attribute__( ( always_inline ) ) __STATIC_INLINE uint32_t __SHSUB8(uint32_t op1, uint32_t op2) { uint32_t result; __ASM volatile ("shsub8 %0, %1, %2" : "=r" (result) : "r" (op1), "r" (op2) ); return(result); } __attribute__( ( always_inline ) ) __STATIC_INLINE uint32_t __USUB8(uint32_t op1, uint32_t op2) { uint32_t result; __ASM volatile ("usub8 %0, %1, %2" : "=r" (result) : "r" (op1), "r" (op2) ); return(result); } __attribute__( ( always_inline ) ) __STATIC_INLINE uint32_t __UQSUB8(uint32_t op1, uint32_t op2) { uint32_t result; __ASM volatile ("uqsub8 %0, %1, %2" : "=r" (result) : "r" (op1), "r" (op2) ); return(result); } __attribute__( ( always_inline ) ) __STATIC_INLINE uint32_t __UHSUB8(uint32_t op1, uint32_t op2) { uint32_t result; __ASM volatile ("uhsub8 %0, %1, %2" : "=r" (result) : "r" (op1), "r" (op2) ); return(result); } __attribute__( ( always_inline ) ) __STATIC_INLINE uint32_t __SADD16(uint32_t op1, uint32_t op2) { uint32_t result; __ASM volatile ("sadd16 %0, %1, %2" : "=r" (result) : "r" (op1), "r" (op2) ); return(result); } __attribute__( ( always_inline ) ) __STATIC_INLINE uint32_t __QADD16(uint32_t op1, uint32_t op2) { uint32_t result; __ASM volatile ("qadd16 %0, %1, %2" : "=r" (result) : "r" (op1), "r" (op2) ); return(result); } __attribute__( ( always_inline ) ) __STATIC_INLINE uint32_t __SHADD16(uint32_t op1, uint32_t op2) { uint32_t result; __ASM volatile ("shadd16 %0, %1, %2" : "=r" (result) : "r" (op1), "r" (op2) ); return(result); } __attribute__( ( always_inline ) ) __STATIC_INLINE uint32_t __UADD16(uint32_t op1, uint32_t op2) { uint32_t result; __ASM volatile ("uadd16 %0, %1, %2" : "=r" (result) : "r" (op1), "r" (op2) ); return(result); } __attribute__( ( always_inline ) ) __STATIC_INLINE uint32_t __UQADD16(uint32_t op1, uint32_t op2) { uint32_t result; __ASM volatile ("uqadd16 %0, %1, %2" : "=r" (result) : "r" (op1), "r" (op2) ); return(result); } __attribute__( ( always_inline ) ) __STATIC_INLINE uint32_t __UHADD16(uint32_t op1, uint32_t op2) { uint32_t result; __ASM volatile ("uhadd16 %0, %1, %2" : "=r" (result) : "r" (op1), "r" (op2) ); return(result); } __attribute__( ( always_inline ) ) __STATIC_INLINE uint32_t __SSUB16(uint32_t op1, uint32_t op2) { uint32_t result; __ASM volatile ("ssub16 %0, %1, %2" : "=r" (result) : "r" (op1), "r" (op2) ); return(result); } __attribute__( ( always_inline ) ) __STATIC_INLINE uint32_t __QSUB16(uint32_t op1, uint32_t op2) { uint32_t result; __ASM volatile ("qsub16 %0, %1, %2" : "=r" (result) : "r" (op1), "r" (op2) ); return(result); } __attribute__( ( always_inline ) ) __STATIC_INLINE uint32_t __SHSUB16(uint32_t op1, uint32_t op2) { uint32_t result; __ASM volatile ("shsub16 %0, %1, %2" : "=r" (result) : "r" (op1), "r" (op2) ); return(result); } __attribute__( ( always_inline ) ) __STATIC_INLINE uint32_t __USUB16(uint32_t op1, uint32_t op2) { uint32_t result; __ASM volatile ("usub16 %0, %1, %2" : "=r" (result) : "r" (op1), "r" (op2) ); return(result); } __attribute__( ( always_inline ) ) __STATIC_INLINE uint32_t __UQSUB16(uint32_t op1, uint32_t op2) { uint32_t result; __ASM volatile ("uqsub16 %0, %1, %2" : "=r" (result) : "r" (op1), "r" (op2) ); return(result); } __attribute__( ( always_inline ) ) __STATIC_INLINE uint32_t __UHSUB16(uint32_t op1, uint32_t op2) { uint32_t result; __ASM volatile ("uhsub16 %0, %1, %2" : "=r" (result) : "r" (op1), "r" (op2) ); return(result); } __attribute__( ( always_inline ) ) __STATIC_INLINE uint32_t __SASX(uint32_t op1, uint32_t op2) { uint32_t result; __ASM volatile ("sasx %0, %1, %2" : "=r" (result) : "r" (op1), "r" (op2) ); return(result); } __attribute__( ( always_inline ) ) __STATIC_INLINE uint32_t __QASX(uint32_t op1, uint32_t op2) { uint32_t result; __ASM volatile ("qasx %0, %1, %2" : "=r" (result) : "r" (op1), "r" (op2) ); return(result); } __attribute__( ( always_inline ) ) __STATIC_INLINE uint32_t __SHASX(uint32_t op1, uint32_t op2) { uint32_t result; __ASM volatile ("shasx %0, %1, %2" : "=r" (result) : "r" (op1), "r" (op2) ); return(result); } __attribute__( ( always_inline ) ) __STATIC_INLINE uint32_t __UASX(uint32_t op1, uint32_t op2) { uint32_t result; __ASM volatile ("uasx %0, %1, %2" : "=r" (result) : "r" (op1), "r" (op2) ); return(result); } __attribute__( ( always_inline ) ) __STATIC_INLINE uint32_t __UQASX(uint32_t op1, uint32_t op2) { uint32_t result; __ASM volatile ("uqasx %0, %1, %2" : "=r" (result) : "r" (op1), "r" (op2) ); return(result); } __attribute__( ( always_inline ) ) __STATIC_INLINE uint32_t __UHASX(uint32_t op1, uint32_t op2) { uint32_t result; __ASM volatile ("uhasx %0, %1, %2" : "=r" (result) : "r" (op1), "r" (op2) ); return(result); } __attribute__( ( always_inline ) ) __STATIC_INLINE uint32_t __SSAX(uint32_t op1, uint32_t op2) { uint32_t result; __ASM volatile ("ssax %0, %1, %2" : "=r" (result) : "r" (op1), "r" (op2) ); return(result); } __attribute__( ( always_inline ) ) __STATIC_INLINE uint32_t __QSAX(uint32_t op1, uint32_t op2) { uint32_t result; __ASM volatile ("qsax %0, %1, %2" : "=r" (result) : "r" (op1), "r" (op2) ); return(result); } __attribute__( ( always_inline ) ) __STATIC_INLINE uint32_t __SHSAX(uint32_t op1, uint32_t op2) { uint32_t result; __ASM volatile ("shsax %0, %1, %2" : "=r" (result) : "r" (op1), "r" (op2) ); return(result); } __attribute__( ( always_inline ) ) __STATIC_INLINE uint32_t __USAX(uint32_t op1, uint32_t op2) { uint32_t result; __ASM volatile ("usax %0, %1, %2" : "=r" (result) : "r" (op1), "r" (op2) ); return(result); } __attribute__( ( always_inline ) ) __STATIC_INLINE uint32_t __UQSAX(uint32_t op1, uint32_t op2) { uint32_t result; __ASM volatile ("uqsax %0, %1, %2" : "=r" (result) : "r" (op1), "r" (op2) ); return(result); } __attribute__( ( always_inline ) ) __STATIC_INLINE uint32_t __UHSAX(uint32_t op1, uint32_t op2) { uint32_t result; __ASM volatile ("uhsax %0, %1, %2" : "=r" (result) : "r" (op1), "r" (op2) ); return(result); } __attribute__( ( always_inline ) ) __STATIC_INLINE uint32_t __USAD8(uint32_t op1, uint32_t op2) { uint32_t result; __ASM volatile ("usad8 %0, %1, %2" : "=r" (result) : "r" (op1), "r" (op2) ); return(result); } __attribute__( ( always_inline ) ) __STATIC_INLINE uint32_t __USADA8(uint32_t op1, uint32_t op2, uint32_t op3) { uint32_t result; __ASM volatile ("usada8 %0, %1, %2, %3" : "=r" (result) : "r" (op1), "r" (op2), "r" (op3) ); return(result); } #define __SSAT16(ARG1,ARG2) \ ({ \ uint32_t __RES, __ARG1 = (ARG1); \ __ASM ("ssat16 %0, %1, %2" : "=r" (__RES) : "I" (ARG2), "r" (__ARG1) ); \ __RES; \ }) #define __USAT16(ARG1,ARG2) \ ({ \ uint32_t __RES, __ARG1 = (ARG1); \ __ASM ("usat16 %0, %1, %2" : "=r" (__RES) : "I" (ARG2), "r" (__ARG1) ); \ __RES; \ }) __attribute__( ( always_inline ) ) __STATIC_INLINE uint32_t __UXTB16(uint32_t op1) { uint32_t result; __ASM volatile ("uxtb16 %0, %1" : "=r" (result) : "r" (op1)); return(result); } __attribute__( ( always_inline ) ) __STATIC_INLINE uint32_t __UXTAB16(uint32_t op1, uint32_t op2) { uint32_t result; __ASM volatile ("uxtab16 %0, %1, %2" : "=r" (result) : "r" (op1), "r" (op2) ); return(result); } __attribute__( ( always_inline ) ) __STATIC_INLINE uint32_t __SXTB16(uint32_t op1) { uint32_t result; __ASM volatile ("sxtb16 %0, %1" : "=r" (result) : "r" (op1)); return(result); } __attribute__( ( always_inline ) ) __STATIC_INLINE uint32_t __SXTAB16(uint32_t op1, uint32_t op2) { uint32_t result; __ASM volatile ("sxtab16 %0, %1, %2" : "=r" (result) : "r" (op1), "r" (op2) ); return(result); } __attribute__( ( always_inline ) ) __STATIC_INLINE uint32_t __SMUAD (uint32_t op1, uint32_t op2) { uint32_t result; __ASM volatile ("smuad %0, %1, %2" : "=r" (result) : "r" (op1), "r" (op2) ); return(result); } __attribute__( ( always_inline ) ) __STATIC_INLINE uint32_t __SMUADX (uint32_t op1, uint32_t op2) { uint32_t result; __ASM volatile ("smuadx %0, %1, %2" : "=r" (result) : "r" (op1), "r" (op2) ); return(result); } __attribute__( ( always_inline ) ) __STATIC_INLINE uint32_t __SMLAD (uint32_t op1, uint32_t op2, uint32_t op3) { uint32_t result; __ASM volatile ("smlad %0, %1, %2, %3" : "=r" (result) : "r" (op1), "r" (op2), "r" (op3) ); return(result); } __attribute__( ( always_inline ) ) __STATIC_INLINE uint32_t __SMLADX (uint32_t op1, uint32_t op2, uint32_t op3) { uint32_t result; __ASM volatile ("smladx %0, %1, %2, %3" : "=r" (result) : "r" (op1), "r" (op2), "r" (op3) ); return(result); } __attribute__( ( always_inline ) ) __STATIC_INLINE uint64_t __SMLALD (uint32_t op1, uint32_t op2, uint64_t acc) { union llreg_u{ uint32_t w32[2]; uint64_t w64; } llr; llr.w64 = acc; #ifndef __ARMEB__ // Little endian __ASM volatile ("smlald %0, %1, %2, %3" : "=r" (llr.w32[0]), "=r" (llr.w32[1]): "r" (op1), "r" (op2) , "0" (llr.w32[0]), "1" (llr.w32[1]) ); #else // Big endian __ASM volatile ("smlald %0, %1, %2, %3" : "=r" (llr.w32[1]), "=r" (llr.w32[0]): "r" (op1), "r" (op2) , "0" (llr.w32[1]), "1" (llr.w32[0]) ); #endif return(llr.w64); } __attribute__( ( always_inline ) ) __STATIC_INLINE uint64_t __SMLALDX (uint32_t op1, uint32_t op2, uint64_t acc) { union llreg_u{ uint32_t w32[2]; uint64_t w64; } llr; llr.w64 = acc; #ifndef __ARMEB__ // Little endian __ASM volatile ("smlaldx %0, %1, %2, %3" : "=r" (llr.w32[0]), "=r" (llr.w32[1]): "r" (op1), "r" (op2) , "0" (llr.w32[0]), "1" (llr.w32[1]) ); #else // Big endian __ASM volatile ("smlaldx %0, %1, %2, %3" : "=r" (llr.w32[1]), "=r" (llr.w32[0]): "r" (op1), "r" (op2) , "0" (llr.w32[1]), "1" (llr.w32[0]) ); #endif return(llr.w64); } __attribute__( ( always_inline ) ) __STATIC_INLINE uint32_t __SMUSD (uint32_t op1, uint32_t op2) { uint32_t result; __ASM volatile ("smusd %0, %1, %2" : "=r" (result) : "r" (op1), "r" (op2) ); return(result); } __attribute__( ( always_inline ) ) __STATIC_INLINE uint32_t __SMUSDX (uint32_t op1, uint32_t op2) { uint32_t result; __ASM volatile ("smusdx %0, %1, %2" : "=r" (result) : "r" (op1), "r" (op2) ); return(result); } __attribute__( ( always_inline ) ) __STATIC_INLINE uint32_t __SMLSD (uint32_t op1, uint32_t op2, uint32_t op3) { uint32_t result; __ASM volatile ("smlsd %0, %1, %2, %3" : "=r" (result) : "r" (op1), "r" (op2), "r" (op3) ); return(result); } __attribute__( ( always_inline ) ) __STATIC_INLINE uint32_t __SMLSDX (uint32_t op1, uint32_t op2, uint32_t op3) { uint32_t result; __ASM volatile ("smlsdx %0, %1, %2, %3" : "=r" (result) : "r" (op1), "r" (op2), "r" (op3) ); return(result); } __attribute__( ( always_inline ) ) __STATIC_INLINE uint64_t __SMLSLD (uint32_t op1, uint32_t op2, uint64_t acc) { union llreg_u{ uint32_t w32[2]; uint64_t w64; } llr; llr.w64 = acc; #ifndef __ARMEB__ // Little endian __ASM volatile ("smlsld %0, %1, %2, %3" : "=r" (llr.w32[0]), "=r" (llr.w32[1]): "r" (op1), "r" (op2) , "0" (llr.w32[0]), "1" (llr.w32[1]) ); #else // Big endian __ASM volatile ("smlsld %0, %1, %2, %3" : "=r" (llr.w32[1]), "=r" (llr.w32[0]): "r" (op1), "r" (op2) , "0" (llr.w32[1]), "1" (llr.w32[0]) ); #endif return(llr.w64); } __attribute__( ( always_inline ) ) __STATIC_INLINE uint64_t __SMLSLDX (uint32_t op1, uint32_t op2, uint64_t acc) { union llreg_u{ uint32_t w32[2]; uint64_t w64; } llr; llr.w64 = acc; #ifndef __ARMEB__ // Little endian __ASM volatile ("smlsldx %0, %1, %2, %3" : "=r" (llr.w32[0]), "=r" (llr.w32[1]): "r" (op1), "r" (op2) , "0" (llr.w32[0]), "1" (llr.w32[1]) ); #else // Big endian __ASM volatile ("smlsldx %0, %1, %2, %3" : "=r" (llr.w32[1]), "=r" (llr.w32[0]): "r" (op1), "r" (op2) , "0" (llr.w32[1]), "1" (llr.w32[0]) ); #endif return(llr.w64); } __attribute__( ( always_inline ) ) __STATIC_INLINE uint32_t __SEL (uint32_t op1, uint32_t op2) { uint32_t result; __ASM volatile ("sel %0, %1, %2" : "=r" (result) : "r" (op1), "r" (op2) ); return(result); } __attribute__( ( always_inline ) ) __STATIC_INLINE uint32_t __QADD(uint32_t op1, uint32_t op2) { uint32_t result; __ASM volatile ("qadd %0, %1, %2" : "=r" (result) : "r" (op1), "r" (op2) ); return(result); } __attribute__( ( always_inline ) ) __STATIC_INLINE uint32_t __QSUB(uint32_t op1, uint32_t op2) { uint32_t result; __ASM volatile ("qsub %0, %1, %2" : "=r" (result) : "r" (op1), "r" (op2) ); return(result); } #define __PKHBT(ARG1,ARG2,ARG3) \ ({ \ uint32_t __RES, __ARG1 = (ARG1), __ARG2 = (ARG2); \ __ASM ("pkhbt %0, %1, %2, lsl %3" : "=r" (__RES) : "r" (__ARG1), "r" (__ARG2), "I" (ARG3) ); \ __RES; \ }) #define __PKHTB(ARG1,ARG2,ARG3) \ ({ \ uint32_t __RES, __ARG1 = (ARG1), __ARG2 = (ARG2); \ if (ARG3 == 0) \ __ASM ("pkhtb %0, %1, %2" : "=r" (__RES) : "r" (__ARG1), "r" (__ARG2) ); \ else \ __ASM ("pkhtb %0, %1, %2, asr %3" : "=r" (__RES) : "r" (__ARG1), "r" (__ARG2), "I" (ARG3) ); \ __RES; \ }) __attribute__( ( always_inline ) ) __STATIC_INLINE uint32_t __SMMLA (int32_t op1, int32_t op2, int32_t op3) { int32_t result; __ASM volatile ("smmla %0, %1, %2, %3" : "=r" (result): "r" (op1), "r" (op2), "r" (op3) ); return(result); } #elif defined ( __ICCARM__ ) /*------------------ ICC Compiler -------------------*/ /* IAR iccarm specific functions */ #include #elif defined ( __TMS470__ ) /*---------------- TI CCS Compiler ------------------*/ /* TI CCS specific functions */ #include #elif defined ( __TASKING__ ) /*------------------ TASKING Compiler --------------*/ /* TASKING carm specific functions */ /* not yet supported */ #elif defined ( __CSMC__ ) /*------------------ COSMIC Compiler -------------------*/ /* Cosmic specific functions */ #include #endif /*@} end of group CMSIS_SIMD_intrinsics */ #ifdef __cplusplus } #endif #endif /* __CORE_CMSIMD_H */ ================================================ FILE: Zelig/mbed/TARGET_LPC1768/system_LPC17xx.h ================================================ /****************************************************************************** * @file: system_LPC17xx.h * @purpose: CMSIS Cortex-M3 Device Peripheral Access Layer Header File * for the NXP LPC17xx Device Series * @version: V1.02 * @date: 27. July 2009 *---------------------------------------------------------------------------- * * Copyright (C) 2009 ARM Limited. All rights reserved. * * ARM Limited (ARM) is supplying this software for use with Cortex-M3 * processor based microcontrollers. This file can be freely distributed * within development tools that are supporting such ARM based processors. * * THIS SOFTWARE IS PROVIDED "AS IS". NO WARRANTIES, WHETHER EXPRESS, IMPLIED * OR STATUTORY, INCLUDING, BUT NOT LIMITED TO, IMPLIED WARRANTIES OF * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE APPLY TO THIS SOFTWARE. * ARM SHALL NOT, IN ANY CIRCUMSTANCES, BE LIABLE FOR SPECIAL, INCIDENTAL, OR * CONSEQUENTIAL DAMAGES, FOR ANY REASON WHATSOEVER. * ******************************************************************************/ #ifndef __SYSTEM_LPC17xx_H #define __SYSTEM_LPC17xx_H #ifdef __cplusplus extern "C" { #endif extern uint32_t SystemCoreClock; /*!< System Clock Frequency (Core Clock) */ /** * Initialize the system * * @param none * @return none * * @brief Setup the microcontroller system. * Initialize the System and update the SystemCoreClock variable. */ extern void SystemInit (void); /** * Update SystemCoreClock variable * * @param none * @return none * * @brief Updates the SystemCoreClock with current core Clock * retrieved from cpu registers. */ extern void SystemCoreClockUpdate (void); #ifdef __cplusplus } #endif #endif /* __SYSTEM_LPC17xx_H */ ================================================ FILE: Zelig/mbed/TARGET_NUCLEO_F091RC/TARGET_STM/TARGET_STM32F0/PeripheralPins.h ================================================ /* mbed Microcontroller Library ******************************************************************************* * Copyright (c) 2014, STMicroelectronics * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * 1. Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * 3. Neither the name of 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. ******************************************************************************* */ #ifndef MBED_PERIPHERALPINS_H #define MBED_PERIPHERALPINS_H #include "pinmap.h" #include "PeripheralNames.h" //*** ADC *** extern const PinMap PinMap_ADC[]; //*** DAC *** extern const PinMap PinMap_DAC[]; //*** I2C *** extern const PinMap PinMap_I2C_SDA[]; extern const PinMap PinMap_I2C_SCL[]; //*** PWM *** extern const PinMap PinMap_PWM[]; //*** SERIAL *** extern const PinMap PinMap_UART_TX[]; extern const PinMap PinMap_UART_RX[]; //*** SPI *** extern const PinMap PinMap_SPI_MOSI[]; extern const PinMap PinMap_SPI_MISO[]; extern const PinMap PinMap_SPI_SCLK[]; extern const PinMap PinMap_SPI_SSEL[]; #endif ================================================ FILE: Zelig/mbed/TARGET_NUCLEO_F091RC/TARGET_STM/TARGET_STM32F0/TARGET_NUCLEO_F091RC/PeripheralNames.h ================================================ /* mbed Microcontroller Library ******************************************************************************* * Copyright (c) 2014, STMicroelectronics * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * 1. Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * 3. Neither the name of 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. ******************************************************************************* */ #ifndef MBED_PERIPHERALNAMES_H #define MBED_PERIPHERALNAMES_H #include "cmsis.h" #ifdef __cplusplus extern "C" { #endif typedef enum { ADC_1 = (int)ADC1_BASE } ADCName; typedef enum { DAC_1 = (int)DAC_BASE } DACName; typedef enum { UART_1 = (int)USART1_BASE, UART_2 = (int)USART2_BASE, UART_3 = (int)USART3_BASE, UART_4 = (int)USART4_BASE, UART_5 = (int)USART5_BASE, UART_6 = (int)USART6_BASE, UART_7 = (int)USART7_BASE, UART_8 = (int)USART8_BASE } UARTName; #define STDIO_UART_TX PA_2 #define STDIO_UART_RX PA_3 #define STDIO_UART UART_2 typedef enum { SPI_1 = (int)SPI1_BASE, SPI_2 = (int)SPI2_BASE } SPIName; typedef enum { I2C_1 = (int)I2C1_BASE, I2C_2 = (int)I2C2_BASE } I2CName; typedef enum { PWM_1 = (int)TIM1_BASE, PWM_2 = (int)TIM2_BASE, PWM_3 = (int)TIM3_BASE, PWM_14 = (int)TIM14_BASE, PWM_15 = (int)TIM15_BASE, PWM_16 = (int)TIM16_BASE, PWM_17 = (int)TIM17_BASE } PWMName; #ifdef __cplusplus } #endif #endif ================================================ FILE: Zelig/mbed/TARGET_NUCLEO_F091RC/TARGET_STM/TARGET_STM32F0/TARGET_NUCLEO_F091RC/PinNames.h ================================================ /* mbed Microcontroller Library ******************************************************************************* * Copyright (c) 2014, STMicroelectronics * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * 1. Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * 3. Neither the name of 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. ******************************************************************************* */ #ifndef MBED_PINNAMES_H #define MBED_PINNAMES_H #include "cmsis.h" #ifdef __cplusplus extern "C" { #endif // See stm32f0xx_hal_gpio.h and stm32f0xx_hal_gpio_ex.h for values of MODE, PUPD and AFNUM #define STM_PIN_DATA(MODE, PUPD, AFNUM) ((int)(((AFNUM) << 7) | ((PUPD) << 4) | ((MODE) << 0))) #define STM_PIN_MODE(X) (((X) >> 0) & 0x0F) #define STM_PIN_PUPD(X) (((X) >> 4) & 0x07) #define STM_PIN_AFNUM(X) (((X) >> 7) & 0x0F) #define STM_MODE_INPUT (0) #define STM_MODE_OUTPUT_PP (1) #define STM_MODE_OUTPUT_OD (2) #define STM_MODE_AF_PP (3) #define STM_MODE_AF_OD (4) #define STM_MODE_ANALOG (5) #define STM_MODE_IT_RISING (6) #define STM_MODE_IT_FALLING (7) #define STM_MODE_IT_RISING_FALLING (8) #define STM_MODE_EVT_RISING (9) #define STM_MODE_EVT_FALLING (10) #define STM_MODE_EVT_RISING_FALLING (11) #define STM_MODE_IT_EVT_RESET (12) // High nibble = port number (0=A, 1=B, 2=C, 3=D, 4=E, 5=F, 6=G, 7=H) // Low nibble = pin number #define STM_PORT(X) (((uint32_t)(X) >> 4) & 0xF) #define STM_PIN(X) ((uint32_t)(X) & 0xF) typedef enum { PIN_INPUT, PIN_OUTPUT } PinDirection; typedef enum { PA_0 = 0x00, PA_1 = 0x01, PA_2 = 0x02, PA_3 = 0x03, PA_4 = 0x04, PA_5 = 0x05, PA_6 = 0x06, PA_7 = 0x07, PA_8 = 0x08, PA_9 = 0x09, PA_10 = 0x0A, PA_11 = 0x0B, PA_12 = 0x0C, PA_13 = 0x0D, PA_14 = 0x0E, PA_15 = 0x0F, PB_0 = 0x10, PB_1 = 0x11, PB_2 = 0x12, PB_3 = 0x13, PB_4 = 0x14, PB_5 = 0x15, PB_6 = 0x16, PB_7 = 0x17, PB_8 = 0x18, PB_9 = 0x19, PB_10 = 0x1A, PB_11 = 0x1B, PB_12 = 0x1C, PB_13 = 0x1D, PB_14 = 0x1E, PB_15 = 0x1F, PC_0 = 0x20, PC_1 = 0x21, PC_2 = 0x22, PC_3 = 0x23, PC_4 = 0x24, PC_5 = 0x25, PC_6 = 0x26, PC_7 = 0x27, PC_8 = 0x28, PC_9 = 0x29, PC_10 = 0x2A, PC_11 = 0x2B, PC_12 = 0x2C, PC_13 = 0x2D, PC_14 = 0x2E, PC_15 = 0x2F, PD_2 = 0x32, PF_0 = 0x50, PF_1 = 0x51, PF_11 = 0x5B, // Arduino connector namings A0 = PA_0, A1 = PA_1, A2 = PA_4, A3 = PB_0, A4 = PC_1, A5 = PC_0, D0 = PA_3, D1 = PA_2, D2 = PA_10, D3 = PB_3, D4 = PB_5, D5 = PB_4, D6 = PB_10, D7 = PA_8, D8 = PA_9, D9 = PC_7, D10 = PB_6, D11 = PA_7, D12 = PA_6, D13 = PA_5, D14 = PB_9, D15 = PB_8, // Generic signals namings LED1 = PA_5, LED2 = PA_5, LED3 = PA_5, LED4 = PA_5, USER_BUTTON = PC_13, SERIAL_TX = PA_2, SERIAL_RX = PA_3, USBTX = PA_2, USBRX = PA_3, I2C_SCL = PB_8, I2C_SDA = PB_9, SPI_MOSI = PA_7, SPI_MISO = PA_6, SPI_SCK = PA_5, SPI_CS = PB_6, PWM_OUT = PB_4, // Not connected NC = (int)0xFFFFFFFF } PinName; typedef enum { PullNone = 0, PullUp = 1, PullDown = 2, OpenDrain = 3, PullDefault = PullNone } PinMode; #ifdef __cplusplus } #endif #endif ================================================ FILE: Zelig/mbed/TARGET_NUCLEO_F091RC/TARGET_STM/TARGET_STM32F0/TARGET_NUCLEO_F091RC/PortNames.h ================================================ /* mbed Microcontroller Library ******************************************************************************* * Copyright (c) 2014, STMicroelectronics * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * 1. Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * 3. Neither the name of 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. ******************************************************************************* */ #ifndef MBED_PORTNAMES_H #define MBED_PORTNAMES_H #ifdef __cplusplus extern "C" { #endif typedef enum { PortA = 0, PortB = 1, PortC = 2, PortD = 3, PortF = 5 } PortName; #ifdef __cplusplus } #endif #endif ================================================ FILE: Zelig/mbed/TARGET_NUCLEO_F091RC/TARGET_STM/TARGET_STM32F0/TARGET_NUCLEO_F091RC/device.h ================================================ /* mbed Microcontroller Library ******************************************************************************* * Copyright (c) 2014, STMicroelectronics * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * 1. Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * 3. Neither the name of 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. ******************************************************************************* */ #ifndef MBED_DEVICE_H #define MBED_DEVICE_H #define DEVICE_PORTIN 1 #define DEVICE_PORTOUT 1 #define DEVICE_PORTINOUT 1 #define DEVICE_INTERRUPTIN 1 #define DEVICE_ANALOGIN 1 #define DEVICE_ANALOGOUT 1 #define DEVICE_SERIAL 1 #define DEVICE_I2C 1 #define DEVICE_I2CSLAVE 1 #define DEVICE_SPI 1 #define DEVICE_SPISLAVE 1 #define DEVICE_RTC 1 #define DEVICE_PWMOUT 1 #define DEVICE_SLEEP 1 //======================================= #define DEVICE_SEMIHOST 0 #define DEVICE_LOCALFILESYSTEM 0 #define DEVICE_ID_LENGTH 24 #define DEVICE_DEBUG_AWARENESS 0 #define DEVICE_STDIO_MESSAGES 1 #define DEVICE_ERROR_RED 0 #include "objects.h" #endif ================================================ FILE: Zelig/mbed/TARGET_NUCLEO_F091RC/TARGET_STM/TARGET_STM32F0/TARGET_NUCLEO_F091RC/objects.h ================================================ /* mbed Microcontroller Library ******************************************************************************* * Copyright (c) 2014, STMicroelectronics * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * 1. Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * 3. Neither the name of 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. ******************************************************************************* */ #ifndef MBED_OBJECTS_H #define MBED_OBJECTS_H #include "cmsis.h" #include "PortNames.h" #include "PeripheralNames.h" #include "PinNames.h" #ifdef __cplusplus extern "C" { #endif struct gpio_irq_s { IRQn_Type irq_n; uint32_t irq_index; uint32_t event; PinName pin; }; struct port_s { PortName port; uint32_t mask; PinDirection direction; __IO uint32_t *reg_in; __IO uint32_t *reg_out; }; struct analogin_s { ADCName adc; PinName pin; }; struct dac_s { DACName dac; PinName pin; }; struct serial_s { UARTName uart; int index; // Used by irq uint32_t baudrate; uint32_t databits; uint32_t stopbits; uint32_t parity; PinName pin_tx; PinName pin_rx; }; struct spi_s { SPIName spi; uint32_t bits; uint32_t cpol; uint32_t cpha; uint32_t mode; uint32_t nss; uint32_t br_presc; PinName pin_miso; PinName pin_mosi; PinName pin_sclk; PinName pin_ssel; }; struct i2c_s { I2CName i2c; }; struct pwmout_s { PWMName pwm; PinName pin; uint32_t period; uint32_t pulse; }; #include "gpio_object.h" #ifdef __cplusplus } #endif #endif ================================================ FILE: Zelig/mbed/TARGET_NUCLEO_F091RC/TARGET_STM/TARGET_STM32F0/gpio_object.h ================================================ /* mbed Microcontroller Library ******************************************************************************* * Copyright (c) 2014, STMicroelectronics * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * 1. Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * 3. Neither the name of 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. ******************************************************************************* */ #ifndef MBED_GPIO_OBJECT_H #define MBED_GPIO_OBJECT_H #include "mbed_assert.h" #include "cmsis.h" #include "PortNames.h" #include "PeripheralNames.h" #include "PinNames.h" #ifdef __cplusplus extern "C" { #endif typedef struct { PinName pin; uint32_t mask; __IO uint32_t *reg_in; __IO uint32_t *reg_set; __IO uint32_t *reg_clr; } gpio_t; static inline void gpio_write(gpio_t *obj, int value) { MBED_ASSERT(obj->pin != (PinName)NC); if (value) { *obj->reg_set = obj->mask; } else { *obj->reg_clr = obj->mask; } } static inline int gpio_read(gpio_t *obj) { MBED_ASSERT(obj->pin != (PinName)NC); return ((*obj->reg_in & obj->mask) ? 1 : 0); } static inline int gpio_is_connected(const gpio_t *obj) { return obj->pin != (PinName)NC; } #ifdef __cplusplus } #endif #endif ================================================ FILE: Zelig/mbed/TARGET_NUCLEO_F091RC/TOOLCHAIN_GCC_ARM/STM32F091XC.ld ================================================ /* Linker script to configure memory regions. */ MEMORY { FLASH (rx) : ORIGIN = 0x08000000, LENGTH = 256k RAM (xrw) : ORIGIN = 0x200000C0, LENGTH = 32k - 0x0C0 } /* Linker script to place sections and symbol values. Should be used together * with other linker script that defines memory regions FLASH and RAM. * It references following symbols, which must be defined in code: * Reset_Handler : Entry of reset handler * * It defines following symbols, which code can use without definition: * __exidx_start * __exidx_end * __etext * __data_start__ * __preinit_array_start * __preinit_array_end * __init_array_start * __init_array_end * __fini_array_start * __fini_array_end * __data_end__ * __bss_start__ * __bss_end__ * __end__ * end * __HeapLimit * __StackLimit * __StackTop * __stack * _estack */ ENTRY(Reset_Handler) SECTIONS { .text : { KEEP(*(.isr_vector)) *(.text*) KEEP(*(.init)) KEEP(*(.fini)) /* .ctors */ *crtbegin.o(.ctors) *crtbegin?.o(.ctors) *(EXCLUDE_FILE(*crtend?.o *crtend.o) .ctors) *(SORT(.ctors.*)) *(.ctors) /* .dtors */ *crtbegin.o(.dtors) *crtbegin?.o(.dtors) *(EXCLUDE_FILE(*crtend?.o *crtend.o) .dtors) *(SORT(.dtors.*)) *(.dtors) *(.rodata*) KEEP(*(.eh_frame*)) } > FLASH .ARM.extab : { *(.ARM.extab* .gnu.linkonce.armextab.*) } > FLASH __exidx_start = .; .ARM.exidx : { *(.ARM.exidx* .gnu.linkonce.armexidx.*) } > FLASH __exidx_end = .; __etext = .; _sidata = .; .data : AT (__etext) { __data_start__ = .; _sdata = .; *(vtable) *(.data*) . = ALIGN(4); /* preinit data */ PROVIDE_HIDDEN (__preinit_array_start = .); KEEP(*(.preinit_array)) PROVIDE_HIDDEN (__preinit_array_end = .); . = ALIGN(4); /* init data */ PROVIDE_HIDDEN (__init_array_start = .); KEEP(*(SORT(.init_array.*))) KEEP(*(.init_array)) PROVIDE_HIDDEN (__init_array_end = .); . = ALIGN(4); /* finit data */ PROVIDE_HIDDEN (__fini_array_start = .); KEEP(*(SORT(.fini_array.*))) KEEP(*(.fini_array)) PROVIDE_HIDDEN (__fini_array_end = .); KEEP(*(.jcr*)) . = ALIGN(4); /* All data end */ __data_end__ = .; _edata = .; } > RAM .bss : { . = ALIGN(4); __bss_start__ = .; _sbss = .; *(.bss*) *(COMMON) . = ALIGN(4); __bss_end__ = .; _ebss = .; } > RAM .heap (COPY): { __end__ = .; end = __end__; *(.heap*) __HeapLimit = .; } > RAM /* .stack_dummy section doesn't contains any symbols. It is only * used for linker to calculate size of stack sections, and assign * values to stack symbols later */ .stack_dummy (COPY): { *(.stack*) } > RAM /* * The section '.managed_exception_thread' is a LLILUM Specific addition to pad * the stack space at the bottom with enough space to build a managed array. * Assuming that the stack bottom (_StackLimit) is 8 bytes aligned, we add * 16 bytes that will contain the array ObjectHeader and the length member (see * ArrayImpl.cs). This way we do preserve stack alignment. */ .stack_dummy_managed_exception_thread : { *(.managed_exception_thread) } > RAM /* Set stack top to end of RAM, and stack limit move down by * size of stack_dummy section */ __StackTop = ORIGIN(RAM) + LENGTH(RAM); _estack = __StackTop; __StackLimit = __StackTop - SIZEOF(.stack_dummy) + SIZEOF(.stack_dummy_managed_exception_thread); PROVIDE(__stack = __StackTop); /* Check if data + heap + stack exceeds RAM limit */ ASSERT(__StackLimit >= __HeapLimit, "region RAM overflowed with stack") } ================================================ FILE: Zelig/mbed/TARGET_NUCLEO_F091RC/arm_common_tables.h ================================================ /* ---------------------------------------------------------------------- * Copyright (C) 2010-2014 ARM Limited. All rights reserved. * * $Date: 19. March 2015 * $Revision: V.1.4.5 * * Project: CMSIS DSP Library * Title: arm_common_tables.h * * Description: This file has extern declaration for common tables like Bitreverse, reciprocal etc which are used across different functions * * Target Processor: Cortex-M4/Cortex-M3 * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * - Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * - Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * - Neither the name of ARM LIMITED nor the names of its contributors * may be used to endorse or promote products derived from this * software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * -------------------------------------------------------------------- */ #ifndef _ARM_COMMON_TABLES_H #define _ARM_COMMON_TABLES_H #include "arm_math.h" extern const uint16_t armBitRevTable[1024]; extern const q15_t armRecipTableQ15[64]; extern const q31_t armRecipTableQ31[64]; //extern const q31_t realCoefAQ31[1024]; //extern const q31_t realCoefBQ31[1024]; extern const float32_t twiddleCoef_16[32]; extern const float32_t twiddleCoef_32[64]; extern const float32_t twiddleCoef_64[128]; extern const float32_t twiddleCoef_128[256]; extern const float32_t twiddleCoef_256[512]; extern const float32_t twiddleCoef_512[1024]; extern const float32_t twiddleCoef_1024[2048]; extern const float32_t twiddleCoef_2048[4096]; extern const float32_t twiddleCoef_4096[8192]; #define twiddleCoef twiddleCoef_4096 extern const q31_t twiddleCoef_16_q31[24]; extern const q31_t twiddleCoef_32_q31[48]; extern const q31_t twiddleCoef_64_q31[96]; extern const q31_t twiddleCoef_128_q31[192]; extern const q31_t twiddleCoef_256_q31[384]; extern const q31_t twiddleCoef_512_q31[768]; extern const q31_t twiddleCoef_1024_q31[1536]; extern const q31_t twiddleCoef_2048_q31[3072]; extern const q31_t twiddleCoef_4096_q31[6144]; extern const q15_t twiddleCoef_16_q15[24]; extern const q15_t twiddleCoef_32_q15[48]; extern const q15_t twiddleCoef_64_q15[96]; extern const q15_t twiddleCoef_128_q15[192]; extern const q15_t twiddleCoef_256_q15[384]; extern const q15_t twiddleCoef_512_q15[768]; extern const q15_t twiddleCoef_1024_q15[1536]; extern const q15_t twiddleCoef_2048_q15[3072]; extern const q15_t twiddleCoef_4096_q15[6144]; extern const float32_t twiddleCoef_rfft_32[32]; extern const float32_t twiddleCoef_rfft_64[64]; extern const float32_t twiddleCoef_rfft_128[128]; extern const float32_t twiddleCoef_rfft_256[256]; extern const float32_t twiddleCoef_rfft_512[512]; extern const float32_t twiddleCoef_rfft_1024[1024]; extern const float32_t twiddleCoef_rfft_2048[2048]; extern const float32_t twiddleCoef_rfft_4096[4096]; /* floating-point bit reversal tables */ #define ARMBITREVINDEXTABLE__16_TABLE_LENGTH ((uint16_t)20 ) #define ARMBITREVINDEXTABLE__32_TABLE_LENGTH ((uint16_t)48 ) #define ARMBITREVINDEXTABLE__64_TABLE_LENGTH ((uint16_t)56 ) #define ARMBITREVINDEXTABLE_128_TABLE_LENGTH ((uint16_t)208 ) #define ARMBITREVINDEXTABLE_256_TABLE_LENGTH ((uint16_t)440 ) #define ARMBITREVINDEXTABLE_512_TABLE_LENGTH ((uint16_t)448 ) #define ARMBITREVINDEXTABLE1024_TABLE_LENGTH ((uint16_t)1800) #define ARMBITREVINDEXTABLE2048_TABLE_LENGTH ((uint16_t)3808) #define ARMBITREVINDEXTABLE4096_TABLE_LENGTH ((uint16_t)4032) extern const uint16_t armBitRevIndexTable16[ARMBITREVINDEXTABLE__16_TABLE_LENGTH]; extern const uint16_t armBitRevIndexTable32[ARMBITREVINDEXTABLE__32_TABLE_LENGTH]; extern const uint16_t armBitRevIndexTable64[ARMBITREVINDEXTABLE__64_TABLE_LENGTH]; extern const uint16_t armBitRevIndexTable128[ARMBITREVINDEXTABLE_128_TABLE_LENGTH]; extern const uint16_t armBitRevIndexTable256[ARMBITREVINDEXTABLE_256_TABLE_LENGTH]; extern const uint16_t armBitRevIndexTable512[ARMBITREVINDEXTABLE_512_TABLE_LENGTH]; extern const uint16_t armBitRevIndexTable1024[ARMBITREVINDEXTABLE1024_TABLE_LENGTH]; extern const uint16_t armBitRevIndexTable2048[ARMBITREVINDEXTABLE2048_TABLE_LENGTH]; extern const uint16_t armBitRevIndexTable4096[ARMBITREVINDEXTABLE4096_TABLE_LENGTH]; /* fixed-point bit reversal tables */ #define ARMBITREVINDEXTABLE_FIXED___16_TABLE_LENGTH ((uint16_t)12 ) #define ARMBITREVINDEXTABLE_FIXED___32_TABLE_LENGTH ((uint16_t)24 ) #define ARMBITREVINDEXTABLE_FIXED___64_TABLE_LENGTH ((uint16_t)56 ) #define ARMBITREVINDEXTABLE_FIXED__128_TABLE_LENGTH ((uint16_t)112 ) #define ARMBITREVINDEXTABLE_FIXED__256_TABLE_LENGTH ((uint16_t)240 ) #define ARMBITREVINDEXTABLE_FIXED__512_TABLE_LENGTH ((uint16_t)480 ) #define ARMBITREVINDEXTABLE_FIXED_1024_TABLE_LENGTH ((uint16_t)992 ) #define ARMBITREVINDEXTABLE_FIXED_2048_TABLE_LENGTH ((uint16_t)1984) #define ARMBITREVINDEXTABLE_FIXED_4096_TABLE_LENGTH ((uint16_t)4032) extern const uint16_t armBitRevIndexTable_fixed_16[ARMBITREVINDEXTABLE_FIXED___16_TABLE_LENGTH]; extern const uint16_t armBitRevIndexTable_fixed_32[ARMBITREVINDEXTABLE_FIXED___32_TABLE_LENGTH]; extern const uint16_t armBitRevIndexTable_fixed_64[ARMBITREVINDEXTABLE_FIXED___64_TABLE_LENGTH]; extern const uint16_t armBitRevIndexTable_fixed_128[ARMBITREVINDEXTABLE_FIXED__128_TABLE_LENGTH]; extern const uint16_t armBitRevIndexTable_fixed_256[ARMBITREVINDEXTABLE_FIXED__256_TABLE_LENGTH]; extern const uint16_t armBitRevIndexTable_fixed_512[ARMBITREVINDEXTABLE_FIXED__512_TABLE_LENGTH]; extern const uint16_t armBitRevIndexTable_fixed_1024[ARMBITREVINDEXTABLE_FIXED_1024_TABLE_LENGTH]; extern const uint16_t armBitRevIndexTable_fixed_2048[ARMBITREVINDEXTABLE_FIXED_2048_TABLE_LENGTH]; extern const uint16_t armBitRevIndexTable_fixed_4096[ARMBITREVINDEXTABLE_FIXED_4096_TABLE_LENGTH]; /* Tables for Fast Math Sine and Cosine */ extern const float32_t sinTable_f32[FAST_MATH_TABLE_SIZE + 1]; extern const q31_t sinTable_q31[FAST_MATH_TABLE_SIZE + 1]; extern const q15_t sinTable_q15[FAST_MATH_TABLE_SIZE + 1]; #endif /* ARM_COMMON_TABLES_H */ ================================================ FILE: Zelig/mbed/TARGET_NUCLEO_F091RC/arm_const_structs.h ================================================ /* ---------------------------------------------------------------------- * Copyright (C) 2010-2014 ARM Limited. All rights reserved. * * $Date: 19. March 2015 * $Revision: V.1.4.5 * * Project: CMSIS DSP Library * Title: arm_const_structs.h * * Description: This file has constant structs that are initialized for * user convenience. For example, some can be given as * arguments to the arm_cfft_f32() function. * * Target Processor: Cortex-M4/Cortex-M3 * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * - Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * - Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * - Neither the name of ARM LIMITED nor the names of its contributors * may be used to endorse or promote products derived from this * software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * -------------------------------------------------------------------- */ #ifndef _ARM_CONST_STRUCTS_H #define _ARM_CONST_STRUCTS_H #include "arm_math.h" #include "arm_common_tables.h" extern const arm_cfft_instance_f32 arm_cfft_sR_f32_len16; extern const arm_cfft_instance_f32 arm_cfft_sR_f32_len32; extern const arm_cfft_instance_f32 arm_cfft_sR_f32_len64; extern const arm_cfft_instance_f32 arm_cfft_sR_f32_len128; extern const arm_cfft_instance_f32 arm_cfft_sR_f32_len256; extern const arm_cfft_instance_f32 arm_cfft_sR_f32_len512; extern const arm_cfft_instance_f32 arm_cfft_sR_f32_len1024; extern const arm_cfft_instance_f32 arm_cfft_sR_f32_len2048; extern const arm_cfft_instance_f32 arm_cfft_sR_f32_len4096; extern const arm_cfft_instance_q31 arm_cfft_sR_q31_len16; extern const arm_cfft_instance_q31 arm_cfft_sR_q31_len32; extern const arm_cfft_instance_q31 arm_cfft_sR_q31_len64; extern const arm_cfft_instance_q31 arm_cfft_sR_q31_len128; extern const arm_cfft_instance_q31 arm_cfft_sR_q31_len256; extern const arm_cfft_instance_q31 arm_cfft_sR_q31_len512; extern const arm_cfft_instance_q31 arm_cfft_sR_q31_len1024; extern const arm_cfft_instance_q31 arm_cfft_sR_q31_len2048; extern const arm_cfft_instance_q31 arm_cfft_sR_q31_len4096; extern const arm_cfft_instance_q15 arm_cfft_sR_q15_len16; extern const arm_cfft_instance_q15 arm_cfft_sR_q15_len32; extern const arm_cfft_instance_q15 arm_cfft_sR_q15_len64; extern const arm_cfft_instance_q15 arm_cfft_sR_q15_len128; extern const arm_cfft_instance_q15 arm_cfft_sR_q15_len256; extern const arm_cfft_instance_q15 arm_cfft_sR_q15_len512; extern const arm_cfft_instance_q15 arm_cfft_sR_q15_len1024; extern const arm_cfft_instance_q15 arm_cfft_sR_q15_len2048; extern const arm_cfft_instance_q15 arm_cfft_sR_q15_len4096; #endif ================================================ FILE: Zelig/mbed/TARGET_NUCLEO_F091RC/arm_math.h ================================================ /* ---------------------------------------------------------------------- * Copyright (C) 2010-2015 ARM Limited. All rights reserved. * * $Date: 19. March 2015 * $Revision: V.1.4.5 * * Project: CMSIS DSP Library * Title: arm_math.h * * Description: Public header file for CMSIS DSP Library * * Target Processor: Cortex-M7/Cortex-M4/Cortex-M3/Cortex-M0 * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * - Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * - Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * - Neither the name of ARM LIMITED nor the names of its contributors * may be used to endorse or promote products derived from this * software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * -------------------------------------------------------------------- */ /** \mainpage CMSIS DSP Software Library * * Introduction * ------------ * * This user manual describes the CMSIS DSP software library, * a suite of common signal processing functions for use on Cortex-M processor based devices. * * The library is divided into a number of functions each covering a specific category: * - Basic math functions * - Fast math functions * - Complex math functions * - Filters * - Matrix functions * - Transforms * - Motor control functions * - Statistical functions * - Support functions * - Interpolation functions * * The library has separate functions for operating on 8-bit integers, 16-bit integers, * 32-bit integer and 32-bit floating-point values. * * Using the Library * ------------ * * The library installer contains prebuilt versions of the libraries in the Lib folder. * - arm_cortexM7lfdp_math.lib (Little endian and Double Precision Floating Point Unit on Cortex-M7) * - arm_cortexM7bfdp_math.lib (Big endian and Double Precision Floating Point Unit on Cortex-M7) * - arm_cortexM7lfsp_math.lib (Little endian and Single Precision Floating Point Unit on Cortex-M7) * - arm_cortexM7bfsp_math.lib (Big endian and Single Precision Floating Point Unit on Cortex-M7) * - arm_cortexM7l_math.lib (Little endian on Cortex-M7) * - arm_cortexM7b_math.lib (Big endian on Cortex-M7) * - arm_cortexM4lf_math.lib (Little endian and Floating Point Unit on Cortex-M4) * - arm_cortexM4bf_math.lib (Big endian and Floating Point Unit on Cortex-M4) * - arm_cortexM4l_math.lib (Little endian on Cortex-M4) * - arm_cortexM4b_math.lib (Big endian on Cortex-M4) * - arm_cortexM3l_math.lib (Little endian on Cortex-M3) * - arm_cortexM3b_math.lib (Big endian on Cortex-M3) * - arm_cortexM0l_math.lib (Little endian on Cortex-M0 / CortexM0+) * - arm_cortexM0b_math.lib (Big endian on Cortex-M0 / CortexM0+) * * The library functions are declared in the public file arm_math.h which is placed in the Include folder. * Simply include this file and link the appropriate library in the application and begin calling the library functions. The Library supports single * public header file arm_math.h for Cortex-M7/M4/M3/M0/M0+ with little endian and big endian. Same header file will be used for floating point unit(FPU) variants. * Define the appropriate pre processor MACRO ARM_MATH_CM7 or ARM_MATH_CM4 or ARM_MATH_CM3 or * ARM_MATH_CM0 or ARM_MATH_CM0PLUS depending on the target processor in the application. * * Examples * -------- * * The library ships with a number of examples which demonstrate how to use the library functions. * * Toolchain Support * ------------ * * The library has been developed and tested with MDK-ARM version 5.14.0.0 * The library is being tested in GCC and IAR toolchains and updates on this activity will be made available shortly. * * Building the Library * ------------ * * The library installer contains a project file to re build libraries on MDK-ARM Tool chain in the CMSIS\\DSP_Lib\\Source\\ARM folder. * - arm_cortexM_math.uvprojx * * * The libraries can be built by opening the arm_cortexM_math.uvprojx project in MDK-ARM, selecting a specific target, and defining the optional pre processor MACROs detailed above. * * Pre-processor Macros * ------------ * * Each library project have differant pre-processor macros. * * - UNALIGNED_SUPPORT_DISABLE: * * Define macro UNALIGNED_SUPPORT_DISABLE, If the silicon does not support unaligned memory access * * - ARM_MATH_BIG_ENDIAN: * * Define macro ARM_MATH_BIG_ENDIAN to build the library for big endian targets. By default library builds for little endian targets. * * - ARM_MATH_MATRIX_CHECK: * * Define macro ARM_MATH_MATRIX_CHECK for checking on the input and output sizes of matrices * * - ARM_MATH_ROUNDING: * * Define macro ARM_MATH_ROUNDING for rounding on support functions * * - ARM_MATH_CMx: * * Define macro ARM_MATH_CM4 for building the library on Cortex-M4 target, ARM_MATH_CM3 for building library on Cortex-M3 target * and ARM_MATH_CM0 for building library on Cortex-M0 target, ARM_MATH_CM0PLUS for building library on Cortex-M0+ target, and * ARM_MATH_CM7 for building the library on cortex-M7. * * - __FPU_PRESENT: * * Initialize macro __FPU_PRESENT = 1 when building on FPU supported Targets. Enable this macro for M4bf and M4lf libraries * *
* CMSIS-DSP in ARM::CMSIS Pack * ----------------------------- * * The following files relevant to CMSIS-DSP are present in the ARM::CMSIS Pack directories: * |File/Folder |Content | * |------------------------------|------------------------------------------------------------------------| * |\b CMSIS\\Documentation\\DSP | This documentation | * |\b CMSIS\\DSP_Lib | Software license agreement (license.txt) | * |\b CMSIS\\DSP_Lib\\Examples | Example projects demonstrating the usage of the library functions | * |\b CMSIS\\DSP_Lib\\Source | Source files for rebuilding the library | * *
* Revision History of CMSIS-DSP * ------------ * Please refer to \ref ChangeLog_pg. * * Copyright Notice * ------------ * * Copyright (C) 2010-2015 ARM Limited. All rights reserved. */ /** * @defgroup groupMath Basic Math Functions */ /** * @defgroup groupFastMath Fast Math Functions * This set of functions provides a fast approximation to sine, cosine, and square root. * As compared to most of the other functions in the CMSIS math library, the fast math functions * operate on individual values and not arrays. * There are separate functions for Q15, Q31, and floating-point data. * */ /** * @defgroup groupCmplxMath Complex Math Functions * This set of functions operates on complex data vectors. * The data in the complex arrays is stored in an interleaved fashion * (real, imag, real, imag, ...). * In the API functions, the number of samples in a complex array refers * to the number of complex values; the array contains twice this number of * real values. */ /** * @defgroup groupFilters Filtering Functions */ /** * @defgroup groupMatrix Matrix Functions * * This set of functions provides basic matrix math operations. * The functions operate on matrix data structures. For example, * the type * definition for the floating-point matrix structure is shown * below: *
 *     typedef struct
 *     {
 *       uint16_t numRows;     // number of rows of the matrix.
 *       uint16_t numCols;     // number of columns of the matrix.
 *       float32_t *pData;     // points to the data of the matrix.
 *     } arm_matrix_instance_f32;
 * 
* There are similar definitions for Q15 and Q31 data types. * * The structure specifies the size of the matrix and then points to * an array of data. The array is of size numRows X numCols * and the values are arranged in row order. That is, the * matrix element (i, j) is stored at: *
 *     pData[i*numCols + j]
 * 
* * \par Init Functions * There is an associated initialization function for each type of matrix * data structure. * The initialization function sets the values of the internal structure fields. * Refer to the function arm_mat_init_f32(), arm_mat_init_q31() * and arm_mat_init_q15() for floating-point, Q31 and Q15 types, respectively. * * \par * Use of the initialization function is optional. However, if initialization function is used * then the instance structure cannot be placed into a const data section. * To place the instance structure in a const data * section, manually initialize the data structure. For example: *
 * arm_matrix_instance_f32 S = {nRows, nColumns, pData};
 * arm_matrix_instance_q31 S = {nRows, nColumns, pData};
 * arm_matrix_instance_q15 S = {nRows, nColumns, pData};
 * 
* where nRows specifies the number of rows, nColumns * specifies the number of columns, and pData points to the * data array. * * \par Size Checking * By default all of the matrix functions perform size checking on the input and * output matrices. For example, the matrix addition function verifies that the * two input matrices and the output matrix all have the same number of rows and * columns. If the size check fails the functions return: *
 *     ARM_MATH_SIZE_MISMATCH
 * 
* Otherwise the functions return *
 *     ARM_MATH_SUCCESS
 * 
* There is some overhead associated with this matrix size checking. * The matrix size checking is enabled via the \#define *
 *     ARM_MATH_MATRIX_CHECK
 * 
* within the library project settings. By default this macro is defined * and size checking is enabled. By changing the project settings and * undefining this macro size checking is eliminated and the functions * run a bit faster. With size checking disabled the functions always * return ARM_MATH_SUCCESS. */ /** * @defgroup groupTransforms Transform Functions */ /** * @defgroup groupController Controller Functions */ /** * @defgroup groupStats Statistics Functions */ /** * @defgroup groupSupport Support Functions */ /** * @defgroup groupInterpolation Interpolation Functions * These functions perform 1- and 2-dimensional interpolation of data. * Linear interpolation is used for 1-dimensional data and * bilinear interpolation is used for 2-dimensional data. */ /** * @defgroup groupExamples Examples */ #ifndef _ARM_MATH_H #define _ARM_MATH_H #define __CMSIS_GENERIC /* disable NVIC and Systick functions */ #if defined(ARM_MATH_CM7) #include "core_cm7.h" #elif defined (ARM_MATH_CM4) #include "core_cm4.h" #elif defined (ARM_MATH_CM3) #include "core_cm3.h" #elif defined (ARM_MATH_CM0) #include "core_cm0.h" #define ARM_MATH_CM0_FAMILY #elif defined (ARM_MATH_CM0PLUS) #include "core_cm0plus.h" #define ARM_MATH_CM0_FAMILY #else #error "Define according the used Cortex core ARM_MATH_CM7, ARM_MATH_CM4, ARM_MATH_CM3, ARM_MATH_CM0PLUS or ARM_MATH_CM0" #endif #undef __CMSIS_GENERIC /* enable NVIC and Systick functions */ #include "string.h" #include "math.h" #ifdef __cplusplus extern "C" { #endif /** * @brief Macros required for reciprocal calculation in Normalized LMS */ #define DELTA_Q31 (0x100) #define DELTA_Q15 0x5 #define INDEX_MASK 0x0000003F #ifndef PI #define PI 3.14159265358979f #endif /** * @brief Macros required for SINE and COSINE Fast math approximations */ #define FAST_MATH_TABLE_SIZE 512 #define FAST_MATH_Q31_SHIFT (32 - 10) #define FAST_MATH_Q15_SHIFT (16 - 10) #define CONTROLLER_Q31_SHIFT (32 - 9) #define TABLE_SIZE 256 #define TABLE_SPACING_Q31 0x400000 #define TABLE_SPACING_Q15 0x80 /** * @brief Macros required for SINE and COSINE Controller functions */ /* 1.31(q31) Fixed value of 2/360 */ /* -1 to +1 is divided into 360 values so total spacing is (2/360) */ #define INPUT_SPACING 0xB60B61 /** * @brief Macro for Unaligned Support */ #ifndef UNALIGNED_SUPPORT_DISABLE #define ALIGN4 #else #if defined (__GNUC__) #define ALIGN4 __attribute__((aligned(4))) #else #define ALIGN4 __align(4) #endif #endif /* #ifndef UNALIGNED_SUPPORT_DISABLE */ /** * @brief Error status returned by some functions in the library. */ typedef enum { ARM_MATH_SUCCESS = 0, /**< No error */ ARM_MATH_ARGUMENT_ERROR = -1, /**< One or more arguments are incorrect */ ARM_MATH_LENGTH_ERROR = -2, /**< Length of data buffer is incorrect */ ARM_MATH_SIZE_MISMATCH = -3, /**< Size of matrices is not compatible with the operation. */ ARM_MATH_NANINF = -4, /**< Not-a-number (NaN) or infinity is generated */ ARM_MATH_SINGULAR = -5, /**< Generated by matrix inversion if the input matrix is singular and cannot be inverted. */ ARM_MATH_TEST_FAILURE = -6 /**< Test Failed */ } arm_status; /** * @brief 8-bit fractional data type in 1.7 format. */ typedef int8_t q7_t; /** * @brief 16-bit fractional data type in 1.15 format. */ typedef int16_t q15_t; /** * @brief 32-bit fractional data type in 1.31 format. */ typedef int32_t q31_t; /** * @brief 64-bit fractional data type in 1.63 format. */ typedef int64_t q63_t; /** * @brief 32-bit floating-point type definition. */ typedef float float32_t; /** * @brief 64-bit floating-point type definition. */ typedef double float64_t; /** * @brief definition to read/write two 16 bit values. */ #if defined __CC_ARM #define __SIMD32_TYPE int32_t __packed #define CMSIS_UNUSED __attribute__((unused)) #elif defined __ICCARM__ #define __SIMD32_TYPE int32_t __packed #define CMSIS_UNUSED #elif defined __GNUC__ #define __SIMD32_TYPE int32_t #define CMSIS_UNUSED __attribute__((unused)) #elif defined __CSMC__ /* Cosmic */ #define __SIMD32_TYPE int32_t #define CMSIS_UNUSED #elif defined __TASKING__ #define __SIMD32_TYPE __unaligned int32_t #define CMSIS_UNUSED #else #error Unknown compiler #endif #define __SIMD32(addr) (*(__SIMD32_TYPE **) & (addr)) #define __SIMD32_CONST(addr) ((__SIMD32_TYPE *)(addr)) #define _SIMD32_OFFSET(addr) (*(__SIMD32_TYPE *) (addr)) #define __SIMD64(addr) (*(int64_t **) & (addr)) #if defined (ARM_MATH_CM3) || defined (ARM_MATH_CM0_FAMILY) /** * @brief definition to pack two 16 bit values. */ #define __PKHBT(ARG1, ARG2, ARG3) ( (((int32_t)(ARG1) << 0) & (int32_t)0x0000FFFF) | \ (((int32_t)(ARG2) << ARG3) & (int32_t)0xFFFF0000) ) #define __PKHTB(ARG1, ARG2, ARG3) ( (((int32_t)(ARG1) << 0) & (int32_t)0xFFFF0000) | \ (((int32_t)(ARG2) >> ARG3) & (int32_t)0x0000FFFF) ) #endif /** * @brief definition to pack four 8 bit values. */ #ifndef ARM_MATH_BIG_ENDIAN #define __PACKq7(v0,v1,v2,v3) ( (((int32_t)(v0) << 0) & (int32_t)0x000000FF) | \ (((int32_t)(v1) << 8) & (int32_t)0x0000FF00) | \ (((int32_t)(v2) << 16) & (int32_t)0x00FF0000) | \ (((int32_t)(v3) << 24) & (int32_t)0xFF000000) ) #else #define __PACKq7(v0,v1,v2,v3) ( (((int32_t)(v3) << 0) & (int32_t)0x000000FF) | \ (((int32_t)(v2) << 8) & (int32_t)0x0000FF00) | \ (((int32_t)(v1) << 16) & (int32_t)0x00FF0000) | \ (((int32_t)(v0) << 24) & (int32_t)0xFF000000) ) #endif /** * @brief Clips Q63 to Q31 values. */ static __INLINE q31_t clip_q63_to_q31( q63_t x) { return ((q31_t) (x >> 32) != ((q31_t) x >> 31)) ? ((0x7FFFFFFF ^ ((q31_t) (x >> 63)))) : (q31_t) x; } /** * @brief Clips Q63 to Q15 values. */ static __INLINE q15_t clip_q63_to_q15( q63_t x) { return ((q31_t) (x >> 32) != ((q31_t) x >> 31)) ? ((0x7FFF ^ ((q15_t) (x >> 63)))) : (q15_t) (x >> 15); } /** * @brief Clips Q31 to Q7 values. */ static __INLINE q7_t clip_q31_to_q7( q31_t x) { return ((q31_t) (x >> 24) != ((q31_t) x >> 23)) ? ((0x7F ^ ((q7_t) (x >> 31)))) : (q7_t) x; } /** * @brief Clips Q31 to Q15 values. */ static __INLINE q15_t clip_q31_to_q15( q31_t x) { return ((q31_t) (x >> 16) != ((q31_t) x >> 15)) ? ((0x7FFF ^ ((q15_t) (x >> 31)))) : (q15_t) x; } /** * @brief Multiplies 32 X 64 and returns 32 bit result in 2.30 format. */ static __INLINE q63_t mult32x64( q63_t x, q31_t y) { return ((((q63_t) (x & 0x00000000FFFFFFFF) * y) >> 32) + (((q63_t) (x >> 32) * y))); } //#if defined (ARM_MATH_CM0_FAMILY) && defined ( __CC_ARM ) //#define __CLZ __clz //#endif //note: function can be removed when all toolchain support __CLZ for Cortex-M0 #if defined (ARM_MATH_CM0_FAMILY) && ((defined (__ICCARM__)) ) static __INLINE uint32_t __CLZ( q31_t data); static __INLINE uint32_t __CLZ( q31_t data) { uint32_t count = 0; uint32_t mask = 0x80000000; while((data & mask) == 0) { count += 1u; mask = mask >> 1u; } return (count); } #endif /** * @brief Function to Calculates 1/in (reciprocal) value of Q31 Data type. */ static __INLINE uint32_t arm_recip_q31( q31_t in, q31_t * dst, q31_t * pRecipTable) { uint32_t out, tempVal; uint32_t index, i; uint32_t signBits; if(in > 0) { signBits = __CLZ(in) - 1; } else { signBits = __CLZ(-in) - 1; } /* Convert input sample to 1.31 format */ in = in << signBits; /* calculation of index for initial approximated Val */ index = (uint32_t) (in >> 24u); index = (index & INDEX_MASK); /* 1.31 with exp 1 */ out = pRecipTable[index]; /* calculation of reciprocal value */ /* running approximation for two iterations */ for (i = 0u; i < 2u; i++) { tempVal = (q31_t) (((q63_t) in * out) >> 31u); tempVal = 0x7FFFFFFF - tempVal; /* 1.31 with exp 1 */ //out = (q31_t) (((q63_t) out * tempVal) >> 30u); out = (q31_t) clip_q63_to_q31(((q63_t) out * tempVal) >> 30u); } /* write output */ *dst = out; /* return num of signbits of out = 1/in value */ return (signBits + 1u); } /** * @brief Function to Calculates 1/in (reciprocal) value of Q15 Data type. */ static __INLINE uint32_t arm_recip_q15( q15_t in, q15_t * dst, q15_t * pRecipTable) { uint32_t out = 0, tempVal = 0; uint32_t index = 0, i = 0; uint32_t signBits = 0; if(in > 0) { signBits = __CLZ(in) - 17; } else { signBits = __CLZ(-in) - 17; } /* Convert input sample to 1.15 format */ in = in << signBits; /* calculation of index for initial approximated Val */ index = in >> 8; index = (index & INDEX_MASK); /* 1.15 with exp 1 */ out = pRecipTable[index]; /* calculation of reciprocal value */ /* running approximation for two iterations */ for (i = 0; i < 2; i++) { tempVal = (q15_t) (((q31_t) in * out) >> 15); tempVal = 0x7FFF - tempVal; /* 1.15 with exp 1 */ out = (q15_t) (((q31_t) out * tempVal) >> 14); } /* write output */ *dst = out; /* return num of signbits of out = 1/in value */ return (signBits + 1); } /* * @brief C custom defined intrinisic function for only M0 processors */ #if defined(ARM_MATH_CM0_FAMILY) static __INLINE q31_t __SSAT( q31_t x, uint32_t y) { int32_t posMax, negMin; uint32_t i; posMax = 1; for (i = 0; i < (y - 1); i++) { posMax = posMax * 2; } if(x > 0) { posMax = (posMax - 1); if(x > posMax) { x = posMax; } } else { negMin = -posMax; if(x < negMin) { x = negMin; } } return (x); } #endif /* end of ARM_MATH_CM0_FAMILY */ /* * @brief C custom defined intrinsic function for M3 and M0 processors */ #if defined (ARM_MATH_CM3) || defined (ARM_MATH_CM0_FAMILY) /* * @brief C custom defined QADD8 for M3 and M0 processors */ static __INLINE q31_t __QADD8( q31_t x, q31_t y) { q31_t sum; q7_t r, s, t, u; r = (q7_t) x; s = (q7_t) y; r = __SSAT((q31_t) (r + s), 8); s = __SSAT(((q31_t) (((x << 16) >> 24) + ((y << 16) >> 24))), 8); t = __SSAT(((q31_t) (((x << 8) >> 24) + ((y << 8) >> 24))), 8); u = __SSAT(((q31_t) ((x >> 24) + (y >> 24))), 8); sum = (((q31_t) u << 24) & 0xFF000000) | (((q31_t) t << 16) & 0x00FF0000) | (((q31_t) s << 8) & 0x0000FF00) | (r & 0x000000FF); return sum; } /* * @brief C custom defined QSUB8 for M3 and M0 processors */ static __INLINE q31_t __QSUB8( q31_t x, q31_t y) { q31_t sum; q31_t r, s, t, u; r = (q7_t) x; s = (q7_t) y; r = __SSAT((r - s), 8); s = __SSAT(((q31_t) (((x << 16) >> 24) - ((y << 16) >> 24))), 8) << 8; t = __SSAT(((q31_t) (((x << 8) >> 24) - ((y << 8) >> 24))), 8) << 16; u = __SSAT(((q31_t) ((x >> 24) - (y >> 24))), 8) << 24; sum = (u & 0xFF000000) | (t & 0x00FF0000) | (s & 0x0000FF00) | (r & 0x000000FF); return sum; } /* * @brief C custom defined QADD16 for M3 and M0 processors */ /* * @brief C custom defined QADD16 for M3 and M0 processors */ static __INLINE q31_t __QADD16( q31_t x, q31_t y) { q31_t sum; q31_t r, s; r = (q15_t) x; s = (q15_t) y; r = __SSAT(r + s, 16); s = __SSAT(((q31_t) ((x >> 16) + (y >> 16))), 16) << 16; sum = (s & 0xFFFF0000) | (r & 0x0000FFFF); return sum; } /* * @brief C custom defined SHADD16 for M3 and M0 processors */ static __INLINE q31_t __SHADD16( q31_t x, q31_t y) { q31_t sum; q31_t r, s; r = (q15_t) x; s = (q15_t) y; r = ((r >> 1) + (s >> 1)); s = ((q31_t) ((x >> 17) + (y >> 17))) << 16; sum = (s & 0xFFFF0000) | (r & 0x0000FFFF); return sum; } /* * @brief C custom defined QSUB16 for M3 and M0 processors */ static __INLINE q31_t __QSUB16( q31_t x, q31_t y) { q31_t sum; q31_t r, s; r = (q15_t) x; s = (q15_t) y; r = __SSAT(r - s, 16); s = __SSAT(((q31_t) ((x >> 16) - (y >> 16))), 16) << 16; sum = (s & 0xFFFF0000) | (r & 0x0000FFFF); return sum; } /* * @brief C custom defined SHSUB16 for M3 and M0 processors */ static __INLINE q31_t __SHSUB16( q31_t x, q31_t y) { q31_t diff; q31_t r, s; r = (q15_t) x; s = (q15_t) y; r = ((r >> 1) - (s >> 1)); s = (((x >> 17) - (y >> 17)) << 16); diff = (s & 0xFFFF0000) | (r & 0x0000FFFF); return diff; } /* * @brief C custom defined QASX for M3 and M0 processors */ static __INLINE q31_t __QASX( q31_t x, q31_t y) { q31_t sum = 0; sum = ((sum + clip_q31_to_q15((q31_t) ((q15_t) (x >> 16) + (q15_t) y))) << 16) + clip_q31_to_q15((q31_t) ((q15_t) x - (q15_t) (y >> 16))); return sum; } /* * @brief C custom defined SHASX for M3 and M0 processors */ static __INLINE q31_t __SHASX( q31_t x, q31_t y) { q31_t sum; q31_t r, s; r = (q15_t) x; s = (q15_t) y; r = ((r >> 1) - (y >> 17)); s = (((x >> 17) + (s >> 1)) << 16); sum = (s & 0xFFFF0000) | (r & 0x0000FFFF); return sum; } /* * @brief C custom defined QSAX for M3 and M0 processors */ static __INLINE q31_t __QSAX( q31_t x, q31_t y) { q31_t sum = 0; sum = ((sum + clip_q31_to_q15((q31_t) ((q15_t) (x >> 16) - (q15_t) y))) << 16) + clip_q31_to_q15((q31_t) ((q15_t) x + (q15_t) (y >> 16))); return sum; } /* * @brief C custom defined SHSAX for M3 and M0 processors */ static __INLINE q31_t __SHSAX( q31_t x, q31_t y) { q31_t sum; q31_t r, s; r = (q15_t) x; s = (q15_t) y; r = ((r >> 1) + (y >> 17)); s = (((x >> 17) - (s >> 1)) << 16); sum = (s & 0xFFFF0000) | (r & 0x0000FFFF); return sum; } /* * @brief C custom defined SMUSDX for M3 and M0 processors */ static __INLINE q31_t __SMUSDX( q31_t x, q31_t y) { return ((q31_t) (((q15_t) x * (q15_t) (y >> 16)) - ((q15_t) (x >> 16) * (q15_t) y))); } /* * @brief C custom defined SMUADX for M3 and M0 processors */ static __INLINE q31_t __SMUADX( q31_t x, q31_t y) { return ((q31_t) (((q15_t) x * (q15_t) (y >> 16)) + ((q15_t) (x >> 16) * (q15_t) y))); } /* * @brief C custom defined QADD for M3 and M0 processors */ static __INLINE q31_t __QADD( q31_t x, q31_t y) { return clip_q63_to_q31((q63_t) x + y); } /* * @brief C custom defined QSUB for M3 and M0 processors */ static __INLINE q31_t __QSUB( q31_t x, q31_t y) { return clip_q63_to_q31((q63_t) x - y); } /* * @brief C custom defined SMLAD for M3 and M0 processors */ static __INLINE q31_t __SMLAD( q31_t x, q31_t y, q31_t sum) { return (sum + ((q15_t) (x >> 16) * (q15_t) (y >> 16)) + ((q15_t) x * (q15_t) y)); } /* * @brief C custom defined SMLADX for M3 and M0 processors */ static __INLINE q31_t __SMLADX( q31_t x, q31_t y, q31_t sum) { return (sum + ((q15_t) (x >> 16) * (q15_t) (y)) + ((q15_t) x * (q15_t) (y >> 16))); } /* * @brief C custom defined SMLSDX for M3 and M0 processors */ static __INLINE q31_t __SMLSDX( q31_t x, q31_t y, q31_t sum) { return (sum - ((q15_t) (x >> 16) * (q15_t) (y)) + ((q15_t) x * (q15_t) (y >> 16))); } /* * @brief C custom defined SMLALD for M3 and M0 processors */ static __INLINE q63_t __SMLALD( q31_t x, q31_t y, q63_t sum) { return (sum + ((q15_t) (x >> 16) * (q15_t) (y >> 16)) + ((q15_t) x * (q15_t) y)); } /* * @brief C custom defined SMLALDX for M3 and M0 processors */ static __INLINE q63_t __SMLALDX( q31_t x, q31_t y, q63_t sum) { return (sum + ((q15_t) (x >> 16) * (q15_t) y)) + ((q15_t) x * (q15_t) (y >> 16)); } /* * @brief C custom defined SMUAD for M3 and M0 processors */ static __INLINE q31_t __SMUAD( q31_t x, q31_t y) { return (((x >> 16) * (y >> 16)) + (((x << 16) >> 16) * ((y << 16) >> 16))); } /* * @brief C custom defined SMUSD for M3 and M0 processors */ static __INLINE q31_t __SMUSD( q31_t x, q31_t y) { return (-((x >> 16) * (y >> 16)) + (((x << 16) >> 16) * ((y << 16) >> 16))); } /* * @brief C custom defined SXTB16 for M3 and M0 processors */ static __INLINE q31_t __SXTB16( q31_t x) { return ((((x << 24) >> 24) & 0x0000FFFF) | (((x << 8) >> 8) & 0xFFFF0000)); } #endif /* defined (ARM_MATH_CM3) || defined (ARM_MATH_CM0_FAMILY) */ /** * @brief Instance structure for the Q7 FIR filter. */ typedef struct { uint16_t numTaps; /**< number of filter coefficients in the filter. */ q7_t *pState; /**< points to the state variable array. The array is of length numTaps+blockSize-1. */ q7_t *pCoeffs; /**< points to the coefficient array. The array is of length numTaps.*/ } arm_fir_instance_q7; /** * @brief Instance structure for the Q15 FIR filter. */ typedef struct { uint16_t numTaps; /**< number of filter coefficients in the filter. */ q15_t *pState; /**< points to the state variable array. The array is of length numTaps+blockSize-1. */ q15_t *pCoeffs; /**< points to the coefficient array. The array is of length numTaps.*/ } arm_fir_instance_q15; /** * @brief Instance structure for the Q31 FIR filter. */ typedef struct { uint16_t numTaps; /**< number of filter coefficients in the filter. */ q31_t *pState; /**< points to the state variable array. The array is of length numTaps+blockSize-1. */ q31_t *pCoeffs; /**< points to the coefficient array. The array is of length numTaps. */ } arm_fir_instance_q31; /** * @brief Instance structure for the floating-point FIR filter. */ typedef struct { uint16_t numTaps; /**< number of filter coefficients in the filter. */ float32_t *pState; /**< points to the state variable array. The array is of length numTaps+blockSize-1. */ float32_t *pCoeffs; /**< points to the coefficient array. The array is of length numTaps. */ } arm_fir_instance_f32; /** * @brief Processing function for the Q7 FIR filter. * @param[in] *S points to an instance of the Q7 FIR filter structure. * @param[in] *pSrc points to the block of input data. * @param[out] *pDst points to the block of output data. * @param[in] blockSize number of samples to process. * @return none. */ void arm_fir_q7( const arm_fir_instance_q7 * S, q7_t * pSrc, q7_t * pDst, uint32_t blockSize); /** * @brief Initialization function for the Q7 FIR filter. * @param[in,out] *S points to an instance of the Q7 FIR structure. * @param[in] numTaps Number of filter coefficients in the filter. * @param[in] *pCoeffs points to the filter coefficients. * @param[in] *pState points to the state buffer. * @param[in] blockSize number of samples that are processed. * @return none */ void arm_fir_init_q7( arm_fir_instance_q7 * S, uint16_t numTaps, q7_t * pCoeffs, q7_t * pState, uint32_t blockSize); /** * @brief Processing function for the Q15 FIR filter. * @param[in] *S points to an instance of the Q15 FIR structure. * @param[in] *pSrc points to the block of input data. * @param[out] *pDst points to the block of output data. * @param[in] blockSize number of samples to process. * @return none. */ void arm_fir_q15( const arm_fir_instance_q15 * S, q15_t * pSrc, q15_t * pDst, uint32_t blockSize); /** * @brief Processing function for the fast Q15 FIR filter for Cortex-M3 and Cortex-M4. * @param[in] *S points to an instance of the Q15 FIR filter structure. * @param[in] *pSrc points to the block of input data. * @param[out] *pDst points to the block of output data. * @param[in] blockSize number of samples to process. * @return none. */ void arm_fir_fast_q15( const arm_fir_instance_q15 * S, q15_t * pSrc, q15_t * pDst, uint32_t blockSize); /** * @brief Initialization function for the Q15 FIR filter. * @param[in,out] *S points to an instance of the Q15 FIR filter structure. * @param[in] numTaps Number of filter coefficients in the filter. Must be even and greater than or equal to 4. * @param[in] *pCoeffs points to the filter coefficients. * @param[in] *pState points to the state buffer. * @param[in] blockSize number of samples that are processed at a time. * @return The function returns ARM_MATH_SUCCESS if initialization was successful or ARM_MATH_ARGUMENT_ERROR if * numTaps is not a supported value. */ arm_status arm_fir_init_q15( arm_fir_instance_q15 * S, uint16_t numTaps, q15_t * pCoeffs, q15_t * pState, uint32_t blockSize); /** * @brief Processing function for the Q31 FIR filter. * @param[in] *S points to an instance of the Q31 FIR filter structure. * @param[in] *pSrc points to the block of input data. * @param[out] *pDst points to the block of output data. * @param[in] blockSize number of samples to process. * @return none. */ void arm_fir_q31( const arm_fir_instance_q31 * S, q31_t * pSrc, q31_t * pDst, uint32_t blockSize); /** * @brief Processing function for the fast Q31 FIR filter for Cortex-M3 and Cortex-M4. * @param[in] *S points to an instance of the Q31 FIR structure. * @param[in] *pSrc points to the block of input data. * @param[out] *pDst points to the block of output data. * @param[in] blockSize number of samples to process. * @return none. */ void arm_fir_fast_q31( const arm_fir_instance_q31 * S, q31_t * pSrc, q31_t * pDst, uint32_t blockSize); /** * @brief Initialization function for the Q31 FIR filter. * @param[in,out] *S points to an instance of the Q31 FIR structure. * @param[in] numTaps Number of filter coefficients in the filter. * @param[in] *pCoeffs points to the filter coefficients. * @param[in] *pState points to the state buffer. * @param[in] blockSize number of samples that are processed at a time. * @return none. */ void arm_fir_init_q31( arm_fir_instance_q31 * S, uint16_t numTaps, q31_t * pCoeffs, q31_t * pState, uint32_t blockSize); /** * @brief Processing function for the floating-point FIR filter. * @param[in] *S points to an instance of the floating-point FIR structure. * @param[in] *pSrc points to the block of input data. * @param[out] *pDst points to the block of output data. * @param[in] blockSize number of samples to process. * @return none. */ void arm_fir_f32( const arm_fir_instance_f32 * S, float32_t * pSrc, float32_t * pDst, uint32_t blockSize); /** * @brief Initialization function for the floating-point FIR filter. * @param[in,out] *S points to an instance of the floating-point FIR filter structure. * @param[in] numTaps Number of filter coefficients in the filter. * @param[in] *pCoeffs points to the filter coefficients. * @param[in] *pState points to the state buffer. * @param[in] blockSize number of samples that are processed at a time. * @return none. */ void arm_fir_init_f32( arm_fir_instance_f32 * S, uint16_t numTaps, float32_t * pCoeffs, float32_t * pState, uint32_t blockSize); /** * @brief Instance structure for the Q15 Biquad cascade filter. */ typedef struct { int8_t numStages; /**< number of 2nd order stages in the filter. Overall order is 2*numStages. */ q15_t *pState; /**< Points to the array of state coefficients. The array is of length 4*numStages. */ q15_t *pCoeffs; /**< Points to the array of coefficients. The array is of length 5*numStages. */ int8_t postShift; /**< Additional shift, in bits, applied to each output sample. */ } arm_biquad_casd_df1_inst_q15; /** * @brief Instance structure for the Q31 Biquad cascade filter. */ typedef struct { uint32_t numStages; /**< number of 2nd order stages in the filter. Overall order is 2*numStages. */ q31_t *pState; /**< Points to the array of state coefficients. The array is of length 4*numStages. */ q31_t *pCoeffs; /**< Points to the array of coefficients. The array is of length 5*numStages. */ uint8_t postShift; /**< Additional shift, in bits, applied to each output sample. */ } arm_biquad_casd_df1_inst_q31; /** * @brief Instance structure for the floating-point Biquad cascade filter. */ typedef struct { uint32_t numStages; /**< number of 2nd order stages in the filter. Overall order is 2*numStages. */ float32_t *pState; /**< Points to the array of state coefficients. The array is of length 4*numStages. */ float32_t *pCoeffs; /**< Points to the array of coefficients. The array is of length 5*numStages. */ } arm_biquad_casd_df1_inst_f32; /** * @brief Processing function for the Q15 Biquad cascade filter. * @param[in] *S points to an instance of the Q15 Biquad cascade structure. * @param[in] *pSrc points to the block of input data. * @param[out] *pDst points to the block of output data. * @param[in] blockSize number of samples to process. * @return none. */ void arm_biquad_cascade_df1_q15( const arm_biquad_casd_df1_inst_q15 * S, q15_t * pSrc, q15_t * pDst, uint32_t blockSize); /** * @brief Initialization function for the Q15 Biquad cascade filter. * @param[in,out] *S points to an instance of the Q15 Biquad cascade structure. * @param[in] numStages number of 2nd order stages in the filter. * @param[in] *pCoeffs points to the filter coefficients. * @param[in] *pState points to the state buffer. * @param[in] postShift Shift to be applied to the output. Varies according to the coefficients format * @return none */ void arm_biquad_cascade_df1_init_q15( arm_biquad_casd_df1_inst_q15 * S, uint8_t numStages, q15_t * pCoeffs, q15_t * pState, int8_t postShift); /** * @brief Fast but less precise processing function for the Q15 Biquad cascade filter for Cortex-M3 and Cortex-M4. * @param[in] *S points to an instance of the Q15 Biquad cascade structure. * @param[in] *pSrc points to the block of input data. * @param[out] *pDst points to the block of output data. * @param[in] blockSize number of samples to process. * @return none. */ void arm_biquad_cascade_df1_fast_q15( const arm_biquad_casd_df1_inst_q15 * S, q15_t * pSrc, q15_t * pDst, uint32_t blockSize); /** * @brief Processing function for the Q31 Biquad cascade filter * @param[in] *S points to an instance of the Q31 Biquad cascade structure. * @param[in] *pSrc points to the block of input data. * @param[out] *pDst points to the block of output data. * @param[in] blockSize number of samples to process. * @return none. */ void arm_biquad_cascade_df1_q31( const arm_biquad_casd_df1_inst_q31 * S, q31_t * pSrc, q31_t * pDst, uint32_t blockSize); /** * @brief Fast but less precise processing function for the Q31 Biquad cascade filter for Cortex-M3 and Cortex-M4. * @param[in] *S points to an instance of the Q31 Biquad cascade structure. * @param[in] *pSrc points to the block of input data. * @param[out] *pDst points to the block of output data. * @param[in] blockSize number of samples to process. * @return none. */ void arm_biquad_cascade_df1_fast_q31( const arm_biquad_casd_df1_inst_q31 * S, q31_t * pSrc, q31_t * pDst, uint32_t blockSize); /** * @brief Initialization function for the Q31 Biquad cascade filter. * @param[in,out] *S points to an instance of the Q31 Biquad cascade structure. * @param[in] numStages number of 2nd order stages in the filter. * @param[in] *pCoeffs points to the filter coefficients. * @param[in] *pState points to the state buffer. * @param[in] postShift Shift to be applied to the output. Varies according to the coefficients format * @return none */ void arm_biquad_cascade_df1_init_q31( arm_biquad_casd_df1_inst_q31 * S, uint8_t numStages, q31_t * pCoeffs, q31_t * pState, int8_t postShift); /** * @brief Processing function for the floating-point Biquad cascade filter. * @param[in] *S points to an instance of the floating-point Biquad cascade structure. * @param[in] *pSrc points to the block of input data. * @param[out] *pDst points to the block of output data. * @param[in] blockSize number of samples to process. * @return none. */ void arm_biquad_cascade_df1_f32( const arm_biquad_casd_df1_inst_f32 * S, float32_t * pSrc, float32_t * pDst, uint32_t blockSize); /** * @brief Initialization function for the floating-point Biquad cascade filter. * @param[in,out] *S points to an instance of the floating-point Biquad cascade structure. * @param[in] numStages number of 2nd order stages in the filter. * @param[in] *pCoeffs points to the filter coefficients. * @param[in] *pState points to the state buffer. * @return none */ void arm_biquad_cascade_df1_init_f32( arm_biquad_casd_df1_inst_f32 * S, uint8_t numStages, float32_t * pCoeffs, float32_t * pState); /** * @brief Instance structure for the floating-point matrix structure. */ typedef struct { uint16_t numRows; /**< number of rows of the matrix. */ uint16_t numCols; /**< number of columns of the matrix. */ float32_t *pData; /**< points to the data of the matrix. */ } arm_matrix_instance_f32; /** * @brief Instance structure for the floating-point matrix structure. */ typedef struct { uint16_t numRows; /**< number of rows of the matrix. */ uint16_t numCols; /**< number of columns of the matrix. */ float64_t *pData; /**< points to the data of the matrix. */ } arm_matrix_instance_f64; /** * @brief Instance structure for the Q15 matrix structure. */ typedef struct { uint16_t numRows; /**< number of rows of the matrix. */ uint16_t numCols; /**< number of columns of the matrix. */ q15_t *pData; /**< points to the data of the matrix. */ } arm_matrix_instance_q15; /** * @brief Instance structure for the Q31 matrix structure. */ typedef struct { uint16_t numRows; /**< number of rows of the matrix. */ uint16_t numCols; /**< number of columns of the matrix. */ q31_t *pData; /**< points to the data of the matrix. */ } arm_matrix_instance_q31; /** * @brief Floating-point matrix addition. * @param[in] *pSrcA points to the first input matrix structure * @param[in] *pSrcB points to the second input matrix structure * @param[out] *pDst points to output matrix structure * @return The function returns either * ARM_MATH_SIZE_MISMATCH or ARM_MATH_SUCCESS based on the outcome of size checking. */ arm_status arm_mat_add_f32( const arm_matrix_instance_f32 * pSrcA, const arm_matrix_instance_f32 * pSrcB, arm_matrix_instance_f32 * pDst); /** * @brief Q15 matrix addition. * @param[in] *pSrcA points to the first input matrix structure * @param[in] *pSrcB points to the second input matrix structure * @param[out] *pDst points to output matrix structure * @return The function returns either * ARM_MATH_SIZE_MISMATCH or ARM_MATH_SUCCESS based on the outcome of size checking. */ arm_status arm_mat_add_q15( const arm_matrix_instance_q15 * pSrcA, const arm_matrix_instance_q15 * pSrcB, arm_matrix_instance_q15 * pDst); /** * @brief Q31 matrix addition. * @param[in] *pSrcA points to the first input matrix structure * @param[in] *pSrcB points to the second input matrix structure * @param[out] *pDst points to output matrix structure * @return The function returns either * ARM_MATH_SIZE_MISMATCH or ARM_MATH_SUCCESS based on the outcome of size checking. */ arm_status arm_mat_add_q31( const arm_matrix_instance_q31 * pSrcA, const arm_matrix_instance_q31 * pSrcB, arm_matrix_instance_q31 * pDst); /** * @brief Floating-point, complex, matrix multiplication. * @param[in] *pSrcA points to the first input matrix structure * @param[in] *pSrcB points to the second input matrix structure * @param[out] *pDst points to output matrix structure * @return The function returns either * ARM_MATH_SIZE_MISMATCH or ARM_MATH_SUCCESS based on the outcome of size checking. */ arm_status arm_mat_cmplx_mult_f32( const arm_matrix_instance_f32 * pSrcA, const arm_matrix_instance_f32 * pSrcB, arm_matrix_instance_f32 * pDst); /** * @brief Q15, complex, matrix multiplication. * @param[in] *pSrcA points to the first input matrix structure * @param[in] *pSrcB points to the second input matrix structure * @param[out] *pDst points to output matrix structure * @return The function returns either * ARM_MATH_SIZE_MISMATCH or ARM_MATH_SUCCESS based on the outcome of size checking. */ arm_status arm_mat_cmplx_mult_q15( const arm_matrix_instance_q15 * pSrcA, const arm_matrix_instance_q15 * pSrcB, arm_matrix_instance_q15 * pDst, q15_t * pScratch); /** * @brief Q31, complex, matrix multiplication. * @param[in] *pSrcA points to the first input matrix structure * @param[in] *pSrcB points to the second input matrix structure * @param[out] *pDst points to output matrix structure * @return The function returns either * ARM_MATH_SIZE_MISMATCH or ARM_MATH_SUCCESS based on the outcome of size checking. */ arm_status arm_mat_cmplx_mult_q31( const arm_matrix_instance_q31 * pSrcA, const arm_matrix_instance_q31 * pSrcB, arm_matrix_instance_q31 * pDst); /** * @brief Floating-point matrix transpose. * @param[in] *pSrc points to the input matrix * @param[out] *pDst points to the output matrix * @return The function returns either ARM_MATH_SIZE_MISMATCH * or ARM_MATH_SUCCESS based on the outcome of size checking. */ arm_status arm_mat_trans_f32( const arm_matrix_instance_f32 * pSrc, arm_matrix_instance_f32 * pDst); /** * @brief Q15 matrix transpose. * @param[in] *pSrc points to the input matrix * @param[out] *pDst points to the output matrix * @return The function returns either ARM_MATH_SIZE_MISMATCH * or ARM_MATH_SUCCESS based on the outcome of size checking. */ arm_status arm_mat_trans_q15( const arm_matrix_instance_q15 * pSrc, arm_matrix_instance_q15 * pDst); /** * @brief Q31 matrix transpose. * @param[in] *pSrc points to the input matrix * @param[out] *pDst points to the output matrix * @return The function returns either ARM_MATH_SIZE_MISMATCH * or ARM_MATH_SUCCESS based on the outcome of size checking. */ arm_status arm_mat_trans_q31( const arm_matrix_instance_q31 * pSrc, arm_matrix_instance_q31 * pDst); /** * @brief Floating-point matrix multiplication * @param[in] *pSrcA points to the first input matrix structure * @param[in] *pSrcB points to the second input matrix structure * @param[out] *pDst points to output matrix structure * @return The function returns either * ARM_MATH_SIZE_MISMATCH or ARM_MATH_SUCCESS based on the outcome of size checking. */ arm_status arm_mat_mult_f32( const arm_matrix_instance_f32 * pSrcA, const arm_matrix_instance_f32 * pSrcB, arm_matrix_instance_f32 * pDst); /** * @brief Q15 matrix multiplication * @param[in] *pSrcA points to the first input matrix structure * @param[in] *pSrcB points to the second input matrix structure * @param[out] *pDst points to output matrix structure * @param[in] *pState points to the array for storing intermediate results * @return The function returns either * ARM_MATH_SIZE_MISMATCH or ARM_MATH_SUCCESS based on the outcome of size checking. */ arm_status arm_mat_mult_q15( const arm_matrix_instance_q15 * pSrcA, const arm_matrix_instance_q15 * pSrcB, arm_matrix_instance_q15 * pDst, q15_t * pState); /** * @brief Q15 matrix multiplication (fast variant) for Cortex-M3 and Cortex-M4 * @param[in] *pSrcA points to the first input matrix structure * @param[in] *pSrcB points to the second input matrix structure * @param[out] *pDst points to output matrix structure * @param[in] *pState points to the array for storing intermediate results * @return The function returns either * ARM_MATH_SIZE_MISMATCH or ARM_MATH_SUCCESS based on the outcome of size checking. */ arm_status arm_mat_mult_fast_q15( const arm_matrix_instance_q15 * pSrcA, const arm_matrix_instance_q15 * pSrcB, arm_matrix_instance_q15 * pDst, q15_t * pState); /** * @brief Q31 matrix multiplication * @param[in] *pSrcA points to the first input matrix structure * @param[in] *pSrcB points to the second input matrix structure * @param[out] *pDst points to output matrix structure * @return The function returns either * ARM_MATH_SIZE_MISMATCH or ARM_MATH_SUCCESS based on the outcome of size checking. */ arm_status arm_mat_mult_q31( const arm_matrix_instance_q31 * pSrcA, const arm_matrix_instance_q31 * pSrcB, arm_matrix_instance_q31 * pDst); /** * @brief Q31 matrix multiplication (fast variant) for Cortex-M3 and Cortex-M4 * @param[in] *pSrcA points to the first input matrix structure * @param[in] *pSrcB points to the second input matrix structure * @param[out] *pDst points to output matrix structure * @return The function returns either * ARM_MATH_SIZE_MISMATCH or ARM_MATH_SUCCESS based on the outcome of size checking. */ arm_status arm_mat_mult_fast_q31( const arm_matrix_instance_q31 * pSrcA, const arm_matrix_instance_q31 * pSrcB, arm_matrix_instance_q31 * pDst); /** * @brief Floating-point matrix subtraction * @param[in] *pSrcA points to the first input matrix structure * @param[in] *pSrcB points to the second input matrix structure * @param[out] *pDst points to output matrix structure * @return The function returns either * ARM_MATH_SIZE_MISMATCH or ARM_MATH_SUCCESS based on the outcome of size checking. */ arm_status arm_mat_sub_f32( const arm_matrix_instance_f32 * pSrcA, const arm_matrix_instance_f32 * pSrcB, arm_matrix_instance_f32 * pDst); /** * @brief Q15 matrix subtraction * @param[in] *pSrcA points to the first input matrix structure * @param[in] *pSrcB points to the second input matrix structure * @param[out] *pDst points to output matrix structure * @return The function returns either * ARM_MATH_SIZE_MISMATCH or ARM_MATH_SUCCESS based on the outcome of size checking. */ arm_status arm_mat_sub_q15( const arm_matrix_instance_q15 * pSrcA, const arm_matrix_instance_q15 * pSrcB, arm_matrix_instance_q15 * pDst); /** * @brief Q31 matrix subtraction * @param[in] *pSrcA points to the first input matrix structure * @param[in] *pSrcB points to the second input matrix structure * @param[out] *pDst points to output matrix structure * @return The function returns either * ARM_MATH_SIZE_MISMATCH or ARM_MATH_SUCCESS based on the outcome of size checking. */ arm_status arm_mat_sub_q31( const arm_matrix_instance_q31 * pSrcA, const arm_matrix_instance_q31 * pSrcB, arm_matrix_instance_q31 * pDst); /** * @brief Floating-point matrix scaling. * @param[in] *pSrc points to the input matrix * @param[in] scale scale factor * @param[out] *pDst points to the output matrix * @return The function returns either * ARM_MATH_SIZE_MISMATCH or ARM_MATH_SUCCESS based on the outcome of size checking. */ arm_status arm_mat_scale_f32( const arm_matrix_instance_f32 * pSrc, float32_t scale, arm_matrix_instance_f32 * pDst); /** * @brief Q15 matrix scaling. * @param[in] *pSrc points to input matrix * @param[in] scaleFract fractional portion of the scale factor * @param[in] shift number of bits to shift the result by * @param[out] *pDst points to output matrix * @return The function returns either * ARM_MATH_SIZE_MISMATCH or ARM_MATH_SUCCESS based on the outcome of size checking. */ arm_status arm_mat_scale_q15( const arm_matrix_instance_q15 * pSrc, q15_t scaleFract, int32_t shift, arm_matrix_instance_q15 * pDst); /** * @brief Q31 matrix scaling. * @param[in] *pSrc points to input matrix * @param[in] scaleFract fractional portion of the scale factor * @param[in] shift number of bits to shift the result by * @param[out] *pDst points to output matrix structure * @return The function returns either * ARM_MATH_SIZE_MISMATCH or ARM_MATH_SUCCESS based on the outcome of size checking. */ arm_status arm_mat_scale_q31( const arm_matrix_instance_q31 * pSrc, q31_t scaleFract, int32_t shift, arm_matrix_instance_q31 * pDst); /** * @brief Q31 matrix initialization. * @param[in,out] *S points to an instance of the floating-point matrix structure. * @param[in] nRows number of rows in the matrix. * @param[in] nColumns number of columns in the matrix. * @param[in] *pData points to the matrix data array. * @return none */ void arm_mat_init_q31( arm_matrix_instance_q31 * S, uint16_t nRows, uint16_t nColumns, q31_t * pData); /** * @brief Q15 matrix initialization. * @param[in,out] *S points to an instance of the floating-point matrix structure. * @param[in] nRows number of rows in the matrix. * @param[in] nColumns number of columns in the matrix. * @param[in] *pData points to the matrix data array. * @return none */ void arm_mat_init_q15( arm_matrix_instance_q15 * S, uint16_t nRows, uint16_t nColumns, q15_t * pData); /** * @brief Floating-point matrix initialization. * @param[in,out] *S points to an instance of the floating-point matrix structure. * @param[in] nRows number of rows in the matrix. * @param[in] nColumns number of columns in the matrix. * @param[in] *pData points to the matrix data array. * @return none */ void arm_mat_init_f32( arm_matrix_instance_f32 * S, uint16_t nRows, uint16_t nColumns, float32_t * pData); /** * @brief Instance structure for the Q15 PID Control. */ typedef struct { q15_t A0; /**< The derived gain, A0 = Kp + Ki + Kd . */ #ifdef ARM_MATH_CM0_FAMILY q15_t A1; q15_t A2; #else q31_t A1; /**< The derived gain A1 = -Kp - 2Kd | Kd.*/ #endif q15_t state[3]; /**< The state array of length 3. */ q15_t Kp; /**< The proportional gain. */ q15_t Ki; /**< The integral gain. */ q15_t Kd; /**< The derivative gain. */ } arm_pid_instance_q15; /** * @brief Instance structure for the Q31 PID Control. */ typedef struct { q31_t A0; /**< The derived gain, A0 = Kp + Ki + Kd . */ q31_t A1; /**< The derived gain, A1 = -Kp - 2Kd. */ q31_t A2; /**< The derived gain, A2 = Kd . */ q31_t state[3]; /**< The state array of length 3. */ q31_t Kp; /**< The proportional gain. */ q31_t Ki; /**< The integral gain. */ q31_t Kd; /**< The derivative gain. */ } arm_pid_instance_q31; /** * @brief Instance structure for the floating-point PID Control. */ typedef struct { float32_t A0; /**< The derived gain, A0 = Kp + Ki + Kd . */ float32_t A1; /**< The derived gain, A1 = -Kp - 2Kd. */ float32_t A2; /**< The derived gain, A2 = Kd . */ float32_t state[3]; /**< The state array of length 3. */ float32_t Kp; /**< The proportional gain. */ float32_t Ki; /**< The integral gain. */ float32_t Kd; /**< The derivative gain. */ } arm_pid_instance_f32; /** * @brief Initialization function for the floating-point PID Control. * @param[in,out] *S points to an instance of the PID structure. * @param[in] resetStateFlag flag to reset the state. 0 = no change in state 1 = reset the state. * @return none. */ void arm_pid_init_f32( arm_pid_instance_f32 * S, int32_t resetStateFlag); /** * @brief Reset function for the floating-point PID Control. * @param[in,out] *S is an instance of the floating-point PID Control structure * @return none */ void arm_pid_reset_f32( arm_pid_instance_f32 * S); /** * @brief Initialization function for the Q31 PID Control. * @param[in,out] *S points to an instance of the Q15 PID structure. * @param[in] resetStateFlag flag to reset the state. 0 = no change in state 1 = reset the state. * @return none. */ void arm_pid_init_q31( arm_pid_instance_q31 * S, int32_t resetStateFlag); /** * @brief Reset function for the Q31 PID Control. * @param[in,out] *S points to an instance of the Q31 PID Control structure * @return none */ void arm_pid_reset_q31( arm_pid_instance_q31 * S); /** * @brief Initialization function for the Q15 PID Control. * @param[in,out] *S points to an instance of the Q15 PID structure. * @param[in] resetStateFlag flag to reset the state. 0 = no change in state 1 = reset the state. * @return none. */ void arm_pid_init_q15( arm_pid_instance_q15 * S, int32_t resetStateFlag); /** * @brief Reset function for the Q15 PID Control. * @param[in,out] *S points to an instance of the q15 PID Control structure * @return none */ void arm_pid_reset_q15( arm_pid_instance_q15 * S); /** * @brief Instance structure for the floating-point Linear Interpolate function. */ typedef struct { uint32_t nValues; /**< nValues */ float32_t x1; /**< x1 */ float32_t xSpacing; /**< xSpacing */ float32_t *pYData; /**< pointer to the table of Y values */ } arm_linear_interp_instance_f32; /** * @brief Instance structure for the floating-point bilinear interpolation function. */ typedef struct { uint16_t numRows; /**< number of rows in the data table. */ uint16_t numCols; /**< number of columns in the data table. */ float32_t *pData; /**< points to the data table. */ } arm_bilinear_interp_instance_f32; /** * @brief Instance structure for the Q31 bilinear interpolation function. */ typedef struct { uint16_t numRows; /**< number of rows in the data table. */ uint16_t numCols; /**< number of columns in the data table. */ q31_t *pData; /**< points to the data table. */ } arm_bilinear_interp_instance_q31; /** * @brief Instance structure for the Q15 bilinear interpolation function. */ typedef struct { uint16_t numRows; /**< number of rows in the data table. */ uint16_t numCols; /**< number of columns in the data table. */ q15_t *pData; /**< points to the data table. */ } arm_bilinear_interp_instance_q15; /** * @brief Instance structure for the Q15 bilinear interpolation function. */ typedef struct { uint16_t numRows; /**< number of rows in the data table. */ uint16_t numCols; /**< number of columns in the data table. */ q7_t *pData; /**< points to the data table. */ } arm_bilinear_interp_instance_q7; /** * @brief Q7 vector multiplication. * @param[in] *pSrcA points to the first input vector * @param[in] *pSrcB points to the second input vector * @param[out] *pDst points to the output vector * @param[in] blockSize number of samples in each vector * @return none. */ void arm_mult_q7( q7_t * pSrcA, q7_t * pSrcB, q7_t * pDst, uint32_t blockSize); /** * @brief Q15 vector multiplication. * @param[in] *pSrcA points to the first input vector * @param[in] *pSrcB points to the second input vector * @param[out] *pDst points to the output vector * @param[in] blockSize number of samples in each vector * @return none. */ void arm_mult_q15( q15_t * pSrcA, q15_t * pSrcB, q15_t * pDst, uint32_t blockSize); /** * @brief Q31 vector multiplication. * @param[in] *pSrcA points to the first input vector * @param[in] *pSrcB points to the second input vector * @param[out] *pDst points to the output vector * @param[in] blockSize number of samples in each vector * @return none. */ void arm_mult_q31( q31_t * pSrcA, q31_t * pSrcB, q31_t * pDst, uint32_t blockSize); /** * @brief Floating-point vector multiplication. * @param[in] *pSrcA points to the first input vector * @param[in] *pSrcB points to the second input vector * @param[out] *pDst points to the output vector * @param[in] blockSize number of samples in each vector * @return none. */ void arm_mult_f32( float32_t * pSrcA, float32_t * pSrcB, float32_t * pDst, uint32_t blockSize); /** * @brief Instance structure for the Q15 CFFT/CIFFT function. */ typedef struct { uint16_t fftLen; /**< length of the FFT. */ uint8_t ifftFlag; /**< flag that selects forward (ifftFlag=0) or inverse (ifftFlag=1) transform. */ uint8_t bitReverseFlag; /**< flag that enables (bitReverseFlag=1) or disables (bitReverseFlag=0) bit reversal of output. */ q15_t *pTwiddle; /**< points to the Sin twiddle factor table. */ uint16_t *pBitRevTable; /**< points to the bit reversal table. */ uint16_t twidCoefModifier; /**< twiddle coefficient modifier that supports different size FFTs with the same twiddle factor table. */ uint16_t bitRevFactor; /**< bit reversal modifier that supports different size FFTs with the same bit reversal table. */ } arm_cfft_radix2_instance_q15; /* Deprecated */ arm_status arm_cfft_radix2_init_q15( arm_cfft_radix2_instance_q15 * S, uint16_t fftLen, uint8_t ifftFlag, uint8_t bitReverseFlag); /* Deprecated */ void arm_cfft_radix2_q15( const arm_cfft_radix2_instance_q15 * S, q15_t * pSrc); /** * @brief Instance structure for the Q15 CFFT/CIFFT function. */ typedef struct { uint16_t fftLen; /**< length of the FFT. */ uint8_t ifftFlag; /**< flag that selects forward (ifftFlag=0) or inverse (ifftFlag=1) transform. */ uint8_t bitReverseFlag; /**< flag that enables (bitReverseFlag=1) or disables (bitReverseFlag=0) bit reversal of output. */ q15_t *pTwiddle; /**< points to the twiddle factor table. */ uint16_t *pBitRevTable; /**< points to the bit reversal table. */ uint16_t twidCoefModifier; /**< twiddle coefficient modifier that supports different size FFTs with the same twiddle factor table. */ uint16_t bitRevFactor; /**< bit reversal modifier that supports different size FFTs with the same bit reversal table. */ } arm_cfft_radix4_instance_q15; /* Deprecated */ arm_status arm_cfft_radix4_init_q15( arm_cfft_radix4_instance_q15 * S, uint16_t fftLen, uint8_t ifftFlag, uint8_t bitReverseFlag); /* Deprecated */ void arm_cfft_radix4_q15( const arm_cfft_radix4_instance_q15 * S, q15_t * pSrc); /** * @brief Instance structure for the Radix-2 Q31 CFFT/CIFFT function. */ typedef struct { uint16_t fftLen; /**< length of the FFT. */ uint8_t ifftFlag; /**< flag that selects forward (ifftFlag=0) or inverse (ifftFlag=1) transform. */ uint8_t bitReverseFlag; /**< flag that enables (bitReverseFlag=1) or disables (bitReverseFlag=0) bit reversal of output. */ q31_t *pTwiddle; /**< points to the Twiddle factor table. */ uint16_t *pBitRevTable; /**< points to the bit reversal table. */ uint16_t twidCoefModifier; /**< twiddle coefficient modifier that supports different size FFTs with the same twiddle factor table. */ uint16_t bitRevFactor; /**< bit reversal modifier that supports different size FFTs with the same bit reversal table. */ } arm_cfft_radix2_instance_q31; /* Deprecated */ arm_status arm_cfft_radix2_init_q31( arm_cfft_radix2_instance_q31 * S, uint16_t fftLen, uint8_t ifftFlag, uint8_t bitReverseFlag); /* Deprecated */ void arm_cfft_radix2_q31( const arm_cfft_radix2_instance_q31 * S, q31_t * pSrc); /** * @brief Instance structure for the Q31 CFFT/CIFFT function. */ typedef struct { uint16_t fftLen; /**< length of the FFT. */ uint8_t ifftFlag; /**< flag that selects forward (ifftFlag=0) or inverse (ifftFlag=1) transform. */ uint8_t bitReverseFlag; /**< flag that enables (bitReverseFlag=1) or disables (bitReverseFlag=0) bit reversal of output. */ q31_t *pTwiddle; /**< points to the twiddle factor table. */ uint16_t *pBitRevTable; /**< points to the bit reversal table. */ uint16_t twidCoefModifier; /**< twiddle coefficient modifier that supports different size FFTs with the same twiddle factor table. */ uint16_t bitRevFactor; /**< bit reversal modifier that supports different size FFTs with the same bit reversal table. */ } arm_cfft_radix4_instance_q31; /* Deprecated */ void arm_cfft_radix4_q31( const arm_cfft_radix4_instance_q31 * S, q31_t * pSrc); /* Deprecated */ arm_status arm_cfft_radix4_init_q31( arm_cfft_radix4_instance_q31 * S, uint16_t fftLen, uint8_t ifftFlag, uint8_t bitReverseFlag); /** * @brief Instance structure for the floating-point CFFT/CIFFT function. */ typedef struct { uint16_t fftLen; /**< length of the FFT. */ uint8_t ifftFlag; /**< flag that selects forward (ifftFlag=0) or inverse (ifftFlag=1) transform. */ uint8_t bitReverseFlag; /**< flag that enables (bitReverseFlag=1) or disables (bitReverseFlag=0) bit reversal of output. */ float32_t *pTwiddle; /**< points to the Twiddle factor table. */ uint16_t *pBitRevTable; /**< points to the bit reversal table. */ uint16_t twidCoefModifier; /**< twiddle coefficient modifier that supports different size FFTs with the same twiddle factor table. */ uint16_t bitRevFactor; /**< bit reversal modifier that supports different size FFTs with the same bit reversal table. */ float32_t onebyfftLen; /**< value of 1/fftLen. */ } arm_cfft_radix2_instance_f32; /* Deprecated */ arm_status arm_cfft_radix2_init_f32( arm_cfft_radix2_instance_f32 * S, uint16_t fftLen, uint8_t ifftFlag, uint8_t bitReverseFlag); /* Deprecated */ void arm_cfft_radix2_f32( const arm_cfft_radix2_instance_f32 * S, float32_t * pSrc); /** * @brief Instance structure for the floating-point CFFT/CIFFT function. */ typedef struct { uint16_t fftLen; /**< length of the FFT. */ uint8_t ifftFlag; /**< flag that selects forward (ifftFlag=0) or inverse (ifftFlag=1) transform. */ uint8_t bitReverseFlag; /**< flag that enables (bitReverseFlag=1) or disables (bitReverseFlag=0) bit reversal of output. */ float32_t *pTwiddle; /**< points to the Twiddle factor table. */ uint16_t *pBitRevTable; /**< points to the bit reversal table. */ uint16_t twidCoefModifier; /**< twiddle coefficient modifier that supports different size FFTs with the same twiddle factor table. */ uint16_t bitRevFactor; /**< bit reversal modifier that supports different size FFTs with the same bit reversal table. */ float32_t onebyfftLen; /**< value of 1/fftLen. */ } arm_cfft_radix4_instance_f32; /* Deprecated */ arm_status arm_cfft_radix4_init_f32( arm_cfft_radix4_instance_f32 * S, uint16_t fftLen, uint8_t ifftFlag, uint8_t bitReverseFlag); /* Deprecated */ void arm_cfft_radix4_f32( const arm_cfft_radix4_instance_f32 * S, float32_t * pSrc); /** * @brief Instance structure for the fixed-point CFFT/CIFFT function. */ typedef struct { uint16_t fftLen; /**< length of the FFT. */ const q15_t *pTwiddle; /**< points to the Twiddle factor table. */ const uint16_t *pBitRevTable; /**< points to the bit reversal table. */ uint16_t bitRevLength; /**< bit reversal table length. */ } arm_cfft_instance_q15; void arm_cfft_q15( const arm_cfft_instance_q15 * S, q15_t * p1, uint8_t ifftFlag, uint8_t bitReverseFlag); /** * @brief Instance structure for the fixed-point CFFT/CIFFT function. */ typedef struct { uint16_t fftLen; /**< length of the FFT. */ const q31_t *pTwiddle; /**< points to the Twiddle factor table. */ const uint16_t *pBitRevTable; /**< points to the bit reversal table. */ uint16_t bitRevLength; /**< bit reversal table length. */ } arm_cfft_instance_q31; void arm_cfft_q31( const arm_cfft_instance_q31 * S, q31_t * p1, uint8_t ifftFlag, uint8_t bitReverseFlag); /** * @brief Instance structure for the floating-point CFFT/CIFFT function. */ typedef struct { uint16_t fftLen; /**< length of the FFT. */ const float32_t *pTwiddle; /**< points to the Twiddle factor table. */ const uint16_t *pBitRevTable; /**< points to the bit reversal table. */ uint16_t bitRevLength; /**< bit reversal table length. */ } arm_cfft_instance_f32; void arm_cfft_f32( const arm_cfft_instance_f32 * S, float32_t * p1, uint8_t ifftFlag, uint8_t bitReverseFlag); /** * @brief Instance structure for the Q15 RFFT/RIFFT function. */ typedef struct { uint32_t fftLenReal; /**< length of the real FFT. */ uint8_t ifftFlagR; /**< flag that selects forward (ifftFlagR=0) or inverse (ifftFlagR=1) transform. */ uint8_t bitReverseFlagR; /**< flag that enables (bitReverseFlagR=1) or disables (bitReverseFlagR=0) bit reversal of output. */ uint32_t twidCoefRModifier; /**< twiddle coefficient modifier that supports different size FFTs with the same twiddle factor table. */ q15_t *pTwiddleAReal; /**< points to the real twiddle factor table. */ q15_t *pTwiddleBReal; /**< points to the imag twiddle factor table. */ const arm_cfft_instance_q15 *pCfft; /**< points to the complex FFT instance. */ } arm_rfft_instance_q15; arm_status arm_rfft_init_q15( arm_rfft_instance_q15 * S, uint32_t fftLenReal, uint32_t ifftFlagR, uint32_t bitReverseFlag); void arm_rfft_q15( const arm_rfft_instance_q15 * S, q15_t * pSrc, q15_t * pDst); /** * @brief Instance structure for the Q31 RFFT/RIFFT function. */ typedef struct { uint32_t fftLenReal; /**< length of the real FFT. */ uint8_t ifftFlagR; /**< flag that selects forward (ifftFlagR=0) or inverse (ifftFlagR=1) transform. */ uint8_t bitReverseFlagR; /**< flag that enables (bitReverseFlagR=1) or disables (bitReverseFlagR=0) bit reversal of output. */ uint32_t twidCoefRModifier; /**< twiddle coefficient modifier that supports different size FFTs with the same twiddle factor table. */ q31_t *pTwiddleAReal; /**< points to the real twiddle factor table. */ q31_t *pTwiddleBReal; /**< points to the imag twiddle factor table. */ const arm_cfft_instance_q31 *pCfft; /**< points to the complex FFT instance. */ } arm_rfft_instance_q31; arm_status arm_rfft_init_q31( arm_rfft_instance_q31 * S, uint32_t fftLenReal, uint32_t ifftFlagR, uint32_t bitReverseFlag); void arm_rfft_q31( const arm_rfft_instance_q31 * S, q31_t * pSrc, q31_t * pDst); /** * @brief Instance structure for the floating-point RFFT/RIFFT function. */ typedef struct { uint32_t fftLenReal; /**< length of the real FFT. */ uint16_t fftLenBy2; /**< length of the complex FFT. */ uint8_t ifftFlagR; /**< flag that selects forward (ifftFlagR=0) or inverse (ifftFlagR=1) transform. */ uint8_t bitReverseFlagR; /**< flag that enables (bitReverseFlagR=1) or disables (bitReverseFlagR=0) bit reversal of output. */ uint32_t twidCoefRModifier; /**< twiddle coefficient modifier that supports different size FFTs with the same twiddle factor table. */ float32_t *pTwiddleAReal; /**< points to the real twiddle factor table. */ float32_t *pTwiddleBReal; /**< points to the imag twiddle factor table. */ arm_cfft_radix4_instance_f32 *pCfft; /**< points to the complex FFT instance. */ } arm_rfft_instance_f32; arm_status arm_rfft_init_f32( arm_rfft_instance_f32 * S, arm_cfft_radix4_instance_f32 * S_CFFT, uint32_t fftLenReal, uint32_t ifftFlagR, uint32_t bitReverseFlag); void arm_rfft_f32( const arm_rfft_instance_f32 * S, float32_t * pSrc, float32_t * pDst); /** * @brief Instance structure for the floating-point RFFT/RIFFT function. */ typedef struct { arm_cfft_instance_f32 Sint; /**< Internal CFFT structure. */ uint16_t fftLenRFFT; /**< length of the real sequence */ float32_t * pTwiddleRFFT; /**< Twiddle factors real stage */ } arm_rfft_fast_instance_f32 ; arm_status arm_rfft_fast_init_f32 ( arm_rfft_fast_instance_f32 * S, uint16_t fftLen); void arm_rfft_fast_f32( arm_rfft_fast_instance_f32 * S, float32_t * p, float32_t * pOut, uint8_t ifftFlag); /** * @brief Instance structure for the floating-point DCT4/IDCT4 function. */ typedef struct { uint16_t N; /**< length of the DCT4. */ uint16_t Nby2; /**< half of the length of the DCT4. */ float32_t normalize; /**< normalizing factor. */ float32_t *pTwiddle; /**< points to the twiddle factor table. */ float32_t *pCosFactor; /**< points to the cosFactor table. */ arm_rfft_instance_f32 *pRfft; /**< points to the real FFT instance. */ arm_cfft_radix4_instance_f32 *pCfft; /**< points to the complex FFT instance. */ } arm_dct4_instance_f32; /** * @brief Initialization function for the floating-point DCT4/IDCT4. * @param[in,out] *S points to an instance of floating-point DCT4/IDCT4 structure. * @param[in] *S_RFFT points to an instance of floating-point RFFT/RIFFT structure. * @param[in] *S_CFFT points to an instance of floating-point CFFT/CIFFT structure. * @param[in] N length of the DCT4. * @param[in] Nby2 half of the length of the DCT4. * @param[in] normalize normalizing factor. * @return arm_status function returns ARM_MATH_SUCCESS if initialization is successful or ARM_MATH_ARGUMENT_ERROR if fftLenReal is not a supported transform length. */ arm_status arm_dct4_init_f32( arm_dct4_instance_f32 * S, arm_rfft_instance_f32 * S_RFFT, arm_cfft_radix4_instance_f32 * S_CFFT, uint16_t N, uint16_t Nby2, float32_t normalize); /** * @brief Processing function for the floating-point DCT4/IDCT4. * @param[in] *S points to an instance of the floating-point DCT4/IDCT4 structure. * @param[in] *pState points to state buffer. * @param[in,out] *pInlineBuffer points to the in-place input and output buffer. * @return none. */ void arm_dct4_f32( const arm_dct4_instance_f32 * S, float32_t * pState, float32_t * pInlineBuffer); /** * @brief Instance structure for the Q31 DCT4/IDCT4 function. */ typedef struct { uint16_t N; /**< length of the DCT4. */ uint16_t Nby2; /**< half of the length of the DCT4. */ q31_t normalize; /**< normalizing factor. */ q31_t *pTwiddle; /**< points to the twiddle factor table. */ q31_t *pCosFactor; /**< points to the cosFactor table. */ arm_rfft_instance_q31 *pRfft; /**< points to the real FFT instance. */ arm_cfft_radix4_instance_q31 *pCfft; /**< points to the complex FFT instance. */ } arm_dct4_instance_q31; /** * @brief Initialization function for the Q31 DCT4/IDCT4. * @param[in,out] *S points to an instance of Q31 DCT4/IDCT4 structure. * @param[in] *S_RFFT points to an instance of Q31 RFFT/RIFFT structure * @param[in] *S_CFFT points to an instance of Q31 CFFT/CIFFT structure * @param[in] N length of the DCT4. * @param[in] Nby2 half of the length of the DCT4. * @param[in] normalize normalizing factor. * @return arm_status function returns ARM_MATH_SUCCESS if initialization is successful or ARM_MATH_ARGUMENT_ERROR if N is not a supported transform length. */ arm_status arm_dct4_init_q31( arm_dct4_instance_q31 * S, arm_rfft_instance_q31 * S_RFFT, arm_cfft_radix4_instance_q31 * S_CFFT, uint16_t N, uint16_t Nby2, q31_t normalize); /** * @brief Processing function for the Q31 DCT4/IDCT4. * @param[in] *S points to an instance of the Q31 DCT4 structure. * @param[in] *pState points to state buffer. * @param[in,out] *pInlineBuffer points to the in-place input and output buffer. * @return none. */ void arm_dct4_q31( const arm_dct4_instance_q31 * S, q31_t * pState, q31_t * pInlineBuffer); /** * @brief Instance structure for the Q15 DCT4/IDCT4 function. */ typedef struct { uint16_t N; /**< length of the DCT4. */ uint16_t Nby2; /**< half of the length of the DCT4. */ q15_t normalize; /**< normalizing factor. */ q15_t *pTwiddle; /**< points to the twiddle factor table. */ q15_t *pCosFactor; /**< points to the cosFactor table. */ arm_rfft_instance_q15 *pRfft; /**< points to the real FFT instance. */ arm_cfft_radix4_instance_q15 *pCfft; /**< points to the complex FFT instance. */ } arm_dct4_instance_q15; /** * @brief Initialization function for the Q15 DCT4/IDCT4. * @param[in,out] *S points to an instance of Q15 DCT4/IDCT4 structure. * @param[in] *S_RFFT points to an instance of Q15 RFFT/RIFFT structure. * @param[in] *S_CFFT points to an instance of Q15 CFFT/CIFFT structure. * @param[in] N length of the DCT4. * @param[in] Nby2 half of the length of the DCT4. * @param[in] normalize normalizing factor. * @return arm_status function returns ARM_MATH_SUCCESS if initialization is successful or ARM_MATH_ARGUMENT_ERROR if N is not a supported transform length. */ arm_status arm_dct4_init_q15( arm_dct4_instance_q15 * S, arm_rfft_instance_q15 * S_RFFT, arm_cfft_radix4_instance_q15 * S_CFFT, uint16_t N, uint16_t Nby2, q15_t normalize); /** * @brief Processing function for the Q15 DCT4/IDCT4. * @param[in] *S points to an instance of the Q15 DCT4 structure. * @param[in] *pState points to state buffer. * @param[in,out] *pInlineBuffer points to the in-place input and output buffer. * @return none. */ void arm_dct4_q15( const arm_dct4_instance_q15 * S, q15_t * pState, q15_t * pInlineBuffer); /** * @brief Floating-point vector addition. * @param[in] *pSrcA points to the first input vector * @param[in] *pSrcB points to the second input vector * @param[out] *pDst points to the output vector * @param[in] blockSize number of samples in each vector * @return none. */ void arm_add_f32( float32_t * pSrcA, float32_t * pSrcB, float32_t * pDst, uint32_t blockSize); /** * @brief Q7 vector addition. * @param[in] *pSrcA points to the first input vector * @param[in] *pSrcB points to the second input vector * @param[out] *pDst points to the output vector * @param[in] blockSize number of samples in each vector * @return none. */ void arm_add_q7( q7_t * pSrcA, q7_t * pSrcB, q7_t * pDst, uint32_t blockSize); /** * @brief Q15 vector addition. * @param[in] *pSrcA points to the first input vector * @param[in] *pSrcB points to the second input vector * @param[out] *pDst points to the output vector * @param[in] blockSize number of samples in each vector * @return none. */ void arm_add_q15( q15_t * pSrcA, q15_t * pSrcB, q15_t * pDst, uint32_t blockSize); /** * @brief Q31 vector addition. * @param[in] *pSrcA points to the first input vector * @param[in] *pSrcB points to the second input vector * @param[out] *pDst points to the output vector * @param[in] blockSize number of samples in each vector * @return none. */ void arm_add_q31( q31_t * pSrcA, q31_t * pSrcB, q31_t * pDst, uint32_t blockSize); /** * @brief Floating-point vector subtraction. * @param[in] *pSrcA points to the first input vector * @param[in] *pSrcB points to the second input vector * @param[out] *pDst points to the output vector * @param[in] blockSize number of samples in each vector * @return none. */ void arm_sub_f32( float32_t * pSrcA, float32_t * pSrcB, float32_t * pDst, uint32_t blockSize); /** * @brief Q7 vector subtraction. * @param[in] *pSrcA points to the first input vector * @param[in] *pSrcB points to the second input vector * @param[out] *pDst points to the output vector * @param[in] blockSize number of samples in each vector * @return none. */ void arm_sub_q7( q7_t * pSrcA, q7_t * pSrcB, q7_t * pDst, uint32_t blockSize); /** * @brief Q15 vector subtraction. * @param[in] *pSrcA points to the first input vector * @param[in] *pSrcB points to the second input vector * @param[out] *pDst points to the output vector * @param[in] blockSize number of samples in each vector * @return none. */ void arm_sub_q15( q15_t * pSrcA, q15_t * pSrcB, q15_t * pDst, uint32_t blockSize); /** * @brief Q31 vector subtraction. * @param[in] *pSrcA points to the first input vector * @param[in] *pSrcB points to the second input vector * @param[out] *pDst points to the output vector * @param[in] blockSize number of samples in each vector * @return none. */ void arm_sub_q31( q31_t * pSrcA, q31_t * pSrcB, q31_t * pDst, uint32_t blockSize); /** * @brief Multiplies a floating-point vector by a scalar. * @param[in] *pSrc points to the input vector * @param[in] scale scale factor to be applied * @param[out] *pDst points to the output vector * @param[in] blockSize number of samples in the vector * @return none. */ void arm_scale_f32( float32_t * pSrc, float32_t scale, float32_t * pDst, uint32_t blockSize); /** * @brief Multiplies a Q7 vector by a scalar. * @param[in] *pSrc points to the input vector * @param[in] scaleFract fractional portion of the scale value * @param[in] shift number of bits to shift the result by * @param[out] *pDst points to the output vector * @param[in] blockSize number of samples in the vector * @return none. */ void arm_scale_q7( q7_t * pSrc, q7_t scaleFract, int8_t shift, q7_t * pDst, uint32_t blockSize); /** * @brief Multiplies a Q15 vector by a scalar. * @param[in] *pSrc points to the input vector * @param[in] scaleFract fractional portion of the scale value * @param[in] shift number of bits to shift the result by * @param[out] *pDst points to the output vector * @param[in] blockSize number of samples in the vector * @return none. */ void arm_scale_q15( q15_t * pSrc, q15_t scaleFract, int8_t shift, q15_t * pDst, uint32_t blockSize); /** * @brief Multiplies a Q31 vector by a scalar. * @param[in] *pSrc points to the input vector * @param[in] scaleFract fractional portion of the scale value * @param[in] shift number of bits to shift the result by * @param[out] *pDst points to the output vector * @param[in] blockSize number of samples in the vector * @return none. */ void arm_scale_q31( q31_t * pSrc, q31_t scaleFract, int8_t shift, q31_t * pDst, uint32_t blockSize); /** * @brief Q7 vector absolute value. * @param[in] *pSrc points to the input buffer * @param[out] *pDst points to the output buffer * @param[in] blockSize number of samples in each vector * @return none. */ void arm_abs_q7( q7_t * pSrc, q7_t * pDst, uint32_t blockSize); /** * @brief Floating-point vector absolute value. * @param[in] *pSrc points to the input buffer * @param[out] *pDst points to the output buffer * @param[in] blockSize number of samples in each vector * @return none. */ void arm_abs_f32( float32_t * pSrc, float32_t * pDst, uint32_t blockSize); /** * @brief Q15 vector absolute value. * @param[in] *pSrc points to the input buffer * @param[out] *pDst points to the output buffer * @param[in] blockSize number of samples in each vector * @return none. */ void arm_abs_q15( q15_t * pSrc, q15_t * pDst, uint32_t blockSize); /** * @brief Q31 vector absolute value. * @param[in] *pSrc points to the input buffer * @param[out] *pDst points to the output buffer * @param[in] blockSize number of samples in each vector * @return none. */ void arm_abs_q31( q31_t * pSrc, q31_t * pDst, uint32_t blockSize); /** * @brief Dot product of floating-point vectors. * @param[in] *pSrcA points to the first input vector * @param[in] *pSrcB points to the second input vector * @param[in] blockSize number of samples in each vector * @param[out] *result output result returned here * @return none. */ void arm_dot_prod_f32( float32_t * pSrcA, float32_t * pSrcB, uint32_t blockSize, float32_t * result); /** * @brief Dot product of Q7 vectors. * @param[in] *pSrcA points to the first input vector * @param[in] *pSrcB points to the second input vector * @param[in] blockSize number of samples in each vector * @param[out] *result output result returned here * @return none. */ void arm_dot_prod_q7( q7_t * pSrcA, q7_t * pSrcB, uint32_t blockSize, q31_t * result); /** * @brief Dot product of Q15 vectors. * @param[in] *pSrcA points to the first input vector * @param[in] *pSrcB points to the second input vector * @param[in] blockSize number of samples in each vector * @param[out] *result output result returned here * @return none. */ void arm_dot_prod_q15( q15_t * pSrcA, q15_t * pSrcB, uint32_t blockSize, q63_t * result); /** * @brief Dot product of Q31 vectors. * @param[in] *pSrcA points to the first input vector * @param[in] *pSrcB points to the second input vector * @param[in] blockSize number of samples in each vector * @param[out] *result output result returned here * @return none. */ void arm_dot_prod_q31( q31_t * pSrcA, q31_t * pSrcB, uint32_t blockSize, q63_t * result); /** * @brief Shifts the elements of a Q7 vector a specified number of bits. * @param[in] *pSrc points to the input vector * @param[in] shiftBits number of bits to shift. A positive value shifts left; a negative value shifts right. * @param[out] *pDst points to the output vector * @param[in] blockSize number of samples in the vector * @return none. */ void arm_shift_q7( q7_t * pSrc, int8_t shiftBits, q7_t * pDst, uint32_t blockSize); /** * @brief Shifts the elements of a Q15 vector a specified number of bits. * @param[in] *pSrc points to the input vector * @param[in] shiftBits number of bits to shift. A positive value shifts left; a negative value shifts right. * @param[out] *pDst points to the output vector * @param[in] blockSize number of samples in the vector * @return none. */ void arm_shift_q15( q15_t * pSrc, int8_t shiftBits, q15_t * pDst, uint32_t blockSize); /** * @brief Shifts the elements of a Q31 vector a specified number of bits. * @param[in] *pSrc points to the input vector * @param[in] shiftBits number of bits to shift. A positive value shifts left; a negative value shifts right. * @param[out] *pDst points to the output vector * @param[in] blockSize number of samples in the vector * @return none. */ void arm_shift_q31( q31_t * pSrc, int8_t shiftBits, q31_t * pDst, uint32_t blockSize); /** * @brief Adds a constant offset to a floating-point vector. * @param[in] *pSrc points to the input vector * @param[in] offset is the offset to be added * @param[out] *pDst points to the output vector * @param[in] blockSize number of samples in the vector * @return none. */ void arm_offset_f32( float32_t * pSrc, float32_t offset, float32_t * pDst, uint32_t blockSize); /** * @brief Adds a constant offset to a Q7 vector. * @param[in] *pSrc points to the input vector * @param[in] offset is the offset to be added * @param[out] *pDst points to the output vector * @param[in] blockSize number of samples in the vector * @return none. */ void arm_offset_q7( q7_t * pSrc, q7_t offset, q7_t * pDst, uint32_t blockSize); /** * @brief Adds a constant offset to a Q15 vector. * @param[in] *pSrc points to the input vector * @param[in] offset is the offset to be added * @param[out] *pDst points to the output vector * @param[in] blockSize number of samples in the vector * @return none. */ void arm_offset_q15( q15_t * pSrc, q15_t offset, q15_t * pDst, uint32_t blockSize); /** * @brief Adds a constant offset to a Q31 vector. * @param[in] *pSrc points to the input vector * @param[in] offset is the offset to be added * @param[out] *pDst points to the output vector * @param[in] blockSize number of samples in the vector * @return none. */ void arm_offset_q31( q31_t * pSrc, q31_t offset, q31_t * pDst, uint32_t blockSize); /** * @brief Negates the elements of a floating-point vector. * @param[in] *pSrc points to the input vector * @param[out] *pDst points to the output vector * @param[in] blockSize number of samples in the vector * @return none. */ void arm_negate_f32( float32_t * pSrc, float32_t * pDst, uint32_t blockSize); /** * @brief Negates the elements of a Q7 vector. * @param[in] *pSrc points to the input vector * @param[out] *pDst points to the output vector * @param[in] blockSize number of samples in the vector * @return none. */ void arm_negate_q7( q7_t * pSrc, q7_t * pDst, uint32_t blockSize); /** * @brief Negates the elements of a Q15 vector. * @param[in] *pSrc points to the input vector * @param[out] *pDst points to the output vector * @param[in] blockSize number of samples in the vector * @return none. */ void arm_negate_q15( q15_t * pSrc, q15_t * pDst, uint32_t blockSize); /** * @brief Negates the elements of a Q31 vector. * @param[in] *pSrc points to the input vector * @param[out] *pDst points to the output vector * @param[in] blockSize number of samples in the vector * @return none. */ void arm_negate_q31( q31_t * pSrc, q31_t * pDst, uint32_t blockSize); /** * @brief Copies the elements of a floating-point vector. * @param[in] *pSrc input pointer * @param[out] *pDst output pointer * @param[in] blockSize number of samples to process * @return none. */ void arm_copy_f32( float32_t * pSrc, float32_t * pDst, uint32_t blockSize); /** * @brief Copies the elements of a Q7 vector. * @param[in] *pSrc input pointer * @param[out] *pDst output pointer * @param[in] blockSize number of samples to process * @return none. */ void arm_copy_q7( q7_t * pSrc, q7_t * pDst, uint32_t blockSize); /** * @brief Copies the elements of a Q15 vector. * @param[in] *pSrc input pointer * @param[out] *pDst output pointer * @param[in] blockSize number of samples to process * @return none. */ void arm_copy_q15( q15_t * pSrc, q15_t * pDst, uint32_t blockSize); /** * @brief Copies the elements of a Q31 vector. * @param[in] *pSrc input pointer * @param[out] *pDst output pointer * @param[in] blockSize number of samples to process * @return none. */ void arm_copy_q31( q31_t * pSrc, q31_t * pDst, uint32_t blockSize); /** * @brief Fills a constant value into a floating-point vector. * @param[in] value input value to be filled * @param[out] *pDst output pointer * @param[in] blockSize number of samples to process * @return none. */ void arm_fill_f32( float32_t value, float32_t * pDst, uint32_t blockSize); /** * @brief Fills a constant value into a Q7 vector. * @param[in] value input value to be filled * @param[out] *pDst output pointer * @param[in] blockSize number of samples to process * @return none. */ void arm_fill_q7( q7_t value, q7_t * pDst, uint32_t blockSize); /** * @brief Fills a constant value into a Q15 vector. * @param[in] value input value to be filled * @param[out] *pDst output pointer * @param[in] blockSize number of samples to process * @return none. */ void arm_fill_q15( q15_t value, q15_t * pDst, uint32_t blockSize); /** * @brief Fills a constant value into a Q31 vector. * @param[in] value input value to be filled * @param[out] *pDst output pointer * @param[in] blockSize number of samples to process * @return none. */ void arm_fill_q31( q31_t value, q31_t * pDst, uint32_t blockSize); /** * @brief Convolution of floating-point sequences. * @param[in] *pSrcA points to the first input sequence. * @param[in] srcALen length of the first input sequence. * @param[in] *pSrcB points to the second input sequence. * @param[in] srcBLen length of the second input sequence. * @param[out] *pDst points to the location where the output result is written. Length srcALen+srcBLen-1. * @return none. */ void arm_conv_f32( float32_t * pSrcA, uint32_t srcALen, float32_t * pSrcB, uint32_t srcBLen, float32_t * pDst); /** * @brief Convolution of Q15 sequences. * @param[in] *pSrcA points to the first input sequence. * @param[in] srcALen length of the first input sequence. * @param[in] *pSrcB points to the second input sequence. * @param[in] srcBLen length of the second input sequence. * @param[out] *pDst points to the block of output data Length srcALen+srcBLen-1. * @param[in] *pScratch1 points to scratch buffer of size max(srcALen, srcBLen) + 2*min(srcALen, srcBLen) - 2. * @param[in] *pScratch2 points to scratch buffer of size min(srcALen, srcBLen). * @return none. */ void arm_conv_opt_q15( q15_t * pSrcA, uint32_t srcALen, q15_t * pSrcB, uint32_t srcBLen, q15_t * pDst, q15_t * pScratch1, q15_t * pScratch2); /** * @brief Convolution of Q15 sequences. * @param[in] *pSrcA points to the first input sequence. * @param[in] srcALen length of the first input sequence. * @param[in] *pSrcB points to the second input sequence. * @param[in] srcBLen length of the second input sequence. * @param[out] *pDst points to the location where the output result is written. Length srcALen+srcBLen-1. * @return none. */ void arm_conv_q15( q15_t * pSrcA, uint32_t srcALen, q15_t * pSrcB, uint32_t srcBLen, q15_t * pDst); /** * @brief Convolution of Q15 sequences (fast version) for Cortex-M3 and Cortex-M4 * @param[in] *pSrcA points to the first input sequence. * @param[in] srcALen length of the first input sequence. * @param[in] *pSrcB points to the second input sequence. * @param[in] srcBLen length of the second input sequence. * @param[out] *pDst points to the block of output data Length srcALen+srcBLen-1. * @return none. */ void arm_conv_fast_q15( q15_t * pSrcA, uint32_t srcALen, q15_t * pSrcB, uint32_t srcBLen, q15_t * pDst); /** * @brief Convolution of Q15 sequences (fast version) for Cortex-M3 and Cortex-M4 * @param[in] *pSrcA points to the first input sequence. * @param[in] srcALen length of the first input sequence. * @param[in] *pSrcB points to the second input sequence. * @param[in] srcBLen length of the second input sequence. * @param[out] *pDst points to the block of output data Length srcALen+srcBLen-1. * @param[in] *pScratch1 points to scratch buffer of size max(srcALen, srcBLen) + 2*min(srcALen, srcBLen) - 2. * @param[in] *pScratch2 points to scratch buffer of size min(srcALen, srcBLen). * @return none. */ void arm_conv_fast_opt_q15( q15_t * pSrcA, uint32_t srcALen, q15_t * pSrcB, uint32_t srcBLen, q15_t * pDst, q15_t * pScratch1, q15_t * pScratch2); /** * @brief Convolution of Q31 sequences. * @param[in] *pSrcA points to the first input sequence. * @param[in] srcALen length of the first input sequence. * @param[in] *pSrcB points to the second input sequence. * @param[in] srcBLen length of the second input sequence. * @param[out] *pDst points to the block of output data Length srcALen+srcBLen-1. * @return none. */ void arm_conv_q31( q31_t * pSrcA, uint32_t srcALen, q31_t * pSrcB, uint32_t srcBLen, q31_t * pDst); /** * @brief Convolution of Q31 sequences (fast version) for Cortex-M3 and Cortex-M4 * @param[in] *pSrcA points to the first input sequence. * @param[in] srcALen length of the first input sequence. * @param[in] *pSrcB points to the second input sequence. * @param[in] srcBLen length of the second input sequence. * @param[out] *pDst points to the block of output data Length srcALen+srcBLen-1. * @return none. */ void arm_conv_fast_q31( q31_t * pSrcA, uint32_t srcALen, q31_t * pSrcB, uint32_t srcBLen, q31_t * pDst); /** * @brief Convolution of Q7 sequences. * @param[in] *pSrcA points to the first input sequence. * @param[in] srcALen length of the first input sequence. * @param[in] *pSrcB points to the second input sequence. * @param[in] srcBLen length of the second input sequence. * @param[out] *pDst points to the block of output data Length srcALen+srcBLen-1. * @param[in] *pScratch1 points to scratch buffer(of type q15_t) of size max(srcALen, srcBLen) + 2*min(srcALen, srcBLen) - 2. * @param[in] *pScratch2 points to scratch buffer (of type q15_t) of size min(srcALen, srcBLen). * @return none. */ void arm_conv_opt_q7( q7_t * pSrcA, uint32_t srcALen, q7_t * pSrcB, uint32_t srcBLen, q7_t * pDst, q15_t * pScratch1, q15_t * pScratch2); /** * @brief Convolution of Q7 sequences. * @param[in] *pSrcA points to the first input sequence. * @param[in] srcALen length of the first input sequence. * @param[in] *pSrcB points to the second input sequence. * @param[in] srcBLen length of the second input sequence. * @param[out] *pDst points to the block of output data Length srcALen+srcBLen-1. * @return none. */ void arm_conv_q7( q7_t * pSrcA, uint32_t srcALen, q7_t * pSrcB, uint32_t srcBLen, q7_t * pDst); /** * @brief Partial convolution of floating-point sequences. * @param[in] *pSrcA points to the first input sequence. * @param[in] srcALen length of the first input sequence. * @param[in] *pSrcB points to the second input sequence. * @param[in] srcBLen length of the second input sequence. * @param[out] *pDst points to the block of output data * @param[in] firstIndex is the first output sample to start with. * @param[in] numPoints is the number of output points to be computed. * @return Returns either ARM_MATH_SUCCESS if the function completed correctly or ARM_MATH_ARGUMENT_ERROR if the requested subset is not in the range [0 srcALen+srcBLen-2]. */ arm_status arm_conv_partial_f32( float32_t * pSrcA, uint32_t srcALen, float32_t * pSrcB, uint32_t srcBLen, float32_t * pDst, uint32_t firstIndex, uint32_t numPoints); /** * @brief Partial convolution of Q15 sequences. * @param[in] *pSrcA points to the first input sequence. * @param[in] srcALen length of the first input sequence. * @param[in] *pSrcB points to the second input sequence. * @param[in] srcBLen length of the second input sequence. * @param[out] *pDst points to the block of output data * @param[in] firstIndex is the first output sample to start with. * @param[in] numPoints is the number of output points to be computed. * @param[in] * pScratch1 points to scratch buffer of size max(srcALen, srcBLen) + 2*min(srcALen, srcBLen) - 2. * @param[in] * pScratch2 points to scratch buffer of size min(srcALen, srcBLen). * @return Returns either ARM_MATH_SUCCESS if the function completed correctly or ARM_MATH_ARGUMENT_ERROR if the requested subset is not in the range [0 srcALen+srcBLen-2]. */ arm_status arm_conv_partial_opt_q15( q15_t * pSrcA, uint32_t srcALen, q15_t * pSrcB, uint32_t srcBLen, q15_t * pDst, uint32_t firstIndex, uint32_t numPoints, q15_t * pScratch1, q15_t * pScratch2); /** * @brief Partial convolution of Q15 sequences. * @param[in] *pSrcA points to the first input sequence. * @param[in] srcALen length of the first input sequence. * @param[in] *pSrcB points to the second input sequence. * @param[in] srcBLen length of the second input sequence. * @param[out] *pDst points to the block of output data * @param[in] firstIndex is the first output sample to start with. * @param[in] numPoints is the number of output points to be computed. * @return Returns either ARM_MATH_SUCCESS if the function completed correctly or ARM_MATH_ARGUMENT_ERROR if the requested subset is not in the range [0 srcALen+srcBLen-2]. */ arm_status arm_conv_partial_q15( q15_t * pSrcA, uint32_t srcALen, q15_t * pSrcB, uint32_t srcBLen, q15_t * pDst, uint32_t firstIndex, uint32_t numPoints); /** * @brief Partial convolution of Q15 sequences (fast version) for Cortex-M3 and Cortex-M4 * @param[in] *pSrcA points to the first input sequence. * @param[in] srcALen length of the first input sequence. * @param[in] *pSrcB points to the second input sequence. * @param[in] srcBLen length of the second input sequence. * @param[out] *pDst points to the block of output data * @param[in] firstIndex is the first output sample to start with. * @param[in] numPoints is the number of output points to be computed. * @return Returns either ARM_MATH_SUCCESS if the function completed correctly or ARM_MATH_ARGUMENT_ERROR if the requested subset is not in the range [0 srcALen+srcBLen-2]. */ arm_status arm_conv_partial_fast_q15( q15_t * pSrcA, uint32_t srcALen, q15_t * pSrcB, uint32_t srcBLen, q15_t * pDst, uint32_t firstIndex, uint32_t numPoints); /** * @brief Partial convolution of Q15 sequences (fast version) for Cortex-M3 and Cortex-M4 * @param[in] *pSrcA points to the first input sequence. * @param[in] srcALen length of the first input sequence. * @param[in] *pSrcB points to the second input sequence. * @param[in] srcBLen length of the second input sequence. * @param[out] *pDst points to the block of output data * @param[in] firstIndex is the first output sample to start with. * @param[in] numPoints is the number of output points to be computed. * @param[in] * pScratch1 points to scratch buffer of size max(srcALen, srcBLen) + 2*min(srcALen, srcBLen) - 2. * @param[in] * pScratch2 points to scratch buffer of size min(srcALen, srcBLen). * @return Returns either ARM_MATH_SUCCESS if the function completed correctly or ARM_MATH_ARGUMENT_ERROR if the requested subset is not in the range [0 srcALen+srcBLen-2]. */ arm_status arm_conv_partial_fast_opt_q15( q15_t * pSrcA, uint32_t srcALen, q15_t * pSrcB, uint32_t srcBLen, q15_t * pDst, uint32_t firstIndex, uint32_t numPoints, q15_t * pScratch1, q15_t * pScratch2); /** * @brief Partial convolution of Q31 sequences. * @param[in] *pSrcA points to the first input sequence. * @param[in] srcALen length of the first input sequence. * @param[in] *pSrcB points to the second input sequence. * @param[in] srcBLen length of the second input sequence. * @param[out] *pDst points to the block of output data * @param[in] firstIndex is the first output sample to start with. * @param[in] numPoints is the number of output points to be computed. * @return Returns either ARM_MATH_SUCCESS if the function completed correctly or ARM_MATH_ARGUMENT_ERROR if the requested subset is not in the range [0 srcALen+srcBLen-2]. */ arm_status arm_conv_partial_q31( q31_t * pSrcA, uint32_t srcALen, q31_t * pSrcB, uint32_t srcBLen, q31_t * pDst, uint32_t firstIndex, uint32_t numPoints); /** * @brief Partial convolution of Q31 sequences (fast version) for Cortex-M3 and Cortex-M4 * @param[in] *pSrcA points to the first input sequence. * @param[in] srcALen length of the first input sequence. * @param[in] *pSrcB points to the second input sequence. * @param[in] srcBLen length of the second input sequence. * @param[out] *pDst points to the block of output data * @param[in] firstIndex is the first output sample to start with. * @param[in] numPoints is the number of output points to be computed. * @return Returns either ARM_MATH_SUCCESS if the function completed correctly or ARM_MATH_ARGUMENT_ERROR if the requested subset is not in the range [0 srcALen+srcBLen-2]. */ arm_status arm_conv_partial_fast_q31( q31_t * pSrcA, uint32_t srcALen, q31_t * pSrcB, uint32_t srcBLen, q31_t * pDst, uint32_t firstIndex, uint32_t numPoints); /** * @brief Partial convolution of Q7 sequences * @param[in] *pSrcA points to the first input sequence. * @param[in] srcALen length of the first input sequence. * @param[in] *pSrcB points to the second input sequence. * @param[in] srcBLen length of the second input sequence. * @param[out] *pDst points to the block of output data * @param[in] firstIndex is the first output sample to start with. * @param[in] numPoints is the number of output points to be computed. * @param[in] *pScratch1 points to scratch buffer(of type q15_t) of size max(srcALen, srcBLen) + 2*min(srcALen, srcBLen) - 2. * @param[in] *pScratch2 points to scratch buffer (of type q15_t) of size min(srcALen, srcBLen). * @return Returns either ARM_MATH_SUCCESS if the function completed correctly or ARM_MATH_ARGUMENT_ERROR if the requested subset is not in the range [0 srcALen+srcBLen-2]. */ arm_status arm_conv_partial_opt_q7( q7_t * pSrcA, uint32_t srcALen, q7_t * pSrcB, uint32_t srcBLen, q7_t * pDst, uint32_t firstIndex, uint32_t numPoints, q15_t * pScratch1, q15_t * pScratch2); /** * @brief Partial convolution of Q7 sequences. * @param[in] *pSrcA points to the first input sequence. * @param[in] srcALen length of the first input sequence. * @param[in] *pSrcB points to the second input sequence. * @param[in] srcBLen length of the second input sequence. * @param[out] *pDst points to the block of output data * @param[in] firstIndex is the first output sample to start with. * @param[in] numPoints is the number of output points to be computed. * @return Returns either ARM_MATH_SUCCESS if the function completed correctly or ARM_MATH_ARGUMENT_ERROR if the requested subset is not in the range [0 srcALen+srcBLen-2]. */ arm_status arm_conv_partial_q7( q7_t * pSrcA, uint32_t srcALen, q7_t * pSrcB, uint32_t srcBLen, q7_t * pDst, uint32_t firstIndex, uint32_t numPoints); /** * @brief Instance structure for the Q15 FIR decimator. */ typedef struct { uint8_t M; /**< decimation factor. */ uint16_t numTaps; /**< number of coefficients in the filter. */ q15_t *pCoeffs; /**< points to the coefficient array. The array is of length numTaps.*/ q15_t *pState; /**< points to the state variable array. The array is of length numTaps+blockSize-1. */ } arm_fir_decimate_instance_q15; /** * @brief Instance structure for the Q31 FIR decimator. */ typedef struct { uint8_t M; /**< decimation factor. */ uint16_t numTaps; /**< number of coefficients in the filter. */ q31_t *pCoeffs; /**< points to the coefficient array. The array is of length numTaps.*/ q31_t *pState; /**< points to the state variable array. The array is of length numTaps+blockSize-1. */ } arm_fir_decimate_instance_q31; /** * @brief Instance structure for the floating-point FIR decimator. */ typedef struct { uint8_t M; /**< decimation factor. */ uint16_t numTaps; /**< number of coefficients in the filter. */ float32_t *pCoeffs; /**< points to the coefficient array. The array is of length numTaps.*/ float32_t *pState; /**< points to the state variable array. The array is of length numTaps+blockSize-1. */ } arm_fir_decimate_instance_f32; /** * @brief Processing function for the floating-point FIR decimator. * @param[in] *S points to an instance of the floating-point FIR decimator structure. * @param[in] *pSrc points to the block of input data. * @param[out] *pDst points to the block of output data * @param[in] blockSize number of input samples to process per call. * @return none */ void arm_fir_decimate_f32( const arm_fir_decimate_instance_f32 * S, float32_t * pSrc, float32_t * pDst, uint32_t blockSize); /** * @brief Initialization function for the floating-point FIR decimator. * @param[in,out] *S points to an instance of the floating-point FIR decimator structure. * @param[in] numTaps number of coefficients in the filter. * @param[in] M decimation factor. * @param[in] *pCoeffs points to the filter coefficients. * @param[in] *pState points to the state buffer. * @param[in] blockSize number of input samples to process per call. * @return The function returns ARM_MATH_SUCCESS if initialization is successful or ARM_MATH_LENGTH_ERROR if * blockSize is not a multiple of M. */ arm_status arm_fir_decimate_init_f32( arm_fir_decimate_instance_f32 * S, uint16_t numTaps, uint8_t M, float32_t * pCoeffs, float32_t * pState, uint32_t blockSize); /** * @brief Processing function for the Q15 FIR decimator. * @param[in] *S points to an instance of the Q15 FIR decimator structure. * @param[in] *pSrc points to the block of input data. * @param[out] *pDst points to the block of output data * @param[in] blockSize number of input samples to process per call. * @return none */ void arm_fir_decimate_q15( const arm_fir_decimate_instance_q15 * S, q15_t * pSrc, q15_t * pDst, uint32_t blockSize); /** * @brief Processing function for the Q15 FIR decimator (fast variant) for Cortex-M3 and Cortex-M4. * @param[in] *S points to an instance of the Q15 FIR decimator structure. * @param[in] *pSrc points to the block of input data. * @param[out] *pDst points to the block of output data * @param[in] blockSize number of input samples to process per call. * @return none */ void arm_fir_decimate_fast_q15( const arm_fir_decimate_instance_q15 * S, q15_t * pSrc, q15_t * pDst, uint32_t blockSize); /** * @brief Initialization function for the Q15 FIR decimator. * @param[in,out] *S points to an instance of the Q15 FIR decimator structure. * @param[in] numTaps number of coefficients in the filter. * @param[in] M decimation factor. * @param[in] *pCoeffs points to the filter coefficients. * @param[in] *pState points to the state buffer. * @param[in] blockSize number of input samples to process per call. * @return The function returns ARM_MATH_SUCCESS if initialization is successful or ARM_MATH_LENGTH_ERROR if * blockSize is not a multiple of M. */ arm_status arm_fir_decimate_init_q15( arm_fir_decimate_instance_q15 * S, uint16_t numTaps, uint8_t M, q15_t * pCoeffs, q15_t * pState, uint32_t blockSize); /** * @brief Processing function for the Q31 FIR decimator. * @param[in] *S points to an instance of the Q31 FIR decimator structure. * @param[in] *pSrc points to the block of input data. * @param[out] *pDst points to the block of output data * @param[in] blockSize number of input samples to process per call. * @return none */ void arm_fir_decimate_q31( const arm_fir_decimate_instance_q31 * S, q31_t * pSrc, q31_t * pDst, uint32_t blockSize); /** * @brief Processing function for the Q31 FIR decimator (fast variant) for Cortex-M3 and Cortex-M4. * @param[in] *S points to an instance of the Q31 FIR decimator structure. * @param[in] *pSrc points to the block of input data. * @param[out] *pDst points to the block of output data * @param[in] blockSize number of input samples to process per call. * @return none */ void arm_fir_decimate_fast_q31( arm_fir_decimate_instance_q31 * S, q31_t * pSrc, q31_t * pDst, uint32_t blockSize); /** * @brief Initialization function for the Q31 FIR decimator. * @param[in,out] *S points to an instance of the Q31 FIR decimator structure. * @param[in] numTaps number of coefficients in the filter. * @param[in] M decimation factor. * @param[in] *pCoeffs points to the filter coefficients. * @param[in] *pState points to the state buffer. * @param[in] blockSize number of input samples to process per call. * @return The function returns ARM_MATH_SUCCESS if initialization is successful or ARM_MATH_LENGTH_ERROR if * blockSize is not a multiple of M. */ arm_status arm_fir_decimate_init_q31( arm_fir_decimate_instance_q31 * S, uint16_t numTaps, uint8_t M, q31_t * pCoeffs, q31_t * pState, uint32_t blockSize); /** * @brief Instance structure for the Q15 FIR interpolator. */ typedef struct { uint8_t L; /**< upsample factor. */ uint16_t phaseLength; /**< length of each polyphase filter component. */ q15_t *pCoeffs; /**< points to the coefficient array. The array is of length L*phaseLength. */ q15_t *pState; /**< points to the state variable array. The array is of length blockSize+phaseLength-1. */ } arm_fir_interpolate_instance_q15; /** * @brief Instance structure for the Q31 FIR interpolator. */ typedef struct { uint8_t L; /**< upsample factor. */ uint16_t phaseLength; /**< length of each polyphase filter component. */ q31_t *pCoeffs; /**< points to the coefficient array. The array is of length L*phaseLength. */ q31_t *pState; /**< points to the state variable array. The array is of length blockSize+phaseLength-1. */ } arm_fir_interpolate_instance_q31; /** * @brief Instance structure for the floating-point FIR interpolator. */ typedef struct { uint8_t L; /**< upsample factor. */ uint16_t phaseLength; /**< length of each polyphase filter component. */ float32_t *pCoeffs; /**< points to the coefficient array. The array is of length L*phaseLength. */ float32_t *pState; /**< points to the state variable array. The array is of length phaseLength+numTaps-1. */ } arm_fir_interpolate_instance_f32; /** * @brief Processing function for the Q15 FIR interpolator. * @param[in] *S points to an instance of the Q15 FIR interpolator structure. * @param[in] *pSrc points to the block of input data. * @param[out] *pDst points to the block of output data. * @param[in] blockSize number of input samples to process per call. * @return none. */ void arm_fir_interpolate_q15( const arm_fir_interpolate_instance_q15 * S, q15_t * pSrc, q15_t * pDst, uint32_t blockSize); /** * @brief Initialization function for the Q15 FIR interpolator. * @param[in,out] *S points to an instance of the Q15 FIR interpolator structure. * @param[in] L upsample factor. * @param[in] numTaps number of filter coefficients in the filter. * @param[in] *pCoeffs points to the filter coefficient buffer. * @param[in] *pState points to the state buffer. * @param[in] blockSize number of input samples to process per call. * @return The function returns ARM_MATH_SUCCESS if initialization is successful or ARM_MATH_LENGTH_ERROR if * the filter length numTaps is not a multiple of the interpolation factor L. */ arm_status arm_fir_interpolate_init_q15( arm_fir_interpolate_instance_q15 * S, uint8_t L, uint16_t numTaps, q15_t * pCoeffs, q15_t * pState, uint32_t blockSize); /** * @brief Processing function for the Q31 FIR interpolator. * @param[in] *S points to an instance of the Q15 FIR interpolator structure. * @param[in] *pSrc points to the block of input data. * @param[out] *pDst points to the block of output data. * @param[in] blockSize number of input samples to process per call. * @return none. */ void arm_fir_interpolate_q31( const arm_fir_interpolate_instance_q31 * S, q31_t * pSrc, q31_t * pDst, uint32_t blockSize); /** * @brief Initialization function for the Q31 FIR interpolator. * @param[in,out] *S points to an instance of the Q31 FIR interpolator structure. * @param[in] L upsample factor. * @param[in] numTaps number of filter coefficients in the filter. * @param[in] *pCoeffs points to the filter coefficient buffer. * @param[in] *pState points to the state buffer. * @param[in] blockSize number of input samples to process per call. * @return The function returns ARM_MATH_SUCCESS if initialization is successful or ARM_MATH_LENGTH_ERROR if * the filter length numTaps is not a multiple of the interpolation factor L. */ arm_status arm_fir_interpolate_init_q31( arm_fir_interpolate_instance_q31 * S, uint8_t L, uint16_t numTaps, q31_t * pCoeffs, q31_t * pState, uint32_t blockSize); /** * @brief Processing function for the floating-point FIR interpolator. * @param[in] *S points to an instance of the floating-point FIR interpolator structure. * @param[in] *pSrc points to the block of input data. * @param[out] *pDst points to the block of output data. * @param[in] blockSize number of input samples to process per call. * @return none. */ void arm_fir_interpolate_f32( const arm_fir_interpolate_instance_f32 * S, float32_t * pSrc, float32_t * pDst, uint32_t blockSize); /** * @brief Initialization function for the floating-point FIR interpolator. * @param[in,out] *S points to an instance of the floating-point FIR interpolator structure. * @param[in] L upsample factor. * @param[in] numTaps number of filter coefficients in the filter. * @param[in] *pCoeffs points to the filter coefficient buffer. * @param[in] *pState points to the state buffer. * @param[in] blockSize number of input samples to process per call. * @return The function returns ARM_MATH_SUCCESS if initialization is successful or ARM_MATH_LENGTH_ERROR if * the filter length numTaps is not a multiple of the interpolation factor L. */ arm_status arm_fir_interpolate_init_f32( arm_fir_interpolate_instance_f32 * S, uint8_t L, uint16_t numTaps, float32_t * pCoeffs, float32_t * pState, uint32_t blockSize); /** * @brief Instance structure for the high precision Q31 Biquad cascade filter. */ typedef struct { uint8_t numStages; /**< number of 2nd order stages in the filter. Overall order is 2*numStages. */ q63_t *pState; /**< points to the array of state coefficients. The array is of length 4*numStages. */ q31_t *pCoeffs; /**< points to the array of coefficients. The array is of length 5*numStages. */ uint8_t postShift; /**< additional shift, in bits, applied to each output sample. */ } arm_biquad_cas_df1_32x64_ins_q31; /** * @param[in] *S points to an instance of the high precision Q31 Biquad cascade filter structure. * @param[in] *pSrc points to the block of input data. * @param[out] *pDst points to the block of output data * @param[in] blockSize number of samples to process. * @return none. */ void arm_biquad_cas_df1_32x64_q31( const arm_biquad_cas_df1_32x64_ins_q31 * S, q31_t * pSrc, q31_t * pDst, uint32_t blockSize); /** * @param[in,out] *S points to an instance of the high precision Q31 Biquad cascade filter structure. * @param[in] numStages number of 2nd order stages in the filter. * @param[in] *pCoeffs points to the filter coefficients. * @param[in] *pState points to the state buffer. * @param[in] postShift shift to be applied to the output. Varies according to the coefficients format * @return none */ void arm_biquad_cas_df1_32x64_init_q31( arm_biquad_cas_df1_32x64_ins_q31 * S, uint8_t numStages, q31_t * pCoeffs, q63_t * pState, uint8_t postShift); /** * @brief Instance structure for the floating-point transposed direct form II Biquad cascade filter. */ typedef struct { uint8_t numStages; /**< number of 2nd order stages in the filter. Overall order is 2*numStages. */ float32_t *pState; /**< points to the array of state coefficients. The array is of length 2*numStages. */ float32_t *pCoeffs; /**< points to the array of coefficients. The array is of length 5*numStages. */ } arm_biquad_cascade_df2T_instance_f32; /** * @brief Instance structure for the floating-point transposed direct form II Biquad cascade filter. */ typedef struct { uint8_t numStages; /**< number of 2nd order stages in the filter. Overall order is 2*numStages. */ float32_t *pState; /**< points to the array of state coefficients. The array is of length 4*numStages. */ float32_t *pCoeffs; /**< points to the array of coefficients. The array is of length 5*numStages. */ } arm_biquad_cascade_stereo_df2T_instance_f32; /** * @brief Instance structure for the floating-point transposed direct form II Biquad cascade filter. */ typedef struct { uint8_t numStages; /**< number of 2nd order stages in the filter. Overall order is 2*numStages. */ float64_t *pState; /**< points to the array of state coefficients. The array is of length 2*numStages. */ float64_t *pCoeffs; /**< points to the array of coefficients. The array is of length 5*numStages. */ } arm_biquad_cascade_df2T_instance_f64; /** * @brief Processing function for the floating-point transposed direct form II Biquad cascade filter. * @param[in] *S points to an instance of the filter data structure. * @param[in] *pSrc points to the block of input data. * @param[out] *pDst points to the block of output data * @param[in] blockSize number of samples to process. * @return none. */ void arm_biquad_cascade_df2T_f32( const arm_biquad_cascade_df2T_instance_f32 * S, float32_t * pSrc, float32_t * pDst, uint32_t blockSize); /** * @brief Processing function for the floating-point transposed direct form II Biquad cascade filter. 2 channels * @param[in] *S points to an instance of the filter data structure. * @param[in] *pSrc points to the block of input data. * @param[out] *pDst points to the block of output data * @param[in] blockSize number of samples to process. * @return none. */ void arm_biquad_cascade_stereo_df2T_f32( const arm_biquad_cascade_stereo_df2T_instance_f32 * S, float32_t * pSrc, float32_t * pDst, uint32_t blockSize); /** * @brief Processing function for the floating-point transposed direct form II Biquad cascade filter. * @param[in] *S points to an instance of the filter data structure. * @param[in] *pSrc points to the block of input data. * @param[out] *pDst points to the block of output data * @param[in] blockSize number of samples to process. * @return none. */ void arm_biquad_cascade_df2T_f64( const arm_biquad_cascade_df2T_instance_f64 * S, float64_t * pSrc, float64_t * pDst, uint32_t blockSize); /** * @brief Initialization function for the floating-point transposed direct form II Biquad cascade filter. * @param[in,out] *S points to an instance of the filter data structure. * @param[in] numStages number of 2nd order stages in the filter. * @param[in] *pCoeffs points to the filter coefficients. * @param[in] *pState points to the state buffer. * @return none */ void arm_biquad_cascade_df2T_init_f32( arm_biquad_cascade_df2T_instance_f32 * S, uint8_t numStages, float32_t * pCoeffs, float32_t * pState); /** * @brief Initialization function for the floating-point transposed direct form II Biquad cascade filter. * @param[in,out] *S points to an instance of the filter data structure. * @param[in] numStages number of 2nd order stages in the filter. * @param[in] *pCoeffs points to the filter coefficients. * @param[in] *pState points to the state buffer. * @return none */ void arm_biquad_cascade_stereo_df2T_init_f32( arm_biquad_cascade_stereo_df2T_instance_f32 * S, uint8_t numStages, float32_t * pCoeffs, float32_t * pState); /** * @brief Initialization function for the floating-point transposed direct form II Biquad cascade filter. * @param[in,out] *S points to an instance of the filter data structure. * @param[in] numStages number of 2nd order stages in the filter. * @param[in] *pCoeffs points to the filter coefficients. * @param[in] *pState points to the state buffer. * @return none */ void arm_biquad_cascade_df2T_init_f64( arm_biquad_cascade_df2T_instance_f64 * S, uint8_t numStages, float64_t * pCoeffs, float64_t * pState); /** * @brief Instance structure for the Q15 FIR lattice filter. */ typedef struct { uint16_t numStages; /**< number of filter stages. */ q15_t *pState; /**< points to the state variable array. The array is of length numStages. */ q15_t *pCoeffs; /**< points to the coefficient array. The array is of length numStages. */ } arm_fir_lattice_instance_q15; /** * @brief Instance structure for the Q31 FIR lattice filter. */ typedef struct { uint16_t numStages; /**< number of filter stages. */ q31_t *pState; /**< points to the state variable array. The array is of length numStages. */ q31_t *pCoeffs; /**< points to the coefficient array. The array is of length numStages. */ } arm_fir_lattice_instance_q31; /** * @brief Instance structure for the floating-point FIR lattice filter. */ typedef struct { uint16_t numStages; /**< number of filter stages. */ float32_t *pState; /**< points to the state variable array. The array is of length numStages. */ float32_t *pCoeffs; /**< points to the coefficient array. The array is of length numStages. */ } arm_fir_lattice_instance_f32; /** * @brief Initialization function for the Q15 FIR lattice filter. * @param[in] *S points to an instance of the Q15 FIR lattice structure. * @param[in] numStages number of filter stages. * @param[in] *pCoeffs points to the coefficient buffer. The array is of length numStages. * @param[in] *pState points to the state buffer. The array is of length numStages. * @return none. */ void arm_fir_lattice_init_q15( arm_fir_lattice_instance_q15 * S, uint16_t numStages, q15_t * pCoeffs, q15_t * pState); /** * @brief Processing function for the Q15 FIR lattice filter. * @param[in] *S points to an instance of the Q15 FIR lattice structure. * @param[in] *pSrc points to the block of input data. * @param[out] *pDst points to the block of output data. * @param[in] blockSize number of samples to process. * @return none. */ void arm_fir_lattice_q15( const arm_fir_lattice_instance_q15 * S, q15_t * pSrc, q15_t * pDst, uint32_t blockSize); /** * @brief Initialization function for the Q31 FIR lattice filter. * @param[in] *S points to an instance of the Q31 FIR lattice structure. * @param[in] numStages number of filter stages. * @param[in] *pCoeffs points to the coefficient buffer. The array is of length numStages. * @param[in] *pState points to the state buffer. The array is of length numStages. * @return none. */ void arm_fir_lattice_init_q31( arm_fir_lattice_instance_q31 * S, uint16_t numStages, q31_t * pCoeffs, q31_t * pState); /** * @brief Processing function for the Q31 FIR lattice filter. * @param[in] *S points to an instance of the Q31 FIR lattice structure. * @param[in] *pSrc points to the block of input data. * @param[out] *pDst points to the block of output data * @param[in] blockSize number of samples to process. * @return none. */ void arm_fir_lattice_q31( const arm_fir_lattice_instance_q31 * S, q31_t * pSrc, q31_t * pDst, uint32_t blockSize); /** * @brief Initialization function for the floating-point FIR lattice filter. * @param[in] *S points to an instance of the floating-point FIR lattice structure. * @param[in] numStages number of filter stages. * @param[in] *pCoeffs points to the coefficient buffer. The array is of length numStages. * @param[in] *pState points to the state buffer. The array is of length numStages. * @return none. */ void arm_fir_lattice_init_f32( arm_fir_lattice_instance_f32 * S, uint16_t numStages, float32_t * pCoeffs, float32_t * pState); /** * @brief Processing function for the floating-point FIR lattice filter. * @param[in] *S points to an instance of the floating-point FIR lattice structure. * @param[in] *pSrc points to the block of input data. * @param[out] *pDst points to the block of output data * @param[in] blockSize number of samples to process. * @return none. */ void arm_fir_lattice_f32( const arm_fir_lattice_instance_f32 * S, float32_t * pSrc, float32_t * pDst, uint32_t blockSize); /** * @brief Instance structure for the Q15 IIR lattice filter. */ typedef struct { uint16_t numStages; /**< number of stages in the filter. */ q15_t *pState; /**< points to the state variable array. The array is of length numStages+blockSize. */ q15_t *pkCoeffs; /**< points to the reflection coefficient array. The array is of length numStages. */ q15_t *pvCoeffs; /**< points to the ladder coefficient array. The array is of length numStages+1. */ } arm_iir_lattice_instance_q15; /** * @brief Instance structure for the Q31 IIR lattice filter. */ typedef struct { uint16_t numStages; /**< number of stages in the filter. */ q31_t *pState; /**< points to the state variable array. The array is of length numStages+blockSize. */ q31_t *pkCoeffs; /**< points to the reflection coefficient array. The array is of length numStages. */ q31_t *pvCoeffs; /**< points to the ladder coefficient array. The array is of length numStages+1. */ } arm_iir_lattice_instance_q31; /** * @brief Instance structure for the floating-point IIR lattice filter. */ typedef struct { uint16_t numStages; /**< number of stages in the filter. */ float32_t *pState; /**< points to the state variable array. The array is of length numStages+blockSize. */ float32_t *pkCoeffs; /**< points to the reflection coefficient array. The array is of length numStages. */ float32_t *pvCoeffs; /**< points to the ladder coefficient array. The array is of length numStages+1. */ } arm_iir_lattice_instance_f32; /** * @brief Processing function for the floating-point IIR lattice filter. * @param[in] *S points to an instance of the floating-point IIR lattice structure. * @param[in] *pSrc points to the block of input data. * @param[out] *pDst points to the block of output data. * @param[in] blockSize number of samples to process. * @return none. */ void arm_iir_lattice_f32( const arm_iir_lattice_instance_f32 * S, float32_t * pSrc, float32_t * pDst, uint32_t blockSize); /** * @brief Initialization function for the floating-point IIR lattice filter. * @param[in] *S points to an instance of the floating-point IIR lattice structure. * @param[in] numStages number of stages in the filter. * @param[in] *pkCoeffs points to the reflection coefficient buffer. The array is of length numStages. * @param[in] *pvCoeffs points to the ladder coefficient buffer. The array is of length numStages+1. * @param[in] *pState points to the state buffer. The array is of length numStages+blockSize-1. * @param[in] blockSize number of samples to process. * @return none. */ void arm_iir_lattice_init_f32( arm_iir_lattice_instance_f32 * S, uint16_t numStages, float32_t * pkCoeffs, float32_t * pvCoeffs, float32_t * pState, uint32_t blockSize); /** * @brief Processing function for the Q31 IIR lattice filter. * @param[in] *S points to an instance of the Q31 IIR lattice structure. * @param[in] *pSrc points to the block of input data. * @param[out] *pDst points to the block of output data. * @param[in] blockSize number of samples to process. * @return none. */ void arm_iir_lattice_q31( const arm_iir_lattice_instance_q31 * S, q31_t * pSrc, q31_t * pDst, uint32_t blockSize); /** * @brief Initialization function for the Q31 IIR lattice filter. * @param[in] *S points to an instance of the Q31 IIR lattice structure. * @param[in] numStages number of stages in the filter. * @param[in] *pkCoeffs points to the reflection coefficient buffer. The array is of length numStages. * @param[in] *pvCoeffs points to the ladder coefficient buffer. The array is of length numStages+1. * @param[in] *pState points to the state buffer. The array is of length numStages+blockSize. * @param[in] blockSize number of samples to process. * @return none. */ void arm_iir_lattice_init_q31( arm_iir_lattice_instance_q31 * S, uint16_t numStages, q31_t * pkCoeffs, q31_t * pvCoeffs, q31_t * pState, uint32_t blockSize); /** * @brief Processing function for the Q15 IIR lattice filter. * @param[in] *S points to an instance of the Q15 IIR lattice structure. * @param[in] *pSrc points to the block of input data. * @param[out] *pDst points to the block of output data. * @param[in] blockSize number of samples to process. * @return none. */ void arm_iir_lattice_q15( const arm_iir_lattice_instance_q15 * S, q15_t * pSrc, q15_t * pDst, uint32_t blockSize); /** * @brief Initialization function for the Q15 IIR lattice filter. * @param[in] *S points to an instance of the fixed-point Q15 IIR lattice structure. * @param[in] numStages number of stages in the filter. * @param[in] *pkCoeffs points to reflection coefficient buffer. The array is of length numStages. * @param[in] *pvCoeffs points to ladder coefficient buffer. The array is of length numStages+1. * @param[in] *pState points to state buffer. The array is of length numStages+blockSize. * @param[in] blockSize number of samples to process per call. * @return none. */ void arm_iir_lattice_init_q15( arm_iir_lattice_instance_q15 * S, uint16_t numStages, q15_t * pkCoeffs, q15_t * pvCoeffs, q15_t * pState, uint32_t blockSize); /** * @brief Instance structure for the floating-point LMS filter. */ typedef struct { uint16_t numTaps; /**< number of coefficients in the filter. */ float32_t *pState; /**< points to the state variable array. The array is of length numTaps+blockSize-1. */ float32_t *pCoeffs; /**< points to the coefficient array. The array is of length numTaps. */ float32_t mu; /**< step size that controls filter coefficient updates. */ } arm_lms_instance_f32; /** * @brief Processing function for floating-point LMS filter. * @param[in] *S points to an instance of the floating-point LMS filter structure. * @param[in] *pSrc points to the block of input data. * @param[in] *pRef points to the block of reference data. * @param[out] *pOut points to the block of output data. * @param[out] *pErr points to the block of error data. * @param[in] blockSize number of samples to process. * @return none. */ void arm_lms_f32( const arm_lms_instance_f32 * S, float32_t * pSrc, float32_t * pRef, float32_t * pOut, float32_t * pErr, uint32_t blockSize); /** * @brief Initialization function for floating-point LMS filter. * @param[in] *S points to an instance of the floating-point LMS filter structure. * @param[in] numTaps number of filter coefficients. * @param[in] *pCoeffs points to the coefficient buffer. * @param[in] *pState points to state buffer. * @param[in] mu step size that controls filter coefficient updates. * @param[in] blockSize number of samples to process. * @return none. */ void arm_lms_init_f32( arm_lms_instance_f32 * S, uint16_t numTaps, float32_t * pCoeffs, float32_t * pState, float32_t mu, uint32_t blockSize); /** * @brief Instance structure for the Q15 LMS filter. */ typedef struct { uint16_t numTaps; /**< number of coefficients in the filter. */ q15_t *pState; /**< points to the state variable array. The array is of length numTaps+blockSize-1. */ q15_t *pCoeffs; /**< points to the coefficient array. The array is of length numTaps. */ q15_t mu; /**< step size that controls filter coefficient updates. */ uint32_t postShift; /**< bit shift applied to coefficients. */ } arm_lms_instance_q15; /** * @brief Initialization function for the Q15 LMS filter. * @param[in] *S points to an instance of the Q15 LMS filter structure. * @param[in] numTaps number of filter coefficients. * @param[in] *pCoeffs points to the coefficient buffer. * @param[in] *pState points to the state buffer. * @param[in] mu step size that controls filter coefficient updates. * @param[in] blockSize number of samples to process. * @param[in] postShift bit shift applied to coefficients. * @return none. */ void arm_lms_init_q15( arm_lms_instance_q15 * S, uint16_t numTaps, q15_t * pCoeffs, q15_t * pState, q15_t mu, uint32_t blockSize, uint32_t postShift); /** * @brief Processing function for Q15 LMS filter. * @param[in] *S points to an instance of the Q15 LMS filter structure. * @param[in] *pSrc points to the block of input data. * @param[in] *pRef points to the block of reference data. * @param[out] *pOut points to the block of output data. * @param[out] *pErr points to the block of error data. * @param[in] blockSize number of samples to process. * @return none. */ void arm_lms_q15( const arm_lms_instance_q15 * S, q15_t * pSrc, q15_t * pRef, q15_t * pOut, q15_t * pErr, uint32_t blockSize); /** * @brief Instance structure for the Q31 LMS filter. */ typedef struct { uint16_t numTaps; /**< number of coefficients in the filter. */ q31_t *pState; /**< points to the state variable array. The array is of length numTaps+blockSize-1. */ q31_t *pCoeffs; /**< points to the coefficient array. The array is of length numTaps. */ q31_t mu; /**< step size that controls filter coefficient updates. */ uint32_t postShift; /**< bit shift applied to coefficients. */ } arm_lms_instance_q31; /** * @brief Processing function for Q31 LMS filter. * @param[in] *S points to an instance of the Q15 LMS filter structure. * @param[in] *pSrc points to the block of input data. * @param[in] *pRef points to the block of reference data. * @param[out] *pOut points to the block of output data. * @param[out] *pErr points to the block of error data. * @param[in] blockSize number of samples to process. * @return none. */ void arm_lms_q31( const arm_lms_instance_q31 * S, q31_t * pSrc, q31_t * pRef, q31_t * pOut, q31_t * pErr, uint32_t blockSize); /** * @brief Initialization function for Q31 LMS filter. * @param[in] *S points to an instance of the Q31 LMS filter structure. * @param[in] numTaps number of filter coefficients. * @param[in] *pCoeffs points to coefficient buffer. * @param[in] *pState points to state buffer. * @param[in] mu step size that controls filter coefficient updates. * @param[in] blockSize number of samples to process. * @param[in] postShift bit shift applied to coefficients. * @return none. */ void arm_lms_init_q31( arm_lms_instance_q31 * S, uint16_t numTaps, q31_t * pCoeffs, q31_t * pState, q31_t mu, uint32_t blockSize, uint32_t postShift); /** * @brief Instance structure for the floating-point normalized LMS filter. */ typedef struct { uint16_t numTaps; /**< number of coefficients in the filter. */ float32_t *pState; /**< points to the state variable array. The array is of length numTaps+blockSize-1. */ float32_t *pCoeffs; /**< points to the coefficient array. The array is of length numTaps. */ float32_t mu; /**< step size that control filter coefficient updates. */ float32_t energy; /**< saves previous frame energy. */ float32_t x0; /**< saves previous input sample. */ } arm_lms_norm_instance_f32; /** * @brief Processing function for floating-point normalized LMS filter. * @param[in] *S points to an instance of the floating-point normalized LMS filter structure. * @param[in] *pSrc points to the block of input data. * @param[in] *pRef points to the block of reference data. * @param[out] *pOut points to the block of output data. * @param[out] *pErr points to the block of error data. * @param[in] blockSize number of samples to process. * @return none. */ void arm_lms_norm_f32( arm_lms_norm_instance_f32 * S, float32_t * pSrc, float32_t * pRef, float32_t * pOut, float32_t * pErr, uint32_t blockSize); /** * @brief Initialization function for floating-point normalized LMS filter. * @param[in] *S points to an instance of the floating-point LMS filter structure. * @param[in] numTaps number of filter coefficients. * @param[in] *pCoeffs points to coefficient buffer. * @param[in] *pState points to state buffer. * @param[in] mu step size that controls filter coefficient updates. * @param[in] blockSize number of samples to process. * @return none. */ void arm_lms_norm_init_f32( arm_lms_norm_instance_f32 * S, uint16_t numTaps, float32_t * pCoeffs, float32_t * pState, float32_t mu, uint32_t blockSize); /** * @brief Instance structure for the Q31 normalized LMS filter. */ typedef struct { uint16_t numTaps; /**< number of coefficients in the filter. */ q31_t *pState; /**< points to the state variable array. The array is of length numTaps+blockSize-1. */ q31_t *pCoeffs; /**< points to the coefficient array. The array is of length numTaps. */ q31_t mu; /**< step size that controls filter coefficient updates. */ uint8_t postShift; /**< bit shift applied to coefficients. */ q31_t *recipTable; /**< points to the reciprocal initial value table. */ q31_t energy; /**< saves previous frame energy. */ q31_t x0; /**< saves previous input sample. */ } arm_lms_norm_instance_q31; /** * @brief Processing function for Q31 normalized LMS filter. * @param[in] *S points to an instance of the Q31 normalized LMS filter structure. * @param[in] *pSrc points to the block of input data. * @param[in] *pRef points to the block of reference data. * @param[out] *pOut points to the block of output data. * @param[out] *pErr points to the block of error data. * @param[in] blockSize number of samples to process. * @return none. */ void arm_lms_norm_q31( arm_lms_norm_instance_q31 * S, q31_t * pSrc, q31_t * pRef, q31_t * pOut, q31_t * pErr, uint32_t blockSize); /** * @brief Initialization function for Q31 normalized LMS filter. * @param[in] *S points to an instance of the Q31 normalized LMS filter structure. * @param[in] numTaps number of filter coefficients. * @param[in] *pCoeffs points to coefficient buffer. * @param[in] *pState points to state buffer. * @param[in] mu step size that controls filter coefficient updates. * @param[in] blockSize number of samples to process. * @param[in] postShift bit shift applied to coefficients. * @return none. */ void arm_lms_norm_init_q31( arm_lms_norm_instance_q31 * S, uint16_t numTaps, q31_t * pCoeffs, q31_t * pState, q31_t mu, uint32_t blockSize, uint8_t postShift); /** * @brief Instance structure for the Q15 normalized LMS filter. */ typedef struct { uint16_t numTaps; /**< Number of coefficients in the filter. */ q15_t *pState; /**< points to the state variable array. The array is of length numTaps+blockSize-1. */ q15_t *pCoeffs; /**< points to the coefficient array. The array is of length numTaps. */ q15_t mu; /**< step size that controls filter coefficient updates. */ uint8_t postShift; /**< bit shift applied to coefficients. */ q15_t *recipTable; /**< Points to the reciprocal initial value table. */ q15_t energy; /**< saves previous frame energy. */ q15_t x0; /**< saves previous input sample. */ } arm_lms_norm_instance_q15; /** * @brief Processing function for Q15 normalized LMS filter. * @param[in] *S points to an instance of the Q15 normalized LMS filter structure. * @param[in] *pSrc points to the block of input data. * @param[in] *pRef points to the block of reference data. * @param[out] *pOut points to the block of output data. * @param[out] *pErr points to the block of error data. * @param[in] blockSize number of samples to process. * @return none. */ void arm_lms_norm_q15( arm_lms_norm_instance_q15 * S, q15_t * pSrc, q15_t * pRef, q15_t * pOut, q15_t * pErr, uint32_t blockSize); /** * @brief Initialization function for Q15 normalized LMS filter. * @param[in] *S points to an instance of the Q15 normalized LMS filter structure. * @param[in] numTaps number of filter coefficients. * @param[in] *pCoeffs points to coefficient buffer. * @param[in] *pState points to state buffer. * @param[in] mu step size that controls filter coefficient updates. * @param[in] blockSize number of samples to process. * @param[in] postShift bit shift applied to coefficients. * @return none. */ void arm_lms_norm_init_q15( arm_lms_norm_instance_q15 * S, uint16_t numTaps, q15_t * pCoeffs, q15_t * pState, q15_t mu, uint32_t blockSize, uint8_t postShift); /** * @brief Correlation of floating-point sequences. * @param[in] *pSrcA points to the first input sequence. * @param[in] srcALen length of the first input sequence. * @param[in] *pSrcB points to the second input sequence. * @param[in] srcBLen length of the second input sequence. * @param[out] *pDst points to the block of output data Length 2 * max(srcALen, srcBLen) - 1. * @return none. */ void arm_correlate_f32( float32_t * pSrcA, uint32_t srcALen, float32_t * pSrcB, uint32_t srcBLen, float32_t * pDst); /** * @brief Correlation of Q15 sequences * @param[in] *pSrcA points to the first input sequence. * @param[in] srcALen length of the first input sequence. * @param[in] *pSrcB points to the second input sequence. * @param[in] srcBLen length of the second input sequence. * @param[out] *pDst points to the block of output data Length 2 * max(srcALen, srcBLen) - 1. * @param[in] *pScratch points to scratch buffer of size max(srcALen, srcBLen) + 2*min(srcALen, srcBLen) - 2. * @return none. */ void arm_correlate_opt_q15( q15_t * pSrcA, uint32_t srcALen, q15_t * pSrcB, uint32_t srcBLen, q15_t * pDst, q15_t * pScratch); /** * @brief Correlation of Q15 sequences. * @param[in] *pSrcA points to the first input sequence. * @param[in] srcALen length of the first input sequence. * @param[in] *pSrcB points to the second input sequence. * @param[in] srcBLen length of the second input sequence. * @param[out] *pDst points to the block of output data Length 2 * max(srcALen, srcBLen) - 1. * @return none. */ void arm_correlate_q15( q15_t * pSrcA, uint32_t srcALen, q15_t * pSrcB, uint32_t srcBLen, q15_t * pDst); /** * @brief Correlation of Q15 sequences (fast version) for Cortex-M3 and Cortex-M4. * @param[in] *pSrcA points to the first input sequence. * @param[in] srcALen length of the first input sequence. * @param[in] *pSrcB points to the second input sequence. * @param[in] srcBLen length of the second input sequence. * @param[out] *pDst points to the block of output data Length 2 * max(srcALen, srcBLen) - 1. * @return none. */ void arm_correlate_fast_q15( q15_t * pSrcA, uint32_t srcALen, q15_t * pSrcB, uint32_t srcBLen, q15_t * pDst); /** * @brief Correlation of Q15 sequences (fast version) for Cortex-M3 and Cortex-M4. * @param[in] *pSrcA points to the first input sequence. * @param[in] srcALen length of the first input sequence. * @param[in] *pSrcB points to the second input sequence. * @param[in] srcBLen length of the second input sequence. * @param[out] *pDst points to the block of output data Length 2 * max(srcALen, srcBLen) - 1. * @param[in] *pScratch points to scratch buffer of size max(srcALen, srcBLen) + 2*min(srcALen, srcBLen) - 2. * @return none. */ void arm_correlate_fast_opt_q15( q15_t * pSrcA, uint32_t srcALen, q15_t * pSrcB, uint32_t srcBLen, q15_t * pDst, q15_t * pScratch); /** * @brief Correlation of Q31 sequences. * @param[in] *pSrcA points to the first input sequence. * @param[in] srcALen length of the first input sequence. * @param[in] *pSrcB points to the second input sequence. * @param[in] srcBLen length of the second input sequence. * @param[out] *pDst points to the block of output data Length 2 * max(srcALen, srcBLen) - 1. * @return none. */ void arm_correlate_q31( q31_t * pSrcA, uint32_t srcALen, q31_t * pSrcB, uint32_t srcBLen, q31_t * pDst); /** * @brief Correlation of Q31 sequences (fast version) for Cortex-M3 and Cortex-M4 * @param[in] *pSrcA points to the first input sequence. * @param[in] srcALen length of the first input sequence. * @param[in] *pSrcB points to the second input sequence. * @param[in] srcBLen length of the second input sequence. * @param[out] *pDst points to the block of output data Length 2 * max(srcALen, srcBLen) - 1. * @return none. */ void arm_correlate_fast_q31( q31_t * pSrcA, uint32_t srcALen, q31_t * pSrcB, uint32_t srcBLen, q31_t * pDst); /** * @brief Correlation of Q7 sequences. * @param[in] *pSrcA points to the first input sequence. * @param[in] srcALen length of the first input sequence. * @param[in] *pSrcB points to the second input sequence. * @param[in] srcBLen length of the second input sequence. * @param[out] *pDst points to the block of output data Length 2 * max(srcALen, srcBLen) - 1. * @param[in] *pScratch1 points to scratch buffer(of type q15_t) of size max(srcALen, srcBLen) + 2*min(srcALen, srcBLen) - 2. * @param[in] *pScratch2 points to scratch buffer (of type q15_t) of size min(srcALen, srcBLen). * @return none. */ void arm_correlate_opt_q7( q7_t * pSrcA, uint32_t srcALen, q7_t * pSrcB, uint32_t srcBLen, q7_t * pDst, q15_t * pScratch1, q15_t * pScratch2); /** * @brief Correlation of Q7 sequences. * @param[in] *pSrcA points to the first input sequence. * @param[in] srcALen length of the first input sequence. * @param[in] *pSrcB points to the second input sequence. * @param[in] srcBLen length of the second input sequence. * @param[out] *pDst points to the block of output data Length 2 * max(srcALen, srcBLen) - 1. * @return none. */ void arm_correlate_q7( q7_t * pSrcA, uint32_t srcALen, q7_t * pSrcB, uint32_t srcBLen, q7_t * pDst); /** * @brief Instance structure for the floating-point sparse FIR filter. */ typedef struct { uint16_t numTaps; /**< number of coefficients in the filter. */ uint16_t stateIndex; /**< state buffer index. Points to the oldest sample in the state buffer. */ float32_t *pState; /**< points to the state buffer array. The array is of length maxDelay+blockSize-1. */ float32_t *pCoeffs; /**< points to the coefficient array. The array is of length numTaps.*/ uint16_t maxDelay; /**< maximum offset specified by the pTapDelay array. */ int32_t *pTapDelay; /**< points to the array of delay values. The array is of length numTaps. */ } arm_fir_sparse_instance_f32; /** * @brief Instance structure for the Q31 sparse FIR filter. */ typedef struct { uint16_t numTaps; /**< number of coefficients in the filter. */ uint16_t stateIndex; /**< state buffer index. Points to the oldest sample in the state buffer. */ q31_t *pState; /**< points to the state buffer array. The array is of length maxDelay+blockSize-1. */ q31_t *pCoeffs; /**< points to the coefficient array. The array is of length numTaps.*/ uint16_t maxDelay; /**< maximum offset specified by the pTapDelay array. */ int32_t *pTapDelay; /**< points to the array of delay values. The array is of length numTaps. */ } arm_fir_sparse_instance_q31; /** * @brief Instance structure for the Q15 sparse FIR filter. */ typedef struct { uint16_t numTaps; /**< number of coefficients in the filter. */ uint16_t stateIndex; /**< state buffer index. Points to the oldest sample in the state buffer. */ q15_t *pState; /**< points to the state buffer array. The array is of length maxDelay+blockSize-1. */ q15_t *pCoeffs; /**< points to the coefficient array. The array is of length numTaps.*/ uint16_t maxDelay; /**< maximum offset specified by the pTapDelay array. */ int32_t *pTapDelay; /**< points to the array of delay values. The array is of length numTaps. */ } arm_fir_sparse_instance_q15; /** * @brief Instance structure for the Q7 sparse FIR filter. */ typedef struct { uint16_t numTaps; /**< number of coefficients in the filter. */ uint16_t stateIndex; /**< state buffer index. Points to the oldest sample in the state buffer. */ q7_t *pState; /**< points to the state buffer array. The array is of length maxDelay+blockSize-1. */ q7_t *pCoeffs; /**< points to the coefficient array. The array is of length numTaps.*/ uint16_t maxDelay; /**< maximum offset specified by the pTapDelay array. */ int32_t *pTapDelay; /**< points to the array of delay values. The array is of length numTaps. */ } arm_fir_sparse_instance_q7; /** * @brief Processing function for the floating-point sparse FIR filter. * @param[in] *S points to an instance of the floating-point sparse FIR structure. * @param[in] *pSrc points to the block of input data. * @param[out] *pDst points to the block of output data * @param[in] *pScratchIn points to a temporary buffer of size blockSize. * @param[in] blockSize number of input samples to process per call. * @return none. */ void arm_fir_sparse_f32( arm_fir_sparse_instance_f32 * S, float32_t * pSrc, float32_t * pDst, float32_t * pScratchIn, uint32_t blockSize); /** * @brief Initialization function for the floating-point sparse FIR filter. * @param[in,out] *S points to an instance of the floating-point sparse FIR structure. * @param[in] numTaps number of nonzero coefficients in the filter. * @param[in] *pCoeffs points to the array of filter coefficients. * @param[in] *pState points to the state buffer. * @param[in] *pTapDelay points to the array of offset times. * @param[in] maxDelay maximum offset time supported. * @param[in] blockSize number of samples that will be processed per block. * @return none */ void arm_fir_sparse_init_f32( arm_fir_sparse_instance_f32 * S, uint16_t numTaps, float32_t * pCoeffs, float32_t * pState, int32_t * pTapDelay, uint16_t maxDelay, uint32_t blockSize); /** * @brief Processing function for the Q31 sparse FIR filter. * @param[in] *S points to an instance of the Q31 sparse FIR structure. * @param[in] *pSrc points to the block of input data. * @param[out] *pDst points to the block of output data * @param[in] *pScratchIn points to a temporary buffer of size blockSize. * @param[in] blockSize number of input samples to process per call. * @return none. */ void arm_fir_sparse_q31( arm_fir_sparse_instance_q31 * S, q31_t * pSrc, q31_t * pDst, q31_t * pScratchIn, uint32_t blockSize); /** * @brief Initialization function for the Q31 sparse FIR filter. * @param[in,out] *S points to an instance of the Q31 sparse FIR structure. * @param[in] numTaps number of nonzero coefficients in the filter. * @param[in] *pCoeffs points to the array of filter coefficients. * @param[in] *pState points to the state buffer. * @param[in] *pTapDelay points to the array of offset times. * @param[in] maxDelay maximum offset time supported. * @param[in] blockSize number of samples that will be processed per block. * @return none */ void arm_fir_sparse_init_q31( arm_fir_sparse_instance_q31 * S, uint16_t numTaps, q31_t * pCoeffs, q31_t * pState, int32_t * pTapDelay, uint16_t maxDelay, uint32_t blockSize); /** * @brief Processing function for the Q15 sparse FIR filter. * @param[in] *S points to an instance of the Q15 sparse FIR structure. * @param[in] *pSrc points to the block of input data. * @param[out] *pDst points to the block of output data * @param[in] *pScratchIn points to a temporary buffer of size blockSize. * @param[in] *pScratchOut points to a temporary buffer of size blockSize. * @param[in] blockSize number of input samples to process per call. * @return none. */ void arm_fir_sparse_q15( arm_fir_sparse_instance_q15 * S, q15_t * pSrc, q15_t * pDst, q15_t * pScratchIn, q31_t * pScratchOut, uint32_t blockSize); /** * @brief Initialization function for the Q15 sparse FIR filter. * @param[in,out] *S points to an instance of the Q15 sparse FIR structure. * @param[in] numTaps number of nonzero coefficients in the filter. * @param[in] *pCoeffs points to the array of filter coefficients. * @param[in] *pState points to the state buffer. * @param[in] *pTapDelay points to the array of offset times. * @param[in] maxDelay maximum offset time supported. * @param[in] blockSize number of samples that will be processed per block. * @return none */ void arm_fir_sparse_init_q15( arm_fir_sparse_instance_q15 * S, uint16_t numTaps, q15_t * pCoeffs, q15_t * pState, int32_t * pTapDelay, uint16_t maxDelay, uint32_t blockSize); /** * @brief Processing function for the Q7 sparse FIR filter. * @param[in] *S points to an instance of the Q7 sparse FIR structure. * @param[in] *pSrc points to the block of input data. * @param[out] *pDst points to the block of output data * @param[in] *pScratchIn points to a temporary buffer of size blockSize. * @param[in] *pScratchOut points to a temporary buffer of size blockSize. * @param[in] blockSize number of input samples to process per call. * @return none. */ void arm_fir_sparse_q7( arm_fir_sparse_instance_q7 * S, q7_t * pSrc, q7_t * pDst, q7_t * pScratchIn, q31_t * pScratchOut, uint32_t blockSize); /** * @brief Initialization function for the Q7 sparse FIR filter. * @param[in,out] *S points to an instance of the Q7 sparse FIR structure. * @param[in] numTaps number of nonzero coefficients in the filter. * @param[in] *pCoeffs points to the array of filter coefficients. * @param[in] *pState points to the state buffer. * @param[in] *pTapDelay points to the array of offset times. * @param[in] maxDelay maximum offset time supported. * @param[in] blockSize number of samples that will be processed per block. * @return none */ void arm_fir_sparse_init_q7( arm_fir_sparse_instance_q7 * S, uint16_t numTaps, q7_t * pCoeffs, q7_t * pState, int32_t * pTapDelay, uint16_t maxDelay, uint32_t blockSize); /* * @brief Floating-point sin_cos function. * @param[in] theta input value in degrees * @param[out] *pSinVal points to the processed sine output. * @param[out] *pCosVal points to the processed cos output. * @return none. */ void arm_sin_cos_f32( float32_t theta, float32_t * pSinVal, float32_t * pCcosVal); /* * @brief Q31 sin_cos function. * @param[in] theta scaled input value in degrees * @param[out] *pSinVal points to the processed sine output. * @param[out] *pCosVal points to the processed cosine output. * @return none. */ void arm_sin_cos_q31( q31_t theta, q31_t * pSinVal, q31_t * pCosVal); /** * @brief Floating-point complex conjugate. * @param[in] *pSrc points to the input vector * @param[out] *pDst points to the output vector * @param[in] numSamples number of complex samples in each vector * @return none. */ void arm_cmplx_conj_f32( float32_t * pSrc, float32_t * pDst, uint32_t numSamples); /** * @brief Q31 complex conjugate. * @param[in] *pSrc points to the input vector * @param[out] *pDst points to the output vector * @param[in] numSamples number of complex samples in each vector * @return none. */ void arm_cmplx_conj_q31( q31_t * pSrc, q31_t * pDst, uint32_t numSamples); /** * @brief Q15 complex conjugate. * @param[in] *pSrc points to the input vector * @param[out] *pDst points to the output vector * @param[in] numSamples number of complex samples in each vector * @return none. */ void arm_cmplx_conj_q15( q15_t * pSrc, q15_t * pDst, uint32_t numSamples); /** * @brief Floating-point complex magnitude squared * @param[in] *pSrc points to the complex input vector * @param[out] *pDst points to the real output vector * @param[in] numSamples number of complex samples in the input vector * @return none. */ void arm_cmplx_mag_squared_f32( float32_t * pSrc, float32_t * pDst, uint32_t numSamples); /** * @brief Q31 complex magnitude squared * @param[in] *pSrc points to the complex input vector * @param[out] *pDst points to the real output vector * @param[in] numSamples number of complex samples in the input vector * @return none. */ void arm_cmplx_mag_squared_q31( q31_t * pSrc, q31_t * pDst, uint32_t numSamples); /** * @brief Q15 complex magnitude squared * @param[in] *pSrc points to the complex input vector * @param[out] *pDst points to the real output vector * @param[in] numSamples number of complex samples in the input vector * @return none. */ void arm_cmplx_mag_squared_q15( q15_t * pSrc, q15_t * pDst, uint32_t numSamples); /** * @ingroup groupController */ /** * @defgroup PID PID Motor Control * * A Proportional Integral Derivative (PID) controller is a generic feedback control * loop mechanism widely used in industrial control systems. * A PID controller is the most commonly used type of feedback controller. * * This set of functions implements (PID) controllers * for Q15, Q31, and floating-point data types. The functions operate on a single sample * of data and each call to the function returns a single processed value. * S points to an instance of the PID control data structure. in * is the input sample value. The functions return the output value. * * \par Algorithm: *
   *    y[n] = y[n-1] + A0 * x[n] + A1 * x[n-1] + A2 * x[n-2]
   *    A0 = Kp + Ki + Kd
   *    A1 = (-Kp ) - (2 * Kd )
   *    A2 = Kd  
* * \par * where \c Kp is proportional constant, \c Ki is Integral constant and \c Kd is Derivative constant * * \par * \image html PID.gif "Proportional Integral Derivative Controller" * * \par * The PID controller calculates an "error" value as the difference between * the measured output and the reference input. * The controller attempts to minimize the error by adjusting the process control inputs. * The proportional value determines the reaction to the current error, * the integral value determines the reaction based on the sum of recent errors, * and the derivative value determines the reaction based on the rate at which the error has been changing. * * \par Instance Structure * The Gains A0, A1, A2 and state variables for a PID controller are stored together in an instance data structure. * A separate instance structure must be defined for each PID Controller. * There are separate instance structure declarations for each of the 3 supported data types. * * \par Reset Functions * There is also an associated reset function for each data type which clears the state array. * * \par Initialization Functions * There is also an associated initialization function for each data type. * The initialization function performs the following operations: * - Initializes the Gains A0, A1, A2 from Kp,Ki, Kd gains. * - Zeros out the values in the state buffer. * * \par * Instance structure cannot be placed into a const data section and it is recommended to use the initialization function. * * \par Fixed-Point Behavior * Care must be taken when using the fixed-point versions of the PID Controller functions. * In particular, the overflow and saturation behavior of the accumulator used in each function must be considered. * Refer to the function specific documentation below for usage guidelines. */ /** * @addtogroup PID * @{ */ /** * @brief Process function for the floating-point PID Control. * @param[in,out] *S is an instance of the floating-point PID Control structure * @param[in] in input sample to process * @return out processed output sample. */ static __INLINE float32_t arm_pid_f32( arm_pid_instance_f32 * S, float32_t in) { float32_t out; /* y[n] = y[n-1] + A0 * x[n] + A1 * x[n-1] + A2 * x[n-2] */ out = (S->A0 * in) + (S->A1 * S->state[0]) + (S->A2 * S->state[1]) + (S->state[2]); /* Update state */ S->state[1] = S->state[0]; S->state[0] = in; S->state[2] = out; /* return to application */ return (out); } /** * @brief Process function for the Q31 PID Control. * @param[in,out] *S points to an instance of the Q31 PID Control structure * @param[in] in input sample to process * @return out processed output sample. * * Scaling and Overflow Behavior: * \par * The function is implemented using an internal 64-bit accumulator. * The accumulator has a 2.62 format and maintains full precision of the intermediate multiplication results but provides only a single guard bit. * Thus, if the accumulator result overflows it wraps around rather than clip. * In order to avoid overflows completely the input signal must be scaled down by 2 bits as there are four additions. * After all multiply-accumulates are performed, the 2.62 accumulator is truncated to 1.32 format and then saturated to 1.31 format. */ static __INLINE q31_t arm_pid_q31( arm_pid_instance_q31 * S, q31_t in) { q63_t acc; q31_t out; /* acc = A0 * x[n] */ acc = (q63_t) S->A0 * in; /* acc += A1 * x[n-1] */ acc += (q63_t) S->A1 * S->state[0]; /* acc += A2 * x[n-2] */ acc += (q63_t) S->A2 * S->state[1]; /* convert output to 1.31 format to add y[n-1] */ out = (q31_t) (acc >> 31u); /* out += y[n-1] */ out += S->state[2]; /* Update state */ S->state[1] = S->state[0]; S->state[0] = in; S->state[2] = out; /* return to application */ return (out); } /** * @brief Process function for the Q15 PID Control. * @param[in,out] *S points to an instance of the Q15 PID Control structure * @param[in] in input sample to process * @return out processed output sample. * * Scaling and Overflow Behavior: * \par * The function is implemented using a 64-bit internal accumulator. * Both Gains and state variables are represented in 1.15 format and multiplications yield a 2.30 result. * The 2.30 intermediate results are accumulated in a 64-bit accumulator in 34.30 format. * There is no risk of internal overflow with this approach and the full precision of intermediate multiplications is preserved. * After all additions have been performed, the accumulator is truncated to 34.15 format by discarding low 15 bits. * Lastly, the accumulator is saturated to yield a result in 1.15 format. */ static __INLINE q15_t arm_pid_q15( arm_pid_instance_q15 * S, q15_t in) { q63_t acc; q15_t out; #ifndef ARM_MATH_CM0_FAMILY __SIMD32_TYPE *vstate; /* Implementation of PID controller */ /* acc = A0 * x[n] */ acc = (q31_t) __SMUAD(S->A0, in); /* acc += A1 * x[n-1] + A2 * x[n-2] */ vstate = __SIMD32_CONST(S->state); acc = __SMLALD(S->A1, (q31_t) *vstate, acc); #else /* acc = A0 * x[n] */ acc = ((q31_t) S->A0) * in; /* acc += A1 * x[n-1] + A2 * x[n-2] */ acc += (q31_t) S->A1 * S->state[0]; acc += (q31_t) S->A2 * S->state[1]; #endif /* acc += y[n-1] */ acc += (q31_t) S->state[2] << 15; /* saturate the output */ out = (q15_t) (__SSAT((acc >> 15), 16)); /* Update state */ S->state[1] = S->state[0]; S->state[0] = in; S->state[2] = out; /* return to application */ return (out); } /** * @} end of PID group */ /** * @brief Floating-point matrix inverse. * @param[in] *src points to the instance of the input floating-point matrix structure. * @param[out] *dst points to the instance of the output floating-point matrix structure. * @return The function returns ARM_MATH_SIZE_MISMATCH, if the dimensions do not match. * If the input matrix is singular (does not have an inverse), then the algorithm terminates and returns error status ARM_MATH_SINGULAR. */ arm_status arm_mat_inverse_f32( const arm_matrix_instance_f32 * src, arm_matrix_instance_f32 * dst); /** * @brief Floating-point matrix inverse. * @param[in] *src points to the instance of the input floating-point matrix structure. * @param[out] *dst points to the instance of the output floating-point matrix structure. * @return The function returns ARM_MATH_SIZE_MISMATCH, if the dimensions do not match. * If the input matrix is singular (does not have an inverse), then the algorithm terminates and returns error status ARM_MATH_SINGULAR. */ arm_status arm_mat_inverse_f64( const arm_matrix_instance_f64 * src, arm_matrix_instance_f64 * dst); /** * @ingroup groupController */ /** * @defgroup clarke Vector Clarke Transform * Forward Clarke transform converts the instantaneous stator phases into a two-coordinate time invariant vector. * Generally the Clarke transform uses three-phase currents Ia, Ib and Ic to calculate currents * in the two-phase orthogonal stator axis Ialpha and Ibeta. * When Ialpha is superposed with Ia as shown in the figure below * \image html clarke.gif Stator current space vector and its components in (a,b). * and Ia + Ib + Ic = 0, in this condition Ialpha and Ibeta * can be calculated using only Ia and Ib. * * The function operates on a single sample of data and each call to the function returns the processed output. * The library provides separate functions for Q31 and floating-point data types. * \par Algorithm * \image html clarkeFormula.gif * where Ia and Ib are the instantaneous stator phases and * pIalpha and pIbeta are the two coordinates of time invariant vector. * \par Fixed-Point Behavior * Care must be taken when using the Q31 version of the Clarke transform. * In particular, the overflow and saturation behavior of the accumulator used must be considered. * Refer to the function specific documentation below for usage guidelines. */ /** * @addtogroup clarke * @{ */ /** * * @brief Floating-point Clarke transform * @param[in] Ia input three-phase coordinate a * @param[in] Ib input three-phase coordinate b * @param[out] *pIalpha points to output two-phase orthogonal vector axis alpha * @param[out] *pIbeta points to output two-phase orthogonal vector axis beta * @return none. */ static __INLINE void arm_clarke_f32( float32_t Ia, float32_t Ib, float32_t * pIalpha, float32_t * pIbeta) { /* Calculate pIalpha using the equation, pIalpha = Ia */ *pIalpha = Ia; /* Calculate pIbeta using the equation, pIbeta = (1/sqrt(3)) * Ia + (2/sqrt(3)) * Ib */ *pIbeta = ((float32_t) 0.57735026919 * Ia + (float32_t) 1.15470053838 * Ib); } /** * @brief Clarke transform for Q31 version * @param[in] Ia input three-phase coordinate a * @param[in] Ib input three-phase coordinate b * @param[out] *pIalpha points to output two-phase orthogonal vector axis alpha * @param[out] *pIbeta points to output two-phase orthogonal vector axis beta * @return none. * * Scaling and Overflow Behavior: * \par * The function is implemented using an internal 32-bit accumulator. * The accumulator maintains 1.31 format by truncating lower 31 bits of the intermediate multiplication in 2.62 format. * There is saturation on the addition, hence there is no risk of overflow. */ static __INLINE void arm_clarke_q31( q31_t Ia, q31_t Ib, q31_t * pIalpha, q31_t * pIbeta) { q31_t product1, product2; /* Temporary variables used to store intermediate results */ /* Calculating pIalpha from Ia by equation pIalpha = Ia */ *pIalpha = Ia; /* Intermediate product is calculated by (1/(sqrt(3)) * Ia) */ product1 = (q31_t) (((q63_t) Ia * 0x24F34E8B) >> 30); /* Intermediate product is calculated by (2/sqrt(3) * Ib) */ product2 = (q31_t) (((q63_t) Ib * 0x49E69D16) >> 30); /* pIbeta is calculated by adding the intermediate products */ *pIbeta = __QADD(product1, product2); } /** * @} end of clarke group */ /** * @brief Converts the elements of the Q7 vector to Q31 vector. * @param[in] *pSrc input pointer * @param[out] *pDst output pointer * @param[in] blockSize number of samples to process * @return none. */ void arm_q7_to_q31( q7_t * pSrc, q31_t * pDst, uint32_t blockSize); /** * @ingroup groupController */ /** * @defgroup inv_clarke Vector Inverse Clarke Transform * Inverse Clarke transform converts the two-coordinate time invariant vector into instantaneous stator phases. * * The function operates on a single sample of data and each call to the function returns the processed output. * The library provides separate functions for Q31 and floating-point data types. * \par Algorithm * \image html clarkeInvFormula.gif * where pIa and pIb are the instantaneous stator phases and * Ialpha and Ibeta are the two coordinates of time invariant vector. * \par Fixed-Point Behavior * Care must be taken when using the Q31 version of the Clarke transform. * In particular, the overflow and saturation behavior of the accumulator used must be considered. * Refer to the function specific documentation below for usage guidelines. */ /** * @addtogroup inv_clarke * @{ */ /** * @brief Floating-point Inverse Clarke transform * @param[in] Ialpha input two-phase orthogonal vector axis alpha * @param[in] Ibeta input two-phase orthogonal vector axis beta * @param[out] *pIa points to output three-phase coordinate a * @param[out] *pIb points to output three-phase coordinate b * @return none. */ static __INLINE void arm_inv_clarke_f32( float32_t Ialpha, float32_t Ibeta, float32_t * pIa, float32_t * pIb) { /* Calculating pIa from Ialpha by equation pIa = Ialpha */ *pIa = Ialpha; /* Calculating pIb from Ialpha and Ibeta by equation pIb = -(1/2) * Ialpha + (sqrt(3)/2) * Ibeta */ *pIb = -0.5 * Ialpha + (float32_t) 0.8660254039 *Ibeta; } /** * @brief Inverse Clarke transform for Q31 version * @param[in] Ialpha input two-phase orthogonal vector axis alpha * @param[in] Ibeta input two-phase orthogonal vector axis beta * @param[out] *pIa points to output three-phase coordinate a * @param[out] *pIb points to output three-phase coordinate b * @return none. * * Scaling and Overflow Behavior: * \par * The function is implemented using an internal 32-bit accumulator. * The accumulator maintains 1.31 format by truncating lower 31 bits of the intermediate multiplication in 2.62 format. * There is saturation on the subtraction, hence there is no risk of overflow. */ static __INLINE void arm_inv_clarke_q31( q31_t Ialpha, q31_t Ibeta, q31_t * pIa, q31_t * pIb) { q31_t product1, product2; /* Temporary variables used to store intermediate results */ /* Calculating pIa from Ialpha by equation pIa = Ialpha */ *pIa = Ialpha; /* Intermediate product is calculated by (1/(2*sqrt(3)) * Ia) */ product1 = (q31_t) (((q63_t) (Ialpha) * (0x40000000)) >> 31); /* Intermediate product is calculated by (1/sqrt(3) * pIb) */ product2 = (q31_t) (((q63_t) (Ibeta) * (0x6ED9EBA1)) >> 31); /* pIb is calculated by subtracting the products */ *pIb = __QSUB(product2, product1); } /** * @} end of inv_clarke group */ /** * @brief Converts the elements of the Q7 vector to Q15 vector. * @param[in] *pSrc input pointer * @param[out] *pDst output pointer * @param[in] blockSize number of samples to process * @return none. */ void arm_q7_to_q15( q7_t * pSrc, q15_t * pDst, uint32_t blockSize); /** * @ingroup groupController */ /** * @defgroup park Vector Park Transform * * Forward Park transform converts the input two-coordinate vector to flux and torque components. * The Park transform can be used to realize the transformation of the Ialpha and the Ibeta currents * from the stationary to the moving reference frame and control the spatial relationship between * the stator vector current and rotor flux vector. * If we consider the d axis aligned with the rotor flux, the diagram below shows the * current vector and the relationship from the two reference frames: * \image html park.gif "Stator current space vector and its component in (a,b) and in the d,q rotating reference frame" * * The function operates on a single sample of data and each call to the function returns the processed output. * The library provides separate functions for Q31 and floating-point data types. * \par Algorithm * \image html parkFormula.gif * where Ialpha and Ibeta are the stator vector components, * pId and pIq are rotor vector components and cosVal and sinVal are the * cosine and sine values of theta (rotor flux position). * \par Fixed-Point Behavior * Care must be taken when using the Q31 version of the Park transform. * In particular, the overflow and saturation behavior of the accumulator used must be considered. * Refer to the function specific documentation below for usage guidelines. */ /** * @addtogroup park * @{ */ /** * @brief Floating-point Park transform * @param[in] Ialpha input two-phase vector coordinate alpha * @param[in] Ibeta input two-phase vector coordinate beta * @param[out] *pId points to output rotor reference frame d * @param[out] *pIq points to output rotor reference frame q * @param[in] sinVal sine value of rotation angle theta * @param[in] cosVal cosine value of rotation angle theta * @return none. * * The function implements the forward Park transform. * */ static __INLINE void arm_park_f32( float32_t Ialpha, float32_t Ibeta, float32_t * pId, float32_t * pIq, float32_t sinVal, float32_t cosVal) { /* Calculate pId using the equation, pId = Ialpha * cosVal + Ibeta * sinVal */ *pId = Ialpha * cosVal + Ibeta * sinVal; /* Calculate pIq using the equation, pIq = - Ialpha * sinVal + Ibeta * cosVal */ *pIq = -Ialpha * sinVal + Ibeta * cosVal; } /** * @brief Park transform for Q31 version * @param[in] Ialpha input two-phase vector coordinate alpha * @param[in] Ibeta input two-phase vector coordinate beta * @param[out] *pId points to output rotor reference frame d * @param[out] *pIq points to output rotor reference frame q * @param[in] sinVal sine value of rotation angle theta * @param[in] cosVal cosine value of rotation angle theta * @return none. * * Scaling and Overflow Behavior: * \par * The function is implemented using an internal 32-bit accumulator. * The accumulator maintains 1.31 format by truncating lower 31 bits of the intermediate multiplication in 2.62 format. * There is saturation on the addition and subtraction, hence there is no risk of overflow. */ static __INLINE void arm_park_q31( q31_t Ialpha, q31_t Ibeta, q31_t * pId, q31_t * pIq, q31_t sinVal, q31_t cosVal) { q31_t product1, product2; /* Temporary variables used to store intermediate results */ q31_t product3, product4; /* Temporary variables used to store intermediate results */ /* Intermediate product is calculated by (Ialpha * cosVal) */ product1 = (q31_t) (((q63_t) (Ialpha) * (cosVal)) >> 31); /* Intermediate product is calculated by (Ibeta * sinVal) */ product2 = (q31_t) (((q63_t) (Ibeta) * (sinVal)) >> 31); /* Intermediate product is calculated by (Ialpha * sinVal) */ product3 = (q31_t) (((q63_t) (Ialpha) * (sinVal)) >> 31); /* Intermediate product is calculated by (Ibeta * cosVal) */ product4 = (q31_t) (((q63_t) (Ibeta) * (cosVal)) >> 31); /* Calculate pId by adding the two intermediate products 1 and 2 */ *pId = __QADD(product1, product2); /* Calculate pIq by subtracting the two intermediate products 3 from 4 */ *pIq = __QSUB(product4, product3); } /** * @} end of park group */ /** * @brief Converts the elements of the Q7 vector to floating-point vector. * @param[in] *pSrc is input pointer * @param[out] *pDst is output pointer * @param[in] blockSize is the number of samples to process * @return none. */ void arm_q7_to_float( q7_t * pSrc, float32_t * pDst, uint32_t blockSize); /** * @ingroup groupController */ /** * @defgroup inv_park Vector Inverse Park transform * Inverse Park transform converts the input flux and torque components to two-coordinate vector. * * The function operates on a single sample of data and each call to the function returns the processed output. * The library provides separate functions for Q31 and floating-point data types. * \par Algorithm * \image html parkInvFormula.gif * where pIalpha and pIbeta are the stator vector components, * Id and Iq are rotor vector components and cosVal and sinVal are the * cosine and sine values of theta (rotor flux position). * \par Fixed-Point Behavior * Care must be taken when using the Q31 version of the Park transform. * In particular, the overflow and saturation behavior of the accumulator used must be considered. * Refer to the function specific documentation below for usage guidelines. */ /** * @addtogroup inv_park * @{ */ /** * @brief Floating-point Inverse Park transform * @param[in] Id input coordinate of rotor reference frame d * @param[in] Iq input coordinate of rotor reference frame q * @param[out] *pIalpha points to output two-phase orthogonal vector axis alpha * @param[out] *pIbeta points to output two-phase orthogonal vector axis beta * @param[in] sinVal sine value of rotation angle theta * @param[in] cosVal cosine value of rotation angle theta * @return none. */ static __INLINE void arm_inv_park_f32( float32_t Id, float32_t Iq, float32_t * pIalpha, float32_t * pIbeta, float32_t sinVal, float32_t cosVal) { /* Calculate pIalpha using the equation, pIalpha = Id * cosVal - Iq * sinVal */ *pIalpha = Id * cosVal - Iq * sinVal; /* Calculate pIbeta using the equation, pIbeta = Id * sinVal + Iq * cosVal */ *pIbeta = Id * sinVal + Iq * cosVal; } /** * @brief Inverse Park transform for Q31 version * @param[in] Id input coordinate of rotor reference frame d * @param[in] Iq input coordinate of rotor reference frame q * @param[out] *pIalpha points to output two-phase orthogonal vector axis alpha * @param[out] *pIbeta points to output two-phase orthogonal vector axis beta * @param[in] sinVal sine value of rotation angle theta * @param[in] cosVal cosine value of rotation angle theta * @return none. * * Scaling and Overflow Behavior: * \par * The function is implemented using an internal 32-bit accumulator. * The accumulator maintains 1.31 format by truncating lower 31 bits of the intermediate multiplication in 2.62 format. * There is saturation on the addition, hence there is no risk of overflow. */ static __INLINE void arm_inv_park_q31( q31_t Id, q31_t Iq, q31_t * pIalpha, q31_t * pIbeta, q31_t sinVal, q31_t cosVal) { q31_t product1, product2; /* Temporary variables used to store intermediate results */ q31_t product3, product4; /* Temporary variables used to store intermediate results */ /* Intermediate product is calculated by (Id * cosVal) */ product1 = (q31_t) (((q63_t) (Id) * (cosVal)) >> 31); /* Intermediate product is calculated by (Iq * sinVal) */ product2 = (q31_t) (((q63_t) (Iq) * (sinVal)) >> 31); /* Intermediate product is calculated by (Id * sinVal) */ product3 = (q31_t) (((q63_t) (Id) * (sinVal)) >> 31); /* Intermediate product is calculated by (Iq * cosVal) */ product4 = (q31_t) (((q63_t) (Iq) * (cosVal)) >> 31); /* Calculate pIalpha by using the two intermediate products 1 and 2 */ *pIalpha = __QSUB(product1, product2); /* Calculate pIbeta by using the two intermediate products 3 and 4 */ *pIbeta = __QADD(product4, product3); } /** * @} end of Inverse park group */ /** * @brief Converts the elements of the Q31 vector to floating-point vector. * @param[in] *pSrc is input pointer * @param[out] *pDst is output pointer * @param[in] blockSize is the number of samples to process * @return none. */ void arm_q31_to_float( q31_t * pSrc, float32_t * pDst, uint32_t blockSize); /** * @ingroup groupInterpolation */ /** * @defgroup LinearInterpolate Linear Interpolation * * Linear interpolation is a method of curve fitting using linear polynomials. * Linear interpolation works by effectively drawing a straight line between two neighboring samples and returning the appropriate point along that line * * \par * \image html LinearInterp.gif "Linear interpolation" * * \par * A Linear Interpolate function calculates an output value(y), for the input(x) * using linear interpolation of the input values x0, x1( nearest input values) and the output values y0 and y1(nearest output values) * * \par Algorithm: *
   *       y = y0 + (x - x0) * ((y1 - y0)/(x1-x0))
   *       where x0, x1 are nearest values of input x
   *             y0, y1 are nearest values to output y
   * 
* * \par * This set of functions implements Linear interpolation process * for Q7, Q15, Q31, and floating-point data types. The functions operate on a single * sample of data and each call to the function returns a single processed value. * S points to an instance of the Linear Interpolate function data structure. * x is the input sample value. The functions returns the output value. * * \par * if x is outside of the table boundary, Linear interpolation returns first value of the table * if x is below input range and returns last value of table if x is above range. */ /** * @addtogroup LinearInterpolate * @{ */ /** * @brief Process function for the floating-point Linear Interpolation Function. * @param[in,out] *S is an instance of the floating-point Linear Interpolation structure * @param[in] x input sample to process * @return y processed output sample. * */ static __INLINE float32_t arm_linear_interp_f32( arm_linear_interp_instance_f32 * S, float32_t x) { float32_t y; float32_t x0, x1; /* Nearest input values */ float32_t y0, y1; /* Nearest output values */ float32_t xSpacing = S->xSpacing; /* spacing between input values */ int32_t i; /* Index variable */ float32_t *pYData = S->pYData; /* pointer to output table */ /* Calculation of index */ i = (int32_t) ((x - S->x1) / xSpacing); if(i < 0) { /* Iniatilize output for below specified range as least output value of table */ y = pYData[0]; } else if((uint32_t)i >= S->nValues) { /* Iniatilize output for above specified range as last output value of table */ y = pYData[S->nValues - 1]; } else { /* Calculation of nearest input values */ x0 = S->x1 + i * xSpacing; x1 = S->x1 + (i + 1) * xSpacing; /* Read of nearest output values */ y0 = pYData[i]; y1 = pYData[i + 1]; /* Calculation of output */ y = y0 + (x - x0) * ((y1 - y0) / (x1 - x0)); } /* returns output value */ return (y); } /** * * @brief Process function for the Q31 Linear Interpolation Function. * @param[in] *pYData pointer to Q31 Linear Interpolation table * @param[in] x input sample to process * @param[in] nValues number of table values * @return y processed output sample. * * \par * Input sample x is in 12.20 format which contains 12 bits for table index and 20 bits for fractional part. * This function can support maximum of table size 2^12. * */ static __INLINE q31_t arm_linear_interp_q31( q31_t * pYData, q31_t x, uint32_t nValues) { q31_t y; /* output */ q31_t y0, y1; /* Nearest output values */ q31_t fract; /* fractional part */ int32_t index; /* Index to read nearest output values */ /* Input is in 12.20 format */ /* 12 bits for the table index */ /* Index value calculation */ index = ((x & 0xFFF00000) >> 20); if(index >= (int32_t)(nValues - 1)) { return (pYData[nValues - 1]); } else if(index < 0) { return (pYData[0]); } else { /* 20 bits for the fractional part */ /* shift left by 11 to keep fract in 1.31 format */ fract = (x & 0x000FFFFF) << 11; /* Read two nearest output values from the index in 1.31(q31) format */ y0 = pYData[index]; y1 = pYData[index + 1u]; /* Calculation of y0 * (1-fract) and y is in 2.30 format */ y = ((q31_t) ((q63_t) y0 * (0x7FFFFFFF - fract) >> 32)); /* Calculation of y0 * (1-fract) + y1 *fract and y is in 2.30 format */ y += ((q31_t) (((q63_t) y1 * fract) >> 32)); /* Convert y to 1.31 format */ return (y << 1u); } } /** * * @brief Process function for the Q15 Linear Interpolation Function. * @param[in] *pYData pointer to Q15 Linear Interpolation table * @param[in] x input sample to process * @param[in] nValues number of table values * @return y processed output sample. * * \par * Input sample x is in 12.20 format which contains 12 bits for table index and 20 bits for fractional part. * This function can support maximum of table size 2^12. * */ static __INLINE q15_t arm_linear_interp_q15( q15_t * pYData, q31_t x, uint32_t nValues) { q63_t y; /* output */ q15_t y0, y1; /* Nearest output values */ q31_t fract; /* fractional part */ int32_t index; /* Index to read nearest output values */ /* Input is in 12.20 format */ /* 12 bits for the table index */ /* Index value calculation */ index = ((x & 0xFFF00000) >> 20u); if(index >= (int32_t)(nValues - 1)) { return (pYData[nValues - 1]); } else if(index < 0) { return (pYData[0]); } else { /* 20 bits for the fractional part */ /* fract is in 12.20 format */ fract = (x & 0x000FFFFF); /* Read two nearest output values from the index */ y0 = pYData[index]; y1 = pYData[index + 1u]; /* Calculation of y0 * (1-fract) and y is in 13.35 format */ y = ((q63_t) y0 * (0xFFFFF - fract)); /* Calculation of (y0 * (1-fract) + y1 * fract) and y is in 13.35 format */ y += ((q63_t) y1 * (fract)); /* convert y to 1.15 format */ return (y >> 20); } } /** * * @brief Process function for the Q7 Linear Interpolation Function. * @param[in] *pYData pointer to Q7 Linear Interpolation table * @param[in] x input sample to process * @param[in] nValues number of table values * @return y processed output sample. * * \par * Input sample x is in 12.20 format which contains 12 bits for table index and 20 bits for fractional part. * This function can support maximum of table size 2^12. */ static __INLINE q7_t arm_linear_interp_q7( q7_t * pYData, q31_t x, uint32_t nValues) { q31_t y; /* output */ q7_t y0, y1; /* Nearest output values */ q31_t fract; /* fractional part */ uint32_t index; /* Index to read nearest output values */ /* Input is in 12.20 format */ /* 12 bits for the table index */ /* Index value calculation */ if (x < 0) { return (pYData[0]); } index = (x >> 20) & 0xfff; if(index >= (nValues - 1)) { return (pYData[nValues - 1]); } else { /* 20 bits for the fractional part */ /* fract is in 12.20 format */ fract = (x & 0x000FFFFF); /* Read two nearest output values from the index and are in 1.7(q7) format */ y0 = pYData[index]; y1 = pYData[index + 1u]; /* Calculation of y0 * (1-fract ) and y is in 13.27(q27) format */ y = ((y0 * (0xFFFFF - fract))); /* Calculation of y1 * fract + y0 * (1-fract) and y is in 13.27(q27) format */ y += (y1 * fract); /* convert y to 1.7(q7) format */ return (y >> 20u); } } /** * @} end of LinearInterpolate group */ /** * @brief Fast approximation to the trigonometric sine function for floating-point data. * @param[in] x input value in radians. * @return sin(x). */ float32_t arm_sin_f32( float32_t x); /** * @brief Fast approximation to the trigonometric sine function for Q31 data. * @param[in] x Scaled input value in radians. * @return sin(x). */ q31_t arm_sin_q31( q31_t x); /** * @brief Fast approximation to the trigonometric sine function for Q15 data. * @param[in] x Scaled input value in radians. * @return sin(x). */ q15_t arm_sin_q15( q15_t x); /** * @brief Fast approximation to the trigonometric cosine function for floating-point data. * @param[in] x input value in radians. * @return cos(x). */ float32_t arm_cos_f32( float32_t x); /** * @brief Fast approximation to the trigonometric cosine function for Q31 data. * @param[in] x Scaled input value in radians. * @return cos(x). */ q31_t arm_cos_q31( q31_t x); /** * @brief Fast approximation to the trigonometric cosine function for Q15 data. * @param[in] x Scaled input value in radians. * @return cos(x). */ q15_t arm_cos_q15( q15_t x); /** * @ingroup groupFastMath */ /** * @defgroup SQRT Square Root * * Computes the square root of a number. * There are separate functions for Q15, Q31, and floating-point data types. * The square root function is computed using the Newton-Raphson algorithm. * This is an iterative algorithm of the form: *
   *      x1 = x0 - f(x0)/f'(x0)
   * 
* where x1 is the current estimate, * x0 is the previous estimate, and * f'(x0) is the derivative of f() evaluated at x0. * For the square root function, the algorithm reduces to: *
   *     x0 = in/2                         [initial guess]
   *     x1 = 1/2 * ( x0 + in / x0)        [each iteration]
   * 
*/ /** * @addtogroup SQRT * @{ */ /** * @brief Floating-point square root function. * @param[in] in input value. * @param[out] *pOut square root of input value. * @return The function returns ARM_MATH_SUCCESS if input value is positive value or ARM_MATH_ARGUMENT_ERROR if * in is negative value and returns zero output for negative values. */ static __INLINE arm_status arm_sqrt_f32( float32_t in, float32_t * pOut) { if(in >= 0.0f) { // #if __FPU_USED #if (__FPU_USED == 1) && defined ( __CC_ARM ) *pOut = __sqrtf(in); #else *pOut = sqrtf(in); #endif return (ARM_MATH_SUCCESS); } else { *pOut = 0.0f; return (ARM_MATH_ARGUMENT_ERROR); } } /** * @brief Q31 square root function. * @param[in] in input value. The range of the input value is [0 +1) or 0x00000000 to 0x7FFFFFFF. * @param[out] *pOut square root of input value. * @return The function returns ARM_MATH_SUCCESS if input value is positive value or ARM_MATH_ARGUMENT_ERROR if * in is negative value and returns zero output for negative values. */ arm_status arm_sqrt_q31( q31_t in, q31_t * pOut); /** * @brief Q15 square root function. * @param[in] in input value. The range of the input value is [0 +1) or 0x0000 to 0x7FFF. * @param[out] *pOut square root of input value. * @return The function returns ARM_MATH_SUCCESS if input value is positive value or ARM_MATH_ARGUMENT_ERROR if * in is negative value and returns zero output for negative values. */ arm_status arm_sqrt_q15( q15_t in, q15_t * pOut); /** * @} end of SQRT group */ /** * @brief floating-point Circular write function. */ static __INLINE void arm_circularWrite_f32( int32_t * circBuffer, int32_t L, uint16_t * writeOffset, int32_t bufferInc, const int32_t * src, int32_t srcInc, uint32_t blockSize) { uint32_t i = 0u; int32_t wOffset; /* Copy the value of Index pointer that points * to the current location where the input samples to be copied */ wOffset = *writeOffset; /* Loop over the blockSize */ i = blockSize; while(i > 0u) { /* copy the input sample to the circular buffer */ circBuffer[wOffset] = *src; /* Update the input pointer */ src += srcInc; /* Circularly update wOffset. Watch out for positive and negative value */ wOffset += bufferInc; if(wOffset >= L) wOffset -= L; /* Decrement the loop counter */ i--; } /* Update the index pointer */ *writeOffset = wOffset; } /** * @brief floating-point Circular Read function. */ static __INLINE void arm_circularRead_f32( int32_t * circBuffer, int32_t L, int32_t * readOffset, int32_t bufferInc, int32_t * dst, int32_t * dst_base, int32_t dst_length, int32_t dstInc, uint32_t blockSize) { uint32_t i = 0u; int32_t rOffset, dst_end; /* Copy the value of Index pointer that points * to the current location from where the input samples to be read */ rOffset = *readOffset; dst_end = (int32_t) (dst_base + dst_length); /* Loop over the blockSize */ i = blockSize; while(i > 0u) { /* copy the sample from the circular buffer to the destination buffer */ *dst = circBuffer[rOffset]; /* Update the input pointer */ dst += dstInc; if(dst == (int32_t *) dst_end) { dst = dst_base; } /* Circularly update rOffset. Watch out for positive and negative value */ rOffset += bufferInc; if(rOffset >= L) { rOffset -= L; } /* Decrement the loop counter */ i--; } /* Update the index pointer */ *readOffset = rOffset; } /** * @brief Q15 Circular write function. */ static __INLINE void arm_circularWrite_q15( q15_t * circBuffer, int32_t L, uint16_t * writeOffset, int32_t bufferInc, const q15_t * src, int32_t srcInc, uint32_t blockSize) { uint32_t i = 0u; int32_t wOffset; /* Copy the value of Index pointer that points * to the current location where the input samples to be copied */ wOffset = *writeOffset; /* Loop over the blockSize */ i = blockSize; while(i > 0u) { /* copy the input sample to the circular buffer */ circBuffer[wOffset] = *src; /* Update the input pointer */ src += srcInc; /* Circularly update wOffset. Watch out for positive and negative value */ wOffset += bufferInc; if(wOffset >= L) wOffset -= L; /* Decrement the loop counter */ i--; } /* Update the index pointer */ *writeOffset = wOffset; } /** * @brief Q15 Circular Read function. */ static __INLINE void arm_circularRead_q15( q15_t * circBuffer, int32_t L, int32_t * readOffset, int32_t bufferInc, q15_t * dst, q15_t * dst_base, int32_t dst_length, int32_t dstInc, uint32_t blockSize) { uint32_t i = 0; int32_t rOffset, dst_end; /* Copy the value of Index pointer that points * to the current location from where the input samples to be read */ rOffset = *readOffset; dst_end = (int32_t) (dst_base + dst_length); /* Loop over the blockSize */ i = blockSize; while(i > 0u) { /* copy the sample from the circular buffer to the destination buffer */ *dst = circBuffer[rOffset]; /* Update the input pointer */ dst += dstInc; if(dst == (q15_t *) dst_end) { dst = dst_base; } /* Circularly update wOffset. Watch out for positive and negative value */ rOffset += bufferInc; if(rOffset >= L) { rOffset -= L; } /* Decrement the loop counter */ i--; } /* Update the index pointer */ *readOffset = rOffset; } /** * @brief Q7 Circular write function. */ static __INLINE void arm_circularWrite_q7( q7_t * circBuffer, int32_t L, uint16_t * writeOffset, int32_t bufferInc, const q7_t * src, int32_t srcInc, uint32_t blockSize) { uint32_t i = 0u; int32_t wOffset; /* Copy the value of Index pointer that points * to the current location where the input samples to be copied */ wOffset = *writeOffset; /* Loop over the blockSize */ i = blockSize; while(i > 0u) { /* copy the input sample to the circular buffer */ circBuffer[wOffset] = *src; /* Update the input pointer */ src += srcInc; /* Circularly update wOffset. Watch out for positive and negative value */ wOffset += bufferInc; if(wOffset >= L) wOffset -= L; /* Decrement the loop counter */ i--; } /* Update the index pointer */ *writeOffset = wOffset; } /** * @brief Q7 Circular Read function. */ static __INLINE void arm_circularRead_q7( q7_t * circBuffer, int32_t L, int32_t * readOffset, int32_t bufferInc, q7_t * dst, q7_t * dst_base, int32_t dst_length, int32_t dstInc, uint32_t blockSize) { uint32_t i = 0; int32_t rOffset, dst_end; /* Copy the value of Index pointer that points * to the current location from where the input samples to be read */ rOffset = *readOffset; dst_end = (int32_t) (dst_base + dst_length); /* Loop over the blockSize */ i = blockSize; while(i > 0u) { /* copy the sample from the circular buffer to the destination buffer */ *dst = circBuffer[rOffset]; /* Update the input pointer */ dst += dstInc; if(dst == (q7_t *) dst_end) { dst = dst_base; } /* Circularly update rOffset. Watch out for positive and negative value */ rOffset += bufferInc; if(rOffset >= L) { rOffset -= L; } /* Decrement the loop counter */ i--; } /* Update the index pointer */ *readOffset = rOffset; } /** * @brief Sum of the squares of the elements of a Q31 vector. * @param[in] *pSrc is input pointer * @param[in] blockSize is the number of samples to process * @param[out] *pResult is output value. * @return none. */ void arm_power_q31( q31_t * pSrc, uint32_t blockSize, q63_t * pResult); /** * @brief Sum of the squares of the elements of a floating-point vector. * @param[in] *pSrc is input pointer * @param[in] blockSize is the number of samples to process * @param[out] *pResult is output value. * @return none. */ void arm_power_f32( float32_t * pSrc, uint32_t blockSize, float32_t * pResult); /** * @brief Sum of the squares of the elements of a Q15 vector. * @param[in] *pSrc is input pointer * @param[in] blockSize is the number of samples to process * @param[out] *pResult is output value. * @return none. */ void arm_power_q15( q15_t * pSrc, uint32_t blockSize, q63_t * pResult); /** * @brief Sum of the squares of the elements of a Q7 vector. * @param[in] *pSrc is input pointer * @param[in] blockSize is the number of samples to process * @param[out] *pResult is output value. * @return none. */ void arm_power_q7( q7_t * pSrc, uint32_t blockSize, q31_t * pResult); /** * @brief Mean value of a Q7 vector. * @param[in] *pSrc is input pointer * @param[in] blockSize is the number of samples to process * @param[out] *pResult is output value. * @return none. */ void arm_mean_q7( q7_t * pSrc, uint32_t blockSize, q7_t * pResult); /** * @brief Mean value of a Q15 vector. * @param[in] *pSrc is input pointer * @param[in] blockSize is the number of samples to process * @param[out] *pResult is output value. * @return none. */ void arm_mean_q15( q15_t * pSrc, uint32_t blockSize, q15_t * pResult); /** * @brief Mean value of a Q31 vector. * @param[in] *pSrc is input pointer * @param[in] blockSize is the number of samples to process * @param[out] *pResult is output value. * @return none. */ void arm_mean_q31( q31_t * pSrc, uint32_t blockSize, q31_t * pResult); /** * @brief Mean value of a floating-point vector. * @param[in] *pSrc is input pointer * @param[in] blockSize is the number of samples to process * @param[out] *pResult is output value. * @return none. */ void arm_mean_f32( float32_t * pSrc, uint32_t blockSize, float32_t * pResult); /** * @brief Variance of the elements of a floating-point vector. * @param[in] *pSrc is input pointer * @param[in] blockSize is the number of samples to process * @param[out] *pResult is output value. * @return none. */ void arm_var_f32( float32_t * pSrc, uint32_t blockSize, float32_t * pResult); /** * @brief Variance of the elements of a Q31 vector. * @param[in] *pSrc is input pointer * @param[in] blockSize is the number of samples to process * @param[out] *pResult is output value. * @return none. */ void arm_var_q31( q31_t * pSrc, uint32_t blockSize, q31_t * pResult); /** * @brief Variance of the elements of a Q15 vector. * @param[in] *pSrc is input pointer * @param[in] blockSize is the number of samples to process * @param[out] *pResult is output value. * @return none. */ void arm_var_q15( q15_t * pSrc, uint32_t blockSize, q15_t * pResult); /** * @brief Root Mean Square of the elements of a floating-point vector. * @param[in] *pSrc is input pointer * @param[in] blockSize is the number of samples to process * @param[out] *pResult is output value. * @return none. */ void arm_rms_f32( float32_t * pSrc, uint32_t blockSize, float32_t * pResult); /** * @brief Root Mean Square of the elements of a Q31 vector. * @param[in] *pSrc is input pointer * @param[in] blockSize is the number of samples to process * @param[out] *pResult is output value. * @return none. */ void arm_rms_q31( q31_t * pSrc, uint32_t blockSize, q31_t * pResult); /** * @brief Root Mean Square of the elements of a Q15 vector. * @param[in] *pSrc is input pointer * @param[in] blockSize is the number of samples to process * @param[out] *pResult is output value. * @return none. */ void arm_rms_q15( q15_t * pSrc, uint32_t blockSize, q15_t * pResult); /** * @brief Standard deviation of the elements of a floating-point vector. * @param[in] *pSrc is input pointer * @param[in] blockSize is the number of samples to process * @param[out] *pResult is output value. * @return none. */ void arm_std_f32( float32_t * pSrc, uint32_t blockSize, float32_t * pResult); /** * @brief Standard deviation of the elements of a Q31 vector. * @param[in] *pSrc is input pointer * @param[in] blockSize is the number of samples to process * @param[out] *pResult is output value. * @return none. */ void arm_std_q31( q31_t * pSrc, uint32_t blockSize, q31_t * pResult); /** * @brief Standard deviation of the elements of a Q15 vector. * @param[in] *pSrc is input pointer * @param[in] blockSize is the number of samples to process * @param[out] *pResult is output value. * @return none. */ void arm_std_q15( q15_t * pSrc, uint32_t blockSize, q15_t * pResult); /** * @brief Floating-point complex magnitude * @param[in] *pSrc points to the complex input vector * @param[out] *pDst points to the real output vector * @param[in] numSamples number of complex samples in the input vector * @return none. */ void arm_cmplx_mag_f32( float32_t * pSrc, float32_t * pDst, uint32_t numSamples); /** * @brief Q31 complex magnitude * @param[in] *pSrc points to the complex input vector * @param[out] *pDst points to the real output vector * @param[in] numSamples number of complex samples in the input vector * @return none. */ void arm_cmplx_mag_q31( q31_t * pSrc, q31_t * pDst, uint32_t numSamples); /** * @brief Q15 complex magnitude * @param[in] *pSrc points to the complex input vector * @param[out] *pDst points to the real output vector * @param[in] numSamples number of complex samples in the input vector * @return none. */ void arm_cmplx_mag_q15( q15_t * pSrc, q15_t * pDst, uint32_t numSamples); /** * @brief Q15 complex dot product * @param[in] *pSrcA points to the first input vector * @param[in] *pSrcB points to the second input vector * @param[in] numSamples number of complex samples in each vector * @param[out] *realResult real part of the result returned here * @param[out] *imagResult imaginary part of the result returned here * @return none. */ void arm_cmplx_dot_prod_q15( q15_t * pSrcA, q15_t * pSrcB, uint32_t numSamples, q31_t * realResult, q31_t * imagResult); /** * @brief Q31 complex dot product * @param[in] *pSrcA points to the first input vector * @param[in] *pSrcB points to the second input vector * @param[in] numSamples number of complex samples in each vector * @param[out] *realResult real part of the result returned here * @param[out] *imagResult imaginary part of the result returned here * @return none. */ void arm_cmplx_dot_prod_q31( q31_t * pSrcA, q31_t * pSrcB, uint32_t numSamples, q63_t * realResult, q63_t * imagResult); /** * @brief Floating-point complex dot product * @param[in] *pSrcA points to the first input vector * @param[in] *pSrcB points to the second input vector * @param[in] numSamples number of complex samples in each vector * @param[out] *realResult real part of the result returned here * @param[out] *imagResult imaginary part of the result returned here * @return none. */ void arm_cmplx_dot_prod_f32( float32_t * pSrcA, float32_t * pSrcB, uint32_t numSamples, float32_t * realResult, float32_t * imagResult); /** * @brief Q15 complex-by-real multiplication * @param[in] *pSrcCmplx points to the complex input vector * @param[in] *pSrcReal points to the real input vector * @param[out] *pCmplxDst points to the complex output vector * @param[in] numSamples number of samples in each vector * @return none. */ void arm_cmplx_mult_real_q15( q15_t * pSrcCmplx, q15_t * pSrcReal, q15_t * pCmplxDst, uint32_t numSamples); /** * @brief Q31 complex-by-real multiplication * @param[in] *pSrcCmplx points to the complex input vector * @param[in] *pSrcReal points to the real input vector * @param[out] *pCmplxDst points to the complex output vector * @param[in] numSamples number of samples in each vector * @return none. */ void arm_cmplx_mult_real_q31( q31_t * pSrcCmplx, q31_t * pSrcReal, q31_t * pCmplxDst, uint32_t numSamples); /** * @brief Floating-point complex-by-real multiplication * @param[in] *pSrcCmplx points to the complex input vector * @param[in] *pSrcReal points to the real input vector * @param[out] *pCmplxDst points to the complex output vector * @param[in] numSamples number of samples in each vector * @return none. */ void arm_cmplx_mult_real_f32( float32_t * pSrcCmplx, float32_t * pSrcReal, float32_t * pCmplxDst, uint32_t numSamples); /** * @brief Minimum value of a Q7 vector. * @param[in] *pSrc is input pointer * @param[in] blockSize is the number of samples to process * @param[out] *result is output pointer * @param[in] index is the array index of the minimum value in the input buffer. * @return none. */ void arm_min_q7( q7_t * pSrc, uint32_t blockSize, q7_t * result, uint32_t * index); /** * @brief Minimum value of a Q15 vector. * @param[in] *pSrc is input pointer * @param[in] blockSize is the number of samples to process * @param[out] *pResult is output pointer * @param[in] *pIndex is the array index of the minimum value in the input buffer. * @return none. */ void arm_min_q15( q15_t * pSrc, uint32_t blockSize, q15_t * pResult, uint32_t * pIndex); /** * @brief Minimum value of a Q31 vector. * @param[in] *pSrc is input pointer * @param[in] blockSize is the number of samples to process * @param[out] *pResult is output pointer * @param[out] *pIndex is the array index of the minimum value in the input buffer. * @return none. */ void arm_min_q31( q31_t * pSrc, uint32_t blockSize, q31_t * pResult, uint32_t * pIndex); /** * @brief Minimum value of a floating-point vector. * @param[in] *pSrc is input pointer * @param[in] blockSize is the number of samples to process * @param[out] *pResult is output pointer * @param[out] *pIndex is the array index of the minimum value in the input buffer. * @return none. */ void arm_min_f32( float32_t * pSrc, uint32_t blockSize, float32_t * pResult, uint32_t * pIndex); /** * @brief Maximum value of a Q7 vector. * @param[in] *pSrc points to the input buffer * @param[in] blockSize length of the input vector * @param[out] *pResult maximum value returned here * @param[out] *pIndex index of maximum value returned here * @return none. */ void arm_max_q7( q7_t * pSrc, uint32_t blockSize, q7_t * pResult, uint32_t * pIndex); /** * @brief Maximum value of a Q15 vector. * @param[in] *pSrc points to the input buffer * @param[in] blockSize length of the input vector * @param[out] *pResult maximum value returned here * @param[out] *pIndex index of maximum value returned here * @return none. */ void arm_max_q15( q15_t * pSrc, uint32_t blockSize, q15_t * pResult, uint32_t * pIndex); /** * @brief Maximum value of a Q31 vector. * @param[in] *pSrc points to the input buffer * @param[in] blockSize length of the input vector * @param[out] *pResult maximum value returned here * @param[out] *pIndex index of maximum value returned here * @return none. */ void arm_max_q31( q31_t * pSrc, uint32_t blockSize, q31_t * pResult, uint32_t * pIndex); /** * @brief Maximum value of a floating-point vector. * @param[in] *pSrc points to the input buffer * @param[in] blockSize length of the input vector * @param[out] *pResult maximum value returned here * @param[out] *pIndex index of maximum value returned here * @return none. */ void arm_max_f32( float32_t * pSrc, uint32_t blockSize, float32_t * pResult, uint32_t * pIndex); /** * @brief Q15 complex-by-complex multiplication * @param[in] *pSrcA points to the first input vector * @param[in] *pSrcB points to the second input vector * @param[out] *pDst points to the output vector * @param[in] numSamples number of complex samples in each vector * @return none. */ void arm_cmplx_mult_cmplx_q15( q15_t * pSrcA, q15_t * pSrcB, q15_t * pDst, uint32_t numSamples); /** * @brief Q31 complex-by-complex multiplication * @param[in] *pSrcA points to the first input vector * @param[in] *pSrcB points to the second input vector * @param[out] *pDst points to the output vector * @param[in] numSamples number of complex samples in each vector * @return none. */ void arm_cmplx_mult_cmplx_q31( q31_t * pSrcA, q31_t * pSrcB, q31_t * pDst, uint32_t numSamples); /** * @brief Floating-point complex-by-complex multiplication * @param[in] *pSrcA points to the first input vector * @param[in] *pSrcB points to the second input vector * @param[out] *pDst points to the output vector * @param[in] numSamples number of complex samples in each vector * @return none. */ void arm_cmplx_mult_cmplx_f32( float32_t * pSrcA, float32_t * pSrcB, float32_t * pDst, uint32_t numSamples); /** * @brief Converts the elements of the floating-point vector to Q31 vector. * @param[in] *pSrc points to the floating-point input vector * @param[out] *pDst points to the Q31 output vector * @param[in] blockSize length of the input vector * @return none. */ void arm_float_to_q31( float32_t * pSrc, q31_t * pDst, uint32_t blockSize); /** * @brief Converts the elements of the floating-point vector to Q15 vector. * @param[in] *pSrc points to the floating-point input vector * @param[out] *pDst points to the Q15 output vector * @param[in] blockSize length of the input vector * @return none */ void arm_float_to_q15( float32_t * pSrc, q15_t * pDst, uint32_t blockSize); /** * @brief Converts the elements of the floating-point vector to Q7 vector. * @param[in] *pSrc points to the floating-point input vector * @param[out] *pDst points to the Q7 output vector * @param[in] blockSize length of the input vector * @return none */ void arm_float_to_q7( float32_t * pSrc, q7_t * pDst, uint32_t blockSize); /** * @brief Converts the elements of the Q31 vector to Q15 vector. * @param[in] *pSrc is input pointer * @param[out] *pDst is output pointer * @param[in] blockSize is the number of samples to process * @return none. */ void arm_q31_to_q15( q31_t * pSrc, q15_t * pDst, uint32_t blockSize); /** * @brief Converts the elements of the Q31 vector to Q7 vector. * @param[in] *pSrc is input pointer * @param[out] *pDst is output pointer * @param[in] blockSize is the number of samples to process * @return none. */ void arm_q31_to_q7( q31_t * pSrc, q7_t * pDst, uint32_t blockSize); /** * @brief Converts the elements of the Q15 vector to floating-point vector. * @param[in] *pSrc is input pointer * @param[out] *pDst is output pointer * @param[in] blockSize is the number of samples to process * @return none. */ void arm_q15_to_float( q15_t * pSrc, float32_t * pDst, uint32_t blockSize); /** * @brief Converts the elements of the Q15 vector to Q31 vector. * @param[in] *pSrc is input pointer * @param[out] *pDst is output pointer * @param[in] blockSize is the number of samples to process * @return none. */ void arm_q15_to_q31( q15_t * pSrc, q31_t * pDst, uint32_t blockSize); /** * @brief Converts the elements of the Q15 vector to Q7 vector. * @param[in] *pSrc is input pointer * @param[out] *pDst is output pointer * @param[in] blockSize is the number of samples to process * @return none. */ void arm_q15_to_q7( q15_t * pSrc, q7_t * pDst, uint32_t blockSize); /** * @ingroup groupInterpolation */ /** * @defgroup BilinearInterpolate Bilinear Interpolation * * Bilinear interpolation is an extension of linear interpolation applied to a two dimensional grid. * The underlying function f(x, y) is sampled on a regular grid and the interpolation process * determines values between the grid points. * Bilinear interpolation is equivalent to two step linear interpolation, first in the x-dimension and then in the y-dimension. * Bilinear interpolation is often used in image processing to rescale images. * The CMSIS DSP library provides bilinear interpolation functions for Q7, Q15, Q31, and floating-point data types. * * Algorithm * \par * The instance structure used by the bilinear interpolation functions describes a two dimensional data table. * For floating-point, the instance structure is defined as: *
   *   typedef struct
   *   {
   *     uint16_t numRows;
   *     uint16_t numCols;
   *     float32_t *pData;
   * } arm_bilinear_interp_instance_f32;
   * 
* * \par * where numRows specifies the number of rows in the table; * numCols specifies the number of columns in the table; * and pData points to an array of size numRows*numCols values. * The data table pTable is organized in row order and the supplied data values fall on integer indexes. * That is, table element (x,y) is located at pTable[x + y*numCols] where x and y are integers. * * \par * Let (x, y) specify the desired interpolation point. Then define: *
   *     XF = floor(x)
   *     YF = floor(y)
   * 
* \par * The interpolated output point is computed as: *
   *  f(x, y) = f(XF, YF) * (1-(x-XF)) * (1-(y-YF))
   *           + f(XF+1, YF) * (x-XF)*(1-(y-YF))
   *           + f(XF, YF+1) * (1-(x-XF))*(y-YF)
   *           + f(XF+1, YF+1) * (x-XF)*(y-YF)
   * 
* Note that the coordinates (x, y) contain integer and fractional components. * The integer components specify which portion of the table to use while the * fractional components control the interpolation processor. * * \par * if (x,y) are outside of the table boundary, Bilinear interpolation returns zero output. */ /** * @addtogroup BilinearInterpolate * @{ */ /** * * @brief Floating-point bilinear interpolation. * @param[in,out] *S points to an instance of the interpolation structure. * @param[in] X interpolation coordinate. * @param[in] Y interpolation coordinate. * @return out interpolated value. */ static __INLINE float32_t arm_bilinear_interp_f32( const arm_bilinear_interp_instance_f32 * S, float32_t X, float32_t Y) { float32_t out; float32_t f00, f01, f10, f11; float32_t *pData = S->pData; int32_t xIndex, yIndex, index; float32_t xdiff, ydiff; float32_t b1, b2, b3, b4; xIndex = (int32_t) X; yIndex = (int32_t) Y; /* Care taken for table outside boundary */ /* Returns zero output when values are outside table boundary */ if(xIndex < 0 || xIndex > (S->numRows - 1) || yIndex < 0 || yIndex > (S->numCols - 1)) { return (0); } /* Calculation of index for two nearest points in X-direction */ index = (xIndex - 1) + (yIndex - 1) * S->numCols; /* Read two nearest points in X-direction */ f00 = pData[index]; f01 = pData[index + 1]; /* Calculation of index for two nearest points in Y-direction */ index = (xIndex - 1) + (yIndex) * S->numCols; /* Read two nearest points in Y-direction */ f10 = pData[index]; f11 = pData[index + 1]; /* Calculation of intermediate values */ b1 = f00; b2 = f01 - f00; b3 = f10 - f00; b4 = f00 - f01 - f10 + f11; /* Calculation of fractional part in X */ xdiff = X - xIndex; /* Calculation of fractional part in Y */ ydiff = Y - yIndex; /* Calculation of bi-linear interpolated output */ out = b1 + b2 * xdiff + b3 * ydiff + b4 * xdiff * ydiff; /* return to application */ return (out); } /** * * @brief Q31 bilinear interpolation. * @param[in,out] *S points to an instance of the interpolation structure. * @param[in] X interpolation coordinate in 12.20 format. * @param[in] Y interpolation coordinate in 12.20 format. * @return out interpolated value. */ static __INLINE q31_t arm_bilinear_interp_q31( arm_bilinear_interp_instance_q31 * S, q31_t X, q31_t Y) { q31_t out; /* Temporary output */ q31_t acc = 0; /* output */ q31_t xfract, yfract; /* X, Y fractional parts */ q31_t x1, x2, y1, y2; /* Nearest output values */ int32_t rI, cI; /* Row and column indices */ q31_t *pYData = S->pData; /* pointer to output table values */ uint32_t nCols = S->numCols; /* num of rows */ /* Input is in 12.20 format */ /* 12 bits for the table index */ /* Index value calculation */ rI = ((X & 0xFFF00000) >> 20u); /* Input is in 12.20 format */ /* 12 bits for the table index */ /* Index value calculation */ cI = ((Y & 0xFFF00000) >> 20u); /* Care taken for table outside boundary */ /* Returns zero output when values are outside table boundary */ if(rI < 0 || rI > (S->numRows - 1) || cI < 0 || cI > (S->numCols - 1)) { return (0); } /* 20 bits for the fractional part */ /* shift left xfract by 11 to keep 1.31 format */ xfract = (X & 0x000FFFFF) << 11u; /* Read two nearest output values from the index */ x1 = pYData[(rI) + nCols * (cI)]; x2 = pYData[(rI) + nCols * (cI) + 1u]; /* 20 bits for the fractional part */ /* shift left yfract by 11 to keep 1.31 format */ yfract = (Y & 0x000FFFFF) << 11u; /* Read two nearest output values from the index */ y1 = pYData[(rI) + nCols * (cI + 1)]; y2 = pYData[(rI) + nCols * (cI + 1) + 1u]; /* Calculation of x1 * (1-xfract ) * (1-yfract) and acc is in 3.29(q29) format */ out = ((q31_t) (((q63_t) x1 * (0x7FFFFFFF - xfract)) >> 32)); acc = ((q31_t) (((q63_t) out * (0x7FFFFFFF - yfract)) >> 32)); /* x2 * (xfract) * (1-yfract) in 3.29(q29) and adding to acc */ out = ((q31_t) ((q63_t) x2 * (0x7FFFFFFF - yfract) >> 32)); acc += ((q31_t) ((q63_t) out * (xfract) >> 32)); /* y1 * (1 - xfract) * (yfract) in 3.29(q29) and adding to acc */ out = ((q31_t) ((q63_t) y1 * (0x7FFFFFFF - xfract) >> 32)); acc += ((q31_t) ((q63_t) out * (yfract) >> 32)); /* y2 * (xfract) * (yfract) in 3.29(q29) and adding to acc */ out = ((q31_t) ((q63_t) y2 * (xfract) >> 32)); acc += ((q31_t) ((q63_t) out * (yfract) >> 32)); /* Convert acc to 1.31(q31) format */ return (acc << 2u); } /** * @brief Q15 bilinear interpolation. * @param[in,out] *S points to an instance of the interpolation structure. * @param[in] X interpolation coordinate in 12.20 format. * @param[in] Y interpolation coordinate in 12.20 format. * @return out interpolated value. */ static __INLINE q15_t arm_bilinear_interp_q15( arm_bilinear_interp_instance_q15 * S, q31_t X, q31_t Y) { q63_t acc = 0; /* output */ q31_t out; /* Temporary output */ q15_t x1, x2, y1, y2; /* Nearest output values */ q31_t xfract, yfract; /* X, Y fractional parts */ int32_t rI, cI; /* Row and column indices */ q15_t *pYData = S->pData; /* pointer to output table values */ uint32_t nCols = S->numCols; /* num of rows */ /* Input is in 12.20 format */ /* 12 bits for the table index */ /* Index value calculation */ rI = ((X & 0xFFF00000) >> 20); /* Input is in 12.20 format */ /* 12 bits for the table index */ /* Index value calculation */ cI = ((Y & 0xFFF00000) >> 20); /* Care taken for table outside boundary */ /* Returns zero output when values are outside table boundary */ if(rI < 0 || rI > (S->numRows - 1) || cI < 0 || cI > (S->numCols - 1)) { return (0); } /* 20 bits for the fractional part */ /* xfract should be in 12.20 format */ xfract = (X & 0x000FFFFF); /* Read two nearest output values from the index */ x1 = pYData[(rI) + nCols * (cI)]; x2 = pYData[(rI) + nCols * (cI) + 1u]; /* 20 bits for the fractional part */ /* yfract should be in 12.20 format */ yfract = (Y & 0x000FFFFF); /* Read two nearest output values from the index */ y1 = pYData[(rI) + nCols * (cI + 1)]; y2 = pYData[(rI) + nCols * (cI + 1) + 1u]; /* Calculation of x1 * (1-xfract ) * (1-yfract) and acc is in 13.51 format */ /* x1 is in 1.15(q15), xfract in 12.20 format and out is in 13.35 format */ /* convert 13.35 to 13.31 by right shifting and out is in 1.31 */ out = (q31_t) (((q63_t) x1 * (0xFFFFF - xfract)) >> 4u); acc = ((q63_t) out * (0xFFFFF - yfract)); /* x2 * (xfract) * (1-yfract) in 1.51 and adding to acc */ out = (q31_t) (((q63_t) x2 * (0xFFFFF - yfract)) >> 4u); acc += ((q63_t) out * (xfract)); /* y1 * (1 - xfract) * (yfract) in 1.51 and adding to acc */ out = (q31_t) (((q63_t) y1 * (0xFFFFF - xfract)) >> 4u); acc += ((q63_t) out * (yfract)); /* y2 * (xfract) * (yfract) in 1.51 and adding to acc */ out = (q31_t) (((q63_t) y2 * (xfract)) >> 4u); acc += ((q63_t) out * (yfract)); /* acc is in 13.51 format and down shift acc by 36 times */ /* Convert out to 1.15 format */ return (acc >> 36); } /** * @brief Q7 bilinear interpolation. * @param[in,out] *S points to an instance of the interpolation structure. * @param[in] X interpolation coordinate in 12.20 format. * @param[in] Y interpolation coordinate in 12.20 format. * @return out interpolated value. */ static __INLINE q7_t arm_bilinear_interp_q7( arm_bilinear_interp_instance_q7 * S, q31_t X, q31_t Y) { q63_t acc = 0; /* output */ q31_t out; /* Temporary output */ q31_t xfract, yfract; /* X, Y fractional parts */ q7_t x1, x2, y1, y2; /* Nearest output values */ int32_t rI, cI; /* Row and column indices */ q7_t *pYData = S->pData; /* pointer to output table values */ uint32_t nCols = S->numCols; /* num of rows */ /* Input is in 12.20 format */ /* 12 bits for the table index */ /* Index value calculation */ rI = ((X & 0xFFF00000) >> 20); /* Input is in 12.20 format */ /* 12 bits for the table index */ /* Index value calculation */ cI = ((Y & 0xFFF00000) >> 20); /* Care taken for table outside boundary */ /* Returns zero output when values are outside table boundary */ if(rI < 0 || rI > (S->numRows - 1) || cI < 0 || cI > (S->numCols - 1)) { return (0); } /* 20 bits for the fractional part */ /* xfract should be in 12.20 format */ xfract = (X & 0x000FFFFF); /* Read two nearest output values from the index */ x1 = pYData[(rI) + nCols * (cI)]; x2 = pYData[(rI) + nCols * (cI) + 1u]; /* 20 bits for the fractional part */ /* yfract should be in 12.20 format */ yfract = (Y & 0x000FFFFF); /* Read two nearest output values from the index */ y1 = pYData[(rI) + nCols * (cI + 1)]; y2 = pYData[(rI) + nCols * (cI + 1) + 1u]; /* Calculation of x1 * (1-xfract ) * (1-yfract) and acc is in 16.47 format */ out = ((x1 * (0xFFFFF - xfract))); acc = (((q63_t) out * (0xFFFFF - yfract))); /* x2 * (xfract) * (1-yfract) in 2.22 and adding to acc */ out = ((x2 * (0xFFFFF - yfract))); acc += (((q63_t) out * (xfract))); /* y1 * (1 - xfract) * (yfract) in 2.22 and adding to acc */ out = ((y1 * (0xFFFFF - xfract))); acc += (((q63_t) out * (yfract))); /* y2 * (xfract) * (yfract) in 2.22 and adding to acc */ out = ((y2 * (yfract))); acc += (((q63_t) out * (xfract))); /* acc in 16.47 format and down shift by 40 to convert to 1.7 format */ return (acc >> 40); } /** * @} end of BilinearInterpolate group */ //SMMLAR #define multAcc_32x32_keep32_R(a, x, y) \ a = (q31_t) (((((q63_t) a) << 32) + ((q63_t) x * y) + 0x80000000LL ) >> 32) //SMMLSR #define multSub_32x32_keep32_R(a, x, y) \ a = (q31_t) (((((q63_t) a) << 32) - ((q63_t) x * y) + 0x80000000LL ) >> 32) //SMMULR #define mult_32x32_keep32_R(a, x, y) \ a = (q31_t) (((q63_t) x * y + 0x80000000LL ) >> 32) //SMMLA #define multAcc_32x32_keep32(a, x, y) \ a += (q31_t) (((q63_t) x * y) >> 32) //SMMLS #define multSub_32x32_keep32(a, x, y) \ a -= (q31_t) (((q63_t) x * y) >> 32) //SMMUL #define mult_32x32_keep32(a, x, y) \ a = (q31_t) (((q63_t) x * y ) >> 32) #if defined ( __CC_ARM ) //Keil //Enter low optimization region - place directly above function definition #ifdef ARM_MATH_CM4 #define LOW_OPTIMIZATION_ENTER \ _Pragma ("push") \ _Pragma ("O1") #else #define LOW_OPTIMIZATION_ENTER #endif //Exit low optimization region - place directly after end of function definition #ifdef ARM_MATH_CM4 #define LOW_OPTIMIZATION_EXIT \ _Pragma ("pop") #else #define LOW_OPTIMIZATION_EXIT #endif //Enter low optimization region - place directly above function definition #define IAR_ONLY_LOW_OPTIMIZATION_ENTER //Exit low optimization region - place directly after end of function definition #define IAR_ONLY_LOW_OPTIMIZATION_EXIT #elif defined(__ICCARM__) //IAR //Enter low optimization region - place directly above function definition #ifdef ARM_MATH_CM4 #define LOW_OPTIMIZATION_ENTER \ _Pragma ("optimize=low") #else #define LOW_OPTIMIZATION_ENTER #endif //Exit low optimization region - place directly after end of function definition #define LOW_OPTIMIZATION_EXIT //Enter low optimization region - place directly above function definition #ifdef ARM_MATH_CM4 #define IAR_ONLY_LOW_OPTIMIZATION_ENTER \ _Pragma ("optimize=low") #else #define IAR_ONLY_LOW_OPTIMIZATION_ENTER #endif //Exit low optimization region - place directly after end of function definition #define IAR_ONLY_LOW_OPTIMIZATION_EXIT #elif defined(__GNUC__) #define LOW_OPTIMIZATION_ENTER __attribute__(( optimize("-O1") )) #define LOW_OPTIMIZATION_EXIT #define IAR_ONLY_LOW_OPTIMIZATION_ENTER #define IAR_ONLY_LOW_OPTIMIZATION_EXIT #elif defined(__CSMC__) // Cosmic #define LOW_OPTIMIZATION_ENTER #define LOW_OPTIMIZATION_EXIT #define IAR_ONLY_LOW_OPTIMIZATION_ENTER #define IAR_ONLY_LOW_OPTIMIZATION_EXIT #elif defined(__TASKING__) // TASKING #define LOW_OPTIMIZATION_ENTER #define LOW_OPTIMIZATION_EXIT #define IAR_ONLY_LOW_OPTIMIZATION_ENTER #define IAR_ONLY_LOW_OPTIMIZATION_EXIT #endif #ifdef __cplusplus } #endif #endif /* _ARM_MATH_H */ /** * * End of file. */ ================================================ FILE: Zelig/mbed/TARGET_NUCLEO_F091RC/cmsis.h ================================================ /* mbed Microcontroller Library * A generic CMSIS include header ******************************************************************************* * Copyright (c) 2015, STMicroelectronics * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * 1. Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * 3. Neither the name of 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. ******************************************************************************* */ #ifndef MBED_CMSIS_H #define MBED_CMSIS_H #include "stm32f0xx.h" #include "cmsis_nvic.h" #endif ================================================ FILE: Zelig/mbed/TARGET_NUCLEO_F091RC/cmsis_nvic.h ================================================ /* mbed Microcontroller Library * CMSIS-style functionality to support dynamic vectors ******************************************************************************* * Copyright (c) 2015, STMicroelectronics * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * 1. Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * 3. Neither the name of 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. ******************************************************************************* */ #ifndef MBED_CMSIS_NVIC_H #define MBED_CMSIS_NVIC_H // STM32F091RC // CORE: 16 vectors = 64 bytes from 0x00 to 0x3F // MCU Peripherals: 32 vectors = 128 bytes from 0x40 to 0xBF // Total: 48 vectors = 192 bytes (0xC0) to be reserved in RAM #define NVIC_NUM_VECTORS 48 #define NVIC_USER_IRQ_OFFSET 16 #include "cmsis.h" #ifdef __cplusplus extern "C" { #endif void NVIC_SetVector(IRQn_Type IRQn, uint32_t vector); uint32_t NVIC_GetVector(IRQn_Type IRQn); #ifdef __cplusplus } #endif #endif ================================================ FILE: Zelig/mbed/TARGET_NUCLEO_F091RC/core_ca9.h ================================================ /**************************************************************************//** * @file core_ca9.h * @brief CMSIS Cortex-A9 Core Peripheral Access Layer Header File * @version * @date 25 March 2013 * * @note * ******************************************************************************/ /* Copyright (c) 2009 - 2012 ARM LIMITED All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: - Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. - Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. - Neither the name of ARM 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 COPYRIGHT HOLDERS AND 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. ---------------------------------------------------------------------------*/ #if defined ( __ICCARM__ ) #pragma system_include /* treat file as system include file for MISRA check */ #endif #ifdef __cplusplus extern "C" { #endif #ifndef __CORE_CA9_H_GENERIC #define __CORE_CA9_H_GENERIC /** \page CMSIS_MISRA_Exceptions MISRA-C:2004 Compliance Exceptions CMSIS violates the following MISRA-C:2004 rules: \li Required Rule 8.5, object/function definition in header file.
Function definitions in header files are used to allow 'inlining'. \li Required Rule 18.4, declaration of union type or object of union type: '{...}'.
Unions are used for effective representation of core registers. \li Advisory Rule 19.7, Function-like macro defined.
Function-like macros are used to allow more efficient code. */ /******************************************************************************* * CMSIS definitions ******************************************************************************/ /** \ingroup Cortex_A9 @{ */ /* CMSIS CA9 definitions */ #define __CA9_CMSIS_VERSION_MAIN (0x03) /*!< [31:16] CMSIS HAL main version */ #define __CA9_CMSIS_VERSION_SUB (0x10) /*!< [15:0] CMSIS HAL sub version */ #define __CA9_CMSIS_VERSION ((__CA9_CMSIS_VERSION_MAIN << 16) | \ __CA9_CMSIS_VERSION_SUB ) /*!< CMSIS HAL version number */ #define __CORTEX_A (0x09) /*!< Cortex-A Core */ #if defined ( __CC_ARM ) #define __ASM __asm /*!< asm keyword for ARM Compiler */ #define __INLINE __inline /*!< inline keyword for ARM Compiler */ #define __STATIC_INLINE static __inline #define __STATIC_ASM static __asm #elif defined ( __ICCARM__ ) #define __ASM __asm /*!< asm keyword for IAR Compiler */ #define __INLINE inline /*!< inline keyword for IAR Compiler. Only available in High optimization mode! */ #define __STATIC_INLINE static inline #define __STATIC_ASM static __asm #elif defined ( __TMS470__ ) #define __ASM __asm /*!< asm keyword for TI CCS Compiler */ #define __STATIC_INLINE static inline #define __STATIC_ASM static __asm #elif defined ( __GNUC__ ) #define __ASM __asm /*!< asm keyword for GNU Compiler */ #define __INLINE inline /*!< inline keyword for GNU Compiler */ #define __STATIC_INLINE static inline #define __STATIC_ASM static __asm #elif defined ( __TASKING__ ) #define __ASM __asm /*!< asm keyword for TASKING Compiler */ #define __INLINE inline /*!< inline keyword for TASKING Compiler */ #define __STATIC_INLINE static inline #define __STATIC_ASM static __asm #endif /** __FPU_USED indicates whether an FPU is used or not. For this, __FPU_PRESENT has to be checked prior to making use of FPU specific registers and functions. */ #if defined ( __CC_ARM ) #if defined __TARGET_FPU_VFP #if (__FPU_PRESENT == 1) #define __FPU_USED 1 #else #warning "Compiler generates FPU instructions for a device without an FPU (check __FPU_PRESENT)" #define __FPU_USED 0 #endif #else #define __FPU_USED 0 #endif #elif defined ( __ICCARM__ ) #if defined __ARMVFP__ #if (__FPU_PRESENT == 1) #define __FPU_USED 1 #else #warning "Compiler generates FPU instructions for a device without an FPU (check __FPU_PRESENT)" #define __FPU_USED 0 #endif #else #define __FPU_USED 0 #endif #elif defined ( __TMS470__ ) #if defined __TI_VFP_SUPPORT__ #if (__FPU_PRESENT == 1) #define __FPU_USED 1 #else #warning "Compiler generates FPU instructions for a device without an FPU (check __FPU_PRESENT)" #define __FPU_USED 0 #endif #else #define __FPU_USED 0 #endif #elif defined ( __GNUC__ ) #if defined (__VFP_FP__) && !defined(__SOFTFP__) #if (__FPU_PRESENT == 1) #define __FPU_USED 1 #else #warning "Compiler generates FPU instructions for a device without an FPU (check __FPU_PRESENT)" #define __FPU_USED 0 #endif #else #define __FPU_USED 0 #endif #elif defined ( __TASKING__ ) #if defined __FPU_VFP__ #if (__FPU_PRESENT == 1) #define __FPU_USED 1 #else #error "Compiler generates FPU instructions for a device without an FPU (check __FPU_PRESENT)" #define __FPU_USED 0 #endif #else #define __FPU_USED 0 #endif #endif #include /*!< standard types definitions */ #include "core_caInstr.h" /*!< Core Instruction Access */ #include "core_caFunc.h" /*!< Core Function Access */ #include "core_cm4_simd.h" /*!< Compiler specific SIMD Intrinsics */ #endif /* __CORE_CA9_H_GENERIC */ #ifndef __CMSIS_GENERIC #ifndef __CORE_CA9_H_DEPENDANT #define __CORE_CA9_H_DEPENDANT /* check device defines and use defaults */ #if defined __CHECK_DEVICE_DEFINES #ifndef __CA9_REV #define __CA9_REV 0x0000 #warning "__CA9_REV not defined in device header file; using default!" #endif #ifndef __FPU_PRESENT #define __FPU_PRESENT 1 #warning "__FPU_PRESENT not defined in device header file; using default!" #endif #ifndef __Vendor_SysTickConfig #define __Vendor_SysTickConfig 1 #endif #if __Vendor_SysTickConfig == 0 #error "__Vendor_SysTickConfig set to 0, but vendor systick timer must be supplied for Cortex-A9" #endif #endif /* IO definitions (access restrictions to peripheral registers) */ /** \defgroup CMSIS_glob_defs CMSIS Global Defines IO Type Qualifiers are used \li to specify the access to peripheral variables. \li for automatic generation of peripheral register debug information. */ #ifdef __cplusplus #define __I volatile /*!< Defines 'read only' permissions */ #else #define __I volatile const /*!< Defines 'read only' permissions */ #endif #define __O volatile /*!< Defines 'write only' permissions */ #define __IO volatile /*!< Defines 'read / write' permissions */ /*@} end of group Cortex_A9 */ /******************************************************************************* * Register Abstraction ******************************************************************************/ /** \defgroup CMSIS_core_register Defines and Type Definitions \brief Type definitions and defines for Cortex-A processor based devices. */ /** \ingroup CMSIS_core_register \defgroup CMSIS_CORE Status and Control Registers \brief Core Register type definitions. @{ */ /** \brief Union type to access the Application Program Status Register (APSR). */ typedef union { struct { uint32_t _reserved0:16; /*!< bit: 0..15 Reserved */ uint32_t GE:4; /*!< bit: 16..19 Greater than or Equal flags */ uint32_t reserved1:7; /*!< bit: 20..23 Reserved */ uint32_t Q:1; /*!< bit: 27 Saturation condition flag */ uint32_t V:1; /*!< bit: 28 Overflow condition code flag */ uint32_t C:1; /*!< bit: 29 Carry condition code flag */ uint32_t Z:1; /*!< bit: 30 Zero condition code flag */ uint32_t N:1; /*!< bit: 31 Negative condition code flag */ } b; /*!< Structure used for bit access */ uint32_t w; /*!< Type used for word access */ } APSR_Type; /*@} end of group CMSIS_CORE */ /*@} end of CMSIS_Core_FPUFunctions */ #endif /* __CORE_CA9_H_GENERIC */ #endif /* __CMSIS_GENERIC */ #ifdef __cplusplus } #endif ================================================ FILE: Zelig/mbed/TARGET_NUCLEO_F091RC/core_caFunc.h ================================================ /**************************************************************************//** * @file core_caFunc.h * @brief CMSIS Cortex-A Core Function Access Header File * @version V3.10 * @date 30 Oct 2013 * * @note * ******************************************************************************/ /* Copyright (c) 2009 - 2013 ARM LIMITED All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: - Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. - Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. - Neither the name of ARM 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 COPYRIGHT HOLDERS AND 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. ---------------------------------------------------------------------------*/ #ifndef __CORE_CAFUNC_H__ #define __CORE_CAFUNC_H__ /* ########################### Core Function Access ########################### */ /** \ingroup CMSIS_Core_FunctionInterface \defgroup CMSIS_Core_RegAccFunctions CMSIS Core Register Access Functions @{ */ #if defined ( __CC_ARM ) /*------------------RealView Compiler -----------------*/ /* ARM armcc specific functions */ #if (__ARMCC_VERSION < 400677) #error "Please use ARM Compiler Toolchain V4.0.677 or later!" #endif #define MODE_USR 0x10 #define MODE_FIQ 0x11 #define MODE_IRQ 0x12 #define MODE_SVC 0x13 #define MODE_MON 0x16 #define MODE_ABT 0x17 #define MODE_HYP 0x1A #define MODE_UND 0x1B #define MODE_SYS 0x1F /** \brief Get APSR Register This function returns the content of the APSR Register. \return APSR Register value */ __STATIC_INLINE uint32_t __get_APSR(void) { register uint32_t __regAPSR __ASM("apsr"); return(__regAPSR); } /** \brief Get CPSR Register This function returns the content of the CPSR Register. \return CPSR Register value */ __STATIC_INLINE uint32_t __get_CPSR(void) { register uint32_t __regCPSR __ASM("cpsr"); return(__regCPSR); } /** \brief Set Stack Pointer This function assigns the given value to the current stack pointer. \param [in] topOfStack Stack Pointer value to set */ register uint32_t __regSP __ASM("sp"); __STATIC_INLINE void __set_SP(uint32_t topOfStack) { __regSP = topOfStack; } /** \brief Get link register This function returns the value of the link register \return Value of link register */ register uint32_t __reglr __ASM("lr"); __STATIC_INLINE uint32_t __get_LR(void) { return(__reglr); } /** \brief Set link register This function sets the value of the link register \param [in] lr LR value to set */ __STATIC_INLINE void __set_LR(uint32_t lr) { __reglr = lr; } /** \brief Set Process Stack Pointer This function assigns the given value to the USR/SYS Stack Pointer (PSP). \param [in] topOfProcStack USR/SYS Stack Pointer value to set */ __STATIC_ASM void __set_PSP(uint32_t topOfProcStack) { ARM PRESERVE8 BIC R0, R0, #7 ;ensure stack is 8-byte aligned MRS R1, CPSR CPS #MODE_SYS ;no effect in USR mode MOV SP, R0 MSR CPSR_c, R1 ;no effect in USR mode ISB BX LR } /** \brief Set User Mode This function changes the processor state to User Mode */ __STATIC_ASM void __set_CPS_USR(void) { ARM CPS #MODE_USR BX LR } /** \brief Enable FIQ This function enables FIQ interrupts by clearing the F-bit in the CPSR. Can only be executed in Privileged modes. */ #define __enable_fault_irq __enable_fiq /** \brief Disable FIQ This function disables FIQ interrupts by setting the F-bit in the CPSR. Can only be executed in Privileged modes. */ #define __disable_fault_irq __disable_fiq /** \brief Get FPSCR This function returns the current value of the Floating Point Status/Control register. \return Floating Point Status/Control register value */ __STATIC_INLINE uint32_t __get_FPSCR(void) { #if (__FPU_PRESENT == 1) && (__FPU_USED == 1) register uint32_t __regfpscr __ASM("fpscr"); return(__regfpscr); #else return(0); #endif } /** \brief Set FPSCR This function assigns the given value to the Floating Point Status/Control register. \param [in] fpscr Floating Point Status/Control value to set */ __STATIC_INLINE void __set_FPSCR(uint32_t fpscr) { #if (__FPU_PRESENT == 1) && (__FPU_USED == 1) register uint32_t __regfpscr __ASM("fpscr"); __regfpscr = (fpscr); #endif } /** \brief Get FPEXC This function returns the current value of the Floating Point Exception Control register. \return Floating Point Exception Control register value */ __STATIC_INLINE uint32_t __get_FPEXC(void) { #if (__FPU_PRESENT == 1) register uint32_t __regfpexc __ASM("fpexc"); return(__regfpexc); #else return(0); #endif } /** \brief Set FPEXC This function assigns the given value to the Floating Point Exception Control register. \param [in] fpscr Floating Point Exception Control value to set */ __STATIC_INLINE void __set_FPEXC(uint32_t fpexc) { #if (__FPU_PRESENT == 1) register uint32_t __regfpexc __ASM("fpexc"); __regfpexc = (fpexc); #endif } /** \brief Get CPACR This function returns the current value of the Coprocessor Access Control register. \return Coprocessor Access Control register value */ __STATIC_INLINE uint32_t __get_CPACR(void) { register uint32_t __regCPACR __ASM("cp15:0:c1:c0:2"); return __regCPACR; } /** \brief Set CPACR This function assigns the given value to the Coprocessor Access Control register. \param [in] cpacr Coprocessor Acccess Control value to set */ __STATIC_INLINE void __set_CPACR(uint32_t cpacr) { register uint32_t __regCPACR __ASM("cp15:0:c1:c0:2"); __regCPACR = cpacr; __ISB(); } /** \brief Get CBAR This function returns the value of the Configuration Base Address register. \return Configuration Base Address register value */ __STATIC_INLINE uint32_t __get_CBAR() { register uint32_t __regCBAR __ASM("cp15:4:c15:c0:0"); return(__regCBAR); } /** \brief Get TTBR0 This function returns the value of the Translation Table Base Register 0. \return Translation Table Base Register 0 value */ __STATIC_INLINE uint32_t __get_TTBR0() { register uint32_t __regTTBR0 __ASM("cp15:0:c2:c0:0"); return(__regTTBR0); } /** \brief Set TTBR0 This function assigns the given value to the Translation Table Base Register 0. \param [in] ttbr0 Translation Table Base Register 0 value to set */ __STATIC_INLINE void __set_TTBR0(uint32_t ttbr0) { register uint32_t __regTTBR0 __ASM("cp15:0:c2:c0:0"); __regTTBR0 = ttbr0; __ISB(); } /** \brief Get DACR This function returns the value of the Domain Access Control Register. \return Domain Access Control Register value */ __STATIC_INLINE uint32_t __get_DACR() { register uint32_t __regDACR __ASM("cp15:0:c3:c0:0"); return(__regDACR); } /** \brief Set DACR This function assigns the given value to the Domain Access Control Register. \param [in] dacr Domain Access Control Register value to set */ __STATIC_INLINE void __set_DACR(uint32_t dacr) { register uint32_t __regDACR __ASM("cp15:0:c3:c0:0"); __regDACR = dacr; __ISB(); } /******************************** Cache and BTAC enable ****************************************************/ /** \brief Set SCTLR This function assigns the given value to the System Control Register. \param [in] sctlr System Control Register value to set */ __STATIC_INLINE void __set_SCTLR(uint32_t sctlr) { register uint32_t __regSCTLR __ASM("cp15:0:c1:c0:0"); __regSCTLR = sctlr; } /** \brief Get SCTLR This function returns the value of the System Control Register. \return System Control Register value */ __STATIC_INLINE uint32_t __get_SCTLR() { register uint32_t __regSCTLR __ASM("cp15:0:c1:c0:0"); return(__regSCTLR); } /** \brief Enable Caches Enable Caches */ __STATIC_INLINE void __enable_caches(void) { // Set I bit 12 to enable I Cache // Set C bit 2 to enable D Cache __set_SCTLR( __get_SCTLR() | (1 << 12) | (1 << 2)); } /** \brief Disable Caches Disable Caches */ __STATIC_INLINE void __disable_caches(void) { // Clear I bit 12 to disable I Cache // Clear C bit 2 to disable D Cache __set_SCTLR( __get_SCTLR() & ~(1 << 12) & ~(1 << 2)); __ISB(); } /** \brief Enable BTAC Enable BTAC */ __STATIC_INLINE void __enable_btac(void) { // Set Z bit 11 to enable branch prediction __set_SCTLR( __get_SCTLR() | (1 << 11)); __ISB(); } /** \brief Disable BTAC Disable BTAC */ __STATIC_INLINE void __disable_btac(void) { // Clear Z bit 11 to disable branch prediction __set_SCTLR( __get_SCTLR() & ~(1 << 11)); } /** \brief Enable MMU Enable MMU */ __STATIC_INLINE void __enable_mmu(void) { // Set M bit 0 to enable the MMU // Set AFE bit to enable simplified access permissions model // Clear TRE bit to disable TEX remap and A bit to disable strict alignment fault checking __set_SCTLR( (__get_SCTLR() & ~(1 << 28) & ~(1 << 1)) | 1 | (1 << 29)); __ISB(); } /** \brief Disable MMU Disable MMU */ __STATIC_INLINE void __disable_mmu(void) { // Clear M bit 0 to disable the MMU __set_SCTLR( __get_SCTLR() & ~1); __ISB(); } /******************************** TLB maintenance operations ************************************************/ /** \brief Invalidate the whole tlb TLBIALL. Invalidate the whole tlb */ __STATIC_INLINE void __ca9u_inv_tlb_all(void) { register uint32_t __TLBIALL __ASM("cp15:0:c8:c7:0"); __TLBIALL = 0; __DSB(); __ISB(); } /******************************** BTB maintenance operations ************************************************/ /** \brief Invalidate entire branch predictor array BPIALL. Branch Predictor Invalidate All. */ __STATIC_INLINE void __v7_inv_btac(void) { register uint32_t __BPIALL __ASM("cp15:0:c7:c5:6"); __BPIALL = 0; __DSB(); //ensure completion of the invalidation __ISB(); //ensure instruction fetch path sees new state } /******************************** L1 cache operations ******************************************************/ /** \brief Invalidate the whole I$ ICIALLU. Instruction Cache Invalidate All to PoU */ __STATIC_INLINE void __v7_inv_icache_all(void) { register uint32_t __ICIALLU __ASM("cp15:0:c7:c5:0"); __ICIALLU = 0; __DSB(); //ensure completion of the invalidation __ISB(); //ensure instruction fetch path sees new I cache state } /** \brief Clean D$ by MVA DCCMVAC. Data cache clean by MVA to PoC */ __STATIC_INLINE void __v7_clean_dcache_mva(void *va) { register uint32_t __DCCMVAC __ASM("cp15:0:c7:c10:1"); __DCCMVAC = (uint32_t)va; __DMB(); //ensure the ordering of data cache maintenance operations and their effects } /** \brief Invalidate D$ by MVA DCIMVAC. Data cache invalidate by MVA to PoC */ __STATIC_INLINE void __v7_inv_dcache_mva(void *va) { register uint32_t __DCIMVAC __ASM("cp15:0:c7:c6:1"); __DCIMVAC = (uint32_t)va; __DMB(); //ensure the ordering of data cache maintenance operations and their effects } /** \brief Clean and Invalidate D$ by MVA DCCIMVAC. Data cache clean and invalidate by MVA to PoC */ __STATIC_INLINE void __v7_clean_inv_dcache_mva(void *va) { register uint32_t __DCCIMVAC __ASM("cp15:0:c7:c14:1"); __DCCIMVAC = (uint32_t)va; __DMB(); //ensure the ordering of data cache maintenance operations and their effects } /** \brief Clean and Invalidate the entire data or unified cache Generic mechanism for cleaning/invalidating the entire data or unified cache to the point of coherency. */ #pragma push #pragma arm __STATIC_ASM void __v7_all_cache(uint32_t op) { ARM PUSH {R4-R11} MRC p15, 1, R6, c0, c0, 1 // Read CLIDR ANDS R3, R6, #0x07000000 // Extract coherency level MOV R3, R3, LSR #23 // Total cache levels << 1 BEQ Finished // If 0, no need to clean MOV R10, #0 // R10 holds current cache level << 1 Loop1 ADD R2, R10, R10, LSR #1 // R2 holds cache "Set" position MOV R1, R6, LSR R2 // Bottom 3 bits are the Cache-type for this level AND R1, R1, #7 // Isolate those lower 3 bits CMP R1, #2 BLT Skip // No cache or only instruction cache at this level MCR p15, 2, R10, c0, c0, 0 // Write the Cache Size selection register ISB // ISB to sync the change to the CacheSizeID reg MRC p15, 1, R1, c0, c0, 0 // Reads current Cache Size ID register AND R2, R1, #7 // Extract the line length field ADD R2, R2, #4 // Add 4 for the line length offset (log2 16 bytes) LDR R4, =0x3FF ANDS R4, R4, R1, LSR #3 // R4 is the max number on the way size (right aligned) CLZ R5, R4 // R5 is the bit position of the way size increment LDR R7, =0x7FFF ANDS R7, R7, R1, LSR #13 // R7 is the max number of the index size (right aligned) Loop2 MOV R9, R4 // R9 working copy of the max way size (right aligned) Loop3 ORR R11, R10, R9, LSL R5 // Factor in the Way number and cache number into R11 ORR R11, R11, R7, LSL R2 // Factor in the Set number CMP R0, #0 BNE Dccsw MCR p15, 0, R11, c7, c6, 2 // DCISW. Invalidate by Set/Way B cont Dccsw CMP R0, #1 BNE Dccisw MCR p15, 0, R11, c7, c10, 2 // DCCSW. Clean by Set/Way B cont Dccisw MCR p15, 0, R11, c7, c14, 2 // DCCISW. Clean and Invalidate by Set/Way cont SUBS R9, R9, #1 // Decrement the Way number BGE Loop3 SUBS R7, R7, #1 // Decrement the Set number BGE Loop2 Skip ADD R10, R10, #2 // Increment the cache number CMP R3, R10 BGT Loop1 Finished DSB POP {R4-R11} BX lr } #pragma pop /** \brief Invalidate the whole D$ DCISW. Invalidate by Set/Way */ __STATIC_INLINE void __v7_inv_dcache_all(void) { __v7_all_cache(0); } /** \brief Clean the whole D$ DCCSW. Clean by Set/Way */ __STATIC_INLINE void __v7_clean_dcache_all(void) { __v7_all_cache(1); } /** \brief Clean and invalidate the whole D$ DCCISW. Clean and Invalidate by Set/Way */ __STATIC_INLINE void __v7_clean_inv_dcache_all(void) { __v7_all_cache(2); } #include "core_ca_mmu.h" #elif (defined (__ICCARM__)) /*---------------- ICC Compiler ---------------------*/ #error IAR Compiler support not implemented for Cortex-A #elif (defined (__GNUC__)) /*------------------ GNU Compiler ---------------------*/ /* GNU gcc specific functions */ #define MODE_USR 0x10 #define MODE_FIQ 0x11 #define MODE_IRQ 0x12 #define MODE_SVC 0x13 #define MODE_MON 0x16 #define MODE_ABT 0x17 #define MODE_HYP 0x1A #define MODE_UND 0x1B #define MODE_SYS 0x1F __attribute__( ( always_inline ) ) __STATIC_INLINE void __enable_irq(void) { __ASM volatile ("cpsie i"); } /** \brief Disable IRQ Interrupts This function disables IRQ interrupts by setting the I-bit in the CPSR. Can only be executed in Privileged modes. */ __attribute__( ( always_inline ) ) __STATIC_INLINE uint32_t __disable_irq(void) { uint32_t result; __ASM volatile ("mrs %0, cpsr" : "=r" (result)); __ASM volatile ("cpsid i"); return(result & 0x80); } /** \brief Get APSR Register This function returns the content of the APSR Register. \return APSR Register value */ __attribute__( ( always_inline ) ) __STATIC_INLINE uint32_t __get_APSR(void) { #if 1 register uint32_t __regAPSR; __ASM volatile ("mrs %0, apsr" : "=r" (__regAPSR) ); #else register uint32_t __regAPSR __ASM("apsr"); #endif return(__regAPSR); } /** \brief Get CPSR Register This function returns the content of the CPSR Register. \return CPSR Register value */ __attribute__( ( always_inline ) ) __STATIC_INLINE uint32_t __get_CPSR(void) { #if 1 register uint32_t __regCPSR; __ASM volatile ("mrs %0, cpsr" : "=r" (__regCPSR)); #else register uint32_t __regCPSR __ASM("cpsr"); #endif return(__regCPSR); } #if 0 /** \brief Set Stack Pointer This function assigns the given value to the current stack pointer. \param [in] topOfStack Stack Pointer value to set */ __attribute__( ( always_inline ) ) __STATIC_INLINE void __set_SP(uint32_t topOfStack) { register uint32_t __regSP __ASM("sp"); __regSP = topOfStack; } #endif /** \brief Get link register This function returns the value of the link register \return Value of link register */ __attribute__( ( always_inline ) ) __STATIC_INLINE uint32_t __get_LR(void) { register uint32_t __reglr __ASM("lr"); return(__reglr); } #if 0 /** \brief Set link register This function sets the value of the link register \param [in] lr LR value to set */ __attribute__( ( always_inline ) ) __STATIC_INLINE void __set_LR(uint32_t lr) { register uint32_t __reglr __ASM("lr"); __reglr = lr; } #endif /** \brief Set Process Stack Pointer This function assigns the given value to the USR/SYS Stack Pointer (PSP). \param [in] topOfProcStack USR/SYS Stack Pointer value to set */ __attribute__( ( always_inline ) ) __STATIC_INLINE void __set_PSP(uint32_t topOfProcStack) { __asm__ volatile ( ".ARM;" ".eabi_attribute Tag_ABI_align8_preserved,1;" "BIC R0, R0, #7;" /* ;ensure stack is 8-byte aligned */ "MRS R1, CPSR;" "CPS %0;" /* ;no effect in USR mode */ "MOV SP, R0;" "MSR CPSR_c, R1;" /* ;no effect in USR mode */ "ISB;" //"BX LR;" : : "i"(MODE_SYS) : "r0", "r1"); return; } /** \brief Set User Mode This function changes the processor state to User Mode */ __attribute__( ( always_inline ) ) __STATIC_INLINE void __set_CPS_USR(void) { __asm__ volatile ( ".ARM;" "CPS %0;" //"BX LR;" : : "i"(MODE_USR) : ); return; } /** \brief Enable FIQ This function enables FIQ interrupts by clearing the F-bit in the CPSR. Can only be executed in Privileged modes. */ #define __enable_fault_irq() __asm__ volatile ("cpsie f") /** \brief Disable FIQ This function disables FIQ interrupts by setting the F-bit in the CPSR. Can only be executed in Privileged modes. */ #define __disable_fault_irq() __asm__ volatile ("cpsid f") /** \brief Get FPSCR This function returns the current value of the Floating Point Status/Control register. \return Floating Point Status/Control register value */ __attribute__( ( always_inline ) ) __STATIC_INLINE uint32_t __get_FPSCR(void) { #if (__FPU_PRESENT == 1) && (__FPU_USED == 1) #if 1 uint32_t result; __ASM volatile ("vmrs %0, fpscr" : "=r" (result) ); return (result); #else register uint32_t __regfpscr __ASM("fpscr"); return(__regfpscr); #endif #else return(0); #endif } /** \brief Set FPSCR This function assigns the given value to the Floating Point Status/Control register. \param [in] fpscr Floating Point Status/Control value to set */ __attribute__( ( always_inline ) ) __STATIC_INLINE void __set_FPSCR(uint32_t fpscr) { #if (__FPU_PRESENT == 1) && (__FPU_USED == 1) #if 1 __ASM volatile ("vmsr fpscr, %0" : : "r" (fpscr) ); #else register uint32_t __regfpscr __ASM("fpscr"); __regfpscr = (fpscr); #endif #endif } /** \brief Get FPEXC This function returns the current value of the Floating Point Exception Control register. \return Floating Point Exception Control register value */ __attribute__( ( always_inline ) ) __STATIC_INLINE uint32_t __get_FPEXC(void) { #if (__FPU_PRESENT == 1) #if 1 uint32_t result; __ASM volatile ("vmrs %0, fpexc" : "=r" (result)); return (result); #else register uint32_t __regfpexc __ASM("fpexc"); return(__regfpexc); #endif #else return(0); #endif } /** \brief Set FPEXC This function assigns the given value to the Floating Point Exception Control register. \param [in] fpscr Floating Point Exception Control value to set */ __attribute__( ( always_inline ) ) __STATIC_INLINE void __set_FPEXC(uint32_t fpexc) { #if (__FPU_PRESENT == 1) #if 1 __ASM volatile ("vmsr fpexc, %0" : : "r" (fpexc)); #else register uint32_t __regfpexc __ASM("fpexc"); __regfpexc = (fpexc); #endif #endif } /** \brief Get CPACR This function returns the current value of the Coprocessor Access Control register. \return Coprocessor Access Control register value */ __attribute__( ( always_inline ) ) __STATIC_INLINE uint32_t __get_CPACR(void) { #if 1 register uint32_t __regCPACR; __ASM volatile ("mrc p15, 0, %0, c1, c0, 2" : "=r" (__regCPACR)); #else register uint32_t __regCPACR __ASM("cp15:0:c1:c0:2"); #endif return __regCPACR; } /** \brief Set CPACR This function assigns the given value to the Coprocessor Access Control register. \param [in] cpacr Coprocessor Acccess Control value to set */ __attribute__( ( always_inline ) ) __STATIC_INLINE void __set_CPACR(uint32_t cpacr) { #if 1 __ASM volatile ("mcr p15, 0, %0, c1, c0, 2" : : "r" (cpacr)); #else register uint32_t __regCPACR __ASM("cp15:0:c1:c0:2"); __regCPACR = cpacr; #endif __ISB(); } /** \brief Get CBAR This function returns the value of the Configuration Base Address register. \return Configuration Base Address register value */ __attribute__( ( always_inline ) ) __STATIC_INLINE uint32_t __get_CBAR() { #if 1 register uint32_t __regCBAR; __ASM volatile ("mrc p15, 4, %0, c15, c0, 0" : "=r" (__regCBAR)); #else register uint32_t __regCBAR __ASM("cp15:4:c15:c0:0"); #endif return(__regCBAR); } /** \brief Get TTBR0 This function returns the value of the Translation Table Base Register 0. \return Translation Table Base Register 0 value */ __attribute__( ( always_inline ) ) __STATIC_INLINE uint32_t __get_TTBR0() { #if 1 register uint32_t __regTTBR0; __ASM volatile ("mrc p15, 0, %0, c2, c0, 0" : "=r" (__regTTBR0)); #else register uint32_t __regTTBR0 __ASM("cp15:0:c2:c0:0"); #endif return(__regTTBR0); } /** \brief Set TTBR0 This function assigns the given value to the Translation Table Base Register 0. \param [in] ttbr0 Translation Table Base Register 0 value to set */ __attribute__( ( always_inline ) ) __STATIC_INLINE void __set_TTBR0(uint32_t ttbr0) { #if 1 __ASM volatile ("mcr p15, 0, %0, c2, c0, 0" : : "r" (ttbr0)); #else register uint32_t __regTTBR0 __ASM("cp15:0:c2:c0:0"); __regTTBR0 = ttbr0; #endif __ISB(); } /** \brief Get DACR This function returns the value of the Domain Access Control Register. \return Domain Access Control Register value */ __attribute__( ( always_inline ) ) __STATIC_INLINE uint32_t __get_DACR() { #if 1 register uint32_t __regDACR; __ASM volatile ("mrc p15, 0, %0, c3, c0, 0" : "=r" (__regDACR)); #else register uint32_t __regDACR __ASM("cp15:0:c3:c0:0"); #endif return(__regDACR); } /** \brief Set DACR This function assigns the given value to the Domain Access Control Register. \param [in] dacr Domain Access Control Register value to set */ __attribute__( ( always_inline ) ) __STATIC_INLINE void __set_DACR(uint32_t dacr) { #if 1 __ASM volatile ("mcr p15, 0, %0, c3, c0, 0" : : "r" (dacr)); #else register uint32_t __regDACR __ASM("cp15:0:c3:c0:0"); __regDACR = dacr; #endif __ISB(); } /******************************** Cache and BTAC enable ****************************************************/ /** \brief Set SCTLR This function assigns the given value to the System Control Register. \param [in] sctlr System Control Register value to set */ __attribute__( ( always_inline ) ) __STATIC_INLINE void __set_SCTLR(uint32_t sctlr) { #if 1 __ASM volatile ("mcr p15, 0, %0, c1, c0, 0" : : "r" (sctlr)); #else register uint32_t __regSCTLR __ASM("cp15:0:c1:c0:0"); __regSCTLR = sctlr; #endif } /** \brief Get SCTLR This function returns the value of the System Control Register. \return System Control Register value */ __attribute__( ( always_inline ) ) __STATIC_INLINE uint32_t __get_SCTLR() { #if 1 register uint32_t __regSCTLR; __ASM volatile ("mrc p15, 0, %0, c1, c0, 0" : "=r" (__regSCTLR)); #else register uint32_t __regSCTLR __ASM("cp15:0:c1:c0:0"); #endif return(__regSCTLR); } /** \brief Enable Caches Enable Caches */ __attribute__( ( always_inline ) ) __STATIC_INLINE void __enable_caches(void) { // Set I bit 12 to enable I Cache // Set C bit 2 to enable D Cache __set_SCTLR( __get_SCTLR() | (1 << 12) | (1 << 2)); } /** \brief Disable Caches Disable Caches */ __attribute__( ( always_inline ) ) __STATIC_INLINE void __disable_caches(void) { // Clear I bit 12 to disable I Cache // Clear C bit 2 to disable D Cache __set_SCTLR( __get_SCTLR() & ~(1 << 12) & ~(1 << 2)); __ISB(); } /** \brief Enable BTAC Enable BTAC */ __attribute__( ( always_inline ) ) __STATIC_INLINE void __enable_btac(void) { // Set Z bit 11 to enable branch prediction __set_SCTLR( __get_SCTLR() | (1 << 11)); __ISB(); } /** \brief Disable BTAC Disable BTAC */ __attribute__( ( always_inline ) ) __STATIC_INLINE void __disable_btac(void) { // Clear Z bit 11 to disable branch prediction __set_SCTLR( __get_SCTLR() & ~(1 << 11)); } /** \brief Enable MMU Enable MMU */ __attribute__( ( always_inline ) ) __STATIC_INLINE void __enable_mmu(void) { // Set M bit 0 to enable the MMU // Set AFE bit to enable simplified access permissions model // Clear TRE bit to disable TEX remap and A bit to disable strict alignment fault checking __set_SCTLR( (__get_SCTLR() & ~(1 << 28) & ~(1 << 1)) | 1 | (1 << 29)); __ISB(); } /** \brief Disable MMU Disable MMU */ __attribute__( ( always_inline ) ) __STATIC_INLINE void __disable_mmu(void) { // Clear M bit 0 to disable the MMU __set_SCTLR( __get_SCTLR() & ~1); __ISB(); } /******************************** TLB maintenance operations ************************************************/ /** \brief Invalidate the whole tlb TLBIALL. Invalidate the whole tlb */ __attribute__( ( always_inline ) ) __STATIC_INLINE void __ca9u_inv_tlb_all(void) { #if 1 __ASM volatile ("mcr p15, 0, %0, c8, c7, 0" : : "r" (0)); #else register uint32_t __TLBIALL __ASM("cp15:0:c8:c7:0"); __TLBIALL = 0; #endif __DSB(); __ISB(); } /******************************** BTB maintenance operations ************************************************/ /** \brief Invalidate entire branch predictor array BPIALL. Branch Predictor Invalidate All. */ __attribute__( ( always_inline ) ) __STATIC_INLINE void __v7_inv_btac(void) { #if 1 __ASM volatile ("mcr p15, 0, %0, c7, c5, 6" : : "r" (0)); #else register uint32_t __BPIALL __ASM("cp15:0:c7:c5:6"); __BPIALL = 0; #endif __DSB(); //ensure completion of the invalidation __ISB(); //ensure instruction fetch path sees new state } /******************************** L1 cache operations ******************************************************/ /** \brief Invalidate the whole I$ ICIALLU. Instruction Cache Invalidate All to PoU */ __attribute__( ( always_inline ) ) __STATIC_INLINE void __v7_inv_icache_all(void) { #if 1 __ASM volatile ("mcr p15, 0, %0, c7, c5, 0" : : "r" (0)); #else register uint32_t __ICIALLU __ASM("cp15:0:c7:c5:0"); __ICIALLU = 0; #endif __DSB(); //ensure completion of the invalidation __ISB(); //ensure instruction fetch path sees new I cache state } /** \brief Clean D$ by MVA DCCMVAC. Data cache clean by MVA to PoC */ __attribute__( ( always_inline ) ) __STATIC_INLINE void __v7_clean_dcache_mva(void *va) { #if 1 __ASM volatile ("mcr p15, 0, %0, c7, c10, 1" : : "r" ((uint32_t)va)); #else register uint32_t __DCCMVAC __ASM("cp15:0:c7:c10:1"); __DCCMVAC = (uint32_t)va; #endif __DMB(); //ensure the ordering of data cache maintenance operations and their effects } /** \brief Invalidate D$ by MVA DCIMVAC. Data cache invalidate by MVA to PoC */ __attribute__( ( always_inline ) ) __STATIC_INLINE void __v7_inv_dcache_mva(void *va) { #if 1 __ASM volatile ("mcr p15, 0, %0, c7, c6, 1" : : "r" ((uint32_t)va)); #else register uint32_t __DCIMVAC __ASM("cp15:0:c7:c6:1"); __DCIMVAC = (uint32_t)va; #endif __DMB(); //ensure the ordering of data cache maintenance operations and their effects } /** \brief Clean and Invalidate D$ by MVA DCCIMVAC. Data cache clean and invalidate by MVA to PoC */ __attribute__( ( always_inline ) ) __STATIC_INLINE void __v7_clean_inv_dcache_mva(void *va) { #if 1 __ASM volatile ("mcr p15, 0, %0, c7, c14, 1" : : "r" ((uint32_t)va)); #else register uint32_t __DCCIMVAC __ASM("cp15:0:c7:c14:1"); __DCCIMVAC = (uint32_t)va; #endif __DMB(); //ensure the ordering of data cache maintenance operations and their effects } /** \brief Clean and Invalidate the entire data or unified cache Generic mechanism for cleaning/invalidating the entire data or unified cache to the point of coherency. */ extern void __v7_all_cache(uint32_t op); /** \brief Invalidate the whole D$ DCISW. Invalidate by Set/Way */ __attribute__( ( always_inline ) ) __STATIC_INLINE void __v7_inv_dcache_all(void) { __v7_all_cache(0); } /** \brief Clean the whole D$ DCCSW. Clean by Set/Way */ __attribute__( ( always_inline ) ) __STATIC_INLINE void __v7_clean_dcache_all(void) { __v7_all_cache(1); } /** \brief Clean and invalidate the whole D$ DCCISW. Clean and Invalidate by Set/Way */ __attribute__( ( always_inline ) ) __STATIC_INLINE void __v7_clean_inv_dcache_all(void) { __v7_all_cache(2); } #include "core_ca_mmu.h" #elif (defined (__TASKING__)) /*--------------- TASKING Compiler -----------------*/ #error TASKING Compiler support not implemented for Cortex-A #endif /*@} end of CMSIS_Core_RegAccFunctions */ #endif /* __CORE_CAFUNC_H__ */ ================================================ FILE: Zelig/mbed/TARGET_NUCLEO_F091RC/core_caInstr.h ================================================ /**************************************************************************//** * @file core_caInstr.h * @brief CMSIS Cortex-A9 Core Peripheral Access Layer Header File * @version * @date 04. December 2012 * * @note * ******************************************************************************/ /* Copyright (c) 2009 - 2012 ARM LIMITED All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: - Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. - Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. - Neither the name of ARM 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 COPYRIGHT HOLDERS AND 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. ---------------------------------------------------------------------------*/ #ifndef __CORE_CAINSTR_H__ #define __CORE_CAINSTR_H__ #define __CORTEX_M 0x3 #include "core_cmInstr.h" #undef __CORTEX_M #endif ================================================ FILE: Zelig/mbed/TARGET_NUCLEO_F091RC/core_ca_mmu.h ================================================ ;/**************************************************************************//** ; * @file core_ca_mmu.h ; * @brief MMU Startup File for A9_MP Device Series ; * @version V1.01 ; * @date 10 Sept 2014 ; * ; * @note ; * ; ******************************************************************************/ ;/* Copyright (c) 2012-2014 ARM LIMITED ; ; All rights reserved. ; Redistribution and use in source and binary forms, with or without ; modification, are permitted provided that the following conditions are met: ; - Redistributions of source code must retain the above copyright ; notice, this list of conditions and the following disclaimer. ; - Redistributions in binary form must reproduce the above copyright ; notice, this list of conditions and the following disclaimer in the ; documentation and/or other materials provided with the distribution. ; - Neither the name of ARM 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 COPYRIGHT HOLDERS AND CONTRIBUTORS BE ; LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR ; CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF ; SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS ; INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN ; CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ; ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE ; POSSIBILITY OF SUCH DAMAGE. ; ---------------------------------------------------------------------------*/ #ifdef __cplusplus extern "C" { #endif #ifndef _MMU_FUNC_H #define _MMU_FUNC_H #define SECTION_DESCRIPTOR (0x2) #define SECTION_MASK (0xFFFFFFFC) #define SECTION_TEXCB_MASK (0xFFFF8FF3) #define SECTION_B_SHIFT (2) #define SECTION_C_SHIFT (3) #define SECTION_TEX0_SHIFT (12) #define SECTION_TEX1_SHIFT (13) #define SECTION_TEX2_SHIFT (14) #define SECTION_XN_MASK (0xFFFFFFEF) #define SECTION_XN_SHIFT (4) #define SECTION_DOMAIN_MASK (0xFFFFFE1F) #define SECTION_DOMAIN_SHIFT (5) #define SECTION_P_MASK (0xFFFFFDFF) #define SECTION_P_SHIFT (9) #define SECTION_AP_MASK (0xFFFF73FF) #define SECTION_AP_SHIFT (10) #define SECTION_AP2_SHIFT (15) #define SECTION_S_MASK (0xFFFEFFFF) #define SECTION_S_SHIFT (16) #define SECTION_NG_MASK (0xFFFDFFFF) #define SECTION_NG_SHIFT (17) #define SECTION_NS_MASK (0xFFF7FFFF) #define SECTION_NS_SHIFT (19) #define PAGE_L1_DESCRIPTOR (0x1) #define PAGE_L1_MASK (0xFFFFFFFC) #define PAGE_L2_4K_DESC (0x2) #define PAGE_L2_4K_MASK (0xFFFFFFFD) #define PAGE_L2_64K_DESC (0x1) #define PAGE_L2_64K_MASK (0xFFFFFFFC) #define PAGE_4K_TEXCB_MASK (0xFFFFFE33) #define PAGE_4K_B_SHIFT (2) #define PAGE_4K_C_SHIFT (3) #define PAGE_4K_TEX0_SHIFT (6) #define PAGE_4K_TEX1_SHIFT (7) #define PAGE_4K_TEX2_SHIFT (8) #define PAGE_64K_TEXCB_MASK (0xFFFF8FF3) #define PAGE_64K_B_SHIFT (2) #define PAGE_64K_C_SHIFT (3) #define PAGE_64K_TEX0_SHIFT (12) #define PAGE_64K_TEX1_SHIFT (13) #define PAGE_64K_TEX2_SHIFT (14) #define PAGE_TEXCB_MASK (0xFFFF8FF3) #define PAGE_B_SHIFT (2) #define PAGE_C_SHIFT (3) #define PAGE_TEX_SHIFT (12) #define PAGE_XN_4K_MASK (0xFFFFFFFE) #define PAGE_XN_4K_SHIFT (0) #define PAGE_XN_64K_MASK (0xFFFF7FFF) #define PAGE_XN_64K_SHIFT (15) #define PAGE_DOMAIN_MASK (0xFFFFFE1F) #define PAGE_DOMAIN_SHIFT (5) #define PAGE_P_MASK (0xFFFFFDFF) #define PAGE_P_SHIFT (9) #define PAGE_AP_MASK (0xFFFFFDCF) #define PAGE_AP_SHIFT (4) #define PAGE_AP2_SHIFT (9) #define PAGE_S_MASK (0xFFFFFBFF) #define PAGE_S_SHIFT (10) #define PAGE_NG_MASK (0xFFFFF7FF) #define PAGE_NG_SHIFT (11) #define PAGE_NS_MASK (0xFFFFFFF7) #define PAGE_NS_SHIFT (3) #define OFFSET_1M (0x00100000) #define OFFSET_64K (0x00010000) #define OFFSET_4K (0x00001000) #define DESCRIPTOR_FAULT (0x00000000) /* ########################### MMU Function Access ########################### */ /** \ingroup MMU_FunctionInterface \defgroup MMU_Functions MMU Functions Interface @{ */ /* Attributes enumerations */ /* Region size attributes */ typedef enum { SECTION, PAGE_4k, PAGE_64k, } mmu_region_size_Type; /* Region type attributes */ typedef enum { NORMAL, DEVICE, SHARED_DEVICE, NON_SHARED_DEVICE, STRONGLY_ORDERED } mmu_memory_Type; /* Region cacheability attributes */ typedef enum { NON_CACHEABLE, WB_WA, WT, WB_NO_WA, } mmu_cacheability_Type; /* Region parity check attributes */ typedef enum { ECC_DISABLED, ECC_ENABLED, } mmu_ecc_check_Type; /* Region execution attributes */ typedef enum { EXECUTE, NON_EXECUTE, } mmu_execute_Type; /* Region global attributes */ typedef enum { GLOBAL, NON_GLOBAL, } mmu_global_Type; /* Region shareability attributes */ typedef enum { NON_SHARED, SHARED, } mmu_shared_Type; /* Region security attributes */ typedef enum { SECURE, NON_SECURE, } mmu_secure_Type; /* Region access attributes */ typedef enum { NO_ACCESS, RW, READ, } mmu_access_Type; /* Memory Region definition */ typedef struct RegionStruct { mmu_region_size_Type rg_t; mmu_memory_Type mem_t; uint8_t domain; mmu_cacheability_Type inner_norm_t; mmu_cacheability_Type outer_norm_t; mmu_ecc_check_Type e_t; mmu_execute_Type xn_t; mmu_global_Type g_t; mmu_secure_Type sec_t; mmu_access_Type priv_t; mmu_access_Type user_t; mmu_shared_Type sh_t; } mmu_region_attributes_Type; /** \brief Set section execution-never attribute The function sets section execution-never attribute \param [out] descriptor_l1 L1 descriptor. \param [in] xn Section execution-never attribute : EXECUTE , NON_EXECUTE. \return 0 */ __STATIC_INLINE int __xn_section(uint32_t *descriptor_l1, mmu_execute_Type xn) { *descriptor_l1 &= SECTION_XN_MASK; *descriptor_l1 |= ((xn & 0x1) << SECTION_XN_SHIFT); return 0; } /** \brief Set section domain The function sets section domain \param [out] descriptor_l1 L1 descriptor. \param [in] domain Section domain \return 0 */ __STATIC_INLINE int __domain_section(uint32_t *descriptor_l1, uint8_t domain) { *descriptor_l1 &= SECTION_DOMAIN_MASK; *descriptor_l1 |= ((domain & 0xF) << SECTION_DOMAIN_SHIFT); return 0; } /** \brief Set section parity check The function sets section parity check \param [out] descriptor_l1 L1 descriptor. \param [in] p_bit Parity check: ECC_DISABLED, ECC_ENABLED \return 0 */ __STATIC_INLINE int __p_section(uint32_t *descriptor_l1, mmu_ecc_check_Type p_bit) { *descriptor_l1 &= SECTION_P_MASK; *descriptor_l1 |= ((p_bit & 0x1) << SECTION_P_SHIFT); return 0; } /** \brief Set section access privileges The function sets section access privileges \param [out] descriptor_l1 L1 descriptor. \param [in] user User Level Access: NO_ACCESS, RW, READ \param [in] priv Privilege Level Access: NO_ACCESS, RW, READ \param [in] afe Access flag enable \return 0 */ __STATIC_INLINE int __ap_section(uint32_t *descriptor_l1, mmu_access_Type user, mmu_access_Type priv, uint32_t afe) { uint32_t ap = 0; if (afe == 0) { //full access if ((priv == NO_ACCESS) && (user == NO_ACCESS)) { ap = 0x0; } else if ((priv == RW) && (user == NO_ACCESS)) { ap = 0x1; } else if ((priv == RW) && (user == READ)) { ap = 0x2; } else if ((priv == RW) && (user == RW)) { ap = 0x3; } else if ((priv == READ) && (user == NO_ACCESS)) { ap = 0x5; } else if ((priv == READ) && (user == READ)) { ap = 0x7; } } else { //Simplified access if ((priv == RW) && (user == NO_ACCESS)) { ap = 0x1; } else if ((priv == RW) && (user == RW)) { ap = 0x3; } else if ((priv == READ) && (user == NO_ACCESS)) { ap = 0x5; } else if ((priv == READ) && (user == READ)) { ap = 0x7; } } *descriptor_l1 &= SECTION_AP_MASK; *descriptor_l1 |= (ap & 0x3) << SECTION_AP_SHIFT; *descriptor_l1 |= ((ap & 0x4)>>2) << SECTION_AP2_SHIFT; return 0; } /** \brief Set section shareability The function sets section shareability \param [out] descriptor_l1 L1 descriptor. \param [in] s_bit Section shareability: NON_SHARED, SHARED \return 0 */ __STATIC_INLINE int __shared_section(uint32_t *descriptor_l1, mmu_shared_Type s_bit) { *descriptor_l1 &= SECTION_S_MASK; *descriptor_l1 |= ((s_bit & 0x1) << SECTION_S_SHIFT); return 0; } /** \brief Set section Global attribute The function sets section Global attribute \param [out] descriptor_l1 L1 descriptor. \param [in] g_bit Section attribute: GLOBAL, NON_GLOBAL \return 0 */ __STATIC_INLINE int __global_section(uint32_t *descriptor_l1, mmu_global_Type g_bit) { *descriptor_l1 &= SECTION_NG_MASK; *descriptor_l1 |= ((g_bit & 0x1) << SECTION_NG_SHIFT); return 0; } /** \brief Set section Security attribute The function sets section Global attribute \param [out] descriptor_l1 L1 descriptor. \param [in] s_bit Section Security attribute: SECURE, NON_SECURE \return 0 */ __STATIC_INLINE int __secure_section(uint32_t *descriptor_l1, mmu_secure_Type s_bit) { *descriptor_l1 &= SECTION_NS_MASK; *descriptor_l1 |= ((s_bit & 0x1) << SECTION_NS_SHIFT); return 0; } /* Page 4k or 64k */ /** \brief Set 4k/64k page execution-never attribute The function sets 4k/64k page execution-never attribute \param [out] descriptor_l2 L2 descriptor. \param [in] xn Page execution-never attribute : EXECUTE , NON_EXECUTE. \param [in] page Page size: PAGE_4k, PAGE_64k, \return 0 */ __STATIC_INLINE int __xn_page(uint32_t *descriptor_l2, mmu_execute_Type xn, mmu_region_size_Type page) { if (page == PAGE_4k) { *descriptor_l2 &= PAGE_XN_4K_MASK; *descriptor_l2 |= ((xn & 0x1) << PAGE_XN_4K_SHIFT); } else { *descriptor_l2 &= PAGE_XN_64K_MASK; *descriptor_l2 |= ((xn & 0x1) << PAGE_XN_64K_SHIFT); } return 0; } /** \brief Set 4k/64k page domain The function sets 4k/64k page domain \param [out] descriptor_l1 L1 descriptor. \param [in] domain Page domain \return 0 */ __STATIC_INLINE int __domain_page(uint32_t *descriptor_l1, uint8_t domain) { *descriptor_l1 &= PAGE_DOMAIN_MASK; *descriptor_l1 |= ((domain & 0xf) << PAGE_DOMAIN_SHIFT); return 0; } /** \brief Set 4k/64k page parity check The function sets 4k/64k page parity check \param [out] descriptor_l1 L1 descriptor. \param [in] p_bit Parity check: ECC_DISABLED, ECC_ENABLED \return 0 */ __STATIC_INLINE int __p_page(uint32_t *descriptor_l1, mmu_ecc_check_Type p_bit) { *descriptor_l1 &= SECTION_P_MASK; *descriptor_l1 |= ((p_bit & 0x1) << SECTION_P_SHIFT); return 0; } /** \brief Set 4k/64k page access privileges The function sets 4k/64k page access privileges \param [out] descriptor_l2 L2 descriptor. \param [in] user User Level Access: NO_ACCESS, RW, READ \param [in] priv Privilege Level Access: NO_ACCESS, RW, READ \param [in] afe Access flag enable \return 0 */ __STATIC_INLINE int __ap_page(uint32_t *descriptor_l2, mmu_access_Type user, mmu_access_Type priv, uint32_t afe) { uint32_t ap = 0; if (afe == 0) { //full access if ((priv == NO_ACCESS) && (user == NO_ACCESS)) { ap = 0x0; } else if ((priv == RW) && (user == NO_ACCESS)) { ap = 0x1; } else if ((priv == RW) && (user == READ)) { ap = 0x2; } else if ((priv == RW) && (user == RW)) { ap = 0x3; } else if ((priv == READ) && (user == NO_ACCESS)) { ap = 0x5; } else if ((priv == READ) && (user == READ)) { ap = 0x6; } } else { //Simplified access if ((priv == RW) && (user == NO_ACCESS)) { ap = 0x1; } else if ((priv == RW) && (user == RW)) { ap = 0x3; } else if ((priv == READ) && (user == NO_ACCESS)) { ap = 0x5; } else if ((priv == READ) && (user == READ)) { ap = 0x7; } } *descriptor_l2 &= PAGE_AP_MASK; *descriptor_l2 |= (ap & 0x3) << PAGE_AP_SHIFT; *descriptor_l2 |= ((ap & 0x4)>>2) << PAGE_AP2_SHIFT; return 0; } /** \brief Set 4k/64k page shareability The function sets 4k/64k page shareability \param [out] descriptor_l2 L2 descriptor. \param [in] s_bit 4k/64k page shareability: NON_SHARED, SHARED \return 0 */ __STATIC_INLINE int __shared_page(uint32_t *descriptor_l2, mmu_shared_Type s_bit) { *descriptor_l2 &= PAGE_S_MASK; *descriptor_l2 |= ((s_bit & 0x1) << PAGE_S_SHIFT); return 0; } /** \brief Set 4k/64k page Global attribute The function sets 4k/64k page Global attribute \param [out] descriptor_l2 L2 descriptor. \param [in] g_bit 4k/64k page attribute: GLOBAL, NON_GLOBAL \return 0 */ __STATIC_INLINE int __global_page(uint32_t *descriptor_l2, mmu_global_Type g_bit) { *descriptor_l2 &= PAGE_NG_MASK; *descriptor_l2 |= ((g_bit & 0x1) << PAGE_NG_SHIFT); return 0; } /** \brief Set 4k/64k page Security attribute The function sets 4k/64k page Global attribute \param [out] descriptor_l1 L1 descriptor. \param [in] s_bit 4k/64k page Security attribute: SECURE, NON_SECURE \return 0 */ __STATIC_INLINE int __secure_page(uint32_t *descriptor_l1, mmu_secure_Type s_bit) { *descriptor_l1 &= PAGE_NS_MASK; *descriptor_l1 |= ((s_bit & 0x1) << PAGE_NS_SHIFT); return 0; } /** \brief Set Section memory attributes The function sets section memory attributes \param [out] descriptor_l1 L1 descriptor. \param [in] mem Section memory type: NORMAL, DEVICE, SHARED_DEVICE, NON_SHARED_DEVICE, STRONGLY_ORDERED \param [in] outer Outer cacheability: NON_CACHEABLE, WB_WA, WT, WB_NO_WA, \param [in] inner Inner cacheability: NON_CACHEABLE, WB_WA, WT, WB_NO_WA, \return 0 */ __STATIC_INLINE int __memory_section(uint32_t *descriptor_l1, mmu_memory_Type mem, mmu_cacheability_Type outer, mmu_cacheability_Type inner) { *descriptor_l1 &= SECTION_TEXCB_MASK; if (STRONGLY_ORDERED == mem) { return 0; } else if (SHARED_DEVICE == mem) { *descriptor_l1 |= (1 << SECTION_B_SHIFT); } else if (NON_SHARED_DEVICE == mem) { *descriptor_l1 |= (1 << SECTION_TEX1_SHIFT); } else if (NORMAL == mem) { *descriptor_l1 |= 1 << SECTION_TEX2_SHIFT; switch(inner) { case NON_CACHEABLE: break; case WB_WA: *descriptor_l1 |= (1 << SECTION_B_SHIFT); break; case WT: *descriptor_l1 |= 1 << SECTION_C_SHIFT; break; case WB_NO_WA: *descriptor_l1 |= (1 << SECTION_B_SHIFT) | (1 << SECTION_C_SHIFT); break; } switch(outer) { case NON_CACHEABLE: break; case WB_WA: *descriptor_l1 |= (1 << SECTION_TEX0_SHIFT); break; case WT: *descriptor_l1 |= 1 << SECTION_TEX1_SHIFT; break; case WB_NO_WA: *descriptor_l1 |= (1 << SECTION_TEX0_SHIFT) | (1 << SECTION_TEX0_SHIFT); break; } } return 0; } /** \brief Set 4k/64k page memory attributes The function sets 4k/64k page memory attributes \param [out] descriptor_l2 L2 descriptor. \param [in] mem 4k/64k page memory type: NORMAL, DEVICE, SHARED_DEVICE, NON_SHARED_DEVICE, STRONGLY_ORDERED \param [in] outer Outer cacheability: NON_CACHEABLE, WB_WA, WT, WB_NO_WA, \param [in] inner Inner cacheability: NON_CACHEABLE, WB_WA, WT, WB_NO_WA, \return 0 */ __STATIC_INLINE int __memory_page(uint32_t *descriptor_l2, mmu_memory_Type mem, mmu_cacheability_Type outer, mmu_cacheability_Type inner, mmu_region_size_Type page) { *descriptor_l2 &= PAGE_4K_TEXCB_MASK; if (page == PAGE_64k) { //same as section __memory_section(descriptor_l2, mem, outer, inner); } else { if (STRONGLY_ORDERED == mem) { return 0; } else if (SHARED_DEVICE == mem) { *descriptor_l2 |= (1 << PAGE_4K_B_SHIFT); } else if (NON_SHARED_DEVICE == mem) { *descriptor_l2 |= (1 << PAGE_4K_TEX1_SHIFT); } else if (NORMAL == mem) { *descriptor_l2 |= 1 << PAGE_4K_TEX2_SHIFT; switch(inner) { case NON_CACHEABLE: break; case WB_WA: *descriptor_l2 |= (1 << PAGE_4K_B_SHIFT); break; case WT: *descriptor_l2 |= 1 << PAGE_4K_C_SHIFT; break; case WB_NO_WA: *descriptor_l2 |= (1 << PAGE_4K_B_SHIFT) | (1 << PAGE_4K_C_SHIFT); break; } switch(outer) { case NON_CACHEABLE: break; case WB_WA: *descriptor_l2 |= (1 << PAGE_4K_TEX0_SHIFT); break; case WT: *descriptor_l2 |= 1 << PAGE_4K_TEX1_SHIFT; break; case WB_NO_WA: *descriptor_l2 |= (1 << PAGE_4K_TEX0_SHIFT) | (1 << PAGE_4K_TEX0_SHIFT); break; } } } return 0; } /** \brief Create a L1 section descriptor The function creates a section descriptor. Assumptions: - 16MB super sections not supported - TEX remap disabled, so memory type and attributes are described directly by bits in the descriptor - Functions always return 0 \param [out] descriptor L1 descriptor \param [out] descriptor2 L2 descriptor \param [in] reg Section attributes \return 0 */ __STATIC_INLINE int __get_section_descriptor(uint32_t *descriptor, mmu_region_attributes_Type reg) { *descriptor = 0; __memory_section(descriptor, reg.mem_t, reg.outer_norm_t, reg.inner_norm_t); __xn_section(descriptor,reg.xn_t); __domain_section(descriptor, reg.domain); __p_section(descriptor, reg.e_t); __ap_section(descriptor, reg.priv_t, reg.user_t, 1); __shared_section(descriptor,reg.sh_t); __global_section(descriptor,reg.g_t); __secure_section(descriptor,reg.sec_t); *descriptor &= SECTION_MASK; *descriptor |= SECTION_DESCRIPTOR; return 0; } /** \brief Create a L1 and L2 4k/64k page descriptor The function creates a 4k/64k page descriptor. Assumptions: - TEX remap disabled, so memory type and attributes are described directly by bits in the descriptor - Functions always return 0 \param [out] descriptor L1 descriptor \param [out] descriptor2 L2 descriptor \param [in] reg 4k/64k page attributes \return 0 */ __STATIC_INLINE int __get_page_descriptor(uint32_t *descriptor, uint32_t *descriptor2, mmu_region_attributes_Type reg) { *descriptor = 0; *descriptor2 = 0; switch (reg.rg_t) { case PAGE_4k: __memory_page(descriptor2, reg.mem_t, reg.outer_norm_t, reg.inner_norm_t, PAGE_4k); __xn_page(descriptor2, reg.xn_t, PAGE_4k); __domain_page(descriptor, reg.domain); __p_page(descriptor, reg.e_t); __ap_page(descriptor2, reg.priv_t, reg.user_t, 1); __shared_page(descriptor2,reg.sh_t); __global_page(descriptor2,reg.g_t); __secure_page(descriptor,reg.sec_t); *descriptor &= PAGE_L1_MASK; *descriptor |= PAGE_L1_DESCRIPTOR; *descriptor2 &= PAGE_L2_4K_MASK; *descriptor2 |= PAGE_L2_4K_DESC; break; case PAGE_64k: __memory_page(descriptor2, reg.mem_t, reg.outer_norm_t, reg.inner_norm_t, PAGE_64k); __xn_page(descriptor2, reg.xn_t, PAGE_64k); __domain_page(descriptor, reg.domain); __p_page(descriptor, reg.e_t); __ap_page(descriptor2, reg.priv_t, reg.user_t, 1); __shared_page(descriptor2,reg.sh_t); __global_page(descriptor2,reg.g_t); __secure_page(descriptor,reg.sec_t); *descriptor &= PAGE_L1_MASK; *descriptor |= PAGE_L1_DESCRIPTOR; *descriptor2 &= PAGE_L2_64K_MASK; *descriptor2 |= PAGE_L2_64K_DESC; break; case SECTION: //error break; } return 0; } /** \brief Create a 1MB Section \param [in] ttb Translation table base address \param [in] base_address Section base address \param [in] count Number of sections to create \param [in] descriptor_l1 L1 descriptor (region attributes) */ __STATIC_INLINE void __TTSection(uint32_t *ttb, uint32_t base_address, uint32_t count, uint32_t descriptor_l1) { uint32_t offset; uint32_t entry; uint32_t i; offset = base_address >> 20; entry = (base_address & 0xFFF00000) | descriptor_l1; //4 bytes aligned ttb = ttb + offset; for (i = 0; i < count; i++ ) { //4 bytes aligned *ttb++ = entry; entry += OFFSET_1M; } } /** \brief Create a 4k page entry \param [in] ttb L1 table base address \param [in] base_address 4k base address \param [in] count Number of 4k pages to create \param [in] descriptor_l1 L1 descriptor (region attributes) \param [in] ttb_l2 L2 table base address \param [in] descriptor_l2 L2 descriptor (region attributes) */ __STATIC_INLINE void __TTPage_4k(uint32_t *ttb, uint32_t base_address, uint32_t count, uint32_t descriptor_l1, uint32_t *ttb_l2, uint32_t descriptor_l2 ) { uint32_t offset, offset2; uint32_t entry, entry2; uint32_t i; offset = base_address >> 20; entry = ((int)ttb_l2 & 0xFFFFFC00) | descriptor_l1; //4 bytes aligned ttb += offset; //create l1_entry *ttb = entry; offset2 = (base_address & 0xff000) >> 12; ttb_l2 += offset2; entry2 = (base_address & 0xFFFFF000) | descriptor_l2; for (i = 0; i < count; i++ ) { //4 bytes aligned *ttb_l2++ = entry2; entry2 += OFFSET_4K; } } /** \brief Create a 64k page entry \param [in] ttb L1 table base address \param [in] base_address 64k base address \param [in] count Number of 64k pages to create \param [in] descriptor_l1 L1 descriptor (region attributes) \param [in] ttb_l2 L2 table base address \param [in] descriptor_l2 L2 descriptor (region attributes) */ __STATIC_INLINE void __TTPage_64k(uint32_t *ttb, uint32_t base_address, uint32_t count, uint32_t descriptor_l1, uint32_t *ttb_l2, uint32_t descriptor_l2 ) { uint32_t offset, offset2; uint32_t entry, entry2; uint32_t i,j; offset = base_address >> 20; entry = ((int)ttb_l2 & 0xFFFFFC00) | descriptor_l1; //4 bytes aligned ttb += offset; //create l1_entry *ttb = entry; offset2 = (base_address & 0xff000) >> 12; ttb_l2 += offset2; entry2 = (base_address & 0xFFFF0000) | descriptor_l2; for (i = 0; i < count; i++ ) { //create 16 entries for (j = 0; j < 16; j++) //4 bytes aligned *ttb_l2++ = entry2; entry2 += OFFSET_64K; } } /*@} end of MMU_Functions */ #endif #ifdef __cplusplus } #endif ================================================ FILE: Zelig/mbed/TARGET_NUCLEO_F091RC/core_cm0.h ================================================ /**************************************************************************//** * @file core_cm0.h * @brief CMSIS Cortex-M0 Core Peripheral Access Layer Header File * @version V4.10 * @date 18. March 2015 * * @note * ******************************************************************************/ /* Copyright (c) 2009 - 2015 ARM LIMITED All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: - Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. - Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. - Neither the name of ARM 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 COPYRIGHT HOLDERS AND 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. ---------------------------------------------------------------------------*/ #if defined ( __ICCARM__ ) #pragma system_include /* treat file as system include file for MISRA check */ #endif #ifndef __CORE_CM0_H_GENERIC #define __CORE_CM0_H_GENERIC #ifdef __cplusplus extern "C" { #endif /** \page CMSIS_MISRA_Exceptions MISRA-C:2004 Compliance Exceptions CMSIS violates the following MISRA-C:2004 rules: \li Required Rule 8.5, object/function definition in header file.
Function definitions in header files are used to allow 'inlining'. \li Required Rule 18.4, declaration of union type or object of union type: '{...}'.
Unions are used for effective representation of core registers. \li Advisory Rule 19.7, Function-like macro defined.
Function-like macros are used to allow more efficient code. */ /******************************************************************************* * CMSIS definitions ******************************************************************************/ /** \ingroup Cortex_M0 @{ */ /* CMSIS CM0 definitions */ #define __CM0_CMSIS_VERSION_MAIN (0x04) /*!< [31:16] CMSIS HAL main version */ #define __CM0_CMSIS_VERSION_SUB (0x00) /*!< [15:0] CMSIS HAL sub version */ #define __CM0_CMSIS_VERSION ((__CM0_CMSIS_VERSION_MAIN << 16) | \ __CM0_CMSIS_VERSION_SUB ) /*!< CMSIS HAL version number */ #define __CORTEX_M (0x00) /*!< Cortex-M Core */ #if defined ( __CC_ARM ) #define __ASM __asm /*!< asm keyword for ARM Compiler */ #define __INLINE __inline /*!< inline keyword for ARM Compiler */ #define __STATIC_INLINE static __inline #elif defined ( __GNUC__ ) #define __ASM __asm /*!< asm keyword for GNU Compiler */ #define __INLINE inline /*!< inline keyword for GNU Compiler */ #define __STATIC_INLINE static inline #elif defined ( __ICCARM__ ) #define __ASM __asm /*!< asm keyword for IAR Compiler */ #define __INLINE inline /*!< inline keyword for IAR Compiler. Only available in High optimization mode! */ #define __STATIC_INLINE static inline #elif defined ( __TMS470__ ) #define __ASM __asm /*!< asm keyword for TI CCS Compiler */ #define __STATIC_INLINE static inline #elif defined ( __TASKING__ ) #define __ASM __asm /*!< asm keyword for TASKING Compiler */ #define __INLINE inline /*!< inline keyword for TASKING Compiler */ #define __STATIC_INLINE static inline #elif defined ( __CSMC__ ) #define __packed #define __ASM _asm /*!< asm keyword for COSMIC Compiler */ #define __INLINE inline /*use -pc99 on compile line !< inline keyword for COSMIC Compiler */ #define __STATIC_INLINE static inline #endif /** __FPU_USED indicates whether an FPU is used or not. This core does not support an FPU at all */ #define __FPU_USED 0 #if defined ( __CC_ARM ) #if defined __TARGET_FPU_VFP #warning "Compiler generates FPU instructions for a device without an FPU (check __FPU_PRESENT)" #endif #elif defined ( __GNUC__ ) #if defined (__VFP_FP__) && !defined(__SOFTFP__) #warning "Compiler generates FPU instructions for a device without an FPU (check __FPU_PRESENT)" #endif #elif defined ( __ICCARM__ ) #if defined __ARMVFP__ #warning "Compiler generates FPU instructions for a device without an FPU (check __FPU_PRESENT)" #endif #elif defined ( __TMS470__ ) #if defined __TI__VFP_SUPPORT____ #warning "Compiler generates FPU instructions for a device without an FPU (check __FPU_PRESENT)" #endif #elif defined ( __TASKING__ ) #if defined __FPU_VFP__ #error "Compiler generates FPU instructions for a device without an FPU (check __FPU_PRESENT)" #endif #elif defined ( __CSMC__ ) /* Cosmic */ #if ( __CSMC__ & 0x400) // FPU present for parser #error "Compiler generates FPU instructions for a device without an FPU (check __FPU_PRESENT)" #endif #endif #include /* standard types definitions */ #include /* Core Instruction Access */ #include /* Core Function Access */ #ifdef __cplusplus } #endif #endif /* __CORE_CM0_H_GENERIC */ #ifndef __CMSIS_GENERIC #ifndef __CORE_CM0_H_DEPENDANT #define __CORE_CM0_H_DEPENDANT #ifdef __cplusplus extern "C" { #endif /* check device defines and use defaults */ #if defined __CHECK_DEVICE_DEFINES #ifndef __CM0_REV #define __CM0_REV 0x0000 #warning "__CM0_REV not defined in device header file; using default!" #endif #ifndef __NVIC_PRIO_BITS #define __NVIC_PRIO_BITS 2 #warning "__NVIC_PRIO_BITS not defined in device header file; using default!" #endif #ifndef __Vendor_SysTickConfig #define __Vendor_SysTickConfig 0 #warning "__Vendor_SysTickConfig not defined in device header file; using default!" #endif #endif /* IO definitions (access restrictions to peripheral registers) */ /** \defgroup CMSIS_glob_defs CMSIS Global Defines IO Type Qualifiers are used \li to specify the access to peripheral variables. \li for automatic generation of peripheral register debug information. */ #ifdef __cplusplus #define __I volatile /*!< Defines 'read only' permissions */ #else #define __I volatile const /*!< Defines 'read only' permissions */ #endif #define __O volatile /*!< Defines 'write only' permissions */ #define __IO volatile /*!< Defines 'read / write' permissions */ /*@} end of group Cortex_M0 */ /******************************************************************************* * Register Abstraction Core Register contain: - Core Register - Core NVIC Register - Core SCB Register - Core SysTick Register ******************************************************************************/ /** \defgroup CMSIS_core_register Defines and Type Definitions \brief Type definitions and defines for Cortex-M processor based devices. */ /** \ingroup CMSIS_core_register \defgroup CMSIS_CORE Status and Control Registers \brief Core Register type definitions. @{ */ /** \brief Union type to access the Application Program Status Register (APSR). */ typedef union { struct { uint32_t _reserved0:28; /*!< bit: 0..27 Reserved */ uint32_t V:1; /*!< bit: 28 Overflow condition code flag */ uint32_t C:1; /*!< bit: 29 Carry condition code flag */ uint32_t Z:1; /*!< bit: 30 Zero condition code flag */ uint32_t N:1; /*!< bit: 31 Negative condition code flag */ } b; /*!< Structure used for bit access */ uint32_t w; /*!< Type used for word access */ } APSR_Type; /* APSR Register Definitions */ #define APSR_N_Pos 31 /*!< APSR: N Position */ #define APSR_N_Msk (1UL << APSR_N_Pos) /*!< APSR: N Mask */ #define APSR_Z_Pos 30 /*!< APSR: Z Position */ #define APSR_Z_Msk (1UL << APSR_Z_Pos) /*!< APSR: Z Mask */ #define APSR_C_Pos 29 /*!< APSR: C Position */ #define APSR_C_Msk (1UL << APSR_C_Pos) /*!< APSR: C Mask */ #define APSR_V_Pos 28 /*!< APSR: V Position */ #define APSR_V_Msk (1UL << APSR_V_Pos) /*!< APSR: V Mask */ /** \brief Union type to access the Interrupt Program Status Register (IPSR). */ typedef union { struct { uint32_t ISR:9; /*!< bit: 0.. 8 Exception number */ uint32_t _reserved0:23; /*!< bit: 9..31 Reserved */ } b; /*!< Structure used for bit access */ uint32_t w; /*!< Type used for word access */ } IPSR_Type; /* IPSR Register Definitions */ #define IPSR_ISR_Pos 0 /*!< IPSR: ISR Position */ #define IPSR_ISR_Msk (0x1FFUL /*<< IPSR_ISR_Pos*/) /*!< IPSR: ISR Mask */ /** \brief Union type to access the Special-Purpose Program Status Registers (xPSR). */ typedef union { struct { uint32_t ISR:9; /*!< bit: 0.. 8 Exception number */ uint32_t _reserved0:15; /*!< bit: 9..23 Reserved */ uint32_t T:1; /*!< bit: 24 Thumb bit (read 0) */ uint32_t _reserved1:3; /*!< bit: 25..27 Reserved */ uint32_t V:1; /*!< bit: 28 Overflow condition code flag */ uint32_t C:1; /*!< bit: 29 Carry condition code flag */ uint32_t Z:1; /*!< bit: 30 Zero condition code flag */ uint32_t N:1; /*!< bit: 31 Negative condition code flag */ } b; /*!< Structure used for bit access */ uint32_t w; /*!< Type used for word access */ } xPSR_Type; /* xPSR Register Definitions */ #define xPSR_N_Pos 31 /*!< xPSR: N Position */ #define xPSR_N_Msk (1UL << xPSR_N_Pos) /*!< xPSR: N Mask */ #define xPSR_Z_Pos 30 /*!< xPSR: Z Position */ #define xPSR_Z_Msk (1UL << xPSR_Z_Pos) /*!< xPSR: Z Mask */ #define xPSR_C_Pos 29 /*!< xPSR: C Position */ #define xPSR_C_Msk (1UL << xPSR_C_Pos) /*!< xPSR: C Mask */ #define xPSR_V_Pos 28 /*!< xPSR: V Position */ #define xPSR_V_Msk (1UL << xPSR_V_Pos) /*!< xPSR: V Mask */ #define xPSR_T_Pos 24 /*!< xPSR: T Position */ #define xPSR_T_Msk (1UL << xPSR_T_Pos) /*!< xPSR: T Mask */ #define xPSR_ISR_Pos 0 /*!< xPSR: ISR Position */ #define xPSR_ISR_Msk (0x1FFUL /*<< xPSR_ISR_Pos*/) /*!< xPSR: ISR Mask */ /** \brief Union type to access the Control Registers (CONTROL). */ typedef union { struct { uint32_t _reserved0:1; /*!< bit: 0 Reserved */ uint32_t SPSEL:1; /*!< bit: 1 Stack to be used */ uint32_t _reserved1:30; /*!< bit: 2..31 Reserved */ } b; /*!< Structure used for bit access */ uint32_t w; /*!< Type used for word access */ } CONTROL_Type; /* CONTROL Register Definitions */ #define CONTROL_SPSEL_Pos 1 /*!< CONTROL: SPSEL Position */ #define CONTROL_SPSEL_Msk (1UL << CONTROL_SPSEL_Pos) /*!< CONTROL: SPSEL Mask */ /*@} end of group CMSIS_CORE */ /** \ingroup CMSIS_core_register \defgroup CMSIS_NVIC Nested Vectored Interrupt Controller (NVIC) \brief Type definitions for the NVIC Registers @{ */ /** \brief Structure type to access the Nested Vectored Interrupt Controller (NVIC). */ typedef struct { __IO uint32_t ISER[1]; /*!< Offset: 0x000 (R/W) Interrupt Set Enable Register */ uint32_t RESERVED0[31]; __IO uint32_t ICER[1]; /*!< Offset: 0x080 (R/W) Interrupt Clear Enable Register */ uint32_t RSERVED1[31]; __IO uint32_t ISPR[1]; /*!< Offset: 0x100 (R/W) Interrupt Set Pending Register */ uint32_t RESERVED2[31]; __IO uint32_t ICPR[1]; /*!< Offset: 0x180 (R/W) Interrupt Clear Pending Register */ uint32_t RESERVED3[31]; uint32_t RESERVED4[64]; __IO uint32_t IP[8]; /*!< Offset: 0x300 (R/W) Interrupt Priority Register */ } NVIC_Type; /*@} end of group CMSIS_NVIC */ /** \ingroup CMSIS_core_register \defgroup CMSIS_SCB System Control Block (SCB) \brief Type definitions for the System Control Block Registers @{ */ /** \brief Structure type to access the System Control Block (SCB). */ typedef struct { __I uint32_t CPUID; /*!< Offset: 0x000 (R/ ) CPUID Base Register */ __IO uint32_t ICSR; /*!< Offset: 0x004 (R/W) Interrupt Control and State Register */ uint32_t RESERVED0; __IO uint32_t AIRCR; /*!< Offset: 0x00C (R/W) Application Interrupt and Reset Control Register */ __IO uint32_t SCR; /*!< Offset: 0x010 (R/W) System Control Register */ __IO uint32_t CCR; /*!< Offset: 0x014 (R/W) Configuration Control Register */ uint32_t RESERVED1; __IO uint32_t SHP[2]; /*!< Offset: 0x01C (R/W) System Handlers Priority Registers. [0] is RESERVED */ __IO uint32_t SHCSR; /*!< Offset: 0x024 (R/W) System Handler Control and State Register */ } SCB_Type; /* SCB CPUID Register Definitions */ #define SCB_CPUID_IMPLEMENTER_Pos 24 /*!< SCB CPUID: IMPLEMENTER Position */ #define SCB_CPUID_IMPLEMENTER_Msk (0xFFUL << SCB_CPUID_IMPLEMENTER_Pos) /*!< SCB CPUID: IMPLEMENTER Mask */ #define SCB_CPUID_VARIANT_Pos 20 /*!< SCB CPUID: VARIANT Position */ #define SCB_CPUID_VARIANT_Msk (0xFUL << SCB_CPUID_VARIANT_Pos) /*!< SCB CPUID: VARIANT Mask */ #define SCB_CPUID_ARCHITECTURE_Pos 16 /*!< SCB CPUID: ARCHITECTURE Position */ #define SCB_CPUID_ARCHITECTURE_Msk (0xFUL << SCB_CPUID_ARCHITECTURE_Pos) /*!< SCB CPUID: ARCHITECTURE Mask */ #define SCB_CPUID_PARTNO_Pos 4 /*!< SCB CPUID: PARTNO Position */ #define SCB_CPUID_PARTNO_Msk (0xFFFUL << SCB_CPUID_PARTNO_Pos) /*!< SCB CPUID: PARTNO Mask */ #define SCB_CPUID_REVISION_Pos 0 /*!< SCB CPUID: REVISION Position */ #define SCB_CPUID_REVISION_Msk (0xFUL /*<< SCB_CPUID_REVISION_Pos*/) /*!< SCB CPUID: REVISION Mask */ /* SCB Interrupt Control State Register Definitions */ #define SCB_ICSR_NMIPENDSET_Pos 31 /*!< SCB ICSR: NMIPENDSET Position */ #define SCB_ICSR_NMIPENDSET_Msk (1UL << SCB_ICSR_NMIPENDSET_Pos) /*!< SCB ICSR: NMIPENDSET Mask */ #define SCB_ICSR_PENDSVSET_Pos 28 /*!< SCB ICSR: PENDSVSET Position */ #define SCB_ICSR_PENDSVSET_Msk (1UL << SCB_ICSR_PENDSVSET_Pos) /*!< SCB ICSR: PENDSVSET Mask */ #define SCB_ICSR_PENDSVCLR_Pos 27 /*!< SCB ICSR: PENDSVCLR Position */ #define SCB_ICSR_PENDSVCLR_Msk (1UL << SCB_ICSR_PENDSVCLR_Pos) /*!< SCB ICSR: PENDSVCLR Mask */ #define SCB_ICSR_PENDSTSET_Pos 26 /*!< SCB ICSR: PENDSTSET Position */ #define SCB_ICSR_PENDSTSET_Msk (1UL << SCB_ICSR_PENDSTSET_Pos) /*!< SCB ICSR: PENDSTSET Mask */ #define SCB_ICSR_PENDSTCLR_Pos 25 /*!< SCB ICSR: PENDSTCLR Position */ #define SCB_ICSR_PENDSTCLR_Msk (1UL << SCB_ICSR_PENDSTCLR_Pos) /*!< SCB ICSR: PENDSTCLR Mask */ #define SCB_ICSR_ISRPREEMPT_Pos 23 /*!< SCB ICSR: ISRPREEMPT Position */ #define SCB_ICSR_ISRPREEMPT_Msk (1UL << SCB_ICSR_ISRPREEMPT_Pos) /*!< SCB ICSR: ISRPREEMPT Mask */ #define SCB_ICSR_ISRPENDING_Pos 22 /*!< SCB ICSR: ISRPENDING Position */ #define SCB_ICSR_ISRPENDING_Msk (1UL << SCB_ICSR_ISRPENDING_Pos) /*!< SCB ICSR: ISRPENDING Mask */ #define SCB_ICSR_VECTPENDING_Pos 12 /*!< SCB ICSR: VECTPENDING Position */ #define SCB_ICSR_VECTPENDING_Msk (0x1FFUL << SCB_ICSR_VECTPENDING_Pos) /*!< SCB ICSR: VECTPENDING Mask */ #define SCB_ICSR_VECTACTIVE_Pos 0 /*!< SCB ICSR: VECTACTIVE Position */ #define SCB_ICSR_VECTACTIVE_Msk (0x1FFUL /*<< SCB_ICSR_VECTACTIVE_Pos*/) /*!< SCB ICSR: VECTACTIVE Mask */ /* SCB Application Interrupt and Reset Control Register Definitions */ #define SCB_AIRCR_VECTKEY_Pos 16 /*!< SCB AIRCR: VECTKEY Position */ #define SCB_AIRCR_VECTKEY_Msk (0xFFFFUL << SCB_AIRCR_VECTKEY_Pos) /*!< SCB AIRCR: VECTKEY Mask */ #define SCB_AIRCR_VECTKEYSTAT_Pos 16 /*!< SCB AIRCR: VECTKEYSTAT Position */ #define SCB_AIRCR_VECTKEYSTAT_Msk (0xFFFFUL << SCB_AIRCR_VECTKEYSTAT_Pos) /*!< SCB AIRCR: VECTKEYSTAT Mask */ #define SCB_AIRCR_ENDIANESS_Pos 15 /*!< SCB AIRCR: ENDIANESS Position */ #define SCB_AIRCR_ENDIANESS_Msk (1UL << SCB_AIRCR_ENDIANESS_Pos) /*!< SCB AIRCR: ENDIANESS Mask */ #define SCB_AIRCR_SYSRESETREQ_Pos 2 /*!< SCB AIRCR: SYSRESETREQ Position */ #define SCB_AIRCR_SYSRESETREQ_Msk (1UL << SCB_AIRCR_SYSRESETREQ_Pos) /*!< SCB AIRCR: SYSRESETREQ Mask */ #define SCB_AIRCR_VECTCLRACTIVE_Pos 1 /*!< SCB AIRCR: VECTCLRACTIVE Position */ #define SCB_AIRCR_VECTCLRACTIVE_Msk (1UL << SCB_AIRCR_VECTCLRACTIVE_Pos) /*!< SCB AIRCR: VECTCLRACTIVE Mask */ /* SCB System Control Register Definitions */ #define SCB_SCR_SEVONPEND_Pos 4 /*!< SCB SCR: SEVONPEND Position */ #define SCB_SCR_SEVONPEND_Msk (1UL << SCB_SCR_SEVONPEND_Pos) /*!< SCB SCR: SEVONPEND Mask */ #define SCB_SCR_SLEEPDEEP_Pos 2 /*!< SCB SCR: SLEEPDEEP Position */ #define SCB_SCR_SLEEPDEEP_Msk (1UL << SCB_SCR_SLEEPDEEP_Pos) /*!< SCB SCR: SLEEPDEEP Mask */ #define SCB_SCR_SLEEPONEXIT_Pos 1 /*!< SCB SCR: SLEEPONEXIT Position */ #define SCB_SCR_SLEEPONEXIT_Msk (1UL << SCB_SCR_SLEEPONEXIT_Pos) /*!< SCB SCR: SLEEPONEXIT Mask */ /* SCB Configuration Control Register Definitions */ #define SCB_CCR_STKALIGN_Pos 9 /*!< SCB CCR: STKALIGN Position */ #define SCB_CCR_STKALIGN_Msk (1UL << SCB_CCR_STKALIGN_Pos) /*!< SCB CCR: STKALIGN Mask */ #define SCB_CCR_UNALIGN_TRP_Pos 3 /*!< SCB CCR: UNALIGN_TRP Position */ #define SCB_CCR_UNALIGN_TRP_Msk (1UL << SCB_CCR_UNALIGN_TRP_Pos) /*!< SCB CCR: UNALIGN_TRP Mask */ /* SCB System Handler Control and State Register Definitions */ #define SCB_SHCSR_SVCALLPENDED_Pos 15 /*!< SCB SHCSR: SVCALLPENDED Position */ #define SCB_SHCSR_SVCALLPENDED_Msk (1UL << SCB_SHCSR_SVCALLPENDED_Pos) /*!< SCB SHCSR: SVCALLPENDED Mask */ /*@} end of group CMSIS_SCB */ /** \ingroup CMSIS_core_register \defgroup CMSIS_SysTick System Tick Timer (SysTick) \brief Type definitions for the System Timer Registers. @{ */ /** \brief Structure type to access the System Timer (SysTick). */ typedef struct { __IO uint32_t CTRL; /*!< Offset: 0x000 (R/W) SysTick Control and Status Register */ __IO uint32_t LOAD; /*!< Offset: 0x004 (R/W) SysTick Reload Value Register */ __IO uint32_t VAL; /*!< Offset: 0x008 (R/W) SysTick Current Value Register */ __I uint32_t CALIB; /*!< Offset: 0x00C (R/ ) SysTick Calibration Register */ } SysTick_Type; /* SysTick Control / Status Register Definitions */ #define SysTick_CTRL_COUNTFLAG_Pos 16 /*!< SysTick CTRL: COUNTFLAG Position */ #define SysTick_CTRL_COUNTFLAG_Msk (1UL << SysTick_CTRL_COUNTFLAG_Pos) /*!< SysTick CTRL: COUNTFLAG Mask */ #define SysTick_CTRL_CLKSOURCE_Pos 2 /*!< SysTick CTRL: CLKSOURCE Position */ #define SysTick_CTRL_CLKSOURCE_Msk (1UL << SysTick_CTRL_CLKSOURCE_Pos) /*!< SysTick CTRL: CLKSOURCE Mask */ #define SysTick_CTRL_TICKINT_Pos 1 /*!< SysTick CTRL: TICKINT Position */ #define SysTick_CTRL_TICKINT_Msk (1UL << SysTick_CTRL_TICKINT_Pos) /*!< SysTick CTRL: TICKINT Mask */ #define SysTick_CTRL_ENABLE_Pos 0 /*!< SysTick CTRL: ENABLE Position */ #define SysTick_CTRL_ENABLE_Msk (1UL /*<< SysTick_CTRL_ENABLE_Pos*/) /*!< SysTick CTRL: ENABLE Mask */ /* SysTick Reload Register Definitions */ #define SysTick_LOAD_RELOAD_Pos 0 /*!< SysTick LOAD: RELOAD Position */ #define SysTick_LOAD_RELOAD_Msk (0xFFFFFFUL /*<< SysTick_LOAD_RELOAD_Pos*/) /*!< SysTick LOAD: RELOAD Mask */ /* SysTick Current Register Definitions */ #define SysTick_VAL_CURRENT_Pos 0 /*!< SysTick VAL: CURRENT Position */ #define SysTick_VAL_CURRENT_Msk (0xFFFFFFUL /*<< SysTick_VAL_CURRENT_Pos*/) /*!< SysTick VAL: CURRENT Mask */ /* SysTick Calibration Register Definitions */ #define SysTick_CALIB_NOREF_Pos 31 /*!< SysTick CALIB: NOREF Position */ #define SysTick_CALIB_NOREF_Msk (1UL << SysTick_CALIB_NOREF_Pos) /*!< SysTick CALIB: NOREF Mask */ #define SysTick_CALIB_SKEW_Pos 30 /*!< SysTick CALIB: SKEW Position */ #define SysTick_CALIB_SKEW_Msk (1UL << SysTick_CALIB_SKEW_Pos) /*!< SysTick CALIB: SKEW Mask */ #define SysTick_CALIB_TENMS_Pos 0 /*!< SysTick CALIB: TENMS Position */ #define SysTick_CALIB_TENMS_Msk (0xFFFFFFUL /*<< SysTick_CALIB_TENMS_Pos*/) /*!< SysTick CALIB: TENMS Mask */ /*@} end of group CMSIS_SysTick */ /** \ingroup CMSIS_core_register \defgroup CMSIS_CoreDebug Core Debug Registers (CoreDebug) \brief Cortex-M0 Core Debug Registers (DCB registers, SHCSR, and DFSR) are only accessible over DAP and not via processor. Therefore they are not covered by the Cortex-M0 header file. @{ */ /*@} end of group CMSIS_CoreDebug */ /** \ingroup CMSIS_core_register \defgroup CMSIS_core_base Core Definitions \brief Definitions for base addresses, unions, and structures. @{ */ /* Memory mapping of Cortex-M0 Hardware */ #define SCS_BASE (0xE000E000UL) /*!< System Control Space Base Address */ #define SysTick_BASE (SCS_BASE + 0x0010UL) /*!< SysTick Base Address */ #define NVIC_BASE (SCS_BASE + 0x0100UL) /*!< NVIC Base Address */ #define SCB_BASE (SCS_BASE + 0x0D00UL) /*!< System Control Block Base Address */ #define SCB ((SCB_Type *) SCB_BASE ) /*!< SCB configuration struct */ #define SysTick ((SysTick_Type *) SysTick_BASE ) /*!< SysTick configuration struct */ #define NVIC ((NVIC_Type *) NVIC_BASE ) /*!< NVIC configuration struct */ /*@} */ /******************************************************************************* * Hardware Abstraction Layer Core Function Interface contains: - Core NVIC Functions - Core SysTick Functions - Core Register Access Functions ******************************************************************************/ /** \defgroup CMSIS_Core_FunctionInterface Functions and Instructions Reference */ /* ########################## NVIC functions #################################### */ /** \ingroup CMSIS_Core_FunctionInterface \defgroup CMSIS_Core_NVICFunctions NVIC Functions \brief Functions that manage interrupts and exceptions via the NVIC. @{ */ /* Interrupt Priorities are WORD accessible only under ARMv6M */ /* The following MACROS handle generation of the register offset and byte masks */ #define _BIT_SHIFT(IRQn) ( ((((uint32_t)(int32_t)(IRQn)) ) & 0x03UL) * 8UL) #define _SHP_IDX(IRQn) ( (((((uint32_t)(int32_t)(IRQn)) & 0x0FUL)-8UL) >> 2UL) ) #define _IP_IDX(IRQn) ( (((uint32_t)(int32_t)(IRQn)) >> 2UL) ) /** \brief Enable External Interrupt The function enables a device-specific interrupt in the NVIC interrupt controller. \param [in] IRQn External interrupt number. Value cannot be negative. */ __STATIC_INLINE void NVIC_EnableIRQ(IRQn_Type IRQn) { NVIC->ISER[0] = (uint32_t)(1UL << (((uint32_t)(int32_t)IRQn) & 0x1FUL)); } /** \brief Disable External Interrupt The function disables a device-specific interrupt in the NVIC interrupt controller. \param [in] IRQn External interrupt number. Value cannot be negative. */ __STATIC_INLINE void NVIC_DisableIRQ(IRQn_Type IRQn) { NVIC->ICER[0] = (uint32_t)(1UL << (((uint32_t)(int32_t)IRQn) & 0x1FUL)); } /** \brief Get Pending Interrupt The function reads the pending register in the NVIC and returns the pending bit for the specified interrupt. \param [in] IRQn Interrupt number. \return 0 Interrupt status is not pending. \return 1 Interrupt status is pending. */ __STATIC_INLINE uint32_t NVIC_GetPendingIRQ(IRQn_Type IRQn) { return((uint32_t)(((NVIC->ISPR[0] & (1UL << (((uint32_t)(int32_t)IRQn) & 0x1FUL))) != 0UL) ? 1UL : 0UL)); } /** \brief Set Pending Interrupt The function sets the pending bit of an external interrupt. \param [in] IRQn Interrupt number. Value cannot be negative. */ __STATIC_INLINE void NVIC_SetPendingIRQ(IRQn_Type IRQn) { NVIC->ISPR[0] = (uint32_t)(1UL << (((uint32_t)(int32_t)IRQn) & 0x1FUL)); } /** \brief Clear Pending Interrupt The function clears the pending bit of an external interrupt. \param [in] IRQn External interrupt number. Value cannot be negative. */ __STATIC_INLINE void NVIC_ClearPendingIRQ(IRQn_Type IRQn) { NVIC->ICPR[0] = (uint32_t)(1UL << (((uint32_t)(int32_t)IRQn) & 0x1FUL)); } /** \brief Set Interrupt Priority The function sets the priority of an interrupt. \note The priority cannot be set for every core interrupt. \param [in] IRQn Interrupt number. \param [in] priority Priority to set. */ __STATIC_INLINE void NVIC_SetPriority(IRQn_Type IRQn, uint32_t priority) { if((int32_t)(IRQn) < 0) { SCB->SHP[_SHP_IDX(IRQn)] = ((uint32_t)(SCB->SHP[_SHP_IDX(IRQn)] & ~(0xFFUL << _BIT_SHIFT(IRQn))) | (((priority << (8 - __NVIC_PRIO_BITS)) & (uint32_t)0xFFUL) << _BIT_SHIFT(IRQn))); } else { NVIC->IP[_IP_IDX(IRQn)] = ((uint32_t)(NVIC->IP[_IP_IDX(IRQn)] & ~(0xFFUL << _BIT_SHIFT(IRQn))) | (((priority << (8 - __NVIC_PRIO_BITS)) & (uint32_t)0xFFUL) << _BIT_SHIFT(IRQn))); } } /** \brief Get Interrupt Priority The function reads the priority of an interrupt. The interrupt number can be positive to specify an external (device specific) interrupt, or negative to specify an internal (core) interrupt. \param [in] IRQn Interrupt number. \return Interrupt Priority. Value is aligned automatically to the implemented priority bits of the microcontroller. */ __STATIC_INLINE uint32_t NVIC_GetPriority(IRQn_Type IRQn) { if((int32_t)(IRQn) < 0) { return((uint32_t)(((SCB->SHP[_SHP_IDX(IRQn)] >> _BIT_SHIFT(IRQn) ) & (uint32_t)0xFFUL) >> (8 - __NVIC_PRIO_BITS))); } else { return((uint32_t)(((NVIC->IP[ _IP_IDX(IRQn)] >> _BIT_SHIFT(IRQn) ) & (uint32_t)0xFFUL) >> (8 - __NVIC_PRIO_BITS))); } } /** \brief System Reset The function initiates a system reset request to reset the MCU. */ __STATIC_INLINE void NVIC_SystemReset(void) { __DSB(); /* Ensure all outstanding memory accesses included buffered write are completed before reset */ SCB->AIRCR = ((0x5FAUL << SCB_AIRCR_VECTKEY_Pos) | SCB_AIRCR_SYSRESETREQ_Msk); __DSB(); /* Ensure completion of memory access */ while(1) { __NOP(); } /* wait until reset */ } /*@} end of CMSIS_Core_NVICFunctions */ /* ################################## SysTick function ############################################ */ /** \ingroup CMSIS_Core_FunctionInterface \defgroup CMSIS_Core_SysTickFunctions SysTick Functions \brief Functions that configure the System. @{ */ #if (__Vendor_SysTickConfig == 0) /** \brief System Tick Configuration The function initializes the System Timer and its interrupt, and starts the System Tick Timer. Counter is in free running mode to generate periodic interrupts. \param [in] ticks Number of ticks between two interrupts. \return 0 Function succeeded. \return 1 Function failed. \note When the variable __Vendor_SysTickConfig is set to 1, then the function SysTick_Config is not included. In this case, the file device.h must contain a vendor-specific implementation of this function. */ __STATIC_INLINE uint32_t SysTick_Config(uint32_t ticks) { if ((ticks - 1UL) > SysTick_LOAD_RELOAD_Msk) { return (1UL); } /* Reload value impossible */ SysTick->LOAD = (uint32_t)(ticks - 1UL); /* set reload register */ NVIC_SetPriority (SysTick_IRQn, (1UL << __NVIC_PRIO_BITS) - 1UL); /* set Priority for Systick Interrupt */ SysTick->VAL = 0UL; /* Load the SysTick Counter Value */ SysTick->CTRL = SysTick_CTRL_CLKSOURCE_Msk | SysTick_CTRL_TICKINT_Msk | SysTick_CTRL_ENABLE_Msk; /* Enable SysTick IRQ and SysTick Timer */ return (0UL); /* Function successful */ } #endif /*@} end of CMSIS_Core_SysTickFunctions */ #ifdef __cplusplus } #endif #endif /* __CORE_CM0_H_DEPENDANT */ #endif /* __CMSIS_GENERIC */ ================================================ FILE: Zelig/mbed/TARGET_NUCLEO_F091RC/core_cm0plus.h ================================================ /**************************************************************************//** * @file core_cm0plus.h * @brief CMSIS Cortex-M0+ Core Peripheral Access Layer Header File * @version V4.10 * @date 18. March 2015 * * @note * ******************************************************************************/ /* Copyright (c) 2009 - 2015 ARM LIMITED All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: - Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. - Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. - Neither the name of ARM 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 COPYRIGHT HOLDERS AND 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. ---------------------------------------------------------------------------*/ #if defined ( __ICCARM__ ) #pragma system_include /* treat file as system include file for MISRA check */ #endif #ifndef __CORE_CM0PLUS_H_GENERIC #define __CORE_CM0PLUS_H_GENERIC #ifdef __cplusplus extern "C" { #endif /** \page CMSIS_MISRA_Exceptions MISRA-C:2004 Compliance Exceptions CMSIS violates the following MISRA-C:2004 rules: \li Required Rule 8.5, object/function definition in header file.
Function definitions in header files are used to allow 'inlining'. \li Required Rule 18.4, declaration of union type or object of union type: '{...}'.
Unions are used for effective representation of core registers. \li Advisory Rule 19.7, Function-like macro defined.
Function-like macros are used to allow more efficient code. */ /******************************************************************************* * CMSIS definitions ******************************************************************************/ /** \ingroup Cortex-M0+ @{ */ /* CMSIS CM0P definitions */ #define __CM0PLUS_CMSIS_VERSION_MAIN (0x04) /*!< [31:16] CMSIS HAL main version */ #define __CM0PLUS_CMSIS_VERSION_SUB (0x00) /*!< [15:0] CMSIS HAL sub version */ #define __CM0PLUS_CMSIS_VERSION ((__CM0PLUS_CMSIS_VERSION_MAIN << 16) | \ __CM0PLUS_CMSIS_VERSION_SUB) /*!< CMSIS HAL version number */ #define __CORTEX_M (0x00) /*!< Cortex-M Core */ #if defined ( __CC_ARM ) #define __ASM __asm /*!< asm keyword for ARM Compiler */ #define __INLINE __inline /*!< inline keyword for ARM Compiler */ #define __STATIC_INLINE static __inline #elif defined ( __GNUC__ ) #define __ASM __asm /*!< asm keyword for GNU Compiler */ #define __INLINE inline /*!< inline keyword for GNU Compiler */ #define __STATIC_INLINE static inline #elif defined ( __ICCARM__ ) #define __ASM __asm /*!< asm keyword for IAR Compiler */ #define __INLINE inline /*!< inline keyword for IAR Compiler. Only available in High optimization mode! */ #define __STATIC_INLINE static inline #elif defined ( __TMS470__ ) #define __ASM __asm /*!< asm keyword for TI CCS Compiler */ #define __STATIC_INLINE static inline #elif defined ( __TASKING__ ) #define __ASM __asm /*!< asm keyword for TASKING Compiler */ #define __INLINE inline /*!< inline keyword for TASKING Compiler */ #define __STATIC_INLINE static inline #elif defined ( __CSMC__ ) #define __packed #define __ASM _asm /*!< asm keyword for COSMIC Compiler */ #define __INLINE inline /*use -pc99 on compile line !< inline keyword for COSMIC Compiler */ #define __STATIC_INLINE static inline #endif /** __FPU_USED indicates whether an FPU is used or not. This core does not support an FPU at all */ #define __FPU_USED 0 #if defined ( __CC_ARM ) #if defined __TARGET_FPU_VFP #warning "Compiler generates FPU instructions for a device without an FPU (check __FPU_PRESENT)" #endif #elif defined ( __GNUC__ ) #if defined (__VFP_FP__) && !defined(__SOFTFP__) #warning "Compiler generates FPU instructions for a device without an FPU (check __FPU_PRESENT)" #endif #elif defined ( __ICCARM__ ) #if defined __ARMVFP__ #warning "Compiler generates FPU instructions for a device without an FPU (check __FPU_PRESENT)" #endif #elif defined ( __TMS470__ ) #if defined __TI__VFP_SUPPORT____ #warning "Compiler generates FPU instructions for a device without an FPU (check __FPU_PRESENT)" #endif #elif defined ( __TASKING__ ) #if defined __FPU_VFP__ #error "Compiler generates FPU instructions for a device without an FPU (check __FPU_PRESENT)" #endif #elif defined ( __CSMC__ ) /* Cosmic */ #if ( __CSMC__ & 0x400) // FPU present for parser #error "Compiler generates FPU instructions for a device without an FPU (check __FPU_PRESENT)" #endif #endif #include /* standard types definitions */ #include /* Core Instruction Access */ #include /* Core Function Access */ #ifdef __cplusplus } #endif #endif /* __CORE_CM0PLUS_H_GENERIC */ #ifndef __CMSIS_GENERIC #ifndef __CORE_CM0PLUS_H_DEPENDANT #define __CORE_CM0PLUS_H_DEPENDANT #ifdef __cplusplus extern "C" { #endif /* check device defines and use defaults */ #if defined __CHECK_DEVICE_DEFINES #ifndef __CM0PLUS_REV #define __CM0PLUS_REV 0x0000 #warning "__CM0PLUS_REV not defined in device header file; using default!" #endif #ifndef __MPU_PRESENT #define __MPU_PRESENT 0 #warning "__MPU_PRESENT not defined in device header file; using default!" #endif #ifndef __VTOR_PRESENT #define __VTOR_PRESENT 0 #warning "__VTOR_PRESENT not defined in device header file; using default!" #endif #ifndef __NVIC_PRIO_BITS #define __NVIC_PRIO_BITS 2 #warning "__NVIC_PRIO_BITS not defined in device header file; using default!" #endif #ifndef __Vendor_SysTickConfig #define __Vendor_SysTickConfig 0 #warning "__Vendor_SysTickConfig not defined in device header file; using default!" #endif #endif /* IO definitions (access restrictions to peripheral registers) */ /** \defgroup CMSIS_glob_defs CMSIS Global Defines IO Type Qualifiers are used \li to specify the access to peripheral variables. \li for automatic generation of peripheral register debug information. */ #ifdef __cplusplus #define __I volatile /*!< Defines 'read only' permissions */ #else #define __I volatile const /*!< Defines 'read only' permissions */ #endif #define __O volatile /*!< Defines 'write only' permissions */ #define __IO volatile /*!< Defines 'read / write' permissions */ /*@} end of group Cortex-M0+ */ /******************************************************************************* * Register Abstraction Core Register contain: - Core Register - Core NVIC Register - Core SCB Register - Core SysTick Register - Core MPU Register ******************************************************************************/ /** \defgroup CMSIS_core_register Defines and Type Definitions \brief Type definitions and defines for Cortex-M processor based devices. */ /** \ingroup CMSIS_core_register \defgroup CMSIS_CORE Status and Control Registers \brief Core Register type definitions. @{ */ /** \brief Union type to access the Application Program Status Register (APSR). */ typedef union { struct { uint32_t _reserved0:28; /*!< bit: 0..27 Reserved */ uint32_t V:1; /*!< bit: 28 Overflow condition code flag */ uint32_t C:1; /*!< bit: 29 Carry condition code flag */ uint32_t Z:1; /*!< bit: 30 Zero condition code flag */ uint32_t N:1; /*!< bit: 31 Negative condition code flag */ } b; /*!< Structure used for bit access */ uint32_t w; /*!< Type used for word access */ } APSR_Type; /* APSR Register Definitions */ #define APSR_N_Pos 31 /*!< APSR: N Position */ #define APSR_N_Msk (1UL << APSR_N_Pos) /*!< APSR: N Mask */ #define APSR_Z_Pos 30 /*!< APSR: Z Position */ #define APSR_Z_Msk (1UL << APSR_Z_Pos) /*!< APSR: Z Mask */ #define APSR_C_Pos 29 /*!< APSR: C Position */ #define APSR_C_Msk (1UL << APSR_C_Pos) /*!< APSR: C Mask */ #define APSR_V_Pos 28 /*!< APSR: V Position */ #define APSR_V_Msk (1UL << APSR_V_Pos) /*!< APSR: V Mask */ /** \brief Union type to access the Interrupt Program Status Register (IPSR). */ typedef union { struct { uint32_t ISR:9; /*!< bit: 0.. 8 Exception number */ uint32_t _reserved0:23; /*!< bit: 9..31 Reserved */ } b; /*!< Structure used for bit access */ uint32_t w; /*!< Type used for word access */ } IPSR_Type; /* IPSR Register Definitions */ #define IPSR_ISR_Pos 0 /*!< IPSR: ISR Position */ #define IPSR_ISR_Msk (0x1FFUL /*<< IPSR_ISR_Pos*/) /*!< IPSR: ISR Mask */ /** \brief Union type to access the Special-Purpose Program Status Registers (xPSR). */ typedef union { struct { uint32_t ISR:9; /*!< bit: 0.. 8 Exception number */ uint32_t _reserved0:15; /*!< bit: 9..23 Reserved */ uint32_t T:1; /*!< bit: 24 Thumb bit (read 0) */ uint32_t _reserved1:3; /*!< bit: 25..27 Reserved */ uint32_t V:1; /*!< bit: 28 Overflow condition code flag */ uint32_t C:1; /*!< bit: 29 Carry condition code flag */ uint32_t Z:1; /*!< bit: 30 Zero condition code flag */ uint32_t N:1; /*!< bit: 31 Negative condition code flag */ } b; /*!< Structure used for bit access */ uint32_t w; /*!< Type used for word access */ } xPSR_Type; /* xPSR Register Definitions */ #define xPSR_N_Pos 31 /*!< xPSR: N Position */ #define xPSR_N_Msk (1UL << xPSR_N_Pos) /*!< xPSR: N Mask */ #define xPSR_Z_Pos 30 /*!< xPSR: Z Position */ #define xPSR_Z_Msk (1UL << xPSR_Z_Pos) /*!< xPSR: Z Mask */ #define xPSR_C_Pos 29 /*!< xPSR: C Position */ #define xPSR_C_Msk (1UL << xPSR_C_Pos) /*!< xPSR: C Mask */ #define xPSR_V_Pos 28 /*!< xPSR: V Position */ #define xPSR_V_Msk (1UL << xPSR_V_Pos) /*!< xPSR: V Mask */ #define xPSR_T_Pos 24 /*!< xPSR: T Position */ #define xPSR_T_Msk (1UL << xPSR_T_Pos) /*!< xPSR: T Mask */ #define xPSR_ISR_Pos 0 /*!< xPSR: ISR Position */ #define xPSR_ISR_Msk (0x1FFUL /*<< xPSR_ISR_Pos*/) /*!< xPSR: ISR Mask */ /** \brief Union type to access the Control Registers (CONTROL). */ typedef union { struct { uint32_t nPRIV:1; /*!< bit: 0 Execution privilege in Thread mode */ uint32_t SPSEL:1; /*!< bit: 1 Stack to be used */ uint32_t _reserved1:30; /*!< bit: 2..31 Reserved */ } b; /*!< Structure used for bit access */ uint32_t w; /*!< Type used for word access */ } CONTROL_Type; /* CONTROL Register Definitions */ #define CONTROL_SPSEL_Pos 1 /*!< CONTROL: SPSEL Position */ #define CONTROL_SPSEL_Msk (1UL << CONTROL_SPSEL_Pos) /*!< CONTROL: SPSEL Mask */ #define CONTROL_nPRIV_Pos 0 /*!< CONTROL: nPRIV Position */ #define CONTROL_nPRIV_Msk (1UL /*<< CONTROL_nPRIV_Pos*/) /*!< CONTROL: nPRIV Mask */ /*@} end of group CMSIS_CORE */ /** \ingroup CMSIS_core_register \defgroup CMSIS_NVIC Nested Vectored Interrupt Controller (NVIC) \brief Type definitions for the NVIC Registers @{ */ /** \brief Structure type to access the Nested Vectored Interrupt Controller (NVIC). */ typedef struct { __IO uint32_t ISER[1]; /*!< Offset: 0x000 (R/W) Interrupt Set Enable Register */ uint32_t RESERVED0[31]; __IO uint32_t ICER[1]; /*!< Offset: 0x080 (R/W) Interrupt Clear Enable Register */ uint32_t RSERVED1[31]; __IO uint32_t ISPR[1]; /*!< Offset: 0x100 (R/W) Interrupt Set Pending Register */ uint32_t RESERVED2[31]; __IO uint32_t ICPR[1]; /*!< Offset: 0x180 (R/W) Interrupt Clear Pending Register */ uint32_t RESERVED3[31]; uint32_t RESERVED4[64]; __IO uint32_t IP[8]; /*!< Offset: 0x300 (R/W) Interrupt Priority Register */ } NVIC_Type; /*@} end of group CMSIS_NVIC */ /** \ingroup CMSIS_core_register \defgroup CMSIS_SCB System Control Block (SCB) \brief Type definitions for the System Control Block Registers @{ */ /** \brief Structure type to access the System Control Block (SCB). */ typedef struct { __I uint32_t CPUID; /*!< Offset: 0x000 (R/ ) CPUID Base Register */ __IO uint32_t ICSR; /*!< Offset: 0x004 (R/W) Interrupt Control and State Register */ #if (__VTOR_PRESENT == 1) __IO uint32_t VTOR; /*!< Offset: 0x008 (R/W) Vector Table Offset Register */ #else uint32_t RESERVED0; #endif __IO uint32_t AIRCR; /*!< Offset: 0x00C (R/W) Application Interrupt and Reset Control Register */ __IO uint32_t SCR; /*!< Offset: 0x010 (R/W) System Control Register */ __IO uint32_t CCR; /*!< Offset: 0x014 (R/W) Configuration Control Register */ uint32_t RESERVED1; __IO uint32_t SHP[2]; /*!< Offset: 0x01C (R/W) System Handlers Priority Registers. [0] is RESERVED */ __IO uint32_t SHCSR; /*!< Offset: 0x024 (R/W) System Handler Control and State Register */ } SCB_Type; /* SCB CPUID Register Definitions */ #define SCB_CPUID_IMPLEMENTER_Pos 24 /*!< SCB CPUID: IMPLEMENTER Position */ #define SCB_CPUID_IMPLEMENTER_Msk (0xFFUL << SCB_CPUID_IMPLEMENTER_Pos) /*!< SCB CPUID: IMPLEMENTER Mask */ #define SCB_CPUID_VARIANT_Pos 20 /*!< SCB CPUID: VARIANT Position */ #define SCB_CPUID_VARIANT_Msk (0xFUL << SCB_CPUID_VARIANT_Pos) /*!< SCB CPUID: VARIANT Mask */ #define SCB_CPUID_ARCHITECTURE_Pos 16 /*!< SCB CPUID: ARCHITECTURE Position */ #define SCB_CPUID_ARCHITECTURE_Msk (0xFUL << SCB_CPUID_ARCHITECTURE_Pos) /*!< SCB CPUID: ARCHITECTURE Mask */ #define SCB_CPUID_PARTNO_Pos 4 /*!< SCB CPUID: PARTNO Position */ #define SCB_CPUID_PARTNO_Msk (0xFFFUL << SCB_CPUID_PARTNO_Pos) /*!< SCB CPUID: PARTNO Mask */ #define SCB_CPUID_REVISION_Pos 0 /*!< SCB CPUID: REVISION Position */ #define SCB_CPUID_REVISION_Msk (0xFUL /*<< SCB_CPUID_REVISION_Pos*/) /*!< SCB CPUID: REVISION Mask */ /* SCB Interrupt Control State Register Definitions */ #define SCB_ICSR_NMIPENDSET_Pos 31 /*!< SCB ICSR: NMIPENDSET Position */ #define SCB_ICSR_NMIPENDSET_Msk (1UL << SCB_ICSR_NMIPENDSET_Pos) /*!< SCB ICSR: NMIPENDSET Mask */ #define SCB_ICSR_PENDSVSET_Pos 28 /*!< SCB ICSR: PENDSVSET Position */ #define SCB_ICSR_PENDSVSET_Msk (1UL << SCB_ICSR_PENDSVSET_Pos) /*!< SCB ICSR: PENDSVSET Mask */ #define SCB_ICSR_PENDSVCLR_Pos 27 /*!< SCB ICSR: PENDSVCLR Position */ #define SCB_ICSR_PENDSVCLR_Msk (1UL << SCB_ICSR_PENDSVCLR_Pos) /*!< SCB ICSR: PENDSVCLR Mask */ #define SCB_ICSR_PENDSTSET_Pos 26 /*!< SCB ICSR: PENDSTSET Position */ #define SCB_ICSR_PENDSTSET_Msk (1UL << SCB_ICSR_PENDSTSET_Pos) /*!< SCB ICSR: PENDSTSET Mask */ #define SCB_ICSR_PENDSTCLR_Pos 25 /*!< SCB ICSR: PENDSTCLR Position */ #define SCB_ICSR_PENDSTCLR_Msk (1UL << SCB_ICSR_PENDSTCLR_Pos) /*!< SCB ICSR: PENDSTCLR Mask */ #define SCB_ICSR_ISRPREEMPT_Pos 23 /*!< SCB ICSR: ISRPREEMPT Position */ #define SCB_ICSR_ISRPREEMPT_Msk (1UL << SCB_ICSR_ISRPREEMPT_Pos) /*!< SCB ICSR: ISRPREEMPT Mask */ #define SCB_ICSR_ISRPENDING_Pos 22 /*!< SCB ICSR: ISRPENDING Position */ #define SCB_ICSR_ISRPENDING_Msk (1UL << SCB_ICSR_ISRPENDING_Pos) /*!< SCB ICSR: ISRPENDING Mask */ #define SCB_ICSR_VECTPENDING_Pos 12 /*!< SCB ICSR: VECTPENDING Position */ #define SCB_ICSR_VECTPENDING_Msk (0x1FFUL << SCB_ICSR_VECTPENDING_Pos) /*!< SCB ICSR: VECTPENDING Mask */ #define SCB_ICSR_VECTACTIVE_Pos 0 /*!< SCB ICSR: VECTACTIVE Position */ #define SCB_ICSR_VECTACTIVE_Msk (0x1FFUL /*<< SCB_ICSR_VECTACTIVE_Pos*/) /*!< SCB ICSR: VECTACTIVE Mask */ #if (__VTOR_PRESENT == 1) /* SCB Interrupt Control State Register Definitions */ #define SCB_VTOR_TBLOFF_Pos 8 /*!< SCB VTOR: TBLOFF Position */ #define SCB_VTOR_TBLOFF_Msk (0xFFFFFFUL << SCB_VTOR_TBLOFF_Pos) /*!< SCB VTOR: TBLOFF Mask */ #endif /* SCB Application Interrupt and Reset Control Register Definitions */ #define SCB_AIRCR_VECTKEY_Pos 16 /*!< SCB AIRCR: VECTKEY Position */ #define SCB_AIRCR_VECTKEY_Msk (0xFFFFUL << SCB_AIRCR_VECTKEY_Pos) /*!< SCB AIRCR: VECTKEY Mask */ #define SCB_AIRCR_VECTKEYSTAT_Pos 16 /*!< SCB AIRCR: VECTKEYSTAT Position */ #define SCB_AIRCR_VECTKEYSTAT_Msk (0xFFFFUL << SCB_AIRCR_VECTKEYSTAT_Pos) /*!< SCB AIRCR: VECTKEYSTAT Mask */ #define SCB_AIRCR_ENDIANESS_Pos 15 /*!< SCB AIRCR: ENDIANESS Position */ #define SCB_AIRCR_ENDIANESS_Msk (1UL << SCB_AIRCR_ENDIANESS_Pos) /*!< SCB AIRCR: ENDIANESS Mask */ #define SCB_AIRCR_SYSRESETREQ_Pos 2 /*!< SCB AIRCR: SYSRESETREQ Position */ #define SCB_AIRCR_SYSRESETREQ_Msk (1UL << SCB_AIRCR_SYSRESETREQ_Pos) /*!< SCB AIRCR: SYSRESETREQ Mask */ #define SCB_AIRCR_VECTCLRACTIVE_Pos 1 /*!< SCB AIRCR: VECTCLRACTIVE Position */ #define SCB_AIRCR_VECTCLRACTIVE_Msk (1UL << SCB_AIRCR_VECTCLRACTIVE_Pos) /*!< SCB AIRCR: VECTCLRACTIVE Mask */ /* SCB System Control Register Definitions */ #define SCB_SCR_SEVONPEND_Pos 4 /*!< SCB SCR: SEVONPEND Position */ #define SCB_SCR_SEVONPEND_Msk (1UL << SCB_SCR_SEVONPEND_Pos) /*!< SCB SCR: SEVONPEND Mask */ #define SCB_SCR_SLEEPDEEP_Pos 2 /*!< SCB SCR: SLEEPDEEP Position */ #define SCB_SCR_SLEEPDEEP_Msk (1UL << SCB_SCR_SLEEPDEEP_Pos) /*!< SCB SCR: SLEEPDEEP Mask */ #define SCB_SCR_SLEEPONEXIT_Pos 1 /*!< SCB SCR: SLEEPONEXIT Position */ #define SCB_SCR_SLEEPONEXIT_Msk (1UL << SCB_SCR_SLEEPONEXIT_Pos) /*!< SCB SCR: SLEEPONEXIT Mask */ /* SCB Configuration Control Register Definitions */ #define SCB_CCR_STKALIGN_Pos 9 /*!< SCB CCR: STKALIGN Position */ #define SCB_CCR_STKALIGN_Msk (1UL << SCB_CCR_STKALIGN_Pos) /*!< SCB CCR: STKALIGN Mask */ #define SCB_CCR_UNALIGN_TRP_Pos 3 /*!< SCB CCR: UNALIGN_TRP Position */ #define SCB_CCR_UNALIGN_TRP_Msk (1UL << SCB_CCR_UNALIGN_TRP_Pos) /*!< SCB CCR: UNALIGN_TRP Mask */ /* SCB System Handler Control and State Register Definitions */ #define SCB_SHCSR_SVCALLPENDED_Pos 15 /*!< SCB SHCSR: SVCALLPENDED Position */ #define SCB_SHCSR_SVCALLPENDED_Msk (1UL << SCB_SHCSR_SVCALLPENDED_Pos) /*!< SCB SHCSR: SVCALLPENDED Mask */ /*@} end of group CMSIS_SCB */ /** \ingroup CMSIS_core_register \defgroup CMSIS_SysTick System Tick Timer (SysTick) \brief Type definitions for the System Timer Registers. @{ */ /** \brief Structure type to access the System Timer (SysTick). */ typedef struct { __IO uint32_t CTRL; /*!< Offset: 0x000 (R/W) SysTick Control and Status Register */ __IO uint32_t LOAD; /*!< Offset: 0x004 (R/W) SysTick Reload Value Register */ __IO uint32_t VAL; /*!< Offset: 0x008 (R/W) SysTick Current Value Register */ __I uint32_t CALIB; /*!< Offset: 0x00C (R/ ) SysTick Calibration Register */ } SysTick_Type; /* SysTick Control / Status Register Definitions */ #define SysTick_CTRL_COUNTFLAG_Pos 16 /*!< SysTick CTRL: COUNTFLAG Position */ #define SysTick_CTRL_COUNTFLAG_Msk (1UL << SysTick_CTRL_COUNTFLAG_Pos) /*!< SysTick CTRL: COUNTFLAG Mask */ #define SysTick_CTRL_CLKSOURCE_Pos 2 /*!< SysTick CTRL: CLKSOURCE Position */ #define SysTick_CTRL_CLKSOURCE_Msk (1UL << SysTick_CTRL_CLKSOURCE_Pos) /*!< SysTick CTRL: CLKSOURCE Mask */ #define SysTick_CTRL_TICKINT_Pos 1 /*!< SysTick CTRL: TICKINT Position */ #define SysTick_CTRL_TICKINT_Msk (1UL << SysTick_CTRL_TICKINT_Pos) /*!< SysTick CTRL: TICKINT Mask */ #define SysTick_CTRL_ENABLE_Pos 0 /*!< SysTick CTRL: ENABLE Position */ #define SysTick_CTRL_ENABLE_Msk (1UL /*<< SysTick_CTRL_ENABLE_Pos*/) /*!< SysTick CTRL: ENABLE Mask */ /* SysTick Reload Register Definitions */ #define SysTick_LOAD_RELOAD_Pos 0 /*!< SysTick LOAD: RELOAD Position */ #define SysTick_LOAD_RELOAD_Msk (0xFFFFFFUL /*<< SysTick_LOAD_RELOAD_Pos*/) /*!< SysTick LOAD: RELOAD Mask */ /* SysTick Current Register Definitions */ #define SysTick_VAL_CURRENT_Pos 0 /*!< SysTick VAL: CURRENT Position */ #define SysTick_VAL_CURRENT_Msk (0xFFFFFFUL /*<< SysTick_VAL_CURRENT_Pos*/) /*!< SysTick VAL: CURRENT Mask */ /* SysTick Calibration Register Definitions */ #define SysTick_CALIB_NOREF_Pos 31 /*!< SysTick CALIB: NOREF Position */ #define SysTick_CALIB_NOREF_Msk (1UL << SysTick_CALIB_NOREF_Pos) /*!< SysTick CALIB: NOREF Mask */ #define SysTick_CALIB_SKEW_Pos 30 /*!< SysTick CALIB: SKEW Position */ #define SysTick_CALIB_SKEW_Msk (1UL << SysTick_CALIB_SKEW_Pos) /*!< SysTick CALIB: SKEW Mask */ #define SysTick_CALIB_TENMS_Pos 0 /*!< SysTick CALIB: TENMS Position */ #define SysTick_CALIB_TENMS_Msk (0xFFFFFFUL /*<< SysTick_CALIB_TENMS_Pos*/) /*!< SysTick CALIB: TENMS Mask */ /*@} end of group CMSIS_SysTick */ #if (__MPU_PRESENT == 1) /** \ingroup CMSIS_core_register \defgroup CMSIS_MPU Memory Protection Unit (MPU) \brief Type definitions for the Memory Protection Unit (MPU) @{ */ /** \brief Structure type to access the Memory Protection Unit (MPU). */ typedef struct { __I uint32_t TYPE; /*!< Offset: 0x000 (R/ ) MPU Type Register */ __IO uint32_t CTRL; /*!< Offset: 0x004 (R/W) MPU Control Register */ __IO uint32_t RNR; /*!< Offset: 0x008 (R/W) MPU Region RNRber Register */ __IO uint32_t RBAR; /*!< Offset: 0x00C (R/W) MPU Region Base Address Register */ __IO uint32_t RASR; /*!< Offset: 0x010 (R/W) MPU Region Attribute and Size Register */ } MPU_Type; /* MPU Type Register */ #define MPU_TYPE_IREGION_Pos 16 /*!< MPU TYPE: IREGION Position */ #define MPU_TYPE_IREGION_Msk (0xFFUL << MPU_TYPE_IREGION_Pos) /*!< MPU TYPE: IREGION Mask */ #define MPU_TYPE_DREGION_Pos 8 /*!< MPU TYPE: DREGION Position */ #define MPU_TYPE_DREGION_Msk (0xFFUL << MPU_TYPE_DREGION_Pos) /*!< MPU TYPE: DREGION Mask */ #define MPU_TYPE_SEPARATE_Pos 0 /*!< MPU TYPE: SEPARATE Position */ #define MPU_TYPE_SEPARATE_Msk (1UL /*<< MPU_TYPE_SEPARATE_Pos*/) /*!< MPU TYPE: SEPARATE Mask */ /* MPU Control Register */ #define MPU_CTRL_PRIVDEFENA_Pos 2 /*!< MPU CTRL: PRIVDEFENA Position */ #define MPU_CTRL_PRIVDEFENA_Msk (1UL << MPU_CTRL_PRIVDEFENA_Pos) /*!< MPU CTRL: PRIVDEFENA Mask */ #define MPU_CTRL_HFNMIENA_Pos 1 /*!< MPU CTRL: HFNMIENA Position */ #define MPU_CTRL_HFNMIENA_Msk (1UL << MPU_CTRL_HFNMIENA_Pos) /*!< MPU CTRL: HFNMIENA Mask */ #define MPU_CTRL_ENABLE_Pos 0 /*!< MPU CTRL: ENABLE Position */ #define MPU_CTRL_ENABLE_Msk (1UL /*<< MPU_CTRL_ENABLE_Pos*/) /*!< MPU CTRL: ENABLE Mask */ /* MPU Region Number Register */ #define MPU_RNR_REGION_Pos 0 /*!< MPU RNR: REGION Position */ #define MPU_RNR_REGION_Msk (0xFFUL /*<< MPU_RNR_REGION_Pos*/) /*!< MPU RNR: REGION Mask */ /* MPU Region Base Address Register */ #define MPU_RBAR_ADDR_Pos 8 /*!< MPU RBAR: ADDR Position */ #define MPU_RBAR_ADDR_Msk (0xFFFFFFUL << MPU_RBAR_ADDR_Pos) /*!< MPU RBAR: ADDR Mask */ #define MPU_RBAR_VALID_Pos 4 /*!< MPU RBAR: VALID Position */ #define MPU_RBAR_VALID_Msk (1UL << MPU_RBAR_VALID_Pos) /*!< MPU RBAR: VALID Mask */ #define MPU_RBAR_REGION_Pos 0 /*!< MPU RBAR: REGION Position */ #define MPU_RBAR_REGION_Msk (0xFUL /*<< MPU_RBAR_REGION_Pos*/) /*!< MPU RBAR: REGION Mask */ /* MPU Region Attribute and Size Register */ #define MPU_RASR_ATTRS_Pos 16 /*!< MPU RASR: MPU Region Attribute field Position */ #define MPU_RASR_ATTRS_Msk (0xFFFFUL << MPU_RASR_ATTRS_Pos) /*!< MPU RASR: MPU Region Attribute field Mask */ #define MPU_RASR_XN_Pos 28 /*!< MPU RASR: ATTRS.XN Position */ #define MPU_RASR_XN_Msk (1UL << MPU_RASR_XN_Pos) /*!< MPU RASR: ATTRS.XN Mask */ #define MPU_RASR_AP_Pos 24 /*!< MPU RASR: ATTRS.AP Position */ #define MPU_RASR_AP_Msk (0x7UL << MPU_RASR_AP_Pos) /*!< MPU RASR: ATTRS.AP Mask */ #define MPU_RASR_TEX_Pos 19 /*!< MPU RASR: ATTRS.TEX Position */ #define MPU_RASR_TEX_Msk (0x7UL << MPU_RASR_TEX_Pos) /*!< MPU RASR: ATTRS.TEX Mask */ #define MPU_RASR_S_Pos 18 /*!< MPU RASR: ATTRS.S Position */ #define MPU_RASR_S_Msk (1UL << MPU_RASR_S_Pos) /*!< MPU RASR: ATTRS.S Mask */ #define MPU_RASR_C_Pos 17 /*!< MPU RASR: ATTRS.C Position */ #define MPU_RASR_C_Msk (1UL << MPU_RASR_C_Pos) /*!< MPU RASR: ATTRS.C Mask */ #define MPU_RASR_B_Pos 16 /*!< MPU RASR: ATTRS.B Position */ #define MPU_RASR_B_Msk (1UL << MPU_RASR_B_Pos) /*!< MPU RASR: ATTRS.B Mask */ #define MPU_RASR_SRD_Pos 8 /*!< MPU RASR: Sub-Region Disable Position */ #define MPU_RASR_SRD_Msk (0xFFUL << MPU_RASR_SRD_Pos) /*!< MPU RASR: Sub-Region Disable Mask */ #define MPU_RASR_SIZE_Pos 1 /*!< MPU RASR: Region Size Field Position */ #define MPU_RASR_SIZE_Msk (0x1FUL << MPU_RASR_SIZE_Pos) /*!< MPU RASR: Region Size Field Mask */ #define MPU_RASR_ENABLE_Pos 0 /*!< MPU RASR: Region enable bit Position */ #define MPU_RASR_ENABLE_Msk (1UL /*<< MPU_RASR_ENABLE_Pos*/) /*!< MPU RASR: Region enable bit Disable Mask */ /*@} end of group CMSIS_MPU */ #endif /** \ingroup CMSIS_core_register \defgroup CMSIS_CoreDebug Core Debug Registers (CoreDebug) \brief Cortex-M0+ Core Debug Registers (DCB registers, SHCSR, and DFSR) are only accessible over DAP and not via processor. Therefore they are not covered by the Cortex-M0 header file. @{ */ /*@} end of group CMSIS_CoreDebug */ /** \ingroup CMSIS_core_register \defgroup CMSIS_core_base Core Definitions \brief Definitions for base addresses, unions, and structures. @{ */ /* Memory mapping of Cortex-M0+ Hardware */ #define SCS_BASE (0xE000E000UL) /*!< System Control Space Base Address */ #define SysTick_BASE (SCS_BASE + 0x0010UL) /*!< SysTick Base Address */ #define NVIC_BASE (SCS_BASE + 0x0100UL) /*!< NVIC Base Address */ #define SCB_BASE (SCS_BASE + 0x0D00UL) /*!< System Control Block Base Address */ #define SCB ((SCB_Type *) SCB_BASE ) /*!< SCB configuration struct */ #define SysTick ((SysTick_Type *) SysTick_BASE ) /*!< SysTick configuration struct */ #define NVIC ((NVIC_Type *) NVIC_BASE ) /*!< NVIC configuration struct */ #if (__MPU_PRESENT == 1) #define MPU_BASE (SCS_BASE + 0x0D90UL) /*!< Memory Protection Unit */ #define MPU ((MPU_Type *) MPU_BASE ) /*!< Memory Protection Unit */ #endif /*@} */ /******************************************************************************* * Hardware Abstraction Layer Core Function Interface contains: - Core NVIC Functions - Core SysTick Functions - Core Register Access Functions ******************************************************************************/ /** \defgroup CMSIS_Core_FunctionInterface Functions and Instructions Reference */ /* ########################## NVIC functions #################################### */ /** \ingroup CMSIS_Core_FunctionInterface \defgroup CMSIS_Core_NVICFunctions NVIC Functions \brief Functions that manage interrupts and exceptions via the NVIC. @{ */ /* Interrupt Priorities are WORD accessible only under ARMv6M */ /* The following MACROS handle generation of the register offset and byte masks */ #define _BIT_SHIFT(IRQn) ( ((((uint32_t)(int32_t)(IRQn)) ) & 0x03UL) * 8UL) #define _SHP_IDX(IRQn) ( (((((uint32_t)(int32_t)(IRQn)) & 0x0FUL)-8UL) >> 2UL) ) #define _IP_IDX(IRQn) ( (((uint32_t)(int32_t)(IRQn)) >> 2UL) ) /** \brief Enable External Interrupt The function enables a device-specific interrupt in the NVIC interrupt controller. \param [in] IRQn External interrupt number. Value cannot be negative. */ __STATIC_INLINE void NVIC_EnableIRQ(IRQn_Type IRQn) { NVIC->ISER[0] = (uint32_t)(1UL << (((uint32_t)(int32_t)IRQn) & 0x1FUL)); } /** \brief Disable External Interrupt The function disables a device-specific interrupt in the NVIC interrupt controller. \param [in] IRQn External interrupt number. Value cannot be negative. */ __STATIC_INLINE void NVIC_DisableIRQ(IRQn_Type IRQn) { NVIC->ICER[0] = (uint32_t)(1UL << (((uint32_t)(int32_t)IRQn) & 0x1FUL)); } /** \brief Get Pending Interrupt The function reads the pending register in the NVIC and returns the pending bit for the specified interrupt. \param [in] IRQn Interrupt number. \return 0 Interrupt status is not pending. \return 1 Interrupt status is pending. */ __STATIC_INLINE uint32_t NVIC_GetPendingIRQ(IRQn_Type IRQn) { return((uint32_t)(((NVIC->ISPR[0] & (1UL << (((uint32_t)(int32_t)IRQn) & 0x1FUL))) != 0UL) ? 1UL : 0UL)); } /** \brief Set Pending Interrupt The function sets the pending bit of an external interrupt. \param [in] IRQn Interrupt number. Value cannot be negative. */ __STATIC_INLINE void NVIC_SetPendingIRQ(IRQn_Type IRQn) { NVIC->ISPR[0] = (uint32_t)(1UL << (((uint32_t)(int32_t)IRQn) & 0x1FUL)); } /** \brief Clear Pending Interrupt The function clears the pending bit of an external interrupt. \param [in] IRQn External interrupt number. Value cannot be negative. */ __STATIC_INLINE void NVIC_ClearPendingIRQ(IRQn_Type IRQn) { NVIC->ICPR[0] = (uint32_t)(1UL << (((uint32_t)(int32_t)IRQn) & 0x1FUL)); } /** \brief Set Interrupt Priority The function sets the priority of an interrupt. \note The priority cannot be set for every core interrupt. \param [in] IRQn Interrupt number. \param [in] priority Priority to set. */ __STATIC_INLINE void NVIC_SetPriority(IRQn_Type IRQn, uint32_t priority) { if((int32_t)(IRQn) < 0) { SCB->SHP[_SHP_IDX(IRQn)] = ((uint32_t)(SCB->SHP[_SHP_IDX(IRQn)] & ~(0xFFUL << _BIT_SHIFT(IRQn))) | (((priority << (8 - __NVIC_PRIO_BITS)) & (uint32_t)0xFFUL) << _BIT_SHIFT(IRQn))); } else { NVIC->IP[_IP_IDX(IRQn)] = ((uint32_t)(NVIC->IP[_IP_IDX(IRQn)] & ~(0xFFUL << _BIT_SHIFT(IRQn))) | (((priority << (8 - __NVIC_PRIO_BITS)) & (uint32_t)0xFFUL) << _BIT_SHIFT(IRQn))); } } /** \brief Get Interrupt Priority The function reads the priority of an interrupt. The interrupt number can be positive to specify an external (device specific) interrupt, or negative to specify an internal (core) interrupt. \param [in] IRQn Interrupt number. \return Interrupt Priority. Value is aligned automatically to the implemented priority bits of the microcontroller. */ __STATIC_INLINE uint32_t NVIC_GetPriority(IRQn_Type IRQn) { if((int32_t)(IRQn) < 0) { return((uint32_t)(((SCB->SHP[_SHP_IDX(IRQn)] >> _BIT_SHIFT(IRQn) ) & (uint32_t)0xFFUL) >> (8 - __NVIC_PRIO_BITS))); } else { return((uint32_t)(((NVIC->IP[ _IP_IDX(IRQn)] >> _BIT_SHIFT(IRQn) ) & (uint32_t)0xFFUL) >> (8 - __NVIC_PRIO_BITS))); } } /** \brief System Reset The function initiates a system reset request to reset the MCU. */ __STATIC_INLINE void NVIC_SystemReset(void) { __DSB(); /* Ensure all outstanding memory accesses included buffered write are completed before reset */ SCB->AIRCR = ((0x5FAUL << SCB_AIRCR_VECTKEY_Pos) | SCB_AIRCR_SYSRESETREQ_Msk); __DSB(); /* Ensure completion of memory access */ while(1) { __NOP(); } /* wait until reset */ } /*@} end of CMSIS_Core_NVICFunctions */ /* ################################## SysTick function ############################################ */ /** \ingroup CMSIS_Core_FunctionInterface \defgroup CMSIS_Core_SysTickFunctions SysTick Functions \brief Functions that configure the System. @{ */ #if (__Vendor_SysTickConfig == 0) /** \brief System Tick Configuration The function initializes the System Timer and its interrupt, and starts the System Tick Timer. Counter is in free running mode to generate periodic interrupts. \param [in] ticks Number of ticks between two interrupts. \return 0 Function succeeded. \return 1 Function failed. \note When the variable __Vendor_SysTickConfig is set to 1, then the function SysTick_Config is not included. In this case, the file device.h must contain a vendor-specific implementation of this function. */ __STATIC_INLINE uint32_t SysTick_Config(uint32_t ticks) { if ((ticks - 1UL) > SysTick_LOAD_RELOAD_Msk) {return (1UL);} /* Reload value impossible */ SysTick->LOAD = (uint32_t)(ticks - 1UL); /* set reload register */ NVIC_SetPriority (SysTick_IRQn, (1UL << __NVIC_PRIO_BITS) - 1UL); /* set Priority for Systick Interrupt */ SysTick->VAL = 0UL; /* Load the SysTick Counter Value */ SysTick->CTRL = SysTick_CTRL_CLKSOURCE_Msk | SysTick_CTRL_TICKINT_Msk | SysTick_CTRL_ENABLE_Msk; /* Enable SysTick IRQ and SysTick Timer */ return (0UL); /* Function successful */ } #endif /*@} end of CMSIS_Core_SysTickFunctions */ #ifdef __cplusplus } #endif #endif /* __CORE_CM0PLUS_H_DEPENDANT */ #endif /* __CMSIS_GENERIC */ ================================================ FILE: Zelig/mbed/TARGET_NUCLEO_F091RC/core_cm3.h ================================================ /**************************************************************************//** * @file core_cm3.h * @brief CMSIS Cortex-M3 Core Peripheral Access Layer Header File * @version V4.10 * @date 18. March 2015 * * @note * ******************************************************************************/ /* Copyright (c) 2009 - 2015 ARM LIMITED All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: - Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. - Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. - Neither the name of ARM 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 COPYRIGHT HOLDERS AND 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. ---------------------------------------------------------------------------*/ #if defined ( __ICCARM__ ) #pragma system_include /* treat file as system include file for MISRA check */ #endif #ifndef __CORE_CM3_H_GENERIC #define __CORE_CM3_H_GENERIC #ifdef __cplusplus extern "C" { #endif /** \page CMSIS_MISRA_Exceptions MISRA-C:2004 Compliance Exceptions CMSIS violates the following MISRA-C:2004 rules: \li Required Rule 8.5, object/function definition in header file.
Function definitions in header files are used to allow 'inlining'. \li Required Rule 18.4, declaration of union type or object of union type: '{...}'.
Unions are used for effective representation of core registers. \li Advisory Rule 19.7, Function-like macro defined.
Function-like macros are used to allow more efficient code. */ /******************************************************************************* * CMSIS definitions ******************************************************************************/ /** \ingroup Cortex_M3 @{ */ /* CMSIS CM3 definitions */ #define __CM3_CMSIS_VERSION_MAIN (0x04) /*!< [31:16] CMSIS HAL main version */ #define __CM3_CMSIS_VERSION_SUB (0x00) /*!< [15:0] CMSIS HAL sub version */ #define __CM3_CMSIS_VERSION ((__CM3_CMSIS_VERSION_MAIN << 16) | \ __CM3_CMSIS_VERSION_SUB ) /*!< CMSIS HAL version number */ #define __CORTEX_M (0x03) /*!< Cortex-M Core */ #if defined ( __CC_ARM ) #define __ASM __asm /*!< asm keyword for ARM Compiler */ #define __INLINE __inline /*!< inline keyword for ARM Compiler */ #define __STATIC_INLINE static __inline #elif defined ( __GNUC__ ) #define __ASM __asm /*!< asm keyword for GNU Compiler */ #define __INLINE inline /*!< inline keyword for GNU Compiler */ #define __STATIC_INLINE static inline #elif defined ( __ICCARM__ ) #define __ASM __asm /*!< asm keyword for IAR Compiler */ #define __INLINE inline /*!< inline keyword for IAR Compiler. Only available in High optimization mode! */ #define __STATIC_INLINE static inline #elif defined ( __TMS470__ ) #define __ASM __asm /*!< asm keyword for TI CCS Compiler */ #define __STATIC_INLINE static inline #elif defined ( __TASKING__ ) #define __ASM __asm /*!< asm keyword for TASKING Compiler */ #define __INLINE inline /*!< inline keyword for TASKING Compiler */ #define __STATIC_INLINE static inline #elif defined ( __CSMC__ ) #define __packed #define __ASM _asm /*!< asm keyword for COSMIC Compiler */ #define __INLINE inline /*use -pc99 on compile line !< inline keyword for COSMIC Compiler */ #define __STATIC_INLINE static inline #endif /** __FPU_USED indicates whether an FPU is used or not. This core does not support an FPU at all */ #define __FPU_USED 0 #if defined ( __CC_ARM ) #if defined __TARGET_FPU_VFP #warning "Compiler generates FPU instructions for a device without an FPU (check __FPU_PRESENT)" #endif #elif defined ( __GNUC__ ) #if defined (__VFP_FP__) && !defined(__SOFTFP__) #warning "Compiler generates FPU instructions for a device without an FPU (check __FPU_PRESENT)" #endif #elif defined ( __ICCARM__ ) #if defined __ARMVFP__ #warning "Compiler generates FPU instructions for a device without an FPU (check __FPU_PRESENT)" #endif #elif defined ( __TMS470__ ) #if defined __TI__VFP_SUPPORT____ #warning "Compiler generates FPU instructions for a device without an FPU (check __FPU_PRESENT)" #endif #elif defined ( __TASKING__ ) #if defined __FPU_VFP__ #error "Compiler generates FPU instructions for a device without an FPU (check __FPU_PRESENT)" #endif #elif defined ( __CSMC__ ) /* Cosmic */ #if ( __CSMC__ & 0x400) // FPU present for parser #error "Compiler generates FPU instructions for a device without an FPU (check __FPU_PRESENT)" #endif #endif #include /* standard types definitions */ #include /* Core Instruction Access */ #include /* Core Function Access */ #ifdef __cplusplus } #endif #endif /* __CORE_CM3_H_GENERIC */ #ifndef __CMSIS_GENERIC #ifndef __CORE_CM3_H_DEPENDANT #define __CORE_CM3_H_DEPENDANT #ifdef __cplusplus extern "C" { #endif /* check device defines and use defaults */ #if defined __CHECK_DEVICE_DEFINES #ifndef __CM3_REV #define __CM3_REV 0x0200 #warning "__CM3_REV not defined in device header file; using default!" #endif #ifndef __MPU_PRESENT #define __MPU_PRESENT 0 #warning "__MPU_PRESENT not defined in device header file; using default!" #endif #ifndef __NVIC_PRIO_BITS #define __NVIC_PRIO_BITS 4 #warning "__NVIC_PRIO_BITS not defined in device header file; using default!" #endif #ifndef __Vendor_SysTickConfig #define __Vendor_SysTickConfig 0 #warning "__Vendor_SysTickConfig not defined in device header file; using default!" #endif #endif /* IO definitions (access restrictions to peripheral registers) */ /** \defgroup CMSIS_glob_defs CMSIS Global Defines IO Type Qualifiers are used \li to specify the access to peripheral variables. \li for automatic generation of peripheral register debug information. */ #ifdef __cplusplus #define __I volatile /*!< Defines 'read only' permissions */ #else #define __I volatile const /*!< Defines 'read only' permissions */ #endif #define __O volatile /*!< Defines 'write only' permissions */ #define __IO volatile /*!< Defines 'read / write' permissions */ /*@} end of group Cortex_M3 */ /******************************************************************************* * Register Abstraction Core Register contain: - Core Register - Core NVIC Register - Core SCB Register - Core SysTick Register - Core Debug Register - Core MPU Register ******************************************************************************/ /** \defgroup CMSIS_core_register Defines and Type Definitions \brief Type definitions and defines for Cortex-M processor based devices. */ /** \ingroup CMSIS_core_register \defgroup CMSIS_CORE Status and Control Registers \brief Core Register type definitions. @{ */ /** \brief Union type to access the Application Program Status Register (APSR). */ typedef union { struct { uint32_t _reserved0:27; /*!< bit: 0..26 Reserved */ uint32_t Q:1; /*!< bit: 27 Saturation condition flag */ uint32_t V:1; /*!< bit: 28 Overflow condition code flag */ uint32_t C:1; /*!< bit: 29 Carry condition code flag */ uint32_t Z:1; /*!< bit: 30 Zero condition code flag */ uint32_t N:1; /*!< bit: 31 Negative condition code flag */ } b; /*!< Structure used for bit access */ uint32_t w; /*!< Type used for word access */ } APSR_Type; /* APSR Register Definitions */ #define APSR_N_Pos 31 /*!< APSR: N Position */ #define APSR_N_Msk (1UL << APSR_N_Pos) /*!< APSR: N Mask */ #define APSR_Z_Pos 30 /*!< APSR: Z Position */ #define APSR_Z_Msk (1UL << APSR_Z_Pos) /*!< APSR: Z Mask */ #define APSR_C_Pos 29 /*!< APSR: C Position */ #define APSR_C_Msk (1UL << APSR_C_Pos) /*!< APSR: C Mask */ #define APSR_V_Pos 28 /*!< APSR: V Position */ #define APSR_V_Msk (1UL << APSR_V_Pos) /*!< APSR: V Mask */ #define APSR_Q_Pos 27 /*!< APSR: Q Position */ #define APSR_Q_Msk (1UL << APSR_Q_Pos) /*!< APSR: Q Mask */ /** \brief Union type to access the Interrupt Program Status Register (IPSR). */ typedef union { struct { uint32_t ISR:9; /*!< bit: 0.. 8 Exception number */ uint32_t _reserved0:23; /*!< bit: 9..31 Reserved */ } b; /*!< Structure used for bit access */ uint32_t w; /*!< Type used for word access */ } IPSR_Type; /* IPSR Register Definitions */ #define IPSR_ISR_Pos 0 /*!< IPSR: ISR Position */ #define IPSR_ISR_Msk (0x1FFUL /*<< IPSR_ISR_Pos*/) /*!< IPSR: ISR Mask */ /** \brief Union type to access the Special-Purpose Program Status Registers (xPSR). */ typedef union { struct { uint32_t ISR:9; /*!< bit: 0.. 8 Exception number */ uint32_t _reserved0:15; /*!< bit: 9..23 Reserved */ uint32_t T:1; /*!< bit: 24 Thumb bit (read 0) */ uint32_t IT:2; /*!< bit: 25..26 saved IT state (read 0) */ uint32_t Q:1; /*!< bit: 27 Saturation condition flag */ uint32_t V:1; /*!< bit: 28 Overflow condition code flag */ uint32_t C:1; /*!< bit: 29 Carry condition code flag */ uint32_t Z:1; /*!< bit: 30 Zero condition code flag */ uint32_t N:1; /*!< bit: 31 Negative condition code flag */ } b; /*!< Structure used for bit access */ uint32_t w; /*!< Type used for word access */ } xPSR_Type; /* xPSR Register Definitions */ #define xPSR_N_Pos 31 /*!< xPSR: N Position */ #define xPSR_N_Msk (1UL << xPSR_N_Pos) /*!< xPSR: N Mask */ #define xPSR_Z_Pos 30 /*!< xPSR: Z Position */ #define xPSR_Z_Msk (1UL << xPSR_Z_Pos) /*!< xPSR: Z Mask */ #define xPSR_C_Pos 29 /*!< xPSR: C Position */ #define xPSR_C_Msk (1UL << xPSR_C_Pos) /*!< xPSR: C Mask */ #define xPSR_V_Pos 28 /*!< xPSR: V Position */ #define xPSR_V_Msk (1UL << xPSR_V_Pos) /*!< xPSR: V Mask */ #define xPSR_Q_Pos 27 /*!< xPSR: Q Position */ #define xPSR_Q_Msk (1UL << xPSR_Q_Pos) /*!< xPSR: Q Mask */ #define xPSR_IT_Pos 25 /*!< xPSR: IT Position */ #define xPSR_IT_Msk (3UL << xPSR_IT_Pos) /*!< xPSR: IT Mask */ #define xPSR_T_Pos 24 /*!< xPSR: T Position */ #define xPSR_T_Msk (1UL << xPSR_T_Pos) /*!< xPSR: T Mask */ #define xPSR_ISR_Pos 0 /*!< xPSR: ISR Position */ #define xPSR_ISR_Msk (0x1FFUL /*<< xPSR_ISR_Pos*/) /*!< xPSR: ISR Mask */ /** \brief Union type to access the Control Registers (CONTROL). */ typedef union { struct { uint32_t nPRIV:1; /*!< bit: 0 Execution privilege in Thread mode */ uint32_t SPSEL:1; /*!< bit: 1 Stack to be used */ uint32_t _reserved1:30; /*!< bit: 2..31 Reserved */ } b; /*!< Structure used for bit access */ uint32_t w; /*!< Type used for word access */ } CONTROL_Type; /* CONTROL Register Definitions */ #define CONTROL_SPSEL_Pos 1 /*!< CONTROL: SPSEL Position */ #define CONTROL_SPSEL_Msk (1UL << CONTROL_SPSEL_Pos) /*!< CONTROL: SPSEL Mask */ #define CONTROL_nPRIV_Pos 0 /*!< CONTROL: nPRIV Position */ #define CONTROL_nPRIV_Msk (1UL /*<< CONTROL_nPRIV_Pos*/) /*!< CONTROL: nPRIV Mask */ /*@} end of group CMSIS_CORE */ /** \ingroup CMSIS_core_register \defgroup CMSIS_NVIC Nested Vectored Interrupt Controller (NVIC) \brief Type definitions for the NVIC Registers @{ */ /** \brief Structure type to access the Nested Vectored Interrupt Controller (NVIC). */ typedef struct { __IO uint32_t ISER[8]; /*!< Offset: 0x000 (R/W) Interrupt Set Enable Register */ uint32_t RESERVED0[24]; __IO uint32_t ICER[8]; /*!< Offset: 0x080 (R/W) Interrupt Clear Enable Register */ uint32_t RSERVED1[24]; __IO uint32_t ISPR[8]; /*!< Offset: 0x100 (R/W) Interrupt Set Pending Register */ uint32_t RESERVED2[24]; __IO uint32_t ICPR[8]; /*!< Offset: 0x180 (R/W) Interrupt Clear Pending Register */ uint32_t RESERVED3[24]; __IO uint32_t IABR[8]; /*!< Offset: 0x200 (R/W) Interrupt Active bit Register */ uint32_t RESERVED4[56]; __IO uint8_t IP[240]; /*!< Offset: 0x300 (R/W) Interrupt Priority Register (8Bit wide) */ uint32_t RESERVED5[644]; __O uint32_t STIR; /*!< Offset: 0xE00 ( /W) Software Trigger Interrupt Register */ } NVIC_Type; /* Software Triggered Interrupt Register Definitions */ #define NVIC_STIR_INTID_Pos 0 /*!< STIR: INTLINESNUM Position */ #define NVIC_STIR_INTID_Msk (0x1FFUL /*<< NVIC_STIR_INTID_Pos*/) /*!< STIR: INTLINESNUM Mask */ /*@} end of group CMSIS_NVIC */ /** \ingroup CMSIS_core_register \defgroup CMSIS_SCB System Control Block (SCB) \brief Type definitions for the System Control Block Registers @{ */ /** \brief Structure type to access the System Control Block (SCB). */ typedef struct { __I uint32_t CPUID; /*!< Offset: 0x000 (R/ ) CPUID Base Register */ __IO uint32_t ICSR; /*!< Offset: 0x004 (R/W) Interrupt Control and State Register */ __IO uint32_t VTOR; /*!< Offset: 0x008 (R/W) Vector Table Offset Register */ __IO uint32_t AIRCR; /*!< Offset: 0x00C (R/W) Application Interrupt and Reset Control Register */ __IO uint32_t SCR; /*!< Offset: 0x010 (R/W) System Control Register */ __IO uint32_t CCR; /*!< Offset: 0x014 (R/W) Configuration Control Register */ __IO uint8_t SHP[12]; /*!< Offset: 0x018 (R/W) System Handlers Priority Registers (4-7, 8-11, 12-15) */ __IO uint32_t SHCSR; /*!< Offset: 0x024 (R/W) System Handler Control and State Register */ __IO uint32_t CFSR; /*!< Offset: 0x028 (R/W) Configurable Fault Status Register */ __IO uint32_t HFSR; /*!< Offset: 0x02C (R/W) HardFault Status Register */ __IO uint32_t DFSR; /*!< Offset: 0x030 (R/W) Debug Fault Status Register */ __IO uint32_t MMFAR; /*!< Offset: 0x034 (R/W) MemManage Fault Address Register */ __IO uint32_t BFAR; /*!< Offset: 0x038 (R/W) BusFault Address Register */ __IO uint32_t AFSR; /*!< Offset: 0x03C (R/W) Auxiliary Fault Status Register */ __I uint32_t PFR[2]; /*!< Offset: 0x040 (R/ ) Processor Feature Register */ __I uint32_t DFR; /*!< Offset: 0x048 (R/ ) Debug Feature Register */ __I uint32_t ADR; /*!< Offset: 0x04C (R/ ) Auxiliary Feature Register */ __I uint32_t MMFR[4]; /*!< Offset: 0x050 (R/ ) Memory Model Feature Register */ __I uint32_t ISAR[5]; /*!< Offset: 0x060 (R/ ) Instruction Set Attributes Register */ uint32_t RESERVED0[5]; __IO uint32_t CPACR; /*!< Offset: 0x088 (R/W) Coprocessor Access Control Register */ } SCB_Type; /* SCB CPUID Register Definitions */ #define SCB_CPUID_IMPLEMENTER_Pos 24 /*!< SCB CPUID: IMPLEMENTER Position */ #define SCB_CPUID_IMPLEMENTER_Msk (0xFFUL << SCB_CPUID_IMPLEMENTER_Pos) /*!< SCB CPUID: IMPLEMENTER Mask */ #define SCB_CPUID_VARIANT_Pos 20 /*!< SCB CPUID: VARIANT Position */ #define SCB_CPUID_VARIANT_Msk (0xFUL << SCB_CPUID_VARIANT_Pos) /*!< SCB CPUID: VARIANT Mask */ #define SCB_CPUID_ARCHITECTURE_Pos 16 /*!< SCB CPUID: ARCHITECTURE Position */ #define SCB_CPUID_ARCHITECTURE_Msk (0xFUL << SCB_CPUID_ARCHITECTURE_Pos) /*!< SCB CPUID: ARCHITECTURE Mask */ #define SCB_CPUID_PARTNO_Pos 4 /*!< SCB CPUID: PARTNO Position */ #define SCB_CPUID_PARTNO_Msk (0xFFFUL << SCB_CPUID_PARTNO_Pos) /*!< SCB CPUID: PARTNO Mask */ #define SCB_CPUID_REVISION_Pos 0 /*!< SCB CPUID: REVISION Position */ #define SCB_CPUID_REVISION_Msk (0xFUL /*<< SCB_CPUID_REVISION_Pos*/) /*!< SCB CPUID: REVISION Mask */ /* SCB Interrupt Control State Register Definitions */ #define SCB_ICSR_NMIPENDSET_Pos 31 /*!< SCB ICSR: NMIPENDSET Position */ #define SCB_ICSR_NMIPENDSET_Msk (1UL << SCB_ICSR_NMIPENDSET_Pos) /*!< SCB ICSR: NMIPENDSET Mask */ #define SCB_ICSR_PENDSVSET_Pos 28 /*!< SCB ICSR: PENDSVSET Position */ #define SCB_ICSR_PENDSVSET_Msk (1UL << SCB_ICSR_PENDSVSET_Pos) /*!< SCB ICSR: PENDSVSET Mask */ #define SCB_ICSR_PENDSVCLR_Pos 27 /*!< SCB ICSR: PENDSVCLR Position */ #define SCB_ICSR_PENDSVCLR_Msk (1UL << SCB_ICSR_PENDSVCLR_Pos) /*!< SCB ICSR: PENDSVCLR Mask */ #define SCB_ICSR_PENDSTSET_Pos 26 /*!< SCB ICSR: PENDSTSET Position */ #define SCB_ICSR_PENDSTSET_Msk (1UL << SCB_ICSR_PENDSTSET_Pos) /*!< SCB ICSR: PENDSTSET Mask */ #define SCB_ICSR_PENDSTCLR_Pos 25 /*!< SCB ICSR: PENDSTCLR Position */ #define SCB_ICSR_PENDSTCLR_Msk (1UL << SCB_ICSR_PENDSTCLR_Pos) /*!< SCB ICSR: PENDSTCLR Mask */ #define SCB_ICSR_ISRPREEMPT_Pos 23 /*!< SCB ICSR: ISRPREEMPT Position */ #define SCB_ICSR_ISRPREEMPT_Msk (1UL << SCB_ICSR_ISRPREEMPT_Pos) /*!< SCB ICSR: ISRPREEMPT Mask */ #define SCB_ICSR_ISRPENDING_Pos 22 /*!< SCB ICSR: ISRPENDING Position */ #define SCB_ICSR_ISRPENDING_Msk (1UL << SCB_ICSR_ISRPENDING_Pos) /*!< SCB ICSR: ISRPENDING Mask */ #define SCB_ICSR_VECTPENDING_Pos 12 /*!< SCB ICSR: VECTPENDING Position */ #define SCB_ICSR_VECTPENDING_Msk (0x1FFUL << SCB_ICSR_VECTPENDING_Pos) /*!< SCB ICSR: VECTPENDING Mask */ #define SCB_ICSR_RETTOBASE_Pos 11 /*!< SCB ICSR: RETTOBASE Position */ #define SCB_ICSR_RETTOBASE_Msk (1UL << SCB_ICSR_RETTOBASE_Pos) /*!< SCB ICSR: RETTOBASE Mask */ #define SCB_ICSR_VECTACTIVE_Pos 0 /*!< SCB ICSR: VECTACTIVE Position */ #define SCB_ICSR_VECTACTIVE_Msk (0x1FFUL /*<< SCB_ICSR_VECTACTIVE_Pos*/) /*!< SCB ICSR: VECTACTIVE Mask */ /* SCB Vector Table Offset Register Definitions */ #if (__CM3_REV < 0x0201) /* core r2p1 */ #define SCB_VTOR_TBLBASE_Pos 29 /*!< SCB VTOR: TBLBASE Position */ #define SCB_VTOR_TBLBASE_Msk (1UL << SCB_VTOR_TBLBASE_Pos) /*!< SCB VTOR: TBLBASE Mask */ #define SCB_VTOR_TBLOFF_Pos 7 /*!< SCB VTOR: TBLOFF Position */ #define SCB_VTOR_TBLOFF_Msk (0x3FFFFFUL << SCB_VTOR_TBLOFF_Pos) /*!< SCB VTOR: TBLOFF Mask */ #else #define SCB_VTOR_TBLOFF_Pos 7 /*!< SCB VTOR: TBLOFF Position */ #define SCB_VTOR_TBLOFF_Msk (0x1FFFFFFUL << SCB_VTOR_TBLOFF_Pos) /*!< SCB VTOR: TBLOFF Mask */ #endif /* SCB Application Interrupt and Reset Control Register Definitions */ #define SCB_AIRCR_VECTKEY_Pos 16 /*!< SCB AIRCR: VECTKEY Position */ #define SCB_AIRCR_VECTKEY_Msk (0xFFFFUL << SCB_AIRCR_VECTKEY_Pos) /*!< SCB AIRCR: VECTKEY Mask */ #define SCB_AIRCR_VECTKEYSTAT_Pos 16 /*!< SCB AIRCR: VECTKEYSTAT Position */ #define SCB_AIRCR_VECTKEYSTAT_Msk (0xFFFFUL << SCB_AIRCR_VECTKEYSTAT_Pos) /*!< SCB AIRCR: VECTKEYSTAT Mask */ #define SCB_AIRCR_ENDIANESS_Pos 15 /*!< SCB AIRCR: ENDIANESS Position */ #define SCB_AIRCR_ENDIANESS_Msk (1UL << SCB_AIRCR_ENDIANESS_Pos) /*!< SCB AIRCR: ENDIANESS Mask */ #define SCB_AIRCR_PRIGROUP_Pos 8 /*!< SCB AIRCR: PRIGROUP Position */ #define SCB_AIRCR_PRIGROUP_Msk (7UL << SCB_AIRCR_PRIGROUP_Pos) /*!< SCB AIRCR: PRIGROUP Mask */ #define SCB_AIRCR_SYSRESETREQ_Pos 2 /*!< SCB AIRCR: SYSRESETREQ Position */ #define SCB_AIRCR_SYSRESETREQ_Msk (1UL << SCB_AIRCR_SYSRESETREQ_Pos) /*!< SCB AIRCR: SYSRESETREQ Mask */ #define SCB_AIRCR_VECTCLRACTIVE_Pos 1 /*!< SCB AIRCR: VECTCLRACTIVE Position */ #define SCB_AIRCR_VECTCLRACTIVE_Msk (1UL << SCB_AIRCR_VECTCLRACTIVE_Pos) /*!< SCB AIRCR: VECTCLRACTIVE Mask */ #define SCB_AIRCR_VECTRESET_Pos 0 /*!< SCB AIRCR: VECTRESET Position */ #define SCB_AIRCR_VECTRESET_Msk (1UL /*<< SCB_AIRCR_VECTRESET_Pos*/) /*!< SCB AIRCR: VECTRESET Mask */ /* SCB System Control Register Definitions */ #define SCB_SCR_SEVONPEND_Pos 4 /*!< SCB SCR: SEVONPEND Position */ #define SCB_SCR_SEVONPEND_Msk (1UL << SCB_SCR_SEVONPEND_Pos) /*!< SCB SCR: SEVONPEND Mask */ #define SCB_SCR_SLEEPDEEP_Pos 2 /*!< SCB SCR: SLEEPDEEP Position */ #define SCB_SCR_SLEEPDEEP_Msk (1UL << SCB_SCR_SLEEPDEEP_Pos) /*!< SCB SCR: SLEEPDEEP Mask */ #define SCB_SCR_SLEEPONEXIT_Pos 1 /*!< SCB SCR: SLEEPONEXIT Position */ #define SCB_SCR_SLEEPONEXIT_Msk (1UL << SCB_SCR_SLEEPONEXIT_Pos) /*!< SCB SCR: SLEEPONEXIT Mask */ /* SCB Configuration Control Register Definitions */ #define SCB_CCR_STKALIGN_Pos 9 /*!< SCB CCR: STKALIGN Position */ #define SCB_CCR_STKALIGN_Msk (1UL << SCB_CCR_STKALIGN_Pos) /*!< SCB CCR: STKALIGN Mask */ #define SCB_CCR_BFHFNMIGN_Pos 8 /*!< SCB CCR: BFHFNMIGN Position */ #define SCB_CCR_BFHFNMIGN_Msk (1UL << SCB_CCR_BFHFNMIGN_Pos) /*!< SCB CCR: BFHFNMIGN Mask */ #define SCB_CCR_DIV_0_TRP_Pos 4 /*!< SCB CCR: DIV_0_TRP Position */ #define SCB_CCR_DIV_0_TRP_Msk (1UL << SCB_CCR_DIV_0_TRP_Pos) /*!< SCB CCR: DIV_0_TRP Mask */ #define SCB_CCR_UNALIGN_TRP_Pos 3 /*!< SCB CCR: UNALIGN_TRP Position */ #define SCB_CCR_UNALIGN_TRP_Msk (1UL << SCB_CCR_UNALIGN_TRP_Pos) /*!< SCB CCR: UNALIGN_TRP Mask */ #define SCB_CCR_USERSETMPEND_Pos 1 /*!< SCB CCR: USERSETMPEND Position */ #define SCB_CCR_USERSETMPEND_Msk (1UL << SCB_CCR_USERSETMPEND_Pos) /*!< SCB CCR: USERSETMPEND Mask */ #define SCB_CCR_NONBASETHRDENA_Pos 0 /*!< SCB CCR: NONBASETHRDENA Position */ #define SCB_CCR_NONBASETHRDENA_Msk (1UL /*<< SCB_CCR_NONBASETHRDENA_Pos*/) /*!< SCB CCR: NONBASETHRDENA Mask */ /* SCB System Handler Control and State Register Definitions */ #define SCB_SHCSR_USGFAULTENA_Pos 18 /*!< SCB SHCSR: USGFAULTENA Position */ #define SCB_SHCSR_USGFAULTENA_Msk (1UL << SCB_SHCSR_USGFAULTENA_Pos) /*!< SCB SHCSR: USGFAULTENA Mask */ #define SCB_SHCSR_BUSFAULTENA_Pos 17 /*!< SCB SHCSR: BUSFAULTENA Position */ #define SCB_SHCSR_BUSFAULTENA_Msk (1UL << SCB_SHCSR_BUSFAULTENA_Pos) /*!< SCB SHCSR: BUSFAULTENA Mask */ #define SCB_SHCSR_MEMFAULTENA_Pos 16 /*!< SCB SHCSR: MEMFAULTENA Position */ #define SCB_SHCSR_MEMFAULTENA_Msk (1UL << SCB_SHCSR_MEMFAULTENA_Pos) /*!< SCB SHCSR: MEMFAULTENA Mask */ #define SCB_SHCSR_SVCALLPENDED_Pos 15 /*!< SCB SHCSR: SVCALLPENDED Position */ #define SCB_SHCSR_SVCALLPENDED_Msk (1UL << SCB_SHCSR_SVCALLPENDED_Pos) /*!< SCB SHCSR: SVCALLPENDED Mask */ #define SCB_SHCSR_BUSFAULTPENDED_Pos 14 /*!< SCB SHCSR: BUSFAULTPENDED Position */ #define SCB_SHCSR_BUSFAULTPENDED_Msk (1UL << SCB_SHCSR_BUSFAULTPENDED_Pos) /*!< SCB SHCSR: BUSFAULTPENDED Mask */ #define SCB_SHCSR_MEMFAULTPENDED_Pos 13 /*!< SCB SHCSR: MEMFAULTPENDED Position */ #define SCB_SHCSR_MEMFAULTPENDED_Msk (1UL << SCB_SHCSR_MEMFAULTPENDED_Pos) /*!< SCB SHCSR: MEMFAULTPENDED Mask */ #define SCB_SHCSR_USGFAULTPENDED_Pos 12 /*!< SCB SHCSR: USGFAULTPENDED Position */ #define SCB_SHCSR_USGFAULTPENDED_Msk (1UL << SCB_SHCSR_USGFAULTPENDED_Pos) /*!< SCB SHCSR: USGFAULTPENDED Mask */ #define SCB_SHCSR_SYSTICKACT_Pos 11 /*!< SCB SHCSR: SYSTICKACT Position */ #define SCB_SHCSR_SYSTICKACT_Msk (1UL << SCB_SHCSR_SYSTICKACT_Pos) /*!< SCB SHCSR: SYSTICKACT Mask */ #define SCB_SHCSR_PENDSVACT_Pos 10 /*!< SCB SHCSR: PENDSVACT Position */ #define SCB_SHCSR_PENDSVACT_Msk (1UL << SCB_SHCSR_PENDSVACT_Pos) /*!< SCB SHCSR: PENDSVACT Mask */ #define SCB_SHCSR_MONITORACT_Pos 8 /*!< SCB SHCSR: MONITORACT Position */ #define SCB_SHCSR_MONITORACT_Msk (1UL << SCB_SHCSR_MONITORACT_Pos) /*!< SCB SHCSR: MONITORACT Mask */ #define SCB_SHCSR_SVCALLACT_Pos 7 /*!< SCB SHCSR: SVCALLACT Position */ #define SCB_SHCSR_SVCALLACT_Msk (1UL << SCB_SHCSR_SVCALLACT_Pos) /*!< SCB SHCSR: SVCALLACT Mask */ #define SCB_SHCSR_USGFAULTACT_Pos 3 /*!< SCB SHCSR: USGFAULTACT Position */ #define SCB_SHCSR_USGFAULTACT_Msk (1UL << SCB_SHCSR_USGFAULTACT_Pos) /*!< SCB SHCSR: USGFAULTACT Mask */ #define SCB_SHCSR_BUSFAULTACT_Pos 1 /*!< SCB SHCSR: BUSFAULTACT Position */ #define SCB_SHCSR_BUSFAULTACT_Msk (1UL << SCB_SHCSR_BUSFAULTACT_Pos) /*!< SCB SHCSR: BUSFAULTACT Mask */ #define SCB_SHCSR_MEMFAULTACT_Pos 0 /*!< SCB SHCSR: MEMFAULTACT Position */ #define SCB_SHCSR_MEMFAULTACT_Msk (1UL /*<< SCB_SHCSR_MEMFAULTACT_Pos*/) /*!< SCB SHCSR: MEMFAULTACT Mask */ /* SCB Configurable Fault Status Registers Definitions */ #define SCB_CFSR_USGFAULTSR_Pos 16 /*!< SCB CFSR: Usage Fault Status Register Position */ #define SCB_CFSR_USGFAULTSR_Msk (0xFFFFUL << SCB_CFSR_USGFAULTSR_Pos) /*!< SCB CFSR: Usage Fault Status Register Mask */ #define SCB_CFSR_BUSFAULTSR_Pos 8 /*!< SCB CFSR: Bus Fault Status Register Position */ #define SCB_CFSR_BUSFAULTSR_Msk (0xFFUL << SCB_CFSR_BUSFAULTSR_Pos) /*!< SCB CFSR: Bus Fault Status Register Mask */ #define SCB_CFSR_MEMFAULTSR_Pos 0 /*!< SCB CFSR: Memory Manage Fault Status Register Position */ #define SCB_CFSR_MEMFAULTSR_Msk (0xFFUL /*<< SCB_CFSR_MEMFAULTSR_Pos*/) /*!< SCB CFSR: Memory Manage Fault Status Register Mask */ /* SCB Hard Fault Status Registers Definitions */ #define SCB_HFSR_DEBUGEVT_Pos 31 /*!< SCB HFSR: DEBUGEVT Position */ #define SCB_HFSR_DEBUGEVT_Msk (1UL << SCB_HFSR_DEBUGEVT_Pos) /*!< SCB HFSR: DEBUGEVT Mask */ #define SCB_HFSR_FORCED_Pos 30 /*!< SCB HFSR: FORCED Position */ #define SCB_HFSR_FORCED_Msk (1UL << SCB_HFSR_FORCED_Pos) /*!< SCB HFSR: FORCED Mask */ #define SCB_HFSR_VECTTBL_Pos 1 /*!< SCB HFSR: VECTTBL Position */ #define SCB_HFSR_VECTTBL_Msk (1UL << SCB_HFSR_VECTTBL_Pos) /*!< SCB HFSR: VECTTBL Mask */ /* SCB Debug Fault Status Register Definitions */ #define SCB_DFSR_EXTERNAL_Pos 4 /*!< SCB DFSR: EXTERNAL Position */ #define SCB_DFSR_EXTERNAL_Msk (1UL << SCB_DFSR_EXTERNAL_Pos) /*!< SCB DFSR: EXTERNAL Mask */ #define SCB_DFSR_VCATCH_Pos 3 /*!< SCB DFSR: VCATCH Position */ #define SCB_DFSR_VCATCH_Msk (1UL << SCB_DFSR_VCATCH_Pos) /*!< SCB DFSR: VCATCH Mask */ #define SCB_DFSR_DWTTRAP_Pos 2 /*!< SCB DFSR: DWTTRAP Position */ #define SCB_DFSR_DWTTRAP_Msk (1UL << SCB_DFSR_DWTTRAP_Pos) /*!< SCB DFSR: DWTTRAP Mask */ #define SCB_DFSR_BKPT_Pos 1 /*!< SCB DFSR: BKPT Position */ #define SCB_DFSR_BKPT_Msk (1UL << SCB_DFSR_BKPT_Pos) /*!< SCB DFSR: BKPT Mask */ #define SCB_DFSR_HALTED_Pos 0 /*!< SCB DFSR: HALTED Position */ #define SCB_DFSR_HALTED_Msk (1UL /*<< SCB_DFSR_HALTED_Pos*/) /*!< SCB DFSR: HALTED Mask */ /*@} end of group CMSIS_SCB */ /** \ingroup CMSIS_core_register \defgroup CMSIS_SCnSCB System Controls not in SCB (SCnSCB) \brief Type definitions for the System Control and ID Register not in the SCB @{ */ /** \brief Structure type to access the System Control and ID Register not in the SCB. */ typedef struct { uint32_t RESERVED0[1]; __I uint32_t ICTR; /*!< Offset: 0x004 (R/ ) Interrupt Controller Type Register */ #if ((defined __CM3_REV) && (__CM3_REV >= 0x200)) __IO uint32_t ACTLR; /*!< Offset: 0x008 (R/W) Auxiliary Control Register */ #else uint32_t RESERVED1[1]; #endif } SCnSCB_Type; /* Interrupt Controller Type Register Definitions */ #define SCnSCB_ICTR_INTLINESNUM_Pos 0 /*!< ICTR: INTLINESNUM Position */ #define SCnSCB_ICTR_INTLINESNUM_Msk (0xFUL /*<< SCnSCB_ICTR_INTLINESNUM_Pos*/) /*!< ICTR: INTLINESNUM Mask */ /* Auxiliary Control Register Definitions */ #define SCnSCB_ACTLR_DISFOLD_Pos 2 /*!< ACTLR: DISFOLD Position */ #define SCnSCB_ACTLR_DISFOLD_Msk (1UL << SCnSCB_ACTLR_DISFOLD_Pos) /*!< ACTLR: DISFOLD Mask */ #define SCnSCB_ACTLR_DISDEFWBUF_Pos 1 /*!< ACTLR: DISDEFWBUF Position */ #define SCnSCB_ACTLR_DISDEFWBUF_Msk (1UL << SCnSCB_ACTLR_DISDEFWBUF_Pos) /*!< ACTLR: DISDEFWBUF Mask */ #define SCnSCB_ACTLR_DISMCYCINT_Pos 0 /*!< ACTLR: DISMCYCINT Position */ #define SCnSCB_ACTLR_DISMCYCINT_Msk (1UL /*<< SCnSCB_ACTLR_DISMCYCINT_Pos*/) /*!< ACTLR: DISMCYCINT Mask */ /*@} end of group CMSIS_SCnotSCB */ /** \ingroup CMSIS_core_register \defgroup CMSIS_SysTick System Tick Timer (SysTick) \brief Type definitions for the System Timer Registers. @{ */ /** \brief Structure type to access the System Timer (SysTick). */ typedef struct { __IO uint32_t CTRL; /*!< Offset: 0x000 (R/W) SysTick Control and Status Register */ __IO uint32_t LOAD; /*!< Offset: 0x004 (R/W) SysTick Reload Value Register */ __IO uint32_t VAL; /*!< Offset: 0x008 (R/W) SysTick Current Value Register */ __I uint32_t CALIB; /*!< Offset: 0x00C (R/ ) SysTick Calibration Register */ } SysTick_Type; /* SysTick Control / Status Register Definitions */ #define SysTick_CTRL_COUNTFLAG_Pos 16 /*!< SysTick CTRL: COUNTFLAG Position */ #define SysTick_CTRL_COUNTFLAG_Msk (1UL << SysTick_CTRL_COUNTFLAG_Pos) /*!< SysTick CTRL: COUNTFLAG Mask */ #define SysTick_CTRL_CLKSOURCE_Pos 2 /*!< SysTick CTRL: CLKSOURCE Position */ #define SysTick_CTRL_CLKSOURCE_Msk (1UL << SysTick_CTRL_CLKSOURCE_Pos) /*!< SysTick CTRL: CLKSOURCE Mask */ #define SysTick_CTRL_TICKINT_Pos 1 /*!< SysTick CTRL: TICKINT Position */ #define SysTick_CTRL_TICKINT_Msk (1UL << SysTick_CTRL_TICKINT_Pos) /*!< SysTick CTRL: TICKINT Mask */ #define SysTick_CTRL_ENABLE_Pos 0 /*!< SysTick CTRL: ENABLE Position */ #define SysTick_CTRL_ENABLE_Msk (1UL /*<< SysTick_CTRL_ENABLE_Pos*/) /*!< SysTick CTRL: ENABLE Mask */ /* SysTick Reload Register Definitions */ #define SysTick_LOAD_RELOAD_Pos 0 /*!< SysTick LOAD: RELOAD Position */ #define SysTick_LOAD_RELOAD_Msk (0xFFFFFFUL /*<< SysTick_LOAD_RELOAD_Pos*/) /*!< SysTick LOAD: RELOAD Mask */ /* SysTick Current Register Definitions */ #define SysTick_VAL_CURRENT_Pos 0 /*!< SysTick VAL: CURRENT Position */ #define SysTick_VAL_CURRENT_Msk (0xFFFFFFUL /*<< SysTick_VAL_CURRENT_Pos*/) /*!< SysTick VAL: CURRENT Mask */ /* SysTick Calibration Register Definitions */ #define SysTick_CALIB_NOREF_Pos 31 /*!< SysTick CALIB: NOREF Position */ #define SysTick_CALIB_NOREF_Msk (1UL << SysTick_CALIB_NOREF_Pos) /*!< SysTick CALIB: NOREF Mask */ #define SysTick_CALIB_SKEW_Pos 30 /*!< SysTick CALIB: SKEW Position */ #define SysTick_CALIB_SKEW_Msk (1UL << SysTick_CALIB_SKEW_Pos) /*!< SysTick CALIB: SKEW Mask */ #define SysTick_CALIB_TENMS_Pos 0 /*!< SysTick CALIB: TENMS Position */ #define SysTick_CALIB_TENMS_Msk (0xFFFFFFUL /*<< SysTick_CALIB_TENMS_Pos*/) /*!< SysTick CALIB: TENMS Mask */ /*@} end of group CMSIS_SysTick */ /** \ingroup CMSIS_core_register \defgroup CMSIS_ITM Instrumentation Trace Macrocell (ITM) \brief Type definitions for the Instrumentation Trace Macrocell (ITM) @{ */ /** \brief Structure type to access the Instrumentation Trace Macrocell Register (ITM). */ typedef struct { __O union { __O uint8_t u8; /*!< Offset: 0x000 ( /W) ITM Stimulus Port 8-bit */ __O uint16_t u16; /*!< Offset: 0x000 ( /W) ITM Stimulus Port 16-bit */ __O uint32_t u32; /*!< Offset: 0x000 ( /W) ITM Stimulus Port 32-bit */ } PORT [32]; /*!< Offset: 0x000 ( /W) ITM Stimulus Port Registers */ uint32_t RESERVED0[864]; __IO uint32_t TER; /*!< Offset: 0xE00 (R/W) ITM Trace Enable Register */ uint32_t RESERVED1[15]; __IO uint32_t TPR; /*!< Offset: 0xE40 (R/W) ITM Trace Privilege Register */ uint32_t RESERVED2[15]; __IO uint32_t TCR; /*!< Offset: 0xE80 (R/W) ITM Trace Control Register */ uint32_t RESERVED3[29]; __O uint32_t IWR; /*!< Offset: 0xEF8 ( /W) ITM Integration Write Register */ __I uint32_t IRR; /*!< Offset: 0xEFC (R/ ) ITM Integration Read Register */ __IO uint32_t IMCR; /*!< Offset: 0xF00 (R/W) ITM Integration Mode Control Register */ uint32_t RESERVED4[43]; __O uint32_t LAR; /*!< Offset: 0xFB0 ( /W) ITM Lock Access Register */ __I uint32_t LSR; /*!< Offset: 0xFB4 (R/ ) ITM Lock Status Register */ uint32_t RESERVED5[6]; __I uint32_t PID4; /*!< Offset: 0xFD0 (R/ ) ITM Peripheral Identification Register #4 */ __I uint32_t PID5; /*!< Offset: 0xFD4 (R/ ) ITM Peripheral Identification Register #5 */ __I uint32_t PID6; /*!< Offset: 0xFD8 (R/ ) ITM Peripheral Identification Register #6 */ __I uint32_t PID7; /*!< Offset: 0xFDC (R/ ) ITM Peripheral Identification Register #7 */ __I uint32_t PID0; /*!< Offset: 0xFE0 (R/ ) ITM Peripheral Identification Register #0 */ __I uint32_t PID1; /*!< Offset: 0xFE4 (R/ ) ITM Peripheral Identification Register #1 */ __I uint32_t PID2; /*!< Offset: 0xFE8 (R/ ) ITM Peripheral Identification Register #2 */ __I uint32_t PID3; /*!< Offset: 0xFEC (R/ ) ITM Peripheral Identification Register #3 */ __I uint32_t CID0; /*!< Offset: 0xFF0 (R/ ) ITM Component Identification Register #0 */ __I uint32_t CID1; /*!< Offset: 0xFF4 (R/ ) ITM Component Identification Register #1 */ __I uint32_t CID2; /*!< Offset: 0xFF8 (R/ ) ITM Component Identification Register #2 */ __I uint32_t CID3; /*!< Offset: 0xFFC (R/ ) ITM Component Identification Register #3 */ } ITM_Type; /* ITM Trace Privilege Register Definitions */ #define ITM_TPR_PRIVMASK_Pos 0 /*!< ITM TPR: PRIVMASK Position */ #define ITM_TPR_PRIVMASK_Msk (0xFUL /*<< ITM_TPR_PRIVMASK_Pos*/) /*!< ITM TPR: PRIVMASK Mask */ /* ITM Trace Control Register Definitions */ #define ITM_TCR_BUSY_Pos 23 /*!< ITM TCR: BUSY Position */ #define ITM_TCR_BUSY_Msk (1UL << ITM_TCR_BUSY_Pos) /*!< ITM TCR: BUSY Mask */ #define ITM_TCR_TraceBusID_Pos 16 /*!< ITM TCR: ATBID Position */ #define ITM_TCR_TraceBusID_Msk (0x7FUL << ITM_TCR_TraceBusID_Pos) /*!< ITM TCR: ATBID Mask */ #define ITM_TCR_GTSFREQ_Pos 10 /*!< ITM TCR: Global timestamp frequency Position */ #define ITM_TCR_GTSFREQ_Msk (3UL << ITM_TCR_GTSFREQ_Pos) /*!< ITM TCR: Global timestamp frequency Mask */ #define ITM_TCR_TSPrescale_Pos 8 /*!< ITM TCR: TSPrescale Position */ #define ITM_TCR_TSPrescale_Msk (3UL << ITM_TCR_TSPrescale_Pos) /*!< ITM TCR: TSPrescale Mask */ #define ITM_TCR_SWOENA_Pos 4 /*!< ITM TCR: SWOENA Position */ #define ITM_TCR_SWOENA_Msk (1UL << ITM_TCR_SWOENA_Pos) /*!< ITM TCR: SWOENA Mask */ #define ITM_TCR_DWTENA_Pos 3 /*!< ITM TCR: DWTENA Position */ #define ITM_TCR_DWTENA_Msk (1UL << ITM_TCR_DWTENA_Pos) /*!< ITM TCR: DWTENA Mask */ #define ITM_TCR_SYNCENA_Pos 2 /*!< ITM TCR: SYNCENA Position */ #define ITM_TCR_SYNCENA_Msk (1UL << ITM_TCR_SYNCENA_Pos) /*!< ITM TCR: SYNCENA Mask */ #define ITM_TCR_TSENA_Pos 1 /*!< ITM TCR: TSENA Position */ #define ITM_TCR_TSENA_Msk (1UL << ITM_TCR_TSENA_Pos) /*!< ITM TCR: TSENA Mask */ #define ITM_TCR_ITMENA_Pos 0 /*!< ITM TCR: ITM Enable bit Position */ #define ITM_TCR_ITMENA_Msk (1UL /*<< ITM_TCR_ITMENA_Pos*/) /*!< ITM TCR: ITM Enable bit Mask */ /* ITM Integration Write Register Definitions */ #define ITM_IWR_ATVALIDM_Pos 0 /*!< ITM IWR: ATVALIDM Position */ #define ITM_IWR_ATVALIDM_Msk (1UL /*<< ITM_IWR_ATVALIDM_Pos*/) /*!< ITM IWR: ATVALIDM Mask */ /* ITM Integration Read Register Definitions */ #define ITM_IRR_ATREADYM_Pos 0 /*!< ITM IRR: ATREADYM Position */ #define ITM_IRR_ATREADYM_Msk (1UL /*<< ITM_IRR_ATREADYM_Pos*/) /*!< ITM IRR: ATREADYM Mask */ /* ITM Integration Mode Control Register Definitions */ #define ITM_IMCR_INTEGRATION_Pos 0 /*!< ITM IMCR: INTEGRATION Position */ #define ITM_IMCR_INTEGRATION_Msk (1UL /*<< ITM_IMCR_INTEGRATION_Pos*/) /*!< ITM IMCR: INTEGRATION Mask */ /* ITM Lock Status Register Definitions */ #define ITM_LSR_ByteAcc_Pos 2 /*!< ITM LSR: ByteAcc Position */ #define ITM_LSR_ByteAcc_Msk (1UL << ITM_LSR_ByteAcc_Pos) /*!< ITM LSR: ByteAcc Mask */ #define ITM_LSR_Access_Pos 1 /*!< ITM LSR: Access Position */ #define ITM_LSR_Access_Msk (1UL << ITM_LSR_Access_Pos) /*!< ITM LSR: Access Mask */ #define ITM_LSR_Present_Pos 0 /*!< ITM LSR: Present Position */ #define ITM_LSR_Present_Msk (1UL /*<< ITM_LSR_Present_Pos*/) /*!< ITM LSR: Present Mask */ /*@}*/ /* end of group CMSIS_ITM */ /** \ingroup CMSIS_core_register \defgroup CMSIS_DWT Data Watchpoint and Trace (DWT) \brief Type definitions for the Data Watchpoint and Trace (DWT) @{ */ /** \brief Structure type to access the Data Watchpoint and Trace Register (DWT). */ typedef struct { __IO uint32_t CTRL; /*!< Offset: 0x000 (R/W) Control Register */ __IO uint32_t CYCCNT; /*!< Offset: 0x004 (R/W) Cycle Count Register */ __IO uint32_t CPICNT; /*!< Offset: 0x008 (R/W) CPI Count Register */ __IO uint32_t EXCCNT; /*!< Offset: 0x00C (R/W) Exception Overhead Count Register */ __IO uint32_t SLEEPCNT; /*!< Offset: 0x010 (R/W) Sleep Count Register */ __IO uint32_t LSUCNT; /*!< Offset: 0x014 (R/W) LSU Count Register */ __IO uint32_t FOLDCNT; /*!< Offset: 0x018 (R/W) Folded-instruction Count Register */ __I uint32_t PCSR; /*!< Offset: 0x01C (R/ ) Program Counter Sample Register */ __IO uint32_t COMP0; /*!< Offset: 0x020 (R/W) Comparator Register 0 */ __IO uint32_t MASK0; /*!< Offset: 0x024 (R/W) Mask Register 0 */ __IO uint32_t FUNCTION0; /*!< Offset: 0x028 (R/W) Function Register 0 */ uint32_t RESERVED0[1]; __IO uint32_t COMP1; /*!< Offset: 0x030 (R/W) Comparator Register 1 */ __IO uint32_t MASK1; /*!< Offset: 0x034 (R/W) Mask Register 1 */ __IO uint32_t FUNCTION1; /*!< Offset: 0x038 (R/W) Function Register 1 */ uint32_t RESERVED1[1]; __IO uint32_t COMP2; /*!< Offset: 0x040 (R/W) Comparator Register 2 */ __IO uint32_t MASK2; /*!< Offset: 0x044 (R/W) Mask Register 2 */ __IO uint32_t FUNCTION2; /*!< Offset: 0x048 (R/W) Function Register 2 */ uint32_t RESERVED2[1]; __IO uint32_t COMP3; /*!< Offset: 0x050 (R/W) Comparator Register 3 */ __IO uint32_t MASK3; /*!< Offset: 0x054 (R/W) Mask Register 3 */ __IO uint32_t FUNCTION3; /*!< Offset: 0x058 (R/W) Function Register 3 */ } DWT_Type; /* DWT Control Register Definitions */ #define DWT_CTRL_NUMCOMP_Pos 28 /*!< DWT CTRL: NUMCOMP Position */ #define DWT_CTRL_NUMCOMP_Msk (0xFUL << DWT_CTRL_NUMCOMP_Pos) /*!< DWT CTRL: NUMCOMP Mask */ #define DWT_CTRL_NOTRCPKT_Pos 27 /*!< DWT CTRL: NOTRCPKT Position */ #define DWT_CTRL_NOTRCPKT_Msk (0x1UL << DWT_CTRL_NOTRCPKT_Pos) /*!< DWT CTRL: NOTRCPKT Mask */ #define DWT_CTRL_NOEXTTRIG_Pos 26 /*!< DWT CTRL: NOEXTTRIG Position */ #define DWT_CTRL_NOEXTTRIG_Msk (0x1UL << DWT_CTRL_NOEXTTRIG_Pos) /*!< DWT CTRL: NOEXTTRIG Mask */ #define DWT_CTRL_NOCYCCNT_Pos 25 /*!< DWT CTRL: NOCYCCNT Position */ #define DWT_CTRL_NOCYCCNT_Msk (0x1UL << DWT_CTRL_NOCYCCNT_Pos) /*!< DWT CTRL: NOCYCCNT Mask */ #define DWT_CTRL_NOPRFCNT_Pos 24 /*!< DWT CTRL: NOPRFCNT Position */ #define DWT_CTRL_NOPRFCNT_Msk (0x1UL << DWT_CTRL_NOPRFCNT_Pos) /*!< DWT CTRL: NOPRFCNT Mask */ #define DWT_CTRL_CYCEVTENA_Pos 22 /*!< DWT CTRL: CYCEVTENA Position */ #define DWT_CTRL_CYCEVTENA_Msk (0x1UL << DWT_CTRL_CYCEVTENA_Pos) /*!< DWT CTRL: CYCEVTENA Mask */ #define DWT_CTRL_FOLDEVTENA_Pos 21 /*!< DWT CTRL: FOLDEVTENA Position */ #define DWT_CTRL_FOLDEVTENA_Msk (0x1UL << DWT_CTRL_FOLDEVTENA_Pos) /*!< DWT CTRL: FOLDEVTENA Mask */ #define DWT_CTRL_LSUEVTENA_Pos 20 /*!< DWT CTRL: LSUEVTENA Position */ #define DWT_CTRL_LSUEVTENA_Msk (0x1UL << DWT_CTRL_LSUEVTENA_Pos) /*!< DWT CTRL: LSUEVTENA Mask */ #define DWT_CTRL_SLEEPEVTENA_Pos 19 /*!< DWT CTRL: SLEEPEVTENA Position */ #define DWT_CTRL_SLEEPEVTENA_Msk (0x1UL << DWT_CTRL_SLEEPEVTENA_Pos) /*!< DWT CTRL: SLEEPEVTENA Mask */ #define DWT_CTRL_EXCEVTENA_Pos 18 /*!< DWT CTRL: EXCEVTENA Position */ #define DWT_CTRL_EXCEVTENA_Msk (0x1UL << DWT_CTRL_EXCEVTENA_Pos) /*!< DWT CTRL: EXCEVTENA Mask */ #define DWT_CTRL_CPIEVTENA_Pos 17 /*!< DWT CTRL: CPIEVTENA Position */ #define DWT_CTRL_CPIEVTENA_Msk (0x1UL << DWT_CTRL_CPIEVTENA_Pos) /*!< DWT CTRL: CPIEVTENA Mask */ #define DWT_CTRL_EXCTRCENA_Pos 16 /*!< DWT CTRL: EXCTRCENA Position */ #define DWT_CTRL_EXCTRCENA_Msk (0x1UL << DWT_CTRL_EXCTRCENA_Pos) /*!< DWT CTRL: EXCTRCENA Mask */ #define DWT_CTRL_PCSAMPLENA_Pos 12 /*!< DWT CTRL: PCSAMPLENA Position */ #define DWT_CTRL_PCSAMPLENA_Msk (0x1UL << DWT_CTRL_PCSAMPLENA_Pos) /*!< DWT CTRL: PCSAMPLENA Mask */ #define DWT_CTRL_SYNCTAP_Pos 10 /*!< DWT CTRL: SYNCTAP Position */ #define DWT_CTRL_SYNCTAP_Msk (0x3UL << DWT_CTRL_SYNCTAP_Pos) /*!< DWT CTRL: SYNCTAP Mask */ #define DWT_CTRL_CYCTAP_Pos 9 /*!< DWT CTRL: CYCTAP Position */ #define DWT_CTRL_CYCTAP_Msk (0x1UL << DWT_CTRL_CYCTAP_Pos) /*!< DWT CTRL: CYCTAP Mask */ #define DWT_CTRL_POSTINIT_Pos 5 /*!< DWT CTRL: POSTINIT Position */ #define DWT_CTRL_POSTINIT_Msk (0xFUL << DWT_CTRL_POSTINIT_Pos) /*!< DWT CTRL: POSTINIT Mask */ #define DWT_CTRL_POSTPRESET_Pos 1 /*!< DWT CTRL: POSTPRESET Position */ #define DWT_CTRL_POSTPRESET_Msk (0xFUL << DWT_CTRL_POSTPRESET_Pos) /*!< DWT CTRL: POSTPRESET Mask */ #define DWT_CTRL_CYCCNTENA_Pos 0 /*!< DWT CTRL: CYCCNTENA Position */ #define DWT_CTRL_CYCCNTENA_Msk (0x1UL /*<< DWT_CTRL_CYCCNTENA_Pos*/) /*!< DWT CTRL: CYCCNTENA Mask */ /* DWT CPI Count Register Definitions */ #define DWT_CPICNT_CPICNT_Pos 0 /*!< DWT CPICNT: CPICNT Position */ #define DWT_CPICNT_CPICNT_Msk (0xFFUL /*<< DWT_CPICNT_CPICNT_Pos*/) /*!< DWT CPICNT: CPICNT Mask */ /* DWT Exception Overhead Count Register Definitions */ #define DWT_EXCCNT_EXCCNT_Pos 0 /*!< DWT EXCCNT: EXCCNT Position */ #define DWT_EXCCNT_EXCCNT_Msk (0xFFUL /*<< DWT_EXCCNT_EXCCNT_Pos*/) /*!< DWT EXCCNT: EXCCNT Mask */ /* DWT Sleep Count Register Definitions */ #define DWT_SLEEPCNT_SLEEPCNT_Pos 0 /*!< DWT SLEEPCNT: SLEEPCNT Position */ #define DWT_SLEEPCNT_SLEEPCNT_Msk (0xFFUL /*<< DWT_SLEEPCNT_SLEEPCNT_Pos*/) /*!< DWT SLEEPCNT: SLEEPCNT Mask */ /* DWT LSU Count Register Definitions */ #define DWT_LSUCNT_LSUCNT_Pos 0 /*!< DWT LSUCNT: LSUCNT Position */ #define DWT_LSUCNT_LSUCNT_Msk (0xFFUL /*<< DWT_LSUCNT_LSUCNT_Pos*/) /*!< DWT LSUCNT: LSUCNT Mask */ /* DWT Folded-instruction Count Register Definitions */ #define DWT_FOLDCNT_FOLDCNT_Pos 0 /*!< DWT FOLDCNT: FOLDCNT Position */ #define DWT_FOLDCNT_FOLDCNT_Msk (0xFFUL /*<< DWT_FOLDCNT_FOLDCNT_Pos*/) /*!< DWT FOLDCNT: FOLDCNT Mask */ /* DWT Comparator Mask Register Definitions */ #define DWT_MASK_MASK_Pos 0 /*!< DWT MASK: MASK Position */ #define DWT_MASK_MASK_Msk (0x1FUL /*<< DWT_MASK_MASK_Pos*/) /*!< DWT MASK: MASK Mask */ /* DWT Comparator Function Register Definitions */ #define DWT_FUNCTION_MATCHED_Pos 24 /*!< DWT FUNCTION: MATCHED Position */ #define DWT_FUNCTION_MATCHED_Msk (0x1UL << DWT_FUNCTION_MATCHED_Pos) /*!< DWT FUNCTION: MATCHED Mask */ #define DWT_FUNCTION_DATAVADDR1_Pos 16 /*!< DWT FUNCTION: DATAVADDR1 Position */ #define DWT_FUNCTION_DATAVADDR1_Msk (0xFUL << DWT_FUNCTION_DATAVADDR1_Pos) /*!< DWT FUNCTION: DATAVADDR1 Mask */ #define DWT_FUNCTION_DATAVADDR0_Pos 12 /*!< DWT FUNCTION: DATAVADDR0 Position */ #define DWT_FUNCTION_DATAVADDR0_Msk (0xFUL << DWT_FUNCTION_DATAVADDR0_Pos) /*!< DWT FUNCTION: DATAVADDR0 Mask */ #define DWT_FUNCTION_DATAVSIZE_Pos 10 /*!< DWT FUNCTION: DATAVSIZE Position */ #define DWT_FUNCTION_DATAVSIZE_Msk (0x3UL << DWT_FUNCTION_DATAVSIZE_Pos) /*!< DWT FUNCTION: DATAVSIZE Mask */ #define DWT_FUNCTION_LNK1ENA_Pos 9 /*!< DWT FUNCTION: LNK1ENA Position */ #define DWT_FUNCTION_LNK1ENA_Msk (0x1UL << DWT_FUNCTION_LNK1ENA_Pos) /*!< DWT FUNCTION: LNK1ENA Mask */ #define DWT_FUNCTION_DATAVMATCH_Pos 8 /*!< DWT FUNCTION: DATAVMATCH Position */ #define DWT_FUNCTION_DATAVMATCH_Msk (0x1UL << DWT_FUNCTION_DATAVMATCH_Pos) /*!< DWT FUNCTION: DATAVMATCH Mask */ #define DWT_FUNCTION_CYCMATCH_Pos 7 /*!< DWT FUNCTION: CYCMATCH Position */ #define DWT_FUNCTION_CYCMATCH_Msk (0x1UL << DWT_FUNCTION_CYCMATCH_Pos) /*!< DWT FUNCTION: CYCMATCH Mask */ #define DWT_FUNCTION_EMITRANGE_Pos 5 /*!< DWT FUNCTION: EMITRANGE Position */ #define DWT_FUNCTION_EMITRANGE_Msk (0x1UL << DWT_FUNCTION_EMITRANGE_Pos) /*!< DWT FUNCTION: EMITRANGE Mask */ #define DWT_FUNCTION_FUNCTION_Pos 0 /*!< DWT FUNCTION: FUNCTION Position */ #define DWT_FUNCTION_FUNCTION_Msk (0xFUL /*<< DWT_FUNCTION_FUNCTION_Pos*/) /*!< DWT FUNCTION: FUNCTION Mask */ /*@}*/ /* end of group CMSIS_DWT */ /** \ingroup CMSIS_core_register \defgroup CMSIS_TPI Trace Port Interface (TPI) \brief Type definitions for the Trace Port Interface (TPI) @{ */ /** \brief Structure type to access the Trace Port Interface Register (TPI). */ typedef struct { __IO uint32_t SSPSR; /*!< Offset: 0x000 (R/ ) Supported Parallel Port Size Register */ __IO uint32_t CSPSR; /*!< Offset: 0x004 (R/W) Current Parallel Port Size Register */ uint32_t RESERVED0[2]; __IO uint32_t ACPR; /*!< Offset: 0x010 (R/W) Asynchronous Clock Prescaler Register */ uint32_t RESERVED1[55]; __IO uint32_t SPPR; /*!< Offset: 0x0F0 (R/W) Selected Pin Protocol Register */ uint32_t RESERVED2[131]; __I uint32_t FFSR; /*!< Offset: 0x300 (R/ ) Formatter and Flush Status Register */ __IO uint32_t FFCR; /*!< Offset: 0x304 (R/W) Formatter and Flush Control Register */ __I uint32_t FSCR; /*!< Offset: 0x308 (R/ ) Formatter Synchronization Counter Register */ uint32_t RESERVED3[759]; __I uint32_t TRIGGER; /*!< Offset: 0xEE8 (R/ ) TRIGGER */ __I uint32_t FIFO0; /*!< Offset: 0xEEC (R/ ) Integration ETM Data */ __I uint32_t ITATBCTR2; /*!< Offset: 0xEF0 (R/ ) ITATBCTR2 */ uint32_t RESERVED4[1]; __I uint32_t ITATBCTR0; /*!< Offset: 0xEF8 (R/ ) ITATBCTR0 */ __I uint32_t FIFO1; /*!< Offset: 0xEFC (R/ ) Integration ITM Data */ __IO uint32_t ITCTRL; /*!< Offset: 0xF00 (R/W) Integration Mode Control */ uint32_t RESERVED5[39]; __IO uint32_t CLAIMSET; /*!< Offset: 0xFA0 (R/W) Claim tag set */ __IO uint32_t CLAIMCLR; /*!< Offset: 0xFA4 (R/W) Claim tag clear */ uint32_t RESERVED7[8]; __I uint32_t DEVID; /*!< Offset: 0xFC8 (R/ ) TPIU_DEVID */ __I uint32_t DEVTYPE; /*!< Offset: 0xFCC (R/ ) TPIU_DEVTYPE */ } TPI_Type; /* TPI Asynchronous Clock Prescaler Register Definitions */ #define TPI_ACPR_PRESCALER_Pos 0 /*!< TPI ACPR: PRESCALER Position */ #define TPI_ACPR_PRESCALER_Msk (0x1FFFUL /*<< TPI_ACPR_PRESCALER_Pos*/) /*!< TPI ACPR: PRESCALER Mask */ /* TPI Selected Pin Protocol Register Definitions */ #define TPI_SPPR_TXMODE_Pos 0 /*!< TPI SPPR: TXMODE Position */ #define TPI_SPPR_TXMODE_Msk (0x3UL /*<< TPI_SPPR_TXMODE_Pos*/) /*!< TPI SPPR: TXMODE Mask */ /* TPI Formatter and Flush Status Register Definitions */ #define TPI_FFSR_FtNonStop_Pos 3 /*!< TPI FFSR: FtNonStop Position */ #define TPI_FFSR_FtNonStop_Msk (0x1UL << TPI_FFSR_FtNonStop_Pos) /*!< TPI FFSR: FtNonStop Mask */ #define TPI_FFSR_TCPresent_Pos 2 /*!< TPI FFSR: TCPresent Position */ #define TPI_FFSR_TCPresent_Msk (0x1UL << TPI_FFSR_TCPresent_Pos) /*!< TPI FFSR: TCPresent Mask */ #define TPI_FFSR_FtStopped_Pos 1 /*!< TPI FFSR: FtStopped Position */ #define TPI_FFSR_FtStopped_Msk (0x1UL << TPI_FFSR_FtStopped_Pos) /*!< TPI FFSR: FtStopped Mask */ #define TPI_FFSR_FlInProg_Pos 0 /*!< TPI FFSR: FlInProg Position */ #define TPI_FFSR_FlInProg_Msk (0x1UL /*<< TPI_FFSR_FlInProg_Pos*/) /*!< TPI FFSR: FlInProg Mask */ /* TPI Formatter and Flush Control Register Definitions */ #define TPI_FFCR_TrigIn_Pos 8 /*!< TPI FFCR: TrigIn Position */ #define TPI_FFCR_TrigIn_Msk (0x1UL << TPI_FFCR_TrigIn_Pos) /*!< TPI FFCR: TrigIn Mask */ #define TPI_FFCR_EnFCont_Pos 1 /*!< TPI FFCR: EnFCont Position */ #define TPI_FFCR_EnFCont_Msk (0x1UL << TPI_FFCR_EnFCont_Pos) /*!< TPI FFCR: EnFCont Mask */ /* TPI TRIGGER Register Definitions */ #define TPI_TRIGGER_TRIGGER_Pos 0 /*!< TPI TRIGGER: TRIGGER Position */ #define TPI_TRIGGER_TRIGGER_Msk (0x1UL /*<< TPI_TRIGGER_TRIGGER_Pos*/) /*!< TPI TRIGGER: TRIGGER Mask */ /* TPI Integration ETM Data Register Definitions (FIFO0) */ #define TPI_FIFO0_ITM_ATVALID_Pos 29 /*!< TPI FIFO0: ITM_ATVALID Position */ #define TPI_FIFO0_ITM_ATVALID_Msk (0x3UL << TPI_FIFO0_ITM_ATVALID_Pos) /*!< TPI FIFO0: ITM_ATVALID Mask */ #define TPI_FIFO0_ITM_bytecount_Pos 27 /*!< TPI FIFO0: ITM_bytecount Position */ #define TPI_FIFO0_ITM_bytecount_Msk (0x3UL << TPI_FIFO0_ITM_bytecount_Pos) /*!< TPI FIFO0: ITM_bytecount Mask */ #define TPI_FIFO0_ETM_ATVALID_Pos 26 /*!< TPI FIFO0: ETM_ATVALID Position */ #define TPI_FIFO0_ETM_ATVALID_Msk (0x3UL << TPI_FIFO0_ETM_ATVALID_Pos) /*!< TPI FIFO0: ETM_ATVALID Mask */ #define TPI_FIFO0_ETM_bytecount_Pos 24 /*!< TPI FIFO0: ETM_bytecount Position */ #define TPI_FIFO0_ETM_bytecount_Msk (0x3UL << TPI_FIFO0_ETM_bytecount_Pos) /*!< TPI FIFO0: ETM_bytecount Mask */ #define TPI_FIFO0_ETM2_Pos 16 /*!< TPI FIFO0: ETM2 Position */ #define TPI_FIFO0_ETM2_Msk (0xFFUL << TPI_FIFO0_ETM2_Pos) /*!< TPI FIFO0: ETM2 Mask */ #define TPI_FIFO0_ETM1_Pos 8 /*!< TPI FIFO0: ETM1 Position */ #define TPI_FIFO0_ETM1_Msk (0xFFUL << TPI_FIFO0_ETM1_Pos) /*!< TPI FIFO0: ETM1 Mask */ #define TPI_FIFO0_ETM0_Pos 0 /*!< TPI FIFO0: ETM0 Position */ #define TPI_FIFO0_ETM0_Msk (0xFFUL /*<< TPI_FIFO0_ETM0_Pos*/) /*!< TPI FIFO0: ETM0 Mask */ /* TPI ITATBCTR2 Register Definitions */ #define TPI_ITATBCTR2_ATREADY_Pos 0 /*!< TPI ITATBCTR2: ATREADY Position */ #define TPI_ITATBCTR2_ATREADY_Msk (0x1UL /*<< TPI_ITATBCTR2_ATREADY_Pos*/) /*!< TPI ITATBCTR2: ATREADY Mask */ /* TPI Integration ITM Data Register Definitions (FIFO1) */ #define TPI_FIFO1_ITM_ATVALID_Pos 29 /*!< TPI FIFO1: ITM_ATVALID Position */ #define TPI_FIFO1_ITM_ATVALID_Msk (0x3UL << TPI_FIFO1_ITM_ATVALID_Pos) /*!< TPI FIFO1: ITM_ATVALID Mask */ #define TPI_FIFO1_ITM_bytecount_Pos 27 /*!< TPI FIFO1: ITM_bytecount Position */ #define TPI_FIFO1_ITM_bytecount_Msk (0x3UL << TPI_FIFO1_ITM_bytecount_Pos) /*!< TPI FIFO1: ITM_bytecount Mask */ #define TPI_FIFO1_ETM_ATVALID_Pos 26 /*!< TPI FIFO1: ETM_ATVALID Position */ #define TPI_FIFO1_ETM_ATVALID_Msk (0x3UL << TPI_FIFO1_ETM_ATVALID_Pos) /*!< TPI FIFO1: ETM_ATVALID Mask */ #define TPI_FIFO1_ETM_bytecount_Pos 24 /*!< TPI FIFO1: ETM_bytecount Position */ #define TPI_FIFO1_ETM_bytecount_Msk (0x3UL << TPI_FIFO1_ETM_bytecount_Pos) /*!< TPI FIFO1: ETM_bytecount Mask */ #define TPI_FIFO1_ITM2_Pos 16 /*!< TPI FIFO1: ITM2 Position */ #define TPI_FIFO1_ITM2_Msk (0xFFUL << TPI_FIFO1_ITM2_Pos) /*!< TPI FIFO1: ITM2 Mask */ #define TPI_FIFO1_ITM1_Pos 8 /*!< TPI FIFO1: ITM1 Position */ #define TPI_FIFO1_ITM1_Msk (0xFFUL << TPI_FIFO1_ITM1_Pos) /*!< TPI FIFO1: ITM1 Mask */ #define TPI_FIFO1_ITM0_Pos 0 /*!< TPI FIFO1: ITM0 Position */ #define TPI_FIFO1_ITM0_Msk (0xFFUL /*<< TPI_FIFO1_ITM0_Pos*/) /*!< TPI FIFO1: ITM0 Mask */ /* TPI ITATBCTR0 Register Definitions */ #define TPI_ITATBCTR0_ATREADY_Pos 0 /*!< TPI ITATBCTR0: ATREADY Position */ #define TPI_ITATBCTR0_ATREADY_Msk (0x1UL /*<< TPI_ITATBCTR0_ATREADY_Pos*/) /*!< TPI ITATBCTR0: ATREADY Mask */ /* TPI Integration Mode Control Register Definitions */ #define TPI_ITCTRL_Mode_Pos 0 /*!< TPI ITCTRL: Mode Position */ #define TPI_ITCTRL_Mode_Msk (0x1UL /*<< TPI_ITCTRL_Mode_Pos*/) /*!< TPI ITCTRL: Mode Mask */ /* TPI DEVID Register Definitions */ #define TPI_DEVID_NRZVALID_Pos 11 /*!< TPI DEVID: NRZVALID Position */ #define TPI_DEVID_NRZVALID_Msk (0x1UL << TPI_DEVID_NRZVALID_Pos) /*!< TPI DEVID: NRZVALID Mask */ #define TPI_DEVID_MANCVALID_Pos 10 /*!< TPI DEVID: MANCVALID Position */ #define TPI_DEVID_MANCVALID_Msk (0x1UL << TPI_DEVID_MANCVALID_Pos) /*!< TPI DEVID: MANCVALID Mask */ #define TPI_DEVID_PTINVALID_Pos 9 /*!< TPI DEVID: PTINVALID Position */ #define TPI_DEVID_PTINVALID_Msk (0x1UL << TPI_DEVID_PTINVALID_Pos) /*!< TPI DEVID: PTINVALID Mask */ #define TPI_DEVID_MinBufSz_Pos 6 /*!< TPI DEVID: MinBufSz Position */ #define TPI_DEVID_MinBufSz_Msk (0x7UL << TPI_DEVID_MinBufSz_Pos) /*!< TPI DEVID: MinBufSz Mask */ #define TPI_DEVID_AsynClkIn_Pos 5 /*!< TPI DEVID: AsynClkIn Position */ #define TPI_DEVID_AsynClkIn_Msk (0x1UL << TPI_DEVID_AsynClkIn_Pos) /*!< TPI DEVID: AsynClkIn Mask */ #define TPI_DEVID_NrTraceInput_Pos 0 /*!< TPI DEVID: NrTraceInput Position */ #define TPI_DEVID_NrTraceInput_Msk (0x1FUL /*<< TPI_DEVID_NrTraceInput_Pos*/) /*!< TPI DEVID: NrTraceInput Mask */ /* TPI DEVTYPE Register Definitions */ #define TPI_DEVTYPE_MajorType_Pos 4 /*!< TPI DEVTYPE: MajorType Position */ #define TPI_DEVTYPE_MajorType_Msk (0xFUL << TPI_DEVTYPE_MajorType_Pos) /*!< TPI DEVTYPE: MajorType Mask */ #define TPI_DEVTYPE_SubType_Pos 0 /*!< TPI DEVTYPE: SubType Position */ #define TPI_DEVTYPE_SubType_Msk (0xFUL /*<< TPI_DEVTYPE_SubType_Pos*/) /*!< TPI DEVTYPE: SubType Mask */ /*@}*/ /* end of group CMSIS_TPI */ #if (__MPU_PRESENT == 1) /** \ingroup CMSIS_core_register \defgroup CMSIS_MPU Memory Protection Unit (MPU) \brief Type definitions for the Memory Protection Unit (MPU) @{ */ /** \brief Structure type to access the Memory Protection Unit (MPU). */ typedef struct { __I uint32_t TYPE; /*!< Offset: 0x000 (R/ ) MPU Type Register */ __IO uint32_t CTRL; /*!< Offset: 0x004 (R/W) MPU Control Register */ __IO uint32_t RNR; /*!< Offset: 0x008 (R/W) MPU Region RNRber Register */ __IO uint32_t RBAR; /*!< Offset: 0x00C (R/W) MPU Region Base Address Register */ __IO uint32_t RASR; /*!< Offset: 0x010 (R/W) MPU Region Attribute and Size Register */ __IO uint32_t RBAR_A1; /*!< Offset: 0x014 (R/W) MPU Alias 1 Region Base Address Register */ __IO uint32_t RASR_A1; /*!< Offset: 0x018 (R/W) MPU Alias 1 Region Attribute and Size Register */ __IO uint32_t RBAR_A2; /*!< Offset: 0x01C (R/W) MPU Alias 2 Region Base Address Register */ __IO uint32_t RASR_A2; /*!< Offset: 0x020 (R/W) MPU Alias 2 Region Attribute and Size Register */ __IO uint32_t RBAR_A3; /*!< Offset: 0x024 (R/W) MPU Alias 3 Region Base Address Register */ __IO uint32_t RASR_A3; /*!< Offset: 0x028 (R/W) MPU Alias 3 Region Attribute and Size Register */ } MPU_Type; /* MPU Type Register */ #define MPU_TYPE_IREGION_Pos 16 /*!< MPU TYPE: IREGION Position */ #define MPU_TYPE_IREGION_Msk (0xFFUL << MPU_TYPE_IREGION_Pos) /*!< MPU TYPE: IREGION Mask */ #define MPU_TYPE_DREGION_Pos 8 /*!< MPU TYPE: DREGION Position */ #define MPU_TYPE_DREGION_Msk (0xFFUL << MPU_TYPE_DREGION_Pos) /*!< MPU TYPE: DREGION Mask */ #define MPU_TYPE_SEPARATE_Pos 0 /*!< MPU TYPE: SEPARATE Position */ #define MPU_TYPE_SEPARATE_Msk (1UL /*<< MPU_TYPE_SEPARATE_Pos*/) /*!< MPU TYPE: SEPARATE Mask */ /* MPU Control Register */ #define MPU_CTRL_PRIVDEFENA_Pos 2 /*!< MPU CTRL: PRIVDEFENA Position */ #define MPU_CTRL_PRIVDEFENA_Msk (1UL << MPU_CTRL_PRIVDEFENA_Pos) /*!< MPU CTRL: PRIVDEFENA Mask */ #define MPU_CTRL_HFNMIENA_Pos 1 /*!< MPU CTRL: HFNMIENA Position */ #define MPU_CTRL_HFNMIENA_Msk (1UL << MPU_CTRL_HFNMIENA_Pos) /*!< MPU CTRL: HFNMIENA Mask */ #define MPU_CTRL_ENABLE_Pos 0 /*!< MPU CTRL: ENABLE Position */ #define MPU_CTRL_ENABLE_Msk (1UL /*<< MPU_CTRL_ENABLE_Pos*/) /*!< MPU CTRL: ENABLE Mask */ /* MPU Region Number Register */ #define MPU_RNR_REGION_Pos 0 /*!< MPU RNR: REGION Position */ #define MPU_RNR_REGION_Msk (0xFFUL /*<< MPU_RNR_REGION_Pos*/) /*!< MPU RNR: REGION Mask */ /* MPU Region Base Address Register */ #define MPU_RBAR_ADDR_Pos 5 /*!< MPU RBAR: ADDR Position */ #define MPU_RBAR_ADDR_Msk (0x7FFFFFFUL << MPU_RBAR_ADDR_Pos) /*!< MPU RBAR: ADDR Mask */ #define MPU_RBAR_VALID_Pos 4 /*!< MPU RBAR: VALID Position */ #define MPU_RBAR_VALID_Msk (1UL << MPU_RBAR_VALID_Pos) /*!< MPU RBAR: VALID Mask */ #define MPU_RBAR_REGION_Pos 0 /*!< MPU RBAR: REGION Position */ #define MPU_RBAR_REGION_Msk (0xFUL /*<< MPU_RBAR_REGION_Pos*/) /*!< MPU RBAR: REGION Mask */ /* MPU Region Attribute and Size Register */ #define MPU_RASR_ATTRS_Pos 16 /*!< MPU RASR: MPU Region Attribute field Position */ #define MPU_RASR_ATTRS_Msk (0xFFFFUL << MPU_RASR_ATTRS_Pos) /*!< MPU RASR: MPU Region Attribute field Mask */ #define MPU_RASR_XN_Pos 28 /*!< MPU RASR: ATTRS.XN Position */ #define MPU_RASR_XN_Msk (1UL << MPU_RASR_XN_Pos) /*!< MPU RASR: ATTRS.XN Mask */ #define MPU_RASR_AP_Pos 24 /*!< MPU RASR: ATTRS.AP Position */ #define MPU_RASR_AP_Msk (0x7UL << MPU_RASR_AP_Pos) /*!< MPU RASR: ATTRS.AP Mask */ #define MPU_RASR_TEX_Pos 19 /*!< MPU RASR: ATTRS.TEX Position */ #define MPU_RASR_TEX_Msk (0x7UL << MPU_RASR_TEX_Pos) /*!< MPU RASR: ATTRS.TEX Mask */ #define MPU_RASR_S_Pos 18 /*!< MPU RASR: ATTRS.S Position */ #define MPU_RASR_S_Msk (1UL << MPU_RASR_S_Pos) /*!< MPU RASR: ATTRS.S Mask */ #define MPU_RASR_C_Pos 17 /*!< MPU RASR: ATTRS.C Position */ #define MPU_RASR_C_Msk (1UL << MPU_RASR_C_Pos) /*!< MPU RASR: ATTRS.C Mask */ #define MPU_RASR_B_Pos 16 /*!< MPU RASR: ATTRS.B Position */ #define MPU_RASR_B_Msk (1UL << MPU_RASR_B_Pos) /*!< MPU RASR: ATTRS.B Mask */ #define MPU_RASR_SRD_Pos 8 /*!< MPU RASR: Sub-Region Disable Position */ #define MPU_RASR_SRD_Msk (0xFFUL << MPU_RASR_SRD_Pos) /*!< MPU RASR: Sub-Region Disable Mask */ #define MPU_RASR_SIZE_Pos 1 /*!< MPU RASR: Region Size Field Position */ #define MPU_RASR_SIZE_Msk (0x1FUL << MPU_RASR_SIZE_Pos) /*!< MPU RASR: Region Size Field Mask */ #define MPU_RASR_ENABLE_Pos 0 /*!< MPU RASR: Region enable bit Position */ #define MPU_RASR_ENABLE_Msk (1UL /*<< MPU_RASR_ENABLE_Pos*/) /*!< MPU RASR: Region enable bit Disable Mask */ /*@} end of group CMSIS_MPU */ #endif /** \ingroup CMSIS_core_register \defgroup CMSIS_CoreDebug Core Debug Registers (CoreDebug) \brief Type definitions for the Core Debug Registers @{ */ /** \brief Structure type to access the Core Debug Register (CoreDebug). */ typedef struct { __IO uint32_t DHCSR; /*!< Offset: 0x000 (R/W) Debug Halting Control and Status Register */ __O uint32_t DCRSR; /*!< Offset: 0x004 ( /W) Debug Core Register Selector Register */ __IO uint32_t DCRDR; /*!< Offset: 0x008 (R/W) Debug Core Register Data Register */ __IO uint32_t DEMCR; /*!< Offset: 0x00C (R/W) Debug Exception and Monitor Control Register */ } CoreDebug_Type; /* Debug Halting Control and Status Register */ #define CoreDebug_DHCSR_DBGKEY_Pos 16 /*!< CoreDebug DHCSR: DBGKEY Position */ #define CoreDebug_DHCSR_DBGKEY_Msk (0xFFFFUL << CoreDebug_DHCSR_DBGKEY_Pos) /*!< CoreDebug DHCSR: DBGKEY Mask */ #define CoreDebug_DHCSR_S_RESET_ST_Pos 25 /*!< CoreDebug DHCSR: S_RESET_ST Position */ #define CoreDebug_DHCSR_S_RESET_ST_Msk (1UL << CoreDebug_DHCSR_S_RESET_ST_Pos) /*!< CoreDebug DHCSR: S_RESET_ST Mask */ #define CoreDebug_DHCSR_S_RETIRE_ST_Pos 24 /*!< CoreDebug DHCSR: S_RETIRE_ST Position */ #define CoreDebug_DHCSR_S_RETIRE_ST_Msk (1UL << CoreDebug_DHCSR_S_RETIRE_ST_Pos) /*!< CoreDebug DHCSR: S_RETIRE_ST Mask */ #define CoreDebug_DHCSR_S_LOCKUP_Pos 19 /*!< CoreDebug DHCSR: S_LOCKUP Position */ #define CoreDebug_DHCSR_S_LOCKUP_Msk (1UL << CoreDebug_DHCSR_S_LOCKUP_Pos) /*!< CoreDebug DHCSR: S_LOCKUP Mask */ #define CoreDebug_DHCSR_S_SLEEP_Pos 18 /*!< CoreDebug DHCSR: S_SLEEP Position */ #define CoreDebug_DHCSR_S_SLEEP_Msk (1UL << CoreDebug_DHCSR_S_SLEEP_Pos) /*!< CoreDebug DHCSR: S_SLEEP Mask */ #define CoreDebug_DHCSR_S_HALT_Pos 17 /*!< CoreDebug DHCSR: S_HALT Position */ #define CoreDebug_DHCSR_S_HALT_Msk (1UL << CoreDebug_DHCSR_S_HALT_Pos) /*!< CoreDebug DHCSR: S_HALT Mask */ #define CoreDebug_DHCSR_S_REGRDY_Pos 16 /*!< CoreDebug DHCSR: S_REGRDY Position */ #define CoreDebug_DHCSR_S_REGRDY_Msk (1UL << CoreDebug_DHCSR_S_REGRDY_Pos) /*!< CoreDebug DHCSR: S_REGRDY Mask */ #define CoreDebug_DHCSR_C_SNAPSTALL_Pos 5 /*!< CoreDebug DHCSR: C_SNAPSTALL Position */ #define CoreDebug_DHCSR_C_SNAPSTALL_Msk (1UL << CoreDebug_DHCSR_C_SNAPSTALL_Pos) /*!< CoreDebug DHCSR: C_SNAPSTALL Mask */ #define CoreDebug_DHCSR_C_MASKINTS_Pos 3 /*!< CoreDebug DHCSR: C_MASKINTS Position */ #define CoreDebug_DHCSR_C_MASKINTS_Msk (1UL << CoreDebug_DHCSR_C_MASKINTS_Pos) /*!< CoreDebug DHCSR: C_MASKINTS Mask */ #define CoreDebug_DHCSR_C_STEP_Pos 2 /*!< CoreDebug DHCSR: C_STEP Position */ #define CoreDebug_DHCSR_C_STEP_Msk (1UL << CoreDebug_DHCSR_C_STEP_Pos) /*!< CoreDebug DHCSR: C_STEP Mask */ #define CoreDebug_DHCSR_C_HALT_Pos 1 /*!< CoreDebug DHCSR: C_HALT Position */ #define CoreDebug_DHCSR_C_HALT_Msk (1UL << CoreDebug_DHCSR_C_HALT_Pos) /*!< CoreDebug DHCSR: C_HALT Mask */ #define CoreDebug_DHCSR_C_DEBUGEN_Pos 0 /*!< CoreDebug DHCSR: C_DEBUGEN Position */ #define CoreDebug_DHCSR_C_DEBUGEN_Msk (1UL /*<< CoreDebug_DHCSR_C_DEBUGEN_Pos*/) /*!< CoreDebug DHCSR: C_DEBUGEN Mask */ /* Debug Core Register Selector Register */ #define CoreDebug_DCRSR_REGWnR_Pos 16 /*!< CoreDebug DCRSR: REGWnR Position */ #define CoreDebug_DCRSR_REGWnR_Msk (1UL << CoreDebug_DCRSR_REGWnR_Pos) /*!< CoreDebug DCRSR: REGWnR Mask */ #define CoreDebug_DCRSR_REGSEL_Pos 0 /*!< CoreDebug DCRSR: REGSEL Position */ #define CoreDebug_DCRSR_REGSEL_Msk (0x1FUL /*<< CoreDebug_DCRSR_REGSEL_Pos*/) /*!< CoreDebug DCRSR: REGSEL Mask */ /* Debug Exception and Monitor Control Register */ #define CoreDebug_DEMCR_TRCENA_Pos 24 /*!< CoreDebug DEMCR: TRCENA Position */ #define CoreDebug_DEMCR_TRCENA_Msk (1UL << CoreDebug_DEMCR_TRCENA_Pos) /*!< CoreDebug DEMCR: TRCENA Mask */ #define CoreDebug_DEMCR_MON_REQ_Pos 19 /*!< CoreDebug DEMCR: MON_REQ Position */ #define CoreDebug_DEMCR_MON_REQ_Msk (1UL << CoreDebug_DEMCR_MON_REQ_Pos) /*!< CoreDebug DEMCR: MON_REQ Mask */ #define CoreDebug_DEMCR_MON_STEP_Pos 18 /*!< CoreDebug DEMCR: MON_STEP Position */ #define CoreDebug_DEMCR_MON_STEP_Msk (1UL << CoreDebug_DEMCR_MON_STEP_Pos) /*!< CoreDebug DEMCR: MON_STEP Mask */ #define CoreDebug_DEMCR_MON_PEND_Pos 17 /*!< CoreDebug DEMCR: MON_PEND Position */ #define CoreDebug_DEMCR_MON_PEND_Msk (1UL << CoreDebug_DEMCR_MON_PEND_Pos) /*!< CoreDebug DEMCR: MON_PEND Mask */ #define CoreDebug_DEMCR_MON_EN_Pos 16 /*!< CoreDebug DEMCR: MON_EN Position */ #define CoreDebug_DEMCR_MON_EN_Msk (1UL << CoreDebug_DEMCR_MON_EN_Pos) /*!< CoreDebug DEMCR: MON_EN Mask */ #define CoreDebug_DEMCR_VC_HARDERR_Pos 10 /*!< CoreDebug DEMCR: VC_HARDERR Position */ #define CoreDebug_DEMCR_VC_HARDERR_Msk (1UL << CoreDebug_DEMCR_VC_HARDERR_Pos) /*!< CoreDebug DEMCR: VC_HARDERR Mask */ #define CoreDebug_DEMCR_VC_INTERR_Pos 9 /*!< CoreDebug DEMCR: VC_INTERR Position */ #define CoreDebug_DEMCR_VC_INTERR_Msk (1UL << CoreDebug_DEMCR_VC_INTERR_Pos) /*!< CoreDebug DEMCR: VC_INTERR Mask */ #define CoreDebug_DEMCR_VC_BUSERR_Pos 8 /*!< CoreDebug DEMCR: VC_BUSERR Position */ #define CoreDebug_DEMCR_VC_BUSERR_Msk (1UL << CoreDebug_DEMCR_VC_BUSERR_Pos) /*!< CoreDebug DEMCR: VC_BUSERR Mask */ #define CoreDebug_DEMCR_VC_STATERR_Pos 7 /*!< CoreDebug DEMCR: VC_STATERR Position */ #define CoreDebug_DEMCR_VC_STATERR_Msk (1UL << CoreDebug_DEMCR_VC_STATERR_Pos) /*!< CoreDebug DEMCR: VC_STATERR Mask */ #define CoreDebug_DEMCR_VC_CHKERR_Pos 6 /*!< CoreDebug DEMCR: VC_CHKERR Position */ #define CoreDebug_DEMCR_VC_CHKERR_Msk (1UL << CoreDebug_DEMCR_VC_CHKERR_Pos) /*!< CoreDebug DEMCR: VC_CHKERR Mask */ #define CoreDebug_DEMCR_VC_NOCPERR_Pos 5 /*!< CoreDebug DEMCR: VC_NOCPERR Position */ #define CoreDebug_DEMCR_VC_NOCPERR_Msk (1UL << CoreDebug_DEMCR_VC_NOCPERR_Pos) /*!< CoreDebug DEMCR: VC_NOCPERR Mask */ #define CoreDebug_DEMCR_VC_MMERR_Pos 4 /*!< CoreDebug DEMCR: VC_MMERR Position */ #define CoreDebug_DEMCR_VC_MMERR_Msk (1UL << CoreDebug_DEMCR_VC_MMERR_Pos) /*!< CoreDebug DEMCR: VC_MMERR Mask */ #define CoreDebug_DEMCR_VC_CORERESET_Pos 0 /*!< CoreDebug DEMCR: VC_CORERESET Position */ #define CoreDebug_DEMCR_VC_CORERESET_Msk (1UL /*<< CoreDebug_DEMCR_VC_CORERESET_Pos*/) /*!< CoreDebug DEMCR: VC_CORERESET Mask */ /*@} end of group CMSIS_CoreDebug */ /** \ingroup CMSIS_core_register \defgroup CMSIS_core_base Core Definitions \brief Definitions for base addresses, unions, and structures. @{ */ /* Memory mapping of Cortex-M3 Hardware */ #define SCS_BASE (0xE000E000UL) /*!< System Control Space Base Address */ #define ITM_BASE (0xE0000000UL) /*!< ITM Base Address */ #define DWT_BASE (0xE0001000UL) /*!< DWT Base Address */ #define TPI_BASE (0xE0040000UL) /*!< TPI Base Address */ #define CoreDebug_BASE (0xE000EDF0UL) /*!< Core Debug Base Address */ #define SysTick_BASE (SCS_BASE + 0x0010UL) /*!< SysTick Base Address */ #define NVIC_BASE (SCS_BASE + 0x0100UL) /*!< NVIC Base Address */ #define SCB_BASE (SCS_BASE + 0x0D00UL) /*!< System Control Block Base Address */ #define SCnSCB ((SCnSCB_Type *) SCS_BASE ) /*!< System control Register not in SCB */ #define SCB ((SCB_Type *) SCB_BASE ) /*!< SCB configuration struct */ #define SysTick ((SysTick_Type *) SysTick_BASE ) /*!< SysTick configuration struct */ #define NVIC ((NVIC_Type *) NVIC_BASE ) /*!< NVIC configuration struct */ #define ITM ((ITM_Type *) ITM_BASE ) /*!< ITM configuration struct */ #define DWT ((DWT_Type *) DWT_BASE ) /*!< DWT configuration struct */ #define TPI ((TPI_Type *) TPI_BASE ) /*!< TPI configuration struct */ #define CoreDebug ((CoreDebug_Type *) CoreDebug_BASE) /*!< Core Debug configuration struct */ #if (__MPU_PRESENT == 1) #define MPU_BASE (SCS_BASE + 0x0D90UL) /*!< Memory Protection Unit */ #define MPU ((MPU_Type *) MPU_BASE ) /*!< Memory Protection Unit */ #endif /*@} */ /******************************************************************************* * Hardware Abstraction Layer Core Function Interface contains: - Core NVIC Functions - Core SysTick Functions - Core Debug Functions - Core Register Access Functions ******************************************************************************/ /** \defgroup CMSIS_Core_FunctionInterface Functions and Instructions Reference */ /* ########################## NVIC functions #################################### */ /** \ingroup CMSIS_Core_FunctionInterface \defgroup CMSIS_Core_NVICFunctions NVIC Functions \brief Functions that manage interrupts and exceptions via the NVIC. @{ */ /** \brief Set Priority Grouping The function sets the priority grouping field using the required unlock sequence. The parameter PriorityGroup is assigned to the field SCB->AIRCR [10:8] PRIGROUP field. Only values from 0..7 are used. In case of a conflict between priority grouping and available priority bits (__NVIC_PRIO_BITS), the smallest possible priority group is set. \param [in] PriorityGroup Priority grouping field. */ __STATIC_INLINE void NVIC_SetPriorityGrouping(uint32_t PriorityGroup) { uint32_t reg_value; uint32_t PriorityGroupTmp = (PriorityGroup & (uint32_t)0x07UL); /* only values 0..7 are used */ reg_value = SCB->AIRCR; /* read old register configuration */ reg_value &= ~((uint32_t)(SCB_AIRCR_VECTKEY_Msk | SCB_AIRCR_PRIGROUP_Msk)); /* clear bits to change */ reg_value = (reg_value | ((uint32_t)0x5FAUL << SCB_AIRCR_VECTKEY_Pos) | (PriorityGroupTmp << 8) ); /* Insert write key and priorty group */ SCB->AIRCR = reg_value; } /** \brief Get Priority Grouping The function reads the priority grouping field from the NVIC Interrupt Controller. \return Priority grouping field (SCB->AIRCR [10:8] PRIGROUP field). */ __STATIC_INLINE uint32_t NVIC_GetPriorityGrouping(void) { return ((uint32_t)((SCB->AIRCR & SCB_AIRCR_PRIGROUP_Msk) >> SCB_AIRCR_PRIGROUP_Pos)); } /** \brief Enable External Interrupt The function enables a device-specific interrupt in the NVIC interrupt controller. \param [in] IRQn External interrupt number. Value cannot be negative. */ __STATIC_INLINE void NVIC_EnableIRQ(IRQn_Type IRQn) { NVIC->ISER[(((uint32_t)(int32_t)IRQn) >> 5UL)] = (uint32_t)(1UL << (((uint32_t)(int32_t)IRQn) & 0x1FUL)); } /** \brief Disable External Interrupt The function disables a device-specific interrupt in the NVIC interrupt controller. \param [in] IRQn External interrupt number. Value cannot be negative. */ __STATIC_INLINE void NVIC_DisableIRQ(IRQn_Type IRQn) { NVIC->ICER[(((uint32_t)(int32_t)IRQn) >> 5UL)] = (uint32_t)(1UL << (((uint32_t)(int32_t)IRQn) & 0x1FUL)); } /** \brief Get Pending Interrupt The function reads the pending register in the NVIC and returns the pending bit for the specified interrupt. \param [in] IRQn Interrupt number. \return 0 Interrupt status is not pending. \return 1 Interrupt status is pending. */ __STATIC_INLINE uint32_t NVIC_GetPendingIRQ(IRQn_Type IRQn) { return((uint32_t)(((NVIC->ISPR[(((uint32_t)(int32_t)IRQn) >> 5UL)] & (1UL << (((uint32_t)(int32_t)IRQn) & 0x1FUL))) != 0UL) ? 1UL : 0UL)); } /** \brief Set Pending Interrupt The function sets the pending bit of an external interrupt. \param [in] IRQn Interrupt number. Value cannot be negative. */ __STATIC_INLINE void NVIC_SetPendingIRQ(IRQn_Type IRQn) { NVIC->ISPR[(((uint32_t)(int32_t)IRQn) >> 5UL)] = (uint32_t)(1UL << (((uint32_t)(int32_t)IRQn) & 0x1FUL)); } /** \brief Clear Pending Interrupt The function clears the pending bit of an external interrupt. \param [in] IRQn External interrupt number. Value cannot be negative. */ __STATIC_INLINE void NVIC_ClearPendingIRQ(IRQn_Type IRQn) { NVIC->ICPR[(((uint32_t)(int32_t)IRQn) >> 5UL)] = (uint32_t)(1UL << (((uint32_t)(int32_t)IRQn) & 0x1FUL)); } /** \brief Get Active Interrupt The function reads the active register in NVIC and returns the active bit. \param [in] IRQn Interrupt number. \return 0 Interrupt status is not active. \return 1 Interrupt status is active. */ __STATIC_INLINE uint32_t NVIC_GetActive(IRQn_Type IRQn) { return((uint32_t)(((NVIC->IABR[(((uint32_t)(int32_t)IRQn) >> 5UL)] & (1UL << (((uint32_t)(int32_t)IRQn) & 0x1FUL))) != 0UL) ? 1UL : 0UL)); } /** \brief Set Interrupt Priority The function sets the priority of an interrupt. \note The priority cannot be set for every core interrupt. \param [in] IRQn Interrupt number. \param [in] priority Priority to set. */ __STATIC_INLINE void NVIC_SetPriority(IRQn_Type IRQn, uint32_t priority) { if((int32_t)IRQn < 0) { SCB->SHP[(((uint32_t)(int32_t)IRQn) & 0xFUL)-4UL] = (uint8_t)((priority << (8 - __NVIC_PRIO_BITS)) & (uint32_t)0xFFUL); } else { NVIC->IP[((uint32_t)(int32_t)IRQn)] = (uint8_t)((priority << (8 - __NVIC_PRIO_BITS)) & (uint32_t)0xFFUL); } } /** \brief Get Interrupt Priority The function reads the priority of an interrupt. The interrupt number can be positive to specify an external (device specific) interrupt, or negative to specify an internal (core) interrupt. \param [in] IRQn Interrupt number. \return Interrupt Priority. Value is aligned automatically to the implemented priority bits of the microcontroller. */ __STATIC_INLINE uint32_t NVIC_GetPriority(IRQn_Type IRQn) { if((int32_t)IRQn < 0) { return(((uint32_t)SCB->SHP[(((uint32_t)(int32_t)IRQn) & 0xFUL)-4UL] >> (8 - __NVIC_PRIO_BITS))); } else { return(((uint32_t)NVIC->IP[((uint32_t)(int32_t)IRQn)] >> (8 - __NVIC_PRIO_BITS))); } } /** \brief Encode Priority The function encodes the priority for an interrupt with the given priority group, preemptive priority value, and subpriority value. In case of a conflict between priority grouping and available priority bits (__NVIC_PRIO_BITS), the smallest possible priority group is set. \param [in] PriorityGroup Used priority group. \param [in] PreemptPriority Preemptive priority value (starting from 0). \param [in] SubPriority Subpriority value (starting from 0). \return Encoded priority. Value can be used in the function \ref NVIC_SetPriority(). */ __STATIC_INLINE uint32_t NVIC_EncodePriority (uint32_t PriorityGroup, uint32_t PreemptPriority, uint32_t SubPriority) { uint32_t PriorityGroupTmp = (PriorityGroup & (uint32_t)0x07UL); /* only values 0..7 are used */ uint32_t PreemptPriorityBits; uint32_t SubPriorityBits; PreemptPriorityBits = ((7UL - PriorityGroupTmp) > (uint32_t)(__NVIC_PRIO_BITS)) ? (uint32_t)(__NVIC_PRIO_BITS) : (uint32_t)(7UL - PriorityGroupTmp); SubPriorityBits = ((PriorityGroupTmp + (uint32_t)(__NVIC_PRIO_BITS)) < (uint32_t)7UL) ? (uint32_t)0UL : (uint32_t)((PriorityGroupTmp - 7UL) + (uint32_t)(__NVIC_PRIO_BITS)); return ( ((PreemptPriority & (uint32_t)((1UL << (PreemptPriorityBits)) - 1UL)) << SubPriorityBits) | ((SubPriority & (uint32_t)((1UL << (SubPriorityBits )) - 1UL))) ); } /** \brief Decode Priority The function decodes an interrupt priority value with a given priority group to preemptive priority value and subpriority value. In case of a conflict between priority grouping and available priority bits (__NVIC_PRIO_BITS) the smallest possible priority group is set. \param [in] Priority Priority value, which can be retrieved with the function \ref NVIC_GetPriority(). \param [in] PriorityGroup Used priority group. \param [out] pPreemptPriority Preemptive priority value (starting from 0). \param [out] pSubPriority Subpriority value (starting from 0). */ __STATIC_INLINE void NVIC_DecodePriority (uint32_t Priority, uint32_t PriorityGroup, uint32_t* pPreemptPriority, uint32_t* pSubPriority) { uint32_t PriorityGroupTmp = (PriorityGroup & (uint32_t)0x07UL); /* only values 0..7 are used */ uint32_t PreemptPriorityBits; uint32_t SubPriorityBits; PreemptPriorityBits = ((7UL - PriorityGroupTmp) > (uint32_t)(__NVIC_PRIO_BITS)) ? (uint32_t)(__NVIC_PRIO_BITS) : (uint32_t)(7UL - PriorityGroupTmp); SubPriorityBits = ((PriorityGroupTmp + (uint32_t)(__NVIC_PRIO_BITS)) < (uint32_t)7UL) ? (uint32_t)0UL : (uint32_t)((PriorityGroupTmp - 7UL) + (uint32_t)(__NVIC_PRIO_BITS)); *pPreemptPriority = (Priority >> SubPriorityBits) & (uint32_t)((1UL << (PreemptPriorityBits)) - 1UL); *pSubPriority = (Priority ) & (uint32_t)((1UL << (SubPriorityBits )) - 1UL); } /** \brief System Reset The function initiates a system reset request to reset the MCU. */ __STATIC_INLINE void NVIC_SystemReset(void) { __DSB(); /* Ensure all outstanding memory accesses included buffered write are completed before reset */ SCB->AIRCR = (uint32_t)((0x5FAUL << SCB_AIRCR_VECTKEY_Pos) | (SCB->AIRCR & SCB_AIRCR_PRIGROUP_Msk) | SCB_AIRCR_SYSRESETREQ_Msk ); /* Keep priority group unchanged */ __DSB(); /* Ensure completion of memory access */ while(1) { __NOP(); } /* wait until reset */ } /*@} end of CMSIS_Core_NVICFunctions */ /* ################################## SysTick function ############################################ */ /** \ingroup CMSIS_Core_FunctionInterface \defgroup CMSIS_Core_SysTickFunctions SysTick Functions \brief Functions that configure the System. @{ */ #if (__Vendor_SysTickConfig == 0) /** \brief System Tick Configuration The function initializes the System Timer and its interrupt, and starts the System Tick Timer. Counter is in free running mode to generate periodic interrupts. \param [in] ticks Number of ticks between two interrupts. \return 0 Function succeeded. \return 1 Function failed. \note When the variable __Vendor_SysTickConfig is set to 1, then the function SysTick_Config is not included. In this case, the file device.h must contain a vendor-specific implementation of this function. */ __STATIC_INLINE uint32_t SysTick_Config(uint32_t ticks) { if ((ticks - 1UL) > SysTick_LOAD_RELOAD_Msk) { return (1UL); } /* Reload value impossible */ SysTick->LOAD = (uint32_t)(ticks - 1UL); /* set reload register */ NVIC_SetPriority (SysTick_IRQn, (1UL << __NVIC_PRIO_BITS) - 1UL); /* set Priority for Systick Interrupt */ SysTick->VAL = 0UL; /* Load the SysTick Counter Value */ SysTick->CTRL = SysTick_CTRL_CLKSOURCE_Msk | SysTick_CTRL_TICKINT_Msk | SysTick_CTRL_ENABLE_Msk; /* Enable SysTick IRQ and SysTick Timer */ return (0UL); /* Function successful */ } #endif /*@} end of CMSIS_Core_SysTickFunctions */ /* ##################################### Debug In/Output function ########################################### */ /** \ingroup CMSIS_Core_FunctionInterface \defgroup CMSIS_core_DebugFunctions ITM Functions \brief Functions that access the ITM debug interface. @{ */ extern volatile int32_t ITM_RxBuffer; /*!< External variable to receive characters. */ #define ITM_RXBUFFER_EMPTY 0x5AA55AA5 /*!< Value identifying \ref ITM_RxBuffer is ready for next character. */ /** \brief ITM Send Character The function transmits a character via the ITM channel 0, and \li Just returns when no debugger is connected that has booked the output. \li Is blocking when a debugger is connected, but the previous character sent has not been transmitted. \param [in] ch Character to transmit. \returns Character to transmit. */ __STATIC_INLINE uint32_t ITM_SendChar (uint32_t ch) { if (((ITM->TCR & ITM_TCR_ITMENA_Msk) != 0UL) && /* ITM enabled */ ((ITM->TER & 1UL ) != 0UL) ) /* ITM Port #0 enabled */ { while (ITM->PORT[0].u32 == 0UL) { __NOP(); } ITM->PORT[0].u8 = (uint8_t)ch; } return (ch); } /** \brief ITM Receive Character The function inputs a character via the external variable \ref ITM_RxBuffer. \return Received character. \return -1 No character pending. */ __STATIC_INLINE int32_t ITM_ReceiveChar (void) { int32_t ch = -1; /* no character available */ if (ITM_RxBuffer != ITM_RXBUFFER_EMPTY) { ch = ITM_RxBuffer; ITM_RxBuffer = ITM_RXBUFFER_EMPTY; /* ready for next character */ } return (ch); } /** \brief ITM Check Character The function checks whether a character is pending for reading in the variable \ref ITM_RxBuffer. \return 0 No character available. \return 1 Character available. */ __STATIC_INLINE int32_t ITM_CheckChar (void) { if (ITM_RxBuffer == ITM_RXBUFFER_EMPTY) { return (0); /* no character available */ } else { return (1); /* character available */ } } /*@} end of CMSIS_core_DebugFunctions */ #ifdef __cplusplus } #endif #endif /* __CORE_CM3_H_DEPENDANT */ #endif /* __CMSIS_GENERIC */ ================================================ FILE: Zelig/mbed/TARGET_NUCLEO_F091RC/core_cm4.h ================================================ /**************************************************************************//** * @file core_cm4.h * @brief CMSIS Cortex-M4 Core Peripheral Access Layer Header File * @version V4.10 * @date 18. March 2015 * * @note * ******************************************************************************/ /* Copyright (c) 2009 - 2015 ARM LIMITED All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: - Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. - Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. - Neither the name of ARM 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 COPYRIGHT HOLDERS AND 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. ---------------------------------------------------------------------------*/ #if defined ( __ICCARM__ ) #pragma system_include /* treat file as system include file for MISRA check */ #endif #ifndef __CORE_CM4_H_GENERIC #define __CORE_CM4_H_GENERIC #ifdef __cplusplus extern "C" { #endif /** \page CMSIS_MISRA_Exceptions MISRA-C:2004 Compliance Exceptions CMSIS violates the following MISRA-C:2004 rules: \li Required Rule 8.5, object/function definition in header file.
Function definitions in header files are used to allow 'inlining'. \li Required Rule 18.4, declaration of union type or object of union type: '{...}'.
Unions are used for effective representation of core registers. \li Advisory Rule 19.7, Function-like macro defined.
Function-like macros are used to allow more efficient code. */ /******************************************************************************* * CMSIS definitions ******************************************************************************/ /** \ingroup Cortex_M4 @{ */ /* CMSIS CM4 definitions */ #define __CM4_CMSIS_VERSION_MAIN (0x04) /*!< [31:16] CMSIS HAL main version */ #define __CM4_CMSIS_VERSION_SUB (0x00) /*!< [15:0] CMSIS HAL sub version */ #define __CM4_CMSIS_VERSION ((__CM4_CMSIS_VERSION_MAIN << 16) | \ __CM4_CMSIS_VERSION_SUB ) /*!< CMSIS HAL version number */ #define __CORTEX_M (0x04) /*!< Cortex-M Core */ #if defined ( __CC_ARM ) #define __ASM __asm /*!< asm keyword for ARM Compiler */ #define __INLINE __inline /*!< inline keyword for ARM Compiler */ #define __STATIC_INLINE static __inline #elif defined ( __GNUC__ ) #define __ASM __asm /*!< asm keyword for GNU Compiler */ #define __INLINE inline /*!< inline keyword for GNU Compiler */ #define __STATIC_INLINE static inline #elif defined ( __ICCARM__ ) #define __ASM __asm /*!< asm keyword for IAR Compiler */ #define __INLINE inline /*!< inline keyword for IAR Compiler. Only available in High optimization mode! */ #define __STATIC_INLINE static inline #elif defined ( __TMS470__ ) #define __ASM __asm /*!< asm keyword for TI CCS Compiler */ #define __STATIC_INLINE static inline #elif defined ( __TASKING__ ) #define __ASM __asm /*!< asm keyword for TASKING Compiler */ #define __INLINE inline /*!< inline keyword for TASKING Compiler */ #define __STATIC_INLINE static inline #elif defined ( __CSMC__ ) #define __packed #define __ASM _asm /*!< asm keyword for COSMIC Compiler */ #define __INLINE inline /*use -pc99 on compile line !< inline keyword for COSMIC Compiler */ #define __STATIC_INLINE static inline #endif /** __FPU_USED indicates whether an FPU is used or not. For this, __FPU_PRESENT has to be checked prior to making use of FPU specific registers and functions. */ #if defined ( __CC_ARM ) #if defined __TARGET_FPU_VFP #if (__FPU_PRESENT == 1) #define __FPU_USED 1 #else #warning "Compiler generates FPU instructions for a device without an FPU (check __FPU_PRESENT)" #define __FPU_USED 0 #endif #else #define __FPU_USED 0 #endif #elif defined ( __GNUC__ ) #if defined (__VFP_FP__) && !defined(__SOFTFP__) #if (__FPU_PRESENT == 1) #define __FPU_USED 1 #else #warning "Compiler generates FPU instructions for a device without an FPU (check __FPU_PRESENT)" #define __FPU_USED 0 #endif #else #define __FPU_USED 0 #endif #elif defined ( __ICCARM__ ) #if defined __ARMVFP__ #if (__FPU_PRESENT == 1) #define __FPU_USED 1 #else #warning "Compiler generates FPU instructions for a device without an FPU (check __FPU_PRESENT)" #define __FPU_USED 0 #endif #else #define __FPU_USED 0 #endif #elif defined ( __TMS470__ ) #if defined __TI_VFP_SUPPORT__ #if (__FPU_PRESENT == 1) #define __FPU_USED 1 #else #warning "Compiler generates FPU instructions for a device without an FPU (check __FPU_PRESENT)" #define __FPU_USED 0 #endif #else #define __FPU_USED 0 #endif #elif defined ( __TASKING__ ) #if defined __FPU_VFP__ #if (__FPU_PRESENT == 1) #define __FPU_USED 1 #else #error "Compiler generates FPU instructions for a device without an FPU (check __FPU_PRESENT)" #define __FPU_USED 0 #endif #else #define __FPU_USED 0 #endif #elif defined ( __CSMC__ ) /* Cosmic */ #if ( __CSMC__ & 0x400) // FPU present for parser #if (__FPU_PRESENT == 1) #define __FPU_USED 1 #else #error "Compiler generates FPU instructions for a device without an FPU (check __FPU_PRESENT)" #define __FPU_USED 0 #endif #else #define __FPU_USED 0 #endif #endif #include /* standard types definitions */ #include /* Core Instruction Access */ #include /* Core Function Access */ #include /* Compiler specific SIMD Intrinsics */ #ifdef __cplusplus } #endif #endif /* __CORE_CM4_H_GENERIC */ #ifndef __CMSIS_GENERIC #ifndef __CORE_CM4_H_DEPENDANT #define __CORE_CM4_H_DEPENDANT #ifdef __cplusplus extern "C" { #endif /* check device defines and use defaults */ #if defined __CHECK_DEVICE_DEFINES #ifndef __CM4_REV #define __CM4_REV 0x0000 #warning "__CM4_REV not defined in device header file; using default!" #endif #ifndef __FPU_PRESENT #define __FPU_PRESENT 0 #warning "__FPU_PRESENT not defined in device header file; using default!" #endif #ifndef __MPU_PRESENT #define __MPU_PRESENT 0 #warning "__MPU_PRESENT not defined in device header file; using default!" #endif #ifndef __NVIC_PRIO_BITS #define __NVIC_PRIO_BITS 4 #warning "__NVIC_PRIO_BITS not defined in device header file; using default!" #endif #ifndef __Vendor_SysTickConfig #define __Vendor_SysTickConfig 0 #warning "__Vendor_SysTickConfig not defined in device header file; using default!" #endif #endif /* IO definitions (access restrictions to peripheral registers) */ /** \defgroup CMSIS_glob_defs CMSIS Global Defines IO Type Qualifiers are used \li to specify the access to peripheral variables. \li for automatic generation of peripheral register debug information. */ #ifdef __cplusplus #define __I volatile /*!< Defines 'read only' permissions */ #else #define __I volatile const /*!< Defines 'read only' permissions */ #endif #define __O volatile /*!< Defines 'write only' permissions */ #define __IO volatile /*!< Defines 'read / write' permissions */ /*@} end of group Cortex_M4 */ /******************************************************************************* * Register Abstraction Core Register contain: - Core Register - Core NVIC Register - Core SCB Register - Core SysTick Register - Core Debug Register - Core MPU Register - Core FPU Register ******************************************************************************/ /** \defgroup CMSIS_core_register Defines and Type Definitions \brief Type definitions and defines for Cortex-M processor based devices. */ /** \ingroup CMSIS_core_register \defgroup CMSIS_CORE Status and Control Registers \brief Core Register type definitions. @{ */ /** \brief Union type to access the Application Program Status Register (APSR). */ typedef union { struct { uint32_t _reserved0:16; /*!< bit: 0..15 Reserved */ uint32_t GE:4; /*!< bit: 16..19 Greater than or Equal flags */ uint32_t _reserved1:7; /*!< bit: 20..26 Reserved */ uint32_t Q:1; /*!< bit: 27 Saturation condition flag */ uint32_t V:1; /*!< bit: 28 Overflow condition code flag */ uint32_t C:1; /*!< bit: 29 Carry condition code flag */ uint32_t Z:1; /*!< bit: 30 Zero condition code flag */ uint32_t N:1; /*!< bit: 31 Negative condition code flag */ } b; /*!< Structure used for bit access */ uint32_t w; /*!< Type used for word access */ } APSR_Type; /* APSR Register Definitions */ #define APSR_N_Pos 31 /*!< APSR: N Position */ #define APSR_N_Msk (1UL << APSR_N_Pos) /*!< APSR: N Mask */ #define APSR_Z_Pos 30 /*!< APSR: Z Position */ #define APSR_Z_Msk (1UL << APSR_Z_Pos) /*!< APSR: Z Mask */ #define APSR_C_Pos 29 /*!< APSR: C Position */ #define APSR_C_Msk (1UL << APSR_C_Pos) /*!< APSR: C Mask */ #define APSR_V_Pos 28 /*!< APSR: V Position */ #define APSR_V_Msk (1UL << APSR_V_Pos) /*!< APSR: V Mask */ #define APSR_Q_Pos 27 /*!< APSR: Q Position */ #define APSR_Q_Msk (1UL << APSR_Q_Pos) /*!< APSR: Q Mask */ #define APSR_GE_Pos 16 /*!< APSR: GE Position */ #define APSR_GE_Msk (0xFUL << APSR_GE_Pos) /*!< APSR: GE Mask */ /** \brief Union type to access the Interrupt Program Status Register (IPSR). */ typedef union { struct { uint32_t ISR:9; /*!< bit: 0.. 8 Exception number */ uint32_t _reserved0:23; /*!< bit: 9..31 Reserved */ } b; /*!< Structure used for bit access */ uint32_t w; /*!< Type used for word access */ } IPSR_Type; /* IPSR Register Definitions */ #define IPSR_ISR_Pos 0 /*!< IPSR: ISR Position */ #define IPSR_ISR_Msk (0x1FFUL /*<< IPSR_ISR_Pos*/) /*!< IPSR: ISR Mask */ /** \brief Union type to access the Special-Purpose Program Status Registers (xPSR). */ typedef union { struct { uint32_t ISR:9; /*!< bit: 0.. 8 Exception number */ uint32_t _reserved0:7; /*!< bit: 9..15 Reserved */ uint32_t GE:4; /*!< bit: 16..19 Greater than or Equal flags */ uint32_t _reserved1:4; /*!< bit: 20..23 Reserved */ uint32_t T:1; /*!< bit: 24 Thumb bit (read 0) */ uint32_t IT:2; /*!< bit: 25..26 saved IT state (read 0) */ uint32_t Q:1; /*!< bit: 27 Saturation condition flag */ uint32_t V:1; /*!< bit: 28 Overflow condition code flag */ uint32_t C:1; /*!< bit: 29 Carry condition code flag */ uint32_t Z:1; /*!< bit: 30 Zero condition code flag */ uint32_t N:1; /*!< bit: 31 Negative condition code flag */ } b; /*!< Structure used for bit access */ uint32_t w; /*!< Type used for word access */ } xPSR_Type; /* xPSR Register Definitions */ #define xPSR_N_Pos 31 /*!< xPSR: N Position */ #define xPSR_N_Msk (1UL << xPSR_N_Pos) /*!< xPSR: N Mask */ #define xPSR_Z_Pos 30 /*!< xPSR: Z Position */ #define xPSR_Z_Msk (1UL << xPSR_Z_Pos) /*!< xPSR: Z Mask */ #define xPSR_C_Pos 29 /*!< xPSR: C Position */ #define xPSR_C_Msk (1UL << xPSR_C_Pos) /*!< xPSR: C Mask */ #define xPSR_V_Pos 28 /*!< xPSR: V Position */ #define xPSR_V_Msk (1UL << xPSR_V_Pos) /*!< xPSR: V Mask */ #define xPSR_Q_Pos 27 /*!< xPSR: Q Position */ #define xPSR_Q_Msk (1UL << xPSR_Q_Pos) /*!< xPSR: Q Mask */ #define xPSR_IT_Pos 25 /*!< xPSR: IT Position */ #define xPSR_IT_Msk (3UL << xPSR_IT_Pos) /*!< xPSR: IT Mask */ #define xPSR_T_Pos 24 /*!< xPSR: T Position */ #define xPSR_T_Msk (1UL << xPSR_T_Pos) /*!< xPSR: T Mask */ #define xPSR_GE_Pos 16 /*!< xPSR: GE Position */ #define xPSR_GE_Msk (0xFUL << xPSR_GE_Pos) /*!< xPSR: GE Mask */ #define xPSR_ISR_Pos 0 /*!< xPSR: ISR Position */ #define xPSR_ISR_Msk (0x1FFUL /*<< xPSR_ISR_Pos*/) /*!< xPSR: ISR Mask */ /** \brief Union type to access the Control Registers (CONTROL). */ typedef union { struct { uint32_t nPRIV:1; /*!< bit: 0 Execution privilege in Thread mode */ uint32_t SPSEL:1; /*!< bit: 1 Stack to be used */ uint32_t FPCA:1; /*!< bit: 2 FP extension active flag */ uint32_t _reserved0:29; /*!< bit: 3..31 Reserved */ } b; /*!< Structure used for bit access */ uint32_t w; /*!< Type used for word access */ } CONTROL_Type; /* CONTROL Register Definitions */ #define CONTROL_FPCA_Pos 2 /*!< CONTROL: FPCA Position */ #define CONTROL_FPCA_Msk (1UL << CONTROL_FPCA_Pos) /*!< CONTROL: FPCA Mask */ #define CONTROL_SPSEL_Pos 1 /*!< CONTROL: SPSEL Position */ #define CONTROL_SPSEL_Msk (1UL << CONTROL_SPSEL_Pos) /*!< CONTROL: SPSEL Mask */ #define CONTROL_nPRIV_Pos 0 /*!< CONTROL: nPRIV Position */ #define CONTROL_nPRIV_Msk (1UL /*<< CONTROL_nPRIV_Pos*/) /*!< CONTROL: nPRIV Mask */ /*@} end of group CMSIS_CORE */ /** \ingroup CMSIS_core_register \defgroup CMSIS_NVIC Nested Vectored Interrupt Controller (NVIC) \brief Type definitions for the NVIC Registers @{ */ /** \brief Structure type to access the Nested Vectored Interrupt Controller (NVIC). */ typedef struct { __IO uint32_t ISER[8]; /*!< Offset: 0x000 (R/W) Interrupt Set Enable Register */ uint32_t RESERVED0[24]; __IO uint32_t ICER[8]; /*!< Offset: 0x080 (R/W) Interrupt Clear Enable Register */ uint32_t RSERVED1[24]; __IO uint32_t ISPR[8]; /*!< Offset: 0x100 (R/W) Interrupt Set Pending Register */ uint32_t RESERVED2[24]; __IO uint32_t ICPR[8]; /*!< Offset: 0x180 (R/W) Interrupt Clear Pending Register */ uint32_t RESERVED3[24]; __IO uint32_t IABR[8]; /*!< Offset: 0x200 (R/W) Interrupt Active bit Register */ uint32_t RESERVED4[56]; __IO uint8_t IP[240]; /*!< Offset: 0x300 (R/W) Interrupt Priority Register (8Bit wide) */ uint32_t RESERVED5[644]; __O uint32_t STIR; /*!< Offset: 0xE00 ( /W) Software Trigger Interrupt Register */ } NVIC_Type; /* Software Triggered Interrupt Register Definitions */ #define NVIC_STIR_INTID_Pos 0 /*!< STIR: INTLINESNUM Position */ #define NVIC_STIR_INTID_Msk (0x1FFUL /*<< NVIC_STIR_INTID_Pos*/) /*!< STIR: INTLINESNUM Mask */ /*@} end of group CMSIS_NVIC */ /** \ingroup CMSIS_core_register \defgroup CMSIS_SCB System Control Block (SCB) \brief Type definitions for the System Control Block Registers @{ */ /** \brief Structure type to access the System Control Block (SCB). */ typedef struct { __I uint32_t CPUID; /*!< Offset: 0x000 (R/ ) CPUID Base Register */ __IO uint32_t ICSR; /*!< Offset: 0x004 (R/W) Interrupt Control and State Register */ __IO uint32_t VTOR; /*!< Offset: 0x008 (R/W) Vector Table Offset Register */ __IO uint32_t AIRCR; /*!< Offset: 0x00C (R/W) Application Interrupt and Reset Control Register */ __IO uint32_t SCR; /*!< Offset: 0x010 (R/W) System Control Register */ __IO uint32_t CCR; /*!< Offset: 0x014 (R/W) Configuration Control Register */ __IO uint8_t SHP[12]; /*!< Offset: 0x018 (R/W) System Handlers Priority Registers (4-7, 8-11, 12-15) */ __IO uint32_t SHCSR; /*!< Offset: 0x024 (R/W) System Handler Control and State Register */ __IO uint32_t CFSR; /*!< Offset: 0x028 (R/W) Configurable Fault Status Register */ __IO uint32_t HFSR; /*!< Offset: 0x02C (R/W) HardFault Status Register */ __IO uint32_t DFSR; /*!< Offset: 0x030 (R/W) Debug Fault Status Register */ __IO uint32_t MMFAR; /*!< Offset: 0x034 (R/W) MemManage Fault Address Register */ __IO uint32_t BFAR; /*!< Offset: 0x038 (R/W) BusFault Address Register */ __IO uint32_t AFSR; /*!< Offset: 0x03C (R/W) Auxiliary Fault Status Register */ __I uint32_t PFR[2]; /*!< Offset: 0x040 (R/ ) Processor Feature Register */ __I uint32_t DFR; /*!< Offset: 0x048 (R/ ) Debug Feature Register */ __I uint32_t ADR; /*!< Offset: 0x04C (R/ ) Auxiliary Feature Register */ __I uint32_t MMFR[4]; /*!< Offset: 0x050 (R/ ) Memory Model Feature Register */ __I uint32_t ISAR[5]; /*!< Offset: 0x060 (R/ ) Instruction Set Attributes Register */ uint32_t RESERVED0[5]; __IO uint32_t CPACR; /*!< Offset: 0x088 (R/W) Coprocessor Access Control Register */ } SCB_Type; /* SCB CPUID Register Definitions */ #define SCB_CPUID_IMPLEMENTER_Pos 24 /*!< SCB CPUID: IMPLEMENTER Position */ #define SCB_CPUID_IMPLEMENTER_Msk (0xFFUL << SCB_CPUID_IMPLEMENTER_Pos) /*!< SCB CPUID: IMPLEMENTER Mask */ #define SCB_CPUID_VARIANT_Pos 20 /*!< SCB CPUID: VARIANT Position */ #define SCB_CPUID_VARIANT_Msk (0xFUL << SCB_CPUID_VARIANT_Pos) /*!< SCB CPUID: VARIANT Mask */ #define SCB_CPUID_ARCHITECTURE_Pos 16 /*!< SCB CPUID: ARCHITECTURE Position */ #define SCB_CPUID_ARCHITECTURE_Msk (0xFUL << SCB_CPUID_ARCHITECTURE_Pos) /*!< SCB CPUID: ARCHITECTURE Mask */ #define SCB_CPUID_PARTNO_Pos 4 /*!< SCB CPUID: PARTNO Position */ #define SCB_CPUID_PARTNO_Msk (0xFFFUL << SCB_CPUID_PARTNO_Pos) /*!< SCB CPUID: PARTNO Mask */ #define SCB_CPUID_REVISION_Pos 0 /*!< SCB CPUID: REVISION Position */ #define SCB_CPUID_REVISION_Msk (0xFUL /*<< SCB_CPUID_REVISION_Pos*/) /*!< SCB CPUID: REVISION Mask */ /* SCB Interrupt Control State Register Definitions */ #define SCB_ICSR_NMIPENDSET_Pos 31 /*!< SCB ICSR: NMIPENDSET Position */ #define SCB_ICSR_NMIPENDSET_Msk (1UL << SCB_ICSR_NMIPENDSET_Pos) /*!< SCB ICSR: NMIPENDSET Mask */ #define SCB_ICSR_PENDSVSET_Pos 28 /*!< SCB ICSR: PENDSVSET Position */ #define SCB_ICSR_PENDSVSET_Msk (1UL << SCB_ICSR_PENDSVSET_Pos) /*!< SCB ICSR: PENDSVSET Mask */ #define SCB_ICSR_PENDSVCLR_Pos 27 /*!< SCB ICSR: PENDSVCLR Position */ #define SCB_ICSR_PENDSVCLR_Msk (1UL << SCB_ICSR_PENDSVCLR_Pos) /*!< SCB ICSR: PENDSVCLR Mask */ #define SCB_ICSR_PENDSTSET_Pos 26 /*!< SCB ICSR: PENDSTSET Position */ #define SCB_ICSR_PENDSTSET_Msk (1UL << SCB_ICSR_PENDSTSET_Pos) /*!< SCB ICSR: PENDSTSET Mask */ #define SCB_ICSR_PENDSTCLR_Pos 25 /*!< SCB ICSR: PENDSTCLR Position */ #define SCB_ICSR_PENDSTCLR_Msk (1UL << SCB_ICSR_PENDSTCLR_Pos) /*!< SCB ICSR: PENDSTCLR Mask */ #define SCB_ICSR_ISRPREEMPT_Pos 23 /*!< SCB ICSR: ISRPREEMPT Position */ #define SCB_ICSR_ISRPREEMPT_Msk (1UL << SCB_ICSR_ISRPREEMPT_Pos) /*!< SCB ICSR: ISRPREEMPT Mask */ #define SCB_ICSR_ISRPENDING_Pos 22 /*!< SCB ICSR: ISRPENDING Position */ #define SCB_ICSR_ISRPENDING_Msk (1UL << SCB_ICSR_ISRPENDING_Pos) /*!< SCB ICSR: ISRPENDING Mask */ #define SCB_ICSR_VECTPENDING_Pos 12 /*!< SCB ICSR: VECTPENDING Position */ #define SCB_ICSR_VECTPENDING_Msk (0x1FFUL << SCB_ICSR_VECTPENDING_Pos) /*!< SCB ICSR: VECTPENDING Mask */ #define SCB_ICSR_RETTOBASE_Pos 11 /*!< SCB ICSR: RETTOBASE Position */ #define SCB_ICSR_RETTOBASE_Msk (1UL << SCB_ICSR_RETTOBASE_Pos) /*!< SCB ICSR: RETTOBASE Mask */ #define SCB_ICSR_VECTACTIVE_Pos 0 /*!< SCB ICSR: VECTACTIVE Position */ #define SCB_ICSR_VECTACTIVE_Msk (0x1FFUL /*<< SCB_ICSR_VECTACTIVE_Pos*/) /*!< SCB ICSR: VECTACTIVE Mask */ /* SCB Vector Table Offset Register Definitions */ #define SCB_VTOR_TBLOFF_Pos 7 /*!< SCB VTOR: TBLOFF Position */ #define SCB_VTOR_TBLOFF_Msk (0x1FFFFFFUL << SCB_VTOR_TBLOFF_Pos) /*!< SCB VTOR: TBLOFF Mask */ /* SCB Application Interrupt and Reset Control Register Definitions */ #define SCB_AIRCR_VECTKEY_Pos 16 /*!< SCB AIRCR: VECTKEY Position */ #define SCB_AIRCR_VECTKEY_Msk (0xFFFFUL << SCB_AIRCR_VECTKEY_Pos) /*!< SCB AIRCR: VECTKEY Mask */ #define SCB_AIRCR_VECTKEYSTAT_Pos 16 /*!< SCB AIRCR: VECTKEYSTAT Position */ #define SCB_AIRCR_VECTKEYSTAT_Msk (0xFFFFUL << SCB_AIRCR_VECTKEYSTAT_Pos) /*!< SCB AIRCR: VECTKEYSTAT Mask */ #define SCB_AIRCR_ENDIANESS_Pos 15 /*!< SCB AIRCR: ENDIANESS Position */ #define SCB_AIRCR_ENDIANESS_Msk (1UL << SCB_AIRCR_ENDIANESS_Pos) /*!< SCB AIRCR: ENDIANESS Mask */ #define SCB_AIRCR_PRIGROUP_Pos 8 /*!< SCB AIRCR: PRIGROUP Position */ #define SCB_AIRCR_PRIGROUP_Msk (7UL << SCB_AIRCR_PRIGROUP_Pos) /*!< SCB AIRCR: PRIGROUP Mask */ #define SCB_AIRCR_SYSRESETREQ_Pos 2 /*!< SCB AIRCR: SYSRESETREQ Position */ #define SCB_AIRCR_SYSRESETREQ_Msk (1UL << SCB_AIRCR_SYSRESETREQ_Pos) /*!< SCB AIRCR: SYSRESETREQ Mask */ #define SCB_AIRCR_VECTCLRACTIVE_Pos 1 /*!< SCB AIRCR: VECTCLRACTIVE Position */ #define SCB_AIRCR_VECTCLRACTIVE_Msk (1UL << SCB_AIRCR_VECTCLRACTIVE_Pos) /*!< SCB AIRCR: VECTCLRACTIVE Mask */ #define SCB_AIRCR_VECTRESET_Pos 0 /*!< SCB AIRCR: VECTRESET Position */ #define SCB_AIRCR_VECTRESET_Msk (1UL /*<< SCB_AIRCR_VECTRESET_Pos*/) /*!< SCB AIRCR: VECTRESET Mask */ /* SCB System Control Register Definitions */ #define SCB_SCR_SEVONPEND_Pos 4 /*!< SCB SCR: SEVONPEND Position */ #define SCB_SCR_SEVONPEND_Msk (1UL << SCB_SCR_SEVONPEND_Pos) /*!< SCB SCR: SEVONPEND Mask */ #define SCB_SCR_SLEEPDEEP_Pos 2 /*!< SCB SCR: SLEEPDEEP Position */ #define SCB_SCR_SLEEPDEEP_Msk (1UL << SCB_SCR_SLEEPDEEP_Pos) /*!< SCB SCR: SLEEPDEEP Mask */ #define SCB_SCR_SLEEPONEXIT_Pos 1 /*!< SCB SCR: SLEEPONEXIT Position */ #define SCB_SCR_SLEEPONEXIT_Msk (1UL << SCB_SCR_SLEEPONEXIT_Pos) /*!< SCB SCR: SLEEPONEXIT Mask */ /* SCB Configuration Control Register Definitions */ #define SCB_CCR_STKALIGN_Pos 9 /*!< SCB CCR: STKALIGN Position */ #define SCB_CCR_STKALIGN_Msk (1UL << SCB_CCR_STKALIGN_Pos) /*!< SCB CCR: STKALIGN Mask */ #define SCB_CCR_BFHFNMIGN_Pos 8 /*!< SCB CCR: BFHFNMIGN Position */ #define SCB_CCR_BFHFNMIGN_Msk (1UL << SCB_CCR_BFHFNMIGN_Pos) /*!< SCB CCR: BFHFNMIGN Mask */ #define SCB_CCR_DIV_0_TRP_Pos 4 /*!< SCB CCR: DIV_0_TRP Position */ #define SCB_CCR_DIV_0_TRP_Msk (1UL << SCB_CCR_DIV_0_TRP_Pos) /*!< SCB CCR: DIV_0_TRP Mask */ #define SCB_CCR_UNALIGN_TRP_Pos 3 /*!< SCB CCR: UNALIGN_TRP Position */ #define SCB_CCR_UNALIGN_TRP_Msk (1UL << SCB_CCR_UNALIGN_TRP_Pos) /*!< SCB CCR: UNALIGN_TRP Mask */ #define SCB_CCR_USERSETMPEND_Pos 1 /*!< SCB CCR: USERSETMPEND Position */ #define SCB_CCR_USERSETMPEND_Msk (1UL << SCB_CCR_USERSETMPEND_Pos) /*!< SCB CCR: USERSETMPEND Mask */ #define SCB_CCR_NONBASETHRDENA_Pos 0 /*!< SCB CCR: NONBASETHRDENA Position */ #define SCB_CCR_NONBASETHRDENA_Msk (1UL /*<< SCB_CCR_NONBASETHRDENA_Pos*/) /*!< SCB CCR: NONBASETHRDENA Mask */ /* SCB System Handler Control and State Register Definitions */ #define SCB_SHCSR_USGFAULTENA_Pos 18 /*!< SCB SHCSR: USGFAULTENA Position */ #define SCB_SHCSR_USGFAULTENA_Msk (1UL << SCB_SHCSR_USGFAULTENA_Pos) /*!< SCB SHCSR: USGFAULTENA Mask */ #define SCB_SHCSR_BUSFAULTENA_Pos 17 /*!< SCB SHCSR: BUSFAULTENA Position */ #define SCB_SHCSR_BUSFAULTENA_Msk (1UL << SCB_SHCSR_BUSFAULTENA_Pos) /*!< SCB SHCSR: BUSFAULTENA Mask */ #define SCB_SHCSR_MEMFAULTENA_Pos 16 /*!< SCB SHCSR: MEMFAULTENA Position */ #define SCB_SHCSR_MEMFAULTENA_Msk (1UL << SCB_SHCSR_MEMFAULTENA_Pos) /*!< SCB SHCSR: MEMFAULTENA Mask */ #define SCB_SHCSR_SVCALLPENDED_Pos 15 /*!< SCB SHCSR: SVCALLPENDED Position */ #define SCB_SHCSR_SVCALLPENDED_Msk (1UL << SCB_SHCSR_SVCALLPENDED_Pos) /*!< SCB SHCSR: SVCALLPENDED Mask */ #define SCB_SHCSR_BUSFAULTPENDED_Pos 14 /*!< SCB SHCSR: BUSFAULTPENDED Position */ #define SCB_SHCSR_BUSFAULTPENDED_Msk (1UL << SCB_SHCSR_BUSFAULTPENDED_Pos) /*!< SCB SHCSR: BUSFAULTPENDED Mask */ #define SCB_SHCSR_MEMFAULTPENDED_Pos 13 /*!< SCB SHCSR: MEMFAULTPENDED Position */ #define SCB_SHCSR_MEMFAULTPENDED_Msk (1UL << SCB_SHCSR_MEMFAULTPENDED_Pos) /*!< SCB SHCSR: MEMFAULTPENDED Mask */ #define SCB_SHCSR_USGFAULTPENDED_Pos 12 /*!< SCB SHCSR: USGFAULTPENDED Position */ #define SCB_SHCSR_USGFAULTPENDED_Msk (1UL << SCB_SHCSR_USGFAULTPENDED_Pos) /*!< SCB SHCSR: USGFAULTPENDED Mask */ #define SCB_SHCSR_SYSTICKACT_Pos 11 /*!< SCB SHCSR: SYSTICKACT Position */ #define SCB_SHCSR_SYSTICKACT_Msk (1UL << SCB_SHCSR_SYSTICKACT_Pos) /*!< SCB SHCSR: SYSTICKACT Mask */ #define SCB_SHCSR_PENDSVACT_Pos 10 /*!< SCB SHCSR: PENDSVACT Position */ #define SCB_SHCSR_PENDSVACT_Msk (1UL << SCB_SHCSR_PENDSVACT_Pos) /*!< SCB SHCSR: PENDSVACT Mask */ #define SCB_SHCSR_MONITORACT_Pos 8 /*!< SCB SHCSR: MONITORACT Position */ #define SCB_SHCSR_MONITORACT_Msk (1UL << SCB_SHCSR_MONITORACT_Pos) /*!< SCB SHCSR: MONITORACT Mask */ #define SCB_SHCSR_SVCALLACT_Pos 7 /*!< SCB SHCSR: SVCALLACT Position */ #define SCB_SHCSR_SVCALLACT_Msk (1UL << SCB_SHCSR_SVCALLACT_Pos) /*!< SCB SHCSR: SVCALLACT Mask */ #define SCB_SHCSR_USGFAULTACT_Pos 3 /*!< SCB SHCSR: USGFAULTACT Position */ #define SCB_SHCSR_USGFAULTACT_Msk (1UL << SCB_SHCSR_USGFAULTACT_Pos) /*!< SCB SHCSR: USGFAULTACT Mask */ #define SCB_SHCSR_BUSFAULTACT_Pos 1 /*!< SCB SHCSR: BUSFAULTACT Position */ #define SCB_SHCSR_BUSFAULTACT_Msk (1UL << SCB_SHCSR_BUSFAULTACT_Pos) /*!< SCB SHCSR: BUSFAULTACT Mask */ #define SCB_SHCSR_MEMFAULTACT_Pos 0 /*!< SCB SHCSR: MEMFAULTACT Position */ #define SCB_SHCSR_MEMFAULTACT_Msk (1UL /*<< SCB_SHCSR_MEMFAULTACT_Pos*/) /*!< SCB SHCSR: MEMFAULTACT Mask */ /* SCB Configurable Fault Status Registers Definitions */ #define SCB_CFSR_USGFAULTSR_Pos 16 /*!< SCB CFSR: Usage Fault Status Register Position */ #define SCB_CFSR_USGFAULTSR_Msk (0xFFFFUL << SCB_CFSR_USGFAULTSR_Pos) /*!< SCB CFSR: Usage Fault Status Register Mask */ #define SCB_CFSR_BUSFAULTSR_Pos 8 /*!< SCB CFSR: Bus Fault Status Register Position */ #define SCB_CFSR_BUSFAULTSR_Msk (0xFFUL << SCB_CFSR_BUSFAULTSR_Pos) /*!< SCB CFSR: Bus Fault Status Register Mask */ #define SCB_CFSR_MEMFAULTSR_Pos 0 /*!< SCB CFSR: Memory Manage Fault Status Register Position */ #define SCB_CFSR_MEMFAULTSR_Msk (0xFFUL /*<< SCB_CFSR_MEMFAULTSR_Pos*/) /*!< SCB CFSR: Memory Manage Fault Status Register Mask */ /* SCB Hard Fault Status Registers Definitions */ #define SCB_HFSR_DEBUGEVT_Pos 31 /*!< SCB HFSR: DEBUGEVT Position */ #define SCB_HFSR_DEBUGEVT_Msk (1UL << SCB_HFSR_DEBUGEVT_Pos) /*!< SCB HFSR: DEBUGEVT Mask */ #define SCB_HFSR_FORCED_Pos 30 /*!< SCB HFSR: FORCED Position */ #define SCB_HFSR_FORCED_Msk (1UL << SCB_HFSR_FORCED_Pos) /*!< SCB HFSR: FORCED Mask */ #define SCB_HFSR_VECTTBL_Pos 1 /*!< SCB HFSR: VECTTBL Position */ #define SCB_HFSR_VECTTBL_Msk (1UL << SCB_HFSR_VECTTBL_Pos) /*!< SCB HFSR: VECTTBL Mask */ /* SCB Debug Fault Status Register Definitions */ #define SCB_DFSR_EXTERNAL_Pos 4 /*!< SCB DFSR: EXTERNAL Position */ #define SCB_DFSR_EXTERNAL_Msk (1UL << SCB_DFSR_EXTERNAL_Pos) /*!< SCB DFSR: EXTERNAL Mask */ #define SCB_DFSR_VCATCH_Pos 3 /*!< SCB DFSR: VCATCH Position */ #define SCB_DFSR_VCATCH_Msk (1UL << SCB_DFSR_VCATCH_Pos) /*!< SCB DFSR: VCATCH Mask */ #define SCB_DFSR_DWTTRAP_Pos 2 /*!< SCB DFSR: DWTTRAP Position */ #define SCB_DFSR_DWTTRAP_Msk (1UL << SCB_DFSR_DWTTRAP_Pos) /*!< SCB DFSR: DWTTRAP Mask */ #define SCB_DFSR_BKPT_Pos 1 /*!< SCB DFSR: BKPT Position */ #define SCB_DFSR_BKPT_Msk (1UL << SCB_DFSR_BKPT_Pos) /*!< SCB DFSR: BKPT Mask */ #define SCB_DFSR_HALTED_Pos 0 /*!< SCB DFSR: HALTED Position */ #define SCB_DFSR_HALTED_Msk (1UL /*<< SCB_DFSR_HALTED_Pos*/) /*!< SCB DFSR: HALTED Mask */ /*@} end of group CMSIS_SCB */ /** \ingroup CMSIS_core_register \defgroup CMSIS_SCnSCB System Controls not in SCB (SCnSCB) \brief Type definitions for the System Control and ID Register not in the SCB @{ */ /** \brief Structure type to access the System Control and ID Register not in the SCB. */ typedef struct { uint32_t RESERVED0[1]; __I uint32_t ICTR; /*!< Offset: 0x004 (R/ ) Interrupt Controller Type Register */ __IO uint32_t ACTLR; /*!< Offset: 0x008 (R/W) Auxiliary Control Register */ } SCnSCB_Type; /* Interrupt Controller Type Register Definitions */ #define SCnSCB_ICTR_INTLINESNUM_Pos 0 /*!< ICTR: INTLINESNUM Position */ #define SCnSCB_ICTR_INTLINESNUM_Msk (0xFUL /*<< SCnSCB_ICTR_INTLINESNUM_Pos*/) /*!< ICTR: INTLINESNUM Mask */ /* Auxiliary Control Register Definitions */ #define SCnSCB_ACTLR_DISOOFP_Pos 9 /*!< ACTLR: DISOOFP Position */ #define SCnSCB_ACTLR_DISOOFP_Msk (1UL << SCnSCB_ACTLR_DISOOFP_Pos) /*!< ACTLR: DISOOFP Mask */ #define SCnSCB_ACTLR_DISFPCA_Pos 8 /*!< ACTLR: DISFPCA Position */ #define SCnSCB_ACTLR_DISFPCA_Msk (1UL << SCnSCB_ACTLR_DISFPCA_Pos) /*!< ACTLR: DISFPCA Mask */ #define SCnSCB_ACTLR_DISFOLD_Pos 2 /*!< ACTLR: DISFOLD Position */ #define SCnSCB_ACTLR_DISFOLD_Msk (1UL << SCnSCB_ACTLR_DISFOLD_Pos) /*!< ACTLR: DISFOLD Mask */ #define SCnSCB_ACTLR_DISDEFWBUF_Pos 1 /*!< ACTLR: DISDEFWBUF Position */ #define SCnSCB_ACTLR_DISDEFWBUF_Msk (1UL << SCnSCB_ACTLR_DISDEFWBUF_Pos) /*!< ACTLR: DISDEFWBUF Mask */ #define SCnSCB_ACTLR_DISMCYCINT_Pos 0 /*!< ACTLR: DISMCYCINT Position */ #define SCnSCB_ACTLR_DISMCYCINT_Msk (1UL /*<< SCnSCB_ACTLR_DISMCYCINT_Pos*/) /*!< ACTLR: DISMCYCINT Mask */ /*@} end of group CMSIS_SCnotSCB */ /** \ingroup CMSIS_core_register \defgroup CMSIS_SysTick System Tick Timer (SysTick) \brief Type definitions for the System Timer Registers. @{ */ /** \brief Structure type to access the System Timer (SysTick). */ typedef struct { __IO uint32_t CTRL; /*!< Offset: 0x000 (R/W) SysTick Control and Status Register */ __IO uint32_t LOAD; /*!< Offset: 0x004 (R/W) SysTick Reload Value Register */ __IO uint32_t VAL; /*!< Offset: 0x008 (R/W) SysTick Current Value Register */ __I uint32_t CALIB; /*!< Offset: 0x00C (R/ ) SysTick Calibration Register */ } SysTick_Type; /* SysTick Control / Status Register Definitions */ #define SysTick_CTRL_COUNTFLAG_Pos 16 /*!< SysTick CTRL: COUNTFLAG Position */ #define SysTick_CTRL_COUNTFLAG_Msk (1UL << SysTick_CTRL_COUNTFLAG_Pos) /*!< SysTick CTRL: COUNTFLAG Mask */ #define SysTick_CTRL_CLKSOURCE_Pos 2 /*!< SysTick CTRL: CLKSOURCE Position */ #define SysTick_CTRL_CLKSOURCE_Msk (1UL << SysTick_CTRL_CLKSOURCE_Pos) /*!< SysTick CTRL: CLKSOURCE Mask */ #define SysTick_CTRL_TICKINT_Pos 1 /*!< SysTick CTRL: TICKINT Position */ #define SysTick_CTRL_TICKINT_Msk (1UL << SysTick_CTRL_TICKINT_Pos) /*!< SysTick CTRL: TICKINT Mask */ #define SysTick_CTRL_ENABLE_Pos 0 /*!< SysTick CTRL: ENABLE Position */ #define SysTick_CTRL_ENABLE_Msk (1UL /*<< SysTick_CTRL_ENABLE_Pos*/) /*!< SysTick CTRL: ENABLE Mask */ /* SysTick Reload Register Definitions */ #define SysTick_LOAD_RELOAD_Pos 0 /*!< SysTick LOAD: RELOAD Position */ #define SysTick_LOAD_RELOAD_Msk (0xFFFFFFUL /*<< SysTick_LOAD_RELOAD_Pos*/) /*!< SysTick LOAD: RELOAD Mask */ /* SysTick Current Register Definitions */ #define SysTick_VAL_CURRENT_Pos 0 /*!< SysTick VAL: CURRENT Position */ #define SysTick_VAL_CURRENT_Msk (0xFFFFFFUL /*<< SysTick_VAL_CURRENT_Pos*/) /*!< SysTick VAL: CURRENT Mask */ /* SysTick Calibration Register Definitions */ #define SysTick_CALIB_NOREF_Pos 31 /*!< SysTick CALIB: NOREF Position */ #define SysTick_CALIB_NOREF_Msk (1UL << SysTick_CALIB_NOREF_Pos) /*!< SysTick CALIB: NOREF Mask */ #define SysTick_CALIB_SKEW_Pos 30 /*!< SysTick CALIB: SKEW Position */ #define SysTick_CALIB_SKEW_Msk (1UL << SysTick_CALIB_SKEW_Pos) /*!< SysTick CALIB: SKEW Mask */ #define SysTick_CALIB_TENMS_Pos 0 /*!< SysTick CALIB: TENMS Position */ #define SysTick_CALIB_TENMS_Msk (0xFFFFFFUL /*<< SysTick_CALIB_TENMS_Pos*/) /*!< SysTick CALIB: TENMS Mask */ /*@} end of group CMSIS_SysTick */ /** \ingroup CMSIS_core_register \defgroup CMSIS_ITM Instrumentation Trace Macrocell (ITM) \brief Type definitions for the Instrumentation Trace Macrocell (ITM) @{ */ /** \brief Structure type to access the Instrumentation Trace Macrocell Register (ITM). */ typedef struct { __O union { __O uint8_t u8; /*!< Offset: 0x000 ( /W) ITM Stimulus Port 8-bit */ __O uint16_t u16; /*!< Offset: 0x000 ( /W) ITM Stimulus Port 16-bit */ __O uint32_t u32; /*!< Offset: 0x000 ( /W) ITM Stimulus Port 32-bit */ } PORT [32]; /*!< Offset: 0x000 ( /W) ITM Stimulus Port Registers */ uint32_t RESERVED0[864]; __IO uint32_t TER; /*!< Offset: 0xE00 (R/W) ITM Trace Enable Register */ uint32_t RESERVED1[15]; __IO uint32_t TPR; /*!< Offset: 0xE40 (R/W) ITM Trace Privilege Register */ uint32_t RESERVED2[15]; __IO uint32_t TCR; /*!< Offset: 0xE80 (R/W) ITM Trace Control Register */ uint32_t RESERVED3[29]; __O uint32_t IWR; /*!< Offset: 0xEF8 ( /W) ITM Integration Write Register */ __I uint32_t IRR; /*!< Offset: 0xEFC (R/ ) ITM Integration Read Register */ __IO uint32_t IMCR; /*!< Offset: 0xF00 (R/W) ITM Integration Mode Control Register */ uint32_t RESERVED4[43]; __O uint32_t LAR; /*!< Offset: 0xFB0 ( /W) ITM Lock Access Register */ __I uint32_t LSR; /*!< Offset: 0xFB4 (R/ ) ITM Lock Status Register */ uint32_t RESERVED5[6]; __I uint32_t PID4; /*!< Offset: 0xFD0 (R/ ) ITM Peripheral Identification Register #4 */ __I uint32_t PID5; /*!< Offset: 0xFD4 (R/ ) ITM Peripheral Identification Register #5 */ __I uint32_t PID6; /*!< Offset: 0xFD8 (R/ ) ITM Peripheral Identification Register #6 */ __I uint32_t PID7; /*!< Offset: 0xFDC (R/ ) ITM Peripheral Identification Register #7 */ __I uint32_t PID0; /*!< Offset: 0xFE0 (R/ ) ITM Peripheral Identification Register #0 */ __I uint32_t PID1; /*!< Offset: 0xFE4 (R/ ) ITM Peripheral Identification Register #1 */ __I uint32_t PID2; /*!< Offset: 0xFE8 (R/ ) ITM Peripheral Identification Register #2 */ __I uint32_t PID3; /*!< Offset: 0xFEC (R/ ) ITM Peripheral Identification Register #3 */ __I uint32_t CID0; /*!< Offset: 0xFF0 (R/ ) ITM Component Identification Register #0 */ __I uint32_t CID1; /*!< Offset: 0xFF4 (R/ ) ITM Component Identification Register #1 */ __I uint32_t CID2; /*!< Offset: 0xFF8 (R/ ) ITM Component Identification Register #2 */ __I uint32_t CID3; /*!< Offset: 0xFFC (R/ ) ITM Component Identification Register #3 */ } ITM_Type; /* ITM Trace Privilege Register Definitions */ #define ITM_TPR_PRIVMASK_Pos 0 /*!< ITM TPR: PRIVMASK Position */ #define ITM_TPR_PRIVMASK_Msk (0xFUL /*<< ITM_TPR_PRIVMASK_Pos*/) /*!< ITM TPR: PRIVMASK Mask */ /* ITM Trace Control Register Definitions */ #define ITM_TCR_BUSY_Pos 23 /*!< ITM TCR: BUSY Position */ #define ITM_TCR_BUSY_Msk (1UL << ITM_TCR_BUSY_Pos) /*!< ITM TCR: BUSY Mask */ #define ITM_TCR_TraceBusID_Pos 16 /*!< ITM TCR: ATBID Position */ #define ITM_TCR_TraceBusID_Msk (0x7FUL << ITM_TCR_TraceBusID_Pos) /*!< ITM TCR: ATBID Mask */ #define ITM_TCR_GTSFREQ_Pos 10 /*!< ITM TCR: Global timestamp frequency Position */ #define ITM_TCR_GTSFREQ_Msk (3UL << ITM_TCR_GTSFREQ_Pos) /*!< ITM TCR: Global timestamp frequency Mask */ #define ITM_TCR_TSPrescale_Pos 8 /*!< ITM TCR: TSPrescale Position */ #define ITM_TCR_TSPrescale_Msk (3UL << ITM_TCR_TSPrescale_Pos) /*!< ITM TCR: TSPrescale Mask */ #define ITM_TCR_SWOENA_Pos 4 /*!< ITM TCR: SWOENA Position */ #define ITM_TCR_SWOENA_Msk (1UL << ITM_TCR_SWOENA_Pos) /*!< ITM TCR: SWOENA Mask */ #define ITM_TCR_DWTENA_Pos 3 /*!< ITM TCR: DWTENA Position */ #define ITM_TCR_DWTENA_Msk (1UL << ITM_TCR_DWTENA_Pos) /*!< ITM TCR: DWTENA Mask */ #define ITM_TCR_SYNCENA_Pos 2 /*!< ITM TCR: SYNCENA Position */ #define ITM_TCR_SYNCENA_Msk (1UL << ITM_TCR_SYNCENA_Pos) /*!< ITM TCR: SYNCENA Mask */ #define ITM_TCR_TSENA_Pos 1 /*!< ITM TCR: TSENA Position */ #define ITM_TCR_TSENA_Msk (1UL << ITM_TCR_TSENA_Pos) /*!< ITM TCR: TSENA Mask */ #define ITM_TCR_ITMENA_Pos 0 /*!< ITM TCR: ITM Enable bit Position */ #define ITM_TCR_ITMENA_Msk (1UL /*<< ITM_TCR_ITMENA_Pos*/) /*!< ITM TCR: ITM Enable bit Mask */ /* ITM Integration Write Register Definitions */ #define ITM_IWR_ATVALIDM_Pos 0 /*!< ITM IWR: ATVALIDM Position */ #define ITM_IWR_ATVALIDM_Msk (1UL /*<< ITM_IWR_ATVALIDM_Pos*/) /*!< ITM IWR: ATVALIDM Mask */ /* ITM Integration Read Register Definitions */ #define ITM_IRR_ATREADYM_Pos 0 /*!< ITM IRR: ATREADYM Position */ #define ITM_IRR_ATREADYM_Msk (1UL /*<< ITM_IRR_ATREADYM_Pos*/) /*!< ITM IRR: ATREADYM Mask */ /* ITM Integration Mode Control Register Definitions */ #define ITM_IMCR_INTEGRATION_Pos 0 /*!< ITM IMCR: INTEGRATION Position */ #define ITM_IMCR_INTEGRATION_Msk (1UL /*<< ITM_IMCR_INTEGRATION_Pos*/) /*!< ITM IMCR: INTEGRATION Mask */ /* ITM Lock Status Register Definitions */ #define ITM_LSR_ByteAcc_Pos 2 /*!< ITM LSR: ByteAcc Position */ #define ITM_LSR_ByteAcc_Msk (1UL << ITM_LSR_ByteAcc_Pos) /*!< ITM LSR: ByteAcc Mask */ #define ITM_LSR_Access_Pos 1 /*!< ITM LSR: Access Position */ #define ITM_LSR_Access_Msk (1UL << ITM_LSR_Access_Pos) /*!< ITM LSR: Access Mask */ #define ITM_LSR_Present_Pos 0 /*!< ITM LSR: Present Position */ #define ITM_LSR_Present_Msk (1UL /*<< ITM_LSR_Present_Pos*/) /*!< ITM LSR: Present Mask */ /*@}*/ /* end of group CMSIS_ITM */ /** \ingroup CMSIS_core_register \defgroup CMSIS_DWT Data Watchpoint and Trace (DWT) \brief Type definitions for the Data Watchpoint and Trace (DWT) @{ */ /** \brief Structure type to access the Data Watchpoint and Trace Register (DWT). */ typedef struct { __IO uint32_t CTRL; /*!< Offset: 0x000 (R/W) Control Register */ __IO uint32_t CYCCNT; /*!< Offset: 0x004 (R/W) Cycle Count Register */ __IO uint32_t CPICNT; /*!< Offset: 0x008 (R/W) CPI Count Register */ __IO uint32_t EXCCNT; /*!< Offset: 0x00C (R/W) Exception Overhead Count Register */ __IO uint32_t SLEEPCNT; /*!< Offset: 0x010 (R/W) Sleep Count Register */ __IO uint32_t LSUCNT; /*!< Offset: 0x014 (R/W) LSU Count Register */ __IO uint32_t FOLDCNT; /*!< Offset: 0x018 (R/W) Folded-instruction Count Register */ __I uint32_t PCSR; /*!< Offset: 0x01C (R/ ) Program Counter Sample Register */ __IO uint32_t COMP0; /*!< Offset: 0x020 (R/W) Comparator Register 0 */ __IO uint32_t MASK0; /*!< Offset: 0x024 (R/W) Mask Register 0 */ __IO uint32_t FUNCTION0; /*!< Offset: 0x028 (R/W) Function Register 0 */ uint32_t RESERVED0[1]; __IO uint32_t COMP1; /*!< Offset: 0x030 (R/W) Comparator Register 1 */ __IO uint32_t MASK1; /*!< Offset: 0x034 (R/W) Mask Register 1 */ __IO uint32_t FUNCTION1; /*!< Offset: 0x038 (R/W) Function Register 1 */ uint32_t RESERVED1[1]; __IO uint32_t COMP2; /*!< Offset: 0x040 (R/W) Comparator Register 2 */ __IO uint32_t MASK2; /*!< Offset: 0x044 (R/W) Mask Register 2 */ __IO uint32_t FUNCTION2; /*!< Offset: 0x048 (R/W) Function Register 2 */ uint32_t RESERVED2[1]; __IO uint32_t COMP3; /*!< Offset: 0x050 (R/W) Comparator Register 3 */ __IO uint32_t MASK3; /*!< Offset: 0x054 (R/W) Mask Register 3 */ __IO uint32_t FUNCTION3; /*!< Offset: 0x058 (R/W) Function Register 3 */ } DWT_Type; /* DWT Control Register Definitions */ #define DWT_CTRL_NUMCOMP_Pos 28 /*!< DWT CTRL: NUMCOMP Position */ #define DWT_CTRL_NUMCOMP_Msk (0xFUL << DWT_CTRL_NUMCOMP_Pos) /*!< DWT CTRL: NUMCOMP Mask */ #define DWT_CTRL_NOTRCPKT_Pos 27 /*!< DWT CTRL: NOTRCPKT Position */ #define DWT_CTRL_NOTRCPKT_Msk (0x1UL << DWT_CTRL_NOTRCPKT_Pos) /*!< DWT CTRL: NOTRCPKT Mask */ #define DWT_CTRL_NOEXTTRIG_Pos 26 /*!< DWT CTRL: NOEXTTRIG Position */ #define DWT_CTRL_NOEXTTRIG_Msk (0x1UL << DWT_CTRL_NOEXTTRIG_Pos) /*!< DWT CTRL: NOEXTTRIG Mask */ #define DWT_CTRL_NOCYCCNT_Pos 25 /*!< DWT CTRL: NOCYCCNT Position */ #define DWT_CTRL_NOCYCCNT_Msk (0x1UL << DWT_CTRL_NOCYCCNT_Pos) /*!< DWT CTRL: NOCYCCNT Mask */ #define DWT_CTRL_NOPRFCNT_Pos 24 /*!< DWT CTRL: NOPRFCNT Position */ #define DWT_CTRL_NOPRFCNT_Msk (0x1UL << DWT_CTRL_NOPRFCNT_Pos) /*!< DWT CTRL: NOPRFCNT Mask */ #define DWT_CTRL_CYCEVTENA_Pos 22 /*!< DWT CTRL: CYCEVTENA Position */ #define DWT_CTRL_CYCEVTENA_Msk (0x1UL << DWT_CTRL_CYCEVTENA_Pos) /*!< DWT CTRL: CYCEVTENA Mask */ #define DWT_CTRL_FOLDEVTENA_Pos 21 /*!< DWT CTRL: FOLDEVTENA Position */ #define DWT_CTRL_FOLDEVTENA_Msk (0x1UL << DWT_CTRL_FOLDEVTENA_Pos) /*!< DWT CTRL: FOLDEVTENA Mask */ #define DWT_CTRL_LSUEVTENA_Pos 20 /*!< DWT CTRL: LSUEVTENA Position */ #define DWT_CTRL_LSUEVTENA_Msk (0x1UL << DWT_CTRL_LSUEVTENA_Pos) /*!< DWT CTRL: LSUEVTENA Mask */ #define DWT_CTRL_SLEEPEVTENA_Pos 19 /*!< DWT CTRL: SLEEPEVTENA Position */ #define DWT_CTRL_SLEEPEVTENA_Msk (0x1UL << DWT_CTRL_SLEEPEVTENA_Pos) /*!< DWT CTRL: SLEEPEVTENA Mask */ #define DWT_CTRL_EXCEVTENA_Pos 18 /*!< DWT CTRL: EXCEVTENA Position */ #define DWT_CTRL_EXCEVTENA_Msk (0x1UL << DWT_CTRL_EXCEVTENA_Pos) /*!< DWT CTRL: EXCEVTENA Mask */ #define DWT_CTRL_CPIEVTENA_Pos 17 /*!< DWT CTRL: CPIEVTENA Position */ #define DWT_CTRL_CPIEVTENA_Msk (0x1UL << DWT_CTRL_CPIEVTENA_Pos) /*!< DWT CTRL: CPIEVTENA Mask */ #define DWT_CTRL_EXCTRCENA_Pos 16 /*!< DWT CTRL: EXCTRCENA Position */ #define DWT_CTRL_EXCTRCENA_Msk (0x1UL << DWT_CTRL_EXCTRCENA_Pos) /*!< DWT CTRL: EXCTRCENA Mask */ #define DWT_CTRL_PCSAMPLENA_Pos 12 /*!< DWT CTRL: PCSAMPLENA Position */ #define DWT_CTRL_PCSAMPLENA_Msk (0x1UL << DWT_CTRL_PCSAMPLENA_Pos) /*!< DWT CTRL: PCSAMPLENA Mask */ #define DWT_CTRL_SYNCTAP_Pos 10 /*!< DWT CTRL: SYNCTAP Position */ #define DWT_CTRL_SYNCTAP_Msk (0x3UL << DWT_CTRL_SYNCTAP_Pos) /*!< DWT CTRL: SYNCTAP Mask */ #define DWT_CTRL_CYCTAP_Pos 9 /*!< DWT CTRL: CYCTAP Position */ #define DWT_CTRL_CYCTAP_Msk (0x1UL << DWT_CTRL_CYCTAP_Pos) /*!< DWT CTRL: CYCTAP Mask */ #define DWT_CTRL_POSTINIT_Pos 5 /*!< DWT CTRL: POSTINIT Position */ #define DWT_CTRL_POSTINIT_Msk (0xFUL << DWT_CTRL_POSTINIT_Pos) /*!< DWT CTRL: POSTINIT Mask */ #define DWT_CTRL_POSTPRESET_Pos 1 /*!< DWT CTRL: POSTPRESET Position */ #define DWT_CTRL_POSTPRESET_Msk (0xFUL << DWT_CTRL_POSTPRESET_Pos) /*!< DWT CTRL: POSTPRESET Mask */ #define DWT_CTRL_CYCCNTENA_Pos 0 /*!< DWT CTRL: CYCCNTENA Position */ #define DWT_CTRL_CYCCNTENA_Msk (0x1UL /*<< DWT_CTRL_CYCCNTENA_Pos*/) /*!< DWT CTRL: CYCCNTENA Mask */ /* DWT CPI Count Register Definitions */ #define DWT_CPICNT_CPICNT_Pos 0 /*!< DWT CPICNT: CPICNT Position */ #define DWT_CPICNT_CPICNT_Msk (0xFFUL /*<< DWT_CPICNT_CPICNT_Pos*/) /*!< DWT CPICNT: CPICNT Mask */ /* DWT Exception Overhead Count Register Definitions */ #define DWT_EXCCNT_EXCCNT_Pos 0 /*!< DWT EXCCNT: EXCCNT Position */ #define DWT_EXCCNT_EXCCNT_Msk (0xFFUL /*<< DWT_EXCCNT_EXCCNT_Pos*/) /*!< DWT EXCCNT: EXCCNT Mask */ /* DWT Sleep Count Register Definitions */ #define DWT_SLEEPCNT_SLEEPCNT_Pos 0 /*!< DWT SLEEPCNT: SLEEPCNT Position */ #define DWT_SLEEPCNT_SLEEPCNT_Msk (0xFFUL /*<< DWT_SLEEPCNT_SLEEPCNT_Pos*/) /*!< DWT SLEEPCNT: SLEEPCNT Mask */ /* DWT LSU Count Register Definitions */ #define DWT_LSUCNT_LSUCNT_Pos 0 /*!< DWT LSUCNT: LSUCNT Position */ #define DWT_LSUCNT_LSUCNT_Msk (0xFFUL /*<< DWT_LSUCNT_LSUCNT_Pos*/) /*!< DWT LSUCNT: LSUCNT Mask */ /* DWT Folded-instruction Count Register Definitions */ #define DWT_FOLDCNT_FOLDCNT_Pos 0 /*!< DWT FOLDCNT: FOLDCNT Position */ #define DWT_FOLDCNT_FOLDCNT_Msk (0xFFUL /*<< DWT_FOLDCNT_FOLDCNT_Pos*/) /*!< DWT FOLDCNT: FOLDCNT Mask */ /* DWT Comparator Mask Register Definitions */ #define DWT_MASK_MASK_Pos 0 /*!< DWT MASK: MASK Position */ #define DWT_MASK_MASK_Msk (0x1FUL /*<< DWT_MASK_MASK_Pos*/) /*!< DWT MASK: MASK Mask */ /* DWT Comparator Function Register Definitions */ #define DWT_FUNCTION_MATCHED_Pos 24 /*!< DWT FUNCTION: MATCHED Position */ #define DWT_FUNCTION_MATCHED_Msk (0x1UL << DWT_FUNCTION_MATCHED_Pos) /*!< DWT FUNCTION: MATCHED Mask */ #define DWT_FUNCTION_DATAVADDR1_Pos 16 /*!< DWT FUNCTION: DATAVADDR1 Position */ #define DWT_FUNCTION_DATAVADDR1_Msk (0xFUL << DWT_FUNCTION_DATAVADDR1_Pos) /*!< DWT FUNCTION: DATAVADDR1 Mask */ #define DWT_FUNCTION_DATAVADDR0_Pos 12 /*!< DWT FUNCTION: DATAVADDR0 Position */ #define DWT_FUNCTION_DATAVADDR0_Msk (0xFUL << DWT_FUNCTION_DATAVADDR0_Pos) /*!< DWT FUNCTION: DATAVADDR0 Mask */ #define DWT_FUNCTION_DATAVSIZE_Pos 10 /*!< DWT FUNCTION: DATAVSIZE Position */ #define DWT_FUNCTION_DATAVSIZE_Msk (0x3UL << DWT_FUNCTION_DATAVSIZE_Pos) /*!< DWT FUNCTION: DATAVSIZE Mask */ #define DWT_FUNCTION_LNK1ENA_Pos 9 /*!< DWT FUNCTION: LNK1ENA Position */ #define DWT_FUNCTION_LNK1ENA_Msk (0x1UL << DWT_FUNCTION_LNK1ENA_Pos) /*!< DWT FUNCTION: LNK1ENA Mask */ #define DWT_FUNCTION_DATAVMATCH_Pos 8 /*!< DWT FUNCTION: DATAVMATCH Position */ #define DWT_FUNCTION_DATAVMATCH_Msk (0x1UL << DWT_FUNCTION_DATAVMATCH_Pos) /*!< DWT FUNCTION: DATAVMATCH Mask */ #define DWT_FUNCTION_CYCMATCH_Pos 7 /*!< DWT FUNCTION: CYCMATCH Position */ #define DWT_FUNCTION_CYCMATCH_Msk (0x1UL << DWT_FUNCTION_CYCMATCH_Pos) /*!< DWT FUNCTION: CYCMATCH Mask */ #define DWT_FUNCTION_EMITRANGE_Pos 5 /*!< DWT FUNCTION: EMITRANGE Position */ #define DWT_FUNCTION_EMITRANGE_Msk (0x1UL << DWT_FUNCTION_EMITRANGE_Pos) /*!< DWT FUNCTION: EMITRANGE Mask */ #define DWT_FUNCTION_FUNCTION_Pos 0 /*!< DWT FUNCTION: FUNCTION Position */ #define DWT_FUNCTION_FUNCTION_Msk (0xFUL /*<< DWT_FUNCTION_FUNCTION_Pos*/) /*!< DWT FUNCTION: FUNCTION Mask */ /*@}*/ /* end of group CMSIS_DWT */ /** \ingroup CMSIS_core_register \defgroup CMSIS_TPI Trace Port Interface (TPI) \brief Type definitions for the Trace Port Interface (TPI) @{ */ /** \brief Structure type to access the Trace Port Interface Register (TPI). */ typedef struct { __IO uint32_t SSPSR; /*!< Offset: 0x000 (R/ ) Supported Parallel Port Size Register */ __IO uint32_t CSPSR; /*!< Offset: 0x004 (R/W) Current Parallel Port Size Register */ uint32_t RESERVED0[2]; __IO uint32_t ACPR; /*!< Offset: 0x010 (R/W) Asynchronous Clock Prescaler Register */ uint32_t RESERVED1[55]; __IO uint32_t SPPR; /*!< Offset: 0x0F0 (R/W) Selected Pin Protocol Register */ uint32_t RESERVED2[131]; __I uint32_t FFSR; /*!< Offset: 0x300 (R/ ) Formatter and Flush Status Register */ __IO uint32_t FFCR; /*!< Offset: 0x304 (R/W) Formatter and Flush Control Register */ __I uint32_t FSCR; /*!< Offset: 0x308 (R/ ) Formatter Synchronization Counter Register */ uint32_t RESERVED3[759]; __I uint32_t TRIGGER; /*!< Offset: 0xEE8 (R/ ) TRIGGER */ __I uint32_t FIFO0; /*!< Offset: 0xEEC (R/ ) Integration ETM Data */ __I uint32_t ITATBCTR2; /*!< Offset: 0xEF0 (R/ ) ITATBCTR2 */ uint32_t RESERVED4[1]; __I uint32_t ITATBCTR0; /*!< Offset: 0xEF8 (R/ ) ITATBCTR0 */ __I uint32_t FIFO1; /*!< Offset: 0xEFC (R/ ) Integration ITM Data */ __IO uint32_t ITCTRL; /*!< Offset: 0xF00 (R/W) Integration Mode Control */ uint32_t RESERVED5[39]; __IO uint32_t CLAIMSET; /*!< Offset: 0xFA0 (R/W) Claim tag set */ __IO uint32_t CLAIMCLR; /*!< Offset: 0xFA4 (R/W) Claim tag clear */ uint32_t RESERVED7[8]; __I uint32_t DEVID; /*!< Offset: 0xFC8 (R/ ) TPIU_DEVID */ __I uint32_t DEVTYPE; /*!< Offset: 0xFCC (R/ ) TPIU_DEVTYPE */ } TPI_Type; /* TPI Asynchronous Clock Prescaler Register Definitions */ #define TPI_ACPR_PRESCALER_Pos 0 /*!< TPI ACPR: PRESCALER Position */ #define TPI_ACPR_PRESCALER_Msk (0x1FFFUL /*<< TPI_ACPR_PRESCALER_Pos*/) /*!< TPI ACPR: PRESCALER Mask */ /* TPI Selected Pin Protocol Register Definitions */ #define TPI_SPPR_TXMODE_Pos 0 /*!< TPI SPPR: TXMODE Position */ #define TPI_SPPR_TXMODE_Msk (0x3UL /*<< TPI_SPPR_TXMODE_Pos*/) /*!< TPI SPPR: TXMODE Mask */ /* TPI Formatter and Flush Status Register Definitions */ #define TPI_FFSR_FtNonStop_Pos 3 /*!< TPI FFSR: FtNonStop Position */ #define TPI_FFSR_FtNonStop_Msk (0x1UL << TPI_FFSR_FtNonStop_Pos) /*!< TPI FFSR: FtNonStop Mask */ #define TPI_FFSR_TCPresent_Pos 2 /*!< TPI FFSR: TCPresent Position */ #define TPI_FFSR_TCPresent_Msk (0x1UL << TPI_FFSR_TCPresent_Pos) /*!< TPI FFSR: TCPresent Mask */ #define TPI_FFSR_FtStopped_Pos 1 /*!< TPI FFSR: FtStopped Position */ #define TPI_FFSR_FtStopped_Msk (0x1UL << TPI_FFSR_FtStopped_Pos) /*!< TPI FFSR: FtStopped Mask */ #define TPI_FFSR_FlInProg_Pos 0 /*!< TPI FFSR: FlInProg Position */ #define TPI_FFSR_FlInProg_Msk (0x1UL /*<< TPI_FFSR_FlInProg_Pos*/) /*!< TPI FFSR: FlInProg Mask */ /* TPI Formatter and Flush Control Register Definitions */ #define TPI_FFCR_TrigIn_Pos 8 /*!< TPI FFCR: TrigIn Position */ #define TPI_FFCR_TrigIn_Msk (0x1UL << TPI_FFCR_TrigIn_Pos) /*!< TPI FFCR: TrigIn Mask */ #define TPI_FFCR_EnFCont_Pos 1 /*!< TPI FFCR: EnFCont Position */ #define TPI_FFCR_EnFCont_Msk (0x1UL << TPI_FFCR_EnFCont_Pos) /*!< TPI FFCR: EnFCont Mask */ /* TPI TRIGGER Register Definitions */ #define TPI_TRIGGER_TRIGGER_Pos 0 /*!< TPI TRIGGER: TRIGGER Position */ #define TPI_TRIGGER_TRIGGER_Msk (0x1UL /*<< TPI_TRIGGER_TRIGGER_Pos*/) /*!< TPI TRIGGER: TRIGGER Mask */ /* TPI Integration ETM Data Register Definitions (FIFO0) */ #define TPI_FIFO0_ITM_ATVALID_Pos 29 /*!< TPI FIFO0: ITM_ATVALID Position */ #define TPI_FIFO0_ITM_ATVALID_Msk (0x3UL << TPI_FIFO0_ITM_ATVALID_Pos) /*!< TPI FIFO0: ITM_ATVALID Mask */ #define TPI_FIFO0_ITM_bytecount_Pos 27 /*!< TPI FIFO0: ITM_bytecount Position */ #define TPI_FIFO0_ITM_bytecount_Msk (0x3UL << TPI_FIFO0_ITM_bytecount_Pos) /*!< TPI FIFO0: ITM_bytecount Mask */ #define TPI_FIFO0_ETM_ATVALID_Pos 26 /*!< TPI FIFO0: ETM_ATVALID Position */ #define TPI_FIFO0_ETM_ATVALID_Msk (0x3UL << TPI_FIFO0_ETM_ATVALID_Pos) /*!< TPI FIFO0: ETM_ATVALID Mask */ #define TPI_FIFO0_ETM_bytecount_Pos 24 /*!< TPI FIFO0: ETM_bytecount Position */ #define TPI_FIFO0_ETM_bytecount_Msk (0x3UL << TPI_FIFO0_ETM_bytecount_Pos) /*!< TPI FIFO0: ETM_bytecount Mask */ #define TPI_FIFO0_ETM2_Pos 16 /*!< TPI FIFO0: ETM2 Position */ #define TPI_FIFO0_ETM2_Msk (0xFFUL << TPI_FIFO0_ETM2_Pos) /*!< TPI FIFO0: ETM2 Mask */ #define TPI_FIFO0_ETM1_Pos 8 /*!< TPI FIFO0: ETM1 Position */ #define TPI_FIFO0_ETM1_Msk (0xFFUL << TPI_FIFO0_ETM1_Pos) /*!< TPI FIFO0: ETM1 Mask */ #define TPI_FIFO0_ETM0_Pos 0 /*!< TPI FIFO0: ETM0 Position */ #define TPI_FIFO0_ETM0_Msk (0xFFUL /*<< TPI_FIFO0_ETM0_Pos*/) /*!< TPI FIFO0: ETM0 Mask */ /* TPI ITATBCTR2 Register Definitions */ #define TPI_ITATBCTR2_ATREADY_Pos 0 /*!< TPI ITATBCTR2: ATREADY Position */ #define TPI_ITATBCTR2_ATREADY_Msk (0x1UL /*<< TPI_ITATBCTR2_ATREADY_Pos*/) /*!< TPI ITATBCTR2: ATREADY Mask */ /* TPI Integration ITM Data Register Definitions (FIFO1) */ #define TPI_FIFO1_ITM_ATVALID_Pos 29 /*!< TPI FIFO1: ITM_ATVALID Position */ #define TPI_FIFO1_ITM_ATVALID_Msk (0x3UL << TPI_FIFO1_ITM_ATVALID_Pos) /*!< TPI FIFO1: ITM_ATVALID Mask */ #define TPI_FIFO1_ITM_bytecount_Pos 27 /*!< TPI FIFO1: ITM_bytecount Position */ #define TPI_FIFO1_ITM_bytecount_Msk (0x3UL << TPI_FIFO1_ITM_bytecount_Pos) /*!< TPI FIFO1: ITM_bytecount Mask */ #define TPI_FIFO1_ETM_ATVALID_Pos 26 /*!< TPI FIFO1: ETM_ATVALID Position */ #define TPI_FIFO1_ETM_ATVALID_Msk (0x3UL << TPI_FIFO1_ETM_ATVALID_Pos) /*!< TPI FIFO1: ETM_ATVALID Mask */ #define TPI_FIFO1_ETM_bytecount_Pos 24 /*!< TPI FIFO1: ETM_bytecount Position */ #define TPI_FIFO1_ETM_bytecount_Msk (0x3UL << TPI_FIFO1_ETM_bytecount_Pos) /*!< TPI FIFO1: ETM_bytecount Mask */ #define TPI_FIFO1_ITM2_Pos 16 /*!< TPI FIFO1: ITM2 Position */ #define TPI_FIFO1_ITM2_Msk (0xFFUL << TPI_FIFO1_ITM2_Pos) /*!< TPI FIFO1: ITM2 Mask */ #define TPI_FIFO1_ITM1_Pos 8 /*!< TPI FIFO1: ITM1 Position */ #define TPI_FIFO1_ITM1_Msk (0xFFUL << TPI_FIFO1_ITM1_Pos) /*!< TPI FIFO1: ITM1 Mask */ #define TPI_FIFO1_ITM0_Pos 0 /*!< TPI FIFO1: ITM0 Position */ #define TPI_FIFO1_ITM0_Msk (0xFFUL /*<< TPI_FIFO1_ITM0_Pos*/) /*!< TPI FIFO1: ITM0 Mask */ /* TPI ITATBCTR0 Register Definitions */ #define TPI_ITATBCTR0_ATREADY_Pos 0 /*!< TPI ITATBCTR0: ATREADY Position */ #define TPI_ITATBCTR0_ATREADY_Msk (0x1UL /*<< TPI_ITATBCTR0_ATREADY_Pos*/) /*!< TPI ITATBCTR0: ATREADY Mask */ /* TPI Integration Mode Control Register Definitions */ #define TPI_ITCTRL_Mode_Pos 0 /*!< TPI ITCTRL: Mode Position */ #define TPI_ITCTRL_Mode_Msk (0x1UL /*<< TPI_ITCTRL_Mode_Pos*/) /*!< TPI ITCTRL: Mode Mask */ /* TPI DEVID Register Definitions */ #define TPI_DEVID_NRZVALID_Pos 11 /*!< TPI DEVID: NRZVALID Position */ #define TPI_DEVID_NRZVALID_Msk (0x1UL << TPI_DEVID_NRZVALID_Pos) /*!< TPI DEVID: NRZVALID Mask */ #define TPI_DEVID_MANCVALID_Pos 10 /*!< TPI DEVID: MANCVALID Position */ #define TPI_DEVID_MANCVALID_Msk (0x1UL << TPI_DEVID_MANCVALID_Pos) /*!< TPI DEVID: MANCVALID Mask */ #define TPI_DEVID_PTINVALID_Pos 9 /*!< TPI DEVID: PTINVALID Position */ #define TPI_DEVID_PTINVALID_Msk (0x1UL << TPI_DEVID_PTINVALID_Pos) /*!< TPI DEVID: PTINVALID Mask */ #define TPI_DEVID_MinBufSz_Pos 6 /*!< TPI DEVID: MinBufSz Position */ #define TPI_DEVID_MinBufSz_Msk (0x7UL << TPI_DEVID_MinBufSz_Pos) /*!< TPI DEVID: MinBufSz Mask */ #define TPI_DEVID_AsynClkIn_Pos 5 /*!< TPI DEVID: AsynClkIn Position */ #define TPI_DEVID_AsynClkIn_Msk (0x1UL << TPI_DEVID_AsynClkIn_Pos) /*!< TPI DEVID: AsynClkIn Mask */ #define TPI_DEVID_NrTraceInput_Pos 0 /*!< TPI DEVID: NrTraceInput Position */ #define TPI_DEVID_NrTraceInput_Msk (0x1FUL /*<< TPI_DEVID_NrTraceInput_Pos*/) /*!< TPI DEVID: NrTraceInput Mask */ /* TPI DEVTYPE Register Definitions */ #define TPI_DEVTYPE_MajorType_Pos 4 /*!< TPI DEVTYPE: MajorType Position */ #define TPI_DEVTYPE_MajorType_Msk (0xFUL << TPI_DEVTYPE_MajorType_Pos) /*!< TPI DEVTYPE: MajorType Mask */ #define TPI_DEVTYPE_SubType_Pos 0 /*!< TPI DEVTYPE: SubType Position */ #define TPI_DEVTYPE_SubType_Msk (0xFUL /*<< TPI_DEVTYPE_SubType_Pos*/) /*!< TPI DEVTYPE: SubType Mask */ /*@}*/ /* end of group CMSIS_TPI */ #if (__MPU_PRESENT == 1) /** \ingroup CMSIS_core_register \defgroup CMSIS_MPU Memory Protection Unit (MPU) \brief Type definitions for the Memory Protection Unit (MPU) @{ */ /** \brief Structure type to access the Memory Protection Unit (MPU). */ typedef struct { __I uint32_t TYPE; /*!< Offset: 0x000 (R/ ) MPU Type Register */ __IO uint32_t CTRL; /*!< Offset: 0x004 (R/W) MPU Control Register */ __IO uint32_t RNR; /*!< Offset: 0x008 (R/W) MPU Region RNRber Register */ __IO uint32_t RBAR; /*!< Offset: 0x00C (R/W) MPU Region Base Address Register */ __IO uint32_t RASR; /*!< Offset: 0x010 (R/W) MPU Region Attribute and Size Register */ __IO uint32_t RBAR_A1; /*!< Offset: 0x014 (R/W) MPU Alias 1 Region Base Address Register */ __IO uint32_t RASR_A1; /*!< Offset: 0x018 (R/W) MPU Alias 1 Region Attribute and Size Register */ __IO uint32_t RBAR_A2; /*!< Offset: 0x01C (R/W) MPU Alias 2 Region Base Address Register */ __IO uint32_t RASR_A2; /*!< Offset: 0x020 (R/W) MPU Alias 2 Region Attribute and Size Register */ __IO uint32_t RBAR_A3; /*!< Offset: 0x024 (R/W) MPU Alias 3 Region Base Address Register */ __IO uint32_t RASR_A3; /*!< Offset: 0x028 (R/W) MPU Alias 3 Region Attribute and Size Register */ } MPU_Type; /* MPU Type Register */ #define MPU_TYPE_IREGION_Pos 16 /*!< MPU TYPE: IREGION Position */ #define MPU_TYPE_IREGION_Msk (0xFFUL << MPU_TYPE_IREGION_Pos) /*!< MPU TYPE: IREGION Mask */ #define MPU_TYPE_DREGION_Pos 8 /*!< MPU TYPE: DREGION Position */ #define MPU_TYPE_DREGION_Msk (0xFFUL << MPU_TYPE_DREGION_Pos) /*!< MPU TYPE: DREGION Mask */ #define MPU_TYPE_SEPARATE_Pos 0 /*!< MPU TYPE: SEPARATE Position */ #define MPU_TYPE_SEPARATE_Msk (1UL /*<< MPU_TYPE_SEPARATE_Pos*/) /*!< MPU TYPE: SEPARATE Mask */ /* MPU Control Register */ #define MPU_CTRL_PRIVDEFENA_Pos 2 /*!< MPU CTRL: PRIVDEFENA Position */ #define MPU_CTRL_PRIVDEFENA_Msk (1UL << MPU_CTRL_PRIVDEFENA_Pos) /*!< MPU CTRL: PRIVDEFENA Mask */ #define MPU_CTRL_HFNMIENA_Pos 1 /*!< MPU CTRL: HFNMIENA Position */ #define MPU_CTRL_HFNMIENA_Msk (1UL << MPU_CTRL_HFNMIENA_Pos) /*!< MPU CTRL: HFNMIENA Mask */ #define MPU_CTRL_ENABLE_Pos 0 /*!< MPU CTRL: ENABLE Position */ #define MPU_CTRL_ENABLE_Msk (1UL /*<< MPU_CTRL_ENABLE_Pos*/) /*!< MPU CTRL: ENABLE Mask */ /* MPU Region Number Register */ #define MPU_RNR_REGION_Pos 0 /*!< MPU RNR: REGION Position */ #define MPU_RNR_REGION_Msk (0xFFUL /*<< MPU_RNR_REGION_Pos*/) /*!< MPU RNR: REGION Mask */ /* MPU Region Base Address Register */ #define MPU_RBAR_ADDR_Pos 5 /*!< MPU RBAR: ADDR Position */ #define MPU_RBAR_ADDR_Msk (0x7FFFFFFUL << MPU_RBAR_ADDR_Pos) /*!< MPU RBAR: ADDR Mask */ #define MPU_RBAR_VALID_Pos 4 /*!< MPU RBAR: VALID Position */ #define MPU_RBAR_VALID_Msk (1UL << MPU_RBAR_VALID_Pos) /*!< MPU RBAR: VALID Mask */ #define MPU_RBAR_REGION_Pos 0 /*!< MPU RBAR: REGION Position */ #define MPU_RBAR_REGION_Msk (0xFUL /*<< MPU_RBAR_REGION_Pos*/) /*!< MPU RBAR: REGION Mask */ /* MPU Region Attribute and Size Register */ #define MPU_RASR_ATTRS_Pos 16 /*!< MPU RASR: MPU Region Attribute field Position */ #define MPU_RASR_ATTRS_Msk (0xFFFFUL << MPU_RASR_ATTRS_Pos) /*!< MPU RASR: MPU Region Attribute field Mask */ #define MPU_RASR_XN_Pos 28 /*!< MPU RASR: ATTRS.XN Position */ #define MPU_RASR_XN_Msk (1UL << MPU_RASR_XN_Pos) /*!< MPU RASR: ATTRS.XN Mask */ #define MPU_RASR_AP_Pos 24 /*!< MPU RASR: ATTRS.AP Position */ #define MPU_RASR_AP_Msk (0x7UL << MPU_RASR_AP_Pos) /*!< MPU RASR: ATTRS.AP Mask */ #define MPU_RASR_TEX_Pos 19 /*!< MPU RASR: ATTRS.TEX Position */ #define MPU_RASR_TEX_Msk (0x7UL << MPU_RASR_TEX_Pos) /*!< MPU RASR: ATTRS.TEX Mask */ #define MPU_RASR_S_Pos 18 /*!< MPU RASR: ATTRS.S Position */ #define MPU_RASR_S_Msk (1UL << MPU_RASR_S_Pos) /*!< MPU RASR: ATTRS.S Mask */ #define MPU_RASR_C_Pos 17 /*!< MPU RASR: ATTRS.C Position */ #define MPU_RASR_C_Msk (1UL << MPU_RASR_C_Pos) /*!< MPU RASR: ATTRS.C Mask */ #define MPU_RASR_B_Pos 16 /*!< MPU RASR: ATTRS.B Position */ #define MPU_RASR_B_Msk (1UL << MPU_RASR_B_Pos) /*!< MPU RASR: ATTRS.B Mask */ #define MPU_RASR_SRD_Pos 8 /*!< MPU RASR: Sub-Region Disable Position */ #define MPU_RASR_SRD_Msk (0xFFUL << MPU_RASR_SRD_Pos) /*!< MPU RASR: Sub-Region Disable Mask */ #define MPU_RASR_SIZE_Pos 1 /*!< MPU RASR: Region Size Field Position */ #define MPU_RASR_SIZE_Msk (0x1FUL << MPU_RASR_SIZE_Pos) /*!< MPU RASR: Region Size Field Mask */ #define MPU_RASR_ENABLE_Pos 0 /*!< MPU RASR: Region enable bit Position */ #define MPU_RASR_ENABLE_Msk (1UL /*<< MPU_RASR_ENABLE_Pos*/) /*!< MPU RASR: Region enable bit Disable Mask */ /*@} end of group CMSIS_MPU */ #endif #if (__FPU_PRESENT == 1) /** \ingroup CMSIS_core_register \defgroup CMSIS_FPU Floating Point Unit (FPU) \brief Type definitions for the Floating Point Unit (FPU) @{ */ /** \brief Structure type to access the Floating Point Unit (FPU). */ typedef struct { uint32_t RESERVED0[1]; __IO uint32_t FPCCR; /*!< Offset: 0x004 (R/W) Floating-Point Context Control Register */ __IO uint32_t FPCAR; /*!< Offset: 0x008 (R/W) Floating-Point Context Address Register */ __IO uint32_t FPDSCR; /*!< Offset: 0x00C (R/W) Floating-Point Default Status Control Register */ __I uint32_t MVFR0; /*!< Offset: 0x010 (R/ ) Media and FP Feature Register 0 */ __I uint32_t MVFR1; /*!< Offset: 0x014 (R/ ) Media and FP Feature Register 1 */ } FPU_Type; /* Floating-Point Context Control Register */ #define FPU_FPCCR_ASPEN_Pos 31 /*!< FPCCR: ASPEN bit Position */ #define FPU_FPCCR_ASPEN_Msk (1UL << FPU_FPCCR_ASPEN_Pos) /*!< FPCCR: ASPEN bit Mask */ #define FPU_FPCCR_LSPEN_Pos 30 /*!< FPCCR: LSPEN Position */ #define FPU_FPCCR_LSPEN_Msk (1UL << FPU_FPCCR_LSPEN_Pos) /*!< FPCCR: LSPEN bit Mask */ #define FPU_FPCCR_MONRDY_Pos 8 /*!< FPCCR: MONRDY Position */ #define FPU_FPCCR_MONRDY_Msk (1UL << FPU_FPCCR_MONRDY_Pos) /*!< FPCCR: MONRDY bit Mask */ #define FPU_FPCCR_BFRDY_Pos 6 /*!< FPCCR: BFRDY Position */ #define FPU_FPCCR_BFRDY_Msk (1UL << FPU_FPCCR_BFRDY_Pos) /*!< FPCCR: BFRDY bit Mask */ #define FPU_FPCCR_MMRDY_Pos 5 /*!< FPCCR: MMRDY Position */ #define FPU_FPCCR_MMRDY_Msk (1UL << FPU_FPCCR_MMRDY_Pos) /*!< FPCCR: MMRDY bit Mask */ #define FPU_FPCCR_HFRDY_Pos 4 /*!< FPCCR: HFRDY Position */ #define FPU_FPCCR_HFRDY_Msk (1UL << FPU_FPCCR_HFRDY_Pos) /*!< FPCCR: HFRDY bit Mask */ #define FPU_FPCCR_THREAD_Pos 3 /*!< FPCCR: processor mode bit Position */ #define FPU_FPCCR_THREAD_Msk (1UL << FPU_FPCCR_THREAD_Pos) /*!< FPCCR: processor mode active bit Mask */ #define FPU_FPCCR_USER_Pos 1 /*!< FPCCR: privilege level bit Position */ #define FPU_FPCCR_USER_Msk (1UL << FPU_FPCCR_USER_Pos) /*!< FPCCR: privilege level bit Mask */ #define FPU_FPCCR_LSPACT_Pos 0 /*!< FPCCR: Lazy state preservation active bit Position */ #define FPU_FPCCR_LSPACT_Msk (1UL /*<< FPU_FPCCR_LSPACT_Pos*/) /*!< FPCCR: Lazy state preservation active bit Mask */ /* Floating-Point Context Address Register */ #define FPU_FPCAR_ADDRESS_Pos 3 /*!< FPCAR: ADDRESS bit Position */ #define FPU_FPCAR_ADDRESS_Msk (0x1FFFFFFFUL << FPU_FPCAR_ADDRESS_Pos) /*!< FPCAR: ADDRESS bit Mask */ /* Floating-Point Default Status Control Register */ #define FPU_FPDSCR_AHP_Pos 26 /*!< FPDSCR: AHP bit Position */ #define FPU_FPDSCR_AHP_Msk (1UL << FPU_FPDSCR_AHP_Pos) /*!< FPDSCR: AHP bit Mask */ #define FPU_FPDSCR_DN_Pos 25 /*!< FPDSCR: DN bit Position */ #define FPU_FPDSCR_DN_Msk (1UL << FPU_FPDSCR_DN_Pos) /*!< FPDSCR: DN bit Mask */ #define FPU_FPDSCR_FZ_Pos 24 /*!< FPDSCR: FZ bit Position */ #define FPU_FPDSCR_FZ_Msk (1UL << FPU_FPDSCR_FZ_Pos) /*!< FPDSCR: FZ bit Mask */ #define FPU_FPDSCR_RMode_Pos 22 /*!< FPDSCR: RMode bit Position */ #define FPU_FPDSCR_RMode_Msk (3UL << FPU_FPDSCR_RMode_Pos) /*!< FPDSCR: RMode bit Mask */ /* Media and FP Feature Register 0 */ #define FPU_MVFR0_FP_rounding_modes_Pos 28 /*!< MVFR0: FP rounding modes bits Position */ #define FPU_MVFR0_FP_rounding_modes_Msk (0xFUL << FPU_MVFR0_FP_rounding_modes_Pos) /*!< MVFR0: FP rounding modes bits Mask */ #define FPU_MVFR0_Short_vectors_Pos 24 /*!< MVFR0: Short vectors bits Position */ #define FPU_MVFR0_Short_vectors_Msk (0xFUL << FPU_MVFR0_Short_vectors_Pos) /*!< MVFR0: Short vectors bits Mask */ #define FPU_MVFR0_Square_root_Pos 20 /*!< MVFR0: Square root bits Position */ #define FPU_MVFR0_Square_root_Msk (0xFUL << FPU_MVFR0_Square_root_Pos) /*!< MVFR0: Square root bits Mask */ #define FPU_MVFR0_Divide_Pos 16 /*!< MVFR0: Divide bits Position */ #define FPU_MVFR0_Divide_Msk (0xFUL << FPU_MVFR0_Divide_Pos) /*!< MVFR0: Divide bits Mask */ #define FPU_MVFR0_FP_excep_trapping_Pos 12 /*!< MVFR0: FP exception trapping bits Position */ #define FPU_MVFR0_FP_excep_trapping_Msk (0xFUL << FPU_MVFR0_FP_excep_trapping_Pos) /*!< MVFR0: FP exception trapping bits Mask */ #define FPU_MVFR0_Double_precision_Pos 8 /*!< MVFR0: Double-precision bits Position */ #define FPU_MVFR0_Double_precision_Msk (0xFUL << FPU_MVFR0_Double_precision_Pos) /*!< MVFR0: Double-precision bits Mask */ #define FPU_MVFR0_Single_precision_Pos 4 /*!< MVFR0: Single-precision bits Position */ #define FPU_MVFR0_Single_precision_Msk (0xFUL << FPU_MVFR0_Single_precision_Pos) /*!< MVFR0: Single-precision bits Mask */ #define FPU_MVFR0_A_SIMD_registers_Pos 0 /*!< MVFR0: A_SIMD registers bits Position */ #define FPU_MVFR0_A_SIMD_registers_Msk (0xFUL /*<< FPU_MVFR0_A_SIMD_registers_Pos*/) /*!< MVFR0: A_SIMD registers bits Mask */ /* Media and FP Feature Register 1 */ #define FPU_MVFR1_FP_fused_MAC_Pos 28 /*!< MVFR1: FP fused MAC bits Position */ #define FPU_MVFR1_FP_fused_MAC_Msk (0xFUL << FPU_MVFR1_FP_fused_MAC_Pos) /*!< MVFR1: FP fused MAC bits Mask */ #define FPU_MVFR1_FP_HPFP_Pos 24 /*!< MVFR1: FP HPFP bits Position */ #define FPU_MVFR1_FP_HPFP_Msk (0xFUL << FPU_MVFR1_FP_HPFP_Pos) /*!< MVFR1: FP HPFP bits Mask */ #define FPU_MVFR1_D_NaN_mode_Pos 4 /*!< MVFR1: D_NaN mode bits Position */ #define FPU_MVFR1_D_NaN_mode_Msk (0xFUL << FPU_MVFR1_D_NaN_mode_Pos) /*!< MVFR1: D_NaN mode bits Mask */ #define FPU_MVFR1_FtZ_mode_Pos 0 /*!< MVFR1: FtZ mode bits Position */ #define FPU_MVFR1_FtZ_mode_Msk (0xFUL /*<< FPU_MVFR1_FtZ_mode_Pos*/) /*!< MVFR1: FtZ mode bits Mask */ /*@} end of group CMSIS_FPU */ #endif /** \ingroup CMSIS_core_register \defgroup CMSIS_CoreDebug Core Debug Registers (CoreDebug) \brief Type definitions for the Core Debug Registers @{ */ /** \brief Structure type to access the Core Debug Register (CoreDebug). */ typedef struct { __IO uint32_t DHCSR; /*!< Offset: 0x000 (R/W) Debug Halting Control and Status Register */ __O uint32_t DCRSR; /*!< Offset: 0x004 ( /W) Debug Core Register Selector Register */ __IO uint32_t DCRDR; /*!< Offset: 0x008 (R/W) Debug Core Register Data Register */ __IO uint32_t DEMCR; /*!< Offset: 0x00C (R/W) Debug Exception and Monitor Control Register */ } CoreDebug_Type; /* Debug Halting Control and Status Register */ #define CoreDebug_DHCSR_DBGKEY_Pos 16 /*!< CoreDebug DHCSR: DBGKEY Position */ #define CoreDebug_DHCSR_DBGKEY_Msk (0xFFFFUL << CoreDebug_DHCSR_DBGKEY_Pos) /*!< CoreDebug DHCSR: DBGKEY Mask */ #define CoreDebug_DHCSR_S_RESET_ST_Pos 25 /*!< CoreDebug DHCSR: S_RESET_ST Position */ #define CoreDebug_DHCSR_S_RESET_ST_Msk (1UL << CoreDebug_DHCSR_S_RESET_ST_Pos) /*!< CoreDebug DHCSR: S_RESET_ST Mask */ #define CoreDebug_DHCSR_S_RETIRE_ST_Pos 24 /*!< CoreDebug DHCSR: S_RETIRE_ST Position */ #define CoreDebug_DHCSR_S_RETIRE_ST_Msk (1UL << CoreDebug_DHCSR_S_RETIRE_ST_Pos) /*!< CoreDebug DHCSR: S_RETIRE_ST Mask */ #define CoreDebug_DHCSR_S_LOCKUP_Pos 19 /*!< CoreDebug DHCSR: S_LOCKUP Position */ #define CoreDebug_DHCSR_S_LOCKUP_Msk (1UL << CoreDebug_DHCSR_S_LOCKUP_Pos) /*!< CoreDebug DHCSR: S_LOCKUP Mask */ #define CoreDebug_DHCSR_S_SLEEP_Pos 18 /*!< CoreDebug DHCSR: S_SLEEP Position */ #define CoreDebug_DHCSR_S_SLEEP_Msk (1UL << CoreDebug_DHCSR_S_SLEEP_Pos) /*!< CoreDebug DHCSR: S_SLEEP Mask */ #define CoreDebug_DHCSR_S_HALT_Pos 17 /*!< CoreDebug DHCSR: S_HALT Position */ #define CoreDebug_DHCSR_S_HALT_Msk (1UL << CoreDebug_DHCSR_S_HALT_Pos) /*!< CoreDebug DHCSR: S_HALT Mask */ #define CoreDebug_DHCSR_S_REGRDY_Pos 16 /*!< CoreDebug DHCSR: S_REGRDY Position */ #define CoreDebug_DHCSR_S_REGRDY_Msk (1UL << CoreDebug_DHCSR_S_REGRDY_Pos) /*!< CoreDebug DHCSR: S_REGRDY Mask */ #define CoreDebug_DHCSR_C_SNAPSTALL_Pos 5 /*!< CoreDebug DHCSR: C_SNAPSTALL Position */ #define CoreDebug_DHCSR_C_SNAPSTALL_Msk (1UL << CoreDebug_DHCSR_C_SNAPSTALL_Pos) /*!< CoreDebug DHCSR: C_SNAPSTALL Mask */ #define CoreDebug_DHCSR_C_MASKINTS_Pos 3 /*!< CoreDebug DHCSR: C_MASKINTS Position */ #define CoreDebug_DHCSR_C_MASKINTS_Msk (1UL << CoreDebug_DHCSR_C_MASKINTS_Pos) /*!< CoreDebug DHCSR: C_MASKINTS Mask */ #define CoreDebug_DHCSR_C_STEP_Pos 2 /*!< CoreDebug DHCSR: C_STEP Position */ #define CoreDebug_DHCSR_C_STEP_Msk (1UL << CoreDebug_DHCSR_C_STEP_Pos) /*!< CoreDebug DHCSR: C_STEP Mask */ #define CoreDebug_DHCSR_C_HALT_Pos 1 /*!< CoreDebug DHCSR: C_HALT Position */ #define CoreDebug_DHCSR_C_HALT_Msk (1UL << CoreDebug_DHCSR_C_HALT_Pos) /*!< CoreDebug DHCSR: C_HALT Mask */ #define CoreDebug_DHCSR_C_DEBUGEN_Pos 0 /*!< CoreDebug DHCSR: C_DEBUGEN Position */ #define CoreDebug_DHCSR_C_DEBUGEN_Msk (1UL /*<< CoreDebug_DHCSR_C_DEBUGEN_Pos*/) /*!< CoreDebug DHCSR: C_DEBUGEN Mask */ /* Debug Core Register Selector Register */ #define CoreDebug_DCRSR_REGWnR_Pos 16 /*!< CoreDebug DCRSR: REGWnR Position */ #define CoreDebug_DCRSR_REGWnR_Msk (1UL << CoreDebug_DCRSR_REGWnR_Pos) /*!< CoreDebug DCRSR: REGWnR Mask */ #define CoreDebug_DCRSR_REGSEL_Pos 0 /*!< CoreDebug DCRSR: REGSEL Position */ #define CoreDebug_DCRSR_REGSEL_Msk (0x1FUL /*<< CoreDebug_DCRSR_REGSEL_Pos*/) /*!< CoreDebug DCRSR: REGSEL Mask */ /* Debug Exception and Monitor Control Register */ #define CoreDebug_DEMCR_TRCENA_Pos 24 /*!< CoreDebug DEMCR: TRCENA Position */ #define CoreDebug_DEMCR_TRCENA_Msk (1UL << CoreDebug_DEMCR_TRCENA_Pos) /*!< CoreDebug DEMCR: TRCENA Mask */ #define CoreDebug_DEMCR_MON_REQ_Pos 19 /*!< CoreDebug DEMCR: MON_REQ Position */ #define CoreDebug_DEMCR_MON_REQ_Msk (1UL << CoreDebug_DEMCR_MON_REQ_Pos) /*!< CoreDebug DEMCR: MON_REQ Mask */ #define CoreDebug_DEMCR_MON_STEP_Pos 18 /*!< CoreDebug DEMCR: MON_STEP Position */ #define CoreDebug_DEMCR_MON_STEP_Msk (1UL << CoreDebug_DEMCR_MON_STEP_Pos) /*!< CoreDebug DEMCR: MON_STEP Mask */ #define CoreDebug_DEMCR_MON_PEND_Pos 17 /*!< CoreDebug DEMCR: MON_PEND Position */ #define CoreDebug_DEMCR_MON_PEND_Msk (1UL << CoreDebug_DEMCR_MON_PEND_Pos) /*!< CoreDebug DEMCR: MON_PEND Mask */ #define CoreDebug_DEMCR_MON_EN_Pos 16 /*!< CoreDebug DEMCR: MON_EN Position */ #define CoreDebug_DEMCR_MON_EN_Msk (1UL << CoreDebug_DEMCR_MON_EN_Pos) /*!< CoreDebug DEMCR: MON_EN Mask */ #define CoreDebug_DEMCR_VC_HARDERR_Pos 10 /*!< CoreDebug DEMCR: VC_HARDERR Position */ #define CoreDebug_DEMCR_VC_HARDERR_Msk (1UL << CoreDebug_DEMCR_VC_HARDERR_Pos) /*!< CoreDebug DEMCR: VC_HARDERR Mask */ #define CoreDebug_DEMCR_VC_INTERR_Pos 9 /*!< CoreDebug DEMCR: VC_INTERR Position */ #define CoreDebug_DEMCR_VC_INTERR_Msk (1UL << CoreDebug_DEMCR_VC_INTERR_Pos) /*!< CoreDebug DEMCR: VC_INTERR Mask */ #define CoreDebug_DEMCR_VC_BUSERR_Pos 8 /*!< CoreDebug DEMCR: VC_BUSERR Position */ #define CoreDebug_DEMCR_VC_BUSERR_Msk (1UL << CoreDebug_DEMCR_VC_BUSERR_Pos) /*!< CoreDebug DEMCR: VC_BUSERR Mask */ #define CoreDebug_DEMCR_VC_STATERR_Pos 7 /*!< CoreDebug DEMCR: VC_STATERR Position */ #define CoreDebug_DEMCR_VC_STATERR_Msk (1UL << CoreDebug_DEMCR_VC_STATERR_Pos) /*!< CoreDebug DEMCR: VC_STATERR Mask */ #define CoreDebug_DEMCR_VC_CHKERR_Pos 6 /*!< CoreDebug DEMCR: VC_CHKERR Position */ #define CoreDebug_DEMCR_VC_CHKERR_Msk (1UL << CoreDebug_DEMCR_VC_CHKERR_Pos) /*!< CoreDebug DEMCR: VC_CHKERR Mask */ #define CoreDebug_DEMCR_VC_NOCPERR_Pos 5 /*!< CoreDebug DEMCR: VC_NOCPERR Position */ #define CoreDebug_DEMCR_VC_NOCPERR_Msk (1UL << CoreDebug_DEMCR_VC_NOCPERR_Pos) /*!< CoreDebug DEMCR: VC_NOCPERR Mask */ #define CoreDebug_DEMCR_VC_MMERR_Pos 4 /*!< CoreDebug DEMCR: VC_MMERR Position */ #define CoreDebug_DEMCR_VC_MMERR_Msk (1UL << CoreDebug_DEMCR_VC_MMERR_Pos) /*!< CoreDebug DEMCR: VC_MMERR Mask */ #define CoreDebug_DEMCR_VC_CORERESET_Pos 0 /*!< CoreDebug DEMCR: VC_CORERESET Position */ #define CoreDebug_DEMCR_VC_CORERESET_Msk (1UL /*<< CoreDebug_DEMCR_VC_CORERESET_Pos*/) /*!< CoreDebug DEMCR: VC_CORERESET Mask */ /*@} end of group CMSIS_CoreDebug */ /** \ingroup CMSIS_core_register \defgroup CMSIS_core_base Core Definitions \brief Definitions for base addresses, unions, and structures. @{ */ /* Memory mapping of Cortex-M4 Hardware */ #define SCS_BASE (0xE000E000UL) /*!< System Control Space Base Address */ #define ITM_BASE (0xE0000000UL) /*!< ITM Base Address */ #define DWT_BASE (0xE0001000UL) /*!< DWT Base Address */ #define TPI_BASE (0xE0040000UL) /*!< TPI Base Address */ #define CoreDebug_BASE (0xE000EDF0UL) /*!< Core Debug Base Address */ #define SysTick_BASE (SCS_BASE + 0x0010UL) /*!< SysTick Base Address */ #define NVIC_BASE (SCS_BASE + 0x0100UL) /*!< NVIC Base Address */ #define SCB_BASE (SCS_BASE + 0x0D00UL) /*!< System Control Block Base Address */ #define SCnSCB ((SCnSCB_Type *) SCS_BASE ) /*!< System control Register not in SCB */ #define SCB ((SCB_Type *) SCB_BASE ) /*!< SCB configuration struct */ #define SysTick ((SysTick_Type *) SysTick_BASE ) /*!< SysTick configuration struct */ #define NVIC ((NVIC_Type *) NVIC_BASE ) /*!< NVIC configuration struct */ #define ITM ((ITM_Type *) ITM_BASE ) /*!< ITM configuration struct */ #define DWT ((DWT_Type *) DWT_BASE ) /*!< DWT configuration struct */ #define TPI ((TPI_Type *) TPI_BASE ) /*!< TPI configuration struct */ #define CoreDebug ((CoreDebug_Type *) CoreDebug_BASE) /*!< Core Debug configuration struct */ #if (__MPU_PRESENT == 1) #define MPU_BASE (SCS_BASE + 0x0D90UL) /*!< Memory Protection Unit */ #define MPU ((MPU_Type *) MPU_BASE ) /*!< Memory Protection Unit */ #endif #if (__FPU_PRESENT == 1) #define FPU_BASE (SCS_BASE + 0x0F30UL) /*!< Floating Point Unit */ #define FPU ((FPU_Type *) FPU_BASE ) /*!< Floating Point Unit */ #endif /*@} */ /******************************************************************************* * Hardware Abstraction Layer Core Function Interface contains: - Core NVIC Functions - Core SysTick Functions - Core Debug Functions - Core Register Access Functions ******************************************************************************/ /** \defgroup CMSIS_Core_FunctionInterface Functions and Instructions Reference */ /* ########################## NVIC functions #################################### */ /** \ingroup CMSIS_Core_FunctionInterface \defgroup CMSIS_Core_NVICFunctions NVIC Functions \brief Functions that manage interrupts and exceptions via the NVIC. @{ */ /** \brief Set Priority Grouping The function sets the priority grouping field using the required unlock sequence. The parameter PriorityGroup is assigned to the field SCB->AIRCR [10:8] PRIGROUP field. Only values from 0..7 are used. In case of a conflict between priority grouping and available priority bits (__NVIC_PRIO_BITS), the smallest possible priority group is set. \param [in] PriorityGroup Priority grouping field. */ __STATIC_INLINE void NVIC_SetPriorityGrouping(uint32_t PriorityGroup) { uint32_t reg_value; uint32_t PriorityGroupTmp = (PriorityGroup & (uint32_t)0x07UL); /* only values 0..7 are used */ reg_value = SCB->AIRCR; /* read old register configuration */ reg_value &= ~((uint32_t)(SCB_AIRCR_VECTKEY_Msk | SCB_AIRCR_PRIGROUP_Msk)); /* clear bits to change */ reg_value = (reg_value | ((uint32_t)0x5FAUL << SCB_AIRCR_VECTKEY_Pos) | (PriorityGroupTmp << 8) ); /* Insert write key and priorty group */ SCB->AIRCR = reg_value; } /** \brief Get Priority Grouping The function reads the priority grouping field from the NVIC Interrupt Controller. \return Priority grouping field (SCB->AIRCR [10:8] PRIGROUP field). */ __STATIC_INLINE uint32_t NVIC_GetPriorityGrouping(void) { return ((uint32_t)((SCB->AIRCR & SCB_AIRCR_PRIGROUP_Msk) >> SCB_AIRCR_PRIGROUP_Pos)); } /** \brief Enable External Interrupt The function enables a device-specific interrupt in the NVIC interrupt controller. \param [in] IRQn External interrupt number. Value cannot be negative. */ __STATIC_INLINE void NVIC_EnableIRQ(IRQn_Type IRQn) { NVIC->ISER[(((uint32_t)(int32_t)IRQn) >> 5UL)] = (uint32_t)(1UL << (((uint32_t)(int32_t)IRQn) & 0x1FUL)); } /** \brief Disable External Interrupt The function disables a device-specific interrupt in the NVIC interrupt controller. \param [in] IRQn External interrupt number. Value cannot be negative. */ __STATIC_INLINE void NVIC_DisableIRQ(IRQn_Type IRQn) { NVIC->ICER[(((uint32_t)(int32_t)IRQn) >> 5UL)] = (uint32_t)(1UL << (((uint32_t)(int32_t)IRQn) & 0x1FUL)); } /** \brief Get Pending Interrupt The function reads the pending register in the NVIC and returns the pending bit for the specified interrupt. \param [in] IRQn Interrupt number. \return 0 Interrupt status is not pending. \return 1 Interrupt status is pending. */ __STATIC_INLINE uint32_t NVIC_GetPendingIRQ(IRQn_Type IRQn) { return((uint32_t)(((NVIC->ISPR[(((uint32_t)(int32_t)IRQn) >> 5UL)] & (1UL << (((uint32_t)(int32_t)IRQn) & 0x1FUL))) != 0UL) ? 1UL : 0UL)); } /** \brief Set Pending Interrupt The function sets the pending bit of an external interrupt. \param [in] IRQn Interrupt number. Value cannot be negative. */ __STATIC_INLINE void NVIC_SetPendingIRQ(IRQn_Type IRQn) { NVIC->ISPR[(((uint32_t)(int32_t)IRQn) >> 5UL)] = (uint32_t)(1UL << (((uint32_t)(int32_t)IRQn) & 0x1FUL)); } /** \brief Clear Pending Interrupt The function clears the pending bit of an external interrupt. \param [in] IRQn External interrupt number. Value cannot be negative. */ __STATIC_INLINE void NVIC_ClearPendingIRQ(IRQn_Type IRQn) { NVIC->ICPR[(((uint32_t)(int32_t)IRQn) >> 5UL)] = (uint32_t)(1UL << (((uint32_t)(int32_t)IRQn) & 0x1FUL)); } /** \brief Get Active Interrupt The function reads the active register in NVIC and returns the active bit. \param [in] IRQn Interrupt number. \return 0 Interrupt status is not active. \return 1 Interrupt status is active. */ __STATIC_INLINE uint32_t NVIC_GetActive(IRQn_Type IRQn) { return((uint32_t)(((NVIC->IABR[(((uint32_t)(int32_t)IRQn) >> 5UL)] & (1UL << (((uint32_t)(int32_t)IRQn) & 0x1FUL))) != 0UL) ? 1UL : 0UL)); } /** \brief Set Interrupt Priority The function sets the priority of an interrupt. \note The priority cannot be set for every core interrupt. \param [in] IRQn Interrupt number. \param [in] priority Priority to set. */ __STATIC_INLINE void NVIC_SetPriority(IRQn_Type IRQn, uint32_t priority) { if((int32_t)IRQn < 0) { SCB->SHP[(((uint32_t)(int32_t)IRQn) & 0xFUL)-4UL] = (uint8_t)((priority << (8 - __NVIC_PRIO_BITS)) & (uint32_t)0xFFUL); } else { NVIC->IP[((uint32_t)(int32_t)IRQn)] = (uint8_t)((priority << (8 - __NVIC_PRIO_BITS)) & (uint32_t)0xFFUL); } } /** \brief Get Interrupt Priority The function reads the priority of an interrupt. The interrupt number can be positive to specify an external (device specific) interrupt, or negative to specify an internal (core) interrupt. \param [in] IRQn Interrupt number. \return Interrupt Priority. Value is aligned automatically to the implemented priority bits of the microcontroller. */ __STATIC_INLINE uint32_t NVIC_GetPriority(IRQn_Type IRQn) { if((int32_t)IRQn < 0) { return(((uint32_t)SCB->SHP[(((uint32_t)(int32_t)IRQn) & 0xFUL)-4UL] >> (8 - __NVIC_PRIO_BITS))); } else { return(((uint32_t)NVIC->IP[((uint32_t)(int32_t)IRQn)] >> (8 - __NVIC_PRIO_BITS))); } } /** \brief Encode Priority The function encodes the priority for an interrupt with the given priority group, preemptive priority value, and subpriority value. In case of a conflict between priority grouping and available priority bits (__NVIC_PRIO_BITS), the smallest possible priority group is set. \param [in] PriorityGroup Used priority group. \param [in] PreemptPriority Preemptive priority value (starting from 0). \param [in] SubPriority Subpriority value (starting from 0). \return Encoded priority. Value can be used in the function \ref NVIC_SetPriority(). */ __STATIC_INLINE uint32_t NVIC_EncodePriority (uint32_t PriorityGroup, uint32_t PreemptPriority, uint32_t SubPriority) { uint32_t PriorityGroupTmp = (PriorityGroup & (uint32_t)0x07UL); /* only values 0..7 are used */ uint32_t PreemptPriorityBits; uint32_t SubPriorityBits; PreemptPriorityBits = ((7UL - PriorityGroupTmp) > (uint32_t)(__NVIC_PRIO_BITS)) ? (uint32_t)(__NVIC_PRIO_BITS) : (uint32_t)(7UL - PriorityGroupTmp); SubPriorityBits = ((PriorityGroupTmp + (uint32_t)(__NVIC_PRIO_BITS)) < (uint32_t)7UL) ? (uint32_t)0UL : (uint32_t)((PriorityGroupTmp - 7UL) + (uint32_t)(__NVIC_PRIO_BITS)); return ( ((PreemptPriority & (uint32_t)((1UL << (PreemptPriorityBits)) - 1UL)) << SubPriorityBits) | ((SubPriority & (uint32_t)((1UL << (SubPriorityBits )) - 1UL))) ); } /** \brief Decode Priority The function decodes an interrupt priority value with a given priority group to preemptive priority value and subpriority value. In case of a conflict between priority grouping and available priority bits (__NVIC_PRIO_BITS) the smallest possible priority group is set. \param [in] Priority Priority value, which can be retrieved with the function \ref NVIC_GetPriority(). \param [in] PriorityGroup Used priority group. \param [out] pPreemptPriority Preemptive priority value (starting from 0). \param [out] pSubPriority Subpriority value (starting from 0). */ __STATIC_INLINE void NVIC_DecodePriority (uint32_t Priority, uint32_t PriorityGroup, uint32_t* pPreemptPriority, uint32_t* pSubPriority) { uint32_t PriorityGroupTmp = (PriorityGroup & (uint32_t)0x07UL); /* only values 0..7 are used */ uint32_t PreemptPriorityBits; uint32_t SubPriorityBits; PreemptPriorityBits = ((7UL - PriorityGroupTmp) > (uint32_t)(__NVIC_PRIO_BITS)) ? (uint32_t)(__NVIC_PRIO_BITS) : (uint32_t)(7UL - PriorityGroupTmp); SubPriorityBits = ((PriorityGroupTmp + (uint32_t)(__NVIC_PRIO_BITS)) < (uint32_t)7UL) ? (uint32_t)0UL : (uint32_t)((PriorityGroupTmp - 7UL) + (uint32_t)(__NVIC_PRIO_BITS)); *pPreemptPriority = (Priority >> SubPriorityBits) & (uint32_t)((1UL << (PreemptPriorityBits)) - 1UL); *pSubPriority = (Priority ) & (uint32_t)((1UL << (SubPriorityBits )) - 1UL); } /** \brief System Reset The function initiates a system reset request to reset the MCU. */ __STATIC_INLINE void NVIC_SystemReset(void) { __DSB(); /* Ensure all outstanding memory accesses included buffered write are completed before reset */ SCB->AIRCR = (uint32_t)((0x5FAUL << SCB_AIRCR_VECTKEY_Pos) | (SCB->AIRCR & SCB_AIRCR_PRIGROUP_Msk) | SCB_AIRCR_SYSRESETREQ_Msk ); /* Keep priority group unchanged */ __DSB(); /* Ensure completion of memory access */ while(1) { __NOP(); } /* wait until reset */ } /*@} end of CMSIS_Core_NVICFunctions */ /* ################################## SysTick function ############################################ */ /** \ingroup CMSIS_Core_FunctionInterface \defgroup CMSIS_Core_SysTickFunctions SysTick Functions \brief Functions that configure the System. @{ */ #if (__Vendor_SysTickConfig == 0) /** \brief System Tick Configuration The function initializes the System Timer and its interrupt, and starts the System Tick Timer. Counter is in free running mode to generate periodic interrupts. \param [in] ticks Number of ticks between two interrupts. \return 0 Function succeeded. \return 1 Function failed. \note When the variable __Vendor_SysTickConfig is set to 1, then the function SysTick_Config is not included. In this case, the file device.h must contain a vendor-specific implementation of this function. */ __STATIC_INLINE uint32_t SysTick_Config(uint32_t ticks) { if ((ticks - 1UL) > SysTick_LOAD_RELOAD_Msk) { return (1UL); } /* Reload value impossible */ SysTick->LOAD = (uint32_t)(ticks - 1UL); /* set reload register */ NVIC_SetPriority (SysTick_IRQn, (1UL << __NVIC_PRIO_BITS) - 1UL); /* set Priority for Systick Interrupt */ SysTick->VAL = 0UL; /* Load the SysTick Counter Value */ SysTick->CTRL = SysTick_CTRL_CLKSOURCE_Msk | SysTick_CTRL_TICKINT_Msk | SysTick_CTRL_ENABLE_Msk; /* Enable SysTick IRQ and SysTick Timer */ return (0UL); /* Function successful */ } #endif /*@} end of CMSIS_Core_SysTickFunctions */ /* ##################################### Debug In/Output function ########################################### */ /** \ingroup CMSIS_Core_FunctionInterface \defgroup CMSIS_core_DebugFunctions ITM Functions \brief Functions that access the ITM debug interface. @{ */ extern volatile int32_t ITM_RxBuffer; /*!< External variable to receive characters. */ #define ITM_RXBUFFER_EMPTY 0x5AA55AA5 /*!< Value identifying \ref ITM_RxBuffer is ready for next character. */ /** \brief ITM Send Character The function transmits a character via the ITM channel 0, and \li Just returns when no debugger is connected that has booked the output. \li Is blocking when a debugger is connected, but the previous character sent has not been transmitted. \param [in] ch Character to transmit. \returns Character to transmit. */ __STATIC_INLINE uint32_t ITM_SendChar (uint32_t ch) { if (((ITM->TCR & ITM_TCR_ITMENA_Msk) != 0UL) && /* ITM enabled */ ((ITM->TER & 1UL ) != 0UL) ) /* ITM Port #0 enabled */ { while (ITM->PORT[0].u32 == 0UL) { __NOP(); } ITM->PORT[0].u8 = (uint8_t)ch; } return (ch); } /** \brief ITM Receive Character The function inputs a character via the external variable \ref ITM_RxBuffer. \return Received character. \return -1 No character pending. */ __STATIC_INLINE int32_t ITM_ReceiveChar (void) { int32_t ch = -1; /* no character available */ if (ITM_RxBuffer != ITM_RXBUFFER_EMPTY) { ch = ITM_RxBuffer; ITM_RxBuffer = ITM_RXBUFFER_EMPTY; /* ready for next character */ } return (ch); } /** \brief ITM Check Character The function checks whether a character is pending for reading in the variable \ref ITM_RxBuffer. \return 0 No character available. \return 1 Character available. */ __STATIC_INLINE int32_t ITM_CheckChar (void) { if (ITM_RxBuffer == ITM_RXBUFFER_EMPTY) { return (0); /* no character available */ } else { return (1); /* character available */ } } /*@} end of CMSIS_core_DebugFunctions */ #ifdef __cplusplus } #endif #endif /* __CORE_CM4_H_DEPENDANT */ #endif /* __CMSIS_GENERIC */ ================================================ FILE: Zelig/mbed/TARGET_NUCLEO_F091RC/core_cm4_simd.h ================================================ /**************************************************************************//** * @file core_cm4_simd.h * @brief CMSIS Cortex-M4 SIMD Header File * @version V3.20 * @date 25. February 2013 * * @note * ******************************************************************************/ /* Copyright (c) 2009 - 2013 ARM LIMITED All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: - Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. - Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. - Neither the name of ARM 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 COPYRIGHT HOLDERS AND CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. ---------------------------------------------------------------------------*/ #ifdef __cplusplus extern "C" { #endif #ifndef __CORE_CM4_SIMD_H #define __CORE_CM4_SIMD_H /******************************************************************************* * Hardware Abstraction Layer ******************************************************************************/ /* ################### Compiler specific Intrinsics ########################### */ /** \defgroup CMSIS_SIMD_intrinsics CMSIS SIMD Intrinsics Access to dedicated SIMD instructions @{ */ #if defined ( __CC_ARM ) /*------------------RealView Compiler -----------------*/ /* ARM armcc specific functions */ /*------ CM4 SIMD Intrinsics -----------------------------------------------------*/ #define __SADD8 __sadd8 #define __QADD8 __qadd8 #define __SHADD8 __shadd8 #define __UADD8 __uadd8 #define __UQADD8 __uqadd8 #define __UHADD8 __uhadd8 #define __SSUB8 __ssub8 #define __QSUB8 __qsub8 #define __SHSUB8 __shsub8 #define __USUB8 __usub8 #define __UQSUB8 __uqsub8 #define __UHSUB8 __uhsub8 #define __SADD16 __sadd16 #define __QADD16 __qadd16 #define __SHADD16 __shadd16 #define __UADD16 __uadd16 #define __UQADD16 __uqadd16 #define __UHADD16 __uhadd16 #define __SSUB16 __ssub16 #define __QSUB16 __qsub16 #define __SHSUB16 __shsub16 #define __USUB16 __usub16 #define __UQSUB16 __uqsub16 #define __UHSUB16 __uhsub16 #define __SASX __sasx #define __QASX __qasx #define __SHASX __shasx #define __UASX __uasx #define __UQASX __uqasx #define __UHASX __uhasx #define __SSAX __ssax #define __QSAX __qsax #define __SHSAX __shsax #define __USAX __usax #define __UQSAX __uqsax #define __UHSAX __uhsax #define __USAD8 __usad8 #define __USADA8 __usada8 #define __SSAT16 __ssat16 #define __USAT16 __usat16 #define __UXTB16 __uxtb16 #define __UXTAB16 __uxtab16 #define __SXTB16 __sxtb16 #define __SXTAB16 __sxtab16 #define __SMUAD __smuad #define __SMUADX __smuadx #define __SMLAD __smlad #define __SMLADX __smladx #define __SMLALD __smlald #define __SMLALDX __smlaldx #define __SMUSD __smusd #define __SMUSDX __smusdx #define __SMLSD __smlsd #define __SMLSDX __smlsdx #define __SMLSLD __smlsld #define __SMLSLDX __smlsldx #define __SEL __sel #define __QADD __qadd #define __QSUB __qsub #define __PKHBT(ARG1,ARG2,ARG3) ( ((((uint32_t)(ARG1)) ) & 0x0000FFFFUL) | \ ((((uint32_t)(ARG2)) << (ARG3)) & 0xFFFF0000UL) ) #define __PKHTB(ARG1,ARG2,ARG3) ( ((((uint32_t)(ARG1)) ) & 0xFFFF0000UL) | \ ((((uint32_t)(ARG2)) >> (ARG3)) & 0x0000FFFFUL) ) #define __SMMLA(ARG1,ARG2,ARG3) ( (int32_t)((((int64_t)(ARG1) * (ARG2)) + \ ((int64_t)(ARG3) << 32) ) >> 32)) /*-- End CM4 SIMD Intrinsics -----------------------------------------------------*/ #elif defined ( __ICCARM__ ) /*------------------ ICC Compiler -------------------*/ /* IAR iccarm specific functions */ /*------ CM4 SIMD Intrinsics -----------------------------------------------------*/ #include /*-- End CM4 SIMD Intrinsics -----------------------------------------------------*/ #elif defined ( __TMS470__ ) /*---------------- TI CCS Compiler ------------------*/ /* TI CCS specific functions */ /*------ CM4 SIMD Intrinsics -----------------------------------------------------*/ #include /*-- End CM4 SIMD Intrinsics -----------------------------------------------------*/ #elif defined ( __GNUC__ ) /*------------------ GNU Compiler ---------------------*/ /* GNU gcc specific functions */ /*------ CM4 SIMD Intrinsics -----------------------------------------------------*/ __attribute__( ( always_inline ) ) __STATIC_INLINE uint32_t __SADD8(uint32_t op1, uint32_t op2) { uint32_t result; __ASM volatile ("sadd8 %0, %1, %2" : "=r" (result) : "r" (op1), "r" (op2) ); return(result); } __attribute__( ( always_inline ) ) __STATIC_INLINE uint32_t __QADD8(uint32_t op1, uint32_t op2) { uint32_t result; __ASM volatile ("qadd8 %0, %1, %2" : "=r" (result) : "r" (op1), "r" (op2) ); return(result); } __attribute__( ( always_inline ) ) __STATIC_INLINE uint32_t __SHADD8(uint32_t op1, uint32_t op2) { uint32_t result; __ASM volatile ("shadd8 %0, %1, %2" : "=r" (result) : "r" (op1), "r" (op2) ); return(result); } __attribute__( ( always_inline ) ) __STATIC_INLINE uint32_t __UADD8(uint32_t op1, uint32_t op2) { uint32_t result; __ASM volatile ("uadd8 %0, %1, %2" : "=r" (result) : "r" (op1), "r" (op2) ); return(result); } __attribute__( ( always_inline ) ) __STATIC_INLINE uint32_t __UQADD8(uint32_t op1, uint32_t op2) { uint32_t result; __ASM volatile ("uqadd8 %0, %1, %2" : "=r" (result) : "r" (op1), "r" (op2) ); return(result); } __attribute__( ( always_inline ) ) __STATIC_INLINE uint32_t __UHADD8(uint32_t op1, uint32_t op2) { uint32_t result; __ASM volatile ("uhadd8 %0, %1, %2" : "=r" (result) : "r" (op1), "r" (op2) ); return(result); } __attribute__( ( always_inline ) ) __STATIC_INLINE uint32_t __SSUB8(uint32_t op1, uint32_t op2) { uint32_t result; __ASM volatile ("ssub8 %0, %1, %2" : "=r" (result) : "r" (op1), "r" (op2) ); return(result); } __attribute__( ( always_inline ) ) __STATIC_INLINE uint32_t __QSUB8(uint32_t op1, uint32_t op2) { uint32_t result; __ASM volatile ("qsub8 %0, %1, %2" : "=r" (result) : "r" (op1), "r" (op2) ); return(result); } __attribute__( ( always_inline ) ) __STATIC_INLINE uint32_t __SHSUB8(uint32_t op1, uint32_t op2) { uint32_t result; __ASM volatile ("shsub8 %0, %1, %2" : "=r" (result) : "r" (op1), "r" (op2) ); return(result); } __attribute__( ( always_inline ) ) __STATIC_INLINE uint32_t __USUB8(uint32_t op1, uint32_t op2) { uint32_t result; __ASM volatile ("usub8 %0, %1, %2" : "=r" (result) : "r" (op1), "r" (op2) ); return(result); } __attribute__( ( always_inline ) ) __STATIC_INLINE uint32_t __UQSUB8(uint32_t op1, uint32_t op2) { uint32_t result; __ASM volatile ("uqsub8 %0, %1, %2" : "=r" (result) : "r" (op1), "r" (op2) ); return(result); } __attribute__( ( always_inline ) ) __STATIC_INLINE uint32_t __UHSUB8(uint32_t op1, uint32_t op2) { uint32_t result; __ASM volatile ("uhsub8 %0, %1, %2" : "=r" (result) : "r" (op1), "r" (op2) ); return(result); } __attribute__( ( always_inline ) ) __STATIC_INLINE uint32_t __SADD16(uint32_t op1, uint32_t op2) { uint32_t result; __ASM volatile ("sadd16 %0, %1, %2" : "=r" (result) : "r" (op1), "r" (op2) ); return(result); } __attribute__( ( always_inline ) ) __STATIC_INLINE uint32_t __QADD16(uint32_t op1, uint32_t op2) { uint32_t result; __ASM volatile ("qadd16 %0, %1, %2" : "=r" (result) : "r" (op1), "r" (op2) ); return(result); } __attribute__( ( always_inline ) ) __STATIC_INLINE uint32_t __SHADD16(uint32_t op1, uint32_t op2) { uint32_t result; __ASM volatile ("shadd16 %0, %1, %2" : "=r" (result) : "r" (op1), "r" (op2) ); return(result); } __attribute__( ( always_inline ) ) __STATIC_INLINE uint32_t __UADD16(uint32_t op1, uint32_t op2) { uint32_t result; __ASM volatile ("uadd16 %0, %1, %2" : "=r" (result) : "r" (op1), "r" (op2) ); return(result); } __attribute__( ( always_inline ) ) __STATIC_INLINE uint32_t __UQADD16(uint32_t op1, uint32_t op2) { uint32_t result; __ASM volatile ("uqadd16 %0, %1, %2" : "=r" (result) : "r" (op1), "r" (op2) ); return(result); } __attribute__( ( always_inline ) ) __STATIC_INLINE uint32_t __UHADD16(uint32_t op1, uint32_t op2) { uint32_t result; __ASM volatile ("uhadd16 %0, %1, %2" : "=r" (result) : "r" (op1), "r" (op2) ); return(result); } __attribute__( ( always_inline ) ) __STATIC_INLINE uint32_t __SSUB16(uint32_t op1, uint32_t op2) { uint32_t result; __ASM volatile ("ssub16 %0, %1, %2" : "=r" (result) : "r" (op1), "r" (op2) ); return(result); } __attribute__( ( always_inline ) ) __STATIC_INLINE uint32_t __QSUB16(uint32_t op1, uint32_t op2) { uint32_t result; __ASM volatile ("qsub16 %0, %1, %2" : "=r" (result) : "r" (op1), "r" (op2) ); return(result); } __attribute__( ( always_inline ) ) __STATIC_INLINE uint32_t __SHSUB16(uint32_t op1, uint32_t op2) { uint32_t result; __ASM volatile ("shsub16 %0, %1, %2" : "=r" (result) : "r" (op1), "r" (op2) ); return(result); } __attribute__( ( always_inline ) ) __STATIC_INLINE uint32_t __USUB16(uint32_t op1, uint32_t op2) { uint32_t result; __ASM volatile ("usub16 %0, %1, %2" : "=r" (result) : "r" (op1), "r" (op2) ); return(result); } __attribute__( ( always_inline ) ) __STATIC_INLINE uint32_t __UQSUB16(uint32_t op1, uint32_t op2) { uint32_t result; __ASM volatile ("uqsub16 %0, %1, %2" : "=r" (result) : "r" (op1), "r" (op2) ); return(result); } __attribute__( ( always_inline ) ) __STATIC_INLINE uint32_t __UHSUB16(uint32_t op1, uint32_t op2) { uint32_t result; __ASM volatile ("uhsub16 %0, %1, %2" : "=r" (result) : "r" (op1), "r" (op2) ); return(result); } __attribute__( ( always_inline ) ) __STATIC_INLINE uint32_t __SASX(uint32_t op1, uint32_t op2) { uint32_t result; __ASM volatile ("sasx %0, %1, %2" : "=r" (result) : "r" (op1), "r" (op2) ); return(result); } __attribute__( ( always_inline ) ) __STATIC_INLINE uint32_t __QASX(uint32_t op1, uint32_t op2) { uint32_t result; __ASM volatile ("qasx %0, %1, %2" : "=r" (result) : "r" (op1), "r" (op2) ); return(result); } __attribute__( ( always_inline ) ) __STATIC_INLINE uint32_t __SHASX(uint32_t op1, uint32_t op2) { uint32_t result; __ASM volatile ("shasx %0, %1, %2" : "=r" (result) : "r" (op1), "r" (op2) ); return(result); } __attribute__( ( always_inline ) ) __STATIC_INLINE uint32_t __UASX(uint32_t op1, uint32_t op2) { uint32_t result; __ASM volatile ("uasx %0, %1, %2" : "=r" (result) : "r" (op1), "r" (op2) ); return(result); } __attribute__( ( always_inline ) ) __STATIC_INLINE uint32_t __UQASX(uint32_t op1, uint32_t op2) { uint32_t result; __ASM volatile ("uqasx %0, %1, %2" : "=r" (result) : "r" (op1), "r" (op2) ); return(result); } __attribute__( ( always_inline ) ) __STATIC_INLINE uint32_t __UHASX(uint32_t op1, uint32_t op2) { uint32_t result; __ASM volatile ("uhasx %0, %1, %2" : "=r" (result) : "r" (op1), "r" (op2) ); return(result); } __attribute__( ( always_inline ) ) __STATIC_INLINE uint32_t __SSAX(uint32_t op1, uint32_t op2) { uint32_t result; __ASM volatile ("ssax %0, %1, %2" : "=r" (result) : "r" (op1), "r" (op2) ); return(result); } __attribute__( ( always_inline ) ) __STATIC_INLINE uint32_t __QSAX(uint32_t op1, uint32_t op2) { uint32_t result; __ASM volatile ("qsax %0, %1, %2" : "=r" (result) : "r" (op1), "r" (op2) ); return(result); } __attribute__( ( always_inline ) ) __STATIC_INLINE uint32_t __SHSAX(uint32_t op1, uint32_t op2) { uint32_t result; __ASM volatile ("shsax %0, %1, %2" : "=r" (result) : "r" (op1), "r" (op2) ); return(result); } __attribute__( ( always_inline ) ) __STATIC_INLINE uint32_t __USAX(uint32_t op1, uint32_t op2) { uint32_t result; __ASM volatile ("usax %0, %1, %2" : "=r" (result) : "r" (op1), "r" (op2) ); return(result); } __attribute__( ( always_inline ) ) __STATIC_INLINE uint32_t __UQSAX(uint32_t op1, uint32_t op2) { uint32_t result; __ASM volatile ("uqsax %0, %1, %2" : "=r" (result) : "r" (op1), "r" (op2) ); return(result); } __attribute__( ( always_inline ) ) __STATIC_INLINE uint32_t __UHSAX(uint32_t op1, uint32_t op2) { uint32_t result; __ASM volatile ("uhsax %0, %1, %2" : "=r" (result) : "r" (op1), "r" (op2) ); return(result); } __attribute__( ( always_inline ) ) __STATIC_INLINE uint32_t __USAD8(uint32_t op1, uint32_t op2) { uint32_t result; __ASM volatile ("usad8 %0, %1, %2" : "=r" (result) : "r" (op1), "r" (op2) ); return(result); } __attribute__( ( always_inline ) ) __STATIC_INLINE uint32_t __USADA8(uint32_t op1, uint32_t op2, uint32_t op3) { uint32_t result; __ASM volatile ("usada8 %0, %1, %2, %3" : "=r" (result) : "r" (op1), "r" (op2), "r" (op3) ); return(result); } #define __SSAT16(ARG1,ARG2) \ ({ \ uint32_t __RES, __ARG1 = (ARG1); \ __ASM ("ssat16 %0, %1, %2" : "=r" (__RES) : "I" (ARG2), "r" (__ARG1) ); \ __RES; \ }) #define __USAT16(ARG1,ARG2) \ ({ \ uint32_t __RES, __ARG1 = (ARG1); \ __ASM ("usat16 %0, %1, %2" : "=r" (__RES) : "I" (ARG2), "r" (__ARG1) ); \ __RES; \ }) __attribute__( ( always_inline ) ) __STATIC_INLINE uint32_t __UXTB16(uint32_t op1) { uint32_t result; __ASM volatile ("uxtb16 %0, %1" : "=r" (result) : "r" (op1)); return(result); } __attribute__( ( always_inline ) ) __STATIC_INLINE uint32_t __UXTAB16(uint32_t op1, uint32_t op2) { uint32_t result; __ASM volatile ("uxtab16 %0, %1, %2" : "=r" (result) : "r" (op1), "r" (op2) ); return(result); } __attribute__( ( always_inline ) ) __STATIC_INLINE uint32_t __SXTB16(uint32_t op1) { uint32_t result; __ASM volatile ("sxtb16 %0, %1" : "=r" (result) : "r" (op1)); return(result); } __attribute__( ( always_inline ) ) __STATIC_INLINE uint32_t __SXTAB16(uint32_t op1, uint32_t op2) { uint32_t result; __ASM volatile ("sxtab16 %0, %1, %2" : "=r" (result) : "r" (op1), "r" (op2) ); return(result); } __attribute__( ( always_inline ) ) __STATIC_INLINE uint32_t __SMUAD (uint32_t op1, uint32_t op2) { uint32_t result; __ASM volatile ("smuad %0, %1, %2" : "=r" (result) : "r" (op1), "r" (op2) ); return(result); } __attribute__( ( always_inline ) ) __STATIC_INLINE uint32_t __SMUADX (uint32_t op1, uint32_t op2) { uint32_t result; __ASM volatile ("smuadx %0, %1, %2" : "=r" (result) : "r" (op1), "r" (op2) ); return(result); } __attribute__( ( always_inline ) ) __STATIC_INLINE uint32_t __SMLAD (uint32_t op1, uint32_t op2, uint32_t op3) { uint32_t result; __ASM volatile ("smlad %0, %1, %2, %3" : "=r" (result) : "r" (op1), "r" (op2), "r" (op3) ); return(result); } __attribute__( ( always_inline ) ) __STATIC_INLINE uint32_t __SMLADX (uint32_t op1, uint32_t op2, uint32_t op3) { uint32_t result; __ASM volatile ("smladx %0, %1, %2, %3" : "=r" (result) : "r" (op1), "r" (op2), "r" (op3) ); return(result); } #define __SMLALD(ARG1,ARG2,ARG3) \ ({ \ uint32_t __ARG1 = (ARG1), __ARG2 = (ARG2), __ARG3_H = (uint32_t)((uint64_t)(ARG3) >> 32), __ARG3_L = (uint32_t)((uint64_t)(ARG3) & 0xFFFFFFFFUL); \ __ASM volatile ("smlald %0, %1, %2, %3" : "=r" (__ARG3_L), "=r" (__ARG3_H) : "r" (__ARG1), "r" (__ARG2), "0" (__ARG3_L), "1" (__ARG3_H) ); \ (uint64_t)(((uint64_t)__ARG3_H << 32) | __ARG3_L); \ }) #define __SMLALDX(ARG1,ARG2,ARG3) \ ({ \ uint32_t __ARG1 = (ARG1), __ARG2 = (ARG2), __ARG3_H = (uint32_t)((uint64_t)(ARG3) >> 32), __ARG3_L = (uint32_t)((uint64_t)(ARG3) & 0xFFFFFFFFUL); \ __ASM volatile ("smlaldx %0, %1, %2, %3" : "=r" (__ARG3_L), "=r" (__ARG3_H) : "r" (__ARG1), "r" (__ARG2), "0" (__ARG3_L), "1" (__ARG3_H) ); \ (uint64_t)(((uint64_t)__ARG3_H << 32) | __ARG3_L); \ }) __attribute__( ( always_inline ) ) __STATIC_INLINE uint32_t __SMUSD (uint32_t op1, uint32_t op2) { uint32_t result; __ASM volatile ("smusd %0, %1, %2" : "=r" (result) : "r" (op1), "r" (op2) ); return(result); } __attribute__( ( always_inline ) ) __STATIC_INLINE uint32_t __SMUSDX (uint32_t op1, uint32_t op2) { uint32_t result; __ASM volatile ("smusdx %0, %1, %2" : "=r" (result) : "r" (op1), "r" (op2) ); return(result); } __attribute__( ( always_inline ) ) __STATIC_INLINE uint32_t __SMLSD (uint32_t op1, uint32_t op2, uint32_t op3) { uint32_t result; __ASM volatile ("smlsd %0, %1, %2, %3" : "=r" (result) : "r" (op1), "r" (op2), "r" (op3) ); return(result); } __attribute__( ( always_inline ) ) __STATIC_INLINE uint32_t __SMLSDX (uint32_t op1, uint32_t op2, uint32_t op3) { uint32_t result; __ASM volatile ("smlsdx %0, %1, %2, %3" : "=r" (result) : "r" (op1), "r" (op2), "r" (op3) ); return(result); } #define __SMLSLD(ARG1,ARG2,ARG3) \ ({ \ uint32_t __ARG1 = (ARG1), __ARG2 = (ARG2), __ARG3_H = (uint32_t)((ARG3) >> 32), __ARG3_L = (uint32_t)((ARG3) & 0xFFFFFFFFUL); \ __ASM volatile ("smlsld %0, %1, %2, %3" : "=r" (__ARG3_L), "=r" (__ARG3_H) : "r" (__ARG1), "r" (__ARG2), "0" (__ARG3_L), "1" (__ARG3_H) ); \ (uint64_t)(((uint64_t)__ARG3_H << 32) | __ARG3_L); \ }) #define __SMLSLDX(ARG1,ARG2,ARG3) \ ({ \ uint32_t __ARG1 = (ARG1), __ARG2 = (ARG2), __ARG3_H = (uint32_t)((ARG3) >> 32), __ARG3_L = (uint32_t)((ARG3) & 0xFFFFFFFFUL); \ __ASM volatile ("smlsldx %0, %1, %2, %3" : "=r" (__ARG3_L), "=r" (__ARG3_H) : "r" (__ARG1), "r" (__ARG2), "0" (__ARG3_L), "1" (__ARG3_H) ); \ (uint64_t)(((uint64_t)__ARG3_H << 32) | __ARG3_L); \ }) __attribute__( ( always_inline ) ) __STATIC_INLINE uint32_t __SEL (uint32_t op1, uint32_t op2) { uint32_t result; __ASM volatile ("sel %0, %1, %2" : "=r" (result) : "r" (op1), "r" (op2) ); return(result); } __attribute__( ( always_inline ) ) __STATIC_INLINE uint32_t __QADD(uint32_t op1, uint32_t op2) { uint32_t result; __ASM volatile ("qadd %0, %1, %2" : "=r" (result) : "r" (op1), "r" (op2) ); return(result); } __attribute__( ( always_inline ) ) __STATIC_INLINE uint32_t __QSUB(uint32_t op1, uint32_t op2) { uint32_t result; __ASM volatile ("qsub %0, %1, %2" : "=r" (result) : "r" (op1), "r" (op2) ); return(result); } #define __PKHBT(ARG1,ARG2,ARG3) \ ({ \ uint32_t __RES, __ARG1 = (ARG1), __ARG2 = (ARG2); \ __ASM ("pkhbt %0, %1, %2, lsl %3" : "=r" (__RES) : "r" (__ARG1), "r" (__ARG2), "I" (ARG3) ); \ __RES; \ }) #define __PKHTB(ARG1,ARG2,ARG3) \ ({ \ uint32_t __RES, __ARG1 = (ARG1), __ARG2 = (ARG2); \ if (ARG3 == 0) \ __ASM ("pkhtb %0, %1, %2" : "=r" (__RES) : "r" (__ARG1), "r" (__ARG2) ); \ else \ __ASM ("pkhtb %0, %1, %2, asr %3" : "=r" (__RES) : "r" (__ARG1), "r" (__ARG2), "I" (ARG3) ); \ __RES; \ }) __attribute__( ( always_inline ) ) __STATIC_INLINE uint32_t __SMMLA (int32_t op1, int32_t op2, int32_t op3) { int32_t result; __ASM volatile ("smmla %0, %1, %2, %3" : "=r" (result): "r" (op1), "r" (op2), "r" (op3) ); return(result); } /*-- End CM4 SIMD Intrinsics -----------------------------------------------------*/ #elif defined ( __TASKING__ ) /*------------------ TASKING Compiler --------------*/ /* TASKING carm specific functions */ /*------ CM4 SIMD Intrinsics -----------------------------------------------------*/ /* not yet supported */ /*-- End CM4 SIMD Intrinsics -----------------------------------------------------*/ #endif /*@} end of group CMSIS_SIMD_intrinsics */ #endif /* __CORE_CM4_SIMD_H */ #ifdef __cplusplus } #endif ================================================ FILE: Zelig/mbed/TARGET_NUCLEO_F091RC/core_cm7.h ================================================ /**************************************************************************//** * @file core_cm7.h * @brief CMSIS Cortex-M7 Core Peripheral Access Layer Header File * @version V4.10 * @date 18. March 2015 * * @note * ******************************************************************************/ /* Copyright (c) 2009 - 2015 ARM LIMITED All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: - Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. - Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. - Neither the name of ARM 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 COPYRIGHT HOLDERS AND 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. ---------------------------------------------------------------------------*/ #if defined ( __ICCARM__ ) #pragma system_include /* treat file as system include file for MISRA check */ #endif #ifndef __CORE_CM7_H_GENERIC #define __CORE_CM7_H_GENERIC #ifdef __cplusplus extern "C" { #endif /** \page CMSIS_MISRA_Exceptions MISRA-C:2004 Compliance Exceptions CMSIS violates the following MISRA-C:2004 rules: \li Required Rule 8.5, object/function definition in header file.
Function definitions in header files are used to allow 'inlining'. \li Required Rule 18.4, declaration of union type or object of union type: '{...}'.
Unions are used for effective representation of core registers. \li Advisory Rule 19.7, Function-like macro defined.
Function-like macros are used to allow more efficient code. */ /******************************************************************************* * CMSIS definitions ******************************************************************************/ /** \ingroup Cortex_M7 @{ */ /* CMSIS CM7 definitions */ #define __CM7_CMSIS_VERSION_MAIN (0x04) /*!< [31:16] CMSIS HAL main version */ #define __CM7_CMSIS_VERSION_SUB (0x00) /*!< [15:0] CMSIS HAL sub version */ #define __CM7_CMSIS_VERSION ((__CM7_CMSIS_VERSION_MAIN << 16) | \ __CM7_CMSIS_VERSION_SUB ) /*!< CMSIS HAL version number */ #define __CORTEX_M (0x07) /*!< Cortex-M Core */ #if defined ( __CC_ARM ) #define __ASM __asm /*!< asm keyword for ARM Compiler */ #define __INLINE __inline /*!< inline keyword for ARM Compiler */ #define __STATIC_INLINE static __inline #elif defined ( __GNUC__ ) #define __ASM __asm /*!< asm keyword for GNU Compiler */ #define __INLINE inline /*!< inline keyword for GNU Compiler */ #define __STATIC_INLINE static inline #elif defined ( __ICCARM__ ) #define __ASM __asm /*!< asm keyword for IAR Compiler */ #define __INLINE inline /*!< inline keyword for IAR Compiler. Only available in High optimization mode! */ #define __STATIC_INLINE static inline #elif defined ( __TMS470__ ) #define __ASM __asm /*!< asm keyword for TI CCS Compiler */ #define __STATIC_INLINE static inline #elif defined ( __TASKING__ ) #define __ASM __asm /*!< asm keyword for TASKING Compiler */ #define __INLINE inline /*!< inline keyword for TASKING Compiler */ #define __STATIC_INLINE static inline #elif defined ( __CSMC__ ) #define __packed #define __ASM _asm /*!< asm keyword for COSMIC Compiler */ #define __INLINE inline /*use -pc99 on compile line !< inline keyword for COSMIC Compiler */ #define __STATIC_INLINE static inline #endif /** __FPU_USED indicates whether an FPU is used or not. For this, __FPU_PRESENT has to be checked prior to making use of FPU specific registers and functions. */ #if defined ( __CC_ARM ) #if defined __TARGET_FPU_VFP #if (__FPU_PRESENT == 1) #define __FPU_USED 1 #else #warning "Compiler generates FPU instructions for a device without an FPU (check __FPU_PRESENT)" #define __FPU_USED 0 #endif #else #define __FPU_USED 0 #endif #elif defined ( __GNUC__ ) #if defined (__VFP_FP__) && !defined(__SOFTFP__) #if (__FPU_PRESENT == 1) #define __FPU_USED 1 #else #warning "Compiler generates FPU instructions for a device without an FPU (check __FPU_PRESENT)" #define __FPU_USED 0 #endif #else #define __FPU_USED 0 #endif #elif defined ( __ICCARM__ ) #if defined __ARMVFP__ #if (__FPU_PRESENT == 1) #define __FPU_USED 1 #else #warning "Compiler generates FPU instructions for a device without an FPU (check __FPU_PRESENT)" #define __FPU_USED 0 #endif #else #define __FPU_USED 0 #endif #elif defined ( __TMS470__ ) #if defined __TI_VFP_SUPPORT__ #if (__FPU_PRESENT == 1) #define __FPU_USED 1 #else #warning "Compiler generates FPU instructions for a device without an FPU (check __FPU_PRESENT)" #define __FPU_USED 0 #endif #else #define __FPU_USED 0 #endif #elif defined ( __TASKING__ ) #if defined __FPU_VFP__ #if (__FPU_PRESENT == 1) #define __FPU_USED 1 #else #error "Compiler generates FPU instructions for a device without an FPU (check __FPU_PRESENT)" #define __FPU_USED 0 #endif #else #define __FPU_USED 0 #endif #elif defined ( __CSMC__ ) /* Cosmic */ #if ( __CSMC__ & 0x400) // FPU present for parser #if (__FPU_PRESENT == 1) #define __FPU_USED 1 #else #error "Compiler generates FPU instructions for a device without an FPU (check __FPU_PRESENT)" #define __FPU_USED 0 #endif #else #define __FPU_USED 0 #endif #endif #include /* standard types definitions */ #include /* Core Instruction Access */ #include /* Core Function Access */ #include /* Compiler specific SIMD Intrinsics */ #ifdef __cplusplus } #endif #endif /* __CORE_CM7_H_GENERIC */ #ifndef __CMSIS_GENERIC #ifndef __CORE_CM7_H_DEPENDANT #define __CORE_CM7_H_DEPENDANT #ifdef __cplusplus extern "C" { #endif /* check device defines and use defaults */ #if defined __CHECK_DEVICE_DEFINES #ifndef __CM7_REV #define __CM7_REV 0x0000 #warning "__CM7_REV not defined in device header file; using default!" #endif #ifndef __FPU_PRESENT #define __FPU_PRESENT 0 #warning "__FPU_PRESENT not defined in device header file; using default!" #endif #ifndef __MPU_PRESENT #define __MPU_PRESENT 0 #warning "__MPU_PRESENT not defined in device header file; using default!" #endif #ifndef __ICACHE_PRESENT #define __ICACHE_PRESENT 0 #warning "__ICACHE_PRESENT not defined in device header file; using default!" #endif #ifndef __DCACHE_PRESENT #define __DCACHE_PRESENT 0 #warning "__DCACHE_PRESENT not defined in device header file; using default!" #endif #ifndef __DTCM_PRESENT #define __DTCM_PRESENT 0 #warning "__DTCM_PRESENT not defined in device header file; using default!" #endif #ifndef __NVIC_PRIO_BITS #define __NVIC_PRIO_BITS 3 #warning "__NVIC_PRIO_BITS not defined in device header file; using default!" #endif #ifndef __Vendor_SysTickConfig #define __Vendor_SysTickConfig 0 #warning "__Vendor_SysTickConfig not defined in device header file; using default!" #endif #endif /* IO definitions (access restrictions to peripheral registers) */ /** \defgroup CMSIS_glob_defs CMSIS Global Defines IO Type Qualifiers are used \li to specify the access to peripheral variables. \li for automatic generation of peripheral register debug information. */ #ifdef __cplusplus #define __I volatile /*!< Defines 'read only' permissions */ #else #define __I volatile const /*!< Defines 'read only' permissions */ #endif #define __O volatile /*!< Defines 'write only' permissions */ #define __IO volatile /*!< Defines 'read / write' permissions */ /*@} end of group Cortex_M7 */ /******************************************************************************* * Register Abstraction Core Register contain: - Core Register - Core NVIC Register - Core SCB Register - Core SysTick Register - Core Debug Register - Core MPU Register - Core FPU Register ******************************************************************************/ /** \defgroup CMSIS_core_register Defines and Type Definitions \brief Type definitions and defines for Cortex-M processor based devices. */ /** \ingroup CMSIS_core_register \defgroup CMSIS_CORE Status and Control Registers \brief Core Register type definitions. @{ */ /** \brief Union type to access the Application Program Status Register (APSR). */ typedef union { struct { uint32_t _reserved0:16; /*!< bit: 0..15 Reserved */ uint32_t GE:4; /*!< bit: 16..19 Greater than or Equal flags */ uint32_t _reserved1:7; /*!< bit: 20..26 Reserved */ uint32_t Q:1; /*!< bit: 27 Saturation condition flag */ uint32_t V:1; /*!< bit: 28 Overflow condition code flag */ uint32_t C:1; /*!< bit: 29 Carry condition code flag */ uint32_t Z:1; /*!< bit: 30 Zero condition code flag */ uint32_t N:1; /*!< bit: 31 Negative condition code flag */ } b; /*!< Structure used for bit access */ uint32_t w; /*!< Type used for word access */ } APSR_Type; /* APSR Register Definitions */ #define APSR_N_Pos 31 /*!< APSR: N Position */ #define APSR_N_Msk (1UL << APSR_N_Pos) /*!< APSR: N Mask */ #define APSR_Z_Pos 30 /*!< APSR: Z Position */ #define APSR_Z_Msk (1UL << APSR_Z_Pos) /*!< APSR: Z Mask */ #define APSR_C_Pos 29 /*!< APSR: C Position */ #define APSR_C_Msk (1UL << APSR_C_Pos) /*!< APSR: C Mask */ #define APSR_V_Pos 28 /*!< APSR: V Position */ #define APSR_V_Msk (1UL << APSR_V_Pos) /*!< APSR: V Mask */ #define APSR_Q_Pos 27 /*!< APSR: Q Position */ #define APSR_Q_Msk (1UL << APSR_Q_Pos) /*!< APSR: Q Mask */ #define APSR_GE_Pos 16 /*!< APSR: GE Position */ #define APSR_GE_Msk (0xFUL << APSR_GE_Pos) /*!< APSR: GE Mask */ /** \brief Union type to access the Interrupt Program Status Register (IPSR). */ typedef union { struct { uint32_t ISR:9; /*!< bit: 0.. 8 Exception number */ uint32_t _reserved0:23; /*!< bit: 9..31 Reserved */ } b; /*!< Structure used for bit access */ uint32_t w; /*!< Type used for word access */ } IPSR_Type; /* IPSR Register Definitions */ #define IPSR_ISR_Pos 0 /*!< IPSR: ISR Position */ #define IPSR_ISR_Msk (0x1FFUL /*<< IPSR_ISR_Pos*/) /*!< IPSR: ISR Mask */ /** \brief Union type to access the Special-Purpose Program Status Registers (xPSR). */ typedef union { struct { uint32_t ISR:9; /*!< bit: 0.. 8 Exception number */ uint32_t _reserved0:7; /*!< bit: 9..15 Reserved */ uint32_t GE:4; /*!< bit: 16..19 Greater than or Equal flags */ uint32_t _reserved1:4; /*!< bit: 20..23 Reserved */ uint32_t T:1; /*!< bit: 24 Thumb bit (read 0) */ uint32_t IT:2; /*!< bit: 25..26 saved IT state (read 0) */ uint32_t Q:1; /*!< bit: 27 Saturation condition flag */ uint32_t V:1; /*!< bit: 28 Overflow condition code flag */ uint32_t C:1; /*!< bit: 29 Carry condition code flag */ uint32_t Z:1; /*!< bit: 30 Zero condition code flag */ uint32_t N:1; /*!< bit: 31 Negative condition code flag */ } b; /*!< Structure used for bit access */ uint32_t w; /*!< Type used for word access */ } xPSR_Type; /* xPSR Register Definitions */ #define xPSR_N_Pos 31 /*!< xPSR: N Position */ #define xPSR_N_Msk (1UL << xPSR_N_Pos) /*!< xPSR: N Mask */ #define xPSR_Z_Pos 30 /*!< xPSR: Z Position */ #define xPSR_Z_Msk (1UL << xPSR_Z_Pos) /*!< xPSR: Z Mask */ #define xPSR_C_Pos 29 /*!< xPSR: C Position */ #define xPSR_C_Msk (1UL << xPSR_C_Pos) /*!< xPSR: C Mask */ #define xPSR_V_Pos 28 /*!< xPSR: V Position */ #define xPSR_V_Msk (1UL << xPSR_V_Pos) /*!< xPSR: V Mask */ #define xPSR_Q_Pos 27 /*!< xPSR: Q Position */ #define xPSR_Q_Msk (1UL << xPSR_Q_Pos) /*!< xPSR: Q Mask */ #define xPSR_IT_Pos 25 /*!< xPSR: IT Position */ #define xPSR_IT_Msk (3UL << xPSR_IT_Pos) /*!< xPSR: IT Mask */ #define xPSR_T_Pos 24 /*!< xPSR: T Position */ #define xPSR_T_Msk (1UL << xPSR_T_Pos) /*!< xPSR: T Mask */ #define xPSR_GE_Pos 16 /*!< xPSR: GE Position */ #define xPSR_GE_Msk (0xFUL << xPSR_GE_Pos) /*!< xPSR: GE Mask */ #define xPSR_ISR_Pos 0 /*!< xPSR: ISR Position */ #define xPSR_ISR_Msk (0x1FFUL /*<< xPSR_ISR_Pos*/) /*!< xPSR: ISR Mask */ /** \brief Union type to access the Control Registers (CONTROL). */ typedef union { struct { uint32_t nPRIV:1; /*!< bit: 0 Execution privilege in Thread mode */ uint32_t SPSEL:1; /*!< bit: 1 Stack to be used */ uint32_t FPCA:1; /*!< bit: 2 FP extension active flag */ uint32_t _reserved0:29; /*!< bit: 3..31 Reserved */ } b; /*!< Structure used for bit access */ uint32_t w; /*!< Type used for word access */ } CONTROL_Type; /* CONTROL Register Definitions */ #define CONTROL_FPCA_Pos 2 /*!< CONTROL: FPCA Position */ #define CONTROL_FPCA_Msk (1UL << CONTROL_FPCA_Pos) /*!< CONTROL: FPCA Mask */ #define CONTROL_SPSEL_Pos 1 /*!< CONTROL: SPSEL Position */ #define CONTROL_SPSEL_Msk (1UL << CONTROL_SPSEL_Pos) /*!< CONTROL: SPSEL Mask */ #define CONTROL_nPRIV_Pos 0 /*!< CONTROL: nPRIV Position */ #define CONTROL_nPRIV_Msk (1UL /*<< CONTROL_nPRIV_Pos*/) /*!< CONTROL: nPRIV Mask */ /*@} end of group CMSIS_CORE */ /** \ingroup CMSIS_core_register \defgroup CMSIS_NVIC Nested Vectored Interrupt Controller (NVIC) \brief Type definitions for the NVIC Registers @{ */ /** \brief Structure type to access the Nested Vectored Interrupt Controller (NVIC). */ typedef struct { __IO uint32_t ISER[8]; /*!< Offset: 0x000 (R/W) Interrupt Set Enable Register */ uint32_t RESERVED0[24]; __IO uint32_t ICER[8]; /*!< Offset: 0x080 (R/W) Interrupt Clear Enable Register */ uint32_t RSERVED1[24]; __IO uint32_t ISPR[8]; /*!< Offset: 0x100 (R/W) Interrupt Set Pending Register */ uint32_t RESERVED2[24]; __IO uint32_t ICPR[8]; /*!< Offset: 0x180 (R/W) Interrupt Clear Pending Register */ uint32_t RESERVED3[24]; __IO uint32_t IABR[8]; /*!< Offset: 0x200 (R/W) Interrupt Active bit Register */ uint32_t RESERVED4[56]; __IO uint8_t IP[240]; /*!< Offset: 0x300 (R/W) Interrupt Priority Register (8Bit wide) */ uint32_t RESERVED5[644]; __O uint32_t STIR; /*!< Offset: 0xE00 ( /W) Software Trigger Interrupt Register */ } NVIC_Type; /* Software Triggered Interrupt Register Definitions */ #define NVIC_STIR_INTID_Pos 0 /*!< STIR: INTLINESNUM Position */ #define NVIC_STIR_INTID_Msk (0x1FFUL /*<< NVIC_STIR_INTID_Pos*/) /*!< STIR: INTLINESNUM Mask */ /*@} end of group CMSIS_NVIC */ /** \ingroup CMSIS_core_register \defgroup CMSIS_SCB System Control Block (SCB) \brief Type definitions for the System Control Block Registers @{ */ /** \brief Structure type to access the System Control Block (SCB). */ typedef struct { __I uint32_t CPUID; /*!< Offset: 0x000 (R/ ) CPUID Base Register */ __IO uint32_t ICSR; /*!< Offset: 0x004 (R/W) Interrupt Control and State Register */ __IO uint32_t VTOR; /*!< Offset: 0x008 (R/W) Vector Table Offset Register */ __IO uint32_t AIRCR; /*!< Offset: 0x00C (R/W) Application Interrupt and Reset Control Register */ __IO uint32_t SCR; /*!< Offset: 0x010 (R/W) System Control Register */ __IO uint32_t CCR; /*!< Offset: 0x014 (R/W) Configuration Control Register */ __IO uint8_t SHPR[12]; /*!< Offset: 0x018 (R/W) System Handlers Priority Registers (4-7, 8-11, 12-15) */ __IO uint32_t SHCSR; /*!< Offset: 0x024 (R/W) System Handler Control and State Register */ __IO uint32_t CFSR; /*!< Offset: 0x028 (R/W) Configurable Fault Status Register */ __IO uint32_t HFSR; /*!< Offset: 0x02C (R/W) HardFault Status Register */ __IO uint32_t DFSR; /*!< Offset: 0x030 (R/W) Debug Fault Status Register */ __IO uint32_t MMFAR; /*!< Offset: 0x034 (R/W) MemManage Fault Address Register */ __IO uint32_t BFAR; /*!< Offset: 0x038 (R/W) BusFault Address Register */ __IO uint32_t AFSR; /*!< Offset: 0x03C (R/W) Auxiliary Fault Status Register */ __I uint32_t ID_PFR[2]; /*!< Offset: 0x040 (R/ ) Processor Feature Register */ __I uint32_t ID_DFR; /*!< Offset: 0x048 (R/ ) Debug Feature Register */ __I uint32_t ID_AFR; /*!< Offset: 0x04C (R/ ) Auxiliary Feature Register */ __I uint32_t ID_MFR[4]; /*!< Offset: 0x050 (R/ ) Memory Model Feature Register */ __I uint32_t ID_ISAR[5]; /*!< Offset: 0x060 (R/ ) Instruction Set Attributes Register */ uint32_t RESERVED0[1]; __I uint32_t CLIDR; /*!< Offset: 0x078 (R/ ) Cache Level ID register */ __I uint32_t CTR; /*!< Offset: 0x07C (R/ ) Cache Type register */ __I uint32_t CCSIDR; /*!< Offset: 0x080 (R/ ) Cache Size ID Register */ __IO uint32_t CSSELR; /*!< Offset: 0x084 (R/W) Cache Size Selection Register */ __IO uint32_t CPACR; /*!< Offset: 0x088 (R/W) Coprocessor Access Control Register */ uint32_t RESERVED3[93]; __O uint32_t STIR; /*!< Offset: 0x200 ( /W) Software Triggered Interrupt Register */ uint32_t RESERVED4[15]; __I uint32_t MVFR0; /*!< Offset: 0x240 (R/ ) Media and VFP Feature Register 0 */ __I uint32_t MVFR1; /*!< Offset: 0x244 (R/ ) Media and VFP Feature Register 1 */ __I uint32_t MVFR2; /*!< Offset: 0x248 (R/ ) Media and VFP Feature Register 1 */ uint32_t RESERVED5[1]; __O uint32_t ICIALLU; /*!< Offset: 0x250 ( /W) I-Cache Invalidate All to PoU */ uint32_t RESERVED6[1]; __O uint32_t ICIMVAU; /*!< Offset: 0x258 ( /W) I-Cache Invalidate by MVA to PoU */ __O uint32_t DCIMVAC; /*!< Offset: 0x25C ( /W) D-Cache Invalidate by MVA to PoC */ __O uint32_t DCISW; /*!< Offset: 0x260 ( /W) D-Cache Invalidate by Set-way */ __O uint32_t DCCMVAU; /*!< Offset: 0x264 ( /W) D-Cache Clean by MVA to PoU */ __O uint32_t DCCMVAC; /*!< Offset: 0x268 ( /W) D-Cache Clean by MVA to PoC */ __O uint32_t DCCSW; /*!< Offset: 0x26C ( /W) D-Cache Clean by Set-way */ __O uint32_t DCCIMVAC; /*!< Offset: 0x270 ( /W) D-Cache Clean and Invalidate by MVA to PoC */ __O uint32_t DCCISW; /*!< Offset: 0x274 ( /W) D-Cache Clean and Invalidate by Set-way */ uint32_t RESERVED7[6]; __IO uint32_t ITCMCR; /*!< Offset: 0x290 (R/W) Instruction Tightly-Coupled Memory Control Register */ __IO uint32_t DTCMCR; /*!< Offset: 0x294 (R/W) Data Tightly-Coupled Memory Control Registers */ __IO uint32_t AHBPCR; /*!< Offset: 0x298 (R/W) AHBP Control Register */ __IO uint32_t CACR; /*!< Offset: 0x29C (R/W) L1 Cache Control Register */ __IO uint32_t AHBSCR; /*!< Offset: 0x2A0 (R/W) AHB Slave Control Register */ uint32_t RESERVED8[1]; __IO uint32_t ABFSR; /*!< Offset: 0x2A8 (R/W) Auxiliary Bus Fault Status Register */ } SCB_Type; /* SCB CPUID Register Definitions */ #define SCB_CPUID_IMPLEMENTER_Pos 24 /*!< SCB CPUID: IMPLEMENTER Position */ #define SCB_CPUID_IMPLEMENTER_Msk (0xFFUL << SCB_CPUID_IMPLEMENTER_Pos) /*!< SCB CPUID: IMPLEMENTER Mask */ #define SCB_CPUID_VARIANT_Pos 20 /*!< SCB CPUID: VARIANT Position */ #define SCB_CPUID_VARIANT_Msk (0xFUL << SCB_CPUID_VARIANT_Pos) /*!< SCB CPUID: VARIANT Mask */ #define SCB_CPUID_ARCHITECTURE_Pos 16 /*!< SCB CPUID: ARCHITECTURE Position */ #define SCB_CPUID_ARCHITECTURE_Msk (0xFUL << SCB_CPUID_ARCHITECTURE_Pos) /*!< SCB CPUID: ARCHITECTURE Mask */ #define SCB_CPUID_PARTNO_Pos 4 /*!< SCB CPUID: PARTNO Position */ #define SCB_CPUID_PARTNO_Msk (0xFFFUL << SCB_CPUID_PARTNO_Pos) /*!< SCB CPUID: PARTNO Mask */ #define SCB_CPUID_REVISION_Pos 0 /*!< SCB CPUID: REVISION Position */ #define SCB_CPUID_REVISION_Msk (0xFUL /*<< SCB_CPUID_REVISION_Pos*/) /*!< SCB CPUID: REVISION Mask */ /* SCB Interrupt Control State Register Definitions */ #define SCB_ICSR_NMIPENDSET_Pos 31 /*!< SCB ICSR: NMIPENDSET Position */ #define SCB_ICSR_NMIPENDSET_Msk (1UL << SCB_ICSR_NMIPENDSET_Pos) /*!< SCB ICSR: NMIPENDSET Mask */ #define SCB_ICSR_PENDSVSET_Pos 28 /*!< SCB ICSR: PENDSVSET Position */ #define SCB_ICSR_PENDSVSET_Msk (1UL << SCB_ICSR_PENDSVSET_Pos) /*!< SCB ICSR: PENDSVSET Mask */ #define SCB_ICSR_PENDSVCLR_Pos 27 /*!< SCB ICSR: PENDSVCLR Position */ #define SCB_ICSR_PENDSVCLR_Msk (1UL << SCB_ICSR_PENDSVCLR_Pos) /*!< SCB ICSR: PENDSVCLR Mask */ #define SCB_ICSR_PENDSTSET_Pos 26 /*!< SCB ICSR: PENDSTSET Position */ #define SCB_ICSR_PENDSTSET_Msk (1UL << SCB_ICSR_PENDSTSET_Pos) /*!< SCB ICSR: PENDSTSET Mask */ #define SCB_ICSR_PENDSTCLR_Pos 25 /*!< SCB ICSR: PENDSTCLR Position */ #define SCB_ICSR_PENDSTCLR_Msk (1UL << SCB_ICSR_PENDSTCLR_Pos) /*!< SCB ICSR: PENDSTCLR Mask */ #define SCB_ICSR_ISRPREEMPT_Pos 23 /*!< SCB ICSR: ISRPREEMPT Position */ #define SCB_ICSR_ISRPREEMPT_Msk (1UL << SCB_ICSR_ISRPREEMPT_Pos) /*!< SCB ICSR: ISRPREEMPT Mask */ #define SCB_ICSR_ISRPENDING_Pos 22 /*!< SCB ICSR: ISRPENDING Position */ #define SCB_ICSR_ISRPENDING_Msk (1UL << SCB_ICSR_ISRPENDING_Pos) /*!< SCB ICSR: ISRPENDING Mask */ #define SCB_ICSR_VECTPENDING_Pos 12 /*!< SCB ICSR: VECTPENDING Position */ #define SCB_ICSR_VECTPENDING_Msk (0x1FFUL << SCB_ICSR_VECTPENDING_Pos) /*!< SCB ICSR: VECTPENDING Mask */ #define SCB_ICSR_RETTOBASE_Pos 11 /*!< SCB ICSR: RETTOBASE Position */ #define SCB_ICSR_RETTOBASE_Msk (1UL << SCB_ICSR_RETTOBASE_Pos) /*!< SCB ICSR: RETTOBASE Mask */ #define SCB_ICSR_VECTACTIVE_Pos 0 /*!< SCB ICSR: VECTACTIVE Position */ #define SCB_ICSR_VECTACTIVE_Msk (0x1FFUL /*<< SCB_ICSR_VECTACTIVE_Pos*/) /*!< SCB ICSR: VECTACTIVE Mask */ /* SCB Vector Table Offset Register Definitions */ #define SCB_VTOR_TBLOFF_Pos 7 /*!< SCB VTOR: TBLOFF Position */ #define SCB_VTOR_TBLOFF_Msk (0x1FFFFFFUL << SCB_VTOR_TBLOFF_Pos) /*!< SCB VTOR: TBLOFF Mask */ /* SCB Application Interrupt and Reset Control Register Definitions */ #define SCB_AIRCR_VECTKEY_Pos 16 /*!< SCB AIRCR: VECTKEY Position */ #define SCB_AIRCR_VECTKEY_Msk (0xFFFFUL << SCB_AIRCR_VECTKEY_Pos) /*!< SCB AIRCR: VECTKEY Mask */ #define SCB_AIRCR_VECTKEYSTAT_Pos 16 /*!< SCB AIRCR: VECTKEYSTAT Position */ #define SCB_AIRCR_VECTKEYSTAT_Msk (0xFFFFUL << SCB_AIRCR_VECTKEYSTAT_Pos) /*!< SCB AIRCR: VECTKEYSTAT Mask */ #define SCB_AIRCR_ENDIANESS_Pos 15 /*!< SCB AIRCR: ENDIANESS Position */ #define SCB_AIRCR_ENDIANESS_Msk (1UL << SCB_AIRCR_ENDIANESS_Pos) /*!< SCB AIRCR: ENDIANESS Mask */ #define SCB_AIRCR_PRIGROUP_Pos 8 /*!< SCB AIRCR: PRIGROUP Position */ #define SCB_AIRCR_PRIGROUP_Msk (7UL << SCB_AIRCR_PRIGROUP_Pos) /*!< SCB AIRCR: PRIGROUP Mask */ #define SCB_AIRCR_SYSRESETREQ_Pos 2 /*!< SCB AIRCR: SYSRESETREQ Position */ #define SCB_AIRCR_SYSRESETREQ_Msk (1UL << SCB_AIRCR_SYSRESETREQ_Pos) /*!< SCB AIRCR: SYSRESETREQ Mask */ #define SCB_AIRCR_VECTCLRACTIVE_Pos 1 /*!< SCB AIRCR: VECTCLRACTIVE Position */ #define SCB_AIRCR_VECTCLRACTIVE_Msk (1UL << SCB_AIRCR_VECTCLRACTIVE_Pos) /*!< SCB AIRCR: VECTCLRACTIVE Mask */ #define SCB_AIRCR_VECTRESET_Pos 0 /*!< SCB AIRCR: VECTRESET Position */ #define SCB_AIRCR_VECTRESET_Msk (1UL /*<< SCB_AIRCR_VECTRESET_Pos*/) /*!< SCB AIRCR: VECTRESET Mask */ /* SCB System Control Register Definitions */ #define SCB_SCR_SEVONPEND_Pos 4 /*!< SCB SCR: SEVONPEND Position */ #define SCB_SCR_SEVONPEND_Msk (1UL << SCB_SCR_SEVONPEND_Pos) /*!< SCB SCR: SEVONPEND Mask */ #define SCB_SCR_SLEEPDEEP_Pos 2 /*!< SCB SCR: SLEEPDEEP Position */ #define SCB_SCR_SLEEPDEEP_Msk (1UL << SCB_SCR_SLEEPDEEP_Pos) /*!< SCB SCR: SLEEPDEEP Mask */ #define SCB_SCR_SLEEPONEXIT_Pos 1 /*!< SCB SCR: SLEEPONEXIT Position */ #define SCB_SCR_SLEEPONEXIT_Msk (1UL << SCB_SCR_SLEEPONEXIT_Pos) /*!< SCB SCR: SLEEPONEXIT Mask */ /* SCB Configuration Control Register Definitions */ #define SCB_CCR_BP_Pos 18 /*!< SCB CCR: Branch prediction enable bit Position */ #define SCB_CCR_BP_Msk (1UL << SCB_CCR_BP_Pos) /*!< SCB CCR: Branch prediction enable bit Mask */ #define SCB_CCR_IC_Pos 17 /*!< SCB CCR: Instruction cache enable bit Position */ #define SCB_CCR_IC_Msk (1UL << SCB_CCR_IC_Pos) /*!< SCB CCR: Instruction cache enable bit Mask */ #define SCB_CCR_DC_Pos 16 /*!< SCB CCR: Cache enable bit Position */ #define SCB_CCR_DC_Msk (1UL << SCB_CCR_DC_Pos) /*!< SCB CCR: Cache enable bit Mask */ #define SCB_CCR_STKALIGN_Pos 9 /*!< SCB CCR: STKALIGN Position */ #define SCB_CCR_STKALIGN_Msk (1UL << SCB_CCR_STKALIGN_Pos) /*!< SCB CCR: STKALIGN Mask */ #define SCB_CCR_BFHFNMIGN_Pos 8 /*!< SCB CCR: BFHFNMIGN Position */ #define SCB_CCR_BFHFNMIGN_Msk (1UL << SCB_CCR_BFHFNMIGN_Pos) /*!< SCB CCR: BFHFNMIGN Mask */ #define SCB_CCR_DIV_0_TRP_Pos 4 /*!< SCB CCR: DIV_0_TRP Position */ #define SCB_CCR_DIV_0_TRP_Msk (1UL << SCB_CCR_DIV_0_TRP_Pos) /*!< SCB CCR: DIV_0_TRP Mask */ #define SCB_CCR_UNALIGN_TRP_Pos 3 /*!< SCB CCR: UNALIGN_TRP Position */ #define SCB_CCR_UNALIGN_TRP_Msk (1UL << SCB_CCR_UNALIGN_TRP_Pos) /*!< SCB CCR: UNALIGN_TRP Mask */ #define SCB_CCR_USERSETMPEND_Pos 1 /*!< SCB CCR: USERSETMPEND Position */ #define SCB_CCR_USERSETMPEND_Msk (1UL << SCB_CCR_USERSETMPEND_Pos) /*!< SCB CCR: USERSETMPEND Mask */ #define SCB_CCR_NONBASETHRDENA_Pos 0 /*!< SCB CCR: NONBASETHRDENA Position */ #define SCB_CCR_NONBASETHRDENA_Msk (1UL /*<< SCB_CCR_NONBASETHRDENA_Pos*/) /*!< SCB CCR: NONBASETHRDENA Mask */ /* SCB System Handler Control and State Register Definitions */ #define SCB_SHCSR_USGFAULTENA_Pos 18 /*!< SCB SHCSR: USGFAULTENA Position */ #define SCB_SHCSR_USGFAULTENA_Msk (1UL << SCB_SHCSR_USGFAULTENA_Pos) /*!< SCB SHCSR: USGFAULTENA Mask */ #define SCB_SHCSR_BUSFAULTENA_Pos 17 /*!< SCB SHCSR: BUSFAULTENA Position */ #define SCB_SHCSR_BUSFAULTENA_Msk (1UL << SCB_SHCSR_BUSFAULTENA_Pos) /*!< SCB SHCSR: BUSFAULTENA Mask */ #define SCB_SHCSR_MEMFAULTENA_Pos 16 /*!< SCB SHCSR: MEMFAULTENA Position */ #define SCB_SHCSR_MEMFAULTENA_Msk (1UL << SCB_SHCSR_MEMFAULTENA_Pos) /*!< SCB SHCSR: MEMFAULTENA Mask */ #define SCB_SHCSR_SVCALLPENDED_Pos 15 /*!< SCB SHCSR: SVCALLPENDED Position */ #define SCB_SHCSR_SVCALLPENDED_Msk (1UL << SCB_SHCSR_SVCALLPENDED_Pos) /*!< SCB SHCSR: SVCALLPENDED Mask */ #define SCB_SHCSR_BUSFAULTPENDED_Pos 14 /*!< SCB SHCSR: BUSFAULTPENDED Position */ #define SCB_SHCSR_BUSFAULTPENDED_Msk (1UL << SCB_SHCSR_BUSFAULTPENDED_Pos) /*!< SCB SHCSR: BUSFAULTPENDED Mask */ #define SCB_SHCSR_MEMFAULTPENDED_Pos 13 /*!< SCB SHCSR: MEMFAULTPENDED Position */ #define SCB_SHCSR_MEMFAULTPENDED_Msk (1UL << SCB_SHCSR_MEMFAULTPENDED_Pos) /*!< SCB SHCSR: MEMFAULTPENDED Mask */ #define SCB_SHCSR_USGFAULTPENDED_Pos 12 /*!< SCB SHCSR: USGFAULTPENDED Position */ #define SCB_SHCSR_USGFAULTPENDED_Msk (1UL << SCB_SHCSR_USGFAULTPENDED_Pos) /*!< SCB SHCSR: USGFAULTPENDED Mask */ #define SCB_SHCSR_SYSTICKACT_Pos 11 /*!< SCB SHCSR: SYSTICKACT Position */ #define SCB_SHCSR_SYSTICKACT_Msk (1UL << SCB_SHCSR_SYSTICKACT_Pos) /*!< SCB SHCSR: SYSTICKACT Mask */ #define SCB_SHCSR_PENDSVACT_Pos 10 /*!< SCB SHCSR: PENDSVACT Position */ #define SCB_SHCSR_PENDSVACT_Msk (1UL << SCB_SHCSR_PENDSVACT_Pos) /*!< SCB SHCSR: PENDSVACT Mask */ #define SCB_SHCSR_MONITORACT_Pos 8 /*!< SCB SHCSR: MONITORACT Position */ #define SCB_SHCSR_MONITORACT_Msk (1UL << SCB_SHCSR_MONITORACT_Pos) /*!< SCB SHCSR: MONITORACT Mask */ #define SCB_SHCSR_SVCALLACT_Pos 7 /*!< SCB SHCSR: SVCALLACT Position */ #define SCB_SHCSR_SVCALLACT_Msk (1UL << SCB_SHCSR_SVCALLACT_Pos) /*!< SCB SHCSR: SVCALLACT Mask */ #define SCB_SHCSR_USGFAULTACT_Pos 3 /*!< SCB SHCSR: USGFAULTACT Position */ #define SCB_SHCSR_USGFAULTACT_Msk (1UL << SCB_SHCSR_USGFAULTACT_Pos) /*!< SCB SHCSR: USGFAULTACT Mask */ #define SCB_SHCSR_BUSFAULTACT_Pos 1 /*!< SCB SHCSR: BUSFAULTACT Position */ #define SCB_SHCSR_BUSFAULTACT_Msk (1UL << SCB_SHCSR_BUSFAULTACT_Pos) /*!< SCB SHCSR: BUSFAULTACT Mask */ #define SCB_SHCSR_MEMFAULTACT_Pos 0 /*!< SCB SHCSR: MEMFAULTACT Position */ #define SCB_SHCSR_MEMFAULTACT_Msk (1UL /*<< SCB_SHCSR_MEMFAULTACT_Pos*/) /*!< SCB SHCSR: MEMFAULTACT Mask */ /* SCB Configurable Fault Status Registers Definitions */ #define SCB_CFSR_USGFAULTSR_Pos 16 /*!< SCB CFSR: Usage Fault Status Register Position */ #define SCB_CFSR_USGFAULTSR_Msk (0xFFFFUL << SCB_CFSR_USGFAULTSR_Pos) /*!< SCB CFSR: Usage Fault Status Register Mask */ #define SCB_CFSR_BUSFAULTSR_Pos 8 /*!< SCB CFSR: Bus Fault Status Register Position */ #define SCB_CFSR_BUSFAULTSR_Msk (0xFFUL << SCB_CFSR_BUSFAULTSR_Pos) /*!< SCB CFSR: Bus Fault Status Register Mask */ #define SCB_CFSR_MEMFAULTSR_Pos 0 /*!< SCB CFSR: Memory Manage Fault Status Register Position */ #define SCB_CFSR_MEMFAULTSR_Msk (0xFFUL /*<< SCB_CFSR_MEMFAULTSR_Pos*/) /*!< SCB CFSR: Memory Manage Fault Status Register Mask */ /* SCB Hard Fault Status Registers Definitions */ #define SCB_HFSR_DEBUGEVT_Pos 31 /*!< SCB HFSR: DEBUGEVT Position */ #define SCB_HFSR_DEBUGEVT_Msk (1UL << SCB_HFSR_DEBUGEVT_Pos) /*!< SCB HFSR: DEBUGEVT Mask */ #define SCB_HFSR_FORCED_Pos 30 /*!< SCB HFSR: FORCED Position */ #define SCB_HFSR_FORCED_Msk (1UL << SCB_HFSR_FORCED_Pos) /*!< SCB HFSR: FORCED Mask */ #define SCB_HFSR_VECTTBL_Pos 1 /*!< SCB HFSR: VECTTBL Position */ #define SCB_HFSR_VECTTBL_Msk (1UL << SCB_HFSR_VECTTBL_Pos) /*!< SCB HFSR: VECTTBL Mask */ /* SCB Debug Fault Status Register Definitions */ #define SCB_DFSR_EXTERNAL_Pos 4 /*!< SCB DFSR: EXTERNAL Position */ #define SCB_DFSR_EXTERNAL_Msk (1UL << SCB_DFSR_EXTERNAL_Pos) /*!< SCB DFSR: EXTERNAL Mask */ #define SCB_DFSR_VCATCH_Pos 3 /*!< SCB DFSR: VCATCH Position */ #define SCB_DFSR_VCATCH_Msk (1UL << SCB_DFSR_VCATCH_Pos) /*!< SCB DFSR: VCATCH Mask */ #define SCB_DFSR_DWTTRAP_Pos 2 /*!< SCB DFSR: DWTTRAP Position */ #define SCB_DFSR_DWTTRAP_Msk (1UL << SCB_DFSR_DWTTRAP_Pos) /*!< SCB DFSR: DWTTRAP Mask */ #define SCB_DFSR_BKPT_Pos 1 /*!< SCB DFSR: BKPT Position */ #define SCB_DFSR_BKPT_Msk (1UL << SCB_DFSR_BKPT_Pos) /*!< SCB DFSR: BKPT Mask */ #define SCB_DFSR_HALTED_Pos 0 /*!< SCB DFSR: HALTED Position */ #define SCB_DFSR_HALTED_Msk (1UL /*<< SCB_DFSR_HALTED_Pos*/) /*!< SCB DFSR: HALTED Mask */ /* Cache Level ID register */ #define SCB_CLIDR_LOUU_Pos 27 /*!< SCB CLIDR: LoUU Position */ #define SCB_CLIDR_LOUU_Msk (7UL << SCB_CLIDR_LOUU_Pos) /*!< SCB CLIDR: LoUU Mask */ #define SCB_CLIDR_LOC_Pos 24 /*!< SCB CLIDR: LoC Position */ #define SCB_CLIDR_LOC_Msk (7UL << SCB_CLIDR_FORMAT_Pos) /*!< SCB CLIDR: LoC Mask */ /* Cache Type register */ #define SCB_CTR_FORMAT_Pos 29 /*!< SCB CTR: Format Position */ #define SCB_CTR_FORMAT_Msk (7UL << SCB_CTR_FORMAT_Pos) /*!< SCB CTR: Format Mask */ #define SCB_CTR_CWG_Pos 24 /*!< SCB CTR: CWG Position */ #define SCB_CTR_CWG_Msk (0xFUL << SCB_CTR_CWG_Pos) /*!< SCB CTR: CWG Mask */ #define SCB_CTR_ERG_Pos 20 /*!< SCB CTR: ERG Position */ #define SCB_CTR_ERG_Msk (0xFUL << SCB_CTR_ERG_Pos) /*!< SCB CTR: ERG Mask */ #define SCB_CTR_DMINLINE_Pos 16 /*!< SCB CTR: DminLine Position */ #define SCB_CTR_DMINLINE_Msk (0xFUL << SCB_CTR_DMINLINE_Pos) /*!< SCB CTR: DminLine Mask */ #define SCB_CTR_IMINLINE_Pos 0 /*!< SCB CTR: ImInLine Position */ #define SCB_CTR_IMINLINE_Msk (0xFUL /*<< SCB_CTR_IMINLINE_Pos*/) /*!< SCB CTR: ImInLine Mask */ /* Cache Size ID Register */ #define SCB_CCSIDR_WT_Pos 31 /*!< SCB CCSIDR: WT Position */ #define SCB_CCSIDR_WT_Msk (7UL << SCB_CCSIDR_WT_Pos) /*!< SCB CCSIDR: WT Mask */ #define SCB_CCSIDR_WB_Pos 30 /*!< SCB CCSIDR: WB Position */ #define SCB_CCSIDR_WB_Msk (7UL << SCB_CCSIDR_WB_Pos) /*!< SCB CCSIDR: WB Mask */ #define SCB_CCSIDR_RA_Pos 29 /*!< SCB CCSIDR: RA Position */ #define SCB_CCSIDR_RA_Msk (7UL << SCB_CCSIDR_RA_Pos) /*!< SCB CCSIDR: RA Mask */ #define SCB_CCSIDR_WA_Pos 28 /*!< SCB CCSIDR: WA Position */ #define SCB_CCSIDR_WA_Msk (7UL << SCB_CCSIDR_WA_Pos) /*!< SCB CCSIDR: WA Mask */ #define SCB_CCSIDR_NUMSETS_Pos 13 /*!< SCB CCSIDR: NumSets Position */ #define SCB_CCSIDR_NUMSETS_Msk (0x7FFFUL << SCB_CCSIDR_NUMSETS_Pos) /*!< SCB CCSIDR: NumSets Mask */ #define SCB_CCSIDR_ASSOCIATIVITY_Pos 3 /*!< SCB CCSIDR: Associativity Position */ #define SCB_CCSIDR_ASSOCIATIVITY_Msk (0x3FFUL << SCB_CCSIDR_ASSOCIATIVITY_Pos) /*!< SCB CCSIDR: Associativity Mask */ #define SCB_CCSIDR_LINESIZE_Pos 0 /*!< SCB CCSIDR: LineSize Position */ #define SCB_CCSIDR_LINESIZE_Msk (7UL /*<< SCB_CCSIDR_LINESIZE_Pos*/) /*!< SCB CCSIDR: LineSize Mask */ /* Cache Size Selection Register */ #define SCB_CSSELR_LEVEL_Pos 1 /*!< SCB CSSELR: Level Position */ #define SCB_CSSELR_LEVEL_Msk (7UL << SCB_CSSELR_LEVEL_Pos) /*!< SCB CSSELR: Level Mask */ #define SCB_CSSELR_IND_Pos 0 /*!< SCB CSSELR: InD Position */ #define SCB_CSSELR_IND_Msk (1UL /*<< SCB_CSSELR_IND_Pos*/) /*!< SCB CSSELR: InD Mask */ /* SCB Software Triggered Interrupt Register */ #define SCB_STIR_INTID_Pos 0 /*!< SCB STIR: INTID Position */ #define SCB_STIR_INTID_Msk (0x1FFUL /*<< SCB_STIR_INTID_Pos*/) /*!< SCB STIR: INTID Mask */ /* Instruction Tightly-Coupled Memory Control Register*/ #define SCB_ITCMCR_SZ_Pos 3 /*!< SCB ITCMCR: SZ Position */ #define SCB_ITCMCR_SZ_Msk (0xFUL << SCB_ITCMCR_SZ_Pos) /*!< SCB ITCMCR: SZ Mask */ #define SCB_ITCMCR_RETEN_Pos 2 /*!< SCB ITCMCR: RETEN Position */ #define SCB_ITCMCR_RETEN_Msk (1UL << SCB_ITCMCR_RETEN_Pos) /*!< SCB ITCMCR: RETEN Mask */ #define SCB_ITCMCR_RMW_Pos 1 /*!< SCB ITCMCR: RMW Position */ #define SCB_ITCMCR_RMW_Msk (1UL << SCB_ITCMCR_RMW_Pos) /*!< SCB ITCMCR: RMW Mask */ #define SCB_ITCMCR_EN_Pos 0 /*!< SCB ITCMCR: EN Position */ #define SCB_ITCMCR_EN_Msk (1UL /*<< SCB_ITCMCR_EN_Pos*/) /*!< SCB ITCMCR: EN Mask */ /* Data Tightly-Coupled Memory Control Registers */ #define SCB_DTCMCR_SZ_Pos 3 /*!< SCB DTCMCR: SZ Position */ #define SCB_DTCMCR_SZ_Msk (0xFUL << SCB_DTCMCR_SZ_Pos) /*!< SCB DTCMCR: SZ Mask */ #define SCB_DTCMCR_RETEN_Pos 2 /*!< SCB DTCMCR: RETEN Position */ #define SCB_DTCMCR_RETEN_Msk (1UL << SCB_DTCMCR_RETEN_Pos) /*!< SCB DTCMCR: RETEN Mask */ #define SCB_DTCMCR_RMW_Pos 1 /*!< SCB DTCMCR: RMW Position */ #define SCB_DTCMCR_RMW_Msk (1UL << SCB_DTCMCR_RMW_Pos) /*!< SCB DTCMCR: RMW Mask */ #define SCB_DTCMCR_EN_Pos 0 /*!< SCB DTCMCR: EN Position */ #define SCB_DTCMCR_EN_Msk (1UL /*<< SCB_DTCMCR_EN_Pos*/) /*!< SCB DTCMCR: EN Mask */ /* AHBP Control Register */ #define SCB_AHBPCR_SZ_Pos 1 /*!< SCB AHBPCR: SZ Position */ #define SCB_AHBPCR_SZ_Msk (7UL << SCB_AHBPCR_SZ_Pos) /*!< SCB AHBPCR: SZ Mask */ #define SCB_AHBPCR_EN_Pos 0 /*!< SCB AHBPCR: EN Position */ #define SCB_AHBPCR_EN_Msk (1UL /*<< SCB_AHBPCR_EN_Pos*/) /*!< SCB AHBPCR: EN Mask */ /* L1 Cache Control Register */ #define SCB_CACR_FORCEWT_Pos 2 /*!< SCB CACR: FORCEWT Position */ #define SCB_CACR_FORCEWT_Msk (1UL << SCB_CACR_FORCEWT_Pos) /*!< SCB CACR: FORCEWT Mask */ #define SCB_CACR_ECCEN_Pos 1 /*!< SCB CACR: ECCEN Position */ #define SCB_CACR_ECCEN_Msk (1UL << SCB_CACR_ECCEN_Pos) /*!< SCB CACR: ECCEN Mask */ #define SCB_CACR_SIWT_Pos 0 /*!< SCB CACR: SIWT Position */ #define SCB_CACR_SIWT_Msk (1UL /*<< SCB_CACR_SIWT_Pos*/) /*!< SCB CACR: SIWT Mask */ /* AHBS control register */ #define SCB_AHBSCR_INITCOUNT_Pos 11 /*!< SCB AHBSCR: INITCOUNT Position */ #define SCB_AHBSCR_INITCOUNT_Msk (0x1FUL << SCB_AHBPCR_INITCOUNT_Pos) /*!< SCB AHBSCR: INITCOUNT Mask */ #define SCB_AHBSCR_TPRI_Pos 2 /*!< SCB AHBSCR: TPRI Position */ #define SCB_AHBSCR_TPRI_Msk (0x1FFUL << SCB_AHBPCR_TPRI_Pos) /*!< SCB AHBSCR: TPRI Mask */ #define SCB_AHBSCR_CTL_Pos 0 /*!< SCB AHBSCR: CTL Position*/ #define SCB_AHBSCR_CTL_Msk (3UL /*<< SCB_AHBPCR_CTL_Pos*/) /*!< SCB AHBSCR: CTL Mask */ /* Auxiliary Bus Fault Status Register */ #define SCB_ABFSR_AXIMTYPE_Pos 8 /*!< SCB ABFSR: AXIMTYPE Position*/ #define SCB_ABFSR_AXIMTYPE_Msk (3UL << SCB_ABFSR_AXIMTYPE_Pos) /*!< SCB ABFSR: AXIMTYPE Mask */ #define SCB_ABFSR_EPPB_Pos 4 /*!< SCB ABFSR: EPPB Position*/ #define SCB_ABFSR_EPPB_Msk (1UL << SCB_ABFSR_EPPB_Pos) /*!< SCB ABFSR: EPPB Mask */ #define SCB_ABFSR_AXIM_Pos 3 /*!< SCB ABFSR: AXIM Position*/ #define SCB_ABFSR_AXIM_Msk (1UL << SCB_ABFSR_AXIM_Pos) /*!< SCB ABFSR: AXIM Mask */ #define SCB_ABFSR_AHBP_Pos 2 /*!< SCB ABFSR: AHBP Position*/ #define SCB_ABFSR_AHBP_Msk (1UL << SCB_ABFSR_AHBP_Pos) /*!< SCB ABFSR: AHBP Mask */ #define SCB_ABFSR_DTCM_Pos 1 /*!< SCB ABFSR: DTCM Position*/ #define SCB_ABFSR_DTCM_Msk (1UL << SCB_ABFSR_DTCM_Pos) /*!< SCB ABFSR: DTCM Mask */ #define SCB_ABFSR_ITCM_Pos 0 /*!< SCB ABFSR: ITCM Position*/ #define SCB_ABFSR_ITCM_Msk (1UL /*<< SCB_ABFSR_ITCM_Pos*/) /*!< SCB ABFSR: ITCM Mask */ /*@} end of group CMSIS_SCB */ /** \ingroup CMSIS_core_register \defgroup CMSIS_SCnSCB System Controls not in SCB (SCnSCB) \brief Type definitions for the System Control and ID Register not in the SCB @{ */ /** \brief Structure type to access the System Control and ID Register not in the SCB. */ typedef struct { uint32_t RESERVED0[1]; __I uint32_t ICTR; /*!< Offset: 0x004 (R/ ) Interrupt Controller Type Register */ __IO uint32_t ACTLR; /*!< Offset: 0x008 (R/W) Auxiliary Control Register */ } SCnSCB_Type; /* Interrupt Controller Type Register Definitions */ #define SCnSCB_ICTR_INTLINESNUM_Pos 0 /*!< ICTR: INTLINESNUM Position */ #define SCnSCB_ICTR_INTLINESNUM_Msk (0xFUL /*<< SCnSCB_ICTR_INTLINESNUM_Pos*/) /*!< ICTR: INTLINESNUM Mask */ /* Auxiliary Control Register Definitions */ #define SCnSCB_ACTLR_DISITMATBFLUSH_Pos 12 /*!< ACTLR: DISITMATBFLUSH Position */ #define SCnSCB_ACTLR_DISITMATBFLUSH_Msk (1UL << SCnSCB_ACTLR_DISITMATBFLUSH_Pos) /*!< ACTLR: DISITMATBFLUSH Mask */ #define SCnSCB_ACTLR_DISRAMODE_Pos 11 /*!< ACTLR: DISRAMODE Position */ #define SCnSCB_ACTLR_DISRAMODE_Msk (1UL << SCnSCB_ACTLR_DISRAMODE_Pos) /*!< ACTLR: DISRAMODE Mask */ #define SCnSCB_ACTLR_FPEXCODIS_Pos 10 /*!< ACTLR: FPEXCODIS Position */ #define SCnSCB_ACTLR_FPEXCODIS_Msk (1UL << SCnSCB_ACTLR_FPEXCODIS_Pos) /*!< ACTLR: FPEXCODIS Mask */ #define SCnSCB_ACTLR_DISFOLD_Pos 2 /*!< ACTLR: DISFOLD Position */ #define SCnSCB_ACTLR_DISFOLD_Msk (1UL << SCnSCB_ACTLR_DISFOLD_Pos) /*!< ACTLR: DISFOLD Mask */ #define SCnSCB_ACTLR_DISMCYCINT_Pos 0 /*!< ACTLR: DISMCYCINT Position */ #define SCnSCB_ACTLR_DISMCYCINT_Msk (1UL /*<< SCnSCB_ACTLR_DISMCYCINT_Pos*/) /*!< ACTLR: DISMCYCINT Mask */ /*@} end of group CMSIS_SCnotSCB */ /** \ingroup CMSIS_core_register \defgroup CMSIS_SysTick System Tick Timer (SysTick) \brief Type definitions for the System Timer Registers. @{ */ /** \brief Structure type to access the System Timer (SysTick). */ typedef struct { __IO uint32_t CTRL; /*!< Offset: 0x000 (R/W) SysTick Control and Status Register */ __IO uint32_t LOAD; /*!< Offset: 0x004 (R/W) SysTick Reload Value Register */ __IO uint32_t VAL; /*!< Offset: 0x008 (R/W) SysTick Current Value Register */ __I uint32_t CALIB; /*!< Offset: 0x00C (R/ ) SysTick Calibration Register */ } SysTick_Type; /* SysTick Control / Status Register Definitions */ #define SysTick_CTRL_COUNTFLAG_Pos 16 /*!< SysTick CTRL: COUNTFLAG Position */ #define SysTick_CTRL_COUNTFLAG_Msk (1UL << SysTick_CTRL_COUNTFLAG_Pos) /*!< SysTick CTRL: COUNTFLAG Mask */ #define SysTick_CTRL_CLKSOURCE_Pos 2 /*!< SysTick CTRL: CLKSOURCE Position */ #define SysTick_CTRL_CLKSOURCE_Msk (1UL << SysTick_CTRL_CLKSOURCE_Pos) /*!< SysTick CTRL: CLKSOURCE Mask */ #define SysTick_CTRL_TICKINT_Pos 1 /*!< SysTick CTRL: TICKINT Position */ #define SysTick_CTRL_TICKINT_Msk (1UL << SysTick_CTRL_TICKINT_Pos) /*!< SysTick CTRL: TICKINT Mask */ #define SysTick_CTRL_ENABLE_Pos 0 /*!< SysTick CTRL: ENABLE Position */ #define SysTick_CTRL_ENABLE_Msk (1UL /*<< SysTick_CTRL_ENABLE_Pos*/) /*!< SysTick CTRL: ENABLE Mask */ /* SysTick Reload Register Definitions */ #define SysTick_LOAD_RELOAD_Pos 0 /*!< SysTick LOAD: RELOAD Position */ #define SysTick_LOAD_RELOAD_Msk (0xFFFFFFUL /*<< SysTick_LOAD_RELOAD_Pos*/) /*!< SysTick LOAD: RELOAD Mask */ /* SysTick Current Register Definitions */ #define SysTick_VAL_CURRENT_Pos 0 /*!< SysTick VAL: CURRENT Position */ #define SysTick_VAL_CURRENT_Msk (0xFFFFFFUL /*<< SysTick_VAL_CURRENT_Pos*/) /*!< SysTick VAL: CURRENT Mask */ /* SysTick Calibration Register Definitions */ #define SysTick_CALIB_NOREF_Pos 31 /*!< SysTick CALIB: NOREF Position */ #define SysTick_CALIB_NOREF_Msk (1UL << SysTick_CALIB_NOREF_Pos) /*!< SysTick CALIB: NOREF Mask */ #define SysTick_CALIB_SKEW_Pos 30 /*!< SysTick CALIB: SKEW Position */ #define SysTick_CALIB_SKEW_Msk (1UL << SysTick_CALIB_SKEW_Pos) /*!< SysTick CALIB: SKEW Mask */ #define SysTick_CALIB_TENMS_Pos 0 /*!< SysTick CALIB: TENMS Position */ #define SysTick_CALIB_TENMS_Msk (0xFFFFFFUL /*<< SysTick_CALIB_TENMS_Pos*/) /*!< SysTick CALIB: TENMS Mask */ /*@} end of group CMSIS_SysTick */ /** \ingroup CMSIS_core_register \defgroup CMSIS_ITM Instrumentation Trace Macrocell (ITM) \brief Type definitions for the Instrumentation Trace Macrocell (ITM) @{ */ /** \brief Structure type to access the Instrumentation Trace Macrocell Register (ITM). */ typedef struct { __O union { __O uint8_t u8; /*!< Offset: 0x000 ( /W) ITM Stimulus Port 8-bit */ __O uint16_t u16; /*!< Offset: 0x000 ( /W) ITM Stimulus Port 16-bit */ __O uint32_t u32; /*!< Offset: 0x000 ( /W) ITM Stimulus Port 32-bit */ } PORT [32]; /*!< Offset: 0x000 ( /W) ITM Stimulus Port Registers */ uint32_t RESERVED0[864]; __IO uint32_t TER; /*!< Offset: 0xE00 (R/W) ITM Trace Enable Register */ uint32_t RESERVED1[15]; __IO uint32_t TPR; /*!< Offset: 0xE40 (R/W) ITM Trace Privilege Register */ uint32_t RESERVED2[15]; __IO uint32_t TCR; /*!< Offset: 0xE80 (R/W) ITM Trace Control Register */ uint32_t RESERVED3[29]; __O uint32_t IWR; /*!< Offset: 0xEF8 ( /W) ITM Integration Write Register */ __I uint32_t IRR; /*!< Offset: 0xEFC (R/ ) ITM Integration Read Register */ __IO uint32_t IMCR; /*!< Offset: 0xF00 (R/W) ITM Integration Mode Control Register */ uint32_t RESERVED4[43]; __O uint32_t LAR; /*!< Offset: 0xFB0 ( /W) ITM Lock Access Register */ __I uint32_t LSR; /*!< Offset: 0xFB4 (R/ ) ITM Lock Status Register */ uint32_t RESERVED5[6]; __I uint32_t PID4; /*!< Offset: 0xFD0 (R/ ) ITM Peripheral Identification Register #4 */ __I uint32_t PID5; /*!< Offset: 0xFD4 (R/ ) ITM Peripheral Identification Register #5 */ __I uint32_t PID6; /*!< Offset: 0xFD8 (R/ ) ITM Peripheral Identification Register #6 */ __I uint32_t PID7; /*!< Offset: 0xFDC (R/ ) ITM Peripheral Identification Register #7 */ __I uint32_t PID0; /*!< Offset: 0xFE0 (R/ ) ITM Peripheral Identification Register #0 */ __I uint32_t PID1; /*!< Offset: 0xFE4 (R/ ) ITM Peripheral Identification Register #1 */ __I uint32_t PID2; /*!< Offset: 0xFE8 (R/ ) ITM Peripheral Identification Register #2 */ __I uint32_t PID3; /*!< Offset: 0xFEC (R/ ) ITM Peripheral Identification Register #3 */ __I uint32_t CID0; /*!< Offset: 0xFF0 (R/ ) ITM Component Identification Register #0 */ __I uint32_t CID1; /*!< Offset: 0xFF4 (R/ ) ITM Component Identification Register #1 */ __I uint32_t CID2; /*!< Offset: 0xFF8 (R/ ) ITM Component Identification Register #2 */ __I uint32_t CID3; /*!< Offset: 0xFFC (R/ ) ITM Component Identification Register #3 */ } ITM_Type; /* ITM Trace Privilege Register Definitions */ #define ITM_TPR_PRIVMASK_Pos 0 /*!< ITM TPR: PRIVMASK Position */ #define ITM_TPR_PRIVMASK_Msk (0xFUL /*<< ITM_TPR_PRIVMASK_Pos*/) /*!< ITM TPR: PRIVMASK Mask */ /* ITM Trace Control Register Definitions */ #define ITM_TCR_BUSY_Pos 23 /*!< ITM TCR: BUSY Position */ #define ITM_TCR_BUSY_Msk (1UL << ITM_TCR_BUSY_Pos) /*!< ITM TCR: BUSY Mask */ #define ITM_TCR_TraceBusID_Pos 16 /*!< ITM TCR: ATBID Position */ #define ITM_TCR_TraceBusID_Msk (0x7FUL << ITM_TCR_TraceBusID_Pos) /*!< ITM TCR: ATBID Mask */ #define ITM_TCR_GTSFREQ_Pos 10 /*!< ITM TCR: Global timestamp frequency Position */ #define ITM_TCR_GTSFREQ_Msk (3UL << ITM_TCR_GTSFREQ_Pos) /*!< ITM TCR: Global timestamp frequency Mask */ #define ITM_TCR_TSPrescale_Pos 8 /*!< ITM TCR: TSPrescale Position */ #define ITM_TCR_TSPrescale_Msk (3UL << ITM_TCR_TSPrescale_Pos) /*!< ITM TCR: TSPrescale Mask */ #define ITM_TCR_SWOENA_Pos 4 /*!< ITM TCR: SWOENA Position */ #define ITM_TCR_SWOENA_Msk (1UL << ITM_TCR_SWOENA_Pos) /*!< ITM TCR: SWOENA Mask */ #define ITM_TCR_DWTENA_Pos 3 /*!< ITM TCR: DWTENA Position */ #define ITM_TCR_DWTENA_Msk (1UL << ITM_TCR_DWTENA_Pos) /*!< ITM TCR: DWTENA Mask */ #define ITM_TCR_SYNCENA_Pos 2 /*!< ITM TCR: SYNCENA Position */ #define ITM_TCR_SYNCENA_Msk (1UL << ITM_TCR_SYNCENA_Pos) /*!< ITM TCR: SYNCENA Mask */ #define ITM_TCR_TSENA_Pos 1 /*!< ITM TCR: TSENA Position */ #define ITM_TCR_TSENA_Msk (1UL << ITM_TCR_TSENA_Pos) /*!< ITM TCR: TSENA Mask */ #define ITM_TCR_ITMENA_Pos 0 /*!< ITM TCR: ITM Enable bit Position */ #define ITM_TCR_ITMENA_Msk (1UL /*<< ITM_TCR_ITMENA_Pos*/) /*!< ITM TCR: ITM Enable bit Mask */ /* ITM Integration Write Register Definitions */ #define ITM_IWR_ATVALIDM_Pos 0 /*!< ITM IWR: ATVALIDM Position */ #define ITM_IWR_ATVALIDM_Msk (1UL /*<< ITM_IWR_ATVALIDM_Pos*/) /*!< ITM IWR: ATVALIDM Mask */ /* ITM Integration Read Register Definitions */ #define ITM_IRR_ATREADYM_Pos 0 /*!< ITM IRR: ATREADYM Position */ #define ITM_IRR_ATREADYM_Msk (1UL /*<< ITM_IRR_ATREADYM_Pos*/) /*!< ITM IRR: ATREADYM Mask */ /* ITM Integration Mode Control Register Definitions */ #define ITM_IMCR_INTEGRATION_Pos 0 /*!< ITM IMCR: INTEGRATION Position */ #define ITM_IMCR_INTEGRATION_Msk (1UL /*<< ITM_IMCR_INTEGRATION_Pos*/) /*!< ITM IMCR: INTEGRATION Mask */ /* ITM Lock Status Register Definitions */ #define ITM_LSR_ByteAcc_Pos 2 /*!< ITM LSR: ByteAcc Position */ #define ITM_LSR_ByteAcc_Msk (1UL << ITM_LSR_ByteAcc_Pos) /*!< ITM LSR: ByteAcc Mask */ #define ITM_LSR_Access_Pos 1 /*!< ITM LSR: Access Position */ #define ITM_LSR_Access_Msk (1UL << ITM_LSR_Access_Pos) /*!< ITM LSR: Access Mask */ #define ITM_LSR_Present_Pos 0 /*!< ITM LSR: Present Position */ #define ITM_LSR_Present_Msk (1UL /*<< ITM_LSR_Present_Pos*/) /*!< ITM LSR: Present Mask */ /*@}*/ /* end of group CMSIS_ITM */ /** \ingroup CMSIS_core_register \defgroup CMSIS_DWT Data Watchpoint and Trace (DWT) \brief Type definitions for the Data Watchpoint and Trace (DWT) @{ */ /** \brief Structure type to access the Data Watchpoint and Trace Register (DWT). */ typedef struct { __IO uint32_t CTRL; /*!< Offset: 0x000 (R/W) Control Register */ __IO uint32_t CYCCNT; /*!< Offset: 0x004 (R/W) Cycle Count Register */ __IO uint32_t CPICNT; /*!< Offset: 0x008 (R/W) CPI Count Register */ __IO uint32_t EXCCNT; /*!< Offset: 0x00C (R/W) Exception Overhead Count Register */ __IO uint32_t SLEEPCNT; /*!< Offset: 0x010 (R/W) Sleep Count Register */ __IO uint32_t LSUCNT; /*!< Offset: 0x014 (R/W) LSU Count Register */ __IO uint32_t FOLDCNT; /*!< Offset: 0x018 (R/W) Folded-instruction Count Register */ __I uint32_t PCSR; /*!< Offset: 0x01C (R/ ) Program Counter Sample Register */ __IO uint32_t COMP0; /*!< Offset: 0x020 (R/W) Comparator Register 0 */ __IO uint32_t MASK0; /*!< Offset: 0x024 (R/W) Mask Register 0 */ __IO uint32_t FUNCTION0; /*!< Offset: 0x028 (R/W) Function Register 0 */ uint32_t RESERVED0[1]; __IO uint32_t COMP1; /*!< Offset: 0x030 (R/W) Comparator Register 1 */ __IO uint32_t MASK1; /*!< Offset: 0x034 (R/W) Mask Register 1 */ __IO uint32_t FUNCTION1; /*!< Offset: 0x038 (R/W) Function Register 1 */ uint32_t RESERVED1[1]; __IO uint32_t COMP2; /*!< Offset: 0x040 (R/W) Comparator Register 2 */ __IO uint32_t MASK2; /*!< Offset: 0x044 (R/W) Mask Register 2 */ __IO uint32_t FUNCTION2; /*!< Offset: 0x048 (R/W) Function Register 2 */ uint32_t RESERVED2[1]; __IO uint32_t COMP3; /*!< Offset: 0x050 (R/W) Comparator Register 3 */ __IO uint32_t MASK3; /*!< Offset: 0x054 (R/W) Mask Register 3 */ __IO uint32_t FUNCTION3; /*!< Offset: 0x058 (R/W) Function Register 3 */ uint32_t RESERVED3[981]; __O uint32_t LAR; /*!< Offset: 0xFB0 ( W) Lock Access Register */ __I uint32_t LSR; /*!< Offset: 0xFB4 (R ) Lock Status Register */ } DWT_Type; /* DWT Control Register Definitions */ #define DWT_CTRL_NUMCOMP_Pos 28 /*!< DWT CTRL: NUMCOMP Position */ #define DWT_CTRL_NUMCOMP_Msk (0xFUL << DWT_CTRL_NUMCOMP_Pos) /*!< DWT CTRL: NUMCOMP Mask */ #define DWT_CTRL_NOTRCPKT_Pos 27 /*!< DWT CTRL: NOTRCPKT Position */ #define DWT_CTRL_NOTRCPKT_Msk (0x1UL << DWT_CTRL_NOTRCPKT_Pos) /*!< DWT CTRL: NOTRCPKT Mask */ #define DWT_CTRL_NOEXTTRIG_Pos 26 /*!< DWT CTRL: NOEXTTRIG Position */ #define DWT_CTRL_NOEXTTRIG_Msk (0x1UL << DWT_CTRL_NOEXTTRIG_Pos) /*!< DWT CTRL: NOEXTTRIG Mask */ #define DWT_CTRL_NOCYCCNT_Pos 25 /*!< DWT CTRL: NOCYCCNT Position */ #define DWT_CTRL_NOCYCCNT_Msk (0x1UL << DWT_CTRL_NOCYCCNT_Pos) /*!< DWT CTRL: NOCYCCNT Mask */ #define DWT_CTRL_NOPRFCNT_Pos 24 /*!< DWT CTRL: NOPRFCNT Position */ #define DWT_CTRL_NOPRFCNT_Msk (0x1UL << DWT_CTRL_NOPRFCNT_Pos) /*!< DWT CTRL: NOPRFCNT Mask */ #define DWT_CTRL_CYCEVTENA_Pos 22 /*!< DWT CTRL: CYCEVTENA Position */ #define DWT_CTRL_CYCEVTENA_Msk (0x1UL << DWT_CTRL_CYCEVTENA_Pos) /*!< DWT CTRL: CYCEVTENA Mask */ #define DWT_CTRL_FOLDEVTENA_Pos 21 /*!< DWT CTRL: FOLDEVTENA Position */ #define DWT_CTRL_FOLDEVTENA_Msk (0x1UL << DWT_CTRL_FOLDEVTENA_Pos) /*!< DWT CTRL: FOLDEVTENA Mask */ #define DWT_CTRL_LSUEVTENA_Pos 20 /*!< DWT CTRL: LSUEVTENA Position */ #define DWT_CTRL_LSUEVTENA_Msk (0x1UL << DWT_CTRL_LSUEVTENA_Pos) /*!< DWT CTRL: LSUEVTENA Mask */ #define DWT_CTRL_SLEEPEVTENA_Pos 19 /*!< DWT CTRL: SLEEPEVTENA Position */ #define DWT_CTRL_SLEEPEVTENA_Msk (0x1UL << DWT_CTRL_SLEEPEVTENA_Pos) /*!< DWT CTRL: SLEEPEVTENA Mask */ #define DWT_CTRL_EXCEVTENA_Pos 18 /*!< DWT CTRL: EXCEVTENA Position */ #define DWT_CTRL_EXCEVTENA_Msk (0x1UL << DWT_CTRL_EXCEVTENA_Pos) /*!< DWT CTRL: EXCEVTENA Mask */ #define DWT_CTRL_CPIEVTENA_Pos 17 /*!< DWT CTRL: CPIEVTENA Position */ #define DWT_CTRL_CPIEVTENA_Msk (0x1UL << DWT_CTRL_CPIEVTENA_Pos) /*!< DWT CTRL: CPIEVTENA Mask */ #define DWT_CTRL_EXCTRCENA_Pos 16 /*!< DWT CTRL: EXCTRCENA Position */ #define DWT_CTRL_EXCTRCENA_Msk (0x1UL << DWT_CTRL_EXCTRCENA_Pos) /*!< DWT CTRL: EXCTRCENA Mask */ #define DWT_CTRL_PCSAMPLENA_Pos 12 /*!< DWT CTRL: PCSAMPLENA Position */ #define DWT_CTRL_PCSAMPLENA_Msk (0x1UL << DWT_CTRL_PCSAMPLENA_Pos) /*!< DWT CTRL: PCSAMPLENA Mask */ #define DWT_CTRL_SYNCTAP_Pos 10 /*!< DWT CTRL: SYNCTAP Position */ #define DWT_CTRL_SYNCTAP_Msk (0x3UL << DWT_CTRL_SYNCTAP_Pos) /*!< DWT CTRL: SYNCTAP Mask */ #define DWT_CTRL_CYCTAP_Pos 9 /*!< DWT CTRL: CYCTAP Position */ #define DWT_CTRL_CYCTAP_Msk (0x1UL << DWT_CTRL_CYCTAP_Pos) /*!< DWT CTRL: CYCTAP Mask */ #define DWT_CTRL_POSTINIT_Pos 5 /*!< DWT CTRL: POSTINIT Position */ #define DWT_CTRL_POSTINIT_Msk (0xFUL << DWT_CTRL_POSTINIT_Pos) /*!< DWT CTRL: POSTINIT Mask */ #define DWT_CTRL_POSTPRESET_Pos 1 /*!< DWT CTRL: POSTPRESET Position */ #define DWT_CTRL_POSTPRESET_Msk (0xFUL << DWT_CTRL_POSTPRESET_Pos) /*!< DWT CTRL: POSTPRESET Mask */ #define DWT_CTRL_CYCCNTENA_Pos 0 /*!< DWT CTRL: CYCCNTENA Position */ #define DWT_CTRL_CYCCNTENA_Msk (0x1UL /*<< DWT_CTRL_CYCCNTENA_Pos*/) /*!< DWT CTRL: CYCCNTENA Mask */ /* DWT CPI Count Register Definitions */ #define DWT_CPICNT_CPICNT_Pos 0 /*!< DWT CPICNT: CPICNT Position */ #define DWT_CPICNT_CPICNT_Msk (0xFFUL /*<< DWT_CPICNT_CPICNT_Pos*/) /*!< DWT CPICNT: CPICNT Mask */ /* DWT Exception Overhead Count Register Definitions */ #define DWT_EXCCNT_EXCCNT_Pos 0 /*!< DWT EXCCNT: EXCCNT Position */ #define DWT_EXCCNT_EXCCNT_Msk (0xFFUL /*<< DWT_EXCCNT_EXCCNT_Pos*/) /*!< DWT EXCCNT: EXCCNT Mask */ /* DWT Sleep Count Register Definitions */ #define DWT_SLEEPCNT_SLEEPCNT_Pos 0 /*!< DWT SLEEPCNT: SLEEPCNT Position */ #define DWT_SLEEPCNT_SLEEPCNT_Msk (0xFFUL /*<< DWT_SLEEPCNT_SLEEPCNT_Pos*/) /*!< DWT SLEEPCNT: SLEEPCNT Mask */ /* DWT LSU Count Register Definitions */ #define DWT_LSUCNT_LSUCNT_Pos 0 /*!< DWT LSUCNT: LSUCNT Position */ #define DWT_LSUCNT_LSUCNT_Msk (0xFFUL /*<< DWT_LSUCNT_LSUCNT_Pos*/) /*!< DWT LSUCNT: LSUCNT Mask */ /* DWT Folded-instruction Count Register Definitions */ #define DWT_FOLDCNT_FOLDCNT_Pos 0 /*!< DWT FOLDCNT: FOLDCNT Position */ #define DWT_FOLDCNT_FOLDCNT_Msk (0xFFUL /*<< DWT_FOLDCNT_FOLDCNT_Pos*/) /*!< DWT FOLDCNT: FOLDCNT Mask */ /* DWT Comparator Mask Register Definitions */ #define DWT_MASK_MASK_Pos 0 /*!< DWT MASK: MASK Position */ #define DWT_MASK_MASK_Msk (0x1FUL /*<< DWT_MASK_MASK_Pos*/) /*!< DWT MASK: MASK Mask */ /* DWT Comparator Function Register Definitions */ #define DWT_FUNCTION_MATCHED_Pos 24 /*!< DWT FUNCTION: MATCHED Position */ #define DWT_FUNCTION_MATCHED_Msk (0x1UL << DWT_FUNCTION_MATCHED_Pos) /*!< DWT FUNCTION: MATCHED Mask */ #define DWT_FUNCTION_DATAVADDR1_Pos 16 /*!< DWT FUNCTION: DATAVADDR1 Position */ #define DWT_FUNCTION_DATAVADDR1_Msk (0xFUL << DWT_FUNCTION_DATAVADDR1_Pos) /*!< DWT FUNCTION: DATAVADDR1 Mask */ #define DWT_FUNCTION_DATAVADDR0_Pos 12 /*!< DWT FUNCTION: DATAVADDR0 Position */ #define DWT_FUNCTION_DATAVADDR0_Msk (0xFUL << DWT_FUNCTION_DATAVADDR0_Pos) /*!< DWT FUNCTION: DATAVADDR0 Mask */ #define DWT_FUNCTION_DATAVSIZE_Pos 10 /*!< DWT FUNCTION: DATAVSIZE Position */ #define DWT_FUNCTION_DATAVSIZE_Msk (0x3UL << DWT_FUNCTION_DATAVSIZE_Pos) /*!< DWT FUNCTION: DATAVSIZE Mask */ #define DWT_FUNCTION_LNK1ENA_Pos 9 /*!< DWT FUNCTION: LNK1ENA Position */ #define DWT_FUNCTION_LNK1ENA_Msk (0x1UL << DWT_FUNCTION_LNK1ENA_Pos) /*!< DWT FUNCTION: LNK1ENA Mask */ #define DWT_FUNCTION_DATAVMATCH_Pos 8 /*!< DWT FUNCTION: DATAVMATCH Position */ #define DWT_FUNCTION_DATAVMATCH_Msk (0x1UL << DWT_FUNCTION_DATAVMATCH_Pos) /*!< DWT FUNCTION: DATAVMATCH Mask */ #define DWT_FUNCTION_CYCMATCH_Pos 7 /*!< DWT FUNCTION: CYCMATCH Position */ #define DWT_FUNCTION_CYCMATCH_Msk (0x1UL << DWT_FUNCTION_CYCMATCH_Pos) /*!< DWT FUNCTION: CYCMATCH Mask */ #define DWT_FUNCTION_EMITRANGE_Pos 5 /*!< DWT FUNCTION: EMITRANGE Position */ #define DWT_FUNCTION_EMITRANGE_Msk (0x1UL << DWT_FUNCTION_EMITRANGE_Pos) /*!< DWT FUNCTION: EMITRANGE Mask */ #define DWT_FUNCTION_FUNCTION_Pos 0 /*!< DWT FUNCTION: FUNCTION Position */ #define DWT_FUNCTION_FUNCTION_Msk (0xFUL /*<< DWT_FUNCTION_FUNCTION_Pos*/) /*!< DWT FUNCTION: FUNCTION Mask */ /*@}*/ /* end of group CMSIS_DWT */ /** \ingroup CMSIS_core_register \defgroup CMSIS_TPI Trace Port Interface (TPI) \brief Type definitions for the Trace Port Interface (TPI) @{ */ /** \brief Structure type to access the Trace Port Interface Register (TPI). */ typedef struct { __IO uint32_t SSPSR; /*!< Offset: 0x000 (R/ ) Supported Parallel Port Size Register */ __IO uint32_t CSPSR; /*!< Offset: 0x004 (R/W) Current Parallel Port Size Register */ uint32_t RESERVED0[2]; __IO uint32_t ACPR; /*!< Offset: 0x010 (R/W) Asynchronous Clock Prescaler Register */ uint32_t RESERVED1[55]; __IO uint32_t SPPR; /*!< Offset: 0x0F0 (R/W) Selected Pin Protocol Register */ uint32_t RESERVED2[131]; __I uint32_t FFSR; /*!< Offset: 0x300 (R/ ) Formatter and Flush Status Register */ __IO uint32_t FFCR; /*!< Offset: 0x304 (R/W) Formatter and Flush Control Register */ __I uint32_t FSCR; /*!< Offset: 0x308 (R/ ) Formatter Synchronization Counter Register */ uint32_t RESERVED3[759]; __I uint32_t TRIGGER; /*!< Offset: 0xEE8 (R/ ) TRIGGER */ __I uint32_t FIFO0; /*!< Offset: 0xEEC (R/ ) Integration ETM Data */ __I uint32_t ITATBCTR2; /*!< Offset: 0xEF0 (R/ ) ITATBCTR2 */ uint32_t RESERVED4[1]; __I uint32_t ITATBCTR0; /*!< Offset: 0xEF8 (R/ ) ITATBCTR0 */ __I uint32_t FIFO1; /*!< Offset: 0xEFC (R/ ) Integration ITM Data */ __IO uint32_t ITCTRL; /*!< Offset: 0xF00 (R/W) Integration Mode Control */ uint32_t RESERVED5[39]; __IO uint32_t CLAIMSET; /*!< Offset: 0xFA0 (R/W) Claim tag set */ __IO uint32_t CLAIMCLR; /*!< Offset: 0xFA4 (R/W) Claim tag clear */ uint32_t RESERVED7[8]; __I uint32_t DEVID; /*!< Offset: 0xFC8 (R/ ) TPIU_DEVID */ __I uint32_t DEVTYPE; /*!< Offset: 0xFCC (R/ ) TPIU_DEVTYPE */ } TPI_Type; /* TPI Asynchronous Clock Prescaler Register Definitions */ #define TPI_ACPR_PRESCALER_Pos 0 /*!< TPI ACPR: PRESCALER Position */ #define TPI_ACPR_PRESCALER_Msk (0x1FFFUL /*<< TPI_ACPR_PRESCALER_Pos*/) /*!< TPI ACPR: PRESCALER Mask */ /* TPI Selected Pin Protocol Register Definitions */ #define TPI_SPPR_TXMODE_Pos 0 /*!< TPI SPPR: TXMODE Position */ #define TPI_SPPR_TXMODE_Msk (0x3UL /*<< TPI_SPPR_TXMODE_Pos*/) /*!< TPI SPPR: TXMODE Mask */ /* TPI Formatter and Flush Status Register Definitions */ #define TPI_FFSR_FtNonStop_Pos 3 /*!< TPI FFSR: FtNonStop Position */ #define TPI_FFSR_FtNonStop_Msk (0x1UL << TPI_FFSR_FtNonStop_Pos) /*!< TPI FFSR: FtNonStop Mask */ #define TPI_FFSR_TCPresent_Pos 2 /*!< TPI FFSR: TCPresent Position */ #define TPI_FFSR_TCPresent_Msk (0x1UL << TPI_FFSR_TCPresent_Pos) /*!< TPI FFSR: TCPresent Mask */ #define TPI_FFSR_FtStopped_Pos 1 /*!< TPI FFSR: FtStopped Position */ #define TPI_FFSR_FtStopped_Msk (0x1UL << TPI_FFSR_FtStopped_Pos) /*!< TPI FFSR: FtStopped Mask */ #define TPI_FFSR_FlInProg_Pos 0 /*!< TPI FFSR: FlInProg Position */ #define TPI_FFSR_FlInProg_Msk (0x1UL /*<< TPI_FFSR_FlInProg_Pos*/) /*!< TPI FFSR: FlInProg Mask */ /* TPI Formatter and Flush Control Register Definitions */ #define TPI_FFCR_TrigIn_Pos 8 /*!< TPI FFCR: TrigIn Position */ #define TPI_FFCR_TrigIn_Msk (0x1UL << TPI_FFCR_TrigIn_Pos) /*!< TPI FFCR: TrigIn Mask */ #define TPI_FFCR_EnFCont_Pos 1 /*!< TPI FFCR: EnFCont Position */ #define TPI_FFCR_EnFCont_Msk (0x1UL << TPI_FFCR_EnFCont_Pos) /*!< TPI FFCR: EnFCont Mask */ /* TPI TRIGGER Register Definitions */ #define TPI_TRIGGER_TRIGGER_Pos 0 /*!< TPI TRIGGER: TRIGGER Position */ #define TPI_TRIGGER_TRIGGER_Msk (0x1UL /*<< TPI_TRIGGER_TRIGGER_Pos*/) /*!< TPI TRIGGER: TRIGGER Mask */ /* TPI Integration ETM Data Register Definitions (FIFO0) */ #define TPI_FIFO0_ITM_ATVALID_Pos 29 /*!< TPI FIFO0: ITM_ATVALID Position */ #define TPI_FIFO0_ITM_ATVALID_Msk (0x3UL << TPI_FIFO0_ITM_ATVALID_Pos) /*!< TPI FIFO0: ITM_ATVALID Mask */ #define TPI_FIFO0_ITM_bytecount_Pos 27 /*!< TPI FIFO0: ITM_bytecount Position */ #define TPI_FIFO0_ITM_bytecount_Msk (0x3UL << TPI_FIFO0_ITM_bytecount_Pos) /*!< TPI FIFO0: ITM_bytecount Mask */ #define TPI_FIFO0_ETM_ATVALID_Pos 26 /*!< TPI FIFO0: ETM_ATVALID Position */ #define TPI_FIFO0_ETM_ATVALID_Msk (0x3UL << TPI_FIFO0_ETM_ATVALID_Pos) /*!< TPI FIFO0: ETM_ATVALID Mask */ #define TPI_FIFO0_ETM_bytecount_Pos 24 /*!< TPI FIFO0: ETM_bytecount Position */ #define TPI_FIFO0_ETM_bytecount_Msk (0x3UL << TPI_FIFO0_ETM_bytecount_Pos) /*!< TPI FIFO0: ETM_bytecount Mask */ #define TPI_FIFO0_ETM2_Pos 16 /*!< TPI FIFO0: ETM2 Position */ #define TPI_FIFO0_ETM2_Msk (0xFFUL << TPI_FIFO0_ETM2_Pos) /*!< TPI FIFO0: ETM2 Mask */ #define TPI_FIFO0_ETM1_Pos 8 /*!< TPI FIFO0: ETM1 Position */ #define TPI_FIFO0_ETM1_Msk (0xFFUL << TPI_FIFO0_ETM1_Pos) /*!< TPI FIFO0: ETM1 Mask */ #define TPI_FIFO0_ETM0_Pos 0 /*!< TPI FIFO0: ETM0 Position */ #define TPI_FIFO0_ETM0_Msk (0xFFUL /*<< TPI_FIFO0_ETM0_Pos*/) /*!< TPI FIFO0: ETM0 Mask */ /* TPI ITATBCTR2 Register Definitions */ #define TPI_ITATBCTR2_ATREADY_Pos 0 /*!< TPI ITATBCTR2: ATREADY Position */ #define TPI_ITATBCTR2_ATREADY_Msk (0x1UL /*<< TPI_ITATBCTR2_ATREADY_Pos*/) /*!< TPI ITATBCTR2: ATREADY Mask */ /* TPI Integration ITM Data Register Definitions (FIFO1) */ #define TPI_FIFO1_ITM_ATVALID_Pos 29 /*!< TPI FIFO1: ITM_ATVALID Position */ #define TPI_FIFO1_ITM_ATVALID_Msk (0x3UL << TPI_FIFO1_ITM_ATVALID_Pos) /*!< TPI FIFO1: ITM_ATVALID Mask */ #define TPI_FIFO1_ITM_bytecount_Pos 27 /*!< TPI FIFO1: ITM_bytecount Position */ #define TPI_FIFO1_ITM_bytecount_Msk (0x3UL << TPI_FIFO1_ITM_bytecount_Pos) /*!< TPI FIFO1: ITM_bytecount Mask */ #define TPI_FIFO1_ETM_ATVALID_Pos 26 /*!< TPI FIFO1: ETM_ATVALID Position */ #define TPI_FIFO1_ETM_ATVALID_Msk (0x3UL << TPI_FIFO1_ETM_ATVALID_Pos) /*!< TPI FIFO1: ETM_ATVALID Mask */ #define TPI_FIFO1_ETM_bytecount_Pos 24 /*!< TPI FIFO1: ETM_bytecount Position */ #define TPI_FIFO1_ETM_bytecount_Msk (0x3UL << TPI_FIFO1_ETM_bytecount_Pos) /*!< TPI FIFO1: ETM_bytecount Mask */ #define TPI_FIFO1_ITM2_Pos 16 /*!< TPI FIFO1: ITM2 Position */ #define TPI_FIFO1_ITM2_Msk (0xFFUL << TPI_FIFO1_ITM2_Pos) /*!< TPI FIFO1: ITM2 Mask */ #define TPI_FIFO1_ITM1_Pos 8 /*!< TPI FIFO1: ITM1 Position */ #define TPI_FIFO1_ITM1_Msk (0xFFUL << TPI_FIFO1_ITM1_Pos) /*!< TPI FIFO1: ITM1 Mask */ #define TPI_FIFO1_ITM0_Pos 0 /*!< TPI FIFO1: ITM0 Position */ #define TPI_FIFO1_ITM0_Msk (0xFFUL /*<< TPI_FIFO1_ITM0_Pos*/) /*!< TPI FIFO1: ITM0 Mask */ /* TPI ITATBCTR0 Register Definitions */ #define TPI_ITATBCTR0_ATREADY_Pos 0 /*!< TPI ITATBCTR0: ATREADY Position */ #define TPI_ITATBCTR0_ATREADY_Msk (0x1UL /*<< TPI_ITATBCTR0_ATREADY_Pos*/) /*!< TPI ITATBCTR0: ATREADY Mask */ /* TPI Integration Mode Control Register Definitions */ #define TPI_ITCTRL_Mode_Pos 0 /*!< TPI ITCTRL: Mode Position */ #define TPI_ITCTRL_Mode_Msk (0x1UL /*<< TPI_ITCTRL_Mode_Pos*/) /*!< TPI ITCTRL: Mode Mask */ /* TPI DEVID Register Definitions */ #define TPI_DEVID_NRZVALID_Pos 11 /*!< TPI DEVID: NRZVALID Position */ #define TPI_DEVID_NRZVALID_Msk (0x1UL << TPI_DEVID_NRZVALID_Pos) /*!< TPI DEVID: NRZVALID Mask */ #define TPI_DEVID_MANCVALID_Pos 10 /*!< TPI DEVID: MANCVALID Position */ #define TPI_DEVID_MANCVALID_Msk (0x1UL << TPI_DEVID_MANCVALID_Pos) /*!< TPI DEVID: MANCVALID Mask */ #define TPI_DEVID_PTINVALID_Pos 9 /*!< TPI DEVID: PTINVALID Position */ #define TPI_DEVID_PTINVALID_Msk (0x1UL << TPI_DEVID_PTINVALID_Pos) /*!< TPI DEVID: PTINVALID Mask */ #define TPI_DEVID_MinBufSz_Pos 6 /*!< TPI DEVID: MinBufSz Position */ #define TPI_DEVID_MinBufSz_Msk (0x7UL << TPI_DEVID_MinBufSz_Pos) /*!< TPI DEVID: MinBufSz Mask */ #define TPI_DEVID_AsynClkIn_Pos 5 /*!< TPI DEVID: AsynClkIn Position */ #define TPI_DEVID_AsynClkIn_Msk (0x1UL << TPI_DEVID_AsynClkIn_Pos) /*!< TPI DEVID: AsynClkIn Mask */ #define TPI_DEVID_NrTraceInput_Pos 0 /*!< TPI DEVID: NrTraceInput Position */ #define TPI_DEVID_NrTraceInput_Msk (0x1FUL /*<< TPI_DEVID_NrTraceInput_Pos*/) /*!< TPI DEVID: NrTraceInput Mask */ /* TPI DEVTYPE Register Definitions */ #define TPI_DEVTYPE_MajorType_Pos 4 /*!< TPI DEVTYPE: MajorType Position */ #define TPI_DEVTYPE_MajorType_Msk (0xFUL << TPI_DEVTYPE_MajorType_Pos) /*!< TPI DEVTYPE: MajorType Mask */ #define TPI_DEVTYPE_SubType_Pos 0 /*!< TPI DEVTYPE: SubType Position */ #define TPI_DEVTYPE_SubType_Msk (0xFUL /*<< TPI_DEVTYPE_SubType_Pos*/) /*!< TPI DEVTYPE: SubType Mask */ /*@}*/ /* end of group CMSIS_TPI */ #if (__MPU_PRESENT == 1) /** \ingroup CMSIS_core_register \defgroup CMSIS_MPU Memory Protection Unit (MPU) \brief Type definitions for the Memory Protection Unit (MPU) @{ */ /** \brief Structure type to access the Memory Protection Unit (MPU). */ typedef struct { __I uint32_t TYPE; /*!< Offset: 0x000 (R/ ) MPU Type Register */ __IO uint32_t CTRL; /*!< Offset: 0x004 (R/W) MPU Control Register */ __IO uint32_t RNR; /*!< Offset: 0x008 (R/W) MPU Region RNRber Register */ __IO uint32_t RBAR; /*!< Offset: 0x00C (R/W) MPU Region Base Address Register */ __IO uint32_t RASR; /*!< Offset: 0x010 (R/W) MPU Region Attribute and Size Register */ __IO uint32_t RBAR_A1; /*!< Offset: 0x014 (R/W) MPU Alias 1 Region Base Address Register */ __IO uint32_t RASR_A1; /*!< Offset: 0x018 (R/W) MPU Alias 1 Region Attribute and Size Register */ __IO uint32_t RBAR_A2; /*!< Offset: 0x01C (R/W) MPU Alias 2 Region Base Address Register */ __IO uint32_t RASR_A2; /*!< Offset: 0x020 (R/W) MPU Alias 2 Region Attribute and Size Register */ __IO uint32_t RBAR_A3; /*!< Offset: 0x024 (R/W) MPU Alias 3 Region Base Address Register */ __IO uint32_t RASR_A3; /*!< Offset: 0x028 (R/W) MPU Alias 3 Region Attribute and Size Register */ } MPU_Type; /* MPU Type Register */ #define MPU_TYPE_IREGION_Pos 16 /*!< MPU TYPE: IREGION Position */ #define MPU_TYPE_IREGION_Msk (0xFFUL << MPU_TYPE_IREGION_Pos) /*!< MPU TYPE: IREGION Mask */ #define MPU_TYPE_DREGION_Pos 8 /*!< MPU TYPE: DREGION Position */ #define MPU_TYPE_DREGION_Msk (0xFFUL << MPU_TYPE_DREGION_Pos) /*!< MPU TYPE: DREGION Mask */ #define MPU_TYPE_SEPARATE_Pos 0 /*!< MPU TYPE: SEPARATE Position */ #define MPU_TYPE_SEPARATE_Msk (1UL /*<< MPU_TYPE_SEPARATE_Pos*/) /*!< MPU TYPE: SEPARATE Mask */ /* MPU Control Register */ #define MPU_CTRL_PRIVDEFENA_Pos 2 /*!< MPU CTRL: PRIVDEFENA Position */ #define MPU_CTRL_PRIVDEFENA_Msk (1UL << MPU_CTRL_PRIVDEFENA_Pos) /*!< MPU CTRL: PRIVDEFENA Mask */ #define MPU_CTRL_HFNMIENA_Pos 1 /*!< MPU CTRL: HFNMIENA Position */ #define MPU_CTRL_HFNMIENA_Msk (1UL << MPU_CTRL_HFNMIENA_Pos) /*!< MPU CTRL: HFNMIENA Mask */ #define MPU_CTRL_ENABLE_Pos 0 /*!< MPU CTRL: ENABLE Position */ #define MPU_CTRL_ENABLE_Msk (1UL /*<< MPU_CTRL_ENABLE_Pos*/) /*!< MPU CTRL: ENABLE Mask */ /* MPU Region Number Register */ #define MPU_RNR_REGION_Pos 0 /*!< MPU RNR: REGION Position */ #define MPU_RNR_REGION_Msk (0xFFUL /*<< MPU_RNR_REGION_Pos*/) /*!< MPU RNR: REGION Mask */ /* MPU Region Base Address Register */ #define MPU_RBAR_ADDR_Pos 5 /*!< MPU RBAR: ADDR Position */ #define MPU_RBAR_ADDR_Msk (0x7FFFFFFUL << MPU_RBAR_ADDR_Pos) /*!< MPU RBAR: ADDR Mask */ #define MPU_RBAR_VALID_Pos 4 /*!< MPU RBAR: VALID Position */ #define MPU_RBAR_VALID_Msk (1UL << MPU_RBAR_VALID_Pos) /*!< MPU RBAR: VALID Mask */ #define MPU_RBAR_REGION_Pos 0 /*!< MPU RBAR: REGION Position */ #define MPU_RBAR_REGION_Msk (0xFUL /*<< MPU_RBAR_REGION_Pos*/) /*!< MPU RBAR: REGION Mask */ /* MPU Region Attribute and Size Register */ #define MPU_RASR_ATTRS_Pos 16 /*!< MPU RASR: MPU Region Attribute field Position */ #define MPU_RASR_ATTRS_Msk (0xFFFFUL << MPU_RASR_ATTRS_Pos) /*!< MPU RASR: MPU Region Attribute field Mask */ #define MPU_RASR_XN_Pos 28 /*!< MPU RASR: ATTRS.XN Position */ #define MPU_RASR_XN_Msk (1UL << MPU_RASR_XN_Pos) /*!< MPU RASR: ATTRS.XN Mask */ #define MPU_RASR_AP_Pos 24 /*!< MPU RASR: ATTRS.AP Position */ #define MPU_RASR_AP_Msk (0x7UL << MPU_RASR_AP_Pos) /*!< MPU RASR: ATTRS.AP Mask */ #define MPU_RASR_TEX_Pos 19 /*!< MPU RASR: ATTRS.TEX Position */ #define MPU_RASR_TEX_Msk (0x7UL << MPU_RASR_TEX_Pos) /*!< MPU RASR: ATTRS.TEX Mask */ #define MPU_RASR_S_Pos 18 /*!< MPU RASR: ATTRS.S Position */ #define MPU_RASR_S_Msk (1UL << MPU_RASR_S_Pos) /*!< MPU RASR: ATTRS.S Mask */ #define MPU_RASR_C_Pos 17 /*!< MPU RASR: ATTRS.C Position */ #define MPU_RASR_C_Msk (1UL << MPU_RASR_C_Pos) /*!< MPU RASR: ATTRS.C Mask */ #define MPU_RASR_B_Pos 16 /*!< MPU RASR: ATTRS.B Position */ #define MPU_RASR_B_Msk (1UL << MPU_RASR_B_Pos) /*!< MPU RASR: ATTRS.B Mask */ #define MPU_RASR_SRD_Pos 8 /*!< MPU RASR: Sub-Region Disable Position */ #define MPU_RASR_SRD_Msk (0xFFUL << MPU_RASR_SRD_Pos) /*!< MPU RASR: Sub-Region Disable Mask */ #define MPU_RASR_SIZE_Pos 1 /*!< MPU RASR: Region Size Field Position */ #define MPU_RASR_SIZE_Msk (0x1FUL << MPU_RASR_SIZE_Pos) /*!< MPU RASR: Region Size Field Mask */ #define MPU_RASR_ENABLE_Pos 0 /*!< MPU RASR: Region enable bit Position */ #define MPU_RASR_ENABLE_Msk (1UL /*<< MPU_RASR_ENABLE_Pos*/) /*!< MPU RASR: Region enable bit Disable Mask */ /*@} end of group CMSIS_MPU */ #endif #if (__FPU_PRESENT == 1) /** \ingroup CMSIS_core_register \defgroup CMSIS_FPU Floating Point Unit (FPU) \brief Type definitions for the Floating Point Unit (FPU) @{ */ /** \brief Structure type to access the Floating Point Unit (FPU). */ typedef struct { uint32_t RESERVED0[1]; __IO uint32_t FPCCR; /*!< Offset: 0x004 (R/W) Floating-Point Context Control Register */ __IO uint32_t FPCAR; /*!< Offset: 0x008 (R/W) Floating-Point Context Address Register */ __IO uint32_t FPDSCR; /*!< Offset: 0x00C (R/W) Floating-Point Default Status Control Register */ __I uint32_t MVFR0; /*!< Offset: 0x010 (R/ ) Media and FP Feature Register 0 */ __I uint32_t MVFR1; /*!< Offset: 0x014 (R/ ) Media and FP Feature Register 1 */ __I uint32_t MVFR2; /*!< Offset: 0x018 (R/ ) Media and FP Feature Register 2 */ } FPU_Type; /* Floating-Point Context Control Register */ #define FPU_FPCCR_ASPEN_Pos 31 /*!< FPCCR: ASPEN bit Position */ #define FPU_FPCCR_ASPEN_Msk (1UL << FPU_FPCCR_ASPEN_Pos) /*!< FPCCR: ASPEN bit Mask */ #define FPU_FPCCR_LSPEN_Pos 30 /*!< FPCCR: LSPEN Position */ #define FPU_FPCCR_LSPEN_Msk (1UL << FPU_FPCCR_LSPEN_Pos) /*!< FPCCR: LSPEN bit Mask */ #define FPU_FPCCR_MONRDY_Pos 8 /*!< FPCCR: MONRDY Position */ #define FPU_FPCCR_MONRDY_Msk (1UL << FPU_FPCCR_MONRDY_Pos) /*!< FPCCR: MONRDY bit Mask */ #define FPU_FPCCR_BFRDY_Pos 6 /*!< FPCCR: BFRDY Position */ #define FPU_FPCCR_BFRDY_Msk (1UL << FPU_FPCCR_BFRDY_Pos) /*!< FPCCR: BFRDY bit Mask */ #define FPU_FPCCR_MMRDY_Pos 5 /*!< FPCCR: MMRDY Position */ #define FPU_FPCCR_MMRDY_Msk (1UL << FPU_FPCCR_MMRDY_Pos) /*!< FPCCR: MMRDY bit Mask */ #define FPU_FPCCR_HFRDY_Pos 4 /*!< FPCCR: HFRDY Position */ #define FPU_FPCCR_HFRDY_Msk (1UL << FPU_FPCCR_HFRDY_Pos) /*!< FPCCR: HFRDY bit Mask */ #define FPU_FPCCR_THREAD_Pos 3 /*!< FPCCR: processor mode bit Position */ #define FPU_FPCCR_THREAD_Msk (1UL << FPU_FPCCR_THREAD_Pos) /*!< FPCCR: processor mode active bit Mask */ #define FPU_FPCCR_USER_Pos 1 /*!< FPCCR: privilege level bit Position */ #define FPU_FPCCR_USER_Msk (1UL << FPU_FPCCR_USER_Pos) /*!< FPCCR: privilege level bit Mask */ #define FPU_FPCCR_LSPACT_Pos 0 /*!< FPCCR: Lazy state preservation active bit Position */ #define FPU_FPCCR_LSPACT_Msk (1UL /*<< FPU_FPCCR_LSPACT_Pos*/) /*!< FPCCR: Lazy state preservation active bit Mask */ /* Floating-Point Context Address Register */ #define FPU_FPCAR_ADDRESS_Pos 3 /*!< FPCAR: ADDRESS bit Position */ #define FPU_FPCAR_ADDRESS_Msk (0x1FFFFFFFUL << FPU_FPCAR_ADDRESS_Pos) /*!< FPCAR: ADDRESS bit Mask */ /* Floating-Point Default Status Control Register */ #define FPU_FPDSCR_AHP_Pos 26 /*!< FPDSCR: AHP bit Position */ #define FPU_FPDSCR_AHP_Msk (1UL << FPU_FPDSCR_AHP_Pos) /*!< FPDSCR: AHP bit Mask */ #define FPU_FPDSCR_DN_Pos 25 /*!< FPDSCR: DN bit Position */ #define FPU_FPDSCR_DN_Msk (1UL << FPU_FPDSCR_DN_Pos) /*!< FPDSCR: DN bit Mask */ #define FPU_FPDSCR_FZ_Pos 24 /*!< FPDSCR: FZ bit Position */ #define FPU_FPDSCR_FZ_Msk (1UL << FPU_FPDSCR_FZ_Pos) /*!< FPDSCR: FZ bit Mask */ #define FPU_FPDSCR_RMode_Pos 22 /*!< FPDSCR: RMode bit Position */ #define FPU_FPDSCR_RMode_Msk (3UL << FPU_FPDSCR_RMode_Pos) /*!< FPDSCR: RMode bit Mask */ /* Media and FP Feature Register 0 */ #define FPU_MVFR0_FP_rounding_modes_Pos 28 /*!< MVFR0: FP rounding modes bits Position */ #define FPU_MVFR0_FP_rounding_modes_Msk (0xFUL << FPU_MVFR0_FP_rounding_modes_Pos) /*!< MVFR0: FP rounding modes bits Mask */ #define FPU_MVFR0_Short_vectors_Pos 24 /*!< MVFR0: Short vectors bits Position */ #define FPU_MVFR0_Short_vectors_Msk (0xFUL << FPU_MVFR0_Short_vectors_Pos) /*!< MVFR0: Short vectors bits Mask */ #define FPU_MVFR0_Square_root_Pos 20 /*!< MVFR0: Square root bits Position */ #define FPU_MVFR0_Square_root_Msk (0xFUL << FPU_MVFR0_Square_root_Pos) /*!< MVFR0: Square root bits Mask */ #define FPU_MVFR0_Divide_Pos 16 /*!< MVFR0: Divide bits Position */ #define FPU_MVFR0_Divide_Msk (0xFUL << FPU_MVFR0_Divide_Pos) /*!< MVFR0: Divide bits Mask */ #define FPU_MVFR0_FP_excep_trapping_Pos 12 /*!< MVFR0: FP exception trapping bits Position */ #define FPU_MVFR0_FP_excep_trapping_Msk (0xFUL << FPU_MVFR0_FP_excep_trapping_Pos) /*!< MVFR0: FP exception trapping bits Mask */ #define FPU_MVFR0_Double_precision_Pos 8 /*!< MVFR0: Double-precision bits Position */ #define FPU_MVFR0_Double_precision_Msk (0xFUL << FPU_MVFR0_Double_precision_Pos) /*!< MVFR0: Double-precision bits Mask */ #define FPU_MVFR0_Single_precision_Pos 4 /*!< MVFR0: Single-precision bits Position */ #define FPU_MVFR0_Single_precision_Msk (0xFUL << FPU_MVFR0_Single_precision_Pos) /*!< MVFR0: Single-precision bits Mask */ #define FPU_MVFR0_A_SIMD_registers_Pos 0 /*!< MVFR0: A_SIMD registers bits Position */ #define FPU_MVFR0_A_SIMD_registers_Msk (0xFUL /*<< FPU_MVFR0_A_SIMD_registers_Pos*/) /*!< MVFR0: A_SIMD registers bits Mask */ /* Media and FP Feature Register 1 */ #define FPU_MVFR1_FP_fused_MAC_Pos 28 /*!< MVFR1: FP fused MAC bits Position */ #define FPU_MVFR1_FP_fused_MAC_Msk (0xFUL << FPU_MVFR1_FP_fused_MAC_Pos) /*!< MVFR1: FP fused MAC bits Mask */ #define FPU_MVFR1_FP_HPFP_Pos 24 /*!< MVFR1: FP HPFP bits Position */ #define FPU_MVFR1_FP_HPFP_Msk (0xFUL << FPU_MVFR1_FP_HPFP_Pos) /*!< MVFR1: FP HPFP bits Mask */ #define FPU_MVFR1_D_NaN_mode_Pos 4 /*!< MVFR1: D_NaN mode bits Position */ #define FPU_MVFR1_D_NaN_mode_Msk (0xFUL << FPU_MVFR1_D_NaN_mode_Pos) /*!< MVFR1: D_NaN mode bits Mask */ #define FPU_MVFR1_FtZ_mode_Pos 0 /*!< MVFR1: FtZ mode bits Position */ #define FPU_MVFR1_FtZ_mode_Msk (0xFUL /*<< FPU_MVFR1_FtZ_mode_Pos*/) /*!< MVFR1: FtZ mode bits Mask */ /* Media and FP Feature Register 2 */ /*@} end of group CMSIS_FPU */ #endif /** \ingroup CMSIS_core_register \defgroup CMSIS_CoreDebug Core Debug Registers (CoreDebug) \brief Type definitions for the Core Debug Registers @{ */ /** \brief Structure type to access the Core Debug Register (CoreDebug). */ typedef struct { __IO uint32_t DHCSR; /*!< Offset: 0x000 (R/W) Debug Halting Control and Status Register */ __O uint32_t DCRSR; /*!< Offset: 0x004 ( /W) Debug Core Register Selector Register */ __IO uint32_t DCRDR; /*!< Offset: 0x008 (R/W) Debug Core Register Data Register */ __IO uint32_t DEMCR; /*!< Offset: 0x00C (R/W) Debug Exception and Monitor Control Register */ } CoreDebug_Type; /* Debug Halting Control and Status Register */ #define CoreDebug_DHCSR_DBGKEY_Pos 16 /*!< CoreDebug DHCSR: DBGKEY Position */ #define CoreDebug_DHCSR_DBGKEY_Msk (0xFFFFUL << CoreDebug_DHCSR_DBGKEY_Pos) /*!< CoreDebug DHCSR: DBGKEY Mask */ #define CoreDebug_DHCSR_S_RESET_ST_Pos 25 /*!< CoreDebug DHCSR: S_RESET_ST Position */ #define CoreDebug_DHCSR_S_RESET_ST_Msk (1UL << CoreDebug_DHCSR_S_RESET_ST_Pos) /*!< CoreDebug DHCSR: S_RESET_ST Mask */ #define CoreDebug_DHCSR_S_RETIRE_ST_Pos 24 /*!< CoreDebug DHCSR: S_RETIRE_ST Position */ #define CoreDebug_DHCSR_S_RETIRE_ST_Msk (1UL << CoreDebug_DHCSR_S_RETIRE_ST_Pos) /*!< CoreDebug DHCSR: S_RETIRE_ST Mask */ #define CoreDebug_DHCSR_S_LOCKUP_Pos 19 /*!< CoreDebug DHCSR: S_LOCKUP Position */ #define CoreDebug_DHCSR_S_LOCKUP_Msk (1UL << CoreDebug_DHCSR_S_LOCKUP_Pos) /*!< CoreDebug DHCSR: S_LOCKUP Mask */ #define CoreDebug_DHCSR_S_SLEEP_Pos 18 /*!< CoreDebug DHCSR: S_SLEEP Position */ #define CoreDebug_DHCSR_S_SLEEP_Msk (1UL << CoreDebug_DHCSR_S_SLEEP_Pos) /*!< CoreDebug DHCSR: S_SLEEP Mask */ #define CoreDebug_DHCSR_S_HALT_Pos 17 /*!< CoreDebug DHCSR: S_HALT Position */ #define CoreDebug_DHCSR_S_HALT_Msk (1UL << CoreDebug_DHCSR_S_HALT_Pos) /*!< CoreDebug DHCSR: S_HALT Mask */ #define CoreDebug_DHCSR_S_REGRDY_Pos 16 /*!< CoreDebug DHCSR: S_REGRDY Position */ #define CoreDebug_DHCSR_S_REGRDY_Msk (1UL << CoreDebug_DHCSR_S_REGRDY_Pos) /*!< CoreDebug DHCSR: S_REGRDY Mask */ #define CoreDebug_DHCSR_C_SNAPSTALL_Pos 5 /*!< CoreDebug DHCSR: C_SNAPSTALL Position */ #define CoreDebug_DHCSR_C_SNAPSTALL_Msk (1UL << CoreDebug_DHCSR_C_SNAPSTALL_Pos) /*!< CoreDebug DHCSR: C_SNAPSTALL Mask */ #define CoreDebug_DHCSR_C_MASKINTS_Pos 3 /*!< CoreDebug DHCSR: C_MASKINTS Position */ #define CoreDebug_DHCSR_C_MASKINTS_Msk (1UL << CoreDebug_DHCSR_C_MASKINTS_Pos) /*!< CoreDebug DHCSR: C_MASKINTS Mask */ #define CoreDebug_DHCSR_C_STEP_Pos 2 /*!< CoreDebug DHCSR: C_STEP Position */ #define CoreDebug_DHCSR_C_STEP_Msk (1UL << CoreDebug_DHCSR_C_STEP_Pos) /*!< CoreDebug DHCSR: C_STEP Mask */ #define CoreDebug_DHCSR_C_HALT_Pos 1 /*!< CoreDebug DHCSR: C_HALT Position */ #define CoreDebug_DHCSR_C_HALT_Msk (1UL << CoreDebug_DHCSR_C_HALT_Pos) /*!< CoreDebug DHCSR: C_HALT Mask */ #define CoreDebug_DHCSR_C_DEBUGEN_Pos 0 /*!< CoreDebug DHCSR: C_DEBUGEN Position */ #define CoreDebug_DHCSR_C_DEBUGEN_Msk (1UL /*<< CoreDebug_DHCSR_C_DEBUGEN_Pos*/) /*!< CoreDebug DHCSR: C_DEBUGEN Mask */ /* Debug Core Register Selector Register */ #define CoreDebug_DCRSR_REGWnR_Pos 16 /*!< CoreDebug DCRSR: REGWnR Position */ #define CoreDebug_DCRSR_REGWnR_Msk (1UL << CoreDebug_DCRSR_REGWnR_Pos) /*!< CoreDebug DCRSR: REGWnR Mask */ #define CoreDebug_DCRSR_REGSEL_Pos 0 /*!< CoreDebug DCRSR: REGSEL Position */ #define CoreDebug_DCRSR_REGSEL_Msk (0x1FUL /*<< CoreDebug_DCRSR_REGSEL_Pos*/) /*!< CoreDebug DCRSR: REGSEL Mask */ /* Debug Exception and Monitor Control Register */ #define CoreDebug_DEMCR_TRCENA_Pos 24 /*!< CoreDebug DEMCR: TRCENA Position */ #define CoreDebug_DEMCR_TRCENA_Msk (1UL << CoreDebug_DEMCR_TRCENA_Pos) /*!< CoreDebug DEMCR: TRCENA Mask */ #define CoreDebug_DEMCR_MON_REQ_Pos 19 /*!< CoreDebug DEMCR: MON_REQ Position */ #define CoreDebug_DEMCR_MON_REQ_Msk (1UL << CoreDebug_DEMCR_MON_REQ_Pos) /*!< CoreDebug DEMCR: MON_REQ Mask */ #define CoreDebug_DEMCR_MON_STEP_Pos 18 /*!< CoreDebug DEMCR: MON_STEP Position */ #define CoreDebug_DEMCR_MON_STEP_Msk (1UL << CoreDebug_DEMCR_MON_STEP_Pos) /*!< CoreDebug DEMCR: MON_STEP Mask */ #define CoreDebug_DEMCR_MON_PEND_Pos 17 /*!< CoreDebug DEMCR: MON_PEND Position */ #define CoreDebug_DEMCR_MON_PEND_Msk (1UL << CoreDebug_DEMCR_MON_PEND_Pos) /*!< CoreDebug DEMCR: MON_PEND Mask */ #define CoreDebug_DEMCR_MON_EN_Pos 16 /*!< CoreDebug DEMCR: MON_EN Position */ #define CoreDebug_DEMCR_MON_EN_Msk (1UL << CoreDebug_DEMCR_MON_EN_Pos) /*!< CoreDebug DEMCR: MON_EN Mask */ #define CoreDebug_DEMCR_VC_HARDERR_Pos 10 /*!< CoreDebug DEMCR: VC_HARDERR Position */ #define CoreDebug_DEMCR_VC_HARDERR_Msk (1UL << CoreDebug_DEMCR_VC_HARDERR_Pos) /*!< CoreDebug DEMCR: VC_HARDERR Mask */ #define CoreDebug_DEMCR_VC_INTERR_Pos 9 /*!< CoreDebug DEMCR: VC_INTERR Position */ #define CoreDebug_DEMCR_VC_INTERR_Msk (1UL << CoreDebug_DEMCR_VC_INTERR_Pos) /*!< CoreDebug DEMCR: VC_INTERR Mask */ #define CoreDebug_DEMCR_VC_BUSERR_Pos 8 /*!< CoreDebug DEMCR: VC_BUSERR Position */ #define CoreDebug_DEMCR_VC_BUSERR_Msk (1UL << CoreDebug_DEMCR_VC_BUSERR_Pos) /*!< CoreDebug DEMCR: VC_BUSERR Mask */ #define CoreDebug_DEMCR_VC_STATERR_Pos 7 /*!< CoreDebug DEMCR: VC_STATERR Position */ #define CoreDebug_DEMCR_VC_STATERR_Msk (1UL << CoreDebug_DEMCR_VC_STATERR_Pos) /*!< CoreDebug DEMCR: VC_STATERR Mask */ #define CoreDebug_DEMCR_VC_CHKERR_Pos 6 /*!< CoreDebug DEMCR: VC_CHKERR Position */ #define CoreDebug_DEMCR_VC_CHKERR_Msk (1UL << CoreDebug_DEMCR_VC_CHKERR_Pos) /*!< CoreDebug DEMCR: VC_CHKERR Mask */ #define CoreDebug_DEMCR_VC_NOCPERR_Pos 5 /*!< CoreDebug DEMCR: VC_NOCPERR Position */ #define CoreDebug_DEMCR_VC_NOCPERR_Msk (1UL << CoreDebug_DEMCR_VC_NOCPERR_Pos) /*!< CoreDebug DEMCR: VC_NOCPERR Mask */ #define CoreDebug_DEMCR_VC_MMERR_Pos 4 /*!< CoreDebug DEMCR: VC_MMERR Position */ #define CoreDebug_DEMCR_VC_MMERR_Msk (1UL << CoreDebug_DEMCR_VC_MMERR_Pos) /*!< CoreDebug DEMCR: VC_MMERR Mask */ #define CoreDebug_DEMCR_VC_CORERESET_Pos 0 /*!< CoreDebug DEMCR: VC_CORERESET Position */ #define CoreDebug_DEMCR_VC_CORERESET_Msk (1UL /*<< CoreDebug_DEMCR_VC_CORERESET_Pos*/) /*!< CoreDebug DEMCR: VC_CORERESET Mask */ /*@} end of group CMSIS_CoreDebug */ /** \ingroup CMSIS_core_register \defgroup CMSIS_core_base Core Definitions \brief Definitions for base addresses, unions, and structures. @{ */ /* Memory mapping of Cortex-M4 Hardware */ #define SCS_BASE (0xE000E000UL) /*!< System Control Space Base Address */ #define ITM_BASE (0xE0000000UL) /*!< ITM Base Address */ #define DWT_BASE (0xE0001000UL) /*!< DWT Base Address */ #define TPI_BASE (0xE0040000UL) /*!< TPI Base Address */ #define CoreDebug_BASE (0xE000EDF0UL) /*!< Core Debug Base Address */ #define SysTick_BASE (SCS_BASE + 0x0010UL) /*!< SysTick Base Address */ #define NVIC_BASE (SCS_BASE + 0x0100UL) /*!< NVIC Base Address */ #define SCB_BASE (SCS_BASE + 0x0D00UL) /*!< System Control Block Base Address */ #define SCnSCB ((SCnSCB_Type *) SCS_BASE ) /*!< System control Register not in SCB */ #define SCB ((SCB_Type *) SCB_BASE ) /*!< SCB configuration struct */ #define SysTick ((SysTick_Type *) SysTick_BASE ) /*!< SysTick configuration struct */ #define NVIC ((NVIC_Type *) NVIC_BASE ) /*!< NVIC configuration struct */ #define ITM ((ITM_Type *) ITM_BASE ) /*!< ITM configuration struct */ #define DWT ((DWT_Type *) DWT_BASE ) /*!< DWT configuration struct */ #define TPI ((TPI_Type *) TPI_BASE ) /*!< TPI configuration struct */ #define CoreDebug ((CoreDebug_Type *) CoreDebug_BASE) /*!< Core Debug configuration struct */ #if (__MPU_PRESENT == 1) #define MPU_BASE (SCS_BASE + 0x0D90UL) /*!< Memory Protection Unit */ #define MPU ((MPU_Type *) MPU_BASE ) /*!< Memory Protection Unit */ #endif #if (__FPU_PRESENT == 1) #define FPU_BASE (SCS_BASE + 0x0F30UL) /*!< Floating Point Unit */ #define FPU ((FPU_Type *) FPU_BASE ) /*!< Floating Point Unit */ #endif /*@} */ /******************************************************************************* * Hardware Abstraction Layer Core Function Interface contains: - Core NVIC Functions - Core SysTick Functions - Core Debug Functions - Core Register Access Functions ******************************************************************************/ /** \defgroup CMSIS_Core_FunctionInterface Functions and Instructions Reference */ /* ########################## NVIC functions #################################### */ /** \ingroup CMSIS_Core_FunctionInterface \defgroup CMSIS_Core_NVICFunctions NVIC Functions \brief Functions that manage interrupts and exceptions via the NVIC. @{ */ /** \brief Set Priority Grouping The function sets the priority grouping field using the required unlock sequence. The parameter PriorityGroup is assigned to the field SCB->AIRCR [10:8] PRIGROUP field. Only values from 0..7 are used. In case of a conflict between priority grouping and available priority bits (__NVIC_PRIO_BITS), the smallest possible priority group is set. \param [in] PriorityGroup Priority grouping field. */ __STATIC_INLINE void NVIC_SetPriorityGrouping(uint32_t PriorityGroup) { uint32_t reg_value; uint32_t PriorityGroupTmp = (PriorityGroup & (uint32_t)0x07UL); /* only values 0..7 are used */ reg_value = SCB->AIRCR; /* read old register configuration */ reg_value &= ~((uint32_t)(SCB_AIRCR_VECTKEY_Msk | SCB_AIRCR_PRIGROUP_Msk)); /* clear bits to change */ reg_value = (reg_value | ((uint32_t)0x5FAUL << SCB_AIRCR_VECTKEY_Pos) | (PriorityGroupTmp << 8) ); /* Insert write key and priorty group */ SCB->AIRCR = reg_value; } /** \brief Get Priority Grouping The function reads the priority grouping field from the NVIC Interrupt Controller. \return Priority grouping field (SCB->AIRCR [10:8] PRIGROUP field). */ __STATIC_INLINE uint32_t NVIC_GetPriorityGrouping(void) { return ((uint32_t)((SCB->AIRCR & SCB_AIRCR_PRIGROUP_Msk) >> SCB_AIRCR_PRIGROUP_Pos)); } /** \brief Enable External Interrupt The function enables a device-specific interrupt in the NVIC interrupt controller. \param [in] IRQn External interrupt number. Value cannot be negative. */ __STATIC_INLINE void NVIC_EnableIRQ(IRQn_Type IRQn) { NVIC->ISER[(((uint32_t)(int32_t)IRQn) >> 5UL)] = (uint32_t)(1UL << (((uint32_t)(int32_t)IRQn) & 0x1FUL)); } /** \brief Disable External Interrupt The function disables a device-specific interrupt in the NVIC interrupt controller. \param [in] IRQn External interrupt number. Value cannot be negative. */ __STATIC_INLINE void NVIC_DisableIRQ(IRQn_Type IRQn) { NVIC->ICER[(((uint32_t)(int32_t)IRQn) >> 5UL)] = (uint32_t)(1UL << (((uint32_t)(int32_t)IRQn) & 0x1FUL)); } /** \brief Get Pending Interrupt The function reads the pending register in the NVIC and returns the pending bit for the specified interrupt. \param [in] IRQn Interrupt number. \return 0 Interrupt status is not pending. \return 1 Interrupt status is pending. */ __STATIC_INLINE uint32_t NVIC_GetPendingIRQ(IRQn_Type IRQn) { return((uint32_t)(((NVIC->ISPR[(((uint32_t)(int32_t)IRQn) >> 5UL)] & (1UL << (((uint32_t)(int32_t)IRQn) & 0x1FUL))) != 0UL) ? 1UL : 0UL)); } /** \brief Set Pending Interrupt The function sets the pending bit of an external interrupt. \param [in] IRQn Interrupt number. Value cannot be negative. */ __STATIC_INLINE void NVIC_SetPendingIRQ(IRQn_Type IRQn) { NVIC->ISPR[(((uint32_t)(int32_t)IRQn) >> 5UL)] = (uint32_t)(1UL << (((uint32_t)(int32_t)IRQn) & 0x1FUL)); } /** \brief Clear Pending Interrupt The function clears the pending bit of an external interrupt. \param [in] IRQn External interrupt number. Value cannot be negative. */ __STATIC_INLINE void NVIC_ClearPendingIRQ(IRQn_Type IRQn) { NVIC->ICPR[(((uint32_t)(int32_t)IRQn) >> 5UL)] = (uint32_t)(1UL << (((uint32_t)(int32_t)IRQn) & 0x1FUL)); } /** \brief Get Active Interrupt The function reads the active register in NVIC and returns the active bit. \param [in] IRQn Interrupt number. \return 0 Interrupt status is not active. \return 1 Interrupt status is active. */ __STATIC_INLINE uint32_t NVIC_GetActive(IRQn_Type IRQn) { return((uint32_t)(((NVIC->IABR[(((uint32_t)(int32_t)IRQn) >> 5UL)] & (1UL << (((uint32_t)(int32_t)IRQn) & 0x1FUL))) != 0UL) ? 1UL : 0UL)); } /** \brief Set Interrupt Priority The function sets the priority of an interrupt. \note The priority cannot be set for every core interrupt. \param [in] IRQn Interrupt number. \param [in] priority Priority to set. */ __STATIC_INLINE void NVIC_SetPriority(IRQn_Type IRQn, uint32_t priority) { if((int32_t)IRQn < 0) { SCB->SHPR[(((uint32_t)(int32_t)IRQn) & 0xFUL)-4UL] = (uint8_t)((priority << (8 - __NVIC_PRIO_BITS)) & (uint32_t)0xFFUL); } else { NVIC->IP[((uint32_t)(int32_t)IRQn)] = (uint8_t)((priority << (8 - __NVIC_PRIO_BITS)) & (uint32_t)0xFFUL); } } /** \brief Get Interrupt Priority The function reads the priority of an interrupt. The interrupt number can be positive to specify an external (device specific) interrupt, or negative to specify an internal (core) interrupt. \param [in] IRQn Interrupt number. \return Interrupt Priority. Value is aligned automatically to the implemented priority bits of the microcontroller. */ __STATIC_INLINE uint32_t NVIC_GetPriority(IRQn_Type IRQn) { if((int32_t)IRQn < 0) { return(((uint32_t)SCB->SHPR[(((uint32_t)(int32_t)IRQn) & 0xFUL)-4UL] >> (8 - __NVIC_PRIO_BITS))); } else { return(((uint32_t)NVIC->IP[((uint32_t)(int32_t)IRQn)] >> (8 - __NVIC_PRIO_BITS))); } } /** \brief Encode Priority The function encodes the priority for an interrupt with the given priority group, preemptive priority value, and subpriority value. In case of a conflict between priority grouping and available priority bits (__NVIC_PRIO_BITS), the smallest possible priority group is set. \param [in] PriorityGroup Used priority group. \param [in] PreemptPriority Preemptive priority value (starting from 0). \param [in] SubPriority Subpriority value (starting from 0). \return Encoded priority. Value can be used in the function \ref NVIC_SetPriority(). */ __STATIC_INLINE uint32_t NVIC_EncodePriority (uint32_t PriorityGroup, uint32_t PreemptPriority, uint32_t SubPriority) { uint32_t PriorityGroupTmp = (PriorityGroup & (uint32_t)0x07UL); /* only values 0..7 are used */ uint32_t PreemptPriorityBits; uint32_t SubPriorityBits; PreemptPriorityBits = ((7UL - PriorityGroupTmp) > (uint32_t)(__NVIC_PRIO_BITS)) ? (uint32_t)(__NVIC_PRIO_BITS) : (uint32_t)(7UL - PriorityGroupTmp); SubPriorityBits = ((PriorityGroupTmp + (uint32_t)(__NVIC_PRIO_BITS)) < (uint32_t)7UL) ? (uint32_t)0UL : (uint32_t)((PriorityGroupTmp - 7UL) + (uint32_t)(__NVIC_PRIO_BITS)); return ( ((PreemptPriority & (uint32_t)((1UL << (PreemptPriorityBits)) - 1UL)) << SubPriorityBits) | ((SubPriority & (uint32_t)((1UL << (SubPriorityBits )) - 1UL))) ); } /** \brief Decode Priority The function decodes an interrupt priority value with a given priority group to preemptive priority value and subpriority value. In case of a conflict between priority grouping and available priority bits (__NVIC_PRIO_BITS) the smallest possible priority group is set. \param [in] Priority Priority value, which can be retrieved with the function \ref NVIC_GetPriority(). \param [in] PriorityGroup Used priority group. \param [out] pPreemptPriority Preemptive priority value (starting from 0). \param [out] pSubPriority Subpriority value (starting from 0). */ __STATIC_INLINE void NVIC_DecodePriority (uint32_t Priority, uint32_t PriorityGroup, uint32_t* pPreemptPriority, uint32_t* pSubPriority) { uint32_t PriorityGroupTmp = (PriorityGroup & (uint32_t)0x07UL); /* only values 0..7 are used */ uint32_t PreemptPriorityBits; uint32_t SubPriorityBits; PreemptPriorityBits = ((7UL - PriorityGroupTmp) > (uint32_t)(__NVIC_PRIO_BITS)) ? (uint32_t)(__NVIC_PRIO_BITS) : (uint32_t)(7UL - PriorityGroupTmp); SubPriorityBits = ((PriorityGroupTmp + (uint32_t)(__NVIC_PRIO_BITS)) < (uint32_t)7UL) ? (uint32_t)0UL : (uint32_t)((PriorityGroupTmp - 7UL) + (uint32_t)(__NVIC_PRIO_BITS)); *pPreemptPriority = (Priority >> SubPriorityBits) & (uint32_t)((1UL << (PreemptPriorityBits)) - 1UL); *pSubPriority = (Priority ) & (uint32_t)((1UL << (SubPriorityBits )) - 1UL); } /** \brief System Reset The function initiates a system reset request to reset the MCU. */ __STATIC_INLINE void NVIC_SystemReset(void) { __DSB(); /* Ensure all outstanding memory accesses included buffered write are completed before reset */ SCB->AIRCR = (uint32_t)((0x5FAUL << SCB_AIRCR_VECTKEY_Pos) | (SCB->AIRCR & SCB_AIRCR_PRIGROUP_Msk) | SCB_AIRCR_SYSRESETREQ_Msk ); /* Keep priority group unchanged */ __DSB(); /* Ensure completion of memory access */ while(1) { __NOP(); } /* wait until reset */ } /*@} end of CMSIS_Core_NVICFunctions */ /* ########################## FPU functions #################################### */ /** \ingroup CMSIS_Core_FunctionInterface \defgroup CMSIS_Core_FpuFunctions FPU Functions \brief Function that provides FPU type. @{ */ /** \fn uint32_t SCB_GetFPUType(void) \brief get FPU type \returns - \b 0: No FPU - \b 1: Single precision FPU - \b 2: Double + Single precision FPU */ __STATIC_INLINE uint32_t SCB_GetFPUType(void) { uint32_t mvfr0; mvfr0 = SCB->MVFR0; if ((mvfr0 & 0x00000FF0UL) == 0x220UL) { return 2UL; // Double + Single precision FPU } else if ((mvfr0 & 0x00000FF0UL) == 0x020UL) { return 1UL; // Single precision FPU } else { return 0UL; // No FPU } } /*@} end of CMSIS_Core_FpuFunctions */ /* ########################## Cache functions #################################### */ /** \ingroup CMSIS_Core_FunctionInterface \defgroup CMSIS_Core_CacheFunctions Cache Functions \brief Functions that configure Instruction and Data cache. @{ */ /* Cache Size ID Register Macros */ #define CCSIDR_WAYS(x) (((x) & SCB_CCSIDR_ASSOCIATIVITY_Msk) >> SCB_CCSIDR_ASSOCIATIVITY_Pos) #define CCSIDR_SETS(x) (((x) & SCB_CCSIDR_NUMSETS_Msk ) >> SCB_CCSIDR_NUMSETS_Pos ) #define CCSIDR_LSSHIFT(x) (((x) & SCB_CCSIDR_LINESIZE_Msk ) /*>> SCB_CCSIDR_LINESIZE_Pos*/ ) /** \brief Enable I-Cache The function turns on I-Cache */ __STATIC_INLINE void SCB_EnableICache (void) { #if (__ICACHE_PRESENT == 1) __DSB(); __ISB(); SCB->ICIALLU = 0UL; // invalidate I-Cache SCB->CCR |= (uint32_t)SCB_CCR_IC_Msk; // enable I-Cache __DSB(); __ISB(); #endif } /** \brief Disable I-Cache The function turns off I-Cache */ __STATIC_INLINE void SCB_DisableICache (void) { #if (__ICACHE_PRESENT == 1) __DSB(); __ISB(); SCB->CCR &= ~(uint32_t)SCB_CCR_IC_Msk; // disable I-Cache SCB->ICIALLU = 0UL; // invalidate I-Cache __DSB(); __ISB(); #endif } /** \brief Invalidate I-Cache The function invalidates I-Cache */ __STATIC_INLINE void SCB_InvalidateICache (void) { #if (__ICACHE_PRESENT == 1) __DSB(); __ISB(); SCB->ICIALLU = 0UL; __DSB(); __ISB(); #endif } /** \brief Enable D-Cache The function turns on D-Cache */ __STATIC_INLINE void SCB_EnableDCache (void) { #if (__DCACHE_PRESENT == 1) uint32_t ccsidr, sshift, wshift, sw; uint32_t sets, ways; SCB->CSSELR = (0UL << 1) | 0UL; // Level 1 data cache ccsidr = SCB->CCSIDR; sets = (uint32_t)(CCSIDR_SETS(ccsidr)); sshift = (uint32_t)(CCSIDR_LSSHIFT(ccsidr) + 4UL); ways = (uint32_t)(CCSIDR_WAYS(ccsidr)); wshift = (uint32_t)((uint32_t)__CLZ(ways) & 0x1FUL); __DSB(); do { // invalidate D-Cache uint32_t tmpways = ways; do { sw = ((tmpways << wshift) | (sets << sshift)); SCB->DCISW = sw; } while(tmpways--); } while(sets--); __DSB(); SCB->CCR |= (uint32_t)SCB_CCR_DC_Msk; // enable D-Cache __DSB(); __ISB(); #endif } /** \brief Disable D-Cache The function turns off D-Cache */ __STATIC_INLINE void SCB_DisableDCache (void) { #if (__DCACHE_PRESENT == 1) uint32_t ccsidr, sshift, wshift, sw; uint32_t sets, ways; SCB->CSSELR = (0UL << 1) | 0UL; // Level 1 data cache ccsidr = SCB->CCSIDR; sets = (uint32_t)(CCSIDR_SETS(ccsidr)); sshift = (uint32_t)(CCSIDR_LSSHIFT(ccsidr) + 4UL); ways = (uint32_t)(CCSIDR_WAYS(ccsidr)); wshift = (uint32_t)((uint32_t)__CLZ(ways) & 0x1FUL); __DSB(); SCB->CCR &= ~(uint32_t)SCB_CCR_DC_Msk; // disable D-Cache do { // clean & invalidate D-Cache uint32_t tmpways = ways; do { sw = ((tmpways << wshift) | (sets << sshift)); SCB->DCCISW = sw; } while(tmpways--); } while(sets--); __DSB(); __ISB(); #endif } /** \brief Invalidate D-Cache The function invalidates D-Cache */ __STATIC_INLINE void SCB_InvalidateDCache (void) { #if (__DCACHE_PRESENT == 1) uint32_t ccsidr, sshift, wshift, sw; uint32_t sets, ways; SCB->CSSELR = (0UL << 1) | 0UL; // Level 1 data cache ccsidr = SCB->CCSIDR; sets = (uint32_t)(CCSIDR_SETS(ccsidr)); sshift = (uint32_t)(CCSIDR_LSSHIFT(ccsidr) + 4UL); ways = (uint32_t)(CCSIDR_WAYS(ccsidr)); wshift = (uint32_t)((uint32_t)__CLZ(ways) & 0x1FUL); __DSB(); do { // invalidate D-Cache uint32_t tmpways = ways; do { sw = ((tmpways << wshift) | (sets << sshift)); SCB->DCISW = sw; } while(tmpways--); } while(sets--); __DSB(); __ISB(); #endif } /** \brief Clean D-Cache The function cleans D-Cache */ __STATIC_INLINE void SCB_CleanDCache (void) { #if (__DCACHE_PRESENT == 1) uint32_t ccsidr, sshift, wshift, sw; uint32_t sets, ways; SCB->CSSELR = (0UL << 1) | 0UL; // Level 1 data cache ccsidr = SCB->CCSIDR; sets = (uint32_t)(CCSIDR_SETS(ccsidr)); sshift = (uint32_t)(CCSIDR_LSSHIFT(ccsidr) + 4UL); ways = (uint32_t)(CCSIDR_WAYS(ccsidr)); wshift = (uint32_t)((uint32_t)__CLZ(ways) & 0x1FUL); __DSB(); do { // clean D-Cache uint32_t tmpways = ways; do { sw = ((tmpways << wshift) | (sets << sshift)); SCB->DCCSW = sw; } while(tmpways--); } while(sets--); __DSB(); __ISB(); #endif } /** \brief Clean & Invalidate D-Cache The function cleans and Invalidates D-Cache */ __STATIC_INLINE void SCB_CleanInvalidateDCache (void) { #if (__DCACHE_PRESENT == 1) uint32_t ccsidr, sshift, wshift, sw; uint32_t sets, ways; SCB->CSSELR = (0UL << 1) | 0UL; // Level 1 data cache ccsidr = SCB->CCSIDR; sets = (uint32_t)(CCSIDR_SETS(ccsidr)); sshift = (uint32_t)(CCSIDR_LSSHIFT(ccsidr) + 4UL); ways = (uint32_t)(CCSIDR_WAYS(ccsidr)); wshift = (uint32_t)((uint32_t)__CLZ(ways) & 0x1FUL); __DSB(); do { // clean & invalidate D-Cache uint32_t tmpways = ways; do { sw = ((tmpways << wshift) | (sets << sshift)); SCB->DCCISW = sw; } while(tmpways--); } while(sets--); __DSB(); __ISB(); #endif } /** \fn void SCB_InvalidateDCache_by_Addr(volatile uint32_t *addr, int32_t dsize) \brief D-Cache Invalidate by address \param[in] addr address (aligned to 32-byte boundary) \param[in] dsize size of memory block (in number of bytes) */ __STATIC_INLINE void SCB_InvalidateDCache_by_Addr (uint32_t *addr, int32_t dsize) { #if (__DCACHE_PRESENT == 1) int32_t op_size = dsize; uint32_t op_addr = (uint32_t)addr; uint32_t linesize = 32UL; // in Cortex-M7 size of cache line is fixed to 8 words (32 bytes) __DSB(); while (op_size > 0) { SCB->DCIMVAC = op_addr; op_addr += linesize; op_size -= (int32_t)linesize; } __DSB(); __ISB(); #endif } /** \fn void SCB_CleanDCache_by_Addr(volatile uint32_t *addr, int32_t dsize) \brief D-Cache Clean by address \param[in] addr address (aligned to 32-byte boundary) \param[in] dsize size of memory block (in number of bytes) */ __STATIC_INLINE void SCB_CleanDCache_by_Addr (uint32_t *addr, int32_t dsize) { #if (__DCACHE_PRESENT == 1) int32_t op_size = dsize; uint32_t op_addr = (uint32_t) addr; uint32_t linesize = 32UL; // in Cortex-M7 size of cache line is fixed to 8 words (32 bytes) __DSB(); while (op_size > 0) { SCB->DCCMVAC = op_addr; op_addr += linesize; op_size -= (int32_t)linesize; } __DSB(); __ISB(); #endif } /** \fn void SCB_CleanInvalidateDCache_by_Addr(volatile uint32_t *addr, int32_t dsize) \brief D-Cache Clean and Invalidate by address \param[in] addr address (aligned to 32-byte boundary) \param[in] dsize size of memory block (in number of bytes) */ __STATIC_INLINE void SCB_CleanInvalidateDCache_by_Addr (uint32_t *addr, int32_t dsize) { #if (__DCACHE_PRESENT == 1) int32_t op_size = dsize; uint32_t op_addr = (uint32_t) addr; uint32_t linesize = 32UL; // in Cortex-M7 size of cache line is fixed to 8 words (32 bytes) __DSB(); while (op_size > 0) { SCB->DCCIMVAC = op_addr; op_addr += linesize; op_size -= (int32_t)linesize; } __DSB(); __ISB(); #endif } /*@} end of CMSIS_Core_CacheFunctions */ /* ################################## SysTick function ############################################ */ /** \ingroup CMSIS_Core_FunctionInterface \defgroup CMSIS_Core_SysTickFunctions SysTick Functions \brief Functions that configure the System. @{ */ #if (__Vendor_SysTickConfig == 0) /** \brief System Tick Configuration The function initializes the System Timer and its interrupt, and starts the System Tick Timer. Counter is in free running mode to generate periodic interrupts. \param [in] ticks Number of ticks between two interrupts. \return 0 Function succeeded. \return 1 Function failed. \note When the variable __Vendor_SysTickConfig is set to 1, then the function SysTick_Config is not included. In this case, the file device.h must contain a vendor-specific implementation of this function. */ __STATIC_INLINE uint32_t SysTick_Config(uint32_t ticks) { if ((ticks - 1UL) > SysTick_LOAD_RELOAD_Msk) { return (1UL); } /* Reload value impossible */ SysTick->LOAD = (uint32_t)(ticks - 1UL); /* set reload register */ NVIC_SetPriority (SysTick_IRQn, (1UL << __NVIC_PRIO_BITS) - 1UL); /* set Priority for Systick Interrupt */ SysTick->VAL = 0UL; /* Load the SysTick Counter Value */ SysTick->CTRL = SysTick_CTRL_CLKSOURCE_Msk | SysTick_CTRL_TICKINT_Msk | SysTick_CTRL_ENABLE_Msk; /* Enable SysTick IRQ and SysTick Timer */ return (0UL); /* Function successful */ } #endif /*@} end of CMSIS_Core_SysTickFunctions */ /* ##################################### Debug In/Output function ########################################### */ /** \ingroup CMSIS_Core_FunctionInterface \defgroup CMSIS_core_DebugFunctions ITM Functions \brief Functions that access the ITM debug interface. @{ */ extern volatile int32_t ITM_RxBuffer; /*!< External variable to receive characters. */ #define ITM_RXBUFFER_EMPTY 0x5AA55AA5 /*!< Value identifying \ref ITM_RxBuffer is ready for next character. */ /** \brief ITM Send Character The function transmits a character via the ITM channel 0, and \li Just returns when no debugger is connected that has booked the output. \li Is blocking when a debugger is connected, but the previous character sent has not been transmitted. \param [in] ch Character to transmit. \returns Character to transmit. */ __STATIC_INLINE uint32_t ITM_SendChar (uint32_t ch) { if (((ITM->TCR & ITM_TCR_ITMENA_Msk) != 0UL) && /* ITM enabled */ ((ITM->TER & 1UL ) != 0UL) ) /* ITM Port #0 enabled */ { while (ITM->PORT[0].u32 == 0UL) { __NOP(); } ITM->PORT[0].u8 = (uint8_t)ch; } return (ch); } /** \brief ITM Receive Character The function inputs a character via the external variable \ref ITM_RxBuffer. \return Received character. \return -1 No character pending. */ __STATIC_INLINE int32_t ITM_ReceiveChar (void) { int32_t ch = -1; /* no character available */ if (ITM_RxBuffer != ITM_RXBUFFER_EMPTY) { ch = ITM_RxBuffer; ITM_RxBuffer = ITM_RXBUFFER_EMPTY; /* ready for next character */ } return (ch); } /** \brief ITM Check Character The function checks whether a character is pending for reading in the variable \ref ITM_RxBuffer. \return 0 No character available. \return 1 Character available. */ __STATIC_INLINE int32_t ITM_CheckChar (void) { if (ITM_RxBuffer == ITM_RXBUFFER_EMPTY) { return (0); /* no character available */ } else { return (1); /* character available */ } } /*@} end of CMSIS_core_DebugFunctions */ #ifdef __cplusplus } #endif #endif /* __CORE_CM7_H_DEPENDANT */ #endif /* __CMSIS_GENERIC */ ================================================ FILE: Zelig/mbed/TARGET_NUCLEO_F091RC/core_cmFunc.h ================================================ /**************************************************************************//** * @file core_cmFunc.h * @brief CMSIS Cortex-M Core Function Access Header File * @version V4.10 * @date 18. March 2015 * * @note * ******************************************************************************/ /* Copyright (c) 2009 - 2015 ARM LIMITED All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: - Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. - Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. - Neither the name of ARM 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 COPYRIGHT HOLDERS AND 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. ---------------------------------------------------------------------------*/ #ifndef __CORE_CMFUNC_H #define __CORE_CMFUNC_H /* ########################### Core Function Access ########################### */ /** \ingroup CMSIS_Core_FunctionInterface \defgroup CMSIS_Core_RegAccFunctions CMSIS Core Register Access Functions @{ */ #if defined ( __CC_ARM ) /*------------------RealView Compiler -----------------*/ /* ARM armcc specific functions */ #if (__ARMCC_VERSION < 400677) #error "Please use ARM Compiler Toolchain V4.0.677 or later!" #endif /* intrinsic void __enable_irq(); */ /* intrinsic void __disable_irq(); */ /** \brief Get Control Register This function returns the content of the Control Register. \return Control Register value */ __STATIC_INLINE uint32_t __get_CONTROL(void) { register uint32_t __regControl __ASM("control"); return(__regControl); } /** \brief Set Control Register This function writes the given value to the Control Register. \param [in] control Control Register value to set */ __STATIC_INLINE void __set_CONTROL(uint32_t control) { register uint32_t __regControl __ASM("control"); __regControl = control; } /** \brief Get IPSR Register This function returns the content of the IPSR Register. \return IPSR Register value */ __STATIC_INLINE uint32_t __get_IPSR(void) { register uint32_t __regIPSR __ASM("ipsr"); return(__regIPSR); } /** \brief Get APSR Register This function returns the content of the APSR Register. \return APSR Register value */ __STATIC_INLINE uint32_t __get_APSR(void) { register uint32_t __regAPSR __ASM("apsr"); return(__regAPSR); } /** \brief Get xPSR Register This function returns the content of the xPSR Register. \return xPSR Register value */ __STATIC_INLINE uint32_t __get_xPSR(void) { register uint32_t __regXPSR __ASM("xpsr"); return(__regXPSR); } /** \brief Get Process Stack Pointer This function returns the current value of the Process Stack Pointer (PSP). \return PSP Register value */ __STATIC_INLINE uint32_t __get_PSP(void) { register uint32_t __regProcessStackPointer __ASM("psp"); return(__regProcessStackPointer); } /** \brief Set Process Stack Pointer This function assigns the given value to the Process Stack Pointer (PSP). \param [in] topOfProcStack Process Stack Pointer value to set */ __STATIC_INLINE void __set_PSP(uint32_t topOfProcStack) { register uint32_t __regProcessStackPointer __ASM("psp"); __regProcessStackPointer = topOfProcStack; } /** \brief Get Main Stack Pointer This function returns the current value of the Main Stack Pointer (MSP). \return MSP Register value */ __STATIC_INLINE uint32_t __get_MSP(void) { register uint32_t __regMainStackPointer __ASM("msp"); return(__regMainStackPointer); } /** \brief Set Main Stack Pointer This function assigns the given value to the Main Stack Pointer (MSP). \param [in] topOfMainStack Main Stack Pointer value to set */ __STATIC_INLINE void __set_MSP(uint32_t topOfMainStack) { register uint32_t __regMainStackPointer __ASM("msp"); __regMainStackPointer = topOfMainStack; } /** \brief Get Priority Mask This function returns the current state of the priority mask bit from the Priority Mask Register. \return Priority Mask value */ __STATIC_INLINE uint32_t __get_PRIMASK(void) { register uint32_t __regPriMask __ASM("primask"); return(__regPriMask); } /** \brief Set Priority Mask This function assigns the given value to the Priority Mask Register. \param [in] priMask Priority Mask */ __STATIC_INLINE void __set_PRIMASK(uint32_t priMask) { register uint32_t __regPriMask __ASM("primask"); __regPriMask = (priMask); } #if (__CORTEX_M >= 0x03) || (__CORTEX_SC >= 300) /** \brief Enable FIQ This function enables FIQ interrupts by clearing the F-bit in the CPSR. Can only be executed in Privileged modes. */ #define __enable_fault_irq __enable_fiq /** \brief Disable FIQ This function disables FIQ interrupts by setting the F-bit in the CPSR. Can only be executed in Privileged modes. */ #define __disable_fault_irq __disable_fiq /** \brief Get Base Priority This function returns the current value of the Base Priority register. \return Base Priority register value */ __STATIC_INLINE uint32_t __get_BASEPRI(void) { register uint32_t __regBasePri __ASM("basepri"); return(__regBasePri); } /** \brief Set Base Priority This function assigns the given value to the Base Priority register. \param [in] basePri Base Priority value to set */ __STATIC_INLINE void __set_BASEPRI(uint32_t basePri) { register uint32_t __regBasePri __ASM("basepri"); __regBasePri = (basePri & 0xff); } /** \brief Set Base Priority with condition This function assigns the given value to the Base Priority register only if BASEPRI masking is disabled, or the new value increases the BASEPRI priority level. \param [in] basePri Base Priority value to set */ __STATIC_INLINE void __set_BASEPRI_MAX(uint32_t basePri) { register uint32_t __regBasePriMax __ASM("basepri_max"); __regBasePriMax = (basePri & 0xff); } /** \brief Get Fault Mask This function returns the current value of the Fault Mask register. \return Fault Mask register value */ __STATIC_INLINE uint32_t __get_FAULTMASK(void) { register uint32_t __regFaultMask __ASM("faultmask"); return(__regFaultMask); } /** \brief Set Fault Mask This function assigns the given value to the Fault Mask register. \param [in] faultMask Fault Mask value to set */ __STATIC_INLINE void __set_FAULTMASK(uint32_t faultMask) { register uint32_t __regFaultMask __ASM("faultmask"); __regFaultMask = (faultMask & (uint32_t)1); } #endif /* (__CORTEX_M >= 0x03) || (__CORTEX_SC >= 300) */ #if (__CORTEX_M == 0x04) || (__CORTEX_M == 0x07) /** \brief Get FPSCR This function returns the current value of the Floating Point Status/Control register. \return Floating Point Status/Control register value */ __STATIC_INLINE uint32_t __get_FPSCR(void) { #if (__FPU_PRESENT == 1) && (__FPU_USED == 1) register uint32_t __regfpscr __ASM("fpscr"); return(__regfpscr); #else return(0); #endif } /** \brief Set FPSCR This function assigns the given value to the Floating Point Status/Control register. \param [in] fpscr Floating Point Status/Control value to set */ __STATIC_INLINE void __set_FPSCR(uint32_t fpscr) { #if (__FPU_PRESENT == 1) && (__FPU_USED == 1) register uint32_t __regfpscr __ASM("fpscr"); __regfpscr = (fpscr); #endif } #endif /* (__CORTEX_M == 0x04) || (__CORTEX_M == 0x07) */ #elif defined ( __GNUC__ ) /*------------------ GNU Compiler ---------------------*/ /* GNU gcc specific functions */ /** \brief Enable IRQ Interrupts This function enables IRQ interrupts by clearing the I-bit in the CPSR. Can only be executed in Privileged modes. */ __attribute__( ( always_inline ) ) __STATIC_INLINE void __enable_irq(void) { __ASM volatile ("cpsie i" : : : "memory"); } /** \brief Disable IRQ Interrupts This function disables IRQ interrupts by setting the I-bit in the CPSR. Can only be executed in Privileged modes. */ __attribute__( ( always_inline ) ) __STATIC_INLINE void __disable_irq(void) { __ASM volatile ("cpsid i" : : : "memory"); } /** \brief Get Control Register This function returns the content of the Control Register. \return Control Register value */ __attribute__( ( always_inline ) ) __STATIC_INLINE uint32_t __get_CONTROL(void) { uint32_t result; __ASM volatile ("MRS %0, control" : "=r" (result) ); return(result); } /** \brief Set Control Register This function writes the given value to the Control Register. \param [in] control Control Register value to set */ __attribute__( ( always_inline ) ) __STATIC_INLINE void __set_CONTROL(uint32_t control) { __ASM volatile ("MSR control, %0" : : "r" (control) : "memory"); } /** \brief Get IPSR Register This function returns the content of the IPSR Register. \return IPSR Register value */ __attribute__( ( always_inline ) ) __STATIC_INLINE uint32_t __get_IPSR(void) { uint32_t result; __ASM volatile ("MRS %0, ipsr" : "=r" (result) ); return(result); } /** \brief Get APSR Register This function returns the content of the APSR Register. \return APSR Register value */ __attribute__( ( always_inline ) ) __STATIC_INLINE uint32_t __get_APSR(void) { uint32_t result; __ASM volatile ("MRS %0, apsr" : "=r" (result) ); return(result); } /** \brief Get xPSR Register This function returns the content of the xPSR Register. \return xPSR Register value */ __attribute__( ( always_inline ) ) __STATIC_INLINE uint32_t __get_xPSR(void) { uint32_t result; __ASM volatile ("MRS %0, xpsr" : "=r" (result) ); return(result); } /** \brief Get Process Stack Pointer This function returns the current value of the Process Stack Pointer (PSP). \return PSP Register value */ __attribute__( ( always_inline ) ) __STATIC_INLINE uint32_t __get_PSP(void) { register uint32_t result; __ASM volatile ("MRS %0, psp\n" : "=r" (result) ); return(result); } /** \brief Set Process Stack Pointer This function assigns the given value to the Process Stack Pointer (PSP). \param [in] topOfProcStack Process Stack Pointer value to set */ __attribute__( ( always_inline ) ) __STATIC_INLINE void __set_PSP(uint32_t topOfProcStack) { __ASM volatile ("MSR psp, %0\n" : : "r" (topOfProcStack) : "sp"); } /** \brief Get Main Stack Pointer This function returns the current value of the Main Stack Pointer (MSP). \return MSP Register value */ __attribute__( ( always_inline ) ) __STATIC_INLINE uint32_t __get_MSP(void) { register uint32_t result; __ASM volatile ("MRS %0, msp\n" : "=r" (result) ); return(result); } /** \brief Set Main Stack Pointer This function assigns the given value to the Main Stack Pointer (MSP). \param [in] topOfMainStack Main Stack Pointer value to set */ __attribute__( ( always_inline ) ) __STATIC_INLINE void __set_MSP(uint32_t topOfMainStack) { __ASM volatile ("MSR msp, %0\n" : : "r" (topOfMainStack) : "sp"); } /** \brief Get Priority Mask This function returns the current state of the priority mask bit from the Priority Mask Register. \return Priority Mask value */ __attribute__( ( always_inline ) ) __STATIC_INLINE uint32_t __get_PRIMASK(void) { uint32_t result; __ASM volatile ("MRS %0, primask" : "=r" (result) ); return(result); } /** \brief Set Priority Mask This function assigns the given value to the Priority Mask Register. \param [in] priMask Priority Mask */ __attribute__( ( always_inline ) ) __STATIC_INLINE void __set_PRIMASK(uint32_t priMask) { __ASM volatile ("MSR primask, %0" : : "r" (priMask) : "memory"); } #if (__CORTEX_M >= 0x03) /** \brief Enable FIQ This function enables FIQ interrupts by clearing the F-bit in the CPSR. Can only be executed in Privileged modes. */ __attribute__( ( always_inline ) ) __STATIC_INLINE void __enable_fault_irq(void) { __ASM volatile ("cpsie f" : : : "memory"); } /** \brief Disable FIQ This function disables FIQ interrupts by setting the F-bit in the CPSR. Can only be executed in Privileged modes. */ __attribute__( ( always_inline ) ) __STATIC_INLINE void __disable_fault_irq(void) { __ASM volatile ("cpsid f" : : : "memory"); } /** \brief Get Base Priority This function returns the current value of the Base Priority register. \return Base Priority register value */ __attribute__( ( always_inline ) ) __STATIC_INLINE uint32_t __get_BASEPRI(void) { uint32_t result; __ASM volatile ("MRS %0, basepri" : "=r" (result) ); return(result); } /** \brief Set Base Priority This function assigns the given value to the Base Priority register. \param [in] basePri Base Priority value to set */ __attribute__( ( always_inline ) ) __STATIC_INLINE void __set_BASEPRI(uint32_t value) { __ASM volatile ("MSR basepri, %0" : : "r" (value) : "memory"); } /** \brief Set Base Priority with condition This function assigns the given value to the Base Priority register only if BASEPRI masking is disabled, or the new value increases the BASEPRI priority level. \param [in] basePri Base Priority value to set */ __attribute__( ( always_inline ) ) __STATIC_INLINE void __set_BASEPRI_MAX(uint32_t value) { __ASM volatile ("MSR basepri_max, %0" : : "r" (value) : "memory"); } /** \brief Get Fault Mask This function returns the current value of the Fault Mask register. \return Fault Mask register value */ __attribute__( ( always_inline ) ) __STATIC_INLINE uint32_t __get_FAULTMASK(void) { uint32_t result; __ASM volatile ("MRS %0, faultmask" : "=r" (result) ); return(result); } /** \brief Set Fault Mask This function assigns the given value to the Fault Mask register. \param [in] faultMask Fault Mask value to set */ __attribute__( ( always_inline ) ) __STATIC_INLINE void __set_FAULTMASK(uint32_t faultMask) { __ASM volatile ("MSR faultmask, %0" : : "r" (faultMask) : "memory"); } #endif /* (__CORTEX_M >= 0x03) */ #if (__CORTEX_M == 0x04) || (__CORTEX_M == 0x07) /** \brief Get FPSCR This function returns the current value of the Floating Point Status/Control register. \return Floating Point Status/Control register value */ __attribute__( ( always_inline ) ) __STATIC_INLINE uint32_t __get_FPSCR(void) { #if (__FPU_PRESENT == 1) && (__FPU_USED == 1) uint32_t result; /* Empty asm statement works as a scheduling barrier */ __ASM volatile (""); __ASM volatile ("VMRS %0, fpscr" : "=r" (result) ); __ASM volatile (""); return(result); #else return(0); #endif } /** \brief Set FPSCR This function assigns the given value to the Floating Point Status/Control register. \param [in] fpscr Floating Point Status/Control value to set */ __attribute__( ( always_inline ) ) __STATIC_INLINE void __set_FPSCR(uint32_t fpscr) { #if (__FPU_PRESENT == 1) && (__FPU_USED == 1) /* Empty asm statement works as a scheduling barrier */ __ASM volatile (""); __ASM volatile ("VMSR fpscr, %0" : : "r" (fpscr) : "vfpcc"); __ASM volatile (""); #endif } #endif /* (__CORTEX_M == 0x04) || (__CORTEX_M == 0x07) */ #elif defined ( __ICCARM__ ) /*------------------ ICC Compiler -------------------*/ /* IAR iccarm specific functions */ #include #elif defined ( __TMS470__ ) /*---------------- TI CCS Compiler ------------------*/ /* TI CCS specific functions */ #include #elif defined ( __TASKING__ ) /*------------------ TASKING Compiler --------------*/ /* TASKING carm specific functions */ /* * The CMSIS functions have been implemented as intrinsics in the compiler. * Please use "carm -?i" to get an up to date list of all intrinsics, * Including the CMSIS ones. */ #elif defined ( __CSMC__ ) /*------------------ COSMIC Compiler -------------------*/ /* Cosmic specific functions */ #include #endif /*@} end of CMSIS_Core_RegAccFunctions */ #endif /* __CORE_CMFUNC_H */ ================================================ FILE: Zelig/mbed/TARGET_NUCLEO_F091RC/core_cmInstr.h ================================================ /**************************************************************************//** * @file core_cmInstr.h * @brief CMSIS Cortex-M Core Instruction Access Header File * @version V4.10 * @date 18. March 2015 * * @note * ******************************************************************************/ /* Copyright (c) 2009 - 2014 ARM LIMITED All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: - Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. - Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. - Neither the name of ARM 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 COPYRIGHT HOLDERS AND 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. ---------------------------------------------------------------------------*/ #ifndef __CORE_CMINSTR_H #define __CORE_CMINSTR_H /* ########################## Core Instruction Access ######################### */ /** \defgroup CMSIS_Core_InstructionInterface CMSIS Core Instruction Interface Access to dedicated instructions @{ */ #if defined ( __CC_ARM ) /*------------------RealView Compiler -----------------*/ /* ARM armcc specific functions */ #if (__ARMCC_VERSION < 400677) #error "Please use ARM Compiler Toolchain V4.0.677 or later!" #endif /** \brief No Operation No Operation does nothing. This instruction can be used for code alignment purposes. */ #define __NOP __nop /** \brief Wait For Interrupt Wait For Interrupt is a hint instruction that suspends execution until one of a number of events occurs. */ #define __WFI __wfi /** \brief Wait For Event Wait For Event is a hint instruction that permits the processor to enter a low-power state until one of a number of events occurs. */ #define __WFE __wfe /** \brief Send Event Send Event is a hint instruction. It causes an event to be signaled to the CPU. */ #define __SEV __sev /** \brief Instruction Synchronization Barrier Instruction Synchronization Barrier flushes the pipeline in the processor, so that all instructions following the ISB are fetched from cache or memory, after the instruction has been completed. */ #define __ISB() do {\ __schedule_barrier();\ __isb(0xF);\ __schedule_barrier();\ } while (0) /** \brief Data Synchronization Barrier This function acts as a special kind of Data Memory Barrier. It completes when all explicit memory accesses before this instruction complete. */ #define __DSB() do {\ __schedule_barrier();\ __dsb(0xF);\ __schedule_barrier();\ } while (0) /** \brief Data Memory Barrier This function ensures the apparent order of the explicit memory operations before and after the instruction, without ensuring their completion. */ #define __DMB() do {\ __schedule_barrier();\ __dmb(0xF);\ __schedule_barrier();\ } while (0) /** \brief Reverse byte order (32 bit) This function reverses the byte order in integer value. \param [in] value Value to reverse \return Reversed value */ #define __REV __rev /** \brief Reverse byte order (16 bit) This function reverses the byte order in two unsigned short values. \param [in] value Value to reverse \return Reversed value */ #ifndef __NO_EMBEDDED_ASM __attribute__((section(".rev16_text"))) __STATIC_INLINE __ASM uint32_t __REV16(uint32_t value) { rev16 r0, r0 bx lr } #endif /** \brief Reverse byte order in signed short value This function reverses the byte order in a signed short value with sign extension to integer. \param [in] value Value to reverse \return Reversed value */ #ifndef __NO_EMBEDDED_ASM __attribute__((section(".revsh_text"))) __STATIC_INLINE __ASM int32_t __REVSH(int32_t value) { revsh r0, r0 bx lr } #endif /** \brief Rotate Right in unsigned value (32 bit) This function Rotate Right (immediate) provides the value of the contents of a register rotated by a variable number of bits. \param [in] value Value to rotate \param [in] value Number of Bits to rotate \return Rotated value */ #define __ROR __ror /** \brief Breakpoint This function causes the processor to enter Debug state. Debug tools can use this to investigate system state when the instruction at a particular address is reached. \param [in] value is ignored by the processor. If required, a debugger can use it to store additional information about the breakpoint. */ #define __BKPT(value) __breakpoint(value) /** \brief Reverse bit order of value This function reverses the bit order of the given value. \param [in] value Value to reverse \return Reversed value */ #if (__CORTEX_M >= 0x03) || (__CORTEX_SC >= 300) #define __RBIT __rbit #else __attribute__((always_inline)) __STATIC_INLINE uint32_t __RBIT(uint32_t value) { uint32_t result; int32_t s = 4 /*sizeof(v)*/ * 8 - 1; // extra shift needed at end result = value; // r will be reversed bits of v; first get LSB of v for (value >>= 1; value; value >>= 1) { result <<= 1; result |= value & 1; s--; } result <<= s; // shift when v's highest bits are zero return(result); } #endif /** \brief Count leading zeros This function counts the number of leading zeros of a data value. \param [in] value Value to count the leading zeros \return number of leading zeros in value */ #define __CLZ __clz #if (__CORTEX_M >= 0x03) || (__CORTEX_SC >= 300) /** \brief LDR Exclusive (8 bit) This function executes a exclusive LDR instruction for 8 bit value. \param [in] ptr Pointer to data \return value of type uint8_t at (*ptr) */ #define __LDREXB(ptr) ((uint8_t ) __ldrex(ptr)) /** \brief LDR Exclusive (16 bit) This function executes a exclusive LDR instruction for 16 bit values. \param [in] ptr Pointer to data \return value of type uint16_t at (*ptr) */ #define __LDREXH(ptr) ((uint16_t) __ldrex(ptr)) /** \brief LDR Exclusive (32 bit) This function executes a exclusive LDR instruction for 32 bit values. \param [in] ptr Pointer to data \return value of type uint32_t at (*ptr) */ #define __LDREXW(ptr) ((uint32_t ) __ldrex(ptr)) /** \brief STR Exclusive (8 bit) This function executes a exclusive STR instruction for 8 bit values. \param [in] value Value to store \param [in] ptr Pointer to location \return 0 Function succeeded \return 1 Function failed */ #define __STREXB(value, ptr) __strex(value, ptr) /** \brief STR Exclusive (16 bit) This function executes a exclusive STR instruction for 16 bit values. \param [in] value Value to store \param [in] ptr Pointer to location \return 0 Function succeeded \return 1 Function failed */ #define __STREXH(value, ptr) __strex(value, ptr) /** \brief STR Exclusive (32 bit) This function executes a exclusive STR instruction for 32 bit values. \param [in] value Value to store \param [in] ptr Pointer to location \return 0 Function succeeded \return 1 Function failed */ #define __STREXW(value, ptr) __strex(value, ptr) /** \brief Remove the exclusive lock This function removes the exclusive lock which is created by LDREX. */ #define __CLREX __clrex /** \brief Signed Saturate This function saturates a signed value. \param [in] value Value to be saturated \param [in] sat Bit position to saturate to (1..32) \return Saturated value */ #define __SSAT __ssat /** \brief Unsigned Saturate This function saturates an unsigned value. \param [in] value Value to be saturated \param [in] sat Bit position to saturate to (0..31) \return Saturated value */ #define __USAT __usat /** \brief Rotate Right with Extend (32 bit) This function moves each bit of a bitstring right by one bit. The carry input is shifted in at the left end of the bitstring. \param [in] value Value to rotate \return Rotated value */ #ifndef __NO_EMBEDDED_ASM __attribute__((section(".rrx_text"))) __STATIC_INLINE __ASM uint32_t __RRX(uint32_t value) { rrx r0, r0 bx lr } #endif /** \brief LDRT Unprivileged (8 bit) This function executes a Unprivileged LDRT instruction for 8 bit value. \param [in] ptr Pointer to data \return value of type uint8_t at (*ptr) */ #define __LDRBT(ptr) ((uint8_t ) __ldrt(ptr)) /** \brief LDRT Unprivileged (16 bit) This function executes a Unprivileged LDRT instruction for 16 bit values. \param [in] ptr Pointer to data \return value of type uint16_t at (*ptr) */ #define __LDRHT(ptr) ((uint16_t) __ldrt(ptr)) /** \brief LDRT Unprivileged (32 bit) This function executes a Unprivileged LDRT instruction for 32 bit values. \param [in] ptr Pointer to data \return value of type uint32_t at (*ptr) */ #define __LDRT(ptr) ((uint32_t ) __ldrt(ptr)) /** \brief STRT Unprivileged (8 bit) This function executes a Unprivileged STRT instruction for 8 bit values. \param [in] value Value to store \param [in] ptr Pointer to location */ #define __STRBT(value, ptr) __strt(value, ptr) /** \brief STRT Unprivileged (16 bit) This function executes a Unprivileged STRT instruction for 16 bit values. \param [in] value Value to store \param [in] ptr Pointer to location */ #define __STRHT(value, ptr) __strt(value, ptr) /** \brief STRT Unprivileged (32 bit) This function executes a Unprivileged STRT instruction for 32 bit values. \param [in] value Value to store \param [in] ptr Pointer to location */ #define __STRT(value, ptr) __strt(value, ptr) #endif /* (__CORTEX_M >= 0x03) || (__CORTEX_SC >= 300) */ #elif defined ( __GNUC__ ) /*------------------ GNU Compiler ---------------------*/ /* GNU gcc specific functions */ /* Define macros for porting to both thumb1 and thumb2. * For thumb1, use low register (r0-r7), specified by constrant "l" * Otherwise, use general registers, specified by constrant "r" */ #if defined (__thumb__) && !defined (__thumb2__) #define __CMSIS_GCC_OUT_REG(r) "=l" (r) #define __CMSIS_GCC_USE_REG(r) "l" (r) #else #define __CMSIS_GCC_OUT_REG(r) "=r" (r) #define __CMSIS_GCC_USE_REG(r) "r" (r) #endif /** \brief No Operation No Operation does nothing. This instruction can be used for code alignment purposes. */ __attribute__((always_inline)) __STATIC_INLINE void __NOP(void) { __ASM volatile ("nop"); } /** \brief Wait For Interrupt Wait For Interrupt is a hint instruction that suspends execution until one of a number of events occurs. */ __attribute__((always_inline)) __STATIC_INLINE void __WFI(void) { __ASM volatile ("wfi"); } /** \brief Wait For Event Wait For Event is a hint instruction that permits the processor to enter a low-power state until one of a number of events occurs. */ __attribute__((always_inline)) __STATIC_INLINE void __WFE(void) { __ASM volatile ("wfe"); } /** \brief Send Event Send Event is a hint instruction. It causes an event to be signaled to the CPU. */ __attribute__((always_inline)) __STATIC_INLINE void __SEV(void) { __ASM volatile ("sev"); } /** \brief Instruction Synchronization Barrier Instruction Synchronization Barrier flushes the pipeline in the processor, so that all instructions following the ISB are fetched from cache or memory, after the instruction has been completed. */ __attribute__((always_inline)) __STATIC_INLINE void __ISB(void) { __ASM volatile ("isb 0xF":::"memory"); } /** \brief Data Synchronization Barrier This function acts as a special kind of Data Memory Barrier. It completes when all explicit memory accesses before this instruction complete. */ __attribute__((always_inline)) __STATIC_INLINE void __DSB(void) { __ASM volatile ("dsb 0xF":::"memory"); } /** \brief Data Memory Barrier This function ensures the apparent order of the explicit memory operations before and after the instruction, without ensuring their completion. */ __attribute__((always_inline)) __STATIC_INLINE void __DMB(void) { __ASM volatile ("dmb 0xF":::"memory"); } /** \brief Reverse byte order (32 bit) This function reverses the byte order in integer value. \param [in] value Value to reverse \return Reversed value */ __attribute__((always_inline)) __STATIC_INLINE uint32_t __REV(uint32_t value) { #if (__GNUC__ > 4) || (__GNUC__ == 4 && __GNUC_MINOR__ >= 5) return __builtin_bswap32(value); #else uint32_t result; __ASM volatile ("rev %0, %1" : __CMSIS_GCC_OUT_REG (result) : __CMSIS_GCC_USE_REG (value) ); return(result); #endif } /** \brief Reverse byte order (16 bit) This function reverses the byte order in two unsigned short values. \param [in] value Value to reverse \return Reversed value */ __attribute__((always_inline)) __STATIC_INLINE uint32_t __REV16(uint32_t value) { uint32_t result; __ASM volatile ("rev16 %0, %1" : __CMSIS_GCC_OUT_REG (result) : __CMSIS_GCC_USE_REG (value) ); return(result); } /** \brief Reverse byte order in signed short value This function reverses the byte order in a signed short value with sign extension to integer. \param [in] value Value to reverse \return Reversed value */ __attribute__((always_inline)) __STATIC_INLINE int32_t __REVSH(int32_t value) { #if (__GNUC__ > 4) || (__GNUC__ == 4 && __GNUC_MINOR__ >= 8) return (short)__builtin_bswap16(value); #else uint32_t result; __ASM volatile ("revsh %0, %1" : __CMSIS_GCC_OUT_REG (result) : __CMSIS_GCC_USE_REG (value) ); return(result); #endif } /** \brief Rotate Right in unsigned value (32 bit) This function Rotate Right (immediate) provides the value of the contents of a register rotated by a variable number of bits. \param [in] value Value to rotate \param [in] value Number of Bits to rotate \return Rotated value */ __attribute__((always_inline)) __STATIC_INLINE uint32_t __ROR(uint32_t op1, uint32_t op2) { return (op1 >> op2) | (op1 << (32 - op2)); } /** \brief Breakpoint This function causes the processor to enter Debug state. Debug tools can use this to investigate system state when the instruction at a particular address is reached. \param [in] value is ignored by the processor. If required, a debugger can use it to store additional information about the breakpoint. */ #define __BKPT(value) __ASM volatile ("bkpt "#value) /** \brief Reverse bit order of value This function reverses the bit order of the given value. \param [in] value Value to reverse \return Reversed value */ __attribute__((always_inline)) __STATIC_INLINE uint32_t __RBIT(uint32_t value) { uint32_t result; #if (__CORTEX_M >= 0x03) || (__CORTEX_SC >= 300) __ASM volatile ("rbit %0, %1" : "=r" (result) : "r" (value) ); #else int32_t s = 4 /*sizeof(v)*/ * 8 - 1; // extra shift needed at end result = value; // r will be reversed bits of v; first get LSB of v for (value >>= 1; value; value >>= 1) { result <<= 1; result |= value & 1; s--; } result <<= s; // shift when v's highest bits are zero #endif return(result); } /** \brief Count leading zeros This function counts the number of leading zeros of a data value. \param [in] value Value to count the leading zeros \return number of leading zeros in value */ #define __CLZ __builtin_clz #if (__CORTEX_M >= 0x03) || (__CORTEX_SC >= 300) /** \brief LDR Exclusive (8 bit) This function executes a exclusive LDR instruction for 8 bit value. \param [in] ptr Pointer to data \return value of type uint8_t at (*ptr) */ __attribute__((always_inline)) __STATIC_INLINE uint8_t __LDREXB(volatile uint8_t *addr) { uint32_t result; #if (__GNUC__ > 4) || (__GNUC__ == 4 && __GNUC_MINOR__ >= 8) __ASM volatile ("ldrexb %0, %1" : "=r" (result) : "Q" (*addr) ); #else /* Prior to GCC 4.8, "Q" will be expanded to [rx, #0] which is not accepted by assembler. So has to use following less efficient pattern. */ __ASM volatile ("ldrexb %0, [%1]" : "=r" (result) : "r" (addr) : "memory" ); #endif return ((uint8_t) result); /* Add explicit type cast here */ } /** \brief LDR Exclusive (16 bit) This function executes a exclusive LDR instruction for 16 bit values. \param [in] ptr Pointer to data \return value of type uint16_t at (*ptr) */ __attribute__((always_inline)) __STATIC_INLINE uint16_t __LDREXH(volatile uint16_t *addr) { uint32_t result; #if (__GNUC__ > 4) || (__GNUC__ == 4 && __GNUC_MINOR__ >= 8) __ASM volatile ("ldrexh %0, %1" : "=r" (result) : "Q" (*addr) ); #else /* Prior to GCC 4.8, "Q" will be expanded to [rx, #0] which is not accepted by assembler. So has to use following less efficient pattern. */ __ASM volatile ("ldrexh %0, [%1]" : "=r" (result) : "r" (addr) : "memory" ); #endif return ((uint16_t) result); /* Add explicit type cast here */ } /** \brief LDR Exclusive (32 bit) This function executes a exclusive LDR instruction for 32 bit values. \param [in] ptr Pointer to data \return value of type uint32_t at (*ptr) */ __attribute__((always_inline)) __STATIC_INLINE uint32_t __LDREXW(volatile uint32_t *addr) { uint32_t result; __ASM volatile ("ldrex %0, %1" : "=r" (result) : "Q" (*addr) ); return(result); } /** \brief STR Exclusive (8 bit) This function executes a exclusive STR instruction for 8 bit values. \param [in] value Value to store \param [in] ptr Pointer to location \return 0 Function succeeded \return 1 Function failed */ __attribute__((always_inline)) __STATIC_INLINE uint32_t __STREXB(uint8_t value, volatile uint8_t *addr) { uint32_t result; __ASM volatile ("strexb %0, %2, %1" : "=&r" (result), "=Q" (*addr) : "r" ((uint32_t)value) ); return(result); } /** \brief STR Exclusive (16 bit) This function executes a exclusive STR instruction for 16 bit values. \param [in] value Value to store \param [in] ptr Pointer to location \return 0 Function succeeded \return 1 Function failed */ __attribute__((always_inline)) __STATIC_INLINE uint32_t __STREXH(uint16_t value, volatile uint16_t *addr) { uint32_t result; __ASM volatile ("strexh %0, %2, %1" : "=&r" (result), "=Q" (*addr) : "r" ((uint32_t)value) ); return(result); } /** \brief STR Exclusive (32 bit) This function executes a exclusive STR instruction for 32 bit values. \param [in] value Value to store \param [in] ptr Pointer to location \return 0 Function succeeded \return 1 Function failed */ __attribute__((always_inline)) __STATIC_INLINE uint32_t __STREXW(uint32_t value, volatile uint32_t *addr) { uint32_t result; __ASM volatile ("strex %0, %2, %1" : "=&r" (result), "=Q" (*addr) : "r" (value) ); return(result); } /** \brief Remove the exclusive lock This function removes the exclusive lock which is created by LDREX. */ __attribute__((always_inline)) __STATIC_INLINE void __CLREX(void) { __ASM volatile ("clrex" ::: "memory"); } /** \brief Signed Saturate This function saturates a signed value. \param [in] value Value to be saturated \param [in] sat Bit position to saturate to (1..32) \return Saturated value */ #define __SSAT(ARG1,ARG2) \ ({ \ uint32_t __RES, __ARG1 = (ARG1); \ __ASM ("ssat %0, %1, %2" : "=r" (__RES) : "I" (ARG2), "r" (__ARG1) ); \ __RES; \ }) /** \brief Unsigned Saturate This function saturates an unsigned value. \param [in] value Value to be saturated \param [in] sat Bit position to saturate to (0..31) \return Saturated value */ #define __USAT(ARG1,ARG2) \ ({ \ uint32_t __RES, __ARG1 = (ARG1); \ __ASM ("usat %0, %1, %2" : "=r" (__RES) : "I" (ARG2), "r" (__ARG1) ); \ __RES; \ }) /** \brief Rotate Right with Extend (32 bit) This function moves each bit of a bitstring right by one bit. The carry input is shifted in at the left end of the bitstring. \param [in] value Value to rotate \return Rotated value */ __attribute__((always_inline)) __STATIC_INLINE uint32_t __RRX(uint32_t value) { uint32_t result; __ASM volatile ("rrx %0, %1" : __CMSIS_GCC_OUT_REG (result) : __CMSIS_GCC_USE_REG (value) ); return(result); } /** \brief LDRT Unprivileged (8 bit) This function executes a Unprivileged LDRT instruction for 8 bit value. \param [in] ptr Pointer to data \return value of type uint8_t at (*ptr) */ __attribute__((always_inline)) __STATIC_INLINE uint8_t __LDRBT(volatile uint8_t *addr) { uint32_t result; #if (__GNUC__ > 4) || (__GNUC__ == 4 && __GNUC_MINOR__ >= 8) __ASM volatile ("ldrbt %0, %1" : "=r" (result) : "Q" (*addr) ); #else /* Prior to GCC 4.8, "Q" will be expanded to [rx, #0] which is not accepted by assembler. So has to use following less efficient pattern. */ __ASM volatile ("ldrbt %0, [%1]" : "=r" (result) : "r" (addr) : "memory" ); #endif return ((uint8_t) result); /* Add explicit type cast here */ } /** \brief LDRT Unprivileged (16 bit) This function executes a Unprivileged LDRT instruction for 16 bit values. \param [in] ptr Pointer to data \return value of type uint16_t at (*ptr) */ __attribute__((always_inline)) __STATIC_INLINE uint16_t __LDRHT(volatile uint16_t *addr) { uint32_t result; #if (__GNUC__ > 4) || (__GNUC__ == 4 && __GNUC_MINOR__ >= 8) __ASM volatile ("ldrht %0, %1" : "=r" (result) : "Q" (*addr) ); #else /* Prior to GCC 4.8, "Q" will be expanded to [rx, #0] which is not accepted by assembler. So has to use following less efficient pattern. */ __ASM volatile ("ldrht %0, [%1]" : "=r" (result) : "r" (addr) : "memory" ); #endif return ((uint16_t) result); /* Add explicit type cast here */ } /** \brief LDRT Unprivileged (32 bit) This function executes a Unprivileged LDRT instruction for 32 bit values. \param [in] ptr Pointer to data \return value of type uint32_t at (*ptr) */ __attribute__((always_inline)) __STATIC_INLINE uint32_t __LDRT(volatile uint32_t *addr) { uint32_t result; __ASM volatile ("ldrt %0, %1" : "=r" (result) : "Q" (*addr) ); return(result); } /** \brief STRT Unprivileged (8 bit) This function executes a Unprivileged STRT instruction for 8 bit values. \param [in] value Value to store \param [in] ptr Pointer to location */ __attribute__((always_inline)) __STATIC_INLINE void __STRBT(uint8_t value, volatile uint8_t *addr) { __ASM volatile ("strbt %1, %0" : "=Q" (*addr) : "r" ((uint32_t)value) ); } /** \brief STRT Unprivileged (16 bit) This function executes a Unprivileged STRT instruction for 16 bit values. \param [in] value Value to store \param [in] ptr Pointer to location */ __attribute__((always_inline)) __STATIC_INLINE void __STRHT(uint16_t value, volatile uint16_t *addr) { __ASM volatile ("strht %1, %0" : "=Q" (*addr) : "r" ((uint32_t)value) ); } /** \brief STRT Unprivileged (32 bit) This function executes a Unprivileged STRT instruction for 32 bit values. \param [in] value Value to store \param [in] ptr Pointer to location */ __attribute__((always_inline)) __STATIC_INLINE void __STRT(uint32_t value, volatile uint32_t *addr) { __ASM volatile ("strt %1, %0" : "=Q" (*addr) : "r" (value) ); } #endif /* (__CORTEX_M >= 0x03) || (__CORTEX_SC >= 300) */ #elif defined ( __ICCARM__ ) /*------------------ ICC Compiler -------------------*/ /* IAR iccarm specific functions */ #include #elif defined ( __TMS470__ ) /*---------------- TI CCS Compiler ------------------*/ /* TI CCS specific functions */ #include #elif defined ( __TASKING__ ) /*------------------ TASKING Compiler --------------*/ /* TASKING carm specific functions */ /* * The CMSIS functions have been implemented as intrinsics in the compiler. * Please use "carm -?i" to get an up to date list of all intrinsics, * Including the CMSIS ones. */ #elif defined ( __CSMC__ ) /*------------------ COSMIC Compiler -------------------*/ /* Cosmic specific functions */ #include #endif /*@}*/ /* end of group CMSIS_Core_InstructionInterface */ #endif /* __CORE_CMINSTR_H */ ================================================ FILE: Zelig/mbed/TARGET_NUCLEO_F091RC/core_cmSimd.h ================================================ /**************************************************************************//** * @file core_cmSimd.h * @brief CMSIS Cortex-M SIMD Header File * @version V4.10 * @date 18. March 2015 * * @note * ******************************************************************************/ /* Copyright (c) 2009 - 2014 ARM LIMITED All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: - Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. - Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. - Neither the name of ARM 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 COPYRIGHT HOLDERS AND 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. ---------------------------------------------------------------------------*/ #if defined ( __ICCARM__ ) #pragma system_include /* treat file as system include file for MISRA check */ #endif #ifndef __CORE_CMSIMD_H #define __CORE_CMSIMD_H #ifdef __cplusplus extern "C" { #endif /******************************************************************************* * Hardware Abstraction Layer ******************************************************************************/ /* ################### Compiler specific Intrinsics ########################### */ /** \defgroup CMSIS_SIMD_intrinsics CMSIS SIMD Intrinsics Access to dedicated SIMD instructions @{ */ #if defined ( __CC_ARM ) /*------------------RealView Compiler -----------------*/ /* ARM armcc specific functions */ #define __SADD8 __sadd8 #define __QADD8 __qadd8 #define __SHADD8 __shadd8 #define __UADD8 __uadd8 #define __UQADD8 __uqadd8 #define __UHADD8 __uhadd8 #define __SSUB8 __ssub8 #define __QSUB8 __qsub8 #define __SHSUB8 __shsub8 #define __USUB8 __usub8 #define __UQSUB8 __uqsub8 #define __UHSUB8 __uhsub8 #define __SADD16 __sadd16 #define __QADD16 __qadd16 #define __SHADD16 __shadd16 #define __UADD16 __uadd16 #define __UQADD16 __uqadd16 #define __UHADD16 __uhadd16 #define __SSUB16 __ssub16 #define __QSUB16 __qsub16 #define __SHSUB16 __shsub16 #define __USUB16 __usub16 #define __UQSUB16 __uqsub16 #define __UHSUB16 __uhsub16 #define __SASX __sasx #define __QASX __qasx #define __SHASX __shasx #define __UASX __uasx #define __UQASX __uqasx #define __UHASX __uhasx #define __SSAX __ssax #define __QSAX __qsax #define __SHSAX __shsax #define __USAX __usax #define __UQSAX __uqsax #define __UHSAX __uhsax #define __USAD8 __usad8 #define __USADA8 __usada8 #define __SSAT16 __ssat16 #define __USAT16 __usat16 #define __UXTB16 __uxtb16 #define __UXTAB16 __uxtab16 #define __SXTB16 __sxtb16 #define __SXTAB16 __sxtab16 #define __SMUAD __smuad #define __SMUADX __smuadx #define __SMLAD __smlad #define __SMLADX __smladx #define __SMLALD __smlald #define __SMLALDX __smlaldx #define __SMUSD __smusd #define __SMUSDX __smusdx #define __SMLSD __smlsd #define __SMLSDX __smlsdx #define __SMLSLD __smlsld #define __SMLSLDX __smlsldx #define __SEL __sel #define __QADD __qadd #define __QSUB __qsub #define __PKHBT(ARG1,ARG2,ARG3) ( ((((uint32_t)(ARG1)) ) & 0x0000FFFFUL) | \ ((((uint32_t)(ARG2)) << (ARG3)) & 0xFFFF0000UL) ) #define __PKHTB(ARG1,ARG2,ARG3) ( ((((uint32_t)(ARG1)) ) & 0xFFFF0000UL) | \ ((((uint32_t)(ARG2)) >> (ARG3)) & 0x0000FFFFUL) ) #define __SMMLA(ARG1,ARG2,ARG3) ( (int32_t)((((int64_t)(ARG1) * (ARG2)) + \ ((int64_t)(ARG3) << 32) ) >> 32)) #elif defined ( __GNUC__ ) /*------------------ GNU Compiler ---------------------*/ /* GNU gcc specific functions */ __attribute__( ( always_inline ) ) __STATIC_INLINE uint32_t __SADD8(uint32_t op1, uint32_t op2) { uint32_t result; __ASM volatile ("sadd8 %0, %1, %2" : "=r" (result) : "r" (op1), "r" (op2) ); return(result); } __attribute__( ( always_inline ) ) __STATIC_INLINE uint32_t __QADD8(uint32_t op1, uint32_t op2) { uint32_t result; __ASM volatile ("qadd8 %0, %1, %2" : "=r" (result) : "r" (op1), "r" (op2) ); return(result); } __attribute__( ( always_inline ) ) __STATIC_INLINE uint32_t __SHADD8(uint32_t op1, uint32_t op2) { uint32_t result; __ASM volatile ("shadd8 %0, %1, %2" : "=r" (result) : "r" (op1), "r" (op2) ); return(result); } __attribute__( ( always_inline ) ) __STATIC_INLINE uint32_t __UADD8(uint32_t op1, uint32_t op2) { uint32_t result; __ASM volatile ("uadd8 %0, %1, %2" : "=r" (result) : "r" (op1), "r" (op2) ); return(result); } __attribute__( ( always_inline ) ) __STATIC_INLINE uint32_t __UQADD8(uint32_t op1, uint32_t op2) { uint32_t result; __ASM volatile ("uqadd8 %0, %1, %2" : "=r" (result) : "r" (op1), "r" (op2) ); return(result); } __attribute__( ( always_inline ) ) __STATIC_INLINE uint32_t __UHADD8(uint32_t op1, uint32_t op2) { uint32_t result; __ASM volatile ("uhadd8 %0, %1, %2" : "=r" (result) : "r" (op1), "r" (op2) ); return(result); } __attribute__( ( always_inline ) ) __STATIC_INLINE uint32_t __SSUB8(uint32_t op1, uint32_t op2) { uint32_t result; __ASM volatile ("ssub8 %0, %1, %2" : "=r" (result) : "r" (op1), "r" (op2) ); return(result); } __attribute__( ( always_inline ) ) __STATIC_INLINE uint32_t __QSUB8(uint32_t op1, uint32_t op2) { uint32_t result; __ASM volatile ("qsub8 %0, %1, %2" : "=r" (result) : "r" (op1), "r" (op2) ); return(result); } __attribute__( ( always_inline ) ) __STATIC_INLINE uint32_t __SHSUB8(uint32_t op1, uint32_t op2) { uint32_t result; __ASM volatile ("shsub8 %0, %1, %2" : "=r" (result) : "r" (op1), "r" (op2) ); return(result); } __attribute__( ( always_inline ) ) __STATIC_INLINE uint32_t __USUB8(uint32_t op1, uint32_t op2) { uint32_t result; __ASM volatile ("usub8 %0, %1, %2" : "=r" (result) : "r" (op1), "r" (op2) ); return(result); } __attribute__( ( always_inline ) ) __STATIC_INLINE uint32_t __UQSUB8(uint32_t op1, uint32_t op2) { uint32_t result; __ASM volatile ("uqsub8 %0, %1, %2" : "=r" (result) : "r" (op1), "r" (op2) ); return(result); } __attribute__( ( always_inline ) ) __STATIC_INLINE uint32_t __UHSUB8(uint32_t op1, uint32_t op2) { uint32_t result; __ASM volatile ("uhsub8 %0, %1, %2" : "=r" (result) : "r" (op1), "r" (op2) ); return(result); } __attribute__( ( always_inline ) ) __STATIC_INLINE uint32_t __SADD16(uint32_t op1, uint32_t op2) { uint32_t result; __ASM volatile ("sadd16 %0, %1, %2" : "=r" (result) : "r" (op1), "r" (op2) ); return(result); } __attribute__( ( always_inline ) ) __STATIC_INLINE uint32_t __QADD16(uint32_t op1, uint32_t op2) { uint32_t result; __ASM volatile ("qadd16 %0, %1, %2" : "=r" (result) : "r" (op1), "r" (op2) ); return(result); } __attribute__( ( always_inline ) ) __STATIC_INLINE uint32_t __SHADD16(uint32_t op1, uint32_t op2) { uint32_t result; __ASM volatile ("shadd16 %0, %1, %2" : "=r" (result) : "r" (op1), "r" (op2) ); return(result); } __attribute__( ( always_inline ) ) __STATIC_INLINE uint32_t __UADD16(uint32_t op1, uint32_t op2) { uint32_t result; __ASM volatile ("uadd16 %0, %1, %2" : "=r" (result) : "r" (op1), "r" (op2) ); return(result); } __attribute__( ( always_inline ) ) __STATIC_INLINE uint32_t __UQADD16(uint32_t op1, uint32_t op2) { uint32_t result; __ASM volatile ("uqadd16 %0, %1, %2" : "=r" (result) : "r" (op1), "r" (op2) ); return(result); } __attribute__( ( always_inline ) ) __STATIC_INLINE uint32_t __UHADD16(uint32_t op1, uint32_t op2) { uint32_t result; __ASM volatile ("uhadd16 %0, %1, %2" : "=r" (result) : "r" (op1), "r" (op2) ); return(result); } __attribute__( ( always_inline ) ) __STATIC_INLINE uint32_t __SSUB16(uint32_t op1, uint32_t op2) { uint32_t result; __ASM volatile ("ssub16 %0, %1, %2" : "=r" (result) : "r" (op1), "r" (op2) ); return(result); } __attribute__( ( always_inline ) ) __STATIC_INLINE uint32_t __QSUB16(uint32_t op1, uint32_t op2) { uint32_t result; __ASM volatile ("qsub16 %0, %1, %2" : "=r" (result) : "r" (op1), "r" (op2) ); return(result); } __attribute__( ( always_inline ) ) __STATIC_INLINE uint32_t __SHSUB16(uint32_t op1, uint32_t op2) { uint32_t result; __ASM volatile ("shsub16 %0, %1, %2" : "=r" (result) : "r" (op1), "r" (op2) ); return(result); } __attribute__( ( always_inline ) ) __STATIC_INLINE uint32_t __USUB16(uint32_t op1, uint32_t op2) { uint32_t result; __ASM volatile ("usub16 %0, %1, %2" : "=r" (result) : "r" (op1), "r" (op2) ); return(result); } __attribute__( ( always_inline ) ) __STATIC_INLINE uint32_t __UQSUB16(uint32_t op1, uint32_t op2) { uint32_t result; __ASM volatile ("uqsub16 %0, %1, %2" : "=r" (result) : "r" (op1), "r" (op2) ); return(result); } __attribute__( ( always_inline ) ) __STATIC_INLINE uint32_t __UHSUB16(uint32_t op1, uint32_t op2) { uint32_t result; __ASM volatile ("uhsub16 %0, %1, %2" : "=r" (result) : "r" (op1), "r" (op2) ); return(result); } __attribute__( ( always_inline ) ) __STATIC_INLINE uint32_t __SASX(uint32_t op1, uint32_t op2) { uint32_t result; __ASM volatile ("sasx %0, %1, %2" : "=r" (result) : "r" (op1), "r" (op2) ); return(result); } __attribute__( ( always_inline ) ) __STATIC_INLINE uint32_t __QASX(uint32_t op1, uint32_t op2) { uint32_t result; __ASM volatile ("qasx %0, %1, %2" : "=r" (result) : "r" (op1), "r" (op2) ); return(result); } __attribute__( ( always_inline ) ) __STATIC_INLINE uint32_t __SHASX(uint32_t op1, uint32_t op2) { uint32_t result; __ASM volatile ("shasx %0, %1, %2" : "=r" (result) : "r" (op1), "r" (op2) ); return(result); } __attribute__( ( always_inline ) ) __STATIC_INLINE uint32_t __UASX(uint32_t op1, uint32_t op2) { uint32_t result; __ASM volatile ("uasx %0, %1, %2" : "=r" (result) : "r" (op1), "r" (op2) ); return(result); } __attribute__( ( always_inline ) ) __STATIC_INLINE uint32_t __UQASX(uint32_t op1, uint32_t op2) { uint32_t result; __ASM volatile ("uqasx %0, %1, %2" : "=r" (result) : "r" (op1), "r" (op2) ); return(result); } __attribute__( ( always_inline ) ) __STATIC_INLINE uint32_t __UHASX(uint32_t op1, uint32_t op2) { uint32_t result; __ASM volatile ("uhasx %0, %1, %2" : "=r" (result) : "r" (op1), "r" (op2) ); return(result); } __attribute__( ( always_inline ) ) __STATIC_INLINE uint32_t __SSAX(uint32_t op1, uint32_t op2) { uint32_t result; __ASM volatile ("ssax %0, %1, %2" : "=r" (result) : "r" (op1), "r" (op2) ); return(result); } __attribute__( ( always_inline ) ) __STATIC_INLINE uint32_t __QSAX(uint32_t op1, uint32_t op2) { uint32_t result; __ASM volatile ("qsax %0, %1, %2" : "=r" (result) : "r" (op1), "r" (op2) ); return(result); } __attribute__( ( always_inline ) ) __STATIC_INLINE uint32_t __SHSAX(uint32_t op1, uint32_t op2) { uint32_t result; __ASM volatile ("shsax %0, %1, %2" : "=r" (result) : "r" (op1), "r" (op2) ); return(result); } __attribute__( ( always_inline ) ) __STATIC_INLINE uint32_t __USAX(uint32_t op1, uint32_t op2) { uint32_t result; __ASM volatile ("usax %0, %1, %2" : "=r" (result) : "r" (op1), "r" (op2) ); return(result); } __attribute__( ( always_inline ) ) __STATIC_INLINE uint32_t __UQSAX(uint32_t op1, uint32_t op2) { uint32_t result; __ASM volatile ("uqsax %0, %1, %2" : "=r" (result) : "r" (op1), "r" (op2) ); return(result); } __attribute__( ( always_inline ) ) __STATIC_INLINE uint32_t __UHSAX(uint32_t op1, uint32_t op2) { uint32_t result; __ASM volatile ("uhsax %0, %1, %2" : "=r" (result) : "r" (op1), "r" (op2) ); return(result); } __attribute__( ( always_inline ) ) __STATIC_INLINE uint32_t __USAD8(uint32_t op1, uint32_t op2) { uint32_t result; __ASM volatile ("usad8 %0, %1, %2" : "=r" (result) : "r" (op1), "r" (op2) ); return(result); } __attribute__( ( always_inline ) ) __STATIC_INLINE uint32_t __USADA8(uint32_t op1, uint32_t op2, uint32_t op3) { uint32_t result; __ASM volatile ("usada8 %0, %1, %2, %3" : "=r" (result) : "r" (op1), "r" (op2), "r" (op3) ); return(result); } #define __SSAT16(ARG1,ARG2) \ ({ \ uint32_t __RES, __ARG1 = (ARG1); \ __ASM ("ssat16 %0, %1, %2" : "=r" (__RES) : "I" (ARG2), "r" (__ARG1) ); \ __RES; \ }) #define __USAT16(ARG1,ARG2) \ ({ \ uint32_t __RES, __ARG1 = (ARG1); \ __ASM ("usat16 %0, %1, %2" : "=r" (__RES) : "I" (ARG2), "r" (__ARG1) ); \ __RES; \ }) __attribute__( ( always_inline ) ) __STATIC_INLINE uint32_t __UXTB16(uint32_t op1) { uint32_t result; __ASM volatile ("uxtb16 %0, %1" : "=r" (result) : "r" (op1)); return(result); } __attribute__( ( always_inline ) ) __STATIC_INLINE uint32_t __UXTAB16(uint32_t op1, uint32_t op2) { uint32_t result; __ASM volatile ("uxtab16 %0, %1, %2" : "=r" (result) : "r" (op1), "r" (op2) ); return(result); } __attribute__( ( always_inline ) ) __STATIC_INLINE uint32_t __SXTB16(uint32_t op1) { uint32_t result; __ASM volatile ("sxtb16 %0, %1" : "=r" (result) : "r" (op1)); return(result); } __attribute__( ( always_inline ) ) __STATIC_INLINE uint32_t __SXTAB16(uint32_t op1, uint32_t op2) { uint32_t result; __ASM volatile ("sxtab16 %0, %1, %2" : "=r" (result) : "r" (op1), "r" (op2) ); return(result); } __attribute__( ( always_inline ) ) __STATIC_INLINE uint32_t __SMUAD (uint32_t op1, uint32_t op2) { uint32_t result; __ASM volatile ("smuad %0, %1, %2" : "=r" (result) : "r" (op1), "r" (op2) ); return(result); } __attribute__( ( always_inline ) ) __STATIC_INLINE uint32_t __SMUADX (uint32_t op1, uint32_t op2) { uint32_t result; __ASM volatile ("smuadx %0, %1, %2" : "=r" (result) : "r" (op1), "r" (op2) ); return(result); } __attribute__( ( always_inline ) ) __STATIC_INLINE uint32_t __SMLAD (uint32_t op1, uint32_t op2, uint32_t op3) { uint32_t result; __ASM volatile ("smlad %0, %1, %2, %3" : "=r" (result) : "r" (op1), "r" (op2), "r" (op3) ); return(result); } __attribute__( ( always_inline ) ) __STATIC_INLINE uint32_t __SMLADX (uint32_t op1, uint32_t op2, uint32_t op3) { uint32_t result; __ASM volatile ("smladx %0, %1, %2, %3" : "=r" (result) : "r" (op1), "r" (op2), "r" (op3) ); return(result); } __attribute__( ( always_inline ) ) __STATIC_INLINE uint64_t __SMLALD (uint32_t op1, uint32_t op2, uint64_t acc) { union llreg_u{ uint32_t w32[2]; uint64_t w64; } llr; llr.w64 = acc; #ifndef __ARMEB__ // Little endian __ASM volatile ("smlald %0, %1, %2, %3" : "=r" (llr.w32[0]), "=r" (llr.w32[1]): "r" (op1), "r" (op2) , "0" (llr.w32[0]), "1" (llr.w32[1]) ); #else // Big endian __ASM volatile ("smlald %0, %1, %2, %3" : "=r" (llr.w32[1]), "=r" (llr.w32[0]): "r" (op1), "r" (op2) , "0" (llr.w32[1]), "1" (llr.w32[0]) ); #endif return(llr.w64); } __attribute__( ( always_inline ) ) __STATIC_INLINE uint64_t __SMLALDX (uint32_t op1, uint32_t op2, uint64_t acc) { union llreg_u{ uint32_t w32[2]; uint64_t w64; } llr; llr.w64 = acc; #ifndef __ARMEB__ // Little endian __ASM volatile ("smlaldx %0, %1, %2, %3" : "=r" (llr.w32[0]), "=r" (llr.w32[1]): "r" (op1), "r" (op2) , "0" (llr.w32[0]), "1" (llr.w32[1]) ); #else // Big endian __ASM volatile ("smlaldx %0, %1, %2, %3" : "=r" (llr.w32[1]), "=r" (llr.w32[0]): "r" (op1), "r" (op2) , "0" (llr.w32[1]), "1" (llr.w32[0]) ); #endif return(llr.w64); } __attribute__( ( always_inline ) ) __STATIC_INLINE uint32_t __SMUSD (uint32_t op1, uint32_t op2) { uint32_t result; __ASM volatile ("smusd %0, %1, %2" : "=r" (result) : "r" (op1), "r" (op2) ); return(result); } __attribute__( ( always_inline ) ) __STATIC_INLINE uint32_t __SMUSDX (uint32_t op1, uint32_t op2) { uint32_t result; __ASM volatile ("smusdx %0, %1, %2" : "=r" (result) : "r" (op1), "r" (op2) ); return(result); } __attribute__( ( always_inline ) ) __STATIC_INLINE uint32_t __SMLSD (uint32_t op1, uint32_t op2, uint32_t op3) { uint32_t result; __ASM volatile ("smlsd %0, %1, %2, %3" : "=r" (result) : "r" (op1), "r" (op2), "r" (op3) ); return(result); } __attribute__( ( always_inline ) ) __STATIC_INLINE uint32_t __SMLSDX (uint32_t op1, uint32_t op2, uint32_t op3) { uint32_t result; __ASM volatile ("smlsdx %0, %1, %2, %3" : "=r" (result) : "r" (op1), "r" (op2), "r" (op3) ); return(result); } __attribute__( ( always_inline ) ) __STATIC_INLINE uint64_t __SMLSLD (uint32_t op1, uint32_t op2, uint64_t acc) { union llreg_u{ uint32_t w32[2]; uint64_t w64; } llr; llr.w64 = acc; #ifndef __ARMEB__ // Little endian __ASM volatile ("smlsld %0, %1, %2, %3" : "=r" (llr.w32[0]), "=r" (llr.w32[1]): "r" (op1), "r" (op2) , "0" (llr.w32[0]), "1" (llr.w32[1]) ); #else // Big endian __ASM volatile ("smlsld %0, %1, %2, %3" : "=r" (llr.w32[1]), "=r" (llr.w32[0]): "r" (op1), "r" (op2) , "0" (llr.w32[1]), "1" (llr.w32[0]) ); #endif return(llr.w64); } __attribute__( ( always_inline ) ) __STATIC_INLINE uint64_t __SMLSLDX (uint32_t op1, uint32_t op2, uint64_t acc) { union llreg_u{ uint32_t w32[2]; uint64_t w64; } llr; llr.w64 = acc; #ifndef __ARMEB__ // Little endian __ASM volatile ("smlsldx %0, %1, %2, %3" : "=r" (llr.w32[0]), "=r" (llr.w32[1]): "r" (op1), "r" (op2) , "0" (llr.w32[0]), "1" (llr.w32[1]) ); #else // Big endian __ASM volatile ("smlsldx %0, %1, %2, %3" : "=r" (llr.w32[1]), "=r" (llr.w32[0]): "r" (op1), "r" (op2) , "0" (llr.w32[1]), "1" (llr.w32[0]) ); #endif return(llr.w64); } __attribute__( ( always_inline ) ) __STATIC_INLINE uint32_t __SEL (uint32_t op1, uint32_t op2) { uint32_t result; __ASM volatile ("sel %0, %1, %2" : "=r" (result) : "r" (op1), "r" (op2) ); return(result); } __attribute__( ( always_inline ) ) __STATIC_INLINE uint32_t __QADD(uint32_t op1, uint32_t op2) { uint32_t result; __ASM volatile ("qadd %0, %1, %2" : "=r" (result) : "r" (op1), "r" (op2) ); return(result); } __attribute__( ( always_inline ) ) __STATIC_INLINE uint32_t __QSUB(uint32_t op1, uint32_t op2) { uint32_t result; __ASM volatile ("qsub %0, %1, %2" : "=r" (result) : "r" (op1), "r" (op2) ); return(result); } #define __PKHBT(ARG1,ARG2,ARG3) \ ({ \ uint32_t __RES, __ARG1 = (ARG1), __ARG2 = (ARG2); \ __ASM ("pkhbt %0, %1, %2, lsl %3" : "=r" (__RES) : "r" (__ARG1), "r" (__ARG2), "I" (ARG3) ); \ __RES; \ }) #define __PKHTB(ARG1,ARG2,ARG3) \ ({ \ uint32_t __RES, __ARG1 = (ARG1), __ARG2 = (ARG2); \ if (ARG3 == 0) \ __ASM ("pkhtb %0, %1, %2" : "=r" (__RES) : "r" (__ARG1), "r" (__ARG2) ); \ else \ __ASM ("pkhtb %0, %1, %2, asr %3" : "=r" (__RES) : "r" (__ARG1), "r" (__ARG2), "I" (ARG3) ); \ __RES; \ }) __attribute__( ( always_inline ) ) __STATIC_INLINE uint32_t __SMMLA (int32_t op1, int32_t op2, int32_t op3) { int32_t result; __ASM volatile ("smmla %0, %1, %2, %3" : "=r" (result): "r" (op1), "r" (op2), "r" (op3) ); return(result); } #elif defined ( __ICCARM__ ) /*------------------ ICC Compiler -------------------*/ /* IAR iccarm specific functions */ #include #elif defined ( __TMS470__ ) /*---------------- TI CCS Compiler ------------------*/ /* TI CCS specific functions */ #include #elif defined ( __TASKING__ ) /*------------------ TASKING Compiler --------------*/ /* TASKING carm specific functions */ /* not yet supported */ #elif defined ( __CSMC__ ) /*------------------ COSMIC Compiler -------------------*/ /* Cosmic specific functions */ #include #endif /*@} end of group CMSIS_SIMD_intrinsics */ #ifdef __cplusplus } #endif #endif /* __CORE_CMSIMD_H */ ================================================ FILE: Zelig/mbed/TARGET_NUCLEO_F091RC/core_sc000.h ================================================ /**************************************************************************//** * @file core_sc000.h * @brief CMSIS SC000 Core Peripheral Access Layer Header File * @version V4.10 * @date 18. March 2015 * * @note * ******************************************************************************/ /* Copyright (c) 2009 - 2015 ARM LIMITED All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: - Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. - Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. - Neither the name of ARM 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 COPYRIGHT HOLDERS AND 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. ---------------------------------------------------------------------------*/ #if defined ( __ICCARM__ ) #pragma system_include /* treat file as system include file for MISRA check */ #endif #ifndef __CORE_SC000_H_GENERIC #define __CORE_SC000_H_GENERIC #ifdef __cplusplus extern "C" { #endif /** \page CMSIS_MISRA_Exceptions MISRA-C:2004 Compliance Exceptions CMSIS violates the following MISRA-C:2004 rules: \li Required Rule 8.5, object/function definition in header file.
Function definitions in header files are used to allow 'inlining'. \li Required Rule 18.4, declaration of union type or object of union type: '{...}'.
Unions are used for effective representation of core registers. \li Advisory Rule 19.7, Function-like macro defined.
Function-like macros are used to allow more efficient code. */ /******************************************************************************* * CMSIS definitions ******************************************************************************/ /** \ingroup SC000 @{ */ /* CMSIS SC000 definitions */ #define __SC000_CMSIS_VERSION_MAIN (0x04) /*!< [31:16] CMSIS HAL main version */ #define __SC000_CMSIS_VERSION_SUB (0x00) /*!< [15:0] CMSIS HAL sub version */ #define __SC000_CMSIS_VERSION ((__SC000_CMSIS_VERSION_MAIN << 16) | \ __SC000_CMSIS_VERSION_SUB ) /*!< CMSIS HAL version number */ #define __CORTEX_SC (000) /*!< Cortex secure core */ #if defined ( __CC_ARM ) #define __ASM __asm /*!< asm keyword for ARM Compiler */ #define __INLINE __inline /*!< inline keyword for ARM Compiler */ #define __STATIC_INLINE static __inline #elif defined ( __GNUC__ ) #define __ASM __asm /*!< asm keyword for GNU Compiler */ #define __INLINE inline /*!< inline keyword for GNU Compiler */ #define __STATIC_INLINE static inline #elif defined ( __ICCARM__ ) #define __ASM __asm /*!< asm keyword for IAR Compiler */ #define __INLINE inline /*!< inline keyword for IAR Compiler. Only available in High optimization mode! */ #define __STATIC_INLINE static inline #elif defined ( __TMS470__ ) #define __ASM __asm /*!< asm keyword for TI CCS Compiler */ #define __STATIC_INLINE static inline #elif defined ( __TASKING__ ) #define __ASM __asm /*!< asm keyword for TASKING Compiler */ #define __INLINE inline /*!< inline keyword for TASKING Compiler */ #define __STATIC_INLINE static inline #elif defined ( __CSMC__ ) #define __packed #define __ASM _asm /*!< asm keyword for COSMIC Compiler */ #define __INLINE inline /*use -pc99 on compile line !< inline keyword for COSMIC Compiler */ #define __STATIC_INLINE static inline #endif /** __FPU_USED indicates whether an FPU is used or not. This core does not support an FPU at all */ #define __FPU_USED 0 #if defined ( __CC_ARM ) #if defined __TARGET_FPU_VFP #warning "Compiler generates FPU instructions for a device without an FPU (check __FPU_PRESENT)" #endif #elif defined ( __GNUC__ ) #if defined (__VFP_FP__) && !defined(__SOFTFP__) #warning "Compiler generates FPU instructions for a device without an FPU (check __FPU_PRESENT)" #endif #elif defined ( __ICCARM__ ) #if defined __ARMVFP__ #warning "Compiler generates FPU instructions for a device without an FPU (check __FPU_PRESENT)" #endif #elif defined ( __TMS470__ ) #if defined __TI__VFP_SUPPORT____ #warning "Compiler generates FPU instructions for a device without an FPU (check __FPU_PRESENT)" #endif #elif defined ( __TASKING__ ) #if defined __FPU_VFP__ #error "Compiler generates FPU instructions for a device without an FPU (check __FPU_PRESENT)" #endif #elif defined ( __CSMC__ ) /* Cosmic */ #if ( __CSMC__ & 0x400) // FPU present for parser #error "Compiler generates FPU instructions for a device without an FPU (check __FPU_PRESENT)" #endif #endif #include /* standard types definitions */ #include /* Core Instruction Access */ #include /* Core Function Access */ #ifdef __cplusplus } #endif #endif /* __CORE_SC000_H_GENERIC */ #ifndef __CMSIS_GENERIC #ifndef __CORE_SC000_H_DEPENDANT #define __CORE_SC000_H_DEPENDANT #ifdef __cplusplus extern "C" { #endif /* check device defines and use defaults */ #if defined __CHECK_DEVICE_DEFINES #ifndef __SC000_REV #define __SC000_REV 0x0000 #warning "__SC000_REV not defined in device header file; using default!" #endif #ifndef __MPU_PRESENT #define __MPU_PRESENT 0 #warning "__MPU_PRESENT not defined in device header file; using default!" #endif #ifndef __NVIC_PRIO_BITS #define __NVIC_PRIO_BITS 2 #warning "__NVIC_PRIO_BITS not defined in device header file; using default!" #endif #ifndef __Vendor_SysTickConfig #define __Vendor_SysTickConfig 0 #warning "__Vendor_SysTickConfig not defined in device header file; using default!" #endif #endif /* IO definitions (access restrictions to peripheral registers) */ /** \defgroup CMSIS_glob_defs CMSIS Global Defines IO Type Qualifiers are used \li to specify the access to peripheral variables. \li for automatic generation of peripheral register debug information. */ #ifdef __cplusplus #define __I volatile /*!< Defines 'read only' permissions */ #else #define __I volatile const /*!< Defines 'read only' permissions */ #endif #define __O volatile /*!< Defines 'write only' permissions */ #define __IO volatile /*!< Defines 'read / write' permissions */ /*@} end of group SC000 */ /******************************************************************************* * Register Abstraction Core Register contain: - Core Register - Core NVIC Register - Core SCB Register - Core SysTick Register - Core MPU Register ******************************************************************************/ /** \defgroup CMSIS_core_register Defines and Type Definitions \brief Type definitions and defines for Cortex-M processor based devices. */ /** \ingroup CMSIS_core_register \defgroup CMSIS_CORE Status and Control Registers \brief Core Register type definitions. @{ */ /** \brief Union type to access the Application Program Status Register (APSR). */ typedef union { struct { uint32_t _reserved0:28; /*!< bit: 0..27 Reserved */ uint32_t V:1; /*!< bit: 28 Overflow condition code flag */ uint32_t C:1; /*!< bit: 29 Carry condition code flag */ uint32_t Z:1; /*!< bit: 30 Zero condition code flag */ uint32_t N:1; /*!< bit: 31 Negative condition code flag */ } b; /*!< Structure used for bit access */ uint32_t w; /*!< Type used for word access */ } APSR_Type; /* APSR Register Definitions */ #define APSR_N_Pos 31 /*!< APSR: N Position */ #define APSR_N_Msk (1UL << APSR_N_Pos) /*!< APSR: N Mask */ #define APSR_Z_Pos 30 /*!< APSR: Z Position */ #define APSR_Z_Msk (1UL << APSR_Z_Pos) /*!< APSR: Z Mask */ #define APSR_C_Pos 29 /*!< APSR: C Position */ #define APSR_C_Msk (1UL << APSR_C_Pos) /*!< APSR: C Mask */ #define APSR_V_Pos 28 /*!< APSR: V Position */ #define APSR_V_Msk (1UL << APSR_V_Pos) /*!< APSR: V Mask */ /** \brief Union type to access the Interrupt Program Status Register (IPSR). */ typedef union { struct { uint32_t ISR:9; /*!< bit: 0.. 8 Exception number */ uint32_t _reserved0:23; /*!< bit: 9..31 Reserved */ } b; /*!< Structure used for bit access */ uint32_t w; /*!< Type used for word access */ } IPSR_Type; /* IPSR Register Definitions */ #define IPSR_ISR_Pos 0 /*!< IPSR: ISR Position */ #define IPSR_ISR_Msk (0x1FFUL /*<< IPSR_ISR_Pos*/) /*!< IPSR: ISR Mask */ /** \brief Union type to access the Special-Purpose Program Status Registers (xPSR). */ typedef union { struct { uint32_t ISR:9; /*!< bit: 0.. 8 Exception number */ uint32_t _reserved0:15; /*!< bit: 9..23 Reserved */ uint32_t T:1; /*!< bit: 24 Thumb bit (read 0) */ uint32_t _reserved1:3; /*!< bit: 25..27 Reserved */ uint32_t V:1; /*!< bit: 28 Overflow condition code flag */ uint32_t C:1; /*!< bit: 29 Carry condition code flag */ uint32_t Z:1; /*!< bit: 30 Zero condition code flag */ uint32_t N:1; /*!< bit: 31 Negative condition code flag */ } b; /*!< Structure used for bit access */ uint32_t w; /*!< Type used for word access */ } xPSR_Type; /* xPSR Register Definitions */ #define xPSR_N_Pos 31 /*!< xPSR: N Position */ #define xPSR_N_Msk (1UL << xPSR_N_Pos) /*!< xPSR: N Mask */ #define xPSR_Z_Pos 30 /*!< xPSR: Z Position */ #define xPSR_Z_Msk (1UL << xPSR_Z_Pos) /*!< xPSR: Z Mask */ #define xPSR_C_Pos 29 /*!< xPSR: C Position */ #define xPSR_C_Msk (1UL << xPSR_C_Pos) /*!< xPSR: C Mask */ #define xPSR_V_Pos 28 /*!< xPSR: V Position */ #define xPSR_V_Msk (1UL << xPSR_V_Pos) /*!< xPSR: V Mask */ #define xPSR_T_Pos 24 /*!< xPSR: T Position */ #define xPSR_T_Msk (1UL << xPSR_T_Pos) /*!< xPSR: T Mask */ #define xPSR_ISR_Pos 0 /*!< xPSR: ISR Position */ #define xPSR_ISR_Msk (0x1FFUL /*<< xPSR_ISR_Pos*/) /*!< xPSR: ISR Mask */ /** \brief Union type to access the Control Registers (CONTROL). */ typedef union { struct { uint32_t _reserved0:1; /*!< bit: 0 Reserved */ uint32_t SPSEL:1; /*!< bit: 1 Stack to be used */ uint32_t _reserved1:30; /*!< bit: 2..31 Reserved */ } b; /*!< Structure used for bit access */ uint32_t w; /*!< Type used for word access */ } CONTROL_Type; /* CONTROL Register Definitions */ #define CONTROL_SPSEL_Pos 1 /*!< CONTROL: SPSEL Position */ #define CONTROL_SPSEL_Msk (1UL << CONTROL_SPSEL_Pos) /*!< CONTROL: SPSEL Mask */ /*@} end of group CMSIS_CORE */ /** \ingroup CMSIS_core_register \defgroup CMSIS_NVIC Nested Vectored Interrupt Controller (NVIC) \brief Type definitions for the NVIC Registers @{ */ /** \brief Structure type to access the Nested Vectored Interrupt Controller (NVIC). */ typedef struct { __IO uint32_t ISER[1]; /*!< Offset: 0x000 (R/W) Interrupt Set Enable Register */ uint32_t RESERVED0[31]; __IO uint32_t ICER[1]; /*!< Offset: 0x080 (R/W) Interrupt Clear Enable Register */ uint32_t RSERVED1[31]; __IO uint32_t ISPR[1]; /*!< Offset: 0x100 (R/W) Interrupt Set Pending Register */ uint32_t RESERVED2[31]; __IO uint32_t ICPR[1]; /*!< Offset: 0x180 (R/W) Interrupt Clear Pending Register */ uint32_t RESERVED3[31]; uint32_t RESERVED4[64]; __IO uint32_t IP[8]; /*!< Offset: 0x300 (R/W) Interrupt Priority Register */ } NVIC_Type; /*@} end of group CMSIS_NVIC */ /** \ingroup CMSIS_core_register \defgroup CMSIS_SCB System Control Block (SCB) \brief Type definitions for the System Control Block Registers @{ */ /** \brief Structure type to access the System Control Block (SCB). */ typedef struct { __I uint32_t CPUID; /*!< Offset: 0x000 (R/ ) CPUID Base Register */ __IO uint32_t ICSR; /*!< Offset: 0x004 (R/W) Interrupt Control and State Register */ __IO uint32_t VTOR; /*!< Offset: 0x008 (R/W) Vector Table Offset Register */ __IO uint32_t AIRCR; /*!< Offset: 0x00C (R/W) Application Interrupt and Reset Control Register */ __IO uint32_t SCR; /*!< Offset: 0x010 (R/W) System Control Register */ __IO uint32_t CCR; /*!< Offset: 0x014 (R/W) Configuration Control Register */ uint32_t RESERVED0[1]; __IO uint32_t SHP[2]; /*!< Offset: 0x01C (R/W) System Handlers Priority Registers. [0] is RESERVED */ __IO uint32_t SHCSR; /*!< Offset: 0x024 (R/W) System Handler Control and State Register */ uint32_t RESERVED1[154]; __IO uint32_t SFCR; /*!< Offset: 0x290 (R/W) Security Features Control Register */ } SCB_Type; /* SCB CPUID Register Definitions */ #define SCB_CPUID_IMPLEMENTER_Pos 24 /*!< SCB CPUID: IMPLEMENTER Position */ #define SCB_CPUID_IMPLEMENTER_Msk (0xFFUL << SCB_CPUID_IMPLEMENTER_Pos) /*!< SCB CPUID: IMPLEMENTER Mask */ #define SCB_CPUID_VARIANT_Pos 20 /*!< SCB CPUID: VARIANT Position */ #define SCB_CPUID_VARIANT_Msk (0xFUL << SCB_CPUID_VARIANT_Pos) /*!< SCB CPUID: VARIANT Mask */ #define SCB_CPUID_ARCHITECTURE_Pos 16 /*!< SCB CPUID: ARCHITECTURE Position */ #define SCB_CPUID_ARCHITECTURE_Msk (0xFUL << SCB_CPUID_ARCHITECTURE_Pos) /*!< SCB CPUID: ARCHITECTURE Mask */ #define SCB_CPUID_PARTNO_Pos 4 /*!< SCB CPUID: PARTNO Position */ #define SCB_CPUID_PARTNO_Msk (0xFFFUL << SCB_CPUID_PARTNO_Pos) /*!< SCB CPUID: PARTNO Mask */ #define SCB_CPUID_REVISION_Pos 0 /*!< SCB CPUID: REVISION Position */ #define SCB_CPUID_REVISION_Msk (0xFUL /*<< SCB_CPUID_REVISION_Pos*/) /*!< SCB CPUID: REVISION Mask */ /* SCB Interrupt Control State Register Definitions */ #define SCB_ICSR_NMIPENDSET_Pos 31 /*!< SCB ICSR: NMIPENDSET Position */ #define SCB_ICSR_NMIPENDSET_Msk (1UL << SCB_ICSR_NMIPENDSET_Pos) /*!< SCB ICSR: NMIPENDSET Mask */ #define SCB_ICSR_PENDSVSET_Pos 28 /*!< SCB ICSR: PENDSVSET Position */ #define SCB_ICSR_PENDSVSET_Msk (1UL << SCB_ICSR_PENDSVSET_Pos) /*!< SCB ICSR: PENDSVSET Mask */ #define SCB_ICSR_PENDSVCLR_Pos 27 /*!< SCB ICSR: PENDSVCLR Position */ #define SCB_ICSR_PENDSVCLR_Msk (1UL << SCB_ICSR_PENDSVCLR_Pos) /*!< SCB ICSR: PENDSVCLR Mask */ #define SCB_ICSR_PENDSTSET_Pos 26 /*!< SCB ICSR: PENDSTSET Position */ #define SCB_ICSR_PENDSTSET_Msk (1UL << SCB_ICSR_PENDSTSET_Pos) /*!< SCB ICSR: PENDSTSET Mask */ #define SCB_ICSR_PENDSTCLR_Pos 25 /*!< SCB ICSR: PENDSTCLR Position */ #define SCB_ICSR_PENDSTCLR_Msk (1UL << SCB_ICSR_PENDSTCLR_Pos) /*!< SCB ICSR: PENDSTCLR Mask */ #define SCB_ICSR_ISRPREEMPT_Pos 23 /*!< SCB ICSR: ISRPREEMPT Position */ #define SCB_ICSR_ISRPREEMPT_Msk (1UL << SCB_ICSR_ISRPREEMPT_Pos) /*!< SCB ICSR: ISRPREEMPT Mask */ #define SCB_ICSR_ISRPENDING_Pos 22 /*!< SCB ICSR: ISRPENDING Position */ #define SCB_ICSR_ISRPENDING_Msk (1UL << SCB_ICSR_ISRPENDING_Pos) /*!< SCB ICSR: ISRPENDING Mask */ #define SCB_ICSR_VECTPENDING_Pos 12 /*!< SCB ICSR: VECTPENDING Position */ #define SCB_ICSR_VECTPENDING_Msk (0x1FFUL << SCB_ICSR_VECTPENDING_Pos) /*!< SCB ICSR: VECTPENDING Mask */ #define SCB_ICSR_VECTACTIVE_Pos 0 /*!< SCB ICSR: VECTACTIVE Position */ #define SCB_ICSR_VECTACTIVE_Msk (0x1FFUL /*<< SCB_ICSR_VECTACTIVE_Pos*/) /*!< SCB ICSR: VECTACTIVE Mask */ /* SCB Interrupt Control State Register Definitions */ #define SCB_VTOR_TBLOFF_Pos 7 /*!< SCB VTOR: TBLOFF Position */ #define SCB_VTOR_TBLOFF_Msk (0x1FFFFFFUL << SCB_VTOR_TBLOFF_Pos) /*!< SCB VTOR: TBLOFF Mask */ /* SCB Application Interrupt and Reset Control Register Definitions */ #define SCB_AIRCR_VECTKEY_Pos 16 /*!< SCB AIRCR: VECTKEY Position */ #define SCB_AIRCR_VECTKEY_Msk (0xFFFFUL << SCB_AIRCR_VECTKEY_Pos) /*!< SCB AIRCR: VECTKEY Mask */ #define SCB_AIRCR_VECTKEYSTAT_Pos 16 /*!< SCB AIRCR: VECTKEYSTAT Position */ #define SCB_AIRCR_VECTKEYSTAT_Msk (0xFFFFUL << SCB_AIRCR_VECTKEYSTAT_Pos) /*!< SCB AIRCR: VECTKEYSTAT Mask */ #define SCB_AIRCR_ENDIANESS_Pos 15 /*!< SCB AIRCR: ENDIANESS Position */ #define SCB_AIRCR_ENDIANESS_Msk (1UL << SCB_AIRCR_ENDIANESS_Pos) /*!< SCB AIRCR: ENDIANESS Mask */ #define SCB_AIRCR_SYSRESETREQ_Pos 2 /*!< SCB AIRCR: SYSRESETREQ Position */ #define SCB_AIRCR_SYSRESETREQ_Msk (1UL << SCB_AIRCR_SYSRESETREQ_Pos) /*!< SCB AIRCR: SYSRESETREQ Mask */ #define SCB_AIRCR_VECTCLRACTIVE_Pos 1 /*!< SCB AIRCR: VECTCLRACTIVE Position */ #define SCB_AIRCR_VECTCLRACTIVE_Msk (1UL << SCB_AIRCR_VECTCLRACTIVE_Pos) /*!< SCB AIRCR: VECTCLRACTIVE Mask */ /* SCB System Control Register Definitions */ #define SCB_SCR_SEVONPEND_Pos 4 /*!< SCB SCR: SEVONPEND Position */ #define SCB_SCR_SEVONPEND_Msk (1UL << SCB_SCR_SEVONPEND_Pos) /*!< SCB SCR: SEVONPEND Mask */ #define SCB_SCR_SLEEPDEEP_Pos 2 /*!< SCB SCR: SLEEPDEEP Position */ #define SCB_SCR_SLEEPDEEP_Msk (1UL << SCB_SCR_SLEEPDEEP_Pos) /*!< SCB SCR: SLEEPDEEP Mask */ #define SCB_SCR_SLEEPONEXIT_Pos 1 /*!< SCB SCR: SLEEPONEXIT Position */ #define SCB_SCR_SLEEPONEXIT_Msk (1UL << SCB_SCR_SLEEPONEXIT_Pos) /*!< SCB SCR: SLEEPONEXIT Mask */ /* SCB Configuration Control Register Definitions */ #define SCB_CCR_STKALIGN_Pos 9 /*!< SCB CCR: STKALIGN Position */ #define SCB_CCR_STKALIGN_Msk (1UL << SCB_CCR_STKALIGN_Pos) /*!< SCB CCR: STKALIGN Mask */ #define SCB_CCR_UNALIGN_TRP_Pos 3 /*!< SCB CCR: UNALIGN_TRP Position */ #define SCB_CCR_UNALIGN_TRP_Msk (1UL << SCB_CCR_UNALIGN_TRP_Pos) /*!< SCB CCR: UNALIGN_TRP Mask */ /* SCB System Handler Control and State Register Definitions */ #define SCB_SHCSR_SVCALLPENDED_Pos 15 /*!< SCB SHCSR: SVCALLPENDED Position */ #define SCB_SHCSR_SVCALLPENDED_Msk (1UL << SCB_SHCSR_SVCALLPENDED_Pos) /*!< SCB SHCSR: SVCALLPENDED Mask */ /*@} end of group CMSIS_SCB */ /** \ingroup CMSIS_core_register \defgroup CMSIS_SCnSCB System Controls not in SCB (SCnSCB) \brief Type definitions for the System Control and ID Register not in the SCB @{ */ /** \brief Structure type to access the System Control and ID Register not in the SCB. */ typedef struct { uint32_t RESERVED0[2]; __IO uint32_t ACTLR; /*!< Offset: 0x008 (R/W) Auxiliary Control Register */ } SCnSCB_Type; /* Auxiliary Control Register Definitions */ #define SCnSCB_ACTLR_DISMCYCINT_Pos 0 /*!< ACTLR: DISMCYCINT Position */ #define SCnSCB_ACTLR_DISMCYCINT_Msk (1UL /*<< SCnSCB_ACTLR_DISMCYCINT_Pos*/) /*!< ACTLR: DISMCYCINT Mask */ /*@} end of group CMSIS_SCnotSCB */ /** \ingroup CMSIS_core_register \defgroup CMSIS_SysTick System Tick Timer (SysTick) \brief Type definitions for the System Timer Registers. @{ */ /** \brief Structure type to access the System Timer (SysTick). */ typedef struct { __IO uint32_t CTRL; /*!< Offset: 0x000 (R/W) SysTick Control and Status Register */ __IO uint32_t LOAD; /*!< Offset: 0x004 (R/W) SysTick Reload Value Register */ __IO uint32_t VAL; /*!< Offset: 0x008 (R/W) SysTick Current Value Register */ __I uint32_t CALIB; /*!< Offset: 0x00C (R/ ) SysTick Calibration Register */ } SysTick_Type; /* SysTick Control / Status Register Definitions */ #define SysTick_CTRL_COUNTFLAG_Pos 16 /*!< SysTick CTRL: COUNTFLAG Position */ #define SysTick_CTRL_COUNTFLAG_Msk (1UL << SysTick_CTRL_COUNTFLAG_Pos) /*!< SysTick CTRL: COUNTFLAG Mask */ #define SysTick_CTRL_CLKSOURCE_Pos 2 /*!< SysTick CTRL: CLKSOURCE Position */ #define SysTick_CTRL_CLKSOURCE_Msk (1UL << SysTick_CTRL_CLKSOURCE_Pos) /*!< SysTick CTRL: CLKSOURCE Mask */ #define SysTick_CTRL_TICKINT_Pos 1 /*!< SysTick CTRL: TICKINT Position */ #define SysTick_CTRL_TICKINT_Msk (1UL << SysTick_CTRL_TICKINT_Pos) /*!< SysTick CTRL: TICKINT Mask */ #define SysTick_CTRL_ENABLE_Pos 0 /*!< SysTick CTRL: ENABLE Position */ #define SysTick_CTRL_ENABLE_Msk (1UL /*<< SysTick_CTRL_ENABLE_Pos*/) /*!< SysTick CTRL: ENABLE Mask */ /* SysTick Reload Register Definitions */ #define SysTick_LOAD_RELOAD_Pos 0 /*!< SysTick LOAD: RELOAD Position */ #define SysTick_LOAD_RELOAD_Msk (0xFFFFFFUL /*<< SysTick_LOAD_RELOAD_Pos*/) /*!< SysTick LOAD: RELOAD Mask */ /* SysTick Current Register Definitions */ #define SysTick_VAL_CURRENT_Pos 0 /*!< SysTick VAL: CURRENT Position */ #define SysTick_VAL_CURRENT_Msk (0xFFFFFFUL /*<< SysTick_VAL_CURRENT_Pos*/) /*!< SysTick VAL: CURRENT Mask */ /* SysTick Calibration Register Definitions */ #define SysTick_CALIB_NOREF_Pos 31 /*!< SysTick CALIB: NOREF Position */ #define SysTick_CALIB_NOREF_Msk (1UL << SysTick_CALIB_NOREF_Pos) /*!< SysTick CALIB: NOREF Mask */ #define SysTick_CALIB_SKEW_Pos 30 /*!< SysTick CALIB: SKEW Position */ #define SysTick_CALIB_SKEW_Msk (1UL << SysTick_CALIB_SKEW_Pos) /*!< SysTick CALIB: SKEW Mask */ #define SysTick_CALIB_TENMS_Pos 0 /*!< SysTick CALIB: TENMS Position */ #define SysTick_CALIB_TENMS_Msk (0xFFFFFFUL /*<< SysTick_CALIB_TENMS_Pos*/) /*!< SysTick CALIB: TENMS Mask */ /*@} end of group CMSIS_SysTick */ #if (__MPU_PRESENT == 1) /** \ingroup CMSIS_core_register \defgroup CMSIS_MPU Memory Protection Unit (MPU) \brief Type definitions for the Memory Protection Unit (MPU) @{ */ /** \brief Structure type to access the Memory Protection Unit (MPU). */ typedef struct { __I uint32_t TYPE; /*!< Offset: 0x000 (R/ ) MPU Type Register */ __IO uint32_t CTRL; /*!< Offset: 0x004 (R/W) MPU Control Register */ __IO uint32_t RNR; /*!< Offset: 0x008 (R/W) MPU Region RNRber Register */ __IO uint32_t RBAR; /*!< Offset: 0x00C (R/W) MPU Region Base Address Register */ __IO uint32_t RASR; /*!< Offset: 0x010 (R/W) MPU Region Attribute and Size Register */ } MPU_Type; /* MPU Type Register */ #define MPU_TYPE_IREGION_Pos 16 /*!< MPU TYPE: IREGION Position */ #define MPU_TYPE_IREGION_Msk (0xFFUL << MPU_TYPE_IREGION_Pos) /*!< MPU TYPE: IREGION Mask */ #define MPU_TYPE_DREGION_Pos 8 /*!< MPU TYPE: DREGION Position */ #define MPU_TYPE_DREGION_Msk (0xFFUL << MPU_TYPE_DREGION_Pos) /*!< MPU TYPE: DREGION Mask */ #define MPU_TYPE_SEPARATE_Pos 0 /*!< MPU TYPE: SEPARATE Position */ #define MPU_TYPE_SEPARATE_Msk (1UL /*<< MPU_TYPE_SEPARATE_Pos*/) /*!< MPU TYPE: SEPARATE Mask */ /* MPU Control Register */ #define MPU_CTRL_PRIVDEFENA_Pos 2 /*!< MPU CTRL: PRIVDEFENA Position */ #define MPU_CTRL_PRIVDEFENA_Msk (1UL << MPU_CTRL_PRIVDEFENA_Pos) /*!< MPU CTRL: PRIVDEFENA Mask */ #define MPU_CTRL_HFNMIENA_Pos 1 /*!< MPU CTRL: HFNMIENA Position */ #define MPU_CTRL_HFNMIENA_Msk (1UL << MPU_CTRL_HFNMIENA_Pos) /*!< MPU CTRL: HFNMIENA Mask */ #define MPU_CTRL_ENABLE_Pos 0 /*!< MPU CTRL: ENABLE Position */ #define MPU_CTRL_ENABLE_Msk (1UL /*<< MPU_CTRL_ENABLE_Pos*/) /*!< MPU CTRL: ENABLE Mask */ /* MPU Region Number Register */ #define MPU_RNR_REGION_Pos 0 /*!< MPU RNR: REGION Position */ #define MPU_RNR_REGION_Msk (0xFFUL /*<< MPU_RNR_REGION_Pos*/) /*!< MPU RNR: REGION Mask */ /* MPU Region Base Address Register */ #define MPU_RBAR_ADDR_Pos 8 /*!< MPU RBAR: ADDR Position */ #define MPU_RBAR_ADDR_Msk (0xFFFFFFUL << MPU_RBAR_ADDR_Pos) /*!< MPU RBAR: ADDR Mask */ #define MPU_RBAR_VALID_Pos 4 /*!< MPU RBAR: VALID Position */ #define MPU_RBAR_VALID_Msk (1UL << MPU_RBAR_VALID_Pos) /*!< MPU RBAR: VALID Mask */ #define MPU_RBAR_REGION_Pos 0 /*!< MPU RBAR: REGION Position */ #define MPU_RBAR_REGION_Msk (0xFUL /*<< MPU_RBAR_REGION_Pos*/) /*!< MPU RBAR: REGION Mask */ /* MPU Region Attribute and Size Register */ #define MPU_RASR_ATTRS_Pos 16 /*!< MPU RASR: MPU Region Attribute field Position */ #define MPU_RASR_ATTRS_Msk (0xFFFFUL << MPU_RASR_ATTRS_Pos) /*!< MPU RASR: MPU Region Attribute field Mask */ #define MPU_RASR_XN_Pos 28 /*!< MPU RASR: ATTRS.XN Position */ #define MPU_RASR_XN_Msk (1UL << MPU_RASR_XN_Pos) /*!< MPU RASR: ATTRS.XN Mask */ #define MPU_RASR_AP_Pos 24 /*!< MPU RASR: ATTRS.AP Position */ #define MPU_RASR_AP_Msk (0x7UL << MPU_RASR_AP_Pos) /*!< MPU RASR: ATTRS.AP Mask */ #define MPU_RASR_TEX_Pos 19 /*!< MPU RASR: ATTRS.TEX Position */ #define MPU_RASR_TEX_Msk (0x7UL << MPU_RASR_TEX_Pos) /*!< MPU RASR: ATTRS.TEX Mask */ #define MPU_RASR_S_Pos 18 /*!< MPU RASR: ATTRS.S Position */ #define MPU_RASR_S_Msk (1UL << MPU_RASR_S_Pos) /*!< MPU RASR: ATTRS.S Mask */ #define MPU_RASR_C_Pos 17 /*!< MPU RASR: ATTRS.C Position */ #define MPU_RASR_C_Msk (1UL << MPU_RASR_C_Pos) /*!< MPU RASR: ATTRS.C Mask */ #define MPU_RASR_B_Pos 16 /*!< MPU RASR: ATTRS.B Position */ #define MPU_RASR_B_Msk (1UL << MPU_RASR_B_Pos) /*!< MPU RASR: ATTRS.B Mask */ #define MPU_RASR_SRD_Pos 8 /*!< MPU RASR: Sub-Region Disable Position */ #define MPU_RASR_SRD_Msk (0xFFUL << MPU_RASR_SRD_Pos) /*!< MPU RASR: Sub-Region Disable Mask */ #define MPU_RASR_SIZE_Pos 1 /*!< MPU RASR: Region Size Field Position */ #define MPU_RASR_SIZE_Msk (0x1FUL << MPU_RASR_SIZE_Pos) /*!< MPU RASR: Region Size Field Mask */ #define MPU_RASR_ENABLE_Pos 0 /*!< MPU RASR: Region enable bit Position */ #define MPU_RASR_ENABLE_Msk (1UL /*<< MPU_RASR_ENABLE_Pos*/) /*!< MPU RASR: Region enable bit Disable Mask */ /*@} end of group CMSIS_MPU */ #endif /** \ingroup CMSIS_core_register \defgroup CMSIS_CoreDebug Core Debug Registers (CoreDebug) \brief SC000 Core Debug Registers (DCB registers, SHCSR, and DFSR) are only accessible over DAP and not via processor. Therefore they are not covered by the Cortex-M0 header file. @{ */ /*@} end of group CMSIS_CoreDebug */ /** \ingroup CMSIS_core_register \defgroup CMSIS_core_base Core Definitions \brief Definitions for base addresses, unions, and structures. @{ */ /* Memory mapping of SC000 Hardware */ #define SCS_BASE (0xE000E000UL) /*!< System Control Space Base Address */ #define SysTick_BASE (SCS_BASE + 0x0010UL) /*!< SysTick Base Address */ #define NVIC_BASE (SCS_BASE + 0x0100UL) /*!< NVIC Base Address */ #define SCB_BASE (SCS_BASE + 0x0D00UL) /*!< System Control Block Base Address */ #define SCnSCB ((SCnSCB_Type *) SCS_BASE ) /*!< System control Register not in SCB */ #define SCB ((SCB_Type *) SCB_BASE ) /*!< SCB configuration struct */ #define SysTick ((SysTick_Type *) SysTick_BASE ) /*!< SysTick configuration struct */ #define NVIC ((NVIC_Type *) NVIC_BASE ) /*!< NVIC configuration struct */ #if (__MPU_PRESENT == 1) #define MPU_BASE (SCS_BASE + 0x0D90UL) /*!< Memory Protection Unit */ #define MPU ((MPU_Type *) MPU_BASE ) /*!< Memory Protection Unit */ #endif /*@} */ /******************************************************************************* * Hardware Abstraction Layer Core Function Interface contains: - Core NVIC Functions - Core SysTick Functions - Core Register Access Functions ******************************************************************************/ /** \defgroup CMSIS_Core_FunctionInterface Functions and Instructions Reference */ /* ########################## NVIC functions #################################### */ /** \ingroup CMSIS_Core_FunctionInterface \defgroup CMSIS_Core_NVICFunctions NVIC Functions \brief Functions that manage interrupts and exceptions via the NVIC. @{ */ /* Interrupt Priorities are WORD accessible only under ARMv6M */ /* The following MACROS handle generation of the register offset and byte masks */ #define _BIT_SHIFT(IRQn) ( ((((uint32_t)(int32_t)(IRQn)) ) & 0x03UL) * 8UL) #define _SHP_IDX(IRQn) ( (((((uint32_t)(int32_t)(IRQn)) & 0x0FUL)-8UL) >> 2UL) ) #define _IP_IDX(IRQn) ( (((uint32_t)(int32_t)(IRQn)) >> 2UL) ) /** \brief Enable External Interrupt The function enables a device-specific interrupt in the NVIC interrupt controller. \param [in] IRQn External interrupt number. Value cannot be negative. */ __STATIC_INLINE void NVIC_EnableIRQ(IRQn_Type IRQn) { NVIC->ISER[0] = (uint32_t)(1UL << (((uint32_t)(int32_t)IRQn) & 0x1FUL)); } /** \brief Disable External Interrupt The function disables a device-specific interrupt in the NVIC interrupt controller. \param [in] IRQn External interrupt number. Value cannot be negative. */ __STATIC_INLINE void NVIC_DisableIRQ(IRQn_Type IRQn) { NVIC->ICER[0] = (uint32_t)(1UL << (((uint32_t)(int32_t)IRQn) & 0x1FUL)); } /** \brief Get Pending Interrupt The function reads the pending register in the NVIC and returns the pending bit for the specified interrupt. \param [in] IRQn Interrupt number. \return 0 Interrupt status is not pending. \return 1 Interrupt status is pending. */ __STATIC_INLINE uint32_t NVIC_GetPendingIRQ(IRQn_Type IRQn) { return((uint32_t)(((NVIC->ISPR[0] & (1UL << (((uint32_t)(int32_t)IRQn) & 0x1FUL))) != 0UL) ? 1UL : 0UL)); } /** \brief Set Pending Interrupt The function sets the pending bit of an external interrupt. \param [in] IRQn Interrupt number. Value cannot be negative. */ __STATIC_INLINE void NVIC_SetPendingIRQ(IRQn_Type IRQn) { NVIC->ISPR[0] = (uint32_t)(1UL << (((uint32_t)(int32_t)IRQn) & 0x1FUL)); } /** \brief Clear Pending Interrupt The function clears the pending bit of an external interrupt. \param [in] IRQn External interrupt number. Value cannot be negative. */ __STATIC_INLINE void NVIC_ClearPendingIRQ(IRQn_Type IRQn) { NVIC->ICPR[0] = (uint32_t)(1UL << (((uint32_t)(int32_t)IRQn) & 0x1FUL)); } /** \brief Set Interrupt Priority The function sets the priority of an interrupt. \note The priority cannot be set for every core interrupt. \param [in] IRQn Interrupt number. \param [in] priority Priority to set. */ __STATIC_INLINE void NVIC_SetPriority(IRQn_Type IRQn, uint32_t priority) { if((int32_t)(IRQn) < 0) { SCB->SHP[_SHP_IDX(IRQn)] = ((uint32_t)(SCB->SHP[_SHP_IDX(IRQn)] & ~(0xFFUL << _BIT_SHIFT(IRQn))) | (((priority << (8 - __NVIC_PRIO_BITS)) & (uint32_t)0xFFUL) << _BIT_SHIFT(IRQn))); } else { NVIC->IP[_IP_IDX(IRQn)] = ((uint32_t)(NVIC->IP[_IP_IDX(IRQn)] & ~(0xFFUL << _BIT_SHIFT(IRQn))) | (((priority << (8 - __NVIC_PRIO_BITS)) & (uint32_t)0xFFUL) << _BIT_SHIFT(IRQn))); } } /** \brief Get Interrupt Priority The function reads the priority of an interrupt. The interrupt number can be positive to specify an external (device specific) interrupt, or negative to specify an internal (core) interrupt. \param [in] IRQn Interrupt number. \return Interrupt Priority. Value is aligned automatically to the implemented priority bits of the microcontroller. */ __STATIC_INLINE uint32_t NVIC_GetPriority(IRQn_Type IRQn) { if((int32_t)(IRQn) < 0) { return((uint32_t)(((SCB->SHP[_SHP_IDX(IRQn)] >> _BIT_SHIFT(IRQn) ) & (uint32_t)0xFFUL) >> (8 - __NVIC_PRIO_BITS))); } else { return((uint32_t)(((NVIC->IP[ _IP_IDX(IRQn)] >> _BIT_SHIFT(IRQn) ) & (uint32_t)0xFFUL) >> (8 - __NVIC_PRIO_BITS))); } } /** \brief System Reset The function initiates a system reset request to reset the MCU. */ __STATIC_INLINE void NVIC_SystemReset(void) { __DSB(); /* Ensure all outstanding memory accesses included buffered write are completed before reset */ SCB->AIRCR = ((0x5FAUL << SCB_AIRCR_VECTKEY_Pos) | SCB_AIRCR_SYSRESETREQ_Msk); __DSB(); /* Ensure completion of memory access */ while(1) { __NOP(); } /* wait until reset */ } /*@} end of CMSIS_Core_NVICFunctions */ /* ################################## SysTick function ############################################ */ /** \ingroup CMSIS_Core_FunctionInterface \defgroup CMSIS_Core_SysTickFunctions SysTick Functions \brief Functions that configure the System. @{ */ #if (__Vendor_SysTickConfig == 0) /** \brief System Tick Configuration The function initializes the System Timer and its interrupt, and starts the System Tick Timer. Counter is in free running mode to generate periodic interrupts. \param [in] ticks Number of ticks between two interrupts. \return 0 Function succeeded. \return 1 Function failed. \note When the variable __Vendor_SysTickConfig is set to 1, then the function SysTick_Config is not included. In this case, the file device.h must contain a vendor-specific implementation of this function. */ __STATIC_INLINE uint32_t SysTick_Config(uint32_t ticks) { if ((ticks - 1UL) > SysTick_LOAD_RELOAD_Msk) {return (1UL);} /* Reload value impossible */ SysTick->LOAD = (uint32_t)(ticks - 1UL); /* set reload register */ NVIC_SetPriority (SysTick_IRQn, (1UL << __NVIC_PRIO_BITS) - 1UL); /* set Priority for Systick Interrupt */ SysTick->VAL = 0UL; /* Load the SysTick Counter Value */ SysTick->CTRL = SysTick_CTRL_CLKSOURCE_Msk | SysTick_CTRL_TICKINT_Msk | SysTick_CTRL_ENABLE_Msk; /* Enable SysTick IRQ and SysTick Timer */ return (0UL); /* Function successful */ } #endif /*@} end of CMSIS_Core_SysTickFunctions */ #ifdef __cplusplus } #endif #endif /* __CORE_SC000_H_DEPENDANT */ #endif /* __CMSIS_GENERIC */ ================================================ FILE: Zelig/mbed/TARGET_NUCLEO_F091RC/core_sc300.h ================================================ /**************************************************************************//** * @file core_sc300.h * @brief CMSIS SC300 Core Peripheral Access Layer Header File * @version V4.10 * @date 18. March 2015 * * @note * ******************************************************************************/ /* Copyright (c) 2009 - 2015 ARM LIMITED All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: - Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. - Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. - Neither the name of ARM 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 COPYRIGHT HOLDERS AND 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. ---------------------------------------------------------------------------*/ #if defined ( __ICCARM__ ) #pragma system_include /* treat file as system include file for MISRA check */ #endif #ifndef __CORE_SC300_H_GENERIC #define __CORE_SC300_H_GENERIC #ifdef __cplusplus extern "C" { #endif /** \page CMSIS_MISRA_Exceptions MISRA-C:2004 Compliance Exceptions CMSIS violates the following MISRA-C:2004 rules: \li Required Rule 8.5, object/function definition in header file.
Function definitions in header files are used to allow 'inlining'. \li Required Rule 18.4, declaration of union type or object of union type: '{...}'.
Unions are used for effective representation of core registers. \li Advisory Rule 19.7, Function-like macro defined.
Function-like macros are used to allow more efficient code. */ /******************************************************************************* * CMSIS definitions ******************************************************************************/ /** \ingroup SC3000 @{ */ /* CMSIS SC300 definitions */ #define __SC300_CMSIS_VERSION_MAIN (0x04) /*!< [31:16] CMSIS HAL main version */ #define __SC300_CMSIS_VERSION_SUB (0x00) /*!< [15:0] CMSIS HAL sub version */ #define __SC300_CMSIS_VERSION ((__SC300_CMSIS_VERSION_MAIN << 16) | \ __SC300_CMSIS_VERSION_SUB ) /*!< CMSIS HAL version number */ #define __CORTEX_SC (300) /*!< Cortex secure core */ #if defined ( __CC_ARM ) #define __ASM __asm /*!< asm keyword for ARM Compiler */ #define __INLINE __inline /*!< inline keyword for ARM Compiler */ #define __STATIC_INLINE static __inline #elif defined ( __GNUC__ ) #define __ASM __asm /*!< asm keyword for GNU Compiler */ #define __INLINE inline /*!< inline keyword for GNU Compiler */ #define __STATIC_INLINE static inline #elif defined ( __ICCARM__ ) #define __ASM __asm /*!< asm keyword for IAR Compiler */ #define __INLINE inline /*!< inline keyword for IAR Compiler. Only available in High optimization mode! */ #define __STATIC_INLINE static inline #elif defined ( __TMS470__ ) #define __ASM __asm /*!< asm keyword for TI CCS Compiler */ #define __STATIC_INLINE static inline #elif defined ( __TASKING__ ) #define __ASM __asm /*!< asm keyword for TASKING Compiler */ #define __INLINE inline /*!< inline keyword for TASKING Compiler */ #define __STATIC_INLINE static inline #elif defined ( __CSMC__ ) #define __packed #define __ASM _asm /*!< asm keyword for COSMIC Compiler */ #define __INLINE inline /*use -pc99 on compile line !< inline keyword for COSMIC Compiler */ #define __STATIC_INLINE static inline #endif /** __FPU_USED indicates whether an FPU is used or not. This core does not support an FPU at all */ #define __FPU_USED 0 #if defined ( __CC_ARM ) #if defined __TARGET_FPU_VFP #warning "Compiler generates FPU instructions for a device without an FPU (check __FPU_PRESENT)" #endif #elif defined ( __GNUC__ ) #if defined (__VFP_FP__) && !defined(__SOFTFP__) #warning "Compiler generates FPU instructions for a device without an FPU (check __FPU_PRESENT)" #endif #elif defined ( __ICCARM__ ) #if defined __ARMVFP__ #warning "Compiler generates FPU instructions for a device without an FPU (check __FPU_PRESENT)" #endif #elif defined ( __TMS470__ ) #if defined __TI__VFP_SUPPORT____ #warning "Compiler generates FPU instructions for a device without an FPU (check __FPU_PRESENT)" #endif #elif defined ( __TASKING__ ) #if defined __FPU_VFP__ #error "Compiler generates FPU instructions for a device without an FPU (check __FPU_PRESENT)" #endif #elif defined ( __CSMC__ ) /* Cosmic */ #if ( __CSMC__ & 0x400) // FPU present for parser #error "Compiler generates FPU instructions for a device without an FPU (check __FPU_PRESENT)" #endif #endif #include /* standard types definitions */ #include /* Core Instruction Access */ #include /* Core Function Access */ #ifdef __cplusplus } #endif #endif /* __CORE_SC300_H_GENERIC */ #ifndef __CMSIS_GENERIC #ifndef __CORE_SC300_H_DEPENDANT #define __CORE_SC300_H_DEPENDANT #ifdef __cplusplus extern "C" { #endif /* check device defines and use defaults */ #if defined __CHECK_DEVICE_DEFINES #ifndef __SC300_REV #define __SC300_REV 0x0000 #warning "__SC300_REV not defined in device header file; using default!" #endif #ifndef __MPU_PRESENT #define __MPU_PRESENT 0 #warning "__MPU_PRESENT not defined in device header file; using default!" #endif #ifndef __NVIC_PRIO_BITS #define __NVIC_PRIO_BITS 4 #warning "__NVIC_PRIO_BITS not defined in device header file; using default!" #endif #ifndef __Vendor_SysTickConfig #define __Vendor_SysTickConfig 0 #warning "__Vendor_SysTickConfig not defined in device header file; using default!" #endif #endif /* IO definitions (access restrictions to peripheral registers) */ /** \defgroup CMSIS_glob_defs CMSIS Global Defines IO Type Qualifiers are used \li to specify the access to peripheral variables. \li for automatic generation of peripheral register debug information. */ #ifdef __cplusplus #define __I volatile /*!< Defines 'read only' permissions */ #else #define __I volatile const /*!< Defines 'read only' permissions */ #endif #define __O volatile /*!< Defines 'write only' permissions */ #define __IO volatile /*!< Defines 'read / write' permissions */ /*@} end of group SC300 */ /******************************************************************************* * Register Abstraction Core Register contain: - Core Register - Core NVIC Register - Core SCB Register - Core SysTick Register - Core Debug Register - Core MPU Register ******************************************************************************/ /** \defgroup CMSIS_core_register Defines and Type Definitions \brief Type definitions and defines for Cortex-M processor based devices. */ /** \ingroup CMSIS_core_register \defgroup CMSIS_CORE Status and Control Registers \brief Core Register type definitions. @{ */ /** \brief Union type to access the Application Program Status Register (APSR). */ typedef union { struct { uint32_t _reserved0:27; /*!< bit: 0..26 Reserved */ uint32_t Q:1; /*!< bit: 27 Saturation condition flag */ uint32_t V:1; /*!< bit: 28 Overflow condition code flag */ uint32_t C:1; /*!< bit: 29 Carry condition code flag */ uint32_t Z:1; /*!< bit: 30 Zero condition code flag */ uint32_t N:1; /*!< bit: 31 Negative condition code flag */ } b; /*!< Structure used for bit access */ uint32_t w; /*!< Type used for word access */ } APSR_Type; /* APSR Register Definitions */ #define APSR_N_Pos 31 /*!< APSR: N Position */ #define APSR_N_Msk (1UL << APSR_N_Pos) /*!< APSR: N Mask */ #define APSR_Z_Pos 30 /*!< APSR: Z Position */ #define APSR_Z_Msk (1UL << APSR_Z_Pos) /*!< APSR: Z Mask */ #define APSR_C_Pos 29 /*!< APSR: C Position */ #define APSR_C_Msk (1UL << APSR_C_Pos) /*!< APSR: C Mask */ #define APSR_V_Pos 28 /*!< APSR: V Position */ #define APSR_V_Msk (1UL << APSR_V_Pos) /*!< APSR: V Mask */ #define APSR_Q_Pos 27 /*!< APSR: Q Position */ #define APSR_Q_Msk (1UL << APSR_Q_Pos) /*!< APSR: Q Mask */ /** \brief Union type to access the Interrupt Program Status Register (IPSR). */ typedef union { struct { uint32_t ISR:9; /*!< bit: 0.. 8 Exception number */ uint32_t _reserved0:23; /*!< bit: 9..31 Reserved */ } b; /*!< Structure used for bit access */ uint32_t w; /*!< Type used for word access */ } IPSR_Type; /* IPSR Register Definitions */ #define IPSR_ISR_Pos 0 /*!< IPSR: ISR Position */ #define IPSR_ISR_Msk (0x1FFUL /*<< IPSR_ISR_Pos*/) /*!< IPSR: ISR Mask */ /** \brief Union type to access the Special-Purpose Program Status Registers (xPSR). */ typedef union { struct { uint32_t ISR:9; /*!< bit: 0.. 8 Exception number */ uint32_t _reserved0:15; /*!< bit: 9..23 Reserved */ uint32_t T:1; /*!< bit: 24 Thumb bit (read 0) */ uint32_t IT:2; /*!< bit: 25..26 saved IT state (read 0) */ uint32_t Q:1; /*!< bit: 27 Saturation condition flag */ uint32_t V:1; /*!< bit: 28 Overflow condition code flag */ uint32_t C:1; /*!< bit: 29 Carry condition code flag */ uint32_t Z:1; /*!< bit: 30 Zero condition code flag */ uint32_t N:1; /*!< bit: 31 Negative condition code flag */ } b; /*!< Structure used for bit access */ uint32_t w; /*!< Type used for word access */ } xPSR_Type; /* xPSR Register Definitions */ #define xPSR_N_Pos 31 /*!< xPSR: N Position */ #define xPSR_N_Msk (1UL << xPSR_N_Pos) /*!< xPSR: N Mask */ #define xPSR_Z_Pos 30 /*!< xPSR: Z Position */ #define xPSR_Z_Msk (1UL << xPSR_Z_Pos) /*!< xPSR: Z Mask */ #define xPSR_C_Pos 29 /*!< xPSR: C Position */ #define xPSR_C_Msk (1UL << xPSR_C_Pos) /*!< xPSR: C Mask */ #define xPSR_V_Pos 28 /*!< xPSR: V Position */ #define xPSR_V_Msk (1UL << xPSR_V_Pos) /*!< xPSR: V Mask */ #define xPSR_Q_Pos 27 /*!< xPSR: Q Position */ #define xPSR_Q_Msk (1UL << xPSR_Q_Pos) /*!< xPSR: Q Mask */ #define xPSR_IT_Pos 25 /*!< xPSR: IT Position */ #define xPSR_IT_Msk (3UL << xPSR_IT_Pos) /*!< xPSR: IT Mask */ #define xPSR_T_Pos 24 /*!< xPSR: T Position */ #define xPSR_T_Msk (1UL << xPSR_T_Pos) /*!< xPSR: T Mask */ #define xPSR_ISR_Pos 0 /*!< xPSR: ISR Position */ #define xPSR_ISR_Msk (0x1FFUL /*<< xPSR_ISR_Pos*/) /*!< xPSR: ISR Mask */ /** \brief Union type to access the Control Registers (CONTROL). */ typedef union { struct { uint32_t nPRIV:1; /*!< bit: 0 Execution privilege in Thread mode */ uint32_t SPSEL:1; /*!< bit: 1 Stack to be used */ uint32_t _reserved1:30; /*!< bit: 2..31 Reserved */ } b; /*!< Structure used for bit access */ uint32_t w; /*!< Type used for word access */ } CONTROL_Type; /* CONTROL Register Definitions */ #define CONTROL_SPSEL_Pos 1 /*!< CONTROL: SPSEL Position */ #define CONTROL_SPSEL_Msk (1UL << CONTROL_SPSEL_Pos) /*!< CONTROL: SPSEL Mask */ #define CONTROL_nPRIV_Pos 0 /*!< CONTROL: nPRIV Position */ #define CONTROL_nPRIV_Msk (1UL /*<< CONTROL_nPRIV_Pos*/) /*!< CONTROL: nPRIV Mask */ /*@} end of group CMSIS_CORE */ /** \ingroup CMSIS_core_register \defgroup CMSIS_NVIC Nested Vectored Interrupt Controller (NVIC) \brief Type definitions for the NVIC Registers @{ */ /** \brief Structure type to access the Nested Vectored Interrupt Controller (NVIC). */ typedef struct { __IO uint32_t ISER[8]; /*!< Offset: 0x000 (R/W) Interrupt Set Enable Register */ uint32_t RESERVED0[24]; __IO uint32_t ICER[8]; /*!< Offset: 0x080 (R/W) Interrupt Clear Enable Register */ uint32_t RSERVED1[24]; __IO uint32_t ISPR[8]; /*!< Offset: 0x100 (R/W) Interrupt Set Pending Register */ uint32_t RESERVED2[24]; __IO uint32_t ICPR[8]; /*!< Offset: 0x180 (R/W) Interrupt Clear Pending Register */ uint32_t RESERVED3[24]; __IO uint32_t IABR[8]; /*!< Offset: 0x200 (R/W) Interrupt Active bit Register */ uint32_t RESERVED4[56]; __IO uint8_t IP[240]; /*!< Offset: 0x300 (R/W) Interrupt Priority Register (8Bit wide) */ uint32_t RESERVED5[644]; __O uint32_t STIR; /*!< Offset: 0xE00 ( /W) Software Trigger Interrupt Register */ } NVIC_Type; /* Software Triggered Interrupt Register Definitions */ #define NVIC_STIR_INTID_Pos 0 /*!< STIR: INTLINESNUM Position */ #define NVIC_STIR_INTID_Msk (0x1FFUL /*<< NVIC_STIR_INTID_Pos*/) /*!< STIR: INTLINESNUM Mask */ /*@} end of group CMSIS_NVIC */ /** \ingroup CMSIS_core_register \defgroup CMSIS_SCB System Control Block (SCB) \brief Type definitions for the System Control Block Registers @{ */ /** \brief Structure type to access the System Control Block (SCB). */ typedef struct { __I uint32_t CPUID; /*!< Offset: 0x000 (R/ ) CPUID Base Register */ __IO uint32_t ICSR; /*!< Offset: 0x004 (R/W) Interrupt Control and State Register */ __IO uint32_t VTOR; /*!< Offset: 0x008 (R/W) Vector Table Offset Register */ __IO uint32_t AIRCR; /*!< Offset: 0x00C (R/W) Application Interrupt and Reset Control Register */ __IO uint32_t SCR; /*!< Offset: 0x010 (R/W) System Control Register */ __IO uint32_t CCR; /*!< Offset: 0x014 (R/W) Configuration Control Register */ __IO uint8_t SHP[12]; /*!< Offset: 0x018 (R/W) System Handlers Priority Registers (4-7, 8-11, 12-15) */ __IO uint32_t SHCSR; /*!< Offset: 0x024 (R/W) System Handler Control and State Register */ __IO uint32_t CFSR; /*!< Offset: 0x028 (R/W) Configurable Fault Status Register */ __IO uint32_t HFSR; /*!< Offset: 0x02C (R/W) HardFault Status Register */ __IO uint32_t DFSR; /*!< Offset: 0x030 (R/W) Debug Fault Status Register */ __IO uint32_t MMFAR; /*!< Offset: 0x034 (R/W) MemManage Fault Address Register */ __IO uint32_t BFAR; /*!< Offset: 0x038 (R/W) BusFault Address Register */ __IO uint32_t AFSR; /*!< Offset: 0x03C (R/W) Auxiliary Fault Status Register */ __I uint32_t PFR[2]; /*!< Offset: 0x040 (R/ ) Processor Feature Register */ __I uint32_t DFR; /*!< Offset: 0x048 (R/ ) Debug Feature Register */ __I uint32_t ADR; /*!< Offset: 0x04C (R/ ) Auxiliary Feature Register */ __I uint32_t MMFR[4]; /*!< Offset: 0x050 (R/ ) Memory Model Feature Register */ __I uint32_t ISAR[5]; /*!< Offset: 0x060 (R/ ) Instruction Set Attributes Register */ uint32_t RESERVED0[5]; __IO uint32_t CPACR; /*!< Offset: 0x088 (R/W) Coprocessor Access Control Register */ uint32_t RESERVED1[129]; __IO uint32_t SFCR; /*!< Offset: 0x290 (R/W) Security Features Control Register */ } SCB_Type; /* SCB CPUID Register Definitions */ #define SCB_CPUID_IMPLEMENTER_Pos 24 /*!< SCB CPUID: IMPLEMENTER Position */ #define SCB_CPUID_IMPLEMENTER_Msk (0xFFUL << SCB_CPUID_IMPLEMENTER_Pos) /*!< SCB CPUID: IMPLEMENTER Mask */ #define SCB_CPUID_VARIANT_Pos 20 /*!< SCB CPUID: VARIANT Position */ #define SCB_CPUID_VARIANT_Msk (0xFUL << SCB_CPUID_VARIANT_Pos) /*!< SCB CPUID: VARIANT Mask */ #define SCB_CPUID_ARCHITECTURE_Pos 16 /*!< SCB CPUID: ARCHITECTURE Position */ #define SCB_CPUID_ARCHITECTURE_Msk (0xFUL << SCB_CPUID_ARCHITECTURE_Pos) /*!< SCB CPUID: ARCHITECTURE Mask */ #define SCB_CPUID_PARTNO_Pos 4 /*!< SCB CPUID: PARTNO Position */ #define SCB_CPUID_PARTNO_Msk (0xFFFUL << SCB_CPUID_PARTNO_Pos) /*!< SCB CPUID: PARTNO Mask */ #define SCB_CPUID_REVISION_Pos 0 /*!< SCB CPUID: REVISION Position */ #define SCB_CPUID_REVISION_Msk (0xFUL /*<< SCB_CPUID_REVISION_Pos*/) /*!< SCB CPUID: REVISION Mask */ /* SCB Interrupt Control State Register Definitions */ #define SCB_ICSR_NMIPENDSET_Pos 31 /*!< SCB ICSR: NMIPENDSET Position */ #define SCB_ICSR_NMIPENDSET_Msk (1UL << SCB_ICSR_NMIPENDSET_Pos) /*!< SCB ICSR: NMIPENDSET Mask */ #define SCB_ICSR_PENDSVSET_Pos 28 /*!< SCB ICSR: PENDSVSET Position */ #define SCB_ICSR_PENDSVSET_Msk (1UL << SCB_ICSR_PENDSVSET_Pos) /*!< SCB ICSR: PENDSVSET Mask */ #define SCB_ICSR_PENDSVCLR_Pos 27 /*!< SCB ICSR: PENDSVCLR Position */ #define SCB_ICSR_PENDSVCLR_Msk (1UL << SCB_ICSR_PENDSVCLR_Pos) /*!< SCB ICSR: PENDSVCLR Mask */ #define SCB_ICSR_PENDSTSET_Pos 26 /*!< SCB ICSR: PENDSTSET Position */ #define SCB_ICSR_PENDSTSET_Msk (1UL << SCB_ICSR_PENDSTSET_Pos) /*!< SCB ICSR: PENDSTSET Mask */ #define SCB_ICSR_PENDSTCLR_Pos 25 /*!< SCB ICSR: PENDSTCLR Position */ #define SCB_ICSR_PENDSTCLR_Msk (1UL << SCB_ICSR_PENDSTCLR_Pos) /*!< SCB ICSR: PENDSTCLR Mask */ #define SCB_ICSR_ISRPREEMPT_Pos 23 /*!< SCB ICSR: ISRPREEMPT Position */ #define SCB_ICSR_ISRPREEMPT_Msk (1UL << SCB_ICSR_ISRPREEMPT_Pos) /*!< SCB ICSR: ISRPREEMPT Mask */ #define SCB_ICSR_ISRPENDING_Pos 22 /*!< SCB ICSR: ISRPENDING Position */ #define SCB_ICSR_ISRPENDING_Msk (1UL << SCB_ICSR_ISRPENDING_Pos) /*!< SCB ICSR: ISRPENDING Mask */ #define SCB_ICSR_VECTPENDING_Pos 12 /*!< SCB ICSR: VECTPENDING Position */ #define SCB_ICSR_VECTPENDING_Msk (0x1FFUL << SCB_ICSR_VECTPENDING_Pos) /*!< SCB ICSR: VECTPENDING Mask */ #define SCB_ICSR_RETTOBASE_Pos 11 /*!< SCB ICSR: RETTOBASE Position */ #define SCB_ICSR_RETTOBASE_Msk (1UL << SCB_ICSR_RETTOBASE_Pos) /*!< SCB ICSR: RETTOBASE Mask */ #define SCB_ICSR_VECTACTIVE_Pos 0 /*!< SCB ICSR: VECTACTIVE Position */ #define SCB_ICSR_VECTACTIVE_Msk (0x1FFUL /*<< SCB_ICSR_VECTACTIVE_Pos*/) /*!< SCB ICSR: VECTACTIVE Mask */ /* SCB Vector Table Offset Register Definitions */ #define SCB_VTOR_TBLBASE_Pos 29 /*!< SCB VTOR: TBLBASE Position */ #define SCB_VTOR_TBLBASE_Msk (1UL << SCB_VTOR_TBLBASE_Pos) /*!< SCB VTOR: TBLBASE Mask */ #define SCB_VTOR_TBLOFF_Pos 7 /*!< SCB VTOR: TBLOFF Position */ #define SCB_VTOR_TBLOFF_Msk (0x3FFFFFUL << SCB_VTOR_TBLOFF_Pos) /*!< SCB VTOR: TBLOFF Mask */ /* SCB Application Interrupt and Reset Control Register Definitions */ #define SCB_AIRCR_VECTKEY_Pos 16 /*!< SCB AIRCR: VECTKEY Position */ #define SCB_AIRCR_VECTKEY_Msk (0xFFFFUL << SCB_AIRCR_VECTKEY_Pos) /*!< SCB AIRCR: VECTKEY Mask */ #define SCB_AIRCR_VECTKEYSTAT_Pos 16 /*!< SCB AIRCR: VECTKEYSTAT Position */ #define SCB_AIRCR_VECTKEYSTAT_Msk (0xFFFFUL << SCB_AIRCR_VECTKEYSTAT_Pos) /*!< SCB AIRCR: VECTKEYSTAT Mask */ #define SCB_AIRCR_ENDIANESS_Pos 15 /*!< SCB AIRCR: ENDIANESS Position */ #define SCB_AIRCR_ENDIANESS_Msk (1UL << SCB_AIRCR_ENDIANESS_Pos) /*!< SCB AIRCR: ENDIANESS Mask */ #define SCB_AIRCR_PRIGROUP_Pos 8 /*!< SCB AIRCR: PRIGROUP Position */ #define SCB_AIRCR_PRIGROUP_Msk (7UL << SCB_AIRCR_PRIGROUP_Pos) /*!< SCB AIRCR: PRIGROUP Mask */ #define SCB_AIRCR_SYSRESETREQ_Pos 2 /*!< SCB AIRCR: SYSRESETREQ Position */ #define SCB_AIRCR_SYSRESETREQ_Msk (1UL << SCB_AIRCR_SYSRESETREQ_Pos) /*!< SCB AIRCR: SYSRESETREQ Mask */ #define SCB_AIRCR_VECTCLRACTIVE_Pos 1 /*!< SCB AIRCR: VECTCLRACTIVE Position */ #define SCB_AIRCR_VECTCLRACTIVE_Msk (1UL << SCB_AIRCR_VECTCLRACTIVE_Pos) /*!< SCB AIRCR: VECTCLRACTIVE Mask */ #define SCB_AIRCR_VECTRESET_Pos 0 /*!< SCB AIRCR: VECTRESET Position */ #define SCB_AIRCR_VECTRESET_Msk (1UL /*<< SCB_AIRCR_VECTRESET_Pos*/) /*!< SCB AIRCR: VECTRESET Mask */ /* SCB System Control Register Definitions */ #define SCB_SCR_SEVONPEND_Pos 4 /*!< SCB SCR: SEVONPEND Position */ #define SCB_SCR_SEVONPEND_Msk (1UL << SCB_SCR_SEVONPEND_Pos) /*!< SCB SCR: SEVONPEND Mask */ #define SCB_SCR_SLEEPDEEP_Pos 2 /*!< SCB SCR: SLEEPDEEP Position */ #define SCB_SCR_SLEEPDEEP_Msk (1UL << SCB_SCR_SLEEPDEEP_Pos) /*!< SCB SCR: SLEEPDEEP Mask */ #define SCB_SCR_SLEEPONEXIT_Pos 1 /*!< SCB SCR: SLEEPONEXIT Position */ #define SCB_SCR_SLEEPONEXIT_Msk (1UL << SCB_SCR_SLEEPONEXIT_Pos) /*!< SCB SCR: SLEEPONEXIT Mask */ /* SCB Configuration Control Register Definitions */ #define SCB_CCR_STKALIGN_Pos 9 /*!< SCB CCR: STKALIGN Position */ #define SCB_CCR_STKALIGN_Msk (1UL << SCB_CCR_STKALIGN_Pos) /*!< SCB CCR: STKALIGN Mask */ #define SCB_CCR_BFHFNMIGN_Pos 8 /*!< SCB CCR: BFHFNMIGN Position */ #define SCB_CCR_BFHFNMIGN_Msk (1UL << SCB_CCR_BFHFNMIGN_Pos) /*!< SCB CCR: BFHFNMIGN Mask */ #define SCB_CCR_DIV_0_TRP_Pos 4 /*!< SCB CCR: DIV_0_TRP Position */ #define SCB_CCR_DIV_0_TRP_Msk (1UL << SCB_CCR_DIV_0_TRP_Pos) /*!< SCB CCR: DIV_0_TRP Mask */ #define SCB_CCR_UNALIGN_TRP_Pos 3 /*!< SCB CCR: UNALIGN_TRP Position */ #define SCB_CCR_UNALIGN_TRP_Msk (1UL << SCB_CCR_UNALIGN_TRP_Pos) /*!< SCB CCR: UNALIGN_TRP Mask */ #define SCB_CCR_USERSETMPEND_Pos 1 /*!< SCB CCR: USERSETMPEND Position */ #define SCB_CCR_USERSETMPEND_Msk (1UL << SCB_CCR_USERSETMPEND_Pos) /*!< SCB CCR: USERSETMPEND Mask */ #define SCB_CCR_NONBASETHRDENA_Pos 0 /*!< SCB CCR: NONBASETHRDENA Position */ #define SCB_CCR_NONBASETHRDENA_Msk (1UL /*<< SCB_CCR_NONBASETHRDENA_Pos*/) /*!< SCB CCR: NONBASETHRDENA Mask */ /* SCB System Handler Control and State Register Definitions */ #define SCB_SHCSR_USGFAULTENA_Pos 18 /*!< SCB SHCSR: USGFAULTENA Position */ #define SCB_SHCSR_USGFAULTENA_Msk (1UL << SCB_SHCSR_USGFAULTENA_Pos) /*!< SCB SHCSR: USGFAULTENA Mask */ #define SCB_SHCSR_BUSFAULTENA_Pos 17 /*!< SCB SHCSR: BUSFAULTENA Position */ #define SCB_SHCSR_BUSFAULTENA_Msk (1UL << SCB_SHCSR_BUSFAULTENA_Pos) /*!< SCB SHCSR: BUSFAULTENA Mask */ #define SCB_SHCSR_MEMFAULTENA_Pos 16 /*!< SCB SHCSR: MEMFAULTENA Position */ #define SCB_SHCSR_MEMFAULTENA_Msk (1UL << SCB_SHCSR_MEMFAULTENA_Pos) /*!< SCB SHCSR: MEMFAULTENA Mask */ #define SCB_SHCSR_SVCALLPENDED_Pos 15 /*!< SCB SHCSR: SVCALLPENDED Position */ #define SCB_SHCSR_SVCALLPENDED_Msk (1UL << SCB_SHCSR_SVCALLPENDED_Pos) /*!< SCB SHCSR: SVCALLPENDED Mask */ #define SCB_SHCSR_BUSFAULTPENDED_Pos 14 /*!< SCB SHCSR: BUSFAULTPENDED Position */ #define SCB_SHCSR_BUSFAULTPENDED_Msk (1UL << SCB_SHCSR_BUSFAULTPENDED_Pos) /*!< SCB SHCSR: BUSFAULTPENDED Mask */ #define SCB_SHCSR_MEMFAULTPENDED_Pos 13 /*!< SCB SHCSR: MEMFAULTPENDED Position */ #define SCB_SHCSR_MEMFAULTPENDED_Msk (1UL << SCB_SHCSR_MEMFAULTPENDED_Pos) /*!< SCB SHCSR: MEMFAULTPENDED Mask */ #define SCB_SHCSR_USGFAULTPENDED_Pos 12 /*!< SCB SHCSR: USGFAULTPENDED Position */ #define SCB_SHCSR_USGFAULTPENDED_Msk (1UL << SCB_SHCSR_USGFAULTPENDED_Pos) /*!< SCB SHCSR: USGFAULTPENDED Mask */ #define SCB_SHCSR_SYSTICKACT_Pos 11 /*!< SCB SHCSR: SYSTICKACT Position */ #define SCB_SHCSR_SYSTICKACT_Msk (1UL << SCB_SHCSR_SYSTICKACT_Pos) /*!< SCB SHCSR: SYSTICKACT Mask */ #define SCB_SHCSR_PENDSVACT_Pos 10 /*!< SCB SHCSR: PENDSVACT Position */ #define SCB_SHCSR_PENDSVACT_Msk (1UL << SCB_SHCSR_PENDSVACT_Pos) /*!< SCB SHCSR: PENDSVACT Mask */ #define SCB_SHCSR_MONITORACT_Pos 8 /*!< SCB SHCSR: MONITORACT Position */ #define SCB_SHCSR_MONITORACT_Msk (1UL << SCB_SHCSR_MONITORACT_Pos) /*!< SCB SHCSR: MONITORACT Mask */ #define SCB_SHCSR_SVCALLACT_Pos 7 /*!< SCB SHCSR: SVCALLACT Position */ #define SCB_SHCSR_SVCALLACT_Msk (1UL << SCB_SHCSR_SVCALLACT_Pos) /*!< SCB SHCSR: SVCALLACT Mask */ #define SCB_SHCSR_USGFAULTACT_Pos 3 /*!< SCB SHCSR: USGFAULTACT Position */ #define SCB_SHCSR_USGFAULTACT_Msk (1UL << SCB_SHCSR_USGFAULTACT_Pos) /*!< SCB SHCSR: USGFAULTACT Mask */ #define SCB_SHCSR_BUSFAULTACT_Pos 1 /*!< SCB SHCSR: BUSFAULTACT Position */ #define SCB_SHCSR_BUSFAULTACT_Msk (1UL << SCB_SHCSR_BUSFAULTACT_Pos) /*!< SCB SHCSR: BUSFAULTACT Mask */ #define SCB_SHCSR_MEMFAULTACT_Pos 0 /*!< SCB SHCSR: MEMFAULTACT Position */ #define SCB_SHCSR_MEMFAULTACT_Msk (1UL /*<< SCB_SHCSR_MEMFAULTACT_Pos*/) /*!< SCB SHCSR: MEMFAULTACT Mask */ /* SCB Configurable Fault Status Registers Definitions */ #define SCB_CFSR_USGFAULTSR_Pos 16 /*!< SCB CFSR: Usage Fault Status Register Position */ #define SCB_CFSR_USGFAULTSR_Msk (0xFFFFUL << SCB_CFSR_USGFAULTSR_Pos) /*!< SCB CFSR: Usage Fault Status Register Mask */ #define SCB_CFSR_BUSFAULTSR_Pos 8 /*!< SCB CFSR: Bus Fault Status Register Position */ #define SCB_CFSR_BUSFAULTSR_Msk (0xFFUL << SCB_CFSR_BUSFAULTSR_Pos) /*!< SCB CFSR: Bus Fault Status Register Mask */ #define SCB_CFSR_MEMFAULTSR_Pos 0 /*!< SCB CFSR: Memory Manage Fault Status Register Position */ #define SCB_CFSR_MEMFAULTSR_Msk (0xFFUL /*<< SCB_CFSR_MEMFAULTSR_Pos*/) /*!< SCB CFSR: Memory Manage Fault Status Register Mask */ /* SCB Hard Fault Status Registers Definitions */ #define SCB_HFSR_DEBUGEVT_Pos 31 /*!< SCB HFSR: DEBUGEVT Position */ #define SCB_HFSR_DEBUGEVT_Msk (1UL << SCB_HFSR_DEBUGEVT_Pos) /*!< SCB HFSR: DEBUGEVT Mask */ #define SCB_HFSR_FORCED_Pos 30 /*!< SCB HFSR: FORCED Position */ #define SCB_HFSR_FORCED_Msk (1UL << SCB_HFSR_FORCED_Pos) /*!< SCB HFSR: FORCED Mask */ #define SCB_HFSR_VECTTBL_Pos 1 /*!< SCB HFSR: VECTTBL Position */ #define SCB_HFSR_VECTTBL_Msk (1UL << SCB_HFSR_VECTTBL_Pos) /*!< SCB HFSR: VECTTBL Mask */ /* SCB Debug Fault Status Register Definitions */ #define SCB_DFSR_EXTERNAL_Pos 4 /*!< SCB DFSR: EXTERNAL Position */ #define SCB_DFSR_EXTERNAL_Msk (1UL << SCB_DFSR_EXTERNAL_Pos) /*!< SCB DFSR: EXTERNAL Mask */ #define SCB_DFSR_VCATCH_Pos 3 /*!< SCB DFSR: VCATCH Position */ #define SCB_DFSR_VCATCH_Msk (1UL << SCB_DFSR_VCATCH_Pos) /*!< SCB DFSR: VCATCH Mask */ #define SCB_DFSR_DWTTRAP_Pos 2 /*!< SCB DFSR: DWTTRAP Position */ #define SCB_DFSR_DWTTRAP_Msk (1UL << SCB_DFSR_DWTTRAP_Pos) /*!< SCB DFSR: DWTTRAP Mask */ #define SCB_DFSR_BKPT_Pos 1 /*!< SCB DFSR: BKPT Position */ #define SCB_DFSR_BKPT_Msk (1UL << SCB_DFSR_BKPT_Pos) /*!< SCB DFSR: BKPT Mask */ #define SCB_DFSR_HALTED_Pos 0 /*!< SCB DFSR: HALTED Position */ #define SCB_DFSR_HALTED_Msk (1UL /*<< SCB_DFSR_HALTED_Pos*/) /*!< SCB DFSR: HALTED Mask */ /*@} end of group CMSIS_SCB */ /** \ingroup CMSIS_core_register \defgroup CMSIS_SCnSCB System Controls not in SCB (SCnSCB) \brief Type definitions for the System Control and ID Register not in the SCB @{ */ /** \brief Structure type to access the System Control and ID Register not in the SCB. */ typedef struct { uint32_t RESERVED0[1]; __I uint32_t ICTR; /*!< Offset: 0x004 (R/ ) Interrupt Controller Type Register */ uint32_t RESERVED1[1]; } SCnSCB_Type; /* Interrupt Controller Type Register Definitions */ #define SCnSCB_ICTR_INTLINESNUM_Pos 0 /*!< ICTR: INTLINESNUM Position */ #define SCnSCB_ICTR_INTLINESNUM_Msk (0xFUL /*<< SCnSCB_ICTR_INTLINESNUM_Pos*/) /*!< ICTR: INTLINESNUM Mask */ /*@} end of group CMSIS_SCnotSCB */ /** \ingroup CMSIS_core_register \defgroup CMSIS_SysTick System Tick Timer (SysTick) \brief Type definitions for the System Timer Registers. @{ */ /** \brief Structure type to access the System Timer (SysTick). */ typedef struct { __IO uint32_t CTRL; /*!< Offset: 0x000 (R/W) SysTick Control and Status Register */ __IO uint32_t LOAD; /*!< Offset: 0x004 (R/W) SysTick Reload Value Register */ __IO uint32_t VAL; /*!< Offset: 0x008 (R/W) SysTick Current Value Register */ __I uint32_t CALIB; /*!< Offset: 0x00C (R/ ) SysTick Calibration Register */ } SysTick_Type; /* SysTick Control / Status Register Definitions */ #define SysTick_CTRL_COUNTFLAG_Pos 16 /*!< SysTick CTRL: COUNTFLAG Position */ #define SysTick_CTRL_COUNTFLAG_Msk (1UL << SysTick_CTRL_COUNTFLAG_Pos) /*!< SysTick CTRL: COUNTFLAG Mask */ #define SysTick_CTRL_CLKSOURCE_Pos 2 /*!< SysTick CTRL: CLKSOURCE Position */ #define SysTick_CTRL_CLKSOURCE_Msk (1UL << SysTick_CTRL_CLKSOURCE_Pos) /*!< SysTick CTRL: CLKSOURCE Mask */ #define SysTick_CTRL_TICKINT_Pos 1 /*!< SysTick CTRL: TICKINT Position */ #define SysTick_CTRL_TICKINT_Msk (1UL << SysTick_CTRL_TICKINT_Pos) /*!< SysTick CTRL: TICKINT Mask */ #define SysTick_CTRL_ENABLE_Pos 0 /*!< SysTick CTRL: ENABLE Position */ #define SysTick_CTRL_ENABLE_Msk (1UL /*<< SysTick_CTRL_ENABLE_Pos*/) /*!< SysTick CTRL: ENABLE Mask */ /* SysTick Reload Register Definitions */ #define SysTick_LOAD_RELOAD_Pos 0 /*!< SysTick LOAD: RELOAD Position */ #define SysTick_LOAD_RELOAD_Msk (0xFFFFFFUL /*<< SysTick_LOAD_RELOAD_Pos*/) /*!< SysTick LOAD: RELOAD Mask */ /* SysTick Current Register Definitions */ #define SysTick_VAL_CURRENT_Pos 0 /*!< SysTick VAL: CURRENT Position */ #define SysTick_VAL_CURRENT_Msk (0xFFFFFFUL /*<< SysTick_VAL_CURRENT_Pos*/) /*!< SysTick VAL: CURRENT Mask */ /* SysTick Calibration Register Definitions */ #define SysTick_CALIB_NOREF_Pos 31 /*!< SysTick CALIB: NOREF Position */ #define SysTick_CALIB_NOREF_Msk (1UL << SysTick_CALIB_NOREF_Pos) /*!< SysTick CALIB: NOREF Mask */ #define SysTick_CALIB_SKEW_Pos 30 /*!< SysTick CALIB: SKEW Position */ #define SysTick_CALIB_SKEW_Msk (1UL << SysTick_CALIB_SKEW_Pos) /*!< SysTick CALIB: SKEW Mask */ #define SysTick_CALIB_TENMS_Pos 0 /*!< SysTick CALIB: TENMS Position */ #define SysTick_CALIB_TENMS_Msk (0xFFFFFFUL /*<< SysTick_CALIB_TENMS_Pos*/) /*!< SysTick CALIB: TENMS Mask */ /*@} end of group CMSIS_SysTick */ /** \ingroup CMSIS_core_register \defgroup CMSIS_ITM Instrumentation Trace Macrocell (ITM) \brief Type definitions for the Instrumentation Trace Macrocell (ITM) @{ */ /** \brief Structure type to access the Instrumentation Trace Macrocell Register (ITM). */ typedef struct { __O union { __O uint8_t u8; /*!< Offset: 0x000 ( /W) ITM Stimulus Port 8-bit */ __O uint16_t u16; /*!< Offset: 0x000 ( /W) ITM Stimulus Port 16-bit */ __O uint32_t u32; /*!< Offset: 0x000 ( /W) ITM Stimulus Port 32-bit */ } PORT [32]; /*!< Offset: 0x000 ( /W) ITM Stimulus Port Registers */ uint32_t RESERVED0[864]; __IO uint32_t TER; /*!< Offset: 0xE00 (R/W) ITM Trace Enable Register */ uint32_t RESERVED1[15]; __IO uint32_t TPR; /*!< Offset: 0xE40 (R/W) ITM Trace Privilege Register */ uint32_t RESERVED2[15]; __IO uint32_t TCR; /*!< Offset: 0xE80 (R/W) ITM Trace Control Register */ uint32_t RESERVED3[29]; __O uint32_t IWR; /*!< Offset: 0xEF8 ( /W) ITM Integration Write Register */ __I uint32_t IRR; /*!< Offset: 0xEFC (R/ ) ITM Integration Read Register */ __IO uint32_t IMCR; /*!< Offset: 0xF00 (R/W) ITM Integration Mode Control Register */ uint32_t RESERVED4[43]; __O uint32_t LAR; /*!< Offset: 0xFB0 ( /W) ITM Lock Access Register */ __I uint32_t LSR; /*!< Offset: 0xFB4 (R/ ) ITM Lock Status Register */ uint32_t RESERVED5[6]; __I uint32_t PID4; /*!< Offset: 0xFD0 (R/ ) ITM Peripheral Identification Register #4 */ __I uint32_t PID5; /*!< Offset: 0xFD4 (R/ ) ITM Peripheral Identification Register #5 */ __I uint32_t PID6; /*!< Offset: 0xFD8 (R/ ) ITM Peripheral Identification Register #6 */ __I uint32_t PID7; /*!< Offset: 0xFDC (R/ ) ITM Peripheral Identification Register #7 */ __I uint32_t PID0; /*!< Offset: 0xFE0 (R/ ) ITM Peripheral Identification Register #0 */ __I uint32_t PID1; /*!< Offset: 0xFE4 (R/ ) ITM Peripheral Identification Register #1 */ __I uint32_t PID2; /*!< Offset: 0xFE8 (R/ ) ITM Peripheral Identification Register #2 */ __I uint32_t PID3; /*!< Offset: 0xFEC (R/ ) ITM Peripheral Identification Register #3 */ __I uint32_t CID0; /*!< Offset: 0xFF0 (R/ ) ITM Component Identification Register #0 */ __I uint32_t CID1; /*!< Offset: 0xFF4 (R/ ) ITM Component Identification Register #1 */ __I uint32_t CID2; /*!< Offset: 0xFF8 (R/ ) ITM Component Identification Register #2 */ __I uint32_t CID3; /*!< Offset: 0xFFC (R/ ) ITM Component Identification Register #3 */ } ITM_Type; /* ITM Trace Privilege Register Definitions */ #define ITM_TPR_PRIVMASK_Pos 0 /*!< ITM TPR: PRIVMASK Position */ #define ITM_TPR_PRIVMASK_Msk (0xFUL /*<< ITM_TPR_PRIVMASK_Pos*/) /*!< ITM TPR: PRIVMASK Mask */ /* ITM Trace Control Register Definitions */ #define ITM_TCR_BUSY_Pos 23 /*!< ITM TCR: BUSY Position */ #define ITM_TCR_BUSY_Msk (1UL << ITM_TCR_BUSY_Pos) /*!< ITM TCR: BUSY Mask */ #define ITM_TCR_TraceBusID_Pos 16 /*!< ITM TCR: ATBID Position */ #define ITM_TCR_TraceBusID_Msk (0x7FUL << ITM_TCR_TraceBusID_Pos) /*!< ITM TCR: ATBID Mask */ #define ITM_TCR_GTSFREQ_Pos 10 /*!< ITM TCR: Global timestamp frequency Position */ #define ITM_TCR_GTSFREQ_Msk (3UL << ITM_TCR_GTSFREQ_Pos) /*!< ITM TCR: Global timestamp frequency Mask */ #define ITM_TCR_TSPrescale_Pos 8 /*!< ITM TCR: TSPrescale Position */ #define ITM_TCR_TSPrescale_Msk (3UL << ITM_TCR_TSPrescale_Pos) /*!< ITM TCR: TSPrescale Mask */ #define ITM_TCR_SWOENA_Pos 4 /*!< ITM TCR: SWOENA Position */ #define ITM_TCR_SWOENA_Msk (1UL << ITM_TCR_SWOENA_Pos) /*!< ITM TCR: SWOENA Mask */ #define ITM_TCR_DWTENA_Pos 3 /*!< ITM TCR: DWTENA Position */ #define ITM_TCR_DWTENA_Msk (1UL << ITM_TCR_DWTENA_Pos) /*!< ITM TCR: DWTENA Mask */ #define ITM_TCR_SYNCENA_Pos 2 /*!< ITM TCR: SYNCENA Position */ #define ITM_TCR_SYNCENA_Msk (1UL << ITM_TCR_SYNCENA_Pos) /*!< ITM TCR: SYNCENA Mask */ #define ITM_TCR_TSENA_Pos 1 /*!< ITM TCR: TSENA Position */ #define ITM_TCR_TSENA_Msk (1UL << ITM_TCR_TSENA_Pos) /*!< ITM TCR: TSENA Mask */ #define ITM_TCR_ITMENA_Pos 0 /*!< ITM TCR: ITM Enable bit Position */ #define ITM_TCR_ITMENA_Msk (1UL /*<< ITM_TCR_ITMENA_Pos*/) /*!< ITM TCR: ITM Enable bit Mask */ /* ITM Integration Write Register Definitions */ #define ITM_IWR_ATVALIDM_Pos 0 /*!< ITM IWR: ATVALIDM Position */ #define ITM_IWR_ATVALIDM_Msk (1UL /*<< ITM_IWR_ATVALIDM_Pos*/) /*!< ITM IWR: ATVALIDM Mask */ /* ITM Integration Read Register Definitions */ #define ITM_IRR_ATREADYM_Pos 0 /*!< ITM IRR: ATREADYM Position */ #define ITM_IRR_ATREADYM_Msk (1UL /*<< ITM_IRR_ATREADYM_Pos*/) /*!< ITM IRR: ATREADYM Mask */ /* ITM Integration Mode Control Register Definitions */ #define ITM_IMCR_INTEGRATION_Pos 0 /*!< ITM IMCR: INTEGRATION Position */ #define ITM_IMCR_INTEGRATION_Msk (1UL /*<< ITM_IMCR_INTEGRATION_Pos*/) /*!< ITM IMCR: INTEGRATION Mask */ /* ITM Lock Status Register Definitions */ #define ITM_LSR_ByteAcc_Pos 2 /*!< ITM LSR: ByteAcc Position */ #define ITM_LSR_ByteAcc_Msk (1UL << ITM_LSR_ByteAcc_Pos) /*!< ITM LSR: ByteAcc Mask */ #define ITM_LSR_Access_Pos 1 /*!< ITM LSR: Access Position */ #define ITM_LSR_Access_Msk (1UL << ITM_LSR_Access_Pos) /*!< ITM LSR: Access Mask */ #define ITM_LSR_Present_Pos 0 /*!< ITM LSR: Present Position */ #define ITM_LSR_Present_Msk (1UL /*<< ITM_LSR_Present_Pos*/) /*!< ITM LSR: Present Mask */ /*@}*/ /* end of group CMSIS_ITM */ /** \ingroup CMSIS_core_register \defgroup CMSIS_DWT Data Watchpoint and Trace (DWT) \brief Type definitions for the Data Watchpoint and Trace (DWT) @{ */ /** \brief Structure type to access the Data Watchpoint and Trace Register (DWT). */ typedef struct { __IO uint32_t CTRL; /*!< Offset: 0x000 (R/W) Control Register */ __IO uint32_t CYCCNT; /*!< Offset: 0x004 (R/W) Cycle Count Register */ __IO uint32_t CPICNT; /*!< Offset: 0x008 (R/W) CPI Count Register */ __IO uint32_t EXCCNT; /*!< Offset: 0x00C (R/W) Exception Overhead Count Register */ __IO uint32_t SLEEPCNT; /*!< Offset: 0x010 (R/W) Sleep Count Register */ __IO uint32_t LSUCNT; /*!< Offset: 0x014 (R/W) LSU Count Register */ __IO uint32_t FOLDCNT; /*!< Offset: 0x018 (R/W) Folded-instruction Count Register */ __I uint32_t PCSR; /*!< Offset: 0x01C (R/ ) Program Counter Sample Register */ __IO uint32_t COMP0; /*!< Offset: 0x020 (R/W) Comparator Register 0 */ __IO uint32_t MASK0; /*!< Offset: 0x024 (R/W) Mask Register 0 */ __IO uint32_t FUNCTION0; /*!< Offset: 0x028 (R/W) Function Register 0 */ uint32_t RESERVED0[1]; __IO uint32_t COMP1; /*!< Offset: 0x030 (R/W) Comparator Register 1 */ __IO uint32_t MASK1; /*!< Offset: 0x034 (R/W) Mask Register 1 */ __IO uint32_t FUNCTION1; /*!< Offset: 0x038 (R/W) Function Register 1 */ uint32_t RESERVED1[1]; __IO uint32_t COMP2; /*!< Offset: 0x040 (R/W) Comparator Register 2 */ __IO uint32_t MASK2; /*!< Offset: 0x044 (R/W) Mask Register 2 */ __IO uint32_t FUNCTION2; /*!< Offset: 0x048 (R/W) Function Register 2 */ uint32_t RESERVED2[1]; __IO uint32_t COMP3; /*!< Offset: 0x050 (R/W) Comparator Register 3 */ __IO uint32_t MASK3; /*!< Offset: 0x054 (R/W) Mask Register 3 */ __IO uint32_t FUNCTION3; /*!< Offset: 0x058 (R/W) Function Register 3 */ } DWT_Type; /* DWT Control Register Definitions */ #define DWT_CTRL_NUMCOMP_Pos 28 /*!< DWT CTRL: NUMCOMP Position */ #define DWT_CTRL_NUMCOMP_Msk (0xFUL << DWT_CTRL_NUMCOMP_Pos) /*!< DWT CTRL: NUMCOMP Mask */ #define DWT_CTRL_NOTRCPKT_Pos 27 /*!< DWT CTRL: NOTRCPKT Position */ #define DWT_CTRL_NOTRCPKT_Msk (0x1UL << DWT_CTRL_NOTRCPKT_Pos) /*!< DWT CTRL: NOTRCPKT Mask */ #define DWT_CTRL_NOEXTTRIG_Pos 26 /*!< DWT CTRL: NOEXTTRIG Position */ #define DWT_CTRL_NOEXTTRIG_Msk (0x1UL << DWT_CTRL_NOEXTTRIG_Pos) /*!< DWT CTRL: NOEXTTRIG Mask */ #define DWT_CTRL_NOCYCCNT_Pos 25 /*!< DWT CTRL: NOCYCCNT Position */ #define DWT_CTRL_NOCYCCNT_Msk (0x1UL << DWT_CTRL_NOCYCCNT_Pos) /*!< DWT CTRL: NOCYCCNT Mask */ #define DWT_CTRL_NOPRFCNT_Pos 24 /*!< DWT CTRL: NOPRFCNT Position */ #define DWT_CTRL_NOPRFCNT_Msk (0x1UL << DWT_CTRL_NOPRFCNT_Pos) /*!< DWT CTRL: NOPRFCNT Mask */ #define DWT_CTRL_CYCEVTENA_Pos 22 /*!< DWT CTRL: CYCEVTENA Position */ #define DWT_CTRL_CYCEVTENA_Msk (0x1UL << DWT_CTRL_CYCEVTENA_Pos) /*!< DWT CTRL: CYCEVTENA Mask */ #define DWT_CTRL_FOLDEVTENA_Pos 21 /*!< DWT CTRL: FOLDEVTENA Position */ #define DWT_CTRL_FOLDEVTENA_Msk (0x1UL << DWT_CTRL_FOLDEVTENA_Pos) /*!< DWT CTRL: FOLDEVTENA Mask */ #define DWT_CTRL_LSUEVTENA_Pos 20 /*!< DWT CTRL: LSUEVTENA Position */ #define DWT_CTRL_LSUEVTENA_Msk (0x1UL << DWT_CTRL_LSUEVTENA_Pos) /*!< DWT CTRL: LSUEVTENA Mask */ #define DWT_CTRL_SLEEPEVTENA_Pos 19 /*!< DWT CTRL: SLEEPEVTENA Position */ #define DWT_CTRL_SLEEPEVTENA_Msk (0x1UL << DWT_CTRL_SLEEPEVTENA_Pos) /*!< DWT CTRL: SLEEPEVTENA Mask */ #define DWT_CTRL_EXCEVTENA_Pos 18 /*!< DWT CTRL: EXCEVTENA Position */ #define DWT_CTRL_EXCEVTENA_Msk (0x1UL << DWT_CTRL_EXCEVTENA_Pos) /*!< DWT CTRL: EXCEVTENA Mask */ #define DWT_CTRL_CPIEVTENA_Pos 17 /*!< DWT CTRL: CPIEVTENA Position */ #define DWT_CTRL_CPIEVTENA_Msk (0x1UL << DWT_CTRL_CPIEVTENA_Pos) /*!< DWT CTRL: CPIEVTENA Mask */ #define DWT_CTRL_EXCTRCENA_Pos 16 /*!< DWT CTRL: EXCTRCENA Position */ #define DWT_CTRL_EXCTRCENA_Msk (0x1UL << DWT_CTRL_EXCTRCENA_Pos) /*!< DWT CTRL: EXCTRCENA Mask */ #define DWT_CTRL_PCSAMPLENA_Pos 12 /*!< DWT CTRL: PCSAMPLENA Position */ #define DWT_CTRL_PCSAMPLENA_Msk (0x1UL << DWT_CTRL_PCSAMPLENA_Pos) /*!< DWT CTRL: PCSAMPLENA Mask */ #define DWT_CTRL_SYNCTAP_Pos 10 /*!< DWT CTRL: SYNCTAP Position */ #define DWT_CTRL_SYNCTAP_Msk (0x3UL << DWT_CTRL_SYNCTAP_Pos) /*!< DWT CTRL: SYNCTAP Mask */ #define DWT_CTRL_CYCTAP_Pos 9 /*!< DWT CTRL: CYCTAP Position */ #define DWT_CTRL_CYCTAP_Msk (0x1UL << DWT_CTRL_CYCTAP_Pos) /*!< DWT CTRL: CYCTAP Mask */ #define DWT_CTRL_POSTINIT_Pos 5 /*!< DWT CTRL: POSTINIT Position */ #define DWT_CTRL_POSTINIT_Msk (0xFUL << DWT_CTRL_POSTINIT_Pos) /*!< DWT CTRL: POSTINIT Mask */ #define DWT_CTRL_POSTPRESET_Pos 1 /*!< DWT CTRL: POSTPRESET Position */ #define DWT_CTRL_POSTPRESET_Msk (0xFUL << DWT_CTRL_POSTPRESET_Pos) /*!< DWT CTRL: POSTPRESET Mask */ #define DWT_CTRL_CYCCNTENA_Pos 0 /*!< DWT CTRL: CYCCNTENA Position */ #define DWT_CTRL_CYCCNTENA_Msk (0x1UL /*<< DWT_CTRL_CYCCNTENA_Pos*/) /*!< DWT CTRL: CYCCNTENA Mask */ /* DWT CPI Count Register Definitions */ #define DWT_CPICNT_CPICNT_Pos 0 /*!< DWT CPICNT: CPICNT Position */ #define DWT_CPICNT_CPICNT_Msk (0xFFUL /*<< DWT_CPICNT_CPICNT_Pos*/) /*!< DWT CPICNT: CPICNT Mask */ /* DWT Exception Overhead Count Register Definitions */ #define DWT_EXCCNT_EXCCNT_Pos 0 /*!< DWT EXCCNT: EXCCNT Position */ #define DWT_EXCCNT_EXCCNT_Msk (0xFFUL /*<< DWT_EXCCNT_EXCCNT_Pos*/) /*!< DWT EXCCNT: EXCCNT Mask */ /* DWT Sleep Count Register Definitions */ #define DWT_SLEEPCNT_SLEEPCNT_Pos 0 /*!< DWT SLEEPCNT: SLEEPCNT Position */ #define DWT_SLEEPCNT_SLEEPCNT_Msk (0xFFUL /*<< DWT_SLEEPCNT_SLEEPCNT_Pos*/) /*!< DWT SLEEPCNT: SLEEPCNT Mask */ /* DWT LSU Count Register Definitions */ #define DWT_LSUCNT_LSUCNT_Pos 0 /*!< DWT LSUCNT: LSUCNT Position */ #define DWT_LSUCNT_LSUCNT_Msk (0xFFUL /*<< DWT_LSUCNT_LSUCNT_Pos*/) /*!< DWT LSUCNT: LSUCNT Mask */ /* DWT Folded-instruction Count Register Definitions */ #define DWT_FOLDCNT_FOLDCNT_Pos 0 /*!< DWT FOLDCNT: FOLDCNT Position */ #define DWT_FOLDCNT_FOLDCNT_Msk (0xFFUL /*<< DWT_FOLDCNT_FOLDCNT_Pos*/) /*!< DWT FOLDCNT: FOLDCNT Mask */ /* DWT Comparator Mask Register Definitions */ #define DWT_MASK_MASK_Pos 0 /*!< DWT MASK: MASK Position */ #define DWT_MASK_MASK_Msk (0x1FUL /*<< DWT_MASK_MASK_Pos*/) /*!< DWT MASK: MASK Mask */ /* DWT Comparator Function Register Definitions */ #define DWT_FUNCTION_MATCHED_Pos 24 /*!< DWT FUNCTION: MATCHED Position */ #define DWT_FUNCTION_MATCHED_Msk (0x1UL << DWT_FUNCTION_MATCHED_Pos) /*!< DWT FUNCTION: MATCHED Mask */ #define DWT_FUNCTION_DATAVADDR1_Pos 16 /*!< DWT FUNCTION: DATAVADDR1 Position */ #define DWT_FUNCTION_DATAVADDR1_Msk (0xFUL << DWT_FUNCTION_DATAVADDR1_Pos) /*!< DWT FUNCTION: DATAVADDR1 Mask */ #define DWT_FUNCTION_DATAVADDR0_Pos 12 /*!< DWT FUNCTION: DATAVADDR0 Position */ #define DWT_FUNCTION_DATAVADDR0_Msk (0xFUL << DWT_FUNCTION_DATAVADDR0_Pos) /*!< DWT FUNCTION: DATAVADDR0 Mask */ #define DWT_FUNCTION_DATAVSIZE_Pos 10 /*!< DWT FUNCTION: DATAVSIZE Position */ #define DWT_FUNCTION_DATAVSIZE_Msk (0x3UL << DWT_FUNCTION_DATAVSIZE_Pos) /*!< DWT FUNCTION: DATAVSIZE Mask */ #define DWT_FUNCTION_LNK1ENA_Pos 9 /*!< DWT FUNCTION: LNK1ENA Position */ #define DWT_FUNCTION_LNK1ENA_Msk (0x1UL << DWT_FUNCTION_LNK1ENA_Pos) /*!< DWT FUNCTION: LNK1ENA Mask */ #define DWT_FUNCTION_DATAVMATCH_Pos 8 /*!< DWT FUNCTION: DATAVMATCH Position */ #define DWT_FUNCTION_DATAVMATCH_Msk (0x1UL << DWT_FUNCTION_DATAVMATCH_Pos) /*!< DWT FUNCTION: DATAVMATCH Mask */ #define DWT_FUNCTION_CYCMATCH_Pos 7 /*!< DWT FUNCTION: CYCMATCH Position */ #define DWT_FUNCTION_CYCMATCH_Msk (0x1UL << DWT_FUNCTION_CYCMATCH_Pos) /*!< DWT FUNCTION: CYCMATCH Mask */ #define DWT_FUNCTION_EMITRANGE_Pos 5 /*!< DWT FUNCTION: EMITRANGE Position */ #define DWT_FUNCTION_EMITRANGE_Msk (0x1UL << DWT_FUNCTION_EMITRANGE_Pos) /*!< DWT FUNCTION: EMITRANGE Mask */ #define DWT_FUNCTION_FUNCTION_Pos 0 /*!< DWT FUNCTION: FUNCTION Position */ #define DWT_FUNCTION_FUNCTION_Msk (0xFUL /*<< DWT_FUNCTION_FUNCTION_Pos*/) /*!< DWT FUNCTION: FUNCTION Mask */ /*@}*/ /* end of group CMSIS_DWT */ /** \ingroup CMSIS_core_register \defgroup CMSIS_TPI Trace Port Interface (TPI) \brief Type definitions for the Trace Port Interface (TPI) @{ */ /** \brief Structure type to access the Trace Port Interface Register (TPI). */ typedef struct { __IO uint32_t SSPSR; /*!< Offset: 0x000 (R/ ) Supported Parallel Port Size Register */ __IO uint32_t CSPSR; /*!< Offset: 0x004 (R/W) Current Parallel Port Size Register */ uint32_t RESERVED0[2]; __IO uint32_t ACPR; /*!< Offset: 0x010 (R/W) Asynchronous Clock Prescaler Register */ uint32_t RESERVED1[55]; __IO uint32_t SPPR; /*!< Offset: 0x0F0 (R/W) Selected Pin Protocol Register */ uint32_t RESERVED2[131]; __I uint32_t FFSR; /*!< Offset: 0x300 (R/ ) Formatter and Flush Status Register */ __IO uint32_t FFCR; /*!< Offset: 0x304 (R/W) Formatter and Flush Control Register */ __I uint32_t FSCR; /*!< Offset: 0x308 (R/ ) Formatter Synchronization Counter Register */ uint32_t RESERVED3[759]; __I uint32_t TRIGGER; /*!< Offset: 0xEE8 (R/ ) TRIGGER */ __I uint32_t FIFO0; /*!< Offset: 0xEEC (R/ ) Integration ETM Data */ __I uint32_t ITATBCTR2; /*!< Offset: 0xEF0 (R/ ) ITATBCTR2 */ uint32_t RESERVED4[1]; __I uint32_t ITATBCTR0; /*!< Offset: 0xEF8 (R/ ) ITATBCTR0 */ __I uint32_t FIFO1; /*!< Offset: 0xEFC (R/ ) Integration ITM Data */ __IO uint32_t ITCTRL; /*!< Offset: 0xF00 (R/W) Integration Mode Control */ uint32_t RESERVED5[39]; __IO uint32_t CLAIMSET; /*!< Offset: 0xFA0 (R/W) Claim tag set */ __IO uint32_t CLAIMCLR; /*!< Offset: 0xFA4 (R/W) Claim tag clear */ uint32_t RESERVED7[8]; __I uint32_t DEVID; /*!< Offset: 0xFC8 (R/ ) TPIU_DEVID */ __I uint32_t DEVTYPE; /*!< Offset: 0xFCC (R/ ) TPIU_DEVTYPE */ } TPI_Type; /* TPI Asynchronous Clock Prescaler Register Definitions */ #define TPI_ACPR_PRESCALER_Pos 0 /*!< TPI ACPR: PRESCALER Position */ #define TPI_ACPR_PRESCALER_Msk (0x1FFFUL /*<< TPI_ACPR_PRESCALER_Pos*/) /*!< TPI ACPR: PRESCALER Mask */ /* TPI Selected Pin Protocol Register Definitions */ #define TPI_SPPR_TXMODE_Pos 0 /*!< TPI SPPR: TXMODE Position */ #define TPI_SPPR_TXMODE_Msk (0x3UL /*<< TPI_SPPR_TXMODE_Pos*/) /*!< TPI SPPR: TXMODE Mask */ /* TPI Formatter and Flush Status Register Definitions */ #define TPI_FFSR_FtNonStop_Pos 3 /*!< TPI FFSR: FtNonStop Position */ #define TPI_FFSR_FtNonStop_Msk (0x1UL << TPI_FFSR_FtNonStop_Pos) /*!< TPI FFSR: FtNonStop Mask */ #define TPI_FFSR_TCPresent_Pos 2 /*!< TPI FFSR: TCPresent Position */ #define TPI_FFSR_TCPresent_Msk (0x1UL << TPI_FFSR_TCPresent_Pos) /*!< TPI FFSR: TCPresent Mask */ #define TPI_FFSR_FtStopped_Pos 1 /*!< TPI FFSR: FtStopped Position */ #define TPI_FFSR_FtStopped_Msk (0x1UL << TPI_FFSR_FtStopped_Pos) /*!< TPI FFSR: FtStopped Mask */ #define TPI_FFSR_FlInProg_Pos 0 /*!< TPI FFSR: FlInProg Position */ #define TPI_FFSR_FlInProg_Msk (0x1UL /*<< TPI_FFSR_FlInProg_Pos*/) /*!< TPI FFSR: FlInProg Mask */ /* TPI Formatter and Flush Control Register Definitions */ #define TPI_FFCR_TrigIn_Pos 8 /*!< TPI FFCR: TrigIn Position */ #define TPI_FFCR_TrigIn_Msk (0x1UL << TPI_FFCR_TrigIn_Pos) /*!< TPI FFCR: TrigIn Mask */ #define TPI_FFCR_EnFCont_Pos 1 /*!< TPI FFCR: EnFCont Position */ #define TPI_FFCR_EnFCont_Msk (0x1UL << TPI_FFCR_EnFCont_Pos) /*!< TPI FFCR: EnFCont Mask */ /* TPI TRIGGER Register Definitions */ #define TPI_TRIGGER_TRIGGER_Pos 0 /*!< TPI TRIGGER: TRIGGER Position */ #define TPI_TRIGGER_TRIGGER_Msk (0x1UL /*<< TPI_TRIGGER_TRIGGER_Pos*/) /*!< TPI TRIGGER: TRIGGER Mask */ /* TPI Integration ETM Data Register Definitions (FIFO0) */ #define TPI_FIFO0_ITM_ATVALID_Pos 29 /*!< TPI FIFO0: ITM_ATVALID Position */ #define TPI_FIFO0_ITM_ATVALID_Msk (0x3UL << TPI_FIFO0_ITM_ATVALID_Pos) /*!< TPI FIFO0: ITM_ATVALID Mask */ #define TPI_FIFO0_ITM_bytecount_Pos 27 /*!< TPI FIFO0: ITM_bytecount Position */ #define TPI_FIFO0_ITM_bytecount_Msk (0x3UL << TPI_FIFO0_ITM_bytecount_Pos) /*!< TPI FIFO0: ITM_bytecount Mask */ #define TPI_FIFO0_ETM_ATVALID_Pos 26 /*!< TPI FIFO0: ETM_ATVALID Position */ #define TPI_FIFO0_ETM_ATVALID_Msk (0x3UL << TPI_FIFO0_ETM_ATVALID_Pos) /*!< TPI FIFO0: ETM_ATVALID Mask */ #define TPI_FIFO0_ETM_bytecount_Pos 24 /*!< TPI FIFO0: ETM_bytecount Position */ #define TPI_FIFO0_ETM_bytecount_Msk (0x3UL << TPI_FIFO0_ETM_bytecount_Pos) /*!< TPI FIFO0: ETM_bytecount Mask */ #define TPI_FIFO0_ETM2_Pos 16 /*!< TPI FIFO0: ETM2 Position */ #define TPI_FIFO0_ETM2_Msk (0xFFUL << TPI_FIFO0_ETM2_Pos) /*!< TPI FIFO0: ETM2 Mask */ #define TPI_FIFO0_ETM1_Pos 8 /*!< TPI FIFO0: ETM1 Position */ #define TPI_FIFO0_ETM1_Msk (0xFFUL << TPI_FIFO0_ETM1_Pos) /*!< TPI FIFO0: ETM1 Mask */ #define TPI_FIFO0_ETM0_Pos 0 /*!< TPI FIFO0: ETM0 Position */ #define TPI_FIFO0_ETM0_Msk (0xFFUL /*<< TPI_FIFO0_ETM0_Pos*/) /*!< TPI FIFO0: ETM0 Mask */ /* TPI ITATBCTR2 Register Definitions */ #define TPI_ITATBCTR2_ATREADY_Pos 0 /*!< TPI ITATBCTR2: ATREADY Position */ #define TPI_ITATBCTR2_ATREADY_Msk (0x1UL /*<< TPI_ITATBCTR2_ATREADY_Pos*/) /*!< TPI ITATBCTR2: ATREADY Mask */ /* TPI Integration ITM Data Register Definitions (FIFO1) */ #define TPI_FIFO1_ITM_ATVALID_Pos 29 /*!< TPI FIFO1: ITM_ATVALID Position */ #define TPI_FIFO1_ITM_ATVALID_Msk (0x3UL << TPI_FIFO1_ITM_ATVALID_Pos) /*!< TPI FIFO1: ITM_ATVALID Mask */ #define TPI_FIFO1_ITM_bytecount_Pos 27 /*!< TPI FIFO1: ITM_bytecount Position */ #define TPI_FIFO1_ITM_bytecount_Msk (0x3UL << TPI_FIFO1_ITM_bytecount_Pos) /*!< TPI FIFO1: ITM_bytecount Mask */ #define TPI_FIFO1_ETM_ATVALID_Pos 26 /*!< TPI FIFO1: ETM_ATVALID Position */ #define TPI_FIFO1_ETM_ATVALID_Msk (0x3UL << TPI_FIFO1_ETM_ATVALID_Pos) /*!< TPI FIFO1: ETM_ATVALID Mask */ #define TPI_FIFO1_ETM_bytecount_Pos 24 /*!< TPI FIFO1: ETM_bytecount Position */ #define TPI_FIFO1_ETM_bytecount_Msk (0x3UL << TPI_FIFO1_ETM_bytecount_Pos) /*!< TPI FIFO1: ETM_bytecount Mask */ #define TPI_FIFO1_ITM2_Pos 16 /*!< TPI FIFO1: ITM2 Position */ #define TPI_FIFO1_ITM2_Msk (0xFFUL << TPI_FIFO1_ITM2_Pos) /*!< TPI FIFO1: ITM2 Mask */ #define TPI_FIFO1_ITM1_Pos 8 /*!< TPI FIFO1: ITM1 Position */ #define TPI_FIFO1_ITM1_Msk (0xFFUL << TPI_FIFO1_ITM1_Pos) /*!< TPI FIFO1: ITM1 Mask */ #define TPI_FIFO1_ITM0_Pos 0 /*!< TPI FIFO1: ITM0 Position */ #define TPI_FIFO1_ITM0_Msk (0xFFUL /*<< TPI_FIFO1_ITM0_Pos*/) /*!< TPI FIFO1: ITM0 Mask */ /* TPI ITATBCTR0 Register Definitions */ #define TPI_ITATBCTR0_ATREADY_Pos 0 /*!< TPI ITATBCTR0: ATREADY Position */ #define TPI_ITATBCTR0_ATREADY_Msk (0x1UL /*<< TPI_ITATBCTR0_ATREADY_Pos*/) /*!< TPI ITATBCTR0: ATREADY Mask */ /* TPI Integration Mode Control Register Definitions */ #define TPI_ITCTRL_Mode_Pos 0 /*!< TPI ITCTRL: Mode Position */ #define TPI_ITCTRL_Mode_Msk (0x1UL /*<< TPI_ITCTRL_Mode_Pos*/) /*!< TPI ITCTRL: Mode Mask */ /* TPI DEVID Register Definitions */ #define TPI_DEVID_NRZVALID_Pos 11 /*!< TPI DEVID: NRZVALID Position */ #define TPI_DEVID_NRZVALID_Msk (0x1UL << TPI_DEVID_NRZVALID_Pos) /*!< TPI DEVID: NRZVALID Mask */ #define TPI_DEVID_MANCVALID_Pos 10 /*!< TPI DEVID: MANCVALID Position */ #define TPI_DEVID_MANCVALID_Msk (0x1UL << TPI_DEVID_MANCVALID_Pos) /*!< TPI DEVID: MANCVALID Mask */ #define TPI_DEVID_PTINVALID_Pos 9 /*!< TPI DEVID: PTINVALID Position */ #define TPI_DEVID_PTINVALID_Msk (0x1UL << TPI_DEVID_PTINVALID_Pos) /*!< TPI DEVID: PTINVALID Mask */ #define TPI_DEVID_MinBufSz_Pos 6 /*!< TPI DEVID: MinBufSz Position */ #define TPI_DEVID_MinBufSz_Msk (0x7UL << TPI_DEVID_MinBufSz_Pos) /*!< TPI DEVID: MinBufSz Mask */ #define TPI_DEVID_AsynClkIn_Pos 5 /*!< TPI DEVID: AsynClkIn Position */ #define TPI_DEVID_AsynClkIn_Msk (0x1UL << TPI_DEVID_AsynClkIn_Pos) /*!< TPI DEVID: AsynClkIn Mask */ #define TPI_DEVID_NrTraceInput_Pos 0 /*!< TPI DEVID: NrTraceInput Position */ #define TPI_DEVID_NrTraceInput_Msk (0x1FUL /*<< TPI_DEVID_NrTraceInput_Pos*/) /*!< TPI DEVID: NrTraceInput Mask */ /* TPI DEVTYPE Register Definitions */ #define TPI_DEVTYPE_MajorType_Pos 4 /*!< TPI DEVTYPE: MajorType Position */ #define TPI_DEVTYPE_MajorType_Msk (0xFUL << TPI_DEVTYPE_MajorType_Pos) /*!< TPI DEVTYPE: MajorType Mask */ #define TPI_DEVTYPE_SubType_Pos 0 /*!< TPI DEVTYPE: SubType Position */ #define TPI_DEVTYPE_SubType_Msk (0xFUL /*<< TPI_DEVTYPE_SubType_Pos*/) /*!< TPI DEVTYPE: SubType Mask */ /*@}*/ /* end of group CMSIS_TPI */ #if (__MPU_PRESENT == 1) /** \ingroup CMSIS_core_register \defgroup CMSIS_MPU Memory Protection Unit (MPU) \brief Type definitions for the Memory Protection Unit (MPU) @{ */ /** \brief Structure type to access the Memory Protection Unit (MPU). */ typedef struct { __I uint32_t TYPE; /*!< Offset: 0x000 (R/ ) MPU Type Register */ __IO uint32_t CTRL; /*!< Offset: 0x004 (R/W) MPU Control Register */ __IO uint32_t RNR; /*!< Offset: 0x008 (R/W) MPU Region RNRber Register */ __IO uint32_t RBAR; /*!< Offset: 0x00C (R/W) MPU Region Base Address Register */ __IO uint32_t RASR; /*!< Offset: 0x010 (R/W) MPU Region Attribute and Size Register */ __IO uint32_t RBAR_A1; /*!< Offset: 0x014 (R/W) MPU Alias 1 Region Base Address Register */ __IO uint32_t RASR_A1; /*!< Offset: 0x018 (R/W) MPU Alias 1 Region Attribute and Size Register */ __IO uint32_t RBAR_A2; /*!< Offset: 0x01C (R/W) MPU Alias 2 Region Base Address Register */ __IO uint32_t RASR_A2; /*!< Offset: 0x020 (R/W) MPU Alias 2 Region Attribute and Size Register */ __IO uint32_t RBAR_A3; /*!< Offset: 0x024 (R/W) MPU Alias 3 Region Base Address Register */ __IO uint32_t RASR_A3; /*!< Offset: 0x028 (R/W) MPU Alias 3 Region Attribute and Size Register */ } MPU_Type; /* MPU Type Register */ #define MPU_TYPE_IREGION_Pos 16 /*!< MPU TYPE: IREGION Position */ #define MPU_TYPE_IREGION_Msk (0xFFUL << MPU_TYPE_IREGION_Pos) /*!< MPU TYPE: IREGION Mask */ #define MPU_TYPE_DREGION_Pos 8 /*!< MPU TYPE: DREGION Position */ #define MPU_TYPE_DREGION_Msk (0xFFUL << MPU_TYPE_DREGION_Pos) /*!< MPU TYPE: DREGION Mask */ #define MPU_TYPE_SEPARATE_Pos 0 /*!< MPU TYPE: SEPARATE Position */ #define MPU_TYPE_SEPARATE_Msk (1UL /*<< MPU_TYPE_SEPARATE_Pos*/) /*!< MPU TYPE: SEPARATE Mask */ /* MPU Control Register */ #define MPU_CTRL_PRIVDEFENA_Pos 2 /*!< MPU CTRL: PRIVDEFENA Position */ #define MPU_CTRL_PRIVDEFENA_Msk (1UL << MPU_CTRL_PRIVDEFENA_Pos) /*!< MPU CTRL: PRIVDEFENA Mask */ #define MPU_CTRL_HFNMIENA_Pos 1 /*!< MPU CTRL: HFNMIENA Position */ #define MPU_CTRL_HFNMIENA_Msk (1UL << MPU_CTRL_HFNMIENA_Pos) /*!< MPU CTRL: HFNMIENA Mask */ #define MPU_CTRL_ENABLE_Pos 0 /*!< MPU CTRL: ENABLE Position */ #define MPU_CTRL_ENABLE_Msk (1UL /*<< MPU_CTRL_ENABLE_Pos*/) /*!< MPU CTRL: ENABLE Mask */ /* MPU Region Number Register */ #define MPU_RNR_REGION_Pos 0 /*!< MPU RNR: REGION Position */ #define MPU_RNR_REGION_Msk (0xFFUL /*<< MPU_RNR_REGION_Pos*/) /*!< MPU RNR: REGION Mask */ /* MPU Region Base Address Register */ #define MPU_RBAR_ADDR_Pos 5 /*!< MPU RBAR: ADDR Position */ #define MPU_RBAR_ADDR_Msk (0x7FFFFFFUL << MPU_RBAR_ADDR_Pos) /*!< MPU RBAR: ADDR Mask */ #define MPU_RBAR_VALID_Pos 4 /*!< MPU RBAR: VALID Position */ #define MPU_RBAR_VALID_Msk (1UL << MPU_RBAR_VALID_Pos) /*!< MPU RBAR: VALID Mask */ #define MPU_RBAR_REGION_Pos 0 /*!< MPU RBAR: REGION Position */ #define MPU_RBAR_REGION_Msk (0xFUL /*<< MPU_RBAR_REGION_Pos*/) /*!< MPU RBAR: REGION Mask */ /* MPU Region Attribute and Size Register */ #define MPU_RASR_ATTRS_Pos 16 /*!< MPU RASR: MPU Region Attribute field Position */ #define MPU_RASR_ATTRS_Msk (0xFFFFUL << MPU_RASR_ATTRS_Pos) /*!< MPU RASR: MPU Region Attribute field Mask */ #define MPU_RASR_XN_Pos 28 /*!< MPU RASR: ATTRS.XN Position */ #define MPU_RASR_XN_Msk (1UL << MPU_RASR_XN_Pos) /*!< MPU RASR: ATTRS.XN Mask */ #define MPU_RASR_AP_Pos 24 /*!< MPU RASR: ATTRS.AP Position */ #define MPU_RASR_AP_Msk (0x7UL << MPU_RASR_AP_Pos) /*!< MPU RASR: ATTRS.AP Mask */ #define MPU_RASR_TEX_Pos 19 /*!< MPU RASR: ATTRS.TEX Position */ #define MPU_RASR_TEX_Msk (0x7UL << MPU_RASR_TEX_Pos) /*!< MPU RASR: ATTRS.TEX Mask */ #define MPU_RASR_S_Pos 18 /*!< MPU RASR: ATTRS.S Position */ #define MPU_RASR_S_Msk (1UL << MPU_RASR_S_Pos) /*!< MPU RASR: ATTRS.S Mask */ #define MPU_RASR_C_Pos 17 /*!< MPU RASR: ATTRS.C Position */ #define MPU_RASR_C_Msk (1UL << MPU_RASR_C_Pos) /*!< MPU RASR: ATTRS.C Mask */ #define MPU_RASR_B_Pos 16 /*!< MPU RASR: ATTRS.B Position */ #define MPU_RASR_B_Msk (1UL << MPU_RASR_B_Pos) /*!< MPU RASR: ATTRS.B Mask */ #define MPU_RASR_SRD_Pos 8 /*!< MPU RASR: Sub-Region Disable Position */ #define MPU_RASR_SRD_Msk (0xFFUL << MPU_RASR_SRD_Pos) /*!< MPU RASR: Sub-Region Disable Mask */ #define MPU_RASR_SIZE_Pos 1 /*!< MPU RASR: Region Size Field Position */ #define MPU_RASR_SIZE_Msk (0x1FUL << MPU_RASR_SIZE_Pos) /*!< MPU RASR: Region Size Field Mask */ #define MPU_RASR_ENABLE_Pos 0 /*!< MPU RASR: Region enable bit Position */ #define MPU_RASR_ENABLE_Msk (1UL /*<< MPU_RASR_ENABLE_Pos*/) /*!< MPU RASR: Region enable bit Disable Mask */ /*@} end of group CMSIS_MPU */ #endif /** \ingroup CMSIS_core_register \defgroup CMSIS_CoreDebug Core Debug Registers (CoreDebug) \brief Type definitions for the Core Debug Registers @{ */ /** \brief Structure type to access the Core Debug Register (CoreDebug). */ typedef struct { __IO uint32_t DHCSR; /*!< Offset: 0x000 (R/W) Debug Halting Control and Status Register */ __O uint32_t DCRSR; /*!< Offset: 0x004 ( /W) Debug Core Register Selector Register */ __IO uint32_t DCRDR; /*!< Offset: 0x008 (R/W) Debug Core Register Data Register */ __IO uint32_t DEMCR; /*!< Offset: 0x00C (R/W) Debug Exception and Monitor Control Register */ } CoreDebug_Type; /* Debug Halting Control and Status Register */ #define CoreDebug_DHCSR_DBGKEY_Pos 16 /*!< CoreDebug DHCSR: DBGKEY Position */ #define CoreDebug_DHCSR_DBGKEY_Msk (0xFFFFUL << CoreDebug_DHCSR_DBGKEY_Pos) /*!< CoreDebug DHCSR: DBGKEY Mask */ #define CoreDebug_DHCSR_S_RESET_ST_Pos 25 /*!< CoreDebug DHCSR: S_RESET_ST Position */ #define CoreDebug_DHCSR_S_RESET_ST_Msk (1UL << CoreDebug_DHCSR_S_RESET_ST_Pos) /*!< CoreDebug DHCSR: S_RESET_ST Mask */ #define CoreDebug_DHCSR_S_RETIRE_ST_Pos 24 /*!< CoreDebug DHCSR: S_RETIRE_ST Position */ #define CoreDebug_DHCSR_S_RETIRE_ST_Msk (1UL << CoreDebug_DHCSR_S_RETIRE_ST_Pos) /*!< CoreDebug DHCSR: S_RETIRE_ST Mask */ #define CoreDebug_DHCSR_S_LOCKUP_Pos 19 /*!< CoreDebug DHCSR: S_LOCKUP Position */ #define CoreDebug_DHCSR_S_LOCKUP_Msk (1UL << CoreDebug_DHCSR_S_LOCKUP_Pos) /*!< CoreDebug DHCSR: S_LOCKUP Mask */ #define CoreDebug_DHCSR_S_SLEEP_Pos 18 /*!< CoreDebug DHCSR: S_SLEEP Position */ #define CoreDebug_DHCSR_S_SLEEP_Msk (1UL << CoreDebug_DHCSR_S_SLEEP_Pos) /*!< CoreDebug DHCSR: S_SLEEP Mask */ #define CoreDebug_DHCSR_S_HALT_Pos 17 /*!< CoreDebug DHCSR: S_HALT Position */ #define CoreDebug_DHCSR_S_HALT_Msk (1UL << CoreDebug_DHCSR_S_HALT_Pos) /*!< CoreDebug DHCSR: S_HALT Mask */ #define CoreDebug_DHCSR_S_REGRDY_Pos 16 /*!< CoreDebug DHCSR: S_REGRDY Position */ #define CoreDebug_DHCSR_S_REGRDY_Msk (1UL << CoreDebug_DHCSR_S_REGRDY_Pos) /*!< CoreDebug DHCSR: S_REGRDY Mask */ #define CoreDebug_DHCSR_C_SNAPSTALL_Pos 5 /*!< CoreDebug DHCSR: C_SNAPSTALL Position */ #define CoreDebug_DHCSR_C_SNAPSTALL_Msk (1UL << CoreDebug_DHCSR_C_SNAPSTALL_Pos) /*!< CoreDebug DHCSR: C_SNAPSTALL Mask */ #define CoreDebug_DHCSR_C_MASKINTS_Pos 3 /*!< CoreDebug DHCSR: C_MASKINTS Position */ #define CoreDebug_DHCSR_C_MASKINTS_Msk (1UL << CoreDebug_DHCSR_C_MASKINTS_Pos) /*!< CoreDebug DHCSR: C_MASKINTS Mask */ #define CoreDebug_DHCSR_C_STEP_Pos 2 /*!< CoreDebug DHCSR: C_STEP Position */ #define CoreDebug_DHCSR_C_STEP_Msk (1UL << CoreDebug_DHCSR_C_STEP_Pos) /*!< CoreDebug DHCSR: C_STEP Mask */ #define CoreDebug_DHCSR_C_HALT_Pos 1 /*!< CoreDebug DHCSR: C_HALT Position */ #define CoreDebug_DHCSR_C_HALT_Msk (1UL << CoreDebug_DHCSR_C_HALT_Pos) /*!< CoreDebug DHCSR: C_HALT Mask */ #define CoreDebug_DHCSR_C_DEBUGEN_Pos 0 /*!< CoreDebug DHCSR: C_DEBUGEN Position */ #define CoreDebug_DHCSR_C_DEBUGEN_Msk (1UL /*<< CoreDebug_DHCSR_C_DEBUGEN_Pos*/) /*!< CoreDebug DHCSR: C_DEBUGEN Mask */ /* Debug Core Register Selector Register */ #define CoreDebug_DCRSR_REGWnR_Pos 16 /*!< CoreDebug DCRSR: REGWnR Position */ #define CoreDebug_DCRSR_REGWnR_Msk (1UL << CoreDebug_DCRSR_REGWnR_Pos) /*!< CoreDebug DCRSR: REGWnR Mask */ #define CoreDebug_DCRSR_REGSEL_Pos 0 /*!< CoreDebug DCRSR: REGSEL Position */ #define CoreDebug_DCRSR_REGSEL_Msk (0x1FUL /*<< CoreDebug_DCRSR_REGSEL_Pos*/) /*!< CoreDebug DCRSR: REGSEL Mask */ /* Debug Exception and Monitor Control Register */ #define CoreDebug_DEMCR_TRCENA_Pos 24 /*!< CoreDebug DEMCR: TRCENA Position */ #define CoreDebug_DEMCR_TRCENA_Msk (1UL << CoreDebug_DEMCR_TRCENA_Pos) /*!< CoreDebug DEMCR: TRCENA Mask */ #define CoreDebug_DEMCR_MON_REQ_Pos 19 /*!< CoreDebug DEMCR: MON_REQ Position */ #define CoreDebug_DEMCR_MON_REQ_Msk (1UL << CoreDebug_DEMCR_MON_REQ_Pos) /*!< CoreDebug DEMCR: MON_REQ Mask */ #define CoreDebug_DEMCR_MON_STEP_Pos 18 /*!< CoreDebug DEMCR: MON_STEP Position */ #define CoreDebug_DEMCR_MON_STEP_Msk (1UL << CoreDebug_DEMCR_MON_STEP_Pos) /*!< CoreDebug DEMCR: MON_STEP Mask */ #define CoreDebug_DEMCR_MON_PEND_Pos 17 /*!< CoreDebug DEMCR: MON_PEND Position */ #define CoreDebug_DEMCR_MON_PEND_Msk (1UL << CoreDebug_DEMCR_MON_PEND_Pos) /*!< CoreDebug DEMCR: MON_PEND Mask */ #define CoreDebug_DEMCR_MON_EN_Pos 16 /*!< CoreDebug DEMCR: MON_EN Position */ #define CoreDebug_DEMCR_MON_EN_Msk (1UL << CoreDebug_DEMCR_MON_EN_Pos) /*!< CoreDebug DEMCR: MON_EN Mask */ #define CoreDebug_DEMCR_VC_HARDERR_Pos 10 /*!< CoreDebug DEMCR: VC_HARDERR Position */ #define CoreDebug_DEMCR_VC_HARDERR_Msk (1UL << CoreDebug_DEMCR_VC_HARDERR_Pos) /*!< CoreDebug DEMCR: VC_HARDERR Mask */ #define CoreDebug_DEMCR_VC_INTERR_Pos 9 /*!< CoreDebug DEMCR: VC_INTERR Position */ #define CoreDebug_DEMCR_VC_INTERR_Msk (1UL << CoreDebug_DEMCR_VC_INTERR_Pos) /*!< CoreDebug DEMCR: VC_INTERR Mask */ #define CoreDebug_DEMCR_VC_BUSERR_Pos 8 /*!< CoreDebug DEMCR: VC_BUSERR Position */ #define CoreDebug_DEMCR_VC_BUSERR_Msk (1UL << CoreDebug_DEMCR_VC_BUSERR_Pos) /*!< CoreDebug DEMCR: VC_BUSERR Mask */ #define CoreDebug_DEMCR_VC_STATERR_Pos 7 /*!< CoreDebug DEMCR: VC_STATERR Position */ #define CoreDebug_DEMCR_VC_STATERR_Msk (1UL << CoreDebug_DEMCR_VC_STATERR_Pos) /*!< CoreDebug DEMCR: VC_STATERR Mask */ #define CoreDebug_DEMCR_VC_CHKERR_Pos 6 /*!< CoreDebug DEMCR: VC_CHKERR Position */ #define CoreDebug_DEMCR_VC_CHKERR_Msk (1UL << CoreDebug_DEMCR_VC_CHKERR_Pos) /*!< CoreDebug DEMCR: VC_CHKERR Mask */ #define CoreDebug_DEMCR_VC_NOCPERR_Pos 5 /*!< CoreDebug DEMCR: VC_NOCPERR Position */ #define CoreDebug_DEMCR_VC_NOCPERR_Msk (1UL << CoreDebug_DEMCR_VC_NOCPERR_Pos) /*!< CoreDebug DEMCR: VC_NOCPERR Mask */ #define CoreDebug_DEMCR_VC_MMERR_Pos 4 /*!< CoreDebug DEMCR: VC_MMERR Position */ #define CoreDebug_DEMCR_VC_MMERR_Msk (1UL << CoreDebug_DEMCR_VC_MMERR_Pos) /*!< CoreDebug DEMCR: VC_MMERR Mask */ #define CoreDebug_DEMCR_VC_CORERESET_Pos 0 /*!< CoreDebug DEMCR: VC_CORERESET Position */ #define CoreDebug_DEMCR_VC_CORERESET_Msk (1UL /*<< CoreDebug_DEMCR_VC_CORERESET_Pos*/) /*!< CoreDebug DEMCR: VC_CORERESET Mask */ /*@} end of group CMSIS_CoreDebug */ /** \ingroup CMSIS_core_register \defgroup CMSIS_core_base Core Definitions \brief Definitions for base addresses, unions, and structures. @{ */ /* Memory mapping of Cortex-M3 Hardware */ #define SCS_BASE (0xE000E000UL) /*!< System Control Space Base Address */ #define ITM_BASE (0xE0000000UL) /*!< ITM Base Address */ #define DWT_BASE (0xE0001000UL) /*!< DWT Base Address */ #define TPI_BASE (0xE0040000UL) /*!< TPI Base Address */ #define CoreDebug_BASE (0xE000EDF0UL) /*!< Core Debug Base Address */ #define SysTick_BASE (SCS_BASE + 0x0010UL) /*!< SysTick Base Address */ #define NVIC_BASE (SCS_BASE + 0x0100UL) /*!< NVIC Base Address */ #define SCB_BASE (SCS_BASE + 0x0D00UL) /*!< System Control Block Base Address */ #define SCnSCB ((SCnSCB_Type *) SCS_BASE ) /*!< System control Register not in SCB */ #define SCB ((SCB_Type *) SCB_BASE ) /*!< SCB configuration struct */ #define SysTick ((SysTick_Type *) SysTick_BASE ) /*!< SysTick configuration struct */ #define NVIC ((NVIC_Type *) NVIC_BASE ) /*!< NVIC configuration struct */ #define ITM ((ITM_Type *) ITM_BASE ) /*!< ITM configuration struct */ #define DWT ((DWT_Type *) DWT_BASE ) /*!< DWT configuration struct */ #define TPI ((TPI_Type *) TPI_BASE ) /*!< TPI configuration struct */ #define CoreDebug ((CoreDebug_Type *) CoreDebug_BASE) /*!< Core Debug configuration struct */ #if (__MPU_PRESENT == 1) #define MPU_BASE (SCS_BASE + 0x0D90UL) /*!< Memory Protection Unit */ #define MPU ((MPU_Type *) MPU_BASE ) /*!< Memory Protection Unit */ #endif /*@} */ /******************************************************************************* * Hardware Abstraction Layer Core Function Interface contains: - Core NVIC Functions - Core SysTick Functions - Core Debug Functions - Core Register Access Functions ******************************************************************************/ /** \defgroup CMSIS_Core_FunctionInterface Functions and Instructions Reference */ /* ########################## NVIC functions #################################### */ /** \ingroup CMSIS_Core_FunctionInterface \defgroup CMSIS_Core_NVICFunctions NVIC Functions \brief Functions that manage interrupts and exceptions via the NVIC. @{ */ /** \brief Set Priority Grouping The function sets the priority grouping field using the required unlock sequence. The parameter PriorityGroup is assigned to the field SCB->AIRCR [10:8] PRIGROUP field. Only values from 0..7 are used. In case of a conflict between priority grouping and available priority bits (__NVIC_PRIO_BITS), the smallest possible priority group is set. \param [in] PriorityGroup Priority grouping field. */ __STATIC_INLINE void NVIC_SetPriorityGrouping(uint32_t PriorityGroup) { uint32_t reg_value; uint32_t PriorityGroupTmp = (PriorityGroup & (uint32_t)0x07UL); /* only values 0..7 are used */ reg_value = SCB->AIRCR; /* read old register configuration */ reg_value &= ~((uint32_t)(SCB_AIRCR_VECTKEY_Msk | SCB_AIRCR_PRIGROUP_Msk)); /* clear bits to change */ reg_value = (reg_value | ((uint32_t)0x5FAUL << SCB_AIRCR_VECTKEY_Pos) | (PriorityGroupTmp << 8) ); /* Insert write key and priorty group */ SCB->AIRCR = reg_value; } /** \brief Get Priority Grouping The function reads the priority grouping field from the NVIC Interrupt Controller. \return Priority grouping field (SCB->AIRCR [10:8] PRIGROUP field). */ __STATIC_INLINE uint32_t NVIC_GetPriorityGrouping(void) { return ((uint32_t)((SCB->AIRCR & SCB_AIRCR_PRIGROUP_Msk) >> SCB_AIRCR_PRIGROUP_Pos)); } /** \brief Enable External Interrupt The function enables a device-specific interrupt in the NVIC interrupt controller. \param [in] IRQn External interrupt number. Value cannot be negative. */ __STATIC_INLINE void NVIC_EnableIRQ(IRQn_Type IRQn) { NVIC->ISER[(((uint32_t)(int32_t)IRQn) >> 5UL)] = (uint32_t)(1UL << (((uint32_t)(int32_t)IRQn) & 0x1FUL)); } /** \brief Disable External Interrupt The function disables a device-specific interrupt in the NVIC interrupt controller. \param [in] IRQn External interrupt number. Value cannot be negative. */ __STATIC_INLINE void NVIC_DisableIRQ(IRQn_Type IRQn) { NVIC->ICER[(((uint32_t)(int32_t)IRQn) >> 5UL)] = (uint32_t)(1UL << (((uint32_t)(int32_t)IRQn) & 0x1FUL)); } /** \brief Get Pending Interrupt The function reads the pending register in the NVIC and returns the pending bit for the specified interrupt. \param [in] IRQn Interrupt number. \return 0 Interrupt status is not pending. \return 1 Interrupt status is pending. */ __STATIC_INLINE uint32_t NVIC_GetPendingIRQ(IRQn_Type IRQn) { return((uint32_t)(((NVIC->ISPR[(((uint32_t)(int32_t)IRQn) >> 5UL)] & (1UL << (((uint32_t)(int32_t)IRQn) & 0x1FUL))) != 0UL) ? 1UL : 0UL)); } /** \brief Set Pending Interrupt The function sets the pending bit of an external interrupt. \param [in] IRQn Interrupt number. Value cannot be negative. */ __STATIC_INLINE void NVIC_SetPendingIRQ(IRQn_Type IRQn) { NVIC->ISPR[(((uint32_t)(int32_t)IRQn) >> 5UL)] = (uint32_t)(1UL << (((uint32_t)(int32_t)IRQn) & 0x1FUL)); } /** \brief Clear Pending Interrupt The function clears the pending bit of an external interrupt. \param [in] IRQn External interrupt number. Value cannot be negative. */ __STATIC_INLINE void NVIC_ClearPendingIRQ(IRQn_Type IRQn) { NVIC->ICPR[(((uint32_t)(int32_t)IRQn) >> 5UL)] = (uint32_t)(1UL << (((uint32_t)(int32_t)IRQn) & 0x1FUL)); } /** \brief Get Active Interrupt The function reads the active register in NVIC and returns the active bit. \param [in] IRQn Interrupt number. \return 0 Interrupt status is not active. \return 1 Interrupt status is active. */ __STATIC_INLINE uint32_t NVIC_GetActive(IRQn_Type IRQn) { return((uint32_t)(((NVIC->IABR[(((uint32_t)(int32_t)IRQn) >> 5UL)] & (1UL << (((uint32_t)(int32_t)IRQn) & 0x1FUL))) != 0UL) ? 1UL : 0UL)); } /** \brief Set Interrupt Priority The function sets the priority of an interrupt. \note The priority cannot be set for every core interrupt. \param [in] IRQn Interrupt number. \param [in] priority Priority to set. */ __STATIC_INLINE void NVIC_SetPriority(IRQn_Type IRQn, uint32_t priority) { if((int32_t)IRQn < 0) { SCB->SHP[(((uint32_t)(int32_t)IRQn) & 0xFUL)-4UL] = (uint8_t)((priority << (8 - __NVIC_PRIO_BITS)) & (uint32_t)0xFFUL); } else { NVIC->IP[((uint32_t)(int32_t)IRQn)] = (uint8_t)((priority << (8 - __NVIC_PRIO_BITS)) & (uint32_t)0xFFUL); } } /** \brief Get Interrupt Priority The function reads the priority of an interrupt. The interrupt number can be positive to specify an external (device specific) interrupt, or negative to specify an internal (core) interrupt. \param [in] IRQn Interrupt number. \return Interrupt Priority. Value is aligned automatically to the implemented priority bits of the microcontroller. */ __STATIC_INLINE uint32_t NVIC_GetPriority(IRQn_Type IRQn) { if((int32_t)IRQn < 0) { return(((uint32_t)SCB->SHP[(((uint32_t)(int32_t)IRQn) & 0xFUL)-4UL] >> (8 - __NVIC_PRIO_BITS))); } else { return(((uint32_t)NVIC->IP[((uint32_t)(int32_t)IRQn)] >> (8 - __NVIC_PRIO_BITS))); } } /** \brief Encode Priority The function encodes the priority for an interrupt with the given priority group, preemptive priority value, and subpriority value. In case of a conflict between priority grouping and available priority bits (__NVIC_PRIO_BITS), the smallest possible priority group is set. \param [in] PriorityGroup Used priority group. \param [in] PreemptPriority Preemptive priority value (starting from 0). \param [in] SubPriority Subpriority value (starting from 0). \return Encoded priority. Value can be used in the function \ref NVIC_SetPriority(). */ __STATIC_INLINE uint32_t NVIC_EncodePriority (uint32_t PriorityGroup, uint32_t PreemptPriority, uint32_t SubPriority) { uint32_t PriorityGroupTmp = (PriorityGroup & (uint32_t)0x07UL); /* only values 0..7 are used */ uint32_t PreemptPriorityBits; uint32_t SubPriorityBits; PreemptPriorityBits = ((7UL - PriorityGroupTmp) > (uint32_t)(__NVIC_PRIO_BITS)) ? (uint32_t)(__NVIC_PRIO_BITS) : (uint32_t)(7UL - PriorityGroupTmp); SubPriorityBits = ((PriorityGroupTmp + (uint32_t)(__NVIC_PRIO_BITS)) < (uint32_t)7UL) ? (uint32_t)0UL : (uint32_t)((PriorityGroupTmp - 7UL) + (uint32_t)(__NVIC_PRIO_BITS)); return ( ((PreemptPriority & (uint32_t)((1UL << (PreemptPriorityBits)) - 1UL)) << SubPriorityBits) | ((SubPriority & (uint32_t)((1UL << (SubPriorityBits )) - 1UL))) ); } /** \brief Decode Priority The function decodes an interrupt priority value with a given priority group to preemptive priority value and subpriority value. In case of a conflict between priority grouping and available priority bits (__NVIC_PRIO_BITS) the smallest possible priority group is set. \param [in] Priority Priority value, which can be retrieved with the function \ref NVIC_GetPriority(). \param [in] PriorityGroup Used priority group. \param [out] pPreemptPriority Preemptive priority value (starting from 0). \param [out] pSubPriority Subpriority value (starting from 0). */ __STATIC_INLINE void NVIC_DecodePriority (uint32_t Priority, uint32_t PriorityGroup, uint32_t* pPreemptPriority, uint32_t* pSubPriority) { uint32_t PriorityGroupTmp = (PriorityGroup & (uint32_t)0x07UL); /* only values 0..7 are used */ uint32_t PreemptPriorityBits; uint32_t SubPriorityBits; PreemptPriorityBits = ((7UL - PriorityGroupTmp) > (uint32_t)(__NVIC_PRIO_BITS)) ? (uint32_t)(__NVIC_PRIO_BITS) : (uint32_t)(7UL - PriorityGroupTmp); SubPriorityBits = ((PriorityGroupTmp + (uint32_t)(__NVIC_PRIO_BITS)) < (uint32_t)7UL) ? (uint32_t)0UL : (uint32_t)((PriorityGroupTmp - 7UL) + (uint32_t)(__NVIC_PRIO_BITS)); *pPreemptPriority = (Priority >> SubPriorityBits) & (uint32_t)((1UL << (PreemptPriorityBits)) - 1UL); *pSubPriority = (Priority ) & (uint32_t)((1UL << (SubPriorityBits )) - 1UL); } /** \brief System Reset The function initiates a system reset request to reset the MCU. */ __STATIC_INLINE void NVIC_SystemReset(void) { __DSB(); /* Ensure all outstanding memory accesses included buffered write are completed before reset */ SCB->AIRCR = (uint32_t)((0x5FAUL << SCB_AIRCR_VECTKEY_Pos) | (SCB->AIRCR & SCB_AIRCR_PRIGROUP_Msk) | SCB_AIRCR_SYSRESETREQ_Msk ); /* Keep priority group unchanged */ __DSB(); /* Ensure completion of memory access */ while(1) { __NOP(); } /* wait until reset */ } /*@} end of CMSIS_Core_NVICFunctions */ /* ################################## SysTick function ############################################ */ /** \ingroup CMSIS_Core_FunctionInterface \defgroup CMSIS_Core_SysTickFunctions SysTick Functions \brief Functions that configure the System. @{ */ #if (__Vendor_SysTickConfig == 0) /** \brief System Tick Configuration The function initializes the System Timer and its interrupt, and starts the System Tick Timer. Counter is in free running mode to generate periodic interrupts. \param [in] ticks Number of ticks between two interrupts. \return 0 Function succeeded. \return 1 Function failed. \note When the variable __Vendor_SysTickConfig is set to 1, then the function SysTick_Config is not included. In this case, the file device.h must contain a vendor-specific implementation of this function. */ __STATIC_INLINE uint32_t SysTick_Config(uint32_t ticks) { if ((ticks - 1UL) > SysTick_LOAD_RELOAD_Msk) { return (1UL); } /* Reload value impossible */ SysTick->LOAD = (uint32_t)(ticks - 1UL); /* set reload register */ NVIC_SetPriority (SysTick_IRQn, (1UL << __NVIC_PRIO_BITS) - 1UL); /* set Priority for Systick Interrupt */ SysTick->VAL = 0UL; /* Load the SysTick Counter Value */ SysTick->CTRL = SysTick_CTRL_CLKSOURCE_Msk | SysTick_CTRL_TICKINT_Msk | SysTick_CTRL_ENABLE_Msk; /* Enable SysTick IRQ and SysTick Timer */ return (0UL); /* Function successful */ } #endif /*@} end of CMSIS_Core_SysTickFunctions */ /* ##################################### Debug In/Output function ########################################### */ /** \ingroup CMSIS_Core_FunctionInterface \defgroup CMSIS_core_DebugFunctions ITM Functions \brief Functions that access the ITM debug interface. @{ */ extern volatile int32_t ITM_RxBuffer; /*!< External variable to receive characters. */ #define ITM_RXBUFFER_EMPTY 0x5AA55AA5 /*!< Value identifying \ref ITM_RxBuffer is ready for next character. */ /** \brief ITM Send Character The function transmits a character via the ITM channel 0, and \li Just returns when no debugger is connected that has booked the output. \li Is blocking when a debugger is connected, but the previous character sent has not been transmitted. \param [in] ch Character to transmit. \returns Character to transmit. */ __STATIC_INLINE uint32_t ITM_SendChar (uint32_t ch) { if (((ITM->TCR & ITM_TCR_ITMENA_Msk) != 0UL) && /* ITM enabled */ ((ITM->TER & 1UL ) != 0UL) ) /* ITM Port #0 enabled */ { while (ITM->PORT[0].u32 == 0UL) { __NOP(); } ITM->PORT[0].u8 = (uint8_t)ch; } return (ch); } /** \brief ITM Receive Character The function inputs a character via the external variable \ref ITM_RxBuffer. \return Received character. \return -1 No character pending. */ __STATIC_INLINE int32_t ITM_ReceiveChar (void) { int32_t ch = -1; /* no character available */ if (ITM_RxBuffer != ITM_RXBUFFER_EMPTY) { ch = ITM_RxBuffer; ITM_RxBuffer = ITM_RXBUFFER_EMPTY; /* ready for next character */ } return (ch); } /** \brief ITM Check Character The function checks whether a character is pending for reading in the variable \ref ITM_RxBuffer. \return 0 No character available. \return 1 Character available. */ __STATIC_INLINE int32_t ITM_CheckChar (void) { if (ITM_RxBuffer == ITM_RXBUFFER_EMPTY) { return (0); /* no character available */ } else { return (1); /* character available */ } } /*@} end of CMSIS_core_DebugFunctions */ #ifdef __cplusplus } #endif #endif /* __CORE_SC300_H_DEPENDANT */ #endif /* __CMSIS_GENERIC */ ================================================ FILE: Zelig/mbed/TARGET_NUCLEO_F091RC/hal_tick.h ================================================ /** ****************************************************************************** * @file hal_tick.h * @author MCD Application Team * @brief Initialization of HAL tick ****************************************************************************** * @attention * *

© COPYRIGHT(c) 2015 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. * ****************************************************************************** */ #ifndef __HAL_TICK_H #define __HAL_TICK_H #ifdef __cplusplus extern "C" { #endif #include "stm32f0xx.h" #include "cmsis_nvic.h" #define TIM_MST TIM2 #define TIM_MST_IRQ TIM2_IRQn #define TIM_MST_RCC __TIM2_CLK_ENABLE() #define TIM_MST_RESET_ON __TIM2_FORCE_RESET() #define TIM_MST_RESET_OFF __TIM2_RELEASE_RESET() #define HAL_TICK_DELAY (1000) // 1 ms #ifdef __cplusplus } #endif #endif // __HAL_TICK_H /************************ (C) COPYRIGHT STMicroelectronics *****END OF FILE****/ ================================================ FILE: Zelig/mbed/TARGET_NUCLEO_F091RC/stm32_hal_legacy.h ================================================ /** ****************************************************************************** * @file stm32_hal_legacy.h * @author MCD Application Team * @version V1.3.0 * @date 26-June-2015 * @brief This file contains aliases definition for the STM32Cube HAL constants * macros and functions maintained for legacy purpose. ****************************************************************************** * @attention * *

© COPYRIGHT(c) 2015 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. * ****************************************************************************** */ /* Define to prevent recursive inclusion -------------------------------------*/ #ifndef __STM32_HAL_LEGACY #define __STM32_HAL_LEGACY #ifdef __cplusplus extern "C" { #endif /* Includes ------------------------------------------------------------------*/ /* Exported types ------------------------------------------------------------*/ /* Exported constants --------------------------------------------------------*/ /** @defgroup HAL_AES_Aliased_Defines HAL CRYP Aliased Defines maintained for legacy purpose * @{ */ #define AES_FLAG_RDERR CRYP_FLAG_RDERR #define AES_FLAG_WRERR CRYP_FLAG_WRERR #define AES_CLEARFLAG_CCF CRYP_CLEARFLAG_CCF #define AES_CLEARFLAG_RDERR CRYP_CLEARFLAG_RDERR #define AES_CLEARFLAG_WRERR CRYP_CLEARFLAG_WRERR /** * @} */ /** @defgroup HAL_ADC_Aliased_Defines HAL ADC Aliased Defines maintained for legacy purpose * @{ */ #define ADC_RESOLUTION12b ADC_RESOLUTION_12B #define ADC_RESOLUTION10b ADC_RESOLUTION_10B #define ADC_RESOLUTION8b ADC_RESOLUTION_8B #define ADC_RESOLUTION6b ADC_RESOLUTION_6B #define OVR_DATA_OVERWRITTEN ADC_OVR_DATA_OVERWRITTEN #define OVR_DATA_PRESERVED ADC_OVR_DATA_PRESERVED #define EOC_SINGLE_CONV ADC_EOC_SINGLE_CONV #define EOC_SEQ_CONV ADC_EOC_SEQ_CONV #define EOC_SINGLE_SEQ_CONV ADC_EOC_SINGLE_SEQ_CONV #define REGULAR_GROUP ADC_REGULAR_GROUP #define INJECTED_GROUP ADC_INJECTED_GROUP #define REGULAR_INJECTED_GROUP ADC_REGULAR_INJECTED_GROUP #define AWD_EVENT ADC_AWD_EVENT #define AWD1_EVENT ADC_AWD1_EVENT #define AWD2_EVENT ADC_AWD2_EVENT #define AWD3_EVENT ADC_AWD3_EVENT #define OVR_EVENT ADC_OVR_EVENT #define JQOVF_EVENT ADC_JQOVF_EVENT #define ALL_CHANNELS ADC_ALL_CHANNELS #define REGULAR_CHANNELS ADC_REGULAR_CHANNELS #define INJECTED_CHANNELS ADC_INJECTED_CHANNELS #define SYSCFG_FLAG_SENSOR_ADC ADC_FLAG_SENSOR #define SYSCFG_FLAG_VREF_ADC ADC_FLAG_VREFINT #define ADC_CLOCKPRESCALER_PCLK_DIV1 ADC_CLOCK_SYNC_PCLK_DIV1 #define ADC_CLOCKPRESCALER_PCLK_DIV2 ADC_CLOCK_SYNC_PCLK_DIV2 #define ADC_CLOCKPRESCALER_PCLK_DIV4 ADC_CLOCK_SYNC_PCLK_DIV4 #define ADC_CLOCKPRESCALER_PCLK_DIV6 ADC_CLOCK_SYNC_PCLK_DIV6 #define ADC_CLOCKPRESCALER_PCLK_DIV8 ADC_CLOCK_SYNC_PCLK_DIV8 #define ADC_EXTERNALTRIG0_T6_TRGO ADC_EXTERNALTRIGCONV_T6_TRGO #define ADC_EXTERNALTRIG1_T21_CC2 ADC_EXTERNALTRIGCONV_T21_CC2 #define ADC_EXTERNALTRIG2_T2_TRGO ADC_EXTERNALTRIGCONV_T2_TRGO #define ADC_EXTERNALTRIG3_T2_CC4 ADC_EXTERNALTRIGCONV_T2_CC4 #define ADC_EXTERNALTRIG4_T22_TRGO ADC_EXTERNALTRIGCONV_T22_TRGO #define ADC_EXTERNALTRIG7_EXT_IT11 ADC_EXTERNALTRIGCONV_EXT_IT11 #define ADC_CLOCK_ASYNC ADC_CLOCK_ASYNC_DIV1 #define ADC_EXTERNALTRIG_EDGE_NONE ADC_EXTERNALTRIGCONVEDGE_NONE #define ADC_EXTERNALTRIG_EDGE_RISING ADC_EXTERNALTRIGCONVEDGE_RISING #define ADC_EXTERNALTRIG_EDGE_FALLING ADC_EXTERNALTRIGCONVEDGE_FALLING #define ADC_EXTERNALTRIG_EDGE_RISINGFALLING ADC_EXTERNALTRIGCONVEDGE_RISINGFALLING /** * @} */ /** @defgroup HAL_CEC_Aliased_Defines HAL CEC Aliased Defines maintained for legacy purpose * @{ */ #define __HAL_CEC_GET_IT __HAL_CEC_GET_FLAG /** * @} */ /** @defgroup HAL_COMP_Aliased_Defines HAL COMP Aliased Defines maintained for legacy purpose * @{ */ #define COMP_WINDOWMODE_DISABLED COMP_WINDOWMODE_DISABLE #define COMP_WINDOWMODE_ENABLED COMP_WINDOWMODE_ENABLE #define COMP_EXTI_LINE_COMP1_EVENT COMP_EXTI_LINE_COMP1 #define COMP_EXTI_LINE_COMP2_EVENT COMP_EXTI_LINE_COMP2 /** * @} */ /** @defgroup HAL_CRC_Aliased_Defines HAL CRC Aliased Defines maintained for legacy purpose * @{ */ #define CRC_OUTPUTDATA_INVERSION_DISABLED CRC_OUTPUTDATA_INVERSION_DISABLE #define CRC_OUTPUTDATA_INVERSION_ENABLED CRC_OUTPUTDATA_INVERSION_ENABLE /** * @} */ /** @defgroup HAL_DAC_Aliased_Defines HAL DAC Aliased Defines maintained for legacy purpose * @{ */ #define DAC1_CHANNEL_1 DAC_CHANNEL_1 #define DAC1_CHANNEL_2 DAC_CHANNEL_2 #define DAC2_CHANNEL_1 DAC_CHANNEL_1 #define DAC_WAVE_NONE ((uint32_t)0x00000000) #define DAC_WAVE_NOISE ((uint32_t)DAC_CR_WAVE1_0) #define DAC_WAVE_TRIANGLE ((uint32_t)DAC_CR_WAVE1_1) #define DAC_WAVEGENERATION_NONE DAC_WAVE_NONE #define DAC_WAVEGENERATION_NOISE DAC_WAVE_NOISE #define DAC_WAVEGENERATION_TRIANGLE DAC_WAVE_TRIANGLE /** * @} */ /** @defgroup HAL_DMA_Aliased_Defines HAL DMA Aliased Defines maintained for legacy purpose * @{ */ #define HAL_REMAPDMA_ADC_DMA_CH2 DMA_REMAP_ADC_DMA_CH2 #define HAL_REMAPDMA_USART1_TX_DMA_CH4 DMA_REMAP_USART1_TX_DMA_CH4 #define HAL_REMAPDMA_USART1_RX_DMA_CH5 DMA_REMAP_USART1_RX_DMA_CH5 #define HAL_REMAPDMA_TIM16_DMA_CH4 DMA_REMAP_TIM16_DMA_CH4 #define HAL_REMAPDMA_TIM17_DMA_CH2 DMA_REMAP_TIM17_DMA_CH2 #define HAL_REMAPDMA_USART3_DMA_CH32 DMA_REMAP_USART3_DMA_CH32 #define HAL_REMAPDMA_TIM16_DMA_CH6 DMA_REMAP_TIM16_DMA_CH6 #define HAL_REMAPDMA_TIM17_DMA_CH7 DMA_REMAP_TIM17_DMA_CH7 #define HAL_REMAPDMA_SPI2_DMA_CH67 DMA_REMAP_SPI2_DMA_CH67 #define HAL_REMAPDMA_USART2_DMA_CH67 DMA_REMAP_USART2_DMA_CH67 #define HAL_REMAPDMA_USART3_DMA_CH32 DMA_REMAP_USART3_DMA_CH32 #define HAL_REMAPDMA_I2C1_DMA_CH76 DMA_REMAP_I2C1_DMA_CH76 #define HAL_REMAPDMA_TIM1_DMA_CH6 DMA_REMAP_TIM1_DMA_CH6 #define HAL_REMAPDMA_TIM2_DMA_CH7 DMA_REMAP_TIM2_DMA_CH7 #define HAL_REMAPDMA_TIM3_DMA_CH6 DMA_REMAP_TIM3_DMA_CH6 #define IS_HAL_REMAPDMA IS_DMA_REMAP #define __HAL_REMAPDMA_CHANNEL_ENABLE __HAL_DMA_REMAP_CHANNEL_ENABLE #define __HAL_REMAPDMA_CHANNEL_DISABLE __HAL_DMA_REMAP_CHANNEL_DISABLE /** * @} */ /** @defgroup HAL_FLASH_Aliased_Defines HAL FLASH Aliased Defines maintained for legacy purpose * @{ */ #define TYPEPROGRAM_BYTE FLASH_TYPEPROGRAM_BYTE #define TYPEPROGRAM_HALFWORD FLASH_TYPEPROGRAM_HALFWORD #define TYPEPROGRAM_WORD FLASH_TYPEPROGRAM_WORD #define TYPEPROGRAM_DOUBLEWORD FLASH_TYPEPROGRAM_DOUBLEWORD #define TYPEERASE_SECTORS FLASH_TYPEERASE_SECTORS #define TYPEERASE_PAGES FLASH_TYPEERASE_PAGES #define TYPEERASE_PAGEERASE FLASH_TYPEERASE_PAGES #define TYPEERASE_MASSERASE FLASH_TYPEERASE_MASSERASE #define WRPSTATE_DISABLE OB_WRPSTATE_DISABLE #define WRPSTATE_ENABLE OB_WRPSTATE_ENABLE #define HAL_FLASH_TIMEOUT_VALUE FLASH_TIMEOUT_VALUE #define OBEX_PCROP OPTIONBYTE_PCROP #define OBEX_BOOTCONFIG OPTIONBYTE_BOOTCONFIG #define PCROPSTATE_DISABLE OB_PCROP_STATE_DISABLE #define PCROPSTATE_ENABLE OB_PCROP_STATE_ENABLE #define TYPEERASEDATA_BYTE FLASH_TYPEERASEDATA_BYTE #define TYPEERASEDATA_HALFWORD FLASH_TYPEERASEDATA_HALFWORD #define TYPEERASEDATA_WORD FLASH_TYPEERASEDATA_WORD #define TYPEPROGRAMDATA_BYTE FLASH_TYPEPROGRAMDATA_BYTE #define TYPEPROGRAMDATA_HALFWORD FLASH_TYPEPROGRAMDATA_HALFWORD #define TYPEPROGRAMDATA_WORD FLASH_TYPEPROGRAMDATA_WORD #define TYPEPROGRAMDATA_FASTBYTE FLASH_TYPEPROGRAMDATA_FASTBYTE #define TYPEPROGRAMDATA_FASTHALFWORD FLASH_TYPEPROGRAMDATA_FASTHALFWORD #define TYPEPROGRAMDATA_FASTWORD FLASH_TYPEPROGRAMDATA_FASTWORD #define PAGESIZE FLASH_PAGE_SIZE #define TYPEPROGRAM_FASTBYTE FLASH_TYPEPROGRAM_BYTE #define TYPEPROGRAM_FASTHALFWORD FLASH_TYPEPROGRAM_HALFWORD #define TYPEPROGRAM_FASTWORD FLASH_TYPEPROGRAM_WORD #define VOLTAGE_RANGE_1 FLASH_VOLTAGE_RANGE_1 #define VOLTAGE_RANGE_2 FLASH_VOLTAGE_RANGE_2 #define VOLTAGE_RANGE_3 FLASH_VOLTAGE_RANGE_3 #define VOLTAGE_RANGE_4 FLASH_VOLTAGE_RANGE_4 #define TYPEPROGRAM_FAST FLASH_TYPEPROGRAM_FAST #define TYPEPROGRAM_FAST_AND_LAST FLASH_TYPEPROGRAM_FAST_AND_LAST #define WRPAREA_BANK1_AREAA OB_WRPAREA_BANK1_AREAA #define WRPAREA_BANK1_AREAB OB_WRPAREA_BANK1_AREAB #define WRPAREA_BANK2_AREAA OB_WRPAREA_BANK2_AREAA #define WRPAREA_BANK2_AREAB OB_WRPAREA_BANK2_AREAB #define IWDG_STDBY_FREEZE OB_IWDG_STDBY_FREEZE #define IWDG_STDBY_ACTIVE OB_IWDG_STDBY_RUN #define IWDG_STOP_FREEZE OB_IWDG_STOP_FREEZE #define IWDG_STOP_ACTIVE OB_IWDG_STOP_RUN #define FLASH_ERROR_NONE HAL_FLASH_ERROR_NONE #define FLASH_ERROR_RD HAL_FLASH_ERROR_RD #define FLASH_ERROR_PG HAL_FLASH_ERROR_PROG #define FLASH_ERROR_PGP HAL_FLASH_ERROR_PGS #define FLASH_ERROR_WRP HAL_FLASH_ERROR_WRP #define FLASH_ERROR_OPTV HAL_FLASH_ERROR_OPTV #define FLASH_ERROR_OPTVUSR HAL_FLASH_ERROR_OPTVUSR #define FLASH_ERROR_PROG HAL_FLASH_ERROR_PROG #define FLASH_ERROR_OP HAL_FLASH_ERROR_OPERATION #define FLASH_ERROR_PGA HAL_FLASH_ERROR_PGA #define FLASH_ERROR_SIZE HAL_FLASH_ERROR_SIZE #define FLASH_ERROR_SIZ HAL_FLASH_ERROR_SIZE #define FLASH_ERROR_PGS HAL_FLASH_ERROR_PGS #define FLASH_ERROR_MIS HAL_FLASH_ERROR_MIS #define FLASH_ERROR_FAST HAL_FLASH_ERROR_FAST #define FLASH_ERROR_FWWERR HAL_FLASH_ERROR_FWWERR #define FLASH_ERROR_NOTZERO HAL_FLASH_ERROR_NOTZERO #define FLASH_ERROR_OPERATION HAL_FLASH_ERROR_OPERATION #define FLASH_ERROR_ERS HAL_FLASH_ERROR_ERS #define OB_WDG_SW OB_IWDG_SW #define OB_WDG_HW OB_IWDG_HW /** * @} */ /** @defgroup HAL_SYSCFG_Aliased_Defines HAL SYSCFG Aliased Defines maintained for legacy purpose * @{ */ #define SYSCFG_FASTMODEPLUS_I2C_PB6 I2C_FASTMODEPLUS_PB6 #define SYSCFG_FASTMODEPLUS_I2C_PB7 I2C_FASTMODEPLUS_PB7 #define SYSCFG_FASTMODEPLUS_I2C_PB8 I2C_FASTMODEPLUS_PB8 #define SYSCFG_FASTMODEPLUS_I2C_PB9 I2C_FASTMODEPLUS_PB9 #define SYSCFG_FASTMODEPLUS_I2C1 I2C_FASTMODEPLUS_I2C1 #define SYSCFG_FASTMODEPLUS_I2C2 I2C_FASTMODEPLUS_I2C2 #define SYSCFG_FASTMODEPLUS_I2C3 I2C_FASTMODEPLUS_I2C3 /** * @} */ /** @defgroup LL_FMC_Aliased_Defines LL FMC Aliased Defines maintained for compatibility purpose * @{ */ #if defined(STM32L4) || defined(STM32F7) #define FMC_NAND_PCC_WAIT_FEATURE_DISABLE FMC_NAND_WAIT_FEATURE_DISABLE #define FMC_NAND_PCC_WAIT_FEATURE_ENABLE FMC_NAND_WAIT_FEATURE_ENABLE #define FMC_NAND_PCC_MEM_BUS_WIDTH_8 FMC_NAND_MEM_BUS_WIDTH_8 #define FMC_NAND_PCC_MEM_BUS_WIDTH_16 FMC_NAND_MEM_BUS_WIDTH_16 #else #define FMC_NAND_WAIT_FEATURE_DISABLE FMC_NAND_PCC_WAIT_FEATURE_DISABLE #define FMC_NAND_WAIT_FEATURE_ENABLE FMC_NAND_PCC_WAIT_FEATURE_ENABLE #define FMC_NAND_MEM_BUS_WIDTH_8 FMC_NAND_PCC_MEM_BUS_WIDTH_8 #define FMC_NAND_MEM_BUS_WIDTH_16 FMC_NAND_PCC_MEM_BUS_WIDTH_16 #endif /** * @} */ /** @defgroup LL_FSMC_Aliased_Defines LL FSMC Aliased Defines maintained for legacy purpose * @{ */ #define FSMC_NORSRAM_TYPEDEF FSMC_NORSRAM_TypeDef #define FSMC_NORSRAM_EXTENDED_TYPEDEF FSMC_NORSRAM_EXTENDED_TypeDef /** * @} */ /** @defgroup HAL_GPIO_Aliased_Macros HAL GPIO Aliased Macros maintained for legacy purpose * @{ */ #define GET_GPIO_SOURCE GPIO_GET_INDEX #define GET_GPIO_INDEX GPIO_GET_INDEX #if defined(STM32F4) #define GPIO_AF12_SDMMC GPIO_AF12_SDIO #define GPIO_AF12_SDMMC1 GPIO_AF12_SDIO #endif #if defined(STM32F7) #define GPIO_AF12_SDIO GPIO_AF12_SDMMC1 #define GPIO_AF12_SDMMC GPIO_AF12_SDMMC1 #endif #if defined(STM32L4) #define GPIO_AF12_SDIO GPIO_AF12_SDMMC1 #define GPIO_AF12_SDMMC GPIO_AF12_SDMMC1 #endif #define GPIO_AF0_LPTIM GPIO_AF0_LPTIM1 #define GPIO_AF1_LPTIM GPIO_AF1_LPTIM1 #define GPIO_AF2_LPTIM GPIO_AF2_LPTIM1 /** * @} */ /** @defgroup HAL_HRTIM_Aliased_Macros HAL HRTIM Aliased Macros maintained for legacy purpose * @{ */ #define HRTIM_TIMDELAYEDPROTECTION_DISABLED HRTIM_TIMER_A_B_C_DELAYEDPROTECTION_DISABLED #define HRTIM_TIMDELAYEDPROTECTION_DELAYEDOUT1_EEV68 HRTIM_TIMER_A_B_C_DELAYEDPROTECTION_DELAYEDOUT1_EEV6 #define HRTIM_TIMDELAYEDPROTECTION_DELAYEDOUT2_EEV68 HRTIM_TIMER_A_B_C_DELAYEDPROTECTION_DELAYEDOUT2_EEV6 #define HRTIM_TIMDELAYEDPROTECTION_DELAYEDBOTH_EEV68 HRTIM_TIMER_A_B_C_DELAYEDPROTECTION_DELAYEDBOTH_EEV6 #define HRTIM_TIMDELAYEDPROTECTION_BALANCED_EEV68 HRTIM_TIMER_A_B_C_DELAYEDPROTECTION_BALANCED_EEV6 #define HRTIM_TIMDELAYEDPROTECTION_DELAYEDOUT1_DEEV79 HRTIM_TIMER_A_B_C_DELAYEDPROTECTION_DELAYEDOUT1_DEEV7 #define HRTIM_TIMDELAYEDPROTECTION_DELAYEDOUT2_DEEV79 HRTIM_TIMER_A_B_C_DELAYEDPROTECTION_DELAYEDOUT2_DEEV7 #define HRTIM_TIMDELAYEDPROTECTION_DELAYEDBOTH_EEV79 HRTIM_TIMER_A_B_C_DELAYEDPROTECTION_DELAYEDBOTH_EEV7 #define HRTIM_TIMDELAYEDPROTECTION_BALANCED_EEV79 HRTIM_TIMER_A_B_C_DELAYEDPROTECTION_BALANCED_EEV7 /** * @} */ /** @defgroup HAL_I2C_Aliased_Defines HAL I2C Aliased Defines maintained for legacy purpose * @{ */ #define I2C_DUALADDRESS_DISABLED I2C_DUALADDRESS_DISABLE #define I2C_DUALADDRESS_ENABLED I2C_DUALADDRESS_ENABLE #define I2C_GENERALCALL_DISABLED I2C_GENERALCALL_DISABLE #define I2C_GENERALCALL_ENABLED I2C_GENERALCALL_ENABLE #define I2C_NOSTRETCH_DISABLED I2C_NOSTRETCH_DISABLE #define I2C_NOSTRETCH_ENABLED I2C_NOSTRETCH_ENABLE #define I2C_ANALOGFILTER_ENABLED I2C_ANALOGFILTER_ENABLE #define I2C_ANALOGFILTER_DISABLED I2C_ANALOGFILTER_DISABLE /** * @} */ /** @defgroup HAL_IRDA_Aliased_Defines HAL IRDA Aliased Defines maintained for legacy purpose * @{ */ #define IRDA_ONE_BIT_SAMPLE_DISABLED IRDA_ONE_BIT_SAMPLE_DISABLE #define IRDA_ONE_BIT_SAMPLE_ENABLED IRDA_ONE_BIT_SAMPLE_ENABLE /** * @} */ /** @defgroup HAL_IWDG_Aliased_Defines HAL IWDG Aliased Defines maintained for legacy purpose * @{ */ #define KR_KEY_RELOAD IWDG_KEY_RELOAD #define KR_KEY_ENABLE IWDG_KEY_ENABLE #define KR_KEY_EWA IWDG_KEY_WRITE_ACCESS_ENABLE #define KR_KEY_DWA IWDG_KEY_WRITE_ACCESS_DISABLE /** * @} */ /** @defgroup HAL_LPTIM_Aliased_Defines HAL LPTIM Aliased Defines maintained for legacy purpose * @{ */ #define LPTIM_CLOCKSAMPLETIME_DIRECTTRANSISTION LPTIM_CLOCKSAMPLETIME_DIRECTTRANSITION #define LPTIM_CLOCKSAMPLETIME_2TRANSISTIONS LPTIM_CLOCKSAMPLETIME_2TRANSITIONS #define LPTIM_CLOCKSAMPLETIME_4TRANSISTIONS LPTIM_CLOCKSAMPLETIME_4TRANSITIONS #define LPTIM_CLOCKSAMPLETIME_8TRANSISTIONS LPTIM_CLOCKSAMPLETIME_8TRANSITIONS #define LPTIM_CLOCKPOLARITY_RISINGEDGE LPTIM_CLOCKPOLARITY_RISING #define LPTIM_CLOCKPOLARITY_FALLINGEDGE LPTIM_CLOCKPOLARITY_FALLING #define LPTIM_CLOCKPOLARITY_BOTHEDGES LPTIM_CLOCKPOLARITY_RISING_FALLING #define LPTIM_TRIGSAMPLETIME_2TRANSITION LPTIM_TRIGSAMPLETIME_2TRANSISTIONS #define LPTIM_TRIGSAMPLETIME_4TRANSITION LPTIM_TRIGSAMPLETIME_4TRANSISTIONS #define LPTIM_TRIGSAMPLETIME_8TRANSITION LPTIM_TRIGSAMPLETIME_8TRANSISTIONS /** * @} */ /** @defgroup HAL_NAND_Aliased_Defines HAL NAND Aliased Defines maintained for legacy purpose * @{ */ #define NAND_AddressTypedef NAND_AddressTypeDef #define __ARRAY_ADDRESS ARRAY_ADDRESS #define __ADDR_1st_CYCLE ADDR_1ST_CYCLE #define __ADDR_2nd_CYCLE ADDR_2ND_CYCLE #define __ADDR_3rd_CYCLE ADDR_3RD_CYCLE #define __ADDR_4th_CYCLE ADDR_4TH_CYCLE /** * @} */ /** @defgroup HAL_NOR_Aliased_Defines HAL NOR Aliased Defines maintained for legacy purpose * @{ */ #define NOR_StatusTypedef HAL_NOR_StatusTypeDef #define NOR_SUCCESS HAL_NOR_STATUS_SUCCESS #define NOR_ONGOING HAL_NOR_STATUS_ONGOING #define NOR_ERROR HAL_NOR_STATUS_ERROR #define NOR_TIMEOUT HAL_NOR_STATUS_TIMEOUT #define __NOR_WRITE NOR_WRITE #define __NOR_ADDR_SHIFT NOR_ADDR_SHIFT /** * @} */ /** @defgroup HAL_OPAMP_Aliased_Defines HAL OPAMP Aliased Defines maintained for legacy purpose * @{ */ #define OPAMP_NONINVERTINGINPUT_VP0 OPAMP_NONINVERTINGINPUT_IO0 #define OPAMP_NONINVERTINGINPUT_VP1 OPAMP_NONINVERTINGINPUT_IO1 #define OPAMP_NONINVERTINGINPUT_VP2 OPAMP_NONINVERTINGINPUT_IO2 #define OPAMP_NONINVERTINGINPUT_VP3 OPAMP_NONINVERTINGINPUT_IO3 #define OPAMP_SEC_NONINVERTINGINPUT_VP0 OPAMP_SEC_NONINVERTINGINPUT_IO0 #define OPAMP_SEC_NONINVERTINGINPUT_VP1 OPAMP_SEC_NONINVERTINGINPUT_IO1 #define OPAMP_SEC_NONINVERTINGINPUT_VP2 OPAMP_SEC_NONINVERTINGINPUT_IO2 #define OPAMP_SEC_NONINVERTINGINPUT_VP3 OPAMP_SEC_NONINVERTINGINPUT_IO3 #define OPAMP_INVERTINGINPUT_VM0 OPAMP_INVERTINGINPUT_IO0 #define OPAMP_INVERTINGINPUT_VM1 OPAMP_INVERTINGINPUT_IO1 #define IOPAMP_INVERTINGINPUT_VM0 OPAMP_INVERTINGINPUT_IO0 #define IOPAMP_INVERTINGINPUT_VM1 OPAMP_INVERTINGINPUT_IO1 #define OPAMP_SEC_INVERTINGINPUT_VM0 OPAMP_SEC_INVERTINGINPUT_IO0 #define OPAMP_SEC_INVERTINGINPUT_VM1 OPAMP_SEC_INVERTINGINPUT_IO1 #define OPAMP_INVERTINGINPUT_VINM OPAMP_SEC_INVERTINGINPUT_IO1 #define OPAMP_PGACONNECT_NO OPAMP_PGA_CONNECT_INVERTINGINPUT_NO #define OPAMP_PGACONNECT_VM0 OPAMP_PGA_CONNECT_INVERTINGINPUT_IO0 #define OPAMP_PGACONNECT_VM1 OPAMP_PGA_CONNECT_INVERTINGINPUT_IO1 /** * @} */ /** @defgroup HAL_I2S_Aliased_Defines HAL I2S Aliased Defines maintained for legacy purpose * @{ */ #define I2S_STANDARD_PHILLIPS I2S_STANDARD_PHILIPS /** * @} */ /** @defgroup HAL_PCCARD_Aliased_Defines HAL PCCARD Aliased Defines maintained for legacy purpose * @{ */ /* Compact Flash-ATA registers description */ #define CF_DATA ATA_DATA #define CF_SECTOR_COUNT ATA_SECTOR_COUNT #define CF_SECTOR_NUMBER ATA_SECTOR_NUMBER #define CF_CYLINDER_LOW ATA_CYLINDER_LOW #define CF_CYLINDER_HIGH ATA_CYLINDER_HIGH #define CF_CARD_HEAD ATA_CARD_HEAD #define CF_STATUS_CMD ATA_STATUS_CMD #define CF_STATUS_CMD_ALTERNATE ATA_STATUS_CMD_ALTERNATE #define CF_COMMON_DATA_AREA ATA_COMMON_DATA_AREA /* Compact Flash-ATA commands */ #define CF_READ_SECTOR_CMD ATA_READ_SECTOR_CMD #define CF_WRITE_SECTOR_CMD ATA_WRITE_SECTOR_CMD #define CF_ERASE_SECTOR_CMD ATA_ERASE_SECTOR_CMD #define CF_IDENTIFY_CMD ATA_IDENTIFY_CMD #define PCCARD_StatusTypedef HAL_PCCARD_StatusTypeDef #define PCCARD_SUCCESS HAL_PCCARD_STATUS_SUCCESS #define PCCARD_ONGOING HAL_PCCARD_STATUS_ONGOING #define PCCARD_ERROR HAL_PCCARD_STATUS_ERROR #define PCCARD_TIMEOUT HAL_PCCARD_STATUS_TIMEOUT /** * @} */ /** @defgroup HAL_RTC_Aliased_Defines HAL RTC Aliased Defines maintained for legacy purpose * @{ */ #define FORMAT_BIN RTC_FORMAT_BIN #define FORMAT_BCD RTC_FORMAT_BCD #define RTC_ALARMSUBSECONDMASK_None RTC_ALARMSUBSECONDMASK_NONE #define RTC_TAMPERERASEBACKUP_ENABLED RTC_TAMPER_ERASE_BACKUP_ENABLE #define RTC_TAMPERERASEBACKUP_DISABLED RTC_TAMPER_ERASE_BACKUP_DISABLE #define RTC_TAMPERMASK_FLAG_DISABLED RTC_TAMPERMASK_FLAG_DISABLE #define RTC_TAMPERMASK_FLAG_ENABLED RTC_TAMPERMASK_FLAG_ENABLE #define RTC_MASKTAMPERFLAG_DISABLED RTC_TAMPERMASK_FLAG_DISABLE #define RTC_MASKTAMPERFLAG_ENABLED RTC_TAMPERMASK_FLAG_ENABLE #define RTC_TAMPERERASEBACKUP_ENABLED RTC_TAMPER_ERASE_BACKUP_ENABLE #define RTC_TAMPERERASEBACKUP_DISABLED RTC_TAMPER_ERASE_BACKUP_DISABLE #define RTC_MASKTAMPERFLAG_DISABLED RTC_TAMPERMASK_FLAG_DISABLE #define RTC_MASKTAMPERFLAG_ENABLED RTC_TAMPERMASK_FLAG_ENABLE #define RTC_TAMPER1_2_INTERRUPT RTC_ALL_TAMPER_INTERRUPT #define RTC_TAMPER1_2_3_INTERRUPT RTC_ALL_TAMPER_INTERRUPT #define RTC_TIMESTAMPPIN_PC13 RTC_TIMESTAMPPIN_DEFAULT #define RTC_OUTPUT_REMAP_PC13 RTC_OUTPUT_REMAP_NONE #define RTC_OUTPUT_REMAP_PB14 RTC_OUTPUT_REMAP_POS1 /** * @} */ /** @defgroup HAL_SMARTCARD_Aliased_Defines HAL SMARTCARD Aliased Defines maintained for legacy purpose * @{ */ #define SMARTCARD_NACK_ENABLED SMARTCARD_NACK_ENABLE #define SMARTCARD_NACK_DISABLED SMARTCARD_NACK_DISABLE #define SMARTCARD_ONEBIT_SAMPLING_DISABLED SMARTCARD_ONE_BIT_SAMPLE_DISABLE #define SMARTCARD_ONEBIT_SAMPLING_ENABLED SMARTCARD_ONE_BIT_SAMPLE_ENABLE #define SMARTCARD_ONEBIT_SAMPLING_DISABLE SMARTCARD_ONE_BIT_SAMPLE_DISABLE #define SMARTCARD_ONEBIT_SAMPLING_ENABLE SMARTCARD_ONE_BIT_SAMPLE_ENABLE #define SMARTCARD_TIMEOUT_DISABLED SMARTCARD_TIMEOUT_DISABLE #define SMARTCARD_TIMEOUT_ENABLED SMARTCARD_TIMEOUT_ENABLE #define SMARTCARD_LASTBIT_DISABLED SMARTCARD_LASTBIT_DISABLE #define SMARTCARD_LASTBIT_ENABLED SMARTCARD_LASTBIT_ENABLE /** * @} */ /** @defgroup HAL_SMBUS_Aliased_Defines HAL SMBUS Aliased Defines maintained for legacy purpose * @{ */ #define SMBUS_DUALADDRESS_DISABLED SMBUS_DUALADDRESS_DISABLE #define SMBUS_DUALADDRESS_ENABLED SMBUS_DUALADDRESS_ENABLE #define SMBUS_GENERALCALL_DISABLED SMBUS_GENERALCALL_DISABLE #define SMBUS_GENERALCALL_ENABLED SMBUS_GENERALCALL_ENABLE #define SMBUS_NOSTRETCH_DISABLED SMBUS_NOSTRETCH_DISABLE #define SMBUS_NOSTRETCH_ENABLED SMBUS_NOSTRETCH_ENABLE #define SMBUS_ANALOGFILTER_ENABLED SMBUS_ANALOGFILTER_ENABLE #define SMBUS_ANALOGFILTER_DISABLED SMBUS_ANALOGFILTER_DISABLE #define SMBUS_PEC_DISABLED SMBUS_PEC_DISABLE #define SMBUS_PEC_ENABLED SMBUS_PEC_ENABLE #define HAL_SMBUS_STATE_SLAVE_LISTEN HAL_SMBUS_STATE_LISTEN /** * @} */ /** @defgroup HAL_SPI_Aliased_Defines HAL SPI Aliased Defines maintained for legacy purpose * @{ */ #define SPI_TIMODE_DISABLED SPI_TIMODE_DISABLE #define SPI_TIMODE_ENABLED SPI_TIMODE_ENABLE #define SPI_CRCCALCULATION_DISABLED SPI_CRCCALCULATION_DISABLE #define SPI_CRCCALCULATION_ENABLED SPI_CRCCALCULATION_ENABLE #define SPI_NSS_PULSE_DISABLED SPI_NSS_PULSE_DISABLE #define SPI_NSS_PULSE_ENABLED SPI_NSS_PULSE_ENABLE /** * @} */ /** @defgroup HAL_TIM_Aliased_Defines HAL TIM Aliased Defines maintained for legacy purpose * @{ */ #define CCER_CCxE_MASK TIM_CCER_CCxE_MASK #define CCER_CCxNE_MASK TIM_CCER_CCxNE_MASK #define TIM_DMABase_CR1 TIM_DMABASE_CR1 #define TIM_DMABase_CR2 TIM_DMABASE_CR2 #define TIM_DMABase_SMCR TIM_DMABASE_SMCR #define TIM_DMABase_DIER TIM_DMABASE_DIER #define TIM_DMABase_SR TIM_DMABASE_SR #define TIM_DMABase_EGR TIM_DMABASE_EGR #define TIM_DMABase_CCMR1 TIM_DMABASE_CCMR1 #define TIM_DMABase_CCMR2 TIM_DMABASE_CCMR2 #define TIM_DMABase_CCER TIM_DMABASE_CCER #define TIM_DMABase_CNT TIM_DMABASE_CNT #define TIM_DMABase_PSC TIM_DMABASE_PSC #define TIM_DMABase_ARR TIM_DMABASE_ARR #define TIM_DMABase_RCR TIM_DMABASE_RCR #define TIM_DMABase_CCR1 TIM_DMABASE_CCR1 #define TIM_DMABase_CCR2 TIM_DMABASE_CCR2 #define TIM_DMABase_CCR3 TIM_DMABASE_CCR3 #define TIM_DMABase_CCR4 TIM_DMABASE_CCR4 #define TIM_DMABase_BDTR TIM_DMABASE_BDTR #define TIM_DMABase_DCR TIM_DMABASE_DCR #define TIM_DMABase_DMAR TIM_DMABASE_DMAR #define TIM_DMABase_OR1 TIM_DMABASE_OR1 #define TIM_DMABase_CCMR3 TIM_DMABASE_CCMR3 #define TIM_DMABase_CCR5 TIM_DMABASE_CCR5 #define TIM_DMABase_CCR6 TIM_DMABASE_CCR6 #define TIM_DMABase_OR2 TIM_DMABASE_OR2 #define TIM_DMABase_OR3 TIM_DMABASE_OR3 #define TIM_DMABase_OR TIM_DMABASE_OR #define TIM_EventSource_Update TIM_EVENTSOURCE_UPDATE #define TIM_EventSource_CC1 TIM_EVENTSOURCE_CC1 #define TIM_EventSource_CC2 TIM_EVENTSOURCE_CC2 #define TIM_EventSource_CC3 TIM_EVENTSOURCE_CC3 #define TIM_EventSource_CC4 TIM_EVENTSOURCE_CC4 #define TIM_EventSource_COM TIM_EVENTSOURCE_COM #define TIM_EventSource_Trigger TIM_EVENTSOURCE_TRIGGER #define TIM_EventSource_Break TIM_EVENTSOURCE_BREAK #define TIM_EventSource_Break2 TIM_EVENTSOURCE_BREAK2 #define TIM_DMABurstLength_1Transfer TIM_DMABURSTLENGTH_1TRANSFER #define TIM_DMABurstLength_2Transfers TIM_DMABURSTLENGTH_2TRANSFERS #define TIM_DMABurstLength_3Transfers TIM_DMABURSTLENGTH_3TRANSFERS #define TIM_DMABurstLength_4Transfers TIM_DMABURSTLENGTH_4TRANSFERS #define TIM_DMABurstLength_5Transfers TIM_DMABURSTLENGTH_5TRANSFERS #define TIM_DMABurstLength_6Transfers TIM_DMABURSTLENGTH_6TRANSFERS #define TIM_DMABurstLength_7Transfers TIM_DMABURSTLENGTH_7TRANSFERS #define TIM_DMABurstLength_8Transfers TIM_DMABURSTLENGTH_8TRANSFERS #define TIM_DMABurstLength_9Transfers TIM_DMABURSTLENGTH_9TRANSFERS #define TIM_DMABurstLength_10Transfers TIM_DMABURSTLENGTH_10TRANSFERS #define TIM_DMABurstLength_11Transfers TIM_DMABURSTLENGTH_11TRANSFERS #define TIM_DMABurstLength_12Transfers TIM_DMABURSTLENGTH_12TRANSFERS #define TIM_DMABurstLength_13Transfers TIM_DMABURSTLENGTH_13TRANSFERS #define TIM_DMABurstLength_14Transfers TIM_DMABURSTLENGTH_14TRANSFERS #define TIM_DMABurstLength_15Transfers TIM_DMABURSTLENGTH_15TRANSFERS #define TIM_DMABurstLength_16Transfers TIM_DMABURSTLENGTH_16TRANSFERS #define TIM_DMABurstLength_17Transfers TIM_DMABURSTLENGTH_17TRANSFERS #define TIM_DMABurstLength_18Transfers TIM_DMABURSTLENGTH_18TRANSFERS /** * @} */ /** @defgroup HAL_TSC_Aliased_Defines HAL TSC Aliased Defines maintained for legacy purpose * @{ */ #define TSC_SYNC_POL_FALL TSC_SYNC_POLARITY_FALLING #define TSC_SYNC_POL_RISE_HIGH TSC_SYNC_POLARITY_RISING /** * @} */ /** @defgroup HAL_UART_Aliased_Defines HAL UART Aliased Defines maintained for legacy purpose * @{ */ #define UART_ONEBIT_SAMPLING_DISABLED UART_ONE_BIT_SAMPLE_DISABLE #define UART_ONEBIT_SAMPLING_ENABLED UART_ONE_BIT_SAMPLE_ENABLE #define UART_ONE_BIT_SAMPLE_DISABLED UART_ONE_BIT_SAMPLE_DISABLE #define UART_ONE_BIT_SAMPLE_ENABLED UART_ONE_BIT_SAMPLE_ENABLE #define __HAL_UART_ONEBIT_ENABLE __HAL_UART_ONE_BIT_SAMPLE_ENABLE #define __HAL_UART_ONEBIT_DISABLE __HAL_UART_ONE_BIT_SAMPLE_DISABLE #define __DIV_SAMPLING16 UART_DIV_SAMPLING16 #define __DIVMANT_SAMPLING16 UART_DIVMANT_SAMPLING16 #define __DIVFRAQ_SAMPLING16 UART_DIVFRAQ_SAMPLING16 #define __UART_BRR_SAMPLING16 UART_BRR_SAMPLING16 #define __DIV_SAMPLING8 UART_DIV_SAMPLING8 #define __DIVMANT_SAMPLING8 UART_DIVMANT_SAMPLING8 #define __DIVFRAQ_SAMPLING8 UART_DIVFRAQ_SAMPLING8 #define __UART_BRR_SAMPLING8 UART_BRR_SAMPLING8 #define UART_WAKEUPMETHODE_IDLELINE UART_WAKEUPMETHOD_IDLELINE #define UART_WAKEUPMETHODE_ADDRESSMARK UART_WAKEUPMETHOD_ADDRESSMARK /** * @} */ /** @defgroup HAL_USART_Aliased_Defines HAL USART Aliased Defines maintained for legacy purpose * @{ */ #define USART_CLOCK_DISABLED USART_CLOCK_DISABLE #define USART_CLOCK_ENABLED USART_CLOCK_ENABLE #define USARTNACK_ENABLED USART_NACK_ENABLE #define USARTNACK_DISABLED USART_NACK_DISABLE /** * @} */ /** @defgroup HAL_WWDG_Aliased_Defines HAL WWDG Aliased Defines maintained for legacy purpose * @{ */ #define CFR_BASE WWDG_CFR_BASE /** * @} */ /** @defgroup HAL_CAN_Aliased_Defines HAL CAN Aliased Defines maintained for legacy purpose * @{ */ #define CAN_FilterFIFO0 CAN_FILTER_FIFO0 #define CAN_FilterFIFO1 CAN_FILTER_FIFO1 #define CAN_IT_RQCP0 CAN_IT_TME #define CAN_IT_RQCP1 CAN_IT_TME #define CAN_IT_RQCP2 CAN_IT_TME #define INAK_TIMEOUT CAN_TIMEOUT_VALUE #define SLAK_TIMEOUT CAN_TIMEOUT_VALUE #define CAN_TXSTATUS_FAILED ((uint8_t)0x00) #define CAN_TXSTATUS_OK ((uint8_t)0x01) #define CAN_TXSTATUS_PENDING ((uint8_t)0x02) /** * @} */ /** @defgroup HAL_ETH_Aliased_Defines HAL ETH Aliased Defines maintained for legacy purpose * @{ */ #define VLAN_TAG ETH_VLAN_TAG #define MIN_ETH_PAYLOAD ETH_MIN_ETH_PAYLOAD #define MAX_ETH_PAYLOAD ETH_MAX_ETH_PAYLOAD #define JUMBO_FRAME_PAYLOAD ETH_JUMBO_FRAME_PAYLOAD #define MACMIIAR_CR_MASK ETH_MACMIIAR_CR_MASK #define MACCR_CLEAR_MASK ETH_MACCR_CLEAR_MASK #define MACFCR_CLEAR_MASK ETH_MACFCR_CLEAR_MASK #define DMAOMR_CLEAR_MASK ETH_DMAOMR_CLEAR_MASK #define ETH_MMCCR ((uint32_t)0x00000100) #define ETH_MMCRIR ((uint32_t)0x00000104) #define ETH_MMCTIR ((uint32_t)0x00000108) #define ETH_MMCRIMR ((uint32_t)0x0000010C) #define ETH_MMCTIMR ((uint32_t)0x00000110) #define ETH_MMCTGFSCCR ((uint32_t)0x0000014C) #define ETH_MMCTGFMSCCR ((uint32_t)0x00000150) #define ETH_MMCTGFCR ((uint32_t)0x00000168) #define ETH_MMCRFCECR ((uint32_t)0x00000194) #define ETH_MMCRFAECR ((uint32_t)0x00000198) #define ETH_MMCRGUFCR ((uint32_t)0x000001C4) /** * @} */ /** @defgroup HAL_PPP_Aliased_Defines HAL PPP Aliased Defines maintained for legacy purpose * @{ */ /** * @} */ /* Exported functions --------------------------------------------------------*/ /** @defgroup HAL_CRYP_Aliased_Functions HAL CRYP Aliased Functions maintained for legacy purpose * @{ */ #define HAL_CRYP_ComputationCpltCallback HAL_CRYPEx_ComputationCpltCallback /** * @} */ /** @defgroup HAL_HASH_Aliased_Functions HAL HASH Aliased Functions maintained for legacy purpose * @{ */ #define HAL_HMAC_MD5_Finish HAL_HASH_MD5_Finish #define HAL_HMAC_SHA1_Finish HAL_HASH_SHA1_Finish #define HAL_HMAC_SHA224_Finish HAL_HASH_SHA224_Finish #define HAL_HMAC_SHA256_Finish HAL_HASH_SHA256_Finish /*HASH Algorithm Selection*/ #define HASH_AlgoSelection_SHA1 HASH_ALGOSELECTION_SHA1 #define HASH_AlgoSelection_SHA224 HASH_ALGOSELECTION_SHA224 #define HASH_AlgoSelection_SHA256 HASH_ALGOSELECTION_SHA256 #define HASH_AlgoSelection_MD5 HASH_ALGOSELECTION_MD5 #define HASH_AlgoMode_HASH HASH_ALGOMODE_HASH #define HASH_AlgoMode_HMAC HASH_ALGOMODE_HMAC #define HASH_HMACKeyType_ShortKey HASH_HMAC_KEYTYPE_SHORTKEY #define HASH_HMACKeyType_LongKey HASH_HMAC_KEYTYPE_LONGKEY /** * @} */ /** @defgroup HAL_Aliased_Functions HAL Generic Aliased Functions maintained for legacy purpose * @{ */ #define HAL_EnableDBGSleepMode HAL_DBGMCU_EnableDBGSleepMode #define HAL_DisableDBGSleepMode HAL_DBGMCU_DisableDBGSleepMode #define HAL_EnableDBGStopMode HAL_DBGMCU_EnableDBGStopMode #define HAL_DisableDBGStopMode HAL_DBGMCU_DisableDBGStopMode #define HAL_EnableDBGStandbyMode HAL_DBGMCU_EnableDBGStandbyMode #define HAL_DisableDBGStandbyMode HAL_DBGMCU_DisableDBGStandbyMode #define HAL_DBG_LowPowerConfig(Periph, cmd) (((cmd)==ENABLE)? HAL_DBGMCU_DBG_EnableLowPowerConfig(Periph) : HAL_DBGMCU_DBG_DisableLowPowerConfig(Periph)) #define HAL_VREFINT_OutputSelect HAL_SYSCFG_VREFINT_OutputSelect #define HAL_Lock_Cmd(cmd) (((cmd)==ENABLE) ? HAL_SYSCFG_Enable_Lock_VREFINT() : HAL_SYSCFG_Disable_Lock_VREFINT()) #define HAL_VREFINT_Cmd(cmd) (((cmd)==ENABLE)? HAL_SYSCFG_EnableVREFINT() : HAL_SYSCFG_DisableVREFINT()) #define HAL_ADC_EnableBuffer_Cmd(cmd) (((cmd)==ENABLE) ? HAL_ADCEx_EnableVREFINT() : HAL_ADCEx_DisableVREFINT()) #define HAL_ADC_EnableBufferSensor_Cmd(cmd) (((cmd)==ENABLE) ? HAL_ADCEx_EnableVREFINTTempSensor() : HAL_ADCEx_DisableVREFINTTempSensor()) /** * @} */ /** @defgroup HAL_FLASH_Aliased_Functions HAL FLASH Aliased Functions maintained for legacy purpose * @{ */ #define FLASH_HalfPageProgram HAL_FLASHEx_HalfPageProgram #define FLASH_EnableRunPowerDown HAL_FLASHEx_EnableRunPowerDown #define FLASH_DisableRunPowerDown HAL_FLASHEx_DisableRunPowerDown #define HAL_DATA_EEPROMEx_Unlock HAL_FLASHEx_DATAEEPROM_Unlock #define HAL_DATA_EEPROMEx_Lock HAL_FLASHEx_DATAEEPROM_Lock #define HAL_DATA_EEPROMEx_Erase HAL_FLASHEx_DATAEEPROM_Erase #define HAL_DATA_EEPROMEx_Program HAL_FLASHEx_DATAEEPROM_Program /** * @} */ /** @defgroup HAL_I2C_Aliased_Functions HAL I2C Aliased Functions maintained for legacy purpose * @{ */ #define HAL_I2CEx_AnalogFilter_Config HAL_I2CEx_ConfigAnalogFilter #define HAL_I2CEx_DigitalFilter_Config HAL_I2CEx_ConfigDigitalFilter #define HAL_I2CFastModePlusConfig(SYSCFG_I2CFastModePlus, cmd) (((cmd)==ENABLE)? HAL_I2CEx_EnableFastModePlus(SYSCFG_I2CFastModePlus): HAL_I2CEx_DisableFastModePlus(SYSCFG_I2CFastModePlus)) /** * @} */ /** @defgroup HAL_PWR_Aliased HAL PWR Aliased maintained for legacy purpose * @{ */ #define HAL_PWR_PVDConfig HAL_PWR_ConfigPVD #define HAL_PWR_DisableBkUpReg HAL_PWREx_DisableBkUpReg #define HAL_PWR_DisableFlashPowerDown HAL_PWREx_DisableFlashPowerDown #define HAL_PWR_DisableVddio2Monitor HAL_PWREx_DisableVddio2Monitor #define HAL_PWR_EnableBkUpReg HAL_PWREx_EnableBkUpReg #define HAL_PWR_EnableFlashPowerDown HAL_PWREx_EnableFlashPowerDown #define HAL_PWR_EnableVddio2Monitor HAL_PWREx_EnableVddio2Monitor #define HAL_PWR_PVD_PVM_IRQHandler HAL_PWREx_PVD_PVM_IRQHandler #define HAL_PWR_PVDLevelConfig HAL_PWR_ConfigPVD #define HAL_PWR_Vddio2Monitor_IRQHandler HAL_PWREx_Vddio2Monitor_IRQHandler #define HAL_PWR_Vddio2MonitorCallback HAL_PWREx_Vddio2MonitorCallback #define HAL_PWREx_ActivateOverDrive HAL_PWREx_EnableOverDrive #define HAL_PWREx_DeactivateOverDrive HAL_PWREx_DisableOverDrive #define HAL_PWREx_DisableSDADCAnalog HAL_PWREx_DisableSDADC #define HAL_PWREx_EnableSDADCAnalog HAL_PWREx_EnableSDADC #define HAL_PWREx_PVMConfig HAL_PWREx_ConfigPVM #define PWR_MODE_NORMAL PWR_PVD_MODE_NORMAL #define PWR_MODE_IT_RISING PWR_PVD_MODE_IT_RISING #define PWR_MODE_IT_FALLING PWR_PVD_MODE_IT_FALLING #define PWR_MODE_IT_RISING_FALLING PWR_PVD_MODE_IT_RISING_FALLING #define PWR_MODE_EVENT_RISING PWR_PVD_MODE_EVENT_RISING #define PWR_MODE_EVENT_FALLING PWR_PVD_MODE_EVENT_FALLING #define PWR_MODE_EVENT_RISING_FALLING PWR_PVD_MODE_EVENT_RISING_FALLING #define CR_OFFSET_BB PWR_CR_OFFSET_BB #define CSR_OFFSET_BB PWR_CSR_OFFSET_BB #define DBP_BitNumber DBP_BIT_NUMBER #define PVDE_BitNumber PVDE_BIT_NUMBER #define PMODE_BitNumber PMODE_BIT_NUMBER #define EWUP_BitNumber EWUP_BIT_NUMBER #define FPDS_BitNumber FPDS_BIT_NUMBER #define ODEN_BitNumber ODEN_BIT_NUMBER #define ODSWEN_BitNumber ODSWEN_BIT_NUMBER #define MRLVDS_BitNumber MRLVDS_BIT_NUMBER #define LPLVDS_BitNumber LPLVDS_BIT_NUMBER #define BRE_BitNumber BRE_BIT_NUMBER #define PWR_MODE_EVT PWR_PVD_MODE_NORMAL /** * @} */ /** @defgroup HAL_SMBUS_Aliased_Functions HAL SMBUS Aliased Functions maintained for legacy purpose * @{ */ #define HAL_SMBUS_Slave_Listen_IT HAL_SMBUS_EnableListen_IT #define HAL_SMBUS_SlaveAddrCallback HAL_SMBUS_AddrCallback #define HAL_SMBUS_SlaveListenCpltCallback HAL_SMBUS_ListenCpltCallback /** * @} */ /** @defgroup HAL_SPI_Aliased_Functions HAL SPI Aliased Functions maintained for legacy purpose * @{ */ #define HAL_SPI_FlushRxFifo HAL_SPIEx_FlushRxFifo /** * @} */ /** @defgroup HAL_TIM_Aliased_Functions HAL TIM Aliased Functions maintained for legacy purpose * @{ */ #define HAL_TIM_DMADelayPulseCplt TIM_DMADelayPulseCplt #define HAL_TIM_DMAError TIM_DMAError #define HAL_TIM_DMACaptureCplt TIM_DMACaptureCplt #define HAL_TIMEx_DMACommutationCplt TIMEx_DMACommutationCplt /** * @} */ /** @defgroup HAL_UART_Aliased_Functions HAL UART Aliased Functions maintained for legacy purpose * @{ */ #define HAL_UART_WakeupCallback HAL_UARTEx_WakeupCallback /** * @} */ /** @defgroup HAL_LTDC_Aliased_Functions HAL LTDC Aliased Functions maintained for legacy purpose * @{ */ #define HAL_LTDC_LineEvenCallback HAL_LTDC_LineEventCallback /** * @} */ /** @defgroup HAL_PPP_Aliased_Functions HAL PPP Aliased Functions maintained for legacy purpose * @{ */ /** * @} */ /* Exported macros ------------------------------------------------------------*/ /** @defgroup HAL_AES_Aliased_Macros HAL CRYP Aliased Macros maintained for legacy purpose * @{ */ #define AES_IT_CC CRYP_IT_CC #define AES_IT_ERR CRYP_IT_ERR #define AES_FLAG_CCF CRYP_FLAG_CCF /** * @} */ /** @defgroup HAL_Aliased_Macros HAL Generic Aliased Macros maintained for legacy purpose * @{ */ #define __HAL_GET_BOOT_MODE __HAL_SYSCFG_GET_BOOT_MODE #define __HAL_REMAPMEMORY_FLASH __HAL_SYSCFG_REMAPMEMORY_FLASH #define __HAL_REMAPMEMORY_SYSTEMFLASH __HAL_SYSCFG_REMAPMEMORY_SYSTEMFLASH #define __HAL_REMAPMEMORY_SRAM __HAL_SYSCFG_REMAPMEMORY_SRAM #define __HAL_REMAPMEMORY_FMC __HAL_SYSCFG_REMAPMEMORY_FMC #define __HAL_REMAPMEMORY_FMC_SDRAM __HAL_SYSCFG_REMAPMEMORY_FMC_SDRAM #define __HAL_REMAPMEMORY_FSMC __HAL_SYSCFG_REMAPMEMORY_FSMC #define __HAL_REMAPMEMORY_QUADSPI __HAL_SYSCFG_REMAPMEMORY_QUADSPI #define __HAL_FMC_BANK __HAL_SYSCFG_FMC_BANK #define __HAL_GET_FLAG __HAL_SYSCFG_GET_FLAG #define __HAL_CLEAR_FLAG __HAL_SYSCFG_CLEAR_FLAG #define __HAL_VREFINT_OUT_ENABLE __HAL_SYSCFG_VREFINT_OUT_ENABLE #define __HAL_VREFINT_OUT_DISABLE __HAL_SYSCFG_VREFINT_OUT_DISABLE #define SYSCFG_FLAG_VREF_READY SYSCFG_FLAG_VREFINT_READY #define SYSCFG_FLAG_RC48 RCC_FLAG_HSI48 #define IS_SYSCFG_FASTMODEPLUS_CONFIG IS_I2C_FASTMODEPLUS #define UFB_MODE_BitNumber UFB_MODE_BIT_NUMBER #define CMP_PD_BitNumber CMP_PD_BIT_NUMBER /** * @} */ /** @defgroup HAL_ADC_Aliased_Macros HAL ADC Aliased Macros maintained for legacy purpose * @{ */ #define __ADC_ENABLE __HAL_ADC_ENABLE #define __ADC_DISABLE __HAL_ADC_DISABLE #define __HAL_ADC_ENABLING_CONDITIONS ADC_ENABLING_CONDITIONS #define __HAL_ADC_DISABLING_CONDITIONS ADC_DISABLING_CONDITIONS #define __HAL_ADC_IS_ENABLED ADC_IS_ENABLE #define __ADC_IS_ENABLED ADC_IS_ENABLE #define __HAL_ADC_IS_SOFTWARE_START_REGULAR ADC_IS_SOFTWARE_START_REGULAR #define __HAL_ADC_IS_SOFTWARE_START_INJECTED ADC_IS_SOFTWARE_START_INJECTED #define __HAL_ADC_IS_CONVERSION_ONGOING_REGULAR_INJECTED ADC_IS_CONVERSION_ONGOING_REGULAR_INJECTED #define __HAL_ADC_IS_CONVERSION_ONGOING_REGULAR ADC_IS_CONVERSION_ONGOING_REGULAR #define __HAL_ADC_IS_CONVERSION_ONGOING_INJECTED ADC_IS_CONVERSION_ONGOING_INJECTED #define __HAL_ADC_IS_CONVERSION_ONGOING ADC_IS_CONVERSION_ONGOING #define __HAL_ADC_CLEAR_ERRORCODE ADC_CLEAR_ERRORCODE #define __HAL_ADC_GET_RESOLUTION ADC_GET_RESOLUTION #define __HAL_ADC_JSQR_RK ADC_JSQR_RK #define __HAL_ADC_CFGR_AWD1CH ADC_CFGR_AWD1CH_SHIFT #define __HAL_ADC_CFGR_AWD23CR ADC_CFGR_AWD23CR #define __HAL_ADC_CFGR_INJECT_AUTO_CONVERSION ADC_CFGR_INJECT_AUTO_CONVERSION #define __HAL_ADC_CFGR_INJECT_CONTEXT_QUEUE ADC_CFGR_INJECT_CONTEXT_QUEUE #define __HAL_ADC_CFGR_INJECT_DISCCONTINUOUS ADC_CFGR_INJECT_DISCCONTINUOUS #define __HAL_ADC_CFGR_REG_DISCCONTINUOUS ADC_CFGR_REG_DISCCONTINUOUS #define __HAL_ADC_CFGR_DISCONTINUOUS_NUM ADC_CFGR_DISCONTINUOUS_NUM #define __HAL_ADC_CFGR_AUTOWAIT ADC_CFGR_AUTOWAIT #define __HAL_ADC_CFGR_CONTINUOUS ADC_CFGR_CONTINUOUS #define __HAL_ADC_CFGR_OVERRUN ADC_CFGR_OVERRUN #define __HAL_ADC_CFGR_DMACONTREQ ADC_CFGR_DMACONTREQ #define __HAL_ADC_CFGR_EXTSEL ADC_CFGR_EXTSEL_SET #define __HAL_ADC_JSQR_JEXTSEL ADC_JSQR_JEXTSEL_SET #define __HAL_ADC_OFR_CHANNEL ADC_OFR_CHANNEL #define __HAL_ADC_DIFSEL_CHANNEL ADC_DIFSEL_CHANNEL #define __HAL_ADC_CALFACT_DIFF_SET ADC_CALFACT_DIFF_SET #define __HAL_ADC_CALFACT_DIFF_GET ADC_CALFACT_DIFF_GET #define __HAL_ADC_TRX_HIGHTHRESHOLD ADC_TRX_HIGHTHRESHOLD #define __HAL_ADC_OFFSET_SHIFT_RESOLUTION ADC_OFFSET_SHIFT_RESOLUTION #define __HAL_ADC_AWD1THRESHOLD_SHIFT_RESOLUTION ADC_AWD1THRESHOLD_SHIFT_RESOLUTION #define __HAL_ADC_AWD23THRESHOLD_SHIFT_RESOLUTION ADC_AWD23THRESHOLD_SHIFT_RESOLUTION #define __HAL_ADC_COMMON_REGISTER ADC_COMMON_REGISTER #define __HAL_ADC_COMMON_CCR_MULTI ADC_COMMON_CCR_MULTI #define __HAL_ADC_MULTIMODE_IS_ENABLED ADC_MULTIMODE_IS_ENABLE #define __ADC_MULTIMODE_IS_ENABLED ADC_MULTIMODE_IS_ENABLE #define __HAL_ADC_NONMULTIMODE_OR_MULTIMODEMASTER ADC_NONMULTIMODE_OR_MULTIMODEMASTER #define __HAL_ADC_COMMON_ADC_OTHER ADC_COMMON_ADC_OTHER #define __HAL_ADC_MULTI_SLAVE ADC_MULTI_SLAVE #define __HAL_ADC_SQR1_L ADC_SQR1_L_SHIFT #define __HAL_ADC_JSQR_JL ADC_JSQR_JL_SHIFT #define __HAL_ADC_JSQR_RK_JL ADC_JSQR_RK_JL #define __HAL_ADC_CR1_DISCONTINUOUS_NUM ADC_CR1_DISCONTINUOUS_NUM #define __HAL_ADC_CR1_SCAN ADC_CR1_SCAN_SET #define __HAL_ADC_CONVCYCLES_MAX_RANGE ADC_CONVCYCLES_MAX_RANGE #define __HAL_ADC_CLOCK_PRESCALER_RANGE ADC_CLOCK_PRESCALER_RANGE #define __HAL_ADC_GET_CLOCK_PRESCALER ADC_GET_CLOCK_PRESCALER #define __HAL_ADC_SQR1 ADC_SQR1 #define __HAL_ADC_SMPR1 ADC_SMPR1 #define __HAL_ADC_SMPR2 ADC_SMPR2 #define __HAL_ADC_SQR3_RK ADC_SQR3_RK #define __HAL_ADC_SQR2_RK ADC_SQR2_RK #define __HAL_ADC_SQR1_RK ADC_SQR1_RK #define __HAL_ADC_CR2_CONTINUOUS ADC_CR2_CONTINUOUS #define __HAL_ADC_CR1_DISCONTINUOUS ADC_CR1_DISCONTINUOUS #define __HAL_ADC_CR1_SCANCONV ADC_CR1_SCANCONV #define __HAL_ADC_CR2_EOCSelection ADC_CR2_EOCSelection #define __HAL_ADC_CR2_DMAContReq ADC_CR2_DMAContReq #define __HAL_ADC_GET_RESOLUTION ADC_GET_RESOLUTION #define __HAL_ADC_JSQR ADC_JSQR #define __HAL_ADC_CHSELR_CHANNEL ADC_CHSELR_CHANNEL #define __HAL_ADC_CFGR1_REG_DISCCONTINUOUS ADC_CFGR1_REG_DISCCONTINUOUS #define __HAL_ADC_CFGR1_AUTOOFF ADC_CFGR1_AUTOOFF #define __HAL_ADC_CFGR1_AUTOWAIT ADC_CFGR1_AUTOWAIT #define __HAL_ADC_CFGR1_CONTINUOUS ADC_CFGR1_CONTINUOUS #define __HAL_ADC_CFGR1_OVERRUN ADC_CFGR1_OVERRUN #define __HAL_ADC_CFGR1_SCANDIR ADC_CFGR1_SCANDIR #define __HAL_ADC_CFGR1_DMACONTREQ ADC_CFGR1_DMACONTREQ /** * @} */ /** @defgroup HAL_DAC_Aliased_Macros HAL DAC Aliased Macros maintained for legacy purpose * @{ */ #define __HAL_DHR12R1_ALIGNEMENT DAC_DHR12R1_ALIGNMENT #define __HAL_DHR12R2_ALIGNEMENT DAC_DHR12R2_ALIGNMENT #define __HAL_DHR12RD_ALIGNEMENT DAC_DHR12RD_ALIGNMENT #define IS_DAC_GENERATE_WAVE IS_DAC_WAVE /** * @} */ /** @defgroup HAL_DBGMCU_Aliased_Macros HAL DBGMCU Aliased Macros maintained for legacy purpose * @{ */ #define __HAL_FREEZE_TIM1_DBGMCU __HAL_DBGMCU_FREEZE_TIM1 #define __HAL_UNFREEZE_TIM1_DBGMCU __HAL_DBGMCU_UNFREEZE_TIM1 #define __HAL_FREEZE_TIM2_DBGMCU __HAL_DBGMCU_FREEZE_TIM2 #define __HAL_UNFREEZE_TIM2_DBGMCU __HAL_DBGMCU_UNFREEZE_TIM2 #define __HAL_FREEZE_TIM3_DBGMCU __HAL_DBGMCU_FREEZE_TIM3 #define __HAL_UNFREEZE_TIM3_DBGMCU __HAL_DBGMCU_UNFREEZE_TIM3 #define __HAL_FREEZE_TIM4_DBGMCU __HAL_DBGMCU_FREEZE_TIM4 #define __HAL_UNFREEZE_TIM4_DBGMCU __HAL_DBGMCU_UNFREEZE_TIM4 #define __HAL_FREEZE_TIM5_DBGMCU __HAL_DBGMCU_FREEZE_TIM5 #define __HAL_UNFREEZE_TIM5_DBGMCU __HAL_DBGMCU_UNFREEZE_TIM5 #define __HAL_FREEZE_TIM6_DBGMCU __HAL_DBGMCU_FREEZE_TIM6 #define __HAL_UNFREEZE_TIM6_DBGMCU __HAL_DBGMCU_UNFREEZE_TIM6 #define __HAL_FREEZE_TIM7_DBGMCU __HAL_DBGMCU_FREEZE_TIM7 #define __HAL_UNFREEZE_TIM7_DBGMCU __HAL_DBGMCU_UNFREEZE_TIM7 #define __HAL_FREEZE_TIM8_DBGMCU __HAL_DBGMCU_FREEZE_TIM8 #define __HAL_UNFREEZE_TIM8_DBGMCU __HAL_DBGMCU_UNFREEZE_TIM8 #define __HAL_FREEZE_TIM9_DBGMCU __HAL_DBGMCU_FREEZE_TIM9 #define __HAL_UNFREEZE_TIM9_DBGMCU __HAL_DBGMCU_UNFREEZE_TIM9 #define __HAL_FREEZE_TIM10_DBGMCU __HAL_DBGMCU_FREEZE_TIM10 #define __HAL_UNFREEZE_TIM10_DBGMCU __HAL_DBGMCU_UNFREEZE_TIM10 #define __HAL_FREEZE_TIM11_DBGMCU __HAL_DBGMCU_FREEZE_TIM11 #define __HAL_UNFREEZE_TIM11_DBGMCU __HAL_DBGMCU_UNFREEZE_TIM11 #define __HAL_FREEZE_TIM12_DBGMCU __HAL_DBGMCU_FREEZE_TIM12 #define __HAL_UNFREEZE_TIM12_DBGMCU __HAL_DBGMCU_UNFREEZE_TIM12 #define __HAL_FREEZE_TIM13_DBGMCU __HAL_DBGMCU_FREEZE_TIM13 #define __HAL_UNFREEZE_TIM13_DBGMCU __HAL_DBGMCU_UNFREEZE_TIM13 #define __HAL_FREEZE_TIM14_DBGMCU __HAL_DBGMCU_FREEZE_TIM14 #define __HAL_UNFREEZE_TIM14_DBGMCU __HAL_DBGMCU_UNFREEZE_TIM14 #define __HAL_FREEZE_CAN2_DBGMCU __HAL_DBGMCU_FREEZE_CAN2 #define __HAL_UNFREEZE_CAN2_DBGMCU __HAL_DBGMCU_UNFREEZE_CAN2 #define __HAL_FREEZE_TIM15_DBGMCU __HAL_DBGMCU_FREEZE_TIM15 #define __HAL_UNFREEZE_TIM15_DBGMCU __HAL_DBGMCU_UNFREEZE_TIM15 #define __HAL_FREEZE_TIM16_DBGMCU __HAL_DBGMCU_FREEZE_TIM16 #define __HAL_UNFREEZE_TIM16_DBGMCU __HAL_DBGMCU_UNFREEZE_TIM16 #define __HAL_FREEZE_TIM17_DBGMCU __HAL_DBGMCU_FREEZE_TIM17 #define __HAL_UNFREEZE_TIM17_DBGMCU __HAL_DBGMCU_UNFREEZE_TIM17 #define __HAL_FREEZE_RTC_DBGMCU __HAL_DBGMCU_FREEZE_RTC #define __HAL_UNFREEZE_RTC_DBGMCU __HAL_DBGMCU_UNFREEZE_RTC #define __HAL_FREEZE_WWDG_DBGMCU __HAL_DBGMCU_FREEZE_WWDG #define __HAL_UNFREEZE_WWDG_DBGMCU __HAL_DBGMCU_UNFREEZE_WWDG #define __HAL_FREEZE_IWDG_DBGMCU __HAL_DBGMCU_FREEZE_IWDG #define __HAL_UNFREEZE_IWDG_DBGMCU __HAL_DBGMCU_UNFREEZE_IWDG #define __HAL_FREEZE_I2C1_TIMEOUT_DBGMCU __HAL_DBGMCU_FREEZE_I2C1_TIMEOUT #define __HAL_UNFREEZE_I2C1_TIMEOUT_DBGMCU __HAL_DBGMCU_UNFREEZE_I2C1_TIMEOUT #define __HAL_FREEZE_I2C2_TIMEOUT_DBGMCU __HAL_DBGMCU_FREEZE_I2C2_TIMEOUT #define __HAL_UNFREEZE_I2C2_TIMEOUT_DBGMCU __HAL_DBGMCU_UNFREEZE_I2C2_TIMEOUT #define __HAL_FREEZE_I2C3_TIMEOUT_DBGMCU __HAL_DBGMCU_FREEZE_I2C3_TIMEOUT #define __HAL_UNFREEZE_I2C3_TIMEOUT_DBGMCU __HAL_DBGMCU_UNFREEZE_I2C3_TIMEOUT #define __HAL_FREEZE_CAN1_DBGMCU __HAL_DBGMCU_FREEZE_CAN1 #define __HAL_UNFREEZE_CAN1_DBGMCU __HAL_DBGMCU_UNFREEZE_CAN1 #define __HAL_FREEZE_LPTIM1_DBGMCU __HAL_DBGMCU_FREEZE_LPTIM1 #define __HAL_UNFREEZE_LPTIM1_DBGMCU __HAL_DBGMCU_UNFREEZE_LPTIM1 #define __HAL_FREEZE_LPTIM2_DBGMCU __HAL_DBGMCU_FREEZE_LPTIM2 #define __HAL_UNFREEZE_LPTIM2_DBGMCU __HAL_DBGMCU_UNFREEZE_LPTIM2 /** * @} */ /** @defgroup HAL_COMP_Aliased_Macros HAL COMP Aliased Macros maintained for legacy purpose * @{ */ #define __HAL_COMP_EXTI_RISING_IT_ENABLE(__EXTILINE__) (((__EXTILINE__) == COMP_EXTI_LINE_COMP1) ? __HAL_COMP_COMP1_EXTI_ENABLE_RISING_EDGE() : \ __HAL_COMP_COMP2_EXTI_ENABLE_RISING_EDGE()) #define __HAL_COMP_EXTI_RISING_IT_DISABLE(__EXTILINE__) (((__EXTILINE__) == COMP_EXTI_LINE_COMP1) ? __HAL_COMP_COMP1_EXTI_ENABLE_RISING_EDGE() : \ __HAL_COMP_COMP2_EXTI_DISABLE_RISING_EDGE()) #define __HAL_COMP_EXTI_FALLING_IT_ENABLE(__EXTILINE__) (((__EXTILINE__) == COMP_EXTI_LINE_COMP1) ? __HAL_COMP_COMP1_EXTI_ENABLE_FALLING_EDGE() : \ __HAL_COMP_COMP2_EXTI_ENABLE_FALLING_EDGE()) #define __HAL_COMP_EXTI_FALLING_IT_DISABLE(__EXTILINE__) (((__EXTILINE__) == COMP_EXTI_LINE_COMP1) ? __HAL_COMP_COMP1_EXTI_ENABLE_FALLING_EDGE() : \ __HAL_COMP_COMP2_EXTI_DISABLE_FALLING_EDGE()) #define __HAL_COMP_EXTI_ENABLE_IT(__EXTILINE__) (((__EXTILINE__) == COMP_EXTI_LINE_COMP1) ? __HAL_COMP_COMP1_EXTI_ENABLE_IT() : \ __HAL_COMP_COMP2_EXTI_ENABLE_IT()) #define __HAL_COMP_EXTI_DISABLE_IT(__EXTILINE__) (((__EXTILINE__) == COMP_EXTI_LINE_COMP1) ? __HAL_COMP_COMP1_EXTI_DISABLE_IT() : \ __HAL_COMP_COMP2_EXTI_DISABLE_IT()) #define __HAL_COMP_EXTI_GET_FLAG(__FLAG__) (((__FLAG__) == COMP_EXTI_LINE_COMP1) ? __HAL_COMP_COMP1_EXTI_GET_FLAG() : \ __HAL_COMP_COMP2_EXTI_GET_FLAG()) #define __HAL_COMP_EXTI_CLEAR_FLAG(__FLAG__) (((__FLAG__) == COMP_EXTI_LINE_COMP1) ? __HAL_COMP_COMP1_EXTI_CLEAR_FLAG() : \ __HAL_COMP_COMP2_EXTI_CLEAR_FLAG()) #define __HAL_COMP_GET_EXTI_LINE COMP_GET_EXTI_LINE /** * @} */ /** @defgroup HAL_DAC_Aliased_Macros HAL DAC Aliased Macros maintained for legacy purpose * @{ */ #define IS_DAC_WAVE(WAVE) (((WAVE) == DAC_WAVE_NONE) || \ ((WAVE) == DAC_WAVE_NOISE)|| \ ((WAVE) == DAC_WAVE_TRIANGLE)) /** * @} */ /** @defgroup HAL_FLASH_Aliased_Macros HAL FLASH Aliased Macros maintained for legacy purpose * @{ */ #define IS_WRPAREA IS_OB_WRPAREA #define IS_TYPEPROGRAM IS_FLASH_TYPEPROGRAM #define IS_TYPEPROGRAMFLASH IS_FLASH_TYPEPROGRAM #define IS_TYPEERASE IS_FLASH_TYPEERASE #define IS_NBSECTORS IS_FLASH_NBSECTORS #define IS_OB_WDG_SOURCE IS_OB_IWDG_SOURCE /** * @} */ /** @defgroup HAL_I2C_Aliased_Macros HAL I2C Aliased Macros maintained for legacy purpose * @{ */ #define __HAL_I2C_RESET_CR2 I2C_RESET_CR2 #define __HAL_I2C_GENERATE_START I2C_GENERATE_START #define __HAL_I2C_FREQ_RANGE I2C_FREQ_RANGE #define __HAL_I2C_RISE_TIME I2C_RISE_TIME #define __HAL_I2C_SPEED_STANDARD I2C_SPEED_STANDARD #define __HAL_I2C_SPEED_FAST I2C_SPEED_FAST #define __HAL_I2C_SPEED I2C_SPEED #define __HAL_I2C_7BIT_ADD_WRITE I2C_7BIT_ADD_WRITE #define __HAL_I2C_7BIT_ADD_READ I2C_7BIT_ADD_READ #define __HAL_I2C_10BIT_ADDRESS I2C_10BIT_ADDRESS #define __HAL_I2C_10BIT_HEADER_WRITE I2C_10BIT_HEADER_WRITE #define __HAL_I2C_10BIT_HEADER_READ I2C_10BIT_HEADER_READ #define __HAL_I2C_MEM_ADD_MSB I2C_MEM_ADD_MSB #define __HAL_I2C_MEM_ADD_LSB I2C_MEM_ADD_LSB #define __HAL_I2C_FREQRANGE I2C_FREQRANGE /** * @} */ /** @defgroup HAL_I2S_Aliased_Macros HAL I2S Aliased Macros maintained for legacy purpose * @{ */ #define IS_I2S_INSTANCE IS_I2S_ALL_INSTANCE #define IS_I2S_INSTANCE_EXT IS_I2S_ALL_INSTANCE_EXT /** * @} */ /** @defgroup HAL_IRDA_Aliased_Macros HAL IRDA Aliased Macros maintained for legacy purpose * @{ */ #define __IRDA_DISABLE __HAL_IRDA_DISABLE #define __IRDA_ENABLE __HAL_IRDA_ENABLE #define __HAL_IRDA_GETCLOCKSOURCE IRDA_GETCLOCKSOURCE #define __HAL_IRDA_MASK_COMPUTATION IRDA_MASK_COMPUTATION #define __IRDA_GETCLOCKSOURCE IRDA_GETCLOCKSOURCE #define __IRDA_MASK_COMPUTATION IRDA_MASK_COMPUTATION #define IS_IRDA_ONEBIT_SAMPLE IS_IRDA_ONE_BIT_SAMPLE /** * @} */ /** @defgroup HAL_IWDG_Aliased_Macros HAL IWDG Aliased Macros maintained for legacy purpose * @{ */ #define __HAL_IWDG_ENABLE_WRITE_ACCESS IWDG_ENABLE_WRITE_ACCESS #define __HAL_IWDG_DISABLE_WRITE_ACCESS IWDG_DISABLE_WRITE_ACCESS /** * @} */ /** @defgroup HAL_LPTIM_Aliased_Macros HAL LPTIM Aliased Macros maintained for legacy purpose * @{ */ #define __HAL_LPTIM_ENABLE_INTERRUPT __HAL_LPTIM_ENABLE_IT #define __HAL_LPTIM_DISABLE_INTERRUPT __HAL_LPTIM_DISABLE_IT #define __HAL_LPTIM_GET_ITSTATUS __HAL_LPTIM_GET_IT_SOURCE /** * @} */ /** @defgroup HAL_OPAMP_Aliased_Macros HAL OPAMP Aliased Macros maintained for legacy purpose * @{ */ #define __OPAMP_CSR_OPAXPD OPAMP_CSR_OPAXPD #define __OPAMP_CSR_S3SELX OPAMP_CSR_S3SELX #define __OPAMP_CSR_S4SELX OPAMP_CSR_S4SELX #define __OPAMP_CSR_S5SELX OPAMP_CSR_S5SELX #define __OPAMP_CSR_S6SELX OPAMP_CSR_S6SELX #define __OPAMP_CSR_OPAXCAL_L OPAMP_CSR_OPAXCAL_L #define __OPAMP_CSR_OPAXCAL_H OPAMP_CSR_OPAXCAL_H #define __OPAMP_CSR_OPAXLPM OPAMP_CSR_OPAXLPM #define __OPAMP_CSR_ALL_SWITCHES OPAMP_CSR_ALL_SWITCHES #define __OPAMP_CSR_ANAWSELX OPAMP_CSR_ANAWSELX #define __OPAMP_CSR_OPAXCALOUT OPAMP_CSR_OPAXCALOUT #define __OPAMP_OFFSET_TRIM_BITSPOSITION OPAMP_OFFSET_TRIM_BITSPOSITION #define __OPAMP_OFFSET_TRIM_SET OPAMP_OFFSET_TRIM_SET /** * @} */ /** @defgroup HAL_PWR_Aliased_Macros HAL PWR Aliased Macros maintained for legacy purpose * @{ */ #define __HAL_PVD_EVENT_DISABLE __HAL_PWR_PVD_EXTI_DISABLE_EVENT #define __HAL_PVD_EVENT_ENABLE __HAL_PWR_PVD_EXTI_ENABLE_EVENT #define __HAL_PVD_EXTI_FALLINGTRIGGER_DISABLE __HAL_PWR_PVD_EXTI_DISABLE_FALLING_EDGE #define __HAL_PVD_EXTI_FALLINGTRIGGER_ENABLE __HAL_PWR_PVD_EXTI_ENABLE_FALLING_EDGE #define __HAL_PVD_EXTI_RISINGTRIGGER_DISABLE __HAL_PWR_PVD_EXTI_DISABLE_RISING_EDGE #define __HAL_PVD_EXTI_RISINGTRIGGER_ENABLE __HAL_PWR_PVD_EXTI_ENABLE_RISING_EDGE #define __HAL_PVM_EVENT_DISABLE __HAL_PWR_PVM_EVENT_DISABLE #define __HAL_PVM_EVENT_ENABLE __HAL_PWR_PVM_EVENT_ENABLE #define __HAL_PVM_EXTI_FALLINGTRIGGER_DISABLE __HAL_PWR_PVM_EXTI_FALLINGTRIGGER_DISABLE #define __HAL_PVM_EXTI_FALLINGTRIGGER_ENABLE __HAL_PWR_PVM_EXTI_FALLINGTRIGGER_ENABLE #define __HAL_PVM_EXTI_RISINGTRIGGER_DISABLE __HAL_PWR_PVM_EXTI_RISINGTRIGGER_DISABLE #define __HAL_PVM_EXTI_RISINGTRIGGER_ENABLE __HAL_PWR_PVM_EXTI_RISINGTRIGGER_ENABLE #define __HAL_PWR_INTERNALWAKEUP_DISABLE HAL_PWREx_DisableInternalWakeUpLine #define __HAL_PWR_INTERNALWAKEUP_ENABLE HAL_PWREx_EnableInternalWakeUpLine #define __HAL_PWR_PULL_UP_DOWN_CONFIG_DISABLE HAL_PWREx_DisablePullUpPullDownConfig #define __HAL_PWR_PULL_UP_DOWN_CONFIG_ENABLE HAL_PWREx_EnablePullUpPullDownConfig #define __HAL_PWR_PVD_EXTI_CLEAR_EGDE_TRIGGER() __HAL_PWR_PVD_EXTI_DISABLE_RISING_EDGE();__HAL_PWR_PVD_EXTI_DISABLE_FALLING_EDGE() #define __HAL_PWR_PVD_EXTI_EVENT_DISABLE __HAL_PWR_PVD_EXTI_DISABLE_EVENT #define __HAL_PWR_PVD_EXTI_EVENT_ENABLE __HAL_PWR_PVD_EXTI_ENABLE_EVENT #define __HAL_PWR_PVD_EXTI_FALLINGTRIGGER_DISABLE __HAL_PWR_PVD_EXTI_DISABLE_FALLING_EDGE #define __HAL_PWR_PVD_EXTI_FALLINGTRIGGER_ENABLE __HAL_PWR_PVD_EXTI_ENABLE_FALLING_EDGE #define __HAL_PWR_PVD_EXTI_RISINGTRIGGER_DISABLE __HAL_PWR_PVD_EXTI_DISABLE_RISING_EDGE #define __HAL_PWR_PVD_EXTI_RISINGTRIGGER_ENABLE __HAL_PWR_PVD_EXTI_ENABLE_RISING_EDGE #define __HAL_PWR_PVD_EXTI_SET_FALLING_EGDE_TRIGGER __HAL_PWR_PVD_EXTI_ENABLE_FALLING_EDGE #define __HAL_PWR_PVD_EXTI_SET_RISING_EDGE_TRIGGER __HAL_PWR_PVD_EXTI_ENABLE_RISING_EDGE #define __HAL_PWR_PVM_DISABLE() HAL_PWREx_DisablePVM1();HAL_PWREx_DisablePVM2();HAL_PWREx_DisablePVM3();HAL_PWREx_DisablePVM4() #define __HAL_PWR_PVM_ENABLE() HAL_PWREx_EnablePVM1();HAL_PWREx_EnablePVM2();HAL_PWREx_EnablePVM3();HAL_PWREx_EnablePVM4() #define __HAL_PWR_SRAM2CONTENT_PRESERVE_DISABLE HAL_PWREx_DisableSRAM2ContentRetention #define __HAL_PWR_SRAM2CONTENT_PRESERVE_ENABLE HAL_PWREx_EnableSRAM2ContentRetention #define __HAL_PWR_VDDIO2_DISABLE HAL_PWREx_DisableVddIO2 #define __HAL_PWR_VDDIO2_ENABLE HAL_PWREx_EnableVddIO2 #define __HAL_PWR_VDDIO2_EXTI_CLEAR_EGDE_TRIGGER __HAL_PWR_VDDIO2_EXTI_DISABLE_FALLING_EDGE #define __HAL_PWR_VDDIO2_EXTI_SET_FALLING_EGDE_TRIGGER __HAL_PWR_VDDIO2_EXTI_ENABLE_FALLING_EDGE #define __HAL_PWR_VDDUSB_DISABLE HAL_PWREx_DisableVddUSB #define __HAL_PWR_VDDUSB_ENABLE HAL_PWREx_EnableVddUSB #if defined (STM32F4) #define __HAL_PVD_EXTI_ENABLE_IT(PWR_EXTI_LINE_PVD) __HAL_PWR_PVD_EXTI_ENABLE_IT() #define __HAL_PVD_EXTI_DISABLE_IT(PWR_EXTI_LINE_PVD) __HAL_PWR_PVD_EXTI_DISABLE_IT() #define __HAL_PVD_EXTI_GET_FLAG(PWR_EXTI_LINE_PVD) __HAL_PWR_PVD_EXTI_GET_FLAG() #define __HAL_PVD_EXTI_CLEAR_FLAG(PWR_EXTI_LINE_PVD) __HAL_PWR_PVD_EXTI_CLEAR_FLAG() #define __HAL_PVD_EXTI_GENERATE_SWIT(PWR_EXTI_LINE_PVD) __HAL_PWR_PVD_EXTI_GENERATE_SWIT() #else #define __HAL_PVD_EXTI_CLEAR_FLAG __HAL_PWR_PVD_EXTI_CLEAR_FLAG #define __HAL_PVD_EXTI_DISABLE_IT __HAL_PWR_PVD_EXTI_DISABLE_IT #define __HAL_PVD_EXTI_ENABLE_IT __HAL_PWR_PVD_EXTI_ENABLE_IT #define __HAL_PVD_EXTI_GENERATE_SWIT __HAL_PWR_PVD_EXTI_GENERATE_SWIT #define __HAL_PVD_EXTI_GET_FLAG __HAL_PWR_PVD_EXTI_GET_FLAG #endif /* STM32F4 */ /** * @} */ /** @defgroup HAL_RCC_Aliased HAL RCC Aliased maintained for legacy purpose * @{ */ #define RCC_StopWakeUpClock_MSI RCC_STOP_WAKEUPCLOCK_MSI #define RCC_StopWakeUpClock_HSI RCC_STOP_WAKEUPCLOCK_HSI #define HAL_RCC_CCSCallback HAL_RCC_CSSCallback #define HAL_RC48_EnableBuffer_Cmd(cmd) (((cmd)==ENABLE) ? HAL_RCCEx_EnableHSI48_VREFINT() : HAL_RCCEx_DisableHSI48_VREFINT()) #define __ADC_CLK_DISABLE __HAL_RCC_ADC_CLK_DISABLE #define __ADC_CLK_ENABLE __HAL_RCC_ADC_CLK_ENABLE #define __ADC_CLK_SLEEP_DISABLE __HAL_RCC_ADC_CLK_SLEEP_DISABLE #define __ADC_CLK_SLEEP_ENABLE __HAL_RCC_ADC_CLK_SLEEP_ENABLE #define __ADC_FORCE_RESET __HAL_RCC_ADC_FORCE_RESET #define __ADC_RELEASE_RESET __HAL_RCC_ADC_RELEASE_RESET #define __ADC1_CLK_DISABLE __HAL_RCC_ADC1_CLK_DISABLE #define __ADC1_CLK_ENABLE __HAL_RCC_ADC1_CLK_ENABLE #define __ADC1_FORCE_RESET __HAL_RCC_ADC1_FORCE_RESET #define __ADC1_RELEASE_RESET __HAL_RCC_ADC1_RELEASE_RESET #define __ADC1_CLK_SLEEP_ENABLE __HAL_RCC_ADC1_CLK_SLEEP_ENABLE #define __ADC1_CLK_SLEEP_DISABLE __HAL_RCC_ADC1_CLK_SLEEP_DISABLE #define __ADC2_CLK_DISABLE __HAL_RCC_ADC2_CLK_DISABLE #define __ADC2_CLK_ENABLE __HAL_RCC_ADC2_CLK_ENABLE #define __ADC2_FORCE_RESET __HAL_RCC_ADC2_FORCE_RESET #define __ADC2_RELEASE_RESET __HAL_RCC_ADC2_RELEASE_RESET #define __ADC3_CLK_DISABLE __HAL_RCC_ADC3_CLK_DISABLE #define __ADC3_CLK_ENABLE __HAL_RCC_ADC3_CLK_ENABLE #define __ADC3_FORCE_RESET __HAL_RCC_ADC3_FORCE_RESET #define __ADC3_RELEASE_RESET __HAL_RCC_ADC3_RELEASE_RESET #define __AES_CLK_DISABLE __HAL_RCC_AES_CLK_DISABLE #define __AES_CLK_ENABLE __HAL_RCC_AES_CLK_ENABLE #define __AES_CLK_SLEEP_DISABLE __HAL_RCC_AES_CLK_SLEEP_DISABLE #define __AES_CLK_SLEEP_ENABLE __HAL_RCC_AES_CLK_SLEEP_ENABLE #define __AES_FORCE_RESET __HAL_RCC_AES_FORCE_RESET #define __AES_RELEASE_RESET __HAL_RCC_AES_RELEASE_RESET #define __CRYP_CLK_SLEEP_ENABLE __HAL_RCC_CRYP_CLK_SLEEP_ENABLE #define __CRYP_CLK_SLEEP_DISABLE __HAL_RCC_CRYP_CLK_SLEEP_DISABLE #define __CRYP_CLK_ENABLE __HAL_RCC_CRYP_CLK_ENABLE #define __CRYP_CLK_DISABLE __HAL_RCC_CRYP_CLK_DISABLE #define __CRYP_FORCE_RESET __HAL_RCC_CRYP_FORCE_RESET #define __CRYP_RELEASE_RESET __HAL_RCC_CRYP_RELEASE_RESET #define __AFIO_CLK_DISABLE __HAL_RCC_AFIO_CLK_DISABLE #define __AFIO_CLK_ENABLE __HAL_RCC_AFIO_CLK_ENABLE #define __AFIO_FORCE_RESET __HAL_RCC_AFIO_FORCE_RESET #define __AFIO_RELEASE_RESET __HAL_RCC_AFIO_RELEASE_RESET #define __AHB_FORCE_RESET __HAL_RCC_AHB_FORCE_RESET #define __AHB_RELEASE_RESET __HAL_RCC_AHB_RELEASE_RESET #define __AHB1_FORCE_RESET __HAL_RCC_AHB1_FORCE_RESET #define __AHB1_RELEASE_RESET __HAL_RCC_AHB1_RELEASE_RESET #define __AHB2_FORCE_RESET __HAL_RCC_AHB2_FORCE_RESET #define __AHB2_RELEASE_RESET __HAL_RCC_AHB2_RELEASE_RESET #define __AHB3_FORCE_RESET __HAL_RCC_AHB3_FORCE_RESET #define __AHB3_RELEASE_RESET __HAL_RCC_AHB3_RELEASE_RESET #define __APB1_FORCE_RESET __HAL_RCC_APB1_FORCE_RESET #define __APB1_RELEASE_RESET __HAL_RCC_APB1_RELEASE_RESET #define __APB2_FORCE_RESET __HAL_RCC_APB2_FORCE_RESET #define __APB2_RELEASE_RESET __HAL_RCC_APB2_RELEASE_RESET #define __BKP_CLK_DISABLE __HAL_RCC_BKP_CLK_DISABLE #define __BKP_CLK_ENABLE __HAL_RCC_BKP_CLK_ENABLE #define __BKP_FORCE_RESET __HAL_RCC_BKP_FORCE_RESET #define __BKP_RELEASE_RESET __HAL_RCC_BKP_RELEASE_RESET #define __CAN1_CLK_DISABLE __HAL_RCC_CAN1_CLK_DISABLE #define __CAN1_CLK_ENABLE __HAL_RCC_CAN1_CLK_ENABLE #define __CAN1_CLK_SLEEP_DISABLE __HAL_RCC_CAN1_CLK_SLEEP_DISABLE #define __CAN1_CLK_SLEEP_ENABLE __HAL_RCC_CAN1_CLK_SLEEP_ENABLE #define __CAN1_FORCE_RESET __HAL_RCC_CAN1_FORCE_RESET #define __CAN1_RELEASE_RESET __HAL_RCC_CAN1_RELEASE_RESET #define __CAN_CLK_DISABLE __HAL_RCC_CAN1_CLK_DISABLE #define __CAN_CLK_ENABLE __HAL_RCC_CAN1_CLK_ENABLE #define __CAN_FORCE_RESET __HAL_RCC_CAN1_FORCE_RESET #define __CAN_RELEASE_RESET __HAL_RCC_CAN1_RELEASE_RESET #define __CAN2_CLK_DISABLE __HAL_RCC_CAN2_CLK_DISABLE #define __CAN2_CLK_ENABLE __HAL_RCC_CAN2_CLK_ENABLE #define __CAN2_FORCE_RESET __HAL_RCC_CAN2_FORCE_RESET #define __CAN2_RELEASE_RESET __HAL_RCC_CAN2_RELEASE_RESET #define __CEC_CLK_DISABLE __HAL_RCC_CEC_CLK_DISABLE #define __CEC_CLK_ENABLE __HAL_RCC_CEC_CLK_ENABLE #define __COMP_CLK_DISABLE __HAL_RCC_COMP_CLK_DISABLE #define __COMP_CLK_ENABLE __HAL_RCC_COMP_CLK_ENABLE #define __COMP_FORCE_RESET __HAL_RCC_COMP_FORCE_RESET #define __COMP_RELEASE_RESET __HAL_RCC_COMP_RELEASE_RESET #define __COMP_CLK_SLEEP_ENABLE __HAL_RCC_COMP_CLK_SLEEP_ENABLE #define __COMP_CLK_SLEEP_DISABLE __HAL_RCC_COMP_CLK_SLEEP_DISABLE #define __CEC_FORCE_RESET __HAL_RCC_CEC_FORCE_RESET #define __CEC_RELEASE_RESET __HAL_RCC_CEC_RELEASE_RESET #define __CRC_CLK_DISABLE __HAL_RCC_CRC_CLK_DISABLE #define __CRC_CLK_ENABLE __HAL_RCC_CRC_CLK_ENABLE #define __CRC_CLK_SLEEP_DISABLE __HAL_RCC_CRC_CLK_SLEEP_DISABLE #define __CRC_CLK_SLEEP_ENABLE __HAL_RCC_CRC_CLK_SLEEP_ENABLE #define __CRC_FORCE_RESET __HAL_RCC_CRC_FORCE_RESET #define __CRC_RELEASE_RESET __HAL_RCC_CRC_RELEASE_RESET #define __DAC_CLK_DISABLE __HAL_RCC_DAC_CLK_DISABLE #define __DAC_CLK_ENABLE __HAL_RCC_DAC_CLK_ENABLE #define __DAC_FORCE_RESET __HAL_RCC_DAC_FORCE_RESET #define __DAC_RELEASE_RESET __HAL_RCC_DAC_RELEASE_RESET #define __DAC1_CLK_DISABLE __HAL_RCC_DAC1_CLK_DISABLE #define __DAC1_CLK_ENABLE __HAL_RCC_DAC1_CLK_ENABLE #define __DAC1_CLK_SLEEP_DISABLE __HAL_RCC_DAC1_CLK_SLEEP_DISABLE #define __DAC1_CLK_SLEEP_ENABLE __HAL_RCC_DAC1_CLK_SLEEP_ENABLE #define __DAC1_FORCE_RESET __HAL_RCC_DAC1_FORCE_RESET #define __DAC1_RELEASE_RESET __HAL_RCC_DAC1_RELEASE_RESET #define __DBGMCU_CLK_ENABLE __HAL_RCC_DBGMCU_CLK_ENABLE #define __DBGMCU_CLK_DISABLE __HAL_RCC_DBGMCU_CLK_DISABLE #define __DBGMCU_FORCE_RESET __HAL_RCC_DBGMCU_FORCE_RESET #define __DBGMCU_RELEASE_RESET __HAL_RCC_DBGMCU_RELEASE_RESET #define __DFSDM_CLK_DISABLE __HAL_RCC_DFSDM_CLK_DISABLE #define __DFSDM_CLK_ENABLE __HAL_RCC_DFSDM_CLK_ENABLE #define __DFSDM_CLK_SLEEP_DISABLE __HAL_RCC_DFSDM_CLK_SLEEP_DISABLE #define __DFSDM_CLK_SLEEP_ENABLE __HAL_RCC_DFSDM_CLK_SLEEP_ENABLE #define __DFSDM_FORCE_RESET __HAL_RCC_DFSDM_FORCE_RESET #define __DFSDM_RELEASE_RESET __HAL_RCC_DFSDM_RELEASE_RESET #define __DMA1_CLK_DISABLE __HAL_RCC_DMA1_CLK_DISABLE #define __DMA1_CLK_ENABLE __HAL_RCC_DMA1_CLK_ENABLE #define __DMA1_CLK_SLEEP_DISABLE __HAL_RCC_DMA1_CLK_SLEEP_DISABLE #define __DMA1_CLK_SLEEP_ENABLE __HAL_RCC_DMA1_CLK_SLEEP_ENABLE #define __DMA1_FORCE_RESET __HAL_RCC_DMA1_FORCE_RESET #define __DMA1_RELEASE_RESET __HAL_RCC_DMA1_RELEASE_RESET #define __DMA2_CLK_DISABLE __HAL_RCC_DMA2_CLK_DISABLE #define __DMA2_CLK_ENABLE __HAL_RCC_DMA2_CLK_ENABLE #define __DMA2_CLK_SLEEP_DISABLE __HAL_RCC_DMA2_CLK_SLEEP_DISABLE #define __DMA2_CLK_SLEEP_ENABLE __HAL_RCC_DMA2_CLK_SLEEP_ENABLE #define __DMA2_FORCE_RESET __HAL_RCC_DMA2_FORCE_RESET #define __DMA2_RELEASE_RESET __HAL_RCC_DMA2_RELEASE_RESET #define __ETHMAC_CLK_DISABLE __HAL_RCC_ETHMAC_CLK_DISABLE #define __ETHMAC_CLK_ENABLE __HAL_RCC_ETHMAC_CLK_ENABLE #define __ETHMAC_FORCE_RESET __HAL_RCC_ETHMAC_FORCE_RESET #define __ETHMAC_RELEASE_RESET __HAL_RCC_ETHMAC_RELEASE_RESET #define __ETHMACRX_CLK_DISABLE __HAL_RCC_ETHMACRX_CLK_DISABLE #define __ETHMACRX_CLK_ENABLE __HAL_RCC_ETHMACRX_CLK_ENABLE #define __ETHMACTX_CLK_DISABLE __HAL_RCC_ETHMACTX_CLK_DISABLE #define __ETHMACTX_CLK_ENABLE __HAL_RCC_ETHMACTX_CLK_ENABLE #define __FIREWALL_CLK_DISABLE __HAL_RCC_FIREWALL_CLK_DISABLE #define __FIREWALL_CLK_ENABLE __HAL_RCC_FIREWALL_CLK_ENABLE #define __FLASH_CLK_DISABLE __HAL_RCC_FLASH_CLK_DISABLE #define __FLASH_CLK_ENABLE __HAL_RCC_FLASH_CLK_ENABLE #define __FLASH_CLK_SLEEP_DISABLE __HAL_RCC_FLASH_CLK_SLEEP_DISABLE #define __FLASH_CLK_SLEEP_ENABLE __HAL_RCC_FLASH_CLK_SLEEP_ENABLE #define __FLASH_FORCE_RESET __HAL_RCC_FLASH_FORCE_RESET #define __FLASH_RELEASE_RESET __HAL_RCC_FLASH_RELEASE_RESET #define __FLITF_CLK_DISABLE __HAL_RCC_FLITF_CLK_DISABLE #define __FLITF_CLK_ENABLE __HAL_RCC_FLITF_CLK_ENABLE #define __FLITF_FORCE_RESET __HAL_RCC_FLITF_FORCE_RESET #define __FLITF_RELEASE_RESET __HAL_RCC_FLITF_RELEASE_RESET #define __FLITF_CLK_SLEEP_ENABLE __HAL_RCC_FLITF_CLK_SLEEP_ENABLE #define __FLITF_CLK_SLEEP_DISABLE __HAL_RCC_FLITF_CLK_SLEEP_DISABLE #define __FMC_CLK_DISABLE __HAL_RCC_FMC_CLK_DISABLE #define __FMC_CLK_ENABLE __HAL_RCC_FMC_CLK_ENABLE #define __FMC_CLK_SLEEP_DISABLE __HAL_RCC_FMC_CLK_SLEEP_DISABLE #define __FMC_CLK_SLEEP_ENABLE __HAL_RCC_FMC_CLK_SLEEP_ENABLE #define __FMC_FORCE_RESET __HAL_RCC_FMC_FORCE_RESET #define __FMC_RELEASE_RESET __HAL_RCC_FMC_RELEASE_RESET #define __FSMC_CLK_DISABLE __HAL_RCC_FSMC_CLK_DISABLE #define __FSMC_CLK_ENABLE __HAL_RCC_FSMC_CLK_ENABLE #define __GPIOA_CLK_DISABLE __HAL_RCC_GPIOA_CLK_DISABLE #define __GPIOA_CLK_ENABLE __HAL_RCC_GPIOA_CLK_ENABLE #define __GPIOA_CLK_SLEEP_DISABLE __HAL_RCC_GPIOA_CLK_SLEEP_DISABLE #define __GPIOA_CLK_SLEEP_ENABLE __HAL_RCC_GPIOA_CLK_SLEEP_ENABLE #define __GPIOA_FORCE_RESET __HAL_RCC_GPIOA_FORCE_RESET #define __GPIOA_RELEASE_RESET __HAL_RCC_GPIOA_RELEASE_RESET #define __GPIOB_CLK_DISABLE __HAL_RCC_GPIOB_CLK_DISABLE #define __GPIOB_CLK_ENABLE __HAL_RCC_GPIOB_CLK_ENABLE #define __GPIOB_CLK_SLEEP_DISABLE __HAL_RCC_GPIOB_CLK_SLEEP_DISABLE #define __GPIOB_CLK_SLEEP_ENABLE __HAL_RCC_GPIOB_CLK_SLEEP_ENABLE #define __GPIOB_FORCE_RESET __HAL_RCC_GPIOB_FORCE_RESET #define __GPIOB_RELEASE_RESET __HAL_RCC_GPIOB_RELEASE_RESET #define __GPIOC_CLK_DISABLE __HAL_RCC_GPIOC_CLK_DISABLE #define __GPIOC_CLK_ENABLE __HAL_RCC_GPIOC_CLK_ENABLE #define __GPIOC_CLK_SLEEP_DISABLE __HAL_RCC_GPIOC_CLK_SLEEP_DISABLE #define __GPIOC_CLK_SLEEP_ENABLE __HAL_RCC_GPIOC_CLK_SLEEP_ENABLE #define __GPIOC_FORCE_RESET __HAL_RCC_GPIOC_FORCE_RESET #define __GPIOC_RELEASE_RESET __HAL_RCC_GPIOC_RELEASE_RESET #define __GPIOD_CLK_DISABLE __HAL_RCC_GPIOD_CLK_DISABLE #define __GPIOD_CLK_ENABLE __HAL_RCC_GPIOD_CLK_ENABLE #define __GPIOD_CLK_SLEEP_DISABLE __HAL_RCC_GPIOD_CLK_SLEEP_DISABLE #define __GPIOD_CLK_SLEEP_ENABLE __HAL_RCC_GPIOD_CLK_SLEEP_ENABLE #define __GPIOD_FORCE_RESET __HAL_RCC_GPIOD_FORCE_RESET #define __GPIOD_RELEASE_RESET __HAL_RCC_GPIOD_RELEASE_RESET #define __GPIOE_CLK_DISABLE __HAL_RCC_GPIOE_CLK_DISABLE #define __GPIOE_CLK_ENABLE __HAL_RCC_GPIOE_CLK_ENABLE #define __GPIOE_CLK_SLEEP_DISABLE __HAL_RCC_GPIOE_CLK_SLEEP_DISABLE #define __GPIOE_CLK_SLEEP_ENABLE __HAL_RCC_GPIOE_CLK_SLEEP_ENABLE #define __GPIOE_FORCE_RESET __HAL_RCC_GPIOE_FORCE_RESET #define __GPIOE_RELEASE_RESET __HAL_RCC_GPIOE_RELEASE_RESET #define __GPIOF_CLK_DISABLE __HAL_RCC_GPIOF_CLK_DISABLE #define __GPIOF_CLK_ENABLE __HAL_RCC_GPIOF_CLK_ENABLE #define __GPIOF_CLK_SLEEP_DISABLE __HAL_RCC_GPIOF_CLK_SLEEP_DISABLE #define __GPIOF_CLK_SLEEP_ENABLE __HAL_RCC_GPIOF_CLK_SLEEP_ENABLE #define __GPIOF_FORCE_RESET __HAL_RCC_GPIOF_FORCE_RESET #define __GPIOF_RELEASE_RESET __HAL_RCC_GPIOF_RELEASE_RESET #define __GPIOG_CLK_DISABLE __HAL_RCC_GPIOG_CLK_DISABLE #define __GPIOG_CLK_ENABLE __HAL_RCC_GPIOG_CLK_ENABLE #define __GPIOG_CLK_SLEEP_DISABLE __HAL_RCC_GPIOG_CLK_SLEEP_DISABLE #define __GPIOG_CLK_SLEEP_ENABLE __HAL_RCC_GPIOG_CLK_SLEEP_ENABLE #define __GPIOG_FORCE_RESET __HAL_RCC_GPIOG_FORCE_RESET #define __GPIOG_RELEASE_RESET __HAL_RCC_GPIOG_RELEASE_RESET #define __GPIOH_CLK_DISABLE __HAL_RCC_GPIOH_CLK_DISABLE #define __GPIOH_CLK_ENABLE __HAL_RCC_GPIOH_CLK_ENABLE #define __GPIOH_CLK_SLEEP_DISABLE __HAL_RCC_GPIOH_CLK_SLEEP_DISABLE #define __GPIOH_CLK_SLEEP_ENABLE __HAL_RCC_GPIOH_CLK_SLEEP_ENABLE #define __GPIOH_FORCE_RESET __HAL_RCC_GPIOH_FORCE_RESET #define __GPIOH_RELEASE_RESET __HAL_RCC_GPIOH_RELEASE_RESET #define __I2C1_CLK_DISABLE __HAL_RCC_I2C1_CLK_DISABLE #define __I2C1_CLK_ENABLE __HAL_RCC_I2C1_CLK_ENABLE #define __I2C1_CLK_SLEEP_DISABLE __HAL_RCC_I2C1_CLK_SLEEP_DISABLE #define __I2C1_CLK_SLEEP_ENABLE __HAL_RCC_I2C1_CLK_SLEEP_ENABLE #define __I2C1_FORCE_RESET __HAL_RCC_I2C1_FORCE_RESET #define __I2C1_RELEASE_RESET __HAL_RCC_I2C1_RELEASE_RESET #define __I2C2_CLK_DISABLE __HAL_RCC_I2C2_CLK_DISABLE #define __I2C2_CLK_ENABLE __HAL_RCC_I2C2_CLK_ENABLE #define __I2C2_CLK_SLEEP_DISABLE __HAL_RCC_I2C2_CLK_SLEEP_DISABLE #define __I2C2_CLK_SLEEP_ENABLE __HAL_RCC_I2C2_CLK_SLEEP_ENABLE #define __I2C2_FORCE_RESET __HAL_RCC_I2C2_FORCE_RESET #define __I2C2_RELEASE_RESET __HAL_RCC_I2C2_RELEASE_RESET #define __I2C3_CLK_DISABLE __HAL_RCC_I2C3_CLK_DISABLE #define __I2C3_CLK_ENABLE __HAL_RCC_I2C3_CLK_ENABLE #define __I2C3_CLK_SLEEP_DISABLE __HAL_RCC_I2C3_CLK_SLEEP_DISABLE #define __I2C3_CLK_SLEEP_ENABLE __HAL_RCC_I2C3_CLK_SLEEP_ENABLE #define __I2C3_FORCE_RESET __HAL_RCC_I2C3_FORCE_RESET #define __I2C3_RELEASE_RESET __HAL_RCC_I2C3_RELEASE_RESET #define __LCD_CLK_DISABLE __HAL_RCC_LCD_CLK_DISABLE #define __LCD_CLK_ENABLE __HAL_RCC_LCD_CLK_ENABLE #define __LCD_CLK_SLEEP_DISABLE __HAL_RCC_LCD_CLK_SLEEP_DISABLE #define __LCD_CLK_SLEEP_ENABLE __HAL_RCC_LCD_CLK_SLEEP_ENABLE #define __LCD_FORCE_RESET __HAL_RCC_LCD_FORCE_RESET #define __LCD_RELEASE_RESET __HAL_RCC_LCD_RELEASE_RESET #define __LPTIM1_CLK_DISABLE __HAL_RCC_LPTIM1_CLK_DISABLE #define __LPTIM1_CLK_ENABLE __HAL_RCC_LPTIM1_CLK_ENABLE #define __LPTIM1_CLK_SLEEP_DISABLE __HAL_RCC_LPTIM1_CLK_SLEEP_DISABLE #define __LPTIM1_CLK_SLEEP_ENABLE __HAL_RCC_LPTIM1_CLK_SLEEP_ENABLE #define __LPTIM1_FORCE_RESET __HAL_RCC_LPTIM1_FORCE_RESET #define __LPTIM1_RELEASE_RESET __HAL_RCC_LPTIM1_RELEASE_RESET #define __LPTIM2_CLK_DISABLE __HAL_RCC_LPTIM2_CLK_DISABLE #define __LPTIM2_CLK_ENABLE __HAL_RCC_LPTIM2_CLK_ENABLE #define __LPTIM2_CLK_SLEEP_DISABLE __HAL_RCC_LPTIM2_CLK_SLEEP_DISABLE #define __LPTIM2_CLK_SLEEP_ENABLE __HAL_RCC_LPTIM2_CLK_SLEEP_ENABLE #define __LPTIM2_FORCE_RESET __HAL_RCC_LPTIM2_FORCE_RESET #define __LPTIM2_RELEASE_RESET __HAL_RCC_LPTIM2_RELEASE_RESET #define __LPUART1_CLK_DISABLE __HAL_RCC_LPUART1_CLK_DISABLE #define __LPUART1_CLK_ENABLE __HAL_RCC_LPUART1_CLK_ENABLE #define __LPUART1_CLK_SLEEP_DISABLE __HAL_RCC_LPUART1_CLK_SLEEP_DISABLE #define __LPUART1_CLK_SLEEP_ENABLE __HAL_RCC_LPUART1_CLK_SLEEP_ENABLE #define __LPUART1_FORCE_RESET __HAL_RCC_LPUART1_FORCE_RESET #define __LPUART1_RELEASE_RESET __HAL_RCC_LPUART1_RELEASE_RESET #define __OPAMP_CLK_DISABLE __HAL_RCC_OPAMP_CLK_DISABLE #define __OPAMP_CLK_ENABLE __HAL_RCC_OPAMP_CLK_ENABLE #define __OPAMP_CLK_SLEEP_DISABLE __HAL_RCC_OPAMP_CLK_SLEEP_DISABLE #define __OPAMP_CLK_SLEEP_ENABLE __HAL_RCC_OPAMP_CLK_SLEEP_ENABLE #define __OPAMP_FORCE_RESET __HAL_RCC_OPAMP_FORCE_RESET #define __OPAMP_RELEASE_RESET __HAL_RCC_OPAMP_RELEASE_RESET #define __OTGFS_CLK_DISABLE __HAL_RCC_OTGFS_CLK_DISABLE #define __OTGFS_CLK_ENABLE __HAL_RCC_OTGFS_CLK_ENABLE #define __OTGFS_CLK_SLEEP_DISABLE __HAL_RCC_OTGFS_CLK_SLEEP_DISABLE #define __OTGFS_CLK_SLEEP_ENABLE __HAL_RCC_OTGFS_CLK_SLEEP_ENABLE #define __OTGFS_FORCE_RESET __HAL_RCC_OTGFS_FORCE_RESET #define __OTGFS_RELEASE_RESET __HAL_RCC_OTGFS_RELEASE_RESET #define __PWR_CLK_DISABLE __HAL_RCC_PWR_CLK_DISABLE #define __PWR_CLK_ENABLE __HAL_RCC_PWR_CLK_ENABLE #define __PWR_CLK_SLEEP_DISABLE __HAL_RCC_PWR_CLK_SLEEP_DISABLE #define __PWR_CLK_SLEEP_ENABLE __HAL_RCC_PWR_CLK_SLEEP_ENABLE #define __PWR_FORCE_RESET __HAL_RCC_PWR_FORCE_RESET #define __PWR_RELEASE_RESET __HAL_RCC_PWR_RELEASE_RESET #define __QSPI_CLK_DISABLE __HAL_RCC_QSPI_CLK_DISABLE #define __QSPI_CLK_ENABLE __HAL_RCC_QSPI_CLK_ENABLE #define __QSPI_CLK_SLEEP_DISABLE __HAL_RCC_QSPI_CLK_SLEEP_DISABLE #define __QSPI_CLK_SLEEP_ENABLE __HAL_RCC_QSPI_CLK_SLEEP_ENABLE #define __QSPI_FORCE_RESET __HAL_RCC_QSPI_FORCE_RESET #define __QSPI_RELEASE_RESET __HAL_RCC_QSPI_RELEASE_RESET #define __RNG_CLK_DISABLE __HAL_RCC_RNG_CLK_DISABLE #define __RNG_CLK_ENABLE __HAL_RCC_RNG_CLK_ENABLE #define __RNG_CLK_SLEEP_DISABLE __HAL_RCC_RNG_CLK_SLEEP_DISABLE #define __RNG_CLK_SLEEP_ENABLE __HAL_RCC_RNG_CLK_SLEEP_ENABLE #define __RNG_FORCE_RESET __HAL_RCC_RNG_FORCE_RESET #define __RNG_RELEASE_RESET __HAL_RCC_RNG_RELEASE_RESET #define __SAI1_CLK_DISABLE __HAL_RCC_SAI1_CLK_DISABLE #define __SAI1_CLK_ENABLE __HAL_RCC_SAI1_CLK_ENABLE #define __SAI1_CLK_SLEEP_DISABLE __HAL_RCC_SAI1_CLK_SLEEP_DISABLE #define __SAI1_CLK_SLEEP_ENABLE __HAL_RCC_SAI1_CLK_SLEEP_ENABLE #define __SAI1_FORCE_RESET __HAL_RCC_SAI1_FORCE_RESET #define __SAI1_RELEASE_RESET __HAL_RCC_SAI1_RELEASE_RESET #define __SAI2_CLK_DISABLE __HAL_RCC_SAI2_CLK_DISABLE #define __SAI2_CLK_ENABLE __HAL_RCC_SAI2_CLK_ENABLE #define __SAI2_CLK_SLEEP_DISABLE __HAL_RCC_SAI2_CLK_SLEEP_DISABLE #define __SAI2_CLK_SLEEP_ENABLE __HAL_RCC_SAI2_CLK_SLEEP_ENABLE #define __SAI2_FORCE_RESET __HAL_RCC_SAI2_FORCE_RESET #define __SAI2_RELEASE_RESET __HAL_RCC_SAI2_RELEASE_RESET #define __SDIO_CLK_DISABLE __HAL_RCC_SDIO_CLK_DISABLE #define __SDIO_CLK_ENABLE __HAL_RCC_SDIO_CLK_ENABLE #define __SDMMC_CLK_DISABLE __HAL_RCC_SDMMC_CLK_DISABLE #define __SDMMC_CLK_ENABLE __HAL_RCC_SDMMC_CLK_ENABLE #define __SDMMC_CLK_SLEEP_DISABLE __HAL_RCC_SDMMC_CLK_SLEEP_DISABLE #define __SDMMC_CLK_SLEEP_ENABLE __HAL_RCC_SDMMC_CLK_SLEEP_ENABLE #define __SDMMC_FORCE_RESET __HAL_RCC_SDMMC_FORCE_RESET #define __SDMMC_RELEASE_RESET __HAL_RCC_SDMMC_RELEASE_RESET #define __SPI1_CLK_DISABLE __HAL_RCC_SPI1_CLK_DISABLE #define __SPI1_CLK_ENABLE __HAL_RCC_SPI1_CLK_ENABLE #define __SPI1_CLK_SLEEP_DISABLE __HAL_RCC_SPI1_CLK_SLEEP_DISABLE #define __SPI1_CLK_SLEEP_ENABLE __HAL_RCC_SPI1_CLK_SLEEP_ENABLE #define __SPI1_FORCE_RESET __HAL_RCC_SPI1_FORCE_RESET #define __SPI1_RELEASE_RESET __HAL_RCC_SPI1_RELEASE_RESET #define __SPI2_CLK_DISABLE __HAL_RCC_SPI2_CLK_DISABLE #define __SPI2_CLK_ENABLE __HAL_RCC_SPI2_CLK_ENABLE #define __SPI2_CLK_SLEEP_DISABLE __HAL_RCC_SPI2_CLK_SLEEP_DISABLE #define __SPI2_CLK_SLEEP_ENABLE __HAL_RCC_SPI2_CLK_SLEEP_ENABLE #define __SPI2_FORCE_RESET __HAL_RCC_SPI2_FORCE_RESET #define __SPI2_RELEASE_RESET __HAL_RCC_SPI2_RELEASE_RESET #define __SPI3_CLK_DISABLE __HAL_RCC_SPI3_CLK_DISABLE #define __SPI3_CLK_ENABLE __HAL_RCC_SPI3_CLK_ENABLE #define __SPI3_CLK_SLEEP_DISABLE __HAL_RCC_SPI3_CLK_SLEEP_DISABLE #define __SPI3_CLK_SLEEP_ENABLE __HAL_RCC_SPI3_CLK_SLEEP_ENABLE #define __SPI3_FORCE_RESET __HAL_RCC_SPI3_FORCE_RESET #define __SPI3_RELEASE_RESET __HAL_RCC_SPI3_RELEASE_RESET #define __SRAM_CLK_DISABLE __HAL_RCC_SRAM_CLK_DISABLE #define __SRAM_CLK_ENABLE __HAL_RCC_SRAM_CLK_ENABLE #define __SRAM1_CLK_SLEEP_DISABLE __HAL_RCC_SRAM1_CLK_SLEEP_DISABLE #define __SRAM1_CLK_SLEEP_ENABLE __HAL_RCC_SRAM1_CLK_SLEEP_ENABLE #define __SRAM2_CLK_SLEEP_DISABLE __HAL_RCC_SRAM2_CLK_SLEEP_DISABLE #define __SRAM2_CLK_SLEEP_ENABLE __HAL_RCC_SRAM2_CLK_SLEEP_ENABLE #define __SWPMI1_CLK_DISABLE __HAL_RCC_SWPMI1_CLK_DISABLE #define __SWPMI1_CLK_ENABLE __HAL_RCC_SWPMI1_CLK_ENABLE #define __SWPMI1_CLK_SLEEP_DISABLE __HAL_RCC_SWPMI1_CLK_SLEEP_DISABLE #define __SWPMI1_CLK_SLEEP_ENABLE __HAL_RCC_SWPMI1_CLK_SLEEP_ENABLE #define __SWPMI1_FORCE_RESET __HAL_RCC_SWPMI1_FORCE_RESET #define __SWPMI1_RELEASE_RESET __HAL_RCC_SWPMI1_RELEASE_RESET #define __SYSCFG_CLK_DISABLE __HAL_RCC_SYSCFG_CLK_DISABLE #define __SYSCFG_CLK_ENABLE __HAL_RCC_SYSCFG_CLK_ENABLE #define __SYSCFG_CLK_SLEEP_DISABLE __HAL_RCC_SYSCFG_CLK_SLEEP_DISABLE #define __SYSCFG_CLK_SLEEP_ENABLE __HAL_RCC_SYSCFG_CLK_SLEEP_ENABLE #define __SYSCFG_FORCE_RESET __HAL_RCC_SYSCFG_FORCE_RESET #define __SYSCFG_RELEASE_RESET __HAL_RCC_SYSCFG_RELEASE_RESET #define __TIM1_CLK_DISABLE __HAL_RCC_TIM1_CLK_DISABLE #define __TIM1_CLK_ENABLE __HAL_RCC_TIM1_CLK_ENABLE #define __TIM1_CLK_SLEEP_DISABLE __HAL_RCC_TIM1_CLK_SLEEP_DISABLE #define __TIM1_CLK_SLEEP_ENABLE __HAL_RCC_TIM1_CLK_SLEEP_ENABLE #define __TIM1_FORCE_RESET __HAL_RCC_TIM1_FORCE_RESET #define __TIM1_RELEASE_RESET __HAL_RCC_TIM1_RELEASE_RESET #define __TIM10_CLK_DISABLE __HAL_RCC_TIM10_CLK_DISABLE #define __TIM10_CLK_ENABLE __HAL_RCC_TIM10_CLK_ENABLE #define __TIM10_FORCE_RESET __HAL_RCC_TIM10_FORCE_RESET #define __TIM10_RELEASE_RESET __HAL_RCC_TIM10_RELEASE_RESET #define __TIM11_CLK_DISABLE __HAL_RCC_TIM11_CLK_DISABLE #define __TIM11_CLK_ENABLE __HAL_RCC_TIM11_CLK_ENABLE #define __TIM11_FORCE_RESET __HAL_RCC_TIM11_FORCE_RESET #define __TIM11_RELEASE_RESET __HAL_RCC_TIM11_RELEASE_RESET #define __TIM12_CLK_DISABLE __HAL_RCC_TIM12_CLK_DISABLE #define __TIM12_CLK_ENABLE __HAL_RCC_TIM12_CLK_ENABLE #define __TIM12_FORCE_RESET __HAL_RCC_TIM12_FORCE_RESET #define __TIM12_RELEASE_RESET __HAL_RCC_TIM12_RELEASE_RESET #define __TIM13_CLK_DISABLE __HAL_RCC_TIM13_CLK_DISABLE #define __TIM13_CLK_ENABLE __HAL_RCC_TIM13_CLK_ENABLE #define __TIM13_FORCE_RESET __HAL_RCC_TIM13_FORCE_RESET #define __TIM13_RELEASE_RESET __HAL_RCC_TIM13_RELEASE_RESET #define __TIM14_CLK_DISABLE __HAL_RCC_TIM14_CLK_DISABLE #define __TIM14_CLK_ENABLE __HAL_RCC_TIM14_CLK_ENABLE #define __TIM14_FORCE_RESET __HAL_RCC_TIM14_FORCE_RESET #define __TIM14_RELEASE_RESET __HAL_RCC_TIM14_RELEASE_RESET #define __TIM15_CLK_DISABLE __HAL_RCC_TIM15_CLK_DISABLE #define __TIM15_CLK_ENABLE __HAL_RCC_TIM15_CLK_ENABLE #define __TIM15_CLK_SLEEP_DISABLE __HAL_RCC_TIM15_CLK_SLEEP_DISABLE #define __TIM15_CLK_SLEEP_ENABLE __HAL_RCC_TIM15_CLK_SLEEP_ENABLE #define __TIM15_FORCE_RESET __HAL_RCC_TIM15_FORCE_RESET #define __TIM15_RELEASE_RESET __HAL_RCC_TIM15_RELEASE_RESET #define __TIM16_CLK_DISABLE __HAL_RCC_TIM16_CLK_DISABLE #define __TIM16_CLK_ENABLE __HAL_RCC_TIM16_CLK_ENABLE #define __TIM16_CLK_SLEEP_DISABLE __HAL_RCC_TIM16_CLK_SLEEP_DISABLE #define __TIM16_CLK_SLEEP_ENABLE __HAL_RCC_TIM16_CLK_SLEEP_ENABLE #define __TIM16_FORCE_RESET __HAL_RCC_TIM16_FORCE_RESET #define __TIM16_RELEASE_RESET __HAL_RCC_TIM16_RELEASE_RESET #define __TIM17_CLK_DISABLE __HAL_RCC_TIM17_CLK_DISABLE #define __TIM17_CLK_ENABLE __HAL_RCC_TIM17_CLK_ENABLE #define __TIM17_CLK_SLEEP_DISABLE __HAL_RCC_TIM17_CLK_SLEEP_DISABLE #define __TIM17_CLK_SLEEP_ENABLE __HAL_RCC_TIM17_CLK_SLEEP_ENABLE #define __TIM17_FORCE_RESET __HAL_RCC_TIM17_FORCE_RESET #define __TIM17_RELEASE_RESET __HAL_RCC_TIM17_RELEASE_RESET #define __TIM2_CLK_DISABLE __HAL_RCC_TIM2_CLK_DISABLE #define __TIM2_CLK_ENABLE __HAL_RCC_TIM2_CLK_ENABLE #define __TIM2_CLK_SLEEP_DISABLE __HAL_RCC_TIM2_CLK_SLEEP_DISABLE #define __TIM2_CLK_SLEEP_ENABLE __HAL_RCC_TIM2_CLK_SLEEP_ENABLE #define __TIM2_FORCE_RESET __HAL_RCC_TIM2_FORCE_RESET #define __TIM2_RELEASE_RESET __HAL_RCC_TIM2_RELEASE_RESET #define __TIM3_CLK_DISABLE __HAL_RCC_TIM3_CLK_DISABLE #define __TIM3_CLK_ENABLE __HAL_RCC_TIM3_CLK_ENABLE #define __TIM3_CLK_SLEEP_DISABLE __HAL_RCC_TIM3_CLK_SLEEP_DISABLE #define __TIM3_CLK_SLEEP_ENABLE __HAL_RCC_TIM3_CLK_SLEEP_ENABLE #define __TIM3_FORCE_RESET __HAL_RCC_TIM3_FORCE_RESET #define __TIM3_RELEASE_RESET __HAL_RCC_TIM3_RELEASE_RESET #define __TIM4_CLK_DISABLE __HAL_RCC_TIM4_CLK_DISABLE #define __TIM4_CLK_ENABLE __HAL_RCC_TIM4_CLK_ENABLE #define __TIM4_CLK_SLEEP_DISABLE __HAL_RCC_TIM4_CLK_SLEEP_DISABLE #define __TIM4_CLK_SLEEP_ENABLE __HAL_RCC_TIM4_CLK_SLEEP_ENABLE #define __TIM4_FORCE_RESET __HAL_RCC_TIM4_FORCE_RESET #define __TIM4_RELEASE_RESET __HAL_RCC_TIM4_RELEASE_RESET #define __TIM5_CLK_DISABLE __HAL_RCC_TIM5_CLK_DISABLE #define __TIM5_CLK_ENABLE __HAL_RCC_TIM5_CLK_ENABLE #define __TIM5_CLK_SLEEP_DISABLE __HAL_RCC_TIM5_CLK_SLEEP_DISABLE #define __TIM5_CLK_SLEEP_ENABLE __HAL_RCC_TIM5_CLK_SLEEP_ENABLE #define __TIM5_FORCE_RESET __HAL_RCC_TIM5_FORCE_RESET #define __TIM5_RELEASE_RESET __HAL_RCC_TIM5_RELEASE_RESET #define __TIM6_CLK_DISABLE __HAL_RCC_TIM6_CLK_DISABLE #define __TIM6_CLK_ENABLE __HAL_RCC_TIM6_CLK_ENABLE #define __TIM6_CLK_SLEEP_DISABLE __HAL_RCC_TIM6_CLK_SLEEP_DISABLE #define __TIM6_CLK_SLEEP_ENABLE __HAL_RCC_TIM6_CLK_SLEEP_ENABLE #define __TIM6_FORCE_RESET __HAL_RCC_TIM6_FORCE_RESET #define __TIM6_RELEASE_RESET __HAL_RCC_TIM6_RELEASE_RESET #define __TIM7_CLK_DISABLE __HAL_RCC_TIM7_CLK_DISABLE #define __TIM7_CLK_ENABLE __HAL_RCC_TIM7_CLK_ENABLE #define __TIM7_CLK_SLEEP_DISABLE __HAL_RCC_TIM7_CLK_SLEEP_DISABLE #define __TIM7_CLK_SLEEP_ENABLE __HAL_RCC_TIM7_CLK_SLEEP_ENABLE #define __TIM7_FORCE_RESET __HAL_RCC_TIM7_FORCE_RESET #define __TIM7_RELEASE_RESET __HAL_RCC_TIM7_RELEASE_RESET #define __TIM8_CLK_DISABLE __HAL_RCC_TIM8_CLK_DISABLE #define __TIM8_CLK_ENABLE __HAL_RCC_TIM8_CLK_ENABLE #define __TIM8_CLK_SLEEP_DISABLE __HAL_RCC_TIM8_CLK_SLEEP_DISABLE #define __TIM8_CLK_SLEEP_ENABLE __HAL_RCC_TIM8_CLK_SLEEP_ENABLE #define __TIM8_FORCE_RESET __HAL_RCC_TIM8_FORCE_RESET #define __TIM8_RELEASE_RESET __HAL_RCC_TIM8_RELEASE_RESET #define __TIM9_CLK_DISABLE __HAL_RCC_TIM9_CLK_DISABLE #define __TIM9_CLK_ENABLE __HAL_RCC_TIM9_CLK_ENABLE #define __TIM9_FORCE_RESET __HAL_RCC_TIM9_FORCE_RESET #define __TIM9_RELEASE_RESET __HAL_RCC_TIM9_RELEASE_RESET #define __TSC_CLK_DISABLE __HAL_RCC_TSC_CLK_DISABLE #define __TSC_CLK_ENABLE __HAL_RCC_TSC_CLK_ENABLE #define __TSC_CLK_SLEEP_DISABLE __HAL_RCC_TSC_CLK_SLEEP_DISABLE #define __TSC_CLK_SLEEP_ENABLE __HAL_RCC_TSC_CLK_SLEEP_ENABLE #define __TSC_FORCE_RESET __HAL_RCC_TSC_FORCE_RESET #define __TSC_RELEASE_RESET __HAL_RCC_TSC_RELEASE_RESET #define __UART4_CLK_DISABLE __HAL_RCC_UART4_CLK_DISABLE #define __UART4_CLK_ENABLE __HAL_RCC_UART4_CLK_ENABLE #define __UART4_CLK_SLEEP_DISABLE __HAL_RCC_UART4_CLK_SLEEP_DISABLE #define __UART4_CLK_SLEEP_ENABLE __HAL_RCC_UART4_CLK_SLEEP_ENABLE #define __UART4_FORCE_RESET __HAL_RCC_UART4_FORCE_RESET #define __UART4_RELEASE_RESET __HAL_RCC_UART4_RELEASE_RESET #define __UART5_CLK_DISABLE __HAL_RCC_UART5_CLK_DISABLE #define __UART5_CLK_ENABLE __HAL_RCC_UART5_CLK_ENABLE #define __UART5_CLK_SLEEP_DISABLE __HAL_RCC_UART5_CLK_SLEEP_DISABLE #define __UART5_CLK_SLEEP_ENABLE __HAL_RCC_UART5_CLK_SLEEP_ENABLE #define __UART5_FORCE_RESET __HAL_RCC_UART5_FORCE_RESET #define __UART5_RELEASE_RESET __HAL_RCC_UART5_RELEASE_RESET #define __USART1_CLK_DISABLE __HAL_RCC_USART1_CLK_DISABLE #define __USART1_CLK_ENABLE __HAL_RCC_USART1_CLK_ENABLE #define __USART1_CLK_SLEEP_DISABLE __HAL_RCC_USART1_CLK_SLEEP_DISABLE #define __USART1_CLK_SLEEP_ENABLE __HAL_RCC_USART1_CLK_SLEEP_ENABLE #define __USART1_FORCE_RESET __HAL_RCC_USART1_FORCE_RESET #define __USART1_RELEASE_RESET __HAL_RCC_USART1_RELEASE_RESET #define __USART2_CLK_DISABLE __HAL_RCC_USART2_CLK_DISABLE #define __USART2_CLK_ENABLE __HAL_RCC_USART2_CLK_ENABLE #define __USART2_CLK_SLEEP_DISABLE __HAL_RCC_USART2_CLK_SLEEP_DISABLE #define __USART2_CLK_SLEEP_ENABLE __HAL_RCC_USART2_CLK_SLEEP_ENABLE #define __USART2_FORCE_RESET __HAL_RCC_USART2_FORCE_RESET #define __USART2_RELEASE_RESET __HAL_RCC_USART2_RELEASE_RESET #define __USART3_CLK_DISABLE __HAL_RCC_USART3_CLK_DISABLE #define __USART3_CLK_ENABLE __HAL_RCC_USART3_CLK_ENABLE #define __USART3_CLK_SLEEP_DISABLE __HAL_RCC_USART3_CLK_SLEEP_DISABLE #define __USART3_CLK_SLEEP_ENABLE __HAL_RCC_USART3_CLK_SLEEP_ENABLE #define __USART3_FORCE_RESET __HAL_RCC_USART3_FORCE_RESET #define __USART3_RELEASE_RESET __HAL_RCC_USART3_RELEASE_RESET #define __USART4_CLK_DISABLE __HAL_RCC_USART4_CLK_DISABLE #define __USART4_CLK_ENABLE __HAL_RCC_USART4_CLK_ENABLE #define __USART4_CLK_SLEEP_ENABLE __HAL_RCC_USART4_CLK_SLEEP_ENABLE #define __USART4_CLK_SLEEP_DISABLE __HAL_RCC_USART4_CLK_SLEEP_DISABLE #define __USART4_FORCE_RESET __HAL_RCC_USART4_FORCE_RESET #define __USART4_RELEASE_RESET __HAL_RCC_USART4_RELEASE_RESET #define __USART5_CLK_DISABLE __HAL_RCC_USART5_CLK_DISABLE #define __USART5_CLK_ENABLE __HAL_RCC_USART5_CLK_ENABLE #define __USART5_CLK_SLEEP_ENABLE __HAL_RCC_USART5_CLK_SLEEP_ENABLE #define __USART5_CLK_SLEEP_DISABLE __HAL_RCC_USART5_CLK_SLEEP_DISABLE #define __USART5_FORCE_RESET __HAL_RCC_USART5_FORCE_RESET #define __USART5_RELEASE_RESET __HAL_RCC_USART5_RELEASE_RESET #define __USART7_CLK_DISABLE __HAL_RCC_USART7_CLK_DISABLE #define __USART7_CLK_ENABLE __HAL_RCC_USART7_CLK_ENABLE #define __USART7_FORCE_RESET __HAL_RCC_USART7_FORCE_RESET #define __USART7_RELEASE_RESET __HAL_RCC_USART7_RELEASE_RESET #define __USART8_CLK_DISABLE __HAL_RCC_USART8_CLK_DISABLE #define __USART8_CLK_ENABLE __HAL_RCC_USART8_CLK_ENABLE #define __USART8_FORCE_RESET __HAL_RCC_USART8_FORCE_RESET #define __USART8_RELEASE_RESET __HAL_RCC_USART8_RELEASE_RESET #define __USB_CLK_DISABLE __HAL_RCC_USB_CLK_DISABLE #define __USB_CLK_ENABLE __HAL_RCC_USB_CLK_ENABLE #define __USB_FORCE_RESET __HAL_RCC_USB_FORCE_RESET #define __USB_CLK_SLEEP_ENABLE __HAL_RCC_USB_CLK_SLEEP_ENABLE #define __USB_CLK_SLEEP_DISABLE __HAL_RCC_USB_CLK_SLEEP_DISABLE #define __USB_OTG_FS_CLK_DISABLE __HAL_RCC_USB_OTG_FS_CLK_DISABLE #define __USB_OTG_FS_CLK_ENABLE __HAL_RCC_USB_OTG_FS_CLK_ENABLE #define __USB_RELEASE_RESET __HAL_RCC_USB_RELEASE_RESET #define __WWDG_CLK_DISABLE __HAL_RCC_WWDG_CLK_DISABLE #define __WWDG_CLK_ENABLE __HAL_RCC_WWDG_CLK_ENABLE #define __WWDG_CLK_SLEEP_DISABLE __HAL_RCC_WWDG_CLK_SLEEP_DISABLE #define __WWDG_CLK_SLEEP_ENABLE __HAL_RCC_WWDG_CLK_SLEEP_ENABLE #define __WWDG_FORCE_RESET __HAL_RCC_WWDG_FORCE_RESET #define __WWDG_RELEASE_RESET __HAL_RCC_WWDG_RELEASE_RESET #define __TIM21_CLK_ENABLE __HAL_RCC_TIM21_CLK_ENABLE #define __TIM21_CLK_DISABLE __HAL_RCC_TIM21_CLK_DISABLE #define __TIM21_FORCE_RESET __HAL_RCC_TIM21_FORCE_RESET #define __TIM21_RELEASE_RESET __HAL_RCC_TIM21_RELEASE_RESET #define __TIM21_CLK_SLEEP_ENABLE __HAL_RCC_TIM21_CLK_SLEEP_ENABLE #define __TIM21_CLK_SLEEP_DISABLE __HAL_RCC_TIM21_CLK_SLEEP_DISABLE #define __TIM22_CLK_ENABLE __HAL_RCC_TIM22_CLK_ENABLE #define __TIM22_CLK_DISABLE __HAL_RCC_TIM22_CLK_DISABLE #define __TIM22_FORCE_RESET __HAL_RCC_TIM22_FORCE_RESET #define __TIM22_RELEASE_RESET __HAL_RCC_TIM22_RELEASE_RESET #define __TIM22_CLK_SLEEP_ENABLE __HAL_RCC_TIM22_CLK_SLEEP_ENABLE #define __TIM22_CLK_SLEEP_DISABLE __HAL_RCC_TIM22_CLK_SLEEP_DISABLE #define __CRS_CLK_DISABLE __HAL_RCC_CRS_CLK_DISABLE #define __CRS_CLK_ENABLE __HAL_RCC_CRS_CLK_ENABLE #define __CRS_CLK_SLEEP_DISABLE __HAL_RCC_CRS_CLK_SLEEP_DISABLE #define __CRS_CLK_SLEEP_ENABLE __HAL_RCC_CRS_CLK_SLEEP_ENABLE #define __CRS_FORCE_RESET __HAL_RCC_CRS_FORCE_RESET #define __CRS_RELEASE_RESET __HAL_RCC_CRS_RELEASE_RESET #define __RCC_BACKUPRESET_FORCE __HAL_RCC_BACKUPRESET_FORCE #define __RCC_BACKUPRESET_RELEASE __HAL_RCC_BACKUPRESET_RELEASE #define __USB_OTG_FS_FORCE_RESET __HAL_RCC_USB_OTG_FS_FORCE_RESET #define __USB_OTG_FS_RELEASE_RESET __HAL_RCC_USB_OTG_FS_RELEASE_RESET #define __USB_OTG_FS_CLK_SLEEP_ENABLE __HAL_RCC_USB_OTG_FS_CLK_SLEEP_ENABLE #define __USB_OTG_FS_CLK_SLEEP_DISABLE __HAL_RCC_USB_OTG_FS_CLK_SLEEP_DISABLE #define __USB_OTG_HS_CLK_DISABLE __HAL_RCC_USB_OTG_HS_CLK_DISABLE #define __USB_OTG_HS_CLK_ENABLE __HAL_RCC_USB_OTG_HS_CLK_ENABLE #define __USB_OTG_HS_ULPI_CLK_ENABLE __HAL_RCC_USB_OTG_HS_ULPI_CLK_ENABLE #define __USB_OTG_HS_ULPI_CLK_DISABLE __HAL_RCC_USB_OTG_HS_ULPI_CLK_DISABLE #define __TIM9_CLK_SLEEP_ENABLE __HAL_RCC_TIM9_CLK_SLEEP_ENABLE #define __TIM9_CLK_SLEEP_DISABLE __HAL_RCC_TIM9_CLK_SLEEP_DISABLE #define __TIM10_CLK_SLEEP_ENABLE __HAL_RCC_TIM10_CLK_SLEEP_ENABLE #define __TIM10_CLK_SLEEP_DISABLE __HAL_RCC_TIM10_CLK_SLEEP_DISABLE #define __TIM11_CLK_SLEEP_ENABLE __HAL_RCC_TIM11_CLK_SLEEP_ENABLE #define __TIM11_CLK_SLEEP_DISABLE __HAL_RCC_TIM11_CLK_SLEEP_DISABLE #define __ETHMACPTP_CLK_SLEEP_ENABLE __HAL_RCC_ETHMACPTP_CLK_SLEEP_ENABLE #define __ETHMACPTP_CLK_SLEEP_DISABLE __HAL_RCC_ETHMACPTP_CLK_SLEEP_DISABLE #define __ETHMACPTP_CLK_ENABLE __HAL_RCC_ETHMACPTP_CLK_ENABLE #define __ETHMACPTP_CLK_DISABLE __HAL_RCC_ETHMACPTP_CLK_DISABLE #define __HASH_CLK_ENABLE __HAL_RCC_HASH_CLK_ENABLE #define __HASH_FORCE_RESET __HAL_RCC_HASH_FORCE_RESET #define __HASH_RELEASE_RESET __HAL_RCC_HASH_RELEASE_RESET #define __HASH_CLK_SLEEP_ENABLE __HAL_RCC_HASH_CLK_SLEEP_ENABLE #define __HASH_CLK_SLEEP_DISABLE __HAL_RCC_HASH_CLK_SLEEP_DISABLE #define __HASH_CLK_DISABLE __HAL_RCC_HASH_CLK_DISABLE #define __SPI5_CLK_ENABLE __HAL_RCC_SPI5_CLK_ENABLE #define __SPI5_CLK_DISABLE __HAL_RCC_SPI5_CLK_DISABLE #define __SPI5_FORCE_RESET __HAL_RCC_SPI5_FORCE_RESET #define __SPI5_RELEASE_RESET __HAL_RCC_SPI5_RELEASE_RESET #define __SPI5_CLK_SLEEP_ENABLE __HAL_RCC_SPI5_CLK_SLEEP_ENABLE #define __SPI5_CLK_SLEEP_DISABLE __HAL_RCC_SPI5_CLK_SLEEP_DISABLE #define __SPI6_CLK_ENABLE __HAL_RCC_SPI6_CLK_ENABLE #define __SPI6_CLK_DISABLE __HAL_RCC_SPI6_CLK_DISABLE #define __SPI6_FORCE_RESET __HAL_RCC_SPI6_FORCE_RESET #define __SPI6_RELEASE_RESET __HAL_RCC_SPI6_RELEASE_RESET #define __SPI6_CLK_SLEEP_ENABLE __HAL_RCC_SPI6_CLK_SLEEP_ENABLE #define __SPI6_CLK_SLEEP_DISABLE __HAL_RCC_SPI6_CLK_SLEEP_DISABLE #define __LTDC_CLK_ENABLE __HAL_RCC_LTDC_CLK_ENABLE #define __LTDC_CLK_DISABLE __HAL_RCC_LTDC_CLK_DISABLE #define __LTDC_FORCE_RESET __HAL_RCC_LTDC_FORCE_RESET #define __LTDC_RELEASE_RESET __HAL_RCC_LTDC_RELEASE_RESET #define __LTDC_CLK_SLEEP_ENABLE __HAL_RCC_LTDC_CLK_SLEEP_ENABLE #define __ETHMAC_CLK_SLEEP_ENABLE __HAL_RCC_ETHMAC_CLK_SLEEP_ENABLE #define __ETHMAC_CLK_SLEEP_DISABLE __HAL_RCC_ETHMAC_CLK_SLEEP_DISABLE #define __ETHMACTX_CLK_SLEEP_ENABLE __HAL_RCC_ETHMACTX_CLK_SLEEP_ENABLE #define __ETHMACTX_CLK_SLEEP_DISABLE __HAL_RCC_ETHMACTX_CLK_SLEEP_DISABLE #define __ETHMACRX_CLK_SLEEP_ENABLE __HAL_RCC_ETHMACRX_CLK_SLEEP_ENABLE #define __ETHMACRX_CLK_SLEEP_DISABLE __HAL_RCC_ETHMACRX_CLK_SLEEP_DISABLE #define __TIM12_CLK_SLEEP_ENABLE __HAL_RCC_TIM12_CLK_SLEEP_ENABLE #define __TIM12_CLK_SLEEP_DISABLE __HAL_RCC_TIM12_CLK_SLEEP_DISABLE #define __TIM13_CLK_SLEEP_ENABLE __HAL_RCC_TIM13_CLK_SLEEP_ENABLE #define __TIM13_CLK_SLEEP_DISABLE __HAL_RCC_TIM13_CLK_SLEEP_DISABLE #define __TIM14_CLK_SLEEP_ENABLE __HAL_RCC_TIM14_CLK_SLEEP_ENABLE #define __TIM14_CLK_SLEEP_DISABLE __HAL_RCC_TIM14_CLK_SLEEP_DISABLE #define __BKPSRAM_CLK_ENABLE __HAL_RCC_BKPSRAM_CLK_ENABLE #define __BKPSRAM_CLK_DISABLE __HAL_RCC_BKPSRAM_CLK_DISABLE #define __BKPSRAM_CLK_SLEEP_ENABLE __HAL_RCC_BKPSRAM_CLK_SLEEP_ENABLE #define __BKPSRAM_CLK_SLEEP_DISABLE __HAL_RCC_BKPSRAM_CLK_SLEEP_DISABLE #define __CCMDATARAMEN_CLK_ENABLE __HAL_RCC_CCMDATARAMEN_CLK_ENABLE #define __CCMDATARAMEN_CLK_DISABLE __HAL_RCC_CCMDATARAMEN_CLK_DISABLE #define __USART6_CLK_ENABLE __HAL_RCC_USART6_CLK_ENABLE #define __USART6_CLK_DISABLE __HAL_RCC_USART6_CLK_DISABLE #define __USART6_FORCE_RESET __HAL_RCC_USART6_FORCE_RESET #define __USART6_RELEASE_RESET __HAL_RCC_USART6_RELEASE_RESET #define __USART6_CLK_SLEEP_ENABLE __HAL_RCC_USART6_CLK_SLEEP_ENABLE #define __USART6_CLK_SLEEP_DISABLE __HAL_RCC_USART6_CLK_SLEEP_DISABLE #define __SPI4_CLK_ENABLE __HAL_RCC_SPI4_CLK_ENABLE #define __SPI4_CLK_DISABLE __HAL_RCC_SPI4_CLK_DISABLE #define __SPI4_FORCE_RESET __HAL_RCC_SPI4_FORCE_RESET #define __SPI4_RELEASE_RESET __HAL_RCC_SPI4_RELEASE_RESET #define __SPI4_CLK_SLEEP_ENABLE __HAL_RCC_SPI4_CLK_SLEEP_ENABLE #define __SPI4_CLK_SLEEP_DISABLE __HAL_RCC_SPI4_CLK_SLEEP_DISABLE #define __GPIOI_CLK_ENABLE __HAL_RCC_GPIOI_CLK_ENABLE #define __GPIOI_CLK_DISABLE __HAL_RCC_GPIOI_CLK_DISABLE #define __GPIOI_FORCE_RESET __HAL_RCC_GPIOI_FORCE_RESET #define __GPIOI_RELEASE_RESET __HAL_RCC_GPIOI_RELEASE_RESET #define __GPIOI_CLK_SLEEP_ENABLE __HAL_RCC_GPIOI_CLK_SLEEP_ENABLE #define __GPIOI_CLK_SLEEP_DISABLE __HAL_RCC_GPIOI_CLK_SLEEP_DISABLE #define __GPIOJ_CLK_ENABLE __HAL_RCC_GPIOJ_CLK_ENABLE #define __GPIOJ_CLK_DISABLE __HAL_RCC_GPIOJ_CLK_DISABLE #define __GPIOJ_FORCE_RESET __HAL_RCC_GPIOJ_FORCE_RESET #define __GPIOJ_RELEASE_RESET __HAL_RCC_GPIOJ_RELEASE_RESET #define __GPIOJ_CLK_SLEEP_ENABLE __HAL_RCC_GPIOJ_CLK_SLEEP_ENABLE #define __GPIOJ_CLK_SLEEP_DISABLE __HAL_RCC_GPIOJ_CLK_SLEEP_DISABLE #define __GPIOK_CLK_ENABLE __HAL_RCC_GPIOK_CLK_ENABLE #define __GPIOK_CLK_DISABLE __HAL_RCC_GPIOK_CLK_DISABLE #define __GPIOK_RELEASE_RESET __HAL_RCC_GPIOK_RELEASE_RESET #define __GPIOK_CLK_SLEEP_ENABLE __HAL_RCC_GPIOK_CLK_SLEEP_ENABLE #define __GPIOK_CLK_SLEEP_DISABLE __HAL_RCC_GPIOK_CLK_SLEEP_DISABLE #define __ETH_CLK_ENABLE __HAL_RCC_ETH_CLK_ENABLE #define __ETH_CLK_DISABLE __HAL_RCC_ETH_CLK_DISABLE #define __DCMI_CLK_ENABLE __HAL_RCC_DCMI_CLK_ENABLE #define __DCMI_CLK_DISABLE __HAL_RCC_DCMI_CLK_DISABLE #define __DCMI_FORCE_RESET __HAL_RCC_DCMI_FORCE_RESET #define __DCMI_RELEASE_RESET __HAL_RCC_DCMI_RELEASE_RESET #define __DCMI_CLK_SLEEP_ENABLE __HAL_RCC_DCMI_CLK_SLEEP_ENABLE #define __DCMI_CLK_SLEEP_DISABLE __HAL_RCC_DCMI_CLK_SLEEP_DISABLE #define __UART7_CLK_ENABLE __HAL_RCC_UART7_CLK_ENABLE #define __UART7_CLK_DISABLE __HAL_RCC_UART7_CLK_DISABLE #define __UART7_RELEASE_RESET __HAL_RCC_UART7_RELEASE_RESET #define __UART7_FORCE_RESET __HAL_RCC_UART7_FORCE_RESET #define __UART7_CLK_SLEEP_ENABLE __HAL_RCC_UART7_CLK_SLEEP_ENABLE #define __UART7_CLK_SLEEP_DISABLE __HAL_RCC_UART7_CLK_SLEEP_DISABLE #define __UART8_CLK_ENABLE __HAL_RCC_UART8_CLK_ENABLE #define __UART8_CLK_DISABLE __HAL_RCC_UART8_CLK_DISABLE #define __UART8_FORCE_RESET __HAL_RCC_UART8_FORCE_RESET #define __UART8_RELEASE_RESET __HAL_RCC_UART8_RELEASE_RESET #define __UART8_CLK_SLEEP_ENABLE __HAL_RCC_UART8_CLK_SLEEP_ENABLE #define __UART8_CLK_SLEEP_DISABLE __HAL_RCC_UART8_CLK_SLEEP_DISABLE #define __OTGHS_CLK_SLEEP_ENABLE __HAL_RCC_USB_OTG_HS_CLK_SLEEP_ENABLE #define __OTGHS_CLK_SLEEP_DISABLE __HAL_RCC_USB_OTG_HS_CLK_SLEEP_DISABLE #define __OTGHS_FORCE_RESET __HAL_RCC_USB_OTG_HS_FORCE_RESET #define __OTGHS_RELEASE_RESET __HAL_RCC_USB_OTG_HS_RELEASE_RESET #define __OTGHSULPI_CLK_SLEEP_ENABLE __HAL_RCC_USB_OTG_HS_ULPI_CLK_SLEEP_ENABLE #define __OTGHSULPI_CLK_SLEEP_DISABLE __HAL_RCC_USB_OTG_HS_ULPI_CLK_SLEEP_DISABLE #define __HAL_RCC_OTGHS_CLK_SLEEP_ENABLE __HAL_RCC_USB_OTG_HS_CLK_SLEEP_ENABLE #define __HAL_RCC_OTGHS_CLK_SLEEP_DISABLE __HAL_RCC_USB_OTG_HS_CLK_SLEEP_DISABLE #define __HAL_RCC_OTGHS_IS_CLK_SLEEP_ENABLED __HAL_RCC_USB_OTG_HS_IS_CLK_SLEEP_ENABLED #define __HAL_RCC_OTGHS_IS_CLK_SLEEP_DISABLED __HAL_RCC_USB_OTG_HS_IS_CLK_SLEEP_DISABLED #define __HAL_RCC_OTGHS_FORCE_RESET __HAL_RCC_USB_OTG_HS_FORCE_RESET #define __HAL_RCC_OTGHS_RELEASE_RESET __HAL_RCC_USB_OTG_HS_RELEASE_RESET #define __HAL_RCC_OTGHSULPI_CLK_SLEEP_ENABLE __HAL_RCC_USB_OTG_HS_ULPI_CLK_SLEEP_ENABLE #define __HAL_RCC_OTGHSULPI_CLK_SLEEP_DISABLE __HAL_RCC_USB_OTG_HS_ULPI_CLK_SLEEP_DISABLE #define __HAL_RCC_OTGHSULPI_IS_CLK_SLEEP_ENABLED __HAL_RCC_USB_OTG_HS_ULPI_IS_CLK_SLEEP_ENABLED #define __HAL_RCC_OTGHSULPI_IS_CLK_SLEEP_DISABLED __HAL_RCC_USB_OTG_HS_ULPI_IS_CLK_SLEEP_DISABLED #define __CRYP_FORCE_RESET __HAL_RCC_CRYP_FORCE_RESET #define __SRAM3_CLK_SLEEP_ENABLE __HAL_RCC_SRAM3_CLK_SLEEP_ENABLE #define __CAN2_CLK_SLEEP_ENABLE __HAL_RCC_CAN2_CLK_SLEEP_ENABLE #define __CAN2_CLK_SLEEP_DISABLE __HAL_RCC_CAN2_CLK_SLEEP_DISABLE #define __DAC_CLK_SLEEP_ENABLE __HAL_RCC_DAC_CLK_SLEEP_ENABLE #define __DAC_CLK_SLEEP_DISABLE __HAL_RCC_DAC_CLK_SLEEP_DISABLE #define __ADC2_CLK_SLEEP_ENABLE __HAL_RCC_ADC2_CLK_SLEEP_ENABLE #define __ADC2_CLK_SLEEP_DISABLE __HAL_RCC_ADC2_CLK_SLEEP_DISABLE #define __ADC3_CLK_SLEEP_ENABLE __HAL_RCC_ADC3_CLK_SLEEP_ENABLE #define __ADC3_CLK_SLEEP_DISABLE __HAL_RCC_ADC3_CLK_SLEEP_DISABLE #define __FSMC_FORCE_RESET __HAL_RCC_FSMC_FORCE_RESET #define __FSMC_RELEASE_RESET __HAL_RCC_FSMC_RELEASE_RESET #define __FSMC_CLK_SLEEP_ENABLE __HAL_RCC_FSMC_CLK_SLEEP_ENABLE #define __FSMC_CLK_SLEEP_DISABLE __HAL_RCC_FSMC_CLK_SLEEP_DISABLE #define __SDIO_FORCE_RESET __HAL_RCC_SDIO_FORCE_RESET #define __SDIO_RELEASE_RESET __HAL_RCC_SDIO_RELEASE_RESET #define __SDIO_CLK_SLEEP_DISABLE __HAL_RCC_SDIO_CLK_SLEEP_DISABLE #define __SDIO_CLK_SLEEP_ENABLE __HAL_RCC_SDIO_CLK_SLEEP_ENABLE #define __DMA2D_CLK_ENABLE __HAL_RCC_DMA2D_CLK_ENABLE #define __DMA2D_CLK_DISABLE __HAL_RCC_DMA2D_CLK_DISABLE #define __DMA2D_FORCE_RESET __HAL_RCC_DMA2D_FORCE_RESET #define __DMA2D_RELEASE_RESET __HAL_RCC_DMA2D_RELEASE_RESET #define __DMA2D_CLK_SLEEP_ENABLE __HAL_RCC_DMA2D_CLK_SLEEP_ENABLE #define __DMA2D_CLK_SLEEP_DISABLE __HAL_RCC_DMA2D_CLK_SLEEP_DISABLE /* alias define maintained for legacy */ #define __HAL_RCC_OTGFS_FORCE_RESET __HAL_RCC_USB_OTG_FS_FORCE_RESET #define __HAL_RCC_OTGFS_RELEASE_RESET __HAL_RCC_USB_OTG_FS_RELEASE_RESET #if defined(STM32F4) #define __HAL_RCC_SDMMC1_CLK_ENABLE __HAL_RCC_SDIO_CLK_ENABLE #define __HAL_RCC_SDMMC1_FORCE_RESET __HAL_RCC_SDIO_FORCE_RESET #define __HAL_RCC_SDMMC1_RELEASE_RESET __HAL_RCC_SDIO_RELEASE_RESET #define __HAL_RCC_SDMMC1_CLK_SLEEP_ENABLE __HAL_RCC_SDIO_CLK_SLEEP_ENABLE #define __HAL_RCC_SDMMC1_CLK_SLEEP_DISABLE __HAL_RCC_SDIO_CLK_SLEEP_DISABLE #define __HAL_RCC_SDMMC1_CLK_ENABLE __HAL_RCC_SDIO_CLK_ENABLE #define __HAL_RCC_SDMMC1_CLK_DISABLE __HAL_RCC_SDIO_CLK_DISABLE #define Sdmmc1ClockSelection SdioClockSelection #define RCC_PERIPHCLK_SDMMC1 RCC_PERIPHCLK_SDIO #define RCC_SDMMC1CLKSOURCE_CLK48 RCC_SDIOCLKSOURCE_CK48 #define RCC_SDMMC1CLKSOURCE_SYSCLK RCC_SDIOCLKSOURCE_SYSCLK #define __HAL_RCC_SDMMC1_CONFIG __HAL_RCC_SDIO_CONFIG #define __HAL_RCC_GET_SDMMC1_SOURCE __HAL_RCC_GET_SDIO_SOURCE #endif #if defined(STM32F7) || defined(STM32L4) #define __HAL_RCC_SDIO_CLK_ENABLE __HAL_RCC_SDMMC1_CLK_ENABLE #define __HAL_RCC_SDIO_FORCE_RESET __HAL_RCC_SDMMC1_FORCE_RESET #define __HAL_RCC_SDIO_RELEASE_RESET __HAL_RCC_SDMMC1_RELEASE_RESET #define __HAL_RCC_SDIO_CLK_SLEEP_ENABLE __HAL_RCC_SDMMC1_CLK_SLEEP_ENABLE #define __HAL_RCC_SDIO_CLK_SLEEP_DISABLE __HAL_RCC_SDMMC1_CLK_SLEEP_DISABLE #define __HAL_RCC_SDIO_CLK_ENABLE __HAL_RCC_SDMMC1_CLK_ENABLE #define __HAL_RCC_SDIO_CLK_DISABLE __HAL_RCC_SDMMC1_CLK_DISABLE #define SdioClockSelection Sdmmc1ClockSelection #define RCC_PERIPHCLK_SDIO RCC_PERIPHCLK_SDMMC1 #define __HAL_RCC_SDIO_CONFIG __HAL_RCC_SDMMC1_CONFIG #define __HAL_RCC_GET_SDIO_SOURCE __HAL_RCC_GET_SDMMC1_SOURCE #endif #if defined(STM32F7) #define RCC_SDIOCLKSOURCE_CK48 RCC_SDMMC1CLKSOURCE_CLK48 #define RCC_SDIOCLKSOURCE_SYSCLK RCC_SDMMC1CLKSOURCE_SYSCLK #endif #define __HAL_RCC_I2SCLK __HAL_RCC_I2S_CONFIG #define __HAL_RCC_I2SCLK_CONFIG __HAL_RCC_I2S_CONFIG #define __RCC_PLLSRC RCC_GET_PLL_OSCSOURCE #define IS_RCC_MSIRANGE IS_RCC_MSI_CLOCK_RANGE #define IS_RCC_RTCCLK_SOURCE IS_RCC_RTCCLKSOURCE #define IS_RCC_SYSCLK_DIV IS_RCC_HCLK #define IS_RCC_HCLK_DIV IS_RCC_PCLK #define IS_RCC_MCOSOURCE IS_RCC_MCO1SOURCE #define RCC_MCO_NODIV RCC_MCODIV_1 #define RCC_RTCCLKSOURCE_NONE RCC_RTCCLKSOURCE_NO_CLK #define HSION_BitNumber RCC_HSION_BIT_NUMBER #define CSSON_BitNumber RCC_CSSON_BIT_NUMBER #define PLLON_BitNumber RCC_PLLON_BIT_NUMBER #define PLLI2SON_BitNumber RCC_PLLI2SON_BIT_NUMBER #define I2SSRC_BitNumber RCC_I2SSRC_BIT_NUMBER #define RTCEN_BitNumber RCC_RTCEN_BIT_NUMBER #define BDRST_BitNumber RCC_BDRST_BIT_NUMBER #define LSION_BitNumber RCC_LSION_BIT_NUMBER #define PLLSAION_BitNumber RCC_PLLSAION_BIT_NUMBER #define TIMPRE_BitNumber RCC_TIMPRE_BIT_NUMBER #define CR_BYTE2_ADDRESS RCC_CR_BYTE2_ADDRESS #define CIR_BYTE1_ADDRESS RCC_CIR_BYTE1_ADDRESS #define CIR_BYTE2_ADDRESS RCC_CIR_BYTE2_ADDRESS #define BDCR_BYTE0_ADDRESS RCC_BDCR_BYTE0_ADDRESS #define DBP_TIMEOUT_VALUE RCC_DBP_TIMEOUT_VALUE #define LSE_TIMEOUT_VALUE RCC_LSE_TIMEOUT_VALUE #define CR_HSION_BB RCC_CR_HSION_BB #define CR_CSSON_BB RCC_CR_CSSON_BB #define CR_PLLON_BB RCC_CR_PLLON_BB #define CR_PLLI2SON_BB RCC_CR_PLLI2SON_BB #define CR_MSION_BB RCC_CR_MSION_BB #define CSR_LSION_BB RCC_CSR_LSION_BB #define CSR_LSEON_BB RCC_CSR_LSEON_BB #define CSR_LSEBYP_BB RCC_CSR_LSEBYP_BB #define CSR_RTCEN_BB RCC_CSR_RTCEN_BB #define CSR_RTCRST_BB RCC_CSR_RTCRST_BB #define CFGR_I2SSRC_BB RCC_CFGR_I2SSRC_BB #define BDCR_RTCEN_BB RCC_BDCR_RTCEN_BB #define BDCR_BDRST_BB RCC_BDCR_BDRST_BB #define CR_PLLSAION_BB RCC_CR_PLLSAION_BB #define DCKCFGR_TIMPRE_BB RCC_DCKCFGR_TIMPRE_BB /** * @} */ /** @defgroup HAL_RNG_Aliased_Macros HAL RNG Aliased Macros maintained for legacy purpose * @{ */ #define HAL_RNG_ReadyCallback(__HANDLE__) HAL_RNG_ReadyDataCallback((__HANDLE__), uint32_t random32bit) /** * @} */ /** @defgroup HAL_RTC_Aliased_Macros HAL RTC Aliased Macros maintained for legacy purpose * @{ */ #define __HAL_RTC_CLEAR_FLAG __HAL_RTC_EXTI_CLEAR_FLAG #define __HAL_RTC_DISABLE_IT __HAL_RTC_EXTI_DISABLE_IT #define __HAL_RTC_ENABLE_IT __HAL_RTC_EXTI_ENABLE_IT #if defined (STM32F1) #define __HAL_RTC_EXTI_CLEAR_FLAG(RTC_EXTI_LINE_ALARM_EVENT) __HAL_RTC_ALARM_EXTI_CLEAR_FLAG() #define __HAL_RTC_EXTI_ENABLE_IT(RTC_EXTI_LINE_ALARM_EVENT) __HAL_RTC_ALARM_EXTI_ENABLE_IT() #define __HAL_RTC_EXTI_DISABLE_IT(RTC_EXTI_LINE_ALARM_EVENT) __HAL_RTC_ALARM_EXTI_DISABLE_IT() #define __HAL_RTC_EXTI_GET_FLAG(RTC_EXTI_LINE_ALARM_EVENT) __HAL_RTC_ALARM_EXTI_GET_FLAG() #define __HAL_RTC_EXTI_GENERATE_SWIT(RTC_EXTI_LINE_ALARM_EVENT) __HAL_RTC_ALARM_EXTI_GENERATE_SWIT() #else #define __HAL_RTC_EXTI_CLEAR_FLAG(__EXTI_LINE__) (((__EXTI_LINE__) == RTC_EXTI_LINE_ALARM_EVENT) ? __HAL_RTC_ALARM_EXTI_CLEAR_FLAG() : \ (((__EXTI_LINE__) == RTC_EXTI_LINE_WAKEUPTIMER_EVENT) ? __HAL_RTC_WAKEUPTIMER_EXTI_CLEAR_FLAG() : \ __HAL_RTC_TAMPER_TIMESTAMP_EXTI_CLEAR_FLAG())) #define __HAL_RTC_EXTI_ENABLE_IT(__EXTI_LINE__) (((__EXTI_LINE__) == RTC_EXTI_LINE_ALARM_EVENT) ? __HAL_RTC_ALARM_EXTI_ENABLE_IT() : \ (((__EXTI_LINE__) == RTC_EXTI_LINE_WAKEUPTIMER_EVENT) ? __HAL_RTC_WAKEUPTIMER_EXTI_ENABLE_IT() : \ __HAL_RTC_TAMPER_TIMESTAMP_EXTI_ENABLE_IT())) #define __HAL_RTC_EXTI_DISABLE_IT(__EXTI_LINE__) (((__EXTI_LINE__) == RTC_EXTI_LINE_ALARM_EVENT) ? __HAL_RTC_ALARM_EXTI_DISABLE_IT() : \ (((__EXTI_LINE__) == RTC_EXTI_LINE_WAKEUPTIMER_EVENT) ? __HAL_RTC_WAKEUPTIMER_EXTI_DISABLE_IT() : \ __HAL_RTC_TAMPER_TIMESTAMP_EXTI_DISABLE_IT())) #define __HAL_RTC_EXTI_GET_FLAG(__EXTI_LINE__) (((__EXTI_LINE__) == RTC_EXTI_LINE_ALARM_EVENT) ? __HAL_RTC_ALARM_EXTI_GET_FLAG() : \ (((__EXTI_LINE__) == RTC_EXTI_LINE_WAKEUPTIMER_EVENT) ? __HAL_RTC_WAKEUPTIMER_EXTI_GET_FLAG() : \ __HAL_RTC_TAMPER_TIMESTAMP_EXTI_GET_FLAG())) #define __HAL_RTC_EXTI_GENERATE_SWIT(__EXTI_LINE__) (((__EXTI_LINE__) == RTC_EXTI_LINE_ALARM_EVENT) ? __HAL_RTC_ALARM_EXTI_GENERATE_SWIT() : \ (((__EXTI_LINE__) == RTC_EXTI_LINE_WAKEUPTIMER_EVENT) ? __HAL_RTC_WAKEUPTIMER_EXTI_GENERATE_SWIT() : \ __HAL_RTC_TAMPER_TIMESTAMP_EXTI_GENERATE_SWIT())) #endif /* STM32F1 */ #define IS_ALARM IS_RTC_ALARM #define IS_ALARM_MASK IS_RTC_ALARM_MASK #define IS_TAMPER IS_RTC_TAMPER #define IS_TAMPER_ERASE_MODE IS_RTC_TAMPER_ERASE_MODE #define IS_TAMPER_FILTER IS_RTC_TAMPER_FILTER #define IS_TAMPER_INTERRUPT IS_RTC_TAMPER_INTERRUPT #define IS_TAMPER_MASKFLAG_STATE IS_RTC_TAMPER_MASKFLAG_STATE #define IS_TAMPER_PRECHARGE_DURATION IS_RTC_TAMPER_PRECHARGE_DURATION #define IS_TAMPER_PULLUP_STATE IS_RTC_TAMPER_PULLUP_STATE #define IS_TAMPER_SAMPLING_FREQ IS_RTC_TAMPER_SAMPLING_FREQ #define IS_TAMPER_TIMESTAMPONTAMPER_DETECTION IS_RTC_TAMPER_TIMESTAMPONTAMPER_DETECTION #define IS_TAMPER_TRIGGER IS_RTC_TAMPER_TRIGGER #define IS_WAKEUP_CLOCK IS_RTC_WAKEUP_CLOCK #define IS_WAKEUP_COUNTER IS_RTC_WAKEUP_COUNTER #define __RTC_WRITEPROTECTION_ENABLE __HAL_RTC_WRITEPROTECTION_ENABLE #define __RTC_WRITEPROTECTION_DISABLE __HAL_RTC_WRITEPROTECTION_DISABLE /** * @} */ /** @defgroup HAL_SD_Aliased_Macros HAL SD Aliased Macros maintained for legacy purpose * @{ */ #define SD_OCR_CID_CSD_OVERWRIETE SD_OCR_CID_CSD_OVERWRITE #define SD_CMD_SD_APP_STAUS SD_CMD_SD_APP_STATUS #if defined(STM32F4) #define SD_SDMMC_DISABLED SD_SDIO_DISABLED #define SD_SDMMC_FUNCTION_BUSY SD_SDIO_FUNCTION_BUSY #define SD_SDMMC_FUNCTION_FAILED SD_SDIO_FUNCTION_FAILED #define SD_SDMMC_UNKNOWN_FUNCTION SD_SDIO_UNKNOWN_FUNCTION #define SD_CMD_SDMMC_SEN_OP_COND SD_CMD_SDIO_SEN_OP_COND #define SD_CMD_SDMMC_RW_DIRECT SD_CMD_SDIO_RW_DIRECT #define SD_CMD_SDMMC_RW_EXTENDED SD_CMD_SDIO_RW_EXTENDED #define __HAL_SD_SDMMC_ENABLE __HAL_SD_SDIO_ENABLE #define __HAL_SD_SDMMC_DISABLE __HAL_SD_SDIO_DISABLE #define __HAL_SD_SDMMC_DMA_ENABLE __HAL_SD_SDIO_DMA_ENABLE #define __HAL_SD_SDMMC_DMA_DISABLE __HAL_SD_SDIO_DMA_DISABL #define __HAL_SD_SDMMC_ENABLE_IT __HAL_SD_SDIO_ENABLE_IT #define __HAL_SD_SDMMC_DISABLE_IT __HAL_SD_SDIO_DISABLE_IT #define __HAL_SD_SDMMC_GET_FLAG __HAL_SD_SDIO_GET_FLAG #define __HAL_SD_SDMMC_CLEAR_FLAG __HAL_SD_SDIO_CLEAR_FLAG #define __HAL_SD_SDMMC_GET_IT __HAL_SD_SDIO_GET_IT #define __HAL_SD_SDMMC_CLEAR_IT __HAL_SD_SDIO_CLEAR_IT #define SDMMC_STATIC_FLAGS SDIO_STATIC_FLAGS #define SDMMC_CMD0TIMEOUT SDIO_CMD0TIMEOUT #define SD_SDMMC_SEND_IF_COND SD_SDIO_SEND_IF_COND /* alias CMSIS */ #define SDMMC1_IRQn SDIO_IRQn #define SDMMC1_IRQHandler SDIO_IRQHandler #endif #if defined(STM32F7) || defined(STM32L4) #define SD_SDIO_DISABLED SD_SDMMC_DISABLED #define SD_SDIO_FUNCTION_BUSY SD_SDMMC_FUNCTION_BUSY #define SD_SDIO_FUNCTION_FAILED SD_SDMMC_FUNCTION_FAILED #define SD_SDIO_UNKNOWN_FUNCTION SD_SDMMC_UNKNOWN_FUNCTION #define SD_CMD_SDIO_SEN_OP_COND SD_CMD_SDMMC_SEN_OP_COND #define SD_CMD_SDIO_RW_DIRECT SD_CMD_SDMMC_RW_DIRECT #define SD_CMD_SDIO_RW_EXTENDED SD_CMD_SDMMC_RW_EXTENDED #define __HAL_SD_SDIO_ENABLE __HAL_SD_SDMMC_ENABLE #define __HAL_SD_SDIO_DISABLE __HAL_SD_SDMMC_DISABLE #define __HAL_SD_SDIO_DMA_ENABLE __HAL_SD_SDMMC_DMA_ENABLE #define __HAL_SD_SDIO_DMA_DISABL __HAL_SD_SDMMC_DMA_DISABLE #define __HAL_SD_SDIO_ENABLE_IT __HAL_SD_SDMMC_ENABLE_IT #define __HAL_SD_SDIO_DISABLE_IT __HAL_SD_SDMMC_DISABLE_IT #define __HAL_SD_SDIO_GET_FLAG __HAL_SD_SDMMC_GET_FLAG #define __HAL_SD_SDIO_CLEAR_FLAG __HAL_SD_SDMMC_CLEAR_FLAG #define __HAL_SD_SDIO_GET_IT __HAL_SD_SDMMC_GET_IT #define __HAL_SD_SDIO_CLEAR_IT __HAL_SD_SDMMC_CLEAR_IT #define SDIO_STATIC_FLAGS SDMMC_STATIC_FLAGS #define SDIO_CMD0TIMEOUT SDMMC_CMD0TIMEOUT #define SD_SDIO_SEND_IF_COND SD_SDMMC_SEND_IF_COND /* alias CMSIS for compatibilities */ #define SDIO_IRQn SDMMC1_IRQn #define SDIO_IRQHandler SDMMC1_IRQHandler #endif /** * @} */ /** @defgroup HAL_SMARTCARD_Aliased_Macros HAL SMARTCARD Aliased Macros maintained for legacy purpose * @{ */ #define __SMARTCARD_ENABLE_IT __HAL_SMARTCARD_ENABLE_IT #define __SMARTCARD_DISABLE_IT __HAL_SMARTCARD_DISABLE_IT #define __SMARTCARD_ENABLE __HAL_SMARTCARD_ENABLE #define __SMARTCARD_DISABLE __HAL_SMARTCARD_DISABLE #define __SMARTCARD_DMA_REQUEST_ENABLE __HAL_SMARTCARD_DMA_REQUEST_ENABLE #define __SMARTCARD_DMA_REQUEST_DISABLE __HAL_SMARTCARD_DMA_REQUEST_DISABLE #define __HAL_SMARTCARD_GETCLOCKSOURCE SMARTCARD_GETCLOCKSOURCE #define __SMARTCARD_GETCLOCKSOURCE SMARTCARD_GETCLOCKSOURCE #define IS_SMARTCARD_ONEBIT_SAMPLING IS_SMARTCARD_ONE_BIT_SAMPLE /** * @} */ /** @defgroup HAL_SMBUS_Aliased_Macros HAL SMBUS Aliased Macros maintained for legacy purpose * @{ */ #define __HAL_SMBUS_RESET_CR1 SMBUS_RESET_CR1 #define __HAL_SMBUS_RESET_CR2 SMBUS_RESET_CR2 #define __HAL_SMBUS_GENERATE_START SMBUS_GENERATE_START #define __HAL_SMBUS_GET_ADDR_MATCH SMBUS_GET_ADDR_MATCH #define __HAL_SMBUS_GET_DIR SMBUS_GET_DIR #define __HAL_SMBUS_GET_STOP_MODE SMBUS_GET_STOP_MODE #define __HAL_SMBUS_GET_PEC_MODE SMBUS_GET_PEC_MODE #define __HAL_SMBUS_GET_ALERT_ENABLED SMBUS_GET_ALERT_ENABLED /** * @} */ /** @defgroup HAL_SPI_Aliased_Macros HAL SPI Aliased Macros maintained for legacy purpose * @{ */ #define __HAL_SPI_1LINE_TX SPI_1LINE_TX #define __HAL_SPI_1LINE_RX SPI_1LINE_RX #define __HAL_SPI_RESET_CRC SPI_RESET_CRC /** * @} */ /** @defgroup HAL_UART_Aliased_Macros HAL UART Aliased Macros maintained for legacy purpose * @{ */ #define __HAL_UART_GETCLOCKSOURCE UART_GETCLOCKSOURCE #define __HAL_UART_MASK_COMPUTATION UART_MASK_COMPUTATION #define __UART_GETCLOCKSOURCE UART_GETCLOCKSOURCE #define __UART_MASK_COMPUTATION UART_MASK_COMPUTATION #define IS_UART_WAKEUPMETHODE IS_UART_WAKEUPMETHOD #define IS_UART_ONEBIT_SAMPLE IS_UART_ONE_BIT_SAMPLE #define IS_UART_ONEBIT_SAMPLING IS_UART_ONE_BIT_SAMPLE /** * @} */ /** @defgroup HAL_USART_Aliased_Macros HAL USART Aliased Macros maintained for legacy purpose * @{ */ #define __USART_ENABLE_IT __HAL_USART_ENABLE_IT #define __USART_DISABLE_IT __HAL_USART_DISABLE_IT #define __USART_ENABLE __HAL_USART_ENABLE #define __USART_DISABLE __HAL_USART_DISABLE #define __HAL_USART_GETCLOCKSOURCE USART_GETCLOCKSOURCE #define __USART_GETCLOCKSOURCE USART_GETCLOCKSOURCE /** * @} */ /** @defgroup HAL_USB_Aliased_Macros HAL USB Aliased Macros maintained for legacy purpose * @{ */ #define USB_EXTI_LINE_WAKEUP USB_WAKEUP_EXTI_LINE #define USB_FS_EXTI_TRIGGER_RISING_EDGE USB_OTG_FS_WAKEUP_EXTI_RISING_EDGE #define USB_FS_EXTI_TRIGGER_FALLING_EDGE USB_OTG_FS_WAKEUP_EXTI_FALLING_EDGE #define USB_FS_EXTI_TRIGGER_BOTH_EDGE USB_OTG_FS_WAKEUP_EXTI_RISING_FALLING_EDGE #define USB_FS_EXTI_LINE_WAKEUP USB_OTG_FS_WAKEUP_EXTI_LINE #define USB_HS_EXTI_TRIGGER_RISING_EDGE USB_OTG_HS_WAKEUP_EXTI_RISING_EDGE #define USB_HS_EXTI_TRIGGER_FALLING_EDGE USB_OTG_HS_WAKEUP_EXTI_FALLING_EDGE #define USB_HS_EXTI_TRIGGER_BOTH_EDGE USB_OTG_HS_WAKEUP_EXTI_RISING_FALLING_EDGE #define USB_HS_EXTI_LINE_WAKEUP USB_OTG_HS_WAKEUP_EXTI_LINE #define __HAL_USB_EXTI_ENABLE_IT __HAL_USB_WAKEUP_EXTI_ENABLE_IT #define __HAL_USB_EXTI_DISABLE_IT __HAL_USB_WAKEUP_EXTI_DISABLE_IT #define __HAL_USB_EXTI_GET_FLAG __HAL_USB_WAKEUP_EXTI_GET_FLAG #define __HAL_USB_EXTI_CLEAR_FLAG __HAL_USB_WAKEUP_EXTI_CLEAR_FLAG #define __HAL_USB_EXTI_SET_RISING_EDGE_TRIGGER __HAL_USB_WAKEUP_EXTI_ENABLE_RISING_EDGE #define __HAL_USB_EXTI_SET_FALLING_EDGE_TRIGGER __HAL_USB_WAKEUP_EXTI_ENABLE_FALLING_EDGE #define __HAL_USB_EXTI_SET_FALLINGRISING_TRIGGER __HAL_USB_WAKEUP_EXTI_ENABLE_RISING_FALLING_EDGE #define __HAL_USB_FS_EXTI_ENABLE_IT __HAL_USB_OTG_FS_WAKEUP_EXTI_ENABLE_IT #define __HAL_USB_FS_EXTI_DISABLE_IT __HAL_USB_OTG_FS_WAKEUP_EXTI_DISABLE_IT #define __HAL_USB_FS_EXTI_GET_FLAG __HAL_USB_OTG_FS_WAKEUP_EXTI_GET_FLAG #define __HAL_USB_FS_EXTI_CLEAR_FLAG __HAL_USB_OTG_FS_WAKEUP_EXTI_CLEAR_FLAG #define __HAL_USB_FS_EXTI_SET_RISING_EGDE_TRIGGER __HAL_USB_OTG_FS_WAKEUP_EXTI_ENABLE_RISING_EDGE #define __HAL_USB_FS_EXTI_SET_FALLING_EGDE_TRIGGER __HAL_USB_OTG_FS_WAKEUP_EXTI_ENABLE_FALLING_EDGE #define __HAL_USB_FS_EXTI_SET_FALLINGRISING_TRIGGER __HAL_USB_OTG_FS_WAKEUP_EXTI_ENABLE_RISING_FALLING_EDGE #define __HAL_USB_FS_EXTI_GENERATE_SWIT __HAL_USB_OTG_FS_WAKEUP_EXTI_GENERATE_SWIT #define __HAL_USB_HS_EXTI_ENABLE_IT __HAL_USB_OTG_HS_WAKEUP_EXTI_ENABLE_IT #define __HAL_USB_HS_EXTI_DISABLE_IT __HAL_USB_OTG_HS_WAKEUP_EXTI_DISABLE_IT #define __HAL_USB_HS_EXTI_GET_FLAG __HAL_USB_OTG_HS_WAKEUP_EXTI_GET_FLAG #define __HAL_USB_HS_EXTI_CLEAR_FLAG __HAL_USB_OTG_HS_WAKEUP_EXTI_CLEAR_FLAG #define __HAL_USB_HS_EXTI_SET_RISING_EGDE_TRIGGER __HAL_USB_OTG_HS_WAKEUP_EXTI_ENABLE_RISING_EDGE #define __HAL_USB_HS_EXTI_SET_FALLING_EGDE_TRIGGER __HAL_USB_OTG_HS_WAKEUP_EXTI_ENABLE_FALLING_EDGE #define __HAL_USB_HS_EXTI_SET_FALLINGRISING_TRIGGER __HAL_USB_OTG_HS_WAKEUP_EXTI_ENABLE_RISING_FALLING_EDGE #define __HAL_USB_HS_EXTI_GENERATE_SWIT __HAL_USB_OTG_HS_WAKEUP_EXTI_GENERATE_SWIT #define HAL_PCD_ActiveRemoteWakeup HAL_PCD_ActivateRemoteWakeup #define HAL_PCD_DeActiveRemoteWakeup HAL_PCD_DeActivateRemoteWakeup #define HAL_PCD_SetTxFiFo HAL_PCDEx_SetTxFiFo #define HAL_PCD_SetRxFiFo HAL_PCDEx_SetRxFiFo /** * @} */ /** @defgroup HAL_TIM_Aliased_Macros HAL TIM Aliased Macros maintained for legacy purpose * @{ */ #define __HAL_TIM_SetICPrescalerValue TIM_SET_ICPRESCALERVALUE #define __HAL_TIM_ResetICPrescalerValue TIM_RESET_ICPRESCALERVALUE #define TIM_GET_ITSTATUS __HAL_TIM_GET_IT_SOURCE #define TIM_GET_CLEAR_IT __HAL_TIM_CLEAR_IT #define __HAL_TIM_GET_ITSTATUS __HAL_TIM_GET_IT_SOURCE #define __HAL_TIM_DIRECTION_STATUS __HAL_TIM_IS_TIM_COUNTING_DOWN #define __HAL_TIM_PRESCALER __HAL_TIM_SET_PRESCALER #define __HAL_TIM_SetCounter __HAL_TIM_SET_COUNTER #define __HAL_TIM_GetCounter __HAL_TIM_GET_COUNTER #define __HAL_TIM_SetAutoreload __HAL_TIM_SET_AUTORELOAD #define __HAL_TIM_GetAutoreload __HAL_TIM_GET_AUTORELOAD #define __HAL_TIM_SetClockDivision __HAL_TIM_SET_CLOCKDIVISION #define __HAL_TIM_GetClockDivision __HAL_TIM_GET_CLOCKDIVISION #define __HAL_TIM_SetICPrescaler __HAL_TIM_SET_ICPRESCALER #define __HAL_TIM_GetICPrescaler __HAL_TIM_GET_ICPRESCALER #define __HAL_TIM_SetCompare __HAL_TIM_SET_COMPARE #define __HAL_TIM_GetCompare __HAL_TIM_GET_COMPARE #define TIM_TS_ITR0 ((uint32_t)0x0000) #define TIM_TS_ITR1 ((uint32_t)0x0010) #define TIM_TS_ITR2 ((uint32_t)0x0020) #define TIM_TS_ITR3 ((uint32_t)0x0030) #define IS_TIM_INTERNAL_TRIGGER_SELECTION(SELECTION) (((SELECTION) == TIM_TS_ITR0) || \ ((SELECTION) == TIM_TS_ITR1) || \ ((SELECTION) == TIM_TS_ITR2) || \ ((SELECTION) == TIM_TS_ITR3)) #define TIM_CHANNEL_1 ((uint32_t)0x0000) #define TIM_CHANNEL_2 ((uint32_t)0x0004) #define IS_TIM_PWMI_CHANNELS(CHANNEL) (((CHANNEL) == TIM_CHANNEL_1) || \ ((CHANNEL) == TIM_CHANNEL_2)) #define TIM_OUTPUTNSTATE_DISABLE ((uint32_t)0x0000) #define TIM_OUTPUTNSTATE_ENABLE (TIM_CCER_CC1NE) #define IS_TIM_OUTPUTN_STATE(STATE) (((STATE) == TIM_OUTPUTNSTATE_DISABLE) || \ ((STATE) == TIM_OUTPUTNSTATE_ENABLE)) #define TIM_OUTPUTSTATE_DISABLE ((uint32_t)0x0000) #define TIM_OUTPUTSTATE_ENABLE (TIM_CCER_CC1E) #define IS_TIM_OUTPUT_STATE(STATE) (((STATE) == TIM_OUTPUTSTATE_DISABLE) || \ ((STATE) == TIM_OUTPUTSTATE_ENABLE)) /** * @} */ /** @defgroup HAL_ETH_Aliased_Macros HAL ETH Aliased Macros maintained for legacy purpose * @{ */ #define __HAL_ETH_EXTI_ENABLE_IT __HAL_ETH_WAKEUP_EXTI_ENABLE_IT #define __HAL_ETH_EXTI_DISABLE_IT __HAL_ETH_WAKEUP_EXTI_DISABLE_IT #define __HAL_ETH_EXTI_GET_FLAG __HAL_ETH_WAKEUP_EXTI_GET_FLAG #define __HAL_ETH_EXTI_CLEAR_FLAG __HAL_ETH_WAKEUP_EXTI_CLEAR_FLAG #define __HAL_ETH_EXTI_SET_RISING_EGDE_TRIGGER __HAL_ETH_WAKEUP_EXTI_ENABLE_RISING_EDGE_TRIGGER #define __HAL_ETH_EXTI_SET_FALLING_EGDE_TRIGGER __HAL_ETH_WAKEUP_EXTI_ENABLE_FALLING_EDGE_TRIGGER #define __HAL_ETH_EXTI_SET_FALLINGRISING_TRIGGER __HAL_ETH_WAKEUP_EXTI_ENABLE_FALLINGRISING_TRIGGER #define ETH_PROMISCIOUSMODE_ENABLE ETH_PROMISCUOUS_MODE_ENABLE #define ETH_PROMISCIOUSMODE_DISABLE ETH_PROMISCUOUS_MODE_DISABLE #define IS_ETH_PROMISCIOUS_MODE IS_ETH_PROMISCUOUS_MODE /** * @} */ /** @defgroup HAL_LTDC_Aliased_Macros HAL LTDC Aliased Macros maintained for legacy purpose * @{ */ #define __HAL_LTDC_LAYER LTDC_LAYER /** * @} */ /** @defgroup HAL_SAI_Aliased_Macros HAL SAI Aliased Macros maintained for legacy purpose * @{ */ #define SAI_OUTPUTDRIVE_DISABLED SAI_OUTPUTDRIVE_DISABLE #define SAI_OUTPUTDRIVE_ENABLED SAI_OUTPUTDRIVE_ENABLE #define SAI_MASTERDIVIDER_ENABLED SAI_MASTERDIVIDER_ENABLE #define SAI_MASTERDIVIDER_DISABLED SAI_MASTERDIVIDER_DISABLE #define SAI_STREOMODE SAI_STEREOMODE #define SAI_FIFOStatus_Empty SAI_FIFOSTATUS_EMPTY #define SAI_FIFOStatus_Less1QuarterFull SAI_FIFOSTATUS_LESS1QUARTERFULL #define SAI_FIFOStatus_1QuarterFull SAI_FIFOSTATUS_1QUARTERFULL #define SAI_FIFOStatus_HalfFull SAI_FIFOSTATUS_HALFFULL #define SAI_FIFOStatus_3QuartersFull SAI_FIFOSTATUS_3QUARTERFULL #define SAI_FIFOStatus_Full SAI_FIFOSTATUS_FULL #define IS_SAI_BLOCK_MONO_STREO_MODE IS_SAI_BLOCK_MONO_STEREO_MODE /** * @} */ /** @defgroup HAL_PPP_Aliased_Macros HAL PPP Aliased Macros maintained for legacy purpose * @{ */ /** * @} */ #ifdef __cplusplus } #endif #endif /* ___STM32_HAL_LEGACY */ /************************ (C) COPYRIGHT STMicroelectronics *****END OF FILE****/ ================================================ FILE: Zelig/mbed/TARGET_NUCLEO_F091RC/stm32f091xc.h ================================================ /** ****************************************************************************** * @file stm32f091xc.h * @author MCD Application Team * @version V2.2.2 * @date 26-June-2015 * @brief CMSIS STM32F091xC devices Peripheral Access Layer Header File. * * This file contains: * - Data structures and the address mapping for all peripherals * - Peripheral's registers declarations and bits definition * - Macros to access peripherals registers hardware * ****************************************************************************** * @attention * *

© COPYRIGHT(c) 2015 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. * ****************************************************************************** */ /** @addtogroup CMSIS_Device * @{ */ /** @addtogroup stm32f091xc * @{ */ #ifndef __STM32F091xC_H #define __STM32F091xC_H #ifdef __cplusplus extern "C" { #endif /* __cplusplus */ /** @addtogroup Configuration_section_for_CMSIS * @{ */ /** * @brief Configuration of the Cortex-M0 Processor and Core Peripherals */ #define __CM0_REV 0 /*!< Core Revision r0p0 */ #define __MPU_PRESENT 0 /*!< STM32F0xx do not provide MPU */ #define __NVIC_PRIO_BITS 2 /*!< STM32F0xx uses 2 Bits for the Priority Levels */ #define __Vendor_SysTickConfig 0 /*!< Set to 1 if different SysTick Config is used */ /** * @} */ /** @addtogroup Peripheral_interrupt_number_definition * @{ */ /** * @brief STM32F091xC device Interrupt Number Definition */ typedef enum { /****** Cortex-M0 Processor Exceptions Numbers **************************************************************/ NonMaskableInt_IRQn = -14, /*!< 2 Non Maskable Interrupt */ HardFault_IRQn = -13, /*!< 3 Cortex-M0 Hard Fault Interrupt */ SVC_IRQn = -5, /*!< 11 Cortex-M0 SV Call Interrupt */ PendSV_IRQn = -2, /*!< 14 Cortex-M0 Pend SV Interrupt */ SysTick_IRQn = -1, /*!< 15 Cortex-M0 System Tick Interrupt */ /****** STM32F091xC specific Interrupt Numbers **************************************************/ WWDG_IRQn = 0, /*!< Window WatchDog Interrupt */ PVD_VDDIO2_IRQn = 1, /*!< PVD & VDDIO2 Interrupts through EXTI Lines 16 and 31 */ RTC_IRQn = 2, /*!< RTC Interrupt through EXTI Lines 17, 19 and 20 */ FLASH_IRQn = 3, /*!< FLASH global Interrupt */ RCC_CRS_IRQn = 4, /*!< RCC & CRS global Interrupts */ EXTI0_1_IRQn = 5, /*!< EXTI Line 0 and 1 Interrupts */ EXTI2_3_IRQn = 6, /*!< EXTI Line 2 and 3 Interrupts */ EXTI4_15_IRQn = 7, /*!< EXTI Line 4 to 15 Interrupts */ TSC_IRQn = 8, /*!< Touch Sensing Controller Interrupts */ DMA1_Ch1_IRQn = 9, /*!< DMA1 Channel 1 Interrupt */ DMA1_Ch2_3_DMA2_Ch1_2_IRQn = 10, /*!< DMA1 Channel 2 and 3 & DMA2 Channel 1 and 2 Interrupts */ DMA1_Ch4_7_DMA2_Ch3_5_IRQn = 11, /*!< DMA1 Channel 4 to 7 & DMA2 Channel 3 to 5 Interrupts */ ADC1_COMP_IRQn = 12, /*!< ADC, COMP1 and COMP2 Interrupts (EXTI Lines 21 and 22) */ TIM1_BRK_UP_TRG_COM_IRQn = 13, /*!< TIM1 Break, Update, Trigger and Commutation Interrupts */ TIM1_CC_IRQn = 14, /*!< TIM1 Capture Compare Interrupt */ TIM2_IRQn = 15, /*!< TIM2 global Interrupt */ TIM3_IRQn = 16, /*!< TIM3 global Interrupt */ TIM6_DAC_IRQn = 17, /*!< TIM6 global and DAC channel underrun error Interrupts */ TIM7_IRQn = 18, /*!< TIM7 global Interrupt */ TIM14_IRQn = 19, /*!< TIM14 global Interrupt */ TIM15_IRQn = 20, /*!< TIM15 global Interrupt */ TIM16_IRQn = 21, /*!< TIM16 global Interrupt */ TIM17_IRQn = 22, /*!< TIM17 global Interrupt */ I2C1_IRQn = 23, /*!< I2C1 Event Interrupt & EXTI Line23 Interrupt (I2C1 wakeup) */ I2C2_IRQn = 24, /*!< I2C2 Event Interrupt */ SPI1_IRQn = 25, /*!< SPI1 global Interrupt */ SPI2_IRQn = 26, /*!< SPI2 global Interrupt */ USART1_IRQn = 27, /*!< USART1 global Interrupt & EXTI Line25 Interrupt (USART1 wakeup) */ USART2_IRQn = 28, /*!< USART2 global Interrupt & EXTI Line26 Interrupt (USART2 wakeup) */ USART3_8_IRQn = 29, /*!< USART3 to USART8 global Interrupts */ CEC_CAN_IRQn = 30 /*!< CEC and CAN global Interrupts & EXTI Line27 Interrupt */ } IRQn_Type; /** * @} */ #include "core_cm0.h" /* Cortex-M0 processor and core peripherals */ #include "system_stm32f0xx.h" /* STM32F0xx System Header */ #include /** @addtogroup Peripheral_registers_structures * @{ */ /** * @brief Analog to Digital Converter */ typedef struct { __IO uint32_t ISR; /*!< ADC Interrupt and Status register, Address offset:0x00 */ __IO uint32_t IER; /*!< ADC Interrupt Enable register, Address offset:0x04 */ __IO uint32_t CR; /*!< ADC Control register, Address offset:0x08 */ __IO uint32_t CFGR1; /*!< ADC Configuration register 1, Address offset:0x0C */ __IO uint32_t CFGR2; /*!< ADC Configuration register 2, Address offset:0x10 */ __IO uint32_t SMPR; /*!< ADC Sampling time register, Address offset:0x14 */ uint32_t RESERVED1; /*!< Reserved, 0x18 */ uint32_t RESERVED2; /*!< Reserved, 0x1C */ __IO uint32_t TR; /*!< ADC watchdog threshold register, Address offset:0x20 */ uint32_t RESERVED3; /*!< Reserved, 0x24 */ __IO uint32_t CHSELR; /*!< ADC channel selection register, Address offset:0x28 */ uint32_t RESERVED4[5]; /*!< Reserved, 0x2C */ __IO uint32_t DR; /*!< ADC data register, Address offset:0x40 */ }ADC_TypeDef; typedef struct { __IO uint32_t CCR; }ADC_Common_TypeDef; /** * @brief Controller Area Network TxMailBox */ typedef struct { __IO uint32_t TIR; /*!< CAN TX mailbox identifier register */ __IO uint32_t TDTR; /*!< CAN mailbox data length control and time stamp register */ __IO uint32_t TDLR; /*!< CAN mailbox data low register */ __IO uint32_t TDHR; /*!< CAN mailbox data high register */ }CAN_TxMailBox_TypeDef; /** * @brief Controller Area Network FIFOMailBox */ typedef struct { __IO uint32_t RIR; /*!< CAN receive FIFO mailbox identifier register */ __IO uint32_t RDTR; /*!< CAN receive FIFO mailbox data length control and time stamp register */ __IO uint32_t RDLR; /*!< CAN receive FIFO mailbox data low register */ __IO uint32_t RDHR; /*!< CAN receive FIFO mailbox data high register */ }CAN_FIFOMailBox_TypeDef; /** * @brief Controller Area Network FilterRegister */ typedef struct { __IO uint32_t FR1; /*!< CAN Filter bank register 1 */ __IO uint32_t FR2; /*!< CAN Filter bank register 1 */ }CAN_FilterRegister_TypeDef; /** * @brief Controller Area Network */ typedef struct { __IO uint32_t MCR; /*!< CAN master control register, Address offset: 0x00 */ __IO uint32_t MSR; /*!< CAN master status register, Address offset: 0x04 */ __IO uint32_t TSR; /*!< CAN transmit status register, Address offset: 0x08 */ __IO uint32_t RF0R; /*!< CAN receive FIFO 0 register, Address offset: 0x0C */ __IO uint32_t RF1R; /*!< CAN receive FIFO 1 register, Address offset: 0x10 */ __IO uint32_t IER; /*!< CAN interrupt enable register, Address offset: 0x14 */ __IO uint32_t ESR; /*!< CAN error status register, Address offset: 0x18 */ __IO uint32_t BTR; /*!< CAN bit timing register, Address offset: 0x1C */ uint32_t RESERVED0[88]; /*!< Reserved, 0x020 - 0x17F */ CAN_TxMailBox_TypeDef sTxMailBox[3]; /*!< CAN Tx MailBox, Address offset: 0x180 - 0x1AC */ CAN_FIFOMailBox_TypeDef sFIFOMailBox[2]; /*!< CAN FIFO MailBox, Address offset: 0x1B0 - 0x1CC */ uint32_t RESERVED1[12]; /*!< Reserved, 0x1D0 - 0x1FF */ __IO uint32_t FMR; /*!< CAN filter master register, Address offset: 0x200 */ __IO uint32_t FM1R; /*!< CAN filter mode register, Address offset: 0x204 */ uint32_t RESERVED2; /*!< Reserved, 0x208 */ __IO uint32_t FS1R; /*!< CAN filter scale register, Address offset: 0x20C */ uint32_t RESERVED3; /*!< Reserved, 0x210 */ __IO uint32_t FFA1R; /*!< CAN filter FIFO assignment register, Address offset: 0x214 */ uint32_t RESERVED4; /*!< Reserved, 0x218 */ __IO uint32_t FA1R; /*!< CAN filter activation register, Address offset: 0x21C */ uint32_t RESERVED5[8]; /*!< Reserved, 0x220-0x23F */ CAN_FilterRegister_TypeDef sFilterRegister[28]; /*!< CAN Filter Register, Address offset: 0x240-0x31C */ }CAN_TypeDef; /** * @brief HDMI-CEC */ typedef struct { __IO uint32_t CR; /*!< CEC control register, Address offset:0x00 */ __IO uint32_t CFGR; /*!< CEC configuration register, Address offset:0x04 */ __IO uint32_t TXDR; /*!< CEC Tx data register , Address offset:0x08 */ __IO uint32_t RXDR; /*!< CEC Rx Data Register, Address offset:0x0C */ __IO uint32_t ISR; /*!< CEC Interrupt and Status Register, Address offset:0x10 */ __IO uint32_t IER; /*!< CEC interrupt enable register, Address offset:0x14 */ }CEC_TypeDef; /** * @brief Comparator */ typedef struct { __IO uint32_t CSR; /*!< Comparator 1 & 2 control Status register, Address offset: 0x00 */ }COMP1_2_TypeDef; typedef struct { __IO uint16_t CSR; /*!< Comparator control Status register, Address offset: 0x00 */ }COMP_TypeDef; /** * @brief CRC calculation unit */ typedef struct { __IO uint32_t DR; /*!< CRC Data register, Address offset: 0x00 */ __IO uint8_t IDR; /*!< CRC Independent data register, Address offset: 0x04 */ uint8_t RESERVED0; /*!< Reserved, 0x05 */ uint16_t RESERVED1; /*!< Reserved, 0x06 */ __IO uint32_t CR; /*!< CRC Control register, Address offset: 0x08 */ uint32_t RESERVED2; /*!< Reserved, 0x0C */ __IO uint32_t INIT; /*!< Initial CRC value register, Address offset: 0x10 */ __IO uint32_t POL; /*!< CRC polynomial register, Address offset: 0x14 */ }CRC_TypeDef; /** * @brief Clock Recovery System */ typedef struct { __IO uint32_t CR; /*!< CRS ccontrol register, Address offset: 0x00 */ __IO uint32_t CFGR; /*!< CRS configuration register, Address offset: 0x04 */ __IO uint32_t ISR; /*!< CRS interrupt and status register, Address offset: 0x08 */ __IO uint32_t ICR; /*!< CRS interrupt flag clear register, Address offset: 0x0C */ }CRS_TypeDef; /** * @brief Digital to Analog Converter */ typedef struct { __IO uint32_t CR; /*!< DAC control register, Address offset: 0x00 */ __IO uint32_t SWTRIGR; /*!< DAC software trigger register, Address offset: 0x04 */ __IO uint32_t DHR12R1; /*!< DAC channel1 12-bit right-aligned data holding register, Address offset: 0x08 */ __IO uint32_t DHR12L1; /*!< DAC channel1 12-bit left aligned data holding register, Address offset: 0x0C */ __IO uint32_t DHR8R1; /*!< DAC channel1 8-bit right aligned data holding register, Address offset: 0x10 */ __IO uint32_t DHR12R2; /*!< DAC channel2 12-bit right aligned data holding register, Address offset: 0x14 */ __IO uint32_t DHR12L2; /*!< DAC channel2 12-bit left aligned data holding register, Address offset: 0x18 */ __IO uint32_t DHR8R2; /*!< DAC channel2 8-bit right-aligned data holding register, Address offset: 0x1C */ __IO uint32_t DHR12RD; /*!< Dual DAC 12-bit right-aligned data holding register, Address offset: 0x20 */ __IO uint32_t DHR12LD; /*!< DUAL DAC 12-bit left aligned data holding register, Address offset: 0x24 */ __IO uint32_t DHR8RD; /*!< DUAL DAC 8-bit right aligned data holding register, Address offset: 0x28 */ __IO uint32_t DOR1; /*!< DAC channel1 data output register, Address offset: 0x2C */ __IO uint32_t DOR2; /*!< DAC channel2 data output register, Address offset: 0x30 */ __IO uint32_t SR; /*!< DAC status register, Address offset: 0x34 */ }DAC_TypeDef; /** * @brief Debug MCU */ typedef struct { __IO uint32_t IDCODE; /*!< MCU device ID code, Address offset: 0x00 */ __IO uint32_t CR; /*!< Debug MCU configuration register, Address offset: 0x04 */ __IO uint32_t APB1FZ; /*!< Debug MCU APB1 freeze register, Address offset: 0x08 */ __IO uint32_t APB2FZ; /*!< Debug MCU APB2 freeze register, Address offset: 0x0C */ }DBGMCU_TypeDef; /** * @brief DMA Controller */ typedef struct { __IO uint32_t CCR; /*!< DMA channel x configuration register */ __IO uint32_t CNDTR; /*!< DMA channel x number of data register */ __IO uint32_t CPAR; /*!< DMA channel x peripheral address register */ __IO uint32_t CMAR; /*!< DMA channel x memory address register */ }DMA_Channel_TypeDef; typedef struct { __IO uint32_t ISR; /*!< DMA interrupt status register, Address offset: 0x00 */ __IO uint32_t IFCR; /*!< DMA interrupt flag clear register, Address offset: 0x04 */ uint32_t RESERVED0[40];/*!< Reserved as declared by channel typedef 0x08 - 0xA4 */ __IO uint32_t CSELR; /*!< Channel selection register, Address offset: 0xA8 */ }DMA_TypeDef; /** * @brief External Interrupt/Event Controller */ typedef struct { __IO uint32_t IMR; /*! exti[31] Interrupt */ #define SYSCFG_ITLINE1_SR_VDDIO2 ((uint32_t)0x00000002) /*!< VDDIO2 -> exti[16] Interrupt */ #define SYSCFG_ITLINE2_SR_RTC_WAKEUP ((uint32_t)0x00000001) /*!< RTC WAKEUP -> exti[20] Interrupt */ #define SYSCFG_ITLINE2_SR_RTC_TSTAMP ((uint32_t)0x00000002) /*!< RTC Time Stamp -> exti[19] interrupt */ #define SYSCFG_ITLINE2_SR_RTC_ALRA ((uint32_t)0x00000003) /*!< RTC Alarm -> exti[17] interrupt .... */ #define SYSCFG_ITLINE3_SR_FLASH_ITF ((uint32_t)0x00000001) /*!< Flash ITF Interrupt */ #define SYSCFG_ITLINE4_SR_CRS ((uint32_t)0x00000001) /*!< CRS interrupt */ #define SYSCFG_ITLINE4_SR_CLK_CTRL ((uint32_t)0x00000002) /*!< CLK CTRL interrupt */ #define SYSCFG_ITLINE5_SR_EXTI0 ((uint32_t)0x00000001) /*!< External Interrupt 0 */ #define SYSCFG_ITLINE5_SR_EXTI1 ((uint32_t)0x00000002) /*!< External Interrupt 1 */ #define SYSCFG_ITLINE6_SR_EXTI2 ((uint32_t)0x00000001) /*!< External Interrupt 2 */ #define SYSCFG_ITLINE6_SR_EXTI3 ((uint32_t)0x00000002) /*!< External Interrupt 3 */ #define SYSCFG_ITLINE7_SR_EXTI4 ((uint32_t)0x00000001) /*!< External Interrupt 15 to 4 */ #define SYSCFG_ITLINE7_SR_EXTI5 ((uint32_t)0x00000002) /*!< External Interrupt 15 to 4 */ #define SYSCFG_ITLINE7_SR_EXTI6 ((uint32_t)0x00000004) /*!< External Interrupt 15 to 4 */ #define SYSCFG_ITLINE7_SR_EXTI7 ((uint32_t)0x00000008) /*!< External Interrupt 15 to 4 */ #define SYSCFG_ITLINE7_SR_EXTI8 ((uint32_t)0x00000010) /*!< External Interrupt 15 to 4 */ #define SYSCFG_ITLINE7_SR_EXTI9 ((uint32_t)0x00000020) /*!< External Interrupt 15 to 4 */ #define SYSCFG_ITLINE7_SR_EXTI10 ((uint32_t)0x00000040) /*!< External Interrupt 15 to 4 */ #define SYSCFG_ITLINE7_SR_EXTI11 ((uint32_t)0x00000080) /*!< External Interrupt 15 to 4 */ #define SYSCFG_ITLINE7_SR_EXTI12 ((uint32_t)0x00000100) /*!< External Interrupt 15 to 4 */ #define SYSCFG_ITLINE7_SR_EXTI13 ((uint32_t)0x00000200) /*!< External Interrupt 15 to 4 */ #define SYSCFG_ITLINE7_SR_EXTI14 ((uint32_t)0x00000400) /*!< External Interrupt 15 to 4 */ #define SYSCFG_ITLINE7_SR_EXTI15 ((uint32_t)0x00000800) /*!< External Interrupt 15 to 4 */ #define SYSCFG_ITLINE8_SR_TSC_EOA ((uint32_t)0x00000001) /*!< Touch control EOA Interrupt */ #define SYSCFG_ITLINE8_SR_TSC_MCE ((uint32_t)0x00000002) /*!< Touch control MCE Interrupt */ #define SYSCFG_ITLINE9_SR_DMA1_CH1 ((uint32_t)0x00000001) /*!< DMA1 Channel 1 Interrupt */ #define SYSCFG_ITLINE10_SR_DMA1_CH2 ((uint32_t)0x00000001) /*!< DMA1 Channel 2 Interrupt */ #define SYSCFG_ITLINE10_SR_DMA1_CH3 ((uint32_t)0x00000002) /*!< DMA2 Channel 3 Interrupt */ #define SYSCFG_ITLINE10_SR_DMA2_CH1 ((uint32_t)0x00000004) /*!< DMA2 Channel 1 Interrupt */ #define SYSCFG_ITLINE10_SR_DMA2_CH2 ((uint32_t)0x00000008) /*!< DMA2 Channel 2 Interrupt */ #define SYSCFG_ITLINE11_SR_DMA1_CH4 ((uint32_t)0x00000001) /*!< DMA1 Channel 4 Interrupt */ #define SYSCFG_ITLINE11_SR_DMA1_CH5 ((uint32_t)0x00000002) /*!< DMA1 Channel 5 Interrupt */ #define SYSCFG_ITLINE11_SR_DMA1_CH6 ((uint32_t)0x00000004) /*!< DMA1 Channel 6 Interrupt */ #define SYSCFG_ITLINE11_SR_DMA1_CH7 ((uint32_t)0x00000008) /*!< DMA1 Channel 7 Interrupt */ #define SYSCFG_ITLINE11_SR_DMA2_CH3 ((uint32_t)0x00000010) /*!< DMA2 Channel 3 Interrupt */ #define SYSCFG_ITLINE11_SR_DMA2_CH4 ((uint32_t)0x00000020) /*!< DMA2 Channel 4 Interrupt */ #define SYSCFG_ITLINE11_SR_DMA2_CH5 ((uint32_t)0x00000040) /*!< DMA2 Channel 5 Interrupt */ #define SYSCFG_ITLINE12_SR_ADC ((uint32_t)0x00000001) /*!< ADC Interrupt */ #define SYSCFG_ITLINE12_SR_COMP1 ((uint32_t)0x00000002) /*!< COMP1 Interrupt -> exti[21] */ #define SYSCFG_ITLINE12_SR_COMP2 ((uint32_t)0x00000004) /*!< COMP2 Interrupt -> exti[22] */ #define SYSCFG_ITLINE13_SR_TIM1_BRK ((uint32_t)0x00000001) /*!< TIM1 BRK Interrupt */ #define SYSCFG_ITLINE13_SR_TIM1_UPD ((uint32_t)0x00000002) /*!< TIM1 UPD Interrupt */ #define SYSCFG_ITLINE13_SR_TIM1_TRG ((uint32_t)0x00000004) /*!< TIM1 TRG Interrupt */ #define SYSCFG_ITLINE13_SR_TIM1_CCU ((uint32_t)0x00000008) /*!< TIM1 CCU Interrupt */ #define SYSCFG_ITLINE14_SR_TIM1_CC ((uint32_t)0x00000001) /*!< TIM1 CC Interrupt */ #define SYSCFG_ITLINE15_SR_TIM2_GLB ((uint32_t)0x00000001) /*!< TIM2 GLB Interrupt */ #define SYSCFG_ITLINE16_SR_TIM3_GLB ((uint32_t)0x00000001) /*!< TIM3 GLB Interrupt */ #define SYSCFG_ITLINE17_SR_DAC ((uint32_t)0x00000001) /*!< DAC Interrupt */ #define SYSCFG_ITLINE17_SR_TIM6_GLB ((uint32_t)0x00000002) /*!< TIM6 GLB Interrupt */ #define SYSCFG_ITLINE18_SR_TIM7_GLB ((uint32_t)0x00000001) /*!< TIM7 GLB Interrupt */ #define SYSCFG_ITLINE19_SR_TIM14_GLB ((uint32_t)0x00000001) /*!< TIM14 GLB Interrupt */ #define SYSCFG_ITLINE20_SR_TIM15_GLB ((uint32_t)0x00000001) /*!< TIM15 GLB Interrupt */ #define SYSCFG_ITLINE21_SR_TIM16_GLB ((uint32_t)0x00000001) /*!< TIM16 GLB Interrupt */ #define SYSCFG_ITLINE22_SR_TIM17_GLB ((uint32_t)0x00000001) /*!< TIM17 GLB Interrupt */ #define SYSCFG_ITLINE23_SR_I2C1_GLB ((uint32_t)0x00000001) /*!< I2C1 GLB Interrupt -> exti[23] */ #define SYSCFG_ITLINE24_SR_I2C2_GLB ((uint32_t)0x00000001) /*!< I2C2 GLB Interrupt */ #define SYSCFG_ITLINE25_SR_SPI1 ((uint32_t)0x00000001) /*!< SPI1 Interrupt */ #define SYSCFG_ITLINE26_SR_SPI2 ((uint32_t)0x00000001) /*!< SPI2 Interrupt */ #define SYSCFG_ITLINE27_SR_USART1_GLB ((uint32_t)0x00000001) /*!< USART1 GLB Interrupt -> exti[25] */ #define SYSCFG_ITLINE28_SR_USART2_GLB ((uint32_t)0x00000001) /*!< USART2 GLB Interrupt -> exti[26] */ #define SYSCFG_ITLINE29_SR_USART3_GLB ((uint32_t)0x00000001) /*!< USART3 GLB Interrupt -> exti[28] */ #define SYSCFG_ITLINE29_SR_USART4_GLB ((uint32_t)0x00000002) /*!< USART4 GLB Interrupt */ #define SYSCFG_ITLINE29_SR_USART5_GLB ((uint32_t)0x00000004) /*!< USART5 GLB Interrupt */ #define SYSCFG_ITLINE29_SR_USART6_GLB ((uint32_t)0x00000008) /*!< USART6 GLB Interrupt */ #define SYSCFG_ITLINE29_SR_USART7_GLB ((uint32_t)0x00000010) /*!< USART7 GLB Interrupt */ #define SYSCFG_ITLINE29_SR_USART8_GLB ((uint32_t)0x00000020) /*!< USART8 GLB Interrupt */ #define SYSCFG_ITLINE30_SR_CAN ((uint32_t)0x00000001) /*!< CAN Interrupt */ #define SYSCFG_ITLINE30_SR_CEC ((uint32_t)0x00000002) /*!< CEC Interrupt */ /*****************************************************************************/ /* */ /* Timers (TIM) */ /* */ /*****************************************************************************/ /******************* Bit definition for TIM_CR1 register *******************/ #define TIM_CR1_CEN ((uint32_t)0x00000001) /*!
© COPYRIGHT(c) 2015 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. * ****************************************************************************** */ /** @addtogroup CMSIS * @{ */ /** @addtogroup stm32f0xx * @{ */ #ifndef __STM32F0xx_H #define __STM32F0xx_H #ifdef __cplusplus extern "C" { #endif /* __cplusplus */ /** @addtogroup Library_configuration_section * @{ */ /** * @brief STM32 Family */ #if !defined (STM32F0) #define STM32F0 #endif /* STM32F0 */ /* Uncomment the line below according to the target STM32 device used in your application */ #if !defined (STM32F030x6) && !defined (STM32F030x8) && \ !defined (STM32F031x6) && !defined (STM32F038xx) && \ !defined (STM32F042x6) && !defined (STM32F048xx) && !defined (STM32F070x6) && \ !defined (STM32F051x8) && !defined (STM32F058xx) && \ !defined (STM32F071xB) && !defined (STM32F072xB) && !defined (STM32F078xx) && !defined (STM32F070xB) && \ !defined (STM32F091xC) && !defined (STM32F098xx) && !defined (STM32F030xC) /* #define STM32F030x6 */ /*!< STM32F030x4, STM32F030x6 Devices (STM32F030xx microcontrollers where the Flash memory ranges between 16 and 32 Kbytes) */ /* #define STM32F030x8 */ /*!< STM32F030x8 Devices (STM32F030xx microcontrollers where the Flash memory is 64 Kbytes) */ /* #define STM32F031x6 */ /*!< STM32F031x4, STM32F031x6 Devices (STM32F031xx microcontrollers where the Flash memory ranges between 16 and 32 Kbytes) */ /* #define STM32F038xx */ /*!< STM32F038xx Devices (STM32F038xx microcontrollers where the Flash memory is 32 Kbytes) */ /* #define STM32F042x6 */ /*!< STM32F042x4, STM32F042x6 Devices (STM32F042xx microcontrollers where the Flash memory ranges between 16 and 32 Kbytes) */ /* #define STM32F048x6 */ /*!< STM32F048xx Devices (STM32F042xx microcontrollers where the Flash memory is 32 Kbytes) */ /* #define STM32F051x8 */ /*!< STM32F051x4, STM32F051x6, STM32F051x8 Devices (STM32F051xx microcontrollers where the Flash memory ranges between 16 and 64 Kbytes) */ /* #define STM32F058xx */ /*!< STM32F058xx Devices (STM32F058xx microcontrollers where the Flash memory is 64 Kbytes) */ /* #define STM32F070x6 */ /*!< STM32F070x6 Devices (STM32F070x6 microcontrollers where the Flash memory ranges between 16 and 32 Kbytes) */ /* #define STM32F070xB */ /*!< STM32F070xB Devices (STM32F070xB microcontrollers where the Flash memory ranges between 64 and 128 Kbytes) */ /* #define STM32F071xB */ /*!< STM32F071x8, STM32F071xB Devices (STM32F071xx microcontrollers where the Flash memory ranges between 64 and 128 Kbytes) */ /* #define STM32F072xB */ /*!< STM32F072x8, STM32F072xB Devices (STM32F072xx microcontrollers where the Flash memory ranges between 64 and 128 Kbytes) */ /* #define STM32F078xx */ /*!< STM32F078xx Devices (STM32F078xx microcontrollers where the Flash memory is 128 Kbytes) */ /* #define STM32F030xC */ /*!< STM32F030xC Devices (STM32F030xC microcontrollers where the Flash memory is 256 Kbytes) */ #define STM32F091xC /*!< STM32F091xC Devices (STM32F091xx microcontrollers where the Flash memory is 256 Kbytes) */ /* #define STM32F098xx */ /*!< STM32F098xx Devices (STM32F098xx microcontrollers where the Flash memory is 256 Kbytes) */ #endif /* Tip: To avoid modifying this file each time you need to switch between these devices, you can define the device in your toolchain compiler preprocessor. */ #if !defined (USE_HAL_DRIVER) /** * @brief Comment the line below if you will not use the peripherals drivers. In this case, these drivers will not be included and the application code will be based on direct access to peripherals registers */ #define USE_HAL_DRIVER #endif /* USE_HAL_DRIVER */ /** * @brief CMSIS Device version number V2.2.2 */ #define __STM32F0xx_CMSIS_DEVICE_VERSION_MAIN (0x02) /*!< [31:24] main version */ #define __STM32F0xx_CMSIS_DEVICE_VERSION_SUB1 (0x02) /*!< [23:16] sub1 version */ #define __STM32F0xx_CMSIS_DEVICE_VERSION_SUB2 (0x02) /*!< [15:8] sub2 version */ #define __STM32F0xx_CMSIS_DEVICE_VERSION_RC (0x00) /*!< [7:0] release candidate */ #define __STM32F0xx_CMSIS_DEVICE_VERSION ((__CMSIS_DEVICE_VERSION_MAIN << 24)\ |(__CMSIS_DEVICE_HAL_VERSION_SUB1 << 16)\ |(__CMSIS_DEVICE_HAL_VERSION_SUB2 << 8 )\ |(__CMSIS_DEVICE_HAL_VERSION_RC)) /** * @} */ /** @addtogroup Device_Included * @{ */ #if defined(STM32F030x6) #include "stm32f030x6.h" #elif defined(STM32F030x8) #include "stm32f030x8.h" #elif defined(STM32F031x6) #include "stm32f031x6.h" #elif defined(STM32F038xx) #include "stm32f038xx.h" #elif defined(STM32F042x6) #include "stm32f042x6.h" #elif defined(STM32F048xx) #include "stm32f048xx.h" #elif defined(STM32F051x8) #include "stm32f051x8.h" #elif defined(STM32F058xx) #include "stm32f058xx.h" #elif defined(STM32F070x6) #include "stm32f070x6.h" #elif defined(STM32F070xB) #include "stm32f070xb.h" #elif defined(STM32F071xB) #include "stm32f071xb.h" #elif defined(STM32F072xB) #include "stm32f072xb.h" #elif defined(STM32F078xx) #include "stm32f078xx.h" #elif defined(STM32F091xC) #include "stm32f091xc.h" #elif defined(STM32F098xx) #include "stm32f098xx.h" #elif defined(STM32F030xC) #include "stm32f030xc.h" #else #error "Please select first the target STM32F0xx device used in your application (in stm32f0xx.h file)" #endif /** * @} */ /** @addtogroup Exported_types * @{ */ typedef enum { RESET = 0, SET = !RESET } FlagStatus, ITStatus; typedef enum { DISABLE = 0, ENABLE = !DISABLE } FunctionalState; #define IS_FUNCTIONAL_STATE(STATE) (((STATE) == DISABLE) || ((STATE) == ENABLE)) typedef enum { ERROR = 0, SUCCESS = !ERROR } ErrorStatus; /** * @} */ /** @addtogroup Exported_macros * @{ */ #define SET_BIT(REG, BIT) ((REG) |= (BIT)) #define CLEAR_BIT(REG, BIT) ((REG) &= ~(BIT)) #define READ_BIT(REG, BIT) ((REG) & (BIT)) #define CLEAR_REG(REG) ((REG) = (0x0)) #define WRITE_REG(REG, VAL) ((REG) = (VAL)) #define READ_REG(REG) ((REG)) #define MODIFY_REG(REG, CLEARMASK, SETMASK) WRITE_REG((REG), (((READ_REG(REG)) & (~(CLEARMASK))) | (SETMASK))) /** * @} */ #if defined (USE_HAL_DRIVER) #include "stm32f0xx_hal.h" #endif /* USE_HAL_DRIVER */ #ifdef __cplusplus } #endif /* __cplusplus */ #endif /* __STM32F0xx_H */ /** * @} */ /** * @} */ /************************ (C) COPYRIGHT STMicroelectronics *****END OF FILE****/ ================================================ FILE: Zelig/mbed/TARGET_NUCLEO_F091RC/stm32f0xx_hal.h ================================================ /** ****************************************************************************** * @file stm32f0xx_hal.h * @author MCD Application Team * @version V1.3.0 * @date 26-June-2015 * @brief This file contains all the functions prototypes for the HAL * module driver. ****************************************************************************** * @attention * *

© COPYRIGHT(c) 2015 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. * ****************************************************************************** */ /* Define to prevent recursive inclusion -------------------------------------*/ #ifndef __STM32F0xx_HAL_H #define __STM32F0xx_HAL_H #ifdef __cplusplus extern "C" { #endif /* Includes ------------------------------------------------------------------*/ #include "stm32f0xx_hal_conf.h" /** @addtogroup STM32F0xx_HAL_Driver * @{ */ /** @addtogroup HAL * @{ */ /* Private macros ------------------------------------------------------------*/ /** @addtogroup HAL_Private_Macros * @{ */ #if defined(STM32F091xC) || defined(STM32F098xx) || defined(STM32F042x6) || defined(STM32F048xx) || \ defined(STM32F030x6) || defined(STM32F031x6) || defined(STM32F038xx) || defined(STM32F070x6) || \ defined(STM32F070xB) || defined(STM32F030x6) #define IS_SYSCFG_FASTMODEPLUS(__PIN__) ((((__PIN__) & SYSCFG_FASTMODEPLUS_PA9) == SYSCFG_FASTMODEPLUS_PA9) || \ (((__PIN__) & SYSCFG_FASTMODEPLUS_PA10) == SYSCFG_FASTMODEPLUS_PA10) || \ (((__PIN__) & SYSCFG_FASTMODEPLUS_PB6) == SYSCFG_FASTMODEPLUS_PB6) || \ (((__PIN__) & SYSCFG_FASTMODEPLUS_PB7) == SYSCFG_FASTMODEPLUS_PB7) || \ (((__PIN__) & SYSCFG_FASTMODEPLUS_PB8) == SYSCFG_FASTMODEPLUS_PB8) || \ (((__PIN__) & SYSCFG_FASTMODEPLUS_PB9) == SYSCFG_FASTMODEPLUS_PB9)) #else #define IS_SYSCFG_FASTMODEPLUS(__PIN__) ((((__PIN__) & SYSCFG_FASTMODEPLUS_PB6) == SYSCFG_FASTMODEPLUS_PB6) || \ (((__PIN__) & SYSCFG_FASTMODEPLUS_PB7) == SYSCFG_FASTMODEPLUS_PB7) || \ (((__PIN__) & SYSCFG_FASTMODEPLUS_PB8) == SYSCFG_FASTMODEPLUS_PB8) || \ (((__PIN__) & SYSCFG_FASTMODEPLUS_PB9) == SYSCFG_FASTMODEPLUS_PB9)) #endif #if defined(SYSCFG_CFGR1_PA11_PA12_RMP) #define IS_HAL_REMAP_PIN(RMP) ((RMP) == HAL_REMAP_PA11_PA12) #endif /* SYSCFG_CFGR1_PA11_PA12_RMP */ #if defined(STM32F091xC) || defined(STM32F098xx) #define IS_HAL_SYSCFG_IRDA_ENV_SEL(SEL) (((SEL) == HAL_SYSCFG_IRDA_ENV_SEL_TIM16) || \ ((SEL) == HAL_SYSCFG_IRDA_ENV_SEL_USART1) || \ ((SEL) == HAL_SYSCFG_IRDA_ENV_SEL_USART4)) #endif /* STM32F091xC || STM32F098xx */ /** * @} */ /* Exported types ------------------------------------------------------------*/ /* Exported constants --------------------------------------------------------*/ /** @defgroup HAL_Exported_Constants HAL Exported Constants * @{ */ #if defined(SYSCFG_CFGR1_PA11_PA12_RMP) /** @defgroup HAL_Pin_remapping HAL Pin remapping * @{ */ #define HAL_REMAP_PA11_PA12 (SYSCFG_CFGR1_PA11_PA12_RMP) /*!< PA11 and PA12 remapping bit for small packages (28 and 20 pins). 0: No remap (pin pair PA9/10 mapped on the pins) 1: Remap (pin pair PA11/12 mapped instead of PA9/10) */ /** * @} */ #endif /* SYSCFG_CFGR1_PA11_PA12_RMP */ #if defined(STM32F091xC) || defined(STM32F098xx) /** @defgroup HAL_IRDA_ENV_SEL HAL IRDA Enveloppe Selection * @note Applicable on STM32F09x * @{ */ #define HAL_SYSCFG_IRDA_ENV_SEL_TIM16 (SYSCFG_CFGR1_IRDA_ENV_SEL_0 & SYSCFG_CFGR1_IRDA_ENV_SEL_1) /* 00: Timer16 is selected as IRDA Modulation enveloppe source */ #define HAL_SYSCFG_IRDA_ENV_SEL_USART1 (SYSCFG_CFGR1_IRDA_ENV_SEL_0) /* 01: USART1 is selected as IRDA Modulation enveloppe source */ #define HAL_SYSCFG_IRDA_ENV_SEL_USART4 (SYSCFG_CFGR1_IRDA_ENV_SEL_1) /* 10: USART4 is selected as IRDA Modulation enveloppe source */ /** * @} */ #endif /* STM32F091xC || STM32F098xx */ /** @defgroup SYSCFG_FastModePlus_GPIO Fast-mode Plus on GPIO * @{ */ /** @brief Fast-mode Plus driving capability on a specific GPIO */ #if defined(STM32F091xC) || defined(STM32F098xx) || defined(STM32F042x6) || defined(STM32F048xx) || \ defined(STM32F030x6) || defined(STM32F031x6) || defined(STM32F038xx) || defined(STM32F070x6) || \ defined(STM32F070xB) || defined(STM32F030x6) #define SYSCFG_FASTMODEPLUS_PA9 SYSCFG_CFGR1_I2C_FMP_PA9 /*!< Enable Fast-mode Plus on PA9 */ #define SYSCFG_FASTMODEPLUS_PA10 SYSCFG_CFGR1_I2C_FMP_PA10 /*!< Enable Fast-mode Plus on PA10 */ #endif #define SYSCFG_FASTMODEPLUS_PB6 SYSCFG_CFGR1_I2C_FMP_PB6 /*!< Enable Fast-mode Plus on PB6 */ #define SYSCFG_FASTMODEPLUS_PB7 SYSCFG_CFGR1_I2C_FMP_PB7 /*!< Enable Fast-mode Plus on PB7 */ #define SYSCFG_FASTMODEPLUS_PB8 SYSCFG_CFGR1_I2C_FMP_PB8 /*!< Enable Fast-mode Plus on PB8 */ #define SYSCFG_FASTMODEPLUS_PB9 SYSCFG_CFGR1_I2C_FMP_PB9 /*!< Enable Fast-mode Plus on PB9 */ /** * @} */ #if defined(STM32F091xC) || defined (STM32F098xx) /** @defgroup HAL_ISR_Wrapper HAL ISR Wrapper * @brief ISR Wrapper * @note applicable on STM32F09x * @{ */ #define HAL_SYSCFG_ITLINE0 ((uint32_t) 0x00000000) /*!< Internal define for macro handling */ #define HAL_SYSCFG_ITLINE1 ((uint32_t) 0x00000001) /*!< Internal define for macro handling */ #define HAL_SYSCFG_ITLINE2 ((uint32_t) 0x00000002) /*!< Internal define for macro handling */ #define HAL_SYSCFG_ITLINE3 ((uint32_t) 0x00000003) /*!< Internal define for macro handling */ #define HAL_SYSCFG_ITLINE4 ((uint32_t) 0x00000004) /*!< Internal define for macro handling */ #define HAL_SYSCFG_ITLINE5 ((uint32_t) 0x00000005) /*!< Internal define for macro handling */ #define HAL_SYSCFG_ITLINE6 ((uint32_t) 0x00000006) /*!< Internal define for macro handling */ #define HAL_SYSCFG_ITLINE7 ((uint32_t) 0x00000007) /*!< Internal define for macro handling */ #define HAL_SYSCFG_ITLINE8 ((uint32_t) 0x00000008) /*!< Internal define for macro handling */ #define HAL_SYSCFG_ITLINE9 ((uint32_t) 0x00000009) /*!< Internal define for macro handling */ #define HAL_SYSCFG_ITLINE10 ((uint32_t) 0x0000000A) /*!< Internal define for macro handling */ #define HAL_SYSCFG_ITLINE11 ((uint32_t) 0x0000000B) /*!< Internal define for macro handling */ #define HAL_SYSCFG_ITLINE12 ((uint32_t) 0x0000000C) /*!< Internal define for macro handling */ #define HAL_SYSCFG_ITLINE13 ((uint32_t) 0x0000000D) /*!< Internal define for macro handling */ #define HAL_SYSCFG_ITLINE14 ((uint32_t) 0x0000000E) /*!< Internal define for macro handling */ #define HAL_SYSCFG_ITLINE15 ((uint32_t) 0x0000000F) /*!< Internal define for macro handling */ #define HAL_SYSCFG_ITLINE16 ((uint32_t) 0x00000010) /*!< Internal define for macro handling */ #define HAL_SYSCFG_ITLINE17 ((uint32_t) 0x00000011) /*!< Internal define for macro handling */ #define HAL_SYSCFG_ITLINE18 ((uint32_t) 0x00000012) /*!< Internal define for macro handling */ #define HAL_SYSCFG_ITLINE19 ((uint32_t) 0x00000013) /*!< Internal define for macro handling */ #define HAL_SYSCFG_ITLINE20 ((uint32_t) 0x00000014) /*!< Internal define for macro handling */ #define HAL_SYSCFG_ITLINE21 ((uint32_t) 0x00000015) /*!< Internal define for macro handling */ #define HAL_SYSCFG_ITLINE22 ((uint32_t) 0x00000016) /*!< Internal define for macro handling */ #define HAL_SYSCFG_ITLINE23 ((uint32_t) 0x00000017) /*!< Internal define for macro handling */ #define HAL_SYSCFG_ITLINE24 ((uint32_t) 0x00000018) /*!< Internal define for macro handling */ #define HAL_SYSCFG_ITLINE25 ((uint32_t) 0x00000019) /*!< Internal define for macro handling */ #define HAL_SYSCFG_ITLINE26 ((uint32_t) 0x0000001A) /*!< Internal define for macro handling */ #define HAL_SYSCFG_ITLINE27 ((uint32_t) 0x0000001B) /*!< Internal define for macro handling */ #define HAL_SYSCFG_ITLINE28 ((uint32_t) 0x0000001C) /*!< Internal define for macro handling */ #define HAL_SYSCFG_ITLINE29 ((uint32_t) 0x0000001D) /*!< Internal define for macro handling */ #define HAL_SYSCFG_ITLINE30 ((uint32_t) 0x0000001E) /*!< Internal define for macro handling */ #define HAL_SYSCFG_ITLINE31 ((uint32_t) 0x0000001F) /*!< Internal define for macro handling */ #define HAL_ITLINE_EWDG ((uint32_t) ((HAL_SYSCFG_ITLINE0 << 0x18) | SYSCFG_ITLINE0_SR_EWDG)) /*!< EWDG has expired .... */ #if defined(STM32F091xC) #define HAL_ITLINE_PVDOUT ((uint32_t) ((HAL_SYSCFG_ITLINE1 << 0x18) | SYSCFG_ITLINE1_SR_PVDOUT)) /*!< Power voltage detection Interrupt .... */ #endif #define HAL_ITLINE_VDDIO2 ((uint32_t) ((HAL_SYSCFG_ITLINE1 << 0x18) | SYSCFG_ITLINE1_SR_VDDIO2)) /*!< VDDIO2 Interrupt .... */ #define HAL_ITLINE_RTC_WAKEUP ((uint32_t) ((HAL_SYSCFG_ITLINE2 << 0x18) | SYSCFG_ITLINE2_SR_RTC_WAKEUP)) /*!< RTC WAKEUP -> exti[20] Interrupt */ #define HAL_ITLINE_RTC_TSTAMP ((uint32_t) ((HAL_SYSCFG_ITLINE2 << 0x18) | SYSCFG_ITLINE2_SR_RTC_TSTAMP)) /*!< RTC Time Stamp -> exti[19] interrupt */ #define HAL_ITLINE_RTC_ALRA ((uint32_t) ((HAL_SYSCFG_ITLINE2 << 0x18) | SYSCFG_ITLINE2_SR_RTC_ALRA)) /*!< RTC Alarm -> exti[17] interrupt .... */ #define HAL_ITLINE_FLASH_ITF ((uint32_t) ((HAL_SYSCFG_ITLINE3 << 0x18) | SYSCFG_ITLINE3_SR_FLASH_ITF)) /*!< Flash ITF Interrupt */ #define HAL_ITLINE_CRS ((uint32_t) ((HAL_SYSCFG_ITLINE4 << 0x18) | SYSCFG_ITLINE4_SR_CRS)) /*!< CRS Interrupt */ #define HAL_ITLINE_CLK_CTRL ((uint32_t) ((HAL_SYSCFG_ITLINE4 << 0x18) | SYSCFG_ITLINE4_SR_CLK_CTRL)) /*!< CLK Control Interrupt */ #define HAL_ITLINE_EXTI0 ((uint32_t) ((HAL_SYSCFG_ITLINE5 << 0x18) | SYSCFG_ITLINE5_SR_EXTI0)) /*!< External Interrupt 0 */ #define HAL_ITLINE_EXTI1 ((uint32_t) ((HAL_SYSCFG_ITLINE5 << 0x18) | SYSCFG_ITLINE5_SR_EXTI1)) /*!< External Interrupt 1 */ #define HAL_ITLINE_EXTI2 ((uint32_t) ((HAL_SYSCFG_ITLINE6 << 0x18) | SYSCFG_ITLINE6_SR_EXTI2)) /*!< External Interrupt 2 */ #define HAL_ITLINE_EXTI3 ((uint32_t) ((HAL_SYSCFG_ITLINE6 << 0x18) | SYSCFG_ITLINE6_SR_EXTI3)) /*!< External Interrupt 3 */ #define HAL_ITLINE_EXTI4 ((uint32_t) ((HAL_SYSCFG_ITLINE7 << 0x18) | SYSCFG_ITLINE7_SR_EXTI4)) /*!< EXTI4 Interrupt */ #define HAL_ITLINE_EXTI5 ((uint32_t) ((HAL_SYSCFG_ITLINE7 << 0x18) | SYSCFG_ITLINE7_SR_EXTI5)) /*!< EXTI5 Interrupt */ #define HAL_ITLINE_EXTI6 ((uint32_t) ((HAL_SYSCFG_ITLINE7 << 0x18) | SYSCFG_ITLINE7_SR_EXTI6)) /*!< EXTI6 Interrupt */ #define HAL_ITLINE_EXTI7 ((uint32_t) ((HAL_SYSCFG_ITLINE7 << 0x18) | SYSCFG_ITLINE7_SR_EXTI7)) /*!< EXTI7 Interrupt */ #define HAL_ITLINE_EXTI8 ((uint32_t) ((HAL_SYSCFG_ITLINE7 << 0x18) | SYSCFG_ITLINE7_SR_EXTI8)) /*!< EXTI8 Interrupt */ #define HAL_ITLINE_EXTI9 ((uint32_t) ((HAL_SYSCFG_ITLINE7 << 0x18) | SYSCFG_ITLINE7_SR_EXTI9)) /*!< EXTI9 Interrupt */ #define HAL_ITLINE_EXTI10 ((uint32_t) ((HAL_SYSCFG_ITLINE7 << 0x18) | SYSCFG_ITLINE7_SR_EXTI10)) /*!< EXTI10 Interrupt */ #define HAL_ITLINE_EXTI11 ((uint32_t) ((HAL_SYSCFG_ITLINE7 << 0x18) | SYSCFG_ITLINE7_SR_EXTI11)) /*!< EXTI11 Interrupt */ #define HAL_ITLINE_EXTI12 ((uint32_t) ((HAL_SYSCFG_ITLINE7 << 0x18) | SYSCFG_ITLINE7_SR_EXTI12)) /*!< EXTI12 Interrupt */ #define HAL_ITLINE_EXTI13 ((uint32_t) ((HAL_SYSCFG_ITLINE7 << 0x18) | SYSCFG_ITLINE7_SR_EXTI13)) /*!< EXTI13 Interrupt */ #define HAL_ITLINE_EXTI14 ((uint32_t) ((HAL_SYSCFG_ITLINE7 << 0x18) | SYSCFG_ITLINE7_SR_EXTI14)) /*!< EXTI14 Interrupt */ #define HAL_ITLINE_EXTI15 ((uint32_t) ((HAL_SYSCFG_ITLINE7 << 0x18) | SYSCFG_ITLINE7_SR_EXTI15)) /*!< EXTI15 Interrupt */ #define HAL_ITLINE_TSC_EOA ((uint32_t) ((HAL_SYSCFG_ITLINE8 << 0x18) | SYSCFG_ITLINE8_SR_TSC_EOA)) /*!< Touch control EOA Interrupt */ #define HAL_ITLINE_TSC_MCE ((uint32_t) ((HAL_SYSCFG_ITLINE8 << 0x18) | SYSCFG_ITLINE8_SR_TSC_MCE)) /*!< Touch control MCE Interrupt */ #define HAL_ITLINE_DMA1_CH1 ((uint32_t) ((HAL_SYSCFG_ITLINE9 << 0x18) | SYSCFG_ITLINE9_SR_DMA1_CH1)) /*!< DMA1 Channel 1 Interrupt */ #define HAL_ITLINE_DMA1_CH2 ((uint32_t) ((HAL_SYSCFG_ITLINE10 << 0x18) | SYSCFG_ITLINE10_SR_DMA1_CH2)) /*!< DMA1 Channel 2 Interrupt */ #define HAL_ITLINE_DMA1_CH3 ((uint32_t) ((HAL_SYSCFG_ITLINE10 << 0x18) | SYSCFG_ITLINE10_SR_DMA1_CH3)) /*!< DMA1 Channel 3 Interrupt */ #define HAL_ITLINE_DMA2_CH1 ((uint32_t) ((HAL_SYSCFG_ITLINE10 << 0x18) | SYSCFG_ITLINE10_SR_DMA2_CH1)) /*!< DMA2 Channel 1 Interrupt */ #define HAL_ITLINE_DMA2_CH2 ((uint32_t) ((HAL_SYSCFG_ITLINE10 << 0x18) | SYSCFG_ITLINE10_SR_DMA2_CH2)) /*!< DMA2 Channel 2 Interrupt */ #define HAL_ITLINE_DMA1_CH4 ((uint32_t) ((HAL_SYSCFG_ITLINE11 << 0x18) | SYSCFG_ITLINE11_SR_DMA1_CH4)) /*!< DMA1 Channel 4 Interrupt */ #define HAL_ITLINE_DMA1_CH5 ((uint32_t) ((HAL_SYSCFG_ITLINE11 << 0x18) | SYSCFG_ITLINE11_SR_DMA1_CH5)) /*!< DMA1 Channel 5 Interrupt */ #define HAL_ITLINE_DMA1_CH6 ((uint32_t) ((HAL_SYSCFG_ITLINE11 << 0x18) | SYSCFG_ITLINE11_SR_DMA1_CH6)) /*!< DMA1 Channel 6 Interrupt */ #define HAL_ITLINE_DMA1_CH7 ((uint32_t) ((HAL_SYSCFG_ITLINE11 << 0x18) | SYSCFG_ITLINE11_SR_DMA1_CH7)) /*!< DMA1 Channel 7 Interrupt */ #define HAL_ITLINE_DMA2_CH3 ((uint32_t) ((HAL_SYSCFG_ITLINE11 << 0x18) | SYSCFG_ITLINE11_SR_DMA2_CH3)) /*!< DMA2 Channel 3 Interrupt */ #define HAL_ITLINE_DMA2_CH4 ((uint32_t) ((HAL_SYSCFG_ITLINE11 << 0x18) | SYSCFG_ITLINE11_SR_DMA2_CH4)) /*!< DMA2 Channel 4 Interrupt */ #define HAL_ITLINE_DMA2_CH5 ((uint32_t) ((HAL_SYSCFG_ITLINE11 << 0x18) | SYSCFG_ITLINE11_SR_DMA2_CH5)) /*!< DMA2 Channel 5 Interrupt */ #define HAL_ITLINE_ADC ((uint32_t) ((HAL_SYSCFG_ITLINE12 << 0x18) | SYSCFG_ITLINE12_SR_ADC)) /*!< ADC Interrupt */ #define HAL_ITLINE_COMP1 ((uint32_t) ((HAL_SYSCFG_ITLINE12 << 0x18) | SYSCFG_ITLINE12_SR_COMP1)) /*!< COMP1 Interrupt -> exti[21] */ #define HAL_ITLINE_COMP2 ((uint32_t) ((HAL_SYSCFG_ITLINE12 << 0x18) | SYSCFG_ITLINE12_SR_COMP2)) /*!< COMP2 Interrupt -> exti[21] */ #define HAL_ITLINE_TIM1_BRK ((uint32_t) ((HAL_SYSCFG_ITLINE13 << 0x18) | SYSCFG_ITLINE13_SR_TIM1_BRK)) /*!< TIM1 BRK Interrupt */ #define HAL_ITLINE_TIM1_UPD ((uint32_t) ((HAL_SYSCFG_ITLINE13 << 0x18) | SYSCFG_ITLINE13_SR_TIM1_UPD)) /*!< TIM1 UPD Interrupt */ #define HAL_ITLINE_TIM1_TRG ((uint32_t) ((HAL_SYSCFG_ITLINE13 << 0x18) | SYSCFG_ITLINE13_SR_TIM1_TRG)) /*!< TIM1 TRG Interrupt */ #define HAL_ITLINE_TIM1_CCU ((uint32_t) ((HAL_SYSCFG_ITLINE13 << 0x18) | SYSCFG_ITLINE13_SR_TIM1_CCU)) /*!< TIM1 CCU Interrupt */ #define HAL_ITLINE_TIM1_CC ((uint32_t) ((HAL_SYSCFG_ITLINE14 << 0x18) | SYSCFG_ITLINE14_SR_TIM1_CC)) /*!< TIM1 CC Interrupt */ #define HAL_ITLINE_TIM2 ((uint32_t) ((HAL_SYSCFG_ITLINE15 << 0x18) | SYSCFG_ITLINE15_SR_TIM2_GLB)) /*!< TIM2 Interrupt */ #define HAL_ITLINE_TIM3 ((uint32_t) ((HAL_SYSCFG_ITLINE16 << 0x18) | SYSCFG_ITLINE16_SR_TIM3_GLB)) /*!< TIM3 Interrupt */ #define HAL_ITLINE_DAC ((uint32_t) ((HAL_SYSCFG_ITLINE17 << 0x18) | SYSCFG_ITLINE17_SR_DAC)) /*!< DAC Interrupt */ #define HAL_ITLINE_TIM6 ((uint32_t) ((HAL_SYSCFG_ITLINE17 << 0x18) | SYSCFG_ITLINE17_SR_TIM6_GLB)) /*!< TIM6 Interrupt */ #define HAL_ITLINE_TIM7 ((uint32_t) ((HAL_SYSCFG_ITLINE18 << 0x18) | SYSCFG_ITLINE18_SR_TIM7_GLB)) /*!< TIM7 Interrupt */ #define HAL_ITLINE_TIM14 ((uint32_t) ((HAL_SYSCFG_ITLINE19 << 0x18) | SYSCFG_ITLINE19_SR_TIM14_GLB)) /*!< TIM14 Interrupt */ #define HAL_ITLINE_TIM15 ((uint32_t) ((HAL_SYSCFG_ITLINE20 << 0x18) | SYSCFG_ITLINE20_SR_TIM15_GLB)) /*!< TIM15 Interrupt */ #define HAL_ITLINE_TIM16 ((uint32_t) ((HAL_SYSCFG_ITLINE21 << 0x18) | SYSCFG_ITLINE21_SR_TIM16_GLB)) /*!< TIM16 Interrupt */ #define HAL_ITLINE_TIM17 ((uint32_t) ((HAL_SYSCFG_ITLINE22 << 0x18) | SYSCFG_ITLINE22_SR_TIM17_GLB)) /*!< TIM17 Interrupt */ #define HAL_ITLINE_I2C1 ((uint32_t) ((HAL_SYSCFG_ITLINE23 << 0x18) | SYSCFG_ITLINE23_SR_I2C1_GLB)) /*!< I2C1 Interrupt -> exti[23] */ #define HAL_ITLINE_I2C2 ((uint32_t) ((HAL_SYSCFG_ITLINE24 << 0x18) | SYSCFG_ITLINE24_SR_I2C2_GLB)) /*!< I2C2 Interrupt */ #define HAL_ITLINE_SPI1 ((uint32_t) ((HAL_SYSCFG_ITLINE25 << 0x18) | SYSCFG_ITLINE25_SR_SPI1)) /*!< I2C1 Interrupt -> exti[23] */ #define HAL_ITLINE_SPI2 ((uint32_t) ((HAL_SYSCFG_ITLINE26 << 0x18) | SYSCFG_ITLINE26_SR_SPI2)) /*!< SPI1 Interrupt */ #define HAL_ITLINE_USART1 ((uint32_t) ((HAL_SYSCFG_ITLINE27 << 0x18) | SYSCFG_ITLINE27_SR_USART1_GLB)) /*!< USART1 GLB Interrupt -> exti[25] */ #define HAL_ITLINE_USART2 ((uint32_t) ((HAL_SYSCFG_ITLINE28 << 0x18) | SYSCFG_ITLINE28_SR_USART2_GLB)) /*!< USART2 GLB Interrupt -> exti[26] */ #define HAL_ITLINE_USART3 ((uint32_t) ((HAL_SYSCFG_ITLINE29 << 0x18) | SYSCFG_ITLINE29_SR_USART3_GLB)) /*!< USART3 Interrupt .... */ #define HAL_ITLINE_USART4 ((uint32_t) ((HAL_SYSCFG_ITLINE29 << 0x18) | SYSCFG_ITLINE29_SR_USART4_GLB)) /*!< USART4 Interrupt .... */ #define HAL_ITLINE_USART5 ((uint32_t) ((HAL_SYSCFG_ITLINE29 << 0x18) | SYSCFG_ITLINE29_SR_USART5_GLB)) /*!< USART5 Interrupt .... */ #define HAL_ITLINE_USART6 ((uint32_t) ((HAL_SYSCFG_ITLINE29 << 0x18) | SYSCFG_ITLINE29_SR_USART6_GLB)) /*!< USART6 Interrupt .... */ #define HAL_ITLINE_USART7 ((uint32_t) ((HAL_SYSCFG_ITLINE29 << 0x18) | SYSCFG_ITLINE29_SR_USART7_GLB)) /*!< USART7 Interrupt .... */ #define HAL_ITLINE_USART8 ((uint32_t) ((HAL_SYSCFG_ITLINE29 << 0x18) | SYSCFG_ITLINE29_SR_USART8_GLB)) /*!< USART8 Interrupt .... */ #define HAL_ITLINE_CAN ((uint32_t) ((HAL_SYSCFG_ITLINE30 << 0x18) | SYSCFG_ITLINE30_SR_CAN)) /*!< CAN Interrupt */ #define HAL_ITLINE_CEC ((uint32_t) ((HAL_SYSCFG_ITLINE30 << 0x18) | SYSCFG_ITLINE30_SR_CEC)) /*!< CEC Interrupt -> exti[27] */ /** * @} */ #endif /* STM32F091xC || STM32F098xx */ /** * @} */ /* Exported macros -----------------------------------------------------------*/ /** @defgroup HAL_Exported_Macros HAL Exported Macros * @{ */ /** @defgroup HAL_Freeze_Unfreeze_Peripherals HAL Freeze Unfreeze Peripherals * @brief Freeze/Unfreeze Peripherals in Debug mode * @{ */ #if defined(DBGMCU_APB1_FZ_DBG_CAN_STOP) #define __HAL_FREEZE_CAN_DBGMCU() (DBGMCU->APB1FZ |= (DBGMCU_APB1_FZ_DBG_CAN_STOP)) #define __HAL_UNFREEZE_CAN_DBGMCU() (DBGMCU->APB1FZ &= ~(DBGMCU_APB1_FZ_DBG_CAN_STOP)) #endif /* DBGMCU_APB1_FZ_DBG_CAN_STOP */ #if defined(DBGMCU_APB1_FZ_DBG_RTC_STOP) #define __HAL_DBGMCU_FREEZE_RTC() (DBGMCU->APB1FZ |= (DBGMCU_APB1_FZ_DBG_RTC_STOP)) #define __HAL_DBGMCU_UNFREEZE_RTC() (DBGMCU->APB1FZ &= ~(DBGMCU_APB1_FZ_DBG_RTC_STOP)) #endif /* DBGMCU_APB1_FZ_DBG_RTC_STOP */ #if defined(DBGMCU_APB1_FZ_DBG_I2C1_SMBUS_TIMEOUT) #define __HAL_DBGMCU_FREEZE_I2C1_TIMEOUT() (DBGMCU->APB1FZ |= (DBGMCU_APB1_FZ_DBG_I2C1_SMBUS_TIMEOUT)) #define __HAL_DBGMCU_UNFREEZE_I2C1_TIMEOUT() (DBGMCU->APB1FZ &= ~(DBGMCU_APB1_FZ_DBG_I2C1_SMBUS_TIMEOUT)) #endif /* DBGMCU_APB1_FZ_DBG_I2C1_SMBUS_TIMEOUT */ #if defined(DBGMCU_APB1_FZ_DBG_IWDG_STOP) #define __HAL_DBGMCU_FREEZE_IWDG() (DBGMCU->APB1FZ |= (DBGMCU_APB1_FZ_DBG_IWDG_STOP)) #define __HAL_DBGMCU_UNFREEZE_IWDG() (DBGMCU->APB1FZ &= ~(DBGMCU_APB1_FZ_DBG_IWDG_STOP)) #endif /* DBGMCU_APB1_FZ_DBG_IWDG_STOP */ #if defined(DBGMCU_APB1_FZ_DBG_WWDG_STOP) #define __HAL_DBGMCU_FREEZE_WWDG() (DBGMCU->APB1FZ |= (DBGMCU_APB1_FZ_DBG_WWDG_STOP)) #define __HAL_DBGMCU_UNFREEZE_WWDG() (DBGMCU->APB1FZ &= ~(DBGMCU_APB1_FZ_DBG_WWDG_STOP)) #endif /* DBGMCU_APB1_FZ_DBG_WWDG_STOP */ #if defined(DBGMCU_APB1_FZ_DBG_TIM2_STOP) #define __HAL_DBGMCU_FREEZE_TIM2() (DBGMCU->APB1FZ |= (DBGMCU_APB1_FZ_DBG_TIM2_STOP)) #define __HAL_DBGMCU_UNFREEZE_TIM2() (DBGMCU->APB1FZ &= ~(DBGMCU_APB1_FZ_DBG_TIM2_STOP)) #endif /* DBGMCU_APB1_FZ_DBG_TIM2_STOP */ #if defined(DBGMCU_APB1_FZ_DBG_TIM3_STOP) #define __HAL_DBGMCU_FREEZE_TIM3() (DBGMCU->APB1FZ |= (DBGMCU_APB1_FZ_DBG_TIM3_STOP)) #define __HAL_DBGMCU_UNFREEZE_TIM3() (DBGMCU->APB1FZ &= ~(DBGMCU_APB1_FZ_DBG_TIM3_STOP)) #endif /* DBGMCU_APB1_FZ_DBG_TIM3_STOP */ #if defined(DBGMCU_APB1_FZ_DBG_TIM6_STOP) #define __HAL_DBGMCU_FREEZE_TIM6() (DBGMCU->APB1FZ |= (DBGMCU_APB1_FZ_DBG_TIM6_STOP)) #define __HAL_DBGMCU_UNFREEZE_TIM6() (DBGMCU->APB1FZ &= ~(DBGMCU_APB1_FZ_DBG_TIM6_STOP)) #endif /* DBGMCU_APB1_FZ_DBG_TIM6_STOP */ #if defined(DBGMCU_APB1_FZ_DBG_TIM7_STOP) #define __HAL_DBGMCU_FREEZE_TIM7() (DBGMCU->APB1FZ |= (DBGMCU_APB1_FZ_DBG_TIM7_STOP)) #define __HAL_DBGMCU_UNFREEZE_TIM7() (DBGMCU->APB1FZ &= ~(DBGMCU_APB1_FZ_DBG_TIM7_STOP)) #endif /* DBGMCU_APB1_FZ_DBG_TIM7_STOP */ #if defined(DBGMCU_APB1_FZ_DBG_TIM14_STOP) #define __HAL_DBGMCU_FREEZE_TIM14() (DBGMCU->APB1FZ |= (DBGMCU_APB1_FZ_DBG_TIM14_STOP)) #define __HAL_DBGMCU_UNFREEZE_TIM14() (DBGMCU->APB1FZ &= ~(DBGMCU_APB1_FZ_DBG_TIM14_STOP)) #endif /* DBGMCU_APB1_FZ_DBG_TIM14_STOP */ #if defined(DBGMCU_APB2_FZ_DBG_TIM1_STOP) #define __HAL_DBGMCU_FREEZE_TIM1() (DBGMCU->APB2FZ |= (DBGMCU_APB2_FZ_DBG_TIM1_STOP)) #define __HAL_DBGMCU_UNFREEZE_TIM1() (DBGMCU->APB2FZ &= ~(DBGMCU_APB2_FZ_DBG_TIM1_STOP)) #endif /* DBGMCU_APB2_FZ_DBG_TIM1_STOP */ #if defined(DBGMCU_APB2_FZ_DBG_TIM15_STOP) #define __HAL_DBGMCU_FREEZE_TIM15() (DBGMCU->APB2FZ |= (DBGMCU_APB2_FZ_DBG_TIM15_STOP)) #define __HAL_DBGMCU_UNFREEZE_TIM15() (DBGMCU->APB2FZ &= ~(DBGMCU_APB2_FZ_DBG_TIM15_STOP)) #endif /* DBGMCU_APB2_FZ_DBG_TIM15_STOP */ #if defined(DBGMCU_APB2_FZ_DBG_TIM16_STOP) #define __HAL_DBGMCU_FREEZE_TIM16() (DBGMCU->APB2FZ |= (DBGMCU_APB2_FZ_DBG_TIM16_STOP)) #define __HAL_DBGMCU_UNFREEZE_TIM16() (DBGMCU->APB2FZ &= ~(DBGMCU_APB2_FZ_DBG_TIM16_STOP)) #endif /* DBGMCU_APB2_FZ_DBG_TIM16_STOP */ #if defined(DBGMCU_APB2_FZ_DBG_TIM17_STOP) #define __HAL_DBGMCU_FREEZE_TIM17() (DBGMCU->APB2FZ |= (DBGMCU_APB2_FZ_DBG_TIM17_STOP)) #define __HAL_DBGMCU_UNFREEZE_TIM17() (DBGMCU->APB2FZ &= ~(DBGMCU_APB2_FZ_DBG_TIM17_STOP)) #endif /* DBGMCU_APB2_FZ_DBG_TIM17_STOP */ /** * @} */ /** @defgroup Memory_Mapping_Selection Memory Mapping Selection * @{ */ #if defined(SYSCFG_CFGR1_MEM_MODE) /** @brief Main Flash memory mapped at 0x00000000 */ #define __HAL_SYSCFG_REMAPMEMORY_FLASH() (SYSCFG->CFGR1 &= ~(SYSCFG_CFGR1_MEM_MODE)) #endif /* SYSCFG_CFGR1_MEM_MODE */ #if defined(SYSCFG_CFGR1_MEM_MODE_0) /** @brief System Flash memory mapped at 0x00000000 */ #define __HAL_SYSCFG_REMAPMEMORY_SYSTEMFLASH() do {SYSCFG->CFGR1 &= ~(SYSCFG_CFGR1_MEM_MODE); \ SYSCFG->CFGR1 |= SYSCFG_CFGR1_MEM_MODE_0; \ }while(0) #endif /* SYSCFG_CFGR1_MEM_MODE_0 */ #if defined(SYSCFG_CFGR1_MEM_MODE_0) && defined(SYSCFG_CFGR1_MEM_MODE_1) /** @brief Embedded SRAM mapped at 0x00000000 */ #define __HAL_SYSCFG_REMAPMEMORY_SRAM() do {SYSCFG->CFGR1 &= ~(SYSCFG_CFGR1_MEM_MODE); \ SYSCFG->CFGR1 |= (SYSCFG_CFGR1_MEM_MODE_0 | SYSCFG_CFGR1_MEM_MODE_1); \ }while(0) #endif /* SYSCFG_CFGR1_MEM_MODE_0 && SYSCFG_CFGR1_MEM_MODE_1 */ /** * @} */ #if defined(SYSCFG_CFGR1_PA11_PA12_RMP) /** @defgroup HAL_Pin_remap HAL Pin remap * @brief Pin remapping enable/disable macros * @param __PIN_REMAP__: This parameter can be a value of @ref HAL_Pin_remapping * @{ */ #define __HAL_REMAP_PIN_ENABLE(__PIN_REMAP__) do {assert_param(IS_HAL_REMAP_PIN((__PIN_REMAP__))); \ SYSCFG->CFGR1 |= (__PIN_REMAP__); \ }while(0) #define __HAL_REMAP_PIN_DISABLE(__PIN_REMAP__) do {assert_param(IS_HAL_REMAP_PIN((__PIN_REMAP__))); \ SYSCFG->CFGR1 &= ~(__PIN_REMAP__); \ }while(0) /** * @} */ #endif /* SYSCFG_CFGR1_PA11_PA12_RMP */ /** @brief Fast-mode Plus driving capability enable/disable macros * @param __FASTMODEPLUS__: This parameter can be a value of @ref SYSCFG_FastModePlus_GPIO values. * That you can find above these macros. */ #define __HAL_SYSCFG_FASTMODEPLUS_ENABLE(__FASTMODEPLUS__) do {assert_param(IS_SYSCFG_FASTMODEPLUS((__FASTMODEPLUS__)));\ SET_BIT(SYSCFG->CFGR1, (__FASTMODEPLUS__));\ }while(0) #define __HAL_SYSCFG_FASTMODEPLUS_DISABLE(__FASTMODEPLUS__) do {assert_param(IS_SYSCFG_FASTMODEPLUS((__FASTMODEPLUS__)));\ CLEAR_BIT(SYSCFG->CFGR1, (__FASTMODEPLUS__));\ }while(0) #if defined(SYSCFG_CFGR2_LOCKUP_LOCK) /** @defgroup Cortex_Lockup_Enable Cortex Lockup Enable * @{ */ /** @brief SYSCFG Break Lockup lock * Enables and locks the connection of Cortex-M0 LOCKUP (Hardfault) output to TIM1/15/16/17 Break input * @note The selected configuration is locked and can be unlocked by system reset */ #define __HAL_SYSCFG_BREAK_LOCKUP_LOCK() do {SYSCFG->CFGR2 &= ~(SYSCFG_CFGR2_LOCKUP_LOCK); \ SYSCFG->CFGR2 |= SYSCFG_CFGR2_LOCKUP_LOCK; \ }while(0) /** * @} */ #endif /* SYSCFG_CFGR2_LOCKUP_LOCK */ #if defined(SYSCFG_CFGR2_PVD_LOCK) /** @defgroup PVD_Lock_Enable PVD Lock * @{ */ /** @brief SYSCFG Break PVD lock * Enables and locks the PVD connection with Timer1/8/15/16/17 Break Input, , as well as the PVDE and PLS[2:0] in the PWR_CR register * @note The selected configuration is locked and can be unlocked by system reset */ #define __HAL_SYSCFG_BREAK_PVD_LOCK() do {SYSCFG->CFGR2 &= ~(SYSCFG_CFGR2_PVD_LOCK); \ SYSCFG->CFGR2 |= SYSCFG_CFGR2_PVD_LOCK; \ }while(0) /** * @} */ #endif /* SYSCFG_CFGR2_PVD_LOCK */ #if defined(SYSCFG_CFGR2_SRAM_PARITY_LOCK) /** @defgroup SRAM_Parity_Lock SRAM Parity Lock * @{ */ /** @brief SYSCFG Break SRAM PARITY lock * Enables and locks the SRAM_PARITY error signal with Break Input of TIMER1/8/15/16/17 * @note The selected configuration is locked and can be unlocked by system reset */ #define __HAL_SYSCFG_BREAK_SRAMPARITY_LOCK() do {SYSCFG->CFGR2 &= ~(SYSCFG_CFGR2_SRAM_PARITY_LOCK); \ SYSCFG->CFGR2 |= SYSCFG_CFGR2_SRAM_PARITY_LOCK; \ }while(0) /** * @} */ #endif /* SYSCFG_CFGR2_SRAM_PARITY_LOCK */ #if defined(SYSCFG_CFGR2_SRAM_PEF) /** @defgroup HAL_SYSCFG_Parity_check_on_RAM HAL SYSCFG Parity check on RAM * @brief Parity check on RAM disable macro * @note Disabling the parity check on RAM locks the configuration bit. * To re-enable the parity check on RAM perform a system reset. * @{ */ #define __HAL_SYSCFG_RAM_PARITYCHECK_DISABLE() (SYSCFG->CFGR2 |= SYSCFG_CFGR2_SRAM_PEF) /** * @} */ #endif /* SYSCFG_CFGR2_SRAM_PEF */ #if defined(STM32F091xC) || defined (STM32F098xx) /** @defgroup HAL_ISR_wrapper_check HAL ISR wrapper check * @brief ISR wrapper check * @note This feature is applicable on STM32F09x * @note Allow to determine interrupt source per line. * @{ */ #define __HAL_GET_PENDING_IT(__SOURCE__) (SYSCFG->IT_LINE_SR[((__SOURCE__) >> 0x18)] & ((__SOURCE__) & 0x00FFFFFF)) /** * @} */ #endif /* (STM32F091xC) || defined (STM32F098xx)*/ #if defined(STM32F091xC) || defined (STM32F098xx) /** @defgroup HAL_SYSCFG_IRDA_modulation_envelope_selection HAL SYSCFG IRDA modulation envelope selection * @brief selection of the modulation envelope signal macro, using bits [7:6] of SYS_CTRL(CFGR1) register * @note This feature is applicable on STM32F09x * @param __SOURCE__: This parameter can be a value of @ref HAL_IRDA_ENV_SEL * @{ */ #define __HAL_SYSCFG_IRDA_ENV_SELECTION(__SOURCE__) do {assert_param(IS_HAL_SYSCFG_IRDA_ENV_SEL((__SOURCE__))); \ SYSCFG->CFGR1 &= ~(SYSCFG_CFGR1_IRDA_ENV_SEL); \ SYSCFG->CFGR1 |= (__SOURCE__); \ }while(0) #define __HAL_SYSCFG_GET_IRDA_ENV_SELECTION() ((SYSCFG->CFGR1) & 0x000000C0) /** * @} */ #endif /* (STM32F091xC) || defined (STM32F098xx)*/ /** * @} */ /* Exported functions --------------------------------------------------------*/ /** @addtogroup HAL_Exported_Functions * @{ */ /** @addtogroup HAL_Exported_Functions_Group1 * @{ */ /* Initialization and de-initialization functions ******************************/ HAL_StatusTypeDef HAL_Init(void); HAL_StatusTypeDef HAL_DeInit(void); void HAL_MspInit(void); void HAL_MspDeInit(void); HAL_StatusTypeDef HAL_InitTick (uint32_t TickPriority); /** * @} */ /** @addtogroup HAL_Exported_Functions_Group2 * @{ */ /* Peripheral Control functions ************************************************/ void HAL_IncTick(void); void HAL_Delay(__IO uint32_t Delay); uint32_t HAL_GetTick(void); void HAL_SuspendTick(void); void HAL_ResumeTick(void); uint32_t HAL_GetHalVersion(void); uint32_t HAL_GetREVID(void); uint32_t HAL_GetDEVID(void); void HAL_DBGMCU_EnableDBGStopMode(void); void HAL_DBGMCU_DisableDBGStopMode(void); void HAL_DBGMCU_EnableDBGStandbyMode(void); void HAL_DBGMCU_DisableDBGStandbyMode(void); /** * @} */ /** * @} */ /** * @} */ /** * @} */ #ifdef __cplusplus } #endif #endif /* __STM32F0xx_HAL_H */ /************************ (C) COPYRIGHT STMicroelectronics *****END OF FILE****/ ================================================ FILE: Zelig/mbed/TARGET_NUCLEO_F091RC/stm32f0xx_hal_adc.h ================================================ /** ****************************************************************************** * @file stm32f0xx_hal_adc.h * @author MCD Application Team * @version V1.3.0 * @date 26-June-2015 * @brief Header file containing functions prototypes of ADC HAL library. ****************************************************************************** * @attention * *

© COPYRIGHT(c) 2015 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. * ****************************************************************************** */ /* Define to prevent recursive inclusion -------------------------------------*/ #ifndef __STM32F0xx_HAL_ADC_H #define __STM32F0xx_HAL_ADC_H #ifdef __cplusplus extern "C" { #endif /* Includes ------------------------------------------------------------------*/ #include "stm32f0xx_hal_def.h" /** @addtogroup STM32F0xx_HAL_Driver * @{ */ /** @addtogroup ADC * @{ */ /* Exported types ------------------------------------------------------------*/ /** @defgroup ADC_Exported_Types ADC Exported Types * @{ */ /** * @brief Structure definition of ADC initialization and regular group * @note The setting of these parameters with function HAL_ADC_Init() is conditioned to ADC state. * ADC state can be either: * - For all parameters: ADC disabled (this is the only possible ADC state to modify parameter 'ClockPrescaler') * - For all parameters except 'ClockPrescaler' and 'resolution': ADC enabled without conversion on going on regular group. * If ADC is not in the appropriate state to modify some parameters, these parameters setting is bypassed * without error reporting (as it can be the expected behaviour in case of intended action to update another parameter (which fulfills the ADC state condition) on the fly). */ typedef struct { uint32_t ClockPrescaler; /*!< Select ADC clock source (synchronous clock derived from APB clock or asynchronous clock derived from ADC dedicated HSI RC oscillator 14MHz) and clock prescaler. This parameter can be a value of @ref ADC_ClockPrescaler Note: In case of usage of the ADC dedicated HSI RC oscillator, it must be preliminarily enabled at RCC top level. Note: This parameter can be modified only if the ADC is disabled */ uint32_t Resolution; /*!< Configures the ADC resolution. This parameter can be a value of @ref ADC_Resolution */ uint32_t DataAlign; /*!< Specifies whether the ADC data alignment is left or right. This parameter can be a value of @ref ADC_Data_align */ uint32_t ScanConvMode; /*!< Configures the sequencer of regular group. This parameter can be associated to parameter 'DiscontinuousConvMode' to have main sequence subdivided in successive parts. Sequencer is automatically enabled if several channels are set (sequencer cannot be disabled, as it can be the case on other STM32 devices): If only 1 channel is set: Conversion is performed in single mode. If several channels are set: Conversions are performed in sequence mode (ranks defined by each channel number: channel 0 fixed on rank 0, channel 1 fixed on rank1, ...). Scan direction can be set to forward (from channel 0 to channel 18) or backward (from channel 18 to channel 0). This parameter can be a value of @ref ADC_Scan_mode */ uint32_t EOCSelection; /*!< Specifies what EOC (End Of Conversion) flag is used for conversion by polling and interruption: end of conversion of each rank or complete sequence. This parameter can be a value of @ref ADC_EOCSelection. */ uint32_t LowPowerAutoWait; /*!< Selects the dynamic low power Auto Delay: new conversion start only when the previous conversion (for regular group) has been treated by user software, using function HAL_ADC_GetValue(). This feature automatically adapts the ADC conversions trigs to the speed of the system that reads the data. Moreover, this avoids risk of overrun for low frequency applications. This parameter can be set to ENABLE or DISABLE. Note: Do not use with interruption or DMA (HAL_ADC_Start_IT(), HAL_ADC_Start_DMA()) since they have to clear immediately the EOC flag to free the IRQ vector sequencer. Do use with polling: 1. Start conversion with HAL_ADC_Start(), 2. Later on, when conversion data is needed: use HAL_ADC_PollForConversion() to ensure that conversion is completed and use HAL_ADC_GetValue() to retrieve conversion result and trig another conversion. */ uint32_t LowPowerAutoPowerOff; /*!< Selects the auto-off mode: the ADC automatically powers-off after a conversion and automatically wakes-up when a new conversion is triggered (with startup time between trigger and start of sampling). This feature can be combined with automatic wait mode (parameter 'LowPowerAutoWait'). This parameter can be set to ENABLE or DISABLE. Note: If enabled, this feature also turns off the ADC dedicated 14 MHz RC oscillator (HSI14) */ uint32_t ContinuousConvMode; /*!< Specifies whether the conversion is performed in single mode (one conversion) or continuous mode for regular group, after the selected trigger occurred (software start or external trigger). This parameter can be set to ENABLE or DISABLE. */ uint32_t DiscontinuousConvMode; /*!< Specifies whether the conversions sequence of regular group is performed in Complete-sequence/Discontinuous-sequence (main sequence subdivided in successive parts). Discontinuous mode is used only if sequencer is enabled (parameter 'ScanConvMode'). If sequencer is disabled, this parameter is discarded. Discontinuous mode can be enabled only if continuous mode is disabled. If continuous mode is enabled, this parameter setting is discarded. This parameter can be set to ENABLE or DISABLE Note: Number of discontinuous ranks increment is fixed to one-by-one. */ uint32_t ExternalTrigConv; /*!< Selects the external event used to trigger the conversion start of regular group. If set to ADC_SOFTWARE_START, external triggers are disabled. This parameter can be a value of @ref ADC_External_trigger_source_Regular */ uint32_t ExternalTrigConvEdge; /*!< Selects the external trigger edge of regular group. If trigger is set to ADC_SOFTWARE_START, this parameter is discarded. This parameter can be a value of @ref ADC_External_trigger_edge_Regular */ uint32_t DMAContinuousRequests; /*!< Specifies whether the DMA requests are performed in one shot mode (DMA transfer stop when number of conversions is reached) or in Continuous mode (DMA transfer unlimited, whatever number of conversions). Note: In continuous mode, DMA must be configured in circular mode. Otherwise an overrun will be triggered when DMA buffer maximum pointer is reached. This parameter can be set to ENABLE or DISABLE. */ uint32_t Overrun; /*!< Select the behaviour in case of overrun: data preserved or overwritten This parameter has an effect on regular group only, including in DMA mode. This parameter can be a value of @ref ADC_Overrun */ uint32_t SamplingTimeCommon; /*!< Sampling time value to be set for the selected channel. Unit: ADC clock cycles Conversion time is the addition of sampling time and processing time (12.5 ADC clock cycles at ADC resolution 12 bits, 10.5 cycles at 10 bits, 8.5 cycles at 8 bits, 6.5 cycles at 6 bits). Note: On STM32F0 devices, the sampling time setting is common to all channels. On some other STM32 devices, this parameter in channel wise and is located into ADC channel initialization structure. This parameter can be a value of @ref ADC_sampling_times Note: In case of usage of internal measurement channels (VrefInt/Vbat/TempSensor), sampling time constraints must be respected (sampling time can be adjusted in function of ADC clock frequency and sampling time setting) Refer to device datasheet for timings values, parameters TS_vrefint, TS_vbat, TS_temp (values rough order: 5us to 17us). */ }ADC_InitTypeDef; /** * @brief Structure definition of ADC channel for regular group * @note The setting of these parameters with function HAL_ADC_ConfigChannel() is conditioned to ADC state. * ADC state can be either: * - For all parameters: ADC disabled or enabled without conversion on going on regular group. * If ADC is not in the appropriate state to modify some parameters, these parameters setting is bypassed * without error reporting (as it can be the expected behaviour in case of intended action to update another parameter (which fulfills the ADC state condition) on the fly). */ typedef struct { uint32_t Channel; /*!< Specifies the channel to configure into ADC regular group. This parameter can be a value of @ref ADC_channels Note: Depending on devices, some channels may not be available on package pins. Refer to device datasheet for channels availability. */ uint32_t Rank; /*!< Add or remove the channel from ADC regular group sequencer. On STM32F0 devices, number of ranks in the sequence is defined by number of channels enabled, rank of each channel is defined by channel number (channel 0 fixed on rank 0, channel 1 fixed on rank1, ...).. Despite the channel rank is fixed, this parameter allow an additional possibility: to remove the selected rank (selected channel) from sequencer. This parameter can be a value of @ref ADC_rank */ uint32_t SamplingTime; /*!< Sampling time value to be set for the selected channel. Unit: ADC clock cycles Conversion time is the addition of sampling time and processing time (12.5 ADC clock cycles at ADC resolution 12 bits, 10.5 cycles at 10 bits, 8.5 cycles at 8 bits, 6.5 cycles at 6 bits). This parameter can be a value of @ref ADC_sampling_times Caution: this setting impacts the entire regular group. Therefore, call of HAL_ADC_ConfigChannel() to configure a channel can impact the configuration of other channels previously set. Caution: Obsolete parameter. Use parameter "SamplingTimeCommon" in ADC initialization structure. If parameter "SamplingTimeCommon" is set to a valid sampling time, parameter "SamplingTime" is discarded. Note: In case of usage of internal measurement channels (VrefInt/Vbat/TempSensor), sampling time constraints must be respected (sampling time can be adjusted in function of ADC clock frequency and sampling time setting) Refer to device datasheet for timings values, parameters TS_vrefint, TS_vbat, TS_temp (values rough order: 5us to 17us). */ }ADC_ChannelConfTypeDef; /** * @brief Structure definition of ADC analog watchdog * @note The setting of these parameters with function HAL_ADC_AnalogWDGConfig() is conditioned to ADC state. * ADC state can be either: ADC disabled or ADC enabled without conversion on going on regular group. */ typedef struct { uint32_t WatchdogMode; /*!< Configures the ADC analog watchdog mode: single/all/none channels. This parameter can be a value of @ref ADC_analog_watchdog_mode. */ uint32_t Channel; /*!< Selects which ADC channel to monitor by analog watchdog. This parameter has an effect only if parameter 'WatchdogMode' is configured on single channel. Only 1 channel can be monitored. This parameter can be a value of @ref ADC_channels. */ uint32_t ITMode; /*!< Specifies whether the analog watchdog is configured in interrupt or polling mode. This parameter can be set to ENABLE or DISABLE */ uint32_t HighThreshold; /*!< Configures the ADC analog watchdog High threshold value. Depending of ADC resolution selected (12, 10, 8 or 6 bits), this parameter must be a number between Min_Data = 0x000 and Max_Data = 0xFFF, 0x3FF, 0xFF or 0x3F respectively. */ uint32_t LowThreshold; /*!< Configures the ADC analog watchdog High threshold value. Depending of ADC resolution selected (12, 10, 8 or 6 bits), this parameter must be a number between Min_Data = 0x000 and Max_Data = 0xFFF, 0x3FF, 0xFF or 0x3F respectively. */ }ADC_AnalogWDGConfTypeDef; /** * @brief HAL ADC state machine: ADC states definition (bitfields) */ /* States of ADC global scope */ #define HAL_ADC_STATE_RESET ((uint32_t)0x00000000) /*!< ADC not yet initialized or disabled */ #define HAL_ADC_STATE_READY ((uint32_t)0x00000001) /*!< ADC peripheral ready for use */ #define HAL_ADC_STATE_BUSY_INTERNAL ((uint32_t)0x00000002) /*!< ADC is busy to internal process (initialization, calibration) */ #define HAL_ADC_STATE_TIMEOUT ((uint32_t)0x00000004) /*!< TimeOut occurrence */ /* States of ADC errors */ #define HAL_ADC_STATE_ERROR_INTERNAL ((uint32_t)0x00000010) /*!< Internal error occurrence */ #define HAL_ADC_STATE_ERROR_CONFIG ((uint32_t)0x00000020) /*!< Configuration error occurrence */ #define HAL_ADC_STATE_ERROR_DMA ((uint32_t)0x00000040) /*!< DMA error occurrence */ /* States of ADC group regular */ #define HAL_ADC_STATE_REG_BUSY ((uint32_t)0x00000100) /*!< A conversion on group regular is ongoing or can occur (either by continuous mode, external trigger, low power auto power-on, multimode ADC master control) */ #define HAL_ADC_STATE_REG_EOC ((uint32_t)0x00000200) /*!< Conversion data available on group regular */ #define HAL_ADC_STATE_REG_OVR ((uint32_t)0x00000400) /*!< Overrun occurrence */ #define HAL_ADC_STATE_REG_EOSMP ((uint32_t)0x00000800) /*!< Not available on STM32F0 device: End Of Sampling flag raised */ /* States of ADC group injected */ #define HAL_ADC_STATE_INJ_BUSY ((uint32_t)0x00001000) /*!< Not available on STM32F0 device: A conversion on group injected is ongoing or can occur (either by auto-injection mode, external trigger, low power auto power-on, multimode ADC master control) */ #define HAL_ADC_STATE_INJ_EOC ((uint32_t)0x00002000) /*!< Not available on STM32F0 device: Conversion data available on group injected */ #define HAL_ADC_STATE_INJ_JQOVF ((uint32_t)0x00004000) /*!< Not available on STM32F0 device: Not available on STM32F0 device: Injected queue overflow occurrence */ /* States of ADC analog watchdogs */ #define HAL_ADC_STATE_AWD1 ((uint32_t)0x00010000) /*!< Out-of-window occurrence of analog watchdog 1 */ #define HAL_ADC_STATE_AWD2 ((uint32_t)0x00020000) /*!< Not available on STM32F0 device: Out-of-window occurrence of analog watchdog 2 */ #define HAL_ADC_STATE_AWD3 ((uint32_t)0x00040000) /*!< Not available on STM32F0 device: Out-of-window occurrence of analog watchdog 3 */ /* States of ADC multi-mode */ #define HAL_ADC_STATE_MULTIMODE_SLAVE ((uint32_t)0x00100000) /*!< Not available on STM32F0 device: ADC in multimode slave state, controlled by another ADC master ( */ /** * @brief ADC handle Structure definition */ typedef struct { ADC_TypeDef *Instance; /*!< Register base address */ ADC_InitTypeDef Init; /*!< ADC required parameters */ DMA_HandleTypeDef *DMA_Handle; /*!< Pointer DMA Handler */ HAL_LockTypeDef Lock; /*!< ADC locking object */ __IO uint32_t State; /*!< ADC communication state (bitmap of ADC states) */ __IO uint32_t ErrorCode; /*!< ADC Error code */ }ADC_HandleTypeDef; /** * @} */ /* Exported constants --------------------------------------------------------*/ /** @defgroup ADC_Exported_Constants ADC Exported Constants * @{ */ /** @defgroup ADC_Error_Code ADC Error Code * @{ */ #define HAL_ADC_ERROR_NONE ((uint32_t)0x00) /*!< No error */ #define HAL_ADC_ERROR_INTERNAL ((uint32_t)0x01) /*!< ADC IP internal error: if problem of clocking, enable/disable, erroneous state */ #define HAL_ADC_ERROR_OVR ((uint32_t)0x02) /*!< Overrun error */ #define HAL_ADC_ERROR_DMA ((uint32_t)0x04) /*!< DMA transfer error */ /** * @} */ /** @defgroup ADC_ClockPrescaler ADC ClockPrescaler * @{ */ #define ADC_CLOCK_ASYNC_DIV1 ((uint32_t)0x00000000) /*!< ADC asynchronous clock derived from ADC dedicated HSI */ #define ADC_CLOCK_SYNC_PCLK_DIV2 ((uint32_t)ADC_CFGR2_CKMODE_0) /*!< ADC synchronous clock derived from AHB clock divided by a prescaler of 2 */ #define ADC_CLOCK_SYNC_PCLK_DIV4 ((uint32_t)ADC_CFGR2_CKMODE_1) /*!< ADC synchronous clock derived from AHB clock divided by a prescaler of 4 */ /** * @} */ /** @defgroup ADC_Resolution ADC Resolution * @{ */ #define ADC_RESOLUTION_12B ((uint32_t)0x00000000) /*!< ADC 12-bit resolution */ #define ADC_RESOLUTION_10B ((uint32_t)ADC_CFGR1_RES_0) /*!< ADC 10-bit resolution */ #define ADC_RESOLUTION_8B ((uint32_t)ADC_CFGR1_RES_1) /*!< ADC 8-bit resolution */ #define ADC_RESOLUTION_6B ((uint32_t)ADC_CFGR1_RES) /*!< ADC 6-bit resolution */ /** * @} */ /** @defgroup ADC_Data_align ADC Data_align * @{ */ #define ADC_DATAALIGN_RIGHT ((uint32_t)0x00000000) #define ADC_DATAALIGN_LEFT ((uint32_t)ADC_CFGR1_ALIGN) /** * @} */ /** @defgroup ADC_Scan_mode ADC Scan mode * @{ */ /* Note: Scan mode values must be compatible with other STM32 devices having */ /* a configurable sequencer. */ /* Scan direction setting values are defined by taking in account */ /* already defined values for other STM32 devices: */ /* ADC_SCAN_DISABLE ((uint32_t)0x00000000) */ /* ADC_SCAN_ENABLE ((uint32_t)0x00000001) */ /* Scan direction forward is considered as default setting equivalent */ /* to scan enable. */ /* Scan direction backward is considered as additional setting. */ /* In case of migration from another STM32 device, the user will be */ /* warned of change of setting choices with assert check. */ #define ADC_SCAN_DIRECTION_FORWARD ((uint32_t)0x00000001) /*!< Scan direction forward: from channel 0 to channel 18 */ #define ADC_SCAN_DIRECTION_BACKWARD ((uint32_t)0x00000002) /*!< Scan direction backward: from channel 18 to channel 0 */ #define ADC_SCAN_ENABLE ADC_SCAN_DIRECTION_FORWARD /* For compatibility with other STM32 devices */ /** * @} */ /** @defgroup ADC_External_trigger_edge_Regular ADC External trigger edge Regular * @{ */ #define ADC_EXTERNALTRIGCONVEDGE_NONE ((uint32_t)0x00000000) #define ADC_EXTERNALTRIGCONVEDGE_RISING ((uint32_t)ADC_CFGR1_EXTEN_0) #define ADC_EXTERNALTRIGCONVEDGE_FALLING ((uint32_t)ADC_CFGR1_EXTEN_1) #define ADC_EXTERNALTRIGCONVEDGE_RISINGFALLING ((uint32_t)ADC_CFGR1_EXTEN) /** * @} */ /** @defgroup ADC_EOCSelection ADC EOCSelection * @{ */ #define ADC_EOC_SINGLE_CONV ((uint32_t) ADC_ISR_EOC) #define ADC_EOC_SEQ_CONV ((uint32_t) ADC_ISR_EOS) #define ADC_EOC_SINGLE_SEQ_CONV ((uint32_t)(ADC_ISR_EOC | ADC_ISR_EOS)) /*!< reserved for future use */ /** * @} */ /** @defgroup ADC_Overrun ADC Overrun * @{ */ #define ADC_OVR_DATA_OVERWRITTEN ((uint32_t)0x00000000) #define ADC_OVR_DATA_PRESERVED ((uint32_t)0x00000001) /** * @} */ /** @defgroup ADC_rank ADC rank * @{ */ #define ADC_RANK_CHANNEL_NUMBER ((uint32_t)0x00001000) /*!< Enable the rank of the selected channels. Number of ranks in the sequence is defined by number of channels enabled, rank of each channel is defined by channel number (channel 0 fixed on rank 0, channel 1 fixed on rank1, ...) */ #define ADC_RANK_NONE ((uint32_t)0x00001001) /*!< Disable the selected rank (selected channel) from sequencer */ /** * @} */ /** @defgroup ADC_sampling_times ADC sampling times * @{ */ /* Note: Parameter "ADC_SAMPLETIME_1CYCLE_5" defined with a dummy bit */ /* to distinguish this parameter versus reset value 0x00000000, */ /* in the context of management of parameters "SamplingTimeCommon" */ /* and "SamplingTime" (obsolete)). */ #define ADC_SAMPLETIME_1CYCLE_5 ((uint32_t)0x10000000) /*!< Sampling time 1.5 ADC clock cycle */ #define ADC_SAMPLETIME_7CYCLES_5 ((uint32_t) ADC_SMPR_SMP_0) /*!< Sampling time 7.5 ADC clock cycles */ #define ADC_SAMPLETIME_13CYCLES_5 ((uint32_t) ADC_SMPR_SMP_1) /*!< Sampling time 13.5 ADC clock cycles */ #define ADC_SAMPLETIME_28CYCLES_5 ((uint32_t)(ADC_SMPR_SMP_1 | ADC_SMPR_SMP_0)) /*!< Sampling time 28.5 ADC clock cycles */ #define ADC_SAMPLETIME_41CYCLES_5 ((uint32_t) ADC_SMPR_SMP_2) /*!< Sampling time 41.5 ADC clock cycles */ #define ADC_SAMPLETIME_55CYCLES_5 ((uint32_t)(ADC_SMPR_SMP_2 | ADC_SMPR_SMP_0)) /*!< Sampling time 55.5 ADC clock cycles */ #define ADC_SAMPLETIME_71CYCLES_5 ((uint32_t)(ADC_SMPR_SMP_2 | ADC_SMPR_SMP_1)) /*!< Sampling time 71.5 ADC clock cycles */ #define ADC_SAMPLETIME_239CYCLES_5 ((uint32_t) ADC_SMPR_SMP) /*!< Sampling time 239.5 ADC clock cycles */ /** * @} */ /** @defgroup ADC_analog_watchdog_mode ADC analog watchdog mode * @{ */ #define ADC_ANALOGWATCHDOG_NONE ((uint32_t) 0x00000000) #define ADC_ANALOGWATCHDOG_SINGLE_REG ((uint32_t)(ADC_CFGR1_AWDSGL | ADC_CFGR1_AWDEN)) #define ADC_ANALOGWATCHDOG_ALL_REG ((uint32_t) ADC_CFGR1_AWDEN) /** * @} */ /** @defgroup ADC_Event_type ADC Event type * @{ */ #define ADC_AWD_EVENT ((uint32_t)ADC_FLAG_AWD) /*!< ADC Analog watchdog 1 event */ #define ADC_OVR_EVENT ((uint32_t)ADC_FLAG_OVR) /*!< ADC overrun event */ /** * @} */ /** @defgroup ADC_interrupts_definition ADC interrupts definition * @{ */ #define ADC_IT_AWD ADC_IER_AWDIE /*!< ADC Analog watchdog interrupt source */ #define ADC_IT_OVR ADC_IER_OVRIE /*!< ADC overrun interrupt source */ #define ADC_IT_EOS ADC_IER_EOSEQIE /*!< ADC End of Regular sequence of Conversions interrupt source */ #define ADC_IT_EOC ADC_IER_EOCIE /*!< ADC End of Regular Conversion interrupt source */ #define ADC_IT_EOSMP ADC_IER_EOSMPIE /*!< ADC End of Sampling interrupt source */ #define ADC_IT_RDY ADC_IER_ADRDYIE /*!< ADC Ready interrupt source */ /** * @} */ /** @defgroup ADC_flags_definition ADC flags definition * @{ */ #define ADC_FLAG_AWD ADC_ISR_AWD /*!< ADC Analog watchdog flag */ #define ADC_FLAG_OVR ADC_ISR_OVR /*!< ADC overrun flag */ #define ADC_FLAG_EOS ADC_ISR_EOSEQ /*!< ADC End of Regular sequence of Conversions flag */ #define ADC_FLAG_EOC ADC_ISR_EOC /*!< ADC End of Regular Conversion flag */ #define ADC_FLAG_EOSMP ADC_ISR_EOSMP /*!< ADC End of Sampling flag */ #define ADC_FLAG_RDY ADC_ISR_ADRDY /*!< ADC Ready flag */ /** * @} */ /** * @} */ /* Private constants ---------------------------------------------------------*/ /** @addtogroup ADC_Private_Constants ADC Private Constants * @{ */ /** @defgroup ADC_Internal_HAL_driver_Ext_trig_src_Regular ADC Internal HAL driver Ext trig src Regular * @{ */ /* List of external triggers of regular group for ADC1: */ /* (used internally by HAL driver. To not use into HAL structure parameters) */ #define ADC1_2_EXTERNALTRIG_T1_TRGO ((uint32_t)0x00000000) #define ADC1_2_EXTERNALTRIG_T1_CC4 ((uint32_t)ADC_CFGR1_EXTSEL_0) #define ADC1_2_EXTERNALTRIG_T2_TRGO ((uint32_t)ADC_CFGR1_EXTSEL_1) #define ADC1_2_EXTERNALTRIG_T3_TRGO ((uint32_t)(ADC_CFGR1_EXTSEL_1 | ADC_CFGR1_EXTSEL_0)) #define ADC1_2_EXTERNALTRIG_T15_TRGO ((uint32_t)ADC_CFGR1_EXTSEL_2) /** * @} */ /* Combination of all post-conversion flags bits: EOC/EOS, OVR, AWD */ #define ADC_FLAG_POSTCONV_ALL (ADC_FLAG_AWD | ADC_FLAG_OVR | ADC_FLAG_EOS | ADC_FLAG_EOC) /** * @} */ /* Exported macro ------------------------------------------------------------*/ /** @defgroup ADC_Exported_Macros ADC Exported Macros * @{ */ /* Macro for internal HAL driver usage, and possibly can be used into code of */ /* final user. */ /** * @brief Enable the ADC peripheral * @param __HANDLE__: ADC handle * @retval None */ #define __HAL_ADC_ENABLE(__HANDLE__) \ ((__HANDLE__)->Instance->CR |= ADC_CR_ADEN) /** * @brief Disable the ADC peripheral * @param __HANDLE__: ADC handle * @retval None */ #define __HAL_ADC_DISABLE(__HANDLE__) \ do{ \ (__HANDLE__)->Instance->CR |= ADC_CR_ADDIS; \ __HAL_ADC_CLEAR_FLAG((__HANDLE__), (ADC_FLAG_EOSMP | ADC_FLAG_RDY)); \ } while(0) /** * @brief Enable the ADC end of conversion interrupt. * @param __HANDLE__: ADC handle * @param __INTERRUPT__: ADC Interrupt * This parameter can be any combination of the following values: * @arg ADC_IT_EOC: ADC End of Regular Conversion interrupt source * @arg ADC_IT_EOS: ADC End of Regular sequence of Conversions interrupt source * @arg ADC_IT_AWD: ADC Analog watchdog interrupt source * @arg ADC_IT_OVR: ADC overrun interrupt source * @arg ADC_IT_EOSMP: ADC End of Sampling interrupt source * @arg ADC_IT_RDY: ADC Ready interrupt source * @retval None */ #define __HAL_ADC_ENABLE_IT(__HANDLE__, __INTERRUPT__) \ (((__HANDLE__)->Instance->IER) |= (__INTERRUPT__)) /** * @brief Disable the ADC end of conversion interrupt. * @param __HANDLE__: ADC handle * @param __INTERRUPT__: ADC Interrupt * This parameter can be any combination of the following values: * @arg ADC_IT_EOC: ADC End of Regular Conversion interrupt source * @arg ADC_IT_EOS: ADC End of Regular sequence of Conversions interrupt source * @arg ADC_IT_AWD: ADC Analog watchdog interrupt source * @arg ADC_IT_OVR: ADC overrun interrupt source * @arg ADC_IT_EOSMP: ADC End of Sampling interrupt source * @arg ADC_IT_RDY: ADC Ready interrupt source * @retval None */ #define __HAL_ADC_DISABLE_IT(__HANDLE__, __INTERRUPT__) \ (((__HANDLE__)->Instance->IER) &= ~(__INTERRUPT__)) /** @brief Checks if the specified ADC interrupt source is enabled or disabled. * @param __HANDLE__: ADC handle * @param __INTERRUPT__: ADC interrupt source to check * This parameter can be any combination of the following values: * @arg ADC_IT_EOC: ADC End of Regular Conversion interrupt source * @arg ADC_IT_EOS: ADC End of Regular sequence of Conversions interrupt source * @arg ADC_IT_AWD: ADC Analog watchdog interrupt source * @arg ADC_IT_OVR: ADC overrun interrupt source * @arg ADC_IT_EOSMP: ADC End of Sampling interrupt source * @arg ADC_IT_RDY: ADC Ready interrupt source * @retval State ofinterruption (SET or RESET) */ #define __HAL_ADC_GET_IT_SOURCE(__HANDLE__, __INTERRUPT__) \ (((__HANDLE__)->Instance->IER & (__INTERRUPT__)) == (__INTERRUPT__)) /** * @brief Get the selected ADC's flag status. * @param __HANDLE__: ADC handle * @param __FLAG__: ADC flag * This parameter can be any combination of the following values: * @arg ADC_FLAG_EOC: ADC End of Regular conversion flag * @arg ADC_FLAG_EOS: ADC End of Regular sequence of Conversions flag * @arg ADC_FLAG_AWD: ADC Analog watchdog flag * @arg ADC_FLAG_OVR: ADC overrun flag * @arg ADC_FLAG_EOSMP: ADC End of Sampling flag * @arg ADC_FLAG_RDY: ADC Ready flag * @retval None */ #define __HAL_ADC_GET_FLAG(__HANDLE__, __FLAG__) \ ((((__HANDLE__)->Instance->ISR) & (__FLAG__)) == (__FLAG__)) /** * @brief Clear the ADC's pending flags * @param __HANDLE__: ADC handle * @param __FLAG__: ADC flag * This parameter can be any combination of the following values: * @arg ADC_FLAG_EOC: ADC End of Regular conversion flag * @arg ADC_FLAG_EOS: ADC End of Regular sequence of Conversions flag * @arg ADC_FLAG_AWD: ADC Analog watchdog flag * @arg ADC_FLAG_OVR: ADC overrun flag * @arg ADC_FLAG_EOSMP: ADC End of Sampling flag * @arg ADC_FLAG_RDY: ADC Ready flag * @retval None */ /* Note: bit cleared bit by writing 1 (writing 0 has no effect on any bit of register ISR) */ #define __HAL_ADC_CLEAR_FLAG(__HANDLE__, __FLAG__) \ (((__HANDLE__)->Instance->ISR) = (__FLAG__)) /** @brief Reset ADC handle state * @param __HANDLE__: ADC handle * @retval None */ #define __HAL_ADC_RESET_HANDLE_STATE(__HANDLE__) \ ((__HANDLE__)->State = HAL_ADC_STATE_RESET) /** * @} */ /* Private macro -------------------------------------------------------------*/ /** @defgroup ADC_Private_Macros ADC Private Macros * @{ */ /* Macro reserved for internal HAL driver usage, not intended to be used in */ /* code of final user. */ /** * @brief Verification of hardware constraints before ADC can be enabled * @param __HANDLE__: ADC handle * @retval SET (ADC can be enabled) or RESET (ADC cannot be enabled) */ #define ADC_ENABLING_CONDITIONS(__HANDLE__) \ (( ( ((__HANDLE__)->Instance->CR) & \ (ADC_CR_ADCAL | ADC_CR_ADSTP | ADC_CR_ADSTART | ADC_CR_ADDIS | ADC_CR_ADEN) \ ) == RESET \ ) ? SET : RESET) /** * @brief Verification of hardware constraints before ADC can be disabled * @param __HANDLE__: ADC handle * @retval SET (ADC can be disabled) or RESET (ADC cannot be disabled) */ #define ADC_DISABLING_CONDITIONS(__HANDLE__) \ (( ( ((__HANDLE__)->Instance->CR) & \ (ADC_CR_ADSTART | ADC_CR_ADEN)) == ADC_CR_ADEN \ ) ? SET : RESET) /** * @brief Verification of ADC state: enabled or disabled * @param __HANDLE__: ADC handle * @retval SET (ADC enabled) or RESET (ADC disabled) */ /* Note: If low power mode AutoPowerOff is enabled, power-on/off phases are */ /* performed automatically by hardware and flag ADC_FLAG_RDY is not */ /* set. */ #define ADC_IS_ENABLE(__HANDLE__) \ (( ((((__HANDLE__)->Instance->CR) & (ADC_CR_ADEN | ADC_CR_ADDIS)) == ADC_CR_ADEN) && \ (((((__HANDLE__)->Instance->ISR) & ADC_FLAG_RDY) == ADC_FLAG_RDY) || \ ((((__HANDLE__)->Instance->CFGR1) & ADC_CFGR1_AUTOFF) == ADC_CFGR1_AUTOFF) ) \ ) ? SET : RESET) /** * @brief Test if conversion trigger of regular group is software start * or external trigger. * @param __HANDLE__: ADC handle * @retval SET (software start) or RESET (external trigger) */ #define ADC_IS_SOFTWARE_START_REGULAR(__HANDLE__) \ (((__HANDLE__)->Instance->CFGR1 & ADC_CFGR1_EXTEN) == RESET) /** * @brief Check if no conversion on going on regular group * @param __HANDLE__: ADC handle * @retval SET (conversion is on going) or RESET (no conversion is on going) */ #define ADC_IS_CONVERSION_ONGOING_REGULAR(__HANDLE__) \ (( (((__HANDLE__)->Instance->CR) & ADC_CR_ADSTART) == RESET \ ) ? RESET : SET) /** * @brief Returns resolution bits in CFGR1 register: RES[1:0]. * Returned value is among parameters to @ref ADC_Resolution. * @param __HANDLE__: ADC handle * @retval None */ #define ADC_GET_RESOLUTION(__HANDLE__) \ (((__HANDLE__)->Instance->CFGR1) & ADC_CFGR1_RES) /** * @brief Returns ADC sample time bits in SMPR register: SMP[2:0]. * Returned value is among parameters to @ref ADC_Resolution. * @param __HANDLE__: ADC handle * @retval None */ #define ADC_GET_SAMPLINGTIME(__HANDLE__) \ (((__HANDLE__)->Instance->SMPR) & ADC_SMPR_SMP) /** * @brief Simultaneously clears and sets specific bits of the handle State * @note: ADC_STATE_CLR_SET() macro is merely aliased to generic macro MODIFY_REG(), * the first parameter is the ADC handle State, the second parameter is the * bit field to clear, the third and last parameter is the bit field to set. * @retval None */ #define ADC_STATE_CLR_SET MODIFY_REG /** * @brief Clear ADC error code (set it to error code: "no error") * @param __HANDLE__: ADC handle * @retval None */ #define ADC_CLEAR_ERRORCODE(__HANDLE__) \ ((__HANDLE__)->ErrorCode = HAL_ADC_ERROR_NONE) /** * @brief Configure the channel number into channel selection register * @param _CHANNEL_: ADC Channel * @retval None */ /* This function converts ADC channels from numbers (see defgroup ADC_channels) to bitfields, to get the equivalence of CMSIS channels: ADC_CHANNEL_0 ((uint32_t) ADC_CHSELR_CHSEL0) ADC_CHANNEL_1 ((uint32_t) ADC_CHSELR_CHSEL1) ADC_CHANNEL_2 ((uint32_t) ADC_CHSELR_CHSEL2) ADC_CHANNEL_3 ((uint32_t) ADC_CHSELR_CHSEL3) ADC_CHANNEL_4 ((uint32_t) ADC_CHSELR_CHSEL4) ADC_CHANNEL_5 ((uint32_t) ADC_CHSELR_CHSEL5) ADC_CHANNEL_6 ((uint32_t) ADC_CHSELR_CHSEL6) ADC_CHANNEL_7 ((uint32_t) ADC_CHSELR_CHSEL7) ADC_CHANNEL_8 ((uint32_t) ADC_CHSELR_CHSEL8) ADC_CHANNEL_9 ((uint32_t) ADC_CHSELR_CHSEL9) ADC_CHANNEL_10 ((uint32_t) ADC_CHSELR_CHSEL10) ADC_CHANNEL_11 ((uint32_t) ADC_CHSELR_CHSEL11) ADC_CHANNEL_12 ((uint32_t) ADC_CHSELR_CHSEL12) ADC_CHANNEL_13 ((uint32_t) ADC_CHSELR_CHSEL13) ADC_CHANNEL_14 ((uint32_t) ADC_CHSELR_CHSEL14) ADC_CHANNEL_15 ((uint32_t) ADC_CHSELR_CHSEL15) ADC_CHANNEL_16 ((uint32_t) ADC_CHSELR_CHSEL16) ADC_CHANNEL_17 ((uint32_t) ADC_CHSELR_CHSEL17) ADC_CHANNEL_18 ((uint32_t) ADC_CHSELR_CHSEL18) */ #define ADC_CHSELR_CHANNEL(_CHANNEL_) \ ( 1U << (_CHANNEL_)) /** * @brief Set the ADC's sample time * @param _SAMPLETIME_: Sample time parameter. * @retval None */ /* Note: ADC sampling time set using mask ADC_SMPR_SMP due to parameter */ /* "ADC_SAMPLETIME_1CYCLE_5" defined with a dummy bit (bit used to */ /* distinguish this parameter versus reset value 0x00000000, */ /* in the context of management of parameters "SamplingTimeCommon" */ /* and "SamplingTime" (obsolete)). */ #define ADC_SMPR_SET(_SAMPLETIME_) \ ((_SAMPLETIME_) & (ADC_SMPR_SMP)) /** * @brief Set the Analog Watchdog 1 channel. * @param _CHANNEL_: channel to be monitored by Analog Watchdog 1. * @retval None */ #define ADC_CFGR_AWDCH(_CHANNEL_) \ ((_CHANNEL_) << 26) /** * @brief Enable ADC discontinuous conversion mode for regular group * @param _REG_DISCONTINUOUS_MODE_: Regular discontinuous mode. * @retval None */ #define ADC_CFGR1_REG_DISCCONTINUOUS(_REG_DISCONTINUOUS_MODE_) \ ((_REG_DISCONTINUOUS_MODE_) << 16) /** * @brief Enable the ADC auto off mode. * @param _AUTOOFF_: Auto off bit enable or disable. * @retval None */ #define ADC_CFGR1_AUTOOFF(_AUTOOFF_) \ ((_AUTOOFF_) << 15) /** * @brief Enable the ADC auto delay mode. * @param _AUTOWAIT_: Auto delay bit enable or disable. * @retval None */ #define ADC_CFGR1_AUTOWAIT(_AUTOWAIT_) \ ((_AUTOWAIT_) << 14) /** * @brief Enable ADC continuous conversion mode. * @param _CONTINUOUS_MODE_: Continuous mode. * @retval None */ #define ADC_CFGR1_CONTINUOUS(_CONTINUOUS_MODE_) \ ((_CONTINUOUS_MODE_) << 13) /** * @brief Enable ADC overrun mode. * @param _OVERRUN_MODE_: Overrun mode. * @retval Overun bit setting to be programmed into CFGR register */ /* Note: Bit ADC_CFGR1_OVRMOD not used directly in constant */ /* "ADC_OVR_DATA_OVERWRITTEN" to have this case defined to 0x00, to set it */ /* as the default case to be compliant with other STM32 devices. */ #define ADC_CFGR1_OVERRUN(_OVERRUN_MODE_) \ ( ( (_OVERRUN_MODE_) != (ADC_OVR_DATA_PRESERVED) \ )? (ADC_CFGR1_OVRMOD) : (0x00000000) \ ) /** * @brief Enable ADC scan mode to convert multiple ranks with sequencer. * @param _SCAN_MODE_: Scan conversion mode. * @retval None */ /* Note: Scan mode set using this macro (instead of parameter direct set) */ /* due to different modes on other STM32 devices: to avoid any */ /* unwanted setting, the exact parameter corresponding to the device */ /* must be passed to this macro. */ #define ADC_SCANDIR(_SCAN_MODE_) \ ( ( (_SCAN_MODE_) == (ADC_SCAN_DIRECTION_BACKWARD) \ )? (ADC_CFGR1_SCANDIR) : (0x00000000) \ ) /** * @brief Enable the ADC DMA continuous request. * @param _DMACONTREQ_MODE_: DMA continuous request mode. * @retval None */ #define ADC_CFGR1_DMACONTREQ(_DMACONTREQ_MODE_) \ ((_DMACONTREQ_MODE_) << 1) /** * @brief Configure the analog watchdog high threshold into register TR. * @param _Threshold_: Threshold value * @retval None */ #define ADC_TRX_HIGHTHRESHOLD(_Threshold_) \ ((_Threshold_) << 16) /** * @brief Shift the AWD threshold in function of the selected ADC resolution. * Thresholds have to be left-aligned on bit 11, the LSB (right bits) are set to 0. * If resolution 12 bits, no shift. * If resolution 10 bits, shift of 2 ranks on the left. * If resolution 8 bits, shift of 4 ranks on the left. * If resolution 6 bits, shift of 6 ranks on the left. * therefore, shift = (12 - resolution) = 12 - (12- (((RES[1:0]) >> 3)*2)) * @param __HANDLE__: ADC handle * @param _Threshold_: Value to be shifted * @retval None */ #define ADC_AWD1THRESHOLD_SHIFT_RESOLUTION(__HANDLE__, _Threshold_) \ ((_Threshold_) << ((((__HANDLE__)->Instance->CFGR1 & ADC_CFGR1_RES) >> 3)*2)) #define IS_ADC_CLOCKPRESCALER(ADC_CLOCK) (((ADC_CLOCK) == ADC_CLOCK_ASYNC_DIV1) || \ ((ADC_CLOCK) == ADC_CLOCK_SYNC_PCLK_DIV2) || \ ((ADC_CLOCK) == ADC_CLOCK_SYNC_PCLK_DIV4) ) #define IS_ADC_RESOLUTION(RESOLUTION) (((RESOLUTION) == ADC_RESOLUTION_12B) || \ ((RESOLUTION) == ADC_RESOLUTION_10B) || \ ((RESOLUTION) == ADC_RESOLUTION_8B) || \ ((RESOLUTION) == ADC_RESOLUTION_6B) ) #define IS_ADC_DATA_ALIGN(ALIGN) (((ALIGN) == ADC_DATAALIGN_RIGHT) || \ ((ALIGN) == ADC_DATAALIGN_LEFT) ) #define IS_ADC_SCAN_MODE(SCAN_MODE) (((SCAN_MODE) == ADC_SCAN_DIRECTION_FORWARD) || \ ((SCAN_MODE) == ADC_SCAN_DIRECTION_BACKWARD) ) #define IS_ADC_EXTTRIG_EDGE(EDGE) (((EDGE) == ADC_EXTERNALTRIGCONVEDGE_NONE) || \ ((EDGE) == ADC_EXTERNALTRIGCONVEDGE_RISING) || \ ((EDGE) == ADC_EXTERNALTRIGCONVEDGE_FALLING) || \ ((EDGE) == ADC_EXTERNALTRIGCONVEDGE_RISINGFALLING) ) #define IS_ADC_EOC_SELECTION(EOC_SELECTION) (((EOC_SELECTION) == ADC_EOC_SINGLE_CONV) || \ ((EOC_SELECTION) == ADC_EOC_SEQ_CONV) || \ ((EOC_SELECTION) == ADC_EOC_SINGLE_SEQ_CONV) ) #define IS_ADC_OVERRUN(OVR) (((OVR) == ADC_OVR_DATA_PRESERVED) || \ ((OVR) == ADC_OVR_DATA_OVERWRITTEN) ) #define IS_ADC_RANK(WATCHDOG) (((WATCHDOG) == ADC_RANK_CHANNEL_NUMBER) || \ ((WATCHDOG) == ADC_RANK_NONE) ) #define IS_ADC_SAMPLE_TIME(TIME) (((TIME) == ADC_SAMPLETIME_1CYCLE_5) || \ ((TIME) == ADC_SAMPLETIME_7CYCLES_5) || \ ((TIME) == ADC_SAMPLETIME_13CYCLES_5) || \ ((TIME) == ADC_SAMPLETIME_28CYCLES_5) || \ ((TIME) == ADC_SAMPLETIME_41CYCLES_5) || \ ((TIME) == ADC_SAMPLETIME_55CYCLES_5) || \ ((TIME) == ADC_SAMPLETIME_71CYCLES_5) || \ ((TIME) == ADC_SAMPLETIME_239CYCLES_5) ) #define IS_ADC_ANALOG_WATCHDOG_MODE(WATCHDOG) (((WATCHDOG) == ADC_ANALOGWATCHDOG_NONE) || \ ((WATCHDOG) == ADC_ANALOGWATCHDOG_SINGLE_REG) || \ ((WATCHDOG) == ADC_ANALOGWATCHDOG_ALL_REG) ) #define IS_ADC_EVENT_TYPE(EVENT) (((EVENT) == ADC_AWD_EVENT) || \ ((EVENT) == ADC_OVR_EVENT) ) /** @defgroup ADC_range_verification ADC range verification * in function of ADC resolution selected (12, 10, 8 or 6 bits) * @{ */ #define IS_ADC_RANGE(RESOLUTION, ADC_VALUE) \ ((((RESOLUTION) == ADC_RESOLUTION_12B) && ((ADC_VALUE) <= ((uint32_t)0x0FFF))) || \ (((RESOLUTION) == ADC_RESOLUTION_10B) && ((ADC_VALUE) <= ((uint32_t)0x03FF))) || \ (((RESOLUTION) == ADC_RESOLUTION_8B) && ((ADC_VALUE) <= ((uint32_t)0x00FF))) || \ (((RESOLUTION) == ADC_RESOLUTION_6B) && ((ADC_VALUE) <= ((uint32_t)0x003F))) ) /** * @} */ /** @defgroup ADC_regular_rank_verification ADC regular rank verification * @{ */ #define IS_ADC_REGULAR_RANK(RANK) (((RANK) >= ((uint32_t)1)) && ((RANK) <= ((uint32_t)16))) /** * @} */ /** * @} */ /* Include ADC HAL Extension module */ #include "stm32f0xx_hal_adc_ex.h" /* Exported functions --------------------------------------------------------*/ /** @addtogroup ADC_Exported_Functions * @{ */ /** @addtogroup ADC_Exported_Functions_Group1 * @{ */ /* Initialization and de-initialization functions **********************************/ HAL_StatusTypeDef HAL_ADC_Init(ADC_HandleTypeDef* hadc); HAL_StatusTypeDef HAL_ADC_DeInit(ADC_HandleTypeDef *hadc); void HAL_ADC_MspInit(ADC_HandleTypeDef* hadc); void HAL_ADC_MspDeInit(ADC_HandleTypeDef* hadc); /** * @} */ /* IO operation functions *****************************************************/ /** @addtogroup ADC_Exported_Functions_Group2 * @{ */ /* Blocking mode: Polling */ HAL_StatusTypeDef HAL_ADC_Start(ADC_HandleTypeDef* hadc); HAL_StatusTypeDef HAL_ADC_Stop(ADC_HandleTypeDef* hadc); HAL_StatusTypeDef HAL_ADC_PollForConversion(ADC_HandleTypeDef* hadc, uint32_t Timeout); HAL_StatusTypeDef HAL_ADC_PollForEvent(ADC_HandleTypeDef* hadc, uint32_t EventType, uint32_t Timeout); /* Non-blocking mode: Interruption */ HAL_StatusTypeDef HAL_ADC_Start_IT(ADC_HandleTypeDef* hadc); HAL_StatusTypeDef HAL_ADC_Stop_IT(ADC_HandleTypeDef* hadc); /* Non-blocking mode: DMA */ HAL_StatusTypeDef HAL_ADC_Start_DMA(ADC_HandleTypeDef* hadc, uint32_t* pData, uint32_t Length); HAL_StatusTypeDef HAL_ADC_Stop_DMA(ADC_HandleTypeDef* hadc); /* ADC retrieve conversion value intended to be used with polling or interruption */ uint32_t HAL_ADC_GetValue(ADC_HandleTypeDef* hadc); /* ADC IRQHandler and Callbacks used in non-blocking modes (Interruption and DMA) */ void HAL_ADC_IRQHandler(ADC_HandleTypeDef* hadc); void HAL_ADC_ConvCpltCallback(ADC_HandleTypeDef* hadc); void HAL_ADC_ConvHalfCpltCallback(ADC_HandleTypeDef* hadc); void HAL_ADC_LevelOutOfWindowCallback(ADC_HandleTypeDef* hadc); void HAL_ADC_ErrorCallback(ADC_HandleTypeDef *hadc); /** * @} */ /* Peripheral Control functions ***********************************************/ /** @addtogroup ADC_Exported_Functions_Group3 * @{ */ HAL_StatusTypeDef HAL_ADC_ConfigChannel(ADC_HandleTypeDef* hadc, ADC_ChannelConfTypeDef* sConfig); HAL_StatusTypeDef HAL_ADC_AnalogWDGConfig(ADC_HandleTypeDef* hadc, ADC_AnalogWDGConfTypeDef* AnalogWDGConfig); /** * @} */ /* Peripheral State functions *************************************************/ /** @addtogroup ADC_Exported_Functions_Group4 * @{ */ uint32_t HAL_ADC_GetState(ADC_HandleTypeDef* hadc); uint32_t HAL_ADC_GetError(ADC_HandleTypeDef *hadc); /** * @} */ /** * @} */ /** * @} */ /** * @} */ #ifdef __cplusplus } #endif #endif /* __STM32F0xx_HAL_ADC_H */ /************************ (C) COPYRIGHT STMicroelectronics *****END OF FILE****/ ================================================ FILE: Zelig/mbed/TARGET_NUCLEO_F091RC/stm32f0xx_hal_adc_ex.h ================================================ /** ****************************************************************************** * @file stm32f0xx_hal_adc_ex.h * @author MCD Application Team * @version V1.3.0 * @date 26-June-2015 * @brief Header file of ADC HAL Extension module. ****************************************************************************** * @attention * *

© COPYRIGHT(c) 2015 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. * ****************************************************************************** */ /* Define to prevent recursive inclusion -------------------------------------*/ #ifndef __STM32F0xx_HAL_ADC_EX_H #define __STM32F0xx_HAL_ADC_EX_H #ifdef __cplusplus extern "C" { #endif /* Includes ------------------------------------------------------------------*/ #include "stm32f0xx_hal_def.h" /** @addtogroup STM32F0xx_HAL_Driver * @{ */ /** @addtogroup ADCEx * @{ */ /* Exported types ------------------------------------------------------------*/ /* Exported constants --------------------------------------------------------*/ /** @defgroup ADC_Exported_Constants ADC Exported Constants * @{ */ #if !defined(STM32F030x6) && !defined(STM32F030x8) && !defined(STM32F070x6) && !defined(STM32F070xB) && !defined(STM32F030xC) #define ADC_CCR_ALL (ADC_CCR_VBATEN | ADC_CCR_TSEN | ADC_CCR_VREFEN) #else #define ADC_CCR_ALL (ADC_CCR_TSEN | ADC_CCR_VREFEN) #endif /** @defgroup ADC_External_trigger_source_Regular ADC External trigger source Regular * @{ */ /* List of external triggers with generic trigger name, sorted by trigger */ /* name: */ /* External triggers of regular group for ADC1 */ #define ADC_EXTERNALTRIGCONV_T1_TRGO ADC1_2_EXTERNALTRIG_T1_TRGO #define ADC_EXTERNALTRIGCONV_T1_CC4 ADC1_2_EXTERNALTRIG_T1_CC4 #define ADC_EXTERNALTRIGCONV_T3_TRGO ADC1_2_EXTERNALTRIG_T3_TRGO #define ADC_SOFTWARE_START (ADC_CFGR1_EXTSEL + (uint32_t)1) #if !defined(STM32F030x6) && !defined(STM32F030x8) && !defined(STM32F070x6) && !defined(STM32F070xB) && !defined(STM32F030xC) #define ADC_EXTERNALTRIGCONV_T2_TRGO ADC1_2_EXTERNALTRIG_T2_TRGO #endif #if !defined(STM32F030x6) && !defined(STM32F070x6) && !defined(STM32F042x6) #define ADC_EXTERNALTRIGCONV_T15_TRGO ADC1_2_EXTERNALTRIG_T15_TRGO #endif /** * @} */ /** @defgroup ADC_channels ADC channels * @{ */ /* Note: Depending on devices, some channels may not be available on package */ /* pins. Refer to device datasheet for channels availability. */ /* Note: Channels are used by bitfields for setting of channel selection */ /* (register ADC_CHSELR) and used by number for setting of analog */ /* watchdog channel (bits AWDCH in register ADC_CFGR1). */ /* Channels are defined with decimal numbers and converted them to */ /* bitfields when needed. */ #define ADC_CHANNEL_0 ((uint32_t) 0x00000000) #define ADC_CHANNEL_1 ((uint32_t) 0x00000001) #define ADC_CHANNEL_2 ((uint32_t) 0x00000002) #define ADC_CHANNEL_3 ((uint32_t) 0x00000003) #define ADC_CHANNEL_4 ((uint32_t) 0x00000004) #define ADC_CHANNEL_5 ((uint32_t) 0x00000005) #define ADC_CHANNEL_6 ((uint32_t) 0x00000006) #define ADC_CHANNEL_7 ((uint32_t) 0x00000007) #define ADC_CHANNEL_8 ((uint32_t) 0x00000008) #define ADC_CHANNEL_9 ((uint32_t) 0x00000009) #define ADC_CHANNEL_10 ((uint32_t) 0x0000000A) #define ADC_CHANNEL_11 ((uint32_t) 0x0000000B) #define ADC_CHANNEL_12 ((uint32_t) 0x0000000C) #define ADC_CHANNEL_13 ((uint32_t) 0x0000000D) #define ADC_CHANNEL_14 ((uint32_t) 0x0000000E) #define ADC_CHANNEL_15 ((uint32_t) 0x0000000F) #define ADC_CHANNEL_16 ((uint32_t) 0x00000010) #define ADC_CHANNEL_17 ((uint32_t) 0x00000011) #define ADC_CHANNEL_TEMPSENSOR ADC_CHANNEL_16 #define ADC_CHANNEL_VREFINT ADC_CHANNEL_17 #if !defined(STM32F030x6) && !defined(STM32F030x8) && !defined(STM32F070x6) && !defined(STM32F070xB) && !defined(STM32F030xC) #define ADC_CHANNEL_18 ((uint32_t) 0x00000012) #define ADC_CHANNEL_VBAT ADC_CHANNEL_18 #endif /** * @} */ /** * @} */ /* Exported macro ------------------------------------------------------------*/ /* Private macros ------------------------------------------------------------*/ /** @defgroup ADCEx_Private_Macros ADCEx Private Macros * @{ */ /* Macro reserved for internal HAL driver usage, not intended to be used in */ /* code of final user. */ /** * @brief Test if the selected ADC channel is an internal channel * VrefInt/TempSensor/Vbat * Note: On STM32F0, availability of internal channel Vbat depends on * devices lines. * @param __CHANNEL__: ADC channel * @retval None */ #if !defined(STM32F030x6) && !defined(STM32F030x8) && !defined(STM32F070x6) && !defined(STM32F070xB) && !defined(STM32F030xC) #define ADC_IS_CHANNEL_INTERNAL(__CHANNEL__) \ (((__CHANNEL__) == ADC_CHANNEL_TEMPSENSOR) || \ ((__CHANNEL__) == ADC_CHANNEL_VREFINT) || \ ((__CHANNEL__) == ADC_CHANNEL_VBAT) \ ) #else #define ADC_IS_CHANNEL_INTERNAL(__CHANNEL__) \ (((__CHANNEL__) == ADC_CHANNEL_TEMPSENSOR) || \ ((__CHANNEL__) == ADC_CHANNEL_VREFINT) \ ) #endif /** * @brief Select the internal measurement path to be enabled/disabled * corresponding to the selected ADC internal channel * VrefInt/TempSensor/Vbat. * Note: On STM32F0, availability of internal channel Vbat depends on * devices lines. * @param __CHANNEL__: ADC channel * @retval Bit of register ADC_CCR */ #if !defined(STM32F030x6) && !defined(STM32F030x8) && !defined(STM32F070x6) && !defined(STM32F070xB) && !defined(STM32F030xC) #define ADC_CHANNEL_INTERNAL_PATH(__CHANNEL__) \ (( (__CHANNEL__) == ADC_CHANNEL_TEMPSENSOR \ )? \ (ADC_CCR_TSEN) \ : \ ( \ ( (__CHANNEL__) == ADC_CHANNEL_VREFINT \ )? \ (ADC_CCR_VREFEN) \ : \ (ADC_CCR_VBATEN) \ ) \ ) #else #define ADC_CHANNEL_INTERNAL_PATH(__CHANNEL__) \ (( (__CHANNEL__) == ADC_CHANNEL_TEMPSENSOR \ )? \ (ADC_CCR_TSEN) \ : \ (ADC_CHANNEL_VREFINT) \ ) #endif #if defined (STM32F030x6) || defined (STM32F070x6) #define IS_ADC_EXTTRIG(REGTRIG) (((REGTRIG) == ADC_EXTERNALTRIGCONV_T1_TRGO) || \ ((REGTRIG) == ADC_EXTERNALTRIGCONV_T1_CC4) || \ ((REGTRIG) == ADC_EXTERNALTRIGCONV_T3_TRGO) || \ ((REGTRIG) == ADC_SOFTWARE_START)) #elif defined (STM32F042x6) #define IS_ADC_EXTTRIG(REGTRIG) (((REGTRIG) == ADC_EXTERNALTRIGCONV_T1_TRGO) || \ ((REGTRIG) == ADC_EXTERNALTRIGCONV_T1_CC4) || \ ((REGTRIG) == ADC_EXTERNALTRIGCONV_T2_TRGO) || \ ((REGTRIG) == ADC_EXTERNALTRIGCONV_T3_TRGO) || \ ((REGTRIG) == ADC_SOFTWARE_START)) #elif defined (STM32F030xC) || defined (STM32F070xB) || defined (STM32F030x8) #define IS_ADC_EXTTRIG(REGTRIG) (((REGTRIG) == ADC_EXTERNALTRIGCONV_T1_TRGO) || \ ((REGTRIG) == ADC_EXTERNALTRIGCONV_T1_CC4) || \ ((REGTRIG) == ADC_EXTERNALTRIGCONV_T3_TRGO) || \ ((REGTRIG) == ADC_EXTERNALTRIGCONV_T15_TRGO) || \ ((REGTRIG) == ADC_SOFTWARE_START)) #else #define IS_ADC_EXTTRIG(REGTRIG) (((REGTRIG) == ADC_EXTERNALTRIGCONV_T1_TRGO) || \ ((REGTRIG) == ADC_EXTERNALTRIGCONV_T1_CC4) || \ ((REGTRIG) == ADC_EXTERNALTRIGCONV_T2_TRGO) || \ ((REGTRIG) == ADC_EXTERNALTRIGCONV_T3_TRGO) || \ ((REGTRIG) == ADC_EXTERNALTRIGCONV_T15_TRGO) || \ ((REGTRIG) == ADC_SOFTWARE_START)) #endif #if !defined(STM32F030x6) && !defined(STM32F030x8) && !defined(STM32F070x6) && !defined(STM32F070xB) && !defined(STM32F030xC) #define IS_ADC_CHANNEL(CHANNEL) (((CHANNEL) == ADC_CHANNEL_0) || \ ((CHANNEL) == ADC_CHANNEL_1) || \ ((CHANNEL) == ADC_CHANNEL_2) || \ ((CHANNEL) == ADC_CHANNEL_3) || \ ((CHANNEL) == ADC_CHANNEL_4) || \ ((CHANNEL) == ADC_CHANNEL_5) || \ ((CHANNEL) == ADC_CHANNEL_6) || \ ((CHANNEL) == ADC_CHANNEL_7) || \ ((CHANNEL) == ADC_CHANNEL_8) || \ ((CHANNEL) == ADC_CHANNEL_9) || \ ((CHANNEL) == ADC_CHANNEL_10) || \ ((CHANNEL) == ADC_CHANNEL_11) || \ ((CHANNEL) == ADC_CHANNEL_12) || \ ((CHANNEL) == ADC_CHANNEL_13) || \ ((CHANNEL) == ADC_CHANNEL_14) || \ ((CHANNEL) == ADC_CHANNEL_15) || \ ((CHANNEL) == ADC_CHANNEL_TEMPSENSOR) || \ ((CHANNEL) == ADC_CHANNEL_VREFINT) || \ ((CHANNEL) == ADC_CHANNEL_VBAT) ) #else #define IS_ADC_CHANNEL(CHANNEL) (((CHANNEL) == ADC_CHANNEL_0) || \ ((CHANNEL) == ADC_CHANNEL_1) || \ ((CHANNEL) == ADC_CHANNEL_2) || \ ((CHANNEL) == ADC_CHANNEL_3) || \ ((CHANNEL) == ADC_CHANNEL_4) || \ ((CHANNEL) == ADC_CHANNEL_5) || \ ((CHANNEL) == ADC_CHANNEL_6) || \ ((CHANNEL) == ADC_CHANNEL_7) || \ ((CHANNEL) == ADC_CHANNEL_8) || \ ((CHANNEL) == ADC_CHANNEL_9) || \ ((CHANNEL) == ADC_CHANNEL_10) || \ ((CHANNEL) == ADC_CHANNEL_11) || \ ((CHANNEL) == ADC_CHANNEL_12) || \ ((CHANNEL) == ADC_CHANNEL_13) || \ ((CHANNEL) == ADC_CHANNEL_14) || \ ((CHANNEL) == ADC_CHANNEL_15) || \ ((CHANNEL) == ADC_CHANNEL_TEMPSENSOR) || \ ((CHANNEL) == ADC_CHANNEL_VREFINT) ) #endif /** * @} */ /* Exported functions --------------------------------------------------------*/ /** @addtogroup ADCEx_Exported_Functions * @{ */ /* IO operation functions *****************************************************/ /** @addtogroup ADCEx_Exported_Functions_Group1 * @{ */ /* ADC calibration */ HAL_StatusTypeDef HAL_ADCEx_Calibration_Start(ADC_HandleTypeDef* hadc); /** * @} */ /** * @} */ /** * @} */ /** * @} */ #ifdef __cplusplus } #endif #endif /* __STM32F0xx_HAL_ADC_EX_H */ /************************ (C) COPYRIGHT STMicroelectronics *****END OF FILE****/ ================================================ FILE: Zelig/mbed/TARGET_NUCLEO_F091RC/stm32f0xx_hal_can.h ================================================ /** ****************************************************************************** * @file stm32f0xx_hal_can.h * @author MCD Application Team * @version V1.3.0 * @date 26-June-2015 * @brief Header file of CAN HAL module. ****************************************************************************** * @attention * *

© COPYRIGHT(c) 2015 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. * ****************************************************************************** */ /* Define to prevent recursive inclusion -------------------------------------*/ #ifndef __STM32F0xx_HAL_CAN_H #define __STM32F0xx_HAL_CAN_H #ifdef __cplusplus extern "C" { #endif #if defined(STM32F072xB) || defined(STM32F042x6) || defined(STM32F048xx) || defined(STM32F078xx) || defined(STM32F091xC) || defined(STM32F098xx) /* Includes ------------------------------------------------------------------*/ #include "stm32f0xx_hal_def.h" /** @addtogroup STM32F0xx_HAL_Driver * @{ */ /** @addtogroup CAN * @{ */ /* Exported types ------------------------------------------------------------*/ /** @defgroup CAN_Exported_Types CAN Exported Types * @{ */ /** * @brief HAL State structures definition */ typedef enum { HAL_CAN_STATE_RESET = 0x00, /*!< CAN not yet initialized or disabled */ HAL_CAN_STATE_READY = 0x01, /*!< CAN initialized and ready for use */ HAL_CAN_STATE_BUSY = 0x02, /*!< CAN process is ongoing */ HAL_CAN_STATE_BUSY_TX = 0x12, /*!< CAN process is ongoing */ HAL_CAN_STATE_BUSY_RX = 0x22, /*!< CAN process is ongoing */ HAL_CAN_STATE_BUSY_TX_RX = 0x32, /*!< CAN process is ongoing */ HAL_CAN_STATE_TIMEOUT = 0x03, /*!< CAN in Timeout state */ HAL_CAN_STATE_ERROR = 0x04 /*!< CAN error state */ }HAL_CAN_StateTypeDef; /** * @brief CAN init structure definition */ typedef struct { uint32_t Prescaler; /*!< Specifies the length of a time quantum. This parameter must be a number between Min_Data = 1 and Max_Data = 1024. */ uint32_t Mode; /*!< Specifies the CAN operating mode. This parameter can be a value of @ref CAN_operating_mode */ uint32_t SJW; /*!< Specifies the maximum number of time quanta the CAN hardware is allowed to lengthen or shorten a bit to perform resynchronization. This parameter can be a value of @ref CAN_synchronisation_jump_width */ uint32_t BS1; /*!< Specifies the number of time quanta in Bit Segment 1. This parameter can be a value of @ref CAN_time_quantum_in_bit_segment_1 */ uint32_t BS2; /*!< Specifies the number of time quanta in Bit Segment 2. This parameter can be a value of @ref CAN_time_quantum_in_bit_segment_2 */ uint32_t TTCM; /*!< Enable or disable the time triggered communication mode. This parameter can be set to ENABLE or DISABLE. */ uint32_t ABOM; /*!< Enable or disable the automatic bus-off management. This parameter can be set to ENABLE or DISABLE. */ uint32_t AWUM; /*!< Enable or disable the automatic wake-up mode. This parameter can be set to ENABLE or DISABLE. */ uint32_t NART; /*!< Enable or disable the non-automatic retransmission mode. This parameter can be set to ENABLE or DISABLE. */ uint32_t RFLM; /*!< Enable or disable the Receive FIFO Locked mode. This parameter can be set to ENABLE or DISABLE. */ uint32_t TXFP; /*!< Enable or disable the transmit FIFO priority. This parameter can be set to ENABLE or DISABLE. */ }CAN_InitTypeDef; /** * @brief CAN filter configuration structure definition */ typedef struct { uint32_t FilterIdHigh; /*!< Specifies the filter identification number (MSBs for a 32-bit configuration, first one for a 16-bit configuration). This parameter must be a number between Min_Data = 0x0000 and Max_Data = 0xFFFF. */ uint32_t FilterIdLow; /*!< Specifies the filter identification number (LSBs for a 32-bit configuration, second one for a 16-bit configuration). This parameter must be a number between Min_Data = 0x0000 and Max_Data = 0xFFFF. */ uint32_t FilterMaskIdHigh; /*!< Specifies the filter mask number or identification number, according to the mode (MSBs for a 32-bit configuration, first one for a 16-bit configuration). This parameter must be a number between Min_Data = 0x0000 and Max_Data = 0xFFFF. */ uint32_t FilterMaskIdLow; /*!< Specifies the filter mask number or identification number, according to the mode (LSBs for a 32-bit configuration, second one for a 16-bit configuration). This parameter must be a number between Min_Data = 0x0000 and Max_Data = 0xFFFF. */ uint32_t FilterFIFOAssignment; /*!< Specifies the FIFO (0 or 1) which will be assigned to the filter. This parameter can be a value of @ref CAN_filter_FIFO */ uint32_t FilterNumber; /*!< Specifies the filter which will be initialized. This parameter must be a number between Min_Data = 0 and Max_Data = 27. */ uint32_t FilterMode; /*!< Specifies the filter mode to be initialized. This parameter can be a value of @ref CAN_filter_mode */ uint32_t FilterScale; /*!< Specifies the filter scale. This parameter can be a value of @ref CAN_filter_scale */ uint32_t FilterActivation; /*!< Enable or disable the filter. This parameter can be set to ENABLE or DISABLE. */ uint32_t BankNumber; /*!< Select the start slave bank filter This parameter must be a number between Min_Data = 0 and Max_Data = 28. */ }CAN_FilterConfTypeDef; /** * @brief CAN Tx message structure definition */ typedef struct { uint32_t StdId; /*!< Specifies the standard identifier. This parameter must be a number between Min_Data = 0 and Max_Data = 0x7FF. */ uint32_t ExtId; /*!< Specifies the extended identifier. This parameter must be a number between Min_Data = 0 and Max_Data = 0x1FFFFFFF. */ uint32_t IDE; /*!< Specifies the type of identifier for the message that will be transmitted. This parameter can be a value of @ref CAN_identifier_type */ uint32_t RTR; /*!< Specifies the type of frame for the message that will be transmitted. This parameter can be a value of @ref CAN_remote_transmission_request */ uint32_t DLC; /*!< Specifies the length of the frame that will be transmitted. This parameter must be a number between Min_Data = 0 and Max_Data = 8. */ uint8_t Data[8]; /*!< Contains the data to be transmitted. This parameter must be a number between Min_Data = 0 and Max_Data = 0xFF. */ }CanTxMsgTypeDef; /** * @brief CAN Rx message structure definition */ typedef struct { uint32_t StdId; /*!< Specifies the standard identifier. This parameter must be a number between Min_Data = 0 and Max_Data = 0x7FF. */ uint32_t ExtId; /*!< Specifies the extended identifier. This parameter must be a number between Min_Data = 0 and Max_Data = 0x1FFFFFFF. */ uint32_t IDE; /*!< Specifies the type of identifier for the message that will be received. This parameter can be a value of @ref CAN_identifier_type */ uint32_t RTR; /*!< Specifies the type of frame for the received message. This parameter can be a value of @ref CAN_remote_transmission_request */ uint32_t DLC; /*!< Specifies the length of the frame that will be received. This parameter must be a number between Min_Data = 0 and Max_Data = 8. */ uint8_t Data[8]; /*!< Contains the data to be received. This parameter must be a number between Min_Data = 0 and Max_Data = 0xFF. */ uint32_t FMI; /*!< Specifies the index of the filter the message stored in the mailbox passes through. This parameter must be a number between Min_Data = 0 and Max_Data = 0xFF. */ uint32_t FIFONumber; /*!< Specifies the receive FIFO number. This parameter can be CAN_FIFO0 or CAN_FIFO1 */ }CanRxMsgTypeDef; /** * @brief CAN handle Structure definition */ typedef struct { CAN_TypeDef *Instance; /*!< Register base address */ CAN_InitTypeDef Init; /*!< CAN required parameters */ CanTxMsgTypeDef* pTxMsg; /*!< Pointer to transmit structure */ CanRxMsgTypeDef* pRxMsg; /*!< Pointer to reception structure */ HAL_LockTypeDef Lock; /*!< CAN locking object */ __IO HAL_CAN_StateTypeDef State; /*!< CAN communication state */ __IO uint32_t ErrorCode; /*!< CAN Error code This parameter can be a value of @ref HAL_CAN_Error_Code */ }CAN_HandleTypeDef; /** * @} */ /* Exported constants --------------------------------------------------------*/ /** @defgroup CAN_Exported_Constants CAN Exported Constants * @{ */ /** @defgroup HAL_CAN_Error_Code CAN Error Code * @{ */ #define HAL_CAN_ERROR_NONE ((uint32_t)0x00000000) /*!< No error */ #define HAL_CAN_ERROR_EWG ((uint32_t)0x00000001) /*!< EWG error */ #define HAL_CAN_ERROR_EPV ((uint32_t)0x00000002) /*!< EPV error */ #define HAL_CAN_ERROR_BOF ((uint32_t)0x00000004) /*!< BOF error */ #define HAL_CAN_ERROR_STF ((uint32_t)0x00000008) /*!< Stuff error */ #define HAL_CAN_ERROR_FOR ((uint32_t)0x00000010) /*!< Form error */ #define HAL_CAN_ERROR_ACK ((uint32_t)0x00000020) /*!< Acknowledgment error */ #define HAL_CAN_ERROR_BR ((uint32_t)0x00000040) /*!< Bit recessive */ #define HAL_CAN_ERROR_BD ((uint32_t)0x00000080) /*!< LEC dominant */ #define HAL_CAN_ERROR_CRC ((uint32_t)0x00000100) /*!< LEC transfer error */ /** * @} */ /** @defgroup CAN_InitStatus CAN InitStatus * @{ */ #define CAN_INITSTATUS_FAILED ((uint32_t)0x00000000) /*!< CAN initialization failed */ #define CAN_INITSTATUS_SUCCESS ((uint32_t)0x00000001) /*!< CAN initialization OK */ /** * @} */ /** @defgroup CAN_operating_mode CAN operating mode * @{ */ #define CAN_MODE_NORMAL ((uint32_t)0x00000000) /*!< Normal mode */ #define CAN_MODE_LOOPBACK ((uint32_t)CAN_BTR_LBKM) /*!< Loopback mode */ #define CAN_MODE_SILENT ((uint32_t)CAN_BTR_SILM) /*!< Silent mode */ #define CAN_MODE_SILENT_LOOPBACK ((uint32_t)(CAN_BTR_LBKM | CAN_BTR_SILM)) /*!< Loopback combined with silent mode */ /** * @} */ /** @defgroup CAN_synchronisation_jump_width CAN synchronisation jump width * @{ */ #define CAN_SJW_1TQ ((uint32_t)0x00000000) /*!< 1 time quantum */ #define CAN_SJW_2TQ ((uint32_t)CAN_BTR_SJW_0) /*!< 2 time quantum */ #define CAN_SJW_3TQ ((uint32_t)CAN_BTR_SJW_1) /*!< 3 time quantum */ #define CAN_SJW_4TQ ((uint32_t)CAN_BTR_SJW) /*!< 4 time quantum */ /** * @} */ /** @defgroup CAN_time_quantum_in_bit_segment_1 CAN time quantum in bit segment 1 * @{ */ #define CAN_BS1_1TQ ((uint32_t)0x00000000) /*!< 1 time quantum */ #define CAN_BS1_2TQ ((uint32_t)CAN_BTR_TS1_0) /*!< 2 time quantum */ #define CAN_BS1_3TQ ((uint32_t)CAN_BTR_TS1_1) /*!< 3 time quantum */ #define CAN_BS1_4TQ ((uint32_t)(CAN_BTR_TS1_1 | CAN_BTR_TS1_0)) /*!< 4 time quantum */ #define CAN_BS1_5TQ ((uint32_t)CAN_BTR_TS1_2) /*!< 5 time quantum */ #define CAN_BS1_6TQ ((uint32_t)(CAN_BTR_TS1_2 | CAN_BTR_TS1_0)) /*!< 6 time quantum */ #define CAN_BS1_7TQ ((uint32_t)(CAN_BTR_TS1_2 | CAN_BTR_TS1_1)) /*!< 7 time quantum */ #define CAN_BS1_8TQ ((uint32_t)(CAN_BTR_TS1_2 | CAN_BTR_TS1_1 | CAN_BTR_TS1_0)) /*!< 8 time quantum */ #define CAN_BS1_9TQ ((uint32_t)CAN_BTR_TS1_3) /*!< 9 time quantum */ #define CAN_BS1_10TQ ((uint32_t)(CAN_BTR_TS1_3 | CAN_BTR_TS1_0)) /*!< 10 time quantum */ #define CAN_BS1_11TQ ((uint32_t)(CAN_BTR_TS1_3 | CAN_BTR_TS1_1)) /*!< 11 time quantum */ #define CAN_BS1_12TQ ((uint32_t)(CAN_BTR_TS1_3 | CAN_BTR_TS1_1 | CAN_BTR_TS1_0)) /*!< 12 time quantum */ #define CAN_BS1_13TQ ((uint32_t)(CAN_BTR_TS1_3 | CAN_BTR_TS1_2)) /*!< 13 time quantum */ #define CAN_BS1_14TQ ((uint32_t)(CAN_BTR_TS1_3 | CAN_BTR_TS1_2 | CAN_BTR_TS1_0)) /*!< 14 time quantum */ #define CAN_BS1_15TQ ((uint32_t)(CAN_BTR_TS1_3 | CAN_BTR_TS1_2 | CAN_BTR_TS1_1)) /*!< 15 time quantum */ #define CAN_BS1_16TQ ((uint32_t)CAN_BTR_TS1) /*!< 16 time quantum */ /** * @} */ /** @defgroup CAN_time_quantum_in_bit_segment_2 CAN time quantum in bit segment 2 * @{ */ #define CAN_BS2_1TQ ((uint32_t)0x00000000) /*!< 1 time quantum */ #define CAN_BS2_2TQ ((uint32_t)CAN_BTR_TS2_0) /*!< 2 time quantum */ #define CAN_BS2_3TQ ((uint32_t)CAN_BTR_TS2_1) /*!< 3 time quantum */ #define CAN_BS2_4TQ ((uint32_t)(CAN_BTR_TS2_1 | CAN_BTR_TS2_0)) /*!< 4 time quantum */ #define CAN_BS2_5TQ ((uint32_t)CAN_BTR_TS2_2) /*!< 5 time quantum */ #define CAN_BS2_6TQ ((uint32_t)(CAN_BTR_TS2_2 | CAN_BTR_TS2_0)) /*!< 6 time quantum */ #define CAN_BS2_7TQ ((uint32_t)(CAN_BTR_TS2_2 | CAN_BTR_TS2_1)) /*!< 7 time quantum */ #define CAN_BS2_8TQ ((uint32_t)CAN_BTR_TS2) /*!< 8 time quantum */ /** * @} */ /** @defgroup CAN_filter_mode CAN filter mode * @{ */ #define CAN_FILTERMODE_IDMASK ((uint8_t)0x00) /*!< Identifier mask mode */ #define CAN_FILTERMODE_IDLIST ((uint8_t)0x01) /*!< Identifier list mode */ /** * @} */ /** @defgroup CAN_filter_scale CAN filter scale * @{ */ #define CAN_FILTERSCALE_16BIT ((uint8_t)0x00) /*!< Two 16-bit filters */ #define CAN_FILTERSCALE_32BIT ((uint8_t)0x01) /*!< One 32-bit filter */ /** * @} */ /** @defgroup CAN_filter_FIFO CAN filter FIFO * @{ */ #define CAN_FILTER_FIFO0 ((uint8_t)0x00) /*!< Filter FIFO 0 assignment for filter x */ #define CAN_FILTER_FIFO1 ((uint8_t)0x01) /*!< Filter FIFO 1 assignment for filter x */ /** * @} */ /** @defgroup CAN_identifier_type CAN identifier type * @{ */ #define CAN_ID_STD ((uint32_t)0x00000000) /*!< Standard Id */ #define CAN_ID_EXT ((uint32_t)0x00000004) /*!< Extended Id */ /** * @} */ /** @defgroup CAN_remote_transmission_request CAN remote transmission request * @{ */ #define CAN_RTR_DATA ((uint32_t)0x00000000) /*!< Data frame */ #define CAN_RTR_REMOTE ((uint32_t)0x00000002) /*!< Remote frame */ /** * @} */ /** @defgroup CAN_receive_FIFO_number_constants CAN receive FIFO number constants * @{ */ #define CAN_FIFO0 ((uint8_t)0x00) /*!< CAN FIFO 0 used to receive */ #define CAN_FIFO1 ((uint8_t)0x01) /*!< CAN FIFO 1 used to receive */ /** * @} */ /** @defgroup CAN_flags CAN flags * @{ */ /* If the flag is 0x3XXXXXXX, it means that it can be used with CAN_GetFlagStatus() and CAN_ClearFlag() functions. */ /* If the flag is 0x1XXXXXXX, it means that it can only be used with CAN_GetFlagStatus() function. */ /* Transmit Flags */ #define CAN_FLAG_RQCP0 ((uint32_t)0x00000500) /*!< Request MailBox0 flag */ #define CAN_FLAG_RQCP1 ((uint32_t)0x00000508) /*!< Request MailBox1 flag */ #define CAN_FLAG_RQCP2 ((uint32_t)0x00000510) /*!< Request MailBox2 flag */ #define CAN_FLAG_TXOK0 ((uint32_t)0x00000501) /*!< Transmission OK MailBox0 flag */ #define CAN_FLAG_TXOK1 ((uint32_t)0x00000509) /*!< Transmission OK MailBox1 flag */ #define CAN_FLAG_TXOK2 ((uint32_t)0x00000511) /*!< Transmission OK MailBox2 flag */ #define CAN_FLAG_TME0 ((uint32_t)0x0000051A) /*!< Transmit mailbox 0 empty flag */ #define CAN_FLAG_TME1 ((uint32_t)0x0000051B) /*!< Transmit mailbox 0 empty flag */ #define CAN_FLAG_TME2 ((uint32_t)0x0000051C) /*!< Transmit mailbox 0 empty flag */ /* Receive Flags */ #define CAN_FLAG_FF0 ((uint32_t)0x00000203) /*!< FIFO 0 Full flag */ #define CAN_FLAG_FOV0 ((uint32_t)0x00000204) /*!< FIFO 0 Overrun flag */ #define CAN_FLAG_FF1 ((uint32_t)0x00000403) /*!< FIFO 1 Full flag */ #define CAN_FLAG_FOV1 ((uint32_t)0x00000404) /*!< FIFO 1 Overrun flag */ /* Operating Mode Flags */ #define CAN_FLAG_WKU ((uint32_t)0x00000103) /*!< Wake up flag */ #define CAN_FLAG_SLAK ((uint32_t)0x00000101) /*!< Sleep acknowledge flag */ #define CAN_FLAG_SLAKI ((uint32_t)0x00000104) /*!< Sleep acknowledge flag */ /* @note When SLAK interrupt is disabled (SLKIE=0), no polling on SLAKI is possible. In this case the SLAK bit can be polled.*/ /* Error Flags */ #define CAN_FLAG_EWG ((uint32_t)0x00000300) /*!< Error warning flag */ #define CAN_FLAG_EPV ((uint32_t)0x00000301) /*!< Error passive flag */ #define CAN_FLAG_BOF ((uint32_t)0x00000302) /*!< Bus-Off flag */ /** * @} */ /** @defgroup CAN_interrupts CAN interrupts * @{ */ #define CAN_IT_TME ((uint32_t)CAN_IER_TMEIE) /*!< Transmit mailbox empty interrupt */ /* Receive Interrupts */ #define CAN_IT_FMP0 ((uint32_t)CAN_IER_FMPIE0) /*!< FIFO 0 message pending interrupt */ #define CAN_IT_FF0 ((uint32_t)CAN_IER_FFIE0) /*!< FIFO 0 full interrupt */ #define CAN_IT_FOV0 ((uint32_t)CAN_IER_FOVIE0) /*!< FIFO 0 overrun interrupt */ #define CAN_IT_FMP1 ((uint32_t)CAN_IER_FMPIE1) /*!< FIFO 1 message pending interrupt */ #define CAN_IT_FF1 ((uint32_t)CAN_IER_FFIE1) /*!< FIFO 1 full interrupt */ #define CAN_IT_FOV1 ((uint32_t)CAN_IER_FOVIE1) /*!< FIFO 1 overrun interrupt */ /* Operating Mode Interrupts */ #define CAN_IT_WKU ((uint32_t)CAN_IER_WKUIE) /*!< Wake-up interrupt */ #define CAN_IT_SLK ((uint32_t)CAN_IER_SLKIE) /*!< Sleep acknowledge interrupt */ /* Error Interrupts */ #define CAN_IT_EWG ((uint32_t)CAN_IER_EWGIE) /*!< Error warning interrupt */ #define CAN_IT_EPV ((uint32_t)CAN_IER_EPVIE) /*!< Error passive interrupt */ #define CAN_IT_BOF ((uint32_t)CAN_IER_BOFIE) /*!< Bus-off interrupt */ #define CAN_IT_LEC ((uint32_t)CAN_IER_LECIE) /*!< Last error code interrupt */ #define CAN_IT_ERR ((uint32_t)CAN_IER_ERRIE) /*!< Error Interrupt */ /** * @} */ /** @defgroup CAN_Mailboxes CAN Mailboxes * @{ */ /* Mailboxes definition */ #define CAN_TXMAILBOX_0 ((uint8_t)0x00) #define CAN_TXMAILBOX_1 ((uint8_t)0x01) #define CAN_TXMAILBOX_2 ((uint8_t)0x02) /** * @} */ /** * @} */ /* Exported macros -----------------------------------------------------------*/ /** @defgroup CAN_Exported_Macros CAN Exported Macros * @{ */ /** @brief Reset CAN handle state * @param __HANDLE__: CAN handle. * @retval None */ #define __HAL_CAN_RESET_HANDLE_STATE(__HANDLE__) ((__HANDLE__)->State = HAL_CAN_STATE_RESET) /** * @brief Enable the specified CAN interrupts. * @param __HANDLE__: CAN handle. * @param __INTERRUPT__: CAN Interrupt * @retval None */ #define __HAL_CAN_ENABLE_IT(__HANDLE__, __INTERRUPT__) (((__HANDLE__)->Instance->IER) |= (__INTERRUPT__)) /** * @brief Disable the specified CAN interrupts. * @param __HANDLE__: CAN handle. * @param __INTERRUPT__: CAN Interrupt * @retval None */ #define __HAL_CAN_DISABLE_IT(__HANDLE__, __INTERRUPT__) (((__HANDLE__)->Instance->IER) &= ~(__INTERRUPT__)) /** * @brief Return the number of pending received messages. * @param __HANDLE__: CAN handle. * @param __FIFONUMBER__: Receive FIFO number, CAN_FIFO0 or CAN_FIFO1. * @retval The number of pending message. */ #define __HAL_CAN_MSG_PENDING(__HANDLE__, __FIFONUMBER__) (((__FIFONUMBER__) == CAN_FIFO0)? \ ((uint8_t)((__HANDLE__)->Instance->RF0R&(uint32_t)0x03)) : ((uint8_t)((__HANDLE__)->Instance->RF1R&(uint32_t)0x03))) /** @brief Check whether the specified CAN flag is set or not. * @param __HANDLE__: specifies the CAN Handle. * @param __FLAG__: specifies the flag to check. * This parameter can be one of the following values: * @arg CAN_TSR_RQCP0: Request MailBox0 Flag * @arg CAN_TSR_RQCP1: Request MailBox1 Flag * @arg CAN_TSR_RQCP2: Request MailBox2 Flag * @arg CAN_FLAG_TXOK0: Transmission OK MailBox0 Flag * @arg CAN_FLAG_TXOK1: Transmission OK MailBox1 Flag * @arg CAN_FLAG_TXOK2: Transmission OK MailBox2 Flag * @arg CAN_FLAG_TME0: Transmit mailbox 0 empty Flag * @arg CAN_FLAG_TME1: Transmit mailbox 1 empty Flag * @arg CAN_FLAG_TME2: Transmit mailbox 2 empty Flag * @arg CAN_FLAG_FMP0: FIFO 0 Message Pending Flag * @arg CAN_FLAG_FF0: FIFO 0 Full Flag * @arg CAN_FLAG_FOV0: FIFO 0 Overrun Flag * @arg CAN_FLAG_FMP1: FIFO 1 Message Pending Flag * @arg CAN_FLAG_FF1: FIFO 1 Full Flag * @arg CAN_FLAG_FOV1: FIFO 1 Overrun Flag * @arg CAN_FLAG_WKU: Wake up Flag * @arg CAN_FLAG_SLAK: Sleep acknowledge Flag * @arg CAN_FLAG_SLAKI: Sleep acknowledge Flag * @arg CAN_FLAG_EWG: Error Warning Flag * @arg CAN_FLAG_EPV: Error Passive Flag * @arg CAN_FLAG_BOF: Bus-Off Flag * @retval The new state of __FLAG__ (TRUE or FALSE). */ #define __HAL_CAN_GET_FLAG(__HANDLE__, __FLAG__) \ ((((__FLAG__) >> 8) == 5)? ((((__HANDLE__)->Instance->TSR) & (1 << ((__FLAG__) & CAN_FLAG_MASK))) == (1 << ((__FLAG__) & CAN_FLAG_MASK))): \ (((__FLAG__) >> 8) == 2)? ((((__HANDLE__)->Instance->RF0R) & (1 << ((__FLAG__) & CAN_FLAG_MASK))) == (1 << ((__FLAG__) & CAN_FLAG_MASK))): \ (((__FLAG__) >> 8) == 4)? ((((__HANDLE__)->Instance->RF1R) & (1 << ((__FLAG__) & CAN_FLAG_MASK))) == (1 << ((__FLAG__) & CAN_FLAG_MASK))): \ (((__FLAG__) >> 8) == 1)? ((((__HANDLE__)->Instance->MSR) & (1 << ((__FLAG__) & CAN_FLAG_MASK))) == (1 << ((__FLAG__) & CAN_FLAG_MASK))): \ ((((__HANDLE__)->Instance->ESR) & (1 << ((__FLAG__) & CAN_FLAG_MASK))) == (1 << ((__FLAG__) & CAN_FLAG_MASK)))) /** @brief Clear the specified CAN pending flag. * @param __HANDLE__: specifies the CAN Handle. * @param __FLAG__: specifies the flag to check. * This parameter can be one of the following values: * @arg CAN_TSR_RQCP0: Request MailBox0 Flag * @arg CAN_TSR_RQCP1: Request MailBox1 Flag * @arg CAN_TSR_RQCP2: Request MailBox2 Flag * @arg CAN_FLAG_TXOK0: Transmission OK MailBox0 Flag * @arg CAN_FLAG_TXOK1: Transmission OK MailBox1 Flag * @arg CAN_FLAG_TXOK2: Transmission OK MailBox2 Flag * @arg CAN_FLAG_TME0: Transmit mailbox 0 empty Flag * @arg CAN_FLAG_TME1: Transmit mailbox 1 empty Flag * @arg CAN_FLAG_TME2: Transmit mailbox 2 empty Flag * @arg CAN_FLAG_FMP0: FIFO 0 Message Pending Flag * @arg CAN_FLAG_FF0: FIFO 0 Full Flag * @arg CAN_FLAG_FOV0: FIFO 0 Overrun Flag * @arg CAN_FLAG_FMP1: FIFO 1 Message Pending Flag * @arg CAN_FLAG_FF1: FIFO 1 Full Flag * @arg CAN_FLAG_FOV1: FIFO 1 Overrun Flag * @arg CAN_FLAG_WKU: Wake up Flag * @arg CAN_FLAG_SLAKI: Sleep acknowledge Flag * @arg CAN_FLAG_EWG: Error Warning Flag * @arg CAN_FLAG_EPV: Error Passive Flag * @arg CAN_FLAG_BOF: Bus-Off Flag * @retval The new state of __FLAG__ (TRUE or FALSE). */ #define __HAL_CAN_CLEAR_FLAG(__HANDLE__, __FLAG__) \ ((((__FLAG__) >> 8U) == 5)? (((__HANDLE__)->Instance->TSR) = (1U << ((__FLAG__) & CAN_FLAG_MASK))): \ (((__FLAG__) >> 8U) == 2)? (((__HANDLE__)->Instance->RF0R) = (1U << ((__FLAG__) & CAN_FLAG_MASK))): \ (((__FLAG__) >> 8U) == 4)? (((__HANDLE__)->Instance->RF1R) = (1U << ((__FLAG__) & CAN_FLAG_MASK))): \ (((__FLAG__) >> 8U) == 1)? (((__HANDLE__)->Instance->MSR) = (1U << ((__FLAG__) & CAN_FLAG_MASK))): 0) /** @brief Check if the specified CAN interrupt source is enabled or disabled. * @param __HANDLE__: specifies the CAN Handle. * @param __INTERRUPT__: specifies the CAN interrupt source to check. * This parameter can be one of the following values: * @arg CAN_IT_TME: Transmit mailbox empty interrupt enable * @arg CAN_IT_FMP0: FIFO0 message pending interrupt enablev * @arg CAN_IT_FMP1: FIFO1 message pending interrupt enable * @retval The new state of __IT__ (TRUE or FALSE). */ #define __HAL_CAN_GET_IT_SOURCE(__HANDLE__, __INTERRUPT__) ((((__HANDLE__)->Instance->IER & (__INTERRUPT__)) == (__INTERRUPT__)) ? SET : RESET) /** * @brief Check the transmission status of a CAN Frame. * @param __HANDLE__: CAN handle. * @param __TRANSMITMAILBOX__: the number of the mailbox that is used for transmission. * @retval The new status of transmission (TRUE or FALSE). */ #define __HAL_CAN_TRANSMIT_STATUS(__HANDLE__, __TRANSMITMAILBOX__)\ (((__TRANSMITMAILBOX__) == CAN_TXMAILBOX_0)? ((((__HANDLE__)->Instance->TSR) & (CAN_TSR_RQCP0 | CAN_TSR_TXOK0 | CAN_TSR_TME0)) == (CAN_TSR_RQCP0 | CAN_TSR_TXOK0 | CAN_TSR_TME0)) :\ ((__TRANSMITMAILBOX__) == CAN_TXMAILBOX_1)? ((((__HANDLE__)->Instance->TSR) & (CAN_TSR_RQCP1 | CAN_TSR_TXOK1 | CAN_TSR_TME1)) == (CAN_TSR_RQCP1 | CAN_TSR_TXOK1 | CAN_TSR_TME1)) :\ ((((__HANDLE__)->Instance->TSR) & (CAN_TSR_RQCP2 | CAN_TSR_TXOK2 | CAN_TSR_TME2)) == (CAN_TSR_RQCP2 | CAN_TSR_TXOK2 | CAN_TSR_TME2))) /** * @brief Release the specified receive FIFO. * @param __HANDLE__: CAN handle. * @param __FIFONUMBER__: Receive FIFO number, CAN_FIFO0 or CAN_FIFO1. * @retval None */ #define __HAL_CAN_FIFO_RELEASE(__HANDLE__, __FIFONUMBER__) (((__FIFONUMBER__) == CAN_FIFO0)? \ ((__HANDLE__)->Instance->RF0R |= CAN_RF0R_RFOM0) : ((__HANDLE__)->Instance->RF1R |= CAN_RF1R_RFOM1)) /** * @brief Cancel a transmit request. * @param __HANDLE__: specifies the CAN Handle. * @param __TRANSMITMAILBOX__: the number of the mailbox that is used for transmission. * @retval None */ #define __HAL_CAN_CANCEL_TRANSMIT(__HANDLE__, __TRANSMITMAILBOX__)\ (((__TRANSMITMAILBOX__) == CAN_TXMAILBOX_0)? ((__HANDLE__)->Instance->TSR |= CAN_TSR_ABRQ0) :\ ((__TRANSMITMAILBOX__) == CAN_TXMAILBOX_1)? ((__HANDLE__)->Instance->TSR |= CAN_TSR_ABRQ1) :\ ((__HANDLE__)->Instance->TSR |= CAN_TSR_ABRQ2)) /** * @brief Enable or disables the DBG Freeze for CAN. * @param __HANDLE__: specifies the CAN Handle. * @param __NEWSTATE__: new state of the CAN peripheral. * This parameter can be: ENABLE (CAN reception/transmission is frozen * during debug. Reception FIFOs can still be accessed/controlled normally) * or DISABLE (CAN is working during debug). * @retval None */ #define __HAL_CAN_DBG_FREEZE(__HANDLE__, __NEWSTATE__) (((__NEWSTATE__) == ENABLE)? \ ((__HANDLE__)->Instance->MCR |= CAN_MCR_DBF) : ((__HANDLE__)->Instance->MCR &= ~CAN_MCR_DBF)) /** * @} */ /* Exported functions --------------------------------------------------------*/ /** @addtogroup CAN_Exported_Functions CAN Exported Functions * @{ */ /** @addtogroup CAN_Exported_Functions_Group1 Initialization and de-initialization functions * @brief Initialization and Configuration functions * @{ */ /* Initialization and de-initialization functions *****************************/ HAL_StatusTypeDef HAL_CAN_Init(CAN_HandleTypeDef* hcan); HAL_StatusTypeDef HAL_CAN_ConfigFilter(CAN_HandleTypeDef* hcan, CAN_FilterConfTypeDef* sFilterConfig); HAL_StatusTypeDef HAL_CAN_DeInit(CAN_HandleTypeDef* hcan); void HAL_CAN_MspInit(CAN_HandleTypeDef* hcan); void HAL_CAN_MspDeInit(CAN_HandleTypeDef* hcan); /** * @} */ /** @addtogroup CAN_Exported_Functions_Group2 Input and Output operation functions * @brief I/O operation functions * @{ */ /* IO operation functions *****************************************************/ HAL_StatusTypeDef HAL_CAN_Transmit(CAN_HandleTypeDef *hcan, uint32_t Timeout); HAL_StatusTypeDef HAL_CAN_Transmit_IT(CAN_HandleTypeDef *hcan); HAL_StatusTypeDef HAL_CAN_Receive(CAN_HandleTypeDef *hcan, uint8_t FIFONumber, uint32_t Timeout); HAL_StatusTypeDef HAL_CAN_Receive_IT(CAN_HandleTypeDef *hcan, uint8_t FIFONumber); HAL_StatusTypeDef HAL_CAN_Sleep(CAN_HandleTypeDef *hcan); HAL_StatusTypeDef HAL_CAN_WakeUp(CAN_HandleTypeDef *hcan); void HAL_CAN_IRQHandler(CAN_HandleTypeDef* hcan); void HAL_CAN_TxCpltCallback(CAN_HandleTypeDef* hcan); void HAL_CAN_RxCpltCallback(CAN_HandleTypeDef* hcan); void HAL_CAN_ErrorCallback(CAN_HandleTypeDef *hcan); /** * @} */ /** @addtogroup CAN_Exported_Functions_Group3 Peripheral State and Error functions * @brief CAN Peripheral State functions * @{ */ /* Peripheral State and Error functions ***************************************/ uint32_t HAL_CAN_GetError(CAN_HandleTypeDef *hcan); HAL_CAN_StateTypeDef HAL_CAN_GetState(CAN_HandleTypeDef* hcan); /** * @} */ /** * @} */ /* Private types -------------------------------------------------------------*/ /** @defgroup CAN_Private_Types CAN Private Types * @{ */ /** * @} */ /* Private variables ---------------------------------------------------------*/ /** @defgroup CAN_Private_Variables CAN Private Variables * @{ */ /** * @} */ /* Private constants ---------------------------------------------------------*/ /** @defgroup CAN_Private_Constants CAN Private Constants * @{ */ #define CAN_TXSTATUS_NOMAILBOX ((uint8_t)0x04) /*!< CAN cell did not provide CAN_TxStatus_NoMailBox */ #define CAN_FLAG_MASK ((uint32_t)0x000000FF) /** * @} */ /* Private macros ------------------------------------------------------------*/ /** @defgroup CAN_Private_Macros CAN Private Macros * @{ */ #define IS_CAN_MODE(MODE) (((MODE) == CAN_MODE_NORMAL) || \ ((MODE) == CAN_MODE_LOOPBACK)|| \ ((MODE) == CAN_MODE_SILENT) || \ ((MODE) == CAN_MODE_SILENT_LOOPBACK)) #define IS_CAN_SJW(SJW) (((SJW) == CAN_SJW_1TQ) || ((SJW) == CAN_SJW_2TQ)|| \ ((SJW) == CAN_SJW_3TQ) || ((SJW) == CAN_SJW_4TQ)) #define IS_CAN_BS1(BS1) ((BS1) <= CAN_BS1_16TQ) #define IS_CAN_BS2(BS2) ((BS2) <= CAN_BS2_8TQ) #define IS_CAN_PRESCALER(PRESCALER) (((PRESCALER) >= 1) && ((PRESCALER) <= 1024)) #define IS_CAN_FILTER_NUMBER(NUMBER) ((NUMBER) <= 27) #define IS_CAN_FILTER_MODE(MODE) (((MODE) == CAN_FILTERMODE_IDMASK) || \ ((MODE) == CAN_FILTERMODE_IDLIST)) #define IS_CAN_FILTER_SCALE(SCALE) (((SCALE) == CAN_FILTERSCALE_16BIT) || \ ((SCALE) == CAN_FILTERSCALE_32BIT)) #define IS_CAN_FILTER_FIFO(FIFO) (((FIFO) == CAN_FILTER_FIFO0) || \ ((FIFO) == CAN_FILTER_FIFO1)) #define IS_CAN_BANKNUMBER(BANKNUMBER) ((BANKNUMBER) <= 28) #define IS_CAN_TRANSMITMAILBOX(TRANSMITMAILBOX) ((TRANSMITMAILBOX) <= ((uint8_t)0x02)) #define IS_CAN_STDID(STDID) ((STDID) <= ((uint32_t)0x7FF)) #define IS_CAN_EXTID(EXTID) ((EXTID) <= ((uint32_t)0x1FFFFFFF)) #define IS_CAN_DLC(DLC) ((DLC) <= ((uint8_t)0x08)) #define IS_CAN_IDTYPE(IDTYPE) (((IDTYPE) == CAN_ID_STD) || \ ((IDTYPE) == CAN_ID_EXT)) #define IS_CAN_RTR(RTR) (((RTR) == CAN_RTR_DATA) || ((RTR) == CAN_RTR_REMOTE)) #define IS_CAN_FIFO(FIFO) (((FIFO) == CAN_FIFO0) || ((FIFO) == CAN_FIFO1)) /** * @} */ /* Private functions ---------------------------------------------------------*/ /** @defgroup CAN_Private_Functions CAN Private Functions * @{ */ /** * @} */ /** * @} */ /** * @} */ #endif /* STM32F072xB || STM32F042x6 || STM32F048xx || STM32F078xx || STM32F091xC || STM32F098xx */ #ifdef __cplusplus } #endif #endif /* __STM32F0xx_HAL_CAN_H */ /************************ (C) COPYRIGHT STMicroelectronics *****END OF FILE****/ ================================================ FILE: Zelig/mbed/TARGET_NUCLEO_F091RC/stm32f0xx_hal_cec.h ================================================ /** ****************************************************************************** * @file stm32f0xx_hal_cec.h * @author MCD Application Team * @version V1.3.0 * @date 26-June-2015 * @brief Header file of CEC HAL module. ****************************************************************************** * @attention * *

© COPYRIGHT(c) 2015 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. * ****************************************************************************** */ /* Define to prevent recursive inclusion -------------------------------------*/ #ifndef __STM32F0xx_HAL_CEC_H #define __STM32F0xx_HAL_CEC_H #ifdef __cplusplus extern "C" { #endif #if defined(STM32F042x6) || defined(STM32F048xx) ||\ defined(STM32F051x8) || defined(STM32F058xx) ||\ defined(STM32F071xB) || defined(STM32F072xB) || defined(STM32F078xx) ||\ defined(STM32F091xC) || defined(STM32F098xx) /* Includes ------------------------------------------------------------------*/ #include "stm32f0xx_hal_def.h" /** @addtogroup STM32F0xx_HAL_Driver * @{ */ /** @addtogroup CEC CEC * @{ */ /* Exported types ------------------------------------------------------------*/ /** @defgroup CEC_Exported_Types CEC Exported Types * @{ */ /** * @brief CEC Init Structure definition */ typedef struct { uint32_t SignalFreeTime; /*!< Set SFT field, specifies the Signal Free Time. It can be one of @ref CEC_Signal_Free_Time and belongs to the set {0,...,7} where 0x0 is the default configuration else means 0.5 + (SignalFreeTime - 1) nominal data bit periods */ uint32_t Tolerance; /*!< Set RXTOL bit, specifies the tolerance accepted on the received waveforms, it can be a value of @ref CEC_Tolerance : it is either CEC_STANDARD_TOLERANCE or CEC_EXTENDED_TOLERANCE */ uint32_t BRERxStop; /*!< Set BRESTP bit @ref CEC_BRERxStop : specifies whether or not a Bit Rising Error stops the reception. CEC_NO_RX_STOP_ON_BRE: reception is not stopped. CEC_RX_STOP_ON_BRE: reception is stopped. */ uint32_t BREErrorBitGen; /*!< Set BREGEN bit @ref CEC_BREErrorBitGen : specifies whether or not an Error-Bit is generated on the CEC line upon Bit Rising Error detection. CEC_BRE_ERRORBIT_NO_GENERATION: no error-bit generation. CEC_BRE_ERRORBIT_GENERATION: error-bit generation if BRESTP is set. */ uint32_t LBPEErrorBitGen; /*!< Set LBPEGEN bit @ref CEC_LBPEErrorBitGen : specifies whether or not an Error-Bit is generated on the CEC line upon Long Bit Period Error detection. CEC_LBPE_ERRORBIT_NO_GENERATION: no error-bit generation. CEC_LBPE_ERRORBIT_GENERATION: error-bit generation. */ uint32_t BroadcastMsgNoErrorBitGen; /*!< Set BRDNOGEN bit @ref CEC_BroadCastMsgErrorBitGen : allows to avoid an Error-Bit generation on the CEC line upon an error detected on a broadcast message. It supersedes BREGEN and LBPEGEN bits for a broadcast message error handling. It can take two values: 1) CEC_BROADCASTERROR_ERRORBIT_GENERATION. a) BRE detection: error-bit generation on the CEC line if BRESTP=CEC_RX_STOP_ON_BRE and BREGEN=CEC_BRE_ERRORBIT_NO_GENERATION. b) LBPE detection: error-bit generation on the CEC line if LBPGEN=CEC_LBPE_ERRORBIT_NO_GENERATION. 2) CEC_BROADCASTERROR_NO_ERRORBIT_GENERATION. no error-bit generation in case neither a) nor b) are satisfied. Additionally, there is no error-bit generation in case of Short Bit Period Error detection in a broadcast message while LSTN bit is set. */ uint32_t SignalFreeTimeOption; /*!< Set SFTOP bit @ref CEC_SFT_Option : specifies when SFT timer starts. CEC_SFT_START_ON_TXSOM SFT: timer starts when TXSOM is set by software. CEC_SFT_START_ON_TX_RX_END: SFT timer starts automatically at the end of message transmission/reception. */ uint32_t OwnAddress; /*!< Set OAR field, specifies CEC device address within a 15-bit long field */ uint32_t ListenMode; /*!< Set LSTN bit @ref CEC_Listening_Mode : specifies device listening mode. It can take two values: CEC_REDUCED_LISTENING_MODE: CEC peripheral receives only message addressed to its own address (OAR). Messages addressed to different destination are ignored. Broadcast messages are always received. CEC_FULL_LISTENING_MODE: CEC peripheral receives messages addressed to its own address (OAR) with positive acknowledge. Messages addressed to different destination are received, but without interfering with the CEC bus: no acknowledge sent. */ uint8_t InitiatorAddress; /* Initiator address (source logical address, sent in each header) */ }CEC_InitTypeDef; /** * @brief HAL CEC State structures definition */ typedef enum { HAL_CEC_STATE_RESET = 0x00, /*!< Peripheral Reset state */ HAL_CEC_STATE_READY = 0x01, /*!< Peripheral Initialized and ready for use */ HAL_CEC_STATE_BUSY = 0x02, /*!< an internal process is ongoing */ HAL_CEC_STATE_BUSY_TX = 0x03, /*!< Data Transmission process is ongoing */ HAL_CEC_STATE_BUSY_RX = 0x04, /*!< Data Reception process is ongoing */ HAL_CEC_STATE_STANDBY_RX = 0x05, /*!< IP ready to receive, doesn't prevent IP to transmit */ HAL_CEC_STATE_TIMEOUT = 0x06, /*!< Timeout state */ HAL_CEC_STATE_ERROR = 0x07 /*!< State Error */ }HAL_CEC_StateTypeDef; /** * @brief CEC handle Structure definition */ typedef struct { CEC_TypeDef *Instance; /* CEC registers base address */ CEC_InitTypeDef Init; /* CEC communication parameters */ uint8_t *pTxBuffPtr; /* Pointer to CEC Tx transfer Buffer */ uint16_t TxXferCount; /* CEC Tx Transfer Counter */ uint8_t *pRxBuffPtr; /* Pointer to CEC Rx transfer Buffer */ uint16_t RxXferSize; /* CEC Rx Transfer size, 0: header received only */ uint32_t ErrorCode; /* For errors handling purposes, copy of ISR register in case error is reported */ HAL_LockTypeDef Lock; /* Locking object */ HAL_CEC_StateTypeDef State; /* CEC communication state */ }CEC_HandleTypeDef; /** * @} */ /* Exported constants --------------------------------------------------------*/ /** @defgroup CEC_Exported_Constants CEC Exported Constants * @{ */ /** @defgroup CEC_Error_Code CEC Error Code * @{ */ #define HAL_CEC_ERROR_NONE (uint32_t) 0x0 /*!< no error */ #define HAL_CEC_ERROR_RXOVR CEC_ISR_RXOVR /*!< CEC Rx-Overrun */ #define HAL_CEC_ERROR_BRE CEC_ISR_BRE /*!< CEC Rx Bit Rising Error */ #define HAL_CEC_ERROR_SBPE CEC_ISR_SBPE /*!< CEC Rx Short Bit period Error */ #define HAL_CEC_ERROR_LBPE CEC_ISR_LBPE /*!< CEC Rx Long Bit period Error */ #define HAL_CEC_ERROR_RXACKE CEC_ISR_RXACKE /*!< CEC Rx Missing Acknowledge */ #define HAL_CEC_ERROR_ARBLST CEC_ISR_ARBLST /*!< CEC Arbitration Lost */ #define HAL_CEC_ERROR_TXUDR CEC_ISR_TXUDR /*!< CEC Tx-Buffer Underrun */ #define HAL_CEC_ERROR_TXERR CEC_ISR_TXERR /*!< CEC Tx-Error */ #define HAL_CEC_ERROR_TXACKE CEC_ISR_TXACKE /*!< CEC Tx Missing Acknowledge */ /** * @} */ /** @defgroup CEC_Signal_Free_Time Signal Free Time setting parameter * @{ */ #define CEC_DEFAULT_SFT ((uint32_t)0x00000000) #define CEC_0_5_BITPERIOD_SFT ((uint32_t)0x00000001) #define CEC_1_5_BITPERIOD_SFT ((uint32_t)0x00000002) #define CEC_2_5_BITPERIOD_SFT ((uint32_t)0x00000003) #define CEC_3_5_BITPERIOD_SFT ((uint32_t)0x00000004) #define CEC_4_5_BITPERIOD_SFT ((uint32_t)0x00000005) #define CEC_5_5_BITPERIOD_SFT ((uint32_t)0x00000006) #define CEC_6_5_BITPERIOD_SFT ((uint32_t)0x00000007) /** * @} */ /** @defgroup CEC_Tolerance Receiver Tolerance * @{ */ #define CEC_STANDARD_TOLERANCE ((uint32_t)0x00000000) #define CEC_EXTENDED_TOLERANCE ((uint32_t)CEC_CFGR_RXTOL) /** * @} */ /** @defgroup CEC_BRERxStop Reception Stop on Error * @{ */ #define CEC_NO_RX_STOP_ON_BRE ((uint32_t)0x00000000) #define CEC_RX_STOP_ON_BRE ((uint32_t)CEC_CFGR_BRESTP) /** * @} */ /** @defgroup CEC_BREErrorBitGen Error Bit Generation if Bit Rise Error reported * @{ */ #define CEC_BRE_ERRORBIT_NO_GENERATION ((uint32_t)0x00000000) #define CEC_BRE_ERRORBIT_GENERATION ((uint32_t)CEC_CFGR_BREGEN) /** * @} */ /** @defgroup CEC_LBPEErrorBitGen Error Bit Generation if Long Bit Period Error reported * @{ */ #define CEC_LBPE_ERRORBIT_NO_GENERATION ((uint32_t)0x00000000) #define CEC_LBPE_ERRORBIT_GENERATION ((uint32_t)CEC_CFGR_LBPEGEN) /** * @} */ /** @defgroup CEC_BroadCastMsgErrorBitGen Error Bit Generation on Broadcast message * @{ */ #define CEC_BROADCASTERROR_ERRORBIT_GENERATION ((uint32_t)0x00000000) #define CEC_BROADCASTERROR_NO_ERRORBIT_GENERATION ((uint32_t)CEC_CFGR_BRDNOGEN) /** * @} */ /** @defgroup CEC_SFT_Option Signal Free Time start option * @{ */ #define CEC_SFT_START_ON_TXSOM ((uint32_t)0x00000000) #define CEC_SFT_START_ON_TX_RX_END ((uint32_t)CEC_CFGR_SFTOPT) /** * @} */ /** @defgroup CEC_Listening_Mode Listening mode option * @{ */ #define CEC_REDUCED_LISTENING_MODE ((uint32_t)0x00000000) #define CEC_FULL_LISTENING_MODE ((uint32_t)CEC_CFGR_LSTN) /** * @} */ /** @defgroup CEC_OAR_Position Device Own Address position in CEC CFGR register * @{ */ #define CEC_CFGR_OAR_LSB_POS ((uint32_t) 16) /** * @} */ /** @defgroup CEC_Initiator_Position Initiator logical address position in message header * @{ */ #define CEC_INITIATOR_LSB_POS ((uint32_t) 4) /** * @} */ /** @defgroup CEC_Interrupts_Definitions CEC Interrupts definition * @{ */ #define CEC_IT_TXACKE CEC_IER_TXACKEIE #define CEC_IT_TXERR CEC_IER_TXERRIE #define CEC_IT_TXUDR CEC_IER_TXUDRIE #define CEC_IT_TXEND CEC_IER_TXENDIE #define CEC_IT_TXBR CEC_IER_TXBRIE #define CEC_IT_ARBLST CEC_IER_ARBLSTIE #define CEC_IT_RXACKE CEC_IER_RXACKEIE #define CEC_IT_LBPE CEC_IER_LBPEIE #define CEC_IT_SBPE CEC_IER_SBPEIE #define CEC_IT_BRE CEC_IER_BREIE #define CEC_IT_RXOVR CEC_IER_RXOVRIE #define CEC_IT_RXEND CEC_IER_RXENDIE #define CEC_IT_RXBR CEC_IER_RXBRIE /** * @} */ /** @defgroup CEC_Flags_Definitions CEC Flags definition * @{ */ #define CEC_FLAG_TXACKE CEC_ISR_TXACKE #define CEC_FLAG_TXERR CEC_ISR_TXERR #define CEC_FLAG_TXUDR CEC_ISR_TXUDR #define CEC_FLAG_TXEND CEC_ISR_TXEND #define CEC_FLAG_TXBR CEC_ISR_TXBR #define CEC_FLAG_ARBLST CEC_ISR_ARBLST #define CEC_FLAG_RXACKE CEC_ISR_RXACKE #define CEC_FLAG_LBPE CEC_ISR_LBPE #define CEC_FLAG_SBPE CEC_ISR_SBPE #define CEC_FLAG_BRE CEC_ISR_BRE #define CEC_FLAG_RXOVR CEC_ISR_RXOVR #define CEC_FLAG_RXEND CEC_ISR_RXEND #define CEC_FLAG_RXBR CEC_ISR_RXBR /** * @} */ /** @defgroup CEC_ALL_ERROR all RX or TX errors flags in CEC ISR register * @{ */ #define CEC_ISR_ALL_ERROR ((uint32_t)CEC_ISR_RXOVR|CEC_ISR_BRE|CEC_ISR_SBPE|CEC_ISR_LBPE|CEC_ISR_RXACKE|\ CEC_ISR_ARBLST|CEC_ISR_TXUDR|CEC_ISR_TXERR|CEC_ISR_TXACKE) /** * @} */ /** @defgroup CEC_IER_ALL_RX all RX errors interrupts enabling flag * @{ */ #define CEC_IER_RX_ALL_ERR ((uint32_t)CEC_IER_RXACKEIE|CEC_IER_LBPEIE|CEC_IER_SBPEIE|CEC_IER_BREIE|CEC_IER_RXOVRIE) /** * @} */ /** @defgroup CEC_IER_ALL_TX all TX errors interrupts enabling flag * @{ */ #define CEC_IER_TX_ALL_ERR ((uint32_t)CEC_IER_TXACKEIE|CEC_IER_TXERRIE|CEC_IER_TXUDRIE|CEC_IER_ARBLSTIE) /** * @} */ /** * @} */ /* Exported macros -----------------------------------------------------------*/ /** @defgroup CEC_Exported_Macros CEC Exported Macros * @{ */ /** @brief Reset CEC handle state * @param __HANDLE__: CEC handle. * @retval None */ #define __HAL_CEC_RESET_HANDLE_STATE(__HANDLE__) ((__HANDLE__)->State = HAL_CEC_STATE_RESET) /** @brief Checks whether or not the specified CEC interrupt flag is set. * @param __HANDLE__: specifies the CEC Handle. * @param __FLAG__: specifies the interrupt to check. * @arg CEC_FLAG_TXACKE: Tx Missing acknowledge Error * @arg CEC_FLAG_TXERR: Tx Error. * @arg CEC_FLAG_TXUDR: Tx-Buffer Underrun. * @arg CEC_FLAG_TXEND: End of transmission (successful transmission of the last byte). * @arg CEC_FLAG_TXBR: Tx-Byte Request. * @arg CEC_FLAG_ARBLST: Arbitration Lost * @arg CEC_FLAG_RXACKE: Rx-Missing Acknowledge * @arg CEC_FLAG_LBPE: Rx Long period Error * @arg CEC_FLAG_SBPE: Rx Short period Error * @arg CEC_FLAG_BRE: Rx Bit Rissing Error * @arg CEC_FLAG_RXOVR: Rx Overrun. * @arg CEC_FLAG_RXEND: End Of Reception. * @arg CEC_FLAG_RXBR: Rx-Byte Received. * @retval None */ #define __HAL_CEC_GET_FLAG(__HANDLE__, __FLAG__) ((__HANDLE__)->Instance->ISR & (__FLAG__)) /** @brief Clears the interrupt or status flag when raised (write at 1) * @param __HANDLE__: specifies the CEC Handle. * @param __FLAG__: specifies the interrupt/status flag to clear. * This parameter can be one of the following values: * @arg CEC_FLAG_TXACKE: Tx Missing acknowledge Error * @arg CEC_FLAG_TXERR: Tx Error. * @arg CEC_FLAG_TXUDR: Tx-Buffer Underrun. * @arg CEC_FLAG_TXEND: End of transmission (successful transmission of the last byte). * @arg CEC_FLAG_TXBR: Tx-Byte Request. * @arg CEC_FLAG_ARBLST: Arbitration Lost * @arg CEC_FLAG_RXACKE: Rx-Missing Acknowledge * @arg CEC_FLAG_LBPE: Rx Long period Error * @arg CEC_FLAG_SBPE: Rx Short period Error * @arg CEC_FLAG_BRE: Rx Bit Rissing Error * @arg CEC_FLAG_RXOVR: Rx Overrun. * @arg CEC_FLAG_RXEND: End Of Reception. * @arg CEC_FLAG_RXBR: Rx-Byte Received. * @retval none */ #define __HAL_CEC_CLEAR_FLAG(__HANDLE__, __FLAG__) ((__HANDLE__)->Instance->ISR |= (__FLAG__)) /** @brief Enables the specified CEC interrupt. * @param __HANDLE__: specifies the CEC Handle. * @param __INTERRUPT__: specifies the CEC interrupt to enable. * This parameter can be one of the following values: * @arg CEC_IT_TXACKE: Tx Missing acknowledge Error IT Enable * @arg CEC_IT_TXERR: Tx Error IT Enable * @arg CEC_IT_TXUDR: Tx-Buffer Underrun IT Enable * @arg CEC_IT_TXEND: End of transmission IT Enable * @arg CEC_IT_TXBR: Tx-Byte Request IT Enable * @arg CEC_IT_ARBLST: Arbitration Lost IT Enable * @arg CEC_IT_RXACKE: Rx-Missing Acknowledge IT Enable * @arg CEC_IT_LBPE: Rx Long period Error IT Enable * @arg CEC_IT_SBPE: Rx Short period Error IT Enable * @arg CEC_IT_BRE: Rx Bit Rising Error IT Enable * @arg CEC_IT_RXOVR: Rx Overrun IT Enable * @arg CEC_IT_RXEND: End Of Reception IT Enable * @arg CEC_IT_RXBR: Rx-Byte Received IT Enable * @retval none */ #define __HAL_CEC_ENABLE_IT(__HANDLE__, __INTERRUPT__) ((__HANDLE__)->Instance->IER |= (__INTERRUPT__)) /** @brief Disables the specified CEC interrupt. * @param __HANDLE__: specifies the CEC Handle. * @param __INTERRUPT__: specifies the CEC interrupt to disable. * This parameter can be one of the following values: * @arg CEC_IT_TXACKE: Tx Missing acknowledge Error IT Enable * @arg CEC_IT_TXERR: Tx Error IT Enable * @arg CEC_IT_TXUDR: Tx-Buffer Underrun IT Enable * @arg CEC_IT_TXEND: End of transmission IT Enable * @arg CEC_IT_TXBR: Tx-Byte Request IT Enable * @arg CEC_IT_ARBLST: Arbitration Lost IT Enable * @arg CEC_IT_RXACKE: Rx-Missing Acknowledge IT Enable * @arg CEC_IT_LBPE: Rx Long period Error IT Enable * @arg CEC_IT_SBPE: Rx Short period Error IT Enable * @arg CEC_IT_BRE: Rx Bit Rising Error IT Enable * @arg CEC_IT_RXOVR: Rx Overrun IT Enable * @arg CEC_IT_RXEND: End Of Reception IT Enable * @arg CEC_IT_RXBR: Rx-Byte Received IT Enable * @retval none */ #define __HAL_CEC_DISABLE_IT(__HANDLE__, __INTERRUPT__) ((__HANDLE__)->Instance->IER &= (~(__INTERRUPT__))) /** @brief Checks whether or not the specified CEC interrupt is enabled. * @param __HANDLE__: specifies the CEC Handle. * @param __INTERRUPT__: specifies the CEC interrupt to check. * This parameter can be one of the following values: * @arg CEC_IT_TXACKE: Tx Missing acknowledge Error IT Enable * @arg CEC_IT_TXERR: Tx Error IT Enable * @arg CEC_IT_TXUDR: Tx-Buffer Underrun IT Enable * @arg CEC_IT_TXEND: End of transmission IT Enable * @arg CEC_IT_TXBR: Tx-Byte Request IT Enable * @arg CEC_IT_ARBLST: Arbitration Lost IT Enable * @arg CEC_IT_RXACKE: Rx-Missing Acknowledge IT Enable * @arg CEC_IT_LBPE: Rx Long period Error IT Enable * @arg CEC_IT_SBPE: Rx Short period Error IT Enable * @arg CEC_IT_BRE: Rx Bit Rising Error IT Enable * @arg CEC_IT_RXOVR: Rx Overrun IT Enable * @arg CEC_IT_RXEND: End Of Reception IT Enable * @arg CEC_IT_RXBR: Rx-Byte Received IT Enable * @retval FlagStatus */ #define __HAL_CEC_GET_IT_SOURCE(__HANDLE__, __INTERRUPT__) ((__HANDLE__)->Instance->IER & (__INTERRUPT__)) /** @brief Enables the CEC device * @param __HANDLE__: specifies the CEC Handle. * @retval none */ #define __HAL_CEC_ENABLE(__HANDLE__) ((__HANDLE__)->Instance->CR |= CEC_CR_CECEN) /** @brief Disables the CEC device * @param __HANDLE__: specifies the CEC Handle. * @retval none */ #define __HAL_CEC_DISABLE(__HANDLE__) ((__HANDLE__)->Instance->CR &= ~CEC_CR_CECEN) /** @brief Set Transmission Start flag * @param __HANDLE__: specifies the CEC Handle. * @retval none */ #define __HAL_CEC_FIRST_BYTE_TX_SET(__HANDLE__) ((__HANDLE__)->Instance->CR |= CEC_CR_TXSOM) /** @brief Set Transmission End flag * @param __HANDLE__: specifies the CEC Handle. * @retval none * If the CEC message consists of only one byte, TXEOM must be set before of TXSOM. */ #define __HAL_CEC_LAST_BYTE_TX_SET(__HANDLE__) ((__HANDLE__)->Instance->CR |= CEC_CR_TXEOM) /** @brief Get Transmission Start flag * @param __HANDLE__: specifies the CEC Handle. * @retval FlagStatus */ #define __HAL_CEC_GET_TRANSMISSION_START_FLAG(__HANDLE__) ((__HANDLE__)->Instance->CR & CEC_CR_TXSOM) /** @brief Get Transmission End flag * @param __HANDLE__: specifies the CEC Handle. * @retval FlagStatus */ #define __HAL_CEC_GET_TRANSMISSION_END_FLAG(__HANDLE__) ((__HANDLE__)->Instance->CR & CEC_CR_TXEOM) /** @brief Clear OAR register * @param __HANDLE__: specifies the CEC Handle. * @retval none */ #define __HAL_CEC_CLEAR_OAR(__HANDLE__) CLEAR_BIT((__HANDLE__)->Instance->CFGR, CEC_CFGR_OAR) /** @brief Set OAR register (without resetting previously set address in case of multi-address mode) * To reset OAR, __HAL_CEC_CLEAR_OAR() needs to be called beforehand * @param __HANDLE__: specifies the CEC Handle. * @param __ADDRESS__: Own Address value (CEC logical address is identified by bit position) * @retval none */ #define __HAL_CEC_SET_OAR(__HANDLE__,__ADDRESS__) SET_BIT((__HANDLE__)->Instance->CFGR, (__ADDRESS__)<< CEC_CFGR_OAR_LSB_POS) /** * @} */ /* Exported functions --------------------------------------------------------*/ /** @addtogroup CEC_Exported_Functions * @{ */ /** @addtogroup CEC_Exported_Functions_Group1 * @{ */ /* Initialization and de-initialization functions ****************************/ HAL_StatusTypeDef HAL_CEC_Init(CEC_HandleTypeDef *hcec); HAL_StatusTypeDef HAL_CEC_DeInit(CEC_HandleTypeDef *hcec); void HAL_CEC_MspInit(CEC_HandleTypeDef *hcec); void HAL_CEC_MspDeInit(CEC_HandleTypeDef *hcec); /** * @} */ /** @addtogroup CEC_Exported_Functions_Group2 * @{ */ /* I/O operation functions ***************************************************/ HAL_StatusTypeDef HAL_CEC_Transmit(CEC_HandleTypeDef *hcec, uint8_t DestinationAddress, uint8_t *pData, uint32_t Size, uint32_t Timeout); HAL_StatusTypeDef HAL_CEC_Receive(CEC_HandleTypeDef *hcec, uint8_t *pData, uint32_t Timeout); HAL_StatusTypeDef HAL_CEC_Transmit_IT(CEC_HandleTypeDef *hcec, uint8_t DestinationAddress, uint8_t *pData, uint32_t Size); HAL_StatusTypeDef HAL_CEC_Receive_IT(CEC_HandleTypeDef *hcec, uint8_t *pData); uint32_t HAL_CEC_GetReceivedFrameSize(CEC_HandleTypeDef *hcec); void HAL_CEC_IRQHandler(CEC_HandleTypeDef *hcec); void HAL_CEC_TxCpltCallback(CEC_HandleTypeDef *hcec); void HAL_CEC_RxCpltCallback(CEC_HandleTypeDef *hcec); void HAL_CEC_ErrorCallback(CEC_HandleTypeDef *hcec); /** * @} */ /** @addtogroup CEC_Exported_Functions_Group3 * @{ */ /* Peripheral State functions ************************************************/ HAL_CEC_StateTypeDef HAL_CEC_GetState(CEC_HandleTypeDef *hcec); uint32_t HAL_CEC_GetError(CEC_HandleTypeDef *hcec); /** * @} */ /** * @} */ /* Private types -------------------------------------------------------------*/ /** @defgroup CEC_Private_Types CEC Private Types * @{ */ /** * @} */ /* Private variables ---------------------------------------------------------*/ /** @defgroup CEC_Private_Variables CEC Private Variables * @{ */ /** * @} */ /* Private constants ---------------------------------------------------------*/ /** @defgroup CEC_Private_Constants CEC Private Constants * @{ */ /** * @} */ /* Private macros ------------------------------------------------------------*/ /** @defgroup CEC_Private_Macros CEC Private Macros * @{ */ #define IS_CEC_SIGNALFREETIME(__SFT__) ((__SFT__) <= CEC_CFGR_SFT) #define IS_CEC_TOLERANCE(__RXTOL__) (((__RXTOL__) == CEC_STANDARD_TOLERANCE) || \ ((__RXTOL__) == CEC_EXTENDED_TOLERANCE)) #define IS_CEC_BRERXSTOP(__BRERXSTOP__) (((__BRERXSTOP__) == CEC_NO_RX_STOP_ON_BRE) || \ ((__BRERXSTOP__) == CEC_RX_STOP_ON_BRE)) #define IS_CEC_BREERRORBITGEN(__ERRORBITGEN__) (((__ERRORBITGEN__) == CEC_BRE_ERRORBIT_NO_GENERATION) || \ ((__ERRORBITGEN__) == CEC_BRE_ERRORBIT_GENERATION)) #define IS_CEC_LBPEERRORBITGEN(__ERRORBITGEN__) (((__ERRORBITGEN__) == CEC_LBPE_ERRORBIT_NO_GENERATION) || \ ((__ERRORBITGEN__) == CEC_LBPE_ERRORBIT_GENERATION)) #define IS_CEC_BROADCASTERROR_NO_ERRORBIT_GENERATION(__ERRORBITGEN__) (((__ERRORBITGEN__) == CEC_BROADCASTERROR_ERRORBIT_GENERATION) || \ ((__ERRORBITGEN__) == CEC_BROADCASTERROR_NO_ERRORBIT_GENERATION)) #define IS_CEC_SFTOP(__SFTOP__) (((__SFTOP__) == CEC_SFT_START_ON_TXSOM) || \ ((__SFTOP__) == CEC_SFT_START_ON_TX_RX_END)) #define IS_CEC_LISTENING_MODE(__MODE__) (((__MODE__) == CEC_REDUCED_LISTENING_MODE) || \ ((__MODE__) == CEC_FULL_LISTENING_MODE)) /** @brief Check CEC device Own Address Register (OAR) setting. * OAR address is written in a 15-bit field within CEC_CFGR register. * @param __ADDRESS__: CEC own address. * @retval Test result (TRUE or FALSE). */ #define IS_CEC_OAR_ADDRESS(__ADDRESS__) ((__ADDRESS__) <= 0x07FFF) /** @brief Check CEC initiator or destination logical address setting. * Initiator and destination addresses are coded over 4 bits. * @param __ADDRESS__: CEC initiator or logical address. * @retval Test result (TRUE or FALSE). */ #define IS_CEC_ADDRESS(__ADDRESS__) ((__ADDRESS__) <= 0xF) /** @brief Check CEC message size. * The message size is the payload size: without counting the header, * it varies from 0 byte (ping operation, one header only, no payload) to * 15 bytes (1 opcode and up to 14 operands following the header). * @param __SIZE__: CEC message size. * @retval Test result (TRUE or FALSE). */ #define IS_CEC_MSGSIZE(__SIZE__) ((__SIZE__) <= 0xF) /** * @} */ /* Private functions ---------------------------------------------------------*/ /** @defgroup CEC_Private_Functions CEC Private Functions * @{ */ /** * @} */ /** * @} */ /** * @} */ #endif /* defined(STM32F042x6) || defined(STM32F048xx) || */ /* defined(STM32F051x8) || defined(STM32F058xx) || */ /* defined(STM32F071xB) || defined(STM32F072xB) || defined(STM32F078xx) || */ /* defined(STM32F091xC) || defined(STM32F098xx) */ #ifdef __cplusplus } #endif #endif /* __STM32F0xx_HAL_CEC_H */ /************************ (C) COPYRIGHT STMicroelectronics *****END OF FILE****/ ================================================ FILE: Zelig/mbed/TARGET_NUCLEO_F091RC/stm32f0xx_hal_comp.h ================================================ /** ****************************************************************************** * @file stm32f0xx_hal_comp.h * @author MCD Application Team * @version V1.3.0 * @date 26-June-2015 * @brief Header file of COMP HAL module. ****************************************************************************** * @attention * *

© COPYRIGHT(c) 2015 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. * ****************************************************************************** */ /* Define to prevent recursive inclusion -------------------------------------*/ #ifndef __STM32F0xx_HAL_COMP_H #define __STM32F0xx_HAL_COMP_H #ifdef __cplusplus extern "C" { #endif #if defined(STM32F051x8) || defined(STM32F058xx) || \ defined(STM32F071xB) || defined(STM32F072xB) || defined(STM32F078xx) || \ defined(STM32F091xC) || defined(STM32F098xx) /* Includes ------------------------------------------------------------------*/ #include "stm32f0xx_hal_def.h" /** @addtogroup STM32F0xx_HAL_Driver * @{ */ /** @addtogroup COMP COMP * @{ */ /* Exported types ------------------------------------------------------------*/ /** @defgroup COMP_Exported_Types COMP Exported Types * @{ */ /** * @brief COMP Init structure definition */ typedef struct { uint32_t InvertingInput; /*!< Selects the inverting input of the comparator. This parameter can be a value of @ref COMP_InvertingInput */ uint32_t NonInvertingInput; /*!< Selects the non inverting input of the comparator. This parameter can be a value of @ref COMP_NonInvertingInput */ uint32_t Output; /*!< Selects the output redirection of the comparator. This parameter can be a value of @ref COMP_Output */ uint32_t OutputPol; /*!< Selects the output polarity of the comparator. This parameter can be a value of @ref COMP_OutputPolarity */ uint32_t Hysteresis; /*!< Selects the hysteresis voltage of the comparator. This parameter can be a value of @ref COMP_Hysteresis */ uint32_t Mode; /*!< Selects the operating comsumption mode of the comparator to adjust the speed/consumption. This parameter can be a value of @ref COMP_Mode */ uint32_t WindowMode; /*!< Selects the window mode of the comparator 1 & 2. This parameter can be a value of @ref COMP_WindowMode */ uint32_t TriggerMode; /*!< Selects the trigger mode of the comparator (interrupt mode). This parameter can be a value of @ref COMP_TriggerMode */ }COMP_InitTypeDef; /** * @brief COMP Handle Structure definition */ typedef struct { COMP_TypeDef *Instance; /*!< Register base address */ COMP_InitTypeDef Init; /*!< COMP required parameters */ HAL_LockTypeDef Lock; /*!< Locking object */ __IO uint32_t State; /*!< COMP communication state This parameter can be a value of @ref COMP_State */ }COMP_HandleTypeDef; /** * @} */ /* Exported constants --------------------------------------------------------*/ /** @defgroup COMP_Exported_Constants COMP Exported Constants * @{ */ /** @defgroup COMP_State COMP State * @{ */ #define HAL_COMP_STATE_RESET ((uint32_t)0x00000000) /*!< COMP not yet initialized or disabled */ #define HAL_COMP_STATE_READY ((uint32_t)0x00000001) /*!< COMP initialized and ready for use */ #define HAL_COMP_STATE_READY_LOCKED ((uint32_t)0x00000011) /*!< COMP initialized but the configuration is locked */ #define HAL_COMP_STATE_BUSY ((uint32_t)0x00000002) /*!< COMP is running */ #define HAL_COMP_STATE_BUSY_LOCKED ((uint32_t)0x00000012) /*!< COMP is running and the configuration is locked */ /** * @} */ /** @defgroup COMP_OutputPolarity COMP OutputPolarity * @{ */ #define COMP_OUTPUTPOL_NONINVERTED ((uint32_t)0x00000000) /*!< COMP output on GPIO isn't inverted */ #define COMP_OUTPUTPOL_INVERTED COMP_CSR_COMP1POL /*!< COMP output on GPIO is inverted */ /** * @} */ /** @defgroup COMP_Hysteresis COMP Hysteresis * @{ */ #define COMP_HYSTERESIS_NONE ((uint32_t)0x00000000) /*!< No hysteresis */ #define COMP_HYSTERESIS_LOW COMP_CSR_COMP1HYST_0 /*!< Hysteresis level low */ #define COMP_HYSTERESIS_MEDIUM COMP_CSR_COMP1HYST_1 /*!< Hysteresis level medium */ #define COMP_HYSTERESIS_HIGH COMP_CSR_COMP1HYST /*!< Hysteresis level high */ /** * @} */ /** @defgroup COMP_Mode COMP Mode * @{ */ /* Please refer to the electrical characteristics in the device datasheet for the power consumption values */ #define COMP_MODE_HIGHSPEED ((uint32_t)0x00000000) /*!< High Speed */ #define COMP_MODE_MEDIUMSPEED COMP_CSR_COMP1MODE_0 /*!< Medium Speed */ #define COMP_MODE_LOWPOWER COMP_CSR_COMP1MODE_1 /*!< Low power mode */ #define COMP_MODE_ULTRALOWPOWER COMP_CSR_COMP1MODE /*!< Ultra-low power mode */ /** * @} */ /** @defgroup COMP_InvertingInput COMP InvertingInput * @{ */ #define COMP_INVERTINGINPUT_1_4VREFINT ((uint32_t)0x00000000) /*!< 1/4 VREFINT connected to comparator inverting input */ #define COMP_INVERTINGINPUT_1_2VREFINT COMP_CSR_COMP1INSEL_0 /*!< 1/2 VREFINT connected to comparator inverting input */ #define COMP_INVERTINGINPUT_3_4VREFINT COMP_CSR_COMP1INSEL_1 /*!< 3/4 VREFINT connected to comparator inverting input */ #define COMP_INVERTINGINPUT_VREFINT (COMP_CSR_COMP1INSEL_1|COMP_CSR_COMP1INSEL_0) /*!< VREFINT connected to comparator inverting input */ #define COMP_INVERTINGINPUT_DAC1 COMP_CSR_COMP1INSEL_2 /*!< DAC_OUT1 (PA4) connected to comparator inverting input */ #define COMP_INVERTINGINPUT_DAC1SWITCHCLOSED (COMP_CSR_COMP1INSEL_2|COMP_CSR_COMP1SW1) /*!< DAC_OUT1 (PA4) connected to comparator inverting input and close switch (PA0 for COMP1 only) */ #define COMP_INVERTINGINPUT_DAC2 (COMP_CSR_COMP1INSEL_2|COMP_CSR_COMP1INSEL_0) /*!< DAC_OUT2 (PA5) connected to comparator inverting input */ #define COMP_INVERTINGINPUT_IO1 (COMP_CSR_COMP1INSEL_2|COMP_CSR_COMP1INSEL_1) /*!< IO (PA0 for COMP1 and PA2 for COMP2) connected to comparator inverting input */ /** * @} */ /** @defgroup COMP_NonInvertingInput COMP NonInvertingInput * @{ */ #define COMP_NONINVERTINGINPUT_IO1 ((uint32_t)0x00000000) /*!< I/O1 (PA1 for COMP1, PA3 for COMP2) connected to comparator non inverting input */ #define COMP_NONINVERTINGINPUT_DAC1SWITCHCLOSED COMP_CSR_COMP1SW1 /*!< DAC ouput connected to comparator COMP1 non inverting input */ /** * @} */ /** @defgroup COMP_Output COMP Output * @{ */ /* Output Redirection common for COMP1 and COMP2 */ #define COMP_OUTPUT_NONE ((uint32_t)0x00000000) /*!< COMP output isn't connected to other peripherals */ #define COMP_OUTPUT_TIM1BKIN COMP_CSR_COMP1OUTSEL_0 /*!< COMP output connected to TIM1 Break Input (BKIN) */ #define COMP_OUTPUT_TIM1IC1 COMP_CSR_COMP1OUTSEL_1 /*!< COMP output connected to TIM1 Input Capture 1 */ #define COMP_OUTPUT_TIM1OCREFCLR (COMP_CSR_COMP1OUTSEL_1|COMP_CSR_COMP1OUTSEL_0) /*!< COMP output connected to TIM1 OCREF Clear */ #define COMP_OUTPUT_TIM2IC4 COMP_CSR_COMP1OUTSEL_2 /*!< COMP output connected to TIM2 Input Capture 4 */ #define COMP_OUTPUT_TIM2OCREFCLR (COMP_CSR_COMP1OUTSEL_2|COMP_CSR_COMP1OUTSEL_0) /*!< COMP output connected to TIM2 OCREF Clear */ #define COMP_OUTPUT_TIM3IC1 (COMP_CSR_COMP1OUTSEL_2|COMP_CSR_COMP1OUTSEL_1) /*!< COMP output connected to TIM3 Input Capture 1 */ #define COMP_OUTPUT_TIM3OCREFCLR COMP_CSR_COMP1OUTSEL /*!< COMP output connected to TIM3 OCREF Clear */ /** * @} */ /** @defgroup COMP_OutputLevel COMP OutputLevel * @{ */ /* When output polarity is not inverted, comparator output is low when the non-inverting input is at a lower voltage than the inverting input*/ #define COMP_OUTPUTLEVEL_LOW ((uint32_t)0x00000000) /* When output polarity is not inverted, comparator output is high when the non-inverting input is at a higher voltage than the inverting input */ #define COMP_OUTPUTLEVEL_HIGH COMP_CSR_COMP1OUT /** * @} */ /** @defgroup COMP_TriggerMode COMP TriggerMode * @{ */ #define COMP_TRIGGERMODE_NONE ((uint32_t)0x00000000) /*!< No External Interrupt trigger detection */ #define COMP_TRIGGERMODE_IT_RISING ((uint32_t)0x00000001) /*!< External Interrupt Mode with Rising edge trigger detection */ #define COMP_TRIGGERMODE_IT_FALLING ((uint32_t)0x00000002) /*!< External Interrupt Mode with Falling edge trigger detection */ #define COMP_TRIGGERMODE_IT_RISING_FALLING ((uint32_t)0x00000003) /*!< External Interrupt Mode with Rising/Falling edge trigger detection */ #define COMP_TRIGGERMODE_EVENT_RISING ((uint32_t)0x00000010) /*!< Event Mode with Rising edge trigger detection */ #define COMP_TRIGGERMODE_EVENT_FALLING ((uint32_t)0x00000020) /*!< Event Mode with Falling edge trigger detection */ #define COMP_TRIGGERMODE_EVENT_RISING_FALLING ((uint32_t)0x00000030) /*!< Event Mode with Rising/Falling edge trigger detection */ /** * @} */ /** @defgroup COMP_WindowMode COMP WindowMode * @{ */ #define COMP_WINDOWMODE_DISABLE ((uint32_t)0x00000000) /*!< Window mode disabled */ #define COMP_WINDOWMODE_ENABLE COMP_CSR_WNDWEN /*!< Window mode enabled: non inverting input of comparator 2 is connected to the non inverting input of comparator 1 (PA1) */ /** * @} */ /** @defgroup COMP_Flag COMP Flag * @{ */ #define COMP_FLAG_LOCK ((uint32_t)COMP_CSR_COMPxLOCK) /*!< Lock flag */ /** * @} */ /** * @} */ /* Exported macros -----------------------------------------------------------*/ /** @defgroup COMP_Exported_Macros COMP Exported Macros * @{ */ /** @brief Reset COMP handle state * @param __HANDLE__: COMP handle. * @retval None */ #define __HAL_COMP_RESET_HANDLE_STATE(__HANDLE__) ((__HANDLE__)->State = HAL_COMP_STATE_RESET) /** * @brief Enable the specified comparator. * @param __HANDLE__: COMP handle. * @retval None */ #define __HAL_COMP_ENABLE(__HANDLE__) (((__HANDLE__)->Instance == COMP1) ? \ SET_BIT(COMP->CSR, COMP_CSR_COMP1EN) : \ SET_BIT(COMP->CSR, COMP_CSR_COMP2EN)) /** * @brief Disable the specified comparator. * @param __HANDLE__: COMP handle. * @retval None */ #define __HAL_COMP_DISABLE(__HANDLE__) (((__HANDLE__)->Instance == COMP1) ? \ CLEAR_BIT(COMP->CSR, COMP_CSR_COMP1EN) : \ CLEAR_BIT(COMP->CSR, COMP_CSR_COMP2EN)) /** * @brief Lock the specified comparator configuration. * @param __HANDLE__: COMP handle. * @retval None */ #define __HAL_COMP_LOCK(__HANDLE__) (((__HANDLE__)->Instance == COMP1) ? \ SET_BIT(COMP->CSR, COMP_CSR_COMP1LOCK) : \ SET_BIT(COMP->CSR, COMP_CSR_COMP2LOCK)) /** * @brief Enable the COMP1 EXTI line rising edge trigger. * @retval None */ #define __HAL_COMP_COMP1_EXTI_ENABLE_RISING_EDGE() SET_BIT(EXTI->RTSR, COMP_EXTI_LINE_COMP1) /** * @brief Disable the COMP1 EXTI line rising edge trigger. * @retval None */ #define __HAL_COMP_COMP1_EXTI_DISABLE_RISING_EDGE() CLEAR_BIT(EXTI->RTSR, COMP_EXTI_LINE_COMP1) /** * @brief Enable the COMP1 EXTI line falling edge trigger. * @retval None */ #define __HAL_COMP_COMP1_EXTI_ENABLE_FALLING_EDGE() SET_BIT(EXTI->FTSR, COMP_EXTI_LINE_COMP1) /** * @brief Disable the COMP1 EXTI line falling edge trigger. * @retval None */ #define __HAL_COMP_COMP1_EXTI_DISABLE_FALLING_EDGE() CLEAR_BIT(EXTI->FTSR, COMP_EXTI_LINE_COMP1) /** * @brief Enable the COMP1 EXTI line rising & falling edge trigger. * @retval None */ #define __HAL_COMP_COMP1_EXTI_ENABLE_RISING_FALLING_EDGE() do { \ __HAL_COMP_COMP1_EXTI_ENABLE_RISING_EDGE(); \ __HAL_COMP_COMP1_EXTI_ENABLE_FALLING_EDGE(); \ } while(0) /** * @brief Disable the COMP1 EXTI line rising & falling edge trigger. * @retval None */ #define __HAL_COMP_COMP1_EXTI_DISABLE_RISING_FALLING_EDGE() do { \ __HAL_COMP_COMP1_EXTI_DISABLE_RISING_EDGE(); \ __HAL_COMP_COMP1_EXTI_DISABLE_FALLING_EDGE(); \ } while(0) /** * @brief Enable the COMP1 EXTI line in interrupt mode. * @retval None */ #define __HAL_COMP_COMP1_EXTI_ENABLE_IT() SET_BIT(EXTI->IMR, COMP_EXTI_LINE_COMP1) /** * @brief Disable the COMP1 EXTI line in interrupt mode. * @retval None */ #define __HAL_COMP_COMP1_EXTI_DISABLE_IT() CLEAR_BIT(EXTI->IMR, COMP_EXTI_LINE_COMP1) /** * @brief Generate a software interrupt on the COMP1 EXTI line. * @retval None */ #define __HAL_COMP_COMP1_EXTI_GENERATE_SWIT() SET_BIT(EXTI->SWIER, COMP_EXTI_LINE_COMP1) /** * @brief Enable the COMP1 EXTI Line in event mode. * @retval None */ #define __HAL_COMP_COMP1_EXTI_ENABLE_EVENT() SET_BIT(EXTI->EMR, COMP_EXTI_LINE_COMP1) /** * @brief Disable the COMP1 EXTI Line in event mode. * @retval None */ #define __HAL_COMP_COMP1_EXTI_DISABLE_EVENT() CLEAR_BIT(EXTI->EMR, COMP_EXTI_LINE_COMP1) /** * @brief Check whether the COMP1 EXTI line flag is set or not. * @retval RESET or SET */ #define __HAL_COMP_COMP1_EXTI_GET_FLAG() READ_BIT(EXTI->PR, COMP_EXTI_LINE_COMP1) /** * @brief Clear the COMP1 EXTI flag. * @retval None */ #define __HAL_COMP_COMP1_EXTI_CLEAR_FLAG() WRITE_REG(EXTI->PR, COMP_EXTI_LINE_COMP1) /** * @brief Enable the COMP2 EXTI line rising edge trigger. * @retval None */ #define __HAL_COMP_COMP2_EXTI_ENABLE_RISING_EDGE() SET_BIT(EXTI->RTSR, COMP_EXTI_LINE_COMP2) /** * @brief Disable the COMP2 EXTI line rising edge trigger. * @retval None */ #define __HAL_COMP_COMP2_EXTI_DISABLE_RISING_EDGE() CLEAR_BIT(EXTI->RTSR, COMP_EXTI_LINE_COMP2) /** * @brief Enable the COMP2 EXTI line falling edge trigger. * @retval None */ #define __HAL_COMP_COMP2_EXTI_ENABLE_FALLING_EDGE() SET_BIT(EXTI->FTSR, COMP_EXTI_LINE_COMP2) /** * @brief Disable the COMP2 EXTI line falling edge trigger. * @retval None */ #define __HAL_COMP_COMP2_EXTI_DISABLE_FALLING_EDGE() CLEAR_BIT(EXTI->FTSR, COMP_EXTI_LINE_COMP2) /** * @brief Enable the COMP2 EXTI line rising & falling edge trigger. * @retval None */ #define __HAL_COMP_COMP2_EXTI_ENABLE_RISING_FALLING_EDGE() do { \ __HAL_COMP_COMP2_EXTI_ENABLE_RISING_EDGE(); \ __HAL_COMP_COMP2_EXTI_ENABLE_FALLING_EDGE(); \ } while(0) /** * @brief Disable the COMP2 EXTI line rising & falling edge trigger. * @retval None */ #define __HAL_COMP_COMP2_EXTI_DISABLE_RISING_FALLING_EDGE() do { \ __HAL_COMP_COMP2_EXTI_DISABLE_RISING_EDGE(); \ __HAL_COMP_COMP2_EXTI_DISABLE_FALLING_EDGE(); \ } while(0) /** * @brief Enable the COMP2 EXTI line in interrupt mode. * @retval None */ #define __HAL_COMP_COMP2_EXTI_ENABLE_IT() SET_BIT(EXTI->IMR, COMP_EXTI_LINE_COMP2) /** * @brief Disable the COMP2 EXTI line in interrupt mode. * @retval None */ #define __HAL_COMP_COMP2_EXTI_DISABLE_IT() CLEAR_BIT(EXTI->IMR, COMP_EXTI_LINE_COMP2) /** * @brief Generate a software interrupt on the COMP2 EXTI line. * @retval None */ #define __HAL_COMP_COMP2_EXTI_GENERATE_SWIT() SET_BIT(EXTI->SWIER, COMP_EXTI_LINE_COMP2) /** * @brief Enable the COMP2 EXTI Line in event mode. * @retval None */ #define __HAL_COMP_COMP2_EXTI_ENABLE_EVENT() SET_BIT(EXTI->EMR, COMP_EXTI_LINE_COMP2) /** * @brief Disable the COMP2 EXTI Line in event mode. * @retval None */ #define __HAL_COMP_COMP2_EXTI_DISABLE_EVENT() CLEAR_BIT(EXTI->EMR, COMP_EXTI_LINE_COMP2) /** * @brief Check whether the COMP2 EXTI line flag is set or not. * @retval RESET or SET */ #define __HAL_COMP_COMP2_EXTI_GET_FLAG() READ_BIT(EXTI->PR, COMP_EXTI_LINE_COMP2) /** * @brief Clear the COMP2 EXTI flag. * @retval None */ #define __HAL_COMP_COMP2_EXTI_CLEAR_FLAG() WRITE_REG(EXTI->PR, COMP_EXTI_LINE_COMP2) /** @brief Check whether the specified COMP flag is set or not. * @param __HANDLE__: specifies the COMP Handle. * @param __FLAG__: specifies the flag to check. * This parameter can be one of the following values: * @arg COMP_FLAG_LOCK: lock flag * @retval The new state of __FLAG__ (TRUE or FALSE). */ #define __HAL_COMP_GET_FLAG(__HANDLE__, __FLAG__) (((__HANDLE__)->Instance->CSR & (__FLAG__)) == (__FLAG__)) /** * @} */ /* Exported functions --------------------------------------------------------*/ /** @addtogroup COMP_Exported_Functions COMP Exported Functions * @{ */ /** @addtogroup COMP_Exported_Functions_Group1 Initialization/de-initialization functions * @brief Initialization and Configuration functions * @{ */ /* Initialization and de-initialization functions ****************************/ HAL_StatusTypeDef HAL_COMP_Init(COMP_HandleTypeDef *hcomp); HAL_StatusTypeDef HAL_COMP_DeInit (COMP_HandleTypeDef *hcomp); void HAL_COMP_MspInit(COMP_HandleTypeDef *hcomp); void HAL_COMP_MspDeInit(COMP_HandleTypeDef *hcomp); /** * @} */ /** @addtogroup COMP_Exported_Functions_Group2 I/O operation functions * @brief Data transfers functions * @{ */ /* IO operation functions *****************************************************/ HAL_StatusTypeDef HAL_COMP_Start(COMP_HandleTypeDef *hcomp); HAL_StatusTypeDef HAL_COMP_Stop(COMP_HandleTypeDef *hcomp); HAL_StatusTypeDef HAL_COMP_Start_IT(COMP_HandleTypeDef *hcomp); HAL_StatusTypeDef HAL_COMP_Stop_IT(COMP_HandleTypeDef *hcomp); void HAL_COMP_IRQHandler(COMP_HandleTypeDef *hcomp); /** * @} */ /** @addtogroup COMP_Exported_Functions_Group3 Peripheral Control functions * @brief management functions * @{ */ /* Peripheral Control functions ***********************************************/ HAL_StatusTypeDef HAL_COMP_Lock(COMP_HandleTypeDef *hcomp); uint32_t HAL_COMP_GetOutputLevel(COMP_HandleTypeDef *hcomp); /* Callback in Interrupt mode */ void HAL_COMP_TriggerCallback(COMP_HandleTypeDef *hcomp); /** * @} */ /** @addtogroup COMP_Exported_Functions_Group4 Peripheral State functions * @brief Peripheral State functions * @{ */ /* Peripheral State and Error functions ***************************************/ uint32_t HAL_COMP_GetState(COMP_HandleTypeDef *hcomp); /** * @} */ /** * @} */ /* Private types -------------------------------------------------------------*/ /* Private constants ---------------------------------------------------------*/ /** @defgroup COMP_Private_Constants COMP Private Constants * @{ */ /** @defgroup COMP_ExtiLine COMP EXTI Lines * Elements values convention: XXXX0000 * - XXXX : Interrupt mask in the EMR/IMR/RTSR/FTSR register * @{ */ #define COMP_EXTI_LINE_COMP1 ((uint32_t)EXTI_IMR_MR21) /*!< EXTI line 21 connected to COMP1 output */ #define COMP_EXTI_LINE_COMP2 ((uint32_t)EXTI_IMR_MR22) /*!< EXTI line 22 connected to COMP2 output */ /** * @} */ /** * @} */ /* Private macros ------------------------------------------------------------*/ /** @defgroup COMP_Private_Macros COMP Private Macros * @{ */ /** @defgroup COMP_GET_EXTI_LINE COMP Private macros to get EXTI line associated with Comparators * @{ */ /** * @brief Get the specified EXTI line for a comparator instance. * @param __INSTANCE__: specifies the COMP instance. * @retval value of @ref COMP_ExtiLine */ #define COMP_GET_EXTI_LINE(__INSTANCE__) (((__INSTANCE__) == COMP1) ? COMP_EXTI_LINE_COMP1 : \ COMP_EXTI_LINE_COMP2) /** * @} */ /** @defgroup COMP_IS_COMP_Definitions COMP Private macros to check input parameters * @{ */ #define IS_COMP_OUTPUTPOL(POL) (((POL) == COMP_OUTPUTPOL_NONINVERTED) || \ ((POL) == COMP_OUTPUTPOL_INVERTED)) #define IS_COMP_HYSTERESIS(HYSTERESIS) (((HYSTERESIS) == COMP_HYSTERESIS_NONE) || \ ((HYSTERESIS) == COMP_HYSTERESIS_LOW) || \ ((HYSTERESIS) == COMP_HYSTERESIS_MEDIUM) || \ ((HYSTERESIS) == COMP_HYSTERESIS_HIGH)) #define IS_COMP_MODE(MODE) (((MODE) == COMP_MODE_HIGHSPEED) || \ ((MODE) == COMP_MODE_MEDIUMSPEED) || \ ((MODE) == COMP_MODE_LOWPOWER) || \ ((MODE) == COMP_MODE_ULTRALOWPOWER)) #define IS_COMP_INVERTINGINPUT(INPUT) (((INPUT) == COMP_INVERTINGINPUT_1_4VREFINT) || \ ((INPUT) == COMP_INVERTINGINPUT_1_2VREFINT) || \ ((INPUT) == COMP_INVERTINGINPUT_3_4VREFINT) || \ ((INPUT) == COMP_INVERTINGINPUT_VREFINT) || \ ((INPUT) == COMP_INVERTINGINPUT_DAC1) || \ ((INPUT) == COMP_INVERTINGINPUT_DAC1SWITCHCLOSED) || \ ((INPUT) == COMP_INVERTINGINPUT_DAC2) || \ ((INPUT) == COMP_INVERTINGINPUT_IO1)) #define IS_COMP_NONINVERTINGINPUT(INPUT) (((INPUT) == COMP_NONINVERTINGINPUT_IO1) || \ ((INPUT) == COMP_NONINVERTINGINPUT_DAC1SWITCHCLOSED)) #define IS_COMP_OUTPUT(OUTPUT) (((OUTPUT) == COMP_OUTPUT_NONE) || \ ((OUTPUT) == COMP_OUTPUT_TIM1BKIN) || \ ((OUTPUT) == COMP_OUTPUT_TIM1IC1) || \ ((OUTPUT) == COMP_OUTPUT_TIM1OCREFCLR) || \ ((OUTPUT) == COMP_OUTPUT_TIM2IC4) || \ ((OUTPUT) == COMP_OUTPUT_TIM2OCREFCLR) || \ ((OUTPUT) == COMP_OUTPUT_TIM3IC1) || \ ((OUTPUT) == COMP_OUTPUT_TIM3OCREFCLR)) #define IS_COMP_WINDOWMODE(WINDOWMODE) (((WINDOWMODE) == COMP_WINDOWMODE_DISABLE) || \ ((WINDOWMODE) == COMP_WINDOWMODE_ENABLE)) #define IS_COMP_TRIGGERMODE(__MODE__) (((__MODE__) == COMP_TRIGGERMODE_NONE) || \ ((__MODE__) == COMP_TRIGGERMODE_IT_RISING) || \ ((__MODE__) == COMP_TRIGGERMODE_IT_FALLING) || \ ((__MODE__) == COMP_TRIGGERMODE_IT_RISING_FALLING) || \ ((__MODE__) == COMP_TRIGGERMODE_EVENT_RISING) || \ ((__MODE__) == COMP_TRIGGERMODE_EVENT_FALLING) || \ ((__MODE__) == COMP_TRIGGERMODE_EVENT_RISING_FALLING)) /** * @} */ /** @defgroup COMP_Lock COMP Lock * @{ */ #define COMP_LOCK_DISABLE ((uint32_t)0x00000000) #define COMP_LOCK_ENABLE COMP_CSR_COMP1LOCK #define COMP_STATE_BIT_LOCK ((uint32_t)0x10) /** * @} */ /** * @} */ /* Private functions ---------------------------------------------------------*/ /** * @} */ /** * @} */ #endif /* STM32F051x8 || STM32F058xx || */ /* STM32F071xB || STM32F072xB || STM32F078xx || */ /* STM32F091xC || STM32F098xx */ #ifdef __cplusplus } #endif #endif /* __STM32F0xx_HAL_COMP_H */ /************************ (C) COPYRIGHT STMicroelectronics *****END OF FILE****/ ================================================ FILE: Zelig/mbed/TARGET_NUCLEO_F091RC/stm32f0xx_hal_conf.h ================================================ /** ****************************************************************************** * @file stm32f0xx_hal_conf.h * @author MCD Application Team * @version V1.3.0 * @date 26-June-2015 * @brief HAL configuration file. ****************************************************************************** * @attention * *

© COPYRIGHT(c) 2015 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. * ****************************************************************************** */ /* Define to prevent recursive inclusion -------------------------------------*/ #ifndef __STM32F0xx_HAL_CONF_H #define __STM32F0xx_HAL_CONF_H #ifdef __cplusplus extern "C" { #endif /* Exported types ------------------------------------------------------------*/ /* Exported constants --------------------------------------------------------*/ /* ########################## Module Selection ############################## */ /** * @brief This is the list of modules to be used in the HAL driver */ #define HAL_MODULE_ENABLED #define HAL_ADC_MODULE_ENABLED #define HAL_CAN_MODULE_ENABLED #define HAL_CEC_MODULE_ENABLED #define HAL_COMP_MODULE_ENABLED #define HAL_CORTEX_MODULE_ENABLED #define HAL_CRC_MODULE_ENABLED #define HAL_DAC_MODULE_ENABLED #define HAL_DMA_MODULE_ENABLED #define HAL_FLASH_MODULE_ENABLED #define HAL_GPIO_MODULE_ENABLED #define HAL_I2C_MODULE_ENABLED #define HAL_I2S_MODULE_ENABLED #define HAL_IRDA_MODULE_ENABLED #define HAL_IWDG_MODULE_ENABLED #define HAL_PCD_MODULE_ENABLED #define HAL_PWR_MODULE_ENABLED #define HAL_RCC_MODULE_ENABLED #define HAL_RTC_MODULE_ENABLED #define HAL_SMARTCARD_MODULE_ENABLED #define HAL_SMBUS_MODULE_ENABLED #define HAL_SPI_MODULE_ENABLED #define HAL_TIM_MODULE_ENABLED #define HAL_TSC_MODULE_ENABLED #define HAL_UART_MODULE_ENABLED #define HAL_USART_MODULE_ENABLED #define HAL_WWDG_MODULE_ENABLED /* ######################### Oscillator Values adaptation ################### */ /** * @brief Adjust the value of External High Speed oscillator (HSE) used in your application. * This value is used by the RCC HAL module to compute the system frequency * (when HSE is used as system clock source, directly or through the PLL). */ #if !defined (HSE_VALUE) #define HSE_VALUE ((uint32_t)8000000) /*!< Value of the External oscillator in Hz */ #endif /* HSE_VALUE */ /** * @brief In the following line adjust the External High Speed oscillator (HSE) Startup * Timeout value */ #if !defined (HSE_STARTUP_TIMEOUT) #define HSE_STARTUP_TIMEOUT ((uint32_t)200) /*!< Time out for HSE start up, in ms */ #endif /* HSE_STARTUP_TIMEOUT */ /** * @brief Internal High Speed oscillator (HSI) value. * This value is used by the RCC HAL module to compute the system frequency * (when HSI is used as system clock source, directly or through the PLL). */ #if !defined (HSI_VALUE) #define HSI_VALUE ((uint32_t)8000000) /*!< Value of the Internal oscillator in Hz*/ #endif /* HSI_VALUE */ /** * @brief In the following line adjust the Internal High Speed oscillator (HSI) Startup * Timeout value */ #if !defined (HSI_STARTUP_TIMEOUT) #define HSI_STARTUP_TIMEOUT ((uint32_t)100) /*!< Time out for HSI start up */ #endif /* HSI_STARTUP_TIMEOUT */ /** * @brief Internal High Speed oscillator for ADC (HSI14) value. */ #if !defined (HSI14_VALUE) #define HSI14_VALUE ((uint32_t)14000000) /*!< Value of the Internal High Speed oscillator for ADC in Hz. The real value may vary depending on the variations in voltage and temperature. */ #endif /* HSI14_VALUE */ /** * @brief Internal High Speed oscillator for USB (HSI48) value. */ #if !defined (HSI48_VALUE) #define HSI48_VALUE ((uint32_t)48000000) /*!< Value of the Internal High Speed oscillator for USB in Hz. The real value may vary depending on the variations in voltage and temperature. */ #endif /* HSI48_VALUE */ /** * @brief Internal Low Speed oscillator (LSI) value. */ #if !defined (LSI_VALUE) #define LSI_VALUE ((uint32_t)40000) #endif /* LSI_VALUE */ /*!< Value of the Internal Low Speed oscillator in Hz The real value may vary depending on the variations in voltage and temperature. */ /** * @brief External Low Speed oscillator (LSE) value. */ #if !defined (LSE_VALUE) #define LSE_VALUE ((uint32_t)32768) /*!< Value of the External Low Speed oscillator in Hz */ #endif /* LSE_VALUE */ #if !defined (LSE_STARTUP_TIMEOUT) #define LSE_STARTUP_TIMEOUT ((uint32_t)100) /*!< Time out for LSE start up, in ms */ #endif /* HSE_STARTUP_TIMEOUT */ /* Tip: To avoid modifying this file each time you need to use different HSE, === you can define the HSE value in your toolchain compiler preprocessor. */ /* ########################### System Configuration ######################### */ /** * @brief This is the HAL system configuration section */ #define VDD_VALUE ((uint32_t)3300) /*!< Value of VDD in mv */ #define TICK_INT_PRIORITY ((uint32_t)(1<<__NVIC_PRIO_BITS) - 1) /*!< tick interrupt priority (lowest by default) */ /* Warning: Must be set to higher priority for HAL_Delay() */ /* and HAL_GetTick() usage under interrupt context */ #define USE_RTOS 0 #define PREFETCH_ENABLE 1 #define INSTRUCTION_CACHE_ENABLE 0 #define DATA_CACHE_ENABLE 0 /* ########################## Assert Selection ############################## */ /** * @brief Uncomment the line below to expanse the "assert_param" macro in the * HAL drivers code */ /*#define USE_FULL_ASSERT 1*/ /* Includes ------------------------------------------------------------------*/ /** * @brief Include module's header file */ #ifdef HAL_RCC_MODULE_ENABLED #include "stm32f0xx_hal_rcc.h" #endif /* HAL_RCC_MODULE_ENABLED */ #ifdef HAL_GPIO_MODULE_ENABLED #include "stm32f0xx_hal_gpio.h" #endif /* HAL_GPIO_MODULE_ENABLED */ #ifdef HAL_DMA_MODULE_ENABLED #include "stm32f0xx_hal_dma.h" #endif /* HAL_DMA_MODULE_ENABLED */ #ifdef HAL_CORTEX_MODULE_ENABLED #include "stm32f0xx_hal_cortex.h" #endif /* HAL_CORTEX_MODULE_ENABLED */ #ifdef HAL_ADC_MODULE_ENABLED #include "stm32f0xx_hal_adc.h" #endif /* HAL_ADC_MODULE_ENABLED */ #ifdef HAL_CAN_MODULE_ENABLED #include "stm32f0xx_hal_can.h" #endif /* HAL_CAN_MODULE_ENABLED */ #ifdef HAL_CEC_MODULE_ENABLED #include "stm32f0xx_hal_cec.h" #endif /* HAL_CEC_MODULE_ENABLED */ #ifdef HAL_COMP_MODULE_ENABLED #include "stm32f0xx_hal_comp.h" #endif /* HAL_COMP_MODULE_ENABLED */ #ifdef HAL_CRC_MODULE_ENABLED #include "stm32f0xx_hal_crc.h" #endif /* HAL_CRC_MODULE_ENABLED */ #ifdef HAL_DAC_MODULE_ENABLED #include "stm32f0xx_hal_dac.h" #endif /* HAL_DAC_MODULE_ENABLED */ #ifdef HAL_FLASH_MODULE_ENABLED #include "stm32f0xx_hal_flash.h" #endif /* HAL_FLASH_MODULE_ENABLED */ #ifdef HAL_I2C_MODULE_ENABLED #include "stm32f0xx_hal_i2c.h" #endif /* HAL_I2C_MODULE_ENABLED */ #ifdef HAL_I2S_MODULE_ENABLED #include "stm32f0xx_hal_i2s.h" #endif /* HAL_I2S_MODULE_ENABLED */ #ifdef HAL_IRDA_MODULE_ENABLED #include "stm32f0xx_hal_irda.h" #endif /* HAL_IRDA_MODULE_ENABLED */ #ifdef HAL_IWDG_MODULE_ENABLED #include "stm32f0xx_hal_iwdg.h" #endif /* HAL_IWDG_MODULE_ENABLED */ #ifdef HAL_PCD_MODULE_ENABLED #include "stm32f0xx_hal_pcd.h" #endif /* HAL_PCD_MODULE_ENABLED */ #ifdef HAL_PWR_MODULE_ENABLED #include "stm32f0xx_hal_pwr.h" #endif /* HAL_PWR_MODULE_ENABLED */ #ifdef HAL_RTC_MODULE_ENABLED #include "stm32f0xx_hal_rtc.h" #endif /* HAL_RTC_MODULE_ENABLED */ #ifdef HAL_SMARTCARD_MODULE_ENABLED #include "stm32f0xx_hal_smartcard.h" #endif /* HAL_SMARTCARD_MODULE_ENABLED */ #ifdef HAL_SMBUS_MODULE_ENABLED #include "stm32f0xx_hal_smbus.h" #endif /* HAL_SMBUS_MODULE_ENABLED */ #ifdef HAL_SPI_MODULE_ENABLED #include "stm32f0xx_hal_spi.h" #endif /* HAL_SPI_MODULE_ENABLED */ #ifdef HAL_TIM_MODULE_ENABLED #include "stm32f0xx_hal_tim.h" #endif /* HAL_TIM_MODULE_ENABLED */ #ifdef HAL_TSC_MODULE_ENABLED #include "stm32f0xx_hal_tsc.h" #endif /* HAL_TSC_MODULE_ENABLED */ #ifdef HAL_UART_MODULE_ENABLED #include "stm32f0xx_hal_uart.h" #endif /* HAL_UART_MODULE_ENABLED */ #ifdef HAL_USART_MODULE_ENABLED #include "stm32f0xx_hal_usart.h" #endif /* HAL_USART_MODULE_ENABLED */ #ifdef HAL_WWDG_MODULE_ENABLED #include "stm32f0xx_hal_wwdg.h" #endif /* HAL_WWDG_MODULE_ENABLED */ /* Exported macro ------------------------------------------------------------*/ #ifdef USE_FULL_ASSERT /** * @brief The assert_param macro is used for function's parameters check. * @param expr: If expr is false, it calls assert_failed function * which reports the name of the source file and the source * line number of the call that failed. * If expr is true, it returns no value. * @retval None */ #define assert_param(expr) ((expr) ? (void)0 : assert_failed((uint8_t *)__FILE__, __LINE__)) /* Exported functions ------------------------------------------------------- */ void assert_failed(uint8_t* file, uint32_t line); #else #define assert_param(expr) ((void)0) #endif /* USE_FULL_ASSERT */ #ifdef __cplusplus } #endif #endif /* __STM32F0xx_HAL_CONF_H */ /************************ (C) COPYRIGHT STMicroelectronics *****END OF FILE****/ ================================================ FILE: Zelig/mbed/TARGET_NUCLEO_F091RC/stm32f0xx_hal_cortex.h ================================================ /** ****************************************************************************** * @file stm32f0xx_hal_cortex.h * @author MCD Application Team * @version V1.3.0 * @date 26-June-2015 * @brief Header file of CORTEX HAL module. ****************************************************************************** * @attention * *

© COPYRIGHT(c) 2015 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. * ****************************************************************************** */ /* Define to prevent recursive inclusion -------------------------------------*/ #ifndef __STM32F0xx_HAL_CORTEX_H #define __STM32F0xx_HAL_CORTEX_H #ifdef __cplusplus extern "C" { #endif /* Includes ------------------------------------------------------------------*/ #include "stm32f0xx_hal_def.h" /** @addtogroup STM32F0xx_HAL_Driver * @{ */ /** @addtogroup CORTEX CORTEX * @{ */ /* Exported types ------------------------------------------------------------*/ /* Exported constants --------------------------------------------------------*/ /** @defgroup CORTEX_Exported_Constants CORTEX Exported Constants * @{ */ /** @defgroup CORTEX_SysTick_clock_source CORTEX SysTick clock source * @{ */ #define SYSTICK_CLKSOURCE_HCLK_DIV8 ((uint32_t)0x00000000) #define SYSTICK_CLKSOURCE_HCLK ((uint32_t)0x00000004) /** * @} */ /** * @} */ /* Exported Macros -----------------------------------------------------------*/ /** @defgroup CORTEX_Exported_Macro CORTEX Exported Macro * @{ */ /** @brief Configures the SysTick clock source. * @param __CLKSRC__: specifies the SysTick clock source. * This parameter can be one of the following values: * @arg SYSTICK_CLKSOURCE_HCLK_DIV8: AHB clock divided by 8 selected as SysTick clock source. * @arg SYSTICK_CLKSOURCE_HCLK: AHB clock selected as SysTick clock source. * @retval None */ #define __HAL_CORTEX_SYSTICKCLK_CONFIG(__CLKSRC__) \ do { \ if ((__CLKSRC__) == SYSTICK_CLKSOURCE_HCLK) \ { \ SysTick->CTRL |= SYSTICK_CLKSOURCE_HCLK; \ } \ else \ SysTick->CTRL &= ~SYSTICK_CLKSOURCE_HCLK; \ } while(0) /** * @} */ /* Exported functions --------------------------------------------------------*/ /** @addtogroup CORTEX_Exported_Functions CORTEX Exported Functions * @{ */ /** @addtogroup CORTEX_Exported_Functions_Group1 Initialization and de-initialization functions * @brief Initialization and Configuration functions * @{ */ /* Initialization and de-initialization functions *******************************/ void HAL_NVIC_SetPriority(IRQn_Type IRQn,uint32_t PreemptPriority, uint32_t SubPriority); void HAL_NVIC_EnableIRQ(IRQn_Type IRQn); void HAL_NVIC_DisableIRQ(IRQn_Type IRQn); void HAL_NVIC_SystemReset(void); uint32_t HAL_SYSTICK_Config(uint32_t TicksNumb); /** * @} */ /** @addtogroup CORTEX_Exported_Functions_Group2 Peripheral Control functions * @brief Cortex control functions * @{ */ /* Peripheral Control functions *************************************************/ uint32_t HAL_NVIC_GetPriority(IRQn_Type IRQn); uint32_t HAL_NVIC_GetPendingIRQ(IRQn_Type IRQn); void HAL_NVIC_SetPendingIRQ(IRQn_Type IRQn); void HAL_NVIC_ClearPendingIRQ(IRQn_Type IRQn); void HAL_SYSTICK_CLKSourceConfig(uint32_t CLKSource); void HAL_SYSTICK_IRQHandler(void); void HAL_SYSTICK_Callback(void); /** * @} */ /** * @} */ /* Private types -------------------------------------------------------------*/ /* Private variables ---------------------------------------------------------*/ /* Private constants ---------------------------------------------------------*/ /* Private macros ------------------------------------------------------------*/ /** @defgroup CORTEX_Private_Macros CORTEX Private Macros * @{ */ #define IS_NVIC_PREEMPTION_PRIORITY(PRIORITY) ((PRIORITY) < 0x4) #define IS_NVIC_DEVICE_IRQ(IRQ) ((IRQ) >= 0x00) #define IS_SYSTICK_CLK_SOURCE(SOURCE) (((SOURCE) == SYSTICK_CLKSOURCE_HCLK) || \ ((SOURCE) == SYSTICK_CLKSOURCE_HCLK_DIV8)) /** * @} */ /** * @} */ /** * @} */ #ifdef __cplusplus } #endif #endif /* __STM32F0xx_HAL_CORTEX_H */ /************************ (C) COPYRIGHT STMicroelectronics *****END OF FILE****/ ================================================ FILE: Zelig/mbed/TARGET_NUCLEO_F091RC/stm32f0xx_hal_crc.h ================================================ /** ****************************************************************************** * @file stm32f0xx_hal_crc.h * @author MCD Application Team * @version V1.3.0 * @date 26-June-2015 * @brief Header file of CRC HAL module. ****************************************************************************** * @attention * *

© COPYRIGHT(c) 2015 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. * ****************************************************************************** */ /* Define to prevent recursive inclusion -------------------------------------*/ #ifndef __STM32F0xx_HAL_CRC_H #define __STM32F0xx_HAL_CRC_H #ifdef __cplusplus extern "C" { #endif /* Includes ------------------------------------------------------------------*/ #include "stm32f0xx_hal_def.h" /** @addtogroup STM32F0xx_HAL_Driver * @{ */ /** @addtogroup CRC CRC * @{ */ /* Exported types ------------------------------------------------------------*/ /** @defgroup CRC_Exported_Types CRC Exported Types * @{ */ /** * @brief CRC HAL State Structure definition */ typedef enum { HAL_CRC_STATE_RESET = 0x00, /*!< CRC not yet initialized or disabled */ HAL_CRC_STATE_READY = 0x01, /*!< CRC initialized and ready for use */ HAL_CRC_STATE_BUSY = 0x02, /*!< CRC internal process is ongoing */ HAL_CRC_STATE_TIMEOUT = 0x03, /*!< CRC timeout state */ HAL_CRC_STATE_ERROR = 0x04 /*!< CRC error state */ }HAL_CRC_StateTypeDef; /** * @brief CRC Init Structure definition */ typedef struct { uint8_t DefaultPolynomialUse; /*!< This parameter is a value of @ref CRC_Default_Polynomial and indicates if default polynomial is used. If set to DEFAULT_POLYNOMIAL_ENABLE, resort to default X^32 + X^26 + X^23 + X^22 + X^16 + X^12 + X^11 + X^10 +X^8 + X^7 + X^5 + X^4 + X^2+ X +1. In that case, there is no need to set GeneratingPolynomial field. If otherwise set to DEFAULT_POLYNOMIAL_DISABLE, GeneratingPolynomial and CRCLength fields must be set */ uint8_t DefaultInitValueUse; /*!< This parameter is a value of @ref CRC_Default_InitValue_Use and indicates if default init value is used. If set to DEFAULT_INIT_VALUE_ENABLE, resort to default 0xFFFFFFFF value. In that case, there is no need to set InitValue field. If otherwise set to DEFAULT_INIT_VALUE_DISABLE, InitValue field must be set */ uint32_t GeneratingPolynomial; /*!< Set CRC generating polynomial. 7, 8, 16 or 32-bit long value for a polynomial degree respectively equal to 7, 8, 16 or 32. This field is written in normal representation, e.g., for a polynomial of degree 7, X^7 + X^6 + X^5 + X^2 + 1 is written 0x65. No need to specify it if DefaultPolynomialUse is set to DEFAULT_POLYNOMIAL_ENABLE */ uint32_t CRCLength; /*!< This parameter is a value of @ref CRCEx_Polynomial_Sizes and indicates CRC length. Value can be either one of CRC_POLYLENGTH_32B (32-bit CRC) CRC_POLYLENGTH_16B (16-bit CRC) CRC_POLYLENGTH_8B (8-bit CRC) CRC_POLYLENGTH_7B (7-bit CRC) */ uint32_t InitValue; /*!< Init value to initiate CRC computation. No need to specify it if DefaultInitValueUse is set to DEFAULT_INIT_VALUE_ENABLE */ uint32_t InputDataInversionMode; /*!< This parameter is a value of @ref CRCEx_Input_Data_Inversion and specifies input data inversion mode. Can be either one of the following values CRC_INPUTDATA_INVERSION_NONE no input data inversion CRC_INPUTDATA_INVERSION_BYTE byte-wise inversion, 0x1A2B3C4D becomes 0x58D43CB2 CRC_INPUTDATA_INVERSION_HALFWORD halfword-wise inversion, 0x1A2B3C4D becomes 0xD458B23C CRC_INPUTDATA_INVERSION_WORD word-wise inversion, 0x1A2B3C4D becomes 0xB23CD458 */ uint32_t OutputDataInversionMode; /*!< This parameter is a value of @ref CRCEx_Output_Data_Inversion and specifies output data (i.e. CRC) inversion mode. Can be either CRC_OUTPUTDATA_INVERSION_DISABLE no CRC inversion, or CRC_OUTPUTDATA_INVERSION_ENABLE CRC 0x11223344 is converted into 0x22CC4488 */ }CRC_InitTypeDef; /** * @brief CRC Handle Structure definition */ typedef struct { CRC_TypeDef *Instance; /*!< Register base address */ CRC_InitTypeDef Init; /*!< CRC configuration parameters */ HAL_LockTypeDef Lock; /*!< CRC Locking object */ __IO HAL_CRC_StateTypeDef State; /*!< CRC communication state */ uint32_t InputDataFormat; /*!< This parameter is a value of @ref CRC_Input_Buffer_Format and specifies input data format. Can be either CRC_INPUTDATA_FORMAT_BYTES input data is a stream of bytes (8-bit data) CRC_INPUTDATA_FORMAT_HALFWORDS input data is a stream of half-words (16-bit data) CRC_INPUTDATA_FORMAT_WORDS input data is a stream of words (32-bits data) Note that constant CRC_INPUT_FORMAT_UNDEFINED is defined but an initialization error must occur if InputBufferFormat is not one of the three values listed above */ }CRC_HandleTypeDef; /** * @} */ /* Exported constants --------------------------------------------------------*/ /** @defgroup CRC_Exported_Constants CRC Exported Constants * @{ */ /** @defgroup CRC_Default_Polynomial_Value Default CRC generating polynomial * @{ */ #define DEFAULT_CRC32_POLY 0x04C11DB7 /** * @} */ /** @defgroup CRC_Default_InitValue Default CRC computation initialization value * @{ */ #define DEFAULT_CRC_INITVALUE 0xFFFFFFFF /** * @} */ /** @defgroup CRC_Default_Polynomial Indicates whether or not default polynomial is used * @{ */ #define DEFAULT_POLYNOMIAL_ENABLE ((uint8_t)0x00) #define DEFAULT_POLYNOMIAL_DISABLE ((uint8_t)0x01) #define IS_DEFAULT_POLYNOMIAL(DEFAULT) (((DEFAULT) == DEFAULT_POLYNOMIAL_ENABLE) || \ ((DEFAULT) == DEFAULT_POLYNOMIAL_DISABLE)) /** * @} */ /** @defgroup CRC_Default_InitValue_Use Indicates whether or not default init value is used * @{ */ #define DEFAULT_INIT_VALUE_ENABLE ((uint8_t)0x00) #define DEFAULT_INIT_VALUE_DISABLE ((uint8_t)0x01) #define IS_DEFAULT_INIT_VALUE(VALUE) (((VALUE) == DEFAULT_INIT_VALUE_ENABLE) || \ ((VALUE) == DEFAULT_INIT_VALUE_DISABLE)) /** * @} */ /** @defgroup CRC_Input_Buffer_Format Input Buffer Format * @{ */ /* WARNING: CRC_INPUT_FORMAT_UNDEFINED is created for reference purposes but * an error is triggered in HAL_CRC_Init() if InputDataFormat field is set * to CRC_INPUT_FORMAT_UNDEFINED: the format MUST be defined by the user for * the CRC APIs to provide a correct result */ #define CRC_INPUTDATA_FORMAT_UNDEFINED ((uint32_t)0x00000000) #define CRC_INPUTDATA_FORMAT_BYTES ((uint32_t)0x00000001) #define CRC_INPUTDATA_FORMAT_HALFWORDS ((uint32_t)0x00000002) #define CRC_INPUTDATA_FORMAT_WORDS ((uint32_t)0x00000003) #define IS_CRC_INPUTDATA_FORMAT(FORMAT) (((FORMAT) == CRC_INPUTDATA_FORMAT_BYTES) || \ ((FORMAT) == CRC_INPUTDATA_FORMAT_HALFWORDS) || \ ((FORMAT) == CRC_INPUTDATA_FORMAT_WORDS)) /** * @} */ /** * @} */ /* Exported macros -----------------------------------------------------------*/ /** @defgroup CRC_Exported_Macros CRC Exported Macros * @{ */ /** @brief Reset CRC handle state * @param __HANDLE__: CRC handle. * @retval None */ #define __HAL_CRC_RESET_HANDLE_STATE(__HANDLE__) ((__HANDLE__)->State = HAL_CRC_STATE_RESET) /** * @brief Reset CRC Data Register. * @param __HANDLE__: CRC handle * @retval None. */ #define __HAL_CRC_DR_RESET(__HANDLE__) ((__HANDLE__)->Instance->CR |= CRC_CR_RESET) /** * @brief Set CRC INIT non-default value * @param __HANDLE__ : CRC handle * @param __INIT__ : 32-bit initial value * @retval None. */ #define __HAL_CRC_INITIALCRCVALUE_CONFIG(__HANDLE__, __INIT__) ((__HANDLE__)->Instance->INIT = (__INIT__)) /** * @brief Stores a 8-bit data in the Independent Data(ID) register. * @param __HANDLE__: CRC handle * @param __VALUE__: 8-bit value to be stored in the ID register * @retval None */ #define __HAL_CRC_SET_IDR(__HANDLE__, __VALUE__) (WRITE_REG((__HANDLE__)->Instance->IDR, (__VALUE__))) /** * @brief Returns the 8-bit data stored in the Independent Data(ID) register. * @param __HANDLE__: CRC handle * @retval 8-bit value of the ID register */ #define __HAL_CRC_GET_IDR(__HANDLE__) (((__HANDLE__)->Instance->IDR) & CRC_IDR_IDR) /** * @} */ /* Include CRC HAL Extension module */ #include "stm32f0xx_hal_crc_ex.h" /* Exported functions --------------------------------------------------------*/ /** @addtogroup CRC_Exported_Functions CRC Exported Functions * @{ */ /** @addtogroup CRC_Exported_Functions_Group1 Initialization/de-initialization functions * @brief Initialization and Configuration functions. * @{ */ /* Initialization and de-initialization functions ****************************/ HAL_StatusTypeDef HAL_CRC_Init(CRC_HandleTypeDef *hcrc); HAL_StatusTypeDef HAL_CRC_DeInit (CRC_HandleTypeDef *hcrc); void HAL_CRC_MspInit(CRC_HandleTypeDef *hcrc); void HAL_CRC_MspDeInit(CRC_HandleTypeDef *hcrc); /** * @} */ /** @addtogroup CRC_Exported_Functions_Group2 Peripheral Control functions * @brief management functions. * @{ */ /* Peripheral Control functions ***********************************************/ uint32_t HAL_CRC_Accumulate(CRC_HandleTypeDef *hcrc, uint32_t pBuffer[], uint32_t BufferLength); uint32_t HAL_CRC_Calculate(CRC_HandleTypeDef *hcrc, uint32_t pBuffer[], uint32_t BufferLength); /** * @} */ /** @addtogroup CRC_Exported_Functions_Group3 Peripheral State functions * @brief Peripheral State functions. * @{ */ /* Peripheral State and Error functions ***************************************/ HAL_CRC_StateTypeDef HAL_CRC_GetState(CRC_HandleTypeDef *hcrc); /** * @} */ /** * @} */ /** @addtogroup CRC_Exported_Constants CRC Exported Constants * @brief aliases for inter STM32 series compatibility * @{ */ /** @defgroup CRC_Aliases Aliases for inter STM32 series compatibility * @{ */ /* Aliases for inter STM32 series compatibility */ #define HAL_CRC_Input_Data_Reverse HAL_CRCEx_Input_Data_Reverse #define HAL_CRC_Output_Data_Reverse HAL_CRCEx_Output_Data_Reverse /** * @} */ /** * @} */ /** * @} */ /** * @} */ #ifdef __cplusplus } #endif #endif /* __STM32F0xx_HAL_CRC_H */ /************************ (C) COPYRIGHT STMicroelectronics *****END OF FILE****/ ================================================ FILE: Zelig/mbed/TARGET_NUCLEO_F091RC/stm32f0xx_hal_crc_ex.h ================================================ /** ****************************************************************************** * @file stm32f0xx_hal_crc_ex.h * @author MCD Application Team * @version V1.3.0 * @date 26-June-2015 * @brief Header file of CRC HAL extension module. ****************************************************************************** * @attention * *

© COPYRIGHT(c) 2015 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. * ****************************************************************************** */ /* Define to prevent recursive inclusion -------------------------------------*/ #ifndef __STM32F0xx_HAL_CRC_EX_H #define __STM32F0xx_HAL_CRC_EX_H #ifdef __cplusplus extern "C" { #endif /* Includes ------------------------------------------------------------------*/ #include "stm32f0xx_hal_def.h" /** @addtogroup STM32F0xx_HAL_Driver * @{ */ /** @addtogroup CRCEx CRCEx * @{ */ /* Exported types ------------------------------------------------------------*/ /* Exported constants --------------------------------------------------------*/ /** @defgroup CRCEx_Exported_Constants CRCEx Exported Constants * @{ */ /** @defgroup CRCEx_Input_Data_Inversion Input Data Inversion Modes * @{ */ #define CRC_INPUTDATA_INVERSION_NONE ((uint32_t)0x00000000) #define CRC_INPUTDATA_INVERSION_BYTE ((uint32_t)CRC_CR_REV_IN_0) #define CRC_INPUTDATA_INVERSION_HALFWORD ((uint32_t)CRC_CR_REV_IN_1) #define CRC_INPUTDATA_INVERSION_WORD ((uint32_t)CRC_CR_REV_IN) #define IS_CRC_INPUTDATA_INVERSION_MODE(MODE) (((MODE) == CRC_INPUTDATA_INVERSION_NONE) || \ ((MODE) == CRC_INPUTDATA_INVERSION_BYTE) || \ ((MODE) == CRC_INPUTDATA_INVERSION_HALFWORD) || \ ((MODE) == CRC_INPUTDATA_INVERSION_WORD)) /** * @} */ /** @defgroup CRCEx_Output_Data_Inversion Output Data Inversion Modes * @{ */ #define CRC_OUTPUTDATA_INVERSION_DISABLE ((uint32_t)0x00000000) #define CRC_OUTPUTDATA_INVERSION_ENABLE ((uint32_t)CRC_CR_REV_OUT) #define IS_CRC_OUTPUTDATA_INVERSION_MODE(MODE) (((MODE) == CRC_OUTPUTDATA_INVERSION_DISABLE) || \ ((MODE) == CRC_OUTPUTDATA_INVERSION_ENABLE)) /** * @} */ /** @defgroup CRCEx_Polynomial_Sizes Polynomial sizes to configure the IP * @{ */ #if defined(STM32F071xB) || defined(STM32F072xB) || defined(STM32F078xx) || defined(STM32F091xC) || defined(STM32F098xx) #define CRC_POLYLENGTH_32B ((uint32_t)0x00000000) #define CRC_POLYLENGTH_16B ((uint32_t)CRC_CR_POLYSIZE_0) #define CRC_POLYLENGTH_8B ((uint32_t)CRC_CR_POLYSIZE_1) #define CRC_POLYLENGTH_7B ((uint32_t)CRC_CR_POLYSIZE) #define IS_CRC_POL_LENGTH(LENGTH) (((LENGTH) == CRC_POLYLENGTH_32B) || \ ((LENGTH) == CRC_POLYLENGTH_16B) || \ ((LENGTH) == CRC_POLYLENGTH_8B) || \ ((LENGTH) == CRC_POLYLENGTH_7B)) #else #define CRC_POLYLENGTH_32B ((uint32_t)0x00000000) #define IS_CRC_POL_LENGTH(LENGTH) ((LENGTH) == CRC_POLYLENGTH_32B) #endif /* defined(STM32F071xB) || defined(STM32F072xB) || defined(STM32F078xx) || defined(STM32F091xC) || defined(STM32F098xx) */ /** * @} */ /** @defgroup CRCEx_Polynomial_Size_Definitions CRC polynomial possible sizes actual definitions * @{ */ #if defined(STM32F071xB) || defined(STM32F072xB) || defined(STM32F078xx) || defined(STM32F091xC) || defined(STM32F098xx) #define HAL_CRC_LENGTH_32B 32 #define HAL_CRC_LENGTH_16B 16 #define HAL_CRC_LENGTH_8B 8 #define HAL_CRC_LENGTH_7B 7 #else #define HAL_CRC_LENGTH_32B 32 #endif /* defined(STM32F071xB) || defined(STM32F072xB) || defined(STM32F078xx) || defined(STM32F091xC) || defined(STM32F098xx) */ /** * @} */ /** * @} */ /* Exported macro ------------------------------------------------------------*/ /** @defgroup CRCEx_Exported_Macros CRCEx Exported Macros * @{ */ /** * @brief Set CRC output reversal * @param __HANDLE__ : CRC handle * @retval None. */ #define __HAL_CRC_OUTPUTREVERSAL_ENABLE(__HANDLE__) ((__HANDLE__)->Instance->CR |= CRC_CR_REV_OUT) /** * @brief Unset CRC output reversal * @param __HANDLE__ : CRC handle * @retval None. */ #define __HAL_CRC_OUTPUTREVERSAL_DISABLE(__HANDLE__) ((__HANDLE__)->Instance->CR &= ~(CRC_CR_REV_OUT)) #if defined(STM32F071xB) || defined(STM32F072xB) || defined(STM32F078xx) || defined(STM32F091xC) || defined(STM32F098xx) || defined(STM32F070xB) || defined(STM32F030xC) /** * @brief Set CRC non-default polynomial * @param __HANDLE__ : CRC handle * @param __POLYNOMIAL__: 7, 8, 16 or 32-bit polynomial * @retval None. */ #define __HAL_CRC_POLYNOMIAL_CONFIG(__HANDLE__, __POLYNOMIAL__) ((__HANDLE__)->Instance->POL = (__POLYNOMIAL__)) #endif /* defined(STM32F071xB) || defined(STM32F072xB) || defined(STM32F078xx) || defined(STM32F091xC) || defined(STM32F098xx) || defined(STM32F070xB) || defined(STM32F030xC) */ /** * @} */ /* Exported functions --------------------------------------------------------*/ /** @addtogroup CRCEx_Exported_Functions * @{ */ /** @addtogroup CRCEx_Exported_Functions_Group1 Extended Initialization/de-initialization functions * @brief Extended Initialization and Configuration functions. * @{ */ /* Initialization and de-initialization functions ****************************/ HAL_StatusTypeDef HAL_CRCEx_Init(CRC_HandleTypeDef *hcrc); HAL_StatusTypeDef HAL_CRCEx_Input_Data_Reverse(CRC_HandleTypeDef *hcrc, uint32_t InputReverseMode); HAL_StatusTypeDef HAL_CRCEx_Output_Data_Reverse(CRC_HandleTypeDef *hcrc, uint32_t OutputReverseMode); #if defined(STM32F071xB) || defined(STM32F072xB) || defined(STM32F078xx) || defined(STM32F091xC) || defined(STM32F098xx) || defined(STM32F070xB) || defined(STM32F030xC) HAL_StatusTypeDef HAL_CRCEx_Polynomial_Set(CRC_HandleTypeDef *hcrc, uint32_t Pol, uint32_t PolyLength); #endif /* defined(STM32F071xB) || defined(STM32F072xB) || defined(STM32F078xx) || defined(STM32F091xC) || defined(STM32F098xx) || defined(STM32F070xB) || defined(STM32F030xC) */ /** * @} */ /* Peripheral Control functions ***********************************************/ /* Peripheral State and Error functions ***************************************/ /** * @} */ /** * @} */ /** * @} */ #ifdef __cplusplus } #endif #endif /* __STM32F0xx_HAL_CRC_EX_H */ /************************ (C) COPYRIGHT STMicroelectronics *****END OF FILE****/ ================================================ FILE: Zelig/mbed/TARGET_NUCLEO_F091RC/stm32f0xx_hal_dac.h ================================================ /** ****************************************************************************** * @file stm32f0xx_hal_dac.h * @author MCD Application Team * @version V1.3.0 * @date 26-June-2015 * @brief Header file of DAC HAL module. ****************************************************************************** * @attention * *

© COPYRIGHT(c) 2015 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. * ****************************************************************************** */ /* Define to prevent recursive inclusion -------------------------------------*/ #ifndef __STM32F0xx_HAL_DAC_H #define __STM32F0xx_HAL_DAC_H #ifdef __cplusplus extern "C" { #endif /** @addtogroup STM32F0xx_HAL_Driver * @{ */ #if defined(STM32F051x8) || defined(STM32F058xx) || \ defined(STM32F071xB) || defined(STM32F072xB) || defined(STM32F078xx) || \ defined(STM32F091xC) || defined(STM32F098xx) /* Includes ------------------------------------------------------------------*/ #include "stm32f0xx_hal_def.h" /** @addtogroup DAC * @{ */ /* Exported types ------------------------------------------------------------*/ /** @defgroup DAC_Exported_Types DAC Exported Types * @{ */ /** * @brief HAL State structures definition */ typedef enum { HAL_DAC_STATE_RESET = 0x00, /*!< DAC not yet initialized or disabled */ HAL_DAC_STATE_READY = 0x01, /*!< DAC initialized and ready for use */ HAL_DAC_STATE_BUSY = 0x02, /*!< DAC internal processing is ongoing */ HAL_DAC_STATE_TIMEOUT = 0x03, /*!< DAC timeout state */ HAL_DAC_STATE_ERROR = 0x04 /*!< DAC error state */ }HAL_DAC_StateTypeDef; /** * @brief DAC handle Structure definition */ typedef struct { DAC_TypeDef *Instance; /*!< Register base address */ __IO HAL_DAC_StateTypeDef State; /*!< DAC communication state */ HAL_LockTypeDef Lock; /*!< DAC locking object */ DMA_HandleTypeDef *DMA_Handle1; /*!< Pointer DMA handler for channel 1 */ DMA_HandleTypeDef *DMA_Handle2; /*!< Pointer DMA handler for channel 2 */ __IO uint32_t ErrorCode; /*!< DAC Error code */ }DAC_HandleTypeDef; /** * @brief DAC Configuration regular Channel structure definition */ typedef struct { uint32_t DAC_Trigger; /*!< Specifies the external trigger for the selected DAC channel. This parameter can be a value of @ref DAC_trigger_selection */ uint32_t DAC_OutputBuffer; /*!< Specifies whether the DAC channel output buffer is enabled or disabled. This parameter can be a value of @ref DAC_output_buffer */ }DAC_ChannelConfTypeDef; /** * @} */ /* Exported constants --------------------------------------------------------*/ /** @defgroup DAC_Exported_Constants DAC Exported Constants * @{ */ /** @defgroup DAC_Error_Code DAC Error Code * @{ */ #define HAL_DAC_ERROR_NONE 0x00 /*!< No error */ #define HAL_DAC_ERROR_DMAUNDERRUNCH1 0x01 /*!< DAC channel1 DMA underrun error */ #define HAL_DAC_ERROR_DMAUNDERRUNCH2 0x02 /*!< DAC channel2 DMA underrun error */ #define HAL_DAC_ERROR_DMA 0x04 /*!< DMA error */ /** * @} */ /** @defgroup DAC_output_buffer DAC output buffer * @{ */ #define DAC_OUTPUTBUFFER_ENABLE ((uint32_t)0x00000000) #define DAC_OUTPUTBUFFER_DISABLE ((uint32_t)DAC_CR_BOFF1) /** * @} */ /** @defgroup DAC_data_alignment DAC data alignment * @{ */ #define DAC_ALIGN_12B_R ((uint32_t)0x00000000) #define DAC_ALIGN_12B_L ((uint32_t)0x00000004) #define DAC_ALIGN_8B_R ((uint32_t)0x00000008) /** * @} */ /** @defgroup DAC_flags_definition DAC flags definition * @{ */ #define DAC_FLAG_DMAUDR1 ((uint32_t)DAC_SR_DMAUDR1) #define DAC_FLAG_DMAUDR2 ((uint32_t)DAC_SR_DMAUDR2) /** * @} */ /** @defgroup DAC_IT_definition DAC IT definition * @{ */ #define DAC_IT_DMAUDR1 ((uint32_t)DAC_SR_DMAUDR1) #define DAC_IT_DMAUDR2 ((uint32_t)DAC_SR_DMAUDR2) /** * @} */ /** * @} */ /* Exported macro ------------------------------------------------------------*/ /** @defgroup DAC_Exported_Macros DAC Exported Macros * @{ */ /** @brief Reset DAC handle state * @param __HANDLE__: specifies the DAC handle. * @retval None */ #define __HAL_DAC_RESET_HANDLE_STATE(__HANDLE__) ((__HANDLE__)->State = HAL_DAC_STATE_RESET) /** @brief Enable the DAC channel * @param __HANDLE__: specifies the DAC handle. * @param __DAC_Channel__: specifies the DAC channel * @retval None */ #define __HAL_DAC_ENABLE(__HANDLE__, __DAC_Channel__) \ ((__HANDLE__)->Instance->CR |= (DAC_CR_EN1 << (__DAC_Channel__))) /** @brief Disable the DAC channel * @param __HANDLE__: specifies the DAC handle * @param __DAC_Channel__: specifies the DAC channel. * @retval None */ #define __HAL_DAC_DISABLE(__HANDLE__, __DAC_Channel__) \ ((__HANDLE__)->Instance->CR &= ~(DAC_CR_EN1 << (__DAC_Channel__))) /** @brief Enable the DAC interrupt * @param __HANDLE__: specifies the DAC handle * @param __INTERRUPT__: specifies the DAC interrupt. * This parameter can be any combination of the following values: * @arg DAC_IT_DMAUDR1: DAC channel 1 DMA underrun interrupt * @arg DAC_IT_DMAUDR2: DAC channel 2 DMA underrun interrupt * @retval None */ #define __HAL_DAC_ENABLE_IT(__HANDLE__, __INTERRUPT__) (((__HANDLE__)->Instance->CR) |= (__INTERRUPT__)) /** @brief Disable the DAC interrupt * @param __HANDLE__: specifies the DAC handle * @param __INTERRUPT__: specifies the DAC interrupt. * This parameter can be any combination of the following values: * @arg DAC_IT_DMAUDR1: DAC channel 1 DMA underrun interrupt * @retval None */ #define __HAL_DAC_DISABLE_IT(__HANDLE__, __INTERRUPT__) (((__HANDLE__)->Instance->CR) &= ~(__INTERRUPT__)) /** @brief Check whether the specified DAC interrupt source is enabled or not * @param __HANDLE__: DAC handle * @param __INTERRUPT__: DAC interrupt source to check * This parameter can be any combination of the following values: * @arg DAC_IT_DMAUDR1: DAC channel 1 DMA underrun interrupt * @arg DAC_IT_DMAUDR2: DAC channel 2 DMA underrun interrupt * @retval State of interruption (SET or RESET) */ #define __HAL_DAC_GET_IT_SOURCE(__HANDLE__, __INTERRUPT__) (((__HANDLE__)->Instance->CR & (__INTERRUPT__)) == (__INTERRUPT__)) /** @brief Get the selected DAC's flag status * @param __HANDLE__: specifies the DAC handle. * @param __FLAG__: specifies the DAC flag to get. * This parameter can be any combination of the following values: * @arg DAC_FLAG_DMAUDR1: DAC channel 1 DMA underrun flag * @retval None */ #define __HAL_DAC_GET_FLAG(__HANDLE__, __FLAG__) ((((__HANDLE__)->Instance->SR) & (__FLAG__)) == (__FLAG__)) /** @brief Clear the DAC's flag * @param __HANDLE__: specifies the DAC handle. * @param __FLAG__: specifies the DAC flag to clear. * This parameter can be any combination of the following values: * @arg DAC_FLAG_DMAUDR1: DAC channel 1 DMA underrun flag * @retval None */ #define __HAL_DAC_CLEAR_FLAG(__HANDLE__, __FLAG__) (((__HANDLE__)->Instance->SR) = (__FLAG__)) /** * @} */ /* Private macro -------------------------------------------------------------*/ /** @addtogroup DAC_Private_Macros * @{ */ #define IS_DAC_OUTPUT_BUFFER_STATE(STATE) (((STATE) == DAC_OUTPUTBUFFER_ENABLE) || \ ((STATE) == DAC_OUTPUTBUFFER_DISABLE)) #if defined(STM32F071xB) || defined(STM32F072xB) || defined(STM32F078xx) || \ defined(STM32F091xC) || defined(STM32F098xx) #define IS_DAC_CHANNEL(CHANNEL) (((CHANNEL) == DAC_CHANNEL_1) || \ ((CHANNEL) == DAC_CHANNEL_2)) #endif /* STM32F071xB || STM32F072xB || STM32F078xx || */ /* STM32F091xC || STM32F098xx */ #if defined(STM32F051x8) || defined(STM32F058xx) #define IS_DAC_CHANNEL(CHANNEL) (((CHANNEL) == DAC_CHANNEL_1)) #endif /* STM32F051x8 || STM32F058xx */ #define IS_DAC_ALIGN(ALIGN) (((ALIGN) == DAC_ALIGN_12B_R) || \ ((ALIGN) == DAC_ALIGN_12B_L) || \ ((ALIGN) == DAC_ALIGN_8B_R)) #define IS_DAC_DATA(DATA) ((DATA) <= 0xFFF0) /** @brief Set DHR12R1 alignment * @param __ALIGNMENT__: specifies the DAC alignment * @retval None */ #define DAC_DHR12R1_ALIGNMENT(__ALIGNMENT__) (((uint32_t)0x00000008) + (__ALIGNMENT__)) /** @brief Set DHR12R2 alignment * @param __ALIGNMENT__: specifies the DAC alignment * @retval None */ #define DAC_DHR12R2_ALIGNMENT(__ALIGNMENT__) (((uint32_t)0x00000014) + (__ALIGNMENT__)) /** @brief Set DHR12RD alignment * @param __ALIGNMENT__: specifies the DAC alignment * @retval None */ #define DAC_DHR12RD_ALIGNMENT(__ALIGNMENT__) (((uint32_t)0x00000020) + (__ALIGNMENT__)) /** * @} */ /* Include DAC HAL Extension module */ #include "stm32f0xx_hal_dac_ex.h" /* Exported functions --------------------------------------------------------*/ /** @addtogroup DAC_Exported_Functions * @{ */ /** @addtogroup DAC_Exported_Functions_Group1 * @{ */ /* Initialization and de-initialization functions *****************************/ HAL_StatusTypeDef HAL_DAC_Init(DAC_HandleTypeDef* hdac); HAL_StatusTypeDef HAL_DAC_DeInit(DAC_HandleTypeDef* hdac); void HAL_DAC_MspInit(DAC_HandleTypeDef* hdac); void HAL_DAC_MspDeInit(DAC_HandleTypeDef* hdac); /** * @} */ /** @addtogroup DAC_Exported_Functions_Group2 * @{ */ /* IO operation functions *****************************************************/ HAL_StatusTypeDef HAL_DAC_Start(DAC_HandleTypeDef* hdac, uint32_t Channel); HAL_StatusTypeDef HAL_DAC_Stop(DAC_HandleTypeDef* hdac, uint32_t Channel); HAL_StatusTypeDef HAL_DAC_Start_DMA(DAC_HandleTypeDef* hdac, uint32_t Channel, uint32_t* pData, uint32_t Length, uint32_t Alignment); HAL_StatusTypeDef HAL_DAC_Stop_DMA(DAC_HandleTypeDef* hdac, uint32_t Channel); void HAL_DAC_IRQHandler(DAC_HandleTypeDef* hdac); HAL_StatusTypeDef HAL_DAC_SetValue(DAC_HandleTypeDef* hdac, uint32_t Channel, uint32_t Alignment, uint32_t Data); void HAL_DAC_ConvCpltCallbackCh1(DAC_HandleTypeDef* hdac); void HAL_DAC_ConvHalfCpltCallbackCh1(DAC_HandleTypeDef* hdac); void HAL_DAC_ErrorCallbackCh1(DAC_HandleTypeDef *hdac); void HAL_DAC_DMAUnderrunCallbackCh1(DAC_HandleTypeDef *hdac); /** * @} */ /** @addtogroup DAC_Exported_Functions_Group3 * @{ */ /* Peripheral Control functions ***********************************************/ uint32_t HAL_DAC_GetValue(DAC_HandleTypeDef* hdac, uint32_t Channel); HAL_StatusTypeDef HAL_DAC_ConfigChannel(DAC_HandleTypeDef* hdac, DAC_ChannelConfTypeDef* sConfig, uint32_t Channel); /** * @} */ /** @addtogroup DAC_Exported_Functions_Group4 * @{ */ /* Peripheral State and Error functions ***************************************/ HAL_DAC_StateTypeDef HAL_DAC_GetState(DAC_HandleTypeDef* hdac); uint32_t HAL_DAC_GetError(DAC_HandleTypeDef *hdac); /** * @} */ /** * @} */ /** * @} */ #endif /* STM32F051x8 || STM32F058xx || */ /* STM32F071xB || STM32F072xB || STM32F078xx || */ /* STM32F091xC || STM32F098xx */ /** * @} */ #ifdef __cplusplus } #endif #endif /*__STM32F0xx_HAL_DAC_H */ /************************ (C) COPYRIGHT STMicroelectronics *****END OF FILE****/ ================================================ FILE: Zelig/mbed/TARGET_NUCLEO_F091RC/stm32f0xx_hal_dac_ex.h ================================================ /** ****************************************************************************** * @file stm32f0xx_hal_dac_ex.h * @author MCD Application Team * @version V1.3.0 * @date 26-June-2015 * @brief Header file of DAC HAL Extension module. ****************************************************************************** * @attention * *

© COPYRIGHT(c) 2015 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. * ****************************************************************************** */ /* Define to prevent recursive inclusion -------------------------------------*/ #ifndef __STM32F0xx_HAL_DAC_EX_H #define __STM32F0xx_HAL_DAC_EX_H #ifdef __cplusplus extern "C" { #endif /** @addtogroup STM32F0xx_HAL_Driver * @{ */ #if defined(STM32F051x8) || defined(STM32F058xx) || \ defined(STM32F071xB) || defined(STM32F072xB) || defined(STM32F078xx) || \ defined(STM32F091xC) || defined(STM32F098xx) /* Includes ------------------------------------------------------------------*/ #include "stm32f0xx_hal_def.h" /** @addtogroup DACEx * @{ */ /* Exported types ------------------------------------------------------------*/ /* Exported constants --------------------------------------------------------*/ /** @defgroup DACEx_Exported_Constants DACEx Exported Constants * @{ */ /** @defgroup DACEx_lfsrunmask_triangleamplitude DACEx lfsrunmask triangleamplitude * @{ */ #define DAC_LFSRUNMASK_BIT0 ((uint32_t)0x00000000) /*!< Unmask DAC channel LFSR bit0 for noise wave generation */ #define DAC_LFSRUNMASK_BITS1_0 ((uint32_t)DAC_CR_MAMP1_0) /*!< Unmask DAC channel LFSR bit[1:0] for noise wave generation */ #define DAC_LFSRUNMASK_BITS2_0 ((uint32_t)DAC_CR_MAMP1_1) /*!< Unmask DAC channel LFSR bit[2:0] for noise wave generation */ #define DAC_LFSRUNMASK_BITS3_0 ((uint32_t)DAC_CR_MAMP1_1 | DAC_CR_MAMP1_0)/*!< Unmask DAC channel LFSR bit[3:0] for noise wave generation */ #define DAC_LFSRUNMASK_BITS4_0 ((uint32_t)DAC_CR_MAMP1_2) /*!< Unmask DAC channel LFSR bit[4:0] for noise wave generation */ #define DAC_LFSRUNMASK_BITS5_0 ((uint32_t)DAC_CR_MAMP1_2 | DAC_CR_MAMP1_0) /*!< Unmask DAC channel LFSR bit[5:0] for noise wave generation */ #define DAC_LFSRUNMASK_BITS6_0 ((uint32_t)DAC_CR_MAMP1_2 | DAC_CR_MAMP1_1) /*!< Unmask DAC channel LFSR bit[6:0] for noise wave generation */ #define DAC_LFSRUNMASK_BITS7_0 ((uint32_t)DAC_CR_MAMP1_2 | DAC_CR_MAMP1_1 | DAC_CR_MAMP1_0) /*!< Unmask DAC channel LFSR bit[7:0] for noise wave generation */ #define DAC_LFSRUNMASK_BITS8_0 ((uint32_t)DAC_CR_MAMP1_3) /*!< Unmask DAC channel LFSR bit[8:0] for noise wave generation */ #define DAC_LFSRUNMASK_BITS9_0 ((uint32_t)DAC_CR_MAMP1_3 | DAC_CR_MAMP1_0) /*!< Unmask DAC channel LFSR bit[9:0] for noise wave generation */ #define DAC_LFSRUNMASK_BITS10_0 ((uint32_t)DAC_CR_MAMP1_3 | DAC_CR_MAMP1_1) /*!< Unmask DAC channel LFSR bit[10:0] for noise wave generation */ #define DAC_LFSRUNMASK_BITS11_0 ((uint32_t)DAC_CR_MAMP1_3 | DAC_CR_MAMP1_1 | DAC_CR_MAMP1_0) /*!< Unmask DAC channel LFSR bit[11:0] for noise wave generation */ #define DAC_TRIANGLEAMPLITUDE_1 ((uint32_t)0x00000000) /*!< Select max triangle amplitude of 1 */ #define DAC_TRIANGLEAMPLITUDE_3 ((uint32_t)DAC_CR_MAMP1_0) /*!< Select max triangle amplitude of 3 */ #define DAC_TRIANGLEAMPLITUDE_7 ((uint32_t)DAC_CR_MAMP1_1) /*!< Select max triangle amplitude of 7 */ #define DAC_TRIANGLEAMPLITUDE_15 ((uint32_t)DAC_CR_MAMP1_1 | DAC_CR_MAMP1_0) /*!< Select max triangle amplitude of 15 */ #define DAC_TRIANGLEAMPLITUDE_31 ((uint32_t)DAC_CR_MAMP1_2) /*!< Select max triangle amplitude of 31 */ #define DAC_TRIANGLEAMPLITUDE_63 ((uint32_t)DAC_CR_MAMP1_2 | DAC_CR_MAMP1_0) /*!< Select max triangle amplitude of 63 */ #define DAC_TRIANGLEAMPLITUDE_127 ((uint32_t)DAC_CR_MAMP1_2 | DAC_CR_MAMP1_1) /*!< Select max triangle amplitude of 127 */ #define DAC_TRIANGLEAMPLITUDE_255 ((uint32_t)DAC_CR_MAMP1_2 | DAC_CR_MAMP1_1 | DAC_CR_MAMP1_0) /*!< Select max triangle amplitude of 255 */ #define DAC_TRIANGLEAMPLITUDE_511 ((uint32_t)DAC_CR_MAMP1_3) /*!< Select max triangle amplitude of 511 */ #define DAC_TRIANGLEAMPLITUDE_1023 ((uint32_t)DAC_CR_MAMP1_3 | DAC_CR_MAMP1_0) /*!< Select max triangle amplitude of 1023 */ #define DAC_TRIANGLEAMPLITUDE_2047 ((uint32_t)DAC_CR_MAMP1_3 | DAC_CR_MAMP1_1) /*!< Select max triangle amplitude of 2047 */ #define DAC_TRIANGLEAMPLITUDE_4095 ((uint32_t)DAC_CR_MAMP1_3 | DAC_CR_MAMP1_1 | DAC_CR_MAMP1_0) /*!< Select max triangle amplitude of 4095 */ /** * @} */ /** * @} */ /* Exported macro ------------------------------------------------------------*/ /** @defgroup DACEx_Exported_Macros DACEx Exported Macros * @{ */ /** @defgroup DAC_trigger_selection DAC trigger selection * @{ */ #if defined(STM32F051x8) || defined(STM32F058xx) #define DAC_TRIGGER_NONE ((uint32_t)0x00000000) /*!< Conversion is automatic once the DAC1_DHRxxxx register has been loaded, and not by external trigger */ #define DAC_TRIGGER_T2_TRGO ((uint32_t)(DAC_CR_TSEL1_2 | DAC_CR_TEN1)) /*!< TIM2 TRGO selected as external conversion trigger for DAC channel */ #define DAC_TRIGGER_T3_TRGO ((uint32_t)(DAC_CR_TSEL1_0 | DAC_CR_TEN1)) /*!< TIM3 TRGO selected as external conversion trigger for DAC channel */ #define DAC_TRIGGER_T6_TRGO ((uint32_t)DAC_CR_TEN1) /*!< TIM6 TRGO selected as external conversion trigger for DAC channel */ #define DAC_TRIGGER_T15_TRGO ((uint32_t)(DAC_CR_TSEL1_1 | DAC_CR_TSEL1_0 | DAC_CR_TEN1)) /*!< TIM15 TRGO selected as external conversion trigger for DAC channel */ #define DAC_TRIGGER_EXT_IT9 ((uint32_t)(DAC_CR_TSEL1_2 | DAC_CR_TSEL1_1 | DAC_CR_TEN1)) /*!< EXTI Line9 event selected as external conversion trigger for DAC channel */ #define DAC_TRIGGER_SOFTWARE ((uint32_t)(DAC_CR_TSEL1 | DAC_CR_TEN1)) /*!< Conversion started by software trigger for DAC channel */ #endif /* STM32F051x8 || STM32F058xx */ #if defined(STM32F071xB) || defined(STM32F072xB) || defined(STM32F078xx) || \ defined(STM32F091xC) || defined(STM32F098xx) #define DAC_TRIGGER_NONE ((uint32_t)0x00000000) /*!< Conversion is automatic once the DAC1_DHRxxxx register has been loaded, and not by external trigger */ #define DAC_TRIGGER_T2_TRGO ((uint32_t)(DAC_CR_TSEL1_2 | DAC_CR_TEN1)) /*!< TIM2 TRGO selected as external conversion trigger for DAC channel */ #define DAC_TRIGGER_T3_TRGO ((uint32_t)(DAC_CR_TSEL1_0 | DAC_CR_TEN1)) /*!< TIM3 TRGO selected as external conversion trigger for DAC channel */ #define DAC_TRIGGER_T6_TRGO ((uint32_t)DAC_CR_TEN1) /*!< TIM6 TRGO selected as external conversion trigger for DAC channel */ #define DAC_TRIGGER_T7_TRGO ((uint32_t)(DAC_CR_TSEL1_1 | DAC_CR_TEN1)) /*!< TIM7 TRGO selected as external conversion trigger for DAC channel */ #define DAC_TRIGGER_T15_TRGO ((uint32_t)(DAC_CR_TSEL1_1 | DAC_CR_TSEL1_0 | DAC_CR_TEN1)) /*!< TIM15 TRGO selected as external conversion trigger for DAC channel */ #define DAC_TRIGGER_EXT_IT9 ((uint32_t)(DAC_CR_TSEL1_2 | DAC_CR_TSEL1_1 | DAC_CR_TEN1)) /*!< EXTI Line9 event selected as external conversion trigger for DAC channel */ #define DAC_TRIGGER_SOFTWARE ((uint32_t)(DAC_CR_TSEL1 | DAC_CR_TEN1)) /*!< Conversion started by software trigger for DAC channel */ #endif /* STM32F071xB || STM32F072xB || STM32F078xx || */ /* STM32F091xC || STM32F098xx */ /** * @} */ /** @defgroup DAC_Channel_selection DAC Channel selection * @{ */ #if defined(STM32F071xB) || defined(STM32F072xB) || defined(STM32F078xx) || \ defined(STM32F091xC) || defined(STM32F098xx) #define DAC_CHANNEL_1 ((uint32_t)0x00000000) #define DAC_CHANNEL_2 ((uint32_t)0x00000010) #endif /* STM32F071xB || STM32F072xB || STM32F078xx || */ /* STM32F091xC || STM32F098xx */ #if defined(STM32F051x8) || defined(STM32F058xx) #define DAC_CHANNEL_1 ((uint32_t)0x00000000) #endif /* STM32F051x8 || STM32F058xx */ /** * @} */ /** * @} */ /* Private macro -------------------------------------------------------------*/ /** @addtogroup DACEx_Private_Macros * @{ */ #if defined(STM32F071xB) || defined(STM32F072xB) || defined(STM32F078xx) || \ defined(STM32F091xC) || defined(STM32F098xx) #define IS_DAC_TRIGGER(TRIGGER) (((TRIGGER) == DAC_TRIGGER_NONE) || \ ((TRIGGER) == DAC_TRIGGER_T2_TRGO) || \ ((TRIGGER) == DAC_TRIGGER_T3_TRGO) || \ ((TRIGGER) == DAC_TRIGGER_T6_TRGO) || \ ((TRIGGER) == DAC_TRIGGER_T7_TRGO) || \ ((TRIGGER) == DAC_TRIGGER_T15_TRGO) || \ ((TRIGGER) == DAC_TRIGGER_EXT_IT9) || \ ((TRIGGER) == DAC_TRIGGER_SOFTWARE)) #endif /* STM32F071xB || STM32F072xB || STM32F078xx || */ /* STM32F091xC || STM32F098xx */ #if defined(STM32F051x8) || defined(STM32F058xx) #define IS_DAC_TRIGGER(TRIGGER) (((TRIGGER) == DAC_TRIGGER_NONE) || \ ((TRIGGER) == DAC_TRIGGER_T2_TRGO) || \ ((TRIGGER) == DAC_TRIGGER_T3_TRGO) || \ ((TRIGGER) == DAC_TRIGGER_T6_TRGO) || \ ((TRIGGER) == DAC_TRIGGER_T15_TRGO) || \ ((TRIGGER) == DAC_TRIGGER_EXT_IT9) || \ ((TRIGGER) == DAC_TRIGGER_SOFTWARE)) #endif /* STM32F051x8 || STM32F058xx */ #if defined(STM32F071xB) || defined(STM32F072xB) || defined(STM32F078xx) || \ defined(STM32F091xC) || defined(STM32F098xx) #define IS_DAC_TRIGGER(TRIGGER) (((TRIGGER) == DAC_TRIGGER_NONE) || \ ((TRIGGER) == DAC_TRIGGER_T2_TRGO) || \ ((TRIGGER) == DAC_TRIGGER_T3_TRGO) || \ ((TRIGGER) == DAC_TRIGGER_T6_TRGO) || \ ((TRIGGER) == DAC_TRIGGER_T7_TRGO) || \ ((TRIGGER) == DAC_TRIGGER_T15_TRGO) || \ ((TRIGGER) == DAC_TRIGGER_EXT_IT9) || \ ((TRIGGER) == DAC_TRIGGER_SOFTWARE)) #endif /* STM32F071xB || STM32F072xB || STM32F078xx || */ /* STM32F091xC || STM32F098xx */ #define IS_DAC_LFSR_UNMASK_TRIANGLE_AMPLITUDE(VALUE) (((VALUE) == DAC_LFSRUNMASK_BIT0) || \ ((VALUE) == DAC_LFSRUNMASK_BITS1_0) || \ ((VALUE) == DAC_LFSRUNMASK_BITS2_0) || \ ((VALUE) == DAC_LFSRUNMASK_BITS3_0) || \ ((VALUE) == DAC_LFSRUNMASK_BITS4_0) || \ ((VALUE) == DAC_LFSRUNMASK_BITS5_0) || \ ((VALUE) == DAC_LFSRUNMASK_BITS6_0) || \ ((VALUE) == DAC_LFSRUNMASK_BITS7_0) || \ ((VALUE) == DAC_LFSRUNMASK_BITS8_0) || \ ((VALUE) == DAC_LFSRUNMASK_BITS9_0) || \ ((VALUE) == DAC_LFSRUNMASK_BITS10_0) || \ ((VALUE) == DAC_LFSRUNMASK_BITS11_0) || \ ((VALUE) == DAC_TRIANGLEAMPLITUDE_1) || \ ((VALUE) == DAC_TRIANGLEAMPLITUDE_3) || \ ((VALUE) == DAC_TRIANGLEAMPLITUDE_7) || \ ((VALUE) == DAC_TRIANGLEAMPLITUDE_15) || \ ((VALUE) == DAC_TRIANGLEAMPLITUDE_31) || \ ((VALUE) == DAC_TRIANGLEAMPLITUDE_63) || \ ((VALUE) == DAC_TRIANGLEAMPLITUDE_127) || \ ((VALUE) == DAC_TRIANGLEAMPLITUDE_255) || \ ((VALUE) == DAC_TRIANGLEAMPLITUDE_511) || \ ((VALUE) == DAC_TRIANGLEAMPLITUDE_1023) || \ ((VALUE) == DAC_TRIANGLEAMPLITUDE_2047) || \ ((VALUE) == DAC_TRIANGLEAMPLITUDE_4095)) /** * @} */ /* Exported functions --------------------------------------------------------*/ /** @addtogroup DACEx_Exported_Functions * @{ */ /** @addtogroup DACEx_Exported_Functions_Group1 * @{ */ /* IO operation functions *****************************************************/ HAL_StatusTypeDef HAL_DACEx_TriangleWaveGenerate(DAC_HandleTypeDef* hdac, uint32_t Channel, uint32_t Amplitude); HAL_StatusTypeDef HAL_DACEx_NoiseWaveGenerate(DAC_HandleTypeDef* hdac, uint32_t Channel, uint32_t Amplitude); HAL_StatusTypeDef HAL_DACEx_DualSetValue(DAC_HandleTypeDef* hdac, uint32_t Alignment, uint32_t Data1, uint32_t Data2); void HAL_DACEx_ConvCpltCallbackCh2(DAC_HandleTypeDef* hdac); void HAL_DACEx_ConvHalfCpltCallbackCh2(DAC_HandleTypeDef* hdac); void HAL_DACEx_ErrorCallbackCh2(DAC_HandleTypeDef* hdac); void HAL_DACEx_DMAUnderrunCallbackCh2(DAC_HandleTypeDef* hdac); /** * @} */ /** @addtogroup DACEx_Exported_Functions_Group3 * @{ */ /* Peripheral Control functions ***********************************************/ uint32_t HAL_DACEx_DualGetValue(DAC_HandleTypeDef* hdac); /** * @} */ /** * @} */ /** * @} */ #endif /* STM32F051x8 || STM32F058xx || */ /* STM32F071xB || STM32F072xB || STM32F078xx || */ /* STM32F091xC || STM32F098xx */ /** * @} */ #ifdef __cplusplus } #endif #endif /*__STM32F0xx_HAL_DAC_EX_H */ /************************ (C) COPYRIGHT STMicroelectronics *****END OF FILE****/ ================================================ FILE: Zelig/mbed/TARGET_NUCLEO_F091RC/stm32f0xx_hal_def.h ================================================ /** ****************************************************************************** * @file stm32f0xx_hal_def.h * @author MCD Application Team * @version V1.3.0 * @date 26-June-2015 * @brief This file contains HAL common defines, enumeration, macros and * structures definitions. ****************************************************************************** * @attention * *

© COPYRIGHT(c) 2015 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. * ****************************************************************************** */ /* Define to prevent recursive inclusion -------------------------------------*/ #ifndef __STM32F0xx_HAL_DEF #define __STM32F0xx_HAL_DEF #ifdef __cplusplus extern "C" { #endif /* Includes ------------------------------------------------------------------*/ #include "stm32f0xx.h" #include "stm32_hal_legacy.h" #include /* Exported types ------------------------------------------------------------*/ /** * @brief HAL Status structures definition */ typedef enum { HAL_OK = 0x00, HAL_ERROR = 0x01, HAL_BUSY = 0x02, HAL_TIMEOUT = 0x03 } HAL_StatusTypeDef; /** * @brief HAL Lock structures definition */ typedef enum { HAL_UNLOCKED = 0x00, HAL_LOCKED = 0x01 } HAL_LockTypeDef; /* Exported macro ------------------------------------------------------------*/ #define HAL_MAX_DELAY 0xFFFFFFFF #define HAL_IS_BIT_SET(REG, BIT) (((REG) & (BIT)) != RESET) #define HAL_IS_BIT_CLR(REG, BIT) (((REG) & (BIT)) == RESET) #define __HAL_LINKDMA(__HANDLE__, __PPP_DMA_FIELD_, __DMA_HANDLE_) \ do{ \ (__HANDLE__)->__PPP_DMA_FIELD_ = &(__DMA_HANDLE_); \ (__DMA_HANDLE_).Parent = (__HANDLE__); \ } while(0) #define UNUSED(x) ((void)(x)) /** @brief Reset the Handle's State field. * @param __HANDLE__: specifies the Peripheral Handle. * @note This macro can be used for the following purpose: * - When the Handle is declared as local variable; before passing it as parameter * to HAL_PPP_Init() for the first time, it is mandatory to use this macro * to set to 0 the Handle's "State" field. * Otherwise, "State" field may have any random value and the first time the function * HAL_PPP_Init() is called, the low level hardware initialization will be missed * (i.e. HAL_PPP_MspInit() will not be executed). * - When there is a need to reconfigure the low level hardware: instead of calling * HAL_PPP_DeInit() then HAL_PPP_Init(), user can make a call to this macro then HAL_PPP_Init(). * In this later function, when the Handle's "State" field is set to 0, it will execute the function * HAL_PPP_MspInit() which will reconfigure the low level hardware. * @retval None */ #define __HAL_RESET_HANDLE_STATE(__HANDLE__) ((__HANDLE__)->State = 0) #if (USE_RTOS == 1) #error " USE_RTOS should be 0 in the current HAL release " #else #define __HAL_LOCK(__HANDLE__) \ do{ \ if((__HANDLE__)->Lock == HAL_LOCKED) \ { \ return HAL_BUSY; \ } \ else \ { \ (__HANDLE__)->Lock = HAL_LOCKED; \ } \ }while (0) #define __HAL_UNLOCK(__HANDLE__) \ do{ \ (__HANDLE__)->Lock = HAL_UNLOCKED; \ }while (0) #endif /* USE_RTOS */ #if defined ( __GNUC__ ) #ifndef __weak #define __weak __attribute__((weak)) #endif /* __weak */ #ifndef __packed #define __packed __attribute__((__packed__)) #endif /* __packed */ #endif /* __GNUC__ */ /* Macro to get variable aligned on 4-bytes, for __ICCARM__ the directive "#pragma data_alignment=4" must be used instead */ #if defined (__GNUC__) /* GNU Compiler */ #ifndef __ALIGN_END #define __ALIGN_END __attribute__ ((aligned (4))) #endif /* __ALIGN_END */ #ifndef __ALIGN_BEGIN #define __ALIGN_BEGIN #endif /* __ALIGN_BEGIN */ #else #ifndef __ALIGN_END #define __ALIGN_END #endif /* __ALIGN_END */ #ifndef __ALIGN_BEGIN #if defined (__CC_ARM) /* ARM Compiler */ #define __ALIGN_BEGIN __align(4) #elif defined (__ICCARM__) /* IAR Compiler */ #define __ALIGN_BEGIN #endif /* __CC_ARM */ #endif /* __ALIGN_BEGIN */ #endif /* __GNUC__ */ /** * @brief __NOINLINE definition */ #if defined ( __CC_ARM ) || defined ( __GNUC__ ) /* ARM & GNUCompiler ---------------- */ #define __NOINLINE __attribute__ ( (noinline) ) #elif defined ( __ICCARM__ ) /* ICCARM Compiler --------------- */ #define __NOINLINE _Pragma("optimize = no_inline") #endif #ifdef __cplusplus } #endif #endif /* ___STM32F0xx_HAL_DEF */ /************************ (C) COPYRIGHT STMicroelectronics *****END OF FILE****/ ================================================ FILE: Zelig/mbed/TARGET_NUCLEO_F091RC/stm32f0xx_hal_dma.h ================================================ /** ****************************************************************************** * @file stm32f0xx_hal_dma.h * @author MCD Application Team * @version V1.3.0 * @date 26-June-2015 * @brief Header file of DMA HAL module. ****************************************************************************** * @attention * *

© COPYRIGHT(c) 2015 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. * ****************************************************************************** */ /* Define to prevent recursive inclusion -------------------------------------*/ #ifndef __STM32F0xx_HAL_DMA_H #define __STM32F0xx_HAL_DMA_H #ifdef __cplusplus extern "C" { #endif /* Includes ------------------------------------------------------------------*/ #include "stm32f0xx_hal_def.h" /** @addtogroup STM32F0xx_HAL_Driver * @{ */ /** @addtogroup DMA * @{ */ /* Exported types ------------------------------------------------------------*/ /** @defgroup DMA_Exported_Types DMA Exported Types * @{ */ /** * @brief DMA Configuration Structure definition */ typedef struct { uint32_t Direction; /*!< Specifies if the data will be transferred from memory to peripheral, from memory to memory or from peripheral to memory. This parameter can be a value of @ref DMA_Data_transfer_direction */ uint32_t PeriphInc; /*!< Specifies whether the Peripheral address register should be incremented or not. This parameter can be a value of @ref DMA_Peripheral_incremented_mode */ uint32_t MemInc; /*!< Specifies whether the memory address register should be incremented or not. This parameter can be a value of @ref DMA_Memory_incremented_mode */ uint32_t PeriphDataAlignment; /*!< Specifies the Peripheral data width. This parameter can be a value of @ref DMA_Peripheral_data_size */ uint32_t MemDataAlignment; /*!< Specifies the Memory data width. This parameter can be a value of @ref DMA_Memory_data_size */ uint32_t Mode; /*!< Specifies the operation mode of the DMAy Channelx. This parameter can be a value of @ref DMA_mode @note The circular buffer mode cannot be used if the memory-to-memory data transfer is configured on the selected Channel */ uint32_t Priority; /*!< Specifies the software priority for the DMAy Channelx. This parameter can be a value of @ref DMA_Priority_level */ } DMA_InitTypeDef; /** * @brief DMA Configuration enumeration values definition */ typedef enum { DMA_MODE = 0, /*!< Control related DMA mode Parameter in DMA_InitTypeDef */ DMA_PRIORITY = 1, /*!< Control related priority level Parameter in DMA_InitTypeDef */ } DMA_ControlTypeDef; /** * @brief HAL DMA State structures definition */ typedef enum { HAL_DMA_STATE_RESET = 0x00, /*!< DMA not yet initialized or disabled */ HAL_DMA_STATE_READY = 0x01, /*!< DMA initialized and ready for use */ HAL_DMA_STATE_READY_HALF = 0x11, /*!< DMA Half process success */ HAL_DMA_STATE_BUSY = 0x02, /*!< DMA process is ongoing */ HAL_DMA_STATE_TIMEOUT = 0x03, /*!< DMA timeout state */ HAL_DMA_STATE_ERROR = 0x04, /*!< DMA error state */ }HAL_DMA_StateTypeDef; /** * @brief HAL DMA Error Code structure definition */ typedef enum { HAL_DMA_FULL_TRANSFER = 0x00, /*!< Full transfer */ HAL_DMA_HALF_TRANSFER = 0x01, /*!< Half Transfer */ }HAL_DMA_LevelCompleteTypeDef; /** * @brief DMA handle Structure definition */ typedef struct __DMA_HandleTypeDef { DMA_Channel_TypeDef *Instance; /*!< Register base address */ DMA_InitTypeDef Init; /*!< DMA communication parameters */ HAL_LockTypeDef Lock; /*!< DMA locking object */ __IO HAL_DMA_StateTypeDef State; /*!< DMA transfer state */ void *Parent; /*!< Parent object state */ void (* XferCpltCallback)( struct __DMA_HandleTypeDef * hdma); /*!< DMA transfer complete callback */ void (* XferHalfCpltCallback)( struct __DMA_HandleTypeDef * hdma); /*!< DMA Half transfer complete callback */ void (* XferErrorCallback)( struct __DMA_HandleTypeDef * hdma); /*!< DMA transfer error callback */ __IO uint32_t ErrorCode; /*!< DMA Error code */ } DMA_HandleTypeDef; /** * @} */ /* Exported constants --------------------------------------------------------*/ /** @defgroup DMA_Exported_Constants DMA Exported Constants * @{ */ /** @defgroup DMA_Error_Code DMA Error Code * @{ */ #define HAL_DMA_ERROR_NONE ((uint32_t)0x00000000) /*!< No error */ #define HAL_DMA_ERROR_TE ((uint32_t)0x00000001) /*!< Transfer error */ #define HAL_DMA_ERROR_TIMEOUT ((uint32_t)0x00000020) /*!< Timeout error */ /** * @} */ /** @defgroup DMA_Data_transfer_direction DMA Data transfer direction * @{ */ #define DMA_PERIPH_TO_MEMORY ((uint32_t)0x00000000) /*!< Peripheral to memory direction */ #define DMA_MEMORY_TO_PERIPH ((uint32_t)DMA_CCR_DIR) /*!< Memory to peripheral direction */ #define DMA_MEMORY_TO_MEMORY ((uint32_t)(DMA_CCR_MEM2MEM)) /*!< Memory to memory direction */ /** * @} */ /** @defgroup DMA_Peripheral_incremented_mode DMA Peripheral incremented mode * @{ */ #define DMA_PINC_ENABLE ((uint32_t)DMA_CCR_PINC) /*!< Peripheral increment mode Enable */ #define DMA_PINC_DISABLE ((uint32_t)0x00000000) /*!< Peripheral increment mode Disable */ /** * @} */ /** @defgroup DMA_Memory_incremented_mode DMA Memory incremented mode * @{ */ #define DMA_MINC_ENABLE ((uint32_t)DMA_CCR_MINC) /*!< Memory increment mode Enable */ #define DMA_MINC_DISABLE ((uint32_t)0x00000000) /*!< Memory increment mode Disable */ /** * @} */ /** @defgroup DMA_Peripheral_data_size DMA Peripheral data size * @{ */ #define DMA_PDATAALIGN_BYTE ((uint32_t)0x00000000) /*!< Peripheral data alignment : Byte */ #define DMA_PDATAALIGN_HALFWORD ((uint32_t)DMA_CCR_PSIZE_0) /*!< Peripheral data alignment : HalfWord */ #define DMA_PDATAALIGN_WORD ((uint32_t)DMA_CCR_PSIZE_1) /*!< Peripheral data alignment : Word */ /** * @} */ /** @defgroup DMA_Memory_data_size DMA Memory data size * @{ */ #define DMA_MDATAALIGN_BYTE ((uint32_t)0x00000000) /*!< Memory data alignment : Byte */ #define DMA_MDATAALIGN_HALFWORD ((uint32_t)DMA_CCR_MSIZE_0) /*!< Memory data alignment : HalfWord */ #define DMA_MDATAALIGN_WORD ((uint32_t)DMA_CCR_MSIZE_1) /*!< Memory data alignment : Word */ /** * @} */ /** @defgroup DMA_mode DMA mode * @{ */ #define DMA_NORMAL ((uint32_t)0x00000000) /*!< Normal Mode */ #define DMA_CIRCULAR ((uint32_t)DMA_CCR_CIRC) /*!< Circular Mode */ /** * @} */ /** @defgroup DMA_Priority_level DMA Priority level * @{ */ #define DMA_PRIORITY_LOW ((uint32_t)0x00000000) /*!< Priority level : Low */ #define DMA_PRIORITY_MEDIUM ((uint32_t)DMA_CCR_PL_0) /*!< Priority level : Medium */ #define DMA_PRIORITY_HIGH ((uint32_t)DMA_CCR_PL_1) /*!< Priority level : High */ #define DMA_PRIORITY_VERY_HIGH ((uint32_t)DMA_CCR_PL) /*!< Priority level : Very_High */ /** * @} */ /** @defgroup DMA_interrupt_enable_definitions DMA interrupt enable definitions * @{ */ #define DMA_IT_TC ((uint32_t)DMA_CCR_TCIE) #define DMA_IT_HT ((uint32_t)DMA_CCR_HTIE) #define DMA_IT_TE ((uint32_t)DMA_CCR_TEIE) /** * @} */ /** @defgroup DMA_flag_definitions DMA flag definitions * @{ */ #define DMA_FLAG_GL1 ((uint32_t)0x00000001) /*!< Channel 1 global interrupt flag */ #define DMA_FLAG_TC1 ((uint32_t)0x00000002) /*!< Channel 1 transfer complete flag */ #define DMA_FLAG_HT1 ((uint32_t)0x00000004) /*!< Channel 1 half transfer flag */ #define DMA_FLAG_TE1 ((uint32_t)0x00000008) /*!< Channel 1 transfer error flag */ #define DMA_FLAG_GL2 ((uint32_t)0x00000010) /*!< Channel 2 global interrupt flag */ #define DMA_FLAG_TC2 ((uint32_t)0x00000020) /*!< Channel 2 transfer complete flag */ #define DMA_FLAG_HT2 ((uint32_t)0x00000040) /*!< Channel 2 half transfer flag */ #define DMA_FLAG_TE2 ((uint32_t)0x00000080) /*!< Channel 2 transfer error flag */ #define DMA_FLAG_GL3 ((uint32_t)0x00000100) /*!< Channel 3 global interrupt flag */ #define DMA_FLAG_TC3 ((uint32_t)0x00000200) /*!< Channel 3 transfer complete flag */ #define DMA_FLAG_HT3 ((uint32_t)0x00000400) /*!< Channel 3 half transfer flag */ #define DMA_FLAG_TE3 ((uint32_t)0x00000800) /*!< Channel 3 transfer error flag */ #define DMA_FLAG_GL4 ((uint32_t)0x00001000) /*!< Channel 4 global interrupt flag */ #define DMA_FLAG_TC4 ((uint32_t)0x00002000) /*!< Channel 4 transfer complete flag */ #define DMA_FLAG_HT4 ((uint32_t)0x00004000) /*!< Channel 4 half transfer flag */ #define DMA_FLAG_TE4 ((uint32_t)0x00008000) /*!< Channel 4 transfer error flag */ #define DMA_FLAG_GL5 ((uint32_t)0x00010000) /*!< Channel 5 global interrupt flag */ #define DMA_FLAG_TC5 ((uint32_t)0x00020000) /*!< Channel 5 transfer complete flag */ #define DMA_FLAG_HT5 ((uint32_t)0x00040000) /*!< Channel 5 half transfer flag */ #define DMA_FLAG_TE5 ((uint32_t)0x00080000) /*!< Channel 5 transfer error flag */ #define DMA_FLAG_GL6 ((uint32_t)0x00100000) /*!< Channel 6 global interrupt flag */ #define DMA_FLAG_TC6 ((uint32_t)0x00200000) /*!< Channel 6 transfer complete flag */ #define DMA_FLAG_HT6 ((uint32_t)0x00400000) /*!< Channel 6 half transfer flag */ #define DMA_FLAG_TE6 ((uint32_t)0x00800000) /*!< Channel 6 transfer error flag */ #define DMA_FLAG_GL7 ((uint32_t)0x01000000) /*!< Channel 7 global interrupt flag */ #define DMA_FLAG_TC7 ((uint32_t)0x02000000) /*!< Channel 7 transfer complete flag */ #define DMA_FLAG_HT7 ((uint32_t)0x04000000) /*!< Channel 7 half transfer flag */ #define DMA_FLAG_TE7 ((uint32_t)0x08000000) /*!< Channel 7 transfer error flag */ /** * @} */ #if defined(SYSCFG_CFGR1_DMA_RMP) /** @defgroup HAL_DMA_remapping HAL DMA remapping * Elements values convention: 0xYYYYYYYY * - YYYYYYYY : Position in the SYSCFG register CFGR1 * @{ */ #define DMA_REMAP_ADC_DMA_CH2 ((uint32_t)SYSCFG_CFGR1_ADC_DMA_RMP) /*!< ADC DMA remap 0: No remap (ADC DMA requests mapped on DMA channel 1 1: Remap (ADC DMA requests mapped on DMA channel 2 */ #define DMA_REMAP_USART1_TX_DMA_CH4 ((uint32_t)SYSCFG_CFGR1_USART1TX_DMA_RMP) /*!< USART1 TX DMA remap 0: No remap (USART1_TX DMA request mapped on DMA channel 2 1: Remap (USART1_TX DMA request mapped on DMA channel 4 */ #define DMA_REMAP_USART1_RX_DMA_CH5 ((uint32_t)SYSCFG_CFGR1_USART1RX_DMA_RMP) /*!< USART1 RX DMA remap 0: No remap (USART1_RX DMA request mapped on DMA channel 3 1: Remap (USART1_RX DMA request mapped on DMA channel 5 */ #define DMA_REMAP_TIM16_DMA_CH4 ((uint32_t)SYSCFG_CFGR1_TIM16_DMA_RMP) /*!< TIM16 DMA request remap 0: No remap (TIM16_CH1 and TIM16_UP DMA requests mapped on DMA channel 3) 1: Remap (TIM16_CH1 and TIM16_UP DMA requests mapped on DMA channel 4) */ #define DMA_REMAP_TIM17_DMA_CH2 ((uint32_t)SYSCFG_CFGR1_TIM17_DMA_RMP) /*!< TIM17 DMA request remap 0: No remap (TIM17_CH1 and TIM17_UP DMA requests mapped on DMA channel 1 1: Remap (TIM17_CH1 and TIM17_UP DMA requests mapped on DMA channel 2) */ #if defined (STM32F070xB) #define DMA_REMAP_USART3_DMA_CH32 ((uint32_t)SYSCFG_CFGR1_USART3_DMA_RMP) /*!< USART3 DMA request remapping bit. Available on STM32F070xB devices only. 0: Disabled, need to remap before use 1: Remap (USART3_RX and USART3_TX DMA requests mapped on DMA channel 3 and 2 respectively) */ #endif #if defined (STM32F071xB) || defined (STM32F072xB) || defined (STM32F078xx) #define DMA_REMAP_TIM16_DMA_CH6 ((uint32_t)SYSCFG_CFGR1_TIM16_DMA_RMP2) /*!< TIM16 alternate DMA request remapping bit. Available on STM32F07x devices only 0: No alternate remap (TIM16 DMA requestsmapped according to TIM16_DMA_RMP bit) 1: Alternate remap (TIM16_CH1 and TIM16_UP DMA requests mapped on DMA channel 6) */ #define DMA_REMAP_TIM17_DMA_CH7 ((uint32_t)SYSCFG_CFGR1_TIM17_DMA_RMP2) /*!< TIM17 alternate DMA request remapping bit. Available on STM32F07x devices only 0: No alternate remap (TIM17 DMA requestsmapped according to TIM17_DMA_RMP bit) 1: Alternate remap (TIM17_CH1 and TIM17_UP DMA requests mapped on DMA channel 7) */ #define DMA_REMAP_SPI2_DMA_CH67 ((uint32_t)SYSCFG_CFGR1_SPI2_DMA_RMP) /*!< SPI2 DMA request remapping bit. Available on STM32F07x devices only. 0: No remap (SPI2_RX and SPI2_TX DMA requests mapped on DMA channel 4 and 5 respectively) 1: Remap (SPI2_RX and SPI2_TX DMA requests mapped on DMA channel 6 and 7 respectively) */ #define DMA_REMAP_USART2_DMA_CH67 ((uint32_t)SYSCFG_CFGR1_USART2_DMA_RMP) /*!< USART2 DMA request remapping bit. Available on STM32F07x devices only. 0: No remap (USART2_RX and USART2_TX DMA requests mapped on DMA channel 5 and 4 respectively) 1: 1: Remap (USART2_RX and USART2_TX DMA requests mapped on DMA channel 6 and 7 respectively) */ #define DMA_REMAP_USART3_DMA_CH32 ((uint32_t)SYSCFG_CFGR1_USART3_DMA_RMP) /*!< USART3 DMA request remapping bit. Available on STM32F07x devices only. 0: No remap (USART3_RX and USART3_TX DMA requests mapped on DMA channel 6 and 7 respectively) 1: Remap (USART3_RX and USART3_TX DMA requests mapped on DMA channel 3 and 2 respectively) */ #define DMA_REMAP_I2C1_DMA_CH76 ((uint32_t)SYSCFG_CFGR1_I2C1_DMA_RMP) /*!< I2C1 DMA request remapping bit. Available on STM32F07x devices only. 0: No remap (I2C1_RX and I2C1_TX DMA requests mapped on DMA channel 3 and 2 respectively) 1: Remap (I2C1_RX and I2C1_TX DMA requests mapped on DMA channel 7 and 6 respectively) */ #define DMA_REMAP_TIM1_DMA_CH6 ((uint32_t)SYSCFG_CFGR1_TIM1_DMA_RMP) /*!< TIM1 DMA request remapping bit. Available on STM32F07x devices only. 0: No remap (TIM1_CH1, TIM1_CH2 and TIM1_CH3 DMA requests mapped on DMA channel 2, 3 and 4 respectively) 1: Remap (TIM1_CH1, TIM1_CH2 and TIM1_CH3 DMA requests mapped on DMA channel 6 */ #define DMA_REMAP_TIM2_DMA_CH7 ((uint32_t)SYSCFG_CFGR1_TIM2_DMA_RMP) /*!< TIM2 DMA request remapping bit. Available on STM32F07x devices only. 0: No remap (TIM2_CH2 and TIM2_CH4 DMA requests mapped on DMA channel 3 and 4 respectively) 1: Remap (TIM2_CH2 and TIM2_CH4 DMA requests mapped on DMA channel 7 */ #define DMA_REMAP_TIM3_DMA_CH6 ((uint32_t)SYSCFG_CFGR1_TIM3_DMA_RMP) /*!< TIM3 DMA request remapping bit. Available on STM32F07x devices only. 0: No remap (TIM3_CH1 and TIM3_TRIG DMA requests mapped on DMA channel 4) 1: Remap (TIM3_CH1 and TIM3_TRIG DMA requests mapped on DMA channel 6) */ #endif /** * @} */ #endif /* SYSCFG_CFGR1_DMA_RMP */ /** * @} */ /* Exported macro ------------------------------------------------------------*/ /** @defgroup DMA_Exported_Macros DMA Exported Macros * @{ */ /** @brief Reset DMA handle state * @param __HANDLE__: DMA handle. * @retval None */ #define __HAL_DMA_RESET_HANDLE_STATE(__HANDLE__) ((__HANDLE__)->State = HAL_DMA_STATE_RESET) /** * @brief Enable the specified DMA Channel. * @param __HANDLE__: DMA handle * @retval None */ #define __HAL_DMA_ENABLE(__HANDLE__) (SET_BIT((__HANDLE__)->Instance->CCR, DMA_CCR_EN)) /** * @brief Disable the specified DMA Channel. * @param __HANDLE__: DMA handle * @retval None */ #define __HAL_DMA_DISABLE(__HANDLE__) (CLEAR_BIT((__HANDLE__)->Instance->CCR, DMA_CCR_EN)) /* Interrupt & Flag management */ /** * @brief Enables the specified DMA Channel interrupts. * @param __HANDLE__: DMA handle * @param __INTERRUPT__: specifies the DMA interrupt sources to be enabled or disabled. * This parameter can be any combination of the following values: * @arg DMA_IT_TC: Transfer complete interrupt mask * @arg DMA_IT_HT: Half transfer complete interrupt mask * @arg DMA_IT_TE: Transfer error interrupt mask * @retval None */ #define __HAL_DMA_ENABLE_IT(__HANDLE__, __INTERRUPT__) (SET_BIT((__HANDLE__)->Instance->CCR, (__INTERRUPT__))) /** * @brief Disables the specified DMA Channel interrupts. * @param __HANDLE__: DMA handle * @param __INTERRUPT__: specifies the DMA interrupt sources to be enabled or disabled. * This parameter can be any combination of the following values: * @arg DMA_IT_TC: Transfer complete interrupt mask * @arg DMA_IT_HT: Half transfer complete interrupt mask * @arg DMA_IT_TE: Transfer error interrupt mask * @retval None */ #define __HAL_DMA_DISABLE_IT(__HANDLE__, __INTERRUPT__) (CLEAR_BIT((__HANDLE__)->Instance->CCR , (__INTERRUPT__))) /** * @brief Checks whether the specified DMA Channel interrupt is enabled or disabled. * @param __HANDLE__: DMA handle * @param __INTERRUPT__: specifies the DMA interrupt source to check. * This parameter can be one of the following values: * @arg DMA_IT_TC: Transfer complete interrupt mask * @arg DMA_IT_HT: Half transfer complete interrupt mask * @arg DMA_IT_TE: Transfer error interrupt mask * @retval The state of DMA_IT (SET or RESET). */ #define __HAL_DMA_GET_IT_SOURCE(__HANDLE__, __INTERRUPT__) ((((__HANDLE__)->Instance->CCR & (__INTERRUPT__)) == (__INTERRUPT__)) ? SET : RESET) #if defined(SYSCFG_CFGR1_DMA_RMP) /** @brief DMA remapping enable/disable macros * @param __DMA_REMAP__: This parameter can be a value of @ref HAL_DMA_remapping */ #define __HAL_DMA_REMAP_CHANNEL_ENABLE(__DMA_REMAP__) do {assert_param(IS_DMA_REMAP((__DMA_REMAP__))); \ SYSCFG->CFGR1 |= (__DMA_REMAP__); \ }while(0) #define __HAL_DMA_REMAP_CHANNEL_DISABLE(__DMA_REMAP__) do {assert_param(IS_DMA_REMAP((__DMA_REMAP__))); \ SYSCFG->CFGR1 &= ~(__DMA_REMAP__); \ }while(0) #endif /* SYSCFG_CFGR1_DMA_RMP */ /** * @} */ /* Include DMA HAL Extension module */ #include "stm32f0xx_hal_dma_ex.h" /* Exported functions --------------------------------------------------------*/ /** @addtogroup DMA_Exported_Functions * @{ */ /** @addtogroup DMA_Exported_Functions_Group1 * @{ */ /* Initialization and de-initialization functions *****************************/ HAL_StatusTypeDef HAL_DMA_Init(DMA_HandleTypeDef *hdma); HAL_StatusTypeDef HAL_DMA_DeInit (DMA_HandleTypeDef *hdma); /** * @} */ /** @addtogroup DMA_Exported_Functions_Group2 * @{ */ /* Input and Output operation functions *****************************************************/ HAL_StatusTypeDef HAL_DMA_Start (DMA_HandleTypeDef *hdma, uint32_t SrcAddress, uint32_t DstAddress, uint32_t DataLength); HAL_StatusTypeDef HAL_DMA_Start_IT(DMA_HandleTypeDef *hdma, uint32_t SrcAddress, uint32_t DstAddress, uint32_t DataLength); HAL_StatusTypeDef HAL_DMA_Abort(DMA_HandleTypeDef *hdma); HAL_StatusTypeDef HAL_DMA_PollForTransfer(DMA_HandleTypeDef *hdma, uint32_t CompleteLevel, uint32_t Timeout); void HAL_DMA_IRQHandler(DMA_HandleTypeDef *hdma); /** * @} */ /** @addtogroup DMA_Exported_Functions_Group3 * @{ */ /* Peripheral State and Error functions ***************************************/ HAL_DMA_StateTypeDef HAL_DMA_GetState(DMA_HandleTypeDef *hdma); uint32_t HAL_DMA_GetError(DMA_HandleTypeDef *hdma); /** * @} */ /** * @} */ /** @addtogroup DMA_Private_Macros * @{ */ #define IS_DMA_DIRECTION(DIRECTION) (((DIRECTION) == DMA_PERIPH_TO_MEMORY ) || \ ((DIRECTION) == DMA_MEMORY_TO_PERIPH) || \ ((DIRECTION) == DMA_MEMORY_TO_MEMORY)) #define IS_DMA_PERIPHERAL_INC_STATE(STATE) (((STATE) == DMA_PINC_ENABLE) || \ ((STATE) == DMA_PINC_DISABLE)) #define IS_DMA_MEMORY_INC_STATE(STATE) (((STATE) == DMA_MINC_ENABLE) || \ ((STATE) == DMA_MINC_DISABLE)) #define IS_DMA_PERIPHERAL_DATA_SIZE(SIZE) (((SIZE) == DMA_PDATAALIGN_BYTE) || \ ((SIZE) == DMA_PDATAALIGN_HALFWORD) || \ ((SIZE) == DMA_PDATAALIGN_WORD)) #define IS_DMA_MEMORY_DATA_SIZE(SIZE) (((SIZE) == DMA_MDATAALIGN_BYTE) || \ ((SIZE) == DMA_MDATAALIGN_HALFWORD) || \ ((SIZE) == DMA_MDATAALIGN_WORD )) #define IS_DMA_MODE(MODE) (((MODE) == DMA_NORMAL ) || \ ((MODE) == DMA_CIRCULAR)) #define IS_DMA_PRIORITY(PRIORITY) (((PRIORITY) == DMA_PRIORITY_LOW ) || \ ((PRIORITY) == DMA_PRIORITY_MEDIUM) || \ ((PRIORITY) == DMA_PRIORITY_HIGH) || \ ((PRIORITY) == DMA_PRIORITY_VERY_HIGH)) #define IS_DMA_BUFFER_SIZE(SIZE) (((SIZE) >= 0x1) && ((SIZE) < 0x10000)) #if defined(SYSCFG_CFGR1_DMA_RMP) #if defined (STM32F071xB) || defined (STM32F072xB) || defined (STM32F078xx) #define IS_DMA_REMAP(RMP) (((RMP) == DMA_REMAP_ADC_DMA_CH2) || \ ((RMP) == DMA_REMAP_USART1_TX_DMA_CH4) || \ ((RMP) == DMA_REMAP_USART1_RX_DMA_CH5) || \ ((RMP) == DMA_REMAP_TIM16_DMA_CH4) || \ ((RMP) == DMA_REMAP_TIM17_DMA_CH2) || \ ((RMP) == DMA_REMAP_TIM16_DMA_CH6) || \ ((RMP) == DMA_REMAP_TIM17_DMA_CH7) || \ ((RMP) == DMA_REMAP_SPI2_DMA_CH67) || \ ((RMP) == DMA_REMAP_USART2_DMA_CH67) || \ ((RMP) == DMA_REMAP_USART3_DMA_CH32) || \ ((RMP) == DMA_REMAP_I2C1_DMA_CH76) || \ ((RMP) == DMA_REMAP_TIM1_DMA_CH6) || \ ((RMP) == DMA_REMAP_TIM2_DMA_CH7) || \ ((RMP) == DMA_REMAP_TIM3_DMA_CH6)) #elif defined (STM32F070xB) #define IS_DMA_REMAP(RMP) (((RMP) == DMA_REMAP_USART3_DMA_CH32) || \ ((RMP) == DMA_REMAP_ADC_DMA_CH2) || \ ((RMP) == DMA_REMAP_USART1_TX_DMA_CH4) || \ ((RMP) == DMA_REMAP_USART1_RX_DMA_CH5) || \ ((RMP) == DMA_REMAP_TIM16_DMA_CH4) || \ ((RMP) == DMA_REMAP_TIM17_DMA_CH2)) #else #define IS_DMA_REMAP(RMP) (((RMP) == DMA_REMAP_ADC_DMA_CH2) || \ ((RMP) == DMA_REMAP_USART1_TX_DMA_CH4) || \ ((RMP) == DMA_REMAP_USART1_RX_DMA_CH5) || \ ((RMP) == DMA_REMAP_TIM16_DMA_CH4) || \ ((RMP) == DMA_REMAP_TIM17_DMA_CH2)) #endif #endif /* SYSCFG_CFGR1_DMA_RMP */ /** * @} */ /** * @} */ /** * @} */ #ifdef __cplusplus } #endif #endif /* __STM32F0xx_HAL_DMA_H */ /************************ (C) COPYRIGHT STMicroelectronics *****END OF FILE****/ ================================================ FILE: Zelig/mbed/TARGET_NUCLEO_F091RC/stm32f0xx_hal_dma_ex.h ================================================ /** ****************************************************************************** * @file stm32f0xx_hal_dma_ex.h * @author MCD Application Team * @version V1.3.0 * @date 26-June-2015 * @brief Header file of DMA HAL Extension module. ****************************************************************************** * @attention * *

© COPYRIGHT(c) 2015 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. * ****************************************************************************** */ /* Define to prevent recursive inclusion -------------------------------------*/ #ifndef __STM32F0xx_HAL_DMA_EX_H #define __STM32F0xx_HAL_DMA_EX_H #ifdef __cplusplus extern "C" { #endif /* Includes ------------------------------------------------------------------*/ #include "stm32f0xx_hal_def.h" /** @addtogroup STM32F0xx_HAL_Driver * @{ */ /** @defgroup DMAEx DMAEx * @brief DMA HAL module driver * @{ */ /* Exported types ------------------------------------------------------------*/ /* Exported constants --------------------------------------------------------*/ #if defined(STM32F091xC) || defined(STM32F098xx) || defined(STM32F030xC) /** @defgroup DMAEx_Exported_Constants DMAEx Exported Constants * @{ */ #define DMA1_CHANNEL1_RMP 0x00000000 /*!< Internal define for remaping on STM32F09x/30xC */ #define DMA1_CHANNEL2_RMP 0x10000000 /*!< Internal define for remaping on STM32F09x/30xC */ #define DMA1_CHANNEL3_RMP 0x20000000 /*!< Internal define for remaping on STM32F09x/30xC */ #define DMA1_CHANNEL4_RMP 0x30000000 /*!< Internal define for remaping on STM32F09x/30xC */ #define DMA1_CHANNEL5_RMP 0x40000000 /*!< Internal define for remaping on STM32F09x/30xC */ #if !defined(STM32F030xC) #define DMA1_CHANNEL6_RMP 0x50000000 /*!< Internal define for remaping on STM32F09x/30xC */ #define DMA1_CHANNEL7_RMP 0x60000000 /*!< Internal define for remaping on STM32F09x/30xC */ #define DMA2_CHANNEL1_RMP 0x00000000 /*!< Internal define for remaping on STM32F09x/30xC */ #define DMA2_CHANNEL2_RMP 0x10000000 /*!< Internal define for remaping on STM32F09x/30xC */ #define DMA2_CHANNEL3_RMP 0x20000000 /*!< Internal define for remaping on STM32F09x/30xC */ #define DMA2_CHANNEL4_RMP 0x30000000 /*!< Internal define for remaping on STM32F09x/30xC */ #define DMA2_CHANNEL5_RMP 0x40000000 /*!< Internal define for remaping on STM32F09x/30xC */ #endif /* !defined(STM32F030xC) */ /****************** DMA1 remap bit field definition********************/ /* DMA1 - Channel 1 */ #define HAL_DMA1_CH1_DEFAULT (uint32_t) (DMA1_CHANNEL1_RMP | DMA1_CSELR_DEFAULT) /*!< Default remap position for DMA1 */ #define HAL_DMA1_CH1_ADC (uint32_t) (DMA1_CHANNEL1_RMP | DMA1_CSELR_CH1_ADC) /*!< Remap ADC on DMA1 Channel 1*/ #define HAL_DMA1_CH1_TIM17_CH1 (uint32_t) (DMA1_CHANNEL1_RMP | DMA1_CSELR_CH1_TIM17_CH1) /*!< Remap TIM17 channel 1 on DMA1 channel 1 */ #define HAL_DMA1_CH1_TIM17_UP (uint32_t) (DMA1_CHANNEL1_RMP | DMA1_CSELR_CH1_TIM17_UP) /*!< Remap TIM17 up on DMA1 channel 1 */ #define HAL_DMA1_CH1_USART1_RX (uint32_t) (DMA1_CHANNEL1_RMP | DMA1_CSELR_CH1_USART1_RX) /*!< Remap USART1 Rx on DMA1 channel 1 */ #define HAL_DMA1_CH1_USART2_RX (uint32_t) (DMA1_CHANNEL1_RMP | DMA1_CSELR_CH1_USART2_RX) /*!< Remap USART2 Rx on DMA1 channel 1 */ #define HAL_DMA1_CH1_USART3_RX (uint32_t) (DMA1_CHANNEL1_RMP | DMA1_CSELR_CH1_USART3_RX) /*!< Remap USART3 Rx on DMA1 channel 1 */ #define HAL_DMA1_CH1_USART4_RX (uint32_t) (DMA1_CHANNEL1_RMP | DMA1_CSELR_CH1_USART4_RX) /*!< Remap USART4 Rx on DMA1 channel 1 */ #define HAL_DMA1_CH1_USART5_RX (uint32_t) (DMA1_CHANNEL1_RMP | DMA1_CSELR_CH1_USART5_RX) /*!< Remap USART5 Rx on DMA1 channel 1 */ #define HAL_DMA1_CH1_USART6_RX (uint32_t) (DMA1_CHANNEL1_RMP | DMA1_CSELR_CH1_USART6_RX) /*!< Remap USART6 Rx on DMA1 channel 1 */ #if !defined(STM32F030xC) #define HAL_DMA1_CH1_USART7_RX (uint32_t) (DMA1_CHANNEL1_RMP | DMA1_CSELR_CH1_USART7_RX) /*!< Remap USART7 Rx on DMA1 channel 1 */ #define HAL_DMA1_CH1_USART8_RX (uint32_t) (DMA1_CHANNEL1_RMP | DMA1_CSELR_CH1_USART8_RX) /*!< Remap USART8 Rx on DMA1 channel 1 */ #endif /* !defined(STM32F030xC) */ /* DMA1 - Channel 2 */ #define HAL_DMA1_CH2_DEFAULT (uint32_t) (DMA1_CHANNEL2_RMP | DMA1_CSELR_DEFAULT) /*!< Default remap position for DMA1 */ #define HAL_DMA1_CH2_ADC (uint32_t) (DMA1_CHANNEL2_RMP | DMA1_CSELR_CH2_ADC) /*!< Remap ADC on DMA1 channel 2 */ #define HAL_DMA1_CH2_I2C1_TX (uint32_t) (DMA1_CHANNEL2_RMP | DMA1_CSELR_CH2_I2C1_TX) /*!< Remap I2C1 Tx on DMA1 channel 2 */ #define HAL_DMA1_CH2_SPI1_RX (uint32_t) (DMA1_CHANNEL2_RMP | DMA1_CSELR_CH2_SPI1_RX) /*!< Remap SPI1 Rx on DMA1 channel 2 */ #define HAL_DMA1_CH2_TIM1_CH1 (uint32_t) (DMA1_CHANNEL2_RMP | DMA1_CSELR_CH2_TIM1_CH1) /*!< Remap TIM1 channel 1 on DMA1 channel 2 */ #define HAL_DMA1_CH2_TIM17_CH1 (uint32_t) (DMA1_CHANNEL2_RMP | DMA1_CSELR_CH2_TIM17_CH1) /*!< Remap TIM17 channel 1 on DMA1 channel 2 */ #define HAL_DMA1_CH2_TIM17_UP (uint32_t) (DMA1_CHANNEL2_RMP | DMA1_CSELR_CH2_TIM17_UP) /*!< Remap TIM17 up on DMA1 channel 2 */ #define HAL_DMA1_CH2_USART1_TX (uint32_t) (DMA1_CHANNEL2_RMP | DMA1_CSELR_CH2_USART1_TX) /*!< Remap USART1 Tx on DMA1 channel 2 */ #define HAL_DMA1_CH2_USART2_TX (uint32_t) (DMA1_CHANNEL2_RMP | DMA1_CSELR_CH2_USART2_TX) /*!< Remap USART2 Tx on DMA1 channel 2 */ #define HAL_DMA1_CH2_USART3_TX (uint32_t) (DMA1_CHANNEL2_RMP | DMA1_CSELR_CH2_USART3_TX) /*!< Remap USART3 Tx on DMA1 channel 2 */ #define HAL_DMA1_CH2_USART4_TX (uint32_t) (DMA1_CHANNEL2_RMP | DMA1_CSELR_CH2_USART4_TX) /*!< Remap USART4 Tx on DMA1 channel 2 */ #define HAL_DMA1_CH2_USART5_TX (uint32_t) (DMA1_CHANNEL2_RMP | DMA1_CSELR_CH2_USART5_TX) /*!< Remap USART5 Tx on DMA1 channel 2 */ #define HAL_DMA1_CH2_USART6_TX (uint32_t) (DMA1_CHANNEL2_RMP | DMA1_CSELR_CH2_USART6_TX) /*!< Remap USART6 Tx on DMA1 channel 2 */ #if !defined(STM32F030xC) #define HAL_DMA1_CH2_USART7_TX (uint32_t) (DMA1_CHANNEL2_RMP | DMA1_CSELR_CH2_USART7_TX) /*!< Remap USART7 Tx on DMA1 channel 2 */ #define HAL_DMA1_CH2_USART8_TX (uint32_t) (DMA1_CHANNEL2_RMP | DMA1_CSELR_CH2_USART8_TX) /*!< Remap USART8 Tx on DMA1 channel 2 */ #endif /* !defined(STM32F030xC) */ /* DMA1 - Channel 3 */ #define HAL_DMA1_CH3_DEFAULT (uint32_t) (DMA1_CHANNEL3_RMP | DMA1_CSELR_DEFAULT) /*!< Default remap position for DMA1 */ #define HAL_DMA1_CH3_TIM6_UP (uint32_t) (DMA1_CHANNEL3_RMP | DMA1_CSELR_CH3_TIM6_UP) /*!< Remap TIM6 up on DMA1 channel 3 */ #if !defined(STM32F030xC) #define HAL_DMA1_CH3_DAC_CH1 (uint32_t) (DMA1_CHANNEL3_RMP | DMA1_CSELR_CH3_DAC_CH1) /*!< Remap DAC Channel 1on DMA1 channel 3 */ #endif /* !defined(STM32F030xC) */ #define HAL_DMA1_CH3_I2C1_RX (uint32_t) (DMA1_CHANNEL3_RMP | DMA1_CSELR_CH3_I2C1_RX) /*!< Remap I2C1 Rx on DMA1 channel 3 */ #define HAL_DMA1_CH3_SPI1_TX (uint32_t) (DMA1_CHANNEL3_RMP | DMA1_CSELR_CH3_SPI1_TX) /*!< Remap SPI1 Tx on DMA1 channel 3 */ #define HAL_DMA1_CH3_TIM1_CH2 (uint32_t) (DMA1_CHANNEL3_RMP | DMA1_CSELR_CH3_TIM1_CH2) /*!< Remap TIM1 channel 2 on DMA1 channel 3 */ #if !defined(STM32F030xC) #define HAL_DMA1_CH3_TIM2_CH2 (uint32_t) (DMA1_CHANNEL3_RMP | DMA1_CSELR_CH3_TIM2_CH2) /*!< Remap TIM2 channel 2 on DMA1 channel 3 */ #endif /* !defined(STM32F030xC) */ #define HAL_DMA1_CH3_TIM16_CH1 (uint32_t) (DMA1_CHANNEL3_RMP | DMA1_CSELR_CH3_TIM16_CH1) /*!< Remap TIM16 channel 1 on DMA1 channel 3 */ #define HAL_DMA1_CH3_TIM16_UP (uint32_t) (DMA1_CHANNEL3_RMP | DMA1_CSELR_CH3_TIM16_UP) /*!< Remap TIM16 up on DMA1 channel 3 */ #define HAL_DMA1_CH3_USART1_RX (uint32_t) (DMA1_CHANNEL3_RMP | DMA1_CSELR_CH3_USART1_RX) /*!< Remap USART1 Rx on DMA1 channel 3 */ #define HAL_DMA1_CH3_USART2_RX (uint32_t) (DMA1_CHANNEL3_RMP | DMA1_CSELR_CH3_USART2_RX) /*!< Remap USART2 Rx on DMA1 channel 3 */ #define HAL_DMA1_CH3_USART3_RX (uint32_t) (DMA1_CHANNEL3_RMP | DMA1_CSELR_CH3_USART3_RX) /*!< Remap USART3 Rx on DMA1 channel 3 */ #define HAL_DMA1_CH3_USART4_RX (uint32_t) (DMA1_CHANNEL3_RMP | DMA1_CSELR_CH3_USART4_RX) /*!< Remap USART4 Rx on DMA1 channel 3 */ #define HAL_DMA1_CH3_USART5_RX (uint32_t) (DMA1_CHANNEL3_RMP | DMA1_CSELR_CH3_USART5_RX) /*!< Remap USART5 Rx on DMA1 channel 3 */ #define HAL_DMA1_CH3_USART6_RX (uint32_t) (DMA1_CHANNEL3_RMP | DMA1_CSELR_CH3_USART6_RX) /*!< Remap USART6 Rx on DMA1 channel 3 */ #if !defined(STM32F030xC) #define HAL_DMA1_CH3_USART7_RX (uint32_t) (DMA1_CHANNEL3_RMP | DMA1_CSELR_CH3_USART7_RX) /*!< Remap USART7 Rx on DMA1 channel 3 */ #define HAL_DMA1_CH3_USART8_RX (uint32_t) (DMA1_CHANNEL3_RMP | DMA1_CSELR_CH3_USART8_RX) /*!< Remap USART8 Rx on DMA1 channel 3 */ #endif /* !defined(STM32F030xC) */ /* DMA1 - Channel 4 */ #define HAL_DMA1_CH4_DEFAULT (uint32_t) (DMA1_CHANNEL4_RMP | DMA1_CSELR_DEFAULT) /*!< Default remap position for DMA1 */ #define HAL_DMA1_CH4_TIM7_UP (uint32_t) (DMA1_CHANNEL4_RMP | DMA1_CSELR_CH4_TIM7_UP) /*!< Remap TIM7 up on DMA1 channel 4 */ #if !defined(STM32F030xC) #define HAL_DMA1_CH4_DAC_CH2 (uint32_t) (DMA1_CHANNEL4_RMP | DMA1_CSELR_CH4_DAC_CH2) /*!< Remap DAC Channel 2 on DMA1 channel 4 */ #endif /* !defined(STM32F030xC) */ #define HAL_DMA1_CH4_I2C2_TX (uint32_t) (DMA1_CHANNEL4_RMP | DMA1_CSELR_CH4_I2C2_TX) /*!< Remap I2C2 Tx on DMA1 channel 4 */ #define HAL_DMA1_CH4_SPI2_RX (uint32_t) (DMA1_CHANNEL4_RMP | DMA1_CSELR_CH4_SPI2_RX) /*!< Remap SPI2 Rx on DMA1 channel 4 */ #if !defined(STM32F030xC) #define HAL_DMA1_CH4_TIM2_CH4 (uint32_t) (DMA1_CHANNEL4_RMP | DMA1_CSELR_CH4_TIM2_CH4) /*!< Remap TIM2 channel 4 on DMA1 channel 4 */ #endif /* !defined(STM32F030xC) */ #define HAL_DMA1_CH4_TIM3_CH1 (uint32_t) (DMA1_CHANNEL4_RMP | DMA1_CSELR_CH4_TIM3_CH1) /*!< Remap TIM3 channel 1 on DMA1 channel 4 */ #define HAL_DMA1_CH4_TIM3_TRIG (uint32_t) (DMA1_CHANNEL4_RMP | DMA1_CSELR_CH4_TIM3_TRIG) /*!< Remap TIM3 Trig on DMA1 channel 4 */ #define HAL_DMA1_CH4_TIM16_CH1 (uint32_t) (DMA1_CHANNEL4_RMP | DMA1_CSELR_CH4_TIM16_CH1) /*!< Remap TIM16 channel 1 on DMA1 channel 4 */ #define HAL_DMA1_CH4_TIM16_UP (uint32_t) (DMA1_CHANNEL4_RMP | DMA1_CSELR_CH4_TIM16_UP) /*!< Remap TIM16 up on DMA1 channel 4 */ #define HAL_DMA1_CH4_USART1_TX (uint32_t) (DMA1_CHANNEL4_RMP | DMA1_CSELR_CH4_USART1_TX) /*!< Remap USART1 Tx on DMA1 channel 4 */ #define HAL_DMA1_CH4_USART2_TX (uint32_t) (DMA1_CHANNEL4_RMP | DMA1_CSELR_CH4_USART2_TX) /*!< Remap USART2 Tx on DMA1 channel 4 */ #define HAL_DMA1_CH4_USART3_TX (uint32_t) (DMA1_CHANNEL4_RMP | DMA1_CSELR_CH4_USART3_TX) /*!< Remap USART3 Tx on DMA1 channel 4 */ #define HAL_DMA1_CH4_USART4_TX (uint32_t) (DMA1_CHANNEL4_RMP | DMA1_CSELR_CH4_USART4_TX) /*!< Remap USART4 Tx on DMA1 channel 4 */ #define HAL_DMA1_CH4_USART5_TX (uint32_t) (DMA1_CHANNEL4_RMP | DMA1_CSELR_CH4_USART5_TX) /*!< Remap USART5 Tx on DMA1 channel 4 */ #define HAL_DMA1_CH4_USART6_TX (uint32_t) (DMA1_CHANNEL4_RMP | DMA1_CSELR_CH4_USART6_TX) /*!< Remap USART6 Tx on DMA1 channel 4 */ #if !defined(STM32F030xC) #define HAL_DMA1_CH4_USART7_TX (uint32_t) (DMA1_CHANNEL4_RMP | DMA1_CSELR_CH4_USART7_TX) /*!< Remap USART7 Tx on DMA1 channel 4 */ #define HAL_DMA1_CH4_USART8_TX (uint32_t) (DMA1_CHANNEL4_RMP | DMA1_CSELR_CH4_USART8_TX) /*!< Remap USART8 Tx on DMA1 channel 4 */ #endif /* !defined(STM32F030xC) */ /* DMA1 - Channel 5 */ #define HAL_DMA1_CH5_DEFAULT (uint32_t) (DMA1_CHANNEL5_RMP | DMA1_CSELR_DEFAULT) /*!< Default remap position for DMA1 */ #define HAL_DMA1_CH5_I2C2_RX (uint32_t) (DMA1_CHANNEL5_RMP | DMA1_CSELR_CH5_I2C2_RX) /*!< Remap I2C2 Rx on DMA1 channel 5 */ #define HAL_DMA1_CH5_SPI2_TX (uint32_t) (DMA1_CHANNEL5_RMP | DMA1_CSELR_CH5_SPI2_TX) /*!< Remap SPI1 Tx on DMA1 channel 5 */ #define HAL_DMA1_CH5_TIM1_CH3 (uint32_t) (DMA1_CHANNEL5_RMP | DMA1_CSELR_CH5_TIM1_CH3) /*!< Remap TIM1 channel 3 on DMA1 channel 5 */ #define HAL_DMA1_CH5_USART1_RX (uint32_t) (DMA1_CHANNEL5_RMP | DMA1_CSELR_CH5_USART1_RX) /*!< Remap USART1 Rx on DMA1 channel 5 */ #define HAL_DMA1_CH5_USART2_RX (uint32_t) (DMA1_CHANNEL5_RMP | DMA1_CSELR_CH5_USART2_RX) /*!< Remap USART2 Rx on DMA1 channel 5 */ #define HAL_DMA1_CH5_USART3_RX (uint32_t) (DMA1_CHANNEL5_RMP | DMA1_CSELR_CH5_USART3_RX) /*!< Remap USART3 Rx on DMA1 channel 5 */ #define HAL_DMA1_CH5_USART4_RX (uint32_t) (DMA1_CHANNEL5_RMP | DMA1_CSELR_CH5_USART4_RX) /*!< Remap USART4 Rx on DMA1 channel 5 */ #define HAL_DMA1_CH5_USART5_RX (uint32_t) (DMA1_CHANNEL5_RMP | DMA1_CSELR_CH5_USART5_RX) /*!< Remap USART5 Rx on DMA1 channel 5 */ #define HAL_DMA1_CH5_USART6_RX (uint32_t) (DMA1_CHANNEL5_RMP | DMA1_CSELR_CH5_USART6_RX) /*!< Remap USART6 Rx on DMA1 channel 5 */ #if !defined(STM32F030xC) #define HAL_DMA1_CH5_USART7_RX (uint32_t) (DMA1_CHANNEL5_RMP | DMA1_CSELR_CH5_USART7_RX) /*!< Remap USART7 Rx on DMA1 channel 5 */ #define HAL_DMA1_CH5_USART8_RX (uint32_t) (DMA1_CHANNEL5_RMP | DMA1_CSELR_CH5_USART8_RX) /*!< Remap USART8 Rx on DMA1 channel 5 */ #endif /* !defined(STM32F030xC) */ #if !defined(STM32F030xC) /* DMA1 - Channel 6 */ #define HAL_DMA1_CH6_DEFAULT (uint32_t) (DMA1_CHANNEL6_RMP | DMA1_CSELR_DEFAULT) /*!< Default remap position for DMA1 */ #define HAL_DMA1_CH6_I2C1_TX (uint32_t) (DMA1_CHANNEL6_RMP | DMA1_CSELR_CH6_I2C1_TX) /*!< Remap I2C1 Tx on DMA1 channel 6 */ #define HAL_DMA1_CH6_SPI2_RX (uint32_t) (DMA1_CHANNEL6_RMP | DMA1_CSELR_CH6_SPI2_RX) /*!< Remap SPI2 Rx on DMA1 channel 6 */ #define HAL_DMA1_CH6_TIM1_CH1 (uint32_t) (DMA1_CHANNEL6_RMP | DMA1_CSELR_CH6_TIM1_CH1) /*!< Remap TIM1 channel 1 on DMA1 channel 6 */ #define HAL_DMA1_CH6_TIM1_CH2 (uint32_t) (DMA1_CHANNEL6_RMP | DMA1_CSELR_CH6_TIM1_CH2) /*!< Remap TIM1 channel 2 on DMA1 channel 6 */ #define HAL_DMA1_CH6_TIM1_CH3 (uint32_t) (DMA1_CHANNEL6_RMP | DMA1_CSELR_CH6_TIM1_CH3) /*!< Remap TIM1 channel 3 on DMA1 channel 6 */ #define HAL_DMA1_CH6_TIM3_CH1 (uint32_t) (DMA1_CHANNEL6_RMP | DMA1_CSELR_CH6_TIM3_CH1) /*!< Remap TIM3 channel 1 on DMA1 channel 6 */ #define HAL_DMA1_CH6_TIM3_TRIG (uint32_t) (DMA1_CHANNEL6_RMP | DMA1_CSELR_CH6_TIM3_TRIG) /*!< Remap TIM3 Trig on DMA1 channel 6 */ #define HAL_DMA1_CH6_TIM16_CH1 (uint32_t) (DMA1_CHANNEL6_RMP | DMA1_CSELR_CH6_TIM16_CH1) /*!< Remap TIM16 channel 1 on DMA1 channel 6 */ #define HAL_DMA1_CH6_TIM16_UP (uint32_t) (DMA1_CHANNEL6_RMP | DMA1_CSELR_CH6_TIM16_UP) /*!< Remap TIM16 up on DMA1 channel 6 */ #define HAL_DMA1_CH6_USART1_RX (uint32_t) (DMA1_CHANNEL6_RMP | DMA1_CSELR_CH6_USART1_RX) /*!< Remap USART1 Rx on DMA1 channel 6 */ #define HAL_DMA1_CH6_USART2_RX (uint32_t) (DMA1_CHANNEL6_RMP | DMA1_CSELR_CH6_USART2_RX) /*!< Remap USART2 Rx on DMA1 channel 6 */ #define HAL_DMA1_CH6_USART3_RX (uint32_t) (DMA1_CHANNEL6_RMP | DMA1_CSELR_CH6_USART3_RX) /*!< Remap USART3 Rx on DMA1 channel 6 */ #define HAL_DMA1_CH6_USART4_RX (uint32_t) (DMA1_CHANNEL6_RMP | DMA1_CSELR_CH6_USART4_RX) /*!< Remap USART4 Rx on DMA1 channel 6 */ #define HAL_DMA1_CH6_USART5_RX (uint32_t) (DMA1_CHANNEL6_RMP | DMA1_CSELR_CH6_USART5_RX) /*!< Remap USART5 Rx on DMA1 channel 6 */ #define HAL_DMA1_CH6_USART6_RX (uint32_t) (DMA1_CHANNEL6_RMP | DMA1_CSELR_CH6_USART6_RX) /*!< Remap USART6 Rx on DMA1 channel 6 */ #define HAL_DMA1_CH6_USART7_RX (uint32_t) (DMA1_CHANNEL6_RMP | DMA1_CSELR_CH6_USART7_RX) /*!< Remap USART7 Rx on DMA1 channel 6 */ #define HAL_DMA1_CH6_USART8_RX (uint32_t) (DMA1_CHANNEL6_RMP | DMA1_CSELR_CH6_USART8_RX) /*!< Remap USART8 Rx on DMA1 channel 6 */ /* DMA1 - Channel 7 */ #define HAL_DMA1_CH7_DEFAULT (uint32_t) (DMA1_CHANNEL7_RMP | DMA1_CSELR_DEFAULT) /*!< Default remap position for DMA1 */ #define HAL_DMA1_CH7_I2C1_RX (uint32_t) (DMA1_CHANNEL7_RMP | DMA1_CSELR_CH7_I2C1_RX) /*!< Remap I2C1 Rx on DMA1 channel 7 */ #define HAL_DMA1_CH7_SPI2_TX (uint32_t) (DMA1_CHANNEL7_RMP | DMA1_CSELR_CH7_SPI2_TX) /*!< Remap SPI2 Tx on DMA1 channel 7 */ #define HAL_DMA1_CH7_TIM2_CH2 (uint32_t) (DMA1_CHANNEL7_RMP | DMA1_CSELR_CH7_TIM2_CH2) /*!< Remap TIM2 channel 2 on DMA1 channel 7 */ #define HAL_DMA1_CH7_TIM2_CH4 (uint32_t) (DMA1_CHANNEL7_RMP | DMA1_CSELR_CH7_TIM2_CH4) /*!< Remap TIM2 channel 4 on DMA1 channel 7 */ #define HAL_DMA1_CH7_TIM17_CH1 (uint32_t) (DMA1_CHANNEL7_RMP | DMA1_CSELR_CH7_TIM17_CH1) /*!< Remap TIM17 channel 1 on DMA1 channel 7 */ #define HAL_DMA1_CH7_TIM17_UP (uint32_t) (DMA1_CHANNEL7_RMP | DMA1_CSELR_CH7_TIM17_UP) /*!< Remap TIM17 up on DMA1 channel 7 */ #define HAL_DMA1_CH7_USART1_TX (uint32_t) (DMA1_CHANNEL7_RMP | DMA1_CSELR_CH7_USART1_TX) /*!< Remap USART1 Tx on DMA1 channel 7 */ #define HAL_DMA1_CH7_USART2_TX (uint32_t) (DMA1_CHANNEL7_RMP | DMA1_CSELR_CH7_USART2_TX) /*!< Remap USART2 Tx on DMA1 channel 7 */ #define HAL_DMA1_CH7_USART3_TX (uint32_t) (DMA1_CHANNEL7_RMP | DMA1_CSELR_CH7_USART3_TX) /*!< Remap USART3 Tx on DMA1 channel 7 */ #define HAL_DMA1_CH7_USART4_TX (uint32_t) (DMA1_CHANNEL7_RMP | DMA1_CSELR_CH7_USART4_TX) /*!< Remap USART4 Tx on DMA1 channel 7 */ #define HAL_DMA1_CH7_USART5_TX (uint32_t) (DMA1_CHANNEL7_RMP | DMA1_CSELR_CH7_USART5_TX) /*!< Remap USART5 Tx on DMA1 channel 7 */ #define HAL_DMA1_CH7_USART6_TX (uint32_t) (DMA1_CHANNEL7_RMP | DMA1_CSELR_CH7_USART6_TX) /*!< Remap USART6 Tx on DMA1 channel 7 */ #define HAL_DMA1_CH7_USART7_TX (uint32_t) (DMA1_CHANNEL7_RMP | DMA1_CSELR_CH7_USART7_TX) /*!< Remap USART7 Tx on DMA1 channel 7 */ #define HAL_DMA1_CH7_USART8_TX (uint32_t) (DMA1_CHANNEL7_RMP | DMA1_CSELR_CH7_USART8_TX) /*!< Remap USART8 Tx on DMA1 channel 7 */ /****************** DMA2 remap bit field definition********************/ /* DMA2 - Channel 1 */ #define HAL_DMA2_CH1_DEFAULT (uint32_t) (DMA2_CHANNEL1_RMP | DMA2_CSELR_DEFAULT) /*!< Default remap position for DMA2 */ #define HAL_DMA2_CH1_I2C2_TX (uint32_t) (DMA2_CHANNEL1_RMP | DMA2_CSELR_CH1_I2C2_TX) /*!< Remap I2C2 TX on DMA2 channel 1 */ #define HAL_DMA2_CH1_USART1_TX (uint32_t) (DMA2_CHANNEL1_RMP | DMA2_CSELR_CH1_USART1_TX) /*!< Remap USART1 Tx on DMA2 channel 1 */ #define HAL_DMA2_CH1_USART2_TX (uint32_t) (DMA2_CHANNEL1_RMP | DMA2_CSELR_CH1_USART2_TX) /*!< Remap USART2 Tx on DMA2 channel 1 */ #define HAL_DMA2_CH1_USART3_TX (uint32_t) (DMA2_CHANNEL1_RMP | DMA2_CSELR_CH1_USART3_TX) /*!< Remap USART3 Tx on DMA2 channel 1 */ #define HAL_DMA2_CH1_USART4_TX (uint32_t) (DMA2_CHANNEL1_RMP | DMA2_CSELR_CH1_USART4_TX) /*!< Remap USART4 Tx on DMA2 channel 1 */ #define HAL_DMA2_CH1_USART5_TX (uint32_t) (DMA2_CHANNEL1_RMP | DMA2_CSELR_CH1_USART5_TX) /*!< Remap USART5 Tx on DMA2 channel 1 */ #define HAL_DMA2_CH1_USART6_TX (uint32_t) (DMA2_CHANNEL1_RMP | DMA2_CSELR_CH1_USART6_TX) /*!< Remap USART6 Tx on DMA2 channel 1 */ #define HAL_DMA2_CH1_USART7_TX (uint32_t) (DMA2_CHANNEL1_RMP | DMA2_CSELR_CH1_USART7_TX) /*!< Remap USART7 Tx on DMA2 channel 1 */ #define HAL_DMA2_CH1_USART8_TX (uint32_t) (DMA2_CHANNEL1_RMP | DMA2_CSELR_CH1_USART8_TX) /*!< Remap USART8 Tx on DMA2 channel 1 */ /* DMA2 - Channel 2 */ #define HAL_DMA2_CH2_DEFAULT (uint32_t) (DMA2_CHANNEL2_RMP | DMA2_CSELR_DEFAULT) /*!< Default remap position for DMA2 */ #define HAL_DMA2_CH2_I2C2_RX (uint32_t) (DMA2_CHANNEL2_RMP | DMA2_CSELR_CH2_I2C2_RX) /*!< Remap I2C2 Rx on DMA2 channel 2 */ #define HAL_DMA2_CH2_USART1_RX (uint32_t) (DMA2_CHANNEL2_RMP | DMA2_CSELR_CH2_USART1_RX) /*!< Remap USART1 Rx on DMA2 channel 2 */ #define HAL_DMA2_CH2_USART2_RX (uint32_t) (DMA2_CHANNEL2_RMP | DMA2_CSELR_CH2_USART2_RX) /*!< Remap USART2 Rx on DMA2 channel 2 */ #define HAL_DMA2_CH2_USART3_RX (uint32_t) (DMA2_CHANNEL2_RMP | DMA2_CSELR_CH2_USART3_RX) /*!< Remap USART3 Rx on DMA2 channel 2 */ #define HAL_DMA2_CH2_USART4_RX (uint32_t) (DMA2_CHANNEL2_RMP | DMA2_CSELR_CH2_USART4_RX) /*!< Remap USART4 Rx on DMA2 channel 2 */ #define HAL_DMA2_CH2_USART5_RX (uint32_t) (DMA2_CHANNEL2_RMP | DMA2_CSELR_CH2_USART5_RX) /*!< Remap USART5 Rx on DMA2 channel 2 */ #define HAL_DMA2_CH2_USART6_RX (uint32_t) (DMA2_CHANNEL2_RMP | DMA2_CSELR_CH2_USART6_RX) /*!< Remap USART6 Rx on DMA2 channel 2 */ #define HAL_DMA2_CH2_USART7_RX (uint32_t) (DMA2_CHANNEL2_RMP | DMA2_CSELR_CH2_USART7_RX) /*!< Remap USART7 Rx on DMA2 channel 2 */ #define HAL_DMA2_CH2_USART8_RX (uint32_t) (DMA2_CHANNEL2_RMP | DMA2_CSELR_CH2_USART8_RX) /*!< Remap USART8 Rx on DMA2 channel 2 */ /* DMA2 - Channel 3 */ #define HAL_DMA2_CH3_DEFAULT (uint32_t) (DMA2_CHANNEL3_RMP | DMA2_CSELR_DEFAULT) /*!< Default remap position for DMA2 */ #define HAL_DMA2_CH3_TIM6_UP (uint32_t) (DMA2_CHANNEL3_RMP | DMA2_CSELR_CH3_TIM6_UP) /*!< Remap TIM6 up on DMA2 channel 3 */ #define HAL_DMA2_CH3_DAC_CH1 (uint32_t) (DMA2_CHANNEL3_RMP | DMA2_CSELR_CH3_DAC_CH1) /*!< Remap DAC channel 1 on DMA2 channel 3 */ #define HAL_DMA2_CH3_SPI1_RX (uint32_t) (DMA2_CHANNEL3_RMP | DMA2_CSELR_CH3_SPI1_RX) /*!< Remap SPI1 Rx on DMA2 channel 3 */ #define HAL_DMA2_CH3_USART1_RX (uint32_t) (DMA2_CHANNEL3_RMP | DMA2_CSELR_CH3_USART1_RX) /*!< Remap USART1 Rx on DMA2 channel 3 */ #define HAL_DMA2_CH3_USART2_RX (uint32_t) (DMA2_CHANNEL3_RMP | DMA2_CSELR_CH3_USART2_RX) /*!< Remap USART2 Rx on DMA2 channel 3 */ #define HAL_DMA2_CH3_USART3_RX (uint32_t) (DMA2_CHANNEL3_RMP | DMA2_CSELR_CH3_USART3_RX) /*!< Remap USART3 Rx on DMA2 channel 3 */ #define HAL_DMA2_CH3_USART4_RX (uint32_t) (DMA2_CHANNEL3_RMP | DMA2_CSELR_CH3_USART4_RX) /*!< Remap USART4 Rx on DMA2 channel 3 */ #define HAL_DMA2_CH3_USART5_RX (uint32_t) (DMA2_CHANNEL3_RMP | DMA2_CSELR_CH3_USART5_RX) /*!< Remap USART5 Rx on DMA2 channel 3 */ #define HAL_DMA2_CH3_USART6_RX (uint32_t) (DMA2_CHANNEL3_RMP | DMA2_CSELR_CH3_USART6_RX) /*!< Remap USART6 Rx on DMA2 channel 3 */ #define HAL_DMA2_CH3_USART7_RX (uint32_t) (DMA2_CHANNEL3_RMP | DMA2_CSELR_CH3_USART7_RX) /*!< Remap USART7 Rx on DMA2 channel 3 */ #define HAL_DMA2_CH3_USART8_RX (uint32_t) (DMA2_CHANNEL3_RMP | DMA2_CSELR_CH3_USART8_RX) /*!< Remap USART8 Rx on DMA2 channel 3 */ /* DMA2 - Channel 4 */ #define HAL_DMA2_CH4_DEFAULT (uint32_t) (DMA2_CHANNEL4_RMP | DMA2_CSELR_DEFAULT) /*!< Default remap position for DMA2 */ #define HAL_DMA2_CH4_TIM7_UP (uint32_t) (DMA2_CHANNEL4_RMP | DMA2_CSELR_CH4_TIM7_UP) /*!< Remap TIM7 up on DMA2 channel 4 */ #define HAL_DMA2_CH4_DAC_CH2 (uint32_t) (DMA2_CHANNEL4_RMP | DMA2_CSELR_CH4_DAC_CH2) /*!< Remap DAC channel 2 on DMA2 channel 4 */ #define HAL_DMA2_CH4_SPI1_TX (uint32_t) (DMA2_CHANNEL4_RMP | DMA2_CSELR_CH4_SPI1_TX) /*!< Remap SPI1 Tx on DMA2 channel 4 */ #define HAL_DMA2_CH4_USART1_TX (uint32_t) (DMA2_CHANNEL4_RMP | DMA2_CSELR_CH4_USART1_TX) /*!< Remap USART1 Tx on DMA2 channel 4 */ #define HAL_DMA2_CH4_USART2_TX (uint32_t) (DMA2_CHANNEL4_RMP | DMA2_CSELR_CH4_USART2_TX) /*!< Remap USART2 Tx on DMA2 channel 4 */ #define HAL_DMA2_CH4_USART3_TX (uint32_t) (DMA2_CHANNEL4_RMP | DMA2_CSELR_CH4_USART3_TX) /*!< Remap USART3 Tx on DMA2 channel 4 */ #define HAL_DMA2_CH4_USART4_TX (uint32_t) (DMA2_CHANNEL4_RMP | DMA2_CSELR_CH4_USART4_TX) /*!< Remap USART4 Tx on DMA2 channel 4 */ #define HAL_DMA2_CH4_USART5_TX (uint32_t) (DMA2_CHANNEL4_RMP | DMA2_CSELR_CH4_USART5_TX) /*!< Remap USART5 Tx on DMA2 channel 4 */ #define HAL_DMA2_CH4_USART6_TX (uint32_t) (DMA2_CHANNEL4_RMP | DMA2_CSELR_CH4_USART6_TX) /*!< Remap USART6 Tx on DMA2 channel 4 */ #define HAL_DMA2_CH4_USART7_TX (uint32_t) (DMA2_CHANNEL4_RMP | DMA2_CSELR_CH4_USART7_TX) /*!< Remap USART7 Tx on DMA2 channel 4 */ #define HAL_DMA2_CH4_USART8_TX (uint32_t) (DMA2_CHANNEL4_RMP | DMA2_CSELR_CH4_USART8_TX) /*!< Remap USART8 Tx on DMA2 channel 4 */ /* DMA2 - Channel 5 */ #define HAL_DMA2_CH5_DEFAULT (uint32_t) (DMA2_CHANNEL5_RMP | DMA2_CSELR_DEFAULT) /*!< Default remap position for DMA2 */ #define HAL_DMA2_CH5_ADC (uint32_t) (DMA2_CHANNEL5_RMP | DMA2_CSELR_CH5_ADC) /*!< Remap ADC on DMA2 channel 5 */ #define HAL_DMA2_CH5_USART1_TX (uint32_t) (DMA2_CHANNEL5_RMP | DMA2_CSELR_CH5_USART1_TX) /*!< Remap USART1 Tx on DMA2 channel 5 */ #define HAL_DMA2_CH5_USART2_TX (uint32_t) (DMA2_CHANNEL5_RMP | DMA2_CSELR_CH5_USART2_TX) /*!< Remap USART2 Tx on DMA2 channel 5 */ #define HAL_DMA2_CH5_USART3_TX (uint32_t) (DMA2_CHANNEL5_RMP | DMA2_CSELR_CH5_USART3_TX) /*!< Remap USART3 Tx on DMA2 channel 5 */ #define HAL_DMA2_CH5_USART4_TX (uint32_t) (DMA2_CHANNEL5_RMP | DMA2_CSELR_CH5_USART4_TX) /*!< Remap USART4 Tx on DMA2 channel 5 */ #define HAL_DMA2_CH5_USART5_TX (uint32_t) (DMA2_CHANNEL5_RMP | DMA2_CSELR_CH5_USART5_TX) /*!< Remap USART5 Tx on DMA2 channel 5 */ #define HAL_DMA2_CH5_USART6_TX (uint32_t) (DMA2_CHANNEL5_RMP | DMA2_CSELR_CH5_USART6_TX) /*!< Remap USART6 Tx on DMA2 channel 5 */ #define HAL_DMA2_CH5_USART7_TX (uint32_t) (DMA2_CHANNEL5_RMP | DMA2_CSELR_CH5_USART7_TX) /*!< Remap USART7 Tx on DMA2 channel 5 */ #define HAL_DMA2_CH5_USART8_TX (uint32_t) (DMA2_CHANNEL5_RMP | DMA2_CSELR_CH5_USART8_TX) /*!< Remap USART8 Tx on DMA2 channel 5 */ #endif /* !defined(STM32F030xC) */ #if defined(STM32F091xC) || defined(STM32F098xx) #define IS_HAL_DMA1_REMAP(REQUEST) (((REQUEST) == HAL_DMA1_CH1_DEFAULT) ||\ ((REQUEST) == HAL_DMA1_CH1_ADC) ||\ ((REQUEST) == HAL_DMA1_CH1_TIM17_CH1) ||\ ((REQUEST) == HAL_DMA1_CH1_TIM17_UP) ||\ ((REQUEST) == HAL_DMA1_CH1_USART1_RX) ||\ ((REQUEST) == HAL_DMA1_CH1_USART2_RX) ||\ ((REQUEST) == HAL_DMA1_CH1_USART3_RX) ||\ ((REQUEST) == HAL_DMA1_CH1_USART4_RX) ||\ ((REQUEST) == HAL_DMA1_CH1_USART5_RX) ||\ ((REQUEST) == HAL_DMA1_CH1_USART6_RX) ||\ ((REQUEST) == HAL_DMA1_CH1_USART7_RX) ||\ ((REQUEST) == HAL_DMA1_CH1_USART8_RX) ||\ ((REQUEST) == HAL_DMA1_CH2_DEFAULT) ||\ ((REQUEST) == HAL_DMA1_CH2_ADC) ||\ ((REQUEST) == HAL_DMA1_CH2_I2C1_TX) ||\ ((REQUEST) == HAL_DMA1_CH2_SPI1_RX) ||\ ((REQUEST) == HAL_DMA1_CH2_TIM1_CH1) ||\ ((REQUEST) == HAL_DMA1_CH2_I2C1_TX) ||\ ((REQUEST) == HAL_DMA1_CH2_TIM17_CH1) ||\ ((REQUEST) == HAL_DMA1_CH2_TIM17_UP) ||\ ((REQUEST) == HAL_DMA1_CH2_USART1_TX) ||\ ((REQUEST) == HAL_DMA1_CH2_USART2_TX) ||\ ((REQUEST) == HAL_DMA1_CH2_USART3_TX) ||\ ((REQUEST) == HAL_DMA1_CH2_USART4_TX) ||\ ((REQUEST) == HAL_DMA1_CH2_USART5_TX) ||\ ((REQUEST) == HAL_DMA1_CH2_USART6_TX) ||\ ((REQUEST) == HAL_DMA1_CH2_USART7_TX) ||\ ((REQUEST) == HAL_DMA1_CH2_USART8_TX) ||\ ((REQUEST) == HAL_DMA1_CH3_DEFAULT) ||\ ((REQUEST) == HAL_DMA1_CH3_TIM6_UP) ||\ ((REQUEST) == HAL_DMA1_CH3_DAC_CH1) ||\ ((REQUEST) == HAL_DMA1_CH3_I2C1_RX) ||\ ((REQUEST) == HAL_DMA1_CH3_SPI1_TX) ||\ ((REQUEST) == HAL_DMA1_CH3_TIM1_CH2) ||\ ((REQUEST) == HAL_DMA1_CH3_TIM2_CH2) ||\ ((REQUEST) == HAL_DMA1_CH3_TIM16_CH1) ||\ ((REQUEST) == HAL_DMA1_CH3_TIM16_UP) ||\ ((REQUEST) == HAL_DMA1_CH3_USART1_RX) ||\ ((REQUEST) == HAL_DMA1_CH3_USART2_RX) ||\ ((REQUEST) == HAL_DMA1_CH3_USART3_RX) ||\ ((REQUEST) == HAL_DMA1_CH3_USART4_RX) ||\ ((REQUEST) == HAL_DMA1_CH3_USART5_RX) ||\ ((REQUEST) == HAL_DMA1_CH3_USART6_RX) ||\ ((REQUEST) == HAL_DMA1_CH3_USART7_RX) ||\ ((REQUEST) == HAL_DMA1_CH3_USART8_RX) ||\ ((REQUEST) == HAL_DMA1_CH4_DEFAULT) ||\ ((REQUEST) == HAL_DMA1_CH4_TIM7_UP) ||\ ((REQUEST) == HAL_DMA1_CH4_DAC_CH2) ||\ ((REQUEST) == HAL_DMA1_CH4_I2C2_TX) ||\ ((REQUEST) == HAL_DMA1_CH4_SPI2_RX) ||\ ((REQUEST) == HAL_DMA1_CH4_TIM2_CH4) ||\ ((REQUEST) == HAL_DMA1_CH4_TIM3_CH1) ||\ ((REQUEST) == HAL_DMA1_CH4_TIM3_TRIG) ||\ ((REQUEST) == HAL_DMA1_CH4_TIM16_CH1) ||\ ((REQUEST) == HAL_DMA1_CH4_TIM16_UP) ||\ ((REQUEST) == HAL_DMA1_CH4_USART1_TX) ||\ ((REQUEST) == HAL_DMA1_CH4_USART2_TX) ||\ ((REQUEST) == HAL_DMA1_CH4_USART3_TX) ||\ ((REQUEST) == HAL_DMA1_CH4_USART4_TX) ||\ ((REQUEST) == HAL_DMA1_CH4_USART5_TX) ||\ ((REQUEST) == HAL_DMA1_CH4_USART6_TX) ||\ ((REQUEST) == HAL_DMA1_CH4_USART7_TX) ||\ ((REQUEST) == HAL_DMA1_CH4_USART8_TX) ||\ ((REQUEST) == HAL_DMA1_CH5_DEFAULT) ||\ ((REQUEST) == HAL_DMA1_CH5_I2C2_RX) ||\ ((REQUEST) == HAL_DMA1_CH5_SPI2_TX) ||\ ((REQUEST) == HAL_DMA1_CH5_TIM1_CH3) ||\ ((REQUEST) == HAL_DMA1_CH5_USART1_RX) ||\ ((REQUEST) == HAL_DMA1_CH5_USART2_RX) ||\ ((REQUEST) == HAL_DMA1_CH5_USART3_RX) ||\ ((REQUEST) == HAL_DMA1_CH5_USART4_RX) ||\ ((REQUEST) == HAL_DMA1_CH5_USART5_RX) ||\ ((REQUEST) == HAL_DMA1_CH5_USART6_RX) ||\ ((REQUEST) == HAL_DMA1_CH5_USART7_RX) ||\ ((REQUEST) == HAL_DMA1_CH5_USART8_RX) ||\ ((REQUEST) == HAL_DMA1_CH6_DEFAULT) ||\ ((REQUEST) == HAL_DMA1_CH6_I2C1_TX) ||\ ((REQUEST) == HAL_DMA1_CH6_SPI2_RX) ||\ ((REQUEST) == HAL_DMA1_CH6_TIM1_CH1) ||\ ((REQUEST) == HAL_DMA1_CH6_TIM1_CH2) ||\ ((REQUEST) == HAL_DMA1_CH6_TIM1_CH3) ||\ ((REQUEST) == HAL_DMA1_CH6_TIM3_CH1) ||\ ((REQUEST) == HAL_DMA1_CH6_TIM3_TRIG) ||\ ((REQUEST) == HAL_DMA1_CH6_TIM16_CH1) ||\ ((REQUEST) == HAL_DMA1_CH6_TIM16_UP) ||\ ((REQUEST) == HAL_DMA1_CH6_USART1_RX) ||\ ((REQUEST) == HAL_DMA1_CH6_USART2_RX) ||\ ((REQUEST) == HAL_DMA1_CH6_USART3_RX) ||\ ((REQUEST) == HAL_DMA1_CH6_USART4_RX) ||\ ((REQUEST) == HAL_DMA1_CH6_USART5_RX) ||\ ((REQUEST) == HAL_DMA1_CH6_USART6_RX) ||\ ((REQUEST) == HAL_DMA1_CH6_USART7_RX) ||\ ((REQUEST) == HAL_DMA1_CH6_USART8_RX) ||\ ((REQUEST) == HAL_DMA1_CH7_DEFAULT) ||\ ((REQUEST) == HAL_DMA1_CH7_I2C1_RX) ||\ ((REQUEST) == HAL_DMA1_CH7_SPI2_TX) ||\ ((REQUEST) == HAL_DMA1_CH7_TIM2_CH2) ||\ ((REQUEST) == HAL_DMA1_CH7_TIM2_CH4) ||\ ((REQUEST) == HAL_DMA1_CH7_TIM17_CH1) ||\ ((REQUEST) == HAL_DMA1_CH7_TIM17_UP) ||\ ((REQUEST) == HAL_DMA1_CH7_USART1_TX) ||\ ((REQUEST) == HAL_DMA1_CH7_USART2_TX) ||\ ((REQUEST) == HAL_DMA1_CH7_USART3_TX) ||\ ((REQUEST) == HAL_DMA1_CH7_USART4_TX) ||\ ((REQUEST) == HAL_DMA1_CH7_USART5_TX) ||\ ((REQUEST) == HAL_DMA1_CH7_USART6_TX) ||\ ((REQUEST) == HAL_DMA1_CH7_USART7_TX) ||\ ((REQUEST) == HAL_DMA1_CH7_USART8_TX)) #define IS_HAL_DMA2_REMAP(REQUEST) (((REQUEST) == HAL_DMA2_CH1_DEFAULT) ||\ ((REQUEST) == HAL_DMA2_CH1_I2C2_TX) ||\ ((REQUEST) == HAL_DMA2_CH1_USART1_TX) ||\ ((REQUEST) == HAL_DMA2_CH1_USART2_TX) ||\ ((REQUEST) == HAL_DMA2_CH1_USART3_TX) ||\ ((REQUEST) == HAL_DMA2_CH1_USART4_TX) ||\ ((REQUEST) == HAL_DMA2_CH1_USART5_TX) ||\ ((REQUEST) == HAL_DMA2_CH1_USART6_TX) ||\ ((REQUEST) == HAL_DMA2_CH1_USART7_TX) ||\ ((REQUEST) == HAL_DMA2_CH1_USART8_TX) ||\ ((REQUEST) == HAL_DMA2_CH2_DEFAULT) ||\ ((REQUEST) == HAL_DMA2_CH2_I2C2_RX) ||\ ((REQUEST) == HAL_DMA2_CH2_USART1_RX) ||\ ((REQUEST) == HAL_DMA2_CH2_USART2_RX) ||\ ((REQUEST) == HAL_DMA2_CH2_USART3_RX) ||\ ((REQUEST) == HAL_DMA2_CH2_USART4_RX) ||\ ((REQUEST) == HAL_DMA2_CH2_USART5_RX) ||\ ((REQUEST) == HAL_DMA2_CH2_USART6_RX) ||\ ((REQUEST) == HAL_DMA2_CH2_USART7_RX) ||\ ((REQUEST) == HAL_DMA2_CH2_USART8_RX) ||\ ((REQUEST) == HAL_DMA2_CH3_DEFAULT) ||\ ((REQUEST) == HAL_DMA2_CH3_TIM6_UP) ||\ ((REQUEST) == HAL_DMA2_CH3_DAC_CH1) ||\ ((REQUEST) == HAL_DMA2_CH3_SPI1_RX) ||\ ((REQUEST) == HAL_DMA2_CH3_USART1_RX) ||\ ((REQUEST) == HAL_DMA2_CH3_USART2_RX) ||\ ((REQUEST) == HAL_DMA2_CH3_USART3_RX) ||\ ((REQUEST) == HAL_DMA2_CH3_USART4_RX) ||\ ((REQUEST) == HAL_DMA2_CH3_USART5_RX) ||\ ((REQUEST) == HAL_DMA2_CH3_USART6_RX) ||\ ((REQUEST) == HAL_DMA2_CH3_USART7_RX) ||\ ((REQUEST) == HAL_DMA2_CH3_USART8_RX) ||\ ((REQUEST) == HAL_DMA2_CH4_DEFAULT) ||\ ((REQUEST) == HAL_DMA2_CH4_TIM7_UP) ||\ ((REQUEST) == HAL_DMA2_CH4_DAC_CH2) ||\ ((REQUEST) == HAL_DMA2_CH4_SPI1_TX) ||\ ((REQUEST) == HAL_DMA2_CH4_USART1_TX) ||\ ((REQUEST) == HAL_DMA2_CH4_USART2_TX) ||\ ((REQUEST) == HAL_DMA2_CH4_USART3_TX) ||\ ((REQUEST) == HAL_DMA2_CH4_USART4_TX) ||\ ((REQUEST) == HAL_DMA2_CH4_USART5_TX) ||\ ((REQUEST) == HAL_DMA2_CH4_USART6_TX) ||\ ((REQUEST) == HAL_DMA2_CH4_USART7_TX) ||\ ((REQUEST) == HAL_DMA2_CH4_USART8_TX) ||\ ((REQUEST) == HAL_DMA2_CH5_DEFAULT) ||\ ((REQUEST) == HAL_DMA2_CH5_ADC) ||\ ((REQUEST) == HAL_DMA2_CH5_USART1_TX) ||\ ((REQUEST) == HAL_DMA2_CH5_USART2_TX) ||\ ((REQUEST) == HAL_DMA2_CH5_USART3_TX) ||\ ((REQUEST) == HAL_DMA2_CH5_USART4_TX) ||\ ((REQUEST) == HAL_DMA2_CH5_USART5_TX) ||\ ((REQUEST) == HAL_DMA2_CH5_USART6_TX) ||\ ((REQUEST) == HAL_DMA2_CH5_USART7_TX) ||\ ((REQUEST) == HAL_DMA2_CH5_USART8_TX )) #endif /* STM32F091xC || STM32F098xx */ #if defined(STM32F030xC) #define IS_HAL_DMA1_REMAP(REQUEST) (((REQUEST) == HAL_DMA1_CH1_DEFAULT) ||\ ((REQUEST) == HAL_DMA1_CH1_ADC) ||\ ((REQUEST) == HAL_DMA1_CH1_TIM17_CH1) ||\ ((REQUEST) == HAL_DMA1_CH1_TIM17_UP) ||\ ((REQUEST) == HAL_DMA1_CH1_USART1_RX) ||\ ((REQUEST) == HAL_DMA1_CH1_USART2_RX) ||\ ((REQUEST) == HAL_DMA1_CH1_USART3_RX) ||\ ((REQUEST) == HAL_DMA1_CH1_USART4_RX) ||\ ((REQUEST) == HAL_DMA1_CH1_USART5_RX) ||\ ((REQUEST) == HAL_DMA1_CH1_USART6_RX) ||\ ((REQUEST) == HAL_DMA1_CH2_DEFAULT) ||\ ((REQUEST) == HAL_DMA1_CH2_ADC) ||\ ((REQUEST) == HAL_DMA1_CH2_I2C1_TX) ||\ ((REQUEST) == HAL_DMA1_CH2_SPI1_RX) ||\ ((REQUEST) == HAL_DMA1_CH2_TIM1_CH1) ||\ ((REQUEST) == HAL_DMA1_CH2_I2C1_TX) ||\ ((REQUEST) == HAL_DMA1_CH2_TIM17_CH1) ||\ ((REQUEST) == HAL_DMA1_CH2_TIM17_UP) ||\ ((REQUEST) == HAL_DMA1_CH2_USART1_TX) ||\ ((REQUEST) == HAL_DMA1_CH2_USART2_TX) ||\ ((REQUEST) == HAL_DMA1_CH2_USART3_TX) ||\ ((REQUEST) == HAL_DMA1_CH2_USART4_TX) ||\ ((REQUEST) == HAL_DMA1_CH2_USART5_TX) ||\ ((REQUEST) == HAL_DMA1_CH2_USART6_TX) ||\ ((REQUEST) == HAL_DMA1_CH3_DEFAULT) ||\ ((REQUEST) == HAL_DMA1_CH3_TIM6_UP) ||\ ((REQUEST) == HAL_DMA1_CH3_I2C1_RX) ||\ ((REQUEST) == HAL_DMA1_CH3_SPI1_TX) ||\ ((REQUEST) == HAL_DMA1_CH3_TIM1_CH2) ||\ ((REQUEST) == HAL_DMA1_CH3_TIM16_CH1) ||\ ((REQUEST) == HAL_DMA1_CH3_TIM16_UP) ||\ ((REQUEST) == HAL_DMA1_CH3_USART1_RX) ||\ ((REQUEST) == HAL_DMA1_CH3_USART2_RX) ||\ ((REQUEST) == HAL_DMA1_CH3_USART3_RX) ||\ ((REQUEST) == HAL_DMA1_CH3_USART4_RX) ||\ ((REQUEST) == HAL_DMA1_CH3_USART5_RX) ||\ ((REQUEST) == HAL_DMA1_CH3_USART6_RX) ||\ ((REQUEST) == HAL_DMA1_CH4_DEFAULT) ||\ ((REQUEST) == HAL_DMA1_CH4_TIM7_UP) ||\ ((REQUEST) == HAL_DMA1_CH4_I2C2_TX) ||\ ((REQUEST) == HAL_DMA1_CH4_SPI2_RX) ||\ ((REQUEST) == HAL_DMA1_CH4_TIM3_CH1) ||\ ((REQUEST) == HAL_DMA1_CH4_TIM3_TRIG) ||\ ((REQUEST) == HAL_DMA1_CH4_TIM16_CH1) ||\ ((REQUEST) == HAL_DMA1_CH4_TIM16_UP) ||\ ((REQUEST) == HAL_DMA1_CH4_USART1_TX) ||\ ((REQUEST) == HAL_DMA1_CH4_USART2_TX) ||\ ((REQUEST) == HAL_DMA1_CH4_USART3_TX) ||\ ((REQUEST) == HAL_DMA1_CH4_USART4_TX) ||\ ((REQUEST) == HAL_DMA1_CH4_USART5_TX) ||\ ((REQUEST) == HAL_DMA1_CH4_USART6_TX) ||\ ((REQUEST) == HAL_DMA1_CH5_DEFAULT) ||\ ((REQUEST) == HAL_DMA1_CH5_I2C2_RX) ||\ ((REQUEST) == HAL_DMA1_CH5_SPI2_TX) ||\ ((REQUEST) == HAL_DMA1_CH5_TIM1_CH3) ||\ ((REQUEST) == HAL_DMA1_CH5_USART1_RX) ||\ ((REQUEST) == HAL_DMA1_CH5_USART2_RX) ||\ ((REQUEST) == HAL_DMA1_CH5_USART3_RX) ||\ ((REQUEST) == HAL_DMA1_CH5_USART4_RX) ||\ ((REQUEST) == HAL_DMA1_CH5_USART5_RX) ||\ ((REQUEST) == HAL_DMA1_CH5_USART6_RX)) #endif /* STM32F030xC */ /** * @} */ #endif /* STM32F091xC || STM32F098xx || STM32F030xC */ /* Exported macros -----------------------------------------------------------*/ /** @defgroup DMAEx_Exported_Macros DMAEx Exported Macros * @{ */ /* Interrupt & Flag management */ #if defined(STM32F071xB) || defined(STM32F072xB) || defined(STM32F078xx) /** * @brief Returns the current DMA Channel transfer complete flag. * @param __HANDLE__: DMA handle * @retval The specified transfer complete flag index. */ #define __HAL_DMA_GET_TC_FLAG_INDEX(__HANDLE__) \ (((uint32_t)((__HANDLE__)->Instance) == ((uint32_t)DMA1_Channel1))? DMA_FLAG_TC1 :\ ((uint32_t)((__HANDLE__)->Instance) == ((uint32_t)DMA1_Channel2))? DMA_FLAG_TC2 :\ ((uint32_t)((__HANDLE__)->Instance) == ((uint32_t)DMA1_Channel3))? DMA_FLAG_TC3 :\ ((uint32_t)((__HANDLE__)->Instance) == ((uint32_t)DMA1_Channel4))? DMA_FLAG_TC4 :\ ((uint32_t)((__HANDLE__)->Instance) == ((uint32_t)DMA1_Channel5))? DMA_FLAG_TC5 :\ ((uint32_t)((__HANDLE__)->Instance) == ((uint32_t)DMA1_Channel6))? DMA_FLAG_TC6 :\ DMA_FLAG_TC7) /** * @brief Returns the current DMA Channel half transfer complete flag. * @param __HANDLE__: DMA handle * @retval The specified half transfer complete flag index. */ #define __HAL_DMA_GET_HT_FLAG_INDEX(__HANDLE__)\ (((uint32_t)((__HANDLE__)->Instance) == ((uint32_t)DMA1_Channel1))? DMA_FLAG_HT1 :\ ((uint32_t)((__HANDLE__)->Instance) == ((uint32_t)DMA1_Channel2))? DMA_FLAG_HT2 :\ ((uint32_t)((__HANDLE__)->Instance) == ((uint32_t)DMA1_Channel3))? DMA_FLAG_HT3 :\ ((uint32_t)((__HANDLE__)->Instance) == ((uint32_t)DMA1_Channel4))? DMA_FLAG_HT4 :\ ((uint32_t)((__HANDLE__)->Instance) == ((uint32_t)DMA1_Channel5))? DMA_FLAG_HT5 :\ ((uint32_t)((__HANDLE__)->Instance) == ((uint32_t)DMA1_Channel6))? DMA_FLAG_HT6 :\ DMA_FLAG_HT7) /** * @brief Returns the current DMA Channel transfer error flag. * @param __HANDLE__: DMA handle * @retval The specified transfer error flag index. */ #define __HAL_DMA_GET_TE_FLAG_INDEX(__HANDLE__)\ (((uint32_t)((__HANDLE__)->Instance) == ((uint32_t)DMA1_Channel1))? DMA_FLAG_TE1 :\ ((uint32_t)((__HANDLE__)->Instance) == ((uint32_t)DMA1_Channel2))? DMA_FLAG_TE2 :\ ((uint32_t)((__HANDLE__)->Instance) == ((uint32_t)DMA1_Channel3))? DMA_FLAG_TE3 :\ ((uint32_t)((__HANDLE__)->Instance) == ((uint32_t)DMA1_Channel4))? DMA_FLAG_TE4 :\ ((uint32_t)((__HANDLE__)->Instance) == ((uint32_t)DMA1_Channel5))? DMA_FLAG_TE5 :\ ((uint32_t)((__HANDLE__)->Instance) == ((uint32_t)DMA1_Channel6))? DMA_FLAG_TE6 :\ DMA_FLAG_TE7) /** * @brief Get the DMA Channel pending flags. * @param __HANDLE__: DMA handle * @param __FLAG__: Get the specified flag. * This parameter can be any combination of the following values: * @arg DMA_FLAG_TCx: Transfer complete flag * @arg DMA_FLAG_HTx: Half transfer complete flag * @arg DMA_FLAG_TEx: Transfer error flag * Where x can be 1_7 to select the DMA Channel flag. * @retval The state of FLAG (SET or RESET). */ #define __HAL_DMA_GET_FLAG(__HANDLE__, __FLAG__) (DMA1->ISR & (__FLAG__)) /** * @brief Clears the DMA Channel pending flags. * @param __HANDLE__: DMA handle * @param __FLAG__: specifies the flag to clear. * This parameter can be any combination of the following values: * @arg DMA_FLAG_TCx: Transfer complete flag * @arg DMA_FLAG_HTx: Half transfer complete flag * @arg DMA_FLAG_TEx: Transfer error flag * Where x can be 1_7 to select the DMA Channel flag. * @retval None */ #define __HAL_DMA_CLEAR_FLAG(__HANDLE__, __FLAG__) (DMA1->IFCR = (__FLAG__)) #elif defined(STM32F091xC) || defined(STM32F098xx) /** * @brief Returns the current DMA Channel transfer complete flag. * @param __HANDLE__: DMA handle * @retval The specified transfer complete flag index. */ #define __HAL_DMA_GET_TC_FLAG_INDEX(__HANDLE__) \ (((uint32_t)((__HANDLE__)->Instance) == ((uint32_t)DMA1_Channel1))? DMA_FLAG_TC1 :\ ((uint32_t)((__HANDLE__)->Instance) == ((uint32_t)DMA1_Channel2))? DMA_FLAG_TC2 :\ ((uint32_t)((__HANDLE__)->Instance) == ((uint32_t)DMA1_Channel3))? DMA_FLAG_TC3 :\ ((uint32_t)((__HANDLE__)->Instance) == ((uint32_t)DMA1_Channel4))? DMA_FLAG_TC4 :\ ((uint32_t)((__HANDLE__)->Instance) == ((uint32_t)DMA1_Channel5))? DMA_FLAG_TC5 :\ ((uint32_t)((__HANDLE__)->Instance) == ((uint32_t)DMA1_Channel6))? DMA_FLAG_TC6 :\ ((uint32_t)((__HANDLE__)->Instance) == ((uint32_t)DMA1_Channel7))? DMA_FLAG_TC7 :\ ((uint32_t)((__HANDLE__)->Instance) == ((uint32_t)DMA2_Channel1))? DMA_FLAG_TC1 :\ ((uint32_t)((__HANDLE__)->Instance) == ((uint32_t)DMA2_Channel2))? DMA_FLAG_TC2 :\ ((uint32_t)((__HANDLE__)->Instance) == ((uint32_t)DMA2_Channel3))? DMA_FLAG_TC3 :\ ((uint32_t)((__HANDLE__)->Instance) == ((uint32_t)DMA2_Channel4))? DMA_FLAG_TC4 :\ DMA_FLAG_TC5) /** * @brief Returns the current DMA Channel half transfer complete flag. * @param __HANDLE__: DMA handle * @retval The specified half transfer complete flag index. */ #define __HAL_DMA_GET_HT_FLAG_INDEX(__HANDLE__)\ (((uint32_t)((__HANDLE__)->Instance) == ((uint32_t)DMA1_Channel1))? DMA_FLAG_HT1 :\ ((uint32_t)((__HANDLE__)->Instance) == ((uint32_t)DMA1_Channel2))? DMA_FLAG_HT2 :\ ((uint32_t)((__HANDLE__)->Instance) == ((uint32_t)DMA1_Channel3))? DMA_FLAG_HT3 :\ ((uint32_t)((__HANDLE__)->Instance) == ((uint32_t)DMA1_Channel4))? DMA_FLAG_HT4 :\ ((uint32_t)((__HANDLE__)->Instance) == ((uint32_t)DMA1_Channel5))? DMA_FLAG_HT5 :\ ((uint32_t)((__HANDLE__)->Instance) == ((uint32_t)DMA1_Channel6))? DMA_FLAG_HT6 :\ ((uint32_t)((__HANDLE__)->Instance) == ((uint32_t)DMA1_Channel7))? DMA_FLAG_HT7 :\ ((uint32_t)((__HANDLE__)->Instance) == ((uint32_t)DMA2_Channel1))? DMA_FLAG_HT1 :\ ((uint32_t)((__HANDLE__)->Instance) == ((uint32_t)DMA2_Channel2))? DMA_FLAG_HT2 :\ ((uint32_t)((__HANDLE__)->Instance) == ((uint32_t)DMA2_Channel3))? DMA_FLAG_HT3 :\ ((uint32_t)((__HANDLE__)->Instance) == ((uint32_t)DMA2_Channel4))? DMA_FLAG_HT4 :\ DMA_FLAG_HT5) /** * @brief Returns the current DMA Channel transfer error flag. * @param __HANDLE__: DMA handle * @retval The specified transfer error flag index. */ #define __HAL_DMA_GET_TE_FLAG_INDEX(__HANDLE__)\ (((uint32_t)((__HANDLE__)->Instance) == ((uint32_t)DMA1_Channel1))? DMA_FLAG_TE1 :\ ((uint32_t)((__HANDLE__)->Instance) == ((uint32_t)DMA1_Channel2))? DMA_FLAG_TE2 :\ ((uint32_t)((__HANDLE__)->Instance) == ((uint32_t)DMA1_Channel3))? DMA_FLAG_TE3 :\ ((uint32_t)((__HANDLE__)->Instance) == ((uint32_t)DMA1_Channel4))? DMA_FLAG_TE4 :\ ((uint32_t)((__HANDLE__)->Instance) == ((uint32_t)DMA1_Channel5))? DMA_FLAG_TE5 :\ ((uint32_t)((__HANDLE__)->Instance) == ((uint32_t)DMA1_Channel6))? DMA_FLAG_TE6 :\ ((uint32_t)((__HANDLE__)->Instance) == ((uint32_t)DMA1_Channel7))? DMA_FLAG_TE7 :\ ((uint32_t)((__HANDLE__)->Instance) == ((uint32_t)DMA2_Channel1))? DMA_FLAG_TE1 :\ ((uint32_t)((__HANDLE__)->Instance) == ((uint32_t)DMA2_Channel2))? DMA_FLAG_TE2 :\ ((uint32_t)((__HANDLE__)->Instance) == ((uint32_t)DMA2_Channel3))? DMA_FLAG_TE3 :\ ((uint32_t)((__HANDLE__)->Instance) == ((uint32_t)DMA2_Channel4))? DMA_FLAG_TE4 :\ DMA_FLAG_TE5) /** * @brief Get the DMA Channel pending flags. * @param __HANDLE__: DMA handle * @param __FLAG__: Get the specified flag. * This parameter can be any combination of the following values: * @arg DMA_FLAG_TCx: Transfer complete flag * @arg DMA_FLAG_HTx: Half transfer complete flag * @arg DMA_FLAG_TEx: Transfer error flag * Where x can be 0_4, 1_5, 2_6 or 3_7 to select the DMA Channel flag. * @retval The state of FLAG (SET or RESET). */ #define __HAL_DMA_GET_FLAG(__HANDLE__, __FLAG__)\ (((uint32_t)((__HANDLE__)->Instance) > (uint32_t)DMA1_Channel7)? (DMA2->ISR & (__FLAG__)) :\ (DMA1->ISR & (__FLAG__))) /** * @brief Clears the DMA Channel pending flags. * @param __HANDLE__: DMA handle * @param __FLAG__: specifies the flag to clear. * This parameter can be any combination of the following values: * @arg DMA_FLAG_TCx: Transfer complete flag * @arg DMA_FLAG_HTx: Half transfer complete flag * @arg DMA_FLAG_TEx: Transfer error flag * Where x can be 0_4, 1_5, 2_6 or 3_7 to select the DMA Channel flag. * @retval None */ #define __HAL_DMA_CLEAR_FLAG(__HANDLE__, __FLAG__) \ (((uint32_t)((__HANDLE__)->Instance) > (uint32_t)DMA1_Channel7)? (DMA2->IFCR = (__FLAG__)) :\ (DMA1->IFCR = (__FLAG__))) #else /* STM32F030x8_STM32F030xC_STM32F031x6_STM32F038xx_STM32F051x8_STM32F058xx_STM32F070x6_STM32F070xB Product devices */ /** * @brief Returns the current DMA Channel transfer complete flag. * @param __HANDLE__: DMA handle * @retval The specified transfer complete flag index. */ #define __HAL_DMA_GET_TC_FLAG_INDEX(__HANDLE__) \ (((uint32_t)((__HANDLE__)->Instance) == ((uint32_t)DMA1_Channel1))? DMA_FLAG_TC1 :\ ((uint32_t)((__HANDLE__)->Instance) == ((uint32_t)DMA1_Channel2))? DMA_FLAG_TC2 :\ ((uint32_t)((__HANDLE__)->Instance) == ((uint32_t)DMA1_Channel3))? DMA_FLAG_TC3 :\ ((uint32_t)((__HANDLE__)->Instance) == ((uint32_t)DMA1_Channel4))? DMA_FLAG_TC4 :\ DMA_FLAG_TC5) /** * @brief Returns the current DMA Channel half transfer complete flag. * @param __HANDLE__: DMA handle * @retval The specified half transfer complete flag index. */ #define __HAL_DMA_GET_HT_FLAG_INDEX(__HANDLE__)\ (((uint32_t)((__HANDLE__)->Instance) == ((uint32_t)DMA1_Channel1))? DMA_FLAG_HT1 :\ ((uint32_t)((__HANDLE__)->Instance) == ((uint32_t)DMA1_Channel2))? DMA_FLAG_HT2 :\ ((uint32_t)((__HANDLE__)->Instance) == ((uint32_t)DMA1_Channel3))? DMA_FLAG_HT3 :\ ((uint32_t)((__HANDLE__)->Instance) == ((uint32_t)DMA1_Channel4))? DMA_FLAG_HT4 :\ DMA_FLAG_HT5) /** * @brief Returns the current DMA Channel transfer error flag. * @param __HANDLE__: DMA handle * @retval The specified transfer error flag index. */ #define __HAL_DMA_GET_TE_FLAG_INDEX(__HANDLE__)\ (((uint32_t)((__HANDLE__)->Instance) == ((uint32_t)DMA1_Channel1))? DMA_FLAG_TE1 :\ ((uint32_t)((__HANDLE__)->Instance) == ((uint32_t)DMA1_Channel2))? DMA_FLAG_TE2 :\ ((uint32_t)((__HANDLE__)->Instance) == ((uint32_t)DMA1_Channel3))? DMA_FLAG_TE3 :\ ((uint32_t)((__HANDLE__)->Instance) == ((uint32_t)DMA1_Channel4))? DMA_FLAG_TE4 :\ DMA_FLAG_TE5) /** * @brief Get the DMA Channel pending flags. * @param __HANDLE__: DMA handle * @param __FLAG__: Get the specified flag. * This parameter can be any combination of the following values: * @arg DMA_FLAG_TCx: Transfer complete flag * @arg DMA_FLAG_HTx: Half transfer complete flag * @arg DMA_FLAG_TEx: Transfer error flag * Where x can be 1_5 to select the DMA Channel flag. * @retval The state of FLAG (SET or RESET). */ #define __HAL_DMA_GET_FLAG(__HANDLE__, __FLAG__) (DMA1->ISR & (__FLAG__)) /** * @brief Clears the DMA Channel pending flags. * @param __HANDLE__: DMA handle * @param __FLAG__: specifies the flag to clear. * This parameter can be any combination of the following values: * @arg DMA_FLAG_TCx: Transfer complete flag * @arg DMA_FLAG_HTx: Half transfer complete flag * @arg DMA_FLAG_TEx: Transfer error flag * Where x can be 1_5 to select the DMA Channel flag. * @retval None */ #define __HAL_DMA_CLEAR_FLAG(__HANDLE__, __FLAG__) (DMA1->IFCR = (__FLAG__)) #endif #if defined(STM32F091xC) || defined(STM32F098xx) || defined(STM32F030xC) #define __HAL_DMA1_REMAP(__REQUEST__) \ do { assert_param(IS_HAL_DMA1_REMAP(__REQUEST__)); \ DMA1->CSELR &= ~((uint32_t)0x0F << (uint32_t)(((__REQUEST__) >> 28) * 4)); \ DMA1->CSELR |= (uint32_t)((__REQUEST__) & 0x0FFFFFFF); \ }while(0) #if defined(STM32F091xC) || defined(STM32F098xx) #define __HAL_DMA2_REMAP(__REQUEST__) \ do { assert_param(IS_HAL_DMA2_REMAP(__REQUEST__)); \ DMA2->CSELR &= ~((uint32_t)0x0F << (uint32_t)(((__REQUEST__) >> 28) * 4)); \ DMA2->CSELR |= (uint32_t)((__REQUEST__) & 0x0FFFFFFF); \ }while(0) #endif /* STM32F091xC || STM32F098xx */ #endif /* STM32F091xC || STM32F098xx || STM32F030xC */ /** * @} */ /** * @} */ /** * @} */ #ifdef __cplusplus } #endif #endif /* __STM32F0xx_HAL_DMA_EX_H */ /************************ (C) COPYRIGHT STMicroelectronics *****END OF FILE****/ ================================================ FILE: Zelig/mbed/TARGET_NUCLEO_F091RC/stm32f0xx_hal_flash.h ================================================ /** ****************************************************************************** * @file stm32f0xx_hal_flash.h * @author MCD Application Team * @version V1.3.0 * @date 26-June-2015 * @brief Header file of Flash HAL module. ****************************************************************************** * @attention * *

© COPYRIGHT(c) 2015 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. * ****************************************************************************** */ /* Define to prevent recursive inclusion -------------------------------------*/ #ifndef __STM32F0xx_HAL_FLASH_H #define __STM32F0xx_HAL_FLASH_H #ifdef __cplusplus extern "C" { #endif /* Includes ------------------------------------------------------------------*/ #include "stm32f0xx_hal_def.h" /** @addtogroup STM32F0xx_HAL_Driver * @{ */ /** @addtogroup FLASH * @{ */ /** @addtogroup FLASH_Private_Constants * @{ */ #define FLASH_TIMEOUT_VALUE ((uint32_t)50000)/* 50 s */ /** * @} */ /** @addtogroup FLASH_Private_Macros * @{ */ #define IS_FLASH_TYPEPROGRAM(VALUE) (((VALUE) == FLASH_TYPEPROGRAM_HALFWORD) || \ ((VALUE) == FLASH_TYPEPROGRAM_WORD) || \ ((VALUE) == FLASH_TYPEPROGRAM_DOUBLEWORD)) #define IS_FLASH_LATENCY(__LATENCY__) (((__LATENCY__) == FLASH_LATENCY_0) || \ ((__LATENCY__) == FLASH_LATENCY_1)) /** * @} */ /* Exported types ------------------------------------------------------------*/ /** @defgroup FLASH_Exported_Types FLASH Exported Types * @{ */ /** * @brief FLASH Procedure structure definition */ typedef enum { FLASH_PROC_NONE = 0, FLASH_PROC_PAGEERASE = 1, FLASH_PROC_MASSERASE = 2, FLASH_PROC_PROGRAMHALFWORD = 3, FLASH_PROC_PROGRAMWORD = 4, FLASH_PROC_PROGRAMDOUBLEWORD = 5 } FLASH_ProcedureTypeDef; /** * @brief FLASH handle Structure definition */ typedef struct { __IO FLASH_ProcedureTypeDef ProcedureOnGoing; /*!< Internal variable to indicate which procedure is ongoing or not in IT context */ __IO uint32_t DataRemaining; /*!< Internal variable to save the remaining pages to erase or half-word to program in IT context */ __IO uint32_t Address; /*!< Internal variable to save address selected for program or erase */ __IO uint64_t Data; /*!< Internal variable to save data to be programmed */ HAL_LockTypeDef Lock; /*!< FLASH locking object */ __IO uint32_t ErrorCode; /*!< FLASH error code This parameter can be a value of @ref FLASH_Error_Codes */ } FLASH_ProcessTypeDef; /** * @} */ /* Exported constants --------------------------------------------------------*/ /** @defgroup FLASH_Exported_Constants FLASH Exported Constants * @{ */ /** @defgroup FLASH_Error_Codes FLASH Error Codes * @{ */ #define HAL_FLASH_ERROR_NONE ((uint32_t)0x00) #define HAL_FLASH_ERROR_PROG ((uint32_t)0x01) #define HAL_FLASH_ERROR_WRP ((uint32_t)0x02) /** * @} */ /** @defgroup FLASH_Type_Program FLASH Type Program * @{ */ #define FLASH_TYPEPROGRAM_HALFWORD ((uint32_t)0x01) /*!ACR = (FLASH->ACR&(~FLASH_ACR_LATENCY)) | (__LATENCY__)) /** * @brief Get the FLASH Latency. * @retval FLASH Latency * The value of this parameter depend on device used within the same series */ #define __HAL_FLASH_GET_LATENCY() (READ_BIT((FLASH->ACR), FLASH_ACR_LATENCY)) /** * @} */ /** @defgroup FLASH_Prefetch FLASH Prefetch * @brief macros to handle FLASH Prefetch buffer * @{ */ /** * @brief Enable the FLASH prefetch buffer. * @retval None */ #define __HAL_FLASH_PREFETCH_BUFFER_ENABLE() (FLASH->ACR |= FLASH_ACR_PRFTBE) /** * @brief Disable the FLASH prefetch buffer. * @retval None */ #define __HAL_FLASH_PREFETCH_BUFFER_DISABLE() (FLASH->ACR &= (~FLASH_ACR_PRFTBE)) /** * @} */ /** @defgroup FLASH_Interrupt FLASH Interrupts * @brief macros to handle FLASH interrupts * @{ */ /** * @brief Enable the specified FLASH interrupt. * @param __INTERRUPT__ : FLASH interrupt * This parameter can be any combination of the following values: * @arg FLASH_IT_EOP: End of FLASH Operation Interrupt * @arg FLASH_IT_ERR: Error Interrupt * @retval none */ #define __HAL_FLASH_ENABLE_IT(__INTERRUPT__) SET_BIT((FLASH->CR), (__INTERRUPT__)) /** * @brief Disable the specified FLASH interrupt. * @param __INTERRUPT__ : FLASH interrupt * This parameter can be any combination of the following values: * @arg FLASH_IT_EOP: End of FLASH Operation Interrupt * @arg FLASH_IT_ERR: Error Interrupt * @retval none */ #define __HAL_FLASH_DISABLE_IT(__INTERRUPT__) CLEAR_BIT((FLASH->CR), (uint32_t)(__INTERRUPT__)) /** * @brief Get the specified FLASH flag status. * @param __FLAG__: specifies the FLASH flag to check. * This parameter can be one of the following values: * @arg FLASH_FLAG_BSY : FLASH Busy flag * @arg FLASH_FLAG_EOP : FLASH End of Operation flag * @arg FLASH_FLAG_WRPERR: FLASH Write protected error flag * @arg FLASH_FLAG_PGERR : FLASH Programming error flag * @retval The new state of __FLAG__ (SET or RESET). */ #define __HAL_FLASH_GET_FLAG(__FLAG__) (((FLASH->SR) & (__FLAG__)) == (__FLAG__)) /** * @brief Clear the specified FLASH flag. * @param __FLAG__: specifies the FLASH flags to clear. * This parameter can be any combination of the following values: * @arg FLASH_FLAG_BSY : FLASH Busy flag * @arg FLASH_FLAG_EOP : FLASH End of Operation flag * @arg FLASH_FLAG_WRPERR: FLASH Write protected error flag * @arg FLASH_FLAG_PGERR : FLASH Programming error flag * @retval none */ #define __HAL_FLASH_CLEAR_FLAG(__FLAG__) ((FLASH->SR) = (__FLAG__)) /** * @} */ /** * @} */ /* Include FLASH HAL Extended module */ #include "stm32f0xx_hal_flash_ex.h" /* Exported functions --------------------------------------------------------*/ /** @addtogroup FLASH_Exported_Functions * @{ */ /** @addtogroup FLASH_Exported_Functions_Group1 * @{ */ /* IO operation functions *****************************************************/ HAL_StatusTypeDef HAL_FLASH_Program(uint32_t TypeProgram, uint32_t Address, uint64_t Data); HAL_StatusTypeDef HAL_FLASH_Program_IT(uint32_t TypeProgram, uint32_t Address, uint64_t Data); /* FLASH IRQ handler method */ void HAL_FLASH_IRQHandler(void); /* Callbacks in non blocking modes */ void HAL_FLASH_EndOfOperationCallback(uint32_t ReturnValue); void HAL_FLASH_OperationErrorCallback(uint32_t ReturnValue); /** * @} */ /** @addtogroup FLASH_Exported_Functions_Group2 * @{ */ /* Peripheral Control functions ***********************************************/ HAL_StatusTypeDef HAL_FLASH_Unlock(void); HAL_StatusTypeDef HAL_FLASH_Lock(void); HAL_StatusTypeDef HAL_FLASH_OB_Unlock(void); HAL_StatusTypeDef HAL_FLASH_OB_Lock(void); HAL_StatusTypeDef HAL_FLASH_OB_Launch(void); /** * @} */ /** @addtogroup FLASH_Exported_Functions_Group3 * @{ */ /* Peripheral State and Error functions ***************************************/ uint32_t HAL_FLASH_GetError(void); /** * @} */ /** * @} */ /* Private function -------------------------------------------------*/ /** @addtogroup FLASH_Private_Functions * @{ */ void FLASH_PageErase(uint32_t PageAddress); HAL_StatusTypeDef FLASH_WaitForLastOperation(uint32_t Timeout); /** * @} */ /** * @} */ /** * @} */ #ifdef __cplusplus } #endif #endif /* __STM32F0xx_HAL_FLASH_H */ /************************ (C) COPYRIGHT STMicroelectronics *****END OF FILE****/ ================================================ FILE: Zelig/mbed/TARGET_NUCLEO_F091RC/stm32f0xx_hal_flash_ex.h ================================================ /** ****************************************************************************** * @file stm32f0xx_hal_flash_ex.h * @author MCD Application Team * @version V1.3.0 * @date 26-June-2015 * @brief Header file of Flash HAL Extended module. ****************************************************************************** * @attention * *

© COPYRIGHT(c) 2015 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. * ****************************************************************************** */ /* Define to prevent recursive inclusion -------------------------------------*/ #ifndef __STM32F0xx_HAL_FLASH_EX_H #define __STM32F0xx_HAL_FLASH_EX_H #ifdef __cplusplus extern "C" { #endif /* Includes ------------------------------------------------------------------*/ #include "stm32f0xx_hal_def.h" /** @addtogroup STM32F0xx_HAL_Driver * @{ */ /** @addtogroup FLASHEx * @{ */ /** @addtogroup FLASHEx_Private_Macros * @{ */ #define IS_FLASH_TYPEERASE(VALUE) (((VALUE) == FLASH_TYPEERASE_PAGES) || \ ((VALUE) == FLASH_TYPEERASE_MASSERASE)) #define IS_OPTIONBYTE(VALUE) ((VALUE) <= (OPTIONBYTE_WRP | OPTIONBYTE_RDP | OPTIONBYTE_USER | OPTIONBYTE_DATA)) #define IS_WRPSTATE(VALUE) (((VALUE) == OB_WRPSTATE_DISABLE) || \ ((VALUE) == OB_WRPSTATE_ENABLE)) #define IS_OB_DATA_ADDRESS(ADDRESS) (((ADDRESS) == OB_DATA_ADDRESS_DATA0) || ((ADDRESS) == OB_DATA_ADDRESS_DATA1)) #define IS_OB_RDP_LEVEL(LEVEL) (((LEVEL) == OB_RDP_LEVEL_0) ||\ ((LEVEL) == OB_RDP_LEVEL_1))/*||\ ((LEVEL) == OB_RDP_LEVEL_2))*/ #define IS_OB_IWDG_SOURCE(SOURCE) (((SOURCE) == OB_IWDG_SW) || ((SOURCE) == OB_IWDG_HW)) #define IS_OB_STOP_SOURCE(SOURCE) (((SOURCE) == OB_STOP_NO_RST) || ((SOURCE) == OB_STOP_RST)) #define IS_OB_STDBY_SOURCE(SOURCE) (((SOURCE) == OB_STDBY_NO_RST) || ((SOURCE) == OB_STDBY_RST)) #define IS_OB_BOOT1(BOOT1) (((BOOT1) == OB_BOOT1_RESET) || ((BOOT1) == OB_BOOT1_SET)) #define IS_OB_VDDA_ANALOG(ANALOG) (((ANALOG) == OB_VDDA_ANALOG_ON) || ((ANALOG) == OB_VDDA_ANALOG_OFF)) #define IS_OB_SRAM_PARITY(PARITY) (((PARITY) == OB_RAM_PARITY_CHECK_SET) || ((PARITY) == OB_RAM_PARITY_CHECK_RESET)) #if defined(FLASH_OBR_BOOT_SEL) #define IS_OB_BOOT_SEL(BOOT_SEL) (((BOOT_SEL) == OB_BOOT_SEL_RESET) || ((BOOT_SEL) == OB_BOOT_SEL_SET)) #define IS_OB_BOOT0(BOOT0) (((BOOT0) == OB_BOOT0_RESET) || ((BOOT0) == OB_BOOT0_SET)) #endif /* FLASH_OBR_BOOT_SEL */ #define IS_FLASH_NB_PAGES(ADDRESS,NBPAGES) ((ADDRESS)+((NBPAGES)*FLASH_PAGE_SIZE)-1 <= FLASH_BANK1_END) #define IS_OB_WRP(PAGE) (((PAGE) != 0x0000000)) #define IS_FLASH_PROGRAM_ADDRESS(ADDRESS) (((ADDRESS) >= FLASH_BASE) && ((ADDRESS) <= FLASH_BANK1_END)) /** * @} */ /* Exported types ------------------------------------------------------------*/ /** @defgroup FLASHEx_Exported_Types FLASHEx Exported Types * @{ */ /** * @brief FLASH Erase structure definition */ typedef struct { uint32_t TypeErase; /*!< TypeErase: Mass erase or page erase. This parameter can be a value of @ref FLASHEx_Type_Erase */ uint32_t PageAddress; /*!< PageAdress: Initial FLASH page address to erase when mass erase is disabled This parameter must be a number between Min_Data = FLASH_BASE and Max_Data = FLASH_BANK1_END */ uint32_t NbPages; /*!< NbPages: Number of pagess to be erased. This parameter must be a value between Min_Data = 1 and Max_Data = (max number of pages - value of initial page)*/ } FLASH_EraseInitTypeDef; /** * @brief FLASH Options bytes program structure definition */ typedef struct { uint32_t OptionType; /*!< OptionType: Option byte to be configured. This parameter can be a value of @ref FLASHEx_OB_Type */ uint32_t WRPState; /*!< WRPState: Write protection activation or deactivation. This parameter can be a value of @ref FLASHEx_OB_WRP_State */ uint32_t WRPPage; /*!< WRPPage: specifies the page(s) to be write protected This parameter can be a value of @ref FLASHEx_OB_Write_Protection */ uint8_t RDPLevel; /*!< RDPLevel: Set the read protection level.. This parameter can be a value of @ref FLASHEx_OB_Read_Protection */ uint8_t USERConfig; /*!< USERConfig: Program the FLASH User Option Byte: IWDG / STOP / STDBY / BOOT1 / VDDA_ANALOG / SRAM_PARITY This parameter can be a combination of @ref FLASHEx_OB_Watchdog, @ref FLASHEx_OB_nRST_STOP, @ref FLASHEx_OB_nRST_STDBY, @ref FLASHEx_OB_BOOT1, @ref FLASHEx_OB_VDDA_Analog_Monitoring and @ref FLASHEx_OB_RAM_Parity_Check_Enable */ uint32_t DATAAddress; /*!< DATAAddress: Address of the option byte DATA to be programmed This parameter can be a value of @ref FLASHEx_OB_Data_Address */ uint8_t DATAData; /*!< DATAData: Data to be stored in the option byte DATA This parameter must be a number between Min_Data = 0x00 and Max_Data = 0xFF */ } FLASH_OBProgramInitTypeDef; /** * @} */ /* Exported constants --------------------------------------------------------*/ /** @defgroup FLASHEx_Exported_Constants FLASHEx Exported Constants * @{ */ /** @defgroup FLASHEx_Page_Size FLASHEx Page Size * @{ */ #if defined(STM32F030x6) || defined(STM32F030x8) || defined(STM32F031x6) || defined(STM32F038xx) \ || defined(STM32F051x8) || defined(STM32F042x6) || defined(STM32F048xx) || defined(STM32F058xx) || defined(STM32F070x6) #define FLASH_PAGE_SIZE 0x400 #endif /* STM32F030x6 || STM32F030x8 || STM32F031x6 || STM32F051x8 || STM32F042x6 || STM32F048xx || STM32F058xx || STM32F070x6 */ #if defined(STM32F071xB) || defined(STM32F072xB) || defined(STM32F078xx) || defined(STM32F070xB) \ || defined(STM32F091xC) || defined(STM32F098xx) || defined(STM32F030xC) #define FLASH_PAGE_SIZE 0x800 #endif /* STM32F071xB || STM32F072xB || STM32F078xx || STM32F091xC || STM32F098xx || STM32F030xC */ /** * @} */ /** @defgroup FLASHEx_Type_Erase FLASH Type Erase * @{ */ #define FLASH_TYPEERASE_PAGES ((uint32_t)0x00) /*!
© COPYRIGHT(c) 2015 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. * ****************************************************************************** */ /* Define to prevent recursive inclusion -------------------------------------*/ #ifndef __STM32F0xx_HAL_GPIO_H #define __STM32F0xx_HAL_GPIO_H #ifdef __cplusplus extern "C" { #endif /* Includes ------------------------------------------------------------------*/ #include "stm32f0xx_hal_def.h" /** @addtogroup STM32F0xx_HAL_Driver * @{ */ /** @addtogroup GPIO * @{ */ /* Exported types ------------------------------------------------------------*/ /** @defgroup GPIO_Exported_Types GPIO Exported Types * @{ */ /** * @brief GPIO Init structure definition */ typedef struct { uint32_t Pin; /*!< Specifies the GPIO pins to be configured. This parameter can be any value of @ref GPIO_pins */ uint32_t Mode; /*!< Specifies the operating mode for the selected pins. This parameter can be a value of @ref GPIO_mode */ uint32_t Pull; /*!< Specifies the Pull-up or Pull-Down activation for the selected pins. This parameter can be a value of @ref GPIO_pull */ uint32_t Speed; /*!< Specifies the speed for the selected pins. This parameter can be a value of @ref GPIO_speed */ uint32_t Alternate; /*!< Peripheral to be connected to the selected pins This parameter can be a value of @ref GPIOEx_Alternate_function_selection */ }GPIO_InitTypeDef; /** * @brief GPIO Bit SET and Bit RESET enumeration */ typedef enum { GPIO_PIN_RESET = 0, GPIO_PIN_SET }GPIO_PinState; /** * @} */ /* Exported constants --------------------------------------------------------*/ /** @defgroup GPIO_Exported_Constants GPIO Exported Constants * @{ */ /** @defgroup GPIO_pins GPIO pins * @{ */ #define GPIO_PIN_0 ((uint16_t)0x0001) /* Pin 0 selected */ #define GPIO_PIN_1 ((uint16_t)0x0002) /* Pin 1 selected */ #define GPIO_PIN_2 ((uint16_t)0x0004) /* Pin 2 selected */ #define GPIO_PIN_3 ((uint16_t)0x0008) /* Pin 3 selected */ #define GPIO_PIN_4 ((uint16_t)0x0010) /* Pin 4 selected */ #define GPIO_PIN_5 ((uint16_t)0x0020) /* Pin 5 selected */ #define GPIO_PIN_6 ((uint16_t)0x0040) /* Pin 6 selected */ #define GPIO_PIN_7 ((uint16_t)0x0080) /* Pin 7 selected */ #define GPIO_PIN_8 ((uint16_t)0x0100) /* Pin 8 selected */ #define GPIO_PIN_9 ((uint16_t)0x0200) /* Pin 9 selected */ #define GPIO_PIN_10 ((uint16_t)0x0400) /* Pin 10 selected */ #define GPIO_PIN_11 ((uint16_t)0x0800) /* Pin 11 selected */ #define GPIO_PIN_12 ((uint16_t)0x1000) /* Pin 12 selected */ #define GPIO_PIN_13 ((uint16_t)0x2000) /* Pin 13 selected */ #define GPIO_PIN_14 ((uint16_t)0x4000) /* Pin 14 selected */ #define GPIO_PIN_15 ((uint16_t)0x8000) /* Pin 15 selected */ #define GPIO_PIN_All ((uint16_t)0xFFFF) /* All pins selected */ #define GPIO_PIN_MASK ((uint32_t)0x0000FFFF) /* PIN mask for assert test */ /** * @} */ /** @defgroup GPIO_mode GPIO mode * @brief GPIO Configuration Mode * Elements values convention: 0xX0yz00YZ * - X : GPIO mode or EXTI Mode * - y : External IT or Event trigger detection * - z : IO configuration on External IT or Event * - Y : Output type (Push Pull or Open Drain) * - Z : IO Direction mode (Input, Output, Alternate or Analog) * @{ */ #define GPIO_MODE_INPUT ((uint32_t)0x00000000) /*!< Input Floating Mode */ #define GPIO_MODE_OUTPUT_PP ((uint32_t)0x00000001) /*!< Output Push Pull Mode */ #define GPIO_MODE_OUTPUT_OD ((uint32_t)0x00000011) /*!< Output Open Drain Mode */ #define GPIO_MODE_AF_PP ((uint32_t)0x00000002) /*!< Alternate Function Push Pull Mode */ #define GPIO_MODE_AF_OD ((uint32_t)0x00000012) /*!< Alternate Function Open Drain Mode */ #define GPIO_MODE_ANALOG ((uint32_t)0x00000003) /*!< Analog Mode */ #define GPIO_MODE_IT_RISING ((uint32_t)0x10110000) /*!< External Interrupt Mode with Rising edge trigger detection */ #define GPIO_MODE_IT_FALLING ((uint32_t)0x10210000) /*!< External Interrupt Mode with Falling edge trigger detection */ #define GPIO_MODE_IT_RISING_FALLING ((uint32_t)0x10310000) /*!< External Interrupt Mode with Rising/Falling edge trigger detection */ #define GPIO_MODE_EVT_RISING ((uint32_t)0x10120000) /*!< External Event Mode with Rising edge trigger detection */ #define GPIO_MODE_EVT_FALLING ((uint32_t)0x10220000) /*!< External Event Mode with Falling edge trigger detection */ #define GPIO_MODE_EVT_RISING_FALLING ((uint32_t)0x10320000) /*!< External Event Mode with Rising/Falling edge trigger detection */ /** * @} */ /** @defgroup GPIO_speed GPIO speed * @brief GPIO Output Maximum frequency * @{ */ #define GPIO_SPEED_LOW ((uint32_t)0x00000000) /*!< Low speed */ #define GPIO_SPEED_MEDIUM ((uint32_t)0x00000001) /*!< Medium speed */ #define GPIO_SPEED_HIGH ((uint32_t)0x00000003) /*!< High speed */ /** * @} */ /** @defgroup GPIO_pull GPIO pull * @brief GPIO Pull-Up or Pull-Down Activation * @{ */ #define GPIO_NOPULL ((uint32_t)0x00000000) /*!< No Pull-up or Pull-down activation */ #define GPIO_PULLUP ((uint32_t)0x00000001) /*!< Pull-up activation */ #define GPIO_PULLDOWN ((uint32_t)0x00000002) /*!< Pull-down activation */ /** * @} */ /** * @} */ /* Exported macro ------------------------------------------------------------*/ /** @defgroup GPIO_Exported_Macros GPIO Exported Macros * @{ */ /** * @brief Check whether the specified EXTI line flag is set or not. * @param __EXTI_LINE__: specifies the EXTI line flag to check. * This parameter can be GPIO_PIN_x where x can be(0..15) * @retval The new state of __EXTI_LINE__ (SET or RESET). */ #define __HAL_GPIO_EXTI_GET_FLAG(__EXTI_LINE__) (EXTI->PR & (__EXTI_LINE__)) /** * @brief Clear the EXTI's line pending flags. * @param __EXTI_LINE__: specifies the EXTI lines flags to clear. * This parameter can be any combination of GPIO_PIN_x where x can be (0..15) * @retval None */ #define __HAL_GPIO_EXTI_CLEAR_FLAG(__EXTI_LINE__) (EXTI->PR = (__EXTI_LINE__)) /** * @brief Check whether the specified EXTI line is asserted or not. * @param __EXTI_LINE__: specifies the EXTI line to check. * This parameter can be GPIO_PIN_x where x can be(0..15) * @retval The new state of __EXTI_LINE__ (SET or RESET). */ #define __HAL_GPIO_EXTI_GET_IT(__EXTI_LINE__) (EXTI->PR & (__EXTI_LINE__)) /** * @brief Clear the EXTI's line pending bits. * @param __EXTI_LINE__: specifies the EXTI lines to clear. * This parameter can be any combination of GPIO_PIN_x where x can be (0..15) * @retval None */ #define __HAL_GPIO_EXTI_CLEAR_IT(__EXTI_LINE__) (EXTI->PR = (__EXTI_LINE__)) /** * @brief Generate a Software interrupt on selected EXTI line. * @param __EXTI_LINE__: specifies the EXTI line to check. * This parameter can be GPIO_PIN_x where x can be(0..15) * @retval None */ #define __HAL_GPIO_EXTI_GENERATE_SWIT(__EXTI_LINE__) (EXTI->SWIER |= (__EXTI_LINE__)) /** * @} */ /* Private macros ------------------------------------------------------------*/ /** @addtogroup GPIO_Private_Macros GPIO Private Macros * @{ */ #define IS_GPIO_PIN_ACTION(ACTION) (((ACTION) == GPIO_PIN_RESET) || ((ACTION) == GPIO_PIN_SET)) #define IS_GPIO_PIN(__PIN__) (((__PIN__) & GPIO_PIN_MASK) != (uint32_t)0x00) #define IS_GPIO_MODE(__MODE__) (((__MODE__) == GPIO_MODE_INPUT) ||\ ((__MODE__) == GPIO_MODE_OUTPUT_PP) ||\ ((__MODE__) == GPIO_MODE_OUTPUT_OD) ||\ ((__MODE__) == GPIO_MODE_AF_PP) ||\ ((__MODE__) == GPIO_MODE_AF_OD) ||\ ((__MODE__) == GPIO_MODE_IT_RISING) ||\ ((__MODE__) == GPIO_MODE_IT_FALLING) ||\ ((__MODE__) == GPIO_MODE_IT_RISING_FALLING) ||\ ((__MODE__) == GPIO_MODE_EVT_RISING) ||\ ((__MODE__) == GPIO_MODE_EVT_FALLING) ||\ ((__MODE__) == GPIO_MODE_EVT_RISING_FALLING) ||\ ((__MODE__) == GPIO_MODE_ANALOG)) #define IS_GPIO_SPEED(__SPEED__) (((__SPEED__) == GPIO_SPEED_LOW) ||\ ((__SPEED__) == GPIO_SPEED_MEDIUM) ||\ ((__SPEED__) == GPIO_SPEED_HIGH)) #define IS_GPIO_PULL(__PULL__) (((__PULL__) == GPIO_NOPULL) ||\ ((__PULL__) == GPIO_PULLUP) || \ ((__PULL__) == GPIO_PULLDOWN)) /** * @} */ /* Include GPIO HAL Extended module */ #include "stm32f0xx_hal_gpio_ex.h" /* Exported functions --------------------------------------------------------*/ /** @addtogroup GPIO_Exported_Functions GPIO Exported Functions * @{ */ /** @addtogroup GPIO_Exported_Functions_Group1 Initialization/de-initialization functions * @brief Initialization and Configuration functions * @{ */ /* Initialization and de-initialization functions *****************************/ void HAL_GPIO_Init(GPIO_TypeDef *GPIOx, GPIO_InitTypeDef *GPIO_Init); void HAL_GPIO_DeInit(GPIO_TypeDef *GPIOx, uint32_t GPIO_Pin); /** * @} */ /** @addtogroup GPIO_Exported_Functions_Group2 IO operation functions * @{ */ /* IO operation functions *****************************************************/ GPIO_PinState HAL_GPIO_ReadPin(GPIO_TypeDef* GPIOx, uint16_t GPIO_Pin); void HAL_GPIO_WritePin(GPIO_TypeDef* GPIOx, uint16_t GPIO_Pin, GPIO_PinState PinState); void HAL_GPIO_TogglePin(GPIO_TypeDef* GPIOx, uint16_t GPIO_Pin); HAL_StatusTypeDef HAL_GPIO_LockPin(GPIO_TypeDef* GPIOx, uint16_t GPIO_Pin); void HAL_GPIO_EXTI_IRQHandler(uint16_t GPIO_Pin); void HAL_GPIO_EXTI_Callback(uint16_t GPIO_Pin); /** * @} */ /** * @} */ /** * @} */ /** * @} */ #ifdef __cplusplus } #endif #endif /* __STM32F0xx_HAL_GPIO_H */ /************************ (C) COPYRIGHT STMicroelectronics *****END OF FILE****/ ================================================ FILE: Zelig/mbed/TARGET_NUCLEO_F091RC/stm32f0xx_hal_gpio_ex.h ================================================ /** ****************************************************************************** * @file stm32f0xx_hal_gpio_ex.h * @author MCD Application Team * @version V1.3.0 * @date 26-June-2015 * @brief Header file of GPIO HAL Extension module. ****************************************************************************** * @attention * *

© COPYRIGHT(c) 2015 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. * ****************************************************************************** */ /* Define to prevent recursive inclusion -------------------------------------*/ #ifndef __STM32F0xx_HAL_GPIO_EX_H #define __STM32F0xx_HAL_GPIO_EX_H #ifdef __cplusplus extern "C" { #endif /* Includes ------------------------------------------------------------------*/ #include "stm32f0xx_hal_def.h" /** @addtogroup STM32F0xx_HAL_Driver * @{ */ /** @defgroup GPIOEx GPIOEx * @{ */ /* Exported types ------------------------------------------------------------*/ /* Exported constants --------------------------------------------------------*/ /** @defgroup GPIOEx_Exported_Constants GPIOEx Exported Constants * @{ */ /** @defgroup GPIOEx_Alternate_function_selection GPIOEx Alternate function selection * @{ */ #if defined (STM32F030x6) /*------------------------- STM32F030x6---------------------------*/ /* AF 0 */ #define GPIO_AF0_EVENTOUT ((uint8_t)0x00) /*!< AF0: EVENTOUT Alternate Function mapping */ #define GPIO_AF0_MCO ((uint8_t)0x00) /*!< AF0: MCO Alternate Function mapping */ #define GPIO_AF0_SPI1 ((uint8_t)0x00) /*!< AF0: SPI1 Alternate Function mapping */ #define GPIO_AF0_TIM17 ((uint8_t)0x00) /*!< AF0: TIM17 Alternate Function mapping */ #define GPIO_AF0_SWDIO ((uint8_t)0x00) /*!< AF0: SWDIO Alternate Function mapping */ #define GPIO_AF0_SWCLK ((uint8_t)0x00) /*!< AF0: SWCLK Alternate Function mapping */ #define GPIO_AF0_TIM14 ((uint8_t)0x00) /*!< AF0: TIM14 Alternate Function mapping */ #define GPIO_AF0_USART1 ((uint8_t)0x00) /*!< AF0: USART1 Alternate Function mapping */ #define GPIO_AF0_IR ((uint8_t)0x00) /*!< AF0: IR Alternate Function mapping */ /* AF 1 */ #define GPIO_AF1_TIM3 ((uint8_t)0x01) /*!< AF1: TIM3 Alternate Function mapping */ #define GPIO_AF1_USART1 ((uint8_t)0x01) /*!< AF1: USART1 Alternate Function mapping */ #define GPIO_AF1_EVENTOUT ((uint8_t)0x01) /*!< AF1: EVENTOUT Alternate Function mapping */ #define GPIO_AF1_I2C1 ((uint8_t)0x01) /*!< AF1: I2C1 Alternate Function mapping */ #define GPIO_AF1_IR ((uint8_t)0x01) /*!< AF1: IR Alternate Function mapping */ /* AF 2 */ #define GPIO_AF2_TIM1 ((uint8_t)0x02) /*!< AF2: TIM1 Alternate Function mapping */ #define GPIO_AF2_TIM16 ((uint8_t)0x02) /*!< AF2: TIM16 Alternate Function mapping */ #define GPIO_AF2_TIM17 ((uint8_t)0x02) /*!< AF2: TIM17 Alternate Function mapping */ #define GPIO_AF2_EVENTOUT ((uint8_t)0x02) /*!< AF2: EVENTOUT Alternate Function mapping */ /* AF 3 */ #define GPIO_AF3_EVENTOUT ((uint8_t)0x03) /*!< AF3: EVENTOUT Alternate Function mapping */ #define GPIO_AF3_I2C1 ((uint8_t)0x03) /*!< AF3: I2C1 Alternate Function mapping */ /* AF 4 */ #define GPIO_AF4_TIM14 ((uint8_t)0x04) /*!< AF4: TIM14 Alternate Function mapping */ #define GPIO_AF4_I2C1 ((uint8_t)0x04) /*!< AF4: I2C1 Alternate Function mapping */ /* AF 5 */ #define GPIO_AF5_TIM16 ((uint8_t)0x05) /*!< AF5: TIM16 Alternate Function mapping */ #define GPIO_AF5_TIM17 ((uint8_t)0x05) /*!< AF5: TIM17 Alternate Function mapping */ /* AF 6 */ #define GPIO_AF6_EVENTOUT ((uint8_t)0x06) /*!< AF6: EVENTOUT Alternate Function mapping */ #define IS_GPIO_AF(AF) ((AF) <= (uint8_t)0x06) #endif /* STM32F030x6 */ /*---------------------------------- STM32F030x8 -------------------------------------------*/ #if defined (STM32F030x8) /* AF 0 */ #define GPIO_AF0_EVENTOUT ((uint8_t)0x00) /*!< AF0: EVENTOUT Alternate Function mapping */ #define GPIO_AF0_MCO ((uint8_t)0x00) /*!< AF0: MCO Alternate Function mapping */ #define GPIO_AF0_SPI1 ((uint8_t)0x00) /*!< AF0: SPI1 Alternate Function mapping */ #define GPIO_AF0_SPI2 ((uint8_t)0x00) /*!< AF0: SPI2 Alternate Function mapping */ #define GPIO_AF0_TIM15 ((uint8_t)0x00) /*!< AF0: TIM15 Alternate Function mapping */ #define GPIO_AF0_TIM17 ((uint8_t)0x00) /*!< AF0: TIM17 Alternate Function mapping */ #define GPIO_AF0_SWDIO ((uint8_t)0x00) /*!< AF0: SWDIO Alternate Function mapping */ #define GPIO_AF0_SWCLK ((uint8_t)0x00) /*!< AF0: SWCLK Alternate Function mapping */ #define GPIO_AF0_TIM14 ((uint8_t)0x00) /*!< AF0: TIM14 Alternate Function mapping */ #define GPIO_AF0_USART1 ((uint8_t)0x00) /*!< AF0: USART1 Alternate Function mapping */ #define GPIO_AF0_IR ((uint8_t)0x00) /*!< AF0: IR Alternate Function mapping */ /* AF 1 */ #define GPIO_AF1_TIM3 ((uint8_t)0x01) /*!< AF1: TIM3 Alternate Function mapping */ #define GPIO_AF1_TIM15 ((uint8_t)0x01) /*!< AF1: TIM15 Alternate Function mapping */ #define GPIO_AF1_USART1 ((uint8_t)0x01) /*!< AF1: USART1 Alternate Function mapping */ #define GPIO_AF1_USART2 ((uint8_t)0x01) /*!< AF1: USART2 Alternate Function mapping */ #define GPIO_AF1_EVENTOUT ((uint8_t)0x01) /*!< AF1: EVENTOUT Alternate Function mapping */ #define GPIO_AF1_I2C1 ((uint8_t)0x01) /*!< AF1: I2C1 Alternate Function mapping */ #define GPIO_AF1_I2C2 ((uint8_t)0x01) /*!< AF1: I2C2 Alternate Function mapping */ #define GPIO_AF1_IR ((uint8_t)0x01) /*!< AF1: IR Alternate Function mapping */ /* AF 2 */ #define GPIO_AF2_TIM1 ((uint8_t)0x02) /*!< AF2: TIM1 Alternate Function mapping */ #define GPIO_AF2_TIM16 ((uint8_t)0x02) /*!< AF2: TIM16 Alternate Function mapping */ #define GPIO_AF2_TIM17 ((uint8_t)0x02) /*!< AF2: TIM17 Alternate Function mapping */ #define GPIO_AF2_EVENTOUT ((uint8_t)0x02) /*!< AF2: EVENTOUT Alternate Function mapping */ /* AF 3 */ #define GPIO_AF3_EVENTOUT ((uint8_t)0x03) /*!< AF3: EVENTOUT Alternate Function mapping */ #define GPIO_AF3_I2C1 ((uint8_t)0x03) /*!< AF3: I2C1 Alternate Function mapping */ #define GPIO_AF3_TIM15 ((uint8_t)0x03) /*!< AF3: TIM15 Alternate Function mapping */ /* AF 4 */ #define GPIO_AF4_TIM14 ((uint8_t)0x04) /*!< AF4: TIM14 Alternate Function mapping */ /* AF 5 */ #define GPIO_AF5_TIM16 ((uint8_t)0x05) /*!< AF5: TIM16 Alternate Function mapping */ #define GPIO_AF5_TIM17 ((uint8_t)0x05) /*!< AF5: TIM17 Alternate Function mapping */ /* AF 6 */ #define GPIO_AF6_EVENTOUT ((uint8_t)0x06) /*!< AF6: EVENTOUT Alternate Function mapping */ #define IS_GPIO_AF(AF) ((AF) <= (uint8_t)0x06) #endif /* STM32F030x8 */ #if defined (STM32F031x6) || defined (STM32F038xx) /*--------------------------- STM32F031x6/STM32F038xx ---------------------------*/ /* AF 0 */ #define GPIO_AF0_EVENTOUT ((uint8_t)0x00) /*!< AF0: EVENTOUT Alternate Function mapping */ #define GPIO_AF0_MCO ((uint8_t)0x00) /*!< AF0: MCO Alternate Function mapping */ #define GPIO_AF0_SPI1 ((uint8_t)0x00) /*!< AF0: SPI1/I2S1 Alternate Function mapping */ #define GPIO_AF0_TIM17 ((uint8_t)0x00) /*!< AF0: TIM17 Alternate Function mapping */ #define GPIO_AF0_SWDAT ((uint8_t)0x00) /*!< AF0: SWDAT Alternate Function mapping */ #define GPIO_AF0_SWCLK ((uint8_t)0x00) /*!< AF0: SWCLK Alternate Function mapping */ #define GPIO_AF0_TIM14 ((uint8_t)0x00) /*!< AF0: TIM14 Alternate Function mapping */ #define GPIO_AF0_USART1 ((uint8_t)0x00) /*!< AF0: USART1 Alternate Function mapping */ #define GPIO_AF0_IR ((uint8_t)0x00) /*!< AF0: IR Alternate Function mapping */ /* AF 1 */ #define GPIO_AF1_TIM3 ((uint8_t)0x01) /*!< AF1: TIM3 Alternate Function mapping */ #define GPIO_AF1_USART1 ((uint8_t)0x01) /*!< AF1: USART1 Alternate Function mapping */ #define GPIO_AF1_IR ((uint8_t)0x01) /*!< AF1: IR Alternate Function mapping */ #define GPIO_AF1_EVENTOUT ((uint8_t)0x01) /*!< AF1: EVENTOUT Alternate Function mapping */ #define GPIO_AF1_I2C1 ((uint8_t)0x01) /*!< AF1: I2C1 Alternate Function mapping */ /* AF 2 */ #define GPIO_AF2_TIM1 ((uint8_t)0x02) /*!< AF2: TIM1 Alternate Function mapping */ #define GPIO_AF2_TIM2 ((uint8_t)0x02) /*!< AF2: TIM2 Alternate Function mapping */ #define GPIO_AF2_TIM16 ((uint8_t)0x02) /*!< AF2: TIM16 Alternate Function mapping */ #define GPIO_AF2_TIM17 ((uint8_t)0x02) /*!< AF2: TIM17 Alternate Function mapping */ #define GPIO_AF2_EVENTOUT ((uint8_t)0x02) /*!< AF2: EVENTOUT Alternate Function mapping */ /* AF 3 */ #define GPIO_AF3_EVENTOUT ((uint8_t)0x03) /*!< AF3: EVENTOUT Alternate Function mapping */ #define GPIO_AF3_I2C1 ((uint8_t)0x03) /*!< AF3: I2C1 Alternate Function mapping */ /* AF 4 */ #define GPIO_AF4_TIM14 ((uint8_t)0x04) /*!< AF4: TIM14 Alternate Function mapping */ #define GPIO_AF4_I2C1 ((uint8_t)0x04) /*!< AF4: I2C1 Alternate Function mapping */ /* AF 5 */ #define GPIO_AF5_TIM16 ((uint8_t)0x05) /*!< AF5: TIM16 Alternate Function mapping */ #define GPIO_AF5_TIM17 ((uint8_t)0x05) /*!< AF5: TIM17 Alternate Function mapping */ /* AF 6 */ #define GPIO_AF6_EVENTOUT ((uint8_t)0x06) /*!< AF6: EVENTOUT Alternate Function mapping */ #define IS_GPIO_AF(AF) ((AF) <= (uint8_t)0x06) #endif /* STM32F031x6 || STM32F038xx */ #if defined (STM32F051x8) || defined (STM32F058xx) /*--------------------------- STM32F051x8/STM32F058xx---------------------------*/ /* AF 0 */ #define GPIO_AF0_EVENTOUT ((uint8_t)0x00) /*!< AF0: EVENTOUT Alternate Function mapping */ #define GPIO_AF0_MCO ((uint8_t)0x00) /*!< AF0: MCO Alternate Function mapping */ #define GPIO_AF0_SPI1 ((uint8_t)0x00) /*!< AF0: SPI1/I2S1 Alternate Function mapping */ #define GPIO_AF0_SPI2 ((uint8_t)0x00) /*!< AF0: SPI2 Alternate Function mapping */ #define GPIO_AF0_TIM15 ((uint8_t)0x00) /*!< AF0: TIM15 Alternate Function mapping */ #define GPIO_AF0_TIM17 ((uint8_t)0x00) /*!< AF0: TIM17 Alternate Function mapping */ #define GPIO_AF0_SWDIO ((uint8_t)0x00) /*!< AF0: SWDIO Alternate Function mapping */ #define GPIO_AF0_SWCLK ((uint8_t)0x00) /*!< AF0: SWCLK Alternate Function mapping */ #define GPIO_AF0_TIM14 ((uint8_t)0x00) /*!< AF0: TIM14 Alternate Function mapping */ #define GPIO_AF0_USART1 ((uint8_t)0x00) /*!< AF0: USART1 Alternate Function mapping */ #define GPIO_AF0_IR ((uint8_t)0x00) /*!< AF0: IR Alternate Function mapping */ #define GPIO_AF0_CEC ((uint8_t)0x00) /*!< AF0: CEC Alternate Function mapping */ /* AF 1 */ #define GPIO_AF1_TIM3 ((uint8_t)0x01) /*!< AF1: TIM3 Alternate Function mapping */ #define GPIO_AF1_TIM15 ((uint8_t)0x01) /*!< AF1: TIM15 Alternate Function mapping */ #define GPIO_AF1_USART1 ((uint8_t)0x01) /*!< AF1: USART1 Alternate Function mapping */ #define GPIO_AF1_USART2 ((uint8_t)0x01) /*!< AF1: USART2 Alternate Function mapping */ #define GPIO_AF1_EVENTOUT ((uint8_t)0x01) /*!< AF1: EVENTOUT Alternate Function mapping */ #define GPIO_AF1_I2C1 ((uint8_t)0x01) /*!< AF1: I2C1 Alternate Function mapping */ #define GPIO_AF1_I2C2 ((uint8_t)0x01) /*!< AF1: I2C2 Alternate Function mapping */ #define GPIO_AF1_IR ((uint8_t)0x01) /*!< AF1: IR Alternate Function mapping */ #define GPIO_AF1_CEC ((uint8_t)0x01) /*!< AF1: CEC Alternate Function mapping */ /* AF 2 */ #define GPIO_AF2_TIM1 ((uint8_t)0x02) /*!< AF2: TIM1 Alternate Function mapping */ #define GPIO_AF2_TIM2 ((uint8_t)0x02) /*!< AF2: TIM2 Alternate Function mapping */ #define GPIO_AF2_TIM16 ((uint8_t)0x02) /*!< AF2: TIM16 Alternate Function mapping */ #define GPIO_AF2_TIM17 ((uint8_t)0x02) /*!< AF2: TIM17 Alternate Function mapping */ #define GPIO_AF2_EVENTOUT ((uint8_t)0x02) /*!< AF2: EVENTOUT Alternate Function mapping */ /* AF 3 */ #define GPIO_AF3_EVENTOUT ((uint8_t)0x03) /*!< AF3: EVENTOUT Alternate Function mapping */ #define GPIO_AF3_I2C1 ((uint8_t)0x03) /*!< AF3: I2C1 Alternate Function mapping */ #define GPIO_AF3_TIM15 ((uint8_t)0x03) /*!< AF3: TIM15 Alternate Function mapping */ #define GPIO_AF3_TSC ((uint8_t)0x03) /*!< AF3: TSC Alternate Function mapping */ /* AF 4 */ #define GPIO_AF4_TIM14 ((uint8_t)0x04) /*!< AF4: TIM14 Alternate Function mapping */ /* AF 5 */ #define GPIO_AF5_TIM16 ((uint8_t)0x05) /*!< AF5: TIM16 Alternate Function mapping */ #define GPIO_AF5_TIM17 ((uint8_t)0x05) /*!< AF5: TIM17 Alternate Function mapping */ /* AF 6 */ #define GPIO_AF6_EVENTOUT ((uint8_t)0x06) /*!< AF6: EVENTOUT Alternate Function mapping */ /* AF 7 */ #define GPIO_AF7_COMP1 ((uint8_t)0x07) /*!< AF7: COMP1 Alternate Function mapping */ #define GPIO_AF7_COMP2 ((uint8_t)0x07) /*!< AF7: COMP2 Alternate Function mapping */ #define IS_GPIO_AF(AF) ((AF) <= (uint8_t)0x07) #endif /* STM32F051x8/STM32F058xx */ #if defined (STM32F071xB) /*--------------------------- STM32F071xB ---------------------------*/ /* AF 0 */ #define GPIO_AF0_EVENTOUT ((uint8_t)0x00) /*!< AF0: AEVENTOUT Alternate Function mapping */ #define GPIO_AF0_SWDIO ((uint8_t)0x00) /*!< AF0: SWDIO Alternate Function mapping */ #define GPIO_AF0_SWCLK ((uint8_t)0x00) /*!< AF0: SWCLK Alternate Function mapping */ #define GPIO_AF0_MCO ((uint8_t)0x00) /*!< AF0: MCO Alternate Function mapping */ #define GPIO_AF0_CEC ((uint8_t)0x00) /*!< AF0: CEC Alternate Function mapping */ #define GPIO_AF0_CRS ((uint8_t)0x00) /*!< AF0: CRS Alternate Function mapping */ #define GPIO_AF0_IR ((uint8_t)0x00) /*!< AF0: IR Alternate Function mapping */ #define GPIO_AF0_SPI1 ((uint8_t)0x00) /*!< AF0: SPI1/I2S1 Alternate Function mapping */ #define GPIO_AF0_SPI2 ((uint8_t)0x00) /*!< AF0: SPI2/I2S2 Alternate Function mapping */ #define GPIO_AF0_TIM1 ((uint8_t)0x00) /*!< AF0: TIM1 Alternate Function mapping */ #define GPIO_AF0_TIM3 ((uint8_t)0x00) /*!< AF0: TIM3 Alternate Function mapping */ #define GPIO_AF0_TIM14 ((uint8_t)0x00) /*!< AF0: TIM14 Alternate Function mapping */ #define GPIO_AF0_TIM15 ((uint8_t)0x00) /*!< AF0: TIM15 Alternate Function mapping */ #define GPIO_AF0_TIM16 ((uint8_t)0x00) /*!< AF0: TIM16 Alternate Function mapping */ #define GPIO_AF0_TIM17 ((uint8_t)0x00) /*!< AF0: TIM17 Alternate Function mapping */ #define GPIO_AF0_TSC ((uint8_t)0x00) /*!< AF0: TSC Alternate Function mapping */ #define GPIO_AF0_USART1 ((uint8_t)0x00) /*!< AF0: USART1 Alternate Function mapping */ #define GPIO_AF0_USART2 ((uint8_t)0x00) /*!< AF0: USART2 Alternate Function mapping */ #define GPIO_AF0_USART3 ((uint8_t)0x00) /*!< AF0: USART3 Alternate Function mapping */ #define GPIO_AF0_USART4 ((uint8_t)0x00) /*!< AF0: USART4 Alternate Function mapping */ /* AF 1 */ #define GPIO_AF1_TIM3 ((uint8_t)0x01) /*!< AF1: TIM3 Alternate Function mapping */ #define GPIO_AF1_TIM15 ((uint8_t)0x01) /*!< AF1: TIM15 Alternate Function mapping */ #define GPIO_AF1_USART1 ((uint8_t)0x01) /*!< AF1: USART1 Alternate Function mapping */ #define GPIO_AF1_USART2 ((uint8_t)0x01) /*!< AF1: USART2 Alternate Function mapping */ #define GPIO_AF1_USART3 ((uint8_t)0x01) /*!< AF1: USART3 Alternate Function mapping */ #define GPIO_AF1_IR ((uint8_t)0x01) /*!< AF1: IR Alternate Function mapping */ #define GPIO_AF1_CEC ((uint8_t)0x01) /*!< AF1: CEC Alternate Function mapping */ #define GPIO_AF1_EVENTOUT ((uint8_t)0x01) /*!< AF1: EVENTOUT Alternate Function mapping */ #define GPIO_AF1_I2C1 ((uint8_t)0x01) /*!< AF1: I2C1 Alternate Function mapping */ #define GPIO_AF1_I2C2 ((uint8_t)0x01) /*!< AF1: I2C2 Alternate Function mapping */ #define GPIO_AF1_TSC ((uint8_t)0x01) /*!< AF1: TSC Alternate Function mapping */ #define GPIO_AF1_SPI1 ((uint8_t)0x01) /*!< AF1: SPI1 Alternate Function mapping */ #define GPIO_AF1_SPI2 ((uint8_t)0x01) /*!< AF1: SPI2 Alternate Function mapping */ /* AF 2 */ #define GPIO_AF2_TIM1 ((uint8_t)0x02) /*!< AF2: TIM1 Alternate Function mapping */ #define GPIO_AF2_TIM2 ((uint8_t)0x02) /*!< AF2: TIM2 Alternate Function mapping */ #define GPIO_AF2_TIM16 ((uint8_t)0x02) /*!< AF2: TIM16 Alternate Function mapping */ #define GPIO_AF2_TIM17 ((uint8_t)0x02) /*!< AF2: TIM17 Alternate Function mapping */ #define GPIO_AF2_EVENTOUT ((uint8_t)0x02) /*!< AF2: EVENTOUT Alternate Function mapping */ /* AF 3 */ #define GPIO_AF3_EVENTOUT ((uint8_t)0x03) /*!< AF3: EVENTOUT Alternate Function mapping */ #define GPIO_AF3_TSC ((uint8_t)0x03) /*!< AF3: TSC Alternate Function mapping */ #define GPIO_AF3_TIM15 ((uint8_t)0x03) /*!< AF3: TIM15 Alternate Function mapping */ #define GPIO_AF3_I2C1 ((uint8_t)0x03) /*!< AF3: I2C1 Alternate Function mapping */ /* AF 4 */ #define GPIO_AF4_TIM14 ((uint8_t)0x04) /*!< AF4: TIM14 Alternate Function mapping */ #define GPIO_AF4_USART4 ((uint8_t)0x04) /*!< AF4: USART4 Alternate Function mapping */ #define GPIO_AF4_USART3 ((uint8_t)0x04) /*!< AF4: USART3 Alternate Function mapping */ #define GPIO_AF4_CRS ((uint8_t)0x04) /*!< AF4: CRS Alternate Function mapping */ /* AF 5 */ #define GPIO_AF5_TIM15 ((uint8_t)0x05) /*!< AF5: TIM15 Alternate Function mapping */ #define GPIO_AF5_TIM16 ((uint8_t)0x05) /*!< AF5: TIM16 Alternate Function mapping */ #define GPIO_AF5_TIM17 ((uint8_t)0x05) /*!< AF5: TIM17 Alternate Function mapping */ #define GPIO_AF5_SPI2 ((uint8_t)0x05) /*!< AF5: SPI2 Alternate Function mapping */ #define GPIO_AF5_I2C2 ((uint8_t)0x05) /*!< AF5: I2C2 Alternate Function mapping */ /* AF 6 */ #define GPIO_AF6_EVENTOUT ((uint8_t)0x06) /*!< AF6: EVENTOUT Alternate Function mapping */ /* AF 7 */ #define GPIO_AF7_COMP1 ((uint8_t)0x07) /*!< AF7: COMP1 Alternate Function mapping */ #define GPIO_AF7_COMP2 ((uint8_t)0x07) /*!< AF7: COMP2 Alternate Function mapping */ #define IS_GPIO_AF(AF) ((AF) <= (uint8_t)0x07) #endif /* STM32F071xB */ #if defined(STM32F091xC) || defined(STM32F098xx) /*--------------------------- STM32F091xC || STM32F098xx ------------------------------*/ /* AF 0 */ #define GPIO_AF0_EVENTOUT ((uint8_t)0x00) /*!< AF0: EVENTOUT Alternate Function mapping */ #define GPIO_AF0_SWDIO ((uint8_t)0x00) /*!< AF0: SWDIO Alternate Function mapping */ #define GPIO_AF0_SWCLK ((uint8_t)0x00) /*!< AF0: SWCLK Alternate Function mapping */ #define GPIO_AF0_MCO ((uint8_t)0x00) /*!< AF0: MCO Alternate Function mapping */ #define GPIO_AF0_CEC ((uint8_t)0x00) /*!< AF0: CEC Alternate Function mapping */ #define GPIO_AF0_CRS ((uint8_t)0x00) /*!< AF0: CRS Alternate Function mapping */ #define GPIO_AF0_IR ((uint8_t)0x00) /*!< AF0: IR Alternate Function mapping */ #define GPIO_AF0_SPI1 ((uint8_t)0x00) /*!< AF0: SPI1/I2S1 Alternate Function mapping */ #define GPIO_AF0_SPI2 ((uint8_t)0x00) /*!< AF0: SPI2/I2S2 Alternate Function mapping */ #define GPIO_AF0_TIM1 ((uint8_t)0x00) /*!< AF0: TIM1 Alternate Function mapping */ #define GPIO_AF0_TIM3 ((uint8_t)0x00) /*!< AF0: TIM3 Alternate Function mapping */ #define GPIO_AF0_TIM14 ((uint8_t)0x00) /*!< AF0: TIM14 Alternate Function mapping */ #define GPIO_AF0_TIM15 ((uint8_t)0x00) /*!< AF0: TIM15 Alternate Function mapping */ #define GPIO_AF0_TIM16 ((uint8_t)0x00) /*!< AF0: TIM16 Alternate Function mapping */ #define GPIO_AF0_TIM17 ((uint8_t)0x00) /*!< AF0: TIM17 Alternate Function mapping */ #define GPIO_AF0_TSC ((uint8_t)0x00) /*!< AF0: TSC Alternate Function mapping */ #define GPIO_AF0_USART1 ((uint8_t)0x00) /*!< AF0: USART1 Alternate Function mapping */ #define GPIO_AF0_USART2 ((uint8_t)0x00) /*!< AF0: USART2 Alternate Function mapping */ #define GPIO_AF0_USART3 ((uint8_t)0x00) /*!< AF0: USART3 Alternate Function mapping */ #define GPIO_AF0_USART4 ((uint8_t)0x00) /*!< AF0: USART4 Alternate Function mapping */ #define GPIO_AF0_USART8 ((uint8_t)0x00) /*!< AF0: USART8 Alternate Function mapping */ #define GPIO_AF0_CAN ((uint8_t)0x00) /*!< AF0: CAN Alternate Function mapping */ /* AF 1 */ #define GPIO_AF1_TIM3 ((uint8_t)0x01) /*!< AF1: TIM3 Alternate Function mapping */ #define GPIO_AF1_TIM15 ((uint8_t)0x01) /*!< AF1: TIM15 Alternate Function mapping */ #define GPIO_AF1_USART1 ((uint8_t)0x01) /*!< AF1: USART1 Alternate Function mapping */ #define GPIO_AF1_USART2 ((uint8_t)0x01) /*!< AF1: USART2 Alternate Function mapping */ #define GPIO_AF1_USART3 ((uint8_t)0x01) /*!< AF1: USART3 Alternate Function mapping */ #define GPIO_AF1_USART4 ((uint8_t)0x01) /*!< AF1: USART4 Alternate Function mapping */ #define GPIO_AF1_USART5 ((uint8_t)0x01) /*!< AF1: USART5 Alternate Function mapping */ #define GPIO_AF1_USART6 ((uint8_t)0x01) /*!< AF1: USART6 Alternate Function mapping */ #define GPIO_AF1_USART7 ((uint8_t)0x01) /*!< AF1: USART7 Alternate Function mapping */ #define GPIO_AF1_USART8 ((uint8_t)0x01) /*!< AF1: USART8 Alternate Function mapping */ #define GPIO_AF1_IR ((uint8_t)0x01) /*!< AF1: IR Alternate Function mapping */ #define GPIO_AF1_CEC ((uint8_t)0x01) /*!< AF1: CEC Alternate Function mapping */ #define GPIO_AF1_EVENTOUT ((uint8_t)0x01) /*!< AF1: EVENTOUT Alternate Function mapping */ #define GPIO_AF1_I2C1 ((uint8_t)0x01) /*!< AF1: I2C1 Alternate Function mapping */ #define GPIO_AF1_I2C2 ((uint8_t)0x01) /*!< AF1: I2C2 Alternate Function mapping */ #define GPIO_AF1_TSC ((uint8_t)0x01) /*!< AF1: TSC Alternate Function mapping */ #define GPIO_AF1_SPI1 ((uint8_t)0x01) /*!< AF1: SPI1 Alternate Function mapping */ #define GPIO_AF1_SPI2 ((uint8_t)0x01) /*!< AF1: SPI2 Alternate Function mapping */ /* AF 2 */ #define GPIO_AF2_TIM1 ((uint8_t)0x02) /*!< AF2: TIM1 Alternate Function mapping */ #define GPIO_AF2_TIM2 ((uint8_t)0x02) /*!< AF2: TIM2 Alternate Function mapping */ #define GPIO_AF2_TIM16 ((uint8_t)0x02) /*!< AF2: TIM16 Alternate Function mapping */ #define GPIO_AF2_TIM17 ((uint8_t)0x02) /*!< AF2: TIM17 Alternate Function mapping */ #define GPIO_AF2_EVENTOUT ((uint8_t)0x02) /*!< AF2: EVENTOUT Alternate Function mapping */ #define GPIO_AF2_USART5 ((uint8_t)0x02) /*!< AF2: USART5 Alternate Function mapping */ #define GPIO_AF2_USART6 ((uint8_t)0x02) /*!< AF2: USART6 Alternate Function mapping */ #define GPIO_AF2_USART7 ((uint8_t)0x02) /*!< AF2: USART7 Alternate Function mapping */ #define GPIO_AF2_USART8 ((uint8_t)0x02) /*!< AF2: USART8 Alternate Function mapping */ /* AF 3 */ #define GPIO_AF3_EVENTOUT ((uint8_t)0x03) /*!< AF3: EVENTOUT Alternate Function mapping */ #define GPIO_AF3_TSC ((uint8_t)0x03) /*!< AF3: TSC Alternate Function mapping */ #define GPIO_AF3_TIM15 ((uint8_t)0x03) /*!< AF3: TIM15 Alternate Function mapping */ #define GPIO_AF3_I2C1 ((uint8_t)0x03) /*!< AF3: I2C1 Alternate Function mapping */ /* AF 4 */ #define GPIO_AF4_TIM14 ((uint8_t)0x04) /*!< AF4: TIM14 Alternate Function mapping */ #define GPIO_AF4_USART4 ((uint8_t)0x04) /*!< AF4: USART4 Alternate Function mapping */ #define GPIO_AF4_USART3 ((uint8_t)0x04) /*!< AF4: USART3 Alternate Function mapping */ #define GPIO_AF4_CRS ((uint8_t)0x04) /*!< AF4: CRS Alternate Function mapping */ #define GPIO_AF4_CAN ((uint8_t)0x04) /*!< AF4: CAN Alternate Function mapping */ #define GPIO_AF4_I2C1 ((uint8_t)0x04) /*!< AF4: I2C1 Alternate Function mapping */ #define GPIO_AF4_USART5 ((uint8_t)0x04) /*!< AF4: USART5 Alternate Function mapping */ /* AF 5 */ #define GPIO_AF5_TIM15 ((uint8_t)0x05) /*!< AF5: TIM15 Alternate Function mapping */ #define GPIO_AF5_TIM16 ((uint8_t)0x05) /*!< AF5: TIM16 Alternate Function mapping */ #define GPIO_AF5_TIM17 ((uint8_t)0x05) /*!< AF5: TIM17 Alternate Function mapping */ #define GPIO_AF5_SPI2 ((uint8_t)0x05) /*!< AF5: SPI2 Alternate Function mapping */ #define GPIO_AF5_I2C2 ((uint8_t)0x05) /*!< AF5: I2C2 Alternate Function mapping */ #define GPIO_AF5_MCO ((uint8_t)0x05) /*!< AF5: MCO Alternate Function mapping */ #define GPIO_AF5_USART6 ((uint8_t)0x05) /*!< AF5: USART6 Alternate Function mapping */ /* AF 6 */ #define GPIO_AF6_EVENTOUT ((uint8_t)0x06) /*!< AF6: EVENTOUT Alternate Function mapping */ /* AF 7 */ #define GPIO_AF7_COMP1 ((uint8_t)0x07) /*!< AF7: COMP1 Alternate Function mapping */ #define GPIO_AF7_COMP2 ((uint8_t)0x07) /*!< AF7: COMP2 Alternate Function mapping */ #define IS_GPIO_AF(AF) ((AF) <= (uint8_t)0x07) #endif /* STM32F091xC || STM32F098xx */ #if defined(STM32F030xC) /*--------------------------- STM32F030xC ----------------------------------------------------*/ /* AF 0 */ #define GPIO_AF0_EVENTOUT ((uint8_t)0x00) /*!< AF0: EVENTOUT Alternate Function mapping */ #define GPIO_AF0_SWDIO ((uint8_t)0x00) /*!< AF0: SWDIO Alternate Function mapping */ #define GPIO_AF0_SWCLK ((uint8_t)0x00) /*!< AF0: SWCLK Alternate Function mapping */ #define GPIO_AF0_MCO ((uint8_t)0x00) /*!< AF0: MCO Alternate Function mapping */ #define GPIO_AF0_IR ((uint8_t)0x00) /*!< AF0: IR Alternate Function mapping */ #define GPIO_AF0_SPI1 ((uint8_t)0x00) /*!< AF0: SPI1 Alternate Function mapping */ #define GPIO_AF0_SPI2 ((uint8_t)0x00) /*!< AF0: SPI2 Alternate Function mapping */ #define GPIO_AF0_TIM3 ((uint8_t)0x00) /*!< AF0: TIM3 Alternate Function mapping */ #define GPIO_AF0_TIM14 ((uint8_t)0x00) /*!< AF0: TIM14 Alternate Function mapping */ #define GPIO_AF0_TIM15 ((uint8_t)0x00) /*!< AF0: TIM15 Alternate Function mapping */ #define GPIO_AF0_TIM17 ((uint8_t)0x00) /*!< AF0: TIM17 Alternate Function mapping */ #define GPIO_AF0_USART1 ((uint8_t)0x00) /*!< AF0: USART1 Alternate Function mapping */ #define GPIO_AF0_USART4 ((uint8_t)0x00) /*!< AF0: USART4 Alternate Function mapping */ /* AF 1 */ #define GPIO_AF1_TIM3 ((uint8_t)0x01) /*!< AF1: TIM3 Alternate Function mapping */ #define GPIO_AF1_TIM15 ((uint8_t)0x01) /*!< AF1: TIM15 Alternate Function mapping */ #define GPIO_AF1_USART1 ((uint8_t)0x01) /*!< AF1: USART1 Alternate Function mapping */ #define GPIO_AF1_USART2 ((uint8_t)0x01) /*!< AF1: USART2 Alternate Function mapping */ #define GPIO_AF1_USART3 ((uint8_t)0x01) /*!< AF1: USART3 Alternate Function mapping */ #define GPIO_AF1_IR ((uint8_t)0x01) /*!< AF1: IR Alternate Function mapping */ #define GPIO_AF1_EVENTOUT ((uint8_t)0x01) /*!< AF1: EVENTOUT Alternate Function mapping */ #define GPIO_AF1_I2C1 ((uint8_t)0x01) /*!< AF1: I2C1 Alternate Function mapping */ #define GPIO_AF1_I2C2 ((uint8_t)0x01) /*!< AF1: I2C2 Alternate Function mapping */ #define GPIO_AF1_SPI2 ((uint8_t)0x01) /*!< AF1: SPI2 Alternate Function mapping */ /* AF 2 */ #define GPIO_AF2_TIM1 ((uint8_t)0x02) /*!< AF2: TIM1 Alternate Function mapping */ #define GPIO_AF2_TIM16 ((uint8_t)0x02) /*!< AF2: TIM16 Alternate Function mapping */ #define GPIO_AF2_TIM17 ((uint8_t)0x02) /*!< AF2: TIM17 Alternate Function mapping */ #define GPIO_AF2_EVENTOUT ((uint8_t)0x02) /*!< AF2: EVENTOUT Alternate Function mapping */ #define GPIO_AF2_USART5 ((uint8_t)0x02) /*!< AF2: USART5 Alternate Function mapping */ #define GPIO_AF2_USART6 ((uint8_t)0x02) /*!< AF2: USART6 Alternate Function mapping */ /* AF 3 */ #define GPIO_AF3_EVENTOUT ((uint8_t)0x03) /*!< AF3: EVENTOUT Alternate Function mapping */ #define GPIO_AF3_TIM15 ((uint8_t)0x03) /*!< AF3: TIM15 Alternate Function mapping */ #define GPIO_AF3_I2C1 ((uint8_t)0x03) /*!< AF3: I2C1 Alternate Function mapping */ /* AF 4 */ #define GPIO_AF4_TIM14 ((uint8_t)0x04) /*!< AF4: TIM14 Alternate Function mapping */ #define GPIO_AF4_USART4 ((uint8_t)0x04) /*!< AF4: USART4 Alternate Function mapping */ #define GPIO_AF4_USART3 ((uint8_t)0x04) /*!< AF4: USART3 Alternate Function mapping */ #define GPIO_AF4_I2C1 ((uint8_t)0x04) /*!< AF4: I2C1 Alternate Function mapping */ #define GPIO_AF4_USART5 ((uint8_t)0x04) /*!< AF4: USART5 Alternate Function mapping */ /* AF 5 */ #define GPIO_AF5_TIM15 ((uint8_t)0x05) /*!< AF5: TIM15 Alternate Function mapping */ #define GPIO_AF5_TIM16 ((uint8_t)0x05) /*!< AF5: TIM16 Alternate Function mapping */ #define GPIO_AF5_TIM17 ((uint8_t)0x05) /*!< AF5: TIM17 Alternate Function mapping */ #define GPIO_AF5_SPI2 ((uint8_t)0x05) /*!< AF5: SPI2 Alternate Function mapping */ #define GPIO_AF5_I2C2 ((uint8_t)0x05) /*!< AF5: I2C2 Alternate Function mapping */ #define GPIO_AF5_MCO ((uint8_t)0x05) /*!< AF5: MCO Alternate Function mapping */ #define GPIO_AF5_USART6 ((uint8_t)0x05) /*!< AF5: USART6 Alternate Function mapping */ /* AF 6 */ #define GPIO_AF6_EVENTOUT ((uint8_t)0x06) /*!< AF6: EVENTOUT Alternate Function mapping */ #define IS_GPIO_AF(AF) ((AF) <= (uint8_t)0x06) #endif /* STM32F030xC */ #if defined (STM32F072xB) || defined (STM32F078xx) /*--------------------------- STM32F072xB/STM32F078xx ---------------------------*/ /* AF 0 */ #define GPIO_AF0_EVENTOUT ((uint8_t)0x00) /*!< AF0: EVENTOUT Alternate Function mapping */ #define GPIO_AF0_SWDIO ((uint8_t)0x00) /*!< AF0: SWDIO Alternate Function mapping */ #define GPIO_AF0_SWCLK ((uint8_t)0x00) /*!< AF0: SWCLK Alternate Function mapping */ #define GPIO_AF0_MCO ((uint8_t)0x00) /*!< AF0: MCO Alternate Function mapping */ #define GPIO_AF0_CEC ((uint8_t)0x00) /*!< AF0: CEC Alternate Function mapping */ #define GPIO_AF0_CRS ((uint8_t)0x00) /*!< AF0: CRS Alternate Function mapping */ #define GPIO_AF0_IR ((uint8_t)0x00) /*!< AF0: IR Alternate Function mapping */ #define GPIO_AF0_SPI1 ((uint8_t)0x00) /*!< AF0: SPI1/I2S1 Alternate Function mapping */ #define GPIO_AF0_SPI2 ((uint8_t)0x00) /*!< AF0: SPI2/I2S2 Alternate Function mapping */ #define GPIO_AF0_TIM1 ((uint8_t)0x00) /*!< AF0: TIM1 Alternate Function mapping */ #define GPIO_AF0_TIM3 ((uint8_t)0x00) /*!< AF0: TIM3 Alternate Function mapping */ #define GPIO_AF0_TIM14 ((uint8_t)0x00) /*!< AF0: TIM14 Alternate Function mapping */ #define GPIO_AF0_TIM15 ((uint8_t)0x00) /*!< AF0: TIM15 Alternate Function mapping */ #define GPIO_AF0_TIM16 ((uint8_t)0x00) /*!< AF0: TIM16 Alternate Function mapping */ #define GPIO_AF0_TIM17 ((uint8_t)0x00) /*!< AF0: TIM17 Alternate Function mapping */ #define GPIO_AF0_TSC ((uint8_t)0x00) /*!< AF0: TSC Alternate Function mapping */ #define GPIO_AF0_USART1 ((uint8_t)0x00) /*!< AF0: USART1 Alternate Function mapping */ #define GPIO_AF0_USART2 ((uint8_t)0x00) /*!< AF0: USART2 Alternate Function mapping */ #define GPIO_AF0_USART3 ((uint8_t)0x00) /*!< AF0: USART2 Alternate Function mapping */ #define GPIO_AF0_USART4 ((uint8_t)0x00) /*!< AF0: USART4 Alternate Function mapping */ #define GPIO_AF0_CAN ((uint8_t)0x00) /*!< AF0: CAN Alternate Function mapping */ /* AF 1 */ #define GPIO_AF1_TIM3 ((uint8_t)0x01) /*!< AF1: TIM3 Alternate Function mapping */ #define GPIO_AF1_TIM15 ((uint8_t)0x01) /*!< AF1: TIM15 Alternate Function mapping */ #define GPIO_AF1_USART1 ((uint8_t)0x01) /*!< AF1: USART1 Alternate Function mapping */ #define GPIO_AF1_USART2 ((uint8_t)0x01) /*!< AF1: USART2 Alternate Function mapping */ #define GPIO_AF1_USART3 ((uint8_t)0x01) /*!< AF1: USART3 Alternate Function mapping */ #define GPIO_AF1_IR ((uint8_t)0x01) /*!< AF1: IR Alternate Function mapping */ #define GPIO_AF1_CEC ((uint8_t)0x01) /*!< AF1: CEC Alternate Function mapping */ #define GPIO_AF1_EVENTOUT ((uint8_t)0x01) /*!< AF1: EVENTOUT Alternate Function mapping */ #define GPIO_AF1_I2C1 ((uint8_t)0x01) /*!< AF1: I2C1 Alternate Function mapping */ #define GPIO_AF1_I2C2 ((uint8_t)0x01) /*!< AF1: I2C1 Alternate Function mapping */ #define GPIO_AF1_TSC ((uint8_t)0x01) /*!< AF1: I2C1 Alternate Function mapping */ #define GPIO_AF1_SPI1 ((uint8_t)0x01) /*!< AF1: SPI1 Alternate Function mapping */ #define GPIO_AF1_SPI2 ((uint8_t)0x01) /*!< AF1: SPI2 Alternate Function mapping */ /* AF 2 */ #define GPIO_AF2_TIM1 ((uint8_t)0x02) /*!< AF2: TIM1 Alternate Function mapping */ #define GPIO_AF2_TIM2 ((uint8_t)0x02) /*!< AF2: TIM2 Alternate Function mapping */ #define GPIO_AF2_TIM16 ((uint8_t)0x02) /*!< AF2: TIM16 Alternate Function mapping */ #define GPIO_AF2_TIM17 ((uint8_t)0x02) /*!< AF2: TIM17 Alternate Function mapping */ #define GPIO_AF2_EVENTOUT ((uint8_t)0x02) /*!< AF2: EVENTOUT Alternate Function mapping */ #define GPIO_AF2_USB ((uint8_t)0x02) /*!< AF2: USB Alternate Function mapping */ /* AF 3 */ #define GPIO_AF3_EVENTOUT ((uint8_t)0x03) /*!< AF3: EVENTOUT Alternate Function mapping */ #define GPIO_AF3_TSC ((uint8_t)0x03) /*!< AF3: TSC Alternate Function mapping */ #define GPIO_AF3_TIM15 ((uint8_t)0x03) /*!< AF3: TIM15 Alternate Function mapping */ #define GPIO_AF3_I2C1 ((uint8_t)0x03) /*!< AF3: I2C1 Alternate Function mapping */ /* AF 4 */ #define GPIO_AF4_TIM14 ((uint8_t)0x04) /*!< AF4: TIM14 Alternate Function mapping */ #define GPIO_AF4_USART4 ((uint8_t)0x04) /*!< AF4: USART4 Alternate Function mapping */ #define GPIO_AF4_USART3 ((uint8_t)0x04) /*!< AF4: USART3 Alternate Function mapping */ #define GPIO_AF4_CRS ((uint8_t)0x04) /*!< AF4: CRS Alternate Function mapping */ #define GPIO_AF4_CAN ((uint8_t)0x04) /*!< AF4: CAN Alternate Function mapping */ /* AF 5 */ #define GPIO_AF5_TIM15 ((uint8_t)0x05) /*!< AF5: TIM15 Alternate Function mapping */ #define GPIO_AF5_TIM16 ((uint8_t)0x05) /*!< AF5: TIM16 Alternate Function mapping */ #define GPIO_AF5_TIM17 ((uint8_t)0x05) /*!< AF5: TIM17 Alternate Function mapping */ #define GPIO_AF5_SPI2 ((uint8_t)0x05) /*!< AF5: SPI2 Alternate Function mapping */ #define GPIO_AF5_I2C2 ((uint8_t)0x05) /*!< AF5: I2C2 Alternate Function mapping */ /* AF 6 */ #define GPIO_AF6_EVENTOUT ((uint8_t)0x06) /*!< AF6: EVENTOUT Alternate Function mapping */ /* AF 7 */ #define GPIO_AF7_COMP1 ((uint8_t)0x07) /*!< AF7: COMP1 Alternate Function mapping */ #define GPIO_AF7_COMP2 ((uint8_t)0x07) /*!< AF7: COMP2 Alternate Function mapping */ #define IS_GPIO_AF(AF) ((AF) <= (uint8_t)0x07) #endif /* STM32F072xB || STM32F078xx */ #if defined (STM32F070xB) /*---------------------------------- STM32F070xB ---------------------------------------------*/ /* AF 0 */ #define GPIO_AF0_EVENTOUT ((uint8_t)0x00) /*!< AF0: EVENTOUT Alternate Function mapping */ #define GPIO_AF0_SWDIO ((uint8_t)0x00) /*!< AF0: SWDIO Alternate Function mapping */ #define GPIO_AF0_SWCLK ((uint8_t)0x00) /*!< AF0: SWCLK Alternate Function mapping */ #define GPIO_AF0_MCO ((uint8_t)0x00) /*!< AF0: MCO Alternate Function mapping */ #define GPIO_AF0_IR ((uint8_t)0x00) /*!< AF0: IR Alternate Function mapping */ #define GPIO_AF0_SPI1 ((uint8_t)0x00) /*!< AF0: SPI1 Alternate Function mapping */ #define GPIO_AF0_SPI2 ((uint8_t)0x00) /*!< AF0: SPI2 Alternate Function mapping */ #define GPIO_AF0_TIM3 ((uint8_t)0x00) /*!< AF0: TIM3 Alternate Function mapping */ #define GPIO_AF0_TIM14 ((uint8_t)0x00) /*!< AF0: TIM14 Alternate Function mapping */ #define GPIO_AF0_TIM15 ((uint8_t)0x00) /*!< AF0: TIM15 Alternate Function mapping */ #define GPIO_AF0_TIM17 ((uint8_t)0x00) /*!< AF0: TIM17 Alternate Function mapping */ #define GPIO_AF0_USART1 ((uint8_t)0x00) /*!< AF0: USART1 Alternate Function mapping */ #define GPIO_AF0_USART4 ((uint8_t)0x00) /*!< AF0: USART4 Alternate Function mapping */ /* AF 1 */ #define GPIO_AF1_TIM3 ((uint8_t)0x01) /*!< AF1: TIM3 Alternate Function mapping */ #define GPIO_AF1_TIM15 ((uint8_t)0x01) /*!< AF1: TIM15 Alternate Function mapping */ #define GPIO_AF1_USART1 ((uint8_t)0x01) /*!< AF1: USART1 Alternate Function mapping */ #define GPIO_AF1_USART2 ((uint8_t)0x01) /*!< AF1: USART2 Alternate Function mapping */ #define GPIO_AF1_USART3 ((uint8_t)0x01) /*!< AF1: USART4 Alternate Function mapping */ #define GPIO_AF1_IR ((uint8_t)0x01) /*!< AF1: IR Alternate Function mapping */ #define GPIO_AF1_EVENTOUT ((uint8_t)0x01) /*!< AF1: EVENTOUT Alternate Function mapping */ #define GPIO_AF1_I2C1 ((uint8_t)0x01) /*!< AF1: I2C1 Alternate Function mapping */ #define GPIO_AF1_I2C2 ((uint8_t)0x01) /*!< AF1: I2C1 Alternate Function mapping */ #define GPIO_AF1_SPI2 ((uint8_t)0x01) /*!< AF1: SPI2 Alternate Function mapping */ /* AF 2 */ #define GPIO_AF2_TIM1 ((uint8_t)0x02) /*!< AF2: TIM1 Alternate Function mapping */ #define GPIO_AF2_TIM16 ((uint8_t)0x02) /*!< AF2: TIM16 Alternate Function mapping */ #define GPIO_AF2_TIM17 ((uint8_t)0x02) /*!< AF2: TIM17 Alternate Function mapping */ #define GPIO_AF2_EVENTOUT ((uint8_t)0x02) /*!< AF2: EVENTOUT Alternate Function mapping */ #define GPIO_AF2_USB ((uint8_t)0x02) /*!< AF2: USB Alternate Function mapping */ /* AF 3 */ #define GPIO_AF3_EVENTOUT ((uint8_t)0x03) /*!< AF3: EVENTOUT Alternate Function mapping */ #define GPIO_AF3_I2C1 ((uint8_t)0x03) /*!< AF3: I2C1 Alternate Function mapping */ #define GPIO_AF3_TIM15 ((uint8_t)0x03) /*!< AF3: TIM15 Alternate Function mapping */ /* AF 4 */ #define GPIO_AF4_TIM14 ((uint8_t)0x04) /*!< AF4: TIM14 Alternate Function mapping */ #define GPIO_AF4_USART4 ((uint8_t)0x04) /*!< AF4: USART4 Alternate Function mapping */ #define GPIO_AF4_USART3 ((uint8_t)0x04) /*!< AF4: USART3 Alternate Function mapping */ /* AF 5 */ #define GPIO_AF5_TIM15 ((uint8_t)0x05) /*!< AF5: TIM15 Alternate Function mapping */ #define GPIO_AF5_TIM16 ((uint8_t)0x05) /*!< AF5: TIM16 Alternate Function mapping */ #define GPIO_AF5_TIM17 ((uint8_t)0x05) /*!< AF5: TIM17 Alternate Function mapping */ #define GPIO_AF5_SPI2 ((uint8_t)0x05) /*!< AF5: SPI2 Alternate Function mapping */ #define GPIO_AF5_I2C2 ((uint8_t)0x05) /*!< AF5: I2C2 Alternate Function mapping */ /* AF 6 */ #define GPIO_AF6_EVENTOUT ((uint8_t)0x06) /*!< AF6: EVENTOUT Alternate Function mapping */ #define IS_GPIO_AF(AF) ((AF) <= (uint8_t)0x06) #endif /* STM32F070xB */ #if defined (STM32F042x6) || defined (STM32F048xx) /*--------------------------- STM32F042x6/STM32F048xx ---------------------------*/ /* AF 0 */ #define GPIO_AF0_EVENTOUT ((uint8_t)0x00) /*!< AF0: EVENTOUT Alternate Function mapping */ #define GPIO_AF0_CEC ((uint8_t)0x00) /*!< AF0: CEC Alternate Function mapping */ #define GPIO_AF0_CRS ((uint8_t)0x00) /*!< AF0: CRS Alternate Function mapping */ #define GPIO_AF0_IR ((uint8_t)0x00) /*!< AF0: IR Alternate Function mapping */ #define GPIO_AF0_MCO ((uint8_t)0x00) /*!< AF0: MCO Alternate Function mapping */ #define GPIO_AF0_SPI1 ((uint8_t)0x00) /*!< AF0: SPI1/I2S1 Alternate Function mapping */ #define GPIO_AF0_SPI2 ((uint8_t)0x00) /*!< AF0: SPI2/I2S2 Alternate Function mapping */ #define GPIO_AF0_SWDIO ((uint8_t)0x00) /*!< AF0: SWDIO Alternate Function mapping */ #define GPIO_AF0_SWCLK ((uint8_t)0x00) /*!< AF0: SWCLK Alternate Function mapping */ #define GPIO_AF0_TIM14 ((uint8_t)0x00) /*!< AF0: TIM14 Alternate Function mapping */ #define GPIO_AF0_TIM17 ((uint8_t)0x00) /*!< AF0: TIM17 Alternate Function mapping */ #define GPIO_AF0_USART1 ((uint8_t)0x00) /*!< AF0: USART1 Alternate Function mapping */ /* AF 1 */ #define GPIO_AF1_CEC ((uint8_t)0x01) /*!< AF1: CEC Alternate Function mapping */ #define GPIO_AF1_EVENTOUT ((uint8_t)0x01) /*!< AF1: EVENTOUT Alternate Function mapping */ #define GPIO_AF1_I2C1 ((uint8_t)0x01) /*!< AF1: I2C1 Alternate Function mapping */ #define GPIO_AF1_IR ((uint8_t)0x01) /*!< AF1: IR Alternate Function mapping */ #define GPIO_AF1_USART1 ((uint8_t)0x01) /*!< AF1: USART1 Alternate Function mapping */ #define GPIO_AF1_USART2 ((uint8_t)0x01) /*!< AF1: USART2 Alternate Function mapping */ #define GPIO_AF1_TIM3 ((uint8_t)0x01) /*!< AF1: TIM3 Alternate Function mapping */ /* AF 2 */ #define GPIO_AF2_EVENTOUT ((uint8_t)0x02) /*!< AF2: EVENTOUT Alternate Function mapping */ #define GPIO_AF2_TIM1 ((uint8_t)0x02) /*!< AF2: TIM1 Alternate Function mapping */ #define GPIO_AF2_TIM2 ((uint8_t)0x02) /*!< AF2: TIM2 Alternate Function mapping */ #define GPIO_AF2_TIM16 ((uint8_t)0x02) /*!< AF2: TIM16 Alternate Function mapping */ #define GPIO_AF2_TIM17 ((uint8_t)0x02) /*!< AF2: TIM17 Alternate Function mapping */ #define GPIO_AF2_USB ((uint8_t)0x02) /*!< AF2: USB Alternate Function mapping */ /* AF 3 */ #define GPIO_AF3_EVENTOUT ((uint8_t)0x03) /*!< AF3: EVENTOUT Alternate Function mapping */ #define GPIO_AF3_I2C1 ((uint8_t)0x03) /*!< AF3: I2C1 Alternate Function mapping */ #define GPIO_AF3_TSC ((uint8_t)0x03) /*!< AF3: TSC Alternate Function mapping */ /* AF 4 */ #define GPIO_AF4_TIM14 ((uint8_t)0x04) /*!< AF4: TIM14 Alternate Function mapping */ #define GPIO_AF4_CAN ((uint8_t)0x04) /*!< AF4: CAN Alternate Function mapping */ #define GPIO_AF4_CRS ((uint8_t)0x04) /*!< AF4: CRS Alternate Function mapping */ #define GPIO_AF4_I2C1 ((uint8_t)0x04) /*!< AF4: I2C1 Alternate Function mapping */ /* AF 5 */ #define GPIO_AF5_MCO ((uint8_t)0x05) /*!< AF5: MCO Alternate Function mapping */ #define GPIO_AF5_I2C1 ((uint8_t)0x05) /*!< AF5: I2C1 Alternate Function mapping */ #define GPIO_AF5_I2C2 ((uint8_t)0x05) /*!< AF5: I2C2 Alternate Function mapping */ #define GPIO_AF5_SPI2 ((uint8_t)0x05) /*!< AF5: SPI2 Alternate Function mapping */ #define GPIO_AF5_TIM16 ((uint8_t)0x05) /*!< AF5: TIM16 Alternate Function mapping */ #define GPIO_AF5_TIM17 ((uint8_t)0x05) /*!< AF5: TIM17 Alternate Function mapping */ #define GPIO_AF5_USB ((uint8_t)0x05) /*!< AF5: USB Alternate Function mapping */ /* AF 6 */ #define GPIO_AF6_EVENTOUT ((uint8_t)0x06) /*!< AF6: EVENTOUT Alternate Function mapping */ #define IS_GPIO_AF(AF) ((AF) <= (uint8_t)0x06) #endif /* STM32F042x6 || STM32F048xx */ #if defined (STM32F070x6) /*--------------------------------------- STM32F070x6 ----------------------------------------*/ /* AF 0 */ #define GPIO_AF0_EVENTOUT ((uint8_t)0x00) /*!< AF0: EVENTOUT Alternate Function mapping */ #define GPIO_AF0_IR ((uint8_t)0x00) /*!< AF0: IR Alternate Function mapping */ #define GPIO_AF0_MCO ((uint8_t)0x00) /*!< AF0: MCO Alternate Function mapping */ #define GPIO_AF0_SPI1 ((uint8_t)0x00) /*!< AF0: SPI1 Alternate Function mapping */ #define GPIO_AF0_SWDIO ((uint8_t)0x00) /*!< AF0: SWDIO Alternate Function mapping */ #define GPIO_AF0_SWCLK ((uint8_t)0x00) /*!< AF0: SWCLK Alternate Function mapping */ #define GPIO_AF0_TIM14 ((uint8_t)0x00) /*!< AF0: TIM14 Alternate Function mapping */ #define GPIO_AF0_TIM17 ((uint8_t)0x00) /*!< AF0: TIM17 Alternate Function mapping */ #define GPIO_AF0_USART1 ((uint8_t)0x00) /*!< AF0: USART1 Alternate Function mapping */ /* AF 1 */ #define GPIO_AF1_EVENTOUT ((uint8_t)0x01) /*!< AF1: EVENTOUT Alternate Function mapping */ #define GPIO_AF1_I2C1 ((uint8_t)0x01) /*!< AF1: I2C1 Alternate Function mapping */ #define GPIO_AF1_IR ((uint8_t)0x01) /*!< AF1: IR Alternate Function mapping */ #define GPIO_AF1_USART1 ((uint8_t)0x01) /*!< AF1: USART1 Alternate Function mapping */ #define GPIO_AF1_USART2 ((uint8_t)0x01) /*!< AF1: USART2 Alternate Function mapping */ #define GPIO_AF1_TIM3 ((uint8_t)0x01) /*!< AF1: TIM3 Alternate Function mapping */ /* AF 2 */ #define GPIO_AF2_EVENTOUT ((uint8_t)0x02) /*!< AF2: EVENTOUT Alternate Function mapping */ #define GPIO_AF2_TIM1 ((uint8_t)0x02) /*!< AF2: TIM1 Alternate Function mapping */ #define GPIO_AF2_TIM16 ((uint8_t)0x02) /*!< AF2: TIM16 Alternate Function mapping */ #define GPIO_AF2_TIM17 ((uint8_t)0x02) /*!< AF2: TIM17 Alternate Function mapping */ #define GPIO_AF2_USB ((uint8_t)0x02) /*!< AF2: USB Alternate Function mapping */ /* AF 3 */ #define GPIO_AF3_EVENTOUT ((uint8_t)0x03) /*!< AF3: EVENTOUT Alternate Function mapping */ #define GPIO_AF3_I2C1 ((uint8_t)0x03) /*!< AF3: I2C1 Alternate Function mapping */ /* AF 4 */ #define GPIO_AF4_TIM14 ((uint8_t)0x04) /*!< AF4: TIM14 Alternate Function mapping */ #define GPIO_AF4_I2C1 ((uint8_t)0x04) /*!< AF4: I2C1 Alternate Function mapping */ /* AF 5 */ #define GPIO_AF5_MCO ((uint8_t)0x05) /*!< AF5: MCO Alternate Function mapping */ #define GPIO_AF5_I2C1 ((uint8_t)0x05) /*!< AF5: I2C1 Alternate Function mapping */ #define GPIO_AF5_TIM16 ((uint8_t)0x05) /*!< AF5: TIM16 Alternate Function mapping */ #define GPIO_AF5_TIM17 ((uint8_t)0x05) /*!< AF5: TIM17 Alternate Function mapping */ #define GPIO_AF5_USB ((uint8_t)0x05) /*!< AF5: USB Alternate Function mapping */ /* AF 6 */ #define GPIO_AF6_EVENTOUT ((uint8_t)0x06) /*!< AF6: EVENTOUT Alternate Function mapping */ #define IS_GPIO_AF(AF) ((AF) <= (uint8_t)0x06) #endif /* STM32F070x6 */ /** * @} */ /** * @} */ /* Exported macro ------------------------------------------------------------*/ /** @defgroup GPIOEx_Exported_Macros GPIOEx Exported Macros * @{ */ /** @defgroup GPIOEx_Get_Port_Index GPIOEx_Get Port Index * @{ */ #if defined (STM32F071xB) || defined (STM32F072xB) || defined (STM32F078xx) || \ defined (STM32F091xC) || defined (STM32F098xx) #define GPIO_GET_INDEX(__GPIOx__) (((__GPIOx__) == (GPIOA))? 0U :\ ((__GPIOx__) == (GPIOB))? 1U :\ ((__GPIOx__) == (GPIOC))? 2U :\ ((__GPIOx__) == (GPIOD))? 3U :\ ((__GPIOx__) == (GPIOE))? 4U : 5U) #endif #if defined (STM32F030x6) || defined (STM32F030x8) || defined (STM32F070xB) || defined (STM32F030xC) || \ defined (STM32F051x8) || defined (STM32F058xx) #define GPIO_GET_INDEX(__GPIOx__) (((__GPIOx__) == (GPIOA))? 0U :\ ((__GPIOx__) == (GPIOB))? 1U :\ ((__GPIOx__) == (GPIOC))? 2U :\ ((__GPIOx__) == (GPIOD))? 3U : 5U) #endif #if defined (STM32F031x6) || defined (STM32F038xx) || \ defined (STM32F042x6) || defined (STM32F048xx) || defined (STM32F070x6) #define GPIO_GET_INDEX(__GPIOx__) (((__GPIOx__) == (GPIOA))? 0U :\ ((__GPIOx__) == (GPIOB))? 1U :\ ((__GPIOx__) == (GPIOC))? 2U : 5U) #endif /** * @} */ /** * @} */ /* Exported functions --------------------------------------------------------*/ /** * @} */ /** * @} */ #ifdef __cplusplus } #endif #endif /* __STM32F0xx_HAL_GPIO_EX_H */ /************************ (C) COPYRIGHT STMicroelectronics *****END OF FILE****/ ================================================ FILE: Zelig/mbed/TARGET_NUCLEO_F091RC/stm32f0xx_hal_i2c.h ================================================ /** ****************************************************************************** * @file stm32f0xx_hal_i2c.h * @author MCD Application Team * @version V1.3.0 * @date 26-June-2015 * @brief Header file of I2C HAL module. ****************************************************************************** * @attention * *

© COPYRIGHT(c) 2015 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. * ****************************************************************************** */ /* Define to prevent recursive inclusion -------------------------------------*/ #ifndef __STM32F0xx_HAL_I2C_H #define __STM32F0xx_HAL_I2C_H #ifdef __cplusplus extern "C" { #endif /* Includes ------------------------------------------------------------------*/ #include "stm32f0xx_hal_def.h" /** @addtogroup STM32F0xx_HAL_Driver * @{ */ /** @addtogroup I2C * @{ */ /* Exported types ------------------------------------------------------------*/ /** @defgroup I2C_Exported_Types I2C Exported Types * @{ */ /** @defgroup I2C_Configuration_Structure_definition I2C Configuration Structure definition * @brief I2C Configuration Structure definition * @{ */ typedef struct { uint32_t Timing; /*!< Specifies the I2C_TIMINGR_register value. This parameter calculated by referring to I2C initialization section in Reference manual */ uint32_t OwnAddress1; /*!< Specifies the first device own address. This parameter can be a 7-bit or 10-bit address. */ uint32_t AddressingMode; /*!< Specifies if 7-bit or 10-bit addressing mode is selected. This parameter can be a value of @ref I2C_addressing_mode */ uint32_t DualAddressMode; /*!< Specifies if dual addressing mode is selected. This parameter can be a value of @ref I2C_dual_addressing_mode */ uint32_t OwnAddress2; /*!< Specifies the second device own address if dual addressing mode is selected This parameter can be a 7-bit address. */ uint32_t OwnAddress2Masks; /*!< Specifies the acknowledge mask address second device own address if dual addressing mode is selected This parameter can be a value of @ref I2C_own_address2_masks */ uint32_t GeneralCallMode; /*!< Specifies if general call mode is selected. This parameter can be a value of @ref I2C_general_call_addressing_mode */ uint32_t NoStretchMode; /*!< Specifies if nostretch mode is selected. This parameter can be a value of @ref I2C_nostretch_mode */ }I2C_InitTypeDef; /** * @} */ /** @defgroup HAL_state_structure_definition HAL state structure definition * @brief HAL State structure definition * @{ */ typedef enum { HAL_I2C_STATE_RESET = 0x00, /*!< I2C not yet initialized or disabled */ HAL_I2C_STATE_READY = 0x01, /*!< I2C initialized and ready for use */ HAL_I2C_STATE_BUSY = 0x02, /*!< I2C internal process is ongoing */ HAL_I2C_STATE_MASTER_BUSY_TX = 0x12, /*!< Master Data Transmission process is ongoing */ HAL_I2C_STATE_MASTER_BUSY_RX = 0x22, /*!< Master Data Reception process is ongoing */ HAL_I2C_STATE_SLAVE_BUSY_TX = 0x32, /*!< Slave Data Transmission process is ongoing */ HAL_I2C_STATE_SLAVE_BUSY_RX = 0x42, /*!< Slave Data Reception process is ongoing */ HAL_I2C_STATE_MEM_BUSY_TX = 0x52, /*!< Memory Data Transmission process is ongoing */ HAL_I2C_STATE_MEM_BUSY_RX = 0x62, /*!< Memory Data Reception process is ongoing */ HAL_I2C_STATE_TIMEOUT = 0x03, /*!< Timeout state */ HAL_I2C_STATE_ERROR = 0x04 /*!< Reception process is ongoing */ }HAL_I2C_StateTypeDef; /** * @} */ /** @defgroup I2C_Error_Code_definition I2C Error Code definition * @brief I2C Error Code definition * @{ */ #define HAL_I2C_ERROR_NONE ((uint32_t)0x00000000) /*!< No error */ #define HAL_I2C_ERROR_BERR ((uint32_t)0x00000001) /*!< BERR error */ #define HAL_I2C_ERROR_ARLO ((uint32_t)0x00000002) /*!< ARLO error */ #define HAL_I2C_ERROR_AF ((uint32_t)0x00000004) /*!< ACKF error */ #define HAL_I2C_ERROR_OVR ((uint32_t)0x00000008) /*!< OVR error */ #define HAL_I2C_ERROR_DMA ((uint32_t)0x00000010) /*!< DMA transfer error */ #define HAL_I2C_ERROR_TIMEOUT ((uint32_t)0x00000020) /*!< Timeout error */ #define HAL_I2C_ERROR_SIZE ((uint32_t)0x00000040) /*!< Size Management error */ /** * @} */ /** @defgroup I2C_handle_Structure_definition I2C handle Structure definition * @brief I2C handle Structure definition * @{ */ typedef struct { I2C_TypeDef *Instance; /*!< I2C registers base address */ I2C_InitTypeDef Init; /*!< I2C communication parameters */ uint8_t *pBuffPtr; /*!< Pointer to I2C transfer buffer */ uint16_t XferSize; /*!< I2C transfer size */ __IO uint16_t XferCount; /*!< I2C transfer counter */ DMA_HandleTypeDef *hdmatx; /*!< I2C Tx DMA handle parameters */ DMA_HandleTypeDef *hdmarx; /*!< I2C Rx DMA handle parameters */ HAL_LockTypeDef Lock; /*!< I2C locking object */ __IO HAL_I2C_StateTypeDef State; /*!< I2C communication state */ __IO uint32_t ErrorCode; /*!< I2C Error code */ }I2C_HandleTypeDef; /** * @} */ /** * @} */ /* Exported constants --------------------------------------------------------*/ /** @defgroup I2C_Exported_Constants I2C Exported Constants * @{ */ /** @defgroup I2C_addressing_mode I2C addressing mode * @{ */ #define I2C_ADDRESSINGMODE_7BIT ((uint32_t)0x00000001) #define I2C_ADDRESSINGMODE_10BIT ((uint32_t)0x00000002) /** * @} */ /** @defgroup I2C_dual_addressing_mode I2C dual addressing mode * @{ */ #define I2C_DUALADDRESS_DISABLE ((uint32_t)0x00000000) #define I2C_DUALADDRESS_ENABLE I2C_OAR2_OA2EN /** * @} */ /** @defgroup I2C_own_address2_masks I2C own address2 masks * @{ */ #define I2C_OA2_NOMASK ((uint8_t)0x00) #define I2C_OA2_MASK01 ((uint8_t)0x01) #define I2C_OA2_MASK02 ((uint8_t)0x02) #define I2C_OA2_MASK03 ((uint8_t)0x03) #define I2C_OA2_MASK04 ((uint8_t)0x04) #define I2C_OA2_MASK05 ((uint8_t)0x05) #define I2C_OA2_MASK06 ((uint8_t)0x06) #define I2C_OA2_MASK07 ((uint8_t)0x07) /** * @} */ /** @defgroup I2C_general_call_addressing_mode I2C general call addressing mode * @{ */ #define I2C_GENERALCALL_DISABLE ((uint32_t)0x00000000) #define I2C_GENERALCALL_ENABLE I2C_CR1_GCEN /** * @} */ /** @defgroup I2C_nostretch_mode I2C nostretch mode * @{ */ #define I2C_NOSTRETCH_DISABLE ((uint32_t)0x00000000) #define I2C_NOSTRETCH_ENABLE I2C_CR1_NOSTRETCH /** * @} */ /** @defgroup I2C_Memory_Address_Size I2C Memory Address Size * @{ */ #define I2C_MEMADD_SIZE_8BIT ((uint32_t)0x00000001) #define I2C_MEMADD_SIZE_16BIT ((uint32_t)0x00000002) /** * @} */ /** @defgroup I2C_ReloadEndMode_definition I2C ReloadEndMode definition * @{ */ #define I2C_RELOAD_MODE I2C_CR2_RELOAD #define I2C_AUTOEND_MODE I2C_CR2_AUTOEND #define I2C_SOFTEND_MODE ((uint32_t)0x00000000) /** * @} */ /** @defgroup I2C_StartStopMode_definition I2C StartStopMode definition * @{ */ #define I2C_NO_STARTSTOP ((uint32_t)0x00000000) #define I2C_GENERATE_STOP I2C_CR2_STOP #define I2C_GENERATE_START_READ (uint32_t)(I2C_CR2_START | I2C_CR2_RD_WRN) #define I2C_GENERATE_START_WRITE I2C_CR2_START /** * @} */ /** @defgroup I2C_Interrupt_configuration_definition I2C Interrupt configuration definition * @brief I2C Interrupt definition * Elements values convention: 0xXXXXXXXX * - XXXXXXXX : Interrupt control mask * @{ */ #define I2C_IT_ERRI I2C_CR1_ERRIE #define I2C_IT_TCI I2C_CR1_TCIE #define I2C_IT_STOPI I2C_CR1_STOPIE #define I2C_IT_NACKI I2C_CR1_NACKIE #define I2C_IT_ADDRI I2C_CR1_ADDRIE #define I2C_IT_RXI I2C_CR1_RXIE #define I2C_IT_TXI I2C_CR1_TXIE /** * @} */ /** @defgroup I2C_Flag_definition I2C Flag definition * @{ */ #define I2C_FLAG_TXE I2C_ISR_TXE #define I2C_FLAG_TXIS I2C_ISR_TXIS #define I2C_FLAG_RXNE I2C_ISR_RXNE #define I2C_FLAG_ADDR I2C_ISR_ADDR #define I2C_FLAG_AF I2C_ISR_NACKF #define I2C_FLAG_STOPF I2C_ISR_STOPF #define I2C_FLAG_TC I2C_ISR_TC #define I2C_FLAG_TCR I2C_ISR_TCR #define I2C_FLAG_BERR I2C_ISR_BERR #define I2C_FLAG_ARLO I2C_ISR_ARLO #define I2C_FLAG_OVR I2C_ISR_OVR #define I2C_FLAG_PECERR I2C_ISR_PECERR #define I2C_FLAG_TIMEOUT I2C_ISR_TIMEOUT #define I2C_FLAG_ALERT I2C_ISR_ALERT #define I2C_FLAG_BUSY I2C_ISR_BUSY #define I2C_FLAG_DIR I2C_ISR_DIR /** * @} */ /** * @} */ /* Exported macros -----------------------------------------------------------*/ /** @defgroup I2C_Exported_Macros I2C Exported Macros * @{ */ /** @brief Reset I2C handle state. * @param __HANDLE__: specifies the I2C Handle. * @retval None */ #define __HAL_I2C_RESET_HANDLE_STATE(__HANDLE__) ((__HANDLE__)->State = HAL_I2C_STATE_RESET) /** @brief Enable the specified I2C interrupt. * @param __HANDLE__: specifies the I2C Handle. * @param __INTERRUPT__: specifies the interrupt source to enable. * This parameter can be one of the following values: * @arg I2C_IT_ERRI: Errors interrupt enable * @arg I2C_IT_TCI: Transfer complete interrupt enable * @arg I2C_IT_STOPI: STOP detection interrupt enable * @arg I2C_IT_NACKI: NACK received interrupt enable * @arg I2C_IT_ADDRI: Address match interrupt enable * @arg I2C_IT_RXI: RX interrupt enable * @arg I2C_IT_TXI: TX interrupt enable * * @retval None */ #define __HAL_I2C_ENABLE_IT(__HANDLE__, __INTERRUPT__) ((__HANDLE__)->Instance->CR1 |= (__INTERRUPT__)) /** @brief Disable the specified I2C interrupt. * @param __HANDLE__: specifies the I2C Handle. * @param __INTERRUPT__: specifies the interrupt source to disable. * This parameter can be one of the following values: * @arg I2C_IT_ERRI: Errors interrupt enable * @arg I2C_IT_TCI: Transfer complete interrupt enable * @arg I2C_IT_STOPI: STOP detection interrupt enable * @arg I2C_IT_NACKI: NACK received interrupt enable * @arg I2C_IT_ADDRI: Address match interrupt enable * @arg I2C_IT_RXI: RX interrupt enable * @arg I2C_IT_TXI: TX interrupt enable * * @retval None */ #define __HAL_I2C_DISABLE_IT(__HANDLE__, __INTERRUPT__) ((__HANDLE__)->Instance->CR1 &= (~(__INTERRUPT__))) /** @brief Check whether the specified I2C interrupt source is enabled or not. * @param __HANDLE__: specifies the I2C Handle. * @param __INTERRUPT__: specifies the I2C interrupt source to check. * This parameter can be one of the following values: * @arg I2C_IT_ERRI: Errors interrupt enable * @arg I2C_IT_TCI: Transfer complete interrupt enable * @arg I2C_IT_STOPI: STOP detection interrupt enable * @arg I2C_IT_NACKI: NACK received interrupt enable * @arg I2C_IT_ADDRI: Address match interrupt enable * @arg I2C_IT_RXI: RX interrupt enable * @arg I2C_IT_TXI: TX interrupt enable * * @retval The new state of __INTERRUPT__ (TRUE or FALSE). */ #define __HAL_I2C_GET_IT_SOURCE(__HANDLE__, __INTERRUPT__) ((((__HANDLE__)->Instance->CR1 & (__INTERRUPT__)) == (__INTERRUPT__)) ? SET : RESET) /** @brief Check whether the specified I2C flag is set or not. * @param __HANDLE__: specifies the I2C Handle. * @param __FLAG__: specifies the flag to check. * This parameter can be one of the following values: * @arg I2C_FLAG_TXE: Transmit data register empty * @arg I2C_FLAG_TXIS: Transmit interrupt status * @arg I2C_FLAG_RXNE: Receive data register not empty * @arg I2C_FLAG_ADDR: Address matched (slave mode) * @arg I2C_FLAG_AF: Acknowledge failure received flag * @arg I2C_FLAG_STOPF: STOP detection flag * @arg I2C_FLAG_TC: Transfer complete (master mode) * @arg I2C_FLAG_TCR: Transfer complete reload * @arg I2C_FLAG_BERR: Bus error * @arg I2C_FLAG_ARLO: Arbitration lost * @arg I2C_FLAG_OVR: Overrun/Underrun * @arg I2C_FLAG_PECERR: PEC error in reception * @arg I2C_FLAG_TIMEOUT: Timeout or Tlow detection flag * @arg I2C_FLAG_ALERT: SMBus alert * @arg I2C_FLAG_BUSY: Bus busy * @arg I2C_FLAG_DIR: Transfer direction (slave mode) * * @retval The new state of __FLAG__ (TRUE or FALSE). */ #define I2C_FLAG_MASK ((uint32_t)0x0001FFFF) #define __HAL_I2C_GET_FLAG(__HANDLE__, __FLAG__) (((((__HANDLE__)->Instance->ISR) & ((__FLAG__) & I2C_FLAG_MASK)) == ((__FLAG__) & I2C_FLAG_MASK))) /** @brief Clear the I2C pending flags which are cleared by writing 1 in a specific bit. * @param __HANDLE__: specifies the I2C Handle. * @param __FLAG__: specifies the flag to clear. * This parameter can be any combination of the following values: * @arg I2C_FLAG_ADDR: Address matched (slave mode) * @arg I2C_FLAG_AF: Acknowledge failure received flag * @arg I2C_FLAG_STOPF: STOP detection flag * @arg I2C_FLAG_BERR: Bus error * @arg I2C_FLAG_ARLO: Arbitration lost * @arg I2C_FLAG_OVR: Overrun/Underrun * @arg I2C_FLAG_PECERR: PEC error in reception * @arg I2C_FLAG_TIMEOUT: Timeout or Tlow detection flag * @arg I2C_FLAG_ALERT: SMBus alert * * @retval None */ #define __HAL_I2C_CLEAR_FLAG(__HANDLE__, __FLAG__) ((__HANDLE__)->Instance->ICR = ((__FLAG__) & I2C_FLAG_MASK)) /** @brief Enable the specified I2C peripheral. * @param __HANDLE__: specifies the I2C Handle. * @retval None */ #define __HAL_I2C_ENABLE(__HANDLE__) (SET_BIT((__HANDLE__)->Instance->CR1, I2C_CR1_PE)) /** @brief Disable the specified I2C peripheral. * @param __HANDLE__: specifies the I2C Handle. * @retval None */ #define __HAL_I2C_DISABLE(__HANDLE__) (CLEAR_BIT((__HANDLE__)->Instance->CR1, I2C_CR1_PE)) /** * @} */ /* Include I2C HAL Extended module */ #include "stm32f0xx_hal_i2c_ex.h" /* Exported functions --------------------------------------------------------*/ /** @addtogroup I2C_Exported_Functions * @{ */ /** @addtogroup I2C_Exported_Functions_Group1 Initialization and de-initialization functions * @{ */ /* Initialization and de-initialization functions******************************/ HAL_StatusTypeDef HAL_I2C_Init(I2C_HandleTypeDef *hi2c); HAL_StatusTypeDef HAL_I2C_DeInit (I2C_HandleTypeDef *hi2c); void HAL_I2C_MspInit(I2C_HandleTypeDef *hi2c); void HAL_I2C_MspDeInit(I2C_HandleTypeDef *hi2c); /** * @} */ /** @addtogroup I2C_Exported_Functions_Group2 Input and Output operation functions * @{ */ /* IO operation functions ****************************************************/ /******* Blocking mode: Polling */ HAL_StatusTypeDef HAL_I2C_Master_Transmit(I2C_HandleTypeDef *hi2c, uint16_t DevAddress, uint8_t *pData, uint16_t Size, uint32_t Timeout); HAL_StatusTypeDef HAL_I2C_Master_Receive(I2C_HandleTypeDef *hi2c, uint16_t DevAddress, uint8_t *pData, uint16_t Size, uint32_t Timeout); HAL_StatusTypeDef HAL_I2C_Slave_Transmit(I2C_HandleTypeDef *hi2c, uint8_t *pData, uint16_t Size, uint32_t Timeout); HAL_StatusTypeDef HAL_I2C_Slave_Receive(I2C_HandleTypeDef *hi2c, uint8_t *pData, uint16_t Size, uint32_t Timeout); HAL_StatusTypeDef HAL_I2C_Mem_Write(I2C_HandleTypeDef *hi2c, uint16_t DevAddress, uint16_t MemAddress, uint16_t MemAddSize, uint8_t *pData, uint16_t Size, uint32_t Timeout); HAL_StatusTypeDef HAL_I2C_Mem_Read(I2C_HandleTypeDef *hi2c, uint16_t DevAddress, uint16_t MemAddress, uint16_t MemAddSize, uint8_t *pData, uint16_t Size, uint32_t Timeout); HAL_StatusTypeDef HAL_I2C_IsDeviceReady(I2C_HandleTypeDef *hi2c, uint16_t DevAddress, uint32_t Trials, uint32_t Timeout); /******* Non-Blocking mode: Interrupt */ HAL_StatusTypeDef HAL_I2C_Master_Transmit_IT(I2C_HandleTypeDef *hi2c, uint16_t DevAddress, uint8_t *pData, uint16_t Size); HAL_StatusTypeDef HAL_I2C_Master_Receive_IT(I2C_HandleTypeDef *hi2c, uint16_t DevAddress, uint8_t *pData, uint16_t Size); HAL_StatusTypeDef HAL_I2C_Slave_Transmit_IT(I2C_HandleTypeDef *hi2c, uint8_t *pData, uint16_t Size); HAL_StatusTypeDef HAL_I2C_Slave_Receive_IT(I2C_HandleTypeDef *hi2c, uint8_t *pData, uint16_t Size); HAL_StatusTypeDef HAL_I2C_Mem_Write_IT(I2C_HandleTypeDef *hi2c, uint16_t DevAddress, uint16_t MemAddress, uint16_t MemAddSize, uint8_t *pData, uint16_t Size); HAL_StatusTypeDef HAL_I2C_Mem_Read_IT(I2C_HandleTypeDef *hi2c, uint16_t DevAddress, uint16_t MemAddress, uint16_t MemAddSize, uint8_t *pData, uint16_t Size); /******* Non-Blocking mode: DMA */ HAL_StatusTypeDef HAL_I2C_Master_Transmit_DMA(I2C_HandleTypeDef *hi2c, uint16_t DevAddress, uint8_t *pData, uint16_t Size); HAL_StatusTypeDef HAL_I2C_Master_Receive_DMA(I2C_HandleTypeDef *hi2c, uint16_t DevAddress, uint8_t *pData, uint16_t Size); HAL_StatusTypeDef HAL_I2C_Slave_Transmit_DMA(I2C_HandleTypeDef *hi2c, uint8_t *pData, uint16_t Size); HAL_StatusTypeDef HAL_I2C_Slave_Receive_DMA(I2C_HandleTypeDef *hi2c, uint8_t *pData, uint16_t Size); HAL_StatusTypeDef HAL_I2C_Mem_Write_DMA(I2C_HandleTypeDef *hi2c, uint16_t DevAddress, uint16_t MemAddress, uint16_t MemAddSize, uint8_t *pData, uint16_t Size); HAL_StatusTypeDef HAL_I2C_Mem_Read_DMA(I2C_HandleTypeDef *hi2c, uint16_t DevAddress, uint16_t MemAddress, uint16_t MemAddSize, uint8_t *pData, uint16_t Size); /** * @} */ /** @addtogroup I2C_IRQ_Handler_and_Callbacks IRQ Handler and Callbacks * @{ */ /******* I2C IRQHandler and Callbacks used in non blocking modes (Interrupt and DMA) */ void HAL_I2C_EV_IRQHandler(I2C_HandleTypeDef *hi2c); void HAL_I2C_ER_IRQHandler(I2C_HandleTypeDef *hi2c); void HAL_I2C_MasterTxCpltCallback(I2C_HandleTypeDef *hi2c); void HAL_I2C_MasterRxCpltCallback(I2C_HandleTypeDef *hi2c); void HAL_I2C_SlaveTxCpltCallback(I2C_HandleTypeDef *hi2c); void HAL_I2C_SlaveRxCpltCallback(I2C_HandleTypeDef *hi2c); void HAL_I2C_MemTxCpltCallback(I2C_HandleTypeDef *hi2c); void HAL_I2C_MemRxCpltCallback(I2C_HandleTypeDef *hi2c); void HAL_I2C_ErrorCallback(I2C_HandleTypeDef *hi2c); /** * @} */ /** @addtogroup I2C_Exported_Functions_Group3 Peripheral State and Errors functions * @{ */ /* Peripheral State and Errors functions *************************************/ HAL_I2C_StateTypeDef HAL_I2C_GetState(I2C_HandleTypeDef *hi2c); uint32_t HAL_I2C_GetError(I2C_HandleTypeDef *hi2c); /** * @} */ /** * @} */ /* Private constants ---------------------------------------------------------*/ /** @defgroup I2C_Private_Constants I2C Private Constants * @{ */ /** * @} */ /* Private macros ------------------------------------------------------------*/ /** @defgroup I2C_Private_Macro I2C Private Macros * @{ */ #define IS_I2C_ADDRESSING_MODE(MODE) (((MODE) == I2C_ADDRESSINGMODE_7BIT) || \ ((MODE) == I2C_ADDRESSINGMODE_10BIT)) #define IS_I2C_DUAL_ADDRESS(ADDRESS) (((ADDRESS) == I2C_DUALADDRESS_DISABLE) || \ ((ADDRESS) == I2C_DUALADDRESS_ENABLE)) #define IS_I2C_OWN_ADDRESS2_MASK(MASK) (((MASK) == I2C_OA2_NOMASK) || \ ((MASK) == I2C_OA2_MASK01) || \ ((MASK) == I2C_OA2_MASK02) || \ ((MASK) == I2C_OA2_MASK03) || \ ((MASK) == I2C_OA2_MASK04) || \ ((MASK) == I2C_OA2_MASK05) || \ ((MASK) == I2C_OA2_MASK06) || \ ((MASK) == I2C_OA2_MASK07)) #define IS_I2C_GENERAL_CALL(CALL) (((CALL) == I2C_GENERALCALL_DISABLE) || \ ((CALL) == I2C_GENERALCALL_ENABLE)) #define IS_I2C_NO_STRETCH(STRETCH) (((STRETCH) == I2C_NOSTRETCH_DISABLE) || \ ((STRETCH) == I2C_NOSTRETCH_ENABLE)) #define IS_I2C_MEMADD_SIZE(SIZE) (((SIZE) == I2C_MEMADD_SIZE_8BIT) || \ ((SIZE) == I2C_MEMADD_SIZE_16BIT)) #define IS_TRANSFER_MODE(MODE) (((MODE) == I2C_RELOAD_MODE) || \ ((MODE) == I2C_AUTOEND_MODE) || \ ((MODE) == I2C_SOFTEND_MODE)) #define IS_TRANSFER_REQUEST(REQUEST) (((REQUEST) == I2C_GENERATE_STOP) || \ ((REQUEST) == I2C_GENERATE_START_READ) || \ ((REQUEST) == I2C_GENERATE_START_WRITE) || \ ((REQUEST) == I2C_NO_STARTSTOP)) #define I2C_RESET_CR2(__HANDLE__) ((__HANDLE__)->Instance->CR2 &= (uint32_t)~((uint32_t)(I2C_CR2_SADD | I2C_CR2_HEAD10R | I2C_CR2_NBYTES | I2C_CR2_RELOAD | I2C_CR2_RD_WRN))) #define IS_I2C_OWN_ADDRESS1(ADDRESS1) ((ADDRESS1) <= (uint32_t)0x000003FF) #define IS_I2C_OWN_ADDRESS2(ADDRESS2) ((ADDRESS2) <= (uint16_t)0x00FF) #define I2C_MEM_ADD_MSB(__ADDRESS__) ((uint8_t)((uint16_t)(((uint16_t)((__ADDRESS__) & (uint16_t)(0xFF00))) >> 8))) #define I2C_MEM_ADD_LSB(__ADDRESS__) ((uint8_t)((uint16_t)((__ADDRESS__) & (uint16_t)(0x00FF)))) #define I2C_GENERATE_START(__ADDMODE__,__ADDRESS__) (((__ADDMODE__) == I2C_ADDRESSINGMODE_7BIT) ? (uint32_t)((((uint32_t)(__ADDRESS__) & (I2C_CR2_SADD)) | (I2C_CR2_START) | (I2C_CR2_AUTOEND)) & (~I2C_CR2_RD_WRN)) : \ (uint32_t)((((uint32_t)(__ADDRESS__) & (I2C_CR2_SADD)) | (I2C_CR2_ADD10) | (I2C_CR2_START)) & (~I2C_CR2_RD_WRN))) /** * @} */ /* Private Functions ---------------------------------------------------------*/ /** @defgroup I2C_Private_Functions I2C Private Functions * @{ */ /* Private functions are defined in stm32l4xx_hal_i2c.c file */ /** * @} */ /** * @} */ /** * @} */ #ifdef __cplusplus } #endif #endif /* __STM32F0xx_HAL_I2C_H */ /************************ (C) COPYRIGHT STMicroelectronics *****END OF FILE****/ ================================================ FILE: Zelig/mbed/TARGET_NUCLEO_F091RC/stm32f0xx_hal_i2c_ex.h ================================================ /** ****************************************************************************** * @file stm32f0xx_hal_i2c_ex.h * @author MCD Application Team * @version V1.3.0 * @date 26-June-2015 * @brief Header file of I2C HAL Extended module. ****************************************************************************** * @attention * *

© COPYRIGHT(c) 2015 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. * ****************************************************************************** */ /* Define to prevent recursive inclusion -------------------------------------*/ #ifndef __STM32F0xx_HAL_I2C_EX_H #define __STM32F0xx_HAL_I2C_EX_H #ifdef __cplusplus extern "C" { #endif /* Includes ------------------------------------------------------------------*/ #include "stm32f0xx_hal_def.h" /** @addtogroup STM32F0xx_HAL_Driver * @{ */ /** @addtogroup I2CEx I2CEx * @{ */ /* Exported types ------------------------------------------------------------*/ /* Exported constants --------------------------------------------------------*/ /** @defgroup I2CEx_Exported_Constants I2CEx Exported Constants * @{ */ /** @defgroup I2CEx_Analog_Filter I2CEx Analog Filter * @{ */ #define I2C_ANALOGFILTER_ENABLE ((uint32_t)0x00000000) #define I2C_ANALOGFILTER_DISABLE I2C_CR1_ANFOFF /** * @} */ /** @defgroup I2CEx_FastModePlus I2CEx Fast Mode Plus * @{ */ #if defined(STM32F091xC) || defined(STM32F098xx) || defined(STM32F042x6) || defined(STM32F048xx) #define I2C_FASTMODEPLUS_PA9 SYSCFG_CFGR1_I2C_FMP_PA9 /*!< Enable Fast Mode Plus on PA9 */ #define I2C_FASTMODEPLUS_PA10 SYSCFG_CFGR1_I2C_FMP_PA10 /*!< Enable Fast Mode Plus on PA10 */ #define I2C_FASTMODEPLUS_PB6 SYSCFG_CFGR1_I2C_FMP_PB6 /*!< Enable Fast Mode Plus on PB6 */ #define I2C_FASTMODEPLUS_PB7 SYSCFG_CFGR1_I2C_FMP_PB7 /*!< Enable Fast Mode Plus on PB7 */ #define I2C_FASTMODEPLUS_PB8 SYSCFG_CFGR1_I2C_FMP_PB8 /*!< Enable Fast Mode Plus on PB8 */ #define I2C_FASTMODEPLUS_PB9 SYSCFG_CFGR1_I2C_FMP_PB9 /*!< Enable Fast Mode Plus on PB9 */ #define I2C_FASTMODEPLUS_I2C1 SYSCFG_CFGR1_I2C_FMP_I2C1 /*!< Enable Fast Mode Plus on I2C1 pins */ #define I2C_FASTMODEPLUS_I2C2 SYSCFG_CFGR1_I2C_FMP_I2C2 /*!< Enable Fast Mode Plus on I2C2 pins */ #elif defined(STM32F071xB) || defined(STM32F072xB) || defined(STM32F078xx) #define I2C_FASTMODEPLUS_PB6 SYSCFG_CFGR1_I2C_FMP_PB6 /*!< Enable Fast Mode Plus on PB6 */ #define I2C_FASTMODEPLUS_PB7 SYSCFG_CFGR1_I2C_FMP_PB7 /*!< Enable Fast Mode Plus on PB7 */ #define I2C_FASTMODEPLUS_PB8 SYSCFG_CFGR1_I2C_FMP_PB8 /*!< Enable Fast Mode Plus on PB8 */ #define I2C_FASTMODEPLUS_PB9 SYSCFG_CFGR1_I2C_FMP_PB9 /*!< Enable Fast Mode Plus on PB9 */ #define I2C_FASTMODEPLUS_I2C1 SYSCFG_CFGR1_I2C_FMP_I2C1 /*!< Enable Fast Mode Plus on I2C1 pins */ #define I2C_FASTMODEPLUS_I2C2 SYSCFG_CFGR1_I2C_FMP_I2C2 /*!< Enable Fast Mode Plus on I2C2 pins */ #elif defined(STM32F030x6) || defined(STM32F031x6) || defined(STM32F038xx) || defined(STM32F070x6) || defined(STM32F030xC) #define I2C_FASTMODEPLUS_PA9 SYSCFG_CFGR1_I2C_FMP_PA9 /*!< Enable Fast Mode Plus on PA9 */ #define I2C_FASTMODEPLUS_PA10 SYSCFG_CFGR1_I2C_FMP_PA10 /*!< Enable Fast Mode Plus on PA10 */ #define I2C_FASTMODEPLUS_PB6 SYSCFG_CFGR1_I2C_FMP_PB6 /*!< Enable Fast Mode Plus on PB6 */ #define I2C_FASTMODEPLUS_PB7 SYSCFG_CFGR1_I2C_FMP_PB7 /*!< Enable Fast Mode Plus on PB7 */ #define I2C_FASTMODEPLUS_PB8 SYSCFG_CFGR1_I2C_FMP_PB8 /*!< Enable Fast Mode Plus on PB8 */ #define I2C_FASTMODEPLUS_PB9 SYSCFG_CFGR1_I2C_FMP_PB9 /*!< Enable Fast Mode Plus on PB9 */ #define I2C_FASTMODEPLUS_I2C1 SYSCFG_CFGR1_I2C_FMP_I2C1 /*!< Enable Fast Mode Plus on I2C1 pins */ #elif defined(STM32F070xB) #define I2C_FASTMODEPLUS_PB6 SYSCFG_CFGR1_I2C_FMP_PB6 /*!< Enable Fast Mode Plus on PB6 */ #define I2C_FASTMODEPLUS_PB7 SYSCFG_CFGR1_I2C_FMP_PB7 /*!< Enable Fast Mode Plus on PB7 */ #define I2C_FASTMODEPLUS_PB8 SYSCFG_CFGR1_I2C_FMP_PB8 /*!< Enable Fast Mode Plus on PB8 */ #define I2C_FASTMODEPLUS_PB9 SYSCFG_CFGR1_I2C_FMP_PB9 /*!< Enable Fast Mode Plus on PB9 */ #define I2C_FASTMODEPLUS_I2C1 SYSCFG_CFGR1_I2C_FMP_I2C1 /*!< Enable Fast Mode Plus on I2C1 pins */ #else /* defined(STM32F030x8) || defined(STM32F051xx) || defined(STM32F058xx) */ #define I2C_FASTMODEPLUS_PB6 SYSCFG_CFGR1_I2C_FMP_PB6 /*!< Enable Fast Mode Plus on PB6 */ #define I2C_FASTMODEPLUS_PB7 SYSCFG_CFGR1_I2C_FMP_PB7 /*!< Enable Fast Mode Plus on PB7 */ #define I2C_FASTMODEPLUS_PB8 SYSCFG_CFGR1_I2C_FMP_PB8 /*!< Enable Fast Mode Plus on PB8 */ #define I2C_FASTMODEPLUS_PB9 SYSCFG_CFGR1_I2C_FMP_PB9 /*!< Enable Fast Mode Plus on PB9 */ #endif /** * @} */ /** * @} */ /* Exported macro ------------------------------------------------------------*/ /* Exported functions --------------------------------------------------------*/ /** @addtogroup I2CEx_Exported_Functions * @{ */ /** @addtogroup I2CEx_Exported_Functions_Group1 Extended features functions * @brief Extended features functions * @{ */ /* Peripheral Control functions ************************************************/ HAL_StatusTypeDef HAL_I2CEx_ConfigAnalogFilter(I2C_HandleTypeDef *hi2c, uint32_t AnalogFilter); HAL_StatusTypeDef HAL_I2CEx_ConfigDigitalFilter(I2C_HandleTypeDef *hi2c, uint32_t DigitalFilter); #if !defined(STM32F030x6) && !defined(STM32F030x8) && !defined(STM32F070x6) && !defined(STM32F070xB) && !defined(STM32F030xC) HAL_StatusTypeDef HAL_I2CEx_EnableWakeUp (I2C_HandleTypeDef *hi2c); HAL_StatusTypeDef HAL_I2CEx_DisableWakeUp (I2C_HandleTypeDef *hi2c); #endif /* !(STM32F030x6) && !(STM32F030x8) && !(STM32F070x6) && !(STM32F070xB) && !(STM32F030xC) */ void HAL_I2CEx_EnableFastModePlus(uint32_t ConfigFastModePlus); void HAL_I2CEx_DisableFastModePlus(uint32_t ConfigFastModePlus); /* Private constants ---------------------------------------------------------*/ /** @defgroup I2C_Private_Constants I2C Private Constants * @{ */ /** * @} */ /* Private macros ------------------------------------------------------------*/ /** @defgroup I2C_Private_Macro I2C Private Macros * @{ */ #define IS_I2C_ANALOG_FILTER(FILTER) (((FILTER) == I2C_ANALOGFILTER_ENABLE) || \ ((FILTER) == I2C_ANALOGFILTER_DISABLE)) #define IS_I2C_DIGITAL_FILTER(FILTER) ((FILTER) <= 0x0000000F) #if defined(STM32F091xC) || defined(STM32F098xx) || defined(STM32F042x6) || defined(STM32F048xx) #define IS_I2C_FASTMODEPLUS(__CONFIG__) ((((__CONFIG__) & (I2C_FASTMODEPLUS_PA9)) == I2C_FASTMODEPLUS_PA9) || \ (((__CONFIG__) & (I2C_FASTMODEPLUS_PA10)) == I2C_FASTMODEPLUS_PA10) || \ (((__CONFIG__) & (I2C_FASTMODEPLUS_PB6)) == I2C_FASTMODEPLUS_PB6) || \ (((__CONFIG__) & (I2C_FASTMODEPLUS_PB7)) == I2C_FASTMODEPLUS_PB7) || \ (((__CONFIG__) & (I2C_FASTMODEPLUS_PB8)) == I2C_FASTMODEPLUS_PB8) || \ (((__CONFIG__) & (I2C_FASTMODEPLUS_PB9)) == I2C_FASTMODEPLUS_PB9) || \ (((__CONFIG__) & (I2C_FASTMODEPLUS_I2C1)) == I2C_FASTMODEPLUS_I2C1) || \ (((__CONFIG__) & (I2C_FASTMODEPLUS_I2C2)) == I2C_FASTMODEPLUS_I2C2)) #elif defined(STM32F071xB) || defined(STM32F072xB) || defined(STM32F078xx) #define IS_I2C_FASTMODEPLUS(__CONFIG__) ((((__CONFIG__) & (I2C_FASTMODEPLUS_PB6)) == I2C_FASTMODEPLUS_PB6) || \ (((__CONFIG__) & (I2C_FASTMODEPLUS_PB7)) == I2C_FASTMODEPLUS_PB7) || \ (((__CONFIG__) & (I2C_FASTMODEPLUS_PB8)) == I2C_FASTMODEPLUS_PB8) || \ (((__CONFIG__) & (I2C_FASTMODEPLUS_PB9)) == I2C_FASTMODEPLUS_PB9) || \ (((__CONFIG__) & (I2C_FASTMODEPLUS_I2C1)) == I2C_FASTMODEPLUS_I2C1) || \ (((__CONFIG__) & (I2C_FASTMODEPLUS_I2C2)) == I2C_FASTMODEPLUS_I2C2)) #elif defined(STM32F030x6) || defined(STM32F031x6) || defined(STM32F038xx) || defined(STM32F070x6) || defined(STM32F030xC) #define IS_I2C_FASTMODEPLUS(__CONFIG__) ((((__CONFIG__) & (I2C_FASTMODEPLUS_PA9)) == I2C_FASTMODEPLUS_PA9) || \ (((__CONFIG__) & (I2C_FASTMODEPLUS_PA10)) == I2C_FASTMODEPLUS_PA10) || \ (((__CONFIG__) & (I2C_FASTMODEPLUS_PB6)) == I2C_FASTMODEPLUS_PB6) || \ (((__CONFIG__) & (I2C_FASTMODEPLUS_PB7)) == I2C_FASTMODEPLUS_PB7) || \ (((__CONFIG__) & (I2C_FASTMODEPLUS_PB8)) == I2C_FASTMODEPLUS_PB8) || \ (((__CONFIG__) & (I2C_FASTMODEPLUS_PB9)) == I2C_FASTMODEPLUS_PB9) || \ (((__CONFIG__) & (I2C_FASTMODEPLUS_I2C1)) == I2C_FASTMODEPLUS_I2C1)) #elif defined(STM32F070xB) #define IS_I2C_FASTMODEPLUS(__CONFIG__) ((((__CONFIG__) & (I2C_FASTMODEPLUS_PB6)) == I2C_FASTMODEPLUS_PB6) || \ (((__CONFIG__) & (I2C_FASTMODEPLUS_PB7)) == I2C_FASTMODEPLUS_PB7) || \ (((__CONFIG__) & (I2C_FASTMODEPLUS_PB8)) == I2C_FASTMODEPLUS_PB8) || \ (((__CONFIG__) & (I2C_FASTMODEPLUS_PB9)) == I2C_FASTMODEPLUS_PB9) || \ (((__CONFIG__) & (I2C_FASTMODEPLUS_I2C1)) == I2C_FASTMODEPLUS_I2C1)) #else /* defined(STM32F030x8) || defined(STM32F051xx) || defined(STM32F058xx) */ #define IS_I2C_FASTMODEPLUS(__CONFIG__) ((((__CONFIG__) & (I2C_FASTMODEPLUS_PB6)) == I2C_FASTMODEPLUS_PB6) || \ (((__CONFIG__) & (I2C_FASTMODEPLUS_PB7)) == I2C_FASTMODEPLUS_PB7) || \ (((__CONFIG__) & (I2C_FASTMODEPLUS_PB8)) == I2C_FASTMODEPLUS_PB8) || \ (((__CONFIG__) & (I2C_FASTMODEPLUS_PB9)) == I2C_FASTMODEPLUS_PB9)) #endif /** * @} */ /* Private Functions ---------------------------------------------------------*/ /** @defgroup I2C_Private_Functions I2C Private Functions * @{ */ /* Private functions are defined in stm32f0xx_hal_i2c_ex.c file */ /** * @} */ /** * @} */ /** * @} */ /** * @} */ /** * @} */ #ifdef __cplusplus } #endif #endif /* __STM32F0xx_HAL_I2C_EX_H */ /************************ (C) COPYRIGHT STMicroelectronics *****END OF FILE****/ ================================================ FILE: Zelig/mbed/TARGET_NUCLEO_F091RC/stm32f0xx_hal_i2s.h ================================================ /** ****************************************************************************** * @file stm32f0xx_hal_i2s.h * @author MCD Application Team * @version V1.3.0 * @date 26-June-2015 * @brief Header file of I2S HAL module. ****************************************************************************** * @attention * *

© COPYRIGHT(c) 2015 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. * ****************************************************************************** */ /* Define to prevent recursive inclusion -------------------------------------*/ #ifndef __STM32F0xx_HAL_I2S_H #define __STM32F0xx_HAL_I2S_H #ifdef __cplusplus extern "C" { #endif #if defined(STM32F031x6) || defined(STM32F038xx) || \ defined(STM32F051x8) || defined(STM32F058xx) || \ defined(STM32F071xB) || defined(STM32F072xB) || defined(STM32F078xx) || \ defined(STM32F042x6) || defined(STM32F048xx) || \ defined(STM32F091xC) || defined(STM32F098xx) /* Includes ------------------------------------------------------------------*/ #include "stm32f0xx_hal_def.h" /** @addtogroup STM32F0xx_HAL_Driver * @{ */ /** @addtogroup I2S * @{ */ /* Exported types ------------------------------------------------------------*/ /** @defgroup I2S_Exported_Types I2S Exported Types * @{ */ /** * @brief I2S Init structure definition */ typedef struct { uint32_t Mode; /*!< Specifies the I2S operating mode. This parameter can be a value of @ref I2S_Mode */ uint32_t Standard; /*!< Specifies the standard used for the I2S communication. This parameter can be a value of @ref I2S_Standard */ uint32_t DataFormat; /*!< Specifies the data format for the I2S communication. This parameter can be a value of @ref I2S_Data_Format */ uint32_t MCLKOutput; /*!< Specifies whether the I2S MCLK output is enabled or not. This parameter can be a value of @ref I2S_MCLK_Output */ uint32_t AudioFreq; /*!< Specifies the frequency selected for the I2S communication. This parameter can be a value of @ref I2S_Audio_Frequency */ uint32_t CPOL; /*!< Specifies the idle state of the I2S clock. This parameter can be a value of @ref I2S_Clock_Polarity */ }I2S_InitTypeDef; /** * @brief HAL State structures definition */ typedef enum { HAL_I2S_STATE_RESET = 0x00, /*!< I2S not yet initialized or disabled */ HAL_I2S_STATE_READY = 0x01, /*!< I2S initialized and ready for use */ HAL_I2S_STATE_BUSY = 0x02, /*!< I2S internal process is ongoing */ HAL_I2S_STATE_BUSY_TX = 0x03, /*!< Data Transmission process is ongoing */ HAL_I2S_STATE_BUSY_RX = 0x04, /*!< Data Reception process is ongoing */ HAL_I2S_STATE_PAUSE = 0x06, /*!< I2S pause state: used in case of DMA */ HAL_I2S_STATE_ERROR = 0x07 /*!< I2S error state */ }HAL_I2S_StateTypeDef; /** * @brief I2S handle Structure definition */ typedef struct { SPI_TypeDef *Instance; /*!< I2S registers base address */ I2S_InitTypeDef Init; /*!< I2S communication parameters */ uint16_t *pTxBuffPtr; /*!< Pointer to I2S Tx transfer buffer */ __IO uint16_t TxXferSize; /*!< I2S Tx transfer size */ __IO uint16_t TxXferCount; /*!< I2S Tx transfer Counter */ uint16_t *pRxBuffPtr; /*!< Pointer to I2S Rx transfer buffer */ __IO uint16_t RxXferSize; /*!< I2S Rx transfer size */ __IO uint16_t RxXferCount; /*!< I2S Rx transfer counter (This field is initialized at the same value as transfer size at the beginning of the transfer and decremented when a sample is received. NbSamplesReceived = RxBufferSize-RxBufferCount) */ DMA_HandleTypeDef *hdmatx; /*!< I2S Tx DMA handle parameters */ DMA_HandleTypeDef *hdmarx; /*!< I2S Rx DMA handle parameters */ __IO HAL_LockTypeDef Lock; /*!< I2S locking object */ __IO HAL_I2S_StateTypeDef State; /*!< I2S communication state */ __IO uint32_t ErrorCode; /*!< I2S Error code This parameter can be a value of @ref I2S_Error */ }I2S_HandleTypeDef; /** * @} */ /* Exported constants --------------------------------------------------------*/ /** @defgroup I2S_Exported_Constants I2S Exported Constants * @{ */ /** @defgroup I2S_Error I2S Error * @{ */ #define HAL_I2S_ERROR_NONE ((uint32_t)0x00000000) /*!< No error */ #define HAL_I2S_ERROR_TIMEOUT ((uint32_t)0x00000001) /*!< Timeout error */ #define HAL_I2S_ERROR_OVR ((uint32_t)0x00000002) /*!< OVR error */ #define HAL_I2S_ERROR_UDR ((uint32_t)0x00000004) /*!< UDR error */ #define HAL_I2S_ERROR_DMA ((uint32_t)0x00000008) /*!< DMA transfer error */ #define HAL_I2S_ERROR_UNKNOW ((uint32_t)0x00000010) /*!< Unknow Error error */ /** * @} */ /** @defgroup I2S_Mode I2S Mode * @{ */ #define I2S_MODE_SLAVE_TX ((uint32_t)0x00000000) #define I2S_MODE_SLAVE_RX ((uint32_t)0x00000100) #define I2S_MODE_MASTER_TX ((uint32_t)0x00000200) #define I2S_MODE_MASTER_RX ((uint32_t)0x00000300) #define IS_I2S_MODE(MODE) (((MODE) == I2S_MODE_SLAVE_TX) || \ ((MODE) == I2S_MODE_SLAVE_RX) || \ ((MODE) == I2S_MODE_MASTER_TX)|| \ ((MODE) == I2S_MODE_MASTER_RX)) /** * @} */ /** @defgroup I2S_Standard I2S Standard * @{ */ #define I2S_STANDARD_PHILIPS ((uint32_t)0x00000000) #define I2S_STANDARD_MSB ((uint32_t)0x00000010) #define I2S_STANDARD_LSB ((uint32_t)0x00000020) #define I2S_STANDARD_PCM_SHORT ((uint32_t)0x00000030) #define I2S_STANDARD_PCM_LONG ((uint32_t)0x000000B0) #define IS_I2S_STANDARD(STANDARD) (((STANDARD) == I2S_STANDARD_PHILIPS) || \ ((STANDARD) == I2S_STANDARD_MSB) || \ ((STANDARD) == I2S_STANDARD_LSB) || \ ((STANDARD) == I2S_STANDARD_PCM_SHORT) || \ ((STANDARD) == I2S_STANDARD_PCM_LONG)) /** * @} */ /** @defgroup I2S_Data_Format I2S Data Format * @{ */ #define I2S_DATAFORMAT_16B ((uint32_t)0x00000000) #define I2S_DATAFORMAT_16B_EXTENDED ((uint32_t)0x00000001) #define I2S_DATAFORMAT_24B ((uint32_t)0x00000003) #define I2S_DATAFORMAT_32B ((uint32_t)0x00000005) #define IS_I2S_DATA_FORMAT(FORMAT) (((FORMAT) == I2S_DATAFORMAT_16B) || \ ((FORMAT) == I2S_DATAFORMAT_16B_EXTENDED) || \ ((FORMAT) == I2S_DATAFORMAT_24B) || \ ((FORMAT) == I2S_DATAFORMAT_32B)) /** * @} */ /** @defgroup I2S_MCLK_Output I2S MCLK Output * @{ */ #define I2S_MCLKOUTPUT_ENABLE ((uint32_t)SPI_I2SPR_MCKOE) #define I2S_MCLKOUTPUT_DISABLE ((uint32_t)0x00000000) #define IS_I2S_MCLK_OUTPUT(OUTPUT) (((OUTPUT) == I2S_MCLKOUTPUT_ENABLE) || \ ((OUTPUT) == I2S_MCLKOUTPUT_DISABLE)) /** * @} */ /** @defgroup I2S_Audio_Frequency I2S Audio Frequency * @{ */ #define I2S_AUDIOFREQ_192K ((uint32_t)192000) #define I2S_AUDIOFREQ_96K ((uint32_t)96000) #define I2S_AUDIOFREQ_48K ((uint32_t)48000) #define I2S_AUDIOFREQ_44K ((uint32_t)44100) #define I2S_AUDIOFREQ_32K ((uint32_t)32000) #define I2S_AUDIOFREQ_22K ((uint32_t)22050) #define I2S_AUDIOFREQ_16K ((uint32_t)16000) #define I2S_AUDIOFREQ_11K ((uint32_t)11025) #define I2S_AUDIOFREQ_8K ((uint32_t)8000) #define I2S_AUDIOFREQ_DEFAULT ((uint32_t)2) #define IS_I2S_AUDIO_FREQ(FREQ) ((((FREQ) >= I2S_AUDIOFREQ_8K) && \ ((FREQ) <= I2S_AUDIOFREQ_192K)) || \ ((FREQ) == I2S_AUDIOFREQ_DEFAULT)) /** * @} */ /** @defgroup I2S_Clock_Polarity I2S Clock Polarity * @{ */ #define I2S_CPOL_LOW ((uint32_t)0x00000000) #define I2S_CPOL_HIGH ((uint32_t)SPI_I2SCFGR_CKPOL) #define IS_I2S_CPOL(CPOL) (((CPOL) == I2S_CPOL_LOW) || \ ((CPOL) == I2S_CPOL_HIGH)) /** * @} */ /** @defgroup I2S_Interrupt_configuration_definition I2S Interrupt configuration definition * @{ */ #define I2S_IT_TXE SPI_CR2_TXEIE #define I2S_IT_RXNE SPI_CR2_RXNEIE #define I2S_IT_ERR SPI_CR2_ERRIE /** * @} */ /** @defgroup I2S_Flag_definition I2S Flag definition * @{ */ #define I2S_FLAG_TXE SPI_SR_TXE #define I2S_FLAG_RXNE SPI_SR_RXNE #define I2S_FLAG_UDR SPI_SR_UDR #define I2S_FLAG_OVR SPI_SR_OVR #define I2S_FLAG_FRE SPI_SR_FRE #define I2S_FLAG_CHSIDE SPI_SR_CHSIDE #define I2S_FLAG_BSY SPI_SR_BSY /** * @} */ /** * @} */ /* Exported macros -----------------------------------------------------------*/ /** @defgroup I2S_Exported_macros I2S Exported Macros * @{ */ /** @brief Reset I2S handle state * @param __HANDLE__: I2S handle. * @retval None */ #define __HAL_I2S_RESET_HANDLE_STATE(__HANDLE__) ((__HANDLE__)->State = HAL_I2S_STATE_RESET) /** @brief Enable or disable the specified SPI peripheral (in I2S mode). * @param __HANDLE__: specifies the I2S Handle. * @retval None */ #define __HAL_I2S_ENABLE(__HANDLE__) ((__HANDLE__)->Instance->I2SCFGR |= SPI_I2SCFGR_I2SE) #define __HAL_I2S_DISABLE(__HANDLE__) ((__HANDLE__)->Instance->I2SCFGR &= (uint16_t)(~SPI_I2SCFGR_I2SE)) /** @brief Enable or disable the specified I2S interrupts. * @param __HANDLE__: specifies the I2S Handle. * @param __INTERRUPT__: specifies the interrupt source to enable or disable. * This parameter can be one of the following values: * @arg I2S_IT_TXE: Tx buffer empty interrupt enable * @arg I2S_IT_RXNE: RX buffer not empty interrupt enable * @arg I2S_IT_ERR: Error interrupt enable * @retval None */ #define __HAL_I2S_ENABLE_IT(__HANDLE__, __INTERRUPT__) ((__HANDLE__)->Instance->CR2 |= (__INTERRUPT__)) #define __HAL_I2S_DISABLE_IT(__HANDLE__, __INTERRUPT__) ((__HANDLE__)->Instance->CR2 &= (uint16_t)(~(__INTERRUPT__))) /** @brief Checks if the specified I2S interrupt source is enabled or disabled. * @param __HANDLE__: specifies the I2S Handle. * This parameter can be I2S where x: 1, 2, or 3 to select the I2S peripheral. * @param __INTERRUPT__: specifies the I2S interrupt source to check. * This parameter can be one of the following values: * @arg I2S_IT_TXE: Tx buffer empty interrupt enable * @arg I2S_IT_RXNE: RX buffer not empty interrupt enable * @arg I2S_IT_ERR: Error interrupt enable * @retval The new state of __IT__ (TRUE or FALSE). */ #define __HAL_I2S_GET_IT_SOURCE(__HANDLE__, __INTERRUPT__) ((((__HANDLE__)->Instance->CR2 & (__INTERRUPT__)) == (__INTERRUPT__)) ? SET : RESET) /** @brief Checks whether the specified I2S flag is set or not. * @param __HANDLE__: specifies the I2S Handle. * @param __FLAG__: specifies the flag to check. * This parameter can be one of the following values: * @arg I2S_FLAG_RXNE: Receive buffer not empty flag * @arg I2S_FLAG_TXE: Transmit buffer empty flag * @arg I2S_FLAG_UDR: Underrun flag * @arg I2S_FLAG_OVR: Overrun flag * @arg I2S_FLAG_FRE: Frame error flag * @arg I2S_FLAG_CHSIDE: Channel Side flag * @arg I2S_FLAG_BSY: Busy flag * @retval The new state of __FLAG__ (TRUE or FALSE). */ #define __HAL_I2S_GET_FLAG(__HANDLE__, __FLAG__) ((((__HANDLE__)->Instance->SR) & (__FLAG__)) == (__FLAG__)) /** @brief Clears the I2S OVR pending flag. * @param __HANDLE__: specifies the I2S Handle. * @retval None */ #define __HAL_I2S_CLEAR_OVRFLAG(__HANDLE__) do{ \ __IO uint32_t tmpreg; \ tmpreg = (__HANDLE__)->Instance->DR; \ tmpreg = (__HANDLE__)->Instance->SR; \ UNUSED(tmpreg); \ }while(0) /** @brief Clears the I2S UDR pending flag. * @param __HANDLE__: specifies the I2S Handle. * @retval None */ #define __HAL_I2S_CLEAR_UDRFLAG(__HANDLE__) do{\ __IO uint32_t tmpreg;\ tmpreg = ((__HANDLE__)->Instance->SR);\ UNUSED(tmpreg); \ }while(0) /** * @} */ /* Exported functions --------------------------------------------------------*/ /** @addtogroup I2S_Exported_Functions * @{ */ /** @addtogroup I2S_Exported_Functions_Group1 * @{ */ /* Initialization/de-initialization functions **********************************/ HAL_StatusTypeDef HAL_I2S_Init(I2S_HandleTypeDef *hi2s); HAL_StatusTypeDef HAL_I2S_DeInit (I2S_HandleTypeDef *hi2s); void HAL_I2S_MspInit(I2S_HandleTypeDef *hi2s); void HAL_I2S_MspDeInit(I2S_HandleTypeDef *hi2s); /** * @} */ /** @addtogroup I2S_Exported_Functions_Group2 * @{ */ /* I/O operation functions ***************************************************/ /* Blocking mode: Polling */ HAL_StatusTypeDef HAL_I2S_Transmit(I2S_HandleTypeDef *hi2s, uint16_t *pData, uint16_t Size, uint32_t Timeout); HAL_StatusTypeDef HAL_I2S_Receive(I2S_HandleTypeDef *hi2s, uint16_t *pData, uint16_t Size, uint32_t Timeout); /* Non-Blocking mode: Interrupt */ HAL_StatusTypeDef HAL_I2S_Transmit_IT(I2S_HandleTypeDef *hi2s, uint16_t *pData, uint16_t Size); HAL_StatusTypeDef HAL_I2S_Receive_IT(I2S_HandleTypeDef *hi2s, uint16_t *pData, uint16_t Size); void HAL_I2S_IRQHandler(I2S_HandleTypeDef *hi2s); /* Non-Blocking mode: DMA */ HAL_StatusTypeDef HAL_I2S_Transmit_DMA(I2S_HandleTypeDef *hi2s, uint16_t *pData, uint16_t Size); HAL_StatusTypeDef HAL_I2S_Receive_DMA(I2S_HandleTypeDef *hi2s, uint16_t *pData, uint16_t Size); HAL_StatusTypeDef HAL_I2S_DMAPause(I2S_HandleTypeDef *hi2s); HAL_StatusTypeDef HAL_I2S_DMAResume(I2S_HandleTypeDef *hi2s); HAL_StatusTypeDef HAL_I2S_DMAStop(I2S_HandleTypeDef *hi2s); /* Callbacks used in non blocking modes (Interrupt and DMA) *******************/ void HAL_I2S_TxHalfCpltCallback(I2S_HandleTypeDef *hi2s); void HAL_I2S_TxCpltCallback(I2S_HandleTypeDef *hi2s); void HAL_I2S_RxHalfCpltCallback(I2S_HandleTypeDef *hi2s); void HAL_I2S_RxCpltCallback(I2S_HandleTypeDef *hi2s); void HAL_I2S_ErrorCallback(I2S_HandleTypeDef *hi2s); /** * @} */ /** @addtogroup I2S_Exported_Functions_Group3 * @{ */ /* Peripheral Control and State functions ************************************/ HAL_I2S_StateTypeDef HAL_I2S_GetState(I2S_HandleTypeDef *hi2s); uint32_t HAL_I2S_GetError(I2S_HandleTypeDef *hi2s); /** * @} */ /** * @} */ /** * @} */ /** * @} */ #endif /* defined(STM32F031x6) || defined(STM32F038xx) || */ /* defined(STM32F051x8) || defined(STM32F058xx) || */ /* defined(STM32F071xB) || defined(STM32F072xB) || defined(STM32F078xx) ||*/ /* defined(STM32F042x6) || defined(STM32F048xx) || */ /* defined(STM32F091xC) || defined(STM32F098xx) */ #ifdef __cplusplus } #endif #endif /* __STM32F0xx_HAL_I2S_H */ /************************ (C) COPYRIGHT STMicroelectronics *****END OF FILE****/ ================================================ FILE: Zelig/mbed/TARGET_NUCLEO_F091RC/stm32f0xx_hal_irda.h ================================================ /** ****************************************************************************** * @file stm32f0xx_hal_irda.h * @author MCD Application Team * @version V1.3.0 * @date 26-June-2015 * @brief This file contains all the functions prototypes for the IRDA * firmware library. ****************************************************************************** * @attention * *

© COPYRIGHT(c) 2015 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. * ****************************************************************************** */ /* Define to prevent recursive inclusion -------------------------------------*/ #ifndef __STM32F0xx_HAL_IRDA_H #define __STM32F0xx_HAL_IRDA_H #ifdef __cplusplus extern "C" { #endif #if !defined(STM32F030x6) && !defined(STM32F030x8) && !defined(STM32F070x6) && !defined(STM32F070xB) && !defined(STM32F030xC) /* Includes ------------------------------------------------------------------*/ #include "stm32f0xx_hal_def.h" /** @addtogroup STM32F0xx_HAL_Driver * @{ */ /** @addtogroup IRDA * @{ */ /* Exported types ------------------------------------------------------------*/ /** @defgroup IRDA_Exported_Types IRDA Exported Types * @{ */ /** * @brief IRDA Init Structure definition */ typedef struct { uint32_t BaudRate; /*!< This member configures the IRDA communication baud rate. The baud rate register is computed using the following formula: Baud Rate Register = ((PCLKx) / ((hirda->Init.BaudRate))) */ uint32_t WordLength; /*!< Specifies the number of data bits transmitted or received in a frame. This parameter can be a value of @ref IRDAEx_Word_Length */ uint32_t Parity; /*!< Specifies the parity mode. This parameter can be a value of @ref IRDA_Parity @note When parity is enabled, the computed parity is inserted at the MSB position of the transmitted data (9th bit when the word length is set to 9 data bits; 8th bit when the word length is set to 8 data bits). */ uint32_t Mode; /*!< Specifies whether the Receive or Transmit mode is enabled or disabled. This parameter can be a value of @ref IRDA_Mode */ uint8_t Prescaler; /*!< Specifies the Prescaler value for dividing the UART/USART source clock to achieve low-power frequency. @note Prescaler value 0 is forbidden */ uint16_t PowerMode; /*!< Specifies the IRDA power mode. This parameter can be a value of @ref IRDA_Low_Power */ }IRDA_InitTypeDef; /** * @brief HAL IRDA State structures definition */ typedef enum { HAL_IRDA_STATE_RESET = 0x00, /*!< Peripheral is not initialized */ HAL_IRDA_STATE_READY = 0x01, /*!< Peripheral Initialized and ready for use */ HAL_IRDA_STATE_BUSY = 0x02, /*!< an internal process is ongoing */ HAL_IRDA_STATE_BUSY_TX = 0x12, /*!< Data Transmission process is ongoing */ HAL_IRDA_STATE_BUSY_RX = 0x22, /*!< Data Reception process is ongoing */ HAL_IRDA_STATE_BUSY_TX_RX = 0x32, /*!< Data Transmission and Reception process is ongoing */ HAL_IRDA_STATE_TIMEOUT = 0x03, /*!< Timeout state */ HAL_IRDA_STATE_ERROR = 0x04 /*!< Error */ }HAL_IRDA_StateTypeDef; /** * @brief IRDA clock sources definition */ typedef enum { IRDA_CLOCKSOURCE_PCLK1 = 0x00, /*!< PCLK1 clock source */ IRDA_CLOCKSOURCE_HSI = 0x02, /*!< HSI clock source */ IRDA_CLOCKSOURCE_SYSCLK = 0x04, /*!< SYSCLK clock source */ IRDA_CLOCKSOURCE_LSE = 0x08, /*!< LSE clock source */ IRDA_CLOCKSOURCE_UNDEFINED = 0x10 /*!< undefined clock source */ }IRDA_ClockSourceTypeDef; /** * @brief IRDA handle Structure definition */ typedef struct { USART_TypeDef *Instance; /*!< USART registers base address */ IRDA_InitTypeDef Init; /*!< IRDA communication parameters */ uint8_t *pTxBuffPtr; /*!< Pointer to IRDA Tx transfer Buffer */ uint16_t TxXferSize; /*!< IRDA Tx Transfer size */ uint16_t TxXferCount; /*!< IRDA Tx Transfer Counter */ uint8_t *pRxBuffPtr; /*!< Pointer to IRDA Rx transfer Buffer */ uint16_t RxXferSize; /*!< IRDA Rx Transfer size */ uint16_t RxXferCount; /*!< IRDA Rx Transfer Counter */ uint16_t Mask; /*!< USART RX RDR register mask */ DMA_HandleTypeDef *hdmatx; /*!< IRDA Tx DMA Handle parameters */ DMA_HandleTypeDef *hdmarx; /*!< IRDA Rx DMA Handle parameters */ HAL_LockTypeDef Lock; /*!< Locking object */ __IO HAL_IRDA_StateTypeDef State; /*!< IRDA communication state */ __IO uint32_t ErrorCode; /*!< IRDA Error code This parameter can be a value of @ref IRDA_Error */ }IRDA_HandleTypeDef; /** * @brief IRDA Configuration enumeration values definition */ typedef enum { IRDA_BAUDRATE = 0x00, /*!< IRDA Baud rate */ IRDA_PARITY = 0x01, /*!< IRDA frame parity */ IRDA_WORDLENGTH = 0x02, /*!< IRDA frame length */ IRDA_MODE = 0x03, /*!< IRDA communication mode */ IRDA_PRESCALER = 0x04, /*!< IRDA prescaling */ IRDA_POWERMODE = 0x05 /*!< IRDA power mode */ }IRDA_ControlTypeDef; /** * @} */ /* Exported constants --------------------------------------------------------*/ /** @defgroup IRDA_Exported_Constants IRDA Exported Constants * @{ */ /** @defgroup IRDA_Error IRDA Error * @{ */ #define HAL_IRDA_ERROR_NONE ((uint32_t)0x00000000) /*!< No error */ #define HAL_IRDA_ERROR_PE ((uint32_t)0x00000001) /*!< Parity error */ #define HAL_IRDA_ERROR_NE ((uint32_t)0x00000002) /*!< Noise error */ #define HAL_IRDA_ERROR_FE ((uint32_t)0x00000004) /*!< frame error */ #define HAL_IRDA_ERROR_ORE ((uint32_t)0x00000008) /*!< Overrun error */ #define HAL_IRDA_ERROR_DMA ((uint32_t)0x00000010) /*!< DMA transfer error */ /** * @} */ /** @defgroup IRDA_Parity IRDA Parity * @{ */ #define IRDA_PARITY_NONE ((uint32_t)0x00000000) /*!< No parity */ #define IRDA_PARITY_EVEN ((uint32_t)USART_CR1_PCE) /*!< Even parity */ #define IRDA_PARITY_ODD ((uint32_t)(USART_CR1_PCE | USART_CR1_PS)) /*!< Odd parity */ /** * @} */ /** @defgroup IRDA_Transfer_Mode IRDA Transfer Mode * @{ */ #define IRDA_MODE_RX ((uint32_t)USART_CR1_RE) /*!< RX mode */ #define IRDA_MODE_TX ((uint32_t)USART_CR1_TE) /*!< TX mode */ #define IRDA_MODE_TX_RX ((uint32_t)(USART_CR1_TE |USART_CR1_RE)) /*!< RX and TX mode */ /** * @} */ /** @defgroup IRDA_Low_Power IRDA Low Power * @{ */ #define IRDA_POWERMODE_NORMAL ((uint32_t)0x00000000) /*!< IRDA normal power mode */ #define IRDA_POWERMODE_LOWPOWER ((uint32_t)USART_CR3_IRLP) /*!< IRDA low power mode */ /** * @} */ /** @defgroup IRDA_State IRDA State * @{ */ #define IRDA_STATE_DISABLE ((uint32_t)0x00000000) /*!< IRDA disabled */ #define IRDA_STATE_ENABLE ((uint32_t)USART_CR1_UE) /*!< IRDA enabled */ /** * @} */ /** @defgroup IRDA_Mode IRDA Mode * @{ */ #define IRDA_MODE_DISABLE ((uint32_t)0x00000000) /*!< Associated UART disabled in IRDA mode */ #define IRDA_MODE_ENABLE ((uint32_t)USART_CR3_IREN) /*!< Associated UART enabled in IRDA mode */ /** * @} */ /** @defgroup IRDA_One_Bit IRDA One Bit Sampling * @{ */ #define IRDA_ONE_BIT_SAMPLE_DISABLE ((uint32_t)0x00000000) /*!< One-bit sampling disabled */ #define IRDA_ONE_BIT_SAMPLE_ENABLE ((uint32_t)USART_CR3_ONEBIT) /*!< One-bit sampling enabled */ /** * @} */ /** @defgroup IRDA_DMA_Tx IRDA DMA Tx * @{ */ #define IRDA_DMA_TX_DISABLE ((uint32_t)0x00000000) /*!< IRDA DMA TX disabled */ #define IRDA_DMA_TX_ENABLE ((uint32_t)USART_CR3_DMAT) /*!< IRDA DMA TX enabled */ /** * @} */ /** @defgroup IRDA_DMA_Rx IRDA DMA Rx * @{ */ #define IRDA_DMA_RX_DISABLE ((uint32_t)0x00000000) /*!< IRDA DMA RX disabled */ #define IRDA_DMA_RX_ENABLE ((uint32_t)USART_CR3_DMAR) /*!< IRDA DMA RX enabled */ /** * @} */ /** @defgroup IRDA_Request_Parameters IRDA Request Parameters * @{ */ #define IRDA_AUTOBAUD_REQUEST ((uint32_t)USART_RQR_ABRRQ) /*!< Auto-Baud Rate Request */ #define IRDA_RXDATA_FLUSH_REQUEST ((uint32_t)USART_RQR_RXFRQ) /*!< Receive Data flush Request */ #define IRDA_TXDATA_FLUSH_REQUEST ((uint32_t)USART_RQR_TXFRQ) /*!< Transmit data flush Request */ /** * @} */ /** @defgroup IRDA_Flags IRDA Flags * Elements values convention: 0xXXXX * - 0xXXXX : Flag mask in the ISR register * @{ */ #define IRDA_FLAG_REACK ((uint32_t)0x00400000) /*!< IRDA Receive enable acknowledge flag */ #define IRDA_FLAG_TEACK ((uint32_t)0x00200000) /*!< IRDA Transmit enable acknowledge flag */ #define IRDA_FLAG_BUSY ((uint32_t)0x00010000) /*!< IRDA Busy flag */ #define IRDA_FLAG_ABRF ((uint32_t)0x00008000) /*!< IRDA Auto baud rate flag */ #define IRDA_FLAG_ABRE ((uint32_t)0x00004000) /*!< IRDA Auto baud rate error */ #define IRDA_FLAG_TXE ((uint32_t)0x00000080) /*!< IRDA Transmit data register empty */ #define IRDA_FLAG_TC ((uint32_t)0x00000040) /*!< IRDA Transmission complete */ #define IRDA_FLAG_RXNE ((uint32_t)0x00000020) /*!< IRDA Read data register not empty */ #define IRDA_FLAG_ORE ((uint32_t)0x00000008) /*!< IRDA Overrun error */ #define IRDA_FLAG_NE ((uint32_t)0x00000004) /*!< IRDA Noise error */ #define IRDA_FLAG_FE ((uint32_t)0x00000002) /*!< IRDA Noise error */ #define IRDA_FLAG_PE ((uint32_t)0x00000001) /*!< IRDA Parity error */ /** * @} */ /** @defgroup IRDA_Interrupt_definition IRDA Interrupts Definition * Elements values convention: 0000ZZZZ0XXYYYYYb * - YYYYY : Interrupt source position in the XX register (5bits) * - XX : Interrupt source register (2bits) * - 01: CR1 register * - 10: CR2 register * - 11: CR3 register * - ZZZZ : Flag position in the ISR register(4bits) * @{ */ #define IRDA_IT_PE ((uint16_t)0x0028) /*!< IRDA Parity error interruption */ #define IRDA_IT_TXE ((uint16_t)0x0727) /*!< IRDA Transmit data register empty interruption */ #define IRDA_IT_TC ((uint16_t)0x0626) /*!< IRDA Transmission complete interruption */ #define IRDA_IT_RXNE ((uint16_t)0x0525) /*!< IRDA Read data register not empty interruption */ #define IRDA_IT_IDLE ((uint16_t)0x0424) /*!< IRDA Idle interruption */ /** Elements values convention: 000000000XXYYYYYb * - YYYYY : Interrupt source position in the XX register (5bits) * - XX : Interrupt source register (2bits) * - 01: CR1 register * - 10: CR2 register * - 11: CR3 register */ #define IRDA_IT_ERR ((uint16_t)0x0060) /*!< IRDA Error interruption */ /** Elements values convention: 0000ZZZZ00000000b * - ZZZZ : Flag position in the ISR register(4bits) */ #define IRDA_IT_ORE ((uint16_t)0x0300) /*!< IRDA Overrun error interruption */ #define IRDA_IT_NE ((uint16_t)0x0200) /*!< IRDA Noise error interruption */ #define IRDA_IT_FE ((uint16_t)0x0100) /*!< IRDA Frame error interruption */ /** * @} */ /** @defgroup IRDA_IT_CLEAR_Flags IRDA Interruption Clear Flags * @{ */ #define IRDA_CLEAR_PEF USART_ICR_PECF /*!< Parity Error Clear Flag */ #define IRDA_CLEAR_FEF USART_ICR_FECF /*!< Framing Error Clear Flag */ #define IRDA_CLEAR_NEF USART_ICR_NCF /*!< Noise detected Clear Flag */ #define IRDA_CLEAR_OREF USART_ICR_ORECF /*!< OverRun Error Clear Flag */ #define IRDA_CLEAR_TCF USART_ICR_TCCF /*!< Transmission Complete Clear Flag */ /** * @} */ /** @defgroup IRDA_Interruption_Mask IRDA interruptions flags mask * @{ */ #define IRDA_IT_MASK ((uint16_t)0x001F) /*!< IRDA Interruptions flags mask */ /** * @} */ /** * @} */ /* Exported macros -----------------------------------------------------------*/ /** @defgroup IRDA_Exported_Macros IRDA Exported Macros * @{ */ /** @brief Reset IRDA handle state. * @param __HANDLE__: IRDA handle. * @retval None */ #define __HAL_IRDA_RESET_HANDLE_STATE(__HANDLE__) ((__HANDLE__)->State = HAL_IRDA_STATE_RESET) /** @brief Flush the IRDA DR register. * @param __HANDLE__: specifies the IRDA Handle. * @retval None */ #define __HAL_IRDA_FLUSH_DRREGISTER(__HANDLE__) \ do{ \ SET_BIT((__HANDLE__)->Instance->RQR, IRDA_RXDATA_FLUSH_REQUEST); \ SET_BIT((__HANDLE__)->Instance->RQR, IRDA_TXDATA_FLUSH_REQUEST); \ } while(0) /** @brief Clear the specified IRDA pending flag. * @param __HANDLE__: specifies the IRDA Handle. * @param __FLAG__: specifies the flag to check. * This parameter can be any combination of the following values: * @arg IRDA_CLEAR_PEF * @arg IRDA_CLEAR_FEF * @arg IRDA_CLEAR_NEF * @arg IRDA_CLEAR_OREF * @arg IRDA_CLEAR_TCF * @arg IRDA_CLEAR_IDLEF * @retval None */ #define __HAL_IRDA_CLEAR_FLAG(__HANDLE__, __FLAG__) ((__HANDLE__)->Instance->ICR = (__FLAG__)) /** @brief Clear the IRDA PE pending flag. * @param __HANDLE__: specifies the IRDA Handle. * @retval None */ #define __HAL_IRDA_CLEAR_PEFLAG(__HANDLE__) __HAL_IRDA_CLEAR_FLAG((__HANDLE__), IRDA_CLEAR_PEF) /** @brief Clear the IRDA FE pending flag. * @param __HANDLE__: specifies the IRDA Handle. * @retval None */ #define __HAL_IRDA_CLEAR_FEFLAG(__HANDLE__) __HAL_IRDA_CLEAR_FLAG((__HANDLE__), IRDA_CLEAR_FEF) /** @brief Clear the IRDA NE pending flag. * @param __HANDLE__: specifies the IRDA Handle. * @retval None */ #define __HAL_IRDA_CLEAR_NEFLAG(__HANDLE__) __HAL_IRDA_CLEAR_FLAG((__HANDLE__), IRDA_CLEAR_NEF) /** @brief Clear the IRDA ORE pending flag. * @param __HANDLE__: specifies the IRDA Handle. * @retval None */ #define __HAL_IRDA_CLEAR_OREFLAG(__HANDLE__) __HAL_IRDA_CLEAR_FLAG((__HANDLE__), IRDA_CLEAR_OREF) /** @brief Clear the IRDA IDLE pending flag. * @param __HANDLE__: specifies the IRDA Handle. * @retval None */ #define __HAL_IRDA_CLEAR_IDLEFLAG(__HANDLE__) __HAL_IRDA_CLEAR_FLAG((__HANDLE__), IRDA_CLEAR_IDLEF) /** @brief Check whether the specified IRDA flag is set or not. * @param __HANDLE__: specifies the IRDA Handle. * The Handle Instance can be UARTx where x: 1, 2, 3, 4, 5 to select the USART or * UART peripheral * @param __FLAG__: specifies the flag to check. * This parameter can be one of the following values: * @arg IRDA_FLAG_REACK: Receive enable acknowledge flag * @arg IRDA_FLAG_TEACK: Transmit enable acknowledge flag * @arg IRDA_FLAG_BUSY: Busy flag * @arg IRDA_FLAG_ABRF: Auto Baud rate detection flag * @arg IRDA_FLAG_ABRE: Auto Baud rate detection error flag * @arg IRDA_FLAG_TXE: Transmit data register empty flag * @arg IRDA_FLAG_TC: Transmission Complete flag * @arg IRDA_FLAG_RXNE: Receive data register not empty flag * @arg IRDA_FLAG_IDLE: Idle Line detection flag * @arg IRDA_FLAG_ORE: OverRun Error flag * @arg IRDA_FLAG_NE: Noise Error flag * @arg IRDA_FLAG_FE: Framing Error flag * @arg IRDA_FLAG_PE: Parity Error flag * @retval The new state of __FLAG__ (TRUE or FALSE). */ #define __HAL_IRDA_GET_FLAG(__HANDLE__, __FLAG__) (((__HANDLE__)->Instance->ISR & (__FLAG__)) == (__FLAG__)) /** @brief Enable the specified IRDA interrupt. * @param __HANDLE__: specifies the IRDA Handle. * The Handle Instance can be UARTx where x: 1, 2, 3, 4, 5 to select the USART or * UART peripheral * @param __INTERRUPT__: specifies the IRDA interrupt source to enable. * This parameter can be one of the following values: * @arg IRDA_IT_TXE: Transmit Data Register empty interrupt * @arg IRDA_IT_TC: Transmission complete interrupt * @arg IRDA_IT_RXNE: Receive Data register not empty interrupt * @arg IRDA_IT_IDLE: Idle line detection interrupt * @arg IRDA_IT_PE: Parity Error interrupt * @arg IRDA_IT_ERR: Error interrupt(Frame error, noise error, overrun error) * @retval None */ #define __HAL_IRDA_ENABLE_IT(__HANDLE__, __INTERRUPT__) (((((uint8_t)(__INTERRUPT__)) >> 5U) == 1)? ((__HANDLE__)->Instance->CR1 |= (1U << ((__INTERRUPT__) & IRDA_IT_MASK))): \ ((((uint8_t)(__INTERRUPT__)) >> 5U) == 2)? ((__HANDLE__)->Instance->CR2 |= (1U << ((__INTERRUPT__) & IRDA_IT_MASK))): \ ((__HANDLE__)->Instance->CR3 |= (1U << ((__INTERRUPT__) & IRDA_IT_MASK)))) /** @brief Disable the specified IRDA interrupt. * @param __HANDLE__: specifies the IRDA Handle. * The Handle Instance can be UARTx where x: 1, 2, 3, 4, 5 to select the USART or * UART peripheral * @param __INTERRUPT__: specifies the IRDA interrupt source to disable. * This parameter can be one of the following values: * @arg IRDA_IT_TXE: Transmit Data Register empty interrupt * @arg IRDA_IT_TC: Transmission complete interrupt * @arg IRDA_IT_RXNE: Receive Data register not empty interrupt * @arg IRDA_IT_IDLE: Idle line detection interrupt * @arg IRDA_IT_PE: Parity Error interrupt * @arg IRDA_IT_ERR: Error interrupt(Frame error, noise error, overrun error) * @retval None */ #define __HAL_IRDA_DISABLE_IT(__HANDLE__, __INTERRUPT__) (((((uint8_t)(__INTERRUPT__)) >> 5U) == 1)? ((__HANDLE__)->Instance->CR1 &= ~ (1U << ((__INTERRUPT__) & IRDA_IT_MASK))): \ ((((uint8_t)(__INTERRUPT__)) >> 5U) == 2)? ((__HANDLE__)->Instance->CR2 &= ~ (1U << ((__INTERRUPT__) & IRDA_IT_MASK))): \ ((__HANDLE__)->Instance->CR3 &= ~ (1U << ((__INTERRUPT__) & IRDA_IT_MASK)))) /** @brief Check whether the specified IRDA interrupt has occurred or not. * @param __HANDLE__: specifies the IRDA Handle. * The Handle Instance can be UARTx where x: 1, 2, 3, 4, 5 to select the USART or * UART peripheral * @param __IT__: specifies the IRDA interrupt source to check. * This parameter can be one of the following values: * @arg IRDA_IT_TXE: Transmit Data Register empty interrupt * @arg IRDA_IT_TC: Transmission complete interrupt * @arg IRDA_IT_RXNE: Receive Data register not empty interrupt * @arg IRDA_IT_IDLE: Idle line detection interrupt * @arg IRDA_IT_ORE: OverRun Error interrupt * @arg IRDA_IT_NE: Noise Error interrupt * @arg IRDA_IT_FE: Framing Error interrupt * @arg IRDA_IT_PE: Parity Error interrupt * @retval The new state of __IT__ (TRUE or FALSE). */ #define __HAL_IRDA_GET_IT(__HANDLE__, __IT__) ((__HANDLE__)->Instance->ISR & ((uint32_t)1U << ((__IT__)>> 0x08))) /** @brief Check whether the specified IRDA interrupt source is enabled or not. * @param __HANDLE__: specifies the IRDA Handle. * The Handle Instance can be UARTx where x: 1, 2, 3, 4, 5 to select the USART or * UART peripheral * @param __IT__: specifies the IRDA interrupt source to check. * This parameter can be one of the following values: * @arg IRDA_IT_TXE: Transmit Data Register empty interrupt * @arg IRDA_IT_TC: Transmission complete interrupt * @arg IRDA_IT_RXNE: Receive Data register not empty interrupt * @arg IRDA_IT_IDLE: Idle line detection interrupt * @arg IRDA_IT_ORE: OverRun Error interrupt * @arg IRDA_IT_NE: Noise Error interrupt * @arg IRDA_IT_FE: Framing Error interrupt * @arg IRDA_IT_PE: Parity Error interrupt * @retval The new state of __IT__ (TRUE or FALSE). */ #define __HAL_IRDA_GET_IT_SOURCE(__HANDLE__, __IT__) ((((((uint8_t)(__IT__)) >> 5U) == 1)? (__HANDLE__)->Instance->CR1:(((((uint8_t)(__IT__)) >> 5U) == 2)? \ (__HANDLE__)->Instance->CR2 : (__HANDLE__)->Instance->CR3)) & ((uint32_t)1 << (((uint16_t)(__IT__)) & IRDA_IT_MASK))) /** @brief Clear the specified IRDA ISR flag, in setting the proper ICR register flag. * @param __HANDLE__: specifies the IRDA Handle. * The Handle Instance can be UARTx where x: 1, 2, 3, 4, 5 to select the USART or * UART peripheral * @param __IT_CLEAR__: specifies the interrupt clear register flag that needs to be set * to clear the corresponding interrupt * This parameter can be one of the following values: * @arg IRDA_CLEAR_PEF: Parity Error Clear Flag * @arg IRDA_CLEAR_FEF: Framing Error Clear Flag * @arg IRDA_CLEAR_NEF: Noise detected Clear Flag * @arg IRDA_CLEAR_OREF: OverRun Error Clear Flag * @arg IRDA_CLEAR_TCF: Transmission Complete Clear Flag * @retval None */ #define __HAL_IRDA_CLEAR_IT(__HANDLE__, __IT_CLEAR__) ((__HANDLE__)->Instance->ICR = (uint32_t)(__IT_CLEAR__)) /** @brief Set a specific IRDA request flag. * @param __HANDLE__: specifies the IRDA Handle. * The Handle Instance can be UARTx where x: 1, 2, 3, 4, 5 to select the USART or * UART peripheral * @param __REQ__: specifies the request flag to set * This parameter can be one of the following values: * @arg IRDA_AUTOBAUD_REQUEST: Auto-Baud Rate Request * @arg IRDA_RXDATA_FLUSH_REQUEST: Receive Data flush Request * @arg IRDA_TXDATA_FLUSH_REQUEST: Transmit data flush Request * * @retval None */ #define __HAL_IRDA_SEND_REQ(__HANDLE__, __REQ__) ((__HANDLE__)->Instance->RQR |= (uint16_t)(__REQ__)) /** @brief Enable the IRDA one bit sample method. * @param __HANDLE__: specifies the IRDA Handle. * The Handle Instance can be UARTx where x: 1, 2, 3, 4, 5 to select the USART or * UART peripheral * @retval None */ #define __HAL_IRDA_ONE_BIT_SAMPLE_ENABLE(__HANDLE__) ((__HANDLE__)->Instance->CR3|= USART_CR3_ONEBIT) /** @brief Disable the IRDA one bit sample method. * @param __HANDLE__: specifies the IRDA Handle. * The Handle Instance can be UARTx where x: 1, 2, 3, 4, 5 to select the USART or * UART peripheral * @retval None */ #define __HAL_IRDA_ONE_BIT_SAMPLE_DISABLE(__HANDLE__) ((__HANDLE__)->Instance->CR3 &= (uint32_t)~((uint32_t)USART_CR3_ONEBIT)) /** @brief Enable UART/USART associated to IRDA Handle. * @param __HANDLE__: specifies the IRDA Handle. * The Handle Instance can be UARTx where x: 1, 2, 3, 4, 5 to select the USART or * UART peripheral * @retval None */ #define __HAL_IRDA_ENABLE(__HANDLE__) ((__HANDLE__)->Instance->CR1 |= USART_CR1_UE) /** @brief Disable UART/USART associated to IRDA Handle. * @param __HANDLE__: specifies the IRDA Handle. * The Handle Instance can be UARTx where x: 1, 2, 3, 4, 5 to select the USART or * UART peripheral * @retval None */ #define __HAL_IRDA_DISABLE(__HANDLE__) ((__HANDLE__)->Instance->CR1 &= ~USART_CR1_UE) /** * @} */ /* Private macros --------------------------------------------------------*/ /** @defgroup IRDA_Private_Macros IRDA Private Macros * @{ */ /** @brief Ensure that IRDA Baud rate is less or equal to maximum value. * @param __BAUDRATE__: specifies the IRDA Baudrate set by the user. * @retval True or False */ #define IS_IRDA_BAUDRATE(__BAUDRATE__) ((__BAUDRATE__) < 115201) /** @brief Ensure that IRDA prescaler value is strictly larger than 0. * @param __PRESCALER__: specifies the IRDA prescaler value set by the user. * @retval True or False */ #define IS_IRDA_PRESCALER(__PRESCALER__) ((__PRESCALER__) > 0) /** * @brief Ensure that IRDA frame parity is valid. * @param __PARITY__: IRDA frame parity. * @retval SET (__PARITY__ is valid) or RESET (__PARITY__ is invalid) */ #define IS_IRDA_PARITY(__PARITY__) (((__PARITY__) == IRDA_PARITY_NONE) || \ ((__PARITY__) == IRDA_PARITY_EVEN) || \ ((__PARITY__) == IRDA_PARITY_ODD)) /** * @brief Ensure that IRDA communication mode is valid. * @param __MODE__: IRDA communication mode. * @retval SET (__MODE__ is valid) or RESET (__MODE__ is invalid) */ #define IS_IRDA_TX_RX_MODE(__MODE__) ((((__MODE__) & (~((uint32_t)(IRDA_MODE_TX_RX)))) == (uint32_t)0x00) && ((__MODE__) != (uint32_t)0x00)) /** * @brief Ensure that IRDA power mode is valid. * @param __MODE__: IRDA power mode. * @retval SET (__MODE__ is valid) or RESET (__MODE__ is invalid) */ #define IS_IRDA_POWERMODE(__MODE__) (((__MODE__) == IRDA_POWERMODE_LOWPOWER) || \ ((__MODE__) == IRDA_POWERMODE_NORMAL)) /** * @brief Ensure that IRDA state is valid. * @param __STATE__: IRDA state mode. * @retval SET (__STATE__ is valid) or RESET (__STATE__ is invalid) */ #define IS_IRDA_STATE(__STATE__) (((__STATE__) == IRDA_STATE_DISABLE) || \ ((__STATE__) == IRDA_STATE_ENABLE)) /** * @brief Ensure that IRDA associated UART/USART mode is valid. * @param __MODE__: IRDA associated UART/USART mode. * @retval SET (__MODE__ is valid) or RESET (__MODE__ is invalid) */ #define IS_IRDA_MODE(__MODE__) (((__MODE__) == IRDA_MODE_DISABLE) || \ ((__MODE__) == IRDA_MODE_ENABLE)) /** * @brief Ensure that IRDA sampling rate is valid. * @param __ONEBIT__: IRDA sampling rate. * @retval SET (__ONEBIT__ is valid) or RESET (__ONEBIT__ is invalid) */ #define IS_IRDA_ONE_BIT_SAMPLE(__ONEBIT__) (((__ONEBIT__) == IRDA_ONE_BIT_SAMPLE_DISABLE) || \ ((__ONEBIT__) == IRDA_ONE_BIT_SAMPLE_ENABLE)) /** * @brief Ensure that IRDA DMA TX mode is valid. * @param __DMATX__: IRDA DMA TX mode. * @retval SET (__DMATX__ is valid) or RESET (__DMATX__ is invalid) */ #define IS_IRDA_DMA_TX(__DMATX__) (((__DMATX__) == IRDA_DMA_TX_DISABLE) || \ ((__DMATX__) == IRDA_DMA_TX_ENABLE)) /** * @brief Ensure that IRDA DMA RX mode is valid. * @param __DMARX__: IRDA DMA RX mode. * @retval SET (__DMARX__ is valid) or RESET (__DMARX__ is invalid) */ #define IS_IRDA_DMA_RX(__DMARX__) (((__DMARX__) == IRDA_DMA_RX_DISABLE) || \ ((__DMARX__) == IRDA_DMA_RX_ENABLE)) /** * @brief Ensure that IRDA request is valid. * @param __PARAM__: IRDA request. * @retval SET (__PARAM__ is valid) or RESET (__PARAM__ is invalid) */ #define IS_IRDA_REQUEST_PARAMETER(__PARAM__) (((__PARAM__) == IRDA_AUTOBAUD_REQUEST) || \ ((__PARAM__) == IRDA_RXDATA_FLUSH_REQUEST) || \ ((__PARAM__) == IRDA_TXDATA_FLUSH_REQUEST)) /** * @} */ /* Include IRDA HAL Extended module */ #include "stm32f0xx_hal_irda_ex.h" /* Exported functions --------------------------------------------------------*/ /** @addtogroup IRDA_Exported_Functions IRDA Exported Functions * @{ */ /** @addtogroup IRDA_Exported_Functions_Group1 Initialization and de-initialization functions * @{ */ /* Initialization and de-initialization functions ****************************/ HAL_StatusTypeDef HAL_IRDA_Init(IRDA_HandleTypeDef *hirda); HAL_StatusTypeDef HAL_IRDA_DeInit(IRDA_HandleTypeDef *hirda); void HAL_IRDA_MspInit(IRDA_HandleTypeDef *hirda); void HAL_IRDA_MspDeInit(IRDA_HandleTypeDef *hirda); /** * @} */ /** @addtogroup IRDA_Exported_Functions_Group2 IO operation functions * @{ */ /* IO operation functions *****************************************************/ HAL_StatusTypeDef HAL_IRDA_Transmit(IRDA_HandleTypeDef *hirda, uint8_t *pData, uint16_t Size, uint32_t Timeout); HAL_StatusTypeDef HAL_IRDA_Receive(IRDA_HandleTypeDef *hirda, uint8_t *pData, uint16_t Size, uint32_t Timeout); HAL_StatusTypeDef HAL_IRDA_Transmit_IT(IRDA_HandleTypeDef *hirda, uint8_t *pData, uint16_t Size); HAL_StatusTypeDef HAL_IRDA_Receive_IT(IRDA_HandleTypeDef *hirda, uint8_t *pData, uint16_t Size); HAL_StatusTypeDef HAL_IRDA_Transmit_DMA(IRDA_HandleTypeDef *hirda, uint8_t *pData, uint16_t Size); HAL_StatusTypeDef HAL_IRDA_Receive_DMA(IRDA_HandleTypeDef *hirda, uint8_t *pData, uint16_t Size); HAL_StatusTypeDef HAL_IRDA_DMAPause(IRDA_HandleTypeDef *hirda); HAL_StatusTypeDef HAL_IRDA_DMAResume(IRDA_HandleTypeDef *hirda); HAL_StatusTypeDef HAL_IRDA_DMAStop(IRDA_HandleTypeDef *hirda); void HAL_IRDA_IRQHandler(IRDA_HandleTypeDef *hirda); void HAL_IRDA_TxCpltCallback(IRDA_HandleTypeDef *hirda); void HAL_IRDA_RxCpltCallback(IRDA_HandleTypeDef *hirda); void HAL_IRDA_TxHalfCpltCallback(IRDA_HandleTypeDef *hirda); void HAL_IRDA_RxHalfCpltCallback(IRDA_HandleTypeDef *hirda); void HAL_IRDA_ErrorCallback(IRDA_HandleTypeDef *hirda); /** * @} */ /* Peripheral Control functions ************************************************/ /** @addtogroup IRDA_Exported_Functions_Group3 Peripheral State and Error functions * @{ */ /* Peripheral State and Error functions ***************************************/ HAL_IRDA_StateTypeDef HAL_IRDA_GetState(IRDA_HandleTypeDef *hirda); uint32_t HAL_IRDA_GetError(IRDA_HandleTypeDef *hirda); /** * @} */ /** * @} */ /** * @} */ /** * @} */ #endif /* !defined(STM32F030x6) && !defined(STM32F030x8) && !defined(STM32F070x6) && !defined(STM32F070xB) && !defined(STM32F030xC) */ #ifdef __cplusplus } #endif #endif /* __STM32F0xx_HAL_IRDA_H */ /************************ (C) COPYRIGHT STMicroelectronics *****END OF FILE****/ ================================================ FILE: Zelig/mbed/TARGET_NUCLEO_F091RC/stm32f0xx_hal_irda_ex.h ================================================ /** ****************************************************************************** * @file stm32f0xx_hal_irda_ex.h * @author MCD Application Team * @version V1.3.0 * @date 26-June-2015 * @brief Header file of IRDA HAL Extension module. ****************************************************************************** * @attention * *

© COPYRIGHT(c) 2015 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. * ****************************************************************************** */ /* Define to prevent recursive inclusion -------------------------------------*/ #ifndef __STM32F0xx_HAL_IRDA_EX_H #define __STM32F0xx_HAL_IRDA_EX_H #ifdef __cplusplus extern "C" { #endif #if !defined(STM32F030x6) && !defined(STM32F030x8) && !defined(STM32F070x6) && !defined(STM32F070xB) && !defined(STM32F030xC) /* Includes ------------------------------------------------------------------*/ #include "stm32f0xx_hal_def.h" /** @addtogroup STM32F0xx_HAL_Driver * @{ */ /** @addtogroup IRDAEx IRDAEx * @{ */ /* Exported types ------------------------------------------------------------*/ /* Exported constants --------------------------------------------------------*/ /** @defgroup IRDAEx_Exported_Constants IRDAEx Exported Constants * @{ */ /** @defgroup IRDAEx_Word_Length IRDA Word Length * @{ */ #if defined (STM32F042x6) || defined (STM32F048xx) || \ defined (STM32F071xB) || defined (STM32F072xB) || defined (STM32F078xx) || \ defined (STM32F091xC) || defined (STM32F098xx) #define IRDA_WORDLENGTH_7B ((uint32_t)USART_CR1_M1) /*!< 7-bit long frame */ #define IRDA_WORDLENGTH_8B ((uint32_t)0x00000000) /*!< 8-bit long frame */ #define IRDA_WORDLENGTH_9B ((uint32_t)USART_CR1_M0) /*!< 9-bit long frame */ #else #define IRDA_WORDLENGTH_8B ((uint32_t)0x00000000) /*!< 8-bit long frame */ #define IRDA_WORDLENGTH_9B ((uint32_t)USART_CR1_M) /*!< 9-bit long frame */ #endif /* defined (STM32F042x6) || defined (STM32F048xx) || \ defined (STM32F071xB) || defined (STM32F072xB) || defined (STM32F078xx) || \ defined (STM32F091xC) || defined (STM32F098xx)*/ /** * @} */ /** * @} */ /* Exported macros -----------------------------------------------------------*/ /* Exported functions --------------------------------------------------------*/ /* Private macros ------------------------------------------------------------*/ /** @defgroup IRDAEx_Private_Macros IRDAEx Private Macros * @{ */ /** @brief Report the IRDA clock source. * @param __HANDLE__: specifies the IRDA Handle. * @param __CLOCKSOURCE__: output variable. * @retval IRDA clocking source, written in __CLOCKSOURCE__. */ #if defined(STM32F031x6) || defined(STM32F038xx) #define IRDA_GETCLOCKSOURCE(__HANDLE__,__CLOCKSOURCE__) \ do { \ switch(__HAL_RCC_GET_USART1_SOURCE()) \ { \ case RCC_USART1CLKSOURCE_PCLK1: \ (__CLOCKSOURCE__) = IRDA_CLOCKSOURCE_PCLK1; \ break; \ case RCC_USART1CLKSOURCE_HSI: \ (__CLOCKSOURCE__) = IRDA_CLOCKSOURCE_HSI; \ break; \ case RCC_USART1CLKSOURCE_SYSCLK: \ (__CLOCKSOURCE__) = IRDA_CLOCKSOURCE_SYSCLK; \ break; \ case RCC_USART1CLKSOURCE_LSE: \ (__CLOCKSOURCE__) = IRDA_CLOCKSOURCE_LSE; \ break; \ default: \ (__CLOCKSOURCE__) = IRDA_CLOCKSOURCE_UNDEFINED; \ break; \ } \ } while(0) #elif defined (STM32F042x6) || defined (STM32F048xx) || \ defined (STM32F051x8) || defined (STM32F058xx) #define IRDA_GETCLOCKSOURCE(__HANDLE__,__CLOCKSOURCE__) \ do { \ if((__HANDLE__)->Instance == USART1) \ { \ switch(__HAL_RCC_GET_USART1_SOURCE()) \ { \ case RCC_USART1CLKSOURCE_PCLK1: \ (__CLOCKSOURCE__) = IRDA_CLOCKSOURCE_PCLK1; \ break; \ case RCC_USART1CLKSOURCE_HSI: \ (__CLOCKSOURCE__) = IRDA_CLOCKSOURCE_HSI; \ break; \ case RCC_USART1CLKSOURCE_SYSCLK: \ (__CLOCKSOURCE__) = IRDA_CLOCKSOURCE_SYSCLK; \ break; \ case RCC_USART1CLKSOURCE_LSE: \ (__CLOCKSOURCE__) = IRDA_CLOCKSOURCE_LSE; \ break; \ default: \ (__CLOCKSOURCE__) = IRDA_CLOCKSOURCE_UNDEFINED; \ break; \ } \ } \ else if((__HANDLE__)->Instance == USART2) \ { \ (__CLOCKSOURCE__) = IRDA_CLOCKSOURCE_PCLK1; \ } \ else \ { \ (__CLOCKSOURCE__) = IRDA_CLOCKSOURCE_UNDEFINED; \ } \ } while(0) #elif defined(STM32F071xB) || defined(STM32F072xB) || defined(STM32F078xx) #define IRDA_GETCLOCKSOURCE(__HANDLE__,__CLOCKSOURCE__) \ do { \ if((__HANDLE__)->Instance == USART1) \ { \ switch(__HAL_RCC_GET_USART1_SOURCE()) \ { \ case RCC_USART1CLKSOURCE_PCLK1: \ (__CLOCKSOURCE__) = IRDA_CLOCKSOURCE_PCLK1; \ break; \ case RCC_USART1CLKSOURCE_HSI: \ (__CLOCKSOURCE__) = IRDA_CLOCKSOURCE_HSI; \ break; \ case RCC_USART1CLKSOURCE_SYSCLK: \ (__CLOCKSOURCE__) = IRDA_CLOCKSOURCE_SYSCLK; \ break; \ case RCC_USART1CLKSOURCE_LSE: \ (__CLOCKSOURCE__) = IRDA_CLOCKSOURCE_LSE; \ break; \ default: \ (__CLOCKSOURCE__) = IRDA_CLOCKSOURCE_UNDEFINED; \ break; \ } \ } \ else if((__HANDLE__)->Instance == USART2) \ { \ switch(__HAL_RCC_GET_USART2_SOURCE()) \ { \ case RCC_USART2CLKSOURCE_PCLK1: \ (__CLOCKSOURCE__) = IRDA_CLOCKSOURCE_PCLK1; \ break; \ case RCC_USART2CLKSOURCE_HSI: \ (__CLOCKSOURCE__) = IRDA_CLOCKSOURCE_HSI; \ break; \ case RCC_USART2CLKSOURCE_SYSCLK: \ (__CLOCKSOURCE__) = IRDA_CLOCKSOURCE_SYSCLK; \ break; \ case RCC_USART2CLKSOURCE_LSE: \ (__CLOCKSOURCE__) = IRDA_CLOCKSOURCE_LSE; \ break; \ default: \ (__CLOCKSOURCE__) = IRDA_CLOCKSOURCE_UNDEFINED; \ break; \ } \ } \ else if((__HANDLE__)->Instance == USART3) \ { \ (__CLOCKSOURCE__) = IRDA_CLOCKSOURCE_PCLK1; \ } \ else if((__HANDLE__)->Instance == USART4) \ { \ (__CLOCKSOURCE__) = IRDA_CLOCKSOURCE_PCLK1; \ } \ else \ { \ (__CLOCKSOURCE__) = IRDA_CLOCKSOURCE_UNDEFINED; \ } \ } while(0) #elif defined(STM32F091xC) || defined(STM32F098xx) #define IRDA_GETCLOCKSOURCE(__HANDLE__,__CLOCKSOURCE__) \ do { \ if((__HANDLE__)->Instance == USART1) \ { \ switch(__HAL_RCC_GET_USART1_SOURCE()) \ { \ case RCC_USART1CLKSOURCE_PCLK1: \ (__CLOCKSOURCE__) = IRDA_CLOCKSOURCE_PCLK1; \ break; \ case RCC_USART1CLKSOURCE_HSI: \ (__CLOCKSOURCE__) = IRDA_CLOCKSOURCE_HSI; \ break; \ case RCC_USART1CLKSOURCE_SYSCLK: \ (__CLOCKSOURCE__) = IRDA_CLOCKSOURCE_SYSCLK; \ break; \ case RCC_USART1CLKSOURCE_LSE: \ (__CLOCKSOURCE__) = IRDA_CLOCKSOURCE_LSE; \ break; \ default: \ (__CLOCKSOURCE__) = IRDA_CLOCKSOURCE_UNDEFINED; \ break; \ } \ } \ else if((__HANDLE__)->Instance == USART2) \ { \ switch(__HAL_RCC_GET_USART2_SOURCE()) \ { \ case RCC_USART2CLKSOURCE_PCLK1: \ (__CLOCKSOURCE__) = IRDA_CLOCKSOURCE_PCLK1; \ break; \ case RCC_USART2CLKSOURCE_HSI: \ (__CLOCKSOURCE__) = IRDA_CLOCKSOURCE_HSI; \ break; \ case RCC_USART2CLKSOURCE_SYSCLK: \ (__CLOCKSOURCE__) = IRDA_CLOCKSOURCE_SYSCLK; \ break; \ case RCC_USART2CLKSOURCE_LSE: \ (__CLOCKSOURCE__) = IRDA_CLOCKSOURCE_LSE; \ break; \ default: \ (__CLOCKSOURCE__) = IRDA_CLOCKSOURCE_UNDEFINED; \ break; \ } \ } \ else if((__HANDLE__)->Instance == USART3) \ { \ switch(__HAL_RCC_GET_USART3_SOURCE()) \ { \ case RCC_USART3CLKSOURCE_PCLK1: \ (__CLOCKSOURCE__) = IRDA_CLOCKSOURCE_PCLK1; \ break; \ case RCC_USART3CLKSOURCE_HSI: \ (__CLOCKSOURCE__) = IRDA_CLOCKSOURCE_HSI; \ break; \ case RCC_USART3CLKSOURCE_SYSCLK: \ (__CLOCKSOURCE__) = IRDA_CLOCKSOURCE_SYSCLK; \ break; \ case RCC_USART3CLKSOURCE_LSE: \ (__CLOCKSOURCE__) = IRDA_CLOCKSOURCE_LSE; \ break; \ default: \ (__CLOCKSOURCE__) = IRDA_CLOCKSOURCE_UNDEFINED; \ break; \ } \ } \ else if((__HANDLE__)->Instance == USART4) \ { \ (__CLOCKSOURCE__) = IRDA_CLOCKSOURCE_PCLK1; \ } \ else if((__HANDLE__)->Instance == USART5) \ { \ (__CLOCKSOURCE__) = IRDA_CLOCKSOURCE_PCLK1; \ } \ else if((__HANDLE__)->Instance == USART6) \ { \ (__CLOCKSOURCE__) = IRDA_CLOCKSOURCE_PCLK1; \ } \ else if((__HANDLE__)->Instance == USART7) \ { \ (__CLOCKSOURCE__) = IRDA_CLOCKSOURCE_PCLK1; \ } \ else if((__HANDLE__)->Instance == USART8) \ { \ (__CLOCKSOURCE__) = IRDA_CLOCKSOURCE_PCLK1; \ } \ else \ { \ (__CLOCKSOURCE__) = IRDA_CLOCKSOURCE_UNDEFINED; \ } \ } while(0) #endif /* defined(STM32F031x6) || defined(STM32F038xx) */ /** @brief Compute the mask to apply to retrieve the received data * according to the word length and to the parity bits activation. * @note If PCE = 1, the parity bit is not included in the data extracted * by the reception API(). * This masking operation is not carried out in the case of * DMA transfers. * @param __HANDLE__: specifies the IRDA Handle * @retval None, the mask to apply to IRDA RDR register is stored in (__HANDLE__)->Mask field. */ #if defined (STM32F042x6) || defined (STM32F048xx) || \ defined (STM32F071xB) || defined (STM32F072xB) || defined (STM32F078xx) || \ defined (STM32F091xC) || defined (STM32F098xx) #define IRDA_MASK_COMPUTATION(__HANDLE__) \ do { \ if ((__HANDLE__)->Init.WordLength == IRDA_WORDLENGTH_9B) \ { \ if ((__HANDLE__)->Init.Parity == IRDA_PARITY_NONE) \ { \ (__HANDLE__)->Mask = 0x01FF ; \ } \ else \ { \ (__HANDLE__)->Mask = 0x00FF ; \ } \ } \ else if ((__HANDLE__)->Init.WordLength == IRDA_WORDLENGTH_8B) \ { \ if ((__HANDLE__)->Init.Parity == IRDA_PARITY_NONE) \ { \ (__HANDLE__)->Mask = 0x00FF ; \ } \ else \ { \ (__HANDLE__)->Mask = 0x007F ; \ } \ } \ else if ((__HANDLE__)->Init.WordLength == IRDA_WORDLENGTH_7B) \ { \ if ((__HANDLE__)->Init.Parity == IRDA_PARITY_NONE) \ { \ (__HANDLE__)->Mask = 0x007F ; \ } \ else \ { \ (__HANDLE__)->Mask = 0x003F ; \ } \ } \ } while(0) #else #define IRDA_MASK_COMPUTATION(__HANDLE__) \ do { \ if ((__HANDLE__)->Init.WordLength == IRDA_WORDLENGTH_9B) \ { \ if ((__HANDLE__)->Init.Parity == IRDA_PARITY_NONE) \ { \ (__HANDLE__)->Mask = 0x01FF ; \ } \ else \ { \ (__HANDLE__)->Mask = 0x00FF ; \ } \ } \ else if ((__HANDLE__)->Init.WordLength == IRDA_WORDLENGTH_8B) \ { \ if ((__HANDLE__)->Init.Parity == IRDA_PARITY_NONE) \ { \ (__HANDLE__)->Mask = 0x00FF ; \ } \ else \ { \ (__HANDLE__)->Mask = 0x007F ; \ } \ } \ } while(0) #endif /* defined (STM32F042x6) || defined (STM32F048xx) || \ defined (STM32F071xB) || defined (STM32F072xB) || defined (STM32F078xx) || \ defined (STM32F091xC) || defined(STM32F098xx) */ /** * @brief Ensure that IRDA frame length is valid. * @param __LENGTH__: IRDA frame length. * @retval SET (__LENGTH__ is valid) or RESET (__LENGTH__ is invalid) */ #if defined (STM32F042x6) || defined (STM32F048xx) || \ defined (STM32F071xB) || defined (STM32F072xB) || defined (STM32F078xx) || \ defined (STM32F091xC) || defined (STM32F098xx) #define IS_IRDA_WORD_LENGTH(__LENGTH__) (((__LENGTH__) == IRDA_WORDLENGTH_7B) || \ ((__LENGTH__) == IRDA_WORDLENGTH_8B) || \ ((__LENGTH__) == IRDA_WORDLENGTH_9B)) #else #define IS_IRDA_WORD_LENGTH(__LENGTH__) (((__LENGTH__) == IRDA_WORDLENGTH_8B) || \ ((__LENGTH__) == IRDA_WORDLENGTH_9B)) #endif /* defined (STM32F042x6) || defined (STM32F048xx) || \ defined (STM32F071xB) || defined (STM32F072xB) || defined (STM32F078xx) || \ defined (STM32F091xC) || defined (STM32F098xx)*/ /** * @} */ /* Exported functions --------------------------------------------------------*/ /** * @} */ /** * @} */ #endif /* !defined(STM32F030x6) && !defined(STM32F030x8) && !defined(STM32F070x6) && !defined(STM32F070xB) && !defined(STM32F030xC) */ #ifdef __cplusplus } #endif #endif /* __STM32F0xx_HAL_IRDA_EX_H */ /************************ (C) COPYRIGHT STMicroelectronics *****END OF FILE****/ ================================================ FILE: Zelig/mbed/TARGET_NUCLEO_F091RC/stm32f0xx_hal_iwdg.h ================================================ /** ****************************************************************************** * @file stm32f0xx_hal_iwdg.h * @author MCD Application Team * @version V1.3.0 * @date 26-June-2015 * @brief Header file of IWDG HAL module. ****************************************************************************** * @attention * *

© COPYRIGHT(c) 2015 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. * ****************************************************************************** */ /* Define to prevent recursive inclusion -------------------------------------*/ #ifndef __STM32F0xx_HAL_IWDG_H #define __STM32F0xx_HAL_IWDG_H #ifdef __cplusplus extern "C" { #endif /* Includes ------------------------------------------------------------------*/ #include "stm32f0xx_hal_def.h" /** @addtogroup STM32F0xx_HAL_Driver * @{ */ /** @addtogroup IWDG * @{ */ /* Exported types ------------------------------------------------------------*/ /** @defgroup IWDG_Exported_Types IWDG Exported Types * @{ */ /** * @brief IWDG HAL State Structure definition */ typedef enum { HAL_IWDG_STATE_RESET = 0x00, /*!< IWDG not yet initialized or disabled */ HAL_IWDG_STATE_READY = 0x01, /*!< IWDG initialized and ready for use */ HAL_IWDG_STATE_BUSY = 0x02, /*!< IWDG internal process is ongoing */ HAL_IWDG_STATE_TIMEOUT = 0x03, /*!< IWDG timeout state */ HAL_IWDG_STATE_ERROR = 0x04 /*!< IWDG error state */ }HAL_IWDG_StateTypeDef; /** * @brief IWDG Init structure definition */ typedef struct { uint32_t Prescaler; /*!< Select the prescaler of the IWDG. This parameter can be a value of @ref IWDG_Prescaler */ uint32_t Reload; /*!< Specifies the IWDG down-counter reload value. This parameter must be a number between Min_Data = 0 and Max_Data = 0x0FFF */ uint32_t Window; /*!< Specifies the window value to be compared to the down-counter. This parameter must be a number between Min_Data = 0 and Max_Data = 0x0FFF */ } IWDG_InitTypeDef; /** * @brief IWDG Handle Structure definition */ typedef struct { IWDG_TypeDef *Instance; /*!< Register base address */ IWDG_InitTypeDef Init; /*!< IWDG required parameters */ HAL_LockTypeDef Lock; /*!< IWDG Locking object */ __IO HAL_IWDG_StateTypeDef State; /*!< IWDG communication state */ }IWDG_HandleTypeDef; /** * @} */ /* Exported constants --------------------------------------------------------*/ /** @defgroup IWDG_Exported_Constants IWDG Exported Constants * @{ */ /** @defgroup IWDG_Prescaler IWDG Prescaler * @{ */ #define IWDG_PRESCALER_4 ((uint8_t)0x00) /*!< IWDG prescaler set to 4 */ #define IWDG_PRESCALER_8 ((uint8_t)(IWDG_PR_PR_0)) /*!< IWDG prescaler set to 8 */ #define IWDG_PRESCALER_16 ((uint8_t)(IWDG_PR_PR_1)) /*!< IWDG prescaler set to 16 */ #define IWDG_PRESCALER_32 ((uint8_t)(IWDG_PR_PR_1 | IWDG_PR_PR_0)) /*!< IWDG prescaler set to 32 */ #define IWDG_PRESCALER_64 ((uint8_t)(IWDG_PR_PR_2)) /*!< IWDG prescaler set to 64 */ #define IWDG_PRESCALER_128 ((uint8_t)(IWDG_PR_PR_2 | IWDG_PR_PR_0)) /*!< IWDG prescaler set to 128 */ #define IWDG_PRESCALER_256 ((uint8_t)(IWDG_PR_PR_2 | IWDG_PR_PR_1)) /*!< IWDG prescaler set to 256 */ /** * @} */ /** @defgroup IWDG_Window IWDG Window * @{ */ #define IWDG_WINDOW_DISABLE ((uint32_t)0x00000FFF) /** * @} */ /** * @} */ /* Exported macros -----------------------------------------------------------*/ /** @defgroup IWDG_Exported_Macros IWDG Exported Macros * @{ */ /** @brief Reset IWDG handle state. * @param __HANDLE__: IWDG handle. * @retval None */ #define __HAL_IWDG_RESET_HANDLE_STATE(__HANDLE__) ((__HANDLE__)->State = HAL_IWDG_STATE_RESET) /** * @brief Enable the IWDG peripheral. * @param __HANDLE__: IWDG handle * @retval None */ #define __HAL_IWDG_START(__HANDLE__) WRITE_REG((__HANDLE__)->Instance->KR, IWDG_KEY_ENABLE) /** * @brief Reload IWDG counter with value defined in the reload register. * @param __HANDLE__: IWDG handle * @retval None */ #define __HAL_IWDG_RELOAD_COUNTER(__HANDLE__) WRITE_REG((__HANDLE__)->Instance->KR, IWDG_KEY_RELOAD) /** * @brief Get the selected IWDG flag status. * @param __HANDLE__: IWDG handle * @param __FLAG__: specifies the flag to check. * This parameter can be one of the following values: * @arg IWDG_FLAG_PVU: Watchdog counter reload value update flag * @arg IWDG_FLAG_RVU: Watchdog counter prescaler value flag * @arg IWDG_FLAG_WVU: Watchdog counter window value flag * @retval The new state of __FLAG__ (TRUE or FALSE). */ #define __HAL_IWDG_GET_FLAG(__HANDLE__, __FLAG__) (((__HANDLE__)->Instance->SR & (__FLAG__)) == (__FLAG__)) /** * @} */ /* Exported functions --------------------------------------------------------*/ /** @addtogroup IWDG_Exported_Functions * @{ */ /** @addtogroup IWDG_Exported_Functions_Group1 * @{ */ /* Initialization/de-initialization functions ********************************/ HAL_StatusTypeDef HAL_IWDG_Init(IWDG_HandleTypeDef *hiwdg); void HAL_IWDG_MspInit(IWDG_HandleTypeDef *hiwdg); /** * @} */ /** @addtogroup IWDG_Exported_Functions_Group2 * @{ */ /* I/O operation functions ****************************************************/ HAL_StatusTypeDef HAL_IWDG_Start(IWDG_HandleTypeDef *hiwdg); HAL_StatusTypeDef HAL_IWDG_Refresh(IWDG_HandleTypeDef *hiwdg); /** * @} */ /** @addtogroup IWDG_Exported_Functions_Group3 * @{ */ /* Peripheral State functions ************************************************/ HAL_IWDG_StateTypeDef HAL_IWDG_GetState(IWDG_HandleTypeDef *hiwdg); /** * @} */ /** * @} */ /* Private constants ---------------------------------------------------------*/ /** @addtogroup IWDG_Private_Defines * @{ */ /** * @brief IWDG Key Register BitMask */ #define IWDG_KEY_RELOAD ((uint32_t)0x0000AAAA) /*!< IWDG Reload Counter Enable */ #define IWDG_KEY_ENABLE ((uint32_t)0x0000CCCC) /*!< IWDG Peripheral Enable */ #define IWDG_KEY_WRITE_ACCESS_ENABLE ((uint32_t)0x00005555) /*!< IWDG KR Write Access Enable */ #define IWDG_KEY_WRITE_ACCESS_DISABLE ((uint32_t)0x00000000) /*!< IWDG KR Write Access Disable */ /** * @brief IWDG Flag definition */ #define IWDG_FLAG_PVU ((uint32_t)IWDG_SR_PVU) /*!< Watchdog counter prescaler value update flag */ #define IWDG_FLAG_RVU ((uint32_t)IWDG_SR_RVU) /*!< Watchdog counter reload value update flag */ #define IWDG_FLAG_WVU ((uint32_t)IWDG_SR_WVU) /*!< Watchdog counter window value update flag */ /** * @} */ /* Private macros ------------------------------------------------------------*/ /** @defgroup IWDG_Private_Macro IWDG Private Macros * @{ */ /** * @brief Enables write access to IWDG_PR, IWDG_RLR and IWDG_WINR registers. * @param __HANDLE__: IWDG handle * @retval None */ #define IWDG_ENABLE_WRITE_ACCESS(__HANDLE__) WRITE_REG((__HANDLE__)->Instance->KR, IWDG_KEY_WRITE_ACCESS_ENABLE) /** * @brief Disables write access to IWDG_PR, IWDG_RLR and IWDG_WINR registers. * @param __HANDLE__: IWDG handle * @retval None */ #define IWDG_DISABLE_WRITE_ACCESS(__HANDLE__) WRITE_REG((__HANDLE__)->Instance->KR, IWDG_KEY_WRITE_ACCESS_DISABLE) /** * @brief Check IWDG prescaler value. * @param __PRESCALER__: IWDG prescaler value * @retval None */ #define IS_IWDG_PRESCALER(__PRESCALER__) (((__PRESCALER__) == IWDG_PRESCALER_4) || \ ((__PRESCALER__) == IWDG_PRESCALER_8) || \ ((__PRESCALER__) == IWDG_PRESCALER_16) || \ ((__PRESCALER__) == IWDG_PRESCALER_32) || \ ((__PRESCALER__) == IWDG_PRESCALER_64) || \ ((__PRESCALER__) == IWDG_PRESCALER_128)|| \ ((__PRESCALER__) == IWDG_PRESCALER_256)) /** * @brief Check IWDG reload value. * @param __RELOAD__: IWDG reload value * @retval None */ #define IS_IWDG_RELOAD(__RELOAD__) ((__RELOAD__) <= 0xFFF) /** * @brief Check IWDG window value. * @param __WINDOW__: IWDG window value * @retval None */ #define IS_IWDG_WINDOW(__WINDOW__) ((__WINDOW__) <= 0xFFF) /** * @} */ /** * @} */ /** * @} */ #ifdef __cplusplus } #endif #endif /* __STM32F0xx_HAL_IWDG_H */ /************************ (C) COPYRIGHT STMicroelectronics *****END OF FILE****/ ================================================ FILE: Zelig/mbed/TARGET_NUCLEO_F091RC/stm32f0xx_hal_pcd.h ================================================ /** ****************************************************************************** * @file stm32f0xx_hal_pcd.h * @author MCD Application Team * @version V1.3.0 * @date 26-June-2015 * @brief Header file of PCD HAL module. ****************************************************************************** * @attention * *

© COPYRIGHT(c) 2015 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. * ****************************************************************************** */ /* Define to prevent recursive inclusion -------------------------------------*/ #ifndef __STM32F0xx_HAL_PCD_H #define __STM32F0xx_HAL_PCD_H #ifdef __cplusplus extern "C" { #endif #if defined(STM32F042x6) || defined(STM32F048xx) || defined(STM32F072xB) || defined(STM32F078xx) || defined(STM32F070xB)|| defined(STM32F070x6) /* Includes ------------------------------------------------------------------*/ #include "stm32f0xx_hal_def.h" /** @addtogroup STM32F0xx_HAL_Driver * @{ */ /** @addtogroup PCD * @{ */ /* Exported types ------------------------------------------------------------*/ /** @defgroup PCD_Exported_Types PCD Exported Types * @{ */ /** * @brief PCD State structure definition */ typedef enum { HAL_PCD_STATE_RESET = 0x00, HAL_PCD_STATE_READY = 0x01, HAL_PCD_STATE_ERROR = 0x02, HAL_PCD_STATE_BUSY = 0x03, HAL_PCD_STATE_TIMEOUT = 0x04 } PCD_StateTypeDef; /** * @brief PCD double buffered endpoint direction */ typedef enum { PCD_EP_DBUF_OUT, PCD_EP_DBUF_IN, PCD_EP_DBUF_ERR, }PCD_EP_DBUF_DIR; /** * @brief PCD endpoint buffer number */ typedef enum { PCD_EP_NOBUF, PCD_EP_BUF0, PCD_EP_BUF1 }PCD_EP_BUF_NUM; /** * @brief PCD Initialization Structure definition */ typedef struct { uint32_t dev_endpoints; /*!< Device Endpoints number. This parameter depends on the used USB core. This parameter must be a number between Min_Data = 1 and Max_Data = 15 */ uint32_t speed; /*!< USB Core speed. This parameter can be any value of @ref PCD_Core_Speed */ uint32_t ep0_mps; /*!< Set the Endpoint 0 Max Packet size. This parameter can be any value of @ref PCD_EP0_MPS */ uint32_t phy_itface; /*!< Select the used PHY interface. This parameter can be any value of @ref PCD_Core_PHY */ uint32_t Sof_enable; /*!< Enable or disable the output of the SOF signal. This parameter can be set to ENABLE or DISABLE */ uint32_t low_power_enable; /*!< Enable or disable Low Power mode This parameter can be set to ENABLE or DISABLE */ uint32_t lpm_enable; /*!< Enable or disable the Link Power Management . This parameter can be set to ENABLE or DISABLE */ uint32_t battery_charging_enable; /*!< Enable or disable Battery charging. This parameter can be set to ENABLE or DISABLE */ }PCD_InitTypeDef; typedef struct { uint8_t num; /*!< Endpoint number This parameter must be a number between Min_Data = 1 and Max_Data = 15 */ uint8_t is_in; /*!< Endpoint direction This parameter must be a number between Min_Data = 0 and Max_Data = 1 */ uint8_t is_stall; /*!< Endpoint stall condition This parameter must be a number between Min_Data = 0 and Max_Data = 1 */ uint8_t type; /*!< Endpoint type This parameter can be any value of @ref PCD_EP_Type */ uint16_t pmaadress; /*!< PMA Address This parameter can be any value between Min_addr = 0 and Max_addr = 1K */ uint16_t pmaaddr0; /*!< PMA Address0 This parameter can be any value between Min_addr = 0 and Max_addr = 1K */ uint16_t pmaaddr1; /*!< PMA Address1 This parameter can be any value between Min_addr = 0 and Max_addr = 1K */ uint8_t doublebuffer; /*!< Double buffer enable This parameter can be 0 or 1 */ uint32_t maxpacket; /*!< Endpoint Max packet size This parameter must be a number between Min_Data = 0 and Max_Data = 64KB */ uint8_t *xfer_buff; /*!< Pointer to transfer buffer */ uint32_t xfer_len; /*!< Current transfer length */ uint32_t xfer_count; /*!< Partial transfer length in case of multi packet transfer */ }PCD_EPTypeDef; typedef USB_TypeDef PCD_TypeDef; /** * @brief PCD Handle Structure definition */ typedef struct { PCD_TypeDef *Instance; /*!< Register base address */ PCD_InitTypeDef Init; /*!< PCD required parameters */ __IO uint8_t USB_Address; /*!< USB Address */ PCD_EPTypeDef IN_ep[8]; /*!< IN endpoint parameters */ PCD_EPTypeDef OUT_ep[8]; /*!< OUT endpoint parameters */ HAL_LockTypeDef Lock; /*!< PCD peripheral status */ __IO PCD_StateTypeDef State; /*!< PCD communication state */ uint32_t Setup[12]; /*!< Setup packet buffer */ void *pData; /*!< Pointer to upper stack Handler */ } PCD_HandleTypeDef; /** * @} */ /* Include PCD HAL Extension module */ #include "stm32f0xx_hal_pcd_ex.h" /* Exported constants --------------------------------------------------------*/ /** @defgroup PCD_Exported_Constants PCD Exported Constants * @{ */ /** @defgroup PCD_Core_Speed PCD Core Speed * @{ */ #define PCD_SPEED_HIGH 0 /* Not Supported */ #define PCD_SPEED_FULL 2 /** * @} */ /** @defgroup PCD_Core_PHY PCD Core PHY * @{ */ #define PCD_PHY_EMBEDDED 2 /** * @} */ /** * @} */ /* Exported macros -----------------------------------------------------------*/ /** @defgroup PCD_Exported_Macros PCD Exported Macros * @brief macros to handle interrupts and specific clock configurations * @{ */ #define __HAL_PCD_GET_FLAG(__HANDLE__, __INTERRUPT__) ((((__HANDLE__)->Instance->ISTR) & (__INTERRUPT__)) == (__INTERRUPT__)) #define __HAL_PCD_CLEAR_FLAG(__HANDLE__, __INTERRUPT__) (((__HANDLE__)->Instance->ISTR) &= ~(__INTERRUPT__)) #define __HAL_USB_WAKEUP_EXTI_ENABLE_IT() EXTI->IMR |= USB_WAKEUP_EXTI_LINE #define __HAL_USB_WAKEUP_EXTI_DISABLE_IT() EXTI->IMR &= ~(USB_WAKEUP_EXTI_LINE) #define __HAL_USB_EXTI_GENERATE_SWIT(__EXTILINE__) (EXTI->SWIER |= (__EXTILINE__)) /** * @} */ /* Exported functions --------------------------------------------------------*/ /** @addtogroup PCD_Exported_Functions PCD Exported Functions * @{ */ /* Initialization/de-initialization functions ********************************/ /** @addtogroup PCD_Exported_Functions_Group1 Initialization and de-initialization functions * @{ */ HAL_StatusTypeDef HAL_PCD_Init(PCD_HandleTypeDef *hpcd); HAL_StatusTypeDef HAL_PCD_DeInit (PCD_HandleTypeDef *hpcd); void HAL_PCD_MspInit(PCD_HandleTypeDef *hpcd); void HAL_PCD_MspDeInit(PCD_HandleTypeDef *hpcd); /** * @} */ /* I/O operation functions ***************************************************/ /* Non-Blocking mode: Interrupt */ /** @addtogroup PCD_Exported_Functions_Group2 IO operation functions * @{ */ HAL_StatusTypeDef HAL_PCD_Start(PCD_HandleTypeDef *hpcd); HAL_StatusTypeDef HAL_PCD_Stop(PCD_HandleTypeDef *hpcd); void HAL_PCD_IRQHandler(PCD_HandleTypeDef *hpcd); void HAL_PCD_DataOutStageCallback(PCD_HandleTypeDef *hpcd, uint8_t epnum); void HAL_PCD_DataInStageCallback(PCD_HandleTypeDef *hpcd, uint8_t epnum); void HAL_PCD_SetupStageCallback(PCD_HandleTypeDef *hpcd); void HAL_PCD_SOFCallback(PCD_HandleTypeDef *hpcd); void HAL_PCD_ResetCallback(PCD_HandleTypeDef *hpcd); void HAL_PCD_SuspendCallback(PCD_HandleTypeDef *hpcd); void HAL_PCD_ResumeCallback(PCD_HandleTypeDef *hpcd); void HAL_PCD_ISOOUTIncompleteCallback(PCD_HandleTypeDef *hpcd, uint8_t epnum); void HAL_PCD_ISOINIncompleteCallback(PCD_HandleTypeDef *hpcd, uint8_t epnum); void HAL_PCD_ConnectCallback(PCD_HandleTypeDef *hpcd); void HAL_PCD_DisconnectCallback(PCD_HandleTypeDef *hpcd); /** * @} */ /* Peripheral Control functions **********************************************/ /** @addtogroup PCD_Exported_Functions_Group3 Peripheral Control functions * @{ */ HAL_StatusTypeDef HAL_PCD_DevConnect(PCD_HandleTypeDef *hpcd); HAL_StatusTypeDef HAL_PCD_DevDisconnect(PCD_HandleTypeDef *hpcd); HAL_StatusTypeDef HAL_PCD_SetAddress(PCD_HandleTypeDef *hpcd, uint8_t address); HAL_StatusTypeDef HAL_PCD_EP_Open(PCD_HandleTypeDef *hpcd, uint8_t ep_addr, uint16_t ep_mps, uint8_t ep_type); HAL_StatusTypeDef HAL_PCD_EP_Close(PCD_HandleTypeDef *hpcd, uint8_t ep_addr); HAL_StatusTypeDef HAL_PCD_EP_Receive(PCD_HandleTypeDef *hpcd, uint8_t ep_addr, uint8_t *pBuf, uint32_t len); HAL_StatusTypeDef HAL_PCD_EP_Transmit(PCD_HandleTypeDef *hpcd, uint8_t ep_addr, uint8_t *pBuf, uint32_t len); uint16_t HAL_PCD_EP_GetRxCount(PCD_HandleTypeDef *hpcd, uint8_t ep_addr); HAL_StatusTypeDef HAL_PCD_EP_SetStall(PCD_HandleTypeDef *hpcd, uint8_t ep_addr); HAL_StatusTypeDef HAL_PCD_EP_ClrStall(PCD_HandleTypeDef *hpcd, uint8_t ep_addr); HAL_StatusTypeDef HAL_PCD_EP_Flush(PCD_HandleTypeDef *hpcd, uint8_t ep_addr); HAL_StatusTypeDef HAL_PCD_ActivateRemoteWakeup(PCD_HandleTypeDef *hpcd); HAL_StatusTypeDef HAL_PCD_DeActivateRemoteWakeup(PCD_HandleTypeDef *hpcd); /** * @} */ /* Peripheral State functions ************************************************/ /** @addtogroup PCD_Exported_Functions_Group4 Peripheral State functions * @{ */ PCD_StateTypeDef HAL_PCD_GetState(PCD_HandleTypeDef *hpcd); /** * @} */ /** * @} */ /* Private constants ---------------------------------------------------------*/ /** @defgroup PCD_Private_Constants PCD Private Constants * @{ */ /** @defgroup USB_EXTI_Line_Interrupt USB EXTI line interrupt * @{ */ #define USB_WAKEUP_EXTI_LINE ((uint32_t)EXTI_IMR_MR18) /*!< External interrupt line 18 Connected to the USB FS EXTI Line */ /** * @} */ /** @defgroup PCD_EP0_MPS PCD EP0 MPS * @{ */ #define DEP0CTL_MPS_64 0 #define DEP0CTL_MPS_32 1 #define DEP0CTL_MPS_16 2 #define DEP0CTL_MPS_8 3 #define PCD_EP0MPS_64 DEP0CTL_MPS_64 #define PCD_EP0MPS_32 DEP0CTL_MPS_32 #define PCD_EP0MPS_16 DEP0CTL_MPS_16 #define PCD_EP0MPS_08 DEP0CTL_MPS_8 /** * @} */ /** @defgroup PCD_EP_Type PCD EP Type * @{ */ #define PCD_EP_TYPE_CTRL 0 #define PCD_EP_TYPE_ISOC 1 #define PCD_EP_TYPE_BULK 2 #define PCD_EP_TYPE_INTR 3 /** * @} */ /** @defgroup PCD_ENDP PCD ENDP * @{ */ #define PCD_ENDP0 ((uint8_t)0) #define PCD_ENDP1 ((uint8_t)1) #define PCD_ENDP2 ((uint8_t)2) #define PCD_ENDP3 ((uint8_t)3) #define PCD_ENDP4 ((uint8_t)4) #define PCD_ENDP5 ((uint8_t)5) #define PCD_ENDP6 ((uint8_t)6) #define PCD_ENDP7 ((uint8_t)7) /** * @} */ /** @defgroup PCD_ENDP_Kind PCD Endpoint Kind * @{ */ #define PCD_SNG_BUF 0 #define PCD_DBL_BUF 1 /** * @} */ /** * @} */ /* Private macros ------------------------------------------------------------*/ /** @addtogroup PCD_Private_Macros PCD Private Macros * @{ */ /* SetENDPOINT */ #define PCD_SET_ENDPOINT(USBx, bEpNum,wRegValue) (*(&(USBx)->EP0R + (bEpNum) * 2)= (uint16_t)(wRegValue)) /* GetENDPOINT */ #define PCD_GET_ENDPOINT(USBx, bEpNum) (*(&(USBx)->EP0R + (bEpNum) * 2)) /** * @brief sets the type in the endpoint register(bits EP_TYPE[1:0]) * @param USBx: USB peripheral instance register address. * @param bEpNum: Endpoint Number. * @param wType: Endpoint Type. * @retval None */ #define PCD_SET_EPTYPE(USBx, bEpNum,wType) (PCD_SET_ENDPOINT((USBx), (bEpNum),\ ((PCD_GET_ENDPOINT((USBx), (bEpNum)) & USB_EP_T_MASK) | (wType) ))) /** * @brief gets the type in the endpoint register(bits EP_TYPE[1:0]) * @param USBx: USB peripheral instance register address. * @param bEpNum: Endpoint Number. * @retval Endpoint Type */ #define PCD_GET_EPTYPE(USBx, bEpNum) (PCD_GET_ENDPOINT((USBx), (bEpNum)) & USB_EP_T_FIELD) /** * @brief free buffer used from the application realizing it to the line toggles bit SW_BUF in the double buffered endpoint register * @param USBx: USB peripheral instance register address. * @param bEpNum: Endpoint Number. * @param bDir: Direction * @retval None */ #define PCD_FreeUserBuffer(USBx, bEpNum, bDir)\ {\ if ((bDir) == PCD_EP_DBUF_OUT)\ { /* OUT double buffered endpoint */\ PCD_TX_DTOG((USBx), (bEpNum));\ }\ else if ((bDir) == PCD_EP_DBUF_IN)\ { /* IN double buffered endpoint */\ PCD_RX_DTOG((USBx), (bEpNum));\ }\ } /** * @brief gets direction of the double buffered endpoint * @param USBx: USB peripheral instance register address. * @param bEpNum: Endpoint Number. * @retval EP_DBUF_OUT, EP_DBUF_IN, * EP_DBUF_ERR if the endpoint counter not yet programmed. */ #define PCD_GET_DB_DIR(USBx, bEpNum)\ {\ if ((uint16_t)(*PCD_EP_RX_CNT((USBx), (bEpNum)) & 0xFC00) != 0)\ return(PCD_EP_DBUF_OUT);\ else if (((uint16_t)(*PCD_EP_TX_CNT((USBx), (bEpNum))) & 0x03FF) != 0)\ return(PCD_EP_DBUF_IN);\ else\ return(PCD_EP_DBUF_ERR);\ } /** * @brief sets the status for tx transfer (bits STAT_TX[1:0]). * @param USBx: USB peripheral instance register address. * @param bEpNum: Endpoint Number. * @param wState: new state * @retval None */ #define PCD_SET_EP_TX_STATUS(USBx, bEpNum, wState) {\ register uint16_t _wRegVal; \ \ _wRegVal = PCD_GET_ENDPOINT((USBx), (bEpNum)) & USB_EPTX_DTOGMASK;\ /* toggle first bit ? */ \ if((USB_EPTX_DTOG1 & (wState))!= 0) \ _wRegVal ^= USB_EPTX_DTOG1; \ /* toggle second bit ? */ \ if((USB_EPTX_DTOG2 & (wState))!= 0) \ _wRegVal ^= USB_EPTX_DTOG2; \ PCD_SET_ENDPOINT((USBx), (bEpNum), (_wRegVal | USB_EP_CTR_RX|USB_EP_CTR_TX)); \ } /* PCD_SET_EP_TX_STATUS */ /** * @brief sets the status for rx transfer (bits STAT_TX[1:0]) * @param USBx: USB peripheral instance register address. * @param bEpNum: Endpoint Number. * @param wState: new state * @retval None */ #define PCD_SET_EP_RX_STATUS(USBx, bEpNum,wState) {\ register uint16_t _wRegVal; \ \ _wRegVal = PCD_GET_ENDPOINT((USBx), (bEpNum)) & USB_EPRX_DTOGMASK;\ /* toggle first bit ? */ \ if((USB_EPRX_DTOG1 & (wState))!= 0) \ _wRegVal ^= USB_EPRX_DTOG1; \ /* toggle second bit ? */ \ if((USB_EPRX_DTOG2 & (wState))!= 0) \ _wRegVal ^= USB_EPRX_DTOG2; \ PCD_SET_ENDPOINT((USBx), (bEpNum), (_wRegVal | USB_EP_CTR_RX|USB_EP_CTR_TX)); \ } /* PCD_SET_EP_RX_STATUS */ /** * @brief sets the status for rx & tx (bits STAT_TX[1:0] & STAT_RX[1:0]) * @param USBx: USB peripheral instance register address. * @param bEpNum: Endpoint Number. * @param wStaterx: new state. * @param wStatetx: new state. * @retval None */ #define PCD_SET_EP_TXRX_STATUS(USBx,bEpNum,wStaterx,wStatetx) {\ register uint32_t _wRegVal; \ \ _wRegVal = PCD_GET_ENDPOINT((USBx), (bEpNum)) & (USB_EPRX_DTOGMASK |USB_EPTX_STAT) ;\ /* toggle first bit ? */ \ if((USB_EPRX_DTOG1 & ((wStaterx)))!= 0) \ _wRegVal ^= USB_EPRX_DTOG1; \ /* toggle second bit ? */ \ if((USB_EPRX_DTOG2 & (wStaterx))!= 0) \ _wRegVal ^= USB_EPRX_DTOG2; \ /* toggle first bit ? */ \ if((USB_EPTX_DTOG1 & (wStatetx))!= 0) \ _wRegVal ^= USB_EPTX_DTOG1; \ /* toggle second bit ? */ \ if((USB_EPTX_DTOG2 & (wStatetx))!= 0) \ _wRegVal ^= USB_EPTX_DTOG2; \ PCD_SET_ENDPOINT((USBx), (bEpNum), _wRegVal | USB_EP_CTR_RX|USB_EP_CTR_TX); \ } /* PCD_SET_EP_TXRX_STATUS */ /** * @brief gets the status for tx/rx transfer (bits STAT_TX[1:0] * /STAT_RX[1:0]) * @param USBx: USB peripheral instance register address. * @param bEpNum: Endpoint Number. * @retval status */ #define PCD_GET_EP_TX_STATUS(USBx, bEpNum) ((uint16_t)PCD_GET_ENDPOINT((USBx), (bEpNum)) & USB_EPTX_STAT) #define PCD_GET_EP_RX_STATUS(USBx, bEpNum) ((uint16_t)PCD_GET_ENDPOINT((USBx), (bEpNum)) & USB_EPRX_STAT) /** * @brief sets directly the VALID tx/rx-status into the endpoint register * @param USBx: USB peripheral instance register address. * @param bEpNum: Endpoint Number. * @retval None */ #define PCD_SET_EP_TX_VALID(USBx, bEpNum) (PCD_SET_EP_TX_STATUS((USBx), (bEpNum), USB_EP_TX_VALID)) #define PCD_SET_EP_RX_VALID(USBx, bEpNum) (PCD_SET_EP_RX_STATUS((USBx), (bEpNum), USB_EP_RX_VALID)) /** * @brief checks stall condition in an endpoint. * @param USBx: USB peripheral instance register address. * @param bEpNum: Endpoint Number. * @retval TRUE = endpoint in stall condition. */ #define PCD_GET_EP_TX_STALL_STATUS(USBx, bEpNum) (PCD_GET_EP_TX_STATUS((USBx), (bEpNum)) \ == USB_EP_TX_STALL) #define PCD_GET_EP_RX_STALL_STATUS(USBx, bEpNum) (PCD_GET_EP_RX_STATUS((USBx), (bEpNum)) \ == USB_EP_RX_STALL) /** * @brief set & clear EP_KIND bit. * @param USBx: USB peripheral instance register address. * @param bEpNum: Endpoint Number. * @retval None */ #define PCD_SET_EP_KIND(USBx, bEpNum) (PCD_SET_ENDPOINT((USBx), (bEpNum), \ (USB_EP_CTR_RX|USB_EP_CTR_TX|((PCD_GET_ENDPOINT((USBx), (bEpNum)) | USB_EP_KIND) & USB_EPREG_MASK)))) #define PCD_CLEAR_EP_KIND(USBx, bEpNum) (PCD_SET_ENDPOINT((USBx), (bEpNum), \ (USB_EP_CTR_RX|USB_EP_CTR_TX|(PCD_GET_ENDPOINT((USBx), (bEpNum)) & USB_EPKIND_MASK)))) /** * @brief Sets/clears directly STATUS_OUT bit in the endpoint register. * @param USBx: USB peripheral instance register address. * @param bEpNum: Endpoint Number. * @retval None */ #define PCD_SET_OUT_STATUS(USBx, bEpNum) PCD_SET_EP_KIND((USBx), (bEpNum)) #define PCD_CLEAR_OUT_STATUS(USBx, bEpNum) PCD_CLEAR_EP_KIND((USBx), (bEpNum)) /** * @brief Sets/clears directly EP_KIND bit in the endpoint register. * @param USBx: USB peripheral instance register address. * @param bEpNum: Endpoint Number. * @retval None */ #define PCD_SET_EP_DBUF(USBx, bEpNum) PCD_SET_EP_KIND((USBx), (bEpNum)) #define PCD_CLEAR_EP_DBUF(USBx, bEpNum) PCD_CLEAR_EP_KIND((USBx), (bEpNum)) /** * @brief Clears bit CTR_RX / CTR_TX in the endpoint register. * @param USBx: USB peripheral instance register address. * @param bEpNum: Endpoint Number. * @retval None */ #define PCD_CLEAR_RX_EP_CTR(USBx, bEpNum) (PCD_SET_ENDPOINT((USBx), (bEpNum),\ PCD_GET_ENDPOINT((USBx), (bEpNum)) & 0x7FFF & USB_EPREG_MASK)) #define PCD_CLEAR_TX_EP_CTR(USBx, bEpNum) (PCD_SET_ENDPOINT((USBx), (bEpNum),\ PCD_GET_ENDPOINT((USBx), (bEpNum)) & 0xFF7F & USB_EPREG_MASK)) /** * @brief Toggles DTOG_RX / DTOG_TX bit in the endpoint register. * @param USBx: USB peripheral instance register address. * @param bEpNum: Endpoint Number. * @retval None */ #define PCD_RX_DTOG(USBx, bEpNum) (PCD_SET_ENDPOINT((USBx), (bEpNum), \ USB_EP_CTR_RX|USB_EP_CTR_TX|USB_EP_DTOG_RX | (PCD_GET_ENDPOINT((USBx), (bEpNum)) & USB_EPREG_MASK))) #define PCD_TX_DTOG(USBx, bEpNum) (PCD_SET_ENDPOINT((USBx), (bEpNum), \ USB_EP_CTR_RX|USB_EP_CTR_TX|USB_EP_DTOG_TX | (PCD_GET_ENDPOINT((USBx), (bEpNum)) & USB_EPREG_MASK))) /** * @brief Clears DTOG_RX / DTOG_TX bit in the endpoint register. * @param USBx: USB peripheral instance register address. * @param bEpNum: Endpoint Number. * @retval None */ #define PCD_CLEAR_RX_DTOG(USBx, bEpNum) if((PCD_GET_ENDPOINT((USBx), (bEpNum)) & USB_EP_DTOG_RX) != 0)\ PCD_RX_DTOG((USBx), (bEpNum)) #define PCD_CLEAR_TX_DTOG(USBx, bEpNum) if((PCD_GET_ENDPOINT((USBx), (bEpNum)) & USB_EP_DTOG_TX) != 0)\ PCD_TX_DTOG((USBx), (bEpNum)) /** * @brief Sets address in an endpoint register. * @param USBx: USB peripheral instance register address. * @param bEpNum: Endpoint Number. * @param bAddr: Address. * @retval None */ #define PCD_SET_EP_ADDRESS(USBx, bEpNum,bAddr) PCD_SET_ENDPOINT((USBx), (bEpNum),\ USB_EP_CTR_RX|USB_EP_CTR_TX|(PCD_GET_ENDPOINT((USBx), (bEpNum)) & USB_EPREG_MASK) | (bAddr)) /** * @brief Gets address in an endpoint register. * @param USBx: USB peripheral instance register address. * @param bEpNum: Endpoint Number. * @retval None */ #define PCD_GET_EP_ADDRESS(USBx, bEpNum) ((uint8_t)(PCD_GET_ENDPOINT((USBx), (bEpNum)) & USB_EPADDR_FIELD)) #define PCD_EP_TX_ADDRESS(USBx, bEpNum) ((uint16_t *)(((USBx)->BTABLE+(bEpNum)*8)+ ((uint32_t)(USBx) + 0x400))) #define PCD_EP_TX_CNT(USBx, bEpNum) ((uint16_t *)(((USBx)->BTABLE+(bEpNum)*8+2)+ ((uint32_t)(USBx) + 0x400))) #define PCD_EP_RX_ADDRESS(USBx, bEpNum) ((uint16_t *)(((USBx)->BTABLE+(bEpNum)*8+4)+ ((uint32_t)(USBx) + 0x400))) #define PCD_EP_RX_CNT(USBx, bEpNum) ((uint16_t *)(((USBx)->BTABLE+(bEpNum)*8+6)+ ((uint32_t)(USBx) + 0x400))) /** * @brief sets address of the tx/rx buffer. * @param USBx: USB peripheral instance register address. * @param bEpNum: Endpoint Number. * @param wAddr: address to be set (must be word aligned). * @retval None */ #define PCD_SET_EP_TX_ADDRESS(USBx, bEpNum,wAddr) (*PCD_EP_TX_ADDRESS((USBx), (bEpNum)) = (((wAddr) >> 1) << 1)) #define PCD_SET_EP_RX_ADDRESS(USBx, bEpNum,wAddr) (*PCD_EP_RX_ADDRESS((USBx), (bEpNum)) = (((wAddr) >> 1) << 1)) /** * @brief Gets address of the tx/rx buffer. * @param USBx: USB peripheral instance register address. * @param bEpNum: Endpoint Number. * @retval address of the buffer. */ #define PCD_GET_EP_TX_ADDRESS(USBx, bEpNum) ((uint16_t)*PCD_EP_TX_ADDRESS((USBx), (bEpNum))) #define PCD_GET_EP_RX_ADDRESS(USBx, bEpNum) ((uint16_t)*PCD_EP_RX_ADDRESS((USBx), (bEpNum))) /** * @brief Sets counter of rx buffer with no. of blocks. * @param dwReg: Register * @param wCount: Counter. * @param wNBlocks: no. of Blocks. * @retval None */ #define PCD_CALC_BLK32(dwReg,wCount,wNBlocks) {\ (wNBlocks) = (wCount) >> 5;\ if(((wCount) & 0x1f) == 0)\ (wNBlocks)--;\ *pdwReg = (uint16_t)(((wNBlocks) << 10) | 0x8000);\ }/* PCD_CALC_BLK32 */ #define PCD_CALC_BLK2(dwReg,wCount,wNBlocks) {\ (wNBlocks) = (wCount) >> 1;\ if(((wCount) & 0x1) != 0)\ (wNBlocks)++;\ *pdwReg = (uint16_t)((wNBlocks) << 10);\ }/* PCD_CALC_BLK2 */ #define PCD_SET_EP_CNT_RX_REG(dwReg,wCount) {\ uint16_t wNBlocks;\ if((wCount) > 62){PCD_CALC_BLK32((dwReg),(wCount),wNBlocks);}\ else {PCD_CALC_BLK2((dwReg),(wCount),wNBlocks);}\ }/* PCD_SET_EP_CNT_RX_REG */ #define PCD_SET_EP_RX_DBUF0_CNT(USBx, bEpNum,wCount) {\ uint16_t *pdwReg = PCD_EP_TX_CNT((USBx), (bEpNum)); \ PCD_SET_EP_CNT_RX_REG(pdwReg, (wCount));\ } /** * @brief sets counter for the tx/rx buffer. * @param USBx: USB peripheral instance register address. * @param bEpNum: Endpoint Number. * @param wCount: Counter value. * @retval None */ #define PCD_SET_EP_TX_CNT(USBx, bEpNum,wCount) (*PCD_EP_TX_CNT((USBx), (bEpNum)) = (wCount)) #define PCD_SET_EP_RX_CNT(USBx, bEpNum,wCount) {\ uint16_t *pdwReg = PCD_EP_RX_CNT(USBx, bEpNum); \ PCD_SET_EP_CNT_RX_REG(pdwReg, wCount);\ } /** * @brief gets counter of the tx buffer. * @param USBx: USB peripheral instance register address. * @param bEpNum: Endpoint Number. * @retval Counter value */ #define PCD_GET_EP_TX_CNT(USBx, bEpNum)((uint16_t)(*PCD_EP_TX_CNT((USBx), (bEpNum))) & 0x3ff) #define PCD_GET_EP_RX_CNT(USBx, bEpNum)((uint16_t)(*PCD_EP_RX_CNT((USBx), (bEpNum))) & 0x3ff) /** * @brief Sets buffer 0/1 address in a double buffer endpoint. * @param USBx: USB peripheral instance register address. * @param bEpNum: Endpoint Number. * @param wBuf0Addr: buffer 0 address. * @retval Counter value */ #define PCD_SET_EP_DBUF0_ADDR(USBx, bEpNum,wBuf0Addr) {PCD_SET_EP_TX_ADDRESS((USBx), (bEpNum), (wBuf0Addr));} #define PCD_SET_EP_DBUF1_ADDR(USBx, bEpNum,wBuf1Addr) {PCD_SET_EP_RX_ADDRESS((USBx), (bEpNum), (wBuf1Addr));} /** * @brief Sets addresses in a double buffer endpoint. * @param USBx: USB peripheral instance register address. * @param bEpNum: Endpoint Number. * @param wBuf0Addr: buffer 0 address. * @param wBuf1Addr = buffer 1 address. * @retval None */ #define PCD_SET_EP_DBUF_ADDR(USBx, bEpNum,wBuf0Addr,wBuf1Addr) { \ PCD_SET_EP_DBUF0_ADDR((USBx), (bEpNum), (wBuf0Addr));\ PCD_SET_EP_DBUF1_ADDR((USBx), (bEpNum), (wBuf1Addr));\ } /* PCD_SET_EP_DBUF_ADDR */ /** * @brief Gets buffer 0/1 address of a double buffer endpoint. * @param USBx: USB peripheral instance register address. * @param bEpNum: Endpoint Number. * @retval None */ #define PCD_GET_EP_DBUF0_ADDR(USBx, bEpNum) (PCD_GET_EP_TX_ADDRESS((USBx), (bEpNum))) #define PCD_GET_EP_DBUF1_ADDR(USBx, bEpNum) (PCD_GET_EP_RX_ADDRESS((USBx), (bEpNum))) /** * @brief Gets buffer 0/1 address of a double buffer endpoint. * @param USBx: USB peripheral instance register address. * @param bEpNum: Endpoint Number. * @param bDir: endpoint dir EP_DBUF_OUT = OUT * EP_DBUF_IN = IN * @param wCount: Counter value * @retval None */ #define PCD_SET_EP_DBUF0_CNT(USBx, bEpNum, bDir, wCount) { \ if((bDir) == PCD_EP_DBUF_OUT)\ /* OUT endpoint */ \ {PCD_SET_EP_RX_DBUF0_CNT((USBx), (bEpNum),(wCount));} \ else if((bDir) == PCD_EP_DBUF_IN)\ /* IN endpoint */ \ *PCD_EP_TX_CNT((USBx), (bEpNum)) = (uint32_t)(wCount); \ } /* SetEPDblBuf0Count*/ #define PCD_SET_EP_DBUF1_CNT(USBx, bEpNum, bDir, wCount) { \ if((bDir) == PCD_EP_DBUF_OUT)\ /* OUT endpoint */ \ {PCD_SET_EP_RX_CNT((USBx), (bEpNum),(wCount));}\ else if((bDir) == PCD_EP_DBUF_IN)\ /* IN endpoint */\ *PCD_EP_TX_CNT((USBx), (bEpNum)) = (uint32_t)(wCount); \ } /* SetEPDblBuf1Count */ #define PCD_SET_EP_DBUF_CNT(USBx, bEpNum, bDir, wCount) {\ PCD_SET_EP_DBUF0_CNT((USBx), (bEpNum), (bDir), (wCount)); \ PCD_SET_EP_DBUF1_CNT((USBx), (bEpNum), (bDir), (wCount)); \ } /* PCD_SET_EP_DBUF_CNT */ /** * @brief Gets buffer 0/1 rx/tx counter for double buffering. * @param USBx: USB peripheral instance register address. * @param bEpNum: Endpoint Number. * @retval None */ #define PCD_GET_EP_DBUF0_CNT(USBx, bEpNum) (PCD_GET_EP_TX_CNT((USBx), (bEpNum))) #define PCD_GET_EP_DBUF1_CNT(USBx, bEpNum) (PCD_GET_EP_RX_CNT((USBx), (bEpNum))) /** @defgroup PCD_Instance_definition PCD Instance definition * @{ */ #define IS_PCD_ALL_INSTANCE IS_USB_ALL_INSTANCE /** * @} */ /** * @} */ /** * @} */ /** * @} */ #endif /* STM32F042x6 || STM32F072xB || STM32F078xx || STM32F070xB || STM32F070x6 */ #ifdef __cplusplus } #endif #endif /* __STM32F0xx_HAL_PCD_H */ /************************ (C) COPYRIGHT STMicroelectronics *****END OF FILE****/ ================================================ FILE: Zelig/mbed/TARGET_NUCLEO_F091RC/stm32f0xx_hal_pcd_ex.h ================================================ /** ****************************************************************************** * @file stm32f0xx_hal_pcd_ex.h * @author MCD Application Team * @version V1.3.0 * @date 26-June-2015 * @brief Header file of PCD HAL Extension module. ****************************************************************************** * @attention * *

© COPYRIGHT(c) 2015 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. * ****************************************************************************** */ /* Define to prevent recursive inclusion -------------------------------------*/ #ifndef __STM32L0xx_HAL_PCD_EX_H #define __STM32L0xx_HAL_PCD_EX_H #ifdef __cplusplus extern "C" { #endif #if defined(STM32F042x6) || defined(STM32F048xx) || defined(STM32F072xB) || defined(STM32F078xx)|| defined(STM32F070xB)|| defined(STM32F070x6) /* Includes ------------------------------------------------------------------*/ #include "stm32f0xx_hal_def.h" /** @addtogroup STM32F0xx_HAL_Driver * @{ */ /** @addtogroup PCDEx * @{ */ /* Exported types ------------------------------------------------------------*/ /* Exported constants --------------------------------------------------------*/ /* Exported macros -----------------------------------------------------------*/ /* Internal macros -----------------------------------------------------------*/ /* Exported functions --------------------------------------------------------*/ /** @addtogroup PCDEx_Exported_Functions PCDEx Exported Functions * @{ */ /** @addtogroup PCDEx_Exported_Functions_Group1 Peripheral Control functions * @{ */ HAL_StatusTypeDef HAL_PCDEx_PMAConfig(PCD_HandleTypeDef *hpcd, uint16_t ep_addr, uint16_t ep_kind, uint32_t pmaadress); /** * @} */ /** * @} */ /** * @} */ /** * @} */ #endif /* STM32F042x6 || STM32F072xB || STM32F078xx || STM32F070xB || STM32F070x6*/ #ifdef __cplusplus } #endif #endif /* __STM32F0xx_HAL_PCD_EX_H */ /************************ (C) COPYRIGHT STMicroelectronics *****END OF FILE****/ ================================================ FILE: Zelig/mbed/TARGET_NUCLEO_F091RC/stm32f0xx_hal_pwr.h ================================================ /** ****************************************************************************** * @file stm32f0xx_hal_pwr.h * @author MCD Application Team * @version V1.3.0 * @date 26-June-2015 * @brief Header file of PWR HAL module. ****************************************************************************** * @attention * *

© COPYRIGHT(c) 2015 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. * ****************************************************************************** */ /* Define to prevent recursive inclusion -------------------------------------*/ #ifndef __STM32F0xx_HAL_PWR_H #define __STM32F0xx_HAL_PWR_H #ifdef __cplusplus extern "C" { #endif /* Includes ------------------------------------------------------------------*/ #include "stm32f0xx_hal_def.h" /** @addtogroup STM32F0xx_HAL_Driver * @{ */ /** @addtogroup PWR PWR * @{ */ /* Exported types ------------------------------------------------------------*/ /* Exported constants --------------------------------------------------------*/ /** @defgroup PWR_Exported_Constants PWR Exported Constants * @{ */ /** @defgroup PWR_Regulator_state_in_STOP_mode PWR Regulator state in STOP mode * @{ */ #define PWR_MAINREGULATOR_ON ((uint32_t)0x00000000) #define PWR_LOWPOWERREGULATOR_ON PWR_CR_LPDS #define IS_PWR_REGULATOR(REGULATOR) (((REGULATOR) == PWR_MAINREGULATOR_ON) || \ ((REGULATOR) == PWR_LOWPOWERREGULATOR_ON)) /** * @} */ /** @defgroup PWR_SLEEP_mode_entry PWR SLEEP mode entry * @{ */ #define PWR_SLEEPENTRY_WFI ((uint8_t)0x01) #define PWR_SLEEPENTRY_WFE ((uint8_t)0x02) #define IS_PWR_SLEEP_ENTRY(ENTRY) (((ENTRY) == PWR_SLEEPENTRY_WFI) || ((ENTRY) == PWR_SLEEPENTRY_WFE)) /** * @} */ /** @defgroup PWR_STOP_mode_entry PWR STOP mode entry * @{ */ #define PWR_STOPENTRY_WFI ((uint8_t)0x01) #define PWR_STOPENTRY_WFE ((uint8_t)0x02) #define IS_PWR_STOP_ENTRY(ENTRY) (((ENTRY) == PWR_STOPENTRY_WFI) || ((ENTRY) == PWR_STOPENTRY_WFE)) /** * @} */ /** * @} */ /* Exported macro ------------------------------------------------------------*/ /** @defgroup PWR_Exported_Macro PWR Exported Macro * @{ */ /** @brief Check PWR flag is set or not. * @param __FLAG__: specifies the flag to check. * This parameter can be one of the following values: * @arg PWR_FLAG_WU: Wake Up flag. This flag indicates that a wakeup event * was received from the WKUP pin or from the RTC alarm (Alarm A), * RTC Tamper event, RTC TimeStamp event or RTC Wakeup. * An additional wakeup event is detected if the WKUP pin is enabled * (by setting the EWUP bit) when the WKUP pin level is already high. * @arg PWR_FLAG_SB: StandBy flag. This flag indicates that the system was * resumed from StandBy mode. * @arg PWR_FLAG_PVDO: PVD Output. This flag is valid only if PVD is enabled * by the HAL_PWR_EnablePVD() function. The PVD is stopped by Standby mode * For this reason, this bit is equal to 0 after Standby or reset * until the PVDE bit is set. * Warning: this Flag is not available on STM32F030x8 products * @arg PWR_FLAG_VREFINTRDY: This flag indicates that the internal reference * voltage VREFINT is ready. * Warning: this Flag is not available on STM32F030x8 products * @retval The new state of __FLAG__ (TRUE or FALSE). */ #define __HAL_PWR_GET_FLAG(__FLAG__) ((PWR->CSR & (__FLAG__)) == (__FLAG__)) /** @brief Clear the PWR's pending flags. * @param __FLAG__: specifies the flag to clear. * This parameter can be one of the following values: * @arg PWR_FLAG_WU: Wake Up flag * @arg PWR_FLAG_SB: StandBy flag */ #define __HAL_PWR_CLEAR_FLAG(__FLAG__) (PWR->CR |= (__FLAG__) << 2) /** * @} */ /* Include PWR HAL Extension module */ #include "stm32f0xx_hal_pwr_ex.h" /* Exported functions --------------------------------------------------------*/ /** @addtogroup PWR_Exported_Functions PWR Exported Functions * @{ */ /** @addtogroup PWR_Exported_Functions_Group1 Initialization and de-initialization functions * @{ */ /* Initialization and de-initialization functions *****************************/ void HAL_PWR_DeInit(void); /** * @} */ /** @addtogroup PWR_Exported_Functions_Group2 Peripheral Control functions * @{ */ /* Peripheral Control functions **********************************************/ void HAL_PWR_EnableBkUpAccess(void); void HAL_PWR_DisableBkUpAccess(void); /* WakeUp pins configuration functions ****************************************/ void HAL_PWR_EnableWakeUpPin(uint32_t WakeUpPinx); void HAL_PWR_DisableWakeUpPin(uint32_t WakeUpPinx); /* Low Power modes configuration functions ************************************/ void HAL_PWR_EnterSTOPMode(uint32_t Regulator, uint8_t STOPEntry); void HAL_PWR_EnterSLEEPMode(uint32_t Regulator, uint8_t SLEEPEntry); void HAL_PWR_EnterSTANDBYMode(void); void HAL_PWR_EnableSleepOnExit(void); void HAL_PWR_DisableSleepOnExit(void); void HAL_PWR_EnableSEVOnPend(void); void HAL_PWR_DisableSEVOnPend(void); /** * @} */ /** * @} */ /** * @} */ /** * @} */ #ifdef __cplusplus } #endif #endif /* __STM32F0xx_HAL_PWR_H */ /************************ (C) COPYRIGHT STMicroelectronics *****END OF FILE****/ ================================================ FILE: Zelig/mbed/TARGET_NUCLEO_F091RC/stm32f0xx_hal_pwr_ex.h ================================================ /** ****************************************************************************** * @file stm32f0xx_hal_pwr_ex.h * @author MCD Application Team * @version V1.3.0 * @date 26-June-2015 * @brief Header file of PWR HAL Extension module. ****************************************************************************** * @attention * *

© COPYRIGHT(c) 2015 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. * ****************************************************************************** */ /* Define to prevent recursive inclusion -------------------------------------*/ #ifndef __STM32F0xx_HAL_PWR_EX_H #define __STM32F0xx_HAL_PWR_EX_H #ifdef __cplusplus extern "C" { #endif /* Includes ------------------------------------------------------------------*/ #include "stm32f0xx_hal_def.h" /** @addtogroup STM32F0xx_HAL_Driver * @{ */ /** @addtogroup PWREx * @{ */ /* Exported types ------------------------------------------------------------*/ /** @defgroup PWREx_Exported_Types PWREx Exported Types * @{ */ #if defined (STM32F031x6) || defined (STM32F042x6) || defined (STM32F051x8) || \ defined (STM32F071xB) || defined (STM32F072xB) || \ defined (STM32F091xC) /** * @brief PWR PVD configuration structure definition */ typedef struct { uint32_t PVDLevel; /*!< PVDLevel: Specifies the PVD detection level This parameter can be a value of @ref PWREx_PVD_detection_level */ uint32_t Mode; /*!< Mode: Specifies the operating mode for the selected pins. This parameter can be a value of @ref PWREx_PVD_Mode */ }PWR_PVDTypeDef; #endif /* defined (STM32F031x6) || defined (STM32F042x6) || defined (STM32F051x8) || */ /* defined (STM32F071xB) || defined (STM32F072xB) || */ /* defined (STM32F091xC) */ /** * @} */ /* Exported constants --------------------------------------------------------*/ /** @defgroup PWREx_Exported_Constants PWREx Exported Constants * @{ */ /** @defgroup PWREx_WakeUp_Pins PWREx Wakeup Pins * @{ */ #if defined (STM32F071xB) || defined (STM32F072xB) || defined (STM32F078xx) || defined (STM32F070xB) || \ defined (STM32F091xC) || defined (STM32F098xx) || defined (STM32F030xC) #define PWR_WAKEUP_PIN1 ((uint32_t)0x00) #define PWR_WAKEUP_PIN2 ((uint32_t)0x01) #define PWR_WAKEUP_PIN3 ((uint32_t)0x02) #define PWR_WAKEUP_PIN4 ((uint32_t)0x03) #define PWR_WAKEUP_PIN5 ((uint32_t)0x04) #define PWR_WAKEUP_PIN6 ((uint32_t)0x05) #define PWR_WAKEUP_PIN7 ((uint32_t)0x06) #define PWR_WAKEUP_PIN8 ((uint32_t)0x07) #define IS_PWR_WAKEUP_PIN(PIN) (((PIN) == PWR_WAKEUP_PIN1) || \ ((PIN) == PWR_WAKEUP_PIN2) || \ ((PIN) == PWR_WAKEUP_PIN3) || \ ((PIN) == PWR_WAKEUP_PIN4) || \ ((PIN) == PWR_WAKEUP_PIN5) || \ ((PIN) == PWR_WAKEUP_PIN6) || \ ((PIN) == PWR_WAKEUP_PIN7) || \ ((PIN) == PWR_WAKEUP_PIN8)) #else #define PWR_WAKEUP_PIN1 ((uint32_t)0x00) #define PWR_WAKEUP_PIN2 ((uint32_t)0x01) #define IS_PWR_WAKEUP_PIN(PIN) (((PIN) == PWR_WAKEUP_PIN1) || \ ((PIN) == PWR_WAKEUP_PIN2)) #endif /* defined (STM32F071xB) || defined (STM32F072xB) || defined (STM32F078xx) || defined (STM32F070xB) || */ /* defined (STM32F091xC) || defined (STM32F098xx) || defined (STM32F030xC) */ /** * @} */ /** @defgroup PWREx_EXTI_Line PWREx EXTI Line * @{ */ #if defined (STM32F031x6) || defined (STM32F042x6) || defined (STM32F051x8) || \ defined (STM32F071xB) || defined (STM32F072xB) || \ defined (STM32F091xC) #define PWR_EXTI_LINE_PVD ((uint32_t)EXTI_IMR_MR16) /*!< External interrupt line 16 Connected to the PVD EXTI Line */ #endif /* defined (STM32F031x6) || defined (STM32F042x6) || defined (STM32F051x8) || */ /* defined (STM32F071xB) || defined (STM32F072xB) || */ /* defined (STM32F091xC) */ #if defined (STM32F042x6) || defined (STM32F048xx) || \ defined (STM32F071xB) || defined (STM32F072xB) || defined (STM32F078xx) || \ defined (STM32F091xC) || defined (STM32F098xx) #define PWR_EXTI_LINE_VDDIO2 ((uint32_t)EXTI_IMR_MR31) /*!< External interrupt line 31 Connected to the Vddio2 Monitor EXTI Line */ #endif /* defined (STM32F042x6) || defined (STM32F048xx) ||\ defined (STM32F071xB) || defined (STM32F072xB) || defined (STM32F078xx) || \ defined (STM32F091xC) || defined (STM32F098xx) ||*/ /** * @} */ #if defined (STM32F031x6) || defined (STM32F042x6) || defined (STM32F051x8) || \ defined (STM32F071xB) || defined (STM32F072xB) || \ defined (STM32F091xC) /** @defgroup PWREx_PVD_detection_level PWREx PVD detection level * @{ */ #define PWR_PVDLEVEL_0 PWR_CR_PLS_LEV0 #define PWR_PVDLEVEL_1 PWR_CR_PLS_LEV1 #define PWR_PVDLEVEL_2 PWR_CR_PLS_LEV2 #define PWR_PVDLEVEL_3 PWR_CR_PLS_LEV3 #define PWR_PVDLEVEL_4 PWR_CR_PLS_LEV4 #define PWR_PVDLEVEL_5 PWR_CR_PLS_LEV5 #define PWR_PVDLEVEL_6 PWR_CR_PLS_LEV6 #define PWR_PVDLEVEL_7 PWR_CR_PLS_LEV7 #define IS_PWR_PVD_LEVEL(LEVEL) (((LEVEL) == PWR_PVDLEVEL_0) || ((LEVEL) == PWR_PVDLEVEL_1)|| \ ((LEVEL) == PWR_PVDLEVEL_2) || ((LEVEL) == PWR_PVDLEVEL_3)|| \ ((LEVEL) == PWR_PVDLEVEL_4) || ((LEVEL) == PWR_PVDLEVEL_5)|| \ ((LEVEL) == PWR_PVDLEVEL_6) || ((LEVEL) == PWR_PVDLEVEL_7)) /** * @} */ /** @defgroup PWREx_PVD_Mode PWREx PVD Mode * @{ */ #define PWR_PVD_MODE_NORMAL ((uint32_t)0x00000000) /*!< basic mode is used */ #define PWR_PVD_MODE_IT_RISING ((uint32_t)0x00010001) /*!< External Interrupt Mode with Rising edge trigger detection */ #define PWR_PVD_MODE_IT_FALLING ((uint32_t)0x00010002) /*!< External Interrupt Mode with Falling edge trigger detection */ #define PWR_PVD_MODE_IT_RISING_FALLING ((uint32_t)0x00010003) /*!< External Interrupt Mode with Rising/Falling edge trigger detection */ #define PWR_PVD_MODE_EVENT_RISING ((uint32_t)0x00020001) /*!< Event Mode with Rising edge trigger detection */ #define PWR_PVD_MODE_EVENT_FALLING ((uint32_t)0x00020002) /*!< Event Mode with Falling edge trigger detection */ #define PWR_PVD_MODE_EVENT_RISING_FALLING ((uint32_t)0x00020003) /*!< Event Mode with Rising/Falling edge trigger detection */ #define IS_PWR_PVD_MODE(MODE) (((MODE) == PWR_PVD_MODE_IT_RISING)|| ((MODE) == PWR_PVD_MODE_IT_FALLING) || \ ((MODE) == PWR_PVD_MODE_IT_RISING_FALLING) || ((MODE) == PWR_PVD_MODE_EVENT_RISING) || \ ((MODE) == PWR_PVD_MODE_EVENT_FALLING) || ((MODE) == PWR_PVD_MODE_EVENT_RISING_FALLING) || \ ((MODE) == PWR_PVD_MODE_NORMAL)) /** * @} */ #endif /* defined (STM32F031x6) || defined (STM32F042x6) || defined (STM32F051x8) || */ /* defined (STM32F071xB) || defined (STM32F072xB) || */ /* defined (STM32F091xC) */ /** @defgroup PWREx_Flag PWREx Flag * @{ */ #if defined (STM32F031x6) || defined (STM32F042x6) || defined (STM32F051x8) || \ defined (STM32F071xB) || defined (STM32F072xB) || \ defined (STM32F091xC) #define PWR_FLAG_WU PWR_CSR_WUF #define PWR_FLAG_SB PWR_CSR_SBF #define PWR_FLAG_PVDO PWR_CSR_PVDO #define PWR_FLAG_VREFINTRDY PWR_CSR_VREFINTRDYF #elif defined (STM32F070x6) || defined (STM32F070xB) || defined (STM32F030xC) #define PWR_FLAG_WU PWR_CSR_WUF #define PWR_FLAG_SB PWR_CSR_SBF #define PWR_FLAG_VREFINTRDY PWR_CSR_VREFINTRDYF #else #define PWR_FLAG_WU PWR_CSR_WUF #define PWR_FLAG_SB PWR_CSR_SBF #endif /* defined (STM32F031x6) || defined (STM32F042x6) || defined (STM32F051x8) || */ /* defined (STM32F071xB) || defined (STM32F072xB) || */ /* defined (STM32F091xC) */ /** * @} */ /** * @} */ /* Exported macro ------------------------------------------------------------*/ /** @defgroup PWREx_Exported_Macros PWREx Exported Macros * @{ */ #if defined (STM32F031x6) || defined (STM32F042x6) || defined (STM32F051x8) || \ defined (STM32F071xB) || defined (STM32F072xB) || \ defined (STM32F091xC) /** * @brief Enable interrupt on PVD Exti Line 16. * @retval None. */ #define __HAL_PWR_PVD_EXTI_ENABLE_IT() (EXTI->IMR |= (PWR_EXTI_LINE_PVD)) /** * @brief Disable interrupt on PVD Exti Line 16. * @retval None. */ #define __HAL_PWR_PVD_EXTI_DISABLE_IT() (EXTI->IMR &= ~(PWR_EXTI_LINE_PVD)) /** * @brief Enable event on PVD Exti Line 16. * @retval None. */ #define __HAL_PWR_PVD_EXTI_ENABLE_EVENT() (EXTI->EMR |= (PWR_EXTI_LINE_PVD)) /** * @brief Disable event on PVD Exti Line 16. * @retval None. */ #define __HAL_PWR_PVD_EXTI_DISABLE_EVENT() (EXTI->EMR &= ~(PWR_EXTI_LINE_PVD)) /** * @brief Disable the PVD Extended Interrupt Rising Trigger. * @retval None. */ #define __HAL_PWR_PVD_EXTI_DISABLE_RISING_EDGE() CLEAR_BIT(EXTI->RTSR, PWR_EXTI_LINE_PVD) /** * @brief Disable the PVD Extended Interrupt Falling Trigger. * @retval None. */ #define __HAL_PWR_PVD_EXTI_DISABLE_FALLING_EDGE() CLEAR_BIT(EXTI->FTSR, PWR_EXTI_LINE_PVD) /** * @brief Disable the PVD Extended Interrupt Rising & Falling Trigger. * @retval None */ #define __HAL_PWR_PVD_EXTI_DISABLE_RISING_FALLING_EDGE() __HAL_PWR_PVD_EXTI_DISABLE_RISING_EDGE();__HAL_PWR_PVD_EXTI_DISABLE_FALLING_EDGE(); /** * @brief PVD EXTI line configuration: set falling edge trigger. * @retval None. */ #define __HAL_PWR_PVD_EXTI_ENABLE_FALLING_EDGE() EXTI->FTSR |= (PWR_EXTI_LINE_PVD) /** * @brief PVD EXTI line configuration: set rising edge trigger. * @retval None. */ #define __HAL_PWR_PVD_EXTI_ENABLE_RISING_EDGE() EXTI->RTSR |= (PWR_EXTI_LINE_PVD) /** * @brief Enable the PVD Extended Interrupt Rising & Falling Trigger. * @retval None */ #define __HAL_PWR_PVD_EXTI_ENABLE_RISING_FALLING_EDGE() __HAL_PWR_PVD_EXTI_ENABLE_RISING_EDGE();__HAL_PWR_PVD_EXTI_ENABLE_FALLING_EDGE(); /** * @brief Check whether the specified PVD EXTI interrupt flag is set or not. * @retval EXTI PVD Line Status. */ #define __HAL_PWR_PVD_EXTI_GET_FLAG() (EXTI->PR & (PWR_EXTI_LINE_PVD)) /** * @brief Clear the PVD EXTI flag. * @retval None. */ #define __HAL_PWR_PVD_EXTI_CLEAR_FLAG() (EXTI->PR = (PWR_EXTI_LINE_PVD)) /** * @brief Generate a Software interrupt on selected EXTI line. * @retval None. */ #define __HAL_PWR_PVD_EXTI_GENERATE_SWIT() (EXTI->SWIER |= (PWR_EXTI_LINE_PVD)) #endif /* defined (STM32F031x6) || defined (STM32F042x6) || defined (STM32F051x8) || */ /* defined (STM32F071xB) || defined (STM32F072xB) || */ /* defined (STM32F091xC) */ #if defined (STM32F042x6) || defined (STM32F048xx) || \ defined (STM32F071xB) || defined (STM32F072xB) || defined (STM32F078xx) || \ defined (STM32F091xC) || defined (STM32F098xx) /** * @brief Enable interrupt on Vddio2 Monitor Exti Line 31. * @retval None. */ #define __HAL_PWR_VDDIO2_EXTI_ENABLE_IT() (EXTI->IMR |= (PWR_EXTI_LINE_VDDIO2)) /** * @brief Disable interrupt on Vddio2 Monitor Exti Line 31. * @retval None. */ #define __HAL_PWR_VDDIO2_EXTI_DISABLE_IT() (EXTI->IMR &= ~(PWR_EXTI_LINE_VDDIO2)) /** * @brief Vddio2 Monitor EXTI line configuration: clear falling edge and rising edge trigger. * @retval None. */ #define __HAL_PWR_VDDIO2_EXTI_DISABLE_FALLING_EDGE() EXTI->FTSR &= ~(PWR_EXTI_LINE_VDDIO2); \ EXTI->RTSR &= ~(PWR_EXTI_LINE_VDDIO2) /** * @brief Vddio2 Monitor EXTI line configuration: set falling edge trigger. * @retval None. */ #define __HAL_PWR_VDDIO2_EXTI_ENABLE_FALLING_EDGE() EXTI->FTSR |= (PWR_EXTI_LINE_VDDIO2) /** * @brief Check whether the specified VDDIO2 monitor EXTI interrupt flag is set or not. * @retval EXTI VDDIO2 Monitor Line Status. */ #define __HAL_PWR_VDDIO2_EXTI_GET_FLAG() (EXTI->PR & (PWR_EXTI_LINE_VDDIO2)) /** * @brief Clear the VDDIO2 Monitor EXTI flag. * @retval None. */ #define __HAL_PWR_VDDIO2_EXTI_CLEAR_FLAG() (EXTI->PR = (PWR_EXTI_LINE_VDDIO2)) /** * @brief Generate a Software interrupt on selected EXTI line. * @retval None. */ #define __HAL_PWR_VDDIO2_EXTI_GENERATE_SWIT() (EXTI->SWIER |= (PWR_EXTI_LINE_VDDIO2)) #endif /* defined (STM32F042x6) || defined (STM32F048xx) ||\ defined (STM32F071xB) || defined (STM32F072xB) || defined (STM32F078xx) || \ defined (STM32F091xC) || defined (STM32F098xx) */ /** * @} */ /* Exported functions --------------------------------------------------------*/ /** @addtogroup PWREx_Exported_Functions PWREx Exported Functions * @{ */ /** @addtogroup PWREx_Exported_Functions_Group1 * @{ */ /* I/O operation functions ***************************************************/ #if defined (STM32F031x6) || defined (STM32F042x6) || defined (STM32F051x8) || \ defined (STM32F071xB) || defined (STM32F072xB) || \ defined (STM32F091xC) void HAL_PWR_PVD_IRQHandler(void); void HAL_PWR_PVDCallback(void); #endif /* defined (STM32F031x6) || defined (STM32F042x6) || defined (STM32F051x8) || */ /* defined (STM32F071xB) || defined (STM32F072xB) || */ /* defined (STM32F091xC) */ #if defined (STM32F042x6) || defined (STM32F048xx) || \ defined (STM32F071xB) || defined (STM32F072xB) || defined (STM32F078xx) || \ defined (STM32F091xC) || defined (STM32F098xx) void HAL_PWREx_Vddio2Monitor_IRQHandler(void); void HAL_PWREx_Vddio2MonitorCallback(void); #endif /* defined (STM32F042x6) || defined (STM32F048xx) || \ defined (STM32F071xB) || defined (STM32F072xB) || defined (STM32F078xx) || \ defined (STM32F091xC) || defined (STM32F098xx) */ /* Peripheral Control functions **********************************************/ #if defined (STM32F031x6) || defined (STM32F042x6) || defined (STM32F051x8) || \ defined (STM32F071xB) || defined (STM32F072xB) || \ defined (STM32F091xC) void HAL_PWR_ConfigPVD(PWR_PVDTypeDef *sConfigPVD); void HAL_PWR_EnablePVD(void); void HAL_PWR_DisablePVD(void); #endif /* defined (STM32F031x6) || defined (STM32F042x6) || defined (STM32F051x8) || */ /* defined (STM32F071xB) || defined (STM32F072xB) || */ /* defined (STM32F091xC) */ #if defined (STM32F042x6) || defined (STM32F048xx) || \ defined (STM32F071xB) || defined (STM32F072xB) || defined (STM32F078xx) || \ defined (STM32F091xC) || defined (STM32F098xx) void HAL_PWREx_EnableVddio2Monitor(void); void HAL_PWREx_DisableVddio2Monitor(void); #endif /* defined (STM32F042x6) || defined (STM32F048xx) || \ defined (STM32F071xB) || defined (STM32F072xB) || defined (STM32F078xx) || \ defined (STM32F091xC) || defined (STM32F098xx) */ /** * @} */ /** * @} */ /** * @} */ /** * @} */ #ifdef __cplusplus } #endif #endif /* __STM32F0xx_HAL_PWR_EX_H */ /************************ (C) COPYRIGHT STMicroelectronics *****END OF FILE****/ ================================================ FILE: Zelig/mbed/TARGET_NUCLEO_F091RC/stm32f0xx_hal_rcc.h ================================================ /** ****************************************************************************** * @file stm32f0xx_hal_rcc.h * @author MCD Application Team * @version V1.3.0 * @date 26-June-2015 * @brief Header file of RCC HAL module. ****************************************************************************** * @attention * *

© COPYRIGHT(c) 2015 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. * ****************************************************************************** */ /* Define to prevent recursive inclusion -------------------------------------*/ #ifndef __STM32F0xx_HAL_RCC_H #define __STM32F0xx_HAL_RCC_H #ifdef __cplusplus extern "C" { #endif /* Includes ------------------------------------------------------------------*/ #include "stm32f0xx_hal_def.h" /** @addtogroup STM32F0xx_HAL_Driver * @{ */ /** @addtogroup RCC * @{ */ /** @addtogroup RCC_Private_Constants * @{ */ /** @defgroup RCC_Timeout RCC Timeout * @{ */ /* Disable Backup domain write protection state change timeout */ #define RCC_DBP_TIMEOUT_VALUE ((uint32_t)100) /* 100 ms */ /* LSE state change timeout */ #define RCC_LSE_TIMEOUT_VALUE LSE_STARTUP_TIMEOUT #define CLOCKSWITCH_TIMEOUT_VALUE ((uint32_t)5000) /* 5 s */ #define HSE_TIMEOUT_VALUE HSE_STARTUP_TIMEOUT #define HSI_TIMEOUT_VALUE ((uint32_t)100) /* 100 ms */ #define LSI_TIMEOUT_VALUE ((uint32_t)100) /* 100 ms */ #define PLL_TIMEOUT_VALUE ((uint32_t)100) /* 100 ms */ #define HSI14_TIMEOUT_VALUE ((uint32_t)100) /* 100 ms */ #define HSI48_TIMEOUT_VALUE ((uint32_t)100) /* 100 ms */ /** * @} */ /** @defgroup RCC_Register_Offset Register offsets * @{ */ #define RCC_OFFSET (RCC_BASE - PERIPH_BASE) #define RCC_CR_OFFSET 0x00 #define RCC_CFGR_OFFSET 0x04 #define RCC_CIR_OFFSET 0x08 #define RCC_BDCR_OFFSET 0x20 #define RCC_CSR_OFFSET 0x24 /** * @} */ /* CR register byte 2 (Bits[23:16]) base address */ #define RCC_CR_BYTE2_ADDRESS ((uint32_t)(RCC_BASE + RCC_CR_OFFSET + 0x02)) /* CIR register byte 1 (Bits[15:8]) base address */ #define RCC_CIR_BYTE1_ADDRESS ((uint32_t)(RCC_BASE + RCC_CIR_OFFSET + 0x01)) /* CIR register byte 2 (Bits[23:16]) base address */ #define RCC_CIR_BYTE2_ADDRESS ((uint32_t)(RCC_BASE + RCC_CIR_OFFSET + 0x02)) /* Defines used for Flags */ #define CR_REG_INDEX ((uint8_t)1) #define CR2_REG_INDEX 2 #define BDCR_REG_INDEX 3 #define CSR_REG_INDEX 4 /* Flags in the CFGR register */ #define RCC_CFGR_PLLMUL_BITNUMBER 18 #define RCC_CFGR_HPRE_BITNUMBER 4 #define RCC_CFGR_PPRE_BITNUMBER 8 /* Flags in the CFGR2 register */ #define RCC_CFGR2_PREDIV_BITNUMBER 0 /* Flags in the CR register */ #define RCC_CR_HSIRDY_BitNumber 1 #define RCC_CR_HSERDY_BitNumber 17 #define RCC_CR_PLLRDY_BitNumber 25 /* Flags in the CR2 register */ #define RCC_CR2_HSI14RDY_BitNumber 1 #define RCC_CR2_HSI48RDY_BitNumber 16 /* Flags in the BDCR register */ #define RCC_BDCR_LSERDY_BitNumber 1 /* Flags in the CSR register */ #define RCC_CSR_LSIRDY_BitNumber 1 #define RCC_CSR_V18PWRRSTF_BitNumber 23 #define RCC_CSR_RMVF_BitNumber 24 #define RCC_CSR_OBLRSTF_BitNumber 25 #define RCC_CSR_PINRSTF_BitNumber 26 #define RCC_CSR_PORRSTF_BitNumber 27 #define RCC_CSR_SFTRSTF_BitNumber 28 #define RCC_CSR_IWDGRSTF_BitNumber 29 #define RCC_CSR_WWDGRSTF_BitNumber 30 #define RCC_CSR_LPWRRSTF_BitNumber 31 /* Flags in the HSITRIM register */ #define RCC_CR_HSITRIM_BitNumber 3 #define RCC_FLAG_MASK ((uint8_t)0x1F) /** * @} */ /** @addtogroup RCC_Private_Macros * @{ */ #define IS_RCC_HSE(__HSE__) (((__HSE__) == RCC_HSE_OFF) || ((__HSE__) == RCC_HSE_ON) || \ ((__HSE__) == RCC_HSE_BYPASS)) #define IS_RCC_LSE(__LSE__) (((__LSE__) == RCC_LSE_OFF) || ((__LSE__) == RCC_LSE_ON) || \ ((__LSE__) == RCC_LSE_BYPASS)) #define IS_RCC_HSI(__HSI__) (((__HSI__) == RCC_HSI_OFF) || ((__HSI__) == RCC_HSI_ON)) #define IS_RCC_HSI14(__HSI14__) (((__HSI14__) == RCC_HSI14_OFF) || ((__HSI14__) == RCC_HSI14_ON) || ((__HSI14__) == RCC_HSI14_ADC_CONTROL)) #define IS_RCC_CALIBRATION_VALUE(__VALUE__) ((__VALUE__) <= 0x1F) #define IS_RCC_LSI(__LSI__) (((__LSI__) == RCC_LSI_OFF) || ((__LSI__) == RCC_LSI_ON)) #define IS_RCC_PLL(__PLL__) (((__PLL__) == RCC_PLL_NONE) || ((__PLL__) == RCC_PLL_OFF) || \ ((__PLL__) == RCC_PLL_ON)) #define IS_RCC_PREDIV(__PREDIV__) (((__PREDIV__) == RCC_PREDIV_DIV1) || ((__PREDIV__) == RCC_PREDIV_DIV2) || \ ((__PREDIV__) == RCC_PREDIV_DIV3) || ((__PREDIV__) == RCC_PREDIV_DIV4) || \ ((__PREDIV__) == RCC_PREDIV_DIV5) || ((__PREDIV__) == RCC_PREDIV_DIV6) || \ ((__PREDIV__) == RCC_PREDIV_DIV7) || ((__PREDIV__) == RCC_PREDIV_DIV8) || \ ((__PREDIV__) == RCC_PREDIV_DIV9) || ((__PREDIV__) == RCC_PREDIV_DIV10) || \ ((__PREDIV__) == RCC_PREDIV_DIV11) || ((__PREDIV__) == RCC_PREDIV_DIV12) || \ ((__PREDIV__) == RCC_PREDIV_DIV13) || ((__PREDIV__) == RCC_PREDIV_DIV14) || \ ((__PREDIV__) == RCC_PREDIV_DIV15) || ((__PREDIV__) == RCC_PREDIV_DIV16)) #define IS_RCC_PLL_MUL(__MUL__) (((__MUL__) == RCC_PLL_MUL2) || ((__MUL__) == RCC_PLL_MUL3) || \ ((__MUL__) == RCC_PLL_MUL4) || ((__MUL__) == RCC_PLL_MUL5) || \ ((__MUL__) == RCC_PLL_MUL6) || ((__MUL__) == RCC_PLL_MUL7) || \ ((__MUL__) == RCC_PLL_MUL8) || ((__MUL__) == RCC_PLL_MUL9) || \ ((__MUL__) == RCC_PLL_MUL10) || ((__MUL__) == RCC_PLL_MUL11) || \ ((__MUL__) == RCC_PLL_MUL12) || ((__MUL__) == RCC_PLL_MUL13) || \ ((__MUL__) == RCC_PLL_MUL14) || ((__MUL__) == RCC_PLL_MUL15) || \ ((__MUL__) == RCC_PLL_MUL16)) #define IS_RCC_CLOCKTYPE(__CLK__) ((((__CLK__) & RCC_CLOCKTYPE_SYSCLK) == RCC_CLOCKTYPE_SYSCLK) || \ (((__CLK__) & RCC_CLOCKTYPE_HCLK) == RCC_CLOCKTYPE_HCLK) || \ (((__CLK__) & RCC_CLOCKTYPE_PCLK1) == RCC_CLOCKTYPE_PCLK1)) #define IS_RCC_HCLK(__HCLK__) (((__HCLK__) == RCC_SYSCLK_DIV1) || ((__HCLK__) == RCC_SYSCLK_DIV2) || \ ((__HCLK__) == RCC_SYSCLK_DIV4) || ((__HCLK__) == RCC_SYSCLK_DIV8) || \ ((__HCLK__) == RCC_SYSCLK_DIV16) || ((__HCLK__) == RCC_SYSCLK_DIV64) || \ ((__HCLK__) == RCC_SYSCLK_DIV128) || ((__HCLK__) == RCC_SYSCLK_DIV256) || \ ((__HCLK__) == RCC_SYSCLK_DIV512)) #define IS_RCC_PCLK(__PCLK__) (((__PCLK__) == RCC_HCLK_DIV1) || ((__PCLK__) == RCC_HCLK_DIV2) || \ ((__PCLK__) == RCC_HCLK_DIV4) || ((__PCLK__) == RCC_HCLK_DIV8) || \ ((__PCLK__) == RCC_HCLK_DIV16)) #define IS_RCC_MCO(__MCO__) (((__MCO__) == RCC_MCO)) #define IS_RCC_RTCCLKSOURCE(__SOURCE__) (((__SOURCE__) == RCC_RTCCLKSOURCE_NO_CLK) || \ ((__SOURCE__) == RCC_RTCCLKSOURCE_LSE) || \ ((__SOURCE__) == RCC_RTCCLKSOURCE_LSI) || \ ((__SOURCE__) == RCC_RTCCLKSOURCE_HSE_DIV32)) #define IS_RCC_USART1CLKSOURCE(__SOURCE__) (((__SOURCE__) == RCC_USART1CLKSOURCE_PCLK1) || \ ((__SOURCE__) == RCC_USART1CLKSOURCE_SYSCLK) || \ ((__SOURCE__) == RCC_USART1CLKSOURCE_LSE) || \ ((__SOURCE__) == RCC_USART1CLKSOURCE_HSI)) #define IS_RCC_I2C1CLKSOURCE(__SOURCE__) (((__SOURCE__) == RCC_I2C1CLKSOURCE_HSI) || \ ((__SOURCE__) == RCC_I2C1CLKSOURCE_SYSCLK)) /** * @} */ /* Exported types ------------------------------------------------------------*/ /** @defgroup RCC_Exported_Types RCC Exported Types * @{ */ /** * @brief RCC PLL configuration structure definition */ typedef struct { uint32_t PLLState; /*!< The new state of the PLL. This parameter can be a value of @ref RCC_PLL_Config */ uint32_t PLLSource; /*!< PLLSource: PLL entry clock source. This parameter must be a value of @ref RCC_PLL_Clock_Source */ uint32_t PLLMUL; /*!< PLLMUL: Multiplication factor for PLL VCO input clock This parameter must be a value of @ref RCC_PLL_Multiplication_Factor*/ uint32_t PREDIV; /*!< PREDIV: Predivision factor for PLL VCO input clock This parameter must be a value of @ref RCC_PLL_Prediv_Factor */ } RCC_PLLInitTypeDef; /** * @brief RCC Internal/External Oscillator (HSE, HSI, LSE and LSI) configuration structure definition */ typedef struct { uint32_t OscillatorType; /*!< The oscillators to be configured. This parameter can be a value of @ref RCC_Oscillator_Type */ uint32_t HSEState; /*!< The new state of the HSE. This parameter can be a value of @ref RCC_HSE_Config */ uint32_t LSEState; /*!< The new state of the LSE. This parameter can be a value of @ref RCC_LSE_Config */ uint32_t HSIState; /*!< The new state of the HSI. This parameter can be a value of @ref RCC_HSI_Config */ uint32_t HSICalibrationValue; /*!< The HSI calibration trimming value (default is RCC_HSICALIBRATION_DEFAULT). This parameter must be a number between Min_Data = 0x00 and Max_Data = 0x1F */ uint32_t HSI14State; /*!< The new state of the HSI14. This parameter can be a value of @ref RCC_HSI14_Config */ uint32_t HSI14CalibrationValue; /*!< The HSI14 calibration trimming value (default is RCC_HSI14CALIBRATION_DEFAULT). This parameter must be a number between Min_Data = 0x00 and Max_Data = 0x1F */ uint32_t HSI48State; /*!< The new state of the HSI48 (only applicable to STM32F07x, STM32F0x2 and STM32F09x devices). This parameter can be a value of @ref RCCEx_HSI48_Config */ uint32_t LSIState; /*!< The new state of the LSI. This parameter can be a value of @ref RCC_LSI_Config */ RCC_PLLInitTypeDef PLL; /*!< PLL structure parameters */ } RCC_OscInitTypeDef; /** * @brief RCC System, AHB and APB busses clock configuration structure definition */ typedef struct { uint32_t ClockType; /*!< The clock to be configured. This parameter can be a value of @ref RCC_System_Clock_Type */ uint32_t SYSCLKSource; /*!< The clock source (SYSCLKS) used as system clock. This parameter can be a value of @ref RCC_System_Clock_Source */ uint32_t AHBCLKDivider; /*!< The AHB clock (HCLK) divider. This clock is derived from the system clock (SYSCLK). This parameter can be a value of @ref RCC_AHB_Clock_Source */ uint32_t APB1CLKDivider; /*!< The APB1 clock (PCLK1) divider. This clock is derived from the AHB clock (HCLK). This parameter can be a value of @ref RCC_APB1_Clock_Source */ } RCC_ClkInitTypeDef; /** * @} */ /* Exported constants --------------------------------------------------------*/ /** @defgroup RCC_Exported_Constants RCC Exported Constants * @{ */ /** @defgroup RCC_PLL_Clock_Source PLL Clock Source * @{ */ #define RCC_PLLSOURCE_HSE RCC_CFGR_PLLSRC_HSE_PREDIV /*!< HSE clock selected as PLL entry clock source */ /** * @} */ /** @defgroup RCC_Oscillator_Type Oscillator Type * @{ */ #define RCC_OSCILLATORTYPE_NONE ((uint32_t)0x00000000) #define RCC_OSCILLATORTYPE_HSE ((uint32_t)0x00000001) #define RCC_OSCILLATORTYPE_HSI ((uint32_t)0x00000002) #define RCC_OSCILLATORTYPE_LSE ((uint32_t)0x00000004) #define RCC_OSCILLATORTYPE_LSI ((uint32_t)0x00000008) #define RCC_OSCILLATORTYPE_HSI14 ((uint32_t)0x00000010) /** * @} */ /** @defgroup RCC_HSE_Config HSE Config * @{ */ #define RCC_HSE_OFF ((uint32_t)0x00000000) /*!< HSE clock deactivation */ #define RCC_HSE_ON ((uint32_t)0x00000001) /*!< HSE clock activation */ #define RCC_HSE_BYPASS ((uint32_t)0x00000005) /*!< External clock source for HSE clock */ /** * @} */ /** @defgroup RCC_LSE_Config LSE Config * @{ */ #define RCC_LSE_OFF ((uint32_t)0x00000000) /*!< LSE clock deactivation */ #define RCC_LSE_ON ((uint32_t)0x00000001) /*!< LSE clock activation */ #define RCC_LSE_BYPASS ((uint32_t)0x00000005) /*!< External clock source for LSE clock */ /** * @} */ /** @defgroup RCC_HSI_Config HSI Config * @{ */ #define RCC_HSI_OFF ((uint32_t)0x00000000) /*!< HSI clock deactivation */ #define RCC_HSI_ON RCC_CR_HSION /*!< HSI clock activation */ #define RCC_HSICALIBRATION_DEFAULT ((uint32_t)0x10) /* Default HSI calibration trimming value */ /** * @} */ /** @defgroup RCC_HSI14_Config RCC HSI14 Config * @{ */ #define RCC_HSI14_OFF ((uint32_t)0x00) #define RCC_HSI14_ON RCC_CR2_HSI14ON #define RCC_HSI14_ADC_CONTROL (~RCC_CR2_HSI14DIS) #define RCC_HSI14CALIBRATION_DEFAULT ((uint32_t)0x10) /* Default HSI14 calibration trimming value */ /** * @} */ /** @defgroup RCC_LSI_Config LSI Config * @{ */ #define RCC_LSI_OFF ((uint32_t)0x00000000) /*!< LSI clock deactivation */ #define RCC_LSI_ON RCC_CSR_LSION /*!< LSI clock activation */ /** * @} */ /** @defgroup RCC_PLL_Config PLL Config * @{ */ #define RCC_PLL_NONE ((uint32_t)0x00000000) /*!< PLL is not configured */ #define RCC_PLL_OFF ((uint32_t)0x00000001) /*!< PLL deactivation */ #define RCC_PLL_ON ((uint32_t)0x00000002) /*!< PLL activation */ /** * @} */ /** @defgroup RCC_System_Clock_Type System Clock Type * @{ */ #define RCC_CLOCKTYPE_SYSCLK ((uint32_t)0x00000001) /*!< SYSCLK to configure */ #define RCC_CLOCKTYPE_HCLK ((uint32_t)0x00000002) /*!< HCLK to configure */ #define RCC_CLOCKTYPE_PCLK1 ((uint32_t)0x00000004) /*!< PCLK1 to configure */ /** * @} */ /** @defgroup RCC_System_Clock_Source System Clock Source * @{ */ #define RCC_SYSCLKSOURCE_HSI ((uint32_t)RCC_CFGR_SW_HSI) /*!< HSI selected as system clock */ #define RCC_SYSCLKSOURCE_HSE ((uint32_t)RCC_CFGR_SW_HSE) /*!< HSE selected as system clock */ #define RCC_SYSCLKSOURCE_PLLCLK ((uint32_t)RCC_CFGR_SW_PLL) /*!< PLL selected as system clock */ /** * @} */ /** @defgroup RCC_System_Clock_Source_Status System Clock Source Status * @{ */ #define RCC_SYSCLKSOURCE_STATUS_HSI RCC_CFGR_SWS_HSI /*!< HSI used as system clock */ #define RCC_SYSCLKSOURCE_STATUS_HSE RCC_CFGR_SWS_HSE /*!< HSE used as system clock */ #define RCC_SYSCLKSOURCE_STATUS_PLLCLK RCC_CFGR_SWS_PLL /*!< PLL used as system clock */ /** * @} */ /** @defgroup RCC_AHB_Clock_Source AHB Clock Source * @{ */ #define RCC_SYSCLK_DIV1 ((uint32_t)RCC_CFGR_HPRE_DIV1) #define RCC_SYSCLK_DIV2 ((uint32_t)RCC_CFGR_HPRE_DIV2) #define RCC_SYSCLK_DIV4 ((uint32_t)RCC_CFGR_HPRE_DIV4) #define RCC_SYSCLK_DIV8 ((uint32_t)RCC_CFGR_HPRE_DIV8) #define RCC_SYSCLK_DIV16 ((uint32_t)RCC_CFGR_HPRE_DIV16) #define RCC_SYSCLK_DIV64 ((uint32_t)RCC_CFGR_HPRE_DIV64) #define RCC_SYSCLK_DIV128 ((uint32_t)RCC_CFGR_HPRE_DIV128) #define RCC_SYSCLK_DIV256 ((uint32_t)RCC_CFGR_HPRE_DIV256) #define RCC_SYSCLK_DIV512 ((uint32_t)RCC_CFGR_HPRE_DIV512) /** * @} */ /** @defgroup RCC_APB1_Clock_Source RCC APB1 Clock Source * @{ */ #define RCC_HCLK_DIV1 RCC_CFGR_PPRE_DIV1 #define RCC_HCLK_DIV2 RCC_CFGR_PPRE_DIV2 #define RCC_HCLK_DIV4 RCC_CFGR_PPRE_DIV4 #define RCC_HCLK_DIV8 RCC_CFGR_PPRE_DIV8 #define RCC_HCLK_DIV16 RCC_CFGR_PPRE_DIV16 /** * @} */ /** @defgroup RCC_RTC_Clock_Source RTC Clock Source * @{ */ #define RCC_RTCCLKSOURCE_NO_CLK ((uint32_t)0x00000000) /*!< No clock */ #define RCC_RTCCLKSOURCE_LSE ((uint32_t)RCC_BDCR_RTCSEL_LSE) /*!< LSE oscillator clock used as RTC clock */ #define RCC_RTCCLKSOURCE_LSI ((uint32_t)RCC_BDCR_RTCSEL_LSI) /*!< LSI oscillator clock used as RTC clock */ #define RCC_RTCCLKSOURCE_HSE_DIV32 ((uint32_t)RCC_BDCR_RTCSEL_HSE) /*!< HSE oscillator clock divided by 32 used as RTC clock */ /** * @} */ /** @defgroup RCC_PLL_Prediv_Factor RCC PLL Prediv Factor * @{ */ #define RCC_PREDIV_DIV1 RCC_CFGR2_PREDIV_DIV1 #define RCC_PREDIV_DIV2 RCC_CFGR2_PREDIV_DIV2 #define RCC_PREDIV_DIV3 RCC_CFGR2_PREDIV_DIV3 #define RCC_PREDIV_DIV4 RCC_CFGR2_PREDIV_DIV4 #define RCC_PREDIV_DIV5 RCC_CFGR2_PREDIV_DIV5 #define RCC_PREDIV_DIV6 RCC_CFGR2_PREDIV_DIV6 #define RCC_PREDIV_DIV7 RCC_CFGR2_PREDIV_DIV7 #define RCC_PREDIV_DIV8 RCC_CFGR2_PREDIV_DIV8 #define RCC_PREDIV_DIV9 RCC_CFGR2_PREDIV_DIV9 #define RCC_PREDIV_DIV10 RCC_CFGR2_PREDIV_DIV10 #define RCC_PREDIV_DIV11 RCC_CFGR2_PREDIV_DIV11 #define RCC_PREDIV_DIV12 RCC_CFGR2_PREDIV_DIV12 #define RCC_PREDIV_DIV13 RCC_CFGR2_PREDIV_DIV13 #define RCC_PREDIV_DIV14 RCC_CFGR2_PREDIV_DIV14 #define RCC_PREDIV_DIV15 RCC_CFGR2_PREDIV_DIV15 #define RCC_PREDIV_DIV16 RCC_CFGR2_PREDIV_DIV16 /** * @} */ /** @defgroup RCC_PLL_Multiplication_Factor RCC PLL Multiplication Factor * @{ */ #define RCC_PLL_MUL2 RCC_CFGR_PLLMUL2 #define RCC_PLL_MUL3 RCC_CFGR_PLLMUL3 #define RCC_PLL_MUL4 RCC_CFGR_PLLMUL4 #define RCC_PLL_MUL5 RCC_CFGR_PLLMUL5 #define RCC_PLL_MUL6 RCC_CFGR_PLLMUL6 #define RCC_PLL_MUL7 RCC_CFGR_PLLMUL7 #define RCC_PLL_MUL8 RCC_CFGR_PLLMUL8 #define RCC_PLL_MUL9 RCC_CFGR_PLLMUL9 #define RCC_PLL_MUL10 RCC_CFGR_PLLMUL10 #define RCC_PLL_MUL11 RCC_CFGR_PLLMUL11 #define RCC_PLL_MUL12 RCC_CFGR_PLLMUL12 #define RCC_PLL_MUL13 RCC_CFGR_PLLMUL13 #define RCC_PLL_MUL14 RCC_CFGR_PLLMUL14 #define RCC_PLL_MUL15 RCC_CFGR_PLLMUL15 #define RCC_PLL_MUL16 RCC_CFGR_PLLMUL16 /** * @} */ /** @defgroup RCC_USART1_Clock_Source RCC USART1 Clock Source * @{ */ #define RCC_USART1CLKSOURCE_PCLK1 RCC_CFGR3_USART1SW_PCLK #define RCC_USART1CLKSOURCE_SYSCLK RCC_CFGR3_USART1SW_SYSCLK #define RCC_USART1CLKSOURCE_LSE RCC_CFGR3_USART1SW_LSE #define RCC_USART1CLKSOURCE_HSI RCC_CFGR3_USART1SW_HSI /** * @} */ /** @defgroup RCC_I2C1_Clock_Source RCC I2C1 Clock Source * @{ */ #define RCC_I2C1CLKSOURCE_HSI RCC_CFGR3_I2C1SW_HSI #define RCC_I2C1CLKSOURCE_SYSCLK RCC_CFGR3_I2C1SW_SYSCLK /** * @} */ /** @defgroup RCC_MCO_Index MCO Index * @{ */ #define RCC_MCO1 ((uint32_t)0x00000000) #define RCC_MCO RCC_MCO1 /*!< MCO1 to be compliant with other families with 2 MCOs*/ /** * @} */ /** @defgroup RCC_MCO_Clock_Source RCC MCO Clock Source * @{ */ #define RCC_MCOSOURCE_NONE RCC_CFGR_MCO_NOCLOCK #define RCC_MCOSOURCE_LSI RCC_CFGR_MCO_LSI #define RCC_MCOSOURCE_LSE RCC_CFGR_MCO_LSE #define RCC_MCOSOURCE_SYSCLK RCC_CFGR_MCO_SYSCLK #define RCC_MCOSOURCE_HSI RCC_CFGR_MCO_HSI #define RCC_MCOSOURCE_HSE RCC_CFGR_MCO_HSE #define RCC_MCOSOURCE_PLLCLK_DIV2 RCC_CFGR_MCO_PLL #define RCC_MCOSOURCE_HSI14 RCC_CFGR_MCO_HSI14 /** * @} */ /** @defgroup RCC_Interrupt Interrupts * @{ */ #define RCC_IT_LSIRDY ((uint8_t)RCC_CIR_LSIRDYF) /*!< LSI Ready Interrupt flag */ #define RCC_IT_LSERDY ((uint8_t)RCC_CIR_LSERDYF) /*!< LSE Ready Interrupt flag */ #define RCC_IT_HSIRDY ((uint8_t)RCC_CIR_HSIRDYF) /*!< HSI Ready Interrupt flag */ #define RCC_IT_HSERDY ((uint8_t)RCC_CIR_HSERDYF) /*!< HSE Ready Interrupt flag */ #define RCC_IT_PLLRDY ((uint8_t)RCC_CIR_PLLRDYF) /*!< PLL Ready Interrupt flag */ #define RCC_IT_HSI14 ((uint8_t)RCC_CIR_HSI14RDYF) /*!< HSI14 Ready Interrupt flag */ #define RCC_IT_CSS ((uint8_t)RCC_CIR_CSSF) /*!< Clock Security System Interrupt flag */ /** * @} */ /** @defgroup RCC_Flag Flags * Elements values convention: XXXYYYYYb * - YYYYY : Flag position in the register * - XXX : Register index * - 001: CR register * - 010: CR2 register * - 011: BDCR register * - 0100: CSR register * @{ */ /* Flags in the CR register */ #define RCC_FLAG_HSIRDY ((uint8_t)((CR_REG_INDEX << 5) | RCC_CR_HSIRDY_BitNumber)) #define RCC_FLAG_HSERDY ((uint8_t)((CR_REG_INDEX << 5) | RCC_CR_HSERDY_BitNumber)) #define RCC_FLAG_PLLRDY ((uint8_t)((CR_REG_INDEX << 5) | RCC_CR_PLLRDY_BitNumber)) /* Flags in the CR2 register */ #define RCC_FLAG_HSI14RDY ((uint8_t)((CR2_REG_INDEX << 5) | RCC_CR2_HSI14RDY_BitNumber)) /* Flags in the CSR register */ #define RCC_FLAG_LSIRDY ((uint8_t)((CSR_REG_INDEX << 5) | RCC_CSR_LSIRDY_BitNumber)) #define RCC_FLAG_V18PWRRST ((uint8_t)((CSR_REG_INDEX << 5) | RCC_CSR_LSIRDY_BitNumber)) #define RCC_FLAG_RMV ((uint8_t)((CSR_REG_INDEX << 5) | RCC_CSR_RMVF_BitNumber)) #define RCC_FLAG_OBLRST ((uint8_t)((CSR_REG_INDEX << 5) | RCC_CSR_OBLRSTF_BitNumber)) #define RCC_FLAG_PINRST ((uint8_t)((CSR_REG_INDEX << 5) | RCC_CSR_PINRSTF_BitNumber)) #define RCC_FLAG_PORRST ((uint8_t)((CSR_REG_INDEX << 5) | RCC_CSR_PORRSTF_BitNumber)) #define RCC_FLAG_SFTRST ((uint8_t)((CSR_REG_INDEX << 5) | RCC_CSR_SFTRSTF_BitNumber)) #define RCC_FLAG_IWDGRST ((uint8_t)((CSR_REG_INDEX << 5) | RCC_CSR_IWDGRSTF_BitNumber)) #define RCC_FLAG_WWDGRST ((uint8_t)((CSR_REG_INDEX << 5) | RCC_CSR_WWDGRSTF_BitNumber)) #define RCC_FLAG_LPWRRST ((uint8_t)((CSR_REG_INDEX << 5) | RCC_CSR_LPWRRSTF_BitNumber)) /* Flags in the BDCR register */ #define RCC_FLAG_LSERDY ((uint8_t)((BDCR_REG_INDEX << 5) | RCC_BDCR_LSERDY_BitNumber)) /** * @} */ /** * @} */ /* Exported macro ------------------------------------------------------------*/ /** @defgroup RCC_Exported_Macros RCC Exported Macros * @{ */ /** @defgroup RCC_AHB_Clock_Enable_Disable RCC AHB Clock Enable Disable * @brief Enable or disable the AHB peripheral clock. * @note After reset, the peripheral clock (used for registers read/write access) * is disabled and the application software has to enable this clock before * using it. * @{ */ #define __HAL_RCC_GPIOA_CLK_ENABLE() do { \ __IO uint32_t tmpreg; \ SET_BIT(RCC->AHBENR, RCC_AHBENR_GPIOAEN);\ /* Delay after an RCC peripheral clock enabling */ \ tmpreg = READ_BIT(RCC->AHBENR, RCC_AHBENR_GPIOAEN);\ UNUSED(tmpreg); \ } while(0) #define __HAL_RCC_GPIOB_CLK_ENABLE() do { \ __IO uint32_t tmpreg; \ SET_BIT(RCC->AHBENR, RCC_AHBENR_GPIOBEN);\ /* Delay after an RCC peripheral clock enabling */ \ tmpreg = READ_BIT(RCC->AHBENR, RCC_AHBENR_GPIOBEN);\ UNUSED(tmpreg); \ } while(0) #define __HAL_RCC_GPIOC_CLK_ENABLE() do { \ __IO uint32_t tmpreg; \ SET_BIT(RCC->AHBENR, RCC_AHBENR_GPIOCEN);\ /* Delay after an RCC peripheral clock enabling */ \ tmpreg = READ_BIT(RCC->AHBENR, RCC_AHBENR_GPIOCEN);\ UNUSED(tmpreg); \ } while(0) #define __HAL_RCC_GPIOF_CLK_ENABLE() do { \ __IO uint32_t tmpreg; \ SET_BIT(RCC->AHBENR, RCC_AHBENR_GPIOFEN);\ /* Delay after an RCC peripheral clock enabling */ \ tmpreg = READ_BIT(RCC->AHBENR, RCC_AHBENR_GPIOFEN);\ UNUSED(tmpreg); \ } while(0) #define __HAL_RCC_CRC_CLK_ENABLE() do { \ __IO uint32_t tmpreg; \ SET_BIT(RCC->AHBENR, RCC_AHBENR_CRCEN);\ /* Delay after an RCC peripheral clock enabling */ \ tmpreg = READ_BIT(RCC->AHBENR, RCC_AHBENR_CRCEN);\ UNUSED(tmpreg); \ } while(0) #define __HAL_RCC_DMA1_CLK_ENABLE() do { \ __IO uint32_t tmpreg; \ SET_BIT(RCC->AHBENR, RCC_AHBENR_DMA1EN);\ /* Delay after an RCC peripheral clock enabling */ \ tmpreg = READ_BIT(RCC->AHBENR, RCC_AHBENR_DMA1EN);\ UNUSED(tmpreg); \ } while(0) #define __HAL_RCC_SRAM_CLK_ENABLE() do { \ __IO uint32_t tmpreg; \ SET_BIT(RCC->AHBENR, RCC_AHBENR_SRAMEN);\ /* Delay after an RCC peripheral clock enabling */ \ tmpreg = READ_BIT(RCC->AHBENR, RCC_AHBENR_SRAMEN);\ UNUSED(tmpreg); \ } while(0) #define __HAL_RCC_FLITF_CLK_ENABLE() do { \ __IO uint32_t tmpreg; \ SET_BIT(RCC->AHBENR, RCC_AHBENR_FLITFEN);\ /* Delay after an RCC peripheral clock enabling */ \ tmpreg = READ_BIT(RCC->AHBENR, RCC_AHBENR_FLITFEN);\ UNUSED(tmpreg); \ } while(0) #define __HAL_RCC_GPIOA_CLK_DISABLE() (RCC->AHBENR &= ~(RCC_AHBENR_GPIOAEN)) #define __HAL_RCC_GPIOB_CLK_DISABLE() (RCC->AHBENR &= ~(RCC_AHBENR_GPIOBEN)) #define __HAL_RCC_GPIOC_CLK_DISABLE() (RCC->AHBENR &= ~(RCC_AHBENR_GPIOCEN)) #define __HAL_RCC_GPIOF_CLK_DISABLE() (RCC->AHBENR &= ~(RCC_AHBENR_GPIOFEN)) #define __HAL_RCC_CRC_CLK_DISABLE() (RCC->AHBENR &= ~(RCC_AHBENR_CRCEN)) #define __HAL_RCC_DMA1_CLK_DISABLE() (RCC->AHBENR &= ~(RCC_AHBENR_DMA1EN)) #define __HAL_RCC_SRAM_CLK_DISABLE() (RCC->AHBENR &= ~(RCC_AHBENR_SRAMEN)) #define __HAL_RCC_FLITF_CLK_DISABLE() (RCC->AHBENR &= ~(RCC_AHBENR_FLITFEN)) /** * @} */ /** @defgroup RCC_AHB_Peripheral_Clock_Enable_Disable_Status AHB Peripheral Clock Enable Disable Status * @brief Get the enable or disable status of the AHB peripheral clock. * @note After reset, the peripheral clock (used for registers read/write access) * is disabled and the application software has to enable this clock before * using it. * @{ */ #define __HAL_RCC_GPIOA_IS_CLK_ENABLED() ((RCC->AHBENR & (RCC_AHBENR_GPIOAEN)) != RESET) #define __HAL_RCC_GPIOB_IS_CLK_ENABLED() ((RCC->AHBENR & (RCC_AHBENR_GPIOBEN)) != RESET) #define __HAL_RCC_GPIOC_IS_CLK_ENABLED() ((RCC->AHBENR & (RCC_AHBENR_GPIOCEN)) != RESET) #define __HAL_RCC_GPIOF_IS_CLK_ENABLED() ((RCC->AHBENR & (RCC_AHBENR_GPIOFEN)) != RESET) #define __HAL_RCC_CRC_IS_CLK_ENABLED() ((RCC->AHBENR & (RCC_AHBENR_CRCEN)) != RESET) #define __HAL_RCC_DMA1_IS_CLK_ENABLED() ((RCC->AHBENR & (RCC_AHBENR_DMA1EN)) != RESET) #define __HAL_RCC_SRAM_IS_CLK_ENABLED() ((RCC->AHBENR & (RCC_AHBENR_SRAMEN)) != RESET) #define __HAL_RCC_FLITF_IS_CLK_ENABLED() ((RCC->AHBENR & (RCC_AHBENR_FLITFEN)) != RESET) #define __HAL_RCC_GPIOA_IS_CLK_DISABLED() ((RCC->AHBENR & (RCC_AHBENR_GPIOAEN)) == RESET) #define __HAL_RCC_GPIOB_IS_CLK_DISABLED() ((RCC->AHBENR & (RCC_AHBENR_GPIOBEN)) == RESET) #define __HAL_RCC_GPIOC_IS_CLK_DISABLED() ((RCC->AHBENR & (RCC_AHBENR_GPIOCEN)) == RESET) #define __HAL_RCC_GPIOF_IS_CLK_DISABLED() ((RCC->AHBENR & (RCC_AHBENR_GPIOFEN)) == RESET) #define __HAL_RCC_CRC_IS_CLK_DISABLED() ((RCC->AHBENR & (RCC_AHBENR_CRCEN)) == RESET) #define __HAL_RCC_DMA1_IS_CLK_DISABLED() ((RCC->AHBENR & (RCC_AHBENR_DMA1EN)) == RESET) #define __HAL_RCC_SRAM_IS_CLK_DISABLED() ((RCC->AHBENR & (RCC_AHBENR_SRAMEN)) == RESET) #define __HAL_RCC_FLITF_IS_CLK_DISABLED() ((RCC->AHBENR & (RCC_AHBENR_FLITFEN)) == RESET) /** * @} */ /** @defgroup RCC_APB1_Clock_Enable_Disable RCC APB1 Clock Enable Disable * @brief Enable or disable the Low Speed APB (APB1) peripheral clock. * @note After reset, the peripheral clock (used for registers read/write access) * is disabled and the application software has to enable this clock before * using it. * @{ */ #define __HAL_RCC_TIM3_CLK_ENABLE() do { \ __IO uint32_t tmpreg; \ SET_BIT(RCC->APB1ENR, RCC_APB1ENR_TIM3EN);\ /* Delay after an RCC peripheral clock enabling */ \ tmpreg = READ_BIT(RCC->APB1ENR, RCC_APB1ENR_TIM3EN);\ UNUSED(tmpreg); \ } while(0) #define __HAL_RCC_TIM14_CLK_ENABLE() do { \ __IO uint32_t tmpreg; \ SET_BIT(RCC->APB1ENR, RCC_APB1ENR_TIM14EN);\ /* Delay after an RCC peripheral clock enabling */ \ tmpreg = READ_BIT(RCC->APB1ENR, RCC_APB1ENR_TIM14EN);\ UNUSED(tmpreg); \ } while(0) #define __HAL_RCC_WWDG_CLK_ENABLE() do { \ __IO uint32_t tmpreg; \ SET_BIT(RCC->APB1ENR, RCC_APB1ENR_WWDGEN);\ /* Delay after an RCC peripheral clock enabling */ \ tmpreg = READ_BIT(RCC->APB1ENR, RCC_APB1ENR_WWDGEN);\ UNUSED(tmpreg); \ } while(0) #define __HAL_RCC_I2C1_CLK_ENABLE() do { \ __IO uint32_t tmpreg; \ SET_BIT(RCC->APB1ENR, RCC_APB1ENR_I2C1EN);\ /* Delay after an RCC peripheral clock enabling */ \ tmpreg = READ_BIT(RCC->APB1ENR, RCC_APB1ENR_I2C1EN);\ UNUSED(tmpreg); \ } while(0) #define __HAL_RCC_PWR_CLK_ENABLE() do { \ __IO uint32_t tmpreg; \ SET_BIT(RCC->APB1ENR, RCC_APB1ENR_PWREN);\ /* Delay after an RCC peripheral clock enabling */ \ tmpreg = READ_BIT(RCC->APB1ENR, RCC_APB1ENR_PWREN);\ UNUSED(tmpreg); \ } while(0) #define __HAL_RCC_TIM3_CLK_DISABLE() (RCC->APB1ENR &= ~(RCC_APB1ENR_TIM3EN)) #define __HAL_RCC_TIM14_CLK_DISABLE() (RCC->APB1ENR &= ~(RCC_APB1ENR_TIM14EN)) #define __HAL_RCC_WWDG_CLK_DISABLE() (RCC->APB1ENR &= ~(RCC_APB1ENR_WWDGEN)) #define __HAL_RCC_I2C1_CLK_DISABLE() (RCC->APB1ENR &= ~(RCC_APB1ENR_I2C1EN)) #define __HAL_RCC_PWR_CLK_DISABLE() (RCC->APB1ENR &= ~(RCC_APB1ENR_PWREN)) /** * @} */ /** @defgroup RCC_APB1_Peripheral_Clock_Enable_Disable_Status APB1 Peripheral Clock Enable Disable Status * @brief Get the enable or disable status of the APB1 peripheral clock. * @note After reset, the peripheral clock (used for registers read/write access) * is disabled and the application software has to enable this clock before * using it. * @{ */ #define __HAL_RCC_TIM3_IS_CLK_ENABLED() ((RCC->APB1ENR & (RCC_APB1ENR_TIM3EN)) != RESET) #define __HAL_RCC_TIM14_IS_CLK_ENABLED() ((RCC->APB1ENR & (RCC_APB1ENR_TIM14EN)) != RESET) #define __HAL_RCC_WWDG_IS_CLK_ENABLED() ((RCC->APB1ENR & (RCC_APB1ENR_WWDGEN)) != RESET) #define __HAL_RCC_I2C1_IS_CLK_ENABLED() ((RCC->APB1ENR & (RCC_APB1ENR_I2C1EN)) != RESET) #define __HAL_RCC_PWR_IS_CLK_ENABLED() ((RCC->APB1ENR & (RCC_APB1ENR_PWREN)) != RESET) #define __HAL_RCC_TIM3_IS_CLK_DISABLED() ((RCC->APB1ENR & (RCC_APB1ENR_TIM3EN)) == RESET) #define __HAL_RCC_TIM14_IS_CLK_DISABLED() ((RCC->APB1ENR & (RCC_APB1ENR_TIM14EN)) == RESET) #define __HAL_RCC_WWDG_IS_CLK_DISABLED() ((RCC->APB1ENR & (RCC_APB1ENR_WWDGEN)) == RESET) #define __HAL_RCC_I2C1_IS_CLK_DISABLED() ((RCC->APB1ENR & (RCC_APB1ENR_I2C1EN)) == RESET) #define __HAL_RCC_PWR_IS_CLK_DISABLED() ((RCC->APB1ENR & (RCC_APB1ENR_PWREN)) == RESET) /** * @} */ /** @defgroup RCC_APB2_Clock_Enable_Disable RCC APB2 Clock Enable Disable * @brief Enable or disable the High Speed APB (APB2) peripheral clock. * @note After reset, the peripheral clock (used for registers read/write access) * is disabled and the application software has to enable this clock before * using it. * @{ */ #define __HAL_RCC_SYSCFG_CLK_ENABLE() do { \ __IO uint32_t tmpreg; \ SET_BIT(RCC->APB2ENR, RCC_APB2ENR_SYSCFGEN);\ /* Delay after an RCC peripheral clock enabling */ \ tmpreg = READ_BIT(RCC->APB2ENR, RCC_APB2ENR_SYSCFGEN);\ UNUSED(tmpreg); \ } while(0) #define __HAL_RCC_ADC1_CLK_ENABLE() do { \ __IO uint32_t tmpreg; \ SET_BIT(RCC->APB2ENR, RCC_APB2ENR_ADC1EN);\ /* Delay after an RCC peripheral clock enabling */ \ tmpreg = READ_BIT(RCC->APB2ENR, RCC_APB2ENR_ADC1EN);\ UNUSED(tmpreg); \ } while(0) #define __HAL_RCC_TIM1_CLK_ENABLE() do { \ __IO uint32_t tmpreg; \ SET_BIT(RCC->APB2ENR, RCC_APB2ENR_TIM1EN);\ /* Delay after an RCC peripheral clock enabling */ \ tmpreg = READ_BIT(RCC->APB2ENR, RCC_APB2ENR_TIM1EN);\ UNUSED(tmpreg); \ } while(0) #define __HAL_RCC_SPI1_CLK_ENABLE() do { \ __IO uint32_t tmpreg; \ SET_BIT(RCC->APB2ENR, RCC_APB2ENR_SPI1EN);\ /* Delay after an RCC peripheral clock enabling */ \ tmpreg = READ_BIT(RCC->APB2ENR, RCC_APB2ENR_SPI1EN);\ UNUSED(tmpreg); \ } while(0) #define __HAL_RCC_TIM16_CLK_ENABLE() do { \ __IO uint32_t tmpreg; \ SET_BIT(RCC->APB2ENR, RCC_APB2ENR_TIM16EN);\ /* Delay after an RCC peripheral clock enabling */ \ tmpreg = READ_BIT(RCC->APB2ENR, RCC_APB2ENR_TIM16EN);\ UNUSED(tmpreg); \ } while(0) #define __HAL_RCC_TIM17_CLK_ENABLE() do { \ __IO uint32_t tmpreg; \ SET_BIT(RCC->APB2ENR, RCC_APB2ENR_TIM17EN);\ /* Delay after an RCC peripheral clock enabling */ \ tmpreg = READ_BIT(RCC->APB2ENR, RCC_APB2ENR_TIM17EN);\ UNUSED(tmpreg); \ } while(0) #define __HAL_RCC_USART1_CLK_ENABLE() do { \ __IO uint32_t tmpreg; \ SET_BIT(RCC->APB2ENR, RCC_APB2ENR_USART1EN);\ /* Delay after an RCC peripheral clock enabling */ \ tmpreg = READ_BIT(RCC->APB2ENR, RCC_APB2ENR_USART1EN);\ UNUSED(tmpreg); \ } while(0) #define __HAL_RCC_DBGMCU_CLK_ENABLE() do { \ __IO uint32_t tmpreg; \ SET_BIT(RCC->APB2ENR, RCC_APB2ENR_DBGMCUEN);\ /* Delay after an RCC peripheral clock enabling */ \ tmpreg = READ_BIT(RCC->APB2ENR, RCC_APB2ENR_DBGMCUEN);\ UNUSED(tmpreg); \ } while(0) #define __HAL_RCC_SYSCFG_CLK_DISABLE() (RCC->APB2ENR &= ~(RCC_APB2ENR_SYSCFGEN)) #define __HAL_RCC_ADC1_CLK_DISABLE() (RCC->APB2ENR &= ~(RCC_APB2ENR_ADC1EN)) #define __HAL_RCC_TIM1_CLK_DISABLE() (RCC->APB2ENR &= ~(RCC_APB2ENR_TIM1EN)) #define __HAL_RCC_SPI1_CLK_DISABLE() (RCC->APB2ENR &= ~(RCC_APB2ENR_SPI1EN)) #define __HAL_RCC_TIM16_CLK_DISABLE() (RCC->APB2ENR &= ~(RCC_APB2ENR_TIM16EN)) #define __HAL_RCC_TIM17_CLK_DISABLE() (RCC->APB2ENR &= ~(RCC_APB2ENR_TIM17EN)) #define __HAL_RCC_USART1_CLK_DISABLE() (RCC->APB2ENR &= ~(RCC_APB2ENR_USART1EN)) #define __HAL_RCC_DBGMCU_CLK_DISABLE() (RCC->APB2ENR &= ~(RCC_APB2ENR_DBGMCUEN)) /** * @} */ /** @defgroup RCC_APB2_Peripheral_Clock_Enable_Disable_Status APB2 Peripheral Clock Enable Disable Status * @brief Get the enable or disable status of the APB2 peripheral clock. * @note After reset, the peripheral clock (used for registers read/write access) * is disabled and the application software has to enable this clock before * using it. * @{ */ #define __HAL_RCC_SYSCFG_IS_CLK_ENABLED() ((RCC->APB2ENR & (RCC_APB2ENR_SYSCFGEN)) != RESET) #define __HAL_RCC_ADC1_IS_CLK_ENABLED() ((RCC->APB2ENR & (RCC_APB2ENR_ADC1EN)) != RESET) #define __HAL_RCC_TIM1_IS_CLK_ENABLED() ((RCC->APB2ENR & (RCC_APB2ENR_TIM1EN)) != RESET) #define __HAL_RCC_SPI1_IS_CLK_ENABLED() ((RCC->APB2ENR & (RCC_APB2ENR_SPI1EN)) != RESET) #define __HAL_RCC_TIM16_IS_CLK_ENABLED() ((RCC->APB2ENR & (RCC_APB2ENR_TIM16EN)) != RESET) #define __HAL_RCC_TIM17_IS_CLK_ENABLED() ((RCC->APB2ENR & (RCC_APB2ENR_TIM17EN)) != RESET) #define __HAL_RCC_USART1_IS_CLK_ENABLED() ((RCC->APB2ENR & (RCC_APB2ENR_USART1EN)) != RESET) #define __HAL_RCC_DBGMCU_IS_CLK_ENABLED() ((RCC->APB2ENR & (RCC_APB2ENR_DBGMCUEN)) != RESET) #define __HAL_RCC_SYSCFG_IS_CLK_DISABLED() ((RCC->APB2ENR & (RCC_APB2ENR_SYSCFGEN)) == RESET) #define __HAL_RCC_ADC1_IS_CLK_DISABLED() ((RCC->APB2ENR & (RCC_APB2ENR_ADC1EN)) == RESET) #define __HAL_RCC_TIM1_IS_CLK_DISABLED() ((RCC->APB2ENR & (RCC_APB2ENR_TIM1EN)) == RESET) #define __HAL_RCC_SPI1_IS_CLK_DISABLED() ((RCC->APB2ENR & (RCC_APB2ENR_SPI1EN)) == RESET) #define __HAL_RCC_TIM16_IS_CLK_DISABLED() ((RCC->APB2ENR & (RCC_APB2ENR_TIM16EN)) == RESET) #define __HAL_RCC_TIM17_IS_CLK_DISABLED() ((RCC->APB2ENR & (RCC_APB2ENR_TIM17EN)) == RESET) #define __HAL_RCC_USART1_IS_CLK_DISABLED() ((RCC->APB2ENR & (RCC_APB2ENR_USART1EN)) == RESET) #define __HAL_RCC_DBGMCU_IS_CLK_DISABLED() ((RCC->APB2ENR & (RCC_APB2ENR_DBGMCUEN)) == RESET) /** * @} */ /** @defgroup RCC_AHB_Force_Release_Reset RCC AHB Force Release Reset * @brief Force or release AHB peripheral reset. * @{ */ #define __HAL_RCC_AHB_FORCE_RESET() (RCC->AHBRSTR = 0xFFFFFFFF) #define __HAL_RCC_GPIOA_FORCE_RESET() (RCC->AHBRSTR |= (RCC_AHBRSTR_GPIOARST)) #define __HAL_RCC_GPIOB_FORCE_RESET() (RCC->AHBRSTR |= (RCC_AHBRSTR_GPIOBRST)) #define __HAL_RCC_GPIOC_FORCE_RESET() (RCC->AHBRSTR |= (RCC_AHBRSTR_GPIOCRST)) #define __HAL_RCC_GPIOF_FORCE_RESET() (RCC->AHBRSTR |= (RCC_AHBRSTR_GPIOFRST)) #define __HAL_RCC_AHB_RELEASE_RESET() (RCC->AHBRSTR = 0x00) #define __HAL_RCC_GPIOA_RELEASE_RESET() (RCC->AHBRSTR &= ~(RCC_AHBRSTR_GPIOARST)) #define __HAL_RCC_GPIOB_RELEASE_RESET() (RCC->AHBRSTR &= ~(RCC_AHBRSTR_GPIOBRST)) #define __HAL_RCC_GPIOC_RELEASE_RESET() (RCC->AHBRSTR &= ~(RCC_AHBRSTR_GPIOCRST)) #define __HAL_RCC_GPIOF_RELEASE_RESET() (RCC->AHBRSTR &= ~(RCC_AHBRSTR_GPIOFRST)) /** * @} */ /** @defgroup RCC_APB1_Force_Release_Reset RCC APB1 Force Release Reset * @brief Force or release APB1 peripheral reset. * @{ */ #define __HAL_RCC_APB1_FORCE_RESET() (RCC->APB1RSTR = 0xFFFFFFFF) #define __HAL_RCC_TIM3_FORCE_RESET() (RCC->APB1RSTR |= (RCC_APB1RSTR_TIM3RST)) #define __HAL_RCC_TIM14_FORCE_RESET() (RCC->APB1RSTR |= (RCC_APB1RSTR_TIM14RST)) #define __HAL_RCC_WWDG_FORCE_RESET() (RCC->APB1RSTR |= (RCC_APB1RSTR_WWDGRST)) #define __HAL_RCC_I2C1_FORCE_RESET() (RCC->APB1RSTR |= (RCC_APB1RSTR_I2C1RST)) #define __HAL_RCC_PWR_FORCE_RESET() (RCC->APB1RSTR |= (RCC_APB1RSTR_PWRRST)) #define __HAL_RCC_APB1_RELEASE_RESET() (RCC->APB1RSTR = 0x00) #define __HAL_RCC_TIM3_RELEASE_RESET() (RCC->APB1RSTR &= ~(RCC_APB1RSTR_TIM3RST)) #define __HAL_RCC_TIM14_RELEASE_RESET() (RCC->APB1RSTR &= ~(RCC_APB1RSTR_TIM14RST)) #define __HAL_RCC_WWDG_RELEASE_RESET() (RCC->APB1RSTR &= ~(RCC_APB1RSTR_WWDGRST)) #define __HAL_RCC_I2C1_RELEASE_RESET() (RCC->APB1RSTR &= ~(RCC_APB1RSTR_I2C1RST)) #define __HAL_RCC_PWR_RELEASE_RESET() (RCC->APB1RSTR &= ~(RCC_APB1RSTR_PWRRST)) /** * @} */ /** @defgroup RCC_APB2_Force_Release_Reset RCC APB2 Force Release Reset * @brief Force or release APB2 peripheral reset. * @{ */ #define __HAL_RCC_APB2_FORCE_RESET() (RCC->APB2RSTR = 0xFFFFFFFF) #define __HAL_RCC_SYSCFG_FORCE_RESET() (RCC->APB2RSTR |= (RCC_APB2RSTR_SYSCFGRST)) #define __HAL_RCC_ADC1_FORCE_RESET() (RCC->APB2RSTR |= (RCC_APB2RSTR_ADC1RST)) #define __HAL_RCC_TIM1_FORCE_RESET() (RCC->APB2RSTR |= (RCC_APB2RSTR_TIM1RST)) #define __HAL_RCC_SPI1_FORCE_RESET() (RCC->APB2RSTR |= (RCC_APB2RSTR_SPI1RST)) #define __HAL_RCC_USART1_FORCE_RESET() (RCC->APB2RSTR |= (RCC_APB2RSTR_USART1RST)) #define __HAL_RCC_TIM16_FORCE_RESET() (RCC->APB2RSTR |= (RCC_APB2RSTR_TIM16RST)) #define __HAL_RCC_TIM17_FORCE_RESET() (RCC->APB2RSTR |= (RCC_APB2RSTR_TIM17RST)) #define __HAL_RCC_DBGMCU_FORCE_RESET() (RCC->APB2RSTR |= (RCC_APB2RSTR_DBGMCURST)) #define __HAL_RCC_APB2_RELEASE_RESET() (RCC->APB2RSTR = 0x00) #define __HAL_RCC_SYSCFG_RELEASE_RESET() (RCC->APB2RSTR &= ~(RCC_APB2RSTR_SYSCFGRST)) #define __HAL_RCC_ADC1_RELEASE_RESET() (RCC->APB2RSTR &= ~(RCC_APB2RSTR_ADC1RST)) #define __HAL_RCC_TIM1_RELEASE_RESET() (RCC->APB2RSTR &= ~(RCC_APB2RSTR_TIM1RST)) #define __HAL_RCC_SPI1_RELEASE_RESET() (RCC->APB2RSTR &= ~(RCC_APB2RSTR_SPI1RST)) #define __HAL_RCC_USART1_RELEASE_RESET() (RCC->APB2RSTR &= ~(RCC_APB2RSTR_USART1RST)) #define __HAL_RCC_TIM16_RELEASE_RESET() (RCC->APB2RSTR &= ~(RCC_APB2RSTR_TIM16RST)) #define __HAL_RCC_TIM17_RELEASE_RESET() (RCC->APB2RSTR &= ~(RCC_APB2RSTR_TIM17RST)) #define __HAL_RCC_DBGMCU_RELEASE_RESET() (RCC->APB2RSTR &= ~(RCC_APB2RSTR_DBGMCURST)) /** * @} */ /** @defgroup RCC_HSI_Configuration HSI Configuration * @{ */ /** @brief Macros to enable or disable the Internal High Speed oscillator (HSI). * @note The HSI is stopped by hardware when entering STOP and STANDBY modes. * @note HSI can not be stopped if it is used as system clock source. In this case, * you have to select another source of the system clock then stop the HSI. * @note After enabling the HSI, the application software should wait on HSIRDY * flag to be set indicating that HSI clock is stable and can be used as * system clock source. * @note When the HSI is stopped, HSIRDY flag goes low after 6 HSI oscillator * clock cycles. */ #define __HAL_RCC_HSI_ENABLE() SET_BIT(RCC->CR, RCC_CR_HSION) #define __HAL_RCC_HSI_DISABLE() CLEAR_BIT(RCC->CR, RCC_CR_HSION) /** @brief macro to adjust the Internal High Speed oscillator (HSI) calibration value. * @note The calibration is used to compensate for the variations in voltage * and temperature that influence the frequency of the internal HSI RC. * @param _HSICALIBRATIONVALUE_: specifies the calibration trimming value. * (default is RCC_HSICALIBRATION_DEFAULT). * This parameter must be a number between 0 and 0x1F. */ #define __HAL_RCC_HSI_CALIBRATIONVALUE_ADJUST(_HSICALIBRATIONVALUE_) \ MODIFY_REG(RCC->CR, RCC_CR_HSITRIM, (uint32_t)(_HSICALIBRATIONVALUE_) << RCC_CR_HSITRIM_BitNumber) /** * @} */ /** @defgroup RCC_LSI_Configuration LSI Configuration * @{ */ /** @brief Macros to enable or disable the Internal Low Speed oscillator (LSI). * @note After enabling the LSI, the application software should wait on * LSIRDY flag to be set indicating that LSI clock is stable and can * be used to clock the IWDG and/or the RTC. * @note LSI can not be disabled if the IWDG is running. * @note When the LSI is stopped, LSIRDY flag goes low after 6 LSI oscillator * clock cycles. */ #define __HAL_RCC_LSI_ENABLE() SET_BIT(RCC->CSR, RCC_CSR_LSION) #define __HAL_RCC_LSI_DISABLE() CLEAR_BIT(RCC->CSR, RCC_CSR_LSION) /** * @} */ /** @defgroup RCC_HSE_Configuration HSE Configuration * @{ */ /** * @brief Macro to configure the External High Speed oscillator (HSE). * @note Transition HSE Bypass to HSE On and HSE On to HSE Bypass are not * supported by this macro. User should request a transition to HSE Off * first and then HSE On or HSE Bypass. * @note After enabling the HSE (RCC_HSE_ON or RCC_HSE_Bypass), the application * software should wait on HSERDY flag to be set indicating that HSE clock * is stable and can be used to clock the PLL and/or system clock. * @note HSE state can not be changed if it is used directly or through the * PLL as system clock. In this case, you have to select another source * of the system clock then change the HSE state (ex. disable it). * @note The HSE is stopped by hardware when entering STOP and STANDBY modes. * @note This function reset the CSSON bit, so if the Clock security system(CSS) * was previously enabled you have to enable it again after calling this * function. * @param __STATE__: specifies the new state of the HSE. * This parameter can be one of the following values: * @arg RCC_HSE_OFF: turn OFF the HSE oscillator, HSERDY flag goes low after * 6 HSE oscillator clock cycles. * @arg RCC_HSE_ON: turn ON the HSE oscillator * @arg RCC_HSE_BYPASS: HSE oscillator bypassed with external clock */ #define __HAL_RCC_HSE_CONFIG(__STATE__) \ do{ \ if ((__STATE__) == RCC_HSE_ON) \ { \ SET_BIT(RCC->CR, RCC_CR_HSEON); \ } \ else if ((__STATE__) == RCC_HSE_OFF) \ { \ CLEAR_BIT(RCC->CR, RCC_CR_HSEON); \ CLEAR_BIT(RCC->CR, RCC_CR_HSEBYP); \ } \ else if ((__STATE__) == RCC_HSE_BYPASS) \ { \ SET_BIT(RCC->CR, RCC_CR_HSEBYP); \ SET_BIT(RCC->CR, RCC_CR_HSEON); \ } \ else \ { \ CLEAR_BIT(RCC->CR, RCC_CR_HSEON); \ CLEAR_BIT(RCC->CR, RCC_CR_HSEBYP); \ } \ }while(0) /** * @brief Macro to configure the External High Speed oscillator (HSE) Predivision factor for PLL. * @note Predivision factor can not be changed if PLL is used as system clock * In this case, you have to select another source of the system clock, disable the PLL and * then change the HSE predivision factor. * @param __HSE_PREDIV_VALUE__: specifies the division value applied to HSE. * This parameter must be a number between RCC_HSE_PREDIV_DIV1 and RCC_HSE_PREDIV_DIV16. */ #define __HAL_RCC_HSE_PREDIV_CONFIG(__HSE_PREDIV_VALUE__) \ MODIFY_REG(RCC->CFGR2, RCC_CFGR2_PREDIV, (uint32_t)(__HSE_PREDIV_VALUE__)) /** * @} */ /** @defgroup RCC_LSE_Configuration LSE Configuration * @{ */ /** * @brief Macro to configure the External Low Speed oscillator (LSE). * @note Transitions LSE Bypass to LSE On and LSE On to LSE Bypass are not supported by this macro. * @note As the LSE is in the Backup domain and write access is denied to * this domain after reset, you have to enable write access using * HAL_PWR_EnableBkUpAccess() function before to configure the LSE * (to be done once after reset). * @note After enabling the LSE (RCC_LSE_ON or RCC_LSE_BYPASS), the application * software should wait on LSERDY flag to be set indicating that LSE clock * is stable and can be used to clock the RTC. * @param __STATE__: specifies the new state of the LSE. * This parameter can be one of the following values: * @arg RCC_LSE_OFF: turn OFF the LSE oscillator, LSERDY flag goes low after * 6 LSE oscillator clock cycles. * @arg RCC_LSE_ON: turn ON the LSE oscillator. * @arg RCC_LSE_BYPASS: LSE oscillator bypassed with external clock. */ #define __HAL_RCC_LSE_CONFIG(__STATE__) \ do{ \ if ((__STATE__) == RCC_LSE_ON) \ { \ SET_BIT(RCC->BDCR, RCC_BDCR_LSEON); \ } \ else if ((__STATE__) == RCC_LSE_OFF) \ { \ CLEAR_BIT(RCC->BDCR, RCC_BDCR_LSEON); \ CLEAR_BIT(RCC->BDCR, RCC_BDCR_LSEBYP); \ } \ else if ((__STATE__) == RCC_LSE_BYPASS) \ { \ SET_BIT(RCC->BDCR, RCC_BDCR_LSEBYP); \ SET_BIT(RCC->BDCR, RCC_BDCR_LSEON); \ } \ else \ { \ CLEAR_BIT(RCC->BDCR, RCC_BDCR_LSEON); \ CLEAR_BIT(RCC->BDCR, RCC_BDCR_LSEBYP); \ } \ }while(0) /** * @} */ /** @defgroup RCC_HSI14_Configuration RCC_HSI14_Configuration * @{ */ /** @brief Macros to enable or disable the Internal 14Mhz High Speed oscillator (HSI14). * @note The HSI14 is stopped by hardware when entering STOP and STANDBY modes. * @note HSI14 can not be stopped if it is used as system clock source. In this case, * you have to select another source of the system clock then stop the HSI14. * @note After enabling the HSI14 with __HAL_RCC_HSI14_ENABLE(), the application software * should wait on HSI14RDY flag to be set indicating that HSI clock is stable and can be * used as system clock source. This is not necessary if HAL_RCC_OscConfig() is used. * @note When the HSI14 is stopped, HSI14RDY flag goes low after 6 HSI14 oscillator * clock cycles. */ #define __HAL_RCC_HSI14_ENABLE() SET_BIT(RCC->CR2, RCC_CR2_HSI14ON) #define __HAL_RCC_HSI14_DISABLE() CLEAR_BIT(RCC->CR2, RCC_CR2_HSI14ON) /** @brief macros to Enable or Disable the Internal 14Mhz High Speed oscillator (HSI14) usage by ADC. */ #define __HAL_RCC_HSI14ADC_ENABLE() CLEAR_BIT(RCC->CR2, RCC_CR2_HSI14DIS) #define __HAL_RCC_HSI14ADC_DISABLE() SET_BIT(RCC->CR2, RCC_CR2_HSI14DIS) /** @brief Macro to adjust the Internal 14Mhz High Speed oscillator (HSI) calibration value. * @note The calibration is used to compensate for the variations in voltage * and temperature that influence the frequency of the internal HSI14 RC. * @param __HSI14CalibrationValue__: specifies the calibration trimming value * (default is RCC_HSI14CALIBRATION_DEFAULT). * This parameter must be a number between 0 and 0x1F. */ #define RCC_CR2_HSI14TRIM_BitNumber 3 #define __HAL_RCC_HSI14_CALIBRATIONVALUE_ADJUST(__HSI14CalibrationValue__) \ MODIFY_REG(RCC->CR2, RCC_CR2_HSI14TRIM, (uint32_t)(__HSI14CalibrationValue__) << RCC_CR2_HSI14TRIM_BitNumber) /** * @} */ /** @defgroup RCC_USARTx_Clock_Config RCC USARTx Clock Config * @{ */ /** @brief Macro to configure the USART1 clock (USART1CLK). * @param __USART1CLKSource__: specifies the USART1 clock source. * This parameter can be one of the following values: * @arg RCC_USART1CLKSOURCE_PCLK1: PCLK1 selected as USART1 clock * @arg RCC_USART1CLKSOURCE_HSI: HSI selected as USART1 clock * @arg RCC_USART1CLKSOURCE_SYSCLK: System Clock selected as USART1 clock * @arg RCC_USART1CLKSOURCE_LSE: LSE selected as USART1 clock */ #define __HAL_RCC_USART1_CONFIG(__USART1CLKSource__) \ MODIFY_REG(RCC->CFGR3, RCC_CFGR3_USART1SW, (uint32_t)(__USART1CLKSource__)) /** @brief Macro to get the USART1 clock source. * @retval The clock source can be one of the following values: * @arg RCC_USART1CLKSOURCE_PCLK1: PCLK1 selected as USART1 clock * @arg RCC_USART1CLKSOURCE_HSI: HSI selected as USART1 clock * @arg RCC_USART1CLKSOURCE_SYSCLK: System Clock selected as USART1 clock * @arg RCC_USART1CLKSOURCE_LSE: LSE selected as USART1 clock */ #define __HAL_RCC_GET_USART1_SOURCE() ((uint32_t)(READ_BIT(RCC->CFGR3, RCC_CFGR3_USART1SW))) /** * @} */ /** @defgroup RCC_I2Cx_Clock_Config RCC I2Cx Clock Config * @{ */ /** @brief Macro to configure the I2C1 clock (I2C1CLK). * @param __I2C1CLKSource__: specifies the I2C1 clock source. * This parameter can be one of the following values: * @arg RCC_I2C1CLKSOURCE_HSI: HSI selected as I2C1 clock * @arg RCC_I2C1CLKSOURCE_SYSCLK: System Clock selected as I2C1 clock */ #define __HAL_RCC_I2C1_CONFIG(__I2C1CLKSource__) \ MODIFY_REG(RCC->CFGR3, RCC_CFGR3_I2C1SW, (uint32_t)(__I2C1CLKSource__)) /** @brief Macro to get the I2C1 clock source. * @retval The clock source can be one of the following values: * @arg RCC_I2C1CLKSOURCE_HSI: HSI selected as I2C1 clock * @arg RCC_I2C1CLKSOURCE_SYSCLK: System Clock selected as I2C1 clock */ #define __HAL_RCC_GET_I2C1_SOURCE() ((uint32_t)(READ_BIT(RCC->CFGR3, RCC_CFGR3_I2C1SW))) /** * @} */ /** @defgroup RCC_PLL_Configuration PLL Configuration * @{ */ /** @brief Macros to enable the main PLL. * @note After enabling the main PLL, the application software should wait on * PLLRDY flag to be set indicating that PLL clock is stable and can * be used as system clock source. * @note The main PLL is disabled by hardware when entering STOP and STANDBY modes. */ #define __HAL_RCC_PLL_ENABLE() SET_BIT(RCC->CR, RCC_CR_PLLON) /** @brief Macros to disable the main PLL. * @note The main PLL can not be disabled if it is used as system clock source */ #define __HAL_RCC_PLL_DISABLE() CLEAR_BIT(RCC->CR, RCC_CR_PLLON) /** @brief Macro to configure the PLL clock source, multiplication and division factors. * @note This function must be used only when the main PLL is disabled. * * @param __RCC_PLLSOURCE__: specifies the PLL entry clock source. * This parameter can be one of the following values: * @arg RCC_PLLSOURCE_HSI: HSI oscillator clock selected as PLL clock entry * @arg RCC_PLLSOURCE_HSE: HSE oscillator clock selected as PLL clock entry * @param __PLLMUL__: specifies the multiplication factor for PLL VCO output clock * This parameter can be one of the following values: * This parameter must be a number between RCC_PLL_MUL2 and RCC_PLL_MUL16. * @param __PREDIV__: specifies the predivider factor for PLL VCO input clock * This parameter must be a number between RCC_PREDIV_DIV1 and RCC_PREDIV_DIV16. * */ #define __HAL_RCC_PLL_CONFIG(__RCC_PLLSOURCE__ , __PREDIV__, __PLLMUL__) \ do { \ MODIFY_REG(RCC->CFGR2, RCC_CFGR2_PREDIV, (__PREDIV__)); \ MODIFY_REG(RCC->CFGR, RCC_CFGR_PLLMUL | RCC_CFGR_PLLSRC, (uint32_t)((__PLLMUL__)|(__RCC_PLLSOURCE__))); \ } while(0) /** @brief Get oscillator clock selected as PLL input clock * @retval The clock source used for PLL entry. The returned value can be one * of the following: * @arg RCC_PLLSOURCE_HSE: HSE oscillator clock selected as PLL input clock */ #define __HAL_RCC_GET_PLL_OSCSOURCE() ((RCC->CFGR & RCC_CFGR_PLLSRC)) /** * @} */ /** @defgroup RCC_Get_Clock_source Get Clock source * @{ */ /** * @brief Macro to configure the system clock source. * @param __RCC_SYSCLKSOURCE__: specifies the system clock source. * This parameter can be one of the following values: * - RCC_SYSCLKSOURCE_MSI: MSI oscillator is used as system clock source. * - RCC_SYSCLKSOURCE_HSI: HSI oscillator is used as system clock source. * - RCC_SYSCLKSOURCE_HSE: HSE oscillator is used as system clock source. * - RCC_SYSCLKSOURCE_PLLCLK: PLL output is used as system clock source. */ #define __HAL_RCC_SYSCLK_CONFIG(__RCC_SYSCLKSOURCE__) \ MODIFY_REG(RCC->CFGR, RCC_CFGR_SW, (__RCC_SYSCLKSOURCE__)) /** @brief Macro to get the clock source used as system clock. * @retval The clock source used as system clock. The returned value can be one * of the following: * @arg RCC_SYSCLKSOURCE_STATUS_HSI: HSI used as system clock * @arg RCC_SYSCLKSOURCE_STATUS_HSE: HSE used as system clock * @arg RCC_SYSCLKSOURCE_STATUS_PLLCLK: PLL used as system clock */ #define __HAL_RCC_GET_SYSCLK_SOURCE() ((uint32_t)(READ_BIT(RCC->CFGR,RCC_CFGR_SWS))) /** * @} */ /** @defgroup RCC_RTC_Clock_Configuration RCC RTC Clock Configuration * @{ */ /** @brief Macro to configures the RTC clock (RTCCLK). * @note As the RTC clock configuration bits are in the Backup domain and write * access is denied to this domain after reset, you have to enable write * access using the Power Backup Access macro before to configure * the RTC clock source (to be done once after reset). * @note Once the RTC clock is configured it can't be changed unless the * Backup domain is reset using __HAL_RCC_BACKUPRESET_FORCE() macro, or by * a Power On Reset (POR). * * @param __RTC_CLKSOURCE__: specifies the RTC clock source. * This parameter can be one of the following values: * @arg RCC_RTCCLKSOURCE_NO_CLK: No clock selected as RTC clock * @arg RCC_RTCCLKSOURCE_LSE: LSE selected as RTC clock * @arg RCC_RTCCLKSOURCE_LSI: LSI selected as RTC clock * @arg RCC_RTCCLKSOURCE_HSE_DIV32: HSE clock divided by 32 * @note If the LSE or LSI is used as RTC clock source, the RTC continues to * work in STOP and STANDBY modes, and can be used as wakeup source. * However, when the LSI clock and HSE clock divided by 32 is used as RTC clock source, * the RTC cannot be used in STOP and STANDBY modes. * @note The system must always be configured so as to get a PCLK frequency greater than or * equal to the RTCCLK frequency for a proper operation of the RTC. */ #define __HAL_RCC_RTC_CONFIG(__RTC_CLKSOURCE__) MODIFY_REG(RCC->BDCR, RCC_BDCR_RTCSEL, (__RTC_CLKSOURCE__)) /** @brief macros to get the RTC clock source. * @retval The clock source can be one of the following values: * @arg RCC_RTCCLKSOURCE_NO_CLK: No clock selected as RTC clock * @arg RCC_RTCCLKSOURCE_LSE: LSE selected as RTC clock * @arg RCC_RTCCLKSOURCE_LSI: LSI selected as RTC clock * @arg RCC_RTCCLKSOURCE_HSE_DIV32: HSE clock divided by 32 */ #define __HAL_RCC_GET_RTC_SOURCE() (READ_BIT(RCC->BDCR, RCC_BDCR_RTCSEL)) /** @brief Macros to enable the the RTC clock. * @note These macros must be used only after the RTC clock source was selected. */ #define __HAL_RCC_RTC_ENABLE() SET_BIT(RCC->BDCR, RCC_BDCR_RTCEN) /** @brief Macros to disable the the RTC clock. * @note These macros must be used only after the RTC clock source was selected. */ #define __HAL_RCC_RTC_DISABLE() CLEAR_BIT(RCC->BDCR, RCC_BDCR_RTCEN) /** @brief Macros to force the Backup domain reset. * @note This function resets the RTC peripheral (including the backup registers) * and the RTC clock source selection in RCC_BDCR register. */ #define __HAL_RCC_BACKUPRESET_FORCE() SET_BIT(RCC->BDCR, RCC_BDCR_BDRST) /** @brief Macros to release the Backup domain reset. */ #define __HAL_RCC_BACKUPRESET_RELEASE() CLEAR_BIT(RCC->BDCR, RCC_BDCR_BDRST) /** * @} */ /** @defgroup RCC_Flags_Interrupts_Management Flags Interrupts Management * @brief macros to manage the specified RCC Flags and interrupts. * @{ */ /** @brief Enable RCC interrupt. * @param __INTERRUPT__: specifies the RCC interrupt sources to be enabled. * This parameter can be any combination of the following values: * @arg RCC_IT_LSIRDY: LSI ready interrupt * @arg RCC_IT_LSERDY: LSE ready interrupt * @arg RCC_IT_HSIRDY: HSI ready interrupt * @arg RCC_IT_HSERDY: HSE ready interrupt * @arg RCC_IT_PLLRDY: main PLL ready interrupt * @arg RCC_IT_HSI14RDY: HSI14 ready interrupt enable * @arg RCC_IT_HSI48RDY: HSI48 ready interrupt enable (only applicable to STM32F0X2 USB devices) */ #define __HAL_RCC_ENABLE_IT(__INTERRUPT__) (*(__IO uint8_t *) RCC_CIR_BYTE1_ADDRESS |= (__INTERRUPT__)) /** @brief Disable RCC interrupt. * @param __INTERRUPT__: specifies the RCC interrupt sources to be disabled. * This parameter can be any combination of the following values: * @arg RCC_IT_LSIRDY: LSI ready interrupt * @arg RCC_IT_LSERDY: LSE ready interrupt * @arg RCC_IT_HSIRDY: HSI ready interrupt * @arg RCC_IT_HSERDY: HSE ready interrupt * @arg RCC_IT_PLLRDY: main PLL ready interrupt * @arg RCC_IT_HSI14RDY: HSI14 ready interrupt enable * @arg RCC_IT_HSI48RDY: HSI48 ready interrupt enable (only applicable to STM32F0X2 USB devices) */ #define __HAL_RCC_DISABLE_IT(__INTERRUPT__) (*(__IO uint8_t *) RCC_CIR_BYTE1_ADDRESS &= ~(__INTERRUPT__)) /** @brief Clear the RCC's interrupt pending bits. * @param __INTERRUPT__: specifies the interrupt pending bit to clear. * This parameter can be any combination of the following values: * @arg RCC_IT_LSIRDY: LSI ready interrupt. * @arg RCC_IT_LSERDY: LSE ready interrupt. * @arg RCC_IT_HSIRDY: HSI ready interrupt. * @arg RCC_IT_HSERDY: HSE ready interrupt. * @arg RCC_IT_PLLRDY: Main PLL ready interrupt. * @arg RCC_IT_CSS: Clock Security System interrupt * @arg RCC_IT_HSI14RDY: HSI14 ready interrupt enable * @arg RCC_IT_HSI48RDY: HSI48 ready interrupt enable (only applicable to STM32F0X2 USB devices) */ #define __HAL_RCC_CLEAR_IT(__INTERRUPT__) (*(__IO uint8_t *) RCC_CIR_BYTE2_ADDRESS = (__INTERRUPT__)) /** @brief Check the RCC's interrupt has occurred or not. * @param __INTERRUPT__: specifies the RCC interrupt source to check. * This parameter can be one of the following values: * @arg RCC_IT_LSIRDY: LSI ready interrupt. * @arg RCC_IT_LSERDY: LSE ready interrupt. * @arg RCC_IT_HSIRDY: HSI ready interrupt. * @arg RCC_IT_HSERDY: HSE ready interrupt. * @arg RCC_IT_PLLRDY: Main PLL ready interrupt. * @arg RCC_IT_CSS: Clock Security System interrupt * @arg RCC_IT_HSI14RDY: HSI14 ready interrupt enable * @arg RCC_IT_HSI48RDY: HSI48 ready interrupt enable (only applicable to STM32F0X2 USB devices) * @retval The new state of __INTERRUPT__ (TRUE or FALSE). */ #define __HAL_RCC_GET_IT(__INTERRUPT__) ((RCC->CIR & (__INTERRUPT__)) == (__INTERRUPT__)) /** @brief Set RMVF bit to clear the reset flags. * The reset flags are: RCC_FLAG_PINRST, RCC_FLAG_PORRST, RCC_FLAG_SFTRST, * RCC_FLAG_IWDGRST, RCC_FLAG_WWDGRST, RCC_FLAG_LPWRRST */ #define __HAL_RCC_CLEAR_RESET_FLAGS() (RCC->CSR |= RCC_CSR_RMVF) /** @brief Check RCC flag is set or not. * @param __FLAG__: specifies the flag to check. * This parameter can be one of the following values: * @arg RCC_FLAG_HSIRDY: HSI oscillator clock ready. * @arg RCC_FLAG_HSERDY: HSE oscillator clock ready. * @arg RCC_FLAG_PLLRDY: Main PLL clock ready. * @arg RCC_FLAG_HSI14RDY: HSI14 oscillator clock ready * @arg RCC_FLAG_HSI48RDY: HSI48 oscillator clock ready (only applicable to STM32F0X2 USB devices) * @arg RCC_FLAG_LSERDY: LSE oscillator clock ready. * @arg RCC_FLAG_LSIRDY: LSI oscillator clock ready. * @arg RCC_FLAG_OBLRST: Option Byte Load reset * @arg RCC_FLAG_PINRST: Pin reset. * @arg RCC_FLAG_PORRST: POR/PDR reset. * @arg RCC_FLAG_SFTRST: Software reset. * @arg RCC_FLAG_IWDGRST: Independent Watchdog reset. * @arg RCC_FLAG_WWDGRST: Window Watchdog reset. * @arg RCC_FLAG_LPWRRST: Low Power reset. * @retval The new state of __FLAG__ (TRUE or FALSE). */ #define __HAL_RCC_GET_FLAG(__FLAG__) (((((__FLAG__) >> 5) == CR_REG_INDEX)? RCC->CR : \ (((__FLAG__) >> 5) == CR2_REG_INDEX)? RCC->CR2 : \ (((__FLAG__) >> 5) == BDCR_REG_INDEX) ? RCC->BDCR : \ RCC->CSR) & ((uint32_t)1 << ((__FLAG__) & RCC_FLAG_MASK))) /** * @} */ /** * @} */ /* Include RCC HAL Extension module */ #include "stm32f0xx_hal_rcc_ex.h" /* Exported functions --------------------------------------------------------*/ /** @addtogroup RCC_Exported_Functions * @{ */ /** @addtogroup RCC_Exported_Functions_Group1 * @{ */ /* Initialization and de-initialization functions ******************************/ void HAL_RCC_DeInit(void); HAL_StatusTypeDef HAL_RCC_OscConfig(RCC_OscInitTypeDef *RCC_OscInitStruct); HAL_StatusTypeDef HAL_RCC_ClockConfig(RCC_ClkInitTypeDef *RCC_ClkInitStruct, uint32_t FLatency); /** * @} */ /** @addtogroup RCC_Exported_Functions_Group2 * @{ */ /* Peripheral Control functions ************************************************/ void HAL_RCC_MCOConfig(uint32_t RCC_MCOx, uint32_t RCC_MCOSource, uint32_t RCC_MCODiv); void HAL_RCC_EnableCSS(void); void HAL_RCC_DisableCSS(void); uint32_t HAL_RCC_GetSysClockFreq(void); uint32_t HAL_RCC_GetHCLKFreq(void); uint32_t HAL_RCC_GetPCLK1Freq(void); void HAL_RCC_GetOscConfig(RCC_OscInitTypeDef *RCC_OscInitStruct); void HAL_RCC_GetClockConfig(RCC_ClkInitTypeDef *RCC_ClkInitStruct, uint32_t *pFLatency); /* CSS NMI IRQ handler */ void HAL_RCC_NMI_IRQHandler(void); /* User Callbacks in non blocking mode (IT mode) */ void HAL_RCC_CSSCallback(void); /** * @} */ /** * @} */ /** * @} */ /** * @} */ #ifdef __cplusplus } #endif #endif /* __STM32F0xx_HAL_RCC_H */ /************************ (C) COPYRIGHT STMicroelectronics *****END OF FILE****/ ================================================ FILE: Zelig/mbed/TARGET_NUCLEO_F091RC/stm32f0xx_hal_rcc_ex.h ================================================ /** ****************************************************************************** * @file stm32f0xx_hal_rcc_ex.h * @author MCD Application Team * @version V1.3.0 * @date 26-June-2015 * @brief Header file of RCC HAL Extension module. ****************************************************************************** * @attention * *

© COPYRIGHT(c) 2015 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. * ****************************************************************************** */ /* Define to prevent recursive inclusion -------------------------------------*/ #ifndef __STM32F0xx_HAL_RCC_EX_H #define __HAL_RCC_STM32F0xx_HAL_RCC_EX_H #ifdef __cplusplus extern "C" { #endif /* Includes ------------------------------------------------------------------*/ #include "stm32f0xx_hal_def.h" /** @addtogroup STM32F0xx_HAL_Driver * @{ */ /** @addtogroup RCC * @{ */ /** @addtogroup RCC_Private_Macros * @{ */ #if defined(STM32F042x6) || defined(STM32F048xx)\ || defined(STM32F071xB) || defined(STM32F072xB) || defined(STM32F078xx)\ || defined(STM32F091xC) || defined(STM32F098xx) #define IS_RCC_OSCILLATORTYPE(OSCILLATOR) (((OSCILLATOR) == RCC_OSCILLATORTYPE_NONE) || \ (((OSCILLATOR) & RCC_OSCILLATORTYPE_HSE) == RCC_OSCILLATORTYPE_HSE) || \ (((OSCILLATOR) & RCC_OSCILLATORTYPE_HSI) == RCC_OSCILLATORTYPE_HSI) || \ (((OSCILLATOR) & RCC_OSCILLATORTYPE_LSI) == RCC_OSCILLATORTYPE_LSI) || \ (((OSCILLATOR) & RCC_OSCILLATORTYPE_LSE) == RCC_OSCILLATORTYPE_LSE) || \ (((OSCILLATOR) & RCC_OSCILLATORTYPE_HSI14) == RCC_OSCILLATORTYPE_HSI14) || \ (((OSCILLATOR) & RCC_OSCILLATORTYPE_HSI48) == RCC_OSCILLATORTYPE_HSI48)) #define IS_RCC_SYSCLKSOURCE(SOURCE) (((SOURCE) == RCC_SYSCLKSOURCE_HSI) || \ ((SOURCE) == RCC_SYSCLKSOURCE_HSE) || \ ((SOURCE) == RCC_SYSCLKSOURCE_PLLCLK) || \ ((SOURCE) == RCC_SYSCLKSOURCE_HSI48)) #define IS_RCC_SYSCLKSOURCE_STATUS(SOURCE) (((SOURCE) == RCC_SYSCLKSOURCE_STATUS_HSI) || \ ((SOURCE) == RCC_SYSCLKSOURCE_STATUS_HSE) || \ ((SOURCE) == RCC_SYSCLKSOURCE_STATUS_PLLCLK) || \ ((SOURCE) == RCC_SYSCLKSOURCE_STATUS_HSI48)) #define IS_RCC_PLLSOURCE(SOURCE) (((SOURCE) == RCC_PLLSOURCE_HSI) || \ ((SOURCE) == RCC_PLLSOURCE_HSI48) || \ ((SOURCE) == RCC_PLLSOURCE_HSE)) #define IS_RCC_HSI48(HSI48) (((HSI48) == RCC_HSI48_OFF) || ((HSI48) == RCC_HSI48_ON)) #else #define IS_RCC_OSCILLATORTYPE(OSCILLATOR) (((OSCILLATOR) == RCC_OSCILLATORTYPE_NONE) || \ (((OSCILLATOR) & RCC_OSCILLATORTYPE_HSE) == RCC_OSCILLATORTYPE_HSE) || \ (((OSCILLATOR) & RCC_OSCILLATORTYPE_HSI) == RCC_OSCILLATORTYPE_HSI) || \ (((OSCILLATOR) & RCC_OSCILLATORTYPE_LSI) == RCC_OSCILLATORTYPE_LSI) || \ (((OSCILLATOR) & RCC_OSCILLATORTYPE_LSE) == RCC_OSCILLATORTYPE_LSE) || \ (((OSCILLATOR) & RCC_OSCILLATORTYPE_HSI14) == RCC_OSCILLATORTYPE_HSI14)) #define IS_RCC_SYSCLKSOURCE(SOURCE) (((SOURCE) == RCC_SYSCLKSOURCE_HSI) || \ ((SOURCE) == RCC_SYSCLKSOURCE_HSE) || \ ((SOURCE) == RCC_SYSCLKSOURCE_PLLCLK)) #define IS_RCC_SYSCLKSOURCE_STATUS(SOURCE) (((SOURCE) == RCC_SYSCLKSOURCE_STATUS_HSI) || \ ((SOURCE) == RCC_SYSCLKSOURCE_STATUS_HSE) || \ ((SOURCE) == RCC_SYSCLKSOURCE_STATUS_PLLCLK)) #define IS_RCC_PLLSOURCE(SOURCE) (((SOURCE) == RCC_PLLSOURCE_HSI) || \ ((SOURCE) == RCC_PLLSOURCE_HSE)) #endif /* STM32F042x6 || STM32F048xx || */ /* STM32F071xB || STM32F072xB || STM32F078xx || */ /* STM32F091xC || STM32F098xx */ #if defined(STM32F030x6) || defined(STM32F031x6) || defined(STM32F038xx) || defined(STM32F070x6)\ || defined(STM32F070xB) || defined(STM32F030xC) #define IS_RCC_MCO1SOURCE(SOURCE) (((SOURCE) == RCC_MCOSOURCE_NONE) || \ ((SOURCE) == RCC_MCOSOURCE_LSI) || \ ((SOURCE) == RCC_MCOSOURCE_LSE) || \ ((SOURCE) == RCC_MCOSOURCE_SYSCLK) || \ ((SOURCE) == RCC_MCOSOURCE_HSI) || \ ((SOURCE) == RCC_MCOSOURCE_HSE) || \ ((SOURCE) == RCC_MCOSOURCE_PLLCLK_NODIV) || \ ((SOURCE) == RCC_MCOSOURCE_PLLCLK_DIV2) || \ ((SOURCE) == RCC_MCOSOURCE_HSI14)) #endif /* STM32F030x6 || STM32F031x6 || STM32F038xx || STM32F070x6 || STM32F070xB || STM32F030xC */ #if defined(STM32F030x8) || defined(STM32F051x8) || defined(STM32F058xx) #define IS_RCC_MCO1SOURCE(SOURCE) (((SOURCE) == RCC_MCOSOURCE_NONE) || \ ((SOURCE) == RCC_MCOSOURCE_LSI) || \ ((SOURCE) == RCC_MCOSOURCE_LSE) || \ ((SOURCE) == RCC_MCOSOURCE_SYSCLK) || \ ((SOURCE) == RCC_MCOSOURCE_HSI) || \ ((SOURCE) == RCC_MCOSOURCE_HSE) || \ ((SOURCE) == RCC_MCOSOURCE_PLLCLK_DIV2) || \ ((SOURCE) == RCC_MCOSOURCE_HSI14)) #endif /* STM32F030x8 || STM32F051x8 || STM32F058xx */ #if defined(STM32F042x6) || defined(STM32F048xx)\ || defined(STM32F071xB) || defined(STM32F072xB) || defined(STM32F078xx)\ || defined(STM32F091xC) || defined(STM32F098xx) #define IS_RCC_MCO1SOURCE(SOURCE) (((SOURCE) == RCC_MCOSOURCE_NONE) || \ ((SOURCE) == RCC_MCOSOURCE_LSI) || \ ((SOURCE) == RCC_MCOSOURCE_LSE) || \ ((SOURCE) == RCC_MCOSOURCE_SYSCLK) || \ ((SOURCE) == RCC_MCOSOURCE_HSI) || \ ((SOURCE) == RCC_MCOSOURCE_HSE) || \ ((SOURCE) == RCC_MCOSOURCE_PLLCLK_NODIV) || \ ((SOURCE) == RCC_MCOSOURCE_PLLCLK_DIV2) || \ ((SOURCE) == RCC_MCOSOURCE_HSI14) || \ ((SOURCE) == RCC_MCOSOURCE_HSI48)) #endif /* STM32F042x6 || STM32F048xx || */ /* STM32F071xB || STM32F072xB || STM32F078xx || */ /* STM32F091xC || STM32F098xx */ /** * @} */ /** @addtogroup RCC_Exported_Constants * @{ */ #if defined(STM32F042x6) || defined(STM32F048xx)\ || defined(STM32F071xB) || defined(STM32F072xB) || defined(STM32F078xx)\ || defined(STM32F091xC) || defined(STM32F098xx) /** @addtogroup RCC_PLL_Clock_Source * @{ */ #define RCC_PLLSOURCE_HSI RCC_CFGR_PLLSRC_HSI_PREDIV #define RCC_PLLSOURCE_HSI48 RCC_CFGR_PLLSRC_HSI48_PREDIV /** * @} */ /** @addtogroup RCC_Oscillator_Type * @{ */ #define RCC_OSCILLATORTYPE_HSI48 ((uint32_t)0x00000020) /** * @} */ /** @addtogroup RCC_Interrupt * @{ */ #define RCC_IT_HSI48 RCC_CIR_HSI48RDYF /*!< HSI48 Ready Interrupt flag */ /** * @} */ /** @addtogroup RCC_Flag * @{ */ #define RCC_FLAG_HSI48RDY ((uint8_t)((CR2_REG_INDEX << 5) | RCC_CR2_HSI48RDY_BitNumber)) /** * @} */ /** @addtogroup RCC_System_Clock_Source * @{ */ #define RCC_SYSCLKSOURCE_HSI48 RCC_CFGR_SW_HSI48 /** * @} */ /** @addtogroup RCC_System_Clock_Source_Status * @{ */ #define RCC_SYSCLKSOURCE_STATUS_HSI48 RCC_CFGR_SWS_HSI48 /** * @} */ #else /** @addtogroup RCC_PLL_Clock_Source * @{ */ #if defined(STM32F070xB) || defined(STM32F070x6) || defined(STM32F030xC) #define RCC_PLLSOURCE_HSI RCC_CFGR_PLLSRC_HSI_PREDIV #else #define RCC_PLLSOURCE_HSI RCC_CFGR_PLLSRC_HSI_DIV2 #endif /** * @} */ #endif /* STM32F042x6 || STM32F048xx || */ /* STM32F071xB || STM32F072xB || STM32F078xx || */ /* STM32F091xC || STM32F098xx */ /** @addtogroup RCC_MCO_Clock_Source * @{ */ #if defined(STM32F030x6) || defined(STM32F031x6) || defined(STM32F038xx) || defined(STM32F070x6)\ || defined(STM32F070xB) || defined(STM32F030xC) #define RCC_MCOSOURCE_PLLCLK_NODIV (RCC_CFGR_MCO_PLL | RCC_CFGR_PLLNODIV) #endif /* STM32F030x6 || STM32F031x6 || STM32F038xx || STM32F070x6 || STM32F070xB || STM32F030xC */ #if defined(STM32F042x6) || defined(STM32F048xx)\ || defined(STM32F071xB) || defined(STM32F072xB) || defined(STM32F078xx)\ || defined(STM32F091xC) || defined(STM32F098xx) #define RCC_MCOSOURCE_HSI48 RCC_CFGR_MCO_HSI48 #define RCC_MCOSOURCE_PLLCLK_NODIV (RCC_CFGR_MCO_PLL | RCC_CFGR_PLLNODIV) #endif /* STM32F042x6 || STM32F048xx || */ /* STM32F071xB || STM32F072xB || STM32F078xx || */ /* STM32F091xC || STM32F098xx */ /** * @} */ /** * @} */ /** * @} */ /** @addtogroup RCCEx * @{ */ /* Private macro -------------------------------------------------------------*/ /** @defgroup RCCEx_Private_Macros RCCEx Private Macros * @{ */ #if defined(STM32F030x6) || defined(STM32F030x8) || defined(STM32F031x6) || defined(STM32F038xx)\ || defined(STM32F030xC) #define IS_RCC_PERIPHCLK(SELECTION) ((SELECTION) <= (RCC_PERIPHCLK_USART1 | RCC_PERIPHCLK_I2C1 | \ RCC_PERIPHCLK_RTC)) #endif /* STM32F030x6 || STM32F030x8 || STM32F031x6 || STM32F038xx || STM32F030xC */ #if defined(STM32F070x6) || defined(STM32F070xB) #define IS_RCC_PERIPHCLK(SELECTION) ((SELECTION) <= (RCC_PERIPHCLK_USART1 | RCC_PERIPHCLK_I2C1 | \ RCC_PERIPHCLK_RTC | RCC_PERIPHCLK_USB)) #endif /* STM32F070x6 || STM32F070xB */ #if defined(STM32F042x6) || defined(STM32F048xx) #define IS_RCC_PERIPHCLK(SELECTION) ((SELECTION) <= (RCC_PERIPHCLK_USART1 | RCC_PERIPHCLK_I2C1 | \ RCC_PERIPHCLK_CEC | RCC_PERIPHCLK_RTC | \ RCC_PERIPHCLK_USB)) #endif /* STM32F042x6 || STM32F048xx */ #if defined(STM32F051x8) || defined(STM32F058xx) #define IS_RCC_PERIPHCLK(SELECTION) ((SELECTION) <= (RCC_PERIPHCLK_USART1 | RCC_PERIPHCLK_I2C1 | \ RCC_PERIPHCLK_CEC | RCC_PERIPHCLK_RTC)) #endif /* STM32F051x8 || STM32F058xx */ #if defined(STM32F071xB) #define IS_RCC_PERIPHCLK(SELECTION) ((SELECTION) <= (RCC_PERIPHCLK_USART1 | RCC_PERIPHCLK_USART2 | \ RCC_PERIPHCLK_I2C1 | RCC_PERIPHCLK_CEC | \ RCC_PERIPHCLK_RTC)) #endif /* STM32F071xB */ #if defined(STM32F072xB) || defined(STM32F078xx) #define IS_RCC_PERIPHCLK(SELECTION) ((SELECTION) <= (RCC_PERIPHCLK_USART1 | RCC_PERIPHCLK_USART2 | \ RCC_PERIPHCLK_I2C1 | RCC_PERIPHCLK_CEC | \ RCC_PERIPHCLK_RTC | RCC_PERIPHCLK_USB)) #endif /* STM32F072xB || STM32F078xx */ #if defined(STM32F091xC) || defined(STM32F098xx) #define IS_RCC_PERIPHCLK(SELECTION) ((SELECTION) <= (RCC_PERIPHCLK_USART1 | RCC_PERIPHCLK_USART2 | \ RCC_PERIPHCLK_I2C1 | RCC_PERIPHCLK_CEC | \ RCC_PERIPHCLK_RTC | RCC_PERIPHCLK_USART3 )) #endif /* STM32F091xC || STM32F098xx */ #if defined(STM32F042x6) || defined(STM32F048xx) || defined(STM32F072xB) || defined(STM32F078xx) #define IS_RCC_USBCLKSOURCE(SOURCE) (((SOURCE) == RCC_USBCLKSOURCE_HSI48) || \ ((SOURCE) == RCC_USBCLKSOURCE_PLLCLK)) #endif /* STM32F042x6 || STM32F048xx || STM32F072xB || STM32F078xx */ #if defined(STM32F070x6) || defined(STM32F070xB) #define IS_RCC_USBCLKSOURCE(SOURCE) (((SOURCE) == RCC_USBCLKSOURCE_PLLCLK)) #endif /* STM32F070x6 || STM32F070xB */ #if defined(STM32F071xB) || defined(STM32F072xB) || defined(STM32F078xx)\ || defined(STM32F091xC) || defined(STM32F098xx) #define IS_RCC_USART2CLKSOURCE(SOURCE) (((SOURCE) == RCC_USART2CLKSOURCE_PCLK1) || \ ((SOURCE) == RCC_USART2CLKSOURCE_SYSCLK) || \ ((SOURCE) == RCC_USART2CLKSOURCE_LSE) || \ ((SOURCE) == RCC_USART2CLKSOURCE_HSI)) #endif /* STM32F071xB || STM32F072xB || STM32F078xx || */ /* STM32F091xC || STM32F098xx */ #if defined(STM32F091xC) || defined(STM32F098xx) #define IS_RCC_USART3CLKSOURCE(SOURCE) (((SOURCE) == RCC_USART3CLKSOURCE_PCLK1) || \ ((SOURCE) == RCC_USART3CLKSOURCE_SYSCLK) || \ ((SOURCE) == RCC_USART3CLKSOURCE_LSE) || \ ((SOURCE) == RCC_USART3CLKSOURCE_HSI)) #endif /* STM32F091xC || STM32F098xx */ #if defined(STM32F042x6) || defined(STM32F048xx)\ || defined(STM32F051x8) || defined(STM32F058xx)\ || defined(STM32F071xB) || defined(STM32F072xB) || defined(STM32F078xx)\ || defined(STM32F091xC) || defined(STM32F098xx) #define IS_RCC_CECCLKSOURCE(SOURCE) (((SOURCE) == RCC_CECCLKSOURCE_HSI) || \ ((SOURCE) == RCC_CECCLKSOURCE_LSE)) #endif /* STM32F042x6 || STM32F048xx || */ /* STM32F051x8 || STM32F058xx || */ /* STM32F071xB || STM32F072xB || STM32F078xx || */ /* STM32F091xC || STM32F098xx */ #if defined(STM32F030x8) || defined(STM32F051x8) || defined(STM32F058xx) #define IS_RCC_MCODIV(DIV) (((DIV) == RCC_MCODIV_1)) #endif /* STM32F030x8 || STM32F051x8 || STM32F058xx */ #if defined(STM32F030x6) || defined(STM32F031x6) || defined(STM32F038xx) || defined(STM32F070x6)\ || defined(STM32F042x6) || defined(STM32F048xx) || defined(STM32F071xB) || defined(STM32F070xB)\ || defined(STM32F072xB) || defined(STM32F078xx)\ || defined(STM32F091xC) || defined(STM32F098xx) || defined(STM32F030xC) #define IS_RCC_MCODIV(DIV) (((DIV) == RCC_MCO_DIV1) || ((DIV) == RCC_MCO_DIV2) || \ ((DIV) == RCC_MCO_DIV4) || ((DIV) == RCC_MCO_DIV8) || \ ((DIV) == RCC_MCO_DIV16) || ((DIV) == RCC_MCO_DIV32) || \ ((DIV) == RCC_MCO_DIV64) || ((DIV) == RCC_MCO_DIV128)) #endif /* STM32F030x6 || STM32F031x6 || STM32F038xx || STM32F042x6 || STM32F048xx || */ /* STM32F071xB || STM32F072xB || STM32F078xx || STM32F070x6 || STM32F070xB */ /* STM32F091xC || STM32F098xx || STM32F030xC */ #if defined(STM32F042x6) || defined(STM32F048xx)\ || defined(STM32F071xB) || defined(STM32F072xB) || defined(STM32F078xx)\ || defined(STM32F091xC) || defined(STM32F098xx) #define IS_RCC_CRS_SYNC_SOURCE(_SOURCE_) (((_SOURCE_) == RCC_CRS_SYNC_SOURCE_GPIO) || \ ((_SOURCE_) == RCC_CRS_SYNC_SOURCE_LSE) || \ ((_SOURCE_) == RCC_CRS_SYNC_SOURCE_USB)) #define IS_RCC_CRS_SYNC_DIV(_DIV_) (((_DIV_) == RCC_CRS_SYNC_DIV1) || ((_DIV_) == RCC_CRS_SYNC_DIV2) || \ ((_DIV_) == RCC_CRS_SYNC_DIV4) || ((_DIV_) == RCC_CRS_SYNC_DIV8) || \ ((_DIV_) == RCC_CRS_SYNC_DIV16) || ((_DIV_) == RCC_CRS_SYNC_DIV32) || \ ((_DIV_) == RCC_CRS_SYNC_DIV64) || ((_DIV_) == RCC_CRS_SYNC_DIV128)) #define IS_RCC_CRS_SYNC_POLARITY(_POLARITY_) (((_POLARITY_) == RCC_CRS_SYNC_POLARITY_RISING) || \ ((_POLARITY_) == RCC_CRS_SYNC_POLARITY_FALLING)) #define IS_RCC_CRS_RELOADVALUE(_VALUE_) (((_VALUE_) <= 0xFFFF)) #define IS_RCC_CRS_ERRORLIMIT(_VALUE_) (((_VALUE_) <= 0xFF)) #define IS_RCC_CRS_HSI48CALIBRATION(_VALUE_) (((_VALUE_) <= 0x3F)) #define IS_RCC_CRS_FREQERRORDIR(_DIR_) (((_DIR_) == RCC_CRS_FREQERRORDIR_UP) || \ ((_DIR_) == RCC_CRS_FREQERRORDIR_DOWN)) #endif /* STM32F042x6 || STM32F048xx || */ /* STM32F071xB || STM32F072xB || STM32F078xx || */ /* STM32F091xC || STM32F098xx */ /** * @} */ /* Exported types ------------------------------------------------------------*/ /** @defgroup RCCEx_Exported_Types RCCEx Exported Types * @{ */ /** * @brief RCC extended clocks structure definition */ #if defined(STM32F030x6) || defined(STM32F030x8) || defined(STM32F031x6) || defined(STM32F038xx)\ || defined(STM32F030xC) typedef struct { uint32_t PeriphClockSelection; /*!< The Extended Clock to be configured. This parameter can be a value of @ref RCCEx_Periph_Clock_Selection */ uint32_t RTCClockSelection; /*!< Specifies RTC Clock Prescalers Selection This parameter can be a value of @ref RCC_RTC_Clock_Source */ uint32_t Usart1ClockSelection; /*!< USART1 clock source This parameter can be a value of @ref RCC_USART1_Clock_Source */ uint32_t I2c1ClockSelection; /*!< I2C1 clock source This parameter can be a value of @ref RCC_I2C1_Clock_Source */ }RCC_PeriphCLKInitTypeDef; #endif /* STM32F030x6 || STM32F030x8 || STM32F031x6 || STM32F038xx || STM32F030xC */ #if defined(STM32F070x6) || defined(STM32F070xB) typedef struct { uint32_t PeriphClockSelection; /*!< The Extended Clock to be configured. This parameter can be a value of @ref RCCEx_Periph_Clock_Selection */ uint32_t RTCClockSelection; /*!< Specifies RTC Clock Prescalers Selection This parameter can be a value of @ref RCC_RTC_Clock_Source */ uint32_t Usart1ClockSelection; /*!< USART1 clock source This parameter can be a value of @ref RCC_USART1_Clock_Source */ uint32_t I2c1ClockSelection; /*!< I2C1 clock source This parameter can be a value of @ref RCC_I2C1_Clock_Source */ uint32_t UsbClockSelection; /*!< USB clock source This parameter can be a value of @ref RCCEx_USB_Clock_Source */ }RCC_PeriphCLKInitTypeDef; #endif /* STM32F070x6 || STM32F070xB */ #if defined(STM32F042x6) || defined(STM32F048xx) typedef struct { uint32_t PeriphClockSelection; /*!< The Extended Clock to be configured. This parameter can be a value of @ref RCCEx_Periph_Clock_Selection */ uint32_t RTCClockSelection; /*!< Specifies RTC Clock Prescalers Selection This parameter can be a value of @ref RCC_RTC_Clock_Source */ uint32_t Usart1ClockSelection; /*!< USART1 clock source This parameter can be a value of @ref RCC_USART1_Clock_Source */ uint32_t I2c1ClockSelection; /*!< I2C1 clock source This parameter can be a value of @ref RCC_I2C1_Clock_Source */ uint32_t CecClockSelection; /*!< HDMI CEC clock source This parameter can be a value of @ref RCCEx_CEC_Clock_Source */ uint32_t UsbClockSelection; /*!< USB clock source This parameter can be a value of @ref RCCEx_USB_Clock_Source */ }RCC_PeriphCLKInitTypeDef; #endif /* STM32F042x6 || STM32F048xx */ #if defined(STM32F051x8) || defined(STM32F058xx) typedef struct { uint32_t PeriphClockSelection; /*!< The Extended Clock to be configured. This parameter can be a value of @ref RCCEx_Periph_Clock_Selection */ uint32_t RTCClockSelection; /*!< Specifies RTC Clock Prescalers Selection This parameter can be a value of @ref RCC_RTC_Clock_Source */ uint32_t Usart1ClockSelection; /*!< USART1 clock source This parameter can be a value of @ref RCC_USART1_Clock_Source */ uint32_t I2c1ClockSelection; /*!< I2C1 clock source This parameter can be a value of @ref RCC_I2C1_Clock_Source */ uint32_t CecClockSelection; /*!< HDMI CEC clock source This parameter can be a value of @ref RCCEx_CEC_Clock_Source */ }RCC_PeriphCLKInitTypeDef; #endif /* STM32F051x8 || STM32F058xx */ #if defined(STM32F071xB) typedef struct { uint32_t PeriphClockSelection; /*!< The Extended Clock to be configured. This parameter can be a value of @ref RCCEx_Periph_Clock_Selection */ uint32_t RTCClockSelection; /*!< Specifies RTC Clock Prescalers Selection This parameter can be a value of @ref RCC_RTC_Clock_Source */ uint32_t Usart1ClockSelection; /*!< USART1 clock source This parameter can be a value of @ref RCC_USART1_Clock_Source */ uint32_t Usart2ClockSelection; /*!< USART2 clock source This parameter can be a value of @ref RCCEx_USART2_Clock_Source */ uint32_t I2c1ClockSelection; /*!< I2C1 clock source This parameter can be a value of @ref RCC_I2C1_Clock_Source */ uint32_t CecClockSelection; /*!< HDMI CEC clock source This parameter can be a value of @ref RCCEx_CEC_Clock_Source */ }RCC_PeriphCLKInitTypeDef; #endif /* STM32F071xB */ #if defined(STM32F072xB) || defined(STM32F078xx) typedef struct { uint32_t PeriphClockSelection; /*!< The Extended Clock to be configured. This parameter can be a value of @ref RCCEx_Periph_Clock_Selection */ uint32_t RTCClockSelection; /*!< Specifies RTC Clock Prescalers Selection This parameter can be a value of @ref RCC_RTC_Clock_Source */ uint32_t Usart1ClockSelection; /*!< USART1 clock source This parameter can be a value of @ref RCC_USART1_Clock_Source */ uint32_t Usart2ClockSelection; /*!< USART2 clock source This parameter can be a value of @ref RCCEx_USART2_Clock_Source */ uint32_t I2c1ClockSelection; /*!< I2C1 clock source This parameter can be a value of @ref RCC_I2C1_Clock_Source */ uint32_t CecClockSelection; /*!< HDMI CEC clock source This parameter can be a value of @ref RCCEx_CEC_Clock_Source */ uint32_t UsbClockSelection; /*!< USB clock source This parameter can be a value of @ref RCCEx_USB_Clock_Source */ }RCC_PeriphCLKInitTypeDef; #endif /* STM32F072xB || STM32F078xx */ #if defined(STM32F091xC) || defined(STM32F098xx) typedef struct { uint32_t PeriphClockSelection; /*!< The Extended Clock to be configured. This parameter can be a value of @ref RCCEx_Periph_Clock_Selection */ uint32_t RTCClockSelection; /*!< Specifies RTC Clock Prescalers Selection This parameter can be a value of @ref RCC_RTC_Clock_Source */ uint32_t Usart1ClockSelection; /*!< USART1 clock source This parameter can be a value of @ref RCC_USART1_Clock_Source */ uint32_t Usart2ClockSelection; /*!< USART2 clock source This parameter can be a value of @ref RCCEx_USART2_Clock_Source */ uint32_t Usart3ClockSelection; /*!< USART3 clock source This parameter can be a value of @ref RCCEx_USART3_Clock_Source */ uint32_t I2c1ClockSelection; /*!< I2C1 clock source This parameter can be a value of @ref RCC_I2C1_Clock_Source */ uint32_t CecClockSelection; /*!< HDMI CEC clock source This parameter can be a value of @ref RCCEx_CEC_Clock_Source */ }RCC_PeriphCLKInitTypeDef; #endif /* STM32F091xC || STM32F098xx */ #if defined(STM32F042x6) || defined(STM32F048xx)\ || defined(STM32F071xB) || defined(STM32F072xB) || defined(STM32F078xx)\ || defined(STM32F091xC) || defined(STM32F098xx) /** * @brief RCC_CRS Init structure definition */ typedef struct { uint32_t Prescaler; /*!< Specifies the division factor of the SYNC signal. This parameter can be a value of @ref RCCEx_CRS_SynchroDivider */ uint32_t Source; /*!< Specifies the SYNC signal source. This parameter can be a value of @ref RCCEx_CRS_SynchroSource */ uint32_t Polarity; /*!< Specifies the input polarity for the SYNC signal source. This parameter can be a value of @ref RCCEx_CRS_SynchroPolarity */ uint32_t ReloadValue; /*!< Specifies the value to be loaded in the frequency error counter with each SYNC event. It can be calculated in using macro __HAL_RCC_CRS_CALCULATE_RELOADVALUE(_FTARGET_, _FSYNC_) This parameter must be a number between 0 and 0xFFFF or a value of @ref RCCEx_CRS_ReloadValueDefault .*/ uint32_t ErrorLimitValue; /*!< Specifies the value to be used to evaluate the captured frequency error value. This parameter must be a number between 0 and 0xFF or a value of @ref RCCEx_CRS_ErrorLimitDefault */ uint32_t HSI48CalibrationValue; /*!< Specifies a user-programmable trimming value to the HSI48 oscillator. This parameter must be a number between 0 and 0x3F or a value of @ref RCCEx_CRS_HSI48CalibrationDefault */ }RCC_CRSInitTypeDef; /** * @brief RCC_CRS Synchronization structure definition */ typedef struct { uint32_t ReloadValue; /*!< Specifies the value loaded in the Counter reload value. This parameter must be a number between 0 and 0xFFFF*/ uint32_t HSI48CalibrationValue; /*!< Specifies value loaded in HSI48 oscillator smooth trimming. This parameter must be a number between 0 and 0x3F */ uint32_t FreqErrorCapture; /*!< Specifies the value loaded in the .FECAP, the frequency error counter value latched in the time of the last SYNC event. This parameter must be a number between 0 and 0xFFFF */ uint32_t FreqErrorDirection; /*!< Specifies the value loaded in the .FEDIR, the counting direction of the frequency error counter latched in the time of the last SYNC event. It shows whether the actual frequency is below or above the target. This parameter must be a value of @ref RCCEx_CRS_FreqErrorDirection*/ }RCC_CRSSynchroInfoTypeDef; #endif /* STM32F042x6 || STM32F048xx */ /* STM32F071xB || STM32F072xB || STM32F078xx || */ /* STM32F091xC || STM32F098xx */ /** * @} */ /* Exported constants --------------------------------------------------------*/ /** @defgroup RCCEx_Exported_Constants RCCEx Exported Constants * @{ */ #if defined(STM32F042x6) || defined(STM32F048xx)\ || defined(STM32F071xB) || defined(STM32F072xB) || defined(STM32F078xx)\ || defined(STM32F091xC) || defined(STM32F098xx) /** @defgroup RCCEx_HSI48_Config RCCEx HSI48 Config * @{ */ #define RCC_HSI48_OFF ((uint8_t)0x00) #define RCC_HSI48_ON ((uint8_t)0x01) /** * @} */ /** @defgroup RCCEx_CRS_Status RCCEx CRS Status * @{ */ #define RCC_CRS_NONE ((uint32_t)0x00000000) #define RCC_CRS_TIMEOUT ((uint32_t)0x00000001) #define RCC_CRS_SYNCOK ((uint32_t)0x00000002) #define RCC_CRS_SYNCWARM ((uint32_t)0x00000004) #define RCC_CRS_SYNCERR ((uint32_t)0x00000008) #define RCC_CRS_SYNCMISS ((uint32_t)0x00000010) #define RCC_CRS_TRIMOV ((uint32_t)0x00000020) /** * @} */ #else /** @defgroup RCCEx_HSI48_Config RCCEx HSI48 Config * @{ */ #define RCC_HSI48_OFF ((uint8_t)0x00) /** * @} */ #endif /* STM32F042x6 || STM32F048xx */ /* STM32F071xB || STM32F072xB || STM32F078xx || */ /* STM32F091xC || STM32F098xx */ /** @defgroup RCCEx_Periph_Clock_Selection RCCEx Periph Clock Selection * @{ */ #if defined(STM32F030x6) || defined(STM32F030x8) || defined(STM32F031x6) || defined(STM32F038xx)\ || defined(STM32F030xC) #define RCC_PERIPHCLK_USART1 ((uint32_t)0x00000001) #define RCC_PERIPHCLK_I2C1 ((uint32_t)0x00000020) #define RCC_PERIPHCLK_RTC ((uint32_t)0x00010000) #endif /* STM32F030x6 || STM32F030x8 || STM32F031x6 || STM32F038xx || STM32F030xC */ #if defined(STM32F070x6) || defined(STM32F070xB) #define RCC_PERIPHCLK_USART1 ((uint32_t)0x00000001) #define RCC_PERIPHCLK_I2C1 ((uint32_t)0x00000020) #define RCC_PERIPHCLK_RTC ((uint32_t)0x00010000) #define RCC_PERIPHCLK_USB ((uint32_t)0x00020000) #endif /* STM32F070x6 || STM32F070xB */ #if defined(STM32F042x6) || defined(STM32F048xx) #define RCC_PERIPHCLK_USART1 ((uint32_t)0x00000001) #define RCC_PERIPHCLK_I2C1 ((uint32_t)0x00000020) #define RCC_PERIPHCLK_CEC ((uint32_t)0x00000400) #define RCC_PERIPHCLK_RTC ((uint32_t)0x00010000) #define RCC_PERIPHCLK_USB ((uint32_t)0x00020000) #endif /* STM32F042x6 || STM32F048xx */ #if defined(STM32F051x8) || defined(STM32F058xx) #define RCC_PERIPHCLK_USART1 ((uint32_t)0x00000001) #define RCC_PERIPHCLK_I2C1 ((uint32_t)0x00000020) #define RCC_PERIPHCLK_CEC ((uint32_t)0x00000400) #define RCC_PERIPHCLK_RTC ((uint32_t)0x00010000) #endif /* STM32F051x8 || STM32F058xx */ #if defined(STM32F071xB) #define RCC_PERIPHCLK_USART1 ((uint32_t)0x00000001) #define RCC_PERIPHCLK_USART2 ((uint32_t)0x00000002) #define RCC_PERIPHCLK_I2C1 ((uint32_t)0x00000020) #define RCC_PERIPHCLK_CEC ((uint32_t)0x00000400) #define RCC_PERIPHCLK_RTC ((uint32_t)0x00010000) #endif /* STM32F071xB */ #if defined(STM32F072xB) || defined(STM32F078xx) #define RCC_PERIPHCLK_USART1 ((uint32_t)0x00000001) #define RCC_PERIPHCLK_USART2 ((uint32_t)0x00000002) #define RCC_PERIPHCLK_I2C1 ((uint32_t)0x00000020) #define RCC_PERIPHCLK_CEC ((uint32_t)0x00000400) #define RCC_PERIPHCLK_RTC ((uint32_t)0x00010000) #define RCC_PERIPHCLK_USB ((uint32_t)0x00020000) #endif /* STM32F072xB || STM32F078xx */ #if defined(STM32F091xC) || defined(STM32F098xx) #define RCC_PERIPHCLK_USART1 ((uint32_t)0x00000001) #define RCC_PERIPHCLK_USART2 ((uint32_t)0x00000002) #define RCC_PERIPHCLK_I2C1 ((uint32_t)0x00000020) #define RCC_PERIPHCLK_CEC ((uint32_t)0x00000400) #define RCC_PERIPHCLK_RTC ((uint32_t)0x00010000) #define RCC_PERIPHCLK_USART3 ((uint32_t)0x00040000) #endif /* STM32F091xC || STM32F098xx */ /** * @} */ #if defined(STM32F042x6) || defined(STM32F048xx) || defined(STM32F072xB) || defined(STM32F078xx) /** @defgroup RCCEx_USB_Clock_Source RCCEx USB Clock Source * @{ */ #define RCC_USBCLKSOURCE_HSI48 RCC_CFGR3_USBSW_HSI48 #define RCC_USBCLKSOURCE_PLLCLK RCC_CFGR3_USBSW_PLLCLK /** * @} */ #endif /* STM32F042x6 || STM32F048xx || STM32F072xB || STM32F078xx */ #if defined(STM32F070x6) || defined(STM32F070xB) /** @defgroup RCCEx_USB_Clock_Source RCCEx USB Clock Source * @{ */ #define RCC_USBCLKSOURCE_PLLCLK RCC_CFGR3_USBSW_PLLCLK /** * @} */ #endif /* STM32F070x6 || STM32F070xB */ #if defined(STM32F071xB) || defined(STM32F072xB) || defined(STM32F078xx)\ || defined(STM32F091xC) || defined(STM32F098xx) /** @defgroup RCCEx_USART2_Clock_Source RCCEx USART2 Clock Source * @{ */ #define RCC_USART2CLKSOURCE_PCLK1 RCC_CFGR3_USART2SW_PCLK #define RCC_USART2CLKSOURCE_SYSCLK RCC_CFGR3_USART2SW_SYSCLK #define RCC_USART2CLKSOURCE_LSE RCC_CFGR3_USART2SW_LSE #define RCC_USART2CLKSOURCE_HSI RCC_CFGR3_USART2SW_HSI /** * @} */ #endif /* STM32F071xB || STM32F072xB || STM32F078xx || */ /* STM32F091xC || STM32F098xx */ #if defined(STM32F091xC) || defined(STM32F098xx) /** @defgroup RCCEx_USART3_Clock_Source RCCEx USART3 Clock Source * @{ */ #define RCC_USART3CLKSOURCE_PCLK1 RCC_CFGR3_USART3SW_PCLK #define RCC_USART3CLKSOURCE_SYSCLK RCC_CFGR3_USART3SW_SYSCLK #define RCC_USART3CLKSOURCE_LSE RCC_CFGR3_USART3SW_LSE #define RCC_USART3CLKSOURCE_HSI RCC_CFGR3_USART3SW_HSI /** * @} */ #endif /* STM32F091xC || STM32F098xx */ #if defined(STM32F042x6) || defined(STM32F048xx)\ || defined(STM32F051x8) || defined(STM32F058xx)\ || defined(STM32F071xB) || defined(STM32F072xB) || defined(STM32F078xx)\ || defined(STM32F091xC) || defined(STM32F098xx) /** @defgroup RCCEx_CEC_Clock_Source RCCEx CEC Clock Source * @{ */ #define RCC_CECCLKSOURCE_HSI RCC_CFGR3_CECSW_HSI_DIV244 #define RCC_CECCLKSOURCE_LSE RCC_CFGR3_CECSW_LSE /** * @} */ #endif /* STM32F042x6 || STM32F048xx || */ /* STM32F051x8 || STM32F058xx || */ /* STM32F071xB || STM32F072xB || STM32F078xx || */ /* STM32F091xC || STM32F098xx */ /** @defgroup RCCEx_MCOx_Clock_Prescaler RCCEx MCOx Clock Prescaler * @{ */ #if defined(STM32F030x8) || defined(STM32F051x8) || defined(STM32F058xx) #define RCC_MCODIV_1 ((uint32_t)0x00000000) #endif /* STM32F030x8 || STM32F051x8 || STM32F058xx */ #if defined(STM32F030x6) || defined(STM32F031x6) || defined(STM32F038xx) || defined(STM32F070x6)\ || defined(STM32F042x6) || defined(STM32F048xx) || defined(STM32F071xB) || defined(STM32F070xB)\ || defined(STM32F072xB) || defined(STM32F078xx)\ || defined(STM32F091xC) || defined(STM32F098xx) || defined(STM32F030xC) #define RCC_MCO_DIV1 ((uint32_t)0x00000000) #define RCC_MCO_DIV2 ((uint32_t)0x10000000) #define RCC_MCO_DIV4 ((uint32_t)0x20000000) #define RCC_MCO_DIV8 ((uint32_t)0x30000000) #define RCC_MCO_DIV16 ((uint32_t)0x40000000) #define RCC_MCO_DIV32 ((uint32_t)0x50000000) #define RCC_MCO_DIV64 ((uint32_t)0x60000000) #define RCC_MCO_DIV128 ((uint32_t)0x70000000) #endif /* STM32F030x6 || STM32F031x6 || STM32F038xx || STM32F042x6 || STM32F048xx || */ /* STM32F071xB || STM32F072xB || STM32F078xx || STM32F070x6 || STM32F070xB */ /* STM32F091xC || STM32F098xx || STM32F030xC */ /** * @} */ #if defined(STM32F042x6) || defined(STM32F048xx)\ || defined(STM32F071xB) || defined(STM32F072xB) || defined(STM32F078xx)\ || defined(STM32F091xC) || defined(STM32F098xx) /** @defgroup RCCEx_CRS_SynchroSource RCCEx CRS SynchroSource * @{ */ #define RCC_CRS_SYNC_SOURCE_GPIO ((uint32_t)0x00) /*!< Synchro Signal soucre GPIO */ #define RCC_CRS_SYNC_SOURCE_LSE CRS_CFGR_SYNCSRC_0 /*!< Synchro Signal source LSE */ #define RCC_CRS_SYNC_SOURCE_USB CRS_CFGR_SYNCSRC_1 /*!< Synchro Signal source USB SOF (default)*/ /** * @} */ /** @defgroup RCCEx_CRS_SynchroDivider RCCEx CRS SynchroDivider * @{ */ #define RCC_CRS_SYNC_DIV1 ((uint32_t)0x00) /*!< Synchro Signal not divided (default) */ #define RCC_CRS_SYNC_DIV2 CRS_CFGR_SYNCDIV_0 /*!< Synchro Signal divided by 2 */ #define RCC_CRS_SYNC_DIV4 CRS_CFGR_SYNCDIV_1 /*!< Synchro Signal divided by 4 */ #define RCC_CRS_SYNC_DIV8 (CRS_CFGR_SYNCDIV_1 | CRS_CFGR_SYNCDIV_0) /*!< Synchro Signal divided by 8 */ #define RCC_CRS_SYNC_DIV16 CRS_CFGR_SYNCDIV_2 /*!< Synchro Signal divided by 16 */ #define RCC_CRS_SYNC_DIV32 (CRS_CFGR_SYNCDIV_2 | CRS_CFGR_SYNCDIV_0) /*!< Synchro Signal divided by 32 */ #define RCC_CRS_SYNC_DIV64 (CRS_CFGR_SYNCDIV_2 | CRS_CFGR_SYNCDIV_1) /*!< Synchro Signal divided by 64 */ #define RCC_CRS_SYNC_DIV128 CRS_CFGR_SYNCDIV /*!< Synchro Signal divided by 128 */ /** * @} */ /** @defgroup RCCEx_CRS_SynchroPolarity RCCEx CRS SynchroPolarity * @{ */ #define RCC_CRS_SYNC_POLARITY_RISING ((uint32_t)0x00) /*!< Synchro Active on rising edge (default) */ #define RCC_CRS_SYNC_POLARITY_FALLING CRS_CFGR_SYNCPOL /*!< Synchro Active on falling edge */ /** * @} */ /** @defgroup RCCEx_CRS_ReloadValueDefault RCCEx CRS ReloadValueDefault * @{ */ #define RCC_CRS_RELOADVALUE_DEFAULT ((uint32_t)0xBB7F) /*!< The reset value of the RELOAD field corresponds to a target frequency of 48 MHz and a synchronization signal frequency of 1 kHz (SOF signal from USB). */ /** * @} */ /** @defgroup RCCEx_CRS_ErrorLimitDefault RCCEx CRS ErrorLimitDefault * @{ */ #define RCC_CRS_ERRORLIMIT_DEFAULT ((uint32_t)0x22) /*!< Default Frequency error limit */ /** * @} */ /** @defgroup RCCEx_CRS_HSI48CalibrationDefault RCCEx CRS HSI48CalibrationDefault * @{ */ #define RCC_CRS_HSI48CALIBRATION_DEFAULT ((uint32_t)0x20) /*!< The default value is 32, which corresponds to the middle of the trimming interval. The trimming step is around 67 kHz between two consecutive TRIM steps. A higher TRIM value corresponds to a higher output frequency */ /** * @} */ /** @defgroup RCCEx_CRS_FreqErrorDirection RCCEx CRS FreqErrorDirection * @{ */ #define RCC_CRS_FREQERRORDIR_UP ((uint32_t)0x00) /*!< Upcounting direction, the actual frequency is above the target */ #define RCC_CRS_FREQERRORDIR_DOWN ((uint32_t)CRS_ISR_FEDIR) /*!< Downcounting direction, the actual frequency is below the target */ /** * @} */ /** @defgroup RCCEx_CRS_Interrupt_Sources RCCEx CRS Interrupt Sources * @{ */ #define RCC_CRS_IT_SYNCOK CRS_ISR_SYNCOKF /*!< SYNC event OK */ #define RCC_CRS_IT_SYNCWARN CRS_ISR_SYNCWARNF /*!< SYNC warning */ #define RCC_CRS_IT_ERR CRS_ISR_ERRF /*!< error */ #define RCC_CRS_IT_ESYNC CRS_ISR_ESYNCF /*!< Expected SYNC */ #define RCC_CRS_IT_TRIMOVF CRS_ISR_TRIMOVF /*!< Trimming overflow or underflow */ #define RCC_CRS_IT_SYNCERR CRS_ISR_SYNCERR /*!< SYNC error */ #define RCC_CRS_IT_SYNCMISS CRS_ISR_SYNCMISS /*!< SYNC missed*/ /** * @} */ /** @defgroup RCCEx_CRS_Flags RCCEx CRS Flags * @{ */ #define RCC_CRS_FLAG_SYNCOK CRS_ISR_SYNCOKF /* SYNC event OK flag */ #define RCC_CRS_FLAG_SYNCWARN CRS_ISR_SYNCWARNF /* SYNC warning flag */ #define RCC_CRS_FLAG_ERR CRS_ISR_ERRF /* Error flag */ #define RCC_CRS_FLAG_ESYNC CRS_ISR_ESYNCF /* Expected SYNC flag */ #define RCC_CRS_FLAG_TRIMOVF CRS_ISR_TRIMOVF /*!< Trimming overflow or underflow */ #define RCC_CRS_FLAG_SYNCERR CRS_ISR_SYNCERR /*!< SYNC error */ #define RCC_CRS_FLAG_SYNCMISS CRS_ISR_SYNCMISS /*!< SYNC missed*/ /** * @} */ #endif /* STM32F042x6 || STM32F048xx || */ /* STM32F071xB || STM32F072xB || STM32F078xx || */ /* STM32F091xC || STM32F098xx */ /** * @} */ /* Exported macros ------------------------------------------------------------*/ /** @defgroup RCCEx_Exported_Macros RCCEx Exported Macros * @{ */ /** @defgroup RCCEx_Peripheral_Clock_Enable_Disable RCCEx_Peripheral_Clock_Enable_Disable * @brief Enables or disables the AHB1 peripheral clock. * @note After reset, the peripheral clock (used for registers read/write access) * is disabled and the application software has to enable this clock before * using it. * @{ */ #if defined(STM32F030x6) || defined(STM32F030x8)\ || defined(STM32F051x8) || defined(STM32F058xx) || defined(STM32F070xB)\ || defined(STM32F071xB) || defined(STM32F072xB) || defined(STM32F078xx)\ || defined(STM32F091xC) || defined(STM32F098xx) || defined(STM32F030xC) #define __HAL_RCC_GPIOD_CLK_ENABLE() do { \ __IO uint32_t tmpreg; \ SET_BIT(RCC->AHBENR, RCC_AHBENR_GPIODEN);\ /* Delay after an RCC peripheral clock enabling */ \ tmpreg = READ_BIT(RCC->AHBENR, RCC_AHBENR_GPIODEN);\ UNUSED(tmpreg); \ } while(0) #define __HAL_RCC_GPIOD_CLK_DISABLE() (RCC->AHBENR &= ~(RCC_AHBENR_GPIODEN)) #endif /* STM32F030x6 || STM32F030x8 || */ /* STM32F051x8 || STM32F058xx || STM32F070xB || */ /* STM32F071xB || STM32F072xB || STM32F078xx || */ /* STM32F091xC || STM32F098xx || STM32F030xC */ #if defined(STM32F071xB) || defined(STM32F072xB) || defined(STM32F078xx) || defined(STM32F070xB)\ || defined(STM32F091xC) || defined(STM32F098xx) || defined(STM32F030xC) #define __HAL_RCC_GPIOE_CLK_ENABLE() do { \ __IO uint32_t tmpreg; \ SET_BIT(RCC->AHBENR, RCC_AHBENR_GPIOEEN);\ /* Delay after an RCC peripheral clock enabling */ \ tmpreg = READ_BIT(RCC->AHBENR, RCC_AHBENR_GPIOEEN);\ UNUSED(tmpreg); \ } while(0) #define __HAL_RCC_GPIOE_CLK_DISABLE() (RCC->AHBENR &= ~(RCC_AHBENR_GPIOEEN)) #endif /* STM32F071xB || STM32F072xB || STM32F078xx || STM32F070xB || */ /* STM32F091xC || STM32F098xx || STM32F030xC */ #if defined(STM32F042x6) || defined(STM32F048xx)\ || defined(STM32F051x8) || defined(STM32F058xx)\ || defined(STM32F071xB) || defined(STM32F072xB) || defined(STM32F078xx)\ || defined(STM32F091xC) || defined(STM32F098xx) #define __HAL_RCC_TSC_CLK_ENABLE() do { \ __IO uint32_t tmpreg; \ SET_BIT(RCC->AHBENR, RCC_AHBENR_TSCEN);\ /* Delay after an RCC peripheral clock enabling */ \ tmpreg = READ_BIT(RCC->AHBENR, RCC_AHBENR_TSCEN);\ UNUSED(tmpreg); \ } while(0) #define __HAL_RCC_TSC_CLK_DISABLE() (RCC->AHBENR &= ~(RCC_AHBENR_TSCEN)) #endif /* STM32F042x6 || STM32F048xx || */ /* STM32F051x8 || STM32F058xx || */ /* STM32F071xB || STM32F072xB || STM32F078xx || */ /* STM32F091xC || STM32F098xx */ #if defined(STM32F091xC) || defined(STM32F098xx) #define __HAL_RCC_DMA2_CLK_ENABLE() do { \ __IO uint32_t tmpreg; \ SET_BIT(RCC->AHBENR, RCC_AHBENR_DMA2EN);\ /* Delay after an RCC peripheral clock enabling */ \ tmpreg = READ_BIT(RCC->AHBENR, RCC_AHBENR_DMA2EN);\ UNUSED(tmpreg); \ } while(0) #define __HAL_RCC_DMA2_CLK_DISABLE() (RCC->AHBENR &= ~(RCC_AHBENR_DMA2EN)) #endif /* STM32F091xC || STM32F098xx */ /** @brief Enable or disable the Low Speed APB (APB1) peripheral clock. * @note After reset, the peripheral clock (used for registers read/write access) * is disabled and the application software has to enable this clock before * using it. */ #if defined(STM32F030x8)\ || defined(STM32F042x6) || defined(STM32F048xx) || defined(STM32F070x6)\ || defined(STM32F051x8) || defined(STM32F058xx)\ || defined(STM32F071xB) || defined(STM32F072xB) || defined(STM32F078xx) || defined(STM32F070xB)\ || defined(STM32F091xC) || defined(STM32F098xx) || defined(STM32F030xC) #define __HAL_RCC_USART2_CLK_ENABLE() do { \ __IO uint32_t tmpreg; \ SET_BIT(RCC->APB1ENR, RCC_APB1ENR_USART2EN);\ /* Delay after an RCC peripheral clock enabling */ \ tmpreg = READ_BIT(RCC->APB1ENR, RCC_APB1ENR_USART2EN);\ UNUSED(tmpreg); \ } while(0) #define __HAL_RCC_USART2_CLK_DISABLE() (RCC->APB1ENR &= ~(RCC_APB1ENR_USART2EN)) #endif /* STM32F030x8 || STM32F042x6 || STM32F048xx || */ /* STM32F051x8 || STM32F058xx || STM32F070x6 || */ /* STM32F071xB || STM32F072xB || STM32F078xx || STM32F070xB || */ /* STM32F091xC || STM32F098xx || STM32F030xC */ #if defined(STM32F030x8)\ || defined(STM32F042x6) || defined(STM32F048xx)\ || defined(STM32F051x8) || defined(STM32F058xx)\ || defined(STM32F071xB) || defined(STM32F072xB) || defined(STM32F078xx) || defined(STM32F070xB)\ || defined(STM32F091xC) || defined(STM32F098xx) || defined(STM32F030xC) #define __HAL_RCC_SPI2_CLK_ENABLE() do { \ __IO uint32_t tmpreg; \ SET_BIT(RCC->APB1ENR, RCC_APB1ENR_SPI2EN);\ /* Delay after an RCC peripheral clock enabling */ \ tmpreg = READ_BIT(RCC->APB1ENR, RCC_APB1ENR_SPI2EN);\ UNUSED(tmpreg); \ } while(0) #define __HAL_RCC_SPI2_CLK_DISABLE() (RCC->APB1ENR &= ~(RCC_APB1ENR_SPI2EN)) #endif /* STM32F030x8 || STM32F042x6 || STM32F048xx || */ /* STM32F051x8 || STM32F058xx || */ /* STM32F071xB || STM32F072xB || STM32F078xx || STM32F070xB || */ /* STM32F091xC || STM32F098xx || STM32F030xC */ #if defined(STM32F031x6) || defined(STM32F038xx)\ || defined(STM32F042x6) || defined(STM32F048xx)\ || defined(STM32F051x8) || defined(STM32F058xx)\ || defined(STM32F071xB) || defined(STM32F072xB) || defined(STM32F078xx)\ || defined(STM32F091xC) || defined(STM32F098xx) #define __HAL_RCC_TIM2_CLK_ENABLE() do { \ __IO uint32_t tmpreg; \ SET_BIT(RCC->APB1ENR, RCC_APB1ENR_TIM2EN);\ /* Delay after an RCC peripheral clock enabling */ \ tmpreg = READ_BIT(RCC->APB1ENR, RCC_APB1ENR_TIM2EN);\ UNUSED(tmpreg); \ } while(0) #define __HAL_RCC_TIM2_CLK_DISABLE() (RCC->APB1ENR &= ~(RCC_APB1ENR_TIM2EN)) #endif /* STM32F031x6 || STM32F038xx || */ /* STM32F042x6 || STM32F048xx || */ /* STM32F051x8 || STM32F058xx || */ /* STM32F071xB || STM32F072xB || STM32F078xx || */ /* STM32F091xC || STM32F098xx */ #if defined(STM32F030x8) \ || defined(STM32F051x8) || defined(STM32F058xx)\ || defined(STM32F071xB) || defined(STM32F072xB) || defined(STM32F078xx) || defined(STM32F070xB)\ || defined(STM32F091xC) || defined(STM32F098xx) || defined(STM32F030xC) #define __HAL_RCC_TIM6_CLK_ENABLE() do { \ __IO uint32_t tmpreg; \ SET_BIT(RCC->APB1ENR, RCC_APB1ENR_TIM6EN);\ /* Delay after an RCC peripheral clock enabling */ \ tmpreg = READ_BIT(RCC->APB1ENR, RCC_APB1ENR_TIM6EN);\ UNUSED(tmpreg); \ } while(0) #define __HAL_RCC_I2C2_CLK_ENABLE() do { \ __IO uint32_t tmpreg; \ SET_BIT(RCC->APB1ENR, RCC_APB1ENR_I2C2EN);\ /* Delay after an RCC peripheral clock enabling */ \ tmpreg = READ_BIT(RCC->APB1ENR, RCC_APB1ENR_I2C2EN);\ UNUSED(tmpreg); \ } while(0) #define __HAL_RCC_TIM6_CLK_DISABLE() (RCC->APB1ENR &= ~(RCC_APB1ENR_TIM6EN)) #define __HAL_RCC_I2C2_CLK_DISABLE() (RCC->APB1ENR &= ~(RCC_APB1ENR_I2C2EN)) #endif /* STM32F030x8 || */ /* STM32F051x8 || STM32F058xx || */ /* STM32F071xB || STM32F072xB || STM32F078xx || STM32F070xB || */ /* STM32F091xC || STM32F098xx || STM32F030xC */ #if defined(STM32F051x8) || defined(STM32F058xx)\ || defined(STM32F071xB) || defined(STM32F072xB) || defined(STM32F078xx)\ || defined(STM32F091xC) || defined(STM32F098xx) #define __HAL_RCC_DAC1_CLK_ENABLE() do { \ __IO uint32_t tmpreg; \ SET_BIT(RCC->APB1ENR, RCC_APB1ENR_DACEN);\ /* Delay after an RCC peripheral clock enabling */ \ tmpreg = READ_BIT(RCC->APB1ENR, RCC_APB1ENR_DACEN);\ UNUSED(tmpreg); \ } while(0) #define __HAL_RCC_DAC1_CLK_DISABLE() (RCC->APB1ENR &= ~(RCC_APB1ENR_DACEN)) #endif /* STM32F051x8 || STM32F058xx || */ /* STM32F071xB || STM32F072xB || STM32F078xx || */ /* STM32F091xC || STM32F098xx */ #if defined(STM32F042x6) || defined(STM32F048xx)\ || defined(STM32F051x8) || defined(STM32F058xx)\ || defined(STM32F071xB) || defined(STM32F072xB) || defined(STM32F078xx)\ || defined(STM32F091xC) || defined(STM32F098xx) #define __HAL_RCC_CEC_CLK_ENABLE() do { \ __IO uint32_t tmpreg; \ SET_BIT(RCC->APB1ENR, RCC_APB1ENR_CECEN);\ /* Delay after an RCC peripheral clock enabling */ \ tmpreg = READ_BIT(RCC->APB1ENR, RCC_APB1ENR_CECEN);\ UNUSED(tmpreg); \ } while(0) #define __HAL_RCC_CEC_CLK_DISABLE() (RCC->APB1ENR &= ~(RCC_APB1ENR_CECEN)) #endif /* STM32F042x6 || STM32F048xx || */ /* STM32F051x8 || STM32F058xx || */ /* STM32F071xB || STM32F072xB || STM32F078xx || */ /* STM32F091xC || STM32F098xx */ #if defined(STM32F071xB) || defined(STM32F072xB) || defined(STM32F078xx) || defined(STM32F070xB)\ || defined(STM32F091xC) || defined(STM32F098xx) || defined(STM32F030xC) #define __HAL_RCC_TIM7_CLK_ENABLE() do { \ __IO uint32_t tmpreg; \ SET_BIT(RCC->APB1ENR, RCC_APB1ENR_TIM7EN);\ /* Delay after an RCC peripheral clock enabling */ \ tmpreg = READ_BIT(RCC->APB1ENR, RCC_APB1ENR_TIM7EN);\ UNUSED(tmpreg); \ } while(0) #define __HAL_RCC_USART3_CLK_ENABLE() do { \ __IO uint32_t tmpreg; \ SET_BIT(RCC->APB1ENR, RCC_APB1ENR_USART3EN);\ /* Delay after an RCC peripheral clock enabling */ \ tmpreg = READ_BIT(RCC->APB1ENR, RCC_APB1ENR_USART3EN);\ UNUSED(tmpreg); \ } while(0) #define __HAL_RCC_USART4_CLK_ENABLE() do { \ __IO uint32_t tmpreg; \ SET_BIT(RCC->APB1ENR, RCC_APB1ENR_USART4EN);\ /* Delay after an RCC peripheral clock enabling */ \ tmpreg = READ_BIT(RCC->APB1ENR, RCC_APB1ENR_USART4EN);\ UNUSED(tmpreg); \ } while(0) #define __HAL_RCC_TIM7_CLK_DISABLE() (RCC->APB1ENR &= ~(RCC_APB1ENR_TIM7EN)) #define __HAL_RCC_USART3_CLK_DISABLE() (RCC->APB1ENR &= ~(RCC_APB1ENR_USART3EN)) #define __HAL_RCC_USART4_CLK_DISABLE() (RCC->APB1ENR &= ~(RCC_APB1ENR_USART4EN)) #endif /* STM32F071xB || STM32F072xB || STM32F078xx || STM32F070xB || */ /* STM32F091xC || STM32F098xx || STM32F030xC */ #if defined(STM32F042x6) || defined(STM32F048xx) || defined(STM32F070x6)\ || defined(STM32F072xB) || defined(STM32F078xx) || defined(STM32F070xB) #define __HAL_RCC_USB_CLK_ENABLE() do { \ __IO uint32_t tmpreg; \ SET_BIT(RCC->APB1ENR, RCC_APB1ENR_USBEN);\ /* Delay after an RCC peripheral clock enabling */ \ tmpreg = READ_BIT(RCC->APB1ENR, RCC_APB1ENR_USBEN);\ UNUSED(tmpreg); \ } while(0) #define __HAL_RCC_USB_CLK_DISABLE() (RCC->APB1ENR &= ~(RCC_APB1ENR_USBEN)) #endif /* STM32F042x6 || STM32F048xx || STM32F070x6 || */ /* STM32F072xB || STM32F078xx || STM32F070xB */ #if defined(STM32F042x6) || defined(STM32F048xx) || defined(STM32F072xB)\ || defined(STM32F091xC) || defined(STM32F098xx) #define __HAL_RCC_CAN1_CLK_ENABLE() do { \ __IO uint32_t tmpreg; \ SET_BIT(RCC->APB1ENR, RCC_APB1ENR_CANEN);\ /* Delay after an RCC peripheral clock enabling */ \ tmpreg = READ_BIT(RCC->APB1ENR, RCC_APB1ENR_CANEN);\ UNUSED(tmpreg); \ } while(0) #define __HAL_RCC_CAN1_CLK_DISABLE() (RCC->APB1ENR &= ~(RCC_APB1ENR_CANEN)) #endif /* STM32F042x6 || STM32F048xx || STM32F072xB || */ /* STM32F091xC || STM32F098xx */ #if defined(STM32F042x6) || defined(STM32F048xx)\ || defined(STM32F071xB) || defined(STM32F072xB) || defined(STM32F078xx)\ || defined(STM32F091xC) || defined(STM32F098xx) #define __HAL_RCC_CRS_CLK_ENABLE() do { \ __IO uint32_t tmpreg; \ SET_BIT(RCC->APB1ENR, RCC_APB1ENR_CRSEN);\ /* Delay after an RCC peripheral clock enabling */ \ tmpreg = READ_BIT(RCC->APB1ENR, RCC_APB1ENR_CRSEN);\ UNUSED(tmpreg); \ } while(0) #define __HAL_RCC_CRS_CLK_DISABLE() (RCC->APB1ENR &= ~(RCC_APB1ENR_CRSEN)) #endif /* STM32F042x6 || STM32F048xx || */ /* STM32F071xB || STM32F072xB || STM32F078xx || */ /* STM32F091xC || STM32F098xx */ #if defined(STM32F091xC) || defined(STM32F098xx) || defined(STM32F030xC) #define __HAL_RCC_USART5_CLK_ENABLE() do { \ __IO uint32_t tmpreg; \ SET_BIT(RCC->APB1ENR, RCC_APB1ENR_USART5EN);\ /* Delay after an RCC peripheral clock enabling */ \ tmpreg = READ_BIT(RCC->APB1ENR, RCC_APB1ENR_USART5EN);\ UNUSED(tmpreg); \ } while(0) #define __HAL_RCC_USART5_CLK_DISABLE() (RCC->APB1ENR &= ~(RCC_APB1ENR_USART5EN)) #endif /* STM32F091xC || STM32F098xx || STM32F030xC */ /** @brief Enable or disable the High Speed APB (APB2) peripheral clock. * @note After reset, the peripheral clock (used for registers read/write access) * is disabled and the application software has to enable this clock before * using it. */ #if defined(STM32F030x8) || defined(STM32F042x6) || defined(STM32F048xx) || defined(STM32F070x6)\ || defined(STM32F051x8) || defined(STM32F058xx)\ || defined(STM32F071xB) || defined(STM32F072xB) || defined(STM32F078xx) || defined(STM32F070xB)\ || defined(STM32F091xC) || defined(STM32F098xx) || defined(STM32F030xC) #define __HAL_RCC_TIM15_CLK_ENABLE() do { \ __IO uint32_t tmpreg; \ SET_BIT(RCC->APB2ENR, RCC_APB2ENR_TIM15EN);\ /* Delay after an RCC peripheral clock enabling */ \ tmpreg = READ_BIT(RCC->APB2ENR, RCC_APB2ENR_TIM15EN);\ UNUSED(tmpreg); \ } while(0) #define __HAL_RCC_TIM15_CLK_DISABLE() (RCC->APB2ENR &= ~(RCC_APB2ENR_TIM15EN)) #endif /* STM32F030x8 || STM32F042x6 || STM32F048xx || STM32F070x6 || */ /* STM32F051x8 || STM32F058xx || */ /* STM32F071xB || STM32F072xB || STM32F078xx || STM32F070xB || */ /* STM32F091xC || STM32F098xx || STM32F030xC */ #if defined(STM32F091xC) || defined(STM32F098xx) || defined(STM32F030xC) #define __HAL_RCC_USART6_CLK_ENABLE() do { \ __IO uint32_t tmpreg; \ SET_BIT(RCC->APB2ENR, RCC_APB2ENR_USART6EN);\ /* Delay after an RCC peripheral clock enabling */ \ tmpreg = READ_BIT(RCC->APB2ENR, RCC_APB2ENR_USART6EN);\ UNUSED(tmpreg); \ } while(0) #define __HAL_RCC_USART6_CLK_DISABLE() (RCC->APB2ENR &= ~(RCC_APB2ENR_USART6EN)) #endif /* STM32F091xC || STM32F098xx || STM32F030xC */ #if defined(STM32F091xC) || defined(STM32F098xx) #define __HAL_RCC_USART7_CLK_ENABLE() do { \ __IO uint32_t tmpreg; \ SET_BIT(RCC->APB2ENR, RCC_APB2ENR_USART7EN);\ /* Delay after an RCC peripheral clock enabling */ \ tmpreg = READ_BIT(RCC->APB2ENR, RCC_APB2ENR_USART7EN);\ UNUSED(tmpreg); \ } while(0) #define __HAL_RCC_USART8_CLK_ENABLE() do { \ __IO uint32_t tmpreg; \ SET_BIT(RCC->APB2ENR, RCC_APB2ENR_USART8EN);\ /* Delay after an RCC peripheral clock enabling */ \ tmpreg = READ_BIT(RCC->APB2ENR, RCC_APB2ENR_USART8EN);\ UNUSED(tmpreg); \ } while(0) #define __HAL_RCC_USART7_CLK_DISABLE() (RCC->APB2ENR &= ~(RCC_APB2ENR_USART7EN)) #define __HAL_RCC_USART8_CLK_DISABLE() (RCC->APB2ENR &= ~(RCC_APB2ENR_USART8EN)) #endif /* STM32F091xC || STM32F098xx */ /** * @} */ /** @defgroup RCCEx_Force_Release_Peripheral_Reset RCCEx Force Release Peripheral Reset * @brief Forces or releases peripheral reset. * @{ */ /** @brief Force or release AHB peripheral reset. */ #if defined(STM32F030x6) || defined(STM32F030x8)\ || defined(STM32F051x8) || defined(STM32F058xx)\ || defined(STM32F071xB) || defined(STM32F072xB) || defined(STM32F078xx) || defined(STM32F070xB)\ || defined(STM32F091xC) || defined(STM32F098xx) || defined(STM32F030xC) #define __HAL_RCC_GPIOD_FORCE_RESET() (RCC->AHBRSTR |= (RCC_AHBRSTR_GPIODRST)) #define __HAL_RCC_GPIOD_RELEASE_RESET() (RCC->AHBRSTR &= ~(RCC_AHBRSTR_GPIODRST)) #endif /* STM32F030x6 || STM32F030x8 || */ /* STM32F051x8 || STM32F058xx || */ /* STM32F071xB || STM32F072xB || STM32F078xx || STM32F070xB || */ /* STM32F091xC || STM32F098xx || STM32F030xC */ #if defined(STM32F071xB) || defined(STM32F072xB) || defined(STM32F078xx) || defined(STM32F070xB)\ || defined(STM32F091xC) || defined(STM32F098xx) || defined(STM32F030xC) #define __HAL_RCC_GPIOE_FORCE_RESET() (RCC->AHBRSTR |= (RCC_AHBRSTR_GPIOERST)) #define __HAL_RCC_GPIOE_RELEASE_RESET() (RCC->AHBRSTR &= ~(RCC_AHBRSTR_GPIOERST)) #endif /* STM32F071xB || STM32F072xB || STM32F078xx || STM32F070xB || */ /* STM32F091xC || STM32F098xx || STM32F030xC */ #if defined(STM32F042x6) || defined(STM32F048xx)\ || defined(STM32F051x8) || defined(STM32F058xx)\ || defined(STM32F071xB) || defined(STM32F072xB) || defined(STM32F078xx)\ || defined(STM32F091xC) || defined(STM32F098xx) #define __HAL_RCC_TSC_FORCE_RESET() (RCC->AHBRSTR |= (RCC_AHBRSTR_TSCRST)) #define __HAL_RCC_TSC_RELEASE_RESET() (RCC->AHBRSTR &= ~(RCC_AHBRSTR_TSCRST)) #endif /* STM32F042x6 || STM32F048xx || */ /* STM32F051x8 || STM32F058xx || */ /* STM32F071xB || STM32F072xB || STM32F078xx || */ /* STM32F091xC || STM32F098xx */ /** @brief Force or release APB1 peripheral reset. */ #if defined(STM32F030x8) \ || defined(STM32F042x6) || defined(STM32F048xx) || defined(STM32F070x6)\ || defined(STM32F051x8) || defined(STM32F058xx)\ || defined(STM32F071xB) || defined(STM32F072xB) || defined(STM32F078xx) || defined(STM32F070xB)\ || defined(STM32F091xC) || defined(STM32F098xx) || defined(STM32F030xC) #define __HAL_RCC_USART2_FORCE_RESET() (RCC->APB1RSTR |= (RCC_APB1RSTR_USART2RST)) #define __HAL_RCC_SPI2_FORCE_RESET() (RCC->APB1RSTR |= (RCC_APB1RSTR_SPI2RST)) #define __HAL_RCC_USART2_RELEASE_RESET() (RCC->APB1RSTR &= ~(RCC_APB1RSTR_USART2RST)) #define __HAL_RCC_SPI2_RELEASE_RESET() (RCC->APB1RSTR &= ~(RCC_APB1RSTR_SPI2RST)) #endif /* STM32F030x8 || STM32F042x6 || STM32F048xx || STM32F070x6 || */ /* STM32F051x8 || STM32F058xx || */ /* STM32F071xB || STM32F072xB || STM32F078xx || STM32F070xB || */ /* STM32F091xC || STM32F098xx || STM32F030xC */ #if defined(STM32F031x6) || defined(STM32F038xx)\ || defined(STM32F042x6) || defined(STM32F048xx)\ || defined(STM32F051x8) || defined(STM32F058xx)\ || defined(STM32F071xB) || defined(STM32F072xB) || defined(STM32F078xx)\ || defined(STM32F091xC) || defined(STM32F098xx) #define __HAL_RCC_TIM2_FORCE_RESET() (RCC->APB1RSTR |= (RCC_APB1RSTR_TIM2RST)) #define __HAL_RCC_TIM2_RELEASE_RESET() (RCC->APB1RSTR &= ~(RCC_APB1RSTR_TIM2RST)) #endif /* STM32F031x6 || STM32F038xx || */ /* STM32F042x6 || STM32F048xx || */ /* STM32F051x8 || STM32F058xx || */ /* STM32F071xB || STM32F072xB || STM32F078xx || */ /* STM32F091xC || STM32F098xx */ #if defined(STM32F030x8) \ || defined(STM32F051x8) || defined(STM32F058xx)\ || defined(STM32F071xB) || defined(STM32F072xB) || defined(STM32F078xx) || defined(STM32F070xB)\ || defined(STM32F091xC) || defined(STM32F098xx) || defined(STM32F030xC) #define __HAL_RCC_TIM6_FORCE_RESET() (RCC->APB1RSTR |= (RCC_APB1RSTR_TIM6RST)) #define __HAL_RCC_I2C2_FORCE_RESET() (RCC->APB1RSTR |= (RCC_APB1RSTR_I2C2RST)) #define __HAL_RCC_TIM6_RELEASE_RESET() (RCC->APB1RSTR &= ~(RCC_APB1RSTR_TIM6RST)) #define __HAL_RCC_I2C2_RELEASE_RESET() (RCC->APB1RSTR &= ~(RCC_APB1RSTR_I2C2RST)) #endif /* STM32F030x8 || */ /* STM32F051x8 || STM32F058xx || */ /* STM32F071xB || STM32F072xB || STM32F078xx || STM32F070xB || */ /* STM32F091xC || STM32F098xx || STM32F030xC */ #if defined(STM32F051x8) || defined(STM32F058xx)\ || defined(STM32F071xB) || defined(STM32F072xB) || defined(STM32F078xx)\ || defined(STM32F091xC) || defined(STM32F098xx) #define __HAL_RCC_DAC1_FORCE_RESET() (RCC->APB1RSTR |= (RCC_APB1RSTR_DACRST)) #define __HAL_RCC_DAC1_RELEASE_RESET() (RCC->APB1RSTR &= ~(RCC_APB1RSTR_DACRST)) #endif /* STM32F051x8 || STM32F058xx || */ /* STM32F071xB || STM32F072xB || STM32F078xx || */ /* STM32F091xC || STM32F098xx */ #if defined(STM32F042x6) || defined(STM32F048xx)\ || defined(STM32F051x8) || defined(STM32F058xx)\ || defined(STM32F071xB) || defined(STM32F072xB) || defined(STM32F078xx)\ || defined(STM32F091xC) || defined(STM32F098xx) #define __HAL_RCC_CEC_FORCE_RESET() (RCC->APB1RSTR |= (RCC_APB1RSTR_CECRST)) #define __HAL_RCC_CEC_RELEASE_RESET() (RCC->APB1RSTR &= ~(RCC_APB1RSTR_CECRST)) #endif /* STM32F042x6 || STM32F048xx || */ /* STM32F051x8 || STM32F058xx || */ /* STM32F071xB || STM32F072xB || STM32F078xx || */ /* STM32F091xC || STM32F098xx */ #if defined(STM32F071xB) || defined(STM32F072xB) || defined(STM32F078xx) || defined(STM32F070xB)\ || defined(STM32F091xC) || defined(STM32F098xx) || defined(STM32F030xC) #define __HAL_RCC_TIM7_FORCE_RESET() (RCC->APB1RSTR |= (RCC_APB1RSTR_TIM7RST)) #define __HAL_RCC_USART3_FORCE_RESET() (RCC->APB1RSTR |= (RCC_APB1RSTR_USART3RST)) #define __HAL_RCC_USART4_FORCE_RESET() (RCC->APB1RSTR |= (RCC_APB1RSTR_USART4RST)) #define __HAL_RCC_TIM7_RELEASE_RESET() (RCC->APB1RSTR &= ~(RCC_APB1RSTR_TIM7RST)) #define __HAL_RCC_USART3_RELEASE_RESET() (RCC->APB1RSTR &= ~(RCC_APB1RSTR_USART3RST)) #define __HAL_RCC_USART4_RELEASE_RESET() (RCC->APB1RSTR &= ~(RCC_APB1RSTR_USART4RST)) #endif /* STM32F071xB || STM32F072xB || STM32F078xx || STM32F070xB || */ /* STM32F091xC || STM32F098xx || STM32F030xC */ #if defined(STM32F042x6) || defined(STM32F048xx) || defined(STM32F070x6)\ || defined(STM32F072xB) || defined(STM32F078xx) || defined(STM32F070xB) #define __HAL_RCC_USB_FORCE_RESET() (RCC->APB1RSTR |= (RCC_APB1RSTR_USBRST)) #define __HAL_RCC_USB_RELEASE_RESET() (RCC->APB1RSTR &= ~(RCC_APB1RSTR_USBRST)) #endif /* STM32F042x6 || STM32F048xx || STM32F070x6 || */ /* STM32F072xB || STM32F078xx || STM32F070xB */ #if defined(STM32F042x6) || defined(STM32F048xx) || defined(STM32F072xB)\ || defined(STM32F091xC) || defined(STM32F098xx) #define __HAL_RCC_CAN1_FORCE_RESET() (RCC->APB1RSTR |= (RCC_APB1RSTR_CANRST)) #define __HAL_RCC_CAN1_RELEASE_RESET() (RCC->APB1RSTR &= ~(RCC_APB1RSTR_CANRST)) #endif /* STM32F042x6 || STM32F048xx || STM32F072xB || */ /* STM32F091xC || STM32F098xx */ #if defined(STM32F042x6) || defined(STM32F048xx)\ || defined(STM32F071xB) || defined(STM32F072xB) || defined(STM32F078xx)\ || defined(STM32F091xC) || defined(STM32F098xx) #define __HAL_RCC_CRS_FORCE_RESET() (RCC->APB1RSTR |= (RCC_APB1RSTR_CRSRST)) #define __HAL_RCC_CRS_RELEASE_RESET() (RCC->APB1RSTR &= ~(RCC_APB1RSTR_CRSRST)) #endif /* STM32F042x6 || STM32F048xx || */ /* STM32F071xB || STM32F072xB || STM32F078xx || */ /* STM32F091xC || STM32F098xx */ #if defined(STM32F091xC) || defined(STM32F098xx) || defined(STM32F030xC) #define __HAL_RCC_USART5_FORCE_RESET() (RCC->APB1RSTR |= (RCC_APB1RSTR_USART5RST)) #define __HAL_RCC_USART5_RELEASE_RESET() (RCC->APB1RSTR &= ~(RCC_APB1RSTR_USART5RST)) #endif /* STM32F091xC || STM32F098xx || STM32F030xC */ /** @brief Force or release APB2 peripheral reset. */ #if defined(STM32F030x8) || defined(STM32F042x6) || defined(STM32F048xx) || defined(STM32F070x6)\ || defined(STM32F051x8) || defined(STM32F058xx)\ || defined(STM32F071xB) || defined(STM32F072xB) || defined(STM32F078xx) || defined(STM32F070xB)\ || defined(STM32F091xC) || defined(STM32F098xx) || defined(STM32F030xC) #define __HAL_RCC_TIM15_FORCE_RESET() (RCC->APB2RSTR |= (RCC_APB2RSTR_TIM15RST)) #define __HAL_RCC_TIM15_RELEASE_RESET() (RCC->APB2RSTR &= ~(RCC_APB2RSTR_TIM15RST)) #endif /* STM32F030x8 || STM32F042x6 || STM32F048xx || STM32F070x6 || */ /* STM32F051x8 || STM32F058xx || */ /* STM32F071xB || STM32F072xB || STM32F078xx || STM32F070xB || */ /* STM32F091xC || STM32F098xx || STM32F030xC */ #if defined(STM32F091xC) || defined(STM32F098xx) || defined(STM32F030xC) #define __HAL_RCC_USART6_FORCE_RESET() (RCC->APB2RSTR |= (RCC_APB2RSTR_USART6RST)) #define __HAL_RCC_USART6_RELEASE_RESET() (RCC->APB2RSTR &= ~(RCC_APB2RSTR_USART6RST)) #endif /* STM32F091xC || STM32F098xx || STM32F030xC */ #if defined(STM32F091xC) || defined(STM32F098xx) #define __HAL_RCC_USART7_FORCE_RESET() (RCC->APB2RSTR |= (RCC_APB2RSTR_USART7RST)) #define __HAL_RCC_USART8_FORCE_RESET() (RCC->APB2RSTR |= (RCC_APB2RSTR_USART8RST)) #define __HAL_RCC_USART7_RELEASE_RESET() (RCC->APB2RSTR &= ~(RCC_APB2RSTR_USART7RST)) #define __HAL_RCC_USART8_RELEASE_RESET() (RCC->APB2RSTR &= ~(RCC_APB2RSTR_USART8RST)) #endif /* STM32F091xC || STM32F098xx */ /** * @} */ /** @defgroup RCCEx_Peripheral_Clock_Enable_Disable_Status Peripheral Clock Enable Disable Status * @brief Get the enable or disable status of peripheral clock. * @note After reset, the peripheral clock (used for registers read/write access) * is disabled and the application software has to enable this clock before * using it. * @{ */ /** @brief AHB Peripheral Clock Enable Disable Status */ #if defined(STM32F030x6) || defined(STM32F030x8)\ || defined(STM32F051x8) || defined(STM32F058xx) || defined(STM32F070xB)\ || defined(STM32F071xB) || defined(STM32F072xB) || defined(STM32F078xx)\ || defined(STM32F091xC) || defined(STM32F098xx) || defined(STM32F030xC) #define __HAL_RCC_GPIOD_IS_CLK_ENABLED() ((RCC->AHBENR & (RCC_AHBENR_GPIODEN)) != RESET) #define __HAL_RCC_GPIOD_IS_CLK_DISABLED() ((RCC->AHBENR & (RCC_AHBENR_GPIODEN)) == RESET) #endif /* STM32F030x6 || STM32F030x8 || */ /* STM32F051x8 || STM32F058xx || STM32F070xB || */ /* STM32F071xB || STM32F072xB || STM32F078xx || */ /* STM32F091xC || STM32F098xx || STM32F030xC */ #if defined(STM32F071xB) || defined(STM32F072xB) || defined(STM32F078xx) || defined(STM32F070xB)\ || defined(STM32F091xC) || defined(STM32F098xx) || defined(STM32F030xC) #define __HAL_RCC_GPIOE_IS_CLK_ENABLED() ((RCC->AHBENR & (RCC_AHBENR_GPIOEEN)) != RESET) #define __HAL_RCC_GPIOE_IS_CLK_DISABLED() ((RCC->AHBENR & (RCC_AHBENR_GPIOEEN)) == RESET) #endif /* STM32F071xB || STM32F072xB || STM32F078xx || STM32F070xB || */ /* STM32F091xC || STM32F098xx || STM32F030xC */ #if defined(STM32F042x6) || defined(STM32F048xx)\ || defined(STM32F051x8) || defined(STM32F058xx)\ || defined(STM32F071xB) || defined(STM32F072xB) || defined(STM32F078xx)\ || defined(STM32F091xC) || defined(STM32F098xx) #define __HAL_RCC_TSC_IS_CLK_ENABLED() ((RCC->AHBENR & (RCC_AHBENR_TSCEN)) != RESET) #define __HAL_RCC_TSC_IS_CLK_DISABLED() ((RCC->AHBENR & (RCC_AHBENR_TSCEN)) == RESET) #endif /* STM32F042x6 || STM32F048xx || */ /* STM32F051x8 || STM32F058xx || */ /* STM32F071xB || STM32F072xB || STM32F078xx || */ /* STM32F091xC || STM32F098xx */ #if defined(STM32F091xC) || defined(STM32F098xx) #define __HAL_RCC_DMA2_IS_CLK_ENABLED() ((RCC->AHBENR & (RCC_AHBENR_DMA2EN)) != RESET) #define __HAL_RCC_DMA2_IS_CLK_DISABLED() ((RCC->AHBENR & (RCC_AHBENR_DMA2EN)) == RESET) #endif /* STM32F091xC || STM32F098xx */ /** @brief APB1 Peripheral Clock Enable Disable Status */ #if defined(STM32F030x8)\ || defined(STM32F042x6) || defined(STM32F048xx) || defined(STM32F070x6)\ || defined(STM32F051x8) || defined(STM32F058xx)\ || defined(STM32F071xB) || defined(STM32F072xB) || defined(STM32F078xx) || defined(STM32F070xB)\ || defined(STM32F091xC) || defined(STM32F098xx) || defined(STM32F030xC) #define __HAL_RCC_USART2_IS_CLK_ENABLED() ((RCC->APB1ENR & (RCC_APB1ENR_USART2EN)) != RESET) #define __HAL_RCC_USART2_IS_CLK_DISABLED() ((RCC->APB1ENR & (RCC_APB1ENR_USART2EN)) == RESET) #endif /* STM32F030x8 || STM32F042x6 || STM32F048xx || */ /* STM32F051x8 || STM32F058xx || STM32F070x6 || */ /* STM32F071xB || STM32F072xB || STM32F078xx || STM32F070xB || */ /* STM32F091xC || STM32F098xx || STM32F030xC */ #if defined(STM32F030x8)\ || defined(STM32F042x6) || defined(STM32F048xx)\ || defined(STM32F051x8) || defined(STM32F058xx)\ || defined(STM32F071xB) || defined(STM32F072xB) || defined(STM32F078xx) || defined(STM32F070xB)\ || defined(STM32F091xC) || defined(STM32F098xx) || defined(STM32F030xC) #define __HAL_RCC_SPI2_IS_CLK_ENABLED() ((RCC->APB1ENR & (RCC_APB1ENR_SPI2EN)) != RESET) #define __HAL_RCC_SPI2_IS_CLK_DISABLED() ((RCC->APB1ENR & (RCC_APB1ENR_SPI2EN)) == RESET) #endif /* STM32F030x8 || STM32F042x6 || STM32F048xx || */ /* STM32F051x8 || STM32F058xx || */ /* STM32F071xB || STM32F072xB || STM32F078xx || STM32F070xB || */ /* STM32F091xC || STM32F098xx || STM32F030xC */ #if defined(STM32F031x6) || defined(STM32F038xx)\ || defined(STM32F042x6) || defined(STM32F048xx)\ || defined(STM32F051x8) || defined(STM32F058xx)\ || defined(STM32F071xB) || defined(STM32F072xB) || defined(STM32F078xx)\ || defined(STM32F091xC) || defined(STM32F098xx) #define __HAL_RCC_TIM2_IS_CLK_ENABLED() ((RCC->APB1ENR & (RCC_APB1ENR_TIM2EN)) != RESET) #define __HAL_RCC_TIM2_IS_CLK_DISABLED() ((RCC->APB1ENR & (RCC_APB1ENR_TIM2EN)) == RESET) #endif /* STM32F031x6 || STM32F038xx || */ /* STM32F042x6 || STM32F048xx || */ /* STM32F051x8 || STM32F058xx || */ /* STM32F071xB || STM32F072xB || STM32F078xx || */ /* STM32F091xC || STM32F098xx */ #if defined(STM32F030x8) \ || defined(STM32F051x8) || defined(STM32F058xx)\ || defined(STM32F071xB) || defined(STM32F072xB) || defined(STM32F078xx) || defined(STM32F070xB)\ || defined(STM32F091xC) || defined(STM32F098xx) || defined(STM32F030xC) #define __HAL_RCC_TIM6_IS_CLK_ENABLED() ((RCC->APB1ENR & (RCC_APB1ENR_TIM6EN)) != RESET) #define __HAL_RCC_I2C2_IS_CLK_ENABLED() ((RCC->APB1ENR & (RCC_APB1ENR_I2C2EN)) != RESET) #define __HAL_RCC_TIM6_IS_CLK_DISABLED() ((RCC->APB1ENR & (RCC_APB1ENR_TIM6EN)) == RESET) #define __HAL_RCC_I2C2_IS_CLK_DISABLED() ((RCC->APB1ENR & (RCC_APB1ENR_I2C2EN)) == RESET) #endif /* STM32F030x8 || */ /* STM32F051x8 || STM32F058xx || */ /* STM32F071xB || STM32F072xB || STM32F078xx || STM32F070xB || */ /* STM32F091xC || STM32F098xx || STM32F030xC */ #if defined(STM32F051x8) || defined(STM32F058xx)\ || defined(STM32F071xB) || defined(STM32F072xB) || defined(STM32F078xx)\ || defined(STM32F091xC) || defined(STM32F098xx) #define __HAL_RCC_DAC1_IS_CLK_ENABLED() ((RCC->APB1ENR & (RCC_APB1ENR_DAC1EN)) != RESET) #define __HAL_RCC_DAC1_IS_CLK_DISABLED() ((RCC->APB1ENR & (RCC_APB1ENR_DAC1EN)) == RESET) #endif /* STM32F051x8 || STM32F058xx || */ /* STM32F071xB || STM32F072xB || STM32F078xx || */ /* STM32F091xC || STM32F098xx */ #if defined(STM32F042x6) || defined(STM32F048xx)\ || defined(STM32F051x8) || defined(STM32F058xx)\ || defined(STM32F071xB) || defined(STM32F072xB) || defined(STM32F078xx)\ || defined(STM32F091xC) || defined(STM32F098xx) #define __HAL_RCC_CEC_IS_CLK_ENABLED() ((RCC->APB1ENR & (RCC_APB1ENR_CECEN)) != RESET) #define __HAL_RCC_CEC_IS_CLK_DISABLED() ((RCC->APB1ENR & (RCC_APB1ENR_CECEN)) == RESET) #endif /* STM32F042x6 || STM32F048xx || */ /* STM32F051x8 || STM32F058xx || */ /* STM32F071xB || STM32F072xB || STM32F078xx || */ /* STM32F091xC || STM32F098xx */ #if defined(STM32F071xB) || defined(STM32F072xB) || defined(STM32F078xx) || defined(STM32F070xB)\ || defined(STM32F091xC) || defined(STM32F098xx) || defined(STM32F030xC) #define __HAL_RCC_TIM7_IS_CLK_ENABLED() ((RCC->APB1ENR & (RCC_APB1ENR_TIM7EN)) != RESET) #define __HAL_RCC_USART3_IS_CLK_ENABLED() ((RCC->APB1ENR & (RCC_APB1ENR_USART3EN)) != RESET) #define __HAL_RCC_USART4_IS_CLK_ENABLED() ((RCC->APB1ENR & (RCC_APB1ENR_USART4EN)) != RESET) #define __HAL_RCC_TIM7_IS_CLK_DISABLED() ((RCC->APB1ENR & (RCC_APB1ENR_TIM7EN)) == RESET) #define __HAL_RCC_USART3_IS_CLK_DISABLED() ((RCC->APB1ENR & (RCC_APB1ENR_USART3EN)) == RESET) #define __HAL_RCC_USART4_IS_CLK_DISABLED() ((RCC->APB1ENR & (RCC_APB1ENR_USART4EN)) == RESET) #endif /* STM32F071xB || STM32F072xB || STM32F078xx || STM32F070xB || */ /* STM32F091xC || STM32F098xx || STM32F030xC */ #if defined(STM32F042x6) || defined(STM32F048xx) || defined(STM32F070x6)\ || defined(STM32F072xB) || defined(STM32F078xx) || defined(STM32F070xB) #define __HAL_RCC_USB_IS_CLK_ENABLED() ((RCC->APB1ENR & (RCC_APB1ENR_USBEN)) != RESET) #define __HAL_RCC_USB_IS_CLK_DISABLED() ((RCC->APB1ENR & (RCC_APB1ENR_USBEN)) == RESET) #endif /* STM32F042x6 || STM32F048xx || STM32F070x6 || */ /* STM32F072xB || STM32F078xx || STM32F070xB */ #if defined(STM32F042x6) || defined(STM32F048xx) || defined(STM32F072xB)\ || defined(STM32F091xC) || defined(STM32F098xx) #define __HAL_RCC_CAN1_IS_CLK_ENABLED() ((RCC->APB1ENR & (RCC_APB1ENR_CAN1EN)) != RESET) #define __HAL_RCC_CAN1_IS_CLK_DISABLED() ((RCC->APB1ENR & (RCC_APB1ENR_CAN1EN)) == RESET) #endif /* STM32F042x6 || STM32F048xx || STM32F072xB || */ /* STM32F091xC || STM32F098xx */ #if defined(STM32F042x6) || defined(STM32F048xx)\ || defined(STM32F071xB) || defined(STM32F072xB) || defined(STM32F078xx)\ || defined(STM32F091xC) || defined(STM32F098xx) #define __HAL_RCC_CRS_IS_CLK_ENABLED() ((RCC->APB1ENR & (RCC_APB1ENR_CRSEN)) != RESET) #define __HAL_RCC_CRS_IS_CLK_DISABLED() ((RCC->APB1ENR & (RCC_APB1ENR_CRSEN)) == RESET) #endif /* STM32F042x6 || STM32F048xx || */ /* STM32F071xB || STM32F072xB || STM32F078xx || */ /* STM32F091xC || STM32F098xx */ #if defined(STM32F091xC) || defined(STM32F098xx) || defined(STM32F030xC) #define __HAL_RCC_USART5_IS_CLK_ENABLED() ((RCC->APB1ENR & (RCC_APB1ENR_USART5EN)) != RESET) #define __HAL_RCC_USART5_IS_CLK_DISABLED() ((RCC->APB1ENR & (RCC_APB1ENR_USART5EN)) == RESET) #endif /* STM32F091xC || STM32F098xx || STM32F030xC */ /** @brief APB1 Peripheral Clock Enable Disable Status */ #if defined(STM32F030x8) || defined(STM32F042x6) || defined(STM32F048xx) || defined(STM32F070x6)\ || defined(STM32F051x8) || defined(STM32F058xx)\ || defined(STM32F071xB) || defined(STM32F072xB) || defined(STM32F078xx) || defined(STM32F070xB)\ || defined(STM32F091xC) || defined(STM32F098xx) || defined(STM32F030xC) #define __HAL_RCC_TIM15_IS_CLK_ENABLED() ((RCC->APB2ENR & (RCC_APB2ENR_TIM15EN)) != RESET) #define __HAL_RCC_TIM15_IS_CLK_DISABLED() ((RCC->APB2ENR & (RCC_APB2ENR_TIM15EN)) == RESET) #endif /* STM32F030x8 || STM32F042x6 || STM32F048xx || STM32F070x6 || */ /* STM32F051x8 || STM32F058xx || */ /* STM32F071xB || STM32F072xB || STM32F078xx || STM32F070xB || */ /* STM32F091xC || STM32F098xx || STM32F030xC */ #if defined(STM32F091xC) || defined(STM32F098xx) || defined(STM32F030xC) #define __HAL_RCC_USART6_IS_CLK_ENABLED() ((RCC->APB2ENR & (RCC_APB2ENR_USART6EN)) != RESET) #define __HAL_RCC_USART6_IS_CLK_DISABLED() ((RCC->APB2ENR & (RCC_APB2ENR_USART6EN)) == RESET) #endif /* STM32F091xC || STM32F098xx || STM32F030xC */ #if defined(STM32F091xC) || defined(STM32F098xx) #define __HAL_RCC_USART7_IS_CLK_ENABLED() ((RCC->APB2ENR & (RCC_APB2ENR_USART7EN)) != RESET) #define __HAL_RCC_USART8_IS_CLK_ENABLED() ((RCC->APB2ENR & (RCC_APB2ENR_USART8EN)) != RESET) #define __HAL_RCC_USART7_IS_CLK_DISABLED() ((RCC->APB2ENR & (RCC_APB2ENR_USART7EN)) == RESET) #define __HAL_RCC_USART8_IS_CLK_DISABLED() ((RCC->APB2ENR & (RCC_APB2ENR_USART8EN)) == RESET) #endif /* STM32F091xC || STM32F098xx */ /** * @} */ /** @defgroup RCCEx_HSI48_Enable_Disable RCCEx HSI48 Enable Disable * @brief Macros to enable or disable the Internal 48Mhz High Speed oscillator (HSI48). * @note The HSI48 is stopped by hardware when entering STOP and STANDBY modes. * @note HSI48 can not be stopped if it is used as system clock source. In this case, * you have to select another source of the system clock then stop the HSI14. * @note After enabling the HSI48 with __HAL_RCC_HSI48_ENABLE(), the application software * should wait on HSI48RDY flag to be set indicating that HSI48 clock is stable and can be * used as system clock source. This is not necessary if HAL_RCC_OscConfig() is used. * @note When the HSI48 is stopped, HSI48RDY flag goes low after 6 HSI48 oscillator * clock cycles. * @{ */ #if defined(STM32F042x6) || defined(STM32F048xx)\ || defined(STM32F071xB) || defined(STM32F072xB) || defined(STM32F078xx)\ || defined(STM32F091xC) || defined(STM32F098xx) #define __HAL_RCC_HSI48_ENABLE() SET_BIT(RCC->CR2, RCC_CR2_HSI48ON) #define __HAL_RCC_HSI48_DISABLE() CLEAR_BIT(RCC->CR2, RCC_CR2_HSI48ON) /** @brief Macro to get the Internal 48Mhz High Speed oscillator (HSI48) state. * @retval The clock source can be one of the following values: * @arg RCC_HSI48_ON: HSI48 enabled * @arg RCC_HSI48_OFF: HSI48 disabled */ #define __HAL_RCC_GET_HSI48_STATE() \ (((uint32_t)(READ_BIT(RCC->CFGR3, RCC_CR2_HSI48ON)) != RESET) ? RCC_HSI48_ON : RCC_HSI48_OFF) #else /** @brief Macro to get the Internal 48Mhz High Speed oscillator (HSI48) state. * @retval The clock source can be one of the following values: * @arg RCC_HSI_OFF: HSI48 disabled */ #define __HAL_RCC_GET_HSI48_STATE() RCC_HSI_OFF #endif /* STM32F042x6 || STM32F048xx || */ /* STM32F071xB || STM32F072xB || STM32F078xx || */ /* STM32F091xC || STM32F098xx */ /** * @} */ /** @defgroup RCCEx_Peripheral_Clock_Source_Config RCCEx Peripheral Clock Source Config * @{ */ #if defined(STM32F042x6) || defined(STM32F048xx)\ || defined(STM32F072xB) || defined(STM32F078xx)\ || defined(STM32F070x6) || defined(STM32F070xB) /** @brief Macro to configure the USB clock (USBCLK). * @param __USBCLKSource__: specifies the USB clock source. * This parameter can be one of the following values: * @arg RCC_USBCLKSOURCE_HSI48: HSI48 selected as USB clock (not available for STM32F070x6 & STM32F070xB) * @arg RCC_USBCLKSOURCE_PLLCLK: PLL Clock selected as USB clock */ #define __HAL_RCC_USB_CONFIG(__USBCLKSource__) \ MODIFY_REG(RCC->CFGR3, RCC_CFGR3_USBSW, (uint32_t)(__USBCLKSource__)) /** @brief Macro to get the USB clock source. * @retval The clock source can be one of the following values: * @arg RCC_USBCLKSOURCE_HSI48: HSI48 selected as USB clock * @arg RCC_USBCLKSOURCE_PLLCLK: PLL Clock selected as USB clock */ #define __HAL_RCC_GET_USB_SOURCE() ((uint32_t)(READ_BIT(RCC->CFGR3, RCC_CFGR3_USBSW))) #endif /* STM32F042x6 || STM32F048xx || */ /* STM32F072xB || STM32F078xx || */ /* STM32F070x6 || STM32F070xB */ #if defined(STM32F042x6) || defined(STM32F048xx)\ || defined(STM32F051x8) || defined(STM32F058xx)\ || defined(STM32F071xB) || defined(STM32F072xB) || defined(STM32F078xx)\ || defined(STM32F091xC) || defined(STM32F098xx) /** @brief Macro to configure the CEC clock. * @param __CECCLKSource__: specifies the CEC clock source. * This parameter can be one of the following values: * @arg RCC_CECCLKSOURCE_HSI: HSI selected as CEC clock * @arg RCC_CECCLKSOURCE_LSE: LSE selected as CEC clock */ #define __HAL_RCC_CEC_CONFIG(__CECCLKSource__) \ MODIFY_REG(RCC->CFGR3, RCC_CFGR3_CECSW, (uint32_t)(__CECCLKSource__)) /** @brief Macro to get the HDMI CEC clock source. * @retval The clock source can be one of the following values: * @arg RCC_CECCLKSOURCE_HSI: HSI selected as CEC clock * @arg RCC_CECCLKSOURCE_LSE: LSE selected as CEC clock */ #define __HAL_RCC_GET_CEC_SOURCE() ((uint32_t)(READ_BIT(RCC->CFGR3, RCC_CFGR3_CECSW))) #endif /* STM32F042x6 || STM32F048xx || */ /* STM32F051x8 || STM32F058xx || */ /* STM32F071xB || STM32F072xB || STM32F078xx || */ /* STM32F091xC || defined(STM32F098xx) */ #if defined(STM32F030x6) || defined(STM32F031x6) || defined(STM32F038xx)\ || defined(STM32F042x6) || defined(STM32F048xx) || defined(STM32F070x6)\ || defined(STM32F071xB) || defined(STM32F072xB) || defined(STM32F078xx) || defined(STM32F070xB)\ || defined(STM32F091xC) || defined(STM32F098xx) || defined(STM32F030xC) /** @brief Macro to configure the MCO clock. * @param __MCOCLKSource__: specifies the MCO clock source. * This parameter can be one of the following values: * @arg RCC_MCOSOURCE_HSI: HSI selected as MCO clock * @arg RCC_MCOSOURCE_HSE: HSE selected as MCO clock * @arg RCC_MCOSOURCE_LSI: LSI selected as MCO clock * @arg RCC_MCOSOURCE_LSE: LSE selected as MCO clock * @arg RCC_MCOSOURCE_PLLCLK_NODIV: PLLCLK selected as MCO clock * @arg RCC_MCOSOURCE_PLLCLK_DIV2: PLLCLK Divided by 2 selected as MCO clock * @arg RCC_MCOSOURCE_SYSCLK: System Clock selected as MCO clock * @arg RCC_MCOSOURCE_HSI14: HSI14 selected as MCO clock * @arg RCC_MCOSOURCE_HSI48: HSI48 selected as MCO clock * @param __MCODiv__: specifies the MCO clock prescaler. * This parameter can be one of the following values: * @arg RCC_MCO_DIV1: MCO clock source is divided by 1 * @arg RCC_MCO_DIV2: MCO clock source is divided by 2 * @arg RCC_MCO_DIV4: MCO clock source is divided by 4 * @arg RCC_MCO_DIV8: MCO clock source is divided by 8 * @arg RCC_MCO_DIV16: MCO clock source is divided by 16 * @arg RCC_MCO_DIV32: MCO clock source is divided by 32 * @arg RCC_MCO_DIV64: MCO clock source is divided by 64 * @arg RCC_MCO_DIV128: MCO clock source is divided by 128 */ #define __HAL_RCC_MCO_CONFIG(__MCOCLKSource__, __MCODiv__) \ MODIFY_REG(RCC->CFGR, (RCC_CFGR_MCO | RCC_CFGR_MCOPRE), ((__MCOCLKSource__) | (__MCODiv__))) #else /** @brief Macro to configure the MCO clock. * @param __MCOCLKSource__: specifies the MCO clock source. * This parameter can be one of the following values: * @arg RCC_MCOSOURCE_HSI: HSI selected as MCO clock * @arg RCC_MCOSOURCE_HSE: HSE selected as MCO clock * @arg RCC_MCOSOURCE_LSI: LSI selected as MCO clock * @arg RCC_MCOSOURCE_LSE: LSE selected as MCO clock * @arg RCC_MCOSOURCE_PLLCLK_DIV2: PLLCLK Divided by 2 selected as MCO clock * @arg RCC_MCOSOURCE_SYSCLK: System Clock selected as MCO clock * @arg RCC_MCOSOURCE_HSI14: HSI14 selected as MCO clock * @arg RCC_MCOSOURCE_HSI48: HSI48 selected as MCO clock * @param __MCODiv__: specifies the MCO clock prescaler. * This parameter can be one of the following values: * @arg RCC_MCODIV_1: No division applied on MCO clock source */ #define __HAL_RCC_MCO_CONFIG(__MCOCLKSource__, __MCODiv__) \ MODIFY_REG(RCC->CFGR, RCC_CFGR_MCO, __MCOCLKSource__) #endif /* STM32F030x6 || STM32F031x6 || STM32F038xx || STM32F070x6 || */ /* STM32F042x6 || STM32F048xx || */ /* STM32F071xB || STM32F072xB || STM32F078xx || STM32F070xB || */ /* STM32F091xC || STM32F098xx || STM32F030xC */ #if defined(STM32F071xB) || defined(STM32F072xB) || defined(STM32F078xx)\ || defined(STM32F091xC) || defined(STM32F098xx) /** @brief Macro to configure the USART2 clock (USART2CLK). * @param __USART2CLKSource__: specifies the USART2 clock source. * This parameter can be one of the following values: * @arg RCC_USART2CLKSOURCE_PCLK1: PCLK1 selected as USART2 clock * @arg RCC_USART2CLKSOURCE_HSI: HSI selected as USART2 clock * @arg RCC_USART2CLKSOURCE_SYSCLK: System Clock selected as USART2 clock * @arg RCC_USART2CLKSOURCE_LSE: LSE selected as USART2 clock */ #define __HAL_RCC_USART2_CONFIG(__USART2CLKSource__) \ MODIFY_REG(RCC->CFGR3, RCC_CFGR3_USART2SW, (uint32_t)(__USART2CLKSource__)) /** @brief Macro to get the USART2 clock source. * @retval The clock source can be one of the following values: * @arg RCC_USART2CLKSOURCE_PCLK1: PCLK1 selected as USART2 clock * @arg RCC_USART2CLKSOURCE_HSI: HSI selected as USART2 clock * @arg RCC_USART2CLKSOURCE_SYSCLK: System Clock selected as USART2 clock * @arg RCC_USART2CLKSOURCE_LSE: LSE selected as USART2 clock */ #define __HAL_RCC_GET_USART2_SOURCE() ((uint32_t)(READ_BIT(RCC->CFGR3, RCC_CFGR3_USART2SW))) #endif /* STM32F071xB || STM32F072xB || STM32F078xx || STM32F091xC || STM32F098xx*/ #if defined(STM32F091xC) || defined(STM32F098xx) /** @brief Macro to configure the USART3 clock (USART3CLK). * @param __USART3CLKSource__: specifies the USART3 clock source. * This parameter can be one of the following values: * @arg RCC_USART3CLKSOURCE_PCLK1: PCLK1 selected as USART3 clock * @arg RCC_USART3CLKSOURCE_HSI: HSI selected as USART3 clock * @arg RCC_USART3CLKSOURCE_SYSCLK: System Clock selected as USART3 clock * @arg RCC_USART3CLKSOURCE_LSE: LSE selected as USART3 clock */ #define __HAL_RCC_USART3_CONFIG(__USART3CLKSource__) \ MODIFY_REG(RCC->CFGR3, RCC_CFGR3_USART3SW, (uint32_t)(__USART3CLKSource__)) /** @brief Macro to get the USART3 clock source. * @retval The clock source can be one of the following values: * @arg RCC_USART3CLKSOURCE_PCLK1: PCLK1 selected as USART3 clock * @arg RCC_USART3CLKSOURCE_HSI: HSI selected as USART3 clock * @arg RCC_USART3CLKSOURCE_SYSCLK: System Clock selected as USART3 clock * @arg RCC_USART3CLKSOURCE_LSE: LSE selected as USART3 clock */ #define __HAL_RCC_GET_USART3_SOURCE() ((uint32_t)(READ_BIT(RCC->CFGR3, RCC_CFGR3_USART3SW))) #endif /* STM32F091xC || STM32F098xx */ /** * @} */ #if defined(STM32F042x6) || defined(STM32F048xx)\ || defined(STM32F071xB) || defined(STM32F072xB) || defined(STM32F078xx)\ || defined(STM32F091xC) || defined(STM32F098xx) /** @defgroup RCCEx_IT_And_Flag RCCEx IT and Flag * @{ */ /* Interrupt & Flag management */ /** * @brief Enables the specified CRS interrupts. * @param __INTERRUPT__: specifies the CRS interrupt sources to be enabled. * This parameter can be any combination of the following values: * @arg RCC_CRS_IT_SYNCOK * @arg RCC_CRS_IT_SYNCWARN * @arg RCC_CRS_IT_ERR * @arg RCC_CRS_IT_ESYNC * @retval None */ #define __HAL_RCC_CRS_ENABLE_IT(__INTERRUPT__) (CRS->CR |= (__INTERRUPT__)) /** * @brief Disables the specified CRS interrupts. * @param __INTERRUPT__: specifies the CRS interrupt sources to be disabled. * This parameter can be any combination of the following values: * @arg RCC_CRS_IT_SYNCOK * @arg RCC_CRS_IT_SYNCWARN * @arg RCC_CRS_IT_ERR * @arg RCC_CRS_IT_ESYNC * @retval None */ #define __HAL_RCC_CRS_DISABLE_IT(__INTERRUPT__) (CRS->CR &= ~(__INTERRUPT__)) /** @brief Check the CRS's interrupt has occurred or not. * @param __INTERRUPT__: specifies the CRS interrupt source to check. * This parameter can be one of the following values: * @arg RCC_CRS_IT_SYNCOK * @arg RCC_CRS_IT_SYNCWARN * @arg RCC_CRS_IT_ERR * @arg RCC_CRS_IT_ESYNC * @retval The new state of __INTERRUPT__ (SET or RESET). */ #define __HAL_RCC_CRS_GET_IT_SOURCE(__INTERRUPT__) ((CRS->CR & (__INTERRUPT__))? SET : RESET) /** @brief Clear the CRS's interrupt pending bits * bits to clear the selected interrupt pending bits. * @param __INTERRUPT__: specifies the interrupt pending bit to clear. * This parameter can be any combination of the following values: * @arg RCC_CRS_IT_SYNCOK * @arg RCC_CRS_IT_SYNCWARN * @arg RCC_CRS_IT_ERR * @arg RCC_CRS_IT_ESYNC * @arg RCC_CRS_IT_TRIMOVF * @arg RCC_CRS_IT_SYNCERR * @arg RCC_CRS_IT_SYNCMISS */ /* CRS IT Error Mask */ #define RCC_CRS_IT_ERROR_MASK ((uint32_t)(RCC_CRS_IT_TRIMOVF | RCC_CRS_IT_SYNCERR | RCC_CRS_IT_SYNCMISS)) #define __HAL_RCC_CRS_CLEAR_IT(__INTERRUPT__) ((((__INTERRUPT__) & RCC_CRS_IT_ERROR_MASK)!= 0) ? (CRS->ICR |= CRS_ICR_ERRC) : \ (CRS->ICR |= (__INTERRUPT__))) /** * @brief Checks whether the specified CRS flag is set or not. * @param _FLAG_: specifies the flag to check. * This parameter can be one of the following values: * @arg RCC_CRS_FLAG_SYNCOK * @arg RCC_CRS_FLAG_SYNCWARN * @arg RCC_CRS_FLAG_ERR * @arg RCC_CRS_FLAG_ESYNC * @arg RCC_CRS_FLAG_TRIMOVF * @arg RCC_CRS_FLAG_SYNCERR * @arg RCC_CRS_FLAG_SYNCMISS * @retval The new state of _FLAG_ (TRUE or FALSE). */ #define __HAL_RCC_CRS_GET_FLAG(_FLAG_) ((CRS->ISR & (_FLAG_)) == (_FLAG_)) /** * @brief Clears the CRS specified FLAG. * @param _FLAG_: specifies the flag to clear. * This parameter can be one of the following values: * @arg RCC_CRS_FLAG_SYNCOK * @arg RCC_CRS_FLAG_SYNCWARN * @arg RCC_CRS_FLAG_ERR * @arg RCC_CRS_FLAG_ESYNC * @arg RCC_CRS_FLAG_TRIMOVF * @arg RCC_CRS_FLAG_SYNCERR * @arg RCC_CRS_FLAG_SYNCMISS * @retval None */ /* CRS Flag Error Mask */ #define RCC_CRS_FLAG_ERROR_MASK ((uint32_t)(RCC_CRS_FLAG_TRIMOVF | RCC_CRS_FLAG_SYNCERR | RCC_CRS_FLAG_SYNCMISS)) #define __HAL_RCC_CRS_CLEAR_FLAG(__FLAG__) ((((__FLAG__) & RCC_CRS_FLAG_ERROR_MASK)!= 0) ? (CRS->ICR |= CRS_ICR_ERRC) : \ (CRS->ICR |= (__FLAG__))) /** * @} */ /** @defgroup RCCEx_CRS_Extended_Features RCCEx CRS Extended Features * @{ */ /** * @brief Enables the oscillator clock for frequency error counter. * @note when the CEN bit is set the CRS_CFGR register becomes write-protected. * @retval None */ #define __HAL_RCC_CRS_ENABLE_FREQ_ERROR_COUNTER() (CRS->CR |= CRS_CR_CEN) /** * @brief Disables the oscillator clock for frequency error counter. * @retval None */ #define __HAL_RCC_CRS_DISABLE_FREQ_ERROR_COUNTER() (CRS->CR &= ~CRS_CR_CEN) /** * @brief Enables the automatic hardware adjustement of TRIM bits. * @note When the AUTOTRIMEN bit is set the CRS_CFGR register becomes write-protected. * @retval None */ #define __HAL_RCC_CRS_ENABLE_AUTOMATIC_CALIB() (CRS->CR |= CRS_CR_AUTOTRIMEN) /** * @brief Enables or disables the automatic hardware adjustement of TRIM bits. * @retval None */ #define __HAL_RCC_CRS_DISABLE_AUTOMATIC_CALIB() (CRS->CR &= ~CRS_CR_AUTOTRIMEN) /** * @brief Macro to calculate reload value to be set in CRS register according to target and sync frequencies * @note The RELOAD value should be selected according to the ratio between the target frequency and the frequency * of the synchronization source after prescaling. It is then decreased by one in order to * reach the expected synchronization on the zero value. The formula is the following: * RELOAD = (fTARGET / fSYNC) -1 * @param _FTARGET_ Target frequency (value in Hz) * @param _FSYNC_ Synchronization signal frequency (value in Hz) * @retval None */ #define __HAL_RCC_CRS_CALCULATE_RELOADVALUE(_FTARGET_, _FSYNC_) (((_FTARGET_) / (_FSYNC_)) - 1) /** * @} */ #endif /* STM32F042x6 || STM32F048xx || */ /* STM32F071xB || STM32F072xB || STM32F078xx || */ /* STM32F091xC || STM32F098xx */ /** * @} */ /* Exported functions --------------------------------------------------------*/ /** @addtogroup RCCEx_Exported_Functions * @{ */ /** @addtogroup RCCEx_Exported_Functions_Group1 * @{ */ HAL_StatusTypeDef HAL_RCCEx_PeriphCLKConfig(RCC_PeriphCLKInitTypeDef *PeriphClkInit); void HAL_RCCEx_GetPeriphCLKConfig(RCC_PeriphCLKInitTypeDef *PeriphClkInit); uint32_t HAL_RCCEx_GetPeriphCLKFreq(uint32_t PeriphClk); #if defined(STM32F042x6) || defined(STM32F048xx)\ || defined(STM32F071xB) || defined(STM32F072xB) || defined(STM32F078xx)\ || defined(STM32F091xC) || defined(STM32F098xx) void HAL_RCCEx_CRSConfig(RCC_CRSInitTypeDef *pInit); void HAL_RCCEx_CRSSoftwareSynchronizationGenerate(void); void HAL_RCCEx_CRSGetSynchronizationInfo(RCC_CRSSynchroInfoTypeDef *pSynchroInfo); uint32_t HAL_RCCEx_CRSWaitSynchronization(uint32_t Timeout); #endif /* STM32F042x6 || STM32F048xx || */ /* STM32F071xB || STM32F072xB || STM32F078xx || */ /* STM32F091xC || STM32F098xx */ /** * @} */ /** * @} */ /** * @} */ /** * @} */ #ifdef __cplusplus } #endif #endif /* __STM32F0xx_HAL_RCC_EX_H */ /************************ (C) COPYRIGHT STMicroelectronics *****END OF FILE****/ ================================================ FILE: Zelig/mbed/TARGET_NUCLEO_F091RC/stm32f0xx_hal_rtc.h ================================================ /** ****************************************************************************** * @file stm32f0xx_hal_rtc.h * @author MCD Application Team * @version V1.3.0 * @date 26-June-2015 * @brief Header file of RTC HAL module. ****************************************************************************** * @attention * *

© COPYRIGHT(c) 2015 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. * ****************************************************************************** */ /* Define to prevent recursive inclusion -------------------------------------*/ #ifndef __STM32F0xx_HAL_RTC_H #define __STM32F0xx_HAL_RTC_H #ifdef __cplusplus extern "C" { #endif /* Includes ------------------------------------------------------------------*/ #include "stm32f0xx_hal_def.h" /** @addtogroup STM32F0xx_HAL_Driver * @{ */ /** @defgroup RTC RTC * @{ */ /* Exported types ------------------------------------------------------------*/ /** @defgroup RTC_Exported_Types RTC Exported Types * @{ */ /** * @brief HAL State structures definition */ typedef enum { HAL_RTC_STATE_RESET = 0x00, /*!< RTC not yet initialized or disabled */ HAL_RTC_STATE_READY = 0x01, /*!< RTC initialized and ready for use */ HAL_RTC_STATE_BUSY = 0x02, /*!< RTC process is ongoing */ HAL_RTC_STATE_TIMEOUT = 0x03, /*!< RTC timeout state */ HAL_RTC_STATE_ERROR = 0x04 /*!< RTC error state */ }HAL_RTCStateTypeDef; /** * @brief RTC Configuration Structure definition */ typedef struct { uint32_t HourFormat; /*!< Specifies the RTC Hour Format. This parameter can be a value of @ref RTC_Hour_Formats */ uint32_t AsynchPrediv; /*!< Specifies the RTC Asynchronous Predivider value. This parameter must be a number between Min_Data = 0x00 and Max_Data = 0x7F */ uint32_t SynchPrediv; /*!< Specifies the RTC Synchronous Predivider value. This parameter must be a number between Min_Data = 0x00 and Max_Data = 0x7FFF */ uint32_t OutPut; /*!< Specifies which signal will be routed to the RTC output. This parameter can be a value of @ref RTCEx_Output_selection_Definitions */ uint32_t OutPutPolarity; /*!< Specifies the polarity of the output signal. This parameter can be a value of @ref RTC_Output_Polarity_Definitions */ uint32_t OutPutType; /*!< Specifies the RTC Output Pin mode. This parameter can be a value of @ref RTC_Output_Type_ALARM_OUT */ }RTC_InitTypeDef; /** * @brief RTC Time structure definition */ typedef struct { uint8_t Hours; /*!< Specifies the RTC Time Hour. This parameter must be a number between Min_Data = 0 and Max_Data = 12 if the RTC_HourFormat_12 is selected. This parameter must be a number between Min_Data = 0 and Max_Data = 23 if the RTC_HourFormat_24 is selected */ uint8_t Minutes; /*!< Specifies the RTC Time Minutes. This parameter must be a number between Min_Data = 0 and Max_Data = 59 */ uint8_t Seconds; /*!< Specifies the RTC Time Seconds. This parameter must be a number between Min_Data = 0 and Max_Data = 59 */ uint32_t SubSeconds; /*!< Specifies the RTC Time SubSeconds. This parameter must be a number between Min_Data = 0 and Max_Data = 59 */ uint8_t TimeFormat; /*!< Specifies the RTC AM/PM Time. This parameter can be a value of @ref RTC_AM_PM_Definitions */ uint32_t DayLightSaving; /*!< Specifies RTC_DayLightSaveOperation: the value of hour adjustment. This parameter can be a value of @ref RTC_DayLightSaving_Definitions */ uint32_t StoreOperation; /*!< Specifies RTC_StoreOperation value to be written in the BCK bit in CR register to store the operation. This parameter can be a value of @ref RTC_StoreOperation_Definitions */ }RTC_TimeTypeDef; /** * @brief RTC Date structure definition */ typedef struct { uint8_t WeekDay; /*!< Specifies the RTC Date WeekDay. This parameter can be a value of @ref RTC_WeekDay_Definitions */ uint8_t Month; /*!< Specifies the RTC Date Month (in BCD format). This parameter can be a value of @ref RTC_Month_Date_Definitions */ uint8_t Date; /*!< Specifies the RTC Date. This parameter must be a number between Min_Data = 1 and Max_Data = 31 */ uint8_t Year; /*!< Specifies the RTC Date Year. This parameter must be a number between Min_Data = 0 and Max_Data = 99 */ }RTC_DateTypeDef; /** * @brief RTC Alarm structure definition */ typedef struct { RTC_TimeTypeDef AlarmTime; /*!< Specifies the RTC Alarm Time members */ uint32_t AlarmMask; /*!< Specifies the RTC Alarm Masks. This parameter can be a value of @ref RTC_AlarmMask_Definitions */ uint32_t AlarmSubSecondMask; /*!< Specifies the RTC Alarm SubSeconds Masks. This parameter can be a value of @ref RTC_Alarm_Sub_Seconds_Masks_Definitions */ uint32_t AlarmDateWeekDaySel; /*!< Specifies the RTC Alarm is on Date or WeekDay. This parameter can be a value of @ref RTC_AlarmDateWeekDay_Definitions */ uint8_t AlarmDateWeekDay; /*!< Specifies the RTC Alarm Date/WeekDay. If the Alarm Date is selected, this parameter must be set to a value in the 1-31 range. If the Alarm WeekDay is selected, this parameter can be a value of @ref RTC_WeekDay_Definitions */ uint32_t Alarm; /*!< Specifies the alarm . This parameter can be a value of @ref RTC_Alarms_Definitions */ }RTC_AlarmTypeDef; /** * @brief RTC Handle Structure definition */ typedef struct { RTC_TypeDef *Instance; /*!< Register base address */ RTC_InitTypeDef Init; /*!< RTC required parameters */ HAL_LockTypeDef Lock; /*!< RTC locking object */ __IO HAL_RTCStateTypeDef State; /*!< Time communication state */ }RTC_HandleTypeDef; /** * @} */ /* Exported constants --------------------------------------------------------*/ /** @defgroup RTC_Exported_Constants RTC Exported Constants * @{ */ /** @defgroup RTC_Hour_Formats RTC Hour Formats * @{ */ #define RTC_HOURFORMAT_24 ((uint32_t)0x00000000) #define RTC_HOURFORMAT_12 ((uint32_t)0x00000040) /** * @} */ /** @defgroup RTC_Output_Polarity_Definitions RTC Output Polarity Definitions * @{ */ #define RTC_OUTPUT_POLARITY_HIGH ((uint32_t)0x00000000) #define RTC_OUTPUT_POLARITY_LOW ((uint32_t)0x00100000) /** * @} */ /** @defgroup RTC_Output_Type_ALARM_OUT RTC Output Type ALARM OUT * @{ */ #define RTC_OUTPUT_TYPE_OPENDRAIN ((uint32_t)0x00000000) #define RTC_OUTPUT_TYPE_PUSHPULL ((uint32_t)0x00040000) /** * @} */ /** @defgroup RTC_AM_PM_Definitions RTC AM PM Definitions * @{ */ #define RTC_HOURFORMAT12_AM ((uint8_t)0x00) #define RTC_HOURFORMAT12_PM ((uint8_t)0x40) /** * @} */ /** @defgroup RTC_DayLightSaving_Definitions RTC DayLight Saving Definitions * @{ */ #define RTC_DAYLIGHTSAVING_SUB1H ((uint32_t)0x00020000) #define RTC_DAYLIGHTSAVING_ADD1H ((uint32_t)0x00010000) #define RTC_DAYLIGHTSAVING_NONE ((uint32_t)0x00000000) /** * @} */ /** @defgroup RTC_StoreOperation_Definitions RTC Store Operation Definitions * @{ */ #define RTC_STOREOPERATION_RESET ((uint32_t)0x00000000) #define RTC_STOREOPERATION_SET ((uint32_t)0x00040000) /** * @} */ /** @defgroup RTC_Input_parameter_format_definitions RTC Input parameter format definitions * @{ */ #define RTC_FORMAT_BIN ((uint32_t)0x000000000) #define RTC_FORMAT_BCD ((uint32_t)0x000000001) /** * @} */ /** @defgroup RTC_Month_Date_Definitions RTC Month Date Definitions * @{ */ /* Coded in BCD format */ #define RTC_MONTH_JANUARY ((uint8_t)0x01) #define RTC_MONTH_FEBRUARY ((uint8_t)0x02) #define RTC_MONTH_MARCH ((uint8_t)0x03) #define RTC_MONTH_APRIL ((uint8_t)0x04) #define RTC_MONTH_MAY ((uint8_t)0x05) #define RTC_MONTH_JUNE ((uint8_t)0x06) #define RTC_MONTH_JULY ((uint8_t)0x07) #define RTC_MONTH_AUGUST ((uint8_t)0x08) #define RTC_MONTH_SEPTEMBER ((uint8_t)0x09) #define RTC_MONTH_OCTOBER ((uint8_t)0x10) #define RTC_MONTH_NOVEMBER ((uint8_t)0x11) #define RTC_MONTH_DECEMBER ((uint8_t)0x12) /** * @} */ /** @defgroup RTC_WeekDay_Definitions RTC WeekDay Definitions * @{ */ #define RTC_WEEKDAY_MONDAY ((uint8_t)0x01) #define RTC_WEEKDAY_TUESDAY ((uint8_t)0x02) #define RTC_WEEKDAY_WEDNESDAY ((uint8_t)0x03) #define RTC_WEEKDAY_THURSDAY ((uint8_t)0x04) #define RTC_WEEKDAY_FRIDAY ((uint8_t)0x05) #define RTC_WEEKDAY_SATURDAY ((uint8_t)0x06) #define RTC_WEEKDAY_SUNDAY ((uint8_t)0x07) /** * @} */ /** @defgroup RTC_AlarmDateWeekDay_Definitions RTC Alarm Date WeekDay Definitions * @{ */ #define RTC_ALARMDATEWEEKDAYSEL_DATE ((uint32_t)0x00000000) #define RTC_ALARMDATEWEEKDAYSEL_WEEKDAY ((uint32_t)0x40000000) /** * @} */ /** @defgroup RTC_AlarmMask_Definitions RTC Alarm Mask Definitions * @{ */ #define RTC_ALARMMASK_NONE ((uint32_t)0x00000000) #define RTC_ALARMMASK_DATEWEEKDAY RTC_ALRMAR_MSK4 #define RTC_ALARMMASK_HOURS RTC_ALRMAR_MSK3 #define RTC_ALARMMASK_MINUTES RTC_ALRMAR_MSK2 #define RTC_ALARMMASK_SECONDS RTC_ALRMAR_MSK1 #define RTC_ALARMMASK_ALL ((uint32_t)0x80808080) /** * @} */ /** @defgroup RTC_Alarms_Definitions RTC Alarms Definitions * @{ */ #define RTC_ALARM_A RTC_CR_ALRAE /** * @} */ /** @defgroup RTC_Alarm_Sub_Seconds_Masks_Definitions RTC Alarm Sub Seconds Masks Definitions * @{ */ #define RTC_ALARMSUBSECONDMASK_ALL ((uint32_t)0x00000000) /*!< All Alarm SS fields are masked. There is no comparison on sub seconds for Alarm */ #define RTC_ALARMSUBSECONDMASK_SS14_1 ((uint32_t)0x01000000) /*!< SS[14:1] are don't care in Alarm comparison. Only SS[0] is compared. */ #define RTC_ALARMSUBSECONDMASK_SS14_2 ((uint32_t)0x02000000) /*!< SS[14:2] are don't care in Alarm comparison. Only SS[1:0] are compared */ #define RTC_ALARMSUBSECONDMASK_SS14_3 ((uint32_t)0x03000000) /*!< SS[14:3] are don't care in Alarm comparison. Only SS[2:0] are compared */ #define RTC_ALARMSUBSECONDMASK_SS14_4 ((uint32_t)0x04000000) /*!< SS[14:4] are don't care in Alarm comparison. Only SS[3:0] are compared */ #define RTC_ALARMSUBSECONDMASK_SS14_5 ((uint32_t)0x05000000) /*!< SS[14:5] are don't care in Alarm comparison. Only SS[4:0] are compared */ #define RTC_ALARMSUBSECONDMASK_SS14_6 ((uint32_t)0x06000000) /*!< SS[14:6] are don't care in Alarm comparison. Only SS[5:0] are compared */ #define RTC_ALARMSUBSECONDMASK_SS14_7 ((uint32_t)0x07000000) /*!< SS[14:7] are don't care in Alarm comparison. Only SS[6:0] are compared */ #define RTC_ALARMSUBSECONDMASK_SS14_8 ((uint32_t)0x08000000) /*!< SS[14:8] are don't care in Alarm comparison. Only SS[7:0] are compared */ #define RTC_ALARMSUBSECONDMASK_SS14_9 ((uint32_t)0x09000000) /*!< SS[14:9] are don't care in Alarm comparison. Only SS[8:0] are compared */ #define RTC_ALARMSUBSECONDMASK_SS14_10 ((uint32_t)0x0A000000) /*!< SS[14:10] are don't care in Alarm comparison. Only SS[9:0] are compared */ #define RTC_ALARMSUBSECONDMASK_SS14_11 ((uint32_t)0x0B000000) /*!< SS[14:11] are don't care in Alarm comparison. Only SS[10:0] are compared */ #define RTC_ALARMSUBSECONDMASK_SS14_12 ((uint32_t)0x0C000000) /*!< SS[14:12] are don't care in Alarm comparison.Only SS[11:0] are compared */ #define RTC_ALARMSUBSECONDMASK_SS14_13 ((uint32_t)0x0D000000) /*!< SS[14:13] are don't care in Alarm comparison. Only SS[12:0] are compared */ #define RTC_ALARMSUBSECONDMASK_SS14 ((uint32_t)0x0E000000) /*!< SS[14] is don't care in Alarm comparison.Only SS[13:0] are compared */ #define RTC_ALARMSUBSECONDMASK_NONE ((uint32_t)0x0F000000) /*!< SS[14:0] are compared and must match to activate alarm. */ /** * @} */ /** @defgroup RTC_Interrupts_Definitions RTC Interrupts Definitions * @{ */ #define RTC_IT_TS ((uint32_t)0x00008000) #define RTC_IT_WUT ((uint32_t)0x00004000) #define RTC_IT_ALRA ((uint32_t)0x00001000) #define RTC_IT_TAMP ((uint32_t)0x00000004) /* Used only to Enable the Tamper Interrupt */ #define RTC_IT_TAMP1 ((uint32_t)0x00020000) /*only for RTC_ISR flag check*/ #define RTC_IT_TAMP2 ((uint32_t)0x00040000) /*only for RTC_ISR flag check*/ #define RTC_IT_TAMP3 ((uint32_t)0x00080000) /*only for RTC_ISR flag check*/ /** * @} */ /** @defgroup RTC_Flags_Definitions RTC Flags Definitions * @{ */ #define RTC_FLAG_RECALPF ((uint32_t)0x00010000) #define RTC_FLAG_TAMP3F ((uint32_t)0x00008000) #define RTC_FLAG_TAMP2F ((uint32_t)0x00004000) #define RTC_FLAG_TAMP1F ((uint32_t)0x00002000) #define RTC_FLAG_TSOVF ((uint32_t)0x00001000) #define RTC_FLAG_TSF ((uint32_t)0x00000800) #define RTC_FLAG_WUTF ((uint32_t)0x00000400) #define RTC_FLAG_ALRAF ((uint32_t)0x00000100) #define RTC_FLAG_INITF ((uint32_t)0x00000040) #define RTC_FLAG_RSF ((uint32_t)0x00000020) #define RTC_FLAG_INITS ((uint32_t)0x00000010) #define RTC_FLAG_SHPF ((uint32_t)0x00000008) #define RTC_FLAG_WUTWF ((uint32_t)0x00000004) #define RTC_FLAG_ALRAWF ((uint32_t)0x00000001) /** * @} */ /** * @} */ /* Exported macros ------------------------------------------------------------*/ /** @defgroup RTC_Exported_Macros RTC Exported Macros * @{ */ /** @brief Reset RTC handle state * @param __HANDLE__: RTC handle. * @retval None */ #define __HAL_RTC_RESET_HANDLE_STATE(__HANDLE__) ((__HANDLE__)->State = HAL_RTC_STATE_RESET) /** * @brief Disable the write protection for RTC registers. * @param __HANDLE__: specifies the RTC handle. * @retval None */ #define __HAL_RTC_WRITEPROTECTION_DISABLE(__HANDLE__) \ do{ \ (__HANDLE__)->Instance->WPR = 0xCA; \ (__HANDLE__)->Instance->WPR = 0x53; \ } while(0) /** * @brief Enable the write protection for RTC registers. * @param __HANDLE__: specifies the RTC handle. * @retval None */ #define __HAL_RTC_WRITEPROTECTION_ENABLE(__HANDLE__) \ do{ \ (__HANDLE__)->Instance->WPR = 0xFF; \ } while(0) /** * @brief Enable the RTC ALARMA peripheral. * @param __HANDLE__: specifies the RTC handle. * @retval None */ #define __HAL_RTC_ALARMA_ENABLE(__HANDLE__) ((__HANDLE__)->Instance->CR |= (RTC_CR_ALRAE)) /** * @brief Disable the RTC ALARMA peripheral. * @param __HANDLE__: specifies the RTC handle. * @retval None */ #define __HAL_RTC_ALARMA_DISABLE(__HANDLE__) ((__HANDLE__)->Instance->CR &= ~(RTC_CR_ALRAE)) /** * @brief Enable the RTC Alarm interrupt. * @param __HANDLE__: specifies the RTC handle. * @param __INTERRUPT__: specifies the RTC Alarm interrupt sources to be enabled or disabled. * This parameter can be any combination of the following values: * @arg RTC_IT_ALRA: Alarm A interrupt * @retval None */ #define __HAL_RTC_ALARM_ENABLE_IT(__HANDLE__, __INTERRUPT__) ((__HANDLE__)->Instance->CR |= (__INTERRUPT__)) /** * @brief Disable the RTC Alarm interrupt. * @param __HANDLE__: specifies the RTC handle. * @param __INTERRUPT__: specifies the RTC Alarm interrupt sources to be enabled or disabled. * This parameter can be any combination of the following values: * @arg RTC_IT_ALRA: Alarm A interrupt * @retval None */ #define __HAL_RTC_ALARM_DISABLE_IT(__HANDLE__, __INTERRUPT__) ((__HANDLE__)->Instance->CR &= ~(__INTERRUPT__)) /** * @brief Check whether the specified RTC Alarm interrupt has occurred or not. * @param __HANDLE__: specifies the RTC handle. * @param __INTERRUPT__: specifies the RTC Alarm interrupt to check. * This parameter can be: * @arg RTC_IT_ALRA: Alarm A interrupt * @retval None */ #define __HAL_RTC_ALARM_GET_IT(__HANDLE__, __INTERRUPT__) ((((((__HANDLE__)->Instance->ISR)& ((__INTERRUPT__)>> 4)) & 0x0000FFFF) != RESET)? SET : RESET) /** * @brief Check whether the specified RTC Alarm interrupt has been enabled or not. * @param __HANDLE__: specifies the RTC handle. * @param __INTERRUPT__: specifies the RTC Alarm interrupt sources to check. * This parameter can be: * @arg RTC_IT_ALRA: Alarm A interrupt * @retval None */ #define __HAL_RTC_ALARM_GET_IT_SOURCE(__HANDLE__, __INTERRUPT__) (((((__HANDLE__)->Instance->CR) & (__INTERRUPT__)) != RESET) ? SET : RESET) /** * @brief Get the selected RTC Alarm's flag status. * @param __HANDLE__: specifies the RTC handle. * @param __FLAG__: specifies the RTC Alarm Flag sources to check. * This parameter can be: * @arg RTC_FLAG_ALRAF * @arg RTC_FLAG_ALRAWF * @retval None */ #define __HAL_RTC_ALARM_GET_FLAG(__HANDLE__, __FLAG__) (((((__HANDLE__)->Instance->ISR) & (__FLAG__)) != RESET)? SET : RESET) /** * @brief Clear the RTC Alarm's pending flags. * @param __HANDLE__: specifies the RTC handle. * @param __FLAG__: specifies the RTC Alarm Flag sources to clear. * This parameter can be: * @arg RTC_FLAG_ALRAF * @retval None */ #define __HAL_RTC_ALARM_CLEAR_FLAG(__HANDLE__, __FLAG__) ((__HANDLE__)->Instance->ISR) = (~(((__FLAG__) | RTC_ISR_INIT)& 0x0000FFFF)|((__HANDLE__)->Instance->ISR & RTC_ISR_INIT)) /** * @brief Enable interrupt on the RTC Alarm associated Exti line. * @retval None */ #define __HAL_RTC_ALARM_EXTI_ENABLE_IT() (EXTI->IMR |= RTC_EXTI_LINE_ALARM_EVENT) /** * @brief Disable interrupt on the RTC Alarm associated Exti line. * @retval None */ #define __HAL_RTC_ALARM_EXTI_DISABLE_IT() (EXTI->IMR &= ~(RTC_EXTI_LINE_ALARM_EVENT)) /** * @brief Enable event on the RTC Alarm associated Exti line. * @retval None. */ #define __HAL_RTC_ALARM_EXTI_ENABLE_EVENT() (EXTI->EMR |= RTC_EXTI_LINE_ALARM_EVENT) /** * @brief Disable event on the RTC Alarm associated Exti line. * @retval None. */ #define __HAL_RTC_ALARM_EXTI_DISABLE_EVENT() (EXTI->EMR &= ~(RTC_EXTI_LINE_ALARM_EVENT)) /** * @brief Enable falling edge trigger on the RTC Alarm associated Exti line. * @retval None. */ #define __HAL_RTC_ALARM_EXTI_ENABLE_FALLING_EDGE() (EXTI->FTSR |= RTC_EXTI_LINE_ALARM_EVENT) /** * @brief Disable falling edge trigger on the RTC Alarm associated Exti line. * @retval None. */ #define __HAL_RTC_ALARM_EXTI_DISABLE_FALLING_EDGE() (EXTI->FTSR &= ~(RTC_EXTI_LINE_ALARM_EVENT)) /** * @brief Enable rising edge trigger on the RTC Alarm associated Exti line. * @retval None. */ #define __HAL_RTC_ALARM_EXTI_ENABLE_RISING_EDGE() (EXTI->RTSR |= RTC_EXTI_LINE_ALARM_EVENT) /** * @brief Disable rising edge trigger on the RTC Alarm associated Exti line. * @retval None. */ #define __HAL_RTC_ALARM_EXTI_DISABLE_RISING_EDGE() (EXTI->RTSR &= ~(RTC_EXTI_LINE_ALARM_EVENT)) /** * @brief Enable rising & falling edge trigger on the RTC Alarm associated Exti line. * @retval None. */ #define __HAL_RTC_ALARM_EXTI_ENABLE_RISING_FALLING_EDGE() __HAL_RTC_ALARM_EXTI_ENABLE_RISING_EDGE();__HAL_RTC_ALARM_EXTI_ENABLE_FALLING_EDGE(); /** * @brief Disable rising & falling edge trigger on the RTC Alarm associated Exti line. * @retval None. */ #define __HAL_RTC_ALARM_EXTI_DISABLE_RISING_FALLING_EDGE() __HAL_RTC_ALARM_EXTI_DISABLE_RISING_EDGE();__HAL_RTC_ALARM_EXTI_DISABLE_FALLING_EDGE(); /** * @brief Check whether the RTC Alarm associated Exti line interrupt flag is set or not. * @retval Line Status. */ #define __HAL_RTC_ALARM_EXTI_GET_FLAG() (EXTI->PR & RTC_EXTI_LINE_ALARM_EVENT) /** * @brief Clear the RTC Alarm associated Exti line flag. * @retval None. */ #define __HAL_RTC_ALARM_EXTI_CLEAR_FLAG() (EXTI->PR = RTC_EXTI_LINE_ALARM_EVENT) /** * @brief Generate a Software interrupt on RTC Alarm associated Exti line. * @retval None. */ #define __HAL_RTC_ALARM_EXTI_GENERATE_SWIT() (EXTI->SWIER |= RTC_EXTI_LINE_ALARM_EVENT) /** * @} */ /* Include RTC HAL Extended module */ #include "stm32f0xx_hal_rtc_ex.h" /* Exported functions --------------------------------------------------------*/ /** @defgroup RTC_Exported_Functions RTC Exported Functions * @{ */ /** @defgroup RTC_Exported_Functions_Group1 Initialization and de-initialization functions * @{ */ /* Initialization and de-initialization functions ****************************/ HAL_StatusTypeDef HAL_RTC_Init(RTC_HandleTypeDef *hrtc); HAL_StatusTypeDef HAL_RTC_DeInit(RTC_HandleTypeDef *hrtc); void HAL_RTC_MspInit(RTC_HandleTypeDef *hrtc); void HAL_RTC_MspDeInit(RTC_HandleTypeDef *hrtc); /** * @} */ /** @defgroup RTC_Exported_Functions_Group2 RTC Time and Date functions * @{ */ /* RTC Time and Date functions ************************************************/ HAL_StatusTypeDef HAL_RTC_SetTime(RTC_HandleTypeDef *hrtc, RTC_TimeTypeDef *sTime, uint32_t Format); HAL_StatusTypeDef HAL_RTC_GetTime(RTC_HandleTypeDef *hrtc, RTC_TimeTypeDef *sTime, uint32_t Format); HAL_StatusTypeDef HAL_RTC_SetDate(RTC_HandleTypeDef *hrtc, RTC_DateTypeDef *sDate, uint32_t Format); HAL_StatusTypeDef HAL_RTC_GetDate(RTC_HandleTypeDef *hrtc, RTC_DateTypeDef *sDate, uint32_t Format); /** * @} */ /** @defgroup RTC_Exported_Functions_Group3 RTC Alarm functions * @{ */ /* RTC Alarm functions ********************************************************/ HAL_StatusTypeDef HAL_RTC_SetAlarm(RTC_HandleTypeDef *hrtc, RTC_AlarmTypeDef *sAlarm, uint32_t Format); HAL_StatusTypeDef HAL_RTC_SetAlarm_IT(RTC_HandleTypeDef *hrtc, RTC_AlarmTypeDef *sAlarm, uint32_t Format); HAL_StatusTypeDef HAL_RTC_DeactivateAlarm(RTC_HandleTypeDef *hrtc, uint32_t Alarm); HAL_StatusTypeDef HAL_RTC_GetAlarm(RTC_HandleTypeDef *hrtc, RTC_AlarmTypeDef *sAlarm, uint32_t Alarm, uint32_t Format); void HAL_RTC_AlarmIRQHandler(RTC_HandleTypeDef *hrtc); HAL_StatusTypeDef HAL_RTC_PollForAlarmAEvent(RTC_HandleTypeDef *hrtc, uint32_t Timeout); void HAL_RTC_AlarmAEventCallback(RTC_HandleTypeDef *hrtc); /** * @} */ /** @defgroup RTC_Exported_Functions_Group4 Peripheral Control functions * @{ */ /* Peripheral Control functions ***********************************************/ HAL_StatusTypeDef HAL_RTC_WaitForSynchro(RTC_HandleTypeDef* hrtc); /** * @} */ /** @defgroup RTC_Exported_Functions_Group5 Peripheral State functions * @{ */ /* Peripheral State functions *************************************************/ HAL_RTCStateTypeDef HAL_RTC_GetState(RTC_HandleTypeDef *hrtc); /** * @} */ /** * @} */ /* Private types -------------------------------------------------------------*/ /* Private variables ---------------------------------------------------------*/ /* Private constants ---------------------------------------------------------*/ /** @defgroup RTC_Private_Constants RTC Private Constants * @{ */ /* Masks Definition */ #define RTC_TR_RESERVED_MASK ((uint32_t)0x007F7F7F) #define RTC_DR_RESERVED_MASK ((uint32_t)0x00FFFF3F) #define RTC_INIT_MASK ((uint32_t)0xFFFFFFFF) #define RTC_RSF_MASK ((uint32_t)0xFFFFFF5F) #define RTC_FLAGS_MASK ((uint32_t)(RTC_FLAG_TSOVF | RTC_FLAG_TSF | RTC_FLAG_WUTF | \ RTC_FLAG_ALRBF | RTC_FLAG_ALRAF | RTC_FLAG_INITF | \ RTC_FLAG_RSF | RTC_FLAG_INITS | RTC_FLAG_WUTWF | \ RTC_FLAG_ALRBWF | RTC_FLAG_ALRAWF | RTC_FLAG_TAMP1F | \ RTC_FLAG_RECALPF | RTC_FLAG_SHPF)) #define RTC_TIMEOUT_VALUE 1000 #define RTC_EXTI_LINE_ALARM_EVENT ((uint32_t)EXTI_IMR_MR17) /*!< External interrupt line 17 Connected to the RTC Alarm event */ /** * @} */ /* Private macros ------------------------------------------------------------*/ /** @defgroup RTC_Private_Macros RTC Private Macros * @{ */ /** @defgroup RTC_IS_RTC_Definitions RTC Private macros to check input parameters * @{ */ #define IS_RTC_HOUR_FORMAT(FORMAT) (((FORMAT) == RTC_HOURFORMAT_12) || \ ((FORMAT) == RTC_HOURFORMAT_24)) #define IS_RTC_OUTPUT_POL(POL) (((POL) == RTC_OUTPUT_POLARITY_HIGH) || \ ((POL) == RTC_OUTPUT_POLARITY_LOW)) #define IS_RTC_OUTPUT_TYPE(TYPE) (((TYPE) == RTC_OUTPUT_TYPE_OPENDRAIN) || \ ((TYPE) == RTC_OUTPUT_TYPE_PUSHPULL)) #define IS_RTC_HOUR12(HOUR) (((HOUR) > (uint32_t)0) && ((HOUR) <= (uint32_t)12)) #define IS_RTC_HOUR24(HOUR) ((HOUR) <= (uint32_t)23) #define IS_RTC_ASYNCH_PREDIV(PREDIV) ((PREDIV) <= (uint32_t)0x7F) #define IS_RTC_SYNCH_PREDIV(PREDIV) ((PREDIV) <= (uint32_t)0x7FFF) #define IS_RTC_MINUTES(MINUTES) ((MINUTES) <= (uint32_t)59) #define IS_RTC_SECONDS(SECONDS) ((SECONDS) <= (uint32_t)59) #define IS_RTC_HOURFORMAT12(PM) (((PM) == RTC_HOURFORMAT12_AM) || ((PM) == RTC_HOURFORMAT12_PM)) #define IS_RTC_DAYLIGHT_SAVING(SAVE) (((SAVE) == RTC_DAYLIGHTSAVING_SUB1H) || \ ((SAVE) == RTC_DAYLIGHTSAVING_ADD1H) || \ ((SAVE) == RTC_DAYLIGHTSAVING_NONE)) #define IS_RTC_STORE_OPERATION(OPERATION) (((OPERATION) == RTC_STOREOPERATION_RESET) || \ ((OPERATION) == RTC_STOREOPERATION_SET)) #define IS_RTC_FORMAT(FORMAT) (((FORMAT) == RTC_FORMAT_BIN) || ((FORMAT) == RTC_FORMAT_BCD)) #define IS_RTC_YEAR(YEAR) ((YEAR) <= (uint32_t)99) #define IS_RTC_MONTH(MONTH) (((MONTH) >= (uint32_t)1) && ((MONTH) <= (uint32_t)12)) #define IS_RTC_DATE(DATE) (((DATE) >= (uint32_t)1) && ((DATE) <= (uint32_t)31)) #define IS_RTC_WEEKDAY(WEEKDAY) (((WEEKDAY) == RTC_WEEKDAY_MONDAY) || \ ((WEEKDAY) == RTC_WEEKDAY_TUESDAY) || \ ((WEEKDAY) == RTC_WEEKDAY_WEDNESDAY) || \ ((WEEKDAY) == RTC_WEEKDAY_THURSDAY) || \ ((WEEKDAY) == RTC_WEEKDAY_FRIDAY) || \ ((WEEKDAY) == RTC_WEEKDAY_SATURDAY) || \ ((WEEKDAY) == RTC_WEEKDAY_SUNDAY)) #define IS_RTC_ALARM_DATE_WEEKDAY_DATE(DATE) (((DATE) >(uint32_t) 0) && ((DATE) <= (uint32_t)31)) #define IS_RTC_ALARM_DATE_WEEKDAY_WEEKDAY(WEEKDAY) (((WEEKDAY) == RTC_WEEKDAY_MONDAY) || \ ((WEEKDAY) == RTC_WEEKDAY_TUESDAY) || \ ((WEEKDAY) == RTC_WEEKDAY_WEDNESDAY) || \ ((WEEKDAY) == RTC_WEEKDAY_THURSDAY) || \ ((WEEKDAY) == RTC_WEEKDAY_FRIDAY) || \ ((WEEKDAY) == RTC_WEEKDAY_SATURDAY) || \ ((WEEKDAY) == RTC_WEEKDAY_SUNDAY)) #define IS_RTC_ALARM_DATE_WEEKDAY_SEL(SEL) (((SEL) == RTC_ALARMDATEWEEKDAYSEL_DATE) || \ ((SEL) == RTC_ALARMDATEWEEKDAYSEL_WEEKDAY)) #define IS_RTC_ALARM_MASK(MASK) (((MASK) & 0x7F7F7F7F) == (uint32_t)RESET) #define IS_RTC_ALARM(ALARM) ((ALARM) == RTC_ALARM_A) #define IS_RTC_ALARM_SUB_SECOND_VALUE(VALUE) ((VALUE) <= (uint32_t)0x00007FFF) #define IS_RTC_ALARM_SUB_SECOND_MASK(MASK) (((MASK) == RTC_ALARMSUBSECONDMASK_ALL) || \ ((MASK) == RTC_ALARMSUBSECONDMASK_SS14_1) || \ ((MASK) == RTC_ALARMSUBSECONDMASK_SS14_2) || \ ((MASK) == RTC_ALARMSUBSECONDMASK_SS14_3) || \ ((MASK) == RTC_ALARMSUBSECONDMASK_SS14_4) || \ ((MASK) == RTC_ALARMSUBSECONDMASK_SS14_5) || \ ((MASK) == RTC_ALARMSUBSECONDMASK_SS14_6) || \ ((MASK) == RTC_ALARMSUBSECONDMASK_SS14_7) || \ ((MASK) == RTC_ALARMSUBSECONDMASK_SS14_8) || \ ((MASK) == RTC_ALARMSUBSECONDMASK_SS14_9) || \ ((MASK) == RTC_ALARMSUBSECONDMASK_SS14_10) || \ ((MASK) == RTC_ALARMSUBSECONDMASK_SS14_11) || \ ((MASK) == RTC_ALARMSUBSECONDMASK_SS14_12) || \ ((MASK) == RTC_ALARMSUBSECONDMASK_SS14_13) || \ ((MASK) == RTC_ALARMSUBSECONDMASK_SS14) || \ ((MASK) == RTC_ALARMSUBSECONDMASK_NONE)) /** * @} */ /** * @} */ /* Private functions ---------------------------------------------------------*/ /** @defgroup RTC_Private_Functions RTC Private Functions * @{ */ HAL_StatusTypeDef RTC_EnterInitMode(RTC_HandleTypeDef* hrtc); uint8_t RTC_ByteToBcd2(uint8_t Value); uint8_t RTC_Bcd2ToByte(uint8_t Value); /** * @} */ /** * @} */ /** * @} */ #ifdef __cplusplus } #endif #endif /* __STM32F0xx_HAL_RTC_H */ /************************ (C) COPYRIGHT STMicroelectronics *****END OF FILE****/ ================================================ FILE: Zelig/mbed/TARGET_NUCLEO_F091RC/stm32f0xx_hal_rtc_ex.h ================================================ /** ****************************************************************************** * @file stm32f0xx_hal_rtc_ex.h * @author MCD Application Team * @version V1.3.0 * @date 26-June-2015 * @brief Header file of RTC HAL Extended module. ****************************************************************************** * @attention * *

© COPYRIGHT(c) 2015 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. * ****************************************************************************** */ /* Define to prevent recursive inclusion -------------------------------------*/ #ifndef __STM32F0xx_HAL_RTC_EX_H #define __STM32F0xx_HAL_RTC_EX_H #ifdef __cplusplus extern "C" { #endif /* Includes ------------------------------------------------------------------*/ #include "stm32f0xx_hal_def.h" /** @addtogroup STM32F0xx_HAL_Driver * @{ */ /** @defgroup RTCEx RTCEx * @{ */ /* Exported types ------------------------------------------------------------*/ /** @defgroup RTCEx_Exported_Types RTCEx Exported Types * @{ */ /** * @brief RTC Tamper structure definition */ typedef struct { uint32_t Tamper; /*!< Specifies the Tamper Pin. This parameter can be a value of @ref RTCEx_Tamper_Pins_Definitions */ uint32_t Trigger; /*!< Specifies the Tamper Trigger. This parameter can be a value of @ref RTCEx_Tamper_Trigger_Definitions */ uint32_t Filter; /*!< Specifies the RTC Filter Tamper. This parameter can be a value of @ref RTCEx_Tamper_Filter_Definitions */ uint32_t SamplingFrequency; /*!< Specifies the sampling frequency. This parameter can be a value of @ref RTCEx_Tamper_Sampling_Frequencies_Definitions */ uint32_t PrechargeDuration; /*!< Specifies the Precharge Duration . This parameter can be a value of @ref RTCEx_Tamper_Pin_Precharge_Duration_Definitions */ uint32_t TamperPullUp; /*!< Specifies the Tamper PullUp . This parameter can be a value of @ref RTCEx_Tamper_Pull_UP_Definitions */ uint32_t TimeStampOnTamperDetection; /*!< Specifies the TimeStampOnTamperDetection. This parameter can be a value of @ref RTCEx_Tamper_TimeStampOnTamperDetection_Definitions */ }RTC_TamperTypeDef; /** * @} */ /* Exported constants --------------------------------------------------------*/ /** @defgroup RTCEx_Exported_Constants RTCEx Exported Constants * @{ */ /** @defgroup RTCEx_Output_selection_Definitions RTCEx Output Selection Definition * @{ */ #define RTC_OUTPUT_DISABLE ((uint32_t)0x00000000) #define RTC_OUTPUT_ALARMA ((uint32_t)0x00200000) #if defined(STM32F071xB) || defined(STM32F072xB) || defined(STM32F078xx) || defined(STM32F091xC) || defined(STM32F098xx) || defined(STM32F070xB) || defined(STM32F030xC) #define RTC_OUTPUT_WAKEUP ((uint32_t)0x00600000) #endif /** * @} */ #if !defined(STM32F030x6) && !defined(STM32F030x8) && !defined(STM32F030xC) && !defined(STM32F070x6) && !defined(STM32F070xB) /** @defgroup RTCEx_Backup_Registers_Definitions RTCEx Backup Registers Definition * @{ */ #define RTC_BKP_DR0 ((uint32_t)0x00000000) #define RTC_BKP_DR1 ((uint32_t)0x00000001) #define RTC_BKP_DR2 ((uint32_t)0x00000002) #define RTC_BKP_DR3 ((uint32_t)0x00000003) #define RTC_BKP_DR4 ((uint32_t)0x00000004) /** * @} */ #endif /* !defined(STM32F030x6) && !defined(STM32F030x8) && !defined(STM32F030xC) && !defined(STM32F070x6) && !defined(STM32F070xB) */ /** @defgroup RTCEx_Time_Stamp_Edges_definitions RTCEx Time Stamp Edges definition * @{ */ #define RTC_TIMESTAMPEDGE_RISING ((uint32_t)0x00000000) #define RTC_TIMESTAMPEDGE_FALLING ((uint32_t)0x00000008) /** * @} */ /** @defgroup RTCEx_TimeStamp_Pin_Selections RTCEx TimeStamp Pin Selection * @{ */ #define RTC_TIMESTAMPPIN_DEFAULT ((uint32_t)0x00000000) /** * @} */ /** @defgroup RTCEx_Tamper_Pins_Definitions RTCEx Tamper Pins Definition * @{ */ #define RTC_TAMPER_1 RTC_TAFCR_TAMP1E #define RTC_TAMPER_2 RTC_TAFCR_TAMP2E #if defined(STM32F071xB) || defined(STM32F072xB) || defined(STM32F078xx) || defined(STM32F091xC) || defined(STM32F098xx) #define RTC_TAMPER_3 RTC_TAFCR_TAMP3E #endif /** * @} */ /** @defgroup RTCEx_Tamper_Trigger_Definitions RTCEx Tamper Trigger Definition * @{ */ #define RTC_TAMPERTRIGGER_RISINGEDGE ((uint32_t)0x00000000) #define RTC_TAMPERTRIGGER_FALLINGEDGE ((uint32_t)0x00000002) #define RTC_TAMPERTRIGGER_LOWLEVEL RTC_TAMPERTRIGGER_RISINGEDGE #define RTC_TAMPERTRIGGER_HIGHLEVEL RTC_TAMPERTRIGGER_FALLINGEDGE /** * @} */ /** @defgroup RTCEx_Tamper_Filter_Definitions RTCEx Tamper Filter Definition * @{ */ #define RTC_TAMPERFILTER_DISABLE ((uint32_t)0x00000000) /*!< Tamper filter is disabled */ #define RTC_TAMPERFILTER_2SAMPLE ((uint32_t)0x00000800) /*!< Tamper is activated after 2 consecutive samples at the active level */ #define RTC_TAMPERFILTER_4SAMPLE ((uint32_t)0x00001000) /*!< Tamper is activated after 4 consecutive samples at the active level */ #define RTC_TAMPERFILTER_8SAMPLE ((uint32_t)0x00001800) /*!< Tamper is activated after 8 consecutive samples at the active level. */ /** * @} */ /** @defgroup RTCEx_Tamper_Sampling_Frequencies_Definitions RTCEx Tamper Sampling Frequencies Definition * @{ */ #define RTC_TAMPERSAMPLINGFREQ_RTCCLK_DIV32768 ((uint32_t)0x00000000) /*!< Each of the tamper inputs are sampled with a frequency = RTCCLK / 32768 */ #define RTC_TAMPERSAMPLINGFREQ_RTCCLK_DIV16384 ((uint32_t)0x00000100) /*!< Each of the tamper inputs are sampled with a frequency = RTCCLK / 16384 */ #define RTC_TAMPERSAMPLINGFREQ_RTCCLK_DIV8192 ((uint32_t)0x00000200) /*!< Each of the tamper inputs are sampled with a frequency = RTCCLK / 8192 */ #define RTC_TAMPERSAMPLINGFREQ_RTCCLK_DIV4096 ((uint32_t)0x00000300) /*!< Each of the tamper inputs are sampled with a frequency = RTCCLK / 4096 */ #define RTC_TAMPERSAMPLINGFREQ_RTCCLK_DIV2048 ((uint32_t)0x00000400) /*!< Each of the tamper inputs are sampled with a frequency = RTCCLK / 2048 */ #define RTC_TAMPERSAMPLINGFREQ_RTCCLK_DIV1024 ((uint32_t)0x00000500) /*!< Each of the tamper inputs are sampled with a frequency = RTCCLK / 1024 */ #define RTC_TAMPERSAMPLINGFREQ_RTCCLK_DIV512 ((uint32_t)0x00000600) /*!< Each of the tamper inputs are sampled with a frequency = RTCCLK / 512 */ #define RTC_TAMPERSAMPLINGFREQ_RTCCLK_DIV256 ((uint32_t)0x00000700) /*!< Each of the tamper inputs are sampled with a frequency = RTCCLK / 256 */ /** * @} */ /** @defgroup RTCEx_Tamper_Pin_Precharge_Duration_Definitions RTCEx Tamper Pin Precharge Duration Definition * @{ */ #define RTC_TAMPERPRECHARGEDURATION_1RTCCLK ((uint32_t)0x00000000) /*!< Tamper pins are pre-charged before sampling during 1 RTCCLK cycle */ #define RTC_TAMPERPRECHARGEDURATION_2RTCCLK ((uint32_t)0x00002000) /*!< Tamper pins are pre-charged before sampling during 2 RTCCLK cycles */ #define RTC_TAMPERPRECHARGEDURATION_4RTCCLK ((uint32_t)0x00004000) /*!< Tamper pins are pre-charged before sampling during 4 RTCCLK cycles */ #define RTC_TAMPERPRECHARGEDURATION_8RTCCLK ((uint32_t)0x00006000) /*!< Tamper pins are pre-charged before sampling during 8 RTCCLK cycles */ /** * @} */ /** @defgroup RTCEx_Tamper_TimeStampOnTamperDetection_Definitions RTCEx Tamper TimeStampOnTamperDetection Definition * @{ */ #define RTC_TIMESTAMPONTAMPERDETECTION_ENABLE ((uint32_t)RTC_TAFCR_TAMPTS) /*!< TimeStamp on Tamper Detection event saved */ #define RTC_TIMESTAMPONTAMPERDETECTION_DISABLE ((uint32_t)0x00000000) /*!< TimeStamp on Tamper Detection event is not saved */ /** * @} */ /** @defgroup RTCEx_Tamper_Pull_UP_Definitions RTCEx Tamper Pull UP Definition * @{ */ #define RTC_TAMPER_PULLUP_ENABLE ((uint32_t)0x00000000) /*!< Tamper pins are pre-charged before sampling */ #define RTC_TAMPER_PULLUP_DISABLE ((uint32_t)RTC_TAFCR_TAMPPUDIS) /*!< TimeStamp on Tamper Detection event is not saved */ /** * @} */ #if defined(STM32F071xB) || defined(STM32F072xB) || defined(STM32F078xx) || defined(STM32F091xC) || defined(STM32F098xx) || defined(STM32F070xB) || defined(STM32F030xC) /** @defgroup RTCEx_Wakeup_Timer_Definitions RTCEx Wakeup Timer Definition * @{ */ #define RTC_WAKEUPCLOCK_RTCCLK_DIV16 ((uint32_t)0x00000000) #define RTC_WAKEUPCLOCK_RTCCLK_DIV8 ((uint32_t)0x00000001) #define RTC_WAKEUPCLOCK_RTCCLK_DIV4 ((uint32_t)0x00000002) #define RTC_WAKEUPCLOCK_RTCCLK_DIV2 ((uint32_t)0x00000003) #define RTC_WAKEUPCLOCK_CK_SPRE_16BITS ((uint32_t)0x00000004) #define RTC_WAKEUPCLOCK_CK_SPRE_17BITS ((uint32_t)0x00000006) /** * @} */ #endif /* defined(STM32F071xB) || defined(STM32F072xB) || defined(STM32F078xx) || defined(STM32F091xC) || defined(STM32F098xx) || defined(STM32F070xB) || defined(STM32F030xC) */ /** @defgroup RTCEx_Smooth_calib_period_Definitions RTCEx Smooth calib period Definition * @{ */ #define RTC_SMOOTHCALIB_PERIOD_32SEC ((uint32_t)0x00000000) /*!< If RTCCLK = 32768 Hz, Smooth calibation period is 32s, else 2exp20 RTCCLK seconds */ #define RTC_SMOOTHCALIB_PERIOD_16SEC ((uint32_t)0x00002000) /*!< If RTCCLK = 32768 Hz, Smooth calibation period is 16s, else 2exp19 RTCCLK seconds */ #define RTC_SMOOTHCALIB_PERIOD_8SEC ((uint32_t)0x00004000) /*!< If RTCCLK = 32768 Hz, Smooth calibation period is 8s, else 2exp18 RTCCLK seconds */ /** * @} */ /** @defgroup RTCEx_Smooth_calib_Plus_pulses_Definitions RTCEx Smooth calib Plus pulses Definition * @{ */ #define RTC_SMOOTHCALIB_PLUSPULSES_SET ((uint32_t)0x00008000) /*!< The number of RTCCLK pulses added during a X -second window = Y - CALM[8:0] with Y = 512, 256, 128 when X = 32, 16, 8 */ #define RTC_SMOOTHCALIB_PLUSPULSES_RESET ((uint32_t)0x00000000) /*!< The number of RTCCLK pulses subbstited during a 32-second window = CALM[8:0] */ /** * @} */ /** @defgroup RTCEx_Calib_Output_selection_Definitions RTCEx Calib Output selection Definitions * @{ */ #define RTC_CALIBOUTPUT_512HZ ((uint32_t)0x00000000) #define RTC_CALIBOUTPUT_1HZ ((uint32_t)0x00080000) /** * @} */ /** @defgroup RTCEx_Add_1_Second_Parameter_Definition RTCEx Add 1 Second Parameter Definition * @{ */ #define RTC_SHIFTADD1S_RESET ((uint32_t)0x00000000) #define RTC_SHIFTADD1S_SET ((uint32_t)0x80000000) /** * @} */ /** * @} */ /* Exported macros -----------------------------------------------------------*/ /** @defgroup RTCEx_Exported_Macros RTCEx Exported Macros * @{ */ /* ---------------------------------WAKEUPTIMER---------------------------------*/ /** @defgroup RTCEx_WakeUp_Timer RTC WakeUp Timer * @{ */ #if defined(STM32F071xB) || defined(STM32F072xB) || defined(STM32F078xx) || defined(STM32F091xC) || defined(STM32F098xx) || defined(STM32F070xB) || defined(STM32F030xC) /** * @brief Enable the RTC WakeUp Timer peripheral. * @param __HANDLE__: specifies the RTC handle. * @retval None */ #define __HAL_RTC_WAKEUPTIMER_ENABLE(__HANDLE__) ((__HANDLE__)->Instance->CR |= (RTC_CR_WUTE)) /** * @brief Disable the RTC WakeUp Timer peripheral. * @param __HANDLE__: specifies the RTC handle. * @retval None */ #define __HAL_RTC_WAKEUPTIMER_DISABLE(__HANDLE__) ((__HANDLE__)->Instance->CR &= ~(RTC_CR_WUTE)) /** * @brief Enable the RTC WakeUpTimer interrupt. * @param __HANDLE__: specifies the RTC handle. * @param __INTERRUPT__: specifies the RTC WakeUpTimer interrupt sources to be enabled. * This parameter can be: * @arg RTC_IT_WUT: WakeUpTimer interrupt * @retval None */ #define __HAL_RTC_WAKEUPTIMER_ENABLE_IT(__HANDLE__, __INTERRUPT__) ((__HANDLE__)->Instance->CR |= (__INTERRUPT__)) /** * @brief Disable the RTC WakeUpTimer interrupt. * @param __HANDLE__: specifies the RTC handle. * @param __INTERRUPT__: specifies the RTC WakeUpTimer interrupt sources to be disabled. * This parameter can be: * @arg RTC_IT_WUT: WakeUpTimer interrupt * @retval None */ #define __HAL_RTC_WAKEUPTIMER_DISABLE_IT(__HANDLE__, __INTERRUPT__) ((__HANDLE__)->Instance->CR &= ~(__INTERRUPT__)) /** * @brief Check whether the specified RTC WakeUpTimer interrupt has occurred or not. * @param __HANDLE__: specifies the RTC handle. * @param __INTERRUPT__: specifies the RTC WakeUpTimer interrupt to check. * This parameter can be: * @arg RTC_IT_WUT: WakeUpTimer interrupt * @retval None */ #define __HAL_RTC_WAKEUPTIMER_GET_IT(__HANDLE__, __INTERRUPT__) (((((__HANDLE__)->Instance->ISR) & ((__INTERRUPT__)>> 4)) != RESET) ? SET : RESET) /** * @brief Check whether the specified RTC Wake Up timer interrupt has been enabled or not. * @param __HANDLE__: specifies the RTC handle. * @param __INTERRUPT__: specifies the RTC Wake Up timer interrupt sources to check. * This parameter can be: * @arg RTC_IT_WUT: WakeUpTimer interrupt * @retval None */ #define __HAL_RTC_WAKEUPTIMER_GET_IT_SOURCE(__HANDLE__, __INTERRUPT__) (((((__HANDLE__)->Instance->CR) & (__INTERRUPT__)) != RESET) ? SET : RESET) /** * @brief Get the selected RTC WakeUpTimer's flag status. * @param __HANDLE__: specifies the RTC handle. * @param __FLAG__: specifies the RTC WakeUpTimer Flag is pending or not. * This parameter can be: * @arg RTC_FLAG_WUTF * @arg RTC_FLAG_WUTWF * @retval None */ #define __HAL_RTC_WAKEUPTIMER_GET_FLAG(__HANDLE__, __FLAG__) (((((__HANDLE__)->Instance->ISR) & (__FLAG__)) != RESET) ? SET : RESET) /** * @brief Clear the RTC Wake Up timer's pending flags. * @param __HANDLE__: specifies the RTC handle. * @param __FLAG__: specifies the RTC WakeUpTimer Flag to clear. * This parameter can be: * @arg RTC_FLAG_WUTF * @retval None */ #define __HAL_RTC_WAKEUPTIMER_CLEAR_FLAG(__HANDLE__, __FLAG__) ((__HANDLE__)->Instance->ISR) = (~(((__FLAG__) | RTC_ISR_INIT)& 0x0000FFFF)|((__HANDLE__)->Instance->ISR & RTC_ISR_INIT)) /* WAKE-UP TIMER EXTI */ /* ------------------ */ /** * @brief Enable interrupt on the RTC WakeUp Timer associated Exti line. * @retval None */ #define __HAL_RTC_WAKEUPTIMER_EXTI_ENABLE_IT() (EXTI->IMR |= RTC_EXTI_LINE_WAKEUPTIMER_EVENT) /** * @brief Disable interrupt on the RTC WakeUp Timer associated Exti line. * @retval None */ #define __HAL_RTC_WAKEUPTIMER_EXTI_DISABLE_IT() (EXTI->IMR &= ~(RTC_EXTI_LINE_WAKEUPTIMER_EVENT)) /** * @brief Enable event on the RTC WakeUp Timer associated Exti line. * @retval None. */ #define __HAL_RTC_WAKEUPTIMER_EXTI_ENABLE_EVENT() (EXTI->EMR |= RTC_EXTI_LINE_WAKEUPTIMER_EVENT) /** * @brief Disable event on the RTC WakeUp Timer associated Exti line. * @retval None. */ #define __HAL_RTC_WAKEUPTIMER_EXTI_DISABLE_EVENT() (EXTI->EMR &= ~(RTC_EXTI_LINE_WAKEUPTIMER_EVENT)) /** * @brief Enable falling edge trigger on the RTC WakeUp Timer associated Exti line. * @retval None. */ #define __HAL_RTC_WAKEUPTIMER_EXTI_ENABLE_FALLING_EDGE() (EXTI->FTSR |= RTC_EXTI_LINE_WAKEUPTIMER_EVENT) /** * @brief Disable falling edge trigger on the RTC WakeUp Timer associated Exti line. * @retval None. */ #define __HAL_RTC_WAKEUPTIMER_EXTI_DISABLE_FALLING_EDGE() (EXTI->FTSR &= ~(RTC_EXTI_LINE_WAKEUPTIMER_EVENT)) /** * @brief Enable rising edge trigger on the RTC WakeUp Timer associated Exti line. * @retval None. */ #define __HAL_RTC_WAKEUPTIMER_EXTI_ENABLE_RISING_EDGE() (EXTI->RTSR |= RTC_EXTI_LINE_WAKEUPTIMER_EVENT) /** * @brief Disable rising edge trigger on the RTC WakeUp Timer associated Exti line. * @retval None. */ #define __HAL_RTC_WAKEUPTIMER_EXTI_DISABLE_RISING_EDGE() (EXTI->RTSR &= ~(RTC_EXTI_LINE_WAKEUPTIMER_EVENT)) /** * @brief Enable rising & falling edge trigger on the RTC WakeUp Timer associated Exti line. * @retval None. */ #define __HAL_RTC_WAKEUPTIMER_EXTI_ENABLE_RISING_FALLING_EDGE() __HAL_RTC_WAKEUPTIMER_EXTI_ENABLE_RISING_EDGE();__HAL_RTC_WAKEUPTIMER_EXTI_ENABLE_FALLING_EDGE(); /** * @brief Disable rising & falling edge trigger on the RTC WakeUp Timer associated Exti line. * This parameter can be: * @retval None. */ #define __HAL_RTC_WAKEUPTIMER_EXTI_DISABLE_RISING_FALLING_EDGE() __HAL_RTC_WAKEUPTIMER_EXTI_DISABLE_RISING_EDGE();__HAL_RTC_WAKEUPTIMER_EXTI_DISABLE_FALLING_EDGE(); /** * @brief Check whether the RTC WakeUp Timer associated Exti line interrupt flag is set or not. * @retval Line Status. */ #define __HAL_RTC_WAKEUPTIMER_EXTI_GET_FLAG() (EXTI->PR & RTC_EXTI_LINE_WAKEUPTIMER_EVENT) /** * @brief Clear the RTC WakeUp Timer associated Exti line flag. * @retval None. */ #define __HAL_RTC_WAKEUPTIMER_EXTI_CLEAR_FLAG() (EXTI->PR = RTC_EXTI_LINE_WAKEUPTIMER_EVENT) /** * @brief Generate a Software interrupt on the RTC WakeUp Timer associated Exti line. * @retval None. */ #define __HAL_RTC_WAKEUPTIMER_EXTI_GENERATE_SWIT() (EXTI->SWIER |= RTC_EXTI_LINE_WAKEUPTIMER_EVENT) #endif /* defined(STM32F071xB) || defined(STM32F072xB) || defined(STM32F078xx) || defined(STM32F091xC) || defined(STM32F098xx) || defined(STM32F070xB) || defined(STM32F030xC) */ /** * @} */ /* ---------------------------------TIMESTAMP---------------------------------*/ /** @defgroup RTCEx_Timestamp RTC Timestamp * @{ */ /** * @brief Enable the RTC TimeStamp peripheral. * @param __HANDLE__: specifies the RTC handle. * @retval None */ #define __HAL_RTC_TIMESTAMP_ENABLE(__HANDLE__) ((__HANDLE__)->Instance->CR |= (RTC_CR_TSE)) /** * @brief Disable the RTC TimeStamp peripheral. * @param __HANDLE__: specifies the RTC handle. * @retval None */ #define __HAL_RTC_TIMESTAMP_DISABLE(__HANDLE__) ((__HANDLE__)->Instance->CR &= ~(RTC_CR_TSE)) /** * @brief Enable the RTC TimeStamp interrupt. * @param __HANDLE__: specifies the RTC handle. * @param __INTERRUPT__: specifies the RTC TimeStamp interrupt source to be enabled. * This parameter can be: * @arg RTC_IT_TS: TimeStamp interrupt * @retval None */ #define __HAL_RTC_TIMESTAMP_ENABLE_IT(__HANDLE__, __INTERRUPT__) ((__HANDLE__)->Instance->CR |= (__INTERRUPT__)) /** * @brief Disable the RTC TimeStamp interrupt. * @param __HANDLE__: specifies the RTC handle. * @param __INTERRUPT__: specifies the RTC TimeStamp interrupt source to be disabled. * This parameter can be: * @arg RTC_IT_TS: TimeStamp interrupt * @retval None */ #define __HAL_RTC_TIMESTAMP_DISABLE_IT(__HANDLE__, __INTERRUPT__) ((__HANDLE__)->Instance->CR &= ~(__INTERRUPT__)) /** * @brief Check whether the specified RTC TimeStamp interrupt has occurred or not. * @param __HANDLE__: specifies the RTC handle. * @param __INTERRUPT__: specifies the RTC TimeStamp interrupt to check. * This parameter can be: * @arg RTC_IT_TS: TimeStamp interrupt * @retval None */ #define __HAL_RTC_TIMESTAMP_GET_IT(__HANDLE__, __INTERRUPT__) (((((__HANDLE__)->Instance->ISR) & ((__INTERRUPT__)>> 4)) != RESET)? SET : RESET) /** * @brief Check whether the specified RTC Time Stamp interrupt has been enabled or not. * @param __HANDLE__: specifies the RTC handle. * @param __INTERRUPT__: specifies the RTC Time Stamp interrupt source to check. * This parameter can be: * @arg RTC_IT_TS: TimeStamp interrupt * @retval None */ #define __HAL_RTC_TIMESTAMP_GET_IT_SOURCE(__HANDLE__, __INTERRUPT__) (((((__HANDLE__)->Instance->CR) & (__INTERRUPT__)) != RESET) ? SET : RESET) /** * @brief Get the selected RTC TimeStamp's flag status. * @param __HANDLE__: specifies the RTC handle. * @param __FLAG__: specifies the RTC TimeStamp Flag is pending or not. * This parameter can be: * @arg RTC_FLAG_TSF * @arg RTC_FLAG_TSOVF * @retval None */ #define __HAL_RTC_TIMESTAMP_GET_FLAG(__HANDLE__, __FLAG__) (((((__HANDLE__)->Instance->ISR) & (__FLAG__)) != RESET)? SET : RESET) /** * @brief Clear the RTC Time Stamp's pending flags. * @param __HANDLE__: specifies the RTC handle. * @param __FLAG__: specifies the RTC Alarm Flag to clear. * This parameter can be: * @arg RTC_FLAG_TSF * @retval None */ #define __HAL_RTC_TIMESTAMP_CLEAR_FLAG(__HANDLE__, __FLAG__) ((__HANDLE__)->Instance->ISR) = (~(((__FLAG__) | RTC_ISR_INIT)& 0x0000FFFF)|((__HANDLE__)->Instance->ISR & RTC_ISR_INIT)) /** * @} */ /* ---------------------------------TAMPER------------------------------------*/ /** @defgroup RTCEx_Tamper RTC Tamper * @{ */ /** * @brief Enable the RTC Tamper1 input detection. * @param __HANDLE__: specifies the RTC handle. * @retval None */ #define __HAL_RTC_TAMPER1_ENABLE(__HANDLE__) ((__HANDLE__)->Instance->TAFCR |= (RTC_TAFCR_TAMP1E)) /** * @brief Disable the RTC Tamper1 input detection. * @param __HANDLE__: specifies the RTC handle. * @retval None */ #define __HAL_RTC_TAMPER1_DISABLE(__HANDLE__) ((__HANDLE__)->Instance->TAFCR &= ~(RTC_TAFCR_TAMP1E)) /** * @brief Enable the RTC Tamper2 input detection. * @param __HANDLE__: specifies the RTC handle. * @retval None */ #define __HAL_RTC_TAMPER2_ENABLE(__HANDLE__) ((__HANDLE__)->Instance->TAFCR |= (RTC_TAFCR_TAMP2E)) /** * @brief Disable the RTC Tamper2 input detection. * @param __HANDLE__: specifies the RTC handle. * @retval None */ #define __HAL_RTC_TAMPER2_DISABLE(__HANDLE__) ((__HANDLE__)->Instance->TAFCR &= ~(RTC_TAFCR_TAMP2E)) #if defined(STM32F071xB) || defined(STM32F072xB) || defined(STM32F078xx) || defined(STM32F091xC) || defined(STM32F098xx) || defined(STM32F070xB) || defined(STM32F030xC) /** * @brief Enable the RTC Tamper3 input detection. * @param __HANDLE__: specifies the RTC handle. * @retval None */ #define __HAL_RTC_TAMPER3_ENABLE(__HANDLE__) ((__HANDLE__)->Instance->TAFCR |= (RTC_TAFCR_TAMP3E)) /** * @brief Disable the RTC Tamper3 input detection. * @param __HANDLE__: specifies the RTC handle. * @retval None */ #define __HAL_RTC_TAMPER3_DISABLE(__HANDLE__) ((__HANDLE__)->Instance->TAFCR &= ~(RTC_TAFCR_TAMP3E)) #endif /* defined(STM32F071xB) || defined(STM32F072xB) || defined(STM32F078xx) || defined(STM32F091xC) || defined(STM32F098xx) || defined(STM32F070xB) || defined(STM32F030xC) */ /** * @brief Enable the RTC Tamper interrupt. * @param __HANDLE__: specifies the RTC handle. * @param __INTERRUPT__: specifies the RTC Tamper interrupt sources to be enabled. * This parameter can be any combination of the following values: * @arg RTC_IT_TAMP: Tamper interrupt * @retval None */ #define __HAL_RTC_TAMPER_ENABLE_IT(__HANDLE__, __INTERRUPT__) ((__HANDLE__)->Instance->TAFCR |= (__INTERRUPT__)) /** * @brief Disable the RTC Tamper interrupt. * @param __HANDLE__: specifies the RTC handle. * @param __INTERRUPT__: specifies the RTC Tamper interrupt sources to be disabled. * This parameter can be any combination of the following values: * @arg RTC_IT_TAMP: Tamper interrupt * @retval None */ #define __HAL_RTC_TAMPER_DISABLE_IT(__HANDLE__, __INTERRUPT__) ((__HANDLE__)->Instance->TAFCR &= ~(__INTERRUPT__)) #if defined(STM32F071xB) || defined(STM32F072xB) || defined(STM32F078xx) || defined(STM32F091xC) || defined(STM32F098xx) || defined(STM32F070xB) || defined(STM32F030xC) /** * @brief Check whether the specified RTC Tamper interrupt has occurred or not. * @param __HANDLE__: specifies the RTC handle. * @param __INTERRUPT__: specifies the RTC Tamper interrupt to check. * This parameter can be: * @arg RTC_IT_TAMP1: Tamper1 interrupt * @arg RTC_IT_TAMP2: Tamper2 interrupt * @arg RTC_IT_TAMP3: Tamper3 interrupt * @retval None */ #define __HAL_RTC_TAMPER_GET_IT(__HANDLE__, __INTERRUPT__) (((((__HANDLE__)->Instance->ISR) & ((__INTERRUPT__)>> 4)) != RESET)? SET : RESET) #else /** * @brief Check whether the specified RTC Tamper interrupt has occurred or not. * @param __HANDLE__: specifies the RTC handle. * @param __INTERRUPT__: specifies the RTC Tamper interrupt to check. * This parameter can be: * @arg RTC_IT_TAMP1: Tamper1 interrupt * @arg RTC_IT_TAMP2: Tamper2 interrupt * @retval None */ #define __HAL_RTC_TAMPER_GET_IT(__HANDLE__, __INTERRUPT__) (((((__HANDLE__)->Instance->ISR) & ((__INTERRUPT__)>> 4)) != RESET)? SET : RESET) #endif /* defined(STM32F071xB) || defined(STM32F072xB) || defined(STM32F078xx) || defined(STM32F091xC) || defined(STM32F098xx) || defined(STM32F070xB) || defined(STM32F030xC) */ /** * @brief Check whether the specified RTC Tamper interrupt has been enabled or not. * @param __HANDLE__: specifies the RTC handle. * @param __INTERRUPT__: specifies the RTC Tamper interrupt source to check. * This parameter can be: * @arg RTC_IT_TAMP: Tamper interrupt * @retval None */ #define __HAL_RTC_TAMPER_GET_IT_SOURCE(__HANDLE__, __INTERRUPT__) (((((__HANDLE__)->Instance->TAFCR) & (__INTERRUPT__)) != RESET) ? SET : RESET) #if defined(STM32F071xB) || defined(STM32F072xB) || defined(STM32F078xx) || defined(STM32F091xC) || defined(STM32F098xx) || defined(STM32F070xB) || defined(STM32F030xC) /** * @brief Get the selected RTC Tamper's flag status. * @param __HANDLE__: specifies the RTC handle. * @param __FLAG__: specifies the RTC Tamper Flag is pending or not. * This parameter can be: * @arg RTC_FLAG_TAMP1F * @arg RTC_FLAG_TAMP2F * @arg RTC_FLAG_TAMP3F * @retval None */ #define __HAL_RTC_TAMPER_GET_FLAG(__HANDLE__, __FLAG__) (((((__HANDLE__)->Instance->ISR) & (__FLAG__)) != RESET)? SET : RESET) /** * @brief Clear the RTC Tamper's pending flags. * @param __HANDLE__: specifies the RTC handle. * @param __FLAG__: specifies the RTC Tamper Flag to clear. * This parameter can be: * @arg RTC_FLAG_TAMP1F * @arg RTC_FLAG_TAMP2F * @arg RTC_FLAG_TAMP3F * @retval None */ #define __HAL_RTC_TAMPER_CLEAR_FLAG(__HANDLE__, __FLAG__) ((__HANDLE__)->Instance->ISR) = (~(((__FLAG__) | RTC_ISR_INIT)& 0x0000FFFF)|((__HANDLE__)->Instance->ISR & RTC_ISR_INIT)) #else /** * @brief Get the selected RTC Tamper's flag status. * @param __HANDLE__: specifies the RTC handle. * @param __FLAG__: specifies the RTC Tamper Flag is pending or not. * This parameter can be: * @arg RTC_FLAG_TAMP1F * @arg RTC_FLAG_TAMP2F * @retval None */ #define __HAL_RTC_TAMPER_GET_FLAG(__HANDLE__, __FLAG__) (((((__HANDLE__)->Instance->ISR) & (__FLAG__)) != RESET)? SET : RESET) /** * @brief Clear the RTC Tamper's pending flags. * @param __HANDLE__: specifies the RTC handle. * @param __FLAG__: specifies the RTC Tamper Flag to clear. * This parameter can be: * @arg RTC_FLAG_TAMP1F * @arg RTC_FLAG_TAMP2F * @retval None */ #define __HAL_RTC_TAMPER_CLEAR_FLAG(__HANDLE__, __FLAG__) ((__HANDLE__)->Instance->ISR) = (~(((__FLAG__) | RTC_ISR_INIT)& 0x0000FFFF)|((__HANDLE__)->Instance->ISR & RTC_ISR_INIT)) #endif /* defined(STM32F071xB) || defined(STM32F072xB) || defined(STM32F078xx) || defined(STM32F091xC) || defined(STM32F098xx) || defined(STM32F070xB) || defined(STM32F030xC) */ /** * @} */ /* --------------------------TAMPER/TIMESTAMP---------------------------------*/ /** @defgroup RTCEx_Tamper_Timestamp EXTI RTC Tamper Timestamp EXTI * @{ */ /* TAMPER TIMESTAMP EXTI */ /* --------------------- */ /** * @brief Enable interrupt on the RTC Tamper and Timestamp associated Exti line. * @retval None */ #define __HAL_RTC_TAMPER_TIMESTAMP_EXTI_ENABLE_IT() (EXTI->IMR |= RTC_EXTI_LINE_TAMPER_TIMESTAMP_EVENT) /** * @brief Disable interrupt on the RTC Tamper and Timestamp associated Exti line. * @retval None */ #define __HAL_RTC_TAMPER_TIMESTAMP_EXTI_DISABLE_IT() (EXTI->IMR &= ~(RTC_EXTI_LINE_TAMPER_TIMESTAMP_EVENT)) /** * @brief Enable event on the RTC Tamper and Timestamp associated Exti line. * @retval None. */ #define __HAL_RTC_TAMPER_TIMESTAMP_EXTI_ENABLE_EVENT() (EXTI->EMR |= RTC_EXTI_LINE_TAMPER_TIMESTAMP_EVENT) /** * @brief Disable event on the RTC Tamper and Timestamp associated Exti line. * @retval None. */ #define __HAL_RTC_TAMPER_TIMESTAMP_EXTI_DISABLE_EVENT() (EXTI->EMR &= ~(RTC_EXTI_LINE_TAMPER_TIMESTAMP_EVENT)) /** * @brief Enable falling edge trigger on the RTC Tamper and Timestamp associated Exti line. * @retval None. */ #define __HAL_RTC_TAMPER_TIMESTAMP_EXTI_ENABLE_FALLING_EDGE() (EXTI->FTSR |= RTC_EXTI_LINE_TAMPER_TIMESTAMP_EVENT) /** * @brief Disable falling edge trigger on the RTC Tamper and Timestamp associated Exti line. * @retval None. */ #define __HAL_RTC_TAMPER_TIMESTAMP_EXTI_DISABLE_FALLING_EDGE() (EXTI->FTSR &= ~(RTC_EXTI_LINE_TAMPER_TIMESTAMP_EVENT)) /** * @brief Enable rising edge trigger on the RTC Tamper and Timestamp associated Exti line. * @retval None. */ #define __HAL_RTC_TAMPER_TIMESTAMP_EXTI_ENABLE_RISING_EDGE() (EXTI->RTSR |= RTC_EXTI_LINE_TAMPER_TIMESTAMP_EVENT) /** * @brief Disable rising edge trigger on the RTC Tamper and Timestamp associated Exti line. * @retval None. */ #define __HAL_RTC_TAMPER_TIMESTAMP_EXTI_DISABLE_RISING_EDGE() (EXTI->RTSR &= ~(RTC_EXTI_LINE_TAMPER_TIMESTAMP_EVENT)) /** * @brief Enable rising & falling edge trigger on the RTC Tamper and Timestamp associated Exti line. * @retval None. */ #define __HAL_RTC_TAMPER_TIMESTAMP_EXTI_ENABLE_RISING_FALLING_EDGE() __HAL_RTC_TAMPER_TIMESTAMP_EXTI_ENABLE_RISING_EDGE();__HAL_RTC_TAMPER_TIMESTAMP_EXTI_ENABLE_FALLING_EDGE(); /** * @brief Disable rising & falling edge trigger on the RTC Tamper and Timestamp associated Exti line. * This parameter can be: * @retval None. */ #define __HAL_RTC_TAMPER_TIMESTAMP_EXTI_DISABLE_RISING_FALLING_EDGE() __HAL_RTC_TAMPER_TIMESTAMP_EXTI_DISABLE_RISING_EDGE();__HAL_RTC_TAMPER_TIMESTAMP_EXTI_DISABLE_FALLING_EDGE(); /** * @brief Check whether the RTC Tamper and Timestamp associated Exti line interrupt flag is set or not. * @retval Line Status. */ #define __HAL_RTC_TAMPER_TIMESTAMP_EXTI_GET_FLAG() (EXTI->PR & RTC_EXTI_LINE_TAMPER_TIMESTAMP_EVENT) /** * @brief Clear the RTC Tamper and Timestamp associated Exti line flag. * @retval None. */ #define __HAL_RTC_TAMPER_TIMESTAMP_EXTI_CLEAR_FLAG() (EXTI->PR = RTC_EXTI_LINE_TAMPER_TIMESTAMP_EVENT) /** * @brief Generate a Software interrupt on the RTC Tamper and Timestamp associated Exti line * @retval None. */ #define __HAL_RTC_TAMPER_TIMESTAMP_EXTI_GENERATE_SWIT() (EXTI->SWIER |= RTC_EXTI_LINE_TAMPER_TIMESTAMP_EVENT) /** * @} */ /* ------------------------------Calibration----------------------------------*/ /** @defgroup RTCEx_Calibration RTC Calibration * @{ */ /** * @brief Enable the RTC calibration output. * @param __HANDLE__: specifies the RTC handle. * @retval None */ #define __HAL_RTC_CALIBRATION_OUTPUT_ENABLE(__HANDLE__) ((__HANDLE__)->Instance->CR |= (RTC_CR_COE)) /** * @brief Disable the calibration output. * @param __HANDLE__: specifies the RTC handle. * @retval None */ #define __HAL_RTC_CALIBRATION_OUTPUT_DISABLE(__HANDLE__) ((__HANDLE__)->Instance->CR &= ~(RTC_CR_COE)) /** * @brief Enable the clock reference detection. * @param __HANDLE__: specifies the RTC handle. * @retval None */ #define __HAL_RTC_CLOCKREF_DETECTION_ENABLE(__HANDLE__) ((__HANDLE__)->Instance->CR |= (RTC_CR_REFCKON)) /** * @brief Disable the clock reference detection. * @param __HANDLE__: specifies the RTC handle. * @retval None */ #define __HAL_RTC_CLOCKREF_DETECTION_DISABLE(__HANDLE__) ((__HANDLE__)->Instance->CR &= ~(RTC_CR_REFCKON)) /** * @brief Get the selected RTC shift operation's flag status. * @param __HANDLE__: specifies the RTC handle. * @param __FLAG__: specifies the RTC shift operation Flag is pending or not. * This parameter can be: * @arg RTC_FLAG_SHPF * @retval None */ #define __HAL_RTC_SHIFT_GET_FLAG(__HANDLE__, __FLAG__) (((((__HANDLE__)->Instance->ISR) & (__FLAG__)) != RESET)? SET : RESET) /** * @} */ /** * @} */ /* Exported functions --------------------------------------------------------*/ /** @defgroup RTCEx_Exported_Functions RTCEx Exported Functions * @{ */ /* RTC TimeStamp and Tamper functions *****************************************/ /** @defgroup RTCEx_Exported_Functions_Group1 Extended RTC TimeStamp and Tamper functions * @{ */ HAL_StatusTypeDef HAL_RTCEx_SetTimeStamp(RTC_HandleTypeDef *hrtc, uint32_t TimeStampEdge, uint32_t RTC_TimeStampPin); HAL_StatusTypeDef HAL_RTCEx_SetTimeStamp_IT(RTC_HandleTypeDef *hrtc, uint32_t TimeStampEdge, uint32_t RTC_TimeStampPin); HAL_StatusTypeDef HAL_RTCEx_DeactivateTimeStamp(RTC_HandleTypeDef *hrtc); HAL_StatusTypeDef HAL_RTCEx_GetTimeStamp(RTC_HandleTypeDef *hrtc, RTC_TimeTypeDef *sTimeStamp, RTC_DateTypeDef *sTimeStampDate, uint32_t Format); HAL_StatusTypeDef HAL_RTCEx_SetTamper(RTC_HandleTypeDef *hrtc, RTC_TamperTypeDef* sTamper); HAL_StatusTypeDef HAL_RTCEx_SetTamper_IT(RTC_HandleTypeDef *hrtc, RTC_TamperTypeDef* sTamper); HAL_StatusTypeDef HAL_RTCEx_DeactivateTamper(RTC_HandleTypeDef *hrtc, uint32_t Tamper); void HAL_RTCEx_TamperTimeStampIRQHandler(RTC_HandleTypeDef *hrtc); void HAL_RTCEx_Tamper1EventCallback(RTC_HandleTypeDef *hrtc); void HAL_RTCEx_Tamper2EventCallback(RTC_HandleTypeDef *hrtc); #if defined(STM32F071xB) || defined(STM32F072xB) || defined(STM32F078xx) || defined(STM32F091xC) || defined(STM32F098xx) || defined(STM32F070xB) || defined(STM32F030xC) void HAL_RTCEx_Tamper3EventCallback(RTC_HandleTypeDef *hrtc); #endif void HAL_RTCEx_TimeStampEventCallback(RTC_HandleTypeDef *hrtc); HAL_StatusTypeDef HAL_RTCEx_PollForTimeStampEvent(RTC_HandleTypeDef *hrtc, uint32_t Timeout); HAL_StatusTypeDef HAL_RTCEx_PollForTamper1Event(RTC_HandleTypeDef *hrtc, uint32_t Timeout); HAL_StatusTypeDef HAL_RTCEx_PollForTamper2Event(RTC_HandleTypeDef *hrtc, uint32_t Timeout); #if defined(STM32F071xB) || defined(STM32F072xB) || defined(STM32F078xx) || defined(STM32F091xC) || defined(STM32F098xx) || defined(STM32F070xB) || defined(STM32F030xC) HAL_StatusTypeDef HAL_RTCEx_PollForTamper3Event(RTC_HandleTypeDef *hrtc, uint32_t Timeout); #endif /** * @} */ #if defined(STM32F071xB) || defined(STM32F072xB) || defined(STM32F078xx) || defined(STM32F091xC) || defined(STM32F098xx) || defined(STM32F070xB) || defined(STM32F030xC) /* RTC Wake-up functions ******************************************************/ /** @defgroup RTCEx_Exported_Functions_Group2 Extended RTC Wake-up functions * @{ */ HAL_StatusTypeDef HAL_RTCEx_SetWakeUpTimer(RTC_HandleTypeDef *hrtc, uint32_t WakeUpCounter, uint32_t WakeUpClock); HAL_StatusTypeDef HAL_RTCEx_SetWakeUpTimer_IT(RTC_HandleTypeDef *hrtc, uint32_t WakeUpCounter, uint32_t WakeUpClock); uint32_t HAL_RTCEx_DeactivateWakeUpTimer(RTC_HandleTypeDef *hrtc); uint32_t HAL_RTCEx_GetWakeUpTimer(RTC_HandleTypeDef *hrtc); void HAL_RTCEx_WakeUpTimerIRQHandler(RTC_HandleTypeDef *hrtc); void HAL_RTCEx_WakeUpTimerEventCallback(RTC_HandleTypeDef *hrtc); HAL_StatusTypeDef HAL_RTCEx_PollForWakeUpTimerEvent(RTC_HandleTypeDef *hrtc, uint32_t Timeout); #endif /** * @} */ /* Extended Control functions ************************************************/ /** @defgroup RTCEx_Exported_Functions_Group3 Extended Peripheral Control functions * @{ */ #if !defined(STM32F030x6) && !defined(STM32F030x8) && !defined(STM32F030xC) && !defined(STM32F070x6) && !defined(STM32F070xB) void HAL_RTCEx_BKUPWrite(RTC_HandleTypeDef *hrtc, uint32_t BackupRegister, uint32_t Data); uint32_t HAL_RTCEx_BKUPRead(RTC_HandleTypeDef *hrtc, uint32_t BackupRegister); #endif /* !defined(STM32F030x6) && !defined(STM32F030x8) && !defined(STM32F030xC) && !defined(STM32F070x6) && !defined(STM32F070xB) */ HAL_StatusTypeDef HAL_RTCEx_SetSmoothCalib(RTC_HandleTypeDef *hrtc, uint32_t SmoothCalibPeriod, uint32_t SmoothCalibPlusPulses, uint32_t SmouthCalibMinusPulsesValue); HAL_StatusTypeDef HAL_RTCEx_SetSynchroShift(RTC_HandleTypeDef *hrtc, uint32_t ShiftAdd1S, uint32_t ShiftSubFS); HAL_StatusTypeDef HAL_RTCEx_SetCalibrationOutPut(RTC_HandleTypeDef *hrtc, uint32_t CalibOutput); HAL_StatusTypeDef HAL_RTCEx_DeactivateCalibrationOutPut(RTC_HandleTypeDef *hrtc); HAL_StatusTypeDef HAL_RTCEx_SetRefClock(RTC_HandleTypeDef *hrtc); HAL_StatusTypeDef HAL_RTCEx_DeactivateRefClock(RTC_HandleTypeDef *hrtc); HAL_StatusTypeDef HAL_RTCEx_EnableBypassShadow(RTC_HandleTypeDef *hrtc); HAL_StatusTypeDef HAL_RTCEx_DisableBypassShadow(RTC_HandleTypeDef *hrtc); /** * @} */ /* Extended RTC features functions *******************************************/ /** * @} */ /* Private types -------------------------------------------------------------*/ /* Private variables ---------------------------------------------------------*/ /* Private constants ---------------------------------------------------------*/ /** @defgroup RTCEx_Private_Constants RTCEx Private Constants * @{ */ #define RTC_EXTI_LINE_TAMPER_TIMESTAMP_EVENT ((uint32_t)EXTI_IMR_MR19) /*!< External interrupt line 19 Connected to the RTC Tamper and Time Stamp events */ #define RTC_EXTI_LINE_WAKEUPTIMER_EVENT ((uint32_t)EXTI_IMR_MR20) /*!< External interrupt line 20 Connected to the RTC Wakeup event */ /** * @} */ /* Private macros ------------------------------------------------------------*/ /** @defgroup RTCEx_Private_Macros RTCEx Private Macros * @{ */ /** @defgroup RTCEx_IS_RTC_Definitions Private macros to check input parameters * @{ */ #if defined(STM32F071xB) || defined(STM32F072xB) || defined(STM32F078xx) || defined(STM32F091xC) || defined(STM32F098xx) || defined(STM32F070xB) || defined(STM32F030xC) #define IS_RTC_OUTPUT(OUTPUT) (((OUTPUT) == RTC_OUTPUT_DISABLE) || \ ((OUTPUT) == RTC_OUTPUT_ALARMA) || \ ((OUTPUT) == RTC_OUTPUT_WAKEUP)) #else #define IS_RTC_OUTPUT(OUTPUT) (((OUTPUT) == RTC_OUTPUT_DISABLE) || \ ((OUTPUT) == RTC_OUTPUT_ALARMA)) #endif #define IS_RTC_BKP(BKP) ((BKP) < (uint32_t) RTC_BKP_NUMBER) #define IS_TIMESTAMP_EDGE(EDGE) (((EDGE) == RTC_TIMESTAMPEDGE_RISING) || \ ((EDGE) == RTC_TIMESTAMPEDGE_FALLING)) #if defined(STM32F071xB) || defined(STM32F072xB) || defined(STM32F078xx) || defined(STM32F091xC) || defined(STM32F098xx) #define IS_RTC_TAMPER(TAMPER) ((((TAMPER) & (uint32_t)0xFFFFFFD6) == 0x00) && ((TAMPER) != (uint32_t)RESET)) #else #define IS_RTC_TAMPER(TAMPER) ((((TAMPER) & (uint32_t)0xFFFFFFF6) == 0x00) && ((TAMPER) != (uint32_t)RESET)) #endif #define IS_RTC_TIMESTAMP_PIN(PIN) (((PIN) == RTC_TIMESTAMPPIN_DEFAULT)) #define IS_RTC_TAMPER_TRIGGER(TRIGGER) (((TRIGGER) == RTC_TAMPERTRIGGER_RISINGEDGE) || \ ((TRIGGER) == RTC_TAMPERTRIGGER_FALLINGEDGE) || \ ((TRIGGER) == RTC_TAMPERTRIGGER_LOWLEVEL) || \ ((TRIGGER) == RTC_TAMPERTRIGGER_HIGHLEVEL)) #define IS_RTC_TAMPER_FILTER(FILTER) (((FILTER) == RTC_TAMPERFILTER_DISABLE) || \ ((FILTER) == RTC_TAMPERFILTER_2SAMPLE) || \ ((FILTER) == RTC_TAMPERFILTER_4SAMPLE) || \ ((FILTER) == RTC_TAMPERFILTER_8SAMPLE)) #define IS_RTC_TAMPER_SAMPLING_FREQ(FREQ) (((FREQ) == RTC_TAMPERSAMPLINGFREQ_RTCCLK_DIV32768)|| \ ((FREQ) == RTC_TAMPERSAMPLINGFREQ_RTCCLK_DIV16384)|| \ ((FREQ) == RTC_TAMPERSAMPLINGFREQ_RTCCLK_DIV8192) || \ ((FREQ) == RTC_TAMPERSAMPLINGFREQ_RTCCLK_DIV4096) || \ ((FREQ) == RTC_TAMPERSAMPLINGFREQ_RTCCLK_DIV2048) || \ ((FREQ) == RTC_TAMPERSAMPLINGFREQ_RTCCLK_DIV1024) || \ ((FREQ) == RTC_TAMPERSAMPLINGFREQ_RTCCLK_DIV512) || \ ((FREQ) == RTC_TAMPERSAMPLINGFREQ_RTCCLK_DIV256)) #define IS_RTC_TAMPER_PRECHARGE_DURATION(DURATION) (((DURATION) == RTC_TAMPERPRECHARGEDURATION_1RTCCLK) || \ ((DURATION) == RTC_TAMPERPRECHARGEDURATION_2RTCCLK) || \ ((DURATION) == RTC_TAMPERPRECHARGEDURATION_4RTCCLK) || \ ((DURATION) == RTC_TAMPERPRECHARGEDURATION_8RTCCLK)) #define IS_RTC_TAMPER_TIMESTAMPONTAMPER_DETECTION(DETECTION) (((DETECTION) == RTC_TIMESTAMPONTAMPERDETECTION_ENABLE) || \ ((DETECTION) == RTC_TIMESTAMPONTAMPERDETECTION_DISABLE)) #define IS_RTC_TAMPER_PULLUP_STATE(STATE) (((STATE) == RTC_TAMPER_PULLUP_ENABLE) || \ ((STATE) == RTC_TAMPER_PULLUP_DISABLE)) #define IS_RTC_WAKEUP_CLOCK(CLOCK) (((CLOCK) == RTC_WAKEUPCLOCK_RTCCLK_DIV16) || \ ((CLOCK) == RTC_WAKEUPCLOCK_RTCCLK_DIV8) || \ ((CLOCK) == RTC_WAKEUPCLOCK_RTCCLK_DIV4) || \ ((CLOCK) == RTC_WAKEUPCLOCK_RTCCLK_DIV2) || \ ((CLOCK) == RTC_WAKEUPCLOCK_CK_SPRE_16BITS) || \ ((CLOCK) == RTC_WAKEUPCLOCK_CK_SPRE_17BITS)) #define IS_RTC_WAKEUP_COUNTER(COUNTER) ((COUNTER) <= 0xFFFF) #define IS_RTC_SMOOTH_CALIB_PERIOD(PERIOD) (((PERIOD) == RTC_SMOOTHCALIB_PERIOD_32SEC) || \ ((PERIOD) == RTC_SMOOTHCALIB_PERIOD_16SEC) || \ ((PERIOD) == RTC_SMOOTHCALIB_PERIOD_8SEC)) #define IS_RTC_SMOOTH_CALIB_PLUS(PLUS) (((PLUS) == RTC_SMOOTHCALIB_PLUSPULSES_SET) || \ ((PLUS) == RTC_SMOOTHCALIB_PLUSPULSES_RESET)) #define IS_RTC_SMOOTH_CALIB_MINUS(VALUE) ((VALUE) <= 0x000001FF) #define IS_RTC_SHIFT_ADD1S(SEL) (((SEL) == RTC_SHIFTADD1S_RESET) || \ ((SEL) == RTC_SHIFTADD1S_SET)) #define IS_RTC_SHIFT_SUBFS(FS) ((FS) <= 0x00007FFF) #define IS_RTC_CALIB_OUTPUT(OUTPUT) (((OUTPUT) == RTC_CALIBOUTPUT_512HZ) || \ ((OUTPUT) == RTC_CALIBOUTPUT_1HZ)) /** * @} */ /** * @} */ /** * @} */ /** * @} */ #ifdef __cplusplus } #endif #endif /* __STM32F0xx_HAL_RTC_EX_H */ /************************ (C) COPYRIGHT STMicroelectronics *****END OF FILE****/ ================================================ FILE: Zelig/mbed/TARGET_NUCLEO_F091RC/stm32f0xx_hal_smartcard.h ================================================ /** ****************************************************************************** * @file stm32f0xx_hal_smartcard.h * @author MCD Application Team * @version V1.3.0 * @date 26-June-2015 * @brief Header file of SMARTCARD HAL module. ****************************************************************************** * @attention * *

© COPYRIGHT(c) 2015 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. * ****************************************************************************** */ /* Define to prevent recursive inclusion -------------------------------------*/ #ifndef __STM32F0xx_HAL_SMARTCARD_H #define __STM32F0xx_HAL_SMARTCARD_H #ifdef __cplusplus extern "C" { #endif #if !defined(STM32F030x6) && !defined(STM32F030x8) && !defined(STM32F070x6) && !defined(STM32F070xB) && !defined(STM32F030xC) /* Includes ------------------------------------------------------------------*/ #include "stm32f0xx_hal_def.h" /** @addtogroup STM32F0xx_HAL_Driver * @{ */ /** @addtogroup SMARTCARD * @{ */ /* Exported types ------------------------------------------------------------*/ /** @defgroup SMARTCARD_Exported_Types SMARTCARD Exported Types * @{ */ /** * @brief SMARTCARD Init Structure definition */ typedef struct { uint32_t BaudRate; /*!< Configures the SmartCard communication baud rate. The baud rate register is computed using the following formula: Baud Rate Register = ((PCLKx) / ((hsmartcard->Init.BaudRate))) */ uint32_t WordLength; /*!< Specifies the number of data bits transmitted or received in a frame. This parameter @ref SMARTCARD_Word_Length can only be set to 9 (8 data + 1 parity bits). */ uint32_t StopBits; /*!< Specifies the number of stop bits @ref SMARTCARD_Stop_Bits. Only 1.5 stop bits are authorized in SmartCard mode. */ uint16_t Parity; /*!< Specifies the parity mode. This parameter can be a value of @ref SMARTCARD_Parity @note The parity is enabled by default (PCE is forced to 1). Since the WordLength is forced to 8 bits + parity, M is forced to 1 and the parity bit is the 9th bit. */ uint16_t Mode; /*!< Specifies whether the Receive or Transmit mode is enabled or disabled. This parameter can be a value of @ref SMARTCARD_Mode */ uint16_t CLKPolarity; /*!< Specifies the steady state of the serial clock. This parameter can be a value of @ref SMARTCARD_Clock_Polarity */ uint16_t CLKPhase; /*!< Specifies the clock transition on which the bit capture is made. This parameter can be a value of @ref SMARTCARD_Clock_Phase */ uint16_t CLKLastBit; /*!< Specifies whether the clock pulse corresponding to the last transmitted data bit (MSB) has to be output on the SCLK pin in synchronous mode. This parameter can be a value of @ref SMARTCARD_Last_Bit */ uint16_t OneBitSampling; /*!< Specifies whether a single sample or three samples' majority vote is selected. Selecting the single sample method increases the receiver tolerance to clock deviations. This parameter can be a value of @ref SMARTCARD_OneBit_Sampling. */ uint8_t Prescaler; /*!< Specifies the SmartCard Prescaler */ uint8_t GuardTime; /*!< Specifies the SmartCard Guard Time */ uint16_t NACKEnable; /*!< Specifies whether the SmartCard NACK transmission is enabled in case of parity error. This parameter can be a value of @ref SMARTCARD_NACK_Enable */ uint32_t TimeOutEnable; /*!< Specifies whether the receiver timeout is enabled. This parameter can be a value of @ref SMARTCARD_Timeout_Enable*/ uint32_t TimeOutValue; /*!< Specifies the receiver time out value in number of baud blocks: it is used to implement the Character Wait Time (CWT) and Block Wait Time (BWT). It is coded over 24 bits. */ uint8_t BlockLength; /*!< Specifies the SmartCard Block Length in T=1 Reception mode. This parameter can be any value from 0x0 to 0xFF */ uint8_t AutoRetryCount; /*!< Specifies the SmartCard auto-retry count (number of retries in receive and transmit mode). When set to 0, retransmission is disabled. Otherwise, its maximum value is 7 (before signalling an error) */ }SMARTCARD_InitTypeDef; /** * @brief SMARTCARD advanced features initalization structure definition */ typedef struct { uint32_t AdvFeatureInit; /*!< Specifies which advanced SMARTCARD features is initialized. Several advanced features may be initialized at the same time. This parameter can be a value of @ref SMARTCARD_Advanced_Features_Initialization_Type */ uint32_t TxPinLevelInvert; /*!< Specifies whether the TX pin active level is inverted. This parameter can be a value of @ref SMARTCARD_Tx_Inv */ uint32_t RxPinLevelInvert; /*!< Specifies whether the RX pin active level is inverted. This parameter can be a value of @ref SMARTCARD_Rx_Inv */ uint32_t DataInvert; /*!< Specifies whether data are inverted (positive/direct logic vs negative/inverted logic). This parameter can be a value of @ref SMARTCARD_Data_Inv */ uint32_t Swap; /*!< Specifies whether TX and RX pins are swapped. This parameter can be a value of @ref SMARTCARD_Rx_Tx_Swap */ uint32_t OverrunDisable; /*!< Specifies whether the reception overrun detection is disabled. This parameter can be a value of @ref SMARTCARD_Overrun_Disable */ uint32_t DMADisableonRxError; /*!< Specifies whether the DMA is disabled in case of reception error. This parameter can be a value of @ref SMARTCARD_DMA_Disable_on_Rx_Error */ uint32_t MSBFirst; /*!< Specifies whether MSB is sent first on UART line. This parameter can be a value of @ref SMARTCARD_MSB_First */ }SMARTCARD_AdvFeatureInitTypeDef; /** * @brief HAL State structures definition */ typedef enum { HAL_SMARTCARD_STATE_RESET = 0x00, /*!< Peripheral is not initialized */ HAL_SMARTCARD_STATE_READY = 0x01, /*!< Peripheral Initialized and ready for use */ HAL_SMARTCARD_STATE_BUSY = 0x02, /*!< an internal process is ongoing */ HAL_SMARTCARD_STATE_BUSY_TX = 0x12, /*!< Data Transmission process is ongoing */ HAL_SMARTCARD_STATE_BUSY_RX = 0x22, /*!< Data Reception process is ongoing */ HAL_SMARTCARD_STATE_BUSY_TX_RX = 0x32, /*!< Data Transmission and Reception process is ongoing */ HAL_SMARTCARD_STATE_TIMEOUT = 0x03, /*!< Timeout state */ HAL_SMARTCARD_STATE_ERROR = 0x04 /*!< Error */ }HAL_SMARTCARD_StateTypeDef; /** * @brief SMARTCARD clock sources */ typedef enum { SMARTCARD_CLOCKSOURCE_PCLK1 = 0x00, /*!< PCLK1 clock source */ SMARTCARD_CLOCKSOURCE_HSI = 0x02, /*!< HSI clock source */ SMARTCARD_CLOCKSOURCE_SYSCLK = 0x04, /*!< SYSCLK clock source */ SMARTCARD_CLOCKSOURCE_LSE = 0x08, /*!< LSE clock source */ SMARTCARD_CLOCKSOURCE_UNDEFINED = 0x10 /*!< undefined clock source */ }SMARTCARD_ClockSourceTypeDef; /** * @brief SMARTCARD handle Structure definition */ typedef struct { USART_TypeDef *Instance; /*!< USART registers base address */ SMARTCARD_InitTypeDef Init; /*!< SmartCard communication parameters */ SMARTCARD_AdvFeatureInitTypeDef AdvancedInit; /*!< SmartCard advanced features initialization parameters */ uint8_t *pTxBuffPtr; /*!< Pointer to SmartCard Tx transfer Buffer */ uint16_t TxXferSize; /*!< SmartCard Tx Transfer size */ uint16_t TxXferCount; /*!< SmartCard Tx Transfer Counter */ uint8_t *pRxBuffPtr; /*!< Pointer to SmartCard Rx transfer Buffer */ uint16_t RxXferSize; /*!< SmartCard Rx Transfer size */ uint16_t RxXferCount; /*!< SmartCard Rx Transfer Counter */ DMA_HandleTypeDef *hdmatx; /*!< SmartCard Tx DMA Handle parameters */ DMA_HandleTypeDef *hdmarx; /*!< SmartCard Rx DMA Handle parameters */ HAL_LockTypeDef Lock; /*!< Locking object */ __IO HAL_SMARTCARD_StateTypeDef State; /*!< SmartCard communication state */ __IO uint32_t ErrorCode; /*!< SmartCard Error code This parameter can be a value of @ref SMARTCARD_Error */ }SMARTCARD_HandleTypeDef; /** * @} */ /* Exported constants --------------------------------------------------------*/ /** @defgroup SMARTCARD_Exported_Constants SMARTCARD Exported Constants * @{ */ /** @defgroup SMARTCARD_Error SMARTCARD Error * @{ */ #define HAL_SMARTCARD_ERROR_NONE ((uint32_t)0x00000000) /*!< No error */ #define HAL_SMARTCARD_ERROR_PE ((uint32_t)0x00000001) /*!< Parity error */ #define HAL_SMARTCARD_ERROR_NE ((uint32_t)0x00000002) /*!< Noise error */ #define HAL_SMARTCARD_ERROR_FE ((uint32_t)0x00000004) /*!< frame error */ #define HAL_SMARTCARD_ERROR_ORE ((uint32_t)0x00000008) /*!< Overrun error */ #define HAL_SMARTCARD_ERROR_DMA ((uint32_t)0x00000010) /*!< DMA transfer error */ #define HAL_SMARTCARD_ERROR_RTO ((uint32_t)0x00000020) /*!< Receiver TimeOut error */ /** * @} */ /** @defgroup SMARTCARD_Word_Length SMARTCARD Word Length * @{ */ #define SMARTCARD_WORDLENGTH_9B ((uint32_t)USART_CR1_M0) /*!< SMARTCARD frame length */ /** * @} */ /** @defgroup SMARTCARD_Stop_Bits SMARTCARD Stop Bits * @{ */ #define SMARTCARD_STOPBITS_1_5 USART_CR2_STOP /*!< SMARTCARD frame with 1.5 stop bits */ /** * @} */ /** @defgroup SMARTCARD_Parity SMARTCARD Parity * @{ */ #define SMARTCARD_PARITY_EVEN ((uint32_t)USART_CR1_PCE) /*!< SMARTCARD frame even parity */ #define SMARTCARD_PARITY_ODD ((uint32_t)(USART_CR1_PCE | USART_CR1_PS)) /*!< SMARTCARD frame odd parity */ /** * @} */ /** @defgroup SMARTCARD_Mode SMARTCARD Transfer Mode * @{ */ #define SMARTCARD_MODE_RX ((uint32_t)USART_CR1_RE) /*!< SMARTCARD RX mode */ #define SMARTCARD_MODE_TX ((uint32_t)USART_CR1_TE) /*!< SMARTCARD TX mode */ #define SMARTCARD_MODE_TX_RX ((uint32_t)(USART_CR1_TE |USART_CR1_RE)) /*!< SMARTCARD RX and TX mode */ /** * @} */ /** @defgroup SMARTCARD_Clock_Polarity SMARTCARD Clock Polarity * @{ */ #define SMARTCARD_POLARITY_LOW ((uint32_t)0x00000000) /*!< SMARTCARD frame low polarity */ #define SMARTCARD_POLARITY_HIGH ((uint32_t)USART_CR2_CPOL) /*!< SMARTCARD frame high polarity */ /** * @} */ /** @defgroup SMARTCARD_Clock_Phase SMARTCARD Clock Phase * @{ */ #define SMARTCARD_PHASE_1EDGE ((uint32_t)0x00000000) /*!< SMARTCARD frame phase on first clock transition */ #define SMARTCARD_PHASE_2EDGE ((uint32_t)USART_CR2_CPHA) /*!< SMARTCARD frame phase on second clock transition */ /** * @} */ /** @defgroup SMARTCARD_Last_Bit SMARTCARD Last Bit * @{ */ #define SMARTCARD_LASTBIT_DISABLE ((uint32_t)0x00000000) /*!< SMARTCARD frame last data bit clock pulse not output to SCLK pin */ #define SMARTCARD_LASTBIT_ENABLE ((uint32_t)USART_CR2_LBCL) /*!< SMARTCARD frame last data bit clock pulse output to SCLK pin */ /** * @} */ /** @defgroup SMARTCARD_OneBit_Sampling SMARTCARD One Bit Sampling Method * @{ */ #define SMARTCARD_ONE_BIT_SAMPLE_DISABLE ((uint32_t)0x00000000) /*!< SMARTCARD frame one-bit sample disabled */ #define SMARTCARD_ONE_BIT_SAMPLE_ENABLE ((uint32_t)USART_CR3_ONEBIT) /*!< SMARTCARD frame one-bit sample enabled */ /** * @} */ /** @defgroup SMARTCARD_NACK_Enable SMARTCARD NACK Enable * @{ */ #define SMARTCARD_NACK_ENABLE ((uint32_t)USART_CR3_NACK) /*!< SMARTCARD NACK transmission disabled */ #define SMARTCARD_NACK_DISABLE ((uint32_t)0x00000000) /*!< SMARTCARD NACK transmission enabled */ /** * @} */ /** @defgroup SMARTCARD_Timeout_Enable SMARTCARD Timeout Enable * @{ */ #define SMARTCARD_TIMEOUT_DISABLE ((uint32_t)0x00000000) /*!< SMARTCARD receiver timeout disabled */ #define SMARTCARD_TIMEOUT_ENABLE ((uint32_t)USART_CR2_RTOEN) /*!< SMARTCARD receiver timeout enabled */ /** * @} */ /** @defgroup SMARTCARD_Advanced_Features_Initialization_Type SMARTCARD advanced feature initialization type * @{ */ #define SMARTCARD_ADVFEATURE_NO_INIT ((uint32_t)0x00000000) /*!< No advanced feature initialization */ #define SMARTCARD_ADVFEATURE_TXINVERT_INIT ((uint32_t)0x00000001) /*!< TX pin active level inversion */ #define SMARTCARD_ADVFEATURE_RXINVERT_INIT ((uint32_t)0x00000002) /*!< RX pin active level inversion */ #define SMARTCARD_ADVFEATURE_DATAINVERT_INIT ((uint32_t)0x00000004) /*!< Binary data inversion */ #define SMARTCARD_ADVFEATURE_SWAP_INIT ((uint32_t)0x00000008) /*!< TX/RX pins swap */ #define SMARTCARD_ADVFEATURE_RXOVERRUNDISABLE_INIT ((uint32_t)0x00000010) /*!< RX overrun disable */ #define SMARTCARD_ADVFEATURE_DMADISABLEONERROR_INIT ((uint32_t)0x00000020) /*!< DMA disable on Reception Error */ #define SMARTCARD_ADVFEATURE_MSBFIRST_INIT ((uint32_t)0x00000080) /*!< Most significant bit sent/received first */ /** * @} */ /** @defgroup SMARTCARD_Tx_Inv SMARTCARD advanced feature TX pin active level inversion * @{ */ #define SMARTCARD_ADVFEATURE_TXINV_DISABLE ((uint32_t)0x00000000) /*!< TX pin active level inversion disable */ #define SMARTCARD_ADVFEATURE_TXINV_ENABLE ((uint32_t)USART_CR2_TXINV) /*!< TX pin active level inversion enable */ /** * @} */ /** @defgroup SMARTCARD_Rx_Inv SMARTCARD advanced feature RX pin active level inversion * @{ */ #define SMARTCARD_ADVFEATURE_RXINV_DISABLE ((uint32_t)0x00000000) /*!< RX pin active level inversion disable */ #define SMARTCARD_ADVFEATURE_RXINV_ENABLE ((uint32_t)USART_CR2_RXINV) /*!< RX pin active level inversion enable */ /** * @} */ /** @defgroup SMARTCARD_Data_Inv SMARTCARD advanced feature Binary Data inversion * @{ */ #define SMARTCARD_ADVFEATURE_DATAINV_DISABLE ((uint32_t)0x00000000) /*!< Binary data inversion disable */ #define SMARTCARD_ADVFEATURE_DATAINV_ENABLE ((uint32_t)USART_CR2_DATAINV) /*!< Binary data inversion enable */ /** * @} */ /** @defgroup SMARTCARD_Rx_Tx_Swap SMARTCARD advanced feature RX TX pins swap * @{ */ #define SMARTCARD_ADVFEATURE_SWAP_DISABLE ((uint32_t)0x00000000) /*!< TX/RX pins swap disable */ #define SMARTCARD_ADVFEATURE_SWAP_ENABLE ((uint32_t)USART_CR2_SWAP) /*!< TX/RX pins swap enable */ /** * @} */ /** @defgroup SMARTCARD_Overrun_Disable SMARTCARD advanced feature Overrun Disable * @{ */ #define SMARTCARD_ADVFEATURE_OVERRUN_ENABLE ((uint32_t)0x00000000) /*!< RX overrun enable */ #define SMARTCARD_ADVFEATURE_OVERRUN_DISABLE ((uint32_t)USART_CR3_OVRDIS) /*!< RX overrun disable */ /** * @} */ /** @defgroup SMARTCARD_DMA_Disable_on_Rx_Error SMARTCARD advanced feature DMA Disable on Rx Error * @{ */ #define SMARTCARD_ADVFEATURE_DMA_ENABLEONRXERROR ((uint32_t)0x00000000) /*!< DMA enable on Reception Error */ #define SMARTCARD_ADVFEATURE_DMA_DISABLEONRXERROR ((uint32_t)USART_CR3_DDRE) /*!< DMA disable on Reception Error */ /** * @} */ /** @defgroup SMARTCARD_MSB_First SMARTCARD advanced feature MSB first * @{ */ #define SMARTCARD_ADVFEATURE_MSBFIRST_DISABLE ((uint32_t)0x00000000) /*!< Most significant bit sent/received first disable */ #define SMARTCARD_ADVFEATURE_MSBFIRST_ENABLE ((uint32_t)USART_CR2_MSBFIRST) /*!< Most significant bit sent/received first enable */ /** * @} */ /** @defgroup SMARTCARD_Flags SMARTCARD Flags * Elements values convention: 0xXXXX * - 0xXXXX : Flag mask in the ISR register * @{ */ #define SMARTCARD_FLAG_REACK USART_ISR_REACK /*!< SMARTCARD receive enable acknowledge flag */ #define SMARTCARD_FLAG_TEACK USART_ISR_TEACK /*!< SMARTCARD transmit enable acknowledge flag */ #define SMARTCARD_FLAG_BUSY USART_ISR_BUSY /*!< SMARTCARD busy flag */ #define SMARTCARD_FLAG_EOBF USART_ISR_EOBF /*!< SMARTCARD end of block flag */ #define SMARTCARD_FLAG_RTOF USART_ISR_RTOF /*!< SMARTCARD receiver timeout flag */ #define SMARTCARD_FLAG_TXE USART_ISR_TXE /*!< SMARTCARD transmit data register empty */ #define SMARTCARD_FLAG_TC USART_ISR_TC /*!< SMARTCARD transmission complete */ #define SMARTCARD_FLAG_RXNE USART_ISR_RXNE /*!< SMARTCARD read data register not empty */ #define SMARTCARD_FLAG_IDLE USART_ISR_IDLE /*!< SMARTCARD idle line detection */ #define SMARTCARD_FLAG_ORE USART_ISR_ORE /*!< SMARTCARD overrun error */ #define SMARTCARD_FLAG_NE USART_ISR_NE /*!< SMARTCARD noise error */ #define SMARTCARD_FLAG_FE USART_ISR_FE /*!< SMARTCARD frame error */ #define SMARTCARD_FLAG_PE USART_ISR_PE /*!< SMARTCARD parity error */ /** * @} */ /** @defgroup SMARTCARD_Interrupt_definition SMARTCARD Interrupts Definition * Elements values convention: 0000ZZZZ0XXYYYYYb * - YYYYY : Interrupt source position in the XX register (5bits) * - XX : Interrupt source register (2bits) * - 01: CR1 register * - 10: CR2 register * - 11: CR3 register * - ZZZZ : Flag position in the ISR register(4bits) * @{ */ #define SMARTCARD_IT_PE ((uint16_t)0x0028) /*!< SMARTCARD parity error interruption */ #define SMARTCARD_IT_TXE ((uint16_t)0x0727) /*!< SMARTCARD transmit data register empty interruption */ #define SMARTCARD_IT_TC ((uint16_t)0x0626) /*!< SMARTCARD transmission complete interruption */ #define SMARTCARD_IT_RXNE ((uint16_t)0x0525) /*!< SMARTCARD read data register not empty interruption */ #define SMARTCARD_IT_IDLE ((uint16_t)0x0424) /*!< SMARTCARD idle line detection interruption */ #define SMARTCARD_IT_ERR ((uint16_t)0x0060) /*!< SMARTCARD error interruption */ #define SMARTCARD_IT_ORE ((uint16_t)0x0300) /*!< SMARTCARD overrun error interruption */ #define SMARTCARD_IT_NE ((uint16_t)0x0200) /*!< SMARTCARD noise error interruption */ #define SMARTCARD_IT_FE ((uint16_t)0x0100) /*!< SMARTCARD frame error interruption */ #define SMARTCARD_IT_EOB ((uint16_t)0x0C3B) /*!< SMARTCARD end of block interruption */ #define SMARTCARD_IT_RTO ((uint16_t)0x0B3A) /*!< SMARTCARD receiver timeout interruption */ /** * @} */ /** @defgroup SMARTCARD_IT_CLEAR_Flags SMARTCARD Interruption Clear Flags * @{ */ #define SMARTCARD_CLEAR_PEF USART_ICR_PECF /*!< SMARTCARD parity error clear flag */ #define SMARTCARD_CLEAR_FEF USART_ICR_FECF /*!< SMARTCARD framing error clear flag */ #define SMARTCARD_CLEAR_NEF USART_ICR_NCF /*!< SMARTCARD noise detected clear flag */ #define SMARTCARD_CLEAR_OREF USART_ICR_ORECF /*!< SMARTCARD overrun error clear flag */ #define SMARTCARD_CLEAR_IDLEF USART_ICR_IDLECF /*!< SMARTCARD idle line detected clear flag */ #define SMARTCARD_CLEAR_TCF USART_ICR_TCCF /*!< SMARTCARD transmission complete clear flag */ #define SMARTCARD_CLEAR_RTOF USART_ICR_RTOCF /*!< SMARTCARD receiver time out clear flag */ #define SMARTCARD_CLEAR_EOBF USART_ICR_EOBCF /*!< SMARTCARD end of block clear flag */ /** * @} */ /** @defgroup SMARTCARD_CR3_SCARCNT_LSB_POS SMARTCARD auto retry counter LSB position in CR3 register * @{ */ #define SMARTCARD_CR3_SCARCNT_LSB_POS ((uint32_t) 17) /*!< SMARTCARD auto retry counter LSB position in CR3 register */ /** * @} */ /** @defgroup SMARTCARD_GTPR_GT_LSB_POS SMARTCARD guard time value LSB position in GTPR register * @{ */ #define SMARTCARD_GTPR_GT_LSB_POS ((uint32_t) 8) /*!< SMARTCARD guard time value LSB position in GTPR register */ /** * @} */ /** @defgroup SMARTCARD_RTOR_BLEN_LSB_POS SMARTCARD block length LSB position in RTOR register * @{ */ #define SMARTCARD_RTOR_BLEN_LSB_POS ((uint32_t) 24) /*!< SMARTCARD block length LSB position in RTOR register */ /** * @} */ /** @defgroup SMARTCARD_Interruption_Mask SMARTCARD interruptions flags mask * @{ */ #define SMARTCARD_IT_MASK ((uint16_t)0x001F) /*!< SMARTCARD interruptions flags mask */ /** * @} */ /** @defgroup SMARTCARD_Request_Parameters SMARTCARD Request Parameters * @{ */ #define SMARTCARD_RXDATA_FLUSH_REQUEST ((uint16_t)USART_RQR_RXFRQ) /*!< Receive Data flush Request */ #define SMARTCARD_TXDATA_FLUSH_REQUEST ((uint16_t)USART_RQR_TXFRQ) /*!< Transmit data flush Request */ /** * @} */ /** * @} */ /* Exported macros -----------------------------------------------------------*/ /** @defgroup SMARTCARD_Exported_Macros SMARTCARD Exported Macros * @{ */ /** @brief Reset SMARTCARD handle state. * @param __HANDLE__: SMARTCARD handle. * @retval None */ #define __HAL_SMARTCARD_RESET_HANDLE_STATE(__HANDLE__) ((__HANDLE__)->State = HAL_SMARTCARD_STATE_RESET) /** @brief Flush the Smartcard Data registers. * @param __HANDLE__: specifies the SMARTCARD Handle. * @retval None */ #define __HAL_SMARTCARD_FLUSH_DRREGISTER(__HANDLE__) \ do{ \ SET_BIT((__HANDLE__)->Instance->RQR, SMARTCARD_RXDATA_FLUSH_REQUEST); \ SET_BIT((__HANDLE__)->Instance->RQR, SMARTCARD_TXDATA_FLUSH_REQUEST); \ } while(0) /** @brief Clear the specified SMARTCARD pending flag. * @param __HANDLE__: specifies the SMARTCARD Handle. * @param __FLAG__: specifies the flag to check. * This parameter can be any combination of the following values: * @arg SMARTCARD_CLEAR_PEF: Parity error clear flag * @arg SMARTCARD_CLEAR_FEF: Framing error clear flag * @arg SMARTCARD_CLEAR_NEF: Noise detected clear flag * @arg SMARTCARD_CLEAR_OREF: OverRun error clear flag * @arg SMARTCARD_CLEAR_IDLEF: Idle line detected clear flag * @arg SMARTCARD_CLEAR_TCF: Transmission complete clear flag * @arg SMARTCARD_CLEAR_RTOF: Receiver timeout clear flag * @arg SMARTCARD_CLEAR_EOBF: End of block clear flag * @retval None */ #define __HAL_SMARTCARD_CLEAR_FLAG(__HANDLE__, __FLAG__) ((__HANDLE__)->Instance->ICR = (__FLAG__)) /** @brief Clear the SMARTCARD PE pending flag. * @param __HANDLE__: specifies the SMARTCARD Handle. * @retval None */ #define __HAL_SMARTCARD_CLEAR_PEFLAG(__HANDLE__) __HAL_SMARTCARD_CLEAR_FLAG((__HANDLE__), SMARTCARD_CLEAR_PEF) /** @brief Clear the SMARTCARD FE pending flag. * @param __HANDLE__: specifies the SMARTCARD Handle. * @retval None */ #define __HAL_SMARTCARD_CLEAR_FEFLAG(__HANDLE__) __HAL_SMARTCARD_CLEAR_FLAG((__HANDLE__), SMARTCARD_CLEAR_FEF) /** @brief Clear the SMARTCARD NE pending flag. * @param __HANDLE__: specifies the SMARTCARD Handle. * @retval None */ #define __HAL_SMARTCARD_CLEAR_NEFLAG(__HANDLE__) __HAL_SMARTCARD_CLEAR_FLAG((__HANDLE__), SMARTCARD_CLEAR_NEF) /** @brief Clear the SMARTCARD ORE pending flag. * @param __HANDLE__: specifies the SMARTCARD Handle. * @retval None */ #define __HAL_SMARTCARD_CLEAR_OREFLAG(__HANDLE__) __HAL_SMARTCARD_CLEAR_FLAG((__HANDLE__), SMARTCARD_CLEAR_OREF) /** @brief Clear the SMARTCARD IDLE pending flag. * @param __HANDLE__: specifies the SMARTCARD Handle. * @retval None */ #define __HAL_SMARTCARD_CLEAR_IDLEFLAG(__HANDLE__) __HAL_SMARTCARD_CLEAR_FLAG((__HANDLE__), SMARTCARD_CLEAR_IDLEF) /** @brief Check whether the specified Smartcard flag is set or not. * @param __HANDLE__: specifies the SMARTCARD Handle. * The Handle Instance can be USARTx where x: 1, 2 or 3 to select the USART peripheral. * @param __FLAG__: specifies the flag to check. * This parameter can be one of the following values: * @arg SMARTCARD_FLAG_REACK: Receive enable acknowledge flag * @arg SMARTCARD_FLAG_TEACK: Transmit enable acknowledge flag * @arg SMARTCARD_FLAG_BUSY: Busy flag * @arg SMARTCARD_FLAG_EOBF: End of block flag * @arg SMARTCARD_FLAG_RTOF: Receiver timeout flag * @arg SMARTCARD_FLAG_TXE: Transmit data register empty flag * @arg SMARTCARD_FLAG_TC: Transmission complete flag * @arg SMARTCARD_FLAG_RXNE: Receive data register not empty flag * @arg SMARTCARD_FLAG_IDLE: Idle line detection flag * @arg SMARTCARD_FLAG_ORE: Overrun error flag * @arg SMARTCARD_FLAG_NE: Noise error flag * @arg SMARTCARD_FLAG_FE: Framing error flag * @arg SMARTCARD_FLAG_PE: Parity error flag * @retval The new state of __FLAG__ (TRUE or FALSE). */ #define __HAL_SMARTCARD_GET_FLAG(__HANDLE__, __FLAG__) (((__HANDLE__)->Instance->ISR & (__FLAG__)) == (__FLAG__)) /** @brief Enable the specified SmartCard interrupt. * @param __HANDLE__: specifies the SMARTCARD Handle. * The Handle Instance can be USARTx where x: 1, 2 or 3 to select the USART peripheral. * @param __INTERRUPT__: specifies the SMARTCARD interrupt to enable. * This parameter can be one of the following values: * @arg SMARTCARD_IT_EOB: End of block interrupt * @arg SMARTCARD_IT_RTO: Receive timeout interrupt * @arg SMARTCARD_IT_TXE: Transmit data register empty interrupt * @arg SMARTCARD_IT_TC: Transmission complete interrupt * @arg SMARTCARD_IT_RXNE: Receive data register not empty interrupt * @arg SMARTCARD_IT_IDLE: Idle line detection interrupt * @arg SMARTCARD_IT_PE: Parity error interrupt * @arg SMARTCARD_IT_ERR: Error interrupt(frame error, noise error, overrun error) * @retval None */ #define __HAL_SMARTCARD_ENABLE_IT(__HANDLE__, __INTERRUPT__) (((((uint8_t)(__INTERRUPT__)) >> 5U) == 1)? ((__HANDLE__)->Instance->CR1 |= (1U << ((__INTERRUPT__) & SMARTCARD_IT_MASK))): \ ((((uint8_t)(__INTERRUPT__)) >> 5U) == 2)? ((__HANDLE__)->Instance->CR2 |= (1U << ((__INTERRUPT__) & SMARTCARD_IT_MASK))): \ ((__HANDLE__)->Instance->CR3 |= (1U << ((__INTERRUPT__) & SMARTCARD_IT_MASK)))) /** @brief Disable the specified SmartCard interrupt. * @param __HANDLE__: specifies the SMARTCARD Handle. * The Handle Instance can be USARTx where x: 1, 2 or 3 to select the USART peripheral. * @param __INTERRUPT__: specifies the SMARTCARD interrupt to disable. * This parameter can be one of the following values: * @arg SMARTCARD_IT_EOB: End of block interrupt * @arg SMARTCARD_IT_RTO: Receive timeout interrupt * @arg SMARTCARD_IT_TXE: Transmit data register empty interrupt * @arg SMARTCARD_IT_TC: Transmission complete interrupt * @arg SMARTCARD_IT_RXNE: Receive data register not empty interrupt * @arg SMARTCARD_IT_IDLE: Idle line detection interrupt * @arg SMARTCARD_IT_PE: Parity error interrupt * @arg SMARTCARD_IT_ERR: Error interrupt(frame error, noise error, overrun error) * @retval None */ #define __HAL_SMARTCARD_DISABLE_IT(__HANDLE__, __INTERRUPT__) (((((uint8_t)(__INTERRUPT__)) >> 5U) == 1)? ((__HANDLE__)->Instance->CR1 &= ~ (1U << ((__INTERRUPT__) & SMARTCARD_IT_MASK))): \ ((((uint8_t)(__INTERRUPT__)) >> 5U) == 2)? ((__HANDLE__)->Instance->CR2 &= ~ (1U << ((__INTERRUPT__) & SMARTCARD_IT_MASK))): \ ((__HANDLE__)->Instance->CR3 &= ~ (1U << ((__INTERRUPT__) & SMARTCARD_IT_MASK)))) /** @brief Check whether the specified SmartCard interrupt has occurred or not. * @param __HANDLE__: specifies the SMARTCARD Handle. * The Handle Instance can be USARTx where x: 1, 2 or 3 to select the USART peripheral. * @param __IT__: specifies the SMARTCARD interrupt to check. * This parameter can be one of the following values: * @arg SMARTCARD_IT_EOB: End of block interrupt * @arg SMARTCARD_IT_RTO: Receive timeout interrupt * @arg SMARTCARD_IT_TXE: Transmit data register empty interrupt * @arg SMARTCARD_IT_TC: Transmission complete interrupt * @arg SMARTCARD_IT_RXNE: Receive data register not empty interrupt * @arg SMARTCARD_IT_IDLE: Idle line detection interrupt * @arg SMARTCARD_IT_ORE: Overrun error interrupt * @arg SMARTCARD_IT_NE: Noise error interrupt * @arg SMARTCARD_IT_FE: Framing error interrupt * @arg SMARTCARD_IT_PE: Parity error interrupt * @retval The new state of __IT__ (TRUE or FALSE). */ #define __HAL_SMARTCARD_GET_IT(__HANDLE__, __IT__) ((__HANDLE__)->Instance->ISR & ((uint32_t)1 << ((__IT__)>> 0x08))) /** @brief Check whether the specified SmartCard interrupt source is enabled or not. * @param __HANDLE__: specifies the SMARTCARD Handle. * The Handle Instance can be USARTx where x: 1, 2 or 3 to select the USART peripheral. * @param __IT__: specifies the SMARTCARD interrupt source to check. * This parameter can be one of the following values: * @arg SMARTCARD_IT_EOB: End of block interrupt * @arg SMARTCARD_IT_RTO: Receive timeout interrupt * @arg SMARTCARD_IT_TXE: Transmit data register empty interrupt * @arg SMARTCARD_IT_TC: Transmission complete interrupt * @arg SMARTCARD_IT_RXNE: Receive data register not empty interrupt * @arg SMARTCARD_IT_IDLE: Idle line detection interrupt * @arg SMARTCARD_IT_ORE: Overrun error interrupt * @arg SMARTCARD_IT_NE: Noise error interrupt * @arg SMARTCARD_IT_FE: Framing error interrupt * @arg SMARTCARD_IT_PE: Parity error interrupt * @retval The new state of __IT__ (TRUE or FALSE). */ #define __HAL_SMARTCARD_GET_IT_SOURCE(__HANDLE__, __IT__) ((((((uint8_t)(__IT__)) >> 5U) == 1)? (__HANDLE__)->Instance->CR1 : \ (((((uint8_t)(__IT__)) >> 5U) == 2)? (__HANDLE__)->Instance->CR2 : \ (__HANDLE__)->Instance->CR3)) & ((uint32_t)1 << (((uint16_t)(__IT__)) & SMARTCARD_IT_MASK))) /** @brief Clear the specified SMARTCARD ISR flag, in setting the proper ICR register flag. * @param __HANDLE__: specifies the SMARTCARD Handle. * The Handle Instance can be USARTx where x: 1, 2 or 3 to select the USART peripheral. * @param __IT_CLEAR__: specifies the interrupt clear register flag that needs to be set * to clear the corresponding interrupt * This parameter can be one of the following values: * @arg SMARTCARD_CLEAR_PEF: Parity error clear flag * @arg SMARTCARD_CLEAR_FEF: Framing error clear flag * @arg SMARTCARD_CLEAR_NEF: Noise detected clear flag * @arg SMARTCARD_CLEAR_OREF: OverRun error clear flag * @arg SMARTCARD_CLEAR_IDLEF: Idle line detection clear flag * @arg SMARTCARD_CLEAR_TCF: Transmission complete clear flag * @arg SMARTCARD_CLEAR_RTOF: Receiver timeout clear flag * @arg SMARTCARD_CLEAR_EOBF: End of block clear flag * @retval None */ #define __HAL_SMARTCARD_CLEAR_IT(__HANDLE__, __IT_CLEAR__) ((__HANDLE__)->Instance->ICR = (uint32_t)(__IT_CLEAR__)) /** @brief Set a specific SMARTCARD request flag. * @param __HANDLE__: specifies the SMARTCARD Handle. * The Handle Instance can be USARTx where x: 1, 2 or 3 to select the USART peripheral. * @param __REQ__: specifies the request flag to set * This parameter can be one of the following values: * @arg SMARTCARD_RXDATA_FLUSH_REQUEST: Receive data flush Request * @arg SMARTCARD_TXDATA_FLUSH_REQUEST: Transmit data flush Request * * @retval None */ #define __HAL_SMARTCARD_SEND_REQ(__HANDLE__, __REQ__) ((__HANDLE__)->Instance->RQR |= (uint16_t)(__REQ__)) /** @brief Enable the SMARTCARD one bit sample method. * @param __HANDLE__: specifies the SMARTCARD Handle. * @retval None */ #define __HAL_SMARTCARD_ONE_BIT_SAMPLE_ENABLE(__HANDLE__) ((__HANDLE__)->Instance->CR3|= USART_CR3_ONEBIT) /** @brief Disable the SMARTCARD one bit sample method. * @param __HANDLE__: specifies the SMARTCARD Handle. * @retval None */ #define __HAL_SMARTCARD_ONE_BIT_SAMPLE_DISABLE(__HANDLE__) ((__HANDLE__)->Instance->CR3 &= (uint32_t)~((uint32_t)USART_CR3_ONEBIT)) /** @brief Enable the USART associated to the SMARTCARD Handle. * @param __HANDLE__: specifies the SMARTCARD Handle. * The Handle Instance can be UARTx where x: 1, 2, 3 to select the USART peripheral * @retval None */ #define __HAL_SMARTCARD_ENABLE(__HANDLE__) ((__HANDLE__)->Instance->CR1 |= USART_CR1_UE) /** @brief Disable the USART associated to the SMARTCARD Handle * @param __HANDLE__: specifies the SMARTCARD Handle. * The Handle Instance can be UARTx where x: 1, 2, 3 to select the USART peripheral * @retval None */ #define __HAL_SMARTCARD_DISABLE(__HANDLE__) ((__HANDLE__)->Instance->CR1 &= ~USART_CR1_UE) /** * @} */ /* Private macros -------------------------------------------------------------*/ /** @defgroup SMARTCARD_Private_Macros SMARTCARD Private Macros * @{ */ /** @brief Check the Baud rate range. The maximum Baud Rate is derived from the * maximum clock on F0 (i.e. 48 MHz) divided by the oversampling used * on the SMARTCARD (i.e. 16). * @param __BAUDRATE__: Baud rate set by the configuration function. * @retval Test result (TRUE or FALSE) */ #define IS_SMARTCARD_BAUDRATE(__BAUDRATE__) ((__BAUDRATE__) < 4500001) /** @brief Check the block length range. * @note The maximum SMARTCARD block length is 0xFF. * @param __LENGTH__: block length. * @retval Test result (TRUE or FALSE) */ #define IS_SMARTCARD_BLOCKLENGTH(__LENGTH__) ((__LENGTH__) <= 0xFF) /** @brief Check the receiver timeout value. * @note The maximum SMARTCARD receiver timeout value is 0xFFFFFF. * @param __TIMEOUTVALUE__: receiver timeout value. * @retval Test result (TRUE or FALSE) */ #define IS_SMARTCARD_TIMEOUT_VALUE(__TIMEOUTVALUE__) ((__TIMEOUTVALUE__) <= 0xFFFFFF) /** @brief Check the SMARTCARD autoretry counter value. * @note The maximum number of retransmissions is 0x7. * @param __COUNT__: number of retransmissions. * @retval Test result (TRUE or FALSE) */ #define IS_SMARTCARD_AUTORETRY_COUNT(__COUNT__) ((__COUNT__) <= 0x7) /** * @brief Ensure that SMARTCARD frame length is valid. * @param __LENGTH__: SMARTCARD frame length. * @retval SET (__LENGTH__ is valid) or RESET (__LENGTH__ is invalid) */ #define IS_SMARTCARD_WORD_LENGTH(__LENGTH__) ((__LENGTH__) == SMARTCARD_WORDLENGTH_9B) /** * @brief Ensure that SMARTCARD frame number of stop bits is valid. * @param __STOPBITS__: SMARTCARD frame number of stop bits. * @retval SET (__STOPBITS__ is valid) or RESET (__STOPBITS__ is invalid) */ #define IS_SMARTCARD_STOPBITS(__STOPBITS__) ((__STOPBITS__) == SMARTCARD_STOPBITS_1_5) /** * @brief Ensure that SMARTCARD frame parity is valid. * @param __PARITY__: SMARTCARD frame parity. * @retval SET (__PARITY__ is valid) or RESET (__PARITY__ is invalid) */ #define IS_SMARTCARD_PARITY(__PARITY__) (((__PARITY__) == SMARTCARD_PARITY_EVEN) || \ ((__PARITY__) == SMARTCARD_PARITY_ODD)) /** * @brief Ensure that SMARTCARD communication mode is valid. * @param __MODE__: SMARTCARD communication mode. * @retval SET (__MODE__ is valid) or RESET (__MODE__ is invalid) */ #define IS_SMARTCARD_MODE(__MODE__) ((((__MODE__) & (uint16_t)0xFFF3) == 0x00) && ((__MODE__) != (uint16_t)0x00)) /** * @brief Ensure that SMARTCARD frame polarity is valid. * @param __CPOL__: SMARTCARD frame polarity. * @retval SET (__CPOL__ is valid) or RESET (__CPOL__ is invalid) */ #define IS_SMARTCARD_POLARITY(__CPOL__) (((__CPOL__) == SMARTCARD_POLARITY_LOW) || ((__CPOL__) == SMARTCARD_POLARITY_HIGH)) /** * @brief Ensure that SMARTCARD frame phase is valid. * @param __CPHA__: SMARTCARD frame phase. * @retval SET (__CPHA__ is valid) or RESET (__CPHA__ is invalid) */ #define IS_SMARTCARD_PHASE(__CPHA__) (((__CPHA__) == SMARTCARD_PHASE_1EDGE) || ((__CPHA__) == SMARTCARD_PHASE_2EDGE)) /** * @brief Ensure that SMARTCARD frame last bit clock pulse setting is valid. * @param __LASTBIT__: SMARTCARD frame last bit clock pulse setting. * @retval SET (__LASTBIT__ is valid) or RESET (__LASTBIT__ is invalid) */ #define IS_SMARTCARD_LASTBIT(__LASTBIT__) (((__LASTBIT__) == SMARTCARD_LASTBIT_DISABLE) || \ ((__LASTBIT__) == SMARTCARD_LASTBIT_ENABLE)) /** * @brief Ensure that SMARTCARD frame sampling is valid. * @param __ONEBIT__: SMARTCARD frame sampling. * @retval SET (__ONEBIT__ is valid) or RESET (__ONEBIT__ is invalid) */ #define IS_SMARTCARD_ONE_BIT_SAMPLE(__ONEBIT__) (((__ONEBIT__) == SMARTCARD_ONE_BIT_SAMPLE_DISABLE) || \ ((__ONEBIT__) == SMARTCARD_ONE_BIT_SAMPLE_ENABLE)) /** * @brief Ensure that SMARTCARD NACK transmission setting is valid. * @param __NACK__: SMARTCARD NACK transmission setting. * @retval SET (__NACK__ is valid) or RESET (__NACK__ is invalid) */ #define IS_SMARTCARD_NACK(__NACK__) (((__NACK__) == SMARTCARD_NACK_ENABLE) || \ ((__NACK__) == SMARTCARD_NACK_DISABLE)) /** * @brief Ensure that SMARTCARD receiver timeout setting is valid. * @param __TIMEOUT__: SMARTCARD receiver timeout setting. * @retval SET (__TIMEOUT__ is valid) or RESET (__TIMEOUT__ is invalid) */ #define IS_SMARTCARD_TIMEOUT(__TIMEOUT__) (((__TIMEOUT__) == SMARTCARD_TIMEOUT_DISABLE) || \ ((__TIMEOUT__) == SMARTCARD_TIMEOUT_ENABLE)) /** * @brief Ensure that SMARTCARD advanced features initialization is valid. * @param __INIT__: SMARTCARD advanced features initialization. * @retval SET (__INIT__ is valid) or RESET (__INIT__ is invalid) */ #define IS_SMARTCARD_ADVFEATURE_INIT(__INIT__) ((__INIT__) <= (SMARTCARD_ADVFEATURE_NO_INIT | \ SMARTCARD_ADVFEATURE_TXINVERT_INIT | \ SMARTCARD_ADVFEATURE_RXINVERT_INIT | \ SMARTCARD_ADVFEATURE_DATAINVERT_INIT | \ SMARTCARD_ADVFEATURE_SWAP_INIT | \ SMARTCARD_ADVFEATURE_RXOVERRUNDISABLE_INIT | \ SMARTCARD_ADVFEATURE_DMADISABLEONERROR_INIT | \ SMARTCARD_ADVFEATURE_MSBFIRST_INIT)) /** * @brief Ensure that SMARTCARD frame TX inversion setting is valid. * @param __TXINV__: SMARTCARD frame TX inversion setting. * @retval SET (__TXINV__ is valid) or RESET (__TXINV__ is invalid) */ #define IS_SMARTCARD_ADVFEATURE_TXINV(__TXINV__) (((__TXINV__) == SMARTCARD_ADVFEATURE_TXINV_DISABLE) || \ ((__TXINV__) == SMARTCARD_ADVFEATURE_TXINV_ENABLE)) /** * @brief Ensure that SMARTCARD frame RX inversion setting is valid. * @param __RXINV__: SMARTCARD frame RX inversion setting. * @retval SET (__RXINV__ is valid) or RESET (__RXINV__ is invalid) */ #define IS_SMARTCARD_ADVFEATURE_RXINV(__RXINV__) (((__RXINV__) == SMARTCARD_ADVFEATURE_RXINV_DISABLE) || \ ((__RXINV__) == SMARTCARD_ADVFEATURE_RXINV_ENABLE)) /** * @brief Ensure that SMARTCARD frame data inversion setting is valid. * @param __DATAINV__: SMARTCARD frame data inversion setting. * @retval SET (__DATAINV__ is valid) or RESET (__DATAINV__ is invalid) */ #define IS_SMARTCARD_ADVFEATURE_DATAINV(__DATAINV__) (((__DATAINV__) == SMARTCARD_ADVFEATURE_DATAINV_DISABLE) || \ ((__DATAINV__) == SMARTCARD_ADVFEATURE_DATAINV_ENABLE)) /** * @brief Ensure that SMARTCARD frame RX/TX pins swap setting is valid. * @param __SWAP__: SMARTCARD frame RX/TX pins swap setting. * @retval SET (__SWAP__ is valid) or RESET (__SWAP__ is invalid) */ #define IS_SMARTCARD_ADVFEATURE_SWAP(__SWAP__) (((__SWAP__) == SMARTCARD_ADVFEATURE_SWAP_DISABLE) || \ ((__SWAP__) == SMARTCARD_ADVFEATURE_SWAP_ENABLE)) /** * @brief Ensure that SMARTCARD frame overrun setting is valid. * @param __OVERRUN__: SMARTCARD frame overrun setting. * @retval SET (__OVERRUN__ is valid) or RESET (__OVERRUN__ is invalid) */ #define IS_SMARTCARD_OVERRUN(__OVERRUN__) (((__OVERRUN__) == SMARTCARD_ADVFEATURE_OVERRUN_ENABLE) || \ ((__OVERRUN__) == SMARTCARD_ADVFEATURE_OVERRUN_DISABLE)) /** * @brief Ensure that SMARTCARD DMA enabling or disabling on error setting is valid. * @param __DMA__: SMARTCARD DMA enabling or disabling on error setting. * @retval SET (__DMA__ is valid) or RESET (__DMA__ is invalid) */ #define IS_SMARTCARD_ADVFEATURE_DMAONRXERROR(__DMA__) (((__DMA__) == SMARTCARD_ADVFEATURE_DMA_ENABLEONRXERROR) || \ ((__DMA__) == SMARTCARD_ADVFEATURE_DMA_DISABLEONRXERROR)) /** * @brief Ensure that SMARTCARD frame MSB first setting is valid. * @param __MSBFIRST__: SMARTCARD frame MSB first setting. * @retval SET (__MSBFIRST__ is valid) or RESET (__MSBFIRST__ is invalid) */ #define IS_SMARTCARD_ADVFEATURE_MSBFIRST(__MSBFIRST__) (((__MSBFIRST__) == SMARTCARD_ADVFEATURE_MSBFIRST_DISABLE) || \ ((__MSBFIRST__) == SMARTCARD_ADVFEATURE_MSBFIRST_ENABLE)) /** * @brief Ensure that SMARTCARD request parameter is valid. * @param __PARAM__: SMARTCARD request parameter. * @retval SET (__PARAM__ is valid) or RESET (__PARAM__ is invalid) */ #define IS_SMARTCARD_REQUEST_PARAMETER(__PARAM__) (((__PARAM__) == SMARTCARD_RXDATA_FLUSH_REQUEST) || \ ((__PARAM__) == SMARTCARD_TXDATA_FLUSH_REQUEST)) /** * @} */ /* Include SMARTCARD HAL Extended module */ #include "stm32f0xx_hal_smartcard_ex.h" /* Exported functions --------------------------------------------------------*/ /** @addtogroup SMARTCARD_Exported_Functions SMARTCARD Exported Functions * @{ */ /** @addtogroup SMARTCARD_Exported_Functions_Group1 Initialization and de-initialization functions * @{ */ /* Initialization and de-initialization functions ****************************/ HAL_StatusTypeDef HAL_SMARTCARD_Init(SMARTCARD_HandleTypeDef *hsmartcard); HAL_StatusTypeDef HAL_SMARTCARD_DeInit(SMARTCARD_HandleTypeDef *hsmartcard); void HAL_SMARTCARD_MspInit(SMARTCARD_HandleTypeDef *hsmartcard); void HAL_SMARTCARD_MspDeInit(SMARTCARD_HandleTypeDef *hsmartcard); /** * @} */ /** @addtogroup SMARTCARD_Exported_Functions_Group2 IO operation functions * @{ */ /* IO operation functions *****************************************************/ HAL_StatusTypeDef HAL_SMARTCARD_Transmit(SMARTCARD_HandleTypeDef *hsmartcard, uint8_t *pData, uint16_t Size, uint32_t Timeout); HAL_StatusTypeDef HAL_SMARTCARD_Receive(SMARTCARD_HandleTypeDef *hsmartcard, uint8_t *pData, uint16_t Size, uint32_t Timeout); HAL_StatusTypeDef HAL_SMARTCARD_Transmit_IT(SMARTCARD_HandleTypeDef *hsmartcard, uint8_t *pData, uint16_t Size); HAL_StatusTypeDef HAL_SMARTCARD_Receive_IT(SMARTCARD_HandleTypeDef *hsmartcard, uint8_t *pData, uint16_t Size); HAL_StatusTypeDef HAL_SMARTCARD_Transmit_DMA(SMARTCARD_HandleTypeDef *hsmartcard, uint8_t *pData, uint16_t Size); HAL_StatusTypeDef HAL_SMARTCARD_Receive_DMA(SMARTCARD_HandleTypeDef *hsmartcard, uint8_t *pData, uint16_t Size); void HAL_SMARTCARD_IRQHandler(SMARTCARD_HandleTypeDef *hsmartcard); void HAL_SMARTCARD_TxCpltCallback(SMARTCARD_HandleTypeDef *hsmartcard); void HAL_SMARTCARD_RxCpltCallback(SMARTCARD_HandleTypeDef *hsmartcard); void HAL_SMARTCARD_ErrorCallback(SMARTCARD_HandleTypeDef *hsmartcard); /** * @} */ /** @addtogroup SMARTCARD_Exported_Functions_Group3 Peripheral State and Errors functions * @{ */ /* Peripheral State and Error functions ***************************************/ HAL_SMARTCARD_StateTypeDef HAL_SMARTCARD_GetState(SMARTCARD_HandleTypeDef *hsmartcard); uint32_t HAL_SMARTCARD_GetError(SMARTCARD_HandleTypeDef *hsmartcard); /** * @} */ /** * @} */ /** * @} */ /** * @} */ #endif /* !defined(STM32F030x6) && !defined(STM32F030x8)&& !defined(STM32F070x6) && !defined(STM32F070xB) && !defined(STM32F030xC) */ #ifdef __cplusplus } #endif #endif /* __STM32F0xx_HAL_SMARTCARD_H */ /************************ (C) COPYRIGHT STMicroelectronics *****END OF FILE****/ ================================================ FILE: Zelig/mbed/TARGET_NUCLEO_F091RC/stm32f0xx_hal_smartcard_ex.h ================================================ /** ****************************************************************************** * @file stm32f0xx_hal_smartcard_ex.h * @author MCD Application Team * @version V1.3.0 * @date 26-June-2015 * @brief Header file of SMARTCARD HAL Extended module. ****************************************************************************** * @attention * *

© COPYRIGHT(c) 2015 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. * ****************************************************************************** */ /* Define to prevent recursive inclusion -------------------------------------*/ #ifndef __STM32F0xx_HAL_SMARTCARD_EX_H #define __STM32F0xx_HAL_SMARTCARD_EX_H #ifdef __cplusplus extern "C" { #endif #if !defined(STM32F030x6) && !defined(STM32F030x8) && !defined(STM32F070x6) && !defined(STM32F070xB) && !defined(STM32F030xC) /* Includes ------------------------------------------------------------------*/ #include "stm32f0xx_hal_def.h" /** @addtogroup STM32F0xx_HAL_Driver * @{ */ /** @addtogroup SMARTCARDEx * @{ */ /* Exported types ------------------------------------------------------------*/ /* Exported constants --------------------------------------------------------*/ /* Exported macro ------------------------------------------------------------*/ /** @defgroup SMARTCARD_Extended_Exported_Macros SMARTCARDEx Exported Macros * @{ */ /** @brief Reports the SMARTCARD clock source. * @param __HANDLE__: specifies the SMARTCARD Handle * @param __CLOCKSOURCE__ : output variable * @retval the SMARTCARD clocking source, written in __CLOCKSOURCE__. */ #if defined(STM32F031x6) || defined(STM32F038xx) #define SMARTCARD_GETCLOCKSOURCE(__HANDLE__,__CLOCKSOURCE__) \ do { \ switch(__HAL_RCC_GET_USART1_SOURCE()) \ { \ case RCC_USART1CLKSOURCE_PCLK1: \ (__CLOCKSOURCE__) = SMARTCARD_CLOCKSOURCE_PCLK1; \ break; \ case RCC_USART1CLKSOURCE_HSI: \ (__CLOCKSOURCE__) = SMARTCARD_CLOCKSOURCE_HSI; \ break; \ case RCC_USART1CLKSOURCE_SYSCLK: \ (__CLOCKSOURCE__) = SMARTCARD_CLOCKSOURCE_SYSCLK; \ break; \ case RCC_USART1CLKSOURCE_LSE: \ (__CLOCKSOURCE__) = SMARTCARD_CLOCKSOURCE_LSE; \ break; \ default: \ (__CLOCKSOURCE__) = SMARTCARD_CLOCKSOURCE_UNDEFINED; \ break; \ } \ } while(0) #elif defined (STM32F030x8) || \ defined (STM32F042x6) || defined (STM32F048xx) || \ defined (STM32F051x8) || defined (STM32F058xx) #define SMARTCARD_GETCLOCKSOURCE(__HANDLE__,__CLOCKSOURCE__) \ do { \ if((__HANDLE__)->Instance == USART1) \ { \ switch(__HAL_RCC_GET_USART1_SOURCE()) \ { \ case RCC_USART1CLKSOURCE_PCLK1: \ (__CLOCKSOURCE__) = SMARTCARD_CLOCKSOURCE_PCLK1; \ break; \ case RCC_USART1CLKSOURCE_HSI: \ (__CLOCKSOURCE__) = SMARTCARD_CLOCKSOURCE_HSI; \ break; \ case RCC_USART1CLKSOURCE_SYSCLK: \ (__CLOCKSOURCE__) = SMARTCARD_CLOCKSOURCE_SYSCLK; \ break; \ case RCC_USART1CLKSOURCE_LSE: \ (__CLOCKSOURCE__) = SMARTCARD_CLOCKSOURCE_LSE; \ break; \ default: \ (__CLOCKSOURCE__) = SMARTCARD_CLOCKSOURCE_UNDEFINED; \ break; \ } \ } \ else if((__HANDLE__)->Instance == USART2) \ { \ (__CLOCKSOURCE__) = SMARTCARD_CLOCKSOURCE_PCLK1; \ } \ else \ { \ (__CLOCKSOURCE__) = SMARTCARD_CLOCKSOURCE_UNDEFINED; \ } \ } while(0) #elif defined(STM32F071xB) || defined(STM32F072xB) || defined(STM32F078xx) #define SMARTCARD_GETCLOCKSOURCE(__HANDLE__,__CLOCKSOURCE__) \ do { \ if((__HANDLE__)->Instance == USART1) \ { \ switch(__HAL_RCC_GET_USART1_SOURCE()) \ { \ case RCC_USART1CLKSOURCE_PCLK1: \ (__CLOCKSOURCE__) = SMARTCARD_CLOCKSOURCE_PCLK1; \ break; \ case RCC_USART1CLKSOURCE_HSI: \ (__CLOCKSOURCE__) = SMARTCARD_CLOCKSOURCE_HSI; \ break; \ case RCC_USART1CLKSOURCE_SYSCLK: \ (__CLOCKSOURCE__) = SMARTCARD_CLOCKSOURCE_SYSCLK; \ break; \ case RCC_USART1CLKSOURCE_LSE: \ (__CLOCKSOURCE__) = SMARTCARD_CLOCKSOURCE_LSE; \ break; \ default: \ (__CLOCKSOURCE__) = SMARTCARD_CLOCKSOURCE_UNDEFINED; \ break; \ } \ } \ else if((__HANDLE__)->Instance == USART2) \ { \ switch(__HAL_RCC_GET_USART2_SOURCE()) \ { \ case RCC_USART2CLKSOURCE_PCLK1: \ (__CLOCKSOURCE__) = SMARTCARD_CLOCKSOURCE_PCLK1; \ break; \ case RCC_USART2CLKSOURCE_HSI: \ (__CLOCKSOURCE__) = SMARTCARD_CLOCKSOURCE_HSI; \ break; \ case RCC_USART2CLKSOURCE_SYSCLK: \ (__CLOCKSOURCE__) = SMARTCARD_CLOCKSOURCE_SYSCLK; \ break; \ case RCC_USART2CLKSOURCE_LSE: \ (__CLOCKSOURCE__) = SMARTCARD_CLOCKSOURCE_LSE; \ break; \ default: \ (__CLOCKSOURCE__) = SMARTCARD_CLOCKSOURCE_UNDEFINED; \ break; \ } \ } \ else if((__HANDLE__)->Instance == USART3) \ { \ (__CLOCKSOURCE__) = SMARTCARD_CLOCKSOURCE_PCLK1; \ } \ else if((__HANDLE__)->Instance == USART4) \ { \ (__CLOCKSOURCE__) = SMARTCARD_CLOCKSOURCE_PCLK1; \ } \ else \ { \ (__CLOCKSOURCE__) = SMARTCARD_CLOCKSOURCE_UNDEFINED; \ } \ } while(0) #elif defined(STM32F091xC) || defined(STM32F098xx) #define SMARTCARD_GETCLOCKSOURCE(__HANDLE__,__CLOCKSOURCE__) \ do { \ if((__HANDLE__)->Instance == USART1) \ { \ switch(__HAL_RCC_GET_USART1_SOURCE()) \ { \ case RCC_USART1CLKSOURCE_PCLK1: \ (__CLOCKSOURCE__) = SMARTCARD_CLOCKSOURCE_PCLK1; \ break; \ case RCC_USART1CLKSOURCE_HSI: \ (__CLOCKSOURCE__) = SMARTCARD_CLOCKSOURCE_HSI; \ break; \ case RCC_USART1CLKSOURCE_SYSCLK: \ (__CLOCKSOURCE__) = SMARTCARD_CLOCKSOURCE_SYSCLK; \ break; \ case RCC_USART1CLKSOURCE_LSE: \ (__CLOCKSOURCE__) = SMARTCARD_CLOCKSOURCE_LSE; \ break; \ default: \ (__CLOCKSOURCE__) = SMARTCARD_CLOCKSOURCE_UNDEFINED; \ break; \ } \ } \ else if((__HANDLE__)->Instance == USART2) \ { \ switch(__HAL_RCC_GET_USART2_SOURCE()) \ { \ case RCC_USART2CLKSOURCE_PCLK1: \ (__CLOCKSOURCE__) = SMARTCARD_CLOCKSOURCE_PCLK1; \ break; \ case RCC_USART2CLKSOURCE_HSI: \ (__CLOCKSOURCE__) = SMARTCARD_CLOCKSOURCE_HSI; \ break; \ case RCC_USART2CLKSOURCE_SYSCLK: \ (__CLOCKSOURCE__) = SMARTCARD_CLOCKSOURCE_SYSCLK; \ break; \ case RCC_USART2CLKSOURCE_LSE: \ (__CLOCKSOURCE__) = SMARTCARD_CLOCKSOURCE_LSE; \ break; \ default: \ (__CLOCKSOURCE__) = SMARTCARD_CLOCKSOURCE_UNDEFINED; \ break; \ } \ } \ else if((__HANDLE__)->Instance == USART3) \ { \ switch(__HAL_RCC_GET_USART3_SOURCE()) \ { \ case RCC_USART3CLKSOURCE_PCLK1: \ (__CLOCKSOURCE__) = SMARTCARD_CLOCKSOURCE_PCLK1; \ break; \ case RCC_USART3CLKSOURCE_HSI: \ (__CLOCKSOURCE__) = SMARTCARD_CLOCKSOURCE_HSI; \ break; \ case RCC_USART3CLKSOURCE_SYSCLK: \ (__CLOCKSOURCE__) = SMARTCARD_CLOCKSOURCE_SYSCLK; \ break; \ case RCC_USART3CLKSOURCE_LSE: \ (__CLOCKSOURCE__) = SMARTCARD_CLOCKSOURCE_LSE; \ break; \ default: \ (__CLOCKSOURCE__) = SMARTCARD_CLOCKSOURCE_UNDEFINED; \ break; \ } \ } \ else if((__HANDLE__)->Instance == USART4) \ { \ (__CLOCKSOURCE__) = SMARTCARD_CLOCKSOURCE_PCLK1; \ } \ else if((__HANDLE__)->Instance == USART5) \ { \ (__CLOCKSOURCE__) = SMARTCARD_CLOCKSOURCE_PCLK1; \ } \ else if((__HANDLE__)->Instance == USART6) \ { \ (__CLOCKSOURCE__) = SMARTCARD_CLOCKSOURCE_PCLK1; \ } \ else if((__HANDLE__)->Instance == USART7) \ { \ (__CLOCKSOURCE__) = SMARTCARD_CLOCKSOURCE_PCLK1; \ } \ else if((__HANDLE__)->Instance == USART8) \ { \ (__CLOCKSOURCE__) = SMARTCARD_CLOCKSOURCE_PCLK1; \ } \ else \ { \ (__CLOCKSOURCE__) = SMARTCARD_CLOCKSOURCE_UNDEFINED; \ } \ } while(0) #endif /* defined(STM32F031x6) || defined(STM32F038xx) */ /** * @} */ /* Exported functions --------------------------------------------------------*/ /** @addtogroup SMARTCARDEx_Exported_Functions * @{ */ /* Initialization and de-initialization functions ****************************/ /* IO operation methods *******************************************************/ /** @addtogroup SMARTCARDEx_Exported_Functions_Group1 * @{ */ /* Peripheral Control functions ***********************************************/ void HAL_SMARTCARDEx_BlockLength_Config(SMARTCARD_HandleTypeDef *hsmartcard, uint8_t BlockLength); void HAL_SMARTCARDEx_TimeOut_Config(SMARTCARD_HandleTypeDef *hsmartcard, uint32_t TimeOutValue); HAL_StatusTypeDef HAL_SMARTCARDEx_EnableReceiverTimeOut(SMARTCARD_HandleTypeDef *hsmartcard); HAL_StatusTypeDef HAL_SMARTCARDEx_DisableReceiverTimeOut(SMARTCARD_HandleTypeDef *hsmartcard); /* Peripheral State and Error functions ***************************************/ /** * @} */ /** * @} */ /** * @} */ /** * @} */ #endif /* !defined(STM32F030x6) && !defined(STM32F030x8)&& !defined(STM32F070x6) && !defined(STM32F070xB) && !defined(STM32F030xC) */ #ifdef __cplusplus } #endif #endif /* __STM32F0xx_HAL_SMARTCARD_EX_H */ /************************ (C) COPYRIGHT STMicroelectronics *****END OF FILE****/ ================================================ FILE: Zelig/mbed/TARGET_NUCLEO_F091RC/stm32f0xx_hal_smbus.h ================================================ /** ****************************************************************************** * @file stm32f0xx_hal_smbus.h * @author MCD Application Team * @version V1.3.0 * @date 26-June-2015 * @brief Header file of SMBUS HAL module. ****************************************************************************** * @attention * *

© COPYRIGHT(c) 2015 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. * ****************************************************************************** */ /* Define to prevent recursive inclusion -------------------------------------*/ #ifndef __STM32F0xx_HAL_SMBUS_H #define __STM32F0xx_HAL_SMBUS_H #ifdef __cplusplus extern "C" { #endif /* Includes ------------------------------------------------------------------*/ #include "stm32f0xx_hal_def.h" /** @addtogroup STM32F0xx_HAL_Driver * @{ */ /** @addtogroup SMBUS * @{ */ /* Exported types ------------------------------------------------------------*/ /** @defgroup SMBUS_Exported_Types SMBUS Exported Types * @{ */ /** @defgroup SMBUS_Configuration_Structure_definition SMBUS Configuration Structure definition * @brief SMBUS Configuration Structure definition * @{ */ typedef struct { uint32_t Timing; /*!< Specifies the SMBUS_TIMINGR_register value. This parameter calculated by referring to SMBUS initialization section in Reference manual */ uint32_t AnalogFilter; /*!< Specifies if Analog Filter is enable or not. This parameter can be a value of @ref SMBUS_Analog_Filter */ uint32_t OwnAddress1; /*!< Specifies the first device own address. This parameter can be a 7-bit or 10-bit address. */ uint32_t AddressingMode; /*!< Specifies if 7-bit or 10-bit addressing mode for master is selected. This parameter can be a value of @ref SMBUS_addressing_mode */ uint32_t DualAddressMode; /*!< Specifies if dual addressing mode is selected. This parameter can be a value of @ref SMBUS_dual_addressing_mode */ uint32_t OwnAddress2; /*!< Specifies the second device own address if dual addressing mode is selected This parameter can be a 7-bit address. */ uint32_t OwnAddress2Masks; /*!< Specifies the acknoledge mask address second device own address if dual addressing mode is selected This parameter can be a value of @ref SMBUS_own_address2_masks. */ uint32_t GeneralCallMode; /*!< Specifies if general call mode is selected. This parameter can be a value of @ref SMBUS_general_call_addressing_mode. */ uint32_t NoStretchMode; /*!< Specifies if nostretch mode is selected. This parameter can be a value of @ref SMBUS_nostretch_mode */ uint32_t PacketErrorCheckMode; /*!< Specifies if Packet Error Check mode is selected. This parameter can be a value of @ref SMBUS_packet_error_check_mode */ uint32_t PeripheralMode; /*!< Specifies which mode of Periphal is selected. This parameter can be a value of @ref SMBUS_peripheral_mode */ uint32_t SMBusTimeout; /*!< Specifies the content of the 32 Bits SMBUS_TIMEOUT_register value. (Enable bits and different timeout values) This parameter calculated by referring to SMBUS initialization section in Reference manual */ } SMBUS_InitTypeDef; /** * @} */ /** @defgroup HAL_state_definition HAL state definition * @brief HAL State definition * @{ */ #define HAL_SMBUS_STATE_RESET ((uint32_t)0x00000000) /*!< SMBUS not yet initialized or disabled */ #define HAL_SMBUS_STATE_READY ((uint32_t)0x00000001) /*!< SMBUS initialized and ready for use */ #define HAL_SMBUS_STATE_BUSY ((uint32_t)0x00000002) /*!< SMBUS internal process is ongoing */ #define HAL_SMBUS_STATE_MASTER_BUSY_TX ((uint32_t)0x00000012) /*!< Master Data Transmission process is ongoing */ #define HAL_SMBUS_STATE_MASTER_BUSY_RX ((uint32_t)0x00000022) /*!< Master Data Reception process is ongoing */ #define HAL_SMBUS_STATE_SLAVE_BUSY_TX ((uint32_t)0x00000032) /*!< Slave Data Transmission process is ongoing */ #define HAL_SMBUS_STATE_SLAVE_BUSY_RX ((uint32_t)0x00000042) /*!< Slave Data Reception process is ongoing */ #define HAL_SMBUS_STATE_TIMEOUT ((uint32_t)0x00000003) /*!< Timeout state */ #define HAL_SMBUS_STATE_ERROR ((uint32_t)0x00000004) /*!< Reception process is ongoing */ #define HAL_SMBUS_STATE_LISTEN ((uint32_t)0x00000008) /*!< Address Listen Mode is ongoing */ /** * @} */ /** @defgroup SMBUS_Error_Code_definition SMBUS Error Code definition * @brief SMBUS Error Code definition * @{ */ #define HAL_SMBUS_ERROR_NONE ((uint32_t)0x00000000) /*!< No error */ #define HAL_SMBUS_ERROR_BERR ((uint32_t)0x00000001) /*!< BERR error */ #define HAL_SMBUS_ERROR_ARLO ((uint32_t)0x00000002) /*!< ARLO error */ #define HAL_SMBUS_ERROR_ACKF ((uint32_t)0x00000004) /*!< ACKF error */ #define HAL_SMBUS_ERROR_OVR ((uint32_t)0x00000008) /*!< OVR error */ #define HAL_SMBUS_ERROR_HALTIMEOUT ((uint32_t)0x00000010) /*!< Timeout error */ #define HAL_SMBUS_ERROR_BUSTIMEOUT ((uint32_t)0x00000020) /*!< Bus Timeout error */ #define HAL_SMBUS_ERROR_ALERT ((uint32_t)0x00000040) /*!< Alert error */ #define HAL_SMBUS_ERROR_PECERR ((uint32_t)0x00000080) /*!< PEC error */ /** * @} */ /** @defgroup SMBUS_handle_Structure_definition SMBUS handle Structure definition * @brief SMBUS handle Structure definition * @{ */ typedef struct { I2C_TypeDef *Instance; /*!< SMBUS registers base address */ SMBUS_InitTypeDef Init; /*!< SMBUS communication parameters */ uint8_t *pBuffPtr; /*!< Pointer to SMBUS transfer buffer */ uint16_t XferSize; /*!< SMBUS transfer size */ __IO uint16_t XferCount; /*!< SMBUS transfer counter */ __IO uint32_t XferOptions; /*!< SMBUS transfer options */ __IO uint32_t PreviousState; /*!< SMBUS communication Previous state */ HAL_LockTypeDef Lock; /*!< SMBUS locking object */ __IO uint32_t State; /*!< SMBUS communication state */ __IO uint32_t ErrorCode; /*!< SMBUS Error code */ }SMBUS_HandleTypeDef; /** * @} */ /** * @} */ /* Exported constants --------------------------------------------------------*/ /** @defgroup SMBUS_Exported_Constants SMBUS Exported Constants * @{ */ /** @defgroup SMBUS_Analog_Filter SMBUS Analog Filter * @{ */ #define SMBUS_ANALOGFILTER_ENABLE ((uint32_t)0x00000000) #define SMBUS_ANALOGFILTER_DISABLE I2C_CR1_ANFOFF /** * @} */ /** @defgroup SMBUS_addressing_mode SMBUS addressing mode * @{ */ #define SMBUS_ADDRESSINGMODE_7BIT ((uint32_t)0x00000001) #define SMBUS_ADDRESSINGMODE_10BIT ((uint32_t)0x00000002) /** * @} */ /** @defgroup SMBUS_dual_addressing_mode SMBUS dual addressing mode * @{ */ #define SMBUS_DUALADDRESS_DISABLE ((uint32_t)0x00000000) #define SMBUS_DUALADDRESS_ENABLE I2C_OAR2_OA2EN /** * @} */ /** @defgroup SMBUS_own_address2_masks SMBUS ownaddress2 masks * @{ */ #define SMBUS_OA2_NOMASK ((uint8_t)0x00) #define SMBUS_OA2_MASK01 ((uint8_t)0x01) #define SMBUS_OA2_MASK02 ((uint8_t)0x02) #define SMBUS_OA2_MASK03 ((uint8_t)0x03) #define SMBUS_OA2_MASK04 ((uint8_t)0x04) #define SMBUS_OA2_MASK05 ((uint8_t)0x05) #define SMBUS_OA2_MASK06 ((uint8_t)0x06) #define SMBUS_OA2_MASK07 ((uint8_t)0x07) /** * @} */ /** @defgroup SMBUS_general_call_addressing_mode SMBUS general call addressing mode * @{ */ #define SMBUS_GENERALCALL_DISABLE ((uint32_t)0x00000000) #define SMBUS_GENERALCALL_ENABLE I2C_CR1_GCEN /** * @} */ /** @defgroup SMBUS_nostretch_mode SMBUS nostretch mode * @{ */ #define SMBUS_NOSTRETCH_DISABLE ((uint32_t)0x00000000) #define SMBUS_NOSTRETCH_ENABLE I2C_CR1_NOSTRETCH /** * @} */ /** @defgroup SMBUS_packet_error_check_mode SMBUS packet error check mode * @{ */ #define SMBUS_PEC_DISABLE ((uint32_t)0x00000000) #define SMBUS_PEC_ENABLE I2C_CR1_PECEN /** * @} */ /** @defgroup SMBUS_peripheral_mode SMBUS peripheral mode * @{ */ #define SMBUS_PERIPHERAL_MODE_SMBUS_HOST (uint32_t)(I2C_CR1_SMBHEN) #define SMBUS_PERIPHERAL_MODE_SMBUS_SLAVE (uint32_t)(0x00000000) #define SMBUS_PERIPHERAL_MODE_SMBUS_SLAVE_ARP (uint32_t)(I2C_CR1_SMBDEN) /** * @} */ /** @defgroup SMBUS_ReloadEndMode_definition SMBUS ReloadEndMode definition * @{ */ #define SMBUS_SOFTEND_MODE ((uint32_t)0x00000000) #define SMBUS_RELOAD_MODE I2C_CR2_RELOAD #define SMBUS_AUTOEND_MODE I2C_CR2_AUTOEND #define SMBUS_SENDPEC_MODE I2C_CR2_PECBYTE /** * @} */ /** @defgroup SMBUS_StartStopMode_definition SMBUS StartStopMode definition * @{ */ #define SMBUS_NO_STARTSTOP ((uint32_t)0x00000000) #define SMBUS_GENERATE_STOP I2C_CR2_STOP #define SMBUS_GENERATE_START_READ (uint32_t)(I2C_CR2_START | I2C_CR2_RD_WRN) #define SMBUS_GENERATE_START_WRITE I2C_CR2_START /** * @} */ /** @defgroup SMBUS_XferOptions_definition SMBUS XferOptions definition * @{ */ #define SMBUS_FIRST_FRAME ((uint32_t)(SMBUS_SOFTEND_MODE)) #define SMBUS_NEXT_FRAME ((uint32_t)(SMBUS_RELOAD_MODE | SMBUS_SOFTEND_MODE)) #define SMBUS_FIRST_AND_LAST_FRAME_NO_PEC SMBUS_AUTOEND_MODE #define SMBUS_LAST_FRAME_NO_PEC SMBUS_AUTOEND_MODE #define SMBUS_FIRST_AND_LAST_FRAME_WITH_PEC ((uint32_t)(SMBUS_AUTOEND_MODE | SMBUS_SENDPEC_MODE)) #define SMBUS_LAST_FRAME_WITH_PEC ((uint32_t)(SMBUS_AUTOEND_MODE | SMBUS_SENDPEC_MODE)) /** * @} */ /** @defgroup SMBUS_Interrupt_configuration_definition SMBUS Interrupt configuration definition * @brief SMBUS Interrupt definition * Elements values convention: 0xXXXXXXXX * - XXXXXXXX : Interrupt control mask * @{ */ #define SMBUS_IT_ERRI I2C_CR1_ERRIE #define SMBUS_IT_TCI I2C_CR1_TCIE #define SMBUS_IT_STOPI I2C_CR1_STOPIE #define SMBUS_IT_NACKI I2C_CR1_NACKIE #define SMBUS_IT_ADDRI I2C_CR1_ADDRIE #define SMBUS_IT_RXI I2C_CR1_RXIE #define SMBUS_IT_TXI I2C_CR1_TXIE #define SMBUS_IT_TX (SMBUS_IT_ERRI | SMBUS_IT_TCI | SMBUS_IT_STOPI | SMBUS_IT_NACKI | SMBUS_IT_TXI) #define SMBUS_IT_RX (SMBUS_IT_ERRI | SMBUS_IT_TCI | SMBUS_IT_NACKI | SMBUS_IT_RXI) #define SMBUS_IT_ALERT (SMBUS_IT_ERRI) #define SMBUS_IT_ADDR (SMBUS_IT_ADDRI | SMBUS_IT_STOPI | SMBUS_IT_NACKI) /** * @} */ /** @defgroup SMBUS_Flag_definition SMBUS Flag definition * @brief Flag definition * Elements values convention: 0xXXXXYYYY * - XXXXXXXX : Flag mask * @{ */ #define SMBUS_FLAG_TXE I2C_ISR_TXE #define SMBUS_FLAG_TXIS I2C_ISR_TXIS #define SMBUS_FLAG_RXNE I2C_ISR_RXNE #define SMBUS_FLAG_ADDR I2C_ISR_ADDR #define SMBUS_FLAG_AF I2C_ISR_NACKF #define SMBUS_FLAG_STOPF I2C_ISR_STOPF #define SMBUS_FLAG_TC I2C_ISR_TC #define SMBUS_FLAG_TCR I2C_ISR_TCR #define SMBUS_FLAG_BERR I2C_ISR_BERR #define SMBUS_FLAG_ARLO I2C_ISR_ARLO #define SMBUS_FLAG_OVR I2C_ISR_OVR #define SMBUS_FLAG_PECERR I2C_ISR_PECERR #define SMBUS_FLAG_TIMEOUT I2C_ISR_TIMEOUT #define SMBUS_FLAG_ALERT I2C_ISR_ALERT #define SMBUS_FLAG_BUSY I2C_ISR_BUSY #define SMBUS_FLAG_DIR I2C_ISR_DIR /** * @} */ /** * @} */ /* Exported macros ------------------------------------------------------------*/ /** @defgroup SMBUS_Exported_Macros SMBUS Exported Macros * @{ */ /** @brief Reset SMBUS handle state. * @param __HANDLE__: specifies the SMBUS Handle. * @retval None */ #define __HAL_SMBUS_RESET_HANDLE_STATE(__HANDLE__) ((__HANDLE__)->State = HAL_SMBUS_STATE_RESET) /** @brief Enable the specified SMBUS interrupts. * @param __HANDLE__: specifies the SMBUS Handle. * @param __INTERRUPT__: specifies the interrupt source to enable. * This parameter can be one of the following values: * @arg SMBUS_IT_ERRI: Errors interrupt enable * @arg SMBUS_IT_TCI: Transfer complete interrupt enable * @arg SMBUS_IT_STOPI: STOP detection interrupt enable * @arg SMBUS_IT_NACKI: NACK received interrupt enable * @arg SMBUS_IT_ADDRI: Address match interrupt enable * @arg SMBUS_IT_RXI: RX interrupt enable * @arg SMBUS_IT_TXI: TX interrupt enable * * @retval None */ #define __HAL_SMBUS_ENABLE_IT(__HANDLE__, __INTERRUPT__) ((__HANDLE__)->Instance->CR1 |= (__INTERRUPT__)) /** @brief Disable the specified SMBUS interrupts. * @param __HANDLE__: specifies the SMBUS Handle. * @param __INTERRUPT__: specifies the interrupt source to disable. * This parameter can be one of the following values: * @arg SMBUS_IT_ERRI: Errors interrupt enable * @arg SMBUS_IT_TCI: Transfer complete interrupt enable * @arg SMBUS_IT_STOPI: STOP detection interrupt enable * @arg SMBUS_IT_NACKI: NACK received interrupt enable * @arg SMBUS_IT_ADDRI: Address match interrupt enable * @arg SMBUS_IT_RXI: RX interrupt enable * @arg SMBUS_IT_TXI: TX interrupt enable * * @retval None */ #define __HAL_SMBUS_DISABLE_IT(__HANDLE__, __INTERRUPT__) ((__HANDLE__)->Instance->CR1 &= (~(__INTERRUPT__))) /** @brief Check whether the specified SMBUS interrupt source is enabled or not. * @param __HANDLE__: specifies the SMBUS Handle. * @param __INTERRUPT__: specifies the SMBUS interrupt source to check. * This parameter can be one of the following values: * @arg SMBUS_IT_ERRI: Errors interrupt enable * @arg SMBUS_IT_TCI: Transfer complete interrupt enable * @arg SMBUS_IT_STOPI: STOP detection interrupt enable * @arg SMBUS_IT_NACKI: NACK received interrupt enable * @arg SMBUS_IT_ADDRI: Address match interrupt enable * @arg SMBUS_IT_RXI: RX interrupt enable * @arg SMBUS_IT_TXI: TX interrupt enable * * @retval The new state of __IT__ (TRUE or FALSE). */ #define __HAL_SMBUS_GET_IT_SOURCE(__HANDLE__, __INTERRUPT__) ((((__HANDLE__)->Instance->CR1 & (__INTERRUPT__)) == (__INTERRUPT__)) ? SET : RESET) /** @brief Check whether the specified SMBUS flag is set or not. * @param __HANDLE__: specifies the SMBUS Handle. * @param __FLAG__: specifies the flag to check. * This parameter can be one of the following values: * @arg SMBUS_FLAG_TXE: Transmit data register empty * @arg SMBUS_FLAG_TXIS: Transmit interrupt status * @arg SMBUS_FLAG_RXNE: Receive data register not empty * @arg SMBUS_FLAG_ADDR: Address matched (slave mode) * @arg SMBUS_FLAG_AF: NACK received flag * @arg SMBUS_FLAG_STOPF: STOP detection flag * @arg SMBUS_FLAG_TC: Transfer complete (master mode) * @arg SMBUS_FLAG_TCR: Transfer complete reload * @arg SMBUS_FLAG_BERR: Bus error * @arg SMBUS_FLAG_ARLO: Arbitration lost * @arg SMBUS_FLAG_OVR: Overrun/Underrun * @arg SMBUS_FLAG_PECERR: PEC error in reception * @arg SMBUS_FLAG_TIMEOUT: Timeout or Tlow detection flag * @arg SMBUS_FLAG_ALERT: SMBus alert * @arg SMBUS_FLAG_BUSY: Bus busy * @arg SMBUS_FLAG_DIR: Transfer direction (slave mode) * * @retval The new state of __FLAG__ (TRUE or FALSE). */ #define SMBUS_FLAG_MASK ((uint32_t)0x0001FFFF) #define __HAL_SMBUS_GET_FLAG(__HANDLE__, __FLAG__) (((((__HANDLE__)->Instance->ISR) & ((__FLAG__) & SMBUS_FLAG_MASK)) == ((__FLAG__) & SMBUS_FLAG_MASK))) /** @brief Clear the SMBUS pending flags which are cleared by writing 1 in a specific bit. * @param __HANDLE__: specifies the SMBUS Handle. * @param __FLAG__: specifies the flag to clear. * This parameter can be any combination of the following values: * @arg SMBUS_FLAG_ADDR: Address matched (slave mode) * @arg SMBUS_FLAG_AF: NACK received flag * @arg SMBUS_FLAG_STOPF: STOP detection flag * @arg SMBUS_FLAG_BERR: Bus error * @arg SMBUS_FLAG_ARLO: Arbitration lost * @arg SMBUS_FLAG_OVR: Overrun/Underrun * @arg SMBUS_FLAG_PECERR: PEC error in reception * @arg SMBUS_FLAG_TIMEOUT: Timeout or Tlow detection flag * @arg SMBUS_FLAG_ALERT: SMBus alert * * @retval None */ #define __HAL_SMBUS_CLEAR_FLAG(__HANDLE__, __FLAG__) ((__HANDLE__)->Instance->ICR = (__FLAG__)) /** @brief Enable the specified SMBUS peripheral. * @param __HANDLE__: specifies the SMBUS Handle. * @retval None */ #define __HAL_SMBUS_ENABLE(__HANDLE__) (SET_BIT((__HANDLE__)->Instance->CR1, I2C_CR1_PE)) /** @brief Disable the specified SMBUS peripheral. * @param __HANDLE__: specifies the SMBUS Handle. * @retval None */ #define __HAL_SMBUS_DISABLE(__HANDLE__) (CLEAR_BIT((__HANDLE__)->Instance->CR1, I2C_CR1_PE)) /** @brief Generate a Non-Acknowledge SMBUS peripheral in Slave mode. * @param __HANDLE__: specifies the SMBUS Handle. * @retval None */ #define __HAL_SMBUS_GENERATE_NACK(__HANDLE__) (SET_BIT((__HANDLE__)->Instance->CR2, I2C_CR2_NACK)) /** * @} */ /* Private constants ---------------------------------------------------------*/ /* Private macros ------------------------------------------------------------*/ /** @defgroup SMBUS_Private_Macro SMBUS Private Macros * @{ */ #define IS_SMBUS_ANALOG_FILTER(FILTER) (((FILTER) == SMBUS_ANALOGFILTER_ENABLE) || \ ((FILTER) == SMBUS_ANALOGFILTER_DISABLE)) #define IS_SMBUS_ADDRESSING_MODE(MODE) (((MODE) == SMBUS_ADDRESSINGMODE_7BIT) || \ ((MODE) == SMBUS_ADDRESSINGMODE_10BIT)) #define IS_SMBUS_DUAL_ADDRESS(ADDRESS) (((ADDRESS) == SMBUS_DUALADDRESS_DISABLE) || \ ((ADDRESS) == SMBUS_DUALADDRESS_ENABLE)) #define IS_SMBUS_OWN_ADDRESS2_MASK(MASK) (((MASK) == SMBUS_OA2_NOMASK) || \ ((MASK) == SMBUS_OA2_MASK01) || \ ((MASK) == SMBUS_OA2_MASK02) || \ ((MASK) == SMBUS_OA2_MASK03) || \ ((MASK) == SMBUS_OA2_MASK04) || \ ((MASK) == SMBUS_OA2_MASK05) || \ ((MASK) == SMBUS_OA2_MASK06) || \ ((MASK) == SMBUS_OA2_MASK07)) #define IS_SMBUS_GENERAL_CALL(CALL) (((CALL) == SMBUS_GENERALCALL_DISABLE) || \ ((CALL) == SMBUS_GENERALCALL_ENABLE)) #define IS_SMBUS_NO_STRETCH(STRETCH) (((STRETCH) == SMBUS_NOSTRETCH_DISABLE) || \ ((STRETCH) == SMBUS_NOSTRETCH_ENABLE)) #define IS_SMBUS_PEC(PEC) (((PEC) == SMBUS_PEC_DISABLE) || \ ((PEC) == SMBUS_PEC_ENABLE)) #define IS_SMBUS_PERIPHERAL_MODE(MODE) (((MODE) == SMBUS_PERIPHERAL_MODE_SMBUS_HOST) || \ ((MODE) == SMBUS_PERIPHERAL_MODE_SMBUS_SLAVE) || \ ((MODE) == SMBUS_PERIPHERAL_MODE_SMBUS_SLAVE_ARP)) #define IS_SMBUS_TRANSFER_MODE(MODE) (((MODE) == SMBUS_RELOAD_MODE) || \ ((MODE) == SMBUS_AUTOEND_MODE) || \ ((MODE) == SMBUS_SOFTEND_MODE) || \ ((MODE) == (SMBUS_RELOAD_MODE | SMBUS_SENDPEC_MODE)) || \ ((MODE) == (SMBUS_AUTOEND_MODE | SMBUS_SENDPEC_MODE)) || \ ((MODE) == (SMBUS_AUTOEND_MODE | SMBUS_RELOAD_MODE)) || \ ((MODE) == (SMBUS_AUTOEND_MODE | SMBUS_SENDPEC_MODE | SMBUS_RELOAD_MODE ))) #define IS_SMBUS_TRANSFER_REQUEST(REQUEST) (((REQUEST) == SMBUS_GENERATE_STOP) || \ ((REQUEST) == SMBUS_GENERATE_START_READ) || \ ((REQUEST) == SMBUS_GENERATE_START_WRITE) || \ ((REQUEST) == SMBUS_NO_STARTSTOP)) #define IS_SMBUS_TRANSFER_OPTIONS_REQUEST(REQUEST) (((REQUEST) == SMBUS_FIRST_FRAME) || \ ((REQUEST) == SMBUS_NEXT_FRAME) || \ ((REQUEST) == SMBUS_FIRST_AND_LAST_FRAME_NO_PEC) || \ ((REQUEST) == SMBUS_LAST_FRAME_NO_PEC) || \ ((REQUEST) == SMBUS_FIRST_AND_LAST_FRAME_WITH_PEC) || \ ((REQUEST) == SMBUS_LAST_FRAME_WITH_PEC)) #define SMBUS_RESET_CR1(__HANDLE__) ((__HANDLE__)->Instance->CR1 &= (uint32_t)~((uint32_t)(I2C_CR1_SMBHEN | I2C_CR1_SMBDEN | I2C_CR1_PECEN))) #define SMBUS_RESET_CR2(__HANDLE__) ((__HANDLE__)->Instance->CR2 &= (uint32_t)~((uint32_t)(I2C_CR2_SADD | I2C_CR2_HEAD10R | I2C_CR2_NBYTES | I2C_CR2_RELOAD | I2C_CR2_RD_WRN))) #define SMBUS_GENERATE_START(__ADDMODE__,__ADDRESS__) (((__ADDMODE__) == SMBUS_ADDRESSINGMODE_7BIT) ? (uint32_t)((((uint32_t)(__ADDRESS__) & (I2C_CR2_SADD)) | (I2C_CR2_START) | (I2C_CR2_AUTOEND)) & (~I2C_CR2_RD_WRN)) : \ (uint32_t)((((uint32_t)(__ADDRESS__) & (I2C_CR2_SADD)) | (I2C_CR2_ADD10) | (I2C_CR2_START)) & (~I2C_CR2_RD_WRN))) #define SMBUS_GET_ADDR_MATCH(__HANDLE__) (((__HANDLE__)->Instance->ISR & I2C_ISR_ADDCODE) >> 17) #define SMBUS_GET_DIR(__HANDLE__) (((__HANDLE__)->Instance->ISR & I2C_ISR_DIR) >> 16) #define SMBUS_GET_STOP_MODE(__HANDLE__) ((__HANDLE__)->Instance->CR2 & I2C_CR2_AUTOEND) #define SMBUS_GET_PEC_MODE(__HANDLE__) ((__HANDLE__)->Instance->CR2 & I2C_CR2_PECBYTE) #define SMBUS_GET_ALERT_ENABLED(__HANDLE__) ((__HANDLE__)->Instance->CR1 & I2C_CR1_ALERTEN) #define SMBUS_GET_ISR_REG(__HANDLE__) ((__HANDLE__)->Instance->ISR) #define SMBUS_CHECK_FLAG(__ISR__, __FLAG__) ((((__ISR__) & ((__FLAG__) & SMBUS_FLAG_MASK)) == ((__FLAG__) & SMBUS_FLAG_MASK))) #define IS_SMBUS_OWN_ADDRESS1(ADDRESS1) ((ADDRESS1) <= (uint32_t)0x000003FF) #define IS_SMBUS_OWN_ADDRESS2(ADDRESS2) ((ADDRESS2) <= (uint16_t)0x00FF) /** * @} */ /* Private Functions ---------------------------------------------------------*/ /** @defgroup SMBUS_Private_Functions SMBUS Private Functions * @{ */ /* Private functions are defined in stm32l4xx_hal_smbus.c file */ /** * @} */ /* Exported functions --------------------------------------------------------*/ /** @addtogroup SMBUS_Exported_Functions SMBUS Exported Functions * @{ */ /** @addtogroup SMBUS_Exported_Functions_Group1 Initialization and de-initialization functions * @{ */ /* Initialization and de-initialization functions **********************************/ HAL_StatusTypeDef HAL_SMBUS_Init(SMBUS_HandleTypeDef *hsmbus); HAL_StatusTypeDef HAL_SMBUS_DeInit (SMBUS_HandleTypeDef *hsmbus); void HAL_SMBUS_MspInit(SMBUS_HandleTypeDef *hsmbus); void HAL_SMBUS_MspDeInit(SMBUS_HandleTypeDef *hsmbus); /** * @} */ /** @addtogroup SMBUS_Exported_Functions_Group2 Input and Output operation functions * @{ */ /* IO operation functions *****************************************************/ /** @addtogroup Blocking_mode_Polling Blocking mode Polling * @{ */ /******* Blocking mode: Polling */ HAL_StatusTypeDef HAL_SMBUS_IsDeviceReady(SMBUS_HandleTypeDef *hsmbus, uint16_t DevAddress, uint32_t Trials, uint32_t Timeout); /** * @} */ /** @addtogroup Non-Blocking_mode_Interrupt Non-Blocking mode Interrupt * @{ */ /******* Non-Blocking mode: Interrupt */ HAL_StatusTypeDef HAL_SMBUS_Master_Transmit_IT(SMBUS_HandleTypeDef *hsmbus, uint16_t DevAddress, uint8_t *pData, uint16_t Size, uint32_t XferOptions); HAL_StatusTypeDef HAL_SMBUS_Master_Receive_IT(SMBUS_HandleTypeDef *hsmbus, uint16_t DevAddress, uint8_t *pData, uint16_t Size, uint32_t XferOptions); HAL_StatusTypeDef HAL_SMBUS_Master_Abort_IT(SMBUS_HandleTypeDef *hsmbus, uint16_t DevAddress); HAL_StatusTypeDef HAL_SMBUS_Slave_Transmit_IT(SMBUS_HandleTypeDef *hsmbus, uint8_t *pData, uint16_t Size, uint32_t XferOptions); HAL_StatusTypeDef HAL_SMBUS_Slave_Receive_IT(SMBUS_HandleTypeDef *hsmbus, uint8_t *pData, uint16_t Size, uint32_t XferOptions); HAL_StatusTypeDef HAL_SMBUS_EnableAlert_IT(SMBUS_HandleTypeDef *hsmbus); HAL_StatusTypeDef HAL_SMBUS_DisableAlert_IT(SMBUS_HandleTypeDef *hsmbus); HAL_StatusTypeDef HAL_SMBUS_EnableListen_IT(SMBUS_HandleTypeDef *hsmbus); HAL_StatusTypeDef HAL_SMBUS_DisableListen_IT(SMBUS_HandleTypeDef *hsmbus); /** * @} */ /** @addtogroup SMBUS_IRQ_Handler_and_Callbacks IRQ Handler and Callbacks * @{ */ /******* SMBUS IRQHandler and Callbacks used in non blocking modes (Interrupt) */ void HAL_SMBUS_EV_IRQHandler(SMBUS_HandleTypeDef *hsmbus); void HAL_SMBUS_ER_IRQHandler(SMBUS_HandleTypeDef *hsmbus); void HAL_SMBUS_MasterTxCpltCallback(SMBUS_HandleTypeDef *hsmbus); void HAL_SMBUS_MasterRxCpltCallback(SMBUS_HandleTypeDef *hsmbus); void HAL_SMBUS_SlaveTxCpltCallback(SMBUS_HandleTypeDef *hsmbus); void HAL_SMBUS_SlaveRxCpltCallback(SMBUS_HandleTypeDef *hsmbus); void HAL_SMBUS_AddrCallback(SMBUS_HandleTypeDef *hsmbus, uint8_t TransferDirection, uint16_t AddrMatchCode); void HAL_SMBUS_ListenCpltCallback(SMBUS_HandleTypeDef *hsmbus); void HAL_SMBUS_ErrorCallback(SMBUS_HandleTypeDef *hsmbus); /** * @} */ /** @addtogroup SMBUS_Exported_Functions_Group3 Peripheral State and Errors functions * @{ */ /* Peripheral State and Errors functions **************************************************/ uint32_t HAL_SMBUS_GetState(SMBUS_HandleTypeDef *hsmbus); uint32_t HAL_SMBUS_GetError(SMBUS_HandleTypeDef *hsmbus); /** * @} */ /** * @} */ /** * @} */ /** * @} */ /** * @} */ #ifdef __cplusplus } #endif #endif /* __STM32F0xx_HAL_SMBUS_H */ /************************ (C) COPYRIGHT STMicroelectronics *****END OF FILE****/ ================================================ FILE: Zelig/mbed/TARGET_NUCLEO_F091RC/stm32f0xx_hal_spi.h ================================================ /** ****************************************************************************** * @file stm32f0xx_hal_spi.h * @author MCD Application Team * @version V1.3.0 * @date 26-June-2015 * @brief Header file of SPI HAL module. ****************************************************************************** * @attention * *

© COPYRIGHT(c) 2015 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. * ****************************************************************************** */ /* Define to prevent recursive inclusion -------------------------------------*/ #ifndef __STM32F0xx_HAL_SPI_H #define __STM32F0xx_HAL_SPI_H #ifdef __cplusplus extern "C" { #endif /* Includes ------------------------------------------------------------------*/ #include "stm32f0xx_hal_def.h" /** @addtogroup STM32F0xx_HAL_Driver * @{ */ /** @addtogroup SPI * @{ */ /* Exported types ------------------------------------------------------------*/ /** @defgroup SPI_Exported_Types SPI Exported Types * @{ */ /** * @brief SPI Configuration Structure definition */ typedef struct { uint32_t Mode; /*!< Specifies the SPI operating mode. This parameter can be a value of @ref SPI_Mode */ uint32_t Direction; /*!< Specifies the SPI bidirectional mode state. This parameter can be a value of @ref SPI_Direction */ uint32_t DataSize; /*!< Specifies the SPI data size. This parameter can be a value of @ref SPI_Data_Size */ uint32_t CLKPolarity; /*!< Specifies the serial clock steady state. This parameter can be a value of @ref SPI_Clock_Polarity */ uint32_t CLKPhase; /*!< Specifies the clock active edge for the bit capture. This parameter can be a value of @ref SPI_Clock_Phase */ uint32_t NSS; /*!< Specifies whether the NSS signal is managed by hardware (NSS pin) or by software using the SSI bit. This parameter can be a value of @ref SPI_Slave_Select_management */ uint32_t BaudRatePrescaler; /*!< Specifies the Baud Rate prescaler value which will be used to configure the transmit and receive SCK clock. This parameter can be a value of @ref SPI_BaudRate_Prescaler @note The communication clock is derived from the master clock. The slave clock does not need to be set. */ uint32_t FirstBit; /*!< Specifies whether data transfers start from MSB or LSB bit. This parameter can be a value of @ref SPI_MSB_LSB_transmission */ uint32_t TIMode; /*!< Specifies if the TI mode is enabled or not . This parameter can be a value of @ref SPI_TI_mode */ uint32_t CRCCalculation; /*!< Specifies if the CRC calculation is enabled or not. This parameter can be a value of @ref SPI_CRC_Calculation */ uint32_t CRCPolynomial; /*!< Specifies the polynomial used for the CRC calculation. This parameter must be a number between Min_Data = 0 and Max_Data = 65535 */ uint32_t CRCLength; /*!< Specifies the CRC Length used for the CRC calculation. CRC Length is only used with Data8 and Data16, not other data size This parameter can be a value of @ref SPI_CRC_length */ uint32_t NSSPMode; /*!< Specifies whether the NSSP signal is enabled or not . This parameter can be a value of @ref SPI_NSSP_Mode This mode is activated by the NSSP bit in the SPIx_CR2 register and it takes effect only if the SPI interface is configured as Motorola SPI master (FRF=0) with capture on the first edge (SPIx_CR1 CPHA = 0, CPOL setting is ignored).. */ } SPI_InitTypeDef; /** * @brief HAL State structures definition */ typedef enum { HAL_SPI_STATE_RESET = 0x00, /*!< Peripheral not Initialized */ HAL_SPI_STATE_READY = 0x01, /*!< Peripheral Initialized and ready for use */ HAL_SPI_STATE_BUSY = 0x02, /*!< an internal process is ongoing */ HAL_SPI_STATE_BUSY_TX = 0x03, /*!< Data Transmission process is ongoing */ HAL_SPI_STATE_BUSY_RX = 0x04, /*!< Data Reception process is ongoing */ HAL_SPI_STATE_BUSY_TX_RX = 0x05, /*!< Data Transmission and Reception process is ongoing */ HAL_SPI_STATE_ERROR = 0x06 /*!< SPI error state */ }HAL_SPI_StateTypeDef; /** * @brief SPI handle Structure definition */ typedef struct __SPI_HandleTypeDef { SPI_TypeDef *Instance; /* SPI registers base address */ SPI_InitTypeDef Init; /* SPI communication parameters */ uint8_t *pTxBuffPtr; /* Pointer to SPI Tx transfer Buffer */ uint16_t TxXferSize; /* SPI Tx Transfer size */ uint16_t TxXferCount; /* SPI Tx Transfer Counter */ uint8_t *pRxBuffPtr; /* Pointer to SPI Rx transfer Buffer */ uint16_t RxXferSize; /* SPI Rx Transfer size */ uint16_t RxXferCount; /* SPI Rx Transfer Counter */ uint32_t CRCSize; /* SPI CRC size used for the transfer */ void (*RxISR)(struct __SPI_HandleTypeDef *hspi); /* function pointer on Rx IRQ handler */ void (*TxISR)(struct __SPI_HandleTypeDef *hspi); /* function pointer on Tx IRQ handler */ DMA_HandleTypeDef *hdmatx; /* SPI Tx DMA Handle parameters */ DMA_HandleTypeDef *hdmarx; /* SPI Rx DMA Handle parameters */ HAL_LockTypeDef Lock; /* Locking object */ __IO HAL_SPI_StateTypeDef State; /* SPI communication state */ uint32_t ErrorCode; /* SPI Error code */ }SPI_HandleTypeDef; /** * @} */ /* Exported constants --------------------------------------------------------*/ /** @defgroup SPI_Exported_Constants SPI Exported Constants * @{ */ /** @defgroup SPI_Error_Code SPI Error Code * @{ */ #define HAL_SPI_ERROR_NONE (uint32_t)0x00000000 /*!< No error */ #define HAL_SPI_ERROR_MODF (uint32_t)0x00000001 /*!< MODF error */ #define HAL_SPI_ERROR_CRC (uint32_t)0x00000002 /*!< CRC error */ #define HAL_SPI_ERROR_OVR (uint32_t)0x00000004 /*!< OVR error */ #define HAL_SPI_ERROR_FRE (uint32_t)0x00000008 /*!< FRE error */ #define HAL_SPI_ERROR_DMA (uint32_t)0x00000010 /*!< DMA transfer error */ #define HAL_SPI_ERROR_FLAG (uint32_t)0x00000020 /*!< Error on BSY/TXE/FTLVL/FRLVL Flag */ #define HAL_SPI_ERROR_UNKNOW (uint32_t)0x00000040 /*!< Unknown error */ /** * @} */ /** @defgroup SPI_Mode SPI Mode * @{ */ #define SPI_MODE_SLAVE ((uint32_t)0x00000000) #define SPI_MODE_MASTER (SPI_CR1_MSTR | SPI_CR1_SSI) #define IS_SPI_MODE(MODE) (((MODE) == SPI_MODE_SLAVE) || \ ((MODE) == SPI_MODE_MASTER)) /** * @} */ /** @defgroup SPI_Direction SPI Direction Mode * @{ */ #define SPI_DIRECTION_2LINES ((uint32_t)0x00000000) #define SPI_DIRECTION_2LINES_RXONLY SPI_CR1_RXONLY #define SPI_DIRECTION_1LINE SPI_CR1_BIDIMODE #define IS_SPI_DIRECTION(MODE) (((MODE) == SPI_DIRECTION_2LINES) || \ ((MODE) == SPI_DIRECTION_2LINES_RXONLY) ||\ ((MODE) == SPI_DIRECTION_1LINE)) #define IS_SPI_DIRECTION_2LINES(MODE) ((MODE) == SPI_DIRECTION_2LINES) #define IS_SPI_DIRECTION_2LINES_OR_1LINE(MODE) (((MODE) == SPI_DIRECTION_2LINES)|| \ ((MODE) == SPI_DIRECTION_1LINE)) /** * @} */ /** @defgroup SPI_Data_Size SPI Data Size * @{ */ #define SPI_DATASIZE_4BIT ((uint32_t)0x0300) /*!< SPI Datasize = 4bits */ #define SPI_DATASIZE_5BIT ((uint32_t)0x0400) /*!< SPI Datasize = 5bits */ #define SPI_DATASIZE_6BIT ((uint32_t)0x0500) /*!< SPI Datasize = 6bits */ #define SPI_DATASIZE_7BIT ((uint32_t)0x0600) /*!< SPI Datasize = 7bits */ #define SPI_DATASIZE_8BIT ((uint32_t)0x0700) /*!< SPI Datasize = 8bits */ #define SPI_DATASIZE_9BIT ((uint32_t)0x0800) /*!< SPI Datasize = 9bits */ #define SPI_DATASIZE_10BIT ((uint32_t)0x0900) /*!< SPI Datasize = 10bits */ #define SPI_DATASIZE_11BIT ((uint32_t)0x0A00) /*!< SPI Datasize = 11bits */ #define SPI_DATASIZE_12BIT ((uint32_t)0x0B00) /*!< SPI Datasize = 12bits */ #define SPI_DATASIZE_13BIT ((uint32_t)0x0C00) /*!< SPI Datasize = 13bits */ #define SPI_DATASIZE_14BIT ((uint32_t)0x0D00) /*!< SPI Datasize = 14bits */ #define SPI_DATASIZE_15BIT ((uint32_t)0x0E00) /*!< SPI Datasize = 15bits */ #define SPI_DATASIZE_16BIT ((uint32_t)0x0F00) /*!< SPI Datasize = 16bits */ #define IS_SPI_DATASIZE(DATASIZE) (((DATASIZE) == SPI_DATASIZE_16BIT) || \ ((DATASIZE) == SPI_DATASIZE_15BIT) || \ ((DATASIZE) == SPI_DATASIZE_14BIT) || \ ((DATASIZE) == SPI_DATASIZE_13BIT) || \ ((DATASIZE) == SPI_DATASIZE_12BIT) || \ ((DATASIZE) == SPI_DATASIZE_11BIT) || \ ((DATASIZE) == SPI_DATASIZE_10BIT) || \ ((DATASIZE) == SPI_DATASIZE_9BIT) || \ ((DATASIZE) == SPI_DATASIZE_8BIT) || \ ((DATASIZE) == SPI_DATASIZE_7BIT) || \ ((DATASIZE) == SPI_DATASIZE_6BIT) || \ ((DATASIZE) == SPI_DATASIZE_5BIT) || \ ((DATASIZE) == SPI_DATASIZE_4BIT)) /** * @} */ /** @defgroup SPI_Clock_Polarity SPI Clock Polarity * @{ */ #define SPI_POLARITY_LOW ((uint32_t)0x00000000) /*!< SPI polarity Low */ #define SPI_POLARITY_HIGH SPI_CR1_CPOL /*!< SPI polarity High */ #define IS_SPI_CPOL(CPOL) (((CPOL) == SPI_POLARITY_LOW) || \ ((CPOL) == SPI_POLARITY_HIGH)) /** * @} */ /** @defgroup SPI_Clock_Phase SPI Clock Phase * @{ */ #define SPI_PHASE_1EDGE ((uint32_t)0x00000000) /*!< SPI Phase 1EDGE */ #define SPI_PHASE_2EDGE SPI_CR1_CPHA /*!< SPI Phase 2EDGE */ #define IS_SPI_CPHA(CPHA) (((CPHA) == SPI_PHASE_1EDGE) || \ ((CPHA) == SPI_PHASE_2EDGE)) /** * @} */ /** @defgroup SPI_Slave_Select_management SPI Slave Select management * @{ */ #define SPI_NSS_SOFT SPI_CR1_SSM #define SPI_NSS_HARD_INPUT ((uint32_t)0x00000000) #define SPI_NSS_HARD_OUTPUT ((uint32_t)0x00040000) #define IS_SPI_NSS(NSS) (((NSS) == SPI_NSS_SOFT) || \ ((NSS) == SPI_NSS_HARD_INPUT) || \ ((NSS) == SPI_NSS_HARD_OUTPUT)) /** * @} */ /** @defgroup SPI_NSSP_Mode SPI NSS Pulse Mode * @{ */ #define SPI_NSS_PULSE_ENABLE SPI_CR2_NSSP #define SPI_NSS_PULSE_DISABLE ((uint32_t)0x00000000) #define IS_SPI_NSSP(NSSP) (((NSSP) == SPI_NSS_PULSE_ENABLE) || \ ((NSSP) == SPI_NSS_PULSE_DISABLE)) /** * @} */ /** @defgroup SPI_BaudRate_Prescaler SPI BaudRate Prescaler * @{ */ #define SPI_BAUDRATEPRESCALER_2 ((uint32_t)0x00000000) #define SPI_BAUDRATEPRESCALER_4 ((uint32_t)0x00000008) #define SPI_BAUDRATEPRESCALER_8 ((uint32_t)0x00000010) #define SPI_BAUDRATEPRESCALER_16 ((uint32_t)0x00000018) #define SPI_BAUDRATEPRESCALER_32 ((uint32_t)0x00000020) #define SPI_BAUDRATEPRESCALER_64 ((uint32_t)0x00000028) #define SPI_BAUDRATEPRESCALER_128 ((uint32_t)0x00000030) #define SPI_BAUDRATEPRESCALER_256 ((uint32_t)0x00000038) #define IS_SPI_BAUDRATE_PRESCALER(PRESCALER) (((PRESCALER) == SPI_BAUDRATEPRESCALER_2) || \ ((PRESCALER) == SPI_BAUDRATEPRESCALER_4) || \ ((PRESCALER) == SPI_BAUDRATEPRESCALER_8) || \ ((PRESCALER) == SPI_BAUDRATEPRESCALER_16) || \ ((PRESCALER) == SPI_BAUDRATEPRESCALER_32) || \ ((PRESCALER) == SPI_BAUDRATEPRESCALER_64) || \ ((PRESCALER) == SPI_BAUDRATEPRESCALER_128) || \ ((PRESCALER) == SPI_BAUDRATEPRESCALER_256)) /** * @} */ /** @defgroup SPI_MSB_LSB_transmission SPI MSB LSB transmission * @{ */ #define SPI_FIRSTBIT_MSB ((uint32_t)0x00000000) #define SPI_FIRSTBIT_LSB SPI_CR1_LSBFIRST #define IS_SPI_FIRST_BIT(BIT) (((BIT) == SPI_FIRSTBIT_MSB) || \ ((BIT) == SPI_FIRSTBIT_LSB)) /** * @} */ /** @defgroup SPI_TI_mode SPI TI mode * @{ */ #define SPI_TIMODE_DISABLE ((uint32_t)0x00000000) #define SPI_TIMODE_ENABLE SPI_CR2_FRF #define IS_SPI_TIMODE(MODE) (((MODE) == SPI_TIMODE_DISABLE) || \ ((MODE) == SPI_TIMODE_ENABLE)) /** * @} */ /** @defgroup SPI_CRC_Calculation SPI CRC Calculation * @{ */ #define SPI_CRCCALCULATION_DISABLE ((uint32_t)0x00000000) #define SPI_CRCCALCULATION_ENABLE SPI_CR1_CRCEN #define IS_SPI_CRC_CALCULATION(CALCULATION) (((CALCULATION) == SPI_CRCCALCULATION_DISABLE) || \ ((CALCULATION) == SPI_CRCCALCULATION_ENABLE)) /** * @} */ /** @defgroup SPI_CRC_length SPI CRC Length * @{ * This parameter can be one of the following values: * SPI_CRC_LENGTH_DATASIZE: aligned with the data size * SPI_CRC_LENGTH_8BIT : CRC 8bit * SPI_CRC_LENGTH_16BIT : CRC 16bit */ #define SPI_CRC_LENGTH_DATASIZE ((uint32_t)0x00000000) #define SPI_CRC_LENGTH_8BIT ((uint32_t)0x00000001) #define SPI_CRC_LENGTH_16BIT ((uint32_t)0x00000002) #define IS_SPI_CRC_LENGTH(LENGTH) (((LENGTH) == SPI_CRC_LENGTH_DATASIZE) ||\ ((LENGTH) == SPI_CRC_LENGTH_8BIT) || \ ((LENGTH) == SPI_CRC_LENGTH_16BIT)) /** * @} */ /** @defgroup SPI_FIFO_reception_threshold SPI FIFO Reception Threshold * @{ * This parameter can be one of the following values: * SPI_RXFIFO_THRESHOLD or SPI_RXFIFO_THRESHOLD_QF : * RXNE event is generated if the FIFO * level is greater or equal to 1/2(16-bits). * SPI_RXFIFO_THRESHOLD_HF: RXNE event is generated if the FIFO * level is greater or equal to 1/4(8 bits). */ #define SPI_RXFIFO_THRESHOLD SPI_CR2_FRXTH #define SPI_RXFIFO_THRESHOLD_QF SPI_CR2_FRXTH #define SPI_RXFIFO_THRESHOLD_HF ((uint32_t)0x00000000) /** * @} */ /** @defgroup SPI_Interrupt_configuration_definition SPI Interrupt configuration definition * @brief SPI Interrupt definition * Elements values convention: 0xXXXXXXXX * - XXXXXXXX : Interrupt control mask * @{ */ #define SPI_IT_TXE SPI_CR2_TXEIE #define SPI_IT_RXNE SPI_CR2_RXNEIE #define SPI_IT_ERR SPI_CR2_ERRIE /** * @} */ /** @defgroup SPI_Flag_definition SPI Flag definition * @brief Flag definition * Elements values convention: 0xXXXXYYYY * - XXXX : Flag register Index * - YYYY : Flag mask * @{ */ #define SPI_FLAG_RXNE SPI_SR_RXNE /* SPI status flag: Rx buffer not empty flag */ #define SPI_FLAG_TXE SPI_SR_TXE /* SPI status flag: Tx buffer empty flag */ #define SPI_FLAG_BSY SPI_SR_BSY /* SPI status flag: Busy flag */ #define SPI_FLAG_CRCERR SPI_SR_CRCERR /* SPI Error flag: CRC error flag */ #define SPI_FLAG_MODF SPI_SR_MODF /* SPI Error flag: Mode fault flag */ #define SPI_FLAG_OVR SPI_SR_OVR /* SPI Error flag: Overrun flag */ #define SPI_FLAG_FRE SPI_SR_FRE /* SPI Error flag: TI mode frame format error flag */ #define SPI_FLAG_FTLVL SPI_SR_FTLVL /* SPI fifo transmission level */ #define SPI_FLAG_FRLVL SPI_SR_FRLVL /* SPI fifo reception level */ /** * @} */ /** @defgroup SPI_transmission_fifo_status_level SPI Transmission FIFO Status Level * @{ */ #define SPI_FTLVL_EMPTY ((uint32_t)0x0000) #define SPI_FTLVL_QUARTER_FULL ((uint32_t)0x0800) #define SPI_FTLVL_HALF_FULL ((uint32_t)0x1000) #define SPI_FTLVL_FULL ((uint32_t)0x1800) /** * @} */ /** @defgroup SPI_reception_fifo_status_level SPI Reception FIFO Status Level * @{ */ #define SPI_FRLVL_EMPTY ((uint32_t)0x0000) #define SPI_FRLVL_QUARTER_FULL ((uint32_t)0x0200) #define SPI_FRLVL_HALF_FULL ((uint32_t)0x0400) #define SPI_FRLVL_FULL ((uint32_t)0x0600) /** * @} */ /** * @} */ /* Exported macros ------------------------------------------------------------*/ /** @defgroup SPI_Exported_Macros SPI Exported Macros * @{ */ /** @brief Reset SPI handle state. * @param __HANDLE__: SPI handle. * @retval None */ #define __HAL_SPI_RESET_HANDLE_STATE(__HANDLE__) ((__HANDLE__)->State = HAL_SPI_STATE_RESET) /** @brief Enable or disable the specified SPI interrupts. * @param __HANDLE__: specifies the SPI Handle. * This parameter can be SPI where x: 1, 2, or 3 to select the SPI peripheral. * @param __INTERRUPT__: specifies the interrupt source to enable or disable. * This parameter can be one of the following values: * @arg SPI_IT_TXE: Tx buffer empty interrupt enable * @arg SPI_IT_RXNE: RX buffer not empty interrupt enable * @arg SPI_IT_ERR: Error interrupt enable * @retval None */ #define __HAL_SPI_ENABLE_IT(__HANDLE__, __INTERRUPT__) ((__HANDLE__)->Instance->CR2 |= (__INTERRUPT__)) #define __HAL_SPI_DISABLE_IT(__HANDLE__, __INTERRUPT__) ((__HANDLE__)->Instance->CR2 &= (~(__INTERRUPT__))) /** @brief Check whether the specified SPI interrupt source is enabled or not. * @param __HANDLE__: specifies the SPI Handle. * This parameter can be SPI where x: 1, 2, or 3 to select the SPI peripheral. * @param __INTERRUPT__: specifies the SPI interrupt source to check. * This parameter can be one of the following values: * @arg SPI_IT_TXE: Tx buffer empty interrupt enable * @arg SPI_IT_RXNE: RX buffer not empty interrupt enable * @arg SPI_IT_ERR: Error interrupt enable * @retval The new state of __IT__ (TRUE or FALSE). */ #define __HAL_SPI_GET_IT_SOURCE(__HANDLE__, __INTERRUPT__) ((((__HANDLE__)->Instance->CR2 & (__INTERRUPT__)) == (__INTERRUPT__)) ? SET : RESET) /** @brief Check whether the specified SPI flag is set or not. * @param __HANDLE__: specifies the SPI Handle. * This parameter can be SPI where x: 1, 2, or 3 to select the SPI peripheral. * @param __FLAG__: specifies the flag to check. * This parameter can be one of the following values: * @arg SPI_FLAG_RXNE: Receive buffer not empty flag * @arg SPI_FLAG_TXE: Transmit buffer empty flag * @arg SPI_FLAG_CRCERR: CRC error flag * @arg SPI_FLAG_MODF: Mode fault flag * @arg SPI_FLAG_OVR: Overrun flag * @arg SPI_FLAG_BSY: Busy flag * @arg SPI_FLAG_FRE: Frame format error flag * @arg SPI_FLAG_FTLVL: SPI fifo transmission level * @arg SPI_FLAG_FRLVL: SPI fifo reception level * @retval The new state of __FLAG__ (TRUE or FALSE). */ #define __HAL_SPI_GET_FLAG(__HANDLE__, __FLAG__) ((((__HANDLE__)->Instance->SR) & (__FLAG__)) == (__FLAG__)) /** @brief Clear the SPI CRCERR pending flag. * @param __HANDLE__: specifies the SPI Handle. * This parameter can be SPI where x: 1, 2, or 3 to select the SPI peripheral. * @retval None */ #define __HAL_SPI_CLEAR_CRCERRFLAG(__HANDLE__) ((__HANDLE__)->Instance->SR = (uint16_t)(~SPI_FLAG_CRCERR)) /** @brief Clear the SPI MODF pending flag. * @param __HANDLE__: specifies the SPI Handle. * This parameter can be SPI where x: 1, 2, or 3 to select the SPI peripheral. * * @retval None */ #define __HAL_SPI_CLEAR_MODFFLAG(__HANDLE__) \ do{ \ __IO uint32_t tmpreg; \ tmpreg = (__HANDLE__)->Instance->SR; \ (__HANDLE__)->Instance->CR1 &= (~SPI_CR1_SPE); \ UNUSED(tmpreg); \ } while(0) /** @brief Clear the SPI OVR pending flag. * @param __HANDLE__: specifies the SPI Handle. * This parameter can be SPI where x: 1, 2, or 3 to select the SPI peripheral. * * @retval None */ #define __HAL_SPI_CLEAR_OVRFLAG(__HANDLE__) \ do{ \ __IO uint32_t tmpreg; \ tmpreg = (__HANDLE__)->Instance->DR; \ tmpreg = (__HANDLE__)->Instance->SR; \ UNUSED(tmpreg); \ } while(0) /** @brief Clear the SPI FRE pending flag. * @param __HANDLE__: specifies the SPI Handle. * This parameter can be SPI where x: 1, 2, or 3 to select the SPI peripheral. * * @retval None */ #define __HAL_SPI_CLEAR_FREFLAG(__HANDLE__) \ do{ \ __IO uint32_t tmpreg; \ tmpreg = (__HANDLE__)->Instance->SR; \ UNUSED(tmpreg); \ } while(0) /** @brief Enable the SPI peripheral. * @param __HANDLE__: specifies the SPI Handle. * This parameter can be SPI where x: 1, 2, or 3 to select the SPI peripheral. * @retval None */ #define __HAL_SPI_ENABLE(__HANDLE__) ((__HANDLE__)->Instance->CR1 |= SPI_CR1_SPE) /** @brief Disable the SPI peripheral. * @param __HANDLE__: specifies the SPI Handle. * This parameter can be SPI where x: 1, 2, or 3 to select the SPI peripheral. * @retval None */ #define __HAL_SPI_DISABLE(__HANDLE__) ((__HANDLE__)->Instance->CR1 &= (~SPI_CR1_SPE)) /** * @} */ /* Private macros --------------------------------------------------------*/ /** @defgroup SPI_Private_Macros SPI Private Macros * @{ */ /** @brief Set the SPI transmit-only mode. * @param __HANDLE__: specifies the SPI Handle. * This parameter can be SPI where x: 1, 2, or 3 to select the SPI peripheral. * @retval None */ #define SPI_1LINE_TX(__HANDLE__) ((__HANDLE__)->Instance->CR1 |= SPI_CR1_BIDIOE) /** @brief Set the SPI receive-only mode. * @param __HANDLE__: specifies the SPI Handle. * This parameter can be SPI where x: 1, 2, or 3 to select the SPI peripheral. * @retval None */ #define SPI_1LINE_RX(__HANDLE__) ((__HANDLE__)->Instance->CR1 &= (~SPI_CR1_BIDIOE)) /** @brief Reset the CRC calculation of the SPI. * @param __HANDLE__: specifies the SPI Handle. * This parameter can be SPI where x: 1, 2, or 3 to select the SPI peripheral. * @retval None */ #define SPI_RESET_CRC(__HANDLE__) do{(__HANDLE__)->Instance->CR1 &= (uint16_t)(~SPI_CR1_CRCEN);\ (__HANDLE__)->Instance->CR1 |= SPI_CR1_CRCEN;}while(0) #define IS_SPI_CRC_POLYNOMIAL(POLYNOMIAL) (((POLYNOMIAL) >= 0x1) && ((POLYNOMIAL) <= 0xFFFF)) /** * @} */ /* Include SPI HAL Extended module */ #include "stm32f0xx_hal_spi_ex.h" /* Exported functions --------------------------------------------------------*/ /** @addtogroup SPI_Exported_Functions * @{ */ /* Initialization and de-initialization functions ****************************/ /** @addtogroup SPI_Exported_Functions_Group1 * @{ */ HAL_StatusTypeDef HAL_SPI_Init(SPI_HandleTypeDef *hspi); HAL_StatusTypeDef HAL_SPI_DeInit (SPI_HandleTypeDef *hspi); void HAL_SPI_MspInit(SPI_HandleTypeDef *hspi); void HAL_SPI_MspDeInit(SPI_HandleTypeDef *hspi); /** * @} */ /* IO operation functions *****************************************************/ /** @addtogroup SPI_Exported_Functions_Group2 * @{ */ HAL_StatusTypeDef HAL_SPI_Transmit(SPI_HandleTypeDef *hspi, uint8_t *pData, uint16_t Size, uint32_t Timeout); HAL_StatusTypeDef HAL_SPI_Receive(SPI_HandleTypeDef *hspi, uint8_t *pData, uint16_t Size, uint32_t Timeout); HAL_StatusTypeDef HAL_SPI_TransmitReceive(SPI_HandleTypeDef *hspi, uint8_t *pTxData, uint8_t *pRxData, uint16_t Size, uint32_t Timeout); HAL_StatusTypeDef HAL_SPI_Transmit_IT(SPI_HandleTypeDef *hspi, uint8_t *pData, uint16_t Size); HAL_StatusTypeDef HAL_SPI_Receive_IT(SPI_HandleTypeDef *hspi, uint8_t *pData, uint16_t Size); HAL_StatusTypeDef HAL_SPI_TransmitReceive_IT(SPI_HandleTypeDef *hspi, uint8_t *pTxData, uint8_t *pRxData, uint16_t Size); HAL_StatusTypeDef HAL_SPI_Transmit_DMA(SPI_HandleTypeDef *hspi, uint8_t *pData, uint16_t Size); HAL_StatusTypeDef HAL_SPI_Receive_DMA(SPI_HandleTypeDef *hspi, uint8_t *pData, uint16_t Size); HAL_StatusTypeDef HAL_SPI_TransmitReceive_DMA(SPI_HandleTypeDef *hspi, uint8_t *pTxData, uint8_t *pRxData, uint16_t Size); HAL_StatusTypeDef HAL_SPI_DMAPause(SPI_HandleTypeDef *hspi); HAL_StatusTypeDef HAL_SPI_DMAResume(SPI_HandleTypeDef *hspi); HAL_StatusTypeDef HAL_SPI_DMAStop(SPI_HandleTypeDef *hspi); void HAL_SPI_IRQHandler(SPI_HandleTypeDef *hspi); void HAL_SPI_TxCpltCallback(SPI_HandleTypeDef *hspi); void HAL_SPI_RxCpltCallback(SPI_HandleTypeDef *hspi); void HAL_SPI_TxRxCpltCallback(SPI_HandleTypeDef *hspi); void HAL_SPI_TxHalfCpltCallback(SPI_HandleTypeDef *hspi); void HAL_SPI_RxHalfCpltCallback(SPI_HandleTypeDef *hspi); void HAL_SPI_TxRxHalfCpltCallback(SPI_HandleTypeDef *hspi); void HAL_SPI_ErrorCallback(SPI_HandleTypeDef *hspi); /** * @} */ /* Peripheral State and Error functions ***************************************/ /** @addtogroup SPI_Exported_Functions_Group3 * @{ */ HAL_SPI_StateTypeDef HAL_SPI_GetState(SPI_HandleTypeDef *hspi); uint32_t HAL_SPI_GetError(SPI_HandleTypeDef *hspi); /** * @} */ /** * @} */ /** * @} */ /** * @} */ #ifdef __cplusplus } #endif #endif /* __STM32F0xx_HAL_SPI_H */ /************************ (C) COPYRIGHT STMicroelectronics *****END OF FILE****/ ================================================ FILE: Zelig/mbed/TARGET_NUCLEO_F091RC/stm32f0xx_hal_spi_ex.h ================================================ /** ****************************************************************************** * @file stm32f0xx_hal_spi_ex.h * @author MCD Application Team * @version V1.3.0 * @date 26-June-2015 * @brief Header file of SPI HAL Extended module. ****************************************************************************** * @attention * *

© COPYRIGHT(c) 2015 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. * ****************************************************************************** */ /* Define to prevent recursive inclusion -------------------------------------*/ #ifndef __STM32F0xx_HAL_SPI_EX_H #define __STM32F0xx_HAL_SPI_EX_H #ifdef __cplusplus extern "C" { #endif /* Includes ------------------------------------------------------------------*/ #include "stm32f0xx_hal_def.h" /** @addtogroup STM32F0xx_HAL_Driver * @{ */ /** @addtogroup SPIEx * @{ */ /* Exported types ------------------------------------------------------------*/ /* Exported constants --------------------------------------------------------*/ /* Exported macros ------------------------------------------------------------*/ /* Exported functions --------------------------------------------------------*/ /** @addtogroup SPIEx_Exported_Functions * @{ */ /* Initialization and de-initialization functions ****************************/ /* IO operation functions *****************************************************/ /** @addtogroup SPIEx_Exported_Functions_Group1 * @{ */ HAL_StatusTypeDef HAL_SPIEx_FlushRxFifo(SPI_HandleTypeDef *hspi); /** * @} */ /** * @} */ /** * @} */ /** * @} */ #ifdef __cplusplus } #endif #endif /* __STM32F0xx_HAL_SPI_EX_H */ /************************ (C) COPYRIGHT STMicroelectronics *****END OF FILE****/ ================================================ FILE: Zelig/mbed/TARGET_NUCLEO_F091RC/stm32f0xx_hal_tim.h ================================================ /** ****************************************************************************** * @file stm32f0xx_hal_tim.h * @author MCD Application Team * @version V1.3.0 * @date 26-June-2015 * @brief Header file of TIM HAL module. ****************************************************************************** * @attention * *

© COPYRIGHT(c) 2015 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. * ****************************************************************************** */ /* Define to prevent recursive inclusion -------------------------------------*/ #ifndef __STM32F0xx_HAL_TIM_H #define __STM32F0xx_HAL_TIM_H #ifdef __cplusplus extern "C" { #endif /* Includes ------------------------------------------------------------------*/ #include "stm32f0xx_hal_def.h" /** @addtogroup STM32F0xx_HAL_Driver * @{ */ /** @addtogroup TIM * @{ */ /* Exported types ------------------------------------------------------------*/ /** @defgroup TIM_Exported_Types TIM Exported Types * @{ */ /** * @brief TIM Time base Configuration Structure definition */ typedef struct { uint32_t Prescaler; /*!< Specifies the prescaler value used to divide the TIM clock. This parameter can be a number between Min_Data = 0x0000 and Max_Data = 0xFFFF */ uint32_t CounterMode; /*!< Specifies the counter mode. This parameter can be a value of @ref TIM_Counter_Mode */ uint32_t Period; /*!< Specifies the period value to be loaded into the active Auto-Reload Register at the next update event. This parameter can be a number between Min_Data = 0x0000 and Max_Data = 0xFFFF. */ uint32_t ClockDivision; /*!< Specifies the clock division. This parameter can be a value of @ref TIM_ClockDivision */ uint32_t RepetitionCounter; /*!< Specifies the repetition counter value. Each time the RCR downcounter reaches zero, an update event is generated and counting restarts from the RCR value (N). This means in PWM mode that (N+1) corresponds to: - the number of PWM periods in edge-aligned mode - the number of half PWM period in center-aligned mode This parameter must be a number between Min_Data = 0x00 and Max_Data = 0xFF. @note This parameter is valid only for TIM1 and TIM8. */ } TIM_Base_InitTypeDef; /** * @brief TIM Output Compare Configuration Structure definition */ typedef struct { uint32_t OCMode; /*!< Specifies the TIM mode. This parameter can be a value of @ref TIM_Output_Compare_and_PWM_modes */ uint32_t Pulse; /*!< Specifies the pulse value to be loaded into the Capture Compare Register. This parameter can be a number between Min_Data = 0x0000 and Max_Data = 0xFFFF */ uint32_t OCPolarity; /*!< Specifies the output polarity. This parameter can be a value of @ref TIM_Output_Compare_Polarity */ uint32_t OCNPolarity; /*!< Specifies the complementary output polarity. This parameter can be a value of @ref TIM_Output_Compare_N_Polarity @note This parameter is valid only for TIM1 and TIM8. */ uint32_t OCFastMode; /*!< Specifies the Fast mode state. This parameter can be a value of @ref TIM_Output_Fast_State @note This parameter is valid only in PWM1 and PWM2 mode. */ uint32_t OCIdleState; /*!< Specifies the TIM Output Compare pin state during Idle state. This parameter can be a value of @ref TIM_Output_Compare_Idle_State @note This parameter is valid only for TIM1 and TIM8. */ uint32_t OCNIdleState; /*!< Specifies the TIM Output Compare pin state during Idle state. This parameter can be a value of @ref TIM_Output_Compare_N_Idle_State @note This parameter is valid only for TIM1 and TIM8. */ } TIM_OC_InitTypeDef; /** * @brief TIM One Pulse Mode Configuration Structure definition */ typedef struct { uint32_t OCMode; /*!< Specifies the TIM mode. This parameter can be a value of @ref TIM_Output_Compare_and_PWM_modes */ uint32_t Pulse; /*!< Specifies the pulse value to be loaded into the Capture Compare Register. This parameter can be a number between Min_Data = 0x0000 and Max_Data = 0xFFFF */ uint32_t OCPolarity; /*!< Specifies the output polarity. This parameter can be a value of @ref TIM_Output_Compare_Polarity */ uint32_t OCNPolarity; /*!< Specifies the complementary output polarity. This parameter can be a value of @ref TIM_Output_Compare_N_Polarity @note This parameter is valid only for TIM1 and TIM8. */ uint32_t OCIdleState; /*!< Specifies the TIM Output Compare pin state during Idle state. This parameter can be a value of @ref TIM_Output_Compare_Idle_State @note This parameter is valid only for TIM1 and TIM8. */ uint32_t OCNIdleState; /*!< Specifies the TIM Output Compare pin state during Idle state. This parameter can be a value of @ref TIM_Output_Compare_N_Idle_State @note This parameter is valid only for TIM1 and TIM8. */ uint32_t ICPolarity; /*!< Specifies the active edge of the input signal. This parameter can be a value of @ref TIM_Input_Capture_Polarity */ uint32_t ICSelection; /*!< Specifies the input. This parameter can be a value of @ref TIM_Input_Capture_Selection */ uint32_t ICFilter; /*!< Specifies the input capture filter. This parameter can be a number between Min_Data = 0x0 and Max_Data = 0xF */ } TIM_OnePulse_InitTypeDef; /** * @brief TIM Input Capture Configuration Structure definition */ typedef struct { uint32_t ICPolarity; /*!< Specifies the active edge of the input signal. This parameter can be a value of @ref TIM_Input_Capture_Polarity */ uint32_t ICSelection; /*!< Specifies the input. This parameter can be a value of @ref TIM_Input_Capture_Selection */ uint32_t ICPrescaler; /*!< Specifies the Input Capture Prescaler. This parameter can be a value of @ref TIM_Input_Capture_Prescaler */ uint32_t ICFilter; /*!< Specifies the input capture filter. This parameter can be a number between Min_Data = 0x0 and Max_Data = 0xF */ } TIM_IC_InitTypeDef; /** * @brief TIM Encoder Configuration Structure definition */ typedef struct { uint32_t EncoderMode; /*!< Specifies the active edge of the input signal. This parameter can be a value of @ref TIM_Encoder_Mode */ uint32_t IC1Polarity; /*!< Specifies the active edge of the input signal. This parameter can be a value of @ref TIM_Input_Capture_Polarity */ uint32_t IC1Selection; /*!< Specifies the input. This parameter can be a value of @ref TIM_Input_Capture_Selection */ uint32_t IC1Prescaler; /*!< Specifies the Input Capture Prescaler. This parameter can be a value of @ref TIM_Input_Capture_Prescaler */ uint32_t IC1Filter; /*!< Specifies the input capture filter. This parameter can be a number between Min_Data = 0x0 and Max_Data = 0xF */ uint32_t IC2Polarity; /*!< Specifies the active edge of the input signal. This parameter can be a value of @ref TIM_Input_Capture_Polarity */ uint32_t IC2Selection; /*!< Specifies the input. This parameter can be a value of @ref TIM_Input_Capture_Selection */ uint32_t IC2Prescaler; /*!< Specifies the Input Capture Prescaler. This parameter can be a value of @ref TIM_Input_Capture_Prescaler */ uint32_t IC2Filter; /*!< Specifies the input capture filter. This parameter can be a number between Min_Data = 0x0 and Max_Data = 0xF */ } TIM_Encoder_InitTypeDef; /** * @brief TIM Clock Configuration Handle Structure definition */ typedef struct { uint32_t ClockSource; /*!< TIM clock sources This parameter can be a value of @ref TIM_Clock_Source */ uint32_t ClockPolarity; /*!< TIM clock polarity This parameter can be a value of @ref TIM_Clock_Polarity */ uint32_t ClockPrescaler; /*!< TIM clock prescaler This parameter can be a value of @ref TIM_Clock_Prescaler */ uint32_t ClockFilter; /*!< TIM clock filter This parameter can be a number between Min_Data = 0x0 and Max_Data = 0xF */ }TIM_ClockConfigTypeDef; /** * @brief TIM Clear Input Configuration Handle Structure definition */ typedef struct { uint32_t ClearInputState; /*!< TIM clear Input state This parameter can be ENABLE or DISABLE */ uint32_t ClearInputSource; /*!< TIM clear Input sources This parameter can be a value of @ref TIM_ClearInput_Source */ uint32_t ClearInputPolarity; /*!< TIM Clear Input polarity This parameter can be a value of @ref TIM_ClearInput_Polarity */ uint32_t ClearInputPrescaler; /*!< TIM Clear Input prescaler This parameter can be a value of @ref TIM_ClearInput_Prescaler */ uint32_t ClearInputFilter; /*!< TIM Clear Input filter This parameter can be a number between Min_Data = 0x0 and Max_Data = 0xF */ }TIM_ClearInputConfigTypeDef; /** * @brief TIM Slave configuration Structure definition */ typedef struct { uint32_t SlaveMode; /*!< Slave mode selection This parameter can be a value of @ref TIM_Slave_Mode */ uint32_t InputTrigger; /*!< Input Trigger source This parameter can be a value of @ref TIM_Trigger_Selection */ uint32_t TriggerPolarity; /*!< Input Trigger polarity This parameter can be a value of @ref TIM_Trigger_Polarity */ uint32_t TriggerPrescaler; /*!< Input trigger prescaler This parameter can be a value of @ref TIM_Trigger_Prescaler */ uint32_t TriggerFilter; /*!< Input trigger filter This parameter can be a number between Min_Data = 0x0 and Max_Data = 0xF */ }TIM_SlaveConfigTypeDef; /** * @brief HAL State structures definition */ typedef enum { HAL_TIM_STATE_RESET = 0x00, /*!< Peripheral not yet initialized or disabled */ HAL_TIM_STATE_READY = 0x01, /*!< Peripheral Initialized and ready for use */ HAL_TIM_STATE_BUSY = 0x02, /*!< An internal process is ongoing */ HAL_TIM_STATE_TIMEOUT = 0x03, /*!< Timeout state */ HAL_TIM_STATE_ERROR = 0x04 /*!< Reception process is ongoing */ }HAL_TIM_StateTypeDef; /** * @brief HAL Active channel structures definition */ typedef enum { HAL_TIM_ACTIVE_CHANNEL_1 = 0x01, /*!< The active channel is 1 */ HAL_TIM_ACTIVE_CHANNEL_2 = 0x02, /*!< The active channel is 2 */ HAL_TIM_ACTIVE_CHANNEL_3 = 0x04, /*!< The active channel is 3 */ HAL_TIM_ACTIVE_CHANNEL_4 = 0x08, /*!< The active channel is 4 */ HAL_TIM_ACTIVE_CHANNEL_CLEARED = 0x00 /*!< All active channels cleared */ }HAL_TIM_ActiveChannel; /** * @brief TIM Time Base Handle Structure definition */ typedef struct { TIM_TypeDef *Instance; /*!< Register base address */ TIM_Base_InitTypeDef Init; /*!< TIM Time Base required parameters */ HAL_TIM_ActiveChannel Channel; /*!< Active channel */ DMA_HandleTypeDef *hdma[7]; /*!< DMA Handlers array This array is accessed by a @ref TIM_DMA_Handle_index */ HAL_LockTypeDef Lock; /*!< Locking object */ __IO HAL_TIM_StateTypeDef State; /*!< TIM operation state */ }TIM_HandleTypeDef; /** * @} */ /* Exported constants --------------------------------------------------------*/ /** @defgroup TIM_Exported_Constants TIM Exported Constants * @{ */ /** @defgroup TIM_Input_Channel_Polarity TIM Input Channel Polarity * @{ */ #define TIM_INPUTCHANNELPOLARITY_RISING ((uint32_t)0x00000000) /*!< Polarity for TIx source */ #define TIM_INPUTCHANNELPOLARITY_FALLING (TIM_CCER_CC1P) /*!< Polarity for TIx source */ #define TIM_INPUTCHANNELPOLARITY_BOTHEDGE (TIM_CCER_CC1P | TIM_CCER_CC1NP) /*!< Polarity for TIx source */ /** * @} */ /** @defgroup TIM_ETR_Polarity TIM ETR Polarity * @{ */ #define TIM_ETRPOLARITY_INVERTED (TIM_SMCR_ETP) /*!< Polarity for ETR source */ #define TIM_ETRPOLARITY_NONINVERTED ((uint32_t)0x0000) /*!< Polarity for ETR source */ /** * @} */ /** @defgroup TIM_ETR_Prescaler TIM ETR Prescaler * @{ */ #define TIM_ETRPRESCALER_DIV1 ((uint32_t)0x0000) /*!< No prescaler is used */ #define TIM_ETRPRESCALER_DIV2 (TIM_SMCR_ETPS_0) /*!< ETR input source is divided by 2 */ #define TIM_ETRPRESCALER_DIV4 (TIM_SMCR_ETPS_1) /*!< ETR input source is divided by 4 */ #define TIM_ETRPRESCALER_DIV8 (TIM_SMCR_ETPS) /*!< ETR input source is divided by 8 */ /** * @} */ /** @defgroup TIM_Counter_Mode TIM Counter Mode * @{ */ #define TIM_COUNTERMODE_UP ((uint32_t)0x0000) #define TIM_COUNTERMODE_DOWN TIM_CR1_DIR #define TIM_COUNTERMODE_CENTERALIGNED1 TIM_CR1_CMS_0 #define TIM_COUNTERMODE_CENTERALIGNED2 TIM_CR1_CMS_1 #define TIM_COUNTERMODE_CENTERALIGNED3 TIM_CR1_CMS /** * @} */ /** @defgroup TIM_ClockDivision TIM Clock Division * @{ */ #define TIM_CLOCKDIVISION_DIV1 ((uint32_t)0x0000) #define TIM_CLOCKDIVISION_DIV2 (TIM_CR1_CKD_0) #define TIM_CLOCKDIVISION_DIV4 (TIM_CR1_CKD_1) /** * @} */ /** @defgroup TIM_Output_Compare_and_PWM_modes TIM Output Compare and PWM modes * @{ */ #define TIM_OCMODE_TIMING ((uint32_t)0x0000) #define TIM_OCMODE_ACTIVE (TIM_CCMR1_OC1M_0) #define TIM_OCMODE_INACTIVE (TIM_CCMR1_OC1M_1) #define TIM_OCMODE_TOGGLE (TIM_CCMR1_OC1M_0 | TIM_CCMR1_OC1M_1) #define TIM_OCMODE_PWM1 (TIM_CCMR1_OC1M_1 | TIM_CCMR1_OC1M_2) #define TIM_OCMODE_PWM2 (TIM_CCMR1_OC1M) #define TIM_OCMODE_FORCED_ACTIVE (TIM_CCMR1_OC1M_0 | TIM_CCMR1_OC1M_2) #define TIM_OCMODE_FORCED_INACTIVE (TIM_CCMR1_OC1M_2) /** * @} */ /** @defgroup TIM_Output_Fast_State TIM Output Fast State * @{ */ #define TIM_OCFAST_DISABLE ((uint32_t)0x0000) #define TIM_OCFAST_ENABLE (TIM_CCMR1_OC1FE) /** * @} */ /** @defgroup TIM_Output_Compare_Polarity TIM Output Compare Polarity * @{ */ #define TIM_OCPOLARITY_HIGH ((uint32_t)0x0000) #define TIM_OCPOLARITY_LOW (TIM_CCER_CC1P) /** * @} */ /** @defgroup TIM_Output_Compare_N_Polarity TIM Complementary Output Compare Polarity * @{ */ #define TIM_OCNPOLARITY_HIGH ((uint32_t)0x0000) #define TIM_OCNPOLARITY_LOW (TIM_CCER_CC1NP) /** * @} */ /** @defgroup TIM_Output_Compare_Idle_State TIM Output Compare Idle State * @{ */ #define TIM_OCIDLESTATE_SET (TIM_CR2_OIS1) #define TIM_OCIDLESTATE_RESET ((uint32_t)0x0000) /** * @} */ /** @defgroup TIM_Output_Compare_N_Idle_State TIM Complementary Output Compare Idle State * @{ */ #define TIM_OCNIDLESTATE_SET (TIM_CR2_OIS1N) #define TIM_OCNIDLESTATE_RESET ((uint32_t)0x0000) /** * @} */ /** @defgroup TIM_Channel TIM Channel * @{ */ #define TIM_CHANNEL_1 ((uint32_t)0x0000) #define TIM_CHANNEL_2 ((uint32_t)0x0004) #define TIM_CHANNEL_3 ((uint32_t)0x0008) #define TIM_CHANNEL_4 ((uint32_t)0x000C) #define TIM_CHANNEL_ALL ((uint32_t)0x0018) /** * @} */ /** @defgroup TIM_Input_Capture_Polarity TIM Input Capture Polarity * @{ */ #define TIM_ICPOLARITY_RISING TIM_INPUTCHANNELPOLARITY_RISING #define TIM_ICPOLARITY_FALLING TIM_INPUTCHANNELPOLARITY_FALLING #define TIM_ICPOLARITY_BOTHEDGE TIM_INPUTCHANNELPOLARITY_BOTHEDGE /** * @} */ /** @defgroup TIM_Input_Capture_Selection TIM Input Capture Selection * @{ */ #define TIM_ICSELECTION_DIRECTTI (TIM_CCMR1_CC1S_0) /*!< TIM Input 1, 2, 3 or 4 is selected to be connected to IC1, IC2, IC3 or IC4, respectively */ #define TIM_ICSELECTION_INDIRECTTI (TIM_CCMR1_CC1S_1) /*!< TIM Input 1, 2, 3 or 4 is selected to be connected to IC2, IC1, IC4 or IC3, respectively */ #define TIM_ICSELECTION_TRC (TIM_CCMR1_CC1S) /*!< TIM Input 1, 2, 3 or 4 is selected to be connected to TRC */ /** * @} */ /** @defgroup TIM_Input_Capture_Prescaler TIM Input Capture Prescaler * @{ */ #define TIM_ICPSC_DIV1 ((uint32_t)0x0000) /*!< Capture performed each time an edge is detected on the capture input */ #define TIM_ICPSC_DIV2 (TIM_CCMR1_IC1PSC_0) /*!< Capture performed once every 2 events */ #define TIM_ICPSC_DIV4 (TIM_CCMR1_IC1PSC_1) /*!< Capture performed once every 4 events */ #define TIM_ICPSC_DIV8 (TIM_CCMR1_IC1PSC) /*!< Capture performed once every 8 events */ /** * @} */ /** @defgroup TIM_One_Pulse_Mode TIM One Pulse Mode * @{ */ #define TIM_OPMODE_SINGLE (TIM_CR1_OPM) #define TIM_OPMODE_REPETITIVE ((uint32_t)0x0000) /** * @} */ /** @defgroup TIM_Encoder_Mode TIM Encoder Mode * @{ */ #define TIM_ENCODERMODE_TI1 (TIM_SMCR_SMS_0) #define TIM_ENCODERMODE_TI2 (TIM_SMCR_SMS_1) #define TIM_ENCODERMODE_TI12 (TIM_SMCR_SMS_1 | TIM_SMCR_SMS_0) /** * @} */ /** @defgroup TIM_Interrupt_definition TIM Interrupt Definition * @{ */ #define TIM_IT_UPDATE (TIM_DIER_UIE) #define TIM_IT_CC1 (TIM_DIER_CC1IE) #define TIM_IT_CC2 (TIM_DIER_CC2IE) #define TIM_IT_CC3 (TIM_DIER_CC3IE) #define TIM_IT_CC4 (TIM_DIER_CC4IE) #define TIM_IT_COM (TIM_DIER_COMIE) #define TIM_IT_TRIGGER (TIM_DIER_TIE) #define TIM_IT_BREAK (TIM_DIER_BIE) /** * @} */ /** @defgroup TIM_Commutation_Source TIM Commutation Source * @{ */ #define TIM_COMMUTATION_TRGI (TIM_CR2_CCUS) #define TIM_COMMUTATION_SOFTWARE ((uint32_t)0x0000) /** * @} */ /** @defgroup TIM_DMA_sources TIM DMA Sources * @{ */ #define TIM_DMA_UPDATE (TIM_DIER_UDE) #define TIM_DMA_CC1 (TIM_DIER_CC1DE) #define TIM_DMA_CC2 (TIM_DIER_CC2DE) #define TIM_DMA_CC3 (TIM_DIER_CC3DE) #define TIM_DMA_CC4 (TIM_DIER_CC4DE) #define TIM_DMA_COM (TIM_DIER_COMDE) #define TIM_DMA_TRIGGER (TIM_DIER_TDE) /** * @} */ /** @defgroup TIM_Event_Source TIM Event Source * @{ */ #define TIM_EVENTSOURCE_UPDATE TIM_EGR_UG #define TIM_EVENTSOURCE_CC1 TIM_EGR_CC1G #define TIM_EVENTSOURCE_CC2 TIM_EGR_CC2G #define TIM_EVENTSOURCE_CC3 TIM_EGR_CC3G #define TIM_EVENTSOURCE_CC4 TIM_EGR_CC4G #define TIM_EVENTSOURCE_COM TIM_EGR_COMG #define TIM_EVENTSOURCE_TRIGGER TIM_EGR_TG #define TIM_EVENTSOURCE_BREAK TIM_EGR_BG /** * @} */ /** @defgroup TIM_Flag_definition TIM Flag Definition * @{ */ #define TIM_FLAG_UPDATE (TIM_SR_UIF) #define TIM_FLAG_CC1 (TIM_SR_CC1IF) #define TIM_FLAG_CC2 (TIM_SR_CC2IF) #define TIM_FLAG_CC3 (TIM_SR_CC3IF) #define TIM_FLAG_CC4 (TIM_SR_CC4IF) #define TIM_FLAG_COM (TIM_SR_COMIF) #define TIM_FLAG_TRIGGER (TIM_SR_TIF) #define TIM_FLAG_BREAK (TIM_SR_BIF) #define TIM_FLAG_CC1OF (TIM_SR_CC1OF) #define TIM_FLAG_CC2OF (TIM_SR_CC2OF) #define TIM_FLAG_CC3OF (TIM_SR_CC3OF) #define TIM_FLAG_CC4OF (TIM_SR_CC4OF) /** * @} */ /** @defgroup TIM_Clock_Source TIM Clock Source * @{ */ #define TIM_CLOCKSOURCE_ETRMODE2 (TIM_SMCR_ETPS_1) #define TIM_CLOCKSOURCE_INTERNAL (TIM_SMCR_ETPS_0) #define TIM_CLOCKSOURCE_ITR0 ((uint32_t)0x0000) #define TIM_CLOCKSOURCE_ITR1 (TIM_SMCR_TS_0) #define TIM_CLOCKSOURCE_ITR2 (TIM_SMCR_TS_1) #define TIM_CLOCKSOURCE_ITR3 (TIM_SMCR_TS_0 | TIM_SMCR_TS_1) #define TIM_CLOCKSOURCE_TI1ED (TIM_SMCR_TS_2) #define TIM_CLOCKSOURCE_TI1 (TIM_SMCR_TS_0 | TIM_SMCR_TS_2) #define TIM_CLOCKSOURCE_TI2 (TIM_SMCR_TS_1 | TIM_SMCR_TS_2) #define TIM_CLOCKSOURCE_ETRMODE1 (TIM_SMCR_TS) /** * @} */ /** @defgroup TIM_Clock_Polarity TIM Clock Polarity * @{ */ #define TIM_CLOCKPOLARITY_INVERTED TIM_ETRPOLARITY_INVERTED /*!< Polarity for ETRx clock sources */ #define TIM_CLOCKPOLARITY_NONINVERTED TIM_ETRPOLARITY_NONINVERTED /*!< Polarity for ETRx clock sources */ #define TIM_CLOCKPOLARITY_RISING TIM_INPUTCHANNELPOLARITY_RISING /*!< Polarity for TIx clock sources */ #define TIM_CLOCKPOLARITY_FALLING TIM_INPUTCHANNELPOLARITY_FALLING /*!< Polarity for TIx clock sources */ #define TIM_CLOCKPOLARITY_BOTHEDGE TIM_INPUTCHANNELPOLARITY_BOTHEDGE /*!< Polarity for TIx clock sources */ /** * @} */ /** @defgroup TIM_Clock_Prescaler TIM Clock Prescaler * @{ */ #define TIM_CLOCKPRESCALER_DIV1 TIM_ETRPRESCALER_DIV1 /*!< No prescaler is used */ #define TIM_CLOCKPRESCALER_DIV2 TIM_ETRPRESCALER_DIV2 /*!< Prescaler for External ETR Clock: Capture performed once every 2 events. */ #define TIM_CLOCKPRESCALER_DIV4 TIM_ETRPRESCALER_DIV4 /*!< Prescaler for External ETR Clock: Capture performed once every 4 events. */ #define TIM_CLOCKPRESCALER_DIV8 TIM_ETRPRESCALER_DIV8 /*!< Prescaler for External ETR Clock: Capture performed once every 8 events. */ /** * @} */ /** @defgroup TIM_ClearInput_Source TIM ClearInput Source * @{ */ #define TIM_CLEARINPUTSOURCE_ETR ((uint32_t)0x0001) #define TIM_CLEARINPUTSOURCE_NONE ((uint32_t)0x0000) /** * @} */ /** @defgroup TIM_ClearInput_Polarity TIM Clear Input Polarity * @{ */ #define TIM_CLEARINPUTPOLARITY_INVERTED TIM_ETRPOLARITY_INVERTED /*!< Polarity for ETRx pin */ #define TIM_CLEARINPUTPOLARITY_NONINVERTED TIM_ETRPOLARITY_NONINVERTED /*!< Polarity for ETRx pin */ /** * @} */ /** @defgroup TIM_ClearInput_Prescaler TIM Clear Input Prescaler * @{ */ #define TIM_CLEARINPUTPRESCALER_DIV1 TIM_ETRPRESCALER_DIV1 /*!< No prescaler is used */ #define TIM_CLEARINPUTPRESCALER_DIV2 TIM_ETRPRESCALER_DIV2 /*!< Prescaler for External ETR pin: Capture performed once every 2 events. */ #define TIM_CLEARINPUTPRESCALER_DIV4 TIM_ETRPRESCALER_DIV4 /*!< Prescaler for External ETR pin: Capture performed once every 4 events. */ #define TIM_CLEARINPUTPRESCALER_DIV8 TIM_ETRPRESCALER_DIV8 /*!< Prescaler for External ETR pin: Capture performed once every 8 events. */ /** * @} */ /** @defgroup TIM_OSSR_Off_State_Selection_for_Run_mode_state TIM OSSR Off State Selection for Run mode state * @{ */ #define TIM_OSSR_ENABLE (TIM_BDTR_OSSR) #define TIM_OSSR_DISABLE ((uint32_t)0x0000) /** * @} */ /** @defgroup TIM_OSSI_Off_State_Selection_for_Idle_mode_state TIM OSSI Off State Selection for Idle mode state * @{ */ #define TIM_OSSI_ENABLE (TIM_BDTR_OSSI) #define TIM_OSSI_DISABLE ((uint32_t)0x0000) /** * @} */ /** @defgroup TIM_Lock_level TIM Lock level * @{ */ #define TIM_LOCKLEVEL_OFF ((uint32_t)0x0000) #define TIM_LOCKLEVEL_1 (TIM_BDTR_LOCK_0) #define TIM_LOCKLEVEL_2 (TIM_BDTR_LOCK_1) #define TIM_LOCKLEVEL_3 (TIM_BDTR_LOCK) /** * @} */ /** @defgroup TIM_Break_Input_enable_disable TIM Break Input Enable Disable * @{ */ #define TIM_BREAK_ENABLE (TIM_BDTR_BKE) #define TIM_BREAK_DISABLE ((uint32_t)0x0000) /** * @} */ /** @defgroup TIM_Break_Polarity TIM Break Input Polarity * @{ */ #define TIM_BREAKPOLARITY_LOW ((uint32_t)0x0000) #define TIM_BREAKPOLARITY_HIGH (TIM_BDTR_BKP) /** * @} */ /** @defgroup TIM_AOE_Bit_Set_Reset TIM Automatic Output Enable * @{ */ #define TIM_AUTOMATICOUTPUT_ENABLE (TIM_BDTR_AOE) #define TIM_AUTOMATICOUTPUT_DISABLE ((uint32_t)0x0000) /** * @} */ /** @defgroup TIM_Master_Mode_Selection TIM Master Mode Selection * @{ */ #define TIM_TRGO_RESET ((uint32_t)0x0000) #define TIM_TRGO_ENABLE (TIM_CR2_MMS_0) #define TIM_TRGO_UPDATE (TIM_CR2_MMS_1) #define TIM_TRGO_OC1 ((TIM_CR2_MMS_1 | TIM_CR2_MMS_0)) #define TIM_TRGO_OC1REF (TIM_CR2_MMS_2) #define TIM_TRGO_OC2REF ((TIM_CR2_MMS_2 | TIM_CR2_MMS_0)) #define TIM_TRGO_OC3REF ((TIM_CR2_MMS_2 | TIM_CR2_MMS_1)) #define TIM_TRGO_OC4REF ((TIM_CR2_MMS_2 | TIM_CR2_MMS_1 | TIM_CR2_MMS_0)) /** * @} */ /** @defgroup TIM_Slave_Mode TIM Slave Mode * @{ */ #define TIM_SLAVEMODE_DISABLE ((uint32_t)0x0000) #define TIM_SLAVEMODE_RESET ((uint32_t)0x0004) #define TIM_SLAVEMODE_GATED ((uint32_t)0x0005) #define TIM_SLAVEMODE_TRIGGER ((uint32_t)0x0006) #define TIM_SLAVEMODE_EXTERNAL1 ((uint32_t)0x0007) /** * @} */ /** @defgroup TIM_Master_Slave_Mode TIM Master Slave Mode * @{ */ #define TIM_MASTERSLAVEMODE_ENABLE ((uint32_t)0x0080) #define TIM_MASTERSLAVEMODE_DISABLE ((uint32_t)0x0000) /** * @} */ /** @defgroup TIM_Trigger_Selection TIM Trigger Selection * @{ */ #define TIM_TS_ITR0 ((uint32_t)0x0000) #define TIM_TS_ITR1 ((uint32_t)0x0010) #define TIM_TS_ITR2 ((uint32_t)0x0020) #define TIM_TS_ITR3 ((uint32_t)0x0030) #define TIM_TS_TI1F_ED ((uint32_t)0x0040) #define TIM_TS_TI1FP1 ((uint32_t)0x0050) #define TIM_TS_TI2FP2 ((uint32_t)0x0060) #define TIM_TS_ETRF ((uint32_t)0x0070) #define TIM_TS_NONE ((uint32_t)0xFFFF) /** * @} */ /** @defgroup TIM_Trigger_Polarity TIM Trigger Polarity * @{ */ #define TIM_TRIGGERPOLARITY_INVERTED TIM_ETRPOLARITY_INVERTED /*!< Polarity for ETRx trigger sources */ #define TIM_TRIGGERPOLARITY_NONINVERTED TIM_ETRPOLARITY_NONINVERTED /*!< Polarity for ETRx trigger sources */ #define TIM_TRIGGERPOLARITY_RISING TIM_INPUTCHANNELPOLARITY_RISING /*!< Polarity for TIxFPx or TI1_ED trigger sources */ #define TIM_TRIGGERPOLARITY_FALLING TIM_INPUTCHANNELPOLARITY_FALLING /*!< Polarity for TIxFPx or TI1_ED trigger sources */ #define TIM_TRIGGERPOLARITY_BOTHEDGE TIM_INPUTCHANNELPOLARITY_BOTHEDGE /*!< Polarity for TIxFPx or TI1_ED trigger sources */ /** * @} */ /** @defgroup TIM_Trigger_Prescaler TIM Trigger Prescaler * @{ */ #define TIM_TRIGGERPRESCALER_DIV1 TIM_ETRPRESCALER_DIV1 /*!< No prescaler is used */ #define TIM_TRIGGERPRESCALER_DIV2 TIM_ETRPRESCALER_DIV2 /*!< Prescaler for External ETR Trigger: Capture performed once every 2 events. */ #define TIM_TRIGGERPRESCALER_DIV4 TIM_ETRPRESCALER_DIV4 /*!< Prescaler for External ETR Trigger: Capture performed once every 4 events. */ #define TIM_TRIGGERPRESCALER_DIV8 TIM_ETRPRESCALER_DIV8 /*!< Prescaler for External ETR Trigger: Capture performed once every 8 events. */ /** * @} */ /** @defgroup TIM_TI1_Selection TIM TI1 Input Selection * @{ */ #define TIM_TI1SELECTION_CH1 ((uint32_t)0x0000) #define TIM_TI1SELECTION_XORCOMBINATION (TIM_CR2_TI1S) /** * @} */ /** @defgroup TIM_DMA_Base_address TIM DMA Base Address * @{ */ #define TIM_DMABASE_CR1 (0x00000000) #define TIM_DMABASE_CR2 (0x00000001) #define TIM_DMABASE_SMCR (0x00000002) #define TIM_DMABASE_DIER (0x00000003) #define TIM_DMABASE_SR (0x00000004) #define TIM_DMABASE_EGR (0x00000005) #define TIM_DMABASE_CCMR1 (0x00000006) #define TIM_DMABASE_CCMR2 (0x00000007) #define TIM_DMABASE_CCER (0x00000008) #define TIM_DMABASE_CNT (0x00000009) #define TIM_DMABASE_PSC (0x0000000A) #define TIM_DMABASE_ARR (0x0000000B) #define TIM_DMABASE_RCR (0x0000000C) #define TIM_DMABASE_CCR1 (0x0000000D) #define TIM_DMABASE_CCR2 (0x0000000E) #define TIM_DMABASE_CCR3 (0x0000000F) #define TIM_DMABASE_CCR4 (0x00000010) #define TIM_DMABASE_BDTR (0x00000011) #define TIM_DMABASE_DCR (0x00000012) #define TIM_DMABASE_OR (0x00000013) /** * @} */ /** @defgroup TIM_DMA_Burst_Length TIM DMA Burst Length * @{ */ #define TIM_DMABURSTLENGTH_1TRANSFER (0x00000000) #define TIM_DMABURSTLENGTH_2TRANSFERS (0x00000100) #define TIM_DMABURSTLENGTH_3TRANSFERS (0x00000200) #define TIM_DMABURSTLENGTH_4TRANSFERS (0x00000300) #define TIM_DMABURSTLENGTH_5TRANSFERS (0x00000400) #define TIM_DMABURSTLENGTH_6TRANSFERS (0x00000500) #define TIM_DMABURSTLENGTH_7TRANSFERS (0x00000600) #define TIM_DMABURSTLENGTH_8TRANSFERS (0x00000700) #define TIM_DMABURSTLENGTH_9TRANSFERS (0x00000800) #define TIM_DMABURSTLENGTH_10TRANSFERS (0x00000900) #define TIM_DMABURSTLENGTH_11TRANSFERS (0x00000A00) #define TIM_DMABURSTLENGTH_12TRANSFERS (0x00000B00) #define TIM_DMABURSTLENGTH_13TRANSFERS (0x00000C00) #define TIM_DMABURSTLENGTH_14TRANSFERS (0x00000D00) #define TIM_DMABURSTLENGTH_15TRANSFERS (0x00000E00) #define TIM_DMABURSTLENGTH_16TRANSFERS (0x00000F00) #define TIM_DMABURSTLENGTH_17TRANSFERS (0x00001000) #define TIM_DMABURSTLENGTH_18TRANSFERS (0x00001100) /** * @} */ /** @defgroup TIM_DMA_Handle_index TIM DMA Handle Index * @{ */ #define TIM_DMA_ID_UPDATE ((uint16_t) 0x0) /*!< Index of the DMA handle used for Update DMA requests */ #define TIM_DMA_ID_CC1 ((uint16_t) 0x1) /*!< Index of the DMA handle used for Capture/Compare 1 DMA requests */ #define TIM_DMA_ID_CC2 ((uint16_t) 0x2) /*!< Index of the DMA handle used for Capture/Compare 2 DMA requests */ #define TIM_DMA_ID_CC3 ((uint16_t) 0x3) /*!< Index of the DMA handle used for Capture/Compare 3 DMA requests */ #define TIM_DMA_ID_CC4 ((uint16_t) 0x4) /*!< Index of the DMA handle used for Capture/Compare 4 DMA requests */ #define TIM_DMA_ID_COMMUTATION ((uint16_t) 0x5) /*!< Index of the DMA handle used for Commutation DMA requests */ #define TIM_DMA_ID_TRIGGER ((uint16_t) 0x6) /*!< Index of the DMA handle used for Trigger DMA requests */ /** * @} */ /** @defgroup TIM_Channel_CC_State TIM Capture/Compare Channel State * @{ */ #define TIM_CCx_ENABLE ((uint32_t)0x0001) #define TIM_CCx_DISABLE ((uint32_t)0x0000) #define TIM_CCxN_ENABLE ((uint32_t)0x0004) #define TIM_CCxN_DISABLE ((uint32_t)0x0000) /** * @} */ /** * @} */ /* Private Constants -----------------------------------------------------------*/ /** @defgroup TIM_Private_Constants TIM Private Constants * @{ */ /* The counter of a timer instance is disabled only if all the CCx and CCxN channels have been disabled */ #define TIM_CCER_CCxE_MASK ((uint32_t)(TIM_CCER_CC1E | TIM_CCER_CC2E | TIM_CCER_CC3E | TIM_CCER_CC4E)) #define TIM_CCER_CCxNE_MASK ((uint32_t)(TIM_CCER_CC1NE | TIM_CCER_CC2NE | TIM_CCER_CC3NE)) /** * @} */ /* Private Macros -----------------------------------------------------------*/ /** @defgroup TIM_Private_Macros TIM Private Macros * @{ */ #define IS_TIM_COUNTER_MODE(MODE) (((MODE) == TIM_COUNTERMODE_UP) || \ ((MODE) == TIM_COUNTERMODE_DOWN) || \ ((MODE) == TIM_COUNTERMODE_CENTERALIGNED1) || \ ((MODE) == TIM_COUNTERMODE_CENTERALIGNED2) || \ ((MODE) == TIM_COUNTERMODE_CENTERALIGNED3)) #define IS_TIM_CLOCKDIVISION_DIV(DIV) (((DIV) == TIM_CLOCKDIVISION_DIV1) || \ ((DIV) == TIM_CLOCKDIVISION_DIV2) || \ ((DIV) == TIM_CLOCKDIVISION_DIV4)) #define IS_TIM_PWM_MODE(MODE) (((MODE) == TIM_OCMODE_PWM1) || \ ((MODE) == TIM_OCMODE_PWM2)) #define IS_TIM_OC_MODE(MODE) (((MODE) == TIM_OCMODE_TIMING) || \ ((MODE) == TIM_OCMODE_ACTIVE) || \ ((MODE) == TIM_OCMODE_INACTIVE) || \ ((MODE) == TIM_OCMODE_TOGGLE) || \ ((MODE) == TIM_OCMODE_FORCED_ACTIVE) || \ ((MODE) == TIM_OCMODE_FORCED_INACTIVE)) #define IS_TIM_FAST_STATE(STATE) (((STATE) == TIM_OCFAST_DISABLE) || \ ((STATE) == TIM_OCFAST_ENABLE)) #define IS_TIM_OC_POLARITY(POLARITY) (((POLARITY) == TIM_OCPOLARITY_HIGH) || \ ((POLARITY) == TIM_OCPOLARITY_LOW)) #define IS_TIM_OCN_POLARITY(POLARITY) (((POLARITY) == TIM_OCNPOLARITY_HIGH) || \ ((POLARITY) == TIM_OCNPOLARITY_LOW)) #define IS_TIM_OCIDLE_STATE(STATE) (((STATE) == TIM_OCIDLESTATE_SET) || \ ((STATE) == TIM_OCIDLESTATE_RESET)) #define IS_TIM_OCNIDLE_STATE(STATE) (((STATE) == TIM_OCNIDLESTATE_SET) || \ ((STATE) == TIM_OCNIDLESTATE_RESET)) #define IS_TIM_CHANNELS(CHANNEL) (((CHANNEL) == TIM_CHANNEL_1) || \ ((CHANNEL) == TIM_CHANNEL_2) || \ ((CHANNEL) == TIM_CHANNEL_3) || \ ((CHANNEL) == TIM_CHANNEL_4) || \ ((CHANNEL) == TIM_CHANNEL_ALL)) #define IS_TIM_OPM_CHANNELS(CHANNEL) (((CHANNEL) == TIM_CHANNEL_1) || \ ((CHANNEL) == TIM_CHANNEL_2)) #define IS_TIM_COMPLEMENTARY_CHANNELS(CHANNEL) (((CHANNEL) == TIM_CHANNEL_1) || \ ((CHANNEL) == TIM_CHANNEL_2) || \ ((CHANNEL) == TIM_CHANNEL_3)) #define IS_TIM_IC_POLARITY(POLARITY) (((POLARITY) == TIM_ICPOLARITY_RISING) || \ ((POLARITY) == TIM_ICPOLARITY_FALLING) || \ ((POLARITY) == TIM_ICPOLARITY_BOTHEDGE)) #define IS_TIM_IC_SELECTION(SELECTION) (((SELECTION) == TIM_ICSELECTION_DIRECTTI) || \ ((SELECTION) == TIM_ICSELECTION_INDIRECTTI) || \ ((SELECTION) == TIM_ICSELECTION_TRC)) #define IS_TIM_IC_PRESCALER(PRESCALER) (((PRESCALER) == TIM_ICPSC_DIV1) || \ ((PRESCALER) == TIM_ICPSC_DIV2) || \ ((PRESCALER) == TIM_ICPSC_DIV4) || \ ((PRESCALER) == TIM_ICPSC_DIV8)) #define IS_TIM_OPM_MODE(MODE) (((MODE) == TIM_OPMODE_SINGLE) || \ ((MODE) == TIM_OPMODE_REPETITIVE)) #define IS_TIM_ENCODER_MODE(MODE) (((MODE) == TIM_ENCODERMODE_TI1) || \ ((MODE) == TIM_ENCODERMODE_TI2) || \ ((MODE) == TIM_ENCODERMODE_TI12)) #define IS_TIM_DMA_SOURCE(SOURCE) ((((SOURCE) & 0xFFFF80FF) == 0x00000000) && ((SOURCE) != 0x00000000)) #define IS_TIM_EVENT_SOURCE(SOURCE) ((((SOURCE) & 0xFFFFFF00) == 0x00000000) && ((SOURCE) != 0x00000000)) #define IS_TIM_FLAG(FLAG) (((FLAG) == TIM_FLAG_UPDATE) || \ ((FLAG) == TIM_FLAG_CC1) || \ ((FLAG) == TIM_FLAG_CC2) || \ ((FLAG) == TIM_FLAG_CC3) || \ ((FLAG) == TIM_FLAG_CC4) || \ ((FLAG) == TIM_FLAG_COM) || \ ((FLAG) == TIM_FLAG_TRIGGER) || \ ((FLAG) == TIM_FLAG_BREAK) || \ ((FLAG) == TIM_FLAG_CC1OF) || \ ((FLAG) == TIM_FLAG_CC2OF) || \ ((FLAG) == TIM_FLAG_CC3OF) || \ ((FLAG) == TIM_FLAG_CC4OF)) #define IS_TIM_CLOCKSOURCE(CLOCK) (((CLOCK) == TIM_CLOCKSOURCE_INTERNAL) || \ ((CLOCK) == TIM_CLOCKSOURCE_ETRMODE2) || \ ((CLOCK) == TIM_CLOCKSOURCE_ITR0) || \ ((CLOCK) == TIM_CLOCKSOURCE_ITR1) || \ ((CLOCK) == TIM_CLOCKSOURCE_ITR2) || \ ((CLOCK) == TIM_CLOCKSOURCE_ITR3) || \ ((CLOCK) == TIM_CLOCKSOURCE_TI1ED) || \ ((CLOCK) == TIM_CLOCKSOURCE_TI1) || \ ((CLOCK) == TIM_CLOCKSOURCE_TI2) || \ ((CLOCK) == TIM_CLOCKSOURCE_ETRMODE1)) #define IS_TIM_CLOCKPOLARITY(POLARITY) (((POLARITY) == TIM_CLOCKPOLARITY_INVERTED) || \ ((POLARITY) == TIM_CLOCKPOLARITY_NONINVERTED) || \ ((POLARITY) == TIM_CLOCKPOLARITY_RISING) || \ ((POLARITY) == TIM_CLOCKPOLARITY_FALLING) || \ ((POLARITY) == TIM_CLOCKPOLARITY_BOTHEDGE)) #define IS_TIM_CLOCKPRESCALER(PRESCALER) (((PRESCALER) == TIM_CLOCKPRESCALER_DIV1) || \ ((PRESCALER) == TIM_CLOCKPRESCALER_DIV2) || \ ((PRESCALER) == TIM_CLOCKPRESCALER_DIV4) || \ ((PRESCALER) == TIM_CLOCKPRESCALER_DIV8)) #define IS_TIM_CLOCKFILTER(ICFILTER) ((ICFILTER) <= 0xF) #define IS_TIM_CLEARINPUT_SOURCE(SOURCE) (((SOURCE) == TIM_CLEARINPUTSOURCE_NONE) || \ ((SOURCE) == TIM_CLEARINPUTSOURCE_ETR)) #define IS_TIM_CLEARINPUT_POLARITY(POLARITY) (((POLARITY) == TIM_CLEARINPUTPOLARITY_INVERTED) || \ ((POLARITY) == TIM_CLEARINPUTPOLARITY_NONINVERTED)) #define IS_TIM_CLEARINPUT_PRESCALER(PRESCALER) (((PRESCALER) == TIM_CLEARINPUTPRESCALER_DIV1) || \ ((PRESCALER) == TIM_CLEARINPUTPRESCALER_DIV2) || \ ((PRESCALER) == TIM_CLEARINPUTPRESCALER_DIV4) || \ ((PRESCALER) == TIM_CLEARINPUTPRESCALER_DIV8)) #define IS_TIM_CLEARINPUT_FILTER(ICFILTER) ((ICFILTER) <= 0xF) #define IS_TIM_OSSR_STATE(STATE) (((STATE) == TIM_OSSR_ENABLE) || \ ((STATE) == TIM_OSSR_DISABLE)) #define IS_TIM_OSSI_STATE(STATE) (((STATE) == TIM_OSSI_ENABLE) || \ ((STATE) == TIM_OSSI_DISABLE)) #define IS_TIM_LOCK_LEVEL(LEVEL) (((LEVEL) == TIM_LOCKLEVEL_OFF) || \ ((LEVEL) == TIM_LOCKLEVEL_1) || \ ((LEVEL) == TIM_LOCKLEVEL_2) || \ ((LEVEL) == TIM_LOCKLEVEL_3)) #define IS_TIM_BREAK_STATE(STATE) (((STATE) == TIM_BREAK_ENABLE) || \ ((STATE) == TIM_BREAK_DISABLE)) #define IS_TIM_BREAK_POLARITY(POLARITY) (((POLARITY) == TIM_BREAKPOLARITY_LOW) || \ ((POLARITY) == TIM_BREAKPOLARITY_HIGH)) #define IS_TIM_AUTOMATIC_OUTPUT_STATE(STATE) (((STATE) == TIM_AUTOMATICOUTPUT_ENABLE) || \ ((STATE) == TIM_AUTOMATICOUTPUT_DISABLE)) #define IS_TIM_TRGO_SOURCE(SOURCE) (((SOURCE) == TIM_TRGO_RESET) || \ ((SOURCE) == TIM_TRGO_ENABLE) || \ ((SOURCE) == TIM_TRGO_UPDATE) || \ ((SOURCE) == TIM_TRGO_OC1) || \ ((SOURCE) == TIM_TRGO_OC1REF) || \ ((SOURCE) == TIM_TRGO_OC2REF) || \ ((SOURCE) == TIM_TRGO_OC3REF) || \ ((SOURCE) == TIM_TRGO_OC4REF)) #define IS_TIM_SLAVE_MODE(MODE) (((MODE) == TIM_SLAVEMODE_DISABLE) || \ ((MODE) == TIM_SLAVEMODE_GATED) || \ ((MODE) == TIM_SLAVEMODE_RESET) || \ ((MODE) == TIM_SLAVEMODE_TRIGGER) || \ ((MODE) == TIM_SLAVEMODE_EXTERNAL1)) #define IS_TIM_MSM_STATE(STATE) (((STATE) == TIM_MASTERSLAVEMODE_ENABLE) || \ ((STATE) == TIM_MASTERSLAVEMODE_DISABLE)) #define IS_TIM_TRIGGER_SELECTION(SELECTION) (((SELECTION) == TIM_TS_ITR0) || \ ((SELECTION) == TIM_TS_ITR1) || \ ((SELECTION) == TIM_TS_ITR2) || \ ((SELECTION) == TIM_TS_ITR3) || \ ((SELECTION) == TIM_TS_TI1F_ED) || \ ((SELECTION) == TIM_TS_TI1FP1) || \ ((SELECTION) == TIM_TS_TI2FP2) || \ ((SELECTION) == TIM_TS_ETRF)) #define IS_TIM_INTERNAL_TRIGGEREVENT_SELECTION(SELECTION) (((SELECTION) == TIM_TS_ITR0) || \ ((SELECTION) == TIM_TS_ITR1) || \ ((SELECTION) == TIM_TS_ITR2) || \ ((SELECTION) == TIM_TS_ITR3) || \ ((SELECTION) == TIM_TS_NONE)) #define IS_TIM_TRIGGERPOLARITY(POLARITY) (((POLARITY) == TIM_TRIGGERPOLARITY_INVERTED ) || \ ((POLARITY) == TIM_TRIGGERPOLARITY_NONINVERTED) || \ ((POLARITY) == TIM_TRIGGERPOLARITY_RISING ) || \ ((POLARITY) == TIM_TRIGGERPOLARITY_FALLING ) || \ ((POLARITY) == TIM_TRIGGERPOLARITY_BOTHEDGE )) #define IS_TIM_TRIGGERPRESCALER(PRESCALER) (((PRESCALER) == TIM_TRIGGERPRESCALER_DIV1) || \ ((PRESCALER) == TIM_TRIGGERPRESCALER_DIV2) || \ ((PRESCALER) == TIM_TRIGGERPRESCALER_DIV4) || \ ((PRESCALER) == TIM_TRIGGERPRESCALER_DIV8)) #define IS_TIM_TRIGGERFILTER(ICFILTER) ((ICFILTER) <= 0xF) #define IS_TIM_TI1SELECTION(TI1SELECTION) (((TI1SELECTION) == TIM_TI1SELECTION_CH1) || \ ((TI1SELECTION) == TIM_TI1SELECTION_XORCOMBINATION)) #define IS_TIM_DMA_BASE(BASE) (((BASE) == TIM_DMABASE_CR1) || \ ((BASE) == TIM_DMABASE_CR2) || \ ((BASE) == TIM_DMABASE_SMCR) || \ ((BASE) == TIM_DMABASE_DIER) || \ ((BASE) == TIM_DMABASE_SR) || \ ((BASE) == TIM_DMABASE_EGR) || \ ((BASE) == TIM_DMABASE_CCMR1) || \ ((BASE) == TIM_DMABASE_CCMR2) || \ ((BASE) == TIM_DMABASE_CCER) || \ ((BASE) == TIM_DMABASE_CNT) || \ ((BASE) == TIM_DMABASE_PSC) || \ ((BASE) == TIM_DMABASE_ARR) || \ ((BASE) == TIM_DMABASE_RCR) || \ ((BASE) == TIM_DMABASE_CCR1) || \ ((BASE) == TIM_DMABASE_CCR2) || \ ((BASE) == TIM_DMABASE_CCR3) || \ ((BASE) == TIM_DMABASE_CCR4) || \ ((BASE) == TIM_DMABASE_BDTR) || \ ((BASE) == TIM_DMABASE_DCR) || \ ((BASE) == TIM_DMABASE_OR)) #define IS_TIM_DMA_LENGTH(LENGTH) (((LENGTH) == TIM_DMABURSTLENGTH_1TRANSFER) || \ ((LENGTH) == TIM_DMABURSTLENGTH_2TRANSFERS) || \ ((LENGTH) == TIM_DMABURSTLENGTH_3TRANSFERS) || \ ((LENGTH) == TIM_DMABURSTLENGTH_4TRANSFERS) || \ ((LENGTH) == TIM_DMABURSTLENGTH_5TRANSFERS) || \ ((LENGTH) == TIM_DMABURSTLENGTH_6TRANSFERS) || \ ((LENGTH) == TIM_DMABURSTLENGTH_7TRANSFERS) || \ ((LENGTH) == TIM_DMABURSTLENGTH_8TRANSFERS) || \ ((LENGTH) == TIM_DMABURSTLENGTH_9TRANSFERS) || \ ((LENGTH) == TIM_DMABURSTLENGTH_10TRANSFERS) || \ ((LENGTH) == TIM_DMABURSTLENGTH_11TRANSFERS) || \ ((LENGTH) == TIM_DMABURSTLENGTH_12TRANSFERS) || \ ((LENGTH) == TIM_DMABURSTLENGTH_13TRANSFERS) || \ ((LENGTH) == TIM_DMABURSTLENGTH_14TRANSFERS) || \ ((LENGTH) == TIM_DMABURSTLENGTH_15TRANSFERS) || \ ((LENGTH) == TIM_DMABURSTLENGTH_16TRANSFERS) || \ ((LENGTH) == TIM_DMABURSTLENGTH_17TRANSFERS) || \ ((LENGTH) == TIM_DMABURSTLENGTH_18TRANSFERS)) #define IS_TIM_IC_FILTER(ICFILTER) ((ICFILTER) <= 0xF) /** @brief Set TIM IC prescaler * @param __HANDLE__: TIM handle * @param __CHANNEL__: specifies TIM Channel * @param __ICPSC__: specifies the prescaler value. * @retval None */ #define TIM_SET_ICPRESCALERVALUE(__HANDLE__, __CHANNEL__, __ICPSC__) \ (((__CHANNEL__) == TIM_CHANNEL_1) ? ((__HANDLE__)->Instance->CCMR1 |= (__ICPSC__)) :\ ((__CHANNEL__) == TIM_CHANNEL_2) ? ((__HANDLE__)->Instance->CCMR1 |= ((__ICPSC__) << 8)) :\ ((__CHANNEL__) == TIM_CHANNEL_3) ? ((__HANDLE__)->Instance->CCMR2 |= (__ICPSC__)) :\ ((__HANDLE__)->Instance->CCMR2 |= ((__ICPSC__) << 8))) /** @brief Reset TIM IC prescaler * @param __HANDLE__: TIM handle * @param __CHANNEL__: specifies TIM Channel * @retval None */ #define TIM_RESET_ICPRESCALERVALUE(__HANDLE__, __CHANNEL__) \ (((__CHANNEL__) == TIM_CHANNEL_1) ? ((__HANDLE__)->Instance->CCMR1 &= ~TIM_CCMR1_IC1PSC) :\ ((__CHANNEL__) == TIM_CHANNEL_2) ? ((__HANDLE__)->Instance->CCMR1 &= ~TIM_CCMR1_IC2PSC) :\ ((__CHANNEL__) == TIM_CHANNEL_3) ? ((__HANDLE__)->Instance->CCMR2 &= ~TIM_CCMR2_IC3PSC) :\ ((__HANDLE__)->Instance->CCMR2 &= ~TIM_CCMR2_IC4PSC)) /** @brief Set TIM IC polarity * @param __HANDLE__: TIM handle * @param __CHANNEL__: specifies TIM Channel * @param __POLARITY__: specifies TIM Channel Polarity * @retval None */ #define TIM_SET_CAPTUREPOLARITY(__HANDLE__, __CHANNEL__, __POLARITY__) \ (((__CHANNEL__) == TIM_CHANNEL_1) ? ((__HANDLE__)->Instance->CCER |= (__POLARITY__)) :\ ((__CHANNEL__) == TIM_CHANNEL_2) ? ((__HANDLE__)->Instance->CCER |= ((__POLARITY__) << 4)) :\ ((__CHANNEL__) == TIM_CHANNEL_3) ? ((__HANDLE__)->Instance->CCER |= ((__POLARITY__) << 8)) :\ ((__HANDLE__)->Instance->CCER |= (((__POLARITY__) << 12) & TIM_CCER_CC4P))) /** @brief Reset TIM IC polarity * @param __HANDLE__: TIM handle * @param __CHANNEL__: specifies TIM Channel * @retval None */ #define TIM_RESET_CAPTUREPOLARITY(__HANDLE__, __CHANNEL__) \ (((__CHANNEL__) == TIM_CHANNEL_1) ? ((__HANDLE__)->Instance->CCER &= (uint16_t)~(TIM_CCER_CC1P | TIM_CCER_CC1NP)) :\ ((__CHANNEL__) == TIM_CHANNEL_2) ? ((__HANDLE__)->Instance->CCER &= (uint16_t)~(TIM_CCER_CC2P | TIM_CCER_CC2NP)) :\ ((__CHANNEL__) == TIM_CHANNEL_3) ? ((__HANDLE__)->Instance->CCER &= (uint16_t)~(TIM_CCER_CC3P | TIM_CCER_CC3NP)) :\ ((__HANDLE__)->Instance->CCER &= (uint16_t)~TIM_CCER_CC4P)) /** * @} */ /* Private Functions --------------------------------------------------------*/ /** @addtogroup TIM_Private_Functions * @{ */ void TIM_Base_SetConfig(TIM_TypeDef *TIMx, TIM_Base_InitTypeDef *Structure); void TIM_TI1_SetConfig(TIM_TypeDef *TIMx, uint32_t TIM_ICPolarity, uint32_t TIM_ICSelection, uint32_t TIM_ICFilter); void TIM_OC2_SetConfig(TIM_TypeDef *TIMx, TIM_OC_InitTypeDef *OC_Config); void TIM_DMADelayPulseCplt(DMA_HandleTypeDef *hdma); void TIM_DMAError(DMA_HandleTypeDef *hdma); void TIM_DMACaptureCplt(DMA_HandleTypeDef *hdma); void TIM_CCxChannelCmd(TIM_TypeDef* TIMx, uint32_t Channel, uint32_t ChannelState); /** * @} */ /* Exported macros -----------------------------------------------------------*/ /** @defgroup TIM_Exported_Macros TIM Exported Macros * @{ */ /** @brief Reset TIM handle state * @param __HANDLE__: TIM handle. * @retval None */ #define __HAL_TIM_RESET_HANDLE_STATE(__HANDLE__) ((__HANDLE__)->State = HAL_TIM_STATE_RESET) /** * @brief Enable the TIM peripheral. * @param __HANDLE__: TIM handle * @retval None */ #define __HAL_TIM_ENABLE(__HANDLE__) ((__HANDLE__)->Instance->CR1|=(TIM_CR1_CEN)) /** * @brief Enable the TIM main Output. * @param __HANDLE__: TIM handle * @retval None */ #define __HAL_TIM_MOE_ENABLE(__HANDLE__) ((__HANDLE__)->Instance->BDTR|=(TIM_BDTR_MOE)) /** * @brief Disable the TIM peripheral. * @param __HANDLE__: TIM handle * @retval None */ #define __HAL_TIM_DISABLE(__HANDLE__) \ do { \ if (((__HANDLE__)->Instance->CCER & TIM_CCER_CCxE_MASK) == 0) \ { \ if(((__HANDLE__)->Instance->CCER & TIM_CCER_CCxNE_MASK) == 0) \ { \ (__HANDLE__)->Instance->CR1 &= ~(TIM_CR1_CEN); \ } \ } \ } while(0) /* The Main Output Enable of a timer instance is disabled only if all the CCx and CCxN channels have been disabled */ /** * @brief Disable the TIM main Output. * @param __HANDLE__: TIM handle * @retval None * @note The Main Output Enable of a timer instance is disabled only if all the CCx and CCxN channels have been disabled */ #define __HAL_TIM_MOE_DISABLE(__HANDLE__) \ do { \ if (((__HANDLE__)->Instance->CCER & TIM_CCER_CCxE_MASK) == 0) \ { \ if(((__HANDLE__)->Instance->CCER & TIM_CCER_CCxNE_MASK) == 0) \ { \ (__HANDLE__)->Instance->BDTR &= ~(TIM_BDTR_MOE); \ } \ } \ } while(0) /** * @brief Enables the specified TIM interrupt. * @param __HANDLE__: specifies the TIM Handle. * @param __INTERRUPT__: specifies the TIM interrupt source to enable. * This parameter can be one of the following values: * @arg TIM_IT_UPDATE: Update interrupt * @arg TIM_IT_CC1: Capture/Compare 1 interrupt * @arg TIM_IT_CC2: Capture/Compare 2 interrupt * @arg TIM_IT_CC3: Capture/Compare 3 interrupt * @arg TIM_IT_CC4: Capture/Compare 4 interrupt * @arg TIM_IT_COM: Commutation interrupt * @arg TIM_IT_TRIGGER: Trigger interrupt * @arg TIM_IT_BREAK: Break interrupt * @retval None */ #define __HAL_TIM_ENABLE_IT(__HANDLE__, __INTERRUPT__) ((__HANDLE__)->Instance->DIER |= (__INTERRUPT__)) /** * @brief Disables the specified TIM interrupt. * @param __HANDLE__: specifies the TIM Handle. * @param __INTERRUPT__: specifies the TIM interrupt source to disable. * This parameter can be one of the following values: * @arg TIM_IT_UPDATE: Update interrupt * @arg TIM_IT_CC1: Capture/Compare 1 interrupt * @arg TIM_IT_CC2: Capture/Compare 2 interrupt * @arg TIM_IT_CC3: Capture/Compare 3 interrupt * @arg TIM_IT_CC4: Capture/Compare 4 interrupt * @arg TIM_IT_COM: Commutation interrupt * @arg TIM_IT_TRIGGER: Trigger interrupt * @arg TIM_IT_BREAK: Break interrupt * @retval None */ #define __HAL_TIM_DISABLE_IT(__HANDLE__, __INTERRUPT__) ((__HANDLE__)->Instance->DIER &= ~(__INTERRUPT__)) /** * @brief Enables the specified DMA request. * @param __HANDLE__: specifies the TIM Handle. * @param __DMA__: specifies the TIM DMA request to enable. * This parameter can be one of the following values: * @arg TIM_DMA_UPDATE: Update DMA request * @arg TIM_DMA_CC1: Capture/Compare 1 DMA request * @arg TIM_DMA_CC2: Capture/Compare 2 DMA request * @arg TIM_DMA_CC3: Capture/Compare 3 DMA request * @arg TIM_DMA_CC4: Capture/Compare 4 DMA request * @arg TIM_DMA_COM: Commutation DMA request * @arg TIM_DMA_TRIGGER: Trigger DMA request * @retval None */ #define __HAL_TIM_ENABLE_DMA(__HANDLE__, __DMA__) ((__HANDLE__)->Instance->DIER |= (__DMA__)) /** * @brief Disables the specified DMA request. * @param __HANDLE__: specifies the TIM Handle. * @param __DMA__: specifies the TIM DMA request to disable. * This parameter can be one of the following values: * @arg TIM_DMA_UPDATE: Update DMA request * @arg TIM_DMA_CC1: Capture/Compare 1 DMA request * @arg TIM_DMA_CC2: Capture/Compare 2 DMA request * @arg TIM_DMA_CC3: Capture/Compare 3 DMA request * @arg TIM_DMA_CC4: Capture/Compare 4 DMA request * @arg TIM_DMA_COM: Commutation DMA request * @arg TIM_DMA_TRIGGER: Trigger DMA request * @retval None */ #define __HAL_TIM_DISABLE_DMA(__HANDLE__, __DMA__) ((__HANDLE__)->Instance->DIER &= ~(__DMA__)) /** * @brief Checks whether the specified TIM interrupt flag is set or not. * @param __HANDLE__: specifies the TIM Handle. * @param __FLAG__: specifies the TIM interrupt flag to check. * This parameter can be one of the following values: * @arg TIM_FLAG_UPDATE: Update interrupt flag * @arg TIM_FLAG_CC1: Capture/Compare 1 interrupt flag * @arg TIM_FLAG_CC2: Capture/Compare 2 interrupt flag * @arg TIM_FLAG_CC3: Capture/Compare 3 interrupt flag * @arg TIM_FLAG_CC4: Capture/Compare 4 interrupt flag * @arg TIM_FLAG_COM: Commutation interrupt flag * @arg TIM_FLAG_TRIGGER: Trigger interrupt flag * @arg TIM_FLAG_BREAK: Break interrupt flag * @arg TIM_FLAG_CC1OF: Capture/Compare 1 overcapture flag * @arg TIM_FLAG_CC2OF: Capture/Compare 2 overcapture flag * @arg TIM_FLAG_CC3OF: Capture/Compare 3 overcapture flag * @arg TIM_FLAG_CC4OF: Capture/Compare 4 overcapture flag * @retval The new state of __FLAG__ (TRUE or FALSE). */ #define __HAL_TIM_GET_FLAG(__HANDLE__, __FLAG__) (((__HANDLE__)->Instance->SR &(__FLAG__)) == (__FLAG__)) /** * @brief Clears the specified TIM interrupt flag. * @param __HANDLE__: specifies the TIM Handle. * @param __FLAG__: specifies the TIM interrupt flag to clear. * This parameter can be one of the following values: * @arg TIM_FLAG_UPDATE: Update interrupt flag * @arg TIM_FLAG_CC1: Capture/Compare 1 interrupt flag * @arg TIM_FLAG_CC2: Capture/Compare 2 interrupt flag * @arg TIM_FLAG_CC3: Capture/Compare 3 interrupt flag * @arg TIM_FLAG_CC4: Capture/Compare 4 interrupt flag * @arg TIM_FLAG_COM: Commutation interrupt flag * @arg TIM_FLAG_TRIGGER: Trigger interrupt flag * @arg TIM_FLAG_BREAK: Break interrupt flag * @arg TIM_FLAG_CC1OF: Capture/Compare 1 overcapture flag * @arg TIM_FLAG_CC2OF: Capture/Compare 2 overcapture flag * @arg TIM_FLAG_CC3OF: Capture/Compare 3 overcapture flag * @arg TIM_FLAG_CC4OF: Capture/Compare 4 overcapture flag * @retval The new state of __FLAG__ (TRUE or FALSE). */ #define __HAL_TIM_CLEAR_FLAG(__HANDLE__, __FLAG__) ((__HANDLE__)->Instance->SR = ~(__FLAG__)) /** * @brief Checks whether the specified TIM interrupt has occurred or not. * @param __HANDLE__: TIM handle * @param __INTERRUPT__: specifies the TIM interrupt source to check. * @retval The state of TIM_IT (SET or RESET). */ #define __HAL_TIM_GET_IT_SOURCE(__HANDLE__, __INTERRUPT__) ((((__HANDLE__)->Instance->DIER & (__INTERRUPT__)) == (__INTERRUPT__)) ? SET : RESET) /** * @brief Clear the TIM interrupt pending bits * @param __HANDLE__: TIM handle * @param __INTERRUPT__: specifies the interrupt pending bit to clear. * @retval None */ #define __HAL_TIM_CLEAR_IT(__HANDLE__, __INTERRUPT__) ((__HANDLE__)->Instance->SR = ~(__INTERRUPT__)) /** * @brief Indicates whether or not the TIM Counter is used as downcounter * @param __HANDLE__: TIM handle. * @retval False (Counter used as upcounter) or True (Counter used as downcounter) * @note This macro is particularly usefull to get the counting mode when the timer operates in Center-aligned mode or Encoder mode. */ #define __HAL_TIM_IS_TIM_COUNTING_DOWN(__HANDLE__) (((__HANDLE__)->Instance->CR1 & (TIM_CR1_DIR)) == (TIM_CR1_DIR)) /** * @brief Sets the TIM active prescaler register value on update event. * @param __HANDLE__: TIM handle. * @param __PRESC__: specifies the active prescaler register new value. * @retval None */ #define __HAL_TIM_SET_PRESCALER (__HANDLE__, __PRESC__) ((__HANDLE__)->Instance->PSC = (__PRESC__)) /** * @brief Sets the TIM Capture Compare Register value on runtime without * calling another time ConfigChannel function. * @param __HANDLE__: TIM handle. * @param __CHANNEL__ : TIM Channels to be configured. * This parameter can be one of the following values: * @arg TIM_CHANNEL_1: TIM Channel 1 selected * @arg TIM_CHANNEL_2: TIM Channel 2 selected * @arg TIM_CHANNEL_3: TIM Channel 3 selected * @arg TIM_CHANNEL_4: TIM Channel 4 selected * @param __COMPARE__: specifies the Capture Compare register new value. * @retval None */ #define __HAL_TIM_SET_COMPARE(__HANDLE__, __CHANNEL__, __COMPARE__) \ (*(__IO uint32_t *)(&((__HANDLE__)->Instance->CCR1) + ((__CHANNEL__) >> 2)) = (__COMPARE__)) /** * @brief Gets the TIM Capture Compare Register value on runtime * @param __HANDLE__: TIM handle. * @param __CHANNEL__ : TIM Channel associated with the capture compare register * This parameter can be one of the following values: * @arg TIM_CHANNEL_1: get capture/compare 1 register value * @arg TIM_CHANNEL_2: get capture/compare 2 register value * @arg TIM_CHANNEL_3: get capture/compare 3 register value * @arg TIM_CHANNEL_4: get capture/compare 4 register value * @retval None */ #define __HAL_TIM_GET_COMPARE(__HANDLE__, __CHANNEL__) \ (*(__IO uint32_t *)(&((__HANDLE__)->Instance->CCR1) + ((__CHANNEL__) >> 2))) /** * @brief Sets the TIM Counter Register value on runtime. * @param __HANDLE__: TIM handle. * @param __COUNTER__: specifies the Counter register new value. * @retval None */ #define __HAL_TIM_SET_COUNTER(__HANDLE__, __COUNTER__) ((__HANDLE__)->Instance->CNT = (__COUNTER__)) /** * @brief Gets the TIM Counter Register value on runtime. * @param __HANDLE__: TIM handle. * @retval None */ #define __HAL_TIM_GET_COUNTER(__HANDLE__) \ ((__HANDLE__)->Instance->CNT) /** * @brief Sets the TIM Autoreload Register value on runtime without calling * another time any Init function. * @param __HANDLE__: TIM handle. * @param __AUTORELOAD__: specifies the Counter register new value. * @retval None */ #define __HAL_TIM_SET_AUTORELOAD(__HANDLE__, __AUTORELOAD__) \ do{ \ (__HANDLE__)->Instance->ARR = (__AUTORELOAD__); \ (__HANDLE__)->Init.Period = (__AUTORELOAD__); \ } while(0) /** * @brief Gets the TIM Autoreload Register value on runtime * @param __HANDLE__: TIM handle. * @retval None */ #define __HAL_TIM_GET_AUTORELOAD(__HANDLE__) \ ((__HANDLE__)->Instance->ARR) /** * @brief Sets the TIM Clock Division value on runtime without calling * another time any Init function. * @param __HANDLE__: TIM handle. * @param __CKD__: specifies the clock division value. * This parameter can be one of the following value: * @arg TIM_CLOCKDIVISION_DIV1 * @arg TIM_CLOCKDIVISION_DIV2 * @arg TIM_CLOCKDIVISION_DIV4 * @retval None */ #define __HAL_TIM_SET_CLOCKDIVISION(__HANDLE__, __CKD__) \ do{ \ (__HANDLE__)->Instance->CR1 &= ~TIM_CR1_CKD; \ (__HANDLE__)->Instance->CR1 |= (__CKD__); \ (__HANDLE__)->Init.ClockDivision = (__CKD__); \ } while(0) /** * @brief Gets the TIM Clock Division value on runtime * @param __HANDLE__: TIM handle. * @retval None */ #define __HAL_TIM_GET_CLOCKDIVISION(__HANDLE__) \ ((__HANDLE__)->Instance->CR1 & TIM_CR1_CKD) /** * @brief Sets the TIM Input Capture prescaler on runtime without calling * another time HAL_TIM_IC_ConfigChannel() function. * @param __HANDLE__: TIM handle. * @param __CHANNEL__ : TIM Channels to be configured. * This parameter can be one of the following values: * @arg TIM_CHANNEL_1: TIM Channel 1 selected * @arg TIM_CHANNEL_2: TIM Channel 2 selected * @arg TIM_CHANNEL_3: TIM Channel 3 selected * @arg TIM_CHANNEL_4: TIM Channel 4 selected * @param __ICPSC__: specifies the Input Capture4 prescaler new value. * This parameter can be one of the following values: * @arg TIM_ICPSC_DIV1: no prescaler * @arg TIM_ICPSC_DIV2: capture is done once every 2 events * @arg TIM_ICPSC_DIV4: capture is done once every 4 events * @arg TIM_ICPSC_DIV8: capture is done once every 8 events * @retval None */ #define __HAL_TIM_SET_ICPRESCALER(__HANDLE__, __CHANNEL__, __ICPSC__) \ do{ \ TIM_RESET_ICPRESCALERVALUE((__HANDLE__), (__CHANNEL__)); \ TIM_SET_ICPRESCALERVALUE((__HANDLE__), (__CHANNEL__), (__ICPSC__)); \ } while(0) /** * @brief Gets the TIM Input Capture prescaler on runtime * @param __HANDLE__: TIM handle. * @param __CHANNEL__: TIM Channels to be configured. * This parameter can be one of the following values: * @arg TIM_CHANNEL_1: get input capture 1 prescaler value * @arg TIM_CHANNEL_2: get input capture 2 prescaler value * @arg TIM_CHANNEL_3: get input capture 3 prescaler value * @arg TIM_CHANNEL_4: get input capture 4 prescaler value * @retval None */ #define __HAL_TIM_GET_ICPRESCALER(__HANDLE__, __CHANNEL__) \ (((__CHANNEL__) == TIM_CHANNEL_1) ? ((__HANDLE__)->Instance->CCMR1 & TIM_CCMR1_IC1PSC) :\ ((__CHANNEL__) == TIM_CHANNEL_2) ? (((__HANDLE__)->Instance->CCMR1 & TIM_CCMR1_IC2PSC) >> 8) :\ ((__CHANNEL__) == TIM_CHANNEL_3) ? ((__HANDLE__)->Instance->CCMR2 & TIM_CCMR2_IC3PSC) :\ (((__HANDLE__)->Instance->CCMR2 & TIM_CCMR2_IC4PSC)) >> 8) /** * @brief Set the Update Request Source (URS) bit of the TIMx_CR1 register * @param __HANDLE__: TIM handle. * @note When the USR bit of the TIMx_CR1 register is set, only counter * overflow/underflow generates an update interrupt or DMA request (if * enabled) * @retval None */ #define __HAL_TIM_URS_ENABLE(__HANDLE__) \ ((__HANDLE__)->Instance->CR1|= (TIM_CR1_URS)) /** * @brief Reset the Update Request Source (URS) bit of the TIMx_CR1 register * @param __HANDLE__: TIM handle. * @note When the USR bit of the TIMx_CR1 register is reset, any of the * following events generate an update interrupt or DMA request (if * enabled): * (+) Counter overflow/underflow * (+) Setting the UG bit * (+) Update generation through the slave mode controller * @retval None */ #define __HAL_TIM_URS_DISABLE(__HANDLE__) \ ((__HANDLE__)->Instance->CR1&=~(TIM_CR1_URS)) /** * @brief Sets the TIM Capture x input polarity on runtime. * @param __HANDLE__: TIM handle. * @param __CHANNEL__: TIM Channels to be configured. * This parameter can be one of the following values: * @arg TIM_CHANNEL_1: TIM Channel 1 selected * @arg TIM_CHANNEL_2: TIM Channel 2 selected * @arg TIM_CHANNEL_3: TIM Channel 3 selected * @arg TIM_CHANNEL_4: TIM Channel 4 selected * @param __POLARITY__: Polarity for TIx source * @arg TIM_INPUTCHANNELPOLARITY_RISING: Rising Edge * @arg TIM_INPUTCHANNELPOLARITY_FALLING: Falling Edge * @arg TIM_INPUTCHANNELPOLARITY_BOTHEDGE: Rising and Falling Edge * @note The polarity TIM_INPUTCHANNELPOLARITY_BOTHEDGE is not authorized for TIM Channel 4. * @retval None */ #define __HAL_TIM_SET_CAPTUREPOLARITY(__HANDLE__, __CHANNEL__, __POLARITY__) \ do{ \ TIM_RESET_CAPTUREPOLARITY((__HANDLE__), (__CHANNEL__)); \ TIM_SET_CAPTUREPOLARITY((__HANDLE__), (__CHANNEL__), (__POLARITY__)); \ }while(0) /** * @} */ /* Include TIM HAL Extension module */ #include "stm32f0xx_hal_tim_ex.h" /* Exported functions --------------------------------------------------------*/ /** @addtogroup TIM_Exported_Functions * @{ */ /** @addtogroup TIM_Exported_Functions_Group1 * @{ */ /* Time Base functions ********************************************************/ HAL_StatusTypeDef HAL_TIM_Base_Init(TIM_HandleTypeDef *htim); HAL_StatusTypeDef HAL_TIM_Base_DeInit(TIM_HandleTypeDef *htim); void HAL_TIM_Base_MspInit(TIM_HandleTypeDef *htim); void HAL_TIM_Base_MspDeInit(TIM_HandleTypeDef *htim); /* Blocking mode: Polling */ HAL_StatusTypeDef HAL_TIM_Base_Start(TIM_HandleTypeDef *htim); HAL_StatusTypeDef HAL_TIM_Base_Stop(TIM_HandleTypeDef *htim); /* Non-Blocking mode: Interrupt */ HAL_StatusTypeDef HAL_TIM_Base_Start_IT(TIM_HandleTypeDef *htim); HAL_StatusTypeDef HAL_TIM_Base_Stop_IT(TIM_HandleTypeDef *htim); /* Non-Blocking mode: DMA */ HAL_StatusTypeDef HAL_TIM_Base_Start_DMA(TIM_HandleTypeDef *htim, uint32_t *pData, uint16_t Length); HAL_StatusTypeDef HAL_TIM_Base_Stop_DMA(TIM_HandleTypeDef *htim); /** * @} */ /** @addtogroup TIM_Exported_Functions_Group2 * @{ */ /* Timer Output Compare functions **********************************************/ HAL_StatusTypeDef HAL_TIM_OC_Init(TIM_HandleTypeDef *htim); HAL_StatusTypeDef HAL_TIM_OC_DeInit(TIM_HandleTypeDef *htim); void HAL_TIM_OC_MspInit(TIM_HandleTypeDef *htim); void HAL_TIM_OC_MspDeInit(TIM_HandleTypeDef *htim); /* Blocking mode: Polling */ HAL_StatusTypeDef HAL_TIM_OC_Start(TIM_HandleTypeDef *htim, uint32_t Channel); HAL_StatusTypeDef HAL_TIM_OC_Stop(TIM_HandleTypeDef *htim, uint32_t Channel); /* Non-Blocking mode: Interrupt */ HAL_StatusTypeDef HAL_TIM_OC_Start_IT(TIM_HandleTypeDef *htim, uint32_t Channel); HAL_StatusTypeDef HAL_TIM_OC_Stop_IT(TIM_HandleTypeDef *htim, uint32_t Channel); /* Non-Blocking mode: DMA */ HAL_StatusTypeDef HAL_TIM_OC_Start_DMA(TIM_HandleTypeDef *htim, uint32_t Channel, uint32_t *pData, uint16_t Length); HAL_StatusTypeDef HAL_TIM_OC_Stop_DMA(TIM_HandleTypeDef *htim, uint32_t Channel); /** * @} */ /** @addtogroup TIM_Exported_Functions_Group3 * @{ */ /* Timer PWM functions *********************************************************/ HAL_StatusTypeDef HAL_TIM_PWM_Init(TIM_HandleTypeDef *htim); HAL_StatusTypeDef HAL_TIM_PWM_DeInit(TIM_HandleTypeDef *htim); void HAL_TIM_PWM_MspInit(TIM_HandleTypeDef *htim); void HAL_TIM_PWM_MspDeInit(TIM_HandleTypeDef *htim); /* Blocking mode: Polling */ HAL_StatusTypeDef HAL_TIM_PWM_Start(TIM_HandleTypeDef *htim, uint32_t Channel); HAL_StatusTypeDef HAL_TIM_PWM_Stop(TIM_HandleTypeDef *htim, uint32_t Channel); /* Non-Blocking mode: Interrupt */ HAL_StatusTypeDef HAL_TIM_PWM_Start_IT(TIM_HandleTypeDef *htim, uint32_t Channel); HAL_StatusTypeDef HAL_TIM_PWM_Stop_IT(TIM_HandleTypeDef *htim, uint32_t Channel); /* Non-Blocking mode: DMA */ HAL_StatusTypeDef HAL_TIM_PWM_Start_DMA(TIM_HandleTypeDef *htim, uint32_t Channel, uint32_t *pData, uint16_t Length); HAL_StatusTypeDef HAL_TIM_PWM_Stop_DMA(TIM_HandleTypeDef *htim, uint32_t Channel); /** * @} */ /** @addtogroup TIM_Exported_Functions_Group4 * @{ */ /* Timer Input Capture functions ***********************************************/ HAL_StatusTypeDef HAL_TIM_IC_Init(TIM_HandleTypeDef *htim); HAL_StatusTypeDef HAL_TIM_IC_DeInit(TIM_HandleTypeDef *htim); void HAL_TIM_IC_MspInit(TIM_HandleTypeDef *htim); void HAL_TIM_IC_MspDeInit(TIM_HandleTypeDef *htim); /* Blocking mode: Polling */ HAL_StatusTypeDef HAL_TIM_IC_Start(TIM_HandleTypeDef *htim, uint32_t Channel); HAL_StatusTypeDef HAL_TIM_IC_Stop(TIM_HandleTypeDef *htim, uint32_t Channel); /* Non-Blocking mode: Interrupt */ HAL_StatusTypeDef HAL_TIM_IC_Start_IT(TIM_HandleTypeDef *htim, uint32_t Channel); HAL_StatusTypeDef HAL_TIM_IC_Stop_IT(TIM_HandleTypeDef *htim, uint32_t Channel); /* Non-Blocking mode: DMA */ HAL_StatusTypeDef HAL_TIM_IC_Start_DMA(TIM_HandleTypeDef *htim, uint32_t Channel, uint32_t *pData, uint16_t Length); HAL_StatusTypeDef HAL_TIM_IC_Stop_DMA(TIM_HandleTypeDef *htim, uint32_t Channel); /** * @} */ /** @addtogroup TIM_Exported_Functions_Group5 * @{ */ /* Timer One Pulse functions ***************************************************/ HAL_StatusTypeDef HAL_TIM_OnePulse_Init(TIM_HandleTypeDef *htim, uint32_t OnePulseMode); HAL_StatusTypeDef HAL_TIM_OnePulse_DeInit(TIM_HandleTypeDef *htim); void HAL_TIM_OnePulse_MspInit(TIM_HandleTypeDef *htim); void HAL_TIM_OnePulse_MspDeInit(TIM_HandleTypeDef *htim); /* Blocking mode: Polling */ HAL_StatusTypeDef HAL_TIM_OnePulse_Start(TIM_HandleTypeDef *htim, uint32_t OutputChannel); HAL_StatusTypeDef HAL_TIM_OnePulse_Stop(TIM_HandleTypeDef *htim, uint32_t OutputChannel); /* Non-Blocking mode: Interrupt */ HAL_StatusTypeDef HAL_TIM_OnePulse_Start_IT(TIM_HandleTypeDef *htim, uint32_t OutputChannel); HAL_StatusTypeDef HAL_TIM_OnePulse_Stop_IT(TIM_HandleTypeDef *htim, uint32_t OutputChannel); /** * @} */ /** @addtogroup TIM_Exported_Functions_Group6 * @{ */ /* Timer Encoder functions *****************************************************/ HAL_StatusTypeDef HAL_TIM_Encoder_Init(TIM_HandleTypeDef *htim, TIM_Encoder_InitTypeDef* sConfig); HAL_StatusTypeDef HAL_TIM_Encoder_DeInit(TIM_HandleTypeDef *htim); void HAL_TIM_Encoder_MspInit(TIM_HandleTypeDef *htim); void HAL_TIM_Encoder_MspDeInit(TIM_HandleTypeDef *htim); /* Blocking mode: Polling */ HAL_StatusTypeDef HAL_TIM_Encoder_Start(TIM_HandleTypeDef *htim, uint32_t Channel); HAL_StatusTypeDef HAL_TIM_Encoder_Stop(TIM_HandleTypeDef *htim, uint32_t Channel); /* Non-Blocking mode: Interrupt */ HAL_StatusTypeDef HAL_TIM_Encoder_Start_IT(TIM_HandleTypeDef *htim, uint32_t Channel); HAL_StatusTypeDef HAL_TIM_Encoder_Stop_IT(TIM_HandleTypeDef *htim, uint32_t Channel); /* Non-Blocking mode: DMA */ HAL_StatusTypeDef HAL_TIM_Encoder_Start_DMA(TIM_HandleTypeDef *htim, uint32_t Channel, uint32_t *pData1, uint32_t *pData2, uint16_t Length); HAL_StatusTypeDef HAL_TIM_Encoder_Stop_DMA(TIM_HandleTypeDef *htim, uint32_t Channel); /** * @} */ /** @addtogroup TIM_Exported_Functions_Group7 * @{ */ /* Interrupt Handler functions **********************************************/ void HAL_TIM_IRQHandler(TIM_HandleTypeDef *htim); /** * @} */ /** @addtogroup TIM_Exported_Functions_Group8 * @{ */ /* Control functions *********************************************************/ HAL_StatusTypeDef HAL_TIM_OC_ConfigChannel(TIM_HandleTypeDef *htim, TIM_OC_InitTypeDef* sConfig, uint32_t Channel); HAL_StatusTypeDef HAL_TIM_PWM_ConfigChannel(TIM_HandleTypeDef *htim, TIM_OC_InitTypeDef* sConfig, uint32_t Channel); HAL_StatusTypeDef HAL_TIM_IC_ConfigChannel(TIM_HandleTypeDef *htim, TIM_IC_InitTypeDef* sConfig, uint32_t Channel); HAL_StatusTypeDef HAL_TIM_OnePulse_ConfigChannel(TIM_HandleTypeDef *htim, TIM_OnePulse_InitTypeDef* sConfig, uint32_t OutputChannel, uint32_t InputChannel); HAL_StatusTypeDef HAL_TIM_ConfigOCrefClear(TIM_HandleTypeDef *htim, TIM_ClearInputConfigTypeDef * sClearInputConfig, uint32_t Channel); HAL_StatusTypeDef HAL_TIM_ConfigClockSource(TIM_HandleTypeDef *htim, TIM_ClockConfigTypeDef * sClockSourceConfig); HAL_StatusTypeDef HAL_TIM_ConfigTI1Input(TIM_HandleTypeDef *htim, uint32_t TI1_Selection); HAL_StatusTypeDef HAL_TIM_SlaveConfigSynchronization(TIM_HandleTypeDef *htim, TIM_SlaveConfigTypeDef * sSlaveConfig); HAL_StatusTypeDef HAL_TIM_SlaveConfigSynchronization_IT(TIM_HandleTypeDef *htim, TIM_SlaveConfigTypeDef * sSlaveConfig); HAL_StatusTypeDef HAL_TIM_DMABurst_WriteStart(TIM_HandleTypeDef *htim, uint32_t BurstBaseAddress, uint32_t BurstRequestSrc, \ uint32_t *BurstBuffer, uint32_t BurstLength); HAL_StatusTypeDef HAL_TIM_DMABurst_WriteStop(TIM_HandleTypeDef *htim, uint32_t BurstRequestSrc); HAL_StatusTypeDef HAL_TIM_DMABurst_ReadStart(TIM_HandleTypeDef *htim, uint32_t BurstBaseAddress, uint32_t BurstRequestSrc, \ uint32_t *BurstBuffer, uint32_t BurstLength); HAL_StatusTypeDef HAL_TIM_DMABurst_ReadStop(TIM_HandleTypeDef *htim, uint32_t BurstRequestSrc); HAL_StatusTypeDef HAL_TIM_GenerateEvent(TIM_HandleTypeDef *htim, uint32_t EventSource); uint32_t HAL_TIM_ReadCapturedValue(TIM_HandleTypeDef *htim, uint32_t Channel); /** * @} */ /** @addtogroup TIM_Exported_Functions_Group9 * @{ */ /* Callback in non blocking modes (Interrupt and DMA) *************************/ void HAL_TIM_PeriodElapsedCallback(TIM_HandleTypeDef *htim); void HAL_TIM_OC_DelayElapsedCallback(TIM_HandleTypeDef *htim); void HAL_TIM_IC_CaptureCallback(TIM_HandleTypeDef *htim); void HAL_TIM_PWM_PulseFinishedCallback(TIM_HandleTypeDef *htim); void HAL_TIM_TriggerCallback(TIM_HandleTypeDef *htim); void HAL_TIM_ErrorCallback(TIM_HandleTypeDef *htim); /** * @} */ /** @addtogroup TIM_Exported_Functions_Group10 * @{ */ /* Peripheral State functions **************************************************/ HAL_TIM_StateTypeDef HAL_TIM_Base_GetState(TIM_HandleTypeDef *htim); HAL_TIM_StateTypeDef HAL_TIM_OC_GetState(TIM_HandleTypeDef *htim); HAL_TIM_StateTypeDef HAL_TIM_PWM_GetState(TIM_HandleTypeDef *htim); HAL_TIM_StateTypeDef HAL_TIM_IC_GetState(TIM_HandleTypeDef *htim); HAL_TIM_StateTypeDef HAL_TIM_OnePulse_GetState(TIM_HandleTypeDef *htim); HAL_TIM_StateTypeDef HAL_TIM_Encoder_GetState(TIM_HandleTypeDef *htim); /** * @} */ /** * @} */ /** * @} */ /** * @} */ #ifdef __cplusplus } #endif #endif /* __STM32F0xx_HAL_TIM_H */ /************************ (C) COPYRIGHT STMicroelectronics *****END OF FILE****/ ================================================ FILE: Zelig/mbed/TARGET_NUCLEO_F091RC/stm32f0xx_hal_tim_ex.h ================================================ /** ****************************************************************************** * @file stm32f0xx_hal_tim_ex.h * @author MCD Application Team * @version V1.3.0 * @date 26-June-2015 * @brief Header file of TIM HAL Extended module. ****************************************************************************** * @attention * *

© COPYRIGHT(c) 2015 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. * ****************************************************************************** */ /* Define to prevent recursive inclusion -------------------------------------*/ #ifndef __STM32F0xx_HAL_TIM_EX_H #define __STM32F0xx_HAL_TIM_EX_H #ifdef __cplusplus extern "C" { #endif /* Includes ------------------------------------------------------------------*/ #include "stm32f0xx_hal_def.h" /** @addtogroup STM32F0xx_HAL_Driver * @{ */ /** @addtogroup TIMEx * @{ */ /* Exported types ------------------------------------------------------------*/ /** @defgroup TIMEx_Exported_Types TIMEx Exported Types * @{ */ /** * @brief TIM Hall sensor Configuration Structure definition */ typedef struct { uint32_t IC1Polarity; /*!< Specifies the active edge of the input signal. This parameter can be a value of @ref TIM_Input_Capture_Polarity */ uint32_t IC1Prescaler; /*!< Specifies the Input Capture Prescaler. This parameter can be a value of @ref TIM_Input_Capture_Prescaler */ uint32_t IC1Filter; /*!< Specifies the input capture filter. This parameter can be a number between Min_Data = 0x0 and Max_Data = 0xF */ uint32_t Commutation_Delay; /*!< Specifies the pulse value to be loaded into the Capture Compare Register. This parameter can be a number between Min_Data = 0x0000 and Max_Data = 0xFFFF */ } TIM_HallSensor_InitTypeDef; /** * @brief TIM Master configuration Structure definition */ typedef struct { uint32_t MasterOutputTrigger; /*!< Trigger output (TRGO) selection This parameter can be a value of @ref TIM_Master_Mode_Selection */ uint32_t MasterSlaveMode; /*!< Master/slave mode selection This parameter can be a value of @ref TIM_Master_Slave_Mode */ }TIM_MasterConfigTypeDef; /** * @brief TIM Break and Dead time configuration Structure definition */ typedef struct { uint32_t OffStateRunMode; /*!< TIM off state in run mode This parameter can be a value of @ref TIM_OSSR_Off_State_Selection_for_Run_mode_state */ uint32_t OffStateIDLEMode; /*!< TIM off state in IDLE mode This parameter can be a value of @ref TIM_OSSI_Off_State_Selection_for_Idle_mode_state */ uint32_t LockLevel; /*!< TIM Lock level This parameter can be a value of @ref TIM_Lock_level */ uint32_t DeadTime; /*!< TIM dead Time This parameter can be a number between Min_Data = 0x00 and Max_Data = 0xFF */ uint32_t BreakState; /*!< TIM Break State This parameter can be a value of @ref TIM_Break_Input_enable_disable */ uint32_t BreakPolarity; /*!< TIM Break input polarity This parameter can be a value of @ref TIM_Break_Polarity */ uint32_t AutomaticOutput; /*!< TIM Automatic Output Enable state This parameter can be a value of @ref TIM_AOE_Bit_Set_Reset */ } TIM_BreakDeadTimeConfigTypeDef; /** * @} */ /* Exported constants --------------------------------------------------------*/ /** @defgroup TIMEx_Exported_Constants TIMEx Exported Constants * @{ */ /** @defgroup TIMEx_Remap TIMEx Remap * @{ */ #define TIM_TIM14_GPIO (0x00000000) /*!< TIM14 TI1 is connected to GPIO */ #define TIM_TIM14_RTC (0x00000001) /*!< TIM14 TI1 is connected to RTC_clock */ #define TIM_TIM14_HSE (0x00000002) /*!< TIM14 TI1 is connected to HSE/32 */ #define TIM_TIM14_MCO (0x00000003) /*!< TIM14 TI1 is connected to MCO */ #define IS_TIM_REMAP(TIM_REMAP) (((TIM_REMAP) == TIM_TIM14_GPIO) ||\ ((TIM_REMAP) == TIM_TIM14_RTC) ||\ ((TIM_REMAP) == TIM_TIM14_HSE) ||\ ((TIM_REMAP) == TIM_TIM14_MCO)) /** * @} */ /** @defgroup TIMEx_Clock_Filter TIMEx Clock Filter * @{ */ #define IS_TIM_DEADTIME(DEADTIME) ((DEADTIME) <= 0xFF) /*!< BreakDead Time */ /** * @} */ /** * @} */ /* Exported macro ------------------------------------------------------------*/ /* Exported functions --------------------------------------------------------*/ /** @addtogroup TIMEx_Exported_Functions * @{ */ /** @addtogroup TIMEx_Exported_Functions_Group1 * @{ */ /* Timer Hall Sensor functions **********************************************/ HAL_StatusTypeDef HAL_TIMEx_HallSensor_Init(TIM_HandleTypeDef *htim, TIM_HallSensor_InitTypeDef* sConfig); HAL_StatusTypeDef HAL_TIMEx_HallSensor_DeInit(TIM_HandleTypeDef *htim); void HAL_TIMEx_HallSensor_MspInit(TIM_HandleTypeDef *htim); void HAL_TIMEx_HallSensor_MspDeInit(TIM_HandleTypeDef *htim); /* Blocking mode: Polling */ HAL_StatusTypeDef HAL_TIMEx_HallSensor_Start(TIM_HandleTypeDef *htim); HAL_StatusTypeDef HAL_TIMEx_HallSensor_Stop(TIM_HandleTypeDef *htim); /* Non-Blocking mode: Interrupt */ HAL_StatusTypeDef HAL_TIMEx_HallSensor_Start_IT(TIM_HandleTypeDef *htim); HAL_StatusTypeDef HAL_TIMEx_HallSensor_Stop_IT(TIM_HandleTypeDef *htim); /* Non-Blocking mode: DMA */ HAL_StatusTypeDef HAL_TIMEx_HallSensor_Start_DMA(TIM_HandleTypeDef *htim, uint32_t *pData, uint16_t Length); HAL_StatusTypeDef HAL_TIMEx_HallSensor_Stop_DMA(TIM_HandleTypeDef *htim); /** * @} */ /** @addtogroup TIMEx_Exported_Functions_Group2 * @{ */ /* Timer Complementary Output Compare functions *****************************/ /* Blocking mode: Polling */ HAL_StatusTypeDef HAL_TIMEx_OCN_Start(TIM_HandleTypeDef *htim, uint32_t Channel); HAL_StatusTypeDef HAL_TIMEx_OCN_Stop(TIM_HandleTypeDef *htim, uint32_t Channel); /* Non-Blocking mode: Interrupt */ HAL_StatusTypeDef HAL_TIMEx_OCN_Start_IT(TIM_HandleTypeDef *htim, uint32_t Channel); HAL_StatusTypeDef HAL_TIMEx_OCN_Stop_IT(TIM_HandleTypeDef *htim, uint32_t Channel); /* Non-Blocking mode: DMA */ HAL_StatusTypeDef HAL_TIMEx_OCN_Start_DMA(TIM_HandleTypeDef *htim, uint32_t Channel, uint32_t *pData, uint16_t Length); HAL_StatusTypeDef HAL_TIMEx_OCN_Stop_DMA(TIM_HandleTypeDef *htim, uint32_t Channel); /** * @} */ /** @addtogroup TIMEx_Exported_Functions_Group3 * @{ */ /* Timer Complementary PWM functions ****************************************/ /* Blocking mode: Polling */ HAL_StatusTypeDef HAL_TIMEx_PWMN_Start(TIM_HandleTypeDef *htim, uint32_t Channel); HAL_StatusTypeDef HAL_TIMEx_PWMN_Stop(TIM_HandleTypeDef *htim, uint32_t Channel); /* Non-Blocking mode: Interrupt */ HAL_StatusTypeDef HAL_TIMEx_PWMN_Start_IT(TIM_HandleTypeDef *htim, uint32_t Channel); HAL_StatusTypeDef HAL_TIMEx_PWMN_Stop_IT(TIM_HandleTypeDef *htim, uint32_t Channel); /* Non-Blocking mode: DMA */ HAL_StatusTypeDef HAL_TIMEx_PWMN_Start_DMA(TIM_HandleTypeDef *htim, uint32_t Channel, uint32_t *pData, uint16_t Length); HAL_StatusTypeDef HAL_TIMEx_PWMN_Stop_DMA(TIM_HandleTypeDef *htim, uint32_t Channel); /** * @} */ /** @addtogroup TIMEx_Exported_Functions_Group4 * @{ */ /* Timer Complementary One Pulse functions **********************************/ /* Blocking mode: Polling */ HAL_StatusTypeDef HAL_TIMEx_OnePulseN_Start(TIM_HandleTypeDef *htim, uint32_t OutputChannel); HAL_StatusTypeDef HAL_TIMEx_OnePulseN_Stop(TIM_HandleTypeDef *htim, uint32_t OutputChannel); /* Non-Blocking mode: Interrupt */ HAL_StatusTypeDef HAL_TIMEx_OnePulseN_Start_IT(TIM_HandleTypeDef *htim, uint32_t OutputChannel); HAL_StatusTypeDef HAL_TIMEx_OnePulseN_Stop_IT(TIM_HandleTypeDef *htim, uint32_t OutputChannel); /** * @} */ /** @addtogroup TIMEx_Exported_Functions_Group5 * @{ */ /* Extended Control functions ************************************************/ HAL_StatusTypeDef HAL_TIMEx_ConfigCommutationEvent(TIM_HandleTypeDef *htim, uint32_t InputTrigger, uint32_t CommutationSource); HAL_StatusTypeDef HAL_TIMEx_ConfigCommutationEvent_IT(TIM_HandleTypeDef *htim, uint32_t InputTrigger, uint32_t CommutationSource); HAL_StatusTypeDef HAL_TIMEx_ConfigCommutationEvent_DMA(TIM_HandleTypeDef *htim, uint32_t InputTrigger, uint32_t CommutationSource); HAL_StatusTypeDef HAL_TIMEx_MasterConfigSynchronization(TIM_HandleTypeDef *htim, TIM_MasterConfigTypeDef * sMasterConfig); HAL_StatusTypeDef HAL_TIMEx_ConfigBreakDeadTime(TIM_HandleTypeDef *htim, TIM_BreakDeadTimeConfigTypeDef *sBreakDeadTimeConfig); HAL_StatusTypeDef HAL_TIMEx_RemapConfig(TIM_HandleTypeDef *htim, uint32_t Remap); /** * @} */ /** @addtogroup TIMEx_Exported_Functions_Group6 * @{ */ /* Extension Callback *********************************************************/ void HAL_TIMEx_CommutationCallback(TIM_HandleTypeDef *htim); void HAL_TIMEx_BreakCallback(TIM_HandleTypeDef *htim); /** * @} */ /** @addtogroup TIMEx_Exported_Functions_Group7 * @{ */ /* Extension Peripheral State functions **************************************/ HAL_TIM_StateTypeDef HAL_TIMEx_HallSensor_GetState(TIM_HandleTypeDef *htim); /** * @} */ /** * @} */ /* End of exported functions -------------------------------------------------*/ /* Private functions----------------------------------------------------------*/ /** @defgroup TIMEx_Private_Functions TIMEx Private Functions * @{ */ void TIMEx_DMACommutationCplt(DMA_HandleTypeDef *hdma); /** * @} */ /* End of private functions --------------------------------------------------*/ /** * @} */ /** * @} */ #ifdef __cplusplus } #endif #endif /* __STM32F0xx_HAL_TIM_EX_H */ /************************ (C) COPYRIGHT STMicroelectronics *****END OF FILE****/ ================================================ FILE: Zelig/mbed/TARGET_NUCLEO_F091RC/stm32f0xx_hal_tsc.h ================================================ /** ****************************************************************************** * @file stm32f0xx_hal_tsc.h * @author MCD Application Team * @version V1.3.0 * @date 26-June-2015 * @brief This file contains all the functions prototypes for the TSC firmware * library. ****************************************************************************** * @attention * *

© COPYRIGHT(c) 2015 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. * ****************************************************************************** */ /* Define to prevent recursive inclusion -------------------------------------*/ #ifndef __STM32F0xx_TSC_H #define __STM32F0xx_TSC_H #ifdef __cplusplus extern "C" { #endif #if defined(STM32F051x8) || defined(STM32F071xB) || defined(STM32F091xC) || \ defined(STM32F042x6) || defined(STM32F048xx) || defined(STM32F072xB) || \ defined(STM32F058xx) || defined(STM32F078xx) || defined(STM32F098xx) /* Includes ------------------------------------------------------------------*/ #include "stm32f0xx_hal_def.h" /** @addtogroup STM32F0xx_HAL_Driver * @{ */ /** @addtogroup TSC * @{ */ /* Exported types ------------------------------------------------------------*/ /** @defgroup TSC_Exported_Types TSC Exported Types * @{ */ /** * @brief TSC state structure definition */ typedef enum { HAL_TSC_STATE_RESET = 0x00, /*!< TSC registers have their reset value */ HAL_TSC_STATE_READY = 0x01, /*!< TSC registers are initialized or acquisition is completed with success */ HAL_TSC_STATE_BUSY = 0x02, /*!< TSC initialization or acquisition is on-going */ HAL_TSC_STATE_ERROR = 0x03 /*!< Acquisition is completed with max count error */ } HAL_TSC_StateTypeDef; /** * @brief TSC group status structure definition */ typedef enum { TSC_GROUP_ONGOING = 0x00, /*!< Acquisition on group is on-going or not started */ TSC_GROUP_COMPLETED = 0x01 /*!< Acquisition on group is completed with success (no max count error) */ } TSC_GroupStatusTypeDef; /** * @brief TSC init structure definition */ typedef struct { uint32_t CTPulseHighLength; /*!< Charge-transfer high pulse length */ uint32_t CTPulseLowLength; /*!< Charge-transfer low pulse length */ uint32_t SpreadSpectrum; /*!< Spread spectrum activation */ uint32_t SpreadSpectrumDeviation; /*!< Spread spectrum deviation */ uint32_t SpreadSpectrumPrescaler; /*!< Spread spectrum prescaler */ uint32_t PulseGeneratorPrescaler; /*!< Pulse generator prescaler */ uint32_t MaxCountValue; /*!< Max count value */ uint32_t IODefaultMode; /*!< IO default mode */ uint32_t SynchroPinPolarity; /*!< Synchro pin polarity */ uint32_t AcquisitionMode; /*!< Acquisition mode */ uint32_t MaxCountInterrupt; /*!< Max count interrupt activation */ uint32_t ChannelIOs; /*!< Channel IOs mask */ uint32_t ShieldIOs; /*!< Shield IOs mask */ uint32_t SamplingIOs; /*!< Sampling IOs mask */ } TSC_InitTypeDef; /** * @brief TSC IOs configuration structure definition */ typedef struct { uint32_t ChannelIOs; /*!< Channel IOs mask */ uint32_t ShieldIOs; /*!< Shield IOs mask */ uint32_t SamplingIOs; /*!< Sampling IOs mask */ } TSC_IOConfigTypeDef; /** * @brief TSC handle Structure definition */ typedef struct { TSC_TypeDef *Instance; /*!< Register base address */ TSC_InitTypeDef Init; /*!< Initialization parameters */ __IO HAL_TSC_StateTypeDef State; /*!< Peripheral state */ HAL_LockTypeDef Lock; /*!< Lock feature */ } TSC_HandleTypeDef; /** * @} */ /* Exported constants --------------------------------------------------------*/ /** @defgroup TSC_Exported_Constants TSC Exported Constants * @{ */ /** @defgroup TSC_CTPH_Cycles TSC Charge Transfer Pulse High * @{ */ #define TSC_CTPH_1CYCLE ((uint32_t)((uint32_t) 0 << 28)) #define TSC_CTPH_2CYCLES ((uint32_t)((uint32_t) 1 << 28)) #define TSC_CTPH_3CYCLES ((uint32_t)((uint32_t) 2 << 28)) #define TSC_CTPH_4CYCLES ((uint32_t)((uint32_t) 3 << 28)) #define TSC_CTPH_5CYCLES ((uint32_t)((uint32_t) 4 << 28)) #define TSC_CTPH_6CYCLES ((uint32_t)((uint32_t) 5 << 28)) #define TSC_CTPH_7CYCLES ((uint32_t)((uint32_t) 6 << 28)) #define TSC_CTPH_8CYCLES ((uint32_t)((uint32_t) 7 << 28)) #define TSC_CTPH_9CYCLES ((uint32_t)((uint32_t) 8 << 28)) #define TSC_CTPH_10CYCLES ((uint32_t)((uint32_t) 9 << 28)) #define TSC_CTPH_11CYCLES ((uint32_t)((uint32_t)10 << 28)) #define TSC_CTPH_12CYCLES ((uint32_t)((uint32_t)11 << 28)) #define TSC_CTPH_13CYCLES ((uint32_t)((uint32_t)12 << 28)) #define TSC_CTPH_14CYCLES ((uint32_t)((uint32_t)13 << 28)) #define TSC_CTPH_15CYCLES ((uint32_t)((uint32_t)14 << 28)) #define TSC_CTPH_16CYCLES ((uint32_t)((uint32_t)15 << 28)) #define IS_TSC_CTPH(VAL) (((VAL) == TSC_CTPH_1CYCLE) || \ ((VAL) == TSC_CTPH_2CYCLES) || \ ((VAL) == TSC_CTPH_3CYCLES) || \ ((VAL) == TSC_CTPH_4CYCLES) || \ ((VAL) == TSC_CTPH_5CYCLES) || \ ((VAL) == TSC_CTPH_6CYCLES) || \ ((VAL) == TSC_CTPH_7CYCLES) || \ ((VAL) == TSC_CTPH_8CYCLES) || \ ((VAL) == TSC_CTPH_9CYCLES) || \ ((VAL) == TSC_CTPH_10CYCLES) || \ ((VAL) == TSC_CTPH_11CYCLES) || \ ((VAL) == TSC_CTPH_12CYCLES) || \ ((VAL) == TSC_CTPH_13CYCLES) || \ ((VAL) == TSC_CTPH_14CYCLES) || \ ((VAL) == TSC_CTPH_15CYCLES) || \ ((VAL) == TSC_CTPH_16CYCLES)) /** * @} */ /** @defgroup TSC_CTPL_Cycles TSC Charge Transfer Pulse Low * @{ */ #define TSC_CTPL_1CYCLE ((uint32_t)((uint32_t) 0 << 24)) #define TSC_CTPL_2CYCLES ((uint32_t)((uint32_t) 1 << 24)) #define TSC_CTPL_3CYCLES ((uint32_t)((uint32_t) 2 << 24)) #define TSC_CTPL_4CYCLES ((uint32_t)((uint32_t) 3 << 24)) #define TSC_CTPL_5CYCLES ((uint32_t)((uint32_t) 4 << 24)) #define TSC_CTPL_6CYCLES ((uint32_t)((uint32_t) 5 << 24)) #define TSC_CTPL_7CYCLES ((uint32_t)((uint32_t) 6 << 24)) #define TSC_CTPL_8CYCLES ((uint32_t)((uint32_t) 7 << 24)) #define TSC_CTPL_9CYCLES ((uint32_t)((uint32_t) 8 << 24)) #define TSC_CTPL_10CYCLES ((uint32_t)((uint32_t) 9 << 24)) #define TSC_CTPL_11CYCLES ((uint32_t)((uint32_t)10 << 24)) #define TSC_CTPL_12CYCLES ((uint32_t)((uint32_t)11 << 24)) #define TSC_CTPL_13CYCLES ((uint32_t)((uint32_t)12 << 24)) #define TSC_CTPL_14CYCLES ((uint32_t)((uint32_t)13 << 24)) #define TSC_CTPL_15CYCLES ((uint32_t)((uint32_t)14 << 24)) #define TSC_CTPL_16CYCLES ((uint32_t)((uint32_t)15 << 24)) #define IS_TSC_CTPL(VAL) (((VAL) == TSC_CTPL_1CYCLE) || \ ((VAL) == TSC_CTPL_2CYCLES) || \ ((VAL) == TSC_CTPL_3CYCLES) || \ ((VAL) == TSC_CTPL_4CYCLES) || \ ((VAL) == TSC_CTPL_5CYCLES) || \ ((VAL) == TSC_CTPL_6CYCLES) || \ ((VAL) == TSC_CTPL_7CYCLES) || \ ((VAL) == TSC_CTPL_8CYCLES) || \ ((VAL) == TSC_CTPL_9CYCLES) || \ ((VAL) == TSC_CTPL_10CYCLES) || \ ((VAL) == TSC_CTPL_11CYCLES) || \ ((VAL) == TSC_CTPL_12CYCLES) || \ ((VAL) == TSC_CTPL_13CYCLES) || \ ((VAL) == TSC_CTPL_14CYCLES) || \ ((VAL) == TSC_CTPL_15CYCLES) || \ ((VAL) == TSC_CTPL_16CYCLES)) /** * @} */ /** @defgroup TSC_SS_Prescaler_definition TSC Spread spectrum prescaler definition * @{ */ #define TSC_SS_PRESC_DIV1 ((uint32_t)0) #define TSC_SS_PRESC_DIV2 (TSC_CR_SSPSC) #define IS_TSC_SS_PRESC(VAL) (((VAL) == TSC_SS_PRESC_DIV1) || ((VAL) == TSC_SS_PRESC_DIV2)) /** * @} */ /** @defgroup TSC_PG_Prescaler_definition TSC Pulse Generator prescaler definition * @{ */ #define TSC_PG_PRESC_DIV1 ((uint32_t)(0 << 12)) #define TSC_PG_PRESC_DIV2 ((uint32_t)(1 << 12)) #define TSC_PG_PRESC_DIV4 ((uint32_t)(2 << 12)) #define TSC_PG_PRESC_DIV8 ((uint32_t)(3 << 12)) #define TSC_PG_PRESC_DIV16 ((uint32_t)(4 << 12)) #define TSC_PG_PRESC_DIV32 ((uint32_t)(5 << 12)) #define TSC_PG_PRESC_DIV64 ((uint32_t)(6 << 12)) #define TSC_PG_PRESC_DIV128 ((uint32_t)(7 << 12)) #define IS_TSC_PG_PRESC(VAL) (((VAL) == TSC_PG_PRESC_DIV1) || \ ((VAL) == TSC_PG_PRESC_DIV2) || \ ((VAL) == TSC_PG_PRESC_DIV4) || \ ((VAL) == TSC_PG_PRESC_DIV8) || \ ((VAL) == TSC_PG_PRESC_DIV16) || \ ((VAL) == TSC_PG_PRESC_DIV32) || \ ((VAL) == TSC_PG_PRESC_DIV64) || \ ((VAL) == TSC_PG_PRESC_DIV128)) /** * @} */ /** @defgroup TSC_MCV_definition TSC Max Count Value definition * @{ */ #define TSC_MCV_255 ((uint32_t)(0 << 5)) #define TSC_MCV_511 ((uint32_t)(1 << 5)) #define TSC_MCV_1023 ((uint32_t)(2 << 5)) #define TSC_MCV_2047 ((uint32_t)(3 << 5)) #define TSC_MCV_4095 ((uint32_t)(4 << 5)) #define TSC_MCV_8191 ((uint32_t)(5 << 5)) #define TSC_MCV_16383 ((uint32_t)(6 << 5)) #define IS_TSC_MCV(VAL) (((VAL) == TSC_MCV_255) || \ ((VAL) == TSC_MCV_511) || \ ((VAL) == TSC_MCV_1023) || \ ((VAL) == TSC_MCV_2047) || \ ((VAL) == TSC_MCV_4095) || \ ((VAL) == TSC_MCV_8191) || \ ((VAL) == TSC_MCV_16383)) /** * @} */ /** @defgroup TSC_IO_default_mode_definition TSC I/O default mode definition * @{ */ #define TSC_IODEF_OUT_PP_LOW ((uint32_t)0) #define TSC_IODEF_IN_FLOAT (TSC_CR_IODEF) #define IS_TSC_IODEF(VAL) (((VAL) == TSC_IODEF_OUT_PP_LOW) || ((VAL) == TSC_IODEF_IN_FLOAT)) /** * @} */ /** @defgroup TSC_Synchronization_pin_polarity TSC Synchronization pin polarity * @{ */ #define TSC_SYNC_POLARITY_FALLING ((uint32_t)0) #define TSC_SYNC_POLARITY_RISING (TSC_CR_SYNCPOL) #define IS_TSC_SYNC_POL(VAL) (((VAL) == TSC_SYNC_POLARITY_FALLING) || ((VAL) == TSC_SYNC_POLARITY_RISING)) /** * @} */ /** @defgroup TSC_Acquisition_mode TSC Acquisition mode * @{ */ #define TSC_ACQ_MODE_NORMAL ((uint32_t)0) #define TSC_ACQ_MODE_SYNCHRO (TSC_CR_AM) #define IS_TSC_ACQ_MODE(VAL) (((VAL) == TSC_ACQ_MODE_NORMAL) || ((VAL) == TSC_ACQ_MODE_SYNCHRO)) /** * @} */ /** @defgroup TSC_IO_mode_definition TSC I/O mode definition * @{ */ #define TSC_IOMODE_UNUSED ((uint32_t)0) #define TSC_IOMODE_CHANNEL ((uint32_t)1) #define TSC_IOMODE_SHIELD ((uint32_t)2) #define TSC_IOMODE_SAMPLING ((uint32_t)3) #define IS_TSC_IOMODE(VAL) (((VAL) == TSC_IOMODE_UNUSED) || \ ((VAL) == TSC_IOMODE_CHANNEL) || \ ((VAL) == TSC_IOMODE_SHIELD) || \ ((VAL) == TSC_IOMODE_SAMPLING)) /** * @} */ /** @defgroup TSC_interrupts_definition TSC interrupts definition * @{ */ #define TSC_IT_EOA ((uint32_t)TSC_IER_EOAIE) #define TSC_IT_MCE ((uint32_t)TSC_IER_MCEIE) #define IS_TSC_MCE_IT(VAL) (((VAL) == DISABLE) || ((VAL) == ENABLE)) /** * @} */ /** @defgroup TSC_flags_definition TSC Flags Definition * @{ */ #define TSC_FLAG_EOA ((uint32_t)TSC_ISR_EOAF) #define TSC_FLAG_MCE ((uint32_t)TSC_ISR_MCEF) /** * @} */ /** @defgroup TSC_groups_definition TSC groups definition * @{ */ #define TSC_NB_OF_GROUPS (8) #define TSC_GROUP1 ((uint32_t)0x00000001) #define TSC_GROUP2 ((uint32_t)0x00000002) #define TSC_GROUP3 ((uint32_t)0x00000004) #define TSC_GROUP4 ((uint32_t)0x00000008) #define TSC_GROUP5 ((uint32_t)0x00000010) #define TSC_GROUP6 ((uint32_t)0x00000020) #define TSC_GROUP7 ((uint32_t)0x00000040) #define TSC_GROUP8 ((uint32_t)0x00000080) #define TSC_ALL_GROUPS ((uint32_t)0x000000FF) #define TSC_GROUP1_IDX ((uint32_t)0) #define TSC_GROUP2_IDX ((uint32_t)1) #define TSC_GROUP3_IDX ((uint32_t)2) #define TSC_GROUP4_IDX ((uint32_t)3) #define TSC_GROUP5_IDX ((uint32_t)4) #define TSC_GROUP6_IDX ((uint32_t)5) #define TSC_GROUP7_IDX ((uint32_t)6) #define TSC_GROUP8_IDX ((uint32_t)7) #define IS_GROUP_INDEX(VAL) (((VAL) == 0) || (((VAL) > 0) && ((VAL) < TSC_NB_OF_GROUPS))) #define TSC_GROUP1_IO1 ((uint32_t)0x00000001) #define TSC_GROUP1_IO2 ((uint32_t)0x00000002) #define TSC_GROUP1_IO3 ((uint32_t)0x00000004) #define TSC_GROUP1_IO4 ((uint32_t)0x00000008) #define TSC_GROUP1_ALL_IOS ((uint32_t)0x0000000F) #define TSC_GROUP2_IO1 ((uint32_t)0x00000010) #define TSC_GROUP2_IO2 ((uint32_t)0x00000020) #define TSC_GROUP2_IO3 ((uint32_t)0x00000040) #define TSC_GROUP2_IO4 ((uint32_t)0x00000080) #define TSC_GROUP2_ALL_IOS ((uint32_t)0x000000F0) #define TSC_GROUP3_IO1 ((uint32_t)0x00000100) #define TSC_GROUP3_IO2 ((uint32_t)0x00000200) #define TSC_GROUP3_IO3 ((uint32_t)0x00000400) #define TSC_GROUP3_IO4 ((uint32_t)0x00000800) #define TSC_GROUP3_ALL_IOS ((uint32_t)0x00000F00) #define TSC_GROUP4_IO1 ((uint32_t)0x00001000) #define TSC_GROUP4_IO2 ((uint32_t)0x00002000) #define TSC_GROUP4_IO3 ((uint32_t)0x00004000) #define TSC_GROUP4_IO4 ((uint32_t)0x00008000) #define TSC_GROUP4_ALL_IOS ((uint32_t)0x0000F000) #define TSC_GROUP5_IO1 ((uint32_t)0x00010000) #define TSC_GROUP5_IO2 ((uint32_t)0x00020000) #define TSC_GROUP5_IO3 ((uint32_t)0x00040000) #define TSC_GROUP5_IO4 ((uint32_t)0x00080000) #define TSC_GROUP5_ALL_IOS ((uint32_t)0x000F0000) #define TSC_GROUP6_IO1 ((uint32_t)0x00100000) #define TSC_GROUP6_IO2 ((uint32_t)0x00200000) #define TSC_GROUP6_IO3 ((uint32_t)0x00400000) #define TSC_GROUP6_IO4 ((uint32_t)0x00800000) #define TSC_GROUP6_ALL_IOS ((uint32_t)0x00F00000) #define TSC_GROUP7_IO1 ((uint32_t)0x01000000) #define TSC_GROUP7_IO2 ((uint32_t)0x02000000) #define TSC_GROUP7_IO3 ((uint32_t)0x04000000) #define TSC_GROUP7_IO4 ((uint32_t)0x08000000) #define TSC_GROUP7_ALL_IOS ((uint32_t)0x0F000000) #define TSC_GROUP8_IO1 ((uint32_t)0x10000000) #define TSC_GROUP8_IO2 ((uint32_t)0x20000000) #define TSC_GROUP8_IO3 ((uint32_t)0x40000000) #define TSC_GROUP8_IO4 ((uint32_t)0x80000000) #define TSC_GROUP8_ALL_IOS ((uint32_t)0xF0000000) #define TSC_ALL_GROUPS_ALL_IOS ((uint32_t)0xFFFFFFFF) /** * @} */ /** * @} */ /* Private macros -----------------------------------------------------------*/ /** @defgroup TSC_Private_Macros TSC Private Macros * @{ */ /** @defgroup TSC_Spread_Spectrum TSC Spread Spectrum * @{ */ #define IS_TSC_SS(VAL) (((VAL) == DISABLE) || ((VAL) == ENABLE)) #define IS_TSC_SSD(VAL) (((VAL) == 0) || (((VAL) > 0) && ((VAL) < 128))) /** * @} */ /** * @} */ /* Exported macros -----------------------------------------------------------*/ /** @defgroup TSC_Exported_Macros TSC Exported Macros * @{ */ /** @brief Reset TSC handle state * @param __HANDLE__: TSC handle. * @retval None */ #define __HAL_TSC_RESET_HANDLE_STATE(__HANDLE__) ((__HANDLE__)->State = HAL_TSC_STATE_RESET) /** * @brief Enable the TSC peripheral. * @param __HANDLE__: TSC handle * @retval None */ #define __HAL_TSC_ENABLE(__HANDLE__) ((__HANDLE__)->Instance->CR |= TSC_CR_TSCE) /** * @brief Disable the TSC peripheral. * @param __HANDLE__: TSC handle * @retval None */ #define __HAL_TSC_DISABLE(__HANDLE__) ((__HANDLE__)->Instance->CR &= (uint32_t)(~TSC_CR_TSCE)) /** * @brief Start acquisition * @param __HANDLE__: TSC handle * @retval None */ #define __HAL_TSC_START_ACQ(__HANDLE__) ((__HANDLE__)->Instance->CR |= TSC_CR_START) /** * @brief Stop acquisition * @param __HANDLE__: TSC handle * @retval None */ #define __HAL_TSC_STOP_ACQ(__HANDLE__) ((__HANDLE__)->Instance->CR &= (uint32_t)(~TSC_CR_START)) /** * @brief Set IO default mode to output push-pull low * @param __HANDLE__: TSC handle * @retval None */ #define __HAL_TSC_SET_IODEF_OUTPPLOW(__HANDLE__) ((__HANDLE__)->Instance->CR &= (uint32_t)(~TSC_CR_IODEF)) /** * @brief Set IO default mode to input floating * @param __HANDLE__: TSC handle * @retval None */ #define __HAL_TSC_SET_IODEF_INFLOAT(__HANDLE__) ((__HANDLE__)->Instance->CR |= TSC_CR_IODEF) /** * @brief Set synchronization polarity to falling edge * @param __HANDLE__: TSC handle * @retval None */ #define __HAL_TSC_SET_SYNC_POL_FALL(__HANDLE__) ((__HANDLE__)->Instance->CR &= (uint32_t)(~TSC_CR_SYNCPOL)) /** * @brief Set synchronization polarity to rising edge and high level * @param __HANDLE__: TSC handle * @retval None */ #define __HAL_TSC_SET_SYNC_POL_RISE_HIGH(__HANDLE__) ((__HANDLE__)->Instance->CR |= TSC_CR_SYNCPOL) /** * @brief Enable TSC interrupt. * @param __HANDLE__: TSC handle * @param __INTERRUPT__: TSC interrupt * @retval None */ #define __HAL_TSC_ENABLE_IT(__HANDLE__, __INTERRUPT__) ((__HANDLE__)->Instance->IER |= (__INTERRUPT__)) /** * @brief Disable TSC interrupt. * @param __HANDLE__: TSC handle * @param __INTERRUPT__: TSC interrupt * @retval None */ #define __HAL_TSC_DISABLE_IT(__HANDLE__, __INTERRUPT__) ((__HANDLE__)->Instance->IER &= (uint32_t)(~(__INTERRUPT__))) /** @brief Check if the specified TSC interrupt source is enabled or disabled. * @param __HANDLE__: TSC Handle * @param __INTERRUPT__: TSC interrupt * @retval SET or RESET */ #define __HAL_TSC_GET_IT_SOURCE(__HANDLE__, __INTERRUPT__) ((((__HANDLE__)->Instance->IER & (__INTERRUPT__)) == (__INTERRUPT__)) ? SET : RESET) /** * @brief Get the selected TSC's flag status. * @param __HANDLE__: TSC handle * @param __FLAG__: TSC flag * @retval SET or RESET */ #define __HAL_TSC_GET_FLAG(__HANDLE__, __FLAG__) ((((__HANDLE__)->Instance->ISR & (__FLAG__)) == (__FLAG__)) ? SET : RESET) /** * @brief Clear the TSC's pending flag. * @param __HANDLE__: TSC handle * @param __FLAG__: TSC flag * @retval None */ #define __HAL_TSC_CLEAR_FLAG(__HANDLE__, __FLAG__) ((__HANDLE__)->Instance->ICR = (__FLAG__)) /** * @brief Enable schmitt trigger hysteresis on a group of IOs * @param __HANDLE__: TSC handle * @param __GX_IOY_MASK__: IOs mask * @retval None */ #define __HAL_TSC_ENABLE_HYSTERESIS(__HANDLE__, __GX_IOY_MASK__) ((__HANDLE__)->Instance->IOHCR |= (__GX_IOY_MASK__)) /** * @brief Disable schmitt trigger hysteresis on a group of IOs * @param __HANDLE__: TSC handle * @param __GX_IOY_MASK__: IOs mask * @retval None */ #define __HAL_TSC_DISABLE_HYSTERESIS(__HANDLE__, __GX_IOY_MASK__) ((__HANDLE__)->Instance->IOHCR &= (uint32_t)(~(__GX_IOY_MASK__))) /** * @brief Open analog switch on a group of IOs * @param __HANDLE__: TSC handle * @param __GX_IOY_MASK__: IOs mask * @retval None */ #define __HAL_TSC_OPEN_ANALOG_SWITCH(__HANDLE__, __GX_IOY_MASK__) ((__HANDLE__)->Instance->IOASCR &= (uint32_t)(~(__GX_IOY_MASK__))) /** * @brief Close analog switch on a group of IOs * @param __HANDLE__: TSC handle * @param __GX_IOY_MASK__: IOs mask * @retval None */ #define __HAL_TSC_CLOSE_ANALOG_SWITCH(__HANDLE__, __GX_IOY_MASK__) ((__HANDLE__)->Instance->IOASCR |= (__GX_IOY_MASK__)) /** * @brief Enable a group of IOs in channel mode * @param __HANDLE__: TSC handle * @param __GX_IOY_MASK__: IOs mask * @retval None */ #define __HAL_TSC_ENABLE_CHANNEL(__HANDLE__, __GX_IOY_MASK__) ((__HANDLE__)->Instance->IOCCR |= (__GX_IOY_MASK__)) /** * @brief Disable a group of channel IOs * @param __HANDLE__: TSC handle * @param __GX_IOY_MASK__: IOs mask * @retval None */ #define __HAL_TSC_DISABLE_CHANNEL(__HANDLE__, __GX_IOY_MASK__) ((__HANDLE__)->Instance->IOCCR &= (uint32_t)(~(__GX_IOY_MASK__))) /** * @brief Enable a group of IOs in sampling mode * @param __HANDLE__: TSC handle * @param __GX_IOY_MASK__: IOs mask * @retval None */ #define __HAL_TSC_ENABLE_SAMPLING(__HANDLE__, __GX_IOY_MASK__) ((__HANDLE__)->Instance->IOSCR |= (__GX_IOY_MASK__)) /** * @brief Disable a group of sampling IOs * @param __HANDLE__: TSC handle * @param __GX_IOY_MASK__: IOs mask * @retval None */ #define __HAL_TSC_DISABLE_SAMPLING(__HANDLE__, __GX_IOY_MASK__) ((__HANDLE__)->Instance->IOSCR &= (uint32_t)(~(__GX_IOY_MASK__))) /** * @brief Enable acquisition groups * @param __HANDLE__: TSC handle * @param __GX_MASK__: Groups mask * @retval None */ #define __HAL_TSC_ENABLE_GROUP(__HANDLE__, __GX_MASK__) ((__HANDLE__)->Instance->IOGCSR |= (__GX_MASK__)) /** * @brief Disable acquisition groups * @param __HANDLE__: TSC handle * @param __GX_MASK__: Groups mask * @retval None */ #define __HAL_TSC_DISABLE_GROUP(__HANDLE__, __GX_MASK__) ((__HANDLE__)->Instance->IOGCSR &= (uint32_t)(~(__GX_MASK__))) /** @brief Gets acquisition group status * @param __HANDLE__: TSC Handle * @param __GX_INDEX__: Group index * @retval SET or RESET */ #define __HAL_TSC_GET_GROUP_STATUS(__HANDLE__, __GX_INDEX__) \ ((((__HANDLE__)->Instance->IOGCSR & (uint32_t)((uint32_t)1 << ((__GX_INDEX__) + (uint32_t)16))) == (uint32_t)((uint32_t)1 << ((__GX_INDEX__) + (uint32_t)16))) ? TSC_GROUP_COMPLETED : TSC_GROUP_ONGOING) /** * @} */ /* Exported functions --------------------------------------------------------*/ /** @addtogroup TSC_Exported_Functions TSC Exported Functions * @{ */ /** @addtogroup TSC_Exported_Functions_Group1 Initialization/de-initialization functions * @brief Initialization and Configuration functions * @{ */ /* Initialization and de-initialization functions *****************************/ HAL_StatusTypeDef HAL_TSC_Init(TSC_HandleTypeDef* htsc); HAL_StatusTypeDef HAL_TSC_DeInit(TSC_HandleTypeDef *htsc); void HAL_TSC_MspInit(TSC_HandleTypeDef* htsc); void HAL_TSC_MspDeInit(TSC_HandleTypeDef* htsc); /** * @} */ /** @addtogroup TSC_Exported_Functions_Group2 IO operation functions * @brief IO operation functions * @{ */ /* IO operation functions *****************************************************/ HAL_StatusTypeDef HAL_TSC_Start(TSC_HandleTypeDef* htsc); HAL_StatusTypeDef HAL_TSC_Start_IT(TSC_HandleTypeDef* htsc); HAL_StatusTypeDef HAL_TSC_Stop(TSC_HandleTypeDef* htsc); HAL_StatusTypeDef HAL_TSC_Stop_IT(TSC_HandleTypeDef* htsc); TSC_GroupStatusTypeDef HAL_TSC_GroupGetStatus(TSC_HandleTypeDef* htsc, uint32_t gx_index); uint32_t HAL_TSC_GroupGetValue(TSC_HandleTypeDef* htsc, uint32_t gx_index); /** * @} */ /** @addtogroup TSC_Exported_Functions_Group3 Peripheral Control functions * @brief Peripheral Control functions * @{ */ /* Peripheral Control functions ***********************************************/ HAL_StatusTypeDef HAL_TSC_IOConfig(TSC_HandleTypeDef* htsc, TSC_IOConfigTypeDef* config); HAL_StatusTypeDef HAL_TSC_IODischarge(TSC_HandleTypeDef* htsc, uint32_t choice); /** * @} */ /** @addtogroup TSC_Exported_Functions_Group4 State functions * @brief State functions * @{ */ /* Peripheral State and Error functions ***************************************/ HAL_TSC_StateTypeDef HAL_TSC_GetState(TSC_HandleTypeDef* htsc); HAL_StatusTypeDef HAL_TSC_PollForAcquisition(TSC_HandleTypeDef* htsc); void HAL_TSC_IRQHandler(TSC_HandleTypeDef* htsc); /** * @} */ /** @addtogroup TSC_Exported_Functions_Group5 Callback functions * @brief Callback functions * @{ */ /* Callback functions *********************************************************/ void HAL_TSC_ConvCpltCallback(TSC_HandleTypeDef* htsc); void HAL_TSC_ErrorCallback(TSC_HandleTypeDef* htsc); /** * @} */ /** * @} */ /** * @} */ /** * @} */ #endif /* defined(STM32F051x8) || defined(STM32F071xB) || defined(STM32F091xC) || */ /* defined(STM32F042x6) || defined(STM32F048xx) || defined(STM32F072xB) || */ /* defined(STM32F058xx) || defined(STM32F078xx) || defined(STM32F098xx) */ #ifdef __cplusplus } #endif #endif /*__STM32F0xx_TSC_H */ /************************ (C) COPYRIGHT STMicroelectronics *****END OF FILE****/ ================================================ FILE: Zelig/mbed/TARGET_NUCLEO_F091RC/stm32f0xx_hal_uart.h ================================================ /** ****************************************************************************** * @file stm32f0xx_hal_uart.h * @author MCD Application Team * @version V1.3.0 * @date 26-June-2015 * @brief Header file of UART HAL module. ****************************************************************************** * @attention * *

© COPYRIGHT(c) 2015 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. * ****************************************************************************** */ /* Define to prevent recursive inclusion -------------------------------------*/ #ifndef __STM32F0xx_HAL_UART_H #define __STM32F0xx_HAL_UART_H #ifdef __cplusplus extern "C" { #endif /* Includes ------------------------------------------------------------------*/ #include "stm32f0xx_hal_def.h" /** @addtogroup STM32F0xx_HAL_Driver * @{ */ /** @addtogroup UART * @{ */ /* Exported types ------------------------------------------------------------*/ /** @defgroup UART_Exported_Types UART Exported Types * @{ */ /** * @brief UART Init Structure definition */ typedef struct { uint32_t BaudRate; /*!< This member configures the UART communication baud rate. The baud rate register is computed using the following formula: - If oversampling is 16 or in LIN mode (LIN mode not available on F030xx devices), Baud Rate Register = ((PCLKx) / ((huart->Init.BaudRate))) - If oversampling is 8, Baud Rate Register[15:4] = ((2 * PCLKx) / ((huart->Init.BaudRate)))[15:4] Baud Rate Register[3] = 0 Baud Rate Register[2:0] = (((2 * PCLKx) / ((huart->Init.BaudRate)))[3:0]) >> 1 */ uint32_t WordLength; /*!< Specifies the number of data bits transmitted or received in a frame. This parameter can be a value of @ref UARTEx_Word_Length */ uint32_t StopBits; /*!< Specifies the number of stop bits transmitted. This parameter can be a value of @ref UART_Stop_Bits */ uint32_t Parity; /*!< Specifies the parity mode. This parameter can be a value of @ref UART_Parity @note When parity is enabled, the computed parity is inserted at the MSB position of the transmitted data (9th bit when the word length is set to 9 data bits; 8th bit when the word length is set to 8 data bits). */ uint32_t Mode; /*!< Specifies whether the Receive or Transmit mode is enabled or disabled. This parameter can be a value of @ref UART_Mode */ uint32_t HwFlowCtl; /*!< Specifies whether the hardware flow control mode is enabled or disabled. This parameter can be a value of @ref UART_Hardware_Flow_Control */ uint32_t OverSampling; /*!< Specifies whether the Over sampling 8 is enabled or disabled, to achieve higher speed (up to f_PCLK/8). This parameter can be a value of @ref UART_Over_Sampling */ uint32_t OneBitSampling; /*!< Specifies whether a single sample or three samples' majority vote is selected. Selecting the single sample method increases the receiver tolerance to clock deviations. This parameter can be a value of @ref UART_OneBit_Sampling. */ }UART_InitTypeDef; /** * @brief UART Advanced Features initalization structure definition */ typedef struct { uint32_t AdvFeatureInit; /*!< Specifies which advanced UART features is initialized. Several Advanced Features may be initialized at the same time . This parameter can be a value of @ref UART_Advanced_Features_Initialization_Type */ uint32_t TxPinLevelInvert; /*!< Specifies whether the TX pin active level is inverted. This parameter can be a value of @ref UART_Tx_Inv */ uint32_t RxPinLevelInvert; /*!< Specifies whether the RX pin active level is inverted. This parameter can be a value of @ref UART_Rx_Inv */ uint32_t DataInvert; /*!< Specifies whether data are inverted (positive/direct logic vs negative/inverted logic). This parameter can be a value of @ref UART_Data_Inv */ uint32_t Swap; /*!< Specifies whether TX and RX pins are swapped. This parameter can be a value of @ref UART_Rx_Tx_Swap */ uint32_t OverrunDisable; /*!< Specifies whether the reception overrun detection is disabled. This parameter can be a value of @ref UART_Overrun_Disable */ uint32_t DMADisableonRxError; /*!< Specifies whether the DMA is disabled in case of reception error. This parameter can be a value of @ref UART_DMA_Disable_on_Rx_Error */ uint32_t AutoBaudRateEnable; /*!< Specifies whether auto Baud rate detection is enabled. This parameter can be a value of @ref UART_AutoBaudRate_Enable */ uint32_t AutoBaudRateMode; /*!< If auto Baud rate detection is enabled, specifies how the rate detection is carried out. This parameter can be a value of @ref UARTEx_AutoBaud_Rate_Mode */ uint32_t MSBFirst; /*!< Specifies whether MSB is sent first on UART line. This parameter can be a value of @ref UART_MSB_First */ } UART_AdvFeatureInitTypeDef; /** * @brief HAL UART State structures definition */ typedef enum { HAL_UART_STATE_RESET = 0x00, /*!< Peripheral is not initialized */ HAL_UART_STATE_READY = 0x01, /*!< Peripheral Initialized and ready for use */ HAL_UART_STATE_BUSY = 0x02, /*!< an internal process is ongoing */ HAL_UART_STATE_BUSY_TX = 0x12, /*!< Data Transmission process is ongoing */ HAL_UART_STATE_BUSY_RX = 0x22, /*!< Data Reception process is ongoing */ HAL_UART_STATE_BUSY_TX_RX = 0x32, /*!< Data Transmission and Reception process is ongoing */ HAL_UART_STATE_TIMEOUT = 0x03, /*!< Timeout state */ HAL_UART_STATE_ERROR = 0x04 /*!< Error */ }HAL_UART_StateTypeDef; /** * @brief UART clock sources definition */ typedef enum { UART_CLOCKSOURCE_PCLK1 = 0x00, /*!< PCLK1 clock source */ UART_CLOCKSOURCE_HSI = 0x02, /*!< HSI clock source */ UART_CLOCKSOURCE_SYSCLK = 0x04, /*!< SYSCLK clock source */ UART_CLOCKSOURCE_LSE = 0x08, /*!< LSE clock source */ UART_CLOCKSOURCE_UNDEFINED = 0x10 /*!< Undefined clock source */ }UART_ClockSourceTypeDef; /** * @brief UART handle Structure definition */ typedef struct { USART_TypeDef *Instance; /*!< UART registers base address */ UART_InitTypeDef Init; /*!< UART communication parameters */ UART_AdvFeatureInitTypeDef AdvancedInit; /*!< UART Advanced Features initialization parameters */ uint8_t *pTxBuffPtr; /*!< Pointer to UART Tx transfer Buffer */ uint16_t TxXferSize; /*!< UART Tx Transfer size */ uint16_t TxXferCount; /*!< UART Tx Transfer Counter */ uint8_t *pRxBuffPtr; /*!< Pointer to UART Rx transfer Buffer */ uint16_t RxXferSize; /*!< UART Rx Transfer size */ uint16_t RxXferCount; /*!< UART Rx Transfer Counter */ uint16_t Mask; /*!< UART Rx RDR register mask */ DMA_HandleTypeDef *hdmatx; /*!< UART Tx DMA Handle parameters */ DMA_HandleTypeDef *hdmarx; /*!< UART Rx DMA Handle parameters */ HAL_LockTypeDef Lock; /*!< Locking object */ __IO HAL_UART_StateTypeDef State; /*!< UART communication state */ __IO uint32_t ErrorCode; /*!< UART Error code */ }UART_HandleTypeDef; /** * @} */ /* Exported constants --------------------------------------------------------*/ /** @defgroup UART_Exported_Constants UART Exported Constants * @{ */ /** @defgroup UART_Error UART Error * @{ */ #define HAL_UART_ERROR_NONE ((uint32_t)0x00000000) /*!< No error */ #define HAL_UART_ERROR_PE ((uint32_t)0x00000001) /*!< Parity error */ #define HAL_UART_ERROR_NE ((uint32_t)0x00000002) /*!< Noise error */ #define HAL_UART_ERROR_FE ((uint32_t)0x00000004) /*!< frame error */ #define HAL_UART_ERROR_ORE ((uint32_t)0x00000008) /*!< Overrun error */ #define HAL_UART_ERROR_DMA ((uint32_t)0x00000010) /*!< DMA transfer error */ /** * @} */ /** @defgroup UART_Stop_Bits UART Number of Stop Bits * @{ */ #define UART_STOPBITS_1 ((uint32_t)0x0000) #define UART_STOPBITS_2 ((uint32_t)USART_CR2_STOP_1) #define UART_STOPBITS_1_5 ((uint32_t)(USART_CR2_STOP_0 | USART_CR2_STOP_1)) /** * @} */ /** @defgroup UART_Parity UART Parity * @{ */ #define UART_PARITY_NONE ((uint32_t)0x00000000) /*!< No parity */ #define UART_PARITY_EVEN ((uint32_t)USART_CR1_PCE) /*!< Even parity */ #define UART_PARITY_ODD ((uint32_t)(USART_CR1_PCE | USART_CR1_PS)) /*!< Odd parity */ /** * @} */ /** @defgroup UART_Hardware_Flow_Control UART Hardware Flow Control * @{ */ #define UART_HWCONTROL_NONE ((uint32_t)0x00000000) /*!< No hardware control */ #define UART_HWCONTROL_RTS ((uint32_t)USART_CR3_RTSE) /*!< Request To Send */ #define UART_HWCONTROL_CTS ((uint32_t)USART_CR3_CTSE) /*!< Clear To Send */ #define UART_HWCONTROL_RTS_CTS ((uint32_t)(USART_CR3_RTSE | USART_CR3_CTSE)) /*!< Request and Clear To Send */ /** * @} */ /** @defgroup UART_Mode UART Transfer Mode * @{ */ #define UART_MODE_RX ((uint32_t)USART_CR1_RE) /*!< RX mode */ #define UART_MODE_TX ((uint32_t)USART_CR1_TE) /*!< TX mode */ #define UART_MODE_TX_RX ((uint32_t)(USART_CR1_TE |USART_CR1_RE)) /*!< RX and TX mode */ /** * @} */ /** @defgroup UART_State UART State * @{ */ #define UART_STATE_DISABLE ((uint32_t)0x00000000) /*!< UART disabled */ #define UART_STATE_ENABLE ((uint32_t)USART_CR1_UE) /*!< UART enabled */ /** * @} */ /** @defgroup UART_Over_Sampling UART Over Sampling * @{ */ #define UART_OVERSAMPLING_16 ((uint32_t)0x00000000) /*!< Oversampling by 16 */ #define UART_OVERSAMPLING_8 ((uint32_t)USART_CR1_OVER8) /*!< Oversampling by 8 */ /** * @} */ /** @defgroup UART_OneBit_Sampling UART One Bit Sampling Method * @{ */ #define UART_ONE_BIT_SAMPLE_DISABLE ((uint32_t)0x00000000) /*!< One-bit sampling disable */ #define UART_ONE_BIT_SAMPLE_ENABLE ((uint32_t)USART_CR3_ONEBIT) /*!< One-bit sampling enable */ /** * @} */ /** @defgroup UART_Receiver_TimeOut UART Receiver TimeOut * @{ */ #define UART_RECEIVER_TIMEOUT_DISABLE ((uint32_t)0x00000000) /*!< UART receiver timeout disable */ #define UART_RECEIVER_TIMEOUT_ENABLE ((uint32_t)USART_CR2_RTOEN) /*!< UART receiver timeout enable */ /** * @} */ /** @defgroup UART_DMA_Tx UART DMA Tx * @{ */ #define UART_DMA_TX_DISABLE ((uint32_t)0x00000000) /*!< UART DMA TX disabled */ #define UART_DMA_TX_ENABLE ((uint32_t)USART_CR3_DMAT) /*!< UART DMA TX enabled */ /** * @} */ /** @defgroup UART_DMA_Rx UART DMA Rx * @{ */ #define UART_DMA_RX_DISABLE ((uint32_t)0x00000000) /*!< UART DMA RX disabled */ #define UART_DMA_RX_ENABLE ((uint32_t)USART_CR3_DMAR) /*!< UART DMA RX enabled */ /** * @} */ /** @defgroup UART_Half_Duplex_Selection UART Half Duplex Selection * @{ */ #define UART_HALF_DUPLEX_DISABLE ((uint32_t)0x00000000) /*!< UART half-duplex disabled */ #define UART_HALF_DUPLEX_ENABLE ((uint32_t)USART_CR3_HDSEL) /*!< UART half-duplex enabled */ /** * @} */ /** @defgroup UART_WakeUp_Address_Length UART WakeUp Address Length * @{ */ #define UART_ADDRESS_DETECT_4B ((uint32_t)0x00000000) /*!< 4-bit long wake-up address */ #define UART_ADDRESS_DETECT_7B ((uint32_t)USART_CR2_ADDM7) /*!< 7-bit long wake-up address */ /** * @} */ /** @defgroup UART_WakeUp_Methods UART WakeUp Methods * @{ */ #define UART_WAKEUPMETHOD_IDLELINE ((uint32_t)0x00000000) /*!< UART wake-up on idle line */ #define UART_WAKEUPMETHOD_ADDRESSMARK ((uint32_t)USART_CR1_WAKE) /*!< UART wake-up on address mark */ /** * @} */ /** @defgroup UART_IT UART IT * Elements values convention: 000000000XXYYYYYb * - YYYYY : Interrupt source position in the XX register (5bits) * - XX : Interrupt source register (2bits) * - 01: CR1 register * - 10: CR2 register * - 11: CR3 register * @{ */ #define UART_IT_ERR ((uint16_t)0x0060) /** Elements values convention: 0000ZZZZ00000000b * - ZZZZ : Flag position in the ISR register(4bits) */ #define UART_IT_ORE ((uint16_t)0x0300) #define UART_IT_NE ((uint16_t)0x0200) #define UART_IT_FE ((uint16_t)0x0100) /** * @} */ /** @defgroup UART_Advanced_Features_Initialization_Type UART Advanced Feature Initialization Type * @{ */ #define UART_ADVFEATURE_NO_INIT ((uint32_t)0x00000000) /*!< No advanced feature initialization */ #define UART_ADVFEATURE_TXINVERT_INIT ((uint32_t)0x00000001) /*!< TX pin active level inversion */ #define UART_ADVFEATURE_RXINVERT_INIT ((uint32_t)0x00000002) /*!< RX pin active level inversion */ #define UART_ADVFEATURE_DATAINVERT_INIT ((uint32_t)0x00000004) /*!< Binary data inversion */ #define UART_ADVFEATURE_SWAP_INIT ((uint32_t)0x00000008) /*!< TX/RX pins swap */ #define UART_ADVFEATURE_RXOVERRUNDISABLE_INIT ((uint32_t)0x00000010) /*!< RX overrun disable */ #define UART_ADVFEATURE_DMADISABLEONERROR_INIT ((uint32_t)0x00000020) /*!< DMA disable on Reception Error */ #define UART_ADVFEATURE_AUTOBAUDRATE_INIT ((uint32_t)0x00000040) /*!< Auto Baud rate detection initialization */ #define UART_ADVFEATURE_MSBFIRST_INIT ((uint32_t)0x00000080) /*!< Most significant bit sent/received first */ /** * @} */ /** @defgroup UART_Tx_Inv UART Advanced Feature TX Pin Active Level Inversion * @{ */ #define UART_ADVFEATURE_TXINV_DISABLE ((uint32_t)0x00000000) /*!< TX pin active level inversion disable */ #define UART_ADVFEATURE_TXINV_ENABLE ((uint32_t)USART_CR2_TXINV) /*!< TX pin active level inversion enable */ /** * @} */ /** @defgroup UART_Rx_Inv UART Advanced Feature RX Pin Active Level Inversion * @{ */ #define UART_ADVFEATURE_RXINV_DISABLE ((uint32_t)0x00000000) /*!< RX pin active level inversion disable */ #define UART_ADVFEATURE_RXINV_ENABLE ((uint32_t)USART_CR2_RXINV) /*!< RX pin active level inversion enable */ /** * @} */ /** @defgroup UART_Data_Inv UART Advanced Feature Binary Data Inversion * @{ */ #define UART_ADVFEATURE_DATAINV_DISABLE ((uint32_t)0x00000000) /*!< Binary data inversion disable */ #define UART_ADVFEATURE_DATAINV_ENABLE ((uint32_t)USART_CR2_DATAINV) /*!< Binary data inversion enable */ /** * @} */ /** @defgroup UART_Rx_Tx_Swap UART Advanced Feature RX TX Pins Swap * @{ */ #define UART_ADVFEATURE_SWAP_DISABLE ((uint32_t)0x00000000) /*!< TX/RX pins swap disable */ #define UART_ADVFEATURE_SWAP_ENABLE ((uint32_t)USART_CR2_SWAP) /*!< TX/RX pins swap enable */ /** * @} */ /** @defgroup UART_Overrun_Disable UART Advanced Feature Overrun Disable * @{ */ #define UART_ADVFEATURE_OVERRUN_ENABLE ((uint32_t)0x00000000) /*!< RX overrun enable */ #define UART_ADVFEATURE_OVERRUN_DISABLE ((uint32_t)USART_CR3_OVRDIS) /*!< RX overrun disable */ /** * @} */ /** @defgroup UART_AutoBaudRate_Enable UART Advanced Feature Auto BaudRate Enable * @{ */ #define UART_ADVFEATURE_AUTOBAUDRATE_DISABLE ((uint32_t)0x00000000) /*!< RX Auto Baud rate detection enable */ #define UART_ADVFEATURE_AUTOBAUDRATE_ENABLE ((uint32_t)USART_CR2_ABREN) /*!< RX Auto Baud rate detection disable */ /** * @} */ /** @defgroup UART_DMA_Disable_on_Rx_Error UART Advanced Feature DMA Disable On Rx Error * @{ */ #define UART_ADVFEATURE_DMA_ENABLEONRXERROR ((uint32_t)0x00000000) /*!< DMA enable on Reception Error */ #define UART_ADVFEATURE_DMA_DISABLEONRXERROR ((uint32_t)USART_CR3_DDRE) /*!< DMA disable on Reception Error */ /** * @} */ /** @defgroup UART_MSB_First UART Advanced Feature MSB First * @{ */ #define UART_ADVFEATURE_MSBFIRST_DISABLE ((uint32_t)0x00000000) /*!< Most significant bit sent/received first disable */ #define UART_ADVFEATURE_MSBFIRST_ENABLE ((uint32_t)USART_CR2_MSBFIRST) /*!< Most significant bit sent/received first enable */ /** * @} */ /** @defgroup UART_Mute_Mode UART Advanced Feature Mute Mode Enable * @{ */ #define UART_ADVFEATURE_MUTEMODE_DISABLE ((uint32_t)0x00000000) /*!< UART mute mode disable */ #define UART_ADVFEATURE_MUTEMODE_ENABLE ((uint32_t)USART_CR1_MME) /*!< UART mute mode enable */ /** * @} */ /** @defgroup UART_CR2_ADDRESS_LSB_POS UART Address-matching LSB Position In CR2 Register * @{ */ #define UART_CR2_ADDRESS_LSB_POS ((uint32_t) 24) /** * @} */ /** @defgroup UART_DriverEnable_Polarity UART DriverEnable Polarity * @{ */ #define UART_DE_POLARITY_HIGH ((uint32_t)0x00000000) /*!< Driver enable signal is active high */ #define UART_DE_POLARITY_LOW ((uint32_t)USART_CR3_DEP) /*!< Driver enable signal is active low */ /** * @} */ /** @defgroup UART_CR1_DEAT_ADDRESS_LSB_POS UART Driver Enable Assertion Time LSB Position In CR1 Register * @{ */ #define UART_CR1_DEAT_ADDRESS_LSB_POS ((uint32_t) 21) /** * @} */ /** @defgroup UART_CR1_DEDT_ADDRESS_LSB_POS UART Driver Enable DeAssertion Time LSB Position In CR1 Register * @{ */ #define UART_CR1_DEDT_ADDRESS_LSB_POS ((uint32_t) 16) /** * @} */ /** @defgroup UART_Interruption_Mask UART Interruptions Flag Mask * @{ */ #define UART_IT_MASK ((uint32_t)0x001F) /** * @} */ /** @defgroup UART_TimeOut_Value UART polling-based communications time-out value * @{ */ #define HAL_UART_TIMEOUT_VALUE 0x1FFFFFF /** * @} */ /** * @} */ /* Exported macros -----------------------------------------------------------*/ /** @defgroup UART_Exported_Macros UART Exported Macros * @{ */ /** @brief Reset UART handle state. * @param __HANDLE__: UART handle. * @retval None */ #define __HAL_UART_RESET_HANDLE_STATE(__HANDLE__) ((__HANDLE__)->State = HAL_UART_STATE_RESET) /** @brief Clear the specified UART pending flag. * @param __HANDLE__: specifies the UART Handle. * @param __FLAG__: specifies the flag to check. * This parameter can be any combination of the following values: * @arg UART_CLEAR_PEF, Parity Error Clear Flag * @arg UART_CLEAR_FEF, Framing Error Clear Flag * @arg UART_CLEAR_NEF, Noise detected Clear Flag * @arg UART_CLEAR_OREF, OverRun Error Clear Flag * @arg UART_CLEAR_IDLEF, IDLE line detected Clear Flag * @arg UART_CLEAR_TCF, Transmission Complete Clear Flag * @arg UART_CLEAR_LBDF, LIN Break Detection Clear Flag (not available on all devices) * @arg UART_CLEAR_CTSF, CTS Interrupt Clear Flag * @arg UART_CLEAR_RTOF, Receiver Time Out Clear Flag * @arg UART_CLEAR_EOBF, End Of Block Clear Flag (not available on all devices) * @arg UART_CLEAR_CMF, Character Match Clear Flag * @arg UART_CLEAR_WUF, Wake Up from stop mode Clear Flag (not available on all devices) * @retval None */ #define __HAL_UART_CLEAR_FLAG(__HANDLE__, __FLAG__) ((__HANDLE__)->Instance->ICR = (__FLAG__)) /** @brief Clear the UART PE pending flag. * @param __HANDLE__: specifies the UART Handle. * @retval None */ #define __HAL_UART_CLEAR_PEFLAG(__HANDLE__) __HAL_UART_CLEAR_FLAG((__HANDLE__), UART_CLEAR_PEF) /** @brief Clear the UART FE pending flag. * @param __HANDLE__: specifies the UART Handle. * @retval None */ #define __HAL_UART_CLEAR_FEFLAG(__HANDLE__) __HAL_UART_CLEAR_FLAG((__HANDLE__), UART_CLEAR_FEF) /** @brief Clear the UART NE pending flag. * @param __HANDLE__: specifies the UART Handle. * @retval None */ #define __HAL_UART_CLEAR_NEFLAG(__HANDLE__) __HAL_UART_CLEAR_FLAG((__HANDLE__), UART_CLEAR_NEF) /** @brief Clear the UART ORE pending flag. * @param __HANDLE__: specifies the UART Handle. * @retval None */ #define __HAL_UART_CLEAR_OREFLAG(__HANDLE__) __HAL_UART_CLEAR_FLAG((__HANDLE__), UART_CLEAR_OREF) /** @brief Clear the UART IDLE pending flag. * @param __HANDLE__: specifies the UART Handle. * @retval None */ #define __HAL_UART_CLEAR_IDLEFLAG(__HANDLE__) __HAL_UART_CLEAR_FLAG((__HANDLE__), UART_CLEAR_IDLEF) /** @brief Check whether the specified UART flag is set or not. * @param __HANDLE__: specifies the UART Handle. * This parameter can be UARTx where x: 1, 2, 3 or 4 to select the USART or * UART peripheral (datasheet: up to four USART/UARTs) * @param __FLAG__: specifies the flag to check. * This parameter can be one of the following values: * @arg UART_FLAG_REACK: Receive enable acknowledge flag * @arg UART_FLAG_TEACK: Transmit enable acknowledge flag * @arg UART_FLAG_WUF: Wake up from stop mode flag (not available on F030xx devices) * @arg UART_FLAG_RWU: Receiver wake up flag (not available on F030xx devices) * @arg UART_FLAG_SBKF: Send Break flag * @arg UART_FLAG_CMF: Character match flag * @arg UART_FLAG_BUSY: Busy flag * @arg UART_FLAG_ABRF: Auto Baud rate detection flag * @arg UART_FLAG_ABRE: Auto Baud rate detection error flag * @arg UART_FLAG_EOBF: End of block flag (not available on F030xx devices) * @arg UART_FLAG_RTOF: Receiver timeout flag * @arg UART_FLAG_CTS: CTS Change flag * @arg UART_FLAG_LBD: LIN Break detection flag (not available on F030xx devices) * @arg UART_FLAG_TXE: Transmit data register empty flag * @arg UART_FLAG_TC: Transmission Complete flag * @arg UART_FLAG_RXNE: Receive data register not empty flag * @arg UART_FLAG_IDLE: Idle Line detection flag * @arg UART_FLAG_ORE: OverRun Error flag * @arg UART_FLAG_NE: Noise Error flag * @arg UART_FLAG_FE: Framing Error flag * @arg UART_FLAG_PE: Parity Error flag * @retval The new state of __FLAG__ (TRUE or FALSE). */ #define __HAL_UART_GET_FLAG(__HANDLE__, __FLAG__) (((__HANDLE__)->Instance->ISR & (__FLAG__)) == (__FLAG__)) /** @brief Enable the specified UART interrupt. * @param __HANDLE__: specifies the UART Handle. * This parameter can be UARTx where x: 1, 2, 3 or 4 to select the USART or * UART peripheral. (datasheet: up to four USART/UARTs) * @param __INTERRUPT__: specifies the UART interrupt source to enable. * This parameter can be one of the following values: * @arg UART_IT_WUF: Wakeup from stop mode interrupt (not available on F030xx devices) * @arg UART_IT_CM: Character match interrupt * @arg UART_IT_CTS: CTS change interrupt * @arg UART_IT_LBD: LIN Break detection interrupt (not available on F030xx devices) * @arg UART_IT_TXE: Transmit Data Register empty interrupt * @arg UART_IT_TC: Transmission complete interrupt * @arg UART_IT_RXNE: Receive Data register not empty interrupt * @arg UART_IT_IDLE: Idle line detection interrupt * @arg UART_IT_PE: Parity Error interrupt * @arg UART_IT_ERR: Error interrupt(Frame error, noise error, overrun error) * @retval None */ #define __HAL_UART_ENABLE_IT(__HANDLE__, __INTERRUPT__) (((((uint8_t)(__INTERRUPT__)) >> 5U) == 1)? ((__HANDLE__)->Instance->CR1 |= (1U << ((__INTERRUPT__) & UART_IT_MASK))): \ ((((uint8_t)(__INTERRUPT__)) >> 5U) == 2)? ((__HANDLE__)->Instance->CR2 |= (1U << ((__INTERRUPT__) & UART_IT_MASK))): \ ((__HANDLE__)->Instance->CR3 |= (1U << ((__INTERRUPT__) & UART_IT_MASK)))) /** @brief Disable the specified UART interrupt. * @param __HANDLE__: specifies the UART Handle. * This parameter can be UARTx where x: 1, 2, 3 or 4 to select the USART or * UART peripheral. (datasheet: up to four USART/UARTs) * @param __INTERRUPT__: specifies the UART interrupt source to disable. * This parameter can be one of the following values: * @arg UART_IT_WUF: Wakeup from stop mode interrupt (not available on F030xx devices) * @arg UART_IT_CM: Character match interrupt * @arg UART_IT_CTS: CTS change interrupt * @arg UART_IT_LBD: LIN Break detection interrupt (not available on F030xx devices) * @arg UART_IT_TXE: Transmit Data Register empty interrupt * @arg UART_IT_TC: Transmission complete interrupt * @arg UART_IT_RXNE: Receive Data register not empty interrupt * @arg UART_IT_IDLE: Idle line detection interrupt * @arg UART_IT_PE: Parity Error interrupt * @arg UART_IT_ERR: Error interrupt (Frame error, noise error, overrun error) * @retval None */ #define __HAL_UART_DISABLE_IT(__HANDLE__, __INTERRUPT__) (((((uint8_t)(__INTERRUPT__)) >> 5U) == 1)? ((__HANDLE__)->Instance->CR1 &= ~ (1U << ((__INTERRUPT__) & UART_IT_MASK))): \ ((((uint8_t)(__INTERRUPT__)) >> 5U) == 2)? ((__HANDLE__)->Instance->CR2 &= ~ (1U << ((__INTERRUPT__) & UART_IT_MASK))): \ ((__HANDLE__)->Instance->CR3 &= ~ (1U << ((__INTERRUPT__) & UART_IT_MASK)))) /** @brief Check whether the specified UART interrupt has occurred or not. * @param __HANDLE__: specifies the UART Handle. * This parameter can be UARTx where x: 1, 2, 3 or 4 to select the USART or * UART peripheral. (datasheet: up to four USART/UARTs) * @param __IT__: specifies the UART interrupt to check. * This parameter can be one of the following values: * @arg UART_IT_WUF: Wakeup from stop mode interrupt (not available on F030xx devices) * @arg UART_IT_CM: Character match interrupt * @arg UART_IT_CTS: CTS change interrupt * @arg UART_IT_LBD: LIN Break detection interrupt (not available on F030xx devices) * @arg UART_IT_TXE: Transmit Data Register empty interrupt * @arg UART_IT_TC: Transmission complete interrupt * @arg UART_IT_RXNE: Receive Data register not empty interrupt * @arg UART_IT_IDLE: Idle line detection interrupt * @arg UART_IT_ORE: OverRun Error interrupt * @arg UART_IT_NE: Noise Error interrupt * @arg UART_IT_FE: Framing Error interrupt * @arg UART_IT_PE: Parity Error interrupt * @retval The new state of __IT__ (TRUE or FALSE). */ #define __HAL_UART_GET_IT(__HANDLE__, __IT__) ((__HANDLE__)->Instance->ISR & ((uint32_t)1 << ((__IT__)>> 0x08))) /** @brief Check whether the specified UART interrupt source is enabled or not. * @param __HANDLE__: specifies the UART Handle. * This parameter can be UARTx where x: 1, 2, 3 or 4 to select the USART or * UART peripheral. (datasheet: up to four USART/UARTs) * @param __IT__: specifies the UART interrupt source to check. * This parameter can be one of the following values: * @arg UART_IT_WUF: Wakeup from stop mode interrupt (not available on F030xx devices) * @arg UART_IT_CM: Character match interrupt * @arg UART_IT_CTS: CTS change interrupt * @arg UART_IT_LBD: LIN Break detection interrupt (not available on F030xx devices) * @arg UART_IT_TXE: Transmit Data Register empty interrupt * @arg UART_IT_TC: Transmission complete interrupt * @arg UART_IT_RXNE: Receive Data register not empty interrupt * @arg UART_IT_IDLE: Idle line detection interrupt * @arg UART_IT_ORE: OverRun Error interrupt * @arg UART_IT_NE: Noise Error interrupt * @arg UART_IT_FE: Framing Error interrupt * @arg UART_IT_PE: Parity Error interrupt * @retval The new state of __IT__ (TRUE or FALSE). */ #define __HAL_UART_GET_IT_SOURCE(__HANDLE__, __IT__) ((((((uint8_t)(__IT__)) >> 5U) == 1)? (__HANDLE__)->Instance->CR1:(((((uint8_t)(__IT__)) >> 5U) == 2)? \ (__HANDLE__)->Instance->CR2 : (__HANDLE__)->Instance->CR3)) & ((uint32_t)1 << (((uint16_t)(__IT__)) & UART_IT_MASK))) /** @brief Clear the specified UART ISR flag, in setting the proper ICR register flag. * @param __HANDLE__: specifies the UART Handle. * This parameter can be UARTx where x: 1, 2, 3 or 4 to select the USART or * UART peripheral. (datasheet: up to four USART/UARTs) * @param __IT_CLEAR__: specifies the interrupt clear register flag that needs to be set * to clear the corresponding interrupt * This parameter can be one of the following values: * @arg UART_CLEAR_PEF: Parity Error Clear Flag * @arg UART_CLEAR_FEF: Framing Error Clear Flag * @arg UART_CLEAR_NEF: Noise detected Clear Flag * @arg UART_CLEAR_OREF: OverRun Error Clear Flag * @arg UART_CLEAR_IDLEF: IDLE line detected Clear Flag * @arg UART_CLEAR_TCF: Transmission Complete Clear Flag * @arg UART_CLEAR_LBDF: LIN Break Detection Clear Flag (not available on F030xx devices) * @arg UART_CLEAR_CTSF: CTS Interrupt Clear Flag * @arg UART_CLEAR_RTOF: Receiver Time Out Clear Flag * @arg UART_CLEAR_EOBF: End Of Block Clear Flag (not available on F030xx devices) * @arg UART_CLEAR_CMF: Character Match Clear Flag * @arg UART_CLEAR_WUF: Wake Up from stop mode Clear Flag (not available on F030xx devices) * @retval None */ #define __HAL_UART_CLEAR_IT(__HANDLE__, __IT_CLEAR__) ((__HANDLE__)->Instance->ICR = (uint32_t)(__IT_CLEAR__)) /** @brief Set a specific UART request flag. * @param __HANDLE__: specifies the UART Handle. * This parameter can be UARTx where x: 1, 2, 3 or 4 to select the USART or * UART peripheral. (datasheet: up to four USART/UARTs) * @param __REQ__: specifies the request flag to set * This parameter can be one of the following values: * @arg UART_AUTOBAUD_REQUEST: Auto-Baud Rate Request * @arg UART_SENDBREAK_REQUEST: Send Break Request * @arg UART_MUTE_MODE_REQUEST: Mute Mode Request * @arg UART_RXDATA_FLUSH_REQUEST: Receive Data flush Request * @arg UART_TXDATA_FLUSH_REQUEST: Transmit data flush Request (not available on F030xx devices) * @retval None */ #define __HAL_UART_SEND_REQ(__HANDLE__, __REQ__) ((__HANDLE__)->Instance->RQR |= (uint16_t)(__REQ__)) /** @brief Enable the UART one bit sample method. * @param __HANDLE__: specifies the UART Handle. * @retval None */ #define __HAL_UART_ONE_BIT_SAMPLE_ENABLE(__HANDLE__) ((__HANDLE__)->Instance->CR3|= USART_CR3_ONEBIT) /** @brief Disable the UART one bit sample method. * @param __HANDLE__: specifies the UART Handle. * @retval None */ #define __HAL_UART_ONE_BIT_SAMPLE_DISABLE(__HANDLE__) ((__HANDLE__)->Instance->CR3 &= (uint32_t)~((uint32_t)USART_CR3_ONEBIT)) /** @brief Enable UART. * @param __HANDLE__: specifies the UART Handle. * The Handle Instance can be UARTx where x: 1, 2, 3, 4 or 5 to select the UART peripheral * @retval None */ #define __HAL_UART_ENABLE(__HANDLE__) ((__HANDLE__)->Instance->CR1 |= USART_CR1_UE) /** @brief Disable UART. * @param __HANDLE__: specifies the UART Handle. * The Handle Instance can be UARTx where x: 1, 2, 3, 4 or 5 to select the UART peripheral * @retval None */ #define __HAL_UART_DISABLE(__HANDLE__) ((__HANDLE__)->Instance->CR1 &= ~USART_CR1_UE) /** @brief Enable CTS flow control. * @note This macro allows to enable CTS hardware flow control for a given UART instance, * without need to call HAL_UART_Init() function. * As involving direct access to UART registers, usage of this macro should be fully endorsed by user. * @note As macro is expected to be used for modifying CTS Hw flow control feature activation, without need * for USART instance Deinit/Init, following conditions for macro call should be fulfilled : * - UART instance should have already been initialised (through call of HAL_UART_Init() ) * - macro could only be called when corresponding UART instance is disabled (i.e. __HAL_UART_DISABLE(__HANDLE__)) * and should be followed by an Enable macro (i.e. __HAL_UART_ENABLE(__HANDLE__)). * @param __HANDLE__: specifies the UART Handle. * @retval None */ #define __HAL_UART_HWCONTROL_CTS_ENABLE(__HANDLE__) \ do{ \ SET_BIT((__HANDLE__)->Instance->CR3, USART_CR3_CTSE); \ (__HANDLE__)->Init.HwFlowCtl |= USART_CR3_CTSE; \ } while(0) /** @brief Disable CTS flow control. * @note This macro allows to disable CTS hardware flow control for a given UART instance, * without need to call HAL_UART_Init() function. * As involving direct access to UART registers, usage of this macro should be fully endorsed by user. * @note As macro is expected to be used for modifying CTS Hw flow control feature activation, without need * for USART instance Deinit/Init, following conditions for macro call should be fulfilled : * - UART instance should have already been initialised (through call of HAL_UART_Init() ) * - macro could only be called when corresponding UART instance is disabled (i.e. __HAL_UART_DISABLE(__HANDLE__)) * and should be followed by an Enable macro (i.e. __HAL_UART_ENABLE(__HANDLE__)). * @param __HANDLE__: specifies the UART Handle. * @retval None */ #define __HAL_UART_HWCONTROL_CTS_DISABLE(__HANDLE__) \ do{ \ CLEAR_BIT((__HANDLE__)->Instance->CR3, USART_CR3_CTSE); \ (__HANDLE__)->Init.HwFlowCtl &= ~(USART_CR3_CTSE); \ } while(0) /** @brief Enable RTS flow control. * @note This macro allows to enable RTS hardware flow control for a given UART instance, * without need to call HAL_UART_Init() function. * As involving direct access to UART registers, usage of this macro should be fully endorsed by user. * @note As macro is expected to be used for modifying RTS Hw flow control feature activation, without need * for USART instance Deinit/Init, following conditions for macro call should be fulfilled : * - UART instance should have already been initialised (through call of HAL_UART_Init() ) * - macro could only be called when corresponding UART instance is disabled (i.e. __HAL_UART_DISABLE(__HANDLE__)) * and should be followed by an Enable macro (i.e. __HAL_UART_ENABLE(__HANDLE__)). * @param __HANDLE__: specifies the UART Handle. * @retval None */ #define __HAL_UART_HWCONTROL_RTS_ENABLE(__HANDLE__) \ do{ \ SET_BIT((__HANDLE__)->Instance->CR3, USART_CR3_RTSE); \ (__HANDLE__)->Init.HwFlowCtl |= USART_CR3_RTSE; \ } while(0) /** @brief Disable RTS flow control. * @note This macro allows to disable RTS hardware flow control for a given UART instance, * without need to call HAL_UART_Init() function. * As involving direct access to UART registers, usage of this macro should be fully endorsed by user. * @note As macro is expected to be used for modifying RTS Hw flow control feature activation, without need * for USART instance Deinit/Init, following conditions for macro call should be fulfilled : * - UART instance should have already been initialised (through call of HAL_UART_Init() ) * - macro could only be called when corresponding UART instance is disabled (i.e. __HAL_UART_DISABLE(__HANDLE__)) * and should be followed by an Enable macro (i.e. __HAL_UART_ENABLE(__HANDLE__)). * @param __HANDLE__: specifies the UART Handle. * @retval None */ #define __HAL_UART_HWCONTROL_RTS_DISABLE(__HANDLE__) \ do{ \ CLEAR_BIT((__HANDLE__)->Instance->CR3, USART_CR3_RTSE);\ (__HANDLE__)->Init.HwFlowCtl &= ~(USART_CR3_RTSE); \ } while(0) /** * @} */ /* Private macros --------------------------------------------------------*/ /** @defgroup UART_Private_Macros UART Private Macros * @{ */ /** @brief BRR division operation to set BRR register in 8-bit oversampling mode. * @param __PCLK__: UART clock. * @param __BAUD__: Baud rate set by the user. * @retval Division result */ #define UART_DIV_SAMPLING8(__PCLK__, __BAUD__) (((__PCLK__)*2)/((__BAUD__))) /** @brief BRR division operation to set BRR register in 16-bit oversampling mode. * @param __PCLK__: UART clock. * @param __BAUD__: Baud rate set by the user. * @retval Division result */ #define UART_DIV_SAMPLING16(__PCLK__, __BAUD__) (((__PCLK__))/((__BAUD__))) /** @brief Check UART Baud rate * @param __BAUDRATE__: Baudrate specified by the user. * The maximum Baud Rate is derived from the maximum clock on F0 (i.e. 48 MHz) * divided by the smallest oversampling used on the USART (i.e. 8) * @retval SET (__BAUDRATE__ is valid) or RESET (__BAUDRATE__ is invalid) */ #define IS_UART_BAUDRATE(__BAUDRATE__) ((__BAUDRATE__) < 9000001) /** @brief Check UART assertion time. * @param __TIME__: 5-bit value assertion time. * @retval Test result (TRUE or FALSE). */ #define IS_UART_ASSERTIONTIME(__TIME__) ((__TIME__) <= 0x1F) /** @brief Check UART deassertion time. * @param __TIME__: 5-bit value deassertion time. * @retval Test result (TRUE or FALSE). */ #define IS_UART_DEASSERTIONTIME(__TIME__) ((__TIME__) <= 0x1F) /** * @brief Ensure that UART frame number of stop bits is valid. * @param __STOPBITS__: UART frame number of stop bits. * @retval SET (__STOPBITS__ is valid) or RESET (__STOPBITS__ is invalid) UART_STOPBITS_1_5 */ #define IS_UART_STOPBITS(__STOPBITS__) (((__STOPBITS__) == UART_STOPBITS_1) || \ ((__STOPBITS__) == UART_STOPBITS_2) || \ ((__STOPBITS__) == UART_STOPBITS_1_5)) /** * @brief Ensure that UART frame parity is valid. * @param __PARITY__: UART frame parity. * @retval SET (__PARITY__ is valid) or RESET (__PARITY__ is invalid) */ #define IS_UART_PARITY(__PARITY__) (((__PARITY__) == UART_PARITY_NONE) || \ ((__PARITY__) == UART_PARITY_EVEN) || \ ((__PARITY__) == UART_PARITY_ODD)) /** * @brief Ensure that UART hardware flow control is valid. * @param __CONTROL__: UART hardware flow control. * @retval SET (__CONTROL__ is valid) or RESET (__CONTROL__ is invalid) */ #define IS_UART_HARDWARE_FLOW_CONTROL(__CONTROL__)\ (((__CONTROL__) == UART_HWCONTROL_NONE) || \ ((__CONTROL__) == UART_HWCONTROL_RTS) || \ ((__CONTROL__) == UART_HWCONTROL_CTS) || \ ((__CONTROL__) == UART_HWCONTROL_RTS_CTS)) /** * @brief Ensure that UART communication mode is valid. * @param __MODE__: UART communication mode. * @retval SET (__MODE__ is valid) or RESET (__MODE__ is invalid) */ #define IS_UART_MODE(__MODE__) ((((__MODE__) & (~((uint32_t)(UART_MODE_TX_RX)))) == (uint32_t)0x00) && ((__MODE__) != (uint32_t)0x00)) /** * @brief Ensure that UART state is valid. * @param __STATE__: UART state. * @retval SET (__STATE__ is valid) or RESET (__STATE__ is invalid) */ #define IS_UART_STATE(__STATE__) (((__STATE__) == UART_STATE_DISABLE) || \ ((__STATE__) == UART_STATE_ENABLE)) /** * @brief Ensure that UART oversampling is valid. * @param __SAMPLING__: UART oversampling. * @retval SET (__SAMPLING__ is valid) or RESET (__SAMPLING__ is invalid) */ #define IS_UART_OVERSAMPLING(__SAMPLING__) (((__SAMPLING__) == UART_OVERSAMPLING_16) || \ ((__SAMPLING__) == UART_OVERSAMPLING_8)) /** * @brief Ensure that UART frame sampling is valid. * @param __ONEBIT__: UART frame sampling. * @retval SET (__ONEBIT__ is valid) or RESET (__ONEBIT__ is invalid) */ #define IS_UART_ONE_BIT_SAMPLE(__ONEBIT__) (((__ONEBIT__) == UART_ONE_BIT_SAMPLE_DISABLE) || \ ((__ONEBIT__) == UART_ONE_BIT_SAMPLE_ENABLE)) /** * @brief Ensure that Address Length detection parameter is valid. * @param __ADDRESS__: UART Adress length value. * @retval SET (__ADDRESS__ is valid) or RESET (__ADDRESS__ is invalid) */ #define IS_UART_ADDRESSLENGTH_DETECT(__ADDRESS__) (((__ADDRESS__) == UART_ADDRESS_DETECT_4B) || \ ((__ADDRESS__) == UART_ADDRESS_DETECT_7B)) /** * @brief Ensure that UART receiver timeout setting is valid. * @param __TIMEOUT__: UART receiver timeout setting. * @retval SET (__TIMEOUT__ is valid) or RESET (__TIMEOUT__ is invalid) */ #define IS_UART_RECEIVER_TIMEOUT(__TIMEOUT__) (((__TIMEOUT__) == UART_RECEIVER_TIMEOUT_DISABLE) || \ ((__TIMEOUT__) == UART_RECEIVER_TIMEOUT_ENABLE)) /** * @brief Ensure that UART DMA TX state is valid. * @param __DMATX__: UART DMA TX state. * @retval SET (__DMATX__ is valid) or RESET (__DMATX__ is invalid) */ #define IS_UART_DMA_TX(__DMATX__) (((__DMATX__) == UART_DMA_TX_DISABLE) || \ ((__DMATX__) == UART_DMA_TX_ENABLE)) /** * @brief Ensure that UART DMA RX state is valid. * @param __DMARX__: UART DMA RX state. * @retval SET (__DMARX__ is valid) or RESET (__DMARX__ is invalid) */ #define IS_UART_DMA_RX(__DMARX__) (((__DMARX__) == UART_DMA_RX_DISABLE) || \ ((__DMARX__) == UART_DMA_RX_ENABLE)) /** * @brief Ensure that UART half-duplex state is valid. * @param __HDSEL__: UART half-duplex state. * @retval SET (__HDSEL__ is valid) or RESET (__HDSEL__ is invalid) */ #define IS_UART_HALF_DUPLEX(__HDSEL__) (((__HDSEL__) == UART_HALF_DUPLEX_DISABLE) || \ ((__HDSEL__) == UART_HALF_DUPLEX_ENABLE)) /** * @brief Ensure that UART wake-up method is valid. * @param __WAKEUP__: UART wake-up method . * @retval SET (__WAKEUP__ is valid) or RESET (__WAKEUP__ is invalid) */ #define IS_UART_WAKEUPMETHOD(__WAKEUP__) (((__WAKEUP__) == UART_WAKEUPMETHOD_IDLELINE) || \ ((__WAKEUP__) == UART_WAKEUPMETHOD_ADDRESSMARK)) /** * @brief Ensure that UART advanced features initialization is valid. * @param __INIT__: UART advanced features initialization. * @retval SET (__INIT__ is valid) or RESET (__INIT__ is invalid) */ #define IS_UART_ADVFEATURE_INIT(__INIT__) ((__INIT__) <= (UART_ADVFEATURE_NO_INIT | \ UART_ADVFEATURE_TXINVERT_INIT | \ UART_ADVFEATURE_RXINVERT_INIT | \ UART_ADVFEATURE_DATAINVERT_INIT | \ UART_ADVFEATURE_SWAP_INIT | \ UART_ADVFEATURE_RXOVERRUNDISABLE_INIT | \ UART_ADVFEATURE_DMADISABLEONERROR_INIT | \ UART_ADVFEATURE_AUTOBAUDRATE_INIT | \ UART_ADVFEATURE_MSBFIRST_INIT)) /** * @brief Ensure that UART frame TX inversion setting is valid. * @param __TXINV__: UART frame TX inversion setting. * @retval SET (__TXINV__ is valid) or RESET (__TXINV__ is invalid) */ #define IS_UART_ADVFEATURE_TXINV(__TXINV__) (((__TXINV__) == UART_ADVFEATURE_TXINV_DISABLE) || \ ((__TXINV__) == UART_ADVFEATURE_TXINV_ENABLE)) /** * @brief Ensure that UART frame RX inversion setting is valid. * @param __RXINV__: UART frame RX inversion setting. * @retval SET (__RXINV__ is valid) or RESET (__RXINV__ is invalid) */ #define IS_UART_ADVFEATURE_RXINV(__RXINV__) (((__RXINV__) == UART_ADVFEATURE_RXINV_DISABLE) || \ ((__RXINV__) == UART_ADVFEATURE_RXINV_ENABLE)) /** * @brief Ensure that UART frame data inversion setting is valid. * @param __DATAINV__: UART frame data inversion setting. * @retval SET (__DATAINV__ is valid) or RESET (__DATAINV__ is invalid) */ #define IS_UART_ADVFEATURE_DATAINV(__DATAINV__) (((__DATAINV__) == UART_ADVFEATURE_DATAINV_DISABLE) || \ ((__DATAINV__) == UART_ADVFEATURE_DATAINV_ENABLE)) /** * @brief Ensure that UART frame RX/TX pins swap setting is valid. * @param __SWAP__: UART frame RX/TX pins swap setting. * @retval SET (__SWAP__ is valid) or RESET (__SWAP__ is invalid) */ #define IS_UART_ADVFEATURE_SWAP(__SWAP__) (((__SWAP__) == UART_ADVFEATURE_SWAP_DISABLE) || \ ((__SWAP__) == UART_ADVFEATURE_SWAP_ENABLE)) /** * @brief Ensure that UART frame overrun setting is valid. * @param __OVERRUN__: UART frame overrun setting. * @retval SET (__OVERRUN__ is valid) or RESET (__OVERRUN__ is invalid) */ #define IS_UART_OVERRUN(__OVERRUN__) (((__OVERRUN__) == UART_ADVFEATURE_OVERRUN_ENABLE) || \ ((__OVERRUN__) == UART_ADVFEATURE_OVERRUN_DISABLE)) /** * @brief Ensure that UART auto Baud rate state is valid. * @param __AUTOBAUDRATE__: UART auto Baud rate state. * @retval SET (__AUTOBAUDRATE__ is valid) or RESET (__AUTOBAUDRATE__ is invalid) */ #define IS_UART_ADVFEATURE_AUTOBAUDRATE(__AUTOBAUDRATE__) (((__AUTOBAUDRATE__) == UART_ADVFEATURE_AUTOBAUDRATE_DISABLE) || \ ((__AUTOBAUDRATE__) == UART_ADVFEATURE_AUTOBAUDRATE_ENABLE)) /** * @brief Ensure that UART DMA enabling or disabling on error setting is valid. * @param __DMA__: UART DMA enabling or disabling on error setting. * @retval SET (__DMA__ is valid) or RESET (__DMA__ is invalid) */ #define IS_UART_ADVFEATURE_DMAONRXERROR(__DMA__) (((__DMA__) == UART_ADVFEATURE_DMA_ENABLEONRXERROR) || \ ((__DMA__) == UART_ADVFEATURE_DMA_DISABLEONRXERROR)) /** * @brief Ensure that UART frame MSB first setting is valid. * @param __MSBFIRST__: UART frame MSB first setting. * @retval SET (__MSBFIRST__ is valid) or RESET (__MSBFIRST__ is invalid) */ #define IS_UART_ADVFEATURE_MSBFIRST(__MSBFIRST__) (((__MSBFIRST__) == UART_ADVFEATURE_MSBFIRST_DISABLE) || \ ((__MSBFIRST__) == UART_ADVFEATURE_MSBFIRST_ENABLE)) /** * @brief Ensure that UART mute mode state is valid. * @param __MUTE__: UART mute mode state. * @retval SET (__MUTE__ is valid) or RESET (__MUTE__ is invalid) */ #define IS_UART_MUTE_MODE(__MUTE__) (((__MUTE__) == UART_ADVFEATURE_MUTEMODE_DISABLE) || \ ((__MUTE__) == UART_ADVFEATURE_MUTEMODE_ENABLE)) /** * @brief Ensure that UART driver enable polarity is valid. * @param __POLARITY__: UART driver enable polarity. * @retval SET (__POLARITY__ is valid) or RESET (__POLARITY__ is invalid) */ #define IS_UART_DE_POLARITY(__POLARITY__) (((__POLARITY__) == UART_DE_POLARITY_HIGH) || \ ((__POLARITY__) == UART_DE_POLARITY_LOW)) /** * @} */ /* Include UART HAL Extension module */ #include "stm32f0xx_hal_uart_ex.h" /* Exported functions --------------------------------------------------------*/ /** @addtogroup UART_Exported_Functions UART Exported Functions * @{ */ /** @addtogroup UART_Exported_Functions_Group1 Initialization and de-initialization functions * @{ */ /* Initialization and de-initialization functions ****************************/ HAL_StatusTypeDef HAL_UART_Init(UART_HandleTypeDef *huart); HAL_StatusTypeDef HAL_HalfDuplex_Init(UART_HandleTypeDef *huart); HAL_StatusTypeDef HAL_MultiProcessor_Init(UART_HandleTypeDef *huart, uint8_t Address, uint32_t WakeUpMethod); HAL_StatusTypeDef HAL_UART_DeInit (UART_HandleTypeDef *huart); void HAL_UART_MspInit(UART_HandleTypeDef *huart); void HAL_UART_MspDeInit(UART_HandleTypeDef *huart); /** * @} */ /** @addtogroup UART_Exported_Functions_Group2 IO operation functions * @{ */ /* IO operation functions *****************************************************/ HAL_StatusTypeDef HAL_UART_Transmit(UART_HandleTypeDef *huart, uint8_t *pData, uint16_t Size, uint32_t Timeout); HAL_StatusTypeDef HAL_UART_Receive(UART_HandleTypeDef *huart, uint8_t *pData, uint16_t Size, uint32_t Timeout); HAL_StatusTypeDef HAL_UART_Transmit_IT(UART_HandleTypeDef *huart, uint8_t *pData, uint16_t Size); HAL_StatusTypeDef HAL_UART_Receive_IT(UART_HandleTypeDef *huart, uint8_t *pData, uint16_t Size); HAL_StatusTypeDef HAL_UART_Transmit_DMA(UART_HandleTypeDef *huart, uint8_t *pData, uint16_t Size); HAL_StatusTypeDef HAL_UART_Receive_DMA(UART_HandleTypeDef *huart, uint8_t *pData, uint16_t Size); HAL_StatusTypeDef HAL_UART_DMAPause(UART_HandleTypeDef *huart); HAL_StatusTypeDef HAL_UART_DMAResume(UART_HandleTypeDef *huart); HAL_StatusTypeDef HAL_UART_DMAStop(UART_HandleTypeDef *huart); void HAL_UART_IRQHandler(UART_HandleTypeDef *huart); void HAL_UART_TxCpltCallback(UART_HandleTypeDef *huart); void HAL_UART_TxHalfCpltCallback(UART_HandleTypeDef *huart); void HAL_UART_RxCpltCallback(UART_HandleTypeDef *huart); void HAL_UART_RxHalfCpltCallback(UART_HandleTypeDef *huart); void HAL_UART_ErrorCallback(UART_HandleTypeDef *huart); /** * @} */ /** @addtogroup UART_Exported_Functions_Group3 Peripheral Control functions * @{ */ /* Peripheral Control functions ************************************************/ HAL_StatusTypeDef HAL_MultiProcessor_EnableMuteMode(UART_HandleTypeDef *huart); HAL_StatusTypeDef HAL_MultiProcessor_DisableMuteMode(UART_HandleTypeDef *huart); void HAL_MultiProcessor_EnterMuteMode(UART_HandleTypeDef *huart); HAL_StatusTypeDef HAL_HalfDuplex_EnableTransmitter(UART_HandleTypeDef *huart); HAL_StatusTypeDef HAL_HalfDuplex_EnableReceiver(UART_HandleTypeDef *huart); /** * @} */ /** @addtogroup UART_Exported_Functions_Group4 Peripheral State and Error functions * @{ */ /* Peripheral State and Errors functions **************************************************/ HAL_UART_StateTypeDef HAL_UART_GetState(UART_HandleTypeDef *huart); uint32_t HAL_UART_GetError(UART_HandleTypeDef *huart); /** * @} */ /** * @} */ /* Private functions -----------------------------------------------------------*/ /** @addtogroup UART_Private_Functions * @{ */ void UART_AdvFeatureConfig(UART_HandleTypeDef *huart); HAL_StatusTypeDef UART_CheckIdleState(UART_HandleTypeDef *huart); HAL_StatusTypeDef UART_SetConfig(UART_HandleTypeDef *huart); HAL_StatusTypeDef UART_Transmit_IT(UART_HandleTypeDef *huart); HAL_StatusTypeDef UART_EndTransmit_IT(UART_HandleTypeDef *huart); HAL_StatusTypeDef UART_Receive_IT(UART_HandleTypeDef *huart); HAL_StatusTypeDef UART_WaitOnFlagUntilTimeout(UART_HandleTypeDef *huart, uint32_t Flag, FlagStatus Status, uint32_t Timeout); /** * @} */ /** * @} */ /** * @} */ #ifdef __cplusplus } #endif #endif /* __STM32F0xx_HAL_UART_H */ /************************ (C) COPYRIGHT STMicroelectronics *****END OF FILE****/ ================================================ FILE: Zelig/mbed/TARGET_NUCLEO_F091RC/stm32f0xx_hal_uart_ex.h ================================================ /** ****************************************************************************** * @file stm32f0xx_hal_uart_ex.h * @author MCD Application Team * @version V1.3.0 * @date 26-June-2015 * @brief Header file of UART HAL Extension module. ****************************************************************************** * @attention * *

© COPYRIGHT(c) 2015 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. * ****************************************************************************** */ /* Define to prevent recursive inclusion -------------------------------------*/ #ifndef __STM32F0xx_HAL_UART_EX_H #define __STM32F0xx_HAL_UART_EX_H #ifdef __cplusplus extern "C" { #endif /* Includes ------------------------------------------------------------------*/ #include "stm32f0xx_hal_def.h" /** @addtogroup STM32F0xx_HAL_Driver * @{ */ /** @addtogroup UARTEx * @{ */ /* Exported types ------------------------------------------------------------*/ #if !defined(STM32F030x6) && !defined(STM32F030x8) && !defined(STM32F070x6) && !defined(STM32F070xB) && !defined(STM32F030xC) /** @defgroup UARTEx_Exported_Types UARTEx Exported Types * @{ */ /** * @brief UART wake up from stop mode parameters */ typedef struct { uint32_t WakeUpEvent; /*!< Specifies which event will activat the Wakeup from Stop mode flag (WUF). This parameter can be a value of @ref UART_WakeUp_from_Stop_Selection. If set to UART_WAKEUP_ON_ADDRESS, the two other fields below must be filled up. */ uint16_t AddressLength; /*!< Specifies whether the address is 4 or 7-bit long. This parameter can be a value of @ref UART_WakeUp_Address_Length */ uint8_t Address; /*!< UART/USART node address (7-bit long max) */ } UART_WakeUpTypeDef; /** * @} */ #endif /* !defined(STM32F030x6) && !defined(STM32F030x8) && !defined(STM32F070x6) && !defined(STM32F070xB) && !defined(STM32F030xC) */ /* Exported constants --------------------------------------------------------*/ /** @defgroup UARTEx_Exported_Constants UARTEx Exported Constants * @{ */ /** @defgroup UARTEx_Word_Length UARTEx Word Length * @{ */ #if defined (STM32F042x6) || defined (STM32F048xx) || defined (STM32F070x6) || \ defined (STM32F071xB) || defined (STM32F072xB) || defined (STM32F078xx) || defined (STM32F070xB) || \ defined (STM32F091xC) || defined (STM32F098xx) || defined (STM32F030xC) #define UART_WORDLENGTH_7B ((uint32_t)USART_CR1_M1) #define UART_WORDLENGTH_8B ((uint32_t)0x00000000) #define UART_WORDLENGTH_9B ((uint32_t)USART_CR1_M0) #else #define UART_WORDLENGTH_8B ((uint32_t)0x00000000) #define UART_WORDLENGTH_9B ((uint32_t)USART_CR1_M) #endif /* defined (STM32F042x6) || defined (STM32F048xx) || defined (STM32F070x6) || \ defined (STM32F071xB) || defined (STM32F072xB) || defined (STM32F078xx) || defined (STM32F070xB) || \ defined (STM32F091xC) || defined (STM32F098xx) || defined (STM32F030xC) */ /** * @} */ /** @defgroup UARTEx_AutoBaud_Rate_Mode UARTEx Advanced Feature AutoBaud Rate Mode * @{ */ #if defined (STM32F042x6) || defined (STM32F048xx) || defined (STM32F070x6) || \ defined (STM32F071xB) || defined (STM32F072xB) || defined (STM32F078xx) || defined (STM32F070xB) || \ defined (STM32F091xC) || defined (STM32F098xx) || defined (STM32F030xC) #define UART_ADVFEATURE_AUTOBAUDRATE_ONSTARTBIT ((uint32_t)0x00000000) /*!< Auto Baud rate detection on start bit */ #define UART_ADVFEATURE_AUTOBAUDRATE_ONFALLINGEDGE ((uint32_t)USART_CR2_ABRMODE_0) /*!< Auto Baud rate detection on falling edge */ #define UART_ADVFEATURE_AUTOBAUDRATE_ON0X7FFRAME ((uint32_t)USART_CR2_ABRMODE_1) /*!< Auto Baud rate detection on 0x7F frame detection */ #define UART_ADVFEATURE_AUTOBAUDRATE_ON0X55FRAME ((uint32_t)USART_CR2_ABRMODE) /*!< Auto Baud rate detection on 0x55 frame detection */ #else #define UART_ADVFEATURE_AUTOBAUDRATE_ONSTARTBIT ((uint32_t)0x00000000) /*!< Auto Baud rate detection on start bit */ #define UART_ADVFEATURE_AUTOBAUDRATE_ONFALLINGEDGE ((uint32_t)USART_CR2_ABRMODE_0) /*!< Auto Baud rate detection on falling edge */ #endif /* defined (STM32F042x6) || defined (STM32F048xx) || defined (STM32F070x6) || \ defined (STM32F071xB) || defined (STM32F072xB) || defined (STM32F078xx) || defined (STM32F070xB) || \ defined (STM32F091xC) || defined (STM32F098xx) || defined (STM32F030xC) */ /** * @} */ #if !defined(STM32F030x6) && !defined(STM32F030x8) && !defined(STM32F070x6) && !defined(STM32F070xB) && !defined(STM32F030xC) /** @defgroup UARTEx_LIN UARTEx Local Interconnection Network mode * @{ */ #define UART_LIN_DISABLE ((uint32_t)0x00000000) /*!< Local Interconnect Network disable */ #define UART_LIN_ENABLE ((uint32_t)USART_CR2_LINEN) /*!< Local Interconnect Network enable */ /** * @} */ /** @defgroup UARTEx_LIN_Break_Detection UARTEx LIN Break Detection * @{ */ #define UART_LINBREAKDETECTLENGTH_10B ((uint32_t)0x00000000) /*!< LIN 10-bit break detection length */ #define UART_LINBREAKDETECTLENGTH_11B ((uint32_t)USART_CR2_LBDL) /*!< LIN 11-bit break detection length */ /** * @} */ #endif /* !defined(STM32F030x6) && !defined(STM32F030x8) && !defined(STM32F070x6) && !defined(STM32F070xB) && !defined(STM32F030xC) */ /** @defgroup UART_Flags UARTEx Status Flags * Elements values convention: 0xXXXX * - 0xXXXX : Flag mask in the ISR register * @{ */ #if !defined(STM32F030x6) && !defined(STM32F030x8) && !defined(STM32F070x6) && !defined(STM32F070xB) && !defined(STM32F030xC) #define UART_FLAG_REACK ((uint32_t)0x00400000) #endif /* !defined(STM32F030x6) && !defined(STM32F030x8) && !defined(STM32F070x6) && !defined(STM32F070xB) && !defined(STM32F030xC) */ #define UART_FLAG_TEACK ((uint32_t)0x00200000) #if !defined(STM32F030x6) && !defined(STM32F030x8) && !defined(STM32F070x6) && !defined(STM32F070xB) && !defined(STM32F030xC) #define UART_FLAG_WUF ((uint32_t)0x00100000) #endif /* !defined(STM32F030x6) && !defined(STM32F030x8) && !defined(STM32F070x6) && !defined(STM32F070xB) && !defined(STM32F030xC) */ #define UART_FLAG_RWU ((uint32_t)0x00080000) #define UART_FLAG_SBKF ((uint32_t)0x00040000 #define UART_FLAG_CMF ((uint32_t)0x00020000) #define UART_FLAG_BUSY ((uint32_t)0x00010000) #define UART_FLAG_ABRF ((uint32_t)0x00008000) #define UART_FLAG_ABRE ((uint32_t)0x00004000) #if !defined(STM32F030x6) && !defined(STM32F030x8) && !defined(STM32F070x6) && !defined(STM32F070xB) && !defined(STM32F030xC) #define UART_FLAG_EOBF ((uint32_t)0x00001000) #endif /* !defined(STM32F030x6) && !defined(STM32F030x8) && !defined(STM32F070x6) && !defined(STM32F070xB) && !defined(STM32F030xC) */ #define UART_FLAG_RTOF ((uint32_t)0x00000800) #define UART_FLAG_CTS ((uint32_t)0x00000400) #define UART_FLAG_CTSIF ((uint32_t)0x00000200) #if !defined(STM32F030x6) && !defined(STM32F030x8) && !defined(STM32F070x6) && !defined(STM32F070xB) && !defined(STM32F030xC) #define UART_FLAG_LBDF ((uint32_t)0x00000100) #endif /* !defined(STM32F030x6) && !defined(STM32F030x8) && !defined(STM32F070x6) && !defined(STM32F070xB) && !defined(STM32F030xC) */ #define UART_FLAG_TXE ((uint32_t)0x00000080) #define UART_FLAG_TC ((uint32_t)0x00000040) #define UART_FLAG_RXNE ((uint32_t)0x00000020) #define UART_FLAG_IDLE ((uint32_t)0x00000010) #define UART_FLAG_ORE ((uint32_t)0x00000008) #define UART_FLAG_NE ((uint32_t)0x00000004) #define UART_FLAG_FE ((uint32_t)0x00000002) #define UART_FLAG_PE ((uint32_t)0x00000001) /** * @} */ /** @defgroup UART_Interrupt_definition UARTEx Interrupts Definition * Elements values convention: 0000ZZZZZ0XXYYYYYb * - YYYYY : Interrupt source position in the XX register (5bits) * - XX : Interrupt source register (2bits) * - 01: CR1 register * - 10: CR2 register * - 11: CR3 register * - ZZZZZ : Flag position in the ISR register(5bits) * @{ */ #define UART_IT_PE ((uint16_t)0x0028) #define UART_IT_TXE ((uint16_t)0x0727) #define UART_IT_TC ((uint16_t)0x0626) #define UART_IT_RXNE ((uint16_t)0x0525) #define UART_IT_IDLE ((uint16_t)0x0424) #if !defined(STM32F030x6) && !defined(STM32F030x8) && !defined(STM32F070x6) && !defined(STM32F070xB) && !defined(STM32F030xC) #define UART_IT_LBD ((uint16_t)0x0846) #endif /* !defined(STM32F030x6) && !defined(STM32F030x8) && !defined(STM32F070x6) && !defined(STM32F070xB) && !defined(STM32F030xC) */ #define UART_IT_CTS ((uint16_t)0x096A) #define UART_IT_CM ((uint16_t)0x112E) #if !defined(STM32F030x6) && !defined(STM32F030x8) && !defined(STM32F070x6) && !defined(STM32F070xB) && !defined(STM32F030xC) #define UART_IT_WUF ((uint16_t)0x1476) #endif /* !defined(STM32F030x6) && !defined(STM32F030x8) && !defined(STM32F070x6) && !defined(STM32F070xB) && !defined(STM32F030xC) */ /** * @} */ /** @defgroup UART_IT_CLEAR_Flags UARTEx Interruption Clear Flags * @{ */ #define UART_CLEAR_PEF USART_ICR_PECF /*!< Parity Error Clear Flag */ #define UART_CLEAR_FEF USART_ICR_FECF /*!< Framing Error Clear Flag */ #define UART_CLEAR_NEF USART_ICR_NCF /*!< Noise detected Clear Flag */ #define UART_CLEAR_OREF USART_ICR_ORECF /*!< OverRun Error Clear Flag */ #define UART_CLEAR_IDLEF USART_ICR_IDLECF /*!< IDLE line detected Clear Flag */ #define UART_CLEAR_TCF USART_ICR_TCCF /*!< Transmission Complete Clear Flag */ #if !defined(STM32F030x6) && !defined(STM32F030x8) && !defined(STM32F070x6) && !defined(STM32F070xB) && !defined(STM32F030xC) #define UART_CLEAR_LBDF USART_ICR_LBDCF /*!< LIN Break Detection Clear Flag (not available on F030xx devices)*/ #endif /* !defined(STM32F030x6) && !defined(STM32F030x8) && !defined(STM32F070x6) && !defined(STM32F070xB) && !defined(STM32F030xC) */ #define UART_CLEAR_CTSF USART_ICR_CTSCF /*!< CTS Interrupt Clear Flag */ #define UART_CLEAR_RTOF USART_ICR_RTOCF /*!< Receiver Time Out Clear Flag */ #if !defined(STM32F030x6) && !defined(STM32F030x8) && !defined(STM32F070x6) && !defined(STM32F070xB) && !defined(STM32F030xC) #define UART_CLEAR_EOBF USART_ICR_EOBCF /*!< End Of Block Clear Flag */ #endif /* !defined(STM32F030x6) && !defined(STM32F030x8) && !defined(STM32F070x6) && !defined(STM32F070xB) && !defined(STM32F030xC) */ #define UART_CLEAR_CMF USART_ICR_CMCF /*!< Character Match Clear Flag */ #if !defined(STM32F030x6) && !defined(STM32F030x8) && !defined(STM32F070x6) && !defined(STM32F070xB) && !defined(STM32F030xC) #define UART_CLEAR_WUF USART_ICR_WUCF /*!< Wake Up from stop mode Clear Flag */ #endif /* !defined(STM32F030x6) && !defined(STM32F030x8) && !defined(STM32F070x6) && !defined(STM32F070xB) && !defined(STM32F030xC) */ /** * @} */ /** @defgroup UART_Request_Parameters UARTEx Request Parameters * @{ */ #define UART_AUTOBAUD_REQUEST ((uint32_t)USART_RQR_ABRRQ) /*!< Auto-Baud Rate Request */ #define UART_SENDBREAK_REQUEST ((uint32_t)USART_RQR_SBKRQ) /*!< Send Break Request */ #define UART_MUTE_MODE_REQUEST ((uint32_t)USART_RQR_MMRQ) /*!< Mute Mode Request */ #define UART_RXDATA_FLUSH_REQUEST ((uint32_t)USART_RQR_RXFRQ) /*!< Receive Data flush Request */ #if !defined(STM32F030x6) && !defined(STM32F030x8) && !defined(STM32F070x6) && !defined(STM32F070xB) && !defined(STM32F030xC) #define UART_TXDATA_FLUSH_REQUEST ((uint32_t)USART_RQR_TXFRQ) /*!< Transmit data flush Request */ #else #endif /* !defined(STM32F030x6) && !defined(STM32F030x8) && !defined(STM32F070x6) && !defined(STM32F070xB) && !defined(STM32F030xC) */ /** * @} */ #if !defined(STM32F030x6) && !defined(STM32F030x8) && !defined(STM32F070x6) && !defined(STM32F070xB) && !defined(STM32F030xC) /** @defgroup UART_Stop_Mode_Enable UARTEx Advanced Feature Stop Mode Enable * @{ */ #define UART_ADVFEATURE_STOPMODE_DISABLE ((uint32_t)0x00000000) /*!< UART stop mode disable */ #define UART_ADVFEATURE_STOPMODE_ENABLE ((uint32_t)USART_CR1_UESM) /*!< UART stop mode enable */ /** * @} */ /** @defgroup UART_WakeUp_from_Stop_Selection UART WakeUp From Stop Selection * @{ */ #define UART_WAKEUP_ON_ADDRESS ((uint32_t)0x00000000) /*!< UART wake-up on address */ #define UART_WAKEUP_ON_STARTBIT ((uint32_t)USART_CR3_WUS_1) /*!< UART wake-up on start bit */ #define UART_WAKEUP_ON_READDATA_NONEMPTY ((uint32_t)USART_CR3_WUS) /*!< UART wake-up on receive data register not empty */ /** * @} */ #endif /* !defined(STM32F030x6) && !defined(STM32F030x8) && !defined(STM32F070x6) && !defined(STM32F070xB) && !defined(STM32F030xC) */ /** * @} */ /* Exported macros ------------------------------------------------------------*/ /** @defgroup UARTEx_Exported_Macros UARTEx Exported Macros * @{ */ /** @brief Flush the UART Data registers. * @param __HANDLE__: specifies the UART Handle. * @retval None */ #if !defined(STM32F030x6) && !defined(STM32F030x8) #define __HAL_UART_FLUSH_DRREGISTER(__HANDLE__) \ do{ \ SET_BIT((__HANDLE__)->Instance->RQR, UART_RXDATA_FLUSH_REQUEST); \ SET_BIT((__HANDLE__)->Instance->RQR, UART_TXDATA_FLUSH_REQUEST); \ } while(0) #else #define __HAL_UART_FLUSH_DRREGISTER(__HANDLE__) \ do{ \ SET_BIT((__HANDLE__)->Instance->RQR, UART_RXDATA_FLUSH_REQUEST); \ } while(0) #endif /* !defined(STM32F030x6) && !defined(STM32F030x8) */ /** * @} */ /* Private macros ------------------------------------------------------------*/ /** @defgroup UARTEx_Private_Macros UARTEx Private Macros * @{ */ /** @brief Report the UART clock source. * @param __HANDLE__: specifies the UART Handle. * @param __CLOCKSOURCE__: output variable. * @retval UART clocking source, written in __CLOCKSOURCE__. */ #if defined(STM32F030x6) || defined(STM32F031x6) || defined(STM32F038xx) #define UART_GETCLOCKSOURCE(__HANDLE__,__CLOCKSOURCE__) \ do { \ switch(__HAL_RCC_GET_USART1_SOURCE()) \ { \ case RCC_USART1CLKSOURCE_PCLK1: \ (__CLOCKSOURCE__) = UART_CLOCKSOURCE_PCLK1; \ break; \ case RCC_USART1CLKSOURCE_HSI: \ (__CLOCKSOURCE__) = UART_CLOCKSOURCE_HSI; \ break; \ case RCC_USART1CLKSOURCE_SYSCLK: \ (__CLOCKSOURCE__) = UART_CLOCKSOURCE_SYSCLK; \ break; \ case RCC_USART1CLKSOURCE_LSE: \ (__CLOCKSOURCE__) = UART_CLOCKSOURCE_LSE; \ break; \ default: \ (__CLOCKSOURCE__) = UART_CLOCKSOURCE_UNDEFINED; \ break; \ } \ } while(0) #elif defined (STM32F030x8) || defined (STM32F070x6) || \ defined (STM32F042x6) || defined (STM32F048xx) || \ defined (STM32F051x8) || defined (STM32F058xx) #define UART_GETCLOCKSOURCE(__HANDLE__,__CLOCKSOURCE__) \ do { \ if((__HANDLE__)->Instance == USART1) \ { \ switch(__HAL_RCC_GET_USART1_SOURCE()) \ { \ case RCC_USART1CLKSOURCE_PCLK1: \ (__CLOCKSOURCE__) = UART_CLOCKSOURCE_PCLK1; \ break; \ case RCC_USART1CLKSOURCE_HSI: \ (__CLOCKSOURCE__) = UART_CLOCKSOURCE_HSI; \ break; \ case RCC_USART1CLKSOURCE_SYSCLK: \ (__CLOCKSOURCE__) = UART_CLOCKSOURCE_SYSCLK; \ break; \ case RCC_USART1CLKSOURCE_LSE: \ (__CLOCKSOURCE__) = UART_CLOCKSOURCE_LSE; \ break; \ default: \ (__CLOCKSOURCE__) = UART_CLOCKSOURCE_UNDEFINED; \ break; \ } \ } \ else if((__HANDLE__)->Instance == USART2) \ { \ (__CLOCKSOURCE__) = UART_CLOCKSOURCE_PCLK1; \ } \ else \ { \ (__CLOCKSOURCE__) = UART_CLOCKSOURCE_UNDEFINED; \ } \ } while(0) #elif defined(STM32F070xB) #define UART_GETCLOCKSOURCE(__HANDLE__,__CLOCKSOURCE__) \ do { \ if((__HANDLE__)->Instance == USART1) \ { \ switch(__HAL_RCC_GET_USART1_SOURCE()) \ { \ case RCC_USART1CLKSOURCE_PCLK1: \ (__CLOCKSOURCE__) = UART_CLOCKSOURCE_PCLK1; \ break; \ case RCC_USART1CLKSOURCE_HSI: \ (__CLOCKSOURCE__) = UART_CLOCKSOURCE_HSI; \ break; \ case RCC_USART1CLKSOURCE_SYSCLK: \ (__CLOCKSOURCE__) = UART_CLOCKSOURCE_SYSCLK; \ break; \ case RCC_USART1CLKSOURCE_LSE: \ (__CLOCKSOURCE__) = UART_CLOCKSOURCE_LSE; \ break; \ default: \ (__CLOCKSOURCE__) = UART_CLOCKSOURCE_UNDEFINED; \ break; \ } \ } \ else if((__HANDLE__)->Instance == USART2) \ { \ (__CLOCKSOURCE__) = UART_CLOCKSOURCE_PCLK1; \ } \ else if((__HANDLE__)->Instance == USART3) \ { \ (__CLOCKSOURCE__) = UART_CLOCKSOURCE_PCLK1; \ } \ else if((__HANDLE__)->Instance == USART4) \ { \ (__CLOCKSOURCE__) = UART_CLOCKSOURCE_PCLK1; \ } \ else \ { \ (__CLOCKSOURCE__) = UART_CLOCKSOURCE_UNDEFINED; \ } \ } while(0) #elif defined(STM32F071xB) || defined(STM32F072xB) || defined(STM32F078xx) #define UART_GETCLOCKSOURCE(__HANDLE__,__CLOCKSOURCE__) \ do { \ if((__HANDLE__)->Instance == USART1) \ { \ switch(__HAL_RCC_GET_USART1_SOURCE()) \ { \ case RCC_USART1CLKSOURCE_PCLK1: \ (__CLOCKSOURCE__) = UART_CLOCKSOURCE_PCLK1; \ break; \ case RCC_USART1CLKSOURCE_HSI: \ (__CLOCKSOURCE__) = UART_CLOCKSOURCE_HSI; \ break; \ case RCC_USART1CLKSOURCE_SYSCLK: \ (__CLOCKSOURCE__) = UART_CLOCKSOURCE_SYSCLK; \ break; \ case RCC_USART1CLKSOURCE_LSE: \ (__CLOCKSOURCE__) = UART_CLOCKSOURCE_LSE; \ break; \ default: \ (__CLOCKSOURCE__) = UART_CLOCKSOURCE_UNDEFINED; \ break; \ } \ } \ else if((__HANDLE__)->Instance == USART2) \ { \ switch(__HAL_RCC_GET_USART2_SOURCE()) \ { \ case RCC_USART2CLKSOURCE_PCLK1: \ (__CLOCKSOURCE__) = UART_CLOCKSOURCE_PCLK1; \ break; \ case RCC_USART2CLKSOURCE_HSI: \ (__CLOCKSOURCE__) = UART_CLOCKSOURCE_HSI; \ break; \ case RCC_USART2CLKSOURCE_SYSCLK: \ (__CLOCKSOURCE__) = UART_CLOCKSOURCE_SYSCLK; \ break; \ case RCC_USART2CLKSOURCE_LSE: \ (__CLOCKSOURCE__) = UART_CLOCKSOURCE_LSE; \ break; \ default: \ (__CLOCKSOURCE__) = UART_CLOCKSOURCE_UNDEFINED; \ break; \ } \ } \ else if((__HANDLE__)->Instance == USART3) \ { \ (__CLOCKSOURCE__) = UART_CLOCKSOURCE_PCLK1; \ } \ else if((__HANDLE__)->Instance == USART4) \ { \ (__CLOCKSOURCE__) = UART_CLOCKSOURCE_PCLK1; \ } \ else \ { \ (__CLOCKSOURCE__) = UART_CLOCKSOURCE_UNDEFINED; \ } \ } while(0) #elif defined(STM32F091xC) || defined (STM32F098xx) #define UART_GETCLOCKSOURCE(__HANDLE__,__CLOCKSOURCE__) \ do { \ if((__HANDLE__)->Instance == USART1) \ { \ switch(__HAL_RCC_GET_USART1_SOURCE()) \ { \ case RCC_USART1CLKSOURCE_PCLK1: \ (__CLOCKSOURCE__) = UART_CLOCKSOURCE_PCLK1; \ break; \ case RCC_USART1CLKSOURCE_HSI: \ (__CLOCKSOURCE__) = UART_CLOCKSOURCE_HSI; \ break; \ case RCC_USART1CLKSOURCE_SYSCLK: \ (__CLOCKSOURCE__) = UART_CLOCKSOURCE_SYSCLK; \ break; \ case RCC_USART1CLKSOURCE_LSE: \ (__CLOCKSOURCE__) = UART_CLOCKSOURCE_LSE; \ break; \ default: \ (__CLOCKSOURCE__) = UART_CLOCKSOURCE_UNDEFINED; \ break; \ } \ } \ else if((__HANDLE__)->Instance == USART2) \ { \ switch(__HAL_RCC_GET_USART2_SOURCE()) \ { \ case RCC_USART2CLKSOURCE_PCLK1: \ (__CLOCKSOURCE__) = UART_CLOCKSOURCE_PCLK1; \ break; \ case RCC_USART2CLKSOURCE_HSI: \ (__CLOCKSOURCE__) = UART_CLOCKSOURCE_HSI; \ break; \ case RCC_USART2CLKSOURCE_SYSCLK: \ (__CLOCKSOURCE__) = UART_CLOCKSOURCE_SYSCLK; \ break; \ case RCC_USART2CLKSOURCE_LSE: \ (__CLOCKSOURCE__) = UART_CLOCKSOURCE_LSE; \ break; \ default: \ (__CLOCKSOURCE__) = UART_CLOCKSOURCE_UNDEFINED; \ break; \ } \ } \ else if((__HANDLE__)->Instance == USART3) \ { \ switch(__HAL_RCC_GET_USART3_SOURCE()) \ { \ case RCC_USART3CLKSOURCE_PCLK1: \ (__CLOCKSOURCE__) = UART_CLOCKSOURCE_PCLK1; \ break; \ case RCC_USART3CLKSOURCE_HSI: \ (__CLOCKSOURCE__) = UART_CLOCKSOURCE_HSI; \ break; \ case RCC_USART3CLKSOURCE_SYSCLK: \ (__CLOCKSOURCE__) = UART_CLOCKSOURCE_SYSCLK; \ break; \ case RCC_USART3CLKSOURCE_LSE: \ (__CLOCKSOURCE__) = UART_CLOCKSOURCE_LSE; \ break; \ default: \ (__CLOCKSOURCE__) = UART_CLOCKSOURCE_UNDEFINED; \ break; \ } \ } \ else if((__HANDLE__)->Instance == USART4) \ { \ (__CLOCKSOURCE__) = UART_CLOCKSOURCE_PCLK1; \ } \ else if((__HANDLE__)->Instance == USART5) \ { \ (__CLOCKSOURCE__) = UART_CLOCKSOURCE_PCLK1; \ } \ else if((__HANDLE__)->Instance == USART6) \ { \ (__CLOCKSOURCE__) = UART_CLOCKSOURCE_PCLK1; \ } \ else if((__HANDLE__)->Instance == USART7) \ { \ (__CLOCKSOURCE__) = UART_CLOCKSOURCE_PCLK1; \ } \ else if((__HANDLE__)->Instance == USART8) \ { \ (__CLOCKSOURCE__) = UART_CLOCKSOURCE_PCLK1; \ } \ else \ { \ (__CLOCKSOURCE__) = UART_CLOCKSOURCE_UNDEFINED; \ } \ } while(0) #elif defined(STM32F030xC) #define UART_GETCLOCKSOURCE(__HANDLE__,__CLOCKSOURCE__) \ do { \ if((__HANDLE__)->Instance == USART1) \ { \ switch(__HAL_RCC_GET_USART1_SOURCE()) \ { \ case RCC_USART1CLKSOURCE_PCLK1: \ (__CLOCKSOURCE__) = UART_CLOCKSOURCE_PCLK1; \ break; \ case RCC_USART1CLKSOURCE_HSI: \ (__CLOCKSOURCE__) = UART_CLOCKSOURCE_HSI; \ break; \ case RCC_USART1CLKSOURCE_SYSCLK: \ (__CLOCKSOURCE__) = UART_CLOCKSOURCE_SYSCLK; \ break; \ case RCC_USART1CLKSOURCE_LSE: \ (__CLOCKSOURCE__) = UART_CLOCKSOURCE_LSE; \ break; \ default: \ (__CLOCKSOURCE__) = UART_CLOCKSOURCE_UNDEFINED; \ break; \ } \ } \ else if((__HANDLE__)->Instance == USART2) \ { \ (__CLOCKSOURCE__) = UART_CLOCKSOURCE_PCLK1; \ } \ else if((__HANDLE__)->Instance == USART3) \ { \ (__CLOCKSOURCE__) = UART_CLOCKSOURCE_PCLK1; \ } \ else if((__HANDLE__)->Instance == USART4) \ { \ (__CLOCKSOURCE__) = UART_CLOCKSOURCE_PCLK1; \ } \ else if((__HANDLE__)->Instance == USART5) \ { \ (__CLOCKSOURCE__) = UART_CLOCKSOURCE_PCLK1; \ } \ else if((__HANDLE__)->Instance == USART6) \ { \ (__CLOCKSOURCE__) = UART_CLOCKSOURCE_PCLK1; \ } \ else \ { \ (__CLOCKSOURCE__) = UART_CLOCKSOURCE_UNDEFINED; \ } \ } while(0) #endif /* defined(STM32F030x6) || defined(STM32F031x6) || defined(STM32F038xx) */ /** @brief Compute the UART mask to apply to retrieve the received data * according to the word length and to the parity bits activation. * @note If PCE = 1, the parity bit is not included in the data extracted * by the reception API(). * This masking operation is not carried out in the case of * DMA transfers. * @param __HANDLE__: specifies the UART Handle. * @retval None, the mask to apply to UART RDR register is stored in (__HANDLE__)->Mask field. */ #if defined (STM32F042x6) || defined (STM32F048xx) || defined (STM32F070x6) || \ defined (STM32F071xB) || defined (STM32F072xB) || defined (STM32F078xx) || defined (STM32F070xB) || \ defined (STM32F091xC) || defined (STM32F098xx) || defined (STM32F030xC) #define UART_MASK_COMPUTATION(__HANDLE__) \ do { \ if ((__HANDLE__)->Init.WordLength == UART_WORDLENGTH_9B) \ { \ if ((__HANDLE__)->Init.Parity == UART_PARITY_NONE) \ { \ (__HANDLE__)->Mask = 0x01FF ; \ } \ else \ { \ (__HANDLE__)->Mask = 0x00FF ; \ } \ } \ else if ((__HANDLE__)->Init.WordLength == UART_WORDLENGTH_8B) \ { \ if ((__HANDLE__)->Init.Parity == UART_PARITY_NONE) \ { \ (__HANDLE__)->Mask = 0x00FF ; \ } \ else \ { \ (__HANDLE__)->Mask = 0x007F ; \ } \ } \ else if ((__HANDLE__)->Init.WordLength == UART_WORDLENGTH_7B) \ { \ if ((__HANDLE__)->Init.Parity == UART_PARITY_NONE) \ { \ (__HANDLE__)->Mask = 0x007F ; \ } \ else \ { \ (__HANDLE__)->Mask = 0x003F ; \ } \ } \ } while(0) #else #define UART_MASK_COMPUTATION(__HANDLE__) \ do { \ if ((__HANDLE__)->Init.WordLength == UART_WORDLENGTH_9B) \ { \ if ((__HANDLE__)->Init.Parity == UART_PARITY_NONE) \ { \ (__HANDLE__)->Mask = 0x01FF ; \ } \ else \ { \ (__HANDLE__)->Mask = 0x00FF ; \ } \ } \ else if ((__HANDLE__)->Init.WordLength == UART_WORDLENGTH_8B) \ { \ if ((__HANDLE__)->Init.Parity == UART_PARITY_NONE) \ { \ (__HANDLE__)->Mask = 0x00FF ; \ } \ else \ { \ (__HANDLE__)->Mask = 0x007F ; \ } \ } \ } while(0) #endif /* defined (STM32F042x6) || defined (STM32F048xx) || defined (STM32F070x6) || \ defined (STM32F071xB) || defined (STM32F072xB) || defined (STM32F078xx) || defined (STM32F070xB) || \ defined (STM32F091xC) || defined (STM32F098xx) || defined (STM32F030xC) */ /** * @brief Ensure that UART frame length is valid. * @param __LENGTH__: UART frame length. * @retval SET (__LENGTH__ is valid) or RESET (__LENGTH__ is invalid) */ #if defined (STM32F042x6) || defined (STM32F048xx) || defined (STM32F070x6) || \ defined (STM32F071xB) || defined (STM32F072xB) || defined (STM32F078xx) || defined (STM32F070xB) || \ defined (STM32F091xC) || defined (STM32F098xx) || defined (STM32F030xC) #define IS_UART_WORD_LENGTH(__LENGTH__) (((__LENGTH__) == UART_WORDLENGTH_7B) || \ ((__LENGTH__) == UART_WORDLENGTH_8B) || \ ((__LENGTH__) == UART_WORDLENGTH_9B)) #else #define IS_UART_WORD_LENGTH(__LENGTH__) (((__LENGTH__) == UART_WORDLENGTH_8B) || \ ((__LENGTH__) == UART_WORDLENGTH_9B)) #endif /* defined (STM32F042x6) || defined (STM32F048xx) || defined (STM32F070x6) || \ defined (STM32F071xB) || defined (STM32F072xB) || defined (STM32F078xx) || defined (STM32F070xB) || \ defined (STM32F091xC) || defined (STM32F098xx) || defined (STM32F030xC) */ /** * @brief Ensure that UART auto Baud rate detection mode is valid. * @param __MODE__: UART auto Baud rate detection mode. * @retval SET (__MODE__ is valid) or RESET (__MODE__ is invalid) */ #if defined (STM32F042x6) || defined (STM32F048xx) || defined (STM32F070x6) || \ defined (STM32F071xB) || defined (STM32F072xB) || defined (STM32F078xx) || defined (STM32F070xB) || \ defined (STM32F091xC) || defined (STM32F098xx) || defined (STM32F030xC) #define IS_UART_ADVFEATURE_AUTOBAUDRATEMODE(__MODE__) (((__MODE__) == UART_ADVFEATURE_AUTOBAUDRATE_ONSTARTBIT) || \ ((__MODE__) == UART_ADVFEATURE_AUTOBAUDRATE_ONFALLINGEDGE) || \ ((__MODE__) == UART_ADVFEATURE_AUTOBAUDRATE_ON0X7FFRAME) || \ ((__MODE__) == UART_ADVFEATURE_AUTOBAUDRATE_ON0X55FRAME)) #else #define IS_UART_ADVFEATURE_AUTOBAUDRATEMODE(__MODE__) (((__MODE__) == UART_ADVFEATURE_AUTOBAUDRATE_ONSTARTBIT) || \ ((__MODE__) == UART_ADVFEATURE_AUTOBAUDRATE_ONFALLINGEDGE)) #endif /* defined (STM32F042x6) || defined (STM32F048xx) || defined (STM32F070x6) || \ defined (STM32F071xB) || defined (STM32F072xB) || defined (STM32F078xx) || defined (STM32F070xB) || \ defined (STM32F091xC) || defined (STM32F098xx) || defined (STM32F030xC) */ #if !defined(STM32F030x6) && !defined(STM32F030x8) && !defined(STM32F070x6) && !defined(STM32F070xB) && !defined(STM32F030xC) /** * @brief Ensure that UART LIN state is valid. * @param __LIN__: UART LIN state. * @retval SET (__LIN__ is valid) or RESET (__LIN__ is invalid) */ #define IS_UART_LIN(__LIN__) (((__LIN__) == UART_LIN_DISABLE) || \ ((__LIN__) == UART_LIN_ENABLE)) /** * @brief Ensure that UART LIN break detection length is valid. * @param __LENGTH__: UART LIN break detection length. * @retval SET (__LENGTH__ is valid) or RESET (__LENGTH__ is invalid) */ #define IS_UART_LIN_BREAK_DETECT_LENGTH(__LENGTH__) (((__LENGTH__) == UART_LINBREAKDETECTLENGTH_10B) || \ ((__LENGTH__) == UART_LINBREAKDETECTLENGTH_11B)) #endif /* !defined(STM32F030x6) && !defined(STM32F030x8) && !defined(STM32F070x6) && !defined(STM32F070xB) && !defined(STM32F030xC) */ /** * @brief Ensure that UART request parameter is valid. * @param __PARAM__: UART request parameter. * @retval SET (__PARAM__ is valid) or RESET (__PARAM__ is invalid) */ #if !defined(STM32F030x6) && !defined(STM32F030x8) && !defined(STM32F070x6) && !defined(STM32F070xB) && !defined(STM32F030xC) #define IS_UART_REQUEST_PARAMETER(__PARAM__) (((__PARAM__) == UART_AUTOBAUD_REQUEST) || \ ((__PARAM__) == UART_SENDBREAK_REQUEST) || \ ((__PARAM__) == UART_MUTE_MODE_REQUEST) || \ ((__PARAM__) == UART_RXDATA_FLUSH_REQUEST) || \ ((__PARAM__) == UART_TXDATA_FLUSH_REQUEST)) #else #define IS_UART_REQUEST_PARAMETER(__PARAM__) (((__PARAM__) == UART_AUTOBAUD_REQUEST) || \ ((__PARAM__) == UART_SENDBREAK_REQUEST) || \ ((__PARAM__) == UART_MUTE_MODE_REQUEST) || \ ((__PARAM__) == UART_RXDATA_FLUSH_REQUEST)) #endif /* !defined(STM32F030x6) && !defined(STM32F030x8) && !defined(STM32F070x6) && !defined(STM32F070xB) && !defined(STM32F030xC) */ #if !defined(STM32F030x6) && !defined(STM32F030x8) && !defined(STM32F070x6) && !defined(STM32F070xB) && !defined(STM32F030xC) /** * @brief Ensure that UART stop mode state is valid. * @param __STOPMODE__: UART stop mode state. * @retval SET (__STOPMODE__ is valid) or RESET (__STOPMODE__ is invalid) */ #define IS_UART_ADVFEATURE_STOPMODE(__STOPMODE__) (((__STOPMODE__) == UART_ADVFEATURE_STOPMODE_DISABLE) || \ ((__STOPMODE__) == UART_ADVFEATURE_STOPMODE_ENABLE)) /** * @brief Ensure that UART wake-up selection is valid. * @param __WAKE__: UART wake-up selection. * @retval SET (__WAKE__ is valid) or RESET (__WAKE__ is invalid) */ #define IS_UART_WAKEUP_SELECTION(__WAKE__) (((__WAKE__) == UART_WAKEUP_ON_ADDRESS) || \ ((__WAKE__) == UART_WAKEUP_ON_STARTBIT) || \ ((__WAKE__) == UART_WAKEUP_ON_READDATA_NONEMPTY)) #endif /* !defined(STM32F030x6) && !defined(STM32F030x8) && !defined(STM32F070x6) && !defined(STM32F070xB) && !defined(STM32F030xC) */ /** * @} */ /* Exported functions --------------------------------------------------------*/ /** @addtogroup UARTEx_Exported_Functions * @{ */ /** @addtogroup UARTEx_Exported_Functions_Group1 * @brief Extended Initialization and Configuration Functions * @{ */ /* Initialization and de-initialization functions ****************************/ HAL_StatusTypeDef HAL_RS485Ex_Init(UART_HandleTypeDef *huart, uint32_t UART_DEPolarity, uint32_t UART_DEAssertionTime, uint32_t UART_DEDeassertionTime); #if !defined(STM32F030x6) && !defined(STM32F030x8)&& !defined(STM32F070xB)&& !defined(STM32F070x6)&& !defined(STM32F030xC) HAL_StatusTypeDef HAL_LIN_Init(UART_HandleTypeDef *huart, uint32_t BreakDetectLength); #endif /* !defined(STM32F030x6) && !defined(STM32F030x8)&& !defined(STM32F070xB)&& !defined(STM32F070x6)&& !defined(STM32F030xC) */ /** * @} */ /** @addtogroup UARTEx_Exported_Functions_Group2 * @brief Extended UART Interrupt handling function * @{ */ /* IO operation functions ***************************************************/ #if !defined(STM32F030x6) && !defined(STM32F030x8)&& !defined(STM32F070xB)&& !defined(STM32F070x6)&& !defined(STM32F030xC) void HAL_UARTEx_WakeupCallback(UART_HandleTypeDef *huart); #endif /* !defined(STM32F030x6) && !defined(STM32F030x8)&& !defined(STM32F070xB)&& !defined(STM32F070x6)&& !defined(STM32F030xC) */ /** * @} */ /** @addtogroup UARTEx_Exported_Functions_Group3 * @brief Extended Peripheral Control functions * @{ */ /* Peripheral Control functions **********************************************/ HAL_StatusTypeDef HAL_MultiProcessorEx_AddressLength_Set(UART_HandleTypeDef *huart, uint32_t AddressLength); #if !defined(STM32F030x6) && !defined(STM32F030x8)&& !defined(STM32F070xB)&& !defined(STM32F070x6) && !defined(STM32F030xC) HAL_StatusTypeDef HAL_UARTEx_StopModeWakeUpSourceConfig(UART_HandleTypeDef *huart, UART_WakeUpTypeDef WakeUpSelection); HAL_StatusTypeDef HAL_UARTEx_EnableStopMode(UART_HandleTypeDef *huart); HAL_StatusTypeDef HAL_UARTEx_DisableStopMode(UART_HandleTypeDef *huart); HAL_StatusTypeDef HAL_LIN_SendBreak(UART_HandleTypeDef *huart); #endif /* !defined(STM32F030x6) && !defined(STM32F030x8)&& !defined(STM32F070xB)&& !defined(STM32F070x6)&& !defined(STM32F030xC) */ /** * @} */ /* Peripheral State functions ************************************************/ /** * @} */ /* Private functions ---------------------------------------------------------*/ /** * @} */ /** * @} */ #ifdef __cplusplus } #endif #endif /* __STM32F0xx_HAL_UART_EX_H */ /************************ (C) COPYRIGHT STMicroelectronics *****END OF FILE****/ ================================================ FILE: Zelig/mbed/TARGET_NUCLEO_F091RC/stm32f0xx_hal_usart.h ================================================ /** ****************************************************************************** * @file stm32f0xx_hal_usart.h * @author MCD Application Team * @version V1.3.0 * @date 26-June-2015 * @brief Header file of USART HAL module. ****************************************************************************** * @attention * *

© COPYRIGHT(c) 2015 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. * ****************************************************************************** */ /* Define to prevent recursive inclusion -------------------------------------*/ #ifndef __STM32F0xx_HAL_USART_H #define __STM32F0xx_HAL_USART_H #ifdef __cplusplus extern "C" { #endif /* Includes ------------------------------------------------------------------*/ #include "stm32f0xx_hal_def.h" /** @addtogroup STM32F0xx_HAL_Driver * @{ */ /** @addtogroup USART * @{ */ /* Exported types ------------------------------------------------------------*/ /** @defgroup USART_Exported_Types USART Exported Types * @{ */ /** * @brief USART Init Structure definition */ typedef struct { uint32_t BaudRate; /*!< This member configures the Usart communication baud rate. The baud rate is computed using the following formula: Baud Rate Register = ((PCLKx) / ((huart->Init.BaudRate))). */ uint32_t WordLength; /*!< Specifies the number of data bits transmitted or received in a frame. This parameter can be a value of @ref USARTEx_Word_Length. */ uint32_t StopBits; /*!< Specifies the number of stop bits transmitted. This parameter can be a value of @ref USART_Stop_Bits. */ uint32_t Parity; /*!< Specifies the parity mode. This parameter can be a value of @ref USART_Parity @note When parity is enabled, the computed parity is inserted at the MSB position of the transmitted data (9th bit when the word length is set to 9 data bits; 8th bit when the word length is set to 8 data bits). */ uint32_t Mode; /*!< Specifies whether the Receive or Transmit mode is enabled or disabled. This parameter can be a value of @ref USART_Mode. */ uint32_t CLKPolarity; /*!< Specifies the steady state of the serial clock. This parameter can be a value of @ref USART_Clock_Polarity. */ uint32_t CLKPhase; /*!< Specifies the clock transition on which the bit capture is made. This parameter can be a value of @ref USART_Clock_Phase. */ uint32_t CLKLastBit; /*!< Specifies whether the clock pulse corresponding to the last transmitted data bit (MSB) has to be output on the SCLK pin in synchronous mode. This parameter can be a value of @ref USART_Last_Bit. */ }USART_InitTypeDef; /** * @brief HAL USART State structures definition */ typedef enum { HAL_USART_STATE_RESET = 0x00, /*!< Peripheral is not initialized */ HAL_USART_STATE_READY = 0x01, /*!< Peripheral Initialized and ready for use */ HAL_USART_STATE_BUSY = 0x02, /*!< an internal process is ongoing */ HAL_USART_STATE_BUSY_TX = 0x12, /*!< Data Transmission process is ongoing */ HAL_USART_STATE_BUSY_RX = 0x22, /*!< Data Reception process is ongoing */ HAL_USART_STATE_BUSY_TX_RX = 0x32, /*!< Data Transmission Reception process is ongoing */ HAL_USART_STATE_TIMEOUT = 0x03, /*!< Timeout state */ HAL_USART_STATE_ERROR = 0x04 /*!< Error */ }HAL_USART_StateTypeDef; /** * @brief USART clock sources definitions */ typedef enum { USART_CLOCKSOURCE_PCLK1 = 0x00, /*!< PCLK1 clock source */ USART_CLOCKSOURCE_HSI = 0x02, /*!< HSI clock source */ USART_CLOCKSOURCE_SYSCLK = 0x04, /*!< SYSCLK clock source */ USART_CLOCKSOURCE_LSE = 0x08, /*!< LSE clock source */ USART_CLOCKSOURCE_UNDEFINED = 0x10 /*!< undefined clock source */ }USART_ClockSourceTypeDef; /** * @brief USART handle Structure definition */ typedef struct { USART_TypeDef *Instance; /*!< USART registers base address */ USART_InitTypeDef Init; /*!< USART communication parameters */ uint8_t *pTxBuffPtr; /*!< Pointer to USART Tx transfer Buffer */ uint16_t TxXferSize; /*!< USART Tx Transfer size */ uint16_t TxXferCount; /*!< USART Tx Transfer Counter */ uint8_t *pRxBuffPtr; /*!< Pointer to USART Rx transfer Buffer */ uint16_t RxXferSize; /*!< USART Rx Transfer size */ uint16_t RxXferCount; /*!< USART Rx Transfer Counter */ uint16_t Mask; /*!< USART Rx RDR register mask */ DMA_HandleTypeDef *hdmatx; /*!< USART Tx DMA Handle parameters */ DMA_HandleTypeDef *hdmarx; /*!< USART Rx DMA Handle parameters */ HAL_LockTypeDef Lock; /*!< Locking object */ __IO HAL_USART_StateTypeDef State; /*!< USART communication state */ __IO uint32_t ErrorCode; /*!< USART Error code */ }USART_HandleTypeDef; /** * @} */ /* Exported constants --------------------------------------------------------*/ /** @defgroup USART_Exported_Constants USART Exported Constants * @{ */ /** @defgroup USART_Error USART Error * @{ */ #define HAL_USART_ERROR_NONE ((uint32_t)0x00000000) /*!< No error */ #define HAL_USART_ERROR_PE ((uint32_t)0x00000001) /*!< Parity error */ #define HAL_USART_ERROR_NE ((uint32_t)0x00000002) /*!< Noise error */ #define HAL_USART_ERROR_FE ((uint32_t)0x00000004) /*!< frame error */ #define HAL_USART_ERROR_ORE ((uint32_t)0x00000008) /*!< Overrun error */ #define HAL_USART_ERROR_DMA ((uint32_t)0x00000010) /*!< DMA transfer error */ /** * @} */ /** @defgroup USART_Stop_Bits USART Number of Stop Bits * @{ */ #define USART_STOPBITS_1 ((uint32_t)0x0000) #define USART_STOPBITS_2 ((uint32_t)USART_CR2_STOP_1) #define USART_STOPBITS_1_5 ((uint32_t)(USART_CR2_STOP_0 | USART_CR2_STOP_1)) /** * @} */ /** @defgroup USART_Parity USART Parity * @{ */ #define USART_PARITY_NONE ((uint32_t)0x00000000) /*!< No parity */ #define USART_PARITY_EVEN ((uint32_t)USART_CR1_PCE) /*!< Even parity */ #define USART_PARITY_ODD ((uint32_t)(USART_CR1_PCE | USART_CR1_PS)) /*!< Odd parity */ /** * @} */ /** @defgroup USART_Mode USART Mode * @{ */ #define USART_MODE_RX ((uint32_t)USART_CR1_RE) /*!< RX mode */ #define USART_MODE_TX ((uint32_t)USART_CR1_TE) /*!< TX mode */ #define USART_MODE_TX_RX ((uint32_t)(USART_CR1_TE |USART_CR1_RE)) /*!< RX and TX mode */ /** * @} */ /** @defgroup USART_Clock USART Clock * @{ */ #define USART_CLOCK_DISABLE ((uint32_t)0x00000000) /*!< USART clock disable */ #define USART_CLOCK_ENABLE ((uint32_t)USART_CR2_CLKEN) /*!< USART clock enable */ /** * @} */ /** @defgroup USART_Clock_Polarity USART Clock Polarity * @{ */ #define USART_POLARITY_LOW ((uint32_t)0x00000000) /*!< USART Clock signal is steady Low */ #define USART_POLARITY_HIGH ((uint32_t)USART_CR2_CPOL) /*!< USART Clock signal is steady High */ /** * @} */ /** @defgroup USART_Clock_Phase USART Clock Phase * @{ */ #define USART_PHASE_1EDGE ((uint32_t)0x00000000) /*!< USART frame phase on first clock transition */ #define USART_PHASE_2EDGE ((uint32_t)USART_CR2_CPHA) /*!< USART frame phase on second clock transition */ /** * @} */ /** @defgroup USART_Last_Bit USART Last Bit * @{ */ #define USART_LASTBIT_DISABLE ((uint32_t)0x00000000) /*!< USART frame last data bit clock pulse not output to SCLK pin */ #define USART_LASTBIT_ENABLE ((uint32_t)USART_CR2_LBCL) /*!< USART frame last data bit clock pulse output to SCLK pin */ /** * @} */ /** @defgroup USART_Interrupt_definition USART Interrupts Definition * Elements values convention: 0000ZZZZ0XXYYYYYb * - YYYYY : Interrupt source position in the XX register (5bits) * - XX : Interrupt source register (2bits) * - 01: CR1 register * - 10: CR2 register * - 11: CR3 register * - ZZZZ : Flag position in the ISR register(4bits) * @{ */ #define USART_IT_PE ((uint16_t)0x0028) /*!< USART parity error interruption */ #define USART_IT_TXE ((uint16_t)0x0727) /*!< USART transmit data register empty interruption */ #define USART_IT_TC ((uint16_t)0x0626) /*!< USART transmission complete interruption */ #define USART_IT_RXNE ((uint16_t)0x0525) /*!< USART read data register not empty interruption */ #define USART_IT_IDLE ((uint16_t)0x0424) /*!< USART idle interruption */ #define USART_IT_ERR ((uint16_t)0x0060) /*!< USART error interruption */ #define USART_IT_ORE ((uint16_t)0x0300) /*!< USART overrun error interruption */ #define USART_IT_NE ((uint16_t)0x0200) /*!< USART noise error interruption */ #define USART_IT_FE ((uint16_t)0x0100) /*!< USART frame error interruption */ /** * @} */ /** @defgroup USART_IT_CLEAR_Flags USART Interruption Clear Flags * @{ */ #define USART_CLEAR_PEF USART_ICR_PECF /*!< Parity Error Clear Flag */ #define USART_CLEAR_FEF USART_ICR_FECF /*!< Framing Error Clear Flag */ #define USART_CLEAR_NEF USART_ICR_NCF /*!< Noise detected Clear Flag */ #define USART_CLEAR_OREF USART_ICR_ORECF /*!< OverRun Error Clear Flag */ #define USART_CLEAR_IDLEF USART_ICR_IDLECF /*!< IDLE line detected Clear Flag */ #define USART_CLEAR_TCF USART_ICR_TCCF /*!< Transmission Complete Clear Flag */ #define USART_CLEAR_CTSF USART_ICR_CTSCF /*!< CTS Interrupt Clear Flag */ /** * @} */ /** @defgroup USART_Interruption_Mask USART Interruption Flags Mask * @{ */ #define USART_IT_MASK ((uint16_t)0x001F) /*!< USART interruptions flags mask */ /** * @} */ /** * @} */ /* Exported macros -----------------------------------------------------------*/ /** @defgroup USART_Exported_Macros USART Exported Macros * @{ */ /** @brief Reset USART handle state. * @param __HANDLE__: USART handle. * @retval None */ #define __HAL_USART_RESET_HANDLE_STATE(__HANDLE__) ((__HANDLE__)->State = HAL_USART_STATE_RESET) /** @brief Check whether the specified USART flag is set or not. * @param __HANDLE__: specifies the USART Handle * @param __FLAG__: specifies the flag to check. * This parameter can be one of the following values: * @arg USART_FLAG_REACK: Receive enable acknowledge flag * @arg USART_FLAG_TEACK: Transmit enable acknowledge flag * @arg USART_FLAG_BUSY: Busy flag * @arg USART_FLAG_CTS: CTS Change flag * @arg USART_FLAG_TXE: Transmit data register empty flag * @arg USART_FLAG_TC: Transmission Complete flag * @arg USART_FLAG_RXNE: Receive data register not empty flag * @arg USART_FLAG_IDLE: Idle Line detection flag * @arg USART_FLAG_ORE: OverRun Error flag * @arg USART_FLAG_NE: Noise Error flag * @arg USART_FLAG_FE: Framing Error flag * @arg USART_FLAG_PE: Parity Error flag * @retval The new state of __FLAG__ (TRUE or FALSE). */ #define __HAL_USART_GET_FLAG(__HANDLE__, __FLAG__) (((__HANDLE__)->Instance->ISR & (__FLAG__)) == (__FLAG__)) /** @brief Clear the specified USART pending flag. * @param __HANDLE__: specifies the USART Handle. * @param __FLAG__: specifies the flag to check. * This parameter can be any combination of the following values: * @arg USART_CLEAR_PEF * @arg USART_CLEAR_FEF * @arg USART_CLEAR_NEF * @arg USART_CLEAR_OREF * @arg USART_CLEAR_IDLEF * @arg USART_CLEAR_TCF * @arg USART_CLEAR_CTSF * @arg USART_CLEAR_RTOF * @arg USART_CLEAR_EOBF * @arg USART_CLEAR_CMF * @arg USART_CLEAR_WUF * @retval None */ #define __HAL_USART_CLEAR_FLAG(__HANDLE__, __FLAG__) ((__HANDLE__)->Instance->ICR = (__FLAG__)) /** @brief Clear the USART PE pending flag. * @param __HANDLE__: specifies the USART Handle. * @retval None */ #define __HAL_USART_CLEAR_PEFLAG(__HANDLE__) __HAL_USART_CLEAR_FLAG((__HANDLE__), USART_CLEAR_PEF) /** @brief Clear the USART FE pending flag. * @param __HANDLE__: specifies the USART Handle. * @retval None */ #define __HAL_USART_CLEAR_FEFLAG(__HANDLE__) __HAL_USART_CLEAR_FLAG((__HANDLE__), USART_CLEAR_FEF) /** @brief Clear the USART NE pending flag. * @param __HANDLE__: specifies the USART Handle. * @retval None */ #define __HAL_USART_CLEAR_NEFLAG(__HANDLE__) __HAL_USART_CLEAR_FLAG((__HANDLE__), USART_CLEAR_NEF) /** @brief Clear the USART ORE pending flag. * @param __HANDLE__: specifies the USART Handle. * @retval None */ #define __HAL_USART_CLEAR_OREFLAG(__HANDLE__) __HAL_USART_CLEAR_FLAG((__HANDLE__), USART_CLEAR_OREF) /** @brief Clear the USART IDLE pending flag. * @param __HANDLE__: specifies the USART Handle. * @retval None */ #define __HAL_USART_CLEAR_IDLEFLAG(__HANDLE__) __HAL_USART_CLEAR_FLAG((__HANDLE__), USART_CLEAR_IDLEF) /** @brief Enable the specified USART interrupt. * @param __HANDLE__: specifies the USART Handle. * @param __INTERRUPT__: specifies the USART interrupt source to enable. * This parameter can be one of the following values: * @arg USART_IT_TXE: Transmit Data Register empty interrupt * @arg USART_IT_TC: Transmission complete interrupt * @arg USART_IT_RXNE: Receive Data register not empty interrupt * @arg USART_IT_IDLE: Idle line detection interrupt * @arg USART_IT_PE: Parity Error interrupt * @arg USART_IT_ERR: Error interrupt(Frame error, noise error, overrun error) * @retval None */ #define __HAL_USART_ENABLE_IT(__HANDLE__, __INTERRUPT__) (((((uint8_t)(__INTERRUPT__)) >> 5U) == 1)? ((__HANDLE__)->Instance->CR1 |= (1U << ((__INTERRUPT__) & USART_IT_MASK))): \ ((((uint8_t)(__INTERRUPT__)) >> 5U) == 2)? ((__HANDLE__)->Instance->CR2 |= (1U << ((__INTERRUPT__) & USART_IT_MASK))): \ ((__HANDLE__)->Instance->CR3 |= (1U << ((__INTERRUPT__) & USART_IT_MASK)))) /** @brief Disable the specified USART interrupt. * @param __HANDLE__: specifies the USART Handle. * @param __INTERRUPT__: specifies the USART interrupt source to disable. * This parameter can be one of the following values: * @arg USART_IT_TXE: Transmit Data Register empty interrupt * @arg USART_IT_TC: Transmission complete interrupt * @arg USART_IT_RXNE: Receive Data register not empty interrupt * @arg USART_IT_IDLE: Idle line detection interrupt * @arg USART_IT_PE: Parity Error interrupt * @arg USART_IT_ERR: Error interrupt(Frame error, noise error, overrun error) * @retval None */ #define __HAL_USART_DISABLE_IT(__HANDLE__, __INTERRUPT__) (((((uint8_t)(__INTERRUPT__)) >> 5U) == 1)? ((__HANDLE__)->Instance->CR1 &= ~ (1U << ((__INTERRUPT__) & USART_IT_MASK))): \ ((((uint8_t)(__INTERRUPT__)) >> 5U) == 2)? ((__HANDLE__)->Instance->CR2 &= ~ (1U << ((__INTERRUPT__) & USART_IT_MASK))): \ ((__HANDLE__)->Instance->CR3 &= ~ (1U << ((__INTERRUPT__) & USART_IT_MASK)))) /** @brief Check whether the specified USART interrupt has occurred or not. * @param __HANDLE__: specifies the USART Handle. * @param __IT__: specifies the USART interrupt source to check. * This parameter can be one of the following values: * @arg USART_IT_TXE: Transmit Data Register empty interrupt * @arg USART_IT_TC: Transmission complete interrupt * @arg USART_IT_RXNE: Receive Data register not empty interrupt * @arg USART_IT_IDLE: Idle line detection interrupt * @arg USART_IT_ORE: OverRun Error interrupt * @arg USART_IT_NE: Noise Error interrupt * @arg USART_IT_FE: Framing Error interrupt * @arg USART_IT_PE: Parity Error interrupt * @retval The new state of __IT__ (TRUE or FALSE). */ #define __HAL_USART_GET_IT(__HANDLE__, __IT__) ((__HANDLE__)->Instance->ISR & ((uint32_t)1 << ((__IT__)>> 0x08))) /** @brief Check whether the specified USART interrupt source is enabled or not. * @param __HANDLE__: specifies the USART Handle. * @param __IT__: specifies the USART interrupt source to check. * This parameter can be one of the following values: * @arg USART_IT_TXE: Transmit Data Register empty interrupt * @arg USART_IT_TC: Transmission complete interrupt * @arg USART_IT_RXNE: Receive Data register not empty interrupt * @arg USART_IT_IDLE: Idle line detection interrupt * @arg USART_IT_ORE: OverRun Error interrupt * @arg USART_IT_NE: Noise Error interrupt * @arg USART_IT_FE: Framing Error interrupt * @arg USART_IT_PE: Parity Error interrupt * @retval The new state of __IT__ (TRUE or FALSE). */ #define __HAL_USART_GET_IT_SOURCE(__HANDLE__, __IT__) ((((((uint8_t)(__IT__)) >> 5) == 1)? (__HANDLE__)->Instance->CR1:(((((uint8_t)(__IT__)) >> 5) == 2)? \ (__HANDLE__)->Instance->CR2 : (__HANDLE__)->Instance->CR3)) & ((uint32_t)1 << \ (((uint16_t)(__IT__)) & USART_IT_MASK))) /** @brief Clear the specified USART ISR flag, in setting the proper ICR register flag. * @param __HANDLE__: specifies the USART Handle. * @param __IT_CLEAR__: specifies the interrupt clear register flag that needs to be set * to clear the corresponding interrupt. * This parameter can be one of the following values: * @arg USART_CLEAR_PEF: Parity Error Clear Flag * @arg USART_CLEAR_FEF: Framing Error Clear Flag * @arg USART_CLEAR_NEF: Noise detected Clear Flag * @arg USART_CLEAR_OREF: OverRun Error Clear Flag * @arg USART_CLEAR_IDLEF: IDLE line detected Clear Flag * @arg USART_CLEAR_TCF: Transmission Complete Clear Flag * @arg USART_CLEAR_CTSF: CTS Interrupt Clear Flag * @retval None */ #define __HAL_USART_CLEAR_IT(__HANDLE__, __IT_CLEAR__) ((__HANDLE__)->Instance->ICR = (uint32_t)(__IT_CLEAR__)) /** @brief Set a specific USART request flag. * @param __HANDLE__: specifies the USART Handle. * @param __REQ__: specifies the request flag to set. * This parameter can be one of the following values: * @arg USART_RXDATA_FLUSH_REQUEST: Receive Data flush Request * @arg USART_TXDATA_FLUSH_REQUEST: Transmit data flush Request * * @retval None */ #define __HAL_USART_SEND_REQ(__HANDLE__, __REQ__) ((__HANDLE__)->Instance->RQR |= (__REQ__)) /** @brief Enable the USART one bit sample method. * @param __HANDLE__: specifies the USART Handle. * @retval None */ #define __HAL_USART_ONE_BIT_SAMPLE_ENABLE(__HANDLE__) ((__HANDLE__)->Instance->CR3|= USART_CR3_ONEBIT) /** @brief Disable the USART one bit sample method. * @param __HANDLE__: specifies the USART Handle. * @retval None */ #define __HAL_USART_ONE_BIT_SAMPLE_DISABLE(__HANDLE__) ((__HANDLE__)->Instance->CR3 &= (uint32_t)~((uint32_t)USART_CR3_ONEBIT)) /** @brief Enable USART. * @param __HANDLE__: specifies the USART Handle. * @retval None */ #define __HAL_USART_ENABLE(__HANDLE__) ((__HANDLE__)->Instance->CR1 |= USART_CR1_UE) /** @brief Disable USART. * @param __HANDLE__: specifies the USART Handle. * @retval None */ #define __HAL_USART_DISABLE(__HANDLE__) ((__HANDLE__)->Instance->CR1 &= ~USART_CR1_UE) /** * @} */ /* Private macros --------------------------------------------------------*/ /** @defgroup USART_Private_Macros USART Private Macros * @{ */ /** @brief Check USART Baud rate * @param __BAUDRATE__: Baudrate specified by the user. * The maximum Baud Rate is derived from the maximum clock on F0 (i.e. 48 MHz) * divided by the smallest oversampling used on the USART (i.e. 8) * @retval Test result (TRUE or FALSE). */ #define IS_USART_BAUDRATE(__BAUDRATE__) ((__BAUDRATE__) < 9000001) /** * @brief Ensure that USART frame number of stop bits is valid. * @param __STOPBITS__: USART frame number of stop bits. * @retval SET (__STOPBITS__ is valid) or RESET (__STOPBITS__ is invalid) */ #define IS_USART_STOPBITS(__STOPBITS__) (((__STOPBITS__) == USART_STOPBITS_1) || \ ((__STOPBITS__) == USART_STOPBITS_1_5) || \ ((__STOPBITS__) == USART_STOPBITS_2)) /** * @brief Ensure that USART frame parity is valid. * @param __PARITY__: USART frame parity. * @retval SET (__PARITY__ is valid) or RESET (__PARITY__ is invalid) */ #define IS_USART_PARITY(__PARITY__) (((__PARITY__) == USART_PARITY_NONE) || \ ((__PARITY__) == USART_PARITY_EVEN) || \ ((__PARITY__) == USART_PARITY_ODD)) /** * @brief Ensure that USART communication mode is valid. * @param __MODE__: USART communication mode. * @retval SET (__MODE__ is valid) or RESET (__MODE__ is invalid) */ #define IS_USART_MODE(__MODE__) ((((__MODE__) & (uint32_t)0xFFFFFFF3) == 0x00) && ((__MODE__) != (uint32_t)0x00)) /** * @brief Ensure that USART clock state is valid. * @param __CLOCK__: USART clock state. * @retval SET (__CLOCK__ is valid) or RESET (__CLOCK__ is invalid) */ #define IS_USART_CLOCK(__CLOCK__) (((__CLOCK__) == USART_CLOCK_DISABLE) || \ ((__CLOCK__) == USART_CLOCK_ENABLE)) /** * @brief Ensure that USART frame polarity is valid. * @param __CPOL__: USART frame polarity. * @retval SET (__CPOL__ is valid) or RESET (__CPOL__ is invalid) */ #define IS_USART_POLARITY(__CPOL__) (((__CPOL__) == USART_POLARITY_LOW) || ((__CPOL__) == USART_POLARITY_HIGH)) /** * @brief Ensure that USART frame phase is valid. * @param __CPHA__: USART frame phase. * @retval SET (__CPHA__ is valid) or RESET (__CPHA__ is invalid) */ #define IS_USART_PHASE(__CPHA__) (((__CPHA__) == USART_PHASE_1EDGE) || ((__CPHA__) == USART_PHASE_2EDGE)) /** * @brief Ensure that USART frame last bit clock pulse setting is valid. * @param __LASTBIT__: USART frame last bit clock pulse setting. * @retval SET (__LASTBIT__ is valid) or RESET (__LASTBIT__ is invalid) */ #define IS_USART_LASTBIT(__LASTBIT__) (((__LASTBIT__) == USART_LASTBIT_DISABLE) || \ ((__LASTBIT__) == USART_LASTBIT_ENABLE)) /** * @} */ /* Include USART HAL Extension module */ #include "stm32f0xx_hal_usart_ex.h" /* Exported functions --------------------------------------------------------*/ /** @addtogroup USART_Exported_Functions USART Exported Functions * @{ */ /** @addtogroup USART_Exported_Functions_Group1 Initialization and de-initialization functions * @{ */ /* Initialization and de-initialization functions ****************************/ HAL_StatusTypeDef HAL_USART_Init(USART_HandleTypeDef *husart); HAL_StatusTypeDef HAL_USART_DeInit(USART_HandleTypeDef *husart); void HAL_USART_MspInit(USART_HandleTypeDef *husart); void HAL_USART_MspDeInit(USART_HandleTypeDef *husart); /** * @} */ /** @addtogroup USART_Exported_Functions_Group2 IO operation functions * @{ */ /* IO operation functions *****************************************************/ HAL_StatusTypeDef HAL_USART_Transmit(USART_HandleTypeDef *husart, uint8_t *pTxData, uint16_t Size, uint32_t Timeout); HAL_StatusTypeDef HAL_USART_Receive(USART_HandleTypeDef *husart, uint8_t *pRxData, uint16_t Size, uint32_t Timeout); HAL_StatusTypeDef HAL_USART_TransmitReceive(USART_HandleTypeDef *husart, uint8_t *pTxData, uint8_t *pRxData, uint16_t Size, uint32_t Timeout); HAL_StatusTypeDef HAL_USART_Transmit_IT(USART_HandleTypeDef *husart, uint8_t *pTxData, uint16_t Size); HAL_StatusTypeDef HAL_USART_Receive_IT(USART_HandleTypeDef *husart, uint8_t *pRxData, uint16_t Size); HAL_StatusTypeDef HAL_USART_TransmitReceive_IT(USART_HandleTypeDef *husart, uint8_t *pTxData, uint8_t *pRxData, uint16_t Size); HAL_StatusTypeDef HAL_USART_Transmit_DMA(USART_HandleTypeDef *husart, uint8_t *pTxData, uint16_t Size); HAL_StatusTypeDef HAL_USART_Receive_DMA(USART_HandleTypeDef *husart, uint8_t *pRxData, uint16_t Size); HAL_StatusTypeDef HAL_USART_TransmitReceive_DMA(USART_HandleTypeDef *husart, uint8_t *pTxData, uint8_t *pRxData, uint16_t Size); HAL_StatusTypeDef HAL_USART_DMAPause(USART_HandleTypeDef *husart); HAL_StatusTypeDef HAL_USART_DMAResume(USART_HandleTypeDef *husart); HAL_StatusTypeDef HAL_USART_DMAStop(USART_HandleTypeDef *husart); void HAL_USART_IRQHandler(USART_HandleTypeDef *husart); void HAL_USART_TxCpltCallback(USART_HandleTypeDef *husart); void HAL_USART_RxCpltCallback(USART_HandleTypeDef *husart); void HAL_USART_TxHalfCpltCallback(USART_HandleTypeDef *husart); void HAL_USART_RxHalfCpltCallback(USART_HandleTypeDef *husart); void HAL_USART_TxRxCpltCallback(USART_HandleTypeDef *husart); void HAL_USART_ErrorCallback(USART_HandleTypeDef *husart); /** * @} */ /* Peripheral Control functions ***********************************************/ /** @addtogroup USART_Exported_Functions_Group3 Peripheral State and Error functions * @{ */ /* Peripheral State and Error functions ***************************************/ HAL_USART_StateTypeDef HAL_USART_GetState(USART_HandleTypeDef *husart); uint32_t HAL_USART_GetError(USART_HandleTypeDef *husart); /** * @} */ /** * @} */ /** * @} */ /** * @} */ #ifdef __cplusplus } #endif #endif /* __STM32F0xx_HAL_USART_H */ /************************ (C) COPYRIGHT STMicroelectronics *****END OF FILE****/ ================================================ FILE: Zelig/mbed/TARGET_NUCLEO_F091RC/stm32f0xx_hal_usart_ex.h ================================================ /** ****************************************************************************** * @file stm32f0xx_hal_usart_ex.h * @author MCD Application Team * @version V1.3.0 * @date 26-June-2015 * @brief Header file of USART HAL Extension module. ****************************************************************************** * @attention * *

© COPYRIGHT(c) 2015 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. * ****************************************************************************** */ /* Define to prevent recursive inclusion -------------------------------------*/ #ifndef __STM32F0xx_HAL_USART_EX_H #define __STM32F0xx_HAL_USART_EX_H #ifdef __cplusplus extern "C" { #endif /* Includes ------------------------------------------------------------------*/ #include "stm32f0xx_hal_def.h" /** @addtogroup STM32F0xx_HAL_Driver * @{ */ /** @defgroup USARTEx USARTEx * @{ */ /* Exported types ------------------------------------------------------------*/ /* Exported constants --------------------------------------------------------*/ /** @defgroup USARTEx_Exported_Constants USARTEx Exported Constants * @{ */ /** @defgroup USARTEx_Word_Length USARTEx Word Length * @{ */ #if defined (STM32F042x6) || defined (STM32F048xx) || defined (STM32F070x6) || \ defined (STM32F071xB) || defined (STM32F072xB) || defined (STM32F078xx) || defined (STM32F070xB) || \ defined (STM32F091xC) || defined (STM32F098xx) || defined (STM32F030xC) #define USART_WORDLENGTH_7B ((uint32_t)USART_CR1_M1) /*!< 7-bit long USART frame */ #define USART_WORDLENGTH_8B ((uint32_t)0x00000000) /*!< 8-bit long USART frame */ #define USART_WORDLENGTH_9B ((uint32_t)USART_CR1_M0) /*!< 9-bit long USART frame */ #else #define USART_WORDLENGTH_8B ((uint32_t)0x00000000) /*!< 8-bit long USART frame */ #define USART_WORDLENGTH_9B ((uint32_t)USART_CR1_M) /*!< 9-bit long USART frame */ #endif /* defined (STM32F042x6) || defined (STM32F048xx) || defined (STM32F070x6) || defined (STM32F070xB) || \ defined (STM32F071xB) || defined (STM32F072xB) || defined (STM32F078xx) || \ defined (STM32F091xC) || defined (STM32F098xx) || defined (STM32F030xC) */ /** * @} */ /** @defgroup USART_Request_Parameters USARTEx Request Parameters * @{ */ #define USART_RXDATA_FLUSH_REQUEST ((uint32_t)USART_RQR_RXFRQ) /*!< Receive Data flush Request */ #if !defined(STM32F030x6) && !defined(STM32F030x8) && !defined(STM32F070x6) && !defined(STM32F070xB) && !defined(STM32F030xC) #define USART_TXDATA_FLUSH_REQUEST ((uint32_t)USART_RQR_TXFRQ) /*!< Transmit data flush Request */ #else #endif /* !defined(STM32F030x6) && !defined(STM32F030x8) && !defined(STM32F070x6) && !defined(STM32F070xB) && !defined(STM32F030xC) */ /** * @} */ /** @defgroup USART_Flags USART Flags * Elements values convention: 0xXXXX * - 0xXXXX : Flag mask in the ISR register * @{ */ #if !defined(STM32F030x6) && !defined(STM32F030x8) && !defined(STM32F070x6) && !defined(STM32F070xB) && !defined(STM32F030xC) #define USART_FLAG_REACK ((uint32_t)0x00400000) /*!< USART receive enable acknowledge flag */ #endif /* !defined(STM32F030x6) && !defined(STM32F030x8) && !defined(STM32F070x6) && !defined(STM32F070xB) && !defined(STM32F030xC) */ #define USART_FLAG_TEACK ((uint32_t)0x00200000) /*!< USART transmit enable acknowledge flag */ #define USART_FLAG_BUSY ((uint32_t)0x00010000) /*!< USART busy flag */ #define USART_FLAG_CTS ((uint32_t)0x00000400) /*!< USART clear to send flag */ #define USART_FLAG_CTSIF ((uint32_t)0x00000200) /*!< USART clear to send interrupt flag */ #define USART_FLAG_TXE ((uint32_t)0x00000080) /*!< USART transmit data register empty */ #define USART_FLAG_TC ((uint32_t)0x00000040) /*!< USART transmission complete */ #define USART_FLAG_RXNE ((uint32_t)0x00000020) /*!< USART read data register not empty */ #define USART_FLAG_IDLE ((uint32_t)0x00000010) /*!< USART idle flag */ #define USART_FLAG_ORE ((uint32_t)0x00000008) /*!< USART overrun error */ #define USART_FLAG_NE ((uint32_t)0x00000004) /*!< USART noise error */ #define USART_FLAG_FE ((uint32_t)0x00000002) /*!< USART frame error */ #define USART_FLAG_PE ((uint32_t)0x00000001) /*!< USART parity error */ /** * @} */ /** * @} */ /* Exported macros ------------------------------------------------------------*/ /** @defgroup USARTEx_Exported_Macros USARTEx Exported Macros * @{ */ /** @brief Flush the USART Data registers. * @param __HANDLE__: specifies the USART Handle. * @retval None */ #if !defined(STM32F030x6) && !defined(STM32F030x8) && !defined(STM32F070x6) && !defined(STM32F070xB) && !defined(STM32F030xC) #define __HAL_USART_FLUSH_DRREGISTER(__HANDLE__) \ do{ \ SET_BIT((__HANDLE__)->Instance->RQR, USART_RXDATA_FLUSH_REQUEST); \ SET_BIT((__HANDLE__)->Instance->RQR, USART_TXDATA_FLUSH_REQUEST); \ } while(0) #else #define __HAL_USART_FLUSH_DRREGISTER(__HANDLE__) \ do{ \ SET_BIT((__HANDLE__)->Instance->RQR, USART_RXDATA_FLUSH_REQUEST); \ } while(0) #endif /* !defined(STM32F030x6) && !defined(STM32F030x8) && !defined(STM32F070x6) && !defined(STM32F070xB) && !defined(STM32F030xC) */ /** * @} */ /* Private macros ------------------------------------------------------------*/ /** @defgroup USARTEx_Private_Macros USARTEx Private Macros * @{ */ /** @brief Reports the USART clock source. * @param __HANDLE__: specifies the USART Handle * @param __CLOCKSOURCE__ : output variable * @retval the USART clocking source, written in __CLOCKSOURCE__. */ #if defined(STM32F030x6) || defined(STM32F031x6) || defined(STM32F038xx) #define USART_GETCLOCKSOURCE(__HANDLE__,__CLOCKSOURCE__) \ do { \ switch(__HAL_RCC_GET_USART1_SOURCE()) \ { \ case RCC_USART1CLKSOURCE_PCLK1: \ (__CLOCKSOURCE__) = USART_CLOCKSOURCE_PCLK1; \ break; \ case RCC_USART1CLKSOURCE_HSI: \ (__CLOCKSOURCE__) = USART_CLOCKSOURCE_HSI; \ break; \ case RCC_USART1CLKSOURCE_SYSCLK: \ (__CLOCKSOURCE__) = USART_CLOCKSOURCE_SYSCLK; \ break; \ case RCC_USART1CLKSOURCE_LSE: \ (__CLOCKSOURCE__) = USART_CLOCKSOURCE_LSE; \ break; \ default: \ (__CLOCKSOURCE__) = USART_CLOCKSOURCE_UNDEFINED; \ break; \ } \ } while(0) #elif defined (STM32F030x8) || defined (STM32F070x6) || \ defined (STM32F042x6) || defined (STM32F048xx) || \ defined (STM32F051x8) || defined (STM32F058xx) #define USART_GETCLOCKSOURCE(__HANDLE__,__CLOCKSOURCE__) \ do { \ if((__HANDLE__)->Instance == USART1) \ { \ switch(__HAL_RCC_GET_USART1_SOURCE()) \ { \ case RCC_USART1CLKSOURCE_PCLK1: \ (__CLOCKSOURCE__) = USART_CLOCKSOURCE_PCLK1; \ break; \ case RCC_USART1CLKSOURCE_HSI: \ (__CLOCKSOURCE__) = USART_CLOCKSOURCE_HSI; \ break; \ case RCC_USART1CLKSOURCE_SYSCLK: \ (__CLOCKSOURCE__) = USART_CLOCKSOURCE_SYSCLK; \ break; \ case RCC_USART1CLKSOURCE_LSE: \ (__CLOCKSOURCE__) = USART_CLOCKSOURCE_LSE; \ break; \ default: \ (__CLOCKSOURCE__) = USART_CLOCKSOURCE_UNDEFINED; \ break; \ } \ } \ else if((__HANDLE__)->Instance == USART2) \ { \ (__CLOCKSOURCE__) = USART_CLOCKSOURCE_PCLK1; \ } \ else \ { \ (__CLOCKSOURCE__) = USART_CLOCKSOURCE_UNDEFINED; \ } \ } while(0) #elif defined (STM32F070xB) #define USART_GETCLOCKSOURCE(__HANDLE__,__CLOCKSOURCE__) \ do { \ if((__HANDLE__)->Instance == USART1) \ { \ switch(__HAL_RCC_GET_USART1_SOURCE()) \ { \ case RCC_USART1CLKSOURCE_PCLK1: \ (__CLOCKSOURCE__) = USART_CLOCKSOURCE_PCLK1; \ break; \ case RCC_USART1CLKSOURCE_HSI: \ (__CLOCKSOURCE__) = USART_CLOCKSOURCE_HSI; \ break; \ case RCC_USART1CLKSOURCE_SYSCLK: \ (__CLOCKSOURCE__) = USART_CLOCKSOURCE_SYSCLK; \ break; \ case RCC_USART1CLKSOURCE_LSE: \ (__CLOCKSOURCE__) = USART_CLOCKSOURCE_LSE; \ break; \ default: \ (__CLOCKSOURCE__) = USART_CLOCKSOURCE_UNDEFINED; \ break; \ } \ } \ else if((__HANDLE__)->Instance == USART2) \ { \ (__CLOCKSOURCE__) = USART_CLOCKSOURCE_PCLK1; \ } \ else if((__HANDLE__)->Instance == USART3) \ { \ (__CLOCKSOURCE__) = USART_CLOCKSOURCE_PCLK1; \ } \ else if((__HANDLE__)->Instance == USART4) \ { \ (__CLOCKSOURCE__) = USART_CLOCKSOURCE_PCLK1; \ } \ else \ { \ (__CLOCKSOURCE__) = USART_CLOCKSOURCE_UNDEFINED; \ } \ } while(0) #elif defined(STM32F071xB) || defined(STM32F072xB) || defined(STM32F078xx) #define USART_GETCLOCKSOURCE(__HANDLE__,__CLOCKSOURCE__) \ do { \ if((__HANDLE__)->Instance == USART1) \ { \ switch(__HAL_RCC_GET_USART1_SOURCE()) \ { \ case RCC_USART1CLKSOURCE_PCLK1: \ (__CLOCKSOURCE__) = USART_CLOCKSOURCE_PCLK1; \ break; \ case RCC_USART1CLKSOURCE_HSI: \ (__CLOCKSOURCE__) = USART_CLOCKSOURCE_HSI; \ break; \ case RCC_USART1CLKSOURCE_SYSCLK: \ (__CLOCKSOURCE__) = USART_CLOCKSOURCE_SYSCLK; \ break; \ case RCC_USART1CLKSOURCE_LSE: \ (__CLOCKSOURCE__) = USART_CLOCKSOURCE_LSE; \ break; \ default: \ (__CLOCKSOURCE__) = USART_CLOCKSOURCE_UNDEFINED; \ break; \ } \ } \ else if((__HANDLE__)->Instance == USART2) \ { \ switch(__HAL_RCC_GET_USART2_SOURCE()) \ { \ case RCC_USART2CLKSOURCE_PCLK1: \ (__CLOCKSOURCE__) = USART_CLOCKSOURCE_PCLK1; \ break; \ case RCC_USART2CLKSOURCE_HSI: \ (__CLOCKSOURCE__) = USART_CLOCKSOURCE_HSI; \ break; \ case RCC_USART2CLKSOURCE_SYSCLK: \ (__CLOCKSOURCE__) = USART_CLOCKSOURCE_SYSCLK; \ break; \ case RCC_USART2CLKSOURCE_LSE: \ (__CLOCKSOURCE__) = USART_CLOCKSOURCE_LSE; \ break; \ default: \ (__CLOCKSOURCE__) = USART_CLOCKSOURCE_UNDEFINED; \ break; \ } \ } \ else if((__HANDLE__)->Instance == USART3) \ { \ (__CLOCKSOURCE__) = USART_CLOCKSOURCE_PCLK1; \ } \ else if((__HANDLE__)->Instance == USART4) \ { \ (__CLOCKSOURCE__) = USART_CLOCKSOURCE_PCLK1; \ } \ else \ { \ (__CLOCKSOURCE__) = USART_CLOCKSOURCE_UNDEFINED; \ } \ } while(0) #elif defined(STM32F091xC) || defined (STM32F098xx) #define USART_GETCLOCKSOURCE(__HANDLE__,__CLOCKSOURCE__) \ do { \ if((__HANDLE__)->Instance == USART1) \ { \ switch(__HAL_RCC_GET_USART1_SOURCE()) \ { \ case RCC_USART1CLKSOURCE_PCLK1: \ (__CLOCKSOURCE__) = USART_CLOCKSOURCE_PCLK1; \ break; \ case RCC_USART1CLKSOURCE_HSI: \ (__CLOCKSOURCE__) = USART_CLOCKSOURCE_HSI; \ break; \ case RCC_USART1CLKSOURCE_SYSCLK: \ (__CLOCKSOURCE__) = USART_CLOCKSOURCE_SYSCLK; \ break; \ case RCC_USART1CLKSOURCE_LSE: \ (__CLOCKSOURCE__) = USART_CLOCKSOURCE_LSE; \ break; \ default: \ (__CLOCKSOURCE__) = USART_CLOCKSOURCE_UNDEFINED; \ break; \ } \ } \ else if((__HANDLE__)->Instance == USART2) \ { \ switch(__HAL_RCC_GET_USART2_SOURCE()) \ { \ case RCC_USART2CLKSOURCE_PCLK1: \ (__CLOCKSOURCE__) = USART_CLOCKSOURCE_PCLK1; \ break; \ case RCC_USART2CLKSOURCE_HSI: \ (__CLOCKSOURCE__) = USART_CLOCKSOURCE_HSI; \ break; \ case RCC_USART2CLKSOURCE_SYSCLK: \ (__CLOCKSOURCE__) = USART_CLOCKSOURCE_SYSCLK; \ break; \ case RCC_USART2CLKSOURCE_LSE: \ (__CLOCKSOURCE__) = USART_CLOCKSOURCE_LSE; \ break; \ default: \ (__CLOCKSOURCE__) = USART_CLOCKSOURCE_UNDEFINED; \ break; \ } \ } \ else if((__HANDLE__)->Instance == USART3) \ { \ switch(__HAL_RCC_GET_USART3_SOURCE()) \ { \ case RCC_USART3CLKSOURCE_PCLK1: \ (__CLOCKSOURCE__) = USART_CLOCKSOURCE_PCLK1; \ break; \ case RCC_USART3CLKSOURCE_HSI: \ (__CLOCKSOURCE__) = USART_CLOCKSOURCE_HSI; \ break; \ case RCC_USART3CLKSOURCE_SYSCLK: \ (__CLOCKSOURCE__) = USART_CLOCKSOURCE_SYSCLK; \ break; \ case RCC_USART3CLKSOURCE_LSE: \ (__CLOCKSOURCE__) = USART_CLOCKSOURCE_LSE; \ break; \ default: \ (__CLOCKSOURCE__) = USART_CLOCKSOURCE_UNDEFINED; \ break; \ } \ } \ else if((__HANDLE__)->Instance == USART4) \ { \ (__CLOCKSOURCE__) = USART_CLOCKSOURCE_PCLK1; \ } \ else if((__HANDLE__)->Instance == USART5) \ { \ (__CLOCKSOURCE__) = USART_CLOCKSOURCE_PCLK1; \ } \ else if((__HANDLE__)->Instance == USART6) \ { \ (__CLOCKSOURCE__) = USART_CLOCKSOURCE_PCLK1; \ } \ else if((__HANDLE__)->Instance == USART7) \ { \ (__CLOCKSOURCE__) = USART_CLOCKSOURCE_PCLK1; \ } \ else if((__HANDLE__)->Instance == USART8) \ { \ (__CLOCKSOURCE__) = USART_CLOCKSOURCE_PCLK1; \ } \ else \ { \ (__CLOCKSOURCE__) = USART_CLOCKSOURCE_UNDEFINED; \ } \ } while(0) #elif defined(STM32F030xC) #define USART_GETCLOCKSOURCE(__HANDLE__,__CLOCKSOURCE__) \ do { \ if((__HANDLE__)->Instance == USART1) \ { \ switch(__HAL_RCC_GET_USART1_SOURCE()) \ { \ case RCC_USART1CLKSOURCE_PCLK1: \ (__CLOCKSOURCE__) = USART_CLOCKSOURCE_PCLK1; \ break; \ case RCC_USART1CLKSOURCE_HSI: \ (__CLOCKSOURCE__) = USART_CLOCKSOURCE_HSI; \ break; \ case RCC_USART1CLKSOURCE_SYSCLK: \ (__CLOCKSOURCE__) = USART_CLOCKSOURCE_SYSCLK; \ break; \ case RCC_USART1CLKSOURCE_LSE: \ (__CLOCKSOURCE__) = USART_CLOCKSOURCE_LSE; \ break; \ default: \ (__CLOCKSOURCE__) = USART_CLOCKSOURCE_UNDEFINED; \ break; \ } \ } \ else if((__HANDLE__)->Instance == USART2) \ { \ (__CLOCKSOURCE__) = USART_CLOCKSOURCE_PCLK1; \ } \ else if((__HANDLE__)->Instance == USART3) \ { \ (__CLOCKSOURCE__) = USART_CLOCKSOURCE_PCLK1; \ } \ else if((__HANDLE__)->Instance == USART4) \ { \ (__CLOCKSOURCE__) = USART_CLOCKSOURCE_PCLK1; \ } \ else if((__HANDLE__)->Instance == USART5) \ { \ (__CLOCKSOURCE__) = USART_CLOCKSOURCE_PCLK1; \ } \ else if((__HANDLE__)->Instance == USART6) \ { \ (__CLOCKSOURCE__) = USART_CLOCKSOURCE_PCLK1; \ } \ else \ { \ (__CLOCKSOURCE__) = USART_CLOCKSOURCE_UNDEFINED; \ } \ } while(0) #endif /* defined(STM32F030x6) || defined(STM32F031x6) || defined(STM32F038xx) */ /** @brief Compute the USART mask to apply to retrieve the received data * according to the word length and to the parity bits activation. * @note If PCE = 1, the parity bit is not included in the data extracted * by the reception API(). * This masking operation is not carried out in the case of * DMA transfers. * @param __HANDLE__: specifies the USART Handle. * @retval None, the mask to apply to USART RDR register is stored in (__HANDLE__)->Mask field. */ #if defined (STM32F042x6) || defined (STM32F048xx) || defined (STM32F070x6) || \ defined (STM32F071xB) || defined (STM32F072xB) || defined (STM32F078xx) || defined (STM32F070xB) || \ defined (STM32F091xC) || defined (STM32F098xx) || defined (STM32F030xC) #define USART_MASK_COMPUTATION(__HANDLE__) \ do { \ if ((__HANDLE__)->Init.WordLength == USART_WORDLENGTH_9B) \ { \ if ((__HANDLE__)->Init.Parity == USART_PARITY_NONE) \ { \ (__HANDLE__)->Mask = 0x01FF ; \ } \ else \ { \ (__HANDLE__)->Mask = 0x00FF ; \ } \ } \ else if ((__HANDLE__)->Init.WordLength == USART_WORDLENGTH_8B) \ { \ if ((__HANDLE__)->Init.Parity == USART_PARITY_NONE) \ { \ (__HANDLE__)->Mask = 0x00FF ; \ } \ else \ { \ (__HANDLE__)->Mask = 0x007F ; \ } \ } \ else if ((__HANDLE__)->Init.WordLength == USART_WORDLENGTH_7B) \ { \ if ((__HANDLE__)->Init.Parity == USART_PARITY_NONE) \ { \ (__HANDLE__)->Mask = 0x007F ; \ } \ else \ { \ (__HANDLE__)->Mask = 0x003F ; \ } \ } \ } while(0) #else #define USART_MASK_COMPUTATION(__HANDLE__) \ do { \ if ((__HANDLE__)->Init.WordLength == USART_WORDLENGTH_9B) \ { \ if ((__HANDLE__)->Init.Parity == USART_PARITY_NONE) \ { \ (__HANDLE__)->Mask = 0x01FF ; \ } \ else \ { \ (__HANDLE__)->Mask = 0x00FF ; \ } \ } \ else if ((__HANDLE__)->Init.WordLength == USART_WORDLENGTH_8B) \ { \ if ((__HANDLE__)->Init.Parity == USART_PARITY_NONE) \ { \ (__HANDLE__)->Mask = 0x00FF ; \ } \ else \ { \ (__HANDLE__)->Mask = 0x007F ; \ } \ } \ } while(0) #endif /* defined (STM32F042x6) || defined (STM32F048xx) || defined (STM32F070x6) || \ defined (STM32F071xB) || defined (STM32F072xB) || defined (STM32F078xx) || defined (STM32F070xB) || \ defined (STM32F091xC) || defined (STM32F098xx) || defined (STM32F030xC) */ /** * @brief Ensure that USART frame length is valid. * @param __LENGTH__: USART frame length. * @retval SET (__LENGTH__ is valid) or RESET (__LENGTH__ is invalid) */ #if defined (STM32F042x6) || defined (STM32F048xx) || defined (STM32F070x6) || \ defined (STM32F071xB) || defined (STM32F072xB) || defined (STM32F078xx) || defined (STM32F070xB) || \ defined (STM32F091xC) || defined (STM32F098xx) || defined (STM32F030xC) #define IS_USART_WORD_LENGTH(__LENGTH__) (((__LENGTH__) == USART_WORDLENGTH_7B) || \ ((__LENGTH__) == USART_WORDLENGTH_8B) || \ ((__LENGTH__) == USART_WORDLENGTH_9B)) #else #define IS_USART_WORD_LENGTH(__LENGTH__) (((__LENGTH__) == USART_WORDLENGTH_8B) || \ ((__LENGTH__) == USART_WORDLENGTH_9B)) #endif /* defined (STM32F042x6) || defined (STM32F048xx) || defined (STM32F070x6) || defined (STM32F070xB) || \ defined (STM32F071xB) || defined (STM32F072xB) || defined (STM32F078xx) || \ defined (STM32F091xC) || defined (STM32F098xx) || defined (STM32F030xC) */ /** * @brief Ensure that USART request parameter is valid. * @param __PARAM__: USART request parameter. * @retval SET (__PARAM__ is valid) or RESET (__PARAM__ is invalid) */ #if !defined(STM32F030x6) && !defined(STM32F030x8) && !defined(STM32F070x6) && !defined(STM32F070xB) && !defined(STM32F030xC) #define IS_USART_REQUEST_PARAMETER(__PARAM__) (((__PARAM__) == USART_RXDATA_FLUSH_REQUEST) || \ ((__PARAM__) == USART_TXDATA_FLUSH_REQUEST)) #else #define IS_USART_REQUEST_PARAMETER(__PARAM__) ((__PARAM__) == USART_RXDATA_FLUSH_REQUEST) #endif /* !defined(STM32F030x6) && !defined(STM32F030x8) && !defined(STM32F070x6) && !defined(STM32F070xB) && !defined(STM32F030xC) */ /** * @} */ /* Exported functions --------------------------------------------------------*/ /** * @} */ /** * @} */ #ifdef __cplusplus } #endif #endif /* __STM32F0xx_HAL_USART_EX_H */ /************************ (C) COPYRIGHT STMicroelectronics *****END OF FILE****/ ================================================ FILE: Zelig/mbed/TARGET_NUCLEO_F091RC/stm32f0xx_hal_wwdg.h ================================================ /** ****************************************************************************** * @file stm32f0xx_hal_wwdg.h * @author MCD Application Team * @version V1.3.0 * @date 26-June-2015 * @brief Header file of WWDG HAL module. ****************************************************************************** * @attention * *

© COPYRIGHT(c) 2015 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. * ****************************************************************************** */ /* Define to prevent recursive inclusion -------------------------------------*/ #ifndef __STM32F0xx_HAL_WWDG_H #define __STM32F0xx_HAL_WWDG_H #ifdef __cplusplus extern "C" { #endif /* Includes ------------------------------------------------------------------*/ #include "stm32f0xx_hal_def.h" /** @addtogroup STM32F0xx_HAL_Driver * @{ */ /** @addtogroup WWDG * @{ */ /* Exported types ------------------------------------------------------------*/ /** @defgroup WWDG_Exported_Types WWDG Exported Types * @{ */ /** * @brief WWDG HAL State Structure definition */ typedef enum { HAL_WWDG_STATE_RESET = 0x00, /*!< WWDG not yet initialized or disabled */ HAL_WWDG_STATE_READY = 0x01, /*!< WWDG initialized and ready for use */ HAL_WWDG_STATE_BUSY = 0x02, /*!< WWDG internal process is ongoing */ HAL_WWDG_STATE_TIMEOUT = 0x03, /*!< WWDG timeout state */ HAL_WWDG_STATE_ERROR = 0x04 /*!< WWDG error state */ }HAL_WWDG_StateTypeDef; /** * @brief WWDG Init structure definition */ typedef struct { uint32_t Prescaler; /*!< Specifies the prescaler value of the WWDG. This parameter can be a value of @ref WWDG_Prescaler */ uint32_t Window; /*!< Specifies the WWDG window value to be compared to the downcounter. This parameter must be a number lower than Max_Data = 0x80 */ uint32_t Counter; /*!< Specifies the WWDG free-running downcounter value. This parameter must be a number between Min_Data = 0x40 and Max_Data = 0x7F */ } WWDG_InitTypeDef; /** * @brief WWDG handle Structure definition */ typedef struct { WWDG_TypeDef *Instance; /*!< Register base address */ WWDG_InitTypeDef Init; /*!< WWDG required parameters */ HAL_LockTypeDef Lock; /*!< WWDG locking object */ __IO HAL_WWDG_StateTypeDef State; /*!< WWDG communication state */ } WWDG_HandleTypeDef; /** * @} */ /* Exported constants --------------------------------------------------------*/ /** @defgroup WWDG_Exported_Constants WWDG Exported Constants * @{ */ /** @defgroup WWDG_Interrupt_definition WWDG Interrupt definition * @{ */ #define WWDG_IT_EWI WWDG_CFR_EWI /*!< Early wakeup interrupt */ /** * @} */ /** @defgroup WWDG_Flag_definition WWDG Flag definition * @brief WWDG Flag definition * @{ */ #define WWDG_FLAG_EWIF WWDG_SR_EWIF /*!< Early wakeup interrupt flag */ /** * @} */ /** @defgroup WWDG_Prescaler WWDG Prescaler * @{ */ #define WWDG_PRESCALER_1 ((uint32_t)0x00000000) /*!< WWDG counter clock = (PCLK1/4096)/1 */ #define WWDG_PRESCALER_2 WWDG_CFR_WDGTB0 /*!< WWDG counter clock = (PCLK1/4096)/2 */ #define WWDG_PRESCALER_4 WWDG_CFR_WDGTB1 /*!< WWDG counter clock = (PCLK1/4096)/4 */ #define WWDG_PRESCALER_8 WWDG_CFR_WDGTB /*!< WWDG counter clock = (PCLK1/4096)/8 */ /** * @} */ /** * @} */ /* Private macros ------------------------------------------------------------*/ /** @defgroup WWDG_Private_Macros WWDG Private Macros * @{ */ #define IS_WWDG_PRESCALER(__PRESCALER__) (((__PRESCALER__) == WWDG_PRESCALER_1) || \ ((__PRESCALER__) == WWDG_PRESCALER_2) || \ ((__PRESCALER__) == WWDG_PRESCALER_4) || \ ((__PRESCALER__) == WWDG_PRESCALER_8)) #define IS_WWDG_WINDOW(__WINDOW__) ((__WINDOW__) <= 0x7F) #define IS_WWDG_COUNTER(__COUNTER__) (((__COUNTER__) >= 0x40) && ((__COUNTER__) <= 0x7F)) /** * @} */ /* Exported macros ------------------------------------------------------------*/ /** @defgroup WWDG_Exported_Macros WWDG Exported Macros * @{ */ /** @brief Reset WWDG handle state. * @param __HANDLE__: WWDG handle * @retval None */ #define __HAL_WWDG_RESET_HANDLE_STATE(__HANDLE__) ((__HANDLE__)->State = HAL_WWDG_STATE_RESET) /** * @brief Enable the WWDG peripheral. * @param __HANDLE__: WWDG handle * @retval None */ #define __HAL_WWDG_ENABLE(__HANDLE__) ((__HANDLE__)->Instance->CR |= WWDG_CR_WDGA) /** * @brief Disable the WWDG peripheral. * @param __HANDLE__: WWDG handle * @note WARNING: This is a dummy macro for HAL code alignment. * Once enable, WWDG Peripheral cannot be disabled except by a system reset. * @retval None */ #define __HAL_WWDG_DISABLE(__HANDLE__) /* dummy macro */ /** * @brief Enable the WWDG early wakeup interrupt. * @param __HANDLE__: WWDG handle * @param __INTERRUPT__: specifies the interrupt to enable. * This parameter can be one of the following values: * @arg WWDG_IT_EWI: Early wakeup interrupt * @note Once enabled this interrupt cannot be disabled except by a system reset. * @retval None */ #define __HAL_WWDG_ENABLE_IT(__HANDLE__, __INTERRUPT__) ((__HANDLE__)->Instance->CFR |= (__INTERRUPT__)) /** * @brief Disable the WWDG early wakeup interrupt. * @param __HANDLE__: WWDG handle * @param __INTERRUPT__: specifies the interrupt to disable. * This parameter can be one of the following values: * @arg WWDG_IT_EWI: Early wakeup interrupt * @note WARNING: This is a dummy macro for HAL code alignment. * Once enabled this interrupt cannot be disabled except by a system reset. * @retval None */ #define __HAL_WWDG_DISABLE_IT(__HANDLE__, __INTERRUPT__) /* dummy macro */ /** * @brief Check whether the selected WWDG interrupt has occurred or not. * @param __HANDLE__: WWDG handle * @param __INTERRUPT__: specifies the it to check. * This parameter can be one of the following values: * @arg WWDG_FLAG_EWIF: Early wakeup interrupt IT * @retval The new state of WWDG_FLAG (SET or RESET). */ #define __HAL_WWDG_GET_IT(__HANDLE__, __INTERRUPT__) (((__HANDLE__)->Instance->SR & (__INTERRUPT__)) == (__INTERRUPT__)) /** @brief Clear the WWDG interrupt pending bits. * bits to clear the selected interrupt pending bits. * @param __HANDLE__: WWDG handle * @param __INTERRUPT__: specifies the interrupt pending bit to clear. * This parameter can be one of the following values: * @arg WWDG_FLAG_EWIF: Early wakeup interrupt flag */ #define __HAL_WWDG_CLEAR_IT(__HANDLE__, __INTERRUPT__) ((__HANDLE__)->Instance->SR = ~(__INTERRUPT__)) /** * @brief Check whether the specified WWDG flag is set or not. * @param __HANDLE__: WWDG handle * @param __FLAG__: specifies the flag to check. * This parameter can be one of the following values: * @arg WWDG_FLAG_EWIF: Early wakeup interrupt flag * @retval The new state of WWDG_FLAG (SET or RESET). */ #define __HAL_WWDG_GET_FLAG(__HANDLE__, __FLAG__) (((__HANDLE__)->Instance->SR & (__FLAG__)) == (__FLAG__)) /** * @brief Clear the WWDG's pending flags. * @param __HANDLE__: WWDG handle * @param __FLAG__: specifies the flag to clear. * This parameter can be one of the following values: * @arg WWDG_FLAG_EWIF: Early wakeup interrupt flag * @retval None */ #define __HAL_WWDG_CLEAR_FLAG(__HANDLE__, __FLAG__) ((__HANDLE__)->Instance->SR = ~(__FLAG__)) /** @brief Check whether the specified WWDG interrupt source is enabled or not. * @param __HANDLE__: WWDG Handle. * @param __INTERRUPT__: specifies the WWDG interrupt source to check. * This parameter can be one of the following values: * @arg WWDG_IT_EWI: Early Wakeup Interrupt * @retval state of __INTERRUPT__ (TRUE or FALSE). */ #define __HAL_WWDG_GET_IT_SOURCE(__HANDLE__, __INTERRUPT__) (((__HANDLE__)->Instance->CFR & (__INTERRUPT__)) == (__INTERRUPT__)) /** * @} */ /* Exported functions --------------------------------------------------------*/ /** @addtogroup WWDG_Exported_Functions * @{ */ /** @addtogroup WWDG_Exported_Functions_Group1 * @{ */ /* Initialization/de-initialization functions **********************************/ HAL_StatusTypeDef HAL_WWDG_Init(WWDG_HandleTypeDef *hwwdg); HAL_StatusTypeDef HAL_WWDG_DeInit(WWDG_HandleTypeDef *hwwdg); void HAL_WWDG_MspInit(WWDG_HandleTypeDef *hwwdg); void HAL_WWDG_MspDeInit(WWDG_HandleTypeDef *hwwdg); /** * @} */ /** @addtogroup WWDG_Exported_Functions_Group2 * @{ */ /* I/O operation functions ******************************************************/ HAL_StatusTypeDef HAL_WWDG_Start(WWDG_HandleTypeDef *hwwdg); HAL_StatusTypeDef HAL_WWDG_Start_IT(WWDG_HandleTypeDef *hwwdg); HAL_StatusTypeDef HAL_WWDG_Refresh(WWDG_HandleTypeDef *hwwdg, uint32_t Counter); void HAL_WWDG_IRQHandler(WWDG_HandleTypeDef *hwwdg); void HAL_WWDG_WakeupCallback(WWDG_HandleTypeDef* hwwdg); /** * @} */ /** @addtogroup WWDG_Exported_Functions_Group3 * @{ */ /* Peripheral State functions **************************************************/ HAL_WWDG_StateTypeDef HAL_WWDG_GetState(WWDG_HandleTypeDef *hwwdg); /** * @} */ /** * @} */ /** * @} */ /** * @} */ #ifdef __cplusplus } #endif #endif /* __STM32F0xx_HAL_WWDG_H */ /************************ (C) COPYRIGHT STMicroelectronics *****END OF FILE****/ ================================================ FILE: Zelig/mbed/TARGET_NUCLEO_F091RC/system_stm32f0xx.h ================================================ /** ****************************************************************************** * @file system_stm32f0xx.h * @author MCD Application Team * @version V2.2.2 * @date 26-June-2015 * @brief CMSIS Cortex-M0 Device System Source File for STM32F0xx devices. ****************************************************************************** * @attention * *

© COPYRIGHT(c) 2015 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. * ****************************************************************************** */ /** @addtogroup CMSIS * @{ */ /** @addtogroup stm32f0xx_system * @{ */ /** * @brief Define to prevent recursive inclusion */ #ifndef __SYSTEM_STM32F0XX_H #define __SYSTEM_STM32F0XX_H #ifdef __cplusplus extern "C" { #endif /** @addtogroup STM32F0xx_System_Includes * @{ */ /** * @} */ /** @addtogroup STM32F0xx_System_Exported_types * @{ */ /* This variable is updated in three ways: 1) by calling CMSIS function SystemCoreClockUpdate() 3) by calling HAL API function HAL_RCC_GetHCLKFreq() 3) by calling HAL API function HAL_RCC_ClockConfig() Note: If you use this function to configure the system clock; then there is no need to call the 2 first functions listed above, since SystemCoreClock variable is updated automatically. */ extern uint32_t SystemCoreClock; /*!< System Clock Frequency (Core Clock) */ /** * @} */ /** @addtogroup STM32F0xx_System_Exported_Constants * @{ */ /** * @} */ /** @addtogroup STM32F0xx_System_Exported_Macros * @{ */ /** * @} */ /** @addtogroup STM32F0xx_System_Exported_Functions * @{ */ extern void SystemInit(void); extern void SystemCoreClockUpdate(void); extern void SetSysClock(void); /** * @} */ #ifdef __cplusplus } #endif #endif /*__SYSTEM_STM32F0XX_H */ /** * @} */ /** * @} */ /************************ (C) COPYRIGHT STMicroelectronics *****END OF FILE****/ ================================================ FILE: Zelig/mbed/TARGET_NUCLEO_F401RE/TARGET_STM/TARGET_STM32F4/PeripheralPins.h ================================================ /* mbed Microcontroller Library ******************************************************************************* * Copyright (c) 2014, STMicroelectronics * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * 1. Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * 3. Neither the name of 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. ******************************************************************************* */ #ifndef MBED_PERIPHERALPINS_H #define MBED_PERIPHERALPINS_H #include "pinmap.h" #include "PeripheralNames.h" //*** ADC *** extern const PinMap PinMap_ADC[]; //*** DAC *** extern const PinMap PinMap_DAC[]; //*** I2C *** extern const PinMap PinMap_I2C_SDA[]; extern const PinMap PinMap_I2C_SCL[]; //*** PWM *** extern const PinMap PinMap_PWM[]; //*** SERIAL *** extern const PinMap PinMap_UART_TX[]; extern const PinMap PinMap_UART_RX[]; //*** SPI *** extern const PinMap PinMap_SPI_MOSI[]; extern const PinMap PinMap_SPI_MISO[]; extern const PinMap PinMap_SPI_SCLK[]; extern const PinMap PinMap_SPI_SSEL[]; #endif ================================================ FILE: Zelig/mbed/TARGET_NUCLEO_F401RE/TARGET_STM/TARGET_STM32F4/TARGET_NUCLEO_F401RE/PeripheralNames.h ================================================ /* mbed Microcontroller Library ******************************************************************************* * Copyright (c) 2014, STMicroelectronics * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * 1. Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * 3. Neither the name of 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. ******************************************************************************* */ #ifndef MBED_PERIPHERALNAMES_H #define MBED_PERIPHERALNAMES_H #include "cmsis.h" #ifdef __cplusplus extern "C" { #endif typedef enum { ADC_1 = (int)ADC1_BASE } ADCName; typedef enum { UART_1 = (int)USART1_BASE, UART_2 = (int)USART2_BASE, UART_6 = (int)USART6_BASE } UARTName; #define STDIO_UART_TX PA_2 #define STDIO_UART_RX PA_3 #define STDIO_UART UART_2 typedef enum { SPI_1 = (int)SPI1_BASE, SPI_2 = (int)SPI2_BASE, SPI_3 = (int)SPI3_BASE, SPI_4 = (int)SPI4_BASE } SPIName; typedef enum { I2C_1 = (int)I2C1_BASE, I2C_2 = (int)I2C2_BASE, I2C_3 = (int)I2C3_BASE } I2CName; typedef enum { PWM_1 = (int)TIM1_BASE, PWM_2 = (int)TIM2_BASE, PWM_3 = (int)TIM3_BASE, PWM_4 = (int)TIM4_BASE, PWM_5 = (int)TIM5_BASE, PWM_9 = (int)TIM9_BASE, PWM_10 = (int)TIM10_BASE, PWM_11 = (int)TIM11_BASE } PWMName; #ifdef __cplusplus } #endif #endif ================================================ FILE: Zelig/mbed/TARGET_NUCLEO_F401RE/TARGET_STM/TARGET_STM32F4/TARGET_NUCLEO_F401RE/PinNames.h ================================================ /* mbed Microcontroller Library ******************************************************************************* * Copyright (c) 2014, STMicroelectronics * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * 1. Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * 3. Neither the name of 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. ******************************************************************************* */ #ifndef MBED_PINNAMES_H #define MBED_PINNAMES_H #include "cmsis.h" #ifdef __cplusplus extern "C" { #endif // See stm32f4xx_hal_gpio.h and stm32f4xx_hal_gpio_ex.h for values of MODE, PUPD and AFNUM #define STM_PIN_DATA(MODE, PUPD, AFNUM) ((int)(((AFNUM) << 7) | ((PUPD) << 4) | ((MODE) << 0))) #define STM_PIN_DATA_EXT(MODE, PUPD, AFNUM, CHANNEL, INVERTED) ((int)(((INVERTED & 0x01) << 15) | ((CHANNEL & 0x0F) << 11) | ((AFNUM & 0x0F) << 7) | ((PUPD & 0x07) << 4) | ((MODE & 0x0F) << 0))) #define STM_PIN_MODE(X) (((X) >> 0) & 0x0F) #define STM_PIN_PUPD(X) (((X) >> 4) & 0x07) #define STM_PIN_AFNUM(X) (((X) >> 7) & 0x0F) #define STM_PIN_AFNUM(X) (((X) >> 7) & 0x0F) #define STM_PIN_CHANNEL(X) (((X) >> 11) & 0x0F) #define STM_PIN_INVERTED(X) (((X) >> 15) & 0x01) #define STM_MODE_INPUT (0) #define STM_MODE_OUTPUT_PP (1) #define STM_MODE_OUTPUT_OD (2) #define STM_MODE_AF_PP (3) #define STM_MODE_AF_OD (4) #define STM_MODE_ANALOG (5) #define STM_MODE_IT_RISING (6) #define STM_MODE_IT_FALLING (7) #define STM_MODE_IT_RISING_FALLING (8) #define STM_MODE_EVT_RISING (9) #define STM_MODE_EVT_FALLING (10) #define STM_MODE_EVT_RISING_FALLING (11) #define STM_MODE_IT_EVT_RESET (12) // High nibble = port number (0=A, 1=B, 2=C, 3=D, 4=E, 5=F, 6=G, 7=H) // Low nibble = pin number #define STM_PORT(X) (((uint32_t)(X) >> 4) & 0xF) #define STM_PIN(X) ((uint32_t)(X) & 0xF) typedef enum { PIN_INPUT, PIN_OUTPUT } PinDirection; typedef enum { PA_0 = 0x00, PA_1 = 0x01, PA_2 = 0x02, PA_3 = 0x03, PA_4 = 0x04, PA_5 = 0x05, PA_6 = 0x06, PA_7 = 0x07, PA_8 = 0x08, PA_9 = 0x09, PA_10 = 0x0A, PA_11 = 0x0B, PA_12 = 0x0C, PA_13 = 0x0D, PA_14 = 0x0E, PA_15 = 0x0F, PB_0 = 0x10, PB_1 = 0x11, PB_2 = 0x12, PB_3 = 0x13, PB_4 = 0x14, PB_5 = 0x15, PB_6 = 0x16, PB_7 = 0x17, PB_8 = 0x18, PB_9 = 0x19, PB_10 = 0x1A, PB_12 = 0x1C, PB_13 = 0x1D, PB_14 = 0x1E, PB_15 = 0x1F, PC_0 = 0x20, PC_1 = 0x21, PC_2 = 0x22, PC_3 = 0x23, PC_4 = 0x24, PC_5 = 0x25, PC_6 = 0x26, PC_7 = 0x27, PC_8 = 0x28, PC_9 = 0x29, PC_10 = 0x2A, PC_11 = 0x2B, PC_12 = 0x2C, PC_13 = 0x2D, PC_14 = 0x2E, PC_15 = 0x2F, PD_2 = 0x32, PH_0 = 0x70, PH_1 = 0x71, // Arduino connector namings A0 = PA_0, A1 = PA_1, A2 = PA_4, A3 = PB_0, A4 = PC_1, A5 = PC_0, D0 = PA_3, D1 = PA_2, D2 = PA_10, D3 = PB_3, D4 = PB_5, D5 = PB_4, D6 = PB_10, D7 = PA_8, D8 = PA_9, D9 = PC_7, D10 = PB_6, D11 = PA_7, D12 = PA_6, D13 = PA_5, D14 = PB_9, D15 = PB_8, // Generic signals namings LED1 = PA_5, LED2 = PA_5, LED3 = PA_5, LED4 = PA_5, USER_BUTTON = PC_13, SERIAL_TX = PA_2, SERIAL_RX = PA_3, USBTX = PA_2, USBRX = PA_3, I2C_SCL = PB_8, I2C_SDA = PB_9, SPI_MOSI = PA_7, SPI_MISO = PA_6, SPI_SCK = PA_5, SPI_CS = PB_6, PWM_OUT = PB_3, // Not connected NC = (int)0xFFFFFFFF } PinName; typedef enum { PullNone = 0, PullUp = 1, PullDown = 2, OpenDrain = 3, PullDefault = PullNone } PinMode; #ifdef __cplusplus } #endif #endif ================================================ FILE: Zelig/mbed/TARGET_NUCLEO_F401RE/TARGET_STM/TARGET_STM32F4/TARGET_NUCLEO_F401RE/PortNames.h ================================================ /* mbed Microcontroller Library ******************************************************************************* * Copyright (c) 2014, STMicroelectronics * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * 1. Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * 3. Neither the name of 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. ******************************************************************************* */ #ifndef MBED_PORTNAMES_H #define MBED_PORTNAMES_H #ifdef __cplusplus extern "C" { #endif typedef enum { PortA = 0, PortB = 1, PortC = 2, PortD = 3, PortE = 4, PortH = 7 } PortName; #ifdef __cplusplus } #endif #endif ================================================ FILE: Zelig/mbed/TARGET_NUCLEO_F401RE/TARGET_STM/TARGET_STM32F4/TARGET_NUCLEO_F401RE/device.h ================================================ /* mbed Microcontroller Library ******************************************************************************* * Copyright (c) 2014, STMicroelectronics * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * 1. Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * 3. Neither the name of 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. ******************************************************************************* */ #ifndef MBED_DEVICE_H #define MBED_DEVICE_H #define DEVICE_PORTIN 1 #define DEVICE_PORTOUT 1 #define DEVICE_PORTINOUT 1 #define DEVICE_INTERRUPTIN 1 #define DEVICE_ANALOGIN 1 #define DEVICE_ANALOGOUT 0 // Not present on this device #define DEVICE_SERIAL 1 #define DEVICE_I2C 1 #define DEVICE_I2CSLAVE 1 #define DEVICE_SPI 1 #define DEVICE_SPISLAVE 1 #define DEVICE_RTC 1 #define DEVICE_PWMOUT 1 #define DEVICE_SLEEP 1 //======================================= #define DEVICE_SEMIHOST 0 #define DEVICE_LOCALFILESYSTEM 0 #define DEVICE_ID_LENGTH 24 #define DEVICE_DEBUG_AWARENESS 0 #define DEVICE_STDIO_MESSAGES 1 #define DEVICE_ERROR_RED 1 #define LED_RED LED1 #include "objects.h" #endif ================================================ FILE: Zelig/mbed/TARGET_NUCLEO_F401RE/TARGET_STM/TARGET_STM32F4/TARGET_NUCLEO_F401RE/objects.h ================================================ /* mbed Microcontroller Library ******************************************************************************* * Copyright (c) 2014, STMicroelectronics * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * 1. Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * 3. Neither the name of 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. ******************************************************************************* */ #ifndef MBED_OBJECTS_H #define MBED_OBJECTS_H #include "cmsis.h" #include "PortNames.h" #include "PeripheralNames.h" #include "PinNames.h" #ifdef __cplusplus extern "C" { #endif struct gpio_irq_s { IRQn_Type irq_n; uint32_t irq_index; uint32_t event; PinName pin; }; struct port_s { PortName port; uint32_t mask; PinDirection direction; __IO uint32_t *reg_in; __IO uint32_t *reg_out; }; struct analogin_s { ADCName adc; PinName pin; uint8_t channel; }; struct serial_s { UARTName uart; int index; // Used by irq uint32_t baudrate; uint32_t databits; uint32_t stopbits; uint32_t parity; PinName pin_tx; PinName pin_rx; }; struct spi_s { SPIName spi; uint32_t bits; uint32_t cpol; uint32_t cpha; uint32_t mode; uint32_t nss; uint32_t br_presc; PinName pin_miso; PinName pin_mosi; PinName pin_sclk; PinName pin_ssel; }; struct i2c_s { I2CName i2c; uint32_t slave; }; struct pwmout_s { PWMName pwm; PinName pin; uint32_t period; uint32_t pulse; uint8_t channel; uint8_t inverted; }; #include "gpio_object.h" #ifdef __cplusplus } #endif #endif ================================================ FILE: Zelig/mbed/TARGET_NUCLEO_F401RE/TARGET_STM/TARGET_STM32F4/gpio_object.h ================================================ /* mbed Microcontroller Library ******************************************************************************* * Copyright (c) 2014, STMicroelectronics * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * 1. Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * 3. Neither the name of 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. ******************************************************************************* */ #ifndef MBED_GPIO_OBJECT_H #define MBED_GPIO_OBJECT_H #include "mbed_assert.h" #include "cmsis.h" #include "PortNames.h" #include "PeripheralNames.h" #include "PinNames.h" #ifdef __cplusplus extern "C" { #endif typedef struct { PinName pin; uint32_t mask; __IO uint32_t *reg_in; __IO uint32_t *reg_set_clr; } gpio_t; static inline void gpio_write(gpio_t *obj, int value) { MBED_ASSERT(obj->pin != (PinName)NC); if (value) { *obj->reg_set_clr = obj->mask; } else { *obj->reg_set_clr = obj->mask << 16; } } static inline int gpio_read(gpio_t *obj) { MBED_ASSERT(obj->pin != (PinName)NC); return ((*obj->reg_in & obj->mask) ? 1 : 0); } static inline int gpio_is_connected(const gpio_t *obj) { return obj->pin != (PinName)NC; } #ifdef __cplusplus } #endif #endif ================================================ FILE: Zelig/mbed/TARGET_NUCLEO_F401RE/TOOLCHAIN_GCC_ARM/STM32F401XE.ld ================================================ /* Linker script to configure memory regions. */ MEMORY { FLASH (rx) : ORIGIN = 0x08000000, LENGTH = 512K RAM (rwx) : ORIGIN = 0x20000194, LENGTH = 96k - 0x194 } /* Linker script to place sections and symbol values. Should be used together * with other linker script that defines memory regions FLASH and RAM. * It references following symbols, which must be defined in code: * Reset_Handler : Entry of reset handler * * It defines following symbols, which code can use without definition: * __exidx_start * __exidx_end * __etext * __data_start__ * __preinit_array_start * __preinit_array_end * __init_array_start * __init_array_end * __fini_array_start * __fini_array_end * __data_end__ * __bss_start__ * __bss_end__ * __end__ * end * __HeapLimit * __StackLimit * __StackTop * __stack * _estack */ ENTRY(Reset_Handler) SECTIONS { .text : { KEEP(*(.isr_vector)) *(.text*) KEEP(*(.init)) KEEP(*(.fini)) /* .ctors */ *crtbegin.o(.ctors) *crtbegin?.o(.ctors) *(EXCLUDE_FILE(*crtend?.o *crtend.o) .ctors) *(SORT(.ctors.*)) *(.ctors) /* .dtors */ *crtbegin.o(.dtors) *crtbegin?.o(.dtors) *(EXCLUDE_FILE(*crtend?.o *crtend.o) .dtors) *(SORT(.dtors.*)) *(.dtors) *(.rodata*) KEEP(*(.eh_frame*)) } > FLASH .ARM.extab : { *(.ARM.extab* .gnu.linkonce.armextab.*) } > FLASH __exidx_start = .; .ARM.exidx : { *(.ARM.exidx* .gnu.linkonce.armexidx.*) } > FLASH __exidx_end = .; __etext = .; _sidata = .; .data : AT (__etext) { __data_start__ = .; _sdata = .; *(vtable) *(.data*) . = ALIGN(4); /* preinit data */ PROVIDE_HIDDEN (__preinit_array_start = .); KEEP(*(.preinit_array)) PROVIDE_HIDDEN (__preinit_array_end = .); . = ALIGN(4); /* init data */ PROVIDE_HIDDEN (__init_array_start = .); KEEP(*(SORT(.init_array.*))) KEEP(*(.init_array)) PROVIDE_HIDDEN (__init_array_end = .); . = ALIGN(4); /* finit data */ PROVIDE_HIDDEN (__fini_array_start = .); KEEP(*(SORT(.fini_array.*))) KEEP(*(.fini_array)) PROVIDE_HIDDEN (__fini_array_end = .); KEEP(*(.jcr*)) . = ALIGN(4); /* All data end */ __data_end__ = .; _edata = .; } > RAM .bss : { . = ALIGN(4); __bss_start__ = .; _sbss = .; *(.bss*) *(COMMON) . = ALIGN(4); __bss_end__ = .; _ebss = .; } > RAM .heap (COPY): { __end__ = .; end = __end__; *(.heap*) __HeapLimit = .; } > RAM /* .stack_dummy section doesn't contains any symbols. It is only * used for linker to calculate size of stack sections, and assign * values to stack symbols later */ .stack_dummy (COPY): { *(.stack*) } > RAM /* * The section '.managed_exception_thread' is a LLILUM Specific addition to pad * the stack space at the bottom with enough space to build a managed array. * Assuming that the stack bottom (_StackLimit) is 8 bytes aligned, we add * 16 bytes that will contain the array ObjectHeader and the length member (see * ArrayImpl.cs). This way we do preserve stack alignment. */ .stack_dummy_managed_exception_thread : { *(.managed_exception_thread) } > RAM /* Set stack top to end of RAM, and stack limit move down by * size of stack_dummy section */ __StackTop = ORIGIN(RAM) + LENGTH(RAM); _estack = __StackTop; __StackLimit = __StackTop - SIZEOF(.stack_dummy) + SIZEOF(.stack_dummy_managed_exception_thread); PROVIDE(__stack = __StackTop); /* Check if data + heap + stack exceeds RAM limit */ ASSERT(__StackLimit >= __HeapLimit, "region RAM overflowed with stack") } ================================================ FILE: Zelig/mbed/TARGET_NUCLEO_F401RE/arm_common_tables.h ================================================ /* ---------------------------------------------------------------------- * Copyright (C) 2010-2014 ARM Limited. All rights reserved. * * $Date: 19. March 2015 * $Revision: V.1.4.5 * * Project: CMSIS DSP Library * Title: arm_common_tables.h * * Description: This file has extern declaration for common tables like Bitreverse, reciprocal etc which are used across different functions * * Target Processor: Cortex-M4/Cortex-M3 * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * - Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * - Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * - Neither the name of ARM LIMITED nor the names of its contributors * may be used to endorse or promote products derived from this * software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * -------------------------------------------------------------------- */ #ifndef _ARM_COMMON_TABLES_H #define _ARM_COMMON_TABLES_H #include "arm_math.h" extern const uint16_t armBitRevTable[1024]; extern const q15_t armRecipTableQ15[64]; extern const q31_t armRecipTableQ31[64]; //extern const q31_t realCoefAQ31[1024]; //extern const q31_t realCoefBQ31[1024]; extern const float32_t twiddleCoef_16[32]; extern const float32_t twiddleCoef_32[64]; extern const float32_t twiddleCoef_64[128]; extern const float32_t twiddleCoef_128[256]; extern const float32_t twiddleCoef_256[512]; extern const float32_t twiddleCoef_512[1024]; extern const float32_t twiddleCoef_1024[2048]; extern const float32_t twiddleCoef_2048[4096]; extern const float32_t twiddleCoef_4096[8192]; #define twiddleCoef twiddleCoef_4096 extern const q31_t twiddleCoef_16_q31[24]; extern const q31_t twiddleCoef_32_q31[48]; extern const q31_t twiddleCoef_64_q31[96]; extern const q31_t twiddleCoef_128_q31[192]; extern const q31_t twiddleCoef_256_q31[384]; extern const q31_t twiddleCoef_512_q31[768]; extern const q31_t twiddleCoef_1024_q31[1536]; extern const q31_t twiddleCoef_2048_q31[3072]; extern const q31_t twiddleCoef_4096_q31[6144]; extern const q15_t twiddleCoef_16_q15[24]; extern const q15_t twiddleCoef_32_q15[48]; extern const q15_t twiddleCoef_64_q15[96]; extern const q15_t twiddleCoef_128_q15[192]; extern const q15_t twiddleCoef_256_q15[384]; extern const q15_t twiddleCoef_512_q15[768]; extern const q15_t twiddleCoef_1024_q15[1536]; extern const q15_t twiddleCoef_2048_q15[3072]; extern const q15_t twiddleCoef_4096_q15[6144]; extern const float32_t twiddleCoef_rfft_32[32]; extern const float32_t twiddleCoef_rfft_64[64]; extern const float32_t twiddleCoef_rfft_128[128]; extern const float32_t twiddleCoef_rfft_256[256]; extern const float32_t twiddleCoef_rfft_512[512]; extern const float32_t twiddleCoef_rfft_1024[1024]; extern const float32_t twiddleCoef_rfft_2048[2048]; extern const float32_t twiddleCoef_rfft_4096[4096]; /* floating-point bit reversal tables */ #define ARMBITREVINDEXTABLE__16_TABLE_LENGTH ((uint16_t)20 ) #define ARMBITREVINDEXTABLE__32_TABLE_LENGTH ((uint16_t)48 ) #define ARMBITREVINDEXTABLE__64_TABLE_LENGTH ((uint16_t)56 ) #define ARMBITREVINDEXTABLE_128_TABLE_LENGTH ((uint16_t)208 ) #define ARMBITREVINDEXTABLE_256_TABLE_LENGTH ((uint16_t)440 ) #define ARMBITREVINDEXTABLE_512_TABLE_LENGTH ((uint16_t)448 ) #define ARMBITREVINDEXTABLE1024_TABLE_LENGTH ((uint16_t)1800) #define ARMBITREVINDEXTABLE2048_TABLE_LENGTH ((uint16_t)3808) #define ARMBITREVINDEXTABLE4096_TABLE_LENGTH ((uint16_t)4032) extern const uint16_t armBitRevIndexTable16[ARMBITREVINDEXTABLE__16_TABLE_LENGTH]; extern const uint16_t armBitRevIndexTable32[ARMBITREVINDEXTABLE__32_TABLE_LENGTH]; extern const uint16_t armBitRevIndexTable64[ARMBITREVINDEXTABLE__64_TABLE_LENGTH]; extern const uint16_t armBitRevIndexTable128[ARMBITREVINDEXTABLE_128_TABLE_LENGTH]; extern const uint16_t armBitRevIndexTable256[ARMBITREVINDEXTABLE_256_TABLE_LENGTH]; extern const uint16_t armBitRevIndexTable512[ARMBITREVINDEXTABLE_512_TABLE_LENGTH]; extern const uint16_t armBitRevIndexTable1024[ARMBITREVINDEXTABLE1024_TABLE_LENGTH]; extern const uint16_t armBitRevIndexTable2048[ARMBITREVINDEXTABLE2048_TABLE_LENGTH]; extern const uint16_t armBitRevIndexTable4096[ARMBITREVINDEXTABLE4096_TABLE_LENGTH]; /* fixed-point bit reversal tables */ #define ARMBITREVINDEXTABLE_FIXED___16_TABLE_LENGTH ((uint16_t)12 ) #define ARMBITREVINDEXTABLE_FIXED___32_TABLE_LENGTH ((uint16_t)24 ) #define ARMBITREVINDEXTABLE_FIXED___64_TABLE_LENGTH ((uint16_t)56 ) #define ARMBITREVINDEXTABLE_FIXED__128_TABLE_LENGTH ((uint16_t)112 ) #define ARMBITREVINDEXTABLE_FIXED__256_TABLE_LENGTH ((uint16_t)240 ) #define ARMBITREVINDEXTABLE_FIXED__512_TABLE_LENGTH ((uint16_t)480 ) #define ARMBITREVINDEXTABLE_FIXED_1024_TABLE_LENGTH ((uint16_t)992 ) #define ARMBITREVINDEXTABLE_FIXED_2048_TABLE_LENGTH ((uint16_t)1984) #define ARMBITREVINDEXTABLE_FIXED_4096_TABLE_LENGTH ((uint16_t)4032) extern const uint16_t armBitRevIndexTable_fixed_16[ARMBITREVINDEXTABLE_FIXED___16_TABLE_LENGTH]; extern const uint16_t armBitRevIndexTable_fixed_32[ARMBITREVINDEXTABLE_FIXED___32_TABLE_LENGTH]; extern const uint16_t armBitRevIndexTable_fixed_64[ARMBITREVINDEXTABLE_FIXED___64_TABLE_LENGTH]; extern const uint16_t armBitRevIndexTable_fixed_128[ARMBITREVINDEXTABLE_FIXED__128_TABLE_LENGTH]; extern const uint16_t armBitRevIndexTable_fixed_256[ARMBITREVINDEXTABLE_FIXED__256_TABLE_LENGTH]; extern const uint16_t armBitRevIndexTable_fixed_512[ARMBITREVINDEXTABLE_FIXED__512_TABLE_LENGTH]; extern const uint16_t armBitRevIndexTable_fixed_1024[ARMBITREVINDEXTABLE_FIXED_1024_TABLE_LENGTH]; extern const uint16_t armBitRevIndexTable_fixed_2048[ARMBITREVINDEXTABLE_FIXED_2048_TABLE_LENGTH]; extern const uint16_t armBitRevIndexTable_fixed_4096[ARMBITREVINDEXTABLE_FIXED_4096_TABLE_LENGTH]; /* Tables for Fast Math Sine and Cosine */ extern const float32_t sinTable_f32[FAST_MATH_TABLE_SIZE + 1]; extern const q31_t sinTable_q31[FAST_MATH_TABLE_SIZE + 1]; extern const q15_t sinTable_q15[FAST_MATH_TABLE_SIZE + 1]; #endif /* ARM_COMMON_TABLES_H */ ================================================ FILE: Zelig/mbed/TARGET_NUCLEO_F401RE/arm_const_structs.h ================================================ /* ---------------------------------------------------------------------- * Copyright (C) 2010-2014 ARM Limited. All rights reserved. * * $Date: 19. March 2015 * $Revision: V.1.4.5 * * Project: CMSIS DSP Library * Title: arm_const_structs.h * * Description: This file has constant structs that are initialized for * user convenience. For example, some can be given as * arguments to the arm_cfft_f32() function. * * Target Processor: Cortex-M4/Cortex-M3 * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * - Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * - Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * - Neither the name of ARM LIMITED nor the names of its contributors * may be used to endorse or promote products derived from this * software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * -------------------------------------------------------------------- */ #ifndef _ARM_CONST_STRUCTS_H #define _ARM_CONST_STRUCTS_H #include "arm_math.h" #include "arm_common_tables.h" extern const arm_cfft_instance_f32 arm_cfft_sR_f32_len16; extern const arm_cfft_instance_f32 arm_cfft_sR_f32_len32; extern const arm_cfft_instance_f32 arm_cfft_sR_f32_len64; extern const arm_cfft_instance_f32 arm_cfft_sR_f32_len128; extern const arm_cfft_instance_f32 arm_cfft_sR_f32_len256; extern const arm_cfft_instance_f32 arm_cfft_sR_f32_len512; extern const arm_cfft_instance_f32 arm_cfft_sR_f32_len1024; extern const arm_cfft_instance_f32 arm_cfft_sR_f32_len2048; extern const arm_cfft_instance_f32 arm_cfft_sR_f32_len4096; extern const arm_cfft_instance_q31 arm_cfft_sR_q31_len16; extern const arm_cfft_instance_q31 arm_cfft_sR_q31_len32; extern const arm_cfft_instance_q31 arm_cfft_sR_q31_len64; extern const arm_cfft_instance_q31 arm_cfft_sR_q31_len128; extern const arm_cfft_instance_q31 arm_cfft_sR_q31_len256; extern const arm_cfft_instance_q31 arm_cfft_sR_q31_len512; extern const arm_cfft_instance_q31 arm_cfft_sR_q31_len1024; extern const arm_cfft_instance_q31 arm_cfft_sR_q31_len2048; extern const arm_cfft_instance_q31 arm_cfft_sR_q31_len4096; extern const arm_cfft_instance_q15 arm_cfft_sR_q15_len16; extern const arm_cfft_instance_q15 arm_cfft_sR_q15_len32; extern const arm_cfft_instance_q15 arm_cfft_sR_q15_len64; extern const arm_cfft_instance_q15 arm_cfft_sR_q15_len128; extern const arm_cfft_instance_q15 arm_cfft_sR_q15_len256; extern const arm_cfft_instance_q15 arm_cfft_sR_q15_len512; extern const arm_cfft_instance_q15 arm_cfft_sR_q15_len1024; extern const arm_cfft_instance_q15 arm_cfft_sR_q15_len2048; extern const arm_cfft_instance_q15 arm_cfft_sR_q15_len4096; #endif ================================================ FILE: Zelig/mbed/TARGET_NUCLEO_F401RE/arm_math.h ================================================ /* ---------------------------------------------------------------------- * Copyright (C) 2010-2015 ARM Limited. All rights reserved. * * $Date: 19. March 2015 * $Revision: V.1.4.5 * * Project: CMSIS DSP Library * Title: arm_math.h * * Description: Public header file for CMSIS DSP Library * * Target Processor: Cortex-M7/Cortex-M4/Cortex-M3/Cortex-M0 * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * - Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * - Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * - Neither the name of ARM LIMITED nor the names of its contributors * may be used to endorse or promote products derived from this * software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * -------------------------------------------------------------------- */ /** \mainpage CMSIS DSP Software Library * * Introduction * ------------ * * This user manual describes the CMSIS DSP software library, * a suite of common signal processing functions for use on Cortex-M processor based devices. * * The library is divided into a number of functions each covering a specific category: * - Basic math functions * - Fast math functions * - Complex math functions * - Filters * - Matrix functions * - Transforms * - Motor control functions * - Statistical functions * - Support functions * - Interpolation functions * * The library has separate functions for operating on 8-bit integers, 16-bit integers, * 32-bit integer and 32-bit floating-point values. * * Using the Library * ------------ * * The library installer contains prebuilt versions of the libraries in the Lib folder. * - arm_cortexM7lfdp_math.lib (Little endian and Double Precision Floating Point Unit on Cortex-M7) * - arm_cortexM7bfdp_math.lib (Big endian and Double Precision Floating Point Unit on Cortex-M7) * - arm_cortexM7lfsp_math.lib (Little endian and Single Precision Floating Point Unit on Cortex-M7) * - arm_cortexM7bfsp_math.lib (Big endian and Single Precision Floating Point Unit on Cortex-M7) * - arm_cortexM7l_math.lib (Little endian on Cortex-M7) * - arm_cortexM7b_math.lib (Big endian on Cortex-M7) * - arm_cortexM4lf_math.lib (Little endian and Floating Point Unit on Cortex-M4) * - arm_cortexM4bf_math.lib (Big endian and Floating Point Unit on Cortex-M4) * - arm_cortexM4l_math.lib (Little endian on Cortex-M4) * - arm_cortexM4b_math.lib (Big endian on Cortex-M4) * - arm_cortexM3l_math.lib (Little endian on Cortex-M3) * - arm_cortexM3b_math.lib (Big endian on Cortex-M3) * - arm_cortexM0l_math.lib (Little endian on Cortex-M0 / CortexM0+) * - arm_cortexM0b_math.lib (Big endian on Cortex-M0 / CortexM0+) * * The library functions are declared in the public file arm_math.h which is placed in the Include folder. * Simply include this file and link the appropriate library in the application and begin calling the library functions. The Library supports single * public header file arm_math.h for Cortex-M7/M4/M3/M0/M0+ with little endian and big endian. Same header file will be used for floating point unit(FPU) variants. * Define the appropriate pre processor MACRO ARM_MATH_CM7 or ARM_MATH_CM4 or ARM_MATH_CM3 or * ARM_MATH_CM0 or ARM_MATH_CM0PLUS depending on the target processor in the application. * * Examples * -------- * * The library ships with a number of examples which demonstrate how to use the library functions. * * Toolchain Support * ------------ * * The library has been developed and tested with MDK-ARM version 5.14.0.0 * The library is being tested in GCC and IAR toolchains and updates on this activity will be made available shortly. * * Building the Library * ------------ * * The library installer contains a project file to re build libraries on MDK-ARM Tool chain in the CMSIS\\DSP_Lib\\Source\\ARM folder. * - arm_cortexM_math.uvprojx * * * The libraries can be built by opening the arm_cortexM_math.uvprojx project in MDK-ARM, selecting a specific target, and defining the optional pre processor MACROs detailed above. * * Pre-processor Macros * ------------ * * Each library project have differant pre-processor macros. * * - UNALIGNED_SUPPORT_DISABLE: * * Define macro UNALIGNED_SUPPORT_DISABLE, If the silicon does not support unaligned memory access * * - ARM_MATH_BIG_ENDIAN: * * Define macro ARM_MATH_BIG_ENDIAN to build the library for big endian targets. By default library builds for little endian targets. * * - ARM_MATH_MATRIX_CHECK: * * Define macro ARM_MATH_MATRIX_CHECK for checking on the input and output sizes of matrices * * - ARM_MATH_ROUNDING: * * Define macro ARM_MATH_ROUNDING for rounding on support functions * * - ARM_MATH_CMx: * * Define macro ARM_MATH_CM4 for building the library on Cortex-M4 target, ARM_MATH_CM3 for building library on Cortex-M3 target * and ARM_MATH_CM0 for building library on Cortex-M0 target, ARM_MATH_CM0PLUS for building library on Cortex-M0+ target, and * ARM_MATH_CM7 for building the library on cortex-M7. * * - __FPU_PRESENT: * * Initialize macro __FPU_PRESENT = 1 when building on FPU supported Targets. Enable this macro for M4bf and M4lf libraries * *
* CMSIS-DSP in ARM::CMSIS Pack * ----------------------------- * * The following files relevant to CMSIS-DSP are present in the ARM::CMSIS Pack directories: * |File/Folder |Content | * |------------------------------|------------------------------------------------------------------------| * |\b CMSIS\\Documentation\\DSP | This documentation | * |\b CMSIS\\DSP_Lib | Software license agreement (license.txt) | * |\b CMSIS\\DSP_Lib\\Examples | Example projects demonstrating the usage of the library functions | * |\b CMSIS\\DSP_Lib\\Source | Source files for rebuilding the library | * *
* Revision History of CMSIS-DSP * ------------ * Please refer to \ref ChangeLog_pg. * * Copyright Notice * ------------ * * Copyright (C) 2010-2015 ARM Limited. All rights reserved. */ /** * @defgroup groupMath Basic Math Functions */ /** * @defgroup groupFastMath Fast Math Functions * This set of functions provides a fast approximation to sine, cosine, and square root. * As compared to most of the other functions in the CMSIS math library, the fast math functions * operate on individual values and not arrays. * There are separate functions for Q15, Q31, and floating-point data. * */ /** * @defgroup groupCmplxMath Complex Math Functions * This set of functions operates on complex data vectors. * The data in the complex arrays is stored in an interleaved fashion * (real, imag, real, imag, ...). * In the API functions, the number of samples in a complex array refers * to the number of complex values; the array contains twice this number of * real values. */ /** * @defgroup groupFilters Filtering Functions */ /** * @defgroup groupMatrix Matrix Functions * * This set of functions provides basic matrix math operations. * The functions operate on matrix data structures. For example, * the type * definition for the floating-point matrix structure is shown * below: *
 *     typedef struct
 *     {
 *       uint16_t numRows;     // number of rows of the matrix.
 *       uint16_t numCols;     // number of columns of the matrix.
 *       float32_t *pData;     // points to the data of the matrix.
 *     } arm_matrix_instance_f32;
 * 
* There are similar definitions for Q15 and Q31 data types. * * The structure specifies the size of the matrix and then points to * an array of data. The array is of size numRows X numCols * and the values are arranged in row order. That is, the * matrix element (i, j) is stored at: *
 *     pData[i*numCols + j]
 * 
* * \par Init Functions * There is an associated initialization function for each type of matrix * data structure. * The initialization function sets the values of the internal structure fields. * Refer to the function arm_mat_init_f32(), arm_mat_init_q31() * and arm_mat_init_q15() for floating-point, Q31 and Q15 types, respectively. * * \par * Use of the initialization function is optional. However, if initialization function is used * then the instance structure cannot be placed into a const data section. * To place the instance structure in a const data * section, manually initialize the data structure. For example: *
 * arm_matrix_instance_f32 S = {nRows, nColumns, pData};
 * arm_matrix_instance_q31 S = {nRows, nColumns, pData};
 * arm_matrix_instance_q15 S = {nRows, nColumns, pData};
 * 
* where nRows specifies the number of rows, nColumns * specifies the number of columns, and pData points to the * data array. * * \par Size Checking * By default all of the matrix functions perform size checking on the input and * output matrices. For example, the matrix addition function verifies that the * two input matrices and the output matrix all have the same number of rows and * columns. If the size check fails the functions return: *
 *     ARM_MATH_SIZE_MISMATCH
 * 
* Otherwise the functions return *
 *     ARM_MATH_SUCCESS
 * 
* There is some overhead associated with this matrix size checking. * The matrix size checking is enabled via the \#define *
 *     ARM_MATH_MATRIX_CHECK
 * 
* within the library project settings. By default this macro is defined * and size checking is enabled. By changing the project settings and * undefining this macro size checking is eliminated and the functions * run a bit faster. With size checking disabled the functions always * return ARM_MATH_SUCCESS. */ /** * @defgroup groupTransforms Transform Functions */ /** * @defgroup groupController Controller Functions */ /** * @defgroup groupStats Statistics Functions */ /** * @defgroup groupSupport Support Functions */ /** * @defgroup groupInterpolation Interpolation Functions * These functions perform 1- and 2-dimensional interpolation of data. * Linear interpolation is used for 1-dimensional data and * bilinear interpolation is used for 2-dimensional data. */ /** * @defgroup groupExamples Examples */ #ifndef _ARM_MATH_H #define _ARM_MATH_H #define __CMSIS_GENERIC /* disable NVIC and Systick functions */ #if defined(ARM_MATH_CM7) #include "core_cm7.h" #elif defined (ARM_MATH_CM4) #include "core_cm4.h" #elif defined (ARM_MATH_CM3) #include "core_cm3.h" #elif defined (ARM_MATH_CM0) #include "core_cm0.h" #define ARM_MATH_CM0_FAMILY #elif defined (ARM_MATH_CM0PLUS) #include "core_cm0plus.h" #define ARM_MATH_CM0_FAMILY #else #error "Define according the used Cortex core ARM_MATH_CM7, ARM_MATH_CM4, ARM_MATH_CM3, ARM_MATH_CM0PLUS or ARM_MATH_CM0" #endif #undef __CMSIS_GENERIC /* enable NVIC and Systick functions */ #include "string.h" #include "math.h" #ifdef __cplusplus extern "C" { #endif /** * @brief Macros required for reciprocal calculation in Normalized LMS */ #define DELTA_Q31 (0x100) #define DELTA_Q15 0x5 #define INDEX_MASK 0x0000003F #ifndef PI #define PI 3.14159265358979f #endif /** * @brief Macros required for SINE and COSINE Fast math approximations */ #define FAST_MATH_TABLE_SIZE 512 #define FAST_MATH_Q31_SHIFT (32 - 10) #define FAST_MATH_Q15_SHIFT (16 - 10) #define CONTROLLER_Q31_SHIFT (32 - 9) #define TABLE_SIZE 256 #define TABLE_SPACING_Q31 0x400000 #define TABLE_SPACING_Q15 0x80 /** * @brief Macros required for SINE and COSINE Controller functions */ /* 1.31(q31) Fixed value of 2/360 */ /* -1 to +1 is divided into 360 values so total spacing is (2/360) */ #define INPUT_SPACING 0xB60B61 /** * @brief Macro for Unaligned Support */ #ifndef UNALIGNED_SUPPORT_DISABLE #define ALIGN4 #else #if defined (__GNUC__) #define ALIGN4 __attribute__((aligned(4))) #else #define ALIGN4 __align(4) #endif #endif /* #ifndef UNALIGNED_SUPPORT_DISABLE */ /** * @brief Error status returned by some functions in the library. */ typedef enum { ARM_MATH_SUCCESS = 0, /**< No error */ ARM_MATH_ARGUMENT_ERROR = -1, /**< One or more arguments are incorrect */ ARM_MATH_LENGTH_ERROR = -2, /**< Length of data buffer is incorrect */ ARM_MATH_SIZE_MISMATCH = -3, /**< Size of matrices is not compatible with the operation. */ ARM_MATH_NANINF = -4, /**< Not-a-number (NaN) or infinity is generated */ ARM_MATH_SINGULAR = -5, /**< Generated by matrix inversion if the input matrix is singular and cannot be inverted. */ ARM_MATH_TEST_FAILURE = -6 /**< Test Failed */ } arm_status; /** * @brief 8-bit fractional data type in 1.7 format. */ typedef int8_t q7_t; /** * @brief 16-bit fractional data type in 1.15 format. */ typedef int16_t q15_t; /** * @brief 32-bit fractional data type in 1.31 format. */ typedef int32_t q31_t; /** * @brief 64-bit fractional data type in 1.63 format. */ typedef int64_t q63_t; /** * @brief 32-bit floating-point type definition. */ typedef float float32_t; /** * @brief 64-bit floating-point type definition. */ typedef double float64_t; /** * @brief definition to read/write two 16 bit values. */ #if defined __CC_ARM #define __SIMD32_TYPE int32_t __packed #define CMSIS_UNUSED __attribute__((unused)) #elif defined __ICCARM__ #define __SIMD32_TYPE int32_t __packed #define CMSIS_UNUSED #elif defined __GNUC__ #define __SIMD32_TYPE int32_t #define CMSIS_UNUSED __attribute__((unused)) #elif defined __CSMC__ /* Cosmic */ #define __SIMD32_TYPE int32_t #define CMSIS_UNUSED #elif defined __TASKING__ #define __SIMD32_TYPE __unaligned int32_t #define CMSIS_UNUSED #else #error Unknown compiler #endif #define __SIMD32(addr) (*(__SIMD32_TYPE **) & (addr)) #define __SIMD32_CONST(addr) ((__SIMD32_TYPE *)(addr)) #define _SIMD32_OFFSET(addr) (*(__SIMD32_TYPE *) (addr)) #define __SIMD64(addr) (*(int64_t **) & (addr)) #if defined (ARM_MATH_CM3) || defined (ARM_MATH_CM0_FAMILY) /** * @brief definition to pack two 16 bit values. */ #define __PKHBT(ARG1, ARG2, ARG3) ( (((int32_t)(ARG1) << 0) & (int32_t)0x0000FFFF) | \ (((int32_t)(ARG2) << ARG3) & (int32_t)0xFFFF0000) ) #define __PKHTB(ARG1, ARG2, ARG3) ( (((int32_t)(ARG1) << 0) & (int32_t)0xFFFF0000) | \ (((int32_t)(ARG2) >> ARG3) & (int32_t)0x0000FFFF) ) #endif /** * @brief definition to pack four 8 bit values. */ #ifndef ARM_MATH_BIG_ENDIAN #define __PACKq7(v0,v1,v2,v3) ( (((int32_t)(v0) << 0) & (int32_t)0x000000FF) | \ (((int32_t)(v1) << 8) & (int32_t)0x0000FF00) | \ (((int32_t)(v2) << 16) & (int32_t)0x00FF0000) | \ (((int32_t)(v3) << 24) & (int32_t)0xFF000000) ) #else #define __PACKq7(v0,v1,v2,v3) ( (((int32_t)(v3) << 0) & (int32_t)0x000000FF) | \ (((int32_t)(v2) << 8) & (int32_t)0x0000FF00) | \ (((int32_t)(v1) << 16) & (int32_t)0x00FF0000) | \ (((int32_t)(v0) << 24) & (int32_t)0xFF000000) ) #endif /** * @brief Clips Q63 to Q31 values. */ static __INLINE q31_t clip_q63_to_q31( q63_t x) { return ((q31_t) (x >> 32) != ((q31_t) x >> 31)) ? ((0x7FFFFFFF ^ ((q31_t) (x >> 63)))) : (q31_t) x; } /** * @brief Clips Q63 to Q15 values. */ static __INLINE q15_t clip_q63_to_q15( q63_t x) { return ((q31_t) (x >> 32) != ((q31_t) x >> 31)) ? ((0x7FFF ^ ((q15_t) (x >> 63)))) : (q15_t) (x >> 15); } /** * @brief Clips Q31 to Q7 values. */ static __INLINE q7_t clip_q31_to_q7( q31_t x) { return ((q31_t) (x >> 24) != ((q31_t) x >> 23)) ? ((0x7F ^ ((q7_t) (x >> 31)))) : (q7_t) x; } /** * @brief Clips Q31 to Q15 values. */ static __INLINE q15_t clip_q31_to_q15( q31_t x) { return ((q31_t) (x >> 16) != ((q31_t) x >> 15)) ? ((0x7FFF ^ ((q15_t) (x >> 31)))) : (q15_t) x; } /** * @brief Multiplies 32 X 64 and returns 32 bit result in 2.30 format. */ static __INLINE q63_t mult32x64( q63_t x, q31_t y) { return ((((q63_t) (x & 0x00000000FFFFFFFF) * y) >> 32) + (((q63_t) (x >> 32) * y))); } //#if defined (ARM_MATH_CM0_FAMILY) && defined ( __CC_ARM ) //#define __CLZ __clz //#endif //note: function can be removed when all toolchain support __CLZ for Cortex-M0 #if defined (ARM_MATH_CM0_FAMILY) && ((defined (__ICCARM__)) ) static __INLINE uint32_t __CLZ( q31_t data); static __INLINE uint32_t __CLZ( q31_t data) { uint32_t count = 0; uint32_t mask = 0x80000000; while((data & mask) == 0) { count += 1u; mask = mask >> 1u; } return (count); } #endif /** * @brief Function to Calculates 1/in (reciprocal) value of Q31 Data type. */ static __INLINE uint32_t arm_recip_q31( q31_t in, q31_t * dst, q31_t * pRecipTable) { uint32_t out, tempVal; uint32_t index, i; uint32_t signBits; if(in > 0) { signBits = __CLZ(in) - 1; } else { signBits = __CLZ(-in) - 1; } /* Convert input sample to 1.31 format */ in = in << signBits; /* calculation of index for initial approximated Val */ index = (uint32_t) (in >> 24u); index = (index & INDEX_MASK); /* 1.31 with exp 1 */ out = pRecipTable[index]; /* calculation of reciprocal value */ /* running approximation for two iterations */ for (i = 0u; i < 2u; i++) { tempVal = (q31_t) (((q63_t) in * out) >> 31u); tempVal = 0x7FFFFFFF - tempVal; /* 1.31 with exp 1 */ //out = (q31_t) (((q63_t) out * tempVal) >> 30u); out = (q31_t) clip_q63_to_q31(((q63_t) out * tempVal) >> 30u); } /* write output */ *dst = out; /* return num of signbits of out = 1/in value */ return (signBits + 1u); } /** * @brief Function to Calculates 1/in (reciprocal) value of Q15 Data type. */ static __INLINE uint32_t arm_recip_q15( q15_t in, q15_t * dst, q15_t * pRecipTable) { uint32_t out = 0, tempVal = 0; uint32_t index = 0, i = 0; uint32_t signBits = 0; if(in > 0) { signBits = __CLZ(in) - 17; } else { signBits = __CLZ(-in) - 17; } /* Convert input sample to 1.15 format */ in = in << signBits; /* calculation of index for initial approximated Val */ index = in >> 8; index = (index & INDEX_MASK); /* 1.15 with exp 1 */ out = pRecipTable[index]; /* calculation of reciprocal value */ /* running approximation for two iterations */ for (i = 0; i < 2; i++) { tempVal = (q15_t) (((q31_t) in * out) >> 15); tempVal = 0x7FFF - tempVal; /* 1.15 with exp 1 */ out = (q15_t) (((q31_t) out * tempVal) >> 14); } /* write output */ *dst = out; /* return num of signbits of out = 1/in value */ return (signBits + 1); } /* * @brief C custom defined intrinisic function for only M0 processors */ #if defined(ARM_MATH_CM0_FAMILY) static __INLINE q31_t __SSAT( q31_t x, uint32_t y) { int32_t posMax, negMin; uint32_t i; posMax = 1; for (i = 0; i < (y - 1); i++) { posMax = posMax * 2; } if(x > 0) { posMax = (posMax - 1); if(x > posMax) { x = posMax; } } else { negMin = -posMax; if(x < negMin) { x = negMin; } } return (x); } #endif /* end of ARM_MATH_CM0_FAMILY */ /* * @brief C custom defined intrinsic function for M3 and M0 processors */ #if defined (ARM_MATH_CM3) || defined (ARM_MATH_CM0_FAMILY) /* * @brief C custom defined QADD8 for M3 and M0 processors */ static __INLINE q31_t __QADD8( q31_t x, q31_t y) { q31_t sum; q7_t r, s, t, u; r = (q7_t) x; s = (q7_t) y; r = __SSAT((q31_t) (r + s), 8); s = __SSAT(((q31_t) (((x << 16) >> 24) + ((y << 16) >> 24))), 8); t = __SSAT(((q31_t) (((x << 8) >> 24) + ((y << 8) >> 24))), 8); u = __SSAT(((q31_t) ((x >> 24) + (y >> 24))), 8); sum = (((q31_t) u << 24) & 0xFF000000) | (((q31_t) t << 16) & 0x00FF0000) | (((q31_t) s << 8) & 0x0000FF00) | (r & 0x000000FF); return sum; } /* * @brief C custom defined QSUB8 for M3 and M0 processors */ static __INLINE q31_t __QSUB8( q31_t x, q31_t y) { q31_t sum; q31_t r, s, t, u; r = (q7_t) x; s = (q7_t) y; r = __SSAT((r - s), 8); s = __SSAT(((q31_t) (((x << 16) >> 24) - ((y << 16) >> 24))), 8) << 8; t = __SSAT(((q31_t) (((x << 8) >> 24) - ((y << 8) >> 24))), 8) << 16; u = __SSAT(((q31_t) ((x >> 24) - (y >> 24))), 8) << 24; sum = (u & 0xFF000000) | (t & 0x00FF0000) | (s & 0x0000FF00) | (r & 0x000000FF); return sum; } /* * @brief C custom defined QADD16 for M3 and M0 processors */ /* * @brief C custom defined QADD16 for M3 and M0 processors */ static __INLINE q31_t __QADD16( q31_t x, q31_t y) { q31_t sum; q31_t r, s; r = (q15_t) x; s = (q15_t) y; r = __SSAT(r + s, 16); s = __SSAT(((q31_t) ((x >> 16) + (y >> 16))), 16) << 16; sum = (s & 0xFFFF0000) | (r & 0x0000FFFF); return sum; } /* * @brief C custom defined SHADD16 for M3 and M0 processors */ static __INLINE q31_t __SHADD16( q31_t x, q31_t y) { q31_t sum; q31_t r, s; r = (q15_t) x; s = (q15_t) y; r = ((r >> 1) + (s >> 1)); s = ((q31_t) ((x >> 17) + (y >> 17))) << 16; sum = (s & 0xFFFF0000) | (r & 0x0000FFFF); return sum; } /* * @brief C custom defined QSUB16 for M3 and M0 processors */ static __INLINE q31_t __QSUB16( q31_t x, q31_t y) { q31_t sum; q31_t r, s; r = (q15_t) x; s = (q15_t) y; r = __SSAT(r - s, 16); s = __SSAT(((q31_t) ((x >> 16) - (y >> 16))), 16) << 16; sum = (s & 0xFFFF0000) | (r & 0x0000FFFF); return sum; } /* * @brief C custom defined SHSUB16 for M3 and M0 processors */ static __INLINE q31_t __SHSUB16( q31_t x, q31_t y) { q31_t diff; q31_t r, s; r = (q15_t) x; s = (q15_t) y; r = ((r >> 1) - (s >> 1)); s = (((x >> 17) - (y >> 17)) << 16); diff = (s & 0xFFFF0000) | (r & 0x0000FFFF); return diff; } /* * @brief C custom defined QASX for M3 and M0 processors */ static __INLINE q31_t __QASX( q31_t x, q31_t y) { q31_t sum = 0; sum = ((sum + clip_q31_to_q15((q31_t) ((q15_t) (x >> 16) + (q15_t) y))) << 16) + clip_q31_to_q15((q31_t) ((q15_t) x - (q15_t) (y >> 16))); return sum; } /* * @brief C custom defined SHASX for M3 and M0 processors */ static __INLINE q31_t __SHASX( q31_t x, q31_t y) { q31_t sum; q31_t r, s; r = (q15_t) x; s = (q15_t) y; r = ((r >> 1) - (y >> 17)); s = (((x >> 17) + (s >> 1)) << 16); sum = (s & 0xFFFF0000) | (r & 0x0000FFFF); return sum; } /* * @brief C custom defined QSAX for M3 and M0 processors */ static __INLINE q31_t __QSAX( q31_t x, q31_t y) { q31_t sum = 0; sum = ((sum + clip_q31_to_q15((q31_t) ((q15_t) (x >> 16) - (q15_t) y))) << 16) + clip_q31_to_q15((q31_t) ((q15_t) x + (q15_t) (y >> 16))); return sum; } /* * @brief C custom defined SHSAX for M3 and M0 processors */ static __INLINE q31_t __SHSAX( q31_t x, q31_t y) { q31_t sum; q31_t r, s; r = (q15_t) x; s = (q15_t) y; r = ((r >> 1) + (y >> 17)); s = (((x >> 17) - (s >> 1)) << 16); sum = (s & 0xFFFF0000) | (r & 0x0000FFFF); return sum; } /* * @brief C custom defined SMUSDX for M3 and M0 processors */ static __INLINE q31_t __SMUSDX( q31_t x, q31_t y) { return ((q31_t) (((q15_t) x * (q15_t) (y >> 16)) - ((q15_t) (x >> 16) * (q15_t) y))); } /* * @brief C custom defined SMUADX for M3 and M0 processors */ static __INLINE q31_t __SMUADX( q31_t x, q31_t y) { return ((q31_t) (((q15_t) x * (q15_t) (y >> 16)) + ((q15_t) (x >> 16) * (q15_t) y))); } /* * @brief C custom defined QADD for M3 and M0 processors */ static __INLINE q31_t __QADD( q31_t x, q31_t y) { return clip_q63_to_q31((q63_t) x + y); } /* * @brief C custom defined QSUB for M3 and M0 processors */ static __INLINE q31_t __QSUB( q31_t x, q31_t y) { return clip_q63_to_q31((q63_t) x - y); } /* * @brief C custom defined SMLAD for M3 and M0 processors */ static __INLINE q31_t __SMLAD( q31_t x, q31_t y, q31_t sum) { return (sum + ((q15_t) (x >> 16) * (q15_t) (y >> 16)) + ((q15_t) x * (q15_t) y)); } /* * @brief C custom defined SMLADX for M3 and M0 processors */ static __INLINE q31_t __SMLADX( q31_t x, q31_t y, q31_t sum) { return (sum + ((q15_t) (x >> 16) * (q15_t) (y)) + ((q15_t) x * (q15_t) (y >> 16))); } /* * @brief C custom defined SMLSDX for M3 and M0 processors */ static __INLINE q31_t __SMLSDX( q31_t x, q31_t y, q31_t sum) { return (sum - ((q15_t) (x >> 16) * (q15_t) (y)) + ((q15_t) x * (q15_t) (y >> 16))); } /* * @brief C custom defined SMLALD for M3 and M0 processors */ static __INLINE q63_t __SMLALD( q31_t x, q31_t y, q63_t sum) { return (sum + ((q15_t) (x >> 16) * (q15_t) (y >> 16)) + ((q15_t) x * (q15_t) y)); } /* * @brief C custom defined SMLALDX for M3 and M0 processors */ static __INLINE q63_t __SMLALDX( q31_t x, q31_t y, q63_t sum) { return (sum + ((q15_t) (x >> 16) * (q15_t) y)) + ((q15_t) x * (q15_t) (y >> 16)); } /* * @brief C custom defined SMUAD for M3 and M0 processors */ static __INLINE q31_t __SMUAD( q31_t x, q31_t y) { return (((x >> 16) * (y >> 16)) + (((x << 16) >> 16) * ((y << 16) >> 16))); } /* * @brief C custom defined SMUSD for M3 and M0 processors */ static __INLINE q31_t __SMUSD( q31_t x, q31_t y) { return (-((x >> 16) * (y >> 16)) + (((x << 16) >> 16) * ((y << 16) >> 16))); } /* * @brief C custom defined SXTB16 for M3 and M0 processors */ static __INLINE q31_t __SXTB16( q31_t x) { return ((((x << 24) >> 24) & 0x0000FFFF) | (((x << 8) >> 8) & 0xFFFF0000)); } #endif /* defined (ARM_MATH_CM3) || defined (ARM_MATH_CM0_FAMILY) */ /** * @brief Instance structure for the Q7 FIR filter. */ typedef struct { uint16_t numTaps; /**< number of filter coefficients in the filter. */ q7_t *pState; /**< points to the state variable array. The array is of length numTaps+blockSize-1. */ q7_t *pCoeffs; /**< points to the coefficient array. The array is of length numTaps.*/ } arm_fir_instance_q7; /** * @brief Instance structure for the Q15 FIR filter. */ typedef struct { uint16_t numTaps; /**< number of filter coefficients in the filter. */ q15_t *pState; /**< points to the state variable array. The array is of length numTaps+blockSize-1. */ q15_t *pCoeffs; /**< points to the coefficient array. The array is of length numTaps.*/ } arm_fir_instance_q15; /** * @brief Instance structure for the Q31 FIR filter. */ typedef struct { uint16_t numTaps; /**< number of filter coefficients in the filter. */ q31_t *pState; /**< points to the state variable array. The array is of length numTaps+blockSize-1. */ q31_t *pCoeffs; /**< points to the coefficient array. The array is of length numTaps. */ } arm_fir_instance_q31; /** * @brief Instance structure for the floating-point FIR filter. */ typedef struct { uint16_t numTaps; /**< number of filter coefficients in the filter. */ float32_t *pState; /**< points to the state variable array. The array is of length numTaps+blockSize-1. */ float32_t *pCoeffs; /**< points to the coefficient array. The array is of length numTaps. */ } arm_fir_instance_f32; /** * @brief Processing function for the Q7 FIR filter. * @param[in] *S points to an instance of the Q7 FIR filter structure. * @param[in] *pSrc points to the block of input data. * @param[out] *pDst points to the block of output data. * @param[in] blockSize number of samples to process. * @return none. */ void arm_fir_q7( const arm_fir_instance_q7 * S, q7_t * pSrc, q7_t * pDst, uint32_t blockSize); /** * @brief Initialization function for the Q7 FIR filter. * @param[in,out] *S points to an instance of the Q7 FIR structure. * @param[in] numTaps Number of filter coefficients in the filter. * @param[in] *pCoeffs points to the filter coefficients. * @param[in] *pState points to the state buffer. * @param[in] blockSize number of samples that are processed. * @return none */ void arm_fir_init_q7( arm_fir_instance_q7 * S, uint16_t numTaps, q7_t * pCoeffs, q7_t * pState, uint32_t blockSize); /** * @brief Processing function for the Q15 FIR filter. * @param[in] *S points to an instance of the Q15 FIR structure. * @param[in] *pSrc points to the block of input data. * @param[out] *pDst points to the block of output data. * @param[in] blockSize number of samples to process. * @return none. */ void arm_fir_q15( const arm_fir_instance_q15 * S, q15_t * pSrc, q15_t * pDst, uint32_t blockSize); /** * @brief Processing function for the fast Q15 FIR filter for Cortex-M3 and Cortex-M4. * @param[in] *S points to an instance of the Q15 FIR filter structure. * @param[in] *pSrc points to the block of input data. * @param[out] *pDst points to the block of output data. * @param[in] blockSize number of samples to process. * @return none. */ void arm_fir_fast_q15( const arm_fir_instance_q15 * S, q15_t * pSrc, q15_t * pDst, uint32_t blockSize); /** * @brief Initialization function for the Q15 FIR filter. * @param[in,out] *S points to an instance of the Q15 FIR filter structure. * @param[in] numTaps Number of filter coefficients in the filter. Must be even and greater than or equal to 4. * @param[in] *pCoeffs points to the filter coefficients. * @param[in] *pState points to the state buffer. * @param[in] blockSize number of samples that are processed at a time. * @return The function returns ARM_MATH_SUCCESS if initialization was successful or ARM_MATH_ARGUMENT_ERROR if * numTaps is not a supported value. */ arm_status arm_fir_init_q15( arm_fir_instance_q15 * S, uint16_t numTaps, q15_t * pCoeffs, q15_t * pState, uint32_t blockSize); /** * @brief Processing function for the Q31 FIR filter. * @param[in] *S points to an instance of the Q31 FIR filter structure. * @param[in] *pSrc points to the block of input data. * @param[out] *pDst points to the block of output data. * @param[in] blockSize number of samples to process. * @return none. */ void arm_fir_q31( const arm_fir_instance_q31 * S, q31_t * pSrc, q31_t * pDst, uint32_t blockSize); /** * @brief Processing function for the fast Q31 FIR filter for Cortex-M3 and Cortex-M4. * @param[in] *S points to an instance of the Q31 FIR structure. * @param[in] *pSrc points to the block of input data. * @param[out] *pDst points to the block of output data. * @param[in] blockSize number of samples to process. * @return none. */ void arm_fir_fast_q31( const arm_fir_instance_q31 * S, q31_t * pSrc, q31_t * pDst, uint32_t blockSize); /** * @brief Initialization function for the Q31 FIR filter. * @param[in,out] *S points to an instance of the Q31 FIR structure. * @param[in] numTaps Number of filter coefficients in the filter. * @param[in] *pCoeffs points to the filter coefficients. * @param[in] *pState points to the state buffer. * @param[in] blockSize number of samples that are processed at a time. * @return none. */ void arm_fir_init_q31( arm_fir_instance_q31 * S, uint16_t numTaps, q31_t * pCoeffs, q31_t * pState, uint32_t blockSize); /** * @brief Processing function for the floating-point FIR filter. * @param[in] *S points to an instance of the floating-point FIR structure. * @param[in] *pSrc points to the block of input data. * @param[out] *pDst points to the block of output data. * @param[in] blockSize number of samples to process. * @return none. */ void arm_fir_f32( const arm_fir_instance_f32 * S, float32_t * pSrc, float32_t * pDst, uint32_t blockSize); /** * @brief Initialization function for the floating-point FIR filter. * @param[in,out] *S points to an instance of the floating-point FIR filter structure. * @param[in] numTaps Number of filter coefficients in the filter. * @param[in] *pCoeffs points to the filter coefficients. * @param[in] *pState points to the state buffer. * @param[in] blockSize number of samples that are processed at a time. * @return none. */ void arm_fir_init_f32( arm_fir_instance_f32 * S, uint16_t numTaps, float32_t * pCoeffs, float32_t * pState, uint32_t blockSize); /** * @brief Instance structure for the Q15 Biquad cascade filter. */ typedef struct { int8_t numStages; /**< number of 2nd order stages in the filter. Overall order is 2*numStages. */ q15_t *pState; /**< Points to the array of state coefficients. The array is of length 4*numStages. */ q15_t *pCoeffs; /**< Points to the array of coefficients. The array is of length 5*numStages. */ int8_t postShift; /**< Additional shift, in bits, applied to each output sample. */ } arm_biquad_casd_df1_inst_q15; /** * @brief Instance structure for the Q31 Biquad cascade filter. */ typedef struct { uint32_t numStages; /**< number of 2nd order stages in the filter. Overall order is 2*numStages. */ q31_t *pState; /**< Points to the array of state coefficients. The array is of length 4*numStages. */ q31_t *pCoeffs; /**< Points to the array of coefficients. The array is of length 5*numStages. */ uint8_t postShift; /**< Additional shift, in bits, applied to each output sample. */ } arm_biquad_casd_df1_inst_q31; /** * @brief Instance structure for the floating-point Biquad cascade filter. */ typedef struct { uint32_t numStages; /**< number of 2nd order stages in the filter. Overall order is 2*numStages. */ float32_t *pState; /**< Points to the array of state coefficients. The array is of length 4*numStages. */ float32_t *pCoeffs; /**< Points to the array of coefficients. The array is of length 5*numStages. */ } arm_biquad_casd_df1_inst_f32; /** * @brief Processing function for the Q15 Biquad cascade filter. * @param[in] *S points to an instance of the Q15 Biquad cascade structure. * @param[in] *pSrc points to the block of input data. * @param[out] *pDst points to the block of output data. * @param[in] blockSize number of samples to process. * @return none. */ void arm_biquad_cascade_df1_q15( const arm_biquad_casd_df1_inst_q15 * S, q15_t * pSrc, q15_t * pDst, uint32_t blockSize); /** * @brief Initialization function for the Q15 Biquad cascade filter. * @param[in,out] *S points to an instance of the Q15 Biquad cascade structure. * @param[in] numStages number of 2nd order stages in the filter. * @param[in] *pCoeffs points to the filter coefficients. * @param[in] *pState points to the state buffer. * @param[in] postShift Shift to be applied to the output. Varies according to the coefficients format * @return none */ void arm_biquad_cascade_df1_init_q15( arm_biquad_casd_df1_inst_q15 * S, uint8_t numStages, q15_t * pCoeffs, q15_t * pState, int8_t postShift); /** * @brief Fast but less precise processing function for the Q15 Biquad cascade filter for Cortex-M3 and Cortex-M4. * @param[in] *S points to an instance of the Q15 Biquad cascade structure. * @param[in] *pSrc points to the block of input data. * @param[out] *pDst points to the block of output data. * @param[in] blockSize number of samples to process. * @return none. */ void arm_biquad_cascade_df1_fast_q15( const arm_biquad_casd_df1_inst_q15 * S, q15_t * pSrc, q15_t * pDst, uint32_t blockSize); /** * @brief Processing function for the Q31 Biquad cascade filter * @param[in] *S points to an instance of the Q31 Biquad cascade structure. * @param[in] *pSrc points to the block of input data. * @param[out] *pDst points to the block of output data. * @param[in] blockSize number of samples to process. * @return none. */ void arm_biquad_cascade_df1_q31( const arm_biquad_casd_df1_inst_q31 * S, q31_t * pSrc, q31_t * pDst, uint32_t blockSize); /** * @brief Fast but less precise processing function for the Q31 Biquad cascade filter for Cortex-M3 and Cortex-M4. * @param[in] *S points to an instance of the Q31 Biquad cascade structure. * @param[in] *pSrc points to the block of input data. * @param[out] *pDst points to the block of output data. * @param[in] blockSize number of samples to process. * @return none. */ void arm_biquad_cascade_df1_fast_q31( const arm_biquad_casd_df1_inst_q31 * S, q31_t * pSrc, q31_t * pDst, uint32_t blockSize); /** * @brief Initialization function for the Q31 Biquad cascade filter. * @param[in,out] *S points to an instance of the Q31 Biquad cascade structure. * @param[in] numStages number of 2nd order stages in the filter. * @param[in] *pCoeffs points to the filter coefficients. * @param[in] *pState points to the state buffer. * @param[in] postShift Shift to be applied to the output. Varies according to the coefficients format * @return none */ void arm_biquad_cascade_df1_init_q31( arm_biquad_casd_df1_inst_q31 * S, uint8_t numStages, q31_t * pCoeffs, q31_t * pState, int8_t postShift); /** * @brief Processing function for the floating-point Biquad cascade filter. * @param[in] *S points to an instance of the floating-point Biquad cascade structure. * @param[in] *pSrc points to the block of input data. * @param[out] *pDst points to the block of output data. * @param[in] blockSize number of samples to process. * @return none. */ void arm_biquad_cascade_df1_f32( const arm_biquad_casd_df1_inst_f32 * S, float32_t * pSrc, float32_t * pDst, uint32_t blockSize); /** * @brief Initialization function for the floating-point Biquad cascade filter. * @param[in,out] *S points to an instance of the floating-point Biquad cascade structure. * @param[in] numStages number of 2nd order stages in the filter. * @param[in] *pCoeffs points to the filter coefficients. * @param[in] *pState points to the state buffer. * @return none */ void arm_biquad_cascade_df1_init_f32( arm_biquad_casd_df1_inst_f32 * S, uint8_t numStages, float32_t * pCoeffs, float32_t * pState); /** * @brief Instance structure for the floating-point matrix structure. */ typedef struct { uint16_t numRows; /**< number of rows of the matrix. */ uint16_t numCols; /**< number of columns of the matrix. */ float32_t *pData; /**< points to the data of the matrix. */ } arm_matrix_instance_f32; /** * @brief Instance structure for the floating-point matrix structure. */ typedef struct { uint16_t numRows; /**< number of rows of the matrix. */ uint16_t numCols; /**< number of columns of the matrix. */ float64_t *pData; /**< points to the data of the matrix. */ } arm_matrix_instance_f64; /** * @brief Instance structure for the Q15 matrix structure. */ typedef struct { uint16_t numRows; /**< number of rows of the matrix. */ uint16_t numCols; /**< number of columns of the matrix. */ q15_t *pData; /**< points to the data of the matrix. */ } arm_matrix_instance_q15; /** * @brief Instance structure for the Q31 matrix structure. */ typedef struct { uint16_t numRows; /**< number of rows of the matrix. */ uint16_t numCols; /**< number of columns of the matrix. */ q31_t *pData; /**< points to the data of the matrix. */ } arm_matrix_instance_q31; /** * @brief Floating-point matrix addition. * @param[in] *pSrcA points to the first input matrix structure * @param[in] *pSrcB points to the second input matrix structure * @param[out] *pDst points to output matrix structure * @return The function returns either * ARM_MATH_SIZE_MISMATCH or ARM_MATH_SUCCESS based on the outcome of size checking. */ arm_status arm_mat_add_f32( const arm_matrix_instance_f32 * pSrcA, const arm_matrix_instance_f32 * pSrcB, arm_matrix_instance_f32 * pDst); /** * @brief Q15 matrix addition. * @param[in] *pSrcA points to the first input matrix structure * @param[in] *pSrcB points to the second input matrix structure * @param[out] *pDst points to output matrix structure * @return The function returns either * ARM_MATH_SIZE_MISMATCH or ARM_MATH_SUCCESS based on the outcome of size checking. */ arm_status arm_mat_add_q15( const arm_matrix_instance_q15 * pSrcA, const arm_matrix_instance_q15 * pSrcB, arm_matrix_instance_q15 * pDst); /** * @brief Q31 matrix addition. * @param[in] *pSrcA points to the first input matrix structure * @param[in] *pSrcB points to the second input matrix structure * @param[out] *pDst points to output matrix structure * @return The function returns either * ARM_MATH_SIZE_MISMATCH or ARM_MATH_SUCCESS based on the outcome of size checking. */ arm_status arm_mat_add_q31( const arm_matrix_instance_q31 * pSrcA, const arm_matrix_instance_q31 * pSrcB, arm_matrix_instance_q31 * pDst); /** * @brief Floating-point, complex, matrix multiplication. * @param[in] *pSrcA points to the first input matrix structure * @param[in] *pSrcB points to the second input matrix structure * @param[out] *pDst points to output matrix structure * @return The function returns either * ARM_MATH_SIZE_MISMATCH or ARM_MATH_SUCCESS based on the outcome of size checking. */ arm_status arm_mat_cmplx_mult_f32( const arm_matrix_instance_f32 * pSrcA, const arm_matrix_instance_f32 * pSrcB, arm_matrix_instance_f32 * pDst); /** * @brief Q15, complex, matrix multiplication. * @param[in] *pSrcA points to the first input matrix structure * @param[in] *pSrcB points to the second input matrix structure * @param[out] *pDst points to output matrix structure * @return The function returns either * ARM_MATH_SIZE_MISMATCH or ARM_MATH_SUCCESS based on the outcome of size checking. */ arm_status arm_mat_cmplx_mult_q15( const arm_matrix_instance_q15 * pSrcA, const arm_matrix_instance_q15 * pSrcB, arm_matrix_instance_q15 * pDst, q15_t * pScratch); /** * @brief Q31, complex, matrix multiplication. * @param[in] *pSrcA points to the first input matrix structure * @param[in] *pSrcB points to the second input matrix structure * @param[out] *pDst points to output matrix structure * @return The function returns either * ARM_MATH_SIZE_MISMATCH or ARM_MATH_SUCCESS based on the outcome of size checking. */ arm_status arm_mat_cmplx_mult_q31( const arm_matrix_instance_q31 * pSrcA, const arm_matrix_instance_q31 * pSrcB, arm_matrix_instance_q31 * pDst); /** * @brief Floating-point matrix transpose. * @param[in] *pSrc points to the input matrix * @param[out] *pDst points to the output matrix * @return The function returns either ARM_MATH_SIZE_MISMATCH * or ARM_MATH_SUCCESS based on the outcome of size checking. */ arm_status arm_mat_trans_f32( const arm_matrix_instance_f32 * pSrc, arm_matrix_instance_f32 * pDst); /** * @brief Q15 matrix transpose. * @param[in] *pSrc points to the input matrix * @param[out] *pDst points to the output matrix * @return The function returns either ARM_MATH_SIZE_MISMATCH * or ARM_MATH_SUCCESS based on the outcome of size checking. */ arm_status arm_mat_trans_q15( const arm_matrix_instance_q15 * pSrc, arm_matrix_instance_q15 * pDst); /** * @brief Q31 matrix transpose. * @param[in] *pSrc points to the input matrix * @param[out] *pDst points to the output matrix * @return The function returns either ARM_MATH_SIZE_MISMATCH * or ARM_MATH_SUCCESS based on the outcome of size checking. */ arm_status arm_mat_trans_q31( const arm_matrix_instance_q31 * pSrc, arm_matrix_instance_q31 * pDst); /** * @brief Floating-point matrix multiplication * @param[in] *pSrcA points to the first input matrix structure * @param[in] *pSrcB points to the second input matrix structure * @param[out] *pDst points to output matrix structure * @return The function returns either * ARM_MATH_SIZE_MISMATCH or ARM_MATH_SUCCESS based on the outcome of size checking. */ arm_status arm_mat_mult_f32( const arm_matrix_instance_f32 * pSrcA, const arm_matrix_instance_f32 * pSrcB, arm_matrix_instance_f32 * pDst); /** * @brief Q15 matrix multiplication * @param[in] *pSrcA points to the first input matrix structure * @param[in] *pSrcB points to the second input matrix structure * @param[out] *pDst points to output matrix structure * @param[in] *pState points to the array for storing intermediate results * @return The function returns either * ARM_MATH_SIZE_MISMATCH or ARM_MATH_SUCCESS based on the outcome of size checking. */ arm_status arm_mat_mult_q15( const arm_matrix_instance_q15 * pSrcA, const arm_matrix_instance_q15 * pSrcB, arm_matrix_instance_q15 * pDst, q15_t * pState); /** * @brief Q15 matrix multiplication (fast variant) for Cortex-M3 and Cortex-M4 * @param[in] *pSrcA points to the first input matrix structure * @param[in] *pSrcB points to the second input matrix structure * @param[out] *pDst points to output matrix structure * @param[in] *pState points to the array for storing intermediate results * @return The function returns either * ARM_MATH_SIZE_MISMATCH or ARM_MATH_SUCCESS based on the outcome of size checking. */ arm_status arm_mat_mult_fast_q15( const arm_matrix_instance_q15 * pSrcA, const arm_matrix_instance_q15 * pSrcB, arm_matrix_instance_q15 * pDst, q15_t * pState); /** * @brief Q31 matrix multiplication * @param[in] *pSrcA points to the first input matrix structure * @param[in] *pSrcB points to the second input matrix structure * @param[out] *pDst points to output matrix structure * @return The function returns either * ARM_MATH_SIZE_MISMATCH or ARM_MATH_SUCCESS based on the outcome of size checking. */ arm_status arm_mat_mult_q31( const arm_matrix_instance_q31 * pSrcA, const arm_matrix_instance_q31 * pSrcB, arm_matrix_instance_q31 * pDst); /** * @brief Q31 matrix multiplication (fast variant) for Cortex-M3 and Cortex-M4 * @param[in] *pSrcA points to the first input matrix structure * @param[in] *pSrcB points to the second input matrix structure * @param[out] *pDst points to output matrix structure * @return The function returns either * ARM_MATH_SIZE_MISMATCH or ARM_MATH_SUCCESS based on the outcome of size checking. */ arm_status arm_mat_mult_fast_q31( const arm_matrix_instance_q31 * pSrcA, const arm_matrix_instance_q31 * pSrcB, arm_matrix_instance_q31 * pDst); /** * @brief Floating-point matrix subtraction * @param[in] *pSrcA points to the first input matrix structure * @param[in] *pSrcB points to the second input matrix structure * @param[out] *pDst points to output matrix structure * @return The function returns either * ARM_MATH_SIZE_MISMATCH or ARM_MATH_SUCCESS based on the outcome of size checking. */ arm_status arm_mat_sub_f32( const arm_matrix_instance_f32 * pSrcA, const arm_matrix_instance_f32 * pSrcB, arm_matrix_instance_f32 * pDst); /** * @brief Q15 matrix subtraction * @param[in] *pSrcA points to the first input matrix structure * @param[in] *pSrcB points to the second input matrix structure * @param[out] *pDst points to output matrix structure * @return The function returns either * ARM_MATH_SIZE_MISMATCH or ARM_MATH_SUCCESS based on the outcome of size checking. */ arm_status arm_mat_sub_q15( const arm_matrix_instance_q15 * pSrcA, const arm_matrix_instance_q15 * pSrcB, arm_matrix_instance_q15 * pDst); /** * @brief Q31 matrix subtraction * @param[in] *pSrcA points to the first input matrix structure * @param[in] *pSrcB points to the second input matrix structure * @param[out] *pDst points to output matrix structure * @return The function returns either * ARM_MATH_SIZE_MISMATCH or ARM_MATH_SUCCESS based on the outcome of size checking. */ arm_status arm_mat_sub_q31( const arm_matrix_instance_q31 * pSrcA, const arm_matrix_instance_q31 * pSrcB, arm_matrix_instance_q31 * pDst); /** * @brief Floating-point matrix scaling. * @param[in] *pSrc points to the input matrix * @param[in] scale scale factor * @param[out] *pDst points to the output matrix * @return The function returns either * ARM_MATH_SIZE_MISMATCH or ARM_MATH_SUCCESS based on the outcome of size checking. */ arm_status arm_mat_scale_f32( const arm_matrix_instance_f32 * pSrc, float32_t scale, arm_matrix_instance_f32 * pDst); /** * @brief Q15 matrix scaling. * @param[in] *pSrc points to input matrix * @param[in] scaleFract fractional portion of the scale factor * @param[in] shift number of bits to shift the result by * @param[out] *pDst points to output matrix * @return The function returns either * ARM_MATH_SIZE_MISMATCH or ARM_MATH_SUCCESS based on the outcome of size checking. */ arm_status arm_mat_scale_q15( const arm_matrix_instance_q15 * pSrc, q15_t scaleFract, int32_t shift, arm_matrix_instance_q15 * pDst); /** * @brief Q31 matrix scaling. * @param[in] *pSrc points to input matrix * @param[in] scaleFract fractional portion of the scale factor * @param[in] shift number of bits to shift the result by * @param[out] *pDst points to output matrix structure * @return The function returns either * ARM_MATH_SIZE_MISMATCH or ARM_MATH_SUCCESS based on the outcome of size checking. */ arm_status arm_mat_scale_q31( const arm_matrix_instance_q31 * pSrc, q31_t scaleFract, int32_t shift, arm_matrix_instance_q31 * pDst); /** * @brief Q31 matrix initialization. * @param[in,out] *S points to an instance of the floating-point matrix structure. * @param[in] nRows number of rows in the matrix. * @param[in] nColumns number of columns in the matrix. * @param[in] *pData points to the matrix data array. * @return none */ void arm_mat_init_q31( arm_matrix_instance_q31 * S, uint16_t nRows, uint16_t nColumns, q31_t * pData); /** * @brief Q15 matrix initialization. * @param[in,out] *S points to an instance of the floating-point matrix structure. * @param[in] nRows number of rows in the matrix. * @param[in] nColumns number of columns in the matrix. * @param[in] *pData points to the matrix data array. * @return none */ void arm_mat_init_q15( arm_matrix_instance_q15 * S, uint16_t nRows, uint16_t nColumns, q15_t * pData); /** * @brief Floating-point matrix initialization. * @param[in,out] *S points to an instance of the floating-point matrix structure. * @param[in] nRows number of rows in the matrix. * @param[in] nColumns number of columns in the matrix. * @param[in] *pData points to the matrix data array. * @return none */ void arm_mat_init_f32( arm_matrix_instance_f32 * S, uint16_t nRows, uint16_t nColumns, float32_t * pData); /** * @brief Instance structure for the Q15 PID Control. */ typedef struct { q15_t A0; /**< The derived gain, A0 = Kp + Ki + Kd . */ #ifdef ARM_MATH_CM0_FAMILY q15_t A1; q15_t A2; #else q31_t A1; /**< The derived gain A1 = -Kp - 2Kd | Kd.*/ #endif q15_t state[3]; /**< The state array of length 3. */ q15_t Kp; /**< The proportional gain. */ q15_t Ki; /**< The integral gain. */ q15_t Kd; /**< The derivative gain. */ } arm_pid_instance_q15; /** * @brief Instance structure for the Q31 PID Control. */ typedef struct { q31_t A0; /**< The derived gain, A0 = Kp + Ki + Kd . */ q31_t A1; /**< The derived gain, A1 = -Kp - 2Kd. */ q31_t A2; /**< The derived gain, A2 = Kd . */ q31_t state[3]; /**< The state array of length 3. */ q31_t Kp; /**< The proportional gain. */ q31_t Ki; /**< The integral gain. */ q31_t Kd; /**< The derivative gain. */ } arm_pid_instance_q31; /** * @brief Instance structure for the floating-point PID Control. */ typedef struct { float32_t A0; /**< The derived gain, A0 = Kp + Ki + Kd . */ float32_t A1; /**< The derived gain, A1 = -Kp - 2Kd. */ float32_t A2; /**< The derived gain, A2 = Kd . */ float32_t state[3]; /**< The state array of length 3. */ float32_t Kp; /**< The proportional gain. */ float32_t Ki; /**< The integral gain. */ float32_t Kd; /**< The derivative gain. */ } arm_pid_instance_f32; /** * @brief Initialization function for the floating-point PID Control. * @param[in,out] *S points to an instance of the PID structure. * @param[in] resetStateFlag flag to reset the state. 0 = no change in state 1 = reset the state. * @return none. */ void arm_pid_init_f32( arm_pid_instance_f32 * S, int32_t resetStateFlag); /** * @brief Reset function for the floating-point PID Control. * @param[in,out] *S is an instance of the floating-point PID Control structure * @return none */ void arm_pid_reset_f32( arm_pid_instance_f32 * S); /** * @brief Initialization function for the Q31 PID Control. * @param[in,out] *S points to an instance of the Q15 PID structure. * @param[in] resetStateFlag flag to reset the state. 0 = no change in state 1 = reset the state. * @return none. */ void arm_pid_init_q31( arm_pid_instance_q31 * S, int32_t resetStateFlag); /** * @brief Reset function for the Q31 PID Control. * @param[in,out] *S points to an instance of the Q31 PID Control structure * @return none */ void arm_pid_reset_q31( arm_pid_instance_q31 * S); /** * @brief Initialization function for the Q15 PID Control. * @param[in,out] *S points to an instance of the Q15 PID structure. * @param[in] resetStateFlag flag to reset the state. 0 = no change in state 1 = reset the state. * @return none. */ void arm_pid_init_q15( arm_pid_instance_q15 * S, int32_t resetStateFlag); /** * @brief Reset function for the Q15 PID Control. * @param[in,out] *S points to an instance of the q15 PID Control structure * @return none */ void arm_pid_reset_q15( arm_pid_instance_q15 * S); /** * @brief Instance structure for the floating-point Linear Interpolate function. */ typedef struct { uint32_t nValues; /**< nValues */ float32_t x1; /**< x1 */ float32_t xSpacing; /**< xSpacing */ float32_t *pYData; /**< pointer to the table of Y values */ } arm_linear_interp_instance_f32; /** * @brief Instance structure for the floating-point bilinear interpolation function. */ typedef struct { uint16_t numRows; /**< number of rows in the data table. */ uint16_t numCols; /**< number of columns in the data table. */ float32_t *pData; /**< points to the data table. */ } arm_bilinear_interp_instance_f32; /** * @brief Instance structure for the Q31 bilinear interpolation function. */ typedef struct { uint16_t numRows; /**< number of rows in the data table. */ uint16_t numCols; /**< number of columns in the data table. */ q31_t *pData; /**< points to the data table. */ } arm_bilinear_interp_instance_q31; /** * @brief Instance structure for the Q15 bilinear interpolation function. */ typedef struct { uint16_t numRows; /**< number of rows in the data table. */ uint16_t numCols; /**< number of columns in the data table. */ q15_t *pData; /**< points to the data table. */ } arm_bilinear_interp_instance_q15; /** * @brief Instance structure for the Q15 bilinear interpolation function. */ typedef struct { uint16_t numRows; /**< number of rows in the data table. */ uint16_t numCols; /**< number of columns in the data table. */ q7_t *pData; /**< points to the data table. */ } arm_bilinear_interp_instance_q7; /** * @brief Q7 vector multiplication. * @param[in] *pSrcA points to the first input vector * @param[in] *pSrcB points to the second input vector * @param[out] *pDst points to the output vector * @param[in] blockSize number of samples in each vector * @return none. */ void arm_mult_q7( q7_t * pSrcA, q7_t * pSrcB, q7_t * pDst, uint32_t blockSize); /** * @brief Q15 vector multiplication. * @param[in] *pSrcA points to the first input vector * @param[in] *pSrcB points to the second input vector * @param[out] *pDst points to the output vector * @param[in] blockSize number of samples in each vector * @return none. */ void arm_mult_q15( q15_t * pSrcA, q15_t * pSrcB, q15_t * pDst, uint32_t blockSize); /** * @brief Q31 vector multiplication. * @param[in] *pSrcA points to the first input vector * @param[in] *pSrcB points to the second input vector * @param[out] *pDst points to the output vector * @param[in] blockSize number of samples in each vector * @return none. */ void arm_mult_q31( q31_t * pSrcA, q31_t * pSrcB, q31_t * pDst, uint32_t blockSize); /** * @brief Floating-point vector multiplication. * @param[in] *pSrcA points to the first input vector * @param[in] *pSrcB points to the second input vector * @param[out] *pDst points to the output vector * @param[in] blockSize number of samples in each vector * @return none. */ void arm_mult_f32( float32_t * pSrcA, float32_t * pSrcB, float32_t * pDst, uint32_t blockSize); /** * @brief Instance structure for the Q15 CFFT/CIFFT function. */ typedef struct { uint16_t fftLen; /**< length of the FFT. */ uint8_t ifftFlag; /**< flag that selects forward (ifftFlag=0) or inverse (ifftFlag=1) transform. */ uint8_t bitReverseFlag; /**< flag that enables (bitReverseFlag=1) or disables (bitReverseFlag=0) bit reversal of output. */ q15_t *pTwiddle; /**< points to the Sin twiddle factor table. */ uint16_t *pBitRevTable; /**< points to the bit reversal table. */ uint16_t twidCoefModifier; /**< twiddle coefficient modifier that supports different size FFTs with the same twiddle factor table. */ uint16_t bitRevFactor; /**< bit reversal modifier that supports different size FFTs with the same bit reversal table. */ } arm_cfft_radix2_instance_q15; /* Deprecated */ arm_status arm_cfft_radix2_init_q15( arm_cfft_radix2_instance_q15 * S, uint16_t fftLen, uint8_t ifftFlag, uint8_t bitReverseFlag); /* Deprecated */ void arm_cfft_radix2_q15( const arm_cfft_radix2_instance_q15 * S, q15_t * pSrc); /** * @brief Instance structure for the Q15 CFFT/CIFFT function. */ typedef struct { uint16_t fftLen; /**< length of the FFT. */ uint8_t ifftFlag; /**< flag that selects forward (ifftFlag=0) or inverse (ifftFlag=1) transform. */ uint8_t bitReverseFlag; /**< flag that enables (bitReverseFlag=1) or disables (bitReverseFlag=0) bit reversal of output. */ q15_t *pTwiddle; /**< points to the twiddle factor table. */ uint16_t *pBitRevTable; /**< points to the bit reversal table. */ uint16_t twidCoefModifier; /**< twiddle coefficient modifier that supports different size FFTs with the same twiddle factor table. */ uint16_t bitRevFactor; /**< bit reversal modifier that supports different size FFTs with the same bit reversal table. */ } arm_cfft_radix4_instance_q15; /* Deprecated */ arm_status arm_cfft_radix4_init_q15( arm_cfft_radix4_instance_q15 * S, uint16_t fftLen, uint8_t ifftFlag, uint8_t bitReverseFlag); /* Deprecated */ void arm_cfft_radix4_q15( const arm_cfft_radix4_instance_q15 * S, q15_t * pSrc); /** * @brief Instance structure for the Radix-2 Q31 CFFT/CIFFT function. */ typedef struct { uint16_t fftLen; /**< length of the FFT. */ uint8_t ifftFlag; /**< flag that selects forward (ifftFlag=0) or inverse (ifftFlag=1) transform. */ uint8_t bitReverseFlag; /**< flag that enables (bitReverseFlag=1) or disables (bitReverseFlag=0) bit reversal of output. */ q31_t *pTwiddle; /**< points to the Twiddle factor table. */ uint16_t *pBitRevTable; /**< points to the bit reversal table. */ uint16_t twidCoefModifier; /**< twiddle coefficient modifier that supports different size FFTs with the same twiddle factor table. */ uint16_t bitRevFactor; /**< bit reversal modifier that supports different size FFTs with the same bit reversal table. */ } arm_cfft_radix2_instance_q31; /* Deprecated */ arm_status arm_cfft_radix2_init_q31( arm_cfft_radix2_instance_q31 * S, uint16_t fftLen, uint8_t ifftFlag, uint8_t bitReverseFlag); /* Deprecated */ void arm_cfft_radix2_q31( const arm_cfft_radix2_instance_q31 * S, q31_t * pSrc); /** * @brief Instance structure for the Q31 CFFT/CIFFT function. */ typedef struct { uint16_t fftLen; /**< length of the FFT. */ uint8_t ifftFlag; /**< flag that selects forward (ifftFlag=0) or inverse (ifftFlag=1) transform. */ uint8_t bitReverseFlag; /**< flag that enables (bitReverseFlag=1) or disables (bitReverseFlag=0) bit reversal of output. */ q31_t *pTwiddle; /**< points to the twiddle factor table. */ uint16_t *pBitRevTable; /**< points to the bit reversal table. */ uint16_t twidCoefModifier; /**< twiddle coefficient modifier that supports different size FFTs with the same twiddle factor table. */ uint16_t bitRevFactor; /**< bit reversal modifier that supports different size FFTs with the same bit reversal table. */ } arm_cfft_radix4_instance_q31; /* Deprecated */ void arm_cfft_radix4_q31( const arm_cfft_radix4_instance_q31 * S, q31_t * pSrc); /* Deprecated */ arm_status arm_cfft_radix4_init_q31( arm_cfft_radix4_instance_q31 * S, uint16_t fftLen, uint8_t ifftFlag, uint8_t bitReverseFlag); /** * @brief Instance structure for the floating-point CFFT/CIFFT function. */ typedef struct { uint16_t fftLen; /**< length of the FFT. */ uint8_t ifftFlag; /**< flag that selects forward (ifftFlag=0) or inverse (ifftFlag=1) transform. */ uint8_t bitReverseFlag; /**< flag that enables (bitReverseFlag=1) or disables (bitReverseFlag=0) bit reversal of output. */ float32_t *pTwiddle; /**< points to the Twiddle factor table. */ uint16_t *pBitRevTable; /**< points to the bit reversal table. */ uint16_t twidCoefModifier; /**< twiddle coefficient modifier that supports different size FFTs with the same twiddle factor table. */ uint16_t bitRevFactor; /**< bit reversal modifier that supports different size FFTs with the same bit reversal table. */ float32_t onebyfftLen; /**< value of 1/fftLen. */ } arm_cfft_radix2_instance_f32; /* Deprecated */ arm_status arm_cfft_radix2_init_f32( arm_cfft_radix2_instance_f32 * S, uint16_t fftLen, uint8_t ifftFlag, uint8_t bitReverseFlag); /* Deprecated */ void arm_cfft_radix2_f32( const arm_cfft_radix2_instance_f32 * S, float32_t * pSrc); /** * @brief Instance structure for the floating-point CFFT/CIFFT function. */ typedef struct { uint16_t fftLen; /**< length of the FFT. */ uint8_t ifftFlag; /**< flag that selects forward (ifftFlag=0) or inverse (ifftFlag=1) transform. */ uint8_t bitReverseFlag; /**< flag that enables (bitReverseFlag=1) or disables (bitReverseFlag=0) bit reversal of output. */ float32_t *pTwiddle; /**< points to the Twiddle factor table. */ uint16_t *pBitRevTable; /**< points to the bit reversal table. */ uint16_t twidCoefModifier; /**< twiddle coefficient modifier that supports different size FFTs with the same twiddle factor table. */ uint16_t bitRevFactor; /**< bit reversal modifier that supports different size FFTs with the same bit reversal table. */ float32_t onebyfftLen; /**< value of 1/fftLen. */ } arm_cfft_radix4_instance_f32; /* Deprecated */ arm_status arm_cfft_radix4_init_f32( arm_cfft_radix4_instance_f32 * S, uint16_t fftLen, uint8_t ifftFlag, uint8_t bitReverseFlag); /* Deprecated */ void arm_cfft_radix4_f32( const arm_cfft_radix4_instance_f32 * S, float32_t * pSrc); /** * @brief Instance structure for the fixed-point CFFT/CIFFT function. */ typedef struct { uint16_t fftLen; /**< length of the FFT. */ const q15_t *pTwiddle; /**< points to the Twiddle factor table. */ const uint16_t *pBitRevTable; /**< points to the bit reversal table. */ uint16_t bitRevLength; /**< bit reversal table length. */ } arm_cfft_instance_q15; void arm_cfft_q15( const arm_cfft_instance_q15 * S, q15_t * p1, uint8_t ifftFlag, uint8_t bitReverseFlag); /** * @brief Instance structure for the fixed-point CFFT/CIFFT function. */ typedef struct { uint16_t fftLen; /**< length of the FFT. */ const q31_t *pTwiddle; /**< points to the Twiddle factor table. */ const uint16_t *pBitRevTable; /**< points to the bit reversal table. */ uint16_t bitRevLength; /**< bit reversal table length. */ } arm_cfft_instance_q31; void arm_cfft_q31( const arm_cfft_instance_q31 * S, q31_t * p1, uint8_t ifftFlag, uint8_t bitReverseFlag); /** * @brief Instance structure for the floating-point CFFT/CIFFT function. */ typedef struct { uint16_t fftLen; /**< length of the FFT. */ const float32_t *pTwiddle; /**< points to the Twiddle factor table. */ const uint16_t *pBitRevTable; /**< points to the bit reversal table. */ uint16_t bitRevLength; /**< bit reversal table length. */ } arm_cfft_instance_f32; void arm_cfft_f32( const arm_cfft_instance_f32 * S, float32_t * p1, uint8_t ifftFlag, uint8_t bitReverseFlag); /** * @brief Instance structure for the Q15 RFFT/RIFFT function. */ typedef struct { uint32_t fftLenReal; /**< length of the real FFT. */ uint8_t ifftFlagR; /**< flag that selects forward (ifftFlagR=0) or inverse (ifftFlagR=1) transform. */ uint8_t bitReverseFlagR; /**< flag that enables (bitReverseFlagR=1) or disables (bitReverseFlagR=0) bit reversal of output. */ uint32_t twidCoefRModifier; /**< twiddle coefficient modifier that supports different size FFTs with the same twiddle factor table. */ q15_t *pTwiddleAReal; /**< points to the real twiddle factor table. */ q15_t *pTwiddleBReal; /**< points to the imag twiddle factor table. */ const arm_cfft_instance_q15 *pCfft; /**< points to the complex FFT instance. */ } arm_rfft_instance_q15; arm_status arm_rfft_init_q15( arm_rfft_instance_q15 * S, uint32_t fftLenReal, uint32_t ifftFlagR, uint32_t bitReverseFlag); void arm_rfft_q15( const arm_rfft_instance_q15 * S, q15_t * pSrc, q15_t * pDst); /** * @brief Instance structure for the Q31 RFFT/RIFFT function. */ typedef struct { uint32_t fftLenReal; /**< length of the real FFT. */ uint8_t ifftFlagR; /**< flag that selects forward (ifftFlagR=0) or inverse (ifftFlagR=1) transform. */ uint8_t bitReverseFlagR; /**< flag that enables (bitReverseFlagR=1) or disables (bitReverseFlagR=0) bit reversal of output. */ uint32_t twidCoefRModifier; /**< twiddle coefficient modifier that supports different size FFTs with the same twiddle factor table. */ q31_t *pTwiddleAReal; /**< points to the real twiddle factor table. */ q31_t *pTwiddleBReal; /**< points to the imag twiddle factor table. */ const arm_cfft_instance_q31 *pCfft; /**< points to the complex FFT instance. */ } arm_rfft_instance_q31; arm_status arm_rfft_init_q31( arm_rfft_instance_q31 * S, uint32_t fftLenReal, uint32_t ifftFlagR, uint32_t bitReverseFlag); void arm_rfft_q31( const arm_rfft_instance_q31 * S, q31_t * pSrc, q31_t * pDst); /** * @brief Instance structure for the floating-point RFFT/RIFFT function. */ typedef struct { uint32_t fftLenReal; /**< length of the real FFT. */ uint16_t fftLenBy2; /**< length of the complex FFT. */ uint8_t ifftFlagR; /**< flag that selects forward (ifftFlagR=0) or inverse (ifftFlagR=1) transform. */ uint8_t bitReverseFlagR; /**< flag that enables (bitReverseFlagR=1) or disables (bitReverseFlagR=0) bit reversal of output. */ uint32_t twidCoefRModifier; /**< twiddle coefficient modifier that supports different size FFTs with the same twiddle factor table. */ float32_t *pTwiddleAReal; /**< points to the real twiddle factor table. */ float32_t *pTwiddleBReal; /**< points to the imag twiddle factor table. */ arm_cfft_radix4_instance_f32 *pCfft; /**< points to the complex FFT instance. */ } arm_rfft_instance_f32; arm_status arm_rfft_init_f32( arm_rfft_instance_f32 * S, arm_cfft_radix4_instance_f32 * S_CFFT, uint32_t fftLenReal, uint32_t ifftFlagR, uint32_t bitReverseFlag); void arm_rfft_f32( const arm_rfft_instance_f32 * S, float32_t * pSrc, float32_t * pDst); /** * @brief Instance structure for the floating-point RFFT/RIFFT function. */ typedef struct { arm_cfft_instance_f32 Sint; /**< Internal CFFT structure. */ uint16_t fftLenRFFT; /**< length of the real sequence */ float32_t * pTwiddleRFFT; /**< Twiddle factors real stage */ } arm_rfft_fast_instance_f32 ; arm_status arm_rfft_fast_init_f32 ( arm_rfft_fast_instance_f32 * S, uint16_t fftLen); void arm_rfft_fast_f32( arm_rfft_fast_instance_f32 * S, float32_t * p, float32_t * pOut, uint8_t ifftFlag); /** * @brief Instance structure for the floating-point DCT4/IDCT4 function. */ typedef struct { uint16_t N; /**< length of the DCT4. */ uint16_t Nby2; /**< half of the length of the DCT4. */ float32_t normalize; /**< normalizing factor. */ float32_t *pTwiddle; /**< points to the twiddle factor table. */ float32_t *pCosFactor; /**< points to the cosFactor table. */ arm_rfft_instance_f32 *pRfft; /**< points to the real FFT instance. */ arm_cfft_radix4_instance_f32 *pCfft; /**< points to the complex FFT instance. */ } arm_dct4_instance_f32; /** * @brief Initialization function for the floating-point DCT4/IDCT4. * @param[in,out] *S points to an instance of floating-point DCT4/IDCT4 structure. * @param[in] *S_RFFT points to an instance of floating-point RFFT/RIFFT structure. * @param[in] *S_CFFT points to an instance of floating-point CFFT/CIFFT structure. * @param[in] N length of the DCT4. * @param[in] Nby2 half of the length of the DCT4. * @param[in] normalize normalizing factor. * @return arm_status function returns ARM_MATH_SUCCESS if initialization is successful or ARM_MATH_ARGUMENT_ERROR if fftLenReal is not a supported transform length. */ arm_status arm_dct4_init_f32( arm_dct4_instance_f32 * S, arm_rfft_instance_f32 * S_RFFT, arm_cfft_radix4_instance_f32 * S_CFFT, uint16_t N, uint16_t Nby2, float32_t normalize); /** * @brief Processing function for the floating-point DCT4/IDCT4. * @param[in] *S points to an instance of the floating-point DCT4/IDCT4 structure. * @param[in] *pState points to state buffer. * @param[in,out] *pInlineBuffer points to the in-place input and output buffer. * @return none. */ void arm_dct4_f32( const arm_dct4_instance_f32 * S, float32_t * pState, float32_t * pInlineBuffer); /** * @brief Instance structure for the Q31 DCT4/IDCT4 function. */ typedef struct { uint16_t N; /**< length of the DCT4. */ uint16_t Nby2; /**< half of the length of the DCT4. */ q31_t normalize; /**< normalizing factor. */ q31_t *pTwiddle; /**< points to the twiddle factor table. */ q31_t *pCosFactor; /**< points to the cosFactor table. */ arm_rfft_instance_q31 *pRfft; /**< points to the real FFT instance. */ arm_cfft_radix4_instance_q31 *pCfft; /**< points to the complex FFT instance. */ } arm_dct4_instance_q31; /** * @brief Initialization function for the Q31 DCT4/IDCT4. * @param[in,out] *S points to an instance of Q31 DCT4/IDCT4 structure. * @param[in] *S_RFFT points to an instance of Q31 RFFT/RIFFT structure * @param[in] *S_CFFT points to an instance of Q31 CFFT/CIFFT structure * @param[in] N length of the DCT4. * @param[in] Nby2 half of the length of the DCT4. * @param[in] normalize normalizing factor. * @return arm_status function returns ARM_MATH_SUCCESS if initialization is successful or ARM_MATH_ARGUMENT_ERROR if N is not a supported transform length. */ arm_status arm_dct4_init_q31( arm_dct4_instance_q31 * S, arm_rfft_instance_q31 * S_RFFT, arm_cfft_radix4_instance_q31 * S_CFFT, uint16_t N, uint16_t Nby2, q31_t normalize); /** * @brief Processing function for the Q31 DCT4/IDCT4. * @param[in] *S points to an instance of the Q31 DCT4 structure. * @param[in] *pState points to state buffer. * @param[in,out] *pInlineBuffer points to the in-place input and output buffer. * @return none. */ void arm_dct4_q31( const arm_dct4_instance_q31 * S, q31_t * pState, q31_t * pInlineBuffer); /** * @brief Instance structure for the Q15 DCT4/IDCT4 function. */ typedef struct { uint16_t N; /**< length of the DCT4. */ uint16_t Nby2; /**< half of the length of the DCT4. */ q15_t normalize; /**< normalizing factor. */ q15_t *pTwiddle; /**< points to the twiddle factor table. */ q15_t *pCosFactor; /**< points to the cosFactor table. */ arm_rfft_instance_q15 *pRfft; /**< points to the real FFT instance. */ arm_cfft_radix4_instance_q15 *pCfft; /**< points to the complex FFT instance. */ } arm_dct4_instance_q15; /** * @brief Initialization function for the Q15 DCT4/IDCT4. * @param[in,out] *S points to an instance of Q15 DCT4/IDCT4 structure. * @param[in] *S_RFFT points to an instance of Q15 RFFT/RIFFT structure. * @param[in] *S_CFFT points to an instance of Q15 CFFT/CIFFT structure. * @param[in] N length of the DCT4. * @param[in] Nby2 half of the length of the DCT4. * @param[in] normalize normalizing factor. * @return arm_status function returns ARM_MATH_SUCCESS if initialization is successful or ARM_MATH_ARGUMENT_ERROR if N is not a supported transform length. */ arm_status arm_dct4_init_q15( arm_dct4_instance_q15 * S, arm_rfft_instance_q15 * S_RFFT, arm_cfft_radix4_instance_q15 * S_CFFT, uint16_t N, uint16_t Nby2, q15_t normalize); /** * @brief Processing function for the Q15 DCT4/IDCT4. * @param[in] *S points to an instance of the Q15 DCT4 structure. * @param[in] *pState points to state buffer. * @param[in,out] *pInlineBuffer points to the in-place input and output buffer. * @return none. */ void arm_dct4_q15( const arm_dct4_instance_q15 * S, q15_t * pState, q15_t * pInlineBuffer); /** * @brief Floating-point vector addition. * @param[in] *pSrcA points to the first input vector * @param[in] *pSrcB points to the second input vector * @param[out] *pDst points to the output vector * @param[in] blockSize number of samples in each vector * @return none. */ void arm_add_f32( float32_t * pSrcA, float32_t * pSrcB, float32_t * pDst, uint32_t blockSize); /** * @brief Q7 vector addition. * @param[in] *pSrcA points to the first input vector * @param[in] *pSrcB points to the second input vector * @param[out] *pDst points to the output vector * @param[in] blockSize number of samples in each vector * @return none. */ void arm_add_q7( q7_t * pSrcA, q7_t * pSrcB, q7_t * pDst, uint32_t blockSize); /** * @brief Q15 vector addition. * @param[in] *pSrcA points to the first input vector * @param[in] *pSrcB points to the second input vector * @param[out] *pDst points to the output vector * @param[in] blockSize number of samples in each vector * @return none. */ void arm_add_q15( q15_t * pSrcA, q15_t * pSrcB, q15_t * pDst, uint32_t blockSize); /** * @brief Q31 vector addition. * @param[in] *pSrcA points to the first input vector * @param[in] *pSrcB points to the second input vector * @param[out] *pDst points to the output vector * @param[in] blockSize number of samples in each vector * @return none. */ void arm_add_q31( q31_t * pSrcA, q31_t * pSrcB, q31_t * pDst, uint32_t blockSize); /** * @brief Floating-point vector subtraction. * @param[in] *pSrcA points to the first input vector * @param[in] *pSrcB points to the second input vector * @param[out] *pDst points to the output vector * @param[in] blockSize number of samples in each vector * @return none. */ void arm_sub_f32( float32_t * pSrcA, float32_t * pSrcB, float32_t * pDst, uint32_t blockSize); /** * @brief Q7 vector subtraction. * @param[in] *pSrcA points to the first input vector * @param[in] *pSrcB points to the second input vector * @param[out] *pDst points to the output vector * @param[in] blockSize number of samples in each vector * @return none. */ void arm_sub_q7( q7_t * pSrcA, q7_t * pSrcB, q7_t * pDst, uint32_t blockSize); /** * @brief Q15 vector subtraction. * @param[in] *pSrcA points to the first input vector * @param[in] *pSrcB points to the second input vector * @param[out] *pDst points to the output vector * @param[in] blockSize number of samples in each vector * @return none. */ void arm_sub_q15( q15_t * pSrcA, q15_t * pSrcB, q15_t * pDst, uint32_t blockSize); /** * @brief Q31 vector subtraction. * @param[in] *pSrcA points to the first input vector * @param[in] *pSrcB points to the second input vector * @param[out] *pDst points to the output vector * @param[in] blockSize number of samples in each vector * @return none. */ void arm_sub_q31( q31_t * pSrcA, q31_t * pSrcB, q31_t * pDst, uint32_t blockSize); /** * @brief Multiplies a floating-point vector by a scalar. * @param[in] *pSrc points to the input vector * @param[in] scale scale factor to be applied * @param[out] *pDst points to the output vector * @param[in] blockSize number of samples in the vector * @return none. */ void arm_scale_f32( float32_t * pSrc, float32_t scale, float32_t * pDst, uint32_t blockSize); /** * @brief Multiplies a Q7 vector by a scalar. * @param[in] *pSrc points to the input vector * @param[in] scaleFract fractional portion of the scale value * @param[in] shift number of bits to shift the result by * @param[out] *pDst points to the output vector * @param[in] blockSize number of samples in the vector * @return none. */ void arm_scale_q7( q7_t * pSrc, q7_t scaleFract, int8_t shift, q7_t * pDst, uint32_t blockSize); /** * @brief Multiplies a Q15 vector by a scalar. * @param[in] *pSrc points to the input vector * @param[in] scaleFract fractional portion of the scale value * @param[in] shift number of bits to shift the result by * @param[out] *pDst points to the output vector * @param[in] blockSize number of samples in the vector * @return none. */ void arm_scale_q15( q15_t * pSrc, q15_t scaleFract, int8_t shift, q15_t * pDst, uint32_t blockSize); /** * @brief Multiplies a Q31 vector by a scalar. * @param[in] *pSrc points to the input vector * @param[in] scaleFract fractional portion of the scale value * @param[in] shift number of bits to shift the result by * @param[out] *pDst points to the output vector * @param[in] blockSize number of samples in the vector * @return none. */ void arm_scale_q31( q31_t * pSrc, q31_t scaleFract, int8_t shift, q31_t * pDst, uint32_t blockSize); /** * @brief Q7 vector absolute value. * @param[in] *pSrc points to the input buffer * @param[out] *pDst points to the output buffer * @param[in] blockSize number of samples in each vector * @return none. */ void arm_abs_q7( q7_t * pSrc, q7_t * pDst, uint32_t blockSize); /** * @brief Floating-point vector absolute value. * @param[in] *pSrc points to the input buffer * @param[out] *pDst points to the output buffer * @param[in] blockSize number of samples in each vector * @return none. */ void arm_abs_f32( float32_t * pSrc, float32_t * pDst, uint32_t blockSize); /** * @brief Q15 vector absolute value. * @param[in] *pSrc points to the input buffer * @param[out] *pDst points to the output buffer * @param[in] blockSize number of samples in each vector * @return none. */ void arm_abs_q15( q15_t * pSrc, q15_t * pDst, uint32_t blockSize); /** * @brief Q31 vector absolute value. * @param[in] *pSrc points to the input buffer * @param[out] *pDst points to the output buffer * @param[in] blockSize number of samples in each vector * @return none. */ void arm_abs_q31( q31_t * pSrc, q31_t * pDst, uint32_t blockSize); /** * @brief Dot product of floating-point vectors. * @param[in] *pSrcA points to the first input vector * @param[in] *pSrcB points to the second input vector * @param[in] blockSize number of samples in each vector * @param[out] *result output result returned here * @return none. */ void arm_dot_prod_f32( float32_t * pSrcA, float32_t * pSrcB, uint32_t blockSize, float32_t * result); /** * @brief Dot product of Q7 vectors. * @param[in] *pSrcA points to the first input vector * @param[in] *pSrcB points to the second input vector * @param[in] blockSize number of samples in each vector * @param[out] *result output result returned here * @return none. */ void arm_dot_prod_q7( q7_t * pSrcA, q7_t * pSrcB, uint32_t blockSize, q31_t * result); /** * @brief Dot product of Q15 vectors. * @param[in] *pSrcA points to the first input vector * @param[in] *pSrcB points to the second input vector * @param[in] blockSize number of samples in each vector * @param[out] *result output result returned here * @return none. */ void arm_dot_prod_q15( q15_t * pSrcA, q15_t * pSrcB, uint32_t blockSize, q63_t * result); /** * @brief Dot product of Q31 vectors. * @param[in] *pSrcA points to the first input vector * @param[in] *pSrcB points to the second input vector * @param[in] blockSize number of samples in each vector * @param[out] *result output result returned here * @return none. */ void arm_dot_prod_q31( q31_t * pSrcA, q31_t * pSrcB, uint32_t blockSize, q63_t * result); /** * @brief Shifts the elements of a Q7 vector a specified number of bits. * @param[in] *pSrc points to the input vector * @param[in] shiftBits number of bits to shift. A positive value shifts left; a negative value shifts right. * @param[out] *pDst points to the output vector * @param[in] blockSize number of samples in the vector * @return none. */ void arm_shift_q7( q7_t * pSrc, int8_t shiftBits, q7_t * pDst, uint32_t blockSize); /** * @brief Shifts the elements of a Q15 vector a specified number of bits. * @param[in] *pSrc points to the input vector * @param[in] shiftBits number of bits to shift. A positive value shifts left; a negative value shifts right. * @param[out] *pDst points to the output vector * @param[in] blockSize number of samples in the vector * @return none. */ void arm_shift_q15( q15_t * pSrc, int8_t shiftBits, q15_t * pDst, uint32_t blockSize); /** * @brief Shifts the elements of a Q31 vector a specified number of bits. * @param[in] *pSrc points to the input vector * @param[in] shiftBits number of bits to shift. A positive value shifts left; a negative value shifts right. * @param[out] *pDst points to the output vector * @param[in] blockSize number of samples in the vector * @return none. */ void arm_shift_q31( q31_t * pSrc, int8_t shiftBits, q31_t * pDst, uint32_t blockSize); /** * @brief Adds a constant offset to a floating-point vector. * @param[in] *pSrc points to the input vector * @param[in] offset is the offset to be added * @param[out] *pDst points to the output vector * @param[in] blockSize number of samples in the vector * @return none. */ void arm_offset_f32( float32_t * pSrc, float32_t offset, float32_t * pDst, uint32_t blockSize); /** * @brief Adds a constant offset to a Q7 vector. * @param[in] *pSrc points to the input vector * @param[in] offset is the offset to be added * @param[out] *pDst points to the output vector * @param[in] blockSize number of samples in the vector * @return none. */ void arm_offset_q7( q7_t * pSrc, q7_t offset, q7_t * pDst, uint32_t blockSize); /** * @brief Adds a constant offset to a Q15 vector. * @param[in] *pSrc points to the input vector * @param[in] offset is the offset to be added * @param[out] *pDst points to the output vector * @param[in] blockSize number of samples in the vector * @return none. */ void arm_offset_q15( q15_t * pSrc, q15_t offset, q15_t * pDst, uint32_t blockSize); /** * @brief Adds a constant offset to a Q31 vector. * @param[in] *pSrc points to the input vector * @param[in] offset is the offset to be added * @param[out] *pDst points to the output vector * @param[in] blockSize number of samples in the vector * @return none. */ void arm_offset_q31( q31_t * pSrc, q31_t offset, q31_t * pDst, uint32_t blockSize); /** * @brief Negates the elements of a floating-point vector. * @param[in] *pSrc points to the input vector * @param[out] *pDst points to the output vector * @param[in] blockSize number of samples in the vector * @return none. */ void arm_negate_f32( float32_t * pSrc, float32_t * pDst, uint32_t blockSize); /** * @brief Negates the elements of a Q7 vector. * @param[in] *pSrc points to the input vector * @param[out] *pDst points to the output vector * @param[in] blockSize number of samples in the vector * @return none. */ void arm_negate_q7( q7_t * pSrc, q7_t * pDst, uint32_t blockSize); /** * @brief Negates the elements of a Q15 vector. * @param[in] *pSrc points to the input vector * @param[out] *pDst points to the output vector * @param[in] blockSize number of samples in the vector * @return none. */ void arm_negate_q15( q15_t * pSrc, q15_t * pDst, uint32_t blockSize); /** * @brief Negates the elements of a Q31 vector. * @param[in] *pSrc points to the input vector * @param[out] *pDst points to the output vector * @param[in] blockSize number of samples in the vector * @return none. */ void arm_negate_q31( q31_t * pSrc, q31_t * pDst, uint32_t blockSize); /** * @brief Copies the elements of a floating-point vector. * @param[in] *pSrc input pointer * @param[out] *pDst output pointer * @param[in] blockSize number of samples to process * @return none. */ void arm_copy_f32( float32_t * pSrc, float32_t * pDst, uint32_t blockSize); /** * @brief Copies the elements of a Q7 vector. * @param[in] *pSrc input pointer * @param[out] *pDst output pointer * @param[in] blockSize number of samples to process * @return none. */ void arm_copy_q7( q7_t * pSrc, q7_t * pDst, uint32_t blockSize); /** * @brief Copies the elements of a Q15 vector. * @param[in] *pSrc input pointer * @param[out] *pDst output pointer * @param[in] blockSize number of samples to process * @return none. */ void arm_copy_q15( q15_t * pSrc, q15_t * pDst, uint32_t blockSize); /** * @brief Copies the elements of a Q31 vector. * @param[in] *pSrc input pointer * @param[out] *pDst output pointer * @param[in] blockSize number of samples to process * @return none. */ void arm_copy_q31( q31_t * pSrc, q31_t * pDst, uint32_t blockSize); /** * @brief Fills a constant value into a floating-point vector. * @param[in] value input value to be filled * @param[out] *pDst output pointer * @param[in] blockSize number of samples to process * @return none. */ void arm_fill_f32( float32_t value, float32_t * pDst, uint32_t blockSize); /** * @brief Fills a constant value into a Q7 vector. * @param[in] value input value to be filled * @param[out] *pDst output pointer * @param[in] blockSize number of samples to process * @return none. */ void arm_fill_q7( q7_t value, q7_t * pDst, uint32_t blockSize); /** * @brief Fills a constant value into a Q15 vector. * @param[in] value input value to be filled * @param[out] *pDst output pointer * @param[in] blockSize number of samples to process * @return none. */ void arm_fill_q15( q15_t value, q15_t * pDst, uint32_t blockSize); /** * @brief Fills a constant value into a Q31 vector. * @param[in] value input value to be filled * @param[out] *pDst output pointer * @param[in] blockSize number of samples to process * @return none. */ void arm_fill_q31( q31_t value, q31_t * pDst, uint32_t blockSize); /** * @brief Convolution of floating-point sequences. * @param[in] *pSrcA points to the first input sequence. * @param[in] srcALen length of the first input sequence. * @param[in] *pSrcB points to the second input sequence. * @param[in] srcBLen length of the second input sequence. * @param[out] *pDst points to the location where the output result is written. Length srcALen+srcBLen-1. * @return none. */ void arm_conv_f32( float32_t * pSrcA, uint32_t srcALen, float32_t * pSrcB, uint32_t srcBLen, float32_t * pDst); /** * @brief Convolution of Q15 sequences. * @param[in] *pSrcA points to the first input sequence. * @param[in] srcALen length of the first input sequence. * @param[in] *pSrcB points to the second input sequence. * @param[in] srcBLen length of the second input sequence. * @param[out] *pDst points to the block of output data Length srcALen+srcBLen-1. * @param[in] *pScratch1 points to scratch buffer of size max(srcALen, srcBLen) + 2*min(srcALen, srcBLen) - 2. * @param[in] *pScratch2 points to scratch buffer of size min(srcALen, srcBLen). * @return none. */ void arm_conv_opt_q15( q15_t * pSrcA, uint32_t srcALen, q15_t * pSrcB, uint32_t srcBLen, q15_t * pDst, q15_t * pScratch1, q15_t * pScratch2); /** * @brief Convolution of Q15 sequences. * @param[in] *pSrcA points to the first input sequence. * @param[in] srcALen length of the first input sequence. * @param[in] *pSrcB points to the second input sequence. * @param[in] srcBLen length of the second input sequence. * @param[out] *pDst points to the location where the output result is written. Length srcALen+srcBLen-1. * @return none. */ void arm_conv_q15( q15_t * pSrcA, uint32_t srcALen, q15_t * pSrcB, uint32_t srcBLen, q15_t * pDst); /** * @brief Convolution of Q15 sequences (fast version) for Cortex-M3 and Cortex-M4 * @param[in] *pSrcA points to the first input sequence. * @param[in] srcALen length of the first input sequence. * @param[in] *pSrcB points to the second input sequence. * @param[in] srcBLen length of the second input sequence. * @param[out] *pDst points to the block of output data Length srcALen+srcBLen-1. * @return none. */ void arm_conv_fast_q15( q15_t * pSrcA, uint32_t srcALen, q15_t * pSrcB, uint32_t srcBLen, q15_t * pDst); /** * @brief Convolution of Q15 sequences (fast version) for Cortex-M3 and Cortex-M4 * @param[in] *pSrcA points to the first input sequence. * @param[in] srcALen length of the first input sequence. * @param[in] *pSrcB points to the second input sequence. * @param[in] srcBLen length of the second input sequence. * @param[out] *pDst points to the block of output data Length srcALen+srcBLen-1. * @param[in] *pScratch1 points to scratch buffer of size max(srcALen, srcBLen) + 2*min(srcALen, srcBLen) - 2. * @param[in] *pScratch2 points to scratch buffer of size min(srcALen, srcBLen). * @return none. */ void arm_conv_fast_opt_q15( q15_t * pSrcA, uint32_t srcALen, q15_t * pSrcB, uint32_t srcBLen, q15_t * pDst, q15_t * pScratch1, q15_t * pScratch2); /** * @brief Convolution of Q31 sequences. * @param[in] *pSrcA points to the first input sequence. * @param[in] srcALen length of the first input sequence. * @param[in] *pSrcB points to the second input sequence. * @param[in] srcBLen length of the second input sequence. * @param[out] *pDst points to the block of output data Length srcALen+srcBLen-1. * @return none. */ void arm_conv_q31( q31_t * pSrcA, uint32_t srcALen, q31_t * pSrcB, uint32_t srcBLen, q31_t * pDst); /** * @brief Convolution of Q31 sequences (fast version) for Cortex-M3 and Cortex-M4 * @param[in] *pSrcA points to the first input sequence. * @param[in] srcALen length of the first input sequence. * @param[in] *pSrcB points to the second input sequence. * @param[in] srcBLen length of the second input sequence. * @param[out] *pDst points to the block of output data Length srcALen+srcBLen-1. * @return none. */ void arm_conv_fast_q31( q31_t * pSrcA, uint32_t srcALen, q31_t * pSrcB, uint32_t srcBLen, q31_t * pDst); /** * @brief Convolution of Q7 sequences. * @param[in] *pSrcA points to the first input sequence. * @param[in] srcALen length of the first input sequence. * @param[in] *pSrcB points to the second input sequence. * @param[in] srcBLen length of the second input sequence. * @param[out] *pDst points to the block of output data Length srcALen+srcBLen-1. * @param[in] *pScratch1 points to scratch buffer(of type q15_t) of size max(srcALen, srcBLen) + 2*min(srcALen, srcBLen) - 2. * @param[in] *pScratch2 points to scratch buffer (of type q15_t) of size min(srcALen, srcBLen). * @return none. */ void arm_conv_opt_q7( q7_t * pSrcA, uint32_t srcALen, q7_t * pSrcB, uint32_t srcBLen, q7_t * pDst, q15_t * pScratch1, q15_t * pScratch2); /** * @brief Convolution of Q7 sequences. * @param[in] *pSrcA points to the first input sequence. * @param[in] srcALen length of the first input sequence. * @param[in] *pSrcB points to the second input sequence. * @param[in] srcBLen length of the second input sequence. * @param[out] *pDst points to the block of output data Length srcALen+srcBLen-1. * @return none. */ void arm_conv_q7( q7_t * pSrcA, uint32_t srcALen, q7_t * pSrcB, uint32_t srcBLen, q7_t * pDst); /** * @brief Partial convolution of floating-point sequences. * @param[in] *pSrcA points to the first input sequence. * @param[in] srcALen length of the first input sequence. * @param[in] *pSrcB points to the second input sequence. * @param[in] srcBLen length of the second input sequence. * @param[out] *pDst points to the block of output data * @param[in] firstIndex is the first output sample to start with. * @param[in] numPoints is the number of output points to be computed. * @return Returns either ARM_MATH_SUCCESS if the function completed correctly or ARM_MATH_ARGUMENT_ERROR if the requested subset is not in the range [0 srcALen+srcBLen-2]. */ arm_status arm_conv_partial_f32( float32_t * pSrcA, uint32_t srcALen, float32_t * pSrcB, uint32_t srcBLen, float32_t * pDst, uint32_t firstIndex, uint32_t numPoints); /** * @brief Partial convolution of Q15 sequences. * @param[in] *pSrcA points to the first input sequence. * @param[in] srcALen length of the first input sequence. * @param[in] *pSrcB points to the second input sequence. * @param[in] srcBLen length of the second input sequence. * @param[out] *pDst points to the block of output data * @param[in] firstIndex is the first output sample to start with. * @param[in] numPoints is the number of output points to be computed. * @param[in] * pScratch1 points to scratch buffer of size max(srcALen, srcBLen) + 2*min(srcALen, srcBLen) - 2. * @param[in] * pScratch2 points to scratch buffer of size min(srcALen, srcBLen). * @return Returns either ARM_MATH_SUCCESS if the function completed correctly or ARM_MATH_ARGUMENT_ERROR if the requested subset is not in the range [0 srcALen+srcBLen-2]. */ arm_status arm_conv_partial_opt_q15( q15_t * pSrcA, uint32_t srcALen, q15_t * pSrcB, uint32_t srcBLen, q15_t * pDst, uint32_t firstIndex, uint32_t numPoints, q15_t * pScratch1, q15_t * pScratch2); /** * @brief Partial convolution of Q15 sequences. * @param[in] *pSrcA points to the first input sequence. * @param[in] srcALen length of the first input sequence. * @param[in] *pSrcB points to the second input sequence. * @param[in] srcBLen length of the second input sequence. * @param[out] *pDst points to the block of output data * @param[in] firstIndex is the first output sample to start with. * @param[in] numPoints is the number of output points to be computed. * @return Returns either ARM_MATH_SUCCESS if the function completed correctly or ARM_MATH_ARGUMENT_ERROR if the requested subset is not in the range [0 srcALen+srcBLen-2]. */ arm_status arm_conv_partial_q15( q15_t * pSrcA, uint32_t srcALen, q15_t * pSrcB, uint32_t srcBLen, q15_t * pDst, uint32_t firstIndex, uint32_t numPoints); /** * @brief Partial convolution of Q15 sequences (fast version) for Cortex-M3 and Cortex-M4 * @param[in] *pSrcA points to the first input sequence. * @param[in] srcALen length of the first input sequence. * @param[in] *pSrcB points to the second input sequence. * @param[in] srcBLen length of the second input sequence. * @param[out] *pDst points to the block of output data * @param[in] firstIndex is the first output sample to start with. * @param[in] numPoints is the number of output points to be computed. * @return Returns either ARM_MATH_SUCCESS if the function completed correctly or ARM_MATH_ARGUMENT_ERROR if the requested subset is not in the range [0 srcALen+srcBLen-2]. */ arm_status arm_conv_partial_fast_q15( q15_t * pSrcA, uint32_t srcALen, q15_t * pSrcB, uint32_t srcBLen, q15_t * pDst, uint32_t firstIndex, uint32_t numPoints); /** * @brief Partial convolution of Q15 sequences (fast version) for Cortex-M3 and Cortex-M4 * @param[in] *pSrcA points to the first input sequence. * @param[in] srcALen length of the first input sequence. * @param[in] *pSrcB points to the second input sequence. * @param[in] srcBLen length of the second input sequence. * @param[out] *pDst points to the block of output data * @param[in] firstIndex is the first output sample to start with. * @param[in] numPoints is the number of output points to be computed. * @param[in] * pScratch1 points to scratch buffer of size max(srcALen, srcBLen) + 2*min(srcALen, srcBLen) - 2. * @param[in] * pScratch2 points to scratch buffer of size min(srcALen, srcBLen). * @return Returns either ARM_MATH_SUCCESS if the function completed correctly or ARM_MATH_ARGUMENT_ERROR if the requested subset is not in the range [0 srcALen+srcBLen-2]. */ arm_status arm_conv_partial_fast_opt_q15( q15_t * pSrcA, uint32_t srcALen, q15_t * pSrcB, uint32_t srcBLen, q15_t * pDst, uint32_t firstIndex, uint32_t numPoints, q15_t * pScratch1, q15_t * pScratch2); /** * @brief Partial convolution of Q31 sequences. * @param[in] *pSrcA points to the first input sequence. * @param[in] srcALen length of the first input sequence. * @param[in] *pSrcB points to the second input sequence. * @param[in] srcBLen length of the second input sequence. * @param[out] *pDst points to the block of output data * @param[in] firstIndex is the first output sample to start with. * @param[in] numPoints is the number of output points to be computed. * @return Returns either ARM_MATH_SUCCESS if the function completed correctly or ARM_MATH_ARGUMENT_ERROR if the requested subset is not in the range [0 srcALen+srcBLen-2]. */ arm_status arm_conv_partial_q31( q31_t * pSrcA, uint32_t srcALen, q31_t * pSrcB, uint32_t srcBLen, q31_t * pDst, uint32_t firstIndex, uint32_t numPoints); /** * @brief Partial convolution of Q31 sequences (fast version) for Cortex-M3 and Cortex-M4 * @param[in] *pSrcA points to the first input sequence. * @param[in] srcALen length of the first input sequence. * @param[in] *pSrcB points to the second input sequence. * @param[in] srcBLen length of the second input sequence. * @param[out] *pDst points to the block of output data * @param[in] firstIndex is the first output sample to start with. * @param[in] numPoints is the number of output points to be computed. * @return Returns either ARM_MATH_SUCCESS if the function completed correctly or ARM_MATH_ARGUMENT_ERROR if the requested subset is not in the range [0 srcALen+srcBLen-2]. */ arm_status arm_conv_partial_fast_q31( q31_t * pSrcA, uint32_t srcALen, q31_t * pSrcB, uint32_t srcBLen, q31_t * pDst, uint32_t firstIndex, uint32_t numPoints); /** * @brief Partial convolution of Q7 sequences * @param[in] *pSrcA points to the first input sequence. * @param[in] srcALen length of the first input sequence. * @param[in] *pSrcB points to the second input sequence. * @param[in] srcBLen length of the second input sequence. * @param[out] *pDst points to the block of output data * @param[in] firstIndex is the first output sample to start with. * @param[in] numPoints is the number of output points to be computed. * @param[in] *pScratch1 points to scratch buffer(of type q15_t) of size max(srcALen, srcBLen) + 2*min(srcALen, srcBLen) - 2. * @param[in] *pScratch2 points to scratch buffer (of type q15_t) of size min(srcALen, srcBLen). * @return Returns either ARM_MATH_SUCCESS if the function completed correctly or ARM_MATH_ARGUMENT_ERROR if the requested subset is not in the range [0 srcALen+srcBLen-2]. */ arm_status arm_conv_partial_opt_q7( q7_t * pSrcA, uint32_t srcALen, q7_t * pSrcB, uint32_t srcBLen, q7_t * pDst, uint32_t firstIndex, uint32_t numPoints, q15_t * pScratch1, q15_t * pScratch2); /** * @brief Partial convolution of Q7 sequences. * @param[in] *pSrcA points to the first input sequence. * @param[in] srcALen length of the first input sequence. * @param[in] *pSrcB points to the second input sequence. * @param[in] srcBLen length of the second input sequence. * @param[out] *pDst points to the block of output data * @param[in] firstIndex is the first output sample to start with. * @param[in] numPoints is the number of output points to be computed. * @return Returns either ARM_MATH_SUCCESS if the function completed correctly or ARM_MATH_ARGUMENT_ERROR if the requested subset is not in the range [0 srcALen+srcBLen-2]. */ arm_status arm_conv_partial_q7( q7_t * pSrcA, uint32_t srcALen, q7_t * pSrcB, uint32_t srcBLen, q7_t * pDst, uint32_t firstIndex, uint32_t numPoints); /** * @brief Instance structure for the Q15 FIR decimator. */ typedef struct { uint8_t M; /**< decimation factor. */ uint16_t numTaps; /**< number of coefficients in the filter. */ q15_t *pCoeffs; /**< points to the coefficient array. The array is of length numTaps.*/ q15_t *pState; /**< points to the state variable array. The array is of length numTaps+blockSize-1. */ } arm_fir_decimate_instance_q15; /** * @brief Instance structure for the Q31 FIR decimator. */ typedef struct { uint8_t M; /**< decimation factor. */ uint16_t numTaps; /**< number of coefficients in the filter. */ q31_t *pCoeffs; /**< points to the coefficient array. The array is of length numTaps.*/ q31_t *pState; /**< points to the state variable array. The array is of length numTaps+blockSize-1. */ } arm_fir_decimate_instance_q31; /** * @brief Instance structure for the floating-point FIR decimator. */ typedef struct { uint8_t M; /**< decimation factor. */ uint16_t numTaps; /**< number of coefficients in the filter. */ float32_t *pCoeffs; /**< points to the coefficient array. The array is of length numTaps.*/ float32_t *pState; /**< points to the state variable array. The array is of length numTaps+blockSize-1. */ } arm_fir_decimate_instance_f32; /** * @brief Processing function for the floating-point FIR decimator. * @param[in] *S points to an instance of the floating-point FIR decimator structure. * @param[in] *pSrc points to the block of input data. * @param[out] *pDst points to the block of output data * @param[in] blockSize number of input samples to process per call. * @return none */ void arm_fir_decimate_f32( const arm_fir_decimate_instance_f32 * S, float32_t * pSrc, float32_t * pDst, uint32_t blockSize); /** * @brief Initialization function for the floating-point FIR decimator. * @param[in,out] *S points to an instance of the floating-point FIR decimator structure. * @param[in] numTaps number of coefficients in the filter. * @param[in] M decimation factor. * @param[in] *pCoeffs points to the filter coefficients. * @param[in] *pState points to the state buffer. * @param[in] blockSize number of input samples to process per call. * @return The function returns ARM_MATH_SUCCESS if initialization is successful or ARM_MATH_LENGTH_ERROR if * blockSize is not a multiple of M. */ arm_status arm_fir_decimate_init_f32( arm_fir_decimate_instance_f32 * S, uint16_t numTaps, uint8_t M, float32_t * pCoeffs, float32_t * pState, uint32_t blockSize); /** * @brief Processing function for the Q15 FIR decimator. * @param[in] *S points to an instance of the Q15 FIR decimator structure. * @param[in] *pSrc points to the block of input data. * @param[out] *pDst points to the block of output data * @param[in] blockSize number of input samples to process per call. * @return none */ void arm_fir_decimate_q15( const arm_fir_decimate_instance_q15 * S, q15_t * pSrc, q15_t * pDst, uint32_t blockSize); /** * @brief Processing function for the Q15 FIR decimator (fast variant) for Cortex-M3 and Cortex-M4. * @param[in] *S points to an instance of the Q15 FIR decimator structure. * @param[in] *pSrc points to the block of input data. * @param[out] *pDst points to the block of output data * @param[in] blockSize number of input samples to process per call. * @return none */ void arm_fir_decimate_fast_q15( const arm_fir_decimate_instance_q15 * S, q15_t * pSrc, q15_t * pDst, uint32_t blockSize); /** * @brief Initialization function for the Q15 FIR decimator. * @param[in,out] *S points to an instance of the Q15 FIR decimator structure. * @param[in] numTaps number of coefficients in the filter. * @param[in] M decimation factor. * @param[in] *pCoeffs points to the filter coefficients. * @param[in] *pState points to the state buffer. * @param[in] blockSize number of input samples to process per call. * @return The function returns ARM_MATH_SUCCESS if initialization is successful or ARM_MATH_LENGTH_ERROR if * blockSize is not a multiple of M. */ arm_status arm_fir_decimate_init_q15( arm_fir_decimate_instance_q15 * S, uint16_t numTaps, uint8_t M, q15_t * pCoeffs, q15_t * pState, uint32_t blockSize); /** * @brief Processing function for the Q31 FIR decimator. * @param[in] *S points to an instance of the Q31 FIR decimator structure. * @param[in] *pSrc points to the block of input data. * @param[out] *pDst points to the block of output data * @param[in] blockSize number of input samples to process per call. * @return none */ void arm_fir_decimate_q31( const arm_fir_decimate_instance_q31 * S, q31_t * pSrc, q31_t * pDst, uint32_t blockSize); /** * @brief Processing function for the Q31 FIR decimator (fast variant) for Cortex-M3 and Cortex-M4. * @param[in] *S points to an instance of the Q31 FIR decimator structure. * @param[in] *pSrc points to the block of input data. * @param[out] *pDst points to the block of output data * @param[in] blockSize number of input samples to process per call. * @return none */ void arm_fir_decimate_fast_q31( arm_fir_decimate_instance_q31 * S, q31_t * pSrc, q31_t * pDst, uint32_t blockSize); /** * @brief Initialization function for the Q31 FIR decimator. * @param[in,out] *S points to an instance of the Q31 FIR decimator structure. * @param[in] numTaps number of coefficients in the filter. * @param[in] M decimation factor. * @param[in] *pCoeffs points to the filter coefficients. * @param[in] *pState points to the state buffer. * @param[in] blockSize number of input samples to process per call. * @return The function returns ARM_MATH_SUCCESS if initialization is successful or ARM_MATH_LENGTH_ERROR if * blockSize is not a multiple of M. */ arm_status arm_fir_decimate_init_q31( arm_fir_decimate_instance_q31 * S, uint16_t numTaps, uint8_t M, q31_t * pCoeffs, q31_t * pState, uint32_t blockSize); /** * @brief Instance structure for the Q15 FIR interpolator. */ typedef struct { uint8_t L; /**< upsample factor. */ uint16_t phaseLength; /**< length of each polyphase filter component. */ q15_t *pCoeffs; /**< points to the coefficient array. The array is of length L*phaseLength. */ q15_t *pState; /**< points to the state variable array. The array is of length blockSize+phaseLength-1. */ } arm_fir_interpolate_instance_q15; /** * @brief Instance structure for the Q31 FIR interpolator. */ typedef struct { uint8_t L; /**< upsample factor. */ uint16_t phaseLength; /**< length of each polyphase filter component. */ q31_t *pCoeffs; /**< points to the coefficient array. The array is of length L*phaseLength. */ q31_t *pState; /**< points to the state variable array. The array is of length blockSize+phaseLength-1. */ } arm_fir_interpolate_instance_q31; /** * @brief Instance structure for the floating-point FIR interpolator. */ typedef struct { uint8_t L; /**< upsample factor. */ uint16_t phaseLength; /**< length of each polyphase filter component. */ float32_t *pCoeffs; /**< points to the coefficient array. The array is of length L*phaseLength. */ float32_t *pState; /**< points to the state variable array. The array is of length phaseLength+numTaps-1. */ } arm_fir_interpolate_instance_f32; /** * @brief Processing function for the Q15 FIR interpolator. * @param[in] *S points to an instance of the Q15 FIR interpolator structure. * @param[in] *pSrc points to the block of input data. * @param[out] *pDst points to the block of output data. * @param[in] blockSize number of input samples to process per call. * @return none. */ void arm_fir_interpolate_q15( const arm_fir_interpolate_instance_q15 * S, q15_t * pSrc, q15_t * pDst, uint32_t blockSize); /** * @brief Initialization function for the Q15 FIR interpolator. * @param[in,out] *S points to an instance of the Q15 FIR interpolator structure. * @param[in] L upsample factor. * @param[in] numTaps number of filter coefficients in the filter. * @param[in] *pCoeffs points to the filter coefficient buffer. * @param[in] *pState points to the state buffer. * @param[in] blockSize number of input samples to process per call. * @return The function returns ARM_MATH_SUCCESS if initialization is successful or ARM_MATH_LENGTH_ERROR if * the filter length numTaps is not a multiple of the interpolation factor L. */ arm_status arm_fir_interpolate_init_q15( arm_fir_interpolate_instance_q15 * S, uint8_t L, uint16_t numTaps, q15_t * pCoeffs, q15_t * pState, uint32_t blockSize); /** * @brief Processing function for the Q31 FIR interpolator. * @param[in] *S points to an instance of the Q15 FIR interpolator structure. * @param[in] *pSrc points to the block of input data. * @param[out] *pDst points to the block of output data. * @param[in] blockSize number of input samples to process per call. * @return none. */ void arm_fir_interpolate_q31( const arm_fir_interpolate_instance_q31 * S, q31_t * pSrc, q31_t * pDst, uint32_t blockSize); /** * @brief Initialization function for the Q31 FIR interpolator. * @param[in,out] *S points to an instance of the Q31 FIR interpolator structure. * @param[in] L upsample factor. * @param[in] numTaps number of filter coefficients in the filter. * @param[in] *pCoeffs points to the filter coefficient buffer. * @param[in] *pState points to the state buffer. * @param[in] blockSize number of input samples to process per call. * @return The function returns ARM_MATH_SUCCESS if initialization is successful or ARM_MATH_LENGTH_ERROR if * the filter length numTaps is not a multiple of the interpolation factor L. */ arm_status arm_fir_interpolate_init_q31( arm_fir_interpolate_instance_q31 * S, uint8_t L, uint16_t numTaps, q31_t * pCoeffs, q31_t * pState, uint32_t blockSize); /** * @brief Processing function for the floating-point FIR interpolator. * @param[in] *S points to an instance of the floating-point FIR interpolator structure. * @param[in] *pSrc points to the block of input data. * @param[out] *pDst points to the block of output data. * @param[in] blockSize number of input samples to process per call. * @return none. */ void arm_fir_interpolate_f32( const arm_fir_interpolate_instance_f32 * S, float32_t * pSrc, float32_t * pDst, uint32_t blockSize); /** * @brief Initialization function for the floating-point FIR interpolator. * @param[in,out] *S points to an instance of the floating-point FIR interpolator structure. * @param[in] L upsample factor. * @param[in] numTaps number of filter coefficients in the filter. * @param[in] *pCoeffs points to the filter coefficient buffer. * @param[in] *pState points to the state buffer. * @param[in] blockSize number of input samples to process per call. * @return The function returns ARM_MATH_SUCCESS if initialization is successful or ARM_MATH_LENGTH_ERROR if * the filter length numTaps is not a multiple of the interpolation factor L. */ arm_status arm_fir_interpolate_init_f32( arm_fir_interpolate_instance_f32 * S, uint8_t L, uint16_t numTaps, float32_t * pCoeffs, float32_t * pState, uint32_t blockSize); /** * @brief Instance structure for the high precision Q31 Biquad cascade filter. */ typedef struct { uint8_t numStages; /**< number of 2nd order stages in the filter. Overall order is 2*numStages. */ q63_t *pState; /**< points to the array of state coefficients. The array is of length 4*numStages. */ q31_t *pCoeffs; /**< points to the array of coefficients. The array is of length 5*numStages. */ uint8_t postShift; /**< additional shift, in bits, applied to each output sample. */ } arm_biquad_cas_df1_32x64_ins_q31; /** * @param[in] *S points to an instance of the high precision Q31 Biquad cascade filter structure. * @param[in] *pSrc points to the block of input data. * @param[out] *pDst points to the block of output data * @param[in] blockSize number of samples to process. * @return none. */ void arm_biquad_cas_df1_32x64_q31( const arm_biquad_cas_df1_32x64_ins_q31 * S, q31_t * pSrc, q31_t * pDst, uint32_t blockSize); /** * @param[in,out] *S points to an instance of the high precision Q31 Biquad cascade filter structure. * @param[in] numStages number of 2nd order stages in the filter. * @param[in] *pCoeffs points to the filter coefficients. * @param[in] *pState points to the state buffer. * @param[in] postShift shift to be applied to the output. Varies according to the coefficients format * @return none */ void arm_biquad_cas_df1_32x64_init_q31( arm_biquad_cas_df1_32x64_ins_q31 * S, uint8_t numStages, q31_t * pCoeffs, q63_t * pState, uint8_t postShift); /** * @brief Instance structure for the floating-point transposed direct form II Biquad cascade filter. */ typedef struct { uint8_t numStages; /**< number of 2nd order stages in the filter. Overall order is 2*numStages. */ float32_t *pState; /**< points to the array of state coefficients. The array is of length 2*numStages. */ float32_t *pCoeffs; /**< points to the array of coefficients. The array is of length 5*numStages. */ } arm_biquad_cascade_df2T_instance_f32; /** * @brief Instance structure for the floating-point transposed direct form II Biquad cascade filter. */ typedef struct { uint8_t numStages; /**< number of 2nd order stages in the filter. Overall order is 2*numStages. */ float32_t *pState; /**< points to the array of state coefficients. The array is of length 4*numStages. */ float32_t *pCoeffs; /**< points to the array of coefficients. The array is of length 5*numStages. */ } arm_biquad_cascade_stereo_df2T_instance_f32; /** * @brief Instance structure for the floating-point transposed direct form II Biquad cascade filter. */ typedef struct { uint8_t numStages; /**< number of 2nd order stages in the filter. Overall order is 2*numStages. */ float64_t *pState; /**< points to the array of state coefficients. The array is of length 2*numStages. */ float64_t *pCoeffs; /**< points to the array of coefficients. The array is of length 5*numStages. */ } arm_biquad_cascade_df2T_instance_f64; /** * @brief Processing function for the floating-point transposed direct form II Biquad cascade filter. * @param[in] *S points to an instance of the filter data structure. * @param[in] *pSrc points to the block of input data. * @param[out] *pDst points to the block of output data * @param[in] blockSize number of samples to process. * @return none. */ void arm_biquad_cascade_df2T_f32( const arm_biquad_cascade_df2T_instance_f32 * S, float32_t * pSrc, float32_t * pDst, uint32_t blockSize); /** * @brief Processing function for the floating-point transposed direct form II Biquad cascade filter. 2 channels * @param[in] *S points to an instance of the filter data structure. * @param[in] *pSrc points to the block of input data. * @param[out] *pDst points to the block of output data * @param[in] blockSize number of samples to process. * @return none. */ void arm_biquad_cascade_stereo_df2T_f32( const arm_biquad_cascade_stereo_df2T_instance_f32 * S, float32_t * pSrc, float32_t * pDst, uint32_t blockSize); /** * @brief Processing function for the floating-point transposed direct form II Biquad cascade filter. * @param[in] *S points to an instance of the filter data structure. * @param[in] *pSrc points to the block of input data. * @param[out] *pDst points to the block of output data * @param[in] blockSize number of samples to process. * @return none. */ void arm_biquad_cascade_df2T_f64( const arm_biquad_cascade_df2T_instance_f64 * S, float64_t * pSrc, float64_t * pDst, uint32_t blockSize); /** * @brief Initialization function for the floating-point transposed direct form II Biquad cascade filter. * @param[in,out] *S points to an instance of the filter data structure. * @param[in] numStages number of 2nd order stages in the filter. * @param[in] *pCoeffs points to the filter coefficients. * @param[in] *pState points to the state buffer. * @return none */ void arm_biquad_cascade_df2T_init_f32( arm_biquad_cascade_df2T_instance_f32 * S, uint8_t numStages, float32_t * pCoeffs, float32_t * pState); /** * @brief Initialization function for the floating-point transposed direct form II Biquad cascade filter. * @param[in,out] *S points to an instance of the filter data structure. * @param[in] numStages number of 2nd order stages in the filter. * @param[in] *pCoeffs points to the filter coefficients. * @param[in] *pState points to the state buffer. * @return none */ void arm_biquad_cascade_stereo_df2T_init_f32( arm_biquad_cascade_stereo_df2T_instance_f32 * S, uint8_t numStages, float32_t * pCoeffs, float32_t * pState); /** * @brief Initialization function for the floating-point transposed direct form II Biquad cascade filter. * @param[in,out] *S points to an instance of the filter data structure. * @param[in] numStages number of 2nd order stages in the filter. * @param[in] *pCoeffs points to the filter coefficients. * @param[in] *pState points to the state buffer. * @return none */ void arm_biquad_cascade_df2T_init_f64( arm_biquad_cascade_df2T_instance_f64 * S, uint8_t numStages, float64_t * pCoeffs, float64_t * pState); /** * @brief Instance structure for the Q15 FIR lattice filter. */ typedef struct { uint16_t numStages; /**< number of filter stages. */ q15_t *pState; /**< points to the state variable array. The array is of length numStages. */ q15_t *pCoeffs; /**< points to the coefficient array. The array is of length numStages. */ } arm_fir_lattice_instance_q15; /** * @brief Instance structure for the Q31 FIR lattice filter. */ typedef struct { uint16_t numStages; /**< number of filter stages. */ q31_t *pState; /**< points to the state variable array. The array is of length numStages. */ q31_t *pCoeffs; /**< points to the coefficient array. The array is of length numStages. */ } arm_fir_lattice_instance_q31; /** * @brief Instance structure for the floating-point FIR lattice filter. */ typedef struct { uint16_t numStages; /**< number of filter stages. */ float32_t *pState; /**< points to the state variable array. The array is of length numStages. */ float32_t *pCoeffs; /**< points to the coefficient array. The array is of length numStages. */ } arm_fir_lattice_instance_f32; /** * @brief Initialization function for the Q15 FIR lattice filter. * @param[in] *S points to an instance of the Q15 FIR lattice structure. * @param[in] numStages number of filter stages. * @param[in] *pCoeffs points to the coefficient buffer. The array is of length numStages. * @param[in] *pState points to the state buffer. The array is of length numStages. * @return none. */ void arm_fir_lattice_init_q15( arm_fir_lattice_instance_q15 * S, uint16_t numStages, q15_t * pCoeffs, q15_t * pState); /** * @brief Processing function for the Q15 FIR lattice filter. * @param[in] *S points to an instance of the Q15 FIR lattice structure. * @param[in] *pSrc points to the block of input data. * @param[out] *pDst points to the block of output data. * @param[in] blockSize number of samples to process. * @return none. */ void arm_fir_lattice_q15( const arm_fir_lattice_instance_q15 * S, q15_t * pSrc, q15_t * pDst, uint32_t blockSize); /** * @brief Initialization function for the Q31 FIR lattice filter. * @param[in] *S points to an instance of the Q31 FIR lattice structure. * @param[in] numStages number of filter stages. * @param[in] *pCoeffs points to the coefficient buffer. The array is of length numStages. * @param[in] *pState points to the state buffer. The array is of length numStages. * @return none. */ void arm_fir_lattice_init_q31( arm_fir_lattice_instance_q31 * S, uint16_t numStages, q31_t * pCoeffs, q31_t * pState); /** * @brief Processing function for the Q31 FIR lattice filter. * @param[in] *S points to an instance of the Q31 FIR lattice structure. * @param[in] *pSrc points to the block of input data. * @param[out] *pDst points to the block of output data * @param[in] blockSize number of samples to process. * @return none. */ void arm_fir_lattice_q31( const arm_fir_lattice_instance_q31 * S, q31_t * pSrc, q31_t * pDst, uint32_t blockSize); /** * @brief Initialization function for the floating-point FIR lattice filter. * @param[in] *S points to an instance of the floating-point FIR lattice structure. * @param[in] numStages number of filter stages. * @param[in] *pCoeffs points to the coefficient buffer. The array is of length numStages. * @param[in] *pState points to the state buffer. The array is of length numStages. * @return none. */ void arm_fir_lattice_init_f32( arm_fir_lattice_instance_f32 * S, uint16_t numStages, float32_t * pCoeffs, float32_t * pState); /** * @brief Processing function for the floating-point FIR lattice filter. * @param[in] *S points to an instance of the floating-point FIR lattice structure. * @param[in] *pSrc points to the block of input data. * @param[out] *pDst points to the block of output data * @param[in] blockSize number of samples to process. * @return none. */ void arm_fir_lattice_f32( const arm_fir_lattice_instance_f32 * S, float32_t * pSrc, float32_t * pDst, uint32_t blockSize); /** * @brief Instance structure for the Q15 IIR lattice filter. */ typedef struct { uint16_t numStages; /**< number of stages in the filter. */ q15_t *pState; /**< points to the state variable array. The array is of length numStages+blockSize. */ q15_t *pkCoeffs; /**< points to the reflection coefficient array. The array is of length numStages. */ q15_t *pvCoeffs; /**< points to the ladder coefficient array. The array is of length numStages+1. */ } arm_iir_lattice_instance_q15; /** * @brief Instance structure for the Q31 IIR lattice filter. */ typedef struct { uint16_t numStages; /**< number of stages in the filter. */ q31_t *pState; /**< points to the state variable array. The array is of length numStages+blockSize. */ q31_t *pkCoeffs; /**< points to the reflection coefficient array. The array is of length numStages. */ q31_t *pvCoeffs; /**< points to the ladder coefficient array. The array is of length numStages+1. */ } arm_iir_lattice_instance_q31; /** * @brief Instance structure for the floating-point IIR lattice filter. */ typedef struct { uint16_t numStages; /**< number of stages in the filter. */ float32_t *pState; /**< points to the state variable array. The array is of length numStages+blockSize. */ float32_t *pkCoeffs; /**< points to the reflection coefficient array. The array is of length numStages. */ float32_t *pvCoeffs; /**< points to the ladder coefficient array. The array is of length numStages+1. */ } arm_iir_lattice_instance_f32; /** * @brief Processing function for the floating-point IIR lattice filter. * @param[in] *S points to an instance of the floating-point IIR lattice structure. * @param[in] *pSrc points to the block of input data. * @param[out] *pDst points to the block of output data. * @param[in] blockSize number of samples to process. * @return none. */ void arm_iir_lattice_f32( const arm_iir_lattice_instance_f32 * S, float32_t * pSrc, float32_t * pDst, uint32_t blockSize); /** * @brief Initialization function for the floating-point IIR lattice filter. * @param[in] *S points to an instance of the floating-point IIR lattice structure. * @param[in] numStages number of stages in the filter. * @param[in] *pkCoeffs points to the reflection coefficient buffer. The array is of length numStages. * @param[in] *pvCoeffs points to the ladder coefficient buffer. The array is of length numStages+1. * @param[in] *pState points to the state buffer. The array is of length numStages+blockSize-1. * @param[in] blockSize number of samples to process. * @return none. */ void arm_iir_lattice_init_f32( arm_iir_lattice_instance_f32 * S, uint16_t numStages, float32_t * pkCoeffs, float32_t * pvCoeffs, float32_t * pState, uint32_t blockSize); /** * @brief Processing function for the Q31 IIR lattice filter. * @param[in] *S points to an instance of the Q31 IIR lattice structure. * @param[in] *pSrc points to the block of input data. * @param[out] *pDst points to the block of output data. * @param[in] blockSize number of samples to process. * @return none. */ void arm_iir_lattice_q31( const arm_iir_lattice_instance_q31 * S, q31_t * pSrc, q31_t * pDst, uint32_t blockSize); /** * @brief Initialization function for the Q31 IIR lattice filter. * @param[in] *S points to an instance of the Q31 IIR lattice structure. * @param[in] numStages number of stages in the filter. * @param[in] *pkCoeffs points to the reflection coefficient buffer. The array is of length numStages. * @param[in] *pvCoeffs points to the ladder coefficient buffer. The array is of length numStages+1. * @param[in] *pState points to the state buffer. The array is of length numStages+blockSize. * @param[in] blockSize number of samples to process. * @return none. */ void arm_iir_lattice_init_q31( arm_iir_lattice_instance_q31 * S, uint16_t numStages, q31_t * pkCoeffs, q31_t * pvCoeffs, q31_t * pState, uint32_t blockSize); /** * @brief Processing function for the Q15 IIR lattice filter. * @param[in] *S points to an instance of the Q15 IIR lattice structure. * @param[in] *pSrc points to the block of input data. * @param[out] *pDst points to the block of output data. * @param[in] blockSize number of samples to process. * @return none. */ void arm_iir_lattice_q15( const arm_iir_lattice_instance_q15 * S, q15_t * pSrc, q15_t * pDst, uint32_t blockSize); /** * @brief Initialization function for the Q15 IIR lattice filter. * @param[in] *S points to an instance of the fixed-point Q15 IIR lattice structure. * @param[in] numStages number of stages in the filter. * @param[in] *pkCoeffs points to reflection coefficient buffer. The array is of length numStages. * @param[in] *pvCoeffs points to ladder coefficient buffer. The array is of length numStages+1. * @param[in] *pState points to state buffer. The array is of length numStages+blockSize. * @param[in] blockSize number of samples to process per call. * @return none. */ void arm_iir_lattice_init_q15( arm_iir_lattice_instance_q15 * S, uint16_t numStages, q15_t * pkCoeffs, q15_t * pvCoeffs, q15_t * pState, uint32_t blockSize); /** * @brief Instance structure for the floating-point LMS filter. */ typedef struct { uint16_t numTaps; /**< number of coefficients in the filter. */ float32_t *pState; /**< points to the state variable array. The array is of length numTaps+blockSize-1. */ float32_t *pCoeffs; /**< points to the coefficient array. The array is of length numTaps. */ float32_t mu; /**< step size that controls filter coefficient updates. */ } arm_lms_instance_f32; /** * @brief Processing function for floating-point LMS filter. * @param[in] *S points to an instance of the floating-point LMS filter structure. * @param[in] *pSrc points to the block of input data. * @param[in] *pRef points to the block of reference data. * @param[out] *pOut points to the block of output data. * @param[out] *pErr points to the block of error data. * @param[in] blockSize number of samples to process. * @return none. */ void arm_lms_f32( const arm_lms_instance_f32 * S, float32_t * pSrc, float32_t * pRef, float32_t * pOut, float32_t * pErr, uint32_t blockSize); /** * @brief Initialization function for floating-point LMS filter. * @param[in] *S points to an instance of the floating-point LMS filter structure. * @param[in] numTaps number of filter coefficients. * @param[in] *pCoeffs points to the coefficient buffer. * @param[in] *pState points to state buffer. * @param[in] mu step size that controls filter coefficient updates. * @param[in] blockSize number of samples to process. * @return none. */ void arm_lms_init_f32( arm_lms_instance_f32 * S, uint16_t numTaps, float32_t * pCoeffs, float32_t * pState, float32_t mu, uint32_t blockSize); /** * @brief Instance structure for the Q15 LMS filter. */ typedef struct { uint16_t numTaps; /**< number of coefficients in the filter. */ q15_t *pState; /**< points to the state variable array. The array is of length numTaps+blockSize-1. */ q15_t *pCoeffs; /**< points to the coefficient array. The array is of length numTaps. */ q15_t mu; /**< step size that controls filter coefficient updates. */ uint32_t postShift; /**< bit shift applied to coefficients. */ } arm_lms_instance_q15; /** * @brief Initialization function for the Q15 LMS filter. * @param[in] *S points to an instance of the Q15 LMS filter structure. * @param[in] numTaps number of filter coefficients. * @param[in] *pCoeffs points to the coefficient buffer. * @param[in] *pState points to the state buffer. * @param[in] mu step size that controls filter coefficient updates. * @param[in] blockSize number of samples to process. * @param[in] postShift bit shift applied to coefficients. * @return none. */ void arm_lms_init_q15( arm_lms_instance_q15 * S, uint16_t numTaps, q15_t * pCoeffs, q15_t * pState, q15_t mu, uint32_t blockSize, uint32_t postShift); /** * @brief Processing function for Q15 LMS filter. * @param[in] *S points to an instance of the Q15 LMS filter structure. * @param[in] *pSrc points to the block of input data. * @param[in] *pRef points to the block of reference data. * @param[out] *pOut points to the block of output data. * @param[out] *pErr points to the block of error data. * @param[in] blockSize number of samples to process. * @return none. */ void arm_lms_q15( const arm_lms_instance_q15 * S, q15_t * pSrc, q15_t * pRef, q15_t * pOut, q15_t * pErr, uint32_t blockSize); /** * @brief Instance structure for the Q31 LMS filter. */ typedef struct { uint16_t numTaps; /**< number of coefficients in the filter. */ q31_t *pState; /**< points to the state variable array. The array is of length numTaps+blockSize-1. */ q31_t *pCoeffs; /**< points to the coefficient array. The array is of length numTaps. */ q31_t mu; /**< step size that controls filter coefficient updates. */ uint32_t postShift; /**< bit shift applied to coefficients. */ } arm_lms_instance_q31; /** * @brief Processing function for Q31 LMS filter. * @param[in] *S points to an instance of the Q15 LMS filter structure. * @param[in] *pSrc points to the block of input data. * @param[in] *pRef points to the block of reference data. * @param[out] *pOut points to the block of output data. * @param[out] *pErr points to the block of error data. * @param[in] blockSize number of samples to process. * @return none. */ void arm_lms_q31( const arm_lms_instance_q31 * S, q31_t * pSrc, q31_t * pRef, q31_t * pOut, q31_t * pErr, uint32_t blockSize); /** * @brief Initialization function for Q31 LMS filter. * @param[in] *S points to an instance of the Q31 LMS filter structure. * @param[in] numTaps number of filter coefficients. * @param[in] *pCoeffs points to coefficient buffer. * @param[in] *pState points to state buffer. * @param[in] mu step size that controls filter coefficient updates. * @param[in] blockSize number of samples to process. * @param[in] postShift bit shift applied to coefficients. * @return none. */ void arm_lms_init_q31( arm_lms_instance_q31 * S, uint16_t numTaps, q31_t * pCoeffs, q31_t * pState, q31_t mu, uint32_t blockSize, uint32_t postShift); /** * @brief Instance structure for the floating-point normalized LMS filter. */ typedef struct { uint16_t numTaps; /**< number of coefficients in the filter. */ float32_t *pState; /**< points to the state variable array. The array is of length numTaps+blockSize-1. */ float32_t *pCoeffs; /**< points to the coefficient array. The array is of length numTaps. */ float32_t mu; /**< step size that control filter coefficient updates. */ float32_t energy; /**< saves previous frame energy. */ float32_t x0; /**< saves previous input sample. */ } arm_lms_norm_instance_f32; /** * @brief Processing function for floating-point normalized LMS filter. * @param[in] *S points to an instance of the floating-point normalized LMS filter structure. * @param[in] *pSrc points to the block of input data. * @param[in] *pRef points to the block of reference data. * @param[out] *pOut points to the block of output data. * @param[out] *pErr points to the block of error data. * @param[in] blockSize number of samples to process. * @return none. */ void arm_lms_norm_f32( arm_lms_norm_instance_f32 * S, float32_t * pSrc, float32_t * pRef, float32_t * pOut, float32_t * pErr, uint32_t blockSize); /** * @brief Initialization function for floating-point normalized LMS filter. * @param[in] *S points to an instance of the floating-point LMS filter structure. * @param[in] numTaps number of filter coefficients. * @param[in] *pCoeffs points to coefficient buffer. * @param[in] *pState points to state buffer. * @param[in] mu step size that controls filter coefficient updates. * @param[in] blockSize number of samples to process. * @return none. */ void arm_lms_norm_init_f32( arm_lms_norm_instance_f32 * S, uint16_t numTaps, float32_t * pCoeffs, float32_t * pState, float32_t mu, uint32_t blockSize); /** * @brief Instance structure for the Q31 normalized LMS filter. */ typedef struct { uint16_t numTaps; /**< number of coefficients in the filter. */ q31_t *pState; /**< points to the state variable array. The array is of length numTaps+blockSize-1. */ q31_t *pCoeffs; /**< points to the coefficient array. The array is of length numTaps. */ q31_t mu; /**< step size that controls filter coefficient updates. */ uint8_t postShift; /**< bit shift applied to coefficients. */ q31_t *recipTable; /**< points to the reciprocal initial value table. */ q31_t energy; /**< saves previous frame energy. */ q31_t x0; /**< saves previous input sample. */ } arm_lms_norm_instance_q31; /** * @brief Processing function for Q31 normalized LMS filter. * @param[in] *S points to an instance of the Q31 normalized LMS filter structure. * @param[in] *pSrc points to the block of input data. * @param[in] *pRef points to the block of reference data. * @param[out] *pOut points to the block of output data. * @param[out] *pErr points to the block of error data. * @param[in] blockSize number of samples to process. * @return none. */ void arm_lms_norm_q31( arm_lms_norm_instance_q31 * S, q31_t * pSrc, q31_t * pRef, q31_t * pOut, q31_t * pErr, uint32_t blockSize); /** * @brief Initialization function for Q31 normalized LMS filter. * @param[in] *S points to an instance of the Q31 normalized LMS filter structure. * @param[in] numTaps number of filter coefficients. * @param[in] *pCoeffs points to coefficient buffer. * @param[in] *pState points to state buffer. * @param[in] mu step size that controls filter coefficient updates. * @param[in] blockSize number of samples to process. * @param[in] postShift bit shift applied to coefficients. * @return none. */ void arm_lms_norm_init_q31( arm_lms_norm_instance_q31 * S, uint16_t numTaps, q31_t * pCoeffs, q31_t * pState, q31_t mu, uint32_t blockSize, uint8_t postShift); /** * @brief Instance structure for the Q15 normalized LMS filter. */ typedef struct { uint16_t numTaps; /**< Number of coefficients in the filter. */ q15_t *pState; /**< points to the state variable array. The array is of length numTaps+blockSize-1. */ q15_t *pCoeffs; /**< points to the coefficient array. The array is of length numTaps. */ q15_t mu; /**< step size that controls filter coefficient updates. */ uint8_t postShift; /**< bit shift applied to coefficients. */ q15_t *recipTable; /**< Points to the reciprocal initial value table. */ q15_t energy; /**< saves previous frame energy. */ q15_t x0; /**< saves previous input sample. */ } arm_lms_norm_instance_q15; /** * @brief Processing function for Q15 normalized LMS filter. * @param[in] *S points to an instance of the Q15 normalized LMS filter structure. * @param[in] *pSrc points to the block of input data. * @param[in] *pRef points to the block of reference data. * @param[out] *pOut points to the block of output data. * @param[out] *pErr points to the block of error data. * @param[in] blockSize number of samples to process. * @return none. */ void arm_lms_norm_q15( arm_lms_norm_instance_q15 * S, q15_t * pSrc, q15_t * pRef, q15_t * pOut, q15_t * pErr, uint32_t blockSize); /** * @brief Initialization function for Q15 normalized LMS filter. * @param[in] *S points to an instance of the Q15 normalized LMS filter structure. * @param[in] numTaps number of filter coefficients. * @param[in] *pCoeffs points to coefficient buffer. * @param[in] *pState points to state buffer. * @param[in] mu step size that controls filter coefficient updates. * @param[in] blockSize number of samples to process. * @param[in] postShift bit shift applied to coefficients. * @return none. */ void arm_lms_norm_init_q15( arm_lms_norm_instance_q15 * S, uint16_t numTaps, q15_t * pCoeffs, q15_t * pState, q15_t mu, uint32_t blockSize, uint8_t postShift); /** * @brief Correlation of floating-point sequences. * @param[in] *pSrcA points to the first input sequence. * @param[in] srcALen length of the first input sequence. * @param[in] *pSrcB points to the second input sequence. * @param[in] srcBLen length of the second input sequence. * @param[out] *pDst points to the block of output data Length 2 * max(srcALen, srcBLen) - 1. * @return none. */ void arm_correlate_f32( float32_t * pSrcA, uint32_t srcALen, float32_t * pSrcB, uint32_t srcBLen, float32_t * pDst); /** * @brief Correlation of Q15 sequences * @param[in] *pSrcA points to the first input sequence. * @param[in] srcALen length of the first input sequence. * @param[in] *pSrcB points to the second input sequence. * @param[in] srcBLen length of the second input sequence. * @param[out] *pDst points to the block of output data Length 2 * max(srcALen, srcBLen) - 1. * @param[in] *pScratch points to scratch buffer of size max(srcALen, srcBLen) + 2*min(srcALen, srcBLen) - 2. * @return none. */ void arm_correlate_opt_q15( q15_t * pSrcA, uint32_t srcALen, q15_t * pSrcB, uint32_t srcBLen, q15_t * pDst, q15_t * pScratch); /** * @brief Correlation of Q15 sequences. * @param[in] *pSrcA points to the first input sequence. * @param[in] srcALen length of the first input sequence. * @param[in] *pSrcB points to the second input sequence. * @param[in] srcBLen length of the second input sequence. * @param[out] *pDst points to the block of output data Length 2 * max(srcALen, srcBLen) - 1. * @return none. */ void arm_correlate_q15( q15_t * pSrcA, uint32_t srcALen, q15_t * pSrcB, uint32_t srcBLen, q15_t * pDst); /** * @brief Correlation of Q15 sequences (fast version) for Cortex-M3 and Cortex-M4. * @param[in] *pSrcA points to the first input sequence. * @param[in] srcALen length of the first input sequence. * @param[in] *pSrcB points to the second input sequence. * @param[in] srcBLen length of the second input sequence. * @param[out] *pDst points to the block of output data Length 2 * max(srcALen, srcBLen) - 1. * @return none. */ void arm_correlate_fast_q15( q15_t * pSrcA, uint32_t srcALen, q15_t * pSrcB, uint32_t srcBLen, q15_t * pDst); /** * @brief Correlation of Q15 sequences (fast version) for Cortex-M3 and Cortex-M4. * @param[in] *pSrcA points to the first input sequence. * @param[in] srcALen length of the first input sequence. * @param[in] *pSrcB points to the second input sequence. * @param[in] srcBLen length of the second input sequence. * @param[out] *pDst points to the block of output data Length 2 * max(srcALen, srcBLen) - 1. * @param[in] *pScratch points to scratch buffer of size max(srcALen, srcBLen) + 2*min(srcALen, srcBLen) - 2. * @return none. */ void arm_correlate_fast_opt_q15( q15_t * pSrcA, uint32_t srcALen, q15_t * pSrcB, uint32_t srcBLen, q15_t * pDst, q15_t * pScratch); /** * @brief Correlation of Q31 sequences. * @param[in] *pSrcA points to the first input sequence. * @param[in] srcALen length of the first input sequence. * @param[in] *pSrcB points to the second input sequence. * @param[in] srcBLen length of the second input sequence. * @param[out] *pDst points to the block of output data Length 2 * max(srcALen, srcBLen) - 1. * @return none. */ void arm_correlate_q31( q31_t * pSrcA, uint32_t srcALen, q31_t * pSrcB, uint32_t srcBLen, q31_t * pDst); /** * @brief Correlation of Q31 sequences (fast version) for Cortex-M3 and Cortex-M4 * @param[in] *pSrcA points to the first input sequence. * @param[in] srcALen length of the first input sequence. * @param[in] *pSrcB points to the second input sequence. * @param[in] srcBLen length of the second input sequence. * @param[out] *pDst points to the block of output data Length 2 * max(srcALen, srcBLen) - 1. * @return none. */ void arm_correlate_fast_q31( q31_t * pSrcA, uint32_t srcALen, q31_t * pSrcB, uint32_t srcBLen, q31_t * pDst); /** * @brief Correlation of Q7 sequences. * @param[in] *pSrcA points to the first input sequence. * @param[in] srcALen length of the first input sequence. * @param[in] *pSrcB points to the second input sequence. * @param[in] srcBLen length of the second input sequence. * @param[out] *pDst points to the block of output data Length 2 * max(srcALen, srcBLen) - 1. * @param[in] *pScratch1 points to scratch buffer(of type q15_t) of size max(srcALen, srcBLen) + 2*min(srcALen, srcBLen) - 2. * @param[in] *pScratch2 points to scratch buffer (of type q15_t) of size min(srcALen, srcBLen). * @return none. */ void arm_correlate_opt_q7( q7_t * pSrcA, uint32_t srcALen, q7_t * pSrcB, uint32_t srcBLen, q7_t * pDst, q15_t * pScratch1, q15_t * pScratch2); /** * @brief Correlation of Q7 sequences. * @param[in] *pSrcA points to the first input sequence. * @param[in] srcALen length of the first input sequence. * @param[in] *pSrcB points to the second input sequence. * @param[in] srcBLen length of the second input sequence. * @param[out] *pDst points to the block of output data Length 2 * max(srcALen, srcBLen) - 1. * @return none. */ void arm_correlate_q7( q7_t * pSrcA, uint32_t srcALen, q7_t * pSrcB, uint32_t srcBLen, q7_t * pDst); /** * @brief Instance structure for the floating-point sparse FIR filter. */ typedef struct { uint16_t numTaps; /**< number of coefficients in the filter. */ uint16_t stateIndex; /**< state buffer index. Points to the oldest sample in the state buffer. */ float32_t *pState; /**< points to the state buffer array. The array is of length maxDelay+blockSize-1. */ float32_t *pCoeffs; /**< points to the coefficient array. The array is of length numTaps.*/ uint16_t maxDelay; /**< maximum offset specified by the pTapDelay array. */ int32_t *pTapDelay; /**< points to the array of delay values. The array is of length numTaps. */ } arm_fir_sparse_instance_f32; /** * @brief Instance structure for the Q31 sparse FIR filter. */ typedef struct { uint16_t numTaps; /**< number of coefficients in the filter. */ uint16_t stateIndex; /**< state buffer index. Points to the oldest sample in the state buffer. */ q31_t *pState; /**< points to the state buffer array. The array is of length maxDelay+blockSize-1. */ q31_t *pCoeffs; /**< points to the coefficient array. The array is of length numTaps.*/ uint16_t maxDelay; /**< maximum offset specified by the pTapDelay array. */ int32_t *pTapDelay; /**< points to the array of delay values. The array is of length numTaps. */ } arm_fir_sparse_instance_q31; /** * @brief Instance structure for the Q15 sparse FIR filter. */ typedef struct { uint16_t numTaps; /**< number of coefficients in the filter. */ uint16_t stateIndex; /**< state buffer index. Points to the oldest sample in the state buffer. */ q15_t *pState; /**< points to the state buffer array. The array is of length maxDelay+blockSize-1. */ q15_t *pCoeffs; /**< points to the coefficient array. The array is of length numTaps.*/ uint16_t maxDelay; /**< maximum offset specified by the pTapDelay array. */ int32_t *pTapDelay; /**< points to the array of delay values. The array is of length numTaps. */ } arm_fir_sparse_instance_q15; /** * @brief Instance structure for the Q7 sparse FIR filter. */ typedef struct { uint16_t numTaps; /**< number of coefficients in the filter. */ uint16_t stateIndex; /**< state buffer index. Points to the oldest sample in the state buffer. */ q7_t *pState; /**< points to the state buffer array. The array is of length maxDelay+blockSize-1. */ q7_t *pCoeffs; /**< points to the coefficient array. The array is of length numTaps.*/ uint16_t maxDelay; /**< maximum offset specified by the pTapDelay array. */ int32_t *pTapDelay; /**< points to the array of delay values. The array is of length numTaps. */ } arm_fir_sparse_instance_q7; /** * @brief Processing function for the floating-point sparse FIR filter. * @param[in] *S points to an instance of the floating-point sparse FIR structure. * @param[in] *pSrc points to the block of input data. * @param[out] *pDst points to the block of output data * @param[in] *pScratchIn points to a temporary buffer of size blockSize. * @param[in] blockSize number of input samples to process per call. * @return none. */ void arm_fir_sparse_f32( arm_fir_sparse_instance_f32 * S, float32_t * pSrc, float32_t * pDst, float32_t * pScratchIn, uint32_t blockSize); /** * @brief Initialization function for the floating-point sparse FIR filter. * @param[in,out] *S points to an instance of the floating-point sparse FIR structure. * @param[in] numTaps number of nonzero coefficients in the filter. * @param[in] *pCoeffs points to the array of filter coefficients. * @param[in] *pState points to the state buffer. * @param[in] *pTapDelay points to the array of offset times. * @param[in] maxDelay maximum offset time supported. * @param[in] blockSize number of samples that will be processed per block. * @return none */ void arm_fir_sparse_init_f32( arm_fir_sparse_instance_f32 * S, uint16_t numTaps, float32_t * pCoeffs, float32_t * pState, int32_t * pTapDelay, uint16_t maxDelay, uint32_t blockSize); /** * @brief Processing function for the Q31 sparse FIR filter. * @param[in] *S points to an instance of the Q31 sparse FIR structure. * @param[in] *pSrc points to the block of input data. * @param[out] *pDst points to the block of output data * @param[in] *pScratchIn points to a temporary buffer of size blockSize. * @param[in] blockSize number of input samples to process per call. * @return none. */ void arm_fir_sparse_q31( arm_fir_sparse_instance_q31 * S, q31_t * pSrc, q31_t * pDst, q31_t * pScratchIn, uint32_t blockSize); /** * @brief Initialization function for the Q31 sparse FIR filter. * @param[in,out] *S points to an instance of the Q31 sparse FIR structure. * @param[in] numTaps number of nonzero coefficients in the filter. * @param[in] *pCoeffs points to the array of filter coefficients. * @param[in] *pState points to the state buffer. * @param[in] *pTapDelay points to the array of offset times. * @param[in] maxDelay maximum offset time supported. * @param[in] blockSize number of samples that will be processed per block. * @return none */ void arm_fir_sparse_init_q31( arm_fir_sparse_instance_q31 * S, uint16_t numTaps, q31_t * pCoeffs, q31_t * pState, int32_t * pTapDelay, uint16_t maxDelay, uint32_t blockSize); /** * @brief Processing function for the Q15 sparse FIR filter. * @param[in] *S points to an instance of the Q15 sparse FIR structure. * @param[in] *pSrc points to the block of input data. * @param[out] *pDst points to the block of output data * @param[in] *pScratchIn points to a temporary buffer of size blockSize. * @param[in] *pScratchOut points to a temporary buffer of size blockSize. * @param[in] blockSize number of input samples to process per call. * @return none. */ void arm_fir_sparse_q15( arm_fir_sparse_instance_q15 * S, q15_t * pSrc, q15_t * pDst, q15_t * pScratchIn, q31_t * pScratchOut, uint32_t blockSize); /** * @brief Initialization function for the Q15 sparse FIR filter. * @param[in,out] *S points to an instance of the Q15 sparse FIR structure. * @param[in] numTaps number of nonzero coefficients in the filter. * @param[in] *pCoeffs points to the array of filter coefficients. * @param[in] *pState points to the state buffer. * @param[in] *pTapDelay points to the array of offset times. * @param[in] maxDelay maximum offset time supported. * @param[in] blockSize number of samples that will be processed per block. * @return none */ void arm_fir_sparse_init_q15( arm_fir_sparse_instance_q15 * S, uint16_t numTaps, q15_t * pCoeffs, q15_t * pState, int32_t * pTapDelay, uint16_t maxDelay, uint32_t blockSize); /** * @brief Processing function for the Q7 sparse FIR filter. * @param[in] *S points to an instance of the Q7 sparse FIR structure. * @param[in] *pSrc points to the block of input data. * @param[out] *pDst points to the block of output data * @param[in] *pScratchIn points to a temporary buffer of size blockSize. * @param[in] *pScratchOut points to a temporary buffer of size blockSize. * @param[in] blockSize number of input samples to process per call. * @return none. */ void arm_fir_sparse_q7( arm_fir_sparse_instance_q7 * S, q7_t * pSrc, q7_t * pDst, q7_t * pScratchIn, q31_t * pScratchOut, uint32_t blockSize); /** * @brief Initialization function for the Q7 sparse FIR filter. * @param[in,out] *S points to an instance of the Q7 sparse FIR structure. * @param[in] numTaps number of nonzero coefficients in the filter. * @param[in] *pCoeffs points to the array of filter coefficients. * @param[in] *pState points to the state buffer. * @param[in] *pTapDelay points to the array of offset times. * @param[in] maxDelay maximum offset time supported. * @param[in] blockSize number of samples that will be processed per block. * @return none */ void arm_fir_sparse_init_q7( arm_fir_sparse_instance_q7 * S, uint16_t numTaps, q7_t * pCoeffs, q7_t * pState, int32_t * pTapDelay, uint16_t maxDelay, uint32_t blockSize); /* * @brief Floating-point sin_cos function. * @param[in] theta input value in degrees * @param[out] *pSinVal points to the processed sine output. * @param[out] *pCosVal points to the processed cos output. * @return none. */ void arm_sin_cos_f32( float32_t theta, float32_t * pSinVal, float32_t * pCcosVal); /* * @brief Q31 sin_cos function. * @param[in] theta scaled input value in degrees * @param[out] *pSinVal points to the processed sine output. * @param[out] *pCosVal points to the processed cosine output. * @return none. */ void arm_sin_cos_q31( q31_t theta, q31_t * pSinVal, q31_t * pCosVal); /** * @brief Floating-point complex conjugate. * @param[in] *pSrc points to the input vector * @param[out] *pDst points to the output vector * @param[in] numSamples number of complex samples in each vector * @return none. */ void arm_cmplx_conj_f32( float32_t * pSrc, float32_t * pDst, uint32_t numSamples); /** * @brief Q31 complex conjugate. * @param[in] *pSrc points to the input vector * @param[out] *pDst points to the output vector * @param[in] numSamples number of complex samples in each vector * @return none. */ void arm_cmplx_conj_q31( q31_t * pSrc, q31_t * pDst, uint32_t numSamples); /** * @brief Q15 complex conjugate. * @param[in] *pSrc points to the input vector * @param[out] *pDst points to the output vector * @param[in] numSamples number of complex samples in each vector * @return none. */ void arm_cmplx_conj_q15( q15_t * pSrc, q15_t * pDst, uint32_t numSamples); /** * @brief Floating-point complex magnitude squared * @param[in] *pSrc points to the complex input vector * @param[out] *pDst points to the real output vector * @param[in] numSamples number of complex samples in the input vector * @return none. */ void arm_cmplx_mag_squared_f32( float32_t * pSrc, float32_t * pDst, uint32_t numSamples); /** * @brief Q31 complex magnitude squared * @param[in] *pSrc points to the complex input vector * @param[out] *pDst points to the real output vector * @param[in] numSamples number of complex samples in the input vector * @return none. */ void arm_cmplx_mag_squared_q31( q31_t * pSrc, q31_t * pDst, uint32_t numSamples); /** * @brief Q15 complex magnitude squared * @param[in] *pSrc points to the complex input vector * @param[out] *pDst points to the real output vector * @param[in] numSamples number of complex samples in the input vector * @return none. */ void arm_cmplx_mag_squared_q15( q15_t * pSrc, q15_t * pDst, uint32_t numSamples); /** * @ingroup groupController */ /** * @defgroup PID PID Motor Control * * A Proportional Integral Derivative (PID) controller is a generic feedback control * loop mechanism widely used in industrial control systems. * A PID controller is the most commonly used type of feedback controller. * * This set of functions implements (PID) controllers * for Q15, Q31, and floating-point data types. The functions operate on a single sample * of data and each call to the function returns a single processed value. * S points to an instance of the PID control data structure. in * is the input sample value. The functions return the output value. * * \par Algorithm: *
   *    y[n] = y[n-1] + A0 * x[n] + A1 * x[n-1] + A2 * x[n-2]
   *    A0 = Kp + Ki + Kd
   *    A1 = (-Kp ) - (2 * Kd )
   *    A2 = Kd  
* * \par * where \c Kp is proportional constant, \c Ki is Integral constant and \c Kd is Derivative constant * * \par * \image html PID.gif "Proportional Integral Derivative Controller" * * \par * The PID controller calculates an "error" value as the difference between * the measured output and the reference input. * The controller attempts to minimize the error by adjusting the process control inputs. * The proportional value determines the reaction to the current error, * the integral value determines the reaction based on the sum of recent errors, * and the derivative value determines the reaction based on the rate at which the error has been changing. * * \par Instance Structure * The Gains A0, A1, A2 and state variables for a PID controller are stored together in an instance data structure. * A separate instance structure must be defined for each PID Controller. * There are separate instance structure declarations for each of the 3 supported data types. * * \par Reset Functions * There is also an associated reset function for each data type which clears the state array. * * \par Initialization Functions * There is also an associated initialization function for each data type. * The initialization function performs the following operations: * - Initializes the Gains A0, A1, A2 from Kp,Ki, Kd gains. * - Zeros out the values in the state buffer. * * \par * Instance structure cannot be placed into a const data section and it is recommended to use the initialization function. * * \par Fixed-Point Behavior * Care must be taken when using the fixed-point versions of the PID Controller functions. * In particular, the overflow and saturation behavior of the accumulator used in each function must be considered. * Refer to the function specific documentation below for usage guidelines. */ /** * @addtogroup PID * @{ */ /** * @brief Process function for the floating-point PID Control. * @param[in,out] *S is an instance of the floating-point PID Control structure * @param[in] in input sample to process * @return out processed output sample. */ static __INLINE float32_t arm_pid_f32( arm_pid_instance_f32 * S, float32_t in) { float32_t out; /* y[n] = y[n-1] + A0 * x[n] + A1 * x[n-1] + A2 * x[n-2] */ out = (S->A0 * in) + (S->A1 * S->state[0]) + (S->A2 * S->state[1]) + (S->state[2]); /* Update state */ S->state[1] = S->state[0]; S->state[0] = in; S->state[2] = out; /* return to application */ return (out); } /** * @brief Process function for the Q31 PID Control. * @param[in,out] *S points to an instance of the Q31 PID Control structure * @param[in] in input sample to process * @return out processed output sample. * * Scaling and Overflow Behavior: * \par * The function is implemented using an internal 64-bit accumulator. * The accumulator has a 2.62 format and maintains full precision of the intermediate multiplication results but provides only a single guard bit. * Thus, if the accumulator result overflows it wraps around rather than clip. * In order to avoid overflows completely the input signal must be scaled down by 2 bits as there are four additions. * After all multiply-accumulates are performed, the 2.62 accumulator is truncated to 1.32 format and then saturated to 1.31 format. */ static __INLINE q31_t arm_pid_q31( arm_pid_instance_q31 * S, q31_t in) { q63_t acc; q31_t out; /* acc = A0 * x[n] */ acc = (q63_t) S->A0 * in; /* acc += A1 * x[n-1] */ acc += (q63_t) S->A1 * S->state[0]; /* acc += A2 * x[n-2] */ acc += (q63_t) S->A2 * S->state[1]; /* convert output to 1.31 format to add y[n-1] */ out = (q31_t) (acc >> 31u); /* out += y[n-1] */ out += S->state[2]; /* Update state */ S->state[1] = S->state[0]; S->state[0] = in; S->state[2] = out; /* return to application */ return (out); } /** * @brief Process function for the Q15 PID Control. * @param[in,out] *S points to an instance of the Q15 PID Control structure * @param[in] in input sample to process * @return out processed output sample. * * Scaling and Overflow Behavior: * \par * The function is implemented using a 64-bit internal accumulator. * Both Gains and state variables are represented in 1.15 format and multiplications yield a 2.30 result. * The 2.30 intermediate results are accumulated in a 64-bit accumulator in 34.30 format. * There is no risk of internal overflow with this approach and the full precision of intermediate multiplications is preserved. * After all additions have been performed, the accumulator is truncated to 34.15 format by discarding low 15 bits. * Lastly, the accumulator is saturated to yield a result in 1.15 format. */ static __INLINE q15_t arm_pid_q15( arm_pid_instance_q15 * S, q15_t in) { q63_t acc; q15_t out; #ifndef ARM_MATH_CM0_FAMILY __SIMD32_TYPE *vstate; /* Implementation of PID controller */ /* acc = A0 * x[n] */ acc = (q31_t) __SMUAD(S->A0, in); /* acc += A1 * x[n-1] + A2 * x[n-2] */ vstate = __SIMD32_CONST(S->state); acc = __SMLALD(S->A1, (q31_t) *vstate, acc); #else /* acc = A0 * x[n] */ acc = ((q31_t) S->A0) * in; /* acc += A1 * x[n-1] + A2 * x[n-2] */ acc += (q31_t) S->A1 * S->state[0]; acc += (q31_t) S->A2 * S->state[1]; #endif /* acc += y[n-1] */ acc += (q31_t) S->state[2] << 15; /* saturate the output */ out = (q15_t) (__SSAT((acc >> 15), 16)); /* Update state */ S->state[1] = S->state[0]; S->state[0] = in; S->state[2] = out; /* return to application */ return (out); } /** * @} end of PID group */ /** * @brief Floating-point matrix inverse. * @param[in] *src points to the instance of the input floating-point matrix structure. * @param[out] *dst points to the instance of the output floating-point matrix structure. * @return The function returns ARM_MATH_SIZE_MISMATCH, if the dimensions do not match. * If the input matrix is singular (does not have an inverse), then the algorithm terminates and returns error status ARM_MATH_SINGULAR. */ arm_status arm_mat_inverse_f32( const arm_matrix_instance_f32 * src, arm_matrix_instance_f32 * dst); /** * @brief Floating-point matrix inverse. * @param[in] *src points to the instance of the input floating-point matrix structure. * @param[out] *dst points to the instance of the output floating-point matrix structure. * @return The function returns ARM_MATH_SIZE_MISMATCH, if the dimensions do not match. * If the input matrix is singular (does not have an inverse), then the algorithm terminates and returns error status ARM_MATH_SINGULAR. */ arm_status arm_mat_inverse_f64( const arm_matrix_instance_f64 * src, arm_matrix_instance_f64 * dst); /** * @ingroup groupController */ /** * @defgroup clarke Vector Clarke Transform * Forward Clarke transform converts the instantaneous stator phases into a two-coordinate time invariant vector. * Generally the Clarke transform uses three-phase currents Ia, Ib and Ic to calculate currents * in the two-phase orthogonal stator axis Ialpha and Ibeta. * When Ialpha is superposed with Ia as shown in the figure below * \image html clarke.gif Stator current space vector and its components in (a,b). * and Ia + Ib + Ic = 0, in this condition Ialpha and Ibeta * can be calculated using only Ia and Ib. * * The function operates on a single sample of data and each call to the function returns the processed output. * The library provides separate functions for Q31 and floating-point data types. * \par Algorithm * \image html clarkeFormula.gif * where Ia and Ib are the instantaneous stator phases and * pIalpha and pIbeta are the two coordinates of time invariant vector. * \par Fixed-Point Behavior * Care must be taken when using the Q31 version of the Clarke transform. * In particular, the overflow and saturation behavior of the accumulator used must be considered. * Refer to the function specific documentation below for usage guidelines. */ /** * @addtogroup clarke * @{ */ /** * * @brief Floating-point Clarke transform * @param[in] Ia input three-phase coordinate a * @param[in] Ib input three-phase coordinate b * @param[out] *pIalpha points to output two-phase orthogonal vector axis alpha * @param[out] *pIbeta points to output two-phase orthogonal vector axis beta * @return none. */ static __INLINE void arm_clarke_f32( float32_t Ia, float32_t Ib, float32_t * pIalpha, float32_t * pIbeta) { /* Calculate pIalpha using the equation, pIalpha = Ia */ *pIalpha = Ia; /* Calculate pIbeta using the equation, pIbeta = (1/sqrt(3)) * Ia + (2/sqrt(3)) * Ib */ *pIbeta = ((float32_t) 0.57735026919 * Ia + (float32_t) 1.15470053838 * Ib); } /** * @brief Clarke transform for Q31 version * @param[in] Ia input three-phase coordinate a * @param[in] Ib input three-phase coordinate b * @param[out] *pIalpha points to output two-phase orthogonal vector axis alpha * @param[out] *pIbeta points to output two-phase orthogonal vector axis beta * @return none. * * Scaling and Overflow Behavior: * \par * The function is implemented using an internal 32-bit accumulator. * The accumulator maintains 1.31 format by truncating lower 31 bits of the intermediate multiplication in 2.62 format. * There is saturation on the addition, hence there is no risk of overflow. */ static __INLINE void arm_clarke_q31( q31_t Ia, q31_t Ib, q31_t * pIalpha, q31_t * pIbeta) { q31_t product1, product2; /* Temporary variables used to store intermediate results */ /* Calculating pIalpha from Ia by equation pIalpha = Ia */ *pIalpha = Ia; /* Intermediate product is calculated by (1/(sqrt(3)) * Ia) */ product1 = (q31_t) (((q63_t) Ia * 0x24F34E8B) >> 30); /* Intermediate product is calculated by (2/sqrt(3) * Ib) */ product2 = (q31_t) (((q63_t) Ib * 0x49E69D16) >> 30); /* pIbeta is calculated by adding the intermediate products */ *pIbeta = __QADD(product1, product2); } /** * @} end of clarke group */ /** * @brief Converts the elements of the Q7 vector to Q31 vector. * @param[in] *pSrc input pointer * @param[out] *pDst output pointer * @param[in] blockSize number of samples to process * @return none. */ void arm_q7_to_q31( q7_t * pSrc, q31_t * pDst, uint32_t blockSize); /** * @ingroup groupController */ /** * @defgroup inv_clarke Vector Inverse Clarke Transform * Inverse Clarke transform converts the two-coordinate time invariant vector into instantaneous stator phases. * * The function operates on a single sample of data and each call to the function returns the processed output. * The library provides separate functions for Q31 and floating-point data types. * \par Algorithm * \image html clarkeInvFormula.gif * where pIa and pIb are the instantaneous stator phases and * Ialpha and Ibeta are the two coordinates of time invariant vector. * \par Fixed-Point Behavior * Care must be taken when using the Q31 version of the Clarke transform. * In particular, the overflow and saturation behavior of the accumulator used must be considered. * Refer to the function specific documentation below for usage guidelines. */ /** * @addtogroup inv_clarke * @{ */ /** * @brief Floating-point Inverse Clarke transform * @param[in] Ialpha input two-phase orthogonal vector axis alpha * @param[in] Ibeta input two-phase orthogonal vector axis beta * @param[out] *pIa points to output three-phase coordinate a * @param[out] *pIb points to output three-phase coordinate b * @return none. */ static __INLINE void arm_inv_clarke_f32( float32_t Ialpha, float32_t Ibeta, float32_t * pIa, float32_t * pIb) { /* Calculating pIa from Ialpha by equation pIa = Ialpha */ *pIa = Ialpha; /* Calculating pIb from Ialpha and Ibeta by equation pIb = -(1/2) * Ialpha + (sqrt(3)/2) * Ibeta */ *pIb = -0.5 * Ialpha + (float32_t) 0.8660254039 *Ibeta; } /** * @brief Inverse Clarke transform for Q31 version * @param[in] Ialpha input two-phase orthogonal vector axis alpha * @param[in] Ibeta input two-phase orthogonal vector axis beta * @param[out] *pIa points to output three-phase coordinate a * @param[out] *pIb points to output three-phase coordinate b * @return none. * * Scaling and Overflow Behavior: * \par * The function is implemented using an internal 32-bit accumulator. * The accumulator maintains 1.31 format by truncating lower 31 bits of the intermediate multiplication in 2.62 format. * There is saturation on the subtraction, hence there is no risk of overflow. */ static __INLINE void arm_inv_clarke_q31( q31_t Ialpha, q31_t Ibeta, q31_t * pIa, q31_t * pIb) { q31_t product1, product2; /* Temporary variables used to store intermediate results */ /* Calculating pIa from Ialpha by equation pIa = Ialpha */ *pIa = Ialpha; /* Intermediate product is calculated by (1/(2*sqrt(3)) * Ia) */ product1 = (q31_t) (((q63_t) (Ialpha) * (0x40000000)) >> 31); /* Intermediate product is calculated by (1/sqrt(3) * pIb) */ product2 = (q31_t) (((q63_t) (Ibeta) * (0x6ED9EBA1)) >> 31); /* pIb is calculated by subtracting the products */ *pIb = __QSUB(product2, product1); } /** * @} end of inv_clarke group */ /** * @brief Converts the elements of the Q7 vector to Q15 vector. * @param[in] *pSrc input pointer * @param[out] *pDst output pointer * @param[in] blockSize number of samples to process * @return none. */ void arm_q7_to_q15( q7_t * pSrc, q15_t * pDst, uint32_t blockSize); /** * @ingroup groupController */ /** * @defgroup park Vector Park Transform * * Forward Park transform converts the input two-coordinate vector to flux and torque components. * The Park transform can be used to realize the transformation of the Ialpha and the Ibeta currents * from the stationary to the moving reference frame and control the spatial relationship between * the stator vector current and rotor flux vector. * If we consider the d axis aligned with the rotor flux, the diagram below shows the * current vector and the relationship from the two reference frames: * \image html park.gif "Stator current space vector and its component in (a,b) and in the d,q rotating reference frame" * * The function operates on a single sample of data and each call to the function returns the processed output. * The library provides separate functions for Q31 and floating-point data types. * \par Algorithm * \image html parkFormula.gif * where Ialpha and Ibeta are the stator vector components, * pId and pIq are rotor vector components and cosVal and sinVal are the * cosine and sine values of theta (rotor flux position). * \par Fixed-Point Behavior * Care must be taken when using the Q31 version of the Park transform. * In particular, the overflow and saturation behavior of the accumulator used must be considered. * Refer to the function specific documentation below for usage guidelines. */ /** * @addtogroup park * @{ */ /** * @brief Floating-point Park transform * @param[in] Ialpha input two-phase vector coordinate alpha * @param[in] Ibeta input two-phase vector coordinate beta * @param[out] *pId points to output rotor reference frame d * @param[out] *pIq points to output rotor reference frame q * @param[in] sinVal sine value of rotation angle theta * @param[in] cosVal cosine value of rotation angle theta * @return none. * * The function implements the forward Park transform. * */ static __INLINE void arm_park_f32( float32_t Ialpha, float32_t Ibeta, float32_t * pId, float32_t * pIq, float32_t sinVal, float32_t cosVal) { /* Calculate pId using the equation, pId = Ialpha * cosVal + Ibeta * sinVal */ *pId = Ialpha * cosVal + Ibeta * sinVal; /* Calculate pIq using the equation, pIq = - Ialpha * sinVal + Ibeta * cosVal */ *pIq = -Ialpha * sinVal + Ibeta * cosVal; } /** * @brief Park transform for Q31 version * @param[in] Ialpha input two-phase vector coordinate alpha * @param[in] Ibeta input two-phase vector coordinate beta * @param[out] *pId points to output rotor reference frame d * @param[out] *pIq points to output rotor reference frame q * @param[in] sinVal sine value of rotation angle theta * @param[in] cosVal cosine value of rotation angle theta * @return none. * * Scaling and Overflow Behavior: * \par * The function is implemented using an internal 32-bit accumulator. * The accumulator maintains 1.31 format by truncating lower 31 bits of the intermediate multiplication in 2.62 format. * There is saturation on the addition and subtraction, hence there is no risk of overflow. */ static __INLINE void arm_park_q31( q31_t Ialpha, q31_t Ibeta, q31_t * pId, q31_t * pIq, q31_t sinVal, q31_t cosVal) { q31_t product1, product2; /* Temporary variables used to store intermediate results */ q31_t product3, product4; /* Temporary variables used to store intermediate results */ /* Intermediate product is calculated by (Ialpha * cosVal) */ product1 = (q31_t) (((q63_t) (Ialpha) * (cosVal)) >> 31); /* Intermediate product is calculated by (Ibeta * sinVal) */ product2 = (q31_t) (((q63_t) (Ibeta) * (sinVal)) >> 31); /* Intermediate product is calculated by (Ialpha * sinVal) */ product3 = (q31_t) (((q63_t) (Ialpha) * (sinVal)) >> 31); /* Intermediate product is calculated by (Ibeta * cosVal) */ product4 = (q31_t) (((q63_t) (Ibeta) * (cosVal)) >> 31); /* Calculate pId by adding the two intermediate products 1 and 2 */ *pId = __QADD(product1, product2); /* Calculate pIq by subtracting the two intermediate products 3 from 4 */ *pIq = __QSUB(product4, product3); } /** * @} end of park group */ /** * @brief Converts the elements of the Q7 vector to floating-point vector. * @param[in] *pSrc is input pointer * @param[out] *pDst is output pointer * @param[in] blockSize is the number of samples to process * @return none. */ void arm_q7_to_float( q7_t * pSrc, float32_t * pDst, uint32_t blockSize); /** * @ingroup groupController */ /** * @defgroup inv_park Vector Inverse Park transform * Inverse Park transform converts the input flux and torque components to two-coordinate vector. * * The function operates on a single sample of data and each call to the function returns the processed output. * The library provides separate functions for Q31 and floating-point data types. * \par Algorithm * \image html parkInvFormula.gif * where pIalpha and pIbeta are the stator vector components, * Id and Iq are rotor vector components and cosVal and sinVal are the * cosine and sine values of theta (rotor flux position). * \par Fixed-Point Behavior * Care must be taken when using the Q31 version of the Park transform. * In particular, the overflow and saturation behavior of the accumulator used must be considered. * Refer to the function specific documentation below for usage guidelines. */ /** * @addtogroup inv_park * @{ */ /** * @brief Floating-point Inverse Park transform * @param[in] Id input coordinate of rotor reference frame d * @param[in] Iq input coordinate of rotor reference frame q * @param[out] *pIalpha points to output two-phase orthogonal vector axis alpha * @param[out] *pIbeta points to output two-phase orthogonal vector axis beta * @param[in] sinVal sine value of rotation angle theta * @param[in] cosVal cosine value of rotation angle theta * @return none. */ static __INLINE void arm_inv_park_f32( float32_t Id, float32_t Iq, float32_t * pIalpha, float32_t * pIbeta, float32_t sinVal, float32_t cosVal) { /* Calculate pIalpha using the equation, pIalpha = Id * cosVal - Iq * sinVal */ *pIalpha = Id * cosVal - Iq * sinVal; /* Calculate pIbeta using the equation, pIbeta = Id * sinVal + Iq * cosVal */ *pIbeta = Id * sinVal + Iq * cosVal; } /** * @brief Inverse Park transform for Q31 version * @param[in] Id input coordinate of rotor reference frame d * @param[in] Iq input coordinate of rotor reference frame q * @param[out] *pIalpha points to output two-phase orthogonal vector axis alpha * @param[out] *pIbeta points to output two-phase orthogonal vector axis beta * @param[in] sinVal sine value of rotation angle theta * @param[in] cosVal cosine value of rotation angle theta * @return none. * * Scaling and Overflow Behavior: * \par * The function is implemented using an internal 32-bit accumulator. * The accumulator maintains 1.31 format by truncating lower 31 bits of the intermediate multiplication in 2.62 format. * There is saturation on the addition, hence there is no risk of overflow. */ static __INLINE void arm_inv_park_q31( q31_t Id, q31_t Iq, q31_t * pIalpha, q31_t * pIbeta, q31_t sinVal, q31_t cosVal) { q31_t product1, product2; /* Temporary variables used to store intermediate results */ q31_t product3, product4; /* Temporary variables used to store intermediate results */ /* Intermediate product is calculated by (Id * cosVal) */ product1 = (q31_t) (((q63_t) (Id) * (cosVal)) >> 31); /* Intermediate product is calculated by (Iq * sinVal) */ product2 = (q31_t) (((q63_t) (Iq) * (sinVal)) >> 31); /* Intermediate product is calculated by (Id * sinVal) */ product3 = (q31_t) (((q63_t) (Id) * (sinVal)) >> 31); /* Intermediate product is calculated by (Iq * cosVal) */ product4 = (q31_t) (((q63_t) (Iq) * (cosVal)) >> 31); /* Calculate pIalpha by using the two intermediate products 1 and 2 */ *pIalpha = __QSUB(product1, product2); /* Calculate pIbeta by using the two intermediate products 3 and 4 */ *pIbeta = __QADD(product4, product3); } /** * @} end of Inverse park group */ /** * @brief Converts the elements of the Q31 vector to floating-point vector. * @param[in] *pSrc is input pointer * @param[out] *pDst is output pointer * @param[in] blockSize is the number of samples to process * @return none. */ void arm_q31_to_float( q31_t * pSrc, float32_t * pDst, uint32_t blockSize); /** * @ingroup groupInterpolation */ /** * @defgroup LinearInterpolate Linear Interpolation * * Linear interpolation is a method of curve fitting using linear polynomials. * Linear interpolation works by effectively drawing a straight line between two neighboring samples and returning the appropriate point along that line * * \par * \image html LinearInterp.gif "Linear interpolation" * * \par * A Linear Interpolate function calculates an output value(y), for the input(x) * using linear interpolation of the input values x0, x1( nearest input values) and the output values y0 and y1(nearest output values) * * \par Algorithm: *
   *       y = y0 + (x - x0) * ((y1 - y0)/(x1-x0))
   *       where x0, x1 are nearest values of input x
   *             y0, y1 are nearest values to output y
   * 
* * \par * This set of functions implements Linear interpolation process * for Q7, Q15, Q31, and floating-point data types. The functions operate on a single * sample of data and each call to the function returns a single processed value. * S points to an instance of the Linear Interpolate function data structure. * x is the input sample value. The functions returns the output value. * * \par * if x is outside of the table boundary, Linear interpolation returns first value of the table * if x is below input range and returns last value of table if x is above range. */ /** * @addtogroup LinearInterpolate * @{ */ /** * @brief Process function for the floating-point Linear Interpolation Function. * @param[in,out] *S is an instance of the floating-point Linear Interpolation structure * @param[in] x input sample to process * @return y processed output sample. * */ static __INLINE float32_t arm_linear_interp_f32( arm_linear_interp_instance_f32 * S, float32_t x) { float32_t y; float32_t x0, x1; /* Nearest input values */ float32_t y0, y1; /* Nearest output values */ float32_t xSpacing = S->xSpacing; /* spacing between input values */ int32_t i; /* Index variable */ float32_t *pYData = S->pYData; /* pointer to output table */ /* Calculation of index */ i = (int32_t) ((x - S->x1) / xSpacing); if(i < 0) { /* Iniatilize output for below specified range as least output value of table */ y = pYData[0]; } else if((uint32_t)i >= S->nValues) { /* Iniatilize output for above specified range as last output value of table */ y = pYData[S->nValues - 1]; } else { /* Calculation of nearest input values */ x0 = S->x1 + i * xSpacing; x1 = S->x1 + (i + 1) * xSpacing; /* Read of nearest output values */ y0 = pYData[i]; y1 = pYData[i + 1]; /* Calculation of output */ y = y0 + (x - x0) * ((y1 - y0) / (x1 - x0)); } /* returns output value */ return (y); } /** * * @brief Process function for the Q31 Linear Interpolation Function. * @param[in] *pYData pointer to Q31 Linear Interpolation table * @param[in] x input sample to process * @param[in] nValues number of table values * @return y processed output sample. * * \par * Input sample x is in 12.20 format which contains 12 bits for table index and 20 bits for fractional part. * This function can support maximum of table size 2^12. * */ static __INLINE q31_t arm_linear_interp_q31( q31_t * pYData, q31_t x, uint32_t nValues) { q31_t y; /* output */ q31_t y0, y1; /* Nearest output values */ q31_t fract; /* fractional part */ int32_t index; /* Index to read nearest output values */ /* Input is in 12.20 format */ /* 12 bits for the table index */ /* Index value calculation */ index = ((x & 0xFFF00000) >> 20); if(index >= (int32_t)(nValues - 1)) { return (pYData[nValues - 1]); } else if(index < 0) { return (pYData[0]); } else { /* 20 bits for the fractional part */ /* shift left by 11 to keep fract in 1.31 format */ fract = (x & 0x000FFFFF) << 11; /* Read two nearest output values from the index in 1.31(q31) format */ y0 = pYData[index]; y1 = pYData[index + 1u]; /* Calculation of y0 * (1-fract) and y is in 2.30 format */ y = ((q31_t) ((q63_t) y0 * (0x7FFFFFFF - fract) >> 32)); /* Calculation of y0 * (1-fract) + y1 *fract and y is in 2.30 format */ y += ((q31_t) (((q63_t) y1 * fract) >> 32)); /* Convert y to 1.31 format */ return (y << 1u); } } /** * * @brief Process function for the Q15 Linear Interpolation Function. * @param[in] *pYData pointer to Q15 Linear Interpolation table * @param[in] x input sample to process * @param[in] nValues number of table values * @return y processed output sample. * * \par * Input sample x is in 12.20 format which contains 12 bits for table index and 20 bits for fractional part. * This function can support maximum of table size 2^12. * */ static __INLINE q15_t arm_linear_interp_q15( q15_t * pYData, q31_t x, uint32_t nValues) { q63_t y; /* output */ q15_t y0, y1; /* Nearest output values */ q31_t fract; /* fractional part */ int32_t index; /* Index to read nearest output values */ /* Input is in 12.20 format */ /* 12 bits for the table index */ /* Index value calculation */ index = ((x & 0xFFF00000) >> 20u); if(index >= (int32_t)(nValues - 1)) { return (pYData[nValues - 1]); } else if(index < 0) { return (pYData[0]); } else { /* 20 bits for the fractional part */ /* fract is in 12.20 format */ fract = (x & 0x000FFFFF); /* Read two nearest output values from the index */ y0 = pYData[index]; y1 = pYData[index + 1u]; /* Calculation of y0 * (1-fract) and y is in 13.35 format */ y = ((q63_t) y0 * (0xFFFFF - fract)); /* Calculation of (y0 * (1-fract) + y1 * fract) and y is in 13.35 format */ y += ((q63_t) y1 * (fract)); /* convert y to 1.15 format */ return (y >> 20); } } /** * * @brief Process function for the Q7 Linear Interpolation Function. * @param[in] *pYData pointer to Q7 Linear Interpolation table * @param[in] x input sample to process * @param[in] nValues number of table values * @return y processed output sample. * * \par * Input sample x is in 12.20 format which contains 12 bits for table index and 20 bits for fractional part. * This function can support maximum of table size 2^12. */ static __INLINE q7_t arm_linear_interp_q7( q7_t * pYData, q31_t x, uint32_t nValues) { q31_t y; /* output */ q7_t y0, y1; /* Nearest output values */ q31_t fract; /* fractional part */ uint32_t index; /* Index to read nearest output values */ /* Input is in 12.20 format */ /* 12 bits for the table index */ /* Index value calculation */ if (x < 0) { return (pYData[0]); } index = (x >> 20) & 0xfff; if(index >= (nValues - 1)) { return (pYData[nValues - 1]); } else { /* 20 bits for the fractional part */ /* fract is in 12.20 format */ fract = (x & 0x000FFFFF); /* Read two nearest output values from the index and are in 1.7(q7) format */ y0 = pYData[index]; y1 = pYData[index + 1u]; /* Calculation of y0 * (1-fract ) and y is in 13.27(q27) format */ y = ((y0 * (0xFFFFF - fract))); /* Calculation of y1 * fract + y0 * (1-fract) and y is in 13.27(q27) format */ y += (y1 * fract); /* convert y to 1.7(q7) format */ return (y >> 20u); } } /** * @} end of LinearInterpolate group */ /** * @brief Fast approximation to the trigonometric sine function for floating-point data. * @param[in] x input value in radians. * @return sin(x). */ float32_t arm_sin_f32( float32_t x); /** * @brief Fast approximation to the trigonometric sine function for Q31 data. * @param[in] x Scaled input value in radians. * @return sin(x). */ q31_t arm_sin_q31( q31_t x); /** * @brief Fast approximation to the trigonometric sine function for Q15 data. * @param[in] x Scaled input value in radians. * @return sin(x). */ q15_t arm_sin_q15( q15_t x); /** * @brief Fast approximation to the trigonometric cosine function for floating-point data. * @param[in] x input value in radians. * @return cos(x). */ float32_t arm_cos_f32( float32_t x); /** * @brief Fast approximation to the trigonometric cosine function for Q31 data. * @param[in] x Scaled input value in radians. * @return cos(x). */ q31_t arm_cos_q31( q31_t x); /** * @brief Fast approximation to the trigonometric cosine function for Q15 data. * @param[in] x Scaled input value in radians. * @return cos(x). */ q15_t arm_cos_q15( q15_t x); /** * @ingroup groupFastMath */ /** * @defgroup SQRT Square Root * * Computes the square root of a number. * There are separate functions for Q15, Q31, and floating-point data types. * The square root function is computed using the Newton-Raphson algorithm. * This is an iterative algorithm of the form: *
   *      x1 = x0 - f(x0)/f'(x0)
   * 
* where x1 is the current estimate, * x0 is the previous estimate, and * f'(x0) is the derivative of f() evaluated at x0. * For the square root function, the algorithm reduces to: *
   *     x0 = in/2                         [initial guess]
   *     x1 = 1/2 * ( x0 + in / x0)        [each iteration]
   * 
*/ /** * @addtogroup SQRT * @{ */ /** * @brief Floating-point square root function. * @param[in] in input value. * @param[out] *pOut square root of input value. * @return The function returns ARM_MATH_SUCCESS if input value is positive value or ARM_MATH_ARGUMENT_ERROR if * in is negative value and returns zero output for negative values. */ static __INLINE arm_status arm_sqrt_f32( float32_t in, float32_t * pOut) { if(in >= 0.0f) { // #if __FPU_USED #if (__FPU_USED == 1) && defined ( __CC_ARM ) *pOut = __sqrtf(in); #else *pOut = sqrtf(in); #endif return (ARM_MATH_SUCCESS); } else { *pOut = 0.0f; return (ARM_MATH_ARGUMENT_ERROR); } } /** * @brief Q31 square root function. * @param[in] in input value. The range of the input value is [0 +1) or 0x00000000 to 0x7FFFFFFF. * @param[out] *pOut square root of input value. * @return The function returns ARM_MATH_SUCCESS if input value is positive value or ARM_MATH_ARGUMENT_ERROR if * in is negative value and returns zero output for negative values. */ arm_status arm_sqrt_q31( q31_t in, q31_t * pOut); /** * @brief Q15 square root function. * @param[in] in input value. The range of the input value is [0 +1) or 0x0000 to 0x7FFF. * @param[out] *pOut square root of input value. * @return The function returns ARM_MATH_SUCCESS if input value is positive value or ARM_MATH_ARGUMENT_ERROR if * in is negative value and returns zero output for negative values. */ arm_status arm_sqrt_q15( q15_t in, q15_t * pOut); /** * @} end of SQRT group */ /** * @brief floating-point Circular write function. */ static __INLINE void arm_circularWrite_f32( int32_t * circBuffer, int32_t L, uint16_t * writeOffset, int32_t bufferInc, const int32_t * src, int32_t srcInc, uint32_t blockSize) { uint32_t i = 0u; int32_t wOffset; /* Copy the value of Index pointer that points * to the current location where the input samples to be copied */ wOffset = *writeOffset; /* Loop over the blockSize */ i = blockSize; while(i > 0u) { /* copy the input sample to the circular buffer */ circBuffer[wOffset] = *src; /* Update the input pointer */ src += srcInc; /* Circularly update wOffset. Watch out for positive and negative value */ wOffset += bufferInc; if(wOffset >= L) wOffset -= L; /* Decrement the loop counter */ i--; } /* Update the index pointer */ *writeOffset = wOffset; } /** * @brief floating-point Circular Read function. */ static __INLINE void arm_circularRead_f32( int32_t * circBuffer, int32_t L, int32_t * readOffset, int32_t bufferInc, int32_t * dst, int32_t * dst_base, int32_t dst_length, int32_t dstInc, uint32_t blockSize) { uint32_t i = 0u; int32_t rOffset, dst_end; /* Copy the value of Index pointer that points * to the current location from where the input samples to be read */ rOffset = *readOffset; dst_end = (int32_t) (dst_base + dst_length); /* Loop over the blockSize */ i = blockSize; while(i > 0u) { /* copy the sample from the circular buffer to the destination buffer */ *dst = circBuffer[rOffset]; /* Update the input pointer */ dst += dstInc; if(dst == (int32_t *) dst_end) { dst = dst_base; } /* Circularly update rOffset. Watch out for positive and negative value */ rOffset += bufferInc; if(rOffset >= L) { rOffset -= L; } /* Decrement the loop counter */ i--; } /* Update the index pointer */ *readOffset = rOffset; } /** * @brief Q15 Circular write function. */ static __INLINE void arm_circularWrite_q15( q15_t * circBuffer, int32_t L, uint16_t * writeOffset, int32_t bufferInc, const q15_t * src, int32_t srcInc, uint32_t blockSize) { uint32_t i = 0u; int32_t wOffset; /* Copy the value of Index pointer that points * to the current location where the input samples to be copied */ wOffset = *writeOffset; /* Loop over the blockSize */ i = blockSize; while(i > 0u) { /* copy the input sample to the circular buffer */ circBuffer[wOffset] = *src; /* Update the input pointer */ src += srcInc; /* Circularly update wOffset. Watch out for positive and negative value */ wOffset += bufferInc; if(wOffset >= L) wOffset -= L; /* Decrement the loop counter */ i--; } /* Update the index pointer */ *writeOffset = wOffset; } /** * @brief Q15 Circular Read function. */ static __INLINE void arm_circularRead_q15( q15_t * circBuffer, int32_t L, int32_t * readOffset, int32_t bufferInc, q15_t * dst, q15_t * dst_base, int32_t dst_length, int32_t dstInc, uint32_t blockSize) { uint32_t i = 0; int32_t rOffset, dst_end; /* Copy the value of Index pointer that points * to the current location from where the input samples to be read */ rOffset = *readOffset; dst_end = (int32_t) (dst_base + dst_length); /* Loop over the blockSize */ i = blockSize; while(i > 0u) { /* copy the sample from the circular buffer to the destination buffer */ *dst = circBuffer[rOffset]; /* Update the input pointer */ dst += dstInc; if(dst == (q15_t *) dst_end) { dst = dst_base; } /* Circularly update wOffset. Watch out for positive and negative value */ rOffset += bufferInc; if(rOffset >= L) { rOffset -= L; } /* Decrement the loop counter */ i--; } /* Update the index pointer */ *readOffset = rOffset; } /** * @brief Q7 Circular write function. */ static __INLINE void arm_circularWrite_q7( q7_t * circBuffer, int32_t L, uint16_t * writeOffset, int32_t bufferInc, const q7_t * src, int32_t srcInc, uint32_t blockSize) { uint32_t i = 0u; int32_t wOffset; /* Copy the value of Index pointer that points * to the current location where the input samples to be copied */ wOffset = *writeOffset; /* Loop over the blockSize */ i = blockSize; while(i > 0u) { /* copy the input sample to the circular buffer */ circBuffer[wOffset] = *src; /* Update the input pointer */ src += srcInc; /* Circularly update wOffset. Watch out for positive and negative value */ wOffset += bufferInc; if(wOffset >= L) wOffset -= L; /* Decrement the loop counter */ i--; } /* Update the index pointer */ *writeOffset = wOffset; } /** * @brief Q7 Circular Read function. */ static __INLINE void arm_circularRead_q7( q7_t * circBuffer, int32_t L, int32_t * readOffset, int32_t bufferInc, q7_t * dst, q7_t * dst_base, int32_t dst_length, int32_t dstInc, uint32_t blockSize) { uint32_t i = 0; int32_t rOffset, dst_end; /* Copy the value of Index pointer that points * to the current location from where the input samples to be read */ rOffset = *readOffset; dst_end = (int32_t) (dst_base + dst_length); /* Loop over the blockSize */ i = blockSize; while(i > 0u) { /* copy the sample from the circular buffer to the destination buffer */ *dst = circBuffer[rOffset]; /* Update the input pointer */ dst += dstInc; if(dst == (q7_t *) dst_end) { dst = dst_base; } /* Circularly update rOffset. Watch out for positive and negative value */ rOffset += bufferInc; if(rOffset >= L) { rOffset -= L; } /* Decrement the loop counter */ i--; } /* Update the index pointer */ *readOffset = rOffset; } /** * @brief Sum of the squares of the elements of a Q31 vector. * @param[in] *pSrc is input pointer * @param[in] blockSize is the number of samples to process * @param[out] *pResult is output value. * @return none. */ void arm_power_q31( q31_t * pSrc, uint32_t blockSize, q63_t * pResult); /** * @brief Sum of the squares of the elements of a floating-point vector. * @param[in] *pSrc is input pointer * @param[in] blockSize is the number of samples to process * @param[out] *pResult is output value. * @return none. */ void arm_power_f32( float32_t * pSrc, uint32_t blockSize, float32_t * pResult); /** * @brief Sum of the squares of the elements of a Q15 vector. * @param[in] *pSrc is input pointer * @param[in] blockSize is the number of samples to process * @param[out] *pResult is output value. * @return none. */ void arm_power_q15( q15_t * pSrc, uint32_t blockSize, q63_t * pResult); /** * @brief Sum of the squares of the elements of a Q7 vector. * @param[in] *pSrc is input pointer * @param[in] blockSize is the number of samples to process * @param[out] *pResult is output value. * @return none. */ void arm_power_q7( q7_t * pSrc, uint32_t blockSize, q31_t * pResult); /** * @brief Mean value of a Q7 vector. * @param[in] *pSrc is input pointer * @param[in] blockSize is the number of samples to process * @param[out] *pResult is output value. * @return none. */ void arm_mean_q7( q7_t * pSrc, uint32_t blockSize, q7_t * pResult); /** * @brief Mean value of a Q15 vector. * @param[in] *pSrc is input pointer * @param[in] blockSize is the number of samples to process * @param[out] *pResult is output value. * @return none. */ void arm_mean_q15( q15_t * pSrc, uint32_t blockSize, q15_t * pResult); /** * @brief Mean value of a Q31 vector. * @param[in] *pSrc is input pointer * @param[in] blockSize is the number of samples to process * @param[out] *pResult is output value. * @return none. */ void arm_mean_q31( q31_t * pSrc, uint32_t blockSize, q31_t * pResult); /** * @brief Mean value of a floating-point vector. * @param[in] *pSrc is input pointer * @param[in] blockSize is the number of samples to process * @param[out] *pResult is output value. * @return none. */ void arm_mean_f32( float32_t * pSrc, uint32_t blockSize, float32_t * pResult); /** * @brief Variance of the elements of a floating-point vector. * @param[in] *pSrc is input pointer * @param[in] blockSize is the number of samples to process * @param[out] *pResult is output value. * @return none. */ void arm_var_f32( float32_t * pSrc, uint32_t blockSize, float32_t * pResult); /** * @brief Variance of the elements of a Q31 vector. * @param[in] *pSrc is input pointer * @param[in] blockSize is the number of samples to process * @param[out] *pResult is output value. * @return none. */ void arm_var_q31( q31_t * pSrc, uint32_t blockSize, q31_t * pResult); /** * @brief Variance of the elements of a Q15 vector. * @param[in] *pSrc is input pointer * @param[in] blockSize is the number of samples to process * @param[out] *pResult is output value. * @return none. */ void arm_var_q15( q15_t * pSrc, uint32_t blockSize, q15_t * pResult); /** * @brief Root Mean Square of the elements of a floating-point vector. * @param[in] *pSrc is input pointer * @param[in] blockSize is the number of samples to process * @param[out] *pResult is output value. * @return none. */ void arm_rms_f32( float32_t * pSrc, uint32_t blockSize, float32_t * pResult); /** * @brief Root Mean Square of the elements of a Q31 vector. * @param[in] *pSrc is input pointer * @param[in] blockSize is the number of samples to process * @param[out] *pResult is output value. * @return none. */ void arm_rms_q31( q31_t * pSrc, uint32_t blockSize, q31_t * pResult); /** * @brief Root Mean Square of the elements of a Q15 vector. * @param[in] *pSrc is input pointer * @param[in] blockSize is the number of samples to process * @param[out] *pResult is output value. * @return none. */ void arm_rms_q15( q15_t * pSrc, uint32_t blockSize, q15_t * pResult); /** * @brief Standard deviation of the elements of a floating-point vector. * @param[in] *pSrc is input pointer * @param[in] blockSize is the number of samples to process * @param[out] *pResult is output value. * @return none. */ void arm_std_f32( float32_t * pSrc, uint32_t blockSize, float32_t * pResult); /** * @brief Standard deviation of the elements of a Q31 vector. * @param[in] *pSrc is input pointer * @param[in] blockSize is the number of samples to process * @param[out] *pResult is output value. * @return none. */ void arm_std_q31( q31_t * pSrc, uint32_t blockSize, q31_t * pResult); /** * @brief Standard deviation of the elements of a Q15 vector. * @param[in] *pSrc is input pointer * @param[in] blockSize is the number of samples to process * @param[out] *pResult is output value. * @return none. */ void arm_std_q15( q15_t * pSrc, uint32_t blockSize, q15_t * pResult); /** * @brief Floating-point complex magnitude * @param[in] *pSrc points to the complex input vector * @param[out] *pDst points to the real output vector * @param[in] numSamples number of complex samples in the input vector * @return none. */ void arm_cmplx_mag_f32( float32_t * pSrc, float32_t * pDst, uint32_t numSamples); /** * @brief Q31 complex magnitude * @param[in] *pSrc points to the complex input vector * @param[out] *pDst points to the real output vector * @param[in] numSamples number of complex samples in the input vector * @return none. */ void arm_cmplx_mag_q31( q31_t * pSrc, q31_t * pDst, uint32_t numSamples); /** * @brief Q15 complex magnitude * @param[in] *pSrc points to the complex input vector * @param[out] *pDst points to the real output vector * @param[in] numSamples number of complex samples in the input vector * @return none. */ void arm_cmplx_mag_q15( q15_t * pSrc, q15_t * pDst, uint32_t numSamples); /** * @brief Q15 complex dot product * @param[in] *pSrcA points to the first input vector * @param[in] *pSrcB points to the second input vector * @param[in] numSamples number of complex samples in each vector * @param[out] *realResult real part of the result returned here * @param[out] *imagResult imaginary part of the result returned here * @return none. */ void arm_cmplx_dot_prod_q15( q15_t * pSrcA, q15_t * pSrcB, uint32_t numSamples, q31_t * realResult, q31_t * imagResult); /** * @brief Q31 complex dot product * @param[in] *pSrcA points to the first input vector * @param[in] *pSrcB points to the second input vector * @param[in] numSamples number of complex samples in each vector * @param[out] *realResult real part of the result returned here * @param[out] *imagResult imaginary part of the result returned here * @return none. */ void arm_cmplx_dot_prod_q31( q31_t * pSrcA, q31_t * pSrcB, uint32_t numSamples, q63_t * realResult, q63_t * imagResult); /** * @brief Floating-point complex dot product * @param[in] *pSrcA points to the first input vector * @param[in] *pSrcB points to the second input vector * @param[in] numSamples number of complex samples in each vector * @param[out] *realResult real part of the result returned here * @param[out] *imagResult imaginary part of the result returned here * @return none. */ void arm_cmplx_dot_prod_f32( float32_t * pSrcA, float32_t * pSrcB, uint32_t numSamples, float32_t * realResult, float32_t * imagResult); /** * @brief Q15 complex-by-real multiplication * @param[in] *pSrcCmplx points to the complex input vector * @param[in] *pSrcReal points to the real input vector * @param[out] *pCmplxDst points to the complex output vector * @param[in] numSamples number of samples in each vector * @return none. */ void arm_cmplx_mult_real_q15( q15_t * pSrcCmplx, q15_t * pSrcReal, q15_t * pCmplxDst, uint32_t numSamples); /** * @brief Q31 complex-by-real multiplication * @param[in] *pSrcCmplx points to the complex input vector * @param[in] *pSrcReal points to the real input vector * @param[out] *pCmplxDst points to the complex output vector * @param[in] numSamples number of samples in each vector * @return none. */ void arm_cmplx_mult_real_q31( q31_t * pSrcCmplx, q31_t * pSrcReal, q31_t * pCmplxDst, uint32_t numSamples); /** * @brief Floating-point complex-by-real multiplication * @param[in] *pSrcCmplx points to the complex input vector * @param[in] *pSrcReal points to the real input vector * @param[out] *pCmplxDst points to the complex output vector * @param[in] numSamples number of samples in each vector * @return none. */ void arm_cmplx_mult_real_f32( float32_t * pSrcCmplx, float32_t * pSrcReal, float32_t * pCmplxDst, uint32_t numSamples); /** * @brief Minimum value of a Q7 vector. * @param[in] *pSrc is input pointer * @param[in] blockSize is the number of samples to process * @param[out] *result is output pointer * @param[in] index is the array index of the minimum value in the input buffer. * @return none. */ void arm_min_q7( q7_t * pSrc, uint32_t blockSize, q7_t * result, uint32_t * index); /** * @brief Minimum value of a Q15 vector. * @param[in] *pSrc is input pointer * @param[in] blockSize is the number of samples to process * @param[out] *pResult is output pointer * @param[in] *pIndex is the array index of the minimum value in the input buffer. * @return none. */ void arm_min_q15( q15_t * pSrc, uint32_t blockSize, q15_t * pResult, uint32_t * pIndex); /** * @brief Minimum value of a Q31 vector. * @param[in] *pSrc is input pointer * @param[in] blockSize is the number of samples to process * @param[out] *pResult is output pointer * @param[out] *pIndex is the array index of the minimum value in the input buffer. * @return none. */ void arm_min_q31( q31_t * pSrc, uint32_t blockSize, q31_t * pResult, uint32_t * pIndex); /** * @brief Minimum value of a floating-point vector. * @param[in] *pSrc is input pointer * @param[in] blockSize is the number of samples to process * @param[out] *pResult is output pointer * @param[out] *pIndex is the array index of the minimum value in the input buffer. * @return none. */ void arm_min_f32( float32_t * pSrc, uint32_t blockSize, float32_t * pResult, uint32_t * pIndex); /** * @brief Maximum value of a Q7 vector. * @param[in] *pSrc points to the input buffer * @param[in] blockSize length of the input vector * @param[out] *pResult maximum value returned here * @param[out] *pIndex index of maximum value returned here * @return none. */ void arm_max_q7( q7_t * pSrc, uint32_t blockSize, q7_t * pResult, uint32_t * pIndex); /** * @brief Maximum value of a Q15 vector. * @param[in] *pSrc points to the input buffer * @param[in] blockSize length of the input vector * @param[out] *pResult maximum value returned here * @param[out] *pIndex index of maximum value returned here * @return none. */ void arm_max_q15( q15_t * pSrc, uint32_t blockSize, q15_t * pResult, uint32_t * pIndex); /** * @brief Maximum value of a Q31 vector. * @param[in] *pSrc points to the input buffer * @param[in] blockSize length of the input vector * @param[out] *pResult maximum value returned here * @param[out] *pIndex index of maximum value returned here * @return none. */ void arm_max_q31( q31_t * pSrc, uint32_t blockSize, q31_t * pResult, uint32_t * pIndex); /** * @brief Maximum value of a floating-point vector. * @param[in] *pSrc points to the input buffer * @param[in] blockSize length of the input vector * @param[out] *pResult maximum value returned here * @param[out] *pIndex index of maximum value returned here * @return none. */ void arm_max_f32( float32_t * pSrc, uint32_t blockSize, float32_t * pResult, uint32_t * pIndex); /** * @brief Q15 complex-by-complex multiplication * @param[in] *pSrcA points to the first input vector * @param[in] *pSrcB points to the second input vector * @param[out] *pDst points to the output vector * @param[in] numSamples number of complex samples in each vector * @return none. */ void arm_cmplx_mult_cmplx_q15( q15_t * pSrcA, q15_t * pSrcB, q15_t * pDst, uint32_t numSamples); /** * @brief Q31 complex-by-complex multiplication * @param[in] *pSrcA points to the first input vector * @param[in] *pSrcB points to the second input vector * @param[out] *pDst points to the output vector * @param[in] numSamples number of complex samples in each vector * @return none. */ void arm_cmplx_mult_cmplx_q31( q31_t * pSrcA, q31_t * pSrcB, q31_t * pDst, uint32_t numSamples); /** * @brief Floating-point complex-by-complex multiplication * @param[in] *pSrcA points to the first input vector * @param[in] *pSrcB points to the second input vector * @param[out] *pDst points to the output vector * @param[in] numSamples number of complex samples in each vector * @return none. */ void arm_cmplx_mult_cmplx_f32( float32_t * pSrcA, float32_t * pSrcB, float32_t * pDst, uint32_t numSamples); /** * @brief Converts the elements of the floating-point vector to Q31 vector. * @param[in] *pSrc points to the floating-point input vector * @param[out] *pDst points to the Q31 output vector * @param[in] blockSize length of the input vector * @return none. */ void arm_float_to_q31( float32_t * pSrc, q31_t * pDst, uint32_t blockSize); /** * @brief Converts the elements of the floating-point vector to Q15 vector. * @param[in] *pSrc points to the floating-point input vector * @param[out] *pDst points to the Q15 output vector * @param[in] blockSize length of the input vector * @return none */ void arm_float_to_q15( float32_t * pSrc, q15_t * pDst, uint32_t blockSize); /** * @brief Converts the elements of the floating-point vector to Q7 vector. * @param[in] *pSrc points to the floating-point input vector * @param[out] *pDst points to the Q7 output vector * @param[in] blockSize length of the input vector * @return none */ void arm_float_to_q7( float32_t * pSrc, q7_t * pDst, uint32_t blockSize); /** * @brief Converts the elements of the Q31 vector to Q15 vector. * @param[in] *pSrc is input pointer * @param[out] *pDst is output pointer * @param[in] blockSize is the number of samples to process * @return none. */ void arm_q31_to_q15( q31_t * pSrc, q15_t * pDst, uint32_t blockSize); /** * @brief Converts the elements of the Q31 vector to Q7 vector. * @param[in] *pSrc is input pointer * @param[out] *pDst is output pointer * @param[in] blockSize is the number of samples to process * @return none. */ void arm_q31_to_q7( q31_t * pSrc, q7_t * pDst, uint32_t blockSize); /** * @brief Converts the elements of the Q15 vector to floating-point vector. * @param[in] *pSrc is input pointer * @param[out] *pDst is output pointer * @param[in] blockSize is the number of samples to process * @return none. */ void arm_q15_to_float( q15_t * pSrc, float32_t * pDst, uint32_t blockSize); /** * @brief Converts the elements of the Q15 vector to Q31 vector. * @param[in] *pSrc is input pointer * @param[out] *pDst is output pointer * @param[in] blockSize is the number of samples to process * @return none. */ void arm_q15_to_q31( q15_t * pSrc, q31_t * pDst, uint32_t blockSize); /** * @brief Converts the elements of the Q15 vector to Q7 vector. * @param[in] *pSrc is input pointer * @param[out] *pDst is output pointer * @param[in] blockSize is the number of samples to process * @return none. */ void arm_q15_to_q7( q15_t * pSrc, q7_t * pDst, uint32_t blockSize); /** * @ingroup groupInterpolation */ /** * @defgroup BilinearInterpolate Bilinear Interpolation * * Bilinear interpolation is an extension of linear interpolation applied to a two dimensional grid. * The underlying function f(x, y) is sampled on a regular grid and the interpolation process * determines values between the grid points. * Bilinear interpolation is equivalent to two step linear interpolation, first in the x-dimension and then in the y-dimension. * Bilinear interpolation is often used in image processing to rescale images. * The CMSIS DSP library provides bilinear interpolation functions for Q7, Q15, Q31, and floating-point data types. * * Algorithm * \par * The instance structure used by the bilinear interpolation functions describes a two dimensional data table. * For floating-point, the instance structure is defined as: *
   *   typedef struct
   *   {
   *     uint16_t numRows;
   *     uint16_t numCols;
   *     float32_t *pData;
   * } arm_bilinear_interp_instance_f32;
   * 
* * \par * where numRows specifies the number of rows in the table; * numCols specifies the number of columns in the table; * and pData points to an array of size numRows*numCols values. * The data table pTable is organized in row order and the supplied data values fall on integer indexes. * That is, table element (x,y) is located at pTable[x + y*numCols] where x and y are integers. * * \par * Let (x, y) specify the desired interpolation point. Then define: *
   *     XF = floor(x)
   *     YF = floor(y)
   * 
* \par * The interpolated output point is computed as: *
   *  f(x, y) = f(XF, YF) * (1-(x-XF)) * (1-(y-YF))
   *           + f(XF+1, YF) * (x-XF)*(1-(y-YF))
   *           + f(XF, YF+1) * (1-(x-XF))*(y-YF)
   *           + f(XF+1, YF+1) * (x-XF)*(y-YF)
   * 
* Note that the coordinates (x, y) contain integer and fractional components. * The integer components specify which portion of the table to use while the * fractional components control the interpolation processor. * * \par * if (x,y) are outside of the table boundary, Bilinear interpolation returns zero output. */ /** * @addtogroup BilinearInterpolate * @{ */ /** * * @brief Floating-point bilinear interpolation. * @param[in,out] *S points to an instance of the interpolation structure. * @param[in] X interpolation coordinate. * @param[in] Y interpolation coordinate. * @return out interpolated value. */ static __INLINE float32_t arm_bilinear_interp_f32( const arm_bilinear_interp_instance_f32 * S, float32_t X, float32_t Y) { float32_t out; float32_t f00, f01, f10, f11; float32_t *pData = S->pData; int32_t xIndex, yIndex, index; float32_t xdiff, ydiff; float32_t b1, b2, b3, b4; xIndex = (int32_t) X; yIndex = (int32_t) Y; /* Care taken for table outside boundary */ /* Returns zero output when values are outside table boundary */ if(xIndex < 0 || xIndex > (S->numRows - 1) || yIndex < 0 || yIndex > (S->numCols - 1)) { return (0); } /* Calculation of index for two nearest points in X-direction */ index = (xIndex - 1) + (yIndex - 1) * S->numCols; /* Read two nearest points in X-direction */ f00 = pData[index]; f01 = pData[index + 1]; /* Calculation of index for two nearest points in Y-direction */ index = (xIndex - 1) + (yIndex) * S->numCols; /* Read two nearest points in Y-direction */ f10 = pData[index]; f11 = pData[index + 1]; /* Calculation of intermediate values */ b1 = f00; b2 = f01 - f00; b3 = f10 - f00; b4 = f00 - f01 - f10 + f11; /* Calculation of fractional part in X */ xdiff = X - xIndex; /* Calculation of fractional part in Y */ ydiff = Y - yIndex; /* Calculation of bi-linear interpolated output */ out = b1 + b2 * xdiff + b3 * ydiff + b4 * xdiff * ydiff; /* return to application */ return (out); } /** * * @brief Q31 bilinear interpolation. * @param[in,out] *S points to an instance of the interpolation structure. * @param[in] X interpolation coordinate in 12.20 format. * @param[in] Y interpolation coordinate in 12.20 format. * @return out interpolated value. */ static __INLINE q31_t arm_bilinear_interp_q31( arm_bilinear_interp_instance_q31 * S, q31_t X, q31_t Y) { q31_t out; /* Temporary output */ q31_t acc = 0; /* output */ q31_t xfract, yfract; /* X, Y fractional parts */ q31_t x1, x2, y1, y2; /* Nearest output values */ int32_t rI, cI; /* Row and column indices */ q31_t *pYData = S->pData; /* pointer to output table values */ uint32_t nCols = S->numCols; /* num of rows */ /* Input is in 12.20 format */ /* 12 bits for the table index */ /* Index value calculation */ rI = ((X & 0xFFF00000) >> 20u); /* Input is in 12.20 format */ /* 12 bits for the table index */ /* Index value calculation */ cI = ((Y & 0xFFF00000) >> 20u); /* Care taken for table outside boundary */ /* Returns zero output when values are outside table boundary */ if(rI < 0 || rI > (S->numRows - 1) || cI < 0 || cI > (S->numCols - 1)) { return (0); } /* 20 bits for the fractional part */ /* shift left xfract by 11 to keep 1.31 format */ xfract = (X & 0x000FFFFF) << 11u; /* Read two nearest output values from the index */ x1 = pYData[(rI) + nCols * (cI)]; x2 = pYData[(rI) + nCols * (cI) + 1u]; /* 20 bits for the fractional part */ /* shift left yfract by 11 to keep 1.31 format */ yfract = (Y & 0x000FFFFF) << 11u; /* Read two nearest output values from the index */ y1 = pYData[(rI) + nCols * (cI + 1)]; y2 = pYData[(rI) + nCols * (cI + 1) + 1u]; /* Calculation of x1 * (1-xfract ) * (1-yfract) and acc is in 3.29(q29) format */ out = ((q31_t) (((q63_t) x1 * (0x7FFFFFFF - xfract)) >> 32)); acc = ((q31_t) (((q63_t) out * (0x7FFFFFFF - yfract)) >> 32)); /* x2 * (xfract) * (1-yfract) in 3.29(q29) and adding to acc */ out = ((q31_t) ((q63_t) x2 * (0x7FFFFFFF - yfract) >> 32)); acc += ((q31_t) ((q63_t) out * (xfract) >> 32)); /* y1 * (1 - xfract) * (yfract) in 3.29(q29) and adding to acc */ out = ((q31_t) ((q63_t) y1 * (0x7FFFFFFF - xfract) >> 32)); acc += ((q31_t) ((q63_t) out * (yfract) >> 32)); /* y2 * (xfract) * (yfract) in 3.29(q29) and adding to acc */ out = ((q31_t) ((q63_t) y2 * (xfract) >> 32)); acc += ((q31_t) ((q63_t) out * (yfract) >> 32)); /* Convert acc to 1.31(q31) format */ return (acc << 2u); } /** * @brief Q15 bilinear interpolation. * @param[in,out] *S points to an instance of the interpolation structure. * @param[in] X interpolation coordinate in 12.20 format. * @param[in] Y interpolation coordinate in 12.20 format. * @return out interpolated value. */ static __INLINE q15_t arm_bilinear_interp_q15( arm_bilinear_interp_instance_q15 * S, q31_t X, q31_t Y) { q63_t acc = 0; /* output */ q31_t out; /* Temporary output */ q15_t x1, x2, y1, y2; /* Nearest output values */ q31_t xfract, yfract; /* X, Y fractional parts */ int32_t rI, cI; /* Row and column indices */ q15_t *pYData = S->pData; /* pointer to output table values */ uint32_t nCols = S->numCols; /* num of rows */ /* Input is in 12.20 format */ /* 12 bits for the table index */ /* Index value calculation */ rI = ((X & 0xFFF00000) >> 20); /* Input is in 12.20 format */ /* 12 bits for the table index */ /* Index value calculation */ cI = ((Y & 0xFFF00000) >> 20); /* Care taken for table outside boundary */ /* Returns zero output when values are outside table boundary */ if(rI < 0 || rI > (S->numRows - 1) || cI < 0 || cI > (S->numCols - 1)) { return (0); } /* 20 bits for the fractional part */ /* xfract should be in 12.20 format */ xfract = (X & 0x000FFFFF); /* Read two nearest output values from the index */ x1 = pYData[(rI) + nCols * (cI)]; x2 = pYData[(rI) + nCols * (cI) + 1u]; /* 20 bits for the fractional part */ /* yfract should be in 12.20 format */ yfract = (Y & 0x000FFFFF); /* Read two nearest output values from the index */ y1 = pYData[(rI) + nCols * (cI + 1)]; y2 = pYData[(rI) + nCols * (cI + 1) + 1u]; /* Calculation of x1 * (1-xfract ) * (1-yfract) and acc is in 13.51 format */ /* x1 is in 1.15(q15), xfract in 12.20 format and out is in 13.35 format */ /* convert 13.35 to 13.31 by right shifting and out is in 1.31 */ out = (q31_t) (((q63_t) x1 * (0xFFFFF - xfract)) >> 4u); acc = ((q63_t) out * (0xFFFFF - yfract)); /* x2 * (xfract) * (1-yfract) in 1.51 and adding to acc */ out = (q31_t) (((q63_t) x2 * (0xFFFFF - yfract)) >> 4u); acc += ((q63_t) out * (xfract)); /* y1 * (1 - xfract) * (yfract) in 1.51 and adding to acc */ out = (q31_t) (((q63_t) y1 * (0xFFFFF - xfract)) >> 4u); acc += ((q63_t) out * (yfract)); /* y2 * (xfract) * (yfract) in 1.51 and adding to acc */ out = (q31_t) (((q63_t) y2 * (xfract)) >> 4u); acc += ((q63_t) out * (yfract)); /* acc is in 13.51 format and down shift acc by 36 times */ /* Convert out to 1.15 format */ return (acc >> 36); } /** * @brief Q7 bilinear interpolation. * @param[in,out] *S points to an instance of the interpolation structure. * @param[in] X interpolation coordinate in 12.20 format. * @param[in] Y interpolation coordinate in 12.20 format. * @return out interpolated value. */ static __INLINE q7_t arm_bilinear_interp_q7( arm_bilinear_interp_instance_q7 * S, q31_t X, q31_t Y) { q63_t acc = 0; /* output */ q31_t out; /* Temporary output */ q31_t xfract, yfract; /* X, Y fractional parts */ q7_t x1, x2, y1, y2; /* Nearest output values */ int32_t rI, cI; /* Row and column indices */ q7_t *pYData = S->pData; /* pointer to output table values */ uint32_t nCols = S->numCols; /* num of rows */ /* Input is in 12.20 format */ /* 12 bits for the table index */ /* Index value calculation */ rI = ((X & 0xFFF00000) >> 20); /* Input is in 12.20 format */ /* 12 bits for the table index */ /* Index value calculation */ cI = ((Y & 0xFFF00000) >> 20); /* Care taken for table outside boundary */ /* Returns zero output when values are outside table boundary */ if(rI < 0 || rI > (S->numRows - 1) || cI < 0 || cI > (S->numCols - 1)) { return (0); } /* 20 bits for the fractional part */ /* xfract should be in 12.20 format */ xfract = (X & 0x000FFFFF); /* Read two nearest output values from the index */ x1 = pYData[(rI) + nCols * (cI)]; x2 = pYData[(rI) + nCols * (cI) + 1u]; /* 20 bits for the fractional part */ /* yfract should be in 12.20 format */ yfract = (Y & 0x000FFFFF); /* Read two nearest output values from the index */ y1 = pYData[(rI) + nCols * (cI + 1)]; y2 = pYData[(rI) + nCols * (cI + 1) + 1u]; /* Calculation of x1 * (1-xfract ) * (1-yfract) and acc is in 16.47 format */ out = ((x1 * (0xFFFFF - xfract))); acc = (((q63_t) out * (0xFFFFF - yfract))); /* x2 * (xfract) * (1-yfract) in 2.22 and adding to acc */ out = ((x2 * (0xFFFFF - yfract))); acc += (((q63_t) out * (xfract))); /* y1 * (1 - xfract) * (yfract) in 2.22 and adding to acc */ out = ((y1 * (0xFFFFF - xfract))); acc += (((q63_t) out * (yfract))); /* y2 * (xfract) * (yfract) in 2.22 and adding to acc */ out = ((y2 * (yfract))); acc += (((q63_t) out * (xfract))); /* acc in 16.47 format and down shift by 40 to convert to 1.7 format */ return (acc >> 40); } /** * @} end of BilinearInterpolate group */ //SMMLAR #define multAcc_32x32_keep32_R(a, x, y) \ a = (q31_t) (((((q63_t) a) << 32) + ((q63_t) x * y) + 0x80000000LL ) >> 32) //SMMLSR #define multSub_32x32_keep32_R(a, x, y) \ a = (q31_t) (((((q63_t) a) << 32) - ((q63_t) x * y) + 0x80000000LL ) >> 32) //SMMULR #define mult_32x32_keep32_R(a, x, y) \ a = (q31_t) (((q63_t) x * y + 0x80000000LL ) >> 32) //SMMLA #define multAcc_32x32_keep32(a, x, y) \ a += (q31_t) (((q63_t) x * y) >> 32) //SMMLS #define multSub_32x32_keep32(a, x, y) \ a -= (q31_t) (((q63_t) x * y) >> 32) //SMMUL #define mult_32x32_keep32(a, x, y) \ a = (q31_t) (((q63_t) x * y ) >> 32) #if defined ( __CC_ARM ) //Keil //Enter low optimization region - place directly above function definition #ifdef ARM_MATH_CM4 #define LOW_OPTIMIZATION_ENTER \ _Pragma ("push") \ _Pragma ("O1") #else #define LOW_OPTIMIZATION_ENTER #endif //Exit low optimization region - place directly after end of function definition #ifdef ARM_MATH_CM4 #define LOW_OPTIMIZATION_EXIT \ _Pragma ("pop") #else #define LOW_OPTIMIZATION_EXIT #endif //Enter low optimization region - place directly above function definition #define IAR_ONLY_LOW_OPTIMIZATION_ENTER //Exit low optimization region - place directly after end of function definition #define IAR_ONLY_LOW_OPTIMIZATION_EXIT #elif defined(__ICCARM__) //IAR //Enter low optimization region - place directly above function definition #ifdef ARM_MATH_CM4 #define LOW_OPTIMIZATION_ENTER \ _Pragma ("optimize=low") #else #define LOW_OPTIMIZATION_ENTER #endif //Exit low optimization region - place directly after end of function definition #define LOW_OPTIMIZATION_EXIT //Enter low optimization region - place directly above function definition #ifdef ARM_MATH_CM4 #define IAR_ONLY_LOW_OPTIMIZATION_ENTER \ _Pragma ("optimize=low") #else #define IAR_ONLY_LOW_OPTIMIZATION_ENTER #endif //Exit low optimization region - place directly after end of function definition #define IAR_ONLY_LOW_OPTIMIZATION_EXIT #elif defined(__GNUC__) #define LOW_OPTIMIZATION_ENTER __attribute__(( optimize("-O1") )) #define LOW_OPTIMIZATION_EXIT #define IAR_ONLY_LOW_OPTIMIZATION_ENTER #define IAR_ONLY_LOW_OPTIMIZATION_EXIT #elif defined(__CSMC__) // Cosmic #define LOW_OPTIMIZATION_ENTER #define LOW_OPTIMIZATION_EXIT #define IAR_ONLY_LOW_OPTIMIZATION_ENTER #define IAR_ONLY_LOW_OPTIMIZATION_EXIT #elif defined(__TASKING__) // TASKING #define LOW_OPTIMIZATION_ENTER #define LOW_OPTIMIZATION_EXIT #define IAR_ONLY_LOW_OPTIMIZATION_ENTER #define IAR_ONLY_LOW_OPTIMIZATION_EXIT #endif #ifdef __cplusplus } #endif #endif /* _ARM_MATH_H */ /** * * End of file. */ ================================================ FILE: Zelig/mbed/TARGET_NUCLEO_F401RE/cmsis.h ================================================ /* mbed Microcontroller Library * A generic CMSIS include header ******************************************************************************* * Copyright (c) 2014, STMicroelectronics * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * 1. Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * 3. Neither the name of 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. ******************************************************************************* */ #ifndef MBED_CMSIS_H #define MBED_CMSIS_H #include "stm32f4xx.h" #include "cmsis_nvic.h" #endif ================================================ FILE: Zelig/mbed/TARGET_NUCLEO_F401RE/cmsis_nvic.h ================================================ /* mbed Microcontroller Library * CMSIS-style functionality to support dynamic vectors ******************************************************************************* * Copyright (c) 2014, STMicroelectronics * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * 1. Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * 3. Neither the name of 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. ******************************************************************************* */ #ifndef MBED_CMSIS_NVIC_H #define MBED_CMSIS_NVIC_H // STM32F401RE // CORE: 16 vectors = 64 bytes from 0x00 to 0x3F // MCU Peripherals: 85 vectors = 340 bytes from 0x40 to ... // Total: 101 vectors = 404 bytes (0x194) to be reserved in RAM #define NVIC_NUM_VECTORS 101 #define NVIC_USER_IRQ_OFFSET 16 #include "cmsis.h" #ifdef __cplusplus extern "C" { #endif void NVIC_SetVector(IRQn_Type IRQn, uint32_t vector); uint32_t NVIC_GetVector(IRQn_Type IRQn); #ifdef __cplusplus } #endif #endif ================================================ FILE: Zelig/mbed/TARGET_NUCLEO_F401RE/core_ca9.h ================================================ /**************************************************************************//** * @file core_ca9.h * @brief CMSIS Cortex-A9 Core Peripheral Access Layer Header File * @version * @date 25 March 2013 * * @note * ******************************************************************************/ /* Copyright (c) 2009 - 2012 ARM LIMITED All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: - Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. - Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. - Neither the name of ARM 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 COPYRIGHT HOLDERS AND 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. ---------------------------------------------------------------------------*/ #if defined ( __ICCARM__ ) #pragma system_include /* treat file as system include file for MISRA check */ #endif #ifdef __cplusplus extern "C" { #endif #ifndef __CORE_CA9_H_GENERIC #define __CORE_CA9_H_GENERIC /** \page CMSIS_MISRA_Exceptions MISRA-C:2004 Compliance Exceptions CMSIS violates the following MISRA-C:2004 rules: \li Required Rule 8.5, object/function definition in header file.
Function definitions in header files are used to allow 'inlining'. \li Required Rule 18.4, declaration of union type or object of union type: '{...}'.
Unions are used for effective representation of core registers. \li Advisory Rule 19.7, Function-like macro defined.
Function-like macros are used to allow more efficient code. */ /******************************************************************************* * CMSIS definitions ******************************************************************************/ /** \ingroup Cortex_A9 @{ */ /* CMSIS CA9 definitions */ #define __CA9_CMSIS_VERSION_MAIN (0x03) /*!< [31:16] CMSIS HAL main version */ #define __CA9_CMSIS_VERSION_SUB (0x10) /*!< [15:0] CMSIS HAL sub version */ #define __CA9_CMSIS_VERSION ((__CA9_CMSIS_VERSION_MAIN << 16) | \ __CA9_CMSIS_VERSION_SUB ) /*!< CMSIS HAL version number */ #define __CORTEX_A (0x09) /*!< Cortex-A Core */ #if defined ( __CC_ARM ) #define __ASM __asm /*!< asm keyword for ARM Compiler */ #define __INLINE __inline /*!< inline keyword for ARM Compiler */ #define __STATIC_INLINE static __inline #define __STATIC_ASM static __asm #elif defined ( __ICCARM__ ) #define __ASM __asm /*!< asm keyword for IAR Compiler */ #define __INLINE inline /*!< inline keyword for IAR Compiler. Only available in High optimization mode! */ #define __STATIC_INLINE static inline #define __STATIC_ASM static __asm #elif defined ( __TMS470__ ) #define __ASM __asm /*!< asm keyword for TI CCS Compiler */ #define __STATIC_INLINE static inline #define __STATIC_ASM static __asm #elif defined ( __GNUC__ ) #define __ASM __asm /*!< asm keyword for GNU Compiler */ #define __INLINE inline /*!< inline keyword for GNU Compiler */ #define __STATIC_INLINE static inline #define __STATIC_ASM static __asm #elif defined ( __TASKING__ ) #define __ASM __asm /*!< asm keyword for TASKING Compiler */ #define __INLINE inline /*!< inline keyword for TASKING Compiler */ #define __STATIC_INLINE static inline #define __STATIC_ASM static __asm #endif /** __FPU_USED indicates whether an FPU is used or not. For this, __FPU_PRESENT has to be checked prior to making use of FPU specific registers and functions. */ #if defined ( __CC_ARM ) #if defined __TARGET_FPU_VFP #if (__FPU_PRESENT == 1) #define __FPU_USED 1 #else #warning "Compiler generates FPU instructions for a device without an FPU (check __FPU_PRESENT)" #define __FPU_USED 0 #endif #else #define __FPU_USED 0 #endif #elif defined ( __ICCARM__ ) #if defined __ARMVFP__ #if (__FPU_PRESENT == 1) #define __FPU_USED 1 #else #warning "Compiler generates FPU instructions for a device without an FPU (check __FPU_PRESENT)" #define __FPU_USED 0 #endif #else #define __FPU_USED 0 #endif #elif defined ( __TMS470__ ) #if defined __TI_VFP_SUPPORT__ #if (__FPU_PRESENT == 1) #define __FPU_USED 1 #else #warning "Compiler generates FPU instructions for a device without an FPU (check __FPU_PRESENT)" #define __FPU_USED 0 #endif #else #define __FPU_USED 0 #endif #elif defined ( __GNUC__ ) #if defined (__VFP_FP__) && !defined(__SOFTFP__) #if (__FPU_PRESENT == 1) #define __FPU_USED 1 #else #warning "Compiler generates FPU instructions for a device without an FPU (check __FPU_PRESENT)" #define __FPU_USED 0 #endif #else #define __FPU_USED 0 #endif #elif defined ( __TASKING__ ) #if defined __FPU_VFP__ #if (__FPU_PRESENT == 1) #define __FPU_USED 1 #else #error "Compiler generates FPU instructions for a device without an FPU (check __FPU_PRESENT)" #define __FPU_USED 0 #endif #else #define __FPU_USED 0 #endif #endif #include /*!< standard types definitions */ #include "core_caInstr.h" /*!< Core Instruction Access */ #include "core_caFunc.h" /*!< Core Function Access */ #include "core_cm4_simd.h" /*!< Compiler specific SIMD Intrinsics */ #endif /* __CORE_CA9_H_GENERIC */ #ifndef __CMSIS_GENERIC #ifndef __CORE_CA9_H_DEPENDANT #define __CORE_CA9_H_DEPENDANT /* check device defines and use defaults */ #if defined __CHECK_DEVICE_DEFINES #ifndef __CA9_REV #define __CA9_REV 0x0000 #warning "__CA9_REV not defined in device header file; using default!" #endif #ifndef __FPU_PRESENT #define __FPU_PRESENT 1 #warning "__FPU_PRESENT not defined in device header file; using default!" #endif #ifndef __Vendor_SysTickConfig #define __Vendor_SysTickConfig 1 #endif #if __Vendor_SysTickConfig == 0 #error "__Vendor_SysTickConfig set to 0, but vendor systick timer must be supplied for Cortex-A9" #endif #endif /* IO definitions (access restrictions to peripheral registers) */ /** \defgroup CMSIS_glob_defs CMSIS Global Defines IO Type Qualifiers are used \li to specify the access to peripheral variables. \li for automatic generation of peripheral register debug information. */ #ifdef __cplusplus #define __I volatile /*!< Defines 'read only' permissions */ #else #define __I volatile const /*!< Defines 'read only' permissions */ #endif #define __O volatile /*!< Defines 'write only' permissions */ #define __IO volatile /*!< Defines 'read / write' permissions */ /*@} end of group Cortex_A9 */ /******************************************************************************* * Register Abstraction ******************************************************************************/ /** \defgroup CMSIS_core_register Defines and Type Definitions \brief Type definitions and defines for Cortex-A processor based devices. */ /** \ingroup CMSIS_core_register \defgroup CMSIS_CORE Status and Control Registers \brief Core Register type definitions. @{ */ /** \brief Union type to access the Application Program Status Register (APSR). */ typedef union { struct { uint32_t _reserved0:16; /*!< bit: 0..15 Reserved */ uint32_t GE:4; /*!< bit: 16..19 Greater than or Equal flags */ uint32_t reserved1:7; /*!< bit: 20..23 Reserved */ uint32_t Q:1; /*!< bit: 27 Saturation condition flag */ uint32_t V:1; /*!< bit: 28 Overflow condition code flag */ uint32_t C:1; /*!< bit: 29 Carry condition code flag */ uint32_t Z:1; /*!< bit: 30 Zero condition code flag */ uint32_t N:1; /*!< bit: 31 Negative condition code flag */ } b; /*!< Structure used for bit access */ uint32_t w; /*!< Type used for word access */ } APSR_Type; /*@} end of group CMSIS_CORE */ /*@} end of CMSIS_Core_FPUFunctions */ #endif /* __CORE_CA9_H_GENERIC */ #endif /* __CMSIS_GENERIC */ #ifdef __cplusplus } #endif ================================================ FILE: Zelig/mbed/TARGET_NUCLEO_F401RE/core_caFunc.h ================================================ /**************************************************************************//** * @file core_caFunc.h * @brief CMSIS Cortex-A Core Function Access Header File * @version V3.10 * @date 30 Oct 2013 * * @note * ******************************************************************************/ /* Copyright (c) 2009 - 2013 ARM LIMITED All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: - Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. - Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. - Neither the name of ARM 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 COPYRIGHT HOLDERS AND 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. ---------------------------------------------------------------------------*/ #ifndef __CORE_CAFUNC_H__ #define __CORE_CAFUNC_H__ /* ########################### Core Function Access ########################### */ /** \ingroup CMSIS_Core_FunctionInterface \defgroup CMSIS_Core_RegAccFunctions CMSIS Core Register Access Functions @{ */ #if defined ( __CC_ARM ) /*------------------RealView Compiler -----------------*/ /* ARM armcc specific functions */ #if (__ARMCC_VERSION < 400677) #error "Please use ARM Compiler Toolchain V4.0.677 or later!" #endif #define MODE_USR 0x10 #define MODE_FIQ 0x11 #define MODE_IRQ 0x12 #define MODE_SVC 0x13 #define MODE_MON 0x16 #define MODE_ABT 0x17 #define MODE_HYP 0x1A #define MODE_UND 0x1B #define MODE_SYS 0x1F /** \brief Get APSR Register This function returns the content of the APSR Register. \return APSR Register value */ __STATIC_INLINE uint32_t __get_APSR(void) { register uint32_t __regAPSR __ASM("apsr"); return(__regAPSR); } /** \brief Get CPSR Register This function returns the content of the CPSR Register. \return CPSR Register value */ __STATIC_INLINE uint32_t __get_CPSR(void) { register uint32_t __regCPSR __ASM("cpsr"); return(__regCPSR); } /** \brief Set Stack Pointer This function assigns the given value to the current stack pointer. \param [in] topOfStack Stack Pointer value to set */ register uint32_t __regSP __ASM("sp"); __STATIC_INLINE void __set_SP(uint32_t topOfStack) { __regSP = topOfStack; } /** \brief Get link register This function returns the value of the link register \return Value of link register */ register uint32_t __reglr __ASM("lr"); __STATIC_INLINE uint32_t __get_LR(void) { return(__reglr); } /** \brief Set link register This function sets the value of the link register \param [in] lr LR value to set */ __STATIC_INLINE void __set_LR(uint32_t lr) { __reglr = lr; } /** \brief Set Process Stack Pointer This function assigns the given value to the USR/SYS Stack Pointer (PSP). \param [in] topOfProcStack USR/SYS Stack Pointer value to set */ __STATIC_ASM void __set_PSP(uint32_t topOfProcStack) { ARM PRESERVE8 BIC R0, R0, #7 ;ensure stack is 8-byte aligned MRS R1, CPSR CPS #MODE_SYS ;no effect in USR mode MOV SP, R0 MSR CPSR_c, R1 ;no effect in USR mode ISB BX LR } /** \brief Set User Mode This function changes the processor state to User Mode */ __STATIC_ASM void __set_CPS_USR(void) { ARM CPS #MODE_USR BX LR } /** \brief Enable FIQ This function enables FIQ interrupts by clearing the F-bit in the CPSR. Can only be executed in Privileged modes. */ #define __enable_fault_irq __enable_fiq /** \brief Disable FIQ This function disables FIQ interrupts by setting the F-bit in the CPSR. Can only be executed in Privileged modes. */ #define __disable_fault_irq __disable_fiq /** \brief Get FPSCR This function returns the current value of the Floating Point Status/Control register. \return Floating Point Status/Control register value */ __STATIC_INLINE uint32_t __get_FPSCR(void) { #if (__FPU_PRESENT == 1) && (__FPU_USED == 1) register uint32_t __regfpscr __ASM("fpscr"); return(__regfpscr); #else return(0); #endif } /** \brief Set FPSCR This function assigns the given value to the Floating Point Status/Control register. \param [in] fpscr Floating Point Status/Control value to set */ __STATIC_INLINE void __set_FPSCR(uint32_t fpscr) { #if (__FPU_PRESENT == 1) && (__FPU_USED == 1) register uint32_t __regfpscr __ASM("fpscr"); __regfpscr = (fpscr); #endif } /** \brief Get FPEXC This function returns the current value of the Floating Point Exception Control register. \return Floating Point Exception Control register value */ __STATIC_INLINE uint32_t __get_FPEXC(void) { #if (__FPU_PRESENT == 1) register uint32_t __regfpexc __ASM("fpexc"); return(__regfpexc); #else return(0); #endif } /** \brief Set FPEXC This function assigns the given value to the Floating Point Exception Control register. \param [in] fpscr Floating Point Exception Control value to set */ __STATIC_INLINE void __set_FPEXC(uint32_t fpexc) { #if (__FPU_PRESENT == 1) register uint32_t __regfpexc __ASM("fpexc"); __regfpexc = (fpexc); #endif } /** \brief Get CPACR This function returns the current value of the Coprocessor Access Control register. \return Coprocessor Access Control register value */ __STATIC_INLINE uint32_t __get_CPACR(void) { register uint32_t __regCPACR __ASM("cp15:0:c1:c0:2"); return __regCPACR; } /** \brief Set CPACR This function assigns the given value to the Coprocessor Access Control register. \param [in] cpacr Coprocessor Acccess Control value to set */ __STATIC_INLINE void __set_CPACR(uint32_t cpacr) { register uint32_t __regCPACR __ASM("cp15:0:c1:c0:2"); __regCPACR = cpacr; __ISB(); } /** \brief Get CBAR This function returns the value of the Configuration Base Address register. \return Configuration Base Address register value */ __STATIC_INLINE uint32_t __get_CBAR() { register uint32_t __regCBAR __ASM("cp15:4:c15:c0:0"); return(__regCBAR); } /** \brief Get TTBR0 This function returns the value of the Translation Table Base Register 0. \return Translation Table Base Register 0 value */ __STATIC_INLINE uint32_t __get_TTBR0() { register uint32_t __regTTBR0 __ASM("cp15:0:c2:c0:0"); return(__regTTBR0); } /** \brief Set TTBR0 This function assigns the given value to the Translation Table Base Register 0. \param [in] ttbr0 Translation Table Base Register 0 value to set */ __STATIC_INLINE void __set_TTBR0(uint32_t ttbr0) { register uint32_t __regTTBR0 __ASM("cp15:0:c2:c0:0"); __regTTBR0 = ttbr0; __ISB(); } /** \brief Get DACR This function returns the value of the Domain Access Control Register. \return Domain Access Control Register value */ __STATIC_INLINE uint32_t __get_DACR() { register uint32_t __regDACR __ASM("cp15:0:c3:c0:0"); return(__regDACR); } /** \brief Set DACR This function assigns the given value to the Domain Access Control Register. \param [in] dacr Domain Access Control Register value to set */ __STATIC_INLINE void __set_DACR(uint32_t dacr) { register uint32_t __regDACR __ASM("cp15:0:c3:c0:0"); __regDACR = dacr; __ISB(); } /******************************** Cache and BTAC enable ****************************************************/ /** \brief Set SCTLR This function assigns the given value to the System Control Register. \param [in] sctlr System Control Register value to set */ __STATIC_INLINE void __set_SCTLR(uint32_t sctlr) { register uint32_t __regSCTLR __ASM("cp15:0:c1:c0:0"); __regSCTLR = sctlr; } /** \brief Get SCTLR This function returns the value of the System Control Register. \return System Control Register value */ __STATIC_INLINE uint32_t __get_SCTLR() { register uint32_t __regSCTLR __ASM("cp15:0:c1:c0:0"); return(__regSCTLR); } /** \brief Enable Caches Enable Caches */ __STATIC_INLINE void __enable_caches(void) { // Set I bit 12 to enable I Cache // Set C bit 2 to enable D Cache __set_SCTLR( __get_SCTLR() | (1 << 12) | (1 << 2)); } /** \brief Disable Caches Disable Caches */ __STATIC_INLINE void __disable_caches(void) { // Clear I bit 12 to disable I Cache // Clear C bit 2 to disable D Cache __set_SCTLR( __get_SCTLR() & ~(1 << 12) & ~(1 << 2)); __ISB(); } /** \brief Enable BTAC Enable BTAC */ __STATIC_INLINE void __enable_btac(void) { // Set Z bit 11 to enable branch prediction __set_SCTLR( __get_SCTLR() | (1 << 11)); __ISB(); } /** \brief Disable BTAC Disable BTAC */ __STATIC_INLINE void __disable_btac(void) { // Clear Z bit 11 to disable branch prediction __set_SCTLR( __get_SCTLR() & ~(1 << 11)); } /** \brief Enable MMU Enable MMU */ __STATIC_INLINE void __enable_mmu(void) { // Set M bit 0 to enable the MMU // Set AFE bit to enable simplified access permissions model // Clear TRE bit to disable TEX remap and A bit to disable strict alignment fault checking __set_SCTLR( (__get_SCTLR() & ~(1 << 28) & ~(1 << 1)) | 1 | (1 << 29)); __ISB(); } /** \brief Disable MMU Disable MMU */ __STATIC_INLINE void __disable_mmu(void) { // Clear M bit 0 to disable the MMU __set_SCTLR( __get_SCTLR() & ~1); __ISB(); } /******************************** TLB maintenance operations ************************************************/ /** \brief Invalidate the whole tlb TLBIALL. Invalidate the whole tlb */ __STATIC_INLINE void __ca9u_inv_tlb_all(void) { register uint32_t __TLBIALL __ASM("cp15:0:c8:c7:0"); __TLBIALL = 0; __DSB(); __ISB(); } /******************************** BTB maintenance operations ************************************************/ /** \brief Invalidate entire branch predictor array BPIALL. Branch Predictor Invalidate All. */ __STATIC_INLINE void __v7_inv_btac(void) { register uint32_t __BPIALL __ASM("cp15:0:c7:c5:6"); __BPIALL = 0; __DSB(); //ensure completion of the invalidation __ISB(); //ensure instruction fetch path sees new state } /******************************** L1 cache operations ******************************************************/ /** \brief Invalidate the whole I$ ICIALLU. Instruction Cache Invalidate All to PoU */ __STATIC_INLINE void __v7_inv_icache_all(void) { register uint32_t __ICIALLU __ASM("cp15:0:c7:c5:0"); __ICIALLU = 0; __DSB(); //ensure completion of the invalidation __ISB(); //ensure instruction fetch path sees new I cache state } /** \brief Clean D$ by MVA DCCMVAC. Data cache clean by MVA to PoC */ __STATIC_INLINE void __v7_clean_dcache_mva(void *va) { register uint32_t __DCCMVAC __ASM("cp15:0:c7:c10:1"); __DCCMVAC = (uint32_t)va; __DMB(); //ensure the ordering of data cache maintenance operations and their effects } /** \brief Invalidate D$ by MVA DCIMVAC. Data cache invalidate by MVA to PoC */ __STATIC_INLINE void __v7_inv_dcache_mva(void *va) { register uint32_t __DCIMVAC __ASM("cp15:0:c7:c6:1"); __DCIMVAC = (uint32_t)va; __DMB(); //ensure the ordering of data cache maintenance operations and their effects } /** \brief Clean and Invalidate D$ by MVA DCCIMVAC. Data cache clean and invalidate by MVA to PoC */ __STATIC_INLINE void __v7_clean_inv_dcache_mva(void *va) { register uint32_t __DCCIMVAC __ASM("cp15:0:c7:c14:1"); __DCCIMVAC = (uint32_t)va; __DMB(); //ensure the ordering of data cache maintenance operations and their effects } /** \brief Clean and Invalidate the entire data or unified cache Generic mechanism for cleaning/invalidating the entire data or unified cache to the point of coherency. */ #pragma push #pragma arm __STATIC_ASM void __v7_all_cache(uint32_t op) { ARM PUSH {R4-R11} MRC p15, 1, R6, c0, c0, 1 // Read CLIDR ANDS R3, R6, #0x07000000 // Extract coherency level MOV R3, R3, LSR #23 // Total cache levels << 1 BEQ Finished // If 0, no need to clean MOV R10, #0 // R10 holds current cache level << 1 Loop1 ADD R2, R10, R10, LSR #1 // R2 holds cache "Set" position MOV R1, R6, LSR R2 // Bottom 3 bits are the Cache-type for this level AND R1, R1, #7 // Isolate those lower 3 bits CMP R1, #2 BLT Skip // No cache or only instruction cache at this level MCR p15, 2, R10, c0, c0, 0 // Write the Cache Size selection register ISB // ISB to sync the change to the CacheSizeID reg MRC p15, 1, R1, c0, c0, 0 // Reads current Cache Size ID register AND R2, R1, #7 // Extract the line length field ADD R2, R2, #4 // Add 4 for the line length offset (log2 16 bytes) LDR R4, =0x3FF ANDS R4, R4, R1, LSR #3 // R4 is the max number on the way size (right aligned) CLZ R5, R4 // R5 is the bit position of the way size increment LDR R7, =0x7FFF ANDS R7, R7, R1, LSR #13 // R7 is the max number of the index size (right aligned) Loop2 MOV R9, R4 // R9 working copy of the max way size (right aligned) Loop3 ORR R11, R10, R9, LSL R5 // Factor in the Way number and cache number into R11 ORR R11, R11, R7, LSL R2 // Factor in the Set number CMP R0, #0 BNE Dccsw MCR p15, 0, R11, c7, c6, 2 // DCISW. Invalidate by Set/Way B cont Dccsw CMP R0, #1 BNE Dccisw MCR p15, 0, R11, c7, c10, 2 // DCCSW. Clean by Set/Way B cont Dccisw MCR p15, 0, R11, c7, c14, 2 // DCCISW. Clean and Invalidate by Set/Way cont SUBS R9, R9, #1 // Decrement the Way number BGE Loop3 SUBS R7, R7, #1 // Decrement the Set number BGE Loop2 Skip ADD R10, R10, #2 // Increment the cache number CMP R3, R10 BGT Loop1 Finished DSB POP {R4-R11} BX lr } #pragma pop /** \brief Invalidate the whole D$ DCISW. Invalidate by Set/Way */ __STATIC_INLINE void __v7_inv_dcache_all(void) { __v7_all_cache(0); } /** \brief Clean the whole D$ DCCSW. Clean by Set/Way */ __STATIC_INLINE void __v7_clean_dcache_all(void) { __v7_all_cache(1); } /** \brief Clean and invalidate the whole D$ DCCISW. Clean and Invalidate by Set/Way */ __STATIC_INLINE void __v7_clean_inv_dcache_all(void) { __v7_all_cache(2); } #include "core_ca_mmu.h" #elif (defined (__ICCARM__)) /*---------------- ICC Compiler ---------------------*/ #error IAR Compiler support not implemented for Cortex-A #elif (defined (__GNUC__)) /*------------------ GNU Compiler ---------------------*/ /* GNU gcc specific functions */ #define MODE_USR 0x10 #define MODE_FIQ 0x11 #define MODE_IRQ 0x12 #define MODE_SVC 0x13 #define MODE_MON 0x16 #define MODE_ABT 0x17 #define MODE_HYP 0x1A #define MODE_UND 0x1B #define MODE_SYS 0x1F __attribute__( ( always_inline ) ) __STATIC_INLINE void __enable_irq(void) { __ASM volatile ("cpsie i"); } /** \brief Disable IRQ Interrupts This function disables IRQ interrupts by setting the I-bit in the CPSR. Can only be executed in Privileged modes. */ __attribute__( ( always_inline ) ) __STATIC_INLINE uint32_t __disable_irq(void) { uint32_t result; __ASM volatile ("mrs %0, cpsr" : "=r" (result)); __ASM volatile ("cpsid i"); return(result & 0x80); } /** \brief Get APSR Register This function returns the content of the APSR Register. \return APSR Register value */ __attribute__( ( always_inline ) ) __STATIC_INLINE uint32_t __get_APSR(void) { #if 1 register uint32_t __regAPSR; __ASM volatile ("mrs %0, apsr" : "=r" (__regAPSR) ); #else register uint32_t __regAPSR __ASM("apsr"); #endif return(__regAPSR); } /** \brief Get CPSR Register This function returns the content of the CPSR Register. \return CPSR Register value */ __attribute__( ( always_inline ) ) __STATIC_INLINE uint32_t __get_CPSR(void) { #if 1 register uint32_t __regCPSR; __ASM volatile ("mrs %0, cpsr" : "=r" (__regCPSR)); #else register uint32_t __regCPSR __ASM("cpsr"); #endif return(__regCPSR); } #if 0 /** \brief Set Stack Pointer This function assigns the given value to the current stack pointer. \param [in] topOfStack Stack Pointer value to set */ __attribute__( ( always_inline ) ) __STATIC_INLINE void __set_SP(uint32_t topOfStack) { register uint32_t __regSP __ASM("sp"); __regSP = topOfStack; } #endif /** \brief Get link register This function returns the value of the link register \return Value of link register */ __attribute__( ( always_inline ) ) __STATIC_INLINE uint32_t __get_LR(void) { register uint32_t __reglr __ASM("lr"); return(__reglr); } #if 0 /** \brief Set link register This function sets the value of the link register \param [in] lr LR value to set */ __attribute__( ( always_inline ) ) __STATIC_INLINE void __set_LR(uint32_t lr) { register uint32_t __reglr __ASM("lr"); __reglr = lr; } #endif /** \brief Set Process Stack Pointer This function assigns the given value to the USR/SYS Stack Pointer (PSP). \param [in] topOfProcStack USR/SYS Stack Pointer value to set */ __attribute__( ( always_inline ) ) __STATIC_INLINE void __set_PSP(uint32_t topOfProcStack) { __asm__ volatile ( ".ARM;" ".eabi_attribute Tag_ABI_align8_preserved,1;" "BIC R0, R0, #7;" /* ;ensure stack is 8-byte aligned */ "MRS R1, CPSR;" "CPS %0;" /* ;no effect in USR mode */ "MOV SP, R0;" "MSR CPSR_c, R1;" /* ;no effect in USR mode */ "ISB;" //"BX LR;" : : "i"(MODE_SYS) : "r0", "r1"); return; } /** \brief Set User Mode This function changes the processor state to User Mode */ __attribute__( ( always_inline ) ) __STATIC_INLINE void __set_CPS_USR(void) { __asm__ volatile ( ".ARM;" "CPS %0;" //"BX LR;" : : "i"(MODE_USR) : ); return; } /** \brief Enable FIQ This function enables FIQ interrupts by clearing the F-bit in the CPSR. Can only be executed in Privileged modes. */ #define __enable_fault_irq() __asm__ volatile ("cpsie f") /** \brief Disable FIQ This function disables FIQ interrupts by setting the F-bit in the CPSR. Can only be executed in Privileged modes. */ #define __disable_fault_irq() __asm__ volatile ("cpsid f") /** \brief Get FPSCR This function returns the current value of the Floating Point Status/Control register. \return Floating Point Status/Control register value */ __attribute__( ( always_inline ) ) __STATIC_INLINE uint32_t __get_FPSCR(void) { #if (__FPU_PRESENT == 1) && (__FPU_USED == 1) #if 1 uint32_t result; __ASM volatile ("vmrs %0, fpscr" : "=r" (result) ); return (result); #else register uint32_t __regfpscr __ASM("fpscr"); return(__regfpscr); #endif #else return(0); #endif } /** \brief Set FPSCR This function assigns the given value to the Floating Point Status/Control register. \param [in] fpscr Floating Point Status/Control value to set */ __attribute__( ( always_inline ) ) __STATIC_INLINE void __set_FPSCR(uint32_t fpscr) { #if (__FPU_PRESENT == 1) && (__FPU_USED == 1) #if 1 __ASM volatile ("vmsr fpscr, %0" : : "r" (fpscr) ); #else register uint32_t __regfpscr __ASM("fpscr"); __regfpscr = (fpscr); #endif #endif } /** \brief Get FPEXC This function returns the current value of the Floating Point Exception Control register. \return Floating Point Exception Control register value */ __attribute__( ( always_inline ) ) __STATIC_INLINE uint32_t __get_FPEXC(void) { #if (__FPU_PRESENT == 1) #if 1 uint32_t result; __ASM volatile ("vmrs %0, fpexc" : "=r" (result)); return (result); #else register uint32_t __regfpexc __ASM("fpexc"); return(__regfpexc); #endif #else return(0); #endif } /** \brief Set FPEXC This function assigns the given value to the Floating Point Exception Control register. \param [in] fpscr Floating Point Exception Control value to set */ __attribute__( ( always_inline ) ) __STATIC_INLINE void __set_FPEXC(uint32_t fpexc) { #if (__FPU_PRESENT == 1) #if 1 __ASM volatile ("vmsr fpexc, %0" : : "r" (fpexc)); #else register uint32_t __regfpexc __ASM("fpexc"); __regfpexc = (fpexc); #endif #endif } /** \brief Get CPACR This function returns the current value of the Coprocessor Access Control register. \return Coprocessor Access Control register value */ __attribute__( ( always_inline ) ) __STATIC_INLINE uint32_t __get_CPACR(void) { #if 1 register uint32_t __regCPACR; __ASM volatile ("mrc p15, 0, %0, c1, c0, 2" : "=r" (__regCPACR)); #else register uint32_t __regCPACR __ASM("cp15:0:c1:c0:2"); #endif return __regCPACR; } /** \brief Set CPACR This function assigns the given value to the Coprocessor Access Control register. \param [in] cpacr Coprocessor Acccess Control value to set */ __attribute__( ( always_inline ) ) __STATIC_INLINE void __set_CPACR(uint32_t cpacr) { #if 1 __ASM volatile ("mcr p15, 0, %0, c1, c0, 2" : : "r" (cpacr)); #else register uint32_t __regCPACR __ASM("cp15:0:c1:c0:2"); __regCPACR = cpacr; #endif __ISB(); } /** \brief Get CBAR This function returns the value of the Configuration Base Address register. \return Configuration Base Address register value */ __attribute__( ( always_inline ) ) __STATIC_INLINE uint32_t __get_CBAR() { #if 1 register uint32_t __regCBAR; __ASM volatile ("mrc p15, 4, %0, c15, c0, 0" : "=r" (__regCBAR)); #else register uint32_t __regCBAR __ASM("cp15:4:c15:c0:0"); #endif return(__regCBAR); } /** \brief Get TTBR0 This function returns the value of the Translation Table Base Register 0. \return Translation Table Base Register 0 value */ __attribute__( ( always_inline ) ) __STATIC_INLINE uint32_t __get_TTBR0() { #if 1 register uint32_t __regTTBR0; __ASM volatile ("mrc p15, 0, %0, c2, c0, 0" : "=r" (__regTTBR0)); #else register uint32_t __regTTBR0 __ASM("cp15:0:c2:c0:0"); #endif return(__regTTBR0); } /** \brief Set TTBR0 This function assigns the given value to the Translation Table Base Register 0. \param [in] ttbr0 Translation Table Base Register 0 value to set */ __attribute__( ( always_inline ) ) __STATIC_INLINE void __set_TTBR0(uint32_t ttbr0) { #if 1 __ASM volatile ("mcr p15, 0, %0, c2, c0, 0" : : "r" (ttbr0)); #else register uint32_t __regTTBR0 __ASM("cp15:0:c2:c0:0"); __regTTBR0 = ttbr0; #endif __ISB(); } /** \brief Get DACR This function returns the value of the Domain Access Control Register. \return Domain Access Control Register value */ __attribute__( ( always_inline ) ) __STATIC_INLINE uint32_t __get_DACR() { #if 1 register uint32_t __regDACR; __ASM volatile ("mrc p15, 0, %0, c3, c0, 0" : "=r" (__regDACR)); #else register uint32_t __regDACR __ASM("cp15:0:c3:c0:0"); #endif return(__regDACR); } /** \brief Set DACR This function assigns the given value to the Domain Access Control Register. \param [in] dacr Domain Access Control Register value to set */ __attribute__( ( always_inline ) ) __STATIC_INLINE void __set_DACR(uint32_t dacr) { #if 1 __ASM volatile ("mcr p15, 0, %0, c3, c0, 0" : : "r" (dacr)); #else register uint32_t __regDACR __ASM("cp15:0:c3:c0:0"); __regDACR = dacr; #endif __ISB(); } /******************************** Cache and BTAC enable ****************************************************/ /** \brief Set SCTLR This function assigns the given value to the System Control Register. \param [in] sctlr System Control Register value to set */ __attribute__( ( always_inline ) ) __STATIC_INLINE void __set_SCTLR(uint32_t sctlr) { #if 1 __ASM volatile ("mcr p15, 0, %0, c1, c0, 0" : : "r" (sctlr)); #else register uint32_t __regSCTLR __ASM("cp15:0:c1:c0:0"); __regSCTLR = sctlr; #endif } /** \brief Get SCTLR This function returns the value of the System Control Register. \return System Control Register value */ __attribute__( ( always_inline ) ) __STATIC_INLINE uint32_t __get_SCTLR() { #if 1 register uint32_t __regSCTLR; __ASM volatile ("mrc p15, 0, %0, c1, c0, 0" : "=r" (__regSCTLR)); #else register uint32_t __regSCTLR __ASM("cp15:0:c1:c0:0"); #endif return(__regSCTLR); } /** \brief Enable Caches Enable Caches */ __attribute__( ( always_inline ) ) __STATIC_INLINE void __enable_caches(void) { // Set I bit 12 to enable I Cache // Set C bit 2 to enable D Cache __set_SCTLR( __get_SCTLR() | (1 << 12) | (1 << 2)); } /** \brief Disable Caches Disable Caches */ __attribute__( ( always_inline ) ) __STATIC_INLINE void __disable_caches(void) { // Clear I bit 12 to disable I Cache // Clear C bit 2 to disable D Cache __set_SCTLR( __get_SCTLR() & ~(1 << 12) & ~(1 << 2)); __ISB(); } /** \brief Enable BTAC Enable BTAC */ __attribute__( ( always_inline ) ) __STATIC_INLINE void __enable_btac(void) { // Set Z bit 11 to enable branch prediction __set_SCTLR( __get_SCTLR() | (1 << 11)); __ISB(); } /** \brief Disable BTAC Disable BTAC */ __attribute__( ( always_inline ) ) __STATIC_INLINE void __disable_btac(void) { // Clear Z bit 11 to disable branch prediction __set_SCTLR( __get_SCTLR() & ~(1 << 11)); } /** \brief Enable MMU Enable MMU */ __attribute__( ( always_inline ) ) __STATIC_INLINE void __enable_mmu(void) { // Set M bit 0 to enable the MMU // Set AFE bit to enable simplified access permissions model // Clear TRE bit to disable TEX remap and A bit to disable strict alignment fault checking __set_SCTLR( (__get_SCTLR() & ~(1 << 28) & ~(1 << 1)) | 1 | (1 << 29)); __ISB(); } /** \brief Disable MMU Disable MMU */ __attribute__( ( always_inline ) ) __STATIC_INLINE void __disable_mmu(void) { // Clear M bit 0 to disable the MMU __set_SCTLR( __get_SCTLR() & ~1); __ISB(); } /******************************** TLB maintenance operations ************************************************/ /** \brief Invalidate the whole tlb TLBIALL. Invalidate the whole tlb */ __attribute__( ( always_inline ) ) __STATIC_INLINE void __ca9u_inv_tlb_all(void) { #if 1 __ASM volatile ("mcr p15, 0, %0, c8, c7, 0" : : "r" (0)); #else register uint32_t __TLBIALL __ASM("cp15:0:c8:c7:0"); __TLBIALL = 0; #endif __DSB(); __ISB(); } /******************************** BTB maintenance operations ************************************************/ /** \brief Invalidate entire branch predictor array BPIALL. Branch Predictor Invalidate All. */ __attribute__( ( always_inline ) ) __STATIC_INLINE void __v7_inv_btac(void) { #if 1 __ASM volatile ("mcr p15, 0, %0, c7, c5, 6" : : "r" (0)); #else register uint32_t __BPIALL __ASM("cp15:0:c7:c5:6"); __BPIALL = 0; #endif __DSB(); //ensure completion of the invalidation __ISB(); //ensure instruction fetch path sees new state } /******************************** L1 cache operations ******************************************************/ /** \brief Invalidate the whole I$ ICIALLU. Instruction Cache Invalidate All to PoU */ __attribute__( ( always_inline ) ) __STATIC_INLINE void __v7_inv_icache_all(void) { #if 1 __ASM volatile ("mcr p15, 0, %0, c7, c5, 0" : : "r" (0)); #else register uint32_t __ICIALLU __ASM("cp15:0:c7:c5:0"); __ICIALLU = 0; #endif __DSB(); //ensure completion of the invalidation __ISB(); //ensure instruction fetch path sees new I cache state } /** \brief Clean D$ by MVA DCCMVAC. Data cache clean by MVA to PoC */ __attribute__( ( always_inline ) ) __STATIC_INLINE void __v7_clean_dcache_mva(void *va) { #if 1 __ASM volatile ("mcr p15, 0, %0, c7, c10, 1" : : "r" ((uint32_t)va)); #else register uint32_t __DCCMVAC __ASM("cp15:0:c7:c10:1"); __DCCMVAC = (uint32_t)va; #endif __DMB(); //ensure the ordering of data cache maintenance operations and their effects } /** \brief Invalidate D$ by MVA DCIMVAC. Data cache invalidate by MVA to PoC */ __attribute__( ( always_inline ) ) __STATIC_INLINE void __v7_inv_dcache_mva(void *va) { #if 1 __ASM volatile ("mcr p15, 0, %0, c7, c6, 1" : : "r" ((uint32_t)va)); #else register uint32_t __DCIMVAC __ASM("cp15:0:c7:c6:1"); __DCIMVAC = (uint32_t)va; #endif __DMB(); //ensure the ordering of data cache maintenance operations and their effects } /** \brief Clean and Invalidate D$ by MVA DCCIMVAC. Data cache clean and invalidate by MVA to PoC */ __attribute__( ( always_inline ) ) __STATIC_INLINE void __v7_clean_inv_dcache_mva(void *va) { #if 1 __ASM volatile ("mcr p15, 0, %0, c7, c14, 1" : : "r" ((uint32_t)va)); #else register uint32_t __DCCIMVAC __ASM("cp15:0:c7:c14:1"); __DCCIMVAC = (uint32_t)va; #endif __DMB(); //ensure the ordering of data cache maintenance operations and their effects } /** \brief Clean and Invalidate the entire data or unified cache Generic mechanism for cleaning/invalidating the entire data or unified cache to the point of coherency. */ extern void __v7_all_cache(uint32_t op); /** \brief Invalidate the whole D$ DCISW. Invalidate by Set/Way */ __attribute__( ( always_inline ) ) __STATIC_INLINE void __v7_inv_dcache_all(void) { __v7_all_cache(0); } /** \brief Clean the whole D$ DCCSW. Clean by Set/Way */ __attribute__( ( always_inline ) ) __STATIC_INLINE void __v7_clean_dcache_all(void) { __v7_all_cache(1); } /** \brief Clean and invalidate the whole D$ DCCISW. Clean and Invalidate by Set/Way */ __attribute__( ( always_inline ) ) __STATIC_INLINE void __v7_clean_inv_dcache_all(void) { __v7_all_cache(2); } #include "core_ca_mmu.h" #elif (defined (__TASKING__)) /*--------------- TASKING Compiler -----------------*/ #error TASKING Compiler support not implemented for Cortex-A #endif /*@} end of CMSIS_Core_RegAccFunctions */ #endif /* __CORE_CAFUNC_H__ */ ================================================ FILE: Zelig/mbed/TARGET_NUCLEO_F401RE/core_caInstr.h ================================================ /**************************************************************************//** * @file core_caInstr.h * @brief CMSIS Cortex-A9 Core Peripheral Access Layer Header File * @version * @date 04. December 2012 * * @note * ******************************************************************************/ /* Copyright (c) 2009 - 2012 ARM LIMITED All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: - Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. - Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. - Neither the name of ARM 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 COPYRIGHT HOLDERS AND 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. ---------------------------------------------------------------------------*/ #ifndef __CORE_CAINSTR_H__ #define __CORE_CAINSTR_H__ #define __CORTEX_M 0x3 #include "core_cmInstr.h" #undef __CORTEX_M #endif ================================================ FILE: Zelig/mbed/TARGET_NUCLEO_F401RE/core_ca_mmu.h ================================================ ;/**************************************************************************//** ; * @file core_ca_mmu.h ; * @brief MMU Startup File for A9_MP Device Series ; * @version V1.01 ; * @date 10 Sept 2014 ; * ; * @note ; * ; ******************************************************************************/ ;/* Copyright (c) 2012-2014 ARM LIMITED ; ; All rights reserved. ; Redistribution and use in source and binary forms, with or without ; modification, are permitted provided that the following conditions are met: ; - Redistributions of source code must retain the above copyright ; notice, this list of conditions and the following disclaimer. ; - Redistributions in binary form must reproduce the above copyright ; notice, this list of conditions and the following disclaimer in the ; documentation and/or other materials provided with the distribution. ; - Neither the name of ARM 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 COPYRIGHT HOLDERS AND CONTRIBUTORS BE ; LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR ; CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF ; SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS ; INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN ; CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ; ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE ; POSSIBILITY OF SUCH DAMAGE. ; ---------------------------------------------------------------------------*/ #ifdef __cplusplus extern "C" { #endif #ifndef _MMU_FUNC_H #define _MMU_FUNC_H #define SECTION_DESCRIPTOR (0x2) #define SECTION_MASK (0xFFFFFFFC) #define SECTION_TEXCB_MASK (0xFFFF8FF3) #define SECTION_B_SHIFT (2) #define SECTION_C_SHIFT (3) #define SECTION_TEX0_SHIFT (12) #define SECTION_TEX1_SHIFT (13) #define SECTION_TEX2_SHIFT (14) #define SECTION_XN_MASK (0xFFFFFFEF) #define SECTION_XN_SHIFT (4) #define SECTION_DOMAIN_MASK (0xFFFFFE1F) #define SECTION_DOMAIN_SHIFT (5) #define SECTION_P_MASK (0xFFFFFDFF) #define SECTION_P_SHIFT (9) #define SECTION_AP_MASK (0xFFFF73FF) #define SECTION_AP_SHIFT (10) #define SECTION_AP2_SHIFT (15) #define SECTION_S_MASK (0xFFFEFFFF) #define SECTION_S_SHIFT (16) #define SECTION_NG_MASK (0xFFFDFFFF) #define SECTION_NG_SHIFT (17) #define SECTION_NS_MASK (0xFFF7FFFF) #define SECTION_NS_SHIFT (19) #define PAGE_L1_DESCRIPTOR (0x1) #define PAGE_L1_MASK (0xFFFFFFFC) #define PAGE_L2_4K_DESC (0x2) #define PAGE_L2_4K_MASK (0xFFFFFFFD) #define PAGE_L2_64K_DESC (0x1) #define PAGE_L2_64K_MASK (0xFFFFFFFC) #define PAGE_4K_TEXCB_MASK (0xFFFFFE33) #define PAGE_4K_B_SHIFT (2) #define PAGE_4K_C_SHIFT (3) #define PAGE_4K_TEX0_SHIFT (6) #define PAGE_4K_TEX1_SHIFT (7) #define PAGE_4K_TEX2_SHIFT (8) #define PAGE_64K_TEXCB_MASK (0xFFFF8FF3) #define PAGE_64K_B_SHIFT (2) #define PAGE_64K_C_SHIFT (3) #define PAGE_64K_TEX0_SHIFT (12) #define PAGE_64K_TEX1_SHIFT (13) #define PAGE_64K_TEX2_SHIFT (14) #define PAGE_TEXCB_MASK (0xFFFF8FF3) #define PAGE_B_SHIFT (2) #define PAGE_C_SHIFT (3) #define PAGE_TEX_SHIFT (12) #define PAGE_XN_4K_MASK (0xFFFFFFFE) #define PAGE_XN_4K_SHIFT (0) #define PAGE_XN_64K_MASK (0xFFFF7FFF) #define PAGE_XN_64K_SHIFT (15) #define PAGE_DOMAIN_MASK (0xFFFFFE1F) #define PAGE_DOMAIN_SHIFT (5) #define PAGE_P_MASK (0xFFFFFDFF) #define PAGE_P_SHIFT (9) #define PAGE_AP_MASK (0xFFFFFDCF) #define PAGE_AP_SHIFT (4) #define PAGE_AP2_SHIFT (9) #define PAGE_S_MASK (0xFFFFFBFF) #define PAGE_S_SHIFT (10) #define PAGE_NG_MASK (0xFFFFF7FF) #define PAGE_NG_SHIFT (11) #define PAGE_NS_MASK (0xFFFFFFF7) #define PAGE_NS_SHIFT (3) #define OFFSET_1M (0x00100000) #define OFFSET_64K (0x00010000) #define OFFSET_4K (0x00001000) #define DESCRIPTOR_FAULT (0x00000000) /* ########################### MMU Function Access ########################### */ /** \ingroup MMU_FunctionInterface \defgroup MMU_Functions MMU Functions Interface @{ */ /* Attributes enumerations */ /* Region size attributes */ typedef enum { SECTION, PAGE_4k, PAGE_64k, } mmu_region_size_Type; /* Region type attributes */ typedef enum { NORMAL, DEVICE, SHARED_DEVICE, NON_SHARED_DEVICE, STRONGLY_ORDERED } mmu_memory_Type; /* Region cacheability attributes */ typedef enum { NON_CACHEABLE, WB_WA, WT, WB_NO_WA, } mmu_cacheability_Type; /* Region parity check attributes */ typedef enum { ECC_DISABLED, ECC_ENABLED, } mmu_ecc_check_Type; /* Region execution attributes */ typedef enum { EXECUTE, NON_EXECUTE, } mmu_execute_Type; /* Region global attributes */ typedef enum { GLOBAL, NON_GLOBAL, } mmu_global_Type; /* Region shareability attributes */ typedef enum { NON_SHARED, SHARED, } mmu_shared_Type; /* Region security attributes */ typedef enum { SECURE, NON_SECURE, } mmu_secure_Type; /* Region access attributes */ typedef enum { NO_ACCESS, RW, READ, } mmu_access_Type; /* Memory Region definition */ typedef struct RegionStruct { mmu_region_size_Type rg_t; mmu_memory_Type mem_t; uint8_t domain; mmu_cacheability_Type inner_norm_t; mmu_cacheability_Type outer_norm_t; mmu_ecc_check_Type e_t; mmu_execute_Type xn_t; mmu_global_Type g_t; mmu_secure_Type sec_t; mmu_access_Type priv_t; mmu_access_Type user_t; mmu_shared_Type sh_t; } mmu_region_attributes_Type; /** \brief Set section execution-never attribute The function sets section execution-never attribute \param [out] descriptor_l1 L1 descriptor. \param [in] xn Section execution-never attribute : EXECUTE , NON_EXECUTE. \return 0 */ __STATIC_INLINE int __xn_section(uint32_t *descriptor_l1, mmu_execute_Type xn) { *descriptor_l1 &= SECTION_XN_MASK; *descriptor_l1 |= ((xn & 0x1) << SECTION_XN_SHIFT); return 0; } /** \brief Set section domain The function sets section domain \param [out] descriptor_l1 L1 descriptor. \param [in] domain Section domain \return 0 */ __STATIC_INLINE int __domain_section(uint32_t *descriptor_l1, uint8_t domain) { *descriptor_l1 &= SECTION_DOMAIN_MASK; *descriptor_l1 |= ((domain & 0xF) << SECTION_DOMAIN_SHIFT); return 0; } /** \brief Set section parity check The function sets section parity check \param [out] descriptor_l1 L1 descriptor. \param [in] p_bit Parity check: ECC_DISABLED, ECC_ENABLED \return 0 */ __STATIC_INLINE int __p_section(uint32_t *descriptor_l1, mmu_ecc_check_Type p_bit) { *descriptor_l1 &= SECTION_P_MASK; *descriptor_l1 |= ((p_bit & 0x1) << SECTION_P_SHIFT); return 0; } /** \brief Set section access privileges The function sets section access privileges \param [out] descriptor_l1 L1 descriptor. \param [in] user User Level Access: NO_ACCESS, RW, READ \param [in] priv Privilege Level Access: NO_ACCESS, RW, READ \param [in] afe Access flag enable \return 0 */ __STATIC_INLINE int __ap_section(uint32_t *descriptor_l1, mmu_access_Type user, mmu_access_Type priv, uint32_t afe) { uint32_t ap = 0; if (afe == 0) { //full access if ((priv == NO_ACCESS) && (user == NO_ACCESS)) { ap = 0x0; } else if ((priv == RW) && (user == NO_ACCESS)) { ap = 0x1; } else if ((priv == RW) && (user == READ)) { ap = 0x2; } else if ((priv == RW) && (user == RW)) { ap = 0x3; } else if ((priv == READ) && (user == NO_ACCESS)) { ap = 0x5; } else if ((priv == READ) && (user == READ)) { ap = 0x7; } } else { //Simplified access if ((priv == RW) && (user == NO_ACCESS)) { ap = 0x1; } else if ((priv == RW) && (user == RW)) { ap = 0x3; } else if ((priv == READ) && (user == NO_ACCESS)) { ap = 0x5; } else if ((priv == READ) && (user == READ)) { ap = 0x7; } } *descriptor_l1 &= SECTION_AP_MASK; *descriptor_l1 |= (ap & 0x3) << SECTION_AP_SHIFT; *descriptor_l1 |= ((ap & 0x4)>>2) << SECTION_AP2_SHIFT; return 0; } /** \brief Set section shareability The function sets section shareability \param [out] descriptor_l1 L1 descriptor. \param [in] s_bit Section shareability: NON_SHARED, SHARED \return 0 */ __STATIC_INLINE int __shared_section(uint32_t *descriptor_l1, mmu_shared_Type s_bit) { *descriptor_l1 &= SECTION_S_MASK; *descriptor_l1 |= ((s_bit & 0x1) << SECTION_S_SHIFT); return 0; } /** \brief Set section Global attribute The function sets section Global attribute \param [out] descriptor_l1 L1 descriptor. \param [in] g_bit Section attribute: GLOBAL, NON_GLOBAL \return 0 */ __STATIC_INLINE int __global_section(uint32_t *descriptor_l1, mmu_global_Type g_bit) { *descriptor_l1 &= SECTION_NG_MASK; *descriptor_l1 |= ((g_bit & 0x1) << SECTION_NG_SHIFT); return 0; } /** \brief Set section Security attribute The function sets section Global attribute \param [out] descriptor_l1 L1 descriptor. \param [in] s_bit Section Security attribute: SECURE, NON_SECURE \return 0 */ __STATIC_INLINE int __secure_section(uint32_t *descriptor_l1, mmu_secure_Type s_bit) { *descriptor_l1 &= SECTION_NS_MASK; *descriptor_l1 |= ((s_bit & 0x1) << SECTION_NS_SHIFT); return 0; } /* Page 4k or 64k */ /** \brief Set 4k/64k page execution-never attribute The function sets 4k/64k page execution-never attribute \param [out] descriptor_l2 L2 descriptor. \param [in] xn Page execution-never attribute : EXECUTE , NON_EXECUTE. \param [in] page Page size: PAGE_4k, PAGE_64k, \return 0 */ __STATIC_INLINE int __xn_page(uint32_t *descriptor_l2, mmu_execute_Type xn, mmu_region_size_Type page) { if (page == PAGE_4k) { *descriptor_l2 &= PAGE_XN_4K_MASK; *descriptor_l2 |= ((xn & 0x1) << PAGE_XN_4K_SHIFT); } else { *descriptor_l2 &= PAGE_XN_64K_MASK; *descriptor_l2 |= ((xn & 0x1) << PAGE_XN_64K_SHIFT); } return 0; } /** \brief Set 4k/64k page domain The function sets 4k/64k page domain \param [out] descriptor_l1 L1 descriptor. \param [in] domain Page domain \return 0 */ __STATIC_INLINE int __domain_page(uint32_t *descriptor_l1, uint8_t domain) { *descriptor_l1 &= PAGE_DOMAIN_MASK; *descriptor_l1 |= ((domain & 0xf) << PAGE_DOMAIN_SHIFT); return 0; } /** \brief Set 4k/64k page parity check The function sets 4k/64k page parity check \param [out] descriptor_l1 L1 descriptor. \param [in] p_bit Parity check: ECC_DISABLED, ECC_ENABLED \return 0 */ __STATIC_INLINE int __p_page(uint32_t *descriptor_l1, mmu_ecc_check_Type p_bit) { *descriptor_l1 &= SECTION_P_MASK; *descriptor_l1 |= ((p_bit & 0x1) << SECTION_P_SHIFT); return 0; } /** \brief Set 4k/64k page access privileges The function sets 4k/64k page access privileges \param [out] descriptor_l2 L2 descriptor. \param [in] user User Level Access: NO_ACCESS, RW, READ \param [in] priv Privilege Level Access: NO_ACCESS, RW, READ \param [in] afe Access flag enable \return 0 */ __STATIC_INLINE int __ap_page(uint32_t *descriptor_l2, mmu_access_Type user, mmu_access_Type priv, uint32_t afe) { uint32_t ap = 0; if (afe == 0) { //full access if ((priv == NO_ACCESS) && (user == NO_ACCESS)) { ap = 0x0; } else if ((priv == RW) && (user == NO_ACCESS)) { ap = 0x1; } else if ((priv == RW) && (user == READ)) { ap = 0x2; } else if ((priv == RW) && (user == RW)) { ap = 0x3; } else if ((priv == READ) && (user == NO_ACCESS)) { ap = 0x5; } else if ((priv == READ) && (user == READ)) { ap = 0x6; } } else { //Simplified access if ((priv == RW) && (user == NO_ACCESS)) { ap = 0x1; } else if ((priv == RW) && (user == RW)) { ap = 0x3; } else if ((priv == READ) && (user == NO_ACCESS)) { ap = 0x5; } else if ((priv == READ) && (user == READ)) { ap = 0x7; } } *descriptor_l2 &= PAGE_AP_MASK; *descriptor_l2 |= (ap & 0x3) << PAGE_AP_SHIFT; *descriptor_l2 |= ((ap & 0x4)>>2) << PAGE_AP2_SHIFT; return 0; } /** \brief Set 4k/64k page shareability The function sets 4k/64k page shareability \param [out] descriptor_l2 L2 descriptor. \param [in] s_bit 4k/64k page shareability: NON_SHARED, SHARED \return 0 */ __STATIC_INLINE int __shared_page(uint32_t *descriptor_l2, mmu_shared_Type s_bit) { *descriptor_l2 &= PAGE_S_MASK; *descriptor_l2 |= ((s_bit & 0x1) << PAGE_S_SHIFT); return 0; } /** \brief Set 4k/64k page Global attribute The function sets 4k/64k page Global attribute \param [out] descriptor_l2 L2 descriptor. \param [in] g_bit 4k/64k page attribute: GLOBAL, NON_GLOBAL \return 0 */ __STATIC_INLINE int __global_page(uint32_t *descriptor_l2, mmu_global_Type g_bit) { *descriptor_l2 &= PAGE_NG_MASK; *descriptor_l2 |= ((g_bit & 0x1) << PAGE_NG_SHIFT); return 0; } /** \brief Set 4k/64k page Security attribute The function sets 4k/64k page Global attribute \param [out] descriptor_l1 L1 descriptor. \param [in] s_bit 4k/64k page Security attribute: SECURE, NON_SECURE \return 0 */ __STATIC_INLINE int __secure_page(uint32_t *descriptor_l1, mmu_secure_Type s_bit) { *descriptor_l1 &= PAGE_NS_MASK; *descriptor_l1 |= ((s_bit & 0x1) << PAGE_NS_SHIFT); return 0; } /** \brief Set Section memory attributes The function sets section memory attributes \param [out] descriptor_l1 L1 descriptor. \param [in] mem Section memory type: NORMAL, DEVICE, SHARED_DEVICE, NON_SHARED_DEVICE, STRONGLY_ORDERED \param [in] outer Outer cacheability: NON_CACHEABLE, WB_WA, WT, WB_NO_WA, \param [in] inner Inner cacheability: NON_CACHEABLE, WB_WA, WT, WB_NO_WA, \return 0 */ __STATIC_INLINE int __memory_section(uint32_t *descriptor_l1, mmu_memory_Type mem, mmu_cacheability_Type outer, mmu_cacheability_Type inner) { *descriptor_l1 &= SECTION_TEXCB_MASK; if (STRONGLY_ORDERED == mem) { return 0; } else if (SHARED_DEVICE == mem) { *descriptor_l1 |= (1 << SECTION_B_SHIFT); } else if (NON_SHARED_DEVICE == mem) { *descriptor_l1 |= (1 << SECTION_TEX1_SHIFT); } else if (NORMAL == mem) { *descriptor_l1 |= 1 << SECTION_TEX2_SHIFT; switch(inner) { case NON_CACHEABLE: break; case WB_WA: *descriptor_l1 |= (1 << SECTION_B_SHIFT); break; case WT: *descriptor_l1 |= 1 << SECTION_C_SHIFT; break; case WB_NO_WA: *descriptor_l1 |= (1 << SECTION_B_SHIFT) | (1 << SECTION_C_SHIFT); break; } switch(outer) { case NON_CACHEABLE: break; case WB_WA: *descriptor_l1 |= (1 << SECTION_TEX0_SHIFT); break; case WT: *descriptor_l1 |= 1 << SECTION_TEX1_SHIFT; break; case WB_NO_WA: *descriptor_l1 |= (1 << SECTION_TEX0_SHIFT) | (1 << SECTION_TEX0_SHIFT); break; } } return 0; } /** \brief Set 4k/64k page memory attributes The function sets 4k/64k page memory attributes \param [out] descriptor_l2 L2 descriptor. \param [in] mem 4k/64k page memory type: NORMAL, DEVICE, SHARED_DEVICE, NON_SHARED_DEVICE, STRONGLY_ORDERED \param [in] outer Outer cacheability: NON_CACHEABLE, WB_WA, WT, WB_NO_WA, \param [in] inner Inner cacheability: NON_CACHEABLE, WB_WA, WT, WB_NO_WA, \return 0 */ __STATIC_INLINE int __memory_page(uint32_t *descriptor_l2, mmu_memory_Type mem, mmu_cacheability_Type outer, mmu_cacheability_Type inner, mmu_region_size_Type page) { *descriptor_l2 &= PAGE_4K_TEXCB_MASK; if (page == PAGE_64k) { //same as section __memory_section(descriptor_l2, mem, outer, inner); } else { if (STRONGLY_ORDERED == mem) { return 0; } else if (SHARED_DEVICE == mem) { *descriptor_l2 |= (1 << PAGE_4K_B_SHIFT); } else if (NON_SHARED_DEVICE == mem) { *descriptor_l2 |= (1 << PAGE_4K_TEX1_SHIFT); } else if (NORMAL == mem) { *descriptor_l2 |= 1 << PAGE_4K_TEX2_SHIFT; switch(inner) { case NON_CACHEABLE: break; case WB_WA: *descriptor_l2 |= (1 << PAGE_4K_B_SHIFT); break; case WT: *descriptor_l2 |= 1 << PAGE_4K_C_SHIFT; break; case WB_NO_WA: *descriptor_l2 |= (1 << PAGE_4K_B_SHIFT) | (1 << PAGE_4K_C_SHIFT); break; } switch(outer) { case NON_CACHEABLE: break; case WB_WA: *descriptor_l2 |= (1 << PAGE_4K_TEX0_SHIFT); break; case WT: *descriptor_l2 |= 1 << PAGE_4K_TEX1_SHIFT; break; case WB_NO_WA: *descriptor_l2 |= (1 << PAGE_4K_TEX0_SHIFT) | (1 << PAGE_4K_TEX0_SHIFT); break; } } } return 0; } /** \brief Create a L1 section descriptor The function creates a section descriptor. Assumptions: - 16MB super sections not supported - TEX remap disabled, so memory type and attributes are described directly by bits in the descriptor - Functions always return 0 \param [out] descriptor L1 descriptor \param [out] descriptor2 L2 descriptor \param [in] reg Section attributes \return 0 */ __STATIC_INLINE int __get_section_descriptor(uint32_t *descriptor, mmu_region_attributes_Type reg) { *descriptor = 0; __memory_section(descriptor, reg.mem_t, reg.outer_norm_t, reg.inner_norm_t); __xn_section(descriptor,reg.xn_t); __domain_section(descriptor, reg.domain); __p_section(descriptor, reg.e_t); __ap_section(descriptor, reg.priv_t, reg.user_t, 1); __shared_section(descriptor,reg.sh_t); __global_section(descriptor,reg.g_t); __secure_section(descriptor,reg.sec_t); *descriptor &= SECTION_MASK; *descriptor |= SECTION_DESCRIPTOR; return 0; } /** \brief Create a L1 and L2 4k/64k page descriptor The function creates a 4k/64k page descriptor. Assumptions: - TEX remap disabled, so memory type and attributes are described directly by bits in the descriptor - Functions always return 0 \param [out] descriptor L1 descriptor \param [out] descriptor2 L2 descriptor \param [in] reg 4k/64k page attributes \return 0 */ __STATIC_INLINE int __get_page_descriptor(uint32_t *descriptor, uint32_t *descriptor2, mmu_region_attributes_Type reg) { *descriptor = 0; *descriptor2 = 0; switch (reg.rg_t) { case PAGE_4k: __memory_page(descriptor2, reg.mem_t, reg.outer_norm_t, reg.inner_norm_t, PAGE_4k); __xn_page(descriptor2, reg.xn_t, PAGE_4k); __domain_page(descriptor, reg.domain); __p_page(descriptor, reg.e_t); __ap_page(descriptor2, reg.priv_t, reg.user_t, 1); __shared_page(descriptor2,reg.sh_t); __global_page(descriptor2,reg.g_t); __secure_page(descriptor,reg.sec_t); *descriptor &= PAGE_L1_MASK; *descriptor |= PAGE_L1_DESCRIPTOR; *descriptor2 &= PAGE_L2_4K_MASK; *descriptor2 |= PAGE_L2_4K_DESC; break; case PAGE_64k: __memory_page(descriptor2, reg.mem_t, reg.outer_norm_t, reg.inner_norm_t, PAGE_64k); __xn_page(descriptor2, reg.xn_t, PAGE_64k); __domain_page(descriptor, reg.domain); __p_page(descriptor, reg.e_t); __ap_page(descriptor2, reg.priv_t, reg.user_t, 1); __shared_page(descriptor2,reg.sh_t); __global_page(descriptor2,reg.g_t); __secure_page(descriptor,reg.sec_t); *descriptor &= PAGE_L1_MASK; *descriptor |= PAGE_L1_DESCRIPTOR; *descriptor2 &= PAGE_L2_64K_MASK; *descriptor2 |= PAGE_L2_64K_DESC; break; case SECTION: //error break; } return 0; } /** \brief Create a 1MB Section \param [in] ttb Translation table base address \param [in] base_address Section base address \param [in] count Number of sections to create \param [in] descriptor_l1 L1 descriptor (region attributes) */ __STATIC_INLINE void __TTSection(uint32_t *ttb, uint32_t base_address, uint32_t count, uint32_t descriptor_l1) { uint32_t offset; uint32_t entry; uint32_t i; offset = base_address >> 20; entry = (base_address & 0xFFF00000) | descriptor_l1; //4 bytes aligned ttb = ttb + offset; for (i = 0; i < count; i++ ) { //4 bytes aligned *ttb++ = entry; entry += OFFSET_1M; } } /** \brief Create a 4k page entry \param [in] ttb L1 table base address \param [in] base_address 4k base address \param [in] count Number of 4k pages to create \param [in] descriptor_l1 L1 descriptor (region attributes) \param [in] ttb_l2 L2 table base address \param [in] descriptor_l2 L2 descriptor (region attributes) */ __STATIC_INLINE void __TTPage_4k(uint32_t *ttb, uint32_t base_address, uint32_t count, uint32_t descriptor_l1, uint32_t *ttb_l2, uint32_t descriptor_l2 ) { uint32_t offset, offset2; uint32_t entry, entry2; uint32_t i; offset = base_address >> 20; entry = ((int)ttb_l2 & 0xFFFFFC00) | descriptor_l1; //4 bytes aligned ttb += offset; //create l1_entry *ttb = entry; offset2 = (base_address & 0xff000) >> 12; ttb_l2 += offset2; entry2 = (base_address & 0xFFFFF000) | descriptor_l2; for (i = 0; i < count; i++ ) { //4 bytes aligned *ttb_l2++ = entry2; entry2 += OFFSET_4K; } } /** \brief Create a 64k page entry \param [in] ttb L1 table base address \param [in] base_address 64k base address \param [in] count Number of 64k pages to create \param [in] descriptor_l1 L1 descriptor (region attributes) \param [in] ttb_l2 L2 table base address \param [in] descriptor_l2 L2 descriptor (region attributes) */ __STATIC_INLINE void __TTPage_64k(uint32_t *ttb, uint32_t base_address, uint32_t count, uint32_t descriptor_l1, uint32_t *ttb_l2, uint32_t descriptor_l2 ) { uint32_t offset, offset2; uint32_t entry, entry2; uint32_t i,j; offset = base_address >> 20; entry = ((int)ttb_l2 & 0xFFFFFC00) | descriptor_l1; //4 bytes aligned ttb += offset; //create l1_entry *ttb = entry; offset2 = (base_address & 0xff000) >> 12; ttb_l2 += offset2; entry2 = (base_address & 0xFFFF0000) | descriptor_l2; for (i = 0; i < count; i++ ) { //create 16 entries for (j = 0; j < 16; j++) //4 bytes aligned *ttb_l2++ = entry2; entry2 += OFFSET_64K; } } /*@} end of MMU_Functions */ #endif #ifdef __cplusplus } #endif ================================================ FILE: Zelig/mbed/TARGET_NUCLEO_F401RE/core_cm0.h ================================================ /**************************************************************************//** * @file core_cm0.h * @brief CMSIS Cortex-M0 Core Peripheral Access Layer Header File * @version V4.10 * @date 18. March 2015 * * @note * ******************************************************************************/ /* Copyright (c) 2009 - 2015 ARM LIMITED All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: - Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. - Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. - Neither the name of ARM 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 COPYRIGHT HOLDERS AND 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. ---------------------------------------------------------------------------*/ #if defined ( __ICCARM__ ) #pragma system_include /* treat file as system include file for MISRA check */ #endif #ifndef __CORE_CM0_H_GENERIC #define __CORE_CM0_H_GENERIC #ifdef __cplusplus extern "C" { #endif /** \page CMSIS_MISRA_Exceptions MISRA-C:2004 Compliance Exceptions CMSIS violates the following MISRA-C:2004 rules: \li Required Rule 8.5, object/function definition in header file.
Function definitions in header files are used to allow 'inlining'. \li Required Rule 18.4, declaration of union type or object of union type: '{...}'.
Unions are used for effective representation of core registers. \li Advisory Rule 19.7, Function-like macro defined.
Function-like macros are used to allow more efficient code. */ /******************************************************************************* * CMSIS definitions ******************************************************************************/ /** \ingroup Cortex_M0 @{ */ /* CMSIS CM0 definitions */ #define __CM0_CMSIS_VERSION_MAIN (0x04) /*!< [31:16] CMSIS HAL main version */ #define __CM0_CMSIS_VERSION_SUB (0x00) /*!< [15:0] CMSIS HAL sub version */ #define __CM0_CMSIS_VERSION ((__CM0_CMSIS_VERSION_MAIN << 16) | \ __CM0_CMSIS_VERSION_SUB ) /*!< CMSIS HAL version number */ #define __CORTEX_M (0x00) /*!< Cortex-M Core */ #if defined ( __CC_ARM ) #define __ASM __asm /*!< asm keyword for ARM Compiler */ #define __INLINE __inline /*!< inline keyword for ARM Compiler */ #define __STATIC_INLINE static __inline #elif defined ( __GNUC__ ) #define __ASM __asm /*!< asm keyword for GNU Compiler */ #define __INLINE inline /*!< inline keyword for GNU Compiler */ #define __STATIC_INLINE static inline #elif defined ( __ICCARM__ ) #define __ASM __asm /*!< asm keyword for IAR Compiler */ #define __INLINE inline /*!< inline keyword for IAR Compiler. Only available in High optimization mode! */ #define __STATIC_INLINE static inline #elif defined ( __TMS470__ ) #define __ASM __asm /*!< asm keyword for TI CCS Compiler */ #define __STATIC_INLINE static inline #elif defined ( __TASKING__ ) #define __ASM __asm /*!< asm keyword for TASKING Compiler */ #define __INLINE inline /*!< inline keyword for TASKING Compiler */ #define __STATIC_INLINE static inline #elif defined ( __CSMC__ ) #define __packed #define __ASM _asm /*!< asm keyword for COSMIC Compiler */ #define __INLINE inline /*use -pc99 on compile line !< inline keyword for COSMIC Compiler */ #define __STATIC_INLINE static inline #endif /** __FPU_USED indicates whether an FPU is used or not. This core does not support an FPU at all */ #define __FPU_USED 0 #if defined ( __CC_ARM ) #if defined __TARGET_FPU_VFP #warning "Compiler generates FPU instructions for a device without an FPU (check __FPU_PRESENT)" #endif #elif defined ( __GNUC__ ) #if defined (__VFP_FP__) && !defined(__SOFTFP__) #warning "Compiler generates FPU instructions for a device without an FPU (check __FPU_PRESENT)" #endif #elif defined ( __ICCARM__ ) #if defined __ARMVFP__ #warning "Compiler generates FPU instructions for a device without an FPU (check __FPU_PRESENT)" #endif #elif defined ( __TMS470__ ) #if defined __TI__VFP_SUPPORT____ #warning "Compiler generates FPU instructions for a device without an FPU (check __FPU_PRESENT)" #endif #elif defined ( __TASKING__ ) #if defined __FPU_VFP__ #error "Compiler generates FPU instructions for a device without an FPU (check __FPU_PRESENT)" #endif #elif defined ( __CSMC__ ) /* Cosmic */ #if ( __CSMC__ & 0x400) // FPU present for parser #error "Compiler generates FPU instructions for a device without an FPU (check __FPU_PRESENT)" #endif #endif #include /* standard types definitions */ #include /* Core Instruction Access */ #include /* Core Function Access */ #ifdef __cplusplus } #endif #endif /* __CORE_CM0_H_GENERIC */ #ifndef __CMSIS_GENERIC #ifndef __CORE_CM0_H_DEPENDANT #define __CORE_CM0_H_DEPENDANT #ifdef __cplusplus extern "C" { #endif /* check device defines and use defaults */ #if defined __CHECK_DEVICE_DEFINES #ifndef __CM0_REV #define __CM0_REV 0x0000 #warning "__CM0_REV not defined in device header file; using default!" #endif #ifndef __NVIC_PRIO_BITS #define __NVIC_PRIO_BITS 2 #warning "__NVIC_PRIO_BITS not defined in device header file; using default!" #endif #ifndef __Vendor_SysTickConfig #define __Vendor_SysTickConfig 0 #warning "__Vendor_SysTickConfig not defined in device header file; using default!" #endif #endif /* IO definitions (access restrictions to peripheral registers) */ /** \defgroup CMSIS_glob_defs CMSIS Global Defines IO Type Qualifiers are used \li to specify the access to peripheral variables. \li for automatic generation of peripheral register debug information. */ #ifdef __cplusplus #define __I volatile /*!< Defines 'read only' permissions */ #else #define __I volatile const /*!< Defines 'read only' permissions */ #endif #define __O volatile /*!< Defines 'write only' permissions */ #define __IO volatile /*!< Defines 'read / write' permissions */ /*@} end of group Cortex_M0 */ /******************************************************************************* * Register Abstraction Core Register contain: - Core Register - Core NVIC Register - Core SCB Register - Core SysTick Register ******************************************************************************/ /** \defgroup CMSIS_core_register Defines and Type Definitions \brief Type definitions and defines for Cortex-M processor based devices. */ /** \ingroup CMSIS_core_register \defgroup CMSIS_CORE Status and Control Registers \brief Core Register type definitions. @{ */ /** \brief Union type to access the Application Program Status Register (APSR). */ typedef union { struct { uint32_t _reserved0:28; /*!< bit: 0..27 Reserved */ uint32_t V:1; /*!< bit: 28 Overflow condition code flag */ uint32_t C:1; /*!< bit: 29 Carry condition code flag */ uint32_t Z:1; /*!< bit: 30 Zero condition code flag */ uint32_t N:1; /*!< bit: 31 Negative condition code flag */ } b; /*!< Structure used for bit access */ uint32_t w; /*!< Type used for word access */ } APSR_Type; /* APSR Register Definitions */ #define APSR_N_Pos 31 /*!< APSR: N Position */ #define APSR_N_Msk (1UL << APSR_N_Pos) /*!< APSR: N Mask */ #define APSR_Z_Pos 30 /*!< APSR: Z Position */ #define APSR_Z_Msk (1UL << APSR_Z_Pos) /*!< APSR: Z Mask */ #define APSR_C_Pos 29 /*!< APSR: C Position */ #define APSR_C_Msk (1UL << APSR_C_Pos) /*!< APSR: C Mask */ #define APSR_V_Pos 28 /*!< APSR: V Position */ #define APSR_V_Msk (1UL << APSR_V_Pos) /*!< APSR: V Mask */ /** \brief Union type to access the Interrupt Program Status Register (IPSR). */ typedef union { struct { uint32_t ISR:9; /*!< bit: 0.. 8 Exception number */ uint32_t _reserved0:23; /*!< bit: 9..31 Reserved */ } b; /*!< Structure used for bit access */ uint32_t w; /*!< Type used for word access */ } IPSR_Type; /* IPSR Register Definitions */ #define IPSR_ISR_Pos 0 /*!< IPSR: ISR Position */ #define IPSR_ISR_Msk (0x1FFUL /*<< IPSR_ISR_Pos*/) /*!< IPSR: ISR Mask */ /** \brief Union type to access the Special-Purpose Program Status Registers (xPSR). */ typedef union { struct { uint32_t ISR:9; /*!< bit: 0.. 8 Exception number */ uint32_t _reserved0:15; /*!< bit: 9..23 Reserved */ uint32_t T:1; /*!< bit: 24 Thumb bit (read 0) */ uint32_t _reserved1:3; /*!< bit: 25..27 Reserved */ uint32_t V:1; /*!< bit: 28 Overflow condition code flag */ uint32_t C:1; /*!< bit: 29 Carry condition code flag */ uint32_t Z:1; /*!< bit: 30 Zero condition code flag */ uint32_t N:1; /*!< bit: 31 Negative condition code flag */ } b; /*!< Structure used for bit access */ uint32_t w; /*!< Type used for word access */ } xPSR_Type; /* xPSR Register Definitions */ #define xPSR_N_Pos 31 /*!< xPSR: N Position */ #define xPSR_N_Msk (1UL << xPSR_N_Pos) /*!< xPSR: N Mask */ #define xPSR_Z_Pos 30 /*!< xPSR: Z Position */ #define xPSR_Z_Msk (1UL << xPSR_Z_Pos) /*!< xPSR: Z Mask */ #define xPSR_C_Pos 29 /*!< xPSR: C Position */ #define xPSR_C_Msk (1UL << xPSR_C_Pos) /*!< xPSR: C Mask */ #define xPSR_V_Pos 28 /*!< xPSR: V Position */ #define xPSR_V_Msk (1UL << xPSR_V_Pos) /*!< xPSR: V Mask */ #define xPSR_T_Pos 24 /*!< xPSR: T Position */ #define xPSR_T_Msk (1UL << xPSR_T_Pos) /*!< xPSR: T Mask */ #define xPSR_ISR_Pos 0 /*!< xPSR: ISR Position */ #define xPSR_ISR_Msk (0x1FFUL /*<< xPSR_ISR_Pos*/) /*!< xPSR: ISR Mask */ /** \brief Union type to access the Control Registers (CONTROL). */ typedef union { struct { uint32_t _reserved0:1; /*!< bit: 0 Reserved */ uint32_t SPSEL:1; /*!< bit: 1 Stack to be used */ uint32_t _reserved1:30; /*!< bit: 2..31 Reserved */ } b; /*!< Structure used for bit access */ uint32_t w; /*!< Type used for word access */ } CONTROL_Type; /* CONTROL Register Definitions */ #define CONTROL_SPSEL_Pos 1 /*!< CONTROL: SPSEL Position */ #define CONTROL_SPSEL_Msk (1UL << CONTROL_SPSEL_Pos) /*!< CONTROL: SPSEL Mask */ /*@} end of group CMSIS_CORE */ /** \ingroup CMSIS_core_register \defgroup CMSIS_NVIC Nested Vectored Interrupt Controller (NVIC) \brief Type definitions for the NVIC Registers @{ */ /** \brief Structure type to access the Nested Vectored Interrupt Controller (NVIC). */ typedef struct { __IO uint32_t ISER[1]; /*!< Offset: 0x000 (R/W) Interrupt Set Enable Register */ uint32_t RESERVED0[31]; __IO uint32_t ICER[1]; /*!< Offset: 0x080 (R/W) Interrupt Clear Enable Register */ uint32_t RSERVED1[31]; __IO uint32_t ISPR[1]; /*!< Offset: 0x100 (R/W) Interrupt Set Pending Register */ uint32_t RESERVED2[31]; __IO uint32_t ICPR[1]; /*!< Offset: 0x180 (R/W) Interrupt Clear Pending Register */ uint32_t RESERVED3[31]; uint32_t RESERVED4[64]; __IO uint32_t IP[8]; /*!< Offset: 0x300 (R/W) Interrupt Priority Register */ } NVIC_Type; /*@} end of group CMSIS_NVIC */ /** \ingroup CMSIS_core_register \defgroup CMSIS_SCB System Control Block (SCB) \brief Type definitions for the System Control Block Registers @{ */ /** \brief Structure type to access the System Control Block (SCB). */ typedef struct { __I uint32_t CPUID; /*!< Offset: 0x000 (R/ ) CPUID Base Register */ __IO uint32_t ICSR; /*!< Offset: 0x004 (R/W) Interrupt Control and State Register */ uint32_t RESERVED0; __IO uint32_t AIRCR; /*!< Offset: 0x00C (R/W) Application Interrupt and Reset Control Register */ __IO uint32_t SCR; /*!< Offset: 0x010 (R/W) System Control Register */ __IO uint32_t CCR; /*!< Offset: 0x014 (R/W) Configuration Control Register */ uint32_t RESERVED1; __IO uint32_t SHP[2]; /*!< Offset: 0x01C (R/W) System Handlers Priority Registers. [0] is RESERVED */ __IO uint32_t SHCSR; /*!< Offset: 0x024 (R/W) System Handler Control and State Register */ } SCB_Type; /* SCB CPUID Register Definitions */ #define SCB_CPUID_IMPLEMENTER_Pos 24 /*!< SCB CPUID: IMPLEMENTER Position */ #define SCB_CPUID_IMPLEMENTER_Msk (0xFFUL << SCB_CPUID_IMPLEMENTER_Pos) /*!< SCB CPUID: IMPLEMENTER Mask */ #define SCB_CPUID_VARIANT_Pos 20 /*!< SCB CPUID: VARIANT Position */ #define SCB_CPUID_VARIANT_Msk (0xFUL << SCB_CPUID_VARIANT_Pos) /*!< SCB CPUID: VARIANT Mask */ #define SCB_CPUID_ARCHITECTURE_Pos 16 /*!< SCB CPUID: ARCHITECTURE Position */ #define SCB_CPUID_ARCHITECTURE_Msk (0xFUL << SCB_CPUID_ARCHITECTURE_Pos) /*!< SCB CPUID: ARCHITECTURE Mask */ #define SCB_CPUID_PARTNO_Pos 4 /*!< SCB CPUID: PARTNO Position */ #define SCB_CPUID_PARTNO_Msk (0xFFFUL << SCB_CPUID_PARTNO_Pos) /*!< SCB CPUID: PARTNO Mask */ #define SCB_CPUID_REVISION_Pos 0 /*!< SCB CPUID: REVISION Position */ #define SCB_CPUID_REVISION_Msk (0xFUL /*<< SCB_CPUID_REVISION_Pos*/) /*!< SCB CPUID: REVISION Mask */ /* SCB Interrupt Control State Register Definitions */ #define SCB_ICSR_NMIPENDSET_Pos 31 /*!< SCB ICSR: NMIPENDSET Position */ #define SCB_ICSR_NMIPENDSET_Msk (1UL << SCB_ICSR_NMIPENDSET_Pos) /*!< SCB ICSR: NMIPENDSET Mask */ #define SCB_ICSR_PENDSVSET_Pos 28 /*!< SCB ICSR: PENDSVSET Position */ #define SCB_ICSR_PENDSVSET_Msk (1UL << SCB_ICSR_PENDSVSET_Pos) /*!< SCB ICSR: PENDSVSET Mask */ #define SCB_ICSR_PENDSVCLR_Pos 27 /*!< SCB ICSR: PENDSVCLR Position */ #define SCB_ICSR_PENDSVCLR_Msk (1UL << SCB_ICSR_PENDSVCLR_Pos) /*!< SCB ICSR: PENDSVCLR Mask */ #define SCB_ICSR_PENDSTSET_Pos 26 /*!< SCB ICSR: PENDSTSET Position */ #define SCB_ICSR_PENDSTSET_Msk (1UL << SCB_ICSR_PENDSTSET_Pos) /*!< SCB ICSR: PENDSTSET Mask */ #define SCB_ICSR_PENDSTCLR_Pos 25 /*!< SCB ICSR: PENDSTCLR Position */ #define SCB_ICSR_PENDSTCLR_Msk (1UL << SCB_ICSR_PENDSTCLR_Pos) /*!< SCB ICSR: PENDSTCLR Mask */ #define SCB_ICSR_ISRPREEMPT_Pos 23 /*!< SCB ICSR: ISRPREEMPT Position */ #define SCB_ICSR_ISRPREEMPT_Msk (1UL << SCB_ICSR_ISRPREEMPT_Pos) /*!< SCB ICSR: ISRPREEMPT Mask */ #define SCB_ICSR_ISRPENDING_Pos 22 /*!< SCB ICSR: ISRPENDING Position */ #define SCB_ICSR_ISRPENDING_Msk (1UL << SCB_ICSR_ISRPENDING_Pos) /*!< SCB ICSR: ISRPENDING Mask */ #define SCB_ICSR_VECTPENDING_Pos 12 /*!< SCB ICSR: VECTPENDING Position */ #define SCB_ICSR_VECTPENDING_Msk (0x1FFUL << SCB_ICSR_VECTPENDING_Pos) /*!< SCB ICSR: VECTPENDING Mask */ #define SCB_ICSR_VECTACTIVE_Pos 0 /*!< SCB ICSR: VECTACTIVE Position */ #define SCB_ICSR_VECTACTIVE_Msk (0x1FFUL /*<< SCB_ICSR_VECTACTIVE_Pos*/) /*!< SCB ICSR: VECTACTIVE Mask */ /* SCB Application Interrupt and Reset Control Register Definitions */ #define SCB_AIRCR_VECTKEY_Pos 16 /*!< SCB AIRCR: VECTKEY Position */ #define SCB_AIRCR_VECTKEY_Msk (0xFFFFUL << SCB_AIRCR_VECTKEY_Pos) /*!< SCB AIRCR: VECTKEY Mask */ #define SCB_AIRCR_VECTKEYSTAT_Pos 16 /*!< SCB AIRCR: VECTKEYSTAT Position */ #define SCB_AIRCR_VECTKEYSTAT_Msk (0xFFFFUL << SCB_AIRCR_VECTKEYSTAT_Pos) /*!< SCB AIRCR: VECTKEYSTAT Mask */ #define SCB_AIRCR_ENDIANESS_Pos 15 /*!< SCB AIRCR: ENDIANESS Position */ #define SCB_AIRCR_ENDIANESS_Msk (1UL << SCB_AIRCR_ENDIANESS_Pos) /*!< SCB AIRCR: ENDIANESS Mask */ #define SCB_AIRCR_SYSRESETREQ_Pos 2 /*!< SCB AIRCR: SYSRESETREQ Position */ #define SCB_AIRCR_SYSRESETREQ_Msk (1UL << SCB_AIRCR_SYSRESETREQ_Pos) /*!< SCB AIRCR: SYSRESETREQ Mask */ #define SCB_AIRCR_VECTCLRACTIVE_Pos 1 /*!< SCB AIRCR: VECTCLRACTIVE Position */ #define SCB_AIRCR_VECTCLRACTIVE_Msk (1UL << SCB_AIRCR_VECTCLRACTIVE_Pos) /*!< SCB AIRCR: VECTCLRACTIVE Mask */ /* SCB System Control Register Definitions */ #define SCB_SCR_SEVONPEND_Pos 4 /*!< SCB SCR: SEVONPEND Position */ #define SCB_SCR_SEVONPEND_Msk (1UL << SCB_SCR_SEVONPEND_Pos) /*!< SCB SCR: SEVONPEND Mask */ #define SCB_SCR_SLEEPDEEP_Pos 2 /*!< SCB SCR: SLEEPDEEP Position */ #define SCB_SCR_SLEEPDEEP_Msk (1UL << SCB_SCR_SLEEPDEEP_Pos) /*!< SCB SCR: SLEEPDEEP Mask */ #define SCB_SCR_SLEEPONEXIT_Pos 1 /*!< SCB SCR: SLEEPONEXIT Position */ #define SCB_SCR_SLEEPONEXIT_Msk (1UL << SCB_SCR_SLEEPONEXIT_Pos) /*!< SCB SCR: SLEEPONEXIT Mask */ /* SCB Configuration Control Register Definitions */ #define SCB_CCR_STKALIGN_Pos 9 /*!< SCB CCR: STKALIGN Position */ #define SCB_CCR_STKALIGN_Msk (1UL << SCB_CCR_STKALIGN_Pos) /*!< SCB CCR: STKALIGN Mask */ #define SCB_CCR_UNALIGN_TRP_Pos 3 /*!< SCB CCR: UNALIGN_TRP Position */ #define SCB_CCR_UNALIGN_TRP_Msk (1UL << SCB_CCR_UNALIGN_TRP_Pos) /*!< SCB CCR: UNALIGN_TRP Mask */ /* SCB System Handler Control and State Register Definitions */ #define SCB_SHCSR_SVCALLPENDED_Pos 15 /*!< SCB SHCSR: SVCALLPENDED Position */ #define SCB_SHCSR_SVCALLPENDED_Msk (1UL << SCB_SHCSR_SVCALLPENDED_Pos) /*!< SCB SHCSR: SVCALLPENDED Mask */ /*@} end of group CMSIS_SCB */ /** \ingroup CMSIS_core_register \defgroup CMSIS_SysTick System Tick Timer (SysTick) \brief Type definitions for the System Timer Registers. @{ */ /** \brief Structure type to access the System Timer (SysTick). */ typedef struct { __IO uint32_t CTRL; /*!< Offset: 0x000 (R/W) SysTick Control and Status Register */ __IO uint32_t LOAD; /*!< Offset: 0x004 (R/W) SysTick Reload Value Register */ __IO uint32_t VAL; /*!< Offset: 0x008 (R/W) SysTick Current Value Register */ __I uint32_t CALIB; /*!< Offset: 0x00C (R/ ) SysTick Calibration Register */ } SysTick_Type; /* SysTick Control / Status Register Definitions */ #define SysTick_CTRL_COUNTFLAG_Pos 16 /*!< SysTick CTRL: COUNTFLAG Position */ #define SysTick_CTRL_COUNTFLAG_Msk (1UL << SysTick_CTRL_COUNTFLAG_Pos) /*!< SysTick CTRL: COUNTFLAG Mask */ #define SysTick_CTRL_CLKSOURCE_Pos 2 /*!< SysTick CTRL: CLKSOURCE Position */ #define SysTick_CTRL_CLKSOURCE_Msk (1UL << SysTick_CTRL_CLKSOURCE_Pos) /*!< SysTick CTRL: CLKSOURCE Mask */ #define SysTick_CTRL_TICKINT_Pos 1 /*!< SysTick CTRL: TICKINT Position */ #define SysTick_CTRL_TICKINT_Msk (1UL << SysTick_CTRL_TICKINT_Pos) /*!< SysTick CTRL: TICKINT Mask */ #define SysTick_CTRL_ENABLE_Pos 0 /*!< SysTick CTRL: ENABLE Position */ #define SysTick_CTRL_ENABLE_Msk (1UL /*<< SysTick_CTRL_ENABLE_Pos*/) /*!< SysTick CTRL: ENABLE Mask */ /* SysTick Reload Register Definitions */ #define SysTick_LOAD_RELOAD_Pos 0 /*!< SysTick LOAD: RELOAD Position */ #define SysTick_LOAD_RELOAD_Msk (0xFFFFFFUL /*<< SysTick_LOAD_RELOAD_Pos*/) /*!< SysTick LOAD: RELOAD Mask */ /* SysTick Current Register Definitions */ #define SysTick_VAL_CURRENT_Pos 0 /*!< SysTick VAL: CURRENT Position */ #define SysTick_VAL_CURRENT_Msk (0xFFFFFFUL /*<< SysTick_VAL_CURRENT_Pos*/) /*!< SysTick VAL: CURRENT Mask */ /* SysTick Calibration Register Definitions */ #define SysTick_CALIB_NOREF_Pos 31 /*!< SysTick CALIB: NOREF Position */ #define SysTick_CALIB_NOREF_Msk (1UL << SysTick_CALIB_NOREF_Pos) /*!< SysTick CALIB: NOREF Mask */ #define SysTick_CALIB_SKEW_Pos 30 /*!< SysTick CALIB: SKEW Position */ #define SysTick_CALIB_SKEW_Msk (1UL << SysTick_CALIB_SKEW_Pos) /*!< SysTick CALIB: SKEW Mask */ #define SysTick_CALIB_TENMS_Pos 0 /*!< SysTick CALIB: TENMS Position */ #define SysTick_CALIB_TENMS_Msk (0xFFFFFFUL /*<< SysTick_CALIB_TENMS_Pos*/) /*!< SysTick CALIB: TENMS Mask */ /*@} end of group CMSIS_SysTick */ /** \ingroup CMSIS_core_register \defgroup CMSIS_CoreDebug Core Debug Registers (CoreDebug) \brief Cortex-M0 Core Debug Registers (DCB registers, SHCSR, and DFSR) are only accessible over DAP and not via processor. Therefore they are not covered by the Cortex-M0 header file. @{ */ /*@} end of group CMSIS_CoreDebug */ /** \ingroup CMSIS_core_register \defgroup CMSIS_core_base Core Definitions \brief Definitions for base addresses, unions, and structures. @{ */ /* Memory mapping of Cortex-M0 Hardware */ #define SCS_BASE (0xE000E000UL) /*!< System Control Space Base Address */ #define SysTick_BASE (SCS_BASE + 0x0010UL) /*!< SysTick Base Address */ #define NVIC_BASE (SCS_BASE + 0x0100UL) /*!< NVIC Base Address */ #define SCB_BASE (SCS_BASE + 0x0D00UL) /*!< System Control Block Base Address */ #define SCB ((SCB_Type *) SCB_BASE ) /*!< SCB configuration struct */ #define SysTick ((SysTick_Type *) SysTick_BASE ) /*!< SysTick configuration struct */ #define NVIC ((NVIC_Type *) NVIC_BASE ) /*!< NVIC configuration struct */ /*@} */ /******************************************************************************* * Hardware Abstraction Layer Core Function Interface contains: - Core NVIC Functions - Core SysTick Functions - Core Register Access Functions ******************************************************************************/ /** \defgroup CMSIS_Core_FunctionInterface Functions and Instructions Reference */ /* ########################## NVIC functions #################################### */ /** \ingroup CMSIS_Core_FunctionInterface \defgroup CMSIS_Core_NVICFunctions NVIC Functions \brief Functions that manage interrupts and exceptions via the NVIC. @{ */ /* Interrupt Priorities are WORD accessible only under ARMv6M */ /* The following MACROS handle generation of the register offset and byte masks */ #define _BIT_SHIFT(IRQn) ( ((((uint32_t)(int32_t)(IRQn)) ) & 0x03UL) * 8UL) #define _SHP_IDX(IRQn) ( (((((uint32_t)(int32_t)(IRQn)) & 0x0FUL)-8UL) >> 2UL) ) #define _IP_IDX(IRQn) ( (((uint32_t)(int32_t)(IRQn)) >> 2UL) ) /** \brief Enable External Interrupt The function enables a device-specific interrupt in the NVIC interrupt controller. \param [in] IRQn External interrupt number. Value cannot be negative. */ __STATIC_INLINE void NVIC_EnableIRQ(IRQn_Type IRQn) { NVIC->ISER[0] = (uint32_t)(1UL << (((uint32_t)(int32_t)IRQn) & 0x1FUL)); } /** \brief Disable External Interrupt The function disables a device-specific interrupt in the NVIC interrupt controller. \param [in] IRQn External interrupt number. Value cannot be negative. */ __STATIC_INLINE void NVIC_DisableIRQ(IRQn_Type IRQn) { NVIC->ICER[0] = (uint32_t)(1UL << (((uint32_t)(int32_t)IRQn) & 0x1FUL)); } /** \brief Get Pending Interrupt The function reads the pending register in the NVIC and returns the pending bit for the specified interrupt. \param [in] IRQn Interrupt number. \return 0 Interrupt status is not pending. \return 1 Interrupt status is pending. */ __STATIC_INLINE uint32_t NVIC_GetPendingIRQ(IRQn_Type IRQn) { return((uint32_t)(((NVIC->ISPR[0] & (1UL << (((uint32_t)(int32_t)IRQn) & 0x1FUL))) != 0UL) ? 1UL : 0UL)); } /** \brief Set Pending Interrupt The function sets the pending bit of an external interrupt. \param [in] IRQn Interrupt number. Value cannot be negative. */ __STATIC_INLINE void NVIC_SetPendingIRQ(IRQn_Type IRQn) { NVIC->ISPR[0] = (uint32_t)(1UL << (((uint32_t)(int32_t)IRQn) & 0x1FUL)); } /** \brief Clear Pending Interrupt The function clears the pending bit of an external interrupt. \param [in] IRQn External interrupt number. Value cannot be negative. */ __STATIC_INLINE void NVIC_ClearPendingIRQ(IRQn_Type IRQn) { NVIC->ICPR[0] = (uint32_t)(1UL << (((uint32_t)(int32_t)IRQn) & 0x1FUL)); } /** \brief Set Interrupt Priority The function sets the priority of an interrupt. \note The priority cannot be set for every core interrupt. \param [in] IRQn Interrupt number. \param [in] priority Priority to set. */ __STATIC_INLINE void NVIC_SetPriority(IRQn_Type IRQn, uint32_t priority) { if((int32_t)(IRQn) < 0) { SCB->SHP[_SHP_IDX(IRQn)] = ((uint32_t)(SCB->SHP[_SHP_IDX(IRQn)] & ~(0xFFUL << _BIT_SHIFT(IRQn))) | (((priority << (8 - __NVIC_PRIO_BITS)) & (uint32_t)0xFFUL) << _BIT_SHIFT(IRQn))); } else { NVIC->IP[_IP_IDX(IRQn)] = ((uint32_t)(NVIC->IP[_IP_IDX(IRQn)] & ~(0xFFUL << _BIT_SHIFT(IRQn))) | (((priority << (8 - __NVIC_PRIO_BITS)) & (uint32_t)0xFFUL) << _BIT_SHIFT(IRQn))); } } /** \brief Get Interrupt Priority The function reads the priority of an interrupt. The interrupt number can be positive to specify an external (device specific) interrupt, or negative to specify an internal (core) interrupt. \param [in] IRQn Interrupt number. \return Interrupt Priority. Value is aligned automatically to the implemented priority bits of the microcontroller. */ __STATIC_INLINE uint32_t NVIC_GetPriority(IRQn_Type IRQn) { if((int32_t)(IRQn) < 0) { return((uint32_t)(((SCB->SHP[_SHP_IDX(IRQn)] >> _BIT_SHIFT(IRQn) ) & (uint32_t)0xFFUL) >> (8 - __NVIC_PRIO_BITS))); } else { return((uint32_t)(((NVIC->IP[ _IP_IDX(IRQn)] >> _BIT_SHIFT(IRQn) ) & (uint32_t)0xFFUL) >> (8 - __NVIC_PRIO_BITS))); } } /** \brief System Reset The function initiates a system reset request to reset the MCU. */ __STATIC_INLINE void NVIC_SystemReset(void) { __DSB(); /* Ensure all outstanding memory accesses included buffered write are completed before reset */ SCB->AIRCR = ((0x5FAUL << SCB_AIRCR_VECTKEY_Pos) | SCB_AIRCR_SYSRESETREQ_Msk); __DSB(); /* Ensure completion of memory access */ while(1) { __NOP(); } /* wait until reset */ } /*@} end of CMSIS_Core_NVICFunctions */ /* ################################## SysTick function ############################################ */ /** \ingroup CMSIS_Core_FunctionInterface \defgroup CMSIS_Core_SysTickFunctions SysTick Functions \brief Functions that configure the System. @{ */ #if (__Vendor_SysTickConfig == 0) /** \brief System Tick Configuration The function initializes the System Timer and its interrupt, and starts the System Tick Timer. Counter is in free running mode to generate periodic interrupts. \param [in] ticks Number of ticks between two interrupts. \return 0 Function succeeded. \return 1 Function failed. \note When the variable __Vendor_SysTickConfig is set to 1, then the function SysTick_Config is not included. In this case, the file device.h must contain a vendor-specific implementation of this function. */ __STATIC_INLINE uint32_t SysTick_Config(uint32_t ticks) { if ((ticks - 1UL) > SysTick_LOAD_RELOAD_Msk) { return (1UL); } /* Reload value impossible */ SysTick->LOAD = (uint32_t)(ticks - 1UL); /* set reload register */ NVIC_SetPriority (SysTick_IRQn, (1UL << __NVIC_PRIO_BITS) - 1UL); /* set Priority for Systick Interrupt */ SysTick->VAL = 0UL; /* Load the SysTick Counter Value */ SysTick->CTRL = SysTick_CTRL_CLKSOURCE_Msk | SysTick_CTRL_TICKINT_Msk | SysTick_CTRL_ENABLE_Msk; /* Enable SysTick IRQ and SysTick Timer */ return (0UL); /* Function successful */ } #endif /*@} end of CMSIS_Core_SysTickFunctions */ #ifdef __cplusplus } #endif #endif /* __CORE_CM0_H_DEPENDANT */ #endif /* __CMSIS_GENERIC */ ================================================ FILE: Zelig/mbed/TARGET_NUCLEO_F401RE/core_cm0plus.h ================================================ /**************************************************************************//** * @file core_cm0plus.h * @brief CMSIS Cortex-M0+ Core Peripheral Access Layer Header File * @version V4.10 * @date 18. March 2015 * * @note * ******************************************************************************/ /* Copyright (c) 2009 - 2015 ARM LIMITED All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: - Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. - Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. - Neither the name of ARM 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 COPYRIGHT HOLDERS AND 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. ---------------------------------------------------------------------------*/ #if defined ( __ICCARM__ ) #pragma system_include /* treat file as system include file for MISRA check */ #endif #ifndef __CORE_CM0PLUS_H_GENERIC #define __CORE_CM0PLUS_H_GENERIC #ifdef __cplusplus extern "C" { #endif /** \page CMSIS_MISRA_Exceptions MISRA-C:2004 Compliance Exceptions CMSIS violates the following MISRA-C:2004 rules: \li Required Rule 8.5, object/function definition in header file.
Function definitions in header files are used to allow 'inlining'. \li Required Rule 18.4, declaration of union type or object of union type: '{...}'.
Unions are used for effective representation of core registers. \li Advisory Rule 19.7, Function-like macro defined.
Function-like macros are used to allow more efficient code. */ /******************************************************************************* * CMSIS definitions ******************************************************************************/ /** \ingroup Cortex-M0+ @{ */ /* CMSIS CM0P definitions */ #define __CM0PLUS_CMSIS_VERSION_MAIN (0x04) /*!< [31:16] CMSIS HAL main version */ #define __CM0PLUS_CMSIS_VERSION_SUB (0x00) /*!< [15:0] CMSIS HAL sub version */ #define __CM0PLUS_CMSIS_VERSION ((__CM0PLUS_CMSIS_VERSION_MAIN << 16) | \ __CM0PLUS_CMSIS_VERSION_SUB) /*!< CMSIS HAL version number */ #define __CORTEX_M (0x00) /*!< Cortex-M Core */ #if defined ( __CC_ARM ) #define __ASM __asm /*!< asm keyword for ARM Compiler */ #define __INLINE __inline /*!< inline keyword for ARM Compiler */ #define __STATIC_INLINE static __inline #elif defined ( __GNUC__ ) #define __ASM __asm /*!< asm keyword for GNU Compiler */ #define __INLINE inline /*!< inline keyword for GNU Compiler */ #define __STATIC_INLINE static inline #elif defined ( __ICCARM__ ) #define __ASM __asm /*!< asm keyword for IAR Compiler */ #define __INLINE inline /*!< inline keyword for IAR Compiler. Only available in High optimization mode! */ #define __STATIC_INLINE static inline #elif defined ( __TMS470__ ) #define __ASM __asm /*!< asm keyword for TI CCS Compiler */ #define __STATIC_INLINE static inline #elif defined ( __TASKING__ ) #define __ASM __asm /*!< asm keyword for TASKING Compiler */ #define __INLINE inline /*!< inline keyword for TASKING Compiler */ #define __STATIC_INLINE static inline #elif defined ( __CSMC__ ) #define __packed #define __ASM _asm /*!< asm keyword for COSMIC Compiler */ #define __INLINE inline /*use -pc99 on compile line !< inline keyword for COSMIC Compiler */ #define __STATIC_INLINE static inline #endif /** __FPU_USED indicates whether an FPU is used or not. This core does not support an FPU at all */ #define __FPU_USED 0 #if defined ( __CC_ARM ) #if defined __TARGET_FPU_VFP #warning "Compiler generates FPU instructions for a device without an FPU (check __FPU_PRESENT)" #endif #elif defined ( __GNUC__ ) #if defined (__VFP_FP__) && !defined(__SOFTFP__) #warning "Compiler generates FPU instructions for a device without an FPU (check __FPU_PRESENT)" #endif #elif defined ( __ICCARM__ ) #if defined __ARMVFP__ #warning "Compiler generates FPU instructions for a device without an FPU (check __FPU_PRESENT)" #endif #elif defined ( __TMS470__ ) #if defined __TI__VFP_SUPPORT____ #warning "Compiler generates FPU instructions for a device without an FPU (check __FPU_PRESENT)" #endif #elif defined ( __TASKING__ ) #if defined __FPU_VFP__ #error "Compiler generates FPU instructions for a device without an FPU (check __FPU_PRESENT)" #endif #elif defined ( __CSMC__ ) /* Cosmic */ #if ( __CSMC__ & 0x400) // FPU present for parser #error "Compiler generates FPU instructions for a device without an FPU (check __FPU_PRESENT)" #endif #endif #include /* standard types definitions */ #include /* Core Instruction Access */ #include /* Core Function Access */ #ifdef __cplusplus } #endif #endif /* __CORE_CM0PLUS_H_GENERIC */ #ifndef __CMSIS_GENERIC #ifndef __CORE_CM0PLUS_H_DEPENDANT #define __CORE_CM0PLUS_H_DEPENDANT #ifdef __cplusplus extern "C" { #endif /* check device defines and use defaults */ #if defined __CHECK_DEVICE_DEFINES #ifndef __CM0PLUS_REV #define __CM0PLUS_REV 0x0000 #warning "__CM0PLUS_REV not defined in device header file; using default!" #endif #ifndef __MPU_PRESENT #define __MPU_PRESENT 0 #warning "__MPU_PRESENT not defined in device header file; using default!" #endif #ifndef __VTOR_PRESENT #define __VTOR_PRESENT 0 #warning "__VTOR_PRESENT not defined in device header file; using default!" #endif #ifndef __NVIC_PRIO_BITS #define __NVIC_PRIO_BITS 2 #warning "__NVIC_PRIO_BITS not defined in device header file; using default!" #endif #ifndef __Vendor_SysTickConfig #define __Vendor_SysTickConfig 0 #warning "__Vendor_SysTickConfig not defined in device header file; using default!" #endif #endif /* IO definitions (access restrictions to peripheral registers) */ /** \defgroup CMSIS_glob_defs CMSIS Global Defines IO Type Qualifiers are used \li to specify the access to peripheral variables. \li for automatic generation of peripheral register debug information. */ #ifdef __cplusplus #define __I volatile /*!< Defines 'read only' permissions */ #else #define __I volatile const /*!< Defines 'read only' permissions */ #endif #define __O volatile /*!< Defines 'write only' permissions */ #define __IO volatile /*!< Defines 'read / write' permissions */ /*@} end of group Cortex-M0+ */ /******************************************************************************* * Register Abstraction Core Register contain: - Core Register - Core NVIC Register - Core SCB Register - Core SysTick Register - Core MPU Register ******************************************************************************/ /** \defgroup CMSIS_core_register Defines and Type Definitions \brief Type definitions and defines for Cortex-M processor based devices. */ /** \ingroup CMSIS_core_register \defgroup CMSIS_CORE Status and Control Registers \brief Core Register type definitions. @{ */ /** \brief Union type to access the Application Program Status Register (APSR). */ typedef union { struct { uint32_t _reserved0:28; /*!< bit: 0..27 Reserved */ uint32_t V:1; /*!< bit: 28 Overflow condition code flag */ uint32_t C:1; /*!< bit: 29 Carry condition code flag */ uint32_t Z:1; /*!< bit: 30 Zero condition code flag */ uint32_t N:1; /*!< bit: 31 Negative condition code flag */ } b; /*!< Structure used for bit access */ uint32_t w; /*!< Type used for word access */ } APSR_Type; /* APSR Register Definitions */ #define APSR_N_Pos 31 /*!< APSR: N Position */ #define APSR_N_Msk (1UL << APSR_N_Pos) /*!< APSR: N Mask */ #define APSR_Z_Pos 30 /*!< APSR: Z Position */ #define APSR_Z_Msk (1UL << APSR_Z_Pos) /*!< APSR: Z Mask */ #define APSR_C_Pos 29 /*!< APSR: C Position */ #define APSR_C_Msk (1UL << APSR_C_Pos) /*!< APSR: C Mask */ #define APSR_V_Pos 28 /*!< APSR: V Position */ #define APSR_V_Msk (1UL << APSR_V_Pos) /*!< APSR: V Mask */ /** \brief Union type to access the Interrupt Program Status Register (IPSR). */ typedef union { struct { uint32_t ISR:9; /*!< bit: 0.. 8 Exception number */ uint32_t _reserved0:23; /*!< bit: 9..31 Reserved */ } b; /*!< Structure used for bit access */ uint32_t w; /*!< Type used for word access */ } IPSR_Type; /* IPSR Register Definitions */ #define IPSR_ISR_Pos 0 /*!< IPSR: ISR Position */ #define IPSR_ISR_Msk (0x1FFUL /*<< IPSR_ISR_Pos*/) /*!< IPSR: ISR Mask */ /** \brief Union type to access the Special-Purpose Program Status Registers (xPSR). */ typedef union { struct { uint32_t ISR:9; /*!< bit: 0.. 8 Exception number */ uint32_t _reserved0:15; /*!< bit: 9..23 Reserved */ uint32_t T:1; /*!< bit: 24 Thumb bit (read 0) */ uint32_t _reserved1:3; /*!< bit: 25..27 Reserved */ uint32_t V:1; /*!< bit: 28 Overflow condition code flag */ uint32_t C:1; /*!< bit: 29 Carry condition code flag */ uint32_t Z:1; /*!< bit: 30 Zero condition code flag */ uint32_t N:1; /*!< bit: 31 Negative condition code flag */ } b; /*!< Structure used for bit access */ uint32_t w; /*!< Type used for word access */ } xPSR_Type; /* xPSR Register Definitions */ #define xPSR_N_Pos 31 /*!< xPSR: N Position */ #define xPSR_N_Msk (1UL << xPSR_N_Pos) /*!< xPSR: N Mask */ #define xPSR_Z_Pos 30 /*!< xPSR: Z Position */ #define xPSR_Z_Msk (1UL << xPSR_Z_Pos) /*!< xPSR: Z Mask */ #define xPSR_C_Pos 29 /*!< xPSR: C Position */ #define xPSR_C_Msk (1UL << xPSR_C_Pos) /*!< xPSR: C Mask */ #define xPSR_V_Pos 28 /*!< xPSR: V Position */ #define xPSR_V_Msk (1UL << xPSR_V_Pos) /*!< xPSR: V Mask */ #define xPSR_T_Pos 24 /*!< xPSR: T Position */ #define xPSR_T_Msk (1UL << xPSR_T_Pos) /*!< xPSR: T Mask */ #define xPSR_ISR_Pos 0 /*!< xPSR: ISR Position */ #define xPSR_ISR_Msk (0x1FFUL /*<< xPSR_ISR_Pos*/) /*!< xPSR: ISR Mask */ /** \brief Union type to access the Control Registers (CONTROL). */ typedef union { struct { uint32_t nPRIV:1; /*!< bit: 0 Execution privilege in Thread mode */ uint32_t SPSEL:1; /*!< bit: 1 Stack to be used */ uint32_t _reserved1:30; /*!< bit: 2..31 Reserved */ } b; /*!< Structure used for bit access */ uint32_t w; /*!< Type used for word access */ } CONTROL_Type; /* CONTROL Register Definitions */ #define CONTROL_SPSEL_Pos 1 /*!< CONTROL: SPSEL Position */ #define CONTROL_SPSEL_Msk (1UL << CONTROL_SPSEL_Pos) /*!< CONTROL: SPSEL Mask */ #define CONTROL_nPRIV_Pos 0 /*!< CONTROL: nPRIV Position */ #define CONTROL_nPRIV_Msk (1UL /*<< CONTROL_nPRIV_Pos*/) /*!< CONTROL: nPRIV Mask */ /*@} end of group CMSIS_CORE */ /** \ingroup CMSIS_core_register \defgroup CMSIS_NVIC Nested Vectored Interrupt Controller (NVIC) \brief Type definitions for the NVIC Registers @{ */ /** \brief Structure type to access the Nested Vectored Interrupt Controller (NVIC). */ typedef struct { __IO uint32_t ISER[1]; /*!< Offset: 0x000 (R/W) Interrupt Set Enable Register */ uint32_t RESERVED0[31]; __IO uint32_t ICER[1]; /*!< Offset: 0x080 (R/W) Interrupt Clear Enable Register */ uint32_t RSERVED1[31]; __IO uint32_t ISPR[1]; /*!< Offset: 0x100 (R/W) Interrupt Set Pending Register */ uint32_t RESERVED2[31]; __IO uint32_t ICPR[1]; /*!< Offset: 0x180 (R/W) Interrupt Clear Pending Register */ uint32_t RESERVED3[31]; uint32_t RESERVED4[64]; __IO uint32_t IP[8]; /*!< Offset: 0x300 (R/W) Interrupt Priority Register */ } NVIC_Type; /*@} end of group CMSIS_NVIC */ /** \ingroup CMSIS_core_register \defgroup CMSIS_SCB System Control Block (SCB) \brief Type definitions for the System Control Block Registers @{ */ /** \brief Structure type to access the System Control Block (SCB). */ typedef struct { __I uint32_t CPUID; /*!< Offset: 0x000 (R/ ) CPUID Base Register */ __IO uint32_t ICSR; /*!< Offset: 0x004 (R/W) Interrupt Control and State Register */ #if (__VTOR_PRESENT == 1) __IO uint32_t VTOR; /*!< Offset: 0x008 (R/W) Vector Table Offset Register */ #else uint32_t RESERVED0; #endif __IO uint32_t AIRCR; /*!< Offset: 0x00C (R/W) Application Interrupt and Reset Control Register */ __IO uint32_t SCR; /*!< Offset: 0x010 (R/W) System Control Register */ __IO uint32_t CCR; /*!< Offset: 0x014 (R/W) Configuration Control Register */ uint32_t RESERVED1; __IO uint32_t SHP[2]; /*!< Offset: 0x01C (R/W) System Handlers Priority Registers. [0] is RESERVED */ __IO uint32_t SHCSR; /*!< Offset: 0x024 (R/W) System Handler Control and State Register */ } SCB_Type; /* SCB CPUID Register Definitions */ #define SCB_CPUID_IMPLEMENTER_Pos 24 /*!< SCB CPUID: IMPLEMENTER Position */ #define SCB_CPUID_IMPLEMENTER_Msk (0xFFUL << SCB_CPUID_IMPLEMENTER_Pos) /*!< SCB CPUID: IMPLEMENTER Mask */ #define SCB_CPUID_VARIANT_Pos 20 /*!< SCB CPUID: VARIANT Position */ #define SCB_CPUID_VARIANT_Msk (0xFUL << SCB_CPUID_VARIANT_Pos) /*!< SCB CPUID: VARIANT Mask */ #define SCB_CPUID_ARCHITECTURE_Pos 16 /*!< SCB CPUID: ARCHITECTURE Position */ #define SCB_CPUID_ARCHITECTURE_Msk (0xFUL << SCB_CPUID_ARCHITECTURE_Pos) /*!< SCB CPUID: ARCHITECTURE Mask */ #define SCB_CPUID_PARTNO_Pos 4 /*!< SCB CPUID: PARTNO Position */ #define SCB_CPUID_PARTNO_Msk (0xFFFUL << SCB_CPUID_PARTNO_Pos) /*!< SCB CPUID: PARTNO Mask */ #define SCB_CPUID_REVISION_Pos 0 /*!< SCB CPUID: REVISION Position */ #define SCB_CPUID_REVISION_Msk (0xFUL /*<< SCB_CPUID_REVISION_Pos*/) /*!< SCB CPUID: REVISION Mask */ /* SCB Interrupt Control State Register Definitions */ #define SCB_ICSR_NMIPENDSET_Pos 31 /*!< SCB ICSR: NMIPENDSET Position */ #define SCB_ICSR_NMIPENDSET_Msk (1UL << SCB_ICSR_NMIPENDSET_Pos) /*!< SCB ICSR: NMIPENDSET Mask */ #define SCB_ICSR_PENDSVSET_Pos 28 /*!< SCB ICSR: PENDSVSET Position */ #define SCB_ICSR_PENDSVSET_Msk (1UL << SCB_ICSR_PENDSVSET_Pos) /*!< SCB ICSR: PENDSVSET Mask */ #define SCB_ICSR_PENDSVCLR_Pos 27 /*!< SCB ICSR: PENDSVCLR Position */ #define SCB_ICSR_PENDSVCLR_Msk (1UL << SCB_ICSR_PENDSVCLR_Pos) /*!< SCB ICSR: PENDSVCLR Mask */ #define SCB_ICSR_PENDSTSET_Pos 26 /*!< SCB ICSR: PENDSTSET Position */ #define SCB_ICSR_PENDSTSET_Msk (1UL << SCB_ICSR_PENDSTSET_Pos) /*!< SCB ICSR: PENDSTSET Mask */ #define SCB_ICSR_PENDSTCLR_Pos 25 /*!< SCB ICSR: PENDSTCLR Position */ #define SCB_ICSR_PENDSTCLR_Msk (1UL << SCB_ICSR_PENDSTCLR_Pos) /*!< SCB ICSR: PENDSTCLR Mask */ #define SCB_ICSR_ISRPREEMPT_Pos 23 /*!< SCB ICSR: ISRPREEMPT Position */ #define SCB_ICSR_ISRPREEMPT_Msk (1UL << SCB_ICSR_ISRPREEMPT_Pos) /*!< SCB ICSR: ISRPREEMPT Mask */ #define SCB_ICSR_ISRPENDING_Pos 22 /*!< SCB ICSR: ISRPENDING Position */ #define SCB_ICSR_ISRPENDING_Msk (1UL << SCB_ICSR_ISRPENDING_Pos) /*!< SCB ICSR: ISRPENDING Mask */ #define SCB_ICSR_VECTPENDING_Pos 12 /*!< SCB ICSR: VECTPENDING Position */ #define SCB_ICSR_VECTPENDING_Msk (0x1FFUL << SCB_ICSR_VECTPENDING_Pos) /*!< SCB ICSR: VECTPENDING Mask */ #define SCB_ICSR_VECTACTIVE_Pos 0 /*!< SCB ICSR: VECTACTIVE Position */ #define SCB_ICSR_VECTACTIVE_Msk (0x1FFUL /*<< SCB_ICSR_VECTACTIVE_Pos*/) /*!< SCB ICSR: VECTACTIVE Mask */ #if (__VTOR_PRESENT == 1) /* SCB Interrupt Control State Register Definitions */ #define SCB_VTOR_TBLOFF_Pos 8 /*!< SCB VTOR: TBLOFF Position */ #define SCB_VTOR_TBLOFF_Msk (0xFFFFFFUL << SCB_VTOR_TBLOFF_Pos) /*!< SCB VTOR: TBLOFF Mask */ #endif /* SCB Application Interrupt and Reset Control Register Definitions */ #define SCB_AIRCR_VECTKEY_Pos 16 /*!< SCB AIRCR: VECTKEY Position */ #define SCB_AIRCR_VECTKEY_Msk (0xFFFFUL << SCB_AIRCR_VECTKEY_Pos) /*!< SCB AIRCR: VECTKEY Mask */ #define SCB_AIRCR_VECTKEYSTAT_Pos 16 /*!< SCB AIRCR: VECTKEYSTAT Position */ #define SCB_AIRCR_VECTKEYSTAT_Msk (0xFFFFUL << SCB_AIRCR_VECTKEYSTAT_Pos) /*!< SCB AIRCR: VECTKEYSTAT Mask */ #define SCB_AIRCR_ENDIANESS_Pos 15 /*!< SCB AIRCR: ENDIANESS Position */ #define SCB_AIRCR_ENDIANESS_Msk (1UL << SCB_AIRCR_ENDIANESS_Pos) /*!< SCB AIRCR: ENDIANESS Mask */ #define SCB_AIRCR_SYSRESETREQ_Pos 2 /*!< SCB AIRCR: SYSRESETREQ Position */ #define SCB_AIRCR_SYSRESETREQ_Msk (1UL << SCB_AIRCR_SYSRESETREQ_Pos) /*!< SCB AIRCR: SYSRESETREQ Mask */ #define SCB_AIRCR_VECTCLRACTIVE_Pos 1 /*!< SCB AIRCR: VECTCLRACTIVE Position */ #define SCB_AIRCR_VECTCLRACTIVE_Msk (1UL << SCB_AIRCR_VECTCLRACTIVE_Pos) /*!< SCB AIRCR: VECTCLRACTIVE Mask */ /* SCB System Control Register Definitions */ #define SCB_SCR_SEVONPEND_Pos 4 /*!< SCB SCR: SEVONPEND Position */ #define SCB_SCR_SEVONPEND_Msk (1UL << SCB_SCR_SEVONPEND_Pos) /*!< SCB SCR: SEVONPEND Mask */ #define SCB_SCR_SLEEPDEEP_Pos 2 /*!< SCB SCR: SLEEPDEEP Position */ #define SCB_SCR_SLEEPDEEP_Msk (1UL << SCB_SCR_SLEEPDEEP_Pos) /*!< SCB SCR: SLEEPDEEP Mask */ #define SCB_SCR_SLEEPONEXIT_Pos 1 /*!< SCB SCR: SLEEPONEXIT Position */ #define SCB_SCR_SLEEPONEXIT_Msk (1UL << SCB_SCR_SLEEPONEXIT_Pos) /*!< SCB SCR: SLEEPONEXIT Mask */ /* SCB Configuration Control Register Definitions */ #define SCB_CCR_STKALIGN_Pos 9 /*!< SCB CCR: STKALIGN Position */ #define SCB_CCR_STKALIGN_Msk (1UL << SCB_CCR_STKALIGN_Pos) /*!< SCB CCR: STKALIGN Mask */ #define SCB_CCR_UNALIGN_TRP_Pos 3 /*!< SCB CCR: UNALIGN_TRP Position */ #define SCB_CCR_UNALIGN_TRP_Msk (1UL << SCB_CCR_UNALIGN_TRP_Pos) /*!< SCB CCR: UNALIGN_TRP Mask */ /* SCB System Handler Control and State Register Definitions */ #define SCB_SHCSR_SVCALLPENDED_Pos 15 /*!< SCB SHCSR: SVCALLPENDED Position */ #define SCB_SHCSR_SVCALLPENDED_Msk (1UL << SCB_SHCSR_SVCALLPENDED_Pos) /*!< SCB SHCSR: SVCALLPENDED Mask */ /*@} end of group CMSIS_SCB */ /** \ingroup CMSIS_core_register \defgroup CMSIS_SysTick System Tick Timer (SysTick) \brief Type definitions for the System Timer Registers. @{ */ /** \brief Structure type to access the System Timer (SysTick). */ typedef struct { __IO uint32_t CTRL; /*!< Offset: 0x000 (R/W) SysTick Control and Status Register */ __IO uint32_t LOAD; /*!< Offset: 0x004 (R/W) SysTick Reload Value Register */ __IO uint32_t VAL; /*!< Offset: 0x008 (R/W) SysTick Current Value Register */ __I uint32_t CALIB; /*!< Offset: 0x00C (R/ ) SysTick Calibration Register */ } SysTick_Type; /* SysTick Control / Status Register Definitions */ #define SysTick_CTRL_COUNTFLAG_Pos 16 /*!< SysTick CTRL: COUNTFLAG Position */ #define SysTick_CTRL_COUNTFLAG_Msk (1UL << SysTick_CTRL_COUNTFLAG_Pos) /*!< SysTick CTRL: COUNTFLAG Mask */ #define SysTick_CTRL_CLKSOURCE_Pos 2 /*!< SysTick CTRL: CLKSOURCE Position */ #define SysTick_CTRL_CLKSOURCE_Msk (1UL << SysTick_CTRL_CLKSOURCE_Pos) /*!< SysTick CTRL: CLKSOURCE Mask */ #define SysTick_CTRL_TICKINT_Pos 1 /*!< SysTick CTRL: TICKINT Position */ #define SysTick_CTRL_TICKINT_Msk (1UL << SysTick_CTRL_TICKINT_Pos) /*!< SysTick CTRL: TICKINT Mask */ #define SysTick_CTRL_ENABLE_Pos 0 /*!< SysTick CTRL: ENABLE Position */ #define SysTick_CTRL_ENABLE_Msk (1UL /*<< SysTick_CTRL_ENABLE_Pos*/) /*!< SysTick CTRL: ENABLE Mask */ /* SysTick Reload Register Definitions */ #define SysTick_LOAD_RELOAD_Pos 0 /*!< SysTick LOAD: RELOAD Position */ #define SysTick_LOAD_RELOAD_Msk (0xFFFFFFUL /*<< SysTick_LOAD_RELOAD_Pos*/) /*!< SysTick LOAD: RELOAD Mask */ /* SysTick Current Register Definitions */ #define SysTick_VAL_CURRENT_Pos 0 /*!< SysTick VAL: CURRENT Position */ #define SysTick_VAL_CURRENT_Msk (0xFFFFFFUL /*<< SysTick_VAL_CURRENT_Pos*/) /*!< SysTick VAL: CURRENT Mask */ /* SysTick Calibration Register Definitions */ #define SysTick_CALIB_NOREF_Pos 31 /*!< SysTick CALIB: NOREF Position */ #define SysTick_CALIB_NOREF_Msk (1UL << SysTick_CALIB_NOREF_Pos) /*!< SysTick CALIB: NOREF Mask */ #define SysTick_CALIB_SKEW_Pos 30 /*!< SysTick CALIB: SKEW Position */ #define SysTick_CALIB_SKEW_Msk (1UL << SysTick_CALIB_SKEW_Pos) /*!< SysTick CALIB: SKEW Mask */ #define SysTick_CALIB_TENMS_Pos 0 /*!< SysTick CALIB: TENMS Position */ #define SysTick_CALIB_TENMS_Msk (0xFFFFFFUL /*<< SysTick_CALIB_TENMS_Pos*/) /*!< SysTick CALIB: TENMS Mask */ /*@} end of group CMSIS_SysTick */ #if (__MPU_PRESENT == 1) /** \ingroup CMSIS_core_register \defgroup CMSIS_MPU Memory Protection Unit (MPU) \brief Type definitions for the Memory Protection Unit (MPU) @{ */ /** \brief Structure type to access the Memory Protection Unit (MPU). */ typedef struct { __I uint32_t TYPE; /*!< Offset: 0x000 (R/ ) MPU Type Register */ __IO uint32_t CTRL; /*!< Offset: 0x004 (R/W) MPU Control Register */ __IO uint32_t RNR; /*!< Offset: 0x008 (R/W) MPU Region RNRber Register */ __IO uint32_t RBAR; /*!< Offset: 0x00C (R/W) MPU Region Base Address Register */ __IO uint32_t RASR; /*!< Offset: 0x010 (R/W) MPU Region Attribute and Size Register */ } MPU_Type; /* MPU Type Register */ #define MPU_TYPE_IREGION_Pos 16 /*!< MPU TYPE: IREGION Position */ #define MPU_TYPE_IREGION_Msk (0xFFUL << MPU_TYPE_IREGION_Pos) /*!< MPU TYPE: IREGION Mask */ #define MPU_TYPE_DREGION_Pos 8 /*!< MPU TYPE: DREGION Position */ #define MPU_TYPE_DREGION_Msk (0xFFUL << MPU_TYPE_DREGION_Pos) /*!< MPU TYPE: DREGION Mask */ #define MPU_TYPE_SEPARATE_Pos 0 /*!< MPU TYPE: SEPARATE Position */ #define MPU_TYPE_SEPARATE_Msk (1UL /*<< MPU_TYPE_SEPARATE_Pos*/) /*!< MPU TYPE: SEPARATE Mask */ /* MPU Control Register */ #define MPU_CTRL_PRIVDEFENA_Pos 2 /*!< MPU CTRL: PRIVDEFENA Position */ #define MPU_CTRL_PRIVDEFENA_Msk (1UL << MPU_CTRL_PRIVDEFENA_Pos) /*!< MPU CTRL: PRIVDEFENA Mask */ #define MPU_CTRL_HFNMIENA_Pos 1 /*!< MPU CTRL: HFNMIENA Position */ #define MPU_CTRL_HFNMIENA_Msk (1UL << MPU_CTRL_HFNMIENA_Pos) /*!< MPU CTRL: HFNMIENA Mask */ #define MPU_CTRL_ENABLE_Pos 0 /*!< MPU CTRL: ENABLE Position */ #define MPU_CTRL_ENABLE_Msk (1UL /*<< MPU_CTRL_ENABLE_Pos*/) /*!< MPU CTRL: ENABLE Mask */ /* MPU Region Number Register */ #define MPU_RNR_REGION_Pos 0 /*!< MPU RNR: REGION Position */ #define MPU_RNR_REGION_Msk (0xFFUL /*<< MPU_RNR_REGION_Pos*/) /*!< MPU RNR: REGION Mask */ /* MPU Region Base Address Register */ #define MPU_RBAR_ADDR_Pos 8 /*!< MPU RBAR: ADDR Position */ #define MPU_RBAR_ADDR_Msk (0xFFFFFFUL << MPU_RBAR_ADDR_Pos) /*!< MPU RBAR: ADDR Mask */ #define MPU_RBAR_VALID_Pos 4 /*!< MPU RBAR: VALID Position */ #define MPU_RBAR_VALID_Msk (1UL << MPU_RBAR_VALID_Pos) /*!< MPU RBAR: VALID Mask */ #define MPU_RBAR_REGION_Pos 0 /*!< MPU RBAR: REGION Position */ #define MPU_RBAR_REGION_Msk (0xFUL /*<< MPU_RBAR_REGION_Pos*/) /*!< MPU RBAR: REGION Mask */ /* MPU Region Attribute and Size Register */ #define MPU_RASR_ATTRS_Pos 16 /*!< MPU RASR: MPU Region Attribute field Position */ #define MPU_RASR_ATTRS_Msk (0xFFFFUL << MPU_RASR_ATTRS_Pos) /*!< MPU RASR: MPU Region Attribute field Mask */ #define MPU_RASR_XN_Pos 28 /*!< MPU RASR: ATTRS.XN Position */ #define MPU_RASR_XN_Msk (1UL << MPU_RASR_XN_Pos) /*!< MPU RASR: ATTRS.XN Mask */ #define MPU_RASR_AP_Pos 24 /*!< MPU RASR: ATTRS.AP Position */ #define MPU_RASR_AP_Msk (0x7UL << MPU_RASR_AP_Pos) /*!< MPU RASR: ATTRS.AP Mask */ #define MPU_RASR_TEX_Pos 19 /*!< MPU RASR: ATTRS.TEX Position */ #define MPU_RASR_TEX_Msk (0x7UL << MPU_RASR_TEX_Pos) /*!< MPU RASR: ATTRS.TEX Mask */ #define MPU_RASR_S_Pos 18 /*!< MPU RASR: ATTRS.S Position */ #define MPU_RASR_S_Msk (1UL << MPU_RASR_S_Pos) /*!< MPU RASR: ATTRS.S Mask */ #define MPU_RASR_C_Pos 17 /*!< MPU RASR: ATTRS.C Position */ #define MPU_RASR_C_Msk (1UL << MPU_RASR_C_Pos) /*!< MPU RASR: ATTRS.C Mask */ #define MPU_RASR_B_Pos 16 /*!< MPU RASR: ATTRS.B Position */ #define MPU_RASR_B_Msk (1UL << MPU_RASR_B_Pos) /*!< MPU RASR: ATTRS.B Mask */ #define MPU_RASR_SRD_Pos 8 /*!< MPU RASR: Sub-Region Disable Position */ #define MPU_RASR_SRD_Msk (0xFFUL << MPU_RASR_SRD_Pos) /*!< MPU RASR: Sub-Region Disable Mask */ #define MPU_RASR_SIZE_Pos 1 /*!< MPU RASR: Region Size Field Position */ #define MPU_RASR_SIZE_Msk (0x1FUL << MPU_RASR_SIZE_Pos) /*!< MPU RASR: Region Size Field Mask */ #define MPU_RASR_ENABLE_Pos 0 /*!< MPU RASR: Region enable bit Position */ #define MPU_RASR_ENABLE_Msk (1UL /*<< MPU_RASR_ENABLE_Pos*/) /*!< MPU RASR: Region enable bit Disable Mask */ /*@} end of group CMSIS_MPU */ #endif /** \ingroup CMSIS_core_register \defgroup CMSIS_CoreDebug Core Debug Registers (CoreDebug) \brief Cortex-M0+ Core Debug Registers (DCB registers, SHCSR, and DFSR) are only accessible over DAP and not via processor. Therefore they are not covered by the Cortex-M0 header file. @{ */ /*@} end of group CMSIS_CoreDebug */ /** \ingroup CMSIS_core_register \defgroup CMSIS_core_base Core Definitions \brief Definitions for base addresses, unions, and structures. @{ */ /* Memory mapping of Cortex-M0+ Hardware */ #define SCS_BASE (0xE000E000UL) /*!< System Control Space Base Address */ #define SysTick_BASE (SCS_BASE + 0x0010UL) /*!< SysTick Base Address */ #define NVIC_BASE (SCS_BASE + 0x0100UL) /*!< NVIC Base Address */ #define SCB_BASE (SCS_BASE + 0x0D00UL) /*!< System Control Block Base Address */ #define SCB ((SCB_Type *) SCB_BASE ) /*!< SCB configuration struct */ #define SysTick ((SysTick_Type *) SysTick_BASE ) /*!< SysTick configuration struct */ #define NVIC ((NVIC_Type *) NVIC_BASE ) /*!< NVIC configuration struct */ #if (__MPU_PRESENT == 1) #define MPU_BASE (SCS_BASE + 0x0D90UL) /*!< Memory Protection Unit */ #define MPU ((MPU_Type *) MPU_BASE ) /*!< Memory Protection Unit */ #endif /*@} */ /******************************************************************************* * Hardware Abstraction Layer Core Function Interface contains: - Core NVIC Functions - Core SysTick Functions - Core Register Access Functions ******************************************************************************/ /** \defgroup CMSIS_Core_FunctionInterface Functions and Instructions Reference */ /* ########################## NVIC functions #################################### */ /** \ingroup CMSIS_Core_FunctionInterface \defgroup CMSIS_Core_NVICFunctions NVIC Functions \brief Functions that manage interrupts and exceptions via the NVIC. @{ */ /* Interrupt Priorities are WORD accessible only under ARMv6M */ /* The following MACROS handle generation of the register offset and byte masks */ #define _BIT_SHIFT(IRQn) ( ((((uint32_t)(int32_t)(IRQn)) ) & 0x03UL) * 8UL) #define _SHP_IDX(IRQn) ( (((((uint32_t)(int32_t)(IRQn)) & 0x0FUL)-8UL) >> 2UL) ) #define _IP_IDX(IRQn) ( (((uint32_t)(int32_t)(IRQn)) >> 2UL) ) /** \brief Enable External Interrupt The function enables a device-specific interrupt in the NVIC interrupt controller. \param [in] IRQn External interrupt number. Value cannot be negative. */ __STATIC_INLINE void NVIC_EnableIRQ(IRQn_Type IRQn) { NVIC->ISER[0] = (uint32_t)(1UL << (((uint32_t)(int32_t)IRQn) & 0x1FUL)); } /** \brief Disable External Interrupt The function disables a device-specific interrupt in the NVIC interrupt controller. \param [in] IRQn External interrupt number. Value cannot be negative. */ __STATIC_INLINE void NVIC_DisableIRQ(IRQn_Type IRQn) { NVIC->ICER[0] = (uint32_t)(1UL << (((uint32_t)(int32_t)IRQn) & 0x1FUL)); } /** \brief Get Pending Interrupt The function reads the pending register in the NVIC and returns the pending bit for the specified interrupt. \param [in] IRQn Interrupt number. \return 0 Interrupt status is not pending. \return 1 Interrupt status is pending. */ __STATIC_INLINE uint32_t NVIC_GetPendingIRQ(IRQn_Type IRQn) { return((uint32_t)(((NVIC->ISPR[0] & (1UL << (((uint32_t)(int32_t)IRQn) & 0x1FUL))) != 0UL) ? 1UL : 0UL)); } /** \brief Set Pending Interrupt The function sets the pending bit of an external interrupt. \param [in] IRQn Interrupt number. Value cannot be negative. */ __STATIC_INLINE void NVIC_SetPendingIRQ(IRQn_Type IRQn) { NVIC->ISPR[0] = (uint32_t)(1UL << (((uint32_t)(int32_t)IRQn) & 0x1FUL)); } /** \brief Clear Pending Interrupt The function clears the pending bit of an external interrupt. \param [in] IRQn External interrupt number. Value cannot be negative. */ __STATIC_INLINE void NVIC_ClearPendingIRQ(IRQn_Type IRQn) { NVIC->ICPR[0] = (uint32_t)(1UL << (((uint32_t)(int32_t)IRQn) & 0x1FUL)); } /** \brief Set Interrupt Priority The function sets the priority of an interrupt. \note The priority cannot be set for every core interrupt. \param [in] IRQn Interrupt number. \param [in] priority Priority to set. */ __STATIC_INLINE void NVIC_SetPriority(IRQn_Type IRQn, uint32_t priority) { if((int32_t)(IRQn) < 0) { SCB->SHP[_SHP_IDX(IRQn)] = ((uint32_t)(SCB->SHP[_SHP_IDX(IRQn)] & ~(0xFFUL << _BIT_SHIFT(IRQn))) | (((priority << (8 - __NVIC_PRIO_BITS)) & (uint32_t)0xFFUL) << _BIT_SHIFT(IRQn))); } else { NVIC->IP[_IP_IDX(IRQn)] = ((uint32_t)(NVIC->IP[_IP_IDX(IRQn)] & ~(0xFFUL << _BIT_SHIFT(IRQn))) | (((priority << (8 - __NVIC_PRIO_BITS)) & (uint32_t)0xFFUL) << _BIT_SHIFT(IRQn))); } } /** \brief Get Interrupt Priority The function reads the priority of an interrupt. The interrupt number can be positive to specify an external (device specific) interrupt, or negative to specify an internal (core) interrupt. \param [in] IRQn Interrupt number. \return Interrupt Priority. Value is aligned automatically to the implemented priority bits of the microcontroller. */ __STATIC_INLINE uint32_t NVIC_GetPriority(IRQn_Type IRQn) { if((int32_t)(IRQn) < 0) { return((uint32_t)(((SCB->SHP[_SHP_IDX(IRQn)] >> _BIT_SHIFT(IRQn) ) & (uint32_t)0xFFUL) >> (8 - __NVIC_PRIO_BITS))); } else { return((uint32_t)(((NVIC->IP[ _IP_IDX(IRQn)] >> _BIT_SHIFT(IRQn) ) & (uint32_t)0xFFUL) >> (8 - __NVIC_PRIO_BITS))); } } /** \brief System Reset The function initiates a system reset request to reset the MCU. */ __STATIC_INLINE void NVIC_SystemReset(void) { __DSB(); /* Ensure all outstanding memory accesses included buffered write are completed before reset */ SCB->AIRCR = ((0x5FAUL << SCB_AIRCR_VECTKEY_Pos) | SCB_AIRCR_SYSRESETREQ_Msk); __DSB(); /* Ensure completion of memory access */ while(1) { __NOP(); } /* wait until reset */ } /*@} end of CMSIS_Core_NVICFunctions */ /* ################################## SysTick function ############################################ */ /** \ingroup CMSIS_Core_FunctionInterface \defgroup CMSIS_Core_SysTickFunctions SysTick Functions \brief Functions that configure the System. @{ */ #if (__Vendor_SysTickConfig == 0) /** \brief System Tick Configuration The function initializes the System Timer and its interrupt, and starts the System Tick Timer. Counter is in free running mode to generate periodic interrupts. \param [in] ticks Number of ticks between two interrupts. \return 0 Function succeeded. \return 1 Function failed. \note When the variable __Vendor_SysTickConfig is set to 1, then the function SysTick_Config is not included. In this case, the file device.h must contain a vendor-specific implementation of this function. */ __STATIC_INLINE uint32_t SysTick_Config(uint32_t ticks) { if ((ticks - 1UL) > SysTick_LOAD_RELOAD_Msk) {return (1UL);} /* Reload value impossible */ SysTick->LOAD = (uint32_t)(ticks - 1UL); /* set reload register */ NVIC_SetPriority (SysTick_IRQn, (1UL << __NVIC_PRIO_BITS) - 1UL); /* set Priority for Systick Interrupt */ SysTick->VAL = 0UL; /* Load the SysTick Counter Value */ SysTick->CTRL = SysTick_CTRL_CLKSOURCE_Msk | SysTick_CTRL_TICKINT_Msk | SysTick_CTRL_ENABLE_Msk; /* Enable SysTick IRQ and SysTick Timer */ return (0UL); /* Function successful */ } #endif /*@} end of CMSIS_Core_SysTickFunctions */ #ifdef __cplusplus } #endif #endif /* __CORE_CM0PLUS_H_DEPENDANT */ #endif /* __CMSIS_GENERIC */ ================================================ FILE: Zelig/mbed/TARGET_NUCLEO_F401RE/core_cm3.h ================================================ /**************************************************************************//** * @file core_cm3.h * @brief CMSIS Cortex-M3 Core Peripheral Access Layer Header File * @version V4.10 * @date 18. March 2015 * * @note * ******************************************************************************/ /* Copyright (c) 2009 - 2015 ARM LIMITED All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: - Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. - Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. - Neither the name of ARM 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 COPYRIGHT HOLDERS AND 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. ---------------------------------------------------------------------------*/ #if defined ( __ICCARM__ ) #pragma system_include /* treat file as system include file for MISRA check */ #endif #ifndef __CORE_CM3_H_GENERIC #define __CORE_CM3_H_GENERIC #ifdef __cplusplus extern "C" { #endif /** \page CMSIS_MISRA_Exceptions MISRA-C:2004 Compliance Exceptions CMSIS violates the following MISRA-C:2004 rules: \li Required Rule 8.5, object/function definition in header file.
Function definitions in header files are used to allow 'inlining'. \li Required Rule 18.4, declaration of union type or object of union type: '{...}'.
Unions are used for effective representation of core registers. \li Advisory Rule 19.7, Function-like macro defined.
Function-like macros are used to allow more efficient code. */ /******************************************************************************* * CMSIS definitions ******************************************************************************/ /** \ingroup Cortex_M3 @{ */ /* CMSIS CM3 definitions */ #define __CM3_CMSIS_VERSION_MAIN (0x04) /*!< [31:16] CMSIS HAL main version */ #define __CM3_CMSIS_VERSION_SUB (0x00) /*!< [15:0] CMSIS HAL sub version */ #define __CM3_CMSIS_VERSION ((__CM3_CMSIS_VERSION_MAIN << 16) | \ __CM3_CMSIS_VERSION_SUB ) /*!< CMSIS HAL version number */ #define __CORTEX_M (0x03) /*!< Cortex-M Core */ #if defined ( __CC_ARM ) #define __ASM __asm /*!< asm keyword for ARM Compiler */ #define __INLINE __inline /*!< inline keyword for ARM Compiler */ #define __STATIC_INLINE static __inline #elif defined ( __GNUC__ ) #define __ASM __asm /*!< asm keyword for GNU Compiler */ #define __INLINE inline /*!< inline keyword for GNU Compiler */ #define __STATIC_INLINE static inline #elif defined ( __ICCARM__ ) #define __ASM __asm /*!< asm keyword for IAR Compiler */ #define __INLINE inline /*!< inline keyword for IAR Compiler. Only available in High optimization mode! */ #define __STATIC_INLINE static inline #elif defined ( __TMS470__ ) #define __ASM __asm /*!< asm keyword for TI CCS Compiler */ #define __STATIC_INLINE static inline #elif defined ( __TASKING__ ) #define __ASM __asm /*!< asm keyword for TASKING Compiler */ #define __INLINE inline /*!< inline keyword for TASKING Compiler */ #define __STATIC_INLINE static inline #elif defined ( __CSMC__ ) #define __packed #define __ASM _asm /*!< asm keyword for COSMIC Compiler */ #define __INLINE inline /*use -pc99 on compile line !< inline keyword for COSMIC Compiler */ #define __STATIC_INLINE static inline #endif /** __FPU_USED indicates whether an FPU is used or not. This core does not support an FPU at all */ #define __FPU_USED 0 #if defined ( __CC_ARM ) #if defined __TARGET_FPU_VFP #warning "Compiler generates FPU instructions for a device without an FPU (check __FPU_PRESENT)" #endif #elif defined ( __GNUC__ ) #if defined (__VFP_FP__) && !defined(__SOFTFP__) #warning "Compiler generates FPU instructions for a device without an FPU (check __FPU_PRESENT)" #endif #elif defined ( __ICCARM__ ) #if defined __ARMVFP__ #warning "Compiler generates FPU instructions for a device without an FPU (check __FPU_PRESENT)" #endif #elif defined ( __TMS470__ ) #if defined __TI__VFP_SUPPORT____ #warning "Compiler generates FPU instructions for a device without an FPU (check __FPU_PRESENT)" #endif #elif defined ( __TASKING__ ) #if defined __FPU_VFP__ #error "Compiler generates FPU instructions for a device without an FPU (check __FPU_PRESENT)" #endif #elif defined ( __CSMC__ ) /* Cosmic */ #if ( __CSMC__ & 0x400) // FPU present for parser #error "Compiler generates FPU instructions for a device without an FPU (check __FPU_PRESENT)" #endif #endif #include /* standard types definitions */ #include /* Core Instruction Access */ #include /* Core Function Access */ #ifdef __cplusplus } #endif #endif /* __CORE_CM3_H_GENERIC */ #ifndef __CMSIS_GENERIC #ifndef __CORE_CM3_H_DEPENDANT #define __CORE_CM3_H_DEPENDANT #ifdef __cplusplus extern "C" { #endif /* check device defines and use defaults */ #if defined __CHECK_DEVICE_DEFINES #ifndef __CM3_REV #define __CM3_REV 0x0200 #warning "__CM3_REV not defined in device header file; using default!" #endif #ifndef __MPU_PRESENT #define __MPU_PRESENT 0 #warning "__MPU_PRESENT not defined in device header file; using default!" #endif #ifndef __NVIC_PRIO_BITS #define __NVIC_PRIO_BITS 4 #warning "__NVIC_PRIO_BITS not defined in device header file; using default!" #endif #ifndef __Vendor_SysTickConfig #define __Vendor_SysTickConfig 0 #warning "__Vendor_SysTickConfig not defined in device header file; using default!" #endif #endif /* IO definitions (access restrictions to peripheral registers) */ /** \defgroup CMSIS_glob_defs CMSIS Global Defines IO Type Qualifiers are used \li to specify the access to peripheral variables. \li for automatic generation of peripheral register debug information. */ #ifdef __cplusplus #define __I volatile /*!< Defines 'read only' permissions */ #else #define __I volatile const /*!< Defines 'read only' permissions */ #endif #define __O volatile /*!< Defines 'write only' permissions */ #define __IO volatile /*!< Defines 'read / write' permissions */ /*@} end of group Cortex_M3 */ /******************************************************************************* * Register Abstraction Core Register contain: - Core Register - Core NVIC Register - Core SCB Register - Core SysTick Register - Core Debug Register - Core MPU Register ******************************************************************************/ /** \defgroup CMSIS_core_register Defines and Type Definitions \brief Type definitions and defines for Cortex-M processor based devices. */ /** \ingroup CMSIS_core_register \defgroup CMSIS_CORE Status and Control Registers \brief Core Register type definitions. @{ */ /** \brief Union type to access the Application Program Status Register (APSR). */ typedef union { struct { uint32_t _reserved0:27; /*!< bit: 0..26 Reserved */ uint32_t Q:1; /*!< bit: 27 Saturation condition flag */ uint32_t V:1; /*!< bit: 28 Overflow condition code flag */ uint32_t C:1; /*!< bit: 29 Carry condition code flag */ uint32_t Z:1; /*!< bit: 30 Zero condition code flag */ uint32_t N:1; /*!< bit: 31 Negative condition code flag */ } b; /*!< Structure used for bit access */ uint32_t w; /*!< Type used for word access */ } APSR_Type; /* APSR Register Definitions */ #define APSR_N_Pos 31 /*!< APSR: N Position */ #define APSR_N_Msk (1UL << APSR_N_Pos) /*!< APSR: N Mask */ #define APSR_Z_Pos 30 /*!< APSR: Z Position */ #define APSR_Z_Msk (1UL << APSR_Z_Pos) /*!< APSR: Z Mask */ #define APSR_C_Pos 29 /*!< APSR: C Position */ #define APSR_C_Msk (1UL << APSR_C_Pos) /*!< APSR: C Mask */ #define APSR_V_Pos 28 /*!< APSR: V Position */ #define APSR_V_Msk (1UL << APSR_V_Pos) /*!< APSR: V Mask */ #define APSR_Q_Pos 27 /*!< APSR: Q Position */ #define APSR_Q_Msk (1UL << APSR_Q_Pos) /*!< APSR: Q Mask */ /** \brief Union type to access the Interrupt Program Status Register (IPSR). */ typedef union { struct { uint32_t ISR:9; /*!< bit: 0.. 8 Exception number */ uint32_t _reserved0:23; /*!< bit: 9..31 Reserved */ } b; /*!< Structure used for bit access */ uint32_t w; /*!< Type used for word access */ } IPSR_Type; /* IPSR Register Definitions */ #define IPSR_ISR_Pos 0 /*!< IPSR: ISR Position */ #define IPSR_ISR_Msk (0x1FFUL /*<< IPSR_ISR_Pos*/) /*!< IPSR: ISR Mask */ /** \brief Union type to access the Special-Purpose Program Status Registers (xPSR). */ typedef union { struct { uint32_t ISR:9; /*!< bit: 0.. 8 Exception number */ uint32_t _reserved0:15; /*!< bit: 9..23 Reserved */ uint32_t T:1; /*!< bit: 24 Thumb bit (read 0) */ uint32_t IT:2; /*!< bit: 25..26 saved IT state (read 0) */ uint32_t Q:1; /*!< bit: 27 Saturation condition flag */ uint32_t V:1; /*!< bit: 28 Overflow condition code flag */ uint32_t C:1; /*!< bit: 29 Carry condition code flag */ uint32_t Z:1; /*!< bit: 30 Zero condition code flag */ uint32_t N:1; /*!< bit: 31 Negative condition code flag */ } b; /*!< Structure used for bit access */ uint32_t w; /*!< Type used for word access */ } xPSR_Type; /* xPSR Register Definitions */ #define xPSR_N_Pos 31 /*!< xPSR: N Position */ #define xPSR_N_Msk (1UL << xPSR_N_Pos) /*!< xPSR: N Mask */ #define xPSR_Z_Pos 30 /*!< xPSR: Z Position */ #define xPSR_Z_Msk (1UL << xPSR_Z_Pos) /*!< xPSR: Z Mask */ #define xPSR_C_Pos 29 /*!< xPSR: C Position */ #define xPSR_C_Msk (1UL << xPSR_C_Pos) /*!< xPSR: C Mask */ #define xPSR_V_Pos 28 /*!< xPSR: V Position */ #define xPSR_V_Msk (1UL << xPSR_V_Pos) /*!< xPSR: V Mask */ #define xPSR_Q_Pos 27 /*!< xPSR: Q Position */ #define xPSR_Q_Msk (1UL << xPSR_Q_Pos) /*!< xPSR: Q Mask */ #define xPSR_IT_Pos 25 /*!< xPSR: IT Position */ #define xPSR_IT_Msk (3UL << xPSR_IT_Pos) /*!< xPSR: IT Mask */ #define xPSR_T_Pos 24 /*!< xPSR: T Position */ #define xPSR_T_Msk (1UL << xPSR_T_Pos) /*!< xPSR: T Mask */ #define xPSR_ISR_Pos 0 /*!< xPSR: ISR Position */ #define xPSR_ISR_Msk (0x1FFUL /*<< xPSR_ISR_Pos*/) /*!< xPSR: ISR Mask */ /** \brief Union type to access the Control Registers (CONTROL). */ typedef union { struct { uint32_t nPRIV:1; /*!< bit: 0 Execution privilege in Thread mode */ uint32_t SPSEL:1; /*!< bit: 1 Stack to be used */ uint32_t _reserved1:30; /*!< bit: 2..31 Reserved */ } b; /*!< Structure used for bit access */ uint32_t w; /*!< Type used for word access */ } CONTROL_Type; /* CONTROL Register Definitions */ #define CONTROL_SPSEL_Pos 1 /*!< CONTROL: SPSEL Position */ #define CONTROL_SPSEL_Msk (1UL << CONTROL_SPSEL_Pos) /*!< CONTROL: SPSEL Mask */ #define CONTROL_nPRIV_Pos 0 /*!< CONTROL: nPRIV Position */ #define CONTROL_nPRIV_Msk (1UL /*<< CONTROL_nPRIV_Pos*/) /*!< CONTROL: nPRIV Mask */ /*@} end of group CMSIS_CORE */ /** \ingroup CMSIS_core_register \defgroup CMSIS_NVIC Nested Vectored Interrupt Controller (NVIC) \brief Type definitions for the NVIC Registers @{ */ /** \brief Structure type to access the Nested Vectored Interrupt Controller (NVIC). */ typedef struct { __IO uint32_t ISER[8]; /*!< Offset: 0x000 (R/W) Interrupt Set Enable Register */ uint32_t RESERVED0[24]; __IO uint32_t ICER[8]; /*!< Offset: 0x080 (R/W) Interrupt Clear Enable Register */ uint32_t RSERVED1[24]; __IO uint32_t ISPR[8]; /*!< Offset: 0x100 (R/W) Interrupt Set Pending Register */ uint32_t RESERVED2[24]; __IO uint32_t ICPR[8]; /*!< Offset: 0x180 (R/W) Interrupt Clear Pending Register */ uint32_t RESERVED3[24]; __IO uint32_t IABR[8]; /*!< Offset: 0x200 (R/W) Interrupt Active bit Register */ uint32_t RESERVED4[56]; __IO uint8_t IP[240]; /*!< Offset: 0x300 (R/W) Interrupt Priority Register (8Bit wide) */ uint32_t RESERVED5[644]; __O uint32_t STIR; /*!< Offset: 0xE00 ( /W) Software Trigger Interrupt Register */ } NVIC_Type; /* Software Triggered Interrupt Register Definitions */ #define NVIC_STIR_INTID_Pos 0 /*!< STIR: INTLINESNUM Position */ #define NVIC_STIR_INTID_Msk (0x1FFUL /*<< NVIC_STIR_INTID_Pos*/) /*!< STIR: INTLINESNUM Mask */ /*@} end of group CMSIS_NVIC */ /** \ingroup CMSIS_core_register \defgroup CMSIS_SCB System Control Block (SCB) \brief Type definitions for the System Control Block Registers @{ */ /** \brief Structure type to access the System Control Block (SCB). */ typedef struct { __I uint32_t CPUID; /*!< Offset: 0x000 (R/ ) CPUID Base Register */ __IO uint32_t ICSR; /*!< Offset: 0x004 (R/W) Interrupt Control and State Register */ __IO uint32_t VTOR; /*!< Offset: 0x008 (R/W) Vector Table Offset Register */ __IO uint32_t AIRCR; /*!< Offset: 0x00C (R/W) Application Interrupt and Reset Control Register */ __IO uint32_t SCR; /*!< Offset: 0x010 (R/W) System Control Register */ __IO uint32_t CCR; /*!< Offset: 0x014 (R/W) Configuration Control Register */ __IO uint8_t SHP[12]; /*!< Offset: 0x018 (R/W) System Handlers Priority Registers (4-7, 8-11, 12-15) */ __IO uint32_t SHCSR; /*!< Offset: 0x024 (R/W) System Handler Control and State Register */ __IO uint32_t CFSR; /*!< Offset: 0x028 (R/W) Configurable Fault Status Register */ __IO uint32_t HFSR; /*!< Offset: 0x02C (R/W) HardFault Status Register */ __IO uint32_t DFSR; /*!< Offset: 0x030 (R/W) Debug Fault Status Register */ __IO uint32_t MMFAR; /*!< Offset: 0x034 (R/W) MemManage Fault Address Register */ __IO uint32_t BFAR; /*!< Offset: 0x038 (R/W) BusFault Address Register */ __IO uint32_t AFSR; /*!< Offset: 0x03C (R/W) Auxiliary Fault Status Register */ __I uint32_t PFR[2]; /*!< Offset: 0x040 (R/ ) Processor Feature Register */ __I uint32_t DFR; /*!< Offset: 0x048 (R/ ) Debug Feature Register */ __I uint32_t ADR; /*!< Offset: 0x04C (R/ ) Auxiliary Feature Register */ __I uint32_t MMFR[4]; /*!< Offset: 0x050 (R/ ) Memory Model Feature Register */ __I uint32_t ISAR[5]; /*!< Offset: 0x060 (R/ ) Instruction Set Attributes Register */ uint32_t RESERVED0[5]; __IO uint32_t CPACR; /*!< Offset: 0x088 (R/W) Coprocessor Access Control Register */ } SCB_Type; /* SCB CPUID Register Definitions */ #define SCB_CPUID_IMPLEMENTER_Pos 24 /*!< SCB CPUID: IMPLEMENTER Position */ #define SCB_CPUID_IMPLEMENTER_Msk (0xFFUL << SCB_CPUID_IMPLEMENTER_Pos) /*!< SCB CPUID: IMPLEMENTER Mask */ #define SCB_CPUID_VARIANT_Pos 20 /*!< SCB CPUID: VARIANT Position */ #define SCB_CPUID_VARIANT_Msk (0xFUL << SCB_CPUID_VARIANT_Pos) /*!< SCB CPUID: VARIANT Mask */ #define SCB_CPUID_ARCHITECTURE_Pos 16 /*!< SCB CPUID: ARCHITECTURE Position */ #define SCB_CPUID_ARCHITECTURE_Msk (0xFUL << SCB_CPUID_ARCHITECTURE_Pos) /*!< SCB CPUID: ARCHITECTURE Mask */ #define SCB_CPUID_PARTNO_Pos 4 /*!< SCB CPUID: PARTNO Position */ #define SCB_CPUID_PARTNO_Msk (0xFFFUL << SCB_CPUID_PARTNO_Pos) /*!< SCB CPUID: PARTNO Mask */ #define SCB_CPUID_REVISION_Pos 0 /*!< SCB CPUID: REVISION Position */ #define SCB_CPUID_REVISION_Msk (0xFUL /*<< SCB_CPUID_REVISION_Pos*/) /*!< SCB CPUID: REVISION Mask */ /* SCB Interrupt Control State Register Definitions */ #define SCB_ICSR_NMIPENDSET_Pos 31 /*!< SCB ICSR: NMIPENDSET Position */ #define SCB_ICSR_NMIPENDSET_Msk (1UL << SCB_ICSR_NMIPENDSET_Pos) /*!< SCB ICSR: NMIPENDSET Mask */ #define SCB_ICSR_PENDSVSET_Pos 28 /*!< SCB ICSR: PENDSVSET Position */ #define SCB_ICSR_PENDSVSET_Msk (1UL << SCB_ICSR_PENDSVSET_Pos) /*!< SCB ICSR: PENDSVSET Mask */ #define SCB_ICSR_PENDSVCLR_Pos 27 /*!< SCB ICSR: PENDSVCLR Position */ #define SCB_ICSR_PENDSVCLR_Msk (1UL << SCB_ICSR_PENDSVCLR_Pos) /*!< SCB ICSR: PENDSVCLR Mask */ #define SCB_ICSR_PENDSTSET_Pos 26 /*!< SCB ICSR: PENDSTSET Position */ #define SCB_ICSR_PENDSTSET_Msk (1UL << SCB_ICSR_PENDSTSET_Pos) /*!< SCB ICSR: PENDSTSET Mask */ #define SCB_ICSR_PENDSTCLR_Pos 25 /*!< SCB ICSR: PENDSTCLR Position */ #define SCB_ICSR_PENDSTCLR_Msk (1UL << SCB_ICSR_PENDSTCLR_Pos) /*!< SCB ICSR: PENDSTCLR Mask */ #define SCB_ICSR_ISRPREEMPT_Pos 23 /*!< SCB ICSR: ISRPREEMPT Position */ #define SCB_ICSR_ISRPREEMPT_Msk (1UL << SCB_ICSR_ISRPREEMPT_Pos) /*!< SCB ICSR: ISRPREEMPT Mask */ #define SCB_ICSR_ISRPENDING_Pos 22 /*!< SCB ICSR: ISRPENDING Position */ #define SCB_ICSR_ISRPENDING_Msk (1UL << SCB_ICSR_ISRPENDING_Pos) /*!< SCB ICSR: ISRPENDING Mask */ #define SCB_ICSR_VECTPENDING_Pos 12 /*!< SCB ICSR: VECTPENDING Position */ #define SCB_ICSR_VECTPENDING_Msk (0x1FFUL << SCB_ICSR_VECTPENDING_Pos) /*!< SCB ICSR: VECTPENDING Mask */ #define SCB_ICSR_RETTOBASE_Pos 11 /*!< SCB ICSR: RETTOBASE Position */ #define SCB_ICSR_RETTOBASE_Msk (1UL << SCB_ICSR_RETTOBASE_Pos) /*!< SCB ICSR: RETTOBASE Mask */ #define SCB_ICSR_VECTACTIVE_Pos 0 /*!< SCB ICSR: VECTACTIVE Position */ #define SCB_ICSR_VECTACTIVE_Msk (0x1FFUL /*<< SCB_ICSR_VECTACTIVE_Pos*/) /*!< SCB ICSR: VECTACTIVE Mask */ /* SCB Vector Table Offset Register Definitions */ #if (__CM3_REV < 0x0201) /* core r2p1 */ #define SCB_VTOR_TBLBASE_Pos 29 /*!< SCB VTOR: TBLBASE Position */ #define SCB_VTOR_TBLBASE_Msk (1UL << SCB_VTOR_TBLBASE_Pos) /*!< SCB VTOR: TBLBASE Mask */ #define SCB_VTOR_TBLOFF_Pos 7 /*!< SCB VTOR: TBLOFF Position */ #define SCB_VTOR_TBLOFF_Msk (0x3FFFFFUL << SCB_VTOR_TBLOFF_Pos) /*!< SCB VTOR: TBLOFF Mask */ #else #define SCB_VTOR_TBLOFF_Pos 7 /*!< SCB VTOR: TBLOFF Position */ #define SCB_VTOR_TBLOFF_Msk (0x1FFFFFFUL << SCB_VTOR_TBLOFF_Pos) /*!< SCB VTOR: TBLOFF Mask */ #endif /* SCB Application Interrupt and Reset Control Register Definitions */ #define SCB_AIRCR_VECTKEY_Pos 16 /*!< SCB AIRCR: VECTKEY Position */ #define SCB_AIRCR_VECTKEY_Msk (0xFFFFUL << SCB_AIRCR_VECTKEY_Pos) /*!< SCB AIRCR: VECTKEY Mask */ #define SCB_AIRCR_VECTKEYSTAT_Pos 16 /*!< SCB AIRCR: VECTKEYSTAT Position */ #define SCB_AIRCR_VECTKEYSTAT_Msk (0xFFFFUL << SCB_AIRCR_VECTKEYSTAT_Pos) /*!< SCB AIRCR: VECTKEYSTAT Mask */ #define SCB_AIRCR_ENDIANESS_Pos 15 /*!< SCB AIRCR: ENDIANESS Position */ #define SCB_AIRCR_ENDIANESS_Msk (1UL << SCB_AIRCR_ENDIANESS_Pos) /*!< SCB AIRCR: ENDIANESS Mask */ #define SCB_AIRCR_PRIGROUP_Pos 8 /*!< SCB AIRCR: PRIGROUP Position */ #define SCB_AIRCR_PRIGROUP_Msk (7UL << SCB_AIRCR_PRIGROUP_Pos) /*!< SCB AIRCR: PRIGROUP Mask */ #define SCB_AIRCR_SYSRESETREQ_Pos 2 /*!< SCB AIRCR: SYSRESETREQ Position */ #define SCB_AIRCR_SYSRESETREQ_Msk (1UL << SCB_AIRCR_SYSRESETREQ_Pos) /*!< SCB AIRCR: SYSRESETREQ Mask */ #define SCB_AIRCR_VECTCLRACTIVE_Pos 1 /*!< SCB AIRCR: VECTCLRACTIVE Position */ #define SCB_AIRCR_VECTCLRACTIVE_Msk (1UL << SCB_AIRCR_VECTCLRACTIVE_Pos) /*!< SCB AIRCR: VECTCLRACTIVE Mask */ #define SCB_AIRCR_VECTRESET_Pos 0 /*!< SCB AIRCR: VECTRESET Position */ #define SCB_AIRCR_VECTRESET_Msk (1UL /*<< SCB_AIRCR_VECTRESET_Pos*/) /*!< SCB AIRCR: VECTRESET Mask */ /* SCB System Control Register Definitions */ #define SCB_SCR_SEVONPEND_Pos 4 /*!< SCB SCR: SEVONPEND Position */ #define SCB_SCR_SEVONPEND_Msk (1UL << SCB_SCR_SEVONPEND_Pos) /*!< SCB SCR: SEVONPEND Mask */ #define SCB_SCR_SLEEPDEEP_Pos 2 /*!< SCB SCR: SLEEPDEEP Position */ #define SCB_SCR_SLEEPDEEP_Msk (1UL << SCB_SCR_SLEEPDEEP_Pos) /*!< SCB SCR: SLEEPDEEP Mask */ #define SCB_SCR_SLEEPONEXIT_Pos 1 /*!< SCB SCR: SLEEPONEXIT Position */ #define SCB_SCR_SLEEPONEXIT_Msk (1UL << SCB_SCR_SLEEPONEXIT_Pos) /*!< SCB SCR: SLEEPONEXIT Mask */ /* SCB Configuration Control Register Definitions */ #define SCB_CCR_STKALIGN_Pos 9 /*!< SCB CCR: STKALIGN Position */ #define SCB_CCR_STKALIGN_Msk (1UL << SCB_CCR_STKALIGN_Pos) /*!< SCB CCR: STKALIGN Mask */ #define SCB_CCR_BFHFNMIGN_Pos 8 /*!< SCB CCR: BFHFNMIGN Position */ #define SCB_CCR_BFHFNMIGN_Msk (1UL << SCB_CCR_BFHFNMIGN_Pos) /*!< SCB CCR: BFHFNMIGN Mask */ #define SCB_CCR_DIV_0_TRP_Pos 4 /*!< SCB CCR: DIV_0_TRP Position */ #define SCB_CCR_DIV_0_TRP_Msk (1UL << SCB_CCR_DIV_0_TRP_Pos) /*!< SCB CCR: DIV_0_TRP Mask */ #define SCB_CCR_UNALIGN_TRP_Pos 3 /*!< SCB CCR: UNALIGN_TRP Position */ #define SCB_CCR_UNALIGN_TRP_Msk (1UL << SCB_CCR_UNALIGN_TRP_Pos) /*!< SCB CCR: UNALIGN_TRP Mask */ #define SCB_CCR_USERSETMPEND_Pos 1 /*!< SCB CCR: USERSETMPEND Position */ #define SCB_CCR_USERSETMPEND_Msk (1UL << SCB_CCR_USERSETMPEND_Pos) /*!< SCB CCR: USERSETMPEND Mask */ #define SCB_CCR_NONBASETHRDENA_Pos 0 /*!< SCB CCR: NONBASETHRDENA Position */ #define SCB_CCR_NONBASETHRDENA_Msk (1UL /*<< SCB_CCR_NONBASETHRDENA_Pos*/) /*!< SCB CCR: NONBASETHRDENA Mask */ /* SCB System Handler Control and State Register Definitions */ #define SCB_SHCSR_USGFAULTENA_Pos 18 /*!< SCB SHCSR: USGFAULTENA Position */ #define SCB_SHCSR_USGFAULTENA_Msk (1UL << SCB_SHCSR_USGFAULTENA_Pos) /*!< SCB SHCSR: USGFAULTENA Mask */ #define SCB_SHCSR_BUSFAULTENA_Pos 17 /*!< SCB SHCSR: BUSFAULTENA Position */ #define SCB_SHCSR_BUSFAULTENA_Msk (1UL << SCB_SHCSR_BUSFAULTENA_Pos) /*!< SCB SHCSR: BUSFAULTENA Mask */ #define SCB_SHCSR_MEMFAULTENA_Pos 16 /*!< SCB SHCSR: MEMFAULTENA Position */ #define SCB_SHCSR_MEMFAULTENA_Msk (1UL << SCB_SHCSR_MEMFAULTENA_Pos) /*!< SCB SHCSR: MEMFAULTENA Mask */ #define SCB_SHCSR_SVCALLPENDED_Pos 15 /*!< SCB SHCSR: SVCALLPENDED Position */ #define SCB_SHCSR_SVCALLPENDED_Msk (1UL << SCB_SHCSR_SVCALLPENDED_Pos) /*!< SCB SHCSR: SVCALLPENDED Mask */ #define SCB_SHCSR_BUSFAULTPENDED_Pos 14 /*!< SCB SHCSR: BUSFAULTPENDED Position */ #define SCB_SHCSR_BUSFAULTPENDED_Msk (1UL << SCB_SHCSR_BUSFAULTPENDED_Pos) /*!< SCB SHCSR: BUSFAULTPENDED Mask */ #define SCB_SHCSR_MEMFAULTPENDED_Pos 13 /*!< SCB SHCSR: MEMFAULTPENDED Position */ #define SCB_SHCSR_MEMFAULTPENDED_Msk (1UL << SCB_SHCSR_MEMFAULTPENDED_Pos) /*!< SCB SHCSR: MEMFAULTPENDED Mask */ #define SCB_SHCSR_USGFAULTPENDED_Pos 12 /*!< SCB SHCSR: USGFAULTPENDED Position */ #define SCB_SHCSR_USGFAULTPENDED_Msk (1UL << SCB_SHCSR_USGFAULTPENDED_Pos) /*!< SCB SHCSR: USGFAULTPENDED Mask */ #define SCB_SHCSR_SYSTICKACT_Pos 11 /*!< SCB SHCSR: SYSTICKACT Position */ #define SCB_SHCSR_SYSTICKACT_Msk (1UL << SCB_SHCSR_SYSTICKACT_Pos) /*!< SCB SHCSR: SYSTICKACT Mask */ #define SCB_SHCSR_PENDSVACT_Pos 10 /*!< SCB SHCSR: PENDSVACT Position */ #define SCB_SHCSR_PENDSVACT_Msk (1UL << SCB_SHCSR_PENDSVACT_Pos) /*!< SCB SHCSR: PENDSVACT Mask */ #define SCB_SHCSR_MONITORACT_Pos 8 /*!< SCB SHCSR: MONITORACT Position */ #define SCB_SHCSR_MONITORACT_Msk (1UL << SCB_SHCSR_MONITORACT_Pos) /*!< SCB SHCSR: MONITORACT Mask */ #define SCB_SHCSR_SVCALLACT_Pos 7 /*!< SCB SHCSR: SVCALLACT Position */ #define SCB_SHCSR_SVCALLACT_Msk (1UL << SCB_SHCSR_SVCALLACT_Pos) /*!< SCB SHCSR: SVCALLACT Mask */ #define SCB_SHCSR_USGFAULTACT_Pos 3 /*!< SCB SHCSR: USGFAULTACT Position */ #define SCB_SHCSR_USGFAULTACT_Msk (1UL << SCB_SHCSR_USGFAULTACT_Pos) /*!< SCB SHCSR: USGFAULTACT Mask */ #define SCB_SHCSR_BUSFAULTACT_Pos 1 /*!< SCB SHCSR: BUSFAULTACT Position */ #define SCB_SHCSR_BUSFAULTACT_Msk (1UL << SCB_SHCSR_BUSFAULTACT_Pos) /*!< SCB SHCSR: BUSFAULTACT Mask */ #define SCB_SHCSR_MEMFAULTACT_Pos 0 /*!< SCB SHCSR: MEMFAULTACT Position */ #define SCB_SHCSR_MEMFAULTACT_Msk (1UL /*<< SCB_SHCSR_MEMFAULTACT_Pos*/) /*!< SCB SHCSR: MEMFAULTACT Mask */ /* SCB Configurable Fault Status Registers Definitions */ #define SCB_CFSR_USGFAULTSR_Pos 16 /*!< SCB CFSR: Usage Fault Status Register Position */ #define SCB_CFSR_USGFAULTSR_Msk (0xFFFFUL << SCB_CFSR_USGFAULTSR_Pos) /*!< SCB CFSR: Usage Fault Status Register Mask */ #define SCB_CFSR_BUSFAULTSR_Pos 8 /*!< SCB CFSR: Bus Fault Status Register Position */ #define SCB_CFSR_BUSFAULTSR_Msk (0xFFUL << SCB_CFSR_BUSFAULTSR_Pos) /*!< SCB CFSR: Bus Fault Status Register Mask */ #define SCB_CFSR_MEMFAULTSR_Pos 0 /*!< SCB CFSR: Memory Manage Fault Status Register Position */ #define SCB_CFSR_MEMFAULTSR_Msk (0xFFUL /*<< SCB_CFSR_MEMFAULTSR_Pos*/) /*!< SCB CFSR: Memory Manage Fault Status Register Mask */ /* SCB Hard Fault Status Registers Definitions */ #define SCB_HFSR_DEBUGEVT_Pos 31 /*!< SCB HFSR: DEBUGEVT Position */ #define SCB_HFSR_DEBUGEVT_Msk (1UL << SCB_HFSR_DEBUGEVT_Pos) /*!< SCB HFSR: DEBUGEVT Mask */ #define SCB_HFSR_FORCED_Pos 30 /*!< SCB HFSR: FORCED Position */ #define SCB_HFSR_FORCED_Msk (1UL << SCB_HFSR_FORCED_Pos) /*!< SCB HFSR: FORCED Mask */ #define SCB_HFSR_VECTTBL_Pos 1 /*!< SCB HFSR: VECTTBL Position */ #define SCB_HFSR_VECTTBL_Msk (1UL << SCB_HFSR_VECTTBL_Pos) /*!< SCB HFSR: VECTTBL Mask */ /* SCB Debug Fault Status Register Definitions */ #define SCB_DFSR_EXTERNAL_Pos 4 /*!< SCB DFSR: EXTERNAL Position */ #define SCB_DFSR_EXTERNAL_Msk (1UL << SCB_DFSR_EXTERNAL_Pos) /*!< SCB DFSR: EXTERNAL Mask */ #define SCB_DFSR_VCATCH_Pos 3 /*!< SCB DFSR: VCATCH Position */ #define SCB_DFSR_VCATCH_Msk (1UL << SCB_DFSR_VCATCH_Pos) /*!< SCB DFSR: VCATCH Mask */ #define SCB_DFSR_DWTTRAP_Pos 2 /*!< SCB DFSR: DWTTRAP Position */ #define SCB_DFSR_DWTTRAP_Msk (1UL << SCB_DFSR_DWTTRAP_Pos) /*!< SCB DFSR: DWTTRAP Mask */ #define SCB_DFSR_BKPT_Pos 1 /*!< SCB DFSR: BKPT Position */ #define SCB_DFSR_BKPT_Msk (1UL << SCB_DFSR_BKPT_Pos) /*!< SCB DFSR: BKPT Mask */ #define SCB_DFSR_HALTED_Pos 0 /*!< SCB DFSR: HALTED Position */ #define SCB_DFSR_HALTED_Msk (1UL /*<< SCB_DFSR_HALTED_Pos*/) /*!< SCB DFSR: HALTED Mask */ /*@} end of group CMSIS_SCB */ /** \ingroup CMSIS_core_register \defgroup CMSIS_SCnSCB System Controls not in SCB (SCnSCB) \brief Type definitions for the System Control and ID Register not in the SCB @{ */ /** \brief Structure type to access the System Control and ID Register not in the SCB. */ typedef struct { uint32_t RESERVED0[1]; __I uint32_t ICTR; /*!< Offset: 0x004 (R/ ) Interrupt Controller Type Register */ #if ((defined __CM3_REV) && (__CM3_REV >= 0x200)) __IO uint32_t ACTLR; /*!< Offset: 0x008 (R/W) Auxiliary Control Register */ #else uint32_t RESERVED1[1]; #endif } SCnSCB_Type; /* Interrupt Controller Type Register Definitions */ #define SCnSCB_ICTR_INTLINESNUM_Pos 0 /*!< ICTR: INTLINESNUM Position */ #define SCnSCB_ICTR_INTLINESNUM_Msk (0xFUL /*<< SCnSCB_ICTR_INTLINESNUM_Pos*/) /*!< ICTR: INTLINESNUM Mask */ /* Auxiliary Control Register Definitions */ #define SCnSCB_ACTLR_DISFOLD_Pos 2 /*!< ACTLR: DISFOLD Position */ #define SCnSCB_ACTLR_DISFOLD_Msk (1UL << SCnSCB_ACTLR_DISFOLD_Pos) /*!< ACTLR: DISFOLD Mask */ #define SCnSCB_ACTLR_DISDEFWBUF_Pos 1 /*!< ACTLR: DISDEFWBUF Position */ #define SCnSCB_ACTLR_DISDEFWBUF_Msk (1UL << SCnSCB_ACTLR_DISDEFWBUF_Pos) /*!< ACTLR: DISDEFWBUF Mask */ #define SCnSCB_ACTLR_DISMCYCINT_Pos 0 /*!< ACTLR: DISMCYCINT Position */ #define SCnSCB_ACTLR_DISMCYCINT_Msk (1UL /*<< SCnSCB_ACTLR_DISMCYCINT_Pos*/) /*!< ACTLR: DISMCYCINT Mask */ /*@} end of group CMSIS_SCnotSCB */ /** \ingroup CMSIS_core_register \defgroup CMSIS_SysTick System Tick Timer (SysTick) \brief Type definitions for the System Timer Registers. @{ */ /** \brief Structure type to access the System Timer (SysTick). */ typedef struct { __IO uint32_t CTRL; /*!< Offset: 0x000 (R/W) SysTick Control and Status Register */ __IO uint32_t LOAD; /*!< Offset: 0x004 (R/W) SysTick Reload Value Register */ __IO uint32_t VAL; /*!< Offset: 0x008 (R/W) SysTick Current Value Register */ __I uint32_t CALIB; /*!< Offset: 0x00C (R/ ) SysTick Calibration Register */ } SysTick_Type; /* SysTick Control / Status Register Definitions */ #define SysTick_CTRL_COUNTFLAG_Pos 16 /*!< SysTick CTRL: COUNTFLAG Position */ #define SysTick_CTRL_COUNTFLAG_Msk (1UL << SysTick_CTRL_COUNTFLAG_Pos) /*!< SysTick CTRL: COUNTFLAG Mask */ #define SysTick_CTRL_CLKSOURCE_Pos 2 /*!< SysTick CTRL: CLKSOURCE Position */ #define SysTick_CTRL_CLKSOURCE_Msk (1UL << SysTick_CTRL_CLKSOURCE_Pos) /*!< SysTick CTRL: CLKSOURCE Mask */ #define SysTick_CTRL_TICKINT_Pos 1 /*!< SysTick CTRL: TICKINT Position */ #define SysTick_CTRL_TICKINT_Msk (1UL << SysTick_CTRL_TICKINT_Pos) /*!< SysTick CTRL: TICKINT Mask */ #define SysTick_CTRL_ENABLE_Pos 0 /*!< SysTick CTRL: ENABLE Position */ #define SysTick_CTRL_ENABLE_Msk (1UL /*<< SysTick_CTRL_ENABLE_Pos*/) /*!< SysTick CTRL: ENABLE Mask */ /* SysTick Reload Register Definitions */ #define SysTick_LOAD_RELOAD_Pos 0 /*!< SysTick LOAD: RELOAD Position */ #define SysTick_LOAD_RELOAD_Msk (0xFFFFFFUL /*<< SysTick_LOAD_RELOAD_Pos*/) /*!< SysTick LOAD: RELOAD Mask */ /* SysTick Current Register Definitions */ #define SysTick_VAL_CURRENT_Pos 0 /*!< SysTick VAL: CURRENT Position */ #define SysTick_VAL_CURRENT_Msk (0xFFFFFFUL /*<< SysTick_VAL_CURRENT_Pos*/) /*!< SysTick VAL: CURRENT Mask */ /* SysTick Calibration Register Definitions */ #define SysTick_CALIB_NOREF_Pos 31 /*!< SysTick CALIB: NOREF Position */ #define SysTick_CALIB_NOREF_Msk (1UL << SysTick_CALIB_NOREF_Pos) /*!< SysTick CALIB: NOREF Mask */ #define SysTick_CALIB_SKEW_Pos 30 /*!< SysTick CALIB: SKEW Position */ #define SysTick_CALIB_SKEW_Msk (1UL << SysTick_CALIB_SKEW_Pos) /*!< SysTick CALIB: SKEW Mask */ #define SysTick_CALIB_TENMS_Pos 0 /*!< SysTick CALIB: TENMS Position */ #define SysTick_CALIB_TENMS_Msk (0xFFFFFFUL /*<< SysTick_CALIB_TENMS_Pos*/) /*!< SysTick CALIB: TENMS Mask */ /*@} end of group CMSIS_SysTick */ /** \ingroup CMSIS_core_register \defgroup CMSIS_ITM Instrumentation Trace Macrocell (ITM) \brief Type definitions for the Instrumentation Trace Macrocell (ITM) @{ */ /** \brief Structure type to access the Instrumentation Trace Macrocell Register (ITM). */ typedef struct { __O union { __O uint8_t u8; /*!< Offset: 0x000 ( /W) ITM Stimulus Port 8-bit */ __O uint16_t u16; /*!< Offset: 0x000 ( /W) ITM Stimulus Port 16-bit */ __O uint32_t u32; /*!< Offset: 0x000 ( /W) ITM Stimulus Port 32-bit */ } PORT [32]; /*!< Offset: 0x000 ( /W) ITM Stimulus Port Registers */ uint32_t RESERVED0[864]; __IO uint32_t TER; /*!< Offset: 0xE00 (R/W) ITM Trace Enable Register */ uint32_t RESERVED1[15]; __IO uint32_t TPR; /*!< Offset: 0xE40 (R/W) ITM Trace Privilege Register */ uint32_t RESERVED2[15]; __IO uint32_t TCR; /*!< Offset: 0xE80 (R/W) ITM Trace Control Register */ uint32_t RESERVED3[29]; __O uint32_t IWR; /*!< Offset: 0xEF8 ( /W) ITM Integration Write Register */ __I uint32_t IRR; /*!< Offset: 0xEFC (R/ ) ITM Integration Read Register */ __IO uint32_t IMCR; /*!< Offset: 0xF00 (R/W) ITM Integration Mode Control Register */ uint32_t RESERVED4[43]; __O uint32_t LAR; /*!< Offset: 0xFB0 ( /W) ITM Lock Access Register */ __I uint32_t LSR; /*!< Offset: 0xFB4 (R/ ) ITM Lock Status Register */ uint32_t RESERVED5[6]; __I uint32_t PID4; /*!< Offset: 0xFD0 (R/ ) ITM Peripheral Identification Register #4 */ __I uint32_t PID5; /*!< Offset: 0xFD4 (R/ ) ITM Peripheral Identification Register #5 */ __I uint32_t PID6; /*!< Offset: 0xFD8 (R/ ) ITM Peripheral Identification Register #6 */ __I uint32_t PID7; /*!< Offset: 0xFDC (R/ ) ITM Peripheral Identification Register #7 */ __I uint32_t PID0; /*!< Offset: 0xFE0 (R/ ) ITM Peripheral Identification Register #0 */ __I uint32_t PID1; /*!< Offset: 0xFE4 (R/ ) ITM Peripheral Identification Register #1 */ __I uint32_t PID2; /*!< Offset: 0xFE8 (R/ ) ITM Peripheral Identification Register #2 */ __I uint32_t PID3; /*!< Offset: 0xFEC (R/ ) ITM Peripheral Identification Register #3 */ __I uint32_t CID0; /*!< Offset: 0xFF0 (R/ ) ITM Component Identification Register #0 */ __I uint32_t CID1; /*!< Offset: 0xFF4 (R/ ) ITM Component Identification Register #1 */ __I uint32_t CID2; /*!< Offset: 0xFF8 (R/ ) ITM Component Identification Register #2 */ __I uint32_t CID3; /*!< Offset: 0xFFC (R/ ) ITM Component Identification Register #3 */ } ITM_Type; /* ITM Trace Privilege Register Definitions */ #define ITM_TPR_PRIVMASK_Pos 0 /*!< ITM TPR: PRIVMASK Position */ #define ITM_TPR_PRIVMASK_Msk (0xFUL /*<< ITM_TPR_PRIVMASK_Pos*/) /*!< ITM TPR: PRIVMASK Mask */ /* ITM Trace Control Register Definitions */ #define ITM_TCR_BUSY_Pos 23 /*!< ITM TCR: BUSY Position */ #define ITM_TCR_BUSY_Msk (1UL << ITM_TCR_BUSY_Pos) /*!< ITM TCR: BUSY Mask */ #define ITM_TCR_TraceBusID_Pos 16 /*!< ITM TCR: ATBID Position */ #define ITM_TCR_TraceBusID_Msk (0x7FUL << ITM_TCR_TraceBusID_Pos) /*!< ITM TCR: ATBID Mask */ #define ITM_TCR_GTSFREQ_Pos 10 /*!< ITM TCR: Global timestamp frequency Position */ #define ITM_TCR_GTSFREQ_Msk (3UL << ITM_TCR_GTSFREQ_Pos) /*!< ITM TCR: Global timestamp frequency Mask */ #define ITM_TCR_TSPrescale_Pos 8 /*!< ITM TCR: TSPrescale Position */ #define ITM_TCR_TSPrescale_Msk (3UL << ITM_TCR_TSPrescale_Pos) /*!< ITM TCR: TSPrescale Mask */ #define ITM_TCR_SWOENA_Pos 4 /*!< ITM TCR: SWOENA Position */ #define ITM_TCR_SWOENA_Msk (1UL << ITM_TCR_SWOENA_Pos) /*!< ITM TCR: SWOENA Mask */ #define ITM_TCR_DWTENA_Pos 3 /*!< ITM TCR: DWTENA Position */ #define ITM_TCR_DWTENA_Msk (1UL << ITM_TCR_DWTENA_Pos) /*!< ITM TCR: DWTENA Mask */ #define ITM_TCR_SYNCENA_Pos 2 /*!< ITM TCR: SYNCENA Position */ #define ITM_TCR_SYNCENA_Msk (1UL << ITM_TCR_SYNCENA_Pos) /*!< ITM TCR: SYNCENA Mask */ #define ITM_TCR_TSENA_Pos 1 /*!< ITM TCR: TSENA Position */ #define ITM_TCR_TSENA_Msk (1UL << ITM_TCR_TSENA_Pos) /*!< ITM TCR: TSENA Mask */ #define ITM_TCR_ITMENA_Pos 0 /*!< ITM TCR: ITM Enable bit Position */ #define ITM_TCR_ITMENA_Msk (1UL /*<< ITM_TCR_ITMENA_Pos*/) /*!< ITM TCR: ITM Enable bit Mask */ /* ITM Integration Write Register Definitions */ #define ITM_IWR_ATVALIDM_Pos 0 /*!< ITM IWR: ATVALIDM Position */ #define ITM_IWR_ATVALIDM_Msk (1UL /*<< ITM_IWR_ATVALIDM_Pos*/) /*!< ITM IWR: ATVALIDM Mask */ /* ITM Integration Read Register Definitions */ #define ITM_IRR_ATREADYM_Pos 0 /*!< ITM IRR: ATREADYM Position */ #define ITM_IRR_ATREADYM_Msk (1UL /*<< ITM_IRR_ATREADYM_Pos*/) /*!< ITM IRR: ATREADYM Mask */ /* ITM Integration Mode Control Register Definitions */ #define ITM_IMCR_INTEGRATION_Pos 0 /*!< ITM IMCR: INTEGRATION Position */ #define ITM_IMCR_INTEGRATION_Msk (1UL /*<< ITM_IMCR_INTEGRATION_Pos*/) /*!< ITM IMCR: INTEGRATION Mask */ /* ITM Lock Status Register Definitions */ #define ITM_LSR_ByteAcc_Pos 2 /*!< ITM LSR: ByteAcc Position */ #define ITM_LSR_ByteAcc_Msk (1UL << ITM_LSR_ByteAcc_Pos) /*!< ITM LSR: ByteAcc Mask */ #define ITM_LSR_Access_Pos 1 /*!< ITM LSR: Access Position */ #define ITM_LSR_Access_Msk (1UL << ITM_LSR_Access_Pos) /*!< ITM LSR: Access Mask */ #define ITM_LSR_Present_Pos 0 /*!< ITM LSR: Present Position */ #define ITM_LSR_Present_Msk (1UL /*<< ITM_LSR_Present_Pos*/) /*!< ITM LSR: Present Mask */ /*@}*/ /* end of group CMSIS_ITM */ /** \ingroup CMSIS_core_register \defgroup CMSIS_DWT Data Watchpoint and Trace (DWT) \brief Type definitions for the Data Watchpoint and Trace (DWT) @{ */ /** \brief Structure type to access the Data Watchpoint and Trace Register (DWT). */ typedef struct { __IO uint32_t CTRL; /*!< Offset: 0x000 (R/W) Control Register */ __IO uint32_t CYCCNT; /*!< Offset: 0x004 (R/W) Cycle Count Register */ __IO uint32_t CPICNT; /*!< Offset: 0x008 (R/W) CPI Count Register */ __IO uint32_t EXCCNT; /*!< Offset: 0x00C (R/W) Exception Overhead Count Register */ __IO uint32_t SLEEPCNT; /*!< Offset: 0x010 (R/W) Sleep Count Register */ __IO uint32_t LSUCNT; /*!< Offset: 0x014 (R/W) LSU Count Register */ __IO uint32_t FOLDCNT; /*!< Offset: 0x018 (R/W) Folded-instruction Count Register */ __I uint32_t PCSR; /*!< Offset: 0x01C (R/ ) Program Counter Sample Register */ __IO uint32_t COMP0; /*!< Offset: 0x020 (R/W) Comparator Register 0 */ __IO uint32_t MASK0; /*!< Offset: 0x024 (R/W) Mask Register 0 */ __IO uint32_t FUNCTION0; /*!< Offset: 0x028 (R/W) Function Register 0 */ uint32_t RESERVED0[1]; __IO uint32_t COMP1; /*!< Offset: 0x030 (R/W) Comparator Register 1 */ __IO uint32_t MASK1; /*!< Offset: 0x034 (R/W) Mask Register 1 */ __IO uint32_t FUNCTION1; /*!< Offset: 0x038 (R/W) Function Register 1 */ uint32_t RESERVED1[1]; __IO uint32_t COMP2; /*!< Offset: 0x040 (R/W) Comparator Register 2 */ __IO uint32_t MASK2; /*!< Offset: 0x044 (R/W) Mask Register 2 */ __IO uint32_t FUNCTION2; /*!< Offset: 0x048 (R/W) Function Register 2 */ uint32_t RESERVED2[1]; __IO uint32_t COMP3; /*!< Offset: 0x050 (R/W) Comparator Register 3 */ __IO uint32_t MASK3; /*!< Offset: 0x054 (R/W) Mask Register 3 */ __IO uint32_t FUNCTION3; /*!< Offset: 0x058 (R/W) Function Register 3 */ } DWT_Type; /* DWT Control Register Definitions */ #define DWT_CTRL_NUMCOMP_Pos 28 /*!< DWT CTRL: NUMCOMP Position */ #define DWT_CTRL_NUMCOMP_Msk (0xFUL << DWT_CTRL_NUMCOMP_Pos) /*!< DWT CTRL: NUMCOMP Mask */ #define DWT_CTRL_NOTRCPKT_Pos 27 /*!< DWT CTRL: NOTRCPKT Position */ #define DWT_CTRL_NOTRCPKT_Msk (0x1UL << DWT_CTRL_NOTRCPKT_Pos) /*!< DWT CTRL: NOTRCPKT Mask */ #define DWT_CTRL_NOEXTTRIG_Pos 26 /*!< DWT CTRL: NOEXTTRIG Position */ #define DWT_CTRL_NOEXTTRIG_Msk (0x1UL << DWT_CTRL_NOEXTTRIG_Pos) /*!< DWT CTRL: NOEXTTRIG Mask */ #define DWT_CTRL_NOCYCCNT_Pos 25 /*!< DWT CTRL: NOCYCCNT Position */ #define DWT_CTRL_NOCYCCNT_Msk (0x1UL << DWT_CTRL_NOCYCCNT_Pos) /*!< DWT CTRL: NOCYCCNT Mask */ #define DWT_CTRL_NOPRFCNT_Pos 24 /*!< DWT CTRL: NOPRFCNT Position */ #define DWT_CTRL_NOPRFCNT_Msk (0x1UL << DWT_CTRL_NOPRFCNT_Pos) /*!< DWT CTRL: NOPRFCNT Mask */ #define DWT_CTRL_CYCEVTENA_Pos 22 /*!< DWT CTRL: CYCEVTENA Position */ #define DWT_CTRL_CYCEVTENA_Msk (0x1UL << DWT_CTRL_CYCEVTENA_Pos) /*!< DWT CTRL: CYCEVTENA Mask */ #define DWT_CTRL_FOLDEVTENA_Pos 21 /*!< DWT CTRL: FOLDEVTENA Position */ #define DWT_CTRL_FOLDEVTENA_Msk (0x1UL << DWT_CTRL_FOLDEVTENA_Pos) /*!< DWT CTRL: FOLDEVTENA Mask */ #define DWT_CTRL_LSUEVTENA_Pos 20 /*!< DWT CTRL: LSUEVTENA Position */ #define DWT_CTRL_LSUEVTENA_Msk (0x1UL << DWT_CTRL_LSUEVTENA_Pos) /*!< DWT CTRL: LSUEVTENA Mask */ #define DWT_CTRL_SLEEPEVTENA_Pos 19 /*!< DWT CTRL: SLEEPEVTENA Position */ #define DWT_CTRL_SLEEPEVTENA_Msk (0x1UL << DWT_CTRL_SLEEPEVTENA_Pos) /*!< DWT CTRL: SLEEPEVTENA Mask */ #define DWT_CTRL_EXCEVTENA_Pos 18 /*!< DWT CTRL: EXCEVTENA Position */ #define DWT_CTRL_EXCEVTENA_Msk (0x1UL << DWT_CTRL_EXCEVTENA_Pos) /*!< DWT CTRL: EXCEVTENA Mask */ #define DWT_CTRL_CPIEVTENA_Pos 17 /*!< DWT CTRL: CPIEVTENA Position */ #define DWT_CTRL_CPIEVTENA_Msk (0x1UL << DWT_CTRL_CPIEVTENA_Pos) /*!< DWT CTRL: CPIEVTENA Mask */ #define DWT_CTRL_EXCTRCENA_Pos 16 /*!< DWT CTRL: EXCTRCENA Position */ #define DWT_CTRL_EXCTRCENA_Msk (0x1UL << DWT_CTRL_EXCTRCENA_Pos) /*!< DWT CTRL: EXCTRCENA Mask */ #define DWT_CTRL_PCSAMPLENA_Pos 12 /*!< DWT CTRL: PCSAMPLENA Position */ #define DWT_CTRL_PCSAMPLENA_Msk (0x1UL << DWT_CTRL_PCSAMPLENA_Pos) /*!< DWT CTRL: PCSAMPLENA Mask */ #define DWT_CTRL_SYNCTAP_Pos 10 /*!< DWT CTRL: SYNCTAP Position */ #define DWT_CTRL_SYNCTAP_Msk (0x3UL << DWT_CTRL_SYNCTAP_Pos) /*!< DWT CTRL: SYNCTAP Mask */ #define DWT_CTRL_CYCTAP_Pos 9 /*!< DWT CTRL: CYCTAP Position */ #define DWT_CTRL_CYCTAP_Msk (0x1UL << DWT_CTRL_CYCTAP_Pos) /*!< DWT CTRL: CYCTAP Mask */ #define DWT_CTRL_POSTINIT_Pos 5 /*!< DWT CTRL: POSTINIT Position */ #define DWT_CTRL_POSTINIT_Msk (0xFUL << DWT_CTRL_POSTINIT_Pos) /*!< DWT CTRL: POSTINIT Mask */ #define DWT_CTRL_POSTPRESET_Pos 1 /*!< DWT CTRL: POSTPRESET Position */ #define DWT_CTRL_POSTPRESET_Msk (0xFUL << DWT_CTRL_POSTPRESET_Pos) /*!< DWT CTRL: POSTPRESET Mask */ #define DWT_CTRL_CYCCNTENA_Pos 0 /*!< DWT CTRL: CYCCNTENA Position */ #define DWT_CTRL_CYCCNTENA_Msk (0x1UL /*<< DWT_CTRL_CYCCNTENA_Pos*/) /*!< DWT CTRL: CYCCNTENA Mask */ /* DWT CPI Count Register Definitions */ #define DWT_CPICNT_CPICNT_Pos 0 /*!< DWT CPICNT: CPICNT Position */ #define DWT_CPICNT_CPICNT_Msk (0xFFUL /*<< DWT_CPICNT_CPICNT_Pos*/) /*!< DWT CPICNT: CPICNT Mask */ /* DWT Exception Overhead Count Register Definitions */ #define DWT_EXCCNT_EXCCNT_Pos 0 /*!< DWT EXCCNT: EXCCNT Position */ #define DWT_EXCCNT_EXCCNT_Msk (0xFFUL /*<< DWT_EXCCNT_EXCCNT_Pos*/) /*!< DWT EXCCNT: EXCCNT Mask */ /* DWT Sleep Count Register Definitions */ #define DWT_SLEEPCNT_SLEEPCNT_Pos 0 /*!< DWT SLEEPCNT: SLEEPCNT Position */ #define DWT_SLEEPCNT_SLEEPCNT_Msk (0xFFUL /*<< DWT_SLEEPCNT_SLEEPCNT_Pos*/) /*!< DWT SLEEPCNT: SLEEPCNT Mask */ /* DWT LSU Count Register Definitions */ #define DWT_LSUCNT_LSUCNT_Pos 0 /*!< DWT LSUCNT: LSUCNT Position */ #define DWT_LSUCNT_LSUCNT_Msk (0xFFUL /*<< DWT_LSUCNT_LSUCNT_Pos*/) /*!< DWT LSUCNT: LSUCNT Mask */ /* DWT Folded-instruction Count Register Definitions */ #define DWT_FOLDCNT_FOLDCNT_Pos 0 /*!< DWT FOLDCNT: FOLDCNT Position */ #define DWT_FOLDCNT_FOLDCNT_Msk (0xFFUL /*<< DWT_FOLDCNT_FOLDCNT_Pos*/) /*!< DWT FOLDCNT: FOLDCNT Mask */ /* DWT Comparator Mask Register Definitions */ #define DWT_MASK_MASK_Pos 0 /*!< DWT MASK: MASK Position */ #define DWT_MASK_MASK_Msk (0x1FUL /*<< DWT_MASK_MASK_Pos*/) /*!< DWT MASK: MASK Mask */ /* DWT Comparator Function Register Definitions */ #define DWT_FUNCTION_MATCHED_Pos 24 /*!< DWT FUNCTION: MATCHED Position */ #define DWT_FUNCTION_MATCHED_Msk (0x1UL << DWT_FUNCTION_MATCHED_Pos) /*!< DWT FUNCTION: MATCHED Mask */ #define DWT_FUNCTION_DATAVADDR1_Pos 16 /*!< DWT FUNCTION: DATAVADDR1 Position */ #define DWT_FUNCTION_DATAVADDR1_Msk (0xFUL << DWT_FUNCTION_DATAVADDR1_Pos) /*!< DWT FUNCTION: DATAVADDR1 Mask */ #define DWT_FUNCTION_DATAVADDR0_Pos 12 /*!< DWT FUNCTION: DATAVADDR0 Position */ #define DWT_FUNCTION_DATAVADDR0_Msk (0xFUL << DWT_FUNCTION_DATAVADDR0_Pos) /*!< DWT FUNCTION: DATAVADDR0 Mask */ #define DWT_FUNCTION_DATAVSIZE_Pos 10 /*!< DWT FUNCTION: DATAVSIZE Position */ #define DWT_FUNCTION_DATAVSIZE_Msk (0x3UL << DWT_FUNCTION_DATAVSIZE_Pos) /*!< DWT FUNCTION: DATAVSIZE Mask */ #define DWT_FUNCTION_LNK1ENA_Pos 9 /*!< DWT FUNCTION: LNK1ENA Position */ #define DWT_FUNCTION_LNK1ENA_Msk (0x1UL << DWT_FUNCTION_LNK1ENA_Pos) /*!< DWT FUNCTION: LNK1ENA Mask */ #define DWT_FUNCTION_DATAVMATCH_Pos 8 /*!< DWT FUNCTION: DATAVMATCH Position */ #define DWT_FUNCTION_DATAVMATCH_Msk (0x1UL << DWT_FUNCTION_DATAVMATCH_Pos) /*!< DWT FUNCTION: DATAVMATCH Mask */ #define DWT_FUNCTION_CYCMATCH_Pos 7 /*!< DWT FUNCTION: CYCMATCH Position */ #define DWT_FUNCTION_CYCMATCH_Msk (0x1UL << DWT_FUNCTION_CYCMATCH_Pos) /*!< DWT FUNCTION: CYCMATCH Mask */ #define DWT_FUNCTION_EMITRANGE_Pos 5 /*!< DWT FUNCTION: EMITRANGE Position */ #define DWT_FUNCTION_EMITRANGE_Msk (0x1UL << DWT_FUNCTION_EMITRANGE_Pos) /*!< DWT FUNCTION: EMITRANGE Mask */ #define DWT_FUNCTION_FUNCTION_Pos 0 /*!< DWT FUNCTION: FUNCTION Position */ #define DWT_FUNCTION_FUNCTION_Msk (0xFUL /*<< DWT_FUNCTION_FUNCTION_Pos*/) /*!< DWT FUNCTION: FUNCTION Mask */ /*@}*/ /* end of group CMSIS_DWT */ /** \ingroup CMSIS_core_register \defgroup CMSIS_TPI Trace Port Interface (TPI) \brief Type definitions for the Trace Port Interface (TPI) @{ */ /** \brief Structure type to access the Trace Port Interface Register (TPI). */ typedef struct { __IO uint32_t SSPSR; /*!< Offset: 0x000 (R/ ) Supported Parallel Port Size Register */ __IO uint32_t CSPSR; /*!< Offset: 0x004 (R/W) Current Parallel Port Size Register */ uint32_t RESERVED0[2]; __IO uint32_t ACPR; /*!< Offset: 0x010 (R/W) Asynchronous Clock Prescaler Register */ uint32_t RESERVED1[55]; __IO uint32_t SPPR; /*!< Offset: 0x0F0 (R/W) Selected Pin Protocol Register */ uint32_t RESERVED2[131]; __I uint32_t FFSR; /*!< Offset: 0x300 (R/ ) Formatter and Flush Status Register */ __IO uint32_t FFCR; /*!< Offset: 0x304 (R/W) Formatter and Flush Control Register */ __I uint32_t FSCR; /*!< Offset: 0x308 (R/ ) Formatter Synchronization Counter Register */ uint32_t RESERVED3[759]; __I uint32_t TRIGGER; /*!< Offset: 0xEE8 (R/ ) TRIGGER */ __I uint32_t FIFO0; /*!< Offset: 0xEEC (R/ ) Integration ETM Data */ __I uint32_t ITATBCTR2; /*!< Offset: 0xEF0 (R/ ) ITATBCTR2 */ uint32_t RESERVED4[1]; __I uint32_t ITATBCTR0; /*!< Offset: 0xEF8 (R/ ) ITATBCTR0 */ __I uint32_t FIFO1; /*!< Offset: 0xEFC (R/ ) Integration ITM Data */ __IO uint32_t ITCTRL; /*!< Offset: 0xF00 (R/W) Integration Mode Control */ uint32_t RESERVED5[39]; __IO uint32_t CLAIMSET; /*!< Offset: 0xFA0 (R/W) Claim tag set */ __IO uint32_t CLAIMCLR; /*!< Offset: 0xFA4 (R/W) Claim tag clear */ uint32_t RESERVED7[8]; __I uint32_t DEVID; /*!< Offset: 0xFC8 (R/ ) TPIU_DEVID */ __I uint32_t DEVTYPE; /*!< Offset: 0xFCC (R/ ) TPIU_DEVTYPE */ } TPI_Type; /* TPI Asynchronous Clock Prescaler Register Definitions */ #define TPI_ACPR_PRESCALER_Pos 0 /*!< TPI ACPR: PRESCALER Position */ #define TPI_ACPR_PRESCALER_Msk (0x1FFFUL /*<< TPI_ACPR_PRESCALER_Pos*/) /*!< TPI ACPR: PRESCALER Mask */ /* TPI Selected Pin Protocol Register Definitions */ #define TPI_SPPR_TXMODE_Pos 0 /*!< TPI SPPR: TXMODE Position */ #define TPI_SPPR_TXMODE_Msk (0x3UL /*<< TPI_SPPR_TXMODE_Pos*/) /*!< TPI SPPR: TXMODE Mask */ /* TPI Formatter and Flush Status Register Definitions */ #define TPI_FFSR_FtNonStop_Pos 3 /*!< TPI FFSR: FtNonStop Position */ #define TPI_FFSR_FtNonStop_Msk (0x1UL << TPI_FFSR_FtNonStop_Pos) /*!< TPI FFSR: FtNonStop Mask */ #define TPI_FFSR_TCPresent_Pos 2 /*!< TPI FFSR: TCPresent Position */ #define TPI_FFSR_TCPresent_Msk (0x1UL << TPI_FFSR_TCPresent_Pos) /*!< TPI FFSR: TCPresent Mask */ #define TPI_FFSR_FtStopped_Pos 1 /*!< TPI FFSR: FtStopped Position */ #define TPI_FFSR_FtStopped_Msk (0x1UL << TPI_FFSR_FtStopped_Pos) /*!< TPI FFSR: FtStopped Mask */ #define TPI_FFSR_FlInProg_Pos 0 /*!< TPI FFSR: FlInProg Position */ #define TPI_FFSR_FlInProg_Msk (0x1UL /*<< TPI_FFSR_FlInProg_Pos*/) /*!< TPI FFSR: FlInProg Mask */ /* TPI Formatter and Flush Control Register Definitions */ #define TPI_FFCR_TrigIn_Pos 8 /*!< TPI FFCR: TrigIn Position */ #define TPI_FFCR_TrigIn_Msk (0x1UL << TPI_FFCR_TrigIn_Pos) /*!< TPI FFCR: TrigIn Mask */ #define TPI_FFCR_EnFCont_Pos 1 /*!< TPI FFCR: EnFCont Position */ #define TPI_FFCR_EnFCont_Msk (0x1UL << TPI_FFCR_EnFCont_Pos) /*!< TPI FFCR: EnFCont Mask */ /* TPI TRIGGER Register Definitions */ #define TPI_TRIGGER_TRIGGER_Pos 0 /*!< TPI TRIGGER: TRIGGER Position */ #define TPI_TRIGGER_TRIGGER_Msk (0x1UL /*<< TPI_TRIGGER_TRIGGER_Pos*/) /*!< TPI TRIGGER: TRIGGER Mask */ /* TPI Integration ETM Data Register Definitions (FIFO0) */ #define TPI_FIFO0_ITM_ATVALID_Pos 29 /*!< TPI FIFO0: ITM_ATVALID Position */ #define TPI_FIFO0_ITM_ATVALID_Msk (0x3UL << TPI_FIFO0_ITM_ATVALID_Pos) /*!< TPI FIFO0: ITM_ATVALID Mask */ #define TPI_FIFO0_ITM_bytecount_Pos 27 /*!< TPI FIFO0: ITM_bytecount Position */ #define TPI_FIFO0_ITM_bytecount_Msk (0x3UL << TPI_FIFO0_ITM_bytecount_Pos) /*!< TPI FIFO0: ITM_bytecount Mask */ #define TPI_FIFO0_ETM_ATVALID_Pos 26 /*!< TPI FIFO0: ETM_ATVALID Position */ #define TPI_FIFO0_ETM_ATVALID_Msk (0x3UL << TPI_FIFO0_ETM_ATVALID_Pos) /*!< TPI FIFO0: ETM_ATVALID Mask */ #define TPI_FIFO0_ETM_bytecount_Pos 24 /*!< TPI FIFO0: ETM_bytecount Position */ #define TPI_FIFO0_ETM_bytecount_Msk (0x3UL << TPI_FIFO0_ETM_bytecount_Pos) /*!< TPI FIFO0: ETM_bytecount Mask */ #define TPI_FIFO0_ETM2_Pos 16 /*!< TPI FIFO0: ETM2 Position */ #define TPI_FIFO0_ETM2_Msk (0xFFUL << TPI_FIFO0_ETM2_Pos) /*!< TPI FIFO0: ETM2 Mask */ #define TPI_FIFO0_ETM1_Pos 8 /*!< TPI FIFO0: ETM1 Position */ #define TPI_FIFO0_ETM1_Msk (0xFFUL << TPI_FIFO0_ETM1_Pos) /*!< TPI FIFO0: ETM1 Mask */ #define TPI_FIFO0_ETM0_Pos 0 /*!< TPI FIFO0: ETM0 Position */ #define TPI_FIFO0_ETM0_Msk (0xFFUL /*<< TPI_FIFO0_ETM0_Pos*/) /*!< TPI FIFO0: ETM0 Mask */ /* TPI ITATBCTR2 Register Definitions */ #define TPI_ITATBCTR2_ATREADY_Pos 0 /*!< TPI ITATBCTR2: ATREADY Position */ #define TPI_ITATBCTR2_ATREADY_Msk (0x1UL /*<< TPI_ITATBCTR2_ATREADY_Pos*/) /*!< TPI ITATBCTR2: ATREADY Mask */ /* TPI Integration ITM Data Register Definitions (FIFO1) */ #define TPI_FIFO1_ITM_ATVALID_Pos 29 /*!< TPI FIFO1: ITM_ATVALID Position */ #define TPI_FIFO1_ITM_ATVALID_Msk (0x3UL << TPI_FIFO1_ITM_ATVALID_Pos) /*!< TPI FIFO1: ITM_ATVALID Mask */ #define TPI_FIFO1_ITM_bytecount_Pos 27 /*!< TPI FIFO1: ITM_bytecount Position */ #define TPI_FIFO1_ITM_bytecount_Msk (0x3UL << TPI_FIFO1_ITM_bytecount_Pos) /*!< TPI FIFO1: ITM_bytecount Mask */ #define TPI_FIFO1_ETM_ATVALID_Pos 26 /*!< TPI FIFO1: ETM_ATVALID Position */ #define TPI_FIFO1_ETM_ATVALID_Msk (0x3UL << TPI_FIFO1_ETM_ATVALID_Pos) /*!< TPI FIFO1: ETM_ATVALID Mask */ #define TPI_FIFO1_ETM_bytecount_Pos 24 /*!< TPI FIFO1: ETM_bytecount Position */ #define TPI_FIFO1_ETM_bytecount_Msk (0x3UL << TPI_FIFO1_ETM_bytecount_Pos) /*!< TPI FIFO1: ETM_bytecount Mask */ #define TPI_FIFO1_ITM2_Pos 16 /*!< TPI FIFO1: ITM2 Position */ #define TPI_FIFO1_ITM2_Msk (0xFFUL << TPI_FIFO1_ITM2_Pos) /*!< TPI FIFO1: ITM2 Mask */ #define TPI_FIFO1_ITM1_Pos 8 /*!< TPI FIFO1: ITM1 Position */ #define TPI_FIFO1_ITM1_Msk (0xFFUL << TPI_FIFO1_ITM1_Pos) /*!< TPI FIFO1: ITM1 Mask */ #define TPI_FIFO1_ITM0_Pos 0 /*!< TPI FIFO1: ITM0 Position */ #define TPI_FIFO1_ITM0_Msk (0xFFUL /*<< TPI_FIFO1_ITM0_Pos*/) /*!< TPI FIFO1: ITM0 Mask */ /* TPI ITATBCTR0 Register Definitions */ #define TPI_ITATBCTR0_ATREADY_Pos 0 /*!< TPI ITATBCTR0: ATREADY Position */ #define TPI_ITATBCTR0_ATREADY_Msk (0x1UL /*<< TPI_ITATBCTR0_ATREADY_Pos*/) /*!< TPI ITATBCTR0: ATREADY Mask */ /* TPI Integration Mode Control Register Definitions */ #define TPI_ITCTRL_Mode_Pos 0 /*!< TPI ITCTRL: Mode Position */ #define TPI_ITCTRL_Mode_Msk (0x1UL /*<< TPI_ITCTRL_Mode_Pos*/) /*!< TPI ITCTRL: Mode Mask */ /* TPI DEVID Register Definitions */ #define TPI_DEVID_NRZVALID_Pos 11 /*!< TPI DEVID: NRZVALID Position */ #define TPI_DEVID_NRZVALID_Msk (0x1UL << TPI_DEVID_NRZVALID_Pos) /*!< TPI DEVID: NRZVALID Mask */ #define TPI_DEVID_MANCVALID_Pos 10 /*!< TPI DEVID: MANCVALID Position */ #define TPI_DEVID_MANCVALID_Msk (0x1UL << TPI_DEVID_MANCVALID_Pos) /*!< TPI DEVID: MANCVALID Mask */ #define TPI_DEVID_PTINVALID_Pos 9 /*!< TPI DEVID: PTINVALID Position */ #define TPI_DEVID_PTINVALID_Msk (0x1UL << TPI_DEVID_PTINVALID_Pos) /*!< TPI DEVID: PTINVALID Mask */ #define TPI_DEVID_MinBufSz_Pos 6 /*!< TPI DEVID: MinBufSz Position */ #define TPI_DEVID_MinBufSz_Msk (0x7UL << TPI_DEVID_MinBufSz_Pos) /*!< TPI DEVID: MinBufSz Mask */ #define TPI_DEVID_AsynClkIn_Pos 5 /*!< TPI DEVID: AsynClkIn Position */ #define TPI_DEVID_AsynClkIn_Msk (0x1UL << TPI_DEVID_AsynClkIn_Pos) /*!< TPI DEVID: AsynClkIn Mask */ #define TPI_DEVID_NrTraceInput_Pos 0 /*!< TPI DEVID: NrTraceInput Position */ #define TPI_DEVID_NrTraceInput_Msk (0x1FUL /*<< TPI_DEVID_NrTraceInput_Pos*/) /*!< TPI DEVID: NrTraceInput Mask */ /* TPI DEVTYPE Register Definitions */ #define TPI_DEVTYPE_MajorType_Pos 4 /*!< TPI DEVTYPE: MajorType Position */ #define TPI_DEVTYPE_MajorType_Msk (0xFUL << TPI_DEVTYPE_MajorType_Pos) /*!< TPI DEVTYPE: MajorType Mask */ #define TPI_DEVTYPE_SubType_Pos 0 /*!< TPI DEVTYPE: SubType Position */ #define TPI_DEVTYPE_SubType_Msk (0xFUL /*<< TPI_DEVTYPE_SubType_Pos*/) /*!< TPI DEVTYPE: SubType Mask */ /*@}*/ /* end of group CMSIS_TPI */ #if (__MPU_PRESENT == 1) /** \ingroup CMSIS_core_register \defgroup CMSIS_MPU Memory Protection Unit (MPU) \brief Type definitions for the Memory Protection Unit (MPU) @{ */ /** \brief Structure type to access the Memory Protection Unit (MPU). */ typedef struct { __I uint32_t TYPE; /*!< Offset: 0x000 (R/ ) MPU Type Register */ __IO uint32_t CTRL; /*!< Offset: 0x004 (R/W) MPU Control Register */ __IO uint32_t RNR; /*!< Offset: 0x008 (R/W) MPU Region RNRber Register */ __IO uint32_t RBAR; /*!< Offset: 0x00C (R/W) MPU Region Base Address Register */ __IO uint32_t RASR; /*!< Offset: 0x010 (R/W) MPU Region Attribute and Size Register */ __IO uint32_t RBAR_A1; /*!< Offset: 0x014 (R/W) MPU Alias 1 Region Base Address Register */ __IO uint32_t RASR_A1; /*!< Offset: 0x018 (R/W) MPU Alias 1 Region Attribute and Size Register */ __IO uint32_t RBAR_A2; /*!< Offset: 0x01C (R/W) MPU Alias 2 Region Base Address Register */ __IO uint32_t RASR_A2; /*!< Offset: 0x020 (R/W) MPU Alias 2 Region Attribute and Size Register */ __IO uint32_t RBAR_A3; /*!< Offset: 0x024 (R/W) MPU Alias 3 Region Base Address Register */ __IO uint32_t RASR_A3; /*!< Offset: 0x028 (R/W) MPU Alias 3 Region Attribute and Size Register */ } MPU_Type; /* MPU Type Register */ #define MPU_TYPE_IREGION_Pos 16 /*!< MPU TYPE: IREGION Position */ #define MPU_TYPE_IREGION_Msk (0xFFUL << MPU_TYPE_IREGION_Pos) /*!< MPU TYPE: IREGION Mask */ #define MPU_TYPE_DREGION_Pos 8 /*!< MPU TYPE: DREGION Position */ #define MPU_TYPE_DREGION_Msk (0xFFUL << MPU_TYPE_DREGION_Pos) /*!< MPU TYPE: DREGION Mask */ #define MPU_TYPE_SEPARATE_Pos 0 /*!< MPU TYPE: SEPARATE Position */ #define MPU_TYPE_SEPARATE_Msk (1UL /*<< MPU_TYPE_SEPARATE_Pos*/) /*!< MPU TYPE: SEPARATE Mask */ /* MPU Control Register */ #define MPU_CTRL_PRIVDEFENA_Pos 2 /*!< MPU CTRL: PRIVDEFENA Position */ #define MPU_CTRL_PRIVDEFENA_Msk (1UL << MPU_CTRL_PRIVDEFENA_Pos) /*!< MPU CTRL: PRIVDEFENA Mask */ #define MPU_CTRL_HFNMIENA_Pos 1 /*!< MPU CTRL: HFNMIENA Position */ #define MPU_CTRL_HFNMIENA_Msk (1UL << MPU_CTRL_HFNMIENA_Pos) /*!< MPU CTRL: HFNMIENA Mask */ #define MPU_CTRL_ENABLE_Pos 0 /*!< MPU CTRL: ENABLE Position */ #define MPU_CTRL_ENABLE_Msk (1UL /*<< MPU_CTRL_ENABLE_Pos*/) /*!< MPU CTRL: ENABLE Mask */ /* MPU Region Number Register */ #define MPU_RNR_REGION_Pos 0 /*!< MPU RNR: REGION Position */ #define MPU_RNR_REGION_Msk (0xFFUL /*<< MPU_RNR_REGION_Pos*/) /*!< MPU RNR: REGION Mask */ /* MPU Region Base Address Register */ #define MPU_RBAR_ADDR_Pos 5 /*!< MPU RBAR: ADDR Position */ #define MPU_RBAR_ADDR_Msk (0x7FFFFFFUL << MPU_RBAR_ADDR_Pos) /*!< MPU RBAR: ADDR Mask */ #define MPU_RBAR_VALID_Pos 4 /*!< MPU RBAR: VALID Position */ #define MPU_RBAR_VALID_Msk (1UL << MPU_RBAR_VALID_Pos) /*!< MPU RBAR: VALID Mask */ #define MPU_RBAR_REGION_Pos 0 /*!< MPU RBAR: REGION Position */ #define MPU_RBAR_REGION_Msk (0xFUL /*<< MPU_RBAR_REGION_Pos*/) /*!< MPU RBAR: REGION Mask */ /* MPU Region Attribute and Size Register */ #define MPU_RASR_ATTRS_Pos 16 /*!< MPU RASR: MPU Region Attribute field Position */ #define MPU_RASR_ATTRS_Msk (0xFFFFUL << MPU_RASR_ATTRS_Pos) /*!< MPU RASR: MPU Region Attribute field Mask */ #define MPU_RASR_XN_Pos 28 /*!< MPU RASR: ATTRS.XN Position */ #define MPU_RASR_XN_Msk (1UL << MPU_RASR_XN_Pos) /*!< MPU RASR: ATTRS.XN Mask */ #define MPU_RASR_AP_Pos 24 /*!< MPU RASR: ATTRS.AP Position */ #define MPU_RASR_AP_Msk (0x7UL << MPU_RASR_AP_Pos) /*!< MPU RASR: ATTRS.AP Mask */ #define MPU_RASR_TEX_Pos 19 /*!< MPU RASR: ATTRS.TEX Position */ #define MPU_RASR_TEX_Msk (0x7UL << MPU_RASR_TEX_Pos) /*!< MPU RASR: ATTRS.TEX Mask */ #define MPU_RASR_S_Pos 18 /*!< MPU RASR: ATTRS.S Position */ #define MPU_RASR_S_Msk (1UL << MPU_RASR_S_Pos) /*!< MPU RASR: ATTRS.S Mask */ #define MPU_RASR_C_Pos 17 /*!< MPU RASR: ATTRS.C Position */ #define MPU_RASR_C_Msk (1UL << MPU_RASR_C_Pos) /*!< MPU RASR: ATTRS.C Mask */ #define MPU_RASR_B_Pos 16 /*!< MPU RASR: ATTRS.B Position */ #define MPU_RASR_B_Msk (1UL << MPU_RASR_B_Pos) /*!< MPU RASR: ATTRS.B Mask */ #define MPU_RASR_SRD_Pos 8 /*!< MPU RASR: Sub-Region Disable Position */ #define MPU_RASR_SRD_Msk (0xFFUL << MPU_RASR_SRD_Pos) /*!< MPU RASR: Sub-Region Disable Mask */ #define MPU_RASR_SIZE_Pos 1 /*!< MPU RASR: Region Size Field Position */ #define MPU_RASR_SIZE_Msk (0x1FUL << MPU_RASR_SIZE_Pos) /*!< MPU RASR: Region Size Field Mask */ #define MPU_RASR_ENABLE_Pos 0 /*!< MPU RASR: Region enable bit Position */ #define MPU_RASR_ENABLE_Msk (1UL /*<< MPU_RASR_ENABLE_Pos*/) /*!< MPU RASR: Region enable bit Disable Mask */ /*@} end of group CMSIS_MPU */ #endif /** \ingroup CMSIS_core_register \defgroup CMSIS_CoreDebug Core Debug Registers (CoreDebug) \brief Type definitions for the Core Debug Registers @{ */ /** \brief Structure type to access the Core Debug Register (CoreDebug). */ typedef struct { __IO uint32_t DHCSR; /*!< Offset: 0x000 (R/W) Debug Halting Control and Status Register */ __O uint32_t DCRSR; /*!< Offset: 0x004 ( /W) Debug Core Register Selector Register */ __IO uint32_t DCRDR; /*!< Offset: 0x008 (R/W) Debug Core Register Data Register */ __IO uint32_t DEMCR; /*!< Offset: 0x00C (R/W) Debug Exception and Monitor Control Register */ } CoreDebug_Type; /* Debug Halting Control and Status Register */ #define CoreDebug_DHCSR_DBGKEY_Pos 16 /*!< CoreDebug DHCSR: DBGKEY Position */ #define CoreDebug_DHCSR_DBGKEY_Msk (0xFFFFUL << CoreDebug_DHCSR_DBGKEY_Pos) /*!< CoreDebug DHCSR: DBGKEY Mask */ #define CoreDebug_DHCSR_S_RESET_ST_Pos 25 /*!< CoreDebug DHCSR: S_RESET_ST Position */ #define CoreDebug_DHCSR_S_RESET_ST_Msk (1UL << CoreDebug_DHCSR_S_RESET_ST_Pos) /*!< CoreDebug DHCSR: S_RESET_ST Mask */ #define CoreDebug_DHCSR_S_RETIRE_ST_Pos 24 /*!< CoreDebug DHCSR: S_RETIRE_ST Position */ #define CoreDebug_DHCSR_S_RETIRE_ST_Msk (1UL << CoreDebug_DHCSR_S_RETIRE_ST_Pos) /*!< CoreDebug DHCSR: S_RETIRE_ST Mask */ #define CoreDebug_DHCSR_S_LOCKUP_Pos 19 /*!< CoreDebug DHCSR: S_LOCKUP Position */ #define CoreDebug_DHCSR_S_LOCKUP_Msk (1UL << CoreDebug_DHCSR_S_LOCKUP_Pos) /*!< CoreDebug DHCSR: S_LOCKUP Mask */ #define CoreDebug_DHCSR_S_SLEEP_Pos 18 /*!< CoreDebug DHCSR: S_SLEEP Position */ #define CoreDebug_DHCSR_S_SLEEP_Msk (1UL << CoreDebug_DHCSR_S_SLEEP_Pos) /*!< CoreDebug DHCSR: S_SLEEP Mask */ #define CoreDebug_DHCSR_S_HALT_Pos 17 /*!< CoreDebug DHCSR: S_HALT Position */ #define CoreDebug_DHCSR_S_HALT_Msk (1UL << CoreDebug_DHCSR_S_HALT_Pos) /*!< CoreDebug DHCSR: S_HALT Mask */ #define CoreDebug_DHCSR_S_REGRDY_Pos 16 /*!< CoreDebug DHCSR: S_REGRDY Position */ #define CoreDebug_DHCSR_S_REGRDY_Msk (1UL << CoreDebug_DHCSR_S_REGRDY_Pos) /*!< CoreDebug DHCSR: S_REGRDY Mask */ #define CoreDebug_DHCSR_C_SNAPSTALL_Pos 5 /*!< CoreDebug DHCSR: C_SNAPSTALL Position */ #define CoreDebug_DHCSR_C_SNAPSTALL_Msk (1UL << CoreDebug_DHCSR_C_SNAPSTALL_Pos) /*!< CoreDebug DHCSR: C_SNAPSTALL Mask */ #define CoreDebug_DHCSR_C_MASKINTS_Pos 3 /*!< CoreDebug DHCSR: C_MASKINTS Position */ #define CoreDebug_DHCSR_C_MASKINTS_Msk (1UL << CoreDebug_DHCSR_C_MASKINTS_Pos) /*!< CoreDebug DHCSR: C_MASKINTS Mask */ #define CoreDebug_DHCSR_C_STEP_Pos 2 /*!< CoreDebug DHCSR: C_STEP Position */ #define CoreDebug_DHCSR_C_STEP_Msk (1UL << CoreDebug_DHCSR_C_STEP_Pos) /*!< CoreDebug DHCSR: C_STEP Mask */ #define CoreDebug_DHCSR_C_HALT_Pos 1 /*!< CoreDebug DHCSR: C_HALT Position */ #define CoreDebug_DHCSR_C_HALT_Msk (1UL << CoreDebug_DHCSR_C_HALT_Pos) /*!< CoreDebug DHCSR: C_HALT Mask */ #define CoreDebug_DHCSR_C_DEBUGEN_Pos 0 /*!< CoreDebug DHCSR: C_DEBUGEN Position */ #define CoreDebug_DHCSR_C_DEBUGEN_Msk (1UL /*<< CoreDebug_DHCSR_C_DEBUGEN_Pos*/) /*!< CoreDebug DHCSR: C_DEBUGEN Mask */ /* Debug Core Register Selector Register */ #define CoreDebug_DCRSR_REGWnR_Pos 16 /*!< CoreDebug DCRSR: REGWnR Position */ #define CoreDebug_DCRSR_REGWnR_Msk (1UL << CoreDebug_DCRSR_REGWnR_Pos) /*!< CoreDebug DCRSR: REGWnR Mask */ #define CoreDebug_DCRSR_REGSEL_Pos 0 /*!< CoreDebug DCRSR: REGSEL Position */ #define CoreDebug_DCRSR_REGSEL_Msk (0x1FUL /*<< CoreDebug_DCRSR_REGSEL_Pos*/) /*!< CoreDebug DCRSR: REGSEL Mask */ /* Debug Exception and Monitor Control Register */ #define CoreDebug_DEMCR_TRCENA_Pos 24 /*!< CoreDebug DEMCR: TRCENA Position */ #define CoreDebug_DEMCR_TRCENA_Msk (1UL << CoreDebug_DEMCR_TRCENA_Pos) /*!< CoreDebug DEMCR: TRCENA Mask */ #define CoreDebug_DEMCR_MON_REQ_Pos 19 /*!< CoreDebug DEMCR: MON_REQ Position */ #define CoreDebug_DEMCR_MON_REQ_Msk (1UL << CoreDebug_DEMCR_MON_REQ_Pos) /*!< CoreDebug DEMCR: MON_REQ Mask */ #define CoreDebug_DEMCR_MON_STEP_Pos 18 /*!< CoreDebug DEMCR: MON_STEP Position */ #define CoreDebug_DEMCR_MON_STEP_Msk (1UL << CoreDebug_DEMCR_MON_STEP_Pos) /*!< CoreDebug DEMCR: MON_STEP Mask */ #define CoreDebug_DEMCR_MON_PEND_Pos 17 /*!< CoreDebug DEMCR: MON_PEND Position */ #define CoreDebug_DEMCR_MON_PEND_Msk (1UL << CoreDebug_DEMCR_MON_PEND_Pos) /*!< CoreDebug DEMCR: MON_PEND Mask */ #define CoreDebug_DEMCR_MON_EN_Pos 16 /*!< CoreDebug DEMCR: MON_EN Position */ #define CoreDebug_DEMCR_MON_EN_Msk (1UL << CoreDebug_DEMCR_MON_EN_Pos) /*!< CoreDebug DEMCR: MON_EN Mask */ #define CoreDebug_DEMCR_VC_HARDERR_Pos 10 /*!< CoreDebug DEMCR: VC_HARDERR Position */ #define CoreDebug_DEMCR_VC_HARDERR_Msk (1UL << CoreDebug_DEMCR_VC_HARDERR_Pos) /*!< CoreDebug DEMCR: VC_HARDERR Mask */ #define CoreDebug_DEMCR_VC_INTERR_Pos 9 /*!< CoreDebug DEMCR: VC_INTERR Position */ #define CoreDebug_DEMCR_VC_INTERR_Msk (1UL << CoreDebug_DEMCR_VC_INTERR_Pos) /*!< CoreDebug DEMCR: VC_INTERR Mask */ #define CoreDebug_DEMCR_VC_BUSERR_Pos 8 /*!< CoreDebug DEMCR: VC_BUSERR Position */ #define CoreDebug_DEMCR_VC_BUSERR_Msk (1UL << CoreDebug_DEMCR_VC_BUSERR_Pos) /*!< CoreDebug DEMCR: VC_BUSERR Mask */ #define CoreDebug_DEMCR_VC_STATERR_Pos 7 /*!< CoreDebug DEMCR: VC_STATERR Position */ #define CoreDebug_DEMCR_VC_STATERR_Msk (1UL << CoreDebug_DEMCR_VC_STATERR_Pos) /*!< CoreDebug DEMCR: VC_STATERR Mask */ #define CoreDebug_DEMCR_VC_CHKERR_Pos 6 /*!< CoreDebug DEMCR: VC_CHKERR Position */ #define CoreDebug_DEMCR_VC_CHKERR_Msk (1UL << CoreDebug_DEMCR_VC_CHKERR_Pos) /*!< CoreDebug DEMCR: VC_CHKERR Mask */ #define CoreDebug_DEMCR_VC_NOCPERR_Pos 5 /*!< CoreDebug DEMCR: VC_NOCPERR Position */ #define CoreDebug_DEMCR_VC_NOCPERR_Msk (1UL << CoreDebug_DEMCR_VC_NOCPERR_Pos) /*!< CoreDebug DEMCR: VC_NOCPERR Mask */ #define CoreDebug_DEMCR_VC_MMERR_Pos 4 /*!< CoreDebug DEMCR: VC_MMERR Position */ #define CoreDebug_DEMCR_VC_MMERR_Msk (1UL << CoreDebug_DEMCR_VC_MMERR_Pos) /*!< CoreDebug DEMCR: VC_MMERR Mask */ #define CoreDebug_DEMCR_VC_CORERESET_Pos 0 /*!< CoreDebug DEMCR: VC_CORERESET Position */ #define CoreDebug_DEMCR_VC_CORERESET_Msk (1UL /*<< CoreDebug_DEMCR_VC_CORERESET_Pos*/) /*!< CoreDebug DEMCR: VC_CORERESET Mask */ /*@} end of group CMSIS_CoreDebug */ /** \ingroup CMSIS_core_register \defgroup CMSIS_core_base Core Definitions \brief Definitions for base addresses, unions, and structures. @{ */ /* Memory mapping of Cortex-M3 Hardware */ #define SCS_BASE (0xE000E000UL) /*!< System Control Space Base Address */ #define ITM_BASE (0xE0000000UL) /*!< ITM Base Address */ #define DWT_BASE (0xE0001000UL) /*!< DWT Base Address */ #define TPI_BASE (0xE0040000UL) /*!< TPI Base Address */ #define CoreDebug_BASE (0xE000EDF0UL) /*!< Core Debug Base Address */ #define SysTick_BASE (SCS_BASE + 0x0010UL) /*!< SysTick Base Address */ #define NVIC_BASE (SCS_BASE + 0x0100UL) /*!< NVIC Base Address */ #define SCB_BASE (SCS_BASE + 0x0D00UL) /*!< System Control Block Base Address */ #define SCnSCB ((SCnSCB_Type *) SCS_BASE ) /*!< System control Register not in SCB */ #define SCB ((SCB_Type *) SCB_BASE ) /*!< SCB configuration struct */ #define SysTick ((SysTick_Type *) SysTick_BASE ) /*!< SysTick configuration struct */ #define NVIC ((NVIC_Type *) NVIC_BASE ) /*!< NVIC configuration struct */ #define ITM ((ITM_Type *) ITM_BASE ) /*!< ITM configuration struct */ #define DWT ((DWT_Type *) DWT_BASE ) /*!< DWT configuration struct */ #define TPI ((TPI_Type *) TPI_BASE ) /*!< TPI configuration struct */ #define CoreDebug ((CoreDebug_Type *) CoreDebug_BASE) /*!< Core Debug configuration struct */ #if (__MPU_PRESENT == 1) #define MPU_BASE (SCS_BASE + 0x0D90UL) /*!< Memory Protection Unit */ #define MPU ((MPU_Type *) MPU_BASE ) /*!< Memory Protection Unit */ #endif /*@} */ /******************************************************************************* * Hardware Abstraction Layer Core Function Interface contains: - Core NVIC Functions - Core SysTick Functions - Core Debug Functions - Core Register Access Functions ******************************************************************************/ /** \defgroup CMSIS_Core_FunctionInterface Functions and Instructions Reference */ /* ########################## NVIC functions #################################### */ /** \ingroup CMSIS_Core_FunctionInterface \defgroup CMSIS_Core_NVICFunctions NVIC Functions \brief Functions that manage interrupts and exceptions via the NVIC. @{ */ /** \brief Set Priority Grouping The function sets the priority grouping field using the required unlock sequence. The parameter PriorityGroup is assigned to the field SCB->AIRCR [10:8] PRIGROUP field. Only values from 0..7 are used. In case of a conflict between priority grouping and available priority bits (__NVIC_PRIO_BITS), the smallest possible priority group is set. \param [in] PriorityGroup Priority grouping field. */ __STATIC_INLINE void NVIC_SetPriorityGrouping(uint32_t PriorityGroup) { uint32_t reg_value; uint32_t PriorityGroupTmp = (PriorityGroup & (uint32_t)0x07UL); /* only values 0..7 are used */ reg_value = SCB->AIRCR; /* read old register configuration */ reg_value &= ~((uint32_t)(SCB_AIRCR_VECTKEY_Msk | SCB_AIRCR_PRIGROUP_Msk)); /* clear bits to change */ reg_value = (reg_value | ((uint32_t)0x5FAUL << SCB_AIRCR_VECTKEY_Pos) | (PriorityGroupTmp << 8) ); /* Insert write key and priorty group */ SCB->AIRCR = reg_value; } /** \brief Get Priority Grouping The function reads the priority grouping field from the NVIC Interrupt Controller. \return Priority grouping field (SCB->AIRCR [10:8] PRIGROUP field). */ __STATIC_INLINE uint32_t NVIC_GetPriorityGrouping(void) { return ((uint32_t)((SCB->AIRCR & SCB_AIRCR_PRIGROUP_Msk) >> SCB_AIRCR_PRIGROUP_Pos)); } /** \brief Enable External Interrupt The function enables a device-specific interrupt in the NVIC interrupt controller. \param [in] IRQn External interrupt number. Value cannot be negative. */ __STATIC_INLINE void NVIC_EnableIRQ(IRQn_Type IRQn) { NVIC->ISER[(((uint32_t)(int32_t)IRQn) >> 5UL)] = (uint32_t)(1UL << (((uint32_t)(int32_t)IRQn) & 0x1FUL)); } /** \brief Disable External Interrupt The function disables a device-specific interrupt in the NVIC interrupt controller. \param [in] IRQn External interrupt number. Value cannot be negative. */ __STATIC_INLINE void NVIC_DisableIRQ(IRQn_Type IRQn) { NVIC->ICER[(((uint32_t)(int32_t)IRQn) >> 5UL)] = (uint32_t)(1UL << (((uint32_t)(int32_t)IRQn) & 0x1FUL)); } /** \brief Get Pending Interrupt The function reads the pending register in the NVIC and returns the pending bit for the specified interrupt. \param [in] IRQn Interrupt number. \return 0 Interrupt status is not pending. \return 1 Interrupt status is pending. */ __STATIC_INLINE uint32_t NVIC_GetPendingIRQ(IRQn_Type IRQn) { return((uint32_t)(((NVIC->ISPR[(((uint32_t)(int32_t)IRQn) >> 5UL)] & (1UL << (((uint32_t)(int32_t)IRQn) & 0x1FUL))) != 0UL) ? 1UL : 0UL)); } /** \brief Set Pending Interrupt The function sets the pending bit of an external interrupt. \param [in] IRQn Interrupt number. Value cannot be negative. */ __STATIC_INLINE void NVIC_SetPendingIRQ(IRQn_Type IRQn) { NVIC->ISPR[(((uint32_t)(int32_t)IRQn) >> 5UL)] = (uint32_t)(1UL << (((uint32_t)(int32_t)IRQn) & 0x1FUL)); } /** \brief Clear Pending Interrupt The function clears the pending bit of an external interrupt. \param [in] IRQn External interrupt number. Value cannot be negative. */ __STATIC_INLINE void NVIC_ClearPendingIRQ(IRQn_Type IRQn) { NVIC->ICPR[(((uint32_t)(int32_t)IRQn) >> 5UL)] = (uint32_t)(1UL << (((uint32_t)(int32_t)IRQn) & 0x1FUL)); } /** \brief Get Active Interrupt The function reads the active register in NVIC and returns the active bit. \param [in] IRQn Interrupt number. \return 0 Interrupt status is not active. \return 1 Interrupt status is active. */ __STATIC_INLINE uint32_t NVIC_GetActive(IRQn_Type IRQn) { return((uint32_t)(((NVIC->IABR[(((uint32_t)(int32_t)IRQn) >> 5UL)] & (1UL << (((uint32_t)(int32_t)IRQn) & 0x1FUL))) != 0UL) ? 1UL : 0UL)); } /** \brief Set Interrupt Priority The function sets the priority of an interrupt. \note The priority cannot be set for every core interrupt. \param [in] IRQn Interrupt number. \param [in] priority Priority to set. */ __STATIC_INLINE void NVIC_SetPriority(IRQn_Type IRQn, uint32_t priority) { if((int32_t)IRQn < 0) { SCB->SHP[(((uint32_t)(int32_t)IRQn) & 0xFUL)-4UL] = (uint8_t)((priority << (8 - __NVIC_PRIO_BITS)) & (uint32_t)0xFFUL); } else { NVIC->IP[((uint32_t)(int32_t)IRQn)] = (uint8_t)((priority << (8 - __NVIC_PRIO_BITS)) & (uint32_t)0xFFUL); } } /** \brief Get Interrupt Priority The function reads the priority of an interrupt. The interrupt number can be positive to specify an external (device specific) interrupt, or negative to specify an internal (core) interrupt. \param [in] IRQn Interrupt number. \return Interrupt Priority. Value is aligned automatically to the implemented priority bits of the microcontroller. */ __STATIC_INLINE uint32_t NVIC_GetPriority(IRQn_Type IRQn) { if((int32_t)IRQn < 0) { return(((uint32_t)SCB->SHP[(((uint32_t)(int32_t)IRQn) & 0xFUL)-4UL] >> (8 - __NVIC_PRIO_BITS))); } else { return(((uint32_t)NVIC->IP[((uint32_t)(int32_t)IRQn)] >> (8 - __NVIC_PRIO_BITS))); } } /** \brief Encode Priority The function encodes the priority for an interrupt with the given priority group, preemptive priority value, and subpriority value. In case of a conflict between priority grouping and available priority bits (__NVIC_PRIO_BITS), the smallest possible priority group is set. \param [in] PriorityGroup Used priority group. \param [in] PreemptPriority Preemptive priority value (starting from 0). \param [in] SubPriority Subpriority value (starting from 0). \return Encoded priority. Value can be used in the function \ref NVIC_SetPriority(). */ __STATIC_INLINE uint32_t NVIC_EncodePriority (uint32_t PriorityGroup, uint32_t PreemptPriority, uint32_t SubPriority) { uint32_t PriorityGroupTmp = (PriorityGroup & (uint32_t)0x07UL); /* only values 0..7 are used */ uint32_t PreemptPriorityBits; uint32_t SubPriorityBits; PreemptPriorityBits = ((7UL - PriorityGroupTmp) > (uint32_t)(__NVIC_PRIO_BITS)) ? (uint32_t)(__NVIC_PRIO_BITS) : (uint32_t)(7UL - PriorityGroupTmp); SubPriorityBits = ((PriorityGroupTmp + (uint32_t)(__NVIC_PRIO_BITS)) < (uint32_t)7UL) ? (uint32_t)0UL : (uint32_t)((PriorityGroupTmp - 7UL) + (uint32_t)(__NVIC_PRIO_BITS)); return ( ((PreemptPriority & (uint32_t)((1UL << (PreemptPriorityBits)) - 1UL)) << SubPriorityBits) | ((SubPriority & (uint32_t)((1UL << (SubPriorityBits )) - 1UL))) ); } /** \brief Decode Priority The function decodes an interrupt priority value with a given priority group to preemptive priority value and subpriority value. In case of a conflict between priority grouping and available priority bits (__NVIC_PRIO_BITS) the smallest possible priority group is set. \param [in] Priority Priority value, which can be retrieved with the function \ref NVIC_GetPriority(). \param [in] PriorityGroup Used priority group. \param [out] pPreemptPriority Preemptive priority value (starting from 0). \param [out] pSubPriority Subpriority value (starting from 0). */ __STATIC_INLINE void NVIC_DecodePriority (uint32_t Priority, uint32_t PriorityGroup, uint32_t* pPreemptPriority, uint32_t* pSubPriority) { uint32_t PriorityGroupTmp = (PriorityGroup & (uint32_t)0x07UL); /* only values 0..7 are used */ uint32_t PreemptPriorityBits; uint32_t SubPriorityBits; PreemptPriorityBits = ((7UL - PriorityGroupTmp) > (uint32_t)(__NVIC_PRIO_BITS)) ? (uint32_t)(__NVIC_PRIO_BITS) : (uint32_t)(7UL - PriorityGroupTmp); SubPriorityBits = ((PriorityGroupTmp + (uint32_t)(__NVIC_PRIO_BITS)) < (uint32_t)7UL) ? (uint32_t)0UL : (uint32_t)((PriorityGroupTmp - 7UL) + (uint32_t)(__NVIC_PRIO_BITS)); *pPreemptPriority = (Priority >> SubPriorityBits) & (uint32_t)((1UL << (PreemptPriorityBits)) - 1UL); *pSubPriority = (Priority ) & (uint32_t)((1UL << (SubPriorityBits )) - 1UL); } /** \brief System Reset The function initiates a system reset request to reset the MCU. */ __STATIC_INLINE void NVIC_SystemReset(void) { __DSB(); /* Ensure all outstanding memory accesses included buffered write are completed before reset */ SCB->AIRCR = (uint32_t)((0x5FAUL << SCB_AIRCR_VECTKEY_Pos) | (SCB->AIRCR & SCB_AIRCR_PRIGROUP_Msk) | SCB_AIRCR_SYSRESETREQ_Msk ); /* Keep priority group unchanged */ __DSB(); /* Ensure completion of memory access */ while(1) { __NOP(); } /* wait until reset */ } /*@} end of CMSIS_Core_NVICFunctions */ /* ################################## SysTick function ############################################ */ /** \ingroup CMSIS_Core_FunctionInterface \defgroup CMSIS_Core_SysTickFunctions SysTick Functions \brief Functions that configure the System. @{ */ #if (__Vendor_SysTickConfig == 0) /** \brief System Tick Configuration The function initializes the System Timer and its interrupt, and starts the System Tick Timer. Counter is in free running mode to generate periodic interrupts. \param [in] ticks Number of ticks between two interrupts. \return 0 Function succeeded. \return 1 Function failed. \note When the variable __Vendor_SysTickConfig is set to 1, then the function SysTick_Config is not included. In this case, the file device.h must contain a vendor-specific implementation of this function. */ __STATIC_INLINE uint32_t SysTick_Config(uint32_t ticks) { if ((ticks - 1UL) > SysTick_LOAD_RELOAD_Msk) { return (1UL); } /* Reload value impossible */ SysTick->LOAD = (uint32_t)(ticks - 1UL); /* set reload register */ NVIC_SetPriority (SysTick_IRQn, (1UL << __NVIC_PRIO_BITS) - 1UL); /* set Priority for Systick Interrupt */ SysTick->VAL = 0UL; /* Load the SysTick Counter Value */ SysTick->CTRL = SysTick_CTRL_CLKSOURCE_Msk | SysTick_CTRL_TICKINT_Msk | SysTick_CTRL_ENABLE_Msk; /* Enable SysTick IRQ and SysTick Timer */ return (0UL); /* Function successful */ } #endif /*@} end of CMSIS_Core_SysTickFunctions */ /* ##################################### Debug In/Output function ########################################### */ /** \ingroup CMSIS_Core_FunctionInterface \defgroup CMSIS_core_DebugFunctions ITM Functions \brief Functions that access the ITM debug interface. @{ */ extern volatile int32_t ITM_RxBuffer; /*!< External variable to receive characters. */ #define ITM_RXBUFFER_EMPTY 0x5AA55AA5 /*!< Value identifying \ref ITM_RxBuffer is ready for next character. */ /** \brief ITM Send Character The function transmits a character via the ITM channel 0, and \li Just returns when no debugger is connected that has booked the output. \li Is blocking when a debugger is connected, but the previous character sent has not been transmitted. \param [in] ch Character to transmit. \returns Character to transmit. */ __STATIC_INLINE uint32_t ITM_SendChar (uint32_t ch) { if (((ITM->TCR & ITM_TCR_ITMENA_Msk) != 0UL) && /* ITM enabled */ ((ITM->TER & 1UL ) != 0UL) ) /* ITM Port #0 enabled */ { while (ITM->PORT[0].u32 == 0UL) { __NOP(); } ITM->PORT[0].u8 = (uint8_t)ch; } return (ch); } /** \brief ITM Receive Character The function inputs a character via the external variable \ref ITM_RxBuffer. \return Received character. \return -1 No character pending. */ __STATIC_INLINE int32_t ITM_ReceiveChar (void) { int32_t ch = -1; /* no character available */ if (ITM_RxBuffer != ITM_RXBUFFER_EMPTY) { ch = ITM_RxBuffer; ITM_RxBuffer = ITM_RXBUFFER_EMPTY; /* ready for next character */ } return (ch); } /** \brief ITM Check Character The function checks whether a character is pending for reading in the variable \ref ITM_RxBuffer. \return 0 No character available. \return 1 Character available. */ __STATIC_INLINE int32_t ITM_CheckChar (void) { if (ITM_RxBuffer == ITM_RXBUFFER_EMPTY) { return (0); /* no character available */ } else { return (1); /* character available */ } } /*@} end of CMSIS_core_DebugFunctions */ #ifdef __cplusplus } #endif #endif /* __CORE_CM3_H_DEPENDANT */ #endif /* __CMSIS_GENERIC */ ================================================ FILE: Zelig/mbed/TARGET_NUCLEO_F401RE/core_cm4.h ================================================ /**************************************************************************//** * @file core_cm4.h * @brief CMSIS Cortex-M4 Core Peripheral Access Layer Header File * @version V4.10 * @date 18. March 2015 * * @note * ******************************************************************************/ /* Copyright (c) 2009 - 2015 ARM LIMITED All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: - Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. - Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. - Neither the name of ARM 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 COPYRIGHT HOLDERS AND 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. ---------------------------------------------------------------------------*/ #if defined ( __ICCARM__ ) #pragma system_include /* treat file as system include file for MISRA check */ #endif #ifndef __CORE_CM4_H_GENERIC #define __CORE_CM4_H_GENERIC #ifdef __cplusplus extern "C" { #endif /** \page CMSIS_MISRA_Exceptions MISRA-C:2004 Compliance Exceptions CMSIS violates the following MISRA-C:2004 rules: \li Required Rule 8.5, object/function definition in header file.
Function definitions in header files are used to allow 'inlining'. \li Required Rule 18.4, declaration of union type or object of union type: '{...}'.
Unions are used for effective representation of core registers. \li Advisory Rule 19.7, Function-like macro defined.
Function-like macros are used to allow more efficient code. */ /******************************************************************************* * CMSIS definitions ******************************************************************************/ /** \ingroup Cortex_M4 @{ */ /* CMSIS CM4 definitions */ #define __CM4_CMSIS_VERSION_MAIN (0x04) /*!< [31:16] CMSIS HAL main version */ #define __CM4_CMSIS_VERSION_SUB (0x00) /*!< [15:0] CMSIS HAL sub version */ #define __CM4_CMSIS_VERSION ((__CM4_CMSIS_VERSION_MAIN << 16) | \ __CM4_CMSIS_VERSION_SUB ) /*!< CMSIS HAL version number */ #define __CORTEX_M (0x04) /*!< Cortex-M Core */ #if defined ( __CC_ARM ) #define __ASM __asm /*!< asm keyword for ARM Compiler */ #define __INLINE __inline /*!< inline keyword for ARM Compiler */ #define __STATIC_INLINE static __inline #elif defined ( __GNUC__ ) #define __ASM __asm /*!< asm keyword for GNU Compiler */ #define __INLINE inline /*!< inline keyword for GNU Compiler */ #define __STATIC_INLINE static inline #elif defined ( __ICCARM__ ) #define __ASM __asm /*!< asm keyword for IAR Compiler */ #define __INLINE inline /*!< inline keyword for IAR Compiler. Only available in High optimization mode! */ #define __STATIC_INLINE static inline #elif defined ( __TMS470__ ) #define __ASM __asm /*!< asm keyword for TI CCS Compiler */ #define __STATIC_INLINE static inline #elif defined ( __TASKING__ ) #define __ASM __asm /*!< asm keyword for TASKING Compiler */ #define __INLINE inline /*!< inline keyword for TASKING Compiler */ #define __STATIC_INLINE static inline #elif defined ( __CSMC__ ) #define __packed #define __ASM _asm /*!< asm keyword for COSMIC Compiler */ #define __INLINE inline /*use -pc99 on compile line !< inline keyword for COSMIC Compiler */ #define __STATIC_INLINE static inline #endif /** __FPU_USED indicates whether an FPU is used or not. For this, __FPU_PRESENT has to be checked prior to making use of FPU specific registers and functions. */ #if defined ( __CC_ARM ) #if defined __TARGET_FPU_VFP #if (__FPU_PRESENT == 1) #define __FPU_USED 1 #else #warning "Compiler generates FPU instructions for a device without an FPU (check __FPU_PRESENT)" #define __FPU_USED 0 #endif #else #define __FPU_USED 0 #endif #elif defined ( __GNUC__ ) #if defined (__VFP_FP__) && !defined(__SOFTFP__) #if (__FPU_PRESENT == 1) #define __FPU_USED 1 #else #warning "Compiler generates FPU instructions for a device without an FPU (check __FPU_PRESENT)" #define __FPU_USED 0 #endif #else #define __FPU_USED 0 #endif #elif defined ( __ICCARM__ ) #if defined __ARMVFP__ #if (__FPU_PRESENT == 1) #define __FPU_USED 1 #else #warning "Compiler generates FPU instructions for a device without an FPU (check __FPU_PRESENT)" #define __FPU_USED 0 #endif #else #define __FPU_USED 0 #endif #elif defined ( __TMS470__ ) #if defined __TI_VFP_SUPPORT__ #if (__FPU_PRESENT == 1) #define __FPU_USED 1 #else #warning "Compiler generates FPU instructions for a device without an FPU (check __FPU_PRESENT)" #define __FPU_USED 0 #endif #else #define __FPU_USED 0 #endif #elif defined ( __TASKING__ ) #if defined __FPU_VFP__ #if (__FPU_PRESENT == 1) #define __FPU_USED 1 #else #error "Compiler generates FPU instructions for a device without an FPU (check __FPU_PRESENT)" #define __FPU_USED 0 #endif #else #define __FPU_USED 0 #endif #elif defined ( __CSMC__ ) /* Cosmic */ #if ( __CSMC__ & 0x400) // FPU present for parser #if (__FPU_PRESENT == 1) #define __FPU_USED 1 #else #error "Compiler generates FPU instructions for a device without an FPU (check __FPU_PRESENT)" #define __FPU_USED 0 #endif #else #define __FPU_USED 0 #endif #endif #include /* standard types definitions */ #include /* Core Instruction Access */ #include /* Core Function Access */ #include /* Compiler specific SIMD Intrinsics */ #ifdef __cplusplus } #endif #endif /* __CORE_CM4_H_GENERIC */ #ifndef __CMSIS_GENERIC #ifndef __CORE_CM4_H_DEPENDANT #define __CORE_CM4_H_DEPENDANT #ifdef __cplusplus extern "C" { #endif /* check device defines and use defaults */ #if defined __CHECK_DEVICE_DEFINES #ifndef __CM4_REV #define __CM4_REV 0x0000 #warning "__CM4_REV not defined in device header file; using default!" #endif #ifndef __FPU_PRESENT #define __FPU_PRESENT 0 #warning "__FPU_PRESENT not defined in device header file; using default!" #endif #ifndef __MPU_PRESENT #define __MPU_PRESENT 0 #warning "__MPU_PRESENT not defined in device header file; using default!" #endif #ifndef __NVIC_PRIO_BITS #define __NVIC_PRIO_BITS 4 #warning "__NVIC_PRIO_BITS not defined in device header file; using default!" #endif #ifndef __Vendor_SysTickConfig #define __Vendor_SysTickConfig 0 #warning "__Vendor_SysTickConfig not defined in device header file; using default!" #endif #endif /* IO definitions (access restrictions to peripheral registers) */ /** \defgroup CMSIS_glob_defs CMSIS Global Defines IO Type Qualifiers are used \li to specify the access to peripheral variables. \li for automatic generation of peripheral register debug information. */ #ifdef __cplusplus #define __I volatile /*!< Defines 'read only' permissions */ #else #define __I volatile const /*!< Defines 'read only' permissions */ #endif #define __O volatile /*!< Defines 'write only' permissions */ #define __IO volatile /*!< Defines 'read / write' permissions */ /*@} end of group Cortex_M4 */ /******************************************************************************* * Register Abstraction Core Register contain: - Core Register - Core NVIC Register - Core SCB Register - Core SysTick Register - Core Debug Register - Core MPU Register - Core FPU Register ******************************************************************************/ /** \defgroup CMSIS_core_register Defines and Type Definitions \brief Type definitions and defines for Cortex-M processor based devices. */ /** \ingroup CMSIS_core_register \defgroup CMSIS_CORE Status and Control Registers \brief Core Register type definitions. @{ */ /** \brief Union type to access the Application Program Status Register (APSR). */ typedef union { struct { uint32_t _reserved0:16; /*!< bit: 0..15 Reserved */ uint32_t GE:4; /*!< bit: 16..19 Greater than or Equal flags */ uint32_t _reserved1:7; /*!< bit: 20..26 Reserved */ uint32_t Q:1; /*!< bit: 27 Saturation condition flag */ uint32_t V:1; /*!< bit: 28 Overflow condition code flag */ uint32_t C:1; /*!< bit: 29 Carry condition code flag */ uint32_t Z:1; /*!< bit: 30 Zero condition code flag */ uint32_t N:1; /*!< bit: 31 Negative condition code flag */ } b; /*!< Structure used for bit access */ uint32_t w; /*!< Type used for word access */ } APSR_Type; /* APSR Register Definitions */ #define APSR_N_Pos 31 /*!< APSR: N Position */ #define APSR_N_Msk (1UL << APSR_N_Pos) /*!< APSR: N Mask */ #define APSR_Z_Pos 30 /*!< APSR: Z Position */ #define APSR_Z_Msk (1UL << APSR_Z_Pos) /*!< APSR: Z Mask */ #define APSR_C_Pos 29 /*!< APSR: C Position */ #define APSR_C_Msk (1UL << APSR_C_Pos) /*!< APSR: C Mask */ #define APSR_V_Pos 28 /*!< APSR: V Position */ #define APSR_V_Msk (1UL << APSR_V_Pos) /*!< APSR: V Mask */ #define APSR_Q_Pos 27 /*!< APSR: Q Position */ #define APSR_Q_Msk (1UL << APSR_Q_Pos) /*!< APSR: Q Mask */ #define APSR_GE_Pos 16 /*!< APSR: GE Position */ #define APSR_GE_Msk (0xFUL << APSR_GE_Pos) /*!< APSR: GE Mask */ /** \brief Union type to access the Interrupt Program Status Register (IPSR). */ typedef union { struct { uint32_t ISR:9; /*!< bit: 0.. 8 Exception number */ uint32_t _reserved0:23; /*!< bit: 9..31 Reserved */ } b; /*!< Structure used for bit access */ uint32_t w; /*!< Type used for word access */ } IPSR_Type; /* IPSR Register Definitions */ #define IPSR_ISR_Pos 0 /*!< IPSR: ISR Position */ #define IPSR_ISR_Msk (0x1FFUL /*<< IPSR_ISR_Pos*/) /*!< IPSR: ISR Mask */ /** \brief Union type to access the Special-Purpose Program Status Registers (xPSR). */ typedef union { struct { uint32_t ISR:9; /*!< bit: 0.. 8 Exception number */ uint32_t _reserved0:7; /*!< bit: 9..15 Reserved */ uint32_t GE:4; /*!< bit: 16..19 Greater than or Equal flags */ uint32_t _reserved1:4; /*!< bit: 20..23 Reserved */ uint32_t T:1; /*!< bit: 24 Thumb bit (read 0) */ uint32_t IT:2; /*!< bit: 25..26 saved IT state (read 0) */ uint32_t Q:1; /*!< bit: 27 Saturation condition flag */ uint32_t V:1; /*!< bit: 28 Overflow condition code flag */ uint32_t C:1; /*!< bit: 29 Carry condition code flag */ uint32_t Z:1; /*!< bit: 30 Zero condition code flag */ uint32_t N:1; /*!< bit: 31 Negative condition code flag */ } b; /*!< Structure used for bit access */ uint32_t w; /*!< Type used for word access */ } xPSR_Type; /* xPSR Register Definitions */ #define xPSR_N_Pos 31 /*!< xPSR: N Position */ #define xPSR_N_Msk (1UL << xPSR_N_Pos) /*!< xPSR: N Mask */ #define xPSR_Z_Pos 30 /*!< xPSR: Z Position */ #define xPSR_Z_Msk (1UL << xPSR_Z_Pos) /*!< xPSR: Z Mask */ #define xPSR_C_Pos 29 /*!< xPSR: C Position */ #define xPSR_C_Msk (1UL << xPSR_C_Pos) /*!< xPSR: C Mask */ #define xPSR_V_Pos 28 /*!< xPSR: V Position */ #define xPSR_V_Msk (1UL << xPSR_V_Pos) /*!< xPSR: V Mask */ #define xPSR_Q_Pos 27 /*!< xPSR: Q Position */ #define xPSR_Q_Msk (1UL << xPSR_Q_Pos) /*!< xPSR: Q Mask */ #define xPSR_IT_Pos 25 /*!< xPSR: IT Position */ #define xPSR_IT_Msk (3UL << xPSR_IT_Pos) /*!< xPSR: IT Mask */ #define xPSR_T_Pos 24 /*!< xPSR: T Position */ #define xPSR_T_Msk (1UL << xPSR_T_Pos) /*!< xPSR: T Mask */ #define xPSR_GE_Pos 16 /*!< xPSR: GE Position */ #define xPSR_GE_Msk (0xFUL << xPSR_GE_Pos) /*!< xPSR: GE Mask */ #define xPSR_ISR_Pos 0 /*!< xPSR: ISR Position */ #define xPSR_ISR_Msk (0x1FFUL /*<< xPSR_ISR_Pos*/) /*!< xPSR: ISR Mask */ /** \brief Union type to access the Control Registers (CONTROL). */ typedef union { struct { uint32_t nPRIV:1; /*!< bit: 0 Execution privilege in Thread mode */ uint32_t SPSEL:1; /*!< bit: 1 Stack to be used */ uint32_t FPCA:1; /*!< bit: 2 FP extension active flag */ uint32_t _reserved0:29; /*!< bit: 3..31 Reserved */ } b; /*!< Structure used for bit access */ uint32_t w; /*!< Type used for word access */ } CONTROL_Type; /* CONTROL Register Definitions */ #define CONTROL_FPCA_Pos 2 /*!< CONTROL: FPCA Position */ #define CONTROL_FPCA_Msk (1UL << CONTROL_FPCA_Pos) /*!< CONTROL: FPCA Mask */ #define CONTROL_SPSEL_Pos 1 /*!< CONTROL: SPSEL Position */ #define CONTROL_SPSEL_Msk (1UL << CONTROL_SPSEL_Pos) /*!< CONTROL: SPSEL Mask */ #define CONTROL_nPRIV_Pos 0 /*!< CONTROL: nPRIV Position */ #define CONTROL_nPRIV_Msk (1UL /*<< CONTROL_nPRIV_Pos*/) /*!< CONTROL: nPRIV Mask */ /*@} end of group CMSIS_CORE */ /** \ingroup CMSIS_core_register \defgroup CMSIS_NVIC Nested Vectored Interrupt Controller (NVIC) \brief Type definitions for the NVIC Registers @{ */ /** \brief Structure type to access the Nested Vectored Interrupt Controller (NVIC). */ typedef struct { __IO uint32_t ISER[8]; /*!< Offset: 0x000 (R/W) Interrupt Set Enable Register */ uint32_t RESERVED0[24]; __IO uint32_t ICER[8]; /*!< Offset: 0x080 (R/W) Interrupt Clear Enable Register */ uint32_t RSERVED1[24]; __IO uint32_t ISPR[8]; /*!< Offset: 0x100 (R/W) Interrupt Set Pending Register */ uint32_t RESERVED2[24]; __IO uint32_t ICPR[8]; /*!< Offset: 0x180 (R/W) Interrupt Clear Pending Register */ uint32_t RESERVED3[24]; __IO uint32_t IABR[8]; /*!< Offset: 0x200 (R/W) Interrupt Active bit Register */ uint32_t RESERVED4[56]; __IO uint8_t IP[240]; /*!< Offset: 0x300 (R/W) Interrupt Priority Register (8Bit wide) */ uint32_t RESERVED5[644]; __O uint32_t STIR; /*!< Offset: 0xE00 ( /W) Software Trigger Interrupt Register */ } NVIC_Type; /* Software Triggered Interrupt Register Definitions */ #define NVIC_STIR_INTID_Pos 0 /*!< STIR: INTLINESNUM Position */ #define NVIC_STIR_INTID_Msk (0x1FFUL /*<< NVIC_STIR_INTID_Pos*/) /*!< STIR: INTLINESNUM Mask */ /*@} end of group CMSIS_NVIC */ /** \ingroup CMSIS_core_register \defgroup CMSIS_SCB System Control Block (SCB) \brief Type definitions for the System Control Block Registers @{ */ /** \brief Structure type to access the System Control Block (SCB). */ typedef struct { __I uint32_t CPUID; /*!< Offset: 0x000 (R/ ) CPUID Base Register */ __IO uint32_t ICSR; /*!< Offset: 0x004 (R/W) Interrupt Control and State Register */ __IO uint32_t VTOR; /*!< Offset: 0x008 (R/W) Vector Table Offset Register */ __IO uint32_t AIRCR; /*!< Offset: 0x00C (R/W) Application Interrupt and Reset Control Register */ __IO uint32_t SCR; /*!< Offset: 0x010 (R/W) System Control Register */ __IO uint32_t CCR; /*!< Offset: 0x014 (R/W) Configuration Control Register */ __IO uint8_t SHP[12]; /*!< Offset: 0x018 (R/W) System Handlers Priority Registers (4-7, 8-11, 12-15) */ __IO uint32_t SHCSR; /*!< Offset: 0x024 (R/W) System Handler Control and State Register */ __IO uint32_t CFSR; /*!< Offset: 0x028 (R/W) Configurable Fault Status Register */ __IO uint32_t HFSR; /*!< Offset: 0x02C (R/W) HardFault Status Register */ __IO uint32_t DFSR; /*!< Offset: 0x030 (R/W) Debug Fault Status Register */ __IO uint32_t MMFAR; /*!< Offset: 0x034 (R/W) MemManage Fault Address Register */ __IO uint32_t BFAR; /*!< Offset: 0x038 (R/W) BusFault Address Register */ __IO uint32_t AFSR; /*!< Offset: 0x03C (R/W) Auxiliary Fault Status Register */ __I uint32_t PFR[2]; /*!< Offset: 0x040 (R/ ) Processor Feature Register */ __I uint32_t DFR; /*!< Offset: 0x048 (R/ ) Debug Feature Register */ __I uint32_t ADR; /*!< Offset: 0x04C (R/ ) Auxiliary Feature Register */ __I uint32_t MMFR[4]; /*!< Offset: 0x050 (R/ ) Memory Model Feature Register */ __I uint32_t ISAR[5]; /*!< Offset: 0x060 (R/ ) Instruction Set Attributes Register */ uint32_t RESERVED0[5]; __IO uint32_t CPACR; /*!< Offset: 0x088 (R/W) Coprocessor Access Control Register */ } SCB_Type; /* SCB CPUID Register Definitions */ #define SCB_CPUID_IMPLEMENTER_Pos 24 /*!< SCB CPUID: IMPLEMENTER Position */ #define SCB_CPUID_IMPLEMENTER_Msk (0xFFUL << SCB_CPUID_IMPLEMENTER_Pos) /*!< SCB CPUID: IMPLEMENTER Mask */ #define SCB_CPUID_VARIANT_Pos 20 /*!< SCB CPUID: VARIANT Position */ #define SCB_CPUID_VARIANT_Msk (0xFUL << SCB_CPUID_VARIANT_Pos) /*!< SCB CPUID: VARIANT Mask */ #define SCB_CPUID_ARCHITECTURE_Pos 16 /*!< SCB CPUID: ARCHITECTURE Position */ #define SCB_CPUID_ARCHITECTURE_Msk (0xFUL << SCB_CPUID_ARCHITECTURE_Pos) /*!< SCB CPUID: ARCHITECTURE Mask */ #define SCB_CPUID_PARTNO_Pos 4 /*!< SCB CPUID: PARTNO Position */ #define SCB_CPUID_PARTNO_Msk (0xFFFUL << SCB_CPUID_PARTNO_Pos) /*!< SCB CPUID: PARTNO Mask */ #define SCB_CPUID_REVISION_Pos 0 /*!< SCB CPUID: REVISION Position */ #define SCB_CPUID_REVISION_Msk (0xFUL /*<< SCB_CPUID_REVISION_Pos*/) /*!< SCB CPUID: REVISION Mask */ /* SCB Interrupt Control State Register Definitions */ #define SCB_ICSR_NMIPENDSET_Pos 31 /*!< SCB ICSR: NMIPENDSET Position */ #define SCB_ICSR_NMIPENDSET_Msk (1UL << SCB_ICSR_NMIPENDSET_Pos) /*!< SCB ICSR: NMIPENDSET Mask */ #define SCB_ICSR_PENDSVSET_Pos 28 /*!< SCB ICSR: PENDSVSET Position */ #define SCB_ICSR_PENDSVSET_Msk (1UL << SCB_ICSR_PENDSVSET_Pos) /*!< SCB ICSR: PENDSVSET Mask */ #define SCB_ICSR_PENDSVCLR_Pos 27 /*!< SCB ICSR: PENDSVCLR Position */ #define SCB_ICSR_PENDSVCLR_Msk (1UL << SCB_ICSR_PENDSVCLR_Pos) /*!< SCB ICSR: PENDSVCLR Mask */ #define SCB_ICSR_PENDSTSET_Pos 26 /*!< SCB ICSR: PENDSTSET Position */ #define SCB_ICSR_PENDSTSET_Msk (1UL << SCB_ICSR_PENDSTSET_Pos) /*!< SCB ICSR: PENDSTSET Mask */ #define SCB_ICSR_PENDSTCLR_Pos 25 /*!< SCB ICSR: PENDSTCLR Position */ #define SCB_ICSR_PENDSTCLR_Msk (1UL << SCB_ICSR_PENDSTCLR_Pos) /*!< SCB ICSR: PENDSTCLR Mask */ #define SCB_ICSR_ISRPREEMPT_Pos 23 /*!< SCB ICSR: ISRPREEMPT Position */ #define SCB_ICSR_ISRPREEMPT_Msk (1UL << SCB_ICSR_ISRPREEMPT_Pos) /*!< SCB ICSR: ISRPREEMPT Mask */ #define SCB_ICSR_ISRPENDING_Pos 22 /*!< SCB ICSR: ISRPENDING Position */ #define SCB_ICSR_ISRPENDING_Msk (1UL << SCB_ICSR_ISRPENDING_Pos) /*!< SCB ICSR: ISRPENDING Mask */ #define SCB_ICSR_VECTPENDING_Pos 12 /*!< SCB ICSR: VECTPENDING Position */ #define SCB_ICSR_VECTPENDING_Msk (0x1FFUL << SCB_ICSR_VECTPENDING_Pos) /*!< SCB ICSR: VECTPENDING Mask */ #define SCB_ICSR_RETTOBASE_Pos 11 /*!< SCB ICSR: RETTOBASE Position */ #define SCB_ICSR_RETTOBASE_Msk (1UL << SCB_ICSR_RETTOBASE_Pos) /*!< SCB ICSR: RETTOBASE Mask */ #define SCB_ICSR_VECTACTIVE_Pos 0 /*!< SCB ICSR: VECTACTIVE Position */ #define SCB_ICSR_VECTACTIVE_Msk (0x1FFUL /*<< SCB_ICSR_VECTACTIVE_Pos*/) /*!< SCB ICSR: VECTACTIVE Mask */ /* SCB Vector Table Offset Register Definitions */ #define SCB_VTOR_TBLOFF_Pos 7 /*!< SCB VTOR: TBLOFF Position */ #define SCB_VTOR_TBLOFF_Msk (0x1FFFFFFUL << SCB_VTOR_TBLOFF_Pos) /*!< SCB VTOR: TBLOFF Mask */ /* SCB Application Interrupt and Reset Control Register Definitions */ #define SCB_AIRCR_VECTKEY_Pos 16 /*!< SCB AIRCR: VECTKEY Position */ #define SCB_AIRCR_VECTKEY_Msk (0xFFFFUL << SCB_AIRCR_VECTKEY_Pos) /*!< SCB AIRCR: VECTKEY Mask */ #define SCB_AIRCR_VECTKEYSTAT_Pos 16 /*!< SCB AIRCR: VECTKEYSTAT Position */ #define SCB_AIRCR_VECTKEYSTAT_Msk (0xFFFFUL << SCB_AIRCR_VECTKEYSTAT_Pos) /*!< SCB AIRCR: VECTKEYSTAT Mask */ #define SCB_AIRCR_ENDIANESS_Pos 15 /*!< SCB AIRCR: ENDIANESS Position */ #define SCB_AIRCR_ENDIANESS_Msk (1UL << SCB_AIRCR_ENDIANESS_Pos) /*!< SCB AIRCR: ENDIANESS Mask */ #define SCB_AIRCR_PRIGROUP_Pos 8 /*!< SCB AIRCR: PRIGROUP Position */ #define SCB_AIRCR_PRIGROUP_Msk (7UL << SCB_AIRCR_PRIGROUP_Pos) /*!< SCB AIRCR: PRIGROUP Mask */ #define SCB_AIRCR_SYSRESETREQ_Pos 2 /*!< SCB AIRCR: SYSRESETREQ Position */ #define SCB_AIRCR_SYSRESETREQ_Msk (1UL << SCB_AIRCR_SYSRESETREQ_Pos) /*!< SCB AIRCR: SYSRESETREQ Mask */ #define SCB_AIRCR_VECTCLRACTIVE_Pos 1 /*!< SCB AIRCR: VECTCLRACTIVE Position */ #define SCB_AIRCR_VECTCLRACTIVE_Msk (1UL << SCB_AIRCR_VECTCLRACTIVE_Pos) /*!< SCB AIRCR: VECTCLRACTIVE Mask */ #define SCB_AIRCR_VECTRESET_Pos 0 /*!< SCB AIRCR: VECTRESET Position */ #define SCB_AIRCR_VECTRESET_Msk (1UL /*<< SCB_AIRCR_VECTRESET_Pos*/) /*!< SCB AIRCR: VECTRESET Mask */ /* SCB System Control Register Definitions */ #define SCB_SCR_SEVONPEND_Pos 4 /*!< SCB SCR: SEVONPEND Position */ #define SCB_SCR_SEVONPEND_Msk (1UL << SCB_SCR_SEVONPEND_Pos) /*!< SCB SCR: SEVONPEND Mask */ #define SCB_SCR_SLEEPDEEP_Pos 2 /*!< SCB SCR: SLEEPDEEP Position */ #define SCB_SCR_SLEEPDEEP_Msk (1UL << SCB_SCR_SLEEPDEEP_Pos) /*!< SCB SCR: SLEEPDEEP Mask */ #define SCB_SCR_SLEEPONEXIT_Pos 1 /*!< SCB SCR: SLEEPONEXIT Position */ #define SCB_SCR_SLEEPONEXIT_Msk (1UL << SCB_SCR_SLEEPONEXIT_Pos) /*!< SCB SCR: SLEEPONEXIT Mask */ /* SCB Configuration Control Register Definitions */ #define SCB_CCR_STKALIGN_Pos 9 /*!< SCB CCR: STKALIGN Position */ #define SCB_CCR_STKALIGN_Msk (1UL << SCB_CCR_STKALIGN_Pos) /*!< SCB CCR: STKALIGN Mask */ #define SCB_CCR_BFHFNMIGN_Pos 8 /*!< SCB CCR: BFHFNMIGN Position */ #define SCB_CCR_BFHFNMIGN_Msk (1UL << SCB_CCR_BFHFNMIGN_Pos) /*!< SCB CCR: BFHFNMIGN Mask */ #define SCB_CCR_DIV_0_TRP_Pos 4 /*!< SCB CCR: DIV_0_TRP Position */ #define SCB_CCR_DIV_0_TRP_Msk (1UL << SCB_CCR_DIV_0_TRP_Pos) /*!< SCB CCR: DIV_0_TRP Mask */ #define SCB_CCR_UNALIGN_TRP_Pos 3 /*!< SCB CCR: UNALIGN_TRP Position */ #define SCB_CCR_UNALIGN_TRP_Msk (1UL << SCB_CCR_UNALIGN_TRP_Pos) /*!< SCB CCR: UNALIGN_TRP Mask */ #define SCB_CCR_USERSETMPEND_Pos 1 /*!< SCB CCR: USERSETMPEND Position */ #define SCB_CCR_USERSETMPEND_Msk (1UL << SCB_CCR_USERSETMPEND_Pos) /*!< SCB CCR: USERSETMPEND Mask */ #define SCB_CCR_NONBASETHRDENA_Pos 0 /*!< SCB CCR: NONBASETHRDENA Position */ #define SCB_CCR_NONBASETHRDENA_Msk (1UL /*<< SCB_CCR_NONBASETHRDENA_Pos*/) /*!< SCB CCR: NONBASETHRDENA Mask */ /* SCB System Handler Control and State Register Definitions */ #define SCB_SHCSR_USGFAULTENA_Pos 18 /*!< SCB SHCSR: USGFAULTENA Position */ #define SCB_SHCSR_USGFAULTENA_Msk (1UL << SCB_SHCSR_USGFAULTENA_Pos) /*!< SCB SHCSR: USGFAULTENA Mask */ #define SCB_SHCSR_BUSFAULTENA_Pos 17 /*!< SCB SHCSR: BUSFAULTENA Position */ #define SCB_SHCSR_BUSFAULTENA_Msk (1UL << SCB_SHCSR_BUSFAULTENA_Pos) /*!< SCB SHCSR: BUSFAULTENA Mask */ #define SCB_SHCSR_MEMFAULTENA_Pos 16 /*!< SCB SHCSR: MEMFAULTENA Position */ #define SCB_SHCSR_MEMFAULTENA_Msk (1UL << SCB_SHCSR_MEMFAULTENA_Pos) /*!< SCB SHCSR: MEMFAULTENA Mask */ #define SCB_SHCSR_SVCALLPENDED_Pos 15 /*!< SCB SHCSR: SVCALLPENDED Position */ #define SCB_SHCSR_SVCALLPENDED_Msk (1UL << SCB_SHCSR_SVCALLPENDED_Pos) /*!< SCB SHCSR: SVCALLPENDED Mask */ #define SCB_SHCSR_BUSFAULTPENDED_Pos 14 /*!< SCB SHCSR: BUSFAULTPENDED Position */ #define SCB_SHCSR_BUSFAULTPENDED_Msk (1UL << SCB_SHCSR_BUSFAULTPENDED_Pos) /*!< SCB SHCSR: BUSFAULTPENDED Mask */ #define SCB_SHCSR_MEMFAULTPENDED_Pos 13 /*!< SCB SHCSR: MEMFAULTPENDED Position */ #define SCB_SHCSR_MEMFAULTPENDED_Msk (1UL << SCB_SHCSR_MEMFAULTPENDED_Pos) /*!< SCB SHCSR: MEMFAULTPENDED Mask */ #define SCB_SHCSR_USGFAULTPENDED_Pos 12 /*!< SCB SHCSR: USGFAULTPENDED Position */ #define SCB_SHCSR_USGFAULTPENDED_Msk (1UL << SCB_SHCSR_USGFAULTPENDED_Pos) /*!< SCB SHCSR: USGFAULTPENDED Mask */ #define SCB_SHCSR_SYSTICKACT_Pos 11 /*!< SCB SHCSR: SYSTICKACT Position */ #define SCB_SHCSR_SYSTICKACT_Msk (1UL << SCB_SHCSR_SYSTICKACT_Pos) /*!< SCB SHCSR: SYSTICKACT Mask */ #define SCB_SHCSR_PENDSVACT_Pos 10 /*!< SCB SHCSR: PENDSVACT Position */ #define SCB_SHCSR_PENDSVACT_Msk (1UL << SCB_SHCSR_PENDSVACT_Pos) /*!< SCB SHCSR: PENDSVACT Mask */ #define SCB_SHCSR_MONITORACT_Pos 8 /*!< SCB SHCSR: MONITORACT Position */ #define SCB_SHCSR_MONITORACT_Msk (1UL << SCB_SHCSR_MONITORACT_Pos) /*!< SCB SHCSR: MONITORACT Mask */ #define SCB_SHCSR_SVCALLACT_Pos 7 /*!< SCB SHCSR: SVCALLACT Position */ #define SCB_SHCSR_SVCALLACT_Msk (1UL << SCB_SHCSR_SVCALLACT_Pos) /*!< SCB SHCSR: SVCALLACT Mask */ #define SCB_SHCSR_USGFAULTACT_Pos 3 /*!< SCB SHCSR: USGFAULTACT Position */ #define SCB_SHCSR_USGFAULTACT_Msk (1UL << SCB_SHCSR_USGFAULTACT_Pos) /*!< SCB SHCSR: USGFAULTACT Mask */ #define SCB_SHCSR_BUSFAULTACT_Pos 1 /*!< SCB SHCSR: BUSFAULTACT Position */ #define SCB_SHCSR_BUSFAULTACT_Msk (1UL << SCB_SHCSR_BUSFAULTACT_Pos) /*!< SCB SHCSR: BUSFAULTACT Mask */ #define SCB_SHCSR_MEMFAULTACT_Pos 0 /*!< SCB SHCSR: MEMFAULTACT Position */ #define SCB_SHCSR_MEMFAULTACT_Msk (1UL /*<< SCB_SHCSR_MEMFAULTACT_Pos*/) /*!< SCB SHCSR: MEMFAULTACT Mask */ /* SCB Configurable Fault Status Registers Definitions */ #define SCB_CFSR_USGFAULTSR_Pos 16 /*!< SCB CFSR: Usage Fault Status Register Position */ #define SCB_CFSR_USGFAULTSR_Msk (0xFFFFUL << SCB_CFSR_USGFAULTSR_Pos) /*!< SCB CFSR: Usage Fault Status Register Mask */ #define SCB_CFSR_BUSFAULTSR_Pos 8 /*!< SCB CFSR: Bus Fault Status Register Position */ #define SCB_CFSR_BUSFAULTSR_Msk (0xFFUL << SCB_CFSR_BUSFAULTSR_Pos) /*!< SCB CFSR: Bus Fault Status Register Mask */ #define SCB_CFSR_MEMFAULTSR_Pos 0 /*!< SCB CFSR: Memory Manage Fault Status Register Position */ #define SCB_CFSR_MEMFAULTSR_Msk (0xFFUL /*<< SCB_CFSR_MEMFAULTSR_Pos*/) /*!< SCB CFSR: Memory Manage Fault Status Register Mask */ /* SCB Hard Fault Status Registers Definitions */ #define SCB_HFSR_DEBUGEVT_Pos 31 /*!< SCB HFSR: DEBUGEVT Position */ #define SCB_HFSR_DEBUGEVT_Msk (1UL << SCB_HFSR_DEBUGEVT_Pos) /*!< SCB HFSR: DEBUGEVT Mask */ #define SCB_HFSR_FORCED_Pos 30 /*!< SCB HFSR: FORCED Position */ #define SCB_HFSR_FORCED_Msk (1UL << SCB_HFSR_FORCED_Pos) /*!< SCB HFSR: FORCED Mask */ #define SCB_HFSR_VECTTBL_Pos 1 /*!< SCB HFSR: VECTTBL Position */ #define SCB_HFSR_VECTTBL_Msk (1UL << SCB_HFSR_VECTTBL_Pos) /*!< SCB HFSR: VECTTBL Mask */ /* SCB Debug Fault Status Register Definitions */ #define SCB_DFSR_EXTERNAL_Pos 4 /*!< SCB DFSR: EXTERNAL Position */ #define SCB_DFSR_EXTERNAL_Msk (1UL << SCB_DFSR_EXTERNAL_Pos) /*!< SCB DFSR: EXTERNAL Mask */ #define SCB_DFSR_VCATCH_Pos 3 /*!< SCB DFSR: VCATCH Position */ #define SCB_DFSR_VCATCH_Msk (1UL << SCB_DFSR_VCATCH_Pos) /*!< SCB DFSR: VCATCH Mask */ #define SCB_DFSR_DWTTRAP_Pos 2 /*!< SCB DFSR: DWTTRAP Position */ #define SCB_DFSR_DWTTRAP_Msk (1UL << SCB_DFSR_DWTTRAP_Pos) /*!< SCB DFSR: DWTTRAP Mask */ #define SCB_DFSR_BKPT_Pos 1 /*!< SCB DFSR: BKPT Position */ #define SCB_DFSR_BKPT_Msk (1UL << SCB_DFSR_BKPT_Pos) /*!< SCB DFSR: BKPT Mask */ #define SCB_DFSR_HALTED_Pos 0 /*!< SCB DFSR: HALTED Position */ #define SCB_DFSR_HALTED_Msk (1UL /*<< SCB_DFSR_HALTED_Pos*/) /*!< SCB DFSR: HALTED Mask */ /*@} end of group CMSIS_SCB */ /** \ingroup CMSIS_core_register \defgroup CMSIS_SCnSCB System Controls not in SCB (SCnSCB) \brief Type definitions for the System Control and ID Register not in the SCB @{ */ /** \brief Structure type to access the System Control and ID Register not in the SCB. */ typedef struct { uint32_t RESERVED0[1]; __I uint32_t ICTR; /*!< Offset: 0x004 (R/ ) Interrupt Controller Type Register */ __IO uint32_t ACTLR; /*!< Offset: 0x008 (R/W) Auxiliary Control Register */ } SCnSCB_Type; /* Interrupt Controller Type Register Definitions */ #define SCnSCB_ICTR_INTLINESNUM_Pos 0 /*!< ICTR: INTLINESNUM Position */ #define SCnSCB_ICTR_INTLINESNUM_Msk (0xFUL /*<< SCnSCB_ICTR_INTLINESNUM_Pos*/) /*!< ICTR: INTLINESNUM Mask */ /* Auxiliary Control Register Definitions */ #define SCnSCB_ACTLR_DISOOFP_Pos 9 /*!< ACTLR: DISOOFP Position */ #define SCnSCB_ACTLR_DISOOFP_Msk (1UL << SCnSCB_ACTLR_DISOOFP_Pos) /*!< ACTLR: DISOOFP Mask */ #define SCnSCB_ACTLR_DISFPCA_Pos 8 /*!< ACTLR: DISFPCA Position */ #define SCnSCB_ACTLR_DISFPCA_Msk (1UL << SCnSCB_ACTLR_DISFPCA_Pos) /*!< ACTLR: DISFPCA Mask */ #define SCnSCB_ACTLR_DISFOLD_Pos 2 /*!< ACTLR: DISFOLD Position */ #define SCnSCB_ACTLR_DISFOLD_Msk (1UL << SCnSCB_ACTLR_DISFOLD_Pos) /*!< ACTLR: DISFOLD Mask */ #define SCnSCB_ACTLR_DISDEFWBUF_Pos 1 /*!< ACTLR: DISDEFWBUF Position */ #define SCnSCB_ACTLR_DISDEFWBUF_Msk (1UL << SCnSCB_ACTLR_DISDEFWBUF_Pos) /*!< ACTLR: DISDEFWBUF Mask */ #define SCnSCB_ACTLR_DISMCYCINT_Pos 0 /*!< ACTLR: DISMCYCINT Position */ #define SCnSCB_ACTLR_DISMCYCINT_Msk (1UL /*<< SCnSCB_ACTLR_DISMCYCINT_Pos*/) /*!< ACTLR: DISMCYCINT Mask */ /*@} end of group CMSIS_SCnotSCB */ /** \ingroup CMSIS_core_register \defgroup CMSIS_SysTick System Tick Timer (SysTick) \brief Type definitions for the System Timer Registers. @{ */ /** \brief Structure type to access the System Timer (SysTick). */ typedef struct { __IO uint32_t CTRL; /*!< Offset: 0x000 (R/W) SysTick Control and Status Register */ __IO uint32_t LOAD; /*!< Offset: 0x004 (R/W) SysTick Reload Value Register */ __IO uint32_t VAL; /*!< Offset: 0x008 (R/W) SysTick Current Value Register */ __I uint32_t CALIB; /*!< Offset: 0x00C (R/ ) SysTick Calibration Register */ } SysTick_Type; /* SysTick Control / Status Register Definitions */ #define SysTick_CTRL_COUNTFLAG_Pos 16 /*!< SysTick CTRL: COUNTFLAG Position */ #define SysTick_CTRL_COUNTFLAG_Msk (1UL << SysTick_CTRL_COUNTFLAG_Pos) /*!< SysTick CTRL: COUNTFLAG Mask */ #define SysTick_CTRL_CLKSOURCE_Pos 2 /*!< SysTick CTRL: CLKSOURCE Position */ #define SysTick_CTRL_CLKSOURCE_Msk (1UL << SysTick_CTRL_CLKSOURCE_Pos) /*!< SysTick CTRL: CLKSOURCE Mask */ #define SysTick_CTRL_TICKINT_Pos 1 /*!< SysTick CTRL: TICKINT Position */ #define SysTick_CTRL_TICKINT_Msk (1UL << SysTick_CTRL_TICKINT_Pos) /*!< SysTick CTRL: TICKINT Mask */ #define SysTick_CTRL_ENABLE_Pos 0 /*!< SysTick CTRL: ENABLE Position */ #define SysTick_CTRL_ENABLE_Msk (1UL /*<< SysTick_CTRL_ENABLE_Pos*/) /*!< SysTick CTRL: ENABLE Mask */ /* SysTick Reload Register Definitions */ #define SysTick_LOAD_RELOAD_Pos 0 /*!< SysTick LOAD: RELOAD Position */ #define SysTick_LOAD_RELOAD_Msk (0xFFFFFFUL /*<< SysTick_LOAD_RELOAD_Pos*/) /*!< SysTick LOAD: RELOAD Mask */ /* SysTick Current Register Definitions */ #define SysTick_VAL_CURRENT_Pos 0 /*!< SysTick VAL: CURRENT Position */ #define SysTick_VAL_CURRENT_Msk (0xFFFFFFUL /*<< SysTick_VAL_CURRENT_Pos*/) /*!< SysTick VAL: CURRENT Mask */ /* SysTick Calibration Register Definitions */ #define SysTick_CALIB_NOREF_Pos 31 /*!< SysTick CALIB: NOREF Position */ #define SysTick_CALIB_NOREF_Msk (1UL << SysTick_CALIB_NOREF_Pos) /*!< SysTick CALIB: NOREF Mask */ #define SysTick_CALIB_SKEW_Pos 30 /*!< SysTick CALIB: SKEW Position */ #define SysTick_CALIB_SKEW_Msk (1UL << SysTick_CALIB_SKEW_Pos) /*!< SysTick CALIB: SKEW Mask */ #define SysTick_CALIB_TENMS_Pos 0 /*!< SysTick CALIB: TENMS Position */ #define SysTick_CALIB_TENMS_Msk (0xFFFFFFUL /*<< SysTick_CALIB_TENMS_Pos*/) /*!< SysTick CALIB: TENMS Mask */ /*@} end of group CMSIS_SysTick */ /** \ingroup CMSIS_core_register \defgroup CMSIS_ITM Instrumentation Trace Macrocell (ITM) \brief Type definitions for the Instrumentation Trace Macrocell (ITM) @{ */ /** \brief Structure type to access the Instrumentation Trace Macrocell Register (ITM). */ typedef struct { __O union { __O uint8_t u8; /*!< Offset: 0x000 ( /W) ITM Stimulus Port 8-bit */ __O uint16_t u16; /*!< Offset: 0x000 ( /W) ITM Stimulus Port 16-bit */ __O uint32_t u32; /*!< Offset: 0x000 ( /W) ITM Stimulus Port 32-bit */ } PORT [32]; /*!< Offset: 0x000 ( /W) ITM Stimulus Port Registers */ uint32_t RESERVED0[864]; __IO uint32_t TER; /*!< Offset: 0xE00 (R/W) ITM Trace Enable Register */ uint32_t RESERVED1[15]; __IO uint32_t TPR; /*!< Offset: 0xE40 (R/W) ITM Trace Privilege Register */ uint32_t RESERVED2[15]; __IO uint32_t TCR; /*!< Offset: 0xE80 (R/W) ITM Trace Control Register */ uint32_t RESERVED3[29]; __O uint32_t IWR; /*!< Offset: 0xEF8 ( /W) ITM Integration Write Register */ __I uint32_t IRR; /*!< Offset: 0xEFC (R/ ) ITM Integration Read Register */ __IO uint32_t IMCR; /*!< Offset: 0xF00 (R/W) ITM Integration Mode Control Register */ uint32_t RESERVED4[43]; __O uint32_t LAR; /*!< Offset: 0xFB0 ( /W) ITM Lock Access Register */ __I uint32_t LSR; /*!< Offset: 0xFB4 (R/ ) ITM Lock Status Register */ uint32_t RESERVED5[6]; __I uint32_t PID4; /*!< Offset: 0xFD0 (R/ ) ITM Peripheral Identification Register #4 */ __I uint32_t PID5; /*!< Offset: 0xFD4 (R/ ) ITM Peripheral Identification Register #5 */ __I uint32_t PID6; /*!< Offset: 0xFD8 (R/ ) ITM Peripheral Identification Register #6 */ __I uint32_t PID7; /*!< Offset: 0xFDC (R/ ) ITM Peripheral Identification Register #7 */ __I uint32_t PID0; /*!< Offset: 0xFE0 (R/ ) ITM Peripheral Identification Register #0 */ __I uint32_t PID1; /*!< Offset: 0xFE4 (R/ ) ITM Peripheral Identification Register #1 */ __I uint32_t PID2; /*!< Offset: 0xFE8 (R/ ) ITM Peripheral Identification Register #2 */ __I uint32_t PID3; /*!< Offset: 0xFEC (R/ ) ITM Peripheral Identification Register #3 */ __I uint32_t CID0; /*!< Offset: 0xFF0 (R/ ) ITM Component Identification Register #0 */ __I uint32_t CID1; /*!< Offset: 0xFF4 (R/ ) ITM Component Identification Register #1 */ __I uint32_t CID2; /*!< Offset: 0xFF8 (R/ ) ITM Component Identification Register #2 */ __I uint32_t CID3; /*!< Offset: 0xFFC (R/ ) ITM Component Identification Register #3 */ } ITM_Type; /* ITM Trace Privilege Register Definitions */ #define ITM_TPR_PRIVMASK_Pos 0 /*!< ITM TPR: PRIVMASK Position */ #define ITM_TPR_PRIVMASK_Msk (0xFUL /*<< ITM_TPR_PRIVMASK_Pos*/) /*!< ITM TPR: PRIVMASK Mask */ /* ITM Trace Control Register Definitions */ #define ITM_TCR_BUSY_Pos 23 /*!< ITM TCR: BUSY Position */ #define ITM_TCR_BUSY_Msk (1UL << ITM_TCR_BUSY_Pos) /*!< ITM TCR: BUSY Mask */ #define ITM_TCR_TraceBusID_Pos 16 /*!< ITM TCR: ATBID Position */ #define ITM_TCR_TraceBusID_Msk (0x7FUL << ITM_TCR_TraceBusID_Pos) /*!< ITM TCR: ATBID Mask */ #define ITM_TCR_GTSFREQ_Pos 10 /*!< ITM TCR: Global timestamp frequency Position */ #define ITM_TCR_GTSFREQ_Msk (3UL << ITM_TCR_GTSFREQ_Pos) /*!< ITM TCR: Global timestamp frequency Mask */ #define ITM_TCR_TSPrescale_Pos 8 /*!< ITM TCR: TSPrescale Position */ #define ITM_TCR_TSPrescale_Msk (3UL << ITM_TCR_TSPrescale_Pos) /*!< ITM TCR: TSPrescale Mask */ #define ITM_TCR_SWOENA_Pos 4 /*!< ITM TCR: SWOENA Position */ #define ITM_TCR_SWOENA_Msk (1UL << ITM_TCR_SWOENA_Pos) /*!< ITM TCR: SWOENA Mask */ #define ITM_TCR_DWTENA_Pos 3 /*!< ITM TCR: DWTENA Position */ #define ITM_TCR_DWTENA_Msk (1UL << ITM_TCR_DWTENA_Pos) /*!< ITM TCR: DWTENA Mask */ #define ITM_TCR_SYNCENA_Pos 2 /*!< ITM TCR: SYNCENA Position */ #define ITM_TCR_SYNCENA_Msk (1UL << ITM_TCR_SYNCENA_Pos) /*!< ITM TCR: SYNCENA Mask */ #define ITM_TCR_TSENA_Pos 1 /*!< ITM TCR: TSENA Position */ #define ITM_TCR_TSENA_Msk (1UL << ITM_TCR_TSENA_Pos) /*!< ITM TCR: TSENA Mask */ #define ITM_TCR_ITMENA_Pos 0 /*!< ITM TCR: ITM Enable bit Position */ #define ITM_TCR_ITMENA_Msk (1UL /*<< ITM_TCR_ITMENA_Pos*/) /*!< ITM TCR: ITM Enable bit Mask */ /* ITM Integration Write Register Definitions */ #define ITM_IWR_ATVALIDM_Pos 0 /*!< ITM IWR: ATVALIDM Position */ #define ITM_IWR_ATVALIDM_Msk (1UL /*<< ITM_IWR_ATVALIDM_Pos*/) /*!< ITM IWR: ATVALIDM Mask */ /* ITM Integration Read Register Definitions */ #define ITM_IRR_ATREADYM_Pos 0 /*!< ITM IRR: ATREADYM Position */ #define ITM_IRR_ATREADYM_Msk (1UL /*<< ITM_IRR_ATREADYM_Pos*/) /*!< ITM IRR: ATREADYM Mask */ /* ITM Integration Mode Control Register Definitions */ #define ITM_IMCR_INTEGRATION_Pos 0 /*!< ITM IMCR: INTEGRATION Position */ #define ITM_IMCR_INTEGRATION_Msk (1UL /*<< ITM_IMCR_INTEGRATION_Pos*/) /*!< ITM IMCR: INTEGRATION Mask */ /* ITM Lock Status Register Definitions */ #define ITM_LSR_ByteAcc_Pos 2 /*!< ITM LSR: ByteAcc Position */ #define ITM_LSR_ByteAcc_Msk (1UL << ITM_LSR_ByteAcc_Pos) /*!< ITM LSR: ByteAcc Mask */ #define ITM_LSR_Access_Pos 1 /*!< ITM LSR: Access Position */ #define ITM_LSR_Access_Msk (1UL << ITM_LSR_Access_Pos) /*!< ITM LSR: Access Mask */ #define ITM_LSR_Present_Pos 0 /*!< ITM LSR: Present Position */ #define ITM_LSR_Present_Msk (1UL /*<< ITM_LSR_Present_Pos*/) /*!< ITM LSR: Present Mask */ /*@}*/ /* end of group CMSIS_ITM */ /** \ingroup CMSIS_core_register \defgroup CMSIS_DWT Data Watchpoint and Trace (DWT) \brief Type definitions for the Data Watchpoint and Trace (DWT) @{ */ /** \brief Structure type to access the Data Watchpoint and Trace Register (DWT). */ typedef struct { __IO uint32_t CTRL; /*!< Offset: 0x000 (R/W) Control Register */ __IO uint32_t CYCCNT; /*!< Offset: 0x004 (R/W) Cycle Count Register */ __IO uint32_t CPICNT; /*!< Offset: 0x008 (R/W) CPI Count Register */ __IO uint32_t EXCCNT; /*!< Offset: 0x00C (R/W) Exception Overhead Count Register */ __IO uint32_t SLEEPCNT; /*!< Offset: 0x010 (R/W) Sleep Count Register */ __IO uint32_t LSUCNT; /*!< Offset: 0x014 (R/W) LSU Count Register */ __IO uint32_t FOLDCNT; /*!< Offset: 0x018 (R/W) Folded-instruction Count Register */ __I uint32_t PCSR; /*!< Offset: 0x01C (R/ ) Program Counter Sample Register */ __IO uint32_t COMP0; /*!< Offset: 0x020 (R/W) Comparator Register 0 */ __IO uint32_t MASK0; /*!< Offset: 0x024 (R/W) Mask Register 0 */ __IO uint32_t FUNCTION0; /*!< Offset: 0x028 (R/W) Function Register 0 */ uint32_t RESERVED0[1]; __IO uint32_t COMP1; /*!< Offset: 0x030 (R/W) Comparator Register 1 */ __IO uint32_t MASK1; /*!< Offset: 0x034 (R/W) Mask Register 1 */ __IO uint32_t FUNCTION1; /*!< Offset: 0x038 (R/W) Function Register 1 */ uint32_t RESERVED1[1]; __IO uint32_t COMP2; /*!< Offset: 0x040 (R/W) Comparator Register 2 */ __IO uint32_t MASK2; /*!< Offset: 0x044 (R/W) Mask Register 2 */ __IO uint32_t FUNCTION2; /*!< Offset: 0x048 (R/W) Function Register 2 */ uint32_t RESERVED2[1]; __IO uint32_t COMP3; /*!< Offset: 0x050 (R/W) Comparator Register 3 */ __IO uint32_t MASK3; /*!< Offset: 0x054 (R/W) Mask Register 3 */ __IO uint32_t FUNCTION3; /*!< Offset: 0x058 (R/W) Function Register 3 */ } DWT_Type; /* DWT Control Register Definitions */ #define DWT_CTRL_NUMCOMP_Pos 28 /*!< DWT CTRL: NUMCOMP Position */ #define DWT_CTRL_NUMCOMP_Msk (0xFUL << DWT_CTRL_NUMCOMP_Pos) /*!< DWT CTRL: NUMCOMP Mask */ #define DWT_CTRL_NOTRCPKT_Pos 27 /*!< DWT CTRL: NOTRCPKT Position */ #define DWT_CTRL_NOTRCPKT_Msk (0x1UL << DWT_CTRL_NOTRCPKT_Pos) /*!< DWT CTRL: NOTRCPKT Mask */ #define DWT_CTRL_NOEXTTRIG_Pos 26 /*!< DWT CTRL: NOEXTTRIG Position */ #define DWT_CTRL_NOEXTTRIG_Msk (0x1UL << DWT_CTRL_NOEXTTRIG_Pos) /*!< DWT CTRL: NOEXTTRIG Mask */ #define DWT_CTRL_NOCYCCNT_Pos 25 /*!< DWT CTRL: NOCYCCNT Position */ #define DWT_CTRL_NOCYCCNT_Msk (0x1UL << DWT_CTRL_NOCYCCNT_Pos) /*!< DWT CTRL: NOCYCCNT Mask */ #define DWT_CTRL_NOPRFCNT_Pos 24 /*!< DWT CTRL: NOPRFCNT Position */ #define DWT_CTRL_NOPRFCNT_Msk (0x1UL << DWT_CTRL_NOPRFCNT_Pos) /*!< DWT CTRL: NOPRFCNT Mask */ #define DWT_CTRL_CYCEVTENA_Pos 22 /*!< DWT CTRL: CYCEVTENA Position */ #define DWT_CTRL_CYCEVTENA_Msk (0x1UL << DWT_CTRL_CYCEVTENA_Pos) /*!< DWT CTRL: CYCEVTENA Mask */ #define DWT_CTRL_FOLDEVTENA_Pos 21 /*!< DWT CTRL: FOLDEVTENA Position */ #define DWT_CTRL_FOLDEVTENA_Msk (0x1UL << DWT_CTRL_FOLDEVTENA_Pos) /*!< DWT CTRL: FOLDEVTENA Mask */ #define DWT_CTRL_LSUEVTENA_Pos 20 /*!< DWT CTRL: LSUEVTENA Position */ #define DWT_CTRL_LSUEVTENA_Msk (0x1UL << DWT_CTRL_LSUEVTENA_Pos) /*!< DWT CTRL: LSUEVTENA Mask */ #define DWT_CTRL_SLEEPEVTENA_Pos 19 /*!< DWT CTRL: SLEEPEVTENA Position */ #define DWT_CTRL_SLEEPEVTENA_Msk (0x1UL << DWT_CTRL_SLEEPEVTENA_Pos) /*!< DWT CTRL: SLEEPEVTENA Mask */ #define DWT_CTRL_EXCEVTENA_Pos 18 /*!< DWT CTRL: EXCEVTENA Position */ #define DWT_CTRL_EXCEVTENA_Msk (0x1UL << DWT_CTRL_EXCEVTENA_Pos) /*!< DWT CTRL: EXCEVTENA Mask */ #define DWT_CTRL_CPIEVTENA_Pos 17 /*!< DWT CTRL: CPIEVTENA Position */ #define DWT_CTRL_CPIEVTENA_Msk (0x1UL << DWT_CTRL_CPIEVTENA_Pos) /*!< DWT CTRL: CPIEVTENA Mask */ #define DWT_CTRL_EXCTRCENA_Pos 16 /*!< DWT CTRL: EXCTRCENA Position */ #define DWT_CTRL_EXCTRCENA_Msk (0x1UL << DWT_CTRL_EXCTRCENA_Pos) /*!< DWT CTRL: EXCTRCENA Mask */ #define DWT_CTRL_PCSAMPLENA_Pos 12 /*!< DWT CTRL: PCSAMPLENA Position */ #define DWT_CTRL_PCSAMPLENA_Msk (0x1UL << DWT_CTRL_PCSAMPLENA_Pos) /*!< DWT CTRL: PCSAMPLENA Mask */ #define DWT_CTRL_SYNCTAP_Pos 10 /*!< DWT CTRL: SYNCTAP Position */ #define DWT_CTRL_SYNCTAP_Msk (0x3UL << DWT_CTRL_SYNCTAP_Pos) /*!< DWT CTRL: SYNCTAP Mask */ #define DWT_CTRL_CYCTAP_Pos 9 /*!< DWT CTRL: CYCTAP Position */ #define DWT_CTRL_CYCTAP_Msk (0x1UL << DWT_CTRL_CYCTAP_Pos) /*!< DWT CTRL: CYCTAP Mask */ #define DWT_CTRL_POSTINIT_Pos 5 /*!< DWT CTRL: POSTINIT Position */ #define DWT_CTRL_POSTINIT_Msk (0xFUL << DWT_CTRL_POSTINIT_Pos) /*!< DWT CTRL: POSTINIT Mask */ #define DWT_CTRL_POSTPRESET_Pos 1 /*!< DWT CTRL: POSTPRESET Position */ #define DWT_CTRL_POSTPRESET_Msk (0xFUL << DWT_CTRL_POSTPRESET_Pos) /*!< DWT CTRL: POSTPRESET Mask */ #define DWT_CTRL_CYCCNTENA_Pos 0 /*!< DWT CTRL: CYCCNTENA Position */ #define DWT_CTRL_CYCCNTENA_Msk (0x1UL /*<< DWT_CTRL_CYCCNTENA_Pos*/) /*!< DWT CTRL: CYCCNTENA Mask */ /* DWT CPI Count Register Definitions */ #define DWT_CPICNT_CPICNT_Pos 0 /*!< DWT CPICNT: CPICNT Position */ #define DWT_CPICNT_CPICNT_Msk (0xFFUL /*<< DWT_CPICNT_CPICNT_Pos*/) /*!< DWT CPICNT: CPICNT Mask */ /* DWT Exception Overhead Count Register Definitions */ #define DWT_EXCCNT_EXCCNT_Pos 0 /*!< DWT EXCCNT: EXCCNT Position */ #define DWT_EXCCNT_EXCCNT_Msk (0xFFUL /*<< DWT_EXCCNT_EXCCNT_Pos*/) /*!< DWT EXCCNT: EXCCNT Mask */ /* DWT Sleep Count Register Definitions */ #define DWT_SLEEPCNT_SLEEPCNT_Pos 0 /*!< DWT SLEEPCNT: SLEEPCNT Position */ #define DWT_SLEEPCNT_SLEEPCNT_Msk (0xFFUL /*<< DWT_SLEEPCNT_SLEEPCNT_Pos*/) /*!< DWT SLEEPCNT: SLEEPCNT Mask */ /* DWT LSU Count Register Definitions */ #define DWT_LSUCNT_LSUCNT_Pos 0 /*!< DWT LSUCNT: LSUCNT Position */ #define DWT_LSUCNT_LSUCNT_Msk (0xFFUL /*<< DWT_LSUCNT_LSUCNT_Pos*/) /*!< DWT LSUCNT: LSUCNT Mask */ /* DWT Folded-instruction Count Register Definitions */ #define DWT_FOLDCNT_FOLDCNT_Pos 0 /*!< DWT FOLDCNT: FOLDCNT Position */ #define DWT_FOLDCNT_FOLDCNT_Msk (0xFFUL /*<< DWT_FOLDCNT_FOLDCNT_Pos*/) /*!< DWT FOLDCNT: FOLDCNT Mask */ /* DWT Comparator Mask Register Definitions */ #define DWT_MASK_MASK_Pos 0 /*!< DWT MASK: MASK Position */ #define DWT_MASK_MASK_Msk (0x1FUL /*<< DWT_MASK_MASK_Pos*/) /*!< DWT MASK: MASK Mask */ /* DWT Comparator Function Register Definitions */ #define DWT_FUNCTION_MATCHED_Pos 24 /*!< DWT FUNCTION: MATCHED Position */ #define DWT_FUNCTION_MATCHED_Msk (0x1UL << DWT_FUNCTION_MATCHED_Pos) /*!< DWT FUNCTION: MATCHED Mask */ #define DWT_FUNCTION_DATAVADDR1_Pos 16 /*!< DWT FUNCTION: DATAVADDR1 Position */ #define DWT_FUNCTION_DATAVADDR1_Msk (0xFUL << DWT_FUNCTION_DATAVADDR1_Pos) /*!< DWT FUNCTION: DATAVADDR1 Mask */ #define DWT_FUNCTION_DATAVADDR0_Pos 12 /*!< DWT FUNCTION: DATAVADDR0 Position */ #define DWT_FUNCTION_DATAVADDR0_Msk (0xFUL << DWT_FUNCTION_DATAVADDR0_Pos) /*!< DWT FUNCTION: DATAVADDR0 Mask */ #define DWT_FUNCTION_DATAVSIZE_Pos 10 /*!< DWT FUNCTION: DATAVSIZE Position */ #define DWT_FUNCTION_DATAVSIZE_Msk (0x3UL << DWT_FUNCTION_DATAVSIZE_Pos) /*!< DWT FUNCTION: DATAVSIZE Mask */ #define DWT_FUNCTION_LNK1ENA_Pos 9 /*!< DWT FUNCTION: LNK1ENA Position */ #define DWT_FUNCTION_LNK1ENA_Msk (0x1UL << DWT_FUNCTION_LNK1ENA_Pos) /*!< DWT FUNCTION: LNK1ENA Mask */ #define DWT_FUNCTION_DATAVMATCH_Pos 8 /*!< DWT FUNCTION: DATAVMATCH Position */ #define DWT_FUNCTION_DATAVMATCH_Msk (0x1UL << DWT_FUNCTION_DATAVMATCH_Pos) /*!< DWT FUNCTION: DATAVMATCH Mask */ #define DWT_FUNCTION_CYCMATCH_Pos 7 /*!< DWT FUNCTION: CYCMATCH Position */ #define DWT_FUNCTION_CYCMATCH_Msk (0x1UL << DWT_FUNCTION_CYCMATCH_Pos) /*!< DWT FUNCTION: CYCMATCH Mask */ #define DWT_FUNCTION_EMITRANGE_Pos 5 /*!< DWT FUNCTION: EMITRANGE Position */ #define DWT_FUNCTION_EMITRANGE_Msk (0x1UL << DWT_FUNCTION_EMITRANGE_Pos) /*!< DWT FUNCTION: EMITRANGE Mask */ #define DWT_FUNCTION_FUNCTION_Pos 0 /*!< DWT FUNCTION: FUNCTION Position */ #define DWT_FUNCTION_FUNCTION_Msk (0xFUL /*<< DWT_FUNCTION_FUNCTION_Pos*/) /*!< DWT FUNCTION: FUNCTION Mask */ /*@}*/ /* end of group CMSIS_DWT */ /** \ingroup CMSIS_core_register \defgroup CMSIS_TPI Trace Port Interface (TPI) \brief Type definitions for the Trace Port Interface (TPI) @{ */ /** \brief Structure type to access the Trace Port Interface Register (TPI). */ typedef struct { __IO uint32_t SSPSR; /*!< Offset: 0x000 (R/ ) Supported Parallel Port Size Register */ __IO uint32_t CSPSR; /*!< Offset: 0x004 (R/W) Current Parallel Port Size Register */ uint32_t RESERVED0[2]; __IO uint32_t ACPR; /*!< Offset: 0x010 (R/W) Asynchronous Clock Prescaler Register */ uint32_t RESERVED1[55]; __IO uint32_t SPPR; /*!< Offset: 0x0F0 (R/W) Selected Pin Protocol Register */ uint32_t RESERVED2[131]; __I uint32_t FFSR; /*!< Offset: 0x300 (R/ ) Formatter and Flush Status Register */ __IO uint32_t FFCR; /*!< Offset: 0x304 (R/W) Formatter and Flush Control Register */ __I uint32_t FSCR; /*!< Offset: 0x308 (R/ ) Formatter Synchronization Counter Register */ uint32_t RESERVED3[759]; __I uint32_t TRIGGER; /*!< Offset: 0xEE8 (R/ ) TRIGGER */ __I uint32_t FIFO0; /*!< Offset: 0xEEC (R/ ) Integration ETM Data */ __I uint32_t ITATBCTR2; /*!< Offset: 0xEF0 (R/ ) ITATBCTR2 */ uint32_t RESERVED4[1]; __I uint32_t ITATBCTR0; /*!< Offset: 0xEF8 (R/ ) ITATBCTR0 */ __I uint32_t FIFO1; /*!< Offset: 0xEFC (R/ ) Integration ITM Data */ __IO uint32_t ITCTRL; /*!< Offset: 0xF00 (R/W) Integration Mode Control */ uint32_t RESERVED5[39]; __IO uint32_t CLAIMSET; /*!< Offset: 0xFA0 (R/W) Claim tag set */ __IO uint32_t CLAIMCLR; /*!< Offset: 0xFA4 (R/W) Claim tag clear */ uint32_t RESERVED7[8]; __I uint32_t DEVID; /*!< Offset: 0xFC8 (R/ ) TPIU_DEVID */ __I uint32_t DEVTYPE; /*!< Offset: 0xFCC (R/ ) TPIU_DEVTYPE */ } TPI_Type; /* TPI Asynchronous Clock Prescaler Register Definitions */ #define TPI_ACPR_PRESCALER_Pos 0 /*!< TPI ACPR: PRESCALER Position */ #define TPI_ACPR_PRESCALER_Msk (0x1FFFUL /*<< TPI_ACPR_PRESCALER_Pos*/) /*!< TPI ACPR: PRESCALER Mask */ /* TPI Selected Pin Protocol Register Definitions */ #define TPI_SPPR_TXMODE_Pos 0 /*!< TPI SPPR: TXMODE Position */ #define TPI_SPPR_TXMODE_Msk (0x3UL /*<< TPI_SPPR_TXMODE_Pos*/) /*!< TPI SPPR: TXMODE Mask */ /* TPI Formatter and Flush Status Register Definitions */ #define TPI_FFSR_FtNonStop_Pos 3 /*!< TPI FFSR: FtNonStop Position */ #define TPI_FFSR_FtNonStop_Msk (0x1UL << TPI_FFSR_FtNonStop_Pos) /*!< TPI FFSR: FtNonStop Mask */ #define TPI_FFSR_TCPresent_Pos 2 /*!< TPI FFSR: TCPresent Position */ #define TPI_FFSR_TCPresent_Msk (0x1UL << TPI_FFSR_TCPresent_Pos) /*!< TPI FFSR: TCPresent Mask */ #define TPI_FFSR_FtStopped_Pos 1 /*!< TPI FFSR: FtStopped Position */ #define TPI_FFSR_FtStopped_Msk (0x1UL << TPI_FFSR_FtStopped_Pos) /*!< TPI FFSR: FtStopped Mask */ #define TPI_FFSR_FlInProg_Pos 0 /*!< TPI FFSR: FlInProg Position */ #define TPI_FFSR_FlInProg_Msk (0x1UL /*<< TPI_FFSR_FlInProg_Pos*/) /*!< TPI FFSR: FlInProg Mask */ /* TPI Formatter and Flush Control Register Definitions */ #define TPI_FFCR_TrigIn_Pos 8 /*!< TPI FFCR: TrigIn Position */ #define TPI_FFCR_TrigIn_Msk (0x1UL << TPI_FFCR_TrigIn_Pos) /*!< TPI FFCR: TrigIn Mask */ #define TPI_FFCR_EnFCont_Pos 1 /*!< TPI FFCR: EnFCont Position */ #define TPI_FFCR_EnFCont_Msk (0x1UL << TPI_FFCR_EnFCont_Pos) /*!< TPI FFCR: EnFCont Mask */ /* TPI TRIGGER Register Definitions */ #define TPI_TRIGGER_TRIGGER_Pos 0 /*!< TPI TRIGGER: TRIGGER Position */ #define TPI_TRIGGER_TRIGGER_Msk (0x1UL /*<< TPI_TRIGGER_TRIGGER_Pos*/) /*!< TPI TRIGGER: TRIGGER Mask */ /* TPI Integration ETM Data Register Definitions (FIFO0) */ #define TPI_FIFO0_ITM_ATVALID_Pos 29 /*!< TPI FIFO0: ITM_ATVALID Position */ #define TPI_FIFO0_ITM_ATVALID_Msk (0x3UL << TPI_FIFO0_ITM_ATVALID_Pos) /*!< TPI FIFO0: ITM_ATVALID Mask */ #define TPI_FIFO0_ITM_bytecount_Pos 27 /*!< TPI FIFO0: ITM_bytecount Position */ #define TPI_FIFO0_ITM_bytecount_Msk (0x3UL << TPI_FIFO0_ITM_bytecount_Pos) /*!< TPI FIFO0: ITM_bytecount Mask */ #define TPI_FIFO0_ETM_ATVALID_Pos 26 /*!< TPI FIFO0: ETM_ATVALID Position */ #define TPI_FIFO0_ETM_ATVALID_Msk (0x3UL << TPI_FIFO0_ETM_ATVALID_Pos) /*!< TPI FIFO0: ETM_ATVALID Mask */ #define TPI_FIFO0_ETM_bytecount_Pos 24 /*!< TPI FIFO0: ETM_bytecount Position */ #define TPI_FIFO0_ETM_bytecount_Msk (0x3UL << TPI_FIFO0_ETM_bytecount_Pos) /*!< TPI FIFO0: ETM_bytecount Mask */ #define TPI_FIFO0_ETM2_Pos 16 /*!< TPI FIFO0: ETM2 Position */ #define TPI_FIFO0_ETM2_Msk (0xFFUL << TPI_FIFO0_ETM2_Pos) /*!< TPI FIFO0: ETM2 Mask */ #define TPI_FIFO0_ETM1_Pos 8 /*!< TPI FIFO0: ETM1 Position */ #define TPI_FIFO0_ETM1_Msk (0xFFUL << TPI_FIFO0_ETM1_Pos) /*!< TPI FIFO0: ETM1 Mask */ #define TPI_FIFO0_ETM0_Pos 0 /*!< TPI FIFO0: ETM0 Position */ #define TPI_FIFO0_ETM0_Msk (0xFFUL /*<< TPI_FIFO0_ETM0_Pos*/) /*!< TPI FIFO0: ETM0 Mask */ /* TPI ITATBCTR2 Register Definitions */ #define TPI_ITATBCTR2_ATREADY_Pos 0 /*!< TPI ITATBCTR2: ATREADY Position */ #define TPI_ITATBCTR2_ATREADY_Msk (0x1UL /*<< TPI_ITATBCTR2_ATREADY_Pos*/) /*!< TPI ITATBCTR2: ATREADY Mask */ /* TPI Integration ITM Data Register Definitions (FIFO1) */ #define TPI_FIFO1_ITM_ATVALID_Pos 29 /*!< TPI FIFO1: ITM_ATVALID Position */ #define TPI_FIFO1_ITM_ATVALID_Msk (0x3UL << TPI_FIFO1_ITM_ATVALID_Pos) /*!< TPI FIFO1: ITM_ATVALID Mask */ #define TPI_FIFO1_ITM_bytecount_Pos 27 /*!< TPI FIFO1: ITM_bytecount Position */ #define TPI_FIFO1_ITM_bytecount_Msk (0x3UL << TPI_FIFO1_ITM_bytecount_Pos) /*!< TPI FIFO1: ITM_bytecount Mask */ #define TPI_FIFO1_ETM_ATVALID_Pos 26 /*!< TPI FIFO1: ETM_ATVALID Position */ #define TPI_FIFO1_ETM_ATVALID_Msk (0x3UL << TPI_FIFO1_ETM_ATVALID_Pos) /*!< TPI FIFO1: ETM_ATVALID Mask */ #define TPI_FIFO1_ETM_bytecount_Pos 24 /*!< TPI FIFO1: ETM_bytecount Position */ #define TPI_FIFO1_ETM_bytecount_Msk (0x3UL << TPI_FIFO1_ETM_bytecount_Pos) /*!< TPI FIFO1: ETM_bytecount Mask */ #define TPI_FIFO1_ITM2_Pos 16 /*!< TPI FIFO1: ITM2 Position */ #define TPI_FIFO1_ITM2_Msk (0xFFUL << TPI_FIFO1_ITM2_Pos) /*!< TPI FIFO1: ITM2 Mask */ #define TPI_FIFO1_ITM1_Pos 8 /*!< TPI FIFO1: ITM1 Position */ #define TPI_FIFO1_ITM1_Msk (0xFFUL << TPI_FIFO1_ITM1_Pos) /*!< TPI FIFO1: ITM1 Mask */ #define TPI_FIFO1_ITM0_Pos 0 /*!< TPI FIFO1: ITM0 Position */ #define TPI_FIFO1_ITM0_Msk (0xFFUL /*<< TPI_FIFO1_ITM0_Pos*/) /*!< TPI FIFO1: ITM0 Mask */ /* TPI ITATBCTR0 Register Definitions */ #define TPI_ITATBCTR0_ATREADY_Pos 0 /*!< TPI ITATBCTR0: ATREADY Position */ #define TPI_ITATBCTR0_ATREADY_Msk (0x1UL /*<< TPI_ITATBCTR0_ATREADY_Pos*/) /*!< TPI ITATBCTR0: ATREADY Mask */ /* TPI Integration Mode Control Register Definitions */ #define TPI_ITCTRL_Mode_Pos 0 /*!< TPI ITCTRL: Mode Position */ #define TPI_ITCTRL_Mode_Msk (0x1UL /*<< TPI_ITCTRL_Mode_Pos*/) /*!< TPI ITCTRL: Mode Mask */ /* TPI DEVID Register Definitions */ #define TPI_DEVID_NRZVALID_Pos 11 /*!< TPI DEVID: NRZVALID Position */ #define TPI_DEVID_NRZVALID_Msk (0x1UL << TPI_DEVID_NRZVALID_Pos) /*!< TPI DEVID: NRZVALID Mask */ #define TPI_DEVID_MANCVALID_Pos 10 /*!< TPI DEVID: MANCVALID Position */ #define TPI_DEVID_MANCVALID_Msk (0x1UL << TPI_DEVID_MANCVALID_Pos) /*!< TPI DEVID: MANCVALID Mask */ #define TPI_DEVID_PTINVALID_Pos 9 /*!< TPI DEVID: PTINVALID Position */ #define TPI_DEVID_PTINVALID_Msk (0x1UL << TPI_DEVID_PTINVALID_Pos) /*!< TPI DEVID: PTINVALID Mask */ #define TPI_DEVID_MinBufSz_Pos 6 /*!< TPI DEVID: MinBufSz Position */ #define TPI_DEVID_MinBufSz_Msk (0x7UL << TPI_DEVID_MinBufSz_Pos) /*!< TPI DEVID: MinBufSz Mask */ #define TPI_DEVID_AsynClkIn_Pos 5 /*!< TPI DEVID: AsynClkIn Position */ #define TPI_DEVID_AsynClkIn_Msk (0x1UL << TPI_DEVID_AsynClkIn_Pos) /*!< TPI DEVID: AsynClkIn Mask */ #define TPI_DEVID_NrTraceInput_Pos 0 /*!< TPI DEVID: NrTraceInput Position */ #define TPI_DEVID_NrTraceInput_Msk (0x1FUL /*<< TPI_DEVID_NrTraceInput_Pos*/) /*!< TPI DEVID: NrTraceInput Mask */ /* TPI DEVTYPE Register Definitions */ #define TPI_DEVTYPE_MajorType_Pos 4 /*!< TPI DEVTYPE: MajorType Position */ #define TPI_DEVTYPE_MajorType_Msk (0xFUL << TPI_DEVTYPE_MajorType_Pos) /*!< TPI DEVTYPE: MajorType Mask */ #define TPI_DEVTYPE_SubType_Pos 0 /*!< TPI DEVTYPE: SubType Position */ #define TPI_DEVTYPE_SubType_Msk (0xFUL /*<< TPI_DEVTYPE_SubType_Pos*/) /*!< TPI DEVTYPE: SubType Mask */ /*@}*/ /* end of group CMSIS_TPI */ #if (__MPU_PRESENT == 1) /** \ingroup CMSIS_core_register \defgroup CMSIS_MPU Memory Protection Unit (MPU) \brief Type definitions for the Memory Protection Unit (MPU) @{ */ /** \brief Structure type to access the Memory Protection Unit (MPU). */ typedef struct { __I uint32_t TYPE; /*!< Offset: 0x000 (R/ ) MPU Type Register */ __IO uint32_t CTRL; /*!< Offset: 0x004 (R/W) MPU Control Register */ __IO uint32_t RNR; /*!< Offset: 0x008 (R/W) MPU Region RNRber Register */ __IO uint32_t RBAR; /*!< Offset: 0x00C (R/W) MPU Region Base Address Register */ __IO uint32_t RASR; /*!< Offset: 0x010 (R/W) MPU Region Attribute and Size Register */ __IO uint32_t RBAR_A1; /*!< Offset: 0x014 (R/W) MPU Alias 1 Region Base Address Register */ __IO uint32_t RASR_A1; /*!< Offset: 0x018 (R/W) MPU Alias 1 Region Attribute and Size Register */ __IO uint32_t RBAR_A2; /*!< Offset: 0x01C (R/W) MPU Alias 2 Region Base Address Register */ __IO uint32_t RASR_A2; /*!< Offset: 0x020 (R/W) MPU Alias 2 Region Attribute and Size Register */ __IO uint32_t RBAR_A3; /*!< Offset: 0x024 (R/W) MPU Alias 3 Region Base Address Register */ __IO uint32_t RASR_A3; /*!< Offset: 0x028 (R/W) MPU Alias 3 Region Attribute and Size Register */ } MPU_Type; /* MPU Type Register */ #define MPU_TYPE_IREGION_Pos 16 /*!< MPU TYPE: IREGION Position */ #define MPU_TYPE_IREGION_Msk (0xFFUL << MPU_TYPE_IREGION_Pos) /*!< MPU TYPE: IREGION Mask */ #define MPU_TYPE_DREGION_Pos 8 /*!< MPU TYPE: DREGION Position */ #define MPU_TYPE_DREGION_Msk (0xFFUL << MPU_TYPE_DREGION_Pos) /*!< MPU TYPE: DREGION Mask */ #define MPU_TYPE_SEPARATE_Pos 0 /*!< MPU TYPE: SEPARATE Position */ #define MPU_TYPE_SEPARATE_Msk (1UL /*<< MPU_TYPE_SEPARATE_Pos*/) /*!< MPU TYPE: SEPARATE Mask */ /* MPU Control Register */ #define MPU_CTRL_PRIVDEFENA_Pos 2 /*!< MPU CTRL: PRIVDEFENA Position */ #define MPU_CTRL_PRIVDEFENA_Msk (1UL << MPU_CTRL_PRIVDEFENA_Pos) /*!< MPU CTRL: PRIVDEFENA Mask */ #define MPU_CTRL_HFNMIENA_Pos 1 /*!< MPU CTRL: HFNMIENA Position */ #define MPU_CTRL_HFNMIENA_Msk (1UL << MPU_CTRL_HFNMIENA_Pos) /*!< MPU CTRL: HFNMIENA Mask */ #define MPU_CTRL_ENABLE_Pos 0 /*!< MPU CTRL: ENABLE Position */ #define MPU_CTRL_ENABLE_Msk (1UL /*<< MPU_CTRL_ENABLE_Pos*/) /*!< MPU CTRL: ENABLE Mask */ /* MPU Region Number Register */ #define MPU_RNR_REGION_Pos 0 /*!< MPU RNR: REGION Position */ #define MPU_RNR_REGION_Msk (0xFFUL /*<< MPU_RNR_REGION_Pos*/) /*!< MPU RNR: REGION Mask */ /* MPU Region Base Address Register */ #define MPU_RBAR_ADDR_Pos 5 /*!< MPU RBAR: ADDR Position */ #define MPU_RBAR_ADDR_Msk (0x7FFFFFFUL << MPU_RBAR_ADDR_Pos) /*!< MPU RBAR: ADDR Mask */ #define MPU_RBAR_VALID_Pos 4 /*!< MPU RBAR: VALID Position */ #define MPU_RBAR_VALID_Msk (1UL << MPU_RBAR_VALID_Pos) /*!< MPU RBAR: VALID Mask */ #define MPU_RBAR_REGION_Pos 0 /*!< MPU RBAR: REGION Position */ #define MPU_RBAR_REGION_Msk (0xFUL /*<< MPU_RBAR_REGION_Pos*/) /*!< MPU RBAR: REGION Mask */ /* MPU Region Attribute and Size Register */ #define MPU_RASR_ATTRS_Pos 16 /*!< MPU RASR: MPU Region Attribute field Position */ #define MPU_RASR_ATTRS_Msk (0xFFFFUL << MPU_RASR_ATTRS_Pos) /*!< MPU RASR: MPU Region Attribute field Mask */ #define MPU_RASR_XN_Pos 28 /*!< MPU RASR: ATTRS.XN Position */ #define MPU_RASR_XN_Msk (1UL << MPU_RASR_XN_Pos) /*!< MPU RASR: ATTRS.XN Mask */ #define MPU_RASR_AP_Pos 24 /*!< MPU RASR: ATTRS.AP Position */ #define MPU_RASR_AP_Msk (0x7UL << MPU_RASR_AP_Pos) /*!< MPU RASR: ATTRS.AP Mask */ #define MPU_RASR_TEX_Pos 19 /*!< MPU RASR: ATTRS.TEX Position */ #define MPU_RASR_TEX_Msk (0x7UL << MPU_RASR_TEX_Pos) /*!< MPU RASR: ATTRS.TEX Mask */ #define MPU_RASR_S_Pos 18 /*!< MPU RASR: ATTRS.S Position */ #define MPU_RASR_S_Msk (1UL << MPU_RASR_S_Pos) /*!< MPU RASR: ATTRS.S Mask */ #define MPU_RASR_C_Pos 17 /*!< MPU RASR: ATTRS.C Position */ #define MPU_RASR_C_Msk (1UL << MPU_RASR_C_Pos) /*!< MPU RASR: ATTRS.C Mask */ #define MPU_RASR_B_Pos 16 /*!< MPU RASR: ATTRS.B Position */ #define MPU_RASR_B_Msk (1UL << MPU_RASR_B_Pos) /*!< MPU RASR: ATTRS.B Mask */ #define MPU_RASR_SRD_Pos 8 /*!< MPU RASR: Sub-Region Disable Position */ #define MPU_RASR_SRD_Msk (0xFFUL << MPU_RASR_SRD_Pos) /*!< MPU RASR: Sub-Region Disable Mask */ #define MPU_RASR_SIZE_Pos 1 /*!< MPU RASR: Region Size Field Position */ #define MPU_RASR_SIZE_Msk (0x1FUL << MPU_RASR_SIZE_Pos) /*!< MPU RASR: Region Size Field Mask */ #define MPU_RASR_ENABLE_Pos 0 /*!< MPU RASR: Region enable bit Position */ #define MPU_RASR_ENABLE_Msk (1UL /*<< MPU_RASR_ENABLE_Pos*/) /*!< MPU RASR: Region enable bit Disable Mask */ /*@} end of group CMSIS_MPU */ #endif #if (__FPU_PRESENT == 1) /** \ingroup CMSIS_core_register \defgroup CMSIS_FPU Floating Point Unit (FPU) \brief Type definitions for the Floating Point Unit (FPU) @{ */ /** \brief Structure type to access the Floating Point Unit (FPU). */ typedef struct { uint32_t RESERVED0[1]; __IO uint32_t FPCCR; /*!< Offset: 0x004 (R/W) Floating-Point Context Control Register */ __IO uint32_t FPCAR; /*!< Offset: 0x008 (R/W) Floating-Point Context Address Register */ __IO uint32_t FPDSCR; /*!< Offset: 0x00C (R/W) Floating-Point Default Status Control Register */ __I uint32_t MVFR0; /*!< Offset: 0x010 (R/ ) Media and FP Feature Register 0 */ __I uint32_t MVFR1; /*!< Offset: 0x014 (R/ ) Media and FP Feature Register 1 */ } FPU_Type; /* Floating-Point Context Control Register */ #define FPU_FPCCR_ASPEN_Pos 31 /*!< FPCCR: ASPEN bit Position */ #define FPU_FPCCR_ASPEN_Msk (1UL << FPU_FPCCR_ASPEN_Pos) /*!< FPCCR: ASPEN bit Mask */ #define FPU_FPCCR_LSPEN_Pos 30 /*!< FPCCR: LSPEN Position */ #define FPU_FPCCR_LSPEN_Msk (1UL << FPU_FPCCR_LSPEN_Pos) /*!< FPCCR: LSPEN bit Mask */ #define FPU_FPCCR_MONRDY_Pos 8 /*!< FPCCR: MONRDY Position */ #define FPU_FPCCR_MONRDY_Msk (1UL << FPU_FPCCR_MONRDY_Pos) /*!< FPCCR: MONRDY bit Mask */ #define FPU_FPCCR_BFRDY_Pos 6 /*!< FPCCR: BFRDY Position */ #define FPU_FPCCR_BFRDY_Msk (1UL << FPU_FPCCR_BFRDY_Pos) /*!< FPCCR: BFRDY bit Mask */ #define FPU_FPCCR_MMRDY_Pos 5 /*!< FPCCR: MMRDY Position */ #define FPU_FPCCR_MMRDY_Msk (1UL << FPU_FPCCR_MMRDY_Pos) /*!< FPCCR: MMRDY bit Mask */ #define FPU_FPCCR_HFRDY_Pos 4 /*!< FPCCR: HFRDY Position */ #define FPU_FPCCR_HFRDY_Msk (1UL << FPU_FPCCR_HFRDY_Pos) /*!< FPCCR: HFRDY bit Mask */ #define FPU_FPCCR_THREAD_Pos 3 /*!< FPCCR: processor mode bit Position */ #define FPU_FPCCR_THREAD_Msk (1UL << FPU_FPCCR_THREAD_Pos) /*!< FPCCR: processor mode active bit Mask */ #define FPU_FPCCR_USER_Pos 1 /*!< FPCCR: privilege level bit Position */ #define FPU_FPCCR_USER_Msk (1UL << FPU_FPCCR_USER_Pos) /*!< FPCCR: privilege level bit Mask */ #define FPU_FPCCR_LSPACT_Pos 0 /*!< FPCCR: Lazy state preservation active bit Position */ #define FPU_FPCCR_LSPACT_Msk (1UL /*<< FPU_FPCCR_LSPACT_Pos*/) /*!< FPCCR: Lazy state preservation active bit Mask */ /* Floating-Point Context Address Register */ #define FPU_FPCAR_ADDRESS_Pos 3 /*!< FPCAR: ADDRESS bit Position */ #define FPU_FPCAR_ADDRESS_Msk (0x1FFFFFFFUL << FPU_FPCAR_ADDRESS_Pos) /*!< FPCAR: ADDRESS bit Mask */ /* Floating-Point Default Status Control Register */ #define FPU_FPDSCR_AHP_Pos 26 /*!< FPDSCR: AHP bit Position */ #define FPU_FPDSCR_AHP_Msk (1UL << FPU_FPDSCR_AHP_Pos) /*!< FPDSCR: AHP bit Mask */ #define FPU_FPDSCR_DN_Pos 25 /*!< FPDSCR: DN bit Position */ #define FPU_FPDSCR_DN_Msk (1UL << FPU_FPDSCR_DN_Pos) /*!< FPDSCR: DN bit Mask */ #define FPU_FPDSCR_FZ_Pos 24 /*!< FPDSCR: FZ bit Position */ #define FPU_FPDSCR_FZ_Msk (1UL << FPU_FPDSCR_FZ_Pos) /*!< FPDSCR: FZ bit Mask */ #define FPU_FPDSCR_RMode_Pos 22 /*!< FPDSCR: RMode bit Position */ #define FPU_FPDSCR_RMode_Msk (3UL << FPU_FPDSCR_RMode_Pos) /*!< FPDSCR: RMode bit Mask */ /* Media and FP Feature Register 0 */ #define FPU_MVFR0_FP_rounding_modes_Pos 28 /*!< MVFR0: FP rounding modes bits Position */ #define FPU_MVFR0_FP_rounding_modes_Msk (0xFUL << FPU_MVFR0_FP_rounding_modes_Pos) /*!< MVFR0: FP rounding modes bits Mask */ #define FPU_MVFR0_Short_vectors_Pos 24 /*!< MVFR0: Short vectors bits Position */ #define FPU_MVFR0_Short_vectors_Msk (0xFUL << FPU_MVFR0_Short_vectors_Pos) /*!< MVFR0: Short vectors bits Mask */ #define FPU_MVFR0_Square_root_Pos 20 /*!< MVFR0: Square root bits Position */ #define FPU_MVFR0_Square_root_Msk (0xFUL << FPU_MVFR0_Square_root_Pos) /*!< MVFR0: Square root bits Mask */ #define FPU_MVFR0_Divide_Pos 16 /*!< MVFR0: Divide bits Position */ #define FPU_MVFR0_Divide_Msk (0xFUL << FPU_MVFR0_Divide_Pos) /*!< MVFR0: Divide bits Mask */ #define FPU_MVFR0_FP_excep_trapping_Pos 12 /*!< MVFR0: FP exception trapping bits Position */ #define FPU_MVFR0_FP_excep_trapping_Msk (0xFUL << FPU_MVFR0_FP_excep_trapping_Pos) /*!< MVFR0: FP exception trapping bits Mask */ #define FPU_MVFR0_Double_precision_Pos 8 /*!< MVFR0: Double-precision bits Position */ #define FPU_MVFR0_Double_precision_Msk (0xFUL << FPU_MVFR0_Double_precision_Pos) /*!< MVFR0: Double-precision bits Mask */ #define FPU_MVFR0_Single_precision_Pos 4 /*!< MVFR0: Single-precision bits Position */ #define FPU_MVFR0_Single_precision_Msk (0xFUL << FPU_MVFR0_Single_precision_Pos) /*!< MVFR0: Single-precision bits Mask */ #define FPU_MVFR0_A_SIMD_registers_Pos 0 /*!< MVFR0: A_SIMD registers bits Position */ #define FPU_MVFR0_A_SIMD_registers_Msk (0xFUL /*<< FPU_MVFR0_A_SIMD_registers_Pos*/) /*!< MVFR0: A_SIMD registers bits Mask */ /* Media and FP Feature Register 1 */ #define FPU_MVFR1_FP_fused_MAC_Pos 28 /*!< MVFR1: FP fused MAC bits Position */ #define FPU_MVFR1_FP_fused_MAC_Msk (0xFUL << FPU_MVFR1_FP_fused_MAC_Pos) /*!< MVFR1: FP fused MAC bits Mask */ #define FPU_MVFR1_FP_HPFP_Pos 24 /*!< MVFR1: FP HPFP bits Position */ #define FPU_MVFR1_FP_HPFP_Msk (0xFUL << FPU_MVFR1_FP_HPFP_Pos) /*!< MVFR1: FP HPFP bits Mask */ #define FPU_MVFR1_D_NaN_mode_Pos 4 /*!< MVFR1: D_NaN mode bits Position */ #define FPU_MVFR1_D_NaN_mode_Msk (0xFUL << FPU_MVFR1_D_NaN_mode_Pos) /*!< MVFR1: D_NaN mode bits Mask */ #define FPU_MVFR1_FtZ_mode_Pos 0 /*!< MVFR1: FtZ mode bits Position */ #define FPU_MVFR1_FtZ_mode_Msk (0xFUL /*<< FPU_MVFR1_FtZ_mode_Pos*/) /*!< MVFR1: FtZ mode bits Mask */ /*@} end of group CMSIS_FPU */ #endif /** \ingroup CMSIS_core_register \defgroup CMSIS_CoreDebug Core Debug Registers (CoreDebug) \brief Type definitions for the Core Debug Registers @{ */ /** \brief Structure type to access the Core Debug Register (CoreDebug). */ typedef struct { __IO uint32_t DHCSR; /*!< Offset: 0x000 (R/W) Debug Halting Control and Status Register */ __O uint32_t DCRSR; /*!< Offset: 0x004 ( /W) Debug Core Register Selector Register */ __IO uint32_t DCRDR; /*!< Offset: 0x008 (R/W) Debug Core Register Data Register */ __IO uint32_t DEMCR; /*!< Offset: 0x00C (R/W) Debug Exception and Monitor Control Register */ } CoreDebug_Type; /* Debug Halting Control and Status Register */ #define CoreDebug_DHCSR_DBGKEY_Pos 16 /*!< CoreDebug DHCSR: DBGKEY Position */ #define CoreDebug_DHCSR_DBGKEY_Msk (0xFFFFUL << CoreDebug_DHCSR_DBGKEY_Pos) /*!< CoreDebug DHCSR: DBGKEY Mask */ #define CoreDebug_DHCSR_S_RESET_ST_Pos 25 /*!< CoreDebug DHCSR: S_RESET_ST Position */ #define CoreDebug_DHCSR_S_RESET_ST_Msk (1UL << CoreDebug_DHCSR_S_RESET_ST_Pos) /*!< CoreDebug DHCSR: S_RESET_ST Mask */ #define CoreDebug_DHCSR_S_RETIRE_ST_Pos 24 /*!< CoreDebug DHCSR: S_RETIRE_ST Position */ #define CoreDebug_DHCSR_S_RETIRE_ST_Msk (1UL << CoreDebug_DHCSR_S_RETIRE_ST_Pos) /*!< CoreDebug DHCSR: S_RETIRE_ST Mask */ #define CoreDebug_DHCSR_S_LOCKUP_Pos 19 /*!< CoreDebug DHCSR: S_LOCKUP Position */ #define CoreDebug_DHCSR_S_LOCKUP_Msk (1UL << CoreDebug_DHCSR_S_LOCKUP_Pos) /*!< CoreDebug DHCSR: S_LOCKUP Mask */ #define CoreDebug_DHCSR_S_SLEEP_Pos 18 /*!< CoreDebug DHCSR: S_SLEEP Position */ #define CoreDebug_DHCSR_S_SLEEP_Msk (1UL << CoreDebug_DHCSR_S_SLEEP_Pos) /*!< CoreDebug DHCSR: S_SLEEP Mask */ #define CoreDebug_DHCSR_S_HALT_Pos 17 /*!< CoreDebug DHCSR: S_HALT Position */ #define CoreDebug_DHCSR_S_HALT_Msk (1UL << CoreDebug_DHCSR_S_HALT_Pos) /*!< CoreDebug DHCSR: S_HALT Mask */ #define CoreDebug_DHCSR_S_REGRDY_Pos 16 /*!< CoreDebug DHCSR: S_REGRDY Position */ #define CoreDebug_DHCSR_S_REGRDY_Msk (1UL << CoreDebug_DHCSR_S_REGRDY_Pos) /*!< CoreDebug DHCSR: S_REGRDY Mask */ #define CoreDebug_DHCSR_C_SNAPSTALL_Pos 5 /*!< CoreDebug DHCSR: C_SNAPSTALL Position */ #define CoreDebug_DHCSR_C_SNAPSTALL_Msk (1UL << CoreDebug_DHCSR_C_SNAPSTALL_Pos) /*!< CoreDebug DHCSR: C_SNAPSTALL Mask */ #define CoreDebug_DHCSR_C_MASKINTS_Pos 3 /*!< CoreDebug DHCSR: C_MASKINTS Position */ #define CoreDebug_DHCSR_C_MASKINTS_Msk (1UL << CoreDebug_DHCSR_C_MASKINTS_Pos) /*!< CoreDebug DHCSR: C_MASKINTS Mask */ #define CoreDebug_DHCSR_C_STEP_Pos 2 /*!< CoreDebug DHCSR: C_STEP Position */ #define CoreDebug_DHCSR_C_STEP_Msk (1UL << CoreDebug_DHCSR_C_STEP_Pos) /*!< CoreDebug DHCSR: C_STEP Mask */ #define CoreDebug_DHCSR_C_HALT_Pos 1 /*!< CoreDebug DHCSR: C_HALT Position */ #define CoreDebug_DHCSR_C_HALT_Msk (1UL << CoreDebug_DHCSR_C_HALT_Pos) /*!< CoreDebug DHCSR: C_HALT Mask */ #define CoreDebug_DHCSR_C_DEBUGEN_Pos 0 /*!< CoreDebug DHCSR: C_DEBUGEN Position */ #define CoreDebug_DHCSR_C_DEBUGEN_Msk (1UL /*<< CoreDebug_DHCSR_C_DEBUGEN_Pos*/) /*!< CoreDebug DHCSR: C_DEBUGEN Mask */ /* Debug Core Register Selector Register */ #define CoreDebug_DCRSR_REGWnR_Pos 16 /*!< CoreDebug DCRSR: REGWnR Position */ #define CoreDebug_DCRSR_REGWnR_Msk (1UL << CoreDebug_DCRSR_REGWnR_Pos) /*!< CoreDebug DCRSR: REGWnR Mask */ #define CoreDebug_DCRSR_REGSEL_Pos 0 /*!< CoreDebug DCRSR: REGSEL Position */ #define CoreDebug_DCRSR_REGSEL_Msk (0x1FUL /*<< CoreDebug_DCRSR_REGSEL_Pos*/) /*!< CoreDebug DCRSR: REGSEL Mask */ /* Debug Exception and Monitor Control Register */ #define CoreDebug_DEMCR_TRCENA_Pos 24 /*!< CoreDebug DEMCR: TRCENA Position */ #define CoreDebug_DEMCR_TRCENA_Msk (1UL << CoreDebug_DEMCR_TRCENA_Pos) /*!< CoreDebug DEMCR: TRCENA Mask */ #define CoreDebug_DEMCR_MON_REQ_Pos 19 /*!< CoreDebug DEMCR: MON_REQ Position */ #define CoreDebug_DEMCR_MON_REQ_Msk (1UL << CoreDebug_DEMCR_MON_REQ_Pos) /*!< CoreDebug DEMCR: MON_REQ Mask */ #define CoreDebug_DEMCR_MON_STEP_Pos 18 /*!< CoreDebug DEMCR: MON_STEP Position */ #define CoreDebug_DEMCR_MON_STEP_Msk (1UL << CoreDebug_DEMCR_MON_STEP_Pos) /*!< CoreDebug DEMCR: MON_STEP Mask */ #define CoreDebug_DEMCR_MON_PEND_Pos 17 /*!< CoreDebug DEMCR: MON_PEND Position */ #define CoreDebug_DEMCR_MON_PEND_Msk (1UL << CoreDebug_DEMCR_MON_PEND_Pos) /*!< CoreDebug DEMCR: MON_PEND Mask */ #define CoreDebug_DEMCR_MON_EN_Pos 16 /*!< CoreDebug DEMCR: MON_EN Position */ #define CoreDebug_DEMCR_MON_EN_Msk (1UL << CoreDebug_DEMCR_MON_EN_Pos) /*!< CoreDebug DEMCR: MON_EN Mask */ #define CoreDebug_DEMCR_VC_HARDERR_Pos 10 /*!< CoreDebug DEMCR: VC_HARDERR Position */ #define CoreDebug_DEMCR_VC_HARDERR_Msk (1UL << CoreDebug_DEMCR_VC_HARDERR_Pos) /*!< CoreDebug DEMCR: VC_HARDERR Mask */ #define CoreDebug_DEMCR_VC_INTERR_Pos 9 /*!< CoreDebug DEMCR: VC_INTERR Position */ #define CoreDebug_DEMCR_VC_INTERR_Msk (1UL << CoreDebug_DEMCR_VC_INTERR_Pos) /*!< CoreDebug DEMCR: VC_INTERR Mask */ #define CoreDebug_DEMCR_VC_BUSERR_Pos 8 /*!< CoreDebug DEMCR: VC_BUSERR Position */ #define CoreDebug_DEMCR_VC_BUSERR_Msk (1UL << CoreDebug_DEMCR_VC_BUSERR_Pos) /*!< CoreDebug DEMCR: VC_BUSERR Mask */ #define CoreDebug_DEMCR_VC_STATERR_Pos 7 /*!< CoreDebug DEMCR: VC_STATERR Position */ #define CoreDebug_DEMCR_VC_STATERR_Msk (1UL << CoreDebug_DEMCR_VC_STATERR_Pos) /*!< CoreDebug DEMCR: VC_STATERR Mask */ #define CoreDebug_DEMCR_VC_CHKERR_Pos 6 /*!< CoreDebug DEMCR: VC_CHKERR Position */ #define CoreDebug_DEMCR_VC_CHKERR_Msk (1UL << CoreDebug_DEMCR_VC_CHKERR_Pos) /*!< CoreDebug DEMCR: VC_CHKERR Mask */ #define CoreDebug_DEMCR_VC_NOCPERR_Pos 5 /*!< CoreDebug DEMCR: VC_NOCPERR Position */ #define CoreDebug_DEMCR_VC_NOCPERR_Msk (1UL << CoreDebug_DEMCR_VC_NOCPERR_Pos) /*!< CoreDebug DEMCR: VC_NOCPERR Mask */ #define CoreDebug_DEMCR_VC_MMERR_Pos 4 /*!< CoreDebug DEMCR: VC_MMERR Position */ #define CoreDebug_DEMCR_VC_MMERR_Msk (1UL << CoreDebug_DEMCR_VC_MMERR_Pos) /*!< CoreDebug DEMCR: VC_MMERR Mask */ #define CoreDebug_DEMCR_VC_CORERESET_Pos 0 /*!< CoreDebug DEMCR: VC_CORERESET Position */ #define CoreDebug_DEMCR_VC_CORERESET_Msk (1UL /*<< CoreDebug_DEMCR_VC_CORERESET_Pos*/) /*!< CoreDebug DEMCR: VC_CORERESET Mask */ /*@} end of group CMSIS_CoreDebug */ /** \ingroup CMSIS_core_register \defgroup CMSIS_core_base Core Definitions \brief Definitions for base addresses, unions, and structures. @{ */ /* Memory mapping of Cortex-M4 Hardware */ #define SCS_BASE (0xE000E000UL) /*!< System Control Space Base Address */ #define ITM_BASE (0xE0000000UL) /*!< ITM Base Address */ #define DWT_BASE (0xE0001000UL) /*!< DWT Base Address */ #define TPI_BASE (0xE0040000UL) /*!< TPI Base Address */ #define CoreDebug_BASE (0xE000EDF0UL) /*!< Core Debug Base Address */ #define SysTick_BASE (SCS_BASE + 0x0010UL) /*!< SysTick Base Address */ #define NVIC_BASE (SCS_BASE + 0x0100UL) /*!< NVIC Base Address */ #define SCB_BASE (SCS_BASE + 0x0D00UL) /*!< System Control Block Base Address */ #define SCnSCB ((SCnSCB_Type *) SCS_BASE ) /*!< System control Register not in SCB */ #define SCB ((SCB_Type *) SCB_BASE ) /*!< SCB configuration struct */ #define SysTick ((SysTick_Type *) SysTick_BASE ) /*!< SysTick configuration struct */ #define NVIC ((NVIC_Type *) NVIC_BASE ) /*!< NVIC configuration struct */ #define ITM ((ITM_Type *) ITM_BASE ) /*!< ITM configuration struct */ #define DWT ((DWT_Type *) DWT_BASE ) /*!< DWT configuration struct */ #define TPI ((TPI_Type *) TPI_BASE ) /*!< TPI configuration struct */ #define CoreDebug ((CoreDebug_Type *) CoreDebug_BASE) /*!< Core Debug configuration struct */ #if (__MPU_PRESENT == 1) #define MPU_BASE (SCS_BASE + 0x0D90UL) /*!< Memory Protection Unit */ #define MPU ((MPU_Type *) MPU_BASE ) /*!< Memory Protection Unit */ #endif #if (__FPU_PRESENT == 1) #define FPU_BASE (SCS_BASE + 0x0F30UL) /*!< Floating Point Unit */ #define FPU ((FPU_Type *) FPU_BASE ) /*!< Floating Point Unit */ #endif /*@} */ /******************************************************************************* * Hardware Abstraction Layer Core Function Interface contains: - Core NVIC Functions - Core SysTick Functions - Core Debug Functions - Core Register Access Functions ******************************************************************************/ /** \defgroup CMSIS_Core_FunctionInterface Functions and Instructions Reference */ /* ########################## NVIC functions #################################### */ /** \ingroup CMSIS_Core_FunctionInterface \defgroup CMSIS_Core_NVICFunctions NVIC Functions \brief Functions that manage interrupts and exceptions via the NVIC. @{ */ /** \brief Set Priority Grouping The function sets the priority grouping field using the required unlock sequence. The parameter PriorityGroup is assigned to the field SCB->AIRCR [10:8] PRIGROUP field. Only values from 0..7 are used. In case of a conflict between priority grouping and available priority bits (__NVIC_PRIO_BITS), the smallest possible priority group is set. \param [in] PriorityGroup Priority grouping field. */ __STATIC_INLINE void NVIC_SetPriorityGrouping(uint32_t PriorityGroup) { uint32_t reg_value; uint32_t PriorityGroupTmp = (PriorityGroup & (uint32_t)0x07UL); /* only values 0..7 are used */ reg_value = SCB->AIRCR; /* read old register configuration */ reg_value &= ~((uint32_t)(SCB_AIRCR_VECTKEY_Msk | SCB_AIRCR_PRIGROUP_Msk)); /* clear bits to change */ reg_value = (reg_value | ((uint32_t)0x5FAUL << SCB_AIRCR_VECTKEY_Pos) | (PriorityGroupTmp << 8) ); /* Insert write key and priorty group */ SCB->AIRCR = reg_value; } /** \brief Get Priority Grouping The function reads the priority grouping field from the NVIC Interrupt Controller. \return Priority grouping field (SCB->AIRCR [10:8] PRIGROUP field). */ __STATIC_INLINE uint32_t NVIC_GetPriorityGrouping(void) { return ((uint32_t)((SCB->AIRCR & SCB_AIRCR_PRIGROUP_Msk) >> SCB_AIRCR_PRIGROUP_Pos)); } /** \brief Enable External Interrupt The function enables a device-specific interrupt in the NVIC interrupt controller. \param [in] IRQn External interrupt number. Value cannot be negative. */ __STATIC_INLINE void NVIC_EnableIRQ(IRQn_Type IRQn) { NVIC->ISER[(((uint32_t)(int32_t)IRQn) >> 5UL)] = (uint32_t)(1UL << (((uint32_t)(int32_t)IRQn) & 0x1FUL)); } /** \brief Disable External Interrupt The function disables a device-specific interrupt in the NVIC interrupt controller. \param [in] IRQn External interrupt number. Value cannot be negative. */ __STATIC_INLINE void NVIC_DisableIRQ(IRQn_Type IRQn) { NVIC->ICER[(((uint32_t)(int32_t)IRQn) >> 5UL)] = (uint32_t)(1UL << (((uint32_t)(int32_t)IRQn) & 0x1FUL)); } /** \brief Get Pending Interrupt The function reads the pending register in the NVIC and returns the pending bit for the specified interrupt. \param [in] IRQn Interrupt number. \return 0 Interrupt status is not pending. \return 1 Interrupt status is pending. */ __STATIC_INLINE uint32_t NVIC_GetPendingIRQ(IRQn_Type IRQn) { return((uint32_t)(((NVIC->ISPR[(((uint32_t)(int32_t)IRQn) >> 5UL)] & (1UL << (((uint32_t)(int32_t)IRQn) & 0x1FUL))) != 0UL) ? 1UL : 0UL)); } /** \brief Set Pending Interrupt The function sets the pending bit of an external interrupt. \param [in] IRQn Interrupt number. Value cannot be negative. */ __STATIC_INLINE void NVIC_SetPendingIRQ(IRQn_Type IRQn) { NVIC->ISPR[(((uint32_t)(int32_t)IRQn) >> 5UL)] = (uint32_t)(1UL << (((uint32_t)(int32_t)IRQn) & 0x1FUL)); } /** \brief Clear Pending Interrupt The function clears the pending bit of an external interrupt. \param [in] IRQn External interrupt number. Value cannot be negative. */ __STATIC_INLINE void NVIC_ClearPendingIRQ(IRQn_Type IRQn) { NVIC->ICPR[(((uint32_t)(int32_t)IRQn) >> 5UL)] = (uint32_t)(1UL << (((uint32_t)(int32_t)IRQn) & 0x1FUL)); } /** \brief Get Active Interrupt The function reads the active register in NVIC and returns the active bit. \param [in] IRQn Interrupt number. \return 0 Interrupt status is not active. \return 1 Interrupt status is active. */ __STATIC_INLINE uint32_t NVIC_GetActive(IRQn_Type IRQn) { return((uint32_t)(((NVIC->IABR[(((uint32_t)(int32_t)IRQn) >> 5UL)] & (1UL << (((uint32_t)(int32_t)IRQn) & 0x1FUL))) != 0UL) ? 1UL : 0UL)); } /** \brief Set Interrupt Priority The function sets the priority of an interrupt. \note The priority cannot be set for every core interrupt. \param [in] IRQn Interrupt number. \param [in] priority Priority to set. */ __STATIC_INLINE void NVIC_SetPriority(IRQn_Type IRQn, uint32_t priority) { if((int32_t)IRQn < 0) { SCB->SHP[(((uint32_t)(int32_t)IRQn) & 0xFUL)-4UL] = (uint8_t)((priority << (8 - __NVIC_PRIO_BITS)) & (uint32_t)0xFFUL); } else { NVIC->IP[((uint32_t)(int32_t)IRQn)] = (uint8_t)((priority << (8 - __NVIC_PRIO_BITS)) & (uint32_t)0xFFUL); } } /** \brief Get Interrupt Priority The function reads the priority of an interrupt. The interrupt number can be positive to specify an external (device specific) interrupt, or negative to specify an internal (core) interrupt. \param [in] IRQn Interrupt number. \return Interrupt Priority. Value is aligned automatically to the implemented priority bits of the microcontroller. */ __STATIC_INLINE uint32_t NVIC_GetPriority(IRQn_Type IRQn) { if((int32_t)IRQn < 0) { return(((uint32_t)SCB->SHP[(((uint32_t)(int32_t)IRQn) & 0xFUL)-4UL] >> (8 - __NVIC_PRIO_BITS))); } else { return(((uint32_t)NVIC->IP[((uint32_t)(int32_t)IRQn)] >> (8 - __NVIC_PRIO_BITS))); } } /** \brief Encode Priority The function encodes the priority for an interrupt with the given priority group, preemptive priority value, and subpriority value. In case of a conflict between priority grouping and available priority bits (__NVIC_PRIO_BITS), the smallest possible priority group is set. \param [in] PriorityGroup Used priority group. \param [in] PreemptPriority Preemptive priority value (starting from 0). \param [in] SubPriority Subpriority value (starting from 0). \return Encoded priority. Value can be used in the function \ref NVIC_SetPriority(). */ __STATIC_INLINE uint32_t NVIC_EncodePriority (uint32_t PriorityGroup, uint32_t PreemptPriority, uint32_t SubPriority) { uint32_t PriorityGroupTmp = (PriorityGroup & (uint32_t)0x07UL); /* only values 0..7 are used */ uint32_t PreemptPriorityBits; uint32_t SubPriorityBits; PreemptPriorityBits = ((7UL - PriorityGroupTmp) > (uint32_t)(__NVIC_PRIO_BITS)) ? (uint32_t)(__NVIC_PRIO_BITS) : (uint32_t)(7UL - PriorityGroupTmp); SubPriorityBits = ((PriorityGroupTmp + (uint32_t)(__NVIC_PRIO_BITS)) < (uint32_t)7UL) ? (uint32_t)0UL : (uint32_t)((PriorityGroupTmp - 7UL) + (uint32_t)(__NVIC_PRIO_BITS)); return ( ((PreemptPriority & (uint32_t)((1UL << (PreemptPriorityBits)) - 1UL)) << SubPriorityBits) | ((SubPriority & (uint32_t)((1UL << (SubPriorityBits )) - 1UL))) ); } /** \brief Decode Priority The function decodes an interrupt priority value with a given priority group to preemptive priority value and subpriority value. In case of a conflict between priority grouping and available priority bits (__NVIC_PRIO_BITS) the smallest possible priority group is set. \param [in] Priority Priority value, which can be retrieved with the function \ref NVIC_GetPriority(). \param [in] PriorityGroup Used priority group. \param [out] pPreemptPriority Preemptive priority value (starting from 0). \param [out] pSubPriority Subpriority value (starting from 0). */ __STATIC_INLINE void NVIC_DecodePriority (uint32_t Priority, uint32_t PriorityGroup, uint32_t* pPreemptPriority, uint32_t* pSubPriority) { uint32_t PriorityGroupTmp = (PriorityGroup & (uint32_t)0x07UL); /* only values 0..7 are used */ uint32_t PreemptPriorityBits; uint32_t SubPriorityBits; PreemptPriorityBits = ((7UL - PriorityGroupTmp) > (uint32_t)(__NVIC_PRIO_BITS)) ? (uint32_t)(__NVIC_PRIO_BITS) : (uint32_t)(7UL - PriorityGroupTmp); SubPriorityBits = ((PriorityGroupTmp + (uint32_t)(__NVIC_PRIO_BITS)) < (uint32_t)7UL) ? (uint32_t)0UL : (uint32_t)((PriorityGroupTmp - 7UL) + (uint32_t)(__NVIC_PRIO_BITS)); *pPreemptPriority = (Priority >> SubPriorityBits) & (uint32_t)((1UL << (PreemptPriorityBits)) - 1UL); *pSubPriority = (Priority ) & (uint32_t)((1UL << (SubPriorityBits )) - 1UL); } /** \brief System Reset The function initiates a system reset request to reset the MCU. */ __STATIC_INLINE void NVIC_SystemReset(void) { __DSB(); /* Ensure all outstanding memory accesses included buffered write are completed before reset */ SCB->AIRCR = (uint32_t)((0x5FAUL << SCB_AIRCR_VECTKEY_Pos) | (SCB->AIRCR & SCB_AIRCR_PRIGROUP_Msk) | SCB_AIRCR_SYSRESETREQ_Msk ); /* Keep priority group unchanged */ __DSB(); /* Ensure completion of memory access */ while(1) { __NOP(); } /* wait until reset */ } /*@} end of CMSIS_Core_NVICFunctions */ /* ################################## SysTick function ############################################ */ /** \ingroup CMSIS_Core_FunctionInterface \defgroup CMSIS_Core_SysTickFunctions SysTick Functions \brief Functions that configure the System. @{ */ #if (__Vendor_SysTickConfig == 0) /** \brief System Tick Configuration The function initializes the System Timer and its interrupt, and starts the System Tick Timer. Counter is in free running mode to generate periodic interrupts. \param [in] ticks Number of ticks between two interrupts. \return 0 Function succeeded. \return 1 Function failed. \note When the variable __Vendor_SysTickConfig is set to 1, then the function SysTick_Config is not included. In this case, the file device.h must contain a vendor-specific implementation of this function. */ __STATIC_INLINE uint32_t SysTick_Config(uint32_t ticks) { if ((ticks - 1UL) > SysTick_LOAD_RELOAD_Msk) { return (1UL); } /* Reload value impossible */ SysTick->LOAD = (uint32_t)(ticks - 1UL); /* set reload register */ NVIC_SetPriority (SysTick_IRQn, (1UL << __NVIC_PRIO_BITS) - 1UL); /* set Priority for Systick Interrupt */ SysTick->VAL = 0UL; /* Load the SysTick Counter Value */ SysTick->CTRL = SysTick_CTRL_CLKSOURCE_Msk | SysTick_CTRL_TICKINT_Msk | SysTick_CTRL_ENABLE_Msk; /* Enable SysTick IRQ and SysTick Timer */ return (0UL); /* Function successful */ } #endif /*@} end of CMSIS_Core_SysTickFunctions */ /* ##################################### Debug In/Output function ########################################### */ /** \ingroup CMSIS_Core_FunctionInterface \defgroup CMSIS_core_DebugFunctions ITM Functions \brief Functions that access the ITM debug interface. @{ */ extern volatile int32_t ITM_RxBuffer; /*!< External variable to receive characters. */ #define ITM_RXBUFFER_EMPTY 0x5AA55AA5 /*!< Value identifying \ref ITM_RxBuffer is ready for next character. */ /** \brief ITM Send Character The function transmits a character via the ITM channel 0, and \li Just returns when no debugger is connected that has booked the output. \li Is blocking when a debugger is connected, but the previous character sent has not been transmitted. \param [in] ch Character to transmit. \returns Character to transmit. */ __STATIC_INLINE uint32_t ITM_SendChar (uint32_t ch) { if (((ITM->TCR & ITM_TCR_ITMENA_Msk) != 0UL) && /* ITM enabled */ ((ITM->TER & 1UL ) != 0UL) ) /* ITM Port #0 enabled */ { while (ITM->PORT[0].u32 == 0UL) { __NOP(); } ITM->PORT[0].u8 = (uint8_t)ch; } return (ch); } /** \brief ITM Receive Character The function inputs a character via the external variable \ref ITM_RxBuffer. \return Received character. \return -1 No character pending. */ __STATIC_INLINE int32_t ITM_ReceiveChar (void) { int32_t ch = -1; /* no character available */ if (ITM_RxBuffer != ITM_RXBUFFER_EMPTY) { ch = ITM_RxBuffer; ITM_RxBuffer = ITM_RXBUFFER_EMPTY; /* ready for next character */ } return (ch); } /** \brief ITM Check Character The function checks whether a character is pending for reading in the variable \ref ITM_RxBuffer. \return 0 No character available. \return 1 Character available. */ __STATIC_INLINE int32_t ITM_CheckChar (void) { if (ITM_RxBuffer == ITM_RXBUFFER_EMPTY) { return (0); /* no character available */ } else { return (1); /* character available */ } } /*@} end of CMSIS_core_DebugFunctions */ #ifdef __cplusplus } #endif #endif /* __CORE_CM4_H_DEPENDANT */ #endif /* __CMSIS_GENERIC */ ================================================ FILE: Zelig/mbed/TARGET_NUCLEO_F401RE/core_cm4_simd.h ================================================ /**************************************************************************//** * @file core_cm4_simd.h * @brief CMSIS Cortex-M4 SIMD Header File * @version V3.20 * @date 25. February 2013 * * @note * ******************************************************************************/ /* Copyright (c) 2009 - 2013 ARM LIMITED All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: - Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. - Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. - Neither the name of ARM 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 COPYRIGHT HOLDERS AND CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. ---------------------------------------------------------------------------*/ #ifdef __cplusplus extern "C" { #endif #ifndef __CORE_CM4_SIMD_H #define __CORE_CM4_SIMD_H /******************************************************************************* * Hardware Abstraction Layer ******************************************************************************/ /* ################### Compiler specific Intrinsics ########################### */ /** \defgroup CMSIS_SIMD_intrinsics CMSIS SIMD Intrinsics Access to dedicated SIMD instructions @{ */ #if defined ( __CC_ARM ) /*------------------RealView Compiler -----------------*/ /* ARM armcc specific functions */ /*------ CM4 SIMD Intrinsics -----------------------------------------------------*/ #define __SADD8 __sadd8 #define __QADD8 __qadd8 #define __SHADD8 __shadd8 #define __UADD8 __uadd8 #define __UQADD8 __uqadd8 #define __UHADD8 __uhadd8 #define __SSUB8 __ssub8 #define __QSUB8 __qsub8 #define __SHSUB8 __shsub8 #define __USUB8 __usub8 #define __UQSUB8 __uqsub8 #define __UHSUB8 __uhsub8 #define __SADD16 __sadd16 #define __QADD16 __qadd16 #define __SHADD16 __shadd16 #define __UADD16 __uadd16 #define __UQADD16 __uqadd16 #define __UHADD16 __uhadd16 #define __SSUB16 __ssub16 #define __QSUB16 __qsub16 #define __SHSUB16 __shsub16 #define __USUB16 __usub16 #define __UQSUB16 __uqsub16 #define __UHSUB16 __uhsub16 #define __SASX __sasx #define __QASX __qasx #define __SHASX __shasx #define __UASX __uasx #define __UQASX __uqasx #define __UHASX __uhasx #define __SSAX __ssax #define __QSAX __qsax #define __SHSAX __shsax #define __USAX __usax #define __UQSAX __uqsax #define __UHSAX __uhsax #define __USAD8 __usad8 #define __USADA8 __usada8 #define __SSAT16 __ssat16 #define __USAT16 __usat16 #define __UXTB16 __uxtb16 #define __UXTAB16 __uxtab16 #define __SXTB16 __sxtb16 #define __SXTAB16 __sxtab16 #define __SMUAD __smuad #define __SMUADX __smuadx #define __SMLAD __smlad #define __SMLADX __smladx #define __SMLALD __smlald #define __SMLALDX __smlaldx #define __SMUSD __smusd #define __SMUSDX __smusdx #define __SMLSD __smlsd #define __SMLSDX __smlsdx #define __SMLSLD __smlsld #define __SMLSLDX __smlsldx #define __SEL __sel #define __QADD __qadd #define __QSUB __qsub #define __PKHBT(ARG1,ARG2,ARG3) ( ((((uint32_t)(ARG1)) ) & 0x0000FFFFUL) | \ ((((uint32_t)(ARG2)) << (ARG3)) & 0xFFFF0000UL) ) #define __PKHTB(ARG1,ARG2,ARG3) ( ((((uint32_t)(ARG1)) ) & 0xFFFF0000UL) | \ ((((uint32_t)(ARG2)) >> (ARG3)) & 0x0000FFFFUL) ) #define __SMMLA(ARG1,ARG2,ARG3) ( (int32_t)((((int64_t)(ARG1) * (ARG2)) + \ ((int64_t)(ARG3) << 32) ) >> 32)) /*-- End CM4 SIMD Intrinsics -----------------------------------------------------*/ #elif defined ( __ICCARM__ ) /*------------------ ICC Compiler -------------------*/ /* IAR iccarm specific functions */ /*------ CM4 SIMD Intrinsics -----------------------------------------------------*/ #include /*-- End CM4 SIMD Intrinsics -----------------------------------------------------*/ #elif defined ( __TMS470__ ) /*---------------- TI CCS Compiler ------------------*/ /* TI CCS specific functions */ /*------ CM4 SIMD Intrinsics -----------------------------------------------------*/ #include /*-- End CM4 SIMD Intrinsics -----------------------------------------------------*/ #elif defined ( __GNUC__ ) /*------------------ GNU Compiler ---------------------*/ /* GNU gcc specific functions */ /*------ CM4 SIMD Intrinsics -----------------------------------------------------*/ __attribute__( ( always_inline ) ) __STATIC_INLINE uint32_t __SADD8(uint32_t op1, uint32_t op2) { uint32_t result; __ASM volatile ("sadd8 %0, %1, %2" : "=r" (result) : "r" (op1), "r" (op2) ); return(result); } __attribute__( ( always_inline ) ) __STATIC_INLINE uint32_t __QADD8(uint32_t op1, uint32_t op2) { uint32_t result; __ASM volatile ("qadd8 %0, %1, %2" : "=r" (result) : "r" (op1), "r" (op2) ); return(result); } __attribute__( ( always_inline ) ) __STATIC_INLINE uint32_t __SHADD8(uint32_t op1, uint32_t op2) { uint32_t result; __ASM volatile ("shadd8 %0, %1, %2" : "=r" (result) : "r" (op1), "r" (op2) ); return(result); } __attribute__( ( always_inline ) ) __STATIC_INLINE uint32_t __UADD8(uint32_t op1, uint32_t op2) { uint32_t result; __ASM volatile ("uadd8 %0, %1, %2" : "=r" (result) : "r" (op1), "r" (op2) ); return(result); } __attribute__( ( always_inline ) ) __STATIC_INLINE uint32_t __UQADD8(uint32_t op1, uint32_t op2) { uint32_t result; __ASM volatile ("uqadd8 %0, %1, %2" : "=r" (result) : "r" (op1), "r" (op2) ); return(result); } __attribute__( ( always_inline ) ) __STATIC_INLINE uint32_t __UHADD8(uint32_t op1, uint32_t op2) { uint32_t result; __ASM volatile ("uhadd8 %0, %1, %2" : "=r" (result) : "r" (op1), "r" (op2) ); return(result); } __attribute__( ( always_inline ) ) __STATIC_INLINE uint32_t __SSUB8(uint32_t op1, uint32_t op2) { uint32_t result; __ASM volatile ("ssub8 %0, %1, %2" : "=r" (result) : "r" (op1), "r" (op2) ); return(result); } __attribute__( ( always_inline ) ) __STATIC_INLINE uint32_t __QSUB8(uint32_t op1, uint32_t op2) { uint32_t result; __ASM volatile ("qsub8 %0, %1, %2" : "=r" (result) : "r" (op1), "r" (op2) ); return(result); } __attribute__( ( always_inline ) ) __STATIC_INLINE uint32_t __SHSUB8(uint32_t op1, uint32_t op2) { uint32_t result; __ASM volatile ("shsub8 %0, %1, %2" : "=r" (result) : "r" (op1), "r" (op2) ); return(result); } __attribute__( ( always_inline ) ) __STATIC_INLINE uint32_t __USUB8(uint32_t op1, uint32_t op2) { uint32_t result; __ASM volatile ("usub8 %0, %1, %2" : "=r" (result) : "r" (op1), "r" (op2) ); return(result); } __attribute__( ( always_inline ) ) __STATIC_INLINE uint32_t __UQSUB8(uint32_t op1, uint32_t op2) { uint32_t result; __ASM volatile ("uqsub8 %0, %1, %2" : "=r" (result) : "r" (op1), "r" (op2) ); return(result); } __attribute__( ( always_inline ) ) __STATIC_INLINE uint32_t __UHSUB8(uint32_t op1, uint32_t op2) { uint32_t result; __ASM volatile ("uhsub8 %0, %1, %2" : "=r" (result) : "r" (op1), "r" (op2) ); return(result); } __attribute__( ( always_inline ) ) __STATIC_INLINE uint32_t __SADD16(uint32_t op1, uint32_t op2) { uint32_t result; __ASM volatile ("sadd16 %0, %1, %2" : "=r" (result) : "r" (op1), "r" (op2) ); return(result); } __attribute__( ( always_inline ) ) __STATIC_INLINE uint32_t __QADD16(uint32_t op1, uint32_t op2) { uint32_t result; __ASM volatile ("qadd16 %0, %1, %2" : "=r" (result) : "r" (op1), "r" (op2) ); return(result); } __attribute__( ( always_inline ) ) __STATIC_INLINE uint32_t __SHADD16(uint32_t op1, uint32_t op2) { uint32_t result; __ASM volatile ("shadd16 %0, %1, %2" : "=r" (result) : "r" (op1), "r" (op2) ); return(result); } __attribute__( ( always_inline ) ) __STATIC_INLINE uint32_t __UADD16(uint32_t op1, uint32_t op2) { uint32_t result; __ASM volatile ("uadd16 %0, %1, %2" : "=r" (result) : "r" (op1), "r" (op2) ); return(result); } __attribute__( ( always_inline ) ) __STATIC_INLINE uint32_t __UQADD16(uint32_t op1, uint32_t op2) { uint32_t result; __ASM volatile ("uqadd16 %0, %1, %2" : "=r" (result) : "r" (op1), "r" (op2) ); return(result); } __attribute__( ( always_inline ) ) __STATIC_INLINE uint32_t __UHADD16(uint32_t op1, uint32_t op2) { uint32_t result; __ASM volatile ("uhadd16 %0, %1, %2" : "=r" (result) : "r" (op1), "r" (op2) ); return(result); } __attribute__( ( always_inline ) ) __STATIC_INLINE uint32_t __SSUB16(uint32_t op1, uint32_t op2) { uint32_t result; __ASM volatile ("ssub16 %0, %1, %2" : "=r" (result) : "r" (op1), "r" (op2) ); return(result); } __attribute__( ( always_inline ) ) __STATIC_INLINE uint32_t __QSUB16(uint32_t op1, uint32_t op2) { uint32_t result; __ASM volatile ("qsub16 %0, %1, %2" : "=r" (result) : "r" (op1), "r" (op2) ); return(result); } __attribute__( ( always_inline ) ) __STATIC_INLINE uint32_t __SHSUB16(uint32_t op1, uint32_t op2) { uint32_t result; __ASM volatile ("shsub16 %0, %1, %2" : "=r" (result) : "r" (op1), "r" (op2) ); return(result); } __attribute__( ( always_inline ) ) __STATIC_INLINE uint32_t __USUB16(uint32_t op1, uint32_t op2) { uint32_t result; __ASM volatile ("usub16 %0, %1, %2" : "=r" (result) : "r" (op1), "r" (op2) ); return(result); } __attribute__( ( always_inline ) ) __STATIC_INLINE uint32_t __UQSUB16(uint32_t op1, uint32_t op2) { uint32_t result; __ASM volatile ("uqsub16 %0, %1, %2" : "=r" (result) : "r" (op1), "r" (op2) ); return(result); } __attribute__( ( always_inline ) ) __STATIC_INLINE uint32_t __UHSUB16(uint32_t op1, uint32_t op2) { uint32_t result; __ASM volatile ("uhsub16 %0, %1, %2" : "=r" (result) : "r" (op1), "r" (op2) ); return(result); } __attribute__( ( always_inline ) ) __STATIC_INLINE uint32_t __SASX(uint32_t op1, uint32_t op2) { uint32_t result; __ASM volatile ("sasx %0, %1, %2" : "=r" (result) : "r" (op1), "r" (op2) ); return(result); } __attribute__( ( always_inline ) ) __STATIC_INLINE uint32_t __QASX(uint32_t op1, uint32_t op2) { uint32_t result; __ASM volatile ("qasx %0, %1, %2" : "=r" (result) : "r" (op1), "r" (op2) ); return(result); } __attribute__( ( always_inline ) ) __STATIC_INLINE uint32_t __SHASX(uint32_t op1, uint32_t op2) { uint32_t result; __ASM volatile ("shasx %0, %1, %2" : "=r" (result) : "r" (op1), "r" (op2) ); return(result); } __attribute__( ( always_inline ) ) __STATIC_INLINE uint32_t __UASX(uint32_t op1, uint32_t op2) { uint32_t result; __ASM volatile ("uasx %0, %1, %2" : "=r" (result) : "r" (op1), "r" (op2) ); return(result); } __attribute__( ( always_inline ) ) __STATIC_INLINE uint32_t __UQASX(uint32_t op1, uint32_t op2) { uint32_t result; __ASM volatile ("uqasx %0, %1, %2" : "=r" (result) : "r" (op1), "r" (op2) ); return(result); } __attribute__( ( always_inline ) ) __STATIC_INLINE uint32_t __UHASX(uint32_t op1, uint32_t op2) { uint32_t result; __ASM volatile ("uhasx %0, %1, %2" : "=r" (result) : "r" (op1), "r" (op2) ); return(result); } __attribute__( ( always_inline ) ) __STATIC_INLINE uint32_t __SSAX(uint32_t op1, uint32_t op2) { uint32_t result; __ASM volatile ("ssax %0, %1, %2" : "=r" (result) : "r" (op1), "r" (op2) ); return(result); } __attribute__( ( always_inline ) ) __STATIC_INLINE uint32_t __QSAX(uint32_t op1, uint32_t op2) { uint32_t result; __ASM volatile ("qsax %0, %1, %2" : "=r" (result) : "r" (op1), "r" (op2) ); return(result); } __attribute__( ( always_inline ) ) __STATIC_INLINE uint32_t __SHSAX(uint32_t op1, uint32_t op2) { uint32_t result; __ASM volatile ("shsax %0, %1, %2" : "=r" (result) : "r" (op1), "r" (op2) ); return(result); } __attribute__( ( always_inline ) ) __STATIC_INLINE uint32_t __USAX(uint32_t op1, uint32_t op2) { uint32_t result; __ASM volatile ("usax %0, %1, %2" : "=r" (result) : "r" (op1), "r" (op2) ); return(result); } __attribute__( ( always_inline ) ) __STATIC_INLINE uint32_t __UQSAX(uint32_t op1, uint32_t op2) { uint32_t result; __ASM volatile ("uqsax %0, %1, %2" : "=r" (result) : "r" (op1), "r" (op2) ); return(result); } __attribute__( ( always_inline ) ) __STATIC_INLINE uint32_t __UHSAX(uint32_t op1, uint32_t op2) { uint32_t result; __ASM volatile ("uhsax %0, %1, %2" : "=r" (result) : "r" (op1), "r" (op2) ); return(result); } __attribute__( ( always_inline ) ) __STATIC_INLINE uint32_t __USAD8(uint32_t op1, uint32_t op2) { uint32_t result; __ASM volatile ("usad8 %0, %1, %2" : "=r" (result) : "r" (op1), "r" (op2) ); return(result); } __attribute__( ( always_inline ) ) __STATIC_INLINE uint32_t __USADA8(uint32_t op1, uint32_t op2, uint32_t op3) { uint32_t result; __ASM volatile ("usada8 %0, %1, %2, %3" : "=r" (result) : "r" (op1), "r" (op2), "r" (op3) ); return(result); } #define __SSAT16(ARG1,ARG2) \ ({ \ uint32_t __RES, __ARG1 = (ARG1); \ __ASM ("ssat16 %0, %1, %2" : "=r" (__RES) : "I" (ARG2), "r" (__ARG1) ); \ __RES; \ }) #define __USAT16(ARG1,ARG2) \ ({ \ uint32_t __RES, __ARG1 = (ARG1); \ __ASM ("usat16 %0, %1, %2" : "=r" (__RES) : "I" (ARG2), "r" (__ARG1) ); \ __RES; \ }) __attribute__( ( always_inline ) ) __STATIC_INLINE uint32_t __UXTB16(uint32_t op1) { uint32_t result; __ASM volatile ("uxtb16 %0, %1" : "=r" (result) : "r" (op1)); return(result); } __attribute__( ( always_inline ) ) __STATIC_INLINE uint32_t __UXTAB16(uint32_t op1, uint32_t op2) { uint32_t result; __ASM volatile ("uxtab16 %0, %1, %2" : "=r" (result) : "r" (op1), "r" (op2) ); return(result); } __attribute__( ( always_inline ) ) __STATIC_INLINE uint32_t __SXTB16(uint32_t op1) { uint32_t result; __ASM volatile ("sxtb16 %0, %1" : "=r" (result) : "r" (op1)); return(result); } __attribute__( ( always_inline ) ) __STATIC_INLINE uint32_t __SXTAB16(uint32_t op1, uint32_t op2) { uint32_t result; __ASM volatile ("sxtab16 %0, %1, %2" : "=r" (result) : "r" (op1), "r" (op2) ); return(result); } __attribute__( ( always_inline ) ) __STATIC_INLINE uint32_t __SMUAD (uint32_t op1, uint32_t op2) { uint32_t result; __ASM volatile ("smuad %0, %1, %2" : "=r" (result) : "r" (op1), "r" (op2) ); return(result); } __attribute__( ( always_inline ) ) __STATIC_INLINE uint32_t __SMUADX (uint32_t op1, uint32_t op2) { uint32_t result; __ASM volatile ("smuadx %0, %1, %2" : "=r" (result) : "r" (op1), "r" (op2) ); return(result); } __attribute__( ( always_inline ) ) __STATIC_INLINE uint32_t __SMLAD (uint32_t op1, uint32_t op2, uint32_t op3) { uint32_t result; __ASM volatile ("smlad %0, %1, %2, %3" : "=r" (result) : "r" (op1), "r" (op2), "r" (op3) ); return(result); } __attribute__( ( always_inline ) ) __STATIC_INLINE uint32_t __SMLADX (uint32_t op1, uint32_t op2, uint32_t op3) { uint32_t result; __ASM volatile ("smladx %0, %1, %2, %3" : "=r" (result) : "r" (op1), "r" (op2), "r" (op3) ); return(result); } #define __SMLALD(ARG1,ARG2,ARG3) \ ({ \ uint32_t __ARG1 = (ARG1), __ARG2 = (ARG2), __ARG3_H = (uint32_t)((uint64_t)(ARG3) >> 32), __ARG3_L = (uint32_t)((uint64_t)(ARG3) & 0xFFFFFFFFUL); \ __ASM volatile ("smlald %0, %1, %2, %3" : "=r" (__ARG3_L), "=r" (__ARG3_H) : "r" (__ARG1), "r" (__ARG2), "0" (__ARG3_L), "1" (__ARG3_H) ); \ (uint64_t)(((uint64_t)__ARG3_H << 32) | __ARG3_L); \ }) #define __SMLALDX(ARG1,ARG2,ARG3) \ ({ \ uint32_t __ARG1 = (ARG1), __ARG2 = (ARG2), __ARG3_H = (uint32_t)((uint64_t)(ARG3) >> 32), __ARG3_L = (uint32_t)((uint64_t)(ARG3) & 0xFFFFFFFFUL); \ __ASM volatile ("smlaldx %0, %1, %2, %3" : "=r" (__ARG3_L), "=r" (__ARG3_H) : "r" (__ARG1), "r" (__ARG2), "0" (__ARG3_L), "1" (__ARG3_H) ); \ (uint64_t)(((uint64_t)__ARG3_H << 32) | __ARG3_L); \ }) __attribute__( ( always_inline ) ) __STATIC_INLINE uint32_t __SMUSD (uint32_t op1, uint32_t op2) { uint32_t result; __ASM volatile ("smusd %0, %1, %2" : "=r" (result) : "r" (op1), "r" (op2) ); return(result); } __attribute__( ( always_inline ) ) __STATIC_INLINE uint32_t __SMUSDX (uint32_t op1, uint32_t op2) { uint32_t result; __ASM volatile ("smusdx %0, %1, %2" : "=r" (result) : "r" (op1), "r" (op2) ); return(result); } __attribute__( ( always_inline ) ) __STATIC_INLINE uint32_t __SMLSD (uint32_t op1, uint32_t op2, uint32_t op3) { uint32_t result; __ASM volatile ("smlsd %0, %1, %2, %3" : "=r" (result) : "r" (op1), "r" (op2), "r" (op3) ); return(result); } __attribute__( ( always_inline ) ) __STATIC_INLINE uint32_t __SMLSDX (uint32_t op1, uint32_t op2, uint32_t op3) { uint32_t result; __ASM volatile ("smlsdx %0, %1, %2, %3" : "=r" (result) : "r" (op1), "r" (op2), "r" (op3) ); return(result); } #define __SMLSLD(ARG1,ARG2,ARG3) \ ({ \ uint32_t __ARG1 = (ARG1), __ARG2 = (ARG2), __ARG3_H = (uint32_t)((ARG3) >> 32), __ARG3_L = (uint32_t)((ARG3) & 0xFFFFFFFFUL); \ __ASM volatile ("smlsld %0, %1, %2, %3" : "=r" (__ARG3_L), "=r" (__ARG3_H) : "r" (__ARG1), "r" (__ARG2), "0" (__ARG3_L), "1" (__ARG3_H) ); \ (uint64_t)(((uint64_t)__ARG3_H << 32) | __ARG3_L); \ }) #define __SMLSLDX(ARG1,ARG2,ARG3) \ ({ \ uint32_t __ARG1 = (ARG1), __ARG2 = (ARG2), __ARG3_H = (uint32_t)((ARG3) >> 32), __ARG3_L = (uint32_t)((ARG3) & 0xFFFFFFFFUL); \ __ASM volatile ("smlsldx %0, %1, %2, %3" : "=r" (__ARG3_L), "=r" (__ARG3_H) : "r" (__ARG1), "r" (__ARG2), "0" (__ARG3_L), "1" (__ARG3_H) ); \ (uint64_t)(((uint64_t)__ARG3_H << 32) | __ARG3_L); \ }) __attribute__( ( always_inline ) ) __STATIC_INLINE uint32_t __SEL (uint32_t op1, uint32_t op2) { uint32_t result; __ASM volatile ("sel %0, %1, %2" : "=r" (result) : "r" (op1), "r" (op2) ); return(result); } __attribute__( ( always_inline ) ) __STATIC_INLINE uint32_t __QADD(uint32_t op1, uint32_t op2) { uint32_t result; __ASM volatile ("qadd %0, %1, %2" : "=r" (result) : "r" (op1), "r" (op2) ); return(result); } __attribute__( ( always_inline ) ) __STATIC_INLINE uint32_t __QSUB(uint32_t op1, uint32_t op2) { uint32_t result; __ASM volatile ("qsub %0, %1, %2" : "=r" (result) : "r" (op1), "r" (op2) ); return(result); } #define __PKHBT(ARG1,ARG2,ARG3) \ ({ \ uint32_t __RES, __ARG1 = (ARG1), __ARG2 = (ARG2); \ __ASM ("pkhbt %0, %1, %2, lsl %3" : "=r" (__RES) : "r" (__ARG1), "r" (__ARG2), "I" (ARG3) ); \ __RES; \ }) #define __PKHTB(ARG1,ARG2,ARG3) \ ({ \ uint32_t __RES, __ARG1 = (ARG1), __ARG2 = (ARG2); \ if (ARG3 == 0) \ __ASM ("pkhtb %0, %1, %2" : "=r" (__RES) : "r" (__ARG1), "r" (__ARG2) ); \ else \ __ASM ("pkhtb %0, %1, %2, asr %3" : "=r" (__RES) : "r" (__ARG1), "r" (__ARG2), "I" (ARG3) ); \ __RES; \ }) __attribute__( ( always_inline ) ) __STATIC_INLINE uint32_t __SMMLA (int32_t op1, int32_t op2, int32_t op3) { int32_t result; __ASM volatile ("smmla %0, %1, %2, %3" : "=r" (result): "r" (op1), "r" (op2), "r" (op3) ); return(result); } /*-- End CM4 SIMD Intrinsics -----------------------------------------------------*/ #elif defined ( __TASKING__ ) /*------------------ TASKING Compiler --------------*/ /* TASKING carm specific functions */ /*------ CM4 SIMD Intrinsics -----------------------------------------------------*/ /* not yet supported */ /*-- End CM4 SIMD Intrinsics -----------------------------------------------------*/ #endif /*@} end of group CMSIS_SIMD_intrinsics */ #endif /* __CORE_CM4_SIMD_H */ #ifdef __cplusplus } #endif ================================================ FILE: Zelig/mbed/TARGET_NUCLEO_F401RE/core_cm7.h ================================================ /**************************************************************************//** * @file core_cm7.h * @brief CMSIS Cortex-M7 Core Peripheral Access Layer Header File * @version V4.10 * @date 18. March 2015 * * @note * ******************************************************************************/ /* Copyright (c) 2009 - 2015 ARM LIMITED All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: - Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. - Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. - Neither the name of ARM 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 COPYRIGHT HOLDERS AND 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. ---------------------------------------------------------------------------*/ #if defined ( __ICCARM__ ) #pragma system_include /* treat file as system include file for MISRA check */ #endif #ifndef __CORE_CM7_H_GENERIC #define __CORE_CM7_H_GENERIC #ifdef __cplusplus extern "C" { #endif /** \page CMSIS_MISRA_Exceptions MISRA-C:2004 Compliance Exceptions CMSIS violates the following MISRA-C:2004 rules: \li Required Rule 8.5, object/function definition in header file.
Function definitions in header files are used to allow 'inlining'. \li Required Rule 18.4, declaration of union type or object of union type: '{...}'.
Unions are used for effective representation of core registers. \li Advisory Rule 19.7, Function-like macro defined.
Function-like macros are used to allow more efficient code. */ /******************************************************************************* * CMSIS definitions ******************************************************************************/ /** \ingroup Cortex_M7 @{ */ /* CMSIS CM7 definitions */ #define __CM7_CMSIS_VERSION_MAIN (0x04) /*!< [31:16] CMSIS HAL main version */ #define __CM7_CMSIS_VERSION_SUB (0x00) /*!< [15:0] CMSIS HAL sub version */ #define __CM7_CMSIS_VERSION ((__CM7_CMSIS_VERSION_MAIN << 16) | \ __CM7_CMSIS_VERSION_SUB ) /*!< CMSIS HAL version number */ #define __CORTEX_M (0x07) /*!< Cortex-M Core */ #if defined ( __CC_ARM ) #define __ASM __asm /*!< asm keyword for ARM Compiler */ #define __INLINE __inline /*!< inline keyword for ARM Compiler */ #define __STATIC_INLINE static __inline #elif defined ( __GNUC__ ) #define __ASM __asm /*!< asm keyword for GNU Compiler */ #define __INLINE inline /*!< inline keyword for GNU Compiler */ #define __STATIC_INLINE static inline #elif defined ( __ICCARM__ ) #define __ASM __asm /*!< asm keyword for IAR Compiler */ #define __INLINE inline /*!< inline keyword for IAR Compiler. Only available in High optimization mode! */ #define __STATIC_INLINE static inline #elif defined ( __TMS470__ ) #define __ASM __asm /*!< asm keyword for TI CCS Compiler */ #define __STATIC_INLINE static inline #elif defined ( __TASKING__ ) #define __ASM __asm /*!< asm keyword for TASKING Compiler */ #define __INLINE inline /*!< inline keyword for TASKING Compiler */ #define __STATIC_INLINE static inline #elif defined ( __CSMC__ ) #define __packed #define __ASM _asm /*!< asm keyword for COSMIC Compiler */ #define __INLINE inline /*use -pc99 on compile line !< inline keyword for COSMIC Compiler */ #define __STATIC_INLINE static inline #endif /** __FPU_USED indicates whether an FPU is used or not. For this, __FPU_PRESENT has to be checked prior to making use of FPU specific registers and functions. */ #if defined ( __CC_ARM ) #if defined __TARGET_FPU_VFP #if (__FPU_PRESENT == 1) #define __FPU_USED 1 #else #warning "Compiler generates FPU instructions for a device without an FPU (check __FPU_PRESENT)" #define __FPU_USED 0 #endif #else #define __FPU_USED 0 #endif #elif defined ( __GNUC__ ) #if defined (__VFP_FP__) && !defined(__SOFTFP__) #if (__FPU_PRESENT == 1) #define __FPU_USED 1 #else #warning "Compiler generates FPU instructions for a device without an FPU (check __FPU_PRESENT)" #define __FPU_USED 0 #endif #else #define __FPU_USED 0 #endif #elif defined ( __ICCARM__ ) #if defined __ARMVFP__ #if (__FPU_PRESENT == 1) #define __FPU_USED 1 #else #warning "Compiler generates FPU instructions for a device without an FPU (check __FPU_PRESENT)" #define __FPU_USED 0 #endif #else #define __FPU_USED 0 #endif #elif defined ( __TMS470__ ) #if defined __TI_VFP_SUPPORT__ #if (__FPU_PRESENT == 1) #define __FPU_USED 1 #else #warning "Compiler generates FPU instructions for a device without an FPU (check __FPU_PRESENT)" #define __FPU_USED 0 #endif #else #define __FPU_USED 0 #endif #elif defined ( __TASKING__ ) #if defined __FPU_VFP__ #if (__FPU_PRESENT == 1) #define __FPU_USED 1 #else #error "Compiler generates FPU instructions for a device without an FPU (check __FPU_PRESENT)" #define __FPU_USED 0 #endif #else #define __FPU_USED 0 #endif #elif defined ( __CSMC__ ) /* Cosmic */ #if ( __CSMC__ & 0x400) // FPU present for parser #if (__FPU_PRESENT == 1) #define __FPU_USED 1 #else #error "Compiler generates FPU instructions for a device without an FPU (check __FPU_PRESENT)" #define __FPU_USED 0 #endif #else #define __FPU_USED 0 #endif #endif #include /* standard types definitions */ #include /* Core Instruction Access */ #include /* Core Function Access */ #include /* Compiler specific SIMD Intrinsics */ #ifdef __cplusplus } #endif #endif /* __CORE_CM7_H_GENERIC */ #ifndef __CMSIS_GENERIC #ifndef __CORE_CM7_H_DEPENDANT #define __CORE_CM7_H_DEPENDANT #ifdef __cplusplus extern "C" { #endif /* check device defines and use defaults */ #if defined __CHECK_DEVICE_DEFINES #ifndef __CM7_REV #define __CM7_REV 0x0000 #warning "__CM7_REV not defined in device header file; using default!" #endif #ifndef __FPU_PRESENT #define __FPU_PRESENT 0 #warning "__FPU_PRESENT not defined in device header file; using default!" #endif #ifndef __MPU_PRESENT #define __MPU_PRESENT 0 #warning "__MPU_PRESENT not defined in device header file; using default!" #endif #ifndef __ICACHE_PRESENT #define __ICACHE_PRESENT 0 #warning "__ICACHE_PRESENT not defined in device header file; using default!" #endif #ifndef __DCACHE_PRESENT #define __DCACHE_PRESENT 0 #warning "__DCACHE_PRESENT not defined in device header file; using default!" #endif #ifndef __DTCM_PRESENT #define __DTCM_PRESENT 0 #warning "__DTCM_PRESENT not defined in device header file; using default!" #endif #ifndef __NVIC_PRIO_BITS #define __NVIC_PRIO_BITS 3 #warning "__NVIC_PRIO_BITS not defined in device header file; using default!" #endif #ifndef __Vendor_SysTickConfig #define __Vendor_SysTickConfig 0 #warning "__Vendor_SysTickConfig not defined in device header file; using default!" #endif #endif /* IO definitions (access restrictions to peripheral registers) */ /** \defgroup CMSIS_glob_defs CMSIS Global Defines IO Type Qualifiers are used \li to specify the access to peripheral variables. \li for automatic generation of peripheral register debug information. */ #ifdef __cplusplus #define __I volatile /*!< Defines 'read only' permissions */ #else #define __I volatile const /*!< Defines 'read only' permissions */ #endif #define __O volatile /*!< Defines 'write only' permissions */ #define __IO volatile /*!< Defines 'read / write' permissions */ /*@} end of group Cortex_M7 */ /******************************************************************************* * Register Abstraction Core Register contain: - Core Register - Core NVIC Register - Core SCB Register - Core SysTick Register - Core Debug Register - Core MPU Register - Core FPU Register ******************************************************************************/ /** \defgroup CMSIS_core_register Defines and Type Definitions \brief Type definitions and defines for Cortex-M processor based devices. */ /** \ingroup CMSIS_core_register \defgroup CMSIS_CORE Status and Control Registers \brief Core Register type definitions. @{ */ /** \brief Union type to access the Application Program Status Register (APSR). */ typedef union { struct { uint32_t _reserved0:16; /*!< bit: 0..15 Reserved */ uint32_t GE:4; /*!< bit: 16..19 Greater than or Equal flags */ uint32_t _reserved1:7; /*!< bit: 20..26 Reserved */ uint32_t Q:1; /*!< bit: 27 Saturation condition flag */ uint32_t V:1; /*!< bit: 28 Overflow condition code flag */ uint32_t C:1; /*!< bit: 29 Carry condition code flag */ uint32_t Z:1; /*!< bit: 30 Zero condition code flag */ uint32_t N:1; /*!< bit: 31 Negative condition code flag */ } b; /*!< Structure used for bit access */ uint32_t w; /*!< Type used for word access */ } APSR_Type; /* APSR Register Definitions */ #define APSR_N_Pos 31 /*!< APSR: N Position */ #define APSR_N_Msk (1UL << APSR_N_Pos) /*!< APSR: N Mask */ #define APSR_Z_Pos 30 /*!< APSR: Z Position */ #define APSR_Z_Msk (1UL << APSR_Z_Pos) /*!< APSR: Z Mask */ #define APSR_C_Pos 29 /*!< APSR: C Position */ #define APSR_C_Msk (1UL << APSR_C_Pos) /*!< APSR: C Mask */ #define APSR_V_Pos 28 /*!< APSR: V Position */ #define APSR_V_Msk (1UL << APSR_V_Pos) /*!< APSR: V Mask */ #define APSR_Q_Pos 27 /*!< APSR: Q Position */ #define APSR_Q_Msk (1UL << APSR_Q_Pos) /*!< APSR: Q Mask */ #define APSR_GE_Pos 16 /*!< APSR: GE Position */ #define APSR_GE_Msk (0xFUL << APSR_GE_Pos) /*!< APSR: GE Mask */ /** \brief Union type to access the Interrupt Program Status Register (IPSR). */ typedef union { struct { uint32_t ISR:9; /*!< bit: 0.. 8 Exception number */ uint32_t _reserved0:23; /*!< bit: 9..31 Reserved */ } b; /*!< Structure used for bit access */ uint32_t w; /*!< Type used for word access */ } IPSR_Type; /* IPSR Register Definitions */ #define IPSR_ISR_Pos 0 /*!< IPSR: ISR Position */ #define IPSR_ISR_Msk (0x1FFUL /*<< IPSR_ISR_Pos*/) /*!< IPSR: ISR Mask */ /** \brief Union type to access the Special-Purpose Program Status Registers (xPSR). */ typedef union { struct { uint32_t ISR:9; /*!< bit: 0.. 8 Exception number */ uint32_t _reserved0:7; /*!< bit: 9..15 Reserved */ uint32_t GE:4; /*!< bit: 16..19 Greater than or Equal flags */ uint32_t _reserved1:4; /*!< bit: 20..23 Reserved */ uint32_t T:1; /*!< bit: 24 Thumb bit (read 0) */ uint32_t IT:2; /*!< bit: 25..26 saved IT state (read 0) */ uint32_t Q:1; /*!< bit: 27 Saturation condition flag */ uint32_t V:1; /*!< bit: 28 Overflow condition code flag */ uint32_t C:1; /*!< bit: 29 Carry condition code flag */ uint32_t Z:1; /*!< bit: 30 Zero condition code flag */ uint32_t N:1; /*!< bit: 31 Negative condition code flag */ } b; /*!< Structure used for bit access */ uint32_t w; /*!< Type used for word access */ } xPSR_Type; /* xPSR Register Definitions */ #define xPSR_N_Pos 31 /*!< xPSR: N Position */ #define xPSR_N_Msk (1UL << xPSR_N_Pos) /*!< xPSR: N Mask */ #define xPSR_Z_Pos 30 /*!< xPSR: Z Position */ #define xPSR_Z_Msk (1UL << xPSR_Z_Pos) /*!< xPSR: Z Mask */ #define xPSR_C_Pos 29 /*!< xPSR: C Position */ #define xPSR_C_Msk (1UL << xPSR_C_Pos) /*!< xPSR: C Mask */ #define xPSR_V_Pos 28 /*!< xPSR: V Position */ #define xPSR_V_Msk (1UL << xPSR_V_Pos) /*!< xPSR: V Mask */ #define xPSR_Q_Pos 27 /*!< xPSR: Q Position */ #define xPSR_Q_Msk (1UL << xPSR_Q_Pos) /*!< xPSR: Q Mask */ #define xPSR_IT_Pos 25 /*!< xPSR: IT Position */ #define xPSR_IT_Msk (3UL << xPSR_IT_Pos) /*!< xPSR: IT Mask */ #define xPSR_T_Pos 24 /*!< xPSR: T Position */ #define xPSR_T_Msk (1UL << xPSR_T_Pos) /*!< xPSR: T Mask */ #define xPSR_GE_Pos 16 /*!< xPSR: GE Position */ #define xPSR_GE_Msk (0xFUL << xPSR_GE_Pos) /*!< xPSR: GE Mask */ #define xPSR_ISR_Pos 0 /*!< xPSR: ISR Position */ #define xPSR_ISR_Msk (0x1FFUL /*<< xPSR_ISR_Pos*/) /*!< xPSR: ISR Mask */ /** \brief Union type to access the Control Registers (CONTROL). */ typedef union { struct { uint32_t nPRIV:1; /*!< bit: 0 Execution privilege in Thread mode */ uint32_t SPSEL:1; /*!< bit: 1 Stack to be used */ uint32_t FPCA:1; /*!< bit: 2 FP extension active flag */ uint32_t _reserved0:29; /*!< bit: 3..31 Reserved */ } b; /*!< Structure used for bit access */ uint32_t w; /*!< Type used for word access */ } CONTROL_Type; /* CONTROL Register Definitions */ #define CONTROL_FPCA_Pos 2 /*!< CONTROL: FPCA Position */ #define CONTROL_FPCA_Msk (1UL << CONTROL_FPCA_Pos) /*!< CONTROL: FPCA Mask */ #define CONTROL_SPSEL_Pos 1 /*!< CONTROL: SPSEL Position */ #define CONTROL_SPSEL_Msk (1UL << CONTROL_SPSEL_Pos) /*!< CONTROL: SPSEL Mask */ #define CONTROL_nPRIV_Pos 0 /*!< CONTROL: nPRIV Position */ #define CONTROL_nPRIV_Msk (1UL /*<< CONTROL_nPRIV_Pos*/) /*!< CONTROL: nPRIV Mask */ /*@} end of group CMSIS_CORE */ /** \ingroup CMSIS_core_register \defgroup CMSIS_NVIC Nested Vectored Interrupt Controller (NVIC) \brief Type definitions for the NVIC Registers @{ */ /** \brief Structure type to access the Nested Vectored Interrupt Controller (NVIC). */ typedef struct { __IO uint32_t ISER[8]; /*!< Offset: 0x000 (R/W) Interrupt Set Enable Register */ uint32_t RESERVED0[24]; __IO uint32_t ICER[8]; /*!< Offset: 0x080 (R/W) Interrupt Clear Enable Register */ uint32_t RSERVED1[24]; __IO uint32_t ISPR[8]; /*!< Offset: 0x100 (R/W) Interrupt Set Pending Register */ uint32_t RESERVED2[24]; __IO uint32_t ICPR[8]; /*!< Offset: 0x180 (R/W) Interrupt Clear Pending Register */ uint32_t RESERVED3[24]; __IO uint32_t IABR[8]; /*!< Offset: 0x200 (R/W) Interrupt Active bit Register */ uint32_t RESERVED4[56]; __IO uint8_t IP[240]; /*!< Offset: 0x300 (R/W) Interrupt Priority Register (8Bit wide) */ uint32_t RESERVED5[644]; __O uint32_t STIR; /*!< Offset: 0xE00 ( /W) Software Trigger Interrupt Register */ } NVIC_Type; /* Software Triggered Interrupt Register Definitions */ #define NVIC_STIR_INTID_Pos 0 /*!< STIR: INTLINESNUM Position */ #define NVIC_STIR_INTID_Msk (0x1FFUL /*<< NVIC_STIR_INTID_Pos*/) /*!< STIR: INTLINESNUM Mask */ /*@} end of group CMSIS_NVIC */ /** \ingroup CMSIS_core_register \defgroup CMSIS_SCB System Control Block (SCB) \brief Type definitions for the System Control Block Registers @{ */ /** \brief Structure type to access the System Control Block (SCB). */ typedef struct { __I uint32_t CPUID; /*!< Offset: 0x000 (R/ ) CPUID Base Register */ __IO uint32_t ICSR; /*!< Offset: 0x004 (R/W) Interrupt Control and State Register */ __IO uint32_t VTOR; /*!< Offset: 0x008 (R/W) Vector Table Offset Register */ __IO uint32_t AIRCR; /*!< Offset: 0x00C (R/W) Application Interrupt and Reset Control Register */ __IO uint32_t SCR; /*!< Offset: 0x010 (R/W) System Control Register */ __IO uint32_t CCR; /*!< Offset: 0x014 (R/W) Configuration Control Register */ __IO uint8_t SHPR[12]; /*!< Offset: 0x018 (R/W) System Handlers Priority Registers (4-7, 8-11, 12-15) */ __IO uint32_t SHCSR; /*!< Offset: 0x024 (R/W) System Handler Control and State Register */ __IO uint32_t CFSR; /*!< Offset: 0x028 (R/W) Configurable Fault Status Register */ __IO uint32_t HFSR; /*!< Offset: 0x02C (R/W) HardFault Status Register */ __IO uint32_t DFSR; /*!< Offset: 0x030 (R/W) Debug Fault Status Register */ __IO uint32_t MMFAR; /*!< Offset: 0x034 (R/W) MemManage Fault Address Register */ __IO uint32_t BFAR; /*!< Offset: 0x038 (R/W) BusFault Address Register */ __IO uint32_t AFSR; /*!< Offset: 0x03C (R/W) Auxiliary Fault Status Register */ __I uint32_t ID_PFR[2]; /*!< Offset: 0x040 (R/ ) Processor Feature Register */ __I uint32_t ID_DFR; /*!< Offset: 0x048 (R/ ) Debug Feature Register */ __I uint32_t ID_AFR; /*!< Offset: 0x04C (R/ ) Auxiliary Feature Register */ __I uint32_t ID_MFR[4]; /*!< Offset: 0x050 (R/ ) Memory Model Feature Register */ __I uint32_t ID_ISAR[5]; /*!< Offset: 0x060 (R/ ) Instruction Set Attributes Register */ uint32_t RESERVED0[1]; __I uint32_t CLIDR; /*!< Offset: 0x078 (R/ ) Cache Level ID register */ __I uint32_t CTR; /*!< Offset: 0x07C (R/ ) Cache Type register */ __I uint32_t CCSIDR; /*!< Offset: 0x080 (R/ ) Cache Size ID Register */ __IO uint32_t CSSELR; /*!< Offset: 0x084 (R/W) Cache Size Selection Register */ __IO uint32_t CPACR; /*!< Offset: 0x088 (R/W) Coprocessor Access Control Register */ uint32_t RESERVED3[93]; __O uint32_t STIR; /*!< Offset: 0x200 ( /W) Software Triggered Interrupt Register */ uint32_t RESERVED4[15]; __I uint32_t MVFR0; /*!< Offset: 0x240 (R/ ) Media and VFP Feature Register 0 */ __I uint32_t MVFR1; /*!< Offset: 0x244 (R/ ) Media and VFP Feature Register 1 */ __I uint32_t MVFR2; /*!< Offset: 0x248 (R/ ) Media and VFP Feature Register 1 */ uint32_t RESERVED5[1]; __O uint32_t ICIALLU; /*!< Offset: 0x250 ( /W) I-Cache Invalidate All to PoU */ uint32_t RESERVED6[1]; __O uint32_t ICIMVAU; /*!< Offset: 0x258 ( /W) I-Cache Invalidate by MVA to PoU */ __O uint32_t DCIMVAC; /*!< Offset: 0x25C ( /W) D-Cache Invalidate by MVA to PoC */ __O uint32_t DCISW; /*!< Offset: 0x260 ( /W) D-Cache Invalidate by Set-way */ __O uint32_t DCCMVAU; /*!< Offset: 0x264 ( /W) D-Cache Clean by MVA to PoU */ __O uint32_t DCCMVAC; /*!< Offset: 0x268 ( /W) D-Cache Clean by MVA to PoC */ __O uint32_t DCCSW; /*!< Offset: 0x26C ( /W) D-Cache Clean by Set-way */ __O uint32_t DCCIMVAC; /*!< Offset: 0x270 ( /W) D-Cache Clean and Invalidate by MVA to PoC */ __O uint32_t DCCISW; /*!< Offset: 0x274 ( /W) D-Cache Clean and Invalidate by Set-way */ uint32_t RESERVED7[6]; __IO uint32_t ITCMCR; /*!< Offset: 0x290 (R/W) Instruction Tightly-Coupled Memory Control Register */ __IO uint32_t DTCMCR; /*!< Offset: 0x294 (R/W) Data Tightly-Coupled Memory Control Registers */ __IO uint32_t AHBPCR; /*!< Offset: 0x298 (R/W) AHBP Control Register */ __IO uint32_t CACR; /*!< Offset: 0x29C (R/W) L1 Cache Control Register */ __IO uint32_t AHBSCR; /*!< Offset: 0x2A0 (R/W) AHB Slave Control Register */ uint32_t RESERVED8[1]; __IO uint32_t ABFSR; /*!< Offset: 0x2A8 (R/W) Auxiliary Bus Fault Status Register */ } SCB_Type; /* SCB CPUID Register Definitions */ #define SCB_CPUID_IMPLEMENTER_Pos 24 /*!< SCB CPUID: IMPLEMENTER Position */ #define SCB_CPUID_IMPLEMENTER_Msk (0xFFUL << SCB_CPUID_IMPLEMENTER_Pos) /*!< SCB CPUID: IMPLEMENTER Mask */ #define SCB_CPUID_VARIANT_Pos 20 /*!< SCB CPUID: VARIANT Position */ #define SCB_CPUID_VARIANT_Msk (0xFUL << SCB_CPUID_VARIANT_Pos) /*!< SCB CPUID: VARIANT Mask */ #define SCB_CPUID_ARCHITECTURE_Pos 16 /*!< SCB CPUID: ARCHITECTURE Position */ #define SCB_CPUID_ARCHITECTURE_Msk (0xFUL << SCB_CPUID_ARCHITECTURE_Pos) /*!< SCB CPUID: ARCHITECTURE Mask */ #define SCB_CPUID_PARTNO_Pos 4 /*!< SCB CPUID: PARTNO Position */ #define SCB_CPUID_PARTNO_Msk (0xFFFUL << SCB_CPUID_PARTNO_Pos) /*!< SCB CPUID: PARTNO Mask */ #define SCB_CPUID_REVISION_Pos 0 /*!< SCB CPUID: REVISION Position */ #define SCB_CPUID_REVISION_Msk (0xFUL /*<< SCB_CPUID_REVISION_Pos*/) /*!< SCB CPUID: REVISION Mask */ /* SCB Interrupt Control State Register Definitions */ #define SCB_ICSR_NMIPENDSET_Pos 31 /*!< SCB ICSR: NMIPENDSET Position */ #define SCB_ICSR_NMIPENDSET_Msk (1UL << SCB_ICSR_NMIPENDSET_Pos) /*!< SCB ICSR: NMIPENDSET Mask */ #define SCB_ICSR_PENDSVSET_Pos 28 /*!< SCB ICSR: PENDSVSET Position */ #define SCB_ICSR_PENDSVSET_Msk (1UL << SCB_ICSR_PENDSVSET_Pos) /*!< SCB ICSR: PENDSVSET Mask */ #define SCB_ICSR_PENDSVCLR_Pos 27 /*!< SCB ICSR: PENDSVCLR Position */ #define SCB_ICSR_PENDSVCLR_Msk (1UL << SCB_ICSR_PENDSVCLR_Pos) /*!< SCB ICSR: PENDSVCLR Mask */ #define SCB_ICSR_PENDSTSET_Pos 26 /*!< SCB ICSR: PENDSTSET Position */ #define SCB_ICSR_PENDSTSET_Msk (1UL << SCB_ICSR_PENDSTSET_Pos) /*!< SCB ICSR: PENDSTSET Mask */ #define SCB_ICSR_PENDSTCLR_Pos 25 /*!< SCB ICSR: PENDSTCLR Position */ #define SCB_ICSR_PENDSTCLR_Msk (1UL << SCB_ICSR_PENDSTCLR_Pos) /*!< SCB ICSR: PENDSTCLR Mask */ #define SCB_ICSR_ISRPREEMPT_Pos 23 /*!< SCB ICSR: ISRPREEMPT Position */ #define SCB_ICSR_ISRPREEMPT_Msk (1UL << SCB_ICSR_ISRPREEMPT_Pos) /*!< SCB ICSR: ISRPREEMPT Mask */ #define SCB_ICSR_ISRPENDING_Pos 22 /*!< SCB ICSR: ISRPENDING Position */ #define SCB_ICSR_ISRPENDING_Msk (1UL << SCB_ICSR_ISRPENDING_Pos) /*!< SCB ICSR: ISRPENDING Mask */ #define SCB_ICSR_VECTPENDING_Pos 12 /*!< SCB ICSR: VECTPENDING Position */ #define SCB_ICSR_VECTPENDING_Msk (0x1FFUL << SCB_ICSR_VECTPENDING_Pos) /*!< SCB ICSR: VECTPENDING Mask */ #define SCB_ICSR_RETTOBASE_Pos 11 /*!< SCB ICSR: RETTOBASE Position */ #define SCB_ICSR_RETTOBASE_Msk (1UL << SCB_ICSR_RETTOBASE_Pos) /*!< SCB ICSR: RETTOBASE Mask */ #define SCB_ICSR_VECTACTIVE_Pos 0 /*!< SCB ICSR: VECTACTIVE Position */ #define SCB_ICSR_VECTACTIVE_Msk (0x1FFUL /*<< SCB_ICSR_VECTACTIVE_Pos*/) /*!< SCB ICSR: VECTACTIVE Mask */ /* SCB Vector Table Offset Register Definitions */ #define SCB_VTOR_TBLOFF_Pos 7 /*!< SCB VTOR: TBLOFF Position */ #define SCB_VTOR_TBLOFF_Msk (0x1FFFFFFUL << SCB_VTOR_TBLOFF_Pos) /*!< SCB VTOR: TBLOFF Mask */ /* SCB Application Interrupt and Reset Control Register Definitions */ #define SCB_AIRCR_VECTKEY_Pos 16 /*!< SCB AIRCR: VECTKEY Position */ #define SCB_AIRCR_VECTKEY_Msk (0xFFFFUL << SCB_AIRCR_VECTKEY_Pos) /*!< SCB AIRCR: VECTKEY Mask */ #define SCB_AIRCR_VECTKEYSTAT_Pos 16 /*!< SCB AIRCR: VECTKEYSTAT Position */ #define SCB_AIRCR_VECTKEYSTAT_Msk (0xFFFFUL << SCB_AIRCR_VECTKEYSTAT_Pos) /*!< SCB AIRCR: VECTKEYSTAT Mask */ #define SCB_AIRCR_ENDIANESS_Pos 15 /*!< SCB AIRCR: ENDIANESS Position */ #define SCB_AIRCR_ENDIANESS_Msk (1UL << SCB_AIRCR_ENDIANESS_Pos) /*!< SCB AIRCR: ENDIANESS Mask */ #define SCB_AIRCR_PRIGROUP_Pos 8 /*!< SCB AIRCR: PRIGROUP Position */ #define SCB_AIRCR_PRIGROUP_Msk (7UL << SCB_AIRCR_PRIGROUP_Pos) /*!< SCB AIRCR: PRIGROUP Mask */ #define SCB_AIRCR_SYSRESETREQ_Pos 2 /*!< SCB AIRCR: SYSRESETREQ Position */ #define SCB_AIRCR_SYSRESETREQ_Msk (1UL << SCB_AIRCR_SYSRESETREQ_Pos) /*!< SCB AIRCR: SYSRESETREQ Mask */ #define SCB_AIRCR_VECTCLRACTIVE_Pos 1 /*!< SCB AIRCR: VECTCLRACTIVE Position */ #define SCB_AIRCR_VECTCLRACTIVE_Msk (1UL << SCB_AIRCR_VECTCLRACTIVE_Pos) /*!< SCB AIRCR: VECTCLRACTIVE Mask */ #define SCB_AIRCR_VECTRESET_Pos 0 /*!< SCB AIRCR: VECTRESET Position */ #define SCB_AIRCR_VECTRESET_Msk (1UL /*<< SCB_AIRCR_VECTRESET_Pos*/) /*!< SCB AIRCR: VECTRESET Mask */ /* SCB System Control Register Definitions */ #define SCB_SCR_SEVONPEND_Pos 4 /*!< SCB SCR: SEVONPEND Position */ #define SCB_SCR_SEVONPEND_Msk (1UL << SCB_SCR_SEVONPEND_Pos) /*!< SCB SCR: SEVONPEND Mask */ #define SCB_SCR_SLEEPDEEP_Pos 2 /*!< SCB SCR: SLEEPDEEP Position */ #define SCB_SCR_SLEEPDEEP_Msk (1UL << SCB_SCR_SLEEPDEEP_Pos) /*!< SCB SCR: SLEEPDEEP Mask */ #define SCB_SCR_SLEEPONEXIT_Pos 1 /*!< SCB SCR: SLEEPONEXIT Position */ #define SCB_SCR_SLEEPONEXIT_Msk (1UL << SCB_SCR_SLEEPONEXIT_Pos) /*!< SCB SCR: SLEEPONEXIT Mask */ /* SCB Configuration Control Register Definitions */ #define SCB_CCR_BP_Pos 18 /*!< SCB CCR: Branch prediction enable bit Position */ #define SCB_CCR_BP_Msk (1UL << SCB_CCR_BP_Pos) /*!< SCB CCR: Branch prediction enable bit Mask */ #define SCB_CCR_IC_Pos 17 /*!< SCB CCR: Instruction cache enable bit Position */ #define SCB_CCR_IC_Msk (1UL << SCB_CCR_IC_Pos) /*!< SCB CCR: Instruction cache enable bit Mask */ #define SCB_CCR_DC_Pos 16 /*!< SCB CCR: Cache enable bit Position */ #define SCB_CCR_DC_Msk (1UL << SCB_CCR_DC_Pos) /*!< SCB CCR: Cache enable bit Mask */ #define SCB_CCR_STKALIGN_Pos 9 /*!< SCB CCR: STKALIGN Position */ #define SCB_CCR_STKALIGN_Msk (1UL << SCB_CCR_STKALIGN_Pos) /*!< SCB CCR: STKALIGN Mask */ #define SCB_CCR_BFHFNMIGN_Pos 8 /*!< SCB CCR: BFHFNMIGN Position */ #define SCB_CCR_BFHFNMIGN_Msk (1UL << SCB_CCR_BFHFNMIGN_Pos) /*!< SCB CCR: BFHFNMIGN Mask */ #define SCB_CCR_DIV_0_TRP_Pos 4 /*!< SCB CCR: DIV_0_TRP Position */ #define SCB_CCR_DIV_0_TRP_Msk (1UL << SCB_CCR_DIV_0_TRP_Pos) /*!< SCB CCR: DIV_0_TRP Mask */ #define SCB_CCR_UNALIGN_TRP_Pos 3 /*!< SCB CCR: UNALIGN_TRP Position */ #define SCB_CCR_UNALIGN_TRP_Msk (1UL << SCB_CCR_UNALIGN_TRP_Pos) /*!< SCB CCR: UNALIGN_TRP Mask */ #define SCB_CCR_USERSETMPEND_Pos 1 /*!< SCB CCR: USERSETMPEND Position */ #define SCB_CCR_USERSETMPEND_Msk (1UL << SCB_CCR_USERSETMPEND_Pos) /*!< SCB CCR: USERSETMPEND Mask */ #define SCB_CCR_NONBASETHRDENA_Pos 0 /*!< SCB CCR: NONBASETHRDENA Position */ #define SCB_CCR_NONBASETHRDENA_Msk (1UL /*<< SCB_CCR_NONBASETHRDENA_Pos*/) /*!< SCB CCR: NONBASETHRDENA Mask */ /* SCB System Handler Control and State Register Definitions */ #define SCB_SHCSR_USGFAULTENA_Pos 18 /*!< SCB SHCSR: USGFAULTENA Position */ #define SCB_SHCSR_USGFAULTENA_Msk (1UL << SCB_SHCSR_USGFAULTENA_Pos) /*!< SCB SHCSR: USGFAULTENA Mask */ #define SCB_SHCSR_BUSFAULTENA_Pos 17 /*!< SCB SHCSR: BUSFAULTENA Position */ #define SCB_SHCSR_BUSFAULTENA_Msk (1UL << SCB_SHCSR_BUSFAULTENA_Pos) /*!< SCB SHCSR: BUSFAULTENA Mask */ #define SCB_SHCSR_MEMFAULTENA_Pos 16 /*!< SCB SHCSR: MEMFAULTENA Position */ #define SCB_SHCSR_MEMFAULTENA_Msk (1UL << SCB_SHCSR_MEMFAULTENA_Pos) /*!< SCB SHCSR: MEMFAULTENA Mask */ #define SCB_SHCSR_SVCALLPENDED_Pos 15 /*!< SCB SHCSR: SVCALLPENDED Position */ #define SCB_SHCSR_SVCALLPENDED_Msk (1UL << SCB_SHCSR_SVCALLPENDED_Pos) /*!< SCB SHCSR: SVCALLPENDED Mask */ #define SCB_SHCSR_BUSFAULTPENDED_Pos 14 /*!< SCB SHCSR: BUSFAULTPENDED Position */ #define SCB_SHCSR_BUSFAULTPENDED_Msk (1UL << SCB_SHCSR_BUSFAULTPENDED_Pos) /*!< SCB SHCSR: BUSFAULTPENDED Mask */ #define SCB_SHCSR_MEMFAULTPENDED_Pos 13 /*!< SCB SHCSR: MEMFAULTPENDED Position */ #define SCB_SHCSR_MEMFAULTPENDED_Msk (1UL << SCB_SHCSR_MEMFAULTPENDED_Pos) /*!< SCB SHCSR: MEMFAULTPENDED Mask */ #define SCB_SHCSR_USGFAULTPENDED_Pos 12 /*!< SCB SHCSR: USGFAULTPENDED Position */ #define SCB_SHCSR_USGFAULTPENDED_Msk (1UL << SCB_SHCSR_USGFAULTPENDED_Pos) /*!< SCB SHCSR: USGFAULTPENDED Mask */ #define SCB_SHCSR_SYSTICKACT_Pos 11 /*!< SCB SHCSR: SYSTICKACT Position */ #define SCB_SHCSR_SYSTICKACT_Msk (1UL << SCB_SHCSR_SYSTICKACT_Pos) /*!< SCB SHCSR: SYSTICKACT Mask */ #define SCB_SHCSR_PENDSVACT_Pos 10 /*!< SCB SHCSR: PENDSVACT Position */ #define SCB_SHCSR_PENDSVACT_Msk (1UL << SCB_SHCSR_PENDSVACT_Pos) /*!< SCB SHCSR: PENDSVACT Mask */ #define SCB_SHCSR_MONITORACT_Pos 8 /*!< SCB SHCSR: MONITORACT Position */ #define SCB_SHCSR_MONITORACT_Msk (1UL << SCB_SHCSR_MONITORACT_Pos) /*!< SCB SHCSR: MONITORACT Mask */ #define SCB_SHCSR_SVCALLACT_Pos 7 /*!< SCB SHCSR: SVCALLACT Position */ #define SCB_SHCSR_SVCALLACT_Msk (1UL << SCB_SHCSR_SVCALLACT_Pos) /*!< SCB SHCSR: SVCALLACT Mask */ #define SCB_SHCSR_USGFAULTACT_Pos 3 /*!< SCB SHCSR: USGFAULTACT Position */ #define SCB_SHCSR_USGFAULTACT_Msk (1UL << SCB_SHCSR_USGFAULTACT_Pos) /*!< SCB SHCSR: USGFAULTACT Mask */ #define SCB_SHCSR_BUSFAULTACT_Pos 1 /*!< SCB SHCSR: BUSFAULTACT Position */ #define SCB_SHCSR_BUSFAULTACT_Msk (1UL << SCB_SHCSR_BUSFAULTACT_Pos) /*!< SCB SHCSR: BUSFAULTACT Mask */ #define SCB_SHCSR_MEMFAULTACT_Pos 0 /*!< SCB SHCSR: MEMFAULTACT Position */ #define SCB_SHCSR_MEMFAULTACT_Msk (1UL /*<< SCB_SHCSR_MEMFAULTACT_Pos*/) /*!< SCB SHCSR: MEMFAULTACT Mask */ /* SCB Configurable Fault Status Registers Definitions */ #define SCB_CFSR_USGFAULTSR_Pos 16 /*!< SCB CFSR: Usage Fault Status Register Position */ #define SCB_CFSR_USGFAULTSR_Msk (0xFFFFUL << SCB_CFSR_USGFAULTSR_Pos) /*!< SCB CFSR: Usage Fault Status Register Mask */ #define SCB_CFSR_BUSFAULTSR_Pos 8 /*!< SCB CFSR: Bus Fault Status Register Position */ #define SCB_CFSR_BUSFAULTSR_Msk (0xFFUL << SCB_CFSR_BUSFAULTSR_Pos) /*!< SCB CFSR: Bus Fault Status Register Mask */ #define SCB_CFSR_MEMFAULTSR_Pos 0 /*!< SCB CFSR: Memory Manage Fault Status Register Position */ #define SCB_CFSR_MEMFAULTSR_Msk (0xFFUL /*<< SCB_CFSR_MEMFAULTSR_Pos*/) /*!< SCB CFSR: Memory Manage Fault Status Register Mask */ /* SCB Hard Fault Status Registers Definitions */ #define SCB_HFSR_DEBUGEVT_Pos 31 /*!< SCB HFSR: DEBUGEVT Position */ #define SCB_HFSR_DEBUGEVT_Msk (1UL << SCB_HFSR_DEBUGEVT_Pos) /*!< SCB HFSR: DEBUGEVT Mask */ #define SCB_HFSR_FORCED_Pos 30 /*!< SCB HFSR: FORCED Position */ #define SCB_HFSR_FORCED_Msk (1UL << SCB_HFSR_FORCED_Pos) /*!< SCB HFSR: FORCED Mask */ #define SCB_HFSR_VECTTBL_Pos 1 /*!< SCB HFSR: VECTTBL Position */ #define SCB_HFSR_VECTTBL_Msk (1UL << SCB_HFSR_VECTTBL_Pos) /*!< SCB HFSR: VECTTBL Mask */ /* SCB Debug Fault Status Register Definitions */ #define SCB_DFSR_EXTERNAL_Pos 4 /*!< SCB DFSR: EXTERNAL Position */ #define SCB_DFSR_EXTERNAL_Msk (1UL << SCB_DFSR_EXTERNAL_Pos) /*!< SCB DFSR: EXTERNAL Mask */ #define SCB_DFSR_VCATCH_Pos 3 /*!< SCB DFSR: VCATCH Position */ #define SCB_DFSR_VCATCH_Msk (1UL << SCB_DFSR_VCATCH_Pos) /*!< SCB DFSR: VCATCH Mask */ #define SCB_DFSR_DWTTRAP_Pos 2 /*!< SCB DFSR: DWTTRAP Position */ #define SCB_DFSR_DWTTRAP_Msk (1UL << SCB_DFSR_DWTTRAP_Pos) /*!< SCB DFSR: DWTTRAP Mask */ #define SCB_DFSR_BKPT_Pos 1 /*!< SCB DFSR: BKPT Position */ #define SCB_DFSR_BKPT_Msk (1UL << SCB_DFSR_BKPT_Pos) /*!< SCB DFSR: BKPT Mask */ #define SCB_DFSR_HALTED_Pos 0 /*!< SCB DFSR: HALTED Position */ #define SCB_DFSR_HALTED_Msk (1UL /*<< SCB_DFSR_HALTED_Pos*/) /*!< SCB DFSR: HALTED Mask */ /* Cache Level ID register */ #define SCB_CLIDR_LOUU_Pos 27 /*!< SCB CLIDR: LoUU Position */ #define SCB_CLIDR_LOUU_Msk (7UL << SCB_CLIDR_LOUU_Pos) /*!< SCB CLIDR: LoUU Mask */ #define SCB_CLIDR_LOC_Pos 24 /*!< SCB CLIDR: LoC Position */ #define SCB_CLIDR_LOC_Msk (7UL << SCB_CLIDR_FORMAT_Pos) /*!< SCB CLIDR: LoC Mask */ /* Cache Type register */ #define SCB_CTR_FORMAT_Pos 29 /*!< SCB CTR: Format Position */ #define SCB_CTR_FORMAT_Msk (7UL << SCB_CTR_FORMAT_Pos) /*!< SCB CTR: Format Mask */ #define SCB_CTR_CWG_Pos 24 /*!< SCB CTR: CWG Position */ #define SCB_CTR_CWG_Msk (0xFUL << SCB_CTR_CWG_Pos) /*!< SCB CTR: CWG Mask */ #define SCB_CTR_ERG_Pos 20 /*!< SCB CTR: ERG Position */ #define SCB_CTR_ERG_Msk (0xFUL << SCB_CTR_ERG_Pos) /*!< SCB CTR: ERG Mask */ #define SCB_CTR_DMINLINE_Pos 16 /*!< SCB CTR: DminLine Position */ #define SCB_CTR_DMINLINE_Msk (0xFUL << SCB_CTR_DMINLINE_Pos) /*!< SCB CTR: DminLine Mask */ #define SCB_CTR_IMINLINE_Pos 0 /*!< SCB CTR: ImInLine Position */ #define SCB_CTR_IMINLINE_Msk (0xFUL /*<< SCB_CTR_IMINLINE_Pos*/) /*!< SCB CTR: ImInLine Mask */ /* Cache Size ID Register */ #define SCB_CCSIDR_WT_Pos 31 /*!< SCB CCSIDR: WT Position */ #define SCB_CCSIDR_WT_Msk (7UL << SCB_CCSIDR_WT_Pos) /*!< SCB CCSIDR: WT Mask */ #define SCB_CCSIDR_WB_Pos 30 /*!< SCB CCSIDR: WB Position */ #define SCB_CCSIDR_WB_Msk (7UL << SCB_CCSIDR_WB_Pos) /*!< SCB CCSIDR: WB Mask */ #define SCB_CCSIDR_RA_Pos 29 /*!< SCB CCSIDR: RA Position */ #define SCB_CCSIDR_RA_Msk (7UL << SCB_CCSIDR_RA_Pos) /*!< SCB CCSIDR: RA Mask */ #define SCB_CCSIDR_WA_Pos 28 /*!< SCB CCSIDR: WA Position */ #define SCB_CCSIDR_WA_Msk (7UL << SCB_CCSIDR_WA_Pos) /*!< SCB CCSIDR: WA Mask */ #define SCB_CCSIDR_NUMSETS_Pos 13 /*!< SCB CCSIDR: NumSets Position */ #define SCB_CCSIDR_NUMSETS_Msk (0x7FFFUL << SCB_CCSIDR_NUMSETS_Pos) /*!< SCB CCSIDR: NumSets Mask */ #define SCB_CCSIDR_ASSOCIATIVITY_Pos 3 /*!< SCB CCSIDR: Associativity Position */ #define SCB_CCSIDR_ASSOCIATIVITY_Msk (0x3FFUL << SCB_CCSIDR_ASSOCIATIVITY_Pos) /*!< SCB CCSIDR: Associativity Mask */ #define SCB_CCSIDR_LINESIZE_Pos 0 /*!< SCB CCSIDR: LineSize Position */ #define SCB_CCSIDR_LINESIZE_Msk (7UL /*<< SCB_CCSIDR_LINESIZE_Pos*/) /*!< SCB CCSIDR: LineSize Mask */ /* Cache Size Selection Register */ #define SCB_CSSELR_LEVEL_Pos 1 /*!< SCB CSSELR: Level Position */ #define SCB_CSSELR_LEVEL_Msk (7UL << SCB_CSSELR_LEVEL_Pos) /*!< SCB CSSELR: Level Mask */ #define SCB_CSSELR_IND_Pos 0 /*!< SCB CSSELR: InD Position */ #define SCB_CSSELR_IND_Msk (1UL /*<< SCB_CSSELR_IND_Pos*/) /*!< SCB CSSELR: InD Mask */ /* SCB Software Triggered Interrupt Register */ #define SCB_STIR_INTID_Pos 0 /*!< SCB STIR: INTID Position */ #define SCB_STIR_INTID_Msk (0x1FFUL /*<< SCB_STIR_INTID_Pos*/) /*!< SCB STIR: INTID Mask */ /* Instruction Tightly-Coupled Memory Control Register*/ #define SCB_ITCMCR_SZ_Pos 3 /*!< SCB ITCMCR: SZ Position */ #define SCB_ITCMCR_SZ_Msk (0xFUL << SCB_ITCMCR_SZ_Pos) /*!< SCB ITCMCR: SZ Mask */ #define SCB_ITCMCR_RETEN_Pos 2 /*!< SCB ITCMCR: RETEN Position */ #define SCB_ITCMCR_RETEN_Msk (1UL << SCB_ITCMCR_RETEN_Pos) /*!< SCB ITCMCR: RETEN Mask */ #define SCB_ITCMCR_RMW_Pos 1 /*!< SCB ITCMCR: RMW Position */ #define SCB_ITCMCR_RMW_Msk (1UL << SCB_ITCMCR_RMW_Pos) /*!< SCB ITCMCR: RMW Mask */ #define SCB_ITCMCR_EN_Pos 0 /*!< SCB ITCMCR: EN Position */ #define SCB_ITCMCR_EN_Msk (1UL /*<< SCB_ITCMCR_EN_Pos*/) /*!< SCB ITCMCR: EN Mask */ /* Data Tightly-Coupled Memory Control Registers */ #define SCB_DTCMCR_SZ_Pos 3 /*!< SCB DTCMCR: SZ Position */ #define SCB_DTCMCR_SZ_Msk (0xFUL << SCB_DTCMCR_SZ_Pos) /*!< SCB DTCMCR: SZ Mask */ #define SCB_DTCMCR_RETEN_Pos 2 /*!< SCB DTCMCR: RETEN Position */ #define SCB_DTCMCR_RETEN_Msk (1UL << SCB_DTCMCR_RETEN_Pos) /*!< SCB DTCMCR: RETEN Mask */ #define SCB_DTCMCR_RMW_Pos 1 /*!< SCB DTCMCR: RMW Position */ #define SCB_DTCMCR_RMW_Msk (1UL << SCB_DTCMCR_RMW_Pos) /*!< SCB DTCMCR: RMW Mask */ #define SCB_DTCMCR_EN_Pos 0 /*!< SCB DTCMCR: EN Position */ #define SCB_DTCMCR_EN_Msk (1UL /*<< SCB_DTCMCR_EN_Pos*/) /*!< SCB DTCMCR: EN Mask */ /* AHBP Control Register */ #define SCB_AHBPCR_SZ_Pos 1 /*!< SCB AHBPCR: SZ Position */ #define SCB_AHBPCR_SZ_Msk (7UL << SCB_AHBPCR_SZ_Pos) /*!< SCB AHBPCR: SZ Mask */ #define SCB_AHBPCR_EN_Pos 0 /*!< SCB AHBPCR: EN Position */ #define SCB_AHBPCR_EN_Msk (1UL /*<< SCB_AHBPCR_EN_Pos*/) /*!< SCB AHBPCR: EN Mask */ /* L1 Cache Control Register */ #define SCB_CACR_FORCEWT_Pos 2 /*!< SCB CACR: FORCEWT Position */ #define SCB_CACR_FORCEWT_Msk (1UL << SCB_CACR_FORCEWT_Pos) /*!< SCB CACR: FORCEWT Mask */ #define SCB_CACR_ECCEN_Pos 1 /*!< SCB CACR: ECCEN Position */ #define SCB_CACR_ECCEN_Msk (1UL << SCB_CACR_ECCEN_Pos) /*!< SCB CACR: ECCEN Mask */ #define SCB_CACR_SIWT_Pos 0 /*!< SCB CACR: SIWT Position */ #define SCB_CACR_SIWT_Msk (1UL /*<< SCB_CACR_SIWT_Pos*/) /*!< SCB CACR: SIWT Mask */ /* AHBS control register */ #define SCB_AHBSCR_INITCOUNT_Pos 11 /*!< SCB AHBSCR: INITCOUNT Position */ #define SCB_AHBSCR_INITCOUNT_Msk (0x1FUL << SCB_AHBPCR_INITCOUNT_Pos) /*!< SCB AHBSCR: INITCOUNT Mask */ #define SCB_AHBSCR_TPRI_Pos 2 /*!< SCB AHBSCR: TPRI Position */ #define SCB_AHBSCR_TPRI_Msk (0x1FFUL << SCB_AHBPCR_TPRI_Pos) /*!< SCB AHBSCR: TPRI Mask */ #define SCB_AHBSCR_CTL_Pos 0 /*!< SCB AHBSCR: CTL Position*/ #define SCB_AHBSCR_CTL_Msk (3UL /*<< SCB_AHBPCR_CTL_Pos*/) /*!< SCB AHBSCR: CTL Mask */ /* Auxiliary Bus Fault Status Register */ #define SCB_ABFSR_AXIMTYPE_Pos 8 /*!< SCB ABFSR: AXIMTYPE Position*/ #define SCB_ABFSR_AXIMTYPE_Msk (3UL << SCB_ABFSR_AXIMTYPE_Pos) /*!< SCB ABFSR: AXIMTYPE Mask */ #define SCB_ABFSR_EPPB_Pos 4 /*!< SCB ABFSR: EPPB Position*/ #define SCB_ABFSR_EPPB_Msk (1UL << SCB_ABFSR_EPPB_Pos) /*!< SCB ABFSR: EPPB Mask */ #define SCB_ABFSR_AXIM_Pos 3 /*!< SCB ABFSR: AXIM Position*/ #define SCB_ABFSR_AXIM_Msk (1UL << SCB_ABFSR_AXIM_Pos) /*!< SCB ABFSR: AXIM Mask */ #define SCB_ABFSR_AHBP_Pos 2 /*!< SCB ABFSR: AHBP Position*/ #define SCB_ABFSR_AHBP_Msk (1UL << SCB_ABFSR_AHBP_Pos) /*!< SCB ABFSR: AHBP Mask */ #define SCB_ABFSR_DTCM_Pos 1 /*!< SCB ABFSR: DTCM Position*/ #define SCB_ABFSR_DTCM_Msk (1UL << SCB_ABFSR_DTCM_Pos) /*!< SCB ABFSR: DTCM Mask */ #define SCB_ABFSR_ITCM_Pos 0 /*!< SCB ABFSR: ITCM Position*/ #define SCB_ABFSR_ITCM_Msk (1UL /*<< SCB_ABFSR_ITCM_Pos*/) /*!< SCB ABFSR: ITCM Mask */ /*@} end of group CMSIS_SCB */ /** \ingroup CMSIS_core_register \defgroup CMSIS_SCnSCB System Controls not in SCB (SCnSCB) \brief Type definitions for the System Control and ID Register not in the SCB @{ */ /** \brief Structure type to access the System Control and ID Register not in the SCB. */ typedef struct { uint32_t RESERVED0[1]; __I uint32_t ICTR; /*!< Offset: 0x004 (R/ ) Interrupt Controller Type Register */ __IO uint32_t ACTLR; /*!< Offset: 0x008 (R/W) Auxiliary Control Register */ } SCnSCB_Type; /* Interrupt Controller Type Register Definitions */ #define SCnSCB_ICTR_INTLINESNUM_Pos 0 /*!< ICTR: INTLINESNUM Position */ #define SCnSCB_ICTR_INTLINESNUM_Msk (0xFUL /*<< SCnSCB_ICTR_INTLINESNUM_Pos*/) /*!< ICTR: INTLINESNUM Mask */ /* Auxiliary Control Register Definitions */ #define SCnSCB_ACTLR_DISITMATBFLUSH_Pos 12 /*!< ACTLR: DISITMATBFLUSH Position */ #define SCnSCB_ACTLR_DISITMATBFLUSH_Msk (1UL << SCnSCB_ACTLR_DISITMATBFLUSH_Pos) /*!< ACTLR: DISITMATBFLUSH Mask */ #define SCnSCB_ACTLR_DISRAMODE_Pos 11 /*!< ACTLR: DISRAMODE Position */ #define SCnSCB_ACTLR_DISRAMODE_Msk (1UL << SCnSCB_ACTLR_DISRAMODE_Pos) /*!< ACTLR: DISRAMODE Mask */ #define SCnSCB_ACTLR_FPEXCODIS_Pos 10 /*!< ACTLR: FPEXCODIS Position */ #define SCnSCB_ACTLR_FPEXCODIS_Msk (1UL << SCnSCB_ACTLR_FPEXCODIS_Pos) /*!< ACTLR: FPEXCODIS Mask */ #define SCnSCB_ACTLR_DISFOLD_Pos 2 /*!< ACTLR: DISFOLD Position */ #define SCnSCB_ACTLR_DISFOLD_Msk (1UL << SCnSCB_ACTLR_DISFOLD_Pos) /*!< ACTLR: DISFOLD Mask */ #define SCnSCB_ACTLR_DISMCYCINT_Pos 0 /*!< ACTLR: DISMCYCINT Position */ #define SCnSCB_ACTLR_DISMCYCINT_Msk (1UL /*<< SCnSCB_ACTLR_DISMCYCINT_Pos*/) /*!< ACTLR: DISMCYCINT Mask */ /*@} end of group CMSIS_SCnotSCB */ /** \ingroup CMSIS_core_register \defgroup CMSIS_SysTick System Tick Timer (SysTick) \brief Type definitions for the System Timer Registers. @{ */ /** \brief Structure type to access the System Timer (SysTick). */ typedef struct { __IO uint32_t CTRL; /*!< Offset: 0x000 (R/W) SysTick Control and Status Register */ __IO uint32_t LOAD; /*!< Offset: 0x004 (R/W) SysTick Reload Value Register */ __IO uint32_t VAL; /*!< Offset: 0x008 (R/W) SysTick Current Value Register */ __I uint32_t CALIB; /*!< Offset: 0x00C (R/ ) SysTick Calibration Register */ } SysTick_Type; /* SysTick Control / Status Register Definitions */ #define SysTick_CTRL_COUNTFLAG_Pos 16 /*!< SysTick CTRL: COUNTFLAG Position */ #define SysTick_CTRL_COUNTFLAG_Msk (1UL << SysTick_CTRL_COUNTFLAG_Pos) /*!< SysTick CTRL: COUNTFLAG Mask */ #define SysTick_CTRL_CLKSOURCE_Pos 2 /*!< SysTick CTRL: CLKSOURCE Position */ #define SysTick_CTRL_CLKSOURCE_Msk (1UL << SysTick_CTRL_CLKSOURCE_Pos) /*!< SysTick CTRL: CLKSOURCE Mask */ #define SysTick_CTRL_TICKINT_Pos 1 /*!< SysTick CTRL: TICKINT Position */ #define SysTick_CTRL_TICKINT_Msk (1UL << SysTick_CTRL_TICKINT_Pos) /*!< SysTick CTRL: TICKINT Mask */ #define SysTick_CTRL_ENABLE_Pos 0 /*!< SysTick CTRL: ENABLE Position */ #define SysTick_CTRL_ENABLE_Msk (1UL /*<< SysTick_CTRL_ENABLE_Pos*/) /*!< SysTick CTRL: ENABLE Mask */ /* SysTick Reload Register Definitions */ #define SysTick_LOAD_RELOAD_Pos 0 /*!< SysTick LOAD: RELOAD Position */ #define SysTick_LOAD_RELOAD_Msk (0xFFFFFFUL /*<< SysTick_LOAD_RELOAD_Pos*/) /*!< SysTick LOAD: RELOAD Mask */ /* SysTick Current Register Definitions */ #define SysTick_VAL_CURRENT_Pos 0 /*!< SysTick VAL: CURRENT Position */ #define SysTick_VAL_CURRENT_Msk (0xFFFFFFUL /*<< SysTick_VAL_CURRENT_Pos*/) /*!< SysTick VAL: CURRENT Mask */ /* SysTick Calibration Register Definitions */ #define SysTick_CALIB_NOREF_Pos 31 /*!< SysTick CALIB: NOREF Position */ #define SysTick_CALIB_NOREF_Msk (1UL << SysTick_CALIB_NOREF_Pos) /*!< SysTick CALIB: NOREF Mask */ #define SysTick_CALIB_SKEW_Pos 30 /*!< SysTick CALIB: SKEW Position */ #define SysTick_CALIB_SKEW_Msk (1UL << SysTick_CALIB_SKEW_Pos) /*!< SysTick CALIB: SKEW Mask */ #define SysTick_CALIB_TENMS_Pos 0 /*!< SysTick CALIB: TENMS Position */ #define SysTick_CALIB_TENMS_Msk (0xFFFFFFUL /*<< SysTick_CALIB_TENMS_Pos*/) /*!< SysTick CALIB: TENMS Mask */ /*@} end of group CMSIS_SysTick */ /** \ingroup CMSIS_core_register \defgroup CMSIS_ITM Instrumentation Trace Macrocell (ITM) \brief Type definitions for the Instrumentation Trace Macrocell (ITM) @{ */ /** \brief Structure type to access the Instrumentation Trace Macrocell Register (ITM). */ typedef struct { __O union { __O uint8_t u8; /*!< Offset: 0x000 ( /W) ITM Stimulus Port 8-bit */ __O uint16_t u16; /*!< Offset: 0x000 ( /W) ITM Stimulus Port 16-bit */ __O uint32_t u32; /*!< Offset: 0x000 ( /W) ITM Stimulus Port 32-bit */ } PORT [32]; /*!< Offset: 0x000 ( /W) ITM Stimulus Port Registers */ uint32_t RESERVED0[864]; __IO uint32_t TER; /*!< Offset: 0xE00 (R/W) ITM Trace Enable Register */ uint32_t RESERVED1[15]; __IO uint32_t TPR; /*!< Offset: 0xE40 (R/W) ITM Trace Privilege Register */ uint32_t RESERVED2[15]; __IO uint32_t TCR; /*!< Offset: 0xE80 (R/W) ITM Trace Control Register */ uint32_t RESERVED3[29]; __O uint32_t IWR; /*!< Offset: 0xEF8 ( /W) ITM Integration Write Register */ __I uint32_t IRR; /*!< Offset: 0xEFC (R/ ) ITM Integration Read Register */ __IO uint32_t IMCR; /*!< Offset: 0xF00 (R/W) ITM Integration Mode Control Register */ uint32_t RESERVED4[43]; __O uint32_t LAR; /*!< Offset: 0xFB0 ( /W) ITM Lock Access Register */ __I uint32_t LSR; /*!< Offset: 0xFB4 (R/ ) ITM Lock Status Register */ uint32_t RESERVED5[6]; __I uint32_t PID4; /*!< Offset: 0xFD0 (R/ ) ITM Peripheral Identification Register #4 */ __I uint32_t PID5; /*!< Offset: 0xFD4 (R/ ) ITM Peripheral Identification Register #5 */ __I uint32_t PID6; /*!< Offset: 0xFD8 (R/ ) ITM Peripheral Identification Register #6 */ __I uint32_t PID7; /*!< Offset: 0xFDC (R/ ) ITM Peripheral Identification Register #7 */ __I uint32_t PID0; /*!< Offset: 0xFE0 (R/ ) ITM Peripheral Identification Register #0 */ __I uint32_t PID1; /*!< Offset: 0xFE4 (R/ ) ITM Peripheral Identification Register #1 */ __I uint32_t PID2; /*!< Offset: 0xFE8 (R/ ) ITM Peripheral Identification Register #2 */ __I uint32_t PID3; /*!< Offset: 0xFEC (R/ ) ITM Peripheral Identification Register #3 */ __I uint32_t CID0; /*!< Offset: 0xFF0 (R/ ) ITM Component Identification Register #0 */ __I uint32_t CID1; /*!< Offset: 0xFF4 (R/ ) ITM Component Identification Register #1 */ __I uint32_t CID2; /*!< Offset: 0xFF8 (R/ ) ITM Component Identification Register #2 */ __I uint32_t CID3; /*!< Offset: 0xFFC (R/ ) ITM Component Identification Register #3 */ } ITM_Type; /* ITM Trace Privilege Register Definitions */ #define ITM_TPR_PRIVMASK_Pos 0 /*!< ITM TPR: PRIVMASK Position */ #define ITM_TPR_PRIVMASK_Msk (0xFUL /*<< ITM_TPR_PRIVMASK_Pos*/) /*!< ITM TPR: PRIVMASK Mask */ /* ITM Trace Control Register Definitions */ #define ITM_TCR_BUSY_Pos 23 /*!< ITM TCR: BUSY Position */ #define ITM_TCR_BUSY_Msk (1UL << ITM_TCR_BUSY_Pos) /*!< ITM TCR: BUSY Mask */ #define ITM_TCR_TraceBusID_Pos 16 /*!< ITM TCR: ATBID Position */ #define ITM_TCR_TraceBusID_Msk (0x7FUL << ITM_TCR_TraceBusID_Pos) /*!< ITM TCR: ATBID Mask */ #define ITM_TCR_GTSFREQ_Pos 10 /*!< ITM TCR: Global timestamp frequency Position */ #define ITM_TCR_GTSFREQ_Msk (3UL << ITM_TCR_GTSFREQ_Pos) /*!< ITM TCR: Global timestamp frequency Mask */ #define ITM_TCR_TSPrescale_Pos 8 /*!< ITM TCR: TSPrescale Position */ #define ITM_TCR_TSPrescale_Msk (3UL << ITM_TCR_TSPrescale_Pos) /*!< ITM TCR: TSPrescale Mask */ #define ITM_TCR_SWOENA_Pos 4 /*!< ITM TCR: SWOENA Position */ #define ITM_TCR_SWOENA_Msk (1UL << ITM_TCR_SWOENA_Pos) /*!< ITM TCR: SWOENA Mask */ #define ITM_TCR_DWTENA_Pos 3 /*!< ITM TCR: DWTENA Position */ #define ITM_TCR_DWTENA_Msk (1UL << ITM_TCR_DWTENA_Pos) /*!< ITM TCR: DWTENA Mask */ #define ITM_TCR_SYNCENA_Pos 2 /*!< ITM TCR: SYNCENA Position */ #define ITM_TCR_SYNCENA_Msk (1UL << ITM_TCR_SYNCENA_Pos) /*!< ITM TCR: SYNCENA Mask */ #define ITM_TCR_TSENA_Pos 1 /*!< ITM TCR: TSENA Position */ #define ITM_TCR_TSENA_Msk (1UL << ITM_TCR_TSENA_Pos) /*!< ITM TCR: TSENA Mask */ #define ITM_TCR_ITMENA_Pos 0 /*!< ITM TCR: ITM Enable bit Position */ #define ITM_TCR_ITMENA_Msk (1UL /*<< ITM_TCR_ITMENA_Pos*/) /*!< ITM TCR: ITM Enable bit Mask */ /* ITM Integration Write Register Definitions */ #define ITM_IWR_ATVALIDM_Pos 0 /*!< ITM IWR: ATVALIDM Position */ #define ITM_IWR_ATVALIDM_Msk (1UL /*<< ITM_IWR_ATVALIDM_Pos*/) /*!< ITM IWR: ATVALIDM Mask */ /* ITM Integration Read Register Definitions */ #define ITM_IRR_ATREADYM_Pos 0 /*!< ITM IRR: ATREADYM Position */ #define ITM_IRR_ATREADYM_Msk (1UL /*<< ITM_IRR_ATREADYM_Pos*/) /*!< ITM IRR: ATREADYM Mask */ /* ITM Integration Mode Control Register Definitions */ #define ITM_IMCR_INTEGRATION_Pos 0 /*!< ITM IMCR: INTEGRATION Position */ #define ITM_IMCR_INTEGRATION_Msk (1UL /*<< ITM_IMCR_INTEGRATION_Pos*/) /*!< ITM IMCR: INTEGRATION Mask */ /* ITM Lock Status Register Definitions */ #define ITM_LSR_ByteAcc_Pos 2 /*!< ITM LSR: ByteAcc Position */ #define ITM_LSR_ByteAcc_Msk (1UL << ITM_LSR_ByteAcc_Pos) /*!< ITM LSR: ByteAcc Mask */ #define ITM_LSR_Access_Pos 1 /*!< ITM LSR: Access Position */ #define ITM_LSR_Access_Msk (1UL << ITM_LSR_Access_Pos) /*!< ITM LSR: Access Mask */ #define ITM_LSR_Present_Pos 0 /*!< ITM LSR: Present Position */ #define ITM_LSR_Present_Msk (1UL /*<< ITM_LSR_Present_Pos*/) /*!< ITM LSR: Present Mask */ /*@}*/ /* end of group CMSIS_ITM */ /** \ingroup CMSIS_core_register \defgroup CMSIS_DWT Data Watchpoint and Trace (DWT) \brief Type definitions for the Data Watchpoint and Trace (DWT) @{ */ /** \brief Structure type to access the Data Watchpoint and Trace Register (DWT). */ typedef struct { __IO uint32_t CTRL; /*!< Offset: 0x000 (R/W) Control Register */ __IO uint32_t CYCCNT; /*!< Offset: 0x004 (R/W) Cycle Count Register */ __IO uint32_t CPICNT; /*!< Offset: 0x008 (R/W) CPI Count Register */ __IO uint32_t EXCCNT; /*!< Offset: 0x00C (R/W) Exception Overhead Count Register */ __IO uint32_t SLEEPCNT; /*!< Offset: 0x010 (R/W) Sleep Count Register */ __IO uint32_t LSUCNT; /*!< Offset: 0x014 (R/W) LSU Count Register */ __IO uint32_t FOLDCNT; /*!< Offset: 0x018 (R/W) Folded-instruction Count Register */ __I uint32_t PCSR; /*!< Offset: 0x01C (R/ ) Program Counter Sample Register */ __IO uint32_t COMP0; /*!< Offset: 0x020 (R/W) Comparator Register 0 */ __IO uint32_t MASK0; /*!< Offset: 0x024 (R/W) Mask Register 0 */ __IO uint32_t FUNCTION0; /*!< Offset: 0x028 (R/W) Function Register 0 */ uint32_t RESERVED0[1]; __IO uint32_t COMP1; /*!< Offset: 0x030 (R/W) Comparator Register 1 */ __IO uint32_t MASK1; /*!< Offset: 0x034 (R/W) Mask Register 1 */ __IO uint32_t FUNCTION1; /*!< Offset: 0x038 (R/W) Function Register 1 */ uint32_t RESERVED1[1]; __IO uint32_t COMP2; /*!< Offset: 0x040 (R/W) Comparator Register 2 */ __IO uint32_t MASK2; /*!< Offset: 0x044 (R/W) Mask Register 2 */ __IO uint32_t FUNCTION2; /*!< Offset: 0x048 (R/W) Function Register 2 */ uint32_t RESERVED2[1]; __IO uint32_t COMP3; /*!< Offset: 0x050 (R/W) Comparator Register 3 */ __IO uint32_t MASK3; /*!< Offset: 0x054 (R/W) Mask Register 3 */ __IO uint32_t FUNCTION3; /*!< Offset: 0x058 (R/W) Function Register 3 */ uint32_t RESERVED3[981]; __O uint32_t LAR; /*!< Offset: 0xFB0 ( W) Lock Access Register */ __I uint32_t LSR; /*!< Offset: 0xFB4 (R ) Lock Status Register */ } DWT_Type; /* DWT Control Register Definitions */ #define DWT_CTRL_NUMCOMP_Pos 28 /*!< DWT CTRL: NUMCOMP Position */ #define DWT_CTRL_NUMCOMP_Msk (0xFUL << DWT_CTRL_NUMCOMP_Pos) /*!< DWT CTRL: NUMCOMP Mask */ #define DWT_CTRL_NOTRCPKT_Pos 27 /*!< DWT CTRL: NOTRCPKT Position */ #define DWT_CTRL_NOTRCPKT_Msk (0x1UL << DWT_CTRL_NOTRCPKT_Pos) /*!< DWT CTRL: NOTRCPKT Mask */ #define DWT_CTRL_NOEXTTRIG_Pos 26 /*!< DWT CTRL: NOEXTTRIG Position */ #define DWT_CTRL_NOEXTTRIG_Msk (0x1UL << DWT_CTRL_NOEXTTRIG_Pos) /*!< DWT CTRL: NOEXTTRIG Mask */ #define DWT_CTRL_NOCYCCNT_Pos 25 /*!< DWT CTRL: NOCYCCNT Position */ #define DWT_CTRL_NOCYCCNT_Msk (0x1UL << DWT_CTRL_NOCYCCNT_Pos) /*!< DWT CTRL: NOCYCCNT Mask */ #define DWT_CTRL_NOPRFCNT_Pos 24 /*!< DWT CTRL: NOPRFCNT Position */ #define DWT_CTRL_NOPRFCNT_Msk (0x1UL << DWT_CTRL_NOPRFCNT_Pos) /*!< DWT CTRL: NOPRFCNT Mask */ #define DWT_CTRL_CYCEVTENA_Pos 22 /*!< DWT CTRL: CYCEVTENA Position */ #define DWT_CTRL_CYCEVTENA_Msk (0x1UL << DWT_CTRL_CYCEVTENA_Pos) /*!< DWT CTRL: CYCEVTENA Mask */ #define DWT_CTRL_FOLDEVTENA_Pos 21 /*!< DWT CTRL: FOLDEVTENA Position */ #define DWT_CTRL_FOLDEVTENA_Msk (0x1UL << DWT_CTRL_FOLDEVTENA_Pos) /*!< DWT CTRL: FOLDEVTENA Mask */ #define DWT_CTRL_LSUEVTENA_Pos 20 /*!< DWT CTRL: LSUEVTENA Position */ #define DWT_CTRL_LSUEVTENA_Msk (0x1UL << DWT_CTRL_LSUEVTENA_Pos) /*!< DWT CTRL: LSUEVTENA Mask */ #define DWT_CTRL_SLEEPEVTENA_Pos 19 /*!< DWT CTRL: SLEEPEVTENA Position */ #define DWT_CTRL_SLEEPEVTENA_Msk (0x1UL << DWT_CTRL_SLEEPEVTENA_Pos) /*!< DWT CTRL: SLEEPEVTENA Mask */ #define DWT_CTRL_EXCEVTENA_Pos 18 /*!< DWT CTRL: EXCEVTENA Position */ #define DWT_CTRL_EXCEVTENA_Msk (0x1UL << DWT_CTRL_EXCEVTENA_Pos) /*!< DWT CTRL: EXCEVTENA Mask */ #define DWT_CTRL_CPIEVTENA_Pos 17 /*!< DWT CTRL: CPIEVTENA Position */ #define DWT_CTRL_CPIEVTENA_Msk (0x1UL << DWT_CTRL_CPIEVTENA_Pos) /*!< DWT CTRL: CPIEVTENA Mask */ #define DWT_CTRL_EXCTRCENA_Pos 16 /*!< DWT CTRL: EXCTRCENA Position */ #define DWT_CTRL_EXCTRCENA_Msk (0x1UL << DWT_CTRL_EXCTRCENA_Pos) /*!< DWT CTRL: EXCTRCENA Mask */ #define DWT_CTRL_PCSAMPLENA_Pos 12 /*!< DWT CTRL: PCSAMPLENA Position */ #define DWT_CTRL_PCSAMPLENA_Msk (0x1UL << DWT_CTRL_PCSAMPLENA_Pos) /*!< DWT CTRL: PCSAMPLENA Mask */ #define DWT_CTRL_SYNCTAP_Pos 10 /*!< DWT CTRL: SYNCTAP Position */ #define DWT_CTRL_SYNCTAP_Msk (0x3UL << DWT_CTRL_SYNCTAP_Pos) /*!< DWT CTRL: SYNCTAP Mask */ #define DWT_CTRL_CYCTAP_Pos 9 /*!< DWT CTRL: CYCTAP Position */ #define DWT_CTRL_CYCTAP_Msk (0x1UL << DWT_CTRL_CYCTAP_Pos) /*!< DWT CTRL: CYCTAP Mask */ #define DWT_CTRL_POSTINIT_Pos 5 /*!< DWT CTRL: POSTINIT Position */ #define DWT_CTRL_POSTINIT_Msk (0xFUL << DWT_CTRL_POSTINIT_Pos) /*!< DWT CTRL: POSTINIT Mask */ #define DWT_CTRL_POSTPRESET_Pos 1 /*!< DWT CTRL: POSTPRESET Position */ #define DWT_CTRL_POSTPRESET_Msk (0xFUL << DWT_CTRL_POSTPRESET_Pos) /*!< DWT CTRL: POSTPRESET Mask */ #define DWT_CTRL_CYCCNTENA_Pos 0 /*!< DWT CTRL: CYCCNTENA Position */ #define DWT_CTRL_CYCCNTENA_Msk (0x1UL /*<< DWT_CTRL_CYCCNTENA_Pos*/) /*!< DWT CTRL: CYCCNTENA Mask */ /* DWT CPI Count Register Definitions */ #define DWT_CPICNT_CPICNT_Pos 0 /*!< DWT CPICNT: CPICNT Position */ #define DWT_CPICNT_CPICNT_Msk (0xFFUL /*<< DWT_CPICNT_CPICNT_Pos*/) /*!< DWT CPICNT: CPICNT Mask */ /* DWT Exception Overhead Count Register Definitions */ #define DWT_EXCCNT_EXCCNT_Pos 0 /*!< DWT EXCCNT: EXCCNT Position */ #define DWT_EXCCNT_EXCCNT_Msk (0xFFUL /*<< DWT_EXCCNT_EXCCNT_Pos*/) /*!< DWT EXCCNT: EXCCNT Mask */ /* DWT Sleep Count Register Definitions */ #define DWT_SLEEPCNT_SLEEPCNT_Pos 0 /*!< DWT SLEEPCNT: SLEEPCNT Position */ #define DWT_SLEEPCNT_SLEEPCNT_Msk (0xFFUL /*<< DWT_SLEEPCNT_SLEEPCNT_Pos*/) /*!< DWT SLEEPCNT: SLEEPCNT Mask */ /* DWT LSU Count Register Definitions */ #define DWT_LSUCNT_LSUCNT_Pos 0 /*!< DWT LSUCNT: LSUCNT Position */ #define DWT_LSUCNT_LSUCNT_Msk (0xFFUL /*<< DWT_LSUCNT_LSUCNT_Pos*/) /*!< DWT LSUCNT: LSUCNT Mask */ /* DWT Folded-instruction Count Register Definitions */ #define DWT_FOLDCNT_FOLDCNT_Pos 0 /*!< DWT FOLDCNT: FOLDCNT Position */ #define DWT_FOLDCNT_FOLDCNT_Msk (0xFFUL /*<< DWT_FOLDCNT_FOLDCNT_Pos*/) /*!< DWT FOLDCNT: FOLDCNT Mask */ /* DWT Comparator Mask Register Definitions */ #define DWT_MASK_MASK_Pos 0 /*!< DWT MASK: MASK Position */ #define DWT_MASK_MASK_Msk (0x1FUL /*<< DWT_MASK_MASK_Pos*/) /*!< DWT MASK: MASK Mask */ /* DWT Comparator Function Register Definitions */ #define DWT_FUNCTION_MATCHED_Pos 24 /*!< DWT FUNCTION: MATCHED Position */ #define DWT_FUNCTION_MATCHED_Msk (0x1UL << DWT_FUNCTION_MATCHED_Pos) /*!< DWT FUNCTION: MATCHED Mask */ #define DWT_FUNCTION_DATAVADDR1_Pos 16 /*!< DWT FUNCTION: DATAVADDR1 Position */ #define DWT_FUNCTION_DATAVADDR1_Msk (0xFUL << DWT_FUNCTION_DATAVADDR1_Pos) /*!< DWT FUNCTION: DATAVADDR1 Mask */ #define DWT_FUNCTION_DATAVADDR0_Pos 12 /*!< DWT FUNCTION: DATAVADDR0 Position */ #define DWT_FUNCTION_DATAVADDR0_Msk (0xFUL << DWT_FUNCTION_DATAVADDR0_Pos) /*!< DWT FUNCTION: DATAVADDR0 Mask */ #define DWT_FUNCTION_DATAVSIZE_Pos 10 /*!< DWT FUNCTION: DATAVSIZE Position */ #define DWT_FUNCTION_DATAVSIZE_Msk (0x3UL << DWT_FUNCTION_DATAVSIZE_Pos) /*!< DWT FUNCTION: DATAVSIZE Mask */ #define DWT_FUNCTION_LNK1ENA_Pos 9 /*!< DWT FUNCTION: LNK1ENA Position */ #define DWT_FUNCTION_LNK1ENA_Msk (0x1UL << DWT_FUNCTION_LNK1ENA_Pos) /*!< DWT FUNCTION: LNK1ENA Mask */ #define DWT_FUNCTION_DATAVMATCH_Pos 8 /*!< DWT FUNCTION: DATAVMATCH Position */ #define DWT_FUNCTION_DATAVMATCH_Msk (0x1UL << DWT_FUNCTION_DATAVMATCH_Pos) /*!< DWT FUNCTION: DATAVMATCH Mask */ #define DWT_FUNCTION_CYCMATCH_Pos 7 /*!< DWT FUNCTION: CYCMATCH Position */ #define DWT_FUNCTION_CYCMATCH_Msk (0x1UL << DWT_FUNCTION_CYCMATCH_Pos) /*!< DWT FUNCTION: CYCMATCH Mask */ #define DWT_FUNCTION_EMITRANGE_Pos 5 /*!< DWT FUNCTION: EMITRANGE Position */ #define DWT_FUNCTION_EMITRANGE_Msk (0x1UL << DWT_FUNCTION_EMITRANGE_Pos) /*!< DWT FUNCTION: EMITRANGE Mask */ #define DWT_FUNCTION_FUNCTION_Pos 0 /*!< DWT FUNCTION: FUNCTION Position */ #define DWT_FUNCTION_FUNCTION_Msk (0xFUL /*<< DWT_FUNCTION_FUNCTION_Pos*/) /*!< DWT FUNCTION: FUNCTION Mask */ /*@}*/ /* end of group CMSIS_DWT */ /** \ingroup CMSIS_core_register \defgroup CMSIS_TPI Trace Port Interface (TPI) \brief Type definitions for the Trace Port Interface (TPI) @{ */ /** \brief Structure type to access the Trace Port Interface Register (TPI). */ typedef struct { __IO uint32_t SSPSR; /*!< Offset: 0x000 (R/ ) Supported Parallel Port Size Register */ __IO uint32_t CSPSR; /*!< Offset: 0x004 (R/W) Current Parallel Port Size Register */ uint32_t RESERVED0[2]; __IO uint32_t ACPR; /*!< Offset: 0x010 (R/W) Asynchronous Clock Prescaler Register */ uint32_t RESERVED1[55]; __IO uint32_t SPPR; /*!< Offset: 0x0F0 (R/W) Selected Pin Protocol Register */ uint32_t RESERVED2[131]; __I uint32_t FFSR; /*!< Offset: 0x300 (R/ ) Formatter and Flush Status Register */ __IO uint32_t FFCR; /*!< Offset: 0x304 (R/W) Formatter and Flush Control Register */ __I uint32_t FSCR; /*!< Offset: 0x308 (R/ ) Formatter Synchronization Counter Register */ uint32_t RESERVED3[759]; __I uint32_t TRIGGER; /*!< Offset: 0xEE8 (R/ ) TRIGGER */ __I uint32_t FIFO0; /*!< Offset: 0xEEC (R/ ) Integration ETM Data */ __I uint32_t ITATBCTR2; /*!< Offset: 0xEF0 (R/ ) ITATBCTR2 */ uint32_t RESERVED4[1]; __I uint32_t ITATBCTR0; /*!< Offset: 0xEF8 (R/ ) ITATBCTR0 */ __I uint32_t FIFO1; /*!< Offset: 0xEFC (R/ ) Integration ITM Data */ __IO uint32_t ITCTRL; /*!< Offset: 0xF00 (R/W) Integration Mode Control */ uint32_t RESERVED5[39]; __IO uint32_t CLAIMSET; /*!< Offset: 0xFA0 (R/W) Claim tag set */ __IO uint32_t CLAIMCLR; /*!< Offset: 0xFA4 (R/W) Claim tag clear */ uint32_t RESERVED7[8]; __I uint32_t DEVID; /*!< Offset: 0xFC8 (R/ ) TPIU_DEVID */ __I uint32_t DEVTYPE; /*!< Offset: 0xFCC (R/ ) TPIU_DEVTYPE */ } TPI_Type; /* TPI Asynchronous Clock Prescaler Register Definitions */ #define TPI_ACPR_PRESCALER_Pos 0 /*!< TPI ACPR: PRESCALER Position */ #define TPI_ACPR_PRESCALER_Msk (0x1FFFUL /*<< TPI_ACPR_PRESCALER_Pos*/) /*!< TPI ACPR: PRESCALER Mask */ /* TPI Selected Pin Protocol Register Definitions */ #define TPI_SPPR_TXMODE_Pos 0 /*!< TPI SPPR: TXMODE Position */ #define TPI_SPPR_TXMODE_Msk (0x3UL /*<< TPI_SPPR_TXMODE_Pos*/) /*!< TPI SPPR: TXMODE Mask */ /* TPI Formatter and Flush Status Register Definitions */ #define TPI_FFSR_FtNonStop_Pos 3 /*!< TPI FFSR: FtNonStop Position */ #define TPI_FFSR_FtNonStop_Msk (0x1UL << TPI_FFSR_FtNonStop_Pos) /*!< TPI FFSR: FtNonStop Mask */ #define TPI_FFSR_TCPresent_Pos 2 /*!< TPI FFSR: TCPresent Position */ #define TPI_FFSR_TCPresent_Msk (0x1UL << TPI_FFSR_TCPresent_Pos) /*!< TPI FFSR: TCPresent Mask */ #define TPI_FFSR_FtStopped_Pos 1 /*!< TPI FFSR: FtStopped Position */ #define TPI_FFSR_FtStopped_Msk (0x1UL << TPI_FFSR_FtStopped_Pos) /*!< TPI FFSR: FtStopped Mask */ #define TPI_FFSR_FlInProg_Pos 0 /*!< TPI FFSR: FlInProg Position */ #define TPI_FFSR_FlInProg_Msk (0x1UL /*<< TPI_FFSR_FlInProg_Pos*/) /*!< TPI FFSR: FlInProg Mask */ /* TPI Formatter and Flush Control Register Definitions */ #define TPI_FFCR_TrigIn_Pos 8 /*!< TPI FFCR: TrigIn Position */ #define TPI_FFCR_TrigIn_Msk (0x1UL << TPI_FFCR_TrigIn_Pos) /*!< TPI FFCR: TrigIn Mask */ #define TPI_FFCR_EnFCont_Pos 1 /*!< TPI FFCR: EnFCont Position */ #define TPI_FFCR_EnFCont_Msk (0x1UL << TPI_FFCR_EnFCont_Pos) /*!< TPI FFCR: EnFCont Mask */ /* TPI TRIGGER Register Definitions */ #define TPI_TRIGGER_TRIGGER_Pos 0 /*!< TPI TRIGGER: TRIGGER Position */ #define TPI_TRIGGER_TRIGGER_Msk (0x1UL /*<< TPI_TRIGGER_TRIGGER_Pos*/) /*!< TPI TRIGGER: TRIGGER Mask */ /* TPI Integration ETM Data Register Definitions (FIFO0) */ #define TPI_FIFO0_ITM_ATVALID_Pos 29 /*!< TPI FIFO0: ITM_ATVALID Position */ #define TPI_FIFO0_ITM_ATVALID_Msk (0x3UL << TPI_FIFO0_ITM_ATVALID_Pos) /*!< TPI FIFO0: ITM_ATVALID Mask */ #define TPI_FIFO0_ITM_bytecount_Pos 27 /*!< TPI FIFO0: ITM_bytecount Position */ #define TPI_FIFO0_ITM_bytecount_Msk (0x3UL << TPI_FIFO0_ITM_bytecount_Pos) /*!< TPI FIFO0: ITM_bytecount Mask */ #define TPI_FIFO0_ETM_ATVALID_Pos 26 /*!< TPI FIFO0: ETM_ATVALID Position */ #define TPI_FIFO0_ETM_ATVALID_Msk (0x3UL << TPI_FIFO0_ETM_ATVALID_Pos) /*!< TPI FIFO0: ETM_ATVALID Mask */ #define TPI_FIFO0_ETM_bytecount_Pos 24 /*!< TPI FIFO0: ETM_bytecount Position */ #define TPI_FIFO0_ETM_bytecount_Msk (0x3UL << TPI_FIFO0_ETM_bytecount_Pos) /*!< TPI FIFO0: ETM_bytecount Mask */ #define TPI_FIFO0_ETM2_Pos 16 /*!< TPI FIFO0: ETM2 Position */ #define TPI_FIFO0_ETM2_Msk (0xFFUL << TPI_FIFO0_ETM2_Pos) /*!< TPI FIFO0: ETM2 Mask */ #define TPI_FIFO0_ETM1_Pos 8 /*!< TPI FIFO0: ETM1 Position */ #define TPI_FIFO0_ETM1_Msk (0xFFUL << TPI_FIFO0_ETM1_Pos) /*!< TPI FIFO0: ETM1 Mask */ #define TPI_FIFO0_ETM0_Pos 0 /*!< TPI FIFO0: ETM0 Position */ #define TPI_FIFO0_ETM0_Msk (0xFFUL /*<< TPI_FIFO0_ETM0_Pos*/) /*!< TPI FIFO0: ETM0 Mask */ /* TPI ITATBCTR2 Register Definitions */ #define TPI_ITATBCTR2_ATREADY_Pos 0 /*!< TPI ITATBCTR2: ATREADY Position */ #define TPI_ITATBCTR2_ATREADY_Msk (0x1UL /*<< TPI_ITATBCTR2_ATREADY_Pos*/) /*!< TPI ITATBCTR2: ATREADY Mask */ /* TPI Integration ITM Data Register Definitions (FIFO1) */ #define TPI_FIFO1_ITM_ATVALID_Pos 29 /*!< TPI FIFO1: ITM_ATVALID Position */ #define TPI_FIFO1_ITM_ATVALID_Msk (0x3UL << TPI_FIFO1_ITM_ATVALID_Pos) /*!< TPI FIFO1: ITM_ATVALID Mask */ #define TPI_FIFO1_ITM_bytecount_Pos 27 /*!< TPI FIFO1: ITM_bytecount Position */ #define TPI_FIFO1_ITM_bytecount_Msk (0x3UL << TPI_FIFO1_ITM_bytecount_Pos) /*!< TPI FIFO1: ITM_bytecount Mask */ #define TPI_FIFO1_ETM_ATVALID_Pos 26 /*!< TPI FIFO1: ETM_ATVALID Position */ #define TPI_FIFO1_ETM_ATVALID_Msk (0x3UL << TPI_FIFO1_ETM_ATVALID_Pos) /*!< TPI FIFO1: ETM_ATVALID Mask */ #define TPI_FIFO1_ETM_bytecount_Pos 24 /*!< TPI FIFO1: ETM_bytecount Position */ #define TPI_FIFO1_ETM_bytecount_Msk (0x3UL << TPI_FIFO1_ETM_bytecount_Pos) /*!< TPI FIFO1: ETM_bytecount Mask */ #define TPI_FIFO1_ITM2_Pos 16 /*!< TPI FIFO1: ITM2 Position */ #define TPI_FIFO1_ITM2_Msk (0xFFUL << TPI_FIFO1_ITM2_Pos) /*!< TPI FIFO1: ITM2 Mask */ #define TPI_FIFO1_ITM1_Pos 8 /*!< TPI FIFO1: ITM1 Position */ #define TPI_FIFO1_ITM1_Msk (0xFFUL << TPI_FIFO1_ITM1_Pos) /*!< TPI FIFO1: ITM1 Mask */ #define TPI_FIFO1_ITM0_Pos 0 /*!< TPI FIFO1: ITM0 Position */ #define TPI_FIFO1_ITM0_Msk (0xFFUL /*<< TPI_FIFO1_ITM0_Pos*/) /*!< TPI FIFO1: ITM0 Mask */ /* TPI ITATBCTR0 Register Definitions */ #define TPI_ITATBCTR0_ATREADY_Pos 0 /*!< TPI ITATBCTR0: ATREADY Position */ #define TPI_ITATBCTR0_ATREADY_Msk (0x1UL /*<< TPI_ITATBCTR0_ATREADY_Pos*/) /*!< TPI ITATBCTR0: ATREADY Mask */ /* TPI Integration Mode Control Register Definitions */ #define TPI_ITCTRL_Mode_Pos 0 /*!< TPI ITCTRL: Mode Position */ #define TPI_ITCTRL_Mode_Msk (0x1UL /*<< TPI_ITCTRL_Mode_Pos*/) /*!< TPI ITCTRL: Mode Mask */ /* TPI DEVID Register Definitions */ #define TPI_DEVID_NRZVALID_Pos 11 /*!< TPI DEVID: NRZVALID Position */ #define TPI_DEVID_NRZVALID_Msk (0x1UL << TPI_DEVID_NRZVALID_Pos) /*!< TPI DEVID: NRZVALID Mask */ #define TPI_DEVID_MANCVALID_Pos 10 /*!< TPI DEVID: MANCVALID Position */ #define TPI_DEVID_MANCVALID_Msk (0x1UL << TPI_DEVID_MANCVALID_Pos) /*!< TPI DEVID: MANCVALID Mask */ #define TPI_DEVID_PTINVALID_Pos 9 /*!< TPI DEVID: PTINVALID Position */ #define TPI_DEVID_PTINVALID_Msk (0x1UL << TPI_DEVID_PTINVALID_Pos) /*!< TPI DEVID: PTINVALID Mask */ #define TPI_DEVID_MinBufSz_Pos 6 /*!< TPI DEVID: MinBufSz Position */ #define TPI_DEVID_MinBufSz_Msk (0x7UL << TPI_DEVID_MinBufSz_Pos) /*!< TPI DEVID: MinBufSz Mask */ #define TPI_DEVID_AsynClkIn_Pos 5 /*!< TPI DEVID: AsynClkIn Position */ #define TPI_DEVID_AsynClkIn_Msk (0x1UL << TPI_DEVID_AsynClkIn_Pos) /*!< TPI DEVID: AsynClkIn Mask */ #define TPI_DEVID_NrTraceInput_Pos 0 /*!< TPI DEVID: NrTraceInput Position */ #define TPI_DEVID_NrTraceInput_Msk (0x1FUL /*<< TPI_DEVID_NrTraceInput_Pos*/) /*!< TPI DEVID: NrTraceInput Mask */ /* TPI DEVTYPE Register Definitions */ #define TPI_DEVTYPE_MajorType_Pos 4 /*!< TPI DEVTYPE: MajorType Position */ #define TPI_DEVTYPE_MajorType_Msk (0xFUL << TPI_DEVTYPE_MajorType_Pos) /*!< TPI DEVTYPE: MajorType Mask */ #define TPI_DEVTYPE_SubType_Pos 0 /*!< TPI DEVTYPE: SubType Position */ #define TPI_DEVTYPE_SubType_Msk (0xFUL /*<< TPI_DEVTYPE_SubType_Pos*/) /*!< TPI DEVTYPE: SubType Mask */ /*@}*/ /* end of group CMSIS_TPI */ #if (__MPU_PRESENT == 1) /** \ingroup CMSIS_core_register \defgroup CMSIS_MPU Memory Protection Unit (MPU) \brief Type definitions for the Memory Protection Unit (MPU) @{ */ /** \brief Structure type to access the Memory Protection Unit (MPU). */ typedef struct { __I uint32_t TYPE; /*!< Offset: 0x000 (R/ ) MPU Type Register */ __IO uint32_t CTRL; /*!< Offset: 0x004 (R/W) MPU Control Register */ __IO uint32_t RNR; /*!< Offset: 0x008 (R/W) MPU Region RNRber Register */ __IO uint32_t RBAR; /*!< Offset: 0x00C (R/W) MPU Region Base Address Register */ __IO uint32_t RASR; /*!< Offset: 0x010 (R/W) MPU Region Attribute and Size Register */ __IO uint32_t RBAR_A1; /*!< Offset: 0x014 (R/W) MPU Alias 1 Region Base Address Register */ __IO uint32_t RASR_A1; /*!< Offset: 0x018 (R/W) MPU Alias 1 Region Attribute and Size Register */ __IO uint32_t RBAR_A2; /*!< Offset: 0x01C (R/W) MPU Alias 2 Region Base Address Register */ __IO uint32_t RASR_A2; /*!< Offset: 0x020 (R/W) MPU Alias 2 Region Attribute and Size Register */ __IO uint32_t RBAR_A3; /*!< Offset: 0x024 (R/W) MPU Alias 3 Region Base Address Register */ __IO uint32_t RASR_A3; /*!< Offset: 0x028 (R/W) MPU Alias 3 Region Attribute and Size Register */ } MPU_Type; /* MPU Type Register */ #define MPU_TYPE_IREGION_Pos 16 /*!< MPU TYPE: IREGION Position */ #define MPU_TYPE_IREGION_Msk (0xFFUL << MPU_TYPE_IREGION_Pos) /*!< MPU TYPE: IREGION Mask */ #define MPU_TYPE_DREGION_Pos 8 /*!< MPU TYPE: DREGION Position */ #define MPU_TYPE_DREGION_Msk (0xFFUL << MPU_TYPE_DREGION_Pos) /*!< MPU TYPE: DREGION Mask */ #define MPU_TYPE_SEPARATE_Pos 0 /*!< MPU TYPE: SEPARATE Position */ #define MPU_TYPE_SEPARATE_Msk (1UL /*<< MPU_TYPE_SEPARATE_Pos*/) /*!< MPU TYPE: SEPARATE Mask */ /* MPU Control Register */ #define MPU_CTRL_PRIVDEFENA_Pos 2 /*!< MPU CTRL: PRIVDEFENA Position */ #define MPU_CTRL_PRIVDEFENA_Msk (1UL << MPU_CTRL_PRIVDEFENA_Pos) /*!< MPU CTRL: PRIVDEFENA Mask */ #define MPU_CTRL_HFNMIENA_Pos 1 /*!< MPU CTRL: HFNMIENA Position */ #define MPU_CTRL_HFNMIENA_Msk (1UL << MPU_CTRL_HFNMIENA_Pos) /*!< MPU CTRL: HFNMIENA Mask */ #define MPU_CTRL_ENABLE_Pos 0 /*!< MPU CTRL: ENABLE Position */ #define MPU_CTRL_ENABLE_Msk (1UL /*<< MPU_CTRL_ENABLE_Pos*/) /*!< MPU CTRL: ENABLE Mask */ /* MPU Region Number Register */ #define MPU_RNR_REGION_Pos 0 /*!< MPU RNR: REGION Position */ #define MPU_RNR_REGION_Msk (0xFFUL /*<< MPU_RNR_REGION_Pos*/) /*!< MPU RNR: REGION Mask */ /* MPU Region Base Address Register */ #define MPU_RBAR_ADDR_Pos 5 /*!< MPU RBAR: ADDR Position */ #define MPU_RBAR_ADDR_Msk (0x7FFFFFFUL << MPU_RBAR_ADDR_Pos) /*!< MPU RBAR: ADDR Mask */ #define MPU_RBAR_VALID_Pos 4 /*!< MPU RBAR: VALID Position */ #define MPU_RBAR_VALID_Msk (1UL << MPU_RBAR_VALID_Pos) /*!< MPU RBAR: VALID Mask */ #define MPU_RBAR_REGION_Pos 0 /*!< MPU RBAR: REGION Position */ #define MPU_RBAR_REGION_Msk (0xFUL /*<< MPU_RBAR_REGION_Pos*/) /*!< MPU RBAR: REGION Mask */ /* MPU Region Attribute and Size Register */ #define MPU_RASR_ATTRS_Pos 16 /*!< MPU RASR: MPU Region Attribute field Position */ #define MPU_RASR_ATTRS_Msk (0xFFFFUL << MPU_RASR_ATTRS_Pos) /*!< MPU RASR: MPU Region Attribute field Mask */ #define MPU_RASR_XN_Pos 28 /*!< MPU RASR: ATTRS.XN Position */ #define MPU_RASR_XN_Msk (1UL << MPU_RASR_XN_Pos) /*!< MPU RASR: ATTRS.XN Mask */ #define MPU_RASR_AP_Pos 24 /*!< MPU RASR: ATTRS.AP Position */ #define MPU_RASR_AP_Msk (0x7UL << MPU_RASR_AP_Pos) /*!< MPU RASR: ATTRS.AP Mask */ #define MPU_RASR_TEX_Pos 19 /*!< MPU RASR: ATTRS.TEX Position */ #define MPU_RASR_TEX_Msk (0x7UL << MPU_RASR_TEX_Pos) /*!< MPU RASR: ATTRS.TEX Mask */ #define MPU_RASR_S_Pos 18 /*!< MPU RASR: ATTRS.S Position */ #define MPU_RASR_S_Msk (1UL << MPU_RASR_S_Pos) /*!< MPU RASR: ATTRS.S Mask */ #define MPU_RASR_C_Pos 17 /*!< MPU RASR: ATTRS.C Position */ #define MPU_RASR_C_Msk (1UL << MPU_RASR_C_Pos) /*!< MPU RASR: ATTRS.C Mask */ #define MPU_RASR_B_Pos 16 /*!< MPU RASR: ATTRS.B Position */ #define MPU_RASR_B_Msk (1UL << MPU_RASR_B_Pos) /*!< MPU RASR: ATTRS.B Mask */ #define MPU_RASR_SRD_Pos 8 /*!< MPU RASR: Sub-Region Disable Position */ #define MPU_RASR_SRD_Msk (0xFFUL << MPU_RASR_SRD_Pos) /*!< MPU RASR: Sub-Region Disable Mask */ #define MPU_RASR_SIZE_Pos 1 /*!< MPU RASR: Region Size Field Position */ #define MPU_RASR_SIZE_Msk (0x1FUL << MPU_RASR_SIZE_Pos) /*!< MPU RASR: Region Size Field Mask */ #define MPU_RASR_ENABLE_Pos 0 /*!< MPU RASR: Region enable bit Position */ #define MPU_RASR_ENABLE_Msk (1UL /*<< MPU_RASR_ENABLE_Pos*/) /*!< MPU RASR: Region enable bit Disable Mask */ /*@} end of group CMSIS_MPU */ #endif #if (__FPU_PRESENT == 1) /** \ingroup CMSIS_core_register \defgroup CMSIS_FPU Floating Point Unit (FPU) \brief Type definitions for the Floating Point Unit (FPU) @{ */ /** \brief Structure type to access the Floating Point Unit (FPU). */ typedef struct { uint32_t RESERVED0[1]; __IO uint32_t FPCCR; /*!< Offset: 0x004 (R/W) Floating-Point Context Control Register */ __IO uint32_t FPCAR; /*!< Offset: 0x008 (R/W) Floating-Point Context Address Register */ __IO uint32_t FPDSCR; /*!< Offset: 0x00C (R/W) Floating-Point Default Status Control Register */ __I uint32_t MVFR0; /*!< Offset: 0x010 (R/ ) Media and FP Feature Register 0 */ __I uint32_t MVFR1; /*!< Offset: 0x014 (R/ ) Media and FP Feature Register 1 */ __I uint32_t MVFR2; /*!< Offset: 0x018 (R/ ) Media and FP Feature Register 2 */ } FPU_Type; /* Floating-Point Context Control Register */ #define FPU_FPCCR_ASPEN_Pos 31 /*!< FPCCR: ASPEN bit Position */ #define FPU_FPCCR_ASPEN_Msk (1UL << FPU_FPCCR_ASPEN_Pos) /*!< FPCCR: ASPEN bit Mask */ #define FPU_FPCCR_LSPEN_Pos 30 /*!< FPCCR: LSPEN Position */ #define FPU_FPCCR_LSPEN_Msk (1UL << FPU_FPCCR_LSPEN_Pos) /*!< FPCCR: LSPEN bit Mask */ #define FPU_FPCCR_MONRDY_Pos 8 /*!< FPCCR: MONRDY Position */ #define FPU_FPCCR_MONRDY_Msk (1UL << FPU_FPCCR_MONRDY_Pos) /*!< FPCCR: MONRDY bit Mask */ #define FPU_FPCCR_BFRDY_Pos 6 /*!< FPCCR: BFRDY Position */ #define FPU_FPCCR_BFRDY_Msk (1UL << FPU_FPCCR_BFRDY_Pos) /*!< FPCCR: BFRDY bit Mask */ #define FPU_FPCCR_MMRDY_Pos 5 /*!< FPCCR: MMRDY Position */ #define FPU_FPCCR_MMRDY_Msk (1UL << FPU_FPCCR_MMRDY_Pos) /*!< FPCCR: MMRDY bit Mask */ #define FPU_FPCCR_HFRDY_Pos 4 /*!< FPCCR: HFRDY Position */ #define FPU_FPCCR_HFRDY_Msk (1UL << FPU_FPCCR_HFRDY_Pos) /*!< FPCCR: HFRDY bit Mask */ #define FPU_FPCCR_THREAD_Pos 3 /*!< FPCCR: processor mode bit Position */ #define FPU_FPCCR_THREAD_Msk (1UL << FPU_FPCCR_THREAD_Pos) /*!< FPCCR: processor mode active bit Mask */ #define FPU_FPCCR_USER_Pos 1 /*!< FPCCR: privilege level bit Position */ #define FPU_FPCCR_USER_Msk (1UL << FPU_FPCCR_USER_Pos) /*!< FPCCR: privilege level bit Mask */ #define FPU_FPCCR_LSPACT_Pos 0 /*!< FPCCR: Lazy state preservation active bit Position */ #define FPU_FPCCR_LSPACT_Msk (1UL /*<< FPU_FPCCR_LSPACT_Pos*/) /*!< FPCCR: Lazy state preservation active bit Mask */ /* Floating-Point Context Address Register */ #define FPU_FPCAR_ADDRESS_Pos 3 /*!< FPCAR: ADDRESS bit Position */ #define FPU_FPCAR_ADDRESS_Msk (0x1FFFFFFFUL << FPU_FPCAR_ADDRESS_Pos) /*!< FPCAR: ADDRESS bit Mask */ /* Floating-Point Default Status Control Register */ #define FPU_FPDSCR_AHP_Pos 26 /*!< FPDSCR: AHP bit Position */ #define FPU_FPDSCR_AHP_Msk (1UL << FPU_FPDSCR_AHP_Pos) /*!< FPDSCR: AHP bit Mask */ #define FPU_FPDSCR_DN_Pos 25 /*!< FPDSCR: DN bit Position */ #define FPU_FPDSCR_DN_Msk (1UL << FPU_FPDSCR_DN_Pos) /*!< FPDSCR: DN bit Mask */ #define FPU_FPDSCR_FZ_Pos 24 /*!< FPDSCR: FZ bit Position */ #define FPU_FPDSCR_FZ_Msk (1UL << FPU_FPDSCR_FZ_Pos) /*!< FPDSCR: FZ bit Mask */ #define FPU_FPDSCR_RMode_Pos 22 /*!< FPDSCR: RMode bit Position */ #define FPU_FPDSCR_RMode_Msk (3UL << FPU_FPDSCR_RMode_Pos) /*!< FPDSCR: RMode bit Mask */ /* Media and FP Feature Register 0 */ #define FPU_MVFR0_FP_rounding_modes_Pos 28 /*!< MVFR0: FP rounding modes bits Position */ #define FPU_MVFR0_FP_rounding_modes_Msk (0xFUL << FPU_MVFR0_FP_rounding_modes_Pos) /*!< MVFR0: FP rounding modes bits Mask */ #define FPU_MVFR0_Short_vectors_Pos 24 /*!< MVFR0: Short vectors bits Position */ #define FPU_MVFR0_Short_vectors_Msk (0xFUL << FPU_MVFR0_Short_vectors_Pos) /*!< MVFR0: Short vectors bits Mask */ #define FPU_MVFR0_Square_root_Pos 20 /*!< MVFR0: Square root bits Position */ #define FPU_MVFR0_Square_root_Msk (0xFUL << FPU_MVFR0_Square_root_Pos) /*!< MVFR0: Square root bits Mask */ #define FPU_MVFR0_Divide_Pos 16 /*!< MVFR0: Divide bits Position */ #define FPU_MVFR0_Divide_Msk (0xFUL << FPU_MVFR0_Divide_Pos) /*!< MVFR0: Divide bits Mask */ #define FPU_MVFR0_FP_excep_trapping_Pos 12 /*!< MVFR0: FP exception trapping bits Position */ #define FPU_MVFR0_FP_excep_trapping_Msk (0xFUL << FPU_MVFR0_FP_excep_trapping_Pos) /*!< MVFR0: FP exception trapping bits Mask */ #define FPU_MVFR0_Double_precision_Pos 8 /*!< MVFR0: Double-precision bits Position */ #define FPU_MVFR0_Double_precision_Msk (0xFUL << FPU_MVFR0_Double_precision_Pos) /*!< MVFR0: Double-precision bits Mask */ #define FPU_MVFR0_Single_precision_Pos 4 /*!< MVFR0: Single-precision bits Position */ #define FPU_MVFR0_Single_precision_Msk (0xFUL << FPU_MVFR0_Single_precision_Pos) /*!< MVFR0: Single-precision bits Mask */ #define FPU_MVFR0_A_SIMD_registers_Pos 0 /*!< MVFR0: A_SIMD registers bits Position */ #define FPU_MVFR0_A_SIMD_registers_Msk (0xFUL /*<< FPU_MVFR0_A_SIMD_registers_Pos*/) /*!< MVFR0: A_SIMD registers bits Mask */ /* Media and FP Feature Register 1 */ #define FPU_MVFR1_FP_fused_MAC_Pos 28 /*!< MVFR1: FP fused MAC bits Position */ #define FPU_MVFR1_FP_fused_MAC_Msk (0xFUL << FPU_MVFR1_FP_fused_MAC_Pos) /*!< MVFR1: FP fused MAC bits Mask */ #define FPU_MVFR1_FP_HPFP_Pos 24 /*!< MVFR1: FP HPFP bits Position */ #define FPU_MVFR1_FP_HPFP_Msk (0xFUL << FPU_MVFR1_FP_HPFP_Pos) /*!< MVFR1: FP HPFP bits Mask */ #define FPU_MVFR1_D_NaN_mode_Pos 4 /*!< MVFR1: D_NaN mode bits Position */ #define FPU_MVFR1_D_NaN_mode_Msk (0xFUL << FPU_MVFR1_D_NaN_mode_Pos) /*!< MVFR1: D_NaN mode bits Mask */ #define FPU_MVFR1_FtZ_mode_Pos 0 /*!< MVFR1: FtZ mode bits Position */ #define FPU_MVFR1_FtZ_mode_Msk (0xFUL /*<< FPU_MVFR1_FtZ_mode_Pos*/) /*!< MVFR1: FtZ mode bits Mask */ /* Media and FP Feature Register 2 */ /*@} end of group CMSIS_FPU */ #endif /** \ingroup CMSIS_core_register \defgroup CMSIS_CoreDebug Core Debug Registers (CoreDebug) \brief Type definitions for the Core Debug Registers @{ */ /** \brief Structure type to access the Core Debug Register (CoreDebug). */ typedef struct { __IO uint32_t DHCSR; /*!< Offset: 0x000 (R/W) Debug Halting Control and Status Register */ __O uint32_t DCRSR; /*!< Offset: 0x004 ( /W) Debug Core Register Selector Register */ __IO uint32_t DCRDR; /*!< Offset: 0x008 (R/W) Debug Core Register Data Register */ __IO uint32_t DEMCR; /*!< Offset: 0x00C (R/W) Debug Exception and Monitor Control Register */ } CoreDebug_Type; /* Debug Halting Control and Status Register */ #define CoreDebug_DHCSR_DBGKEY_Pos 16 /*!< CoreDebug DHCSR: DBGKEY Position */ #define CoreDebug_DHCSR_DBGKEY_Msk (0xFFFFUL << CoreDebug_DHCSR_DBGKEY_Pos) /*!< CoreDebug DHCSR: DBGKEY Mask */ #define CoreDebug_DHCSR_S_RESET_ST_Pos 25 /*!< CoreDebug DHCSR: S_RESET_ST Position */ #define CoreDebug_DHCSR_S_RESET_ST_Msk (1UL << CoreDebug_DHCSR_S_RESET_ST_Pos) /*!< CoreDebug DHCSR: S_RESET_ST Mask */ #define CoreDebug_DHCSR_S_RETIRE_ST_Pos 24 /*!< CoreDebug DHCSR: S_RETIRE_ST Position */ #define CoreDebug_DHCSR_S_RETIRE_ST_Msk (1UL << CoreDebug_DHCSR_S_RETIRE_ST_Pos) /*!< CoreDebug DHCSR: S_RETIRE_ST Mask */ #define CoreDebug_DHCSR_S_LOCKUP_Pos 19 /*!< CoreDebug DHCSR: S_LOCKUP Position */ #define CoreDebug_DHCSR_S_LOCKUP_Msk (1UL << CoreDebug_DHCSR_S_LOCKUP_Pos) /*!< CoreDebug DHCSR: S_LOCKUP Mask */ #define CoreDebug_DHCSR_S_SLEEP_Pos 18 /*!< CoreDebug DHCSR: S_SLEEP Position */ #define CoreDebug_DHCSR_S_SLEEP_Msk (1UL << CoreDebug_DHCSR_S_SLEEP_Pos) /*!< CoreDebug DHCSR: S_SLEEP Mask */ #define CoreDebug_DHCSR_S_HALT_Pos 17 /*!< CoreDebug DHCSR: S_HALT Position */ #define CoreDebug_DHCSR_S_HALT_Msk (1UL << CoreDebug_DHCSR_S_HALT_Pos) /*!< CoreDebug DHCSR: S_HALT Mask */ #define CoreDebug_DHCSR_S_REGRDY_Pos 16 /*!< CoreDebug DHCSR: S_REGRDY Position */ #define CoreDebug_DHCSR_S_REGRDY_Msk (1UL << CoreDebug_DHCSR_S_REGRDY_Pos) /*!< CoreDebug DHCSR: S_REGRDY Mask */ #define CoreDebug_DHCSR_C_SNAPSTALL_Pos 5 /*!< CoreDebug DHCSR: C_SNAPSTALL Position */ #define CoreDebug_DHCSR_C_SNAPSTALL_Msk (1UL << CoreDebug_DHCSR_C_SNAPSTALL_Pos) /*!< CoreDebug DHCSR: C_SNAPSTALL Mask */ #define CoreDebug_DHCSR_C_MASKINTS_Pos 3 /*!< CoreDebug DHCSR: C_MASKINTS Position */ #define CoreDebug_DHCSR_C_MASKINTS_Msk (1UL << CoreDebug_DHCSR_C_MASKINTS_Pos) /*!< CoreDebug DHCSR: C_MASKINTS Mask */ #define CoreDebug_DHCSR_C_STEP_Pos 2 /*!< CoreDebug DHCSR: C_STEP Position */ #define CoreDebug_DHCSR_C_STEP_Msk (1UL << CoreDebug_DHCSR_C_STEP_Pos) /*!< CoreDebug DHCSR: C_STEP Mask */ #define CoreDebug_DHCSR_C_HALT_Pos 1 /*!< CoreDebug DHCSR: C_HALT Position */ #define CoreDebug_DHCSR_C_HALT_Msk (1UL << CoreDebug_DHCSR_C_HALT_Pos) /*!< CoreDebug DHCSR: C_HALT Mask */ #define CoreDebug_DHCSR_C_DEBUGEN_Pos 0 /*!< CoreDebug DHCSR: C_DEBUGEN Position */ #define CoreDebug_DHCSR_C_DEBUGEN_Msk (1UL /*<< CoreDebug_DHCSR_C_DEBUGEN_Pos*/) /*!< CoreDebug DHCSR: C_DEBUGEN Mask */ /* Debug Core Register Selector Register */ #define CoreDebug_DCRSR_REGWnR_Pos 16 /*!< CoreDebug DCRSR: REGWnR Position */ #define CoreDebug_DCRSR_REGWnR_Msk (1UL << CoreDebug_DCRSR_REGWnR_Pos) /*!< CoreDebug DCRSR: REGWnR Mask */ #define CoreDebug_DCRSR_REGSEL_Pos 0 /*!< CoreDebug DCRSR: REGSEL Position */ #define CoreDebug_DCRSR_REGSEL_Msk (0x1FUL /*<< CoreDebug_DCRSR_REGSEL_Pos*/) /*!< CoreDebug DCRSR: REGSEL Mask */ /* Debug Exception and Monitor Control Register */ #define CoreDebug_DEMCR_TRCENA_Pos 24 /*!< CoreDebug DEMCR: TRCENA Position */ #define CoreDebug_DEMCR_TRCENA_Msk (1UL << CoreDebug_DEMCR_TRCENA_Pos) /*!< CoreDebug DEMCR: TRCENA Mask */ #define CoreDebug_DEMCR_MON_REQ_Pos 19 /*!< CoreDebug DEMCR: MON_REQ Position */ #define CoreDebug_DEMCR_MON_REQ_Msk (1UL << CoreDebug_DEMCR_MON_REQ_Pos) /*!< CoreDebug DEMCR: MON_REQ Mask */ #define CoreDebug_DEMCR_MON_STEP_Pos 18 /*!< CoreDebug DEMCR: MON_STEP Position */ #define CoreDebug_DEMCR_MON_STEP_Msk (1UL << CoreDebug_DEMCR_MON_STEP_Pos) /*!< CoreDebug DEMCR: MON_STEP Mask */ #define CoreDebug_DEMCR_MON_PEND_Pos 17 /*!< CoreDebug DEMCR: MON_PEND Position */ #define CoreDebug_DEMCR_MON_PEND_Msk (1UL << CoreDebug_DEMCR_MON_PEND_Pos) /*!< CoreDebug DEMCR: MON_PEND Mask */ #define CoreDebug_DEMCR_MON_EN_Pos 16 /*!< CoreDebug DEMCR: MON_EN Position */ #define CoreDebug_DEMCR_MON_EN_Msk (1UL << CoreDebug_DEMCR_MON_EN_Pos) /*!< CoreDebug DEMCR: MON_EN Mask */ #define CoreDebug_DEMCR_VC_HARDERR_Pos 10 /*!< CoreDebug DEMCR: VC_HARDERR Position */ #define CoreDebug_DEMCR_VC_HARDERR_Msk (1UL << CoreDebug_DEMCR_VC_HARDERR_Pos) /*!< CoreDebug DEMCR: VC_HARDERR Mask */ #define CoreDebug_DEMCR_VC_INTERR_Pos 9 /*!< CoreDebug DEMCR: VC_INTERR Position */ #define CoreDebug_DEMCR_VC_INTERR_Msk (1UL << CoreDebug_DEMCR_VC_INTERR_Pos) /*!< CoreDebug DEMCR: VC_INTERR Mask */ #define CoreDebug_DEMCR_VC_BUSERR_Pos 8 /*!< CoreDebug DEMCR: VC_BUSERR Position */ #define CoreDebug_DEMCR_VC_BUSERR_Msk (1UL << CoreDebug_DEMCR_VC_BUSERR_Pos) /*!< CoreDebug DEMCR: VC_BUSERR Mask */ #define CoreDebug_DEMCR_VC_STATERR_Pos 7 /*!< CoreDebug DEMCR: VC_STATERR Position */ #define CoreDebug_DEMCR_VC_STATERR_Msk (1UL << CoreDebug_DEMCR_VC_STATERR_Pos) /*!< CoreDebug DEMCR: VC_STATERR Mask */ #define CoreDebug_DEMCR_VC_CHKERR_Pos 6 /*!< CoreDebug DEMCR: VC_CHKERR Position */ #define CoreDebug_DEMCR_VC_CHKERR_Msk (1UL << CoreDebug_DEMCR_VC_CHKERR_Pos) /*!< CoreDebug DEMCR: VC_CHKERR Mask */ #define CoreDebug_DEMCR_VC_NOCPERR_Pos 5 /*!< CoreDebug DEMCR: VC_NOCPERR Position */ #define CoreDebug_DEMCR_VC_NOCPERR_Msk (1UL << CoreDebug_DEMCR_VC_NOCPERR_Pos) /*!< CoreDebug DEMCR: VC_NOCPERR Mask */ #define CoreDebug_DEMCR_VC_MMERR_Pos 4 /*!< CoreDebug DEMCR: VC_MMERR Position */ #define CoreDebug_DEMCR_VC_MMERR_Msk (1UL << CoreDebug_DEMCR_VC_MMERR_Pos) /*!< CoreDebug DEMCR: VC_MMERR Mask */ #define CoreDebug_DEMCR_VC_CORERESET_Pos 0 /*!< CoreDebug DEMCR: VC_CORERESET Position */ #define CoreDebug_DEMCR_VC_CORERESET_Msk (1UL /*<< CoreDebug_DEMCR_VC_CORERESET_Pos*/) /*!< CoreDebug DEMCR: VC_CORERESET Mask */ /*@} end of group CMSIS_CoreDebug */ /** \ingroup CMSIS_core_register \defgroup CMSIS_core_base Core Definitions \brief Definitions for base addresses, unions, and structures. @{ */ /* Memory mapping of Cortex-M4 Hardware */ #define SCS_BASE (0xE000E000UL) /*!< System Control Space Base Address */ #define ITM_BASE (0xE0000000UL) /*!< ITM Base Address */ #define DWT_BASE (0xE0001000UL) /*!< DWT Base Address */ #define TPI_BASE (0xE0040000UL) /*!< TPI Base Address */ #define CoreDebug_BASE (0xE000EDF0UL) /*!< Core Debug Base Address */ #define SysTick_BASE (SCS_BASE + 0x0010UL) /*!< SysTick Base Address */ #define NVIC_BASE (SCS_BASE + 0x0100UL) /*!< NVIC Base Address */ #define SCB_BASE (SCS_BASE + 0x0D00UL) /*!< System Control Block Base Address */ #define SCnSCB ((SCnSCB_Type *) SCS_BASE ) /*!< System control Register not in SCB */ #define SCB ((SCB_Type *) SCB_BASE ) /*!< SCB configuration struct */ #define SysTick ((SysTick_Type *) SysTick_BASE ) /*!< SysTick configuration struct */ #define NVIC ((NVIC_Type *) NVIC_BASE ) /*!< NVIC configuration struct */ #define ITM ((ITM_Type *) ITM_BASE ) /*!< ITM configuration struct */ #define DWT ((DWT_Type *) DWT_BASE ) /*!< DWT configuration struct */ #define TPI ((TPI_Type *) TPI_BASE ) /*!< TPI configuration struct */ #define CoreDebug ((CoreDebug_Type *) CoreDebug_BASE) /*!< Core Debug configuration struct */ #if (__MPU_PRESENT == 1) #define MPU_BASE (SCS_BASE + 0x0D90UL) /*!< Memory Protection Unit */ #define MPU ((MPU_Type *) MPU_BASE ) /*!< Memory Protection Unit */ #endif #if (__FPU_PRESENT == 1) #define FPU_BASE (SCS_BASE + 0x0F30UL) /*!< Floating Point Unit */ #define FPU ((FPU_Type *) FPU_BASE ) /*!< Floating Point Unit */ #endif /*@} */ /******************************************************************************* * Hardware Abstraction Layer Core Function Interface contains: - Core NVIC Functions - Core SysTick Functions - Core Debug Functions - Core Register Access Functions ******************************************************************************/ /** \defgroup CMSIS_Core_FunctionInterface Functions and Instructions Reference */ /* ########################## NVIC functions #################################### */ /** \ingroup CMSIS_Core_FunctionInterface \defgroup CMSIS_Core_NVICFunctions NVIC Functions \brief Functions that manage interrupts and exceptions via the NVIC. @{ */ /** \brief Set Priority Grouping The function sets the priority grouping field using the required unlock sequence. The parameter PriorityGroup is assigned to the field SCB->AIRCR [10:8] PRIGROUP field. Only values from 0..7 are used. In case of a conflict between priority grouping and available priority bits (__NVIC_PRIO_BITS), the smallest possible priority group is set. \param [in] PriorityGroup Priority grouping field. */ __STATIC_INLINE void NVIC_SetPriorityGrouping(uint32_t PriorityGroup) { uint32_t reg_value; uint32_t PriorityGroupTmp = (PriorityGroup & (uint32_t)0x07UL); /* only values 0..7 are used */ reg_value = SCB->AIRCR; /* read old register configuration */ reg_value &= ~((uint32_t)(SCB_AIRCR_VECTKEY_Msk | SCB_AIRCR_PRIGROUP_Msk)); /* clear bits to change */ reg_value = (reg_value | ((uint32_t)0x5FAUL << SCB_AIRCR_VECTKEY_Pos) | (PriorityGroupTmp << 8) ); /* Insert write key and priorty group */ SCB->AIRCR = reg_value; } /** \brief Get Priority Grouping The function reads the priority grouping field from the NVIC Interrupt Controller. \return Priority grouping field (SCB->AIRCR [10:8] PRIGROUP field). */ __STATIC_INLINE uint32_t NVIC_GetPriorityGrouping(void) { return ((uint32_t)((SCB->AIRCR & SCB_AIRCR_PRIGROUP_Msk) >> SCB_AIRCR_PRIGROUP_Pos)); } /** \brief Enable External Interrupt The function enables a device-specific interrupt in the NVIC interrupt controller. \param [in] IRQn External interrupt number. Value cannot be negative. */ __STATIC_INLINE void NVIC_EnableIRQ(IRQn_Type IRQn) { NVIC->ISER[(((uint32_t)(int32_t)IRQn) >> 5UL)] = (uint32_t)(1UL << (((uint32_t)(int32_t)IRQn) & 0x1FUL)); } /** \brief Disable External Interrupt The function disables a device-specific interrupt in the NVIC interrupt controller. \param [in] IRQn External interrupt number. Value cannot be negative. */ __STATIC_INLINE void NVIC_DisableIRQ(IRQn_Type IRQn) { NVIC->ICER[(((uint32_t)(int32_t)IRQn) >> 5UL)] = (uint32_t)(1UL << (((uint32_t)(int32_t)IRQn) & 0x1FUL)); } /** \brief Get Pending Interrupt The function reads the pending register in the NVIC and returns the pending bit for the specified interrupt. \param [in] IRQn Interrupt number. \return 0 Interrupt status is not pending. \return 1 Interrupt status is pending. */ __STATIC_INLINE uint32_t NVIC_GetPendingIRQ(IRQn_Type IRQn) { return((uint32_t)(((NVIC->ISPR[(((uint32_t)(int32_t)IRQn) >> 5UL)] & (1UL << (((uint32_t)(int32_t)IRQn) & 0x1FUL))) != 0UL) ? 1UL : 0UL)); } /** \brief Set Pending Interrupt The function sets the pending bit of an external interrupt. \param [in] IRQn Interrupt number. Value cannot be negative. */ __STATIC_INLINE void NVIC_SetPendingIRQ(IRQn_Type IRQn) { NVIC->ISPR[(((uint32_t)(int32_t)IRQn) >> 5UL)] = (uint32_t)(1UL << (((uint32_t)(int32_t)IRQn) & 0x1FUL)); } /** \brief Clear Pending Interrupt The function clears the pending bit of an external interrupt. \param [in] IRQn External interrupt number. Value cannot be negative. */ __STATIC_INLINE void NVIC_ClearPendingIRQ(IRQn_Type IRQn) { NVIC->ICPR[(((uint32_t)(int32_t)IRQn) >> 5UL)] = (uint32_t)(1UL << (((uint32_t)(int32_t)IRQn) & 0x1FUL)); } /** \brief Get Active Interrupt The function reads the active register in NVIC and returns the active bit. \param [in] IRQn Interrupt number. \return 0 Interrupt status is not active. \return 1 Interrupt status is active. */ __STATIC_INLINE uint32_t NVIC_GetActive(IRQn_Type IRQn) { return((uint32_t)(((NVIC->IABR[(((uint32_t)(int32_t)IRQn) >> 5UL)] & (1UL << (((uint32_t)(int32_t)IRQn) & 0x1FUL))) != 0UL) ? 1UL : 0UL)); } /** \brief Set Interrupt Priority The function sets the priority of an interrupt. \note The priority cannot be set for every core interrupt. \param [in] IRQn Interrupt number. \param [in] priority Priority to set. */ __STATIC_INLINE void NVIC_SetPriority(IRQn_Type IRQn, uint32_t priority) { if((int32_t)IRQn < 0) { SCB->SHPR[(((uint32_t)(int32_t)IRQn) & 0xFUL)-4UL] = (uint8_t)((priority << (8 - __NVIC_PRIO_BITS)) & (uint32_t)0xFFUL); } else { NVIC->IP[((uint32_t)(int32_t)IRQn)] = (uint8_t)((priority << (8 - __NVIC_PRIO_BITS)) & (uint32_t)0xFFUL); } } /** \brief Get Interrupt Priority The function reads the priority of an interrupt. The interrupt number can be positive to specify an external (device specific) interrupt, or negative to specify an internal (core) interrupt. \param [in] IRQn Interrupt number. \return Interrupt Priority. Value is aligned automatically to the implemented priority bits of the microcontroller. */ __STATIC_INLINE uint32_t NVIC_GetPriority(IRQn_Type IRQn) { if((int32_t)IRQn < 0) { return(((uint32_t)SCB->SHPR[(((uint32_t)(int32_t)IRQn) & 0xFUL)-4UL] >> (8 - __NVIC_PRIO_BITS))); } else { return(((uint32_t)NVIC->IP[((uint32_t)(int32_t)IRQn)] >> (8 - __NVIC_PRIO_BITS))); } } /** \brief Encode Priority The function encodes the priority for an interrupt with the given priority group, preemptive priority value, and subpriority value. In case of a conflict between priority grouping and available priority bits (__NVIC_PRIO_BITS), the smallest possible priority group is set. \param [in] PriorityGroup Used priority group. \param [in] PreemptPriority Preemptive priority value (starting from 0). \param [in] SubPriority Subpriority value (starting from 0). \return Encoded priority. Value can be used in the function \ref NVIC_SetPriority(). */ __STATIC_INLINE uint32_t NVIC_EncodePriority (uint32_t PriorityGroup, uint32_t PreemptPriority, uint32_t SubPriority) { uint32_t PriorityGroupTmp = (PriorityGroup & (uint32_t)0x07UL); /* only values 0..7 are used */ uint32_t PreemptPriorityBits; uint32_t SubPriorityBits; PreemptPriorityBits = ((7UL - PriorityGroupTmp) > (uint32_t)(__NVIC_PRIO_BITS)) ? (uint32_t)(__NVIC_PRIO_BITS) : (uint32_t)(7UL - PriorityGroupTmp); SubPriorityBits = ((PriorityGroupTmp + (uint32_t)(__NVIC_PRIO_BITS)) < (uint32_t)7UL) ? (uint32_t)0UL : (uint32_t)((PriorityGroupTmp - 7UL) + (uint32_t)(__NVIC_PRIO_BITS)); return ( ((PreemptPriority & (uint32_t)((1UL << (PreemptPriorityBits)) - 1UL)) << SubPriorityBits) | ((SubPriority & (uint32_t)((1UL << (SubPriorityBits )) - 1UL))) ); } /** \brief Decode Priority The function decodes an interrupt priority value with a given priority group to preemptive priority value and subpriority value. In case of a conflict between priority grouping and available priority bits (__NVIC_PRIO_BITS) the smallest possible priority group is set. \param [in] Priority Priority value, which can be retrieved with the function \ref NVIC_GetPriority(). \param [in] PriorityGroup Used priority group. \param [out] pPreemptPriority Preemptive priority value (starting from 0). \param [out] pSubPriority Subpriority value (starting from 0). */ __STATIC_INLINE void NVIC_DecodePriority (uint32_t Priority, uint32_t PriorityGroup, uint32_t* pPreemptPriority, uint32_t* pSubPriority) { uint32_t PriorityGroupTmp = (PriorityGroup & (uint32_t)0x07UL); /* only values 0..7 are used */ uint32_t PreemptPriorityBits; uint32_t SubPriorityBits; PreemptPriorityBits = ((7UL - PriorityGroupTmp) > (uint32_t)(__NVIC_PRIO_BITS)) ? (uint32_t)(__NVIC_PRIO_BITS) : (uint32_t)(7UL - PriorityGroupTmp); SubPriorityBits = ((PriorityGroupTmp + (uint32_t)(__NVIC_PRIO_BITS)) < (uint32_t)7UL) ? (uint32_t)0UL : (uint32_t)((PriorityGroupTmp - 7UL) + (uint32_t)(__NVIC_PRIO_BITS)); *pPreemptPriority = (Priority >> SubPriorityBits) & (uint32_t)((1UL << (PreemptPriorityBits)) - 1UL); *pSubPriority = (Priority ) & (uint32_t)((1UL << (SubPriorityBits )) - 1UL); } /** \brief System Reset The function initiates a system reset request to reset the MCU. */ __STATIC_INLINE void NVIC_SystemReset(void) { __DSB(); /* Ensure all outstanding memory accesses included buffered write are completed before reset */ SCB->AIRCR = (uint32_t)((0x5FAUL << SCB_AIRCR_VECTKEY_Pos) | (SCB->AIRCR & SCB_AIRCR_PRIGROUP_Msk) | SCB_AIRCR_SYSRESETREQ_Msk ); /* Keep priority group unchanged */ __DSB(); /* Ensure completion of memory access */ while(1) { __NOP(); } /* wait until reset */ } /*@} end of CMSIS_Core_NVICFunctions */ /* ########################## FPU functions #################################### */ /** \ingroup CMSIS_Core_FunctionInterface \defgroup CMSIS_Core_FpuFunctions FPU Functions \brief Function that provides FPU type. @{ */ /** \fn uint32_t SCB_GetFPUType(void) \brief get FPU type \returns - \b 0: No FPU - \b 1: Single precision FPU - \b 2: Double + Single precision FPU */ __STATIC_INLINE uint32_t SCB_GetFPUType(void) { uint32_t mvfr0; mvfr0 = SCB->MVFR0; if ((mvfr0 & 0x00000FF0UL) == 0x220UL) { return 2UL; // Double + Single precision FPU } else if ((mvfr0 & 0x00000FF0UL) == 0x020UL) { return 1UL; // Single precision FPU } else { return 0UL; // No FPU } } /*@} end of CMSIS_Core_FpuFunctions */ /* ########################## Cache functions #################################### */ /** \ingroup CMSIS_Core_FunctionInterface \defgroup CMSIS_Core_CacheFunctions Cache Functions \brief Functions that configure Instruction and Data cache. @{ */ /* Cache Size ID Register Macros */ #define CCSIDR_WAYS(x) (((x) & SCB_CCSIDR_ASSOCIATIVITY_Msk) >> SCB_CCSIDR_ASSOCIATIVITY_Pos) #define CCSIDR_SETS(x) (((x) & SCB_CCSIDR_NUMSETS_Msk ) >> SCB_CCSIDR_NUMSETS_Pos ) #define CCSIDR_LSSHIFT(x) (((x) & SCB_CCSIDR_LINESIZE_Msk ) /*>> SCB_CCSIDR_LINESIZE_Pos*/ ) /** \brief Enable I-Cache The function turns on I-Cache */ __STATIC_INLINE void SCB_EnableICache (void) { #if (__ICACHE_PRESENT == 1) __DSB(); __ISB(); SCB->ICIALLU = 0UL; // invalidate I-Cache SCB->CCR |= (uint32_t)SCB_CCR_IC_Msk; // enable I-Cache __DSB(); __ISB(); #endif } /** \brief Disable I-Cache The function turns off I-Cache */ __STATIC_INLINE void SCB_DisableICache (void) { #if (__ICACHE_PRESENT == 1) __DSB(); __ISB(); SCB->CCR &= ~(uint32_t)SCB_CCR_IC_Msk; // disable I-Cache SCB->ICIALLU = 0UL; // invalidate I-Cache __DSB(); __ISB(); #endif } /** \brief Invalidate I-Cache The function invalidates I-Cache */ __STATIC_INLINE void SCB_InvalidateICache (void) { #if (__ICACHE_PRESENT == 1) __DSB(); __ISB(); SCB->ICIALLU = 0UL; __DSB(); __ISB(); #endif } /** \brief Enable D-Cache The function turns on D-Cache */ __STATIC_INLINE void SCB_EnableDCache (void) { #if (__DCACHE_PRESENT == 1) uint32_t ccsidr, sshift, wshift, sw; uint32_t sets, ways; SCB->CSSELR = (0UL << 1) | 0UL; // Level 1 data cache ccsidr = SCB->CCSIDR; sets = (uint32_t)(CCSIDR_SETS(ccsidr)); sshift = (uint32_t)(CCSIDR_LSSHIFT(ccsidr) + 4UL); ways = (uint32_t)(CCSIDR_WAYS(ccsidr)); wshift = (uint32_t)((uint32_t)__CLZ(ways) & 0x1FUL); __DSB(); do { // invalidate D-Cache uint32_t tmpways = ways; do { sw = ((tmpways << wshift) | (sets << sshift)); SCB->DCISW = sw; } while(tmpways--); } while(sets--); __DSB(); SCB->CCR |= (uint32_t)SCB_CCR_DC_Msk; // enable D-Cache __DSB(); __ISB(); #endif } /** \brief Disable D-Cache The function turns off D-Cache */ __STATIC_INLINE void SCB_DisableDCache (void) { #if (__DCACHE_PRESENT == 1) uint32_t ccsidr, sshift, wshift, sw; uint32_t sets, ways; SCB->CSSELR = (0UL << 1) | 0UL; // Level 1 data cache ccsidr = SCB->CCSIDR; sets = (uint32_t)(CCSIDR_SETS(ccsidr)); sshift = (uint32_t)(CCSIDR_LSSHIFT(ccsidr) + 4UL); ways = (uint32_t)(CCSIDR_WAYS(ccsidr)); wshift = (uint32_t)((uint32_t)__CLZ(ways) & 0x1FUL); __DSB(); SCB->CCR &= ~(uint32_t)SCB_CCR_DC_Msk; // disable D-Cache do { // clean & invalidate D-Cache uint32_t tmpways = ways; do { sw = ((tmpways << wshift) | (sets << sshift)); SCB->DCCISW = sw; } while(tmpways--); } while(sets--); __DSB(); __ISB(); #endif } /** \brief Invalidate D-Cache The function invalidates D-Cache */ __STATIC_INLINE void SCB_InvalidateDCache (void) { #if (__DCACHE_PRESENT == 1) uint32_t ccsidr, sshift, wshift, sw; uint32_t sets, ways; SCB->CSSELR = (0UL << 1) | 0UL; // Level 1 data cache ccsidr = SCB->CCSIDR; sets = (uint32_t)(CCSIDR_SETS(ccsidr)); sshift = (uint32_t)(CCSIDR_LSSHIFT(ccsidr) + 4UL); ways = (uint32_t)(CCSIDR_WAYS(ccsidr)); wshift = (uint32_t)((uint32_t)__CLZ(ways) & 0x1FUL); __DSB(); do { // invalidate D-Cache uint32_t tmpways = ways; do { sw = ((tmpways << wshift) | (sets << sshift)); SCB->DCISW = sw; } while(tmpways--); } while(sets--); __DSB(); __ISB(); #endif } /** \brief Clean D-Cache The function cleans D-Cache */ __STATIC_INLINE void SCB_CleanDCache (void) { #if (__DCACHE_PRESENT == 1) uint32_t ccsidr, sshift, wshift, sw; uint32_t sets, ways; SCB->CSSELR = (0UL << 1) | 0UL; // Level 1 data cache ccsidr = SCB->CCSIDR; sets = (uint32_t)(CCSIDR_SETS(ccsidr)); sshift = (uint32_t)(CCSIDR_LSSHIFT(ccsidr) + 4UL); ways = (uint32_t)(CCSIDR_WAYS(ccsidr)); wshift = (uint32_t)((uint32_t)__CLZ(ways) & 0x1FUL); __DSB(); do { // clean D-Cache uint32_t tmpways = ways; do { sw = ((tmpways << wshift) | (sets << sshift)); SCB->DCCSW = sw; } while(tmpways--); } while(sets--); __DSB(); __ISB(); #endif } /** \brief Clean & Invalidate D-Cache The function cleans and Invalidates D-Cache */ __STATIC_INLINE void SCB_CleanInvalidateDCache (void) { #if (__DCACHE_PRESENT == 1) uint32_t ccsidr, sshift, wshift, sw; uint32_t sets, ways; SCB->CSSELR = (0UL << 1) | 0UL; // Level 1 data cache ccsidr = SCB->CCSIDR; sets = (uint32_t)(CCSIDR_SETS(ccsidr)); sshift = (uint32_t)(CCSIDR_LSSHIFT(ccsidr) + 4UL); ways = (uint32_t)(CCSIDR_WAYS(ccsidr)); wshift = (uint32_t)((uint32_t)__CLZ(ways) & 0x1FUL); __DSB(); do { // clean & invalidate D-Cache uint32_t tmpways = ways; do { sw = ((tmpways << wshift) | (sets << sshift)); SCB->DCCISW = sw; } while(tmpways--); } while(sets--); __DSB(); __ISB(); #endif } /** \fn void SCB_InvalidateDCache_by_Addr(volatile uint32_t *addr, int32_t dsize) \brief D-Cache Invalidate by address \param[in] addr address (aligned to 32-byte boundary) \param[in] dsize size of memory block (in number of bytes) */ __STATIC_INLINE void SCB_InvalidateDCache_by_Addr (uint32_t *addr, int32_t dsize) { #if (__DCACHE_PRESENT == 1) int32_t op_size = dsize; uint32_t op_addr = (uint32_t)addr; uint32_t linesize = 32UL; // in Cortex-M7 size of cache line is fixed to 8 words (32 bytes) __DSB(); while (op_size > 0) { SCB->DCIMVAC = op_addr; op_addr += linesize; op_size -= (int32_t)linesize; } __DSB(); __ISB(); #endif } /** \fn void SCB_CleanDCache_by_Addr(volatile uint32_t *addr, int32_t dsize) \brief D-Cache Clean by address \param[in] addr address (aligned to 32-byte boundary) \param[in] dsize size of memory block (in number of bytes) */ __STATIC_INLINE void SCB_CleanDCache_by_Addr (uint32_t *addr, int32_t dsize) { #if (__DCACHE_PRESENT == 1) int32_t op_size = dsize; uint32_t op_addr = (uint32_t) addr; uint32_t linesize = 32UL; // in Cortex-M7 size of cache line is fixed to 8 words (32 bytes) __DSB(); while (op_size > 0) { SCB->DCCMVAC = op_addr; op_addr += linesize; op_size -= (int32_t)linesize; } __DSB(); __ISB(); #endif } /** \fn void SCB_CleanInvalidateDCache_by_Addr(volatile uint32_t *addr, int32_t dsize) \brief D-Cache Clean and Invalidate by address \param[in] addr address (aligned to 32-byte boundary) \param[in] dsize size of memory block (in number of bytes) */ __STATIC_INLINE void SCB_CleanInvalidateDCache_by_Addr (uint32_t *addr, int32_t dsize) { #if (__DCACHE_PRESENT == 1) int32_t op_size = dsize; uint32_t op_addr = (uint32_t) addr; uint32_t linesize = 32UL; // in Cortex-M7 size of cache line is fixed to 8 words (32 bytes) __DSB(); while (op_size > 0) { SCB->DCCIMVAC = op_addr; op_addr += linesize; op_size -= (int32_t)linesize; } __DSB(); __ISB(); #endif } /*@} end of CMSIS_Core_CacheFunctions */ /* ################################## SysTick function ############################################ */ /** \ingroup CMSIS_Core_FunctionInterface \defgroup CMSIS_Core_SysTickFunctions SysTick Functions \brief Functions that configure the System. @{ */ #if (__Vendor_SysTickConfig == 0) /** \brief System Tick Configuration The function initializes the System Timer and its interrupt, and starts the System Tick Timer. Counter is in free running mode to generate periodic interrupts. \param [in] ticks Number of ticks between two interrupts. \return 0 Function succeeded. \return 1 Function failed. \note When the variable __Vendor_SysTickConfig is set to 1, then the function SysTick_Config is not included. In this case, the file device.h must contain a vendor-specific implementation of this function. */ __STATIC_INLINE uint32_t SysTick_Config(uint32_t ticks) { if ((ticks - 1UL) > SysTick_LOAD_RELOAD_Msk) { return (1UL); } /* Reload value impossible */ SysTick->LOAD = (uint32_t)(ticks - 1UL); /* set reload register */ NVIC_SetPriority (SysTick_IRQn, (1UL << __NVIC_PRIO_BITS) - 1UL); /* set Priority for Systick Interrupt */ SysTick->VAL = 0UL; /* Load the SysTick Counter Value */ SysTick->CTRL = SysTick_CTRL_CLKSOURCE_Msk | SysTick_CTRL_TICKINT_Msk | SysTick_CTRL_ENABLE_Msk; /* Enable SysTick IRQ and SysTick Timer */ return (0UL); /* Function successful */ } #endif /*@} end of CMSIS_Core_SysTickFunctions */ /* ##################################### Debug In/Output function ########################################### */ /** \ingroup CMSIS_Core_FunctionInterface \defgroup CMSIS_core_DebugFunctions ITM Functions \brief Functions that access the ITM debug interface. @{ */ extern volatile int32_t ITM_RxBuffer; /*!< External variable to receive characters. */ #define ITM_RXBUFFER_EMPTY 0x5AA55AA5 /*!< Value identifying \ref ITM_RxBuffer is ready for next character. */ /** \brief ITM Send Character The function transmits a character via the ITM channel 0, and \li Just returns when no debugger is connected that has booked the output. \li Is blocking when a debugger is connected, but the previous character sent has not been transmitted. \param [in] ch Character to transmit. \returns Character to transmit. */ __STATIC_INLINE uint32_t ITM_SendChar (uint32_t ch) { if (((ITM->TCR & ITM_TCR_ITMENA_Msk) != 0UL) && /* ITM enabled */ ((ITM->TER & 1UL ) != 0UL) ) /* ITM Port #0 enabled */ { while (ITM->PORT[0].u32 == 0UL) { __NOP(); } ITM->PORT[0].u8 = (uint8_t)ch; } return (ch); } /** \brief ITM Receive Character The function inputs a character via the external variable \ref ITM_RxBuffer. \return Received character. \return -1 No character pending. */ __STATIC_INLINE int32_t ITM_ReceiveChar (void) { int32_t ch = -1; /* no character available */ if (ITM_RxBuffer != ITM_RXBUFFER_EMPTY) { ch = ITM_RxBuffer; ITM_RxBuffer = ITM_RXBUFFER_EMPTY; /* ready for next character */ } return (ch); } /** \brief ITM Check Character The function checks whether a character is pending for reading in the variable \ref ITM_RxBuffer. \return 0 No character available. \return 1 Character available. */ __STATIC_INLINE int32_t ITM_CheckChar (void) { if (ITM_RxBuffer == ITM_RXBUFFER_EMPTY) { return (0); /* no character available */ } else { return (1); /* character available */ } } /*@} end of CMSIS_core_DebugFunctions */ #ifdef __cplusplus } #endif #endif /* __CORE_CM7_H_DEPENDANT */ #endif /* __CMSIS_GENERIC */ ================================================ FILE: Zelig/mbed/TARGET_NUCLEO_F401RE/core_cmFunc.h ================================================ /**************************************************************************//** * @file core_cmFunc.h * @brief CMSIS Cortex-M Core Function Access Header File * @version V4.10 * @date 18. March 2015 * * @note * ******************************************************************************/ /* Copyright (c) 2009 - 2015 ARM LIMITED All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: - Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. - Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. - Neither the name of ARM 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 COPYRIGHT HOLDERS AND 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. ---------------------------------------------------------------------------*/ #ifndef __CORE_CMFUNC_H #define __CORE_CMFUNC_H /* ########################### Core Function Access ########################### */ /** \ingroup CMSIS_Core_FunctionInterface \defgroup CMSIS_Core_RegAccFunctions CMSIS Core Register Access Functions @{ */ #if defined ( __CC_ARM ) /*------------------RealView Compiler -----------------*/ /* ARM armcc specific functions */ #if (__ARMCC_VERSION < 400677) #error "Please use ARM Compiler Toolchain V4.0.677 or later!" #endif /* intrinsic void __enable_irq(); */ /* intrinsic void __disable_irq(); */ /** \brief Get Control Register This function returns the content of the Control Register. \return Control Register value */ __STATIC_INLINE uint32_t __get_CONTROL(void) { register uint32_t __regControl __ASM("control"); return(__regControl); } /** \brief Set Control Register This function writes the given value to the Control Register. \param [in] control Control Register value to set */ __STATIC_INLINE void __set_CONTROL(uint32_t control) { register uint32_t __regControl __ASM("control"); __regControl = control; } /** \brief Get IPSR Register This function returns the content of the IPSR Register. \return IPSR Register value */ __STATIC_INLINE uint32_t __get_IPSR(void) { register uint32_t __regIPSR __ASM("ipsr"); return(__regIPSR); } /** \brief Get APSR Register This function returns the content of the APSR Register. \return APSR Register value */ __STATIC_INLINE uint32_t __get_APSR(void) { register uint32_t __regAPSR __ASM("apsr"); return(__regAPSR); } /** \brief Get xPSR Register This function returns the content of the xPSR Register. \return xPSR Register value */ __STATIC_INLINE uint32_t __get_xPSR(void) { register uint32_t __regXPSR __ASM("xpsr"); return(__regXPSR); } /** \brief Get Process Stack Pointer This function returns the current value of the Process Stack Pointer (PSP). \return PSP Register value */ __STATIC_INLINE uint32_t __get_PSP(void) { register uint32_t __regProcessStackPointer __ASM("psp"); return(__regProcessStackPointer); } /** \brief Set Process Stack Pointer This function assigns the given value to the Process Stack Pointer (PSP). \param [in] topOfProcStack Process Stack Pointer value to set */ __STATIC_INLINE void __set_PSP(uint32_t topOfProcStack) { register uint32_t __regProcessStackPointer __ASM("psp"); __regProcessStackPointer = topOfProcStack; } /** \brief Get Main Stack Pointer This function returns the current value of the Main Stack Pointer (MSP). \return MSP Register value */ __STATIC_INLINE uint32_t __get_MSP(void) { register uint32_t __regMainStackPointer __ASM("msp"); return(__regMainStackPointer); } /** \brief Set Main Stack Pointer This function assigns the given value to the Main Stack Pointer (MSP). \param [in] topOfMainStack Main Stack Pointer value to set */ __STATIC_INLINE void __set_MSP(uint32_t topOfMainStack) { register uint32_t __regMainStackPointer __ASM("msp"); __regMainStackPointer = topOfMainStack; } /** \brief Get Priority Mask This function returns the current state of the priority mask bit from the Priority Mask Register. \return Priority Mask value */ __STATIC_INLINE uint32_t __get_PRIMASK(void) { register uint32_t __regPriMask __ASM("primask"); return(__regPriMask); } /** \brief Set Priority Mask This function assigns the given value to the Priority Mask Register. \param [in] priMask Priority Mask */ __STATIC_INLINE void __set_PRIMASK(uint32_t priMask) { register uint32_t __regPriMask __ASM("primask"); __regPriMask = (priMask); } #if (__CORTEX_M >= 0x03) || (__CORTEX_SC >= 300) /** \brief Enable FIQ This function enables FIQ interrupts by clearing the F-bit in the CPSR. Can only be executed in Privileged modes. */ #define __enable_fault_irq __enable_fiq /** \brief Disable FIQ This function disables FIQ interrupts by setting the F-bit in the CPSR. Can only be executed in Privileged modes. */ #define __disable_fault_irq __disable_fiq /** \brief Get Base Priority This function returns the current value of the Base Priority register. \return Base Priority register value */ __STATIC_INLINE uint32_t __get_BASEPRI(void) { register uint32_t __regBasePri __ASM("basepri"); return(__regBasePri); } /** \brief Set Base Priority This function assigns the given value to the Base Priority register. \param [in] basePri Base Priority value to set */ __STATIC_INLINE void __set_BASEPRI(uint32_t basePri) { register uint32_t __regBasePri __ASM("basepri"); __regBasePri = (basePri & 0xff); } /** \brief Set Base Priority with condition This function assigns the given value to the Base Priority register only if BASEPRI masking is disabled, or the new value increases the BASEPRI priority level. \param [in] basePri Base Priority value to set */ __STATIC_INLINE void __set_BASEPRI_MAX(uint32_t basePri) { register uint32_t __regBasePriMax __ASM("basepri_max"); __regBasePriMax = (basePri & 0xff); } /** \brief Get Fault Mask This function returns the current value of the Fault Mask register. \return Fault Mask register value */ __STATIC_INLINE uint32_t __get_FAULTMASK(void) { register uint32_t __regFaultMask __ASM("faultmask"); return(__regFaultMask); } /** \brief Set Fault Mask This function assigns the given value to the Fault Mask register. \param [in] faultMask Fault Mask value to set */ __STATIC_INLINE void __set_FAULTMASK(uint32_t faultMask) { register uint32_t __regFaultMask __ASM("faultmask"); __regFaultMask = (faultMask & (uint32_t)1); } #endif /* (__CORTEX_M >= 0x03) || (__CORTEX_SC >= 300) */ #if (__CORTEX_M == 0x04) || (__CORTEX_M == 0x07) /** \brief Get FPSCR This function returns the current value of the Floating Point Status/Control register. \return Floating Point Status/Control register value */ __STATIC_INLINE uint32_t __get_FPSCR(void) { #if (__FPU_PRESENT == 1) && (__FPU_USED == 1) register uint32_t __regfpscr __ASM("fpscr"); return(__regfpscr); #else return(0); #endif } /** \brief Set FPSCR This function assigns the given value to the Floating Point Status/Control register. \param [in] fpscr Floating Point Status/Control value to set */ __STATIC_INLINE void __set_FPSCR(uint32_t fpscr) { #if (__FPU_PRESENT == 1) && (__FPU_USED == 1) register uint32_t __regfpscr __ASM("fpscr"); __regfpscr = (fpscr); #endif } #endif /* (__CORTEX_M == 0x04) || (__CORTEX_M == 0x07) */ #elif defined ( __GNUC__ ) /*------------------ GNU Compiler ---------------------*/ /* GNU gcc specific functions */ /** \brief Enable IRQ Interrupts This function enables IRQ interrupts by clearing the I-bit in the CPSR. Can only be executed in Privileged modes. */ __attribute__( ( always_inline ) ) __STATIC_INLINE void __enable_irq(void) { __ASM volatile ("cpsie i" : : : "memory"); } /** \brief Disable IRQ Interrupts This function disables IRQ interrupts by setting the I-bit in the CPSR. Can only be executed in Privileged modes. */ __attribute__( ( always_inline ) ) __STATIC_INLINE void __disable_irq(void) { __ASM volatile ("cpsid i" : : : "memory"); } /** \brief Get Control Register This function returns the content of the Control Register. \return Control Register value */ __attribute__( ( always_inline ) ) __STATIC_INLINE uint32_t __get_CONTROL(void) { uint32_t result; __ASM volatile ("MRS %0, control" : "=r" (result) ); return(result); } /** \brief Set Control Register This function writes the given value to the Control Register. \param [in] control Control Register value to set */ __attribute__( ( always_inline ) ) __STATIC_INLINE void __set_CONTROL(uint32_t control) { __ASM volatile ("MSR control, %0" : : "r" (control) : "memory"); } /** \brief Get IPSR Register This function returns the content of the IPSR Register. \return IPSR Register value */ __attribute__( ( always_inline ) ) __STATIC_INLINE uint32_t __get_IPSR(void) { uint32_t result; __ASM volatile ("MRS %0, ipsr" : "=r" (result) ); return(result); } /** \brief Get APSR Register This function returns the content of the APSR Register. \return APSR Register value */ __attribute__( ( always_inline ) ) __STATIC_INLINE uint32_t __get_APSR(void) { uint32_t result; __ASM volatile ("MRS %0, apsr" : "=r" (result) ); return(result); } /** \brief Get xPSR Register This function returns the content of the xPSR Register. \return xPSR Register value */ __attribute__( ( always_inline ) ) __STATIC_INLINE uint32_t __get_xPSR(void) { uint32_t result; __ASM volatile ("MRS %0, xpsr" : "=r" (result) ); return(result); } /** \brief Get Process Stack Pointer This function returns the current value of the Process Stack Pointer (PSP). \return PSP Register value */ __attribute__( ( always_inline ) ) __STATIC_INLINE uint32_t __get_PSP(void) { register uint32_t result; __ASM volatile ("MRS %0, psp\n" : "=r" (result) ); return(result); } /** \brief Set Process Stack Pointer This function assigns the given value to the Process Stack Pointer (PSP). \param [in] topOfProcStack Process Stack Pointer value to set */ __attribute__( ( always_inline ) ) __STATIC_INLINE void __set_PSP(uint32_t topOfProcStack) { __ASM volatile ("MSR psp, %0\n" : : "r" (topOfProcStack) : "sp"); } /** \brief Get Main Stack Pointer This function returns the current value of the Main Stack Pointer (MSP). \return MSP Register value */ __attribute__( ( always_inline ) ) __STATIC_INLINE uint32_t __get_MSP(void) { register uint32_t result; __ASM volatile ("MRS %0, msp\n" : "=r" (result) ); return(result); } /** \brief Set Main Stack Pointer This function assigns the given value to the Main Stack Pointer (MSP). \param [in] topOfMainStack Main Stack Pointer value to set */ __attribute__( ( always_inline ) ) __STATIC_INLINE void __set_MSP(uint32_t topOfMainStack) { __ASM volatile ("MSR msp, %0\n" : : "r" (topOfMainStack) : "sp"); } /** \brief Get Priority Mask This function returns the current state of the priority mask bit from the Priority Mask Register. \return Priority Mask value */ __attribute__( ( always_inline ) ) __STATIC_INLINE uint32_t __get_PRIMASK(void) { uint32_t result; __ASM volatile ("MRS %0, primask" : "=r" (result) ); return(result); } /** \brief Set Priority Mask This function assigns the given value to the Priority Mask Register. \param [in] priMask Priority Mask */ __attribute__( ( always_inline ) ) __STATIC_INLINE void __set_PRIMASK(uint32_t priMask) { __ASM volatile ("MSR primask, %0" : : "r" (priMask) : "memory"); } #if (__CORTEX_M >= 0x03) /** \brief Enable FIQ This function enables FIQ interrupts by clearing the F-bit in the CPSR. Can only be executed in Privileged modes. */ __attribute__( ( always_inline ) ) __STATIC_INLINE void __enable_fault_irq(void) { __ASM volatile ("cpsie f" : : : "memory"); } /** \brief Disable FIQ This function disables FIQ interrupts by setting the F-bit in the CPSR. Can only be executed in Privileged modes. */ __attribute__( ( always_inline ) ) __STATIC_INLINE void __disable_fault_irq(void) { __ASM volatile ("cpsid f" : : : "memory"); } /** \brief Get Base Priority This function returns the current value of the Base Priority register. \return Base Priority register value */ __attribute__( ( always_inline ) ) __STATIC_INLINE uint32_t __get_BASEPRI(void) { uint32_t result; __ASM volatile ("MRS %0, basepri" : "=r" (result) ); return(result); } /** \brief Set Base Priority This function assigns the given value to the Base Priority register. \param [in] basePri Base Priority value to set */ __attribute__( ( always_inline ) ) __STATIC_INLINE void __set_BASEPRI(uint32_t value) { __ASM volatile ("MSR basepri, %0" : : "r" (value) : "memory"); } /** \brief Set Base Priority with condition This function assigns the given value to the Base Priority register only if BASEPRI masking is disabled, or the new value increases the BASEPRI priority level. \param [in] basePri Base Priority value to set */ __attribute__( ( always_inline ) ) __STATIC_INLINE void __set_BASEPRI_MAX(uint32_t value) { __ASM volatile ("MSR basepri_max, %0" : : "r" (value) : "memory"); } /** \brief Get Fault Mask This function returns the current value of the Fault Mask register. \return Fault Mask register value */ __attribute__( ( always_inline ) ) __STATIC_INLINE uint32_t __get_FAULTMASK(void) { uint32_t result; __ASM volatile ("MRS %0, faultmask" : "=r" (result) ); return(result); } /** \brief Set Fault Mask This function assigns the given value to the Fault Mask register. \param [in] faultMask Fault Mask value to set */ __attribute__( ( always_inline ) ) __STATIC_INLINE void __set_FAULTMASK(uint32_t faultMask) { __ASM volatile ("MSR faultmask, %0" : : "r" (faultMask) : "memory"); } #endif /* (__CORTEX_M >= 0x03) */ #if (__CORTEX_M == 0x04) || (__CORTEX_M == 0x07) /** \brief Get FPSCR This function returns the current value of the Floating Point Status/Control register. \return Floating Point Status/Control register value */ __attribute__( ( always_inline ) ) __STATIC_INLINE uint32_t __get_FPSCR(void) { #if (__FPU_PRESENT == 1) && (__FPU_USED == 1) uint32_t result; /* Empty asm statement works as a scheduling barrier */ __ASM volatile (""); __ASM volatile ("VMRS %0, fpscr" : "=r" (result) ); __ASM volatile (""); return(result); #else return(0); #endif } /** \brief Set FPSCR This function assigns the given value to the Floating Point Status/Control register. \param [in] fpscr Floating Point Status/Control value to set */ __attribute__( ( always_inline ) ) __STATIC_INLINE void __set_FPSCR(uint32_t fpscr) { #if (__FPU_PRESENT == 1) && (__FPU_USED == 1) /* Empty asm statement works as a scheduling barrier */ __ASM volatile (""); __ASM volatile ("VMSR fpscr, %0" : : "r" (fpscr) : "vfpcc"); __ASM volatile (""); #endif } #endif /* (__CORTEX_M == 0x04) || (__CORTEX_M == 0x07) */ #elif defined ( __ICCARM__ ) /*------------------ ICC Compiler -------------------*/ /* IAR iccarm specific functions */ #include #elif defined ( __TMS470__ ) /*---------------- TI CCS Compiler ------------------*/ /* TI CCS specific functions */ #include #elif defined ( __TASKING__ ) /*------------------ TASKING Compiler --------------*/ /* TASKING carm specific functions */ /* * The CMSIS functions have been implemented as intrinsics in the compiler. * Please use "carm -?i" to get an up to date list of all intrinsics, * Including the CMSIS ones. */ #elif defined ( __CSMC__ ) /*------------------ COSMIC Compiler -------------------*/ /* Cosmic specific functions */ #include #endif /*@} end of CMSIS_Core_RegAccFunctions */ #endif /* __CORE_CMFUNC_H */ ================================================ FILE: Zelig/mbed/TARGET_NUCLEO_F401RE/core_cmInstr.h ================================================ /**************************************************************************//** * @file core_cmInstr.h * @brief CMSIS Cortex-M Core Instruction Access Header File * @version V4.10 * @date 18. March 2015 * * @note * ******************************************************************************/ /* Copyright (c) 2009 - 2014 ARM LIMITED All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: - Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. - Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. - Neither the name of ARM 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 COPYRIGHT HOLDERS AND 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. ---------------------------------------------------------------------------*/ #ifndef __CORE_CMINSTR_H #define __CORE_CMINSTR_H /* ########################## Core Instruction Access ######################### */ /** \defgroup CMSIS_Core_InstructionInterface CMSIS Core Instruction Interface Access to dedicated instructions @{ */ #if defined ( __CC_ARM ) /*------------------RealView Compiler -----------------*/ /* ARM armcc specific functions */ #if (__ARMCC_VERSION < 400677) #error "Please use ARM Compiler Toolchain V4.0.677 or later!" #endif /** \brief No Operation No Operation does nothing. This instruction can be used for code alignment purposes. */ #define __NOP __nop /** \brief Wait For Interrupt Wait For Interrupt is a hint instruction that suspends execution until one of a number of events occurs. */ #define __WFI __wfi /** \brief Wait For Event Wait For Event is a hint instruction that permits the processor to enter a low-power state until one of a number of events occurs. */ #define __WFE __wfe /** \brief Send Event Send Event is a hint instruction. It causes an event to be signaled to the CPU. */ #define __SEV __sev /** \brief Instruction Synchronization Barrier Instruction Synchronization Barrier flushes the pipeline in the processor, so that all instructions following the ISB are fetched from cache or memory, after the instruction has been completed. */ #define __ISB() do {\ __schedule_barrier();\ __isb(0xF);\ __schedule_barrier();\ } while (0) /** \brief Data Synchronization Barrier This function acts as a special kind of Data Memory Barrier. It completes when all explicit memory accesses before this instruction complete. */ #define __DSB() do {\ __schedule_barrier();\ __dsb(0xF);\ __schedule_barrier();\ } while (0) /** \brief Data Memory Barrier This function ensures the apparent order of the explicit memory operations before and after the instruction, without ensuring their completion. */ #define __DMB() do {\ __schedule_barrier();\ __dmb(0xF);\ __schedule_barrier();\ } while (0) /** \brief Reverse byte order (32 bit) This function reverses the byte order in integer value. \param [in] value Value to reverse \return Reversed value */ #define __REV __rev /** \brief Reverse byte order (16 bit) This function reverses the byte order in two unsigned short values. \param [in] value Value to reverse \return Reversed value */ #ifndef __NO_EMBEDDED_ASM __attribute__((section(".rev16_text"))) __STATIC_INLINE __ASM uint32_t __REV16(uint32_t value) { rev16 r0, r0 bx lr } #endif /** \brief Reverse byte order in signed short value This function reverses the byte order in a signed short value with sign extension to integer. \param [in] value Value to reverse \return Reversed value */ #ifndef __NO_EMBEDDED_ASM __attribute__((section(".revsh_text"))) __STATIC_INLINE __ASM int32_t __REVSH(int32_t value) { revsh r0, r0 bx lr } #endif /** \brief Rotate Right in unsigned value (32 bit) This function Rotate Right (immediate) provides the value of the contents of a register rotated by a variable number of bits. \param [in] value Value to rotate \param [in] value Number of Bits to rotate \return Rotated value */ #define __ROR __ror /** \brief Breakpoint This function causes the processor to enter Debug state. Debug tools can use this to investigate system state when the instruction at a particular address is reached. \param [in] value is ignored by the processor. If required, a debugger can use it to store additional information about the breakpoint. */ #define __BKPT(value) __breakpoint(value) /** \brief Reverse bit order of value This function reverses the bit order of the given value. \param [in] value Value to reverse \return Reversed value */ #if (__CORTEX_M >= 0x03) || (__CORTEX_SC >= 300) #define __RBIT __rbit #else __attribute__((always_inline)) __STATIC_INLINE uint32_t __RBIT(uint32_t value) { uint32_t result; int32_t s = 4 /*sizeof(v)*/ * 8 - 1; // extra shift needed at end result = value; // r will be reversed bits of v; first get LSB of v for (value >>= 1; value; value >>= 1) { result <<= 1; result |= value & 1; s--; } result <<= s; // shift when v's highest bits are zero return(result); } #endif /** \brief Count leading zeros This function counts the number of leading zeros of a data value. \param [in] value Value to count the leading zeros \return number of leading zeros in value */ #define __CLZ __clz #if (__CORTEX_M >= 0x03) || (__CORTEX_SC >= 300) /** \brief LDR Exclusive (8 bit) This function executes a exclusive LDR instruction for 8 bit value. \param [in] ptr Pointer to data \return value of type uint8_t at (*ptr) */ #define __LDREXB(ptr) ((uint8_t ) __ldrex(ptr)) /** \brief LDR Exclusive (16 bit) This function executes a exclusive LDR instruction for 16 bit values. \param [in] ptr Pointer to data \return value of type uint16_t at (*ptr) */ #define __LDREXH(ptr) ((uint16_t) __ldrex(ptr)) /** \brief LDR Exclusive (32 bit) This function executes a exclusive LDR instruction for 32 bit values. \param [in] ptr Pointer to data \return value of type uint32_t at (*ptr) */ #define __LDREXW(ptr) ((uint32_t ) __ldrex(ptr)) /** \brief STR Exclusive (8 bit) This function executes a exclusive STR instruction for 8 bit values. \param [in] value Value to store \param [in] ptr Pointer to location \return 0 Function succeeded \return 1 Function failed */ #define __STREXB(value, ptr) __strex(value, ptr) /** \brief STR Exclusive (16 bit) This function executes a exclusive STR instruction for 16 bit values. \param [in] value Value to store \param [in] ptr Pointer to location \return 0 Function succeeded \return 1 Function failed */ #define __STREXH(value, ptr) __strex(value, ptr) /** \brief STR Exclusive (32 bit) This function executes a exclusive STR instruction for 32 bit values. \param [in] value Value to store \param [in] ptr Pointer to location \return 0 Function succeeded \return 1 Function failed */ #define __STREXW(value, ptr) __strex(value, ptr) /** \brief Remove the exclusive lock This function removes the exclusive lock which is created by LDREX. */ #define __CLREX __clrex /** \brief Signed Saturate This function saturates a signed value. \param [in] value Value to be saturated \param [in] sat Bit position to saturate to (1..32) \return Saturated value */ #define __SSAT __ssat /** \brief Unsigned Saturate This function saturates an unsigned value. \param [in] value Value to be saturated \param [in] sat Bit position to saturate to (0..31) \return Saturated value */ #define __USAT __usat /** \brief Rotate Right with Extend (32 bit) This function moves each bit of a bitstring right by one bit. The carry input is shifted in at the left end of the bitstring. \param [in] value Value to rotate \return Rotated value */ #ifndef __NO_EMBEDDED_ASM __attribute__((section(".rrx_text"))) __STATIC_INLINE __ASM uint32_t __RRX(uint32_t value) { rrx r0, r0 bx lr } #endif /** \brief LDRT Unprivileged (8 bit) This function executes a Unprivileged LDRT instruction for 8 bit value. \param [in] ptr Pointer to data \return value of type uint8_t at (*ptr) */ #define __LDRBT(ptr) ((uint8_t ) __ldrt(ptr)) /** \brief LDRT Unprivileged (16 bit) This function executes a Unprivileged LDRT instruction for 16 bit values. \param [in] ptr Pointer to data \return value of type uint16_t at (*ptr) */ #define __LDRHT(ptr) ((uint16_t) __ldrt(ptr)) /** \brief LDRT Unprivileged (32 bit) This function executes a Unprivileged LDRT instruction for 32 bit values. \param [in] ptr Pointer to data \return value of type uint32_t at (*ptr) */ #define __LDRT(ptr) ((uint32_t ) __ldrt(ptr)) /** \brief STRT Unprivileged (8 bit) This function executes a Unprivileged STRT instruction for 8 bit values. \param [in] value Value to store \param [in] ptr Pointer to location */ #define __STRBT(value, ptr) __strt(value, ptr) /** \brief STRT Unprivileged (16 bit) This function executes a Unprivileged STRT instruction for 16 bit values. \param [in] value Value to store \param [in] ptr Pointer to location */ #define __STRHT(value, ptr) __strt(value, ptr) /** \brief STRT Unprivileged (32 bit) This function executes a Unprivileged STRT instruction for 32 bit values. \param [in] value Value to store \param [in] ptr Pointer to location */ #define __STRT(value, ptr) __strt(value, ptr) #endif /* (__CORTEX_M >= 0x03) || (__CORTEX_SC >= 300) */ #elif defined ( __GNUC__ ) /*------------------ GNU Compiler ---------------------*/ /* GNU gcc specific functions */ /* Define macros for porting to both thumb1 and thumb2. * For thumb1, use low register (r0-r7), specified by constrant "l" * Otherwise, use general registers, specified by constrant "r" */ #if defined (__thumb__) && !defined (__thumb2__) #define __CMSIS_GCC_OUT_REG(r) "=l" (r) #define __CMSIS_GCC_USE_REG(r) "l" (r) #else #define __CMSIS_GCC_OUT_REG(r) "=r" (r) #define __CMSIS_GCC_USE_REG(r) "r" (r) #endif /** \brief No Operation No Operation does nothing. This instruction can be used for code alignment purposes. */ __attribute__((always_inline)) __STATIC_INLINE void __NOP(void) { __ASM volatile ("nop"); } /** \brief Wait For Interrupt Wait For Interrupt is a hint instruction that suspends execution until one of a number of events occurs. */ __attribute__((always_inline)) __STATIC_INLINE void __WFI(void) { __ASM volatile ("wfi"); } /** \brief Wait For Event Wait For Event is a hint instruction that permits the processor to enter a low-power state until one of a number of events occurs. */ __attribute__((always_inline)) __STATIC_INLINE void __WFE(void) { __ASM volatile ("wfe"); } /** \brief Send Event Send Event is a hint instruction. It causes an event to be signaled to the CPU. */ __attribute__((always_inline)) __STATIC_INLINE void __SEV(void) { __ASM volatile ("sev"); } /** \brief Instruction Synchronization Barrier Instruction Synchronization Barrier flushes the pipeline in the processor, so that all instructions following the ISB are fetched from cache or memory, after the instruction has been completed. */ __attribute__((always_inline)) __STATIC_INLINE void __ISB(void) { __ASM volatile ("isb 0xF":::"memory"); } /** \brief Data Synchronization Barrier This function acts as a special kind of Data Memory Barrier. It completes when all explicit memory accesses before this instruction complete. */ __attribute__((always_inline)) __STATIC_INLINE void __DSB(void) { __ASM volatile ("dsb 0xF":::"memory"); } /** \brief Data Memory Barrier This function ensures the apparent order of the explicit memory operations before and after the instruction, without ensuring their completion. */ __attribute__((always_inline)) __STATIC_INLINE void __DMB(void) { __ASM volatile ("dmb 0xF":::"memory"); } /** \brief Reverse byte order (32 bit) This function reverses the byte order in integer value. \param [in] value Value to reverse \return Reversed value */ __attribute__((always_inline)) __STATIC_INLINE uint32_t __REV(uint32_t value) { #if (__GNUC__ > 4) || (__GNUC__ == 4 && __GNUC_MINOR__ >= 5) return __builtin_bswap32(value); #else uint32_t result; __ASM volatile ("rev %0, %1" : __CMSIS_GCC_OUT_REG (result) : __CMSIS_GCC_USE_REG (value) ); return(result); #endif } /** \brief Reverse byte order (16 bit) This function reverses the byte order in two unsigned short values. \param [in] value Value to reverse \return Reversed value */ __attribute__((always_inline)) __STATIC_INLINE uint32_t __REV16(uint32_t value) { uint32_t result; __ASM volatile ("rev16 %0, %1" : __CMSIS_GCC_OUT_REG (result) : __CMSIS_GCC_USE_REG (value) ); return(result); } /** \brief Reverse byte order in signed short value This function reverses the byte order in a signed short value with sign extension to integer. \param [in] value Value to reverse \return Reversed value */ __attribute__((always_inline)) __STATIC_INLINE int32_t __REVSH(int32_t value) { #if (__GNUC__ > 4) || (__GNUC__ == 4 && __GNUC_MINOR__ >= 8) return (short)__builtin_bswap16(value); #else uint32_t result; __ASM volatile ("revsh %0, %1" : __CMSIS_GCC_OUT_REG (result) : __CMSIS_GCC_USE_REG (value) ); return(result); #endif } /** \brief Rotate Right in unsigned value (32 bit) This function Rotate Right (immediate) provides the value of the contents of a register rotated by a variable number of bits. \param [in] value Value to rotate \param [in] value Number of Bits to rotate \return Rotated value */ __attribute__((always_inline)) __STATIC_INLINE uint32_t __ROR(uint32_t op1, uint32_t op2) { return (op1 >> op2) | (op1 << (32 - op2)); } /** \brief Breakpoint This function causes the processor to enter Debug state. Debug tools can use this to investigate system state when the instruction at a particular address is reached. \param [in] value is ignored by the processor. If required, a debugger can use it to store additional information about the breakpoint. */ #define __BKPT(value) __ASM volatile ("bkpt "#value) /** \brief Reverse bit order of value This function reverses the bit order of the given value. \param [in] value Value to reverse \return Reversed value */ __attribute__((always_inline)) __STATIC_INLINE uint32_t __RBIT(uint32_t value) { uint32_t result; #if (__CORTEX_M >= 0x03) || (__CORTEX_SC >= 300) __ASM volatile ("rbit %0, %1" : "=r" (result) : "r" (value) ); #else int32_t s = 4 /*sizeof(v)*/ * 8 - 1; // extra shift needed at end result = value; // r will be reversed bits of v; first get LSB of v for (value >>= 1; value; value >>= 1) { result <<= 1; result |= value & 1; s--; } result <<= s; // shift when v's highest bits are zero #endif return(result); } /** \brief Count leading zeros This function counts the number of leading zeros of a data value. \param [in] value Value to count the leading zeros \return number of leading zeros in value */ #define __CLZ __builtin_clz #if (__CORTEX_M >= 0x03) || (__CORTEX_SC >= 300) /** \brief LDR Exclusive (8 bit) This function executes a exclusive LDR instruction for 8 bit value. \param [in] ptr Pointer to data \return value of type uint8_t at (*ptr) */ __attribute__((always_inline)) __STATIC_INLINE uint8_t __LDREXB(volatile uint8_t *addr) { uint32_t result; #if (__GNUC__ > 4) || (__GNUC__ == 4 && __GNUC_MINOR__ >= 8) __ASM volatile ("ldrexb %0, %1" : "=r" (result) : "Q" (*addr) ); #else /* Prior to GCC 4.8, "Q" will be expanded to [rx, #0] which is not accepted by assembler. So has to use following less efficient pattern. */ __ASM volatile ("ldrexb %0, [%1]" : "=r" (result) : "r" (addr) : "memory" ); #endif return ((uint8_t) result); /* Add explicit type cast here */ } /** \brief LDR Exclusive (16 bit) This function executes a exclusive LDR instruction for 16 bit values. \param [in] ptr Pointer to data \return value of type uint16_t at (*ptr) */ __attribute__((always_inline)) __STATIC_INLINE uint16_t __LDREXH(volatile uint16_t *addr) { uint32_t result; #if (__GNUC__ > 4) || (__GNUC__ == 4 && __GNUC_MINOR__ >= 8) __ASM volatile ("ldrexh %0, %1" : "=r" (result) : "Q" (*addr) ); #else /* Prior to GCC 4.8, "Q" will be expanded to [rx, #0] which is not accepted by assembler. So has to use following less efficient pattern. */ __ASM volatile ("ldrexh %0, [%1]" : "=r" (result) : "r" (addr) : "memory" ); #endif return ((uint16_t) result); /* Add explicit type cast here */ } /** \brief LDR Exclusive (32 bit) This function executes a exclusive LDR instruction for 32 bit values. \param [in] ptr Pointer to data \return value of type uint32_t at (*ptr) */ __attribute__((always_inline)) __STATIC_INLINE uint32_t __LDREXW(volatile uint32_t *addr) { uint32_t result; __ASM volatile ("ldrex %0, %1" : "=r" (result) : "Q" (*addr) ); return(result); } /** \brief STR Exclusive (8 bit) This function executes a exclusive STR instruction for 8 bit values. \param [in] value Value to store \param [in] ptr Pointer to location \return 0 Function succeeded \return 1 Function failed */ __attribute__((always_inline)) __STATIC_INLINE uint32_t __STREXB(uint8_t value, volatile uint8_t *addr) { uint32_t result; __ASM volatile ("strexb %0, %2, %1" : "=&r" (result), "=Q" (*addr) : "r" ((uint32_t)value) ); return(result); } /** \brief STR Exclusive (16 bit) This function executes a exclusive STR instruction for 16 bit values. \param [in] value Value to store \param [in] ptr Pointer to location \return 0 Function succeeded \return 1 Function failed */ __attribute__((always_inline)) __STATIC_INLINE uint32_t __STREXH(uint16_t value, volatile uint16_t *addr) { uint32_t result; __ASM volatile ("strexh %0, %2, %1" : "=&r" (result), "=Q" (*addr) : "r" ((uint32_t)value) ); return(result); } /** \brief STR Exclusive (32 bit) This function executes a exclusive STR instruction for 32 bit values. \param [in] value Value to store \param [in] ptr Pointer to location \return 0 Function succeeded \return 1 Function failed */ __attribute__((always_inline)) __STATIC_INLINE uint32_t __STREXW(uint32_t value, volatile uint32_t *addr) { uint32_t result; __ASM volatile ("strex %0, %2, %1" : "=&r" (result), "=Q" (*addr) : "r" (value) ); return(result); } /** \brief Remove the exclusive lock This function removes the exclusive lock which is created by LDREX. */ __attribute__((always_inline)) __STATIC_INLINE void __CLREX(void) { __ASM volatile ("clrex" ::: "memory"); } /** \brief Signed Saturate This function saturates a signed value. \param [in] value Value to be saturated \param [in] sat Bit position to saturate to (1..32) \return Saturated value */ #define __SSAT(ARG1,ARG2) \ ({ \ uint32_t __RES, __ARG1 = (ARG1); \ __ASM ("ssat %0, %1, %2" : "=r" (__RES) : "I" (ARG2), "r" (__ARG1) ); \ __RES; \ }) /** \brief Unsigned Saturate This function saturates an unsigned value. \param [in] value Value to be saturated \param [in] sat Bit position to saturate to (0..31) \return Saturated value */ #define __USAT(ARG1,ARG2) \ ({ \ uint32_t __RES, __ARG1 = (ARG1); \ __ASM ("usat %0, %1, %2" : "=r" (__RES) : "I" (ARG2), "r" (__ARG1) ); \ __RES; \ }) /** \brief Rotate Right with Extend (32 bit) This function moves each bit of a bitstring right by one bit. The carry input is shifted in at the left end of the bitstring. \param [in] value Value to rotate \return Rotated value */ __attribute__((always_inline)) __STATIC_INLINE uint32_t __RRX(uint32_t value) { uint32_t result; __ASM volatile ("rrx %0, %1" : __CMSIS_GCC_OUT_REG (result) : __CMSIS_GCC_USE_REG (value) ); return(result); } /** \brief LDRT Unprivileged (8 bit) This function executes a Unprivileged LDRT instruction for 8 bit value. \param [in] ptr Pointer to data \return value of type uint8_t at (*ptr) */ __attribute__((always_inline)) __STATIC_INLINE uint8_t __LDRBT(volatile uint8_t *addr) { uint32_t result; #if (__GNUC__ > 4) || (__GNUC__ == 4 && __GNUC_MINOR__ >= 8) __ASM volatile ("ldrbt %0, %1" : "=r" (result) : "Q" (*addr) ); #else /* Prior to GCC 4.8, "Q" will be expanded to [rx, #0] which is not accepted by assembler. So has to use following less efficient pattern. */ __ASM volatile ("ldrbt %0, [%1]" : "=r" (result) : "r" (addr) : "memory" ); #endif return ((uint8_t) result); /* Add explicit type cast here */ } /** \brief LDRT Unprivileged (16 bit) This function executes a Unprivileged LDRT instruction for 16 bit values. \param [in] ptr Pointer to data \return value of type uint16_t at (*ptr) */ __attribute__((always_inline)) __STATIC_INLINE uint16_t __LDRHT(volatile uint16_t *addr) { uint32_t result; #if (__GNUC__ > 4) || (__GNUC__ == 4 && __GNUC_MINOR__ >= 8) __ASM volatile ("ldrht %0, %1" : "=r" (result) : "Q" (*addr) ); #else /* Prior to GCC 4.8, "Q" will be expanded to [rx, #0] which is not accepted by assembler. So has to use following less efficient pattern. */ __ASM volatile ("ldrht %0, [%1]" : "=r" (result) : "r" (addr) : "memory" ); #endif return ((uint16_t) result); /* Add explicit type cast here */ } /** \brief LDRT Unprivileged (32 bit) This function executes a Unprivileged LDRT instruction for 32 bit values. \param [in] ptr Pointer to data \return value of type uint32_t at (*ptr) */ __attribute__((always_inline)) __STATIC_INLINE uint32_t __LDRT(volatile uint32_t *addr) { uint32_t result; __ASM volatile ("ldrt %0, %1" : "=r" (result) : "Q" (*addr) ); return(result); } /** \brief STRT Unprivileged (8 bit) This function executes a Unprivileged STRT instruction for 8 bit values. \param [in] value Value to store \param [in] ptr Pointer to location */ __attribute__((always_inline)) __STATIC_INLINE void __STRBT(uint8_t value, volatile uint8_t *addr) { __ASM volatile ("strbt %1, %0" : "=Q" (*addr) : "r" ((uint32_t)value) ); } /** \brief STRT Unprivileged (16 bit) This function executes a Unprivileged STRT instruction for 16 bit values. \param [in] value Value to store \param [in] ptr Pointer to location */ __attribute__((always_inline)) __STATIC_INLINE void __STRHT(uint16_t value, volatile uint16_t *addr) { __ASM volatile ("strht %1, %0" : "=Q" (*addr) : "r" ((uint32_t)value) ); } /** \brief STRT Unprivileged (32 bit) This function executes a Unprivileged STRT instruction for 32 bit values. \param [in] value Value to store \param [in] ptr Pointer to location */ __attribute__((always_inline)) __STATIC_INLINE void __STRT(uint32_t value, volatile uint32_t *addr) { __ASM volatile ("strt %1, %0" : "=Q" (*addr) : "r" (value) ); } #endif /* (__CORTEX_M >= 0x03) || (__CORTEX_SC >= 300) */ #elif defined ( __ICCARM__ ) /*------------------ ICC Compiler -------------------*/ /* IAR iccarm specific functions */ #include #elif defined ( __TMS470__ ) /*---------------- TI CCS Compiler ------------------*/ /* TI CCS specific functions */ #include #elif defined ( __TASKING__ ) /*------------------ TASKING Compiler --------------*/ /* TASKING carm specific functions */ /* * The CMSIS functions have been implemented as intrinsics in the compiler. * Please use "carm -?i" to get an up to date list of all intrinsics, * Including the CMSIS ones. */ #elif defined ( __CSMC__ ) /*------------------ COSMIC Compiler -------------------*/ /* Cosmic specific functions */ #include #endif /*@}*/ /* end of group CMSIS_Core_InstructionInterface */ #endif /* __CORE_CMINSTR_H */ ================================================ FILE: Zelig/mbed/TARGET_NUCLEO_F401RE/core_cmSimd.h ================================================ /**************************************************************************//** * @file core_cmSimd.h * @brief CMSIS Cortex-M SIMD Header File * @version V4.10 * @date 18. March 2015 * * @note * ******************************************************************************/ /* Copyright (c) 2009 - 2014 ARM LIMITED All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: - Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. - Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. - Neither the name of ARM 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 COPYRIGHT HOLDERS AND 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. ---------------------------------------------------------------------------*/ #if defined ( __ICCARM__ ) #pragma system_include /* treat file as system include file for MISRA check */ #endif #ifndef __CORE_CMSIMD_H #define __CORE_CMSIMD_H #ifdef __cplusplus extern "C" { #endif /******************************************************************************* * Hardware Abstraction Layer ******************************************************************************/ /* ################### Compiler specific Intrinsics ########################### */ /** \defgroup CMSIS_SIMD_intrinsics CMSIS SIMD Intrinsics Access to dedicated SIMD instructions @{ */ #if defined ( __CC_ARM ) /*------------------RealView Compiler -----------------*/ /* ARM armcc specific functions */ #define __SADD8 __sadd8 #define __QADD8 __qadd8 #define __SHADD8 __shadd8 #define __UADD8 __uadd8 #define __UQADD8 __uqadd8 #define __UHADD8 __uhadd8 #define __SSUB8 __ssub8 #define __QSUB8 __qsub8 #define __SHSUB8 __shsub8 #define __USUB8 __usub8 #define __UQSUB8 __uqsub8 #define __UHSUB8 __uhsub8 #define __SADD16 __sadd16 #define __QADD16 __qadd16 #define __SHADD16 __shadd16 #define __UADD16 __uadd16 #define __UQADD16 __uqadd16 #define __UHADD16 __uhadd16 #define __SSUB16 __ssub16 #define __QSUB16 __qsub16 #define __SHSUB16 __shsub16 #define __USUB16 __usub16 #define __UQSUB16 __uqsub16 #define __UHSUB16 __uhsub16 #define __SASX __sasx #define __QASX __qasx #define __SHASX __shasx #define __UASX __uasx #define __UQASX __uqasx #define __UHASX __uhasx #define __SSAX __ssax #define __QSAX __qsax #define __SHSAX __shsax #define __USAX __usax #define __UQSAX __uqsax #define __UHSAX __uhsax #define __USAD8 __usad8 #define __USADA8 __usada8 #define __SSAT16 __ssat16 #define __USAT16 __usat16 #define __UXTB16 __uxtb16 #define __UXTAB16 __uxtab16 #define __SXTB16 __sxtb16 #define __SXTAB16 __sxtab16 #define __SMUAD __smuad #define __SMUADX __smuadx #define __SMLAD __smlad #define __SMLADX __smladx #define __SMLALD __smlald #define __SMLALDX __smlaldx #define __SMUSD __smusd #define __SMUSDX __smusdx #define __SMLSD __smlsd #define __SMLSDX __smlsdx #define __SMLSLD __smlsld #define __SMLSLDX __smlsldx #define __SEL __sel #define __QADD __qadd #define __QSUB __qsub #define __PKHBT(ARG1,ARG2,ARG3) ( ((((uint32_t)(ARG1)) ) & 0x0000FFFFUL) | \ ((((uint32_t)(ARG2)) << (ARG3)) & 0xFFFF0000UL) ) #define __PKHTB(ARG1,ARG2,ARG3) ( ((((uint32_t)(ARG1)) ) & 0xFFFF0000UL) | \ ((((uint32_t)(ARG2)) >> (ARG3)) & 0x0000FFFFUL) ) #define __SMMLA(ARG1,ARG2,ARG3) ( (int32_t)((((int64_t)(ARG1) * (ARG2)) + \ ((int64_t)(ARG3) << 32) ) >> 32)) #elif defined ( __GNUC__ ) /*------------------ GNU Compiler ---------------------*/ /* GNU gcc specific functions */ __attribute__( ( always_inline ) ) __STATIC_INLINE uint32_t __SADD8(uint32_t op1, uint32_t op2) { uint32_t result; __ASM volatile ("sadd8 %0, %1, %2" : "=r" (result) : "r" (op1), "r" (op2) ); return(result); } __attribute__( ( always_inline ) ) __STATIC_INLINE uint32_t __QADD8(uint32_t op1, uint32_t op2) { uint32_t result; __ASM volatile ("qadd8 %0, %1, %2" : "=r" (result) : "r" (op1), "r" (op2) ); return(result); } __attribute__( ( always_inline ) ) __STATIC_INLINE uint32_t __SHADD8(uint32_t op1, uint32_t op2) { uint32_t result; __ASM volatile ("shadd8 %0, %1, %2" : "=r" (result) : "r" (op1), "r" (op2) ); return(result); } __attribute__( ( always_inline ) ) __STATIC_INLINE uint32_t __UADD8(uint32_t op1, uint32_t op2) { uint32_t result; __ASM volatile ("uadd8 %0, %1, %2" : "=r" (result) : "r" (op1), "r" (op2) ); return(result); } __attribute__( ( always_inline ) ) __STATIC_INLINE uint32_t __UQADD8(uint32_t op1, uint32_t op2) { uint32_t result; __ASM volatile ("uqadd8 %0, %1, %2" : "=r" (result) : "r" (op1), "r" (op2) ); return(result); } __attribute__( ( always_inline ) ) __STATIC_INLINE uint32_t __UHADD8(uint32_t op1, uint32_t op2) { uint32_t result; __ASM volatile ("uhadd8 %0, %1, %2" : "=r" (result) : "r" (op1), "r" (op2) ); return(result); } __attribute__( ( always_inline ) ) __STATIC_INLINE uint32_t __SSUB8(uint32_t op1, uint32_t op2) { uint32_t result; __ASM volatile ("ssub8 %0, %1, %2" : "=r" (result) : "r" (op1), "r" (op2) ); return(result); } __attribute__( ( always_inline ) ) __STATIC_INLINE uint32_t __QSUB8(uint32_t op1, uint32_t op2) { uint32_t result; __ASM volatile ("qsub8 %0, %1, %2" : "=r" (result) : "r" (op1), "r" (op2) ); return(result); } __attribute__( ( always_inline ) ) __STATIC_INLINE uint32_t __SHSUB8(uint32_t op1, uint32_t op2) { uint32_t result; __ASM volatile ("shsub8 %0, %1, %2" : "=r" (result) : "r" (op1), "r" (op2) ); return(result); } __attribute__( ( always_inline ) ) __STATIC_INLINE uint32_t __USUB8(uint32_t op1, uint32_t op2) { uint32_t result; __ASM volatile ("usub8 %0, %1, %2" : "=r" (result) : "r" (op1), "r" (op2) ); return(result); } __attribute__( ( always_inline ) ) __STATIC_INLINE uint32_t __UQSUB8(uint32_t op1, uint32_t op2) { uint32_t result; __ASM volatile ("uqsub8 %0, %1, %2" : "=r" (result) : "r" (op1), "r" (op2) ); return(result); } __attribute__( ( always_inline ) ) __STATIC_INLINE uint32_t __UHSUB8(uint32_t op1, uint32_t op2) { uint32_t result; __ASM volatile ("uhsub8 %0, %1, %2" : "=r" (result) : "r" (op1), "r" (op2) ); return(result); } __attribute__( ( always_inline ) ) __STATIC_INLINE uint32_t __SADD16(uint32_t op1, uint32_t op2) { uint32_t result; __ASM volatile ("sadd16 %0, %1, %2" : "=r" (result) : "r" (op1), "r" (op2) ); return(result); } __attribute__( ( always_inline ) ) __STATIC_INLINE uint32_t __QADD16(uint32_t op1, uint32_t op2) { uint32_t result; __ASM volatile ("qadd16 %0, %1, %2" : "=r" (result) : "r" (op1), "r" (op2) ); return(result); } __attribute__( ( always_inline ) ) __STATIC_INLINE uint32_t __SHADD16(uint32_t op1, uint32_t op2) { uint32_t result; __ASM volatile ("shadd16 %0, %1, %2" : "=r" (result) : "r" (op1), "r" (op2) ); return(result); } __attribute__( ( always_inline ) ) __STATIC_INLINE uint32_t __UADD16(uint32_t op1, uint32_t op2) { uint32_t result; __ASM volatile ("uadd16 %0, %1, %2" : "=r" (result) : "r" (op1), "r" (op2) ); return(result); } __attribute__( ( always_inline ) ) __STATIC_INLINE uint32_t __UQADD16(uint32_t op1, uint32_t op2) { uint32_t result; __ASM volatile ("uqadd16 %0, %1, %2" : "=r" (result) : "r" (op1), "r" (op2) ); return(result); } __attribute__( ( always_inline ) ) __STATIC_INLINE uint32_t __UHADD16(uint32_t op1, uint32_t op2) { uint32_t result; __ASM volatile ("uhadd16 %0, %1, %2" : "=r" (result) : "r" (op1), "r" (op2) ); return(result); } __attribute__( ( always_inline ) ) __STATIC_INLINE uint32_t __SSUB16(uint32_t op1, uint32_t op2) { uint32_t result; __ASM volatile ("ssub16 %0, %1, %2" : "=r" (result) : "r" (op1), "r" (op2) ); return(result); } __attribute__( ( always_inline ) ) __STATIC_INLINE uint32_t __QSUB16(uint32_t op1, uint32_t op2) { uint32_t result; __ASM volatile ("qsub16 %0, %1, %2" : "=r" (result) : "r" (op1), "r" (op2) ); return(result); } __attribute__( ( always_inline ) ) __STATIC_INLINE uint32_t __SHSUB16(uint32_t op1, uint32_t op2) { uint32_t result; __ASM volatile ("shsub16 %0, %1, %2" : "=r" (result) : "r" (op1), "r" (op2) ); return(result); } __attribute__( ( always_inline ) ) __STATIC_INLINE uint32_t __USUB16(uint32_t op1, uint32_t op2) { uint32_t result; __ASM volatile ("usub16 %0, %1, %2" : "=r" (result) : "r" (op1), "r" (op2) ); return(result); } __attribute__( ( always_inline ) ) __STATIC_INLINE uint32_t __UQSUB16(uint32_t op1, uint32_t op2) { uint32_t result; __ASM volatile ("uqsub16 %0, %1, %2" : "=r" (result) : "r" (op1), "r" (op2) ); return(result); } __attribute__( ( always_inline ) ) __STATIC_INLINE uint32_t __UHSUB16(uint32_t op1, uint32_t op2) { uint32_t result; __ASM volatile ("uhsub16 %0, %1, %2" : "=r" (result) : "r" (op1), "r" (op2) ); return(result); } __attribute__( ( always_inline ) ) __STATIC_INLINE uint32_t __SASX(uint32_t op1, uint32_t op2) { uint32_t result; __ASM volatile ("sasx %0, %1, %2" : "=r" (result) : "r" (op1), "r" (op2) ); return(result); } __attribute__( ( always_inline ) ) __STATIC_INLINE uint32_t __QASX(uint32_t op1, uint32_t op2) { uint32_t result; __ASM volatile ("qasx %0, %1, %2" : "=r" (result) : "r" (op1), "r" (op2) ); return(result); } __attribute__( ( always_inline ) ) __STATIC_INLINE uint32_t __SHASX(uint32_t op1, uint32_t op2) { uint32_t result; __ASM volatile ("shasx %0, %1, %2" : "=r" (result) : "r" (op1), "r" (op2) ); return(result); } __attribute__( ( always_inline ) ) __STATIC_INLINE uint32_t __UASX(uint32_t op1, uint32_t op2) { uint32_t result; __ASM volatile ("uasx %0, %1, %2" : "=r" (result) : "r" (op1), "r" (op2) ); return(result); } __attribute__( ( always_inline ) ) __STATIC_INLINE uint32_t __UQASX(uint32_t op1, uint32_t op2) { uint32_t result; __ASM volatile ("uqasx %0, %1, %2" : "=r" (result) : "r" (op1), "r" (op2) ); return(result); } __attribute__( ( always_inline ) ) __STATIC_INLINE uint32_t __UHASX(uint32_t op1, uint32_t op2) { uint32_t result; __ASM volatile ("uhasx %0, %1, %2" : "=r" (result) : "r" (op1), "r" (op2) ); return(result); } __attribute__( ( always_inline ) ) __STATIC_INLINE uint32_t __SSAX(uint32_t op1, uint32_t op2) { uint32_t result; __ASM volatile ("ssax %0, %1, %2" : "=r" (result) : "r" (op1), "r" (op2) ); return(result); } __attribute__( ( always_inline ) ) __STATIC_INLINE uint32_t __QSAX(uint32_t op1, uint32_t op2) { uint32_t result; __ASM volatile ("qsax %0, %1, %2" : "=r" (result) : "r" (op1), "r" (op2) ); return(result); } __attribute__( ( always_inline ) ) __STATIC_INLINE uint32_t __SHSAX(uint32_t op1, uint32_t op2) { uint32_t result; __ASM volatile ("shsax %0, %1, %2" : "=r" (result) : "r" (op1), "r" (op2) ); return(result); } __attribute__( ( always_inline ) ) __STATIC_INLINE uint32_t __USAX(uint32_t op1, uint32_t op2) { uint32_t result; __ASM volatile ("usax %0, %1, %2" : "=r" (result) : "r" (op1), "r" (op2) ); return(result); } __attribute__( ( always_inline ) ) __STATIC_INLINE uint32_t __UQSAX(uint32_t op1, uint32_t op2) { uint32_t result; __ASM volatile ("uqsax %0, %1, %2" : "=r" (result) : "r" (op1), "r" (op2) ); return(result); } __attribute__( ( always_inline ) ) __STATIC_INLINE uint32_t __UHSAX(uint32_t op1, uint32_t op2) { uint32_t result; __ASM volatile ("uhsax %0, %1, %2" : "=r" (result) : "r" (op1), "r" (op2) ); return(result); } __attribute__( ( always_inline ) ) __STATIC_INLINE uint32_t __USAD8(uint32_t op1, uint32_t op2) { uint32_t result; __ASM volatile ("usad8 %0, %1, %2" : "=r" (result) : "r" (op1), "r" (op2) ); return(result); } __attribute__( ( always_inline ) ) __STATIC_INLINE uint32_t __USADA8(uint32_t op1, uint32_t op2, uint32_t op3) { uint32_t result; __ASM volatile ("usada8 %0, %1, %2, %3" : "=r" (result) : "r" (op1), "r" (op2), "r" (op3) ); return(result); } #define __SSAT16(ARG1,ARG2) \ ({ \ uint32_t __RES, __ARG1 = (ARG1); \ __ASM ("ssat16 %0, %1, %2" : "=r" (__RES) : "I" (ARG2), "r" (__ARG1) ); \ __RES; \ }) #define __USAT16(ARG1,ARG2) \ ({ \ uint32_t __RES, __ARG1 = (ARG1); \ __ASM ("usat16 %0, %1, %2" : "=r" (__RES) : "I" (ARG2), "r" (__ARG1) ); \ __RES; \ }) __attribute__( ( always_inline ) ) __STATIC_INLINE uint32_t __UXTB16(uint32_t op1) { uint32_t result; __ASM volatile ("uxtb16 %0, %1" : "=r" (result) : "r" (op1)); return(result); } __attribute__( ( always_inline ) ) __STATIC_INLINE uint32_t __UXTAB16(uint32_t op1, uint32_t op2) { uint32_t result; __ASM volatile ("uxtab16 %0, %1, %2" : "=r" (result) : "r" (op1), "r" (op2) ); return(result); } __attribute__( ( always_inline ) ) __STATIC_INLINE uint32_t __SXTB16(uint32_t op1) { uint32_t result; __ASM volatile ("sxtb16 %0, %1" : "=r" (result) : "r" (op1)); return(result); } __attribute__( ( always_inline ) ) __STATIC_INLINE uint32_t __SXTAB16(uint32_t op1, uint32_t op2) { uint32_t result; __ASM volatile ("sxtab16 %0, %1, %2" : "=r" (result) : "r" (op1), "r" (op2) ); return(result); } __attribute__( ( always_inline ) ) __STATIC_INLINE uint32_t __SMUAD (uint32_t op1, uint32_t op2) { uint32_t result; __ASM volatile ("smuad %0, %1, %2" : "=r" (result) : "r" (op1), "r" (op2) ); return(result); } __attribute__( ( always_inline ) ) __STATIC_INLINE uint32_t __SMUADX (uint32_t op1, uint32_t op2) { uint32_t result; __ASM volatile ("smuadx %0, %1, %2" : "=r" (result) : "r" (op1), "r" (op2) ); return(result); } __attribute__( ( always_inline ) ) __STATIC_INLINE uint32_t __SMLAD (uint32_t op1, uint32_t op2, uint32_t op3) { uint32_t result; __ASM volatile ("smlad %0, %1, %2, %3" : "=r" (result) : "r" (op1), "r" (op2), "r" (op3) ); return(result); } __attribute__( ( always_inline ) ) __STATIC_INLINE uint32_t __SMLADX (uint32_t op1, uint32_t op2, uint32_t op3) { uint32_t result; __ASM volatile ("smladx %0, %1, %2, %3" : "=r" (result) : "r" (op1), "r" (op2), "r" (op3) ); return(result); } __attribute__( ( always_inline ) ) __STATIC_INLINE uint64_t __SMLALD (uint32_t op1, uint32_t op2, uint64_t acc) { union llreg_u{ uint32_t w32[2]; uint64_t w64; } llr; llr.w64 = acc; #ifndef __ARMEB__ // Little endian __ASM volatile ("smlald %0, %1, %2, %3" : "=r" (llr.w32[0]), "=r" (llr.w32[1]): "r" (op1), "r" (op2) , "0" (llr.w32[0]), "1" (llr.w32[1]) ); #else // Big endian __ASM volatile ("smlald %0, %1, %2, %3" : "=r" (llr.w32[1]), "=r" (llr.w32[0]): "r" (op1), "r" (op2) , "0" (llr.w32[1]), "1" (llr.w32[0]) ); #endif return(llr.w64); } __attribute__( ( always_inline ) ) __STATIC_INLINE uint64_t __SMLALDX (uint32_t op1, uint32_t op2, uint64_t acc) { union llreg_u{ uint32_t w32[2]; uint64_t w64; } llr; llr.w64 = acc; #ifndef __ARMEB__ // Little endian __ASM volatile ("smlaldx %0, %1, %2, %3" : "=r" (llr.w32[0]), "=r" (llr.w32[1]): "r" (op1), "r" (op2) , "0" (llr.w32[0]), "1" (llr.w32[1]) ); #else // Big endian __ASM volatile ("smlaldx %0, %1, %2, %3" : "=r" (llr.w32[1]), "=r" (llr.w32[0]): "r" (op1), "r" (op2) , "0" (llr.w32[1]), "1" (llr.w32[0]) ); #endif return(llr.w64); } __attribute__( ( always_inline ) ) __STATIC_INLINE uint32_t __SMUSD (uint32_t op1, uint32_t op2) { uint32_t result; __ASM volatile ("smusd %0, %1, %2" : "=r" (result) : "r" (op1), "r" (op2) ); return(result); } __attribute__( ( always_inline ) ) __STATIC_INLINE uint32_t __SMUSDX (uint32_t op1, uint32_t op2) { uint32_t result; __ASM volatile ("smusdx %0, %1, %2" : "=r" (result) : "r" (op1), "r" (op2) ); return(result); } __attribute__( ( always_inline ) ) __STATIC_INLINE uint32_t __SMLSD (uint32_t op1, uint32_t op2, uint32_t op3) { uint32_t result; __ASM volatile ("smlsd %0, %1, %2, %3" : "=r" (result) : "r" (op1), "r" (op2), "r" (op3) ); return(result); } __attribute__( ( always_inline ) ) __STATIC_INLINE uint32_t __SMLSDX (uint32_t op1, uint32_t op2, uint32_t op3) { uint32_t result; __ASM volatile ("smlsdx %0, %1, %2, %3" : "=r" (result) : "r" (op1), "r" (op2), "r" (op3) ); return(result); } __attribute__( ( always_inline ) ) __STATIC_INLINE uint64_t __SMLSLD (uint32_t op1, uint32_t op2, uint64_t acc) { union llreg_u{ uint32_t w32[2]; uint64_t w64; } llr; llr.w64 = acc; #ifndef __ARMEB__ // Little endian __ASM volatile ("smlsld %0, %1, %2, %3" : "=r" (llr.w32[0]), "=r" (llr.w32[1]): "r" (op1), "r" (op2) , "0" (llr.w32[0]), "1" (llr.w32[1]) ); #else // Big endian __ASM volatile ("smlsld %0, %1, %2, %3" : "=r" (llr.w32[1]), "=r" (llr.w32[0]): "r" (op1), "r" (op2) , "0" (llr.w32[1]), "1" (llr.w32[0]) ); #endif return(llr.w64); } __attribute__( ( always_inline ) ) __STATIC_INLINE uint64_t __SMLSLDX (uint32_t op1, uint32_t op2, uint64_t acc) { union llreg_u{ uint32_t w32[2]; uint64_t w64; } llr; llr.w64 = acc; #ifndef __ARMEB__ // Little endian __ASM volatile ("smlsldx %0, %1, %2, %3" : "=r" (llr.w32[0]), "=r" (llr.w32[1]): "r" (op1), "r" (op2) , "0" (llr.w32[0]), "1" (llr.w32[1]) ); #else // Big endian __ASM volatile ("smlsldx %0, %1, %2, %3" : "=r" (llr.w32[1]), "=r" (llr.w32[0]): "r" (op1), "r" (op2) , "0" (llr.w32[1]), "1" (llr.w32[0]) ); #endif return(llr.w64); } __attribute__( ( always_inline ) ) __STATIC_INLINE uint32_t __SEL (uint32_t op1, uint32_t op2) { uint32_t result; __ASM volatile ("sel %0, %1, %2" : "=r" (result) : "r" (op1), "r" (op2) ); return(result); } __attribute__( ( always_inline ) ) __STATIC_INLINE uint32_t __QADD(uint32_t op1, uint32_t op2) { uint32_t result; __ASM volatile ("qadd %0, %1, %2" : "=r" (result) : "r" (op1), "r" (op2) ); return(result); } __attribute__( ( always_inline ) ) __STATIC_INLINE uint32_t __QSUB(uint32_t op1, uint32_t op2) { uint32_t result; __ASM volatile ("qsub %0, %1, %2" : "=r" (result) : "r" (op1), "r" (op2) ); return(result); } #define __PKHBT(ARG1,ARG2,ARG3) \ ({ \ uint32_t __RES, __ARG1 = (ARG1), __ARG2 = (ARG2); \ __ASM ("pkhbt %0, %1, %2, lsl %3" : "=r" (__RES) : "r" (__ARG1), "r" (__ARG2), "I" (ARG3) ); \ __RES; \ }) #define __PKHTB(ARG1,ARG2,ARG3) \ ({ \ uint32_t __RES, __ARG1 = (ARG1), __ARG2 = (ARG2); \ if (ARG3 == 0) \ __ASM ("pkhtb %0, %1, %2" : "=r" (__RES) : "r" (__ARG1), "r" (__ARG2) ); \ else \ __ASM ("pkhtb %0, %1, %2, asr %3" : "=r" (__RES) : "r" (__ARG1), "r" (__ARG2), "I" (ARG3) ); \ __RES; \ }) __attribute__( ( always_inline ) ) __STATIC_INLINE uint32_t __SMMLA (int32_t op1, int32_t op2, int32_t op3) { int32_t result; __ASM volatile ("smmla %0, %1, %2, %3" : "=r" (result): "r" (op1), "r" (op2), "r" (op3) ); return(result); } #elif defined ( __ICCARM__ ) /*------------------ ICC Compiler -------------------*/ /* IAR iccarm specific functions */ #include #elif defined ( __TMS470__ ) /*---------------- TI CCS Compiler ------------------*/ /* TI CCS specific functions */ #include #elif defined ( __TASKING__ ) /*------------------ TASKING Compiler --------------*/ /* TASKING carm specific functions */ /* not yet supported */ #elif defined ( __CSMC__ ) /*------------------ COSMIC Compiler -------------------*/ /* Cosmic specific functions */ #include #endif /*@} end of group CMSIS_SIMD_intrinsics */ #ifdef __cplusplus } #endif #endif /* __CORE_CMSIMD_H */ ================================================ FILE: Zelig/mbed/TARGET_NUCLEO_F401RE/core_sc000.h ================================================ /**************************************************************************//** * @file core_sc000.h * @brief CMSIS SC000 Core Peripheral Access Layer Header File * @version V4.10 * @date 18. March 2015 * * @note * ******************************************************************************/ /* Copyright (c) 2009 - 2015 ARM LIMITED All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: - Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. - Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. - Neither the name of ARM 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 COPYRIGHT HOLDERS AND 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. ---------------------------------------------------------------------------*/ #if defined ( __ICCARM__ ) #pragma system_include /* treat file as system include file for MISRA check */ #endif #ifndef __CORE_SC000_H_GENERIC #define __CORE_SC000_H_GENERIC #ifdef __cplusplus extern "C" { #endif /** \page CMSIS_MISRA_Exceptions MISRA-C:2004 Compliance Exceptions CMSIS violates the following MISRA-C:2004 rules: \li Required Rule 8.5, object/function definition in header file.
Function definitions in header files are used to allow 'inlining'. \li Required Rule 18.4, declaration of union type or object of union type: '{...}'.
Unions are used for effective representation of core registers. \li Advisory Rule 19.7, Function-like macro defined.
Function-like macros are used to allow more efficient code. */ /******************************************************************************* * CMSIS definitions ******************************************************************************/ /** \ingroup SC000 @{ */ /* CMSIS SC000 definitions */ #define __SC000_CMSIS_VERSION_MAIN (0x04) /*!< [31:16] CMSIS HAL main version */ #define __SC000_CMSIS_VERSION_SUB (0x00) /*!< [15:0] CMSIS HAL sub version */ #define __SC000_CMSIS_VERSION ((__SC000_CMSIS_VERSION_MAIN << 16) | \ __SC000_CMSIS_VERSION_SUB ) /*!< CMSIS HAL version number */ #define __CORTEX_SC (000) /*!< Cortex secure core */ #if defined ( __CC_ARM ) #define __ASM __asm /*!< asm keyword for ARM Compiler */ #define __INLINE __inline /*!< inline keyword for ARM Compiler */ #define __STATIC_INLINE static __inline #elif defined ( __GNUC__ ) #define __ASM __asm /*!< asm keyword for GNU Compiler */ #define __INLINE inline /*!< inline keyword for GNU Compiler */ #define __STATIC_INLINE static inline #elif defined ( __ICCARM__ ) #define __ASM __asm /*!< asm keyword for IAR Compiler */ #define __INLINE inline /*!< inline keyword for IAR Compiler. Only available in High optimization mode! */ #define __STATIC_INLINE static inline #elif defined ( __TMS470__ ) #define __ASM __asm /*!< asm keyword for TI CCS Compiler */ #define __STATIC_INLINE static inline #elif defined ( __TASKING__ ) #define __ASM __asm /*!< asm keyword for TASKING Compiler */ #define __INLINE inline /*!< inline keyword for TASKING Compiler */ #define __STATIC_INLINE static inline #elif defined ( __CSMC__ ) #define __packed #define __ASM _asm /*!< asm keyword for COSMIC Compiler */ #define __INLINE inline /*use -pc99 on compile line !< inline keyword for COSMIC Compiler */ #define __STATIC_INLINE static inline #endif /** __FPU_USED indicates whether an FPU is used or not. This core does not support an FPU at all */ #define __FPU_USED 0 #if defined ( __CC_ARM ) #if defined __TARGET_FPU_VFP #warning "Compiler generates FPU instructions for a device without an FPU (check __FPU_PRESENT)" #endif #elif defined ( __GNUC__ ) #if defined (__VFP_FP__) && !defined(__SOFTFP__) #warning "Compiler generates FPU instructions for a device without an FPU (check __FPU_PRESENT)" #endif #elif defined ( __ICCARM__ ) #if defined __ARMVFP__ #warning "Compiler generates FPU instructions for a device without an FPU (check __FPU_PRESENT)" #endif #elif defined ( __TMS470__ ) #if defined __TI__VFP_SUPPORT____ #warning "Compiler generates FPU instructions for a device without an FPU (check __FPU_PRESENT)" #endif #elif defined ( __TASKING__ ) #if defined __FPU_VFP__ #error "Compiler generates FPU instructions for a device without an FPU (check __FPU_PRESENT)" #endif #elif defined ( __CSMC__ ) /* Cosmic */ #if ( __CSMC__ & 0x400) // FPU present for parser #error "Compiler generates FPU instructions for a device without an FPU (check __FPU_PRESENT)" #endif #endif #include /* standard types definitions */ #include /* Core Instruction Access */ #include /* Core Function Access */ #ifdef __cplusplus } #endif #endif /* __CORE_SC000_H_GENERIC */ #ifndef __CMSIS_GENERIC #ifndef __CORE_SC000_H_DEPENDANT #define __CORE_SC000_H_DEPENDANT #ifdef __cplusplus extern "C" { #endif /* check device defines and use defaults */ #if defined __CHECK_DEVICE_DEFINES #ifndef __SC000_REV #define __SC000_REV 0x0000 #warning "__SC000_REV not defined in device header file; using default!" #endif #ifndef __MPU_PRESENT #define __MPU_PRESENT 0 #warning "__MPU_PRESENT not defined in device header file; using default!" #endif #ifndef __NVIC_PRIO_BITS #define __NVIC_PRIO_BITS 2 #warning "__NVIC_PRIO_BITS not defined in device header file; using default!" #endif #ifndef __Vendor_SysTickConfig #define __Vendor_SysTickConfig 0 #warning "__Vendor_SysTickConfig not defined in device header file; using default!" #endif #endif /* IO definitions (access restrictions to peripheral registers) */ /** \defgroup CMSIS_glob_defs CMSIS Global Defines IO Type Qualifiers are used \li to specify the access to peripheral variables. \li for automatic generation of peripheral register debug information. */ #ifdef __cplusplus #define __I volatile /*!< Defines 'read only' permissions */ #else #define __I volatile const /*!< Defines 'read only' permissions */ #endif #define __O volatile /*!< Defines 'write only' permissions */ #define __IO volatile /*!< Defines 'read / write' permissions */ /*@} end of group SC000 */ /******************************************************************************* * Register Abstraction Core Register contain: - Core Register - Core NVIC Register - Core SCB Register - Core SysTick Register - Core MPU Register ******************************************************************************/ /** \defgroup CMSIS_core_register Defines and Type Definitions \brief Type definitions and defines for Cortex-M processor based devices. */ /** \ingroup CMSIS_core_register \defgroup CMSIS_CORE Status and Control Registers \brief Core Register type definitions. @{ */ /** \brief Union type to access the Application Program Status Register (APSR). */ typedef union { struct { uint32_t _reserved0:28; /*!< bit: 0..27 Reserved */ uint32_t V:1; /*!< bit: 28 Overflow condition code flag */ uint32_t C:1; /*!< bit: 29 Carry condition code flag */ uint32_t Z:1; /*!< bit: 30 Zero condition code flag */ uint32_t N:1; /*!< bit: 31 Negative condition code flag */ } b; /*!< Structure used for bit access */ uint32_t w; /*!< Type used for word access */ } APSR_Type; /* APSR Register Definitions */ #define APSR_N_Pos 31 /*!< APSR: N Position */ #define APSR_N_Msk (1UL << APSR_N_Pos) /*!< APSR: N Mask */ #define APSR_Z_Pos 30 /*!< APSR: Z Position */ #define APSR_Z_Msk (1UL << APSR_Z_Pos) /*!< APSR: Z Mask */ #define APSR_C_Pos 29 /*!< APSR: C Position */ #define APSR_C_Msk (1UL << APSR_C_Pos) /*!< APSR: C Mask */ #define APSR_V_Pos 28 /*!< APSR: V Position */ #define APSR_V_Msk (1UL << APSR_V_Pos) /*!< APSR: V Mask */ /** \brief Union type to access the Interrupt Program Status Register (IPSR). */ typedef union { struct { uint32_t ISR:9; /*!< bit: 0.. 8 Exception number */ uint32_t _reserved0:23; /*!< bit: 9..31 Reserved */ } b; /*!< Structure used for bit access */ uint32_t w; /*!< Type used for word access */ } IPSR_Type; /* IPSR Register Definitions */ #define IPSR_ISR_Pos 0 /*!< IPSR: ISR Position */ #define IPSR_ISR_Msk (0x1FFUL /*<< IPSR_ISR_Pos*/) /*!< IPSR: ISR Mask */ /** \brief Union type to access the Special-Purpose Program Status Registers (xPSR). */ typedef union { struct { uint32_t ISR:9; /*!< bit: 0.. 8 Exception number */ uint32_t _reserved0:15; /*!< bit: 9..23 Reserved */ uint32_t T:1; /*!< bit: 24 Thumb bit (read 0) */ uint32_t _reserved1:3; /*!< bit: 25..27 Reserved */ uint32_t V:1; /*!< bit: 28 Overflow condition code flag */ uint32_t C:1; /*!< bit: 29 Carry condition code flag */ uint32_t Z:1; /*!< bit: 30 Zero condition code flag */ uint32_t N:1; /*!< bit: 31 Negative condition code flag */ } b; /*!< Structure used for bit access */ uint32_t w; /*!< Type used for word access */ } xPSR_Type; /* xPSR Register Definitions */ #define xPSR_N_Pos 31 /*!< xPSR: N Position */ #define xPSR_N_Msk (1UL << xPSR_N_Pos) /*!< xPSR: N Mask */ #define xPSR_Z_Pos 30 /*!< xPSR: Z Position */ #define xPSR_Z_Msk (1UL << xPSR_Z_Pos) /*!< xPSR: Z Mask */ #define xPSR_C_Pos 29 /*!< xPSR: C Position */ #define xPSR_C_Msk (1UL << xPSR_C_Pos) /*!< xPSR: C Mask */ #define xPSR_V_Pos 28 /*!< xPSR: V Position */ #define xPSR_V_Msk (1UL << xPSR_V_Pos) /*!< xPSR: V Mask */ #define xPSR_T_Pos 24 /*!< xPSR: T Position */ #define xPSR_T_Msk (1UL << xPSR_T_Pos) /*!< xPSR: T Mask */ #define xPSR_ISR_Pos 0 /*!< xPSR: ISR Position */ #define xPSR_ISR_Msk (0x1FFUL /*<< xPSR_ISR_Pos*/) /*!< xPSR: ISR Mask */ /** \brief Union type to access the Control Registers (CONTROL). */ typedef union { struct { uint32_t _reserved0:1; /*!< bit: 0 Reserved */ uint32_t SPSEL:1; /*!< bit: 1 Stack to be used */ uint32_t _reserved1:30; /*!< bit: 2..31 Reserved */ } b; /*!< Structure used for bit access */ uint32_t w; /*!< Type used for word access */ } CONTROL_Type; /* CONTROL Register Definitions */ #define CONTROL_SPSEL_Pos 1 /*!< CONTROL: SPSEL Position */ #define CONTROL_SPSEL_Msk (1UL << CONTROL_SPSEL_Pos) /*!< CONTROL: SPSEL Mask */ /*@} end of group CMSIS_CORE */ /** \ingroup CMSIS_core_register \defgroup CMSIS_NVIC Nested Vectored Interrupt Controller (NVIC) \brief Type definitions for the NVIC Registers @{ */ /** \brief Structure type to access the Nested Vectored Interrupt Controller (NVIC). */ typedef struct { __IO uint32_t ISER[1]; /*!< Offset: 0x000 (R/W) Interrupt Set Enable Register */ uint32_t RESERVED0[31]; __IO uint32_t ICER[1]; /*!< Offset: 0x080 (R/W) Interrupt Clear Enable Register */ uint32_t RSERVED1[31]; __IO uint32_t ISPR[1]; /*!< Offset: 0x100 (R/W) Interrupt Set Pending Register */ uint32_t RESERVED2[31]; __IO uint32_t ICPR[1]; /*!< Offset: 0x180 (R/W) Interrupt Clear Pending Register */ uint32_t RESERVED3[31]; uint32_t RESERVED4[64]; __IO uint32_t IP[8]; /*!< Offset: 0x300 (R/W) Interrupt Priority Register */ } NVIC_Type; /*@} end of group CMSIS_NVIC */ /** \ingroup CMSIS_core_register \defgroup CMSIS_SCB System Control Block (SCB) \brief Type definitions for the System Control Block Registers @{ */ /** \brief Structure type to access the System Control Block (SCB). */ typedef struct { __I uint32_t CPUID; /*!< Offset: 0x000 (R/ ) CPUID Base Register */ __IO uint32_t ICSR; /*!< Offset: 0x004 (R/W) Interrupt Control and State Register */ __IO uint32_t VTOR; /*!< Offset: 0x008 (R/W) Vector Table Offset Register */ __IO uint32_t AIRCR; /*!< Offset: 0x00C (R/W) Application Interrupt and Reset Control Register */ __IO uint32_t SCR; /*!< Offset: 0x010 (R/W) System Control Register */ __IO uint32_t CCR; /*!< Offset: 0x014 (R/W) Configuration Control Register */ uint32_t RESERVED0[1]; __IO uint32_t SHP[2]; /*!< Offset: 0x01C (R/W) System Handlers Priority Registers. [0] is RESERVED */ __IO uint32_t SHCSR; /*!< Offset: 0x024 (R/W) System Handler Control and State Register */ uint32_t RESERVED1[154]; __IO uint32_t SFCR; /*!< Offset: 0x290 (R/W) Security Features Control Register */ } SCB_Type; /* SCB CPUID Register Definitions */ #define SCB_CPUID_IMPLEMENTER_Pos 24 /*!< SCB CPUID: IMPLEMENTER Position */ #define SCB_CPUID_IMPLEMENTER_Msk (0xFFUL << SCB_CPUID_IMPLEMENTER_Pos) /*!< SCB CPUID: IMPLEMENTER Mask */ #define SCB_CPUID_VARIANT_Pos 20 /*!< SCB CPUID: VARIANT Position */ #define SCB_CPUID_VARIANT_Msk (0xFUL << SCB_CPUID_VARIANT_Pos) /*!< SCB CPUID: VARIANT Mask */ #define SCB_CPUID_ARCHITECTURE_Pos 16 /*!< SCB CPUID: ARCHITECTURE Position */ #define SCB_CPUID_ARCHITECTURE_Msk (0xFUL << SCB_CPUID_ARCHITECTURE_Pos) /*!< SCB CPUID: ARCHITECTURE Mask */ #define SCB_CPUID_PARTNO_Pos 4 /*!< SCB CPUID: PARTNO Position */ #define SCB_CPUID_PARTNO_Msk (0xFFFUL << SCB_CPUID_PARTNO_Pos) /*!< SCB CPUID: PARTNO Mask */ #define SCB_CPUID_REVISION_Pos 0 /*!< SCB CPUID: REVISION Position */ #define SCB_CPUID_REVISION_Msk (0xFUL /*<< SCB_CPUID_REVISION_Pos*/) /*!< SCB CPUID: REVISION Mask */ /* SCB Interrupt Control State Register Definitions */ #define SCB_ICSR_NMIPENDSET_Pos 31 /*!< SCB ICSR: NMIPENDSET Position */ #define SCB_ICSR_NMIPENDSET_Msk (1UL << SCB_ICSR_NMIPENDSET_Pos) /*!< SCB ICSR: NMIPENDSET Mask */ #define SCB_ICSR_PENDSVSET_Pos 28 /*!< SCB ICSR: PENDSVSET Position */ #define SCB_ICSR_PENDSVSET_Msk (1UL << SCB_ICSR_PENDSVSET_Pos) /*!< SCB ICSR: PENDSVSET Mask */ #define SCB_ICSR_PENDSVCLR_Pos 27 /*!< SCB ICSR: PENDSVCLR Position */ #define SCB_ICSR_PENDSVCLR_Msk (1UL << SCB_ICSR_PENDSVCLR_Pos) /*!< SCB ICSR: PENDSVCLR Mask */ #define SCB_ICSR_PENDSTSET_Pos 26 /*!< SCB ICSR: PENDSTSET Position */ #define SCB_ICSR_PENDSTSET_Msk (1UL << SCB_ICSR_PENDSTSET_Pos) /*!< SCB ICSR: PENDSTSET Mask */ #define SCB_ICSR_PENDSTCLR_Pos 25 /*!< SCB ICSR: PENDSTCLR Position */ #define SCB_ICSR_PENDSTCLR_Msk (1UL << SCB_ICSR_PENDSTCLR_Pos) /*!< SCB ICSR: PENDSTCLR Mask */ #define SCB_ICSR_ISRPREEMPT_Pos 23 /*!< SCB ICSR: ISRPREEMPT Position */ #define SCB_ICSR_ISRPREEMPT_Msk (1UL << SCB_ICSR_ISRPREEMPT_Pos) /*!< SCB ICSR: ISRPREEMPT Mask */ #define SCB_ICSR_ISRPENDING_Pos 22 /*!< SCB ICSR: ISRPENDING Position */ #define SCB_ICSR_ISRPENDING_Msk (1UL << SCB_ICSR_ISRPENDING_Pos) /*!< SCB ICSR: ISRPENDING Mask */ #define SCB_ICSR_VECTPENDING_Pos 12 /*!< SCB ICSR: VECTPENDING Position */ #define SCB_ICSR_VECTPENDING_Msk (0x1FFUL << SCB_ICSR_VECTPENDING_Pos) /*!< SCB ICSR: VECTPENDING Mask */ #define SCB_ICSR_VECTACTIVE_Pos 0 /*!< SCB ICSR: VECTACTIVE Position */ #define SCB_ICSR_VECTACTIVE_Msk (0x1FFUL /*<< SCB_ICSR_VECTACTIVE_Pos*/) /*!< SCB ICSR: VECTACTIVE Mask */ /* SCB Interrupt Control State Register Definitions */ #define SCB_VTOR_TBLOFF_Pos 7 /*!< SCB VTOR: TBLOFF Position */ #define SCB_VTOR_TBLOFF_Msk (0x1FFFFFFUL << SCB_VTOR_TBLOFF_Pos) /*!< SCB VTOR: TBLOFF Mask */ /* SCB Application Interrupt and Reset Control Register Definitions */ #define SCB_AIRCR_VECTKEY_Pos 16 /*!< SCB AIRCR: VECTKEY Position */ #define SCB_AIRCR_VECTKEY_Msk (0xFFFFUL << SCB_AIRCR_VECTKEY_Pos) /*!< SCB AIRCR: VECTKEY Mask */ #define SCB_AIRCR_VECTKEYSTAT_Pos 16 /*!< SCB AIRCR: VECTKEYSTAT Position */ #define SCB_AIRCR_VECTKEYSTAT_Msk (0xFFFFUL << SCB_AIRCR_VECTKEYSTAT_Pos) /*!< SCB AIRCR: VECTKEYSTAT Mask */ #define SCB_AIRCR_ENDIANESS_Pos 15 /*!< SCB AIRCR: ENDIANESS Position */ #define SCB_AIRCR_ENDIANESS_Msk (1UL << SCB_AIRCR_ENDIANESS_Pos) /*!< SCB AIRCR: ENDIANESS Mask */ #define SCB_AIRCR_SYSRESETREQ_Pos 2 /*!< SCB AIRCR: SYSRESETREQ Position */ #define SCB_AIRCR_SYSRESETREQ_Msk (1UL << SCB_AIRCR_SYSRESETREQ_Pos) /*!< SCB AIRCR: SYSRESETREQ Mask */ #define SCB_AIRCR_VECTCLRACTIVE_Pos 1 /*!< SCB AIRCR: VECTCLRACTIVE Position */ #define SCB_AIRCR_VECTCLRACTIVE_Msk (1UL << SCB_AIRCR_VECTCLRACTIVE_Pos) /*!< SCB AIRCR: VECTCLRACTIVE Mask */ /* SCB System Control Register Definitions */ #define SCB_SCR_SEVONPEND_Pos 4 /*!< SCB SCR: SEVONPEND Position */ #define SCB_SCR_SEVONPEND_Msk (1UL << SCB_SCR_SEVONPEND_Pos) /*!< SCB SCR: SEVONPEND Mask */ #define SCB_SCR_SLEEPDEEP_Pos 2 /*!< SCB SCR: SLEEPDEEP Position */ #define SCB_SCR_SLEEPDEEP_Msk (1UL << SCB_SCR_SLEEPDEEP_Pos) /*!< SCB SCR: SLEEPDEEP Mask */ #define SCB_SCR_SLEEPONEXIT_Pos 1 /*!< SCB SCR: SLEEPONEXIT Position */ #define SCB_SCR_SLEEPONEXIT_Msk (1UL << SCB_SCR_SLEEPONEXIT_Pos) /*!< SCB SCR: SLEEPONEXIT Mask */ /* SCB Configuration Control Register Definitions */ #define SCB_CCR_STKALIGN_Pos 9 /*!< SCB CCR: STKALIGN Position */ #define SCB_CCR_STKALIGN_Msk (1UL << SCB_CCR_STKALIGN_Pos) /*!< SCB CCR: STKALIGN Mask */ #define SCB_CCR_UNALIGN_TRP_Pos 3 /*!< SCB CCR: UNALIGN_TRP Position */ #define SCB_CCR_UNALIGN_TRP_Msk (1UL << SCB_CCR_UNALIGN_TRP_Pos) /*!< SCB CCR: UNALIGN_TRP Mask */ /* SCB System Handler Control and State Register Definitions */ #define SCB_SHCSR_SVCALLPENDED_Pos 15 /*!< SCB SHCSR: SVCALLPENDED Position */ #define SCB_SHCSR_SVCALLPENDED_Msk (1UL << SCB_SHCSR_SVCALLPENDED_Pos) /*!< SCB SHCSR: SVCALLPENDED Mask */ /*@} end of group CMSIS_SCB */ /** \ingroup CMSIS_core_register \defgroup CMSIS_SCnSCB System Controls not in SCB (SCnSCB) \brief Type definitions for the System Control and ID Register not in the SCB @{ */ /** \brief Structure type to access the System Control and ID Register not in the SCB. */ typedef struct { uint32_t RESERVED0[2]; __IO uint32_t ACTLR; /*!< Offset: 0x008 (R/W) Auxiliary Control Register */ } SCnSCB_Type; /* Auxiliary Control Register Definitions */ #define SCnSCB_ACTLR_DISMCYCINT_Pos 0 /*!< ACTLR: DISMCYCINT Position */ #define SCnSCB_ACTLR_DISMCYCINT_Msk (1UL /*<< SCnSCB_ACTLR_DISMCYCINT_Pos*/) /*!< ACTLR: DISMCYCINT Mask */ /*@} end of group CMSIS_SCnotSCB */ /** \ingroup CMSIS_core_register \defgroup CMSIS_SysTick System Tick Timer (SysTick) \brief Type definitions for the System Timer Registers. @{ */ /** \brief Structure type to access the System Timer (SysTick). */ typedef struct { __IO uint32_t CTRL; /*!< Offset: 0x000 (R/W) SysTick Control and Status Register */ __IO uint32_t LOAD; /*!< Offset: 0x004 (R/W) SysTick Reload Value Register */ __IO uint32_t VAL; /*!< Offset: 0x008 (R/W) SysTick Current Value Register */ __I uint32_t CALIB; /*!< Offset: 0x00C (R/ ) SysTick Calibration Register */ } SysTick_Type; /* SysTick Control / Status Register Definitions */ #define SysTick_CTRL_COUNTFLAG_Pos 16 /*!< SysTick CTRL: COUNTFLAG Position */ #define SysTick_CTRL_COUNTFLAG_Msk (1UL << SysTick_CTRL_COUNTFLAG_Pos) /*!< SysTick CTRL: COUNTFLAG Mask */ #define SysTick_CTRL_CLKSOURCE_Pos 2 /*!< SysTick CTRL: CLKSOURCE Position */ #define SysTick_CTRL_CLKSOURCE_Msk (1UL << SysTick_CTRL_CLKSOURCE_Pos) /*!< SysTick CTRL: CLKSOURCE Mask */ #define SysTick_CTRL_TICKINT_Pos 1 /*!< SysTick CTRL: TICKINT Position */ #define SysTick_CTRL_TICKINT_Msk (1UL << SysTick_CTRL_TICKINT_Pos) /*!< SysTick CTRL: TICKINT Mask */ #define SysTick_CTRL_ENABLE_Pos 0 /*!< SysTick CTRL: ENABLE Position */ #define SysTick_CTRL_ENABLE_Msk (1UL /*<< SysTick_CTRL_ENABLE_Pos*/) /*!< SysTick CTRL: ENABLE Mask */ /* SysTick Reload Register Definitions */ #define SysTick_LOAD_RELOAD_Pos 0 /*!< SysTick LOAD: RELOAD Position */ #define SysTick_LOAD_RELOAD_Msk (0xFFFFFFUL /*<< SysTick_LOAD_RELOAD_Pos*/) /*!< SysTick LOAD: RELOAD Mask */ /* SysTick Current Register Definitions */ #define SysTick_VAL_CURRENT_Pos 0 /*!< SysTick VAL: CURRENT Position */ #define SysTick_VAL_CURRENT_Msk (0xFFFFFFUL /*<< SysTick_VAL_CURRENT_Pos*/) /*!< SysTick VAL: CURRENT Mask */ /* SysTick Calibration Register Definitions */ #define SysTick_CALIB_NOREF_Pos 31 /*!< SysTick CALIB: NOREF Position */ #define SysTick_CALIB_NOREF_Msk (1UL << SysTick_CALIB_NOREF_Pos) /*!< SysTick CALIB: NOREF Mask */ #define SysTick_CALIB_SKEW_Pos 30 /*!< SysTick CALIB: SKEW Position */ #define SysTick_CALIB_SKEW_Msk (1UL << SysTick_CALIB_SKEW_Pos) /*!< SysTick CALIB: SKEW Mask */ #define SysTick_CALIB_TENMS_Pos 0 /*!< SysTick CALIB: TENMS Position */ #define SysTick_CALIB_TENMS_Msk (0xFFFFFFUL /*<< SysTick_CALIB_TENMS_Pos*/) /*!< SysTick CALIB: TENMS Mask */ /*@} end of group CMSIS_SysTick */ #if (__MPU_PRESENT == 1) /** \ingroup CMSIS_core_register \defgroup CMSIS_MPU Memory Protection Unit (MPU) \brief Type definitions for the Memory Protection Unit (MPU) @{ */ /** \brief Structure type to access the Memory Protection Unit (MPU). */ typedef struct { __I uint32_t TYPE; /*!< Offset: 0x000 (R/ ) MPU Type Register */ __IO uint32_t CTRL; /*!< Offset: 0x004 (R/W) MPU Control Register */ __IO uint32_t RNR; /*!< Offset: 0x008 (R/W) MPU Region RNRber Register */ __IO uint32_t RBAR; /*!< Offset: 0x00C (R/W) MPU Region Base Address Register */ __IO uint32_t RASR; /*!< Offset: 0x010 (R/W) MPU Region Attribute and Size Register */ } MPU_Type; /* MPU Type Register */ #define MPU_TYPE_IREGION_Pos 16 /*!< MPU TYPE: IREGION Position */ #define MPU_TYPE_IREGION_Msk (0xFFUL << MPU_TYPE_IREGION_Pos) /*!< MPU TYPE: IREGION Mask */ #define MPU_TYPE_DREGION_Pos 8 /*!< MPU TYPE: DREGION Position */ #define MPU_TYPE_DREGION_Msk (0xFFUL << MPU_TYPE_DREGION_Pos) /*!< MPU TYPE: DREGION Mask */ #define MPU_TYPE_SEPARATE_Pos 0 /*!< MPU TYPE: SEPARATE Position */ #define MPU_TYPE_SEPARATE_Msk (1UL /*<< MPU_TYPE_SEPARATE_Pos*/) /*!< MPU TYPE: SEPARATE Mask */ /* MPU Control Register */ #define MPU_CTRL_PRIVDEFENA_Pos 2 /*!< MPU CTRL: PRIVDEFENA Position */ #define MPU_CTRL_PRIVDEFENA_Msk (1UL << MPU_CTRL_PRIVDEFENA_Pos) /*!< MPU CTRL: PRIVDEFENA Mask */ #define MPU_CTRL_HFNMIENA_Pos 1 /*!< MPU CTRL: HFNMIENA Position */ #define MPU_CTRL_HFNMIENA_Msk (1UL << MPU_CTRL_HFNMIENA_Pos) /*!< MPU CTRL: HFNMIENA Mask */ #define MPU_CTRL_ENABLE_Pos 0 /*!< MPU CTRL: ENABLE Position */ #define MPU_CTRL_ENABLE_Msk (1UL /*<< MPU_CTRL_ENABLE_Pos*/) /*!< MPU CTRL: ENABLE Mask */ /* MPU Region Number Register */ #define MPU_RNR_REGION_Pos 0 /*!< MPU RNR: REGION Position */ #define MPU_RNR_REGION_Msk (0xFFUL /*<< MPU_RNR_REGION_Pos*/) /*!< MPU RNR: REGION Mask */ /* MPU Region Base Address Register */ #define MPU_RBAR_ADDR_Pos 8 /*!< MPU RBAR: ADDR Position */ #define MPU_RBAR_ADDR_Msk (0xFFFFFFUL << MPU_RBAR_ADDR_Pos) /*!< MPU RBAR: ADDR Mask */ #define MPU_RBAR_VALID_Pos 4 /*!< MPU RBAR: VALID Position */ #define MPU_RBAR_VALID_Msk (1UL << MPU_RBAR_VALID_Pos) /*!< MPU RBAR: VALID Mask */ #define MPU_RBAR_REGION_Pos 0 /*!< MPU RBAR: REGION Position */ #define MPU_RBAR_REGION_Msk (0xFUL /*<< MPU_RBAR_REGION_Pos*/) /*!< MPU RBAR: REGION Mask */ /* MPU Region Attribute and Size Register */ #define MPU_RASR_ATTRS_Pos 16 /*!< MPU RASR: MPU Region Attribute field Position */ #define MPU_RASR_ATTRS_Msk (0xFFFFUL << MPU_RASR_ATTRS_Pos) /*!< MPU RASR: MPU Region Attribute field Mask */ #define MPU_RASR_XN_Pos 28 /*!< MPU RASR: ATTRS.XN Position */ #define MPU_RASR_XN_Msk (1UL << MPU_RASR_XN_Pos) /*!< MPU RASR: ATTRS.XN Mask */ #define MPU_RASR_AP_Pos 24 /*!< MPU RASR: ATTRS.AP Position */ #define MPU_RASR_AP_Msk (0x7UL << MPU_RASR_AP_Pos) /*!< MPU RASR: ATTRS.AP Mask */ #define MPU_RASR_TEX_Pos 19 /*!< MPU RASR: ATTRS.TEX Position */ #define MPU_RASR_TEX_Msk (0x7UL << MPU_RASR_TEX_Pos) /*!< MPU RASR: ATTRS.TEX Mask */ #define MPU_RASR_S_Pos 18 /*!< MPU RASR: ATTRS.S Position */ #define MPU_RASR_S_Msk (1UL << MPU_RASR_S_Pos) /*!< MPU RASR: ATTRS.S Mask */ #define MPU_RASR_C_Pos 17 /*!< MPU RASR: ATTRS.C Position */ #define MPU_RASR_C_Msk (1UL << MPU_RASR_C_Pos) /*!< MPU RASR: ATTRS.C Mask */ #define MPU_RASR_B_Pos 16 /*!< MPU RASR: ATTRS.B Position */ #define MPU_RASR_B_Msk (1UL << MPU_RASR_B_Pos) /*!< MPU RASR: ATTRS.B Mask */ #define MPU_RASR_SRD_Pos 8 /*!< MPU RASR: Sub-Region Disable Position */ #define MPU_RASR_SRD_Msk (0xFFUL << MPU_RASR_SRD_Pos) /*!< MPU RASR: Sub-Region Disable Mask */ #define MPU_RASR_SIZE_Pos 1 /*!< MPU RASR: Region Size Field Position */ #define MPU_RASR_SIZE_Msk (0x1FUL << MPU_RASR_SIZE_Pos) /*!< MPU RASR: Region Size Field Mask */ #define MPU_RASR_ENABLE_Pos 0 /*!< MPU RASR: Region enable bit Position */ #define MPU_RASR_ENABLE_Msk (1UL /*<< MPU_RASR_ENABLE_Pos*/) /*!< MPU RASR: Region enable bit Disable Mask */ /*@} end of group CMSIS_MPU */ #endif /** \ingroup CMSIS_core_register \defgroup CMSIS_CoreDebug Core Debug Registers (CoreDebug) \brief SC000 Core Debug Registers (DCB registers, SHCSR, and DFSR) are only accessible over DAP and not via processor. Therefore they are not covered by the Cortex-M0 header file. @{ */ /*@} end of group CMSIS_CoreDebug */ /** \ingroup CMSIS_core_register \defgroup CMSIS_core_base Core Definitions \brief Definitions for base addresses, unions, and structures. @{ */ /* Memory mapping of SC000 Hardware */ #define SCS_BASE (0xE000E000UL) /*!< System Control Space Base Address */ #define SysTick_BASE (SCS_BASE + 0x0010UL) /*!< SysTick Base Address */ #define NVIC_BASE (SCS_BASE + 0x0100UL) /*!< NVIC Base Address */ #define SCB_BASE (SCS_BASE + 0x0D00UL) /*!< System Control Block Base Address */ #define SCnSCB ((SCnSCB_Type *) SCS_BASE ) /*!< System control Register not in SCB */ #define SCB ((SCB_Type *) SCB_BASE ) /*!< SCB configuration struct */ #define SysTick ((SysTick_Type *) SysTick_BASE ) /*!< SysTick configuration struct */ #define NVIC ((NVIC_Type *) NVIC_BASE ) /*!< NVIC configuration struct */ #if (__MPU_PRESENT == 1) #define MPU_BASE (SCS_BASE + 0x0D90UL) /*!< Memory Protection Unit */ #define MPU ((MPU_Type *) MPU_BASE ) /*!< Memory Protection Unit */ #endif /*@} */ /******************************************************************************* * Hardware Abstraction Layer Core Function Interface contains: - Core NVIC Functions - Core SysTick Functions - Core Register Access Functions ******************************************************************************/ /** \defgroup CMSIS_Core_FunctionInterface Functions and Instructions Reference */ /* ########################## NVIC functions #################################### */ /** \ingroup CMSIS_Core_FunctionInterface \defgroup CMSIS_Core_NVICFunctions NVIC Functions \brief Functions that manage interrupts and exceptions via the NVIC. @{ */ /* Interrupt Priorities are WORD accessible only under ARMv6M */ /* The following MACROS handle generation of the register offset and byte masks */ #define _BIT_SHIFT(IRQn) ( ((((uint32_t)(int32_t)(IRQn)) ) & 0x03UL) * 8UL) #define _SHP_IDX(IRQn) ( (((((uint32_t)(int32_t)(IRQn)) & 0x0FUL)-8UL) >> 2UL) ) #define _IP_IDX(IRQn) ( (((uint32_t)(int32_t)(IRQn)) >> 2UL) ) /** \brief Enable External Interrupt The function enables a device-specific interrupt in the NVIC interrupt controller. \param [in] IRQn External interrupt number. Value cannot be negative. */ __STATIC_INLINE void NVIC_EnableIRQ(IRQn_Type IRQn) { NVIC->ISER[0] = (uint32_t)(1UL << (((uint32_t)(int32_t)IRQn) & 0x1FUL)); } /** \brief Disable External Interrupt The function disables a device-specific interrupt in the NVIC interrupt controller. \param [in] IRQn External interrupt number. Value cannot be negative. */ __STATIC_INLINE void NVIC_DisableIRQ(IRQn_Type IRQn) { NVIC->ICER[0] = (uint32_t)(1UL << (((uint32_t)(int32_t)IRQn) & 0x1FUL)); } /** \brief Get Pending Interrupt The function reads the pending register in the NVIC and returns the pending bit for the specified interrupt. \param [in] IRQn Interrupt number. \return 0 Interrupt status is not pending. \return 1 Interrupt status is pending. */ __STATIC_INLINE uint32_t NVIC_GetPendingIRQ(IRQn_Type IRQn) { return((uint32_t)(((NVIC->ISPR[0] & (1UL << (((uint32_t)(int32_t)IRQn) & 0x1FUL))) != 0UL) ? 1UL : 0UL)); } /** \brief Set Pending Interrupt The function sets the pending bit of an external interrupt. \param [in] IRQn Interrupt number. Value cannot be negative. */ __STATIC_INLINE void NVIC_SetPendingIRQ(IRQn_Type IRQn) { NVIC->ISPR[0] = (uint32_t)(1UL << (((uint32_t)(int32_t)IRQn) & 0x1FUL)); } /** \brief Clear Pending Interrupt The function clears the pending bit of an external interrupt. \param [in] IRQn External interrupt number. Value cannot be negative. */ __STATIC_INLINE void NVIC_ClearPendingIRQ(IRQn_Type IRQn) { NVIC->ICPR[0] = (uint32_t)(1UL << (((uint32_t)(int32_t)IRQn) & 0x1FUL)); } /** \brief Set Interrupt Priority The function sets the priority of an interrupt. \note The priority cannot be set for every core interrupt. \param [in] IRQn Interrupt number. \param [in] priority Priority to set. */ __STATIC_INLINE void NVIC_SetPriority(IRQn_Type IRQn, uint32_t priority) { if((int32_t)(IRQn) < 0) { SCB->SHP[_SHP_IDX(IRQn)] = ((uint32_t)(SCB->SHP[_SHP_IDX(IRQn)] & ~(0xFFUL << _BIT_SHIFT(IRQn))) | (((priority << (8 - __NVIC_PRIO_BITS)) & (uint32_t)0xFFUL) << _BIT_SHIFT(IRQn))); } else { NVIC->IP[_IP_IDX(IRQn)] = ((uint32_t)(NVIC->IP[_IP_IDX(IRQn)] & ~(0xFFUL << _BIT_SHIFT(IRQn))) | (((priority << (8 - __NVIC_PRIO_BITS)) & (uint32_t)0xFFUL) << _BIT_SHIFT(IRQn))); } } /** \brief Get Interrupt Priority The function reads the priority of an interrupt. The interrupt number can be positive to specify an external (device specific) interrupt, or negative to specify an internal (core) interrupt. \param [in] IRQn Interrupt number. \return Interrupt Priority. Value is aligned automatically to the implemented priority bits of the microcontroller. */ __STATIC_INLINE uint32_t NVIC_GetPriority(IRQn_Type IRQn) { if((int32_t)(IRQn) < 0) { return((uint32_t)(((SCB->SHP[_SHP_IDX(IRQn)] >> _BIT_SHIFT(IRQn) ) & (uint32_t)0xFFUL) >> (8 - __NVIC_PRIO_BITS))); } else { return((uint32_t)(((NVIC->IP[ _IP_IDX(IRQn)] >> _BIT_SHIFT(IRQn) ) & (uint32_t)0xFFUL) >> (8 - __NVIC_PRIO_BITS))); } } /** \brief System Reset The function initiates a system reset request to reset the MCU. */ __STATIC_INLINE void NVIC_SystemReset(void) { __DSB(); /* Ensure all outstanding memory accesses included buffered write are completed before reset */ SCB->AIRCR = ((0x5FAUL << SCB_AIRCR_VECTKEY_Pos) | SCB_AIRCR_SYSRESETREQ_Msk); __DSB(); /* Ensure completion of memory access */ while(1) { __NOP(); } /* wait until reset */ } /*@} end of CMSIS_Core_NVICFunctions */ /* ################################## SysTick function ############################################ */ /** \ingroup CMSIS_Core_FunctionInterface \defgroup CMSIS_Core_SysTickFunctions SysTick Functions \brief Functions that configure the System. @{ */ #if (__Vendor_SysTickConfig == 0) /** \brief System Tick Configuration The function initializes the System Timer and its interrupt, and starts the System Tick Timer. Counter is in free running mode to generate periodic interrupts. \param [in] ticks Number of ticks between two interrupts. \return 0 Function succeeded. \return 1 Function failed. \note When the variable __Vendor_SysTickConfig is set to 1, then the function SysTick_Config is not included. In this case, the file device.h must contain a vendor-specific implementation of this function. */ __STATIC_INLINE uint32_t SysTick_Config(uint32_t ticks) { if ((ticks - 1UL) > SysTick_LOAD_RELOAD_Msk) {return (1UL);} /* Reload value impossible */ SysTick->LOAD = (uint32_t)(ticks - 1UL); /* set reload register */ NVIC_SetPriority (SysTick_IRQn, (1UL << __NVIC_PRIO_BITS) - 1UL); /* set Priority for Systick Interrupt */ SysTick->VAL = 0UL; /* Load the SysTick Counter Value */ SysTick->CTRL = SysTick_CTRL_CLKSOURCE_Msk | SysTick_CTRL_TICKINT_Msk | SysTick_CTRL_ENABLE_Msk; /* Enable SysTick IRQ and SysTick Timer */ return (0UL); /* Function successful */ } #endif /*@} end of CMSIS_Core_SysTickFunctions */ #ifdef __cplusplus } #endif #endif /* __CORE_SC000_H_DEPENDANT */ #endif /* __CMSIS_GENERIC */ ================================================ FILE: Zelig/mbed/TARGET_NUCLEO_F401RE/core_sc300.h ================================================ /**************************************************************************//** * @file core_sc300.h * @brief CMSIS SC300 Core Peripheral Access Layer Header File * @version V4.10 * @date 18. March 2015 * * @note * ******************************************************************************/ /* Copyright (c) 2009 - 2015 ARM LIMITED All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: - Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. - Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. - Neither the name of ARM 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 COPYRIGHT HOLDERS AND 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. ---------------------------------------------------------------------------*/ #if defined ( __ICCARM__ ) #pragma system_include /* treat file as system include file for MISRA check */ #endif #ifndef __CORE_SC300_H_GENERIC #define __CORE_SC300_H_GENERIC #ifdef __cplusplus extern "C" { #endif /** \page CMSIS_MISRA_Exceptions MISRA-C:2004 Compliance Exceptions CMSIS violates the following MISRA-C:2004 rules: \li Required Rule 8.5, object/function definition in header file.
Function definitions in header files are used to allow 'inlining'. \li Required Rule 18.4, declaration of union type or object of union type: '{...}'.
Unions are used for effective representation of core registers. \li Advisory Rule 19.7, Function-like macro defined.
Function-like macros are used to allow more efficient code. */ /******************************************************************************* * CMSIS definitions ******************************************************************************/ /** \ingroup SC3000 @{ */ /* CMSIS SC300 definitions */ #define __SC300_CMSIS_VERSION_MAIN (0x04) /*!< [31:16] CMSIS HAL main version */ #define __SC300_CMSIS_VERSION_SUB (0x00) /*!< [15:0] CMSIS HAL sub version */ #define __SC300_CMSIS_VERSION ((__SC300_CMSIS_VERSION_MAIN << 16) | \ __SC300_CMSIS_VERSION_SUB ) /*!< CMSIS HAL version number */ #define __CORTEX_SC (300) /*!< Cortex secure core */ #if defined ( __CC_ARM ) #define __ASM __asm /*!< asm keyword for ARM Compiler */ #define __INLINE __inline /*!< inline keyword for ARM Compiler */ #define __STATIC_INLINE static __inline #elif defined ( __GNUC__ ) #define __ASM __asm /*!< asm keyword for GNU Compiler */ #define __INLINE inline /*!< inline keyword for GNU Compiler */ #define __STATIC_INLINE static inline #elif defined ( __ICCARM__ ) #define __ASM __asm /*!< asm keyword for IAR Compiler */ #define __INLINE inline /*!< inline keyword for IAR Compiler. Only available in High optimization mode! */ #define __STATIC_INLINE static inline #elif defined ( __TMS470__ ) #define __ASM __asm /*!< asm keyword for TI CCS Compiler */ #define __STATIC_INLINE static inline #elif defined ( __TASKING__ ) #define __ASM __asm /*!< asm keyword for TASKING Compiler */ #define __INLINE inline /*!< inline keyword for TASKING Compiler */ #define __STATIC_INLINE static inline #elif defined ( __CSMC__ ) #define __packed #define __ASM _asm /*!< asm keyword for COSMIC Compiler */ #define __INLINE inline /*use -pc99 on compile line !< inline keyword for COSMIC Compiler */ #define __STATIC_INLINE static inline #endif /** __FPU_USED indicates whether an FPU is used or not. This core does not support an FPU at all */ #define __FPU_USED 0 #if defined ( __CC_ARM ) #if defined __TARGET_FPU_VFP #warning "Compiler generates FPU instructions for a device without an FPU (check __FPU_PRESENT)" #endif #elif defined ( __GNUC__ ) #if defined (__VFP_FP__) && !defined(__SOFTFP__) #warning "Compiler generates FPU instructions for a device without an FPU (check __FPU_PRESENT)" #endif #elif defined ( __ICCARM__ ) #if defined __ARMVFP__ #warning "Compiler generates FPU instructions for a device without an FPU (check __FPU_PRESENT)" #endif #elif defined ( __TMS470__ ) #if defined __TI__VFP_SUPPORT____ #warning "Compiler generates FPU instructions for a device without an FPU (check __FPU_PRESENT)" #endif #elif defined ( __TASKING__ ) #if defined __FPU_VFP__ #error "Compiler generates FPU instructions for a device without an FPU (check __FPU_PRESENT)" #endif #elif defined ( __CSMC__ ) /* Cosmic */ #if ( __CSMC__ & 0x400) // FPU present for parser #error "Compiler generates FPU instructions for a device without an FPU (check __FPU_PRESENT)" #endif #endif #include /* standard types definitions */ #include /* Core Instruction Access */ #include /* Core Function Access */ #ifdef __cplusplus } #endif #endif /* __CORE_SC300_H_GENERIC */ #ifndef __CMSIS_GENERIC #ifndef __CORE_SC300_H_DEPENDANT #define __CORE_SC300_H_DEPENDANT #ifdef __cplusplus extern "C" { #endif /* check device defines and use defaults */ #if defined __CHECK_DEVICE_DEFINES #ifndef __SC300_REV #define __SC300_REV 0x0000 #warning "__SC300_REV not defined in device header file; using default!" #endif #ifndef __MPU_PRESENT #define __MPU_PRESENT 0 #warning "__MPU_PRESENT not defined in device header file; using default!" #endif #ifndef __NVIC_PRIO_BITS #define __NVIC_PRIO_BITS 4 #warning "__NVIC_PRIO_BITS not defined in device header file; using default!" #endif #ifndef __Vendor_SysTickConfig #define __Vendor_SysTickConfig 0 #warning "__Vendor_SysTickConfig not defined in device header file; using default!" #endif #endif /* IO definitions (access restrictions to peripheral registers) */ /** \defgroup CMSIS_glob_defs CMSIS Global Defines IO Type Qualifiers are used \li to specify the access to peripheral variables. \li for automatic generation of peripheral register debug information. */ #ifdef __cplusplus #define __I volatile /*!< Defines 'read only' permissions */ #else #define __I volatile const /*!< Defines 'read only' permissions */ #endif #define __O volatile /*!< Defines 'write only' permissions */ #define __IO volatile /*!< Defines 'read / write' permissions */ /*@} end of group SC300 */ /******************************************************************************* * Register Abstraction Core Register contain: - Core Register - Core NVIC Register - Core SCB Register - Core SysTick Register - Core Debug Register - Core MPU Register ******************************************************************************/ /** \defgroup CMSIS_core_register Defines and Type Definitions \brief Type definitions and defines for Cortex-M processor based devices. */ /** \ingroup CMSIS_core_register \defgroup CMSIS_CORE Status and Control Registers \brief Core Register type definitions. @{ */ /** \brief Union type to access the Application Program Status Register (APSR). */ typedef union { struct { uint32_t _reserved0:27; /*!< bit: 0..26 Reserved */ uint32_t Q:1; /*!< bit: 27 Saturation condition flag */ uint32_t V:1; /*!< bit: 28 Overflow condition code flag */ uint32_t C:1; /*!< bit: 29 Carry condition code flag */ uint32_t Z:1; /*!< bit: 30 Zero condition code flag */ uint32_t N:1; /*!< bit: 31 Negative condition code flag */ } b; /*!< Structure used for bit access */ uint32_t w; /*!< Type used for word access */ } APSR_Type; /* APSR Register Definitions */ #define APSR_N_Pos 31 /*!< APSR: N Position */ #define APSR_N_Msk (1UL << APSR_N_Pos) /*!< APSR: N Mask */ #define APSR_Z_Pos 30 /*!< APSR: Z Position */ #define APSR_Z_Msk (1UL << APSR_Z_Pos) /*!< APSR: Z Mask */ #define APSR_C_Pos 29 /*!< APSR: C Position */ #define APSR_C_Msk (1UL << APSR_C_Pos) /*!< APSR: C Mask */ #define APSR_V_Pos 28 /*!< APSR: V Position */ #define APSR_V_Msk (1UL << APSR_V_Pos) /*!< APSR: V Mask */ #define APSR_Q_Pos 27 /*!< APSR: Q Position */ #define APSR_Q_Msk (1UL << APSR_Q_Pos) /*!< APSR: Q Mask */ /** \brief Union type to access the Interrupt Program Status Register (IPSR). */ typedef union { struct { uint32_t ISR:9; /*!< bit: 0.. 8 Exception number */ uint32_t _reserved0:23; /*!< bit: 9..31 Reserved */ } b; /*!< Structure used for bit access */ uint32_t w; /*!< Type used for word access */ } IPSR_Type; /* IPSR Register Definitions */ #define IPSR_ISR_Pos 0 /*!< IPSR: ISR Position */ #define IPSR_ISR_Msk (0x1FFUL /*<< IPSR_ISR_Pos*/) /*!< IPSR: ISR Mask */ /** \brief Union type to access the Special-Purpose Program Status Registers (xPSR). */ typedef union { struct { uint32_t ISR:9; /*!< bit: 0.. 8 Exception number */ uint32_t _reserved0:15; /*!< bit: 9..23 Reserved */ uint32_t T:1; /*!< bit: 24 Thumb bit (read 0) */ uint32_t IT:2; /*!< bit: 25..26 saved IT state (read 0) */ uint32_t Q:1; /*!< bit: 27 Saturation condition flag */ uint32_t V:1; /*!< bit: 28 Overflow condition code flag */ uint32_t C:1; /*!< bit: 29 Carry condition code flag */ uint32_t Z:1; /*!< bit: 30 Zero condition code flag */ uint32_t N:1; /*!< bit: 31 Negative condition code flag */ } b; /*!< Structure used for bit access */ uint32_t w; /*!< Type used for word access */ } xPSR_Type; /* xPSR Register Definitions */ #define xPSR_N_Pos 31 /*!< xPSR: N Position */ #define xPSR_N_Msk (1UL << xPSR_N_Pos) /*!< xPSR: N Mask */ #define xPSR_Z_Pos 30 /*!< xPSR: Z Position */ #define xPSR_Z_Msk (1UL << xPSR_Z_Pos) /*!< xPSR: Z Mask */ #define xPSR_C_Pos 29 /*!< xPSR: C Position */ #define xPSR_C_Msk (1UL << xPSR_C_Pos) /*!< xPSR: C Mask */ #define xPSR_V_Pos 28 /*!< xPSR: V Position */ #define xPSR_V_Msk (1UL << xPSR_V_Pos) /*!< xPSR: V Mask */ #define xPSR_Q_Pos 27 /*!< xPSR: Q Position */ #define xPSR_Q_Msk (1UL << xPSR_Q_Pos) /*!< xPSR: Q Mask */ #define xPSR_IT_Pos 25 /*!< xPSR: IT Position */ #define xPSR_IT_Msk (3UL << xPSR_IT_Pos) /*!< xPSR: IT Mask */ #define xPSR_T_Pos 24 /*!< xPSR: T Position */ #define xPSR_T_Msk (1UL << xPSR_T_Pos) /*!< xPSR: T Mask */ #define xPSR_ISR_Pos 0 /*!< xPSR: ISR Position */ #define xPSR_ISR_Msk (0x1FFUL /*<< xPSR_ISR_Pos*/) /*!< xPSR: ISR Mask */ /** \brief Union type to access the Control Registers (CONTROL). */ typedef union { struct { uint32_t nPRIV:1; /*!< bit: 0 Execution privilege in Thread mode */ uint32_t SPSEL:1; /*!< bit: 1 Stack to be used */ uint32_t _reserved1:30; /*!< bit: 2..31 Reserved */ } b; /*!< Structure used for bit access */ uint32_t w; /*!< Type used for word access */ } CONTROL_Type; /* CONTROL Register Definitions */ #define CONTROL_SPSEL_Pos 1 /*!< CONTROL: SPSEL Position */ #define CONTROL_SPSEL_Msk (1UL << CONTROL_SPSEL_Pos) /*!< CONTROL: SPSEL Mask */ #define CONTROL_nPRIV_Pos 0 /*!< CONTROL: nPRIV Position */ #define CONTROL_nPRIV_Msk (1UL /*<< CONTROL_nPRIV_Pos*/) /*!< CONTROL: nPRIV Mask */ /*@} end of group CMSIS_CORE */ /** \ingroup CMSIS_core_register \defgroup CMSIS_NVIC Nested Vectored Interrupt Controller (NVIC) \brief Type definitions for the NVIC Registers @{ */ /** \brief Structure type to access the Nested Vectored Interrupt Controller (NVIC). */ typedef struct { __IO uint32_t ISER[8]; /*!< Offset: 0x000 (R/W) Interrupt Set Enable Register */ uint32_t RESERVED0[24]; __IO uint32_t ICER[8]; /*!< Offset: 0x080 (R/W) Interrupt Clear Enable Register */ uint32_t RSERVED1[24]; __IO uint32_t ISPR[8]; /*!< Offset: 0x100 (R/W) Interrupt Set Pending Register */ uint32_t RESERVED2[24]; __IO uint32_t ICPR[8]; /*!< Offset: 0x180 (R/W) Interrupt Clear Pending Register */ uint32_t RESERVED3[24]; __IO uint32_t IABR[8]; /*!< Offset: 0x200 (R/W) Interrupt Active bit Register */ uint32_t RESERVED4[56]; __IO uint8_t IP[240]; /*!< Offset: 0x300 (R/W) Interrupt Priority Register (8Bit wide) */ uint32_t RESERVED5[644]; __O uint32_t STIR; /*!< Offset: 0xE00 ( /W) Software Trigger Interrupt Register */ } NVIC_Type; /* Software Triggered Interrupt Register Definitions */ #define NVIC_STIR_INTID_Pos 0 /*!< STIR: INTLINESNUM Position */ #define NVIC_STIR_INTID_Msk (0x1FFUL /*<< NVIC_STIR_INTID_Pos*/) /*!< STIR: INTLINESNUM Mask */ /*@} end of group CMSIS_NVIC */ /** \ingroup CMSIS_core_register \defgroup CMSIS_SCB System Control Block (SCB) \brief Type definitions for the System Control Block Registers @{ */ /** \brief Structure type to access the System Control Block (SCB). */ typedef struct { __I uint32_t CPUID; /*!< Offset: 0x000 (R/ ) CPUID Base Register */ __IO uint32_t ICSR; /*!< Offset: 0x004 (R/W) Interrupt Control and State Register */ __IO uint32_t VTOR; /*!< Offset: 0x008 (R/W) Vector Table Offset Register */ __IO uint32_t AIRCR; /*!< Offset: 0x00C (R/W) Application Interrupt and Reset Control Register */ __IO uint32_t SCR; /*!< Offset: 0x010 (R/W) System Control Register */ __IO uint32_t CCR; /*!< Offset: 0x014 (R/W) Configuration Control Register */ __IO uint8_t SHP[12]; /*!< Offset: 0x018 (R/W) System Handlers Priority Registers (4-7, 8-11, 12-15) */ __IO uint32_t SHCSR; /*!< Offset: 0x024 (R/W) System Handler Control and State Register */ __IO uint32_t CFSR; /*!< Offset: 0x028 (R/W) Configurable Fault Status Register */ __IO uint32_t HFSR; /*!< Offset: 0x02C (R/W) HardFault Status Register */ __IO uint32_t DFSR; /*!< Offset: 0x030 (R/W) Debug Fault Status Register */ __IO uint32_t MMFAR; /*!< Offset: 0x034 (R/W) MemManage Fault Address Register */ __IO uint32_t BFAR; /*!< Offset: 0x038 (R/W) BusFault Address Register */ __IO uint32_t AFSR; /*!< Offset: 0x03C (R/W) Auxiliary Fault Status Register */ __I uint32_t PFR[2]; /*!< Offset: 0x040 (R/ ) Processor Feature Register */ __I uint32_t DFR; /*!< Offset: 0x048 (R/ ) Debug Feature Register */ __I uint32_t ADR; /*!< Offset: 0x04C (R/ ) Auxiliary Feature Register */ __I uint32_t MMFR[4]; /*!< Offset: 0x050 (R/ ) Memory Model Feature Register */ __I uint32_t ISAR[5]; /*!< Offset: 0x060 (R/ ) Instruction Set Attributes Register */ uint32_t RESERVED0[5]; __IO uint32_t CPACR; /*!< Offset: 0x088 (R/W) Coprocessor Access Control Register */ uint32_t RESERVED1[129]; __IO uint32_t SFCR; /*!< Offset: 0x290 (R/W) Security Features Control Register */ } SCB_Type; /* SCB CPUID Register Definitions */ #define SCB_CPUID_IMPLEMENTER_Pos 24 /*!< SCB CPUID: IMPLEMENTER Position */ #define SCB_CPUID_IMPLEMENTER_Msk (0xFFUL << SCB_CPUID_IMPLEMENTER_Pos) /*!< SCB CPUID: IMPLEMENTER Mask */ #define SCB_CPUID_VARIANT_Pos 20 /*!< SCB CPUID: VARIANT Position */ #define SCB_CPUID_VARIANT_Msk (0xFUL << SCB_CPUID_VARIANT_Pos) /*!< SCB CPUID: VARIANT Mask */ #define SCB_CPUID_ARCHITECTURE_Pos 16 /*!< SCB CPUID: ARCHITECTURE Position */ #define SCB_CPUID_ARCHITECTURE_Msk (0xFUL << SCB_CPUID_ARCHITECTURE_Pos) /*!< SCB CPUID: ARCHITECTURE Mask */ #define SCB_CPUID_PARTNO_Pos 4 /*!< SCB CPUID: PARTNO Position */ #define SCB_CPUID_PARTNO_Msk (0xFFFUL << SCB_CPUID_PARTNO_Pos) /*!< SCB CPUID: PARTNO Mask */ #define SCB_CPUID_REVISION_Pos 0 /*!< SCB CPUID: REVISION Position */ #define SCB_CPUID_REVISION_Msk (0xFUL /*<< SCB_CPUID_REVISION_Pos*/) /*!< SCB CPUID: REVISION Mask */ /* SCB Interrupt Control State Register Definitions */ #define SCB_ICSR_NMIPENDSET_Pos 31 /*!< SCB ICSR: NMIPENDSET Position */ #define SCB_ICSR_NMIPENDSET_Msk (1UL << SCB_ICSR_NMIPENDSET_Pos) /*!< SCB ICSR: NMIPENDSET Mask */ #define SCB_ICSR_PENDSVSET_Pos 28 /*!< SCB ICSR: PENDSVSET Position */ #define SCB_ICSR_PENDSVSET_Msk (1UL << SCB_ICSR_PENDSVSET_Pos) /*!< SCB ICSR: PENDSVSET Mask */ #define SCB_ICSR_PENDSVCLR_Pos 27 /*!< SCB ICSR: PENDSVCLR Position */ #define SCB_ICSR_PENDSVCLR_Msk (1UL << SCB_ICSR_PENDSVCLR_Pos) /*!< SCB ICSR: PENDSVCLR Mask */ #define SCB_ICSR_PENDSTSET_Pos 26 /*!< SCB ICSR: PENDSTSET Position */ #define SCB_ICSR_PENDSTSET_Msk (1UL << SCB_ICSR_PENDSTSET_Pos) /*!< SCB ICSR: PENDSTSET Mask */ #define SCB_ICSR_PENDSTCLR_Pos 25 /*!< SCB ICSR: PENDSTCLR Position */ #define SCB_ICSR_PENDSTCLR_Msk (1UL << SCB_ICSR_PENDSTCLR_Pos) /*!< SCB ICSR: PENDSTCLR Mask */ #define SCB_ICSR_ISRPREEMPT_Pos 23 /*!< SCB ICSR: ISRPREEMPT Position */ #define SCB_ICSR_ISRPREEMPT_Msk (1UL << SCB_ICSR_ISRPREEMPT_Pos) /*!< SCB ICSR: ISRPREEMPT Mask */ #define SCB_ICSR_ISRPENDING_Pos 22 /*!< SCB ICSR: ISRPENDING Position */ #define SCB_ICSR_ISRPENDING_Msk (1UL << SCB_ICSR_ISRPENDING_Pos) /*!< SCB ICSR: ISRPENDING Mask */ #define SCB_ICSR_VECTPENDING_Pos 12 /*!< SCB ICSR: VECTPENDING Position */ #define SCB_ICSR_VECTPENDING_Msk (0x1FFUL << SCB_ICSR_VECTPENDING_Pos) /*!< SCB ICSR: VECTPENDING Mask */ #define SCB_ICSR_RETTOBASE_Pos 11 /*!< SCB ICSR: RETTOBASE Position */ #define SCB_ICSR_RETTOBASE_Msk (1UL << SCB_ICSR_RETTOBASE_Pos) /*!< SCB ICSR: RETTOBASE Mask */ #define SCB_ICSR_VECTACTIVE_Pos 0 /*!< SCB ICSR: VECTACTIVE Position */ #define SCB_ICSR_VECTACTIVE_Msk (0x1FFUL /*<< SCB_ICSR_VECTACTIVE_Pos*/) /*!< SCB ICSR: VECTACTIVE Mask */ /* SCB Vector Table Offset Register Definitions */ #define SCB_VTOR_TBLBASE_Pos 29 /*!< SCB VTOR: TBLBASE Position */ #define SCB_VTOR_TBLBASE_Msk (1UL << SCB_VTOR_TBLBASE_Pos) /*!< SCB VTOR: TBLBASE Mask */ #define SCB_VTOR_TBLOFF_Pos 7 /*!< SCB VTOR: TBLOFF Position */ #define SCB_VTOR_TBLOFF_Msk (0x3FFFFFUL << SCB_VTOR_TBLOFF_Pos) /*!< SCB VTOR: TBLOFF Mask */ /* SCB Application Interrupt and Reset Control Register Definitions */ #define SCB_AIRCR_VECTKEY_Pos 16 /*!< SCB AIRCR: VECTKEY Position */ #define SCB_AIRCR_VECTKEY_Msk (0xFFFFUL << SCB_AIRCR_VECTKEY_Pos) /*!< SCB AIRCR: VECTKEY Mask */ #define SCB_AIRCR_VECTKEYSTAT_Pos 16 /*!< SCB AIRCR: VECTKEYSTAT Position */ #define SCB_AIRCR_VECTKEYSTAT_Msk (0xFFFFUL << SCB_AIRCR_VECTKEYSTAT_Pos) /*!< SCB AIRCR: VECTKEYSTAT Mask */ #define SCB_AIRCR_ENDIANESS_Pos 15 /*!< SCB AIRCR: ENDIANESS Position */ #define SCB_AIRCR_ENDIANESS_Msk (1UL << SCB_AIRCR_ENDIANESS_Pos) /*!< SCB AIRCR: ENDIANESS Mask */ #define SCB_AIRCR_PRIGROUP_Pos 8 /*!< SCB AIRCR: PRIGROUP Position */ #define SCB_AIRCR_PRIGROUP_Msk (7UL << SCB_AIRCR_PRIGROUP_Pos) /*!< SCB AIRCR: PRIGROUP Mask */ #define SCB_AIRCR_SYSRESETREQ_Pos 2 /*!< SCB AIRCR: SYSRESETREQ Position */ #define SCB_AIRCR_SYSRESETREQ_Msk (1UL << SCB_AIRCR_SYSRESETREQ_Pos) /*!< SCB AIRCR: SYSRESETREQ Mask */ #define SCB_AIRCR_VECTCLRACTIVE_Pos 1 /*!< SCB AIRCR: VECTCLRACTIVE Position */ #define SCB_AIRCR_VECTCLRACTIVE_Msk (1UL << SCB_AIRCR_VECTCLRACTIVE_Pos) /*!< SCB AIRCR: VECTCLRACTIVE Mask */ #define SCB_AIRCR_VECTRESET_Pos 0 /*!< SCB AIRCR: VECTRESET Position */ #define SCB_AIRCR_VECTRESET_Msk (1UL /*<< SCB_AIRCR_VECTRESET_Pos*/) /*!< SCB AIRCR: VECTRESET Mask */ /* SCB System Control Register Definitions */ #define SCB_SCR_SEVONPEND_Pos 4 /*!< SCB SCR: SEVONPEND Position */ #define SCB_SCR_SEVONPEND_Msk (1UL << SCB_SCR_SEVONPEND_Pos) /*!< SCB SCR: SEVONPEND Mask */ #define SCB_SCR_SLEEPDEEP_Pos 2 /*!< SCB SCR: SLEEPDEEP Position */ #define SCB_SCR_SLEEPDEEP_Msk (1UL << SCB_SCR_SLEEPDEEP_Pos) /*!< SCB SCR: SLEEPDEEP Mask */ #define SCB_SCR_SLEEPONEXIT_Pos 1 /*!< SCB SCR: SLEEPONEXIT Position */ #define SCB_SCR_SLEEPONEXIT_Msk (1UL << SCB_SCR_SLEEPONEXIT_Pos) /*!< SCB SCR: SLEEPONEXIT Mask */ /* SCB Configuration Control Register Definitions */ #define SCB_CCR_STKALIGN_Pos 9 /*!< SCB CCR: STKALIGN Position */ #define SCB_CCR_STKALIGN_Msk (1UL << SCB_CCR_STKALIGN_Pos) /*!< SCB CCR: STKALIGN Mask */ #define SCB_CCR_BFHFNMIGN_Pos 8 /*!< SCB CCR: BFHFNMIGN Position */ #define SCB_CCR_BFHFNMIGN_Msk (1UL << SCB_CCR_BFHFNMIGN_Pos) /*!< SCB CCR: BFHFNMIGN Mask */ #define SCB_CCR_DIV_0_TRP_Pos 4 /*!< SCB CCR: DIV_0_TRP Position */ #define SCB_CCR_DIV_0_TRP_Msk (1UL << SCB_CCR_DIV_0_TRP_Pos) /*!< SCB CCR: DIV_0_TRP Mask */ #define SCB_CCR_UNALIGN_TRP_Pos 3 /*!< SCB CCR: UNALIGN_TRP Position */ #define SCB_CCR_UNALIGN_TRP_Msk (1UL << SCB_CCR_UNALIGN_TRP_Pos) /*!< SCB CCR: UNALIGN_TRP Mask */ #define SCB_CCR_USERSETMPEND_Pos 1 /*!< SCB CCR: USERSETMPEND Position */ #define SCB_CCR_USERSETMPEND_Msk (1UL << SCB_CCR_USERSETMPEND_Pos) /*!< SCB CCR: USERSETMPEND Mask */ #define SCB_CCR_NONBASETHRDENA_Pos 0 /*!< SCB CCR: NONBASETHRDENA Position */ #define SCB_CCR_NONBASETHRDENA_Msk (1UL /*<< SCB_CCR_NONBASETHRDENA_Pos*/) /*!< SCB CCR: NONBASETHRDENA Mask */ /* SCB System Handler Control and State Register Definitions */ #define SCB_SHCSR_USGFAULTENA_Pos 18 /*!< SCB SHCSR: USGFAULTENA Position */ #define SCB_SHCSR_USGFAULTENA_Msk (1UL << SCB_SHCSR_USGFAULTENA_Pos) /*!< SCB SHCSR: USGFAULTENA Mask */ #define SCB_SHCSR_BUSFAULTENA_Pos 17 /*!< SCB SHCSR: BUSFAULTENA Position */ #define SCB_SHCSR_BUSFAULTENA_Msk (1UL << SCB_SHCSR_BUSFAULTENA_Pos) /*!< SCB SHCSR: BUSFAULTENA Mask */ #define SCB_SHCSR_MEMFAULTENA_Pos 16 /*!< SCB SHCSR: MEMFAULTENA Position */ #define SCB_SHCSR_MEMFAULTENA_Msk (1UL << SCB_SHCSR_MEMFAULTENA_Pos) /*!< SCB SHCSR: MEMFAULTENA Mask */ #define SCB_SHCSR_SVCALLPENDED_Pos 15 /*!< SCB SHCSR: SVCALLPENDED Position */ #define SCB_SHCSR_SVCALLPENDED_Msk (1UL << SCB_SHCSR_SVCALLPENDED_Pos) /*!< SCB SHCSR: SVCALLPENDED Mask */ #define SCB_SHCSR_BUSFAULTPENDED_Pos 14 /*!< SCB SHCSR: BUSFAULTPENDED Position */ #define SCB_SHCSR_BUSFAULTPENDED_Msk (1UL << SCB_SHCSR_BUSFAULTPENDED_Pos) /*!< SCB SHCSR: BUSFAULTPENDED Mask */ #define SCB_SHCSR_MEMFAULTPENDED_Pos 13 /*!< SCB SHCSR: MEMFAULTPENDED Position */ #define SCB_SHCSR_MEMFAULTPENDED_Msk (1UL << SCB_SHCSR_MEMFAULTPENDED_Pos) /*!< SCB SHCSR: MEMFAULTPENDED Mask */ #define SCB_SHCSR_USGFAULTPENDED_Pos 12 /*!< SCB SHCSR: USGFAULTPENDED Position */ #define SCB_SHCSR_USGFAULTPENDED_Msk (1UL << SCB_SHCSR_USGFAULTPENDED_Pos) /*!< SCB SHCSR: USGFAULTPENDED Mask */ #define SCB_SHCSR_SYSTICKACT_Pos 11 /*!< SCB SHCSR: SYSTICKACT Position */ #define SCB_SHCSR_SYSTICKACT_Msk (1UL << SCB_SHCSR_SYSTICKACT_Pos) /*!< SCB SHCSR: SYSTICKACT Mask */ #define SCB_SHCSR_PENDSVACT_Pos 10 /*!< SCB SHCSR: PENDSVACT Position */ #define SCB_SHCSR_PENDSVACT_Msk (1UL << SCB_SHCSR_PENDSVACT_Pos) /*!< SCB SHCSR: PENDSVACT Mask */ #define SCB_SHCSR_MONITORACT_Pos 8 /*!< SCB SHCSR: MONITORACT Position */ #define SCB_SHCSR_MONITORACT_Msk (1UL << SCB_SHCSR_MONITORACT_Pos) /*!< SCB SHCSR: MONITORACT Mask */ #define SCB_SHCSR_SVCALLACT_Pos 7 /*!< SCB SHCSR: SVCALLACT Position */ #define SCB_SHCSR_SVCALLACT_Msk (1UL << SCB_SHCSR_SVCALLACT_Pos) /*!< SCB SHCSR: SVCALLACT Mask */ #define SCB_SHCSR_USGFAULTACT_Pos 3 /*!< SCB SHCSR: USGFAULTACT Position */ #define SCB_SHCSR_USGFAULTACT_Msk (1UL << SCB_SHCSR_USGFAULTACT_Pos) /*!< SCB SHCSR: USGFAULTACT Mask */ #define SCB_SHCSR_BUSFAULTACT_Pos 1 /*!< SCB SHCSR: BUSFAULTACT Position */ #define SCB_SHCSR_BUSFAULTACT_Msk (1UL << SCB_SHCSR_BUSFAULTACT_Pos) /*!< SCB SHCSR: BUSFAULTACT Mask */ #define SCB_SHCSR_MEMFAULTACT_Pos 0 /*!< SCB SHCSR: MEMFAULTACT Position */ #define SCB_SHCSR_MEMFAULTACT_Msk (1UL /*<< SCB_SHCSR_MEMFAULTACT_Pos*/) /*!< SCB SHCSR: MEMFAULTACT Mask */ /* SCB Configurable Fault Status Registers Definitions */ #define SCB_CFSR_USGFAULTSR_Pos 16 /*!< SCB CFSR: Usage Fault Status Register Position */ #define SCB_CFSR_USGFAULTSR_Msk (0xFFFFUL << SCB_CFSR_USGFAULTSR_Pos) /*!< SCB CFSR: Usage Fault Status Register Mask */ #define SCB_CFSR_BUSFAULTSR_Pos 8 /*!< SCB CFSR: Bus Fault Status Register Position */ #define SCB_CFSR_BUSFAULTSR_Msk (0xFFUL << SCB_CFSR_BUSFAULTSR_Pos) /*!< SCB CFSR: Bus Fault Status Register Mask */ #define SCB_CFSR_MEMFAULTSR_Pos 0 /*!< SCB CFSR: Memory Manage Fault Status Register Position */ #define SCB_CFSR_MEMFAULTSR_Msk (0xFFUL /*<< SCB_CFSR_MEMFAULTSR_Pos*/) /*!< SCB CFSR: Memory Manage Fault Status Register Mask */ /* SCB Hard Fault Status Registers Definitions */ #define SCB_HFSR_DEBUGEVT_Pos 31 /*!< SCB HFSR: DEBUGEVT Position */ #define SCB_HFSR_DEBUGEVT_Msk (1UL << SCB_HFSR_DEBUGEVT_Pos) /*!< SCB HFSR: DEBUGEVT Mask */ #define SCB_HFSR_FORCED_Pos 30 /*!< SCB HFSR: FORCED Position */ #define SCB_HFSR_FORCED_Msk (1UL << SCB_HFSR_FORCED_Pos) /*!< SCB HFSR: FORCED Mask */ #define SCB_HFSR_VECTTBL_Pos 1 /*!< SCB HFSR: VECTTBL Position */ #define SCB_HFSR_VECTTBL_Msk (1UL << SCB_HFSR_VECTTBL_Pos) /*!< SCB HFSR: VECTTBL Mask */ /* SCB Debug Fault Status Register Definitions */ #define SCB_DFSR_EXTERNAL_Pos 4 /*!< SCB DFSR: EXTERNAL Position */ #define SCB_DFSR_EXTERNAL_Msk (1UL << SCB_DFSR_EXTERNAL_Pos) /*!< SCB DFSR: EXTERNAL Mask */ #define SCB_DFSR_VCATCH_Pos 3 /*!< SCB DFSR: VCATCH Position */ #define SCB_DFSR_VCATCH_Msk (1UL << SCB_DFSR_VCATCH_Pos) /*!< SCB DFSR: VCATCH Mask */ #define SCB_DFSR_DWTTRAP_Pos 2 /*!< SCB DFSR: DWTTRAP Position */ #define SCB_DFSR_DWTTRAP_Msk (1UL << SCB_DFSR_DWTTRAP_Pos) /*!< SCB DFSR: DWTTRAP Mask */ #define SCB_DFSR_BKPT_Pos 1 /*!< SCB DFSR: BKPT Position */ #define SCB_DFSR_BKPT_Msk (1UL << SCB_DFSR_BKPT_Pos) /*!< SCB DFSR: BKPT Mask */ #define SCB_DFSR_HALTED_Pos 0 /*!< SCB DFSR: HALTED Position */ #define SCB_DFSR_HALTED_Msk (1UL /*<< SCB_DFSR_HALTED_Pos*/) /*!< SCB DFSR: HALTED Mask */ /*@} end of group CMSIS_SCB */ /** \ingroup CMSIS_core_register \defgroup CMSIS_SCnSCB System Controls not in SCB (SCnSCB) \brief Type definitions for the System Control and ID Register not in the SCB @{ */ /** \brief Structure type to access the System Control and ID Register not in the SCB. */ typedef struct { uint32_t RESERVED0[1]; __I uint32_t ICTR; /*!< Offset: 0x004 (R/ ) Interrupt Controller Type Register */ uint32_t RESERVED1[1]; } SCnSCB_Type; /* Interrupt Controller Type Register Definitions */ #define SCnSCB_ICTR_INTLINESNUM_Pos 0 /*!< ICTR: INTLINESNUM Position */ #define SCnSCB_ICTR_INTLINESNUM_Msk (0xFUL /*<< SCnSCB_ICTR_INTLINESNUM_Pos*/) /*!< ICTR: INTLINESNUM Mask */ /*@} end of group CMSIS_SCnotSCB */ /** \ingroup CMSIS_core_register \defgroup CMSIS_SysTick System Tick Timer (SysTick) \brief Type definitions for the System Timer Registers. @{ */ /** \brief Structure type to access the System Timer (SysTick). */ typedef struct { __IO uint32_t CTRL; /*!< Offset: 0x000 (R/W) SysTick Control and Status Register */ __IO uint32_t LOAD; /*!< Offset: 0x004 (R/W) SysTick Reload Value Register */ __IO uint32_t VAL; /*!< Offset: 0x008 (R/W) SysTick Current Value Register */ __I uint32_t CALIB; /*!< Offset: 0x00C (R/ ) SysTick Calibration Register */ } SysTick_Type; /* SysTick Control / Status Register Definitions */ #define SysTick_CTRL_COUNTFLAG_Pos 16 /*!< SysTick CTRL: COUNTFLAG Position */ #define SysTick_CTRL_COUNTFLAG_Msk (1UL << SysTick_CTRL_COUNTFLAG_Pos) /*!< SysTick CTRL: COUNTFLAG Mask */ #define SysTick_CTRL_CLKSOURCE_Pos 2 /*!< SysTick CTRL: CLKSOURCE Position */ #define SysTick_CTRL_CLKSOURCE_Msk (1UL << SysTick_CTRL_CLKSOURCE_Pos) /*!< SysTick CTRL: CLKSOURCE Mask */ #define SysTick_CTRL_TICKINT_Pos 1 /*!< SysTick CTRL: TICKINT Position */ #define SysTick_CTRL_TICKINT_Msk (1UL << SysTick_CTRL_TICKINT_Pos) /*!< SysTick CTRL: TICKINT Mask */ #define SysTick_CTRL_ENABLE_Pos 0 /*!< SysTick CTRL: ENABLE Position */ #define SysTick_CTRL_ENABLE_Msk (1UL /*<< SysTick_CTRL_ENABLE_Pos*/) /*!< SysTick CTRL: ENABLE Mask */ /* SysTick Reload Register Definitions */ #define SysTick_LOAD_RELOAD_Pos 0 /*!< SysTick LOAD: RELOAD Position */ #define SysTick_LOAD_RELOAD_Msk (0xFFFFFFUL /*<< SysTick_LOAD_RELOAD_Pos*/) /*!< SysTick LOAD: RELOAD Mask */ /* SysTick Current Register Definitions */ #define SysTick_VAL_CURRENT_Pos 0 /*!< SysTick VAL: CURRENT Position */ #define SysTick_VAL_CURRENT_Msk (0xFFFFFFUL /*<< SysTick_VAL_CURRENT_Pos*/) /*!< SysTick VAL: CURRENT Mask */ /* SysTick Calibration Register Definitions */ #define SysTick_CALIB_NOREF_Pos 31 /*!< SysTick CALIB: NOREF Position */ #define SysTick_CALIB_NOREF_Msk (1UL << SysTick_CALIB_NOREF_Pos) /*!< SysTick CALIB: NOREF Mask */ #define SysTick_CALIB_SKEW_Pos 30 /*!< SysTick CALIB: SKEW Position */ #define SysTick_CALIB_SKEW_Msk (1UL << SysTick_CALIB_SKEW_Pos) /*!< SysTick CALIB: SKEW Mask */ #define SysTick_CALIB_TENMS_Pos 0 /*!< SysTick CALIB: TENMS Position */ #define SysTick_CALIB_TENMS_Msk (0xFFFFFFUL /*<< SysTick_CALIB_TENMS_Pos*/) /*!< SysTick CALIB: TENMS Mask */ /*@} end of group CMSIS_SysTick */ /** \ingroup CMSIS_core_register \defgroup CMSIS_ITM Instrumentation Trace Macrocell (ITM) \brief Type definitions for the Instrumentation Trace Macrocell (ITM) @{ */ /** \brief Structure type to access the Instrumentation Trace Macrocell Register (ITM). */ typedef struct { __O union { __O uint8_t u8; /*!< Offset: 0x000 ( /W) ITM Stimulus Port 8-bit */ __O uint16_t u16; /*!< Offset: 0x000 ( /W) ITM Stimulus Port 16-bit */ __O uint32_t u32; /*!< Offset: 0x000 ( /W) ITM Stimulus Port 32-bit */ } PORT [32]; /*!< Offset: 0x000 ( /W) ITM Stimulus Port Registers */ uint32_t RESERVED0[864]; __IO uint32_t TER; /*!< Offset: 0xE00 (R/W) ITM Trace Enable Register */ uint32_t RESERVED1[15]; __IO uint32_t TPR; /*!< Offset: 0xE40 (R/W) ITM Trace Privilege Register */ uint32_t RESERVED2[15]; __IO uint32_t TCR; /*!< Offset: 0xE80 (R/W) ITM Trace Control Register */ uint32_t RESERVED3[29]; __O uint32_t IWR; /*!< Offset: 0xEF8 ( /W) ITM Integration Write Register */ __I uint32_t IRR; /*!< Offset: 0xEFC (R/ ) ITM Integration Read Register */ __IO uint32_t IMCR; /*!< Offset: 0xF00 (R/W) ITM Integration Mode Control Register */ uint32_t RESERVED4[43]; __O uint32_t LAR; /*!< Offset: 0xFB0 ( /W) ITM Lock Access Register */ __I uint32_t LSR; /*!< Offset: 0xFB4 (R/ ) ITM Lock Status Register */ uint32_t RESERVED5[6]; __I uint32_t PID4; /*!< Offset: 0xFD0 (R/ ) ITM Peripheral Identification Register #4 */ __I uint32_t PID5; /*!< Offset: 0xFD4 (R/ ) ITM Peripheral Identification Register #5 */ __I uint32_t PID6; /*!< Offset: 0xFD8 (R/ ) ITM Peripheral Identification Register #6 */ __I uint32_t PID7; /*!< Offset: 0xFDC (R/ ) ITM Peripheral Identification Register #7 */ __I uint32_t PID0; /*!< Offset: 0xFE0 (R/ ) ITM Peripheral Identification Register #0 */ __I uint32_t PID1; /*!< Offset: 0xFE4 (R/ ) ITM Peripheral Identification Register #1 */ __I uint32_t PID2; /*!< Offset: 0xFE8 (R/ ) ITM Peripheral Identification Register #2 */ __I uint32_t PID3; /*!< Offset: 0xFEC (R/ ) ITM Peripheral Identification Register #3 */ __I uint32_t CID0; /*!< Offset: 0xFF0 (R/ ) ITM Component Identification Register #0 */ __I uint32_t CID1; /*!< Offset: 0xFF4 (R/ ) ITM Component Identification Register #1 */ __I uint32_t CID2; /*!< Offset: 0xFF8 (R/ ) ITM Component Identification Register #2 */ __I uint32_t CID3; /*!< Offset: 0xFFC (R/ ) ITM Component Identification Register #3 */ } ITM_Type; /* ITM Trace Privilege Register Definitions */ #define ITM_TPR_PRIVMASK_Pos 0 /*!< ITM TPR: PRIVMASK Position */ #define ITM_TPR_PRIVMASK_Msk (0xFUL /*<< ITM_TPR_PRIVMASK_Pos*/) /*!< ITM TPR: PRIVMASK Mask */ /* ITM Trace Control Register Definitions */ #define ITM_TCR_BUSY_Pos 23 /*!< ITM TCR: BUSY Position */ #define ITM_TCR_BUSY_Msk (1UL << ITM_TCR_BUSY_Pos) /*!< ITM TCR: BUSY Mask */ #define ITM_TCR_TraceBusID_Pos 16 /*!< ITM TCR: ATBID Position */ #define ITM_TCR_TraceBusID_Msk (0x7FUL << ITM_TCR_TraceBusID_Pos) /*!< ITM TCR: ATBID Mask */ #define ITM_TCR_GTSFREQ_Pos 10 /*!< ITM TCR: Global timestamp frequency Position */ #define ITM_TCR_GTSFREQ_Msk (3UL << ITM_TCR_GTSFREQ_Pos) /*!< ITM TCR: Global timestamp frequency Mask */ #define ITM_TCR_TSPrescale_Pos 8 /*!< ITM TCR: TSPrescale Position */ #define ITM_TCR_TSPrescale_Msk (3UL << ITM_TCR_TSPrescale_Pos) /*!< ITM TCR: TSPrescale Mask */ #define ITM_TCR_SWOENA_Pos 4 /*!< ITM TCR: SWOENA Position */ #define ITM_TCR_SWOENA_Msk (1UL << ITM_TCR_SWOENA_Pos) /*!< ITM TCR: SWOENA Mask */ #define ITM_TCR_DWTENA_Pos 3 /*!< ITM TCR: DWTENA Position */ #define ITM_TCR_DWTENA_Msk (1UL << ITM_TCR_DWTENA_Pos) /*!< ITM TCR: DWTENA Mask */ #define ITM_TCR_SYNCENA_Pos 2 /*!< ITM TCR: SYNCENA Position */ #define ITM_TCR_SYNCENA_Msk (1UL << ITM_TCR_SYNCENA_Pos) /*!< ITM TCR: SYNCENA Mask */ #define ITM_TCR_TSENA_Pos 1 /*!< ITM TCR: TSENA Position */ #define ITM_TCR_TSENA_Msk (1UL << ITM_TCR_TSENA_Pos) /*!< ITM TCR: TSENA Mask */ #define ITM_TCR_ITMENA_Pos 0 /*!< ITM TCR: ITM Enable bit Position */ #define ITM_TCR_ITMENA_Msk (1UL /*<< ITM_TCR_ITMENA_Pos*/) /*!< ITM TCR: ITM Enable bit Mask */ /* ITM Integration Write Register Definitions */ #define ITM_IWR_ATVALIDM_Pos 0 /*!< ITM IWR: ATVALIDM Position */ #define ITM_IWR_ATVALIDM_Msk (1UL /*<< ITM_IWR_ATVALIDM_Pos*/) /*!< ITM IWR: ATVALIDM Mask */ /* ITM Integration Read Register Definitions */ #define ITM_IRR_ATREADYM_Pos 0 /*!< ITM IRR: ATREADYM Position */ #define ITM_IRR_ATREADYM_Msk (1UL /*<< ITM_IRR_ATREADYM_Pos*/) /*!< ITM IRR: ATREADYM Mask */ /* ITM Integration Mode Control Register Definitions */ #define ITM_IMCR_INTEGRATION_Pos 0 /*!< ITM IMCR: INTEGRATION Position */ #define ITM_IMCR_INTEGRATION_Msk (1UL /*<< ITM_IMCR_INTEGRATION_Pos*/) /*!< ITM IMCR: INTEGRATION Mask */ /* ITM Lock Status Register Definitions */ #define ITM_LSR_ByteAcc_Pos 2 /*!< ITM LSR: ByteAcc Position */ #define ITM_LSR_ByteAcc_Msk (1UL << ITM_LSR_ByteAcc_Pos) /*!< ITM LSR: ByteAcc Mask */ #define ITM_LSR_Access_Pos 1 /*!< ITM LSR: Access Position */ #define ITM_LSR_Access_Msk (1UL << ITM_LSR_Access_Pos) /*!< ITM LSR: Access Mask */ #define ITM_LSR_Present_Pos 0 /*!< ITM LSR: Present Position */ #define ITM_LSR_Present_Msk (1UL /*<< ITM_LSR_Present_Pos*/) /*!< ITM LSR: Present Mask */ /*@}*/ /* end of group CMSIS_ITM */ /** \ingroup CMSIS_core_register \defgroup CMSIS_DWT Data Watchpoint and Trace (DWT) \brief Type definitions for the Data Watchpoint and Trace (DWT) @{ */ /** \brief Structure type to access the Data Watchpoint and Trace Register (DWT). */ typedef struct { __IO uint32_t CTRL; /*!< Offset: 0x000 (R/W) Control Register */ __IO uint32_t CYCCNT; /*!< Offset: 0x004 (R/W) Cycle Count Register */ __IO uint32_t CPICNT; /*!< Offset: 0x008 (R/W) CPI Count Register */ __IO uint32_t EXCCNT; /*!< Offset: 0x00C (R/W) Exception Overhead Count Register */ __IO uint32_t SLEEPCNT; /*!< Offset: 0x010 (R/W) Sleep Count Register */ __IO uint32_t LSUCNT; /*!< Offset: 0x014 (R/W) LSU Count Register */ __IO uint32_t FOLDCNT; /*!< Offset: 0x018 (R/W) Folded-instruction Count Register */ __I uint32_t PCSR; /*!< Offset: 0x01C (R/ ) Program Counter Sample Register */ __IO uint32_t COMP0; /*!< Offset: 0x020 (R/W) Comparator Register 0 */ __IO uint32_t MASK0; /*!< Offset: 0x024 (R/W) Mask Register 0 */ __IO uint32_t FUNCTION0; /*!< Offset: 0x028 (R/W) Function Register 0 */ uint32_t RESERVED0[1]; __IO uint32_t COMP1; /*!< Offset: 0x030 (R/W) Comparator Register 1 */ __IO uint32_t MASK1; /*!< Offset: 0x034 (R/W) Mask Register 1 */ __IO uint32_t FUNCTION1; /*!< Offset: 0x038 (R/W) Function Register 1 */ uint32_t RESERVED1[1]; __IO uint32_t COMP2; /*!< Offset: 0x040 (R/W) Comparator Register 2 */ __IO uint32_t MASK2; /*!< Offset: 0x044 (R/W) Mask Register 2 */ __IO uint32_t FUNCTION2; /*!< Offset: 0x048 (R/W) Function Register 2 */ uint32_t RESERVED2[1]; __IO uint32_t COMP3; /*!< Offset: 0x050 (R/W) Comparator Register 3 */ __IO uint32_t MASK3; /*!< Offset: 0x054 (R/W) Mask Register 3 */ __IO uint32_t FUNCTION3; /*!< Offset: 0x058 (R/W) Function Register 3 */ } DWT_Type; /* DWT Control Register Definitions */ #define DWT_CTRL_NUMCOMP_Pos 28 /*!< DWT CTRL: NUMCOMP Position */ #define DWT_CTRL_NUMCOMP_Msk (0xFUL << DWT_CTRL_NUMCOMP_Pos) /*!< DWT CTRL: NUMCOMP Mask */ #define DWT_CTRL_NOTRCPKT_Pos 27 /*!< DWT CTRL: NOTRCPKT Position */ #define DWT_CTRL_NOTRCPKT_Msk (0x1UL << DWT_CTRL_NOTRCPKT_Pos) /*!< DWT CTRL: NOTRCPKT Mask */ #define DWT_CTRL_NOEXTTRIG_Pos 26 /*!< DWT CTRL: NOEXTTRIG Position */ #define DWT_CTRL_NOEXTTRIG_Msk (0x1UL << DWT_CTRL_NOEXTTRIG_Pos) /*!< DWT CTRL: NOEXTTRIG Mask */ #define DWT_CTRL_NOCYCCNT_Pos 25 /*!< DWT CTRL: NOCYCCNT Position */ #define DWT_CTRL_NOCYCCNT_Msk (0x1UL << DWT_CTRL_NOCYCCNT_Pos) /*!< DWT CTRL: NOCYCCNT Mask */ #define DWT_CTRL_NOPRFCNT_Pos 24 /*!< DWT CTRL: NOPRFCNT Position */ #define DWT_CTRL_NOPRFCNT_Msk (0x1UL << DWT_CTRL_NOPRFCNT_Pos) /*!< DWT CTRL: NOPRFCNT Mask */ #define DWT_CTRL_CYCEVTENA_Pos 22 /*!< DWT CTRL: CYCEVTENA Position */ #define DWT_CTRL_CYCEVTENA_Msk (0x1UL << DWT_CTRL_CYCEVTENA_Pos) /*!< DWT CTRL: CYCEVTENA Mask */ #define DWT_CTRL_FOLDEVTENA_Pos 21 /*!< DWT CTRL: FOLDEVTENA Position */ #define DWT_CTRL_FOLDEVTENA_Msk (0x1UL << DWT_CTRL_FOLDEVTENA_Pos) /*!< DWT CTRL: FOLDEVTENA Mask */ #define DWT_CTRL_LSUEVTENA_Pos 20 /*!< DWT CTRL: LSUEVTENA Position */ #define DWT_CTRL_LSUEVTENA_Msk (0x1UL << DWT_CTRL_LSUEVTENA_Pos) /*!< DWT CTRL: LSUEVTENA Mask */ #define DWT_CTRL_SLEEPEVTENA_Pos 19 /*!< DWT CTRL: SLEEPEVTENA Position */ #define DWT_CTRL_SLEEPEVTENA_Msk (0x1UL << DWT_CTRL_SLEEPEVTENA_Pos) /*!< DWT CTRL: SLEEPEVTENA Mask */ #define DWT_CTRL_EXCEVTENA_Pos 18 /*!< DWT CTRL: EXCEVTENA Position */ #define DWT_CTRL_EXCEVTENA_Msk (0x1UL << DWT_CTRL_EXCEVTENA_Pos) /*!< DWT CTRL: EXCEVTENA Mask */ #define DWT_CTRL_CPIEVTENA_Pos 17 /*!< DWT CTRL: CPIEVTENA Position */ #define DWT_CTRL_CPIEVTENA_Msk (0x1UL << DWT_CTRL_CPIEVTENA_Pos) /*!< DWT CTRL: CPIEVTENA Mask */ #define DWT_CTRL_EXCTRCENA_Pos 16 /*!< DWT CTRL: EXCTRCENA Position */ #define DWT_CTRL_EXCTRCENA_Msk (0x1UL << DWT_CTRL_EXCTRCENA_Pos) /*!< DWT CTRL: EXCTRCENA Mask */ #define DWT_CTRL_PCSAMPLENA_Pos 12 /*!< DWT CTRL: PCSAMPLENA Position */ #define DWT_CTRL_PCSAMPLENA_Msk (0x1UL << DWT_CTRL_PCSAMPLENA_Pos) /*!< DWT CTRL: PCSAMPLENA Mask */ #define DWT_CTRL_SYNCTAP_Pos 10 /*!< DWT CTRL: SYNCTAP Position */ #define DWT_CTRL_SYNCTAP_Msk (0x3UL << DWT_CTRL_SYNCTAP_Pos) /*!< DWT CTRL: SYNCTAP Mask */ #define DWT_CTRL_CYCTAP_Pos 9 /*!< DWT CTRL: CYCTAP Position */ #define DWT_CTRL_CYCTAP_Msk (0x1UL << DWT_CTRL_CYCTAP_Pos) /*!< DWT CTRL: CYCTAP Mask */ #define DWT_CTRL_POSTINIT_Pos 5 /*!< DWT CTRL: POSTINIT Position */ #define DWT_CTRL_POSTINIT_Msk (0xFUL << DWT_CTRL_POSTINIT_Pos) /*!< DWT CTRL: POSTINIT Mask */ #define DWT_CTRL_POSTPRESET_Pos 1 /*!< DWT CTRL: POSTPRESET Position */ #define DWT_CTRL_POSTPRESET_Msk (0xFUL << DWT_CTRL_POSTPRESET_Pos) /*!< DWT CTRL: POSTPRESET Mask */ #define DWT_CTRL_CYCCNTENA_Pos 0 /*!< DWT CTRL: CYCCNTENA Position */ #define DWT_CTRL_CYCCNTENA_Msk (0x1UL /*<< DWT_CTRL_CYCCNTENA_Pos*/) /*!< DWT CTRL: CYCCNTENA Mask */ /* DWT CPI Count Register Definitions */ #define DWT_CPICNT_CPICNT_Pos 0 /*!< DWT CPICNT: CPICNT Position */ #define DWT_CPICNT_CPICNT_Msk (0xFFUL /*<< DWT_CPICNT_CPICNT_Pos*/) /*!< DWT CPICNT: CPICNT Mask */ /* DWT Exception Overhead Count Register Definitions */ #define DWT_EXCCNT_EXCCNT_Pos 0 /*!< DWT EXCCNT: EXCCNT Position */ #define DWT_EXCCNT_EXCCNT_Msk (0xFFUL /*<< DWT_EXCCNT_EXCCNT_Pos*/) /*!< DWT EXCCNT: EXCCNT Mask */ /* DWT Sleep Count Register Definitions */ #define DWT_SLEEPCNT_SLEEPCNT_Pos 0 /*!< DWT SLEEPCNT: SLEEPCNT Position */ #define DWT_SLEEPCNT_SLEEPCNT_Msk (0xFFUL /*<< DWT_SLEEPCNT_SLEEPCNT_Pos*/) /*!< DWT SLEEPCNT: SLEEPCNT Mask */ /* DWT LSU Count Register Definitions */ #define DWT_LSUCNT_LSUCNT_Pos 0 /*!< DWT LSUCNT: LSUCNT Position */ #define DWT_LSUCNT_LSUCNT_Msk (0xFFUL /*<< DWT_LSUCNT_LSUCNT_Pos*/) /*!< DWT LSUCNT: LSUCNT Mask */ /* DWT Folded-instruction Count Register Definitions */ #define DWT_FOLDCNT_FOLDCNT_Pos 0 /*!< DWT FOLDCNT: FOLDCNT Position */ #define DWT_FOLDCNT_FOLDCNT_Msk (0xFFUL /*<< DWT_FOLDCNT_FOLDCNT_Pos*/) /*!< DWT FOLDCNT: FOLDCNT Mask */ /* DWT Comparator Mask Register Definitions */ #define DWT_MASK_MASK_Pos 0 /*!< DWT MASK: MASK Position */ #define DWT_MASK_MASK_Msk (0x1FUL /*<< DWT_MASK_MASK_Pos*/) /*!< DWT MASK: MASK Mask */ /* DWT Comparator Function Register Definitions */ #define DWT_FUNCTION_MATCHED_Pos 24 /*!< DWT FUNCTION: MATCHED Position */ #define DWT_FUNCTION_MATCHED_Msk (0x1UL << DWT_FUNCTION_MATCHED_Pos) /*!< DWT FUNCTION: MATCHED Mask */ #define DWT_FUNCTION_DATAVADDR1_Pos 16 /*!< DWT FUNCTION: DATAVADDR1 Position */ #define DWT_FUNCTION_DATAVADDR1_Msk (0xFUL << DWT_FUNCTION_DATAVADDR1_Pos) /*!< DWT FUNCTION: DATAVADDR1 Mask */ #define DWT_FUNCTION_DATAVADDR0_Pos 12 /*!< DWT FUNCTION: DATAVADDR0 Position */ #define DWT_FUNCTION_DATAVADDR0_Msk (0xFUL << DWT_FUNCTION_DATAVADDR0_Pos) /*!< DWT FUNCTION: DATAVADDR0 Mask */ #define DWT_FUNCTION_DATAVSIZE_Pos 10 /*!< DWT FUNCTION: DATAVSIZE Position */ #define DWT_FUNCTION_DATAVSIZE_Msk (0x3UL << DWT_FUNCTION_DATAVSIZE_Pos) /*!< DWT FUNCTION: DATAVSIZE Mask */ #define DWT_FUNCTION_LNK1ENA_Pos 9 /*!< DWT FUNCTION: LNK1ENA Position */ #define DWT_FUNCTION_LNK1ENA_Msk (0x1UL << DWT_FUNCTION_LNK1ENA_Pos) /*!< DWT FUNCTION: LNK1ENA Mask */ #define DWT_FUNCTION_DATAVMATCH_Pos 8 /*!< DWT FUNCTION: DATAVMATCH Position */ #define DWT_FUNCTION_DATAVMATCH_Msk (0x1UL << DWT_FUNCTION_DATAVMATCH_Pos) /*!< DWT FUNCTION: DATAVMATCH Mask */ #define DWT_FUNCTION_CYCMATCH_Pos 7 /*!< DWT FUNCTION: CYCMATCH Position */ #define DWT_FUNCTION_CYCMATCH_Msk (0x1UL << DWT_FUNCTION_CYCMATCH_Pos) /*!< DWT FUNCTION: CYCMATCH Mask */ #define DWT_FUNCTION_EMITRANGE_Pos 5 /*!< DWT FUNCTION: EMITRANGE Position */ #define DWT_FUNCTION_EMITRANGE_Msk (0x1UL << DWT_FUNCTION_EMITRANGE_Pos) /*!< DWT FUNCTION: EMITRANGE Mask */ #define DWT_FUNCTION_FUNCTION_Pos 0 /*!< DWT FUNCTION: FUNCTION Position */ #define DWT_FUNCTION_FUNCTION_Msk (0xFUL /*<< DWT_FUNCTION_FUNCTION_Pos*/) /*!< DWT FUNCTION: FUNCTION Mask */ /*@}*/ /* end of group CMSIS_DWT */ /** \ingroup CMSIS_core_register \defgroup CMSIS_TPI Trace Port Interface (TPI) \brief Type definitions for the Trace Port Interface (TPI) @{ */ /** \brief Structure type to access the Trace Port Interface Register (TPI). */ typedef struct { __IO uint32_t SSPSR; /*!< Offset: 0x000 (R/ ) Supported Parallel Port Size Register */ __IO uint32_t CSPSR; /*!< Offset: 0x004 (R/W) Current Parallel Port Size Register */ uint32_t RESERVED0[2]; __IO uint32_t ACPR; /*!< Offset: 0x010 (R/W) Asynchronous Clock Prescaler Register */ uint32_t RESERVED1[55]; __IO uint32_t SPPR; /*!< Offset: 0x0F0 (R/W) Selected Pin Protocol Register */ uint32_t RESERVED2[131]; __I uint32_t FFSR; /*!< Offset: 0x300 (R/ ) Formatter and Flush Status Register */ __IO uint32_t FFCR; /*!< Offset: 0x304 (R/W) Formatter and Flush Control Register */ __I uint32_t FSCR; /*!< Offset: 0x308 (R/ ) Formatter Synchronization Counter Register */ uint32_t RESERVED3[759]; __I uint32_t TRIGGER; /*!< Offset: 0xEE8 (R/ ) TRIGGER */ __I uint32_t FIFO0; /*!< Offset: 0xEEC (R/ ) Integration ETM Data */ __I uint32_t ITATBCTR2; /*!< Offset: 0xEF0 (R/ ) ITATBCTR2 */ uint32_t RESERVED4[1]; __I uint32_t ITATBCTR0; /*!< Offset: 0xEF8 (R/ ) ITATBCTR0 */ __I uint32_t FIFO1; /*!< Offset: 0xEFC (R/ ) Integration ITM Data */ __IO uint32_t ITCTRL; /*!< Offset: 0xF00 (R/W) Integration Mode Control */ uint32_t RESERVED5[39]; __IO uint32_t CLAIMSET; /*!< Offset: 0xFA0 (R/W) Claim tag set */ __IO uint32_t CLAIMCLR; /*!< Offset: 0xFA4 (R/W) Claim tag clear */ uint32_t RESERVED7[8]; __I uint32_t DEVID; /*!< Offset: 0xFC8 (R/ ) TPIU_DEVID */ __I uint32_t DEVTYPE; /*!< Offset: 0xFCC (R/ ) TPIU_DEVTYPE */ } TPI_Type; /* TPI Asynchronous Clock Prescaler Register Definitions */ #define TPI_ACPR_PRESCALER_Pos 0 /*!< TPI ACPR: PRESCALER Position */ #define TPI_ACPR_PRESCALER_Msk (0x1FFFUL /*<< TPI_ACPR_PRESCALER_Pos*/) /*!< TPI ACPR: PRESCALER Mask */ /* TPI Selected Pin Protocol Register Definitions */ #define TPI_SPPR_TXMODE_Pos 0 /*!< TPI SPPR: TXMODE Position */ #define TPI_SPPR_TXMODE_Msk (0x3UL /*<< TPI_SPPR_TXMODE_Pos*/) /*!< TPI SPPR: TXMODE Mask */ /* TPI Formatter and Flush Status Register Definitions */ #define TPI_FFSR_FtNonStop_Pos 3 /*!< TPI FFSR: FtNonStop Position */ #define TPI_FFSR_FtNonStop_Msk (0x1UL << TPI_FFSR_FtNonStop_Pos) /*!< TPI FFSR: FtNonStop Mask */ #define TPI_FFSR_TCPresent_Pos 2 /*!< TPI FFSR: TCPresent Position */ #define TPI_FFSR_TCPresent_Msk (0x1UL << TPI_FFSR_TCPresent_Pos) /*!< TPI FFSR: TCPresent Mask */ #define TPI_FFSR_FtStopped_Pos 1 /*!< TPI FFSR: FtStopped Position */ #define TPI_FFSR_FtStopped_Msk (0x1UL << TPI_FFSR_FtStopped_Pos) /*!< TPI FFSR: FtStopped Mask */ #define TPI_FFSR_FlInProg_Pos 0 /*!< TPI FFSR: FlInProg Position */ #define TPI_FFSR_FlInProg_Msk (0x1UL /*<< TPI_FFSR_FlInProg_Pos*/) /*!< TPI FFSR: FlInProg Mask */ /* TPI Formatter and Flush Control Register Definitions */ #define TPI_FFCR_TrigIn_Pos 8 /*!< TPI FFCR: TrigIn Position */ #define TPI_FFCR_TrigIn_Msk (0x1UL << TPI_FFCR_TrigIn_Pos) /*!< TPI FFCR: TrigIn Mask */ #define TPI_FFCR_EnFCont_Pos 1 /*!< TPI FFCR: EnFCont Position */ #define TPI_FFCR_EnFCont_Msk (0x1UL << TPI_FFCR_EnFCont_Pos) /*!< TPI FFCR: EnFCont Mask */ /* TPI TRIGGER Register Definitions */ #define TPI_TRIGGER_TRIGGER_Pos 0 /*!< TPI TRIGGER: TRIGGER Position */ #define TPI_TRIGGER_TRIGGER_Msk (0x1UL /*<< TPI_TRIGGER_TRIGGER_Pos*/) /*!< TPI TRIGGER: TRIGGER Mask */ /* TPI Integration ETM Data Register Definitions (FIFO0) */ #define TPI_FIFO0_ITM_ATVALID_Pos 29 /*!< TPI FIFO0: ITM_ATVALID Position */ #define TPI_FIFO0_ITM_ATVALID_Msk (0x3UL << TPI_FIFO0_ITM_ATVALID_Pos) /*!< TPI FIFO0: ITM_ATVALID Mask */ #define TPI_FIFO0_ITM_bytecount_Pos 27 /*!< TPI FIFO0: ITM_bytecount Position */ #define TPI_FIFO0_ITM_bytecount_Msk (0x3UL << TPI_FIFO0_ITM_bytecount_Pos) /*!< TPI FIFO0: ITM_bytecount Mask */ #define TPI_FIFO0_ETM_ATVALID_Pos 26 /*!< TPI FIFO0: ETM_ATVALID Position */ #define TPI_FIFO0_ETM_ATVALID_Msk (0x3UL << TPI_FIFO0_ETM_ATVALID_Pos) /*!< TPI FIFO0: ETM_ATVALID Mask */ #define TPI_FIFO0_ETM_bytecount_Pos 24 /*!< TPI FIFO0: ETM_bytecount Position */ #define TPI_FIFO0_ETM_bytecount_Msk (0x3UL << TPI_FIFO0_ETM_bytecount_Pos) /*!< TPI FIFO0: ETM_bytecount Mask */ #define TPI_FIFO0_ETM2_Pos 16 /*!< TPI FIFO0: ETM2 Position */ #define TPI_FIFO0_ETM2_Msk (0xFFUL << TPI_FIFO0_ETM2_Pos) /*!< TPI FIFO0: ETM2 Mask */ #define TPI_FIFO0_ETM1_Pos 8 /*!< TPI FIFO0: ETM1 Position */ #define TPI_FIFO0_ETM1_Msk (0xFFUL << TPI_FIFO0_ETM1_Pos) /*!< TPI FIFO0: ETM1 Mask */ #define TPI_FIFO0_ETM0_Pos 0 /*!< TPI FIFO0: ETM0 Position */ #define TPI_FIFO0_ETM0_Msk (0xFFUL /*<< TPI_FIFO0_ETM0_Pos*/) /*!< TPI FIFO0: ETM0 Mask */ /* TPI ITATBCTR2 Register Definitions */ #define TPI_ITATBCTR2_ATREADY_Pos 0 /*!< TPI ITATBCTR2: ATREADY Position */ #define TPI_ITATBCTR2_ATREADY_Msk (0x1UL /*<< TPI_ITATBCTR2_ATREADY_Pos*/) /*!< TPI ITATBCTR2: ATREADY Mask */ /* TPI Integration ITM Data Register Definitions (FIFO1) */ #define TPI_FIFO1_ITM_ATVALID_Pos 29 /*!< TPI FIFO1: ITM_ATVALID Position */ #define TPI_FIFO1_ITM_ATVALID_Msk (0x3UL << TPI_FIFO1_ITM_ATVALID_Pos) /*!< TPI FIFO1: ITM_ATVALID Mask */ #define TPI_FIFO1_ITM_bytecount_Pos 27 /*!< TPI FIFO1: ITM_bytecount Position */ #define TPI_FIFO1_ITM_bytecount_Msk (0x3UL << TPI_FIFO1_ITM_bytecount_Pos) /*!< TPI FIFO1: ITM_bytecount Mask */ #define TPI_FIFO1_ETM_ATVALID_Pos 26 /*!< TPI FIFO1: ETM_ATVALID Position */ #define TPI_FIFO1_ETM_ATVALID_Msk (0x3UL << TPI_FIFO1_ETM_ATVALID_Pos) /*!< TPI FIFO1: ETM_ATVALID Mask */ #define TPI_FIFO1_ETM_bytecount_Pos 24 /*!< TPI FIFO1: ETM_bytecount Position */ #define TPI_FIFO1_ETM_bytecount_Msk (0x3UL << TPI_FIFO1_ETM_bytecount_Pos) /*!< TPI FIFO1: ETM_bytecount Mask */ #define TPI_FIFO1_ITM2_Pos 16 /*!< TPI FIFO1: ITM2 Position */ #define TPI_FIFO1_ITM2_Msk (0xFFUL << TPI_FIFO1_ITM2_Pos) /*!< TPI FIFO1: ITM2 Mask */ #define TPI_FIFO1_ITM1_Pos 8 /*!< TPI FIFO1: ITM1 Position */ #define TPI_FIFO1_ITM1_Msk (0xFFUL << TPI_FIFO1_ITM1_Pos) /*!< TPI FIFO1: ITM1 Mask */ #define TPI_FIFO1_ITM0_Pos 0 /*!< TPI FIFO1: ITM0 Position */ #define TPI_FIFO1_ITM0_Msk (0xFFUL /*<< TPI_FIFO1_ITM0_Pos*/) /*!< TPI FIFO1: ITM0 Mask */ /* TPI ITATBCTR0 Register Definitions */ #define TPI_ITATBCTR0_ATREADY_Pos 0 /*!< TPI ITATBCTR0: ATREADY Position */ #define TPI_ITATBCTR0_ATREADY_Msk (0x1UL /*<< TPI_ITATBCTR0_ATREADY_Pos*/) /*!< TPI ITATBCTR0: ATREADY Mask */ /* TPI Integration Mode Control Register Definitions */ #define TPI_ITCTRL_Mode_Pos 0 /*!< TPI ITCTRL: Mode Position */ #define TPI_ITCTRL_Mode_Msk (0x1UL /*<< TPI_ITCTRL_Mode_Pos*/) /*!< TPI ITCTRL: Mode Mask */ /* TPI DEVID Register Definitions */ #define TPI_DEVID_NRZVALID_Pos 11 /*!< TPI DEVID: NRZVALID Position */ #define TPI_DEVID_NRZVALID_Msk (0x1UL << TPI_DEVID_NRZVALID_Pos) /*!< TPI DEVID: NRZVALID Mask */ #define TPI_DEVID_MANCVALID_Pos 10 /*!< TPI DEVID: MANCVALID Position */ #define TPI_DEVID_MANCVALID_Msk (0x1UL << TPI_DEVID_MANCVALID_Pos) /*!< TPI DEVID: MANCVALID Mask */ #define TPI_DEVID_PTINVALID_Pos 9 /*!< TPI DEVID: PTINVALID Position */ #define TPI_DEVID_PTINVALID_Msk (0x1UL << TPI_DEVID_PTINVALID_Pos) /*!< TPI DEVID: PTINVALID Mask */ #define TPI_DEVID_MinBufSz_Pos 6 /*!< TPI DEVID: MinBufSz Position */ #define TPI_DEVID_MinBufSz_Msk (0x7UL << TPI_DEVID_MinBufSz_Pos) /*!< TPI DEVID: MinBufSz Mask */ #define TPI_DEVID_AsynClkIn_Pos 5 /*!< TPI DEVID: AsynClkIn Position */ #define TPI_DEVID_AsynClkIn_Msk (0x1UL << TPI_DEVID_AsynClkIn_Pos) /*!< TPI DEVID: AsynClkIn Mask */ #define TPI_DEVID_NrTraceInput_Pos 0 /*!< TPI DEVID: NrTraceInput Position */ #define TPI_DEVID_NrTraceInput_Msk (0x1FUL /*<< TPI_DEVID_NrTraceInput_Pos*/) /*!< TPI DEVID: NrTraceInput Mask */ /* TPI DEVTYPE Register Definitions */ #define TPI_DEVTYPE_MajorType_Pos 4 /*!< TPI DEVTYPE: MajorType Position */ #define TPI_DEVTYPE_MajorType_Msk (0xFUL << TPI_DEVTYPE_MajorType_Pos) /*!< TPI DEVTYPE: MajorType Mask */ #define TPI_DEVTYPE_SubType_Pos 0 /*!< TPI DEVTYPE: SubType Position */ #define TPI_DEVTYPE_SubType_Msk (0xFUL /*<< TPI_DEVTYPE_SubType_Pos*/) /*!< TPI DEVTYPE: SubType Mask */ /*@}*/ /* end of group CMSIS_TPI */ #if (__MPU_PRESENT == 1) /** \ingroup CMSIS_core_register \defgroup CMSIS_MPU Memory Protection Unit (MPU) \brief Type definitions for the Memory Protection Unit (MPU) @{ */ /** \brief Structure type to access the Memory Protection Unit (MPU). */ typedef struct { __I uint32_t TYPE; /*!< Offset: 0x000 (R/ ) MPU Type Register */ __IO uint32_t CTRL; /*!< Offset: 0x004 (R/W) MPU Control Register */ __IO uint32_t RNR; /*!< Offset: 0x008 (R/W) MPU Region RNRber Register */ __IO uint32_t RBAR; /*!< Offset: 0x00C (R/W) MPU Region Base Address Register */ __IO uint32_t RASR; /*!< Offset: 0x010 (R/W) MPU Region Attribute and Size Register */ __IO uint32_t RBAR_A1; /*!< Offset: 0x014 (R/W) MPU Alias 1 Region Base Address Register */ __IO uint32_t RASR_A1; /*!< Offset: 0x018 (R/W) MPU Alias 1 Region Attribute and Size Register */ __IO uint32_t RBAR_A2; /*!< Offset: 0x01C (R/W) MPU Alias 2 Region Base Address Register */ __IO uint32_t RASR_A2; /*!< Offset: 0x020 (R/W) MPU Alias 2 Region Attribute and Size Register */ __IO uint32_t RBAR_A3; /*!< Offset: 0x024 (R/W) MPU Alias 3 Region Base Address Register */ __IO uint32_t RASR_A3; /*!< Offset: 0x028 (R/W) MPU Alias 3 Region Attribute and Size Register */ } MPU_Type; /* MPU Type Register */ #define MPU_TYPE_IREGION_Pos 16 /*!< MPU TYPE: IREGION Position */ #define MPU_TYPE_IREGION_Msk (0xFFUL << MPU_TYPE_IREGION_Pos) /*!< MPU TYPE: IREGION Mask */ #define MPU_TYPE_DREGION_Pos 8 /*!< MPU TYPE: DREGION Position */ #define MPU_TYPE_DREGION_Msk (0xFFUL << MPU_TYPE_DREGION_Pos) /*!< MPU TYPE: DREGION Mask */ #define MPU_TYPE_SEPARATE_Pos 0 /*!< MPU TYPE: SEPARATE Position */ #define MPU_TYPE_SEPARATE_Msk (1UL /*<< MPU_TYPE_SEPARATE_Pos*/) /*!< MPU TYPE: SEPARATE Mask */ /* MPU Control Register */ #define MPU_CTRL_PRIVDEFENA_Pos 2 /*!< MPU CTRL: PRIVDEFENA Position */ #define MPU_CTRL_PRIVDEFENA_Msk (1UL << MPU_CTRL_PRIVDEFENA_Pos) /*!< MPU CTRL: PRIVDEFENA Mask */ #define MPU_CTRL_HFNMIENA_Pos 1 /*!< MPU CTRL: HFNMIENA Position */ #define MPU_CTRL_HFNMIENA_Msk (1UL << MPU_CTRL_HFNMIENA_Pos) /*!< MPU CTRL: HFNMIENA Mask */ #define MPU_CTRL_ENABLE_Pos 0 /*!< MPU CTRL: ENABLE Position */ #define MPU_CTRL_ENABLE_Msk (1UL /*<< MPU_CTRL_ENABLE_Pos*/) /*!< MPU CTRL: ENABLE Mask */ /* MPU Region Number Register */ #define MPU_RNR_REGION_Pos 0 /*!< MPU RNR: REGION Position */ #define MPU_RNR_REGION_Msk (0xFFUL /*<< MPU_RNR_REGION_Pos*/) /*!< MPU RNR: REGION Mask */ /* MPU Region Base Address Register */ #define MPU_RBAR_ADDR_Pos 5 /*!< MPU RBAR: ADDR Position */ #define MPU_RBAR_ADDR_Msk (0x7FFFFFFUL << MPU_RBAR_ADDR_Pos) /*!< MPU RBAR: ADDR Mask */ #define MPU_RBAR_VALID_Pos 4 /*!< MPU RBAR: VALID Position */ #define MPU_RBAR_VALID_Msk (1UL << MPU_RBAR_VALID_Pos) /*!< MPU RBAR: VALID Mask */ #define MPU_RBAR_REGION_Pos 0 /*!< MPU RBAR: REGION Position */ #define MPU_RBAR_REGION_Msk (0xFUL /*<< MPU_RBAR_REGION_Pos*/) /*!< MPU RBAR: REGION Mask */ /* MPU Region Attribute and Size Register */ #define MPU_RASR_ATTRS_Pos 16 /*!< MPU RASR: MPU Region Attribute field Position */ #define MPU_RASR_ATTRS_Msk (0xFFFFUL << MPU_RASR_ATTRS_Pos) /*!< MPU RASR: MPU Region Attribute field Mask */ #define MPU_RASR_XN_Pos 28 /*!< MPU RASR: ATTRS.XN Position */ #define MPU_RASR_XN_Msk (1UL << MPU_RASR_XN_Pos) /*!< MPU RASR: ATTRS.XN Mask */ #define MPU_RASR_AP_Pos 24 /*!< MPU RASR: ATTRS.AP Position */ #define MPU_RASR_AP_Msk (0x7UL << MPU_RASR_AP_Pos) /*!< MPU RASR: ATTRS.AP Mask */ #define MPU_RASR_TEX_Pos 19 /*!< MPU RASR: ATTRS.TEX Position */ #define MPU_RASR_TEX_Msk (0x7UL << MPU_RASR_TEX_Pos) /*!< MPU RASR: ATTRS.TEX Mask */ #define MPU_RASR_S_Pos 18 /*!< MPU RASR: ATTRS.S Position */ #define MPU_RASR_S_Msk (1UL << MPU_RASR_S_Pos) /*!< MPU RASR: ATTRS.S Mask */ #define MPU_RASR_C_Pos 17 /*!< MPU RASR: ATTRS.C Position */ #define MPU_RASR_C_Msk (1UL << MPU_RASR_C_Pos) /*!< MPU RASR: ATTRS.C Mask */ #define MPU_RASR_B_Pos 16 /*!< MPU RASR: ATTRS.B Position */ #define MPU_RASR_B_Msk (1UL << MPU_RASR_B_Pos) /*!< MPU RASR: ATTRS.B Mask */ #define MPU_RASR_SRD_Pos 8 /*!< MPU RASR: Sub-Region Disable Position */ #define MPU_RASR_SRD_Msk (0xFFUL << MPU_RASR_SRD_Pos) /*!< MPU RASR: Sub-Region Disable Mask */ #define MPU_RASR_SIZE_Pos 1 /*!< MPU RASR: Region Size Field Position */ #define MPU_RASR_SIZE_Msk (0x1FUL << MPU_RASR_SIZE_Pos) /*!< MPU RASR: Region Size Field Mask */ #define MPU_RASR_ENABLE_Pos 0 /*!< MPU RASR: Region enable bit Position */ #define MPU_RASR_ENABLE_Msk (1UL /*<< MPU_RASR_ENABLE_Pos*/) /*!< MPU RASR: Region enable bit Disable Mask */ /*@} end of group CMSIS_MPU */ #endif /** \ingroup CMSIS_core_register \defgroup CMSIS_CoreDebug Core Debug Registers (CoreDebug) \brief Type definitions for the Core Debug Registers @{ */ /** \brief Structure type to access the Core Debug Register (CoreDebug). */ typedef struct { __IO uint32_t DHCSR; /*!< Offset: 0x000 (R/W) Debug Halting Control and Status Register */ __O uint32_t DCRSR; /*!< Offset: 0x004 ( /W) Debug Core Register Selector Register */ __IO uint32_t DCRDR; /*!< Offset: 0x008 (R/W) Debug Core Register Data Register */ __IO uint32_t DEMCR; /*!< Offset: 0x00C (R/W) Debug Exception and Monitor Control Register */ } CoreDebug_Type; /* Debug Halting Control and Status Register */ #define CoreDebug_DHCSR_DBGKEY_Pos 16 /*!< CoreDebug DHCSR: DBGKEY Position */ #define CoreDebug_DHCSR_DBGKEY_Msk (0xFFFFUL << CoreDebug_DHCSR_DBGKEY_Pos) /*!< CoreDebug DHCSR: DBGKEY Mask */ #define CoreDebug_DHCSR_S_RESET_ST_Pos 25 /*!< CoreDebug DHCSR: S_RESET_ST Position */ #define CoreDebug_DHCSR_S_RESET_ST_Msk (1UL << CoreDebug_DHCSR_S_RESET_ST_Pos) /*!< CoreDebug DHCSR: S_RESET_ST Mask */ #define CoreDebug_DHCSR_S_RETIRE_ST_Pos 24 /*!< CoreDebug DHCSR: S_RETIRE_ST Position */ #define CoreDebug_DHCSR_S_RETIRE_ST_Msk (1UL << CoreDebug_DHCSR_S_RETIRE_ST_Pos) /*!< CoreDebug DHCSR: S_RETIRE_ST Mask */ #define CoreDebug_DHCSR_S_LOCKUP_Pos 19 /*!< CoreDebug DHCSR: S_LOCKUP Position */ #define CoreDebug_DHCSR_S_LOCKUP_Msk (1UL << CoreDebug_DHCSR_S_LOCKUP_Pos) /*!< CoreDebug DHCSR: S_LOCKUP Mask */ #define CoreDebug_DHCSR_S_SLEEP_Pos 18 /*!< CoreDebug DHCSR: S_SLEEP Position */ #define CoreDebug_DHCSR_S_SLEEP_Msk (1UL << CoreDebug_DHCSR_S_SLEEP_Pos) /*!< CoreDebug DHCSR: S_SLEEP Mask */ #define CoreDebug_DHCSR_S_HALT_Pos 17 /*!< CoreDebug DHCSR: S_HALT Position */ #define CoreDebug_DHCSR_S_HALT_Msk (1UL << CoreDebug_DHCSR_S_HALT_Pos) /*!< CoreDebug DHCSR: S_HALT Mask */ #define CoreDebug_DHCSR_S_REGRDY_Pos 16 /*!< CoreDebug DHCSR: S_REGRDY Position */ #define CoreDebug_DHCSR_S_REGRDY_Msk (1UL << CoreDebug_DHCSR_S_REGRDY_Pos) /*!< CoreDebug DHCSR: S_REGRDY Mask */ #define CoreDebug_DHCSR_C_SNAPSTALL_Pos 5 /*!< CoreDebug DHCSR: C_SNAPSTALL Position */ #define CoreDebug_DHCSR_C_SNAPSTALL_Msk (1UL << CoreDebug_DHCSR_C_SNAPSTALL_Pos) /*!< CoreDebug DHCSR: C_SNAPSTALL Mask */ #define CoreDebug_DHCSR_C_MASKINTS_Pos 3 /*!< CoreDebug DHCSR: C_MASKINTS Position */ #define CoreDebug_DHCSR_C_MASKINTS_Msk (1UL << CoreDebug_DHCSR_C_MASKINTS_Pos) /*!< CoreDebug DHCSR: C_MASKINTS Mask */ #define CoreDebug_DHCSR_C_STEP_Pos 2 /*!< CoreDebug DHCSR: C_STEP Position */ #define CoreDebug_DHCSR_C_STEP_Msk (1UL << CoreDebug_DHCSR_C_STEP_Pos) /*!< CoreDebug DHCSR: C_STEP Mask */ #define CoreDebug_DHCSR_C_HALT_Pos 1 /*!< CoreDebug DHCSR: C_HALT Position */ #define CoreDebug_DHCSR_C_HALT_Msk (1UL << CoreDebug_DHCSR_C_HALT_Pos) /*!< CoreDebug DHCSR: C_HALT Mask */ #define CoreDebug_DHCSR_C_DEBUGEN_Pos 0 /*!< CoreDebug DHCSR: C_DEBUGEN Position */ #define CoreDebug_DHCSR_C_DEBUGEN_Msk (1UL /*<< CoreDebug_DHCSR_C_DEBUGEN_Pos*/) /*!< CoreDebug DHCSR: C_DEBUGEN Mask */ /* Debug Core Register Selector Register */ #define CoreDebug_DCRSR_REGWnR_Pos 16 /*!< CoreDebug DCRSR: REGWnR Position */ #define CoreDebug_DCRSR_REGWnR_Msk (1UL << CoreDebug_DCRSR_REGWnR_Pos) /*!< CoreDebug DCRSR: REGWnR Mask */ #define CoreDebug_DCRSR_REGSEL_Pos 0 /*!< CoreDebug DCRSR: REGSEL Position */ #define CoreDebug_DCRSR_REGSEL_Msk (0x1FUL /*<< CoreDebug_DCRSR_REGSEL_Pos*/) /*!< CoreDebug DCRSR: REGSEL Mask */ /* Debug Exception and Monitor Control Register */ #define CoreDebug_DEMCR_TRCENA_Pos 24 /*!< CoreDebug DEMCR: TRCENA Position */ #define CoreDebug_DEMCR_TRCENA_Msk (1UL << CoreDebug_DEMCR_TRCENA_Pos) /*!< CoreDebug DEMCR: TRCENA Mask */ #define CoreDebug_DEMCR_MON_REQ_Pos 19 /*!< CoreDebug DEMCR: MON_REQ Position */ #define CoreDebug_DEMCR_MON_REQ_Msk (1UL << CoreDebug_DEMCR_MON_REQ_Pos) /*!< CoreDebug DEMCR: MON_REQ Mask */ #define CoreDebug_DEMCR_MON_STEP_Pos 18 /*!< CoreDebug DEMCR: MON_STEP Position */ #define CoreDebug_DEMCR_MON_STEP_Msk (1UL << CoreDebug_DEMCR_MON_STEP_Pos) /*!< CoreDebug DEMCR: MON_STEP Mask */ #define CoreDebug_DEMCR_MON_PEND_Pos 17 /*!< CoreDebug DEMCR: MON_PEND Position */ #define CoreDebug_DEMCR_MON_PEND_Msk (1UL << CoreDebug_DEMCR_MON_PEND_Pos) /*!< CoreDebug DEMCR: MON_PEND Mask */ #define CoreDebug_DEMCR_MON_EN_Pos 16 /*!< CoreDebug DEMCR: MON_EN Position */ #define CoreDebug_DEMCR_MON_EN_Msk (1UL << CoreDebug_DEMCR_MON_EN_Pos) /*!< CoreDebug DEMCR: MON_EN Mask */ #define CoreDebug_DEMCR_VC_HARDERR_Pos 10 /*!< CoreDebug DEMCR: VC_HARDERR Position */ #define CoreDebug_DEMCR_VC_HARDERR_Msk (1UL << CoreDebug_DEMCR_VC_HARDERR_Pos) /*!< CoreDebug DEMCR: VC_HARDERR Mask */ #define CoreDebug_DEMCR_VC_INTERR_Pos 9 /*!< CoreDebug DEMCR: VC_INTERR Position */ #define CoreDebug_DEMCR_VC_INTERR_Msk (1UL << CoreDebug_DEMCR_VC_INTERR_Pos) /*!< CoreDebug DEMCR: VC_INTERR Mask */ #define CoreDebug_DEMCR_VC_BUSERR_Pos 8 /*!< CoreDebug DEMCR: VC_BUSERR Position */ #define CoreDebug_DEMCR_VC_BUSERR_Msk (1UL << CoreDebug_DEMCR_VC_BUSERR_Pos) /*!< CoreDebug DEMCR: VC_BUSERR Mask */ #define CoreDebug_DEMCR_VC_STATERR_Pos 7 /*!< CoreDebug DEMCR: VC_STATERR Position */ #define CoreDebug_DEMCR_VC_STATERR_Msk (1UL << CoreDebug_DEMCR_VC_STATERR_Pos) /*!< CoreDebug DEMCR: VC_STATERR Mask */ #define CoreDebug_DEMCR_VC_CHKERR_Pos 6 /*!< CoreDebug DEMCR: VC_CHKERR Position */ #define CoreDebug_DEMCR_VC_CHKERR_Msk (1UL << CoreDebug_DEMCR_VC_CHKERR_Pos) /*!< CoreDebug DEMCR: VC_CHKERR Mask */ #define CoreDebug_DEMCR_VC_NOCPERR_Pos 5 /*!< CoreDebug DEMCR: VC_NOCPERR Position */ #define CoreDebug_DEMCR_VC_NOCPERR_Msk (1UL << CoreDebug_DEMCR_VC_NOCPERR_Pos) /*!< CoreDebug DEMCR: VC_NOCPERR Mask */ #define CoreDebug_DEMCR_VC_MMERR_Pos 4 /*!< CoreDebug DEMCR: VC_MMERR Position */ #define CoreDebug_DEMCR_VC_MMERR_Msk (1UL << CoreDebug_DEMCR_VC_MMERR_Pos) /*!< CoreDebug DEMCR: VC_MMERR Mask */ #define CoreDebug_DEMCR_VC_CORERESET_Pos 0 /*!< CoreDebug DEMCR: VC_CORERESET Position */ #define CoreDebug_DEMCR_VC_CORERESET_Msk (1UL /*<< CoreDebug_DEMCR_VC_CORERESET_Pos*/) /*!< CoreDebug DEMCR: VC_CORERESET Mask */ /*@} end of group CMSIS_CoreDebug */ /** \ingroup CMSIS_core_register \defgroup CMSIS_core_base Core Definitions \brief Definitions for base addresses, unions, and structures. @{ */ /* Memory mapping of Cortex-M3 Hardware */ #define SCS_BASE (0xE000E000UL) /*!< System Control Space Base Address */ #define ITM_BASE (0xE0000000UL) /*!< ITM Base Address */ #define DWT_BASE (0xE0001000UL) /*!< DWT Base Address */ #define TPI_BASE (0xE0040000UL) /*!< TPI Base Address */ #define CoreDebug_BASE (0xE000EDF0UL) /*!< Core Debug Base Address */ #define SysTick_BASE (SCS_BASE + 0x0010UL) /*!< SysTick Base Address */ #define NVIC_BASE (SCS_BASE + 0x0100UL) /*!< NVIC Base Address */ #define SCB_BASE (SCS_BASE + 0x0D00UL) /*!< System Control Block Base Address */ #define SCnSCB ((SCnSCB_Type *) SCS_BASE ) /*!< System control Register not in SCB */ #define SCB ((SCB_Type *) SCB_BASE ) /*!< SCB configuration struct */ #define SysTick ((SysTick_Type *) SysTick_BASE ) /*!< SysTick configuration struct */ #define NVIC ((NVIC_Type *) NVIC_BASE ) /*!< NVIC configuration struct */ #define ITM ((ITM_Type *) ITM_BASE ) /*!< ITM configuration struct */ #define DWT ((DWT_Type *) DWT_BASE ) /*!< DWT configuration struct */ #define TPI ((TPI_Type *) TPI_BASE ) /*!< TPI configuration struct */ #define CoreDebug ((CoreDebug_Type *) CoreDebug_BASE) /*!< Core Debug configuration struct */ #if (__MPU_PRESENT == 1) #define MPU_BASE (SCS_BASE + 0x0D90UL) /*!< Memory Protection Unit */ #define MPU ((MPU_Type *) MPU_BASE ) /*!< Memory Protection Unit */ #endif /*@} */ /******************************************************************************* * Hardware Abstraction Layer Core Function Interface contains: - Core NVIC Functions - Core SysTick Functions - Core Debug Functions - Core Register Access Functions ******************************************************************************/ /** \defgroup CMSIS_Core_FunctionInterface Functions and Instructions Reference */ /* ########################## NVIC functions #################################### */ /** \ingroup CMSIS_Core_FunctionInterface \defgroup CMSIS_Core_NVICFunctions NVIC Functions \brief Functions that manage interrupts and exceptions via the NVIC. @{ */ /** \brief Set Priority Grouping The function sets the priority grouping field using the required unlock sequence. The parameter PriorityGroup is assigned to the field SCB->AIRCR [10:8] PRIGROUP field. Only values from 0..7 are used. In case of a conflict between priority grouping and available priority bits (__NVIC_PRIO_BITS), the smallest possible priority group is set. \param [in] PriorityGroup Priority grouping field. */ __STATIC_INLINE void NVIC_SetPriorityGrouping(uint32_t PriorityGroup) { uint32_t reg_value; uint32_t PriorityGroupTmp = (PriorityGroup & (uint32_t)0x07UL); /* only values 0..7 are used */ reg_value = SCB->AIRCR; /* read old register configuration */ reg_value &= ~((uint32_t)(SCB_AIRCR_VECTKEY_Msk | SCB_AIRCR_PRIGROUP_Msk)); /* clear bits to change */ reg_value = (reg_value | ((uint32_t)0x5FAUL << SCB_AIRCR_VECTKEY_Pos) | (PriorityGroupTmp << 8) ); /* Insert write key and priorty group */ SCB->AIRCR = reg_value; } /** \brief Get Priority Grouping The function reads the priority grouping field from the NVIC Interrupt Controller. \return Priority grouping field (SCB->AIRCR [10:8] PRIGROUP field). */ __STATIC_INLINE uint32_t NVIC_GetPriorityGrouping(void) { return ((uint32_t)((SCB->AIRCR & SCB_AIRCR_PRIGROUP_Msk) >> SCB_AIRCR_PRIGROUP_Pos)); } /** \brief Enable External Interrupt The function enables a device-specific interrupt in the NVIC interrupt controller. \param [in] IRQn External interrupt number. Value cannot be negative. */ __STATIC_INLINE void NVIC_EnableIRQ(IRQn_Type IRQn) { NVIC->ISER[(((uint32_t)(int32_t)IRQn) >> 5UL)] = (uint32_t)(1UL << (((uint32_t)(int32_t)IRQn) & 0x1FUL)); } /** \brief Disable External Interrupt The function disables a device-specific interrupt in the NVIC interrupt controller. \param [in] IRQn External interrupt number. Value cannot be negative. */ __STATIC_INLINE void NVIC_DisableIRQ(IRQn_Type IRQn) { NVIC->ICER[(((uint32_t)(int32_t)IRQn) >> 5UL)] = (uint32_t)(1UL << (((uint32_t)(int32_t)IRQn) & 0x1FUL)); } /** \brief Get Pending Interrupt The function reads the pending register in the NVIC and returns the pending bit for the specified interrupt. \param [in] IRQn Interrupt number. \return 0 Interrupt status is not pending. \return 1 Interrupt status is pending. */ __STATIC_INLINE uint32_t NVIC_GetPendingIRQ(IRQn_Type IRQn) { return((uint32_t)(((NVIC->ISPR[(((uint32_t)(int32_t)IRQn) >> 5UL)] & (1UL << (((uint32_t)(int32_t)IRQn) & 0x1FUL))) != 0UL) ? 1UL : 0UL)); } /** \brief Set Pending Interrupt The function sets the pending bit of an external interrupt. \param [in] IRQn Interrupt number. Value cannot be negative. */ __STATIC_INLINE void NVIC_SetPendingIRQ(IRQn_Type IRQn) { NVIC->ISPR[(((uint32_t)(int32_t)IRQn) >> 5UL)] = (uint32_t)(1UL << (((uint32_t)(int32_t)IRQn) & 0x1FUL)); } /** \brief Clear Pending Interrupt The function clears the pending bit of an external interrupt. \param [in] IRQn External interrupt number. Value cannot be negative. */ __STATIC_INLINE void NVIC_ClearPendingIRQ(IRQn_Type IRQn) { NVIC->ICPR[(((uint32_t)(int32_t)IRQn) >> 5UL)] = (uint32_t)(1UL << (((uint32_t)(int32_t)IRQn) & 0x1FUL)); } /** \brief Get Active Interrupt The function reads the active register in NVIC and returns the active bit. \param [in] IRQn Interrupt number. \return 0 Interrupt status is not active. \return 1 Interrupt status is active. */ __STATIC_INLINE uint32_t NVIC_GetActive(IRQn_Type IRQn) { return((uint32_t)(((NVIC->IABR[(((uint32_t)(int32_t)IRQn) >> 5UL)] & (1UL << (((uint32_t)(int32_t)IRQn) & 0x1FUL))) != 0UL) ? 1UL : 0UL)); } /** \brief Set Interrupt Priority The function sets the priority of an interrupt. \note The priority cannot be set for every core interrupt. \param [in] IRQn Interrupt number. \param [in] priority Priority to set. */ __STATIC_INLINE void NVIC_SetPriority(IRQn_Type IRQn, uint32_t priority) { if((int32_t)IRQn < 0) { SCB->SHP[(((uint32_t)(int32_t)IRQn) & 0xFUL)-4UL] = (uint8_t)((priority << (8 - __NVIC_PRIO_BITS)) & (uint32_t)0xFFUL); } else { NVIC->IP[((uint32_t)(int32_t)IRQn)] = (uint8_t)((priority << (8 - __NVIC_PRIO_BITS)) & (uint32_t)0xFFUL); } } /** \brief Get Interrupt Priority The function reads the priority of an interrupt. The interrupt number can be positive to specify an external (device specific) interrupt, or negative to specify an internal (core) interrupt. \param [in] IRQn Interrupt number. \return Interrupt Priority. Value is aligned automatically to the implemented priority bits of the microcontroller. */ __STATIC_INLINE uint32_t NVIC_GetPriority(IRQn_Type IRQn) { if((int32_t)IRQn < 0) { return(((uint32_t)SCB->SHP[(((uint32_t)(int32_t)IRQn) & 0xFUL)-4UL] >> (8 - __NVIC_PRIO_BITS))); } else { return(((uint32_t)NVIC->IP[((uint32_t)(int32_t)IRQn)] >> (8 - __NVIC_PRIO_BITS))); } } /** \brief Encode Priority The function encodes the priority for an interrupt with the given priority group, preemptive priority value, and subpriority value. In case of a conflict between priority grouping and available priority bits (__NVIC_PRIO_BITS), the smallest possible priority group is set. \param [in] PriorityGroup Used priority group. \param [in] PreemptPriority Preemptive priority value (starting from 0). \param [in] SubPriority Subpriority value (starting from 0). \return Encoded priority. Value can be used in the function \ref NVIC_SetPriority(). */ __STATIC_INLINE uint32_t NVIC_EncodePriority (uint32_t PriorityGroup, uint32_t PreemptPriority, uint32_t SubPriority) { uint32_t PriorityGroupTmp = (PriorityGroup & (uint32_t)0x07UL); /* only values 0..7 are used */ uint32_t PreemptPriorityBits; uint32_t SubPriorityBits; PreemptPriorityBits = ((7UL - PriorityGroupTmp) > (uint32_t)(__NVIC_PRIO_BITS)) ? (uint32_t)(__NVIC_PRIO_BITS) : (uint32_t)(7UL - PriorityGroupTmp); SubPriorityBits = ((PriorityGroupTmp + (uint32_t)(__NVIC_PRIO_BITS)) < (uint32_t)7UL) ? (uint32_t)0UL : (uint32_t)((PriorityGroupTmp - 7UL) + (uint32_t)(__NVIC_PRIO_BITS)); return ( ((PreemptPriority & (uint32_t)((1UL << (PreemptPriorityBits)) - 1UL)) << SubPriorityBits) | ((SubPriority & (uint32_t)((1UL << (SubPriorityBits )) - 1UL))) ); } /** \brief Decode Priority The function decodes an interrupt priority value with a given priority group to preemptive priority value and subpriority value. In case of a conflict between priority grouping and available priority bits (__NVIC_PRIO_BITS) the smallest possible priority group is set. \param [in] Priority Priority value, which can be retrieved with the function \ref NVIC_GetPriority(). \param [in] PriorityGroup Used priority group. \param [out] pPreemptPriority Preemptive priority value (starting from 0). \param [out] pSubPriority Subpriority value (starting from 0). */ __STATIC_INLINE void NVIC_DecodePriority (uint32_t Priority, uint32_t PriorityGroup, uint32_t* pPreemptPriority, uint32_t* pSubPriority) { uint32_t PriorityGroupTmp = (PriorityGroup & (uint32_t)0x07UL); /* only values 0..7 are used */ uint32_t PreemptPriorityBits; uint32_t SubPriorityBits; PreemptPriorityBits = ((7UL - PriorityGroupTmp) > (uint32_t)(__NVIC_PRIO_BITS)) ? (uint32_t)(__NVIC_PRIO_BITS) : (uint32_t)(7UL - PriorityGroupTmp); SubPriorityBits = ((PriorityGroupTmp + (uint32_t)(__NVIC_PRIO_BITS)) < (uint32_t)7UL) ? (uint32_t)0UL : (uint32_t)((PriorityGroupTmp - 7UL) + (uint32_t)(__NVIC_PRIO_BITS)); *pPreemptPriority = (Priority >> SubPriorityBits) & (uint32_t)((1UL << (PreemptPriorityBits)) - 1UL); *pSubPriority = (Priority ) & (uint32_t)((1UL << (SubPriorityBits )) - 1UL); } /** \brief System Reset The function initiates a system reset request to reset the MCU. */ __STATIC_INLINE void NVIC_SystemReset(void) { __DSB(); /* Ensure all outstanding memory accesses included buffered write are completed before reset */ SCB->AIRCR = (uint32_t)((0x5FAUL << SCB_AIRCR_VECTKEY_Pos) | (SCB->AIRCR & SCB_AIRCR_PRIGROUP_Msk) | SCB_AIRCR_SYSRESETREQ_Msk ); /* Keep priority group unchanged */ __DSB(); /* Ensure completion of memory access */ while(1) { __NOP(); } /* wait until reset */ } /*@} end of CMSIS_Core_NVICFunctions */ /* ################################## SysTick function ############################################ */ /** \ingroup CMSIS_Core_FunctionInterface \defgroup CMSIS_Core_SysTickFunctions SysTick Functions \brief Functions that configure the System. @{ */ #if (__Vendor_SysTickConfig == 0) /** \brief System Tick Configuration The function initializes the System Timer and its interrupt, and starts the System Tick Timer. Counter is in free running mode to generate periodic interrupts. \param [in] ticks Number of ticks between two interrupts. \return 0 Function succeeded. \return 1 Function failed. \note When the variable __Vendor_SysTickConfig is set to 1, then the function SysTick_Config is not included. In this case, the file device.h must contain a vendor-specific implementation of this function. */ __STATIC_INLINE uint32_t SysTick_Config(uint32_t ticks) { if ((ticks - 1UL) > SysTick_LOAD_RELOAD_Msk) { return (1UL); } /* Reload value impossible */ SysTick->LOAD = (uint32_t)(ticks - 1UL); /* set reload register */ NVIC_SetPriority (SysTick_IRQn, (1UL << __NVIC_PRIO_BITS) - 1UL); /* set Priority for Systick Interrupt */ SysTick->VAL = 0UL; /* Load the SysTick Counter Value */ SysTick->CTRL = SysTick_CTRL_CLKSOURCE_Msk | SysTick_CTRL_TICKINT_Msk | SysTick_CTRL_ENABLE_Msk; /* Enable SysTick IRQ and SysTick Timer */ return (0UL); /* Function successful */ } #endif /*@} end of CMSIS_Core_SysTickFunctions */ /* ##################################### Debug In/Output function ########################################### */ /** \ingroup CMSIS_Core_FunctionInterface \defgroup CMSIS_core_DebugFunctions ITM Functions \brief Functions that access the ITM debug interface. @{ */ extern volatile int32_t ITM_RxBuffer; /*!< External variable to receive characters. */ #define ITM_RXBUFFER_EMPTY 0x5AA55AA5 /*!< Value identifying \ref ITM_RxBuffer is ready for next character. */ /** \brief ITM Send Character The function transmits a character via the ITM channel 0, and \li Just returns when no debugger is connected that has booked the output. \li Is blocking when a debugger is connected, but the previous character sent has not been transmitted. \param [in] ch Character to transmit. \returns Character to transmit. */ __STATIC_INLINE uint32_t ITM_SendChar (uint32_t ch) { if (((ITM->TCR & ITM_TCR_ITMENA_Msk) != 0UL) && /* ITM enabled */ ((ITM->TER & 1UL ) != 0UL) ) /* ITM Port #0 enabled */ { while (ITM->PORT[0].u32 == 0UL) { __NOP(); } ITM->PORT[0].u8 = (uint8_t)ch; } return (ch); } /** \brief ITM Receive Character The function inputs a character via the external variable \ref ITM_RxBuffer. \return Received character. \return -1 No character pending. */ __STATIC_INLINE int32_t ITM_ReceiveChar (void) { int32_t ch = -1; /* no character available */ if (ITM_RxBuffer != ITM_RXBUFFER_EMPTY) { ch = ITM_RxBuffer; ITM_RxBuffer = ITM_RXBUFFER_EMPTY; /* ready for next character */ } return (ch); } /** \brief ITM Check Character The function checks whether a character is pending for reading in the variable \ref ITM_RxBuffer. \return 0 No character available. \return 1 Character available. */ __STATIC_INLINE int32_t ITM_CheckChar (void) { if (ITM_RxBuffer == ITM_RXBUFFER_EMPTY) { return (0); /* no character available */ } else { return (1); /* character available */ } } /*@} end of CMSIS_core_DebugFunctions */ #ifdef __cplusplus } #endif #endif /* __CORE_SC300_H_DEPENDANT */ #endif /* __CMSIS_GENERIC */ ================================================ FILE: Zelig/mbed/TARGET_NUCLEO_F401RE/hal_tick.h ================================================ /** ****************************************************************************** * @file hal_tick.h * @author MCD Application Team * @brief Initialization of HAL tick ****************************************************************************** * @attention * *

© COPYRIGHT(c) 2014 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. * ****************************************************************************** */ #ifndef __HAL_TICK_H #define __HAL_TICK_H #ifdef __cplusplus extern "C" { #endif #include "stm32f4xx.h" #include "cmsis_nvic.h" #define TIM_MST TIM5 #define TIM_MST_IRQ TIM5_IRQn #define TIM_MST_RCC __TIM5_CLK_ENABLE() #define TIM_MST_RESET_ON __TIM5_FORCE_RESET() #define TIM_MST_RESET_OFF __TIM5_RELEASE_RESET() #define HAL_TICK_DELAY (1000) // 1 ms #ifdef __cplusplus } #endif #endif // __HAL_TICK_H /************************ (C) COPYRIGHT STMicroelectronics *****END OF FILE****/ ================================================ FILE: Zelig/mbed/TARGET_NUCLEO_F401RE/stm32_hal_legacy.h ================================================ /** ****************************************************************************** * @file stm32_hal_legacy.h * @author MCD Application Team * @version V1.4.1 * @date 09-October-2015 * @brief This file contains aliases definition for the STM32Cube HAL constants * macros and functions maintained for legacy purpose. ****************************************************************************** * @attention * *

© COPYRIGHT(c) 2015 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. * ****************************************************************************** */ /* Define to prevent recursive inclusion -------------------------------------*/ #ifndef __STM32_HAL_LEGACY #define __STM32_HAL_LEGACY #ifdef __cplusplus extern "C" { #endif /* Includes ------------------------------------------------------------------*/ /* Exported types ------------------------------------------------------------*/ /* Exported constants --------------------------------------------------------*/ /** @defgroup HAL_AES_Aliased_Defines HAL CRYP Aliased Defines maintained for legacy purpose * @{ */ #define AES_FLAG_RDERR CRYP_FLAG_RDERR #define AES_FLAG_WRERR CRYP_FLAG_WRERR #define AES_CLEARFLAG_CCF CRYP_CLEARFLAG_CCF #define AES_CLEARFLAG_RDERR CRYP_CLEARFLAG_RDERR #define AES_CLEARFLAG_WRERR CRYP_CLEARFLAG_WRERR /** * @} */ /** @defgroup HAL_ADC_Aliased_Defines HAL ADC Aliased Defines maintained for legacy purpose * @{ */ #define ADC_RESOLUTION12b ADC_RESOLUTION_12B #define ADC_RESOLUTION10b ADC_RESOLUTION_10B #define ADC_RESOLUTION8b ADC_RESOLUTION_8B #define ADC_RESOLUTION6b ADC_RESOLUTION_6B #define OVR_DATA_OVERWRITTEN ADC_OVR_DATA_OVERWRITTEN #define OVR_DATA_PRESERVED ADC_OVR_DATA_PRESERVED #define EOC_SINGLE_CONV ADC_EOC_SINGLE_CONV #define EOC_SEQ_CONV ADC_EOC_SEQ_CONV #define EOC_SINGLE_SEQ_CONV ADC_EOC_SINGLE_SEQ_CONV #define REGULAR_GROUP ADC_REGULAR_GROUP #define INJECTED_GROUP ADC_INJECTED_GROUP #define REGULAR_INJECTED_GROUP ADC_REGULAR_INJECTED_GROUP #define AWD_EVENT ADC_AWD_EVENT #define AWD1_EVENT ADC_AWD1_EVENT #define AWD2_EVENT ADC_AWD2_EVENT #define AWD3_EVENT ADC_AWD3_EVENT #define OVR_EVENT ADC_OVR_EVENT #define JQOVF_EVENT ADC_JQOVF_EVENT #define ALL_CHANNELS ADC_ALL_CHANNELS #define REGULAR_CHANNELS ADC_REGULAR_CHANNELS #define INJECTED_CHANNELS ADC_INJECTED_CHANNELS #define SYSCFG_FLAG_SENSOR_ADC ADC_FLAG_SENSOR #define SYSCFG_FLAG_VREF_ADC ADC_FLAG_VREFINT #define ADC_CLOCKPRESCALER_PCLK_DIV1 ADC_CLOCK_SYNC_PCLK_DIV1 #define ADC_CLOCKPRESCALER_PCLK_DIV2 ADC_CLOCK_SYNC_PCLK_DIV2 #define ADC_CLOCKPRESCALER_PCLK_DIV4 ADC_CLOCK_SYNC_PCLK_DIV4 #define ADC_CLOCKPRESCALER_PCLK_DIV6 ADC_CLOCK_SYNC_PCLK_DIV6 #define ADC_CLOCKPRESCALER_PCLK_DIV8 ADC_CLOCK_SYNC_PCLK_DIV8 #define ADC_EXTERNALTRIG0_T6_TRGO ADC_EXTERNALTRIGCONV_T6_TRGO #define ADC_EXTERNALTRIG1_T21_CC2 ADC_EXTERNALTRIGCONV_T21_CC2 #define ADC_EXTERNALTRIG2_T2_TRGO ADC_EXTERNALTRIGCONV_T2_TRGO #define ADC_EXTERNALTRIG3_T2_CC4 ADC_EXTERNALTRIGCONV_T2_CC4 #define ADC_EXTERNALTRIG4_T22_TRGO ADC_EXTERNALTRIGCONV_T22_TRGO #define ADC_EXTERNALTRIG7_EXT_IT11 ADC_EXTERNALTRIGCONV_EXT_IT11 #define ADC_CLOCK_ASYNC ADC_CLOCK_ASYNC_DIV1 #define ADC_EXTERNALTRIG_EDGE_NONE ADC_EXTERNALTRIGCONVEDGE_NONE #define ADC_EXTERNALTRIG_EDGE_RISING ADC_EXTERNALTRIGCONVEDGE_RISING #define ADC_EXTERNALTRIG_EDGE_FALLING ADC_EXTERNALTRIGCONVEDGE_FALLING #define ADC_EXTERNALTRIG_EDGE_RISINGFALLING ADC_EXTERNALTRIGCONVEDGE_RISINGFALLING /** * @} */ /** @defgroup HAL_CEC_Aliased_Defines HAL CEC Aliased Defines maintained for legacy purpose * @{ */ #define __HAL_CEC_GET_IT __HAL_CEC_GET_FLAG /** * @} */ /** @defgroup HAL_COMP_Aliased_Defines HAL COMP Aliased Defines maintained for legacy purpose * @{ */ #define COMP_WINDOWMODE_DISABLED COMP_WINDOWMODE_DISABLE #define COMP_WINDOWMODE_ENABLED COMP_WINDOWMODE_ENABLE #define COMP_EXTI_LINE_COMP1_EVENT COMP_EXTI_LINE_COMP1 #define COMP_EXTI_LINE_COMP2_EVENT COMP_EXTI_LINE_COMP2 /** * @} */ /** @defgroup HAL_CRC_Aliased_Defines HAL CRC Aliased Defines maintained for legacy purpose * @{ */ #define CRC_OUTPUTDATA_INVERSION_DISABLED CRC_OUTPUTDATA_INVERSION_DISABLE #define CRC_OUTPUTDATA_INVERSION_ENABLED CRC_OUTPUTDATA_INVERSION_ENABLE /** * @} */ /** @defgroup HAL_DAC_Aliased_Defines HAL DAC Aliased Defines maintained for legacy purpose * @{ */ #define DAC1_CHANNEL_1 DAC_CHANNEL_1 #define DAC1_CHANNEL_2 DAC_CHANNEL_2 #define DAC2_CHANNEL_1 DAC_CHANNEL_1 #define DAC_WAVE_NONE ((uint32_t)0x00000000) #define DAC_WAVE_NOISE ((uint32_t)DAC_CR_WAVE1_0) #define DAC_WAVE_TRIANGLE ((uint32_t)DAC_CR_WAVE1_1) #define DAC_WAVEGENERATION_NONE DAC_WAVE_NONE #define DAC_WAVEGENERATION_NOISE DAC_WAVE_NOISE #define DAC_WAVEGENERATION_TRIANGLE DAC_WAVE_TRIANGLE /** * @} */ /** @defgroup HAL_DMA_Aliased_Defines HAL DMA Aliased Defines maintained for legacy purpose * @{ */ #define HAL_REMAPDMA_ADC_DMA_CH2 DMA_REMAP_ADC_DMA_CH2 #define HAL_REMAPDMA_USART1_TX_DMA_CH4 DMA_REMAP_USART1_TX_DMA_CH4 #define HAL_REMAPDMA_USART1_RX_DMA_CH5 DMA_REMAP_USART1_RX_DMA_CH5 #define HAL_REMAPDMA_TIM16_DMA_CH4 DMA_REMAP_TIM16_DMA_CH4 #define HAL_REMAPDMA_TIM17_DMA_CH2 DMA_REMAP_TIM17_DMA_CH2 #define HAL_REMAPDMA_USART3_DMA_CH32 DMA_REMAP_USART3_DMA_CH32 #define HAL_REMAPDMA_TIM16_DMA_CH6 DMA_REMAP_TIM16_DMA_CH6 #define HAL_REMAPDMA_TIM17_DMA_CH7 DMA_REMAP_TIM17_DMA_CH7 #define HAL_REMAPDMA_SPI2_DMA_CH67 DMA_REMAP_SPI2_DMA_CH67 #define HAL_REMAPDMA_USART2_DMA_CH67 DMA_REMAP_USART2_DMA_CH67 #define HAL_REMAPDMA_USART3_DMA_CH32 DMA_REMAP_USART3_DMA_CH32 #define HAL_REMAPDMA_I2C1_DMA_CH76 DMA_REMAP_I2C1_DMA_CH76 #define HAL_REMAPDMA_TIM1_DMA_CH6 DMA_REMAP_TIM1_DMA_CH6 #define HAL_REMAPDMA_TIM2_DMA_CH7 DMA_REMAP_TIM2_DMA_CH7 #define HAL_REMAPDMA_TIM3_DMA_CH6 DMA_REMAP_TIM3_DMA_CH6 #define IS_HAL_REMAPDMA IS_DMA_REMAP #define __HAL_REMAPDMA_CHANNEL_ENABLE __HAL_DMA_REMAP_CHANNEL_ENABLE #define __HAL_REMAPDMA_CHANNEL_DISABLE __HAL_DMA_REMAP_CHANNEL_DISABLE /** * @} */ /** @defgroup HAL_FLASH_Aliased_Defines HAL FLASH Aliased Defines maintained for legacy purpose * @{ */ #define TYPEPROGRAM_BYTE FLASH_TYPEPROGRAM_BYTE #define TYPEPROGRAM_HALFWORD FLASH_TYPEPROGRAM_HALFWORD #define TYPEPROGRAM_WORD FLASH_TYPEPROGRAM_WORD #define TYPEPROGRAM_DOUBLEWORD FLASH_TYPEPROGRAM_DOUBLEWORD #define TYPEERASE_SECTORS FLASH_TYPEERASE_SECTORS #define TYPEERASE_PAGES FLASH_TYPEERASE_PAGES #define TYPEERASE_PAGEERASE FLASH_TYPEERASE_PAGES #define TYPEERASE_MASSERASE FLASH_TYPEERASE_MASSERASE #define WRPSTATE_DISABLE OB_WRPSTATE_DISABLE #define WRPSTATE_ENABLE OB_WRPSTATE_ENABLE #define HAL_FLASH_TIMEOUT_VALUE FLASH_TIMEOUT_VALUE #define OBEX_PCROP OPTIONBYTE_PCROP #define OBEX_BOOTCONFIG OPTIONBYTE_BOOTCONFIG #define PCROPSTATE_DISABLE OB_PCROP_STATE_DISABLE #define PCROPSTATE_ENABLE OB_PCROP_STATE_ENABLE #define TYPEERASEDATA_BYTE FLASH_TYPEERASEDATA_BYTE #define TYPEERASEDATA_HALFWORD FLASH_TYPEERASEDATA_HALFWORD #define TYPEERASEDATA_WORD FLASH_TYPEERASEDATA_WORD #define TYPEPROGRAMDATA_BYTE FLASH_TYPEPROGRAMDATA_BYTE #define TYPEPROGRAMDATA_HALFWORD FLASH_TYPEPROGRAMDATA_HALFWORD #define TYPEPROGRAMDATA_WORD FLASH_TYPEPROGRAMDATA_WORD #define TYPEPROGRAMDATA_FASTBYTE FLASH_TYPEPROGRAMDATA_FASTBYTE #define TYPEPROGRAMDATA_FASTHALFWORD FLASH_TYPEPROGRAMDATA_FASTHALFWORD #define TYPEPROGRAMDATA_FASTWORD FLASH_TYPEPROGRAMDATA_FASTWORD #define PAGESIZE FLASH_PAGE_SIZE #define TYPEPROGRAM_FASTBYTE FLASH_TYPEPROGRAM_BYTE #define TYPEPROGRAM_FASTHALFWORD FLASH_TYPEPROGRAM_HALFWORD #define TYPEPROGRAM_FASTWORD FLASH_TYPEPROGRAM_WORD #define VOLTAGE_RANGE_1 FLASH_VOLTAGE_RANGE_1 #define VOLTAGE_RANGE_2 FLASH_VOLTAGE_RANGE_2 #define VOLTAGE_RANGE_3 FLASH_VOLTAGE_RANGE_3 #define VOLTAGE_RANGE_4 FLASH_VOLTAGE_RANGE_4 #define TYPEPROGRAM_FAST FLASH_TYPEPROGRAM_FAST #define TYPEPROGRAM_FAST_AND_LAST FLASH_TYPEPROGRAM_FAST_AND_LAST #define WRPAREA_BANK1_AREAA OB_WRPAREA_BANK1_AREAA #define WRPAREA_BANK1_AREAB OB_WRPAREA_BANK1_AREAB #define WRPAREA_BANK2_AREAA OB_WRPAREA_BANK2_AREAA #define WRPAREA_BANK2_AREAB OB_WRPAREA_BANK2_AREAB #define IWDG_STDBY_FREEZE OB_IWDG_STDBY_FREEZE #define IWDG_STDBY_ACTIVE OB_IWDG_STDBY_RUN #define IWDG_STOP_FREEZE OB_IWDG_STOP_FREEZE #define IWDG_STOP_ACTIVE OB_IWDG_STOP_RUN #define FLASH_ERROR_NONE HAL_FLASH_ERROR_NONE #define FLASH_ERROR_RD HAL_FLASH_ERROR_RD #define FLASH_ERROR_PG HAL_FLASH_ERROR_PROG #define FLASH_ERROR_PGP HAL_FLASH_ERROR_PGS #define FLASH_ERROR_WRP HAL_FLASH_ERROR_WRP #define FLASH_ERROR_OPTV HAL_FLASH_ERROR_OPTV #define FLASH_ERROR_OPTVUSR HAL_FLASH_ERROR_OPTVUSR #define FLASH_ERROR_PROG HAL_FLASH_ERROR_PROG #define FLASH_ERROR_OP HAL_FLASH_ERROR_OPERATION #define FLASH_ERROR_PGA HAL_FLASH_ERROR_PGA #define FLASH_ERROR_SIZE HAL_FLASH_ERROR_SIZE #define FLASH_ERROR_SIZ HAL_FLASH_ERROR_SIZE #define FLASH_ERROR_PGS HAL_FLASH_ERROR_PGS #define FLASH_ERROR_MIS HAL_FLASH_ERROR_MIS #define FLASH_ERROR_FAST HAL_FLASH_ERROR_FAST #define FLASH_ERROR_FWWERR HAL_FLASH_ERROR_FWWERR #define FLASH_ERROR_NOTZERO HAL_FLASH_ERROR_NOTZERO #define FLASH_ERROR_OPERATION HAL_FLASH_ERROR_OPERATION #define FLASH_ERROR_ERS HAL_FLASH_ERROR_ERS #define OB_WDG_SW OB_IWDG_SW #define OB_WDG_HW OB_IWDG_HW #define OB_SDADC12_VDD_MONITOR_SET OB_SDACD_VDD_MONITOR_SET #define OB_SDADC12_VDD_MONITOR_RESET OB_SDACD_VDD_MONITOR_RESET #define OB_RAM_PARITY_CHECK_SET OB_SRAM_PARITY_SET #define OB_RAM_PARITY_CHECK_RESET OB_SRAM_PARITY_RESET #define IS_OB_SDADC12_VDD_MONITOR IS_OB_SDACD_VDD_MONITOR #define OB_RDP_LEVEL0 OB_RDP_LEVEL_0 #define OB_RDP_LEVEL1 OB_RDP_LEVEL_1 #define OB_RDP_LEVEL2 OB_RDP_LEVEL_2 /** * @} */ /** @defgroup HAL_SYSCFG_Aliased_Defines HAL SYSCFG Aliased Defines maintained for legacy purpose * @{ */ #define HAL_SYSCFG_FASTMODEPLUS_I2C_PA9 I2C_FASTMODEPLUS_PA9 #define HAL_SYSCFG_FASTMODEPLUS_I2C_PA10 I2C_FASTMODEPLUS_PA10 #define HAL_SYSCFG_FASTMODEPLUS_I2C_PB6 I2C_FASTMODEPLUS_PB6 #define HAL_SYSCFG_FASTMODEPLUS_I2C_PB7 I2C_FASTMODEPLUS_PB7 #define HAL_SYSCFG_FASTMODEPLUS_I2C_PB8 I2C_FASTMODEPLUS_PB8 #define HAL_SYSCFG_FASTMODEPLUS_I2C_PB9 I2C_FASTMODEPLUS_PB9 #define HAL_SYSCFG_FASTMODEPLUS_I2C1 I2C_FASTMODEPLUS_I2C1 #define HAL_SYSCFG_FASTMODEPLUS_I2C2 I2C_FASTMODEPLUS_I2C2 #define HAL_SYSCFG_FASTMODEPLUS_I2C3 I2C_FASTMODEPLUS_I2C3 /** * @} */ /** @defgroup LL_FMC_Aliased_Defines LL FMC Aliased Defines maintained for compatibility purpose * @{ */ #if defined(STM32L4) || defined(STM32F7) #define FMC_NAND_PCC_WAIT_FEATURE_DISABLE FMC_NAND_WAIT_FEATURE_DISABLE #define FMC_NAND_PCC_WAIT_FEATURE_ENABLE FMC_NAND_WAIT_FEATURE_ENABLE #define FMC_NAND_PCC_MEM_BUS_WIDTH_8 FMC_NAND_MEM_BUS_WIDTH_8 #define FMC_NAND_PCC_MEM_BUS_WIDTH_16 FMC_NAND_MEM_BUS_WIDTH_16 #else #define FMC_NAND_WAIT_FEATURE_DISABLE FMC_NAND_PCC_WAIT_FEATURE_DISABLE #define FMC_NAND_WAIT_FEATURE_ENABLE FMC_NAND_PCC_WAIT_FEATURE_ENABLE #define FMC_NAND_MEM_BUS_WIDTH_8 FMC_NAND_PCC_MEM_BUS_WIDTH_8 #define FMC_NAND_MEM_BUS_WIDTH_16 FMC_NAND_PCC_MEM_BUS_WIDTH_16 #endif /** * @} */ /** @defgroup LL_FSMC_Aliased_Defines LL FSMC Aliased Defines maintained for legacy purpose * @{ */ #define FSMC_NORSRAM_TYPEDEF FSMC_NORSRAM_TypeDef #define FSMC_NORSRAM_EXTENDED_TYPEDEF FSMC_NORSRAM_EXTENDED_TypeDef /** * @} */ /** @defgroup HAL_GPIO_Aliased_Macros HAL GPIO Aliased Macros maintained for legacy purpose * @{ */ #define GET_GPIO_SOURCE GPIO_GET_INDEX #define GET_GPIO_INDEX GPIO_GET_INDEX #if defined(STM32F4) #define GPIO_AF12_SDMMC GPIO_AF12_SDIO #define GPIO_AF12_SDMMC1 GPIO_AF12_SDIO #endif #if defined(STM32F7) #define GPIO_AF12_SDIO GPIO_AF12_SDMMC1 #define GPIO_AF12_SDMMC GPIO_AF12_SDMMC1 #endif #if defined(STM32L4) #define GPIO_AF12_SDIO GPIO_AF12_SDMMC1 #define GPIO_AF12_SDMMC GPIO_AF12_SDMMC1 #endif #define GPIO_AF0_LPTIM GPIO_AF0_LPTIM1 #define GPIO_AF1_LPTIM GPIO_AF1_LPTIM1 #define GPIO_AF2_LPTIM GPIO_AF2_LPTIM1 #if defined(STM32L0) || defined(STM32F4) #define GPIO_SPEED_LOW GPIO_SPEED_FREQ_LOW #define GPIO_SPEED_MEDIUM GPIO_SPEED_FREQ_MEDIUM #define GPIO_SPEED_FAST GPIO_SPEED_FREQ_HIGH #define GPIO_SPEED_HIGH GPIO_SPEED_FREQ_VERY_HIGH #endif /* STM32L0 || STM32F4 */ /** * @} */ /** @defgroup HAL_HRTIM_Aliased_Macros HAL HRTIM Aliased Macros maintained for legacy purpose * @{ */ #define HRTIM_TIMDELAYEDPROTECTION_DISABLED HRTIM_TIMER_A_B_C_DELAYEDPROTECTION_DISABLED #define HRTIM_TIMDELAYEDPROTECTION_DELAYEDOUT1_EEV68 HRTIM_TIMER_A_B_C_DELAYEDPROTECTION_DELAYEDOUT1_EEV6 #define HRTIM_TIMDELAYEDPROTECTION_DELAYEDOUT2_EEV68 HRTIM_TIMER_A_B_C_DELAYEDPROTECTION_DELAYEDOUT2_EEV6 #define HRTIM_TIMDELAYEDPROTECTION_DELAYEDBOTH_EEV68 HRTIM_TIMER_A_B_C_DELAYEDPROTECTION_DELAYEDBOTH_EEV6 #define HRTIM_TIMDELAYEDPROTECTION_BALANCED_EEV68 HRTIM_TIMER_A_B_C_DELAYEDPROTECTION_BALANCED_EEV6 #define HRTIM_TIMDELAYEDPROTECTION_DELAYEDOUT1_DEEV79 HRTIM_TIMER_A_B_C_DELAYEDPROTECTION_DELAYEDOUT1_DEEV7 #define HRTIM_TIMDELAYEDPROTECTION_DELAYEDOUT2_DEEV79 HRTIM_TIMER_A_B_C_DELAYEDPROTECTION_DELAYEDOUT2_DEEV7 #define HRTIM_TIMDELAYEDPROTECTION_DELAYEDBOTH_EEV79 HRTIM_TIMER_A_B_C_DELAYEDPROTECTION_DELAYEDBOTH_EEV7 #define HRTIM_TIMDELAYEDPROTECTION_BALANCED_EEV79 HRTIM_TIMER_A_B_C_DELAYEDPROTECTION_BALANCED_EEV7 /** * @} */ /** @defgroup HAL_I2C_Aliased_Defines HAL I2C Aliased Defines maintained for legacy purpose * @{ */ #define I2C_DUALADDRESS_DISABLED I2C_DUALADDRESS_DISABLE #define I2C_DUALADDRESS_ENABLED I2C_DUALADDRESS_ENABLE #define I2C_GENERALCALL_DISABLED I2C_GENERALCALL_DISABLE #define I2C_GENERALCALL_ENABLED I2C_GENERALCALL_ENABLE #define I2C_NOSTRETCH_DISABLED I2C_NOSTRETCH_DISABLE #define I2C_NOSTRETCH_ENABLED I2C_NOSTRETCH_ENABLE #define I2C_ANALOGFILTER_ENABLED I2C_ANALOGFILTER_ENABLE #define I2C_ANALOGFILTER_DISABLED I2C_ANALOGFILTER_DISABLE /** * @} */ /** @defgroup HAL_IRDA_Aliased_Defines HAL IRDA Aliased Defines maintained for legacy purpose * @{ */ #define IRDA_ONE_BIT_SAMPLE_DISABLED IRDA_ONE_BIT_SAMPLE_DISABLE #define IRDA_ONE_BIT_SAMPLE_ENABLED IRDA_ONE_BIT_SAMPLE_ENABLE /** * @} */ /** @defgroup HAL_IWDG_Aliased_Defines HAL IWDG Aliased Defines maintained for legacy purpose * @{ */ #define KR_KEY_RELOAD IWDG_KEY_RELOAD #define KR_KEY_ENABLE IWDG_KEY_ENABLE #define KR_KEY_EWA IWDG_KEY_WRITE_ACCESS_ENABLE #define KR_KEY_DWA IWDG_KEY_WRITE_ACCESS_DISABLE /** * @} */ /** @defgroup HAL_LPTIM_Aliased_Defines HAL LPTIM Aliased Defines maintained for legacy purpose * @{ */ #define LPTIM_CLOCKSAMPLETIME_DIRECTTRANSISTION LPTIM_CLOCKSAMPLETIME_DIRECTTRANSITION #define LPTIM_CLOCKSAMPLETIME_2TRANSISTIONS LPTIM_CLOCKSAMPLETIME_2TRANSITIONS #define LPTIM_CLOCKSAMPLETIME_4TRANSISTIONS LPTIM_CLOCKSAMPLETIME_4TRANSITIONS #define LPTIM_CLOCKSAMPLETIME_8TRANSISTIONS LPTIM_CLOCKSAMPLETIME_8TRANSITIONS #define LPTIM_CLOCKPOLARITY_RISINGEDGE LPTIM_CLOCKPOLARITY_RISING #define LPTIM_CLOCKPOLARITY_FALLINGEDGE LPTIM_CLOCKPOLARITY_FALLING #define LPTIM_CLOCKPOLARITY_BOTHEDGES LPTIM_CLOCKPOLARITY_RISING_FALLING #define LPTIM_TRIGSAMPLETIME_DIRECTTRANSISTION LPTIM_TRIGSAMPLETIME_DIRECTTRANSITION #define LPTIM_TRIGSAMPLETIME_2TRANSISTIONS LPTIM_TRIGSAMPLETIME_2TRANSITIONS #define LPTIM_TRIGSAMPLETIME_4TRANSISTIONS LPTIM_TRIGSAMPLETIME_4TRANSITIONS #define LPTIM_TRIGSAMPLETIME_8TRANSISTIONS LPTIM_TRIGSAMPLETIME_8TRANSITIONS /* The following 3 definition have also been present in a temporary version of lptim.h */ /* They need to be renamed also to the right name, just in case */ #define LPTIM_TRIGSAMPLETIME_2TRANSITION LPTIM_TRIGSAMPLETIME_2TRANSITIONS #define LPTIM_TRIGSAMPLETIME_4TRANSITION LPTIM_TRIGSAMPLETIME_4TRANSITIONS #define LPTIM_TRIGSAMPLETIME_8TRANSITION LPTIM_TRIGSAMPLETIME_8TRANSITIONS /** * @} */ /** @defgroup HAL_NAND_Aliased_Defines HAL NAND Aliased Defines maintained for legacy purpose * @{ */ #define NAND_AddressTypedef NAND_AddressTypeDef #define __ARRAY_ADDRESS ARRAY_ADDRESS #define __ADDR_1st_CYCLE ADDR_1ST_CYCLE #define __ADDR_2nd_CYCLE ADDR_2ND_CYCLE #define __ADDR_3rd_CYCLE ADDR_3RD_CYCLE #define __ADDR_4th_CYCLE ADDR_4TH_CYCLE /** * @} */ /** @defgroup HAL_NOR_Aliased_Defines HAL NOR Aliased Defines maintained for legacy purpose * @{ */ #define NOR_StatusTypedef HAL_NOR_StatusTypeDef #define NOR_SUCCESS HAL_NOR_STATUS_SUCCESS #define NOR_ONGOING HAL_NOR_STATUS_ONGOING #define NOR_ERROR HAL_NOR_STATUS_ERROR #define NOR_TIMEOUT HAL_NOR_STATUS_TIMEOUT #define __NOR_WRITE NOR_WRITE #define __NOR_ADDR_SHIFT NOR_ADDR_SHIFT /** * @} */ /** @defgroup HAL_OPAMP_Aliased_Defines HAL OPAMP Aliased Defines maintained for legacy purpose * @{ */ #define OPAMP_NONINVERTINGINPUT_VP0 OPAMP_NONINVERTINGINPUT_IO0 #define OPAMP_NONINVERTINGINPUT_VP1 OPAMP_NONINVERTINGINPUT_IO1 #define OPAMP_NONINVERTINGINPUT_VP2 OPAMP_NONINVERTINGINPUT_IO2 #define OPAMP_NONINVERTINGINPUT_VP3 OPAMP_NONINVERTINGINPUT_IO3 #define OPAMP_SEC_NONINVERTINGINPUT_VP0 OPAMP_SEC_NONINVERTINGINPUT_IO0 #define OPAMP_SEC_NONINVERTINGINPUT_VP1 OPAMP_SEC_NONINVERTINGINPUT_IO1 #define OPAMP_SEC_NONINVERTINGINPUT_VP2 OPAMP_SEC_NONINVERTINGINPUT_IO2 #define OPAMP_SEC_NONINVERTINGINPUT_VP3 OPAMP_SEC_NONINVERTINGINPUT_IO3 #define OPAMP_INVERTINGINPUT_VM0 OPAMP_INVERTINGINPUT_IO0 #define OPAMP_INVERTINGINPUT_VM1 OPAMP_INVERTINGINPUT_IO1 #define IOPAMP_INVERTINGINPUT_VM0 OPAMP_INVERTINGINPUT_IO0 #define IOPAMP_INVERTINGINPUT_VM1 OPAMP_INVERTINGINPUT_IO1 #define OPAMP_SEC_INVERTINGINPUT_VM0 OPAMP_SEC_INVERTINGINPUT_IO0 #define OPAMP_SEC_INVERTINGINPUT_VM1 OPAMP_SEC_INVERTINGINPUT_IO1 #define OPAMP_INVERTINGINPUT_VINM OPAMP_SEC_INVERTINGINPUT_IO1 #define OPAMP_PGACONNECT_NO OPAMP_PGA_CONNECT_INVERTINGINPUT_NO #define OPAMP_PGACONNECT_VM0 OPAMP_PGA_CONNECT_INVERTINGINPUT_IO0 #define OPAMP_PGACONNECT_VM1 OPAMP_PGA_CONNECT_INVERTINGINPUT_IO1 /** * @} */ /** @defgroup HAL_I2S_Aliased_Defines HAL I2S Aliased Defines maintained for legacy purpose * @{ */ #define I2S_STANDARD_PHILLIPS I2S_STANDARD_PHILIPS /** * @} */ /** @defgroup HAL_PCCARD_Aliased_Defines HAL PCCARD Aliased Defines maintained for legacy purpose * @{ */ /* Compact Flash-ATA registers description */ #define CF_DATA ATA_DATA #define CF_SECTOR_COUNT ATA_SECTOR_COUNT #define CF_SECTOR_NUMBER ATA_SECTOR_NUMBER #define CF_CYLINDER_LOW ATA_CYLINDER_LOW #define CF_CYLINDER_HIGH ATA_CYLINDER_HIGH #define CF_CARD_HEAD ATA_CARD_HEAD #define CF_STATUS_CMD ATA_STATUS_CMD #define CF_STATUS_CMD_ALTERNATE ATA_STATUS_CMD_ALTERNATE #define CF_COMMON_DATA_AREA ATA_COMMON_DATA_AREA /* Compact Flash-ATA commands */ #define CF_READ_SECTOR_CMD ATA_READ_SECTOR_CMD #define CF_WRITE_SECTOR_CMD ATA_WRITE_SECTOR_CMD #define CF_ERASE_SECTOR_CMD ATA_ERASE_SECTOR_CMD #define CF_IDENTIFY_CMD ATA_IDENTIFY_CMD #define PCCARD_StatusTypedef HAL_PCCARD_StatusTypeDef #define PCCARD_SUCCESS HAL_PCCARD_STATUS_SUCCESS #define PCCARD_ONGOING HAL_PCCARD_STATUS_ONGOING #define PCCARD_ERROR HAL_PCCARD_STATUS_ERROR #define PCCARD_TIMEOUT HAL_PCCARD_STATUS_TIMEOUT /** * @} */ /** @defgroup HAL_RTC_Aliased_Defines HAL RTC Aliased Defines maintained for legacy purpose * @{ */ #define FORMAT_BIN RTC_FORMAT_BIN #define FORMAT_BCD RTC_FORMAT_BCD #define RTC_ALARMSUBSECONDMASK_None RTC_ALARMSUBSECONDMASK_NONE #define RTC_TAMPERERASEBACKUP_ENABLED RTC_TAMPER_ERASE_BACKUP_ENABLE #define RTC_TAMPERERASEBACKUP_DISABLED RTC_TAMPER_ERASE_BACKUP_DISABLE #define RTC_TAMPERMASK_FLAG_DISABLED RTC_TAMPERMASK_FLAG_DISABLE #define RTC_TAMPERMASK_FLAG_ENABLED RTC_TAMPERMASK_FLAG_ENABLE #define RTC_MASKTAMPERFLAG_DISABLED RTC_TAMPERMASK_FLAG_DISABLE #define RTC_MASKTAMPERFLAG_ENABLED RTC_TAMPERMASK_FLAG_ENABLE #define RTC_TAMPERERASEBACKUP_ENABLED RTC_TAMPER_ERASE_BACKUP_ENABLE #define RTC_TAMPERERASEBACKUP_DISABLED RTC_TAMPER_ERASE_BACKUP_DISABLE #define RTC_MASKTAMPERFLAG_DISABLED RTC_TAMPERMASK_FLAG_DISABLE #define RTC_MASKTAMPERFLAG_ENABLED RTC_TAMPERMASK_FLAG_ENABLE #define RTC_TAMPER1_2_INTERRUPT RTC_ALL_TAMPER_INTERRUPT #define RTC_TAMPER1_2_3_INTERRUPT RTC_ALL_TAMPER_INTERRUPT #define RTC_TIMESTAMPPIN_PC13 RTC_TIMESTAMPPIN_DEFAULT #define RTC_TIMESTAMPPIN_PA0 RTC_TIMESTAMPPIN_POS1 #define RTC_TIMESTAMPPIN_PI8 RTC_TIMESTAMPPIN_POS1 #define RTC_TIMESTAMPPIN_PC1 RTC_TIMESTAMPPIN_POS2 #define RTC_OUTPUT_REMAP_PC13 RTC_OUTPUT_REMAP_NONE #define RTC_OUTPUT_REMAP_PB14 RTC_OUTPUT_REMAP_POS1 #define RTC_OUTPUT_REMAP_PB2 RTC_OUTPUT_REMAP_POS1 #define RTC_TAMPERPIN_PC13 RTC_TAMPERPIN_DEFAULT #define RTC_TAMPERPIN_PA0 RTC_TAMPERPIN_POS1 #define RTC_TAMPERPIN_PI8 RTC_TAMPERPIN_POS1 /** * @} */ /** @defgroup HAL_SMARTCARD_Aliased_Defines HAL SMARTCARD Aliased Defines maintained for legacy purpose * @{ */ #define SMARTCARD_NACK_ENABLED SMARTCARD_NACK_ENABLE #define SMARTCARD_NACK_DISABLED SMARTCARD_NACK_DISABLE #define SMARTCARD_ONEBIT_SAMPLING_DISABLED SMARTCARD_ONE_BIT_SAMPLE_DISABLE #define SMARTCARD_ONEBIT_SAMPLING_ENABLED SMARTCARD_ONE_BIT_SAMPLE_ENABLE #define SMARTCARD_ONEBIT_SAMPLING_DISABLE SMARTCARD_ONE_BIT_SAMPLE_DISABLE #define SMARTCARD_ONEBIT_SAMPLING_ENABLE SMARTCARD_ONE_BIT_SAMPLE_ENABLE #define SMARTCARD_TIMEOUT_DISABLED SMARTCARD_TIMEOUT_DISABLE #define SMARTCARD_TIMEOUT_ENABLED SMARTCARD_TIMEOUT_ENABLE #define SMARTCARD_LASTBIT_DISABLED SMARTCARD_LASTBIT_DISABLE #define SMARTCARD_LASTBIT_ENABLED SMARTCARD_LASTBIT_ENABLE /** * @} */ /** @defgroup HAL_SMBUS_Aliased_Defines HAL SMBUS Aliased Defines maintained for legacy purpose * @{ */ #define SMBUS_DUALADDRESS_DISABLED SMBUS_DUALADDRESS_DISABLE #define SMBUS_DUALADDRESS_ENABLED SMBUS_DUALADDRESS_ENABLE #define SMBUS_GENERALCALL_DISABLED SMBUS_GENERALCALL_DISABLE #define SMBUS_GENERALCALL_ENABLED SMBUS_GENERALCALL_ENABLE #define SMBUS_NOSTRETCH_DISABLED SMBUS_NOSTRETCH_DISABLE #define SMBUS_NOSTRETCH_ENABLED SMBUS_NOSTRETCH_ENABLE #define SMBUS_ANALOGFILTER_ENABLED SMBUS_ANALOGFILTER_ENABLE #define SMBUS_ANALOGFILTER_DISABLED SMBUS_ANALOGFILTER_DISABLE #define SMBUS_PEC_DISABLED SMBUS_PEC_DISABLE #define SMBUS_PEC_ENABLED SMBUS_PEC_ENABLE #define HAL_SMBUS_STATE_SLAVE_LISTEN HAL_SMBUS_STATE_LISTEN /** * @} */ /** @defgroup HAL_SPI_Aliased_Defines HAL SPI Aliased Defines maintained for legacy purpose * @{ */ #define SPI_TIMODE_DISABLED SPI_TIMODE_DISABLE #define SPI_TIMODE_ENABLED SPI_TIMODE_ENABLE #define SPI_CRCCALCULATION_DISABLED SPI_CRCCALCULATION_DISABLE #define SPI_CRCCALCULATION_ENABLED SPI_CRCCALCULATION_ENABLE #define SPI_NSS_PULSE_DISABLED SPI_NSS_PULSE_DISABLE #define SPI_NSS_PULSE_ENABLED SPI_NSS_PULSE_ENABLE /** * @} */ /** @defgroup HAL_TIM_Aliased_Defines HAL TIM Aliased Defines maintained for legacy purpose * @{ */ #define CCER_CCxE_MASK TIM_CCER_CCxE_MASK #define CCER_CCxNE_MASK TIM_CCER_CCxNE_MASK #define TIM_DMABase_CR1 TIM_DMABASE_CR1 #define TIM_DMABase_CR2 TIM_DMABASE_CR2 #define TIM_DMABase_SMCR TIM_DMABASE_SMCR #define TIM_DMABase_DIER TIM_DMABASE_DIER #define TIM_DMABase_SR TIM_DMABASE_SR #define TIM_DMABase_EGR TIM_DMABASE_EGR #define TIM_DMABase_CCMR1 TIM_DMABASE_CCMR1 #define TIM_DMABase_CCMR2 TIM_DMABASE_CCMR2 #define TIM_DMABase_CCER TIM_DMABASE_CCER #define TIM_DMABase_CNT TIM_DMABASE_CNT #define TIM_DMABase_PSC TIM_DMABASE_PSC #define TIM_DMABase_ARR TIM_DMABASE_ARR #define TIM_DMABase_RCR TIM_DMABASE_RCR #define TIM_DMABase_CCR1 TIM_DMABASE_CCR1 #define TIM_DMABase_CCR2 TIM_DMABASE_CCR2 #define TIM_DMABase_CCR3 TIM_DMABASE_CCR3 #define TIM_DMABase_CCR4 TIM_DMABASE_CCR4 #define TIM_DMABase_BDTR TIM_DMABASE_BDTR #define TIM_DMABase_DCR TIM_DMABASE_DCR #define TIM_DMABase_DMAR TIM_DMABASE_DMAR #define TIM_DMABase_OR1 TIM_DMABASE_OR1 #define TIM_DMABase_CCMR3 TIM_DMABASE_CCMR3 #define TIM_DMABase_CCR5 TIM_DMABASE_CCR5 #define TIM_DMABase_CCR6 TIM_DMABASE_CCR6 #define TIM_DMABase_OR2 TIM_DMABASE_OR2 #define TIM_DMABase_OR3 TIM_DMABASE_OR3 #define TIM_DMABase_OR TIM_DMABASE_OR #define TIM_EventSource_Update TIM_EVENTSOURCE_UPDATE #define TIM_EventSource_CC1 TIM_EVENTSOURCE_CC1 #define TIM_EventSource_CC2 TIM_EVENTSOURCE_CC2 #define TIM_EventSource_CC3 TIM_EVENTSOURCE_CC3 #define TIM_EventSource_CC4 TIM_EVENTSOURCE_CC4 #define TIM_EventSource_COM TIM_EVENTSOURCE_COM #define TIM_EventSource_Trigger TIM_EVENTSOURCE_TRIGGER #define TIM_EventSource_Break TIM_EVENTSOURCE_BREAK #define TIM_EventSource_Break2 TIM_EVENTSOURCE_BREAK2 #define TIM_DMABurstLength_1Transfer TIM_DMABURSTLENGTH_1TRANSFER #define TIM_DMABurstLength_2Transfers TIM_DMABURSTLENGTH_2TRANSFERS #define TIM_DMABurstLength_3Transfers TIM_DMABURSTLENGTH_3TRANSFERS #define TIM_DMABurstLength_4Transfers TIM_DMABURSTLENGTH_4TRANSFERS #define TIM_DMABurstLength_5Transfers TIM_DMABURSTLENGTH_5TRANSFERS #define TIM_DMABurstLength_6Transfers TIM_DMABURSTLENGTH_6TRANSFERS #define TIM_DMABurstLength_7Transfers TIM_DMABURSTLENGTH_7TRANSFERS #define TIM_DMABurstLength_8Transfers TIM_DMABURSTLENGTH_8TRANSFERS #define TIM_DMABurstLength_9Transfers TIM_DMABURSTLENGTH_9TRANSFERS #define TIM_DMABurstLength_10Transfers TIM_DMABURSTLENGTH_10TRANSFERS #define TIM_DMABurstLength_11Transfers TIM_DMABURSTLENGTH_11TRANSFERS #define TIM_DMABurstLength_12Transfers TIM_DMABURSTLENGTH_12TRANSFERS #define TIM_DMABurstLength_13Transfers TIM_DMABURSTLENGTH_13TRANSFERS #define TIM_DMABurstLength_14Transfers TIM_DMABURSTLENGTH_14TRANSFERS #define TIM_DMABurstLength_15Transfers TIM_DMABURSTLENGTH_15TRANSFERS #define TIM_DMABurstLength_16Transfers TIM_DMABURSTLENGTH_16TRANSFERS #define TIM_DMABurstLength_17Transfers TIM_DMABURSTLENGTH_17TRANSFERS #define TIM_DMABurstLength_18Transfers TIM_DMABURSTLENGTH_18TRANSFERS /** * @} */ /** @defgroup HAL_TSC_Aliased_Defines HAL TSC Aliased Defines maintained for legacy purpose * @{ */ #define TSC_SYNC_POL_FALL TSC_SYNC_POLARITY_FALLING #define TSC_SYNC_POL_RISE_HIGH TSC_SYNC_POLARITY_RISING /** * @} */ /** @defgroup HAL_UART_Aliased_Defines HAL UART Aliased Defines maintained for legacy purpose * @{ */ #define UART_ONEBIT_SAMPLING_DISABLED UART_ONE_BIT_SAMPLE_DISABLE #define UART_ONEBIT_SAMPLING_ENABLED UART_ONE_BIT_SAMPLE_ENABLE #define UART_ONE_BIT_SAMPLE_DISABLED UART_ONE_BIT_SAMPLE_DISABLE #define UART_ONE_BIT_SAMPLE_ENABLED UART_ONE_BIT_SAMPLE_ENABLE #define __HAL_UART_ONEBIT_ENABLE __HAL_UART_ONE_BIT_SAMPLE_ENABLE #define __HAL_UART_ONEBIT_DISABLE __HAL_UART_ONE_BIT_SAMPLE_DISABLE #define __DIV_SAMPLING16 UART_DIV_SAMPLING16 #define __DIVMANT_SAMPLING16 UART_DIVMANT_SAMPLING16 #define __DIVFRAQ_SAMPLING16 UART_DIVFRAQ_SAMPLING16 #define __UART_BRR_SAMPLING16 UART_BRR_SAMPLING16 #define __DIV_SAMPLING8 UART_DIV_SAMPLING8 #define __DIVMANT_SAMPLING8 UART_DIVMANT_SAMPLING8 #define __DIVFRAQ_SAMPLING8 UART_DIVFRAQ_SAMPLING8 #define __UART_BRR_SAMPLING8 UART_BRR_SAMPLING8 #define UART_WAKEUPMETHODE_IDLELINE UART_WAKEUPMETHOD_IDLELINE #define UART_WAKEUPMETHODE_ADDRESSMARK UART_WAKEUPMETHOD_ADDRESSMARK /** * @} */ /** @defgroup HAL_USART_Aliased_Defines HAL USART Aliased Defines maintained for legacy purpose * @{ */ #define USART_CLOCK_DISABLED USART_CLOCK_DISABLE #define USART_CLOCK_ENABLED USART_CLOCK_ENABLE #define USARTNACK_ENABLED USART_NACK_ENABLE #define USARTNACK_DISABLED USART_NACK_DISABLE /** * @} */ /** @defgroup HAL_WWDG_Aliased_Defines HAL WWDG Aliased Defines maintained for legacy purpose * @{ */ #define CFR_BASE WWDG_CFR_BASE /** * @} */ /** @defgroup HAL_CAN_Aliased_Defines HAL CAN Aliased Defines maintained for legacy purpose * @{ */ #define CAN_FilterFIFO0 CAN_FILTER_FIFO0 #define CAN_FilterFIFO1 CAN_FILTER_FIFO1 #define CAN_IT_RQCP0 CAN_IT_TME #define CAN_IT_RQCP1 CAN_IT_TME #define CAN_IT_RQCP2 CAN_IT_TME #define INAK_TIMEOUT CAN_TIMEOUT_VALUE #define SLAK_TIMEOUT CAN_TIMEOUT_VALUE #define CAN_TXSTATUS_FAILED ((uint8_t)0x00) #define CAN_TXSTATUS_OK ((uint8_t)0x01) #define CAN_TXSTATUS_PENDING ((uint8_t)0x02) /** * @} */ /** @defgroup HAL_ETH_Aliased_Defines HAL ETH Aliased Defines maintained for legacy purpose * @{ */ #define VLAN_TAG ETH_VLAN_TAG #define MIN_ETH_PAYLOAD ETH_MIN_ETH_PAYLOAD #define MAX_ETH_PAYLOAD ETH_MAX_ETH_PAYLOAD #define JUMBO_FRAME_PAYLOAD ETH_JUMBO_FRAME_PAYLOAD #define MACMIIAR_CR_MASK ETH_MACMIIAR_CR_MASK #define MACCR_CLEAR_MASK ETH_MACCR_CLEAR_MASK #define MACFCR_CLEAR_MASK ETH_MACFCR_CLEAR_MASK #define DMAOMR_CLEAR_MASK ETH_DMAOMR_CLEAR_MASK #define ETH_MMCCR ((uint32_t)0x00000100) #define ETH_MMCRIR ((uint32_t)0x00000104) #define ETH_MMCTIR ((uint32_t)0x00000108) #define ETH_MMCRIMR ((uint32_t)0x0000010C) #define ETH_MMCTIMR ((uint32_t)0x00000110) #define ETH_MMCTGFSCCR ((uint32_t)0x0000014C) #define ETH_MMCTGFMSCCR ((uint32_t)0x00000150) #define ETH_MMCTGFCR ((uint32_t)0x00000168) #define ETH_MMCRFCECR ((uint32_t)0x00000194) #define ETH_MMCRFAECR ((uint32_t)0x00000198) #define ETH_MMCRGUFCR ((uint32_t)0x000001C4) /** * @} */ /** @defgroup HAL_PPP_Aliased_Defines HAL PPP Aliased Defines maintained for legacy purpose * @{ */ /** * @} */ /* Exported functions --------------------------------------------------------*/ /** @defgroup HAL_CRYP_Aliased_Functions HAL CRYP Aliased Functions maintained for legacy purpose * @{ */ #define HAL_CRYP_ComputationCpltCallback HAL_CRYPEx_ComputationCpltCallback /** * @} */ /** @defgroup HAL_HASH_Aliased_Functions HAL HASH Aliased Functions maintained for legacy purpose * @{ */ #define HAL_HMAC_MD5_Finish HAL_HASH_MD5_Finish #define HAL_HMAC_SHA1_Finish HAL_HASH_SHA1_Finish #define HAL_HMAC_SHA224_Finish HAL_HASH_SHA224_Finish #define HAL_HMAC_SHA256_Finish HAL_HASH_SHA256_Finish /*HASH Algorithm Selection*/ #define HASH_AlgoSelection_SHA1 HASH_ALGOSELECTION_SHA1 #define HASH_AlgoSelection_SHA224 HASH_ALGOSELECTION_SHA224 #define HASH_AlgoSelection_SHA256 HASH_ALGOSELECTION_SHA256 #define HASH_AlgoSelection_MD5 HASH_ALGOSELECTION_MD5 #define HASH_AlgoMode_HASH HASH_ALGOMODE_HASH #define HASH_AlgoMode_HMAC HASH_ALGOMODE_HMAC #define HASH_HMACKeyType_ShortKey HASH_HMAC_KEYTYPE_SHORTKEY #define HASH_HMACKeyType_LongKey HASH_HMAC_KEYTYPE_LONGKEY /** * @} */ /** @defgroup HAL_Aliased_Functions HAL Generic Aliased Functions maintained for legacy purpose * @{ */ #define HAL_EnableDBGSleepMode HAL_DBGMCU_EnableDBGSleepMode #define HAL_DisableDBGSleepMode HAL_DBGMCU_DisableDBGSleepMode #define HAL_EnableDBGStopMode HAL_DBGMCU_EnableDBGStopMode #define HAL_DisableDBGStopMode HAL_DBGMCU_DisableDBGStopMode #define HAL_EnableDBGStandbyMode HAL_DBGMCU_EnableDBGStandbyMode #define HAL_DisableDBGStandbyMode HAL_DBGMCU_DisableDBGStandbyMode #define HAL_DBG_LowPowerConfig(Periph, cmd) (((cmd)==ENABLE)? HAL_DBGMCU_DBG_EnableLowPowerConfig(Periph) : HAL_DBGMCU_DBG_DisableLowPowerConfig(Periph)) #define HAL_VREFINT_OutputSelect HAL_SYSCFG_VREFINT_OutputSelect #define HAL_Lock_Cmd(cmd) (((cmd)==ENABLE) ? HAL_SYSCFG_Enable_Lock_VREFINT() : HAL_SYSCFG_Disable_Lock_VREFINT()) #define HAL_VREFINT_Cmd(cmd) (((cmd)==ENABLE)? HAL_SYSCFG_EnableVREFINT() : HAL_SYSCFG_DisableVREFINT()) #define HAL_ADC_EnableBuffer_Cmd(cmd) (((cmd)==ENABLE) ? HAL_ADCEx_EnableVREFINT() : HAL_ADCEx_DisableVREFINT()) #define HAL_ADC_EnableBufferSensor_Cmd(cmd) (((cmd)==ENABLE) ? HAL_ADCEx_EnableVREFINTTempSensor() : HAL_ADCEx_DisableVREFINTTempSensor()) /** * @} */ /** @defgroup HAL_FLASH_Aliased_Functions HAL FLASH Aliased Functions maintained for legacy purpose * @{ */ #define FLASH_HalfPageProgram HAL_FLASHEx_HalfPageProgram #define FLASH_EnableRunPowerDown HAL_FLASHEx_EnableRunPowerDown #define FLASH_DisableRunPowerDown HAL_FLASHEx_DisableRunPowerDown #define HAL_DATA_EEPROMEx_Unlock HAL_FLASHEx_DATAEEPROM_Unlock #define HAL_DATA_EEPROMEx_Lock HAL_FLASHEx_DATAEEPROM_Lock #define HAL_DATA_EEPROMEx_Erase HAL_FLASHEx_DATAEEPROM_Erase #define HAL_DATA_EEPROMEx_Program HAL_FLASHEx_DATAEEPROM_Program /** * @} */ /** @defgroup HAL_I2C_Aliased_Functions HAL I2C Aliased Functions maintained for legacy purpose * @{ */ #define HAL_I2CEx_AnalogFilter_Config HAL_I2CEx_ConfigAnalogFilter #define HAL_I2CEx_DigitalFilter_Config HAL_I2CEx_ConfigDigitalFilter #define HAL_I2CFastModePlusConfig(SYSCFG_I2CFastModePlus, cmd) (((cmd)==ENABLE)? HAL_I2CEx_EnableFastModePlus(SYSCFG_I2CFastModePlus): HAL_I2CEx_DisableFastModePlus(SYSCFG_I2CFastModePlus)) /** * @} */ /** @defgroup HAL_PWR_Aliased HAL PWR Aliased maintained for legacy purpose * @{ */ #define HAL_PWR_PVDConfig HAL_PWR_ConfigPVD #define HAL_PWR_DisableBkUpReg HAL_PWREx_DisableBkUpReg #define HAL_PWR_DisableFlashPowerDown HAL_PWREx_DisableFlashPowerDown #define HAL_PWR_DisableVddio2Monitor HAL_PWREx_DisableVddio2Monitor #define HAL_PWR_EnableBkUpReg HAL_PWREx_EnableBkUpReg #define HAL_PWR_EnableFlashPowerDown HAL_PWREx_EnableFlashPowerDown #define HAL_PWR_EnableVddio2Monitor HAL_PWREx_EnableVddio2Monitor #define HAL_PWR_PVD_PVM_IRQHandler HAL_PWREx_PVD_PVM_IRQHandler #define HAL_PWR_PVDLevelConfig HAL_PWR_ConfigPVD #define HAL_PWR_Vddio2Monitor_IRQHandler HAL_PWREx_Vddio2Monitor_IRQHandler #define HAL_PWR_Vddio2MonitorCallback HAL_PWREx_Vddio2MonitorCallback #define HAL_PWREx_ActivateOverDrive HAL_PWREx_EnableOverDrive #define HAL_PWREx_DeactivateOverDrive HAL_PWREx_DisableOverDrive #define HAL_PWREx_DisableSDADCAnalog HAL_PWREx_DisableSDADC #define HAL_PWREx_EnableSDADCAnalog HAL_PWREx_EnableSDADC #define HAL_PWREx_PVMConfig HAL_PWREx_ConfigPVM #define PWR_MODE_NORMAL PWR_PVD_MODE_NORMAL #define PWR_MODE_IT_RISING PWR_PVD_MODE_IT_RISING #define PWR_MODE_IT_FALLING PWR_PVD_MODE_IT_FALLING #define PWR_MODE_IT_RISING_FALLING PWR_PVD_MODE_IT_RISING_FALLING #define PWR_MODE_EVENT_RISING PWR_PVD_MODE_EVENT_RISING #define PWR_MODE_EVENT_FALLING PWR_PVD_MODE_EVENT_FALLING #define PWR_MODE_EVENT_RISING_FALLING PWR_PVD_MODE_EVENT_RISING_FALLING #define CR_OFFSET_BB PWR_CR_OFFSET_BB #define CSR_OFFSET_BB PWR_CSR_OFFSET_BB #define DBP_BitNumber DBP_BIT_NUMBER #define PVDE_BitNumber PVDE_BIT_NUMBER #define PMODE_BitNumber PMODE_BIT_NUMBER #define EWUP_BitNumber EWUP_BIT_NUMBER #define FPDS_BitNumber FPDS_BIT_NUMBER #define ODEN_BitNumber ODEN_BIT_NUMBER #define ODSWEN_BitNumber ODSWEN_BIT_NUMBER #define MRLVDS_BitNumber MRLVDS_BIT_NUMBER #define LPLVDS_BitNumber LPLVDS_BIT_NUMBER #define BRE_BitNumber BRE_BIT_NUMBER #define PWR_MODE_EVT PWR_PVD_MODE_NORMAL /** * @} */ /** @defgroup HAL_SMBUS_Aliased_Functions HAL SMBUS Aliased Functions maintained for legacy purpose * @{ */ #define HAL_SMBUS_Slave_Listen_IT HAL_SMBUS_EnableListen_IT #define HAL_SMBUS_SlaveAddrCallback HAL_SMBUS_AddrCallback #define HAL_SMBUS_SlaveListenCpltCallback HAL_SMBUS_ListenCpltCallback /** * @} */ /** @defgroup HAL_SPI_Aliased_Functions HAL SPI Aliased Functions maintained for legacy purpose * @{ */ #define HAL_SPI_FlushRxFifo HAL_SPIEx_FlushRxFifo /** * @} */ /** @defgroup HAL_TIM_Aliased_Functions HAL TIM Aliased Functions maintained for legacy purpose * @{ */ #define HAL_TIM_DMADelayPulseCplt TIM_DMADelayPulseCplt #define HAL_TIM_DMAError TIM_DMAError #define HAL_TIM_DMACaptureCplt TIM_DMACaptureCplt #define HAL_TIMEx_DMACommutationCplt TIMEx_DMACommutationCplt /** * @} */ /** @defgroup HAL_UART_Aliased_Functions HAL UART Aliased Functions maintained for legacy purpose * @{ */ #define HAL_UART_WakeupCallback HAL_UARTEx_WakeupCallback /** * @} */ /** @defgroup HAL_LTDC_Aliased_Functions HAL LTDC Aliased Functions maintained for legacy purpose * @{ */ #define HAL_LTDC_LineEvenCallback HAL_LTDC_LineEventCallback /** * @} */ /** @defgroup HAL_PPP_Aliased_Functions HAL PPP Aliased Functions maintained for legacy purpose * @{ */ /** * @} */ /* Exported macros ------------------------------------------------------------*/ /** @defgroup HAL_AES_Aliased_Macros HAL CRYP Aliased Macros maintained for legacy purpose * @{ */ #define AES_IT_CC CRYP_IT_CC #define AES_IT_ERR CRYP_IT_ERR #define AES_FLAG_CCF CRYP_FLAG_CCF /** * @} */ /** @defgroup HAL_Aliased_Macros HAL Generic Aliased Macros maintained for legacy purpose * @{ */ #define __HAL_GET_BOOT_MODE __HAL_SYSCFG_GET_BOOT_MODE #define __HAL_REMAPMEMORY_FLASH __HAL_SYSCFG_REMAPMEMORY_FLASH #define __HAL_REMAPMEMORY_SYSTEMFLASH __HAL_SYSCFG_REMAPMEMORY_SYSTEMFLASH #define __HAL_REMAPMEMORY_SRAM __HAL_SYSCFG_REMAPMEMORY_SRAM #define __HAL_REMAPMEMORY_FMC __HAL_SYSCFG_REMAPMEMORY_FMC #define __HAL_REMAPMEMORY_FMC_SDRAM __HAL_SYSCFG_REMAPMEMORY_FMC_SDRAM #define __HAL_REMAPMEMORY_FSMC __HAL_SYSCFG_REMAPMEMORY_FSMC #define __HAL_REMAPMEMORY_QUADSPI __HAL_SYSCFG_REMAPMEMORY_QUADSPI #define __HAL_FMC_BANK __HAL_SYSCFG_FMC_BANK #define __HAL_GET_FLAG __HAL_SYSCFG_GET_FLAG #define __HAL_CLEAR_FLAG __HAL_SYSCFG_CLEAR_FLAG #define __HAL_VREFINT_OUT_ENABLE __HAL_SYSCFG_VREFINT_OUT_ENABLE #define __HAL_VREFINT_OUT_DISABLE __HAL_SYSCFG_VREFINT_OUT_DISABLE #define SYSCFG_FLAG_VREF_READY SYSCFG_FLAG_VREFINT_READY #define SYSCFG_FLAG_RC48 RCC_FLAG_HSI48 #define IS_SYSCFG_FASTMODEPLUS_CONFIG IS_I2C_FASTMODEPLUS #define UFB_MODE_BitNumber UFB_MODE_BIT_NUMBER #define CMP_PD_BitNumber CMP_PD_BIT_NUMBER /** * @} */ /** @defgroup HAL_ADC_Aliased_Macros HAL ADC Aliased Macros maintained for legacy purpose * @{ */ #define __ADC_ENABLE __HAL_ADC_ENABLE #define __ADC_DISABLE __HAL_ADC_DISABLE #define __HAL_ADC_ENABLING_CONDITIONS ADC_ENABLING_CONDITIONS #define __HAL_ADC_DISABLING_CONDITIONS ADC_DISABLING_CONDITIONS #define __HAL_ADC_IS_ENABLED ADC_IS_ENABLE #define __ADC_IS_ENABLED ADC_IS_ENABLE #define __HAL_ADC_IS_SOFTWARE_START_REGULAR ADC_IS_SOFTWARE_START_REGULAR #define __HAL_ADC_IS_SOFTWARE_START_INJECTED ADC_IS_SOFTWARE_START_INJECTED #define __HAL_ADC_IS_CONVERSION_ONGOING_REGULAR_INJECTED ADC_IS_CONVERSION_ONGOING_REGULAR_INJECTED #define __HAL_ADC_IS_CONVERSION_ONGOING_REGULAR ADC_IS_CONVERSION_ONGOING_REGULAR #define __HAL_ADC_IS_CONVERSION_ONGOING_INJECTED ADC_IS_CONVERSION_ONGOING_INJECTED #define __HAL_ADC_IS_CONVERSION_ONGOING ADC_IS_CONVERSION_ONGOING #define __HAL_ADC_CLEAR_ERRORCODE ADC_CLEAR_ERRORCODE #define __HAL_ADC_GET_RESOLUTION ADC_GET_RESOLUTION #define __HAL_ADC_JSQR_RK ADC_JSQR_RK #define __HAL_ADC_CFGR_AWD1CH ADC_CFGR_AWD1CH_SHIFT #define __HAL_ADC_CFGR_AWD23CR ADC_CFGR_AWD23CR #define __HAL_ADC_CFGR_INJECT_AUTO_CONVERSION ADC_CFGR_INJECT_AUTO_CONVERSION #define __HAL_ADC_CFGR_INJECT_CONTEXT_QUEUE ADC_CFGR_INJECT_CONTEXT_QUEUE #define __HAL_ADC_CFGR_INJECT_DISCCONTINUOUS ADC_CFGR_INJECT_DISCCONTINUOUS #define __HAL_ADC_CFGR_REG_DISCCONTINUOUS ADC_CFGR_REG_DISCCONTINUOUS #define __HAL_ADC_CFGR_DISCONTINUOUS_NUM ADC_CFGR_DISCONTINUOUS_NUM #define __HAL_ADC_CFGR_AUTOWAIT ADC_CFGR_AUTOWAIT #define __HAL_ADC_CFGR_CONTINUOUS ADC_CFGR_CONTINUOUS #define __HAL_ADC_CFGR_OVERRUN ADC_CFGR_OVERRUN #define __HAL_ADC_CFGR_DMACONTREQ ADC_CFGR_DMACONTREQ #define __HAL_ADC_CFGR_EXTSEL ADC_CFGR_EXTSEL_SET #define __HAL_ADC_JSQR_JEXTSEL ADC_JSQR_JEXTSEL_SET #define __HAL_ADC_OFR_CHANNEL ADC_OFR_CHANNEL #define __HAL_ADC_DIFSEL_CHANNEL ADC_DIFSEL_CHANNEL #define __HAL_ADC_CALFACT_DIFF_SET ADC_CALFACT_DIFF_SET #define __HAL_ADC_CALFACT_DIFF_GET ADC_CALFACT_DIFF_GET #define __HAL_ADC_TRX_HIGHTHRESHOLD ADC_TRX_HIGHTHRESHOLD #define __HAL_ADC_OFFSET_SHIFT_RESOLUTION ADC_OFFSET_SHIFT_RESOLUTION #define __HAL_ADC_AWD1THRESHOLD_SHIFT_RESOLUTION ADC_AWD1THRESHOLD_SHIFT_RESOLUTION #define __HAL_ADC_AWD23THRESHOLD_SHIFT_RESOLUTION ADC_AWD23THRESHOLD_SHIFT_RESOLUTION #define __HAL_ADC_COMMON_REGISTER ADC_COMMON_REGISTER #define __HAL_ADC_COMMON_CCR_MULTI ADC_COMMON_CCR_MULTI #define __HAL_ADC_MULTIMODE_IS_ENABLED ADC_MULTIMODE_IS_ENABLE #define __ADC_MULTIMODE_IS_ENABLED ADC_MULTIMODE_IS_ENABLE #define __HAL_ADC_NONMULTIMODE_OR_MULTIMODEMASTER ADC_NONMULTIMODE_OR_MULTIMODEMASTER #define __HAL_ADC_COMMON_ADC_OTHER ADC_COMMON_ADC_OTHER #define __HAL_ADC_MULTI_SLAVE ADC_MULTI_SLAVE #define __HAL_ADC_SQR1_L ADC_SQR1_L_SHIFT #define __HAL_ADC_JSQR_JL ADC_JSQR_JL_SHIFT #define __HAL_ADC_JSQR_RK_JL ADC_JSQR_RK_JL #define __HAL_ADC_CR1_DISCONTINUOUS_NUM ADC_CR1_DISCONTINUOUS_NUM #define __HAL_ADC_CR1_SCAN ADC_CR1_SCAN_SET #define __HAL_ADC_CONVCYCLES_MAX_RANGE ADC_CONVCYCLES_MAX_RANGE #define __HAL_ADC_CLOCK_PRESCALER_RANGE ADC_CLOCK_PRESCALER_RANGE #define __HAL_ADC_GET_CLOCK_PRESCALER ADC_GET_CLOCK_PRESCALER #define __HAL_ADC_SQR1 ADC_SQR1 #define __HAL_ADC_SMPR1 ADC_SMPR1 #define __HAL_ADC_SMPR2 ADC_SMPR2 #define __HAL_ADC_SQR3_RK ADC_SQR3_RK #define __HAL_ADC_SQR2_RK ADC_SQR2_RK #define __HAL_ADC_SQR1_RK ADC_SQR1_RK #define __HAL_ADC_CR2_CONTINUOUS ADC_CR2_CONTINUOUS #define __HAL_ADC_CR1_DISCONTINUOUS ADC_CR1_DISCONTINUOUS #define __HAL_ADC_CR1_SCANCONV ADC_CR1_SCANCONV #define __HAL_ADC_CR2_EOCSelection ADC_CR2_EOCSelection #define __HAL_ADC_CR2_DMAContReq ADC_CR2_DMAContReq #define __HAL_ADC_GET_RESOLUTION ADC_GET_RESOLUTION #define __HAL_ADC_JSQR ADC_JSQR #define __HAL_ADC_CHSELR_CHANNEL ADC_CHSELR_CHANNEL #define __HAL_ADC_CFGR1_REG_DISCCONTINUOUS ADC_CFGR1_REG_DISCCONTINUOUS #define __HAL_ADC_CFGR1_AUTOOFF ADC_CFGR1_AUTOOFF #define __HAL_ADC_CFGR1_AUTOWAIT ADC_CFGR1_AUTOWAIT #define __HAL_ADC_CFGR1_CONTINUOUS ADC_CFGR1_CONTINUOUS #define __HAL_ADC_CFGR1_OVERRUN ADC_CFGR1_OVERRUN #define __HAL_ADC_CFGR1_SCANDIR ADC_CFGR1_SCANDIR #define __HAL_ADC_CFGR1_DMACONTREQ ADC_CFGR1_DMACONTREQ /** * @} */ /** @defgroup HAL_DAC_Aliased_Macros HAL DAC Aliased Macros maintained for legacy purpose * @{ */ #define __HAL_DHR12R1_ALIGNEMENT DAC_DHR12R1_ALIGNMENT #define __HAL_DHR12R2_ALIGNEMENT DAC_DHR12R2_ALIGNMENT #define __HAL_DHR12RD_ALIGNEMENT DAC_DHR12RD_ALIGNMENT #define IS_DAC_GENERATE_WAVE IS_DAC_WAVE /** * @} */ /** @defgroup HAL_DBGMCU_Aliased_Macros HAL DBGMCU Aliased Macros maintained for legacy purpose * @{ */ #define __HAL_FREEZE_TIM1_DBGMCU __HAL_DBGMCU_FREEZE_TIM1 #define __HAL_UNFREEZE_TIM1_DBGMCU __HAL_DBGMCU_UNFREEZE_TIM1 #define __HAL_FREEZE_TIM2_DBGMCU __HAL_DBGMCU_FREEZE_TIM2 #define __HAL_UNFREEZE_TIM2_DBGMCU __HAL_DBGMCU_UNFREEZE_TIM2 #define __HAL_FREEZE_TIM3_DBGMCU __HAL_DBGMCU_FREEZE_TIM3 #define __HAL_UNFREEZE_TIM3_DBGMCU __HAL_DBGMCU_UNFREEZE_TIM3 #define __HAL_FREEZE_TIM4_DBGMCU __HAL_DBGMCU_FREEZE_TIM4 #define __HAL_UNFREEZE_TIM4_DBGMCU __HAL_DBGMCU_UNFREEZE_TIM4 #define __HAL_FREEZE_TIM5_DBGMCU __HAL_DBGMCU_FREEZE_TIM5 #define __HAL_UNFREEZE_TIM5_DBGMCU __HAL_DBGMCU_UNFREEZE_TIM5 #define __HAL_FREEZE_TIM6_DBGMCU __HAL_DBGMCU_FREEZE_TIM6 #define __HAL_UNFREEZE_TIM6_DBGMCU __HAL_DBGMCU_UNFREEZE_TIM6 #define __HAL_FREEZE_TIM7_DBGMCU __HAL_DBGMCU_FREEZE_TIM7 #define __HAL_UNFREEZE_TIM7_DBGMCU __HAL_DBGMCU_UNFREEZE_TIM7 #define __HAL_FREEZE_TIM8_DBGMCU __HAL_DBGMCU_FREEZE_TIM8 #define __HAL_UNFREEZE_TIM8_DBGMCU __HAL_DBGMCU_UNFREEZE_TIM8 #define __HAL_FREEZE_TIM9_DBGMCU __HAL_DBGMCU_FREEZE_TIM9 #define __HAL_UNFREEZE_TIM9_DBGMCU __HAL_DBGMCU_UNFREEZE_TIM9 #define __HAL_FREEZE_TIM10_DBGMCU __HAL_DBGMCU_FREEZE_TIM10 #define __HAL_UNFREEZE_TIM10_DBGMCU __HAL_DBGMCU_UNFREEZE_TIM10 #define __HAL_FREEZE_TIM11_DBGMCU __HAL_DBGMCU_FREEZE_TIM11 #define __HAL_UNFREEZE_TIM11_DBGMCU __HAL_DBGMCU_UNFREEZE_TIM11 #define __HAL_FREEZE_TIM12_DBGMCU __HAL_DBGMCU_FREEZE_TIM12 #define __HAL_UNFREEZE_TIM12_DBGMCU __HAL_DBGMCU_UNFREEZE_TIM12 #define __HAL_FREEZE_TIM13_DBGMCU __HAL_DBGMCU_FREEZE_TIM13 #define __HAL_UNFREEZE_TIM13_DBGMCU __HAL_DBGMCU_UNFREEZE_TIM13 #define __HAL_FREEZE_TIM14_DBGMCU __HAL_DBGMCU_FREEZE_TIM14 #define __HAL_UNFREEZE_TIM14_DBGMCU __HAL_DBGMCU_UNFREEZE_TIM14 #define __HAL_FREEZE_CAN2_DBGMCU __HAL_DBGMCU_FREEZE_CAN2 #define __HAL_UNFREEZE_CAN2_DBGMCU __HAL_DBGMCU_UNFREEZE_CAN2 #define __HAL_FREEZE_TIM15_DBGMCU __HAL_DBGMCU_FREEZE_TIM15 #define __HAL_UNFREEZE_TIM15_DBGMCU __HAL_DBGMCU_UNFREEZE_TIM15 #define __HAL_FREEZE_TIM16_DBGMCU __HAL_DBGMCU_FREEZE_TIM16 #define __HAL_UNFREEZE_TIM16_DBGMCU __HAL_DBGMCU_UNFREEZE_TIM16 #define __HAL_FREEZE_TIM17_DBGMCU __HAL_DBGMCU_FREEZE_TIM17 #define __HAL_UNFREEZE_TIM17_DBGMCU __HAL_DBGMCU_UNFREEZE_TIM17 #define __HAL_FREEZE_RTC_DBGMCU __HAL_DBGMCU_FREEZE_RTC #define __HAL_UNFREEZE_RTC_DBGMCU __HAL_DBGMCU_UNFREEZE_RTC #define __HAL_FREEZE_WWDG_DBGMCU __HAL_DBGMCU_FREEZE_WWDG #define __HAL_UNFREEZE_WWDG_DBGMCU __HAL_DBGMCU_UNFREEZE_WWDG #define __HAL_FREEZE_IWDG_DBGMCU __HAL_DBGMCU_FREEZE_IWDG #define __HAL_UNFREEZE_IWDG_DBGMCU __HAL_DBGMCU_UNFREEZE_IWDG #define __HAL_FREEZE_I2C1_TIMEOUT_DBGMCU __HAL_DBGMCU_FREEZE_I2C1_TIMEOUT #define __HAL_UNFREEZE_I2C1_TIMEOUT_DBGMCU __HAL_DBGMCU_UNFREEZE_I2C1_TIMEOUT #define __HAL_FREEZE_I2C2_TIMEOUT_DBGMCU __HAL_DBGMCU_FREEZE_I2C2_TIMEOUT #define __HAL_UNFREEZE_I2C2_TIMEOUT_DBGMCU __HAL_DBGMCU_UNFREEZE_I2C2_TIMEOUT #define __HAL_FREEZE_I2C3_TIMEOUT_DBGMCU __HAL_DBGMCU_FREEZE_I2C3_TIMEOUT #define __HAL_UNFREEZE_I2C3_TIMEOUT_DBGMCU __HAL_DBGMCU_UNFREEZE_I2C3_TIMEOUT #define __HAL_FREEZE_CAN1_DBGMCU __HAL_DBGMCU_FREEZE_CAN1 #define __HAL_UNFREEZE_CAN1_DBGMCU __HAL_DBGMCU_UNFREEZE_CAN1 #define __HAL_FREEZE_LPTIM1_DBGMCU __HAL_DBGMCU_FREEZE_LPTIM1 #define __HAL_UNFREEZE_LPTIM1_DBGMCU __HAL_DBGMCU_UNFREEZE_LPTIM1 #define __HAL_FREEZE_LPTIM2_DBGMCU __HAL_DBGMCU_FREEZE_LPTIM2 #define __HAL_UNFREEZE_LPTIM2_DBGMCU __HAL_DBGMCU_UNFREEZE_LPTIM2 /** * @} */ /** @defgroup HAL_COMP_Aliased_Macros HAL COMP Aliased Macros maintained for legacy purpose * @{ */ #define __HAL_COMP_EXTI_RISING_IT_ENABLE(__EXTILINE__) (((__EXTILINE__) == COMP_EXTI_LINE_COMP1) ? __HAL_COMP_COMP1_EXTI_ENABLE_RISING_EDGE() : \ __HAL_COMP_COMP2_EXTI_ENABLE_RISING_EDGE()) #define __HAL_COMP_EXTI_RISING_IT_DISABLE(__EXTILINE__) (((__EXTILINE__) == COMP_EXTI_LINE_COMP1) ? __HAL_COMP_COMP1_EXTI_ENABLE_RISING_EDGE() : \ __HAL_COMP_COMP2_EXTI_DISABLE_RISING_EDGE()) #define __HAL_COMP_EXTI_FALLING_IT_ENABLE(__EXTILINE__) (((__EXTILINE__) == COMP_EXTI_LINE_COMP1) ? __HAL_COMP_COMP1_EXTI_ENABLE_FALLING_EDGE() : \ __HAL_COMP_COMP2_EXTI_ENABLE_FALLING_EDGE()) #define __HAL_COMP_EXTI_FALLING_IT_DISABLE(__EXTILINE__) (((__EXTILINE__) == COMP_EXTI_LINE_COMP1) ? __HAL_COMP_COMP1_EXTI_ENABLE_FALLING_EDGE() : \ __HAL_COMP_COMP2_EXTI_DISABLE_FALLING_EDGE()) #define __HAL_COMP_EXTI_ENABLE_IT(__EXTILINE__) (((__EXTILINE__) == COMP_EXTI_LINE_COMP1) ? __HAL_COMP_COMP1_EXTI_ENABLE_IT() : \ __HAL_COMP_COMP2_EXTI_ENABLE_IT()) #define __HAL_COMP_EXTI_DISABLE_IT(__EXTILINE__) (((__EXTILINE__) == COMP_EXTI_LINE_COMP1) ? __HAL_COMP_COMP1_EXTI_DISABLE_IT() : \ __HAL_COMP_COMP2_EXTI_DISABLE_IT()) #define __HAL_COMP_EXTI_GET_FLAG(__FLAG__) (((__FLAG__) == COMP_EXTI_LINE_COMP1) ? __HAL_COMP_COMP1_EXTI_GET_FLAG() : \ __HAL_COMP_COMP2_EXTI_GET_FLAG()) #define __HAL_COMP_EXTI_CLEAR_FLAG(__FLAG__) (((__FLAG__) == COMP_EXTI_LINE_COMP1) ? __HAL_COMP_COMP1_EXTI_CLEAR_FLAG() : \ __HAL_COMP_COMP2_EXTI_CLEAR_FLAG()) #define __HAL_COMP_GET_EXTI_LINE COMP_GET_EXTI_LINE /** * @} */ /** @defgroup HAL_DAC_Aliased_Macros HAL DAC Aliased Macros maintained for legacy purpose * @{ */ #define IS_DAC_WAVE(WAVE) (((WAVE) == DAC_WAVE_NONE) || \ ((WAVE) == DAC_WAVE_NOISE)|| \ ((WAVE) == DAC_WAVE_TRIANGLE)) /** * @} */ /** @defgroup HAL_FLASH_Aliased_Macros HAL FLASH Aliased Macros maintained for legacy purpose * @{ */ #define IS_WRPAREA IS_OB_WRPAREA #define IS_TYPEPROGRAM IS_FLASH_TYPEPROGRAM #define IS_TYPEPROGRAMFLASH IS_FLASH_TYPEPROGRAM #define IS_TYPEERASE IS_FLASH_TYPEERASE #define IS_NBSECTORS IS_FLASH_NBSECTORS #define IS_OB_WDG_SOURCE IS_OB_IWDG_SOURCE /** * @} */ /** @defgroup HAL_I2C_Aliased_Macros HAL I2C Aliased Macros maintained for legacy purpose * @{ */ #define __HAL_I2C_RESET_CR2 I2C_RESET_CR2 #define __HAL_I2C_GENERATE_START I2C_GENERATE_START #define __HAL_I2C_FREQ_RANGE I2C_FREQ_RANGE #define __HAL_I2C_RISE_TIME I2C_RISE_TIME #define __HAL_I2C_SPEED_STANDARD I2C_SPEED_STANDARD #define __HAL_I2C_SPEED_FAST I2C_SPEED_FAST #define __HAL_I2C_SPEED I2C_SPEED #define __HAL_I2C_7BIT_ADD_WRITE I2C_7BIT_ADD_WRITE #define __HAL_I2C_7BIT_ADD_READ I2C_7BIT_ADD_READ #define __HAL_I2C_10BIT_ADDRESS I2C_10BIT_ADDRESS #define __HAL_I2C_10BIT_HEADER_WRITE I2C_10BIT_HEADER_WRITE #define __HAL_I2C_10BIT_HEADER_READ I2C_10BIT_HEADER_READ #define __HAL_I2C_MEM_ADD_MSB I2C_MEM_ADD_MSB #define __HAL_I2C_MEM_ADD_LSB I2C_MEM_ADD_LSB #define __HAL_I2C_FREQRANGE I2C_FREQRANGE /** * @} */ /** @defgroup HAL_I2S_Aliased_Macros HAL I2S Aliased Macros maintained for legacy purpose * @{ */ #define IS_I2S_INSTANCE IS_I2S_ALL_INSTANCE #define IS_I2S_INSTANCE_EXT IS_I2S_ALL_INSTANCE_EXT /** * @} */ /** @defgroup HAL_IRDA_Aliased_Macros HAL IRDA Aliased Macros maintained for legacy purpose * @{ */ #define __IRDA_DISABLE __HAL_IRDA_DISABLE #define __IRDA_ENABLE __HAL_IRDA_ENABLE #define __HAL_IRDA_GETCLOCKSOURCE IRDA_GETCLOCKSOURCE #define __HAL_IRDA_MASK_COMPUTATION IRDA_MASK_COMPUTATION #define __IRDA_GETCLOCKSOURCE IRDA_GETCLOCKSOURCE #define __IRDA_MASK_COMPUTATION IRDA_MASK_COMPUTATION #define IS_IRDA_ONEBIT_SAMPLE IS_IRDA_ONE_BIT_SAMPLE /** * @} */ /** @defgroup HAL_IWDG_Aliased_Macros HAL IWDG Aliased Macros maintained for legacy purpose * @{ */ #define __HAL_IWDG_ENABLE_WRITE_ACCESS IWDG_ENABLE_WRITE_ACCESS #define __HAL_IWDG_DISABLE_WRITE_ACCESS IWDG_DISABLE_WRITE_ACCESS /** * @} */ /** @defgroup HAL_LPTIM_Aliased_Macros HAL LPTIM Aliased Macros maintained for legacy purpose * @{ */ #define __HAL_LPTIM_ENABLE_INTERRUPT __HAL_LPTIM_ENABLE_IT #define __HAL_LPTIM_DISABLE_INTERRUPT __HAL_LPTIM_DISABLE_IT #define __HAL_LPTIM_GET_ITSTATUS __HAL_LPTIM_GET_IT_SOURCE /** * @} */ /** @defgroup HAL_OPAMP_Aliased_Macros HAL OPAMP Aliased Macros maintained for legacy purpose * @{ */ #define __OPAMP_CSR_OPAXPD OPAMP_CSR_OPAXPD #define __OPAMP_CSR_S3SELX OPAMP_CSR_S3SELX #define __OPAMP_CSR_S4SELX OPAMP_CSR_S4SELX #define __OPAMP_CSR_S5SELX OPAMP_CSR_S5SELX #define __OPAMP_CSR_S6SELX OPAMP_CSR_S6SELX #define __OPAMP_CSR_OPAXCAL_L OPAMP_CSR_OPAXCAL_L #define __OPAMP_CSR_OPAXCAL_H OPAMP_CSR_OPAXCAL_H #define __OPAMP_CSR_OPAXLPM OPAMP_CSR_OPAXLPM #define __OPAMP_CSR_ALL_SWITCHES OPAMP_CSR_ALL_SWITCHES #define __OPAMP_CSR_ANAWSELX OPAMP_CSR_ANAWSELX #define __OPAMP_CSR_OPAXCALOUT OPAMP_CSR_OPAXCALOUT #define __OPAMP_OFFSET_TRIM_BITSPOSITION OPAMP_OFFSET_TRIM_BITSPOSITION #define __OPAMP_OFFSET_TRIM_SET OPAMP_OFFSET_TRIM_SET /** * @} */ /** @defgroup HAL_PWR_Aliased_Macros HAL PWR Aliased Macros maintained for legacy purpose * @{ */ #define __HAL_PVD_EVENT_DISABLE __HAL_PWR_PVD_EXTI_DISABLE_EVENT #define __HAL_PVD_EVENT_ENABLE __HAL_PWR_PVD_EXTI_ENABLE_EVENT #define __HAL_PVD_EXTI_FALLINGTRIGGER_DISABLE __HAL_PWR_PVD_EXTI_DISABLE_FALLING_EDGE #define __HAL_PVD_EXTI_FALLINGTRIGGER_ENABLE __HAL_PWR_PVD_EXTI_ENABLE_FALLING_EDGE #define __HAL_PVD_EXTI_RISINGTRIGGER_DISABLE __HAL_PWR_PVD_EXTI_DISABLE_RISING_EDGE #define __HAL_PVD_EXTI_RISINGTRIGGER_ENABLE __HAL_PWR_PVD_EXTI_ENABLE_RISING_EDGE #define __HAL_PVM_EVENT_DISABLE __HAL_PWR_PVM_EVENT_DISABLE #define __HAL_PVM_EVENT_ENABLE __HAL_PWR_PVM_EVENT_ENABLE #define __HAL_PVM_EXTI_FALLINGTRIGGER_DISABLE __HAL_PWR_PVM_EXTI_FALLINGTRIGGER_DISABLE #define __HAL_PVM_EXTI_FALLINGTRIGGER_ENABLE __HAL_PWR_PVM_EXTI_FALLINGTRIGGER_ENABLE #define __HAL_PVM_EXTI_RISINGTRIGGER_DISABLE __HAL_PWR_PVM_EXTI_RISINGTRIGGER_DISABLE #define __HAL_PVM_EXTI_RISINGTRIGGER_ENABLE __HAL_PWR_PVM_EXTI_RISINGTRIGGER_ENABLE #define __HAL_PWR_INTERNALWAKEUP_DISABLE HAL_PWREx_DisableInternalWakeUpLine #define __HAL_PWR_INTERNALWAKEUP_ENABLE HAL_PWREx_EnableInternalWakeUpLine #define __HAL_PWR_PULL_UP_DOWN_CONFIG_DISABLE HAL_PWREx_DisablePullUpPullDownConfig #define __HAL_PWR_PULL_UP_DOWN_CONFIG_ENABLE HAL_PWREx_EnablePullUpPullDownConfig #define __HAL_PWR_PVD_EXTI_CLEAR_EGDE_TRIGGER() __HAL_PWR_PVD_EXTI_DISABLE_RISING_EDGE();__HAL_PWR_PVD_EXTI_DISABLE_FALLING_EDGE() #define __HAL_PWR_PVD_EXTI_EVENT_DISABLE __HAL_PWR_PVD_EXTI_DISABLE_EVENT #define __HAL_PWR_PVD_EXTI_EVENT_ENABLE __HAL_PWR_PVD_EXTI_ENABLE_EVENT #define __HAL_PWR_PVD_EXTI_FALLINGTRIGGER_DISABLE __HAL_PWR_PVD_EXTI_DISABLE_FALLING_EDGE #define __HAL_PWR_PVD_EXTI_FALLINGTRIGGER_ENABLE __HAL_PWR_PVD_EXTI_ENABLE_FALLING_EDGE #define __HAL_PWR_PVD_EXTI_RISINGTRIGGER_DISABLE __HAL_PWR_PVD_EXTI_DISABLE_RISING_EDGE #define __HAL_PWR_PVD_EXTI_RISINGTRIGGER_ENABLE __HAL_PWR_PVD_EXTI_ENABLE_RISING_EDGE #define __HAL_PWR_PVD_EXTI_SET_FALLING_EGDE_TRIGGER __HAL_PWR_PVD_EXTI_ENABLE_FALLING_EDGE #define __HAL_PWR_PVD_EXTI_SET_RISING_EDGE_TRIGGER __HAL_PWR_PVD_EXTI_ENABLE_RISING_EDGE #define __HAL_PWR_PVM_DISABLE() HAL_PWREx_DisablePVM1();HAL_PWREx_DisablePVM2();HAL_PWREx_DisablePVM3();HAL_PWREx_DisablePVM4() #define __HAL_PWR_PVM_ENABLE() HAL_PWREx_EnablePVM1();HAL_PWREx_EnablePVM2();HAL_PWREx_EnablePVM3();HAL_PWREx_EnablePVM4() #define __HAL_PWR_SRAM2CONTENT_PRESERVE_DISABLE HAL_PWREx_DisableSRAM2ContentRetention #define __HAL_PWR_SRAM2CONTENT_PRESERVE_ENABLE HAL_PWREx_EnableSRAM2ContentRetention #define __HAL_PWR_VDDIO2_DISABLE HAL_PWREx_DisableVddIO2 #define __HAL_PWR_VDDIO2_ENABLE HAL_PWREx_EnableVddIO2 #define __HAL_PWR_VDDIO2_EXTI_CLEAR_EGDE_TRIGGER __HAL_PWR_VDDIO2_EXTI_DISABLE_FALLING_EDGE #define __HAL_PWR_VDDIO2_EXTI_SET_FALLING_EGDE_TRIGGER __HAL_PWR_VDDIO2_EXTI_ENABLE_FALLING_EDGE #define __HAL_PWR_VDDUSB_DISABLE HAL_PWREx_DisableVddUSB #define __HAL_PWR_VDDUSB_ENABLE HAL_PWREx_EnableVddUSB #if defined (STM32F4) #define __HAL_PVD_EXTI_ENABLE_IT(PWR_EXTI_LINE_PVD) __HAL_PWR_PVD_EXTI_ENABLE_IT() #define __HAL_PVD_EXTI_DISABLE_IT(PWR_EXTI_LINE_PVD) __HAL_PWR_PVD_EXTI_DISABLE_IT() #define __HAL_PVD_EXTI_GET_FLAG(PWR_EXTI_LINE_PVD) __HAL_PWR_PVD_EXTI_GET_FLAG() #define __HAL_PVD_EXTI_CLEAR_FLAG(PWR_EXTI_LINE_PVD) __HAL_PWR_PVD_EXTI_CLEAR_FLAG() #define __HAL_PVD_EXTI_GENERATE_SWIT(PWR_EXTI_LINE_PVD) __HAL_PWR_PVD_EXTI_GENERATE_SWIT() #else #define __HAL_PVD_EXTI_CLEAR_FLAG __HAL_PWR_PVD_EXTI_CLEAR_FLAG #define __HAL_PVD_EXTI_DISABLE_IT __HAL_PWR_PVD_EXTI_DISABLE_IT #define __HAL_PVD_EXTI_ENABLE_IT __HAL_PWR_PVD_EXTI_ENABLE_IT #define __HAL_PVD_EXTI_GENERATE_SWIT __HAL_PWR_PVD_EXTI_GENERATE_SWIT #define __HAL_PVD_EXTI_GET_FLAG __HAL_PWR_PVD_EXTI_GET_FLAG #endif /* STM32F4 */ /** * @} */ /** @defgroup HAL_RCC_Aliased HAL RCC Aliased maintained for legacy purpose * @{ */ #define RCC_StopWakeUpClock_MSI RCC_STOP_WAKEUPCLOCK_MSI #define RCC_StopWakeUpClock_HSI RCC_STOP_WAKEUPCLOCK_HSI #define HAL_RCC_CCSCallback HAL_RCC_CSSCallback #define HAL_RC48_EnableBuffer_Cmd(cmd) (((cmd)==ENABLE) ? HAL_RCCEx_EnableHSI48_VREFINT() : HAL_RCCEx_DisableHSI48_VREFINT()) #define __ADC_CLK_DISABLE __HAL_RCC_ADC_CLK_DISABLE #define __ADC_CLK_ENABLE __HAL_RCC_ADC_CLK_ENABLE #define __ADC_CLK_SLEEP_DISABLE __HAL_RCC_ADC_CLK_SLEEP_DISABLE #define __ADC_CLK_SLEEP_ENABLE __HAL_RCC_ADC_CLK_SLEEP_ENABLE #define __ADC_FORCE_RESET __HAL_RCC_ADC_FORCE_RESET #define __ADC_RELEASE_RESET __HAL_RCC_ADC_RELEASE_RESET #define __ADC1_CLK_DISABLE __HAL_RCC_ADC1_CLK_DISABLE #define __ADC1_CLK_ENABLE __HAL_RCC_ADC1_CLK_ENABLE #define __ADC1_FORCE_RESET __HAL_RCC_ADC1_FORCE_RESET #define __ADC1_RELEASE_RESET __HAL_RCC_ADC1_RELEASE_RESET #define __ADC1_CLK_SLEEP_ENABLE __HAL_RCC_ADC1_CLK_SLEEP_ENABLE #define __ADC1_CLK_SLEEP_DISABLE __HAL_RCC_ADC1_CLK_SLEEP_DISABLE #define __ADC2_CLK_DISABLE __HAL_RCC_ADC2_CLK_DISABLE #define __ADC2_CLK_ENABLE __HAL_RCC_ADC2_CLK_ENABLE #define __ADC2_FORCE_RESET __HAL_RCC_ADC2_FORCE_RESET #define __ADC2_RELEASE_RESET __HAL_RCC_ADC2_RELEASE_RESET #define __ADC3_CLK_DISABLE __HAL_RCC_ADC3_CLK_DISABLE #define __ADC3_CLK_ENABLE __HAL_RCC_ADC3_CLK_ENABLE #define __ADC3_FORCE_RESET __HAL_RCC_ADC3_FORCE_RESET #define __ADC3_RELEASE_RESET __HAL_RCC_ADC3_RELEASE_RESET #define __AES_CLK_DISABLE __HAL_RCC_AES_CLK_DISABLE #define __AES_CLK_ENABLE __HAL_RCC_AES_CLK_ENABLE #define __AES_CLK_SLEEP_DISABLE __HAL_RCC_AES_CLK_SLEEP_DISABLE #define __AES_CLK_SLEEP_ENABLE __HAL_RCC_AES_CLK_SLEEP_ENABLE #define __AES_FORCE_RESET __HAL_RCC_AES_FORCE_RESET #define __AES_RELEASE_RESET __HAL_RCC_AES_RELEASE_RESET #define __CRYP_CLK_SLEEP_ENABLE __HAL_RCC_CRYP_CLK_SLEEP_ENABLE #define __CRYP_CLK_SLEEP_DISABLE __HAL_RCC_CRYP_CLK_SLEEP_DISABLE #define __CRYP_CLK_ENABLE __HAL_RCC_CRYP_CLK_ENABLE #define __CRYP_CLK_DISABLE __HAL_RCC_CRYP_CLK_DISABLE #define __CRYP_FORCE_RESET __HAL_RCC_CRYP_FORCE_RESET #define __CRYP_RELEASE_RESET __HAL_RCC_CRYP_RELEASE_RESET #define __AFIO_CLK_DISABLE __HAL_RCC_AFIO_CLK_DISABLE #define __AFIO_CLK_ENABLE __HAL_RCC_AFIO_CLK_ENABLE #define __AFIO_FORCE_RESET __HAL_RCC_AFIO_FORCE_RESET #define __AFIO_RELEASE_RESET __HAL_RCC_AFIO_RELEASE_RESET #define __AHB_FORCE_RESET __HAL_RCC_AHB_FORCE_RESET #define __AHB_RELEASE_RESET __HAL_RCC_AHB_RELEASE_RESET #define __AHB1_FORCE_RESET __HAL_RCC_AHB1_FORCE_RESET #define __AHB1_RELEASE_RESET __HAL_RCC_AHB1_RELEASE_RESET #define __AHB2_FORCE_RESET __HAL_RCC_AHB2_FORCE_RESET #define __AHB2_RELEASE_RESET __HAL_RCC_AHB2_RELEASE_RESET #define __AHB3_FORCE_RESET __HAL_RCC_AHB3_FORCE_RESET #define __AHB3_RELEASE_RESET __HAL_RCC_AHB3_RELEASE_RESET #define __APB1_FORCE_RESET __HAL_RCC_APB1_FORCE_RESET #define __APB1_RELEASE_RESET __HAL_RCC_APB1_RELEASE_RESET #define __APB2_FORCE_RESET __HAL_RCC_APB2_FORCE_RESET #define __APB2_RELEASE_RESET __HAL_RCC_APB2_RELEASE_RESET #define __BKP_CLK_DISABLE __HAL_RCC_BKP_CLK_DISABLE #define __BKP_CLK_ENABLE __HAL_RCC_BKP_CLK_ENABLE #define __BKP_FORCE_RESET __HAL_RCC_BKP_FORCE_RESET #define __BKP_RELEASE_RESET __HAL_RCC_BKP_RELEASE_RESET #define __CAN1_CLK_DISABLE __HAL_RCC_CAN1_CLK_DISABLE #define __CAN1_CLK_ENABLE __HAL_RCC_CAN1_CLK_ENABLE #define __CAN1_CLK_SLEEP_DISABLE __HAL_RCC_CAN1_CLK_SLEEP_DISABLE #define __CAN1_CLK_SLEEP_ENABLE __HAL_RCC_CAN1_CLK_SLEEP_ENABLE #define __CAN1_FORCE_RESET __HAL_RCC_CAN1_FORCE_RESET #define __CAN1_RELEASE_RESET __HAL_RCC_CAN1_RELEASE_RESET #define __CAN_CLK_DISABLE __HAL_RCC_CAN1_CLK_DISABLE #define __CAN_CLK_ENABLE __HAL_RCC_CAN1_CLK_ENABLE #define __CAN_FORCE_RESET __HAL_RCC_CAN1_FORCE_RESET #define __CAN_RELEASE_RESET __HAL_RCC_CAN1_RELEASE_RESET #define __CAN2_CLK_DISABLE __HAL_RCC_CAN2_CLK_DISABLE #define __CAN2_CLK_ENABLE __HAL_RCC_CAN2_CLK_ENABLE #define __CAN2_FORCE_RESET __HAL_RCC_CAN2_FORCE_RESET #define __CAN2_RELEASE_RESET __HAL_RCC_CAN2_RELEASE_RESET #define __CEC_CLK_DISABLE __HAL_RCC_CEC_CLK_DISABLE #define __CEC_CLK_ENABLE __HAL_RCC_CEC_CLK_ENABLE #define __COMP_CLK_DISABLE __HAL_RCC_COMP_CLK_DISABLE #define __COMP_CLK_ENABLE __HAL_RCC_COMP_CLK_ENABLE #define __COMP_FORCE_RESET __HAL_RCC_COMP_FORCE_RESET #define __COMP_RELEASE_RESET __HAL_RCC_COMP_RELEASE_RESET #define __COMP_CLK_SLEEP_ENABLE __HAL_RCC_COMP_CLK_SLEEP_ENABLE #define __COMP_CLK_SLEEP_DISABLE __HAL_RCC_COMP_CLK_SLEEP_DISABLE #define __CEC_FORCE_RESET __HAL_RCC_CEC_FORCE_RESET #define __CEC_RELEASE_RESET __HAL_RCC_CEC_RELEASE_RESET #define __CRC_CLK_DISABLE __HAL_RCC_CRC_CLK_DISABLE #define __CRC_CLK_ENABLE __HAL_RCC_CRC_CLK_ENABLE #define __CRC_CLK_SLEEP_DISABLE __HAL_RCC_CRC_CLK_SLEEP_DISABLE #define __CRC_CLK_SLEEP_ENABLE __HAL_RCC_CRC_CLK_SLEEP_ENABLE #define __CRC_FORCE_RESET __HAL_RCC_CRC_FORCE_RESET #define __CRC_RELEASE_RESET __HAL_RCC_CRC_RELEASE_RESET #define __DAC_CLK_DISABLE __HAL_RCC_DAC_CLK_DISABLE #define __DAC_CLK_ENABLE __HAL_RCC_DAC_CLK_ENABLE #define __DAC_FORCE_RESET __HAL_RCC_DAC_FORCE_RESET #define __DAC_RELEASE_RESET __HAL_RCC_DAC_RELEASE_RESET #define __DAC1_CLK_DISABLE __HAL_RCC_DAC1_CLK_DISABLE #define __DAC1_CLK_ENABLE __HAL_RCC_DAC1_CLK_ENABLE #define __DAC1_CLK_SLEEP_DISABLE __HAL_RCC_DAC1_CLK_SLEEP_DISABLE #define __DAC1_CLK_SLEEP_ENABLE __HAL_RCC_DAC1_CLK_SLEEP_ENABLE #define __DAC1_FORCE_RESET __HAL_RCC_DAC1_FORCE_RESET #define __DAC1_RELEASE_RESET __HAL_RCC_DAC1_RELEASE_RESET #define __DBGMCU_CLK_ENABLE __HAL_RCC_DBGMCU_CLK_ENABLE #define __DBGMCU_CLK_DISABLE __HAL_RCC_DBGMCU_CLK_DISABLE #define __DBGMCU_FORCE_RESET __HAL_RCC_DBGMCU_FORCE_RESET #define __DBGMCU_RELEASE_RESET __HAL_RCC_DBGMCU_RELEASE_RESET #define __DFSDM_CLK_DISABLE __HAL_RCC_DFSDM_CLK_DISABLE #define __DFSDM_CLK_ENABLE __HAL_RCC_DFSDM_CLK_ENABLE #define __DFSDM_CLK_SLEEP_DISABLE __HAL_RCC_DFSDM_CLK_SLEEP_DISABLE #define __DFSDM_CLK_SLEEP_ENABLE __HAL_RCC_DFSDM_CLK_SLEEP_ENABLE #define __DFSDM_FORCE_RESET __HAL_RCC_DFSDM_FORCE_RESET #define __DFSDM_RELEASE_RESET __HAL_RCC_DFSDM_RELEASE_RESET #define __DMA1_CLK_DISABLE __HAL_RCC_DMA1_CLK_DISABLE #define __DMA1_CLK_ENABLE __HAL_RCC_DMA1_CLK_ENABLE #define __DMA1_CLK_SLEEP_DISABLE __HAL_RCC_DMA1_CLK_SLEEP_DISABLE #define __DMA1_CLK_SLEEP_ENABLE __HAL_RCC_DMA1_CLK_SLEEP_ENABLE #define __DMA1_FORCE_RESET __HAL_RCC_DMA1_FORCE_RESET #define __DMA1_RELEASE_RESET __HAL_RCC_DMA1_RELEASE_RESET #define __DMA2_CLK_DISABLE __HAL_RCC_DMA2_CLK_DISABLE #define __DMA2_CLK_ENABLE __HAL_RCC_DMA2_CLK_ENABLE #define __DMA2_CLK_SLEEP_DISABLE __HAL_RCC_DMA2_CLK_SLEEP_DISABLE #define __DMA2_CLK_SLEEP_ENABLE __HAL_RCC_DMA2_CLK_SLEEP_ENABLE #define __DMA2_FORCE_RESET __HAL_RCC_DMA2_FORCE_RESET #define __DMA2_RELEASE_RESET __HAL_RCC_DMA2_RELEASE_RESET #define __ETHMAC_CLK_DISABLE __HAL_RCC_ETHMAC_CLK_DISABLE #define __ETHMAC_CLK_ENABLE __HAL_RCC_ETHMAC_CLK_ENABLE #define __ETHMAC_FORCE_RESET __HAL_RCC_ETHMAC_FORCE_RESET #define __ETHMAC_RELEASE_RESET __HAL_RCC_ETHMAC_RELEASE_RESET #define __ETHMACRX_CLK_DISABLE __HAL_RCC_ETHMACRX_CLK_DISABLE #define __ETHMACRX_CLK_ENABLE __HAL_RCC_ETHMACRX_CLK_ENABLE #define __ETHMACTX_CLK_DISABLE __HAL_RCC_ETHMACTX_CLK_DISABLE #define __ETHMACTX_CLK_ENABLE __HAL_RCC_ETHMACTX_CLK_ENABLE #define __FIREWALL_CLK_DISABLE __HAL_RCC_FIREWALL_CLK_DISABLE #define __FIREWALL_CLK_ENABLE __HAL_RCC_FIREWALL_CLK_ENABLE #define __FLASH_CLK_DISABLE __HAL_RCC_FLASH_CLK_DISABLE #define __FLASH_CLK_ENABLE __HAL_RCC_FLASH_CLK_ENABLE #define __FLASH_CLK_SLEEP_DISABLE __HAL_RCC_FLASH_CLK_SLEEP_DISABLE #define __FLASH_CLK_SLEEP_ENABLE __HAL_RCC_FLASH_CLK_SLEEP_ENABLE #define __FLASH_FORCE_RESET __HAL_RCC_FLASH_FORCE_RESET #define __FLASH_RELEASE_RESET __HAL_RCC_FLASH_RELEASE_RESET #define __FLITF_CLK_DISABLE __HAL_RCC_FLITF_CLK_DISABLE #define __FLITF_CLK_ENABLE __HAL_RCC_FLITF_CLK_ENABLE #define __FLITF_FORCE_RESET __HAL_RCC_FLITF_FORCE_RESET #define __FLITF_RELEASE_RESET __HAL_RCC_FLITF_RELEASE_RESET #define __FLITF_CLK_SLEEP_ENABLE __HAL_RCC_FLITF_CLK_SLEEP_ENABLE #define __FLITF_CLK_SLEEP_DISABLE __HAL_RCC_FLITF_CLK_SLEEP_DISABLE #define __FMC_CLK_DISABLE __HAL_RCC_FMC_CLK_DISABLE #define __FMC_CLK_ENABLE __HAL_RCC_FMC_CLK_ENABLE #define __FMC_CLK_SLEEP_DISABLE __HAL_RCC_FMC_CLK_SLEEP_DISABLE #define __FMC_CLK_SLEEP_ENABLE __HAL_RCC_FMC_CLK_SLEEP_ENABLE #define __FMC_FORCE_RESET __HAL_RCC_FMC_FORCE_RESET #define __FMC_RELEASE_RESET __HAL_RCC_FMC_RELEASE_RESET #define __FSMC_CLK_DISABLE __HAL_RCC_FSMC_CLK_DISABLE #define __FSMC_CLK_ENABLE __HAL_RCC_FSMC_CLK_ENABLE #define __GPIOA_CLK_DISABLE __HAL_RCC_GPIOA_CLK_DISABLE #define __GPIOA_CLK_ENABLE __HAL_RCC_GPIOA_CLK_ENABLE #define __GPIOA_CLK_SLEEP_DISABLE __HAL_RCC_GPIOA_CLK_SLEEP_DISABLE #define __GPIOA_CLK_SLEEP_ENABLE __HAL_RCC_GPIOA_CLK_SLEEP_ENABLE #define __GPIOA_FORCE_RESET __HAL_RCC_GPIOA_FORCE_RESET #define __GPIOA_RELEASE_RESET __HAL_RCC_GPIOA_RELEASE_RESET #define __GPIOB_CLK_DISABLE __HAL_RCC_GPIOB_CLK_DISABLE #define __GPIOB_CLK_ENABLE __HAL_RCC_GPIOB_CLK_ENABLE #define __GPIOB_CLK_SLEEP_DISABLE __HAL_RCC_GPIOB_CLK_SLEEP_DISABLE #define __GPIOB_CLK_SLEEP_ENABLE __HAL_RCC_GPIOB_CLK_SLEEP_ENABLE #define __GPIOB_FORCE_RESET __HAL_RCC_GPIOB_FORCE_RESET #define __GPIOB_RELEASE_RESET __HAL_RCC_GPIOB_RELEASE_RESET #define __GPIOC_CLK_DISABLE __HAL_RCC_GPIOC_CLK_DISABLE #define __GPIOC_CLK_ENABLE __HAL_RCC_GPIOC_CLK_ENABLE #define __GPIOC_CLK_SLEEP_DISABLE __HAL_RCC_GPIOC_CLK_SLEEP_DISABLE #define __GPIOC_CLK_SLEEP_ENABLE __HAL_RCC_GPIOC_CLK_SLEEP_ENABLE #define __GPIOC_FORCE_RESET __HAL_RCC_GPIOC_FORCE_RESET #define __GPIOC_RELEASE_RESET __HAL_RCC_GPIOC_RELEASE_RESET #define __GPIOD_CLK_DISABLE __HAL_RCC_GPIOD_CLK_DISABLE #define __GPIOD_CLK_ENABLE __HAL_RCC_GPIOD_CLK_ENABLE #define __GPIOD_CLK_SLEEP_DISABLE __HAL_RCC_GPIOD_CLK_SLEEP_DISABLE #define __GPIOD_CLK_SLEEP_ENABLE __HAL_RCC_GPIOD_CLK_SLEEP_ENABLE #define __GPIOD_FORCE_RESET __HAL_RCC_GPIOD_FORCE_RESET #define __GPIOD_RELEASE_RESET __HAL_RCC_GPIOD_RELEASE_RESET #define __GPIOE_CLK_DISABLE __HAL_RCC_GPIOE_CLK_DISABLE #define __GPIOE_CLK_ENABLE __HAL_RCC_GPIOE_CLK_ENABLE #define __GPIOE_CLK_SLEEP_DISABLE __HAL_RCC_GPIOE_CLK_SLEEP_DISABLE #define __GPIOE_CLK_SLEEP_ENABLE __HAL_RCC_GPIOE_CLK_SLEEP_ENABLE #define __GPIOE_FORCE_RESET __HAL_RCC_GPIOE_FORCE_RESET #define __GPIOE_RELEASE_RESET __HAL_RCC_GPIOE_RELEASE_RESET #define __GPIOF_CLK_DISABLE __HAL_RCC_GPIOF_CLK_DISABLE #define __GPIOF_CLK_ENABLE __HAL_RCC_GPIOF_CLK_ENABLE #define __GPIOF_CLK_SLEEP_DISABLE __HAL_RCC_GPIOF_CLK_SLEEP_DISABLE #define __GPIOF_CLK_SLEEP_ENABLE __HAL_RCC_GPIOF_CLK_SLEEP_ENABLE #define __GPIOF_FORCE_RESET __HAL_RCC_GPIOF_FORCE_RESET #define __GPIOF_RELEASE_RESET __HAL_RCC_GPIOF_RELEASE_RESET #define __GPIOG_CLK_DISABLE __HAL_RCC_GPIOG_CLK_DISABLE #define __GPIOG_CLK_ENABLE __HAL_RCC_GPIOG_CLK_ENABLE #define __GPIOG_CLK_SLEEP_DISABLE __HAL_RCC_GPIOG_CLK_SLEEP_DISABLE #define __GPIOG_CLK_SLEEP_ENABLE __HAL_RCC_GPIOG_CLK_SLEEP_ENABLE #define __GPIOG_FORCE_RESET __HAL_RCC_GPIOG_FORCE_RESET #define __GPIOG_RELEASE_RESET __HAL_RCC_GPIOG_RELEASE_RESET #define __GPIOH_CLK_DISABLE __HAL_RCC_GPIOH_CLK_DISABLE #define __GPIOH_CLK_ENABLE __HAL_RCC_GPIOH_CLK_ENABLE #define __GPIOH_CLK_SLEEP_DISABLE __HAL_RCC_GPIOH_CLK_SLEEP_DISABLE #define __GPIOH_CLK_SLEEP_ENABLE __HAL_RCC_GPIOH_CLK_SLEEP_ENABLE #define __GPIOH_FORCE_RESET __HAL_RCC_GPIOH_FORCE_RESET #define __GPIOH_RELEASE_RESET __HAL_RCC_GPIOH_RELEASE_RESET #define __I2C1_CLK_DISABLE __HAL_RCC_I2C1_CLK_DISABLE #define __I2C1_CLK_ENABLE __HAL_RCC_I2C1_CLK_ENABLE #define __I2C1_CLK_SLEEP_DISABLE __HAL_RCC_I2C1_CLK_SLEEP_DISABLE #define __I2C1_CLK_SLEEP_ENABLE __HAL_RCC_I2C1_CLK_SLEEP_ENABLE #define __I2C1_FORCE_RESET __HAL_RCC_I2C1_FORCE_RESET #define __I2C1_RELEASE_RESET __HAL_RCC_I2C1_RELEASE_RESET #define __I2C2_CLK_DISABLE __HAL_RCC_I2C2_CLK_DISABLE #define __I2C2_CLK_ENABLE __HAL_RCC_I2C2_CLK_ENABLE #define __I2C2_CLK_SLEEP_DISABLE __HAL_RCC_I2C2_CLK_SLEEP_DISABLE #define __I2C2_CLK_SLEEP_ENABLE __HAL_RCC_I2C2_CLK_SLEEP_ENABLE #define __I2C2_FORCE_RESET __HAL_RCC_I2C2_FORCE_RESET #define __I2C2_RELEASE_RESET __HAL_RCC_I2C2_RELEASE_RESET #define __I2C3_CLK_DISABLE __HAL_RCC_I2C3_CLK_DISABLE #define __I2C3_CLK_ENABLE __HAL_RCC_I2C3_CLK_ENABLE #define __I2C3_CLK_SLEEP_DISABLE __HAL_RCC_I2C3_CLK_SLEEP_DISABLE #define __I2C3_CLK_SLEEP_ENABLE __HAL_RCC_I2C3_CLK_SLEEP_ENABLE #define __I2C3_FORCE_RESET __HAL_RCC_I2C3_FORCE_RESET #define __I2C3_RELEASE_RESET __HAL_RCC_I2C3_RELEASE_RESET #define __LCD_CLK_DISABLE __HAL_RCC_LCD_CLK_DISABLE #define __LCD_CLK_ENABLE __HAL_RCC_LCD_CLK_ENABLE #define __LCD_CLK_SLEEP_DISABLE __HAL_RCC_LCD_CLK_SLEEP_DISABLE #define __LCD_CLK_SLEEP_ENABLE __HAL_RCC_LCD_CLK_SLEEP_ENABLE #define __LCD_FORCE_RESET __HAL_RCC_LCD_FORCE_RESET #define __LCD_RELEASE_RESET __HAL_RCC_LCD_RELEASE_RESET #define __LPTIM1_CLK_DISABLE __HAL_RCC_LPTIM1_CLK_DISABLE #define __LPTIM1_CLK_ENABLE __HAL_RCC_LPTIM1_CLK_ENABLE #define __LPTIM1_CLK_SLEEP_DISABLE __HAL_RCC_LPTIM1_CLK_SLEEP_DISABLE #define __LPTIM1_CLK_SLEEP_ENABLE __HAL_RCC_LPTIM1_CLK_SLEEP_ENABLE #define __LPTIM1_FORCE_RESET __HAL_RCC_LPTIM1_FORCE_RESET #define __LPTIM1_RELEASE_RESET __HAL_RCC_LPTIM1_RELEASE_RESET #define __LPTIM2_CLK_DISABLE __HAL_RCC_LPTIM2_CLK_DISABLE #define __LPTIM2_CLK_ENABLE __HAL_RCC_LPTIM2_CLK_ENABLE #define __LPTIM2_CLK_SLEEP_DISABLE __HAL_RCC_LPTIM2_CLK_SLEEP_DISABLE #define __LPTIM2_CLK_SLEEP_ENABLE __HAL_RCC_LPTIM2_CLK_SLEEP_ENABLE #define __LPTIM2_FORCE_RESET __HAL_RCC_LPTIM2_FORCE_RESET #define __LPTIM2_RELEASE_RESET __HAL_RCC_LPTIM2_RELEASE_RESET #define __LPUART1_CLK_DISABLE __HAL_RCC_LPUART1_CLK_DISABLE #define __LPUART1_CLK_ENABLE __HAL_RCC_LPUART1_CLK_ENABLE #define __LPUART1_CLK_SLEEP_DISABLE __HAL_RCC_LPUART1_CLK_SLEEP_DISABLE #define __LPUART1_CLK_SLEEP_ENABLE __HAL_RCC_LPUART1_CLK_SLEEP_ENABLE #define __LPUART1_FORCE_RESET __HAL_RCC_LPUART1_FORCE_RESET #define __LPUART1_RELEASE_RESET __HAL_RCC_LPUART1_RELEASE_RESET #define __OPAMP_CLK_DISABLE __HAL_RCC_OPAMP_CLK_DISABLE #define __OPAMP_CLK_ENABLE __HAL_RCC_OPAMP_CLK_ENABLE #define __OPAMP_CLK_SLEEP_DISABLE __HAL_RCC_OPAMP_CLK_SLEEP_DISABLE #define __OPAMP_CLK_SLEEP_ENABLE __HAL_RCC_OPAMP_CLK_SLEEP_ENABLE #define __OPAMP_FORCE_RESET __HAL_RCC_OPAMP_FORCE_RESET #define __OPAMP_RELEASE_RESET __HAL_RCC_OPAMP_RELEASE_RESET #define __OTGFS_CLK_DISABLE __HAL_RCC_OTGFS_CLK_DISABLE #define __OTGFS_CLK_ENABLE __HAL_RCC_OTGFS_CLK_ENABLE #define __OTGFS_CLK_SLEEP_DISABLE __HAL_RCC_OTGFS_CLK_SLEEP_DISABLE #define __OTGFS_CLK_SLEEP_ENABLE __HAL_RCC_OTGFS_CLK_SLEEP_ENABLE #define __OTGFS_FORCE_RESET __HAL_RCC_OTGFS_FORCE_RESET #define __OTGFS_RELEASE_RESET __HAL_RCC_OTGFS_RELEASE_RESET #define __PWR_CLK_DISABLE __HAL_RCC_PWR_CLK_DISABLE #define __PWR_CLK_ENABLE __HAL_RCC_PWR_CLK_ENABLE #define __PWR_CLK_SLEEP_DISABLE __HAL_RCC_PWR_CLK_SLEEP_DISABLE #define __PWR_CLK_SLEEP_ENABLE __HAL_RCC_PWR_CLK_SLEEP_ENABLE #define __PWR_FORCE_RESET __HAL_RCC_PWR_FORCE_RESET #define __PWR_RELEASE_RESET __HAL_RCC_PWR_RELEASE_RESET #define __QSPI_CLK_DISABLE __HAL_RCC_QSPI_CLK_DISABLE #define __QSPI_CLK_ENABLE __HAL_RCC_QSPI_CLK_ENABLE #define __QSPI_CLK_SLEEP_DISABLE __HAL_RCC_QSPI_CLK_SLEEP_DISABLE #define __QSPI_CLK_SLEEP_ENABLE __HAL_RCC_QSPI_CLK_SLEEP_ENABLE #define __QSPI_FORCE_RESET __HAL_RCC_QSPI_FORCE_RESET #define __QSPI_RELEASE_RESET __HAL_RCC_QSPI_RELEASE_RESET #define __RNG_CLK_DISABLE __HAL_RCC_RNG_CLK_DISABLE #define __RNG_CLK_ENABLE __HAL_RCC_RNG_CLK_ENABLE #define __RNG_CLK_SLEEP_DISABLE __HAL_RCC_RNG_CLK_SLEEP_DISABLE #define __RNG_CLK_SLEEP_ENABLE __HAL_RCC_RNG_CLK_SLEEP_ENABLE #define __RNG_FORCE_RESET __HAL_RCC_RNG_FORCE_RESET #define __RNG_RELEASE_RESET __HAL_RCC_RNG_RELEASE_RESET #define __SAI1_CLK_DISABLE __HAL_RCC_SAI1_CLK_DISABLE #define __SAI1_CLK_ENABLE __HAL_RCC_SAI1_CLK_ENABLE #define __SAI1_CLK_SLEEP_DISABLE __HAL_RCC_SAI1_CLK_SLEEP_DISABLE #define __SAI1_CLK_SLEEP_ENABLE __HAL_RCC_SAI1_CLK_SLEEP_ENABLE #define __SAI1_FORCE_RESET __HAL_RCC_SAI1_FORCE_RESET #define __SAI1_RELEASE_RESET __HAL_RCC_SAI1_RELEASE_RESET #define __SAI2_CLK_DISABLE __HAL_RCC_SAI2_CLK_DISABLE #define __SAI2_CLK_ENABLE __HAL_RCC_SAI2_CLK_ENABLE #define __SAI2_CLK_SLEEP_DISABLE __HAL_RCC_SAI2_CLK_SLEEP_DISABLE #define __SAI2_CLK_SLEEP_ENABLE __HAL_RCC_SAI2_CLK_SLEEP_ENABLE #define __SAI2_FORCE_RESET __HAL_RCC_SAI2_FORCE_RESET #define __SAI2_RELEASE_RESET __HAL_RCC_SAI2_RELEASE_RESET #define __SDIO_CLK_DISABLE __HAL_RCC_SDIO_CLK_DISABLE #define __SDIO_CLK_ENABLE __HAL_RCC_SDIO_CLK_ENABLE #define __SDMMC_CLK_DISABLE __HAL_RCC_SDMMC_CLK_DISABLE #define __SDMMC_CLK_ENABLE __HAL_RCC_SDMMC_CLK_ENABLE #define __SDMMC_CLK_SLEEP_DISABLE __HAL_RCC_SDMMC_CLK_SLEEP_DISABLE #define __SDMMC_CLK_SLEEP_ENABLE __HAL_RCC_SDMMC_CLK_SLEEP_ENABLE #define __SDMMC_FORCE_RESET __HAL_RCC_SDMMC_FORCE_RESET #define __SDMMC_RELEASE_RESET __HAL_RCC_SDMMC_RELEASE_RESET #define __SPI1_CLK_DISABLE __HAL_RCC_SPI1_CLK_DISABLE #define __SPI1_CLK_ENABLE __HAL_RCC_SPI1_CLK_ENABLE #define __SPI1_CLK_SLEEP_DISABLE __HAL_RCC_SPI1_CLK_SLEEP_DISABLE #define __SPI1_CLK_SLEEP_ENABLE __HAL_RCC_SPI1_CLK_SLEEP_ENABLE #define __SPI1_FORCE_RESET __HAL_RCC_SPI1_FORCE_RESET #define __SPI1_RELEASE_RESET __HAL_RCC_SPI1_RELEASE_RESET #define __SPI2_CLK_DISABLE __HAL_RCC_SPI2_CLK_DISABLE #define __SPI2_CLK_ENABLE __HAL_RCC_SPI2_CLK_ENABLE #define __SPI2_CLK_SLEEP_DISABLE __HAL_RCC_SPI2_CLK_SLEEP_DISABLE #define __SPI2_CLK_SLEEP_ENABLE __HAL_RCC_SPI2_CLK_SLEEP_ENABLE #define __SPI2_FORCE_RESET __HAL_RCC_SPI2_FORCE_RESET #define __SPI2_RELEASE_RESET __HAL_RCC_SPI2_RELEASE_RESET #define __SPI3_CLK_DISABLE __HAL_RCC_SPI3_CLK_DISABLE #define __SPI3_CLK_ENABLE __HAL_RCC_SPI3_CLK_ENABLE #define __SPI3_CLK_SLEEP_DISABLE __HAL_RCC_SPI3_CLK_SLEEP_DISABLE #define __SPI3_CLK_SLEEP_ENABLE __HAL_RCC_SPI3_CLK_SLEEP_ENABLE #define __SPI3_FORCE_RESET __HAL_RCC_SPI3_FORCE_RESET #define __SPI3_RELEASE_RESET __HAL_RCC_SPI3_RELEASE_RESET #define __SRAM_CLK_DISABLE __HAL_RCC_SRAM_CLK_DISABLE #define __SRAM_CLK_ENABLE __HAL_RCC_SRAM_CLK_ENABLE #define __SRAM1_CLK_SLEEP_DISABLE __HAL_RCC_SRAM1_CLK_SLEEP_DISABLE #define __SRAM1_CLK_SLEEP_ENABLE __HAL_RCC_SRAM1_CLK_SLEEP_ENABLE #define __SRAM2_CLK_SLEEP_DISABLE __HAL_RCC_SRAM2_CLK_SLEEP_DISABLE #define __SRAM2_CLK_SLEEP_ENABLE __HAL_RCC_SRAM2_CLK_SLEEP_ENABLE #define __SWPMI1_CLK_DISABLE __HAL_RCC_SWPMI1_CLK_DISABLE #define __SWPMI1_CLK_ENABLE __HAL_RCC_SWPMI1_CLK_ENABLE #define __SWPMI1_CLK_SLEEP_DISABLE __HAL_RCC_SWPMI1_CLK_SLEEP_DISABLE #define __SWPMI1_CLK_SLEEP_ENABLE __HAL_RCC_SWPMI1_CLK_SLEEP_ENABLE #define __SWPMI1_FORCE_RESET __HAL_RCC_SWPMI1_FORCE_RESET #define __SWPMI1_RELEASE_RESET __HAL_RCC_SWPMI1_RELEASE_RESET #define __SYSCFG_CLK_DISABLE __HAL_RCC_SYSCFG_CLK_DISABLE #define __SYSCFG_CLK_ENABLE __HAL_RCC_SYSCFG_CLK_ENABLE #define __SYSCFG_CLK_SLEEP_DISABLE __HAL_RCC_SYSCFG_CLK_SLEEP_DISABLE #define __SYSCFG_CLK_SLEEP_ENABLE __HAL_RCC_SYSCFG_CLK_SLEEP_ENABLE #define __SYSCFG_FORCE_RESET __HAL_RCC_SYSCFG_FORCE_RESET #define __SYSCFG_RELEASE_RESET __HAL_RCC_SYSCFG_RELEASE_RESET #define __TIM1_CLK_DISABLE __HAL_RCC_TIM1_CLK_DISABLE #define __TIM1_CLK_ENABLE __HAL_RCC_TIM1_CLK_ENABLE #define __TIM1_CLK_SLEEP_DISABLE __HAL_RCC_TIM1_CLK_SLEEP_DISABLE #define __TIM1_CLK_SLEEP_ENABLE __HAL_RCC_TIM1_CLK_SLEEP_ENABLE #define __TIM1_FORCE_RESET __HAL_RCC_TIM1_FORCE_RESET #define __TIM1_RELEASE_RESET __HAL_RCC_TIM1_RELEASE_RESET #define __TIM10_CLK_DISABLE __HAL_RCC_TIM10_CLK_DISABLE #define __TIM10_CLK_ENABLE __HAL_RCC_TIM10_CLK_ENABLE #define __TIM10_FORCE_RESET __HAL_RCC_TIM10_FORCE_RESET #define __TIM10_RELEASE_RESET __HAL_RCC_TIM10_RELEASE_RESET #define __TIM11_CLK_DISABLE __HAL_RCC_TIM11_CLK_DISABLE #define __TIM11_CLK_ENABLE __HAL_RCC_TIM11_CLK_ENABLE #define __TIM11_FORCE_RESET __HAL_RCC_TIM11_FORCE_RESET #define __TIM11_RELEASE_RESET __HAL_RCC_TIM11_RELEASE_RESET #define __TIM12_CLK_DISABLE __HAL_RCC_TIM12_CLK_DISABLE #define __TIM12_CLK_ENABLE __HAL_RCC_TIM12_CLK_ENABLE #define __TIM12_FORCE_RESET __HAL_RCC_TIM12_FORCE_RESET #define __TIM12_RELEASE_RESET __HAL_RCC_TIM12_RELEASE_RESET #define __TIM13_CLK_DISABLE __HAL_RCC_TIM13_CLK_DISABLE #define __TIM13_CLK_ENABLE __HAL_RCC_TIM13_CLK_ENABLE #define __TIM13_FORCE_RESET __HAL_RCC_TIM13_FORCE_RESET #define __TIM13_RELEASE_RESET __HAL_RCC_TIM13_RELEASE_RESET #define __TIM14_CLK_DISABLE __HAL_RCC_TIM14_CLK_DISABLE #define __TIM14_CLK_ENABLE __HAL_RCC_TIM14_CLK_ENABLE #define __TIM14_FORCE_RESET __HAL_RCC_TIM14_FORCE_RESET #define __TIM14_RELEASE_RESET __HAL_RCC_TIM14_RELEASE_RESET #define __TIM15_CLK_DISABLE __HAL_RCC_TIM15_CLK_DISABLE #define __TIM15_CLK_ENABLE __HAL_RCC_TIM15_CLK_ENABLE #define __TIM15_CLK_SLEEP_DISABLE __HAL_RCC_TIM15_CLK_SLEEP_DISABLE #define __TIM15_CLK_SLEEP_ENABLE __HAL_RCC_TIM15_CLK_SLEEP_ENABLE #define __TIM15_FORCE_RESET __HAL_RCC_TIM15_FORCE_RESET #define __TIM15_RELEASE_RESET __HAL_RCC_TIM15_RELEASE_RESET #define __TIM16_CLK_DISABLE __HAL_RCC_TIM16_CLK_DISABLE #define __TIM16_CLK_ENABLE __HAL_RCC_TIM16_CLK_ENABLE #define __TIM16_CLK_SLEEP_DISABLE __HAL_RCC_TIM16_CLK_SLEEP_DISABLE #define __TIM16_CLK_SLEEP_ENABLE __HAL_RCC_TIM16_CLK_SLEEP_ENABLE #define __TIM16_FORCE_RESET __HAL_RCC_TIM16_FORCE_RESET #define __TIM16_RELEASE_RESET __HAL_RCC_TIM16_RELEASE_RESET #define __TIM17_CLK_DISABLE __HAL_RCC_TIM17_CLK_DISABLE #define __TIM17_CLK_ENABLE __HAL_RCC_TIM17_CLK_ENABLE #define __TIM17_CLK_SLEEP_DISABLE __HAL_RCC_TIM17_CLK_SLEEP_DISABLE #define __TIM17_CLK_SLEEP_ENABLE __HAL_RCC_TIM17_CLK_SLEEP_ENABLE #define __TIM17_FORCE_RESET __HAL_RCC_TIM17_FORCE_RESET #define __TIM17_RELEASE_RESET __HAL_RCC_TIM17_RELEASE_RESET #define __TIM2_CLK_DISABLE __HAL_RCC_TIM2_CLK_DISABLE #define __TIM2_CLK_ENABLE __HAL_RCC_TIM2_CLK_ENABLE #define __TIM2_CLK_SLEEP_DISABLE __HAL_RCC_TIM2_CLK_SLEEP_DISABLE #define __TIM2_CLK_SLEEP_ENABLE __HAL_RCC_TIM2_CLK_SLEEP_ENABLE #define __TIM2_FORCE_RESET __HAL_RCC_TIM2_FORCE_RESET #define __TIM2_RELEASE_RESET __HAL_RCC_TIM2_RELEASE_RESET #define __TIM3_CLK_DISABLE __HAL_RCC_TIM3_CLK_DISABLE #define __TIM3_CLK_ENABLE __HAL_RCC_TIM3_CLK_ENABLE #define __TIM3_CLK_SLEEP_DISABLE __HAL_RCC_TIM3_CLK_SLEEP_DISABLE #define __TIM3_CLK_SLEEP_ENABLE __HAL_RCC_TIM3_CLK_SLEEP_ENABLE #define __TIM3_FORCE_RESET __HAL_RCC_TIM3_FORCE_RESET #define __TIM3_RELEASE_RESET __HAL_RCC_TIM3_RELEASE_RESET #define __TIM4_CLK_DISABLE __HAL_RCC_TIM4_CLK_DISABLE #define __TIM4_CLK_ENABLE __HAL_RCC_TIM4_CLK_ENABLE #define __TIM4_CLK_SLEEP_DISABLE __HAL_RCC_TIM4_CLK_SLEEP_DISABLE #define __TIM4_CLK_SLEEP_ENABLE __HAL_RCC_TIM4_CLK_SLEEP_ENABLE #define __TIM4_FORCE_RESET __HAL_RCC_TIM4_FORCE_RESET #define __TIM4_RELEASE_RESET __HAL_RCC_TIM4_RELEASE_RESET #define __TIM5_CLK_DISABLE __HAL_RCC_TIM5_CLK_DISABLE #define __TIM5_CLK_ENABLE __HAL_RCC_TIM5_CLK_ENABLE #define __TIM5_CLK_SLEEP_DISABLE __HAL_RCC_TIM5_CLK_SLEEP_DISABLE #define __TIM5_CLK_SLEEP_ENABLE __HAL_RCC_TIM5_CLK_SLEEP_ENABLE #define __TIM5_FORCE_RESET __HAL_RCC_TIM5_FORCE_RESET #define __TIM5_RELEASE_RESET __HAL_RCC_TIM5_RELEASE_RESET #define __TIM6_CLK_DISABLE __HAL_RCC_TIM6_CLK_DISABLE #define __TIM6_CLK_ENABLE __HAL_RCC_TIM6_CLK_ENABLE #define __TIM6_CLK_SLEEP_DISABLE __HAL_RCC_TIM6_CLK_SLEEP_DISABLE #define __TIM6_CLK_SLEEP_ENABLE __HAL_RCC_TIM6_CLK_SLEEP_ENABLE #define __TIM6_FORCE_RESET __HAL_RCC_TIM6_FORCE_RESET #define __TIM6_RELEASE_RESET __HAL_RCC_TIM6_RELEASE_RESET #define __TIM7_CLK_DISABLE __HAL_RCC_TIM7_CLK_DISABLE #define __TIM7_CLK_ENABLE __HAL_RCC_TIM7_CLK_ENABLE #define __TIM7_CLK_SLEEP_DISABLE __HAL_RCC_TIM7_CLK_SLEEP_DISABLE #define __TIM7_CLK_SLEEP_ENABLE __HAL_RCC_TIM7_CLK_SLEEP_ENABLE #define __TIM7_FORCE_RESET __HAL_RCC_TIM7_FORCE_RESET #define __TIM7_RELEASE_RESET __HAL_RCC_TIM7_RELEASE_RESET #define __TIM8_CLK_DISABLE __HAL_RCC_TIM8_CLK_DISABLE #define __TIM8_CLK_ENABLE __HAL_RCC_TIM8_CLK_ENABLE #define __TIM8_CLK_SLEEP_DISABLE __HAL_RCC_TIM8_CLK_SLEEP_DISABLE #define __TIM8_CLK_SLEEP_ENABLE __HAL_RCC_TIM8_CLK_SLEEP_ENABLE #define __TIM8_FORCE_RESET __HAL_RCC_TIM8_FORCE_RESET #define __TIM8_RELEASE_RESET __HAL_RCC_TIM8_RELEASE_RESET #define __TIM9_CLK_DISABLE __HAL_RCC_TIM9_CLK_DISABLE #define __TIM9_CLK_ENABLE __HAL_RCC_TIM9_CLK_ENABLE #define __TIM9_FORCE_RESET __HAL_RCC_TIM9_FORCE_RESET #define __TIM9_RELEASE_RESET __HAL_RCC_TIM9_RELEASE_RESET #define __TSC_CLK_DISABLE __HAL_RCC_TSC_CLK_DISABLE #define __TSC_CLK_ENABLE __HAL_RCC_TSC_CLK_ENABLE #define __TSC_CLK_SLEEP_DISABLE __HAL_RCC_TSC_CLK_SLEEP_DISABLE #define __TSC_CLK_SLEEP_ENABLE __HAL_RCC_TSC_CLK_SLEEP_ENABLE #define __TSC_FORCE_RESET __HAL_RCC_TSC_FORCE_RESET #define __TSC_RELEASE_RESET __HAL_RCC_TSC_RELEASE_RESET #define __UART4_CLK_DISABLE __HAL_RCC_UART4_CLK_DISABLE #define __UART4_CLK_ENABLE __HAL_RCC_UART4_CLK_ENABLE #define __UART4_CLK_SLEEP_DISABLE __HAL_RCC_UART4_CLK_SLEEP_DISABLE #define __UART4_CLK_SLEEP_ENABLE __HAL_RCC_UART4_CLK_SLEEP_ENABLE #define __UART4_FORCE_RESET __HAL_RCC_UART4_FORCE_RESET #define __UART4_RELEASE_RESET __HAL_RCC_UART4_RELEASE_RESET #define __UART5_CLK_DISABLE __HAL_RCC_UART5_CLK_DISABLE #define __UART5_CLK_ENABLE __HAL_RCC_UART5_CLK_ENABLE #define __UART5_CLK_SLEEP_DISABLE __HAL_RCC_UART5_CLK_SLEEP_DISABLE #define __UART5_CLK_SLEEP_ENABLE __HAL_RCC_UART5_CLK_SLEEP_ENABLE #define __UART5_FORCE_RESET __HAL_RCC_UART5_FORCE_RESET #define __UART5_RELEASE_RESET __HAL_RCC_UART5_RELEASE_RESET #define __USART1_CLK_DISABLE __HAL_RCC_USART1_CLK_DISABLE #define __USART1_CLK_ENABLE __HAL_RCC_USART1_CLK_ENABLE #define __USART1_CLK_SLEEP_DISABLE __HAL_RCC_USART1_CLK_SLEEP_DISABLE #define __USART1_CLK_SLEEP_ENABLE __HAL_RCC_USART1_CLK_SLEEP_ENABLE #define __USART1_FORCE_RESET __HAL_RCC_USART1_FORCE_RESET #define __USART1_RELEASE_RESET __HAL_RCC_USART1_RELEASE_RESET #define __USART2_CLK_DISABLE __HAL_RCC_USART2_CLK_DISABLE #define __USART2_CLK_ENABLE __HAL_RCC_USART2_CLK_ENABLE #define __USART2_CLK_SLEEP_DISABLE __HAL_RCC_USART2_CLK_SLEEP_DISABLE #define __USART2_CLK_SLEEP_ENABLE __HAL_RCC_USART2_CLK_SLEEP_ENABLE #define __USART2_FORCE_RESET __HAL_RCC_USART2_FORCE_RESET #define __USART2_RELEASE_RESET __HAL_RCC_USART2_RELEASE_RESET #define __USART3_CLK_DISABLE __HAL_RCC_USART3_CLK_DISABLE #define __USART3_CLK_ENABLE __HAL_RCC_USART3_CLK_ENABLE #define __USART3_CLK_SLEEP_DISABLE __HAL_RCC_USART3_CLK_SLEEP_DISABLE #define __USART3_CLK_SLEEP_ENABLE __HAL_RCC_USART3_CLK_SLEEP_ENABLE #define __USART3_FORCE_RESET __HAL_RCC_USART3_FORCE_RESET #define __USART3_RELEASE_RESET __HAL_RCC_USART3_RELEASE_RESET #define __USART4_CLK_DISABLE __HAL_RCC_USART4_CLK_DISABLE #define __USART4_CLK_ENABLE __HAL_RCC_USART4_CLK_ENABLE #define __USART4_CLK_SLEEP_ENABLE __HAL_RCC_USART4_CLK_SLEEP_ENABLE #define __USART4_CLK_SLEEP_DISABLE __HAL_RCC_USART4_CLK_SLEEP_DISABLE #define __USART4_FORCE_RESET __HAL_RCC_USART4_FORCE_RESET #define __USART4_RELEASE_RESET __HAL_RCC_USART4_RELEASE_RESET #define __USART5_CLK_DISABLE __HAL_RCC_USART5_CLK_DISABLE #define __USART5_CLK_ENABLE __HAL_RCC_USART5_CLK_ENABLE #define __USART5_CLK_SLEEP_ENABLE __HAL_RCC_USART5_CLK_SLEEP_ENABLE #define __USART5_CLK_SLEEP_DISABLE __HAL_RCC_USART5_CLK_SLEEP_DISABLE #define __USART5_FORCE_RESET __HAL_RCC_USART5_FORCE_RESET #define __USART5_RELEASE_RESET __HAL_RCC_USART5_RELEASE_RESET #define __USART7_CLK_DISABLE __HAL_RCC_USART7_CLK_DISABLE #define __USART7_CLK_ENABLE __HAL_RCC_USART7_CLK_ENABLE #define __USART7_FORCE_RESET __HAL_RCC_USART7_FORCE_RESET #define __USART7_RELEASE_RESET __HAL_RCC_USART7_RELEASE_RESET #define __USART8_CLK_DISABLE __HAL_RCC_USART8_CLK_DISABLE #define __USART8_CLK_ENABLE __HAL_RCC_USART8_CLK_ENABLE #define __USART8_FORCE_RESET __HAL_RCC_USART8_FORCE_RESET #define __USART8_RELEASE_RESET __HAL_RCC_USART8_RELEASE_RESET #define __USB_CLK_DISABLE __HAL_RCC_USB_CLK_DISABLE #define __USB_CLK_ENABLE __HAL_RCC_USB_CLK_ENABLE #define __USB_FORCE_RESET __HAL_RCC_USB_FORCE_RESET #define __USB_CLK_SLEEP_ENABLE __HAL_RCC_USB_CLK_SLEEP_ENABLE #define __USB_CLK_SLEEP_DISABLE __HAL_RCC_USB_CLK_SLEEP_DISABLE #define __USB_OTG_FS_CLK_DISABLE __HAL_RCC_USB_OTG_FS_CLK_DISABLE #define __USB_OTG_FS_CLK_ENABLE __HAL_RCC_USB_OTG_FS_CLK_ENABLE #define __USB_RELEASE_RESET __HAL_RCC_USB_RELEASE_RESET #define __WWDG_CLK_DISABLE __HAL_RCC_WWDG_CLK_DISABLE #define __WWDG_CLK_ENABLE __HAL_RCC_WWDG_CLK_ENABLE #define __WWDG_CLK_SLEEP_DISABLE __HAL_RCC_WWDG_CLK_SLEEP_DISABLE #define __WWDG_CLK_SLEEP_ENABLE __HAL_RCC_WWDG_CLK_SLEEP_ENABLE #define __WWDG_FORCE_RESET __HAL_RCC_WWDG_FORCE_RESET #define __WWDG_RELEASE_RESET __HAL_RCC_WWDG_RELEASE_RESET #define __TIM21_CLK_ENABLE __HAL_RCC_TIM21_CLK_ENABLE #define __TIM21_CLK_DISABLE __HAL_RCC_TIM21_CLK_DISABLE #define __TIM21_FORCE_RESET __HAL_RCC_TIM21_FORCE_RESET #define __TIM21_RELEASE_RESET __HAL_RCC_TIM21_RELEASE_RESET #define __TIM21_CLK_SLEEP_ENABLE __HAL_RCC_TIM21_CLK_SLEEP_ENABLE #define __TIM21_CLK_SLEEP_DISABLE __HAL_RCC_TIM21_CLK_SLEEP_DISABLE #define __TIM22_CLK_ENABLE __HAL_RCC_TIM22_CLK_ENABLE #define __TIM22_CLK_DISABLE __HAL_RCC_TIM22_CLK_DISABLE #define __TIM22_FORCE_RESET __HAL_RCC_TIM22_FORCE_RESET #define __TIM22_RELEASE_RESET __HAL_RCC_TIM22_RELEASE_RESET #define __TIM22_CLK_SLEEP_ENABLE __HAL_RCC_TIM22_CLK_SLEEP_ENABLE #define __TIM22_CLK_SLEEP_DISABLE __HAL_RCC_TIM22_CLK_SLEEP_DISABLE #define __CRS_CLK_DISABLE __HAL_RCC_CRS_CLK_DISABLE #define __CRS_CLK_ENABLE __HAL_RCC_CRS_CLK_ENABLE #define __CRS_CLK_SLEEP_DISABLE __HAL_RCC_CRS_CLK_SLEEP_DISABLE #define __CRS_CLK_SLEEP_ENABLE __HAL_RCC_CRS_CLK_SLEEP_ENABLE #define __CRS_FORCE_RESET __HAL_RCC_CRS_FORCE_RESET #define __CRS_RELEASE_RESET __HAL_RCC_CRS_RELEASE_RESET #define __RCC_BACKUPRESET_FORCE __HAL_RCC_BACKUPRESET_FORCE #define __RCC_BACKUPRESET_RELEASE __HAL_RCC_BACKUPRESET_RELEASE #define __USB_OTG_FS_FORCE_RESET __HAL_RCC_USB_OTG_FS_FORCE_RESET #define __USB_OTG_FS_RELEASE_RESET __HAL_RCC_USB_OTG_FS_RELEASE_RESET #define __USB_OTG_FS_CLK_SLEEP_ENABLE __HAL_RCC_USB_OTG_FS_CLK_SLEEP_ENABLE #define __USB_OTG_FS_CLK_SLEEP_DISABLE __HAL_RCC_USB_OTG_FS_CLK_SLEEP_DISABLE #define __USB_OTG_HS_CLK_DISABLE __HAL_RCC_USB_OTG_HS_CLK_DISABLE #define __USB_OTG_HS_CLK_ENABLE __HAL_RCC_USB_OTG_HS_CLK_ENABLE #define __USB_OTG_HS_ULPI_CLK_ENABLE __HAL_RCC_USB_OTG_HS_ULPI_CLK_ENABLE #define __USB_OTG_HS_ULPI_CLK_DISABLE __HAL_RCC_USB_OTG_HS_ULPI_CLK_DISABLE #define __TIM9_CLK_SLEEP_ENABLE __HAL_RCC_TIM9_CLK_SLEEP_ENABLE #define __TIM9_CLK_SLEEP_DISABLE __HAL_RCC_TIM9_CLK_SLEEP_DISABLE #define __TIM10_CLK_SLEEP_ENABLE __HAL_RCC_TIM10_CLK_SLEEP_ENABLE #define __TIM10_CLK_SLEEP_DISABLE __HAL_RCC_TIM10_CLK_SLEEP_DISABLE #define __TIM11_CLK_SLEEP_ENABLE __HAL_RCC_TIM11_CLK_SLEEP_ENABLE #define __TIM11_CLK_SLEEP_DISABLE __HAL_RCC_TIM11_CLK_SLEEP_DISABLE #define __ETHMACPTP_CLK_SLEEP_ENABLE __HAL_RCC_ETHMACPTP_CLK_SLEEP_ENABLE #define __ETHMACPTP_CLK_SLEEP_DISABLE __HAL_RCC_ETHMACPTP_CLK_SLEEP_DISABLE #define __ETHMACPTP_CLK_ENABLE __HAL_RCC_ETHMACPTP_CLK_ENABLE #define __ETHMACPTP_CLK_DISABLE __HAL_RCC_ETHMACPTP_CLK_DISABLE #define __HASH_CLK_ENABLE __HAL_RCC_HASH_CLK_ENABLE #define __HASH_FORCE_RESET __HAL_RCC_HASH_FORCE_RESET #define __HASH_RELEASE_RESET __HAL_RCC_HASH_RELEASE_RESET #define __HASH_CLK_SLEEP_ENABLE __HAL_RCC_HASH_CLK_SLEEP_ENABLE #define __HASH_CLK_SLEEP_DISABLE __HAL_RCC_HASH_CLK_SLEEP_DISABLE #define __HASH_CLK_DISABLE __HAL_RCC_HASH_CLK_DISABLE #define __SPI5_CLK_ENABLE __HAL_RCC_SPI5_CLK_ENABLE #define __SPI5_CLK_DISABLE __HAL_RCC_SPI5_CLK_DISABLE #define __SPI5_FORCE_RESET __HAL_RCC_SPI5_FORCE_RESET #define __SPI5_RELEASE_RESET __HAL_RCC_SPI5_RELEASE_RESET #define __SPI5_CLK_SLEEP_ENABLE __HAL_RCC_SPI5_CLK_SLEEP_ENABLE #define __SPI5_CLK_SLEEP_DISABLE __HAL_RCC_SPI5_CLK_SLEEP_DISABLE #define __SPI6_CLK_ENABLE __HAL_RCC_SPI6_CLK_ENABLE #define __SPI6_CLK_DISABLE __HAL_RCC_SPI6_CLK_DISABLE #define __SPI6_FORCE_RESET __HAL_RCC_SPI6_FORCE_RESET #define __SPI6_RELEASE_RESET __HAL_RCC_SPI6_RELEASE_RESET #define __SPI6_CLK_SLEEP_ENABLE __HAL_RCC_SPI6_CLK_SLEEP_ENABLE #define __SPI6_CLK_SLEEP_DISABLE __HAL_RCC_SPI6_CLK_SLEEP_DISABLE #define __LTDC_CLK_ENABLE __HAL_RCC_LTDC_CLK_ENABLE #define __LTDC_CLK_DISABLE __HAL_RCC_LTDC_CLK_DISABLE #define __LTDC_FORCE_RESET __HAL_RCC_LTDC_FORCE_RESET #define __LTDC_RELEASE_RESET __HAL_RCC_LTDC_RELEASE_RESET #define __LTDC_CLK_SLEEP_ENABLE __HAL_RCC_LTDC_CLK_SLEEP_ENABLE #define __ETHMAC_CLK_SLEEP_ENABLE __HAL_RCC_ETHMAC_CLK_SLEEP_ENABLE #define __ETHMAC_CLK_SLEEP_DISABLE __HAL_RCC_ETHMAC_CLK_SLEEP_DISABLE #define __ETHMACTX_CLK_SLEEP_ENABLE __HAL_RCC_ETHMACTX_CLK_SLEEP_ENABLE #define __ETHMACTX_CLK_SLEEP_DISABLE __HAL_RCC_ETHMACTX_CLK_SLEEP_DISABLE #define __ETHMACRX_CLK_SLEEP_ENABLE __HAL_RCC_ETHMACRX_CLK_SLEEP_ENABLE #define __ETHMACRX_CLK_SLEEP_DISABLE __HAL_RCC_ETHMACRX_CLK_SLEEP_DISABLE #define __TIM12_CLK_SLEEP_ENABLE __HAL_RCC_TIM12_CLK_SLEEP_ENABLE #define __TIM12_CLK_SLEEP_DISABLE __HAL_RCC_TIM12_CLK_SLEEP_DISABLE #define __TIM13_CLK_SLEEP_ENABLE __HAL_RCC_TIM13_CLK_SLEEP_ENABLE #define __TIM13_CLK_SLEEP_DISABLE __HAL_RCC_TIM13_CLK_SLEEP_DISABLE #define __TIM14_CLK_SLEEP_ENABLE __HAL_RCC_TIM14_CLK_SLEEP_ENABLE #define __TIM14_CLK_SLEEP_DISABLE __HAL_RCC_TIM14_CLK_SLEEP_DISABLE #define __BKPSRAM_CLK_ENABLE __HAL_RCC_BKPSRAM_CLK_ENABLE #define __BKPSRAM_CLK_DISABLE __HAL_RCC_BKPSRAM_CLK_DISABLE #define __BKPSRAM_CLK_SLEEP_ENABLE __HAL_RCC_BKPSRAM_CLK_SLEEP_ENABLE #define __BKPSRAM_CLK_SLEEP_DISABLE __HAL_RCC_BKPSRAM_CLK_SLEEP_DISABLE #define __CCMDATARAMEN_CLK_ENABLE __HAL_RCC_CCMDATARAMEN_CLK_ENABLE #define __CCMDATARAMEN_CLK_DISABLE __HAL_RCC_CCMDATARAMEN_CLK_DISABLE #define __USART6_CLK_ENABLE __HAL_RCC_USART6_CLK_ENABLE #define __USART6_CLK_DISABLE __HAL_RCC_USART6_CLK_DISABLE #define __USART6_FORCE_RESET __HAL_RCC_USART6_FORCE_RESET #define __USART6_RELEASE_RESET __HAL_RCC_USART6_RELEASE_RESET #define __USART6_CLK_SLEEP_ENABLE __HAL_RCC_USART6_CLK_SLEEP_ENABLE #define __USART6_CLK_SLEEP_DISABLE __HAL_RCC_USART6_CLK_SLEEP_DISABLE #define __SPI4_CLK_ENABLE __HAL_RCC_SPI4_CLK_ENABLE #define __SPI4_CLK_DISABLE __HAL_RCC_SPI4_CLK_DISABLE #define __SPI4_FORCE_RESET __HAL_RCC_SPI4_FORCE_RESET #define __SPI4_RELEASE_RESET __HAL_RCC_SPI4_RELEASE_RESET #define __SPI4_CLK_SLEEP_ENABLE __HAL_RCC_SPI4_CLK_SLEEP_ENABLE #define __SPI4_CLK_SLEEP_DISABLE __HAL_RCC_SPI4_CLK_SLEEP_DISABLE #define __GPIOI_CLK_ENABLE __HAL_RCC_GPIOI_CLK_ENABLE #define __GPIOI_CLK_DISABLE __HAL_RCC_GPIOI_CLK_DISABLE #define __GPIOI_FORCE_RESET __HAL_RCC_GPIOI_FORCE_RESET #define __GPIOI_RELEASE_RESET __HAL_RCC_GPIOI_RELEASE_RESET #define __GPIOI_CLK_SLEEP_ENABLE __HAL_RCC_GPIOI_CLK_SLEEP_ENABLE #define __GPIOI_CLK_SLEEP_DISABLE __HAL_RCC_GPIOI_CLK_SLEEP_DISABLE #define __GPIOJ_CLK_ENABLE __HAL_RCC_GPIOJ_CLK_ENABLE #define __GPIOJ_CLK_DISABLE __HAL_RCC_GPIOJ_CLK_DISABLE #define __GPIOJ_FORCE_RESET __HAL_RCC_GPIOJ_FORCE_RESET #define __GPIOJ_RELEASE_RESET __HAL_RCC_GPIOJ_RELEASE_RESET #define __GPIOJ_CLK_SLEEP_ENABLE __HAL_RCC_GPIOJ_CLK_SLEEP_ENABLE #define __GPIOJ_CLK_SLEEP_DISABLE __HAL_RCC_GPIOJ_CLK_SLEEP_DISABLE #define __GPIOK_CLK_ENABLE __HAL_RCC_GPIOK_CLK_ENABLE #define __GPIOK_CLK_DISABLE __HAL_RCC_GPIOK_CLK_DISABLE #define __GPIOK_RELEASE_RESET __HAL_RCC_GPIOK_RELEASE_RESET #define __GPIOK_CLK_SLEEP_ENABLE __HAL_RCC_GPIOK_CLK_SLEEP_ENABLE #define __GPIOK_CLK_SLEEP_DISABLE __HAL_RCC_GPIOK_CLK_SLEEP_DISABLE #define __ETH_CLK_ENABLE __HAL_RCC_ETH_CLK_ENABLE #define __ETH_CLK_DISABLE __HAL_RCC_ETH_CLK_DISABLE #define __DCMI_CLK_ENABLE __HAL_RCC_DCMI_CLK_ENABLE #define __DCMI_CLK_DISABLE __HAL_RCC_DCMI_CLK_DISABLE #define __DCMI_FORCE_RESET __HAL_RCC_DCMI_FORCE_RESET #define __DCMI_RELEASE_RESET __HAL_RCC_DCMI_RELEASE_RESET #define __DCMI_CLK_SLEEP_ENABLE __HAL_RCC_DCMI_CLK_SLEEP_ENABLE #define __DCMI_CLK_SLEEP_DISABLE __HAL_RCC_DCMI_CLK_SLEEP_DISABLE #define __UART7_CLK_ENABLE __HAL_RCC_UART7_CLK_ENABLE #define __UART7_CLK_DISABLE __HAL_RCC_UART7_CLK_DISABLE #define __UART7_RELEASE_RESET __HAL_RCC_UART7_RELEASE_RESET #define __UART7_FORCE_RESET __HAL_RCC_UART7_FORCE_RESET #define __UART7_CLK_SLEEP_ENABLE __HAL_RCC_UART7_CLK_SLEEP_ENABLE #define __UART7_CLK_SLEEP_DISABLE __HAL_RCC_UART7_CLK_SLEEP_DISABLE #define __UART8_CLK_ENABLE __HAL_RCC_UART8_CLK_ENABLE #define __UART8_CLK_DISABLE __HAL_RCC_UART8_CLK_DISABLE #define __UART8_FORCE_RESET __HAL_RCC_UART8_FORCE_RESET #define __UART8_RELEASE_RESET __HAL_RCC_UART8_RELEASE_RESET #define __UART8_CLK_SLEEP_ENABLE __HAL_RCC_UART8_CLK_SLEEP_ENABLE #define __UART8_CLK_SLEEP_DISABLE __HAL_RCC_UART8_CLK_SLEEP_DISABLE #define __OTGHS_CLK_SLEEP_ENABLE __HAL_RCC_USB_OTG_HS_CLK_SLEEP_ENABLE #define __OTGHS_CLK_SLEEP_DISABLE __HAL_RCC_USB_OTG_HS_CLK_SLEEP_DISABLE #define __OTGHS_FORCE_RESET __HAL_RCC_USB_OTG_HS_FORCE_RESET #define __OTGHS_RELEASE_RESET __HAL_RCC_USB_OTG_HS_RELEASE_RESET #define __OTGHSULPI_CLK_SLEEP_ENABLE __HAL_RCC_USB_OTG_HS_ULPI_CLK_SLEEP_ENABLE #define __OTGHSULPI_CLK_SLEEP_DISABLE __HAL_RCC_USB_OTG_HS_ULPI_CLK_SLEEP_DISABLE #define __HAL_RCC_OTGHS_CLK_SLEEP_ENABLE __HAL_RCC_USB_OTG_HS_CLK_SLEEP_ENABLE #define __HAL_RCC_OTGHS_CLK_SLEEP_DISABLE __HAL_RCC_USB_OTG_HS_CLK_SLEEP_DISABLE #define __HAL_RCC_OTGHS_IS_CLK_SLEEP_ENABLED __HAL_RCC_USB_OTG_HS_IS_CLK_SLEEP_ENABLED #define __HAL_RCC_OTGHS_IS_CLK_SLEEP_DISABLED __HAL_RCC_USB_OTG_HS_IS_CLK_SLEEP_DISABLED #define __HAL_RCC_OTGHS_FORCE_RESET __HAL_RCC_USB_OTG_HS_FORCE_RESET #define __HAL_RCC_OTGHS_RELEASE_RESET __HAL_RCC_USB_OTG_HS_RELEASE_RESET #define __HAL_RCC_OTGHSULPI_CLK_SLEEP_ENABLE __HAL_RCC_USB_OTG_HS_ULPI_CLK_SLEEP_ENABLE #define __HAL_RCC_OTGHSULPI_CLK_SLEEP_DISABLE __HAL_RCC_USB_OTG_HS_ULPI_CLK_SLEEP_DISABLE #define __HAL_RCC_OTGHSULPI_IS_CLK_SLEEP_ENABLED __HAL_RCC_USB_OTG_HS_ULPI_IS_CLK_SLEEP_ENABLED #define __HAL_RCC_OTGHSULPI_IS_CLK_SLEEP_DISABLED __HAL_RCC_USB_OTG_HS_ULPI_IS_CLK_SLEEP_DISABLED #define __CRYP_FORCE_RESET __HAL_RCC_CRYP_FORCE_RESET #define __SRAM3_CLK_SLEEP_ENABLE __HAL_RCC_SRAM3_CLK_SLEEP_ENABLE #define __CAN2_CLK_SLEEP_ENABLE __HAL_RCC_CAN2_CLK_SLEEP_ENABLE #define __CAN2_CLK_SLEEP_DISABLE __HAL_RCC_CAN2_CLK_SLEEP_DISABLE #define __DAC_CLK_SLEEP_ENABLE __HAL_RCC_DAC_CLK_SLEEP_ENABLE #define __DAC_CLK_SLEEP_DISABLE __HAL_RCC_DAC_CLK_SLEEP_DISABLE #define __ADC2_CLK_SLEEP_ENABLE __HAL_RCC_ADC2_CLK_SLEEP_ENABLE #define __ADC2_CLK_SLEEP_DISABLE __HAL_RCC_ADC2_CLK_SLEEP_DISABLE #define __ADC3_CLK_SLEEP_ENABLE __HAL_RCC_ADC3_CLK_SLEEP_ENABLE #define __ADC3_CLK_SLEEP_DISABLE __HAL_RCC_ADC3_CLK_SLEEP_DISABLE #define __FSMC_FORCE_RESET __HAL_RCC_FSMC_FORCE_RESET #define __FSMC_RELEASE_RESET __HAL_RCC_FSMC_RELEASE_RESET #define __FSMC_CLK_SLEEP_ENABLE __HAL_RCC_FSMC_CLK_SLEEP_ENABLE #define __FSMC_CLK_SLEEP_DISABLE __HAL_RCC_FSMC_CLK_SLEEP_DISABLE #define __SDIO_FORCE_RESET __HAL_RCC_SDIO_FORCE_RESET #define __SDIO_RELEASE_RESET __HAL_RCC_SDIO_RELEASE_RESET #define __SDIO_CLK_SLEEP_DISABLE __HAL_RCC_SDIO_CLK_SLEEP_DISABLE #define __SDIO_CLK_SLEEP_ENABLE __HAL_RCC_SDIO_CLK_SLEEP_ENABLE #define __DMA2D_CLK_ENABLE __HAL_RCC_DMA2D_CLK_ENABLE #define __DMA2D_CLK_DISABLE __HAL_RCC_DMA2D_CLK_DISABLE #define __DMA2D_FORCE_RESET __HAL_RCC_DMA2D_FORCE_RESET #define __DMA2D_RELEASE_RESET __HAL_RCC_DMA2D_RELEASE_RESET #define __DMA2D_CLK_SLEEP_ENABLE __HAL_RCC_DMA2D_CLK_SLEEP_ENABLE #define __DMA2D_CLK_SLEEP_DISABLE __HAL_RCC_DMA2D_CLK_SLEEP_DISABLE /* alias define maintained for legacy */ #define __HAL_RCC_OTGFS_FORCE_RESET __HAL_RCC_USB_OTG_FS_FORCE_RESET #define __HAL_RCC_OTGFS_RELEASE_RESET __HAL_RCC_USB_OTG_FS_RELEASE_RESET #define __ADC12_CLK_ENABLE __HAL_RCC_ADC12_CLK_ENABLE #define __ADC12_CLK_DISABLE __HAL_RCC_ADC12_CLK_DISABLE #define __ADC34_CLK_ENABLE __HAL_RCC_ADC34_CLK_ENABLE #define __ADC34_CLK_DISABLE __HAL_RCC_ADC34_CLK_DISABLE #define __ADC12_CLK_ENABLE __HAL_RCC_ADC12_CLK_ENABLE #define __ADC12_CLK_DISABLE __HAL_RCC_ADC12_CLK_DISABLE #define __DAC2_CLK_ENABLE __HAL_RCC_DAC2_CLK_ENABLE #define __DAC2_CLK_DISABLE __HAL_RCC_DAC2_CLK_DISABLE #define __TIM18_CLK_ENABLE __HAL_RCC_TIM18_CLK_ENABLE #define __TIM18_CLK_DISABLE __HAL_RCC_TIM18_CLK_DISABLE #define __TIM19_CLK_ENABLE __HAL_RCC_TIM19_CLK_ENABLE #define __TIM19_CLK_DISABLE __HAL_RCC_TIM19_CLK_DISABLE #define __TIM20_CLK_ENABLE __HAL_RCC_TIM20_CLK_ENABLE #define __TIM20_CLK_DISABLE __HAL_RCC_TIM20_CLK_DISABLE #define __HRTIM1_CLK_ENABLE __HAL_RCC_HRTIM1_CLK_ENABLE #define __HRTIM1_CLK_DISABLE __HAL_RCC_HRTIM1_CLK_DISABLE #define __SDADC1_CLK_ENABLE __HAL_RCC_SDADC1_CLK_ENABLE #define __SDADC2_CLK_ENABLE __HAL_RCC_SDADC2_CLK_ENABLE #define __SDADC3_CLK_ENABLE __HAL_RCC_SDADC3_CLK_ENABLE #define __SDADC1_CLK_DISABLE __HAL_RCC_SDADC1_CLK_DISABLE #define __SDADC2_CLK_DISABLE __HAL_RCC_SDADC2_CLK_DISABLE #define __SDADC3_CLK_DISABLE __HAL_RCC_SDADC3_CLK_DISABLE #define __ADC12_FORCE_RESET __HAL_RCC_ADC12_FORCE_RESET #define __ADC12_RELEASE_RESET __HAL_RCC_ADC12_RELEASE_RESET #define __ADC34_FORCE_RESET __HAL_RCC_ADC34_FORCE_RESET #define __ADC34_RELEASE_RESET __HAL_RCC_ADC34_RELEASE_RESET #define __ADC12_FORCE_RESET __HAL_RCC_ADC12_FORCE_RESET #define __ADC12_RELEASE_RESET __HAL_RCC_ADC12_RELEASE_RESET #define __DAC2_FORCE_RESET __HAL_RCC_DAC2_FORCE_RESET #define __DAC2_RELEASE_RESET __HAL_RCC_DAC2_RELEASE_RESET #define __TIM18_FORCE_RESET __HAL_RCC_TIM18_FORCE_RESET #define __TIM18_RELEASE_RESET __HAL_RCC_TIM18_RELEASE_RESET #define __TIM19_FORCE_RESET __HAL_RCC_TIM19_FORCE_RESET #define __TIM19_RELEASE_RESET __HAL_RCC_TIM19_RELEASE_RESET #define __TIM20_FORCE_RESET __HAL_RCC_TIM20_FORCE_RESET #define __TIM20_RELEASE_RESET __HAL_RCC_TIM20_RELEASE_RESET #define __HRTIM1_FORCE_RESET __HAL_RCC_HRTIM1_FORCE_RESET #define __HRTIM1_RELEASE_RESET __HAL_RCC_HRTIM1_RELEASE_RESET #define __SDADC1_FORCE_RESET __HAL_RCC_SDADC1_FORCE_RESET #define __SDADC2_FORCE_RESET __HAL_RCC_SDADC2_FORCE_RESET #define __SDADC3_FORCE_RESET __HAL_RCC_SDADC3_FORCE_RESET #define __SDADC1_RELEASE_RESET __HAL_RCC_SDADC1_RELEASE_RESET #define __SDADC2_RELEASE_RESET __HAL_RCC_SDADC2_RELEASE_RESET #define __SDADC3_RELEASE_RESET __HAL_RCC_SDADC3_RELEASE_RESET #define __ADC1_IS_CLK_ENABLED __HAL_RCC_ADC1_IS_CLK_ENABLED #define __ADC1_IS_CLK_DISABLED __HAL_RCC_ADC1_IS_CLK_DISABLED #define __ADC12_IS_CLK_ENABLED __HAL_RCC_ADC12_IS_CLK_ENABLED #define __ADC12_IS_CLK_DISABLED __HAL_RCC_ADC12_IS_CLK_DISABLED #define __ADC34_IS_CLK_ENABLED __HAL_RCC_ADC34_IS_CLK_ENABLED #define __ADC34_IS_CLK_DISABLED __HAL_RCC_ADC34_IS_CLK_DISABLED #define __CEC_IS_CLK_ENABLED __HAL_RCC_CEC_IS_CLK_ENABLED #define __CEC_IS_CLK_DISABLED __HAL_RCC_CEC_IS_CLK_DISABLED #define __CRC_IS_CLK_ENABLED __HAL_RCC_CRC_IS_CLK_ENABLED #define __CRC_IS_CLK_DISABLED __HAL_RCC_CRC_IS_CLK_DISABLED #define __DAC1_IS_CLK_ENABLED __HAL_RCC_DAC1_IS_CLK_ENABLED #define __DAC1_IS_CLK_DISABLED __HAL_RCC_DAC1_IS_CLK_DISABLED #define __DAC2_IS_CLK_ENABLED __HAL_RCC_DAC2_IS_CLK_ENABLED #define __DAC2_IS_CLK_DISABLED __HAL_RCC_DAC2_IS_CLK_DISABLED #define __DMA1_IS_CLK_ENABLED __HAL_RCC_DMA1_IS_CLK_ENABLED #define __DMA1_IS_CLK_DISABLED __HAL_RCC_DMA1_IS_CLK_DISABLED #define __DMA2_IS_CLK_ENABLED __HAL_RCC_DMA2_IS_CLK_ENABLED #define __DMA2_IS_CLK_DISABLED __HAL_RCC_DMA2_IS_CLK_DISABLED #define __FLITF_IS_CLK_ENABLED __HAL_RCC_FLITF_IS_CLK_ENABLED #define __FLITF_IS_CLK_DISABLED __HAL_RCC_FLITF_IS_CLK_DISABLED #define __FMC_IS_CLK_ENABLED __HAL_RCC_FMC_IS_CLK_ENABLED #define __FMC_IS_CLK_DISABLED __HAL_RCC_FMC_IS_CLK_DISABLED #define __GPIOA_IS_CLK_ENABLED __HAL_RCC_GPIOA_IS_CLK_ENABLED #define __GPIOA_IS_CLK_DISABLED __HAL_RCC_GPIOA_IS_CLK_DISABLED #define __GPIOB_IS_CLK_ENABLED __HAL_RCC_GPIOB_IS_CLK_ENABLED #define __GPIOB_IS_CLK_DISABLED __HAL_RCC_GPIOB_IS_CLK_DISABLED #define __GPIOC_IS_CLK_ENABLED __HAL_RCC_GPIOC_IS_CLK_ENABLED #define __GPIOC_IS_CLK_DISABLED __HAL_RCC_GPIOC_IS_CLK_DISABLED #define __GPIOD_IS_CLK_ENABLED __HAL_RCC_GPIOD_IS_CLK_ENABLED #define __GPIOD_IS_CLK_DISABLED __HAL_RCC_GPIOD_IS_CLK_DISABLED #define __GPIOE_IS_CLK_ENABLED __HAL_RCC_GPIOE_IS_CLK_ENABLED #define __GPIOE_IS_CLK_DISABLED __HAL_RCC_GPIOE_IS_CLK_DISABLED #define __GPIOF_IS_CLK_ENABLED __HAL_RCC_GPIOF_IS_CLK_ENABLED #define __GPIOF_IS_CLK_DISABLED __HAL_RCC_GPIOF_IS_CLK_DISABLED #define __GPIOG_IS_CLK_ENABLED __HAL_RCC_GPIOG_IS_CLK_ENABLED #define __GPIOG_IS_CLK_DISABLED __HAL_RCC_GPIOG_IS_CLK_DISABLED #define __GPIOH_IS_CLK_ENABLED __HAL_RCC_GPIOH_IS_CLK_ENABLED #define __GPIOH_IS_CLK_DISABLED __HAL_RCC_GPIOH_IS_CLK_DISABLED #define __HRTIM1_IS_CLK_ENABLED __HAL_RCC_HRTIM1_IS_CLK_ENABLED #define __HRTIM1_IS_CLK_DISABLED __HAL_RCC_HRTIM1_IS_CLK_DISABLED #define __I2C1_IS_CLK_ENABLED __HAL_RCC_I2C1_IS_CLK_ENABLED #define __I2C1_IS_CLK_DISABLED __HAL_RCC_I2C1_IS_CLK_DISABLED #define __I2C2_IS_CLK_ENABLED __HAL_RCC_I2C2_IS_CLK_ENABLED #define __I2C2_IS_CLK_DISABLED __HAL_RCC_I2C2_IS_CLK_DISABLED #define __I2C3_IS_CLK_ENABLED __HAL_RCC_I2C3_IS_CLK_ENABLED #define __I2C3_IS_CLK_DISABLED __HAL_RCC_I2C3_IS_CLK_DISABLED #define __PWR_IS_CLK_ENABLED __HAL_RCC_PWR_IS_CLK_ENABLED #define __PWR_IS_CLK_DISABLED __HAL_RCC_PWR_IS_CLK_DISABLED #define __SYSCFG_IS_CLK_ENABLED __HAL_RCC_SYSCFG_IS_CLK_ENABLED #define __SYSCFG_IS_CLK_DISABLED __HAL_RCC_SYSCFG_IS_CLK_DISABLED #define __SPI1_IS_CLK_ENABLED __HAL_RCC_SPI1_IS_CLK_ENABLED #define __SPI1_IS_CLK_DISABLED __HAL_RCC_SPI1_IS_CLK_DISABLED #define __SPI2_IS_CLK_ENABLED __HAL_RCC_SPI2_IS_CLK_ENABLED #define __SPI2_IS_CLK_DISABLED __HAL_RCC_SPI2_IS_CLK_DISABLED #define __SPI3_IS_CLK_ENABLED __HAL_RCC_SPI3_IS_CLK_ENABLED #define __SPI3_IS_CLK_DISABLED __HAL_RCC_SPI3_IS_CLK_DISABLED #define __SPI4_IS_CLK_ENABLED __HAL_RCC_SPI4_IS_CLK_ENABLED #define __SPI4_IS_CLK_DISABLED __HAL_RCC_SPI4_IS_CLK_DISABLED #define __SDADC1_IS_CLK_ENABLED __HAL_RCC_SDADC1_IS_CLK_ENABLED #define __SDADC1_IS_CLK_DISABLED __HAL_RCC_SDADC1_IS_CLK_DISABLED #define __SDADC2_IS_CLK_ENABLED __HAL_RCC_SDADC2_IS_CLK_ENABLED #define __SDADC2_IS_CLK_DISABLED __HAL_RCC_SDADC2_IS_CLK_DISABLED #define __SDADC3_IS_CLK_ENABLED __HAL_RCC_SDADC3_IS_CLK_ENABLED #define __SDADC3_IS_CLK_DISABLED __HAL_RCC_SDADC3_IS_CLK_DISABLED #define __SRAM_IS_CLK_ENABLED __HAL_RCC_SRAM_IS_CLK_ENABLED #define __SRAM_IS_CLK_DISABLED __HAL_RCC_SRAM_IS_CLK_DISABLED #define __TIM1_IS_CLK_ENABLED __HAL_RCC_TIM1_IS_CLK_ENABLED #define __TIM1_IS_CLK_DISABLED __HAL_RCC_TIM1_IS_CLK_DISABLED #define __TIM2_IS_CLK_ENABLED __HAL_RCC_TIM2_IS_CLK_ENABLED #define __TIM2_IS_CLK_DISABLED __HAL_RCC_TIM2_IS_CLK_DISABLED #define __TIM3_IS_CLK_ENABLED __HAL_RCC_TIM3_IS_CLK_ENABLED #define __TIM3_IS_CLK_DISABLED __HAL_RCC_TIM3_IS_CLK_DISABLED #define __TIM4_IS_CLK_ENABLED __HAL_RCC_TIM4_IS_CLK_ENABLED #define __TIM4_IS_CLK_DISABLED __HAL_RCC_TIM4_IS_CLK_DISABLED #define __TIM5_IS_CLK_ENABLED __HAL_RCC_TIM5_IS_CLK_ENABLED #define __TIM5_IS_CLK_DISABLED __HAL_RCC_TIM5_IS_CLK_DISABLED #define __TIM6_IS_CLK_ENABLED __HAL_RCC_TIM6_IS_CLK_ENABLED #define __TIM6_IS_CLK_DISABLED __HAL_RCC_TIM6_IS_CLK_DISABLED #define __TIM7_IS_CLK_ENABLED __HAL_RCC_TIM7_IS_CLK_ENABLED #define __TIM7_IS_CLK_DISABLED __HAL_RCC_TIM7_IS_CLK_DISABLED #define __TIM8_IS_CLK_ENABLED __HAL_RCC_TIM8_IS_CLK_ENABLED #define __TIM8_IS_CLK_DISABLED __HAL_RCC_TIM8_IS_CLK_DISABLED #define __TIM12_IS_CLK_ENABLED __HAL_RCC_TIM12_IS_CLK_ENABLED #define __TIM12_IS_CLK_DISABLED __HAL_RCC_TIM12_IS_CLK_DISABLED #define __TIM13_IS_CLK_ENABLED __HAL_RCC_TIM13_IS_CLK_ENABLED #define __TIM13_IS_CLK_DISABLED __HAL_RCC_TIM13_IS_CLK_DISABLED #define __TIM14_IS_CLK_ENABLED __HAL_RCC_TIM14_IS_CLK_ENABLED #define __TIM14_IS_CLK_DISABLED __HAL_RCC_TIM14_IS_CLK_DISABLED #define __TIM15_IS_CLK_ENABLED __HAL_RCC_TIM15_IS_CLK_ENABLED #define __TIM15_IS_CLK_DISABLED __HAL_RCC_TIM15_IS_CLK_DISABLED #define __TIM16_IS_CLK_ENABLED __HAL_RCC_TIM16_IS_CLK_ENABLED #define __TIM16_IS_CLK_DISABLED __HAL_RCC_TIM16_IS_CLK_DISABLED #define __TIM17_IS_CLK_ENABLED __HAL_RCC_TIM17_IS_CLK_ENABLED #define __TIM17_IS_CLK_DISABLED __HAL_RCC_TIM17_IS_CLK_DISABLED #define __TIM18_IS_CLK_ENABLED __HAL_RCC_TIM18_IS_CLK_ENABLED #define __TIM18_IS_CLK_DISABLED __HAL_RCC_TIM18_IS_CLK_DISABLED #define __TIM19_IS_CLK_ENABLED __HAL_RCC_TIM19_IS_CLK_ENABLED #define __TIM19_IS_CLK_DISABLED __HAL_RCC_TIM19_IS_CLK_DISABLED #define __TIM20_IS_CLK_ENABLED __HAL_RCC_TIM20_IS_CLK_ENABLED #define __TIM20_IS_CLK_DISABLED __HAL_RCC_TIM20_IS_CLK_DISABLED #define __TSC_IS_CLK_ENABLED __HAL_RCC_TSC_IS_CLK_ENABLED #define __TSC_IS_CLK_DISABLED __HAL_RCC_TSC_IS_CLK_DISABLED #define __UART4_IS_CLK_ENABLED __HAL_RCC_UART4_IS_CLK_ENABLED #define __UART4_IS_CLK_DISABLED __HAL_RCC_UART4_IS_CLK_DISABLED #define __UART5_IS_CLK_ENABLED __HAL_RCC_UART5_IS_CLK_ENABLED #define __UART5_IS_CLK_DISABLED __HAL_RCC_UART5_IS_CLK_DISABLED #define __USART1_IS_CLK_ENABLED __HAL_RCC_USART1_IS_CLK_ENABLED #define __USART1_IS_CLK_DISABLED __HAL_RCC_USART1_IS_CLK_DISABLED #define __USART2_IS_CLK_ENABLED __HAL_RCC_USART2_IS_CLK_ENABLED #define __USART2_IS_CLK_DISABLED __HAL_RCC_USART2_IS_CLK_DISABLED #define __USART3_IS_CLK_ENABLED __HAL_RCC_USART3_IS_CLK_ENABLED #define __USART3_IS_CLK_DISABLED __HAL_RCC_USART3_IS_CLK_DISABLED #define __USB_IS_CLK_ENABLED __HAL_RCC_USB_IS_CLK_ENABLED #define __USB_IS_CLK_DISABLED __HAL_RCC_USB_IS_CLK_DISABLED #define __WWDG_IS_CLK_ENABLED __HAL_RCC_WWDG_IS_CLK_ENABLED #define __WWDG_IS_CLK_DISABLED __HAL_RCC_WWDG_IS_CLK_DISABLED #if defined(STM32F4) #define __HAL_RCC_SDMMC1_CLK_ENABLE __HAL_RCC_SDIO_CLK_ENABLE #define __HAL_RCC_SDMMC1_FORCE_RESET __HAL_RCC_SDIO_FORCE_RESET #define __HAL_RCC_SDMMC1_RELEASE_RESET __HAL_RCC_SDIO_RELEASE_RESET #define __HAL_RCC_SDMMC1_CLK_SLEEP_ENABLE __HAL_RCC_SDIO_CLK_SLEEP_ENABLE #define __HAL_RCC_SDMMC1_CLK_SLEEP_DISABLE __HAL_RCC_SDIO_CLK_SLEEP_DISABLE #define __HAL_RCC_SDMMC1_CLK_ENABLE __HAL_RCC_SDIO_CLK_ENABLE #define __HAL_RCC_SDMMC1_CLK_DISABLE __HAL_RCC_SDIO_CLK_DISABLE #define Sdmmc1ClockSelection SdioClockSelection #define RCC_PERIPHCLK_SDMMC1 RCC_PERIPHCLK_SDIO #define RCC_SDMMC1CLKSOURCE_CLK48 RCC_SDIOCLKSOURCE_CK48 #define RCC_SDMMC1CLKSOURCE_SYSCLK RCC_SDIOCLKSOURCE_SYSCLK #define __HAL_RCC_SDMMC1_CONFIG __HAL_RCC_SDIO_CONFIG #define __HAL_RCC_GET_SDMMC1_SOURCE __HAL_RCC_GET_SDIO_SOURCE #endif #if defined(STM32F7) || defined(STM32L4) #define __HAL_RCC_SDIO_CLK_ENABLE __HAL_RCC_SDMMC1_CLK_ENABLE #define __HAL_RCC_SDIO_FORCE_RESET __HAL_RCC_SDMMC1_FORCE_RESET #define __HAL_RCC_SDIO_RELEASE_RESET __HAL_RCC_SDMMC1_RELEASE_RESET #define __HAL_RCC_SDIO_CLK_SLEEP_ENABLE __HAL_RCC_SDMMC1_CLK_SLEEP_ENABLE #define __HAL_RCC_SDIO_CLK_SLEEP_DISABLE __HAL_RCC_SDMMC1_CLK_SLEEP_DISABLE #define __HAL_RCC_SDIO_CLK_ENABLE __HAL_RCC_SDMMC1_CLK_ENABLE #define __HAL_RCC_SDIO_CLK_DISABLE __HAL_RCC_SDMMC1_CLK_DISABLE #define SdioClockSelection Sdmmc1ClockSelection #define RCC_PERIPHCLK_SDIO RCC_PERIPHCLK_SDMMC1 #define __HAL_RCC_SDIO_CONFIG __HAL_RCC_SDMMC1_CONFIG #define __HAL_RCC_GET_SDIO_SOURCE __HAL_RCC_GET_SDMMC1_SOURCE #endif #if defined(STM32F7) #define RCC_SDIOCLKSOURCE_CK48 RCC_SDMMC1CLKSOURCE_CLK48 #define RCC_SDIOCLKSOURCE_SYSCLK RCC_SDMMC1CLKSOURCE_SYSCLK #endif #define __HAL_RCC_I2SCLK __HAL_RCC_I2S_CONFIG #define __HAL_RCC_I2SCLK_CONFIG __HAL_RCC_I2S_CONFIG #define __RCC_PLLSRC RCC_GET_PLL_OSCSOURCE #define IS_RCC_MSIRANGE IS_RCC_MSI_CLOCK_RANGE #define IS_RCC_RTCCLK_SOURCE IS_RCC_RTCCLKSOURCE #define IS_RCC_SYSCLK_DIV IS_RCC_HCLK #define IS_RCC_HCLK_DIV IS_RCC_PCLK #define RCC_IT_HSI14 RCC_IT_HSI14RDY #define IS_RCC_MCOSOURCE IS_RCC_MCO1SOURCE #define __HAL_RCC_MCO_CONFIG __HAL_RCC_MCO1_CONFIG #define RCC_MCO_NODIV RCC_MCODIV_1 #define RCC_MCO_DIV1 RCC_MCODIV_1 #define RCC_MCO_DIV2 RCC_MCODIV_2 #define RCC_MCO_DIV4 RCC_MCODIV_4 #define RCC_MCO_DIV8 RCC_MCODIV_8 #define RCC_MCO_DIV16 RCC_MCODIV_16 #define RCC_MCO_DIV32 RCC_MCODIV_32 #define RCC_MCO_DIV64 RCC_MCODIV_64 #define RCC_MCO_DIV128 RCC_MCODIV_128 #define RCC_MCOSOURCE_NONE RCC_MCO1SOURCE_NOCLOCK #define RCC_MCOSOURCE_LSI RCC_MCO1SOURCE_LSI #define RCC_MCOSOURCE_LSE RCC_MCO1SOURCE_LSE #define RCC_MCOSOURCE_SYSCLK RCC_MCO1SOURCE_SYSCLK #define RCC_MCOSOURCE_HSI RCC_MCO1SOURCE_HSI #define RCC_MCOSOURCE_HSI14 RCC_MCO1SOURCE_HSI14 #define RCC_MCOSOURCE_HSI48 RCC_MCO1SOURCE_HSI48 #define RCC_MCOSOURCE_HSE RCC_MCO1SOURCE_HSE #define RCC_MCOSOURCE_PLLCLK_DIV1 RCC_MCO1SOURCE_PLLCLK #define RCC_MCOSOURCE_PLLCLK_NODIV RCC_MCO1SOURCE_PLLCLK #define RCC_MCOSOURCE_PLLCLK_DIV2 RCC_MCO1SOURCE_PLLCLK_DIV2 #define RCC_RTCCLKSOURCE_NONE RCC_RTCCLKSOURCE_NO_CLK #define RCC_USBCLK_PLLSAI1 RCC_USBCLKSOURCE_PLLSAI1 #define RCC_USBCLK_PLL RCC_USBCLKSOURCE_PLL #define RCC_USBCLK_MSI RCC_USBCLKSOURCE_MSI #define RCC_USBCLKSOURCE_PLLCLK RCC_USBCLKSOURCE_PLL #define RCC_USBPLLCLK_DIV1 RCC_USBCLKSOURCE_PLL #define RCC_USBPLLCLK_DIV1_5 RCC_USBCLKSOURCE_PLL_DIV1_5 #define RCC_USBPLLCLK_DIV2 RCC_USBCLKSOURCE_PLL_DIV2 #define RCC_USBPLLCLK_DIV3 RCC_USBCLKSOURCE_PLL_DIV3 #define HSION_BitNumber RCC_HSION_BIT_NUMBER #define HSION_BITNUMBER RCC_HSION_BIT_NUMBER #define HSEON_BitNumber RCC_HSEON_BIT_NUMBER #define HSEON_BITNUMBER RCC_HSEON_BIT_NUMBER #define MSION_BITNUMBER RCC_MSION_BIT_NUMBER #define CSSON_BitNumber RCC_CSSON_BIT_NUMBER #define CSSON_BITNUMBER RCC_CSSON_BIT_NUMBER #define PLLON_BitNumber RCC_PLLON_BIT_NUMBER #define PLLON_BITNUMBER RCC_PLLON_BIT_NUMBER #define PLLI2SON_BitNumber RCC_PLLI2SON_BIT_NUMBER #define I2SSRC_BitNumber RCC_I2SSRC_BIT_NUMBER #define RTCEN_BitNumber RCC_RTCEN_BIT_NUMBER #define RTCEN_BITNUMBER RCC_RTCEN_BIT_NUMBER #define BDRST_BitNumber RCC_BDRST_BIT_NUMBER #define BDRST_BITNUMBER RCC_BDRST_BIT_NUMBER #define RTCRST_BITNUMBER RCC_RTCRST_BIT_NUMBER #define LSION_BitNumber RCC_LSION_BIT_NUMBER #define LSION_BITNUMBER RCC_LSION_BIT_NUMBER #define LSEON_BitNumber RCC_LSEON_BIT_NUMBER #define LSEON_BITNUMBER RCC_LSEON_BIT_NUMBER #define LSEBYP_BITNUMBER RCC_LSEBYP_BIT_NUMBER #define PLLSAION_BitNumber RCC_PLLSAION_BIT_NUMBER #define TIMPRE_BitNumber RCC_TIMPRE_BIT_NUMBER #define RMVF_BitNumber RCC_RMVF_BIT_NUMBER #define RMVF_BITNUMBER RCC_RMVF_BIT_NUMBER #define RCC_CR2_HSI14TRIM_BitNumber RCC_HSI14TRIM_BIT_NUMBER #define CR_BYTE2_ADDRESS RCC_CR_BYTE2_ADDRESS #define CIR_BYTE1_ADDRESS RCC_CIR_BYTE1_ADDRESS #define CIR_BYTE2_ADDRESS RCC_CIR_BYTE2_ADDRESS #define BDCR_BYTE0_ADDRESS RCC_BDCR_BYTE0_ADDRESS #define DBP_TIMEOUT_VALUE RCC_DBP_TIMEOUT_VALUE #define LSE_TIMEOUT_VALUE RCC_LSE_TIMEOUT_VALUE #define CR_HSION_BB RCC_CR_HSION_BB #define CR_CSSON_BB RCC_CR_CSSON_BB #define CR_PLLON_BB RCC_CR_PLLON_BB #define CR_PLLI2SON_BB RCC_CR_PLLI2SON_BB #define CR_MSION_BB RCC_CR_MSION_BB #define CSR_LSION_BB RCC_CSR_LSION_BB #define CSR_LSEON_BB RCC_CSR_LSEON_BB #define CSR_LSEBYP_BB RCC_CSR_LSEBYP_BB #define CSR_RTCEN_BB RCC_CSR_RTCEN_BB #define CSR_RTCRST_BB RCC_CSR_RTCRST_BB #define CFGR_I2SSRC_BB RCC_CFGR_I2SSRC_BB #define BDCR_RTCEN_BB RCC_BDCR_RTCEN_BB #define BDCR_BDRST_BB RCC_BDCR_BDRST_BB #define CR_HSEON_BB RCC_CR_HSEON_BB #define CSR_RMVF_BB RCC_CSR_RMVF_BB #define CR_PLLSAION_BB RCC_CR_PLLSAION_BB #define DCKCFGR_TIMPRE_BB RCC_DCKCFGR_TIMPRE_BB /** * @} */ /** @defgroup HAL_RNG_Aliased_Macros HAL RNG Aliased Macros maintained for legacy purpose * @{ */ #define HAL_RNG_ReadyCallback(__HANDLE__) HAL_RNG_ReadyDataCallback((__HANDLE__), uint32_t random32bit) /** * @} */ /** @defgroup HAL_RTC_Aliased_Macros HAL RTC Aliased Macros maintained for legacy purpose * @{ */ #define __HAL_RTC_CLEAR_FLAG __HAL_RTC_EXTI_CLEAR_FLAG #define __HAL_RTC_DISABLE_IT __HAL_RTC_EXTI_DISABLE_IT #define __HAL_RTC_ENABLE_IT __HAL_RTC_EXTI_ENABLE_IT #if defined (STM32F1) #define __HAL_RTC_EXTI_CLEAR_FLAG(RTC_EXTI_LINE_ALARM_EVENT) __HAL_RTC_ALARM_EXTI_CLEAR_FLAG() #define __HAL_RTC_EXTI_ENABLE_IT(RTC_EXTI_LINE_ALARM_EVENT) __HAL_RTC_ALARM_EXTI_ENABLE_IT() #define __HAL_RTC_EXTI_DISABLE_IT(RTC_EXTI_LINE_ALARM_EVENT) __HAL_RTC_ALARM_EXTI_DISABLE_IT() #define __HAL_RTC_EXTI_GET_FLAG(RTC_EXTI_LINE_ALARM_EVENT) __HAL_RTC_ALARM_EXTI_GET_FLAG() #define __HAL_RTC_EXTI_GENERATE_SWIT(RTC_EXTI_LINE_ALARM_EVENT) __HAL_RTC_ALARM_EXTI_GENERATE_SWIT() #else #define __HAL_RTC_EXTI_CLEAR_FLAG(__EXTI_LINE__) (((__EXTI_LINE__) == RTC_EXTI_LINE_ALARM_EVENT) ? __HAL_RTC_ALARM_EXTI_CLEAR_FLAG() : \ (((__EXTI_LINE__) == RTC_EXTI_LINE_WAKEUPTIMER_EVENT) ? __HAL_RTC_WAKEUPTIMER_EXTI_CLEAR_FLAG() : \ __HAL_RTC_TAMPER_TIMESTAMP_EXTI_CLEAR_FLAG())) #define __HAL_RTC_EXTI_ENABLE_IT(__EXTI_LINE__) (((__EXTI_LINE__) == RTC_EXTI_LINE_ALARM_EVENT) ? __HAL_RTC_ALARM_EXTI_ENABLE_IT() : \ (((__EXTI_LINE__) == RTC_EXTI_LINE_WAKEUPTIMER_EVENT) ? __HAL_RTC_WAKEUPTIMER_EXTI_ENABLE_IT() : \ __HAL_RTC_TAMPER_TIMESTAMP_EXTI_ENABLE_IT())) #define __HAL_RTC_EXTI_DISABLE_IT(__EXTI_LINE__) (((__EXTI_LINE__) == RTC_EXTI_LINE_ALARM_EVENT) ? __HAL_RTC_ALARM_EXTI_DISABLE_IT() : \ (((__EXTI_LINE__) == RTC_EXTI_LINE_WAKEUPTIMER_EVENT) ? __HAL_RTC_WAKEUPTIMER_EXTI_DISABLE_IT() : \ __HAL_RTC_TAMPER_TIMESTAMP_EXTI_DISABLE_IT())) #define __HAL_RTC_EXTI_GET_FLAG(__EXTI_LINE__) (((__EXTI_LINE__) == RTC_EXTI_LINE_ALARM_EVENT) ? __HAL_RTC_ALARM_EXTI_GET_FLAG() : \ (((__EXTI_LINE__) == RTC_EXTI_LINE_WAKEUPTIMER_EVENT) ? __HAL_RTC_WAKEUPTIMER_EXTI_GET_FLAG() : \ __HAL_RTC_TAMPER_TIMESTAMP_EXTI_GET_FLAG())) #define __HAL_RTC_EXTI_GENERATE_SWIT(__EXTI_LINE__) (((__EXTI_LINE__) == RTC_EXTI_LINE_ALARM_EVENT) ? __HAL_RTC_ALARM_EXTI_GENERATE_SWIT() : \ (((__EXTI_LINE__) == RTC_EXTI_LINE_WAKEUPTIMER_EVENT) ? __HAL_RTC_WAKEUPTIMER_EXTI_GENERATE_SWIT() : \ __HAL_RTC_TAMPER_TIMESTAMP_EXTI_GENERATE_SWIT())) #endif /* STM32F1 */ #define IS_ALARM IS_RTC_ALARM #define IS_ALARM_MASK IS_RTC_ALARM_MASK #define IS_TAMPER IS_RTC_TAMPER #define IS_TAMPER_ERASE_MODE IS_RTC_TAMPER_ERASE_MODE #define IS_TAMPER_FILTER IS_RTC_TAMPER_FILTER #define IS_TAMPER_INTERRUPT IS_RTC_TAMPER_INTERRUPT #define IS_TAMPER_MASKFLAG_STATE IS_RTC_TAMPER_MASKFLAG_STATE #define IS_TAMPER_PRECHARGE_DURATION IS_RTC_TAMPER_PRECHARGE_DURATION #define IS_TAMPER_PULLUP_STATE IS_RTC_TAMPER_PULLUP_STATE #define IS_TAMPER_SAMPLING_FREQ IS_RTC_TAMPER_SAMPLING_FREQ #define IS_TAMPER_TIMESTAMPONTAMPER_DETECTION IS_RTC_TAMPER_TIMESTAMPONTAMPER_DETECTION #define IS_TAMPER_TRIGGER IS_RTC_TAMPER_TRIGGER #define IS_WAKEUP_CLOCK IS_RTC_WAKEUP_CLOCK #define IS_WAKEUP_COUNTER IS_RTC_WAKEUP_COUNTER #define __RTC_WRITEPROTECTION_ENABLE __HAL_RTC_WRITEPROTECTION_ENABLE #define __RTC_WRITEPROTECTION_DISABLE __HAL_RTC_WRITEPROTECTION_DISABLE /** * @} */ /** @defgroup HAL_SD_Aliased_Macros HAL SD Aliased Macros maintained for legacy purpose * @{ */ #define SD_OCR_CID_CSD_OVERWRIETE SD_OCR_CID_CSD_OVERWRITE #define SD_CMD_SD_APP_STAUS SD_CMD_SD_APP_STATUS #if defined(STM32F4) #define SD_SDMMC_DISABLED SD_SDIO_DISABLED #define SD_SDMMC_FUNCTION_BUSY SD_SDIO_FUNCTION_BUSY #define SD_SDMMC_FUNCTION_FAILED SD_SDIO_FUNCTION_FAILED #define SD_SDMMC_UNKNOWN_FUNCTION SD_SDIO_UNKNOWN_FUNCTION #define SD_CMD_SDMMC_SEN_OP_COND SD_CMD_SDIO_SEN_OP_COND #define SD_CMD_SDMMC_RW_DIRECT SD_CMD_SDIO_RW_DIRECT #define SD_CMD_SDMMC_RW_EXTENDED SD_CMD_SDIO_RW_EXTENDED #define __HAL_SD_SDMMC_ENABLE __HAL_SD_SDIO_ENABLE #define __HAL_SD_SDMMC_DISABLE __HAL_SD_SDIO_DISABLE #define __HAL_SD_SDMMC_DMA_ENABLE __HAL_SD_SDIO_DMA_ENABLE #define __HAL_SD_SDMMC_DMA_DISABLE __HAL_SD_SDIO_DMA_DISABL #define __HAL_SD_SDMMC_ENABLE_IT __HAL_SD_SDIO_ENABLE_IT #define __HAL_SD_SDMMC_DISABLE_IT __HAL_SD_SDIO_DISABLE_IT #define __HAL_SD_SDMMC_GET_FLAG __HAL_SD_SDIO_GET_FLAG #define __HAL_SD_SDMMC_CLEAR_FLAG __HAL_SD_SDIO_CLEAR_FLAG #define __HAL_SD_SDMMC_GET_IT __HAL_SD_SDIO_GET_IT #define __HAL_SD_SDMMC_CLEAR_IT __HAL_SD_SDIO_CLEAR_IT #define SDMMC_STATIC_FLAGS SDIO_STATIC_FLAGS #define SDMMC_CMD0TIMEOUT SDIO_CMD0TIMEOUT #define SD_SDMMC_SEND_IF_COND SD_SDIO_SEND_IF_COND /* alias CMSIS */ #define SDMMC1_IRQn SDIO_IRQn #define SDMMC1_IRQHandler SDIO_IRQHandler #endif #if defined(STM32F7) || defined(STM32L4) #define SD_SDIO_DISABLED SD_SDMMC_DISABLED #define SD_SDIO_FUNCTION_BUSY SD_SDMMC_FUNCTION_BUSY #define SD_SDIO_FUNCTION_FAILED SD_SDMMC_FUNCTION_FAILED #define SD_SDIO_UNKNOWN_FUNCTION SD_SDMMC_UNKNOWN_FUNCTION #define SD_CMD_SDIO_SEN_OP_COND SD_CMD_SDMMC_SEN_OP_COND #define SD_CMD_SDIO_RW_DIRECT SD_CMD_SDMMC_RW_DIRECT #define SD_CMD_SDIO_RW_EXTENDED SD_CMD_SDMMC_RW_EXTENDED #define __HAL_SD_SDIO_ENABLE __HAL_SD_SDMMC_ENABLE #define __HAL_SD_SDIO_DISABLE __HAL_SD_SDMMC_DISABLE #define __HAL_SD_SDIO_DMA_ENABLE __HAL_SD_SDMMC_DMA_ENABLE #define __HAL_SD_SDIO_DMA_DISABL __HAL_SD_SDMMC_DMA_DISABLE #define __HAL_SD_SDIO_ENABLE_IT __HAL_SD_SDMMC_ENABLE_IT #define __HAL_SD_SDIO_DISABLE_IT __HAL_SD_SDMMC_DISABLE_IT #define __HAL_SD_SDIO_GET_FLAG __HAL_SD_SDMMC_GET_FLAG #define __HAL_SD_SDIO_CLEAR_FLAG __HAL_SD_SDMMC_CLEAR_FLAG #define __HAL_SD_SDIO_GET_IT __HAL_SD_SDMMC_GET_IT #define __HAL_SD_SDIO_CLEAR_IT __HAL_SD_SDMMC_CLEAR_IT #define SDIO_STATIC_FLAGS SDMMC_STATIC_FLAGS #define SDIO_CMD0TIMEOUT SDMMC_CMD0TIMEOUT #define SD_SDIO_SEND_IF_COND SD_SDMMC_SEND_IF_COND /* alias CMSIS for compatibilities */ #define SDIO_IRQn SDMMC1_IRQn #define SDIO_IRQHandler SDMMC1_IRQHandler #endif /** * @} */ /** @defgroup HAL_SMARTCARD_Aliased_Macros HAL SMARTCARD Aliased Macros maintained for legacy purpose * @{ */ #define __SMARTCARD_ENABLE_IT __HAL_SMARTCARD_ENABLE_IT #define __SMARTCARD_DISABLE_IT __HAL_SMARTCARD_DISABLE_IT #define __SMARTCARD_ENABLE __HAL_SMARTCARD_ENABLE #define __SMARTCARD_DISABLE __HAL_SMARTCARD_DISABLE #define __SMARTCARD_DMA_REQUEST_ENABLE __HAL_SMARTCARD_DMA_REQUEST_ENABLE #define __SMARTCARD_DMA_REQUEST_DISABLE __HAL_SMARTCARD_DMA_REQUEST_DISABLE #define __HAL_SMARTCARD_GETCLOCKSOURCE SMARTCARD_GETCLOCKSOURCE #define __SMARTCARD_GETCLOCKSOURCE SMARTCARD_GETCLOCKSOURCE #define IS_SMARTCARD_ONEBIT_SAMPLING IS_SMARTCARD_ONE_BIT_SAMPLE /** * @} */ /** @defgroup HAL_SMBUS_Aliased_Macros HAL SMBUS Aliased Macros maintained for legacy purpose * @{ */ #define __HAL_SMBUS_RESET_CR1 SMBUS_RESET_CR1 #define __HAL_SMBUS_RESET_CR2 SMBUS_RESET_CR2 #define __HAL_SMBUS_GENERATE_START SMBUS_GENERATE_START #define __HAL_SMBUS_GET_ADDR_MATCH SMBUS_GET_ADDR_MATCH #define __HAL_SMBUS_GET_DIR SMBUS_GET_DIR #define __HAL_SMBUS_GET_STOP_MODE SMBUS_GET_STOP_MODE #define __HAL_SMBUS_GET_PEC_MODE SMBUS_GET_PEC_MODE #define __HAL_SMBUS_GET_ALERT_ENABLED SMBUS_GET_ALERT_ENABLED /** * @} */ /** @defgroup HAL_SPI_Aliased_Macros HAL SPI Aliased Macros maintained for legacy purpose * @{ */ #define __HAL_SPI_1LINE_TX SPI_1LINE_TX #define __HAL_SPI_1LINE_RX SPI_1LINE_RX #define __HAL_SPI_RESET_CRC SPI_RESET_CRC /** * @} */ /** @defgroup HAL_UART_Aliased_Macros HAL UART Aliased Macros maintained for legacy purpose * @{ */ #define __HAL_UART_GETCLOCKSOURCE UART_GETCLOCKSOURCE #define __HAL_UART_MASK_COMPUTATION UART_MASK_COMPUTATION #define __UART_GETCLOCKSOURCE UART_GETCLOCKSOURCE #define __UART_MASK_COMPUTATION UART_MASK_COMPUTATION #define IS_UART_WAKEUPMETHODE IS_UART_WAKEUPMETHOD #define IS_UART_ONEBIT_SAMPLE IS_UART_ONE_BIT_SAMPLE #define IS_UART_ONEBIT_SAMPLING IS_UART_ONE_BIT_SAMPLE /** * @} */ /** @defgroup HAL_USART_Aliased_Macros HAL USART Aliased Macros maintained for legacy purpose * @{ */ #define __USART_ENABLE_IT __HAL_USART_ENABLE_IT #define __USART_DISABLE_IT __HAL_USART_DISABLE_IT #define __USART_ENABLE __HAL_USART_ENABLE #define __USART_DISABLE __HAL_USART_DISABLE #define __HAL_USART_GETCLOCKSOURCE USART_GETCLOCKSOURCE #define __USART_GETCLOCKSOURCE USART_GETCLOCKSOURCE /** * @} */ /** @defgroup HAL_USB_Aliased_Macros HAL USB Aliased Macros maintained for legacy purpose * @{ */ #define USB_EXTI_LINE_WAKEUP USB_WAKEUP_EXTI_LINE #define USB_FS_EXTI_TRIGGER_RISING_EDGE USB_OTG_FS_WAKEUP_EXTI_RISING_EDGE #define USB_FS_EXTI_TRIGGER_FALLING_EDGE USB_OTG_FS_WAKEUP_EXTI_FALLING_EDGE #define USB_FS_EXTI_TRIGGER_BOTH_EDGE USB_OTG_FS_WAKEUP_EXTI_RISING_FALLING_EDGE #define USB_FS_EXTI_LINE_WAKEUP USB_OTG_FS_WAKEUP_EXTI_LINE #define USB_HS_EXTI_TRIGGER_RISING_EDGE USB_OTG_HS_WAKEUP_EXTI_RISING_EDGE #define USB_HS_EXTI_TRIGGER_FALLING_EDGE USB_OTG_HS_WAKEUP_EXTI_FALLING_EDGE #define USB_HS_EXTI_TRIGGER_BOTH_EDGE USB_OTG_HS_WAKEUP_EXTI_RISING_FALLING_EDGE #define USB_HS_EXTI_LINE_WAKEUP USB_OTG_HS_WAKEUP_EXTI_LINE #define __HAL_USB_EXTI_ENABLE_IT __HAL_USB_WAKEUP_EXTI_ENABLE_IT #define __HAL_USB_EXTI_DISABLE_IT __HAL_USB_WAKEUP_EXTI_DISABLE_IT #define __HAL_USB_EXTI_GET_FLAG __HAL_USB_WAKEUP_EXTI_GET_FLAG #define __HAL_USB_EXTI_CLEAR_FLAG __HAL_USB_WAKEUP_EXTI_CLEAR_FLAG #define __HAL_USB_EXTI_SET_RISING_EDGE_TRIGGER __HAL_USB_WAKEUP_EXTI_ENABLE_RISING_EDGE #define __HAL_USB_EXTI_SET_FALLING_EDGE_TRIGGER __HAL_USB_WAKEUP_EXTI_ENABLE_FALLING_EDGE #define __HAL_USB_EXTI_SET_FALLINGRISING_TRIGGER __HAL_USB_WAKEUP_EXTI_ENABLE_RISING_FALLING_EDGE #define __HAL_USB_FS_EXTI_ENABLE_IT __HAL_USB_OTG_FS_WAKEUP_EXTI_ENABLE_IT #define __HAL_USB_FS_EXTI_DISABLE_IT __HAL_USB_OTG_FS_WAKEUP_EXTI_DISABLE_IT #define __HAL_USB_FS_EXTI_GET_FLAG __HAL_USB_OTG_FS_WAKEUP_EXTI_GET_FLAG #define __HAL_USB_FS_EXTI_CLEAR_FLAG __HAL_USB_OTG_FS_WAKEUP_EXTI_CLEAR_FLAG #define __HAL_USB_FS_EXTI_SET_RISING_EGDE_TRIGGER __HAL_USB_OTG_FS_WAKEUP_EXTI_ENABLE_RISING_EDGE #define __HAL_USB_FS_EXTI_SET_FALLING_EGDE_TRIGGER __HAL_USB_OTG_FS_WAKEUP_EXTI_ENABLE_FALLING_EDGE #define __HAL_USB_FS_EXTI_SET_FALLINGRISING_TRIGGER __HAL_USB_OTG_FS_WAKEUP_EXTI_ENABLE_RISING_FALLING_EDGE #define __HAL_USB_FS_EXTI_GENERATE_SWIT __HAL_USB_OTG_FS_WAKEUP_EXTI_GENERATE_SWIT #define __HAL_USB_HS_EXTI_ENABLE_IT __HAL_USB_OTG_HS_WAKEUP_EXTI_ENABLE_IT #define __HAL_USB_HS_EXTI_DISABLE_IT __HAL_USB_OTG_HS_WAKEUP_EXTI_DISABLE_IT #define __HAL_USB_HS_EXTI_GET_FLAG __HAL_USB_OTG_HS_WAKEUP_EXTI_GET_FLAG #define __HAL_USB_HS_EXTI_CLEAR_FLAG __HAL_USB_OTG_HS_WAKEUP_EXTI_CLEAR_FLAG #define __HAL_USB_HS_EXTI_SET_RISING_EGDE_TRIGGER __HAL_USB_OTG_HS_WAKEUP_EXTI_ENABLE_RISING_EDGE #define __HAL_USB_HS_EXTI_SET_FALLING_EGDE_TRIGGER __HAL_USB_OTG_HS_WAKEUP_EXTI_ENABLE_FALLING_EDGE #define __HAL_USB_HS_EXTI_SET_FALLINGRISING_TRIGGER __HAL_USB_OTG_HS_WAKEUP_EXTI_ENABLE_RISING_FALLING_EDGE #define __HAL_USB_HS_EXTI_GENERATE_SWIT __HAL_USB_OTG_HS_WAKEUP_EXTI_GENERATE_SWIT #define HAL_PCD_ActiveRemoteWakeup HAL_PCD_ActivateRemoteWakeup #define HAL_PCD_DeActiveRemoteWakeup HAL_PCD_DeActivateRemoteWakeup #define HAL_PCD_SetTxFiFo HAL_PCDEx_SetTxFiFo #define HAL_PCD_SetRxFiFo HAL_PCDEx_SetRxFiFo /** * @} */ /** @defgroup HAL_TIM_Aliased_Macros HAL TIM Aliased Macros maintained for legacy purpose * @{ */ #define __HAL_TIM_SetICPrescalerValue TIM_SET_ICPRESCALERVALUE #define __HAL_TIM_ResetICPrescalerValue TIM_RESET_ICPRESCALERVALUE #define TIM_GET_ITSTATUS __HAL_TIM_GET_IT_SOURCE #define TIM_GET_CLEAR_IT __HAL_TIM_CLEAR_IT #define __HAL_TIM_GET_ITSTATUS __HAL_TIM_GET_IT_SOURCE #define __HAL_TIM_DIRECTION_STATUS __HAL_TIM_IS_TIM_COUNTING_DOWN #define __HAL_TIM_PRESCALER __HAL_TIM_SET_PRESCALER #define __HAL_TIM_SetCounter __HAL_TIM_SET_COUNTER #define __HAL_TIM_GetCounter __HAL_TIM_GET_COUNTER #define __HAL_TIM_SetAutoreload __HAL_TIM_SET_AUTORELOAD #define __HAL_TIM_GetAutoreload __HAL_TIM_GET_AUTORELOAD #define __HAL_TIM_SetClockDivision __HAL_TIM_SET_CLOCKDIVISION #define __HAL_TIM_GetClockDivision __HAL_TIM_GET_CLOCKDIVISION #define __HAL_TIM_SetICPrescaler __HAL_TIM_SET_ICPRESCALER #define __HAL_TIM_GetICPrescaler __HAL_TIM_GET_ICPRESCALER #define __HAL_TIM_SetCompare __HAL_TIM_SET_COMPARE #define __HAL_TIM_GetCompare __HAL_TIM_GET_COMPARE #define TIM_TS_ITR0 ((uint32_t)0x0000) #define TIM_TS_ITR1 ((uint32_t)0x0010) #define TIM_TS_ITR2 ((uint32_t)0x0020) #define TIM_TS_ITR3 ((uint32_t)0x0030) #define IS_TIM_INTERNAL_TRIGGER_SELECTION(SELECTION) (((SELECTION) == TIM_TS_ITR0) || \ ((SELECTION) == TIM_TS_ITR1) || \ ((SELECTION) == TIM_TS_ITR2) || \ ((SELECTION) == TIM_TS_ITR3)) #define TIM_CHANNEL_1 ((uint32_t)0x0000) #define TIM_CHANNEL_2 ((uint32_t)0x0004) #define IS_TIM_PWMI_CHANNELS(CHANNEL) (((CHANNEL) == TIM_CHANNEL_1) || \ ((CHANNEL) == TIM_CHANNEL_2)) #define TIM_OUTPUTNSTATE_DISABLE ((uint32_t)0x0000) #define TIM_OUTPUTNSTATE_ENABLE (TIM_CCER_CC1NE) #define IS_TIM_OUTPUTN_STATE(STATE) (((STATE) == TIM_OUTPUTNSTATE_DISABLE) || \ ((STATE) == TIM_OUTPUTNSTATE_ENABLE)) #define TIM_OUTPUTSTATE_DISABLE ((uint32_t)0x0000) #define TIM_OUTPUTSTATE_ENABLE (TIM_CCER_CC1E) #define IS_TIM_OUTPUT_STATE(STATE) (((STATE) == TIM_OUTPUTSTATE_DISABLE) || \ ((STATE) == TIM_OUTPUTSTATE_ENABLE)) /** * @} */ /** @defgroup HAL_ETH_Aliased_Macros HAL ETH Aliased Macros maintained for legacy purpose * @{ */ #define __HAL_ETH_EXTI_ENABLE_IT __HAL_ETH_WAKEUP_EXTI_ENABLE_IT #define __HAL_ETH_EXTI_DISABLE_IT __HAL_ETH_WAKEUP_EXTI_DISABLE_IT #define __HAL_ETH_EXTI_GET_FLAG __HAL_ETH_WAKEUP_EXTI_GET_FLAG #define __HAL_ETH_EXTI_CLEAR_FLAG __HAL_ETH_WAKEUP_EXTI_CLEAR_FLAG #define __HAL_ETH_EXTI_SET_RISING_EGDE_TRIGGER __HAL_ETH_WAKEUP_EXTI_ENABLE_RISING_EDGE_TRIGGER #define __HAL_ETH_EXTI_SET_FALLING_EGDE_TRIGGER __HAL_ETH_WAKEUP_EXTI_ENABLE_FALLING_EDGE_TRIGGER #define __HAL_ETH_EXTI_SET_FALLINGRISING_TRIGGER __HAL_ETH_WAKEUP_EXTI_ENABLE_FALLINGRISING_TRIGGER #define ETH_PROMISCIOUSMODE_ENABLE ETH_PROMISCUOUS_MODE_ENABLE #define ETH_PROMISCIOUSMODE_DISABLE ETH_PROMISCUOUS_MODE_DISABLE #define IS_ETH_PROMISCIOUS_MODE IS_ETH_PROMISCUOUS_MODE /** * @} */ /** @defgroup HAL_LTDC_Aliased_Macros HAL LTDC Aliased Macros maintained for legacy purpose * @{ */ #define __HAL_LTDC_LAYER LTDC_LAYER /** * @} */ /** @defgroup HAL_SAI_Aliased_Macros HAL SAI Aliased Macros maintained for legacy purpose * @{ */ #define SAI_OUTPUTDRIVE_DISABLED SAI_OUTPUTDRIVE_DISABLE #define SAI_OUTPUTDRIVE_ENABLED SAI_OUTPUTDRIVE_ENABLE #define SAI_MASTERDIVIDER_ENABLED SAI_MASTERDIVIDER_ENABLE #define SAI_MASTERDIVIDER_DISABLED SAI_MASTERDIVIDER_DISABLE #define SAI_STREOMODE SAI_STEREOMODE #define SAI_FIFOStatus_Empty SAI_FIFOSTATUS_EMPTY #define SAI_FIFOStatus_Less1QuarterFull SAI_FIFOSTATUS_LESS1QUARTERFULL #define SAI_FIFOStatus_1QuarterFull SAI_FIFOSTATUS_1QUARTERFULL #define SAI_FIFOStatus_HalfFull SAI_FIFOSTATUS_HALFFULL #define SAI_FIFOStatus_3QuartersFull SAI_FIFOSTATUS_3QUARTERFULL #define SAI_FIFOStatus_Full SAI_FIFOSTATUS_FULL #define IS_SAI_BLOCK_MONO_STREO_MODE IS_SAI_BLOCK_MONO_STEREO_MODE /** * @} */ /** @defgroup HAL_PPP_Aliased_Macros HAL PPP Aliased Macros maintained for legacy purpose * @{ */ /** * @} */ #ifdef __cplusplus } #endif #endif /* ___STM32_HAL_LEGACY */ /************************ (C) COPYRIGHT STMicroelectronics *****END OF FILE****/ ================================================ FILE: Zelig/mbed/TARGET_NUCLEO_F401RE/stm32f401xe.h ================================================ /** ****************************************************************************** * @file stm32f401xe.h * @author MCD Application Team * @version V2.3.2 * @date 26-June-2015 * @brief CMSIS STM32F401xExx Device Peripheral Access Layer Header File. * * This file contains: * - Data structures and the address mapping for all peripherals * - Peripheral's registers declarations and bits definition * - Macros to access peripherals registers hardware * ****************************************************************************** * @attention * *

© COPYRIGHT(c) 2015 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. * ****************************************************************************** */ /** @addtogroup CMSIS * @{ */ /** @addtogroup stm32f401xe * @{ */ #ifndef __STM32F401xE_H #define __STM32F401xE_H #ifdef __cplusplus extern "C" { #endif /* __cplusplus */ /** @addtogroup Configuration_section_for_CMSIS * @{ */ /** * @brief Configuration of the Cortex-M4 Processor and Core Peripherals */ #define __CM4_REV 0x0001 /*!< Core revision r0p1 */ #define __MPU_PRESENT 1 /*!< STM32F4XX provides an MPU */ #define __NVIC_PRIO_BITS 4 /*!< STM32F4XX uses 4 Bits for the Priority Levels */ #define __Vendor_SysTickConfig 0 /*!< Set to 1 if different SysTick Config is used */ #define __FPU_PRESENT 1 /*!< FPU present */ /** * @} */ /** @addtogroup Peripheral_interrupt_number_definition * @{ */ /** * @brief STM32F4XX Interrupt Number Definition, according to the selected device * in @ref Library_configuration_section */ typedef enum { /****** Cortex-M4 Processor Exceptions Numbers ****************************************************************/ NonMaskableInt_IRQn = -14, /*!< 2 Non Maskable Interrupt */ MemoryManagement_IRQn = -12, /*!< 4 Cortex-M4 Memory Management Interrupt */ BusFault_IRQn = -11, /*!< 5 Cortex-M4 Bus Fault Interrupt */ UsageFault_IRQn = -10, /*!< 6 Cortex-M4 Usage Fault Interrupt */ SVCall_IRQn = -5, /*!< 11 Cortex-M4 SV Call Interrupt */ DebugMonitor_IRQn = -4, /*!< 12 Cortex-M4 Debug Monitor Interrupt */ PendSV_IRQn = -2, /*!< 14 Cortex-M4 Pend SV Interrupt */ SysTick_IRQn = -1, /*!< 15 Cortex-M4 System Tick Interrupt */ /****** STM32 specific Interrupt Numbers **********************************************************************/ WWDG_IRQn = 0, /*!< Window WatchDog Interrupt */ PVD_IRQn = 1, /*!< PVD through EXTI Line detection Interrupt */ TAMP_STAMP_IRQn = 2, /*!< Tamper and TimeStamp interrupts through the EXTI line */ RTC_WKUP_IRQn = 3, /*!< RTC Wakeup interrupt through the EXTI line */ FLASH_IRQn = 4, /*!< FLASH global Interrupt */ RCC_IRQn = 5, /*!< RCC global Interrupt */ EXTI0_IRQn = 6, /*!< EXTI Line0 Interrupt */ EXTI1_IRQn = 7, /*!< EXTI Line1 Interrupt */ EXTI2_IRQn = 8, /*!< EXTI Line2 Interrupt */ EXTI3_IRQn = 9, /*!< EXTI Line3 Interrupt */ EXTI4_IRQn = 10, /*!< EXTI Line4 Interrupt */ DMA1_Stream0_IRQn = 11, /*!< DMA1 Stream 0 global Interrupt */ DMA1_Stream1_IRQn = 12, /*!< DMA1 Stream 1 global Interrupt */ DMA1_Stream2_IRQn = 13, /*!< DMA1 Stream 2 global Interrupt */ DMA1_Stream3_IRQn = 14, /*!< DMA1 Stream 3 global Interrupt */ DMA1_Stream4_IRQn = 15, /*!< DMA1 Stream 4 global Interrupt */ DMA1_Stream5_IRQn = 16, /*!< DMA1 Stream 5 global Interrupt */ DMA1_Stream6_IRQn = 17, /*!< DMA1 Stream 6 global Interrupt */ ADC_IRQn = 18, /*!< ADC1, ADC2 and ADC3 global Interrupts */ EXTI9_5_IRQn = 23, /*!< External Line[9:5] Interrupts */ TIM1_BRK_TIM9_IRQn = 24, /*!< TIM1 Break interrupt and TIM9 global interrupt */ TIM1_UP_TIM10_IRQn = 25, /*!< TIM1 Update Interrupt and TIM10 global interrupt */ TIM1_TRG_COM_TIM11_IRQn = 26, /*!< TIM1 Trigger and Commutation Interrupt and TIM11 global interrupt */ TIM1_CC_IRQn = 27, /*!< TIM1 Capture Compare Interrupt */ TIM2_IRQn = 28, /*!< TIM2 global Interrupt */ TIM3_IRQn = 29, /*!< TIM3 global Interrupt */ TIM4_IRQn = 30, /*!< TIM4 global Interrupt */ I2C1_EV_IRQn = 31, /*!< I2C1 Event Interrupt */ I2C1_ER_IRQn = 32, /*!< I2C1 Error Interrupt */ I2C2_EV_IRQn = 33, /*!< I2C2 Event Interrupt */ I2C2_ER_IRQn = 34, /*!< I2C2 Error Interrupt */ SPI1_IRQn = 35, /*!< SPI1 global Interrupt */ SPI2_IRQn = 36, /*!< SPI2 global Interrupt */ USART1_IRQn = 37, /*!< USART1 global Interrupt */ USART2_IRQn = 38, /*!< USART2 global Interrupt */ EXTI15_10_IRQn = 40, /*!< External Line[15:10] Interrupts */ RTC_Alarm_IRQn = 41, /*!< RTC Alarm (A and B) through EXTI Line Interrupt */ OTG_FS_WKUP_IRQn = 42, /*!< USB OTG FS Wakeup through EXTI line interrupt */ DMA1_Stream7_IRQn = 47, /*!< DMA1 Stream7 Interrupt */ SDIO_IRQn = 49, /*!< SDIO global Interrupt */ TIM5_IRQn = 50, /*!< TIM5 global Interrupt */ SPI3_IRQn = 51, /*!< SPI3 global Interrupt */ DMA2_Stream0_IRQn = 56, /*!< DMA2 Stream 0 global Interrupt */ DMA2_Stream1_IRQn = 57, /*!< DMA2 Stream 1 global Interrupt */ DMA2_Stream2_IRQn = 58, /*!< DMA2 Stream 2 global Interrupt */ DMA2_Stream3_IRQn = 59, /*!< DMA2 Stream 3 global Interrupt */ DMA2_Stream4_IRQn = 60, /*!< DMA2 Stream 4 global Interrupt */ OTG_FS_IRQn = 67, /*!< USB OTG FS global Interrupt */ DMA2_Stream5_IRQn = 68, /*!< DMA2 Stream 5 global interrupt */ DMA2_Stream6_IRQn = 69, /*!< DMA2 Stream 6 global interrupt */ DMA2_Stream7_IRQn = 70, /*!< DMA2 Stream 7 global interrupt */ USART6_IRQn = 71, /*!< USART6 global interrupt */ I2C3_EV_IRQn = 72, /*!< I2C3 event interrupt */ I2C3_ER_IRQn = 73, /*!< I2C3 error interrupt */ FPU_IRQn = 81, /*!< FPU global interrupt */ SPI4_IRQn = 84 /*!< SPI4 global Interrupt */ } IRQn_Type; /** * @} */ #include "core_cm4.h" /* Cortex-M4 processor and core peripherals */ #include "system_stm32f4xx.h" #include /** @addtogroup Peripheral_registers_structures * @{ */ /** * @brief Analog to Digital Converter */ typedef struct { __IO uint32_t SR; /*!< ADC status register, Address offset: 0x00 */ __IO uint32_t CR1; /*!< ADC control register 1, Address offset: 0x04 */ __IO uint32_t CR2; /*!< ADC control register 2, Address offset: 0x08 */ __IO uint32_t SMPR1; /*!< ADC sample time register 1, Address offset: 0x0C */ __IO uint32_t SMPR2; /*!< ADC sample time register 2, Address offset: 0x10 */ __IO uint32_t JOFR1; /*!< ADC injected channel data offset register 1, Address offset: 0x14 */ __IO uint32_t JOFR2; /*!< ADC injected channel data offset register 2, Address offset: 0x18 */ __IO uint32_t JOFR3; /*!< ADC injected channel data offset register 3, Address offset: 0x1C */ __IO uint32_t JOFR4; /*!< ADC injected channel data offset register 4, Address offset: 0x20 */ __IO uint32_t HTR; /*!< ADC watchdog higher threshold register, Address offset: 0x24 */ __IO uint32_t LTR; /*!< ADC watchdog lower threshold register, Address offset: 0x28 */ __IO uint32_t SQR1; /*!< ADC regular sequence register 1, Address offset: 0x2C */ __IO uint32_t SQR2; /*!< ADC regular sequence register 2, Address offset: 0x30 */ __IO uint32_t SQR3; /*!< ADC regular sequence register 3, Address offset: 0x34 */ __IO uint32_t JSQR; /*!< ADC injected sequence register, Address offset: 0x38*/ __IO uint32_t JDR1; /*!< ADC injected data register 1, Address offset: 0x3C */ __IO uint32_t JDR2; /*!< ADC injected data register 2, Address offset: 0x40 */ __IO uint32_t JDR3; /*!< ADC injected data register 3, Address offset: 0x44 */ __IO uint32_t JDR4; /*!< ADC injected data register 4, Address offset: 0x48 */ __IO uint32_t DR; /*!< ADC regular data register, Address offset: 0x4C */ } ADC_TypeDef; typedef struct { __IO uint32_t CSR; /*!< ADC Common status register, Address offset: ADC1 base address + 0x300 */ __IO uint32_t CCR; /*!< ADC common control register, Address offset: ADC1 base address + 0x304 */ __IO uint32_t CDR; /*!< ADC common regular data register for dual AND triple modes, Address offset: ADC1 base address + 0x308 */ } ADC_Common_TypeDef; /** * @brief CRC calculation unit */ typedef struct { __IO uint32_t DR; /*!< CRC Data register, Address offset: 0x00 */ __IO uint8_t IDR; /*!< CRC Independent data register, Address offset: 0x04 */ uint8_t RESERVED0; /*!< Reserved, 0x05 */ uint16_t RESERVED1; /*!< Reserved, 0x06 */ __IO uint32_t CR; /*!< CRC Control register, Address offset: 0x08 */ } CRC_TypeDef; /** * @brief Debug MCU */ typedef struct { __IO uint32_t IDCODE; /*!< MCU device ID code, Address offset: 0x00 */ __IO uint32_t CR; /*!< Debug MCU configuration register, Address offset: 0x04 */ __IO uint32_t APB1FZ; /*!< Debug MCU APB1 freeze register, Address offset: 0x08 */ __IO uint32_t APB2FZ; /*!< Debug MCU APB2 freeze register, Address offset: 0x0C */ }DBGMCU_TypeDef; /** * @brief DMA Controller */ typedef struct { __IO uint32_t CR; /*!< DMA stream x configuration register */ __IO uint32_t NDTR; /*!< DMA stream x number of data register */ __IO uint32_t PAR; /*!< DMA stream x peripheral address register */ __IO uint32_t M0AR; /*!< DMA stream x memory 0 address register */ __IO uint32_t M1AR; /*!< DMA stream x memory 1 address register */ __IO uint32_t FCR; /*!< DMA stream x FIFO control register */ } DMA_Stream_TypeDef; typedef struct { __IO uint32_t LISR; /*!< DMA low interrupt status register, Address offset: 0x00 */ __IO uint32_t HISR; /*!< DMA high interrupt status register, Address offset: 0x04 */ __IO uint32_t LIFCR; /*!< DMA low interrupt flag clear register, Address offset: 0x08 */ __IO uint32_t HIFCR; /*!< DMA high interrupt flag clear register, Address offset: 0x0C */ } DMA_TypeDef; /** * @brief External Interrupt/Event Controller */ typedef struct { __IO uint32_t IMR; /*!< EXTI Interrupt mask register, Address offset: 0x00 */ __IO uint32_t EMR; /*!< EXTI Event mask register, Address offset: 0x04 */ __IO uint32_t RTSR; /*!< EXTI Rising trigger selection register, Address offset: 0x08 */ __IO uint32_t FTSR; /*!< EXTI Falling trigger selection register, Address offset: 0x0C */ __IO uint32_t SWIER; /*!< EXTI Software interrupt event register, Address offset: 0x10 */ __IO uint32_t PR; /*!< EXTI Pending register, Address offset: 0x14 */ } EXTI_TypeDef; /** * @brief FLASH Registers */ typedef struct { __IO uint32_t ACR; /*!< FLASH access control register, Address offset: 0x00 */ __IO uint32_t KEYR; /*!< FLASH key register, Address offset: 0x04 */ __IO uint32_t OPTKEYR; /*!< FLASH option key register, Address offset: 0x08 */ __IO uint32_t SR; /*!< FLASH status register, Address offset: 0x0C */ __IO uint32_t CR; /*!< FLASH control register, Address offset: 0x10 */ __IO uint32_t OPTCR; /*!< FLASH option control register , Address offset: 0x14 */ __IO uint32_t OPTCR1; /*!< FLASH option control register 1, Address offset: 0x18 */ } FLASH_TypeDef; /** * @brief General Purpose I/O */ typedef struct { __IO uint32_t MODER; /*!< GPIO port mode register, Address offset: 0x00 */ __IO uint32_t OTYPER; /*!< GPIO port output type register, Address offset: 0x04 */ __IO uint32_t OSPEEDR; /*!< GPIO port output speed register, Address offset: 0x08 */ __IO uint32_t PUPDR; /*!< GPIO port pull-up/pull-down register, Address offset: 0x0C */ __IO uint32_t IDR; /*!< GPIO port input data register, Address offset: 0x10 */ __IO uint32_t ODR; /*!< GPIO port output data register, Address offset: 0x14 */ __IO uint32_t BSRR; /*!< GPIO port bit set/reset register, Address offset: 0x18 */ __IO uint32_t LCKR; /*!< GPIO port configuration lock register, Address offset: 0x1C */ __IO uint32_t AFR[2]; /*!< GPIO alternate function registers, Address offset: 0x20-0x24 */ } GPIO_TypeDef; /** * @brief System configuration controller */ typedef struct { __IO uint32_t MEMRMP; /*!< SYSCFG memory remap register, Address offset: 0x00 */ __IO uint32_t PMC; /*!< SYSCFG peripheral mode configuration register, Address offset: 0x04 */ __IO uint32_t EXTICR[4]; /*!< SYSCFG external interrupt configuration registers, Address offset: 0x08-0x14 */ uint32_t RESERVED[2]; /*!< Reserved, 0x18-0x1C */ __IO uint32_t CMPCR; /*!< SYSCFG Compensation cell control register, Address offset: 0x20 */ } SYSCFG_TypeDef; /** * @brief Inter-integrated Circuit Interface */ typedef struct { __IO uint32_t CR1; /*!< I2C Control register 1, Address offset: 0x00 */ __IO uint32_t CR2; /*!< I2C Control register 2, Address offset: 0x04 */ __IO uint32_t OAR1; /*!< I2C Own address register 1, Address offset: 0x08 */ __IO uint32_t OAR2; /*!< I2C Own address register 2, Address offset: 0x0C */ __IO uint32_t DR; /*!< I2C Data register, Address offset: 0x10 */ __IO uint32_t SR1; /*!< I2C Status register 1, Address offset: 0x14 */ __IO uint32_t SR2; /*!< I2C Status register 2, Address offset: 0x18 */ __IO uint32_t CCR; /*!< I2C Clock control register, Address offset: 0x1C */ __IO uint32_t TRISE; /*!< I2C TRISE register, Address offset: 0x20 */ __IO uint32_t FLTR; /*!< I2C FLTR register, Address offset: 0x24 */ } I2C_TypeDef; /** * @brief Independent WATCHDOG */ typedef struct { __IO uint32_t KR; /*!< IWDG Key register, Address offset: 0x00 */ __IO uint32_t PR; /*!< IWDG Prescaler register, Address offset: 0x04 */ __IO uint32_t RLR; /*!< IWDG Reload register, Address offset: 0x08 */ __IO uint32_t SR; /*!< IWDG Status register, Address offset: 0x0C */ } IWDG_TypeDef; /** * @brief Power Control */ typedef struct { __IO uint32_t CR; /*!< PWR power control register, Address offset: 0x00 */ __IO uint32_t CSR; /*!< PWR power control/status register, Address offset: 0x04 */ } PWR_TypeDef; /** * @brief Reset and Clock Control */ typedef struct { __IO uint32_t CR; /*!< RCC clock control register, Address offset: 0x00 */ __IO uint32_t PLLCFGR; /*!< RCC PLL configuration register, Address offset: 0x04 */ __IO uint32_t CFGR; /*!< RCC clock configuration register, Address offset: 0x08 */ __IO uint32_t CIR; /*!< RCC clock interrupt register, Address offset: 0x0C */ __IO uint32_t AHB1RSTR; /*!< RCC AHB1 peripheral reset register, Address offset: 0x10 */ __IO uint32_t AHB2RSTR; /*!< RCC AHB2 peripheral reset register, Address offset: 0x14 */ __IO uint32_t AHB3RSTR; /*!< RCC AHB3 peripheral reset register, Address offset: 0x18 */ uint32_t RESERVED0; /*!< Reserved, 0x1C */ __IO uint32_t APB1RSTR; /*!< RCC APB1 peripheral reset register, Address offset: 0x20 */ __IO uint32_t APB2RSTR; /*!< RCC APB2 peripheral reset register, Address offset: 0x24 */ uint32_t RESERVED1[2]; /*!< Reserved, 0x28-0x2C */ __IO uint32_t AHB1ENR; /*!< RCC AHB1 peripheral clock register, Address offset: 0x30 */ __IO uint32_t AHB2ENR; /*!< RCC AHB2 peripheral clock register, Address offset: 0x34 */ __IO uint32_t AHB3ENR; /*!< RCC AHB3 peripheral clock register, Address offset: 0x38 */ uint32_t RESERVED2; /*!< Reserved, 0x3C */ __IO uint32_t APB1ENR; /*!< RCC APB1 peripheral clock enable register, Address offset: 0x40 */ __IO uint32_t APB2ENR; /*!< RCC APB2 peripheral clock enable register, Address offset: 0x44 */ uint32_t RESERVED3[2]; /*!< Reserved, 0x48-0x4C */ __IO uint32_t AHB1LPENR; /*!< RCC AHB1 peripheral clock enable in low power mode register, Address offset: 0x50 */ __IO uint32_t AHB2LPENR; /*!< RCC AHB2 peripheral clock enable in low power mode register, Address offset: 0x54 */ __IO uint32_t AHB3LPENR; /*!< RCC AHB3 peripheral clock enable in low power mode register, Address offset: 0x58 */ uint32_t RESERVED4; /*!< Reserved, 0x5C */ __IO uint32_t APB1LPENR; /*!< RCC APB1 peripheral clock enable in low power mode register, Address offset: 0x60 */ __IO uint32_t APB2LPENR; /*!< RCC APB2 peripheral clock enable in low power mode register, Address offset: 0x64 */ uint32_t RESERVED5[2]; /*!< Reserved, 0x68-0x6C */ __IO uint32_t BDCR; /*!< RCC Backup domain control register, Address offset: 0x70 */ __IO uint32_t CSR; /*!< RCC clock control & status register, Address offset: 0x74 */ uint32_t RESERVED6[2]; /*!< Reserved, 0x78-0x7C */ __IO uint32_t SSCGR; /*!< RCC spread spectrum clock generation register, Address offset: 0x80 */ __IO uint32_t PLLI2SCFGR; /*!< RCC PLLI2S configuration register, Address offset: 0x84 */ } RCC_TypeDef; /** * @brief Real-Time Clock */ typedef struct { __IO uint32_t TR; /*!< RTC time register, Address offset: 0x00 */ __IO uint32_t DR; /*!< RTC date register, Address offset: 0x04 */ __IO uint32_t CR; /*!< RTC control register, Address offset: 0x08 */ __IO uint32_t ISR; /*!< RTC initialization and status register, Address offset: 0x0C */ __IO uint32_t PRER; /*!< RTC prescaler register, Address offset: 0x10 */ __IO uint32_t WUTR; /*!< RTC wakeup timer register, Address offset: 0x14 */ __IO uint32_t CALIBR; /*!< RTC calibration register, Address offset: 0x18 */ __IO uint32_t ALRMAR; /*!< RTC alarm A register, Address offset: 0x1C */ __IO uint32_t ALRMBR; /*!< RTC alarm B register, Address offset: 0x20 */ __IO uint32_t WPR; /*!< RTC write protection register, Address offset: 0x24 */ __IO uint32_t SSR; /*!< RTC sub second register, Address offset: 0x28 */ __IO uint32_t SHIFTR; /*!< RTC shift control register, Address offset: 0x2C */ __IO uint32_t TSTR; /*!< RTC time stamp time register, Address offset: 0x30 */ __IO uint32_t TSDR; /*!< RTC time stamp date register, Address offset: 0x34 */ __IO uint32_t TSSSR; /*!< RTC time-stamp sub second register, Address offset: 0x38 */ __IO uint32_t CALR; /*!< RTC calibration register, Address offset: 0x3C */ __IO uint32_t TAFCR; /*!< RTC tamper and alternate function configuration register, Address offset: 0x40 */ __IO uint32_t ALRMASSR;/*!< RTC alarm A sub second register, Address offset: 0x44 */ __IO uint32_t ALRMBSSR;/*!< RTC alarm B sub second register, Address offset: 0x48 */ uint32_t RESERVED7; /*!< Reserved, 0x4C */ __IO uint32_t BKP0R; /*!< RTC backup register 1, Address offset: 0x50 */ __IO uint32_t BKP1R; /*!< RTC backup register 1, Address offset: 0x54 */ __IO uint32_t BKP2R; /*!< RTC backup register 2, Address offset: 0x58 */ __IO uint32_t BKP3R; /*!< RTC backup register 3, Address offset: 0x5C */ __IO uint32_t BKP4R; /*!< RTC backup register 4, Address offset: 0x60 */ __IO uint32_t BKP5R; /*!< RTC backup register 5, Address offset: 0x64 */ __IO uint32_t BKP6R; /*!< RTC backup register 6, Address offset: 0x68 */ __IO uint32_t BKP7R; /*!< RTC backup register 7, Address offset: 0x6C */ __IO uint32_t BKP8R; /*!< RTC backup register 8, Address offset: 0x70 */ __IO uint32_t BKP9R; /*!< RTC backup register 9, Address offset: 0x74 */ __IO uint32_t BKP10R; /*!< RTC backup register 10, Address offset: 0x78 */ __IO uint32_t BKP11R; /*!< RTC backup register 11, Address offset: 0x7C */ __IO uint32_t BKP12R; /*!< RTC backup register 12, Address offset: 0x80 */ __IO uint32_t BKP13R; /*!< RTC backup register 13, Address offset: 0x84 */ __IO uint32_t BKP14R; /*!< RTC backup register 14, Address offset: 0x88 */ __IO uint32_t BKP15R; /*!< RTC backup register 15, Address offset: 0x8C */ __IO uint32_t BKP16R; /*!< RTC backup register 16, Address offset: 0x90 */ __IO uint32_t BKP17R; /*!< RTC backup register 17, Address offset: 0x94 */ __IO uint32_t BKP18R; /*!< RTC backup register 18, Address offset: 0x98 */ __IO uint32_t BKP19R; /*!< RTC backup register 19, Address offset: 0x9C */ } RTC_TypeDef; /** * @brief SD host Interface */ typedef struct { __IO uint32_t POWER; /*!< SDIO power control register, Address offset: 0x00 */ __IO uint32_t CLKCR; /*!< SDI clock control register, Address offset: 0x04 */ __IO uint32_t ARG; /*!< SDIO argument register, Address offset: 0x08 */ __IO uint32_t CMD; /*!< SDIO command register, Address offset: 0x0C */ __I uint32_t RESPCMD; /*!< SDIO command response register, Address offset: 0x10 */ __I uint32_t RESP1; /*!< SDIO response 1 register, Address offset: 0x14 */ __I uint32_t RESP2; /*!< SDIO response 2 register, Address offset: 0x18 */ __I uint32_t RESP3; /*!< SDIO response 3 register, Address offset: 0x1C */ __I uint32_t RESP4; /*!< SDIO response 4 register, Address offset: 0x20 */ __IO uint32_t DTIMER; /*!< SDIO data timer register, Address offset: 0x24 */ __IO uint32_t DLEN; /*!< SDIO data length register, Address offset: 0x28 */ __IO uint32_t DCTRL; /*!< SDIO data control register, Address offset: 0x2C */ __I uint32_t DCOUNT; /*!< SDIO data counter register, Address offset: 0x30 */ __I uint32_t STA; /*!< SDIO status register, Address offset: 0x34 */ __IO uint32_t ICR; /*!< SDIO interrupt clear register, Address offset: 0x38 */ __IO uint32_t MASK; /*!< SDIO mask register, Address offset: 0x3C */ uint32_t RESERVED0[2]; /*!< Reserved, 0x40-0x44 */ __I uint32_t FIFOCNT; /*!< SDIO FIFO counter register, Address offset: 0x48 */ uint32_t RESERVED1[13]; /*!< Reserved, 0x4C-0x7C */ __IO uint32_t FIFO; /*!< SDIO data FIFO register, Address offset: 0x80 */ } SDIO_TypeDef; /** * @brief Serial Peripheral Interface */ typedef struct { __IO uint32_t CR1; /*!< SPI control register 1 (not used in I2S mode), Address offset: 0x00 */ __IO uint32_t CR2; /*!< SPI control register 2, Address offset: 0x04 */ __IO uint32_t SR; /*!< SPI status register, Address offset: 0x08 */ __IO uint32_t DR; /*!< SPI data register, Address offset: 0x0C */ __IO uint32_t CRCPR; /*!< SPI CRC polynomial register (not used in I2S mode), Address offset: 0x10 */ __IO uint32_t RXCRCR; /*!< SPI RX CRC register (not used in I2S mode), Address offset: 0x14 */ __IO uint32_t TXCRCR; /*!< SPI TX CRC register (not used in I2S mode), Address offset: 0x18 */ __IO uint32_t I2SCFGR; /*!< SPI_I2S configuration register, Address offset: 0x1C */ __IO uint32_t I2SPR; /*!< SPI_I2S prescaler register, Address offset: 0x20 */ } SPI_TypeDef; /** * @brief TIM */ typedef struct { __IO uint32_t CR1; /*!< TIM control register 1, Address offset: 0x00 */ __IO uint32_t CR2; /*!< TIM control register 2, Address offset: 0x04 */ __IO uint32_t SMCR; /*!< TIM slave mode control register, Address offset: 0x08 */ __IO uint32_t DIER; /*!< TIM DMA/interrupt enable register, Address offset: 0x0C */ __IO uint32_t SR; /*!< TIM status register, Address offset: 0x10 */ __IO uint32_t EGR; /*!< TIM event generation register, Address offset: 0x14 */ __IO uint32_t CCMR1; /*!< TIM capture/compare mode register 1, Address offset: 0x18 */ __IO uint32_t CCMR2; /*!< TIM capture/compare mode register 2, Address offset: 0x1C */ __IO uint32_t CCER; /*!< TIM capture/compare enable register, Address offset: 0x20 */ __IO uint32_t CNT; /*!< TIM counter register, Address offset: 0x24 */ __IO uint32_t PSC; /*!< TIM prescaler, Address offset: 0x28 */ __IO uint32_t ARR; /*!< TIM auto-reload register, Address offset: 0x2C */ __IO uint32_t RCR; /*!< TIM repetition counter register, Address offset: 0x30 */ __IO uint32_t CCR1; /*!< TIM capture/compare register 1, Address offset: 0x34 */ __IO uint32_t CCR2; /*!< TIM capture/compare register 2, Address offset: 0x38 */ __IO uint32_t CCR3; /*!< TIM capture/compare register 3, Address offset: 0x3C */ __IO uint32_t CCR4; /*!< TIM capture/compare register 4, Address offset: 0x40 */ __IO uint32_t BDTR; /*!< TIM break and dead-time register, Address offset: 0x44 */ __IO uint32_t DCR; /*!< TIM DMA control register, Address offset: 0x48 */ __IO uint32_t DMAR; /*!< TIM DMA address for full transfer, Address offset: 0x4C */ __IO uint32_t OR; /*!< TIM option register, Address offset: 0x50 */ } TIM_TypeDef; /** * @brief Universal Synchronous Asynchronous Receiver Transmitter */ typedef struct { __IO uint32_t SR; /*!< USART Status register, Address offset: 0x00 */ __IO uint32_t DR; /*!< USART Data register, Address offset: 0x04 */ __IO uint32_t BRR; /*!< USART Baud rate register, Address offset: 0x08 */ __IO uint32_t CR1; /*!< USART Control register 1, Address offset: 0x0C */ __IO uint32_t CR2; /*!< USART Control register 2, Address offset: 0x10 */ __IO uint32_t CR3; /*!< USART Control register 3, Address offset: 0x14 */ __IO uint32_t GTPR; /*!< USART Guard time and prescaler register, Address offset: 0x18 */ } USART_TypeDef; /** * @brief Window WATCHDOG */ typedef struct { __IO uint32_t CR; /*!< WWDG Control register, Address offset: 0x00 */ __IO uint32_t CFR; /*!< WWDG Configuration register, Address offset: 0x04 */ __IO uint32_t SR; /*!< WWDG Status register, Address offset: 0x08 */ } WWDG_TypeDef; /** * @brief __USB_OTG_Core_register */ typedef struct { __IO uint32_t GOTGCTL; /*!< USB_OTG Control and Status Register Address offset : 0x00 */ __IO uint32_t GOTGINT; /*!< USB_OTG Interrupt Register Address offset : 0x04 */ __IO uint32_t GAHBCFG; /*!< Core AHB Configuration Register Address offset : 0x08 */ __IO uint32_t GUSBCFG; /*!< Core USB Configuration Register Address offset : 0x0C */ __IO uint32_t GRSTCTL; /*!< Core Reset Register Address offset : 0x10 */ __IO uint32_t GINTSTS; /*!< Core Interrupt Register Address offset : 0x14 */ __IO uint32_t GINTMSK; /*!< Core Interrupt Mask Register Address offset : 0x18 */ __IO uint32_t GRXSTSR; /*!< Receive Sts Q Read Register Address offset : 0x1C */ __IO uint32_t GRXSTSP; /*!< Receive Sts Q Read & POP Register Address offset : 0x20 */ __IO uint32_t GRXFSIZ; /* Receive FIFO Size Register Address offset : 0x24 */ __IO uint32_t DIEPTXF0_HNPTXFSIZ; /*!< EP0 / Non Periodic Tx FIFO Size Register Address offset : 0x28 */ __IO uint32_t HNPTXSTS; /*!< Non Periodic Tx FIFO/Queue Sts reg Address offset : 0x2C */ uint32_t Reserved30[2]; /* Reserved Address offset : 0x30 */ __IO uint32_t GCCFG; /*!< General Purpose IO Register Address offset : 0x38 */ __IO uint32_t CID; /*!< User ID Register Address offset : 0x3C */ uint32_t Reserved40[48]; /*!< Reserved Address offset : 0x40-0xFF */ __IO uint32_t HPTXFSIZ; /*!< Host Periodic Tx FIFO Size Reg Address offset : 0x100 */ __IO uint32_t DIEPTXF[0x0F]; /*!< dev Periodic Transmit FIFO */ } USB_OTG_GlobalTypeDef; /** * @brief __device_Registers */ typedef struct { __IO uint32_t DCFG; /*!< dev Configuration Register Address offset : 0x800 */ __IO uint32_t DCTL; /*!< dev Control Register Address offset : 0x804 */ __IO uint32_t DSTS; /*!< dev Status Register (RO) Address offset : 0x808 */ uint32_t Reserved0C; /*!< Reserved Address offset : 0x80C */ __IO uint32_t DIEPMSK; /* !< dev IN Endpoint Mask Address offset : 0x810 */ __IO uint32_t DOEPMSK; /*!< dev OUT Endpoint Mask Address offset : 0x814 */ __IO uint32_t DAINT; /*!< dev All Endpoints Itr Reg Address offset : 0x818 */ __IO uint32_t DAINTMSK; /*!< dev All Endpoints Itr Mask Address offset : 0x81C */ uint32_t Reserved20; /*!< Reserved Address offset : 0x820 */ uint32_t Reserved9; /*!< Reserved Address offset : 0x824 */ __IO uint32_t DVBUSDIS; /*!< dev VBUS discharge Register Address offset : 0x828 */ __IO uint32_t DVBUSPULSE; /*!< dev VBUS Pulse Register Address offset : 0x82C */ __IO uint32_t DTHRCTL; /*!< dev thr Address offset : 0x830 */ __IO uint32_t DIEPEMPMSK; /*!< dev empty msk Address offset : 0x834 */ __IO uint32_t DEACHINT; /*!< dedicated EP interrupt Address offset : 0x838 */ __IO uint32_t DEACHMSK; /*!< dedicated EP msk Address offset : 0x83C */ uint32_t Reserved40; /*!< dedicated EP mask Address offset : 0x840 */ __IO uint32_t DINEP1MSK; /*!< dedicated EP mask Address offset : 0x844 */ uint32_t Reserved44[15]; /*!< Reserved Address offset : 0x844-0x87C */ __IO uint32_t DOUTEP1MSK; /*!< dedicated EP msk Address offset : 0x884 */ } USB_OTG_DeviceTypeDef; /** * @brief __IN_Endpoint-Specific_Register */ typedef struct { __IO uint32_t DIEPCTL; /* dev IN Endpoint Control Reg 900h + (ep_num * 20h) + 00h */ uint32_t Reserved04; /* Reserved 900h + (ep_num * 20h) + 04h */ __IO uint32_t DIEPINT; /* dev IN Endpoint Itr Reg 900h + (ep_num * 20h) + 08h */ uint32_t Reserved0C; /* Reserved 900h + (ep_num * 20h) + 0Ch */ __IO uint32_t DIEPTSIZ; /* IN Endpoint Txfer Size 900h + (ep_num * 20h) + 10h */ __IO uint32_t DIEPDMA; /* IN Endpoint DMA Address Reg 900h + (ep_num * 20h) + 14h */ __IO uint32_t DTXFSTS; /*IN Endpoint Tx FIFO Status Reg 900h + (ep_num * 20h) + 18h */ uint32_t Reserved18; /* Reserved 900h+(ep_num*20h)+1Ch-900h+ (ep_num * 20h) + 1Ch */ } USB_OTG_INEndpointTypeDef; /** * @brief __OUT_Endpoint-Specific_Registers */ typedef struct { __IO uint32_t DOEPCTL; /* dev OUT Endpoint Control Reg B00h + (ep_num * 20h) + 00h*/ uint32_t Reserved04; /* Reserved B00h + (ep_num * 20h) + 04h*/ __IO uint32_t DOEPINT; /* dev OUT Endpoint Itr Reg B00h + (ep_num * 20h) + 08h*/ uint32_t Reserved0C; /* Reserved B00h + (ep_num * 20h) + 0Ch*/ __IO uint32_t DOEPTSIZ; /* dev OUT Endpoint Txfer Size B00h + (ep_num * 20h) + 10h*/ __IO uint32_t DOEPDMA; /* dev OUT Endpoint DMA Address B00h + (ep_num * 20h) + 14h*/ uint32_t Reserved18[2]; /* Reserved B00h + (ep_num * 20h) + 18h - B00h + (ep_num * 20h) + 1Ch*/ } USB_OTG_OUTEndpointTypeDef; /** * @brief __Host_Mode_Register_Structures */ typedef struct { __IO uint32_t HCFG; /* Host Configuration Register 400h*/ __IO uint32_t HFIR; /* Host Frame Interval Register 404h*/ __IO uint32_t HFNUM; /* Host Frame Nbr/Frame Remaining 408h*/ uint32_t Reserved40C; /* Reserved 40Ch*/ __IO uint32_t HPTXSTS; /* Host Periodic Tx FIFO/ Queue Status 410h*/ __IO uint32_t HAINT; /* Host All Channels Interrupt Register 414h*/ __IO uint32_t HAINTMSK; /* Host All Channels Interrupt Mask 418h*/ } USB_OTG_HostTypeDef; /** * @brief __Host_Channel_Specific_Registers */ typedef struct { __IO uint32_t HCCHAR; __IO uint32_t HCSPLT; __IO uint32_t HCINT; __IO uint32_t HCINTMSK; __IO uint32_t HCTSIZ; __IO uint32_t HCDMA; uint32_t Reserved[2]; } USB_OTG_HostChannelTypeDef; /** * @brief Peripheral_memory_map */ #define FLASH_BASE ((uint32_t)0x08000000) /*!< FLASH(up to 1 MB) base address in the alias region */ #define CCMDATARAM_BASE ((uint32_t)0x10000000) /*!< CCM(core coupled memory) data RAM(64 KB) base address in the alias region */ #define SRAM1_BASE ((uint32_t)0x20000000) /*!< SRAM1(112 KB) base address in the alias region */ #define SRAM2_BASE ((uint32_t)0x2001C000) /*!< SRAM2(16 KB) base address in the alias region */ #define PERIPH_BASE ((uint32_t)0x40000000) /*!< Peripheral base address in the alias region */ #define BKPSRAM_BASE ((uint32_t)0x40024000) /*!< Backup SRAM(4 KB) base address in the alias region */ #define SRAM1_BB_BASE ((uint32_t)0x22000000) /*!< SRAM1(112 KB) base address in the bit-band region */ #define SRAM2_BB_BASE ((uint32_t)0x22380000) /*!< SRAM2(16 KB) base address in the bit-band region */ #define PERIPH_BB_BASE ((uint32_t)0x42000000) /*!< Peripheral base address in the bit-band region */ #define BKPSRAM_BB_BASE ((uint32_t)0x42480000) /*!< Backup SRAM(4 KB) base address in the bit-band region */ #define FLASH_END ((uint32_t)0x0807FFFF) /*!< FLASH end address */ /* Legacy defines */ #define SRAM_BASE SRAM1_BASE #define SRAM_BB_BASE SRAM1_BB_BASE /*!< Peripheral memory map */ #define APB1PERIPH_BASE PERIPH_BASE #define APB2PERIPH_BASE (PERIPH_BASE + 0x00010000) #define AHB1PERIPH_BASE (PERIPH_BASE + 0x00020000) #define AHB2PERIPH_BASE (PERIPH_BASE + 0x10000000) /*!< APB1 peripherals */ #define TIM2_BASE (APB1PERIPH_BASE + 0x0000) #define TIM3_BASE (APB1PERIPH_BASE + 0x0400) #define TIM4_BASE (APB1PERIPH_BASE + 0x0800) #define TIM5_BASE (APB1PERIPH_BASE + 0x0C00) #define RTC_BASE (APB1PERIPH_BASE + 0x2800) #define WWDG_BASE (APB1PERIPH_BASE + 0x2C00) #define IWDG_BASE (APB1PERIPH_BASE + 0x3000) #define I2S2ext_BASE (APB1PERIPH_BASE + 0x3400) #define SPI2_BASE (APB1PERIPH_BASE + 0x3800) #define SPI3_BASE (APB1PERIPH_BASE + 0x3C00) #define I2S3ext_BASE (APB1PERIPH_BASE + 0x4000) #define USART2_BASE (APB1PERIPH_BASE + 0x4400) #define I2C1_BASE (APB1PERIPH_BASE + 0x5400) #define I2C2_BASE (APB1PERIPH_BASE + 0x5800) #define I2C3_BASE (APB1PERIPH_BASE + 0x5C00) #define PWR_BASE (APB1PERIPH_BASE + 0x7000) /*!< APB2 peripherals */ #define TIM1_BASE (APB2PERIPH_BASE + 0x0000) #define USART1_BASE (APB2PERIPH_BASE + 0x1000) #define USART6_BASE (APB2PERIPH_BASE + 0x1400) #define ADC1_BASE (APB2PERIPH_BASE + 0x2000) #define ADC_BASE (APB2PERIPH_BASE + 0x2300) #define SDIO_BASE (APB2PERIPH_BASE + 0x2C00) #define SPI1_BASE (APB2PERIPH_BASE + 0x3000) #define SPI4_BASE (APB2PERIPH_BASE + 0x3400) #define SYSCFG_BASE (APB2PERIPH_BASE + 0x3800) #define EXTI_BASE (APB2PERIPH_BASE + 0x3C00) #define TIM9_BASE (APB2PERIPH_BASE + 0x4000) #define TIM10_BASE (APB2PERIPH_BASE + 0x4400) #define TIM11_BASE (APB2PERIPH_BASE + 0x4800) /*!< AHB1 peripherals */ #define GPIOA_BASE (AHB1PERIPH_BASE + 0x0000) #define GPIOB_BASE (AHB1PERIPH_BASE + 0x0400) #define GPIOC_BASE (AHB1PERIPH_BASE + 0x0800) #define GPIOD_BASE (AHB1PERIPH_BASE + 0x0C00) #define GPIOE_BASE (AHB1PERIPH_BASE + 0x1000) #define GPIOH_BASE (AHB1PERIPH_BASE + 0x1C00) #define CRC_BASE (AHB1PERIPH_BASE + 0x3000) #define RCC_BASE (AHB1PERIPH_BASE + 0x3800) #define FLASH_R_BASE (AHB1PERIPH_BASE + 0x3C00) #define DMA1_BASE (AHB1PERIPH_BASE + 0x6000) #define DMA1_Stream0_BASE (DMA1_BASE + 0x010) #define DMA1_Stream1_BASE (DMA1_BASE + 0x028) #define DMA1_Stream2_BASE (DMA1_BASE + 0x040) #define DMA1_Stream3_BASE (DMA1_BASE + 0x058) #define DMA1_Stream4_BASE (DMA1_BASE + 0x070) #define DMA1_Stream5_BASE (DMA1_BASE + 0x088) #define DMA1_Stream6_BASE (DMA1_BASE + 0x0A0) #define DMA1_Stream7_BASE (DMA1_BASE + 0x0B8) #define DMA2_BASE (AHB1PERIPH_BASE + 0x6400) #define DMA2_Stream0_BASE (DMA2_BASE + 0x010) #define DMA2_Stream1_BASE (DMA2_BASE + 0x028) #define DMA2_Stream2_BASE (DMA2_BASE + 0x040) #define DMA2_Stream3_BASE (DMA2_BASE + 0x058) #define DMA2_Stream4_BASE (DMA2_BASE + 0x070) #define DMA2_Stream5_BASE (DMA2_BASE + 0x088) #define DMA2_Stream6_BASE (DMA2_BASE + 0x0A0) #define DMA2_Stream7_BASE (DMA2_BASE + 0x0B8) /* Debug MCU registers base address */ #define DBGMCU_BASE ((uint32_t )0xE0042000) /*!< USB registers base address */ #define USB_OTG_FS_PERIPH_BASE ((uint32_t )0x50000000) #define USB_OTG_GLOBAL_BASE ((uint32_t )0x000) #define USB_OTG_DEVICE_BASE ((uint32_t )0x800) #define USB_OTG_IN_ENDPOINT_BASE ((uint32_t )0x900) #define USB_OTG_OUT_ENDPOINT_BASE ((uint32_t )0xB00) #define USB_OTG_EP_REG_SIZE ((uint32_t )0x20) #define USB_OTG_HOST_BASE ((uint32_t )0x400) #define USB_OTG_HOST_PORT_BASE ((uint32_t )0x440) #define USB_OTG_HOST_CHANNEL_BASE ((uint32_t )0x500) #define USB_OTG_HOST_CHANNEL_SIZE ((uint32_t )0x20) #define USB_OTG_PCGCCTL_BASE ((uint32_t )0xE00) #define USB_OTG_FIFO_BASE ((uint32_t )0x1000) #define USB_OTG_FIFO_SIZE ((uint32_t )0x1000) /** * @} */ /** @addtogroup Peripheral_declaration * @{ */ #define TIM2 ((TIM_TypeDef *) TIM2_BASE) #define TIM3 ((TIM_TypeDef *) TIM3_BASE) #define TIM4 ((TIM_TypeDef *) TIM4_BASE) #define TIM5 ((TIM_TypeDef *) TIM5_BASE) #define RTC ((RTC_TypeDef *) RTC_BASE) #define WWDG ((WWDG_TypeDef *) WWDG_BASE) #define IWDG ((IWDG_TypeDef *) IWDG_BASE) #define I2S2ext ((SPI_TypeDef *) I2S2ext_BASE) #define SPI2 ((SPI_TypeDef *) SPI2_BASE) #define SPI3 ((SPI_TypeDef *) SPI3_BASE) #define I2S3ext ((SPI_TypeDef *) I2S3ext_BASE) #define USART2 ((USART_TypeDef *) USART2_BASE) #define I2C1 ((I2C_TypeDef *) I2C1_BASE) #define I2C2 ((I2C_TypeDef *) I2C2_BASE) #define I2C3 ((I2C_TypeDef *) I2C3_BASE) #define PWR ((PWR_TypeDef *) PWR_BASE) #define TIM1 ((TIM_TypeDef *) TIM1_BASE) #define USART1 ((USART_TypeDef *) USART1_BASE) #define USART6 ((USART_TypeDef *) USART6_BASE) #define ADC ((ADC_Common_TypeDef *) ADC_BASE) #define ADC1 ((ADC_TypeDef *) ADC1_BASE) #define SDIO ((SDIO_TypeDef *) SDIO_BASE) #define SPI1 ((SPI_TypeDef *) SPI1_BASE) #define SPI4 ((SPI_TypeDef *) SPI4_BASE) #define SYSCFG ((SYSCFG_TypeDef *) SYSCFG_BASE) #define EXTI ((EXTI_TypeDef *) EXTI_BASE) #define TIM9 ((TIM_TypeDef *) TIM9_BASE) #define TIM10 ((TIM_TypeDef *) TIM10_BASE) #define TIM11 ((TIM_TypeDef *) TIM11_BASE) #define GPIOA ((GPIO_TypeDef *) GPIOA_BASE) #define GPIOB ((GPIO_TypeDef *) GPIOB_BASE) #define GPIOC ((GPIO_TypeDef *) GPIOC_BASE) #define GPIOD ((GPIO_TypeDef *) GPIOD_BASE) #define GPIOE ((GPIO_TypeDef *) GPIOE_BASE) #define GPIOH ((GPIO_TypeDef *) GPIOH_BASE) #define CRC ((CRC_TypeDef *) CRC_BASE) #define RCC ((RCC_TypeDef *) RCC_BASE) #define FLASH ((FLASH_TypeDef *) FLASH_R_BASE) #define DMA1 ((DMA_TypeDef *) DMA1_BASE) #define DMA1_Stream0 ((DMA_Stream_TypeDef *) DMA1_Stream0_BASE) #define DMA1_Stream1 ((DMA_Stream_TypeDef *) DMA1_Stream1_BASE) #define DMA1_Stream2 ((DMA_Stream_TypeDef *) DMA1_Stream2_BASE) #define DMA1_Stream3 ((DMA_Stream_TypeDef *) DMA1_Stream3_BASE) #define DMA1_Stream4 ((DMA_Stream_TypeDef *) DMA1_Stream4_BASE) #define DMA1_Stream5 ((DMA_Stream_TypeDef *) DMA1_Stream5_BASE) #define DMA1_Stream6 ((DMA_Stream_TypeDef *) DMA1_Stream6_BASE) #define DMA1_Stream7 ((DMA_Stream_TypeDef *) DMA1_Stream7_BASE) #define DMA2 ((DMA_TypeDef *) DMA2_BASE) #define DMA2_Stream0 ((DMA_Stream_TypeDef *) DMA2_Stream0_BASE) #define DMA2_Stream1 ((DMA_Stream_TypeDef *) DMA2_Stream1_BASE) #define DMA2_Stream2 ((DMA_Stream_TypeDef *) DMA2_Stream2_BASE) #define DMA2_Stream3 ((DMA_Stream_TypeDef *) DMA2_Stream3_BASE) #define DMA2_Stream4 ((DMA_Stream_TypeDef *) DMA2_Stream4_BASE) #define DMA2_Stream5 ((DMA_Stream_TypeDef *) DMA2_Stream5_BASE) #define DMA2_Stream6 ((DMA_Stream_TypeDef *) DMA2_Stream6_BASE) #define DMA2_Stream7 ((DMA_Stream_TypeDef *) DMA2_Stream7_BASE) #define DBGMCU ((DBGMCU_TypeDef *) DBGMCU_BASE) #define USB_OTG_FS ((USB_OTG_GlobalTypeDef *) USB_OTG_FS_PERIPH_BASE) /** * @} */ /** @addtogroup Exported_constants * @{ */ /** @addtogroup Peripheral_Registers_Bits_Definition * @{ */ /******************************************************************************/ /* Peripheral Registers_Bits_Definition */ /******************************************************************************/ /******************************************************************************/ /* */ /* Analog to Digital Converter */ /* */ /******************************************************************************/ /******************** Bit definition for ADC_SR register ********************/ #define ADC_SR_AWD ((uint32_t)0x00000001) /*!
© COPYRIGHT(c) 2015 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. * ****************************************************************************** */ /** @addtogroup CMSIS * @{ */ /** @addtogroup stm32f4xx * @{ */ #ifndef __STM32F4xx_H #define __STM32F4xx_H #ifdef __cplusplus extern "C" { #endif /* __cplusplus */ /** @addtogroup Library_configuration_section * @{ */ /** * @brief STM32 Family */ #if !defined (STM32F4) #define STM32F4 #endif /* STM32F4 */ /* Uncomment the line below according to the target STM32 device used in your application */ #if !defined (STM32F405xx) && !defined (STM32F415xx) && !defined (STM32F407xx) && !defined (STM32F417xx) && \ !defined (STM32F427xx) && !defined (STM32F437xx) && !defined (STM32F429xx) && !defined (STM32F439xx) && \ !defined (STM32F401xC) && !defined (STM32F401xE) && !defined (STM32F411xE) && !defined (STM32F446xx) /* #define STM32F405xx */ /*!< STM32F405RG, STM32F405VG and STM32F405ZG Devices */ /* #define STM32F415xx */ /*!< STM32F415RG, STM32F415VG and STM32F415ZG Devices */ /* #define STM32F407xx */ /*!< STM32F407VG, STM32F407VE, STM32F407ZG, STM32F407ZE, STM32F407IG and STM32F407IE Devices */ /* #define STM32F417xx */ /*!< STM32F417VG, STM32F417VE, STM32F417ZG, STM32F417ZE, STM32F417IG and STM32F417IE Devices */ /* #define STM32F427xx */ /*!< STM32F427VG, STM32F427VI, STM32F427ZG, STM32F427ZI, STM32F427IG and STM32F427II Devices */ /* #define STM32F437xx */ /*!< STM32F437VG, STM32F437VI, STM32F437ZG, STM32F437ZI, STM32F437IG and STM32F437II Devices */ /* #define STM32F429xx */ /*!< STM32F429VG, STM32F429VI, STM32F429ZG, STM32F429ZI, STM32F429BG, STM32F429BI, STM32F429NG, STM32F439NI, STM32F429IG and STM32F429II Devices */ /* #define STM32F439xx */ /*!< STM32F439VG, STM32F439VI, STM32F439ZG, STM32F439ZI, STM32F439BG, STM32F439BI, STM32F439NG, STM32F439NI, STM32F439IG and STM32F439II Devices */ /* #define STM32F401xC */ /*!< STM32F401CB, STM32F401CC, STM32F401RB, STM32F401RC, STM32F401VB and STM32F401VC Devices */ #define STM32F401xE /*!< STM32F401CD, STM32F401RD, STM32F401VD, STM32F401CE, STM32F401RE and STM32F401VE Devices */ /* #define STM32F411xE */ /*!< STM32F411CD, STM32F411RD, STM32F411VD, STM32F411CE, STM32F411RE and STM32F411VE Devices */ /* #define STM32F446xx */ /*!< STM32F446MC, STM32F446ME, STM32F446RC, STM32F446RE, STM32F446VC, STM32F446VE, STM32F446ZC, and STM32F446ZE Devices */ #endif /* Tip: To avoid modifying this file each time you need to switch between these devices, you can define the device in your toolchain compiler preprocessor. */ #if !defined (USE_HAL_DRIVER) /** * @brief Comment the line below if you will not use the peripherals drivers. In this case, these drivers will not be included and the application code will be based on direct access to peripherals registers */ #define USE_HAL_DRIVER #endif /* USE_HAL_DRIVER */ /** * @brief CMSIS Device version number V2.3.2 */ #define __STM32F4xx_CMSIS_DEVICE_VERSION_MAIN (0x02) /*!< [31:24] main version */ #define __STM32F4xx_CMSIS_DEVICE_VERSION_SUB1 (0x03) /*!< [23:16] sub1 version */ #define __STM32F4xx_CMSIS_DEVICE_VERSION_SUB2 (0x02) /*!< [15:8] sub2 version */ #define __STM32F4xx_CMSIS_DEVICE_VERSION_RC (0x00) /*!< [7:0] release candidate */ #define __STM32F4xx_CMSIS_DEVICE_VERSION ((__STM32F4xx_CMSIS_DEVICE_VERSION_MAIN << 24)\ |(__STM32F4xx_CMSIS_DEVICE_VERSION_SUB1 << 16)\ |(__STM32F4xx_CMSIS_DEVICE_VERSION_SUB2 << 8 )\ |(__STM32F4xx_CMSIS_DEVICE_VERSION)) /** * @} */ /** @addtogroup Device_Included * @{ */ #if defined(STM32F405xx) #include "stm32f405xx.h" #elif defined(STM32F415xx) #include "stm32f415xx.h" #elif defined(STM32F407xx) #include "stm32f407xx.h" #elif defined(STM32F417xx) #include "stm32f417xx.h" #elif defined(STM32F427xx) #include "stm32f427xx.h" #elif defined(STM32F437xx) #include "stm32f437xx.h" #elif defined(STM32F429xx) #include "stm32f429xx.h" #elif defined(STM32F439xx) #include "stm32f439xx.h" #elif defined(STM32F401xC) #include "stm32f401xc.h" #elif defined(STM32F401xE) #include "stm32f401xe.h" #elif defined(STM32F411xE) #include "stm32f411xe.h" #elif defined(STM32F446xx) #include "stm32f446xx.h" #else #error "Please select first the target STM32F4xx device used in your application (in stm32f4xx.h file)" #endif /** * @} */ /** @addtogroup Exported_types * @{ */ typedef enum { RESET = 0, SET = !RESET } FlagStatus, ITStatus; typedef enum { DISABLE = 0, ENABLE = !DISABLE } FunctionalState; #define IS_FUNCTIONAL_STATE(STATE) (((STATE) == DISABLE) || ((STATE) == ENABLE)) typedef enum { ERROR = 0, SUCCESS = !ERROR } ErrorStatus; /** * @} */ /** @addtogroup Exported_macro * @{ */ #define SET_BIT(REG, BIT) ((REG) |= (BIT)) #define CLEAR_BIT(REG, BIT) ((REG) &= ~(BIT)) #define READ_BIT(REG, BIT) ((REG) & (BIT)) #define CLEAR_REG(REG) ((REG) = (0x0)) #define WRITE_REG(REG, VAL) ((REG) = (VAL)) #define READ_REG(REG) ((REG)) #define MODIFY_REG(REG, CLEARMASK, SETMASK) WRITE_REG((REG), (((READ_REG(REG)) & (~(CLEARMASK))) | (SETMASK))) #define POSITION_VAL(VAL) (__CLZ(__RBIT(VAL))) /** * @} */ #if defined (USE_HAL_DRIVER) #include "stm32f4xx_hal.h" #endif /* USE_HAL_DRIVER */ #ifdef __cplusplus } #endif /* __cplusplus */ #endif /* __STM32F4xx_H */ /** * @} */ /** * @} */ /************************ (C) COPYRIGHT STMicroelectronics *****END OF FILE****/ ================================================ FILE: Zelig/mbed/TARGET_NUCLEO_F401RE/stm32f4xx_hal.h ================================================ /** ****************************************************************************** * @file stm32f4xx_hal.h * @author MCD Application Team * @version V1.4.1 * @date 09-October-2015 * @brief This file contains all the functions prototypes for the HAL * module driver. ****************************************************************************** * @attention * *

© COPYRIGHT(c) 2015 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. * ****************************************************************************** */ /* Define to prevent recursive inclusion -------------------------------------*/ #ifndef __STM32F4xx_HAL_H #define __STM32F4xx_HAL_H #ifdef __cplusplus extern "C" { #endif /* Includes ------------------------------------------------------------------*/ #include "stm32f4xx_hal_conf.h" /** @addtogroup STM32F4xx_HAL_Driver * @{ */ /** @addtogroup HAL * @{ */ /* Exported types ------------------------------------------------------------*/ /* Exported constants --------------------------------------------------------*/ /* Exported macro ------------------------------------------------------------*/ /** @defgroup HAL_Exported_Macros HAL Exported Macros * @{ */ /** @brief Freeze/Unfreeze Peripherals in Debug mode */ #define __HAL_DBGMCU_FREEZE_TIM2() (DBGMCU->APB1FZ |= (DBGMCU_APB1_FZ_DBG_TIM2_STOP)) #define __HAL_DBGMCU_FREEZE_TIM3() (DBGMCU->APB1FZ |= (DBGMCU_APB1_FZ_DBG_TIM3_STOP)) #define __HAL_DBGMCU_FREEZE_TIM4() (DBGMCU->APB1FZ |= (DBGMCU_APB1_FZ_DBG_TIM4_STOP)) #define __HAL_DBGMCU_FREEZE_TIM5() (DBGMCU->APB1FZ |= (DBGMCU_APB1_FZ_DBG_TIM5_STOP)) #define __HAL_DBGMCU_FREEZE_TIM6() (DBGMCU->APB1FZ |= (DBGMCU_APB1_FZ_DBG_TIM6_STOP)) #define __HAL_DBGMCU_FREEZE_TIM7() (DBGMCU->APB1FZ |= (DBGMCU_APB1_FZ_DBG_TIM7_STOP)) #define __HAL_DBGMCU_FREEZE_TIM12() (DBGMCU->APB1FZ |= (DBGMCU_APB1_FZ_DBG_TIM12_STOP)) #define __HAL_DBGMCU_FREEZE_TIM13() (DBGMCU->APB1FZ |= (DBGMCU_APB1_FZ_DBG_TIM13_STOP)) #define __HAL_DBGMCU_FREEZE_TIM14() (DBGMCU->APB1FZ |= (DBGMCU_APB1_FZ_DBG_TIM14_STOP)) #define __HAL_DBGMCU_FREEZE_RTC() (DBGMCU->APB1FZ |= (DBGMCU_APB1_FZ_DBG_RTC_STOP)) #define __HAL_DBGMCU_FREEZE_WWDG() (DBGMCU->APB1FZ |= (DBGMCU_APB1_FZ_DBG_WWDG_STOP)) #define __HAL_DBGMCU_FREEZE_IWDG() (DBGMCU->APB1FZ |= (DBGMCU_APB1_FZ_DBG_IWDG_STOP)) #define __HAL_DBGMCU_FREEZE_I2C1_TIMEOUT() (DBGMCU->APB1FZ |= (DBGMCU_APB1_FZ_DBG_I2C1_SMBUS_TIMEOUT)) #define __HAL_DBGMCU_FREEZE_I2C2_TIMEOUT() (DBGMCU->APB1FZ |= (DBGMCU_APB1_FZ_DBG_I2C2_SMBUS_TIMEOUT)) #define __HAL_DBGMCU_FREEZE_I2C3_TIMEOUT() (DBGMCU->APB1FZ |= (DBGMCU_APB1_FZ_DBG_I2C3_SMBUS_TIMEOUT)) #define __HAL_DBGMCU_FREEZE_CAN1() (DBGMCU->APB1FZ |= (DBGMCU_APB1_FZ_DBG_CAN1_STOP)) #define __HAL_DBGMCU_FREEZE_CAN2() (DBGMCU->APB1FZ |= (DBGMCU_APB1_FZ_DBG_CAN2_STOP)) #define __HAL_DBGMCU_FREEZE_TIM1() (DBGMCU->APB2FZ |= (DBGMCU_APB2_FZ_DBG_TIM1_STOP)) #define __HAL_DBGMCU_FREEZE_TIM8() (DBGMCU->APB2FZ |= (DBGMCU_APB2_FZ_DBG_TIM8_STOP)) #define __HAL_DBGMCU_FREEZE_TIM9() (DBGMCU->APB2FZ |= (DBGMCU_APB2_FZ_DBG_TIM9_STOP)) #define __HAL_DBGMCU_FREEZE_TIM10() (DBGMCU->APB2FZ |= (DBGMCU_APB2_FZ_DBG_TIM10_STOP)) #define __HAL_DBGMCU_FREEZE_TIM11() (DBGMCU->APB2FZ |= (DBGMCU_APB2_FZ_DBG_TIM11_STOP)) #define __HAL_DBGMCU_UNFREEZE_TIM2() (DBGMCU->APB1FZ &= ~(DBGMCU_APB1_FZ_DBG_TIM2_STOP)) #define __HAL_DBGMCU_UNFREEZE_TIM3() (DBGMCU->APB1FZ &= ~(DBGMCU_APB1_FZ_DBG_TIM3_STOP)) #define __HAL_DBGMCU_UNFREEZE_TIM4() (DBGMCU->APB1FZ &= ~(DBGMCU_APB1_FZ_DBG_TIM4_STOP)) #define __HAL_DBGMCU_UNFREEZE_TIM5() (DBGMCU->APB1FZ &= ~(DBGMCU_APB1_FZ_DBG_TIM5_STOP)) #define __HAL_DBGMCU_UNFREEZE_TIM6() (DBGMCU->APB1FZ &= ~(DBGMCU_APB1_FZ_DBG_TIM6_STOP)) #define __HAL_DBGMCU_UNFREEZE_TIM7() (DBGMCU->APB1FZ &= ~(DBGMCU_APB1_FZ_DBG_TIM7_STOP)) #define __HAL_DBGMCU_UNFREEZE_TIM12() (DBGMCU->APB1FZ &= ~(DBGMCU_APB1_FZ_DBG_TIM12_STOP)) #define __HAL_DBGMCU_UNFREEZE_TIM13() (DBGMCU->APB1FZ &= ~(DBGMCU_APB1_FZ_DBG_TIM13_STOP)) #define __HAL_DBGMCU_UNFREEZE_TIM14() (DBGMCU->APB1FZ &= ~(DBGMCU_APB1_FZ_DBG_TIM14_STOP)) #define __HAL_DBGMCU_UNFREEZE_RTC() (DBGMCU->APB1FZ &= ~(DBGMCU_APB1_FZ_DBG_RTC_STOP)) #define __HAL_DBGMCU_UNFREEZE_WWDG() (DBGMCU->APB1FZ &= ~(DBGMCU_APB1_FZ_DBG_WWDG_STOP)) #define __HAL_DBGMCU_UNFREEZE_IWDG() (DBGMCU->APB1FZ &= ~(DBGMCU_APB1_FZ_DBG_IWDG_STOP)) #define __HAL_DBGMCU_UNFREEZE_I2C1_TIMEOUT() (DBGMCU->APB1FZ &= ~(DBGMCU_APB1_FZ_DBG_I2C1_SMBUS_TIMEOUT)) #define __HAL_DBGMCU_UNFREEZE_I2C2_TIMEOUT() (DBGMCU->APB1FZ &= ~(DBGMCU_APB1_FZ_DBG_I2C2_SMBUS_TIMEOUT)) #define __HAL_DBGMCU_UNFREEZE_I2C3_TIMEOUT() (DBGMCU->APB1FZ &= ~(DBGMCU_APB1_FZ_DBG_I2C3_SMBUS_TIMEOUT)) #define __HAL_DBGMCU_UNFREEZE_CAN1() (DBGMCU->APB1FZ &= ~(DBGMCU_APB1_FZ_DBG_CAN1_STOP)) #define __HAL_DBGMCU_UNFREEZE_CAN2() (DBGMCU->APB1FZ &= ~(DBGMCU_APB1_FZ_DBG_CAN2_STOP)) #define __HAL_DBGMCU_UNFREEZE_TIM1() (DBGMCU->APB2FZ &= ~(DBGMCU_APB2_FZ_DBG_TIM1_STOP)) #define __HAL_DBGMCU_UNFREEZE_TIM8() (DBGMCU->APB2FZ &= ~(DBGMCU_APB2_FZ_DBG_TIM8_STOP)) #define __HAL_DBGMCU_UNFREEZE_TIM9() (DBGMCU->APB2FZ &= ~(DBGMCU_APB2_FZ_DBG_TIM9_STOP)) #define __HAL_DBGMCU_UNFREEZE_TIM10() (DBGMCU->APB2FZ &= ~(DBGMCU_APB2_FZ_DBG_TIM10_STOP)) #define __HAL_DBGMCU_UNFREEZE_TIM11() (DBGMCU->APB2FZ &= ~(DBGMCU_APB2_FZ_DBG_TIM11_STOP)) /** @brief Main Flash memory mapped at 0x00000000 */ #define __HAL_SYSCFG_REMAPMEMORY_FLASH() (SYSCFG->MEMRMP &= ~(SYSCFG_MEMRMP_MEM_MODE)) /** @brief System Flash memory mapped at 0x00000000 */ #define __HAL_SYSCFG_REMAPMEMORY_SYSTEMFLASH() do {SYSCFG->MEMRMP &= ~(SYSCFG_MEMRMP_MEM_MODE);\ SYSCFG->MEMRMP |= SYSCFG_MEMRMP_MEM_MODE_0;\ }while(0); /** @brief Embedded SRAM mapped at 0x00000000 */ #define __HAL_SYSCFG_REMAPMEMORY_SRAM() do {SYSCFG->MEMRMP &= ~(SYSCFG_MEMRMP_MEM_MODE);\ SYSCFG->MEMRMP |= (SYSCFG_MEMRMP_MEM_MODE_0 | SYSCFG_MEMRMP_MEM_MODE_1);\ }while(0); #if defined(STM32F405xx) || defined(STM32F415xx) || defined(STM32F407xx)|| defined(STM32F417xx) /** @brief FSMC Bank1 (NOR/PSRAM 1 and 2) mapped at 0x00000000 */ #define __HAL_SYSCFG_REMAPMEMORY_FSMC() do {SYSCFG->MEMRMP &= ~(SYSCFG_MEMRMP_MEM_MODE);\ SYSCFG->MEMRMP |= (SYSCFG_MEMRMP_MEM_MODE_1);\ }while(0); #endif /* STM32F405xx || STM32F415xx || STM32F407xx || STM32F417xx */ #if defined(STM32F427xx) || defined(STM32F437xx) || defined(STM32F429xx)|| defined(STM32F439xx) ||\ defined(STM32F469xx) || defined(STM32F479xx) /** @brief FMC Bank1 (NOR/PSRAM 1 and 2) mapped at 0x00000000 */ #define __HAL_SYSCFG_REMAPMEMORY_FMC() do {SYSCFG->MEMRMP &= ~(SYSCFG_MEMRMP_MEM_MODE);\ SYSCFG->MEMRMP |= (SYSCFG_MEMRMP_MEM_MODE_1);\ }while(0); /** @brief FMC/SDRAM Bank 1 and 2 mapped at 0x00000000 */ #define __HAL_SYSCFG_REMAPMEMORY_FMC_SDRAM() do {SYSCFG->MEMRMP &= ~(SYSCFG_MEMRMP_MEM_MODE);\ SYSCFG->MEMRMP |= (SYSCFG_MEMRMP_MEM_MODE_2);\ }while(0); #endif /* STM32F427xx || STM32F437xx || STM32F429xx || STM32F439xx || STM32F469xx || STM32F479xx */ #if defined(STM32F410Tx) || defined(STM32F410Cx) || defined(STM32F410Rx) /** @defgroup Cortex_Lockup_Enable Cortex Lockup Enable * @{ */ /** @brief SYSCFG Break Lockup lock * Enables and locks the connection of Cortex-M4 LOCKUP (Hardfault) output to TIM1/8 input * @note The selected configuration is locked and can be unlocked by system reset */ #define __HAL_SYSCFG_BREAK_PVD_LOCK() do {SYSCFG->CFGR2 &= ~(SYSCFG_CFGR2_PVD_LOCK); \ SYSCFG->CFGR2 |= SYSCFG_CFGR2_PVD_LOCK; \ }while(0) /** * @} */ /** @defgroup PVD_Lock_Enable PVD Lock * @{ */ /** @brief SYSCFG Break PVD lock * Enables and locks the PVD connection with Timer1/8 Break Input, , as well as the PVDE and PLS[2:0] in the PWR_CR register * @note The selected configuration is locked and can be unlocked by system reset */ #define __HAL_SYSCFG_BREAK_LOCKUP_LOCK() do {SYSCFG->CFGR2 &= ~(SYSCFG_CFGR2_LOCKUP_LOCK); \ SYSCFG->CFGR2 |= SYSCFG_CFGR2_LOCKUP_LOCK; \ }while(0) /** * @} */ #endif /* STM32F410Tx || STM32F410Cx || STM32F410Rx */ /** * @} */ /* Exported functions --------------------------------------------------------*/ /** @addtogroup HAL_Exported_Functions * @{ */ /** @addtogroup HAL_Exported_Functions_Group1 * @{ */ /* Initialization and de-initialization functions ******************************/ HAL_StatusTypeDef HAL_Init(void); HAL_StatusTypeDef HAL_DeInit(void); void HAL_MspInit(void); void HAL_MspDeInit(void); HAL_StatusTypeDef HAL_InitTick (uint32_t TickPriority); /** * @} */ /** @addtogroup HAL_Exported_Functions_Group2 * @{ */ /* Peripheral Control functions ************************************************/ void HAL_IncTick(void); void HAL_Delay(__IO uint32_t Delay); uint32_t HAL_GetTick(void); void HAL_SuspendTick(void); void HAL_ResumeTick(void); uint32_t HAL_GetHalVersion(void); uint32_t HAL_GetREVID(void); uint32_t HAL_GetDEVID(void); void HAL_DBGMCU_EnableDBGSleepMode(void); void HAL_DBGMCU_DisableDBGSleepMode(void); void HAL_DBGMCU_EnableDBGStopMode(void); void HAL_DBGMCU_DisableDBGStopMode(void); void HAL_DBGMCU_EnableDBGStandbyMode(void); void HAL_DBGMCU_DisableDBGStandbyMode(void); void HAL_EnableCompensationCell(void); void HAL_DisableCompensationCell(void); #if defined(STM32F427xx) || defined(STM32F437xx) || defined(STM32F429xx)|| defined(STM32F439xx) ||\ defined(STM32F469xx) || defined(STM32F479xx) void HAL_EnableMemorySwappingBank(void); void HAL_DisableMemorySwappingBank(void); #endif /* STM32F427xx || STM32F437xx || STM32F429xx || STM32F439xx || STM32F469xx || STM32F479xx */ /** * @} */ /** * @} */ /* Private types -------------------------------------------------------------*/ /* Private variables ---------------------------------------------------------*/ /** @defgroup HAL_Private_Variables HAL Private Variables * @{ */ /** * @} */ /* Private constants ---------------------------------------------------------*/ /** @defgroup HAL_Private_Constants HAL Private Constants * @{ */ /** * @} */ /* Private macros ------------------------------------------------------------*/ /* Private functions ---------------------------------------------------------*/ /** * @} */ /** * @} */ #ifdef __cplusplus } #endif #endif /* __STM32F4xx_HAL_H */ /************************ (C) COPYRIGHT STMicroelectronics *****END OF FILE****/ ================================================ FILE: Zelig/mbed/TARGET_NUCLEO_F401RE/stm32f4xx_hal_adc.h ================================================ /** ****************************************************************************** * @file stm32f4xx_hal_adc.h * @author MCD Application Team * @version V1.4.1 * @date 09-October-2015 * @brief Header file containing functions prototypes of ADC HAL library. ****************************************************************************** * @attention * *

© COPYRIGHT(c) 2015 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. * ****************************************************************************** */ /* Define to prevent recursive inclusion -------------------------------------*/ #ifndef __STM32F4xx_ADC_H #define __STM32F4xx_ADC_H #ifdef __cplusplus extern "C" { #endif /* Includes ------------------------------------------------------------------*/ #include "stm32f4xx_hal_def.h" /** @addtogroup STM32F4xx_HAL_Driver * @{ */ /** @addtogroup ADC * @{ */ /* Exported types ------------------------------------------------------------*/ /** @defgroup ADC_Exported_Types ADC Exported Types * @{ */ /** * @brief HAL State structures definition */ typedef enum { HAL_ADC_STATE_RESET = 0x00, /*!< ADC not yet initialized or disabled */ HAL_ADC_STATE_READY = 0x01, /*!< ADC peripheral ready for use */ HAL_ADC_STATE_BUSY = 0x02, /*!< An internal process is ongoing */ HAL_ADC_STATE_BUSY_REG = 0x12, /*!< Regular conversion is ongoing */ HAL_ADC_STATE_BUSY_INJ = 0x22, /*!< Injected conversion is ongoing */ HAL_ADC_STATE_BUSY_INJ_REG = 0x32, /*!< Injected and regular conversion are ongoing */ HAL_ADC_STATE_TIMEOUT = 0x03, /*!< Timeout state */ HAL_ADC_STATE_ERROR = 0x04, /*!< ADC state error */ HAL_ADC_STATE_EOC = 0x05, /*!< Conversion is completed */ HAL_ADC_STATE_EOC_REG = 0x15, /*!< Regular conversion is completed */ HAL_ADC_STATE_EOC_INJ = 0x25, /*!< Injected conversion is completed */ HAL_ADC_STATE_EOC_INJ_REG = 0x35, /*!< Injected and regular conversion are completed */ HAL_ADC_STATE_AWD = 0x06 /*!< ADC state analog watchdog */ }HAL_ADC_StateTypeDef; /** * @brief ADC Init structure definition */ typedef struct { uint32_t ClockPrescaler; /*!< Select the frequency of the clock to the ADC. The clock is common for all the ADCs. This parameter can be a value of @ref ADC_ClockPrescaler */ uint32_t Resolution; /*!< Configures the ADC resolution dual mode. This parameter can be a value of @ref ADC_Resolution */ uint32_t DataAlign; /*!< Specifies whether the ADC data alignment is left or right. This parameter can be a value of @ref ADC_data_align */ uint32_t ScanConvMode; /*!< Specifies whether the conversion is performed in Scan (multi channels) or Single (one channel) mode. This parameter can be set to ENABLE or DISABLE */ uint32_t EOCSelection; /*!< Specifies whether the EOC flag is set at the end of single channel conversion or at the end of all conversions. This parameter can be a value of @ref ADC_EOCSelection Note: Impact on overrun when not using DMA: When EOCSelection is set to ADC_EOC_SINGLE_CONV, overrun detection is automatically enabled, in this case each conversion data must be read. To perform ADC conversions without having to read all conversion data, this parameter must be set to ADC_EOC_SEQ_CONV */ uint32_t ContinuousConvMode; /*!< Specifies whether the conversion is performed in Continuous or Single mode. This parameter can be set to ENABLE or DISABLE. */ uint32_t DMAContinuousRequests; /*!< Specifies whether the DMA requests is performed in Continuous or in Single mode. This parameter can be set to ENABLE or DISABLE. */ uint32_t NbrOfConversion; /*!< Specifies the number of ADC conversions that will be done using the sequencer for regular channel group. This parameter must be a number between Min_Data = 1 and Max_Data = 16. */ uint32_t DiscontinuousConvMode; /*!< Specifies whether the conversion is performed in Discontinuous or not for regular channels. This parameter can be set to ENABLE or DISABLE. */ uint32_t NbrOfDiscConversion; /*!< Specifies the number of ADC discontinuous conversions that will be done using the sequencer for regular channel group. This parameter must be a number between Min_Data = 1 and Max_Data = 8. */ uint32_t ExternalTrigConv; /*!< Selects the external event used to trigger the conversion start of regular group. If set to ADC_SOFTWARE_START, external triggers are disabled. This parameter can be a value of @ref ADC_External_trigger_Source_Regular Note: This parameter can be modified only if there is no conversion is ongoing. */ uint32_t ExternalTrigConvEdge; /*!< Selects the external trigger edge of regular group. If trigger is set to ADC_SOFTWARE_START, this parameter is discarded. This parameter can be a value of @ref ADC_External_trigger_edge_Regular Note: This parameter can be modified only if there is no conversion is ongoing. */ }ADC_InitTypeDef; /** * @brief ADC handle Structure definition */ typedef struct { ADC_TypeDef *Instance; /*!< Register base address */ ADC_InitTypeDef Init; /*!< ADC required parameters */ __IO uint32_t NbrOfCurrentConversionRank; /*!< ADC number of current conversion rank */ DMA_HandleTypeDef *DMA_Handle; /*!< Pointer DMA Handler */ HAL_LockTypeDef Lock; /*!< ADC locking object */ __IO HAL_ADC_StateTypeDef State; /*!< ADC communication state */ __IO uint32_t ErrorCode; /*!< ADC Error code */ }ADC_HandleTypeDef; /** * @brief ADC Configuration regular Channel structure definition */ typedef struct { uint32_t Channel; /*!< The ADC channel to configure. This parameter can be a value of @ref ADC_channels */ uint32_t Rank; /*!< The rank in the regular group sequencer. This parameter must be a number between Min_Data = 1 and Max_Data = 16 */ uint32_t SamplingTime; /*!< The sample time value to be set for the selected channel. This parameter can be a value of @ref ADC_sampling_times */ uint32_t Offset; /*!< Reserved for future use, can be set to 0 */ }ADC_ChannelConfTypeDef; /** * @brief ADC Configuration multi-mode structure definition */ typedef struct { uint32_t WatchdogMode; /*!< Configures the ADC analog watchdog mode. This parameter can be a value of @ref ADC_analog_watchdog_selection */ uint32_t HighThreshold; /*!< Configures the ADC analog watchdog High threshold value. This parameter must be a 12-bit value. */ uint32_t LowThreshold; /*!< Configures the ADC analog watchdog High threshold value. This parameter must be a 12-bit value. */ uint32_t Channel; /*!< Configures ADC channel for the analog watchdog. This parameter has an effect only if watchdog mode is configured on single channel This parameter can be a value of @ref ADC_channels */ uint32_t ITMode; /*!< Specifies whether the analog watchdog is configured is interrupt mode or in polling mode. This parameter can be set to ENABLE or DISABLE */ uint32_t WatchdogNumber; /*!< Reserved for future use, can be set to 0 */ }ADC_AnalogWDGConfTypeDef; /** * @} */ /* Exported constants --------------------------------------------------------*/ /** @defgroup ADC_Exported_Constants ADC Exported Constants * @{ */ /** @defgroup ADC_Error_Code ADC Error Code * @{ */ #define HAL_ADC_ERROR_NONE ((uint32_t)0x00) /*!< No error */ #define HAL_ADC_ERROR_OVR ((uint32_t)0x01) /*!< OVR error */ #define HAL_ADC_ERROR_DMA ((uint32_t)0x02) /*!< DMA transfer error */ /** * @} */ /** @defgroup ADC_ClockPrescaler ADC Clock Prescaler * @{ */ #define ADC_CLOCK_SYNC_PCLK_DIV2 ((uint32_t)0x00000000) #define ADC_CLOCK_SYNC_PCLK_DIV4 ((uint32_t)ADC_CCR_ADCPRE_0) #define ADC_CLOCK_SYNC_PCLK_DIV6 ((uint32_t)ADC_CCR_ADCPRE_1) #define ADC_CLOCK_SYNC_PCLK_DIV8 ((uint32_t)ADC_CCR_ADCPRE) /** * @} */ /** @defgroup ADC_delay_between_2_sampling_phases ADC Delay Between 2 Sampling Phases * @{ */ #define ADC_TWOSAMPLINGDELAY_5CYCLES ((uint32_t)0x00000000) #define ADC_TWOSAMPLINGDELAY_6CYCLES ((uint32_t)ADC_CCR_DELAY_0) #define ADC_TWOSAMPLINGDELAY_7CYCLES ((uint32_t)ADC_CCR_DELAY_1) #define ADC_TWOSAMPLINGDELAY_8CYCLES ((uint32_t)(ADC_CCR_DELAY_1 | ADC_CCR_DELAY_0)) #define ADC_TWOSAMPLINGDELAY_9CYCLES ((uint32_t)ADC_CCR_DELAY_2) #define ADC_TWOSAMPLINGDELAY_10CYCLES ((uint32_t)(ADC_CCR_DELAY_2 | ADC_CCR_DELAY_0)) #define ADC_TWOSAMPLINGDELAY_11CYCLES ((uint32_t)(ADC_CCR_DELAY_2 | ADC_CCR_DELAY_1)) #define ADC_TWOSAMPLINGDELAY_12CYCLES ((uint32_t)(ADC_CCR_DELAY_2 | ADC_CCR_DELAY_1 | ADC_CCR_DELAY_0)) #define ADC_TWOSAMPLINGDELAY_13CYCLES ((uint32_t)ADC_CCR_DELAY_3) #define ADC_TWOSAMPLINGDELAY_14CYCLES ((uint32_t)(ADC_CCR_DELAY_3 | ADC_CCR_DELAY_0)) #define ADC_TWOSAMPLINGDELAY_15CYCLES ((uint32_t)(ADC_CCR_DELAY_3 | ADC_CCR_DELAY_1)) #define ADC_TWOSAMPLINGDELAY_16CYCLES ((uint32_t)(ADC_CCR_DELAY_3 | ADC_CCR_DELAY_1 | ADC_CCR_DELAY_0)) #define ADC_TWOSAMPLINGDELAY_17CYCLES ((uint32_t)(ADC_CCR_DELAY_3 | ADC_CCR_DELAY_2)) #define ADC_TWOSAMPLINGDELAY_18CYCLES ((uint32_t)(ADC_CCR_DELAY_3 | ADC_CCR_DELAY_2 | ADC_CCR_DELAY_0)) #define ADC_TWOSAMPLINGDELAY_19CYCLES ((uint32_t)(ADC_CCR_DELAY_3 | ADC_CCR_DELAY_2 | ADC_CCR_DELAY_1)) #define ADC_TWOSAMPLINGDELAY_20CYCLES ((uint32_t)ADC_CCR_DELAY) /** * @} */ /** @defgroup ADC_Resolution ADC Resolution * @{ */ #define ADC_RESOLUTION_12B ((uint32_t)0x00000000) #define ADC_RESOLUTION_10B ((uint32_t)ADC_CR1_RES_0) #define ADC_RESOLUTION_8B ((uint32_t)ADC_CR1_RES_1) #define ADC_RESOLUTION_6B ((uint32_t)ADC_CR1_RES) /** * @} */ /** @defgroup ADC_External_trigger_edge_Regular ADC External Trigger Edge Regular * @{ */ #define ADC_EXTERNALTRIGCONVEDGE_NONE ((uint32_t)0x00000000) #define ADC_EXTERNALTRIGCONVEDGE_RISING ((uint32_t)ADC_CR2_EXTEN_0) #define ADC_EXTERNALTRIGCONVEDGE_FALLING ((uint32_t)ADC_CR2_EXTEN_1) #define ADC_EXTERNALTRIGCONVEDGE_RISINGFALLING ((uint32_t)ADC_CR2_EXTEN) /** * @} */ /** @defgroup ADC_External_trigger_Source_Regular ADC External Trigger Source Regular * @{ */ /* Note: Parameter ADC_SOFTWARE_START is a software parameter used for */ /* compatibility with other STM32 devices. */ #define ADC_EXTERNALTRIGCONV_T1_CC1 ((uint32_t)0x00000000) #define ADC_EXTERNALTRIGCONV_T1_CC2 ((uint32_t)ADC_CR2_EXTSEL_0) #define ADC_EXTERNALTRIGCONV_T1_CC3 ((uint32_t)ADC_CR2_EXTSEL_1) #define ADC_EXTERNALTRIGCONV_T2_CC2 ((uint32_t)(ADC_CR2_EXTSEL_1 | ADC_CR2_EXTSEL_0)) #define ADC_EXTERNALTRIGCONV_T2_CC3 ((uint32_t)ADC_CR2_EXTSEL_2) #define ADC_EXTERNALTRIGCONV_T2_CC4 ((uint32_t)(ADC_CR2_EXTSEL_2 | ADC_CR2_EXTSEL_0)) #define ADC_EXTERNALTRIGCONV_T2_TRGO ((uint32_t)(ADC_CR2_EXTSEL_2 | ADC_CR2_EXTSEL_1)) #define ADC_EXTERNALTRIGCONV_T3_CC1 ((uint32_t)(ADC_CR2_EXTSEL_2 | ADC_CR2_EXTSEL_1 | ADC_CR2_EXTSEL_0)) #define ADC_EXTERNALTRIGCONV_T3_TRGO ((uint32_t)ADC_CR2_EXTSEL_3) #define ADC_EXTERNALTRIGCONV_T4_CC4 ((uint32_t)(ADC_CR2_EXTSEL_3 | ADC_CR2_EXTSEL_0)) #define ADC_EXTERNALTRIGCONV_T5_CC1 ((uint32_t)(ADC_CR2_EXTSEL_3 | ADC_CR2_EXTSEL_1)) #define ADC_EXTERNALTRIGCONV_T5_CC2 ((uint32_t)(ADC_CR2_EXTSEL_3 | ADC_CR2_EXTSEL_1 | ADC_CR2_EXTSEL_0)) #define ADC_EXTERNALTRIGCONV_T5_CC3 ((uint32_t)(ADC_CR2_EXTSEL_3 | ADC_CR2_EXTSEL_2)) #define ADC_EXTERNALTRIGCONV_T8_CC1 ((uint32_t)(ADC_CR2_EXTSEL_3 | ADC_CR2_EXTSEL_2 | ADC_CR2_EXTSEL_0)) #define ADC_EXTERNALTRIGCONV_T8_TRGO ((uint32_t)(ADC_CR2_EXTSEL_3 | ADC_CR2_EXTSEL_2 | ADC_CR2_EXTSEL_1)) #define ADC_EXTERNALTRIGCONV_Ext_IT11 ((uint32_t)ADC_CR2_EXTSEL) #define ADC_SOFTWARE_START ((uint32_t)ADC_CR2_EXTSEL + 1) /** * @} */ /** @defgroup ADC_data_align ADC Data Align * @{ */ #define ADC_DATAALIGN_RIGHT ((uint32_t)0x00000000) #define ADC_DATAALIGN_LEFT ((uint32_t)ADC_CR2_ALIGN) /** * @} */ /** @defgroup ADC_channels ADC Common Channels * @{ */ #define ADC_CHANNEL_0 ((uint32_t)0x00000000) #define ADC_CHANNEL_1 ((uint32_t)ADC_CR1_AWDCH_0) #define ADC_CHANNEL_2 ((uint32_t)ADC_CR1_AWDCH_1) #define ADC_CHANNEL_3 ((uint32_t)(ADC_CR1_AWDCH_1 | ADC_CR1_AWDCH_0)) #define ADC_CHANNEL_4 ((uint32_t)ADC_CR1_AWDCH_2) #define ADC_CHANNEL_5 ((uint32_t)(ADC_CR1_AWDCH_2 | ADC_CR1_AWDCH_0)) #define ADC_CHANNEL_6 ((uint32_t)(ADC_CR1_AWDCH_2 | ADC_CR1_AWDCH_1)) #define ADC_CHANNEL_7 ((uint32_t)(ADC_CR1_AWDCH_2 | ADC_CR1_AWDCH_1 | ADC_CR1_AWDCH_0)) #define ADC_CHANNEL_8 ((uint32_t)ADC_CR1_AWDCH_3) #define ADC_CHANNEL_9 ((uint32_t)(ADC_CR1_AWDCH_3 | ADC_CR1_AWDCH_0)) #define ADC_CHANNEL_10 ((uint32_t)(ADC_CR1_AWDCH_3 | ADC_CR1_AWDCH_1)) #define ADC_CHANNEL_11 ((uint32_t)(ADC_CR1_AWDCH_3 | ADC_CR1_AWDCH_1 | ADC_CR1_AWDCH_0)) #define ADC_CHANNEL_12 ((uint32_t)(ADC_CR1_AWDCH_3 | ADC_CR1_AWDCH_2)) #define ADC_CHANNEL_13 ((uint32_t)(ADC_CR1_AWDCH_3 | ADC_CR1_AWDCH_2 | ADC_CR1_AWDCH_0)) #define ADC_CHANNEL_14 ((uint32_t)(ADC_CR1_AWDCH_3 | ADC_CR1_AWDCH_2 | ADC_CR1_AWDCH_1)) #define ADC_CHANNEL_15 ((uint32_t)(ADC_CR1_AWDCH_3 | ADC_CR1_AWDCH_2 | ADC_CR1_AWDCH_1 | ADC_CR1_AWDCH_0)) #define ADC_CHANNEL_16 ((uint32_t)ADC_CR1_AWDCH_4) #define ADC_CHANNEL_17 ((uint32_t)(ADC_CR1_AWDCH_4 | ADC_CR1_AWDCH_0)) #define ADC_CHANNEL_18 ((uint32_t)(ADC_CR1_AWDCH_4 | ADC_CR1_AWDCH_1)) #define ADC_CHANNEL_VREFINT ((uint32_t)ADC_CHANNEL_17) #define ADC_CHANNEL_VBAT ((uint32_t)ADC_CHANNEL_18) /** * @} */ /** @defgroup ADC_sampling_times ADC Sampling Times * @{ */ #define ADC_SAMPLETIME_3CYCLES ((uint32_t)0x00000000) #define ADC_SAMPLETIME_15CYCLES ((uint32_t)ADC_SMPR1_SMP10_0) #define ADC_SAMPLETIME_28CYCLES ((uint32_t)ADC_SMPR1_SMP10_1) #define ADC_SAMPLETIME_56CYCLES ((uint32_t)(ADC_SMPR1_SMP10_1 | ADC_SMPR1_SMP10_0)) #define ADC_SAMPLETIME_84CYCLES ((uint32_t)ADC_SMPR1_SMP10_2) #define ADC_SAMPLETIME_112CYCLES ((uint32_t)(ADC_SMPR1_SMP10_2 | ADC_SMPR1_SMP10_0)) #define ADC_SAMPLETIME_144CYCLES ((uint32_t)(ADC_SMPR1_SMP10_2 | ADC_SMPR1_SMP10_1)) #define ADC_SAMPLETIME_480CYCLES ((uint32_t)ADC_SMPR1_SMP10) /** * @} */ /** @defgroup ADC_EOCSelection ADC EOC Selection * @{ */ #define ADC_EOC_SEQ_CONV ((uint32_t)0x00000000) #define ADC_EOC_SINGLE_CONV ((uint32_t)0x00000001) #define ADC_EOC_SINGLE_SEQ_CONV ((uint32_t)0x00000002) /*!< reserved for future use */ /** * @} */ /** @defgroup ADC_Event_type ADC Event Type * @{ */ #define ADC_AWD_EVENT ((uint32_t)ADC_FLAG_AWD) #define ADC_OVR_EVENT ((uint32_t)ADC_FLAG_OVR) /** * @} */ /** @defgroup ADC_analog_watchdog_selection ADC Analog Watchdog Selection * @{ */ #define ADC_ANALOGWATCHDOG_SINGLE_REG ((uint32_t)(ADC_CR1_AWDSGL | ADC_CR1_AWDEN)) #define ADC_ANALOGWATCHDOG_SINGLE_INJEC ((uint32_t)(ADC_CR1_AWDSGL | ADC_CR1_JAWDEN)) #define ADC_ANALOGWATCHDOG_SINGLE_REGINJEC ((uint32_t)(ADC_CR1_AWDSGL | ADC_CR1_AWDEN | ADC_CR1_JAWDEN)) #define ADC_ANALOGWATCHDOG_ALL_REG ((uint32_t)ADC_CR1_AWDEN) #define ADC_ANALOGWATCHDOG_ALL_INJEC ((uint32_t)ADC_CR1_JAWDEN) #define ADC_ANALOGWATCHDOG_ALL_REGINJEC ((uint32_t)(ADC_CR1_AWDEN | ADC_CR1_JAWDEN)) #define ADC_ANALOGWATCHDOG_NONE ((uint32_t)0x00000000) /** * @} */ /** @defgroup ADC_interrupts_definition ADC Interrupts Definition * @{ */ #define ADC_IT_EOC ((uint32_t)ADC_CR1_EOCIE) #define ADC_IT_AWD ((uint32_t)ADC_CR1_AWDIE) #define ADC_IT_JEOC ((uint32_t)ADC_CR1_JEOCIE) #define ADC_IT_OVR ((uint32_t)ADC_CR1_OVRIE) /** * @} */ /** @defgroup ADC_flags_definition ADC Flags Definition * @{ */ #define ADC_FLAG_AWD ((uint32_t)ADC_SR_AWD) #define ADC_FLAG_EOC ((uint32_t)ADC_SR_EOC) #define ADC_FLAG_JEOC ((uint32_t)ADC_SR_JEOC) #define ADC_FLAG_JSTRT ((uint32_t)ADC_SR_JSTRT) #define ADC_FLAG_STRT ((uint32_t)ADC_SR_STRT) #define ADC_FLAG_OVR ((uint32_t)ADC_SR_OVR) /** * @} */ /** @defgroup ADC_channels_type ADC Channels Type * @{ */ #define ADC_ALL_CHANNELS ((uint32_t)0x00000001) #define ADC_REGULAR_CHANNELS ((uint32_t)0x00000002) /*!< reserved for future use */ #define ADC_INJECTED_CHANNELS ((uint32_t)0x00000003) /*!< reserved for future use */ /** * @} */ /** * @} */ /* Exported macro ------------------------------------------------------------*/ /** @defgroup ADC_Exported_Macros ADC Exported Macros * @{ */ /** @brief Reset ADC handle state * @param __HANDLE__: ADC handle * @retval None */ #define __HAL_ADC_RESET_HANDLE_STATE(__HANDLE__) ((__HANDLE__)->State = HAL_ADC_STATE_RESET) /** * @brief Enable the ADC peripheral. * @param __HANDLE__: ADC handle * @retval None */ #define __HAL_ADC_ENABLE(__HANDLE__) ((__HANDLE__)->Instance->CR2 |= ADC_CR2_ADON) /** * @brief Disable the ADC peripheral. * @param __HANDLE__: ADC handle * @retval None */ #define __HAL_ADC_DISABLE(__HANDLE__) ((__HANDLE__)->Instance->CR2 &= ~ADC_CR2_ADON) /** * @brief Enable the ADC end of conversion interrupt. * @param __HANDLE__: specifies the ADC Handle. * @param __INTERRUPT__: ADC Interrupt. * @retval None */ #define __HAL_ADC_ENABLE_IT(__HANDLE__, __INTERRUPT__) (((__HANDLE__)->Instance->CR1) |= (__INTERRUPT__)) /** * @brief Disable the ADC end of conversion interrupt. * @param __HANDLE__: specifies the ADC Handle. * @param __INTERRUPT__: ADC interrupt. * @retval None */ #define __HAL_ADC_DISABLE_IT(__HANDLE__, __INTERRUPT__) (((__HANDLE__)->Instance->CR1) &= ~(__INTERRUPT__)) /** @brief Check if the specified ADC interrupt source is enabled or disabled. * @param __HANDLE__: specifies the ADC Handle. * @param __INTERRUPT__: specifies the ADC interrupt source to check. * @retval The new state of __IT__ (TRUE or FALSE). */ #define __HAL_ADC_GET_IT_SOURCE(__HANDLE__, __INTERRUPT__) (((__HANDLE__)->Instance->CR1 & (__INTERRUPT__)) == (__INTERRUPT__)) /** * @brief Clear the ADC's pending flags. * @param __HANDLE__: specifies the ADC Handle. * @param __FLAG__: ADC flag. * @retval None */ #define __HAL_ADC_CLEAR_FLAG(__HANDLE__, __FLAG__) (((__HANDLE__)->Instance->SR) = ~(__FLAG__)) /** * @brief Get the selected ADC's flag status. * @param __HANDLE__: specifies the ADC Handle. * @param __FLAG__: ADC flag. * @retval None */ #define __HAL_ADC_GET_FLAG(__HANDLE__, __FLAG__) ((((__HANDLE__)->Instance->SR) & (__FLAG__)) == (__FLAG__)) /** * @} */ /* Include ADC HAL Extension module */ #include "stm32f4xx_hal_adc_ex.h" /* Exported functions --------------------------------------------------------*/ /** @addtogroup ADC_Exported_Functions * @{ */ /** @addtogroup ADC_Exported_Functions_Group1 * @{ */ /* Initialization/de-initialization functions ***********************************/ HAL_StatusTypeDef HAL_ADC_Init(ADC_HandleTypeDef* hadc); HAL_StatusTypeDef HAL_ADC_DeInit(ADC_HandleTypeDef *hadc); void HAL_ADC_MspInit(ADC_HandleTypeDef* hadc); void HAL_ADC_MspDeInit(ADC_HandleTypeDef* hadc); /** * @} */ /** @addtogroup ADC_Exported_Functions_Group2 * @{ */ /* I/O operation functions ******************************************************/ HAL_StatusTypeDef HAL_ADC_Start(ADC_HandleTypeDef* hadc); HAL_StatusTypeDef HAL_ADC_Stop(ADC_HandleTypeDef* hadc); HAL_StatusTypeDef HAL_ADC_PollForConversion(ADC_HandleTypeDef* hadc, uint32_t Timeout); HAL_StatusTypeDef HAL_ADC_PollForEvent(ADC_HandleTypeDef* hadc, uint32_t EventType, uint32_t Timeout); HAL_StatusTypeDef HAL_ADC_Start_IT(ADC_HandleTypeDef* hadc); HAL_StatusTypeDef HAL_ADC_Stop_IT(ADC_HandleTypeDef* hadc); void HAL_ADC_IRQHandler(ADC_HandleTypeDef* hadc); HAL_StatusTypeDef HAL_ADC_Start_DMA(ADC_HandleTypeDef* hadc, uint32_t* pData, uint32_t Length); HAL_StatusTypeDef HAL_ADC_Stop_DMA(ADC_HandleTypeDef* hadc); uint32_t HAL_ADC_GetValue(ADC_HandleTypeDef* hadc); void HAL_ADC_ConvCpltCallback(ADC_HandleTypeDef* hadc); void HAL_ADC_ConvHalfCpltCallback(ADC_HandleTypeDef* hadc); void HAL_ADC_LevelOutOfWindowCallback(ADC_HandleTypeDef* hadc); void HAL_ADC_ErrorCallback(ADC_HandleTypeDef *hadc); /** * @} */ /** @addtogroup ADC_Exported_Functions_Group3 * @{ */ /* Peripheral Control functions *************************************************/ HAL_StatusTypeDef HAL_ADC_ConfigChannel(ADC_HandleTypeDef* hadc, ADC_ChannelConfTypeDef* sConfig); HAL_StatusTypeDef HAL_ADC_AnalogWDGConfig(ADC_HandleTypeDef* hadc, ADC_AnalogWDGConfTypeDef* AnalogWDGConfig); /** * @} */ /** @addtogroup ADC_Exported_Functions_Group4 * @{ */ /* Peripheral State functions ***************************************************/ HAL_ADC_StateTypeDef HAL_ADC_GetState(ADC_HandleTypeDef* hadc); uint32_t HAL_ADC_GetError(ADC_HandleTypeDef *hadc); /** * @} */ /** * @} */ /* Private types -------------------------------------------------------------*/ /* Private variables ---------------------------------------------------------*/ /* Private constants ---------------------------------------------------------*/ /** @defgroup ADC_Private_Constants ADC Private Constants * @{ */ /* Delay for ADC stabilization time. */ /* Maximum delay is 1us (refer to device datasheet, parameter tSTAB). */ /* Unit: us */ #define ADC_STAB_DELAY_US ((uint32_t) 3) /* Delay for temperature sensor stabilization time. */ /* Maximum delay is 10us (refer to device datasheet, parameter tSTART). */ /* Unit: us */ #define ADC_TEMPSENSOR_DELAY_US ((uint32_t) 10) /** * @} */ /* Private macros ------------------------------------------------------------*/ /** @defgroup ADC_Private_Macros ADC Private Macros * @{ */ #define IS_ADC_CLOCKPRESCALER(ADC_CLOCK) (((ADC_CLOCK) == ADC_CLOCK_SYNC_PCLK_DIV2) || \ ((ADC_CLOCK) == ADC_CLOCK_SYNC_PCLK_DIV4) || \ ((ADC_CLOCK) == ADC_CLOCK_SYNC_PCLK_DIV6) || \ ((ADC_CLOCK) == ADC_CLOCK_SYNC_PCLK_DIV8)) #define IS_ADC_SAMPLING_DELAY(DELAY) (((DELAY) == ADC_TWOSAMPLINGDELAY_5CYCLES) || \ ((DELAY) == ADC_TWOSAMPLINGDELAY_6CYCLES) || \ ((DELAY) == ADC_TWOSAMPLINGDELAY_7CYCLES) || \ ((DELAY) == ADC_TWOSAMPLINGDELAY_8CYCLES) || \ ((DELAY) == ADC_TWOSAMPLINGDELAY_9CYCLES) || \ ((DELAY) == ADC_TWOSAMPLINGDELAY_10CYCLES) || \ ((DELAY) == ADC_TWOSAMPLINGDELAY_11CYCLES) || \ ((DELAY) == ADC_TWOSAMPLINGDELAY_12CYCLES) || \ ((DELAY) == ADC_TWOSAMPLINGDELAY_13CYCLES) || \ ((DELAY) == ADC_TWOSAMPLINGDELAY_14CYCLES) || \ ((DELAY) == ADC_TWOSAMPLINGDELAY_15CYCLES) || \ ((DELAY) == ADC_TWOSAMPLINGDELAY_16CYCLES) || \ ((DELAY) == ADC_TWOSAMPLINGDELAY_17CYCLES) || \ ((DELAY) == ADC_TWOSAMPLINGDELAY_18CYCLES) || \ ((DELAY) == ADC_TWOSAMPLINGDELAY_19CYCLES) || \ ((DELAY) == ADC_TWOSAMPLINGDELAY_20CYCLES)) #define IS_ADC_RESOLUTION(RESOLUTION) (((RESOLUTION) == ADC_RESOLUTION_12B) || \ ((RESOLUTION) == ADC_RESOLUTION_10B) || \ ((RESOLUTION) == ADC_RESOLUTION_8B) || \ ((RESOLUTION) == ADC_RESOLUTION_6B)) #define IS_ADC_EXT_TRIG_EDGE(EDGE) (((EDGE) == ADC_EXTERNALTRIGCONVEDGE_NONE) || \ ((EDGE) == ADC_EXTERNALTRIGCONVEDGE_RISING) || \ ((EDGE) == ADC_EXTERNALTRIGCONVEDGE_FALLING) || \ ((EDGE) == ADC_EXTERNALTRIGCONVEDGE_RISINGFALLING)) #define IS_ADC_EXT_TRIG(REGTRIG) (((REGTRIG) == ADC_EXTERNALTRIGCONV_T1_CC1) || \ ((REGTRIG) == ADC_EXTERNALTRIGCONV_T1_CC2) || \ ((REGTRIG) == ADC_EXTERNALTRIGCONV_T1_CC3) || \ ((REGTRIG) == ADC_EXTERNALTRIGCONV_T2_CC2) || \ ((REGTRIG) == ADC_EXTERNALTRIGCONV_T2_CC3) || \ ((REGTRIG) == ADC_EXTERNALTRIGCONV_T2_CC4) || \ ((REGTRIG) == ADC_EXTERNALTRIGCONV_T2_TRGO) || \ ((REGTRIG) == ADC_EXTERNALTRIGCONV_T3_CC1) || \ ((REGTRIG) == ADC_EXTERNALTRIGCONV_T3_TRGO) || \ ((REGTRIG) == ADC_EXTERNALTRIGCONV_T4_CC4) || \ ((REGTRIG) == ADC_EXTERNALTRIGCONV_T5_CC1) || \ ((REGTRIG) == ADC_EXTERNALTRIGCONV_T5_CC2) || \ ((REGTRIG) == ADC_EXTERNALTRIGCONV_T5_CC3) || \ ((REGTRIG) == ADC_EXTERNALTRIGCONV_T8_CC1) || \ ((REGTRIG) == ADC_EXTERNALTRIGCONV_T8_TRGO) || \ ((REGTRIG) == ADC_EXTERNALTRIGCONV_Ext_IT11)|| \ ((REGTRIG) == ADC_SOFTWARE_START)) #define IS_ADC_DATA_ALIGN(ALIGN) (((ALIGN) == ADC_DATAALIGN_RIGHT) || \ ((ALIGN) == ADC_DATAALIGN_LEFT)) #define IS_ADC_SAMPLE_TIME(TIME) (((TIME) == ADC_SAMPLETIME_3CYCLES) || \ ((TIME) == ADC_SAMPLETIME_15CYCLES) || \ ((TIME) == ADC_SAMPLETIME_28CYCLES) || \ ((TIME) == ADC_SAMPLETIME_56CYCLES) || \ ((TIME) == ADC_SAMPLETIME_84CYCLES) || \ ((TIME) == ADC_SAMPLETIME_112CYCLES) || \ ((TIME) == ADC_SAMPLETIME_144CYCLES) || \ ((TIME) == ADC_SAMPLETIME_480CYCLES)) #define IS_ADC_EOCSelection(EOCSelection) (((EOCSelection) == ADC_EOC_SINGLE_CONV) || \ ((EOCSelection) == ADC_EOC_SEQ_CONV) || \ ((EOCSelection) == ADC_EOC_SINGLE_SEQ_CONV)) #define IS_ADC_EVENT_TYPE(EVENT) (((EVENT) == ADC_AWD_EVENT) || \ ((EVENT) == ADC_OVR_EVENT)) #define IS_ADC_ANALOG_WATCHDOG(WATCHDOG) (((WATCHDOG) == ADC_ANALOGWATCHDOG_SINGLE_REG) || \ ((WATCHDOG) == ADC_ANALOGWATCHDOG_SINGLE_INJEC) || \ ((WATCHDOG) == ADC_ANALOGWATCHDOG_SINGLE_REGINJEC) || \ ((WATCHDOG) == ADC_ANALOGWATCHDOG_ALL_REG) || \ ((WATCHDOG) == ADC_ANALOGWATCHDOG_ALL_INJEC) || \ ((WATCHDOG) == ADC_ANALOGWATCHDOG_ALL_REGINJEC) || \ ((WATCHDOG) == ADC_ANALOGWATCHDOG_NONE)) #define IS_ADC_CHANNELS_TYPE(CHANNEL_TYPE) (((CHANNEL_TYPE) == ADC_ALL_CHANNELS) || \ ((CHANNEL_TYPE) == ADC_REGULAR_CHANNELS) || \ ((CHANNEL_TYPE) == ADC_INJECTED_CHANNELS)) #define IS_ADC_THRESHOLD(THRESHOLD) ((THRESHOLD) <= ((uint32_t)0xFFF)) #define IS_ADC_REGULAR_LENGTH(LENGTH) (((LENGTH) >= ((uint32_t)1)) && ((LENGTH) <= ((uint32_t)16))) #define IS_ADC_REGULAR_RANK(RANK) (((RANK) >= ((uint32_t)1)) && ((RANK) <= ((uint32_t)16))) #define IS_ADC_REGULAR_DISC_NUMBER(NUMBER) (((NUMBER) >= ((uint32_t)1)) && ((NUMBER) <= ((uint32_t)8))) #define IS_ADC_RANGE(RESOLUTION, ADC_VALUE) \ ((((RESOLUTION) == ADC_RESOLUTION_12B) && ((ADC_VALUE) <= ((uint32_t)0x0FFF))) || \ (((RESOLUTION) == ADC_RESOLUTION_10B) && ((ADC_VALUE) <= ((uint32_t)0x03FF))) || \ (((RESOLUTION) == ADC_RESOLUTION_8B) && ((ADC_VALUE) <= ((uint32_t)0x00FF))) || \ (((RESOLUTION) == ADC_RESOLUTION_6B) && ((ADC_VALUE) <= ((uint32_t)0x003F)))) /** * @brief Set ADC Regular channel sequence length. * @param _NbrOfConversion_: Regular channel sequence length. * @retval None */ #define ADC_SQR1(_NbrOfConversion_) (((_NbrOfConversion_) - (uint8_t)1) << 20) /** * @brief Set the ADC's sample time for channel numbers between 10 and 18. * @param _SAMPLETIME_: Sample time parameter. * @param _CHANNELNB_: Channel number. * @retval None */ #define ADC_SMPR1(_SAMPLETIME_, _CHANNELNB_) ((_SAMPLETIME_) << (3 * (((uint32_t)((uint16_t)(_CHANNELNB_))) - 10))) /** * @brief Set the ADC's sample time for channel numbers between 0 and 9. * @param _SAMPLETIME_: Sample time parameter. * @param _CHANNELNB_: Channel number. * @retval None */ #define ADC_SMPR2(_SAMPLETIME_, _CHANNELNB_) ((_SAMPLETIME_) << (3 * ((uint32_t)((uint16_t)(_CHANNELNB_))))) /** * @brief Set the selected regular channel rank for rank between 1 and 6. * @param _CHANNELNB_: Channel number. * @param _RANKNB_: Rank number. * @retval None */ #define ADC_SQR3_RK(_CHANNELNB_, _RANKNB_) (((uint32_t)((uint16_t)(_CHANNELNB_))) << (5 * ((_RANKNB_) - 1))) /** * @brief Set the selected regular channel rank for rank between 7 and 12. * @param _CHANNELNB_: Channel number. * @param _RANKNB_: Rank number. * @retval None */ #define ADC_SQR2_RK(_CHANNELNB_, _RANKNB_) (((uint32_t)((uint16_t)(_CHANNELNB_))) << (5 * ((_RANKNB_) - 7))) /** * @brief Set the selected regular channel rank for rank between 13 and 16. * @param _CHANNELNB_: Channel number. * @param _RANKNB_: Rank number. * @retval None */ #define ADC_SQR1_RK(_CHANNELNB_, _RANKNB_) (((uint32_t)((uint16_t)(_CHANNELNB_))) << (5 * ((_RANKNB_) - 13))) /** * @brief Enable ADC continuous conversion mode. * @param _CONTINUOUS_MODE_: Continuous mode. * @retval None */ #define ADC_CR2_CONTINUOUS(_CONTINUOUS_MODE_) ((_CONTINUOUS_MODE_) << 1) /** * @brief Configures the number of discontinuous conversions for the regular group channels. * @param _NBR_DISCONTINUOUSCONV_: Number of discontinuous conversions. * @retval None */ #define ADC_CR1_DISCONTINUOUS(_NBR_DISCONTINUOUSCONV_) (((_NBR_DISCONTINUOUSCONV_) - 1) << POSITION_VAL(ADC_CR1_DISCNUM)) /** * @brief Enable ADC scan mode. * @param _SCANCONV_MODE_: Scan conversion mode. * @retval None */ #define ADC_CR1_SCANCONV(_SCANCONV_MODE_) ((_SCANCONV_MODE_) << 8) /** * @brief Enable the ADC end of conversion selection. * @param _EOCSelection_MODE_: End of conversion selection mode. * @retval None */ #define ADC_CR2_EOCSelection(_EOCSelection_MODE_) ((_EOCSelection_MODE_) << 10) /** * @brief Enable the ADC DMA continuous request. * @param _DMAContReq_MODE_: DMA continuous request mode. * @retval None */ #define ADC_CR2_DMAContReq(_DMAContReq_MODE_) ((_DMAContReq_MODE_) << 9) /** * @brief Return resolution bits in CR1 register. * @param __HANDLE__: ADC handle * @retval None */ #define ADC_GET_RESOLUTION(__HANDLE__) (((__HANDLE__)->Instance->CR1) & ADC_CR1_RES) /** * @} */ /* Private functions ---------------------------------------------------------*/ /** @defgroup ADC_Private_Functions ADC Private Functions * @{ */ /** * @} */ /** * @} */ /** * @} */ #ifdef __cplusplus } #endif #endif /*__STM32F4xx_ADC_H */ /************************ (C) COPYRIGHT STMicroelectronics *****END OF FILE****/ ================================================ FILE: Zelig/mbed/TARGET_NUCLEO_F401RE/stm32f4xx_hal_adc_ex.h ================================================ /** ****************************************************************************** * @file stm32f4xx_hal_adc_ex.h * @author MCD Application Team * @version V1.4.1 * @date 09-October-2015 * @brief Header file of ADC HAL module. ****************************************************************************** * @attention * *

© COPYRIGHT(c) 2015 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. * ****************************************************************************** */ /* Define to prevent recursive inclusion -------------------------------------*/ #ifndef __STM32F4xx_ADC_EX_H #define __STM32F4xx_ADC_EX_H #ifdef __cplusplus extern "C" { #endif /* Includes ------------------------------------------------------------------*/ #include "stm32f4xx_hal_def.h" /** @addtogroup STM32F4xx_HAL_Driver * @{ */ /** @addtogroup ADCEx * @{ */ /* Exported types ------------------------------------------------------------*/ /** @defgroup ADCEx_Exported_Types ADC Exported Types * @{ */ /** * @brief ADC Configuration injected Channel structure definition */ typedef struct { uint32_t InjectedChannel; /*!< Configure the ADC injected channel. This parameter can be a value of @ref ADC_channels */ uint32_t InjectedRank; /*!< The rank in the injected group sequencer This parameter must be a number between Min_Data = 1 and Max_Data = 4. */ uint32_t InjectedSamplingTime; /*!< The sample time value to be set for the selected channel. This parameter can be a value of @ref ADC_sampling_times */ uint32_t InjectedOffset; /*!< Defines the offset to be subtracted from the raw converted data when convert injected channels. This parameter must be a number between Min_Data = 0x000 and Max_Data = 0xFFF. */ uint32_t InjectedNbrOfConversion; /*!< Specifies the number of ADC conversions that will be done using the sequencer for injected channel group. This parameter must be a number between Min_Data = 1 and Max_Data = 4. */ uint32_t AutoInjectedConv; /*!< Enables or disables the selected ADC automatic injected group conversion after regular one */ uint32_t InjectedDiscontinuousConvMode; /*!< Specifies whether the conversion is performed in Discontinuous mode or not for injected channels. This parameter can be set to ENABLE or DISABLE. */ uint32_t ExternalTrigInjecConvEdge; /*!< Select the external trigger edge and enable the trigger of an injected channels. This parameter can be a value of @ref ADCEx_External_trigger_edge_Injected */ uint32_t ExternalTrigInjecConv; /*!< Select the external event used to trigger the start of conversion of a injected channels. This parameter can be a value of @ref ADCEx_External_trigger_Source_Injected */ }ADC_InjectionConfTypeDef; /** * @brief ADC Configuration multi-mode structure definition */ typedef struct { uint32_t Mode; /*!< Configures the ADC to operate in independent or multi mode. This parameter can be a value of @ref ADCEx_Common_mode */ uint32_t DMAAccessMode; /*!< Configures the Direct memory access mode for multi ADC mode. This parameter can be a value of @ref ADCEx_Direct_memory_access_mode_for_multi_mode */ uint32_t TwoSamplingDelay; /*!< Configures the Delay between 2 sampling phases. This parameter can be a value of @ref ADC_delay_between_2_sampling_phases */ }ADC_MultiModeTypeDef; /** * @} */ /* Exported constants --------------------------------------------------------*/ /** @defgroup ADCEx_Exported_Constants ADC Exported Constants * @{ */ /** @defgroup ADCEx_Common_mode ADC Common Mode * @{ */ #define ADC_MODE_INDEPENDENT ((uint32_t)0x00000000) #define ADC_DUALMODE_REGSIMULT_INJECSIMULT ((uint32_t)ADC_CCR_MULTI_0) #define ADC_DUALMODE_REGSIMULT_ALTERTRIG ((uint32_t)ADC_CCR_MULTI_1) #define ADC_DUALMODE_INJECSIMULT ((uint32_t)(ADC_CCR_MULTI_2 | ADC_CCR_MULTI_0)) #define ADC_DUALMODE_REGSIMULT ((uint32_t)(ADC_CCR_MULTI_2 | ADC_CCR_MULTI_1)) #define ADC_DUALMODE_INTERL ((uint32_t)(ADC_CCR_MULTI_2 | ADC_CCR_MULTI_1 | ADC_CCR_MULTI_0)) #define ADC_DUALMODE_ALTERTRIG ((uint32_t)(ADC_CCR_MULTI_3 | ADC_CCR_MULTI_0)) #define ADC_TRIPLEMODE_REGSIMULT_INJECSIMULT ((uint32_t)(ADC_CCR_MULTI_4 | ADC_CCR_MULTI_0)) #define ADC_TRIPLEMODE_REGSIMULT_AlterTrig ((uint32_t)(ADC_CCR_MULTI_4 | ADC_CCR_MULTI_1)) #define ADC_TRIPLEMODE_INJECSIMULT ((uint32_t)(ADC_CCR_MULTI_4 | ADC_CCR_MULTI_2 | ADC_CCR_MULTI_0)) #define ADC_TRIPLEMODE_REGSIMULT ((uint32_t)(ADC_CCR_MULTI_4 | ADC_CCR_MULTI_2 | ADC_CCR_MULTI_1)) #define ADC_TRIPLEMODE_INTERL ((uint32_t)(ADC_CCR_MULTI_4 | ADC_CCR_MULTI_2 | ADC_CCR_MULTI_1 | ADC_CCR_MULTI_0)) #define ADC_TRIPLEMODE_ALTERTRIG ((uint32_t)(ADC_CCR_MULTI_4 | ADC_CCR_MULTI_3 | ADC_CCR_MULTI_0)) /** * @} */ /** @defgroup ADCEx_Direct_memory_access_mode_for_multi_mode ADC Direct Memory Access Mode For Multi Mode * @{ */ #define ADC_DMAACCESSMODE_DISABLED ((uint32_t)0x00000000) /*!< DMA mode disabled */ #define ADC_DMAACCESSMODE_1 ((uint32_t)ADC_CCR_DMA_0) /*!< DMA mode 1 enabled (2 / 3 half-words one by one - 1 then 2 then 3)*/ #define ADC_DMAACCESSMODE_2 ((uint32_t)ADC_CCR_DMA_1) /*!< DMA mode 2 enabled (2 / 3 half-words by pairs - 2&1 then 1&3 then 3&2)*/ #define ADC_DMAACCESSMODE_3 ((uint32_t)ADC_CCR_DMA) /*!< DMA mode 3 enabled (2 / 3 bytes by pairs - 2&1 then 1&3 then 3&2) */ /** * @} */ /** @defgroup ADCEx_External_trigger_edge_Injected ADC External Trigger Edge Injected * @{ */ #define ADC_EXTERNALTRIGINJECCONVEDGE_NONE ((uint32_t)0x00000000) #define ADC_EXTERNALTRIGINJECCONVEDGE_RISING ((uint32_t)ADC_CR2_JEXTEN_0) #define ADC_EXTERNALTRIGINJECCONVEDGE_FALLING ((uint32_t)ADC_CR2_JEXTEN_1) #define ADC_EXTERNALTRIGINJECCONVEDGE_RISINGFALLING ((uint32_t)ADC_CR2_JEXTEN) /** * @} */ /** @defgroup ADCEx_External_trigger_Source_Injected ADC External Trigger Source Injected * @{ */ #define ADC_EXTERNALTRIGINJECCONV_T1_CC4 ((uint32_t)0x00000000) #define ADC_EXTERNALTRIGINJECCONV_T1_TRGO ((uint32_t)ADC_CR2_JEXTSEL_0) #define ADC_EXTERNALTRIGINJECCONV_T2_CC1 ((uint32_t)ADC_CR2_JEXTSEL_1) #define ADC_EXTERNALTRIGINJECCONV_T2_TRGO ((uint32_t)(ADC_CR2_JEXTSEL_1 | ADC_CR2_JEXTSEL_0)) #define ADC_EXTERNALTRIGINJECCONV_T3_CC2 ((uint32_t)ADC_CR2_JEXTSEL_2) #define ADC_EXTERNALTRIGINJECCONV_T3_CC4 ((uint32_t)(ADC_CR2_JEXTSEL_2 | ADC_CR2_JEXTSEL_0)) #define ADC_EXTERNALTRIGINJECCONV_T4_CC1 ((uint32_t)(ADC_CR2_JEXTSEL_2 | ADC_CR2_JEXTSEL_1)) #define ADC_EXTERNALTRIGINJECCONV_T4_CC2 ((uint32_t)(ADC_CR2_JEXTSEL_2 | ADC_CR2_JEXTSEL_1 | ADC_CR2_JEXTSEL_0)) #define ADC_EXTERNALTRIGINJECCONV_T4_CC3 ((uint32_t)ADC_CR2_JEXTSEL_3) #define ADC_EXTERNALTRIGINJECCONV_T4_TRGO ((uint32_t)(ADC_CR2_JEXTSEL_3 | ADC_CR2_JEXTSEL_0)) #define ADC_EXTERNALTRIGINJECCONV_T5_CC4 ((uint32_t)(ADC_CR2_JEXTSEL_3 | ADC_CR2_JEXTSEL_1)) #define ADC_EXTERNALTRIGINJECCONV_T5_TRGO ((uint32_t)(ADC_CR2_JEXTSEL_3 | ADC_CR2_JEXTSEL_1 | ADC_CR2_JEXTSEL_0)) #define ADC_EXTERNALTRIGINJECCONV_T8_CC2 ((uint32_t)(ADC_CR2_JEXTSEL_3 | ADC_CR2_JEXTSEL_2)) #define ADC_EXTERNALTRIGINJECCONV_T8_CC3 ((uint32_t)(ADC_CR2_JEXTSEL_3 | ADC_CR2_JEXTSEL_2 | ADC_CR2_JEXTSEL_0)) #define ADC_EXTERNALTRIGINJECCONV_T8_CC4 ((uint32_t)(ADC_CR2_JEXTSEL_3 | ADC_CR2_JEXTSEL_2 | ADC_CR2_JEXTSEL_1)) #define ADC_EXTERNALTRIGINJECCONV_EXT_IT15 ((uint32_t)ADC_CR2_JEXTSEL) #define ADC_INJECTED_SOFTWARE_START ((uint32_t)ADC_CR2_JEXTSEL + 1) /** * @} */ /** @defgroup ADCEx_injected_channel_selection ADC Injected Channel Selection * @{ */ #define ADC_INJECTED_RANK_1 ((uint32_t)0x00000001) #define ADC_INJECTED_RANK_2 ((uint32_t)0x00000002) #define ADC_INJECTED_RANK_3 ((uint32_t)0x00000003) #define ADC_INJECTED_RANK_4 ((uint32_t)0x00000004) /** * @} */ /** @defgroup ADCEx_channels ADC Specific Channels * @{ */ #if defined(STM32F405xx) || defined(STM32F415xx) || defined(STM32F407xx) || defined(STM32F417xx) || \ defined(STM32F401xC) || defined(STM32F401xE) || defined(STM32F410Tx) || defined(STM32F410Cx) || \ defined(STM32F410Rx) || defined(STM32F412xG) #define ADC_CHANNEL_TEMPSENSOR ((uint32_t)ADC_CHANNEL_16) #endif /* STM32F405xx || STM32F415xx || STM32F407xx || STM32F417xx || STM32F401xC || STM32F401xE || STM32F410xx || STM32F412xG */ #if defined(STM32F411xE) || defined(STM32F427xx) || defined(STM32F437xx) || defined(STM32F429xx) || defined(STM32F439xx) || \ defined(STM32F446xx) || defined(STM32F469xx) || defined(STM32F479xx) #define ADC_CHANNEL_DIFFERENCIATION_TEMPSENSOR_VBAT ((uint32_t)0x10000000) /* Dummy bit for driver internal usage, not used in ADC channel setting registers CR1 or SQRx */ #define ADC_CHANNEL_TEMPSENSOR ((uint32_t)ADC_CHANNEL_18 | ADC_CHANNEL_DIFFERENCIATION_TEMPSENSOR_VBAT) #endif /* STM32F411xE || STM32F427xx || STM32F437xx || STM32F429xx || STM32F439xx || STM32F446xx || STM32F469xx || STM32F479xx */ /** * @} */ /** * @} */ /* Exported macro ------------------------------------------------------------*/ /** @defgroup ADC_Exported_Macros ADC Exported Macros * @{ */ /** * @} */ /* Exported functions --------------------------------------------------------*/ /** @addtogroup ADCEx_Exported_Functions * @{ */ /** @addtogroup ADCEx_Exported_Functions_Group1 * @{ */ /* I/O operation functions ******************************************************/ HAL_StatusTypeDef HAL_ADCEx_InjectedStart(ADC_HandleTypeDef* hadc); HAL_StatusTypeDef HAL_ADCEx_InjectedStop(ADC_HandleTypeDef* hadc); HAL_StatusTypeDef HAL_ADCEx_InjectedPollForConversion(ADC_HandleTypeDef* hadc, uint32_t Timeout); HAL_StatusTypeDef HAL_ADCEx_InjectedStart_IT(ADC_HandleTypeDef* hadc); HAL_StatusTypeDef HAL_ADCEx_InjectedStop_IT(ADC_HandleTypeDef* hadc); uint32_t HAL_ADCEx_InjectedGetValue(ADC_HandleTypeDef* hadc, uint32_t InjectedRank); HAL_StatusTypeDef HAL_ADCEx_MultiModeStart_DMA(ADC_HandleTypeDef* hadc, uint32_t* pData, uint32_t Length); HAL_StatusTypeDef HAL_ADCEx_MultiModeStop_DMA(ADC_HandleTypeDef* hadc); uint32_t HAL_ADCEx_MultiModeGetValue(ADC_HandleTypeDef* hadc); void HAL_ADCEx_InjectedConvCpltCallback(ADC_HandleTypeDef* hadc); /* Peripheral Control functions *************************************************/ HAL_StatusTypeDef HAL_ADCEx_InjectedConfigChannel(ADC_HandleTypeDef* hadc,ADC_InjectionConfTypeDef* sConfigInjected); HAL_StatusTypeDef HAL_ADCEx_MultiModeConfigChannel(ADC_HandleTypeDef* hadc, ADC_MultiModeTypeDef* multimode); /** * @} */ /** * @} */ /* Private types -------------------------------------------------------------*/ /* Private variables ---------------------------------------------------------*/ /* Private constants ---------------------------------------------------------*/ /** @defgroup ADCEx_Private_Constants ADC Private Constants * @{ */ /** * @} */ /* Private macros ------------------------------------------------------------*/ /** @defgroup ADCEx_Private_Macros ADC Private Macros * @{ */ #if defined(STM32F405xx) || defined(STM32F415xx) || defined(STM32F407xx) || defined(STM32F417xx) || \ defined(STM32F401xC) || defined(STM32F401xE) || defined(STM32F410Tx) || defined(STM32F410Cx) || \ defined(STM32F410Rx) || defined(STM32F411xE) || defined(STM32F412xG) #define IS_ADC_CHANNEL(CHANNEL) ((CHANNEL) <= ADC_CHANNEL_18) #endif /* STM32F405xx || STM32F415xx || STM32F407xx || STM32F417xx || STM32F401xC || STM32F401xE || STM32F410xx || STM32F411xE || STM32F412xG */ #if defined(STM32F427xx) || defined(STM32F437xx) || defined(STM32F429xx) || defined(STM32F439xx) || \ defined(STM32F446xx) || defined(STM32F469xx) || defined(STM32F479xx) #define IS_ADC_CHANNEL(CHANNEL) (((CHANNEL) <= ADC_CHANNEL_18) || \ ((CHANNEL) == ADC_CHANNEL_TEMPSENSOR)) #endif /* STM32F427xx || STM32F437xx || STM32F429xx || STM32F439xx || STM32F446xx || STM32F469xx || STM32F479xx */ #define IS_ADC_MODE(MODE) (((MODE) == ADC_MODE_INDEPENDENT) || \ ((MODE) == ADC_DUALMODE_REGSIMULT_INJECSIMULT) || \ ((MODE) == ADC_DUALMODE_REGSIMULT_ALTERTRIG) || \ ((MODE) == ADC_DUALMODE_INJECSIMULT) || \ ((MODE) == ADC_DUALMODE_REGSIMULT) || \ ((MODE) == ADC_DUALMODE_INTERL) || \ ((MODE) == ADC_DUALMODE_ALTERTRIG) || \ ((MODE) == ADC_TRIPLEMODE_REGSIMULT_INJECSIMULT) || \ ((MODE) == ADC_TRIPLEMODE_REGSIMULT_AlterTrig) || \ ((MODE) == ADC_TRIPLEMODE_INJECSIMULT) || \ ((MODE) == ADC_TRIPLEMODE_REGSIMULT) || \ ((MODE) == ADC_TRIPLEMODE_INTERL) || \ ((MODE) == ADC_TRIPLEMODE_ALTERTRIG)) #define IS_ADC_DMA_ACCESS_MODE(MODE) (((MODE) == ADC_DMAACCESSMODE_DISABLED) || \ ((MODE) == ADC_DMAACCESSMODE_1) || \ ((MODE) == ADC_DMAACCESSMODE_2) || \ ((MODE) == ADC_DMAACCESSMODE_3)) #define IS_ADC_EXT_INJEC_TRIG_EDGE(EDGE) (((EDGE) == ADC_EXTERNALTRIGINJECCONVEDGE_NONE) || \ ((EDGE) == ADC_EXTERNALTRIGINJECCONVEDGE_RISING) || \ ((EDGE) == ADC_EXTERNALTRIGINJECCONVEDGE_FALLING) || \ ((EDGE) == ADC_EXTERNALTRIGINJECCONVEDGE_RISINGFALLING)) #define IS_ADC_EXT_INJEC_TRIG(INJTRIG) (((INJTRIG) == ADC_EXTERNALTRIGINJECCONV_T1_CC4) || \ ((INJTRIG) == ADC_EXTERNALTRIGINJECCONV_T1_TRGO) || \ ((INJTRIG) == ADC_EXTERNALTRIGINJECCONV_T2_CC1) || \ ((INJTRIG) == ADC_EXTERNALTRIGINJECCONV_T2_TRGO) || \ ((INJTRIG) == ADC_EXTERNALTRIGINJECCONV_T3_CC2) || \ ((INJTRIG) == ADC_EXTERNALTRIGINJECCONV_T3_CC4) || \ ((INJTRIG) == ADC_EXTERNALTRIGINJECCONV_T4_CC1) || \ ((INJTRIG) == ADC_EXTERNALTRIGINJECCONV_T4_CC2) || \ ((INJTRIG) == ADC_EXTERNALTRIGINJECCONV_T4_CC3) || \ ((INJTRIG) == ADC_EXTERNALTRIGINJECCONV_T4_TRGO) || \ ((INJTRIG) == ADC_EXTERNALTRIGINJECCONV_T5_CC4) || \ ((INJTRIG) == ADC_EXTERNALTRIGINJECCONV_T5_TRGO) || \ ((INJTRIG) == ADC_EXTERNALTRIGINJECCONV_T8_CC2) || \ ((INJTRIG) == ADC_EXTERNALTRIGINJECCONV_T8_CC3) || \ ((INJTRIG) == ADC_EXTERNALTRIGINJECCONV_T8_CC4) || \ ((INJTRIG) == ADC_EXTERNALTRIGINJECCONV_EXT_IT15)|| \ ((INJTRIG) == ADC_INJECTED_SOFTWARE_START)) #define IS_ADC_INJECTED_LENGTH(LENGTH) (((LENGTH) >= ((uint32_t)1)) && ((LENGTH) <= ((uint32_t)4))) #define IS_ADC_INJECTED_RANK(RANK) (((RANK) >= ((uint32_t)1)) && ((RANK) <= ((uint32_t)4))) /** * @brief Set the selected injected Channel rank. * @param _CHANNELNB_: Channel number. * @param _RANKNB_: Rank number. * @param _JSQR_JL_: Sequence length. * @retval None */ #define ADC_JSQR(_CHANNELNB_, _RANKNB_, _JSQR_JL_) (((uint32_t)((uint16_t)(_CHANNELNB_))) << (5 * (uint8_t)(((_RANKNB_) + 3) - (_JSQR_JL_)))) /** * @} */ /* Private functions ---------------------------------------------------------*/ /** @defgroup ADCEx_Private_Functions ADC Private Functions * @{ */ /** * @} */ /** * @} */ /** * @} */ #ifdef __cplusplus } #endif #endif /*__STM32F4xx_ADC_EX_H */ /************************ (C) COPYRIGHT STMicroelectronics *****END OF FILE****/ ================================================ FILE: Zelig/mbed/TARGET_NUCLEO_F401RE/stm32f4xx_hal_can.h ================================================ /** ****************************************************************************** * @file stm32f4xx_hal_can.h * @author MCD Application Team * @version V1.4.1 * @date 09-October-2015 * @brief Header file of CAN HAL module. ****************************************************************************** * @attention * *

© COPYRIGHT(c) 2015 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. * ****************************************************************************** */ /* Define to prevent recursive inclusion -------------------------------------*/ #ifndef __STM32F4xx_HAL_CAN_H #define __STM32F4xx_HAL_CAN_H #ifdef __cplusplus extern "C" { #endif #if defined(STM32F405xx) || defined(STM32F415xx) || defined(STM32F407xx) || defined(STM32F417xx) ||\ defined(STM32F427xx) || defined(STM32F437xx) || defined(STM32F429xx) || defined(STM32F439xx) ||\ defined(STM32F446xx) || defined(STM32F469xx) || defined(STM32F479xx) /* Includes ------------------------------------------------------------------*/ #include "stm32f4xx_hal_def.h" /** @addtogroup STM32F4xx_HAL_Driver * @{ */ /** @addtogroup CAN * @{ */ /* Exported types ------------------------------------------------------------*/ /** @defgroup CAN_Exported_Types CAN Exported Types * @{ */ /** * @brief HAL State structures definition */ typedef enum { HAL_CAN_STATE_RESET = 0x00, /*!< CAN not yet initialized or disabled */ HAL_CAN_STATE_READY = 0x01, /*!< CAN initialized and ready for use */ HAL_CAN_STATE_BUSY = 0x02, /*!< CAN process is ongoing */ HAL_CAN_STATE_BUSY_TX = 0x12, /*!< CAN process is ongoing */ HAL_CAN_STATE_BUSY_RX = 0x22, /*!< CAN process is ongoing */ HAL_CAN_STATE_BUSY_TX_RX = 0x32, /*!< CAN process is ongoing */ HAL_CAN_STATE_TIMEOUT = 0x03, /*!< Timeout state */ HAL_CAN_STATE_ERROR = 0x04 /*!< CAN error state */ }HAL_CAN_StateTypeDef; /** * @brief CAN init structure definition */ typedef struct { uint32_t Prescaler; /*!< Specifies the length of a time quantum. This parameter must be a number between Min_Data = 1 and Max_Data = 1024 */ uint32_t Mode; /*!< Specifies the CAN operating mode. This parameter can be a value of @ref CAN_operating_mode */ uint32_t SJW; /*!< Specifies the maximum number of time quanta the CAN hardware is allowed to lengthen or shorten a bit to perform resynchronization. This parameter can be a value of @ref CAN_synchronisation_jump_width */ uint32_t BS1; /*!< Specifies the number of time quanta in Bit Segment 1. This parameter can be a value of @ref CAN_time_quantum_in_bit_segment_1 */ uint32_t BS2; /*!< Specifies the number of time quanta in Bit Segment 2. This parameter can be a value of @ref CAN_time_quantum_in_bit_segment_2 */ uint32_t TTCM; /*!< Enable or disable the time triggered communication mode. This parameter can be set to ENABLE or DISABLE. */ uint32_t ABOM; /*!< Enable or disable the automatic bus-off management. This parameter can be set to ENABLE or DISABLE */ uint32_t AWUM; /*!< Enable or disable the automatic wake-up mode. This parameter can be set to ENABLE or DISABLE */ uint32_t NART; /*!< Enable or disable the non-automatic retransmission mode. This parameter can be set to ENABLE or DISABLE */ uint32_t RFLM; /*!< Enable or disable the receive FIFO Locked mode. This parameter can be set to ENABLE or DISABLE */ uint32_t TXFP; /*!< Enable or disable the transmit FIFO priority. This parameter can be set to ENABLE or DISABLE */ }CAN_InitTypeDef; /** * @brief CAN filter configuration structure definition */ typedef struct { uint32_t FilterIdHigh; /*!< Specifies the filter identification number (MSBs for a 32-bit configuration, first one for a 16-bit configuration). This parameter must be a number between Min_Data = 0x0000 and Max_Data = 0xFFFF */ uint32_t FilterIdLow; /*!< Specifies the filter identification number (LSBs for a 32-bit configuration, second one for a 16-bit configuration). This parameter must be a number between Min_Data = 0x0000 and Max_Data = 0xFFFF */ uint32_t FilterMaskIdHigh; /*!< Specifies the filter mask number or identification number, according to the mode (MSBs for a 32-bit configuration, first one for a 16-bit configuration). This parameter must be a number between Min_Data = 0x0000 and Max_Data = 0xFFFF */ uint32_t FilterMaskIdLow; /*!< Specifies the filter mask number or identification number, according to the mode (LSBs for a 32-bit configuration, second one for a 16-bit configuration). This parameter must be a number between Min_Data = 0x0000 and Max_Data = 0xFFFF */ uint32_t FilterFIFOAssignment; /*!< Specifies the FIFO (0 or 1) which will be assigned to the filter. This parameter can be a value of @ref CAN_filter_FIFO */ uint32_t FilterNumber; /*!< Specifies the filter which will be initialized. This parameter must be a number between Min_Data = 0 and Max_Data = 27 */ uint32_t FilterMode; /*!< Specifies the filter mode to be initialized. This parameter can be a value of @ref CAN_filter_mode */ uint32_t FilterScale; /*!< Specifies the filter scale. This parameter can be a value of @ref CAN_filter_scale */ uint32_t FilterActivation; /*!< Enable or disable the filter. This parameter can be set to ENABLE or DISABLE. */ uint32_t BankNumber; /*!< Select the start slave bank filter. This parameter must be a number between Min_Data = 0 and Max_Data = 28 */ }CAN_FilterConfTypeDef; /** * @brief CAN Tx message structure definition */ typedef struct { uint32_t StdId; /*!< Specifies the standard identifier. This parameter must be a number between Min_Data = 0 and Max_Data = 0x7FF */ uint32_t ExtId; /*!< Specifies the extended identifier. This parameter must be a number between Min_Data = 0 and Max_Data = 0x1FFFFFFF */ uint32_t IDE; /*!< Specifies the type of identifier for the message that will be transmitted. This parameter can be a value of @ref CAN_Identifier_Type */ uint32_t RTR; /*!< Specifies the type of frame for the message that will be transmitted. This parameter can be a value of @ref CAN_remote_transmission_request */ uint32_t DLC; /*!< Specifies the length of the frame that will be transmitted. This parameter must be a number between Min_Data = 0 and Max_Data = 8 */ uint8_t Data[8]; /*!< Contains the data to be transmitted. This parameter must be a number between Min_Data = 0 and Max_Data = 0xFF */ }CanTxMsgTypeDef; /** * @brief CAN Rx message structure definition */ typedef struct { uint32_t StdId; /*!< Specifies the standard identifier. This parameter must be a number between Min_Data = 0 and Max_Data = 0x7FF */ uint32_t ExtId; /*!< Specifies the extended identifier. This parameter must be a number between Min_Data = 0 and Max_Data = 0x1FFFFFFF */ uint32_t IDE; /*!< Specifies the type of identifier for the message that will be received. This parameter can be a value of @ref CAN_Identifier_Type */ uint32_t RTR; /*!< Specifies the type of frame for the received message. This parameter can be a value of @ref CAN_remote_transmission_request */ uint32_t DLC; /*!< Specifies the length of the frame that will be received. This parameter must be a number between Min_Data = 0 and Max_Data = 8 */ uint8_t Data[8]; /*!< Contains the data to be received. This parameter must be a number between Min_Data = 0 and Max_Data = 0xFF */ uint32_t FMI; /*!< Specifies the index of the filter the message stored in the mailbox passes through. This parameter must be a number between Min_Data = 0 and Max_Data = 0xFF */ uint32_t FIFONumber; /*!< Specifies the receive FIFO number. This parameter can be CAN_FIFO0 or CAN_FIFO1 */ }CanRxMsgTypeDef; /** * @brief CAN handle Structure definition */ typedef struct { CAN_TypeDef *Instance; /*!< Register base address */ CAN_InitTypeDef Init; /*!< CAN required parameters */ CanTxMsgTypeDef* pTxMsg; /*!< Pointer to transmit structure */ CanRxMsgTypeDef* pRxMsg; /*!< Pointer to reception structure */ __IO HAL_CAN_StateTypeDef State; /*!< CAN communication state */ HAL_LockTypeDef Lock; /*!< CAN locking object */ __IO uint32_t ErrorCode; /*!< CAN Error code */ }CAN_HandleTypeDef; /** * @} */ /* Exported constants --------------------------------------------------------*/ /** @defgroup CAN_Exported_Constants CAN Exported Constants * @{ */ /** @defgroup HAL_CAN_Error_Code HAL CAN Error Code * @{ */ #define HAL_CAN_ERROR_NONE 0x00 /*!< No error */ #define HAL_CAN_ERROR_EWG 0x01 /*!< EWG error */ #define HAL_CAN_ERROR_EPV 0x02 /*!< EPV error */ #define HAL_CAN_ERROR_BOF 0x04 /*!< BOF error */ #define HAL_CAN_ERROR_STF 0x08 /*!< Stuff error */ #define HAL_CAN_ERROR_FOR 0x10 /*!< Form error */ #define HAL_CAN_ERROR_ACK 0x20 /*!< Acknowledgment error */ #define HAL_CAN_ERROR_BR 0x40 /*!< Bit recessive */ #define HAL_CAN_ERROR_BD 0x80 /*!< LEC dominant */ #define HAL_CAN_ERROR_CRC 0x100 /*!< LEC transfer error */ /** * @} */ /** @defgroup CAN_InitStatus CAN InitStatus * @{ */ #define CAN_INITSTATUS_FAILED ((uint8_t)0x00) /*!< CAN initialization failed */ #define CAN_INITSTATUS_SUCCESS ((uint8_t)0x01) /*!< CAN initialization OK */ /** * @} */ /** @defgroup CAN_operating_mode CAN Operating Mode * @{ */ #define CAN_MODE_NORMAL ((uint32_t)0x00000000) /*!< Normal mode */ #define CAN_MODE_LOOPBACK ((uint32_t)CAN_BTR_LBKM) /*!< Loopback mode */ #define CAN_MODE_SILENT ((uint32_t)CAN_BTR_SILM) /*!< Silent mode */ #define CAN_MODE_SILENT_LOOPBACK ((uint32_t)(CAN_BTR_LBKM | CAN_BTR_SILM)) /*!< Loopback combined with silent mode */ /** * @} */ /** @defgroup CAN_synchronisation_jump_width CAN Synchronisation Jump Width * @{ */ #define CAN_SJW_1TQ ((uint32_t)0x00000000) /*!< 1 time quantum */ #define CAN_SJW_2TQ ((uint32_t)CAN_BTR_SJW_0) /*!< 2 time quantum */ #define CAN_SJW_3TQ ((uint32_t)CAN_BTR_SJW_1) /*!< 3 time quantum */ #define CAN_SJW_4TQ ((uint32_t)CAN_BTR_SJW) /*!< 4 time quantum */ /** * @} */ /** @defgroup CAN_time_quantum_in_bit_segment_1 CAN Time Quantum in bit segment 1 * @{ */ #define CAN_BS1_1TQ ((uint32_t)0x00000000) /*!< 1 time quantum */ #define CAN_BS1_2TQ ((uint32_t)CAN_BTR_TS1_0) /*!< 2 time quantum */ #define CAN_BS1_3TQ ((uint32_t)CAN_BTR_TS1_1) /*!< 3 time quantum */ #define CAN_BS1_4TQ ((uint32_t)(CAN_BTR_TS1_1 | CAN_BTR_TS1_0)) /*!< 4 time quantum */ #define CAN_BS1_5TQ ((uint32_t)CAN_BTR_TS1_2) /*!< 5 time quantum */ #define CAN_BS1_6TQ ((uint32_t)(CAN_BTR_TS1_2 | CAN_BTR_TS1_0)) /*!< 6 time quantum */ #define CAN_BS1_7TQ ((uint32_t)(CAN_BTR_TS1_2 | CAN_BTR_TS1_1)) /*!< 7 time quantum */ #define CAN_BS1_8TQ ((uint32_t)(CAN_BTR_TS1_2 | CAN_BTR_TS1_1 | CAN_BTR_TS1_0)) /*!< 8 time quantum */ #define CAN_BS1_9TQ ((uint32_t)CAN_BTR_TS1_3) /*!< 9 time quantum */ #define CAN_BS1_10TQ ((uint32_t)(CAN_BTR_TS1_3 | CAN_BTR_TS1_0)) /*!< 10 time quantum */ #define CAN_BS1_11TQ ((uint32_t)(CAN_BTR_TS1_3 | CAN_BTR_TS1_1)) /*!< 11 time quantum */ #define CAN_BS1_12TQ ((uint32_t)(CAN_BTR_TS1_3 | CAN_BTR_TS1_1 | CAN_BTR_TS1_0)) /*!< 12 time quantum */ #define CAN_BS1_13TQ ((uint32_t)(CAN_BTR_TS1_3 | CAN_BTR_TS1_2)) /*!< 13 time quantum */ #define CAN_BS1_14TQ ((uint32_t)(CAN_BTR_TS1_3 | CAN_BTR_TS1_2 | CAN_BTR_TS1_0)) /*!< 14 time quantum */ #define CAN_BS1_15TQ ((uint32_t)(CAN_BTR_TS1_3 | CAN_BTR_TS1_2 | CAN_BTR_TS1_1)) /*!< 15 time quantum */ #define CAN_BS1_16TQ ((uint32_t)CAN_BTR_TS1) /*!< 16 time quantum */ /** * @} */ /** @defgroup CAN_time_quantum_in_bit_segment_2 CAN Time Quantum in bit segment 2 * @{ */ #define CAN_BS2_1TQ ((uint32_t)0x00000000) /*!< 1 time quantum */ #define CAN_BS2_2TQ ((uint32_t)CAN_BTR_TS2_0) /*!< 2 time quantum */ #define CAN_BS2_3TQ ((uint32_t)CAN_BTR_TS2_1) /*!< 3 time quantum */ #define CAN_BS2_4TQ ((uint32_t)(CAN_BTR_TS2_1 | CAN_BTR_TS2_0)) /*!< 4 time quantum */ #define CAN_BS2_5TQ ((uint32_t)CAN_BTR_TS2_2) /*!< 5 time quantum */ #define CAN_BS2_6TQ ((uint32_t)(CAN_BTR_TS2_2 | CAN_BTR_TS2_0)) /*!< 6 time quantum */ #define CAN_BS2_7TQ ((uint32_t)(CAN_BTR_TS2_2 | CAN_BTR_TS2_1)) /*!< 7 time quantum */ #define CAN_BS2_8TQ ((uint32_t)CAN_BTR_TS2) /*!< 8 time quantum */ /** * @} */ /** @defgroup CAN_filter_mode CAN Filter Mode * @{ */ #define CAN_FILTERMODE_IDMASK ((uint8_t)0x00) /*!< Identifier mask mode */ #define CAN_FILTERMODE_IDLIST ((uint8_t)0x01) /*!< Identifier list mode */ /** * @} */ /** @defgroup CAN_filter_scale CAN Filter Scale * @{ */ #define CAN_FILTERSCALE_16BIT ((uint8_t)0x00) /*!< Two 16-bit filters */ #define CAN_FILTERSCALE_32BIT ((uint8_t)0x01) /*!< One 32-bit filter */ /** * @} */ /** @defgroup CAN_filter_FIFO CAN Filter FIFO * @{ */ #define CAN_FILTER_FIFO0 ((uint8_t)0x00) /*!< Filter FIFO 0 assignment for filter x */ #define CAN_FILTER_FIFO1 ((uint8_t)0x01) /*!< Filter FIFO 1 assignment for filter x */ /** * @} */ /** @defgroup CAN_Identifier_Type CAN Identifier Type * @{ */ #define CAN_ID_STD ((uint32_t)0x00000000) /*!< Standard Id */ #define CAN_ID_EXT ((uint32_t)0x00000004) /*!< Extended Id */ /** * @} */ /** @defgroup CAN_remote_transmission_request CAN Remote Transmission Request * @{ */ #define CAN_RTR_DATA ((uint32_t)0x00000000) /*!< Data frame */ #define CAN_RTR_REMOTE ((uint32_t)0x00000002) /*!< Remote frame */ /** * @} */ /** @defgroup CAN_receive_FIFO_number_constants CAN Receive FIFO Number Constants * @{ */ #define CAN_FIFO0 ((uint8_t)0x00) /*!< CAN FIFO 0 used to receive */ #define CAN_FIFO1 ((uint8_t)0x01) /*!< CAN FIFO 1 used to receive */ /** * @} */ /** @defgroup CAN_flags CAN Flags * @{ */ /* If the flag is 0x3XXXXXXX, it means that it can be used with CAN_GetFlagStatus() and CAN_ClearFlag() functions. */ /* If the flag is 0x1XXXXXXX, it means that it can only be used with CAN_GetFlagStatus() function. */ /* Transmit Flags */ #define CAN_FLAG_RQCP0 ((uint32_t)0x00000500) /*!< Request MailBox0 flag */ #define CAN_FLAG_RQCP1 ((uint32_t)0x00000508) /*!< Request MailBox1 flag */ #define CAN_FLAG_RQCP2 ((uint32_t)0x00000510) /*!< Request MailBox2 flag */ #define CAN_FLAG_TXOK0 ((uint32_t)0x00000501) /*!< Transmission OK MailBox0 flag */ #define CAN_FLAG_TXOK1 ((uint32_t)0x00000509) /*!< Transmission OK MailBox1 flag */ #define CAN_FLAG_TXOK2 ((uint32_t)0x00000511) /*!< Transmission OK MailBox2 flag */ #define CAN_FLAG_TME0 ((uint32_t)0x0000051A) /*!< Transmit mailbox 0 empty flag */ #define CAN_FLAG_TME1 ((uint32_t)0x0000051B) /*!< Transmit mailbox 0 empty flag */ #define CAN_FLAG_TME2 ((uint32_t)0x0000051C) /*!< Transmit mailbox 0 empty flag */ /* Receive Flags */ #define CAN_FLAG_FF0 ((uint32_t)0x00000203) /*!< FIFO 0 Full flag */ #define CAN_FLAG_FOV0 ((uint32_t)0x00000204) /*!< FIFO 0 Overrun flag */ #define CAN_FLAG_FF1 ((uint32_t)0x00000403) /*!< FIFO 1 Full flag */ #define CAN_FLAG_FOV1 ((uint32_t)0x00000404) /*!< FIFO 1 Overrun flag */ /* Operating Mode Flags */ #define CAN_FLAG_WKU ((uint32_t)0x00000103) /*!< Wake up flag */ #define CAN_FLAG_SLAK ((uint32_t)0x00000101) /*!< Sleep acknowledge flag */ #define CAN_FLAG_SLAKI ((uint32_t)0x00000104) /*!< Sleep acknowledge flag */ /* @note When SLAK interrupt is disabled (SLKIE=0), no polling on SLAKI is possible. In this case the SLAK bit can be polled.*/ /* Error Flags */ #define CAN_FLAG_EWG ((uint32_t)0x00000300) /*!< Error warning flag */ #define CAN_FLAG_EPV ((uint32_t)0x00000301) /*!< Error passive flag */ #define CAN_FLAG_BOF ((uint32_t)0x00000302) /*!< Bus-Off flag */ /** * @} */ /** @defgroup CAN_Interrupts CAN Interrupts * @{ */ #define CAN_IT_TME ((uint32_t)CAN_IER_TMEIE) /*!< Transmit mailbox empty interrupt */ /* Receive Interrupts */ #define CAN_IT_FMP0 ((uint32_t)CAN_IER_FMPIE0) /*!< FIFO 0 message pending interrupt */ #define CAN_IT_FF0 ((uint32_t)CAN_IER_FFIE0) /*!< FIFO 0 full interrupt */ #define CAN_IT_FOV0 ((uint32_t)CAN_IER_FOVIE0) /*!< FIFO 0 overrun interrupt */ #define CAN_IT_FMP1 ((uint32_t)CAN_IER_FMPIE1) /*!< FIFO 1 message pending interrupt */ #define CAN_IT_FF1 ((uint32_t)CAN_IER_FFIE1) /*!< FIFO 1 full interrupt */ #define CAN_IT_FOV1 ((uint32_t)CAN_IER_FOVIE1) /*!< FIFO 1 overrun interrupt */ /* Operating Mode Interrupts */ #define CAN_IT_WKU ((uint32_t)CAN_IER_WKUIE) /*!< Wake-up interrupt */ #define CAN_IT_SLK ((uint32_t)CAN_IER_SLKIE) /*!< Sleep acknowledge interrupt */ /* Error Interrupts */ #define CAN_IT_EWG ((uint32_t)CAN_IER_EWGIE) /*!< Error warning interrupt */ #define CAN_IT_EPV ((uint32_t)CAN_IER_EPVIE) /*!< Error passive interrupt */ #define CAN_IT_BOF ((uint32_t)CAN_IER_BOFIE) /*!< Bus-off interrupt */ #define CAN_IT_LEC ((uint32_t)CAN_IER_LECIE) /*!< Last error code interrupt */ #define CAN_IT_ERR ((uint32_t)CAN_IER_ERRIE) /*!< Error Interrupt */ /** * @} */ /** @defgroup CAN_Mailboxes_Definition CAN Mailboxes Definition * @{ */ #define CAN_TXMAILBOX_0 ((uint8_t)0x00) #define CAN_TXMAILBOX_1 ((uint8_t)0x01) #define CAN_TXMAILBOX_2 ((uint8_t)0x02) /** * @} */ /** * @} */ /* Exported macro ------------------------------------------------------------*/ /** @defgroup CAN_Exported_Macros CAN Exported Macros * @{ */ /** @brief Reset CAN handle state * @param __HANDLE__: specifies the CAN Handle. * @retval None */ #define __HAL_CAN_RESET_HANDLE_STATE(__HANDLE__) ((__HANDLE__)->State = HAL_CAN_STATE_RESET) /** * @brief Enable the specified CAN interrupts. * @param __HANDLE__: CAN handle * @param __INTERRUPT__: CAN Interrupt * @retval None */ #define __HAL_CAN_ENABLE_IT(__HANDLE__, __INTERRUPT__) (((__HANDLE__)->Instance->IER) |= (__INTERRUPT__)) /** * @brief Disable the specified CAN interrupts. * @param __HANDLE__: CAN handle * @param __INTERRUPT__: CAN Interrupt * @retval None */ #define __HAL_CAN_DISABLE_IT(__HANDLE__, __INTERRUPT__) (((__HANDLE__)->Instance->IER) &= ~(__INTERRUPT__)) /** * @brief Return the number of pending received messages. * @param __HANDLE__: CAN handle * @param __FIFONUMBER__: Receive FIFO number, CAN_FIFO0 or CAN_FIFO1. * @retval The number of pending message. */ #define __HAL_CAN_MSG_PENDING(__HANDLE__, __FIFONUMBER__) (((__FIFONUMBER__) == CAN_FIFO0)? \ ((uint8_t)((__HANDLE__)->Instance->RF0R&(uint32_t)0x03)) : ((uint8_t)((__HANDLE__)->Instance->RF1R&(uint32_t)0x03))) /** @brief Check whether the specified CAN flag is set or not. * @param __HANDLE__: CAN Handle * @param __FLAG__: specifies the flag to check. * This parameter can be one of the following values: * @arg CAN_TSR_RQCP0: Request MailBox0 Flag * @arg CAN_TSR_RQCP1: Request MailBox1 Flag * @arg CAN_TSR_RQCP2: Request MailBox2 Flag * @arg CAN_FLAG_TXOK0: Transmission OK MailBox0 Flag * @arg CAN_FLAG_TXOK1: Transmission OK MailBox1 Flag * @arg CAN_FLAG_TXOK2: Transmission OK MailBox2 Flag * @arg CAN_FLAG_TME0: Transmit mailbox 0 empty Flag * @arg CAN_FLAG_TME1: Transmit mailbox 1 empty Flag * @arg CAN_FLAG_TME2: Transmit mailbox 2 empty Flag * @arg CAN_FLAG_FMP0: FIFO 0 Message Pending Flag * @arg CAN_FLAG_FF0: FIFO 0 Full Flag * @arg CAN_FLAG_FOV0: FIFO 0 Overrun Flag * @arg CAN_FLAG_FMP1: FIFO 1 Message Pending Flag * @arg CAN_FLAG_FF1: FIFO 1 Full Flag * @arg CAN_FLAG_FOV1: FIFO 1 Overrun Flag * @arg CAN_FLAG_WKU: Wake up Flag * @arg CAN_FLAG_SLAK: Sleep acknowledge Flag * @arg CAN_FLAG_SLAKI: Sleep acknowledge Flag * @arg CAN_FLAG_EWG: Error Warning Flag * @arg CAN_FLAG_EPV: Error Passive Flag * @arg CAN_FLAG_BOF: Bus-Off Flag * @retval The new state of __FLAG__ (TRUE or FALSE). */ #define __HAL_CAN_GET_FLAG(__HANDLE__, __FLAG__) \ ((((__FLAG__) >> 8) == 5)? ((((__HANDLE__)->Instance->TSR) & (1 << ((__FLAG__) & CAN_FLAG_MASK))) == (1 << ((__FLAG__) & CAN_FLAG_MASK))): \ (((__FLAG__) >> 8) == 2)? ((((__HANDLE__)->Instance->RF0R) & (1 << ((__FLAG__) & CAN_FLAG_MASK))) == (1 << ((__FLAG__) & CAN_FLAG_MASK))): \ (((__FLAG__) >> 8) == 4)? ((((__HANDLE__)->Instance->RF1R) & (1 << ((__FLAG__) & CAN_FLAG_MASK))) == (1 << ((__FLAG__) & CAN_FLAG_MASK))): \ (((__FLAG__) >> 8) == 1)? ((((__HANDLE__)->Instance->MSR) & (1 << ((__FLAG__) & CAN_FLAG_MASK))) == (1 << ((__FLAG__) & CAN_FLAG_MASK))): \ ((((__HANDLE__)->Instance->ESR) & (1 << ((__FLAG__) & CAN_FLAG_MASK))) == (1 << ((__FLAG__) & CAN_FLAG_MASK)))) /** @brief Clear the specified CAN pending flag. * @param __HANDLE__: CAN Handle. * @param __FLAG__: specifies the flag to check. * This parameter can be one of the following values: * @arg CAN_TSR_RQCP0: Request MailBox0 Flag * @arg CAN_TSR_RQCP1: Request MailBox1 Flag * @arg CAN_TSR_RQCP2: Request MailBox2 Flag * @arg CAN_FLAG_TXOK0: Transmission OK MailBox0 Flag * @arg CAN_FLAG_TXOK1: Transmission OK MailBox1 Flag * @arg CAN_FLAG_TXOK2: Transmission OK MailBox2 Flag * @arg CAN_FLAG_TME0: Transmit mailbox 0 empty Flag * @arg CAN_FLAG_TME1: Transmit mailbox 1 empty Flag * @arg CAN_FLAG_TME2: Transmit mailbox 2 empty Flag * @arg CAN_FLAG_FMP0: FIFO 0 Message Pending Flag * @arg CAN_FLAG_FF0: FIFO 0 Full Flag * @arg CAN_FLAG_FOV0: FIFO 0 Overrun Flag * @arg CAN_FLAG_FMP1: FIFO 1 Message Pending Flag * @arg CAN_FLAG_FF1: FIFO 1 Full Flag * @arg CAN_FLAG_FOV1: FIFO 1 Overrun Flag * @arg CAN_FLAG_WKU: Wake up Flag * @arg CAN_FLAG_SLAK: Sleep acknowledge Flag * @arg CAN_FLAG_SLAKI: Sleep acknowledge Flag * @arg CAN_FLAG_EWG: Error Warning Flag * @arg CAN_FLAG_EPV: Error Passive Flag * @arg CAN_FLAG_BOF: Bus-Off Flag * @retval The new state of __FLAG__ (TRUE or FALSE). */ #define __HAL_CAN_CLEAR_FLAG(__HANDLE__, __FLAG__) \ ((((__FLAG__) >> 8) == 5)? (((__HANDLE__)->Instance->TSR) = ~((uint32_t)1 << ((__FLAG__) & CAN_FLAG_MASK))): \ (((__FLAG__) >> 8) == 2)? (((__HANDLE__)->Instance->RF0R) = ~((uint32_t)1 << ((__FLAG__) & CAN_FLAG_MASK))): \ (((__FLAG__) >> 8) == 4)? (((__HANDLE__)->Instance->RF1R) = ~((uint32_t)1 << ((__FLAG__) & CAN_FLAG_MASK))): \ (((__FLAG__) >> 8) == 1)? (((__HANDLE__)->Instance->MSR) = ~((uint32_t)1 << ((__FLAG__) & CAN_FLAG_MASK))): \ (((__HANDLE__)->Instance->ESR) = ~((uint32_t)1 << ((__FLAG__) & CAN_FLAG_MASK)))) /** @brief Check if the specified CAN interrupt source is enabled or disabled. * @param __HANDLE__: CAN Handle * @param __INTERRUPT__: specifies the CAN interrupt source to check. * This parameter can be one of the following values: * @arg CAN_IT_TME: Transmit mailbox empty interrupt enable * @arg CAN_IT_FMP0: FIFO0 message pending interrupt enable * @arg CAN_IT_FMP1: FIFO1 message pending interrupt enable * @retval The new state of __IT__ (TRUE or FALSE). */ #define __HAL_CAN_GET_IT_SOURCE(__HANDLE__, __INTERRUPT__) ((((__HANDLE__)->Instance->IER & (__INTERRUPT__)) == (__INTERRUPT__)) ? SET : RESET) /** * @brief Check the transmission status of a CAN Frame. * @param __HANDLE__: CAN Handle * @param __TRANSMITMAILBOX__: the number of the mailbox that is used for transmission. * @retval The new status of transmission (TRUE or FALSE). */ #define __HAL_CAN_TRANSMIT_STATUS(__HANDLE__, __TRANSMITMAILBOX__)\ (((__TRANSMITMAILBOX__) == CAN_TXMAILBOX_0)? ((((__HANDLE__)->Instance->TSR) & (CAN_TSR_RQCP0 | CAN_TSR_TXOK0 | CAN_TSR_TME0)) == (CAN_TSR_RQCP0 | CAN_TSR_TXOK0 | CAN_TSR_TME0)) :\ ((__TRANSMITMAILBOX__) == CAN_TXMAILBOX_1)? ((((__HANDLE__)->Instance->TSR) & (CAN_TSR_RQCP1 | CAN_TSR_TXOK1 | CAN_TSR_TME1)) == (CAN_TSR_RQCP1 | CAN_TSR_TXOK1 | CAN_TSR_TME1)) :\ ((((__HANDLE__)->Instance->TSR) & (CAN_TSR_RQCP2 | CAN_TSR_TXOK2 | CAN_TSR_TME2)) == (CAN_TSR_RQCP2 | CAN_TSR_TXOK2 | CAN_TSR_TME2))) /** * @brief Release the specified receive FIFO. * @param __HANDLE__: CAN handle * @param __FIFONUMBER__: Receive FIFO number, CAN_FIFO0 or CAN_FIFO1. * @retval None */ #define __HAL_CAN_FIFO_RELEASE(__HANDLE__, __FIFONUMBER__) (((__FIFONUMBER__) == CAN_FIFO0)? \ ((__HANDLE__)->Instance->RF0R |= CAN_RF0R_RFOM0) : ((__HANDLE__)->Instance->RF1R |= CAN_RF1R_RFOM1)) /** * @brief Cancel a transmit request. * @param __HANDLE__: CAN Handle * @param __TRANSMITMAILBOX__: the number of the mailbox that is used for transmission. * @retval None */ #define __HAL_CAN_CANCEL_TRANSMIT(__HANDLE__, __TRANSMITMAILBOX__)\ (((__TRANSMITMAILBOX__) == CAN_TXMAILBOX_0)? ((__HANDLE__)->Instance->TSR |= CAN_TSR_ABRQ0) :\ ((__TRANSMITMAILBOX__) == CAN_TXMAILBOX_1)? ((__HANDLE__)->Instance->TSR |= CAN_TSR_ABRQ1) :\ ((__HANDLE__)->Instance->TSR |= CAN_TSR_ABRQ2)) /** * @brief Enable or disable the DBG Freeze for CAN. * @param __HANDLE__: CAN Handle * @param __NEWSTATE__: new state of the CAN peripheral. * This parameter can be: ENABLE (CAN reception/transmission is frozen * during debug. Reception FIFOs can still be accessed/controlled normally) * or DISABLE (CAN is working during debug). * @retval None */ #define __HAL_CAN_DBG_FREEZE(__HANDLE__, __NEWSTATE__) (((__NEWSTATE__) == ENABLE)? \ ((__HANDLE__)->Instance->MCR |= CAN_MCR_DBF) : ((__HANDLE__)->Instance->MCR &= ~CAN_MCR_DBF)) /** * @} */ /* Exported functions --------------------------------------------------------*/ /** @addtogroup CAN_Exported_Functions * @{ */ /** @addtogroup CAN_Exported_Functions_Group1 * @{ */ /* Initialization/de-initialization functions ***********************************/ HAL_StatusTypeDef HAL_CAN_Init(CAN_HandleTypeDef* hcan); HAL_StatusTypeDef HAL_CAN_ConfigFilter(CAN_HandleTypeDef* hcan, CAN_FilterConfTypeDef* sFilterConfig); HAL_StatusTypeDef HAL_CAN_DeInit(CAN_HandleTypeDef* hcan); void HAL_CAN_MspInit(CAN_HandleTypeDef* hcan); void HAL_CAN_MspDeInit(CAN_HandleTypeDef* hcan); /** * @} */ /** @addtogroup CAN_Exported_Functions_Group2 * @{ */ /* I/O operation functions ******************************************************/ HAL_StatusTypeDef HAL_CAN_Transmit(CAN_HandleTypeDef *hcan, uint32_t Timeout); HAL_StatusTypeDef HAL_CAN_Transmit_IT(CAN_HandleTypeDef *hcan); HAL_StatusTypeDef HAL_CAN_Receive(CAN_HandleTypeDef *hcan, uint8_t FIFONumber, uint32_t Timeout); HAL_StatusTypeDef HAL_CAN_Receive_IT(CAN_HandleTypeDef *hcan, uint8_t FIFONumber); HAL_StatusTypeDef HAL_CAN_Sleep(CAN_HandleTypeDef *hcan); HAL_StatusTypeDef HAL_CAN_WakeUp(CAN_HandleTypeDef *hcan); void HAL_CAN_IRQHandler(CAN_HandleTypeDef* hcan); void HAL_CAN_TxCpltCallback(CAN_HandleTypeDef* hcan); void HAL_CAN_RxCpltCallback(CAN_HandleTypeDef* hcan); void HAL_CAN_ErrorCallback(CAN_HandleTypeDef *hcan); /** * @} */ /** @addtogroup CAN_Exported_Functions_Group3 * @{ */ /* Peripheral State functions ***************************************************/ uint32_t HAL_CAN_GetError(CAN_HandleTypeDef *hcan); HAL_CAN_StateTypeDef HAL_CAN_GetState(CAN_HandleTypeDef* hcan); /** * @} */ /** * @} */ /* Private types -------------------------------------------------------------*/ /** @defgroup CAN_Private_Types CAN Private Types * @{ */ /** * @} */ /* Private variables ---------------------------------------------------------*/ /** @defgroup CAN_Private_Variables CAN Private Variables * @{ */ /** * @} */ /* Private constants ---------------------------------------------------------*/ /** @defgroup CAN_Private_Constants CAN Private Constants * @{ */ #define CAN_TXSTATUS_NOMAILBOX ((uint8_t)0x04) /*!< CAN cell did not provide CAN_TxStatus_NoMailBox */ #define CAN_FLAG_MASK ((uint32_t)0x000000FF) /** * @} */ /* Private macros ------------------------------------------------------------*/ /** @defgroup CAN_Private_Macros CAN Private Macros * @{ */ #define IS_CAN_MODE(MODE) (((MODE) == CAN_MODE_NORMAL) || \ ((MODE) == CAN_MODE_LOOPBACK)|| \ ((MODE) == CAN_MODE_SILENT) || \ ((MODE) == CAN_MODE_SILENT_LOOPBACK)) #define IS_CAN_SJW(SJW) (((SJW) == CAN_SJW_1TQ) || ((SJW) == CAN_SJW_2TQ)|| \ ((SJW) == CAN_SJW_3TQ) || ((SJW) == CAN_SJW_4TQ)) #define IS_CAN_BS1(BS1) ((BS1) <= CAN_BS1_16TQ) #define IS_CAN_BS2(BS2) ((BS2) <= CAN_BS2_8TQ) #define IS_CAN_PRESCALER(PRESCALER) (((PRESCALER) >= 1) && ((PRESCALER) <= 1024)) #define IS_CAN_FILTER_NUMBER(NUMBER) ((NUMBER) <= 27) #define IS_CAN_FILTER_MODE(MODE) (((MODE) == CAN_FILTERMODE_IDMASK) || \ ((MODE) == CAN_FILTERMODE_IDLIST)) #define IS_CAN_FILTER_SCALE(SCALE) (((SCALE) == CAN_FILTERSCALE_16BIT) || \ ((SCALE) == CAN_FILTERSCALE_32BIT)) #define IS_CAN_FILTER_FIFO(FIFO) (((FIFO) == CAN_FILTER_FIFO0) || \ ((FIFO) == CAN_FILTER_FIFO1)) #define IS_CAN_BANKNUMBER(BANKNUMBER) ((BANKNUMBER) <= 28) #define IS_CAN_TRANSMITMAILBOX(TRANSMITMAILBOX) ((TRANSMITMAILBOX) <= ((uint8_t)0x02)) #define IS_CAN_STDID(STDID) ((STDID) <= ((uint32_t)0x7FF)) #define IS_CAN_EXTID(EXTID) ((EXTID) <= ((uint32_t)0x1FFFFFFF)) #define IS_CAN_DLC(DLC) ((DLC) <= ((uint8_t)0x08)) #define IS_CAN_IDTYPE(IDTYPE) (((IDTYPE) == CAN_ID_STD) || \ ((IDTYPE) == CAN_ID_EXT)) #define IS_CAN_RTR(RTR) (((RTR) == CAN_RTR_DATA) || ((RTR) == CAN_RTR_REMOTE)) #define IS_CAN_FIFO(FIFO) (((FIFO) == CAN_FIFO0) || ((FIFO) == CAN_FIFO1)) /** * @} */ /* Private functions ---------------------------------------------------------*/ /** @defgroup CAN_Private_Functions CAN Private Functions * @{ */ /** * @} */ #endif /* STM32F405xx || STM32F415xx || STM32F407xx || STM32F417xx || STM32F427xx || STM32F437xx ||\ STM32F429xx || STM32F439xx || STM32F446xx || STM32F469xx || STM32F479xx */ /** * @} */ /** * @} */ #ifdef __cplusplus } #endif #endif /* __STM32F4xx_CAN_H */ /************************ (C) COPYRIGHT STMicroelectronics *****END OF FILE****/ ================================================ FILE: Zelig/mbed/TARGET_NUCLEO_F401RE/stm32f4xx_hal_cec.h ================================================ /** ****************************************************************************** * @file stm32f4xx_hal_cec.h * @author MCD Application Team * @version V1.4.1 * @date 09-October-2015 * @brief Header file of CEC HAL module. ****************************************************************************** * @attention * *

© COPYRIGHT(c) 2015 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. * ****************************************************************************** */ /* Define to prevent recursive inclusion -------------------------------------*/ #ifndef __STM32F4xx_HAL_CEC_H #define __STM32F4xx_HAL_CEC_H #ifdef __cplusplus extern "C" { #endif #if defined(STM32F446xx) /* Includes ------------------------------------------------------------------*/ #include "stm32f4xx_hal_def.h" /** @addtogroup STM32F4xx_HAL_Driver * @{ */ /** @addtogroup CEC * @{ */ /* Exported types ------------------------------------------------------------*/ /** @defgroup CEC_Exported_Types CEC Exported Types * @{ */ /** * @brief CEC Init Structure definition */ typedef struct { uint32_t SignalFreeTime; /*!< Set SFT field, specifies the Signal Free Time. It can be one of @ref CEC_Signal_Free_Time and belongs to the set {0,...,7} where 0x0 is the default configuration else means 0.5 + (SignalFreeTime - 1) nominal data bit periods */ uint32_t Tolerance; /*!< Set RXTOL bit, specifies the tolerance accepted on the received waveforms, it can be a value of @ref CEC_Tolerance : it is either CEC_STANDARD_TOLERANCE or CEC_EXTENDED_TOLERANCE */ uint32_t BRERxStop; /*!< Set BRESTP bit @ref CEC_BRERxStop : specifies whether or not a Bit Rising Error stops the reception. CEC_NO_RX_STOP_ON_BRE: reception is not stopped. CEC_RX_STOP_ON_BRE: reception is stopped. */ uint32_t BREErrorBitGen; /*!< Set BREGEN bit @ref CEC_BREErrorBitGen : specifies whether or not an Error-Bit is generated on the CEC line upon Bit Rising Error detection. CEC_BRE_ERRORBIT_NO_GENERATION: no error-bit generation. CEC_BRE_ERRORBIT_GENERATION: error-bit generation if BRESTP is set. */ uint32_t LBPEErrorBitGen; /*!< Set LBPEGEN bit @ref CEC_LBPEErrorBitGen : specifies whether or not an Error-Bit is generated on the CEC line upon Long Bit Period Error detection. CEC_LBPE_ERRORBIT_NO_GENERATION: no error-bit generation. CEC_LBPE_ERRORBIT_GENERATION: error-bit generation. */ uint32_t BroadcastMsgNoErrorBitGen; /*!< Set BRDNOGEN bit @ref CEC_BroadCastMsgErrorBitGen : allows to avoid an Error-Bit generation on the CEC line upon an error detected on a broadcast message. It supersedes BREGEN and LBPEGEN bits for a broadcast message error handling. It can take two values: 1) CEC_BROADCASTERROR_ERRORBIT_GENERATION. a) BRE detection: error-bit generation on the CEC line if BRESTP=CEC_RX_STOP_ON_BRE and BREGEN=CEC_BRE_ERRORBIT_NO_GENERATION. b) LBPE detection: error-bit generation on the CEC line if LBPGEN=CEC_LBPE_ERRORBIT_NO_GENERATION. 2) CEC_BROADCASTERROR_NO_ERRORBIT_GENERATION. no error-bit generation in case neither a) nor b) are satisfied. Additionally, there is no error-bit generation in case of Short Bit Period Error detection in a broadcast message while LSTN bit is set. */ uint32_t SignalFreeTimeOption; /*!< Set SFTOP bit @ref CEC_SFT_Option : specifies when SFT timer starts. CEC_SFT_START_ON_TXSOM SFT: timer starts when TXSOM is set by software. CEC_SFT_START_ON_TX_RX_END: SFT timer starts automatically at the end of message transmission/reception. */ uint32_t OwnAddress; /*!< Set OAR field, specifies CEC device address within a 15-bit long field */ uint32_t ListenMode; /*!< Set LSTN bit @ref CEC_Listening_Mode : specifies device listening mode. It can take two values: CEC_REDUCED_LISTENING_MODE: CEC peripheral receives only message addressed to its own address (OAR). Messages addressed to different destination are ignored. Broadcast messages are always received. CEC_FULL_LISTENING_MODE: CEC peripheral receives messages addressed to its own address (OAR) with positive acknowledge. Messages addressed to different destination are received, but without interfering with the CEC bus: no acknowledge sent. */ uint8_t InitiatorAddress; /* Initiator address (source logical address, sent in each header) */ }CEC_InitTypeDef; /** * @brief HAL CEC State structures definition */ typedef enum { HAL_CEC_STATE_RESET = 0x00, /*!< Peripheral Reset state */ HAL_CEC_STATE_READY = 0x01, /*!< Peripheral Initialized and ready for use */ HAL_CEC_STATE_BUSY = 0x02, /*!< an internal process is ongoing */ HAL_CEC_STATE_BUSY_TX = 0x03, /*!< Data Transmission process is ongoing */ HAL_CEC_STATE_BUSY_RX = 0x04, /*!< Data Reception process is ongoing */ HAL_CEC_STATE_STANDBY_RX = 0x05, /*!< IP ready to receive, doesn't prevent IP to transmit */ HAL_CEC_STATE_TIMEOUT = 0x06, /*!< Timeout state */ HAL_CEC_STATE_ERROR = 0x07 /*!< State Error */ }HAL_CEC_StateTypeDef; /** * @brief CEC handle Structure definition */ typedef struct { CEC_TypeDef *Instance; /* CEC registers base address */ CEC_InitTypeDef Init; /* CEC communication parameters */ uint8_t *pTxBuffPtr; /* Pointer to CEC Tx transfer Buffer */ uint16_t TxXferCount; /* CEC Tx Transfer Counter */ uint8_t *pRxBuffPtr; /* Pointer to CEC Rx transfer Buffer */ uint16_t RxXferSize; /* CEC Rx Transfer size, 0: header received only */ uint32_t ErrorCode; /* For errors handling purposes, copy of ISR register in case error is reported */ HAL_LockTypeDef Lock; /* Locking object */ HAL_CEC_StateTypeDef State; /* CEC communication state */ }CEC_HandleTypeDef; /** * @} */ /* Exported constants --------------------------------------------------------*/ /** @defgroup CEC_Exported_Constants CEC Exported Constants * @{ */ /** @defgroup CEC_Error_Code CEC Error Code * @{ */ #define HAL_CEC_ERROR_NONE (uint32_t) 0x0 /*!< no error */ #define HAL_CEC_ERROR_RXOVR CEC_ISR_RXOVR /*!< CEC Rx-Overrun */ #define HAL_CEC_ERROR_BRE CEC_ISR_BRE /*!< CEC Rx Bit Rising Error */ #define HAL_CEC_ERROR_SBPE CEC_ISR_SBPE /*!< CEC Rx Short Bit period Error */ #define HAL_CEC_ERROR_LBPE CEC_ISR_LBPE /*!< CEC Rx Long Bit period Error */ #define HAL_CEC_ERROR_RXACKE CEC_ISR_RXACKE /*!< CEC Rx Missing Acknowledge */ #define HAL_CEC_ERROR_ARBLST CEC_ISR_ARBLST /*!< CEC Arbitration Lost */ #define HAL_CEC_ERROR_TXUDR CEC_ISR_TXUDR /*!< CEC Tx-Buffer Underrun */ #define HAL_CEC_ERROR_TXERR CEC_ISR_TXERR /*!< CEC Tx-Error */ #define HAL_CEC_ERROR_TXACKE CEC_ISR_TXACKE /*!< CEC Tx Missing Acknowledge */ /** * @} */ /** @defgroup CEC_Signal_Free_Time CEC Signal Free Time setting parameter * @{ */ #define CEC_DEFAULT_SFT ((uint32_t)0x00000000) #define CEC_0_5_BITPERIOD_SFT ((uint32_t)0x00000001) #define CEC_1_5_BITPERIOD_SFT ((uint32_t)0x00000002) #define CEC_2_5_BITPERIOD_SFT ((uint32_t)0x00000003) #define CEC_3_5_BITPERIOD_SFT ((uint32_t)0x00000004) #define CEC_4_5_BITPERIOD_SFT ((uint32_t)0x00000005) #define CEC_5_5_BITPERIOD_SFT ((uint32_t)0x00000006) #define CEC_6_5_BITPERIOD_SFT ((uint32_t)0x00000007) /** * @} */ /** @defgroup CEC_Tolerance CEC Receiver Tolerance * @{ */ #define CEC_STANDARD_TOLERANCE ((uint32_t)0x00000000) #define CEC_EXTENDED_TOLERANCE ((uint32_t)CEC_CFGR_RXTOL) /** * @} */ /** @defgroup CEC_BRERxStop CEC Reception Stop on Error * @{ */ #define CEC_NO_RX_STOP_ON_BRE ((uint32_t)0x00000000) #define CEC_RX_STOP_ON_BRE ((uint32_t)CEC_CFGR_BRESTP) /** * @} */ /** @defgroup CEC_BREErrorBitGen CEC Error Bit Generation if Bit Rise Error reported * @{ */ #define CEC_BRE_ERRORBIT_NO_GENERATION ((uint32_t)0x00000000) #define CEC_BRE_ERRORBIT_GENERATION ((uint32_t)CEC_CFGR_BREGEN) /** * @} */ /** @defgroup CEC_LBPEErrorBitGen CEC Error Bit Generation if Long Bit Period Error reported * @{ */ #define CEC_LBPE_ERRORBIT_NO_GENERATION ((uint32_t)0x00000000) #define CEC_LBPE_ERRORBIT_GENERATION ((uint32_t)CEC_CFGR_LBPEGEN) /** * @} */ /** @defgroup CEC_BroadCastMsgErrorBitGen CEC Error Bit Generation on Broadcast message * @{ */ #define CEC_BROADCASTERROR_ERRORBIT_GENERATION ((uint32_t)0x00000000) #define CEC_BROADCASTERROR_NO_ERRORBIT_GENERATION ((uint32_t)CEC_CFGR_BRDNOGEN) /** * @} */ /** @defgroup CEC_SFT_Option CEC Signal Free Time start option * @{ */ #define CEC_SFT_START_ON_TXSOM ((uint32_t)0x00000000) #define CEC_SFT_START_ON_TX_RX_END ((uint32_t)CEC_CFGR_SFTOPT) /** * @} */ /** @defgroup CEC_Listening_Mode CEC Listening mode option * @{ */ #define CEC_REDUCED_LISTENING_MODE ((uint32_t)0x00000000) #define CEC_FULL_LISTENING_MODE ((uint32_t)CEC_CFGR_LSTN) /** * @} */ /** @defgroup CEC_OAR_Position CEC Device Own Address position in CEC CFGR register * @{ */ #define CEC_CFGR_OAR_LSB_POS ((uint32_t) 16) /** * @} */ /** @defgroup CEC_Initiator_Position CEC Initiator logical address position in message header * @{ */ #define CEC_INITIATOR_LSB_POS ((uint32_t) 4) /** * @} */ /** @defgroup CEC_Interrupts_Definitions CEC Interrupts definition * @{ */ #define CEC_IT_TXACKE CEC_IER_TXACKEIE #define CEC_IT_TXERR CEC_IER_TXERRIE #define CEC_IT_TXUDR CEC_IER_TXUDRIE #define CEC_IT_TXEND CEC_IER_TXENDIE #define CEC_IT_TXBR CEC_IER_TXBRIE #define CEC_IT_ARBLST CEC_IER_ARBLSTIE #define CEC_IT_RXACKE CEC_IER_RXACKEIE #define CEC_IT_LBPE CEC_IER_LBPEIE #define CEC_IT_SBPE CEC_IER_SBPEIE #define CEC_IT_BRE CEC_IER_BREIE #define CEC_IT_RXOVR CEC_IER_RXOVRIE #define CEC_IT_RXEND CEC_IER_RXENDIE #define CEC_IT_RXBR CEC_IER_RXBRIE /** * @} */ /** @defgroup CEC_Flags_Definitions CEC Flags definition * @{ */ #define CEC_FLAG_TXACKE CEC_ISR_TXACKE #define CEC_FLAG_TXERR CEC_ISR_TXERR #define CEC_FLAG_TXUDR CEC_ISR_TXUDR #define CEC_FLAG_TXEND CEC_ISR_TXEND #define CEC_FLAG_TXBR CEC_ISR_TXBR #define CEC_FLAG_ARBLST CEC_ISR_ARBLST #define CEC_FLAG_RXACKE CEC_ISR_RXACKE #define CEC_FLAG_LBPE CEC_ISR_LBPE #define CEC_FLAG_SBPE CEC_ISR_SBPE #define CEC_FLAG_BRE CEC_ISR_BRE #define CEC_FLAG_RXOVR CEC_ISR_RXOVR #define CEC_FLAG_RXEND CEC_ISR_RXEND #define CEC_FLAG_RXBR CEC_ISR_RXBR /** * @} */ /** @defgroup CEC_ALL_ERROR CEC all RX or TX errors flags * @{ */ #define CEC_ISR_ALL_ERROR ((uint32_t)CEC_ISR_RXOVR|CEC_ISR_BRE|CEC_ISR_SBPE|CEC_ISR_LBPE|CEC_ISR_RXACKE|\ CEC_ISR_ARBLST|CEC_ISR_TXUDR|CEC_ISR_TXERR|CEC_ISR_TXACKE) /** * @} */ /** @defgroup CEC_IER_ALL_RX CEC all RX errors interrupts enabling flag * @{ */ #define CEC_IER_RX_ALL_ERR ((uint32_t)CEC_IER_RXACKEIE|CEC_IER_LBPEIE|CEC_IER_SBPEIE|CEC_IER_BREIE|CEC_IER_RXOVRIE) /** * @} */ /** @defgroup CEC_IER_ALL_TX CEC all TX errors interrupts enabling flag * @{ */ #define CEC_IER_TX_ALL_ERR ((uint32_t)CEC_IER_TXACKEIE|CEC_IER_TXERRIE|CEC_IER_TXUDRIE|CEC_IER_ARBLSTIE) /** * @} */ /** * @} */ /* Exported macros -----------------------------------------------------------*/ /** @defgroup CEC_Exported_Macros CEC Exported Macros * @{ */ /** @brief Reset CEC handle state * @param __HANDLE__: CEC handle. * @retval None */ #define __HAL_CEC_RESET_HANDLE_STATE(__HANDLE__) ((__HANDLE__)->State = HAL_CEC_STATE_RESET) /** @brief Checks whether or not the specified CEC interrupt flag is set. * @param __HANDLE__: specifies the CEC Handle. * @param __FLAG__: specifies the interrupt to check. * @arg CEC_FLAG_TXACKE: Tx Missing acknowledge Error * @arg CEC_FLAG_TXERR: Tx Error. * @arg CEC_FLAG_TXUDR: Tx-Buffer Underrun. * @arg CEC_FLAG_TXEND: End of transmission (successful transmission of the last byte). * @arg CEC_FLAG_TXBR: Tx-Byte Request. * @arg CEC_FLAG_ARBLST: Arbitration Lost * @arg CEC_FLAG_RXACKE: Rx-Missing Acknowledge * @arg CEC_FLAG_LBPE: Rx Long period Error * @arg CEC_FLAG_SBPE: Rx Short period Error * @arg CEC_FLAG_BRE: Rx Bit Rissing Error * @arg CEC_FLAG_RXOVR: Rx Overrun. * @arg CEC_FLAG_RXEND: End Of Reception. * @arg CEC_FLAG_RXBR: Rx-Byte Received. * @retval ITStatus */ #define __HAL_CEC_GET_FLAG(__HANDLE__, __FLAG__) ((__HANDLE__)->Instance->ISR & (__FLAG__)) /** @brief Clears the interrupt or status flag when raised (write at 1) * @param __HANDLE__: specifies the CEC Handle. * @param __FLAG__: specifies the interrupt/status flag to clear. * This parameter can be one of the following values: * @arg CEC_FLAG_TXACKE: Tx Missing acknowledge Error * @arg CEC_FLAG_TXERR: Tx Error. * @arg CEC_FLAG_TXUDR: Tx-Buffer Underrun. * @arg CEC_FLAG_TXEND: End of transmission (successful transmission of the last byte). * @arg CEC_FLAG_TXBR: Tx-Byte Request. * @arg CEC_FLAG_ARBLST: Arbitration Lost * @arg CEC_FLAG_RXACKE: Rx-Missing Acknowledge * @arg CEC_FLAG_LBPE: Rx Long period Error * @arg CEC_FLAG_SBPE: Rx Short period Error * @arg CEC_FLAG_BRE: Rx Bit Rissing Error * @arg CEC_FLAG_RXOVR: Rx Overrun. * @arg CEC_FLAG_RXEND: End Of Reception. * @arg CEC_FLAG_RXBR: Rx-Byte Received. * @retval none */ #define __HAL_CEC_CLEAR_FLAG(__HANDLE__, __FLAG__) ((__HANDLE__)->Instance->ISR |= (__FLAG__)) /** @brief Enables the specified CEC interrupt. * @param __HANDLE__: specifies the CEC Handle. * @param __INTERRUPT__: specifies the CEC interrupt to enable. * This parameter can be one of the following values: * @arg CEC_IT_TXACKE: Tx Missing acknowledge Error IT Enable * @arg CEC_IT_TXERR: Tx Error IT Enable * @arg CEC_IT_TXUDR: Tx-Buffer Underrun IT Enable * @arg CEC_IT_TXEND: End of transmission IT Enable * @arg CEC_IT_TXBR: Tx-Byte Request IT Enable * @arg CEC_IT_ARBLST: Arbitration Lost IT Enable * @arg CEC_IT_RXACKE: Rx-Missing Acknowledge IT Enable * @arg CEC_IT_LBPE: Rx Long period Error IT Enable * @arg CEC_IT_SBPE: Rx Short period Error IT Enable * @arg CEC_IT_BRE: Rx Bit Rising Error IT Enable * @arg CEC_IT_RXOVR: Rx Overrun IT Enable * @arg CEC_IT_RXEND: End Of Reception IT Enable * @arg CEC_IT_RXBR: Rx-Byte Received IT Enable * @retval none */ #define __HAL_CEC_ENABLE_IT(__HANDLE__, __INTERRUPT__) ((__HANDLE__)->Instance->IER |= (__INTERRUPT__)) /** @brief Disables the specified CEC interrupt. * @param __HANDLE__: specifies the CEC Handle. * @param __INTERRUPT__: specifies the CEC interrupt to disable. * This parameter can be one of the following values: * @arg CEC_IT_TXACKE: Tx Missing acknowledge Error IT Enable * @arg CEC_IT_TXERR: Tx Error IT Enable * @arg CEC_IT_TXUDR: Tx-Buffer Underrun IT Enable * @arg CEC_IT_TXEND: End of transmission IT Enable * @arg CEC_IT_TXBR: Tx-Byte Request IT Enable * @arg CEC_IT_ARBLST: Arbitration Lost IT Enable * @arg CEC_IT_RXACKE: Rx-Missing Acknowledge IT Enable * @arg CEC_IT_LBPE: Rx Long period Error IT Enable * @arg CEC_IT_SBPE: Rx Short period Error IT Enable * @arg CEC_IT_BRE: Rx Bit Rising Error IT Enable * @arg CEC_IT_RXOVR: Rx Overrun IT Enable * @arg CEC_IT_RXEND: End Of Reception IT Enable * @arg CEC_IT_RXBR: Rx-Byte Received IT Enable * @retval none */ #define __HAL_CEC_DISABLE_IT(__HANDLE__, __INTERRUPT__) ((__HANDLE__)->Instance->IER &= (~(__INTERRUPT__))) /** @brief Checks whether or not the specified CEC interrupt is enabled. * @param __HANDLE__: specifies the CEC Handle. * @param __INTERRUPT__: specifies the CEC interrupt to check. * This parameter can be one of the following values: * @arg CEC_IT_TXACKE: Tx Missing acknowledge Error IT Enable * @arg CEC_IT_TXERR: Tx Error IT Enable * @arg CEC_IT_TXUDR: Tx-Buffer Underrun IT Enable * @arg CEC_IT_TXEND: End of transmission IT Enable * @arg CEC_IT_TXBR: Tx-Byte Request IT Enable * @arg CEC_IT_ARBLST: Arbitration Lost IT Enable * @arg CEC_IT_RXACKE: Rx-Missing Acknowledge IT Enable * @arg CEC_IT_LBPE: Rx Long period Error IT Enable * @arg CEC_IT_SBPE: Rx Short period Error IT Enable * @arg CEC_IT_BRE: Rx Bit Rising Error IT Enable * @arg CEC_IT_RXOVR: Rx Overrun IT Enable * @arg CEC_IT_RXEND: End Of Reception IT Enable * @arg CEC_IT_RXBR: Rx-Byte Received IT Enable * @retval FlagStatus */ #define __HAL_CEC_GET_IT_SOURCE(__HANDLE__, __INTERRUPT__) ((__HANDLE__)->Instance->IER & (__INTERRUPT__)) /** @brief Enables the CEC device * @param __HANDLE__: specifies the CEC Handle. * @retval none */ #define __HAL_CEC_ENABLE(__HANDLE__) ((__HANDLE__)->Instance->CR |= CEC_CR_CECEN) /** @brief Disables the CEC device * @param __HANDLE__: specifies the CEC Handle. * @retval none */ #define __HAL_CEC_DISABLE(__HANDLE__) ((__HANDLE__)->Instance->CR &= ~CEC_CR_CECEN) /** @brief Set Transmission Start flag * @param __HANDLE__: specifies the CEC Handle. * @retval none */ #define __HAL_CEC_FIRST_BYTE_TX_SET(__HANDLE__) ((__HANDLE__)->Instance->CR |= CEC_CR_TXSOM) /** @brief Set Transmission End flag * @param __HANDLE__: specifies the CEC Handle. * @retval none * If the CEC message consists of only one byte, TXEOM must be set before of TXSOM. */ #define __HAL_CEC_LAST_BYTE_TX_SET(__HANDLE__) ((__HANDLE__)->Instance->CR |= CEC_CR_TXEOM) /** @brief Get Transmission Start flag * @param __HANDLE__: specifies the CEC Handle. * @retval FlagStatus */ #define __HAL_CEC_GET_TRANSMISSION_START_FLAG(__HANDLE__) ((__HANDLE__)->Instance->CR & CEC_CR_TXSOM) /** @brief Get Transmission End flag * @param __HANDLE__: specifies the CEC Handle. * @retval FlagStatus */ #define __HAL_CEC_GET_TRANSMISSION_END_FLAG(__HANDLE__) ((__HANDLE__)->Instance->CR & CEC_CR_TXEOM) /** @brief Clear OAR register * @param __HANDLE__: specifies the CEC Handle. * @retval none */ #define __HAL_CEC_CLEAR_OAR(__HANDLE__) CLEAR_BIT((__HANDLE__)->Instance->CFGR, CEC_CFGR_OAR) /** @brief Set OAR register (without resetting previously set address in case of multi-address mode) * To reset OAR, __HAL_CEC_CLEAR_OAR() needs to be called beforehand * @param __HANDLE__: specifies the CEC Handle. * @param __ADDRESS__: Own Address value (CEC logical address is identified by bit position) * @retval none */ #define __HAL_CEC_SET_OAR(__HANDLE__,__ADDRESS__) SET_BIT((__HANDLE__)->Instance->CFGR, (__ADDRESS__)<< CEC_CFGR_OAR_LSB_POS) /** * @} */ /* Exported functions --------------------------------------------------------*/ /** @addtogroup CEC_Exported_Functions * @{ */ /** @addtogroup CEC_Exported_Functions_Group1 * @{ */ /* Initialization and de-initialization functions ****************************/ HAL_StatusTypeDef HAL_CEC_Init(CEC_HandleTypeDef *hcec); HAL_StatusTypeDef HAL_CEC_DeInit(CEC_HandleTypeDef *hcec); void HAL_CEC_MspInit(CEC_HandleTypeDef *hcec); void HAL_CEC_MspDeInit(CEC_HandleTypeDef *hcec); /** * @} */ /** @addtogroup CEC_Exported_Functions_Group2 * @{ */ /* I/O operation functions ***************************************************/ HAL_StatusTypeDef HAL_CEC_Transmit(CEC_HandleTypeDef *hcec, uint8_t DestinationAddress, uint8_t *pData, uint32_t Size, uint32_t Timeout); HAL_StatusTypeDef HAL_CEC_Receive(CEC_HandleTypeDef *hcec, uint8_t *pData, uint32_t Timeout); HAL_StatusTypeDef HAL_CEC_Transmit_IT(CEC_HandleTypeDef *hcec, uint8_t DestinationAddress, uint8_t *pData, uint32_t Size); HAL_StatusTypeDef HAL_CEC_Receive_IT(CEC_HandleTypeDef *hcec, uint8_t *pData); uint32_t HAL_CEC_GetReceivedFrameSize(CEC_HandleTypeDef *hcec); void HAL_CEC_IRQHandler(CEC_HandleTypeDef *hcec); void HAL_CEC_TxCpltCallback(CEC_HandleTypeDef *hcec); void HAL_CEC_RxCpltCallback(CEC_HandleTypeDef *hcec); void HAL_CEC_ErrorCallback(CEC_HandleTypeDef *hcec); /** * @} */ /** @addtogroup CEC_Exported_Functions_Group3 * @{ */ /* Peripheral State functions ************************************************/ HAL_CEC_StateTypeDef HAL_CEC_GetState(CEC_HandleTypeDef *hcec); uint32_t HAL_CEC_GetError(CEC_HandleTypeDef *hcec); /** * @} */ /** * @} */ /* Private types -------------------------------------------------------------*/ /** @defgroup CEC_Private_Types CEC Private Types * @{ */ /** * @} */ /* Private variables ---------------------------------------------------------*/ /** @defgroup CEC_Private_Variables CEC Private Variables * @{ */ /** * @} */ /* Private constants ---------------------------------------------------------*/ /** @defgroup CEC_Private_Constants CEC Private Constants * @{ */ /** * @} */ /* Private macros ------------------------------------------------------------*/ /** @defgroup CEC_Private_Macros CEC Private Macros * @{ */ #define IS_CEC_SIGNALFREETIME(__SFT__) ((__SFT__) <= CEC_CFGR_SFT) #define IS_CEC_TOLERANCE(__RXTOL__) (((__RXTOL__) == CEC_STANDARD_TOLERANCE) || \ ((__RXTOL__) == CEC_EXTENDED_TOLERANCE)) #define IS_CEC_BRERXSTOP(__BRERXSTOP__) (((__BRERXSTOP__) == CEC_NO_RX_STOP_ON_BRE) || \ ((__BRERXSTOP__) == CEC_RX_STOP_ON_BRE)) #define IS_CEC_BREERRORBITGEN(__ERRORBITGEN__) (((__ERRORBITGEN__) == CEC_BRE_ERRORBIT_NO_GENERATION) || \ ((__ERRORBITGEN__) == CEC_BRE_ERRORBIT_GENERATION)) #define IS_CEC_LBPEERRORBITGEN(__ERRORBITGEN__) (((__ERRORBITGEN__) == CEC_LBPE_ERRORBIT_NO_GENERATION) || \ ((__ERRORBITGEN__) == CEC_LBPE_ERRORBIT_GENERATION)) #define IS_CEC_BROADCASTERROR_NO_ERRORBIT_GENERATION(__ERRORBITGEN__) (((__ERRORBITGEN__) == CEC_BROADCASTERROR_ERRORBIT_GENERATION) || \ ((__ERRORBITGEN__) == CEC_BROADCASTERROR_NO_ERRORBIT_GENERATION)) #define IS_CEC_SFTOP(__SFTOP__) (((__SFTOP__) == CEC_SFT_START_ON_TXSOM) || \ ((__SFTOP__) == CEC_SFT_START_ON_TX_RX_END)) #define IS_CEC_LISTENING_MODE(__MODE__) (((__MODE__) == CEC_REDUCED_LISTENING_MODE) || \ ((__MODE__) == CEC_FULL_LISTENING_MODE)) /** @brief Check CEC device Own Address Register (OAR) setting. * OAR address is written in a 15-bit field within CEC_CFGR register. * @param __ADDRESS__: CEC own address. * @retval Test result (TRUE or FALSE). */ #define IS_CEC_OAR_ADDRESS(__ADDRESS__) ((__ADDRESS__) <= 0x07FFF) /** @brief Check CEC initiator or destination logical address setting. * Initiator and destination addresses are coded over 4 bits. * @param __ADDRESS__: CEC initiator or logical address. * @retval Test result (TRUE or FALSE). */ #define IS_CEC_ADDRESS(__ADDRESS__) ((__ADDRESS__) <= 0xF) /** @brief Check CEC message size. * The message size is the payload size: without counting the header, * it varies from 0 byte (ping operation, one header only, no payload) to * 15 bytes (1 opcode and up to 14 operands following the header). * @param __SIZE__: CEC message size. * @retval Test result (TRUE or FALSE). */ #define IS_CEC_MSGSIZE(__SIZE__) ((__SIZE__) <= 0xF) /** * @} */ /* Private functions ---------------------------------------------------------*/ /** @defgroup CEC_Private_Functions CEC Private Functions * @{ */ /** * @} */ /** * @} */ /** * @} */ #endif /* STM32F446xx */ #ifdef __cplusplus } #endif #endif /* __STM32F4xx_HAL_CEC_H */ /************************ (C) COPYRIGHT STMicroelectronics *****END OF FILE****/ ================================================ FILE: Zelig/mbed/TARGET_NUCLEO_F401RE/stm32f4xx_hal_conf.h ================================================ /** ****************************************************************************** * @file stm32f4xx_hal_conf.h * @author MCD Application Team * @version V1.2.0 * @date 26-December-2014 * @brief HAL configuration file ****************************************************************************** * @attention * *

© COPYRIGHT(c) 2014 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. * ****************************************************************************** */ /* Define to prevent recursive inclusion -------------------------------------*/ #ifndef __STM32F4xx_HAL_CONF_H #define __STM32F4xx_HAL_CONF_H #ifdef __cplusplus extern "C" { #endif /* Exported types ------------------------------------------------------------*/ /* Exported constants --------------------------------------------------------*/ /* ########################## Module Selection ############################## */ /** * @brief This is the list of modules to be used in the HAL driver */ #define HAL_MODULE_ENABLED #define HAL_ADC_MODULE_ENABLED #define HAL_CAN_MODULE_ENABLED #define HAL_CRC_MODULE_ENABLED #define HAL_CRYP_MODULE_ENABLED #define HAL_DAC_MODULE_ENABLED #define HAL_DCMI_MODULE_ENABLED #define HAL_DMA_MODULE_ENABLED /* #define HAL_DMA2D_MODULE_ENABLED */ #define HAL_ETH_MODULE_ENABLED #define HAL_FLASH_MODULE_ENABLED #define HAL_NAND_MODULE_ENABLED #define HAL_NOR_MODULE_ENABLED #define HAL_PCCARD_MODULE_ENABLED #define HAL_SRAM_MODULE_ENABLED /* #define HAL_SDRAM_MODULE_ENABLED */ #define HAL_HASH_MODULE_ENABLED #define HAL_GPIO_MODULE_ENABLED #define HAL_I2C_MODULE_ENABLED #define HAL_I2S_MODULE_ENABLED #define HAL_IWDG_MODULE_ENABLED #define HAL_LTDC_MODULE_ENABLED #define HAL_PWR_MODULE_ENABLED #define HAL_RCC_MODULE_ENABLED #define HAL_RNG_MODULE_ENABLED #define HAL_RTC_MODULE_ENABLED /* #define HAL_SAI_MODULE_ENABLED */ #define HAL_SD_MODULE_ENABLED #define HAL_SPI_MODULE_ENABLED #define HAL_TIM_MODULE_ENABLED #define HAL_UART_MODULE_ENABLED #define HAL_USART_MODULE_ENABLED #define HAL_IRDA_MODULE_ENABLED #define HAL_SMARTCARD_MODULE_ENABLED #define HAL_WWDG_MODULE_ENABLED #define HAL_CORTEX_MODULE_ENABLED #define HAL_PCD_MODULE_ENABLED #define HAL_HCD_MODULE_ENABLED /* ########################## HSE/HSI Values adaptation ##################### */ /** * @brief Adjust the value of External High Speed oscillator (HSE) used in your application. * This value is used by the RCC HAL module to compute the system frequency * (when HSE is used as system clock source, directly or through the PLL). */ #if !defined (HSE_VALUE) #define HSE_VALUE ((uint32_t)8000000) /*!< Value of the External oscillator in Hz */ #endif /* HSE_VALUE */ #if !defined (HSE_STARTUP_TIMEOUT) #define HSE_STARTUP_TIMEOUT ((uint32_t)200) /*!< Time out for HSE start up, in ms */ #endif /* HSE_STARTUP_TIMEOUT */ /** * @brief Internal High Speed oscillator (HSI) value. * This value is used by the RCC HAL module to compute the system frequency * (when HSI is used as system clock source, directly or through the PLL). */ #if !defined (HSI_VALUE) #define HSI_VALUE ((uint32_t)16000000) /*!< Value of the Internal oscillator in Hz*/ #endif /* HSI_VALUE */ /** * @brief Internal Low Speed oscillator (LSI) value. */ #if !defined (LSI_VALUE) #define LSI_VALUE ((uint32_t)32000) #endif /* LSI_VALUE */ /*!< Value of the Internal Low Speed oscillator in Hz The real value may vary depending on the variations in voltage and temperature. */ /** * @brief External Low Speed oscillator (LSE) value. */ #if !defined (LSE_VALUE) #define LSE_VALUE ((uint32_t)32768) /*!< Value of the External Low Speed oscillator in Hz */ #endif /* LSE_VALUE */ /** * @brief External clock source for I2S peripheral * This value is used by the I2S HAL module to compute the I2S clock source * frequency, this source is inserted directly through I2S_CKIN pad. */ #if !defined (EXTERNAL_CLOCK_VALUE) #define EXTERNAL_CLOCK_VALUE ((uint32_t)12288000) /*!< Value of the Internal oscillator in Hz*/ #endif /* EXTERNAL_CLOCK_VALUE */ /* Tip: To avoid modifying this file each time you need to use different HSE, === you can define the HSE value in your toolchain compiler preprocessor. */ /* ########################### System Configuration ######################### */ /** * @brief This is the HAL system configuration section */ #define VDD_VALUE ((uint32_t)3300) /*!< Value of VDD in mv */ #define TICK_INT_PRIORITY ((uint32_t)0x0F) /*!< tick interrupt priority */ #define USE_RTOS 0 #define PREFETCH_ENABLE 1 #define INSTRUCTION_CACHE_ENABLE 1 #define DATA_CACHE_ENABLE 1 /* ########################## Assert Selection ############################## */ /** * @brief Uncomment the line below to expanse the "assert_param" macro in the * HAL drivers code */ /* #define USE_FULL_ASSERT 1 */ /* ################## Ethernet peripheral configuration ##################### */ /* Section 1 : Ethernet peripheral configuration */ /* MAC ADDRESS: MAC_ADDR0:MAC_ADDR1:MAC_ADDR2:MAC_ADDR3:MAC_ADDR4:MAC_ADDR5 */ #define MAC_ADDR0 2 #define MAC_ADDR1 0 #define MAC_ADDR2 0 #define MAC_ADDR3 0 #define MAC_ADDR4 0 #define MAC_ADDR5 0 /* Definition of the Ethernet driver buffers size and count */ #define ETH_RX_BUF_SIZE ETH_MAX_PACKET_SIZE /* buffer size for receive */ #define ETH_TX_BUF_SIZE ETH_MAX_PACKET_SIZE /* buffer size for transmit */ #define ETH_RXBUFNB ((uint32_t)4) /* 4 Rx buffers of size ETH_RX_BUF_SIZE */ #define ETH_TXBUFNB ((uint32_t)4) /* 4 Tx buffers of size ETH_TX_BUF_SIZE */ /* Section 2: PHY configuration section */ /* DP83848 PHY Address*/ #define DP83848_PHY_ADDRESS 0x01 /* PHY Reset delay these values are based on a 1 ms Systick interrupt*/ #define PHY_RESET_DELAY ((uint32_t)0x000000FF) /* PHY Configuration delay */ #define PHY_CONFIG_DELAY ((uint32_t)0x00000FFF) #define PHY_READ_TO ((uint32_t)0x0000FFFF) #define PHY_WRITE_TO ((uint32_t)0x0000FFFF) /* Section 3: Common PHY Registers */ #define PHY_BCR ((uint16_t)0x00) /*!< Transceiver Basic Control Register */ #define PHY_BSR ((uint16_t)0x01) /*!< Transceiver Basic Status Register */ #define PHY_RESET ((uint16_t)0x8000) /*!< PHY Reset */ #define PHY_LOOPBACK ((uint16_t)0x4000) /*!< Select loop-back mode */ #define PHY_FULLDUPLEX_100M ((uint16_t)0x2100) /*!< Set the full-duplex mode at 100 Mb/s */ #define PHY_HALFDUPLEX_100M ((uint16_t)0x2000) /*!< Set the half-duplex mode at 100 Mb/s */ #define PHY_FULLDUPLEX_10M ((uint16_t)0x0100) /*!< Set the full-duplex mode at 10 Mb/s */ #define PHY_HALFDUPLEX_10M ((uint16_t)0x0000) /*!< Set the half-duplex mode at 10 Mb/s */ #define PHY_AUTONEGOTIATION ((uint16_t)0x1000) /*!< Enable auto-negotiation function */ #define PHY_RESTART_AUTONEGOTIATION ((uint16_t)0x0200) /*!< Restart auto-negotiation function */ #define PHY_POWERDOWN ((uint16_t)0x0800) /*!< Select the power down mode */ #define PHY_ISOLATE ((uint16_t)0x0400) /*!< Isolate PHY from MII */ #define PHY_AUTONEGO_COMPLETE ((uint16_t)0x0020) /*!< Auto-Negotiation process completed */ #define PHY_LINKED_STATUS ((uint16_t)0x0004) /*!< Valid link established */ #define PHY_JABBER_DETECTION ((uint16_t)0x0002) /*!< Jabber condition detected */ /* Section 4: Extended PHY Registers */ #define PHY_SR ((uint16_t)0x10) /*!< PHY status register Offset */ #define PHY_MICR ((uint16_t)0x11) /*!< MII Interrupt Control Register */ #define PHY_MISR ((uint16_t)0x12) /*!< MII Interrupt Status and Misc. Control Register */ #define PHY_LINK_STATUS ((uint16_t)0x0001) /*!< PHY Link mask */ #define PHY_SPEED_STATUS ((uint16_t)0x0002) /*!< PHY Speed mask */ #define PHY_DUPLEX_STATUS ((uint16_t)0x0004) /*!< PHY Duplex mask */ #define PHY_MICR_INT_EN ((uint16_t)0x0002) /*!< PHY Enable interrupts */ #define PHY_MICR_INT_OE ((uint16_t)0x0001) /*!< PHY Enable output interrupt events */ #define PHY_MISR_LINK_INT_EN ((uint16_t)0x0020) /*!< Enable Interrupt on change of link status */ #define PHY_LINK_INTERRUPT ((uint16_t)0x2000) /*!< PHY link status interrupt mask */ /* Includes ------------------------------------------------------------------*/ /** * @brief Include module's header file */ #ifdef HAL_RCC_MODULE_ENABLED #include "stm32f4xx_hal_rcc.h" #endif /* HAL_RCC_MODULE_ENABLED */ #ifdef HAL_GPIO_MODULE_ENABLED #include "stm32f4xx_hal_gpio.h" #endif /* HAL_GPIO_MODULE_ENABLED */ #ifdef HAL_DMA_MODULE_ENABLED #include "stm32f4xx_hal_dma.h" #endif /* HAL_DMA_MODULE_ENABLED */ #ifdef HAL_CORTEX_MODULE_ENABLED #include "stm32f4xx_hal_cortex.h" #endif /* HAL_CORTEX_MODULE_ENABLED */ #ifdef HAL_ADC_MODULE_ENABLED #include "stm32f4xx_hal_adc.h" #endif /* HAL_ADC_MODULE_ENABLED */ #ifdef HAL_CAN_MODULE_ENABLED #include "stm32f4xx_hal_can.h" #endif /* HAL_CAN_MODULE_ENABLED */ #ifdef HAL_CRC_MODULE_ENABLED #include "stm32f4xx_hal_crc.h" #endif /* HAL_CRC_MODULE_ENABLED */ #ifdef HAL_CRYP_MODULE_ENABLED #include "stm32f4xx_hal_cryp.h" #endif /* HAL_CRYP_MODULE_ENABLED */ #ifdef HAL_DMA2D_MODULE_ENABLED #include "stm32f4xx_hal_dma2d.h" #endif /* HAL_DMA2D_MODULE_ENABLED */ #ifdef HAL_DAC_MODULE_ENABLED #include "stm32f4xx_hal_dac.h" #endif /* HAL_DAC_MODULE_ENABLED */ #ifdef HAL_DCMI_MODULE_ENABLED #include "stm32f4xx_hal_dcmi.h" #endif /* HAL_DCMI_MODULE_ENABLED */ #ifdef HAL_ETH_MODULE_ENABLED #include "stm32f4xx_hal_eth.h" #endif /* HAL_ETH_MODULE_ENABLED */ #ifdef HAL_FLASH_MODULE_ENABLED #include "stm32f4xx_hal_flash.h" #endif /* HAL_FLASH_MODULE_ENABLED */ #ifdef HAL_SRAM_MODULE_ENABLED #include "stm32f4xx_hal_sram.h" #endif /* HAL_SRAM_MODULE_ENABLED */ #ifdef HAL_NOR_MODULE_ENABLED #include "stm32f4xx_hal_nor.h" #endif /* HAL_NOR_MODULE_ENABLED */ #ifdef HAL_NAND_MODULE_ENABLED #include "stm32f4xx_hal_nand.h" #endif /* HAL_NAND_MODULE_ENABLED */ #ifdef HAL_PCCARD_MODULE_ENABLED #include "stm32f4xx_hal_pccard.h" #endif /* HAL_PCCARD_MODULE_ENABLED */ #ifdef HAL_SDRAM_MODULE_ENABLED #include "stm32f4xx_hal_sdram.h" #endif /* HAL_SDRAM_MODULE_ENABLED */ #ifdef HAL_HASH_MODULE_ENABLED #include "stm32f4xx_hal_hash.h" #endif /* HAL_HASH_MODULE_ENABLED */ #ifdef HAL_I2C_MODULE_ENABLED #include "stm32f4xx_hal_i2c.h" #endif /* HAL_I2C_MODULE_ENABLED */ #ifdef HAL_I2S_MODULE_ENABLED #include "stm32f4xx_hal_i2s.h" #endif /* HAL_I2S_MODULE_ENABLED */ #ifdef HAL_IWDG_MODULE_ENABLED #include "stm32f4xx_hal_iwdg.h" #endif /* HAL_IWDG_MODULE_ENABLED */ #ifdef HAL_LTDC_MODULE_ENABLED #include "stm32f4xx_hal_ltdc.h" #endif /* HAL_LTDC_MODULE_ENABLED */ #ifdef HAL_PWR_MODULE_ENABLED #include "stm32f4xx_hal_pwr.h" #endif /* HAL_PWR_MODULE_ENABLED */ #ifdef HAL_RNG_MODULE_ENABLED #include "stm32f4xx_hal_rng.h" #endif /* HAL_RNG_MODULE_ENABLED */ #ifdef HAL_RTC_MODULE_ENABLED #include "stm32f4xx_hal_rtc.h" #endif /* HAL_RTC_MODULE_ENABLED */ #ifdef HAL_SAI_MODULE_ENABLED #include "stm32f4xx_hal_sai.h" #endif /* HAL_SAI_MODULE_ENABLED */ #ifdef HAL_SD_MODULE_ENABLED #include "stm32f4xx_hal_sd.h" #endif /* HAL_SD_MODULE_ENABLED */ #ifdef HAL_SPI_MODULE_ENABLED #include "stm32f4xx_hal_spi.h" #endif /* HAL_SPI_MODULE_ENABLED */ #ifdef HAL_TIM_MODULE_ENABLED #include "stm32f4xx_hal_tim.h" #endif /* HAL_TIM_MODULE_ENABLED */ #ifdef HAL_UART_MODULE_ENABLED #include "stm32f4xx_hal_uart.h" #endif /* HAL_UART_MODULE_ENABLED */ #ifdef HAL_USART_MODULE_ENABLED #include "stm32f4xx_hal_usart.h" #endif /* HAL_USART_MODULE_ENABLED */ #ifdef HAL_IRDA_MODULE_ENABLED #include "stm32f4xx_hal_irda.h" #endif /* HAL_IRDA_MODULE_ENABLED */ #ifdef HAL_SMARTCARD_MODULE_ENABLED #include "stm32f4xx_hal_smartcard.h" #endif /* HAL_SMARTCARD_MODULE_ENABLED */ #ifdef HAL_WWDG_MODULE_ENABLED #include "stm32f4xx_hal_wwdg.h" #endif /* HAL_WWDG_MODULE_ENABLED */ #ifdef HAL_PCD_MODULE_ENABLED #include "stm32f4xx_hal_pcd.h" #endif /* HAL_PCD_MODULE_ENABLED */ #ifdef HAL_HCD_MODULE_ENABLED #include "stm32f4xx_hal_hcd.h" #endif /* HAL_HCD_MODULE_ENABLED */ /* Exported macro ------------------------------------------------------------*/ #ifdef USE_FULL_ASSERT /** * @brief The assert_param macro is used for function's parameters check. * @param expr: If expr is false, it calls assert_failed function * which reports the name of the source file and the source * line number of the call that failed. * If expr is true, it returns no value. * @retval None */ #define assert_param(expr) ((expr) ? (void)0 : assert_failed((uint8_t *)__FILE__, __LINE__)) /* Exported functions ------------------------------------------------------- */ void assert_failed(uint8_t* file, uint32_t line); #else #define assert_param(expr) ((void)0) #endif /* USE_FULL_ASSERT */ #ifdef __cplusplus } #endif #endif /* __STM32F4xx_HAL_CONF_H */ /************************ (C) COPYRIGHT STMicroelectronics *****END OF FILE****/ ================================================ FILE: Zelig/mbed/TARGET_NUCLEO_F401RE/stm32f4xx_hal_conf_template.h ================================================ /** ****************************************************************************** * @file stm32f4xx_hal_conf_template.h * @author MCD Application Team * @version V1.4.1 * @date 09-October-2015 * @brief HAL configuration template file. * This file should be copied to the application folder and renamed * to stm32f4xx_hal_conf.h. ****************************************************************************** * @attention * *

© COPYRIGHT(c) 2015 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. * ****************************************************************************** */ /* Define to prevent recursive inclusion -------------------------------------*/ #ifndef __STM32F4xx_HAL_CONF_H #define __STM32F4xx_HAL_CONF_H #ifdef __cplusplus extern "C" { #endif /* Exported types ------------------------------------------------------------*/ /* Exported constants --------------------------------------------------------*/ /* ########################## Module Selection ############################## */ /** * @brief This is the list of modules to be used in the HAL driver */ #define HAL_MODULE_ENABLED #define HAL_ADC_MODULE_ENABLED #define HAL_CAN_MODULE_ENABLED #define HAL_CRC_MODULE_ENABLED #define HAL_CEC_MODULE_ENABLED #define HAL_CRYP_MODULE_ENABLED #define HAL_DAC_MODULE_ENABLED #define HAL_DCMI_MODULE_ENABLED #define HAL_DMA_MODULE_ENABLED #define HAL_DMA2D_MODULE_ENABLED #define HAL_ETH_MODULE_ENABLED #define HAL_FLASH_MODULE_ENABLED #define HAL_NAND_MODULE_ENABLED #define HAL_NOR_MODULE_ENABLED #define HAL_PCCARD_MODULE_ENABLED #define HAL_SRAM_MODULE_ENABLED #define HAL_SDRAM_MODULE_ENABLED #define HAL_HASH_MODULE_ENABLED #define HAL_GPIO_MODULE_ENABLED #define HAL_I2C_MODULE_ENABLED #define HAL_I2S_MODULE_ENABLED #define HAL_IWDG_MODULE_ENABLED #define HAL_LTDC_MODULE_ENABLED #define HAL_DSI_MODULE_ENABLED #define HAL_PWR_MODULE_ENABLED #define HAL_QSPI_MODULE_ENABLED #define HAL_RCC_MODULE_ENABLED #define HAL_RNG_MODULE_ENABLED #define HAL_RTC_MODULE_ENABLED #define HAL_SAI_MODULE_ENABLED #define HAL_SD_MODULE_ENABLED #define HAL_SPI_MODULE_ENABLED #define HAL_TIM_MODULE_ENABLED #define HAL_UART_MODULE_ENABLED #define HAL_USART_MODULE_ENABLED #define HAL_IRDA_MODULE_ENABLED #define HAL_SMARTCARD_MODULE_ENABLED #define HAL_WWDG_MODULE_ENABLED #define HAL_CORTEX_MODULE_ENABLED #define HAL_PCD_MODULE_ENABLED #define HAL_HCD_MODULE_ENABLED #define HAL_FMPI2C_MODULE_ENABLED #define HAL_SPDIFRX_MODULE_ENABLED #define HAL_LPTIM_MODULE_ENABLED /* ########################## HSE/HSI Values adaptation ##################### */ /** * @brief Adjust the value of External High Speed oscillator (HSE) used in your application. * This value is used by the RCC HAL module to compute the system frequency * (when HSE is used as system clock source, directly or through the PLL). */ #if !defined (HSE_VALUE) #define HSE_VALUE ((uint32_t)25000000) /*!< Value of the External oscillator in Hz */ #endif /* HSE_VALUE */ #if !defined (HSE_STARTUP_TIMEOUT) #define HSE_STARTUP_TIMEOUT ((uint32_t)5000) /*!< Time out for HSE start up, in ms */ #endif /* HSE_STARTUP_TIMEOUT */ /** * @brief Internal High Speed oscillator (HSI) value. * This value is used by the RCC HAL module to compute the system frequency * (when HSI is used as system clock source, directly or through the PLL). */ #if !defined (HSI_VALUE) #define HSI_VALUE ((uint32_t)16000000) /*!< Value of the Internal oscillator in Hz*/ #endif /* HSI_VALUE */ /** * @brief Internal Low Speed oscillator (LSI) value. */ #if !defined (LSI_VALUE) #define LSI_VALUE ((uint32_t)32000) /*!< LSI Typical Value in Hz*/ #endif /* LSI_VALUE */ /*!< Value of the Internal Low Speed oscillator in Hz The real value may vary depending on the variations in voltage and temperature.*/ /** * @brief External Low Speed oscillator (LSE) value. */ #if !defined (LSE_VALUE) #define LSE_VALUE ((uint32_t)32768) /*!< Value of the External Low Speed oscillator in Hz */ #endif /* LSE_VALUE */ /** * @brief External clock source for I2S peripheral * This value is used by the I2S HAL module to compute the I2S clock source * frequency, this source is inserted directly through I2S_CKIN pad. */ #if !defined (EXTERNAL_CLOCK_VALUE) #define EXTERNAL_CLOCK_VALUE ((uint32_t)12288000) /*!< Value of the Internal oscillator in Hz*/ #endif /* EXTERNAL_CLOCK_VALUE */ /* Tip: To avoid modifying this file each time you need to use different HSE, === you can define the HSE value in your toolchain compiler preprocessor. */ /* ########################### System Configuration ######################### */ /** * @brief This is the HAL system configuration section */ #define VDD_VALUE ((uint32_t)3300) /*!< Value of VDD in mv */ #define TICK_INT_PRIORITY ((uint32_t)0x0F) /*!< tick interrupt priority */ #define USE_RTOS 0 #define PREFETCH_ENABLE 1 #define INSTRUCTION_CACHE_ENABLE 1 #define DATA_CACHE_ENABLE 1 /* ########################## Assert Selection ############################## */ /** * @brief Uncomment the line below to expanse the "assert_param" macro in the * HAL drivers code */ /* #define USE_FULL_ASSERT 1 */ /* ################## Ethernet peripheral configuration ##################### */ /* Section 1 : Ethernet peripheral configuration */ /* MAC ADDRESS: MAC_ADDR0:MAC_ADDR1:MAC_ADDR2:MAC_ADDR3:MAC_ADDR4:MAC_ADDR5 */ #define MAC_ADDR0 2 #define MAC_ADDR1 0 #define MAC_ADDR2 0 #define MAC_ADDR3 0 #define MAC_ADDR4 0 #define MAC_ADDR5 0 /* Definition of the Ethernet driver buffers size and count */ #define ETH_RX_BUF_SIZE ETH_MAX_PACKET_SIZE /* buffer size for receive */ #define ETH_TX_BUF_SIZE ETH_MAX_PACKET_SIZE /* buffer size for transmit */ #define ETH_RXBUFNB ((uint32_t)4) /* 4 Rx buffers of size ETH_RX_BUF_SIZE */ #define ETH_TXBUFNB ((uint32_t)4) /* 4 Tx buffers of size ETH_TX_BUF_SIZE */ /* Section 2: PHY configuration section */ /* DP83848 PHY Address*/ #define DP83848_PHY_ADDRESS 0x01 /* PHY Reset delay these values are based on a 1 ms Systick interrupt*/ #define PHY_RESET_DELAY ((uint32_t)0x000000FF) /* PHY Configuration delay */ #define PHY_CONFIG_DELAY ((uint32_t)0x00000FFF) #define PHY_READ_TO ((uint32_t)0x0000FFFF) #define PHY_WRITE_TO ((uint32_t)0x0000FFFF) /* Section 3: Common PHY Registers */ #define PHY_BCR ((uint16_t)0x00) /*!< Transceiver Basic Control Register */ #define PHY_BSR ((uint16_t)0x01) /*!< Transceiver Basic Status Register */ #define PHY_RESET ((uint16_t)0x8000) /*!< PHY Reset */ #define PHY_LOOPBACK ((uint16_t)0x4000) /*!< Select loop-back mode */ #define PHY_FULLDUPLEX_100M ((uint16_t)0x2100) /*!< Set the full-duplex mode at 100 Mb/s */ #define PHY_HALFDUPLEX_100M ((uint16_t)0x2000) /*!< Set the half-duplex mode at 100 Mb/s */ #define PHY_FULLDUPLEX_10M ((uint16_t)0x0100) /*!< Set the full-duplex mode at 10 Mb/s */ #define PHY_HALFDUPLEX_10M ((uint16_t)0x0000) /*!< Set the half-duplex mode at 10 Mb/s */ #define PHY_AUTONEGOTIATION ((uint16_t)0x1000) /*!< Enable auto-negotiation function */ #define PHY_RESTART_AUTONEGOTIATION ((uint16_t)0x0200) /*!< Restart auto-negotiation function */ #define PHY_POWERDOWN ((uint16_t)0x0800) /*!< Select the power down mode */ #define PHY_ISOLATE ((uint16_t)0x0400) /*!< Isolate PHY from MII */ #define PHY_AUTONEGO_COMPLETE ((uint16_t)0x0020) /*!< Auto-Negotiation process completed */ #define PHY_LINKED_STATUS ((uint16_t)0x0004) /*!< Valid link established */ #define PHY_JABBER_DETECTION ((uint16_t)0x0002) /*!< Jabber condition detected */ /* Section 4: Extended PHY Registers */ #define PHY_SR ((uint16_t)0x10) /*!< PHY status register Offset */ #define PHY_MICR ((uint16_t)0x11) /*!< MII Interrupt Control Register */ #define PHY_MISR ((uint16_t)0x12) /*!< MII Interrupt Status and Misc. Control Register */ #define PHY_LINK_STATUS ((uint16_t)0x0001) /*!< PHY Link mask */ #define PHY_SPEED_STATUS ((uint16_t)0x0002) /*!< PHY Speed mask */ #define PHY_DUPLEX_STATUS ((uint16_t)0x0004) /*!< PHY Duplex mask */ #define PHY_MICR_INT_EN ((uint16_t)0x0002) /*!< PHY Enable interrupts */ #define PHY_MICR_INT_OE ((uint16_t)0x0001) /*!< PHY Enable output interrupt events */ #define PHY_MISR_LINK_INT_EN ((uint16_t)0x0020) /*!< Enable Interrupt on change of link status */ #define PHY_LINK_INTERRUPT ((uint16_t)0x2000) /*!< PHY link status interrupt mask */ /* Includes ------------------------------------------------------------------*/ /** * @brief Include module's header file */ #ifdef HAL_RCC_MODULE_ENABLED #include "stm32f4xx_hal_rcc.h" #endif /* HAL_RCC_MODULE_ENABLED */ #ifdef HAL_GPIO_MODULE_ENABLED #include "stm32f4xx_hal_gpio.h" #endif /* HAL_GPIO_MODULE_ENABLED */ #ifdef HAL_DMA_MODULE_ENABLED #include "stm32f4xx_hal_dma.h" #endif /* HAL_DMA_MODULE_ENABLED */ #ifdef HAL_CORTEX_MODULE_ENABLED #include "stm32f4xx_hal_cortex.h" #endif /* HAL_CORTEX_MODULE_ENABLED */ #ifdef HAL_ADC_MODULE_ENABLED #include "stm32f4xx_hal_adc.h" #endif /* HAL_ADC_MODULE_ENABLED */ #ifdef HAL_CAN_MODULE_ENABLED #include "stm32f4xx_hal_can.h" #endif /* HAL_CAN_MODULE_ENABLED */ #ifdef HAL_CRC_MODULE_ENABLED #include "stm32f4xx_hal_crc.h" #endif /* HAL_CRC_MODULE_ENABLED */ #ifdef HAL_CRYP_MODULE_ENABLED #include "stm32f4xx_hal_cryp.h" #endif /* HAL_CRYP_MODULE_ENABLED */ #ifdef HAL_DMA2D_MODULE_ENABLED #include "stm32f4xx_hal_dma2d.h" #endif /* HAL_DMA2D_MODULE_ENABLED */ #ifdef HAL_DAC_MODULE_ENABLED #include "stm32f4xx_hal_dac.h" #endif /* HAL_DAC_MODULE_ENABLED */ #ifdef HAL_DCMI_MODULE_ENABLED #include "stm32f4xx_hal_dcmi.h" #endif /* HAL_DCMI_MODULE_ENABLED */ #ifdef HAL_ETH_MODULE_ENABLED #include "stm32f4xx_hal_eth.h" #endif /* HAL_ETH_MODULE_ENABLED */ #ifdef HAL_FLASH_MODULE_ENABLED #include "stm32f4xx_hal_flash.h" #endif /* HAL_FLASH_MODULE_ENABLED */ #ifdef HAL_SRAM_MODULE_ENABLED #include "stm32f4xx_hal_sram.h" #endif /* HAL_SRAM_MODULE_ENABLED */ #ifdef HAL_NOR_MODULE_ENABLED #include "stm32f4xx_hal_nor.h" #endif /* HAL_NOR_MODULE_ENABLED */ #ifdef HAL_NAND_MODULE_ENABLED #include "stm32f4xx_hal_nand.h" #endif /* HAL_NAND_MODULE_ENABLED */ #ifdef HAL_PCCARD_MODULE_ENABLED #include "stm32f4xx_hal_pccard.h" #endif /* HAL_PCCARD_MODULE_ENABLED */ #ifdef HAL_SDRAM_MODULE_ENABLED #include "stm32f4xx_hal_sdram.h" #endif /* HAL_SDRAM_MODULE_ENABLED */ #ifdef HAL_HASH_MODULE_ENABLED #include "stm32f4xx_hal_hash.h" #endif /* HAL_HASH_MODULE_ENABLED */ #ifdef HAL_I2C_MODULE_ENABLED #include "stm32f4xx_hal_i2c.h" #endif /* HAL_I2C_MODULE_ENABLED */ #ifdef HAL_I2S_MODULE_ENABLED #include "stm32f4xx_hal_i2s.h" #endif /* HAL_I2S_MODULE_ENABLED */ #ifdef HAL_IWDG_MODULE_ENABLED #include "stm32f4xx_hal_iwdg.h" #endif /* HAL_IWDG_MODULE_ENABLED */ #ifdef HAL_LTDC_MODULE_ENABLED #include "stm32f4xx_hal_ltdc.h" #endif /* HAL_LTDC_MODULE_ENABLED */ #ifdef HAL_PWR_MODULE_ENABLED #include "stm32f4xx_hal_pwr.h" #endif /* HAL_PWR_MODULE_ENABLED */ #ifdef HAL_RNG_MODULE_ENABLED #include "stm32f4xx_hal_rng.h" #endif /* HAL_RNG_MODULE_ENABLED */ #ifdef HAL_RTC_MODULE_ENABLED #include "stm32f4xx_hal_rtc.h" #endif /* HAL_RTC_MODULE_ENABLED */ #ifdef HAL_SAI_MODULE_ENABLED #include "stm32f4xx_hal_sai.h" #endif /* HAL_SAI_MODULE_ENABLED */ #ifdef HAL_SD_MODULE_ENABLED #include "stm32f4xx_hal_sd.h" #endif /* HAL_SD_MODULE_ENABLED */ #ifdef HAL_SPI_MODULE_ENABLED #include "stm32f4xx_hal_spi.h" #endif /* HAL_SPI_MODULE_ENABLED */ #ifdef HAL_TIM_MODULE_ENABLED #include "stm32f4xx_hal_tim.h" #endif /* HAL_TIM_MODULE_ENABLED */ #ifdef HAL_UART_MODULE_ENABLED #include "stm32f4xx_hal_uart.h" #endif /* HAL_UART_MODULE_ENABLED */ #ifdef HAL_USART_MODULE_ENABLED #include "stm32f4xx_hal_usart.h" #endif /* HAL_USART_MODULE_ENABLED */ #ifdef HAL_IRDA_MODULE_ENABLED #include "stm32f4xx_hal_irda.h" #endif /* HAL_IRDA_MODULE_ENABLED */ #ifdef HAL_SMARTCARD_MODULE_ENABLED #include "stm32f4xx_hal_smartcard.h" #endif /* HAL_SMARTCARD_MODULE_ENABLED */ #ifdef HAL_WWDG_MODULE_ENABLED #include "stm32f4xx_hal_wwdg.h" #endif /* HAL_WWDG_MODULE_ENABLED */ #ifdef HAL_PCD_MODULE_ENABLED #include "stm32f4xx_hal_pcd.h" #endif /* HAL_PCD_MODULE_ENABLED */ #ifdef HAL_HCD_MODULE_ENABLED #include "stm32f4xx_hal_hcd.h" #endif /* HAL_HCD_MODULE_ENABLED */ #ifdef HAL_DSI_MODULE_ENABLED #include "stm32f4xx_hal_dsi.h" #endif /* HAL_DSI_MODULE_ENABLED */ #ifdef HAL_QSPI_MODULE_ENABLED #include "stm32f4xx_hal_qspi.h" #endif /* HAL_QSPI_MODULE_ENABLED */ #ifdef HAL_CEC_MODULE_ENABLED #include "stm32f4xx_hal_cec.h" #endif /* HAL_CEC_MODULE_ENABLED */ #ifdef HAL_FMPI2C_MODULE_ENABLED #include "stm32f4xx_hal_fmpi2c.h" #endif /* HAL_FMPI2C_MODULE_ENABLED */ #ifdef HAL_SPDIFRX_MODULE_ENABLED #include "stm32f4xx_hal_spdifrx.h" #endif /* HAL_SPDIFRX_MODULE_ENABLED */ #ifdef HAL_LPTIM_MODULE_ENABLED #include "stm32f4xx_hal_lptim.h" #endif /* HAL_LPTIM_MODULE_ENABLED */ /* Exported macro ------------------------------------------------------------*/ #ifdef USE_FULL_ASSERT /** * @brief The assert_param macro is used for function's parameters check. * @param expr: If expr is false, it calls assert_failed function * which reports the name of the source file and the source * line number of the call that failed. * If expr is true, it returns no value. * @retval None */ #define assert_param(expr) ((expr) ? (void)0 : assert_failed((uint8_t *)__FILE__, __LINE__)) /* Exported functions ------------------------------------------------------- */ void assert_failed(uint8_t* file, uint32_t line); #else #define assert_param(expr) ((void)0) #endif /* USE_FULL_ASSERT */ #ifdef __cplusplus } #endif #endif /* __STM32F4xx_HAL_CONF_H */ /************************ (C) COPYRIGHT STMicroelectronics *****END OF FILE****/ ================================================ FILE: Zelig/mbed/TARGET_NUCLEO_F401RE/stm32f4xx_hal_cortex.h ================================================ /** ****************************************************************************** * @file stm32f4xx_hal_cortex.h * @author MCD Application Team * @version V1.4.1 * @date 09-October-2015 * @brief Header file of CORTEX HAL module. ****************************************************************************** * @attention * *

© COPYRIGHT(c) 2015 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. * ****************************************************************************** */ /* Define to prevent recursive inclusion -------------------------------------*/ #ifndef __STM32F4xx_HAL_CORTEX_H #define __STM32F4xx_HAL_CORTEX_H #ifdef __cplusplus extern "C" { #endif /* Includes ------------------------------------------------------------------*/ #include "stm32f4xx_hal_def.h" /** @addtogroup STM32F4xx_HAL_Driver * @{ */ /** @addtogroup CORTEX * @{ */ /* Exported types ------------------------------------------------------------*/ /** @defgroup CORTEX_Exported_Types Cortex Exported Types * @{ */ #if (__MPU_PRESENT == 1) /** @defgroup CORTEX_MPU_Region_Initialization_Structure_definition MPU Region Initialization Structure Definition * @brief MPU Region initialization structure * @{ */ typedef struct { uint8_t Enable; /*!< Specifies the status of the region. This parameter can be a value of @ref CORTEX_MPU_Region_Enable */ uint8_t Number; /*!< Specifies the number of the region to protect. This parameter can be a value of @ref CORTEX_MPU_Region_Number */ uint32_t BaseAddress; /*!< Specifies the base address of the region to protect. */ uint8_t Size; /*!< Specifies the size of the region to protect. This parameter can be a value of @ref CORTEX_MPU_Region_Size */ uint8_t SubRegionDisable; /*!< Specifies the number of the subregion protection to disable. This parameter must be a number between Min_Data = 0x00 and Max_Data = 0xFF */ uint8_t TypeExtField; /*!< Specifies the TEX field level. This parameter can be a value of @ref CORTEX_MPU_TEX_Levels */ uint8_t AccessPermission; /*!< Specifies the region access permission type. This parameter can be a value of @ref CORTEX_MPU_Region_Permission_Attributes */ uint8_t DisableExec; /*!< Specifies the instruction access status. This parameter can be a value of @ref CORTEX_MPU_Instruction_Access */ uint8_t IsShareable; /*!< Specifies the shareability status of the protected region. This parameter can be a value of @ref CORTEX_MPU_Access_Shareable */ uint8_t IsCacheable; /*!< Specifies the cacheable status of the region protected. This parameter can be a value of @ref CORTEX_MPU_Access_Cacheable */ uint8_t IsBufferable; /*!< Specifies the bufferable status of the protected region. This parameter can be a value of @ref CORTEX_MPU_Access_Bufferable */ }MPU_Region_InitTypeDef; /** * @} */ #endif /* __MPU_PRESENT */ /** * @} */ /* Exported constants --------------------------------------------------------*/ /** @defgroup CORTEX_Exported_Constants CORTEX Exported Constants * @{ */ /** @defgroup CORTEX_Preemption_Priority_Group CORTEX Preemption Priority Group * @{ */ #define NVIC_PRIORITYGROUP_0 ((uint32_t)0x00000007) /*!< 0 bits for pre-emption priority 4 bits for subpriority */ #define NVIC_PRIORITYGROUP_1 ((uint32_t)0x00000006) /*!< 1 bits for pre-emption priority 3 bits for subpriority */ #define NVIC_PRIORITYGROUP_2 ((uint32_t)0x00000005) /*!< 2 bits for pre-emption priority 2 bits for subpriority */ #define NVIC_PRIORITYGROUP_3 ((uint32_t)0x00000004) /*!< 3 bits for pre-emption priority 1 bits for subpriority */ #define NVIC_PRIORITYGROUP_4 ((uint32_t)0x00000003) /*!< 4 bits for pre-emption priority 0 bits for subpriority */ /** * @} */ /** @defgroup CORTEX_SysTick_clock_source CORTEX _SysTick clock source * @{ */ #define SYSTICK_CLKSOURCE_HCLK_DIV8 ((uint32_t)0x00000000) #define SYSTICK_CLKSOURCE_HCLK ((uint32_t)0x00000004) /** * @} */ #if (__MPU_PRESENT == 1) /** @defgroup CORTEX_MPU_HFNMI_PRIVDEF_Control MPU HFNMI and PRIVILEGED Access control * @{ */ #define MPU_HFNMI_PRIVDEF_NONE ((uint32_t)0x00000000) #define MPU_HARDFAULT_NMI ((uint32_t)0x00000002) #define MPU_PRIVILEGED_DEFAULT ((uint32_t)0x00000004) #define MPU_HFNMI_PRIVDEF ((uint32_t)0x00000006) /** * @} */ /** @defgroup CORTEX_MPU_Region_Enable CORTEX MPU Region Enable * @{ */ #define MPU_REGION_ENABLE ((uint8_t)0x01) #define MPU_REGION_DISABLE ((uint8_t)0x00) /** * @} */ /** @defgroup CORTEX_MPU_Instruction_Access CORTEX MPU Instruction Access * @{ */ #define MPU_INSTRUCTION_ACCESS_ENABLE ((uint8_t)0x00) #define MPU_INSTRUCTION_ACCESS_DISABLE ((uint8_t)0x01) /** * @} */ /** @defgroup CORTEX_MPU_Access_Shareable CORTEX MPU Instruction Access Shareable * @{ */ #define MPU_ACCESS_SHAREABLE ((uint8_t)0x01) #define MPU_ACCESS_NOT_SHAREABLE ((uint8_t)0x00) /** * @} */ /** @defgroup CORTEX_MPU_Access_Cacheable CORTEX MPU Instruction Access Cacheable * @{ */ #define MPU_ACCESS_CACHEABLE ((uint8_t)0x01) #define MPU_ACCESS_NOT_CACHEABLE ((uint8_t)0x00) /** * @} */ /** @defgroup CORTEX_MPU_Access_Bufferable CORTEX MPU Instruction Access Bufferable * @{ */ #define MPU_ACCESS_BUFFERABLE ((uint8_t)0x01) #define MPU_ACCESS_NOT_BUFFERABLE ((uint8_t)0x00) /** * @} */ /** @defgroup CORTEX_MPU_TEX_Levels MPU TEX Levels * @{ */ #define MPU_TEX_LEVEL0 ((uint8_t)0x00) #define MPU_TEX_LEVEL1 ((uint8_t)0x01) #define MPU_TEX_LEVEL2 ((uint8_t)0x02) /** * @} */ /** @defgroup CORTEX_MPU_Region_Size CORTEX MPU Region Size * @{ */ #define MPU_REGION_SIZE_32B ((uint8_t)0x04) #define MPU_REGION_SIZE_64B ((uint8_t)0x05) #define MPU_REGION_SIZE_128B ((uint8_t)0x06) #define MPU_REGION_SIZE_256B ((uint8_t)0x07) #define MPU_REGION_SIZE_512B ((uint8_t)0x08) #define MPU_REGION_SIZE_1KB ((uint8_t)0x09) #define MPU_REGION_SIZE_2KB ((uint8_t)0x0A) #define MPU_REGION_SIZE_4KB ((uint8_t)0x0B) #define MPU_REGION_SIZE_8KB ((uint8_t)0x0C) #define MPU_REGION_SIZE_16KB ((uint8_t)0x0D) #define MPU_REGION_SIZE_32KB ((uint8_t)0x0E) #define MPU_REGION_SIZE_64KB ((uint8_t)0x0F) #define MPU_REGION_SIZE_128KB ((uint8_t)0x10) #define MPU_REGION_SIZE_256KB ((uint8_t)0x11) #define MPU_REGION_SIZE_512KB ((uint8_t)0x12) #define MPU_REGION_SIZE_1MB ((uint8_t)0x13) #define MPU_REGION_SIZE_2MB ((uint8_t)0x14) #define MPU_REGION_SIZE_4MB ((uint8_t)0x15) #define MPU_REGION_SIZE_8MB ((uint8_t)0x16) #define MPU_REGION_SIZE_16MB ((uint8_t)0x17) #define MPU_REGION_SIZE_32MB ((uint8_t)0x18) #define MPU_REGION_SIZE_64MB ((uint8_t)0x19) #define MPU_REGION_SIZE_128MB ((uint8_t)0x1A) #define MPU_REGION_SIZE_256MB ((uint8_t)0x1B) #define MPU_REGION_SIZE_512MB ((uint8_t)0x1C) #define MPU_REGION_SIZE_1GB ((uint8_t)0x1D) #define MPU_REGION_SIZE_2GB ((uint8_t)0x1E) #define MPU_REGION_SIZE_4GB ((uint8_t)0x1F) /** * @} */ /** @defgroup CORTEX_MPU_Region_Permission_Attributes CORTEX MPU Region Permission Attributes * @{ */ #define MPU_REGION_NO_ACCESS ((uint8_t)0x00) #define MPU_REGION_PRIV_RW ((uint8_t)0x01) #define MPU_REGION_PRIV_RW_URO ((uint8_t)0x02) #define MPU_REGION_FULL_ACCESS ((uint8_t)0x03) #define MPU_REGION_PRIV_RO ((uint8_t)0x05) #define MPU_REGION_PRIV_RO_URO ((uint8_t)0x06) /** * @} */ /** @defgroup CORTEX_MPU_Region_Number CORTEX MPU Region Number * @{ */ #define MPU_REGION_NUMBER0 ((uint8_t)0x00) #define MPU_REGION_NUMBER1 ((uint8_t)0x01) #define MPU_REGION_NUMBER2 ((uint8_t)0x02) #define MPU_REGION_NUMBER3 ((uint8_t)0x03) #define MPU_REGION_NUMBER4 ((uint8_t)0x04) #define MPU_REGION_NUMBER5 ((uint8_t)0x05) #define MPU_REGION_NUMBER6 ((uint8_t)0x06) #define MPU_REGION_NUMBER7 ((uint8_t)0x07) /** * @} */ #endif /* __MPU_PRESENT */ /** * @} */ /* Exported Macros -----------------------------------------------------------*/ /** @defgroup CORTEX_Exported_Macros CORTEX Exported Macros * @{ */ /** @brief Configures the SysTick clock source. * @param __CLKSRC__: specifies the SysTick clock source. * This parameter can be one of the following values: * @arg SYSTICK_CLKSOURCE_HCLK_DIV8: AHB clock divided by 8 selected as SysTick clock source. * @arg SYSTICK_CLKSOURCE_HCLK: AHB clock selected as SysTick clock source. * @retval None */ #define __HAL_CORTEX_SYSTICKCLK_CONFIG(__CLKSRC__) \ do { \ if ((__CLKSRC__) == SYSTICK_CLKSOURCE_HCLK) \ { \ SysTick->CTRL |= SYSTICK_CLKSOURCE_HCLK; \ } \ else \ SysTick->CTRL &= ~SYSTICK_CLKSOURCE_HCLK; \ } while(0) /** * @} */ /* Exported functions --------------------------------------------------------*/ /** @addtogroup CORTEX_Exported_Functions * @{ */ /** @addtogroup CORTEX_Exported_Functions_Group1 * @{ */ /* Initialization and de-initialization functions *****************************/ void HAL_NVIC_SetPriorityGrouping(uint32_t PriorityGroup); void HAL_NVIC_SetPriority(IRQn_Type IRQn, uint32_t PreemptPriority, uint32_t SubPriority); void HAL_NVIC_EnableIRQ(IRQn_Type IRQn); void HAL_NVIC_DisableIRQ(IRQn_Type IRQn); void HAL_NVIC_SystemReset(void); uint32_t HAL_SYSTICK_Config(uint32_t TicksNumb); /** * @} */ /** @addtogroup CORTEX_Exported_Functions_Group2 * @{ */ /* Peripheral Control functions ***********************************************/ #if (__MPU_PRESENT == 1) void HAL_MPU_ConfigRegion(MPU_Region_InitTypeDef *MPU_Init); #endif /* __MPU_PRESENT */ uint32_t HAL_NVIC_GetPriorityGrouping(void); void HAL_NVIC_GetPriority(IRQn_Type IRQn, uint32_t PriorityGroup, uint32_t* pPreemptPriority, uint32_t* pSubPriority); uint32_t HAL_NVIC_GetPendingIRQ(IRQn_Type IRQn); void HAL_NVIC_SetPendingIRQ(IRQn_Type IRQn); void HAL_NVIC_ClearPendingIRQ(IRQn_Type IRQn); uint32_t HAL_NVIC_GetActive(IRQn_Type IRQn); void HAL_SYSTICK_CLKSourceConfig(uint32_t CLKSource); void HAL_SYSTICK_IRQHandler(void); void HAL_SYSTICK_Callback(void); /** * @} */ /** * @} */ /* Private types -------------------------------------------------------------*/ /* Private variables ---------------------------------------------------------*/ /* Private constants ---------------------------------------------------------*/ /* Private macros ------------------------------------------------------------*/ /** @defgroup CORTEX_Private_Macros CORTEX Private Macros * @{ */ #define IS_NVIC_PRIORITY_GROUP(GROUP) (((GROUP) == NVIC_PRIORITYGROUP_0) || \ ((GROUP) == NVIC_PRIORITYGROUP_1) || \ ((GROUP) == NVIC_PRIORITYGROUP_2) || \ ((GROUP) == NVIC_PRIORITYGROUP_3) || \ ((GROUP) == NVIC_PRIORITYGROUP_4)) #define IS_NVIC_PREEMPTION_PRIORITY(PRIORITY) ((PRIORITY) < 0x10) #define IS_NVIC_SUB_PRIORITY(PRIORITY) ((PRIORITY) < 0x10) #define IS_NVIC_DEVICE_IRQ(IRQ) ((IRQ) >= 0x00) #define IS_SYSTICK_CLK_SOURCE(SOURCE) (((SOURCE) == SYSTICK_CLKSOURCE_HCLK) || \ ((SOURCE) == SYSTICK_CLKSOURCE_HCLK_DIV8)) #if (__MPU_PRESENT == 1) #define IS_MPU_REGION_ENABLE(STATE) (((STATE) == MPU_REGION_ENABLE) || \ ((STATE) == MPU_REGION_DISABLE)) #define IS_MPU_INSTRUCTION_ACCESS(STATE) (((STATE) == MPU_INSTRUCTION_ACCESS_ENABLE) || \ ((STATE) == MPU_INSTRUCTION_ACCESS_DISABLE)) #define IS_MPU_ACCESS_SHAREABLE(STATE) (((STATE) == MPU_ACCESS_SHAREABLE) || \ ((STATE) == MPU_ACCESS_NOT_SHAREABLE)) #define IS_MPU_ACCESS_CACHEABLE(STATE) (((STATE) == MPU_ACCESS_CACHEABLE) || \ ((STATE) == MPU_ACCESS_NOT_CACHEABLE)) #define IS_MPU_ACCESS_BUFFERABLE(STATE) (((STATE) == MPU_ACCESS_BUFFERABLE) || \ ((STATE) == MPU_ACCESS_NOT_BUFFERABLE)) #define IS_MPU_TEX_LEVEL(TYPE) (((TYPE) == MPU_TEX_LEVEL0) || \ ((TYPE) == MPU_TEX_LEVEL1) || \ ((TYPE) == MPU_TEX_LEVEL2)) #define IS_MPU_REGION_PERMISSION_ATTRIBUTE(TYPE) (((TYPE) == MPU_REGION_NO_ACCESS) || \ ((TYPE) == MPU_REGION_PRIV_RW) || \ ((TYPE) == MPU_REGION_PRIV_RW_URO) || \ ((TYPE) == MPU_REGION_FULL_ACCESS) || \ ((TYPE) == MPU_REGION_PRIV_RO) || \ ((TYPE) == MPU_REGION_PRIV_RO_URO)) #define IS_MPU_REGION_NUMBER(NUMBER) (((NUMBER) == MPU_REGION_NUMBER0) || \ ((NUMBER) == MPU_REGION_NUMBER1) || \ ((NUMBER) == MPU_REGION_NUMBER2) || \ ((NUMBER) == MPU_REGION_NUMBER3) || \ ((NUMBER) == MPU_REGION_NUMBER4) || \ ((NUMBER) == MPU_REGION_NUMBER5) || \ ((NUMBER) == MPU_REGION_NUMBER6) || \ ((NUMBER) == MPU_REGION_NUMBER7)) #define IS_MPU_REGION_SIZE(SIZE) (((SIZE) == MPU_REGION_SIZE_32B) || \ ((SIZE) == MPU_REGION_SIZE_64B) || \ ((SIZE) == MPU_REGION_SIZE_128B) || \ ((SIZE) == MPU_REGION_SIZE_256B) || \ ((SIZE) == MPU_REGION_SIZE_512B) || \ ((SIZE) == MPU_REGION_SIZE_1KB) || \ ((SIZE) == MPU_REGION_SIZE_2KB) || \ ((SIZE) == MPU_REGION_SIZE_4KB) || \ ((SIZE) == MPU_REGION_SIZE_8KB) || \ ((SIZE) == MPU_REGION_SIZE_16KB) || \ ((SIZE) == MPU_REGION_SIZE_32KB) || \ ((SIZE) == MPU_REGION_SIZE_64KB) || \ ((SIZE) == MPU_REGION_SIZE_128KB) || \ ((SIZE) == MPU_REGION_SIZE_256KB) || \ ((SIZE) == MPU_REGION_SIZE_512KB) || \ ((SIZE) == MPU_REGION_SIZE_1MB) || \ ((SIZE) == MPU_REGION_SIZE_2MB) || \ ((SIZE) == MPU_REGION_SIZE_4MB) || \ ((SIZE) == MPU_REGION_SIZE_8MB) || \ ((SIZE) == MPU_REGION_SIZE_16MB) || \ ((SIZE) == MPU_REGION_SIZE_32MB) || \ ((SIZE) == MPU_REGION_SIZE_64MB) || \ ((SIZE) == MPU_REGION_SIZE_128MB) || \ ((SIZE) == MPU_REGION_SIZE_256MB) || \ ((SIZE) == MPU_REGION_SIZE_512MB) || \ ((SIZE) == MPU_REGION_SIZE_1GB) || \ ((SIZE) == MPU_REGION_SIZE_2GB) || \ ((SIZE) == MPU_REGION_SIZE_4GB)) #define IS_MPU_SUB_REGION_DISABLE(SUBREGION) ((SUBREGION) < (uint16_t)0x00FF) #endif /* __MPU_PRESENT */ /** * @} */ /* Private functions ---------------------------------------------------------*/ /** @defgroup CORTEX_Private_Functions CORTEX Private Functions * @brief CORTEX private functions * @{ */ #if (__MPU_PRESENT == 1) /** * @brief Disables the MPU * @retval None */ __STATIC_INLINE void HAL_MPU_Disable(void) { /* Disable fault exceptions */ SCB->SHCSR &= ~SCB_SHCSR_MEMFAULTENA_Msk; /* Disable the MPU */ MPU->CTRL &= ~MPU_CTRL_ENABLE_Msk; } /** * @brief Enables the MPU * @param MPU_Control: Specifies the control mode of the MPU during hard fault, * NMI, FAULTMASK and privileged access to the default memory * This parameter can be one of the following values: * @arg MPU_HFNMI_PRIVDEF_NONE * @arg MPU_HARDFAULT_NMI * @arg MPU_PRIVILEGED_DEFAULT * @arg MPU_HFNMI_PRIVDEF * @retval None */ __STATIC_INLINE void HAL_MPU_Enable(uint32_t MPU_Control) { /* Enable the MPU */ MPU->CTRL = MPU_Control | MPU_CTRL_ENABLE_Msk; /* Enable fault exceptions */ SCB->SHCSR |= SCB_SHCSR_MEMFAULTENA_Msk; } #endif /* __MPU_PRESENT */ /** * @} */ /** * @} */ /** * @} */ #ifdef __cplusplus } #endif #endif /* __STM32F4xx_HAL_CORTEX_H */ /************************ (C) COPYRIGHT STMicroelectronics *****END OF FILE****/ ================================================ FILE: Zelig/mbed/TARGET_NUCLEO_F401RE/stm32f4xx_hal_crc.h ================================================ /** ****************************************************************************** * @file stm32f4xx_hal_crc.h * @author MCD Application Team * @version V1.4.1 * @date 09-October-2015 * @brief Header file of CRC HAL module. ****************************************************************************** * @attention * *

© COPYRIGHT(c) 2015 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. * ****************************************************************************** */ /* Define to prevent recursive inclusion -------------------------------------*/ #ifndef __STM32F4xx_HAL_CRC_H #define __STM32F4xx_HAL_CRC_H #ifdef __cplusplus extern "C" { #endif /* Includes ------------------------------------------------------------------*/ #include "stm32f4xx_hal_def.h" /** @addtogroup STM32F4xx_HAL_Driver * @{ */ /** @defgroup CRC CRC * @brief CRC HAL module driver * @{ */ /* Exported types ------------------------------------------------------------*/ /** @defgroup CRC_Exported_Types CRC Exported Types * @{ */ /** @defgroup CRC_Exported_Types_Group1 CRC State Structure definition * @{ */ typedef enum { HAL_CRC_STATE_RESET = 0x00, /*!< CRC not yet initialized or disabled */ HAL_CRC_STATE_READY = 0x01, /*!< CRC initialized and ready for use */ HAL_CRC_STATE_BUSY = 0x02, /*!< CRC internal process is ongoing */ HAL_CRC_STATE_TIMEOUT = 0x03, /*!< CRC timeout state */ HAL_CRC_STATE_ERROR = 0x04 /*!< CRC error state */ }HAL_CRC_StateTypeDef; /** * @} */ /** @defgroup CRC_Exported_Types_Group2 CRC Handle Structure definition * @{ */ typedef struct { CRC_TypeDef *Instance; /*!< Register base address */ HAL_LockTypeDef Lock; /*!< CRC locking object */ __IO HAL_CRC_StateTypeDef State; /*!< CRC communication state */ }CRC_HandleTypeDef; /** * @} */ /** * @} */ /* Exported constants --------------------------------------------------------*/ /* Exported macro ------------------------------------------------------------*/ /** @defgroup CRC_Exported_Macros CRC Exported Macros * @{ */ /** @brief Resets CRC handle state * @param __HANDLE__: CRC handle * @retval None */ #define __HAL_CRC_RESET_HANDLE_STATE(__HANDLE__) ((__HANDLE__)->State = HAL_CRC_STATE_RESET) /** * @brief Resets CRC Data Register. * @param __HANDLE__: CRC handle * @retval None */ #define __HAL_CRC_DR_RESET(__HANDLE__) ((__HANDLE__)->Instance->CR |= CRC_CR_RESET) /** * @brief Stores a 8-bit data in the Independent Data(ID) register. * @param __HANDLE__: CRC handle * @param __VALUE__: 8-bit value to be stored in the ID register * @retval None */ #define __HAL_CRC_SET_IDR(__HANDLE__, __VALUE__) (WRITE_REG((__HANDLE__)->Instance->IDR, (__VALUE__))) /** * @brief Returns the 8-bit data stored in the Independent Data(ID) register. * @param __HANDLE__: CRC handle * @retval 8-bit value of the ID register */ #define __HAL_CRC_GET_IDR(__HANDLE__) (((__HANDLE__)->Instance->IDR) & CRC_IDR_IDR) /** * @} */ /* Exported functions --------------------------------------------------------*/ /** @defgroup CRC_Exported_Functions CRC Exported Functions * @{ */ /** @defgroup CRC_Exported_Functions_Group1 Initialization and de-initialization functions * @{ */ HAL_StatusTypeDef HAL_CRC_Init(CRC_HandleTypeDef *hcrc); HAL_StatusTypeDef HAL_CRC_DeInit (CRC_HandleTypeDef *hcrc); void HAL_CRC_MspInit(CRC_HandleTypeDef *hcrc); void HAL_CRC_MspDeInit(CRC_HandleTypeDef *hcrc); /** * @} */ /** @defgroup CRC_Exported_Functions_Group2 Peripheral Control functions * @{ */ uint32_t HAL_CRC_Accumulate(CRC_HandleTypeDef *hcrc, uint32_t pBuffer[], uint32_t BufferLength); uint32_t HAL_CRC_Calculate(CRC_HandleTypeDef *hcrc, uint32_t pBuffer[], uint32_t BufferLength); /** * @} */ /** @defgroup CRC_Exported_Functions_Group3 Peripheral State functions * @{ */ HAL_CRC_StateTypeDef HAL_CRC_GetState(CRC_HandleTypeDef *hcrc); /** * @} */ /** * @} */ /* Private types -------------------------------------------------------------*/ /** @defgroup CRC_Private_Types CRC Private Types * @{ */ /** * @} */ /* Private defines -----------------------------------------------------------*/ /** @defgroup CRC_Private_Defines CRC Private Defines * @{ */ /** * @} */ /* Private variables ---------------------------------------------------------*/ /** @defgroup CRC_Private_Variables CRC Private Variables * @{ */ /** * @} */ /* Private constants ---------------------------------------------------------*/ /** @defgroup CRC_Private_Constants CRC Private Constants * @{ */ /** * @} */ /* Private macros ------------------------------------------------------------*/ /** @defgroup CRC_Private_Macros CRC Private Macros * @{ */ /** * @} */ /* Private functions prototypes ----------------------------------------------*/ /** @defgroup CRC_Private_Functions_Prototypes CRC Private Functions Prototypes * @{ */ /** * @} */ /* Private functions ---------------------------------------------------------*/ /** @defgroup CRC_Private_Functions CRC Private Functions * @{ */ /** * @} */ /** * @} */ /** * @} */ #ifdef __cplusplus } #endif #endif /* __STM32F4xx_HAL_CRC_H */ /************************ (C) COPYRIGHT STMicroelectronics *****END OF FILE****/ ================================================ FILE: Zelig/mbed/TARGET_NUCLEO_F401RE/stm32f4xx_hal_cryp.h ================================================ /** ****************************************************************************** * @file stm32f4xx_hal_cryp.h * @author MCD Application Team * @version V1.4.1 * @date 09-October-2015 * @brief Header file of CRYP HAL module. ****************************************************************************** * @attention * *

© COPYRIGHT(c) 2015 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. * ****************************************************************************** */ /* Define to prevent recursive inclusion -------------------------------------*/ #ifndef __STM32F4xx_HAL_CRYP_H #define __STM32F4xx_HAL_CRYP_H #ifdef __cplusplus extern "C" { #endif #if defined(STM32F415xx) || defined(STM32F417xx) || defined(STM32F437xx) || defined(STM32F439xx) || defined(STM32F479xx) /* Includes ------------------------------------------------------------------*/ #include "stm32f4xx_hal_def.h" /** @addtogroup STM32F4xx_HAL_Driver * @{ */ /** @addtogroup CRYP * @{ */ /* Exported types ------------------------------------------------------------*/ /** @defgroup CRYP_Exported_Types CRYP Exported Types * @{ */ /** @defgroup CRYP_Exported_Types_Group1 CRYP Configuration Structure definition * @{ */ typedef struct { uint32_t DataType; /*!< 32-bit data, 16-bit data, 8-bit data or 1-bit string. This parameter can be a value of @ref CRYP CRYP_Data_Type */ uint32_t KeySize; /*!< Used only in AES mode only : 128, 192 or 256 bit key length. This parameter can be a value of @ref CRYP CRYP_Key_Size */ uint8_t* pKey; /*!< The key used for encryption/decryption */ uint8_t* pInitVect; /*!< The initialization vector used also as initialization counter in CTR mode */ uint8_t IVSize; /*!< The size of initialization vector. This parameter (called nonce size in CCM) is used only in AES-128/192/256 encryption/decryption CCM mode */ uint8_t TagSize; /*!< The size of returned authentication TAG. This parameter is used only in AES-128/192/256 encryption/decryption CCM mode */ uint8_t* Header; /*!< The header used in GCM and CCM modes */ uint32_t HeaderSize; /*!< The size of header buffer in bytes */ uint8_t* pScratch; /*!< Scratch buffer used to append the header. It's size must be equal to header size + 21 bytes. This parameter is used only in AES-128/192/256 encryption/decryption CCM mode */ }CRYP_InitTypeDef; /** * @} */ /** @defgroup CRYP_Exported_Types_Group2 CRYP State structures definition * @{ */ typedef enum { HAL_CRYP_STATE_RESET = 0x00, /*!< CRYP not yet initialized or disabled */ HAL_CRYP_STATE_READY = 0x01, /*!< CRYP initialized and ready for use */ HAL_CRYP_STATE_BUSY = 0x02, /*!< CRYP internal processing is ongoing */ HAL_CRYP_STATE_TIMEOUT = 0x03, /*!< CRYP timeout state */ HAL_CRYP_STATE_ERROR = 0x04 /*!< CRYP error state */ }HAL_CRYP_STATETypeDef; /** * @} */ /** @defgroup CRYP_Exported_Types_Group3 CRYP phase structures definition * @{ */ typedef enum { HAL_CRYP_PHASE_READY = 0x01, /*!< CRYP peripheral is ready for initialization. */ HAL_CRYP_PHASE_PROCESS = 0x02, /*!< CRYP peripheral is in processing phase */ HAL_CRYP_PHASE_FINAL = 0x03 /*!< CRYP peripheral is in final phase This is relevant only with CCM and GCM modes */ }HAL_PhaseTypeDef; /** * @} */ /** @defgroup CRYP_Exported_Types_Group4 CRYP handle Structure definition * @{ */ typedef struct { CRYP_TypeDef *Instance; /*!< CRYP registers base address */ CRYP_InitTypeDef Init; /*!< CRYP required parameters */ uint8_t *pCrypInBuffPtr; /*!< Pointer to CRYP processing (encryption, decryption,...) buffer */ uint8_t *pCrypOutBuffPtr; /*!< Pointer to CRYP processing (encryption, decryption,...) buffer */ __IO uint16_t CrypInCount; /*!< Counter of inputed data */ __IO uint16_t CrypOutCount; /*!< Counter of outputted data */ HAL_StatusTypeDef Status; /*!< CRYP peripheral status */ HAL_PhaseTypeDef Phase; /*!< CRYP peripheral phase */ DMA_HandleTypeDef *hdmain; /*!< CRYP In DMA handle parameters */ DMA_HandleTypeDef *hdmaout; /*!< CRYP Out DMA handle parameters */ HAL_LockTypeDef Lock; /*!< CRYP locking object */ __IO HAL_CRYP_STATETypeDef State; /*!< CRYP peripheral state */ }CRYP_HandleTypeDef; /** * @} */ /** * @} */ /* Exported constants --------------------------------------------------------*/ /** @defgroup CRYP_Exported_Constants CRYP Exported Constants * @{ */ /** @defgroup CRYP_Exported_Constants_Group1 CRYP CRYP_Key_Size * @{ */ #define CRYP_KEYSIZE_128B ((uint32_t)0x00000000) #define CRYP_KEYSIZE_192B CRYP_CR_KEYSIZE_0 #define CRYP_KEYSIZE_256B CRYP_CR_KEYSIZE_1 /** * @} */ /** @defgroup CRYP_Exported_Constants_Group2 CRYP CRYP_Data_Type * @{ */ #define CRYP_DATATYPE_32B ((uint32_t)0x00000000) #define CRYP_DATATYPE_16B CRYP_CR_DATATYPE_0 #define CRYP_DATATYPE_8B CRYP_CR_DATATYPE_1 #define CRYP_DATATYPE_1B CRYP_CR_DATATYPE /** * @} */ /** @defgroup CRYP_Exported_Constants_Group3 CRYP CRYP_AlgoModeDirection * @{ */ #define CRYP_CR_ALGOMODE_DIRECTION ((uint32_t)0x0008003C) #define CRYP_CR_ALGOMODE_TDES_ECB_ENCRYPT ((uint32_t)0x00000000) #define CRYP_CR_ALGOMODE_TDES_ECB_DECRYPT ((uint32_t)0x00000004) #define CRYP_CR_ALGOMODE_TDES_CBC_ENCRYPT ((uint32_t)0x00000008) #define CRYP_CR_ALGOMODE_TDES_CBC_DECRYPT ((uint32_t)0x0000000C) #define CRYP_CR_ALGOMODE_DES_ECB_ENCRYPT ((uint32_t)0x00000010) #define CRYP_CR_ALGOMODE_DES_ECB_DECRYPT ((uint32_t)0x00000014) #define CRYP_CR_ALGOMODE_DES_CBC_ENCRYPT ((uint32_t)0x00000018) #define CRYP_CR_ALGOMODE_DES_CBC_DECRYPT ((uint32_t)0x0000001C) #define CRYP_CR_ALGOMODE_AES_ECB_ENCRYPT ((uint32_t)0x00000020) #define CRYP_CR_ALGOMODE_AES_ECB_DECRYPT ((uint32_t)0x00000024) #define CRYP_CR_ALGOMODE_AES_CBC_ENCRYPT ((uint32_t)0x00000028) #define CRYP_CR_ALGOMODE_AES_CBC_DECRYPT ((uint32_t)0x0000002C) #define CRYP_CR_ALGOMODE_AES_CTR_ENCRYPT ((uint32_t)0x00000030) #define CRYP_CR_ALGOMODE_AES_CTR_DECRYPT ((uint32_t)0x00000034) /** * @} */ /** @defgroup CRYP_Exported_Constants_Group4 CRYP CRYP_Interrupt * @{ */ #define CRYP_IT_INI ((uint32_t)CRYP_IMSCR_INIM) /*!< Input FIFO Interrupt */ #define CRYP_IT_OUTI ((uint32_t)CRYP_IMSCR_OUTIM) /*!< Output FIFO Interrupt */ /** * @} */ /** @defgroup CRYP_Exported_Constants_Group5 CRYP CRYP_Flags * @{ */ #define CRYP_FLAG_BUSY ((uint32_t)0x00000010) /*!< The CRYP core is currently processing a block of data or a key preparation (for AES decryption). */ #define CRYP_FLAG_IFEM ((uint32_t)0x00000001) /*!< Input FIFO is empty */ #define CRYP_FLAG_IFNF ((uint32_t)0x00000002) /*!< Input FIFO is not Full */ #define CRYP_FLAG_OFNE ((uint32_t)0x00000004) /*!< Output FIFO is not empty */ #define CRYP_FLAG_OFFU ((uint32_t)0x00000008) /*!< Output FIFO is Full */ #define CRYP_FLAG_OUTRIS ((uint32_t)0x01000002) /*!< Output FIFO service raw interrupt status */ #define CRYP_FLAG_INRIS ((uint32_t)0x01000001) /*!< Input FIFO service raw interrupt status */ /** * @} */ /** * @} */ /* Exported macro ------------------------------------------------------------*/ /** @defgroup CRYP_Exported_Macros CRYP Exported Macros * @{ */ /** @brief Reset CRYP handle state * @param __HANDLE__: specifies the CRYP handle. * @retval None */ #define __HAL_CRYP_RESET_HANDLE_STATE(__HANDLE__) ((__HANDLE__)->State = HAL_CRYP_STATE_RESET) /** * @brief Enable/Disable the CRYP peripheral. * @param __HANDLE__: specifies the CRYP handle. * @retval None */ #define __HAL_CRYP_ENABLE(__HANDLE__) ((__HANDLE__)->Instance->CR |= CRYP_CR_CRYPEN) #define __HAL_CRYP_DISABLE(__HANDLE__) ((__HANDLE__)->Instance->CR &= ~CRYP_CR_CRYPEN) /** * @brief Flush the data FIFO. * @param __HANDLE__: specifies the CRYP handle. * @retval None */ #define __HAL_CRYP_FIFO_FLUSH(__HANDLE__) ((__HANDLE__)->Instance->CR |= CRYP_CR_FFLUSH) /** * @brief Set the algorithm mode: AES-ECB, AES-CBC, AES-CTR, DES-ECB, DES-CBC. * @param __HANDLE__: specifies the CRYP handle. * @param MODE: The algorithm mode. * @retval None */ #define __HAL_CRYP_SET_MODE(__HANDLE__, MODE) ((__HANDLE__)->Instance->CR |= (uint32_t)(MODE)) /** @brief Check whether the specified CRYP flag is set or not. * @param __HANDLE__: specifies the CRYP handle. * @param __FLAG__: specifies the flag to check. * This parameter can be one of the following values: * @arg CRYP_FLAG_BUSY: The CRYP core is currently processing a block of data * or a key preparation (for AES decryption). * @arg CRYP_FLAG_IFEM: Input FIFO is empty * @arg CRYP_FLAG_IFNF: Input FIFO is not full * @arg CRYP_FLAG_INRIS: Input FIFO service raw interrupt is pending * @arg CRYP_FLAG_OFNE: Output FIFO is not empty * @arg CRYP_FLAG_OFFU: Output FIFO is full * @arg CRYP_FLAG_OUTRIS: Input FIFO service raw interrupt is pending * @retval The new state of __FLAG__ (TRUE or FALSE). */ #define __HAL_CRYP_GET_FLAG(__HANDLE__, __FLAG__) ((((uint8_t)((__FLAG__) >> 24)) == 0x01)?((((__HANDLE__)->Instance->RISR) & ((__FLAG__) & CRYP_FLAG_MASK)) == ((__FLAG__) & CRYP_FLAG_MASK)): \ ((((__HANDLE__)->Instance->RISR) & ((__FLAG__) & CRYP_FLAG_MASK)) == ((__FLAG__) & CRYP_FLAG_MASK))) /** @brief Check whether the specified CRYP interrupt is set or not. * @param __HANDLE__: specifies the CRYP handle. * @param __INTERRUPT__: specifies the interrupt to check. * This parameter can be one of the following values: * @arg CRYP_IT_INRIS: Input FIFO service raw interrupt is pending * @arg CRYP_IT_OUTRIS: Output FIFO service raw interrupt is pending * @retval The new state of __INTERRUPT__ (TRUE or FALSE). */ #define __HAL_CRYP_GET_IT(__HANDLE__, __INTERRUPT__) (((__HANDLE__)->Instance->MISR & (__INTERRUPT__)) == (__INTERRUPT__)) /** * @brief Enable the CRYP interrupt. * @param __HANDLE__: specifies the CRYP handle. * @param __INTERRUPT__: CRYP Interrupt. * @retval None */ #define __HAL_CRYP_ENABLE_IT(__HANDLE__, __INTERRUPT__) (((__HANDLE__)->Instance->IMSCR) |= (__INTERRUPT__)) /** * @brief Disable the CRYP interrupt. * @param __HANDLE__: specifies the CRYP handle. * @param __INTERRUPT__: CRYP interrupt. * @retval None */ #define __HAL_CRYP_DISABLE_IT(__HANDLE__, __INTERRUPT__) (((__HANDLE__)->Instance->IMSCR) &= ~(__INTERRUPT__)) /** * @} */ /* Include CRYP HAL Extension module */ #include "stm32f4xx_hal_cryp_ex.h" /* Exported functions --------------------------------------------------------*/ /** @defgroup CRYP_Exported_Functions CRYP Exported Functions * @{ */ /** @addtogroup CRYP_Exported_Functions_Group1 * @{ */ HAL_StatusTypeDef HAL_CRYP_Init(CRYP_HandleTypeDef *hcryp); HAL_StatusTypeDef HAL_CRYP_DeInit(CRYP_HandleTypeDef *hcryp); void HAL_CRYP_MspInit(CRYP_HandleTypeDef *hcryp); void HAL_CRYP_MspDeInit(CRYP_HandleTypeDef *hcryp); /** * @} */ /** @addtogroup CRYP_Exported_Functions_Group2 * @{ */ /* AES encryption/decryption using polling ***********************************/ HAL_StatusTypeDef HAL_CRYP_AESECB_Encrypt(CRYP_HandleTypeDef *hcryp, uint8_t *pPlainData, uint16_t Size, uint8_t *pCypherData, uint32_t Timeout); HAL_StatusTypeDef HAL_CRYP_AESECB_Decrypt(CRYP_HandleTypeDef *hcryp, uint8_t *pCypherData, uint16_t Size, uint8_t *pPlainData, uint32_t Timeout); HAL_StatusTypeDef HAL_CRYP_AESCBC_Encrypt(CRYP_HandleTypeDef *hcryp, uint8_t *pPlainData, uint16_t Size, uint8_t *pCypherData, uint32_t Timeout); HAL_StatusTypeDef HAL_CRYP_AESCBC_Decrypt(CRYP_HandleTypeDef *hcryp, uint8_t *pCypherData, uint16_t Size, uint8_t *pPlainData, uint32_t Timeout); HAL_StatusTypeDef HAL_CRYP_AESCTR_Encrypt(CRYP_HandleTypeDef *hcryp, uint8_t *pPlainData, uint16_t Size, uint8_t *pCypherData, uint32_t Timeout); HAL_StatusTypeDef HAL_CRYP_AESCTR_Decrypt(CRYP_HandleTypeDef *hcryp, uint8_t *pCypherData, uint16_t Size, uint8_t *pPlainData, uint32_t Timeout); /* AES encryption/decryption using interrupt *********************************/ HAL_StatusTypeDef HAL_CRYP_AESECB_Encrypt_IT(CRYP_HandleTypeDef *hcryp, uint8_t *pPlainData, uint16_t Size, uint8_t *pCypherData); HAL_StatusTypeDef HAL_CRYP_AESCBC_Encrypt_IT(CRYP_HandleTypeDef *hcryp, uint8_t *pPlainData, uint16_t Size, uint8_t *pCypherData); HAL_StatusTypeDef HAL_CRYP_AESCTR_Encrypt_IT(CRYP_HandleTypeDef *hcryp, uint8_t *pPlainData, uint16_t Size, uint8_t *pCypherData); HAL_StatusTypeDef HAL_CRYP_AESECB_Decrypt_IT(CRYP_HandleTypeDef *hcryp, uint8_t *pCypherData, uint16_t Size, uint8_t *pPlainData); HAL_StatusTypeDef HAL_CRYP_AESCTR_Decrypt_IT(CRYP_HandleTypeDef *hcryp, uint8_t *pCypherData, uint16_t Size, uint8_t *pPlainData); HAL_StatusTypeDef HAL_CRYP_AESCBC_Decrypt_IT(CRYP_HandleTypeDef *hcryp, uint8_t *pCypherData, uint16_t Size, uint8_t *pPlainData); /* AES encryption/decryption using DMA ***************************************/ HAL_StatusTypeDef HAL_CRYP_AESECB_Encrypt_DMA(CRYP_HandleTypeDef *hcryp, uint8_t *pPlainData, uint16_t Size, uint8_t *pCypherData); HAL_StatusTypeDef HAL_CRYP_AESECB_Decrypt_DMA(CRYP_HandleTypeDef *hcryp, uint8_t *pCypherData, uint16_t Size, uint8_t *pPlainData); HAL_StatusTypeDef HAL_CRYP_AESCBC_Encrypt_DMA(CRYP_HandleTypeDef *hcryp, uint8_t *pPlainData, uint16_t Size, uint8_t *pCypherData); HAL_StatusTypeDef HAL_CRYP_AESCBC_Decrypt_DMA(CRYP_HandleTypeDef *hcryp, uint8_t *pCypherData, uint16_t Size, uint8_t *pPlainData); HAL_StatusTypeDef HAL_CRYP_AESCTR_Encrypt_DMA(CRYP_HandleTypeDef *hcryp, uint8_t *pPlainData, uint16_t Size, uint8_t *pCypherData); HAL_StatusTypeDef HAL_CRYP_AESCTR_Decrypt_DMA(CRYP_HandleTypeDef *hcryp, uint8_t *pCypherData, uint16_t Size, uint8_t *pPlainData); /** * @} */ /** @addtogroup CRYP_Exported_Functions_Group3 * @{ */ /* DES encryption/decryption using polling ***********************************/ HAL_StatusTypeDef HAL_CRYP_DESECB_Encrypt(CRYP_HandleTypeDef *hcryp, uint8_t *pPlainData, uint16_t Size, uint8_t *pCypherData, uint32_t Timeout); HAL_StatusTypeDef HAL_CRYP_DESCBC_Encrypt(CRYP_HandleTypeDef *hcryp, uint8_t *pPlainData, uint16_t Size, uint8_t *pCypherData, uint32_t Timeout); HAL_StatusTypeDef HAL_CRYP_DESECB_Decrypt(CRYP_HandleTypeDef *hcryp, uint8_t *pPlainData, uint16_t Size, uint8_t *pCypherData, uint32_t Timeout); HAL_StatusTypeDef HAL_CRYP_DESCBC_Decrypt(CRYP_HandleTypeDef *hcryp, uint8_t *pPlainData, uint16_t Size, uint8_t *pCypherData, uint32_t Timeout); /* DES encryption/decryption using interrupt *********************************/ HAL_StatusTypeDef HAL_CRYP_DESECB_Encrypt_IT(CRYP_HandleTypeDef *hcryp, uint8_t *pPlainData, uint16_t Size, uint8_t *pCypherData); HAL_StatusTypeDef HAL_CRYP_DESECB_Decrypt_IT(CRYP_HandleTypeDef *hcryp, uint8_t *pCypherData, uint16_t Size, uint8_t *pPlainData); HAL_StatusTypeDef HAL_CRYP_DESCBC_Encrypt_IT(CRYP_HandleTypeDef *hcryp, uint8_t *pPlainData, uint16_t Size, uint8_t *pCypherData); HAL_StatusTypeDef HAL_CRYP_DESCBC_Decrypt_IT(CRYP_HandleTypeDef *hcryp, uint8_t *pCypherData, uint16_t Size, uint8_t *pPlainData); /* DES encryption/decryption using DMA ***************************************/ HAL_StatusTypeDef HAL_CRYP_DESECB_Encrypt_DMA(CRYP_HandleTypeDef *hcryp, uint8_t *pPlainData, uint16_t Size, uint8_t *pCypherData); HAL_StatusTypeDef HAL_CRYP_DESECB_Decrypt_DMA(CRYP_HandleTypeDef *hcryp, uint8_t *pCypherData, uint16_t Size, uint8_t *pPlainData); HAL_StatusTypeDef HAL_CRYP_DESCBC_Encrypt_DMA(CRYP_HandleTypeDef *hcryp, uint8_t *pPlainData, uint16_t Size, uint8_t *pCypherData); HAL_StatusTypeDef HAL_CRYP_DESCBC_Decrypt_DMA(CRYP_HandleTypeDef *hcryp, uint8_t *pCypherData, uint16_t Size, uint8_t *pPlainData); /** * @} */ /** @addtogroup CRYP_Exported_Functions_Group4 * @{ */ /* TDES encryption/decryption using polling **********************************/ HAL_StatusTypeDef HAL_CRYP_TDESECB_Encrypt(CRYP_HandleTypeDef *hcryp, uint8_t *pPlainData, uint16_t Size, uint8_t *pCypherData, uint32_t Timeout); HAL_StatusTypeDef HAL_CRYP_TDESCBC_Encrypt(CRYP_HandleTypeDef *hcryp, uint8_t *pPlainData, uint16_t Size, uint8_t *pCypherData, uint32_t Timeout); HAL_StatusTypeDef HAL_CRYP_TDESECB_Decrypt(CRYP_HandleTypeDef *hcryp, uint8_t *pCypherData, uint16_t Size, uint8_t *pPlainData, uint32_t Timeout); HAL_StatusTypeDef HAL_CRYP_TDESCBC_Decrypt(CRYP_HandleTypeDef *hcryp, uint8_t *pCypherData, uint16_t Size, uint8_t *pPlainData, uint32_t Timeout); /* TDES encryption/decryption using interrupt ********************************/ HAL_StatusTypeDef HAL_CRYP_TDESECB_Encrypt_IT(CRYP_HandleTypeDef *hcryp, uint8_t *pPlainData, uint16_t Size, uint8_t *pCypherData); HAL_StatusTypeDef HAL_CRYP_TDESECB_Decrypt_IT(CRYP_HandleTypeDef *hcryp, uint8_t *pCypherData, uint16_t Size, uint8_t *pPlainData); HAL_StatusTypeDef HAL_CRYP_TDESCBC_Encrypt_IT(CRYP_HandleTypeDef *hcryp, uint8_t *pPlainData, uint16_t Size, uint8_t *pCypherData); HAL_StatusTypeDef HAL_CRYP_TDESCBC_Decrypt_IT(CRYP_HandleTypeDef *hcryp, uint8_t *pCypherData, uint16_t Size, uint8_t *pPlainData); /* TDES encryption/decryption using DMA **************************************/ HAL_StatusTypeDef HAL_CRYP_TDESECB_Encrypt_DMA(CRYP_HandleTypeDef *hcryp, uint8_t *pPlainData, uint16_t Size, uint8_t *pCypherData); HAL_StatusTypeDef HAL_CRYP_TDESECB_Decrypt_DMA(CRYP_HandleTypeDef *hcryp, uint8_t *pCypherData, uint16_t Size, uint8_t *pPlainData); HAL_StatusTypeDef HAL_CRYP_TDESCBC_Encrypt_DMA(CRYP_HandleTypeDef *hcryp, uint8_t *pPlainData, uint16_t Size, uint8_t *pCypherData); HAL_StatusTypeDef HAL_CRYP_TDESCBC_Decrypt_DMA(CRYP_HandleTypeDef *hcryp, uint8_t *pCypherData, uint16_t Size, uint8_t *pPlainData); /** * @} */ /** @addtogroup CRYP_Exported_Functions_Group5 * @{ */ void HAL_CRYP_InCpltCallback(CRYP_HandleTypeDef *hcryp); void HAL_CRYP_OutCpltCallback(CRYP_HandleTypeDef *hcryp); void HAL_CRYP_ErrorCallback(CRYP_HandleTypeDef *hcryp); /** * @} */ /** @addtogroup CRYP_Exported_Functions_Group6 * @{ */ void HAL_CRYP_IRQHandler(CRYP_HandleTypeDef *hcryp); /** * @} */ /** @addtogroup CRYP_Exported_Functions_Group7 * @{ */ HAL_CRYP_STATETypeDef HAL_CRYP_GetState(CRYP_HandleTypeDef *hcryp); /** * @} */ /** * @} */ /* Private types -------------------------------------------------------------*/ /** @defgroup CRYP_Private_Types CRYP Private Types * @{ */ /** * @} */ /* Private variables ---------------------------------------------------------*/ /** @defgroup CRYP_Private_Variables CRYP Private Variables * @{ */ /** * @} */ /* Private constants ---------------------------------------------------------*/ /** @defgroup CRYP_Private_Constants CRYP Private Constants * @{ */ #define CRYP_FLAG_MASK ((uint32_t)0x0000001F) /** * @} */ /* Private macros ------------------------------------------------------------*/ /** @defgroup CRYP_Private_Macros CRYP Private Macros * @{ */ #define IS_CRYP_KEYSIZE(__KEYSIZE__) (((__KEYSIZE__) == CRYP_KEYSIZE_128B) || \ ((__KEYSIZE__) == CRYP_KEYSIZE_192B) || \ ((__KEYSIZE__) == CRYP_KEYSIZE_256B)) #define IS_CRYP_DATATYPE(__DATATYPE__) (((__DATATYPE__) == CRYP_DATATYPE_32B) || \ ((__DATATYPE__) == CRYP_DATATYPE_16B) || \ ((__DATATYPE__) == CRYP_DATATYPE_8B) || \ ((__DATATYPE__) == CRYP_DATATYPE_1B)) /** * @} */ /* Private functions ---------------------------------------------------------*/ /** @defgroup CRYP_Private_Functions CRYP Private Functions * @{ */ /** * @} */ #endif /* STM32F415xx || STM32F417xx || STM32F437xx || STM32F439xx || STM32F479xx */ /** * @} */ /** * @} */ #ifdef __cplusplus } #endif #endif /* __STM32F4xx_HAL_CRYP_H */ /************************ (C) COPYRIGHT STMicroelectronics *****END OF FILE****/ ================================================ FILE: Zelig/mbed/TARGET_NUCLEO_F401RE/stm32f4xx_hal_cryp_ex.h ================================================ /** ****************************************************************************** * @file stm32f4xx_hal_cryp_ex.h * @author MCD Application Team * @version V1.4.1 * @date 09-October-2015 * @brief Header file of CRYP HAL Extension module. ****************************************************************************** * @attention * *

© COPYRIGHT(c) 2015 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. * ****************************************************************************** */ /* Define to prevent recursive inclusion -------------------------------------*/ #ifndef __STM32F4xx_HAL_CRYP_EX_H #define __STM32F4xx_HAL_CRYP_EX_H #ifdef __cplusplus extern "C" { #endif #if defined(STM32F437xx) || defined(STM32F439xx) || defined(STM32F479xx) /* Includes ------------------------------------------------------------------*/ #include "stm32f4xx_hal_def.h" /** @addtogroup STM32F4xx_HAL_Driver * @{ */ /** @addtogroup CRYPEx * @{ */ /* Exported types ------------------------------------------------------------*/ /* Exported constants --------------------------------------------------------*/ /** @defgroup CRYPEx_Exported_Constants CRYPEx Exported Constants * @{ */ /** @defgroup CRYPEx_Exported_Constants_Group1 CRYP AlgoModeDirection * @{ */ #define CRYP_CR_ALGOMODE_AES_GCM_ENCRYPT ((uint32_t)0x00080000) #define CRYP_CR_ALGOMODE_AES_GCM_DECRYPT ((uint32_t)0x00080004) #define CRYP_CR_ALGOMODE_AES_CCM_ENCRYPT ((uint32_t)0x00080008) #define CRYP_CR_ALGOMODE_AES_CCM_DECRYPT ((uint32_t)0x0008000C) /** * @} */ /** @defgroup CRYPEx_Exported_Constants_Group3 CRYP PhaseConfig * @brief The phases are relevant only to AES-GCM and AES-CCM * @{ */ #define CRYP_PHASE_INIT ((uint32_t)0x00000000) #define CRYP_PHASE_HEADER CRYP_CR_GCM_CCMPH_0 #define CRYP_PHASE_PAYLOAD CRYP_CR_GCM_CCMPH_1 #define CRYP_PHASE_FINAL CRYP_CR_GCM_CCMPH /** * @} */ /** * @} */ /* Exported macro ------------------------------------------------------------*/ /** @defgroup CRYPEx_Exported_Macros CRYP Exported Macros * @{ */ /** * @brief Set the phase: Init, header, payload, final. * This is relevant only for GCM and CCM modes. * @param __HANDLE__: specifies the CRYP handle. * @param __PHASE__: The phase. * @retval None */ #define __HAL_CRYP_SET_PHASE(__HANDLE__, __PHASE__) do{(__HANDLE__)->Instance->CR &= (uint32_t)(~CRYP_CR_GCM_CCMPH);\ (__HANDLE__)->Instance->CR |= (uint32_t)(__PHASE__);\ }while(0) /** * @} */ /* Exported functions --------------------------------------------------------*/ /** @defgroup CRYPEx_Exported_Functions CRYPEx Exported Functions * @{ */ /** @addtogroup CRYPEx_Exported_Functions_Group1 * @{ */ /* AES encryption/decryption using polling ***********************************/ HAL_StatusTypeDef HAL_CRYPEx_AESGCM_Encrypt(CRYP_HandleTypeDef *hcryp, uint8_t *pPlainData, uint16_t Size, uint8_t *pCypherData, uint32_t Timeout); HAL_StatusTypeDef HAL_CRYPEx_AESGCM_Decrypt(CRYP_HandleTypeDef *hcryp, uint8_t *pCypherData, uint16_t Size, uint8_t *pPlainData, uint32_t Timeout); HAL_StatusTypeDef HAL_CRYPEx_AESGCM_Finish(CRYP_HandleTypeDef *hcryp, uint32_t Size, uint8_t *AuthTag, uint32_t Timeout); HAL_StatusTypeDef HAL_CRYPEx_AESCCM_Encrypt(CRYP_HandleTypeDef *hcryp, uint8_t *pPlainData, uint16_t Size, uint8_t *pCypherData, uint32_t Timeout); HAL_StatusTypeDef HAL_CRYPEx_AESCCM_Decrypt(CRYP_HandleTypeDef *hcryp, uint8_t *pCypherData, uint16_t Size, uint8_t *pPlainData, uint32_t Timeout); HAL_StatusTypeDef HAL_CRYPEx_AESCCM_Finish(CRYP_HandleTypeDef *hcryp, uint8_t *AuthTag, uint32_t Timeout); /* AES encryption/decryption using interrupt *********************************/ HAL_StatusTypeDef HAL_CRYPEx_AESGCM_Encrypt_IT(CRYP_HandleTypeDef *hcryp, uint8_t *pPlainData, uint16_t Size, uint8_t *pCypherData); HAL_StatusTypeDef HAL_CRYPEx_AESGCM_Decrypt_IT(CRYP_HandleTypeDef *hcryp, uint8_t *pCypherData, uint16_t Size, uint8_t *pPlainData); HAL_StatusTypeDef HAL_CRYPEx_AESCCM_Encrypt_IT(CRYP_HandleTypeDef *hcryp, uint8_t *pPlainData, uint16_t Size, uint8_t *pCypherData); HAL_StatusTypeDef HAL_CRYPEx_AESCCM_Decrypt_IT(CRYP_HandleTypeDef *hcryp, uint8_t *pCypherData, uint16_t Size, uint8_t *pPlainData); /* AES encryption/decryption using DMA ***************************************/ HAL_StatusTypeDef HAL_CRYPEx_AESGCM_Encrypt_DMA(CRYP_HandleTypeDef *hcryp, uint8_t *pPlainData, uint16_t Size, uint8_t *pCypherData); HAL_StatusTypeDef HAL_CRYPEx_AESGCM_Decrypt_DMA(CRYP_HandleTypeDef *hcryp, uint8_t *pCypherData, uint16_t Size, uint8_t *pPlainData); HAL_StatusTypeDef HAL_CRYPEx_AESCCM_Encrypt_DMA(CRYP_HandleTypeDef *hcryp, uint8_t *pPlainData, uint16_t Size, uint8_t *pCypherData); HAL_StatusTypeDef HAL_CRYPEx_AESCCM_Decrypt_DMA(CRYP_HandleTypeDef *hcryp, uint8_t *pCypherData, uint16_t Size, uint8_t *pPlainData); /** * @} */ /** @addtogroup CRYPEx_Exported_Functions_Group2 * @{ */ void HAL_CRYPEx_GCMCCM_IRQHandler(CRYP_HandleTypeDef *hcryp); /** * @} */ /** * @} */ /* Private types -------------------------------------------------------------*/ /** @defgroup CRYPEx_Private_Types CRYPEx Private Types * @{ */ /** * @} */ /* Private variables ---------------------------------------------------------*/ /** @defgroup CRYPEx_Private_Variables CRYPEx Private Variables * @{ */ /** * @} */ /* Private constants ---------------------------------------------------------*/ /** @defgroup CRYPEx_Private_Constants CRYPEx Private Constants * @{ */ /** * @} */ /* Private macros ------------------------------------------------------------*/ /** @defgroup CRYPEx_Private_Macros CRYPEx Private Macros * @{ */ /** * @} */ /* Private functions ---------------------------------------------------------*/ /** @defgroup CRYPEx_Private_Functions CRYPEx Private Functions * @{ */ /** * @} */ #endif /* STM32F437xx || STM32F439xx || STM32F479xx */ /** * @} */ /** * @} */ #ifdef __cplusplus } #endif #endif /* __STM32F4xx_HAL_CRYP_EX_H */ /************************ (C) COPYRIGHT STMicroelectronics *****END OF FILE****/ ================================================ FILE: Zelig/mbed/TARGET_NUCLEO_F401RE/stm32f4xx_hal_dac.h ================================================ /** ****************************************************************************** * @file stm32f4xx_hal_dac.h * @author MCD Application Team * @version V1.4.1 * @date 09-October-2015 * @brief Header file of DAC HAL module. ****************************************************************************** * @attention * *

© COPYRIGHT(c) 2015 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. * ****************************************************************************** */ /* Define to prevent recursive inclusion -------------------------------------*/ #ifndef __STM32F4xx_HAL_DAC_H #define __STM32F4xx_HAL_DAC_H #ifdef __cplusplus extern "C" { #endif #if defined(STM32F405xx) || defined(STM32F415xx) || defined(STM32F407xx) || defined(STM32F417xx) ||\ defined(STM32F427xx) || defined(STM32F437xx) || defined(STM32F429xx) || defined(STM32F439xx) ||\ defined(STM32F410Tx) || defined(STM32F410Cx) || defined(STM32F410Rx) || defined(STM32F446xx) ||\ defined(STM32F469xx) || defined(STM32F479xx) /* Includes ------------------------------------------------------------------*/ #include "stm32f4xx_hal_def.h" /** @addtogroup STM32F4xx_HAL_Driver * @{ */ /** @addtogroup DAC * @{ */ /* Exported types ------------------------------------------------------------*/ /** @defgroup DAC_Exported_Types DAC Exported Types * @{ */ /** * @brief HAL State structures definition */ typedef enum { HAL_DAC_STATE_RESET = 0x00, /*!< DAC not yet initialized or disabled */ HAL_DAC_STATE_READY = 0x01, /*!< DAC initialized and ready for use */ HAL_DAC_STATE_BUSY = 0x02, /*!< DAC internal processing is ongoing */ HAL_DAC_STATE_TIMEOUT = 0x03, /*!< DAC timeout state */ HAL_DAC_STATE_ERROR = 0x04 /*!< DAC error state */ }HAL_DAC_StateTypeDef; /** * @brief DAC handle Structure definition */ typedef struct { DAC_TypeDef *Instance; /*!< Register base address */ __IO HAL_DAC_StateTypeDef State; /*!< DAC communication state */ HAL_LockTypeDef Lock; /*!< DAC locking object */ DMA_HandleTypeDef *DMA_Handle1; /*!< Pointer DMA handler for channel 1 */ DMA_HandleTypeDef *DMA_Handle2; /*!< Pointer DMA handler for channel 2 */ __IO uint32_t ErrorCode; /*!< DAC Error code */ }DAC_HandleTypeDef; /** * @brief DAC Configuration regular Channel structure definition */ typedef struct { uint32_t DAC_Trigger; /*!< Specifies the external trigger for the selected DAC channel. This parameter can be a value of @ref DAC_trigger_selection */ uint32_t DAC_OutputBuffer; /*!< Specifies whether the DAC channel output buffer is enabled or disabled. This parameter can be a value of @ref DAC_output_buffer */ }DAC_ChannelConfTypeDef; /** * @} */ /* Exported constants --------------------------------------------------------*/ /** @defgroup DAC_Exported_Constants DAC Exported Constants * @{ */ /** @defgroup DAC_Error_Code DAC Error Code * @{ */ #define HAL_DAC_ERROR_NONE 0x00 /*!< No error */ #define HAL_DAC_ERROR_DMAUNDERRUNCH1 0x01 /*!< DAC channel1 DAM underrun error */ #define HAL_DAC_ERROR_DMAUNDERRUNCH2 0x02 /*!< DAC channel2 DAM underrun error */ #define HAL_DAC_ERROR_DMA 0x04 /*!< DMA error */ /** * @} */ /** @defgroup DAC_trigger_selection DAC Trigger Selection * @{ */ #define DAC_TRIGGER_NONE ((uint32_t)0x00000000) /*!< Conversion is automatic once the DAC1_DHRxxxx register has been loaded, and not by external trigger */ #define DAC_TRIGGER_T2_TRGO ((uint32_t)(DAC_CR_TSEL1_2 | DAC_CR_TEN1)) /*!< TIM2 TRGO selected as external conversion trigger for DAC channel */ #define DAC_TRIGGER_T4_TRGO ((uint32_t)(DAC_CR_TSEL1_2 | DAC_CR_TSEL1_0 | DAC_CR_TEN1)) /*!< TIM4 TRGO selected as external conversion trigger for DAC channel */ #define DAC_TRIGGER_T5_TRGO ((uint32_t)(DAC_CR_TSEL1_1 | DAC_CR_TSEL1_0 | DAC_CR_TEN1)) /*!< TIM5 TRGO selected as external conversion trigger for DAC channel */ #define DAC_TRIGGER_T6_TRGO ((uint32_t)DAC_CR_TEN1) /*!< TIM6 TRGO selected as external conversion trigger for DAC channel */ #define DAC_TRIGGER_T7_TRGO ((uint32_t)(DAC_CR_TSEL1_1 | DAC_CR_TEN1)) /*!< TIM7 TRGO selected as external conversion trigger for DAC channel */ #define DAC_TRIGGER_T8_TRGO ((uint32_t)(DAC_CR_TSEL1_0 | DAC_CR_TEN1)) /*!< TIM8 TRGO selected as external conversion trigger for DAC channel */ #define DAC_TRIGGER_EXT_IT9 ((uint32_t)(DAC_CR_TSEL1_2 | DAC_CR_TSEL1_1 | DAC_CR_TEN1)) /*!< EXTI Line9 event selected as external conversion trigger for DAC channel */ #define DAC_TRIGGER_SOFTWARE ((uint32_t)(DAC_CR_TSEL1 | DAC_CR_TEN1)) /*!< Conversion started by software trigger for DAC channel */ /** * @} */ /** @defgroup DAC_output_buffer DAC Output Buffer * @{ */ #define DAC_OUTPUTBUFFER_ENABLE ((uint32_t)0x00000000) #define DAC_OUTPUTBUFFER_DISABLE ((uint32_t)DAC_CR_BOFF1) /** * @} */ /** @defgroup DAC_Channel_selection DAC Channel Selection * @{ */ #define DAC_CHANNEL_1 ((uint32_t)0x00000000) #define DAC_CHANNEL_2 ((uint32_t)0x00000010) /** * @} */ /** @defgroup DAC_data_alignment DAC Data Alignment * @{ */ #define DAC_ALIGN_12B_R ((uint32_t)0x00000000) #define DAC_ALIGN_12B_L ((uint32_t)0x00000004) #define DAC_ALIGN_8B_R ((uint32_t)0x00000008) /** * @} */ /** @defgroup DAC_flags_definition DAC Flags Definition * @{ */ #define DAC_FLAG_DMAUDR1 ((uint32_t)DAC_SR_DMAUDR1) #define DAC_FLAG_DMAUDR2 ((uint32_t)DAC_SR_DMAUDR2) /** * @} */ /** @defgroup DAC_IT_definition DAC IT Definition * @{ */ #define DAC_IT_DMAUDR1 ((uint32_t)DAC_SR_DMAUDR1) #define DAC_IT_DMAUDR2 ((uint32_t)DAC_SR_DMAUDR2) /** * @} */ /** * @} */ /* Exported macro ------------------------------------------------------------*/ /** @defgroup DAC_Exported_Macros DAC Exported Macros * @{ */ /** @brief Reset DAC handle state * @param __HANDLE__: specifies the DAC handle. * @retval None */ #define __HAL_DAC_RESET_HANDLE_STATE(__HANDLE__) ((__HANDLE__)->State = HAL_DAC_STATE_RESET) /** @brief Enable the DAC channel * @param __HANDLE__: specifies the DAC handle. * @param __DAC_Channel__: specifies the DAC channel * @retval None */ #define __HAL_DAC_ENABLE(__HANDLE__, __DAC_Channel__) ((__HANDLE__)->Instance->CR |= (DAC_CR_EN1 << (__DAC_Channel__))) /** @brief Disable the DAC channel * @param __HANDLE__: specifies the DAC handle * @param __DAC_Channel__: specifies the DAC channel. * @retval None */ #define __HAL_DAC_DISABLE(__HANDLE__, __DAC_Channel__) ((__HANDLE__)->Instance->CR &= ~(DAC_CR_EN1 << (__DAC_Channel__))) /** @brief Enable the DAC interrupt * @param __HANDLE__: specifies the DAC handle * @param __INTERRUPT__: specifies the DAC interrupt. * @retval None */ #define __HAL_DAC_ENABLE_IT(__HANDLE__, __INTERRUPT__) (((__HANDLE__)->Instance->CR) |= (__INTERRUPT__)) /** @brief Disable the DAC interrupt * @param __HANDLE__: specifies the DAC handle * @param __INTERRUPT__: specifies the DAC interrupt. * @retval None */ #define __HAL_DAC_DISABLE_IT(__HANDLE__, __INTERRUPT__) (((__HANDLE__)->Instance->CR) &= ~(__INTERRUPT__)) /** @brief Checks if the specified DAC interrupt source is enabled or disabled. * @param __HANDLE__: DAC handle * @param __INTERRUPT__: DAC interrupt source to check * This parameter can be any combination of the following values: * @arg DAC_IT_DMAUDR1: DAC channel 1 DMA underrun interrupt * @arg DAC_IT_DMAUDR2: DAC channel 2 DMA underrun interrupt * @retval State of interruption (SET or RESET) */ #define __HAL_DAC_GET_IT_SOURCE(__HANDLE__, __INTERRUPT__) (((__HANDLE__)->Instance->CR & (__INTERRUPT__)) == (__INTERRUPT__)) /** @brief Get the selected DAC's flag status. * @param __HANDLE__: specifies the DAC handle. * @param __FLAG__: specifies the flag to clear. * This parameter can be any combination of the following values: * @arg DAC_FLAG_DMAUDR1: DMA underrun 1 flag * @arg DAC_FLAG_DMAUDR2: DMA underrun 2 flag * @retval None */ #define __HAL_DAC_GET_FLAG(__HANDLE__, __FLAG__) ((((__HANDLE__)->Instance->SR) & (__FLAG__)) == (__FLAG__)) /** @brief Clear the DAC's flag. * @param __HANDLE__: specifies the DAC handle. * @param __FLAG__: specifies the flag to clear. * This parameter can be any combination of the following values: * @arg DAC_FLAG_DMAUDR1: DMA underrun 1 flag * @arg DAC_FLAG_DMAUDR2: DMA underrun 2 flag * @retval None */ #define __HAL_DAC_CLEAR_FLAG(__HANDLE__, __FLAG__) (((__HANDLE__)->Instance->SR) = (__FLAG__)) /** * @} */ /* Include DAC HAL Extension module */ #include "stm32f4xx_hal_dac_ex.h" /* Exported functions --------------------------------------------------------*/ /** @addtogroup DAC_Exported_Functions * @{ */ /** @addtogroup DAC_Exported_Functions_Group1 * @{ */ /* Initialization/de-initialization functions *********************************/ HAL_StatusTypeDef HAL_DAC_Init(DAC_HandleTypeDef* hdac); HAL_StatusTypeDef HAL_DAC_DeInit(DAC_HandleTypeDef* hdac); void HAL_DAC_MspInit(DAC_HandleTypeDef* hdac); void HAL_DAC_MspDeInit(DAC_HandleTypeDef* hdac); /** * @} */ /** @addtogroup DAC_Exported_Functions_Group2 * @{ */ /* I/O operation functions ****************************************************/ HAL_StatusTypeDef HAL_DAC_Start(DAC_HandleTypeDef* hdac, uint32_t Channel); HAL_StatusTypeDef HAL_DAC_Stop(DAC_HandleTypeDef* hdac, uint32_t Channel); HAL_StatusTypeDef HAL_DAC_Start_DMA(DAC_HandleTypeDef* hdac, uint32_t Channel, uint32_t* pData, uint32_t Length, uint32_t Alignment); HAL_StatusTypeDef HAL_DAC_Stop_DMA(DAC_HandleTypeDef* hdac, uint32_t Channel); uint32_t HAL_DAC_GetValue(DAC_HandleTypeDef* hdac, uint32_t Channel); /** * @} */ /** @addtogroup DAC_Exported_Functions_Group3 * @{ */ /* Peripheral Control functions ***********************************************/ HAL_StatusTypeDef HAL_DAC_ConfigChannel(DAC_HandleTypeDef* hdac, DAC_ChannelConfTypeDef* sConfig, uint32_t Channel); HAL_StatusTypeDef HAL_DAC_SetValue(DAC_HandleTypeDef* hdac, uint32_t Channel, uint32_t Alignment, uint32_t Data); /** * @} */ /** @addtogroup DAC_Exported_Functions_Group4 * @{ */ /* Peripheral State functions *************************************************/ HAL_DAC_StateTypeDef HAL_DAC_GetState(DAC_HandleTypeDef* hdac); void HAL_DAC_IRQHandler(DAC_HandleTypeDef* hdac); uint32_t HAL_DAC_GetError(DAC_HandleTypeDef *hdac); void HAL_DAC_ConvCpltCallbackCh1(DAC_HandleTypeDef* hdac); void HAL_DAC_ConvHalfCpltCallbackCh1(DAC_HandleTypeDef* hdac); void HAL_DAC_ErrorCallbackCh1(DAC_HandleTypeDef *hdac); void HAL_DAC_DMAUnderrunCallbackCh1(DAC_HandleTypeDef *hdac); /** * @} */ /** * @} */ /* Private types -------------------------------------------------------------*/ /* Private variables ---------------------------------------------------------*/ /* Private constants ---------------------------------------------------------*/ /** @defgroup DAC_Private_Constants DAC Private Constants * @{ */ /** * @} */ /* Private macros ------------------------------------------------------------*/ /** @defgroup DAC_Private_Macros DAC Private Macros * @{ */ #define IS_DAC_DATA(DATA) ((DATA) <= 0xFFF0) #define IS_DAC_ALIGN(ALIGN) (((ALIGN) == DAC_ALIGN_12B_R) || \ ((ALIGN) == DAC_ALIGN_12B_L) || \ ((ALIGN) == DAC_ALIGN_8B_R)) #define IS_DAC_CHANNEL(CHANNEL) (((CHANNEL) == DAC_CHANNEL_1) || \ ((CHANNEL) == DAC_CHANNEL_2)) #define IS_DAC_OUTPUT_BUFFER_STATE(STATE) (((STATE) == DAC_OUTPUTBUFFER_ENABLE) || \ ((STATE) == DAC_OUTPUTBUFFER_DISABLE)) #define IS_DAC_TRIGGER(TRIGGER) (((TRIGGER) == DAC_TRIGGER_NONE) || \ ((TRIGGER) == DAC_TRIGGER_T2_TRGO) || \ ((TRIGGER) == DAC_TRIGGER_T8_TRGO) || \ ((TRIGGER) == DAC_TRIGGER_T7_TRGO) || \ ((TRIGGER) == DAC_TRIGGER_T5_TRGO) || \ ((TRIGGER) == DAC_TRIGGER_T6_TRGO) || \ ((TRIGGER) == DAC_TRIGGER_T4_TRGO) || \ ((TRIGGER) == DAC_TRIGGER_EXT_IT9) || \ ((TRIGGER) == DAC_TRIGGER_SOFTWARE)) /** @brief Set DHR12R1 alignment * @param __ALIGNMENT__: specifies the DAC alignment * @retval None */ #define DAC_DHR12R1_ALIGNMENT(__ALIGNMENT__) (((uint32_t)0x00000008) + (__ALIGNMENT__)) /** @brief Set DHR12R2 alignment * @param __ALIGNMENT__: specifies the DAC alignment * @retval None */ #define DAC_DHR12R2_ALIGNMENT(__ALIGNMENT__) (((uint32_t)0x00000014) + (__ALIGNMENT__)) /** @brief Set DHR12RD alignment * @param __ALIGNMENT__: specifies the DAC alignment * @retval None */ #define DAC_DHR12RD_ALIGNMENT(__ALIGNMENT__) (((uint32_t)0x00000020) + (__ALIGNMENT__)) /** * @} */ /* Private functions ---------------------------------------------------------*/ /** @defgroup DAC_Private_Functions DAC Private Functions * @{ */ /** * @} */ #endif /* STM32F405xx || STM32F415xx || STM32F407xx || STM32F417xx ||\ STM32F427xx || STM32F437xx || STM32F429xx || STM32F439xx ||\ STM32F410xx || STM32F446xx || STM32F469xx || STM32F479xx */ /** * @} */ /** * @} */ #ifdef __cplusplus } #endif #endif /*__STM32F4xx_HAL_DAC_H */ /************************ (C) COPYRIGHT STMicroelectronics *****END OF FILE****/ ================================================ FILE: Zelig/mbed/TARGET_NUCLEO_F401RE/stm32f4xx_hal_dac_ex.h ================================================ /** ****************************************************************************** * @file stm32f4xx_hal_dac.h * @author MCD Application Team * @version V1.4.1 * @date 09-October-2015 * @brief Header file of DAC HAL Extension module. ****************************************************************************** * @attention * *

© COPYRIGHT(c) 2015 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. * ****************************************************************************** */ /* Define to prevent recursive inclusion -------------------------------------*/ #ifndef __STM32F4xx_HAL_DAC_EX_H #define __STM32F4xx_HAL_DAC_EX_H #ifdef __cplusplus extern "C" { #endif #if defined(STM32F405xx) || defined(STM32F415xx) || defined(STM32F407xx) || defined(STM32F417xx) ||\ defined(STM32F427xx) || defined(STM32F437xx) || defined(STM32F429xx) || defined(STM32F439xx) ||\ defined(STM32F410Tx) || defined(STM32F410Cx) || defined(STM32F410Rx) || defined(STM32F446xx) ||\ defined(STM32F469xx) || defined(STM32F479xx) /* Includes ------------------------------------------------------------------*/ #include "stm32f4xx_hal_def.h" /** @addtogroup STM32F4xx_HAL_Driver * @{ */ /** @addtogroup DACEx * @{ */ /* Exported types ------------------------------------------------------------*/ /* Exported constants --------------------------------------------------------*/ /** @defgroup DACEx_Exported_Constants DAC Exported Constants * @{ */ /** @defgroup DACEx_lfsrunmask_triangleamplitude DAC LFS Run Mask Triangle Amplitude * @{ */ #define DAC_LFSRUNMASK_BIT0 ((uint32_t)0x00000000) /*!< Unmask DAC channel LFSR bit0 for noise wave generation */ #define DAC_LFSRUNMASK_BITS1_0 ((uint32_t)DAC_CR_MAMP1_0) /*!< Unmask DAC channel LFSR bit[1:0] for noise wave generation */ #define DAC_LFSRUNMASK_BITS2_0 ((uint32_t)DAC_CR_MAMP1_1) /*!< Unmask DAC channel LFSR bit[2:0] for noise wave generation */ #define DAC_LFSRUNMASK_BITS3_0 ((uint32_t)DAC_CR_MAMP1_1 | DAC_CR_MAMP1_0)/*!< Unmask DAC channel LFSR bit[3:0] for noise wave generation */ #define DAC_LFSRUNMASK_BITS4_0 ((uint32_t)DAC_CR_MAMP1_2) /*!< Unmask DAC channel LFSR bit[4:0] for noise wave generation */ #define DAC_LFSRUNMASK_BITS5_0 ((uint32_t)DAC_CR_MAMP1_2 | DAC_CR_MAMP1_0) /*!< Unmask DAC channel LFSR bit[5:0] for noise wave generation */ #define DAC_LFSRUNMASK_BITS6_0 ((uint32_t)DAC_CR_MAMP1_2 | DAC_CR_MAMP1_1) /*!< Unmask DAC channel LFSR bit[6:0] for noise wave generation */ #define DAC_LFSRUNMASK_BITS7_0 ((uint32_t)DAC_CR_MAMP1_2 | DAC_CR_MAMP1_1 | DAC_CR_MAMP1_0) /*!< Unmask DAC channel LFSR bit[7:0] for noise wave generation */ #define DAC_LFSRUNMASK_BITS8_0 ((uint32_t)DAC_CR_MAMP1_3) /*!< Unmask DAC channel LFSR bit[8:0] for noise wave generation */ #define DAC_LFSRUNMASK_BITS9_0 ((uint32_t)DAC_CR_MAMP1_3 | DAC_CR_MAMP1_0) /*!< Unmask DAC channel LFSR bit[9:0] for noise wave generation */ #define DAC_LFSRUNMASK_BITS10_0 ((uint32_t)DAC_CR_MAMP1_3 | DAC_CR_MAMP1_1) /*!< Unmask DAC channel LFSR bit[10:0] for noise wave generation */ #define DAC_LFSRUNMASK_BITS11_0 ((uint32_t)DAC_CR_MAMP1_3 | DAC_CR_MAMP1_1 | DAC_CR_MAMP1_0) /*!< Unmask DAC channel LFSR bit[11:0] for noise wave generation */ #define DAC_TRIANGLEAMPLITUDE_1 ((uint32_t)0x00000000) /*!< Select max triangle amplitude of 1 */ #define DAC_TRIANGLEAMPLITUDE_3 ((uint32_t)DAC_CR_MAMP1_0) /*!< Select max triangle amplitude of 3 */ #define DAC_TRIANGLEAMPLITUDE_7 ((uint32_t)DAC_CR_MAMP1_1) /*!< Select max triangle amplitude of 7 */ #define DAC_TRIANGLEAMPLITUDE_15 ((uint32_t)DAC_CR_MAMP1_1 | DAC_CR_MAMP1_0) /*!< Select max triangle amplitude of 15 */ #define DAC_TRIANGLEAMPLITUDE_31 ((uint32_t)DAC_CR_MAMP1_2) /*!< Select max triangle amplitude of 31 */ #define DAC_TRIANGLEAMPLITUDE_63 ((uint32_t)DAC_CR_MAMP1_2 | DAC_CR_MAMP1_0) /*!< Select max triangle amplitude of 63 */ #define DAC_TRIANGLEAMPLITUDE_127 ((uint32_t)DAC_CR_MAMP1_2 | DAC_CR_MAMP1_1) /*!< Select max triangle amplitude of 127 */ #define DAC_TRIANGLEAMPLITUDE_255 ((uint32_t)DAC_CR_MAMP1_2 | DAC_CR_MAMP1_1 | DAC_CR_MAMP1_0) /*!< Select max triangle amplitude of 255 */ #define DAC_TRIANGLEAMPLITUDE_511 ((uint32_t)DAC_CR_MAMP1_3) /*!< Select max triangle amplitude of 511 */ #define DAC_TRIANGLEAMPLITUDE_1023 ((uint32_t)DAC_CR_MAMP1_3 | DAC_CR_MAMP1_0) /*!< Select max triangle amplitude of 1023 */ #define DAC_TRIANGLEAMPLITUDE_2047 ((uint32_t)DAC_CR_MAMP1_3 | DAC_CR_MAMP1_1) /*!< Select max triangle amplitude of 2047 */ #define DAC_TRIANGLEAMPLITUDE_4095 ((uint32_t)DAC_CR_MAMP1_3 | DAC_CR_MAMP1_1 | DAC_CR_MAMP1_0) /*!< Select max triangle amplitude of 4095 */ /** * @} */ /** * @} */ /* Exported macro ------------------------------------------------------------*/ /* Exported functions --------------------------------------------------------*/ /** @addtogroup DACEx_Exported_Functions * @{ */ /** @addtogroup DACEx_Exported_Functions_Group1 * @{ */ /* Extension features functions ***********************************************/ uint32_t HAL_DACEx_DualGetValue(DAC_HandleTypeDef* hdac); HAL_StatusTypeDef HAL_DACEx_TriangleWaveGenerate(DAC_HandleTypeDef* hdac, uint32_t Channel, uint32_t Amplitude); HAL_StatusTypeDef HAL_DACEx_NoiseWaveGenerate(DAC_HandleTypeDef* hdac, uint32_t Channel, uint32_t Amplitude); HAL_StatusTypeDef HAL_DACEx_DualSetValue(DAC_HandleTypeDef* hdac, uint32_t Alignment, uint32_t Data1, uint32_t Data2); void HAL_DACEx_ConvCpltCallbackCh2(DAC_HandleTypeDef* hdac); void HAL_DACEx_ConvHalfCpltCallbackCh2(DAC_HandleTypeDef* hdac); void HAL_DACEx_ErrorCallbackCh2(DAC_HandleTypeDef* hdac); void HAL_DACEx_DMAUnderrunCallbackCh2(DAC_HandleTypeDef* hdac); /** * @} */ /** * @} */ /* Private types -------------------------------------------------------------*/ /* Private variables ---------------------------------------------------------*/ /* Private constants ---------------------------------------------------------*/ /** @defgroup DACEx_Private_Constants DAC Private Constants * @{ */ /** * @} */ /* Private macros ------------------------------------------------------------*/ /** @defgroup DACEx_Private_Macros DAC Private Macros * @{ */ #define IS_DAC_LFSR_UNMASK_TRIANGLE_AMPLITUDE(VALUE) (((VALUE) == DAC_LFSRUNMASK_BIT0) || \ ((VALUE) == DAC_LFSRUNMASK_BITS1_0) || \ ((VALUE) == DAC_LFSRUNMASK_BITS2_0) || \ ((VALUE) == DAC_LFSRUNMASK_BITS3_0) || \ ((VALUE) == DAC_LFSRUNMASK_BITS4_0) || \ ((VALUE) == DAC_LFSRUNMASK_BITS5_0) || \ ((VALUE) == DAC_LFSRUNMASK_BITS6_0) || \ ((VALUE) == DAC_LFSRUNMASK_BITS7_0) || \ ((VALUE) == DAC_LFSRUNMASK_BITS8_0) || \ ((VALUE) == DAC_LFSRUNMASK_BITS9_0) || \ ((VALUE) == DAC_LFSRUNMASK_BITS10_0) || \ ((VALUE) == DAC_LFSRUNMASK_BITS11_0) || \ ((VALUE) == DAC_TRIANGLEAMPLITUDE_1) || \ ((VALUE) == DAC_TRIANGLEAMPLITUDE_3) || \ ((VALUE) == DAC_TRIANGLEAMPLITUDE_7) || \ ((VALUE) == DAC_TRIANGLEAMPLITUDE_15) || \ ((VALUE) == DAC_TRIANGLEAMPLITUDE_31) || \ ((VALUE) == DAC_TRIANGLEAMPLITUDE_63) || \ ((VALUE) == DAC_TRIANGLEAMPLITUDE_127) || \ ((VALUE) == DAC_TRIANGLEAMPLITUDE_255) || \ ((VALUE) == DAC_TRIANGLEAMPLITUDE_511) || \ ((VALUE) == DAC_TRIANGLEAMPLITUDE_1023) || \ ((VALUE) == DAC_TRIANGLEAMPLITUDE_2047) || \ ((VALUE) == DAC_TRIANGLEAMPLITUDE_4095)) /** * @} */ /* Private functions ---------------------------------------------------------*/ /** @defgroup DACEx_Private_Functions DAC Private Functions * @{ */ void DAC_DMAConvCpltCh2(DMA_HandleTypeDef *hdma); void DAC_DMAErrorCh2(DMA_HandleTypeDef *hdma); void DAC_DMAHalfConvCpltCh2(DMA_HandleTypeDef *hdma); /** * @} */ #endif /* STM32F405xx || STM32F415xx || STM32F407xx || STM32F417xx ||\ STM32F427xx || STM32F437xx || STM32F429xx || STM32F439xx ||\ STM32F410xx || STM32F446xx || STM32F469xx || STM32F479xx */ /** * @} */ /** * @} */ #ifdef __cplusplus } #endif #endif /*__STM32F4xx_HAL_DAC_EX_H */ /************************ (C) COPYRIGHT STMicroelectronics *****END OF FILE****/ ================================================ FILE: Zelig/mbed/TARGET_NUCLEO_F401RE/stm32f4xx_hal_dcmi.h ================================================ /** ****************************************************************************** * @file stm32f4xx_hal_dcmi.h * @author MCD Application Team * @version V1.4.1 * @date 09-October-2015 * @brief Header file of DCMI HAL module. ****************************************************************************** * @attention * *

© COPYRIGHT(c) 2015 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. * ****************************************************************************** */ /* Define to prevent recursive inclusion -------------------------------------*/ #ifndef __STM32F4xx_HAL_DCMI_H #define __STM32F4xx_HAL_DCMI_H #ifdef __cplusplus extern "C" { #endif #if defined(STM32F407xx) || defined(STM32F417xx) || defined(STM32F427xx) || defined(STM32F437xx) ||\ defined(STM32F429xx) || defined(STM32F439xx) || defined(STM32F446xx) || defined(STM32F469xx) ||\ defined(STM32F479xx) /* Includes ------------------------------------------------------------------*/ #include "stm32f4xx_hal_def.h" /* Include DCMI HAL Extended module */ /* (include on top of file since DCMI structures are defined in extended file) */ #include "stm32f4xx_hal_dcmi_ex.h" /** @addtogroup STM32F4xx_HAL_Driver * @{ */ /** @addtogroup DCMI DCMI * @brief DCMI HAL module driver * @{ */ /* Exported types ------------------------------------------------------------*/ /** @defgroup DCMI_Exported_Types DCMI Exported Types * @{ */ /** * @brief DCMI Error source */ typedef enum { DCMI_ERROR_SYNC = 1, /*!< Synchronisation error */ DCMI_OVERRUN = 2, /*!< DCMI Overrun */ }DCMI_ErrorTypeDef; /** * @brief HAL DCMI State structures definition */ typedef enum { HAL_DCMI_STATE_RESET = 0x00, /*!< DCMI not yet initialized or disabled */ HAL_DCMI_STATE_READY = 0x01, /*!< DCMI initialized and ready for use */ HAL_DCMI_STATE_BUSY = 0x02, /*!< DCMI internal processing is ongoing */ HAL_DCMI_STATE_TIMEOUT = 0x03, /*!< DCMI timeout state */ HAL_DCMI_STATE_ERROR = 0x04 /*!< DCMI error state */ }HAL_DCMI_StateTypeDef; /** * @brief DCMI handle Structure definition */ typedef struct { DCMI_TypeDef *Instance; /*!< DCMI Register base address */ DCMI_InitTypeDef Init; /*!< DCMI parameters */ HAL_LockTypeDef Lock; /*!< DCMI locking object */ __IO HAL_DCMI_StateTypeDef State; /*!< DCMI state */ __IO uint32_t XferCount; /*!< DMA transfer counter */ __IO uint32_t XferSize; /*!< DMA transfer size */ uint32_t XferTransferNumber; /*!< DMA transfer number */ uint32_t pBuffPtr; /*!< Pointer to DMA output buffer */ DMA_HandleTypeDef *DMA_Handle; /*!< Pointer to the DMA handler */ __IO uint32_t ErrorCode; /*!< DCMI Error code */ }DCMI_HandleTypeDef; /** * @} */ /* Exported constants --------------------------------------------------------*/ /** @defgroup DCMI_Exported_Constants DCMI Exported Constants * @{ */ /** @defgroup DCMI_Error_Code DCMI Error Code * @{ */ #define HAL_DCMI_ERROR_NONE ((uint32_t)0x00000000) /*!< No error */ #define HAL_DCMI_ERROR_OVF ((uint32_t)0x00000001) /*!< Overflow error */ #define HAL_DCMI_ERROR_SYNC ((uint32_t)0x00000002) /*!< Synchronization error */ #define HAL_DCMI_ERROR_TIMEOUT ((uint32_t)0x00000020) /*!< Timeout error */ /** * @} */ /** @defgroup DCMI_Capture_Mode DCMI Capture Mode * @{ */ #define DCMI_MODE_CONTINUOUS ((uint32_t)0x00000000) /*!< The received data are transferred continuously into the destination memory through the DMA */ #define DCMI_MODE_SNAPSHOT ((uint32_t)DCMI_CR_CM) /*!< Once activated, the interface waits for the start of frame and then transfers a single frame through the DMA */ /** * @} */ /** @defgroup DCMI_Synchronization_Mode DCMI Synchronization Mode * @{ */ #define DCMI_SYNCHRO_HARDWARE ((uint32_t)0x00000000) /*!< Hardware synchronization data capture (frame/line start/stop) is synchronized with the HSYNC/VSYNC signals */ #define DCMI_SYNCHRO_EMBEDDED ((uint32_t)DCMI_CR_ESS) /*!< Embedded synchronization data capture is synchronized with synchronization codes embedded in the data flow */ /** * @} */ /** @defgroup DCMI_PIXCK_Polarity DCMI PIXCK Polarity * @{ */ #define DCMI_PCKPOLARITY_FALLING ((uint32_t)0x00000000) /*!< Pixel clock active on Falling edge */ #define DCMI_PCKPOLARITY_RISING ((uint32_t)DCMI_CR_PCKPOL) /*!< Pixel clock active on Rising edge */ /** * @} */ /** @defgroup DCMI_VSYNC_Polarity DCMI VSYNC Polarity * @{ */ #define DCMI_VSPOLARITY_LOW ((uint32_t)0x00000000) /*!< Vertical synchronization active Low */ #define DCMI_VSPOLARITY_HIGH ((uint32_t)DCMI_CR_VSPOL) /*!< Vertical synchronization active High */ /** * @} */ /** @defgroup DCMI_HSYNC_Polarity DCMI HSYNC Polarity * @{ */ #define DCMI_HSPOLARITY_LOW ((uint32_t)0x00000000) /*!< Horizontal synchronization active Low */ #define DCMI_HSPOLARITY_HIGH ((uint32_t)DCMI_CR_HSPOL) /*!< Horizontal synchronization active High */ /** * @} */ /** @defgroup DCMI_MODE_JPEG DCMI MODE JPEG * @{ */ #define DCMI_JPEG_DISABLE ((uint32_t)0x00000000) /*!< Mode JPEG Disabled */ #define DCMI_JPEG_ENABLE ((uint32_t)DCMI_CR_JPEG) /*!< Mode JPEG Enabled */ /** * @} */ /** @defgroup DCMI_Capture_Rate DCMI Capture Rate * @{ */ #define DCMI_CR_ALL_FRAME ((uint32_t)0x00000000) /*!< All frames are captured */ #define DCMI_CR_ALTERNATE_2_FRAME ((uint32_t)DCMI_CR_FCRC_0) /*!< Every alternate frame captured */ #define DCMI_CR_ALTERNATE_4_FRAME ((uint32_t)DCMI_CR_FCRC_1) /*!< One frame in 4 frames captured */ /** * @} */ /** @defgroup DCMI_Extended_Data_Mode DCMI Extended Data Mode * @{ */ #define DCMI_EXTEND_DATA_8B ((uint32_t)0x00000000) /*!< Interface captures 8-bit data on every pixel clock */ #define DCMI_EXTEND_DATA_10B ((uint32_t)DCMI_CR_EDM_0) /*!< Interface captures 10-bit data on every pixel clock */ #define DCMI_EXTEND_DATA_12B ((uint32_t)DCMI_CR_EDM_1) /*!< Interface captures 12-bit data on every pixel clock */ #define DCMI_EXTEND_DATA_14B ((uint32_t)(DCMI_CR_EDM_0 | DCMI_CR_EDM_1)) /*!< Interface captures 14-bit data on every pixel clock */ /** * @} */ /** @defgroup DCMI_Window_Coordinate DCMI Window Coordinate * @{ */ #define DCMI_WINDOW_COORDINATE ((uint32_t)0x3FFF) /*!< Window coordinate */ /** * @} */ /** @defgroup DCMI_Window_Height DCMI Window Height * @{ */ #define DCMI_WINDOW_HEIGHT ((uint32_t)0x1FFF) /*!< Window Height */ /** * @} */ /** @defgroup DCMI_interrupt_sources DCMI interrupt sources * @{ */ #define DCMI_IT_FRAME ((uint32_t)DCMI_IER_FRAME_IE) #define DCMI_IT_OVF ((uint32_t)DCMI_IER_OVF_IE) #define DCMI_IT_ERR ((uint32_t)DCMI_IER_ERR_IE) #define DCMI_IT_VSYNC ((uint32_t)DCMI_IER_VSYNC_IE) #define DCMI_IT_LINE ((uint32_t)DCMI_IER_LINE_IE) /** * @} */ /** @defgroup DCMI_Flags DCMI Flags * @{ */ /** * @brief DCMI SR register */ #define DCMI_FLAG_HSYNC ((uint32_t)0x2001) #define DCMI_FLAG_VSYNC ((uint32_t)0x2002) #define DCMI_FLAG_FNE ((uint32_t)0x2004) /** * @brief DCMI RISR register */ #define DCMI_FLAG_FRAMERI ((uint32_t)DCMI_RISR_FRAME_RIS) #define DCMI_FLAG_OVFRI ((uint32_t)DCMI_RISR_OVF_RIS) #define DCMI_FLAG_ERRRI ((uint32_t)DCMI_RISR_ERR_RIS) #define DCMI_FLAG_VSYNCRI ((uint32_t)DCMI_RISR_VSYNC_RIS) #define DCMI_FLAG_LINERI ((uint32_t)DCMI_RISR_LINE_RIS) /** * @brief DCMI MISR register */ #define DCMI_FLAG_FRAMEMI ((uint32_t)0x1001) #define DCMI_FLAG_OVFMI ((uint32_t)0x1002) #define DCMI_FLAG_ERRMI ((uint32_t)0x1004) #define DCMI_FLAG_VSYNCMI ((uint32_t)0x1008) #define DCMI_FLAG_LINEMI ((uint32_t)0x1010) /** * @} */ /** * @} */ /* Exported macro ------------------------------------------------------------*/ /** @defgroup DCMI_Exported_Macros DCMI Exported Macros * @{ */ /** @brief Reset DCMI handle state * @param __HANDLE__: specifies the DCMI handle. * @retval None */ #define __HAL_DCMI_RESET_HANDLE_STATE(__HANDLE__) ((__HANDLE__)->State = HAL_DCMI_STATE_RESET) /** * @brief Enable the DCMI. * @param __HANDLE__: DCMI handle * @retval None */ #define __HAL_DCMI_ENABLE(__HANDLE__) ((__HANDLE__)->Instance->CR |= DCMI_CR_ENABLE) /** * @brief Disable the DCMI. * @param __HANDLE__: DCMI handle * @retval None */ #define __HAL_DCMI_DISABLE(__HANDLE__) ((__HANDLE__)->Instance->CR &= ~(DCMI_CR_ENABLE)) /* Interrupt & Flag management */ /** * @brief Get the DCMI pending flags. * @param __HANDLE__: DCMI handle * @param __FLAG__: Get the specified flag. * This parameter can be any combination of the following values: * @arg DCMI_FLAG_FRAMERI: Frame capture complete flag mask * @arg DCMI_FLAG_OVFRI: Overflow flag mask * @arg DCMI_FLAG_ERRRI: Synchronization error flag mask * @arg DCMI_FLAG_VSYNCRI: VSYNC flag mask * @arg DCMI_FLAG_LINERI: Line flag mask * @retval The state of FLAG. */ #define __HAL_DCMI_GET_FLAG(__HANDLE__, __FLAG__)\ ((((__FLAG__) & 0x3000) == 0x0)? ((__HANDLE__)->Instance->RISR & (__FLAG__)) :\ (((__FLAG__) & 0x2000) == 0x0)? ((__HANDLE__)->Instance->MISR & (__FLAG__)) : ((__HANDLE__)->Instance->SR & (__FLAG__))) /** * @brief Clear the DCMI pending flags. * @param __HANDLE__: DCMI handle * @param __FLAG__: specifies the flag to clear. * This parameter can be any combination of the following values: * @arg DCMI_FLAG_FRAMERI: Frame capture complete flag mask * @arg DCMI_FLAG_OVFRI: Overflow flag mask * @arg DCMI_FLAG_ERRRI: Synchronization error flag mask * @arg DCMI_FLAG_VSYNCRI: VSYNC flag mask * @arg DCMI_FLAG_LINERI: Line flag mask * @retval None */ #define __HAL_DCMI_CLEAR_FLAG(__HANDLE__, __FLAG__) ((__HANDLE__)->Instance->ICR = (__FLAG__)) /** * @brief Enable the specified DCMI interrupts. * @param __HANDLE__: DCMI handle * @param __INTERRUPT__: specifies the DCMI interrupt sources to be enabled. * This parameter can be any combination of the following values: * @arg DCMI_IT_FRAME: Frame capture complete interrupt mask * @arg DCMI_IT_OVF: Overflow interrupt mask * @arg DCMI_IT_ERR: Synchronization error interrupt mask * @arg DCMI_IT_VSYNC: VSYNC interrupt mask * @arg DCMI_IT_LINE: Line interrupt mask * @retval None */ #define __HAL_DCMI_ENABLE_IT(__HANDLE__, __INTERRUPT__) ((__HANDLE__)->Instance->IER |= (__INTERRUPT__)) /** * @brief Disable the specified DCMI interrupts. * @param __HANDLE__: DCMI handle * @param __INTERRUPT__: specifies the DCMI interrupt sources to be enabled. * This parameter can be any combination of the following values: * @arg DCMI_IT_FRAME: Frame capture complete interrupt mask * @arg DCMI_IT_OVF: Overflow interrupt mask * @arg DCMI_IT_ERR: Synchronization error interrupt mask * @arg DCMI_IT_VSYNC: VSYNC interrupt mask * @arg DCMI_IT_LINE: Line interrupt mask * @retval None */ #define __HAL_DCMI_DISABLE_IT(__HANDLE__, __INTERRUPT__) ((__HANDLE__)->Instance->IER &= ~(__INTERRUPT__)) /** * @brief Check whether the specified DCMI interrupt has occurred or not. * @param __HANDLE__: DCMI handle * @param __INTERRUPT__: specifies the DCMI interrupt source to check. * This parameter can be one of the following values: * @arg DCMI_IT_FRAME: Frame capture complete interrupt mask * @arg DCMI_IT_OVF: Overflow interrupt mask * @arg DCMI_IT_ERR: Synchronization error interrupt mask * @arg DCMI_IT_VSYNC: VSYNC interrupt mask * @arg DCMI_IT_LINE: Line interrupt mask * @retval The state of INTERRUPT. */ #define __HAL_DCMI_GET_IT_SOURCE(__HANDLE__, __INTERRUPT__) ((__HANDLE__)->Instance->MISR & (__INTERRUPT__)) /** * @} */ /* Exported functions --------------------------------------------------------*/ /** @addtogroup DCMI_Exported_Functions * @{ */ /** @addtogroup DCMI_Exported_Functions_Group1 * @{ */ /* Initialization and de-initialization functions *****************************/ HAL_StatusTypeDef HAL_DCMI_Init(DCMI_HandleTypeDef *hdcmi); HAL_StatusTypeDef HAL_DCMI_DeInit(DCMI_HandleTypeDef *hdcmi); void HAL_DCMI_MspInit(DCMI_HandleTypeDef* hdcmi); void HAL_DCMI_MspDeInit(DCMI_HandleTypeDef* hdcmi); /** * @} */ /** @addtogroup DCMI_Exported_Functions_Group2 * @{ */ /* IO operation functions *****************************************************/ HAL_StatusTypeDef HAL_DCMI_Start_DMA(DCMI_HandleTypeDef* hdcmi, uint32_t DCMI_Mode, uint32_t pData, uint32_t Length); HAL_StatusTypeDef HAL_DCMI_Stop(DCMI_HandleTypeDef* hdcmi); void HAL_DCMI_ErrorCallback(DCMI_HandleTypeDef *hdcmi); void HAL_DCMI_LineEventCallback(DCMI_HandleTypeDef *hdcmi); void HAL_DCMI_FrameEventCallback(DCMI_HandleTypeDef *hdcmi); void HAL_DCMI_VsyncEventCallback(DCMI_HandleTypeDef *hdcmi); void HAL_DCMI_IRQHandler(DCMI_HandleTypeDef *hdcmi); /** * @} */ /** @addtogroup DCMI_Exported_Functions_Group3 * @{ */ /* Peripheral Control functions ***********************************************/ HAL_StatusTypeDef HAL_DCMI_ConfigCROP(DCMI_HandleTypeDef *hdcmi, uint32_t X0, uint32_t Y0, uint32_t XSize, uint32_t YSize); HAL_StatusTypeDef HAL_DCMI_EnableCROP(DCMI_HandleTypeDef *hdcmi); HAL_StatusTypeDef HAL_DCMI_DisableCROP(DCMI_HandleTypeDef *hdcmi); /** * @} */ /** @addtogroup DCMI_Exported_Functions_Group4 * @{ */ /* Peripheral State functions *************************************************/ HAL_DCMI_StateTypeDef HAL_DCMI_GetState(DCMI_HandleTypeDef *hdcmi); uint32_t HAL_DCMI_GetError(DCMI_HandleTypeDef *hdcmi); /** * @} */ /** * @} */ /* Private types -------------------------------------------------------------*/ /* Private variables ---------------------------------------------------------*/ /* Private constants ---------------------------------------------------------*/ /* Private macro -------------------------------------------------------------*/ /** @defgroup DCMI_Private_Macros DCMI Private Macros * @{ */ #define IS_DCMI_CAPTURE_MODE(MODE)(((MODE) == DCMI_MODE_CONTINUOUS) || \ ((MODE) == DCMI_MODE_SNAPSHOT)) #define IS_DCMI_SYNCHRO(MODE)(((MODE) == DCMI_SYNCHRO_HARDWARE) || \ ((MODE) == DCMI_SYNCHRO_EMBEDDED)) #define IS_DCMI_PCKPOLARITY(POLARITY)(((POLARITY) == DCMI_PCKPOLARITY_FALLING) || \ ((POLARITY) == DCMI_PCKPOLARITY_RISING)) #define IS_DCMI_VSPOLARITY(POLARITY)(((POLARITY) == DCMI_VSPOLARITY_LOW) || \ ((POLARITY) == DCMI_VSPOLARITY_HIGH)) #define IS_DCMI_HSPOLARITY(POLARITY)(((POLARITY) == DCMI_HSPOLARITY_LOW) || \ ((POLARITY) == DCMI_HSPOLARITY_HIGH)) #define IS_DCMI_MODE_JPEG(JPEG_MODE)(((JPEG_MODE) == DCMI_JPEG_DISABLE) || \ ((JPEG_MODE) == DCMI_JPEG_ENABLE)) #define IS_DCMI_CAPTURE_RATE(RATE) (((RATE) == DCMI_CR_ALL_FRAME) || \ ((RATE) == DCMI_CR_ALTERNATE_2_FRAME) || \ ((RATE) == DCMI_CR_ALTERNATE_4_FRAME)) #define IS_DCMI_EXTENDED_DATA(DATA)(((DATA) == DCMI_EXTEND_DATA_8B) || \ ((DATA) == DCMI_EXTEND_DATA_10B) || \ ((DATA) == DCMI_EXTEND_DATA_12B) || \ ((DATA) == DCMI_EXTEND_DATA_14B)) #define IS_DCMI_WINDOW_COORDINATE(COORDINATE) ((COORDINATE) <= DCMI_WINDOW_COORDINATE) #define IS_DCMI_WINDOW_HEIGHT(HEIGHT) ((HEIGHT) <= DCMI_WINDOW_HEIGHT) /** * @} */ /* Private functions ---------------------------------------------------------*/ /** @addtogroup DCMI_Private_Functions DCMI Private Functions * @{ */ /** * @} */ #endif /* STM32F407xx || STM32F417xx || STM32F427xx || STM32F437xx ||\ STM32F429xx || STM32F439xx || STM32F446xx || STM32F469xx ||\ STM32F479xx */ /** * @} */ /** * @} */ #ifdef __cplusplus } #endif #endif /* __STM32F4xx_HAL_DCMI_H */ /************************ (C) COPYRIGHT STMicroelectronics *****END OF FILE****/ ================================================ FILE: Zelig/mbed/TARGET_NUCLEO_F401RE/stm32f4xx_hal_dcmi_ex.h ================================================ /** ****************************************************************************** * @file stm32f4xx_hal_dcmi_ex.h * @author MCD Application Team * @version V1.4.1 * @date 09-October-2015 * @brief Header file of DCMI Extension HAL module. ****************************************************************************** * @attention * *

© COPYRIGHT(c) 2015 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. * ****************************************************************************** */ /* Define to prevent recursive inclusion -------------------------------------*/ #ifndef __STM32F4xx_HAL_DCMI_EX_H #define __STM32F4xx_HAL_DCMI_EX_H #ifdef __cplusplus extern "C" { #endif #if defined(STM32F407xx) || defined(STM32F417xx) || defined(STM32F427xx) || defined(STM32F437xx) ||\ defined(STM32F429xx) || defined(STM32F439xx) || defined(STM32F446xx) || defined(STM32F469xx) ||\ defined(STM32F479xx) /* Includes ------------------------------------------------------------------*/ #include "stm32f4xx_hal_def.h" /** @addtogroup STM32F4xx_HAL_Driver * @{ */ /** @addtogroup DCMIEx * @brief DCMI HAL module driver * @{ */ /* Exported types ------------------------------------------------------------*/ /** @defgroup DCMIEx_Exported_Types DCMI Extended Exported Types * @{ */ /** * @brief DCMIEx Embedded Synchronisation CODE Init structure definition */ typedef struct { uint8_t FrameStartCode; /*!< Specifies the code of the frame start delimiter. */ uint8_t LineStartCode; /*!< Specifies the code of the line start delimiter. */ uint8_t LineEndCode; /*!< Specifies the code of the line end delimiter. */ uint8_t FrameEndCode; /*!< Specifies the code of the frame end delimiter. */ }DCMI_CodesInitTypeDef; /** * @brief DCMI Init structure definition */ typedef struct { uint32_t SynchroMode; /*!< Specifies the Synchronization Mode: Hardware or Embedded. This parameter can be a value of @ref DCMI_Synchronization_Mode */ uint32_t PCKPolarity; /*!< Specifies the Pixel clock polarity: Falling or Rising. This parameter can be a value of @ref DCMI_PIXCK_Polarity */ uint32_t VSPolarity; /*!< Specifies the Vertical synchronization polarity: High or Low. This parameter can be a value of @ref DCMI_VSYNC_Polarity */ uint32_t HSPolarity; /*!< Specifies the Horizontal synchronization polarity: High or Low. This parameter can be a value of @ref DCMI_HSYNC_Polarity */ uint32_t CaptureRate; /*!< Specifies the frequency of frame capture: All, 1/2 or 1/4. This parameter can be a value of @ref DCMI_Capture_Rate */ uint32_t ExtendedDataMode; /*!< Specifies the data width: 8-bit, 10-bit, 12-bit or 14-bit. This parameter can be a value of @ref DCMI_Extended_Data_Mode */ DCMI_CodesInitTypeDef SyncroCode; /*!< Specifies the code of the frame start delimiter. */ uint32_t JPEGMode; /*!< Enable or Disable the JPEG mode. This parameter can be a value of @ref DCMI_MODE_JPEG */ #if defined(STM32F446xx) || defined(STM32F469xx) || defined(STM32F479xx) uint32_t ByteSelectMode; /*!< Specifies the data to be captured by the interface This parameter can be a value of @ref DCMIEx_Byte_Select_Mode */ uint32_t ByteSelectStart; /*!< Specifies if the data to be captured by the interface is even or odd This parameter can be a value of @ref DCMIEx_Byte_Select_Start */ uint32_t LineSelectMode; /*!< Specifies the line of data to be captured by the interface This parameter can be a value of @ref DCMIEx_Line_Select_Mode */ uint32_t LineSelectStart; /*!< Specifies if the line of data to be captured by the interface is even or odd This parameter can be a value of @ref DCMIEx_Line_Select_Start */ #endif /* STM32F446xx || STM32F469xx || STM32F479xx */ }DCMI_InitTypeDef; /** * @} */ /* Exported constants --------------------------------------------------------*/ #if defined(STM32F446xx) || defined(STM32F469xx) || defined(STM32F479xx) /** @defgroup DCMIEx_Exported_Constants DCMI Exported Constants * @{ */ /** @defgroup DCMIEx_Byte_Select_Mode DCMI Byte Select Mode * @{ */ #define DCMI_BSM_ALL ((uint32_t)0x00000000) /*!< Interface captures all received data */ #define DCMI_BSM_OTHER ((uint32_t)DCMI_CR_BSM_0) /*!< Interface captures every other byte from the received data */ #define DCMI_BSM_ALTERNATE_4 ((uint32_t)DCMI_CR_BSM_1) /*!< Interface captures one byte out of four */ #define DCMI_BSM_ALTERNATE_2 ((uint32_t)(DCMI_CR_BSM_0 | DCMI_CR_BSM_1)) /*!< Interface captures two bytes out of four */ /** * @} */ /** @defgroup DCMIEx_Byte_Select_Start DCMI Byte Select Start * @{ */ #define DCMI_OEBS_ODD ((uint32_t)0x00000000) /*!< Interface captures first data from the frame/line start, second one being dropped */ #define DCMI_OEBS_EVEN ((uint32_t)DCMI_CR_OEBS) /*!< Interface captures second data from the frame/line start, first one being dropped */ /** * @} */ /** @defgroup DCMIEx_Line_Select_Mode DCMI Line Select Mode * @{ */ #define DCMI_LSM_ALL ((uint32_t)0x00000000) /*!< Interface captures all received lines */ #define DCMI_LSM_ALTERNATE_2 ((uint32_t)DCMI_CR_LSM) /*!< Interface captures one line out of two */ /** * @} */ /** @defgroup DCMIEx_Line_Select_Start DCMI Line Select Start * @{ */ #define DCMI_OELS_ODD ((uint32_t)0x00000000) /*!< Interface captures first line from the frame start, second one being dropped */ #define DCMI_OELS_EVEN ((uint32_t)DCMI_CR_OELS) /*!< Interface captures second line from the frame start, first one being dropped */ /** * @} */ /** * @} */ /* Exported macro ------------------------------------------------------------*/ /* Exported functions --------------------------------------------------------*/ /* Private types -------------------------------------------------------------*/ /* Private variables ---------------------------------------------------------*/ /* Private constants ---------------------------------------------------------*/ /* Private macro -------------------------------------------------------------*/ /** @defgroup DCMIEx_Private_Macros DCMI Extended Private Macros * @{ */ #define IS_DCMI_BYTE_SELECT_MODE(MODE)(((MODE) == DCMI_BSM_ALL) || \ ((MODE) == DCMI_BSM_OTHER) || \ ((MODE) == DCMI_BSM_ALTERNATE_4) || \ ((MODE) == DCMI_BSM_ALTERNATE_2)) #define IS_DCMI_BYTE_SELECT_START(POLARITY)(((POLARITY) == DCMI_OEBS_ODD) || \ ((POLARITY) == DCMI_OEBS_EVEN)) #define IS_DCMI_LINE_SELECT_MODE(MODE)(((MODE) == DCMI_LSM_ALL) || \ ((MODE) == DCMI_LSM_ALTERNATE_2)) #define IS_DCMI_LINE_SELECT_START(POLARITY)(((POLARITY) == DCMI_OELS_ODD) || \ ((POLARITY) == DCMI_OELS_EVEN)) #endif /* STM32F446xx || STM32F469xx || STM32F479xx */ /** * @} */ /* Private functions ---------------------------------------------------------*/ #endif /* STM32F407xx || STM32F417xx || STM32F427xx || STM32F437xx ||\ STM32F429xx || STM32F439xx || STM32F446xx || STM32F469xx ||\ STM32F479xx */ /** * @} */ /** * @} */ #ifdef __cplusplus } #endif #endif /* __STM32F4xx_HAL_DCMI_H */ /************************ (C) COPYRIGHT STMicroelectronics *****END OF FILE****/ ================================================ FILE: Zelig/mbed/TARGET_NUCLEO_F401RE/stm32f4xx_hal_def.h ================================================ /** ****************************************************************************** * @file stm32f4xx_hal_def.h * @author MCD Application Team * @version V1.4.1 * @date 09-October-2015 * @brief This file contains HAL common defines, enumeration, macros and * structures definitions. ****************************************************************************** * @attention * *

© COPYRIGHT(c) 2015 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. * ****************************************************************************** */ /* Define to prevent recursive inclusion -------------------------------------*/ #ifndef __STM32F4xx_HAL_DEF #define __STM32F4xx_HAL_DEF #ifdef __cplusplus extern "C" { #endif /* Includes ------------------------------------------------------------------*/ #include "stm32f4xx.h" #include "stm32_hal_legacy.h" #include /* Exported types ------------------------------------------------------------*/ /** * @brief HAL Status structures definition */ typedef enum { HAL_OK = 0x00, HAL_ERROR = 0x01, HAL_BUSY = 0x02, HAL_TIMEOUT = 0x03 } HAL_StatusTypeDef; /** * @brief HAL Lock structures definition */ typedef enum { HAL_UNLOCKED = 0x00, HAL_LOCKED = 0x01 } HAL_LockTypeDef; /* Exported macro ------------------------------------------------------------*/ #define HAL_MAX_DELAY 0xFFFFFFFF #define HAL_IS_BIT_SET(REG, BIT) (((REG) & (BIT)) != RESET) #define HAL_IS_BIT_CLR(REG, BIT) (((REG) & (BIT)) == RESET) #define __HAL_LINKDMA(__HANDLE__, __PPP_DMA_FIELD__, __DMA_HANDLE__) \ do{ \ (__HANDLE__)->__PPP_DMA_FIELD__ = &(__DMA_HANDLE__); \ (__DMA_HANDLE__).Parent = (__HANDLE__); \ } while(0) #define UNUSED(x) ((void)(x)) /** @brief Reset the Handle's State field. * @param __HANDLE__: specifies the Peripheral Handle. * @note This macro can be used for the following purpose: * - When the Handle is declared as local variable; before passing it as parameter * to HAL_PPP_Init() for the first time, it is mandatory to use this macro * to set to 0 the Handle's "State" field. * Otherwise, "State" field may have any random value and the first time the function * HAL_PPP_Init() is called, the low level hardware initialization will be missed * (i.e. HAL_PPP_MspInit() will not be executed). * - When there is a need to reconfigure the low level hardware: instead of calling * HAL_PPP_DeInit() then HAL_PPP_Init(), user can make a call to this macro then HAL_PPP_Init(). * In this later function, when the Handle's "State" field is set to 0, it will execute the function * HAL_PPP_MspInit() which will reconfigure the low level hardware. * @retval None */ #define __HAL_RESET_HANDLE_STATE(__HANDLE__) ((__HANDLE__)->State = 0) #if (USE_RTOS == 1) /* Reserved for future use */ #error USE_RTOS should be 0 in the current HAL release #else #define __HAL_LOCK(__HANDLE__) \ do{ \ if((__HANDLE__)->Lock == HAL_LOCKED) \ { \ return HAL_BUSY; \ } \ else \ { \ (__HANDLE__)->Lock = HAL_LOCKED; \ } \ }while (0) #define __HAL_UNLOCK(__HANDLE__) \ do{ \ (__HANDLE__)->Lock = HAL_UNLOCKED; \ }while (0) #endif /* USE_RTOS */ #if defined ( __GNUC__ ) #ifndef __weak #define __weak __attribute__((weak)) #endif /* __weak */ #ifndef __packed #define __packed __attribute__((__packed__)) #endif /* __packed */ #endif /* __GNUC__ */ /* Macro to get variable aligned on 4-bytes, for __ICCARM__ the directive "#pragma data_alignment=4" must be used instead */ #if defined (__GNUC__) /* GNU Compiler */ #ifndef __ALIGN_END #define __ALIGN_END __attribute__ ((aligned (4))) #endif /* __ALIGN_END */ #ifndef __ALIGN_BEGIN #define __ALIGN_BEGIN #endif /* __ALIGN_BEGIN */ #else #ifndef __ALIGN_END #define __ALIGN_END #endif /* __ALIGN_END */ #ifndef __ALIGN_BEGIN #if defined (__CC_ARM) /* ARM Compiler */ #define __ALIGN_BEGIN __align(4) #elif defined (__ICCARM__) /* IAR Compiler */ #define __ALIGN_BEGIN #endif /* __CC_ARM */ #endif /* __ALIGN_BEGIN */ #endif /* __GNUC__ */ /** * @brief __RAM_FUNC definition */ #if defined ( __CC_ARM ) /* ARM Compiler ------------ RAM functions are defined using the toolchain options. Functions that are executed in RAM should reside in a separate source module. Using the 'Options for File' dialog you can simply change the 'Code / Const' area of a module to a memory space in physical RAM. Available memory areas are declared in the 'Target' tab of the 'Options for Target' dialog. */ #define __RAM_FUNC HAL_StatusTypeDef #elif defined ( __ICCARM__ ) /* ICCARM Compiler --------------- RAM functions are defined using a specific toolchain keyword "__ramfunc". */ #define __RAM_FUNC __ramfunc HAL_StatusTypeDef #elif defined ( __GNUC__ ) /* GNU Compiler ------------ RAM functions are defined using a specific toolchain attribute "__attribute__((section(".RamFunc")))". */ #define __RAM_FUNC HAL_StatusTypeDef __attribute__((section(".RamFunc"))) #endif /** * @brief __NOINLINE definition */ #if defined ( __CC_ARM ) || defined ( __GNUC__ ) /* ARM & GNUCompiler ---------------- */ #define __NOINLINE __attribute__ ( (noinline) ) #elif defined ( __ICCARM__ ) /* ICCARM Compiler --------------- */ #define __NOINLINE _Pragma("optimize = no_inline") #endif #ifdef __cplusplus } #endif #endif /* ___STM32F4xx_HAL_DEF */ /************************ (C) COPYRIGHT STMicroelectronics *****END OF FILE****/ ================================================ FILE: Zelig/mbed/TARGET_NUCLEO_F401RE/stm32f4xx_hal_dma.h ================================================ /** ****************************************************************************** * @file stm32f4xx_hal_dma.h * @author MCD Application Team * @version V1.4.1 * @date 09-October-2015 * @brief Header file of DMA HAL module. ****************************************************************************** * @attention * *

© COPYRIGHT(c) 2015 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. * ****************************************************************************** */ /* Define to prevent recursive inclusion -------------------------------------*/ #ifndef __STM32F4xx_HAL_DMA_H #define __STM32F4xx_HAL_DMA_H #ifdef __cplusplus extern "C" { #endif /* Includes ------------------------------------------------------------------*/ #include "stm32f4xx_hal_def.h" /** @addtogroup STM32F4xx_HAL_Driver * @{ */ /** @addtogroup DMA * @{ */ /* Exported types ------------------------------------------------------------*/ /** @defgroup DMA_Exported_Types DMA Exported Types * @brief DMA Exported Types * @{ */ /** * @brief DMA Configuration Structure definition */ typedef struct { uint32_t Channel; /*!< Specifies the channel used for the specified stream. This parameter can be a value of @ref DMA_Channel_selection */ uint32_t Direction; /*!< Specifies if the data will be transferred from memory to peripheral, from memory to memory or from peripheral to memory. This parameter can be a value of @ref DMA_Data_transfer_direction */ uint32_t PeriphInc; /*!< Specifies whether the Peripheral address register should be incremented or not. This parameter can be a value of @ref DMA_Peripheral_incremented_mode */ uint32_t MemInc; /*!< Specifies whether the memory address register should be incremented or not. This parameter can be a value of @ref DMA_Memory_incremented_mode */ uint32_t PeriphDataAlignment; /*!< Specifies the Peripheral data width. This parameter can be a value of @ref DMA_Peripheral_data_size */ uint32_t MemDataAlignment; /*!< Specifies the Memory data width. This parameter can be a value of @ref DMA_Memory_data_size */ uint32_t Mode; /*!< Specifies the operation mode of the DMAy Streamx. This parameter can be a value of @ref DMA_mode @note The circular buffer mode cannot be used if the memory-to-memory data transfer is configured on the selected Stream */ uint32_t Priority; /*!< Specifies the software priority for the DMAy Streamx. This parameter can be a value of @ref DMA_Priority_level */ uint32_t FIFOMode; /*!< Specifies if the FIFO mode or Direct mode will be used for the specified stream. This parameter can be a value of @ref DMA_FIFO_direct_mode @note The Direct mode (FIFO mode disabled) cannot be used if the memory-to-memory data transfer is configured on the selected stream */ uint32_t FIFOThreshold; /*!< Specifies the FIFO threshold level. This parameter can be a value of @ref DMA_FIFO_threshold_level */ uint32_t MemBurst; /*!< Specifies the Burst transfer configuration for the memory transfers. It specifies the amount of data to be transferred in a single non interruptible transaction. This parameter can be a value of @ref DMA_Memory_burst @note The burst mode is possible only if the address Increment mode is enabled. */ uint32_t PeriphBurst; /*!< Specifies the Burst transfer configuration for the peripheral transfers. It specifies the amount of data to be transferred in a single non interruptable transaction. This parameter can be a value of @ref DMA_Peripheral_burst @note The burst mode is possible only if the address Increment mode is enabled. */ }DMA_InitTypeDef; /** * @brief HAL DMA State structures definition */ typedef enum { HAL_DMA_STATE_RESET = 0x00, /*!< DMA not yet initialized or disabled */ HAL_DMA_STATE_READY = 0x01, /*!< DMA initialized and ready for use */ HAL_DMA_STATE_READY_MEM0 = 0x11, /*!< DMA Mem0 process success */ HAL_DMA_STATE_READY_MEM1 = 0x21, /*!< DMA Mem1 process success */ HAL_DMA_STATE_READY_HALF_MEM0 = 0x31, /*!< DMA Mem0 Half process success */ HAL_DMA_STATE_READY_HALF_MEM1 = 0x41, /*!< DMA Mem1 Half process success */ HAL_DMA_STATE_BUSY = 0x02, /*!< DMA process is ongoing */ HAL_DMA_STATE_BUSY_MEM0 = 0x12, /*!< DMA Mem0 process is ongoing */ HAL_DMA_STATE_BUSY_MEM1 = 0x22, /*!< DMA Mem1 process is ongoing */ HAL_DMA_STATE_TIMEOUT = 0x03, /*!< DMA timeout state */ HAL_DMA_STATE_ERROR = 0x04, /*!< DMA error state */ }HAL_DMA_StateTypeDef; /** * @brief HAL DMA Error Code structure definition */ typedef enum { HAL_DMA_FULL_TRANSFER = 0x00, /*!< Full transfer */ HAL_DMA_HALF_TRANSFER = 0x01, /*!< Half Transfer */ }HAL_DMA_LevelCompleteTypeDef; /** * @brief DMA handle Structure definition */ typedef struct __DMA_HandleTypeDef { DMA_Stream_TypeDef *Instance; /*!< Register base address */ DMA_InitTypeDef Init; /*!< DMA communication parameters */ HAL_LockTypeDef Lock; /*!< DMA locking object */ __IO HAL_DMA_StateTypeDef State; /*!< DMA transfer state */ void *Parent; /*!< Parent object state */ void (* XferCpltCallback)( struct __DMA_HandleTypeDef * hdma); /*!< DMA transfer complete callback */ void (* XferHalfCpltCallback)( struct __DMA_HandleTypeDef * hdma); /*!< DMA Half transfer complete callback */ void (* XferM1CpltCallback)( struct __DMA_HandleTypeDef * hdma); /*!< DMA transfer complete Memory1 callback */ void (* XferErrorCallback)( struct __DMA_HandleTypeDef * hdma); /*!< DMA transfer error callback */ __IO uint32_t ErrorCode; /*!< DMA Error code */ uint32_t StreamBaseAddress; /*!< DMA Stream Base Address */ uint32_t StreamIndex; /*!< DMA Stream Index */ }DMA_HandleTypeDef; /** * @} */ /* Exported constants --------------------------------------------------------*/ /** @defgroup DMA_Exported_Constants DMA Exported Constants * @brief DMA Exported constants * @{ */ /** @defgroup DMA_Error_Code DMA Error Code * @brief DMA Error Code * @{ */ #define HAL_DMA_ERROR_NONE ((uint32_t)0x00000000) /*!< No error */ #define HAL_DMA_ERROR_TE ((uint32_t)0x00000001) /*!< Transfer error */ #define HAL_DMA_ERROR_FE ((uint32_t)0x00000002) /*!< FIFO error */ #define HAL_DMA_ERROR_DME ((uint32_t)0x00000004) /*!< Direct Mode error */ #define HAL_DMA_ERROR_TIMEOUT ((uint32_t)0x00000020) /*!< Timeout error */ /** * @} */ /** @defgroup DMA_Channel_selection DMA Channel selection * @brief DMA channel selection * @{ */ #define DMA_CHANNEL_0 ((uint32_t)0x00000000) /*!< DMA Channel 0 */ #define DMA_CHANNEL_1 ((uint32_t)0x02000000) /*!< DMA Channel 1 */ #define DMA_CHANNEL_2 ((uint32_t)0x04000000) /*!< DMA Channel 2 */ #define DMA_CHANNEL_3 ((uint32_t)0x06000000) /*!< DMA Channel 3 */ #define DMA_CHANNEL_4 ((uint32_t)0x08000000) /*!< DMA Channel 4 */ #define DMA_CHANNEL_5 ((uint32_t)0x0A000000) /*!< DMA Channel 5 */ #define DMA_CHANNEL_6 ((uint32_t)0x0C000000) /*!< DMA Channel 6 */ #define DMA_CHANNEL_7 ((uint32_t)0x0E000000) /*!< DMA Channel 7 */ /** * @} */ /** @defgroup DMA_Data_transfer_direction DMA Data transfer direction * @brief DMA data transfer direction * @{ */ #define DMA_PERIPH_TO_MEMORY ((uint32_t)0x00000000) /*!< Peripheral to memory direction */ #define DMA_MEMORY_TO_PERIPH ((uint32_t)DMA_SxCR_DIR_0) /*!< Memory to peripheral direction */ #define DMA_MEMORY_TO_MEMORY ((uint32_t)DMA_SxCR_DIR_1) /*!< Memory to memory direction */ /** * @} */ /** @defgroup DMA_Peripheral_incremented_mode DMA Peripheral incremented mode * @brief DMA peripheral incremented mode * @{ */ #define DMA_PINC_ENABLE ((uint32_t)DMA_SxCR_PINC) /*!< Peripheral increment mode enable */ #define DMA_PINC_DISABLE ((uint32_t)0x00000000) /*!< Peripheral increment mode disable */ /** * @} */ /** @defgroup DMA_Memory_incremented_mode DMA Memory incremented mode * @brief DMA memory incremented mode * @{ */ #define DMA_MINC_ENABLE ((uint32_t)DMA_SxCR_MINC) /*!< Memory increment mode enable */ #define DMA_MINC_DISABLE ((uint32_t)0x00000000) /*!< Memory increment mode disable */ /** * @} */ /** @defgroup DMA_Peripheral_data_size DMA Peripheral data size * @brief DMA peripheral data size * @{ */ #define DMA_PDATAALIGN_BYTE ((uint32_t)0x00000000) /*!< Peripheral data alignment: Byte */ #define DMA_PDATAALIGN_HALFWORD ((uint32_t)DMA_SxCR_PSIZE_0) /*!< Peripheral data alignment: HalfWord */ #define DMA_PDATAALIGN_WORD ((uint32_t)DMA_SxCR_PSIZE_1) /*!< Peripheral data alignment: Word */ /** * @} */ /** @defgroup DMA_Memory_data_size DMA Memory data size * @brief DMA memory data size * @{ */ #define DMA_MDATAALIGN_BYTE ((uint32_t)0x00000000) /*!< Memory data alignment: Byte */ #define DMA_MDATAALIGN_HALFWORD ((uint32_t)DMA_SxCR_MSIZE_0) /*!< Memory data alignment: HalfWord */ #define DMA_MDATAALIGN_WORD ((uint32_t)DMA_SxCR_MSIZE_1) /*!< Memory data alignment: Word */ /** * @} */ /** @defgroup DMA_mode DMA mode * @brief DMA mode * @{ */ #define DMA_NORMAL ((uint32_t)0x00000000) /*!< Normal mode */ #define DMA_CIRCULAR ((uint32_t)DMA_SxCR_CIRC) /*!< Circular mode */ #define DMA_PFCTRL ((uint32_t)DMA_SxCR_PFCTRL) /*!< Peripheral flow control mode */ /** * @} */ /** @defgroup DMA_Priority_level DMA Priority level * @brief DMA priority levels * @{ */ #define DMA_PRIORITY_LOW ((uint32_t)0x00000000) /*!< Priority level: Low */ #define DMA_PRIORITY_MEDIUM ((uint32_t)DMA_SxCR_PL_0) /*!< Priority level: Medium */ #define DMA_PRIORITY_HIGH ((uint32_t)DMA_SxCR_PL_1) /*!< Priority level: High */ #define DMA_PRIORITY_VERY_HIGH ((uint32_t)DMA_SxCR_PL) /*!< Priority level: Very High */ /** * @} */ /** @defgroup DMA_FIFO_direct_mode DMA FIFO direct mode * @brief DMA FIFO direct mode * @{ */ #define DMA_FIFOMODE_DISABLE ((uint32_t)0x00000000) /*!< FIFO mode disable */ #define DMA_FIFOMODE_ENABLE ((uint32_t)DMA_SxFCR_DMDIS) /*!< FIFO mode enable */ /** * @} */ /** @defgroup DMA_FIFO_threshold_level DMA FIFO threshold level * @brief DMA FIFO level * @{ */ #define DMA_FIFO_THRESHOLD_1QUARTERFULL ((uint32_t)0x00000000) /*!< FIFO threshold 1 quart full configuration */ #define DMA_FIFO_THRESHOLD_HALFFULL ((uint32_t)DMA_SxFCR_FTH_0) /*!< FIFO threshold half full configuration */ #define DMA_FIFO_THRESHOLD_3QUARTERSFULL ((uint32_t)DMA_SxFCR_FTH_1) /*!< FIFO threshold 3 quarts full configuration */ #define DMA_FIFO_THRESHOLD_FULL ((uint32_t)DMA_SxFCR_FTH) /*!< FIFO threshold full configuration */ /** * @} */ /** @defgroup DMA_Memory_burst DMA Memory burst * @brief DMA memory burst * @{ */ #define DMA_MBURST_SINGLE ((uint32_t)0x00000000) #define DMA_MBURST_INC4 ((uint32_t)DMA_SxCR_MBURST_0) #define DMA_MBURST_INC8 ((uint32_t)DMA_SxCR_MBURST_1) #define DMA_MBURST_INC16 ((uint32_t)DMA_SxCR_MBURST) /** * @} */ /** @defgroup DMA_Peripheral_burst DMA Peripheral burst * @brief DMA peripheral burst * @{ */ #define DMA_PBURST_SINGLE ((uint32_t)0x00000000) #define DMA_PBURST_INC4 ((uint32_t)DMA_SxCR_PBURST_0) #define DMA_PBURST_INC8 ((uint32_t)DMA_SxCR_PBURST_1) #define DMA_PBURST_INC16 ((uint32_t)DMA_SxCR_PBURST) /** * @} */ /** @defgroup DMA_interrupt_enable_definitions DMA interrupt enable definitions * @brief DMA interrupts definition * @{ */ #define DMA_IT_TC ((uint32_t)DMA_SxCR_TCIE) #define DMA_IT_HT ((uint32_t)DMA_SxCR_HTIE) #define DMA_IT_TE ((uint32_t)DMA_SxCR_TEIE) #define DMA_IT_DME ((uint32_t)DMA_SxCR_DMEIE) #define DMA_IT_FE ((uint32_t)0x00000080) /** * @} */ /** @defgroup DMA_flag_definitions DMA flag definitions * @brief DMA flag definitions * @{ */ #define DMA_FLAG_FEIF0_4 ((uint32_t)0x00800001) #define DMA_FLAG_DMEIF0_4 ((uint32_t)0x00800004) #define DMA_FLAG_TEIF0_4 ((uint32_t)0x00000008) #define DMA_FLAG_HTIF0_4 ((uint32_t)0x00000010) #define DMA_FLAG_TCIF0_4 ((uint32_t)0x00000020) #define DMA_FLAG_FEIF1_5 ((uint32_t)0x00000040) #define DMA_FLAG_DMEIF1_5 ((uint32_t)0x00000100) #define DMA_FLAG_TEIF1_5 ((uint32_t)0x00000200) #define DMA_FLAG_HTIF1_5 ((uint32_t)0x00000400) #define DMA_FLAG_TCIF1_5 ((uint32_t)0x00000800) #define DMA_FLAG_FEIF2_6 ((uint32_t)0x00010000) #define DMA_FLAG_DMEIF2_6 ((uint32_t)0x00040000) #define DMA_FLAG_TEIF2_6 ((uint32_t)0x00080000) #define DMA_FLAG_HTIF2_6 ((uint32_t)0x00100000) #define DMA_FLAG_TCIF2_6 ((uint32_t)0x00200000) #define DMA_FLAG_FEIF3_7 ((uint32_t)0x00400000) #define DMA_FLAG_DMEIF3_7 ((uint32_t)0x01000000) #define DMA_FLAG_TEIF3_7 ((uint32_t)0x02000000) #define DMA_FLAG_HTIF3_7 ((uint32_t)0x04000000) #define DMA_FLAG_TCIF3_7 ((uint32_t)0x08000000) /** * @} */ /** * @} */ /* Exported macro ------------------------------------------------------------*/ /** @brief Reset DMA handle state * @param __HANDLE__: specifies the DMA handle. * @retval None */ #define __HAL_DMA_RESET_HANDLE_STATE(__HANDLE__) ((__HANDLE__)->State = HAL_DMA_STATE_RESET) /** * @brief Return the current DMA Stream FIFO filled level. * @param __HANDLE__: DMA handle * @retval The FIFO filling state. * - DMA_FIFOStatus_Less1QuarterFull: when FIFO is less than 1 quarter-full * and not empty. * - DMA_FIFOStatus_1QuarterFull: if more than 1 quarter-full. * - DMA_FIFOStatus_HalfFull: if more than 1 half-full. * - DMA_FIFOStatus_3QuartersFull: if more than 3 quarters-full. * - DMA_FIFOStatus_Empty: when FIFO is empty * - DMA_FIFOStatus_Full: when FIFO is full */ #define __HAL_DMA_GET_FS(__HANDLE__) (((__HANDLE__)->Instance->FCR & (DMA_SxFCR_FS))) /** * @brief Enable the specified DMA Stream. * @param __HANDLE__: DMA handle * @retval None */ #define __HAL_DMA_ENABLE(__HANDLE__) ((__HANDLE__)->Instance->CR |= DMA_SxCR_EN) /** * @brief Disable the specified DMA Stream. * @param __HANDLE__: DMA handle * @retval None */ #define __HAL_DMA_DISABLE(__HANDLE__) ((__HANDLE__)->Instance->CR &= ~DMA_SxCR_EN) /* Interrupt & Flag management */ /** * @brief Return the current DMA Stream transfer complete flag. * @param __HANDLE__: DMA handle * @retval The specified transfer complete flag index. */ #define __HAL_DMA_GET_TC_FLAG_INDEX(__HANDLE__) \ (((uint32_t)((__HANDLE__)->Instance) == ((uint32_t)DMA1_Stream0))? DMA_FLAG_TCIF0_4 :\ ((uint32_t)((__HANDLE__)->Instance) == ((uint32_t)DMA2_Stream0))? DMA_FLAG_TCIF0_4 :\ ((uint32_t)((__HANDLE__)->Instance) == ((uint32_t)DMA1_Stream4))? DMA_FLAG_TCIF0_4 :\ ((uint32_t)((__HANDLE__)->Instance) == ((uint32_t)DMA2_Stream4))? DMA_FLAG_TCIF0_4 :\ ((uint32_t)((__HANDLE__)->Instance) == ((uint32_t)DMA1_Stream1))? DMA_FLAG_TCIF1_5 :\ ((uint32_t)((__HANDLE__)->Instance) == ((uint32_t)DMA2_Stream1))? DMA_FLAG_TCIF1_5 :\ ((uint32_t)((__HANDLE__)->Instance) == ((uint32_t)DMA1_Stream5))? DMA_FLAG_TCIF1_5 :\ ((uint32_t)((__HANDLE__)->Instance) == ((uint32_t)DMA2_Stream5))? DMA_FLAG_TCIF1_5 :\ ((uint32_t)((__HANDLE__)->Instance) == ((uint32_t)DMA1_Stream2))? DMA_FLAG_TCIF2_6 :\ ((uint32_t)((__HANDLE__)->Instance) == ((uint32_t)DMA2_Stream2))? DMA_FLAG_TCIF2_6 :\ ((uint32_t)((__HANDLE__)->Instance) == ((uint32_t)DMA1_Stream6))? DMA_FLAG_TCIF2_6 :\ ((uint32_t)((__HANDLE__)->Instance) == ((uint32_t)DMA2_Stream6))? DMA_FLAG_TCIF2_6 :\ DMA_FLAG_TCIF3_7) /** * @brief Return the current DMA Stream half transfer complete flag. * @param __HANDLE__: DMA handle * @retval The specified half transfer complete flag index. */ #define __HAL_DMA_GET_HT_FLAG_INDEX(__HANDLE__)\ (((uint32_t)((__HANDLE__)->Instance) == ((uint32_t)DMA1_Stream0))? DMA_FLAG_HTIF0_4 :\ ((uint32_t)((__HANDLE__)->Instance) == ((uint32_t)DMA2_Stream0))? DMA_FLAG_HTIF0_4 :\ ((uint32_t)((__HANDLE__)->Instance) == ((uint32_t)DMA1_Stream4))? DMA_FLAG_HTIF0_4 :\ ((uint32_t)((__HANDLE__)->Instance) == ((uint32_t)DMA2_Stream4))? DMA_FLAG_HTIF0_4 :\ ((uint32_t)((__HANDLE__)->Instance) == ((uint32_t)DMA1_Stream1))? DMA_FLAG_HTIF1_5 :\ ((uint32_t)((__HANDLE__)->Instance) == ((uint32_t)DMA2_Stream1))? DMA_FLAG_HTIF1_5 :\ ((uint32_t)((__HANDLE__)->Instance) == ((uint32_t)DMA1_Stream5))? DMA_FLAG_HTIF1_5 :\ ((uint32_t)((__HANDLE__)->Instance) == ((uint32_t)DMA2_Stream5))? DMA_FLAG_HTIF1_5 :\ ((uint32_t)((__HANDLE__)->Instance) == ((uint32_t)DMA1_Stream2))? DMA_FLAG_HTIF2_6 :\ ((uint32_t)((__HANDLE__)->Instance) == ((uint32_t)DMA2_Stream2))? DMA_FLAG_HTIF2_6 :\ ((uint32_t)((__HANDLE__)->Instance) == ((uint32_t)DMA1_Stream6))? DMA_FLAG_HTIF2_6 :\ ((uint32_t)((__HANDLE__)->Instance) == ((uint32_t)DMA2_Stream6))? DMA_FLAG_HTIF2_6 :\ DMA_FLAG_HTIF3_7) /** * @brief Return the current DMA Stream transfer error flag. * @param __HANDLE__: DMA handle * @retval The specified transfer error flag index. */ #define __HAL_DMA_GET_TE_FLAG_INDEX(__HANDLE__)\ (((uint32_t)((__HANDLE__)->Instance) == ((uint32_t)DMA1_Stream0))? DMA_FLAG_TEIF0_4 :\ ((uint32_t)((__HANDLE__)->Instance) == ((uint32_t)DMA2_Stream0))? DMA_FLAG_TEIF0_4 :\ ((uint32_t)((__HANDLE__)->Instance) == ((uint32_t)DMA1_Stream4))? DMA_FLAG_TEIF0_4 :\ ((uint32_t)((__HANDLE__)->Instance) == ((uint32_t)DMA2_Stream4))? DMA_FLAG_TEIF0_4 :\ ((uint32_t)((__HANDLE__)->Instance) == ((uint32_t)DMA1_Stream1))? DMA_FLAG_TEIF1_5 :\ ((uint32_t)((__HANDLE__)->Instance) == ((uint32_t)DMA2_Stream1))? DMA_FLAG_TEIF1_5 :\ ((uint32_t)((__HANDLE__)->Instance) == ((uint32_t)DMA1_Stream5))? DMA_FLAG_TEIF1_5 :\ ((uint32_t)((__HANDLE__)->Instance) == ((uint32_t)DMA2_Stream5))? DMA_FLAG_TEIF1_5 :\ ((uint32_t)((__HANDLE__)->Instance) == ((uint32_t)DMA1_Stream2))? DMA_FLAG_TEIF2_6 :\ ((uint32_t)((__HANDLE__)->Instance) == ((uint32_t)DMA2_Stream2))? DMA_FLAG_TEIF2_6 :\ ((uint32_t)((__HANDLE__)->Instance) == ((uint32_t)DMA1_Stream6))? DMA_FLAG_TEIF2_6 :\ ((uint32_t)((__HANDLE__)->Instance) == ((uint32_t)DMA2_Stream6))? DMA_FLAG_TEIF2_6 :\ DMA_FLAG_TEIF3_7) /** * @brief Return the current DMA Stream FIFO error flag. * @param __HANDLE__: DMA handle * @retval The specified FIFO error flag index. */ #define __HAL_DMA_GET_FE_FLAG_INDEX(__HANDLE__)\ (((uint32_t)((__HANDLE__)->Instance) == ((uint32_t)DMA1_Stream0))? DMA_FLAG_FEIF0_4 :\ ((uint32_t)((__HANDLE__)->Instance) == ((uint32_t)DMA2_Stream0))? DMA_FLAG_FEIF0_4 :\ ((uint32_t)((__HANDLE__)->Instance) == ((uint32_t)DMA1_Stream4))? DMA_FLAG_FEIF0_4 :\ ((uint32_t)((__HANDLE__)->Instance) == ((uint32_t)DMA2_Stream4))? DMA_FLAG_FEIF0_4 :\ ((uint32_t)((__HANDLE__)->Instance) == ((uint32_t)DMA1_Stream1))? DMA_FLAG_FEIF1_5 :\ ((uint32_t)((__HANDLE__)->Instance) == ((uint32_t)DMA2_Stream1))? DMA_FLAG_FEIF1_5 :\ ((uint32_t)((__HANDLE__)->Instance) == ((uint32_t)DMA1_Stream5))? DMA_FLAG_FEIF1_5 :\ ((uint32_t)((__HANDLE__)->Instance) == ((uint32_t)DMA2_Stream5))? DMA_FLAG_FEIF1_5 :\ ((uint32_t)((__HANDLE__)->Instance) == ((uint32_t)DMA1_Stream2))? DMA_FLAG_FEIF2_6 :\ ((uint32_t)((__HANDLE__)->Instance) == ((uint32_t)DMA2_Stream2))? DMA_FLAG_FEIF2_6 :\ ((uint32_t)((__HANDLE__)->Instance) == ((uint32_t)DMA1_Stream6))? DMA_FLAG_FEIF2_6 :\ ((uint32_t)((__HANDLE__)->Instance) == ((uint32_t)DMA2_Stream6))? DMA_FLAG_FEIF2_6 :\ DMA_FLAG_FEIF3_7) /** * @brief Return the current DMA Stream direct mode error flag. * @param __HANDLE__: DMA handle * @retval The specified direct mode error flag index. */ #define __HAL_DMA_GET_DME_FLAG_INDEX(__HANDLE__)\ (((uint32_t)((__HANDLE__)->Instance) == ((uint32_t)DMA1_Stream0))? DMA_FLAG_DMEIF0_4 :\ ((uint32_t)((__HANDLE__)->Instance) == ((uint32_t)DMA2_Stream0))? DMA_FLAG_DMEIF0_4 :\ ((uint32_t)((__HANDLE__)->Instance) == ((uint32_t)DMA1_Stream4))? DMA_FLAG_DMEIF0_4 :\ ((uint32_t)((__HANDLE__)->Instance) == ((uint32_t)DMA2_Stream4))? DMA_FLAG_DMEIF0_4 :\ ((uint32_t)((__HANDLE__)->Instance) == ((uint32_t)DMA1_Stream1))? DMA_FLAG_DMEIF1_5 :\ ((uint32_t)((__HANDLE__)->Instance) == ((uint32_t)DMA2_Stream1))? DMA_FLAG_DMEIF1_5 :\ ((uint32_t)((__HANDLE__)->Instance) == ((uint32_t)DMA1_Stream5))? DMA_FLAG_DMEIF1_5 :\ ((uint32_t)((__HANDLE__)->Instance) == ((uint32_t)DMA2_Stream5))? DMA_FLAG_DMEIF1_5 :\ ((uint32_t)((__HANDLE__)->Instance) == ((uint32_t)DMA1_Stream2))? DMA_FLAG_DMEIF2_6 :\ ((uint32_t)((__HANDLE__)->Instance) == ((uint32_t)DMA2_Stream2))? DMA_FLAG_DMEIF2_6 :\ ((uint32_t)((__HANDLE__)->Instance) == ((uint32_t)DMA1_Stream6))? DMA_FLAG_DMEIF2_6 :\ ((uint32_t)((__HANDLE__)->Instance) == ((uint32_t)DMA2_Stream6))? DMA_FLAG_DMEIF2_6 :\ DMA_FLAG_DMEIF3_7) /** * @brief Get the DMA Stream pending flags. * @param __HANDLE__: DMA handle * @param __FLAG__: Get the specified flag. * This parameter can be any combination of the following values: * @arg DMA_FLAG_TCIFx: Transfer complete flag. * @arg DMA_FLAG_HTIFx: Half transfer complete flag. * @arg DMA_FLAG_TEIFx: Transfer error flag. * @arg DMA_FLAG_DMEIFx: Direct mode error flag. * @arg DMA_FLAG_FEIFx: FIFO error flag. * Where x can be 0_4, 1_5, 2_6 or 3_7 to select the DMA Stream flag. * @retval The state of FLAG (SET or RESET). */ #define __HAL_DMA_GET_FLAG(__HANDLE__, __FLAG__)\ (((uint32_t)((__HANDLE__)->Instance) > (uint32_t)DMA2_Stream3)? (DMA2->HISR & (__FLAG__)) :\ ((uint32_t)((__HANDLE__)->Instance) > (uint32_t)DMA1_Stream7)? (DMA2->LISR & (__FLAG__)) :\ ((uint32_t)((__HANDLE__)->Instance) > (uint32_t)DMA1_Stream3)? (DMA1->HISR & (__FLAG__)) : (DMA1->LISR & (__FLAG__))) /** * @brief Clear the DMA Stream pending flags. * @param __HANDLE__: DMA handle * @param __FLAG__: specifies the flag to clear. * This parameter can be any combination of the following values: * @arg DMA_FLAG_TCIFx: Transfer complete flag. * @arg DMA_FLAG_HTIFx: Half transfer complete flag. * @arg DMA_FLAG_TEIFx: Transfer error flag. * @arg DMA_FLAG_DMEIFx: Direct mode error flag. * @arg DMA_FLAG_FEIFx: FIFO error flag. * Where x can be 0_4, 1_5, 2_6 or 3_7 to select the DMA Stream flag. * @retval None */ #define __HAL_DMA_CLEAR_FLAG(__HANDLE__, __FLAG__) \ (((uint32_t)((__HANDLE__)->Instance) > (uint32_t)DMA2_Stream3)? (DMA2->HIFCR = (__FLAG__)) :\ ((uint32_t)((__HANDLE__)->Instance) > (uint32_t)DMA1_Stream7)? (DMA2->LIFCR = (__FLAG__)) :\ ((uint32_t)((__HANDLE__)->Instance) > (uint32_t)DMA1_Stream3)? (DMA1->HIFCR = (__FLAG__)) : (DMA1->LIFCR = (__FLAG__))) /** * @brief Enable the specified DMA Stream interrupts. * @param __HANDLE__: DMA handle * @param __INTERRUPT__: specifies the DMA interrupt sources to be enabled or disabled. * This parameter can be any combination of the following values: * @arg DMA_IT_TC: Transfer complete interrupt mask. * @arg DMA_IT_HT: Half transfer complete interrupt mask. * @arg DMA_IT_TE: Transfer error interrupt mask. * @arg DMA_IT_FE: FIFO error interrupt mask. * @arg DMA_IT_DME: Direct mode error interrupt. * @retval None */ #define __HAL_DMA_ENABLE_IT(__HANDLE__, __INTERRUPT__) (((__INTERRUPT__) != DMA_IT_FE)? \ ((__HANDLE__)->Instance->CR |= (__INTERRUPT__)) : ((__HANDLE__)->Instance->FCR |= (__INTERRUPT__))) /** * @brief Disable the specified DMA Stream interrupts. * @param __HANDLE__: DMA handle * @param __INTERRUPT__: specifies the DMA interrupt sources to be enabled or disabled. * This parameter can be any combination of the following values: * @arg DMA_IT_TC: Transfer complete interrupt mask. * @arg DMA_IT_HT: Half transfer complete interrupt mask. * @arg DMA_IT_TE: Transfer error interrupt mask. * @arg DMA_IT_FE: FIFO error interrupt mask. * @arg DMA_IT_DME: Direct mode error interrupt. * @retval None */ #define __HAL_DMA_DISABLE_IT(__HANDLE__, __INTERRUPT__) (((__INTERRUPT__) != DMA_IT_FE)? \ ((__HANDLE__)->Instance->CR &= ~(__INTERRUPT__)) : ((__HANDLE__)->Instance->FCR &= ~(__INTERRUPT__))) /** * @brief Check whether the specified DMA Stream interrupt is enabled or disabled. * @param __HANDLE__: DMA handle * @param __INTERRUPT__: specifies the DMA interrupt source to check. * This parameter can be one of the following values: * @arg DMA_IT_TC: Transfer complete interrupt mask. * @arg DMA_IT_HT: Half transfer complete interrupt mask. * @arg DMA_IT_TE: Transfer error interrupt mask. * @arg DMA_IT_FE: FIFO error interrupt mask. * @arg DMA_IT_DME: Direct mode error interrupt. * @retval The state of DMA_IT. */ #define __HAL_DMA_GET_IT_SOURCE(__HANDLE__, __INTERRUPT__) (((__INTERRUPT__) != DMA_IT_FE)? \ ((__HANDLE__)->Instance->CR & (__INTERRUPT__)) : \ ((__HANDLE__)->Instance->FCR & (__INTERRUPT__))) /** * @brief Writes the number of data units to be transferred on the DMA Stream. * @param __HANDLE__: DMA handle * @param __COUNTER__: Number of data units to be transferred (from 0 to 65535) * Number of data items depends only on the Peripheral data format. * * @note If Peripheral data format is Bytes: number of data units is equal * to total number of bytes to be transferred. * * @note If Peripheral data format is Half-Word: number of data units is * equal to total number of bytes to be transferred / 2. * * @note If Peripheral data format is Word: number of data units is equal * to total number of bytes to be transferred / 4. * * @retval The number of remaining data units in the current DMAy Streamx transfer. */ #define __HAL_DMA_SET_COUNTER(__HANDLE__, __COUNTER__) ((__HANDLE__)->Instance->NDTR = (uint16_t)(__COUNTER__)) /** * @brief Returns the number of remaining data units in the current DMAy Streamx transfer. * @param __HANDLE__: DMA handle * * @retval The number of remaining data units in the current DMA Stream transfer. */ #define __HAL_DMA_GET_COUNTER(__HANDLE__) ((__HANDLE__)->Instance->NDTR) /* Include DMA HAL Extension module */ #include "stm32f4xx_hal_dma_ex.h" /* Exported functions --------------------------------------------------------*/ /** @defgroup DMA_Exported_Functions DMA Exported Functions * @brief DMA Exported functions * @{ */ /** @defgroup DMA_Exported_Functions_Group1 Initialization and de-initialization functions * @brief Initialization and de-initialization functions * @{ */ HAL_StatusTypeDef HAL_DMA_Init(DMA_HandleTypeDef *hdma); HAL_StatusTypeDef HAL_DMA_DeInit(DMA_HandleTypeDef *hdma); /** * @} */ /** @defgroup DMA_Exported_Functions_Group2 I/O operation functions * @brief I/O operation functions * @{ */ HAL_StatusTypeDef HAL_DMA_Start (DMA_HandleTypeDef *hdma, uint32_t SrcAddress, uint32_t DstAddress, uint32_t DataLength); HAL_StatusTypeDef HAL_DMA_Start_IT(DMA_HandleTypeDef *hdma, uint32_t SrcAddress, uint32_t DstAddress, uint32_t DataLength); HAL_StatusTypeDef HAL_DMA_Abort(DMA_HandleTypeDef *hdma); HAL_StatusTypeDef HAL_DMA_PollForTransfer(DMA_HandleTypeDef *hdma, uint32_t CompleteLevel, uint32_t Timeout); void HAL_DMA_IRQHandler(DMA_HandleTypeDef *hdma); /** * @} */ /** @defgroup DMA_Exported_Functions_Group3 Peripheral State functions * @brief Peripheral State functions * @{ */ HAL_DMA_StateTypeDef HAL_DMA_GetState(DMA_HandleTypeDef *hdma); uint32_t HAL_DMA_GetError(DMA_HandleTypeDef *hdma); /** * @} */ /** * @} */ /* Private Constants -------------------------------------------------------------*/ /** @defgroup DMA_Private_Constants DMA Private Constants * @brief DMA private defines and constants * @{ */ /** * @} */ /* Private macros ------------------------------------------------------------*/ /** @defgroup DMA_Private_Macros DMA Private Macros * @brief DMA private macros * @{ */ #define IS_DMA_CHANNEL(CHANNEL) (((CHANNEL) == DMA_CHANNEL_0) || \ ((CHANNEL) == DMA_CHANNEL_1) || \ ((CHANNEL) == DMA_CHANNEL_2) || \ ((CHANNEL) == DMA_CHANNEL_3) || \ ((CHANNEL) == DMA_CHANNEL_4) || \ ((CHANNEL) == DMA_CHANNEL_5) || \ ((CHANNEL) == DMA_CHANNEL_6) || \ ((CHANNEL) == DMA_CHANNEL_7)) #define IS_DMA_DIRECTION(DIRECTION) (((DIRECTION) == DMA_PERIPH_TO_MEMORY ) || \ ((DIRECTION) == DMA_MEMORY_TO_PERIPH) || \ ((DIRECTION) == DMA_MEMORY_TO_MEMORY)) #define IS_DMA_BUFFER_SIZE(SIZE) (((SIZE) >= 0x1) && ((SIZE) < 0x10000)) #define IS_DMA_PERIPHERAL_INC_STATE(STATE) (((STATE) == DMA_PINC_ENABLE) || \ ((STATE) == DMA_PINC_DISABLE)) #define IS_DMA_MEMORY_INC_STATE(STATE) (((STATE) == DMA_MINC_ENABLE) || \ ((STATE) == DMA_MINC_DISABLE)) #define IS_DMA_PERIPHERAL_DATA_SIZE(SIZE) (((SIZE) == DMA_PDATAALIGN_BYTE) || \ ((SIZE) == DMA_PDATAALIGN_HALFWORD) || \ ((SIZE) == DMA_PDATAALIGN_WORD)) #define IS_DMA_MEMORY_DATA_SIZE(SIZE) (((SIZE) == DMA_MDATAALIGN_BYTE) || \ ((SIZE) == DMA_MDATAALIGN_HALFWORD) || \ ((SIZE) == DMA_MDATAALIGN_WORD )) #define IS_DMA_MODE(MODE) (((MODE) == DMA_NORMAL ) || \ ((MODE) == DMA_CIRCULAR) || \ ((MODE) == DMA_PFCTRL)) #define IS_DMA_PRIORITY(PRIORITY) (((PRIORITY) == DMA_PRIORITY_LOW ) || \ ((PRIORITY) == DMA_PRIORITY_MEDIUM) || \ ((PRIORITY) == DMA_PRIORITY_HIGH) || \ ((PRIORITY) == DMA_PRIORITY_VERY_HIGH)) #define IS_DMA_FIFO_MODE_STATE(STATE) (((STATE) == DMA_FIFOMODE_DISABLE ) || \ ((STATE) == DMA_FIFOMODE_ENABLE)) #define IS_DMA_FIFO_THRESHOLD(THRESHOLD) (((THRESHOLD) == DMA_FIFO_THRESHOLD_1QUARTERFULL ) || \ ((THRESHOLD) == DMA_FIFO_THRESHOLD_HALFFULL) || \ ((THRESHOLD) == DMA_FIFO_THRESHOLD_3QUARTERSFULL) || \ ((THRESHOLD) == DMA_FIFO_THRESHOLD_FULL)) #define IS_DMA_MEMORY_BURST(BURST) (((BURST) == DMA_MBURST_SINGLE) || \ ((BURST) == DMA_MBURST_INC4) || \ ((BURST) == DMA_MBURST_INC8) || \ ((BURST) == DMA_MBURST_INC16)) #define IS_DMA_PERIPHERAL_BURST(BURST) (((BURST) == DMA_PBURST_SINGLE) || \ ((BURST) == DMA_PBURST_INC4) || \ ((BURST) == DMA_PBURST_INC8) || \ ((BURST) == DMA_PBURST_INC16)) /** * @} */ /* Private functions ---------------------------------------------------------*/ /** @defgroup DMA_Private_Functions DMA Private Functions * @brief DMA private functions * @{ */ /** * @} */ /** * @} */ /** * @} */ #ifdef __cplusplus } #endif #endif /* __STM32F4xx_HAL_DMA_H */ /************************ (C) COPYRIGHT STMicroelectronics *****END OF FILE****/ ================================================ FILE: Zelig/mbed/TARGET_NUCLEO_F401RE/stm32f4xx_hal_dma2d.h ================================================ /** ****************************************************************************** * @file stm32f4xx_hal_dma2d.h * @author MCD Application Team * @version V1.4.1 * @date 09-October-2015 * @brief Header file of DMA2D HAL module. ****************************************************************************** * @attention * *

© COPYRIGHT(c) 2015 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. * ****************************************************************************** */ /* Define to prevent recursive inclusion -------------------------------------*/ #ifndef __STM32F4xx_HAL_DMA2D_H #define __STM32F4xx_HAL_DMA2D_H #ifdef __cplusplus extern "C" { #endif #if defined(STM32F427xx) || defined(STM32F437xx) || defined(STM32F429xx) || defined(STM32F439xx) ||\ defined(STM32F469xx) || defined(STM32F479xx) /* Includes ------------------------------------------------------------------*/ #include "stm32f4xx_hal_def.h" /** @addtogroup STM32F4xx_HAL_Driver * @{ */ /** @defgroup DMA2D DMA2D * @brief DMA2D HAL module driver * @{ */ /* Exported types ------------------------------------------------------------*/ /** @defgroup DMA2D_Exported_Types DMA2D Exported Types * @{ */ #define MAX_DMA2D_LAYER 2 /** * @brief DMA2D color Structure definition */ typedef struct { uint32_t Blue; /*!< Configures the blue value. This parameter must be a number between Min_Data = 0x00 and Max_Data = 0xFF. */ uint32_t Green; /*!< Configures the green value. This parameter must be a number between Min_Data = 0x00 and Max_Data = 0xFF. */ uint32_t Red; /*!< Configures the red value. This parameter must be a number between Min_Data = 0x00 and Max_Data = 0xFF. */ } DMA2D_ColorTypeDef; /** * @brief DMA2D CLUT Structure definition */ typedef struct { uint32_t *pCLUT; /*!< Configures the DMA2D CLUT memory address.*/ uint32_t CLUTColorMode; /*!< configures the DMA2D CLUT color mode. This parameter can be one value of @ref DMA2D_CLUT_CM */ uint32_t Size; /*!< configures the DMA2D CLUT size. This parameter must be a number between Min_Data = 0x00 and Max_Data = 0xFF.*/ } DMA2D_CLUTCfgTypeDef; /** * @brief DMA2D Init structure definition */ typedef struct { uint32_t Mode; /*!< configures the DMA2D transfer mode. This parameter can be one value of @ref DMA2D_Mode */ uint32_t ColorMode; /*!< configures the color format of the output image. This parameter can be one value of @ref DMA2D_Color_Mode */ uint32_t OutputOffset; /*!< Specifies the Offset value. This parameter must be a number between Min_Data = 0x0000 and Max_Data = 0x3FFF. */ } DMA2D_InitTypeDef; /** * @brief DMA2D Layer structure definition */ typedef struct { uint32_t InputOffset; /*!< configures the DMA2D foreground offset. This parameter must be a number between Min_Data = 0x0000 and Max_Data = 0x3FFF. */ uint32_t InputColorMode; /*!< configures the DMA2D foreground color mode . This parameter can be one value of @ref DMA2D_Input_Color_Mode */ uint32_t AlphaMode; /*!< configures the DMA2D foreground alpha mode. This parameter can be one value of @ref DMA2D_ALPHA_MODE */ uint32_t InputAlpha; /*!< Specifies the DMA2D foreground alpha value and color value in case of A8 or A4 color mode. This parameter must be a number between Min_Data = 0x00000000 and Max_Data = 0xFFFFFFFF in case of A8 or A4 color mode (ARGB). Otherwise, This parameter must be a number between Min_Data = 0x00 and Max_Data = 0xFF.*/ } DMA2D_LayerCfgTypeDef; /** * @brief HAL DMA2D State structures definition */ typedef enum { HAL_DMA2D_STATE_RESET = 0x00, /*!< DMA2D not yet initialized or disabled */ HAL_DMA2D_STATE_READY = 0x01, /*!< Peripheral Initialized and ready for use */ HAL_DMA2D_STATE_BUSY = 0x02, /*!< an internal process is ongoing */ HAL_DMA2D_STATE_TIMEOUT = 0x03, /*!< Timeout state */ HAL_DMA2D_STATE_ERROR = 0x04, /*!< DMA2D state error */ HAL_DMA2D_STATE_SUSPEND = 0x05 /*!< DMA2D process is suspended */ }HAL_DMA2D_StateTypeDef; /** * @brief DMA2D handle Structure definition */ typedef struct __DMA2D_HandleTypeDef { DMA2D_TypeDef *Instance; /*!< DMA2D Register base address */ DMA2D_InitTypeDef Init; /*!< DMA2D communication parameters */ void (* XferCpltCallback)(struct __DMA2D_HandleTypeDef * hdma2d); /*!< DMA2D transfer complete callback */ void (* XferErrorCallback)(struct __DMA2D_HandleTypeDef * hdma2d); /*!< DMA2D transfer error callback */ DMA2D_LayerCfgTypeDef LayerCfg[MAX_DMA2D_LAYER]; /*!< DMA2D Layers parameters */ HAL_LockTypeDef Lock; /*!< DMA2D Lock */ __IO HAL_DMA2D_StateTypeDef State; /*!< DMA2D transfer state */ __IO uint32_t ErrorCode; /*!< DMA2D Error code */ } DMA2D_HandleTypeDef; /** * @} */ /* Exported constants --------------------------------------------------------*/ /** @defgroup DMA2D_Exported_Constants DMA2D Exported Constants * @{ */ /** @defgroup DMA2D_Error_Code DMA2D Error Code * @{ */ #define HAL_DMA2D_ERROR_NONE ((uint32_t)0x00000000) /*!< No error */ #define HAL_DMA2D_ERROR_TE ((uint32_t)0x00000001) /*!< Transfer error */ #define HAL_DMA2D_ERROR_CE ((uint32_t)0x00000002) /*!< Configuration error */ #define HAL_DMA2D_ERROR_TIMEOUT ((uint32_t)0x00000020) /*!< Timeout error */ /** * @} */ /** @defgroup DMA2D_Mode DMA2D Mode * @{ */ #define DMA2D_M2M ((uint32_t)0x00000000) /*!< DMA2D memory to memory transfer mode */ #define DMA2D_M2M_PFC ((uint32_t)0x00010000) /*!< DMA2D memory to memory with pixel format conversion transfer mode */ #define DMA2D_M2M_BLEND ((uint32_t)0x00020000) /*!< DMA2D memory to memory with blending transfer mode */ #define DMA2D_R2M ((uint32_t)0x00030000) /*!< DMA2D register to memory transfer mode */ /** * @} */ /** @defgroup DMA2D_Color_Mode DMA2D Color Mode * @{ */ #define DMA2D_ARGB8888 ((uint32_t)0x00000000) /*!< ARGB8888 DMA2D color mode */ #define DMA2D_RGB888 ((uint32_t)0x00000001) /*!< RGB888 DMA2D color mode */ #define DMA2D_RGB565 ((uint32_t)0x00000002) /*!< RGB565 DMA2D color mode */ #define DMA2D_ARGB1555 ((uint32_t)0x00000003) /*!< ARGB1555 DMA2D color mode */ #define DMA2D_ARGB4444 ((uint32_t)0x00000004) /*!< ARGB4444 DMA2D color mode */ /** * @} */ /** @defgroup DMA2D_COLOR_VALUE DMA2D COLOR VALUE * @{ */ #define COLOR_VALUE ((uint32_t)0x000000FF) /*!< color value mask */ /** * @} */ /** @defgroup DMA2D_SIZE DMA2D SIZE * @{ */ #define DMA2D_PIXEL (DMA2D_NLR_PL >> 16) /*!< DMA2D pixel per line */ #define DMA2D_LINE DMA2D_NLR_NL /*!< DMA2D number of line */ /** * @} */ /** @defgroup DMA2D_Offset DMA2D Offset * @{ */ #define DMA2D_OFFSET DMA2D_FGOR_LO /*!< Line Offset */ /** * @} */ /** @defgroup DMA2D_Input_Color_Mode DMA2D Input Color Mode * @{ */ #define CM_ARGB8888 ((uint32_t)0x00000000) /*!< ARGB8888 color mode */ #define CM_RGB888 ((uint32_t)0x00000001) /*!< RGB888 color mode */ #define CM_RGB565 ((uint32_t)0x00000002) /*!< RGB565 color mode */ #define CM_ARGB1555 ((uint32_t)0x00000003) /*!< ARGB1555 color mode */ #define CM_ARGB4444 ((uint32_t)0x00000004) /*!< ARGB4444 color mode */ #define CM_L8 ((uint32_t)0x00000005) /*!< L8 color mode */ #define CM_AL44 ((uint32_t)0x00000006) /*!< AL44 color mode */ #define CM_AL88 ((uint32_t)0x00000007) /*!< AL88 color mode */ #define CM_L4 ((uint32_t)0x00000008) /*!< L4 color mode */ #define CM_A8 ((uint32_t)0x00000009) /*!< A8 color mode */ #define CM_A4 ((uint32_t)0x0000000A) /*!< A4 color mode */ /** * @} */ /** @defgroup DMA2D_ALPHA_MODE DMA2D ALPHA MODE * @{ */ #define DMA2D_NO_MODIF_ALPHA ((uint32_t)0x00000000) /*!< No modification of the alpha channel value */ #define DMA2D_REPLACE_ALPHA ((uint32_t)0x00000001) /*!< Replace original alpha channel value by programmed alpha value */ #define DMA2D_COMBINE_ALPHA ((uint32_t)0x00000002) /*!< Replace original alpha channel value by programmed alpha value with original alpha channel value */ /** * @} */ /** @defgroup DMA2D_CLUT_CM DMA2D CLUT CM * @{ */ #define DMA2D_CCM_ARGB8888 ((uint32_t)0x00000000) /*!< ARGB8888 DMA2D C-LUT color mode */ #define DMA2D_CCM_RGB888 ((uint32_t)0x00000001) /*!< RGB888 DMA2D C-LUT color mode */ /** * @} */ /** @defgroup DMA2D_Size_Clut DMA2D Size Clut * @{ */ #define DMA2D_CLUT_SIZE (DMA2D_FGPFCCR_CS >> 8) /*!< DMA2D C-LUT size */ /** * @} */ /** @defgroup DMA2D_DeadTime DMA2D DeadTime * @{ */ #define LINE_WATERMARK DMA2D_LWR_LW /** * @} */ /** @defgroup DMA2D_Interrupts DMA2D Interrupts * @{ */ #define DMA2D_IT_CE DMA2D_CR_CEIE /*!< Configuration Error Interrupt */ #define DMA2D_IT_CTC DMA2D_CR_CTCIE /*!< C-LUT Transfer Complete Interrupt */ #define DMA2D_IT_CAE DMA2D_CR_CAEIE /*!< C-LUT Access Error Interrupt */ #define DMA2D_IT_TW DMA2D_CR_TWIE /*!< Transfer Watermark Interrupt */ #define DMA2D_IT_TC DMA2D_CR_TCIE /*!< Transfer Complete Interrupt */ #define DMA2D_IT_TE DMA2D_CR_TEIE /*!< Transfer Error Interrupt */ /** * @} */ /** @defgroup DMA2D_Flag DMA2D Flag * @{ */ #define DMA2D_FLAG_CE DMA2D_ISR_CEIF /*!< Configuration Error Interrupt Flag */ #define DMA2D_FLAG_CTC DMA2D_ISR_CTCIF /*!< C-LUT Transfer Complete Interrupt Flag */ #define DMA2D_FLAG_CAE DMA2D_ISR_CAEIF /*!< C-LUT Access Error Interrupt Flag */ #define DMA2D_FLAG_TW DMA2D_ISR_TWIF /*!< Transfer Watermark Interrupt Flag */ #define DMA2D_FLAG_TC DMA2D_ISR_TCIF /*!< Transfer Complete Interrupt Flag */ #define DMA2D_FLAG_TE DMA2D_ISR_TEIF /*!< Transfer Error Interrupt Flag */ /** * @} */ /** * @} */ /* Exported macro ------------------------------------------------------------*/ /** @defgroup DMA2D_Exported_Macros DMA2D Exported Macros * @{ */ /** @brief Reset DMA2D handle state * @param __HANDLE__: specifies the DMA2D handle. * @retval None */ #define __HAL_DMA2D_RESET_HANDLE_STATE(__HANDLE__) ((__HANDLE__)->State = HAL_DMA2D_STATE_RESET) /** * @brief Enable the DMA2D. * @param __HANDLE__: DMA2D handle * @retval None. */ #define __HAL_DMA2D_ENABLE(__HANDLE__) ((__HANDLE__)->Instance->CR |= DMA2D_CR_START) /** * @brief Disable the DMA2D. * @param __HANDLE__: DMA2D handle * @retval None. */ #define __HAL_DMA2D_DISABLE(__HANDLE__) ((__HANDLE__)->Instance->CR &= ~DMA2D_CR_START) /* Interrupt & Flag management */ /** * @brief Get the DMA2D pending flags. * @param __HANDLE__: DMA2D handle * @param __FLAG__: Get the specified flag. * This parameter can be any combination of the following values: * @arg DMA2D_FLAG_CE: Configuration error flag * @arg DMA2D_FLAG_CTC: C-LUT transfer complete flag * @arg DMA2D_FLAG_CAE: C-LUT access error flag * @arg DMA2D_FLAG_TW: Transfer Watermark flag * @arg DMA2D_FLAG_TC: Transfer complete flag * @arg DMA2D_FLAG_TE: Transfer error flag * @retval The state of FLAG. */ #define __HAL_DMA2D_GET_FLAG(__HANDLE__, __FLAG__) ((__HANDLE__)->Instance->ISR & (__FLAG__)) /** * @brief Clears the DMA2D pending flags. * @param __HANDLE__: DMA2D handle * @param __FLAG__: specifies the flag to clear. * This parameter can be any combination of the following values: * @arg DMA2D_FLAG_CE: Configuration error flag * @arg DMA2D_FLAG_CTC: C-LUT transfer complete flag * @arg DMA2D_FLAG_CAE: C-LUT access error flag * @arg DMA2D_FLAG_TW: Transfer Watermark flag * @arg DMA2D_FLAG_TC: Transfer complete flag * @arg DMA2D_FLAG_TE: Transfer error flag * @retval None */ #define __HAL_DMA2D_CLEAR_FLAG(__HANDLE__, __FLAG__) ((__HANDLE__)->Instance->IFCR = (__FLAG__)) /** * @brief Enables the specified DMA2D interrupts. * @param __HANDLE__: DMA2D handle * @param __INTERRUPT__: specifies the DMA2D interrupt sources to be enabled. * This parameter can be any combination of the following values: * @arg DMA2D_IT_CE: Configuration error interrupt mask * @arg DMA2D_IT_CTC: C-LUT transfer complete interrupt mask * @arg DMA2D_IT_CAE: C-LUT access error interrupt mask * @arg DMA2D_IT_TW: Transfer Watermark interrupt mask * @arg DMA2D_IT_TC: Transfer complete interrupt mask * @arg DMA2D_IT_TE: Transfer error interrupt mask * @retval None */ #define __HAL_DMA2D_ENABLE_IT(__HANDLE__, __INTERRUPT__) ((__HANDLE__)->Instance->CR |= (__INTERRUPT__)) /** * @brief Disables the specified DMA2D interrupts. * @param __HANDLE__: DMA2D handle * @param __INTERRUPT__: specifies the DMA2D interrupt sources to be disabled. * This parameter can be any combination of the following values: * @arg DMA2D_IT_CE: Configuration error interrupt mask * @arg DMA2D_IT_CTC: C-LUT transfer complete interrupt mask * @arg DMA2D_IT_CAE: C-LUT access error interrupt mask * @arg DMA2D_IT_TW: Transfer Watermark interrupt mask * @arg DMA2D_IT_TC: Transfer complete interrupt mask * @arg DMA2D_IT_TE: Transfer error interrupt mask * @retval None */ #define __HAL_DMA2D_DISABLE_IT(__HANDLE__, __INTERRUPT__) ((__HANDLE__)->Instance->CR &= ~(__INTERRUPT__)) /** * @brief Checks whether the specified DMA2D interrupt has occurred or not. * @param __HANDLE__: DMA2D handle * @param __INTERRUPT__: specifies the DMA2D interrupt source to check. * This parameter can be one of the following values: * @arg DMA2D_IT_CE: Configuration error interrupt mask * @arg DMA2D_IT_CTC: C-LUT transfer complete interrupt mask * @arg DMA2D_IT_CAE: C-LUT access error interrupt mask * @arg DMA2D_IT_TW: Transfer Watermark interrupt mask * @arg DMA2D_IT_TC: Transfer complete interrupt mask * @arg DMA2D_IT_TE: Transfer error interrupt mask * @retval The state of INTERRUPT. */ #define __HAL_DMA2D_GET_IT_SOURCE(__HANDLE__, __INTERRUPT__) ((__HANDLE__)->Instance->CR & (__INTERRUPT__)) /** * @} */ /* Exported functions --------------------------------------------------------*/ /** @defgroup DMA2D_Exported_Functions DMA2D Exported Functions * @{ */ /* Initialization and de-initialization functions *******************************/ HAL_StatusTypeDef HAL_DMA2D_Init(DMA2D_HandleTypeDef *hdma2d); HAL_StatusTypeDef HAL_DMA2D_DeInit (DMA2D_HandleTypeDef *hdma2d); void HAL_DMA2D_MspInit(DMA2D_HandleTypeDef* hdma2d); void HAL_DMA2D_MspDeInit(DMA2D_HandleTypeDef* hdma2d); /* IO operation functions *******************************************************/ HAL_StatusTypeDef HAL_DMA2D_Start(DMA2D_HandleTypeDef *hdma2d, uint32_t pdata, uint32_t DstAddress, uint32_t Width, uint32_t Height); HAL_StatusTypeDef HAL_DMA2D_BlendingStart(DMA2D_HandleTypeDef *hdma2d, uint32_t SrcAddress1, uint32_t SrcAddress2, uint32_t DstAddress, uint32_t Width, uint32_t Height); HAL_StatusTypeDef HAL_DMA2D_Start_IT(DMA2D_HandleTypeDef *hdma2d, uint32_t pdata, uint32_t DstAddress, uint32_t Width, uint32_t Height); HAL_StatusTypeDef HAL_DMA2D_BlendingStart_IT(DMA2D_HandleTypeDef *hdma2d, uint32_t SrcAddress1, uint32_t SrcAddress2, uint32_t DstAddress, uint32_t Width, uint32_t Height); HAL_StatusTypeDef HAL_DMA2D_Suspend(DMA2D_HandleTypeDef *hdma2d); HAL_StatusTypeDef HAL_DMA2D_Resume(DMA2D_HandleTypeDef *hdma2d); HAL_StatusTypeDef HAL_DMA2D_Abort(DMA2D_HandleTypeDef *hdma2d); HAL_StatusTypeDef HAL_DMA2D_PollForTransfer(DMA2D_HandleTypeDef *hdma2d, uint32_t Timeout); void HAL_DMA2D_IRQHandler(DMA2D_HandleTypeDef *hdma2d); /* Peripheral Control functions *************************************************/ HAL_StatusTypeDef HAL_DMA2D_ConfigLayer(DMA2D_HandleTypeDef *hdma2d, uint32_t LayerIdx); HAL_StatusTypeDef HAL_DMA2D_ConfigCLUT(DMA2D_HandleTypeDef *hdma2d, DMA2D_CLUTCfgTypeDef CLUTCfg, uint32_t LayerIdx); HAL_StatusTypeDef HAL_DMA2D_EnableCLUT(DMA2D_HandleTypeDef *hdma2d, uint32_t LayerIdx); HAL_StatusTypeDef HAL_DMA2D_DisableCLUT(DMA2D_HandleTypeDef *hdma2d, uint32_t LayerIdx); HAL_StatusTypeDef HAL_DMA2D_ProgramLineEvent(DMA2D_HandleTypeDef *hdma2d, uint32_t Line); /* Peripheral State functions ***************************************************/ HAL_DMA2D_StateTypeDef HAL_DMA2D_GetState(DMA2D_HandleTypeDef *hdma2d); uint32_t HAL_DMA2D_GetError(DMA2D_HandleTypeDef *hdma2d); /** * @} */ /* Private types -------------------------------------------------------------*/ /** @defgroup DMA2D_Private_Types DMA2D Private Types * @{ */ /** * @} */ /* Private defines -------------------------------------------------------------*/ /** @defgroup DMA2D_Private_Defines DMA2D Private Defines * @{ */ /** * @} */ /* Private variables ---------------------------------------------------------*/ /** @defgroup DMA2D_Private_Variables DMA2D Private Variables * @{ */ /** * @} */ /* Private constants ---------------------------------------------------------*/ /** @defgroup DMA2D_Private_Constants DMA2D Private Constants * @{ */ /** * @} */ /* Private macros ------------------------------------------------------------*/ /** @defgroup DMA2D_Private_Macros DMA2D Private Macros * @{ */ #define IS_DMA2D_LAYER(LAYER) ((LAYER) <= MAX_DMA2D_LAYER) #define IS_DMA2D_MODE(MODE) (((MODE) == DMA2D_M2M) || ((MODE) == DMA2D_M2M_PFC) || \ ((MODE) == DMA2D_M2M_BLEND) || ((MODE) == DMA2D_R2M)) #define IS_DMA2D_CMODE(MODE_ARGB) (((MODE_ARGB) == DMA2D_ARGB8888) || ((MODE_ARGB) == DMA2D_RGB888) || \ ((MODE_ARGB) == DMA2D_RGB565) || ((MODE_ARGB) == DMA2D_ARGB1555) || \ ((MODE_ARGB) == DMA2D_ARGB4444)) #define IS_DMA2D_COLOR(COLOR) ((COLOR) <= COLOR_VALUE) #define IS_DMA2D_LINE(LINE) ((LINE) <= DMA2D_LINE) #define IS_DMA2D_PIXEL(PIXEL) ((PIXEL) <= DMA2D_PIXEL) #define IS_DMA2D_OFFSET(OOFFSET) ((OOFFSET) <= DMA2D_OFFSET) #define IS_DMA2D_INPUT_COLOR_MODE(INPUT_CM) (((INPUT_CM) == CM_ARGB8888) || ((INPUT_CM) == CM_RGB888) || \ ((INPUT_CM) == CM_RGB565) || ((INPUT_CM) == CM_ARGB1555) || \ ((INPUT_CM) == CM_ARGB4444) || ((INPUT_CM) == CM_L8) || \ ((INPUT_CM) == CM_AL44) || ((INPUT_CM) == CM_AL88) || \ ((INPUT_CM) == CM_L4) || ((INPUT_CM) == CM_A8) || \ ((INPUT_CM) == CM_A4)) #define IS_DMA2D_ALPHA_MODE(AlphaMode) (((AlphaMode) == DMA2D_NO_MODIF_ALPHA) || \ ((AlphaMode) == DMA2D_REPLACE_ALPHA) || \ ((AlphaMode) == DMA2D_COMBINE_ALPHA)) #define IS_DMA2D_CLUT_CM(CLUT_CM) (((CLUT_CM) == DMA2D_CCM_ARGB8888) || ((CLUT_CM) == DMA2D_CCM_RGB888)) #define IS_DMA2D_CLUT_SIZE(CLUT_SIZE) ((CLUT_SIZE) <= DMA2D_CLUT_SIZE) #define IS_DMA2D_LineWatermark(LineWatermark) ((LineWatermark) <= LINE_WATERMARK) /** * @} */ /* Private functions prototypes ---------------------------------------------------------*/ /** @defgroup DMA2D_Private_Functions_Prototypes DMA2D Private Functions Prototypes * @{ */ /** * @} */ /* Private functions ---------------------------------------------------------*/ /** @defgroup DMA2D_Private_Functions DMA2D Private Functions * @{ */ /** * @} */ /** * @} */ /** * @} */ #endif /* STM32F427xx || STM32F437xx || STM32F429xx || STM32F439xx || STM32F469xx || STM32F479xx */ #ifdef __cplusplus } #endif #endif /* __STM32F4xx_HAL_DMA2D_H */ /************************ (C) COPYRIGHT STMicroelectronics *****END OF FILE****/ ================================================ FILE: Zelig/mbed/TARGET_NUCLEO_F401RE/stm32f4xx_hal_dma_ex.h ================================================ /** ****************************************************************************** * @file stm32f4xx_hal_dma_ex.h * @author MCD Application Team * @version V1.4.1 * @date 09-October-2015 * @brief Header file of DMA HAL extension module. ****************************************************************************** * @attention * *

© COPYRIGHT(c) 2015 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. * ****************************************************************************** */ /* Define to prevent recursive inclusion -------------------------------------*/ #ifndef __STM32F4xx_HAL_DMA_EX_H #define __STM32F4xx_HAL_DMA_EX_H #ifdef __cplusplus extern "C" { #endif /* Includes ------------------------------------------------------------------*/ #include "stm32f4xx_hal_def.h" /** @addtogroup STM32F4xx_HAL_Driver * @{ */ /** @addtogroup DMAEx * @{ */ /* Exported types ------------------------------------------------------------*/ /** @defgroup DMAEx_Exported_Types DMAEx Exported Types * @brief DMAEx Exported types * @{ */ /** * @brief HAL DMA Memory definition */ typedef enum { MEMORY0 = 0x00, /*!< Memory 0 */ MEMORY1 = 0x01, /*!< Memory 1 */ }HAL_DMA_MemoryTypeDef; /** * @} */ /* Exported functions --------------------------------------------------------*/ /** @defgroup DMAEx_Exported_Functions DMAEx Exported Functions * @brief DMAEx Exported functions * @{ */ /** @defgroup DMAEx_Exported_Functions_Group1 Extended features functions * @brief Extended features functions * @{ */ /* IO operation functions *******************************************************/ HAL_StatusTypeDef HAL_DMAEx_MultiBufferStart(DMA_HandleTypeDef *hdma, uint32_t SrcAddress, uint32_t DstAddress, uint32_t SecondMemAddress, uint32_t DataLength); HAL_StatusTypeDef HAL_DMAEx_MultiBufferStart_IT(DMA_HandleTypeDef *hdma, uint32_t SrcAddress, uint32_t DstAddress, uint32_t SecondMemAddress, uint32_t DataLength); HAL_StatusTypeDef HAL_DMAEx_ChangeMemory(DMA_HandleTypeDef *hdma, uint32_t Address, HAL_DMA_MemoryTypeDef memory); /** * @} */ /** * @} */ /* Private functions ---------------------------------------------------------*/ /** @defgroup DMAEx_Private_Functions DMAEx Private Functions * @brief DMAEx Private functions * @{ */ /** * @} */ /** * @} */ /** * @} */ #ifdef __cplusplus } #endif #endif /*__STM32F4xx_HAL_DMA_EX_H*/ /************************ (C) COPYRIGHT STMicroelectronics *****END OF FILE****/ ================================================ FILE: Zelig/mbed/TARGET_NUCLEO_F401RE/stm32f4xx_hal_dsi.h ================================================ /** ****************************************************************************** * @file stm32f4xx_hal_dsi.h * @author MCD Application Team * @version V1.4.1 * @date 09-October-2015 * @brief Header file of DSI HAL module. ****************************************************************************** * @attention * *

© COPYRIGHT(c) 2015 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. * ****************************************************************************** */ /* Define to prevent recursive inclusion -------------------------------------*/ #ifndef __STM32F4xx_HAL_DSI_H #define __STM32F4xx_HAL_DSI_H #ifdef __cplusplus extern "C" { #endif #if defined(STM32F469xx) || defined(STM32F479xx) /* Includes ------------------------------------------------------------------*/ #include "stm32f4xx_hal_def.h" /** @addtogroup STM32F4xx_HAL_Driver * @{ */ /** @defgroup DSI DSI * @brief DSI HAL module driver * @{ */ /* Exported types ------------------------------------------------------------*/ /** * @brief DSI Init Structure definition */ typedef struct { uint32_t AutomaticClockLaneControl; /*!< Automatic clock lane control This parameter can be any value of @ref DSI_Automatic_Clk_Lane_Control */ uint32_t TXEscapeCkdiv; /*!< TX Escape clock division The values 0 and 1 stop the TX_ESC clock generation */ uint32_t NumberOfLanes; /*!< Number of lanes This parameter can be any value of @ref DSI_Number_Of_Lanes */ }DSI_InitTypeDef; /** * @brief DSI PLL Clock structure definition */ typedef struct { uint32_t PLLNDIV; /*!< PLL Loop Division Factor This parameter must be a value between 10 and 125 */ uint32_t PLLIDF; /*!< PLL Input Division Factor This parameter can be any value of @ref DSI_PLL_IDF */ uint32_t PLLODF; /*!< PLL Output Division Factor This parameter can be any value of @ref DSI_PLL_ODF */ }DSI_PLLInitTypeDef; /** * @brief DSI Video mode configuration */ typedef struct { uint32_t VirtualChannelID; /*!< Virtual channel ID */ uint32_t ColorCoding; /*!< Color coding for LTDC interface This parameter can be any value of @ref DSI_Color_Coding */ uint32_t LooselyPacked; /*!< Enable or disable loosely packed stream (needed only when using 18-bit configuration). This parameter can be any value of @ref DSI_LooselyPacked */ uint32_t Mode; /*!< Video mode type This parameter can be any value of @ref DSI_Video_Mode_Type */ uint32_t PacketSize; /*!< Video packet size */ uint32_t NumberOfChunks; /*!< Number of chunks */ uint32_t NullPacketSize; /*!< Null packet size */ uint32_t HSPolarity; /*!< HSYNC pin polarity This parameter can be any value of @ref DSI_HSYNC_Polarity */ uint32_t VSPolarity; /*!< VSYNC pin polarity This parameter can be any value of @ref DSI_VSYNC_Polarity */ uint32_t DEPolarity; /*!< Data Enable pin polarity This parameter can be any value of @ref DSI_DATA_ENABLE_Polarity */ uint32_t HorizontalSyncActive; /*!< Horizontal synchronism active duration (in lane byte clock cycles) */ uint32_t HorizontalBackPorch; /*!< Horizontal back-porch duration (in lane byte clock cycles) */ uint32_t HorizontalLine; /*!< Horizontal line duration (in lane byte clock cycles) */ uint32_t VerticalSyncActive; /*!< Vertical synchronism active duration */ uint32_t VerticalBackPorch; /*!< Vertical back-porch duration */ uint32_t VerticalFrontPorch; /*!< Vertical front-porch duration */ uint32_t VerticalActive; /*!< Vertical active duration */ uint32_t LPCommandEnable; /*!< Low-power command enable This parameter can be any value of @ref DSI_LP_Command */ uint32_t LPLargestPacketSize; /*!< The size, in bytes, of the low power largest packet that can fit in a line during VSA, VBP and VFP regions */ uint32_t LPVACTLargestPacketSize; /*!< The size, in bytes, of the low power largest packet that can fit in a line during VACT region */ uint32_t LPHorizontalFrontPorchEnable; /*!< Low-power horizontal front-porch enable This parameter can be any value of @ref DSI_LP_HFP */ uint32_t LPHorizontalBackPorchEnable; /*!< Low-power horizontal back-porch enable This parameter can be any value of @ref DSI_LP_HBP */ uint32_t LPVerticalActiveEnable; /*!< Low-power vertical active enable This parameter can be any value of @ref DSI_LP_VACT */ uint32_t LPVerticalFrontPorchEnable; /*!< Low-power vertical front-porch enable This parameter can be any value of @ref DSI_LP_VFP */ uint32_t LPVerticalBackPorchEnable; /*!< Low-power vertical back-porch enable This parameter can be any value of @ref DSI_LP_VBP */ uint32_t LPVerticalSyncActiveEnable; /*!< Low-power vertical sync active enable This parameter can be any value of @ref DSI_LP_VSYNC */ uint32_t FrameBTAAcknowledgeEnable; /*!< Frame bus-turn-around acknowledge enable This parameter can be any value of @ref DSI_FBTA_acknowledge */ }DSI_VidCfgTypeDef; /** * @brief DSI Adapted command mode configuration */ typedef struct { uint32_t VirtualChannelID; /*!< Virtual channel ID */ uint32_t ColorCoding; /*!< Color coding for LTDC interface This parameter can be any value of @ref DSI_Color_Coding */ uint32_t CommandSize; /*!< Maximum allowed size for an LTDC write memory command, measured in pixels. This parameter can be any value between 0x00 and 0xFFFF */ uint32_t TearingEffectSource; /*!< Tearing effect source This parameter can be any value of @ref DSI_TearingEffectSource */ uint32_t TearingEffectPolarity; /*!< Tearing effect pin polarity This parameter can be any value of @ref DSI_TearingEffectPolarity */ uint32_t HSPolarity; /*!< HSYNC pin polarity This parameter can be any value of @ref DSI_HSYNC_Polarity */ uint32_t VSPolarity; /*!< VSYNC pin polarity This parameter can be any value of @ref DSI_VSYNC_Polarity */ uint32_t DEPolarity; /*!< Data Enable pin polarity This parameter can be any value of @ref DSI_DATA_ENABLE_Polarity */ uint32_t VSyncPol; /*!< VSync edge on which the LTDC is halted This parameter can be any value of @ref DSI_Vsync_Polarity */ uint32_t AutomaticRefresh; /*!< Automatic refresh mode This parameter can be any value of @ref DSI_AutomaticRefresh */ uint32_t TEAcknowledgeRequest; /*!< Tearing Effect Acknowledge Request Enable This parameter can be any value of @ref DSI_TE_AcknowledgeRequest */ }DSI_CmdCfgTypeDef; /** * @brief DSI command transmission mode configuration */ typedef struct { uint32_t LPGenShortWriteNoP; /*!< Generic Short Write Zero parameters Transmission This parameter can be any value of @ref DSI_LP_LPGenShortWriteNoP */ uint32_t LPGenShortWriteOneP; /*!< Generic Short Write One parameter Transmission This parameter can be any value of @ref DSI_LP_LPGenShortWriteOneP */ uint32_t LPGenShortWriteTwoP; /*!< Generic Short Write Two parameters Transmission This parameter can be any value of @ref DSI_LP_LPGenShortWriteTwoP */ uint32_t LPGenShortReadNoP; /*!< Generic Short Read Zero parameters Transmission This parameter can be any value of @ref DSI_LP_LPGenShortReadNoP */ uint32_t LPGenShortReadOneP; /*!< Generic Short Read One parameter Transmission This parameter can be any value of @ref DSI_LP_LPGenShortReadOneP */ uint32_t LPGenShortReadTwoP; /*!< Generic Short Read Two parameters Transmission This parameter can be any value of @ref DSI_LP_LPGenShortReadTwoP */ uint32_t LPGenLongWrite; /*!< Generic Long Write Transmission This parameter can be any value of @ref DSI_LP_LPGenLongWrite */ uint32_t LPDcsShortWriteNoP; /*!< DCS Short Write Zero parameters Transmission This parameter can be any value of @ref DSI_LP_LPDcsShortWriteNoP */ uint32_t LPDcsShortWriteOneP; /*!< DCS Short Write One parameter Transmission This parameter can be any value of @ref DSI_LP_LPDcsShortWriteOneP */ uint32_t LPDcsShortReadNoP; /*!< DCS Short Read Zero parameters Transmission This parameter can be any value of @ref DSI_LP_LPDcsShortReadNoP */ uint32_t LPDcsLongWrite; /*!< DCS Long Write Transmission This parameter can be any value of @ref DSI_LP_LPDcsLongWrite */ uint32_t LPMaxReadPacket; /*!< Maximum Read Packet Size Transmission This parameter can be any value of @ref DSI_LP_LPMaxReadPacket */ uint32_t AcknowledgeRequest; /*!< Acknowledge Request Enable This parameter can be any value of @ref DSI_AcknowledgeRequest */ }DSI_LPCmdTypeDef; /** * @brief DSI PHY Timings definition */ typedef struct { uint32_t ClockLaneHS2LPTime; /*!< The maximum time that the D-PHY clock lane takes to go from high-speed to low-power transmission */ uint32_t ClockLaneLP2HSTime; /*!< The maximum time that the D-PHY clock lane takes to go from low-power to high-speed transmission */ uint32_t DataLaneHS2LPTime; /*!< The maximum time that the D-PHY data lanes takes to go from high-speed to low-power transmission */ uint32_t DataLaneLP2HSTime; /*!< The maximum time that the D-PHY data lanes takes to go from low-power to high-speed transmission */ uint32_t DataLaneMaxReadTime; /*!< The maximum time required to perform a read command */ uint32_t StopWaitTime; /*!< The minimum wait period to request a High-Speed transmission after the Stop state */ }DSI_PHY_TimerTypeDef; /** * @brief DSI HOST Timeouts definition */ typedef struct { uint32_t TimeoutCkdiv; /*!< Time-out clock division */ uint32_t HighSpeedTransmissionTimeout; /*!< High-speed transmission time-out */ uint32_t LowPowerReceptionTimeout; /*!< Low-power reception time-out */ uint32_t HighSpeedReadTimeout; /*!< High-speed read time-out */ uint32_t LowPowerReadTimeout; /*!< Low-power read time-out */ uint32_t HighSpeedWriteTimeout; /*!< High-speed write time-out */ uint32_t HighSpeedWritePrespMode; /*!< High-speed write presp mode This parameter can be any value of @ref DSI_HS_PrespMode */ uint32_t LowPowerWriteTimeout; /*!< Low-speed write time-out */ uint32_t BTATimeout; /*!< BTA time-out */ }DSI_HOST_TimeoutTypeDef; /** * @brief DSI States Structure definition */ typedef enum { HAL_DSI_STATE_RESET = 0x00, HAL_DSI_STATE_READY = 0x01, HAL_DSI_STATE_ERROR = 0x02, HAL_DSI_STATE_BUSY = 0x03, HAL_DSI_STATE_TIMEOUT = 0x04 }HAL_DSI_StateTypeDef; /** * @brief DSI Handle Structure definition */ typedef struct { DSI_TypeDef *Instance; /*!< Register base address */ DSI_InitTypeDef Init; /*!< DSI required parameters */ HAL_LockTypeDef Lock; /*!< DSI peripheral status */ __IO HAL_DSI_StateTypeDef State; /*!< DSI communication state */ __IO uint32_t ErrorCode; /*!< DSI Error code */ uint32_t ErrorMsk; /*!< DSI Error monitoring mask */ }DSI_HandleTypeDef; /* Exported constants --------------------------------------------------------*/ /** @defgroup DSI_DCS_Command DSI DCS Command * @{ */ #define DSI_ENTER_IDLE_MODE 0x39 #define DSI_ENTER_INVERT_MODE 0x21 #define DSI_ENTER_NORMAL_MODE 0x13 #define DSI_ENTER_PARTIAL_MODE 0x12 #define DSI_ENTER_SLEEP_MODE 0x10 #define DSI_EXIT_IDLE_MODE 0x38 #define DSI_EXIT_INVERT_MODE 0x20 #define DSI_EXIT_SLEEP_MODE 0x11 #define DSI_GET_3D_CONTROL 0x3F #define DSI_GET_ADDRESS_MODE 0x0B #define DSI_GET_BLUE_CHANNEL 0x08 #define DSI_GET_DIAGNOSTIC_RESULT 0x0F #define DSI_GET_DISPLAY_MODE 0x0D #define DSI_GET_GREEN_CHANNEL 0x07 #define DSI_GET_PIXEL_FORMAT 0x0C #define DSI_GET_POWER_MODE 0x0A #define DSI_GET_RED_CHANNEL 0x06 #define DSI_GET_SCANLINE 0x45 #define DSI_GET_SIGNAL_MODE 0x0E #define DSI_NOP 0x00 #define DSI_READ_DDB_CONTINUE 0xA8 #define DSI_READ_DDB_START 0xA1 #define DSI_READ_MEMORY_CONTINUE 0x3E #define DSI_READ_MEMORY_START 0x2E #define DSI_SET_3D_CONTROL 0x3D #define DSI_SET_ADDRESS_MODE 0x36 #define DSI_SET_COLUMN_ADDRESS 0x2A #define DSI_SET_DISPLAY_OFF 0x28 #define DSI_SET_DISPLAY_ON 0x29 #define DSI_SET_GAMMA_CURVE 0x26 #define DSI_SET_PAGE_ADDRESS 0x2B #define DSI_SET_PARTIAL_COLUMNS 0x31 #define DSI_SET_PARTIAL_ROWS 0x30 #define DSI_SET_PIXEL_FORMAT 0x3A #define DSI_SET_SCROLL_AREA 0x33 #define DSI_SET_SCROLL_START 0x37 #define DSI_SET_TEAR_OFF 0x34 #define DSI_SET_TEAR_ON 0x35 #define DSI_SET_TEAR_SCANLINE 0x44 #define DSI_SET_VSYNC_TIMING 0x40 #define DSI_SOFT_RESET 0x01 #define DSI_WRITE_LUT 0x2D #define DSI_WRITE_MEMORY_CONTINUE 0x3C #define DSI_WRITE_MEMORY_START 0x2C /** * @} */ /** @defgroup DSI_Video_Mode_Type DSI Video Mode Type * @{ */ #define DSI_VID_MODE_NB_PULSES 0 #define DSI_VID_MODE_NB_EVENTS 1 #define DSI_VID_MODE_BURST 2 /** * @} */ /** @defgroup DSI_Color_Mode DSI Color Mode * @{ */ #define DSI_COLOR_MODE_FULL 0 #define DSI_COLOR_MODE_EIGHT DSI_WCR_COLM /** * @} */ /** @defgroup DSI_ShutDown DSI ShutDown * @{ */ #define DSI_DISPLAY_ON 0 #define DSI_DISPLAY_OFF DSI_WCR_SHTDN /** * @} */ /** @defgroup DSI_LP_Command DSI LP Command * @{ */ #define DSI_LP_COMMAND_DISABLE 0 #define DSI_LP_COMMAND_ENABLE DSI_VMCR_LPCE /** * @} */ /** @defgroup DSI_LP_HFP DSI LP HFP * @{ */ #define DSI_LP_HFP_DISABLE 0 #define DSI_LP_HFP_ENABLE DSI_VMCR_LPHFPE /** * @} */ /** @defgroup DSI_LP_HBP DSI LP HBP * @{ */ #define DSI_LP_HBP_DISABLE 0 #define DSI_LP_HBP_ENABLE DSI_VMCR_LPHBPE /** * @} */ /** @defgroup DSI_LP_VACT DSI LP VACT * @{ */ #define DSI_LP_VACT_DISABLE 0 #define DSI_LP_VACT_ENABLE DSI_VMCR_LPVAE /** * @} */ /** @defgroup DSI_LP_VFP DSI LP VFP * @{ */ #define DSI_LP_VFP_DISABLE 0 #define DSI_LP_VFP_ENABLE DSI_VMCR_LPVFPE /** * @} */ /** @defgroup DSI_LP_VBP DSI LP VBP * @{ */ #define DSI_LP_VBP_DISABLE 0 #define DSI_LP_VBP_ENABLE DSI_VMCR_LPVBPE /** * @} */ /** @defgroup DSI_LP_VSYNC DSI LP VSYNC * @{ */ #define DSI_LP_VSYNC_DISABLE 0 #define DSI_LP_VSYNC_ENABLE DSI_VMCR_LPVSAE /** * @} */ /** @defgroup DSI_FBTA_acknowledge DSI FBTA Acknowledge * @{ */ #define DSI_FBTAA_DISABLE 0 #define DSI_FBTAA_ENABLE DSI_VMCR_FBTAAE /** * @} */ /** @defgroup DSI_TearingEffectSource DSI Tearing Effect Source * @{ */ #define DSI_TE_DSILINK 0 #define DSI_TE_EXTERNAL DSI_WCFGR_TESRC /** * @} */ /** @defgroup DSI_TearingEffectPolarity DSI Tearing Effect Polarity * @{ */ #define DSI_TE_RISING_EDGE 0 #define DSI_TE_FALLING_EDGE DSI_WCFGR_TEPOL /** * @} */ /** @defgroup DSI_Vsync_Polarity DSI Vsync Polarity * @{ */ #define DSI_VSYNC_FALLING 0 #define DSI_VSYNC_RISING DSI_WCFGR_VSPOL /** * @} */ /** @defgroup DSI_AutomaticRefresh DSI Automatic Refresh * @{ */ #define DSI_AR_DISABLE 0 #define DSI_AR_ENABLE DSI_WCFGR_AR /** * @} */ /** @defgroup DSI_TE_AcknowledgeRequest DSI TE Acknowledge Request * @{ */ #define DSI_TE_ACKNOWLEDGE_DISABLE 0 #define DSI_TE_ACKNOWLEDGE_ENABLE DSI_CMCR_TEARE /** * @} */ /** @defgroup DSI_AcknowledgeRequest DSI Acknowledge Request * @{ */ #define DSI_ACKNOWLEDGE_DISABLE 0 #define DSI_ACKNOWLEDGE_ENABLE DSI_CMCR_ARE /** * @} */ /** @defgroup DSI_LP_LPGenShortWriteNoP DSI LP LPGen Short Write NoP * @{ */ #define DSI_LP_GSW0P_DISABLE 0 #define DSI_LP_GSW0P_ENABLE DSI_CMCR_GSW0TX /** * @} */ /** @defgroup DSI_LP_LPGenShortWriteOneP DSI LP LPGen Short Write OneP * @{ */ #define DSI_LP_GSW1P_DISABLE 0 #define DSI_LP_GSW1P_ENABLE DSI_CMCR_GSW1TX /** * @} */ /** @defgroup DSI_LP_LPGenShortWriteTwoP DSI LP LPGen Short Write TwoP * @{ */ #define DSI_LP_GSW2P_DISABLE 0 #define DSI_LP_GSW2P_ENABLE DSI_CMCR_GSW2TX /** * @} */ /** @defgroup DSI_LP_LPGenShortReadNoP DSI LP LPGen Short Read NoP * @{ */ #define DSI_LP_GSR0P_DISABLE 0 #define DSI_LP_GSR0P_ENABLE DSI_CMCR_GSR0TX /** * @} */ /** @defgroup DSI_LP_LPGenShortReadOneP DSI LP LPGen Short Read OneP * @{ */ #define DSI_LP_GSR1P_DISABLE 0 #define DSI_LP_GSR1P_ENABLE DSI_CMCR_GSR1TX /** * @} */ /** @defgroup DSI_LP_LPGenShortReadTwoP DSI LP LPGen Short Read TwoP * @{ */ #define DSI_LP_GSR2P_DISABLE 0 #define DSI_LP_GSR2P_ENABLE DSI_CMCR_GSR2TX /** * @} */ /** @defgroup DSI_LP_LPGenLongWrite DSI LP LPGen LongWrite * @{ */ #define DSI_LP_GLW_DISABLE 0 #define DSI_LP_GLW_ENABLE DSI_CMCR_GLWTX /** * @} */ /** @defgroup DSI_LP_LPDcsShortWriteNoP DSI LP LPDcs Short Write NoP * @{ */ #define DSI_LP_DSW0P_DISABLE 0 #define DSI_LP_DSW0P_ENABLE DSI_CMCR_DSW0TX /** * @} */ /** @defgroup DSI_LP_LPDcsShortWriteOneP DSI LP LPDcs Short Write OneP * @{ */ #define DSI_LP_DSW1P_DISABLE 0 #define DSI_LP_DSW1P_ENABLE DSI_CMCR_DSW1TX /** * @} */ /** @defgroup DSI_LP_LPDcsShortReadNoP DSI LP LPDcs Short Read NoP * @{ */ #define DSI_LP_DSR0P_DISABLE 0 #define DSI_LP_DSR0P_ENABLE DSI_CMCR_DSR0TX /** * @} */ /** @defgroup DSI_LP_LPDcsLongWrite DSI LP LPDcs Long Write * @{ */ #define DSI_LP_DLW_DISABLE 0 #define DSI_LP_DLW_ENABLE DSI_CMCR_DLWTX /** * @} */ /** @defgroup DSI_LP_LPMaxReadPacket DSI LP LPMax Read Packet * @{ */ #define DSI_LP_MRDP_DISABLE 0 #define DSI_LP_MRDP_ENABLE DSI_CMCR_MRDPS /** * @} */ /** @defgroup DSI_HS_PrespMode DSI HS Presp Mode * @{ */ #define DSI_HS_PM_DISABLE 0 #define DSI_HS_PM_ENABLE DSI_TCCR3_PM /** * @} */ /** @defgroup DSI_Automatic_Clk_Lane_Control DSI Automatic Clk Lane Control * @{ */ #define DSI_AUTO_CLK_LANE_CTRL_DISABLE 0 #define DSI_AUTO_CLK_LANE_CTRL_ENABLE DSI_CLCR_ACR /** * @} */ /** @defgroup DSI_Number_Of_Lanes DSI Number Of Lanes * @{ */ #define DSI_ONE_DATA_LANE 0 #define DSI_TWO_DATA_LANES 1 /** * @} */ /** @defgroup DSI_FlowControl DSI Flow Control * @{ */ #define DSI_FLOW_CONTROL_CRC_RX DSI_PCR_CRCRXE #define DSI_FLOW_CONTROL_ECC_RX DSI_PCR_ECCRXE #define DSI_FLOW_CONTROL_BTA DSI_PCR_BTAE #define DSI_FLOW_CONTROL_EOTP_RX DSI_PCR_ETRXE #define DSI_FLOW_CONTROL_EOTP_TX DSI_PCR_ETTXE #define DSI_FLOW_CONTROL_ALL (DSI_FLOW_CONTROL_CRC_RX | DSI_FLOW_CONTROL_ECC_RX | \ DSI_FLOW_CONTROL_BTA | DSI_FLOW_CONTROL_EOTP_RX | \ DSI_FLOW_CONTROL_EOTP_TX) /** * @} */ /** @defgroup DSI_Color_Coding DSI Color Coding * @{ */ #define DSI_RGB565 ((uint32_t)0x00000000) /*!< The values 0x00000001 and 0x00000002 can also be used for the RGB565 color mode configuration */ #define DSI_RGB666 ((uint32_t)0x00000003) /*!< The value 0x00000004 can also be used for the RGB666 color mode configuration */ #define DSI_RGB888 ((uint32_t)0x00000005) /** * @} */ /** @defgroup DSI_LooselyPacked DSI Loosely Packed * @{ */ #define DSI_LOOSELY_PACKED_ENABLE DSI_LCOLCR_LPE #define DSI_LOOSELY_PACKED_DISABLE 0 /** * @} */ /** @defgroup DSI_HSYNC_Polarity DSI HSYNC Polarity * @{ */ #define DSI_HSYNC_ACTIVE_HIGH 0 #define DSI_HSYNC_ACTIVE_LOW DSI_LPCR_HSP /** * @} */ /** @defgroup DSI_VSYNC_Polarity DSI VSYNC Polarity * @{ */ #define DSI_VSYNC_ACTIVE_HIGH 0 #define DSI_VSYNC_ACTIVE_LOW DSI_LPCR_VSP /** * @} */ /** @defgroup DSI_DATA_ENABLE_Polarity DSI DATA ENABLE Polarity * @{ */ #define DSI_DATA_ENABLE_ACTIVE_HIGH 0 #define DSI_DATA_ENABLE_ACTIVE_LOW DSI_LPCR_DEP /** * @} */ /** @defgroup DSI_PLL_IDF DSI PLL IDF * @{ */ #define DSI_PLL_IN_DIV1 ((uint32_t)0x00000001) #define DSI_PLL_IN_DIV2 ((uint32_t)0x00000002) #define DSI_PLL_IN_DIV3 ((uint32_t)0x00000003) #define DSI_PLL_IN_DIV4 ((uint32_t)0x00000004) #define DSI_PLL_IN_DIV5 ((uint32_t)0x00000005) #define DSI_PLL_IN_DIV6 ((uint32_t)0x00000006) #define DSI_PLL_IN_DIV7 ((uint32_t)0x00000007) /** * @} */ /** @defgroup DSI_PLL_ODF DSI PLL ODF * @{ */ #define DSI_PLL_OUT_DIV1 ((uint32_t)0x00000000) #define DSI_PLL_OUT_DIV2 ((uint32_t)0x00000001) #define DSI_PLL_OUT_DIV4 ((uint32_t)0x00000002) #define DSI_PLL_OUT_DIV8 ((uint32_t)0x00000003) /** * @} */ /** @defgroup DSI_Flags DSI Flags * @{ */ #define DSI_FLAG_TE DSI_WISR_TEIF #define DSI_FLAG_ER DSI_WISR_ERIF #define DSI_FLAG_BUSY DSI_WISR_BUSY #define DSI_FLAG_PLLLS DSI_WISR_PLLLS #define DSI_FLAG_PLLL DSI_WISR_PLLLIF #define DSI_FLAG_PLLU DSI_WISR_PLLUIF #define DSI_FLAG_RRS DSI_WISR_RRS #define DSI_FLAG_RR DSI_WISR_RRIF /** * @} */ /** @defgroup DSI_Interrupts DSI Interrupts * @{ */ #define DSI_IT_TE DSI_WIER_TEIE #define DSI_IT_ER DSI_WIER_ERIE #define DSI_IT_PLLL DSI_WIER_PLLLIE #define DSI_IT_PLLU DSI_WIER_PLLUIE #define DSI_IT_RR DSI_WIER_RRIE /** * @} */ /** @defgroup DSI_SHORT_WRITE_PKT_Data_Type DSI SHORT WRITE PKT Data Type * @{ */ #define DSI_DCS_SHORT_PKT_WRITE_P0 ((uint32_t)0x00000005) /*!< DCS short write, no parameters */ #define DSI_DCS_SHORT_PKT_WRITE_P1 ((uint32_t)0x00000015) /*!< DCS short write, one parameter */ #define DSI_GEN_SHORT_PKT_WRITE_P0 ((uint32_t)0x00000003) /*!< Generic short write, no parameters */ #define DSI_GEN_SHORT_PKT_WRITE_P1 ((uint32_t)0x00000013) /*!< Generic short write, one parameter */ #define DSI_GEN_SHORT_PKT_WRITE_P2 ((uint32_t)0x00000023) /*!< Generic short write, two parameters */ /** * @} */ /** @defgroup DSI_LONG_WRITE_PKT_Data_Type DSI LONG WRITE PKT Data Type * @{ */ #define DSI_DCS_LONG_PKT_WRITE ((uint32_t)0x00000039) /*!< DCS long write */ #define DSI_GEN_LONG_PKT_WRITE ((uint32_t)0x00000029) /*!< Generic long write */ /** * @} */ /** @defgroup DSI_SHORT_READ_PKT_Data_Type DSI SHORT READ PKT Data Type * @{ */ #define DSI_DCS_SHORT_PKT_READ ((uint32_t)0x00000006) /*!< DCS short read */ #define DSI_GEN_SHORT_PKT_READ_P0 ((uint32_t)0x00000004) /*!< Generic short read, no parameters */ #define DSI_GEN_SHORT_PKT_READ_P1 ((uint32_t)0x00000014) /*!< Generic short read, one parameter */ #define DSI_GEN_SHORT_PKT_READ_P2 ((uint32_t)0x00000024) /*!< Generic short read, two parameters */ /** * @} */ /** @defgroup DSI_Error_Data_Type DSI Error Data Type * @{ */ #define HAL_DSI_ERROR_NONE 0 #define HAL_DSI_ERROR_ACK ((uint32_t)0x00000001) /*!< acknowledge errors */ #define HAL_DSI_ERROR_PHY ((uint32_t)0x00000002) /*!< PHY related errors */ #define HAL_DSI_ERROR_TX ((uint32_t)0x00000004) /*!< transmission error */ #define HAL_DSI_ERROR_RX ((uint32_t)0x00000008) /*!< reception error */ #define HAL_DSI_ERROR_ECC ((uint32_t)0x00000010) /*!< ECC errors */ #define HAL_DSI_ERROR_CRC ((uint32_t)0x00000020) /*!< CRC error */ #define HAL_DSI_ERROR_PSE ((uint32_t)0x00000040) /*!< Packet Size error */ #define HAL_DSI_ERROR_EOT ((uint32_t)0x00000080) /*!< End Of Transmission error */ #define HAL_DSI_ERROR_OVF ((uint32_t)0x00000100) /*!< FIFO overflow error */ #define HAL_DSI_ERROR_GEN ((uint32_t)0x00000200) /*!< Generic FIFO related errors */ /** * @} */ /** @defgroup DSI_Lane_Group DSI Lane Group * @{ */ #define DSI_CLOCK_LANE ((uint32_t)0x00000000) #define DSI_DATA_LANES ((uint32_t)0x00000001) /** * @} */ /** @defgroup DSI_Communication_Delay DSI Communication Delay * @{ */ #define DSI_SLEW_RATE_HSTX ((uint32_t)0x00000000) #define DSI_SLEW_RATE_LPTX ((uint32_t)0x00000001) #define DSI_HS_DELAY ((uint32_t)0x00000002) /** * @} */ /** @defgroup DSI_CustomLane DSI CustomLane * @{ */ #define DSI_SWAP_LANE_PINS ((uint32_t)0x00000000) #define DSI_INVERT_HS_SIGNAL ((uint32_t)0x00000001) /** * @} */ /** @defgroup DSI_Lane_Select DSI Lane Select * @{ */ #define DSI_CLOCK_LANE ((uint32_t)0x00000000) #define DSI_DATA_LANE0 ((uint32_t)0x00000001) #define DSI_DATA_LANE1 ((uint32_t)0x00000002) /** * @} */ /** @defgroup DSI_PHY_Timing DSI PHY Timing * @{ */ #define DSI_TCLK_POST ((uint32_t)0x00000000) #define DSI_TLPX_CLK ((uint32_t)0x00000001) #define DSI_THS_EXIT ((uint32_t)0x00000002) #define DSI_TLPX_DATA ((uint32_t)0x00000003) #define DSI_THS_ZERO ((uint32_t)0x00000004) #define DSI_THS_TRAIL ((uint32_t)0x00000005) #define DSI_THS_PREPARE ((uint32_t)0x00000006) #define DSI_TCLK_ZERO ((uint32_t)0x00000007) #define DSI_TCLK_PREPARE ((uint32_t)0x00000008) /** * @} */ /* Exported macros -----------------------------------------------------------*/ /** * @brief Enables the DSI host. * @param __HANDLE__: DSI handle * @retval None. */ #define __HAL_DSI_ENABLE(__HANDLE__) ((__HANDLE__)->Instance->CR |= DSI_CR_EN) /** * @brief Disables the DSI host. * @param __HANDLE__: DSI handle * @retval None. */ #define __HAL_DSI_DISABLE(__HANDLE__) ((__HANDLE__)->Instance->CR &= ~DSI_CR_EN) /** * @brief Enables the DSI wrapper. * @param __HANDLE__: DSI handle * @retval None. */ #define __HAL_DSI_WRAPPER_ENABLE(__HANDLE__) ((__HANDLE__)->Instance->WCR |= DSI_WCR_DSIEN) /** * @brief Disable the DSI wrapper. * @param __HANDLE__: DSI handle * @retval None. */ #define __HAL_DSI_WRAPPER_DISABLE(__HANDLE__) ((__HANDLE__)->Instance->WCR &= ~DSI_WCR_DSIEN) /** * @brief Enables the DSI PLL. * @param __HANDLE__: DSI handle * @retval None. */ #define __HAL_DSI_PLL_ENABLE(__HANDLE__) ((__HANDLE__)->Instance->WRPCR |= DSI_WRPCR_PLLEN) /** * @brief Disables the DSI PLL. * @param __HANDLE__: DSI handle * @retval None. */ #define __HAL_DSI_PLL_DISABLE(__HANDLE__) ((__HANDLE__)->Instance->WRPCR &= ~DSI_WRPCR_PLLEN) /** * @brief Enables the DSI regulator. * @param __HANDLE__: DSI handle * @retval None. */ #define __HAL_DSI_REG_ENABLE(__HANDLE__) ((__HANDLE__)->Instance->WRPCR |= DSI_WRPCR_REGEN) /** * @brief Disables the DSI regulator. * @param __HANDLE__: DSI handle * @retval None. */ #define __HAL_DSI_REG_DISABLE(__HANDLE__) ((__HANDLE__)->Instance->WRPCR &= ~DSI_WRPCR_REGEN) /** * @brief Get the DSI pending flags. * @param __HANDLE__: DSI handle. * @param __FLAG__: Get the specified flag. * This parameter can be any combination of the following values: * @arg DSI_FLAG_TE : Tearing Effect Interrupt Flag * @arg DSI_FLAG_ER : End of Refresh Interrupt Flag * @arg DSI_FLAG_BUSY : Busy Flag * @arg DSI_FLAG_PLLLS: PLL Lock Status * @arg DSI_FLAG_PLLL : PLL Lock Interrupt Flag * @arg DSI_FLAG_PLLU : PLL Unlock Interrupt Flag * @arg DSI_FLAG_RRS : Regulator Ready Flag * @arg DSI_FLAG_RR : Regulator Ready Interrupt Flag * @retval The state of FLAG (SET or RESET). */ #define __HAL_DSI_GET_FLAG(__HANDLE__, __FLAG__) ((__HANDLE__)->Instance->WISR & (__FLAG__)) /** * @brief Clears the DSI pending flags. * @param __HANDLE__: DSI handle. * @param __FLAG__: specifies the flag to clear. * This parameter can be any combination of the following values: * @arg DSI_FLAG_TE : Tearing Effect Interrupt Flag * @arg DSI_FLAG_ER : End of Refresh Interrupt Flag * @arg DSI_FLAG_PLLL : PLL Lock Interrupt Flag * @arg DSI_FLAG_PLLU : PLL Unlock Interrupt Flag * @arg DSI_FLAG_RR : Regulator Ready Interrupt Flag * @retval None */ #define __HAL_DSI_CLEAR_FLAG(__HANDLE__, __FLAG__) ((__HANDLE__)->Instance->WIFCR = (__FLAG__)) /** * @brief Enables the specified DSI interrupts. * @param __HANDLE__: DSI handle. * @param __INTERRUPT__: specifies the DSI interrupt sources to be enabled. * This parameter can be any combination of the following values: * @arg DSI_IT_TE : Tearing Effect Interrupt * @arg DSI_IT_ER : End of Refresh Interrupt * @arg DSI_IT_PLLL: PLL Lock Interrupt * @arg DSI_IT_PLLU: PLL Unlock Interrupt * @arg DSI_IT_RR : Regulator Ready Interrupt * @retval None */ #define __HAL_DSI_ENABLE_IT(__HANDLE__, __INTERRUPT__) ((__HANDLE__)->Instance->WIER |= (__INTERRUPT__)) /** * @brief Disables the specified DSI interrupts. * @param __HANDLE__: DSI handle * @param __INTERRUPT__: specifies the DSI interrupt sources to be disabled. * This parameter can be any combination of the following values: * @arg DSI_IT_TE : Tearing Effect Interrupt * @arg DSI_IT_ER : End of Refresh Interrupt * @arg DSI_IT_PLLL: PLL Lock Interrupt * @arg DSI_IT_PLLU: PLL Unlock Interrupt * @arg DSI_IT_RR : Regulator Ready Interrupt * @retval None */ #define __HAL_DSI_DISABLE_IT(__HANDLE__, __INTERRUPT__) ((__HANDLE__)->Instance->WIER &= ~(__INTERRUPT__)) /** * @brief Checks whether the specified DSI interrupt has occurred or not. * @param __HANDLE__: DSI handle * @param __INTERRUPT__: specifies the DSI interrupt source to check. * This parameter can be one of the following values: * @arg DSI_IT_TE : Tearing Effect Interrupt * @arg DSI_IT_ER : End of Refresh Interrupt * @arg DSI_IT_PLLL: PLL Lock Interrupt * @arg DSI_IT_PLLU: PLL Unlock Interrupt * @arg DSI_IT_RR : Regulator Ready Interrupt * @retval The state of INTERRUPT (SET or RESET). */ #define __HAL_DSI_GET_IT_SOURCE(__HANDLE__, __INTERRUPT__) ((__HANDLE__)->Instance->WISR & (__INTERRUPT__)) /* Exported functions --------------------------------------------------------*/ /** @defgroup DSI_Exported_Functions DSI Exported Functions * @{ */ HAL_StatusTypeDef HAL_DSI_Init(DSI_HandleTypeDef *hdsi, DSI_PLLInitTypeDef *PLLInit); HAL_StatusTypeDef HAL_DSI_DeInit(DSI_HandleTypeDef *hdsi); void HAL_DSI_MspInit(DSI_HandleTypeDef *hdsi); void HAL_DSI_MspDeInit(DSI_HandleTypeDef *hdsi); void HAL_DSI_IRQHandler(DSI_HandleTypeDef *hdsi); void HAL_DSI_TearingEffectCallback(DSI_HandleTypeDef *hdsi); void HAL_DSI_EndOfRefreshCallback(DSI_HandleTypeDef *hdsi); void HAL_DSI_ErrorCallback(DSI_HandleTypeDef *hdsi); HAL_StatusTypeDef HAL_DSI_SetGenericVCID(DSI_HandleTypeDef *hdsi, uint32_t VirtualChannelID); HAL_StatusTypeDef HAL_DSI_ConfigVideoMode(DSI_HandleTypeDef *hdsi, DSI_VidCfgTypeDef *VidCfg); HAL_StatusTypeDef HAL_DSI_ConfigAdaptedCommandMode(DSI_HandleTypeDef *hdsi, DSI_CmdCfgTypeDef *CmdCfg); HAL_StatusTypeDef HAL_DSI_ConfigCommand(DSI_HandleTypeDef *hdsi, DSI_LPCmdTypeDef *LPCmd); HAL_StatusTypeDef HAL_DSI_ConfigFlowControl(DSI_HandleTypeDef *hdsi, uint32_t FlowControl); HAL_StatusTypeDef HAL_DSI_ConfigPhyTimer(DSI_HandleTypeDef *hdsi, DSI_PHY_TimerTypeDef *PhyTimings); HAL_StatusTypeDef HAL_DSI_ConfigHostTimeouts(DSI_HandleTypeDef *hdsi, DSI_HOST_TimeoutTypeDef *HostTimeouts); HAL_StatusTypeDef HAL_DSI_Start(DSI_HandleTypeDef *hdsi); HAL_StatusTypeDef HAL_DSI_Stop(DSI_HandleTypeDef *hdsi); HAL_StatusTypeDef HAL_DSI_Refresh(DSI_HandleTypeDef *hdsi); HAL_StatusTypeDef HAL_DSI_ColorMode(DSI_HandleTypeDef *hdsi, uint32_t ColorMode); HAL_StatusTypeDef HAL_DSI_Shutdown(DSI_HandleTypeDef *hdsi, uint32_t Shutdown); HAL_StatusTypeDef HAL_DSI_ShortWrite(DSI_HandleTypeDef *hdsi, uint32_t ChannelID, uint32_t Mode, uint32_t Param1, uint32_t Param2); HAL_StatusTypeDef HAL_DSI_LongWrite(DSI_HandleTypeDef *hdsi, uint32_t ChannelID, uint32_t Mode, uint32_t Nbparams, uint32_t Param1, uint8_t* ParametersTable); HAL_StatusTypeDef HAL_DSI_Read(DSI_HandleTypeDef *hdsi, uint32_t ChannelNbr, uint8_t* Array, uint32_t Size, uint32_t Mode, uint32_t DCSCmd, uint8_t* ParametersTable); HAL_StatusTypeDef HAL_DSI_EnterULPMData(DSI_HandleTypeDef *hdsi); HAL_StatusTypeDef HAL_DSI_ExitULPMData(DSI_HandleTypeDef *hdsi); HAL_StatusTypeDef HAL_DSI_EnterULPM(DSI_HandleTypeDef *hdsi); HAL_StatusTypeDef HAL_DSI_ExitULPM(DSI_HandleTypeDef *hdsi); HAL_StatusTypeDef HAL_DSI_PatternGeneratorStart(DSI_HandleTypeDef *hdsi, uint32_t Mode, uint32_t Orientation); HAL_StatusTypeDef HAL_DSI_PatternGeneratorStop(DSI_HandleTypeDef *hdsi); HAL_StatusTypeDef HAL_DSI_SetSlewRateAndDelayTuning(DSI_HandleTypeDef *hdsi, uint32_t CommDelay, uint32_t Lane, uint32_t Value); HAL_StatusTypeDef HAL_DSI_SetLowPowerRXFilter(DSI_HandleTypeDef *hdsi, uint32_t Frequency); HAL_StatusTypeDef HAL_DSI_SetSDD(DSI_HandleTypeDef *hdsi, FunctionalState State); HAL_StatusTypeDef HAL_DSI_SetLanePinsConfiguration(DSI_HandleTypeDef *hdsi, uint32_t CustomLane, uint32_t Lane, FunctionalState State); HAL_StatusTypeDef HAL_DSI_SetPHYTimings(DSI_HandleTypeDef *hdsi, uint32_t Timing, FunctionalState State, uint32_t Value); HAL_StatusTypeDef HAL_DSI_ForceTXStopMode(DSI_HandleTypeDef *hdsi, uint32_t Lane, FunctionalState State); HAL_StatusTypeDef HAL_DSI_ForceRXLowPower(DSI_HandleTypeDef *hdsi, FunctionalState State); HAL_StatusTypeDef HAL_DSI_ForceDataLanesInRX(DSI_HandleTypeDef *hdsi, FunctionalState State); HAL_StatusTypeDef HAL_DSI_SetPullDown(DSI_HandleTypeDef *hdsi, FunctionalState State); HAL_StatusTypeDef HAL_DSI_SetContentionDetectionOff(DSI_HandleTypeDef *hdsi, FunctionalState State); uint32_t HAL_DSI_GetError(DSI_HandleTypeDef *hdsi); HAL_StatusTypeDef HAL_DSI_ConfigErrorMonitor(DSI_HandleTypeDef *hdsi, uint32_t ActiveErrors); HAL_DSI_StateTypeDef HAL_DSI_GetState(DSI_HandleTypeDef *hdsi); /** * @} */ /* Private types -------------------------------------------------------------*/ /** @defgroup DSI_Private_Types DSI Private Types * @{ */ /** * @} */ /* Private defines -----------------------------------------------------------*/ /** @defgroup DSI_Private_Defines DSI Private Defines * @{ */ /** * @} */ /* Private variables ---------------------------------------------------------*/ /** @defgroup DSI_Private_Variables DSI Private Variables * @{ */ /** * @} */ /* Private constants ---------------------------------------------------------*/ /** @defgroup DSI_Private_Constants DSI Private Constants * @{ */ #define DSI_MAX_RETURN_PKT_SIZE ((uint32_t)0x00000037) /*!< Maximum return packet configuration */ /** * @} */ /* Private macros ------------------------------------------------------------*/ /** @defgroup DSI_Private_Macros DSI Private Macros * @{ */ #define IS_DSI_PLL_NDIV(NDIV) ((10 <= (NDIV)) && ((NDIV) <= 125)) #define IS_DSI_PLL_IDF(IDF) (((IDF) == DSI_PLL_IN_DIV1) || \ ((IDF) == DSI_PLL_IN_DIV2) || \ ((IDF) == DSI_PLL_IN_DIV3) || \ ((IDF) == DSI_PLL_IN_DIV4) || \ ((IDF) == DSI_PLL_IN_DIV5) || \ ((IDF) == DSI_PLL_IN_DIV6) || \ ((IDF) == DSI_PLL_IN_DIV7)) #define IS_DSI_PLL_ODF(ODF) (((ODF) == DSI_PLL_OUT_DIV1) || \ ((ODF) == DSI_PLL_OUT_DIV2) || \ ((ODF) == DSI_PLL_OUT_DIV4) || \ ((ODF) == DSI_PLL_OUT_DIV8)) #define IS_DSI_AUTO_CLKLANE_CONTROL(AutoClkLane) (((AutoClkLane) == DSI_AUTO_CLK_LANE_CTRL_DISABLE) || ((AutoClkLane) == DSI_AUTO_CLK_LANE_CTRL_ENABLE)) #define IS_DSI_NUMBER_OF_LANES(NumberOfLanes) (((NumberOfLanes) == DSI_ONE_DATA_LANE) || ((NumberOfLanes) == DSI_TWO_DATA_LANES)) #define IS_DSI_FLOW_CONTROL(FlowControl) (((FlowControl) | DSI_FLOW_CONTROL_ALL) == DSI_FLOW_CONTROL_ALL) #define IS_DSI_COLOR_CODING(ColorCoding) ((ColorCoding) <= 5) #define IS_DSI_LOOSELY_PACKED(LooselyPacked) (((LooselyPacked) == DSI_LOOSELY_PACKED_ENABLE) || ((LooselyPacked) == DSI_LOOSELY_PACKED_DISABLE)) #define IS_DSI_DE_POLARITY(DataEnable) (((DataEnable) == DSI_DATA_ENABLE_ACTIVE_HIGH) || ((DataEnable) == DSI_DATA_ENABLE_ACTIVE_LOW)) #define IS_DSI_VSYNC_POLARITY(VSYNC) (((VSYNC) == DSI_VSYNC_ACTIVE_HIGH) || ((VSYNC) == DSI_VSYNC_ACTIVE_LOW)) #define IS_DSI_HSYNC_POLARITY(HSYNC) (((HSYNC) == DSI_HSYNC_ACTIVE_HIGH) || ((HSYNC) == DSI_HSYNC_ACTIVE_LOW)) #define IS_DSI_VIDEO_MODE_TYPE(VideoModeType) (((VideoModeType) == DSI_VID_MODE_NB_PULSES) || \ ((VideoModeType) == DSI_VID_MODE_NB_EVENTS) || \ ((VideoModeType) == DSI_VID_MODE_BURST)) #define IS_DSI_COLOR_MODE(ColorMode) (((ColorMode) == DSI_COLOR_MODE_FULL) || ((ColorMode) == DSI_COLOR_MODE_EIGHT)) #define IS_DSI_SHUT_DOWN(ShutDown) (((ShutDown) == DSI_DISPLAY_ON) || ((ShutDown) == DSI_DISPLAY_OFF)) #define IS_DSI_LP_COMMAND(LPCommand) (((LPCommand) == DSI_LP_COMMAND_DISABLE) || ((LPCommand) == DSI_LP_COMMAND_ENABLE)) #define IS_DSI_LP_HFP(LPHFP) (((LPHFP) == DSI_LP_HFP_DISABLE) || ((LPHFP) == DSI_LP_HFP_ENABLE)) #define IS_DSI_LP_HBP(LPHBP) (((LPHBP) == DSI_LP_HBP_DISABLE) || ((LPHBP) == DSI_LP_HBP_ENABLE)) #define IS_DSI_LP_VACTIVE(LPVActive) (((LPVActive) == DSI_LP_VACT_DISABLE) || ((LPVActive) == DSI_LP_VACT_ENABLE)) #define IS_DSI_LP_VFP(LPVFP) (((LPVFP) == DSI_LP_VFP_DISABLE) || ((LPVFP) == DSI_LP_VFP_ENABLE)) #define IS_DSI_LP_VBP(LPVBP) (((LPVBP) == DSI_LP_VBP_DISABLE) || ((LPVBP) == DSI_LP_VBP_ENABLE)) #define IS_DSI_LP_VSYNC(LPVSYNC) (((LPVSYNC) == DSI_LP_VSYNC_DISABLE) || ((LPVSYNC) == DSI_LP_VSYNC_ENABLE)) #define IS_DSI_FBTAA(FrameBTAAcknowledge) (((FrameBTAAcknowledge) == DSI_FBTAA_DISABLE) || ((FrameBTAAcknowledge) == DSI_FBTAA_ENABLE)) #define IS_DSI_TE_SOURCE(TESource) (((TESource) == DSI_TE_DSILINK) || ((TESource) == DSI_TE_EXTERNAL)) #define IS_DSI_TE_POLARITY(TEPolarity) (((TEPolarity) == DSI_TE_RISING_EDGE) || ((TEPolarity) == DSI_TE_FALLING_EDGE)) #define IS_DSI_AUTOMATIC_REFRESH(AutomaticRefresh) (((AutomaticRefresh) == DSI_AR_DISABLE) || ((AutomaticRefresh) == DSI_AR_ENABLE)) #define IS_DSI_VS_POLARITY(VSPolarity) (((VSPolarity) == DSI_VSYNC_FALLING) || ((VSPolarity) == DSI_VSYNC_RISING)) #define IS_DSI_TE_ACK_REQUEST(TEAcknowledgeRequest) (((TEAcknowledgeRequest) == DSI_TE_ACKNOWLEDGE_DISABLE) || ((TEAcknowledgeRequest) == DSI_TE_ACKNOWLEDGE_ENABLE)) #define IS_DSI_ACK_REQUEST(AcknowledgeRequest) (((AcknowledgeRequest) == DSI_ACKNOWLEDGE_DISABLE) || ((AcknowledgeRequest) == DSI_ACKNOWLEDGE_ENABLE)) #define IS_DSI_LP_GSW0P(LP_GSW0P) (((LP_GSW0P) == DSI_LP_GSW0P_DISABLE) || ((LP_GSW0P) == DSI_LP_GSW0P_ENABLE)) #define IS_DSI_LP_GSW1P(LP_GSW1P) (((LP_GSW1P) == DSI_LP_GSW1P_DISABLE) || ((LP_GSW1P) == DSI_LP_GSW1P_ENABLE)) #define IS_DSI_LP_GSW2P(LP_GSW2P) (((LP_GSW2P) == DSI_LP_GSW2P_DISABLE) || ((LP_GSW2P) == DSI_LP_GSW2P_ENABLE)) #define IS_DSI_LP_GSR0P(LP_GSR0P) (((LP_GSR0P) == DSI_LP_GSR0P_DISABLE) || ((LP_GSR0P) == DSI_LP_GSR0P_ENABLE)) #define IS_DSI_LP_GSR1P(LP_GSR1P) (((LP_GSR1P) == DSI_LP_GSR1P_DISABLE) || ((LP_GSR1P) == DSI_LP_GSR1P_ENABLE)) #define IS_DSI_LP_GSR2P(LP_GSR2P) (((LP_GSR2P) == DSI_LP_GSR2P_DISABLE) || ((LP_GSR2P) == DSI_LP_GSR2P_ENABLE)) #define IS_DSI_LP_GLW(LP_GLW) (((LP_GLW) == DSI_LP_GLW_DISABLE) || ((LP_GLW) == DSI_LP_GLW_ENABLE)) #define IS_DSI_LP_DSW0P(LP_DSW0P) (((LP_DSW0P) == DSI_LP_DSW0P_DISABLE) || ((LP_DSW0P) == DSI_LP_DSW0P_ENABLE)) #define IS_DSI_LP_DSW1P(LP_DSW1P) (((LP_DSW1P) == DSI_LP_DSW1P_DISABLE) || ((LP_DSW1P) == DSI_LP_DSW1P_ENABLE)) #define IS_DSI_LP_DSR0P(LP_DSR0P) (((LP_DSR0P) == DSI_LP_DSR0P_DISABLE) || ((LP_DSR0P) == DSI_LP_DSR0P_ENABLE)) #define IS_DSI_LP_DLW(LP_DLW) (((LP_DLW) == DSI_LP_DLW_DISABLE) || ((LP_DLW) == DSI_LP_DLW_ENABLE)) #define IS_DSI_LP_MRDP(LP_MRDP) (((LP_MRDP) == DSI_LP_MRDP_DISABLE) || ((LP_MRDP) == DSI_LP_MRDP_ENABLE)) #define IS_DSI_SHORT_WRITE_PACKET_TYPE(MODE) (((MODE) == DSI_DCS_SHORT_PKT_WRITE_P0) || \ ((MODE) == DSI_DCS_SHORT_PKT_WRITE_P1) || \ ((MODE) == DSI_GEN_SHORT_PKT_WRITE_P0) || \ ((MODE) == DSI_GEN_SHORT_PKT_WRITE_P1) || \ ((MODE) == DSI_GEN_SHORT_PKT_WRITE_P2)) #define IS_DSI_LONG_WRITE_PACKET_TYPE(MODE) (((MODE) == DSI_DCS_LONG_PKT_WRITE) || \ ((MODE) == DSI_GEN_LONG_PKT_WRITE)) #define IS_DSI_READ_PACKET_TYPE(MODE) (((MODE) == DSI_DCS_SHORT_PKT_READ) || \ ((MODE) == DSI_GEN_SHORT_PKT_READ_P0) || \ ((MODE) == DSI_GEN_SHORT_PKT_READ_P1) || \ ((MODE) == DSI_GEN_SHORT_PKT_READ_P2)) #define IS_DSI_COMMUNICATION_DELAY(CommDelay) (((CommDelay) == DSI_SLEW_RATE_HSTX) || ((CommDelay) == DSI_SLEW_RATE_LPTX) || ((CommDelay) == DSI_HS_DELAY)) #define IS_DSI_LANE_GROUP(Lane) (((Lane) == DSI_CLOCK_LANE) || ((Lane) == DSI_DATA_LANES)) #define IS_DSI_CUSTOM_LANE(CustomLane) (((CustomLane) == DSI_SWAP_LANE_PINS) || ((CustomLane) == DSI_INVERT_HS_SIGNAL)) #define IS_DSI_LANE(Lane) (((Lane) == DSI_CLOCK_LANE) || ((Lane) == DSI_DATA_LANE0) || ((Lane) == DSI_DATA_LANE1)) #define IS_DSI_PHY_TIMING(Timing) (((Timing) == DSI_TCLK_POST ) || \ ((Timing) == DSI_TLPX_CLK ) || \ ((Timing) == DSI_THS_EXIT ) || \ ((Timing) == DSI_TLPX_DATA ) || \ ((Timing) == DSI_THS_ZERO ) || \ ((Timing) == DSI_THS_TRAIL ) || \ ((Timing) == DSI_THS_PREPARE ) || \ ((Timing) == DSI_TCLK_ZERO ) || \ ((Timing) == DSI_TCLK_PREPARE)) /** * @} */ /* Private functions prototypes ----------------------------------------------*/ /** @defgroup DSI_Private_Functions_Prototypes DSI Private Functions Prototypes * @{ */ /** * @} */ /* Private functions ---------------------------------------------------------*/ /** @defgroup DSI_Private_Functions DSI Private Functions * @{ */ /** * @} */ /** * @} */ /** * @} */ #endif /* STM32F469xx || STM32F479xx */ #ifdef __cplusplus } #endif #endif /* __STM32F4xx_HAL_DSI_H */ /************************ (C) COPYRIGHT STMicroelectronics *****END OF FILE****/ ================================================ FILE: Zelig/mbed/TARGET_NUCLEO_F401RE/stm32f4xx_hal_eth.h ================================================ /** ****************************************************************************** * @file stm32f4xx_hal_eth.h * @author MCD Application Team * @version V1.4.1 * @date 09-October-2015 * @brief Header file of ETH HAL module. ****************************************************************************** * @attention * *

© COPYRIGHT(c) 2015 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. * ****************************************************************************** */ /* Define to prevent recursive inclusion -------------------------------------*/ #ifndef __STM32F4xx_HAL_ETH_H #define __STM32F4xx_HAL_ETH_H #ifdef __cplusplus extern "C" { #endif #if defined(STM32F407xx) || defined(STM32F417xx) || defined(STM32F427xx) || defined(STM32F437xx) ||\ defined(STM32F429xx) || defined(STM32F439xx) || defined(STM32F469xx) || defined(STM32F479xx) /* Includes ------------------------------------------------------------------*/ #include "stm32f4xx_hal_def.h" /** @addtogroup STM32F4xx_HAL_Driver * @{ */ /** @addtogroup ETH * @{ */ /** @addtogroup ETH_Private_Macros * @{ */ #define IS_ETH_PHY_ADDRESS(ADDRESS) ((ADDRESS) <= 0x20) #define IS_ETH_AUTONEGOTIATION(CMD) (((CMD) == ETH_AUTONEGOTIATION_ENABLE) || \ ((CMD) == ETH_AUTONEGOTIATION_DISABLE)) #define IS_ETH_SPEED(SPEED) (((SPEED) == ETH_SPEED_10M) || \ ((SPEED) == ETH_SPEED_100M)) #define IS_ETH_DUPLEX_MODE(MODE) (((MODE) == ETH_MODE_FULLDUPLEX) || \ ((MODE) == ETH_MODE_HALFDUPLEX)) #define IS_ETH_RX_MODE(MODE) (((MODE) == ETH_RXPOLLING_MODE) || \ ((MODE) == ETH_RXINTERRUPT_MODE)) #define IS_ETH_CHECKSUM_MODE(MODE) (((MODE) == ETH_CHECKSUM_BY_HARDWARE) || \ ((MODE) == ETH_CHECKSUM_BY_SOFTWARE)) #define IS_ETH_MEDIA_INTERFACE(MODE) (((MODE) == ETH_MEDIA_INTERFACE_MII) || \ ((MODE) == ETH_MEDIA_INTERFACE_RMII)) #define IS_ETH_WATCHDOG(CMD) (((CMD) == ETH_WATCHDOG_ENABLE) || \ ((CMD) == ETH_WATCHDOG_DISABLE)) #define IS_ETH_JABBER(CMD) (((CMD) == ETH_JABBER_ENABLE) || \ ((CMD) == ETH_JABBER_DISABLE)) #define IS_ETH_INTER_FRAME_GAP(GAP) (((GAP) == ETH_INTERFRAMEGAP_96BIT) || \ ((GAP) == ETH_INTERFRAMEGAP_88BIT) || \ ((GAP) == ETH_INTERFRAMEGAP_80BIT) || \ ((GAP) == ETH_INTERFRAMEGAP_72BIT) || \ ((GAP) == ETH_INTERFRAMEGAP_64BIT) || \ ((GAP) == ETH_INTERFRAMEGAP_56BIT) || \ ((GAP) == ETH_INTERFRAMEGAP_48BIT) || \ ((GAP) == ETH_INTERFRAMEGAP_40BIT)) #define IS_ETH_CARRIER_SENSE(CMD) (((CMD) == ETH_CARRIERSENCE_ENABLE) || \ ((CMD) == ETH_CARRIERSENCE_DISABLE)) #define IS_ETH_RECEIVE_OWN(CMD) (((CMD) == ETH_RECEIVEOWN_ENABLE) || \ ((CMD) == ETH_RECEIVEOWN_DISABLE)) #define IS_ETH_LOOPBACK_MODE(CMD) (((CMD) == ETH_LOOPBACKMODE_ENABLE) || \ ((CMD) == ETH_LOOPBACKMODE_DISABLE)) #define IS_ETH_CHECKSUM_OFFLOAD(CMD) (((CMD) == ETH_CHECKSUMOFFLAOD_ENABLE) || \ ((CMD) == ETH_CHECKSUMOFFLAOD_DISABLE)) #define IS_ETH_RETRY_TRANSMISSION(CMD) (((CMD) == ETH_RETRYTRANSMISSION_ENABLE) || \ ((CMD) == ETH_RETRYTRANSMISSION_DISABLE)) #define IS_ETH_AUTOMATIC_PADCRC_STRIP(CMD) (((CMD) == ETH_AUTOMATICPADCRCSTRIP_ENABLE) || \ ((CMD) == ETH_AUTOMATICPADCRCSTRIP_DISABLE)) #define IS_ETH_BACKOFF_LIMIT(LIMIT) (((LIMIT) == ETH_BACKOFFLIMIT_10) || \ ((LIMIT) == ETH_BACKOFFLIMIT_8) || \ ((LIMIT) == ETH_BACKOFFLIMIT_4) || \ ((LIMIT) == ETH_BACKOFFLIMIT_1)) #define IS_ETH_DEFERRAL_CHECK(CMD) (((CMD) == ETH_DEFFERRALCHECK_ENABLE) || \ ((CMD) == ETH_DEFFERRALCHECK_DISABLE)) #define IS_ETH_RECEIVE_ALL(CMD) (((CMD) == ETH_RECEIVEALL_ENABLE) || \ ((CMD) == ETH_RECEIVEAll_DISABLE)) #define IS_ETH_SOURCE_ADDR_FILTER(CMD) (((CMD) == ETH_SOURCEADDRFILTER_NORMAL_ENABLE) || \ ((CMD) == ETH_SOURCEADDRFILTER_INVERSE_ENABLE) || \ ((CMD) == ETH_SOURCEADDRFILTER_DISABLE)) #define IS_ETH_CONTROL_FRAMES(PASS) (((PASS) == ETH_PASSCONTROLFRAMES_BLOCKALL) || \ ((PASS) == ETH_PASSCONTROLFRAMES_FORWARDALL) || \ ((PASS) == ETH_PASSCONTROLFRAMES_FORWARDPASSEDADDRFILTER)) #define IS_ETH_BROADCAST_FRAMES_RECEPTION(CMD) (((CMD) == ETH_BROADCASTFRAMESRECEPTION_ENABLE) || \ ((CMD) == ETH_BROADCASTFRAMESRECEPTION_DISABLE)) #define IS_ETH_DESTINATION_ADDR_FILTER(FILTER) (((FILTER) == ETH_DESTINATIONADDRFILTER_NORMAL) || \ ((FILTER) == ETH_DESTINATIONADDRFILTER_INVERSE)) #define IS_ETH_PROMISCUOUS_MODE(CMD) (((CMD) == ETH_PROMISCUOUS_MODE_ENABLE) || \ ((CMD) == ETH_PROMISCUOUS_MODE_DISABLE)) #define IS_ETH_MULTICAST_FRAMES_FILTER(FILTER) (((FILTER) == ETH_MULTICASTFRAMESFILTER_PERFECTHASHTABLE) || \ ((FILTER) == ETH_MULTICASTFRAMESFILTER_HASHTABLE) || \ ((FILTER) == ETH_MULTICASTFRAMESFILTER_PERFECT) || \ ((FILTER) == ETH_MULTICASTFRAMESFILTER_NONE)) #define IS_ETH_UNICAST_FRAMES_FILTER(FILTER) (((FILTER) == ETH_UNICASTFRAMESFILTER_PERFECTHASHTABLE) || \ ((FILTER) == ETH_UNICASTFRAMESFILTER_HASHTABLE) || \ ((FILTER) == ETH_UNICASTFRAMESFILTER_PERFECT)) #define IS_ETH_PAUSE_TIME(TIME) ((TIME) <= 0xFFFF) #define IS_ETH_ZEROQUANTA_PAUSE(CMD) (((CMD) == ETH_ZEROQUANTAPAUSE_ENABLE) || \ ((CMD) == ETH_ZEROQUANTAPAUSE_DISABLE)) #define IS_ETH_PAUSE_LOW_THRESHOLD(THRESHOLD) (((THRESHOLD) == ETH_PAUSELOWTHRESHOLD_MINUS4) || \ ((THRESHOLD) == ETH_PAUSELOWTHRESHOLD_MINUS28) || \ ((THRESHOLD) == ETH_PAUSELOWTHRESHOLD_MINUS144) || \ ((THRESHOLD) == ETH_PAUSELOWTHRESHOLD_MINUS256)) #define IS_ETH_UNICAST_PAUSE_FRAME_DETECT(CMD) (((CMD) == ETH_UNICASTPAUSEFRAMEDETECT_ENABLE) || \ ((CMD) == ETH_UNICASTPAUSEFRAMEDETECT_DISABLE)) #define IS_ETH_RECEIVE_FLOWCONTROL(CMD) (((CMD) == ETH_RECEIVEFLOWCONTROL_ENABLE) || \ ((CMD) == ETH_RECEIVEFLOWCONTROL_DISABLE)) #define IS_ETH_TRANSMIT_FLOWCONTROL(CMD) (((CMD) == ETH_TRANSMITFLOWCONTROL_ENABLE) || \ ((CMD) == ETH_TRANSMITFLOWCONTROL_DISABLE)) #define IS_ETH_VLAN_TAG_COMPARISON(COMPARISON) (((COMPARISON) == ETH_VLANTAGCOMPARISON_12BIT) || \ ((COMPARISON) == ETH_VLANTAGCOMPARISON_16BIT)) #define IS_ETH_VLAN_TAG_IDENTIFIER(IDENTIFIER) ((IDENTIFIER) <= 0xFFFF) #define IS_ETH_MAC_ADDRESS0123(ADDRESS) (((ADDRESS) == ETH_MAC_ADDRESS0) || \ ((ADDRESS) == ETH_MAC_ADDRESS1) || \ ((ADDRESS) == ETH_MAC_ADDRESS2) || \ ((ADDRESS) == ETH_MAC_ADDRESS3)) #define IS_ETH_MAC_ADDRESS123(ADDRESS) (((ADDRESS) == ETH_MAC_ADDRESS1) || \ ((ADDRESS) == ETH_MAC_ADDRESS2) || \ ((ADDRESS) == ETH_MAC_ADDRESS3)) #define IS_ETH_MAC_ADDRESS_FILTER(FILTER) (((FILTER) == ETH_MAC_ADDRESSFILTER_SA) || \ ((FILTER) == ETH_MAC_ADDRESSFILTER_DA)) #define IS_ETH_MAC_ADDRESS_MASK(MASK) (((MASK) == ETH_MAC_ADDRESSMASK_BYTE6) || \ ((MASK) == ETH_MAC_ADDRESSMASK_BYTE5) || \ ((MASK) == ETH_MAC_ADDRESSMASK_BYTE4) || \ ((MASK) == ETH_MAC_ADDRESSMASK_BYTE3) || \ ((MASK) == ETH_MAC_ADDRESSMASK_BYTE2) || \ ((MASK) == ETH_MAC_ADDRESSMASK_BYTE1)) #define IS_ETH_DROP_TCPIP_CHECKSUM_FRAME(CMD) (((CMD) == ETH_DROPTCPIPCHECKSUMERRORFRAME_ENABLE) || \ ((CMD) == ETH_DROPTCPIPCHECKSUMERRORFRAME_DISABLE)) #define IS_ETH_RECEIVE_STORE_FORWARD(CMD) (((CMD) == ETH_RECEIVESTOREFORWARD_ENABLE) || \ ((CMD) == ETH_RECEIVESTOREFORWARD_DISABLE)) #define IS_ETH_FLUSH_RECEIVE_FRAME(CMD) (((CMD) == ETH_FLUSHRECEIVEDFRAME_ENABLE) || \ ((CMD) == ETH_FLUSHRECEIVEDFRAME_DISABLE)) #define IS_ETH_TRANSMIT_STORE_FORWARD(CMD) (((CMD) == ETH_TRANSMITSTOREFORWARD_ENABLE) || \ ((CMD) == ETH_TRANSMITSTOREFORWARD_DISABLE)) #define IS_ETH_TRANSMIT_THRESHOLD_CONTROL(THRESHOLD) (((THRESHOLD) == ETH_TRANSMITTHRESHOLDCONTROL_64BYTES) || \ ((THRESHOLD) == ETH_TRANSMITTHRESHOLDCONTROL_128BYTES) || \ ((THRESHOLD) == ETH_TRANSMITTHRESHOLDCONTROL_192BYTES) || \ ((THRESHOLD) == ETH_TRANSMITTHRESHOLDCONTROL_256BYTES) || \ ((THRESHOLD) == ETH_TRANSMITTHRESHOLDCONTROL_40BYTES) || \ ((THRESHOLD) == ETH_TRANSMITTHRESHOLDCONTROL_32BYTES) || \ ((THRESHOLD) == ETH_TRANSMITTHRESHOLDCONTROL_24BYTES) || \ ((THRESHOLD) == ETH_TRANSMITTHRESHOLDCONTROL_16BYTES)) #define IS_ETH_FORWARD_ERROR_FRAMES(CMD) (((CMD) == ETH_FORWARDERRORFRAMES_ENABLE) || \ ((CMD) == ETH_FORWARDERRORFRAMES_DISABLE)) #define IS_ETH_FORWARD_UNDERSIZED_GOOD_FRAMES(CMD) (((CMD) == ETH_FORWARDUNDERSIZEDGOODFRAMES_ENABLE) || \ ((CMD) == ETH_FORWARDUNDERSIZEDGOODFRAMES_DISABLE)) #define IS_ETH_RECEIVE_THRESHOLD_CONTROL(THRESHOLD) (((THRESHOLD) == ETH_RECEIVEDTHRESHOLDCONTROL_64BYTES) || \ ((THRESHOLD) == ETH_RECEIVEDTHRESHOLDCONTROL_32BYTES) || \ ((THRESHOLD) == ETH_RECEIVEDTHRESHOLDCONTROL_96BYTES) || \ ((THRESHOLD) == ETH_RECEIVEDTHRESHOLDCONTROL_128BYTES)) #define IS_ETH_SECOND_FRAME_OPERATE(CMD) (((CMD) == ETH_SECONDFRAMEOPERARTE_ENABLE) || \ ((CMD) == ETH_SECONDFRAMEOPERARTE_DISABLE)) #define IS_ETH_ADDRESS_ALIGNED_BEATS(CMD) (((CMD) == ETH_ADDRESSALIGNEDBEATS_ENABLE) || \ ((CMD) == ETH_ADDRESSALIGNEDBEATS_DISABLE)) #define IS_ETH_FIXED_BURST(CMD) (((CMD) == ETH_FIXEDBURST_ENABLE) || \ ((CMD) == ETH_FIXEDBURST_DISABLE)) #define IS_ETH_RXDMA_BURST_LENGTH(LENGTH) (((LENGTH) == ETH_RXDMABURSTLENGTH_1BEAT) || \ ((LENGTH) == ETH_RXDMABURSTLENGTH_2BEAT) || \ ((LENGTH) == ETH_RXDMABURSTLENGTH_4BEAT) || \ ((LENGTH) == ETH_RXDMABURSTLENGTH_8BEAT) || \ ((LENGTH) == ETH_RXDMABURSTLENGTH_16BEAT) || \ ((LENGTH) == ETH_RXDMABURSTLENGTH_32BEAT) || \ ((LENGTH) == ETH_RXDMABURSTLENGTH_4XPBL_4BEAT) || \ ((LENGTH) == ETH_RXDMABURSTLENGTH_4XPBL_8BEAT) || \ ((LENGTH) == ETH_RXDMABURSTLENGTH_4XPBL_16BEAT) || \ ((LENGTH) == ETH_RXDMABURSTLENGTH_4XPBL_32BEAT) || \ ((LENGTH) == ETH_RXDMABURSTLENGTH_4XPBL_64BEAT) || \ ((LENGTH) == ETH_RXDMABURSTLENGTH_4XPBL_128BEAT)) #define IS_ETH_TXDMA_BURST_LENGTH(LENGTH) (((LENGTH) == ETH_TXDMABURSTLENGTH_1BEAT) || \ ((LENGTH) == ETH_TXDMABURSTLENGTH_2BEAT) || \ ((LENGTH) == ETH_TXDMABURSTLENGTH_4BEAT) || \ ((LENGTH) == ETH_TXDMABURSTLENGTH_8BEAT) || \ ((LENGTH) == ETH_TXDMABURSTLENGTH_16BEAT) || \ ((LENGTH) == ETH_TXDMABURSTLENGTH_32BEAT) || \ ((LENGTH) == ETH_TXDMABURSTLENGTH_4XPBL_4BEAT) || \ ((LENGTH) == ETH_TXDMABURSTLENGTH_4XPBL_8BEAT) || \ ((LENGTH) == ETH_TXDMABURSTLENGTH_4XPBL_16BEAT) || \ ((LENGTH) == ETH_TXDMABURSTLENGTH_4XPBL_32BEAT) || \ ((LENGTH) == ETH_TXDMABURSTLENGTH_4XPBL_64BEAT) || \ ((LENGTH) == ETH_TXDMABURSTLENGTH_4XPBL_128BEAT)) #define IS_ETH_DMA_DESC_SKIP_LENGTH(LENGTH) ((LENGTH) <= 0x1F) #define IS_ETH_DMA_ARBITRATION_ROUNDROBIN_RXTX(RATIO) (((RATIO) == ETH_DMAARBITRATION_ROUNDROBIN_RXTX_1_1) || \ ((RATIO) == ETH_DMAARBITRATION_ROUNDROBIN_RXTX_2_1) || \ ((RATIO) == ETH_DMAARBITRATION_ROUNDROBIN_RXTX_3_1) || \ ((RATIO) == ETH_DMAARBITRATION_ROUNDROBIN_RXTX_4_1) || \ ((RATIO) == ETH_DMAARBITRATION_RXPRIORTX)) #define IS_ETH_DMATXDESC_GET_FLAG(FLAG) (((FLAG) == ETH_DMATXDESC_OWN) || \ ((FLAG) == ETH_DMATXDESC_IC) || \ ((FLAG) == ETH_DMATXDESC_LS) || \ ((FLAG) == ETH_DMATXDESC_FS) || \ ((FLAG) == ETH_DMATXDESC_DC) || \ ((FLAG) == ETH_DMATXDESC_DP) || \ ((FLAG) == ETH_DMATXDESC_TTSE) || \ ((FLAG) == ETH_DMATXDESC_TER) || \ ((FLAG) == ETH_DMATXDESC_TCH) || \ ((FLAG) == ETH_DMATXDESC_TTSS) || \ ((FLAG) == ETH_DMATXDESC_IHE) || \ ((FLAG) == ETH_DMATXDESC_ES) || \ ((FLAG) == ETH_DMATXDESC_JT) || \ ((FLAG) == ETH_DMATXDESC_FF) || \ ((FLAG) == ETH_DMATXDESC_PCE) || \ ((FLAG) == ETH_DMATXDESC_LCA) || \ ((FLAG) == ETH_DMATXDESC_NC) || \ ((FLAG) == ETH_DMATXDESC_LCO) || \ ((FLAG) == ETH_DMATXDESC_EC) || \ ((FLAG) == ETH_DMATXDESC_VF) || \ ((FLAG) == ETH_DMATXDESC_CC) || \ ((FLAG) == ETH_DMATXDESC_ED) || \ ((FLAG) == ETH_DMATXDESC_UF) || \ ((FLAG) == ETH_DMATXDESC_DB)) #define IS_ETH_DMA_TXDESC_SEGMENT(SEGMENT) (((SEGMENT) == ETH_DMATXDESC_LASTSEGMENTS) || \ ((SEGMENT) == ETH_DMATXDESC_FIRSTSEGMENT)) #define IS_ETH_DMA_TXDESC_CHECKSUM(CHECKSUM) (((CHECKSUM) == ETH_DMATXDESC_CHECKSUMBYPASS) || \ ((CHECKSUM) == ETH_DMATXDESC_CHECKSUMIPV4HEADER) || \ ((CHECKSUM) == ETH_DMATXDESC_CHECKSUMTCPUDPICMPSEGMENT) || \ ((CHECKSUM) == ETH_DMATXDESC_CHECKSUMTCPUDPICMPFULL)) #define IS_ETH_DMATXDESC_BUFFER_SIZE(SIZE) ((SIZE) <= 0x1FFF) #define IS_ETH_DMARXDESC_GET_FLAG(FLAG) (((FLAG) == ETH_DMARXDESC_OWN) || \ ((FLAG) == ETH_DMARXDESC_AFM) || \ ((FLAG) == ETH_DMARXDESC_ES) || \ ((FLAG) == ETH_DMARXDESC_DE) || \ ((FLAG) == ETH_DMARXDESC_SAF) || \ ((FLAG) == ETH_DMARXDESC_LE) || \ ((FLAG) == ETH_DMARXDESC_OE) || \ ((FLAG) == ETH_DMARXDESC_VLAN) || \ ((FLAG) == ETH_DMARXDESC_FS) || \ ((FLAG) == ETH_DMARXDESC_LS) || \ ((FLAG) == ETH_DMARXDESC_IPV4HCE) || \ ((FLAG) == ETH_DMARXDESC_LC) || \ ((FLAG) == ETH_DMARXDESC_FT) || \ ((FLAG) == ETH_DMARXDESC_RWT) || \ ((FLAG) == ETH_DMARXDESC_RE) || \ ((FLAG) == ETH_DMARXDESC_DBE) || \ ((FLAG) == ETH_DMARXDESC_CE) || \ ((FLAG) == ETH_DMARXDESC_MAMPCE)) #define IS_ETH_DMA_RXDESC_BUFFER(BUFFER) (((BUFFER) == ETH_DMARXDESC_BUFFER1) || \ ((BUFFER) == ETH_DMARXDESC_BUFFER2)) #define IS_ETH_PMT_GET_FLAG(FLAG) (((FLAG) == ETH_PMT_FLAG_WUFR) || \ ((FLAG) == ETH_PMT_FLAG_MPR)) #define IS_ETH_DMA_FLAG(FLAG) ((((FLAG) & (uint32_t)0xC7FE1800) == 0x00) && ((FLAG) != 0x00)) #define IS_ETH_DMA_GET_FLAG(FLAG) (((FLAG) == ETH_DMA_FLAG_TST) || ((FLAG) == ETH_DMA_FLAG_PMT) || \ ((FLAG) == ETH_DMA_FLAG_MMC) || ((FLAG) == ETH_DMA_FLAG_DATATRANSFERERROR) || \ ((FLAG) == ETH_DMA_FLAG_READWRITEERROR) || ((FLAG) == ETH_DMA_FLAG_ACCESSERROR) || \ ((FLAG) == ETH_DMA_FLAG_NIS) || ((FLAG) == ETH_DMA_FLAG_AIS) || \ ((FLAG) == ETH_DMA_FLAG_ER) || ((FLAG) == ETH_DMA_FLAG_FBE) || \ ((FLAG) == ETH_DMA_FLAG_ET) || ((FLAG) == ETH_DMA_FLAG_RWT) || \ ((FLAG) == ETH_DMA_FLAG_RPS) || ((FLAG) == ETH_DMA_FLAG_RBU) || \ ((FLAG) == ETH_DMA_FLAG_R) || ((FLAG) == ETH_DMA_FLAG_TU) || \ ((FLAG) == ETH_DMA_FLAG_RO) || ((FLAG) == ETH_DMA_FLAG_TJT) || \ ((FLAG) == ETH_DMA_FLAG_TBU) || ((FLAG) == ETH_DMA_FLAG_TPS) || \ ((FLAG) == ETH_DMA_FLAG_T)) #define IS_ETH_MAC_IT(IT) ((((IT) & (uint32_t)0xFFFFFDF1) == 0x00) && ((IT) != 0x00)) #define IS_ETH_MAC_GET_IT(IT) (((IT) == ETH_MAC_IT_TST) || ((IT) == ETH_MAC_IT_MMCT) || \ ((IT) == ETH_MAC_IT_MMCR) || ((IT) == ETH_MAC_IT_MMC) || \ ((IT) == ETH_MAC_IT_PMT)) #define IS_ETH_MAC_GET_FLAG(FLAG) (((FLAG) == ETH_MAC_FLAG_TST) || ((FLAG) == ETH_MAC_FLAG_MMCT) || \ ((FLAG) == ETH_MAC_FLAG_MMCR) || ((FLAG) == ETH_MAC_FLAG_MMC) || \ ((FLAG) == ETH_MAC_FLAG_PMT)) #define IS_ETH_DMA_IT(IT) ((((IT) & (uint32_t)0xC7FE1800) == 0x00) && ((IT) != 0x00)) #define IS_ETH_DMA_GET_IT(IT) (((IT) == ETH_DMA_IT_TST) || ((IT) == ETH_DMA_IT_PMT) || \ ((IT) == ETH_DMA_IT_MMC) || ((IT) == ETH_DMA_IT_NIS) || \ ((IT) == ETH_DMA_IT_AIS) || ((IT) == ETH_DMA_IT_ER) || \ ((IT) == ETH_DMA_IT_FBE) || ((IT) == ETH_DMA_IT_ET) || \ ((IT) == ETH_DMA_IT_RWT) || ((IT) == ETH_DMA_IT_RPS) || \ ((IT) == ETH_DMA_IT_RBU) || ((IT) == ETH_DMA_IT_R) || \ ((IT) == ETH_DMA_IT_TU) || ((IT) == ETH_DMA_IT_RO) || \ ((IT) == ETH_DMA_IT_TJT) || ((IT) == ETH_DMA_IT_TBU) || \ ((IT) == ETH_DMA_IT_TPS) || ((IT) == ETH_DMA_IT_T)) #define IS_ETH_DMA_GET_OVERFLOW(OVERFLOW) (((OVERFLOW) == ETH_DMA_OVERFLOW_RXFIFOCOUNTER) || \ ((OVERFLOW) == ETH_DMA_OVERFLOW_MISSEDFRAMECOUNTER)) #define IS_ETH_MMC_IT(IT) (((((IT) & (uint32_t)0xFFDF3FFF) == 0x00) || (((IT) & (uint32_t)0xEFFDFF9F) == 0x00)) && \ ((IT) != 0x00)) #define IS_ETH_MMC_GET_IT(IT) (((IT) == ETH_MMC_IT_TGF) || ((IT) == ETH_MMC_IT_TGFMSC) || \ ((IT) == ETH_MMC_IT_TGFSC) || ((IT) == ETH_MMC_IT_RGUF) || \ ((IT) == ETH_MMC_IT_RFAE) || ((IT) == ETH_MMC_IT_RFCE)) #define IS_ETH_ENHANCED_DESCRIPTOR_FORMAT(CMD) (((CMD) == ETH_DMAENHANCEDDESCRIPTOR_ENABLE) || \ ((CMD) == ETH_DMAENHANCEDDESCRIPTOR_DISABLE)) /** * @} */ /** @addtogroup ETH_Private_Defines * @{ */ /* Delay to wait when writing to some Ethernet registers */ #define ETH_REG_WRITE_DELAY ((uint32_t)0x00000001) /* ETHERNET Errors */ #define ETH_SUCCESS ((uint32_t)0) #define ETH_ERROR ((uint32_t)1) /* ETHERNET DMA Tx descriptors Collision Count Shift */ #define ETH_DMATXDESC_COLLISION_COUNTSHIFT ((uint32_t)3) /* ETHERNET DMA Tx descriptors Buffer2 Size Shift */ #define ETH_DMATXDESC_BUFFER2_SIZESHIFT ((uint32_t)16) /* ETHERNET DMA Rx descriptors Frame Length Shift */ #define ETH_DMARXDESC_FRAME_LENGTHSHIFT ((uint32_t)16) /* ETHERNET DMA Rx descriptors Buffer2 Size Shift */ #define ETH_DMARXDESC_BUFFER2_SIZESHIFT ((uint32_t)16) /* ETHERNET DMA Rx descriptors Frame length Shift */ #define ETH_DMARXDESC_FRAMELENGTHSHIFT ((uint32_t)16) /* ETHERNET MAC address offsets */ #define ETH_MAC_ADDR_HBASE (uint32_t)(ETH_MAC_BASE + (uint32_t)0x40) /* ETHERNET MAC address high offset */ #define ETH_MAC_ADDR_LBASE (uint32_t)(ETH_MAC_BASE + (uint32_t)0x44) /* ETHERNET MAC address low offset */ /* ETHERNET MACMIIAR register Mask */ #define ETH_MACMIIAR_CR_MASK ((uint32_t)0xFFFFFFE3) /* ETHERNET MACCR register Mask */ #define ETH_MACCR_CLEAR_MASK ((uint32_t)0xFF20810F) /* ETHERNET MACFCR register Mask */ #define ETH_MACFCR_CLEAR_MASK ((uint32_t)0x0000FF41) /* ETHERNET DMAOMR register Mask */ #define ETH_DMAOMR_CLEAR_MASK ((uint32_t)0xF8DE3F23) /* ETHERNET Remote Wake-up frame register length */ #define ETH_WAKEUP_REGISTER_LENGTH 8 /* ETHERNET Missed frames counter Shift */ #define ETH_DMA_RX_OVERFLOW_MISSEDFRAMES_COUNTERSHIFT 17 /** * @} */ /* Exported types ------------------------------------------------------------*/ /** @defgroup ETH_Exported_Types ETH Exported Types * @{ */ /** * @brief HAL State structures definition */ typedef enum { HAL_ETH_STATE_RESET = 0x00, /*!< Peripheral not yet Initialized or disabled */ HAL_ETH_STATE_READY = 0x01, /*!< Peripheral Initialized and ready for use */ HAL_ETH_STATE_BUSY = 0x02, /*!< an internal process is ongoing */ HAL_ETH_STATE_BUSY_TX = 0x12, /*!< Data Transmission process is ongoing */ HAL_ETH_STATE_BUSY_RX = 0x22, /*!< Data Reception process is ongoing */ HAL_ETH_STATE_BUSY_TX_RX = 0x32, /*!< Data Transmission and Reception process is ongoing */ HAL_ETH_STATE_BUSY_WR = 0x42, /*!< Write process is ongoing */ HAL_ETH_STATE_BUSY_RD = 0x82, /*!< Read process is ongoing */ HAL_ETH_STATE_TIMEOUT = 0x03, /*!< Timeout state */ HAL_ETH_STATE_ERROR = 0x04 /*!< Reception process is ongoing */ }HAL_ETH_StateTypeDef; /** * @brief ETH Init Structure definition */ typedef struct { uint32_t AutoNegotiation; /*!< Selects or not the AutoNegotiation mode for the external PHY The AutoNegotiation allows an automatic setting of the Speed (10/100Mbps) and the mode (half/full-duplex). This parameter can be a value of @ref ETH_AutoNegotiation */ uint32_t Speed; /*!< Sets the Ethernet speed: 10/100 Mbps. This parameter can be a value of @ref ETH_Speed */ uint32_t DuplexMode; /*!< Selects the MAC duplex mode: Half-Duplex or Full-Duplex mode This parameter can be a value of @ref ETH_Duplex_Mode */ uint16_t PhyAddress; /*!< Ethernet PHY address. This parameter must be a number between Min_Data = 0 and Max_Data = 32 */ uint8_t *MACAddr; /*!< MAC Address of used Hardware: must be pointer on an array of 6 bytes */ uint32_t RxMode; /*!< Selects the Ethernet Rx mode: Polling mode, Interrupt mode. This parameter can be a value of @ref ETH_Rx_Mode */ uint32_t ChecksumMode; /*!< Selects if the checksum is check by hardware or by software. This parameter can be a value of @ref ETH_Checksum_Mode */ uint32_t MediaInterface ; /*!< Selects the media-independent interface or the reduced media-independent interface. This parameter can be a value of @ref ETH_Media_Interface */ } ETH_InitTypeDef; /** * @brief ETH MAC Configuration Structure definition */ typedef struct { uint32_t Watchdog; /*!< Selects or not the Watchdog timer When enabled, the MAC allows no more then 2048 bytes to be received. When disabled, the MAC can receive up to 16384 bytes. This parameter can be a value of @ref ETH_Watchdog */ uint32_t Jabber; /*!< Selects or not Jabber timer When enabled, the MAC allows no more then 2048 bytes to be sent. When disabled, the MAC can send up to 16384 bytes. This parameter can be a value of @ref ETH_Jabber */ uint32_t InterFrameGap; /*!< Selects the minimum IFG between frames during transmission. This parameter can be a value of @ref ETH_Inter_Frame_Gap */ uint32_t CarrierSense; /*!< Selects or not the Carrier Sense. This parameter can be a value of @ref ETH_Carrier_Sense */ uint32_t ReceiveOwn; /*!< Selects or not the ReceiveOwn, ReceiveOwn allows the reception of frames when the TX_EN signal is asserted in Half-Duplex mode. This parameter can be a value of @ref ETH_Receive_Own */ uint32_t LoopbackMode; /*!< Selects or not the internal MAC MII Loopback mode. This parameter can be a value of @ref ETH_Loop_Back_Mode */ uint32_t ChecksumOffload; /*!< Selects or not the IPv4 checksum checking for received frame payloads' TCP/UDP/ICMP headers. This parameter can be a value of @ref ETH_Checksum_Offload */ uint32_t RetryTransmission; /*!< Selects or not the MAC attempt retries transmission, based on the settings of BL, when a collision occurs (Half-Duplex mode). This parameter can be a value of @ref ETH_Retry_Transmission */ uint32_t AutomaticPadCRCStrip; /*!< Selects or not the Automatic MAC Pad/CRC Stripping. This parameter can be a value of @ref ETH_Automatic_Pad_CRC_Strip */ uint32_t BackOffLimit; /*!< Selects the BackOff limit value. This parameter can be a value of @ref ETH_Back_Off_Limit */ uint32_t DeferralCheck; /*!< Selects or not the deferral check function (Half-Duplex mode). This parameter can be a value of @ref ETH_Deferral_Check */ uint32_t ReceiveAll; /*!< Selects or not all frames reception by the MAC (No filtering). This parameter can be a value of @ref ETH_Receive_All */ uint32_t SourceAddrFilter; /*!< Selects the Source Address Filter mode. This parameter can be a value of @ref ETH_Source_Addr_Filter */ uint32_t PassControlFrames; /*!< Sets the forwarding mode of the control frames (including unicast and multicast PAUSE frames) This parameter can be a value of @ref ETH_Pass_Control_Frames */ uint32_t BroadcastFramesReception; /*!< Selects or not the reception of Broadcast Frames. This parameter can be a value of @ref ETH_Broadcast_Frames_Reception */ uint32_t DestinationAddrFilter; /*!< Sets the destination filter mode for both unicast and multicast frames. This parameter can be a value of @ref ETH_Destination_Addr_Filter */ uint32_t PromiscuousMode; /*!< Selects or not the Promiscuous Mode This parameter can be a value of @ref ETH_Promiscuous_Mode */ uint32_t MulticastFramesFilter; /*!< Selects the Multicast Frames filter mode: None/HashTableFilter/PerfectFilter/PerfectHashTableFilter. This parameter can be a value of @ref ETH_Multicast_Frames_Filter */ uint32_t UnicastFramesFilter; /*!< Selects the Unicast Frames filter mode: HashTableFilter/PerfectFilter/PerfectHashTableFilter. This parameter can be a value of @ref ETH_Unicast_Frames_Filter */ uint32_t HashTableHigh; /*!< This field holds the higher 32 bits of Hash table. This parameter must be a number between Min_Data = 0x0 and Max_Data = 0xFFFFFFFF */ uint32_t HashTableLow; /*!< This field holds the lower 32 bits of Hash table. This parameter must be a number between Min_Data = 0x0 and Max_Data = 0xFFFFFFFF */ uint32_t PauseTime; /*!< This field holds the value to be used in the Pause Time field in the transmit control frame. This parameter must be a number between Min_Data = 0x0 and Max_Data = 0xFFFF */ uint32_t ZeroQuantaPause; /*!< Selects or not the automatic generation of Zero-Quanta Pause Control frames. This parameter can be a value of @ref ETH_Zero_Quanta_Pause */ uint32_t PauseLowThreshold; /*!< This field configures the threshold of the PAUSE to be checked for automatic retransmission of PAUSE Frame. This parameter can be a value of @ref ETH_Pause_Low_Threshold */ uint32_t UnicastPauseFrameDetect; /*!< Selects or not the MAC detection of the Pause frames (with MAC Address0 unicast address and unique multicast address). This parameter can be a value of @ref ETH_Unicast_Pause_Frame_Detect */ uint32_t ReceiveFlowControl; /*!< Enables or disables the MAC to decode the received Pause frame and disable its transmitter for a specified time (Pause Time) This parameter can be a value of @ref ETH_Receive_Flow_Control */ uint32_t TransmitFlowControl; /*!< Enables or disables the MAC to transmit Pause frames (Full-Duplex mode) or the MAC back-pressure operation (Half-Duplex mode) This parameter can be a value of @ref ETH_Transmit_Flow_Control */ uint32_t VLANTagComparison; /*!< Selects the 12-bit VLAN identifier or the complete 16-bit VLAN tag for comparison and filtering. This parameter can be a value of @ref ETH_VLAN_Tag_Comparison */ uint32_t VLANTagIdentifier; /*!< Holds the VLAN tag identifier for receive frames */ } ETH_MACInitTypeDef; /** * @brief ETH DMA Configuration Structure definition */ typedef struct { uint32_t DropTCPIPChecksumErrorFrame; /*!< Selects or not the Dropping of TCP/IP Checksum Error Frames. This parameter can be a value of @ref ETH_Drop_TCP_IP_Checksum_Error_Frame */ uint32_t ReceiveStoreForward; /*!< Enables or disables the Receive store and forward mode. This parameter can be a value of @ref ETH_Receive_Store_Forward */ uint32_t FlushReceivedFrame; /*!< Enables or disables the flushing of received frames. This parameter can be a value of @ref ETH_Flush_Received_Frame */ uint32_t TransmitStoreForward; /*!< Enables or disables Transmit store and forward mode. This parameter can be a value of @ref ETH_Transmit_Store_Forward */ uint32_t TransmitThresholdControl; /*!< Selects or not the Transmit Threshold Control. This parameter can be a value of @ref ETH_Transmit_Threshold_Control */ uint32_t ForwardErrorFrames; /*!< Selects or not the forward to the DMA of erroneous frames. This parameter can be a value of @ref ETH_Forward_Error_Frames */ uint32_t ForwardUndersizedGoodFrames; /*!< Enables or disables the Rx FIFO to forward Undersized frames (frames with no Error and length less than 64 bytes) including pad-bytes and CRC) This parameter can be a value of @ref ETH_Forward_Undersized_Good_Frames */ uint32_t ReceiveThresholdControl; /*!< Selects the threshold level of the Receive FIFO. This parameter can be a value of @ref ETH_Receive_Threshold_Control */ uint32_t SecondFrameOperate; /*!< Selects or not the Operate on second frame mode, which allows the DMA to process a second frame of Transmit data even before obtaining the status for the first frame. This parameter can be a value of @ref ETH_Second_Frame_Operate */ uint32_t AddressAlignedBeats; /*!< Enables or disables the Address Aligned Beats. This parameter can be a value of @ref ETH_Address_Aligned_Beats */ uint32_t FixedBurst; /*!< Enables or disables the AHB Master interface fixed burst transfers. This parameter can be a value of @ref ETH_Fixed_Burst */ uint32_t RxDMABurstLength; /*!< Indicates the maximum number of beats to be transferred in one Rx DMA transaction. This parameter can be a value of @ref ETH_Rx_DMA_Burst_Length */ uint32_t TxDMABurstLength; /*!< Indicates the maximum number of beats to be transferred in one Tx DMA transaction. This parameter can be a value of @ref ETH_Tx_DMA_Burst_Length */ uint32_t EnhancedDescriptorFormat; /*!< Enables the enhanced descriptor format. This parameter can be a value of @ref ETH_DMA_Enhanced_descriptor_format */ uint32_t DescriptorSkipLength; /*!< Specifies the number of word to skip between two unchained descriptors (Ring mode) This parameter must be a number between Min_Data = 0 and Max_Data = 32 */ uint32_t DMAArbitration; /*!< Selects the DMA Tx/Rx arbitration. This parameter can be a value of @ref ETH_DMA_Arbitration */ } ETH_DMAInitTypeDef; /** * @brief ETH DMA Descriptors data structure definition */ typedef struct { __IO uint32_t Status; /*!< Status */ uint32_t ControlBufferSize; /*!< Control and Buffer1, Buffer2 lengths */ uint32_t Buffer1Addr; /*!< Buffer1 address pointer */ uint32_t Buffer2NextDescAddr; /*!< Buffer2 or next descriptor address pointer */ /*!< Enhanced ETHERNET DMA PTP Descriptors */ uint32_t ExtendedStatus; /*!< Extended status for PTP receive descriptor */ uint32_t Reserved1; /*!< Reserved */ uint32_t TimeStampLow; /*!< Time Stamp Low value for transmit and receive */ uint32_t TimeStampHigh; /*!< Time Stamp High value for transmit and receive */ } ETH_DMADescTypeDef; /** * @brief Received Frame Informations structure definition */ typedef struct { ETH_DMADescTypeDef *FSRxDesc; /*!< First Segment Rx Desc */ ETH_DMADescTypeDef *LSRxDesc; /*!< Last Segment Rx Desc */ uint32_t SegCount; /*!< Segment count */ uint32_t length; /*!< Frame length */ uint32_t buffer; /*!< Frame buffer */ } ETH_DMARxFrameInfos; /** * @brief ETH Handle Structure definition */ typedef struct { ETH_TypeDef *Instance; /*!< Register base address */ ETH_InitTypeDef Init; /*!< Ethernet Init Configuration */ uint32_t LinkStatus; /*!< Ethernet link status */ ETH_DMADescTypeDef *RxDesc; /*!< Rx descriptor to Get */ ETH_DMADescTypeDef *TxDesc; /*!< Tx descriptor to Set */ ETH_DMARxFrameInfos RxFrameInfos; /*!< last Rx frame infos */ __IO HAL_ETH_StateTypeDef State; /*!< ETH communication state */ HAL_LockTypeDef Lock; /*!< ETH Lock */ } ETH_HandleTypeDef; /** * @} */ /* Exported constants --------------------------------------------------------*/ /** @defgroup ETH_Exported_Constants ETH Exported Constants * @{ */ /** @defgroup ETH_Buffers_setting ETH Buffers setting * @{ */ #define ETH_MAX_PACKET_SIZE ((uint32_t)1524) /*!< ETH_HEADER + ETH_EXTRA + ETH_VLAN_TAG + ETH_MAX_ETH_PAYLOAD + ETH_CRC */ #define ETH_HEADER ((uint32_t)14) /*!< 6 byte Dest addr, 6 byte Src addr, 2 byte length/type */ #define ETH_CRC ((uint32_t)4) /*!< Ethernet CRC */ #define ETH_EXTRA ((uint32_t)2) /*!< Extra bytes in some cases */ #define ETH_VLAN_TAG ((uint32_t)4) /*!< optional 802.1q VLAN Tag */ #define ETH_MIN_ETH_PAYLOAD ((uint32_t)46) /*!< Minimum Ethernet payload size */ #define ETH_MAX_ETH_PAYLOAD ((uint32_t)1500) /*!< Maximum Ethernet payload size */ #define ETH_JUMBO_FRAME_PAYLOAD ((uint32_t)9000) /*!< Jumbo frame payload size */ /* Ethernet driver receive buffers are organized in a chained linked-list, when an ethernet packet is received, the Rx-DMA will transfer the packet from RxFIFO to the driver receive buffers memory. Depending on the size of the received ethernet packet and the size of each ethernet driver receive buffer, the received packet can take one or more ethernet driver receive buffer. In below are defined the size of one ethernet driver receive buffer ETH_RX_BUF_SIZE and the total count of the driver receive buffers ETH_RXBUFNB. The configured value for ETH_RX_BUF_SIZE and ETH_RXBUFNB are only provided as example, they can be reconfigured in the application layer to fit the application needs */ /* Here we configure each Ethernet driver receive buffer to fit the Max size Ethernet packet */ #ifndef ETH_RX_BUF_SIZE #define ETH_RX_BUF_SIZE ETH_MAX_PACKET_SIZE #endif /* 5 Ethernet driver receive buffers are used (in a chained linked list)*/ #ifndef ETH_RXBUFNB #define ETH_RXBUFNB ((uint32_t)5 /* 5 Rx buffers of size ETH_RX_BUF_SIZE */ #endif /* Ethernet driver transmit buffers are organized in a chained linked-list, when an ethernet packet is transmitted, Tx-DMA will transfer the packet from the driver transmit buffers memory to the TxFIFO. Depending on the size of the Ethernet packet to be transmitted and the size of each ethernet driver transmit buffer, the packet to be transmitted can take one or more ethernet driver transmit buffer. In below are defined the size of one ethernet driver transmit buffer ETH_TX_BUF_SIZE and the total count of the driver transmit buffers ETH_TXBUFNB. The configured value for ETH_TX_BUF_SIZE and ETH_TXBUFNB are only provided as example, they can be reconfigured in the application layer to fit the application needs */ /* Here we configure each Ethernet driver transmit buffer to fit the Max size Ethernet packet */ #ifndef ETH_TX_BUF_SIZE #define ETH_TX_BUF_SIZE ETH_MAX_PACKET_SIZE #endif /* 5 ethernet driver transmit buffers are used (in a chained linked list)*/ #ifndef ETH_TXBUFNB #define ETH_TXBUFNB ((uint32_t)5 /* 5 Tx buffers of size ETH_TX_BUF_SIZE */ #endif /** * @} */ /** @defgroup ETH_DMA_TX_Descriptor ETH DMA TX Descriptor * @{ */ /* DMA Tx Descriptor ----------------------------------------------------------------------------------------------- TDES0 | OWN(31) | CTRL[30:26] | Reserved[25:24] | CTRL[23:20] | Reserved[19:17] | Status[16:0] | ----------------------------------------------------------------------------------------------- TDES1 | Reserved[31:29] | Buffer2 ByteCount[28:16] | Reserved[15:13] | Buffer1 ByteCount[12:0] | ----------------------------------------------------------------------------------------------- TDES2 | Buffer1 Address [31:0] | ----------------------------------------------------------------------------------------------- TDES3 | Buffer2 Address [31:0] / Next Descriptor Address [31:0] | ----------------------------------------------------------------------------------------------- */ /** * @brief Bit definition of TDES0 register: DMA Tx descriptor status register */ #define ETH_DMATXDESC_OWN ((uint32_t)0x80000000) /*!< OWN bit: descriptor is owned by DMA engine */ #define ETH_DMATXDESC_IC ((uint32_t)0x40000000) /*!< Interrupt on Completion */ #define ETH_DMATXDESC_LS ((uint32_t)0x20000000) /*!< Last Segment */ #define ETH_DMATXDESC_FS ((uint32_t)0x10000000) /*!< First Segment */ #define ETH_DMATXDESC_DC ((uint32_t)0x08000000) /*!< Disable CRC */ #define ETH_DMATXDESC_DP ((uint32_t)0x04000000) /*!< Disable Padding */ #define ETH_DMATXDESC_TTSE ((uint32_t)0x02000000) /*!< Transmit Time Stamp Enable */ #define ETH_DMATXDESC_CIC ((uint32_t)0x00C00000) /*!< Checksum Insertion Control: 4 cases */ #define ETH_DMATXDESC_CIC_BYPASS ((uint32_t)0x00000000) /*!< Do Nothing: Checksum Engine is bypassed */ #define ETH_DMATXDESC_CIC_IPV4HEADER ((uint32_t)0x00400000) /*!< IPV4 header Checksum Insertion */ #define ETH_DMATXDESC_CIC_TCPUDPICMP_SEGMENT ((uint32_t)0x00800000) /*!< TCP/UDP/ICMP Checksum Insertion calculated over segment only */ #define ETH_DMATXDESC_CIC_TCPUDPICMP_FULL ((uint32_t)0x00C00000) /*!< TCP/UDP/ICMP Checksum Insertion fully calculated */ #define ETH_DMATXDESC_TER ((uint32_t)0x00200000) /*!< Transmit End of Ring */ #define ETH_DMATXDESC_TCH ((uint32_t)0x00100000) /*!< Second Address Chained */ #define ETH_DMATXDESC_TTSS ((uint32_t)0x00020000) /*!< Tx Time Stamp Status */ #define ETH_DMATXDESC_IHE ((uint32_t)0x00010000) /*!< IP Header Error */ #define ETH_DMATXDESC_ES ((uint32_t)0x00008000) /*!< Error summary: OR of the following bits: UE || ED || EC || LCO || NC || LCA || FF || JT */ #define ETH_DMATXDESC_JT ((uint32_t)0x00004000) /*!< Jabber Timeout */ #define ETH_DMATXDESC_FF ((uint32_t)0x00002000) /*!< Frame Flushed: DMA/MTL flushed the frame due to SW flush */ #define ETH_DMATXDESC_PCE ((uint32_t)0x00001000) /*!< Payload Checksum Error */ #define ETH_DMATXDESC_LCA ((uint32_t)0x00000800) /*!< Loss of Carrier: carrier lost during transmission */ #define ETH_DMATXDESC_NC ((uint32_t)0x00000400) /*!< No Carrier: no carrier signal from the transceiver */ #define ETH_DMATXDESC_LCO ((uint32_t)0x00000200) /*!< Late Collision: transmission aborted due to collision */ #define ETH_DMATXDESC_EC ((uint32_t)0x00000100) /*!< Excessive Collision: transmission aborted after 16 collisions */ #define ETH_DMATXDESC_VF ((uint32_t)0x00000080) /*!< VLAN Frame */ #define ETH_DMATXDESC_CC ((uint32_t)0x00000078) /*!< Collision Count */ #define ETH_DMATXDESC_ED ((uint32_t)0x00000004) /*!< Excessive Deferral */ #define ETH_DMATXDESC_UF ((uint32_t)0x00000002) /*!< Underflow Error: late data arrival from the memory */ #define ETH_DMATXDESC_DB ((uint32_t)0x00000001) /*!< Deferred Bit */ /** * @brief Bit definition of TDES1 register */ #define ETH_DMATXDESC_TBS2 ((uint32_t)0x1FFF0000) /*!< Transmit Buffer2 Size */ #define ETH_DMATXDESC_TBS1 ((uint32_t)0x00001FFF) /*!< Transmit Buffer1 Size */ /** * @brief Bit definition of TDES2 register */ #define ETH_DMATXDESC_B1AP ((uint32_t)0xFFFFFFFF) /*!< Buffer1 Address Pointer */ /** * @brief Bit definition of TDES3 register */ #define ETH_DMATXDESC_B2AP ((uint32_t)0xFFFFFFFF) /*!< Buffer2 Address Pointer */ /*--------------------------------------------------------------------------------------------- TDES6 | Transmit Time Stamp Low [31:0] | ----------------------------------------------------------------------------------------------- TDES7 | Transmit Time Stamp High [31:0] | ----------------------------------------------------------------------------------------------*/ /* Bit definition of TDES6 register */ #define ETH_DMAPTPTXDESC_TTSL ((uint32_t)0xFFFFFFFF) /* Transmit Time Stamp Low */ /* Bit definition of TDES7 register */ #define ETH_DMAPTPTXDESC_TTSH ((uint32_t)0xFFFFFFFF) /* Transmit Time Stamp High */ /** * @} */ /** @defgroup ETH_DMA_RX_Descriptor ETH DMA RX Descriptor * @{ */ /* DMA Rx Descriptor -------------------------------------------------------------------------------------------------------------------- RDES0 | OWN(31) | Status [30:0] | --------------------------------------------------------------------------------------------------------------------- RDES1 | CTRL(31) | Reserved[30:29] | Buffer2 ByteCount[28:16] | CTRL[15:14] | Reserved(13) | Buffer1 ByteCount[12:0] | --------------------------------------------------------------------------------------------------------------------- RDES2 | Buffer1 Address [31:0] | --------------------------------------------------------------------------------------------------------------------- RDES3 | Buffer2 Address [31:0] / Next Descriptor Address [31:0] | --------------------------------------------------------------------------------------------------------------------- */ /** * @brief Bit definition of RDES0 register: DMA Rx descriptor status register */ #define ETH_DMARXDESC_OWN ((uint32_t)0x80000000) /*!< OWN bit: descriptor is owned by DMA engine */ #define ETH_DMARXDESC_AFM ((uint32_t)0x40000000) /*!< DA Filter Fail for the rx frame */ #define ETH_DMARXDESC_FL ((uint32_t)0x3FFF0000) /*!< Receive descriptor frame length */ #define ETH_DMARXDESC_ES ((uint32_t)0x00008000) /*!< Error summary: OR of the following bits: DE || OE || IPC || LC || RWT || RE || CE */ #define ETH_DMARXDESC_DE ((uint32_t)0x00004000) /*!< Descriptor error: no more descriptors for receive frame */ #define ETH_DMARXDESC_SAF ((uint32_t)0x00002000) /*!< SA Filter Fail for the received frame */ #define ETH_DMARXDESC_LE ((uint32_t)0x00001000) /*!< Frame size not matching with length field */ #define ETH_DMARXDESC_OE ((uint32_t)0x00000800) /*!< Overflow Error: Frame was damaged due to buffer overflow */ #define ETH_DMARXDESC_VLAN ((uint32_t)0x00000400) /*!< VLAN Tag: received frame is a VLAN frame */ #define ETH_DMARXDESC_FS ((uint32_t)0x00000200) /*!< First descriptor of the frame */ #define ETH_DMARXDESC_LS ((uint32_t)0x00000100) /*!< Last descriptor of the frame */ #define ETH_DMARXDESC_IPV4HCE ((uint32_t)0x00000080) /*!< IPC Checksum Error: Rx Ipv4 header checksum error */ #define ETH_DMARXDESC_LC ((uint32_t)0x00000040) /*!< Late collision occurred during reception */ #define ETH_DMARXDESC_FT ((uint32_t)0x00000020) /*!< Frame type - Ethernet, otherwise 802.3 */ #define ETH_DMARXDESC_RWT ((uint32_t)0x00000010) /*!< Receive Watchdog Timeout: watchdog timer expired during reception */ #define ETH_DMARXDESC_RE ((uint32_t)0x00000008) /*!< Receive error: error reported by MII interface */ #define ETH_DMARXDESC_DBE ((uint32_t)0x00000004) /*!< Dribble bit error: frame contains non int multiple of 8 bits */ #define ETH_DMARXDESC_CE ((uint32_t)0x00000002) /*!< CRC error */ #define ETH_DMARXDESC_MAMPCE ((uint32_t)0x00000001) /*!< Rx MAC Address/Payload Checksum Error: Rx MAC address matched/ Rx Payload Checksum Error */ /** * @brief Bit definition of RDES1 register */ #define ETH_DMARXDESC_DIC ((uint32_t)0x80000000) /*!< Disable Interrupt on Completion */ #define ETH_DMARXDESC_RBS2 ((uint32_t)0x1FFF0000) /*!< Receive Buffer2 Size */ #define ETH_DMARXDESC_RER ((uint32_t)0x00008000) /*!< Receive End of Ring */ #define ETH_DMARXDESC_RCH ((uint32_t)0x00004000) /*!< Second Address Chained */ #define ETH_DMARXDESC_RBS1 ((uint32_t)0x00001FFF) /*!< Receive Buffer1 Size */ /** * @brief Bit definition of RDES2 register */ #define ETH_DMARXDESC_B1AP ((uint32_t)0xFFFFFFFF) /*!< Buffer1 Address Pointer */ /** * @brief Bit definition of RDES3 register */ #define ETH_DMARXDESC_B2AP ((uint32_t)0xFFFFFFFF) /*!< Buffer2 Address Pointer */ /*--------------------------------------------------------------------------------------------------------------------- RDES4 | Reserved[31:15] | Extended Status [14:0] | --------------------------------------------------------------------------------------------------------------------- RDES5 | Reserved[31:0] | --------------------------------------------------------------------------------------------------------------------- RDES6 | Receive Time Stamp Low [31:0] | --------------------------------------------------------------------------------------------------------------------- RDES7 | Receive Time Stamp High [31:0] | --------------------------------------------------------------------------------------------------------------------*/ /* Bit definition of RDES4 register */ #define ETH_DMAPTPRXDESC_PTPV ((uint32_t)0x00002000) /* PTP Version */ #define ETH_DMAPTPRXDESC_PTPFT ((uint32_t)0x00001000) /* PTP Frame Type */ #define ETH_DMAPTPRXDESC_PTPMT ((uint32_t)0x00000F00) /* PTP Message Type */ #define ETH_DMAPTPRXDESC_PTPMT_SYNC ((uint32_t)0x00000100) /* SYNC message (all clock types) */ #define ETH_DMAPTPRXDESC_PTPMT_FOLLOWUP ((uint32_t)0x00000200) /* FollowUp message (all clock types) */ #define ETH_DMAPTPRXDESC_PTPMT_DELAYREQ ((uint32_t)0x00000300) /* DelayReq message (all clock types) */ #define ETH_DMAPTPRXDESC_PTPMT_DELAYRESP ((uint32_t)0x00000400) /* DelayResp message (all clock types) */ #define ETH_DMAPTPRXDESC_PTPMT_PDELAYREQ_ANNOUNCE ((uint32_t)0x00000500) /* PdelayReq message (peer-to-peer transparent clock) or Announce message (Ordinary or Boundary clock) */ #define ETH_DMAPTPRXDESC_PTPMT_PDELAYRESP_MANAG ((uint32_t)0x00000600) /* PdelayResp message (peer-to-peer transparent clock) or Management message (Ordinary or Boundary clock) */ #define ETH_DMAPTPRXDESC_PTPMT_PDELAYRESPFOLLOWUP_SIGNAL ((uint32_t)0x00000700) /* PdelayRespFollowUp message (peer-to-peer transparent clock) or Signaling message (Ordinary or Boundary clock) */ #define ETH_DMAPTPRXDESC_IPV6PR ((uint32_t)0x00000080) /* IPv6 Packet Received */ #define ETH_DMAPTPRXDESC_IPV4PR ((uint32_t)0x00000040) /* IPv4 Packet Received */ #define ETH_DMAPTPRXDESC_IPCB ((uint32_t)0x00000020) /* IP Checksum Bypassed */ #define ETH_DMAPTPRXDESC_IPPE ((uint32_t)0x00000010) /* IP Payload Error */ #define ETH_DMAPTPRXDESC_IPHE ((uint32_t)0x00000008) /* IP Header Error */ #define ETH_DMAPTPRXDESC_IPPT ((uint32_t)0x00000007) /* IP Payload Type */ #define ETH_DMAPTPRXDESC_IPPT_UDP ((uint32_t)0x00000001) /* UDP payload encapsulated in the IP datagram */ #define ETH_DMAPTPRXDESC_IPPT_TCP ((uint32_t)0x00000002) /* TCP payload encapsulated in the IP datagram */ #define ETH_DMAPTPRXDESC_IPPT_ICMP ((uint32_t)0x00000003) /* ICMP payload encapsulated in the IP datagram */ /* Bit definition of RDES6 register */ #define ETH_DMAPTPRXDESC_RTSL ((uint32_t)0xFFFFFFFF) /* Receive Time Stamp Low */ /* Bit definition of RDES7 register */ #define ETH_DMAPTPRXDESC_RTSH ((uint32_t)0xFFFFFFFF) /* Receive Time Stamp High */ /** * @} */ /** @defgroup ETH_AutoNegotiation ETH AutoNegotiation * @{ */ #define ETH_AUTONEGOTIATION_ENABLE ((uint32_t)0x00000001) #define ETH_AUTONEGOTIATION_DISABLE ((uint32_t)0x00000000) /** * @} */ /** @defgroup ETH_Speed ETH Speed * @{ */ #define ETH_SPEED_10M ((uint32_t)0x00000000) #define ETH_SPEED_100M ((uint32_t)0x00004000) /** * @} */ /** @defgroup ETH_Duplex_Mode ETH Duplex Mode * @{ */ #define ETH_MODE_FULLDUPLEX ((uint32_t)0x00000800) #define ETH_MODE_HALFDUPLEX ((uint32_t)0x00000000) /** * @} */ /** @defgroup ETH_Rx_Mode ETH Rx Mode * @{ */ #define ETH_RXPOLLING_MODE ((uint32_t)0x00000000) #define ETH_RXINTERRUPT_MODE ((uint32_t)0x00000001) /** * @} */ /** @defgroup ETH_Checksum_Mode ETH Checksum Mode * @{ */ #define ETH_CHECKSUM_BY_HARDWARE ((uint32_t)0x00000000) #define ETH_CHECKSUM_BY_SOFTWARE ((uint32_t)0x00000001) /** * @} */ /** @defgroup ETH_Media_Interface ETH Media Interface * @{ */ #define ETH_MEDIA_INTERFACE_MII ((uint32_t)0x00000000) #define ETH_MEDIA_INTERFACE_RMII ((uint32_t)SYSCFG_PMC_MII_RMII_SEL) /** * @} */ /** @defgroup ETH_Watchdog ETH Watchdog * @{ */ #define ETH_WATCHDOG_ENABLE ((uint32_t)0x00000000) #define ETH_WATCHDOG_DISABLE ((uint32_t)0x00800000) /** * @} */ /** @defgroup ETH_Jabber ETH Jabber * @{ */ #define ETH_JABBER_ENABLE ((uint32_t)0x00000000) #define ETH_JABBER_DISABLE ((uint32_t)0x00400000) /** * @} */ /** @defgroup ETH_Inter_Frame_Gap ETH Inter Frame Gap * @{ */ #define ETH_INTERFRAMEGAP_96BIT ((uint32_t)0x00000000) /*!< minimum IFG between frames during transmission is 96Bit */ #define ETH_INTERFRAMEGAP_88BIT ((uint32_t)0x00020000) /*!< minimum IFG between frames during transmission is 88Bit */ #define ETH_INTERFRAMEGAP_80BIT ((uint32_t)0x00040000) /*!< minimum IFG between frames during transmission is 80Bit */ #define ETH_INTERFRAMEGAP_72BIT ((uint32_t)0x00060000) /*!< minimum IFG between frames during transmission is 72Bit */ #define ETH_INTERFRAMEGAP_64BIT ((uint32_t)0x00080000) /*!< minimum IFG between frames during transmission is 64Bit */ #define ETH_INTERFRAMEGAP_56BIT ((uint32_t)0x000A0000) /*!< minimum IFG between frames during transmission is 56Bit */ #define ETH_INTERFRAMEGAP_48BIT ((uint32_t)0x000C0000) /*!< minimum IFG between frames during transmission is 48Bit */ #define ETH_INTERFRAMEGAP_40BIT ((uint32_t)0x000E0000) /*!< minimum IFG between frames during transmission is 40Bit */ /** * @} */ /** @defgroup ETH_Carrier_Sense ETH Carrier Sense * @{ */ #define ETH_CARRIERSENCE_ENABLE ((uint32_t)0x00000000) #define ETH_CARRIERSENCE_DISABLE ((uint32_t)0x00010000) /** * @} */ /** @defgroup ETH_Receive_Own ETH Receive Own * @{ */ #define ETH_RECEIVEOWN_ENABLE ((uint32_t)0x00000000) #define ETH_RECEIVEOWN_DISABLE ((uint32_t)0x00002000) /** * @} */ /** @defgroup ETH_Loop_Back_Mode ETH Loop Back Mode * @{ */ #define ETH_LOOPBACKMODE_ENABLE ((uint32_t)0x00001000) #define ETH_LOOPBACKMODE_DISABLE ((uint32_t)0x00000000) /** * @} */ /** @defgroup ETH_Checksum_Offload ETH Checksum Offload * @{ */ #define ETH_CHECKSUMOFFLAOD_ENABLE ((uint32_t)0x00000400) #define ETH_CHECKSUMOFFLAOD_DISABLE ((uint32_t)0x00000000) /** * @} */ /** @defgroup ETH_Retry_Transmission ETH Retry Transmission * @{ */ #define ETH_RETRYTRANSMISSION_ENABLE ((uint32_t)0x00000000) #define ETH_RETRYTRANSMISSION_DISABLE ((uint32_t)0x00000200) /** * @} */ /** @defgroup ETH_Automatic_Pad_CRC_Strip ETH Automatic Pad CRC Strip * @{ */ #define ETH_AUTOMATICPADCRCSTRIP_ENABLE ((uint32_t)0x00000080) #define ETH_AUTOMATICPADCRCSTRIP_DISABLE ((uint32_t)0x00000000) /** * @} */ /** @defgroup ETH_Back_Off_Limit ETH Back Off Limit * @{ */ #define ETH_BACKOFFLIMIT_10 ((uint32_t)0x00000000) #define ETH_BACKOFFLIMIT_8 ((uint32_t)0x00000020) #define ETH_BACKOFFLIMIT_4 ((uint32_t)0x00000040) #define ETH_BACKOFFLIMIT_1 ((uint32_t)0x00000060) /** * @} */ /** @defgroup ETH_Deferral_Check ETH Deferral Check * @{ */ #define ETH_DEFFERRALCHECK_ENABLE ((uint32_t)0x00000010) #define ETH_DEFFERRALCHECK_DISABLE ((uint32_t)0x00000000) /** * @} */ /** @defgroup ETH_Receive_All ETH Receive All * @{ */ #define ETH_RECEIVEALL_ENABLE ((uint32_t)0x80000000) #define ETH_RECEIVEAll_DISABLE ((uint32_t)0x00000000) /** * @} */ /** @defgroup ETH_Source_Addr_Filter ETH Source Addr Filter * @{ */ #define ETH_SOURCEADDRFILTER_NORMAL_ENABLE ((uint32_t)0x00000200) #define ETH_SOURCEADDRFILTER_INVERSE_ENABLE ((uint32_t)0x00000300) #define ETH_SOURCEADDRFILTER_DISABLE ((uint32_t)0x00000000) /** * @} */ /** @defgroup ETH_Pass_Control_Frames ETH Pass Control Frames * @{ */ #define ETH_PASSCONTROLFRAMES_BLOCKALL ((uint32_t)0x00000040) /*!< MAC filters all control frames from reaching the application */ #define ETH_PASSCONTROLFRAMES_FORWARDALL ((uint32_t)0x00000080) /*!< MAC forwards all control frames to application even if they fail the Address Filter */ #define ETH_PASSCONTROLFRAMES_FORWARDPASSEDADDRFILTER ((uint32_t)0x000000C0) /*!< MAC forwards control frames that pass the Address Filter. */ /** * @} */ /** @defgroup ETH_Broadcast_Frames_Reception ETH Broadcast Frames Reception * @{ */ #define ETH_BROADCASTFRAMESRECEPTION_ENABLE ((uint32_t)0x00000000) #define ETH_BROADCASTFRAMESRECEPTION_DISABLE ((uint32_t)0x00000020) /** * @} */ /** @defgroup ETH_Destination_Addr_Filter ETH Destination Addr Filter * @{ */ #define ETH_DESTINATIONADDRFILTER_NORMAL ((uint32_t)0x00000000) #define ETH_DESTINATIONADDRFILTER_INVERSE ((uint32_t)0x00000008) /** * @} */ /** @defgroup ETH_Promiscuous_Mode ETH Promiscuous Mode * @{ */ #define ETH_PROMISCUOUS_MODE_ENABLE ((uint32_t)0x00000001) #define ETH_PROMISCUOUS_MODE_DISABLE ((uint32_t)0x00000000) /** * @} */ /** @defgroup ETH_Multicast_Frames_Filter ETH Multicast Frames Filter * @{ */ #define ETH_MULTICASTFRAMESFILTER_PERFECTHASHTABLE ((uint32_t)0x00000404) #define ETH_MULTICASTFRAMESFILTER_HASHTABLE ((uint32_t)0x00000004) #define ETH_MULTICASTFRAMESFILTER_PERFECT ((uint32_t)0x00000000) #define ETH_MULTICASTFRAMESFILTER_NONE ((uint32_t)0x00000010) /** * @} */ /** @defgroup ETH_Unicast_Frames_Filter ETH Unicast Frames Filter * @{ */ #define ETH_UNICASTFRAMESFILTER_PERFECTHASHTABLE ((uint32_t)0x00000402) #define ETH_UNICASTFRAMESFILTER_HASHTABLE ((uint32_t)0x00000002) #define ETH_UNICASTFRAMESFILTER_PERFECT ((uint32_t)0x00000000) /** * @} */ /** @defgroup ETH_Zero_Quanta_Pause ETH Zero Quanta Pause * @{ */ #define ETH_ZEROQUANTAPAUSE_ENABLE ((uint32_t)0x00000000) #define ETH_ZEROQUANTAPAUSE_DISABLE ((uint32_t)0x00000080) /** * @} */ /** @defgroup ETH_Pause_Low_Threshold ETH Pause Low Threshold * @{ */ #define ETH_PAUSELOWTHRESHOLD_MINUS4 ((uint32_t)0x00000000) /*!< Pause time minus 4 slot times */ #define ETH_PAUSELOWTHRESHOLD_MINUS28 ((uint32_t)0x00000010) /*!< Pause time minus 28 slot times */ #define ETH_PAUSELOWTHRESHOLD_MINUS144 ((uint32_t)0x00000020) /*!< Pause time minus 144 slot times */ #define ETH_PAUSELOWTHRESHOLD_MINUS256 ((uint32_t)0x00000030) /*!< Pause time minus 256 slot times */ /** * @} */ /** @defgroup ETH_Unicast_Pause_Frame_Detect ETH Unicast Pause Frame Detect * @{ */ #define ETH_UNICASTPAUSEFRAMEDETECT_ENABLE ((uint32_t)0x00000008) #define ETH_UNICASTPAUSEFRAMEDETECT_DISABLE ((uint32_t)0x00000000) /** * @} */ /** @defgroup ETH_Receive_Flow_Control ETH Receive Flow Control * @{ */ #define ETH_RECEIVEFLOWCONTROL_ENABLE ((uint32_t)0x00000004) #define ETH_RECEIVEFLOWCONTROL_DISABLE ((uint32_t)0x00000000) /** * @} */ /** @defgroup ETH_Transmit_Flow_Control ETH Transmit Flow Control * @{ */ #define ETH_TRANSMITFLOWCONTROL_ENABLE ((uint32_t)0x00000002) #define ETH_TRANSMITFLOWCONTROL_DISABLE ((uint32_t)0x00000000) /** * @} */ /** @defgroup ETH_VLAN_Tag_Comparison ETH VLAN Tag Comparison * @{ */ #define ETH_VLANTAGCOMPARISON_12BIT ((uint32_t)0x00010000) #define ETH_VLANTAGCOMPARISON_16BIT ((uint32_t)0x00000000) /** * @} */ /** @defgroup ETH_MAC_addresses ETH MAC addresses * @{ */ #define ETH_MAC_ADDRESS0 ((uint32_t)0x00000000) #define ETH_MAC_ADDRESS1 ((uint32_t)0x00000008) #define ETH_MAC_ADDRESS2 ((uint32_t)0x00000010) #define ETH_MAC_ADDRESS3 ((uint32_t)0x00000018) /** * @} */ /** @defgroup ETH_MAC_addresses_filter_SA_DA ETH MAC addresses filter SA DA * @{ */ #define ETH_MAC_ADDRESSFILTER_SA ((uint32_t)0x00000000) #define ETH_MAC_ADDRESSFILTER_DA ((uint32_t)0x00000008) /** * @} */ /** @defgroup ETH_MAC_addresses_filter_Mask_bytes ETH MAC addresses filter Mask bytes * @{ */ #define ETH_MAC_ADDRESSMASK_BYTE6 ((uint32_t)0x20000000) /*!< Mask MAC Address high reg bits [15:8] */ #define ETH_MAC_ADDRESSMASK_BYTE5 ((uint32_t)0x10000000) /*!< Mask MAC Address high reg bits [7:0] */ #define ETH_MAC_ADDRESSMASK_BYTE4 ((uint32_t)0x08000000) /*!< Mask MAC Address low reg bits [31:24] */ #define ETH_MAC_ADDRESSMASK_BYTE3 ((uint32_t)0x04000000) /*!< Mask MAC Address low reg bits [23:16] */ #define ETH_MAC_ADDRESSMASK_BYTE2 ((uint32_t)0x02000000) /*!< Mask MAC Address low reg bits [15:8] */ #define ETH_MAC_ADDRESSMASK_BYTE1 ((uint32_t)0x01000000) /*!< Mask MAC Address low reg bits [70] */ /** * @} */ /** @defgroup ETH_MAC_Debug_flags ETH MAC Debug flags * @{ */ #define ETH_MAC_TXFIFO_FULL ((uint32_t)0x02000000) /* Tx FIFO full */ #define ETH_MAC_TXFIFONOT_EMPTY ((uint32_t)0x01000000) /* Tx FIFO not empty */ #define ETH_MAC_TXFIFO_WRITE_ACTIVE ((uint32_t)0x00400000) /* Tx FIFO write active */ #define ETH_MAC_TXFIFO_IDLE ((uint32_t)0x00000000) /* Tx FIFO read status: Idle */ #define ETH_MAC_TXFIFO_READ ((uint32_t)0x00100000) /* Tx FIFO read status: Read (transferring data to the MAC transmitter) */ #define ETH_MAC_TXFIFO_WAITING ((uint32_t)0x00200000) /* Tx FIFO read status: Waiting for TxStatus from MAC transmitter */ #define ETH_MAC_TXFIFO_WRITING ((uint32_t)0x00300000) /* Tx FIFO read status: Writing the received TxStatus or flushing the TxFIFO */ #define ETH_MAC_TRANSMISSION_PAUSE ((uint32_t)0x00080000) /* MAC transmitter in pause */ #define ETH_MAC_TRANSMITFRAMECONTROLLER_IDLE ((uint32_t)0x00000000) /* MAC transmit frame controller: Idle */ #define ETH_MAC_TRANSMITFRAMECONTROLLER_WAITING ((uint32_t)0x00020000) /* MAC transmit frame controller: Waiting for Status of previous frame or IFG/backoff period to be over */ #define ETH_MAC_TRANSMITFRAMECONTROLLER_GENRATING_PCF ((uint32_t)0x00040000) /* MAC transmit frame controller: Generating and transmitting a Pause control frame (in full duplex mode) */ #define ETH_MAC_TRANSMITFRAMECONTROLLER_TRANSFERRING ((uint32_t)0x00060000) /* MAC transmit frame controller: Transferring input frame for transmission */ #define ETH_MAC_MII_TRANSMIT_ACTIVE ((uint32_t)0x00010000) /* MAC MII transmit engine active */ #define ETH_MAC_RXFIFO_EMPTY ((uint32_t)0x00000000) /* Rx FIFO fill level: empty */ #define ETH_MAC_RXFIFO_BELOW_THRESHOLD ((uint32_t)0x00000100) /* Rx FIFO fill level: fill-level below flow-control de-activate threshold */ #define ETH_MAC_RXFIFO_ABOVE_THRESHOLD ((uint32_t)0x00000200) /* Rx FIFO fill level: fill-level above flow-control activate threshold */ #define ETH_MAC_RXFIFO_FULL ((uint32_t)0x00000300) /* Rx FIFO fill level: full */ #define ETH_MAC_READCONTROLLER_IDLE ((uint32_t)0x00000000) /* Rx FIFO read controller IDLE state */ #define ETH_MAC_READCONTROLLER_READING_DATA ((uint32_t)0x00000020) /* Rx FIFO read controller Reading frame data */ #define ETH_MAC_READCONTROLLER_READING_STATUS ((uint32_t)0x00000040) /* Rx FIFO read controller Reading frame status (or time-stamp) */ #define ETH_MAC_READCONTROLLER_FLUSHING ((uint32_t)0x00000060) /* Rx FIFO read controller Flushing the frame data and status */ #define ETH_MAC_RXFIFO_WRITE_ACTIVE ((uint32_t)0x00000010) /* Rx FIFO write controller active */ #define ETH_MAC_SMALL_FIFO_NOTACTIVE ((uint32_t)0x00000000) /* MAC small FIFO read / write controllers not active */ #define ETH_MAC_SMALL_FIFO_READ_ACTIVE ((uint32_t)0x00000002) /* MAC small FIFO read controller active */ #define ETH_MAC_SMALL_FIFO_WRITE_ACTIVE ((uint32_t)0x00000004) /* MAC small FIFO write controller active */ #define ETH_MAC_SMALL_FIFO_RW_ACTIVE ((uint32_t)0x00000006) /* MAC small FIFO read / write controllers active */ #define ETH_MAC_MII_RECEIVE_PROTOCOL_ACTIVE ((uint32_t)0x00000001) /* MAC MII receive protocol engine active */ /** * @} */ /** @defgroup ETH_Drop_TCP_IP_Checksum_Error_Frame ETH Drop TCP IP Checksum Error Frame * @{ */ #define ETH_DROPTCPIPCHECKSUMERRORFRAME_ENABLE ((uint32_t)0x00000000) #define ETH_DROPTCPIPCHECKSUMERRORFRAME_DISABLE ((uint32_t)0x04000000) /** * @} */ /** @defgroup ETH_Receive_Store_Forward ETH Receive Store Forward * @{ */ #define ETH_RECEIVESTOREFORWARD_ENABLE ((uint32_t)0x02000000) #define ETH_RECEIVESTOREFORWARD_DISABLE ((uint32_t)0x00000000) /** * @} */ /** @defgroup ETH_Flush_Received_Frame ETH Flush Received Frame * @{ */ #define ETH_FLUSHRECEIVEDFRAME_ENABLE ((uint32_t)0x00000000) #define ETH_FLUSHRECEIVEDFRAME_DISABLE ((uint32_t)0x01000000) /** * @} */ /** @defgroup ETH_Transmit_Store_Forward ETH Transmit Store Forward * @{ */ #define ETH_TRANSMITSTOREFORWARD_ENABLE ((uint32_t)0x00200000) #define ETH_TRANSMITSTOREFORWARD_DISABLE ((uint32_t)0x00000000) /** * @} */ /** @defgroup ETH_Transmit_Threshold_Control ETH Transmit Threshold Control * @{ */ #define ETH_TRANSMITTHRESHOLDCONTROL_64BYTES ((uint32_t)0x00000000) /*!< threshold level of the MTL Transmit FIFO is 64 Bytes */ #define ETH_TRANSMITTHRESHOLDCONTROL_128BYTES ((uint32_t)0x00004000) /*!< threshold level of the MTL Transmit FIFO is 128 Bytes */ #define ETH_TRANSMITTHRESHOLDCONTROL_192BYTES ((uint32_t)0x00008000) /*!< threshold level of the MTL Transmit FIFO is 192 Bytes */ #define ETH_TRANSMITTHRESHOLDCONTROL_256BYTES ((uint32_t)0x0000C000) /*!< threshold level of the MTL Transmit FIFO is 256 Bytes */ #define ETH_TRANSMITTHRESHOLDCONTROL_40BYTES ((uint32_t)0x00010000) /*!< threshold level of the MTL Transmit FIFO is 40 Bytes */ #define ETH_TRANSMITTHRESHOLDCONTROL_32BYTES ((uint32_t)0x00014000) /*!< threshold level of the MTL Transmit FIFO is 32 Bytes */ #define ETH_TRANSMITTHRESHOLDCONTROL_24BYTES ((uint32_t)0x00018000) /*!< threshold level of the MTL Transmit FIFO is 24 Bytes */ #define ETH_TRANSMITTHRESHOLDCONTROL_16BYTES ((uint32_t)0x0001C000) /*!< threshold level of the MTL Transmit FIFO is 16 Bytes */ /** * @} */ /** @defgroup ETH_Forward_Error_Frames ETH Forward Error Frames * @{ */ #define ETH_FORWARDERRORFRAMES_ENABLE ((uint32_t)0x00000080) #define ETH_FORWARDERRORFRAMES_DISABLE ((uint32_t)0x00000000) /** * @} */ /** @defgroup ETH_Forward_Undersized_Good_Frames ETH Forward Undersized Good Frames * @{ */ #define ETH_FORWARDUNDERSIZEDGOODFRAMES_ENABLE ((uint32_t)0x00000040) #define ETH_FORWARDUNDERSIZEDGOODFRAMES_DISABLE ((uint32_t)0x00000000) /** * @} */ /** @defgroup ETH_Receive_Threshold_Control ETH Receive Threshold Control * @{ */ #define ETH_RECEIVEDTHRESHOLDCONTROL_64BYTES ((uint32_t)0x00000000) /*!< threshold level of the MTL Receive FIFO is 64 Bytes */ #define ETH_RECEIVEDTHRESHOLDCONTROL_32BYTES ((uint32_t)0x00000008) /*!< threshold level of the MTL Receive FIFO is 32 Bytes */ #define ETH_RECEIVEDTHRESHOLDCONTROL_96BYTES ((uint32_t)0x00000010) /*!< threshold level of the MTL Receive FIFO is 96 Bytes */ #define ETH_RECEIVEDTHRESHOLDCONTROL_128BYTES ((uint32_t)0x00000018) /*!< threshold level of the MTL Receive FIFO is 128 Bytes */ /** * @} */ /** @defgroup ETH_Second_Frame_Operate ETH Second Frame Operate * @{ */ #define ETH_SECONDFRAMEOPERARTE_ENABLE ((uint32_t)0x00000004) #define ETH_SECONDFRAMEOPERARTE_DISABLE ((uint32_t)0x00000000) /** * @} */ /** @defgroup ETH_Address_Aligned_Beats ETH Address Aligned Beats * @{ */ #define ETH_ADDRESSALIGNEDBEATS_ENABLE ((uint32_t)0x02000000) #define ETH_ADDRESSALIGNEDBEATS_DISABLE ((uint32_t)0x00000000) /** * @} */ /** @defgroup ETH_Fixed_Burst ETH Fixed Burst * @{ */ #define ETH_FIXEDBURST_ENABLE ((uint32_t)0x00010000) #define ETH_FIXEDBURST_DISABLE ((uint32_t)0x00000000) /** * @} */ /** @defgroup ETH_Rx_DMA_Burst_Length ETH Rx DMA Burst Length * @{ */ #define ETH_RXDMABURSTLENGTH_1BEAT ((uint32_t)0x00020000) /*!< maximum number of beats to be transferred in one RxDMA transaction is 1 */ #define ETH_RXDMABURSTLENGTH_2BEAT ((uint32_t)0x00040000) /*!< maximum number of beats to be transferred in one RxDMA transaction is 2 */ #define ETH_RXDMABURSTLENGTH_4BEAT ((uint32_t)0x00080000) /*!< maximum number of beats to be transferred in one RxDMA transaction is 4 */ #define ETH_RXDMABURSTLENGTH_8BEAT ((uint32_t)0x00100000) /*!< maximum number of beats to be transferred in one RxDMA transaction is 8 */ #define ETH_RXDMABURSTLENGTH_16BEAT ((uint32_t)0x00200000) /*!< maximum number of beats to be transferred in one RxDMA transaction is 16 */ #define ETH_RXDMABURSTLENGTH_32BEAT ((uint32_t)0x00400000) /*!< maximum number of beats to be transferred in one RxDMA transaction is 32 */ #define ETH_RXDMABURSTLENGTH_4XPBL_4BEAT ((uint32_t)0x01020000) /*!< maximum number of beats to be transferred in one RxDMA transaction is 4 */ #define ETH_RXDMABURSTLENGTH_4XPBL_8BEAT ((uint32_t)0x01040000) /*!< maximum number of beats to be transferred in one RxDMA transaction is 8 */ #define ETH_RXDMABURSTLENGTH_4XPBL_16BEAT ((uint32_t)0x01080000) /*!< maximum number of beats to be transferred in one RxDMA transaction is 16 */ #define ETH_RXDMABURSTLENGTH_4XPBL_32BEAT ((uint32_t)0x01100000) /*!< maximum number of beats to be transferred in one RxDMA transaction is 32 */ #define ETH_RXDMABURSTLENGTH_4XPBL_64BEAT ((uint32_t)0x01200000) /*!< maximum number of beats to be transferred in one RxDMA transaction is 64 */ #define ETH_RXDMABURSTLENGTH_4XPBL_128BEAT ((uint32_t)0x01400000) /*!< maximum number of beats to be transferred in one RxDMA transaction is 128 */ /** * @} */ /** @defgroup ETH_Tx_DMA_Burst_Length ETH Tx DMA Burst Length * @{ */ #define ETH_TXDMABURSTLENGTH_1BEAT ((uint32_t)0x00000100) /*!< maximum number of beats to be transferred in one TxDMA (or both) transaction is 1 */ #define ETH_TXDMABURSTLENGTH_2BEAT ((uint32_t)0x00000200) /*!< maximum number of beats to be transferred in one TxDMA (or both) transaction is 2 */ #define ETH_TXDMABURSTLENGTH_4BEAT ((uint32_t)0x00000400) /*!< maximum number of beats to be transferred in one TxDMA (or both) transaction is 4 */ #define ETH_TXDMABURSTLENGTH_8BEAT ((uint32_t)0x00000800) /*!< maximum number of beats to be transferred in one TxDMA (or both) transaction is 8 */ #define ETH_TXDMABURSTLENGTH_16BEAT ((uint32_t)0x00001000) /*!< maximum number of beats to be transferred in one TxDMA (or both) transaction is 16 */ #define ETH_TXDMABURSTLENGTH_32BEAT ((uint32_t)0x00002000) /*!< maximum number of beats to be transferred in one TxDMA (or both) transaction is 32 */ #define ETH_TXDMABURSTLENGTH_4XPBL_4BEAT ((uint32_t)0x01000100) /*!< maximum number of beats to be transferred in one TxDMA (or both) transaction is 4 */ #define ETH_TXDMABURSTLENGTH_4XPBL_8BEAT ((uint32_t)0x01000200) /*!< maximum number of beats to be transferred in one TxDMA (or both) transaction is 8 */ #define ETH_TXDMABURSTLENGTH_4XPBL_16BEAT ((uint32_t)0x01000400) /*!< maximum number of beats to be transferred in one TxDMA (or both) transaction is 16 */ #define ETH_TXDMABURSTLENGTH_4XPBL_32BEAT ((uint32_t)0x01000800) /*!< maximum number of beats to be transferred in one TxDMA (or both) transaction is 32 */ #define ETH_TXDMABURSTLENGTH_4XPBL_64BEAT ((uint32_t)0x01001000) /*!< maximum number of beats to be transferred in one TxDMA (or both) transaction is 64 */ #define ETH_TXDMABURSTLENGTH_4XPBL_128BEAT ((uint32_t)0x01002000) /*!< maximum number of beats to be transferred in one TxDMA (or both) transaction is 128 */ /** * @} */ /** @defgroup ETH_DMA_Enhanced_descriptor_format ETH DMA Enhanced descriptor format * @{ */ #define ETH_DMAENHANCEDDESCRIPTOR_ENABLE ((uint32_t)0x00000080) #define ETH_DMAENHANCEDDESCRIPTOR_DISABLE ((uint32_t)0x00000000) /** * @} */ /** @defgroup ETH_DMA_Arbitration ETH DMA Arbitration * @{ */ #define ETH_DMAARBITRATION_ROUNDROBIN_RXTX_1_1 ((uint32_t)0x00000000) #define ETH_DMAARBITRATION_ROUNDROBIN_RXTX_2_1 ((uint32_t)0x00004000) #define ETH_DMAARBITRATION_ROUNDROBIN_RXTX_3_1 ((uint32_t)0x00008000) #define ETH_DMAARBITRATION_ROUNDROBIN_RXTX_4_1 ((uint32_t)0x0000C000) #define ETH_DMAARBITRATION_RXPRIORTX ((uint32_t)0x00000002) /** * @} */ /** @defgroup ETH_DMA_Tx_descriptor_segment ETH DMA Tx descriptor segment * @{ */ #define ETH_DMATXDESC_LASTSEGMENTS ((uint32_t)0x40000000) /*!< Last Segment */ #define ETH_DMATXDESC_FIRSTSEGMENT ((uint32_t)0x20000000) /*!< First Segment */ /** * @} */ /** @defgroup ETH_DMA_Tx_descriptor_Checksum_Insertion_Control ETH DMA Tx descriptor Checksum Insertion Control * @{ */ #define ETH_DMATXDESC_CHECKSUMBYPASS ((uint32_t)0x00000000) /*!< Checksum engine bypass */ #define ETH_DMATXDESC_CHECKSUMIPV4HEADER ((uint32_t)0x00400000) /*!< IPv4 header checksum insertion */ #define ETH_DMATXDESC_CHECKSUMTCPUDPICMPSEGMENT ((uint32_t)0x00800000) /*!< TCP/UDP/ICMP checksum insertion. Pseudo header checksum is assumed to be present */ #define ETH_DMATXDESC_CHECKSUMTCPUDPICMPFULL ((uint32_t)0x00C00000) /*!< TCP/UDP/ICMP checksum fully in hardware including pseudo header */ /** * @} */ /** @defgroup ETH_DMA_Rx_descriptor_buffers ETH DMA Rx descriptor buffers * @{ */ #define ETH_DMARXDESC_BUFFER1 ((uint32_t)0x00000000) /*!< DMA Rx Desc Buffer1 */ #define ETH_DMARXDESC_BUFFER2 ((uint32_t)0x00000001) /*!< DMA Rx Desc Buffer2 */ /** * @} */ /** @defgroup ETH_PMT_Flags ETH PMT Flags * @{ */ #define ETH_PMT_FLAG_WUFFRPR ((uint32_t)0x80000000) /*!< Wake-Up Frame Filter Register Pointer Reset */ #define ETH_PMT_FLAG_WUFR ((uint32_t)0x00000040) /*!< Wake-Up Frame Received */ #define ETH_PMT_FLAG_MPR ((uint32_t)0x00000020) /*!< Magic Packet Received */ /** * @} */ /** @defgroup ETH_MMC_Tx_Interrupts ETH MMC Tx Interrupts * @{ */ #define ETH_MMC_IT_TGF ((uint32_t)0x00200000) /*!< When Tx good frame counter reaches half the maximum value */ #define ETH_MMC_IT_TGFMSC ((uint32_t)0x00008000) /*!< When Tx good multi col counter reaches half the maximum value */ #define ETH_MMC_IT_TGFSC ((uint32_t)0x00004000) /*!< When Tx good single col counter reaches half the maximum value */ /** * @} */ /** @defgroup ETH_MMC_Rx_Interrupts ETH MMC Rx Interrupts * @{ */ #define ETH_MMC_IT_RGUF ((uint32_t)0x10020000) /*!< When Rx good unicast frames counter reaches half the maximum value */ #define ETH_MMC_IT_RFAE ((uint32_t)0x10000040) /*!< When Rx alignment error counter reaches half the maximum value */ #define ETH_MMC_IT_RFCE ((uint32_t)0x10000020) /*!< When Rx crc error counter reaches half the maximum value */ /** * @} */ /** @defgroup ETH_MAC_Flags ETH MAC Flags * @{ */ #define ETH_MAC_FLAG_TST ((uint32_t)0x00000200) /*!< Time stamp trigger flag (on MAC) */ #define ETH_MAC_FLAG_MMCT ((uint32_t)0x00000040) /*!< MMC transmit flag */ #define ETH_MAC_FLAG_MMCR ((uint32_t)0x00000020) /*!< MMC receive flag */ #define ETH_MAC_FLAG_MMC ((uint32_t)0x00000010) /*!< MMC flag (on MAC) */ #define ETH_MAC_FLAG_PMT ((uint32_t)0x00000008) /*!< PMT flag (on MAC) */ /** * @} */ /** @defgroup ETH_DMA_Flags ETH DMA Flags * @{ */ #define ETH_DMA_FLAG_TST ((uint32_t)0x20000000) /*!< Time-stamp trigger interrupt (on DMA) */ #define ETH_DMA_FLAG_PMT ((uint32_t)0x10000000) /*!< PMT interrupt (on DMA) */ #define ETH_DMA_FLAG_MMC ((uint32_t)0x08000000) /*!< MMC interrupt (on DMA) */ #define ETH_DMA_FLAG_DATATRANSFERERROR ((uint32_t)0x00800000) /*!< Error bits 0-Rx DMA, 1-Tx DMA */ #define ETH_DMA_FLAG_READWRITEERROR ((uint32_t)0x01000000) /*!< Error bits 0-write transfer, 1-read transfer */ #define ETH_DMA_FLAG_ACCESSERROR ((uint32_t)0x02000000) /*!< Error bits 0-data buffer, 1-desc. access */ #define ETH_DMA_FLAG_NIS ((uint32_t)0x00010000) /*!< Normal interrupt summary flag */ #define ETH_DMA_FLAG_AIS ((uint32_t)0x00008000) /*!< Abnormal interrupt summary flag */ #define ETH_DMA_FLAG_ER ((uint32_t)0x00004000) /*!< Early receive flag */ #define ETH_DMA_FLAG_FBE ((uint32_t)0x00002000) /*!< Fatal bus error flag */ #define ETH_DMA_FLAG_ET ((uint32_t)0x00000400) /*!< Early transmit flag */ #define ETH_DMA_FLAG_RWT ((uint32_t)0x00000200) /*!< Receive watchdog timeout flag */ #define ETH_DMA_FLAG_RPS ((uint32_t)0x00000100) /*!< Receive process stopped flag */ #define ETH_DMA_FLAG_RBU ((uint32_t)0x00000080) /*!< Receive buffer unavailable flag */ #define ETH_DMA_FLAG_R ((uint32_t)0x00000040) /*!< Receive flag */ #define ETH_DMA_FLAG_TU ((uint32_t)0x00000020) /*!< Underflow flag */ #define ETH_DMA_FLAG_RO ((uint32_t)0x00000010) /*!< Overflow flag */ #define ETH_DMA_FLAG_TJT ((uint32_t)0x00000008) /*!< Transmit jabber timeout flag */ #define ETH_DMA_FLAG_TBU ((uint32_t)0x00000004) /*!< Transmit buffer unavailable flag */ #define ETH_DMA_FLAG_TPS ((uint32_t)0x00000002) /*!< Transmit process stopped flag */ #define ETH_DMA_FLAG_T ((uint32_t)0x00000001) /*!< Transmit flag */ /** * @} */ /** @defgroup ETH_MAC_Interrupts ETH MAC Interrupts * @{ */ #define ETH_MAC_IT_TST ((uint32_t)0x00000200) /*!< Time stamp trigger interrupt (on MAC) */ #define ETH_MAC_IT_MMCT ((uint32_t)0x00000040) /*!< MMC transmit interrupt */ #define ETH_MAC_IT_MMCR ((uint32_t)0x00000020) /*!< MMC receive interrupt */ #define ETH_MAC_IT_MMC ((uint32_t)0x00000010) /*!< MMC interrupt (on MAC) */ #define ETH_MAC_IT_PMT ((uint32_t)0x00000008) /*!< PMT interrupt (on MAC) */ /** * @} */ /** @defgroup ETH_DMA_Interrupts ETH DMA Interrupts * @{ */ #define ETH_DMA_IT_TST ((uint32_t)0x20000000) /*!< Time-stamp trigger interrupt (on DMA) */ #define ETH_DMA_IT_PMT ((uint32_t)0x10000000) /*!< PMT interrupt (on DMA) */ #define ETH_DMA_IT_MMC ((uint32_t)0x08000000) /*!< MMC interrupt (on DMA) */ #define ETH_DMA_IT_NIS ((uint32_t)0x00010000) /*!< Normal interrupt summary */ #define ETH_DMA_IT_AIS ((uint32_t)0x00008000) /*!< Abnormal interrupt summary */ #define ETH_DMA_IT_ER ((uint32_t)0x00004000) /*!< Early receive interrupt */ #define ETH_DMA_IT_FBE ((uint32_t)0x00002000) /*!< Fatal bus error interrupt */ #define ETH_DMA_IT_ET ((uint32_t)0x00000400) /*!< Early transmit interrupt */ #define ETH_DMA_IT_RWT ((uint32_t)0x00000200) /*!< Receive watchdog timeout interrupt */ #define ETH_DMA_IT_RPS ((uint32_t)0x00000100) /*!< Receive process stopped interrupt */ #define ETH_DMA_IT_RBU ((uint32_t)0x00000080) /*!< Receive buffer unavailable interrupt */ #define ETH_DMA_IT_R ((uint32_t)0x00000040) /*!< Receive interrupt */ #define ETH_DMA_IT_TU ((uint32_t)0x00000020) /*!< Underflow interrupt */ #define ETH_DMA_IT_RO ((uint32_t)0x00000010) /*!< Overflow interrupt */ #define ETH_DMA_IT_TJT ((uint32_t)0x00000008) /*!< Transmit jabber timeout interrupt */ #define ETH_DMA_IT_TBU ((uint32_t)0x00000004) /*!< Transmit buffer unavailable interrupt */ #define ETH_DMA_IT_TPS ((uint32_t)0x00000002) /*!< Transmit process stopped interrupt */ #define ETH_DMA_IT_T ((uint32_t)0x00000001) /*!< Transmit interrupt */ /** * @} */ /** @defgroup ETH_DMA_transmit_process_state ETH DMA transmit process state * @{ */ #define ETH_DMA_TRANSMITPROCESS_STOPPED ((uint32_t)0x00000000) /*!< Stopped - Reset or Stop Tx Command issued */ #define ETH_DMA_TRANSMITPROCESS_FETCHING ((uint32_t)0x00100000) /*!< Running - fetching the Tx descriptor */ #define ETH_DMA_TRANSMITPROCESS_WAITING ((uint32_t)0x00200000) /*!< Running - waiting for status */ #define ETH_DMA_TRANSMITPROCESS_READING ((uint32_t)0x00300000) /*!< Running - reading the data from host memory */ #define ETH_DMA_TRANSMITPROCESS_SUSPENDED ((uint32_t)0x00600000) /*!< Suspended - Tx Descriptor unavailable */ #define ETH_DMA_TRANSMITPROCESS_CLOSING ((uint32_t)0x00700000) /*!< Running - closing Rx descriptor */ /** * @} */ /** @defgroup ETH_DMA_receive_process_state ETH DMA receive process state * @{ */ #define ETH_DMA_RECEIVEPROCESS_STOPPED ((uint32_t)0x00000000) /*!< Stopped - Reset or Stop Rx Command issued */ #define ETH_DMA_RECEIVEPROCESS_FETCHING ((uint32_t)0x00020000) /*!< Running - fetching the Rx descriptor */ #define ETH_DMA_RECEIVEPROCESS_WAITING ((uint32_t)0x00060000) /*!< Running - waiting for packet */ #define ETH_DMA_RECEIVEPROCESS_SUSPENDED ((uint32_t)0x00080000) /*!< Suspended - Rx Descriptor unavailable */ #define ETH_DMA_RECEIVEPROCESS_CLOSING ((uint32_t)0x000A0000) /*!< Running - closing descriptor */ #define ETH_DMA_RECEIVEPROCESS_QUEUING ((uint32_t)0x000E0000) /*!< Running - queuing the receive frame into host memory */ /** * @} */ /** @defgroup ETH_DMA_overflow ETH DMA overflow * @{ */ #define ETH_DMA_OVERFLOW_RXFIFOCOUNTER ((uint32_t)0x10000000) /*!< Overflow bit for FIFO overflow counter */ #define ETH_DMA_OVERFLOW_MISSEDFRAMECOUNTER ((uint32_t)0x00010000) /*!< Overflow bit for missed frame counter */ /** * @} */ /** @defgroup ETH_EXTI_LINE_WAKEUP ETH EXTI LINE WAKEUP * @{ */ #define ETH_EXTI_LINE_WAKEUP ((uint32_t)0x00080000) /*!< External interrupt line 19 Connected to the ETH EXTI Line */ /** * @} */ /** * @} */ /* Exported macro ------------------------------------------------------------*/ /** @defgroup ETH_Exported_Macros ETH Exported Macros * @brief macros to handle interrupts and specific clock configurations * @{ */ /** @brief Reset ETH handle state * @param __HANDLE__: specifies the ETH handle. * @retval None */ #define __HAL_ETH_RESET_HANDLE_STATE(__HANDLE__) ((__HANDLE__)->State = HAL_ETH_STATE_RESET) /** * @brief Checks whether the specified ETHERNET DMA Tx Desc flag is set or not. * @param __HANDLE__: ETH Handle * @param __FLAG__: specifies the flag of TDES0 to check. * @retval the ETH_DMATxDescFlag (SET or RESET). */ #define __HAL_ETH_DMATXDESC_GET_FLAG(__HANDLE__, __FLAG__) ((__HANDLE__)->TxDesc->Status & (__FLAG__) == (__FLAG__)) /** * @brief Checks whether the specified ETHERNET DMA Rx Desc flag is set or not. * @param __HANDLE__: ETH Handle * @param __FLAG__: specifies the flag of RDES0 to check. * @retval the ETH_DMATxDescFlag (SET or RESET). */ #define __HAL_ETH_DMARXDESC_GET_FLAG(__HANDLE__, __FLAG__) ((__HANDLE__)->RxDesc->Status & (__FLAG__) == (__FLAG__)) /** * @brief Enables the specified DMA Rx Desc receive interrupt. * @param __HANDLE__: ETH Handle * @retval None */ #define __HAL_ETH_DMARXDESC_ENABLE_IT(__HANDLE__) ((__HANDLE__)->RxDesc->ControlBufferSize &=(~(uint32_t)ETH_DMARXDESC_DIC)) /** * @brief Disables the specified DMA Rx Desc receive interrupt. * @param __HANDLE__: ETH Handle * @retval None */ #define __HAL_ETH_DMARXDESC_DISABLE_IT(__HANDLE__) ((__HANDLE__)->RxDesc->ControlBufferSize |= ETH_DMARXDESC_DIC) /** * @brief Set the specified DMA Rx Desc Own bit. * @param __HANDLE__: ETH Handle * @retval None */ #define __HAL_ETH_DMARXDESC_SET_OWN_BIT(__HANDLE__) ((__HANDLE__)->RxDesc->Status |= ETH_DMARXDESC_OWN) /** * @brief Returns the specified ETHERNET DMA Tx Desc collision count. * @param __HANDLE__: ETH Handle * @retval The Transmit descriptor collision counter value. */ #define __HAL_ETH_DMATXDESC_GET_COLLISION_COUNT(__HANDLE__) (((__HANDLE__)->TxDesc->Status & ETH_DMATXDESC_CC) >> ETH_DMATXDESC_COLLISION_COUNTSHIFT) /** * @brief Set the specified DMA Tx Desc Own bit. * @param __HANDLE__: ETH Handle * @retval None */ #define __HAL_ETH_DMATXDESC_SET_OWN_BIT(__HANDLE__) ((__HANDLE__)->TxDesc->Status |= ETH_DMATXDESC_OWN) /** * @brief Enables the specified DMA Tx Desc Transmit interrupt. * @param __HANDLE__: ETH Handle * @retval None */ #define __HAL_ETH_DMATXDESC_ENABLE_IT(__HANDLE__) ((__HANDLE__)->TxDesc->Status |= ETH_DMATXDESC_IC) /** * @brief Disables the specified DMA Tx Desc Transmit interrupt. * @param __HANDLE__: ETH Handle * @retval None */ #define __HAL_ETH_DMATXDESC_DISABLE_IT(__HANDLE__) ((__HANDLE__)->TxDesc->Status &= ~ETH_DMATXDESC_IC) /** * @brief Selects the specified ETHERNET DMA Tx Desc Checksum Insertion. * @param __HANDLE__: ETH Handle * @param __CHECKSUM__: specifies is the DMA Tx desc checksum insertion. * This parameter can be one of the following values: * @arg ETH_DMATXDESC_CHECKSUMBYPASS : Checksum bypass * @arg ETH_DMATXDESC_CHECKSUMIPV4HEADER : IPv4 header checksum * @arg ETH_DMATXDESC_CHECKSUMTCPUDPICMPSEGMENT : TCP/UDP/ICMP checksum. Pseudo header checksum is assumed to be present * @arg ETH_DMATXDESC_CHECKSUMTCPUDPICMPFULL : TCP/UDP/ICMP checksum fully in hardware including pseudo header * @retval None */ #define __HAL_ETH_DMATXDESC_CHECKSUM_INSERTION(__HANDLE__, __CHECKSUM__) ((__HANDLE__)->TxDesc->Status |= (__CHECKSUM__)) /** * @brief Enables the DMA Tx Desc CRC. * @param __HANDLE__: ETH Handle * @retval None */ #define __HAL_ETH_DMATXDESC_CRC_ENABLE(__HANDLE__) ((__HANDLE__)->TxDesc->Status &= ~ETH_DMATXDESC_DC) /** * @brief Disables the DMA Tx Desc CRC. * @param __HANDLE__: ETH Handle * @retval None */ #define __HAL_ETH_DMATXDESC_CRC_DISABLE(__HANDLE__) ((__HANDLE__)->TxDesc->Status |= ETH_DMATXDESC_DC) /** * @brief Enables the DMA Tx Desc padding for frame shorter than 64 bytes. * @param __HANDLE__: ETH Handle * @retval None */ #define __HAL_ETH_DMATXDESC_SHORT_FRAME_PADDING_ENABLE(__HANDLE__) ((__HANDLE__)->TxDesc->Status &= ~ETH_DMATXDESC_DP) /** * @brief Disables the DMA Tx Desc padding for frame shorter than 64 bytes. * @param __HANDLE__: ETH Handle * @retval None */ #define __HAL_ETH_DMATXDESC_SHORT_FRAME_PADDING_DISABLE(__HANDLE__) ((__HANDLE__)->TxDesc->Status |= ETH_DMATXDESC_DP) /** * @brief Enables the specified ETHERNET MAC interrupts. * @param __HANDLE__ : ETH Handle * @param __INTERRUPT__: specifies the ETHERNET MAC interrupt sources to be * enabled or disabled. * This parameter can be any combination of the following values: * @arg ETH_MAC_IT_TST : Time stamp trigger interrupt * @arg ETH_MAC_IT_PMT : PMT interrupt * @retval None */ #define __HAL_ETH_MAC_ENABLE_IT(__HANDLE__, __INTERRUPT__) ((__HANDLE__)->Instance->MACIMR |= (__INTERRUPT__)) /** * @brief Disables the specified ETHERNET MAC interrupts. * @param __HANDLE__ : ETH Handle * @param __INTERRUPT__: specifies the ETHERNET MAC interrupt sources to be * enabled or disabled. * This parameter can be any combination of the following values: * @arg ETH_MAC_IT_TST : Time stamp trigger interrupt * @arg ETH_MAC_IT_PMT : PMT interrupt * @retval None */ #define __HAL_ETH_MAC_DISABLE_IT(__HANDLE__, __INTERRUPT__) ((__HANDLE__)->Instance->MACIMR &= ~(__INTERRUPT__)) /** * @brief Initiate a Pause Control Frame (Full-duplex only). * @param __HANDLE__: ETH Handle * @retval None */ #define __HAL_ETH_INITIATE_PAUSE_CONTROL_FRAME(__HANDLE__) ((__HANDLE__)->Instance->MACFCR |= ETH_MACFCR_FCBBPA) /** * @brief Checks whether the ETHERNET flow control busy bit is set or not. * @param __HANDLE__: ETH Handle * @retval The new state of flow control busy status bit (SET or RESET). */ #define __HAL_ETH_GET_FLOW_CONTROL_BUSY_STATUS(__HANDLE__) (((__HANDLE__)->Instance->MACFCR & ETH_MACFCR_FCBBPA) == ETH_MACFCR_FCBBPA) /** * @brief Enables the MAC Back Pressure operation activation (Half-duplex only). * @param __HANDLE__: ETH Handle * @retval None */ #define __HAL_ETH_BACK_PRESSURE_ACTIVATION_ENABLE(__HANDLE__) ((__HANDLE__)->Instance->MACFCR |= ETH_MACFCR_FCBBPA) /** * @brief Disables the MAC BackPressure operation activation (Half-duplex only). * @param __HANDLE__: ETH Handle * @retval None */ #define __HAL_ETH_BACK_PRESSURE_ACTIVATION_DISABLE(__HANDLE__) ((__HANDLE__)->Instance->MACFCR &= ~ETH_MACFCR_FCBBPA) /** * @brief Checks whether the specified ETHERNET MAC flag is set or not. * @param __HANDLE__: ETH Handle * @param __FLAG__: specifies the flag to check. * This parameter can be one of the following values: * @arg ETH_MAC_FLAG_TST : Time stamp trigger flag * @arg ETH_MAC_FLAG_MMCT : MMC transmit flag * @arg ETH_MAC_FLAG_MMCR : MMC receive flag * @arg ETH_MAC_FLAG_MMC : MMC flag * @arg ETH_MAC_FLAG_PMT : PMT flag * @retval The state of ETHERNET MAC flag. */ #define __HAL_ETH_MAC_GET_FLAG(__HANDLE__, __FLAG__) (((__HANDLE__)->Instance->MACSR &( __FLAG__)) == ( __FLAG__)) /** * @brief Enables the specified ETHERNET DMA interrupts. * @param __HANDLE__ : ETH Handle * @param __INTERRUPT__: specifies the ETHERNET DMA interrupt sources to be * enabled @ref ETH_DMA_Interrupts * @retval None */ #define __HAL_ETH_DMA_ENABLE_IT(__HANDLE__, __INTERRUPT__) ((__HANDLE__)->Instance->DMAIER |= (__INTERRUPT__)) /** * @brief Disables the specified ETHERNET DMA interrupts. * @param __HANDLE__ : ETH Handle * @param __INTERRUPT__: specifies the ETHERNET DMA interrupt sources to be * disabled. @ref ETH_DMA_Interrupts * @retval None */ #define __HAL_ETH_DMA_DISABLE_IT(__HANDLE__, __INTERRUPT__) ((__HANDLE__)->Instance->DMAIER &= ~(__INTERRUPT__)) /** * @brief Clears the ETHERNET DMA IT pending bit. * @param __HANDLE__ : ETH Handle * @param __INTERRUPT__: specifies the interrupt pending bit to clear. @ref ETH_DMA_Interrupts * @retval None */ #define __HAL_ETH_DMA_CLEAR_IT(__HANDLE__, __INTERRUPT__) ((__HANDLE__)->Instance->DMASR =(__INTERRUPT__)) /** * @brief Checks whether the specified ETHERNET DMA flag is set or not. * @param __HANDLE__: ETH Handle * @param __FLAG__: specifies the flag to check. @ref ETH_DMA_Flags * @retval The new state of ETH_DMA_FLAG (SET or RESET). */ #define __HAL_ETH_DMA_GET_FLAG(__HANDLE__, __FLAG__) (((__HANDLE__)->Instance->DMASR &( __FLAG__)) == ( __FLAG__)) /** * @brief Checks whether the specified ETHERNET DMA flag is set or not. * @param __HANDLE__: ETH Handle * @param __FLAG__: specifies the flag to clear. @ref ETH_DMA_Flags * @retval The new state of ETH_DMA_FLAG (SET or RESET). */ #define __HAL_ETH_DMA_CLEAR_FLAG(__HANDLE__, __FLAG__) ((__HANDLE__)->Instance->DMASR = (__FLAG__)) /** * @brief Checks whether the specified ETHERNET DMA overflow flag is set or not. * @param __HANDLE__: ETH Handle * @param __OVERFLOW__: specifies the DMA overflow flag to check. * This parameter can be one of the following values: * @arg ETH_DMA_OVERFLOW_RXFIFOCOUNTER : Overflow for FIFO Overflows Counter * @arg ETH_DMA_OVERFLOW_MISSEDFRAMECOUNTER : Overflow for Buffer Unavailable Missed Frame Counter * @retval The state of ETHERNET DMA overflow Flag (SET or RESET). */ #define __HAL_ETH_GET_DMA_OVERFLOW_STATUS(__HANDLE__, __OVERFLOW__) (((__HANDLE__)->Instance->DMAMFBOCR & (__OVERFLOW__)) == (__OVERFLOW__)) /** * @brief Set the DMA Receive status watchdog timer register value * @param __HANDLE__: ETH Handle * @param __VALUE__: DMA Receive status watchdog timer register value * @retval None */ #define __HAL_ETH_SET_RECEIVE_WATCHDOG_TIMER(__HANDLE__, __VALUE__) ((__HANDLE__)->Instance->DMARSWTR = (__VALUE__)) /** * @brief Enables any unicast packet filtered by the MAC address * recognition to be a wake-up frame. * @param __HANDLE__: ETH Handle. * @retval None */ #define __HAL_ETH_GLOBAL_UNICAST_WAKEUP_ENABLE(__HANDLE__) ((__HANDLE__)->Instance->MACPMTCSR |= ETH_MACPMTCSR_GU) /** * @brief Disables any unicast packet filtered by the MAC address * recognition to be a wake-up frame. * @param __HANDLE__: ETH Handle. * @retval None */ #define __HAL_ETH_GLOBAL_UNICAST_WAKEUP_DISABLE(__HANDLE__) ((__HANDLE__)->Instance->MACPMTCSR &= ~ETH_MACPMTCSR_GU) /** * @brief Enables the MAC Wake-Up Frame Detection. * @param __HANDLE__: ETH Handle. * @retval None */ #define __HAL_ETH_WAKEUP_FRAME_DETECTION_ENABLE(__HANDLE__) ((__HANDLE__)->Instance->MACPMTCSR |= ETH_MACPMTCSR_WFE) /** * @brief Disables the MAC Wake-Up Frame Detection. * @param __HANDLE__: ETH Handle. * @retval None */ #define __HAL_ETH_WAKEUP_FRAME_DETECTION_DISABLE(__HANDLE__) ((__HANDLE__)->Instance->MACPMTCSR &= ~ETH_MACPMTCSR_WFE) /** * @brief Enables the MAC Magic Packet Detection. * @param __HANDLE__: ETH Handle. * @retval None */ #define __HAL_ETH_MAGIC_PACKET_DETECTION_ENABLE(__HANDLE__) ((__HANDLE__)->Instance->MACPMTCSR |= ETH_MACPMTCSR_MPE) /** * @brief Disables the MAC Magic Packet Detection. * @param __HANDLE__: ETH Handle. * @retval None */ #define __HAL_ETH_MAGIC_PACKET_DETECTION_DISABLE(__HANDLE__) ((__HANDLE__)->Instance->MACPMTCSR &= ~ETH_MACPMTCSR_WFE) /** * @brief Enables the MAC Power Down. * @param __HANDLE__: ETH Handle * @retval None */ #define __HAL_ETH_POWER_DOWN_ENABLE(__HANDLE__) ((__HANDLE__)->Instance->MACPMTCSR |= ETH_MACPMTCSR_PD) /** * @brief Disables the MAC Power Down. * @param __HANDLE__: ETH Handle * @retval None */ #define __HAL_ETH_POWER_DOWN_DISABLE(__HANDLE__) ((__HANDLE__)->Instance->MACPMTCSR &= ~ETH_MACPMTCSR_PD) /** * @brief Checks whether the specified ETHERNET PMT flag is set or not. * @param __HANDLE__: ETH Handle. * @param __FLAG__: specifies the flag to check. * This parameter can be one of the following values: * @arg ETH_PMT_FLAG_WUFFRPR : Wake-Up Frame Filter Register Pointer Reset * @arg ETH_PMT_FLAG_WUFR : Wake-Up Frame Received * @arg ETH_PMT_FLAG_MPR : Magic Packet Received * @retval The new state of ETHERNET PMT Flag (SET or RESET). */ #define __HAL_ETH_GET_PMT_FLAG_STATUS(__HANDLE__, __FLAG__) (((__HANDLE__)->Instance->MACPMTCSR &( __FLAG__)) == ( __FLAG__)) /** * @brief Preset and Initialize the MMC counters to almost-full value: 0xFFFF_FFF0 (full - 16) * @param __HANDLE__: ETH Handle. * @retval None */ #define __HAL_ETH_MMC_COUNTER_FULL_PRESET(__HANDLE__) ((__HANDLE__)->Instance->MMCCR |= (ETH_MMCCR_MCFHP | ETH_MMCCR_MCP)) /** * @brief Preset and Initialize the MMC counters to almost-half value: 0x7FFF_FFF0 (half - 16) * @param __HANDLE__: ETH Handle. * @retval None */ #define __HAL_ETH_MMC_COUNTER_HALF_PRESET(__HANDLE__) do{(__HANDLE__)->Instance->MMCCR &= ~ETH_MMCCR_MCFHP;\ (__HANDLE__)->Instance->MMCCR |= ETH_MMCCR_MCP;} while (0) /** * @brief Enables the MMC Counter Freeze. * @param __HANDLE__: ETH Handle. * @retval None */ #define __HAL_ETH_MMC_COUNTER_FREEZE_ENABLE(__HANDLE__) ((__HANDLE__)->Instance->MMCCR |= ETH_MMCCR_MCF) /** * @brief Disables the MMC Counter Freeze. * @param __HANDLE__: ETH Handle. * @retval None */ #define __HAL_ETH_MMC_COUNTER_FREEZE_DISABLE(__HANDLE__) ((__HANDLE__)->Instance->MMCCR &= ~ETH_MMCCR_MCF) /** * @brief Enables the MMC Reset On Read. * @param __HANDLE__: ETH Handle. * @retval None */ #define __HAL_ETH_ETH_MMC_RESET_ONREAD_ENABLE(__HANDLE__) ((__HANDLE__)->Instance->MMCCR |= ETH_MMCCR_ROR) /** * @brief Disables the MMC Reset On Read. * @param __HANDLE__: ETH Handle. * @retval None */ #define __HAL_ETH_ETH_MMC_RESET_ONREAD_DISABLE(__HANDLE__) ((__HANDLE__)->Instance->MMCCR &= ~ETH_MMCCR_ROR) /** * @brief Enables the MMC Counter Stop Rollover. * @param __HANDLE__: ETH Handle. * @retval None */ #define __HAL_ETH_ETH_MMC_COUNTER_ROLLOVER_ENABLE(__HANDLE__) ((__HANDLE__)->Instance->MMCCR &= ~ETH_MMCCR_CSR) /** * @brief Disables the MMC Counter Stop Rollover. * @param __HANDLE__: ETH Handle. * @retval None */ #define __HAL_ETH_ETH_MMC_COUNTER_ROLLOVER_DISABLE(__HANDLE__) ((__HANDLE__)->Instance->MMCCR |= ETH_MMCCR_CSR) /** * @brief Resets the MMC Counters. * @param __HANDLE__: ETH Handle. * @retval None */ #define __HAL_ETH_MMC_COUNTERS_RESET(__HANDLE__) ((__HANDLE__)->Instance->MMCCR |= ETH_MMCCR_CR) /** * @brief Enables the specified ETHERNET MMC Rx interrupts. * @param __HANDLE__: ETH Handle. * @param __INTERRUPT__: specifies the ETHERNET MMC interrupt sources to be enabled or disabled. * This parameter can be one of the following values: * @arg ETH_MMC_IT_RGUF : When Rx good unicast frames counter reaches half the maximum value * @arg ETH_MMC_IT_RFAE : When Rx alignment error counter reaches half the maximum value * @arg ETH_MMC_IT_RFCE : When Rx crc error counter reaches half the maximum value * @retval None */ #define __HAL_ETH_MMC_RX_IT_ENABLE(__HANDLE__, __INTERRUPT__) (__HANDLE__)->Instance->MMCRIMR &= ~((__INTERRUPT__) & 0xEFFFFFFF) /** * @brief Disables the specified ETHERNET MMC Rx interrupts. * @param __HANDLE__: ETH Handle. * @param __INTERRUPT__: specifies the ETHERNET MMC interrupt sources to be enabled or disabled. * This parameter can be one of the following values: * @arg ETH_MMC_IT_RGUF : When Rx good unicast frames counter reaches half the maximum value * @arg ETH_MMC_IT_RFAE : When Rx alignment error counter reaches half the maximum value * @arg ETH_MMC_IT_RFCE : When Rx crc error counter reaches half the maximum value * @retval None */ #define __HAL_ETH_MMC_RX_IT_DISABLE(__HANDLE__, __INTERRUPT__) (__HANDLE__)->Instance->MMCRIMR |= ((__INTERRUPT__) & 0xEFFFFFFF) /** * @brief Enables the specified ETHERNET MMC Tx interrupts. * @param __HANDLE__: ETH Handle. * @param __INTERRUPT__: specifies the ETHERNET MMC interrupt sources to be enabled or disabled. * This parameter can be one of the following values: * @arg ETH_MMC_IT_TGF : When Tx good frame counter reaches half the maximum value * @arg ETH_MMC_IT_TGFMSC: When Tx good multi col counter reaches half the maximum value * @arg ETH_MMC_IT_TGFSC : When Tx good single col counter reaches half the maximum value * @retval None */ #define __HAL_ETH_MMC_TX_IT_ENABLE(__HANDLE__, __INTERRUPT__) ((__HANDLE__)->Instance->MMCRIMR &= ~ (__INTERRUPT__)) /** * @brief Disables the specified ETHERNET MMC Tx interrupts. * @param __HANDLE__: ETH Handle. * @param __INTERRUPT__: specifies the ETHERNET MMC interrupt sources to be enabled or disabled. * This parameter can be one of the following values: * @arg ETH_MMC_IT_TGF : When Tx good frame counter reaches half the maximum value * @arg ETH_MMC_IT_TGFMSC: When Tx good multi col counter reaches half the maximum value * @arg ETH_MMC_IT_TGFSC : When Tx good single col counter reaches half the maximum value * @retval None */ #define __HAL_ETH_MMC_TX_IT_DISABLE(__HANDLE__, __INTERRUPT__) ((__HANDLE__)->Instance->MMCRIMR |= (__INTERRUPT__)) /** * @brief Enables the ETH External interrupt line. * @retval None */ #define __HAL_ETH_WAKEUP_EXTI_ENABLE_IT() EXTI->IMR |= (ETH_EXTI_LINE_WAKEUP) /** * @brief Disables the ETH External interrupt line. * @retval None */ #define __HAL_ETH_WAKEUP_EXTI_DISABLE_IT() EXTI->IMR &= ~(ETH_EXTI_LINE_WAKEUP) /** * @brief Enable event on ETH External event line. * @retval None. */ #define __HAL_ETH_WAKEUP_EXTI_ENABLE_EVENT() EXTI->EMR |= (ETH_EXTI_LINE_WAKEUP) /** * @brief Disable event on ETH External event line * @retval None. */ #define __HAL_ETH_WAKEUP_EXTI_DISABLE_EVENT() EXTI->EMR &= ~(ETH_EXTI_LINE_WAKEUP) /** * @brief Get flag of the ETH External interrupt line. * @retval None */ #define __HAL_ETH_WAKEUP_EXTI_GET_FLAG() EXTI->PR & (ETH_EXTI_LINE_WAKEUP) /** * @brief Clear flag of the ETH External interrupt line. * @retval None */ #define __HAL_ETH_WAKEUP_EXTI_CLEAR_FLAG() EXTI->PR = (ETH_EXTI_LINE_WAKEUP) /** * @brief Enables rising edge trigger to the ETH External interrupt line. * @retval None */ #define __HAL_ETH_WAKEUP_EXTI_ENABLE_RISING_EDGE_TRIGGER() EXTI->RTSR |= ETH_EXTI_LINE_WAKEUP /** * @brief Disables the rising edge trigger to the ETH External interrupt line. * @retval None */ #define __HAL_ETH_WAKEUP_EXTI_DISABLE_RISING_EDGE_TRIGGER() EXTI->RTSR &= ~(ETH_EXTI_LINE_WAKEUP) /** * @brief Enables falling edge trigger to the ETH External interrupt line. * @retval None */ #define __HAL_ETH_WAKEUP_EXTI_ENABLE_FALLING_EDGE_TRIGGER() EXTI->FTSR |= (ETH_EXTI_LINE_WAKEUP) /** * @brief Disables falling edge trigger to the ETH External interrupt line. * @retval None */ #define __HAL_ETH_WAKEUP_EXTI_DISABLE_FALLING_EDGE_TRIGGER() EXTI->FTSR &= ~(ETH_EXTI_LINE_WAKEUP) /** * @brief Enables rising/falling edge trigger to the ETH External interrupt line. * @retval None */ #define __HAL_ETH_WAKEUP_EXTI_ENABLE_FALLINGRISING_TRIGGER() EXTI->RTSR |= ETH_EXTI_LINE_WAKEUP;\ EXTI->FTSR |= ETH_EXTI_LINE_WAKEUP /** * @brief Disables rising/falling edge trigger to the ETH External interrupt line. * @retval None */ #define __HAL_ETH_WAKEUP_EXTI_DISABLE_FALLINGRISING_TRIGGER() EXTI->RTSR &= ~(ETH_EXTI_LINE_WAKEUP);\ EXTI->FTSR &= ~(ETH_EXTI_LINE_WAKEUP) /** * @brief Generate a Software interrupt on selected EXTI line. * @retval None. */ #define __HAL_ETH_WAKEUP_EXTI_GENERATE_SWIT() EXTI->SWIER|= ETH_EXTI_LINE_WAKEUP /** * @} */ /* Exported functions --------------------------------------------------------*/ /** @addtogroup ETH_Exported_Functions * @{ */ /* Initialization and de-initialization functions ****************************/ /** @addtogroup ETH_Exported_Functions_Group1 * @{ */ HAL_StatusTypeDef HAL_ETH_Init(ETH_HandleTypeDef *heth); HAL_StatusTypeDef HAL_ETH_DeInit(ETH_HandleTypeDef *heth); void HAL_ETH_MspInit(ETH_HandleTypeDef *heth); void HAL_ETH_MspDeInit(ETH_HandleTypeDef *heth); HAL_StatusTypeDef HAL_ETH_DMATxDescListInit(ETH_HandleTypeDef *heth, ETH_DMADescTypeDef *DMATxDescTab, uint8_t* TxBuff, uint32_t TxBuffCount); HAL_StatusTypeDef HAL_ETH_DMARxDescListInit(ETH_HandleTypeDef *heth, ETH_DMADescTypeDef *DMARxDescTab, uint8_t *RxBuff, uint32_t RxBuffCount); /** * @} */ /* IO operation functions ****************************************************/ /** @addtogroup ETH_Exported_Functions_Group2 * @{ */ HAL_StatusTypeDef HAL_ETH_TransmitFrame(ETH_HandleTypeDef *heth, uint32_t FrameLength); HAL_StatusTypeDef HAL_ETH_GetReceivedFrame(ETH_HandleTypeDef *heth); /* Communication with PHY functions*/ HAL_StatusTypeDef HAL_ETH_ReadPHYRegister(ETH_HandleTypeDef *heth, uint16_t PHYReg, uint32_t *RegValue); HAL_StatusTypeDef HAL_ETH_WritePHYRegister(ETH_HandleTypeDef *heth, uint16_t PHYReg, uint32_t RegValue); /* Non-Blocking mode: Interrupt */ HAL_StatusTypeDef HAL_ETH_GetReceivedFrame_IT(ETH_HandleTypeDef *heth); void HAL_ETH_IRQHandler(ETH_HandleTypeDef *heth); /* Callback in non blocking modes (Interrupt) */ void HAL_ETH_TxCpltCallback(ETH_HandleTypeDef *heth); void HAL_ETH_RxCpltCallback(ETH_HandleTypeDef *heth); void HAL_ETH_ErrorCallback(ETH_HandleTypeDef *heth); /** * @} */ /* Peripheral Control functions **********************************************/ /** @addtogroup ETH_Exported_Functions_Group3 * @{ */ HAL_StatusTypeDef HAL_ETH_Start(ETH_HandleTypeDef *heth); HAL_StatusTypeDef HAL_ETH_Stop(ETH_HandleTypeDef *heth); HAL_StatusTypeDef HAL_ETH_ConfigMAC(ETH_HandleTypeDef *heth, ETH_MACInitTypeDef *macconf); HAL_StatusTypeDef HAL_ETH_ConfigDMA(ETH_HandleTypeDef *heth, ETH_DMAInitTypeDef *dmaconf); /** * @} */ /* Peripheral State functions ************************************************/ /** @addtogroup ETH_Exported_Functions_Group4 * @{ */ HAL_ETH_StateTypeDef HAL_ETH_GetState(ETH_HandleTypeDef *heth); /** * @} */ /** * @} */ /** * @} */ /** * @} */ #endif /* STM32F405xx || STM32F415xx || STM32F407xx || STM32F417xx || STM32F427xx ||\ STM32F437xx || STM32F429xx || STM32F439xx || STM32F469xx || STM32F479xx */ #ifdef __cplusplus } #endif #endif /* __STM32F4xx_HAL_ETH_H */ /************************ (C) COPYRIGHT STMicroelectronics *****END OF FILE****/ ================================================ FILE: Zelig/mbed/TARGET_NUCLEO_F401RE/stm32f4xx_hal_flash.h ================================================ /** ****************************************************************************** * @file stm32f4xx_hal_flash.h * @author MCD Application Team * @version V1.4.1 * @date 09-October-2015 * @brief Header file of FLASH HAL module. ****************************************************************************** * @attention * *

© COPYRIGHT(c) 2015 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. * ****************************************************************************** */ /* Define to prevent recursive inclusion -------------------------------------*/ #ifndef __STM32F4xx_HAL_FLASH_H #define __STM32F4xx_HAL_FLASH_H #ifdef __cplusplus extern "C" { #endif /* Includes ------------------------------------------------------------------*/ #include "stm32f4xx_hal_def.h" /** @addtogroup STM32F4xx_HAL_Driver * @{ */ /** @addtogroup FLASH * @{ */ /* Exported types ------------------------------------------------------------*/ /** @defgroup FLASH_Exported_Types FLASH Exported Types * @{ */ /** * @brief FLASH Procedure structure definition */ typedef enum { FLASH_PROC_NONE = 0, FLASH_PROC_SECTERASE, FLASH_PROC_MASSERASE, FLASH_PROC_PROGRAM } FLASH_ProcedureTypeDef; /** * @brief FLASH handle Structure definition */ typedef struct { __IO FLASH_ProcedureTypeDef ProcedureOnGoing; /*Internal variable to indicate which procedure is ongoing or not in IT context*/ __IO uint32_t NbSectorsToErase; /*Internal variable to save the remaining sectors to erase in IT context*/ __IO uint8_t VoltageForErase; /*Internal variable to provide voltage range selected by user in IT context*/ __IO uint32_t Sector; /*Internal variable to define the current sector which is erasing*/ __IO uint32_t Bank; /*Internal variable to save current bank selected during mass erase*/ __IO uint32_t Address; /*Internal variable to save address selected for program*/ HAL_LockTypeDef Lock; /* FLASH locking object */ __IO uint32_t ErrorCode; /* FLASH error code */ }FLASH_ProcessTypeDef; /** * @} */ /* Exported constants --------------------------------------------------------*/ /** @defgroup FLASH_Exported_Constants FLASH Exported Constants * @{ */ /** @defgroup FLASH_Error_Code FLASH Error Code * @brief FLASH Error Code * @{ */ #define HAL_FLASH_ERROR_NONE ((uint32_t)0x00000000) /*!< No error */ #define HAL_FLASH_ERROR_RD ((uint32_t)0x00000001) /*!< Read Protection error */ #define HAL_FLASH_ERROR_PGS ((uint32_t)0x00000002) /*!< Programming Sequence error */ #define HAL_FLASH_ERROR_PGP ((uint32_t)0x00000004) /*!< Programming Parallelism error */ #define HAL_FLASH_ERROR_PGA ((uint32_t)0x00000008) /*!< Programming Alignment error */ #define HAL_FLASH_ERROR_WRP ((uint32_t)0x00000010) /*!< Write protection error */ #define HAL_FLASH_ERROR_OPERATION ((uint32_t)0x00000020) /*!< Operation Error */ /** * @} */ /** @defgroup FLASH_Type_Program FLASH Type Program * @{ */ #define FLASH_TYPEPROGRAM_BYTE ((uint32_t)0x00) /*!< Program byte (8-bit) at a specified address */ #define FLASH_TYPEPROGRAM_HALFWORD ((uint32_t)0x01) /*!< Program a half-word (16-bit) at a specified address */ #define FLASH_TYPEPROGRAM_WORD ((uint32_t)0x02) /*!< Program a word (32-bit) at a specified address */ #define FLASH_TYPEPROGRAM_DOUBLEWORD ((uint32_t)0x03) /*!< Program a double word (64-bit) at a specified address */ /** * @} */ /** @defgroup FLASH_Flag_definition FLASH Flag definition * @brief Flag definition * @{ */ #define FLASH_FLAG_EOP FLASH_SR_EOP /*!< FLASH End of Operation flag */ #define FLASH_FLAG_OPERR FLASH_SR_SOP /*!< FLASH operation Error flag */ #define FLASH_FLAG_WRPERR FLASH_SR_WRPERR /*!< FLASH Write protected error flag */ #define FLASH_FLAG_PGAERR FLASH_SR_PGAERR /*!< FLASH Programming Alignment error flag */ #define FLASH_FLAG_PGPERR FLASH_SR_PGPERR /*!< FLASH Programming Parallelism error flag */ #define FLASH_FLAG_PGSERR FLASH_SR_PGSERR /*!< FLASH Programming Sequence error flag */ #define FLASH_FLAG_RDERR ((uint32_t)0x00000100) /*!< Read Protection error flag (PCROP) */ #define FLASH_FLAG_BSY FLASH_SR_BSY /*!< FLASH Busy flag */ /** * @} */ /** @defgroup FLASH_Interrupt_definition FLASH Interrupt definition * @brief FLASH Interrupt definition * @{ */ #define FLASH_IT_EOP FLASH_CR_EOPIE /*!< End of FLASH Operation Interrupt source */ #define FLASH_IT_ERR ((uint32_t)0x02000000) /*!< Error Interrupt source */ /** * @} */ /** @defgroup FLASH_Program_Parallelism FLASH Program Parallelism * @{ */ #define FLASH_PSIZE_BYTE ((uint32_t)0x00000000) #define FLASH_PSIZE_HALF_WORD ((uint32_t)0x00000100) #define FLASH_PSIZE_WORD ((uint32_t)0x00000200) #define FLASH_PSIZE_DOUBLE_WORD ((uint32_t)0x00000300) #define CR_PSIZE_MASK ((uint32_t)0xFFFFFCFF) /** * @} */ /** @defgroup FLASH_Keys FLASH Keys * @{ */ #define RDP_KEY ((uint16_t)0x00A5) #define FLASH_KEY1 ((uint32_t)0x45670123) #define FLASH_KEY2 ((uint32_t)0xCDEF89AB) #define FLASH_OPT_KEY1 ((uint32_t)0x08192A3B) #define FLASH_OPT_KEY2 ((uint32_t)0x4C5D6E7F) /** * @} */ /** * @} */ /* Exported macro ------------------------------------------------------------*/ /** @defgroup FLASH_Exported_Macros FLASH Exported Macros * @{ */ /** * @brief Set the FLASH Latency. * @param __LATENCY__: FLASH Latency * The value of this parameter depend on device used within the same series * @retval none */ #define __HAL_FLASH_SET_LATENCY(__LATENCY__) (*(__IO uint8_t *)ACR_BYTE0_ADDRESS = (uint8_t)(__LATENCY__)) /** * @brief Get the FLASH Latency. * @retval FLASH Latency * The value of this parameter depend on device used within the same series */ #define __HAL_FLASH_GET_LATENCY() (READ_BIT((FLASH->ACR), FLASH_ACR_LATENCY)) /** * @brief Enable the FLASH prefetch buffer. * @retval none */ #define __HAL_FLASH_PREFETCH_BUFFER_ENABLE() (FLASH->ACR |= FLASH_ACR_PRFTEN) /** * @brief Disable the FLASH prefetch buffer. * @retval none */ #define __HAL_FLASH_PREFETCH_BUFFER_DISABLE() (FLASH->ACR &= (~FLASH_ACR_PRFTEN)) /** * @brief Enable the FLASH instruction cache. * @retval none */ #define __HAL_FLASH_INSTRUCTION_CACHE_ENABLE() (FLASH->ACR |= FLASH_ACR_ICEN) /** * @brief Disable the FLASH instruction cache. * @retval none */ #define __HAL_FLASH_INSTRUCTION_CACHE_DISABLE() (FLASH->ACR &= (~FLASH_ACR_ICEN)) /** * @brief Enable the FLASH data cache. * @retval none */ #define __HAL_FLASH_DATA_CACHE_ENABLE() (FLASH->ACR |= FLASH_ACR_DCEN) /** * @brief Disable the FLASH data cache. * @retval none */ #define __HAL_FLASH_DATA_CACHE_DISABLE() (FLASH->ACR &= (~FLASH_ACR_DCEN)) /** * @brief Resets the FLASH instruction Cache. * @note This function must be used only when the Instruction Cache is disabled. * @retval None */ #define __HAL_FLASH_INSTRUCTION_CACHE_RESET() do {FLASH->ACR |= FLASH_ACR_ICRST; \ FLASH->ACR &= ~FLASH_ACR_ICRST; \ }while(0) /** * @brief Resets the FLASH data Cache. * @note This function must be used only when the data Cache is disabled. * @retval None */ #define __HAL_FLASH_DATA_CACHE_RESET() do {FLASH->ACR |= FLASH_ACR_DCRST; \ FLASH->ACR &= ~FLASH_ACR_DCRST; \ }while(0) /** * @brief Enable the specified FLASH interrupt. * @param __INTERRUPT__ : FLASH interrupt * This parameter can be any combination of the following values: * @arg FLASH_IT_EOP: End of FLASH Operation Interrupt * @arg FLASH_IT_ERR: Error Interrupt * @retval none */ #define __HAL_FLASH_ENABLE_IT(__INTERRUPT__) (FLASH->CR |= (__INTERRUPT__)) /** * @brief Disable the specified FLASH interrupt. * @param __INTERRUPT__ : FLASH interrupt * This parameter can be any combination of the following values: * @arg FLASH_IT_EOP: End of FLASH Operation Interrupt * @arg FLASH_IT_ERR: Error Interrupt * @retval none */ #define __HAL_FLASH_DISABLE_IT(__INTERRUPT__) (FLASH->CR &= ~(uint32_t)(__INTERRUPT__)) /** * @brief Get the specified FLASH flag status. * @param __FLAG__: specifies the FLASH flag to check. * This parameter can be one of the following values: * @arg FLASH_FLAG_EOP : FLASH End of Operation flag * @arg FLASH_FLAG_OPERR : FLASH operation Error flag * @arg FLASH_FLAG_WRPERR: FLASH Write protected error flag * @arg FLASH_FLAG_PGAERR: FLASH Programming Alignment error flag * @arg FLASH_FLAG_PGPERR: FLASH Programming Parallelism error flag * @arg FLASH_FLAG_PGSERR: FLASH Programming Sequence error flag * @arg FLASH_FLAG_RDERR : FLASH Read Protection error flag (PCROP) * @arg FLASH_FLAG_BSY : FLASH Busy flag * @retval The new state of __FLAG__ (SET or RESET). */ #define __HAL_FLASH_GET_FLAG(__FLAG__) ((FLASH->SR & (__FLAG__))) /** * @brief Clear the specified FLASH flag. * @param __FLAG__: specifies the FLASH flags to clear. * This parameter can be any combination of the following values: * @arg FLASH_FLAG_EOP : FLASH End of Operation flag * @arg FLASH_FLAG_OPERR : FLASH operation Error flag * @arg FLASH_FLAG_WRPERR: FLASH Write protected error flag * @arg FLASH_FLAG_PGAERR: FLASH Programming Alignment error flag * @arg FLASH_FLAG_PGPERR: FLASH Programming Parallelism error flag * @arg FLASH_FLAG_PGSERR: FLASH Programming Sequence error flag * @arg FLASH_FLAG_RDERR : FLASH Read Protection error flag (PCROP) * @retval none */ #define __HAL_FLASH_CLEAR_FLAG(__FLAG__) (FLASH->SR = (__FLAG__)) /** * @} */ /* Include FLASH HAL Extension module */ #include "stm32f4xx_hal_flash_ex.h" #include "stm32f4xx_hal_flash_ramfunc.h" /* Exported functions --------------------------------------------------------*/ /** @addtogroup FLASH_Exported_Functions * @{ */ /** @addtogroup FLASH_Exported_Functions_Group1 * @{ */ /* Program operation functions ***********************************************/ HAL_StatusTypeDef HAL_FLASH_Program(uint32_t TypeProgram, uint32_t Address, uint64_t Data); HAL_StatusTypeDef HAL_FLASH_Program_IT(uint32_t TypeProgram, uint32_t Address, uint64_t Data); /* FLASH IRQ handler method */ void HAL_FLASH_IRQHandler(void); /* Callbacks in non blocking modes */ void HAL_FLASH_EndOfOperationCallback(uint32_t ReturnValue); void HAL_FLASH_OperationErrorCallback(uint32_t ReturnValue); /** * @} */ /** @addtogroup FLASH_Exported_Functions_Group2 * @{ */ /* Peripheral Control functions **********************************************/ HAL_StatusTypeDef HAL_FLASH_Unlock(void); HAL_StatusTypeDef HAL_FLASH_Lock(void); HAL_StatusTypeDef HAL_FLASH_OB_Unlock(void); HAL_StatusTypeDef HAL_FLASH_OB_Lock(void); /* Option bytes control */ HAL_StatusTypeDef HAL_FLASH_OB_Launch(void); /** * @} */ /** @addtogroup FLASH_Exported_Functions_Group3 * @{ */ /* Peripheral State functions ************************************************/ uint32_t HAL_FLASH_GetError(void); HAL_StatusTypeDef FLASH_WaitForLastOperation(uint32_t Timeout); /** * @} */ /** * @} */ /* Private types -------------------------------------------------------------*/ /* Private variables ---------------------------------------------------------*/ /** @defgroup FLASH_Private_Variables FLASH Private Variables * @{ */ /** * @} */ /* Private constants ---------------------------------------------------------*/ /** @defgroup FLASH_Private_Constants FLASH Private Constants * @{ */ /** * @brief ACR register byte 0 (Bits[7:0]) base address */ #define ACR_BYTE0_ADDRESS ((uint32_t)0x40023C00) /** * @brief OPTCR register byte 0 (Bits[7:0]) base address */ #define OPTCR_BYTE0_ADDRESS ((uint32_t)0x40023C14) /** * @brief OPTCR register byte 1 (Bits[15:8]) base address */ #define OPTCR_BYTE1_ADDRESS ((uint32_t)0x40023C15) /** * @brief OPTCR register byte 2 (Bits[23:16]) base address */ #define OPTCR_BYTE2_ADDRESS ((uint32_t)0x40023C16) /** * @brief OPTCR register byte 3 (Bits[31:24]) base address */ #define OPTCR_BYTE3_ADDRESS ((uint32_t)0x40023C17) /** * @} */ /* Private macros ------------------------------------------------------------*/ /** @defgroup FLASH_Private_Macros FLASH Private Macros * @{ */ /** @defgroup FLASH_IS_FLASH_Definitions FLASH Private macros to check input parameters * @{ */ #define IS_FLASH_TYPEPROGRAM(VALUE)(((VALUE) == FLASH_TYPEPROGRAM_BYTE) || \ ((VALUE) == FLASH_TYPEPROGRAM_HALFWORD) || \ ((VALUE) == FLASH_TYPEPROGRAM_WORD) || \ ((VALUE) == FLASH_TYPEPROGRAM_DOUBLEWORD)) /** * @} */ /** * @} */ /* Private functions ---------------------------------------------------------*/ /** @defgroup FLASH_Private_Functions FLASH Private Functions * @{ */ /** * @} */ /** * @} */ /** * @} */ #ifdef __cplusplus } #endif #endif /* __STM32F4xx_HAL_FLASH_H */ /************************ (C) COPYRIGHT STMicroelectronics *****END OF FILE****/ ================================================ FILE: Zelig/mbed/TARGET_NUCLEO_F401RE/stm32f4xx_hal_flash_ex.h ================================================ /** ****************************************************************************** * @file stm32f4xx_hal_flash_ex.h * @author MCD Application Team * @version V1.4.1 * @date 09-October-2015 * @brief Header file of FLASH HAL Extension module. ****************************************************************************** * @attention * *

© COPYRIGHT(c) 2015 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. * ****************************************************************************** */ /* Define to prevent recursive inclusion -------------------------------------*/ #ifndef __STM32F4xx_HAL_FLASH_EX_H #define __STM32F4xx_HAL_FLASH_EX_H #ifdef __cplusplus extern "C" { #endif /* Includes ------------------------------------------------------------------*/ #include "stm32f4xx_hal_def.h" /** @addtogroup STM32F4xx_HAL_Driver * @{ */ /** @addtogroup FLASHEx * @{ */ /* Exported types ------------------------------------------------------------*/ /** @defgroup FLASHEx_Exported_Types FLASH Exported Types * @{ */ /** * @brief FLASH Erase structure definition */ typedef struct { uint32_t TypeErase; /*!< Mass erase or sector Erase. This parameter can be a value of @ref FLASHEx_Type_Erase */ uint32_t Banks; /*!< Select banks to erase when Mass erase is enabled. This parameter must be a value of @ref FLASHEx_Banks */ uint32_t Sector; /*!< Initial FLASH sector to erase when Mass erase is disabled This parameter must be a value of @ref FLASHEx_Sectors */ uint32_t NbSectors; /*!< Number of sectors to be erased. This parameter must be a value between 1 and (max number of sectors - value of Initial sector)*/ uint32_t VoltageRange;/*!< The device voltage range which defines the erase parallelism This parameter must be a value of @ref FLASHEx_Voltage_Range */ } FLASH_EraseInitTypeDef; /** * @brief FLASH Option Bytes Program structure definition */ typedef struct { uint32_t OptionType; /*!< Option byte to be configured. This parameter can be a value of @ref FLASHEx_Option_Type */ uint32_t WRPState; /*!< Write protection activation or deactivation. This parameter can be a value of @ref FLASHEx_WRP_State */ uint32_t WRPSector; /*!< Specifies the sector(s) to be write protected. The value of this parameter depend on device used within the same series */ uint32_t Banks; /*!< Select banks for WRP activation/deactivation of all sectors. This parameter must be a value of @ref FLASHEx_Banks */ uint32_t RDPLevel; /*!< Set the read protection level. This parameter can be a value of @ref FLASHEx_Option_Bytes_Read_Protection */ uint32_t BORLevel; /*!< Set the BOR Level. This parameter can be a value of @ref FLASHEx_BOR_Reset_Level */ uint8_t USERConfig; /*!< Program the FLASH User Option Byte: IWDG_SW / RST_STOP / RST_STDBY. */ } FLASH_OBProgramInitTypeDef; /** * @brief FLASH Advanced Option Bytes Program structure definition */ #if defined(STM32F427xx) || defined(STM32F437xx) || defined(STM32F429xx) || defined(STM32F439xx) ||\ defined(STM32F401xC) || defined(STM32F401xE) || defined(STM32F410Tx) || defined(STM32F410Cx) ||\ defined(STM32F410Rx) || defined(STM32F411xE) || defined(STM32F446xx) || defined(STM32F469xx) ||\ defined(STM32F479xx) typedef struct { uint32_t OptionType; /*!< Option byte to be configured for extension. This parameter can be a value of @ref FLASHEx_Advanced_Option_Type */ uint32_t PCROPState; /*!< PCROP activation or deactivation. This parameter can be a value of @ref FLASHEx_PCROP_State */ #if defined(STM32F401xC) || defined(STM32F401xE) || defined(STM32F410Tx) || defined(STM32F410Cx) || defined(STM32F410Rx) || defined(STM32F411xE) || defined(STM32F446xx) uint16_t Sectors; /*!< specifies the sector(s) set for PCROP. This parameter can be a value of @ref FLASHEx_Option_Bytes_PC_ReadWrite_Protection */ #endif /* STM32F401xC || STM32F401xE || STM32F410xx || STM32F411xE || STM32F446xx */ #if defined(STM32F427xx) || defined(STM32F437xx) || defined(STM32F429xx) || defined(STM32F439xx) || defined(STM32F469xx) || defined(STM32F479xx) uint32_t Banks; /*!< Select banks for PCROP activation/deactivation of all sectors. This parameter must be a value of @ref FLASHEx_Banks */ uint16_t SectorsBank1; /*!< Specifies the sector(s) set for PCROP for Bank1. This parameter can be a value of @ref FLASHEx_Option_Bytes_PC_ReadWrite_Protection */ uint16_t SectorsBank2; /*!< Specifies the sector(s) set for PCROP for Bank2. This parameter can be a value of @ref FLASHEx_Option_Bytes_PC_ReadWrite_Protection */ uint8_t BootConfig; /*!< Specifies Option bytes for boot config. This parameter can be a value of @ref FLASHEx_Dual_Boot */ #endif /*STM32F427xx || STM32F437xx || STM32F429xx || STM32F439xx || STM32F469xx || STM32F479xx */ } FLASH_AdvOBProgramInitTypeDef; #endif /* STM32F427xx || STM32F437xx || STM32F429xx || STM32F439xx || STM32F401xC || STM32F401xE || STM32F410xx || STM32F411xE || STM32F446xx || STM32F469xx || STM32F479xx */ /** * @} */ /* Exported constants --------------------------------------------------------*/ /** @defgroup FLASHEx_Exported_Constants FLASH Exported Constants * @{ */ /** @defgroup FLASHEx_Type_Erase FLASH Type Erase * @{ */ #define FLASH_TYPEERASE_SECTORS ((uint32_t)0x00) /*!< Sectors erase only */ #define FLASH_TYPEERASE_MASSERASE ((uint32_t)0x01) /*!< Flash Mass erase activation */ /** * @} */ /** @defgroup FLASHEx_Voltage_Range FLASH Voltage Range * @{ */ #define FLASH_VOLTAGE_RANGE_1 ((uint32_t)0x00) /*!< Device operating range: 1.8V to 2.1V */ #define FLASH_VOLTAGE_RANGE_2 ((uint32_t)0x01) /*!< Device operating range: 2.1V to 2.7V */ #define FLASH_VOLTAGE_RANGE_3 ((uint32_t)0x02) /*!< Device operating range: 2.7V to 3.6V */ #define FLASH_VOLTAGE_RANGE_4 ((uint32_t)0x03) /*!< Device operating range: 2.7V to 3.6V + External Vpp */ /** * @} */ /** @defgroup FLASHEx_WRP_State FLASH WRP State * @{ */ #define OB_WRPSTATE_DISABLE ((uint32_t)0x00) /*!< Disable the write protection of the desired bank 1 sectors */ #define OB_WRPSTATE_ENABLE ((uint32_t)0x01) /*!< Enable the write protection of the desired bank 1 sectors */ /** * @} */ /** @defgroup FLASHEx_Option_Type FLASH Option Type * @{ */ #define OPTIONBYTE_WRP ((uint32_t)0x01) /*!< WRP option byte configuration */ #define OPTIONBYTE_RDP ((uint32_t)0x02) /*!< RDP option byte configuration */ #define OPTIONBYTE_USER ((uint32_t)0x04) /*!< USER option byte configuration */ #define OPTIONBYTE_BOR ((uint32_t)0x08) /*!< BOR option byte configuration */ /** * @} */ /** @defgroup FLASHEx_Option_Bytes_Read_Protection FLASH Option Bytes Read Protection * @{ */ #define OB_RDP_LEVEL_0 ((uint8_t)0xAA) #define OB_RDP_LEVEL_1 ((uint8_t)0x55) #define OB_RDP_LEVEL_2 ((uint8_t)0xCC) /*!< Warning: When enabling read protection level 2 it s no more possible to go back to level 1 or 0 */ /** * @} */ /** @defgroup FLASHEx_Option_Bytes_IWatchdog FLASH Option Bytes IWatchdog * @{ */ #define OB_IWDG_SW ((uint8_t)0x20) /*!< Software IWDG selected */ #define OB_IWDG_HW ((uint8_t)0x00) /*!< Hardware IWDG selected */ /** * @} */ /** @defgroup FLASHEx_Option_Bytes_nRST_STOP FLASH Option Bytes nRST_STOP * @{ */ #define OB_STOP_NO_RST ((uint8_t)0x40) /*!< No reset generated when entering in STOP */ #define OB_STOP_RST ((uint8_t)0x00) /*!< Reset generated when entering in STOP */ /** * @} */ /** @defgroup FLASHEx_Option_Bytes_nRST_STDBY FLASH Option Bytes nRST_STDBY * @{ */ #define OB_STDBY_NO_RST ((uint8_t)0x80) /*!< No reset generated when entering in STANDBY */ #define OB_STDBY_RST ((uint8_t)0x00) /*!< Reset generated when entering in STANDBY */ /** * @} */ /** @defgroup FLASHEx_BOR_Reset_Level FLASH BOR Reset Level * @{ */ #define OB_BOR_LEVEL3 ((uint8_t)0x00) /*!< Supply voltage ranges from 2.70 to 3.60 V */ #define OB_BOR_LEVEL2 ((uint8_t)0x04) /*!< Supply voltage ranges from 2.40 to 2.70 V */ #define OB_BOR_LEVEL1 ((uint8_t)0x08) /*!< Supply voltage ranges from 2.10 to 2.40 V */ #define OB_BOR_OFF ((uint8_t)0x0C) /*!< Supply voltage ranges from 1.62 to 2.10 V */ /** * @} */ #if defined(STM32F427xx) || defined(STM32F437xx) || defined(STM32F429xx) || defined(STM32F439xx) ||\ defined(STM32F401xC) || defined(STM32F401xE) || defined(STM32F410Tx) || defined(STM32F410Cx) ||\ defined(STM32F410Rx) || defined(STM32F411xE) || defined(STM32F446xx) || defined(STM32F469xx) ||\ defined(STM32F479xx) /** @defgroup FLASHEx_PCROP_State FLASH PCROP State * @{ */ #define OB_PCROP_STATE_DISABLE ((uint32_t)0x00) /*!< Disable PCROP */ #define OB_PCROP_STATE_ENABLE ((uint32_t)0x01) /*!< Enable PCROP */ /** * @} */ #endif /* STM32F427xx || STM32F437xx || STM32F429xx || STM32F439xx || STM32F401xC || STM32F401xE ||\ STM32F410xx || STM32F411xE || STM32F446xx || STM32F469xx || STM32F479xx */ /** @defgroup FLASHEx_Advanced_Option_Type FLASH Advanced Option Type * @{ */ #if defined(STM32F427xx) || defined(STM32F437xx) || defined(STM32F429xx) || defined(STM32F439xx) ||\ defined(STM32F469xx) || defined(STM32F479xx) #define OPTIONBYTE_PCROP ((uint32_t)0x01) /*!< PCROP option byte configuration */ #define OPTIONBYTE_BOOTCONFIG ((uint32_t)0x02) /*!< BOOTConfig option byte configuration */ #endif /* STM32F427xx || STM32F437xx || STM32F429xx || STM32F439xx || STM32F469xx || STM32F479xx */ #if defined(STM32F401xC) || defined(STM32F401xE) || defined(STM32F410Tx) || defined(STM32F410Cx) ||\ defined(STM32F410Rx) || defined(STM32F411xE) || defined(STM32F446xx) #define OPTIONBYTE_PCROP ((uint32_t)0x01) /*!= FLASH_BASE) && ((ADDRESS) <= FLASH_END)) #define IS_FLASH_NBSECTORS(NBSECTORS) (((NBSECTORS) != 0) && ((NBSECTORS) <= FLASH_SECTOR_TOTAL)) #if defined(STM32F427xx) || defined(STM32F437xx) || defined(STM32F429xx) || defined(STM32F439xx) || defined(STM32F469xx) || defined(STM32F479xx) #define IS_OB_WRP_SECTOR(SECTOR)((((SECTOR) & (uint32_t)0xFF000000) == 0x00000000) && ((SECTOR) != 0x00000000)) #endif /* STM32F427xx || STM32F437xx || STM32F429xx || STM32F439xx || STM32F469xx || STM32F479xx */ #if defined(STM32F405xx) || defined(STM32F415xx) || defined(STM32F407xx) || defined(STM32F417xx) #define IS_OB_WRP_SECTOR(SECTOR)((((SECTOR) & (uint32_t)0xFFFFF000) == 0x00000000) && ((SECTOR) != 0x00000000)) #endif /* STM32F405xx || STM32F415xx || STM32F407xx || STM32F417xx */ #if defined(STM32F401xC) #define IS_OB_WRP_SECTOR(SECTOR)((((SECTOR) & (uint32_t)0xFFFFF000) == 0x00000000) && ((SECTOR) != 0x00000000)) #endif /* STM32F401xC */ #if defined(STM32F410Tx) || defined(STM32F410Cx) || defined(STM32F410Rx) #define IS_OB_WRP_SECTOR(SECTOR)((((SECTOR) & (uint32_t)0xFFFFF000) == 0x00000000) && ((SECTOR) != 0x00000000)) #endif /* STM32F410Tx || STM32F410Cx || STM32F410Rx */ #if defined(STM32F401xE) || defined(STM32F411xE) || defined(STM32F446xx) #define IS_OB_WRP_SECTOR(SECTOR)((((SECTOR) & (uint32_t)0xFFFFF000) == 0x00000000) && ((SECTOR) != 0x00000000)) #endif /* STM32F401xE || STM32F411xE || STM32F446xx */ #if defined(STM32F427xx) || defined(STM32F437xx) || defined(STM32F429xx) || defined(STM32F439xx) || defined(STM32F469xx) || defined(STM32F479xx) #define IS_OB_PCROP(SECTOR)((((SECTOR) & (uint32_t)0xFFFFF000) == 0x00000000) && ((SECTOR) != 0x00000000)) #endif /* STM32F427xx || STM32F437xx || STM32F429xx || STM32F439xx || STM32F469xx || STM32F479xx */ #if defined(STM32F401xC) #define IS_OB_PCROP(SECTOR)((((SECTOR) & (uint32_t)0xFFFFF000) == 0x00000000) && ((SECTOR) != 0x00000000)) #endif /* STM32F401xC */ #if defined(STM32F410Tx) || defined(STM32F410Cx) || defined(STM32F410Rx) #define IS_OB_PCROP(SECTOR)((((SECTOR) & (uint32_t)0xFFFFF000) == 0x00000000) && ((SECTOR) != 0x00000000)) #endif /* STM32F410Tx || STM32F410Cx || STM32F410Rx */ #if defined(STM32F401xE) || defined(STM32F411xE) || defined(STM32F446xx) #define IS_OB_PCROP(SECTOR)((((SECTOR) & (uint32_t)0xFFFFF000) == 0x00000000) && ((SECTOR) != 0x00000000)) #endif /* STM32F401xE || STM32F411xE || STM32F446xx */ #if defined(STM32F427xx) || defined(STM32F437xx) || defined(STM32F429xx) || defined(STM32F439xx) ||\ defined(STM32F469xx) || defined(STM32F479xx) #define IS_OB_BOOT(BOOT) (((BOOT) == OB_DUAL_BOOT_ENABLE) || ((BOOT) == OB_DUAL_BOOT_DISABLE)) #endif /* STM32F427xx || STM32F437xx || STM32F429xx || STM32F439xx || STM32F469xx || STM32F479xx */ #if defined(STM32F427xx) || defined(STM32F437xx) || defined(STM32F429xx) || defined(STM32F439xx) ||\ defined(STM32F401xC) || defined(STM32F401xE) || defined(STM32F410Tx) || defined(STM32F410Cx) ||\ defined(STM32F410Rx) || defined(STM32F411xE) || defined(STM32F446xx) || defined(STM32F469xx) ||\ defined(STM32F479xx) #define IS_OB_PCROP_SELECT(PCROP) (((PCROP) == OB_PCROP_SELECTED) || ((PCROP) == OB_PCROP_DESELECTED)) #endif /* STM32F427xx || STM32F437xx || STM32F429xx || STM32F439xx || STM32F401xC || STM32F401xE ||\ STM32F410xx || STM32F411xE || STM32F446xx || STM32F469xx || STM32F479xx */ /** * @} */ /** * @} */ /* Private functions ---------------------------------------------------------*/ /** @defgroup FLASHEx_Private_Functions FLASH Private Functions * @{ */ void FLASH_Erase_Sector(uint32_t Sector, uint8_t VoltageRange); /** * @} */ /** * @} */ /** * @} */ #ifdef __cplusplus } #endif #endif /* __STM32F4xx_HAL_FLASH_EX_H */ /************************ (C) COPYRIGHT STMicroelectronics *****END OF FILE****/ ================================================ FILE: Zelig/mbed/TARGET_NUCLEO_F401RE/stm32f4xx_hal_flash_ramfunc.h ================================================ /** ****************************************************************************** * @file stm32f4xx_hal_flash_ramfunc.h * @author MCD Application Team * @version V1.4.1 * @date 09-October-2015 * @brief Header file of FLASH RAMFUNC driver. ****************************************************************************** * @attention * *

© COPYRIGHT(c) 2015 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. * ****************************************************************************** */ /* Define to prevent recursive inclusion -------------------------------------*/ #ifndef __STM32F4xx_FLASH_RAMFUNC_H #define __STM32F4xx_FLASH_RAMFUNC_H #ifdef __cplusplus extern "C" { #endif #if defined(STM32F410Tx) || defined(STM32F410Cx) || defined(STM32F410Rx) || defined(STM32F411xE) || defined(STM32F446xx) /* Includes ------------------------------------------------------------------*/ #include "stm32f4xx_hal_def.h" /** @addtogroup STM32F4xx_HAL_Driver * @{ */ /** @addtogroup FLASHRAMFUNC * @{ */ /* Exported types ------------------------------------------------------------*/ /* Exported macro ------------------------------------------------------------*/ /* Exported functions --------------------------------------------------------*/ /** @addtogroup FLASHRAMFUNC_Exported_Functions * @{ */ /** @addtogroup FLASHRAMFUNC_Exported_Functions_Group1 * @{ */ __RAM_FUNC HAL_FLASHEx_StopFlashInterfaceClk(void); __RAM_FUNC HAL_FLASHEx_StartFlashInterfaceClk(void); __RAM_FUNC HAL_FLASHEx_EnableFlashSleepMode(void); __RAM_FUNC HAL_FLASHEx_DisableFlashSleepMode(void); /** * @} */ /** * @} */ /** * @} */ /** * @} */ #endif /* STM32F410xx || STM32F411xE || STM32F446xx */ #ifdef __cplusplus } #endif #endif /* __STM32F4xx_FLASH_RAMFUNC_H */ /************************ (C) COPYRIGHT STMicroelectronics *****END OF FILE****/ ================================================ FILE: Zelig/mbed/TARGET_NUCLEO_F401RE/stm32f4xx_hal_fmpi2c.h ================================================ /** ****************************************************************************** * @file stm32f4xx_hal_fmpi2c.h * @author MCD Application Team * @version V1.4.1 * @date 09-October-2015 * @brief Header file of FMPI2C HAL module. ****************************************************************************** * @attention * *

© COPYRIGHT(c) 2015 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. * ****************************************************************************** */ /* Define to prevent recursive inclusion -------------------------------------*/ #ifndef __STM32F4xx_HAL_FMPI2C_H #define __STM32F4xx_HAL_FMPI2C_H #ifdef __cplusplus extern "C" { #endif #if defined(STM32F410Tx) || defined(STM32F410Cx) || defined(STM32F410Rx) || defined(STM32F446xx) /* Includes ------------------------------------------------------------------*/ #include "stm32f4xx_hal_def.h" /** @addtogroup STM32F4xx_HAL_Driver * @{ */ /** @addtogroup FMPI2C * @{ */ /* Exported types ------------------------------------------------------------*/ /** @defgroup FMPI2C_Exported_Types FMPI2C Exported Types * @{ */ /** * @brief FMPI2C Configuration Structure definition */ typedef struct { uint32_t Timing; /*!< Specifies the FMPI2C_TIMINGR_register value. This parameter calculated by referring to FMPI2C initialization section in Reference manual */ uint32_t OwnAddress1; /*!< Specifies the first device own address. This parameter can be a 7-bit or 10-bit address. */ uint32_t AddressingMode; /*!< Specifies if 7-bit or 10-bit addressing mode is selected. This parameter can be a value of @ref FMPI2C_addressing_mode */ uint32_t DualAddressMode; /*!< Specifies if dual addressing mode is selected. This parameter can be a value of @ref FMPI2C_dual_addressing_mode */ uint32_t OwnAddress2; /*!< Specifies the second device own address if dual addressing mode is selected This parameter can be a 7-bit address. */ uint32_t OwnAddress2Masks; /*!< Specifies the acknoledge mask address second device own address if dual addressing mode is selected This parameter can be a value of @ref FMPI2C_own_address2_masks */ uint32_t GeneralCallMode; /*!< Specifies if general call mode is selected. This parameter can be a value of @ref FMPI2C_general_call_addressing_mode */ uint32_t NoStretchMode; /*!< Specifies if nostretch mode is selected. This parameter can be a value of @ref FMPI2C_nostretch_mode */ }FMPI2C_InitTypeDef; /** * @brief HAL State structures definition */ typedef enum { HAL_FMPI2C_STATE_RESET = 0x00, /*!< FMPI2C not yet initialized or disabled */ HAL_FMPI2C_STATE_READY = 0x01, /*!< FMPI2C initialized and ready for use */ HAL_FMPI2C_STATE_BUSY = 0x02, /*!< FMPI2C internal process is ongoing */ HAL_FMPI2C_STATE_MASTER_BUSY_TX = 0x12, /*!< Master Data Transmission process is ongoing */ HAL_FMPI2C_STATE_MASTER_BUSY_RX = 0x22, /*!< Master Data Reception process is ongoing */ HAL_FMPI2C_STATE_SLAVE_BUSY_TX = 0x32, /*!< Slave Data Transmission process is ongoing */ HAL_FMPI2C_STATE_SLAVE_BUSY_RX = 0x42, /*!< Slave Data Reception process is ongoing */ HAL_FMPI2C_STATE_MEM_BUSY_TX = 0x52, /*!< Memory Data Transmission process is ongoing */ HAL_FMPI2C_STATE_MEM_BUSY_RX = 0x62, /*!< Memory Data Reception process is ongoing */ HAL_FMPI2C_STATE_TIMEOUT = 0x03, /*!< Timeout state */ HAL_FMPI2C_STATE_ERROR = 0x04 /*!< Reception process is ongoing */ }HAL_FMPI2C_StateTypeDef; /** * @brief HAL FMPI2C Error Code structure definition */ typedef enum { HAL_FMPI2C_ERROR_NONE = 0x00, /*!< No error */ HAL_FMPI2C_ERROR_BERR = 0x01, /*!< BERR error */ HAL_FMPI2C_ERROR_ARLO = 0x02, /*!< ARLO error */ HAL_FMPI2C_ERROR_AF = 0x04, /*!< ACKF error */ HAL_FMPI2C_ERROR_OVR = 0x08, /*!< OVR error */ HAL_FMPI2C_ERROR_DMA = 0x10, /*!< DMA transfer error */ HAL_FMPI2C_ERROR_TIMEOUT = 0x20, /*!< Timeout error */ HAL_FMPI2C_ERROR_SIZE = 0x40 /*!< Size Management error */ }HAL_FMPI2C_ErrorTypeDef; /** * @brief FMPI2C handle Structure definition */ typedef struct { FMPI2C_TypeDef *Instance; /*!< FMPI2C registers base address */ FMPI2C_InitTypeDef Init; /*!< FMPI2C communication parameters */ uint8_t *pBuffPtr; /*!< Pointer to FMPI2C transfer buffer */ uint16_t XferSize; /*!< FMPI2C transfer size */ __IO uint16_t XferCount; /*!< FMPI2C transfer counter */ DMA_HandleTypeDef *hdmatx; /*!< FMPI2C Tx DMA handle parameters */ DMA_HandleTypeDef *hdmarx; /*!< FMPI2C Rx DMA handle parameters */ HAL_LockTypeDef Lock; /*!< FMPI2C locking object */ __IO HAL_FMPI2C_StateTypeDef State; /*!< FMPI2C communication state */ __IO HAL_FMPI2C_ErrorTypeDef ErrorCode; /* FMPI2C Error code */ }FMPI2C_HandleTypeDef; /** * @} */ /* Exported constants --------------------------------------------------------*/ /** @defgroup FMPI2C_Exported_Constants FMPI2C Exported Constants * @{ */ /** @defgroup FMPI2C_addressing_mode FMPI2C addressing mode * @{ */ #define FMPI2C_ADDRESSINGMODE_7BIT ((uint32_t)0x00000001) #define FMPI2C_ADDRESSINGMODE_10BIT ((uint32_t)0x00000002) /** * @} */ /** @defgroup FMPI2C_dual_addressing_mode FMPI2C dual addressing mode * @{ */ #define FMPI2C_DUALADDRESS_DISABLE ((uint32_t)0x00000000) #define FMPI2C_DUALADDRESS_ENABLE FMPI2C_OAR2_OA2EN /** * @} */ /** @defgroup FMPI2C_own_address2_masks FMPI2C own address2 masks * @{ */ #define FMPI2C_OA2_NOMASK ((uint8_t)0x00) #define FMPI2C_OA2_MASK01 ((uint8_t)0x01) #define FMPI2C_OA2_MASK02 ((uint8_t)0x02) #define FMPI2C_OA2_MASK03 ((uint8_t)0x03) #define FMPI2C_OA2_MASK04 ((uint8_t)0x04) #define FMPI2C_OA2_MASK05 ((uint8_t)0x05) #define FMPI2C_OA2_MASK06 ((uint8_t)0x06) #define FMPI2C_OA2_MASK07 ((uint8_t)0x07) /** * @} */ /** @defgroup FMPI2C_general_call_addressing_mode FMPI2C general call addressing mode * @{ */ #define FMPI2C_GENERALCALL_DISABLE ((uint32_t)0x00000000) #define FMPI2C_GENERALCALL_ENABLE FMPI2C_CR1_GCEN /** * @} */ /** @defgroup FMPI2C_nostretch_mode FMPI2C nostretch mode * @{ */ #define FMPI2C_NOSTRETCH_DISABLE ((uint32_t)0x00000000) #define FMPI2C_NOSTRETCH_ENABLE FMPI2C_CR1_NOSTRETCH /** * @} */ /** @defgroup FMPI2C_Memory_Address_Size FMPI2C Memory Address Size * @{ */ #define FMPI2C_MEMADD_SIZE_8BIT ((uint32_t)0x00000001) #define FMPI2C_MEMADD_SIZE_16BIT ((uint32_t)0x00000002) /** * @} */ /** @defgroup FMPI2C_ReloadEndMode_definition FMPI2C ReloadEndMode definition * @{ */ #define FMPI2C_RELOAD_MODE FMPI2C_CR2_RELOAD #define FMPI2C_AUTOEND_MODE FMPI2C_CR2_AUTOEND #define FMPI2C_SOFTEND_MODE ((uint32_t)0x00000000) /** * @} */ /** @defgroup FMPI2C_StartStopMode_definition FMPI2C StartStopMode definition * @{ */ #define FMPI2C_NO_STARTSTOP ((uint32_t)0x00000000) #define FMPI2C_GENERATE_STOP FMPI2C_CR2_STOP #define FMPI2C_GENERATE_START_READ (uint32_t)(FMPI2C_CR2_START | FMPI2C_CR2_RD_WRN) #define FMPI2C_GENERATE_START_WRITE FMPI2C_CR2_START /** * @} */ /** @defgroup FMPI2C_Interrupt_configuration_definition FMPI2C Interrupt configuration definition * @brief FMPI2C Interrupt definition * Elements values convention: 0xXXXXXXXX * - XXXXXXXX : Interrupt control mask * @{ */ #define FMPI2C_IT_ERRI FMPI2C_CR1_ERRIE #define FMPI2C_IT_TCI FMPI2C_CR1_TCIE #define FMPI2C_IT_STOPI FMPI2C_CR1_STOPIE #define FMPI2C_IT_NACKI FMPI2C_CR1_NACKIE #define FMPI2C_IT_ADDRI FMPI2C_CR1_ADDRIE #define FMPI2C_IT_RXI FMPI2C_CR1_RXIE #define FMPI2C_IT_TXI FMPI2C_CR1_TXIE /** * @} */ /** @defgroup FMPI2C_Flag_definition FMPI2C Flag definition * @{ */ #define FMPI2C_FLAG_TXE FMPI2C_ISR_TXE #define FMPI2C_FLAG_TXIS FMPI2C_ISR_TXIS #define FMPI2C_FLAG_RXNE FMPI2C_ISR_RXNE #define FMPI2C_FLAG_ADDR FMPI2C_ISR_ADDR #define FMPI2C_FLAG_AF FMPI2C_ISR_NACKF #define FMPI2C_FLAG_STOPF FMPI2C_ISR_STOPF #define FMPI2C_FLAG_TC FMPI2C_ISR_TC #define FMPI2C_FLAG_TCR FMPI2C_ISR_TCR #define FMPI2C_FLAG_BERR FMPI2C_ISR_BERR #define FMPI2C_FLAG_ARLO FMPI2C_ISR_ARLO #define FMPI2C_FLAG_OVR FMPI2C_ISR_OVR #define FMPI2C_FLAG_PECERR FMPI2C_ISR_PECERR #define FMPI2C_FLAG_TIMEOUT FMPI2C_ISR_TIMEOUT #define FMPI2C_FLAG_ALERT FMPI2C_ISR_ALERT #define FMPI2C_FLAG_BUSY FMPI2C_ISR_BUSY #define FMPI2C_FLAG_DIR FMPI2C_ISR_DIR /** * @} */ /** * @} */ /* Exported macro ------------------------------------------------------------*/ /** @defgroup FMPI2C_Exported_Macros FMPI2C Exported Macros * @{ */ /** @brief Reset FMPI2C handle state * @param __HANDLE__: specifies the FMPI2C Handle. * This parameter can be FMPI2C where x: 1 or 2 to select the FMPI2C peripheral. * @retval None */ #define __HAL_FMPI2C_RESET_HANDLE_STATE(__HANDLE__) ((__HANDLE__)->State = HAL_FMPI2C_STATE_RESET) /** @brief Enables or disables the specified FMPI2C interrupts. * @param __HANDLE__: specifies the FMPI2C Handle. * This parameter can be FMPI2C where x: 1 or 2 to select the FMPI2C peripheral. * @param __INTERRUPT__: specifies the interrupt source to enable or disable. * This parameter can be one of the following values: * @arg FMPI2C_IT_ERRI: Errors interrupt enable * @arg FMPI2C_IT_TCI: Transfer complete interrupt enable * @arg FMPI2C_IT_STOPI: STOP detection interrupt enable * @arg FMPI2C_IT_NACKI: NACK received interrupt enable * @arg FMPI2C_IT_ADDRI: Address match interrupt enable * @arg FMPI2C_IT_RXI: RX interrupt enable * @arg FMPI2C_IT_TXI: TX interrupt enable * * @retval None */ #define __HAL_FMPI2C_ENABLE_IT(__HANDLE__, __INTERRUPT__) ((__HANDLE__)->Instance->CR1 |= (__INTERRUPT__)) #define __HAL_FMPI2C_DISABLE_IT(__HANDLE__, __INTERRUPT__) ((__HANDLE__)->Instance->CR1 &= (~(__INTERRUPT__))) /** @brief Checks if the specified FMPI2C interrupt source is enabled or disabled. * @param __HANDLE__: specifies the FMPI2C Handle. * This parameter can be FMPI2C where x: 1 or 2 to select the FMPI2C peripheral. * @param __INTERRUPT__: specifies the FMPI2C interrupt source to check. * This parameter can be one of the following values: * @arg FMPI2C_IT_ERRI: Errors interrupt enable * @arg FMPI2C_IT_TCI: Transfer complete interrupt enable * @arg FMPI2C_IT_STOPI: STOP detection interrupt enable * @arg FMPI2C_IT_NACKI: NACK received interrupt enable * @arg FMPI2C_IT_ADDRI: Address match interrupt enable * @arg FMPI2C_IT_RXI: RX interrupt enable * @arg FMPI2C_IT_TXI: TX interrupt enable * * @retval The new state of __IT__ (TRUE or FALSE). */ #define __HAL_FMPI2C_GET_IT_SOURCE(__HANDLE__, __INTERRUPT__) ((((__HANDLE__)->Instance->CR1 & (__INTERRUPT__)) == (__INTERRUPT__)) ? SET : RESET) /** @brief Checks whether the specified FMPI2C flag is set or not. * @param __HANDLE__: specifies the FMPI2C Handle. * This parameter can be FMPI2C where x: 1 or 2 to select the FMPI2C peripheral. * @param __FLAG__: specifies the flag to check. * This parameter can be one of the following values: * @arg FMPI2C_FLAG_TXE: Transmit data register empty * @arg FMPI2C_FLAG_TXIS: Transmit interrupt status * @arg FMPI2C_FLAG_RXNE: Receive data register not empty * @arg FMPI2C_FLAG_ADDR: Address matched (slave mode) * @arg FMPI2C_FLAG_AF: Acknowledge failure received flag * @arg FMPI2C_FLAG_STOPF: STOP detection flag * @arg FMPI2C_FLAG_TC: Transfer complete (master mode) * @arg FMPI2C_FLAG_TCR: Transfer complete reload * @arg FMPI2C_FLAG_BERR: Bus error * @arg FMPI2C_FLAG_ARLO: Arbitration lost * @arg FMPI2C_FLAG_OVR: Overrun/Underrun * @arg FMPI2C_FLAG_PECERR: PEC error in reception * @arg FMPI2C_FLAG_TIMEOUT: Timeout or Tlow detection flag * @arg FMPI2C_FLAG_ALERT: SMBus alert * @arg FMPI2C_FLAG_BUSY: Bus busy * @arg FMPI2C_FLAG_DIR: Transfer direction (slave mode) * * @retval The new state of __FLAG__ (TRUE or FALSE). */ #define __HAL_FMPI2C_GET_FLAG(__HANDLE__, __FLAG__) (((((__HANDLE__)->Instance->ISR) & ((__FLAG__) & FMPI2C_FLAG_MASK)) == ((__FLAG__) & FMPI2C_FLAG_MASK))) /** @brief Clears the FMPI2C pending flags which are cleared by writing 1 in a specific bit. * @param __HANDLE__: specifies the FMPI2C Handle. * This parameter can be FMPI2C where x: 1 or 2 to select the FMPI2C peripheral. * @param __FLAG__: specifies the flag to clear. * This parameter can be any combination of the following values: * @arg FMPI2C_FLAG_ADDR: Address matched (slave mode) * @arg FMPI2C_FLAG_AF: Acknowledge failure received flag * @arg FMPI2C_FLAG_STOPF: STOP detection flag * @arg FMPI2C_FLAG_BERR: Bus error * @arg FMPI2C_FLAG_ARLO: Arbitration lost * @arg FMPI2C_FLAG_OVR: Overrun/Underrun * @arg FMPI2C_FLAG_PECERR: PEC error in reception * @arg FMPI2C_FLAG_TIMEOUT: Timeout or Tlow detection flag * @arg FMPI2C_FLAG_ALERT: SMBus alert * * @retval None */ #define __HAL_FMPI2C_CLEAR_FLAG(__HANDLE__, __FLAG__) ((__HANDLE__)->Instance->ICR = ((__FLAG__) & FMPI2C_FLAG_MASK)) #define __HAL_FMPI2C_ENABLE(__HANDLE__) ((__HANDLE__)->Instance->CR1 |= FMPI2C_CR1_PE) #define __HAL_FMPI2C_DISABLE(__HANDLE__) ((__HANDLE__)->Instance->CR1 &= ~FMPI2C_CR1_PE) #define __HAL_FMPI2C_RESET_CR2(__HANDLE__) ((__HANDLE__)->Instance->CR2 &= (uint32_t)~((uint32_t)(FMPI2C_CR2_SADD | FMPI2C_CR2_HEAD10R | FMPI2C_CR2_NBYTES | FMPI2C_CR2_RELOAD | FMPI2C_CR2_RD_WRN))) #define __HAL_FMPI2C_MEM_ADD_MSB(__ADDRESS__) ((uint8_t)((uint16_t)(((uint16_t)((__ADDRESS__) & (uint16_t)(0xFF00))) >> 8))) #define __HAL_FMPI2C_MEM_ADD_LSB(__ADDRESS__) ((uint8_t)((uint16_t)((__ADDRESS__) & (uint16_t)(0x00FF)))) #define __HAL_FMPI2C_GENERATE_START(__ADDMODE__,__ADDRESS__) (((__ADDMODE__) == FMPI2C_ADDRESSINGMODE_7BIT) ? (uint32_t)((((uint32_t)(__ADDRESS__) & (FMPI2C_CR2_SADD)) | (FMPI2C_CR2_START) | (FMPI2C_CR2_AUTOEND)) & (~FMPI2C_CR2_RD_WRN)) : \ (uint32_t)((((uint32_t)(__ADDRESS__) & (FMPI2C_CR2_SADD)) | (FMPI2C_CR2_ADD10) | (FMPI2C_CR2_START)) & (~FMPI2C_CR2_RD_WRN))) #define IS_FMPI2C_OWN_ADDRESS1(ADDRESS1) ((ADDRESS1) <= (uint32_t)0x000003FF) #define IS_FMPI2C_OWN_ADDRESS2(ADDRESS2) ((ADDRESS2) <= (uint16_t)0x00FF) /** * @} */ /* Include FMPI2C HAL Extension module */ #include "stm32f4xx_hal_fmpi2c_ex.h" /* Exported functions --------------------------------------------------------*/ /** @addtogroup FMPI2C_Exported_Functions * @{ */ /** @addtogroup FMPI2C_Exported_Functions_Group1 * @{ */ /* Initialization/de-initialization functions**********************************/ HAL_StatusTypeDef HAL_FMPI2C_Init(FMPI2C_HandleTypeDef *hFMPI2C); HAL_StatusTypeDef HAL_FMPI2C_DeInit (FMPI2C_HandleTypeDef *hFMPI2C); void HAL_FMPI2C_MspInit(FMPI2C_HandleTypeDef *hFMPI2C); void HAL_FMPI2C_MspDeInit(FMPI2C_HandleTypeDef *hFMPI2C); /** * @} */ /** @addtogroup FMPI2C_Exported_Functions_Group2 * @{ */ /* I/O operation functions ***************************************************/ /******* Blocking mode: Polling */ HAL_StatusTypeDef HAL_FMPI2C_Master_Transmit(FMPI2C_HandleTypeDef *hFMPI2C, uint16_t DevAddress, uint8_t *pData, uint16_t Size, uint32_t Timeout); HAL_StatusTypeDef HAL_FMPI2C_Master_Receive(FMPI2C_HandleTypeDef *hFMPI2C, uint16_t DevAddress, uint8_t *pData, uint16_t Size, uint32_t Timeout); HAL_StatusTypeDef HAL_FMPI2C_Slave_Transmit(FMPI2C_HandleTypeDef *hFMPI2C, uint8_t *pData, uint16_t Size, uint32_t Timeout); HAL_StatusTypeDef HAL_FMPI2C_Slave_Receive(FMPI2C_HandleTypeDef *hFMPI2C, uint8_t *pData, uint16_t Size, uint32_t Timeout); HAL_StatusTypeDef HAL_FMPI2C_Mem_Write(FMPI2C_HandleTypeDef *hFMPI2C, uint16_t DevAddress, uint16_t MemAddress, uint16_t MemAddSize, uint8_t *pData, uint16_t Size, uint32_t Timeout); HAL_StatusTypeDef HAL_FMPI2C_Mem_Read(FMPI2C_HandleTypeDef *hFMPI2C, uint16_t DevAddress, uint16_t MemAddress, uint16_t MemAddSize, uint8_t *pData, uint16_t Size, uint32_t Timeout); HAL_StatusTypeDef HAL_FMPI2C_IsDeviceReady(FMPI2C_HandleTypeDef *hFMPI2C, uint16_t DevAddress, uint32_t Trials, uint32_t Timeout); /******* Non-Blocking mode: Interrupt */ HAL_StatusTypeDef HAL_FMPI2C_Master_Transmit_IT(FMPI2C_HandleTypeDef *hFMPI2C, uint16_t DevAddress, uint8_t *pData, uint16_t Size); HAL_StatusTypeDef HAL_FMPI2C_Master_Receive_IT(FMPI2C_HandleTypeDef *hFMPI2C, uint16_t DevAddress, uint8_t *pData, uint16_t Size); HAL_StatusTypeDef HAL_FMPI2C_Slave_Transmit_IT(FMPI2C_HandleTypeDef *hFMPI2C, uint8_t *pData, uint16_t Size); HAL_StatusTypeDef HAL_FMPI2C_Slave_Receive_IT(FMPI2C_HandleTypeDef *hFMPI2C, uint8_t *pData, uint16_t Size); HAL_StatusTypeDef HAL_FMPI2C_Mem_Write_IT(FMPI2C_HandleTypeDef *hFMPI2C, uint16_t DevAddress, uint16_t MemAddress, uint16_t MemAddSize, uint8_t *pData, uint16_t Size); HAL_StatusTypeDef HAL_FMPI2C_Mem_Read_IT(FMPI2C_HandleTypeDef *hFMPI2C, uint16_t DevAddress, uint16_t MemAddress, uint16_t MemAddSize, uint8_t *pData, uint16_t Size); /******* Non-Blocking mode: DMA */ HAL_StatusTypeDef HAL_FMPI2C_Master_Transmit_DMA(FMPI2C_HandleTypeDef *hFMPI2C, uint16_t DevAddress, uint8_t *pData, uint16_t Size); HAL_StatusTypeDef HAL_FMPI2C_Master_Receive_DMA(FMPI2C_HandleTypeDef *hFMPI2C, uint16_t DevAddress, uint8_t *pData, uint16_t Size); HAL_StatusTypeDef HAL_FMPI2C_Slave_Transmit_DMA(FMPI2C_HandleTypeDef *hFMPI2C, uint8_t *pData, uint16_t Size); HAL_StatusTypeDef HAL_FMPI2C_Slave_Receive_DMA(FMPI2C_HandleTypeDef *hFMPI2C, uint8_t *pData, uint16_t Size); HAL_StatusTypeDef HAL_FMPI2C_Mem_Write_DMA(FMPI2C_HandleTypeDef *hFMPI2C, uint16_t DevAddress, uint16_t MemAddress, uint16_t MemAddSize, uint8_t *pData, uint16_t Size); HAL_StatusTypeDef HAL_FMPI2C_Mem_Read_DMA(FMPI2C_HandleTypeDef *hFMPI2C, uint16_t DevAddress, uint16_t MemAddress, uint16_t MemAddSize, uint8_t *pData, uint16_t Size); /******* FMPI2C IRQHandler and Callbacks used in non blocking modes (Interrupt and DMA) */ void HAL_FMPI2C_EV_IRQHandler(FMPI2C_HandleTypeDef *hFMPI2C); void HAL_FMPI2C_ER_IRQHandler(FMPI2C_HandleTypeDef *hFMPI2C); void HAL_FMPI2C_MasterTxCpltCallback(FMPI2C_HandleTypeDef *hFMPI2C); void HAL_FMPI2C_MasterRxCpltCallback(FMPI2C_HandleTypeDef *hFMPI2C); void HAL_FMPI2C_SlaveTxCpltCallback(FMPI2C_HandleTypeDef *hFMPI2C); void HAL_FMPI2C_SlaveRxCpltCallback(FMPI2C_HandleTypeDef *hFMPI2C); void HAL_FMPI2C_MemTxCpltCallback(FMPI2C_HandleTypeDef *hFMPI2C); void HAL_FMPI2C_MemRxCpltCallback(FMPI2C_HandleTypeDef *hFMPI2C); void HAL_FMPI2C_ErrorCallback(FMPI2C_HandleTypeDef *hFMPI2C); /** * @} */ /** @addtogroup FMPI2C_Exported_Functions_Group3 * @{ */ /* Peripheral State functions ************************************************/ HAL_FMPI2C_StateTypeDef HAL_FMPI2C_GetState(FMPI2C_HandleTypeDef *hFMPI2C); uint32_t HAL_FMPI2C_GetError(FMPI2C_HandleTypeDef *hFMPI2C); /** * @} */ /** * @} */ /* Private types -------------------------------------------------------------*/ /* Private variables ---------------------------------------------------------*/ /* Private constants ---------------------------------------------------------*/ /** @defgroup FMPI2C_Private_Constants FMPI2C Private Constants * @{ */ #define FMPI2C_FLAG_MASK ((uint32_t)0x0001FFFF) /** * @} */ /* Private macros ------------------------------------------------------------*/ /** @defgroup FMPI2C_Private_Macros FMPI2C Private Macros * @{ */ #define IS_FMPI2C_ADDRESSING_MODE(MODE) (((MODE) == FMPI2C_ADDRESSINGMODE_7BIT) || \ ((MODE) == FMPI2C_ADDRESSINGMODE_10BIT)) #define IS_FMPI2C_DUAL_ADDRESS(ADDRESS) (((ADDRESS) == FMPI2C_DUALADDRESS_DISABLE) || \ ((ADDRESS) == FMPI2C_DUALADDRESS_ENABLE)) #define IS_FMPI2C_OWN_ADDRESS2_MASK(MASK) (((MASK) == FMPI2C_OA2_NOMASK) || \ ((MASK) == FMPI2C_OA2_MASK01) || \ ((MASK) == FMPI2C_OA2_MASK02) || \ ((MASK) == FMPI2C_OA2_MASK03) || \ ((MASK) == FMPI2C_OA2_MASK04) || \ ((MASK) == FMPI2C_OA2_MASK05) || \ ((MASK) == FMPI2C_OA2_MASK06) || \ ((MASK) == FMPI2C_OA2_MASK07)) #define IS_FMPI2C_GENERAL_CALL(CALL) (((CALL) == FMPI2C_GENERALCALL_DISABLE) || \ ((CALL) == FMPI2C_GENERALCALL_ENABLE)) #define IS_FMPI2C_NO_STRETCH(STRETCH) (((STRETCH) == FMPI2C_NOSTRETCH_DISABLE) || \ ((STRETCH) == FMPI2C_NOSTRETCH_ENABLE)) #define IS_FMPI2C_MEMADD_SIZE(SIZE) (((SIZE) == FMPI2C_MEMADD_SIZE_8BIT) || \ ((SIZE) == FMPI2C_MEMADD_SIZE_16BIT)) #define IS_TRANSFER_MODE(MODE) (((MODE) == FMPI2C_RELOAD_MODE) || \ ((MODE) == FMPI2C_AUTOEND_MODE) || \ ((MODE) == FMPI2C_SOFTEND_MODE)) #define IS_TRANSFER_REQUEST(REQUEST) (((REQUEST) == FMPI2C_GENERATE_STOP) || \ ((REQUEST) == FMPI2C_GENERATE_START_READ) || \ ((REQUEST) == FMPI2C_GENERATE_START_WRITE) || \ ((REQUEST) == FMPI2C_NO_STARTSTOP)) /** * @} */ /* Private functions ---------------------------------------------------------*/ /** @defgroup FMPI2C_Private_Functions FMPI2C Private Functions * @brief FMPI2C private functions * @{ */ /** * @} */ /** * @} */ /** * @} */ #endif /* STM32F410xx || STM32F446xx */ #ifdef __cplusplus } #endif #endif /* __STM32F4xx_HAL_FMPI2C_H */ /************************ (C) COPYRIGHT STMicroelectronics *****END OF FILE****/ ================================================ FILE: Zelig/mbed/TARGET_NUCLEO_F401RE/stm32f4xx_hal_fmpi2c_ex.h ================================================ /** ****************************************************************************** * @file stm32f4xx_hal_fmpi2c_ex.h * @author MCD Application Team * @version V1.4.1 * @date 09-October-2015 * @brief Header file of FMPI2C HAL Extension module. ****************************************************************************** * @attention * *

© COPYRIGHT(c) 2015 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. * ****************************************************************************** */ /* Define to prevent recursive inclusion -------------------------------------*/ #ifndef __STM32F4xx_HAL_FMPI2C_EX_H #define __STM32F4xx_HAL_FMPI2C_EX_H #ifdef __cplusplus extern "C" { #endif #if defined(STM32F410Tx) || defined(STM32F410Cx) || defined(STM32F410Rx) || defined(STM32F446xx) /* Includes ------------------------------------------------------------------*/ #include "stm32f4xx_hal_def.h" /** @addtogroup STM32F4xx_HAL_Driver * @{ */ /** @addtogroup FMPI2CEx * @{ */ /* Exported types ------------------------------------------------------------*/ /* Exported constants --------------------------------------------------------*/ /** @defgroup FMPI2CEx_Exported_Constants FMPI2C Exported Constants * @{ */ /** @defgroup FMPI2CEx_Analog_Filter FMPI2C Analog Filter * @{ */ #define FMPI2C_ANALOGFILTER_ENABLE ((uint32_t)0x00000000) #define FMPI2C_ANALOGFILTER_DISABLE FMPI2C_CR1_ANFOFF /** * @} */ /** @defgroup FMPI2CEx_FastModePlus FMPI2C Fast Mode Plus * @{ */ #define FMPI2C_FASTMODEPLUS_SCL SYSCFG_CFGR_FMPI2C1_SCL /*!< Enable Fast Mode Plus on FMPI2C1 SCL pins */ #define FMPI2C_FASTMODEPLUS_SDA SYSCFG_CFGR_FMPI2C1_SDA /*!< Enable Fast Mode Plus on FMPI2C1 SDA pins */ /** * @} */ /** * @} */ /* Exported macro ------------------------------------------------------------*/ /* Exported functions --------------------------------------------------------*/ /** @addtogroup FMPI2CEx_Exported_Functions * @{ */ /** @addtogroup FMPI2CEx_Exported_Functions_Group1 * @{ */ /* Peripheral Control functions ************************************************/ HAL_StatusTypeDef HAL_FMPI2CEx_AnalogFilter_Config(FMPI2C_HandleTypeDef *hFMPI2C, uint32_t AnalogFilter); HAL_StatusTypeDef HAL_FMPI2CEx_DigitalFilter_Config(FMPI2C_HandleTypeDef *hFMPI2C, uint32_t DigitalFilter); HAL_StatusTypeDef HAL_FMPI2CEx_EnableWakeUp (FMPI2C_HandleTypeDef *hFMPI2C); HAL_StatusTypeDef HAL_FMPI2CEx_DisableWakeUp (FMPI2C_HandleTypeDef *hFMPI2C); void HAL_FMPI2CEx_EnableFastModePlus(uint32_t ConfigFastModePlus); void HAL_FMPI2CEx_DisableFastModePlus(uint32_t ConfigFastModePlus); /** * @} */ /** * @} */ /* Private types -------------------------------------------------------------*/ /* Private variables ---------------------------------------------------------*/ /* Private constants ---------------------------------------------------------*/ /** @defgroup I2CEx_Private_Constants I2C Private Constants * @{ */ /** * @} */ /* Private macros ------------------------------------------------------------*/ /** @defgroup I2CEx_Private_Macros I2C Private Macros * @{ */ #define IS_FMPI2C_ANALOG_FILTER(FILTER) (((FILTER) == FMPI2C_ANALOGFILTER_ENABLE) || \ ((FILTER) == FMPI2C_ANALOGFILTER_DISABLE)) #define IS_FMPI2C_DIGITAL_FILTER(FILTER) ((FILTER) <= 0x0000000F) #define IS_FMPI2C_FASTMODEPLUS(__CONFIG__) ((((__CONFIG__) & (FMPI2C_FASTMODEPLUS_SCL)) == FMPI2C_FASTMODEPLUS_SCL) || \ (((__CONFIG__) & (FMPI2C_FASTMODEPLUS_SDA)) == FMPI2C_FASTMODEPLUS_SDA)) /** * @} */ /** * @} */ /** * @} */ #endif /* STM32F410xx || STM32F446xx */ #ifdef __cplusplus } #endif #endif /* __STM32F4xx_HAL_FMPI2C_EX_H */ /************************ (C) COPYRIGHT STMicroelectronics *****END OF FILE****/ ================================================ FILE: Zelig/mbed/TARGET_NUCLEO_F401RE/stm32f4xx_hal_gpio.h ================================================ /** ****************************************************************************** * @file stm32f4xx_hal_gpio.h * @author MCD Application Team * @version V1.4.1 * @date 09-October-2015 * @brief Header file of GPIO HAL module. ****************************************************************************** * @attention * *

© COPYRIGHT(c) 2015 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. * ****************************************************************************** */ /* Define to prevent recursive inclusion -------------------------------------*/ #ifndef __STM32F4xx_HAL_GPIO_H #define __STM32F4xx_HAL_GPIO_H #ifdef __cplusplus extern "C" { #endif /* Includes ------------------------------------------------------------------*/ #include "stm32f4xx_hal_def.h" /** @addtogroup STM32F4xx_HAL_Driver * @{ */ /** @addtogroup GPIO * @{ */ /* Exported types ------------------------------------------------------------*/ /** @defgroup GPIO_Exported_Types GPIO Exported Types * @{ */ /** * @brief GPIO Init structure definition */ typedef struct { uint32_t Pin; /*!< Specifies the GPIO pins to be configured. This parameter can be any value of @ref GPIO_pins_define */ uint32_t Mode; /*!< Specifies the operating mode for the selected pins. This parameter can be a value of @ref GPIO_mode_define */ uint32_t Pull; /*!< Specifies the Pull-up or Pull-Down activation for the selected pins. This parameter can be a value of @ref GPIO_pull_define */ uint32_t Speed; /*!< Specifies the speed for the selected pins. This parameter can be a value of @ref GPIO_speed_define */ uint32_t Alternate; /*!< Peripheral to be connected to the selected pins. This parameter can be a value of @ref GPIO_Alternate_function_selection */ }GPIO_InitTypeDef; /** * @brief GPIO Bit SET and Bit RESET enumeration */ typedef enum { GPIO_PIN_RESET = 0, GPIO_PIN_SET }GPIO_PinState; /** * @} */ /* Exported constants --------------------------------------------------------*/ /** @defgroup GPIO_Exported_Constants GPIO Exported Constants * @{ */ /** @defgroup GPIO_pins_define GPIO pins define * @{ */ #define GPIO_PIN_0 ((uint16_t)0x0001) /* Pin 0 selected */ #define GPIO_PIN_1 ((uint16_t)0x0002) /* Pin 1 selected */ #define GPIO_PIN_2 ((uint16_t)0x0004) /* Pin 2 selected */ #define GPIO_PIN_3 ((uint16_t)0x0008) /* Pin 3 selected */ #define GPIO_PIN_4 ((uint16_t)0x0010) /* Pin 4 selected */ #define GPIO_PIN_5 ((uint16_t)0x0020) /* Pin 5 selected */ #define GPIO_PIN_6 ((uint16_t)0x0040) /* Pin 6 selected */ #define GPIO_PIN_7 ((uint16_t)0x0080) /* Pin 7 selected */ #define GPIO_PIN_8 ((uint16_t)0x0100) /* Pin 8 selected */ #define GPIO_PIN_9 ((uint16_t)0x0200) /* Pin 9 selected */ #define GPIO_PIN_10 ((uint16_t)0x0400) /* Pin 10 selected */ #define GPIO_PIN_11 ((uint16_t)0x0800) /* Pin 11 selected */ #define GPIO_PIN_12 ((uint16_t)0x1000) /* Pin 12 selected */ #define GPIO_PIN_13 ((uint16_t)0x2000) /* Pin 13 selected */ #define GPIO_PIN_14 ((uint16_t)0x4000) /* Pin 14 selected */ #define GPIO_PIN_15 ((uint16_t)0x8000) /* Pin 15 selected */ #define GPIO_PIN_All ((uint16_t)0xFFFF) /* All pins selected */ #define GPIO_PIN_MASK ((uint32_t)0x0000FFFF) /* PIN mask for assert test */ /** * @} */ /** @defgroup GPIO_mode_define GPIO mode define * @brief GPIO Configuration Mode * Elements values convention: 0xX0yz00YZ * - X : GPIO mode or EXTI Mode * - y : External IT or Event trigger detection * - z : IO configuration on External IT or Event * - Y : Output type (Push Pull or Open Drain) * - Z : IO Direction mode (Input, Output, Alternate or Analog) * @{ */ #define GPIO_MODE_INPUT ((uint32_t)0x00000000) /*!< Input Floating Mode */ #define GPIO_MODE_OUTPUT_PP ((uint32_t)0x00000001) /*!< Output Push Pull Mode */ #define GPIO_MODE_OUTPUT_OD ((uint32_t)0x00000011) /*!< Output Open Drain Mode */ #define GPIO_MODE_AF_PP ((uint32_t)0x00000002) /*!< Alternate Function Push Pull Mode */ #define GPIO_MODE_AF_OD ((uint32_t)0x00000012) /*!< Alternate Function Open Drain Mode */ #define GPIO_MODE_ANALOG ((uint32_t)0x00000003) /*!< Analog Mode */ #define GPIO_MODE_IT_RISING ((uint32_t)0x10110000) /*!< External Interrupt Mode with Rising edge trigger detection */ #define GPIO_MODE_IT_FALLING ((uint32_t)0x10210000) /*!< External Interrupt Mode with Falling edge trigger detection */ #define GPIO_MODE_IT_RISING_FALLING ((uint32_t)0x10310000) /*!< External Interrupt Mode with Rising/Falling edge trigger detection */ #define GPIO_MODE_EVT_RISING ((uint32_t)0x10120000) /*!< External Event Mode with Rising edge trigger detection */ #define GPIO_MODE_EVT_FALLING ((uint32_t)0x10220000) /*!< External Event Mode with Falling edge trigger detection */ #define GPIO_MODE_EVT_RISING_FALLING ((uint32_t)0x10320000) /*!< External Event Mode with Rising/Falling edge trigger detection */ /** * @} */ /** @defgroup GPIO_speed_define GPIO speed define * @brief GPIO Output Maximum frequency * @{ */ #define GPIO_SPEED_FREQ_LOW ((uint32_t)0x00000000) /*!< IO works at 2 MHz, please refer to the product datasheet */ #define GPIO_SPEED_FREQ_MEDIUM ((uint32_t)0x00000001) /*!< range 12,5 MHz to 50 MHz, please refer to the product datasheet */ #define GPIO_SPEED_FREQ_HIGH ((uint32_t)0x00000002) /*!< range 25 MHz to 100 MHz, please refer to the product datasheet */ #define GPIO_SPEED_FREQ_VERY_HIGH ((uint32_t)0x00000003) /*!< range 50 MHz to 200 MHz, please refer to the product datasheet */ /** * @} */ /** @defgroup GPIO_pull_define GPIO pull define * @brief GPIO Pull-Up or Pull-Down Activation * @{ */ #define GPIO_NOPULL ((uint32_t)0x00000000) /*!< No Pull-up or Pull-down activation */ #define GPIO_PULLUP ((uint32_t)0x00000001) /*!< Pull-up activation */ #define GPIO_PULLDOWN ((uint32_t)0x00000002) /*!< Pull-down activation */ /** * @} */ /** * @} */ /* Exported macro ------------------------------------------------------------*/ /** @defgroup GPIO_Exported_Macros GPIO Exported Macros * @{ */ /** * @brief Checks whether the specified EXTI line flag is set or not. * @param __EXTI_LINE__: specifies the EXTI line flag to check. * This parameter can be GPIO_PIN_x where x can be(0..15) * @retval The new state of __EXTI_LINE__ (SET or RESET). */ #define __HAL_GPIO_EXTI_GET_FLAG(__EXTI_LINE__) (EXTI->PR & (__EXTI_LINE__)) /** * @brief Clears the EXTI's line pending flags. * @param __EXTI_LINE__: specifies the EXTI lines flags to clear. * This parameter can be any combination of GPIO_PIN_x where x can be (0..15) * @retval None */ #define __HAL_GPIO_EXTI_CLEAR_FLAG(__EXTI_LINE__) (EXTI->PR = (__EXTI_LINE__)) /** * @brief Checks whether the specified EXTI line is asserted or not. * @param __EXTI_LINE__: specifies the EXTI line to check. * This parameter can be GPIO_PIN_x where x can be(0..15) * @retval The new state of __EXTI_LINE__ (SET or RESET). */ #define __HAL_GPIO_EXTI_GET_IT(__EXTI_LINE__) (EXTI->PR & (__EXTI_LINE__)) /** * @brief Clears the EXTI's line pending bits. * @param __EXTI_LINE__: specifies the EXTI lines to clear. * This parameter can be any combination of GPIO_PIN_x where x can be (0..15) * @retval None */ #define __HAL_GPIO_EXTI_CLEAR_IT(__EXTI_LINE__) (EXTI->PR = (__EXTI_LINE__)) /** * @brief Generates a Software interrupt on selected EXTI line. * @param __EXTI_LINE__: specifies the EXTI line to check. * This parameter can be GPIO_PIN_x where x can be(0..15) * @retval None */ #define __HAL_GPIO_EXTI_GENERATE_SWIT(__EXTI_LINE__) (EXTI->SWIER |= (__EXTI_LINE__)) /** * @} */ /* Include GPIO HAL Extension module */ #include "stm32f4xx_hal_gpio_ex.h" /* Exported functions --------------------------------------------------------*/ /** @addtogroup GPIO_Exported_Functions * @{ */ /** @addtogroup GPIO_Exported_Functions_Group1 * @{ */ /* Initialization and de-initialization functions *****************************/ void HAL_GPIO_Init(GPIO_TypeDef *GPIOx, GPIO_InitTypeDef *GPIO_Init); void HAL_GPIO_DeInit(GPIO_TypeDef *GPIOx, uint32_t GPIO_Pin); /** * @} */ /** @addtogroup GPIO_Exported_Functions_Group2 * @{ */ /* IO operation functions *****************************************************/ GPIO_PinState HAL_GPIO_ReadPin(GPIO_TypeDef* GPIOx, uint16_t GPIO_Pin); void HAL_GPIO_WritePin(GPIO_TypeDef* GPIOx, uint16_t GPIO_Pin, GPIO_PinState PinState); void HAL_GPIO_TogglePin(GPIO_TypeDef* GPIOx, uint16_t GPIO_Pin); HAL_StatusTypeDef HAL_GPIO_LockPin(GPIO_TypeDef* GPIOx, uint16_t GPIO_Pin); void HAL_GPIO_EXTI_IRQHandler(uint16_t GPIO_Pin); void HAL_GPIO_EXTI_Callback(uint16_t GPIO_Pin); /** * @} */ /** * @} */ /* Private types -------------------------------------------------------------*/ /* Private variables ---------------------------------------------------------*/ /* Private constants ---------------------------------------------------------*/ /** @defgroup GPIO_Private_Constants GPIO Private Constants * @{ */ /** * @} */ /* Private macros ------------------------------------------------------------*/ /** @defgroup GPIO_Private_Macros GPIO Private Macros * @{ */ #define IS_GPIO_PIN_ACTION(ACTION) (((ACTION) == GPIO_PIN_RESET) || ((ACTION) == GPIO_PIN_SET)) #define IS_GPIO_PIN(PIN) (((PIN) & GPIO_PIN_MASK ) != (uint32_t)0x00) #define IS_GPIO_MODE(MODE) (((MODE) == GPIO_MODE_INPUT) ||\ ((MODE) == GPIO_MODE_OUTPUT_PP) ||\ ((MODE) == GPIO_MODE_OUTPUT_OD) ||\ ((MODE) == GPIO_MODE_AF_PP) ||\ ((MODE) == GPIO_MODE_AF_OD) ||\ ((MODE) == GPIO_MODE_IT_RISING) ||\ ((MODE) == GPIO_MODE_IT_FALLING) ||\ ((MODE) == GPIO_MODE_IT_RISING_FALLING) ||\ ((MODE) == GPIO_MODE_EVT_RISING) ||\ ((MODE) == GPIO_MODE_EVT_FALLING) ||\ ((MODE) == GPIO_MODE_EVT_RISING_FALLING) ||\ ((MODE) == GPIO_MODE_ANALOG)) #define IS_GPIO_SPEED(SPEED) (((SPEED) == GPIO_SPEED_FREQ_LOW) || ((SPEED) == GPIO_SPEED_FREQ_MEDIUM) || \ ((SPEED) == GPIO_SPEED_FREQ_HIGH) || ((SPEED) == GPIO_SPEED_FREQ_VERY_HIGH)) #define IS_GPIO_PULL(PULL) (((PULL) == GPIO_NOPULL) || ((PULL) == GPIO_PULLUP) || \ ((PULL) == GPIO_PULLDOWN)) /** * @} */ /* Private functions ---------------------------------------------------------*/ /** @defgroup GPIO_Private_Functions GPIO Private Functions * @{ */ /** * @} */ /** * @} */ /** * @} */ #ifdef __cplusplus } #endif #endif /* __STM32F4xx_HAL_GPIO_H */ /************************ (C) COPYRIGHT STMicroelectronics *****END OF FILE****/ ================================================ FILE: Zelig/mbed/TARGET_NUCLEO_F401RE/stm32f4xx_hal_gpio_ex.h ================================================ /** ****************************************************************************** * @file stm32f4xx_hal_gpio_ex.h * @author MCD Application Team * @version V1.4.1 * @date 09-October-2015 * @brief Header file of GPIO HAL Extension module. ****************************************************************************** * @attention * *

© COPYRIGHT(c) 2015 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. * ****************************************************************************** */ /* Define to prevent recursive inclusion -------------------------------------*/ #ifndef __STM32F4xx_HAL_GPIO_EX_H #define __STM32F4xx_HAL_GPIO_EX_H #ifdef __cplusplus extern "C" { #endif /* Includes ------------------------------------------------------------------*/ #include "stm32f4xx_hal_def.h" /** @addtogroup STM32F4xx_HAL_Driver * @{ */ /** @defgroup GPIOEx GPIOEx * @{ */ /* Exported types ------------------------------------------------------------*/ /* Exported constants --------------------------------------------------------*/ /** @defgroup GPIOEx_Exported_Constants GPIO Exported Constants * @{ */ /** @defgroup GPIO_Alternate_function_selection GPIO Alternate Function Selection * @{ */ /*------------------------------------------ STM32F429xx/STM32F439xx ---------*/ #if defined(STM32F429xx) || defined(STM32F439xx) /** * @brief AF 0 selection */ #define GPIO_AF0_RTC_50Hz ((uint8_t)0x00) /* RTC_50Hz Alternate Function mapping */ #define GPIO_AF0_MCO ((uint8_t)0x00) /* MCO (MCO1 and MCO2) Alternate Function mapping */ #define GPIO_AF0_TAMPER ((uint8_t)0x00) /* TAMPER (TAMPER_1 and TAMPER_2) Alternate Function mapping */ #define GPIO_AF0_SWJ ((uint8_t)0x00) /* SWJ (SWD and JTAG) Alternate Function mapping */ #define GPIO_AF0_TRACE ((uint8_t)0x00) /* TRACE Alternate Function mapping */ /** * @brief AF 1 selection */ #define GPIO_AF1_TIM1 ((uint8_t)0x01) /* TIM1 Alternate Function mapping */ #define GPIO_AF1_TIM2 ((uint8_t)0x01) /* TIM2 Alternate Function mapping */ /** * @brief AF 2 selection */ #define GPIO_AF2_TIM3 ((uint8_t)0x02) /* TIM3 Alternate Function mapping */ #define GPIO_AF2_TIM4 ((uint8_t)0x02) /* TIM4 Alternate Function mapping */ #define GPIO_AF2_TIM5 ((uint8_t)0x02) /* TIM5 Alternate Function mapping */ /** * @brief AF 3 selection */ #define GPIO_AF3_TIM8 ((uint8_t)0x03) /* TIM8 Alternate Function mapping */ #define GPIO_AF3_TIM9 ((uint8_t)0x03) /* TIM9 Alternate Function mapping */ #define GPIO_AF3_TIM10 ((uint8_t)0x03) /* TIM10 Alternate Function mapping */ #define GPIO_AF3_TIM11 ((uint8_t)0x03) /* TIM11 Alternate Function mapping */ /** * @brief AF 4 selection */ #define GPIO_AF4_I2C1 ((uint8_t)0x04) /* I2C1 Alternate Function mapping */ #define GPIO_AF4_I2C2 ((uint8_t)0x04) /* I2C2 Alternate Function mapping */ #define GPIO_AF4_I2C3 ((uint8_t)0x04) /* I2C3 Alternate Function mapping */ /** * @brief AF 5 selection */ #define GPIO_AF5_SPI1 ((uint8_t)0x05) /* SPI1 Alternate Function mapping */ #define GPIO_AF5_SPI2 ((uint8_t)0x05) /* SPI2/I2S2 Alternate Function mapping */ #define GPIO_AF5_SPI3 ((uint8_t)0x05) /* SPI3/I2S3 Alternate Function mapping */ #define GPIO_AF5_SPI4 ((uint8_t)0x05) /* SPI4 Alternate Function mapping */ #define GPIO_AF5_SPI5 ((uint8_t)0x05) /* SPI5 Alternate Function mapping */ #define GPIO_AF5_SPI6 ((uint8_t)0x05) /* SPI6 Alternate Function mapping */ #define GPIO_AF5_I2S3ext ((uint8_t)0x05) /* I2S3ext_SD Alternate Function mapping */ /** * @brief AF 6 selection */ #define GPIO_AF6_SPI3 ((uint8_t)0x06) /* SPI3/I2S3 Alternate Function mapping */ #define GPIO_AF6_I2S2ext ((uint8_t)0x06) /* I2S2ext_SD Alternate Function mapping */ #define GPIO_AF6_SAI1 ((uint8_t)0x06) /* SAI1 Alternate Function mapping */ /** * @brief AF 7 selection */ #define GPIO_AF7_USART1 ((uint8_t)0x07) /* USART1 Alternate Function mapping */ #define GPIO_AF7_USART2 ((uint8_t)0x07) /* USART2 Alternate Function mapping */ #define GPIO_AF7_USART3 ((uint8_t)0x07) /* USART3 Alternate Function mapping */ #define GPIO_AF7_I2S3ext ((uint8_t)0x07) /* I2S3ext_SD Alternate Function mapping */ /** * @brief AF 8 selection */ #define GPIO_AF8_UART4 ((uint8_t)0x08) /* UART4 Alternate Function mapping */ #define GPIO_AF8_UART5 ((uint8_t)0x08) /* UART5 Alternate Function mapping */ #define GPIO_AF8_USART6 ((uint8_t)0x08) /* USART6 Alternate Function mapping */ #define GPIO_AF8_UART7 ((uint8_t)0x08) /* UART7 Alternate Function mapping */ #define GPIO_AF8_UART8 ((uint8_t)0x08) /* UART8 Alternate Function mapping */ /** * @brief AF 9 selection */ #define GPIO_AF9_CAN1 ((uint8_t)0x09) /* CAN1 Alternate Function mapping */ #define GPIO_AF9_CAN2 ((uint8_t)0x09) /* CAN2 Alternate Function mapping */ #define GPIO_AF9_TIM12 ((uint8_t)0x09) /* TIM12 Alternate Function mapping */ #define GPIO_AF9_TIM13 ((uint8_t)0x09) /* TIM13 Alternate Function mapping */ #define GPIO_AF9_TIM14 ((uint8_t)0x09) /* TIM14 Alternate Function mapping */ #define GPIO_AF9_LTDC ((uint8_t)0x09) /* LCD-TFT Alternate Function mapping */ /** * @brief AF 10 selection */ #define GPIO_AF10_OTG_FS ((uint8_t)0xA) /* OTG_FS Alternate Function mapping */ #define GPIO_AF10_OTG_HS ((uint8_t)0xA) /* OTG_HS Alternate Function mapping */ /** * @brief AF 11 selection */ #define GPIO_AF11_ETH ((uint8_t)0x0B) /* ETHERNET Alternate Function mapping */ /** * @brief AF 12 selection */ #define GPIO_AF12_FMC ((uint8_t)0xC) /* FMC Alternate Function mapping */ #define GPIO_AF12_OTG_HS_FS ((uint8_t)0xC) /* OTG HS configured in FS, Alternate Function mapping */ #define GPIO_AF12_SDIO ((uint8_t)0xC) /* SDIO Alternate Function mapping */ /** * @brief AF 13 selection */ #define GPIO_AF13_DCMI ((uint8_t)0x0D) /* DCMI Alternate Function mapping */ /** * @brief AF 14 selection */ #define GPIO_AF14_LTDC ((uint8_t)0x0E) /* LCD-TFT Alternate Function mapping */ /** * @brief AF 15 selection */ #define GPIO_AF15_EVENTOUT ((uint8_t)0x0F) /* EVENTOUT Alternate Function mapping */ #endif /* STM32F429xx || STM32F439xx */ /*----------------------------------------------------------------------------*/ /*---------------------------------- STM32F427xx/STM32F437xx------------------*/ #if defined(STM32F427xx) || defined(STM32F437xx) /** * @brief AF 0 selection */ #define GPIO_AF0_RTC_50Hz ((uint8_t)0x00) /* RTC_50Hz Alternate Function mapping */ #define GPIO_AF0_MCO ((uint8_t)0x00) /* MCO (MCO1 and MCO2) Alternate Function mapping */ #define GPIO_AF0_TAMPER ((uint8_t)0x00) /* TAMPER (TAMPER_1 and TAMPER_2) Alternate Function mapping */ #define GPIO_AF0_SWJ ((uint8_t)0x00) /* SWJ (SWD and JTAG) Alternate Function mapping */ #define GPIO_AF0_TRACE ((uint8_t)0x00) /* TRACE Alternate Function mapping */ /** * @brief AF 1 selection */ #define GPIO_AF1_TIM1 ((uint8_t)0x01) /* TIM1 Alternate Function mapping */ #define GPIO_AF1_TIM2 ((uint8_t)0x01) /* TIM2 Alternate Function mapping */ /** * @brief AF 2 selection */ #define GPIO_AF2_TIM3 ((uint8_t)0x02) /* TIM3 Alternate Function mapping */ #define GPIO_AF2_TIM4 ((uint8_t)0x02) /* TIM4 Alternate Function mapping */ #define GPIO_AF2_TIM5 ((uint8_t)0x02) /* TIM5 Alternate Function mapping */ /** * @brief AF 3 selection */ #define GPIO_AF3_TIM8 ((uint8_t)0x03) /* TIM8 Alternate Function mapping */ #define GPIO_AF3_TIM9 ((uint8_t)0x03) /* TIM9 Alternate Function mapping */ #define GPIO_AF3_TIM10 ((uint8_t)0x03) /* TIM10 Alternate Function mapping */ #define GPIO_AF3_TIM11 ((uint8_t)0x03) /* TIM11 Alternate Function mapping */ /** * @brief AF 4 selection */ #define GPIO_AF4_I2C1 ((uint8_t)0x04) /* I2C1 Alternate Function mapping */ #define GPIO_AF4_I2C2 ((uint8_t)0x04) /* I2C2 Alternate Function mapping */ #define GPIO_AF4_I2C3 ((uint8_t)0x04) /* I2C3 Alternate Function mapping */ /** * @brief AF 5 selection */ #define GPIO_AF5_SPI1 ((uint8_t)0x05) /* SPI1 Alternate Function mapping */ #define GPIO_AF5_SPI2 ((uint8_t)0x05) /* SPI2/I2S2 Alternate Function mapping */ #define GPIO_AF5_SPI3 ((uint8_t)0x05) /* SPI3/I2S3 Alternate Function mapping */ #define GPIO_AF5_SPI4 ((uint8_t)0x05) /* SPI4 Alternate Function mapping */ #define GPIO_AF5_SPI5 ((uint8_t)0x05) /* SPI5 Alternate Function mapping */ #define GPIO_AF5_SPI6 ((uint8_t)0x05) /* SPI6 Alternate Function mapping */ /** @brief GPIO_Legacy */ #define GPIO_AF5_I2S3ext GPIO_AF5_SPI3 /* I2S3ext_SD Alternate Function mapping */ /** * @brief AF 6 selection */ #define GPIO_AF6_SPI3 ((uint8_t)0x06) /* SPI3/I2S3 Alternate Function mapping */ #define GPIO_AF6_I2S2ext ((uint8_t)0x06) /* I2S2ext_SD Alternate Function mapping */ #define GPIO_AF6_SAI1 ((uint8_t)0x06) /* SAI1 Alternate Function mapping */ /** * @brief AF 7 selection */ #define GPIO_AF7_USART1 ((uint8_t)0x07) /* USART1 Alternate Function mapping */ #define GPIO_AF7_USART2 ((uint8_t)0x07) /* USART2 Alternate Function mapping */ #define GPIO_AF7_USART3 ((uint8_t)0x07) /* USART3 Alternate Function mapping */ #define GPIO_AF7_I2S3ext ((uint8_t)0x07) /* I2S3ext_SD Alternate Function mapping */ /** * @brief AF 8 selection */ #define GPIO_AF8_UART4 ((uint8_t)0x08) /* UART4 Alternate Function mapping */ #define GPIO_AF8_UART5 ((uint8_t)0x08) /* UART5 Alternate Function mapping */ #define GPIO_AF8_USART6 ((uint8_t)0x08) /* USART6 Alternate Function mapping */ #define GPIO_AF8_UART7 ((uint8_t)0x08) /* UART7 Alternate Function mapping */ #define GPIO_AF8_UART8 ((uint8_t)0x08) /* UART8 Alternate Function mapping */ /** * @brief AF 9 selection */ #define GPIO_AF9_CAN1 ((uint8_t)0x09) /* CAN1 Alternate Function mapping */ #define GPIO_AF9_CAN2 ((uint8_t)0x09) /* CAN2 Alternate Function mapping */ #define GPIO_AF9_TIM12 ((uint8_t)0x09) /* TIM12 Alternate Function mapping */ #define GPIO_AF9_TIM13 ((uint8_t)0x09) /* TIM13 Alternate Function mapping */ #define GPIO_AF9_TIM14 ((uint8_t)0x09) /* TIM14 Alternate Function mapping */ /** * @brief AF 10 selection */ #define GPIO_AF10_OTG_FS ((uint8_t)0xA) /* OTG_FS Alternate Function mapping */ #define GPIO_AF10_OTG_HS ((uint8_t)0xA) /* OTG_HS Alternate Function mapping */ /** * @brief AF 11 selection */ #define GPIO_AF11_ETH ((uint8_t)0x0B) /* ETHERNET Alternate Function mapping */ /** * @brief AF 12 selection */ #define GPIO_AF12_FMC ((uint8_t)0xC) /* FMC Alternate Function mapping */ #define GPIO_AF12_OTG_HS_FS ((uint8_t)0xC) /* OTG HS configured in FS, Alternate Function mapping */ #define GPIO_AF12_SDIO ((uint8_t)0xC) /* SDIO Alternate Function mapping */ /** * @brief AF 13 selection */ #define GPIO_AF13_DCMI ((uint8_t)0x0D) /* DCMI Alternate Function mapping */ /** * @brief AF 15 selection */ #define GPIO_AF15_EVENTOUT ((uint8_t)0x0F) /* EVENTOUT Alternate Function mapping */ #endif /* STM32F427xx || STM32F437xx */ /*----------------------------------------------------------------------------*/ /*---------------------------------- STM32F407xx/STM32F417xx------------------*/ #if defined(STM32F407xx) || defined(STM32F417xx) /** * @brief AF 0 selection */ #define GPIO_AF0_RTC_50Hz ((uint8_t)0x00) /* RTC_50Hz Alternate Function mapping */ #define GPIO_AF0_MCO ((uint8_t)0x00) /* MCO (MCO1 and MCO2) Alternate Function mapping */ #define GPIO_AF0_TAMPER ((uint8_t)0x00) /* TAMPER (TAMPER_1 and TAMPER_2) Alternate Function mapping */ #define GPIO_AF0_SWJ ((uint8_t)0x00) /* SWJ (SWD and JTAG) Alternate Function mapping */ #define GPIO_AF0_TRACE ((uint8_t)0x00) /* TRACE Alternate Function mapping */ /** * @brief AF 1 selection */ #define GPIO_AF1_TIM1 ((uint8_t)0x01) /* TIM1 Alternate Function mapping */ #define GPIO_AF1_TIM2 ((uint8_t)0x01) /* TIM2 Alternate Function mapping */ /** * @brief AF 2 selection */ #define GPIO_AF2_TIM3 ((uint8_t)0x02) /* TIM3 Alternate Function mapping */ #define GPIO_AF2_TIM4 ((uint8_t)0x02) /* TIM4 Alternate Function mapping */ #define GPIO_AF2_TIM5 ((uint8_t)0x02) /* TIM5 Alternate Function mapping */ /** * @brief AF 3 selection */ #define GPIO_AF3_TIM8 ((uint8_t)0x03) /* TIM8 Alternate Function mapping */ #define GPIO_AF3_TIM9 ((uint8_t)0x03) /* TIM9 Alternate Function mapping */ #define GPIO_AF3_TIM10 ((uint8_t)0x03) /* TIM10 Alternate Function mapping */ #define GPIO_AF3_TIM11 ((uint8_t)0x03) /* TIM11 Alternate Function mapping */ /** * @brief AF 4 selection */ #define GPIO_AF4_I2C1 ((uint8_t)0x04) /* I2C1 Alternate Function mapping */ #define GPIO_AF4_I2C2 ((uint8_t)0x04) /* I2C2 Alternate Function mapping */ #define GPIO_AF4_I2C3 ((uint8_t)0x04) /* I2C3 Alternate Function mapping */ /** * @brief AF 5 selection */ #define GPIO_AF5_SPI1 ((uint8_t)0x05) /* SPI1 Alternate Function mapping */ #define GPIO_AF5_SPI2 ((uint8_t)0x05) /* SPI2/I2S2 Alternate Function mapping */ #define GPIO_AF5_I2S3ext ((uint8_t)0x05) /* I2S3ext_SD Alternate Function mapping */ /** * @brief AF 6 selection */ #define GPIO_AF6_SPI3 ((uint8_t)0x06) /* SPI3/I2S3 Alternate Function mapping */ #define GPIO_AF6_I2S2ext ((uint8_t)0x06) /* I2S2ext_SD Alternate Function mapping */ /** * @brief AF 7 selection */ #define GPIO_AF7_USART1 ((uint8_t)0x07) /* USART1 Alternate Function mapping */ #define GPIO_AF7_USART2 ((uint8_t)0x07) /* USART2 Alternate Function mapping */ #define GPIO_AF7_USART3 ((uint8_t)0x07) /* USART3 Alternate Function mapping */ #define GPIO_AF7_I2S3ext ((uint8_t)0x07) /* I2S3ext_SD Alternate Function mapping */ /** * @brief AF 8 selection */ #define GPIO_AF8_UART4 ((uint8_t)0x08) /* UART4 Alternate Function mapping */ #define GPIO_AF8_UART5 ((uint8_t)0x08) /* UART5 Alternate Function mapping */ #define GPIO_AF8_USART6 ((uint8_t)0x08) /* USART6 Alternate Function mapping */ /** * @brief AF 9 selection */ #define GPIO_AF9_CAN1 ((uint8_t)0x09) /* CAN1 Alternate Function mapping */ #define GPIO_AF9_CAN2 ((uint8_t)0x09) /* CAN2 Alternate Function mapping */ #define GPIO_AF9_TIM12 ((uint8_t)0x09) /* TIM12 Alternate Function mapping */ #define GPIO_AF9_TIM13 ((uint8_t)0x09) /* TIM13 Alternate Function mapping */ #define GPIO_AF9_TIM14 ((uint8_t)0x09) /* TIM14 Alternate Function mapping */ /** * @brief AF 10 selection */ #define GPIO_AF10_OTG_FS ((uint8_t)0xA) /* OTG_FS Alternate Function mapping */ #define GPIO_AF10_OTG_HS ((uint8_t)0xA) /* OTG_HS Alternate Function mapping */ /** * @brief AF 11 selection */ #define GPIO_AF11_ETH ((uint8_t)0x0B) /* ETHERNET Alternate Function mapping */ /** * @brief AF 12 selection */ #define GPIO_AF12_FSMC ((uint8_t)0xC) /* FSMC Alternate Function mapping */ #define GPIO_AF12_OTG_HS_FS ((uint8_t)0xC) /* OTG HS configured in FS, Alternate Function mapping */ #define GPIO_AF12_SDIO ((uint8_t)0xC) /* SDIO Alternate Function mapping */ /** * @brief AF 13 selection */ #define GPIO_AF13_DCMI ((uint8_t)0x0D) /* DCMI Alternate Function mapping */ /** * @brief AF 15 selection */ #define GPIO_AF15_EVENTOUT ((uint8_t)0x0F) /* EVENTOUT Alternate Function mapping */ #endif /* STM32F407xx || STM32F417xx */ /*----------------------------------------------------------------------------*/ /*---------------------------------- STM32F405xx/STM32F415xx------------------*/ #if defined(STM32F405xx) || defined(STM32F415xx) /** * @brief AF 0 selection */ #define GPIO_AF0_RTC_50Hz ((uint8_t)0x00) /* RTC_50Hz Alternate Function mapping */ #define GPIO_AF0_MCO ((uint8_t)0x00) /* MCO (MCO1 and MCO2) Alternate Function mapping */ #define GPIO_AF0_TAMPER ((uint8_t)0x00) /* TAMPER (TAMPER_1 and TAMPER_2) Alternate Function mapping */ #define GPIO_AF0_SWJ ((uint8_t)0x00) /* SWJ (SWD and JTAG) Alternate Function mapping */ #define GPIO_AF0_TRACE ((uint8_t)0x00) /* TRACE Alternate Function mapping */ /** * @brief AF 1 selection */ #define GPIO_AF1_TIM1 ((uint8_t)0x01) /* TIM1 Alternate Function mapping */ #define GPIO_AF1_TIM2 ((uint8_t)0x01) /* TIM2 Alternate Function mapping */ /** * @brief AF 2 selection */ #define GPIO_AF2_TIM3 ((uint8_t)0x02) /* TIM3 Alternate Function mapping */ #define GPIO_AF2_TIM4 ((uint8_t)0x02) /* TIM4 Alternate Function mapping */ #define GPIO_AF2_TIM5 ((uint8_t)0x02) /* TIM5 Alternate Function mapping */ /** * @brief AF 3 selection */ #define GPIO_AF3_TIM8 ((uint8_t)0x03) /* TIM8 Alternate Function mapping */ #define GPIO_AF3_TIM9 ((uint8_t)0x03) /* TIM9 Alternate Function mapping */ #define GPIO_AF3_TIM10 ((uint8_t)0x03) /* TIM10 Alternate Function mapping */ #define GPIO_AF3_TIM11 ((uint8_t)0x03) /* TIM11 Alternate Function mapping */ /** * @brief AF 4 selection */ #define GPIO_AF4_I2C1 ((uint8_t)0x04) /* I2C1 Alternate Function mapping */ #define GPIO_AF4_I2C2 ((uint8_t)0x04) /* I2C2 Alternate Function mapping */ #define GPIO_AF4_I2C3 ((uint8_t)0x04) /* I2C3 Alternate Function mapping */ /** * @brief AF 5 selection */ #define GPIO_AF5_SPI1 ((uint8_t)0x05) /* SPI1 Alternate Function mapping */ #define GPIO_AF5_SPI2 ((uint8_t)0x05) /* SPI2/I2S2 Alternate Function mapping */ #define GPIO_AF5_I2S3ext ((uint8_t)0x05) /* I2S3ext_SD Alternate Function mapping */ /** * @brief AF 6 selection */ #define GPIO_AF6_SPI3 ((uint8_t)0x06) /* SPI3/I2S3 Alternate Function mapping */ #define GPIO_AF6_I2S2ext ((uint8_t)0x06) /* I2S2ext_SD Alternate Function mapping */ /** * @brief AF 7 selection */ #define GPIO_AF7_USART1 ((uint8_t)0x07) /* USART1 Alternate Function mapping */ #define GPIO_AF7_USART2 ((uint8_t)0x07) /* USART2 Alternate Function mapping */ #define GPIO_AF7_USART3 ((uint8_t)0x07) /* USART3 Alternate Function mapping */ #define GPIO_AF7_I2S3ext ((uint8_t)0x07) /* I2S3ext_SD Alternate Function mapping */ /** * @brief AF 8 selection */ #define GPIO_AF8_UART4 ((uint8_t)0x08) /* UART4 Alternate Function mapping */ #define GPIO_AF8_UART5 ((uint8_t)0x08) /* UART5 Alternate Function mapping */ #define GPIO_AF8_USART6 ((uint8_t)0x08) /* USART6 Alternate Function mapping */ /** * @brief AF 9 selection */ #define GPIO_AF9_CAN1 ((uint8_t)0x09) /* CAN1 Alternate Function mapping */ #define GPIO_AF9_CAN2 ((uint8_t)0x09) /* CAN2 Alternate Function mapping */ #define GPIO_AF9_TIM12 ((uint8_t)0x09) /* TIM12 Alternate Function mapping */ #define GPIO_AF9_TIM13 ((uint8_t)0x09) /* TIM13 Alternate Function mapping */ #define GPIO_AF9_TIM14 ((uint8_t)0x09) /* TIM14 Alternate Function mapping */ /** * @brief AF 10 selection */ #define GPIO_AF10_OTG_FS ((uint8_t)0xA) /* OTG_FS Alternate Function mapping */ #define GPIO_AF10_OTG_HS ((uint8_t)0xA) /* OTG_HS Alternate Function mapping */ /** * @brief AF 12 selection */ #define GPIO_AF12_FSMC ((uint8_t)0xC) /* FSMC Alternate Function mapping */ #define GPIO_AF12_OTG_HS_FS ((uint8_t)0xC) /* OTG HS configured in FS, Alternate Function mapping */ #define GPIO_AF12_SDIO ((uint8_t)0xC) /* SDIO Alternate Function mapping */ /** * @brief AF 15 selection */ #define GPIO_AF15_EVENTOUT ((uint8_t)0x0F) /* EVENTOUT Alternate Function mapping */ #endif /* STM32F405xx || STM32F415xx */ /*----------------------------------------------------------------------------*/ /*---------------------------------------- STM32F401xx------------------------*/ #if defined(STM32F401xC) || defined(STM32F401xE) /** * @brief AF 0 selection */ #define GPIO_AF0_RTC_50Hz ((uint8_t)0x00) /* RTC_50Hz Alternate Function mapping */ #define GPIO_AF0_MCO ((uint8_t)0x00) /* MCO (MCO1 and MCO2) Alternate Function mapping */ #define GPIO_AF0_TAMPER ((uint8_t)0x00) /* TAMPER (TAMPER_1 and TAMPER_2) Alternate Function mapping */ #define GPIO_AF0_SWJ ((uint8_t)0x00) /* SWJ (SWD and JTAG) Alternate Function mapping */ #define GPIO_AF0_TRACE ((uint8_t)0x00) /* TRACE Alternate Function mapping */ /** * @brief AF 1 selection */ #define GPIO_AF1_TIM1 ((uint8_t)0x01) /* TIM1 Alternate Function mapping */ #define GPIO_AF1_TIM2 ((uint8_t)0x01) /* TIM2 Alternate Function mapping */ /** * @brief AF 2 selection */ #define GPIO_AF2_TIM3 ((uint8_t)0x02) /* TIM3 Alternate Function mapping */ #define GPIO_AF2_TIM4 ((uint8_t)0x02) /* TIM4 Alternate Function mapping */ #define GPIO_AF2_TIM5 ((uint8_t)0x02) /* TIM5 Alternate Function mapping */ /** * @brief AF 3 selection */ #define GPIO_AF3_TIM9 ((uint8_t)0x03) /* TIM9 Alternate Function mapping */ #define GPIO_AF3_TIM10 ((uint8_t)0x03) /* TIM10 Alternate Function mapping */ #define GPIO_AF3_TIM11 ((uint8_t)0x03) /* TIM11 Alternate Function mapping */ /** * @brief AF 4 selection */ #define GPIO_AF4_I2C1 ((uint8_t)0x04) /* I2C1 Alternate Function mapping */ #define GPIO_AF4_I2C2 ((uint8_t)0x04) /* I2C2 Alternate Function mapping */ #define GPIO_AF4_I2C3 ((uint8_t)0x04) /* I2C3 Alternate Function mapping */ /** * @brief AF 5 selection */ #define GPIO_AF5_SPI1 ((uint8_t)0x05) /* SPI1 Alternate Function mapping */ #define GPIO_AF5_SPI2 ((uint8_t)0x05) /* SPI2/I2S2 Alternate Function mapping */ #define GPIO_AF5_SPI4 ((uint8_t)0x05) /* SPI4 Alternate Function mapping */ #define GPIO_AF5_I2S3ext ((uint8_t)0x05) /* I2S3ext_SD Alternate Function mapping */ /** * @brief AF 6 selection */ #define GPIO_AF6_SPI3 ((uint8_t)0x06) /* SPI3/I2S3 Alternate Function mapping */ #define GPIO_AF6_I2S2ext ((uint8_t)0x06) /* I2S2ext_SD Alternate Function mapping */ /** * @brief AF 7 selection */ #define GPIO_AF7_USART1 ((uint8_t)0x07) /* USART1 Alternate Function mapping */ #define GPIO_AF7_USART2 ((uint8_t)0x07) /* USART2 Alternate Function mapping */ #define GPIO_AF7_I2S3ext ((uint8_t)0x07) /* I2S3ext_SD Alternate Function mapping */ /** * @brief AF 8 selection */ #define GPIO_AF8_USART6 ((uint8_t)0x08) /* USART6 Alternate Function mapping */ /** * @brief AF 9 selection */ #define GPIO_AF9_TIM14 ((uint8_t)0x09) /* TIM14 Alternate Function mapping */ #define GPIO_AF9_I2C2 ((uint8_t)0x09) /* I2C2 Alternate Function mapping */ #define GPIO_AF9_I2C3 ((uint8_t)0x09) /* I2C3 Alternate Function mapping */ /** * @brief AF 10 selection */ #define GPIO_AF10_OTG_FS ((uint8_t)0xA) /* OTG_FS Alternate Function mapping */ /** * @brief AF 12 selection */ #define GPIO_AF12_SDIO ((uint8_t)0xC) /* SDIO Alternate Function mapping */ /** * @brief AF 15 selection */ #define GPIO_AF15_EVENTOUT ((uint8_t)0x0F) /* EVENTOUT Alternate Function mapping */ #endif /* STM32F401xC || STM32F401xE */ /*----------------------------------------------------------------------------*/ /*---------------------------------------- STM32F411xx------------------------*/ #if defined(STM32F411xE) /** * @brief AF 0 selection */ #define GPIO_AF0_RTC_50Hz ((uint8_t)0x00) /* RTC_50Hz Alternate Function mapping */ #define GPIO_AF0_MCO ((uint8_t)0x00) /* MCO (MCO1 and MCO2) Alternate Function mapping */ #define GPIO_AF0_TAMPER ((uint8_t)0x00) /* TAMPER (TAMPER_1 and TAMPER_2) Alternate Function mapping */ #define GPIO_AF0_SWJ ((uint8_t)0x00) /* SWJ (SWD and JTAG) Alternate Function mapping */ #define GPIO_AF0_TRACE ((uint8_t)0x00) /* TRACE Alternate Function mapping */ /** * @brief AF 1 selection */ #define GPIO_AF1_TIM1 ((uint8_t)0x01) /* TIM1 Alternate Function mapping */ #define GPIO_AF1_TIM2 ((uint8_t)0x01) /* TIM2 Alternate Function mapping */ /** * @brief AF 2 selection */ #define GPIO_AF2_TIM3 ((uint8_t)0x02) /* TIM3 Alternate Function mapping */ #define GPIO_AF2_TIM4 ((uint8_t)0x02) /* TIM4 Alternate Function mapping */ #define GPIO_AF2_TIM5 ((uint8_t)0x02) /* TIM5 Alternate Function mapping */ /** * @brief AF 3 selection */ #define GPIO_AF3_TIM9 ((uint8_t)0x03) /* TIM9 Alternate Function mapping */ #define GPIO_AF3_TIM10 ((uint8_t)0x03) /* TIM10 Alternate Function mapping */ #define GPIO_AF3_TIM11 ((uint8_t)0x03) /* TIM11 Alternate Function mapping */ /** * @brief AF 4 selection */ #define GPIO_AF4_I2C1 ((uint8_t)0x04) /* I2C1 Alternate Function mapping */ #define GPIO_AF4_I2C2 ((uint8_t)0x04) /* I2C2 Alternate Function mapping */ #define GPIO_AF4_I2C3 ((uint8_t)0x04) /* I2C3 Alternate Function mapping */ /** * @brief AF 5 selection */ #define GPIO_AF5_SPI1 ((uint8_t)0x05) /* SPI1/I2S1 Alternate Function mapping */ #define GPIO_AF5_SPI2 ((uint8_t)0x05) /* SPI2/I2S2 Alternate Function mapping */ #define GPIO_AF5_SPI3 ((uint8_t)0x05) /* SPI3/I2S3 Alternate Function mapping */ #define GPIO_AF5_SPI4 ((uint8_t)0x05) /* SPI4 Alternate Function mapping */ #define GPIO_AF5_I2S3ext ((uint8_t)0x05) /* I2S3ext_SD Alternate Function mapping */ /** * @brief AF 6 selection */ #define GPIO_AF6_SPI2 ((uint8_t)0x06) /* I2S2 Alternate Function mapping */ #define GPIO_AF6_SPI3 ((uint8_t)0x06) /* SPI3/I2S3 Alternate Function mapping */ #define GPIO_AF6_SPI4 ((uint8_t)0x06) /* SPI4/I2S4 Alternate Function mapping */ #define GPIO_AF6_SPI5 ((uint8_t)0x06) /* SPI5/I2S5 Alternate Function mapping */ #define GPIO_AF6_I2S2ext ((uint8_t)0x06) /* I2S2ext_SD Alternate Function mapping */ /** * @brief AF 7 selection */ #define GPIO_AF7_SPI3 ((uint8_t)0x07) /* SPI3/I2S3 Alternate Function mapping */ #define GPIO_AF7_USART1 ((uint8_t)0x07) /* USART1 Alternate Function mapping */ #define GPIO_AF7_USART2 ((uint8_t)0x07) /* USART2 Alternate Function mapping */ #define GPIO_AF7_I2S3ext ((uint8_t)0x07) /* I2S3ext_SD Alternate Function mapping */ /** * @brief AF 8 selection */ #define GPIO_AF8_USART6 ((uint8_t)0x08) /* USART6 Alternate Function mapping */ /** * @brief AF 9 selection */ #define GPIO_AF9_TIM14 ((uint8_t)0x09) /* TIM14 Alternate Function mapping */ #define GPIO_AF9_I2C2 ((uint8_t)0x09) /* I2C2 Alternate Function mapping */ #define GPIO_AF9_I2C3 ((uint8_t)0x09) /* I2C3 Alternate Function mapping */ /** * @brief AF 10 selection */ #define GPIO_AF10_OTG_FS ((uint8_t)0xA) /* OTG_FS Alternate Function mapping */ /** * @brief AF 12 selection */ #define GPIO_AF12_SDIO ((uint8_t)0xC) /* SDIO Alternate Function mapping */ /** * @brief AF 15 selection */ #define GPIO_AF15_EVENTOUT ((uint8_t)0x0F) /* EVENTOUT Alternate Function mapping */ #endif /* STM32F411xE */ /*---------------------------------------- STM32F410xx------------------------*/ #if defined(STM32F410Tx) || defined(STM32F410Cx) || defined(STM32F410Rx) /** * @brief AF 0 selection */ #define GPIO_AF0_RTC_50Hz ((uint8_t)0x00) /* RTC_50Hz Alternate Function mapping */ #define GPIO_AF0_MCO ((uint8_t)0x00) /* MCO (MCO1 and MCO2) Alternate Function mapping */ #define GPIO_AF0_TAMPER ((uint8_t)0x00) /* TAMPER (TAMPER_1 and TAMPER_2) Alternate Function mapping */ #define GPIO_AF0_SWJ ((uint8_t)0x00) /* SWJ (SWD and JTAG) Alternate Function mapping */ #define GPIO_AF0_TRACE ((uint8_t)0x00) /* TRACE Alternate Function mapping */ /** * @brief AF 1 selection */ #define GPIO_AF1_TIM1 ((uint8_t)0x01) /* TIM1 Alternate Function mapping */ #define GPIO_AF1_LPTIM1 ((uint8_t)0x01) /* LPTIM1 Alternate Function mapping */ /** * @brief AF 2 selection */ #define GPIO_AF2_TIM5 ((uint8_t)0x02) /* TIM5 Alternate Function mapping */ /** * @brief AF 3 selection */ #define GPIO_AF3_TIM9 ((uint8_t)0x03) /* TIM9 Alternate Function mapping */ #define GPIO_AF3_TIM11 ((uint8_t)0x03) /* TIM11 Alternate Function mapping */ /** * @brief AF 4 selection */ #define GPIO_AF4_I2C1 ((uint8_t)0x04) /* I2C1 Alternate Function mapping */ #define GPIO_AF4_I2C2 ((uint8_t)0x04) /* I2C2 Alternate Function mapping */ #define GPIO_AF4_FMPI2C1 ((uint8_t)0x04) /* FMPI2C1 Alternate Function mapping */ /** * @brief AF 5 selection */ #define GPIO_AF5_SPI1 ((uint8_t)0x05) /* SPI1/I2S1 Alternate Function mapping */ #if defined(STM32F410Cx) || defined(STM32F410Rx) #define GPIO_AF5_SPI2 ((uint8_t)0x05) /* SPI2/I2S2 Alternate Function mapping */ #endif /* STM32F410Cx || STM32F410Rx */ /** * @brief AF 6 selection */ #define GPIO_AF6_SPI1 ((uint8_t)0x06) /* SPI1 Alternate Function mapping */ #if defined(STM32F410Cx) || defined(STM32F410Rx) #define GPIO_AF6_SPI2 ((uint8_t)0x06) /* I2S2 Alternate Function mapping */ #endif /* STM32F410Cx || STM32F410Rx */ #define GPIO_AF6_SPI5 ((uint8_t)0x06) /* SPI5/I2S5 Alternate Function mapping */ /** * @brief AF 7 selection */ #define GPIO_AF7_USART1 ((uint8_t)0x07) /* USART1 Alternate Function mapping */ #define GPIO_AF7_USART2 ((uint8_t)0x07) /* USART2 Alternate Function mapping */ /** * @brief AF 8 selection */ #define GPIO_AF8_USART6 ((uint8_t)0x08) /* USART6 Alternate Function mapping */ /** * @brief AF 9 selection */ #define GPIO_AF9_I2C2 ((uint8_t)0x09) /* I2C2 Alternate Function mapping */ #define GPIO_AF9_FMPI2C1 ((uint8_t)0x09) /* FMPI2C1 Alternate Function mapping */ /** * @brief AF 15 selection */ #define GPIO_AF15_EVENTOUT ((uint8_t)0x0F) /* EVENTOUT Alternate Function mapping */ #endif /* STM32F410Tx || STM32F410Cx || STM32F410Rx */ /*---------------------------------------- STM32F446xx -----------------------*/ #if defined(STM32F446xx) /** * @brief AF 0 selection */ #define GPIO_AF0_RTC_50Hz ((uint8_t)0x00) /* RTC_50Hz Alternate Function mapping */ #define GPIO_AF0_MCO ((uint8_t)0x00) /* MCO (MCO1 and MCO2) Alternate Function mapping */ #define GPIO_AF0_TAMPER ((uint8_t)0x00) /* TAMPER (TAMPER_1 and TAMPER_2) Alternate Function mapping */ #define GPIO_AF0_SWJ ((uint8_t)0x00) /* SWJ (SWD and JTAG) Alternate Function mapping */ #define GPIO_AF0_TRACE ((uint8_t)0x00) /* TRACE Alternate Function mapping */ /** * @brief AF 1 selection */ #define GPIO_AF1_TIM1 ((uint8_t)0x01) /* TIM1 Alternate Function mapping */ #define GPIO_AF1_TIM2 ((uint8_t)0x01) /* TIM2 Alternate Function mapping */ /** * @brief AF 2 selection */ #define GPIO_AF2_TIM3 ((uint8_t)0x02) /* TIM3 Alternate Function mapping */ #define GPIO_AF2_TIM4 ((uint8_t)0x02) /* TIM4 Alternate Function mapping */ #define GPIO_AF2_TIM5 ((uint8_t)0x02) /* TIM5 Alternate Function mapping */ /** * @brief AF 3 selection */ #define GPIO_AF3_TIM8 ((uint8_t)0x03) /* TIM8 Alternate Function mapping */ #define GPIO_AF3_TIM9 ((uint8_t)0x03) /* TIM9 Alternate Function mapping */ #define GPIO_AF3_TIM10 ((uint8_t)0x03) /* TIM10 Alternate Function mapping */ #define GPIO_AF3_TIM11 ((uint8_t)0x03) /* TIM11 Alternate Function mapping */ #define GPIO_AF3_CEC ((uint8_t)0x03) /* CEC Alternate Function mapping */ /** * @brief AF 4 selection */ #define GPIO_AF4_I2C1 ((uint8_t)0x04) /* I2C1 Alternate Function mapping */ #define GPIO_AF4_I2C2 ((uint8_t)0x04) /* I2C2 Alternate Function mapping */ #define GPIO_AF4_I2C3 ((uint8_t)0x04) /* I2C3 Alternate Function mapping */ #define GPIO_AF4_FMPI2C1 ((uint8_t)0x04) /* FMPI2C1 Alternate Function mapping */ #define GPIO_AF4_CEC ((uint8_t)0x04) /* CEC Alternate Function mapping */ /** * @brief AF 5 selection */ #define GPIO_AF5_SPI1 ((uint8_t)0x05) /* SPI1/I2S1 Alternate Function mapping */ #define GPIO_AF5_SPI2 ((uint8_t)0x05) /* SPI2/I2S2 Alternate Function mapping */ #define GPIO_AF5_SPI3 ((uint8_t)0x05) /* SPI3/I2S3 Alternate Function mapping */ #define GPIO_AF5_SPI4 ((uint8_t)0x05) /* SPI4 Alternate Function mapping */ /** * @brief AF 6 selection */ #define GPIO_AF6_SPI2 ((uint8_t)0x06) /* SPI2/I2S2 Alternate Function mapping */ #define GPIO_AF6_SPI3 ((uint8_t)0x06) /* SPI3/I2S3 Alternate Function mapping */ #define GPIO_AF6_SPI4 ((uint8_t)0x06) /* SPI4 Alternate Function mapping */ #define GPIO_AF6_SAI1 ((uint8_t)0x06) /* SAI1 Alternate Function mapping */ /** * @brief AF 7 selection */ #define GPIO_AF7_USART1 ((uint8_t)0x07) /* USART1 Alternate Function mapping */ #define GPIO_AF7_USART2 ((uint8_t)0x07) /* USART2 Alternate Function mapping */ #define GPIO_AF7_USART3 ((uint8_t)0x07) /* USART3 Alternate Function mapping */ #define GPIO_AF7_UART5 ((uint8_t)0x07) /* UART5 Alternate Function mapping */ #define GPIO_AF7_SPI2 ((uint8_t)0x07) /* SPI2/I2S2 Alternate Function mapping */ #define GPIO_AF7_SPI3 ((uint8_t)0x07) /* SPI3/I2S3 Alternate Function mapping */ #define GPIO_AF7_SPDIFRX ((uint8_t)0x07) /* SPDIFRX Alternate Function mapping */ /** * @brief AF 8 selection */ #define GPIO_AF8_UART4 ((uint8_t)0x08) /* UART4 Alternate Function mapping */ #define GPIO_AF8_UART5 ((uint8_t)0x08) /* UART5 Alternate Function mapping */ #define GPIO_AF8_USART6 ((uint8_t)0x08) /* USART6 Alternate Function mapping */ #define GPIO_AF8_SPDIFRX ((uint8_t)0x08) /* SPDIFRX Alternate Function mapping */ #define GPIO_AF8_SAI2 ((uint8_t)0x08) /* SAI2 Alternate Function mapping */ /** * @brief AF 9 selection */ #define GPIO_AF9_CAN1 ((uint8_t)0x09) /* CAN1 Alternate Function mapping */ #define GPIO_AF9_CAN2 ((uint8_t)0x09) /* CAN2 Alternate Function mapping */ #define GPIO_AF9_TIM12 ((uint8_t)0x09) /* TIM12 Alternate Function mapping */ #define GPIO_AF9_TIM13 ((uint8_t)0x09) /* TIM13 Alternate Function mapping */ #define GPIO_AF9_TIM14 ((uint8_t)0x09) /* TIM14 Alternate Function mapping */ #define GPIO_AF9_QSPI ((uint8_t)0x09) /* QSPI Alternate Function mapping */ /** * @brief AF 10 selection */ #define GPIO_AF10_OTG_FS ((uint8_t)0xA) /* OTG_FS Alternate Function mapping */ #define GPIO_AF10_OTG_HS ((uint8_t)0xA) /* OTG_HS Alternate Function mapping */ #define GPIO_AF10_SAI2 ((uint8_t)0xA) /* SAI2 Alternate Function mapping */ #define GPIO_AF10_QSPI ((uint8_t)0xA) /* QSPI Alternate Function mapping */ /** * @brief AF 11 selection */ #define GPIO_AF11_ETH ((uint8_t)0x0B) /* ETHERNET Alternate Function mapping */ /** * @brief AF 12 selection */ #define GPIO_AF12_FMC ((uint8_t)0xC) /* FMC Alternate Function mapping */ #define GPIO_AF12_OTG_HS_FS ((uint8_t)0xC) /* OTG HS configured in FS, Alternate Function mapping */ #define GPIO_AF12_SDIO ((uint8_t)0xC) /* SDIO Alternate Function mapping */ /** * @brief AF 13 selection */ #define GPIO_AF13_DCMI ((uint8_t)0x0D) /* DCMI Alternate Function mapping */ /** * @brief AF 15 selection */ #define GPIO_AF15_EVENTOUT ((uint8_t)0x0F) /* EVENTOUT Alternate Function mapping */ #endif /* STM32F446xx */ /*----------------------------------------------------------------------------*/ /*-------------------------------- STM32F469xx/STM32F479xx--------------------*/ #if defined(STM32F469xx) || defined(STM32F479xx) /** * @brief AF 0 selection */ #define GPIO_AF0_RTC_50Hz ((uint8_t)0x00) /* RTC_50Hz Alternate Function mapping */ #define GPIO_AF0_MCO ((uint8_t)0x00) /* MCO (MCO1 and MCO2) Alternate Function mapping */ #define GPIO_AF0_TAMPER ((uint8_t)0x00) /* TAMPER (TAMPER_1 and TAMPER_2) Alternate Function mapping */ #define GPIO_AF0_SWJ ((uint8_t)0x00) /* SWJ (SWD and JTAG) Alternate Function mapping */ #define GPIO_AF0_TRACE ((uint8_t)0x00) /* TRACE Alternate Function mapping */ /** * @brief AF 1 selection */ #define GPIO_AF1_TIM1 ((uint8_t)0x01) /* TIM1 Alternate Function mapping */ #define GPIO_AF1_TIM2 ((uint8_t)0x01) /* TIM2 Alternate Function mapping */ /** * @brief AF 2 selection */ #define GPIO_AF2_TIM3 ((uint8_t)0x02) /* TIM3 Alternate Function mapping */ #define GPIO_AF2_TIM4 ((uint8_t)0x02) /* TIM4 Alternate Function mapping */ #define GPIO_AF2_TIM5 ((uint8_t)0x02) /* TIM5 Alternate Function mapping */ /** * @brief AF 3 selection */ #define GPIO_AF3_TIM8 ((uint8_t)0x03) /* TIM8 Alternate Function mapping */ #define GPIO_AF3_TIM9 ((uint8_t)0x03) /* TIM9 Alternate Function mapping */ #define GPIO_AF3_TIM10 ((uint8_t)0x03) /* TIM10 Alternate Function mapping */ #define GPIO_AF3_TIM11 ((uint8_t)0x03) /* TIM11 Alternate Function mapping */ /** * @brief AF 4 selection */ #define GPIO_AF4_I2C1 ((uint8_t)0x04) /* I2C1 Alternate Function mapping */ #define GPIO_AF4_I2C2 ((uint8_t)0x04) /* I2C2 Alternate Function mapping */ #define GPIO_AF4_I2C3 ((uint8_t)0x04) /* I2C3 Alternate Function mapping */ /** * @brief AF 5 selection */ #define GPIO_AF5_SPI1 ((uint8_t)0x05) /* SPI1 Alternate Function mapping */ #define GPIO_AF5_SPI2 ((uint8_t)0x05) /* SPI2/I2S2 Alternate Function mapping */ #define GPIO_AF5_SPI3 ((uint8_t)0x05) /* SPI3/I2S3 Alternate Function mapping */ #define GPIO_AF5_SPI4 ((uint8_t)0x05) /* SPI4 Alternate Function mapping */ #define GPIO_AF5_SPI5 ((uint8_t)0x05) /* SPI5 Alternate Function mapping */ #define GPIO_AF5_SPI6 ((uint8_t)0x05) /* SPI6 Alternate Function mapping */ #define GPIO_AF5_I2S3ext ((uint8_t)0x05) /* I2S3ext_SD Alternate Function mapping */ /** * @brief AF 6 selection */ #define GPIO_AF6_SPI3 ((uint8_t)0x06) /* SPI3/I2S3 Alternate Function mapping */ #define GPIO_AF6_I2S2ext ((uint8_t)0x06) /* I2S2ext_SD Alternate Function mapping */ #define GPIO_AF6_SAI1 ((uint8_t)0x06) /* SAI1 Alternate Function mapping */ /** * @brief AF 7 selection */ #define GPIO_AF7_USART1 ((uint8_t)0x07) /* USART1 Alternate Function mapping */ #define GPIO_AF7_USART2 ((uint8_t)0x07) /* USART2 Alternate Function mapping */ #define GPIO_AF7_USART3 ((uint8_t)0x07) /* USART3 Alternate Function mapping */ #define GPIO_AF7_I2S3ext ((uint8_t)0x07) /* I2S3ext_SD Alternate Function mapping */ /** * @brief AF 8 selection */ #define GPIO_AF8_UART4 ((uint8_t)0x08) /* UART4 Alternate Function mapping */ #define GPIO_AF8_UART5 ((uint8_t)0x08) /* UART5 Alternate Function mapping */ #define GPIO_AF8_USART6 ((uint8_t)0x08) /* USART6 Alternate Function mapping */ #define GPIO_AF8_UART7 ((uint8_t)0x08) /* UART7 Alternate Function mapping */ #define GPIO_AF8_UART8 ((uint8_t)0x08) /* UART8 Alternate Function mapping */ /** * @brief AF 9 selection */ #define GPIO_AF9_CAN1 ((uint8_t)0x09) /* CAN1 Alternate Function mapping */ #define GPIO_AF9_CAN2 ((uint8_t)0x09) /* CAN2 Alternate Function mapping */ #define GPIO_AF9_TIM12 ((uint8_t)0x09) /* TIM12 Alternate Function mapping */ #define GPIO_AF9_TIM13 ((uint8_t)0x09) /* TIM13 Alternate Function mapping */ #define GPIO_AF9_TIM14 ((uint8_t)0x09) /* TIM14 Alternate Function mapping */ #define GPIO_AF9_LTDC ((uint8_t)0x09) /* LCD-TFT Alternate Function mapping */ #define GPIO_AF9_QSPI ((uint8_t)0x09) /* QSPI Alternate Function mapping */ /** * @brief AF 10 selection */ #define GPIO_AF10_OTG_FS ((uint8_t)0xA) /* OTG_FS Alternate Function mapping */ #define GPIO_AF10_OTG_HS ((uint8_t)0xA) /* OTG_HS Alternate Function mapping */ #define GPIO_AF10_QSPI ((uint8_t)0xA) /* QSPI Alternate Function mapping */ /** * @brief AF 11 selection */ #define GPIO_AF11_ETH ((uint8_t)0x0B) /* ETHERNET Alternate Function mapping */ /** * @brief AF 12 selection */ #define GPIO_AF12_FMC ((uint8_t)0xC) /* FMC Alternate Function mapping */ #define GPIO_AF12_OTG_HS_FS ((uint8_t)0xC) /* OTG HS configured in FS, Alternate Function mapping */ #define GPIO_AF12_SDIO ((uint8_t)0xC) /* SDIO Alternate Function mapping */ /** * @brief AF 13 selection */ #define GPIO_AF13_DCMI ((uint8_t)0x0D) /* DCMI Alternate Function mapping */ #define GPIO_AF13_DSI ((uint8_t)0x0D) /* DSI Alternate Function mapping */ /** * @brief AF 14 selection */ #define GPIO_AF14_LTDC ((uint8_t)0x0E) /* LCD-TFT Alternate Function mapping */ /** * @brief AF 15 selection */ #define GPIO_AF15_EVENTOUT ((uint8_t)0x0F) /* EVENTOUT Alternate Function mapping */ #endif /* STM32F469xx || STM32F479xx */ /*----------------------------------------------------------------------------*/ /** * @} */ /** * @} */ /* Exported macro ------------------------------------------------------------*/ /** @defgroup GPIOEx_Exported_Macros GPIO Exported Macros * @{ */ /** * @} */ /* Exported functions --------------------------------------------------------*/ /** @defgroup GPIOEx_Exported_Functions GPIO Exported Functions * @{ */ /** * @} */ /* Private types -------------------------------------------------------------*/ /* Private variables ---------------------------------------------------------*/ /* Private constants ---------------------------------------------------------*/ /** @defgroup GPIOEx_Private_Constants GPIO Private Constants * @{ */ /** * @} */ /* Private macros ------------------------------------------------------------*/ /** @defgroup GPIOEx_Private_Macros GPIO Private Macros * @{ */ /** @defgroup GPIOEx_Get_Port_Index GPIO Get Port Index * @{ */ #if defined(STM32F405xx) || defined(STM32F415xx) || defined(STM32F407xx) || defined(STM32F417xx) #define GPIO_GET_INDEX(__GPIOx__) (uint8_t)(((__GPIOx__) == (GPIOA))? 0U :\ ((__GPIOx__) == (GPIOB))? 1U :\ ((__GPIOx__) == (GPIOC))? 2U :\ ((__GPIOx__) == (GPIOD))? 3U :\ ((__GPIOx__) == (GPIOE))? 4U :\ ((__GPIOx__) == (GPIOF))? 5U :\ ((__GPIOx__) == (GPIOG))? 6U :\ ((__GPIOx__) == (GPIOH))? 7U :\ ((__GPIOx__) == (GPIOI))? 8U : 9U) #endif /* STM32F405xx || STM32F415xx || STM32F407xx || STM32F417xx */ #if defined(STM32F427xx) || defined(STM32F437xx) || defined(STM32F429xx) || defined(STM32F439xx) ||\ defined(STM32F469xx) || defined(STM32F479xx) #define GPIO_GET_INDEX(__GPIOx__) (uint8_t)(((__GPIOx__) == (GPIOA))? 0U :\ ((__GPIOx__) == (GPIOB))? 1U :\ ((__GPIOx__) == (GPIOC))? 2U :\ ((__GPIOx__) == (GPIOD))? 3U :\ ((__GPIOx__) == (GPIOE))? 4U :\ ((__GPIOx__) == (GPIOF))? 5U :\ ((__GPIOx__) == (GPIOG))? 6U :\ ((__GPIOx__) == (GPIOH))? 7U :\ ((__GPIOx__) == (GPIOI))? 8U :\ ((__GPIOx__) == (GPIOJ))? 9U : 10U) #endif /* STM32F427xx || STM32F437xx || STM32F429xx || STM32F439xx || STM32F469xx || STM32F479xx */ #if defined(STM32F410Tx) || defined(STM32F410Cx) || defined(STM32F410Rx) #define GPIO_GET_INDEX(__GPIOx__) (uint8_t)(((__GPIOx__) == (GPIOA))? 0U :\ ((__GPIOx__) == (GPIOB))? 1U :\ ((__GPIOx__) == (GPIOC))? 2U :\ ((__GPIOx__) == (GPIOH))? 7U : 8U) #endif /* STM32F410Tx || STM32F410Cx || STM32F410Rx */ #if defined(STM32F401xC) || defined(STM32F401xE) || defined(STM32F411xE) #define GPIO_GET_INDEX(__GPIOx__) (uint8_t)(((__GPIOx__) == (GPIOA))? 0U :\ ((__GPIOx__) == (GPIOB))? 1U :\ ((__GPIOx__) == (GPIOC))? 2U :\ ((__GPIOx__) == (GPIOD))? 3U :\ ((__GPIOx__) == (GPIOE))? 4U : 5U) #endif /* STM32F401xC || STM32F401xE || STM32F411xE */ #if defined(STM32F446xx) #define GPIO_GET_INDEX(__GPIOx__) (uint8_t)(((__GPIOx__) == (GPIOA))? 0U :\ ((__GPIOx__) == (GPIOB))? 1U :\ ((__GPIOx__) == (GPIOC))? 2U :\ ((__GPIOx__) == (GPIOD))? 3U :\ ((__GPIOx__) == (GPIOE))? 4U :\ ((__GPIOx__) == (GPIOF))? 5U :\ ((__GPIOx__) == (GPIOG))? 6U : 8U) #endif /* STM32F446xx */ /** * @} */ /** @defgroup GPIOEx_IS_Alternat_function_selection GPIO Check Alternate Function * @{ */ /*------------------------- STM32F429xx/STM32F439xx---------------------------*/ #if defined(STM32F429xx) || defined(STM32F439xx) #define IS_GPIO_AF(AF) (((AF) == GPIO_AF0_RTC_50Hz) || ((AF) == GPIO_AF9_TIM14) || \ ((AF) == GPIO_AF0_MCO) || ((AF) == GPIO_AF0_TAMPER) || \ ((AF) == GPIO_AF0_SWJ) || ((AF) == GPIO_AF0_TRACE) || \ ((AF) == GPIO_AF1_TIM1) || ((AF) == GPIO_AF1_TIM2) || \ ((AF) == GPIO_AF2_TIM3) || ((AF) == GPIO_AF2_TIM4) || \ ((AF) == GPIO_AF2_TIM5) || ((AF) == GPIO_AF3_TIM8) || \ ((AF) == GPIO_AF4_I2C1) || ((AF) == GPIO_AF4_I2C2) || \ ((AF) == GPIO_AF4_I2C3) || ((AF) == GPIO_AF5_SPI1) || \ ((AF) == GPIO_AF5_SPI2) || ((AF) == GPIO_AF9_TIM13) || \ ((AF) == GPIO_AF6_SPI3) || ((AF) == GPIO_AF9_TIM12) || \ ((AF) == GPIO_AF7_USART1) || ((AF) == GPIO_AF7_USART2) || \ ((AF) == GPIO_AF7_USART3) || ((AF) == GPIO_AF8_UART4) || \ ((AF) == GPIO_AF8_UART5) || ((AF) == GPIO_AF8_USART6) || \ ((AF) == GPIO_AF9_CAN1) || ((AF) == GPIO_AF9_CAN2) || \ ((AF) == GPIO_AF10_OTG_FS) || ((AF) == GPIO_AF10_OTG_HS) || \ ((AF) == GPIO_AF11_ETH) || ((AF) == GPIO_AF12_OTG_HS_FS) || \ ((AF) == GPIO_AF12_SDIO) || ((AF) == GPIO_AF13_DCMI) || \ ((AF) == GPIO_AF15_EVENTOUT) || ((AF) == GPIO_AF5_SPI4) || \ ((AF) == GPIO_AF5_SPI5) || ((AF) == GPIO_AF5_SPI6) || \ ((AF) == GPIO_AF8_UART7) || ((AF) == GPIO_AF8_UART8) || \ ((AF) == GPIO_AF12_FMC) || ((AF) == GPIO_AF6_SAI1) || \ ((AF) == GPIO_AF14_LTDC)) #endif /* STM32F429xx || STM32F439xx */ /*----------------------------------------------------------------------------*/ /*---------------------------------- STM32F427xx/STM32F437xx------------------*/ #if defined(STM32F427xx) || defined(STM32F437xx) #define IS_GPIO_AF(AF) (((AF) == GPIO_AF0_RTC_50Hz) || ((AF) == GPIO_AF9_TIM14) || \ ((AF) == GPIO_AF0_MCO) || ((AF) == GPIO_AF0_TAMPER) || \ ((AF) == GPIO_AF0_SWJ) || ((AF) == GPIO_AF0_TRACE) || \ ((AF) == GPIO_AF1_TIM1) || ((AF) == GPIO_AF1_TIM2) || \ ((AF) == GPIO_AF2_TIM3) || ((AF) == GPIO_AF2_TIM4) || \ ((AF) == GPIO_AF2_TIM5) || ((AF) == GPIO_AF3_TIM8) || \ ((AF) == GPIO_AF4_I2C1) || ((AF) == GPIO_AF4_I2C2) || \ ((AF) == GPIO_AF4_I2C3) || ((AF) == GPIO_AF5_SPI1) || \ ((AF) == GPIO_AF5_SPI2) || ((AF) == GPIO_AF9_TIM13) || \ ((AF) == GPIO_AF6_SPI3) || ((AF) == GPIO_AF9_TIM12) || \ ((AF) == GPIO_AF7_USART1) || ((AF) == GPIO_AF7_USART2) || \ ((AF) == GPIO_AF7_USART3) || ((AF) == GPIO_AF8_UART4) || \ ((AF) == GPIO_AF8_UART5) || ((AF) == GPIO_AF8_USART6) || \ ((AF) == GPIO_AF9_CAN1) || ((AF) == GPIO_AF9_CAN2) || \ ((AF) == GPIO_AF10_OTG_FS) || ((AF) == GPIO_AF10_OTG_HS) || \ ((AF) == GPIO_AF11_ETH) || ((AF) == GPIO_AF12_OTG_HS_FS) || \ ((AF) == GPIO_AF12_SDIO) || ((AF) == GPIO_AF13_DCMI) || \ ((AF) == GPIO_AF15_EVENTOUT) || ((AF) == GPIO_AF5_SPI4) || \ ((AF) == GPIO_AF5_SPI5) || ((AF) == GPIO_AF5_SPI6) || \ ((AF) == GPIO_AF8_UART7) || ((AF) == GPIO_AF8_UART8) || \ ((AF) == GPIO_AF12_FMC) || ((AF) == GPIO_AF6_SAI1)) #endif /* STM32F427xx || STM32F437xx */ /*----------------------------------------------------------------------------*/ /*---------------------------------- STM32F407xx/STM32F417xx------------------*/ #if defined(STM32F407xx) || defined(STM32F417xx) #define IS_GPIO_AF(AF) (((AF) == GPIO_AF0_RTC_50Hz) || ((AF) == GPIO_AF9_TIM14) || \ ((AF) == GPIO_AF0_MCO) || ((AF) == GPIO_AF0_TAMPER) || \ ((AF) == GPIO_AF0_SWJ) || ((AF) == GPIO_AF0_TRACE) || \ ((AF) == GPIO_AF1_TIM1) || ((AF) == GPIO_AF1_TIM2) || \ ((AF) == GPIO_AF2_TIM3) || ((AF) == GPIO_AF2_TIM4) || \ ((AF) == GPIO_AF2_TIM5) || ((AF) == GPIO_AF3_TIM8) || \ ((AF) == GPIO_AF4_I2C1) || ((AF) == GPIO_AF4_I2C2) || \ ((AF) == GPIO_AF4_I2C3) || ((AF) == GPIO_AF5_SPI1) || \ ((AF) == GPIO_AF5_SPI2) || ((AF) == GPIO_AF9_TIM13) || \ ((AF) == GPIO_AF6_SPI3) || ((AF) == GPIO_AF9_TIM12) || \ ((AF) == GPIO_AF7_USART1) || ((AF) == GPIO_AF7_USART2) || \ ((AF) == GPIO_AF7_USART3) || ((AF) == GPIO_AF8_UART4) || \ ((AF) == GPIO_AF8_UART5) || ((AF) == GPIO_AF8_USART6) || \ ((AF) == GPIO_AF9_CAN1) || ((AF) == GPIO_AF9_CAN2) || \ ((AF) == GPIO_AF10_OTG_FS) || ((AF) == GPIO_AF10_OTG_HS) || \ ((AF) == GPIO_AF11_ETH) || ((AF) == GPIO_AF12_OTG_HS_FS) || \ ((AF) == GPIO_AF12_SDIO) || ((AF) == GPIO_AF13_DCMI) || \ ((AF) == GPIO_AF12_FSMC) || ((AF) == GPIO_AF15_EVENTOUT)) #endif /* STM32F407xx || STM32F417xx */ /*----------------------------------------------------------------------------*/ /*---------------------------------- STM32F405xx/STM32F415xx------------------*/ #if defined(STM32F405xx) || defined(STM32F415xx) #define IS_GPIO_AF(AF) (((AF) == GPIO_AF0_RTC_50Hz) || ((AF) == GPIO_AF9_TIM14) || \ ((AF) == GPIO_AF0_MCO) || ((AF) == GPIO_AF0_TAMPER) || \ ((AF) == GPIO_AF0_SWJ) || ((AF) == GPIO_AF0_TRACE) || \ ((AF) == GPIO_AF1_TIM1) || ((AF) == GPIO_AF1_TIM2) || \ ((AF) == GPIO_AF2_TIM3) || ((AF) == GPIO_AF2_TIM4) || \ ((AF) == GPIO_AF2_TIM5) || ((AF) == GPIO_AF3_TIM8) || \ ((AF) == GPIO_AF4_I2C1) || ((AF) == GPIO_AF4_I2C2) || \ ((AF) == GPIO_AF4_I2C3) || ((AF) == GPIO_AF5_SPI1) || \ ((AF) == GPIO_AF5_SPI2) || ((AF) == GPIO_AF9_TIM13) || \ ((AF) == GPIO_AF6_SPI3) || ((AF) == GPIO_AF9_TIM12) || \ ((AF) == GPIO_AF7_USART1) || ((AF) == GPIO_AF7_USART2) || \ ((AF) == GPIO_AF7_USART3) || ((AF) == GPIO_AF8_UART4) || \ ((AF) == GPIO_AF8_UART5) || ((AF) == GPIO_AF8_USART6) || \ ((AF) == GPIO_AF9_CAN1) || ((AF) == GPIO_AF9_CAN2) || \ ((AF) == GPIO_AF10_OTG_FS) || ((AF) == GPIO_AF10_OTG_HS) || \ ((AF) == GPIO_AF12_OTG_HS_FS) || ((AF) == GPIO_AF12_SDIO) || \ ((AF) == GPIO_AF12_FSMC) || ((AF) == GPIO_AF15_EVENTOUT)) #endif /* STM32F405xx || STM32F415xx */ /*----------------------------------------------------------------------------*/ /*---------------------------------------- STM32F401xx------------------------*/ #if defined(STM32F401xC) || defined(STM32F401xE) #define IS_GPIO_AF(AF) (((AF) == GPIO_AF0_RTC_50Hz) || ((AF) == GPIO_AF9_TIM14) || \ ((AF) == GPIO_AF0_MCO) || ((AF) == GPIO_AF0_TAMPER) || \ ((AF) == GPIO_AF0_SWJ) || ((AF) == GPIO_AF0_TRACE) || \ ((AF) == GPIO_AF1_TIM1) || ((AF) == GPIO_AF1_TIM2) || \ ((AF) == GPIO_AF2_TIM3) || ((AF) == GPIO_AF2_TIM4) || \ ((AF) == GPIO_AF2_TIM5) || ((AF) == GPIO_AF4_I2C1) || \ ((AF) == GPIO_AF4_I2C2) || ((AF) == GPIO_AF4_I2C3) || \ ((AF) == GPIO_AF5_SPI1) || ((AF) == GPIO_AF5_SPI2) || \ ((AF) == GPIO_AF6_SPI3) || ((AF) == GPIO_AF5_SPI4) || \ ((AF) == GPIO_AF7_USART1) || ((AF) == GPIO_AF7_USART2) || \ ((AF) == GPIO_AF8_USART6) || ((AF) == GPIO_AF10_OTG_FS) || \ ((AF) == GPIO_AF9_I2C2) || ((AF) == GPIO_AF9_I2C3) || \ ((AF) == GPIO_AF12_SDIO) || ((AF) == GPIO_AF15_EVENTOUT)) #endif /* STM32F401xC || STM32F401xE */ /*----------------------------------------------------------------------------*/ /*---------------------------------------- STM32F410xx------------------------*/ #if defined(STM32F410Tx) || defined(STM32F410Cx) || defined(STM32F410Rx) #define IS_GPIO_AF(AF) (((AF) < 10) || ((AF) == 15)) #endif /* STM32F410Tx || STM32F410Cx || STM32F410Rx */ /*---------------------------------------- STM32F411xx------------------------*/ #if defined(STM32F411xE) #define IS_GPIO_AF(AF) (((AF) == GPIO_AF0_RTC_50Hz) || ((AF) == GPIO_AF9_TIM14) || \ ((AF) == GPIO_AF0_MCO) || ((AF) == GPIO_AF0_TAMPER) || \ ((AF) == GPIO_AF0_SWJ) || ((AF) == GPIO_AF0_TRACE) || \ ((AF) == GPIO_AF1_TIM1) || ((AF) == GPIO_AF1_TIM2) || \ ((AF) == GPIO_AF2_TIM3) || ((AF) == GPIO_AF2_TIM4) || \ ((AF) == GPIO_AF2_TIM5) || ((AF) == GPIO_AF4_I2C1) || \ ((AF) == GPIO_AF4_I2C2) || ((AF) == GPIO_AF4_I2C3) || \ ((AF) == GPIO_AF5_SPI1) || ((AF) == GPIO_AF5_SPI2) || \ ((AF) == GPIO_AF5_SPI3) || ((AF) == GPIO_AF6_SPI4) || \ ((AF) == GPIO_AF6_SPI3) || ((AF) == GPIO_AF5_SPI4) || \ ((AF) == GPIO_AF6_SPI5) || ((AF) == GPIO_AF7_SPI3) || \ ((AF) == GPIO_AF7_USART1) || ((AF) == GPIO_AF7_USART2) || \ ((AF) == GPIO_AF8_USART6) || ((AF) == GPIO_AF10_OTG_FS) || \ ((AF) == GPIO_AF9_I2C2) || ((AF) == GPIO_AF9_I2C3) || \ ((AF) == GPIO_AF12_SDIO) || ((AF) == GPIO_AF15_EVENTOUT)) #endif /* STM32F411xE */ /*----------------------------------------------------------------------------*/ /*----------------------------------------------- STM32F446xx ----------------*/ #if defined(STM32F446xx) #define IS_GPIO_AF(AF) (((AF) == GPIO_AF0_RTC_50Hz) || ((AF) == GPIO_AF9_TIM14) || \ ((AF) == GPIO_AF0_MCO) || ((AF) == GPIO_AF0_TAMPER) || \ ((AF) == GPIO_AF0_SWJ) || ((AF) == GPIO_AF0_TRACE) || \ ((AF) == GPIO_AF1_TIM1) || ((AF) == GPIO_AF1_TIM2) || \ ((AF) == GPIO_AF2_TIM3) || ((AF) == GPIO_AF2_TIM4) || \ ((AF) == GPIO_AF2_TIM5) || ((AF) == GPIO_AF3_TIM8) || \ ((AF) == GPIO_AF4_I2C1) || ((AF) == GPIO_AF4_I2C2) || \ ((AF) == GPIO_AF4_I2C3) || ((AF) == GPIO_AF5_SPI1) || \ ((AF) == GPIO_AF5_SPI2) || ((AF) == GPIO_AF9_TIM13) || \ ((AF) == GPIO_AF6_SPI3) || ((AF) == GPIO_AF9_TIM12) || \ ((AF) == GPIO_AF7_USART1) || ((AF) == GPIO_AF7_USART2) || \ ((AF) == GPIO_AF7_USART3) || ((AF) == GPIO_AF8_UART4) || \ ((AF) == GPIO_AF8_UART5) || ((AF) == GPIO_AF8_USART6) || \ ((AF) == GPIO_AF9_CAN1) || ((AF) == GPIO_AF9_CAN2) || \ ((AF) == GPIO_AF10_OTG_FS) || ((AF) == GPIO_AF10_OTG_HS) || \ ((AF) == GPIO_AF11_ETH) || ((AF) == GPIO_AF12_OTG_HS_FS) || \ ((AF) == GPIO_AF12_SDIO) || ((AF) == GPIO_AF13_DCMI) || \ ((AF) == GPIO_AF15_EVENTOUT) || ((AF) == GPIO_AF5_SPI4) || \ ((AF) == GPIO_AF12_FMC) || ((AF) == GPIO_AF6_SAI1) || \ ((AF) == GPIO_AF3_CEC) || ((AF) == GPIO_AF4_CEC) || \ ((AF) == GPIO_AF5_SPI3) || ((AF) == GPIO_AF6_SPI2) || \ ((AF) == GPIO_AF6_SPI4) || ((AF) == GPIO_AF7_UART5) || \ ((AF) == GPIO_AF7_SPI2) || ((AF) == GPIO_AF7_SPI3) || \ ((AF) == GPIO_AF7_SPDIFRX) || ((AF) == GPIO_AF8_SPDIFRX) || \ ((AF) == GPIO_AF8_SAI2) || ((AF) == GPIO_AF9_QSPI) || \ ((AF) == GPIO_AF10_SAI2) || ((AF) == GPIO_AF10_QSPI)) #endif /* STM32F446xx */ /*----------------------------------------------------------------------------*/ /*------------------------------------------- STM32F469xx/STM32F479xx --------*/ #if defined(STM32F469xx) || defined(STM32F479xx) #define IS_GPIO_AF(AF) (((AF) == GPIO_AF0_RTC_50Hz) || ((AF) == GPIO_AF9_TIM14) || \ ((AF) == GPIO_AF0_MCO) || ((AF) == GPIO_AF0_TAMPER) || \ ((AF) == GPIO_AF0_SWJ) || ((AF) == GPIO_AF0_TRACE) || \ ((AF) == GPIO_AF1_TIM1) || ((AF) == GPIO_AF1_TIM2) || \ ((AF) == GPIO_AF2_TIM3) || ((AF) == GPIO_AF2_TIM4) || \ ((AF) == GPIO_AF2_TIM5) || ((AF) == GPIO_AF3_TIM8) || \ ((AF) == GPIO_AF4_I2C1) || ((AF) == GPIO_AF4_I2C2) || \ ((AF) == GPIO_AF4_I2C3) || ((AF) == GPIO_AF5_SPI1) || \ ((AF) == GPIO_AF5_SPI2) || ((AF) == GPIO_AF9_TIM13) || \ ((AF) == GPIO_AF6_SPI3) || ((AF) == GPIO_AF9_TIM12) || \ ((AF) == GPIO_AF7_USART1) || ((AF) == GPIO_AF7_USART2) || \ ((AF) == GPIO_AF7_USART3) || ((AF) == GPIO_AF8_UART4) || \ ((AF) == GPIO_AF8_UART5) || ((AF) == GPIO_AF8_USART6) || \ ((AF) == GPIO_AF9_CAN1) || ((AF) == GPIO_AF9_CAN2) || \ ((AF) == GPIO_AF10_OTG_FS) || ((AF) == GPIO_AF10_OTG_HS) || \ ((AF) == GPIO_AF11_ETH) || ((AF) == GPIO_AF12_OTG_HS_FS) || \ ((AF) == GPIO_AF12_SDIO) || ((AF) == GPIO_AF13_DCMI) || \ ((AF) == GPIO_AF15_EVENTOUT) || ((AF) == GPIO_AF5_SPI4) || \ ((AF) == GPIO_AF5_SPI5) || ((AF) == GPIO_AF5_SPI6) || \ ((AF) == GPIO_AF8_UART7) || ((AF) == GPIO_AF8_UART8) || \ ((AF) == GPIO_AF12_FMC) || ((AF) == GPIO_AF6_SAI1) || \ ((AF) == GPIO_AF14_LTDC) || ((AF) == GPIO_AF13_DSI) || \ ((AF) == GPIO_AF9_QSPI) || ((AF) == GPIO_AF10_QSPI)) #endif /* STM32F469xx || STM32F479xx */ /*----------------------------------------------------------------------------*/ /** * @} */ /** * @} */ /* Private functions ---------------------------------------------------------*/ /** @defgroup GPIOEx_Private_Functions GPIO Private Functions * @{ */ /** * @} */ /** * @} */ /** * @} */ #ifdef __cplusplus } #endif #endif /* __STM32F4xx_HAL_GPIO_EX_H */ /************************ (C) COPYRIGHT STMicroelectronics *****END OF FILE****/ ================================================ FILE: Zelig/mbed/TARGET_NUCLEO_F401RE/stm32f4xx_hal_hash.h ================================================ /** ****************************************************************************** * @file stm32f4xx_hal_hash.h * @author MCD Application Team * @version V1.4.1 * @date 09-October-2015 * @brief Header file of HASH HAL module. ****************************************************************************** * @attention * *

© COPYRIGHT(c) 2015 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. * ****************************************************************************** */ /* Define to prevent recursive inclusion -------------------------------------*/ #ifndef __STM32F4xx_HAL_HASH_H #define __STM32F4xx_HAL_HASH_H #ifdef __cplusplus extern "C" { #endif #if defined(STM32F415xx) || defined(STM32F417xx) || defined(STM32F437xx) || defined(STM32F439xx) || defined(STM32F479xx) /* Includes ------------------------------------------------------------------*/ #include "stm32f4xx_hal_def.h" /** @addtogroup STM32F4xx_HAL_Driver * @{ */ /** @addtogroup HASH * @brief HASH HAL module driver * @{ */ /* Exported types ------------------------------------------------------------*/ /** @defgroup HASH_Exported_Types HASH Exported Types * @{ */ /** @defgroup HASH_Exported_Types_Group1 HASH Configuration Structure definition * @{ */ typedef struct { uint32_t DataType; /*!< 32-bit data, 16-bit data, 8-bit data or 1-bit string. This parameter can be a value of @ref HASH DataType */ uint32_t KeySize; /*!< The key size is used only in HMAC operation */ uint8_t* pKey; /*!< The key is used only in HMAC operation */ }HASH_InitTypeDef; /** * @} */ /** @defgroup HASH_Exported_Types_Group2 HASH State structures definition * @{ */ typedef enum { HAL_HASH_STATE_RESET = 0x00, /*!< HASH not yet initialized or disabled */ HAL_HASH_STATE_READY = 0x01, /*!< HASH initialized and ready for use */ HAL_HASH_STATE_BUSY = 0x02, /*!< HASH internal process is ongoing */ HAL_HASH_STATE_TIMEOUT = 0x03, /*!< HASH timeout state */ HAL_HASH_STATE_ERROR = 0x04 /*!< HASH error state */ }HAL_HASH_STATETypeDef; /** * @} */ /** @defgroup HASH_Exported_Types_Group3 HASH phase structures definition * @{ */ typedef enum { HAL_HASH_PHASE_READY = 0x01, /*!< HASH peripheral is ready for initialization */ HAL_HASH_PHASE_PROCESS = 0x02, /*!< HASH peripheral is in processing phase */ }HAL_HASHPhaseTypeDef; /** * @} */ /** @defgroup HASH_Exported_Types_Group4 HASH Handle structures definition * @{ */ typedef struct { HASH_InitTypeDef Init; /*!< HASH required parameters */ uint8_t *pHashInBuffPtr; /*!< Pointer to input buffer */ uint8_t *pHashOutBuffPtr; /*!< Pointer to input buffer */ __IO uint32_t HashBuffSize; /*!< Size of buffer to be processed */ __IO uint32_t HashInCount; /*!< Counter of inputed data */ __IO uint32_t HashITCounter; /*!< Counter of issued interrupts */ HAL_StatusTypeDef Status; /*!< HASH peripheral status */ HAL_HASHPhaseTypeDef Phase; /*!< HASH peripheral phase */ DMA_HandleTypeDef *hdmain; /*!< HASH In DMA handle parameters */ HAL_LockTypeDef Lock; /*!< HASH locking object */ __IO HAL_HASH_STATETypeDef State; /*!< HASH peripheral state */ } HASH_HandleTypeDef; /** * @} */ /** * @} */ /* Exported constants --------------------------------------------------------*/ /** @defgroup HASH_Exported_Constants HASH Exported Constants * @{ */ /** @defgroup HASH_Exported_Constants_Group1 HASH Algorithm Selection * @{ */ #define HASH_ALGOSELECTION_SHA1 ((uint32_t)0x0000) /*!< HASH function is SHA1 */ #define HASH_ALGOSELECTION_SHA224 HASH_CR_ALGO_1 /*!< HASH function is SHA224 */ #define HASH_ALGOSELECTION_SHA256 HASH_CR_ALGO /*!< HASH function is SHA256 */ #define HASH_ALGOSELECTION_MD5 HASH_CR_ALGO_0 /*!< HASH function is MD5 */ /** * @} */ /** @defgroup HASH_Exported_Constants_Group2 HASH Algorithm Mode * @{ */ #define HASH_ALGOMODE_HASH ((uint32_t)0x00000000) /*!< Algorithm is HASH */ #define HASH_ALGOMODE_HMAC HASH_CR_MODE /*!< Algorithm is HMAC */ /** * @} */ /** @defgroup HASH_Exported_Constants_Group3 HASH DataType * @{ */ #define HASH_DATATYPE_32B ((uint32_t)0x0000) /*!< 32-bit data. No swapping */ #define HASH_DATATYPE_16B HASH_CR_DATATYPE_0 /*!< 16-bit data. Each half word is swapped */ #define HASH_DATATYPE_8B HASH_CR_DATATYPE_1 /*!< 8-bit data. All bytes are swapped */ #define HASH_DATATYPE_1B HASH_CR_DATATYPE /*!< 1-bit data. In the word all bits are swapped */ /** * @} */ /** @defgroup HASH_Exported_Constants_Group4 HASH HMAC Long key * @brief HASH HMAC Long key used only for HMAC mode * @{ */ #define HASH_HMAC_KEYTYPE_SHORTKEY ((uint32_t)0x00000000) /*!< HMAC Key is <= 64 bytes */ #define HASH_HMAC_KEYTYPE_LONGKEY HASH_CR_LKEY /*!< HMAC Key is > 64 bytes */ /** * @} */ /** @defgroup HASH_Exported_Constants_Group5 HASH Flags definition * @{ */ #define HASH_FLAG_DINIS HASH_SR_DINIS /*!< 16 locations are free in the DIN : A new block can be entered into the input buffer */ #define HASH_FLAG_DCIS HASH_SR_DCIS /*!< Digest calculation complete */ #define HASH_FLAG_DMAS HASH_SR_DMAS /*!< DMA interface is enabled (DMAE=1) or a transfer is ongoing */ #define HASH_FLAG_BUSY HASH_SR_BUSY /*!< The hash core is Busy : processing a block of data */ #define HASH_FLAG_DINNE HASH_CR_DINNE /*!< DIN not empty : The input buffer contains at least one word of data */ /** * @} */ /** @defgroup HASH_Exported_Constants_Group6 HASH Interrupts definition * @{ */ #define HASH_IT_DINI HASH_IMR_DINIE /*!< A new block can be entered into the input buffer (DIN) */ #define HASH_IT_DCI HASH_IMR_DCIE /*!< Digest calculation complete */ /** * @} */ /** * @} */ /* Exported macro ------------------------------------------------------------*/ /** @defgroup HASH_Exported_Macros HASH Exported Macros * @{ */ /** @brief Reset HASH handle state * @param __HANDLE__: specifies the HASH handle. * @retval None */ #define __HAL_HASH_RESET_HANDLE_STATE(__HANDLE__) ((__HANDLE__)->State = HAL_HASH_STATE_RESET) /** @brief Check whether the specified HASH flag is set or not. * @param __FLAG__: specifies the flag to check. * This parameter can be one of the following values: * @arg HASH_FLAG_DINIS: A new block can be entered into the input buffer. * @arg HASH_FLAG_DCIS: Digest calculation complete * @arg HASH_FLAG_DMAS: DMA interface is enabled (DMAE=1) or a transfer is ongoing * @arg HASH_FLAG_BUSY: The hash core is Busy : processing a block of data * @arg HASH_FLAG_DINNE: DIN not empty : The input buffer contains at least one word of data * @retval The new state of __FLAG__ (TRUE or FALSE). */ #define __HAL_HASH_GET_FLAG(__FLAG__) (((__FLAG__) > 8U) ? ((HASH->CR & (__FLAG__)) == (__FLAG__)) :\ ((HASH->SR & (__FLAG__)) == (__FLAG__))) /** * @brief Enable the multiple DMA mode. * This feature is available only in STM32F429x and STM32F439x devices. * @retval None */ #define __HAL_HASH_SET_MDMAT() HASH->CR |= HASH_CR_MDMAT /** * @brief Disable the multiple DMA mode. * @retval None */ #define __HAL_HASH_RESET_MDMAT() HASH->CR &= (uint32_t)(~HASH_CR_MDMAT) /** * @brief Start the digest computation * @retval None */ #define __HAL_HASH_START_DIGEST() HASH->STR |= HASH_STR_DCAL /** * @brief Set the number of valid bits in last word written in Data register * @param SIZE: size in byte of last data written in Data register. * @retval None */ #define __HAL_HASH_SET_NBVALIDBITS(SIZE) do{HASH->STR &= ~(HASH_STR_NBLW);\ HASH->STR |= 8 * ((SIZE) % 4);\ }while(0) /** * @} */ /* Include HASH HAL Extension module */ #include "stm32f4xx_hal_hash_ex.h" /* Exported functions --------------------------------------------------------*/ /** @defgroup HASH_Exported_Functions HASH Exported Functions * @{ */ /** @addtogroup HASH_Exported_Functions_Group1 * @{ */ HAL_StatusTypeDef HAL_HASH_Init(HASH_HandleTypeDef *hhash); HAL_StatusTypeDef HAL_HASH_DeInit(HASH_HandleTypeDef *hhash); /** * @} */ /** @addtogroup HASH_Exported_Functions_Group2 * @{ */ HAL_StatusTypeDef HAL_HASH_SHA1_Start(HASH_HandleTypeDef *hhash, uint8_t *pInBuffer, uint32_t Size, uint8_t* pOutBuffer, uint32_t Timeout); HAL_StatusTypeDef HAL_HASH_MD5_Start(HASH_HandleTypeDef *hhash, uint8_t *pInBuffer, uint32_t Size, uint8_t* pOutBuffer, uint32_t Timeout); HAL_StatusTypeDef HAL_HASH_MD5_Accumulate(HASH_HandleTypeDef *hhash, uint8_t *pInBuffer, uint32_t Size); HAL_StatusTypeDef HAL_HASH_SHA1_Accumulate(HASH_HandleTypeDef *hhash, uint8_t *pInBuffer, uint32_t Size); /** * @} */ /** @addtogroup HASH_Exported_Functions_Group3 * @{ */ HAL_StatusTypeDef HAL_HMAC_SHA1_Start(HASH_HandleTypeDef *hhash, uint8_t *pInBuffer, uint32_t Size, uint8_t* pOutBuffer, uint32_t Timeout); HAL_StatusTypeDef HAL_HMAC_MD5_Start(HASH_HandleTypeDef *hhash, uint8_t *pInBuffer, uint32_t Size, uint8_t* pOutBuffer, uint32_t Timeout); /** * @} */ /** @addtogroup HASH_Exported_Functions_Group4 * @{ */ HAL_StatusTypeDef HAL_HASH_SHA1_Start_IT(HASH_HandleTypeDef *hhash, uint8_t *pInBuffer, uint32_t Size, uint8_t* pOutBuffer); HAL_StatusTypeDef HAL_HASH_MD5_Start_IT(HASH_HandleTypeDef *hhash, uint8_t *pInBuffer, uint32_t Size, uint8_t* pOutBuffer); /** * @} */ /** @addtogroup HASH_Exported_Functions_Group5 * @{ */ HAL_StatusTypeDef HAL_HASH_SHA1_Start_DMA(HASH_HandleTypeDef *hhash, uint8_t *pInBuffer, uint32_t Size); HAL_StatusTypeDef HAL_HASH_SHA1_Finish(HASH_HandleTypeDef *hhash, uint8_t* pOutBuffer, uint32_t Timeout); HAL_StatusTypeDef HAL_HASH_MD5_Start_DMA(HASH_HandleTypeDef *hhash, uint8_t *pInBuffer, uint32_t Size); HAL_StatusTypeDef HAL_HASH_MD5_Finish(HASH_HandleTypeDef *hhash, uint8_t* pOutBuffer, uint32_t Timeout); /** * @} */ /** @addtogroup HASH_Exported_Functions_Group6 * @{ */ HAL_StatusTypeDef HAL_HMAC_SHA1_Start_DMA(HASH_HandleTypeDef *hhash, uint8_t *pInBuffer, uint32_t Size); HAL_StatusTypeDef HAL_HMAC_MD5_Start_DMA(HASH_HandleTypeDef *hhash, uint8_t *pInBuffer, uint32_t Size); /** * @} */ /** @addtogroup HASH_Exported_Functions_Group7 * @{ */ void HAL_HASH_IRQHandler(HASH_HandleTypeDef *hhash); /** * @} */ /** @addtogroup HASH_Exported_Functions_Group8 * @{ */ HAL_HASH_STATETypeDef HAL_HASH_GetState(HASH_HandleTypeDef *hhash); void HAL_HASH_MspInit(HASH_HandleTypeDef *hhash); void HAL_HASH_MspDeInit(HASH_HandleTypeDef *hhash); void HAL_HASH_InCpltCallback(HASH_HandleTypeDef *hhash); void HAL_HASH_DgstCpltCallback(HASH_HandleTypeDef *hhash); void HAL_HASH_ErrorCallback(HASH_HandleTypeDef *hhash); /** * @} */ /** * @} */ /* Private types -------------------------------------------------------------*/ /** @defgroup HASH_Private_Types HASH Private Types * @{ */ /** * @} */ /* Private variables ---------------------------------------------------------*/ /** @defgroup HASH_Private_Variables HASH Private Variables * @{ */ /** * @} */ /* Private constants ---------------------------------------------------------*/ /** @defgroup HASH_Private_Constants HASH Private Constants * @{ */ /** * @} */ /* Private macros ------------------------------------------------------------*/ /** @defgroup HASH_Private_Macros HASH Private Macros * @{ */ #define IS_HASH_ALGOSELECTION(__ALGOSELECTION__) (((__ALGOSELECTION__) == HASH_ALGOSELECTION_SHA1) || \ ((__ALGOSELECTION__) == HASH_ALGOSELECTION_SHA224) || \ ((__ALGOSELECTION__) == HASH_ALGOSELECTION_SHA256) || \ ((__ALGOSELECTION__) == HASH_ALGOSELECTION_MD5)) #define IS_HASH_ALGOMODE(__ALGOMODE__) (((__ALGOMODE__) == HASH_ALGOMODE_HASH) || \ ((__ALGOMODE__) == HASH_ALGOMODE_HMAC)) #define IS_HASH_DATATYPE(__DATATYPE__) (((__DATATYPE__) == HASH_DATATYPE_32B)|| \ ((__DATATYPE__) == HASH_DATATYPE_16B)|| \ ((__DATATYPE__) == HASH_DATATYPE_8B) || \ ((__DATATYPE__) == HASH_DATATYPE_1B)) #define IS_HASH_HMAC_KEYTYPE(__KEYTYPE__) (((__KEYTYPE__) == HASH_HMAC_KEYTYPE_SHORTKEY) || \ ((__KEYTYPE__) == HASH_HMAC_KEYTYPE_LONGKEY)) #define IS_HASH_SHA1_BUFFER_SIZE(__SIZE__) ((((__SIZE__)%4) != 0)? 0U: 1U) /** * @} */ /* Private functions ---------------------------------------------------------*/ /** @defgroup HASH_Private_Functions HASH Private Functions * @{ */ /** * @} */ #endif /* STM32F415xx || STM32F417xx || STM32F437xx || STM32F439xx || STM32F479xx */ /** * @} */ /** * @} */ #ifdef __cplusplus } #endif #endif /* __STM32F4xx_HAL_HASH_H */ /************************ (C) COPYRIGHT STMicroelectronics *****END OF FILE****/ ================================================ FILE: Zelig/mbed/TARGET_NUCLEO_F401RE/stm32f4xx_hal_hash_ex.h ================================================ /** ****************************************************************************** * @file stm32f4xx_hal_hash_ex.h * @author MCD Application Team * @version V1.4.1 * @date 09-October-2015 * @brief Header file of HASH HAL Extension module. ****************************************************************************** * @attention * *

© COPYRIGHT(c) 2015 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. * ****************************************************************************** */ /* Define to prevent recursive inclusion -------------------------------------*/ #ifndef __STM32F4xx_HAL_HASH_EX_H #define __STM32F4xx_HAL_HASH_EX_H #ifdef __cplusplus extern "C" { #endif #if defined(STM32F437xx) || defined(STM32F439xx) || defined(STM32F479xx) /* Includes ------------------------------------------------------------------*/ #include "stm32f4xx_hal_def.h" /** @addtogroup STM32F4xx_HAL_Driver * @{ */ /** @addtogroup HASHEx * @brief HASHEx HAL Extension module driver * @{ */ /* Exported types ------------------------------------------------------------*/ /* Exported constants --------------------------------------------------------*/ /* Exported macro ------------------------------------------------------------*/ /* Exported functions --------------------------------------------------------*/ /** @defgroup HASHEx_Exported_Functions HASHEx Exported Functions * @{ */ /** @defgroup HASHEx_Exported_Functions_Group1 HASHEx processing using polling functions * @{ */ HAL_StatusTypeDef HAL_HASHEx_SHA224_Start(HASH_HandleTypeDef *hhash, uint8_t *pInBuffer, uint32_t Size, uint8_t* pOutBuffer, uint32_t Timeout); HAL_StatusTypeDef HAL_HASHEx_SHA256_Start(HASH_HandleTypeDef *hhash, uint8_t *pInBuffer, uint32_t Size, uint8_t* pOutBuffer, uint32_t Timeout); HAL_StatusTypeDef HAL_HASHEx_SHA224_Accumulate(HASH_HandleTypeDef *hhash, uint8_t *pInBuffer, uint32_t Size); HAL_StatusTypeDef HAL_HASHEx_SHA256_Accumulate(HASH_HandleTypeDef *hhash, uint8_t *pInBuffer, uint32_t Size); /** * @} */ /** @defgroup HASHEx_Exported_Functions_Group2 HMAC processing using polling functions * @{ */ HAL_StatusTypeDef HAL_HMACEx_SHA224_Start(HASH_HandleTypeDef *hhash, uint8_t *pInBuffer, uint32_t Size, uint8_t* pOutBuffer, uint32_t Timeout); HAL_StatusTypeDef HAL_HMACEx_SHA256_Start(HASH_HandleTypeDef *hhash, uint8_t *pInBuffer, uint32_t Size, uint8_t* pOutBuffer, uint32_t Timeout); /** * @} */ /** @defgroup HASHEx_Exported_Functions_Group3 HASHEx processing using functions * @{ */ HAL_StatusTypeDef HAL_HASHEx_SHA224_Start_IT(HASH_HandleTypeDef *hhash, uint8_t *pInBuffer, uint32_t Size, uint8_t* pOutBuffer); HAL_StatusTypeDef HAL_HASHEx_SHA256_Start_IT(HASH_HandleTypeDef *hhash, uint8_t *pInBuffer, uint32_t Size, uint8_t* pOutBuffer); /** * @} */ /** @defgroup HASHEx_Exported_Functions_Group4 HASHEx processing using DMA * @{ */ HAL_StatusTypeDef HAL_HASHEx_SHA224_Start_DMA(HASH_HandleTypeDef *hhash, uint8_t *pInBuffer, uint32_t Size); HAL_StatusTypeDef HAL_HASHEx_SHA224_Finish(HASH_HandleTypeDef *hhash, uint8_t* pOutBuffer, uint32_t Timeout); HAL_StatusTypeDef HAL_HASHEx_SHA256_Start_DMA(HASH_HandleTypeDef *hhash, uint8_t *pInBuffer, uint32_t Size); HAL_StatusTypeDef HAL_HASHEx_SHA256_Finish(HASH_HandleTypeDef *hhash, uint8_t* pOutBuffer, uint32_t Timeout); /** * @} */ /** @defgroup HASHEx_Exported_Functions_Group5 HMAC processing using DMA * @{ */ HAL_StatusTypeDef HAL_HMACEx_SHA224_Start_DMA(HASH_HandleTypeDef *hhash, uint8_t *pInBuffer, uint32_t Size); HAL_StatusTypeDef HAL_HMACEx_SHA256_Start_DMA(HASH_HandleTypeDef *hhash, uint8_t *pInBuffer, uint32_t Size); /** * @} */ /** @defgroup HASHEx_Exported_Functions_Group6 HASHEx processing functions * @{ */ void HAL_HASHEx_IRQHandler(HASH_HandleTypeDef *hhash); /** * @} */ /** * @} */ /* Private types -------------------------------------------------------------*/ /** @defgroup HASHEx_Private_Types HASHEx Private Types * @{ */ /** * @} */ /* Private variables ---------------------------------------------------------*/ /** @defgroup HASHEx_Private_Variables HASHEx Private Variables * @{ */ /** * @} */ /* Private constants ---------------------------------------------------------*/ /** @defgroup HASHEx_Private_Constants HASHEx Private Constants * @{ */ /** * @} */ /* Private macros ------------------------------------------------------------*/ /** @defgroup HASHEx_Private_Macros HASHEx Private Macros * @{ */ /** * @} */ /* Private functions ---------------------------------------------------------*/ /** @defgroup HASHEx_Private_Functions HASHEx Private Functions * @{ */ /** * @} */ #endif /* STM32F437xx || STM32F439xx || STM32F479xx */ /** * @} */ /** * @} */ #ifdef __cplusplus } #endif #endif /* __STM32F4xx_HAL_HASH_EX_H */ /************************ (C) COPYRIGHT STMicroelectronics *****END OF FILE****/ ================================================ FILE: Zelig/mbed/TARGET_NUCLEO_F401RE/stm32f4xx_hal_hcd.h ================================================ /** ****************************************************************************** * @file stm32f4xx_hal_hcd.h * @author MCD Application Team * @version V1.4.1 * @date 09-October-2015 * @brief Header file of HCD HAL module. ****************************************************************************** * @attention * *

© COPYRIGHT(c) 2015 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. * ****************************************************************************** */ /* Define to prevent recursive inclusion -------------------------------------*/ #ifndef __STM32F4xx_HAL_HCD_H #define __STM32F4xx_HAL_HCD_H #ifdef __cplusplus extern "C" { #endif #if defined(STM32F405xx) || defined(STM32F415xx) || defined(STM32F407xx) || defined(STM32F417xx) || \ defined(STM32F427xx) || defined(STM32F437xx) || defined(STM32F429xx) || defined(STM32F439xx) || \ defined(STM32F401xC) || defined(STM32F401xE) || defined(STM32F411xE) || defined(STM32F446xx) || \ defined(STM32F469xx) || defined(STM32F479xx) /* Includes ------------------------------------------------------------------*/ #include "stm32f4xx_ll_usb.h" /** @addtogroup STM32F4xx_HAL_Driver * @{ */ /** @addtogroup HCD * @{ */ /* Exported types ------------------------------------------------------------*/ /** @defgroup HCD_Exported_Types HCD Exported Types * @{ */ /** @defgroup HCD_Exported_Types_Group1 HCD State Structure definition * @{ */ typedef enum { HAL_HCD_STATE_RESET = 0x00, HAL_HCD_STATE_READY = 0x01, HAL_HCD_STATE_ERROR = 0x02, HAL_HCD_STATE_BUSY = 0x03, HAL_HCD_STATE_TIMEOUT = 0x04 } HCD_StateTypeDef; typedef USB_OTG_GlobalTypeDef HCD_TypeDef; typedef USB_OTG_CfgTypeDef HCD_InitTypeDef; typedef USB_OTG_HCTypeDef HCD_HCTypeDef ; typedef USB_OTG_URBStateTypeDef HCD_URBStateTypeDef ; typedef USB_OTG_HCStateTypeDef HCD_HCStateTypeDef ; /** * @} */ /** @defgroup HCD_Exported_Types_Group2 HCD Handle Structure definition * @{ */ typedef struct { HCD_TypeDef *Instance; /*!< Register base address */ HCD_InitTypeDef Init; /*!< HCD required parameters */ HCD_HCTypeDef hc[15]; /*!< Host channels parameters */ HAL_LockTypeDef Lock; /*!< HCD peripheral status */ __IO HCD_StateTypeDef State; /*!< HCD communication state */ void *pData; /*!< Pointer Stack Handler */ } HCD_HandleTypeDef; /** * @} */ /** * @} */ /* Exported constants --------------------------------------------------------*/ /** @defgroup HCD_Exported_Constants HCD Exported Constants * @{ */ /** @defgroup HCD_Speed HCD Speed * @{ */ #define HCD_SPEED_HIGH 0 #define HCD_SPEED_LOW 2 #define HCD_SPEED_FULL 3 /** * @} */ /** @defgroup HCD_PHY_Module HCD PHY Module * @{ */ #define HCD_PHY_ULPI 1 #define HCD_PHY_EMBEDDED 2 /** * @} */ /** * @} */ /* Exported macro ------------------------------------------------------------*/ /** @defgroup HCD_Exported_Macros HCD Exported Macros * @brief macros to handle interrupts and specific clock configurations * @{ */ #define __HAL_HCD_ENABLE(__HANDLE__) USB_EnableGlobalInt ((__HANDLE__)->Instance) #define __HAL_HCD_DISABLE(__HANDLE__) USB_DisableGlobalInt ((__HANDLE__)->Instance) #define __HAL_HCD_GET_FLAG(__HANDLE__, __INTERRUPT__) ((USB_ReadInterrupts((__HANDLE__)->Instance) & (__INTERRUPT__)) == (__INTERRUPT__)) #define __HAL_HCD_CLEAR_FLAG(__HANDLE__, __INTERRUPT__) (((__HANDLE__)->Instance->GINTSTS) = (__INTERRUPT__)) #define __HAL_HCD_IS_INVALID_INTERRUPT(__HANDLE__) (USB_ReadInterrupts((__HANDLE__)->Instance) == 0) #define __HAL_HCD_CLEAR_HC_INT(chnum, __INTERRUPT__) (USBx_HC(chnum)->HCINT = (__INTERRUPT__)) #define __HAL_HCD_MASK_HALT_HC_INT(chnum) (USBx_HC(chnum)->HCINTMSK &= ~USB_OTG_HCINTMSK_CHHM) #define __HAL_HCD_UNMASK_HALT_HC_INT(chnum) (USBx_HC(chnum)->HCINTMSK |= USB_OTG_HCINTMSK_CHHM) #define __HAL_HCD_MASK_ACK_HC_INT(chnum) (USBx_HC(chnum)->HCINTMSK &= ~USB_OTG_HCINTMSK_ACKM) #define __HAL_HCD_UNMASK_ACK_HC_INT(chnum) (USBx_HC(chnum)->HCINTMSK |= USB_OTG_HCINTMSK_ACKM) /** * @} */ /* Exported functions --------------------------------------------------------*/ /** @addtogroup HCD_Exported_Functions HCD Exported Functions * @{ */ /* Initialization/de-initialization functions ********************************/ /** @addtogroup HCD_Exported_Functions_Group1 Initialization and de-initialization functions * @{ */ HAL_StatusTypeDef HAL_HCD_Init(HCD_HandleTypeDef *hhcd); HAL_StatusTypeDef HAL_HCD_DeInit(HCD_HandleTypeDef *hhcd); HAL_StatusTypeDef HAL_HCD_HC_Init(HCD_HandleTypeDef *hhcd, uint8_t ch_num, uint8_t epnum, uint8_t dev_address, uint8_t speed, uint8_t ep_type, uint16_t mps); HAL_StatusTypeDef HAL_HCD_HC_Halt(HCD_HandleTypeDef *hhcd, uint8_t ch_num); void HAL_HCD_MspInit(HCD_HandleTypeDef *hhcd); void HAL_HCD_MspDeInit(HCD_HandleTypeDef *hhcd); /** * @} */ /* I/O operation functions ***************************************************/ /** @addtogroup HCD_Exported_Functions_Group2 Input and Output operation functions * @{ */ HAL_StatusTypeDef HAL_HCD_HC_SubmitRequest(HCD_HandleTypeDef *hhcd, uint8_t pipe, uint8_t direction, uint8_t ep_type, uint8_t token, uint8_t* pbuff, uint16_t length, uint8_t do_ping); /* Non-Blocking mode: Interrupt */ void HAL_HCD_IRQHandler(HCD_HandleTypeDef *hhcd); void HAL_HCD_SOF_Callback(HCD_HandleTypeDef *hhcd); void HAL_HCD_Connect_Callback(HCD_HandleTypeDef *hhcd); void HAL_HCD_Disconnect_Callback(HCD_HandleTypeDef *hhcd); void HAL_HCD_HC_NotifyURBChange_Callback(HCD_HandleTypeDef *hhcd, uint8_t chnum, HCD_URBStateTypeDef urb_state); /** * @} */ /* Peripheral Control functions **********************************************/ /** @addtogroup HCD_Exported_Functions_Group3 Peripheral Control functions * @{ */ HAL_StatusTypeDef HAL_HCD_ResetPort(HCD_HandleTypeDef *hhcd); HAL_StatusTypeDef HAL_HCD_Start(HCD_HandleTypeDef *hhcd); HAL_StatusTypeDef HAL_HCD_Stop(HCD_HandleTypeDef *hhcd); /** * @} */ /* Peripheral State functions ************************************************/ /** @addtogroup HCD_Exported_Functions_Group4 Peripheral State functions * @{ */ HCD_StateTypeDef HAL_HCD_GetState(HCD_HandleTypeDef *hhcd); HCD_URBStateTypeDef HAL_HCD_HC_GetURBState(HCD_HandleTypeDef *hhcd, uint8_t chnum); uint32_t HAL_HCD_HC_GetXferCount(HCD_HandleTypeDef *hhcd, uint8_t chnum); HCD_HCStateTypeDef HAL_HCD_HC_GetState(HCD_HandleTypeDef *hhcd, uint8_t chnum); uint32_t HAL_HCD_GetCurrentFrame(HCD_HandleTypeDef *hhcd); uint32_t HAL_HCD_GetCurrentSpeed(HCD_HandleTypeDef *hhcd); /** * @} */ /** * @} */ /* Private macros ------------------------------------------------------------*/ /** @defgroup HCD_Private_Macros HCD Private Macros * @{ */ /** @defgroup HCD_Instance_definition HCD Instance definition * @{ */ #if defined(STM32F405xx) || defined(STM32F415xx) || defined(STM32F407xx) || defined(STM32F417xx) || defined(STM32F427xx) ||\ defined(STM32F437xx) || defined(STM32F429xx) || defined(STM32F439xx) || defined(STM32F446xx) || defined(STM32F469xx) ||\ defined(STM32F479xx) #define IS_HCD_ALL_INSTANCE(INSTANCE) (((INSTANCE) == USB_OTG_FS) || \ ((INSTANCE) == USB_OTG_HS)) #elif defined(STM32F401xC) || defined(STM32F401xE) || defined(STM32F411xE) #define IS_HCD_ALL_INSTANCE(INSTANCE) (((INSTANCE) == USB_OTG_FS)) #endif /** * @} */ /** * @} */ /** * @} */ /** * @} */ #endif /* STM32F405xx || STM32F415xx || STM32F407xx || STM32F417xx || STM32F427xx || STM32F437xx || STM32F429xx || STM32F439xx || STM32F401xC || STM32F401xE || STM32F411xE || STM32F446xx || STM32F469xx || STM32F479xx */ #ifdef __cplusplus } #endif #endif /* __STM32F4xx_HAL_HCD_H */ /************************ (C) COPYRIGHT STMicroelectronics *****END OF FILE****/ ================================================ FILE: Zelig/mbed/TARGET_NUCLEO_F401RE/stm32f4xx_hal_i2c.h ================================================ /** ****************************************************************************** * @file stm32f4xx_hal_i2c.h * @author MCD Application Team * @version V1.4.1 * @date 09-October-2015 * @brief Header file of I2C HAL module. ****************************************************************************** * @attention * *

© COPYRIGHT(c) 2015 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. * ****************************************************************************** */ /* Define to prevent recursive inclusion -------------------------------------*/ #ifndef __STM32F4xx_HAL_I2C_H #define __STM32F4xx_HAL_I2C_H #ifdef __cplusplus extern "C" { #endif /* Includes ------------------------------------------------------------------*/ #include "stm32f4xx_hal_def.h" /** @addtogroup STM32F4xx_HAL_Driver * @{ */ /** @addtogroup I2C * @{ */ /* Exported types ------------------------------------------------------------*/ /** @defgroup I2C_Exported_Types I2C Exported Types * @{ */ /** * @brief I2C Configuration Structure definition */ typedef struct { uint32_t ClockSpeed; /*!< Specifies the clock frequency. This parameter must be set to a value lower than 400kHz */ uint32_t DutyCycle; /*!< Specifies the I2C fast mode duty cycle. This parameter can be a value of @ref I2C_duty_cycle_in_fast_mode */ uint32_t OwnAddress1; /*!< Specifies the first device own address. This parameter can be a 7-bit or 10-bit address. */ uint32_t AddressingMode; /*!< Specifies if 7-bit or 10-bit addressing mode is selected. This parameter can be a value of @ref I2C_addressing_mode */ uint32_t DualAddressMode; /*!< Specifies if dual addressing mode is selected. This parameter can be a value of @ref I2C_dual_addressing_mode */ uint32_t OwnAddress2; /*!< Specifies the second device own address if dual addressing mode is selected This parameter can be a 7-bit address. */ uint32_t GeneralCallMode; /*!< Specifies if general call mode is selected. This parameter can be a value of @ref I2C_general_call_addressing_mode */ uint32_t NoStretchMode; /*!< Specifies if nostretch mode is selected. This parameter can be a value of @ref I2C_nostretch_mode */ }I2C_InitTypeDef; /** * @brief HAL State structures definition */ typedef enum { HAL_I2C_STATE_RESET = 0x00, /*!< I2C not yet initialized or disabled */ HAL_I2C_STATE_READY = 0x01, /*!< I2C initialized and ready for use */ HAL_I2C_STATE_BUSY = 0x02, /*!< I2C internal process is ongoing */ HAL_I2C_STATE_BUSY_TX = 0x12, /*!< Data Transmission process is ongoing */ HAL_I2C_STATE_BUSY_RX = 0x22, /*!< Data Reception process is ongoing */ HAL_I2C_STATE_MEM_BUSY_TX = 0x32, /*!< Memory Data Transmission process is ongoing */ HAL_I2C_STATE_MEM_BUSY_RX = 0x42, /*!< Memory Data Reception process is ongoing */ HAL_I2C_STATE_TIMEOUT = 0x03, /*!< I2C timeout state */ HAL_I2C_STATE_ERROR = 0x04 /*!< I2C error state */ }HAL_I2C_StateTypeDef; /** * @brief I2C handle Structure definition */ typedef struct { I2C_TypeDef *Instance; /*!< I2C registers base address */ I2C_InitTypeDef Init; /*!< I2C communication parameters */ uint8_t *pBuffPtr; /*!< Pointer to I2C transfer buffer */ uint16_t XferSize; /*!< I2C transfer size */ __IO uint16_t XferCount; /*!< I2C transfer counter */ DMA_HandleTypeDef *hdmatx; /*!< I2C Tx DMA handle parameters */ DMA_HandleTypeDef *hdmarx; /*!< I2C Rx DMA handle parameters */ HAL_LockTypeDef Lock; /*!< I2C locking object */ __IO HAL_I2C_StateTypeDef State; /*!< I2C communication state */ __IO uint32_t ErrorCode; /*!< I2C Error code */ }I2C_HandleTypeDef; /** * @} */ /* Exported constants --------------------------------------------------------*/ /** @defgroup I2C_Exported_Constants I2C Exported Constants * @{ */ /** @defgroup I2C_Error_Code I2C Error Code * @brief I2C Error Code * @{ */ #define HAL_I2C_ERROR_NONE ((uint32_t)0x00000000) /*!< No error */ #define HAL_I2C_ERROR_BERR ((uint32_t)0x00000001) /*!< BERR error */ #define HAL_I2C_ERROR_ARLO ((uint32_t)0x00000002) /*!< ARLO error */ #define HAL_I2C_ERROR_AF ((uint32_t)0x00000004) /*!< AF error */ #define HAL_I2C_ERROR_OVR ((uint32_t)0x00000008) /*!< OVR error */ #define HAL_I2C_ERROR_DMA ((uint32_t)0x00000010) /*!< DMA transfer error */ #define HAL_I2C_ERROR_TIMEOUT ((uint32_t)0x00000020) /*!< Timeout Error */ /** * @} */ /** @defgroup I2C_duty_cycle_in_fast_mode I2C duty cycle in fast mode * @{ */ #define I2C_DUTYCYCLE_2 ((uint32_t)0x00000000) #define I2C_DUTYCYCLE_16_9 I2C_CCR_DUTY /** * @} */ /** @defgroup I2C_addressing_mode I2C addressing mode * @{ */ #define I2C_ADDRESSINGMODE_7BIT ((uint32_t)0x00004000) #define I2C_ADDRESSINGMODE_10BIT (I2C_OAR1_ADDMODE | ((uint32_t)0x00004000)) /** * @} */ /** @defgroup I2C_dual_addressing_mode I2C dual addressing mode * @{ */ #define I2C_DUALADDRESS_DISABLE ((uint32_t)0x00000000) #define I2C_DUALADDRESS_ENABLE I2C_OAR2_ENDUAL /** * @} */ /** @defgroup I2C_general_call_addressing_mode I2C general call addressing mode * @{ */ #define I2C_GENERALCALL_DISABLE ((uint32_t)0x00000000) #define I2C_GENERALCALL_ENABLE I2C_CR1_ENGC /** * @} */ /** @defgroup I2C_nostretch_mode I2C nostretch mode * @{ */ #define I2C_NOSTRETCH_DISABLE ((uint32_t)0x00000000) #define I2C_NOSTRETCH_ENABLE I2C_CR1_NOSTRETCH /** * @} */ /** @defgroup I2C_Memory_Address_Size I2C Memory Address Size * @{ */ #define I2C_MEMADD_SIZE_8BIT ((uint32_t)0x00000001) #define I2C_MEMADD_SIZE_16BIT ((uint32_t)0x00000010) /** * @} */ /** @defgroup I2C_Interrupt_configuration_definition I2C Interrupt configuration definition * @{ */ #define I2C_IT_BUF I2C_CR2_ITBUFEN #define I2C_IT_EVT I2C_CR2_ITEVTEN #define I2C_IT_ERR I2C_CR2_ITERREN /** * @} */ /** @defgroup I2C_Flag_definition I2C Flag definition * @{ */ #define I2C_FLAG_SMBALERT ((uint32_t)0x00018000) #define I2C_FLAG_TIMEOUT ((uint32_t)0x00014000) #define I2C_FLAG_PECERR ((uint32_t)0x00011000) #define I2C_FLAG_OVR ((uint32_t)0x00010800) #define I2C_FLAG_AF ((uint32_t)0x00010400) #define I2C_FLAG_ARLO ((uint32_t)0x00010200) #define I2C_FLAG_BERR ((uint32_t)0x00010100) #define I2C_FLAG_TXE ((uint32_t)0x00010080) #define I2C_FLAG_RXNE ((uint32_t)0x00010040) #define I2C_FLAG_STOPF ((uint32_t)0x00010010) #define I2C_FLAG_ADD10 ((uint32_t)0x00010008) #define I2C_FLAG_BTF ((uint32_t)0x00010004) #define I2C_FLAG_ADDR ((uint32_t)0x00010002) #define I2C_FLAG_SB ((uint32_t)0x00010001) #define I2C_FLAG_DUALF ((uint32_t)0x00100080) #define I2C_FLAG_SMBHOST ((uint32_t)0x00100040) #define I2C_FLAG_SMBDEFAULT ((uint32_t)0x00100020) #define I2C_FLAG_GENCALL ((uint32_t)0x00100010) #define I2C_FLAG_TRA ((uint32_t)0x00100004) #define I2C_FLAG_BUSY ((uint32_t)0x00100002) #define I2C_FLAG_MSL ((uint32_t)0x00100001) /** * @} */ /** * @} */ /* Exported macro ------------------------------------------------------------*/ /** @defgroup I2C_Exported_Macros I2C Exported Macros * @{ */ /** @brief Reset I2C handle state * @param __HANDLE__: specifies the I2C Handle. * This parameter can be I2C where x: 1, 2, or 3 to select the I2C peripheral. * @retval None */ #define __HAL_I2C_RESET_HANDLE_STATE(__HANDLE__) ((__HANDLE__)->State = HAL_I2C_STATE_RESET) /** @brief Enable or disable the specified I2C interrupts. * @param __HANDLE__: specifies the I2C Handle. * This parameter can be I2C where x: 1, 2, or 3 to select the I2C peripheral. * @param __INTERRUPT__: specifies the interrupt source to enable or disable. * This parameter can be one of the following values: * @arg I2C_IT_BUF: Buffer interrupt enable * @arg I2C_IT_EVT: Event interrupt enable * @arg I2C_IT_ERR: Error interrupt enable * @retval None */ #define __HAL_I2C_ENABLE_IT(__HANDLE__, __INTERRUPT__) ((__HANDLE__)->Instance->CR2 |= (__INTERRUPT__)) #define __HAL_I2C_DISABLE_IT(__HANDLE__, __INTERRUPT__) ((__HANDLE__)->Instance->CR2 &= (~(__INTERRUPT__))) /** @brief Checks if the specified I2C interrupt source is enabled or disabled. * @param __HANDLE__: specifies the I2C Handle. * This parameter can be I2C where x: 1, 2, or 3 to select the I2C peripheral. * @param __INTERRUPT__: specifies the I2C interrupt source to check. * This parameter can be one of the following values: * @arg I2C_IT_BUF: Buffer interrupt enable * @arg I2C_IT_EVT: Event interrupt enable * @arg I2C_IT_ERR: Error interrupt enable * @retval The new state of __INTERRUPT__ (TRUE or FALSE). */ #define __HAL_I2C_GET_IT_SOURCE(__HANDLE__, __INTERRUPT__) ((((__HANDLE__)->Instance->CR2 & (__INTERRUPT__)) == (__INTERRUPT__)) ? SET : RESET) /** @brief Checks whether the specified I2C flag is set or not. * @param __HANDLE__: specifies the I2C Handle. * This parameter can be I2C where x: 1, 2, or 3 to select the I2C peripheral. * @param __FLAG__: specifies the flag to check. * This parameter can be one of the following values: * @arg I2C_FLAG_SMBALERT: SMBus Alert flag * @arg I2C_FLAG_TIMEOUT: Timeout or Tlow error flag * @arg I2C_FLAG_PECERR: PEC error in reception flag * @arg I2C_FLAG_OVR: Overrun/Underrun flag * @arg I2C_FLAG_AF: Acknowledge failure flag * @arg I2C_FLAG_ARLO: Arbitration lost flag * @arg I2C_FLAG_BERR: Bus error flag * @arg I2C_FLAG_TXE: Data register empty flag * @arg I2C_FLAG_RXNE: Data register not empty flag * @arg I2C_FLAG_STOPF: Stop detection flag * @arg I2C_FLAG_ADD10: 10-bit header sent flag * @arg I2C_FLAG_BTF: Byte transfer finished flag * @arg I2C_FLAG_ADDR: Address sent flag * Address matched flag * @arg I2C_FLAG_SB: Start bit flag * @arg I2C_FLAG_DUALF: Dual flag * @arg I2C_FLAG_SMBHOST: SMBus host header * @arg I2C_FLAG_SMBDEFAULT: SMBus default header * @arg I2C_FLAG_GENCALL: General call header flag * @arg I2C_FLAG_TRA: Transmitter/Receiver flag * @arg I2C_FLAG_BUSY: Bus busy flag * @arg I2C_FLAG_MSL: Master/Slave flag * @retval The new state of __FLAG__ (TRUE or FALSE). */ #define __HAL_I2C_GET_FLAG(__HANDLE__, __FLAG__) ((((uint8_t)((__FLAG__) >> 16)) == 0x01)?((((__HANDLE__)->Instance->SR1) & ((__FLAG__) & I2C_FLAG_MASK)) == ((__FLAG__) & I2C_FLAG_MASK)): \ ((((__HANDLE__)->Instance->SR2) & ((__FLAG__) & I2C_FLAG_MASK)) == ((__FLAG__) & I2C_FLAG_MASK))) /** @brief Clears the I2C pending flags which are cleared by writing 0 in a specific bit. * @param __HANDLE__: specifies the I2C Handle. * This parameter can be I2C where x: 1, 2, or 3 to select the I2C peripheral. * @param __FLAG__: specifies the flag to clear. * This parameter can be any combination of the following values: * @arg I2C_FLAG_SMBALERT: SMBus Alert flag * @arg I2C_FLAG_TIMEOUT: Timeout or Tlow error flag * @arg I2C_FLAG_PECERR: PEC error in reception flag * @arg I2C_FLAG_OVR: Overrun/Underrun flag (Slave mode) * @arg I2C_FLAG_AF: Acknowledge failure flag * @arg I2C_FLAG_ARLO: Arbitration lost flag (Master mode) * @arg I2C_FLAG_BERR: Bus error flag * @retval None */ #define __HAL_I2C_CLEAR_FLAG(__HANDLE__, __FLAG__) ((__HANDLE__)->Instance->SR1 = ~((__FLAG__) & I2C_FLAG_MASK)) /** @brief Clears the I2C ADDR pending flag. * @param __HANDLE__: specifies the I2C Handle. * This parameter can be I2C where x: 1, 2, or 3 to select the I2C peripheral. * @retval None */ #define __HAL_I2C_CLEAR_ADDRFLAG(__HANDLE__) \ do{ \ __IO uint32_t tmpreg; \ tmpreg = (__HANDLE__)->Instance->SR1; \ tmpreg = (__HANDLE__)->Instance->SR2; \ UNUSED(tmpreg); \ } while(0) /** @brief Clears the I2C STOPF pending flag. * @param __HANDLE__: specifies the I2C Handle. * This parameter can be I2C where x: 1, 2, or 3 to select the I2C peripheral. * @retval None */ #define __HAL_I2C_CLEAR_STOPFLAG(__HANDLE__) \ do{ \ __IO uint32_t tmpreg; \ tmpreg = (__HANDLE__)->Instance->SR1; \ (__HANDLE__)->Instance->CR1 |= I2C_CR1_PE; \ UNUSED(tmpreg); \ } while(0) #define __HAL_I2C_ENABLE(__HANDLE__) ((__HANDLE__)->Instance->CR1 |= I2C_CR1_PE) #define __HAL_I2C_DISABLE(__HANDLE__) ((__HANDLE__)->Instance->CR1 &= ~I2C_CR1_PE) /** * @} */ /* Include I2C HAL Extension module */ #include "stm32f4xx_hal_i2c_ex.h" /* Exported functions --------------------------------------------------------*/ /** @addtogroup I2C_Exported_Functions * @{ */ /** @addtogroup I2C_Exported_Functions_Group1 * @{ */ /* Initialization/de-initialization functions **********************************/ HAL_StatusTypeDef HAL_I2C_Init(I2C_HandleTypeDef *hi2c); HAL_StatusTypeDef HAL_I2C_DeInit (I2C_HandleTypeDef *hi2c); void HAL_I2C_MspInit(I2C_HandleTypeDef *hi2c); void HAL_I2C_MspDeInit(I2C_HandleTypeDef *hi2c); /** * @} */ /** @addtogroup I2C_Exported_Functions_Group2 * @{ */ /* I/O operation functions *****************************************************/ /******* Blocking mode: Polling */ HAL_StatusTypeDef HAL_I2C_Master_Transmit(I2C_HandleTypeDef *hi2c, uint16_t DevAddress, uint8_t *pData, uint16_t Size, uint32_t Timeout); HAL_StatusTypeDef HAL_I2C_Master_Receive(I2C_HandleTypeDef *hi2c, uint16_t DevAddress, uint8_t *pData, uint16_t Size, uint32_t Timeout); HAL_StatusTypeDef HAL_I2C_Slave_Transmit(I2C_HandleTypeDef *hi2c, uint8_t *pData, uint16_t Size, uint32_t Timeout); HAL_StatusTypeDef HAL_I2C_Slave_Receive(I2C_HandleTypeDef *hi2c, uint8_t *pData, uint16_t Size, uint32_t Timeout); HAL_StatusTypeDef HAL_I2C_Mem_Write(I2C_HandleTypeDef *hi2c, uint16_t DevAddress, uint16_t MemAddress, uint16_t MemAddSize, uint8_t *pData, uint16_t Size, uint32_t Timeout); HAL_StatusTypeDef HAL_I2C_Mem_Read(I2C_HandleTypeDef *hi2c, uint16_t DevAddress, uint16_t MemAddress, uint16_t MemAddSize, uint8_t *pData, uint16_t Size, uint32_t Timeout); HAL_StatusTypeDef HAL_I2C_IsDeviceReady(I2C_HandleTypeDef *hi2c, uint16_t DevAddress, uint32_t Trials, uint32_t Timeout); /******* Non-Blocking mode: Interrupt */ HAL_StatusTypeDef HAL_I2C_Master_Transmit_IT(I2C_HandleTypeDef *hi2c, uint16_t DevAddress, uint8_t *pData, uint16_t Size); HAL_StatusTypeDef HAL_I2C_Master_Receive_IT(I2C_HandleTypeDef *hi2c, uint16_t DevAddress, uint8_t *pData, uint16_t Size); HAL_StatusTypeDef HAL_I2C_Slave_Transmit_IT(I2C_HandleTypeDef *hi2c, uint8_t *pData, uint16_t Size); HAL_StatusTypeDef HAL_I2C_Slave_Receive_IT(I2C_HandleTypeDef *hi2c, uint8_t *pData, uint16_t Size); HAL_StatusTypeDef HAL_I2C_Mem_Write_IT(I2C_HandleTypeDef *hi2c, uint16_t DevAddress, uint16_t MemAddress, uint16_t MemAddSize, uint8_t *pData, uint16_t Size); HAL_StatusTypeDef HAL_I2C_Mem_Read_IT(I2C_HandleTypeDef *hi2c, uint16_t DevAddress, uint16_t MemAddress, uint16_t MemAddSize, uint8_t *pData, uint16_t Size); /******* Non-Blocking mode: DMA */ HAL_StatusTypeDef HAL_I2C_Master_Transmit_DMA(I2C_HandleTypeDef *hi2c, uint16_t DevAddress, uint8_t *pData, uint16_t Size); HAL_StatusTypeDef HAL_I2C_Master_Receive_DMA(I2C_HandleTypeDef *hi2c, uint16_t DevAddress, uint8_t *pData, uint16_t Size); HAL_StatusTypeDef HAL_I2C_Slave_Transmit_DMA(I2C_HandleTypeDef *hi2c, uint8_t *pData, uint16_t Size); HAL_StatusTypeDef HAL_I2C_Slave_Receive_DMA(I2C_HandleTypeDef *hi2c, uint8_t *pData, uint16_t Size); HAL_StatusTypeDef HAL_I2C_Mem_Write_DMA(I2C_HandleTypeDef *hi2c, uint16_t DevAddress, uint16_t MemAddress, uint16_t MemAddSize, uint8_t *pData, uint16_t Size); HAL_StatusTypeDef HAL_I2C_Mem_Read_DMA(I2C_HandleTypeDef *hi2c, uint16_t DevAddress, uint16_t MemAddress, uint16_t MemAddSize, uint8_t *pData, uint16_t Size); /******* I2C IRQHandler and Callbacks used in non blocking modes (Interrupt and DMA) */ void HAL_I2C_EV_IRQHandler(I2C_HandleTypeDef *hi2c); void HAL_I2C_ER_IRQHandler(I2C_HandleTypeDef *hi2c); void HAL_I2C_MasterTxCpltCallback(I2C_HandleTypeDef *hi2c); void HAL_I2C_MasterRxCpltCallback(I2C_HandleTypeDef *hi2c); void HAL_I2C_SlaveTxCpltCallback(I2C_HandleTypeDef *hi2c); void HAL_I2C_SlaveRxCpltCallback(I2C_HandleTypeDef *hi2c); void HAL_I2C_MemTxCpltCallback(I2C_HandleTypeDef *hi2c); void HAL_I2C_MemRxCpltCallback(I2C_HandleTypeDef *hi2c); void HAL_I2C_ErrorCallback(I2C_HandleTypeDef *hi2c); /** * @} */ /** @addtogroup I2C_Exported_Functions_Group3 * @{ */ /* Peripheral Control and State functions **************************************/ HAL_I2C_StateTypeDef HAL_I2C_GetState(I2C_HandleTypeDef *hi2c); uint32_t HAL_I2C_GetError(I2C_HandleTypeDef *hi2c); /** * @} */ /** * @} */ /* Private types -------------------------------------------------------------*/ /* Private variables ---------------------------------------------------------*/ /* Private constants ---------------------------------------------------------*/ /** @defgroup I2C_Private_Constants I2C Private Constants * @{ */ #define I2C_FLAG_MASK ((uint32_t)0x0000FFFF) /** * @} */ /* Private macros ------------------------------------------------------------*/ /** @defgroup I2C_Private_Macros I2C Private Macros * @{ */ #define I2C_FREQRANGE(__PCLK__) ((__PCLK__)/1000000) #define I2C_RISE_TIME(__FREQRANGE__, __SPEED__) (((__SPEED__) <= 100000) ? ((__FREQRANGE__) + 1) : ((((__FREQRANGE__) * 300) / 1000) + 1)) #define I2C_SPEED_STANDARD(__PCLK__, __SPEED__) (((((__PCLK__)/((__SPEED__) << 1)) & I2C_CCR_CCR) < 4)? 4:((__PCLK__) / ((__SPEED__) << 1))) #define I2C_SPEED_FAST(__PCLK__, __SPEED__, __DUTYCYCLE__) (((__DUTYCYCLE__) == I2C_DUTYCYCLE_2)? ((__PCLK__) / ((__SPEED__) * 3)) : (((__PCLK__) / ((__SPEED__) * 25)) | I2C_DUTYCYCLE_16_9)) #define I2C_SPEED(__PCLK__, __SPEED__, __DUTYCYCLE__) (((__SPEED__) <= 100000)? (I2C_SPEED_STANDARD((__PCLK__), (__SPEED__))) : \ ((I2C_SPEED_FAST((__PCLK__), (__SPEED__), (__DUTYCYCLE__)) & I2C_CCR_CCR) == 0)? 1 : \ ((I2C_SPEED_FAST((__PCLK__), (__SPEED__), (__DUTYCYCLE__))) | I2C_CCR_FS)) #define I2C_7BIT_ADD_WRITE(__ADDRESS__) ((uint8_t)((__ADDRESS__) & (~I2C_OAR1_ADD0))) #define I2C_7BIT_ADD_READ(__ADDRESS__) ((uint8_t)((__ADDRESS__) | I2C_OAR1_ADD0)) #define I2C_10BIT_ADDRESS(__ADDRESS__) ((uint8_t)((uint16_t)((__ADDRESS__) & (uint16_t)(0x00FF)))) #define I2C_10BIT_HEADER_WRITE(__ADDRESS__) ((uint8_t)((uint16_t)((uint16_t)(((uint16_t)((__ADDRESS__) & (uint16_t)(0x0300))) >> 7) | (uint16_t)(0xF0)))) #define I2C_10BIT_HEADER_READ(__ADDRESS__) ((uint8_t)((uint16_t)((uint16_t)(((uint16_t)((__ADDRESS__) & (uint16_t)(0x0300))) >> 7) | (uint16_t)(0xF1)))) #define I2C_MEM_ADD_MSB(__ADDRESS__) ((uint8_t)((uint16_t)(((uint16_t)((__ADDRESS__) & (uint16_t)(0xFF00))) >> 8))) #define I2C_MEM_ADD_LSB(__ADDRESS__) ((uint8_t)((uint16_t)((__ADDRESS__) & (uint16_t)(0x00FF)))) /** @defgroup I2C_IS_RTC_Definitions I2C Private macros to check input parameters * @{ */ #define IS_I2C_DUTY_CYCLE(CYCLE) (((CYCLE) == I2C_DUTYCYCLE_2) || \ ((CYCLE) == I2C_DUTYCYCLE_16_9)) #define IS_I2C_ADDRESSING_MODE(ADDRESS) (((ADDRESS) == I2C_ADDRESSINGMODE_7BIT) || \ ((ADDRESS) == I2C_ADDRESSINGMODE_10BIT)) #define IS_I2C_DUAL_ADDRESS(ADDRESS) (((ADDRESS) == I2C_DUALADDRESS_DISABLE) || \ ((ADDRESS) == I2C_DUALADDRESS_ENABLE)) #define IS_I2C_GENERAL_CALL(CALL) (((CALL) == I2C_GENERALCALL_DISABLE) || \ ((CALL) == I2C_GENERALCALL_ENABLE)) #define IS_I2C_NO_STRETCH(STRETCH) (((STRETCH) == I2C_NOSTRETCH_DISABLE) || \ ((STRETCH) == I2C_NOSTRETCH_ENABLE)) #define IS_I2C_MEMADD_SIZE(SIZE) (((SIZE) == I2C_MEMADD_SIZE_8BIT) || \ ((SIZE) == I2C_MEMADD_SIZE_16BIT)) #define IS_I2C_CLOCK_SPEED(SPEED) (((SPEED) > 0) && ((SPEED) <= 400000)) #define IS_I2C_OWN_ADDRESS1(ADDRESS1) (((ADDRESS1) & (uint32_t)(0xFFFFFC00)) == 0) #define IS_I2C_OWN_ADDRESS2(ADDRESS2) (((ADDRESS2) & (uint32_t)(0xFFFFFF01)) == 0) /** * @} */ /** * @} */ /* Private functions ---------------------------------------------------------*/ /** @defgroup I2C_Private_Functions I2C Private Functions * @{ */ /** * @} */ /** * @} */ /** * @} */ #ifdef __cplusplus } #endif #endif /* __STM32F4xx_HAL_I2C_H */ /************************ (C) COPYRIGHT STMicroelectronics *****END OF FILE****/ ================================================ FILE: Zelig/mbed/TARGET_NUCLEO_F401RE/stm32f4xx_hal_i2c_ex.h ================================================ /** ****************************************************************************** * @file stm32f4xx_hal_i2c_ex.h * @author MCD Application Team * @version V1.4.1 * @date 09-October-2015 * @brief Header file of I2C HAL Extension module. ****************************************************************************** * @attention * *

© COPYRIGHT(c) 2015 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. * ****************************************************************************** */ /* Define to prevent recursive inclusion -------------------------------------*/ #ifndef __STM32F4xx_HAL_I2C_EX_H #define __STM32F4xx_HAL_I2C_EX_H #ifdef __cplusplus extern "C" { #endif #if defined(STM32F427xx) || defined(STM32F437xx) || defined(STM32F429xx) || defined(STM32F439xx) ||\ defined(STM32F401xC) || defined(STM32F401xE) || defined(STM32F411xE) || defined(STM32F446xx) ||\ defined(STM32F469xx) || defined(STM32F479xx) /* Includes ------------------------------------------------------------------*/ #include "stm32f4xx_hal_def.h" /** @addtogroup STM32F4xx_HAL_Driver * @{ */ /** @addtogroup I2CEx * @{ */ /* Exported types ------------------------------------------------------------*/ /* Exported constants --------------------------------------------------------*/ /** @defgroup I2CEx_Exported_Constants I2C Exported Constants * @{ */ /** @defgroup I2CEx_Analog_Filter I2C Analog Filter * @{ */ #define I2C_ANALOGFILTER_ENABLE ((uint32_t)0x00000000) #define I2C_ANALOGFILTER_DISABLE I2C_FLTR_ANOFF /** * @} */ /** * @} */ /* Exported macro ------------------------------------------------------------*/ /* Exported functions --------------------------------------------------------*/ /** @addtogroup I2CEx_Exported_Functions * @{ */ /** @addtogroup I2CEx_Exported_Functions_Group1 * @{ */ /* Peripheral Control functions ************************************************/ HAL_StatusTypeDef HAL_I2CEx_ConfigAnalogFilter(I2C_HandleTypeDef *hi2c, uint32_t AnalogFilter); HAL_StatusTypeDef HAL_I2CEx_ConfigDigitalFilter(I2C_HandleTypeDef *hi2c, uint32_t DigitalFilter); /** * @} */ /** * @} */ /* Private types -------------------------------------------------------------*/ /* Private variables ---------------------------------------------------------*/ /* Private constants ---------------------------------------------------------*/ /** @defgroup I2CEx_Private_Constants I2C Private Constants * @{ */ /** * @} */ /* Private macros ------------------------------------------------------------*/ /** @defgroup I2CEx_Private_Macros I2C Private Macros * @{ */ #define IS_I2C_ANALOG_FILTER(FILTER) (((FILTER) == I2C_ANALOGFILTER_ENABLE) || \ ((FILTER) == I2C_ANALOGFILTER_DISABLE)) #define IS_I2C_DIGITAL_FILTER(FILTER) ((FILTER) <= 0x0000000F) /** * @} */ /** * @} */ /** * @} */ #endif /* STM32F427xx || STM32F429xx || STM32F437xx || STM32F439xx || STM32F401xC ||\ STM32F401xE || STM32F411xE || STM32F446xx || STM32F469xx || STM32F479xx */ #ifdef __cplusplus } #endif #endif /* __STM32F4xx_HAL_I2C_EX_H */ /************************ (C) COPYRIGHT STMicroelectronics *****END OF FILE****/ ================================================ FILE: Zelig/mbed/TARGET_NUCLEO_F401RE/stm32f4xx_hal_i2s.h ================================================ /** ****************************************************************************** * @file stm32f4xx_hal_i2s.h * @author MCD Application Team * @version V1.4.1 * @date 09-October-2015 * @brief Header file of I2S HAL module. ****************************************************************************** * @attention * *

© COPYRIGHT(c) 2015 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. * ****************************************************************************** */ /* Define to prevent recursive inclusion -------------------------------------*/ #ifndef __STM32F4xx_HAL_I2S_H #define __STM32F4xx_HAL_I2S_H #ifdef __cplusplus extern "C" { #endif /* Includes ------------------------------------------------------------------*/ #include "stm32f4xx_hal_def.h" /** @addtogroup STM32F4xx_HAL_Driver * @{ */ /** @addtogroup I2S * @{ */ /* Exported types ------------------------------------------------------------*/ /** @defgroup I2S_Exported_Types I2S Exported Types * @{ */ /** * @brief I2S Init structure definition */ typedef struct { uint32_t Mode; /*!< Specifies the I2S operating mode. This parameter can be a value of @ref I2S_Mode */ uint32_t Standard; /*!< Specifies the standard used for the I2S communication. This parameter can be a value of @ref I2S_Standard */ uint32_t DataFormat; /*!< Specifies the data format for the I2S communication. This parameter can be a value of @ref I2S_Data_Format */ uint32_t MCLKOutput; /*!< Specifies whether the I2S MCLK output is enabled or not. This parameter can be a value of @ref I2S_MCLK_Output */ uint32_t AudioFreq; /*!< Specifies the frequency selected for the I2S communication. This parameter can be a value of @ref I2S_Audio_Frequency */ uint32_t CPOL; /*!< Specifies the idle state of the I2S clock. This parameter can be a value of @ref I2S_Clock_Polarity */ uint32_t ClockSource; /*!< Specifies the I2S Clock Source. This parameter can be a value of @ref I2S_Clock_Source */ uint32_t FullDuplexMode; /*!< Specifies the I2S FullDuplex mode. This parameter can be a value of @ref I2S_FullDuplex_Mode */ }I2S_InitTypeDef; /** * @brief HAL State structures definition */ typedef enum { HAL_I2S_STATE_RESET = 0x00, /*!< I2S not yet initialized or disabled */ HAL_I2S_STATE_READY = 0x01, /*!< I2S initialized and ready for use */ HAL_I2S_STATE_BUSY = 0x02, /*!< I2S internal process is ongoing */ HAL_I2S_STATE_BUSY_TX = 0x12, /*!< Data Transmission process is ongoing */ HAL_I2S_STATE_BUSY_RX = 0x22, /*!< Data Reception process is ongoing */ HAL_I2S_STATE_BUSY_TX_RX = 0x32, /*!< Data Transmission and Reception process is ongoing */ HAL_I2S_STATE_TIMEOUT = 0x03, /*!< I2S timeout state */ HAL_I2S_STATE_ERROR = 0x04 /*!< I2S error state */ }HAL_I2S_StateTypeDef; /** * @brief I2S handle Structure definition */ typedef struct { SPI_TypeDef *Instance; /* I2S registers base address */ I2S_InitTypeDef Init; /* I2S communication parameters */ uint16_t *pTxBuffPtr; /* Pointer to I2S Tx transfer buffer */ __IO uint16_t TxXferSize; /* I2S Tx transfer size */ __IO uint16_t TxXferCount; /* I2S Tx transfer Counter */ uint16_t *pRxBuffPtr; /* Pointer to I2S Rx transfer buffer */ __IO uint16_t RxXferSize; /* I2S Rx transfer size */ __IO uint16_t RxXferCount; /* I2S Rx transfer counter */ DMA_HandleTypeDef *hdmatx; /* I2S Tx DMA handle parameters */ DMA_HandleTypeDef *hdmarx; /* I2S Rx DMA handle parameters */ __IO HAL_LockTypeDef Lock; /* I2S locking object */ __IO HAL_I2S_StateTypeDef State; /* I2S communication state */ __IO uint32_t ErrorCode; /* I2S Error code */ }I2S_HandleTypeDef; /** * @} */ /* Exported constants --------------------------------------------------------*/ /** @defgroup I2S_Exported_Constants I2S Exported Constants * @{ */ /** @defgroup I2S_Error_Code I2S Error Code * @brief I2S Error Code * @{ */ #define HAL_I2S_ERROR_NONE ((uint32_t)0x00000000) /*!< No error */ #define HAL_I2S_ERROR_UDR ((uint32_t)0x00000001) /*!< I2S Underrun error */ #define HAL_I2S_ERROR_OVR ((uint32_t)0x00000002) /*!< I2S Overrun error */ #define HAL_I2SEX_ERROR_UDR ((uint32_t)0x00000004) /*!< I2S extended Underrun error */ #define HAL_I2SEX_ERROR_OVR ((uint32_t)0x00000008) /*!< I2S extended Overrun error */ #define HAL_I2S_ERROR_FRE ((uint32_t)0x00000010) /*!< I2S Frame format error */ #define HAL_I2S_ERROR_DMA ((uint32_t)0x00000020) /*!< DMA transfer error */ /** * @} */ /** @defgroup I2S_Mode I2S Mode * @{ */ #define I2S_MODE_SLAVE_TX ((uint32_t)0x00000000) #define I2S_MODE_SLAVE_RX ((uint32_t)0x00000100) #define I2S_MODE_MASTER_TX ((uint32_t)0x00000200) #define I2S_MODE_MASTER_RX ((uint32_t)0x00000300) /** * @} */ /** @defgroup I2S_Standard I2S Standard * @{ */ #define I2S_STANDARD_PHILIPS ((uint32_t)0x00000000) #define I2S_STANDARD_MSB ((uint32_t)0x00000010) #define I2S_STANDARD_LSB ((uint32_t)0x00000020) #define I2S_STANDARD_PCM_SHORT ((uint32_t)0x00000030) #define I2S_STANDARD_PCM_LONG ((uint32_t)0x000000B0) /** * @} */ /** @defgroup I2S_Data_Format I2S Data Format * @{ */ #define I2S_DATAFORMAT_16B ((uint32_t)0x00000000) #define I2S_DATAFORMAT_16B_EXTENDED ((uint32_t)0x00000001) #define I2S_DATAFORMAT_24B ((uint32_t)0x00000003) #define I2S_DATAFORMAT_32B ((uint32_t)0x00000005) /** * @} */ /** @defgroup I2S_MCLK_Output I2S Mclk Output * @{ */ #define I2S_MCLKOUTPUT_ENABLE ((uint32_t)SPI_I2SPR_MCKOE) #define I2S_MCLKOUTPUT_DISABLE ((uint32_t)0x00000000) /** * @} */ /** @defgroup I2S_Audio_Frequency I2S Audio Frequency * @{ */ #define I2S_AUDIOFREQ_192K ((uint32_t)192000) #define I2S_AUDIOFREQ_96K ((uint32_t)96000) #define I2S_AUDIOFREQ_48K ((uint32_t)48000) #define I2S_AUDIOFREQ_44K ((uint32_t)44100) #define I2S_AUDIOFREQ_32K ((uint32_t)32000) #define I2S_AUDIOFREQ_22K ((uint32_t)22050) #define I2S_AUDIOFREQ_16K ((uint32_t)16000) #define I2S_AUDIOFREQ_11K ((uint32_t)11025) #define I2S_AUDIOFREQ_8K ((uint32_t)8000) #define I2S_AUDIOFREQ_DEFAULT ((uint32_t)2) /** * @} */ /** @defgroup I2S_FullDuplex_Mode I2S FullDuplex Mode * @{ */ #define I2S_FULLDUPLEXMODE_DISABLE ((uint32_t)0x00000000) #define I2S_FULLDUPLEXMODE_ENABLE ((uint32_t)0x00000001) /** * @} */ /** @defgroup I2S_Clock_Polarity I2S Clock Polarity * @{ */ #define I2S_CPOL_LOW ((uint32_t)0x00000000) #define I2S_CPOL_HIGH ((uint32_t)SPI_I2SCFGR_CKPOL) /** * @} */ /** @defgroup I2S_Interrupts_Definition I2S Interrupts Definition * @{ */ #define I2S_IT_TXE SPI_CR2_TXEIE #define I2S_IT_RXNE SPI_CR2_RXNEIE #define I2S_IT_ERR SPI_CR2_ERRIE /** * @} */ /** @defgroup I2S_Flags_Definition I2S Flags Definition * @{ */ #define I2S_FLAG_TXE SPI_SR_TXE #define I2S_FLAG_RXNE SPI_SR_RXNE #define I2S_FLAG_UDR SPI_SR_UDR #define I2S_FLAG_OVR SPI_SR_OVR #define I2S_FLAG_FRE SPI_SR_FRE #define I2S_FLAG_CHSIDE SPI_SR_CHSIDE #define I2S_FLAG_BSY SPI_SR_BSY /** * @} */ /** * @} */ /* Exported macro ------------------------------------------------------------*/ /** @defgroup I2S_Exported_Macros I2S Exported Macros * @{ */ /** @brief Reset I2S handle state * @param __HANDLE__: specifies the I2S Handle. * @retval None */ #define __HAL_I2S_RESET_HANDLE_STATE(__HANDLE__) ((__HANDLE__)->State = HAL_I2S_STATE_RESET) /** @brief Enable or disable the specified SPI peripheral (in I2S mode). * @param __HANDLE__: specifies the I2S Handle. * @retval None */ #define __HAL_I2S_ENABLE(__HANDLE__) ((__HANDLE__)->Instance->I2SCFGR |= SPI_I2SCFGR_I2SE) #define __HAL_I2S_DISABLE(__HANDLE__) ((__HANDLE__)->Instance->I2SCFGR &= ~SPI_I2SCFGR_I2SE) /** @brief Enable or disable the specified I2S interrupts. * @param __HANDLE__: specifies the I2S Handle. * @param __INTERRUPT__: specifies the interrupt source to enable or disable. * This parameter can be one of the following values: * @arg I2S_IT_TXE: Tx buffer empty interrupt enable * @arg I2S_IT_RXNE: RX buffer not empty interrupt enable * @arg I2S_IT_ERR: Error interrupt enable * @retval None */ #define __HAL_I2S_ENABLE_IT(__HANDLE__, __INTERRUPT__) ((__HANDLE__)->Instance->CR2 |= (__INTERRUPT__)) #define __HAL_I2S_DISABLE_IT(__HANDLE__, __INTERRUPT__) ((__HANDLE__)->Instance->CR2 &= ~(__INTERRUPT__)) /** @brief Checks if the specified I2S interrupt source is enabled or disabled. * @param __HANDLE__: specifies the I2S Handle. * This parameter can be I2S where x: 1, 2, or 3 to select the I2S peripheral. * @param __INTERRUPT__: specifies the I2S interrupt source to check. * This parameter can be one of the following values: * @arg I2S_IT_TXE: Tx buffer empty interrupt enable * @arg I2S_IT_RXNE: RX buffer not empty interrupt enable * @arg I2S_IT_ERR: Error interrupt enable * @retval The new state of __IT__ (TRUE or FALSE). */ #define __HAL_I2S_GET_IT_SOURCE(__HANDLE__, __INTERRUPT__) ((((__HANDLE__)->Instance->CR2 & (__INTERRUPT__)) == (__INTERRUPT__)) ? SET : RESET) /** @brief Checks whether the specified I2S flag is set or not. * @param __HANDLE__: specifies the I2S Handle. * @param __FLAG__: specifies the flag to check. * This parameter can be one of the following values: * @arg I2S_FLAG_RXNE: Receive buffer not empty flag * @arg I2S_FLAG_TXE: Transmit buffer empty flag * @arg I2S_FLAG_UDR: Underrun flag * @arg I2S_FLAG_OVR: Overrun flag * @arg I2S_FLAG_FRE: Frame error flag * @arg I2S_FLAG_CHSIDE: Channel Side flag * @arg I2S_FLAG_BSY: Busy flag * @retval The new state of __FLAG__ (TRUE or FALSE). */ #define __HAL_I2S_GET_FLAG(__HANDLE__, __FLAG__) ((((__HANDLE__)->Instance->SR) & (__FLAG__)) == (__FLAG__)) /** @brief Clears the I2S OVR pending flag. * @param __HANDLE__: specifies the I2S Handle. * @retval None */ #define __HAL_I2S_CLEAR_OVRFLAG(__HANDLE__) \ do{ \ __IO uint32_t tmpreg; \ tmpreg = (__HANDLE__)->Instance->DR; \ tmpreg = (__HANDLE__)->Instance->SR; \ UNUSED(tmpreg); \ } while(0) /** @brief Clears the I2S UDR pending flag. * @param __HANDLE__: specifies the I2S Handle. * @retval None */ #define __HAL_I2S_CLEAR_UDRFLAG(__HANDLE__) \ do{ \ __IO uint32_t tmpreg; \ tmpreg = (__HANDLE__)->Instance->SR; \ UNUSED(tmpreg); \ } while(0) /** * @} */ /* Include I2S Extension module */ #include "stm32f4xx_hal_i2s_ex.h" /* Exported functions --------------------------------------------------------*/ /** @addtogroup I2S_Exported_Functions * @{ */ /** @addtogroup I2S_Exported_Functions_Group1 * @{ */ /* Initialization/de-initialization functions **********************************/ HAL_StatusTypeDef HAL_I2S_Init(I2S_HandleTypeDef *hi2s); HAL_StatusTypeDef HAL_I2S_DeInit (I2S_HandleTypeDef *hi2s); void HAL_I2S_MspInit(I2S_HandleTypeDef *hi2s); void HAL_I2S_MspDeInit(I2S_HandleTypeDef *hi2s); /** * @} */ /** @addtogroup I2S_Exported_Functions_Group2 * @{ */ /* I/O operation functions *****************************************************/ /* Blocking mode: Polling */ HAL_StatusTypeDef HAL_I2S_Transmit(I2S_HandleTypeDef *hi2s, uint16_t *pData, uint16_t Size, uint32_t Timeout); HAL_StatusTypeDef HAL_I2S_Receive(I2S_HandleTypeDef *hi2s, uint16_t *pData, uint16_t Size, uint32_t Timeout); /* Non-Blocking mode: Interrupt */ HAL_StatusTypeDef HAL_I2S_Transmit_IT(I2S_HandleTypeDef *hi2s, uint16_t *pData, uint16_t Size); HAL_StatusTypeDef HAL_I2S_Receive_IT(I2S_HandleTypeDef *hi2s, uint16_t *pData, uint16_t Size); void HAL_I2S_IRQHandler(I2S_HandleTypeDef *hi2s); /* Non-Blocking mode: DMA */ HAL_StatusTypeDef HAL_I2S_Transmit_DMA(I2S_HandleTypeDef *hi2s, uint16_t *pData, uint16_t Size); HAL_StatusTypeDef HAL_I2S_Receive_DMA(I2S_HandleTypeDef *hi2s, uint16_t *pData, uint16_t Size); HAL_StatusTypeDef HAL_I2S_DMAPause(I2S_HandleTypeDef *hi2s); HAL_StatusTypeDef HAL_I2S_DMAResume(I2S_HandleTypeDef *hi2s); HAL_StatusTypeDef HAL_I2S_DMAStop(I2S_HandleTypeDef *hi2s); /* Peripheral Control and State functions **************************************/ HAL_I2S_StateTypeDef HAL_I2S_GetState(I2S_HandleTypeDef *hi2s); uint32_t HAL_I2S_GetError(I2S_HandleTypeDef *hi2s); /* Callbacks used in non blocking modes (Interrupt and DMA) *******************/ void HAL_I2S_TxHalfCpltCallback(I2S_HandleTypeDef *hi2s); void HAL_I2S_TxCpltCallback(I2S_HandleTypeDef *hi2s); void HAL_I2S_RxHalfCpltCallback(I2S_HandleTypeDef *hi2s); void HAL_I2S_RxCpltCallback(I2S_HandleTypeDef *hi2s); void HAL_I2S_ErrorCallback(I2S_HandleTypeDef *hi2s); /** * @} */ /** * @} */ /* Private types -------------------------------------------------------------*/ /* Private variables ---------------------------------------------------------*/ /* Private constants ---------------------------------------------------------*/ /** @defgroup I2S_Private_Constants I2S Private Constants * @{ */ /** * @} */ /* Private macros ------------------------------------------------------------*/ /** @defgroup I2S_Private_Macros I2S Private Macros * @{ */ #define IS_I2S_MODE(MODE) (((MODE) == I2S_MODE_SLAVE_TX) || \ ((MODE) == I2S_MODE_SLAVE_RX) || \ ((MODE) == I2S_MODE_MASTER_TX) || \ ((MODE) == I2S_MODE_MASTER_RX)) #define IS_I2S_STANDARD(STANDARD) (((STANDARD) == I2S_STANDARD_PHILIPS) || \ ((STANDARD) == I2S_STANDARD_MSB) || \ ((STANDARD) == I2S_STANDARD_LSB) || \ ((STANDARD) == I2S_STANDARD_PCM_SHORT) || \ ((STANDARD) == I2S_STANDARD_PCM_LONG)) #define IS_I2S_DATA_FORMAT(FORMAT) (((FORMAT) == I2S_DATAFORMAT_16B) || \ ((FORMAT) == I2S_DATAFORMAT_16B_EXTENDED) || \ ((FORMAT) == I2S_DATAFORMAT_24B) || \ ((FORMAT) == I2S_DATAFORMAT_32B)) #define IS_I2S_MCLK_OUTPUT(OUTPUT) (((OUTPUT) == I2S_MCLKOUTPUT_ENABLE) || \ ((OUTPUT) == I2S_MCLKOUTPUT_DISABLE)) #define IS_I2S_AUDIO_FREQ(FREQ) ((((FREQ) >= I2S_AUDIOFREQ_8K) && \ ((FREQ) <= I2S_AUDIOFREQ_192K)) || \ ((FREQ) == I2S_AUDIOFREQ_DEFAULT)) #define IS_I2S_FULLDUPLEX_MODE(MODE) (((MODE) == I2S_FULLDUPLEXMODE_DISABLE) || \ ((MODE) == I2S_FULLDUPLEXMODE_ENABLE)) #define IS_I2S_CPOL(CPOL) (((CPOL) == I2S_CPOL_LOW) || \ ((CPOL) == I2S_CPOL_HIGH)) /** * @} */ /* Private functions ---------------------------------------------------------*/ /** @defgroup I2S_Private_Functions I2S Private Functions * @{ */ void I2S_DMATxCplt(DMA_HandleTypeDef *hdma); void I2S_DMATxHalfCplt(DMA_HandleTypeDef *hdma); void I2S_DMARxCplt(DMA_HandleTypeDef *hdma); void I2S_DMARxHalfCplt(DMA_HandleTypeDef *hdma); void I2S_DMAError(DMA_HandleTypeDef *hdma); HAL_StatusTypeDef I2S_WaitFlagStateUntilTimeout(I2S_HandleTypeDef *hi2s, uint32_t Flag, uint32_t Status, uint32_t Timeout); HAL_StatusTypeDef I2S_Transmit_IT(I2S_HandleTypeDef *hi2s); HAL_StatusTypeDef I2S_Receive_IT(I2S_HandleTypeDef *hi2s); /** * @} */ /** * @} */ /** * @} */ #ifdef __cplusplus } #endif #endif /* __STM32F4xx_HAL_I2S_H */ /************************ (C) COPYRIGHT STMicroelectronics *****END OF FILE****/ ================================================ FILE: Zelig/mbed/TARGET_NUCLEO_F401RE/stm32f4xx_hal_i2s_ex.h ================================================ /** ****************************************************************************** * @file stm32f4xx_hal_i2s_ex.h * @author MCD Application Team * @version V1.4.1 * @date 09-October-2015 * @brief Header file of I2S HAL module. ****************************************************************************** * @attention * *

© COPYRIGHT(c) 2015 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. * ****************************************************************************** */ /* Define to prevent recursive inclusion -------------------------------------*/ #ifndef __STM32F4xx_HAL_I2S_EX_H #define __STM32F4xx_HAL_I2S_EX_H #ifdef __cplusplus extern "C" { #endif /* Includes ------------------------------------------------------------------*/ #include "stm32f4xx_hal_def.h" /** @addtogroup STM32F4xx_HAL_Driver * @{ */ /** @addtogroup I2SEx * @{ */ /* Exported types ------------------------------------------------------------*/ /** @defgroup I2SEx_Exported_Types I2S Exported Types * @{ */ /** * @} */ /* Exported constants --------------------------------------------------------*/ /** @defgroup I2SEx_Exported_Constants I2S Exported Constants * @{ */ /** @defgroup I2S_Clock_Source I2S Clock Source * @{ */ #if defined(STM32F405xx) || defined(STM32F415xx) || defined(STM32F407xx) || defined(STM32F417xx) || \ defined(STM32F427xx) || defined(STM32F437xx) || defined(STM32F429xx) || defined(STM32F439xx) || \ defined(STM32F401xC) || defined(STM32F401xE) || defined(STM32F411xE) || defined(STM32F469xx) || \ defined(STM32F479xx) #define I2S_CLOCK_PLL ((uint32_t)0x00000000) #define I2S_CLOCK_EXTERNAL ((uint32_t)0x00000001) #endif /* STM32F405xx || STM32F415xx || STM32F407xx || STM32F417xx || STM32F427xx || STM32F437xx || STM32F429xx || STM32F439xx || STM32F401xC || STM32F401xE || STM32F411xE || STM32F469xx || STM32F479xx */ #if defined(STM32F446xx) #define I2S_CLOCK_PLL ((uint32_t)0x00000000) #define I2S_CLOCK_EXTERNAL ((uint32_t)0x00000001) #define I2S_CLOCK_PLLR ((uint32_t)0x00000002) #define I2S_CLOCK_PLLSRC ((uint32_t)0x00000003) #endif /* STM32F446xx */ #if defined(STM32F410Tx) || defined(STM32F410Cx) || defined(STM32F410Rx) #define I2S_CLOCK_PLLSRC ((uint32_t)0x00000000) #define I2S_CLOCK_EXTERNAL ((uint32_t)0x00000001) #define I2S_CLOCK_PLLR ((uint32_t)0x00000002) #endif /* STM32F410Tx || STM32F410Cx || STM32F410Rx */ /** * @} */ /** * @} */ /* Exported macro ------------------------------------------------------------*/ /** @defgroup I2SEx_Exported_Macros I2S Exported Macros * @{ */ /** * @} */ /* Exported functions --------------------------------------------------------*/ /** @addtogroup I2SEx_Exported_Functions * @{ */ /** @addtogroup I2SEx_Exported_Functions_Group1 * @{ */ /* Extended features functions **************************************************/ /* Blocking mode: Polling */ HAL_StatusTypeDef HAL_I2SEx_TransmitReceive(I2S_HandleTypeDef *hi2s, uint16_t *pTxData, uint16_t *pRxData, uint16_t Size, uint32_t Timeout); /* Non-Blocking mode: Interrupt */ HAL_StatusTypeDef HAL_I2SEx_TransmitReceive_IT(I2S_HandleTypeDef *hi2s, uint16_t *pTxData, uint16_t *pRxData, uint16_t Size); /* Non-Blocking mode: DMA */ HAL_StatusTypeDef HAL_I2SEx_TransmitReceive_DMA(I2S_HandleTypeDef *hi2s, uint16_t *pTxData, uint16_t *pRxData, uint16_t Size); /** * @} */ /** * @} */ /* Private types -------------------------------------------------------------*/ /* Private variables ---------------------------------------------------------*/ /* Private constants ---------------------------------------------------------*/ /** @defgroup I2SEx_Private_Constants I2S Private Constants * @{ */ /** * @} */ /* Private macros ------------------------------------------------------------*/ /** @defgroup I2SEx_Private_Macros I2S Private Macros * @{ */ #if defined(STM32F405xx) || defined(STM32F415xx) || defined(STM32F407xx) || defined(STM32F417xx) || \ defined(STM32F427xx) || defined(STM32F437xx) || defined(STM32F429xx) || defined(STM32F439xx) || \ defined(STM32F401xC) || defined(STM32F401xE) || defined(STM32F411xE) || defined(STM32F469xx) || \ defined(STM32F479xx) #define IS_I2S_CLOCKSOURCE(CLOCK) (((CLOCK) == I2S_CLOCK_EXTERNAL) ||\ ((CLOCK) == I2S_CLOCK_PLL)) #endif /* STM32F405xx || STM32F415xx || STM32F407xx || STM32F417xx || STM32F427xx || STM32F437xx || STM32F429xx || STM32F439xx || STM32F401xC || STM32F401xE || STM32F411xE || STM32F469xx || STM32F479xx */ #if defined(STM32F446xx) #define IS_I2S_CLOCKSOURCE(CLOCK) (((CLOCK) == I2S_CLOCK_EXTERNAL) ||\ ((CLOCK) == I2S_CLOCK_PLL) ||\ ((CLOCK) == I2S_CLOCK_PLLSRC) ||\ ((CLOCK) == I2S_CLOCK_PLLR)) #endif /* STM32F446xx */ #if defined(STM32F410Tx) || defined(STM32F410Cx) || defined(STM32F410Rx) #define IS_I2S_CLOCKSOURCE(CLOCK) (((CLOCK) == I2S_CLOCK_EXTERNAL) ||\ ((CLOCK) == I2S_CLOCK_PLLSRC) ||\ ((CLOCK) == I2S_CLOCK_PLLR)) #endif /* STM32F410Tx || STM32F410Cx || STM32F410Rx */ #if defined(STM32F405xx) || defined(STM32F415xx) || defined(STM32F407xx) || defined(STM32F417xx) || \ defined(STM32F427xx) || defined(STM32F437xx) || defined(STM32F429xx) || defined(STM32F439xx) || \ defined(STM32F401xC) || defined(STM32F401xE) || defined(STM32F410Cx) || defined(STM32F410Rx) || \ defined(STM32F411xE) || defined(STM32F446xx) || defined(STM32F469xx) || defined(STM32F479xx) #define I2SxEXT(__INSTANCE__) ((__INSTANCE__) == (SPI2)? (SPI_TypeDef *)(I2S2ext_BASE): (SPI_TypeDef *)(I2S3ext_BASE)) #endif /* STM32F405xx || STM32F415xx || STM32F407xx || STM32F417xx || STM32F427xx || STM32F437xx || STM32F429xx || STM32F439xx || STM32F401xC || STM32F401xE || STM32F410Cx || STM32F410Rx || STM32F411xE || STM32F446xx || STM32F469xx || STM32F479xx */ /** * @} */ /* Private functions ---------------------------------------------------------*/ /** @defgroup I2SEx_Private_Functions I2S Private Functions * @{ */ HAL_StatusTypeDef I2SEx_TransmitReceive_IT(I2S_HandleTypeDef *hi2s); uint32_t I2S_GetInputClock(I2S_HandleTypeDef *hi2s); /** * @} */ /** * @} */ /** * @} */ #ifdef __cplusplus } #endif #endif /* __STM32F4xx_HAL_I2S_EX_H */ /************************ (C) COPYRIGHT STMicroelectronics *****END OF FILE****/ ================================================ FILE: Zelig/mbed/TARGET_NUCLEO_F401RE/stm32f4xx_hal_irda.h ================================================ /** ****************************************************************************** * @file stm32f4xx_hal_irda.h * @author MCD Application Team * @version V1.4.1 * @date 09-October-2015 * @brief Header file of IRDA HAL module. ****************************************************************************** * @attention * *

© COPYRIGHT(c) 2015 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. * ****************************************************************************** */ /* Define to prevent recursive inclusion -------------------------------------*/ #ifndef __STM32F4xx_HAL_IRDA_H #define __STM32F4xx_HAL_IRDA_H #ifdef __cplusplus extern "C" { #endif /* Includes ------------------------------------------------------------------*/ #include "stm32f4xx_hal_def.h" /** @addtogroup STM32F4xx_HAL_Driver * @{ */ /** @addtogroup IRDA * @{ */ /* Exported types ------------------------------------------------------------*/ /** @defgroup IRDA_Exported_Types IRDA Exported Types * @{ */ /** * @brief IRDA Init Structure definition */ typedef struct { uint32_t BaudRate; /*!< This member configures the IRDA communication baud rate. The baud rate is computed using the following formula: - IntegerDivider = ((PCLKx) / (8 * (hirda->Init.BaudRate))) - FractionalDivider = ((IntegerDivider - ((uint32_t) IntegerDivider)) * 8) + 0.5 */ uint32_t WordLength; /*!< Specifies the number of data bits transmitted or received in a frame. This parameter can be a value of @ref IRDA_Word_Length */ uint32_t Parity; /*!< Specifies the parity mode. This parameter can be a value of @ref IRDA_Parity @note When parity is enabled, the computed parity is inserted at the MSB position of the transmitted data (9th bit when the word length is set to 9 data bits; 8th bit when the word length is set to 8 data bits). */ uint32_t Mode; /*!< Specifies wether the Receive or Transmit mode is enabled or disabled. This parameter can be a value of @ref IRDA_Mode */ uint8_t Prescaler; /*!< Specifies the Prescaler */ uint32_t IrDAMode; /*!< Specifies the IrDA mode This parameter can be a value of @ref IRDA_Low_Power */ }IRDA_InitTypeDef; /** * @brief HAL State structures definition */ typedef enum { HAL_IRDA_STATE_RESET = 0x00, /*!< Peripheral is not yet Initialized */ HAL_IRDA_STATE_READY = 0x01, /*!< Peripheral Initialized and ready for use */ HAL_IRDA_STATE_BUSY = 0x02, /*!< An internal process is ongoing */ HAL_IRDA_STATE_BUSY_TX = 0x12, /*!< Data Transmission process is ongoing */ HAL_IRDA_STATE_BUSY_RX = 0x22, /*!< Data Reception process is ongoing */ HAL_IRDA_STATE_BUSY_TX_RX = 0x32, /*!< Data Transmission and Reception process is ongoing */ HAL_IRDA_STATE_TIMEOUT = 0x03, /*!< Timeout state */ HAL_IRDA_STATE_ERROR = 0x04 /*!< Error */ }HAL_IRDA_StateTypeDef; /** * @brief IRDA handle Structure definition */ typedef struct { USART_TypeDef *Instance; /* USART registers base address */ IRDA_InitTypeDef Init; /* IRDA communication parameters */ uint8_t *pTxBuffPtr; /* Pointer to IRDA Tx transfer Buffer */ uint16_t TxXferSize; /* IRDA Tx Transfer size */ uint16_t TxXferCount; /* IRDA Tx Transfer Counter */ uint8_t *pRxBuffPtr; /* Pointer to IRDA Rx transfer Buffer */ uint16_t RxXferSize; /* IRDA Rx Transfer size */ uint16_t RxXferCount; /* IRDA Rx Transfer Counter */ DMA_HandleTypeDef *hdmatx; /* IRDA Tx DMA Handle parameters */ DMA_HandleTypeDef *hdmarx; /* IRDA Rx DMA Handle parameters */ HAL_LockTypeDef Lock; /* Locking object */ __IO HAL_IRDA_StateTypeDef State; /* IRDA communication state */ __IO uint32_t ErrorCode; /* IRDA Error code */ }IRDA_HandleTypeDef; /** * @} */ /* Exported constants --------------------------------------------------------*/ /** @defgroup IRDA_Exported_Constants IRDA Exported constants * @{ */ /** @defgroup IRDA_Error_Code IRDA Error Code * @brief IRDA Error Code * @{ */ #define HAL_IRDA_ERROR_NONE ((uint32_t)0x00000000) /*!< No error */ #define HAL_IRDA_ERROR_PE ((uint32_t)0x00000001) /*!< Parity error */ #define HAL_IRDA_ERROR_NE ((uint32_t)0x00000002) /*!< Noise error */ #define HAL_IRDA_ERROR_FE ((uint32_t)0x00000004) /*!< Frame error */ #define HAL_IRDA_ERROR_ORE ((uint32_t)0x00000008) /*!< Overrun error */ #define HAL_IRDA_ERROR_DMA ((uint32_t)0x00000010) /*!< DMA transfer error */ /** * @} */ /** @defgroup IRDA_Word_Length IRDA Word Length * @{ */ #define IRDA_WORDLENGTH_8B ((uint32_t)0x00000000) #define IRDA_WORDLENGTH_9B ((uint32_t)USART_CR1_M) /** * @} */ /** @defgroup IRDA_Parity IRDA Parity * @{ */ #define IRDA_PARITY_NONE ((uint32_t)0x00000000) #define IRDA_PARITY_EVEN ((uint32_t)USART_CR1_PCE) #define IRDA_PARITY_ODD ((uint32_t)(USART_CR1_PCE | USART_CR1_PS)) /** * @} */ /** @defgroup IRDA_Mode IRDA Transfer Mode * @{ */ #define IRDA_MODE_RX ((uint32_t)USART_CR1_RE) #define IRDA_MODE_TX ((uint32_t)USART_CR1_TE) #define IRDA_MODE_TX_RX ((uint32_t)(USART_CR1_TE |USART_CR1_RE)) /** * @} */ /** @defgroup IRDA_Low_Power IRDA Low Power * @{ */ #define IRDA_POWERMODE_LOWPOWER ((uint32_t)USART_CR3_IRLP) #define IRDA_POWERMODE_NORMAL ((uint32_t)0x00000000) /** * @} */ /** @defgroup IRDA_Flags IRDA Flags * Elements values convention: 0xXXXX * - 0xXXXX : Flag mask in the SR register * @{ */ #define IRDA_FLAG_TXE ((uint32_t)0x00000080) #define IRDA_FLAG_TC ((uint32_t)0x00000040) #define IRDA_FLAG_RXNE ((uint32_t)0x00000020) #define IRDA_FLAG_IDLE ((uint32_t)0x00000010) #define IRDA_FLAG_ORE ((uint32_t)0x00000008) #define IRDA_FLAG_NE ((uint32_t)0x00000004) #define IRDA_FLAG_FE ((uint32_t)0x00000002) #define IRDA_FLAG_PE ((uint32_t)0x00000001) /** * @} */ /** @defgroup IRDA_Interrupt_definition IRDA Interrupt Definitions * Elements values convention: 0xY000XXXX * - XXXX : Interrupt mask in the XX register * - Y : Interrupt source register (2bits) * - 01: CR1 register * - 10: CR2 register * - 11: CR3 register * @{ */ #define IRDA_IT_PE ((uint32_t)(IRDA_CR1_REG_INDEX << 28 | USART_CR1_PEIE)) #define IRDA_IT_TXE ((uint32_t)(IRDA_CR1_REG_INDEX << 28 | USART_CR1_TXEIE)) #define IRDA_IT_TC ((uint32_t)(IRDA_CR1_REG_INDEX << 28 | USART_CR1_TCIE)) #define IRDA_IT_RXNE ((uint32_t)(IRDA_CR1_REG_INDEX << 28 | USART_CR1_RXNEIE)) #define IRDA_IT_IDLE ((uint32_t)(IRDA_CR1_REG_INDEX << 28 | USART_CR1_IDLEIE)) #define IRDA_IT_LBD ((uint32_t)(IRDA_CR2_REG_INDEX << 28 | USART_CR2_LBDIE)) #define IRDA_IT_CTS ((uint32_t)(IRDA_CR3_REG_INDEX << 28 | USART_CR3_CTSIE)) #define IRDA_IT_ERR ((uint32_t)(IRDA_CR3_REG_INDEX << 28 | USART_CR3_EIE)) /** * @} */ /** * @} */ /* Exported macro ------------------------------------------------------------*/ /** @defgroup IRDA_Exported_Macros IRDA Exported Macros * @{ */ /** @brief Reset IRDA handle state * @param __HANDLE__: specifies the USART Handle. * This parameter can be USARTx where x: 1, 2, 3, 4, 5, 6, 7 or 8 to select the USART or * UART peripheral. * @retval None */ #define __HAL_IRDA_RESET_HANDLE_STATE(__HANDLE__) ((__HANDLE__)->State = HAL_IRDA_STATE_RESET) /** @brief Flushs the IRDA DR register * @param __HANDLE__: specifies the USART Handle. * This parameter can be USARTx where x: 1, 2, 3, 4, 5, 6, 7 or 8 to select the USART or * UART peripheral. */ #define __HAL_IRDA_FLUSH_DRREGISTER(__HANDLE__) ((__HANDLE__)->Instance->DR) /** @brief Checks whether the specified IRDA flag is set or not. * @param __HANDLE__: specifies the USART Handle. * This parameter can be USARTx where x: 1, 2, 3, 4, 5, 6, 7 or 8 to select the USART or * UART peripheral. * @param __FLAG__: specifies the flag to check. * This parameter can be one of the following values: * @arg IRDA_FLAG_TXE: Transmit data register empty flag * @arg IRDA_FLAG_TC: Transmission Complete flag * @arg IRDA_FLAG_RXNE: Receive data register not empty flag * @arg IRDA_FLAG_IDLE: Idle Line detection flag * @arg IRDA_FLAG_ORE: OverRun Error flag * @arg IRDA_FLAG_NE: Noise Error flag * @arg IRDA_FLAG_FE: Framing Error flag * @arg IRDA_FLAG_PE: Parity Error flag * @retval The new state of __FLAG__ (TRUE or FALSE). */ #define __HAL_IRDA_GET_FLAG(__HANDLE__, __FLAG__) (((__HANDLE__)->Instance->SR & (__FLAG__)) == (__FLAG__)) /** @brief Clears the specified IRDA pending flag. * @param __HANDLE__: specifies the USART Handle. * This parameter can be USARTx where x: 1, 2, 3, 4, 5, 6, 7 or 8 to select the USART or * UART peripheral. * @param __FLAG__: specifies the flag to check. * This parameter can be any combination of the following values: * @arg IRDA_FLAG_TC: Transmission Complete flag. * @arg IRDA_FLAG_RXNE: Receive data register not empty flag. * * @note PE (Parity error), FE (Framing error), NE (Noise error), ORE (OverRun * error) and IDLE (Idle line detected) flags are cleared by software * sequence: a read operation to USART_SR register followed by a read * operation to USART_DR register. * @note RXNE flag can be also cleared by a read to the USART_DR register. * @note TC flag can be also cleared by software sequence: a read operation to * USART_SR register followed by a write operation to USART_DR register. * @note TXE flag is cleared only by a write to the USART_DR register. * * @retval None */ #define __HAL_IRDA_CLEAR_FLAG(__HANDLE__, __FLAG__) ((__HANDLE__)->Instance->SR = ~(__FLAG__)) /** @brief Clear the IRDA PE pending flag. * @param __HANDLE__: specifies the USART Handle. * This parameter can be USARTx where x: 1, 2, 3, 4, 5, 6, 7 or 8 to select the USART or * UART peripheral. * @retval None */ #define __HAL_IRDA_CLEAR_PEFLAG(__HANDLE__) \ do{ \ __IO uint32_t tmpreg; \ tmpreg = (__HANDLE__)->Instance->SR; \ UNUSED(tmpreg); \ } while(0) /** @brief Clear the IRDA FE pending flag. * @param __HANDLE__: specifies the USART Handle. * This parameter can be USARTx where x: 1, 2, 3, 4, 5, 6, 7 or 8 to select the USART or * UART peripheral. * @retval None */ #define __HAL_IRDA_CLEAR_FEFLAG(__HANDLE__) __HAL_IRDA_CLEAR_PEFLAG(__HANDLE__) /** @brief Clear the IRDA NE pending flag. * @param __HANDLE__: specifies the USART Handle. * This parameter can be USARTx where x: 1, 2, 3, 4, 5, 6, 7 or 8 to select the USART or * UART peripheral. * @retval None */ #define __HAL_IRDA_CLEAR_NEFLAG(__HANDLE__) __HAL_IRDA_CLEAR_PEFLAG(__HANDLE__) /** @brief Clear the IRDA ORE pending flag. * @param __HANDLE__: specifies the USART Handle. * This parameter can be USARTx where x: 1, 2, 3, 4, 5, 6, 7 or 8 to select the USART or * UART peripheral. * @retval None */ #define __HAL_IRDA_CLEAR_OREFLAG(__HANDLE__) __HAL_IRDA_CLEAR_PEFLAG(__HANDLE__) /** @brief Clear the IRDA IDLE pending flag. * @param __HANDLE__: specifies the USART Handle. * This parameter can be USARTx where x: 1, 2, 3, 4, 5, 6, 7 or 8 to select the USART or * UART peripheral. * @retval None */ #define __HAL_IRDA_CLEAR_IDLEFLAG(__HANDLE__) __HAL_IRDA_CLEAR_PEFLAG(__HANDLE__) /** @brief Enables or disables the specified IRDA interrupt. * @param __HANDLE__: specifies the USART Handle. * This parameter can be USARTx where x: 1, 2, 3, 4, 5, 6, 7 or 8 to select the USART or * UART peripheral. * @param __INTERRUPT__: specifies the IRDA interrupt source to check. * This parameter can be one of the following values: * @arg IRDA_IT_TXE: Transmit Data Register empty interrupt * @arg IRDA_IT_TC: Transmission complete interrupt * @arg IRDA_IT_RXNE: Receive Data register not empty interrupt * @arg IRDA_IT_IDLE: Idle line detection interrupt * @arg IRDA_IT_PE: Parity Error interrupt * @arg IRDA_IT_ERR: Error interrupt(Frame error, noise error, overrun error) * @retval None */ #define __HAL_IRDA_ENABLE_IT(__HANDLE__, __INTERRUPT__) ((((__INTERRUPT__) >> 28) == 1)? ((__HANDLE__)->Instance->CR1 |= ((__INTERRUPT__) & IRDA_IT_MASK)): \ (((__INTERRUPT__) >> 28) == 2)? ((__HANDLE__)->Instance->CR2 |= ((__INTERRUPT__) & IRDA_IT_MASK)): \ ((__HANDLE__)->Instance->CR3 |= ((__INTERRUPT__) & IRDA_IT_MASK))) #define __HAL_IRDA_DISABLE_IT(__HANDLE__, __INTERRUPT__) ((((__INTERRUPT__) >> 28) == 1)? ((__HANDLE__)->Instance->CR1 &= ~((__INTERRUPT__) & IRDA_IT_MASK)): \ (((__INTERRUPT__) >> 28) == 2)? ((__HANDLE__)->Instance->CR2 &= ~((__INTERRUPT__) & IRDA_IT_MASK)): \ ((__HANDLE__)->Instance->CR3 &= ~ ((__INTERRUPT__) & IRDA_IT_MASK))) /** @brief Checks whether the specified IRDA interrupt has occurred or not. * @param __HANDLE__: specifies the USART Handle. * This parameter can be USARTx where x: 1, 2, 3, 4, 5, 6, 7 or 8 to select the USART or * UART peripheral. * @param __IT__: specifies the IRDA interrupt source to check. * This parameter can be one of the following values: * @arg IRDA_IT_TXE: Transmit Data Register empty interrupt * @arg IRDA_IT_TC: Transmission complete interrupt * @arg IRDA_IT_RXNE: Receive Data register not empty interrupt * @arg IRDA_IT_IDLE: Idle line detection interrupt * @arg USART_IT_ERR: Error interrupt * @arg IRDA_IT_PE: Parity Error interrupt * @retval The new state of __IT__ (TRUE or FALSE). */ #define __HAL_IRDA_GET_IT_SOURCE(__HANDLE__, __IT__) (((((__IT__) >> 28) == 1)? (__HANDLE__)->Instance->CR1:(((((uint32_t)(__IT__)) >> 28) == 2)? \ (__HANDLE__)->Instance->CR2 : (__HANDLE__)->Instance->CR3)) & (((uint32_t)(__IT__)) & IRDA_IT_MASK)) /** @brief Macro to enable the IRDA's one bit sample method * @param __HANDLE__: specifies the IRDA Handle. * @retval None */ #define __HAL_IRDA_ONE_BIT_SAMPLE_ENABLE(__HANDLE__) ((__HANDLE__)->Instance->CR3|= USART_CR3_ONEBIT) /** @brief Macro to disable the IRDA's one bit sample method * @param __HANDLE__: specifies the IRDA Handle. * @retval None */ #define __HAL_IRDA_ONE_BIT_SAMPLE_DISABLE(__HANDLE__) ((__HANDLE__)->Instance->CR3 &= (uint16_t)~((uint16_t)USART_CR3_ONEBIT)) /** @brief Enable UART/USART associated to IRDA Handle * @param __HANDLE__: specifies the IRDA Handle. * IRDA Handle selects the USARTx or UARTy peripheral * (USART,UART availability and x,y values depending on device). * @retval None */ #define __HAL_IRDA_ENABLE(__HANDLE__) ((__HANDLE__)->Instance->CR1 |= USART_CR1_UE) /** @brief Disable UART/USART associated to IRDA Handle * @param __HANDLE__: specifies the IRDA Handle. * IRDA Handle selects the USARTx or UARTy peripheral * (USART,UART availability and x,y values depending on device). * @retval None */ #define __HAL_IRDA_DISABLE(__HANDLE__) ((__HANDLE__)->Instance->CR1 &= ~USART_CR1_UE) /** * @} */ /* Exported functions --------------------------------------------------------*/ /** @addtogroup IRDA_Exported_Functions * @{ */ /** @addtogroup IRDA_Exported_Functions_Group1 * @{ */ /* Initialization/de-initialization functions **********************************/ HAL_StatusTypeDef HAL_IRDA_Init(IRDA_HandleTypeDef *hirda); HAL_StatusTypeDef HAL_IRDA_DeInit(IRDA_HandleTypeDef *hirda); void HAL_IRDA_MspInit(IRDA_HandleTypeDef *hirda); void HAL_IRDA_MspDeInit(IRDA_HandleTypeDef *hirda); /** * @} */ /** @addtogroup IRDA_Exported_Functions_Group2 * @{ */ /* IO operation functions *******************************************************/ HAL_StatusTypeDef HAL_IRDA_Transmit(IRDA_HandleTypeDef *hirda, uint8_t *pData, uint16_t Size, uint32_t Timeout); HAL_StatusTypeDef HAL_IRDA_Receive(IRDA_HandleTypeDef *hirda, uint8_t *pData, uint16_t Size, uint32_t Timeout); HAL_StatusTypeDef HAL_IRDA_Transmit_IT(IRDA_HandleTypeDef *hirda, uint8_t *pData, uint16_t Size); HAL_StatusTypeDef HAL_IRDA_Receive_IT(IRDA_HandleTypeDef *hirda, uint8_t *pData, uint16_t Size); HAL_StatusTypeDef HAL_IRDA_Transmit_DMA(IRDA_HandleTypeDef *hirda, uint8_t *pData, uint16_t Size); HAL_StatusTypeDef HAL_IRDA_Receive_DMA(IRDA_HandleTypeDef *hirda, uint8_t *pData, uint16_t Size); HAL_StatusTypeDef HAL_IRDA_DMAPause(IRDA_HandleTypeDef *hirda); HAL_StatusTypeDef HAL_IRDA_DMAResume(IRDA_HandleTypeDef *hirda); HAL_StatusTypeDef HAL_IRDA_DMAStop(IRDA_HandleTypeDef *hirda); void HAL_IRDA_IRQHandler(IRDA_HandleTypeDef *hirda); void HAL_IRDA_TxCpltCallback(IRDA_HandleTypeDef *hirda); void HAL_IRDA_RxCpltCallback(IRDA_HandleTypeDef *hirda); void HAL_IRDA_TxHalfCpltCallback(IRDA_HandleTypeDef *hirda); void HAL_IRDA_RxHalfCpltCallback(IRDA_HandleTypeDef *hirda); void HAL_IRDA_ErrorCallback(IRDA_HandleTypeDef *hirda); /** * @} */ /** @addtogroup IRDA_Exported_Functions_Group3 * @{ */ /* Peripheral State functions **************************************************/ HAL_IRDA_StateTypeDef HAL_IRDA_GetState(IRDA_HandleTypeDef *hirda); uint32_t HAL_IRDA_GetError(IRDA_HandleTypeDef *hirda); /** * @} */ /** * @} */ /* Private types -------------------------------------------------------------*/ /* Private variables ---------------------------------------------------------*/ /* Private constants ---------------------------------------------------------*/ /** @defgroup IRDA_Private_Constants IRDA Private Constants * @{ */ /** @brief IRDA interruptions flag mask * */ #define IRDA_IT_MASK ((uint32_t) USART_CR1_PEIE | USART_CR1_TXEIE | USART_CR1_TCIE | USART_CR1_RXNEIE | \ USART_CR1_IDLEIE | USART_CR2_LBDIE | USART_CR3_CTSIE | USART_CR3_EIE ) #define IRDA_CR1_REG_INDEX 1 #define IRDA_CR2_REG_INDEX 2 #define IRDA_CR3_REG_INDEX 3 /** * @} */ /* Private macros --------------------------------------------------------*/ /** @defgroup IRDA_Private_Macros IRDA Private Macros * @{ */ #define IS_IRDA_WORD_LENGTH(LENGTH) (((LENGTH) == IRDA_WORDLENGTH_8B) || \ ((LENGTH) == IRDA_WORDLENGTH_9B)) #define IS_IRDA_PARITY(PARITY) (((PARITY) == IRDA_PARITY_NONE) || \ ((PARITY) == IRDA_PARITY_EVEN) || \ ((PARITY) == IRDA_PARITY_ODD)) #define IS_IRDA_MODE(MODE) ((((MODE) & (uint32_t)0x0000FFF3) == 0x00) && ((MODE) != (uint32_t)0x000000)) #define IS_IRDA_POWERMODE(MODE) (((MODE) == IRDA_POWERMODE_LOWPOWER) || \ ((MODE) == IRDA_POWERMODE_NORMAL)) #define IS_IRDA_BAUDRATE(BAUDRATE) ((BAUDRATE) < 115201) #define IRDA_DIV(_PCLK_, _BAUD_) (((_PCLK_)*25)/(4*(_BAUD_))) #define IRDA_DIVMANT(_PCLK_, _BAUD_) (IRDA_DIV((_PCLK_), (_BAUD_))/100) #define IRDA_DIVFRAQ(_PCLK_, _BAUD_) (((IRDA_DIV((_PCLK_), (_BAUD_)) - (IRDA_DIVMANT((_PCLK_), (_BAUD_)) * 100)) * 16 + 50) / 100) #define IRDA_BRR(_PCLK_, _BAUD_) ((IRDA_DIVMANT((_PCLK_), (_BAUD_)) << 4)|(IRDA_DIVFRAQ((_PCLK_), (_BAUD_)) & 0x0F)) /** * @} */ /* Private functions ---------------------------------------------------------*/ /** @defgroup IRDA_Private_Functions IRDA Private Functions * @{ */ /** * @} */ /** * @} */ /** * @} */ #ifdef __cplusplus } #endif #endif /* __STM32F4xx_HAL_IRDA_H */ /************************ (C) COPYRIGHT STMicroelectronics *****END OF FILE****/ ================================================ FILE: Zelig/mbed/TARGET_NUCLEO_F401RE/stm32f4xx_hal_iwdg.h ================================================ /** ****************************************************************************** * @file stm32f4xx_hal_iwdg.h * @author MCD Application Team * @version V1.4.1 * @date 09-October-2015 * @brief Header file of IWDG HAL module. ****************************************************************************** * @attention * *

© COPYRIGHT(c) 2015 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. * ****************************************************************************** */ /* Define to prevent recursive inclusion -------------------------------------*/ #ifndef __STM32F4xx_HAL_IWDG_H #define __STM32F4xx_HAL_IWDG_H #ifdef __cplusplus extern "C" { #endif /* Includes ------------------------------------------------------------------*/ #include "stm32f4xx_hal_def.h" /** @addtogroup STM32F4xx_HAL_Driver * @{ */ /** @addtogroup IWDG * @{ */ /* Exported types ------------------------------------------------------------*/ /** @defgroup IWDG_Exported_Types IWDG Exported Types * @{ */ /** * @brief IWDG HAL State Structure definition */ typedef enum { HAL_IWDG_STATE_RESET = 0x00, /*!< IWDG not yet initialized or disabled */ HAL_IWDG_STATE_READY = 0x01, /*!< IWDG initialized and ready for use */ HAL_IWDG_STATE_BUSY = 0x02, /*!< IWDG internal process is ongoing */ HAL_IWDG_STATE_TIMEOUT = 0x03, /*!< IWDG timeout state */ HAL_IWDG_STATE_ERROR = 0x04 /*!< IWDG error state */ }HAL_IWDG_StateTypeDef; /** * @brief IWDG Init structure definition */ typedef struct { uint32_t Prescaler; /*!< Select the prescaler of the IWDG. This parameter can be a value of @ref IWDG_Prescaler */ uint32_t Reload; /*!< Specifies the IWDG down-counter reload value. This parameter must be a number between Min_Data = 0 and Max_Data = 0x0FFF */ }IWDG_InitTypeDef; /** * @brief IWDG Handle Structure definition */ typedef struct { IWDG_TypeDef *Instance; /*!< Register base address */ IWDG_InitTypeDef Init; /*!< IWDG required parameters */ HAL_LockTypeDef Lock; /*!< IWDG Locking object */ __IO HAL_IWDG_StateTypeDef State; /*!< IWDG communication state */ }IWDG_HandleTypeDef; /** * @} */ /* Exported constants --------------------------------------------------------*/ /** @defgroup IWDG_Exported_Constants IWDG Exported Constants * @{ */ /** @defgroup IWDG_Registers_BitMask IWDG Registers BitMask * @brief IWDG registers bit mask * @{ */ /* --- KR Register ---*/ /* KR register bit mask */ #define IWDG_KEY_RELOAD ((uint32_t)0xAAAA) /*!< IWDG Reload Counter Enable */ #define IWDG_KEY_ENABLE ((uint32_t)0xCCCC) /*!< IWDG Peripheral Enable */ #define IWDG_KEY_WRITE_ACCESS_ENABLE ((uint32_t)0x5555) /*!< IWDG KR Write Access Enable */ #define IWDG_KEY_WRITE_ACCESS_DISABLE ((uint32_t)0x0000) /*!< IWDG KR Write Access Disable */ /** * @} */ /** @defgroup IWDG_Flag_definition IWDG Flag definition * @{ */ #define IWDG_FLAG_PVU ((uint32_t)IWDG_SR_PVU) /*!< Watchdog counter prescaler value update Flag */ #define IWDG_FLAG_RVU ((uint32_t)IWDG_SR_RVU) /*!< Watchdog counter reload value update Flag */ /** * @} */ /** @defgroup IWDG_Prescaler IWDG Prescaler * @{ */ #define IWDG_PRESCALER_4 ((uint8_t)0x00) /*!< IWDG prescaler set to 4 */ #define IWDG_PRESCALER_8 ((uint8_t)(IWDG_PR_PR_0)) /*!< IWDG prescaler set to 8 */ #define IWDG_PRESCALER_16 ((uint8_t)(IWDG_PR_PR_1)) /*!< IWDG prescaler set to 16 */ #define IWDG_PRESCALER_32 ((uint8_t)(IWDG_PR_PR_1 | IWDG_PR_PR_0)) /*!< IWDG prescaler set to 32 */ #define IWDG_PRESCALER_64 ((uint8_t)(IWDG_PR_PR_2)) /*!< IWDG prescaler set to 64 */ #define IWDG_PRESCALER_128 ((uint8_t)(IWDG_PR_PR_2 | IWDG_PR_PR_0)) /*!< IWDG prescaler set to 128 */ #define IWDG_PRESCALER_256 ((uint8_t)(IWDG_PR_PR_2 | IWDG_PR_PR_1)) /*!< IWDG prescaler set to 256 */ /** * @} */ /** * @} */ /* Exported macros -----------------------------------------------------------*/ /** @defgroup IWDG_Exported_Macros IWDG Exported Macros * @{ */ /** @brief Reset IWDG handle state * @param __HANDLE__: IWDG handle. * @retval None */ #define __HAL_IWDG_RESET_HANDLE_STATE(__HANDLE__) ((__HANDLE__)->State = HAL_IWDG_STATE_RESET) /** * @brief Enables the IWDG peripheral. * @param __HANDLE__: IWDG handle * @retval None */ #define __HAL_IWDG_START(__HANDLE__) WRITE_REG((__HANDLE__)->Instance->KR, IWDG_KEY_ENABLE) /** * @brief Reloads IWDG counter with value defined in the reload register * (write access to IWDG_PR and IWDG_RLR registers disabled). * @param __HANDLE__: IWDG handle * @retval None */ #define __HAL_IWDG_RELOAD_COUNTER(__HANDLE__) WRITE_REG((__HANDLE__)->Instance->KR, IWDG_KEY_RELOAD) /** * @brief Gets the selected IWDG's flag status. * @param __HANDLE__: IWDG handle * @param __FLAG__: specifies the flag to check. * This parameter can be one of the following values: * @arg IWDG_FLAG_PVU: Watchdog counter reload value update flag * @arg IWDG_FLAG_RVU: Watchdog counter prescaler value flag * @retval The new state of __FLAG__ (TRUE or FALSE). */ #define __HAL_IWDG_GET_FLAG(__HANDLE__, __FLAG__) (((__HANDLE__)->Instance->SR & (__FLAG__)) == (__FLAG__)) /** * @} */ /* Exported functions --------------------------------------------------------*/ /** @addtogroup IWDG_Exported_Functions * @{ */ /** @addtogroup IWDG_Exported_Functions_Group1 * @{ */ /* Initialization/de-initialization functions ********************************/ HAL_StatusTypeDef HAL_IWDG_Init(IWDG_HandleTypeDef *hiwdg); void HAL_IWDG_MspInit(IWDG_HandleTypeDef *hiwdg); /** * @} */ /** @addtogroup IWDG_Exported_Functions_Group2 * @{ */ /* I/O operation functions ****************************************************/ HAL_StatusTypeDef HAL_IWDG_Start(IWDG_HandleTypeDef *hiwdg); HAL_StatusTypeDef HAL_IWDG_Refresh(IWDG_HandleTypeDef *hiwdg); /** * @} */ /** @addtogroup IWDG_Exported_Functions_Group3 * @{ */ /* Peripheral State functions ************************************************/ HAL_IWDG_StateTypeDef HAL_IWDG_GetState(IWDG_HandleTypeDef *hiwdg); /** * @} */ /** * @} */ /* Private macro -------------------------------------------------------------*/ /** @defgroup IWDG_Private_Macros IWDG Private Macros * @{ */ /** * @brief Enables write access to IWDG_PR and IWDG_RLR registers. * @param __HANDLE__: IWDG handle * @retval None */ #define IWDG_ENABLE_WRITE_ACCESS(__HANDLE__) WRITE_REG((__HANDLE__)->Instance->KR, IWDG_KEY_WRITE_ACCESS_ENABLE) /** * @brief Disables write access to IWDG_PR and IWDG_RLR registers. * @param __HANDLE__: IWDG handle * @retval None */ #define IWDG_DISABLE_WRITE_ACCESS(__HANDLE__) WRITE_REG((__HANDLE__)->Instance->KR, IWDG_KEY_WRITE_ACCESS_DISABLE) #define IS_IWDG_PRESCALER(__PRESCALER__) (((__PRESCALER__) == IWDG_PRESCALER_4) || \ ((__PRESCALER__) == IWDG_PRESCALER_8) || \ ((__PRESCALER__) == IWDG_PRESCALER_16) || \ ((__PRESCALER__) == IWDG_PRESCALER_32) || \ ((__PRESCALER__) == IWDG_PRESCALER_64) || \ ((__PRESCALER__) == IWDG_PRESCALER_128)|| \ ((__PRESCALER__) == IWDG_PRESCALER_256)) #define IS_IWDG_RELOAD(__RELOAD__) ((__RELOAD__) <= 0xFFF) /** * @} */ /* Private define ------------------------------------------------------------*/ /** @defgroup IWDG_Private_Constants IWDG Private Constants * @{ */ /** * @} */ /** * @} */ /** * @} */ #ifdef __cplusplus } #endif #endif /* __STM32F4xx_HAL_IWDG_H */ /************************ (C) COPYRIGHT STMicroelectronics *****END OF FILE****/ ================================================ FILE: Zelig/mbed/TARGET_NUCLEO_F401RE/stm32f4xx_hal_lptim.h ================================================ /** ****************************************************************************** * @file stm32f4xx_hal_lptim.h * @author MCD Application Team * @version V1.4.1 * @date 09-October-2015 * @brief Header file of LPTIM HAL module. ****************************************************************************** * @attention * *

© COPYRIGHT(c) 2015 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. * ****************************************************************************** */ /* Define to prevent recursive inclusion -------------------------------------*/ #ifndef __STM32F4xx_HAL_LPTIM_H #define __STM32F4xx_HAL_LPTIM_H #ifdef __cplusplus extern "C" { #endif #if defined(STM32F410Tx) || defined(STM32F410Cx) || defined(STM32F410Rx) /* Includes ------------------------------------------------------------------*/ #include "stm32f4xx_hal_def.h" /** @addtogroup STM32F4xx_HAL_Driver * @{ */ /** @defgroup LPTIM LPTIM * @brief LPTIM HAL module driver * @{ */ /* Exported types ------------------------------------------------------------*/ /** @defgroup LPTIM_Exported_Types LPTIM Exported Types * @{ */ /** @defgroup LPTIM_WAKEUPTIMER_EXTILINE LPTIM WAKEUP Timer EXTI Line * @{ */ #define LPTIM_EXTI_LINE_WAKEUPTIMER_EVENT ((uint32_t)EXTI_IMR_MR23) /*!< External interrupt line 23 Connected to the LPTIM EXTI Line */ /** * @} */ /** * @brief LPTIM Clock configuration definition */ typedef struct { uint32_t Source; /*!< Selects the clock source. This parameter can be a value of @ref LPTIM_Clock_Source */ uint32_t Prescaler; /*!< Specifies the counter clock Prescaler. This parameter can be a value of @ref LPTIM_Clock_Prescaler */ }LPTIM_ClockConfigTypeDef; /** * @brief LPTIM Clock configuration definition */ typedef struct { uint32_t Polarity; /*!< Selects the polarity of the active edge for the counter unit if the ULPTIM input is selected. Note: This parameter is used only when Ultra low power clock source is used. Note: If the polarity is configured on 'both edges', an auxiliary clock (one of the Low power oscillator) must be active. This parameter can be a value of @ref LPTIM_Clock_Polarity */ uint32_t SampleTime; /*!< Selects the clock sampling time to configure the clock glitch filter. Note: This parameter is used only when Ultra low power clock source is used. This parameter can be a value of @ref LPTIM_Clock_Sample_Time */ }LPTIM_ULPClockConfigTypeDef; /** * @brief LPTIM Trigger configuration definition */ typedef struct { uint32_t Source; /*!< Selects the Trigger source. This parameter can be a value of @ref LPTIM_Trigger_Source */ uint32_t ActiveEdge; /*!< Selects the Trigger active edge. Note: This parameter is used only when an external trigger is used. This parameter can be a value of @ref LPTIM_External_Trigger_Polarity */ uint32_t SampleTime; /*!< Selects the trigger sampling time to configure the clock glitch filter. Note: This parameter is used only when an external trigger is used. This parameter can be a value of @ref LPTIM_Trigger_Sample_Time */ }LPTIM_TriggerConfigTypeDef; /** * @brief LPTIM Initialization Structure definition */ typedef struct { LPTIM_ClockConfigTypeDef Clock; /*!< Specifies the clock parameters */ LPTIM_ULPClockConfigTypeDef UltraLowPowerClock; /*!< Specifies the Ultra Low Power clock parameters */ LPTIM_TriggerConfigTypeDef Trigger; /*!< Specifies the Trigger parameters */ uint32_t OutputPolarity; /*!< Specifies the Output polarity. This parameter can be a value of @ref LPTIM_Output_Polarity */ uint32_t UpdateMode; /*!< Specifies whether the update of the autorelaod and the compare values is done immediately or after the end of current period. This parameter can be a value of @ref LPTIM_Updating_Mode */ uint32_t CounterSource; /*!< Specifies whether the counter is incremented each internal event or each external event. This parameter can be a value of @ref LPTIM_Counter_Source */ }LPTIM_InitTypeDef; /** * @brief HAL LPTIM State structure definition */ typedef enum __HAL_LPTIM_StateTypeDef { HAL_LPTIM_STATE_RESET = 0x00, /*!< Peripheral not yet initialized or disabled */ HAL_LPTIM_STATE_READY = 0x01, /*!< Peripheral Initialized and ready for use */ HAL_LPTIM_STATE_BUSY = 0x02, /*!< An internal process is ongoing */ HAL_LPTIM_STATE_TIMEOUT = 0x03, /*!< Timeout state */ HAL_LPTIM_STATE_ERROR = 0x04 /*!< Internal Process is ongoing */ }HAL_LPTIM_StateTypeDef; /** * @brief LPTIM handle Structure definition */ typedef struct { LPTIM_TypeDef *Instance; /*!< Register base address */ LPTIM_InitTypeDef Init; /*!< LPTIM required parameters */ HAL_StatusTypeDef Status; /*!< LPTIM peripheral status */ HAL_LockTypeDef Lock; /*!< LPTIM locking object */ __IO HAL_LPTIM_StateTypeDef State; /*!< LPTIM peripheral state */ }LPTIM_HandleTypeDef; /** * @} */ /* Exported constants --------------------------------------------------------*/ /** @defgroup LPTIM_Exported_Constants LPTIM Exported Constants * @{ */ /** @defgroup LPTIM_Clock_Source LPTIM Clock Source * @{ */ #define LPTIM_CLOCKSOURCE_APBCLOCK_LPOSC ((uint32_t)0x00) #define LPTIM_CLOCKSOURCE_ULPTIM LPTIM_CFGR_CKSEL /** * @} */ /** @defgroup LPTIM_Clock_Prescaler LPTIM Clock Prescaler * @{ */ #define LPTIM_PRESCALER_DIV1 ((uint32_t)0x000000) #define LPTIM_PRESCALER_DIV2 LPTIM_CFGR_PRESC_0 #define LPTIM_PRESCALER_DIV4 LPTIM_CFGR_PRESC_1 #define LPTIM_PRESCALER_DIV8 ((uint32_t)(LPTIM_CFGR_PRESC_0 | LPTIM_CFGR_PRESC_1)) #define LPTIM_PRESCALER_DIV16 LPTIM_CFGR_PRESC_2 #define LPTIM_PRESCALER_DIV32 ((uint32_t)(LPTIM_CFGR_PRESC_0 | LPTIM_CFGR_PRESC_2)) #define LPTIM_PRESCALER_DIV64 ((uint32_t)(LPTIM_CFGR_PRESC_1 | LPTIM_CFGR_PRESC_2)) #define LPTIM_PRESCALER_DIV128 ((uint32_t)LPTIM_CFGR_PRESC) /** * @} */ /** @defgroup LPTIM_Output_Polarity LPTIM Output Polarity * @{ */ #define LPTIM_OUTPUTPOLARITY_HIGH ((uint32_t)0x00000000) #define LPTIM_OUTPUTPOLARITY_LOW (LPTIM_CFGR_WAVPOL) /** * @} */ /** @defgroup LPTIM_Clock_Sample_Time LPTIM Clock Sample Time * @{ */ #define LPTIM_CLOCKSAMPLETIME_DIRECTTRANSITION ((uint32_t)0x00000000) #define LPTIM_CLOCKSAMPLETIME_2TRANSITIONS LPTIM_CFGR_CKFLT_0 #define LPTIM_CLOCKSAMPLETIME_4TRANSITIONS LPTIM_CFGR_CKFLT_1 #define LPTIM_CLOCKSAMPLETIME_8TRANSITIONS LPTIM_CFGR_CKFLT /** * @} */ /** @defgroup LPTIM_Clock_Polarity LPTIM Clock Polarity * @{ */ #define LPTIM_CLOCKPOLARITY_RISING ((uint32_t)0x00000000) #define LPTIM_CLOCKPOLARITY_FALLING LPTIM_CFGR_CKPOL_0 #define LPTIM_CLOCKPOLARITY_RISING_FALLING LPTIM_CFGR_CKPOL_1 /** * @} */ /** @defgroup LPTIM_Trigger_Source LPTIM Trigger Source * @{ */ #define LPTIM_TRIGSOURCE_SOFTWARE ((uint32_t)0x0000FFFF) #define LPTIM_TRIGSOURCE_0 ((uint32_t)0x00000000) #define LPTIM_TRIGSOURCE_1 ((uint32_t)LPTIM_CFGR_TRIGSEL_0) #define LPTIM_TRIGSOURCE_2 LPTIM_CFGR_TRIGSEL_1 #define LPTIM_TRIGSOURCE_3 ((uint32_t)LPTIM_CFGR_TRIGSEL_0 | LPTIM_CFGR_TRIGSEL_1) #define LPTIM_TRIGSOURCE_4 LPTIM_CFGR_TRIGSEL_2 #define LPTIM_TRIGSOURCE_5 ((uint32_t)LPTIM_CFGR_TRIGSEL_0 | LPTIM_CFGR_TRIGSEL_2) /** * @} */ /** @defgroup LPTIM_External_Trigger_Polarity LPTIM External Trigger Polarity * @{ */ #define LPTIM_ACTIVEEDGE_RISING LPTIM_CFGR_TRIGEN_0 #define LPTIM_ACTIVEEDGE_FALLING LPTIM_CFGR_TRIGEN_1 #define LPTIM_ACTIVEEDGE_RISING_FALLING LPTIM_CFGR_TRIGEN /** * @} */ /** @defgroup LPTIM_Trigger_Sample_Time LPTIM Trigger Sample Time * @{ */ #define LPTIM_TRIGSAMPLETIME_DIRECTTRANSITION ((uint32_t)0x00000000) #define LPTIM_TRIGSAMPLETIME_2TRANSITIONS LPTIM_CFGR_TRGFLT_0 #define LPTIM_TRIGSAMPLETIME_4TRANSITIONS LPTIM_CFGR_TRGFLT_1 #define LPTIM_TRIGSAMPLETIME_8TRANSITIONS LPTIM_CFGR_TRGFLT /** * @} */ /** @defgroup LPTIM_Updating_Mode LPTIM Updating Mode * @{ */ #define LPTIM_UPDATE_IMMEDIATE ((uint32_t)0x00000000) #define LPTIM_UPDATE_ENDOFPERIOD LPTIM_CFGR_PRELOAD /** * @} */ /** @defgroup LPTIM_Counter_Source LPTIM Counter Source * @{ */ #define LPTIM_COUNTERSOURCE_INTERNAL ((uint32_t)0x00000000) #define LPTIM_COUNTERSOURCE_EXTERNAL LPTIM_CFGR_COUNTMODE /** * @} */ /** @defgroup LPTIM_Flag_Definition LPTIM Flag Definition * @{ */ #define LPTIM_FLAG_DOWN LPTIM_ISR_DOWN #define LPTIM_FLAG_UP LPTIM_ISR_UP #define LPTIM_FLAG_ARROK LPTIM_ISR_ARROK #define LPTIM_FLAG_CMPOK LPTIM_ISR_CMPOK #define LPTIM_FLAG_EXTTRIG LPTIM_ISR_EXTTRIG #define LPTIM_FLAG_ARRM LPTIM_ISR_ARRM #define LPTIM_FLAG_CMPM LPTIM_ISR_CMPM /** * @} */ /** @defgroup LPTIM_Interrupts_Definition LPTIM Interrupts Definition * @{ */ #define LPTIM_IT_DOWN LPTIM_IER_DOWNIE #define LPTIM_IT_UP LPTIM_IER_UPIE #define LPTIM_IT_ARROK LPTIM_IER_ARROKIE #define LPTIM_IT_CMPOK LPTIM_IER_CMPOKIE #define LPTIM_IT_EXTTRIG LPTIM_IER_EXTTRIGIE #define LPTIM_IT_ARRM LPTIM_IER_ARRMIE #define LPTIM_IT_CMPM LPTIM_IER_CMPMIE /** * @} */ /** @defgroup LPTIM_Option Register Definition * @{ */ #define LPTIM_OP_PAD_AF ((uint32_t)0x00000000) #define LPTIM_OP_PAD_PA4 LPTIM_OR_OR_0 #define LPTIM_OP_PAD_PB9 LPTIM_OR_OR_1 #define LPTIM_OP_TIM_DAC LPTIM_OR_OR /** * @} */ /** * @} */ /* Exported macro ------------------------------------------------------------*/ /** @defgroup LPTIM_Exported_Macros LPTIM Exported Macros * @{ */ /** @brief Reset LPTIM handle state * @param __HANDLE__: LPTIM handle * @retval None */ #define __HAL_LPTIM_RESET_HANDLE_STATE(__HANDLE__) ((__HANDLE__)->State = HAL_LPTIM_STATE_RESET) /** * @brief Enable/Disable the LPTIM peripheral. * @param __HANDLE__: LPTIM handle * @retval None */ #define __HAL_LPTIM_ENABLE(__HANDLE__) ((__HANDLE__)->Instance->CR |= (LPTIM_CR_ENABLE)) #define __HAL_LPTIM_DISABLE(__HANDLE__) ((__HANDLE__)->Instance->CR &= ~(LPTIM_CR_ENABLE)) /** * @brief Starts the LPTIM peripheral in Continuous or in single mode. * @param __HANDLE__: DMA handle * @retval None */ #define __HAL_LPTIM_START_CONTINUOUS(__HANDLE__) ((__HANDLE__)->Instance->CR |= LPTIM_CR_CNTSTRT) #define __HAL_LPTIM_START_SINGLE(__HANDLE__) ((__HANDLE__)->Instance->CR |= LPTIM_CR_SNGSTRT) /** * @brief Writes the passed parameter in the Autoreload register. * @param __HANDLE__: LPTIM handle * @param __VALUE__ : Autoreload value * @retval None */ #define __HAL_LPTIM_AUTORELOAD_SET(__HANDLE__ , __VALUE__) ((__HANDLE__)->Instance->ARR = (__VALUE__)) /** * @brief Writes the passed parameter in the Compare register. * @param __HANDLE__: LPTIM handle * @param __VALUE__ : Compare value * @retval None */ #define __HAL_LPTIM_COMPARE_SET(__HANDLE__ , __VALUE__) ((__HANDLE__)->Instance->CMP = (__VALUE__)) /** * @brief Checks whether the specified LPTIM flag is set or not. * @param __HANDLE__: LPTIM handle * @param __FLAG__ : LPTIM flag to check * This parameter can be a value of: * @arg LPTIM_FLAG_DOWN : Counter direction change up Flag. * @arg LPTIM_FLAG_UP : Counter direction change down to up Flag. * @arg LPTIM_FLAG_ARROK : Autoreload register update OK Flag. * @arg LPTIM_FLAG_CMPOK : Compare register update OK Flag. * @arg LPTIM_FLAG_EXTTRIG : External trigger edge event Flag. * @arg LPTIM_FLAG_ARRM : Autoreload match Flag. * @arg LPTIM_FLAG_CMPM : Compare match Flag. * @retval The state of the specified flag (SET or RESET). */ #define __HAL_LPTIM_GET_FLAG(__HANDLE__, __FLAG__) (((__HANDLE__)->Instance->ISR &(__FLAG__)) == (__FLAG__)) /** * @brief Clears the specified LPTIM flag. * @param __HANDLE__: LPTIM handle. * @param __FLAG__ : LPTIM flag to clear. * This parameter can be a value of: * @arg LPTIM_FLAG_DOWN : Counter direction change up Flag. * @arg LPTIM_FLAG_UP : Counter direction change down to up Flag. * @arg LPTIM_FLAG_ARROK : Autoreload register update OK Flag. * @arg LPTIM_FLAG_CMPOK : Compare register update OK Flag. * @arg LPTIM_FLAG_EXTTRIG : External trigger edge event Flag. * @arg LPTIM_FLAG_ARRM : Autoreload match Flag. * @arg LPTIM_FLAG_CMPM : Compare match Flag. * @retval None. */ #define __HAL_LPTIM_CLEAR_FLAG(__HANDLE__, __FLAG__) ((__HANDLE__)->Instance->ICR = (__FLAG__)) /** * @brief Enable the specified LPTIM interrupt. * @param __HANDLE__ : LPTIM handle. * @param __INTERRUPT__ : LPTIM interrupt to set. * This parameter can be a value of: * @arg LPTIM_IT_DOWN : Counter direction change up Interrupt. * @arg LPTIM_IT_UP : Counter direction change down to up Interrupt. * @arg LPTIM_IT_ARROK : Autoreload register update OK Interrupt. * @arg LPTIM_IT_CMPOK : Compare register update OK Interrupt. * @arg LPTIM_IT_EXTTRIG : External trigger edge event Interrupt. * @arg LPTIM_IT_ARRM : Autoreload match Interrupt. * @arg LPTIM_IT_CMPM : Compare match Interrupt. * @retval None. */ #define __HAL_LPTIM_ENABLE_IT(__HANDLE__, __INTERRUPT__) ((__HANDLE__)->Instance->IER |= (__INTERRUPT__)) /** * @brief Disable the specified LPTIM interrupt. * @param __HANDLE__ : LPTIM handle. * @param __INTERRUPT__ : LPTIM interrupt to set. * This parameter can be a value of: * @arg LPTIM_IT_DOWN : Counter direction change up Interrupt. * @arg LPTIM_IT_UP : Counter direction change down to up Interrupt. * @arg LPTIM_IT_ARROK : Autoreload register update OK Interrupt. * @arg LPTIM_IT_CMPOK : Compare register update OK Interrupt. * @arg LPTIM_IT_EXTTRIG : External trigger edge event Interrupt. * @arg LPTIM_IT_ARRM : Autoreload match Interrupt. * @arg LPTIM_IT_CMPM : Compare match Interrupt. * @retval None. */ #define __HAL_LPTIM_DISABLE_IT(__HANDLE__, __INTERRUPT__) ((__HANDLE__)->Instance->IER &= (~(__INTERRUPT__))) /** * @brief Checks whether the specified LPTIM interrupt is set or not. * @param __HANDLE__ : LPTIM handle. * @param __INTERRUPT__ : LPTIM interrupt to check. * This parameter can be a value of: * @arg LPTIM_IT_DOWN : Counter direction change up Interrupt. * @arg LPTIM_IT_UP : Counter direction change down to up Interrupt. * @arg LPTIM_IT_ARROK : Autoreload register update OK Interrupt. * @arg LPTIM_IT_CMPOK : Compare register update OK Interrupt. * @arg LPTIM_IT_EXTTRIG : External trigger edge event Interrupt. * @arg LPTIM_IT_ARRM : Autoreload match Interrupt. * @arg LPTIM_IT_CMPM : Compare match Interrupt. * @retval Interrupt status. */ #define __HAL_LPTIM_GET_IT_SOURCE(__HANDLE__, __INTERRUPT__) ((((__HANDLE__)->Instance->IER & (__INTERRUPT__)) == (__INTERRUPT__)) ? SET : RESET) /** @brief LPTIM Option Register * @param __HANDLE__: LPTIM handle * @param __VALUE__: This parameter can be a value of : * @arg LPTIM_OP_PAD_AF * @arg LPTIM_OP_PAD_PA4 * @arg LPTIM_OP_PAD_PB9 * @arg LPTIM_OP_TIM_DAC * @retval None */ #define __HAL_LPTIM_OPTR_CONFIG(__HANDLE__ , __VALUE__) ((__HANDLE__)->Instance->OR = (__VALUE__)) /** * @brief Enable interrupt on the LPTIM Wake-up Timer associated Exti line. * @retval None */ #define __HAL_LPTIM_WAKEUPTIMER_EXTI_ENABLE_IT() (EXTI->IMR |= LPTIM_EXTI_LINE_WAKEUPTIMER_EVENT) /** * @brief Disable interrupt on the LPTIM Wake-up Timer associated Exti line. * @retval None */ #define __HAL_LPTIM_WAKEUPTIMER_EXTI_DISABLE_IT() (EXTI->IMR &= ~(LPTIM_EXTI_LINE_WAKEUPTIMER_EVENT)) /** * @brief Enable event on the LPTIM Wake-up Timer associated Exti line. * @retval None. */ #define __HAL_LPTIM_WAKEUPTIMER_EXTI_ENABLE_EVENT() (EXTI->EMR |= LPTIM_EXTI_LINE_WAKEUPTIMER_EVENT) /** * @brief Disable event on the LPTIM Wake-up Timer associated Exti line. * @retval None. */ #define __HAL_LPTIM_WAKEUPTIMER_EXTI_DISABLE_EVENT() (EXTI->EMR &= ~(LPTIM_EXTI_LINE_WAKEUPTIMER_EVENT)) /** * @brief Enable falling edge trigger on the LPTIM Wake-up Timer associated Exti line. * @retval None. */ #define __HAL_LPTIM_WAKEUPTIMER_EXTI_ENABLE_FALLING_EDGE() (EXTI->FTSR |= LPTIM_EXTI_LINE_WAKEUPTIMER_EVENT) /** * @brief Disable falling edge trigger on the LPTIM Wake-up Timer associated Exti line. * @retval None. */ #define __HAL_LPTIM_WAKEUPTIMER_EXTI_DISABLE_FALLING_EDGE() (EXTI->FTSR &= ~(LPTIM_EXTI_LINE_WAKEUPTIMER_EVENT)) /** * @brief Enable rising edge trigger on the LPTIM Wake-up Timer associated Exti line. * @retval None. */ #define __HAL_LPTIM_WAKEUPTIMER_EXTI_ENABLE_RISING_EDGE() (EXTI->RTSR |= LPTIM_EXTI_LINE_WAKEUPTIMER_EVENT) /** * @brief Disable rising edge trigger on the LPTIM Wake-up Timer associated Exti line. * @retval None. */ #define __HAL_LPTIM_WAKEUPTIMER_EXTI_DISABLE_RISING_EDGE() (EXTI->RTSR &= ~(LPTIM_EXTI_LINE_WAKEUPTIMER_EVENT)) /** * @brief Enable rising & falling edge trigger on the LPTIM Wake-up Timer associated Exti line. * @retval None. */ #define __HAL_LPTIM_WAKEUPTIMER_EXTI_ENABLE_RISING_FALLING_EDGE() __HAL_LPTIM_WAKEUPTIMER_EXTI_ENABLE_RISING_EDGE();__HAL_LPTIM_WAKEUPTIMER_EXTI_ENABLE_FALLING_EDGE(); /** * @brief Disable rising & falling edge trigger on the LPTIM Wake-up Timer associated Exti line. * This parameter can be: * @retval None. */ #define __HAL_LPTIM_WAKEUPTIMER_EXTI_DISABLE_RISING_FALLING_EDGE() __HAL_LPTIM_WAKEUPTIMER_EXTI_DISABLE_RISING_EDGE();__HAL_LPTIM_WAKEUPTIMER_EXTI_DISABLE_FALLING_EDGE(); /** * @brief Check whether the LPTIM Wake-up Timer associated Exti line interrupt flag is set or not. * @retval Line Status. */ #define __HAL_LPTIM_WAKEUPTIMER_EXTI_GET_FLAG() (EXTI->PR & LPTIM_EXTI_LINE_WAKEUPTIMER_EVENT) /** * @brief Clear the LPTIM Wake-up Timer associated Exti line flag. * @retval None. */ #define __HAL_LPTIM_WAKEUPTIMER_EXTI_CLEAR_FLAG() (EXTI->PR = LPTIM_EXTI_LINE_WAKEUPTIMER_EVENT) /** * @brief Generate a Software interrupt on the LPTIM Wake-up Timer associated Exti line. * @retval None. */ #define __HAL_LPTIM_WAKEUPTIMER_EXTI_GENERATE_SWIT() (EXTI->SWIER |= LPTIM_EXTI_LINE_WAKEUPTIMER_EVENT) /** * @} */ /* Exported functions --------------------------------------------------------*/ /** @defgroup LPTIM_Exported_Functions LPTIM Exported Functions * @{ */ /* Initialization/de-initialization functions ********************************/ HAL_StatusTypeDef HAL_LPTIM_Init(LPTIM_HandleTypeDef *hlptim); HAL_StatusTypeDef HAL_LPTIM_DeInit(LPTIM_HandleTypeDef *hlptim); /* MSP functions *************************************************************/ void HAL_LPTIM_MspInit(LPTIM_HandleTypeDef *hlptim); void HAL_LPTIM_MspDeInit(LPTIM_HandleTypeDef *hlptim); /* Start/Stop operation functions *********************************************/ /* ################################# PWM Mode ################################*/ /* Blocking mode: Polling */ HAL_StatusTypeDef HAL_LPTIM_PWM_Start(LPTIM_HandleTypeDef *hlptim, uint32_t Period, uint32_t Pulse); HAL_StatusTypeDef HAL_LPTIM_PWM_Stop(LPTIM_HandleTypeDef *hlptim); /* Non-Blocking mode: Interrupt */ HAL_StatusTypeDef HAL_LPTIM_PWM_Start_IT(LPTIM_HandleTypeDef *hlptim, uint32_t Period, uint32_t Pulse); HAL_StatusTypeDef HAL_LPTIM_PWM_Stop_IT(LPTIM_HandleTypeDef *hlptim); /* ############################# One Pulse Mode ##############################*/ /* Blocking mode: Polling */ HAL_StatusTypeDef HAL_LPTIM_OnePulse_Start(LPTIM_HandleTypeDef *hlptim, uint32_t Period, uint32_t Pulse); HAL_StatusTypeDef HAL_LPTIM_OnePulse_Stop(LPTIM_HandleTypeDef *hlptim); /* Non-Blocking mode: Interrupt */ HAL_StatusTypeDef HAL_LPTIM_OnePulse_Start_IT(LPTIM_HandleTypeDef *hlptim, uint32_t Period, uint32_t Pulse); HAL_StatusTypeDef HAL_LPTIM_OnePulse_Stop_IT(LPTIM_HandleTypeDef *hlptim); /* ############################## Set once Mode ##############################*/ /* Blocking mode: Polling */ HAL_StatusTypeDef HAL_LPTIM_SetOnce_Start(LPTIM_HandleTypeDef *hlptim, uint32_t Period, uint32_t Pulse); HAL_StatusTypeDef HAL_LPTIM_SetOnce_Stop(LPTIM_HandleTypeDef *hlptim); /* Non-Blocking mode: Interrupt */ HAL_StatusTypeDef HAL_LPTIM_SetOnce_Start_IT(LPTIM_HandleTypeDef *hlptim, uint32_t Period, uint32_t Pulse); HAL_StatusTypeDef HAL_LPTIM_SetOnce_Stop_IT(LPTIM_HandleTypeDef *hlptim); /* ############################### Encoder Mode ##############################*/ /* Blocking mode: Polling */ HAL_StatusTypeDef HAL_LPTIM_Encoder_Start(LPTIM_HandleTypeDef *hlptim, uint32_t Period); HAL_StatusTypeDef HAL_LPTIM_Encoder_Stop(LPTIM_HandleTypeDef *hlptim); /* Non-Blocking mode: Interrupt */ HAL_StatusTypeDef HAL_LPTIM_Encoder_Start_IT(LPTIM_HandleTypeDef *hlptim, uint32_t Period); HAL_StatusTypeDef HAL_LPTIM_Encoder_Stop_IT(LPTIM_HandleTypeDef *hlptim); /* ############################# Time out Mode ##############################*/ /* Blocking mode: Polling */ HAL_StatusTypeDef HAL_LPTIM_TimeOut_Start(LPTIM_HandleTypeDef *hlptim, uint32_t Period, uint32_t Timeout); HAL_StatusTypeDef HAL_LPTIM_TimeOut_Stop(LPTIM_HandleTypeDef *hlptim); /* Non-Blocking mode: Interrupt */ HAL_StatusTypeDef HAL_LPTIM_TimeOut_Start_IT(LPTIM_HandleTypeDef *hlptim, uint32_t Period, uint32_t Timeout); HAL_StatusTypeDef HAL_LPTIM_TimeOut_Stop_IT(LPTIM_HandleTypeDef *hlptim); /* ############################## Counter Mode ###############################*/ /* Blocking mode: Polling */ HAL_StatusTypeDef HAL_LPTIM_Counter_Start(LPTIM_HandleTypeDef *hlptim, uint32_t Period); HAL_StatusTypeDef HAL_LPTIM_Counter_Stop(LPTIM_HandleTypeDef *hlptim); /* Non-Blocking mode: Interrupt */ HAL_StatusTypeDef HAL_LPTIM_Counter_Start_IT(LPTIM_HandleTypeDef *hlptim, uint32_t Period); HAL_StatusTypeDef HAL_LPTIM_Counter_Stop_IT(LPTIM_HandleTypeDef *hlptim); /* Reading operation functions ************************************************/ uint32_t HAL_LPTIM_ReadCounter(LPTIM_HandleTypeDef *hlptim); uint32_t HAL_LPTIM_ReadAutoReload(LPTIM_HandleTypeDef *hlptim); uint32_t HAL_LPTIM_ReadCompare(LPTIM_HandleTypeDef *hlptim); /* LPTIM IRQ functions *******************************************************/ void HAL_LPTIM_IRQHandler(LPTIM_HandleTypeDef *hlptim); /* CallBack functions ********************************************************/ void HAL_LPTIM_CompareMatchCallback(LPTIM_HandleTypeDef *hlptim); void HAL_LPTIM_AutoReloadMatchCallback(LPTIM_HandleTypeDef *hlptim); void HAL_LPTIM_TriggerCallback(LPTIM_HandleTypeDef *hlptim); void HAL_LPTIM_CompareWriteCallback(LPTIM_HandleTypeDef *hlptim); void HAL_LPTIM_AutoReloadWriteCallback(LPTIM_HandleTypeDef *hlptim); void HAL_LPTIM_DirectionUpCallback(LPTIM_HandleTypeDef *hlptim); void HAL_LPTIM_DirectionDownCallback(LPTIM_HandleTypeDef *hlptim); /* Peripheral State functions ************************************************/ HAL_LPTIM_StateTypeDef HAL_LPTIM_GetState(LPTIM_HandleTypeDef *hlptim); /** * @} */ /* Private types -------------------------------------------------------------*/ /** @defgroup LPTIM_Private_Types LPTIM Private Types * @{ */ /** * @} */ /* Private variables ---------------------------------------------------------*/ /** @defgroup LPTIM_Private_Variables LPTIM Private Variables * @{ */ /** * @} */ /* Private constants ---------------------------------------------------------*/ /** @defgroup LPTIM_Private_Constants LPTIM Private Constants * @{ */ /** * @} */ /* Private macros ------------------------------------------------------------*/ /** @defgroup LPTIM_Private_Macros LPTIM Private Macros * @{ */ #define IS_LPTIM_CLOCK_SOURCE(__SOURCE__) (((__SOURCE__) == LPTIM_CLOCKSOURCE_ULPTIM) || \ ((__SOURCE__) == LPTIM_CLOCKSOURCE_APBCLOCK_LPOSC)) #define IS_LPTIM_CLOCK_PRESCALER(__PRESCALER__) (((__PRESCALER__) == LPTIM_PRESCALER_DIV1 ) || \ ((__PRESCALER__) == LPTIM_PRESCALER_DIV2 ) || \ ((__PRESCALER__) == LPTIM_PRESCALER_DIV4 ) || \ ((__PRESCALER__) == LPTIM_PRESCALER_DIV8 ) || \ ((__PRESCALER__) == LPTIM_PRESCALER_DIV16 ) || \ ((__PRESCALER__) == LPTIM_PRESCALER_DIV32 ) || \ ((__PRESCALER__) == LPTIM_PRESCALER_DIV64 ) || \ ((__PRESCALER__) == LPTIM_PRESCALER_DIV128)) #define IS_LPTIM_CLOCK_PRESCALERDIV1(__PRESCALER__) ((__PRESCALER__) == LPTIM_PRESCALER_DIV1) #define IS_LPTIM_OUTPUT_POLARITY(__POLARITY__) (((__POLARITY__) == LPTIM_OUTPUTPOLARITY_LOW ) || \ ((__POLARITY__) == LPTIM_OUTPUTPOLARITY_HIGH)) #define IS_LPTIM_CLOCK_SAMPLE_TIME(__SAMPLETIME__) (((__SAMPLETIME__) == LPTIM_CLOCKSAMPLETIME_DIRECTTRANSITION) || \ ((__SAMPLETIME__) == LPTIM_CLOCKSAMPLETIME_2TRANSITIONS) || \ ((__SAMPLETIME__) == LPTIM_CLOCKSAMPLETIME_4TRANSITIONS) || \ ((__SAMPLETIME__) == LPTIM_CLOCKSAMPLETIME_8TRANSITIONS)) #define IS_LPTIM_CLOCK_POLARITY(__POLARITY__) (((__POLARITY__) == LPTIM_CLOCKPOLARITY_RISING) || \ ((__POLARITY__) == LPTIM_CLOCKPOLARITY_FALLING) || \ ((__POLARITY__) == LPTIM_CLOCKPOLARITY_RISING_FALLING)) #define IS_LPTIM_TRG_SOURCE(__TRIG__) (((__TRIG__) == LPTIM_TRIGSOURCE_SOFTWARE) || \ ((__TRIG__) == LPTIM_TRIGSOURCE_0) || \ ((__TRIG__) == LPTIM_TRIGSOURCE_1) || \ ((__TRIG__) == LPTIM_TRIGSOURCE_2) || \ ((__TRIG__) == LPTIM_TRIGSOURCE_3) || \ ((__TRIG__) == LPTIM_TRIGSOURCE_4) || \ ((__TRIG__) == LPTIM_TRIGSOURCE_5)) #define IS_LPTIM_EXT_TRG_POLARITY(__POLAR__) (((__POLAR__) == LPTIM_ACTIVEEDGE_RISING ) || \ ((__POLAR__) == LPTIM_ACTIVEEDGE_FALLING ) || \ ((__POLAR__) == LPTIM_ACTIVEEDGE_RISING_FALLING )) #define IS_LPTIM_TRIG_SAMPLE_TIME(__SAMPLETIME__) (((__SAMPLETIME__) == LPTIM_TRIGSAMPLETIME_DIRECTTRANSITION) || \ ((__SAMPLETIME__) == LPTIM_TRIGSAMPLETIME_2TRANSITIONS ) || \ ((__SAMPLETIME__) == LPTIM_TRIGSAMPLETIME_4TRANSITIONS ) || \ ((__SAMPLETIME__) == LPTIM_TRIGSAMPLETIME_8TRANSITIONS )) #define IS_LPTIM_UPDATE_MODE(__MODE__) (((__MODE__) == LPTIM_UPDATE_IMMEDIATE) || \ ((__MODE__) == LPTIM_UPDATE_ENDOFPERIOD)) #define IS_LPTIM_COUNTER_SOURCE(__SOURCE__) (((__SOURCE__) == LPTIM_COUNTERSOURCE_INTERNAL) || \ ((__SOURCE__) == LPTIM_COUNTERSOURCE_EXTERNAL)) #define IS_LPTIM_AUTORELOAD(__AUTORELOAD__) ((__AUTORELOAD__) <= 0x0000FFFF) #define IS_LPTIM_COMPARE(__COMPARE__) ((__COMPARE__) <= 0x0000FFFF) #define IS_LPTIM_PERIOD(PERIOD) ((PERIOD) <= 0x0000FFFF) #define IS_LPTIM_PULSE(PULSE) ((PULSE) <= 0x0000FFFF) /** * @} */ /* Private functions ---------------------------------------------------------*/ /** @defgroup LPTIM_Private_Functions LPTIM Private Functions * @{ */ /** * @} */ /** * @} */ /** * @} */ #endif /* STM32F410Tx || STM32F410Cx || STM32F410Rx */ #ifdef __cplusplus } #endif #endif /* __STM32F4xx_HAL_LPTIM_H */ /************************ (C) COPYRIGHT STMicroelectronics *****END OF FILE****/ ================================================ FILE: Zelig/mbed/TARGET_NUCLEO_F401RE/stm32f4xx_hal_ltdc.h ================================================ /** ****************************************************************************** * @file stm32f4xx_hal_ltdc.h * @author MCD Application Team * @version V1.4.1 * @date 09-October-2015 * @brief Header file of LTDC HAL module. ****************************************************************************** * @attention * *

© COPYRIGHT(c) 2015 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. * ****************************************************************************** */ /* Define to prevent recursive inclusion -------------------------------------*/ #ifndef __STM32F4xx_HAL_LTDC_H #define __STM32F4xx_HAL_LTDC_H #ifdef __cplusplus extern "C" { #endif #if defined(STM32F429xx) || defined(STM32F439xx) || defined(STM32F469xx) || defined(STM32F479xx) /* Includes ------------------------------------------------------------------*/ #include "stm32f4xx_hal_def.h" /** @addtogroup STM32F4xx_HAL_Driver * @{ */ /** @defgroup LTDC LTDC * @brief LTDC HAL module driver * @{ */ /* Exported types ------------------------------------------------------------*/ /** @defgroup LTDC_Exported_Types LTDC Exported Types * @{ */ #define MAX_LAYER 2 /** * @brief LTDC color structure definition */ typedef struct { uint8_t Blue; /*!< Configures the blue value. This parameter must be a number between Min_Data = 0x00 and Max_Data = 0xFF. */ uint8_t Green; /*!< Configures the green value. This parameter must be a number between Min_Data = 0x00 and Max_Data = 0xFF. */ uint8_t Red; /*!< Configures the red value. This parameter must be a number between Min_Data = 0x00 and Max_Data = 0xFF. */ uint8_t Reserved; /*!< Reserved 0xFF */ } LTDC_ColorTypeDef; /** * @brief LTDC Init structure definition */ typedef struct { uint32_t HSPolarity; /*!< configures the horizontal synchronization polarity. This parameter can be one value of @ref LTDC_HS_POLARITY */ uint32_t VSPolarity; /*!< configures the vertical synchronization polarity. This parameter can be one value of @ref LTDC_VS_POLARITY */ uint32_t DEPolarity; /*!< configures the data enable polarity. This parameter can be one of value of @ref LTDC_DE_POLARITY */ uint32_t PCPolarity; /*!< configures the pixel clock polarity. This parameter can be one of value of @ref LTDC_PC_POLARITY */ uint32_t HorizontalSync; /*!< configures the number of Horizontal synchronization width. This parameter must be a number between Min_Data = 0x000 and Max_Data = 0xFFF. */ uint32_t VerticalSync; /*!< configures the number of Vertical synchronization height. This parameter must be a number between Min_Data = 0x000 and Max_Data = 0x7FF. */ uint32_t AccumulatedHBP; /*!< configures the accumulated horizontal back porch width. This parameter must be a number between Min_Data = LTDC_HorizontalSync and Max_Data = 0xFFF. */ uint32_t AccumulatedVBP; /*!< configures the accumulated vertical back porch height. This parameter must be a number between Min_Data = LTDC_VerticalSync and Max_Data = 0x7FF. */ uint32_t AccumulatedActiveW; /*!< configures the accumulated active width. This parameter must be a number between Min_Data = LTDC_AccumulatedHBP and Max_Data = 0xFFF. */ uint32_t AccumulatedActiveH; /*!< configures the accumulated active height. This parameter must be a number between Min_Data = LTDC_AccumulatedVBP and Max_Data = 0x7FF. */ uint32_t TotalWidth; /*!< configures the total width. This parameter must be a number between Min_Data = LTDC_AccumulatedActiveW and Max_Data = 0xFFF. */ uint32_t TotalHeigh; /*!< configures the total height. This parameter must be a number between Min_Data = LTDC_AccumulatedActiveH and Max_Data = 0x7FF. */ LTDC_ColorTypeDef Backcolor; /*!< Configures the background color. */ } LTDC_InitTypeDef; /** * @brief LTDC Layer structure definition */ typedef struct { uint32_t WindowX0; /*!< Configures the Window Horizontal Start Position. This parameter must be a number between Min_Data = 0x000 and Max_Data = 0xFFF. */ uint32_t WindowX1; /*!< Configures the Window Horizontal Stop Position. This parameter must be a number between Min_Data = 0x000 and Max_Data = 0xFFF. */ uint32_t WindowY0; /*!< Configures the Window vertical Start Position. This parameter must be a number between Min_Data = 0x000 and Max_Data = 0xFFF. */ uint32_t WindowY1; /*!< Configures the Window vertical Stop Position. This parameter must be a number between Min_Data = 0x0000 and Max_Data = 0xFFFF. */ uint32_t PixelFormat; /*!< Specifies the pixel format. This parameter can be one of value of @ref LTDC_Pixelformat */ uint32_t Alpha; /*!< Specifies the constant alpha used for blending. This parameter must be a number between Min_Data = 0x00 and Max_Data = 0xFF. */ uint32_t Alpha0; /*!< Configures the default alpha value. This parameter must be a number between Min_Data = 0x00 and Max_Data = 0xFF. */ uint32_t BlendingFactor1; /*!< Select the blending factor 1. This parameter can be one of value of @ref LTDC_BlendingFactor1 */ uint32_t BlendingFactor2; /*!< Select the blending factor 2. This parameter can be one of value of @ref LTDC_BlendingFactor2 */ uint32_t FBStartAdress; /*!< Configures the color frame buffer address */ uint32_t ImageWidth; /*!< Configures the color frame buffer line length. This parameter must be a number between Min_Data = 0x0000 and Max_Data = 0x1FFF. */ uint32_t ImageHeight; /*!< Specifies the number of line in frame buffer. This parameter must be a number between Min_Data = 0x000 and Max_Data = 0x7FF. */ LTDC_ColorTypeDef Backcolor; /*!< Configures the layer background color. */ } LTDC_LayerCfgTypeDef; /** * @brief HAL LTDC State structures definition */ typedef enum { HAL_LTDC_STATE_RESET = 0x00, /*!< LTDC not yet initialized or disabled */ HAL_LTDC_STATE_READY = 0x01, /*!< LTDC initialized and ready for use */ HAL_LTDC_STATE_BUSY = 0x02, /*!< LTDC internal process is ongoing */ HAL_LTDC_STATE_TIMEOUT = 0x03, /*!< LTDC Timeout state */ HAL_LTDC_STATE_ERROR = 0x04 /*!< LTDC state error */ }HAL_LTDC_StateTypeDef; /** * @brief LTDC handle Structure definition */ typedef struct { LTDC_TypeDef *Instance; /*!< LTDC Register base address */ LTDC_InitTypeDef Init; /*!< LTDC parameters */ LTDC_LayerCfgTypeDef LayerCfg[MAX_LAYER]; /*!< LTDC Layers parameters */ HAL_LockTypeDef Lock; /*!< LTDC Lock */ __IO HAL_LTDC_StateTypeDef State; /*!< LTDC state */ __IO uint32_t ErrorCode; /*!< LTDC Error code */ } LTDC_HandleTypeDef; /** * @} */ /* Exported constants --------------------------------------------------------*/ /** @defgroup LTDC_Exported_Constants LTDC Exported Constants * @{ */ /** @defgroup LTDC_Error_Code LTDC Error Code * @{ */ #define HAL_LTDC_ERROR_NONE ((uint32_t)0x00000000) /*!< LTDC No error */ #define HAL_LTDC_ERROR_TE ((uint32_t)0x00000001) /*!< LTDC Transfer error */ #define HAL_LTDC_ERROR_FU ((uint32_t)0x00000002) /*!< LTDC FIFO Underrun */ #define HAL_LTDC_ERROR_TIMEOUT ((uint32_t)0x00000020) /*!< LTDC Timeout error */ /** * @} */ /** @defgroup LTDC_HS_POLARITY LTDC HS POLARITY * @{ */ #define LTDC_HSPOLARITY_AL ((uint32_t)0x00000000) /*!< Horizontal Synchronization is active low. */ #define LTDC_HSPOLARITY_AH LTDC_GCR_HSPOL /*!< Horizontal Synchronization is active high. */ /** * @} */ /** @defgroup LTDC_VS_POLARITY LTDC VS POLARITY * @{ */ #define LTDC_VSPOLARITY_AL ((uint32_t)0x00000000) /*!< Vertical Synchronization is active low. */ #define LTDC_VSPOLARITY_AH LTDC_GCR_VSPOL /*!< Vertical Synchronization is active high. */ /** * @} */ /** @defgroup LTDC_DE_POLARITY LTDC DE POLARITY * @{ */ #define LTDC_DEPOLARITY_AL ((uint32_t)0x00000000) /*!< Data Enable, is active low. */ #define LTDC_DEPOLARITY_AH LTDC_GCR_DEPOL /*!< Data Enable, is active high. */ /** * @} */ /** @defgroup LTDC_PC_POLARITY LTDC PC POLARITY * @{ */ #define LTDC_PCPOLARITY_IPC ((uint32_t)0x00000000) /*!< input pixel clock. */ #define LTDC_PCPOLARITY_IIPC LTDC_GCR_PCPOL /*!< inverted input pixel clock. */ /** * @} */ /** @defgroup LTDC_SYNC LTDC SYNC * @{ */ #define LTDC_HORIZONTALSYNC (LTDC_SSCR_HSW >> 16) /*!< Horizontal synchronization width. */ #define LTDC_VERTICALSYNC LTDC_SSCR_VSH /*!< Vertical synchronization height. */ /** * @} */ /** @defgroup LTDC_BACK_COLOR LTDC BACK COLOR * @{ */ #define LTDC_COLOR ((uint32_t)0x000000FF) /*!< Color mask */ /** * @} */ /** @defgroup LTDC_BlendingFactor1 LTDC Blending Factor1 * @{ */ #define LTDC_BLENDING_FACTOR1_CA ((uint32_t)0x00000400) /*!< Blending factor : Cte Alpha */ #define LTDC_BLENDING_FACTOR1_PAxCA ((uint32_t)0x00000600) /*!< Blending factor : Cte Alpha x Pixel Alpha*/ /** * @} */ /** @defgroup LTDC_BlendingFactor2 LTDC Blending Factor2 * @{ */ #define LTDC_BLENDING_FACTOR2_CA ((uint32_t)0x00000005) /*!< Blending factor : Cte Alpha */ #define LTDC_BLENDING_FACTOR2_PAxCA ((uint32_t)0x00000007) /*!< Blending factor : Cte Alpha x Pixel Alpha*/ /** * @} */ /** @defgroup LTDC_Pixelformat LTDC Pixel format * @{ */ #define LTDC_PIXEL_FORMAT_ARGB8888 ((uint32_t)0x00000000) /*!< ARGB8888 LTDC pixel format */ #define LTDC_PIXEL_FORMAT_RGB888 ((uint32_t)0x00000001) /*!< RGB888 LTDC pixel format */ #define LTDC_PIXEL_FORMAT_RGB565 ((uint32_t)0x00000002) /*!< RGB565 LTDC pixel format */ #define LTDC_PIXEL_FORMAT_ARGB1555 ((uint32_t)0x00000003) /*!< ARGB1555 LTDC pixel format */ #define LTDC_PIXEL_FORMAT_ARGB4444 ((uint32_t)0x00000004) /*!< ARGB4444 LTDC pixel format */ #define LTDC_PIXEL_FORMAT_L8 ((uint32_t)0x00000005) /*!< L8 LTDC pixel format */ #define LTDC_PIXEL_FORMAT_AL44 ((uint32_t)0x00000006) /*!< AL44 LTDC pixel format */ #define LTDC_PIXEL_FORMAT_AL88 ((uint32_t)0x00000007) /*!< AL88 LTDC pixel format */ /** * @} */ /** @defgroup LTDC_Alpha LTDC Alpha * @{ */ #define LTDC_ALPHA LTDC_LxCACR_CONSTA /*!< LTDC Cte Alpha mask */ /** * @} */ /** @defgroup LTDC_LAYER_Config LTDC LAYER Config * @{ */ #define LTDC_STOPPOSITION (LTDC_LxWHPCR_WHSPPOS >> 16) /*!< LTDC Layer stop position */ #define LTDC_STARTPOSITION LTDC_LxWHPCR_WHSTPOS /*!< LTDC Layer start position */ #define LTDC_COLOR_FRAME_BUFFER LTDC_LxCFBLR_CFBLL /*!< LTDC Layer Line length */ #define LTDC_LINE_NUMBER LTDC_LxCFBLNR_CFBLNBR /*!< LTDC Layer Line number */ /** * @} */ /** @defgroup LTDC_Interrupts LTDC Interrupts * @{ */ #define LTDC_IT_LI LTDC_IER_LIE #define LTDC_IT_FU LTDC_IER_FUIE #define LTDC_IT_TE LTDC_IER_TERRIE #define LTDC_IT_RR LTDC_IER_RRIE /** * @} */ /** @defgroup LTDC_Flag LTDC Flag * @{ */ #define LTDC_FLAG_LI LTDC_ISR_LIF #define LTDC_FLAG_FU LTDC_ISR_FUIF #define LTDC_FLAG_TE LTDC_ISR_TERRIF #define LTDC_FLAG_RR LTDC_ISR_RRIF /** * @} */ /** * @} */ /* Exported macro ------------------------------------------------------------*/ /** @defgroup LTDC_Exported_Macros LTDC Exported Macros * @{ */ /** @brief Reset LTDC handle state * @param __HANDLE__: specifies the LTDC handle. * @retval None */ #define __HAL_LTDC_RESET_HANDLE_STATE(__HANDLE__) ((__HANDLE__)->State = HAL_LTDC_STATE_RESET) /** * @brief Enable the LTDC. * @param __HANDLE__: LTDC handle * @retval None. */ #define __HAL_LTDC_ENABLE(__HANDLE__) ((__HANDLE__)->Instance->GCR |= LTDC_GCR_LTDCEN) /** * @brief Disable the LTDC. * @param __HANDLE__: LTDC handle * @retval None. */ #define __HAL_LTDC_DISABLE(__HANDLE__) ((__HANDLE__)->Instance->GCR &= ~(LTDC_GCR_LTDCEN)) /** * @brief Enable the LTDC Layer. * @param __HANDLE__: LTDC handle * @param __LAYER__: Specify the layer to be enabled * This parameter can be 0 or 1 * @retval None. */ #define __HAL_LTDC_LAYER_ENABLE(__HANDLE__, __LAYER__) ((LTDC_LAYER((__HANDLE__), (__LAYER__)))->CR |= (uint32_t)LTDC_LxCR_LEN) /** * @brief Disable the LTDC Layer. * @param __HANDLE__: LTDC handle * @param __LAYER__: Specify the layer to be disabled * This parameter can be 0 or 1 * @retval None. */ #define __HAL_LTDC_LAYER_DISABLE(__HANDLE__, __LAYER__) ((LTDC_LAYER((__HANDLE__), (__LAYER__)))->CR &= ~(uint32_t)LTDC_LxCR_LEN) /** * @brief Reload Layer Configuration. * @param __HANDLE__: LTDC handle * @retval None. */ #define __HAL_LTDC_RELOAD_CONFIG(__HANDLE__) ((__HANDLE__)->Instance->SRCR |= LTDC_SRCR_IMR) /* Interrupt & Flag management */ /** * @brief Get the LTDC pending flags. * @param __HANDLE__: LTDC handle * @param __FLAG__: Get the specified flag. * This parameter can be any combination of the following values: * @arg LTDC_FLAG_LI: Line Interrupt flag * @arg LTDC_FLAG_FU: FIFO Underrun Interrupt flag * @arg LTDC_FLAG_TE: Transfer Error interrupt flag * @arg LTDC_FLAG_RR: Register Reload Interrupt Flag * @retval The state of FLAG (SET or RESET). */ #define __HAL_LTDC_GET_FLAG(__HANDLE__, __FLAG__) ((__HANDLE__)->Instance->ISR & (__FLAG__)) /** * @brief Clears the LTDC pending flags. * @param __HANDLE__: LTDC handle * @param __FLAG__: specifies the flag to clear. * This parameter can be any combination of the following values: * @arg LTDC_FLAG_LI: Line Interrupt flag * @arg LTDC_FLAG_FU: FIFO Underrun Interrupt flag * @arg LTDC_FLAG_TE: Transfer Error interrupt flag * @arg LTDC_FLAG_RR: Register Reload Interrupt Flag * @retval None */ #define __HAL_LTDC_CLEAR_FLAG(__HANDLE__, __FLAG__) ((__HANDLE__)->Instance->ICR = (__FLAG__)) /** * @brief Enables the specified LTDC interrupts. * @param __HANDLE__: LTDC handle * @param __INTERRUPT__: specifies the LTDC interrupt sources to be enabled. * This parameter can be any combination of the following values: * @arg LTDC_IT_LI: Line Interrupt flag * @arg LTDC_IT_FU: FIFO Underrun Interrupt flag * @arg LTDC_IT_TE: Transfer Error interrupt flag * @arg LTDC_IT_RR: Register Reload Interrupt Flag * @retval None */ #define __HAL_LTDC_ENABLE_IT(__HANDLE__, __INTERRUPT__) ((__HANDLE__)->Instance->IER |= (__INTERRUPT__)) /** * @brief Disables the specified LTDC interrupts. * @param __HANDLE__: LTDC handle * @param __INTERRUPT__: specifies the LTDC interrupt sources to be disabled. * This parameter can be any combination of the following values: * @arg LTDC_IT_LI: Line Interrupt flag * @arg LTDC_IT_FU: FIFO Underrun Interrupt flag * @arg LTDC_IT_TE: Transfer Error interrupt flag * @arg LTDC_IT_RR: Register Reload Interrupt Flag * @retval None */ #define __HAL_LTDC_DISABLE_IT(__HANDLE__, __INTERRUPT__) ((__HANDLE__)->Instance->IER &= ~(__INTERRUPT__)) /** * @brief Checks whether the specified LTDC interrupt has occurred or not. * @param __HANDLE__: LTDC handle * @param __INTERRUPT__: specifies the LTDC interrupt source to check. * This parameter can be one of the following values: * @arg LTDC_IT_LI: Line Interrupt flag * @arg LTDC_IT_FU: FIFO Underrun Interrupt flag * @arg LTDC_IT_TE: Transfer Error interrupt flag * @arg LTDC_IT_RR: Register Reload Interrupt Flag * @retval The state of INTERRUPT (SET or RESET). */ #define __HAL_LTDC_GET_IT_SOURCE(__HANDLE__, __INTERRUPT__) ((__HANDLE__)->Instance->ISR & (__INTERRUPT__)) /** * @} */ /* Include LTDC HAL Extension module */ #include "stm32f4xx_hal_ltdc_ex.h" /* Exported functions --------------------------------------------------------*/ /** @addtogroup LTDC_Exported_Functions * @{ */ /** @addtogroup LTDC_Exported_Functions_Group1 * @{ */ /* Initialization and de-initialization functions *****************************/ HAL_StatusTypeDef HAL_LTDC_Init(LTDC_HandleTypeDef *hltdc); HAL_StatusTypeDef HAL_LTDC_DeInit(LTDC_HandleTypeDef *hltdc); void HAL_LTDC_MspInit(LTDC_HandleTypeDef* hltdc); void HAL_LTDC_MspDeInit(LTDC_HandleTypeDef* hltdc); void HAL_LTDC_ErrorCallback(LTDC_HandleTypeDef *hltdc); void HAL_LTDC_LineEventCallback(LTDC_HandleTypeDef *hltdc); /** * @} */ /** @addtogroup LTDC_Exported_Functions_Group2 * @{ */ /* IO operation functions *****************************************************/ void HAL_LTDC_IRQHandler(LTDC_HandleTypeDef *hltdc); /** * @} */ /** @addtogroup LTDC_Exported_Functions_Group3 * @{ */ /* Peripheral Control functions ***********************************************/ HAL_StatusTypeDef HAL_LTDC_ConfigLayer(LTDC_HandleTypeDef *hltdc, LTDC_LayerCfgTypeDef *pLayerCfg, uint32_t LayerIdx); HAL_StatusTypeDef HAL_LTDC_SetWindowSize(LTDC_HandleTypeDef *hltdc, uint32_t XSize, uint32_t YSize, uint32_t LayerIdx); HAL_StatusTypeDef HAL_LTDC_SetWindowPosition(LTDC_HandleTypeDef *hltdc, uint32_t X0, uint32_t Y0, uint32_t LayerIdx); HAL_StatusTypeDef HAL_LTDC_SetPixelFormat(LTDC_HandleTypeDef *hltdc, uint32_t Pixelformat, uint32_t LayerIdx); HAL_StatusTypeDef HAL_LTDC_SetAlpha(LTDC_HandleTypeDef *hltdc, uint32_t Alpha, uint32_t LayerIdx); HAL_StatusTypeDef HAL_LTDC_SetAddress(LTDC_HandleTypeDef *hltdc, uint32_t Address, uint32_t LayerIdx); HAL_StatusTypeDef HAL_LTDC_SetPitch(LTDC_HandleTypeDef *hltdc, uint32_t LinePitchInPixels, uint32_t LayerIdx); HAL_StatusTypeDef HAL_LTDC_ConfigColorKeying(LTDC_HandleTypeDef *hltdc, uint32_t RGBValue, uint32_t LayerIdx); HAL_StatusTypeDef HAL_LTDC_ConfigCLUT(LTDC_HandleTypeDef *hltdc, uint32_t *pCLUT, uint32_t CLUTSize, uint32_t LayerIdx); HAL_StatusTypeDef HAL_LTDC_EnableColorKeying(LTDC_HandleTypeDef *hltdc, uint32_t LayerIdx); HAL_StatusTypeDef HAL_LTDC_DisableColorKeying(LTDC_HandleTypeDef *hltdc, uint32_t LayerIdx); HAL_StatusTypeDef HAL_LTDC_EnableCLUT(LTDC_HandleTypeDef *hltdc, uint32_t LayerIdx); HAL_StatusTypeDef HAL_LTDC_DisableCLUT(LTDC_HandleTypeDef *hltdc, uint32_t LayerIdx); HAL_StatusTypeDef HAL_LTDC_ProgramLineEvent(LTDC_HandleTypeDef *hltdc, uint32_t Line); HAL_StatusTypeDef HAL_LTDC_EnableDither(LTDC_HandleTypeDef *hltdc); HAL_StatusTypeDef HAL_LTDC_DisableDither(LTDC_HandleTypeDef *hltdc); /** * @} */ /** @addtogroup LTDC_Exported_Functions_Group4 * @{ */ /* Peripheral State functions *************************************************/ HAL_LTDC_StateTypeDef HAL_LTDC_GetState(LTDC_HandleTypeDef *hltdc); uint32_t HAL_LTDC_GetError(LTDC_HandleTypeDef *hltdc); /** * @} */ /** * @} */ /* Private types -------------------------------------------------------------*/ /** @defgroup LTDC_Private_Types LTDC Private Types * @{ */ /** * @} */ /* Private variables ---------------------------------------------------------*/ /** @defgroup LTDC_Private_Variables LTDC Private Variables * @{ */ /** * @} */ /* Private constants ---------------------------------------------------------*/ /** @defgroup LTDC_Private_Constants LTDC Private Constants * @{ */ /** * @} */ /* Private macros ------------------------------------------------------------*/ /** @defgroup LTDC_Private_Macros LTDC Private Macros * @{ */ #define LTDC_LAYER(__HANDLE__, __LAYER__) ((LTDC_Layer_TypeDef *)((uint32_t)(((uint32_t)((__HANDLE__)->Instance)) + 0x84 + (0x80*(__LAYER__))))) #define IS_LTDC_LAYER(LAYER) ((LAYER) <= MAX_LAYER) #define IS_LTDC_HSPOL(HSPOL) (((HSPOL) == LTDC_HSPOLARITY_AL) || \ ((HSPOL) == LTDC_HSPOLARITY_AH)) #define IS_LTDC_VSPOL(VSPOL) (((VSPOL) == LTDC_VSPOLARITY_AL) || \ ((VSPOL) == LTDC_VSPOLARITY_AH)) #define IS_LTDC_DEPOL(DEPOL) (((DEPOL) == LTDC_DEPOLARITY_AL) || \ ((DEPOL) == LTDC_DEPOLARITY_AH)) #define IS_LTDC_PCPOL(PCPOL) (((PCPOL) == LTDC_PCPOLARITY_IPC) || \ ((PCPOL) == LTDC_PCPOLARITY_IIPC)) #define IS_LTDC_HSYNC(HSYNC) ((HSYNC) <= LTDC_HORIZONTALSYNC) #define IS_LTDC_VSYNC(VSYNC) ((VSYNC) <= LTDC_VERTICALSYNC) #define IS_LTDC_AHBP(AHBP) ((AHBP) <= LTDC_HORIZONTALSYNC) #define IS_LTDC_AVBP(AVBP) ((AVBP) <= LTDC_VERTICALSYNC) #define IS_LTDC_AAW(AAW) ((AAW) <= LTDC_HORIZONTALSYNC) #define IS_LTDC_AAH(AAH) ((AAH) <= LTDC_VERTICALSYNC) #define IS_LTDC_TOTALW(TOTALW) ((TOTALW) <= LTDC_HORIZONTALSYNC) #define IS_LTDC_TOTALH(TOTALH) ((TOTALH) <= LTDC_VERTICALSYNC) #define IS_LTDC_BLUEVALUE(BBLUE) ((BBLUE) <= LTDC_COLOR) #define IS_LTDC_GREENVALUE(BGREEN) ((BGREEN) <= LTDC_COLOR) #define IS_LTDC_REDVALUE(BRED) ((BRED) <= LTDC_COLOR) #define IS_LTDC_BLENDING_FACTOR1(BlendingFactor1) (((BlendingFactor1) == LTDC_BLENDING_FACTOR1_CA) || \ ((BlendingFactor1) == LTDC_BLENDING_FACTOR1_PAxCA)) #define IS_LTDC_BLENDING_FACTOR2(BlendingFactor2) (((BlendingFactor2) == LTDC_BLENDING_FACTOR2_CA) || \ ((BlendingFactor2) == LTDC_BLENDING_FACTOR2_PAxCA)) #define IS_LTDC_PIXEL_FORMAT(Pixelformat) (((Pixelformat) == LTDC_PIXEL_FORMAT_ARGB8888) || ((Pixelformat) == LTDC_PIXEL_FORMAT_RGB888) || \ ((Pixelformat) == LTDC_PIXEL_FORMAT_RGB565) || ((Pixelformat) == LTDC_PIXEL_FORMAT_ARGB1555) || \ ((Pixelformat) == LTDC_PIXEL_FORMAT_ARGB4444) || ((Pixelformat) == LTDC_PIXEL_FORMAT_L8) || \ ((Pixelformat) == LTDC_PIXEL_FORMAT_AL44) || ((Pixelformat) == LTDC_PIXEL_FORMAT_AL88)) #define IS_LTDC_ALPHA(ALPHA) ((ALPHA) <= LTDC_ALPHA) #define IS_LTDC_HCONFIGST(HCONFIGST) ((HCONFIGST) <= LTDC_STARTPOSITION) #define IS_LTDC_HCONFIGSP(HCONFIGSP) ((HCONFIGSP) <= LTDC_STOPPOSITION) #define IS_LTDC_VCONFIGST(VCONFIGST) ((VCONFIGST) <= LTDC_STARTPOSITION) #define IS_LTDC_VCONFIGSP(VCONFIGSP) ((VCONFIGSP) <= LTDC_STOPPOSITION) #define IS_LTDC_CFBP(CFBP) ((CFBP) <= LTDC_COLOR_FRAME_BUFFER) #define IS_LTDC_CFBLL(CFBLL) ((CFBLL) <= LTDC_COLOR_FRAME_BUFFER) #define IS_LTDC_CFBLNBR(CFBLNBR) ((CFBLNBR) <= LTDC_LINE_NUMBER) #define IS_LTDC_LIPOS(LIPOS) ((LIPOS) <= 0x7FF) /** * @} */ /* Private functions ---------------------------------------------------------*/ /** @defgroup LTDC_Private_Functions LTDC Private Functions * @{ */ /** * @} */ /** * @} */ /** * @} */ #endif /* STM32F429xx || STM32F439xx || STM32F469xx || STM32F479xx */ #ifdef __cplusplus } #endif #endif /* __STM32F4xx_HAL_LTDC_H */ /************************ (C) COPYRIGHT STMicroelectronics *****END OF FILE****/ ================================================ FILE: Zelig/mbed/TARGET_NUCLEO_F401RE/stm32f4xx_hal_ltdc_ex.h ================================================ /** ****************************************************************************** * @file stm32f4xx_hal_ltdc_ex.h * @author MCD Application Team * @version V1.4.1 * @date 09-October-2015 * @brief Header file of LTDC HAL Extension module. ****************************************************************************** * @attention * *

© COPYRIGHT(c) 2015 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. * ****************************************************************************** */ /* Define to prevent recursive inclusion -------------------------------------*/ #ifndef __STM32F4xx_HAL_LTDC_EX_H #define __STM32F4xx_HAL_LTDC_EX_H #ifdef __cplusplus extern "C" { #endif #if defined(STM32F469xx) || defined(STM32F479xx) /* Includes ------------------------------------------------------------------*/ #include "stm32f4xx_hal_def.h" #include "stm32f4xx_hal_dsi.h" /** @addtogroup STM32F4xx_HAL_Driver * @{ */ /** @addtogroup LTDCEx * @{ */ /* Exported types ------------------------------------------------------------*/ /* Exported constants --------------------------------------------------------*/ /** @defgroup LTDCEx_Exported_Constants LTDCEx Exported Constants * @{ */ /** * @} */ /* Exported macro ------------------------------------------------------------*/ /** @defgroup LTDCEx_Exported_Macros LTDC Exported Macros * @{ */ /** * @} */ /* Exported functions --------------------------------------------------------*/ /** @defgroup LTDCEx_Exported_Functions LTDC Extended Exported Functions * @{ */ HAL_StatusTypeDef HAL_LTDC_StructInitFromVideoConfig(LTDC_HandleTypeDef* hltdc, DSI_VidCfgTypeDef *VidCfg); HAL_StatusTypeDef HAL_LTDC_StructInitFromAdaptedCommandConfig(LTDC_HandleTypeDef* hltdc, DSI_CmdCfgTypeDef *CmdCfg); /** * @} */ /* Private types -------------------------------------------------------------*/ /** @defgroup LTDCEx_Private_Types LTDCEx Private Types * @{ */ /** * @} */ /* Private variables ---------------------------------------------------------*/ /** @defgroup LTDCEx_Private_Variables LTDCEx Private Variables * @{ */ /** * @} */ /* Private constants ---------------------------------------------------------*/ /** @defgroup LTDCEx_Private_Constants LTDCEx Private Constants * @{ */ /** * @} */ /* Private macros ------------------------------------------------------------*/ /** @defgroup LTDCEx_Private_Macros LTDCEx Private Macros * @{ */ /** * @} */ /* Private functions ---------------------------------------------------------*/ /** @defgroup LTDCEx_Private_Functions LTDCEx Private Functions * @{ */ /** * @} */ /** * @} */ /** * @} */ #endif /* STM32F469xx || STM32F479xx */ #ifdef __cplusplus } #endif #endif /* __STM32F4xx_HAL_LTDC_EX_H */ /************************ (C) COPYRIGHT STMicroelectronics *****END OF FILE****/ ================================================ FILE: Zelig/mbed/TARGET_NUCLEO_F401RE/stm32f4xx_hal_nand.h ================================================ /** ****************************************************************************** * @file stm32f4xx_hal_nand.h * @author MCD Application Team * @version V1.4.1 * @date 09-October-2015 * @brief Header file of NAND HAL module. ****************************************************************************** * @attention * *

© COPYRIGHT(c) 2015 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. * ****************************************************************************** */ /* Define to prevent recursive inclusion -------------------------------------*/ #ifndef __STM32F4xx_HAL_NAND_H #define __STM32F4xx_HAL_NAND_H #ifdef __cplusplus extern "C" { #endif /* Includes ------------------------------------------------------------------*/ #if defined(STM32F405xx) || defined(STM32F415xx) || defined(STM32F407xx) || defined(STM32F417xx) #include "stm32f4xx_ll_fsmc.h" #endif /* STM32F405xx || STM32F415xx || STM32F407xx || STM32F417xx */ #if defined(STM32F427xx) || defined(STM32F437xx) || defined(STM32F429xx) || defined(STM32F439xx) ||\ defined(STM32F446xx) || defined(STM32F469xx) || defined(STM32F479xx) #include "stm32f4xx_ll_fmc.h" #endif /* STM32F427xx || STM32F437xx || STM32F429xx || STM32F439xx || STM32F446xx || STM32F469xx ||\ STM32F479xx */ /** @addtogroup STM32F4xx_HAL_Driver * @{ */ /** @addtogroup NAND * @{ */ #if defined(STM32F405xx) || defined(STM32F415xx) || defined(STM32F407xx) || defined(STM32F417xx) || \ defined(STM32F427xx) || defined(STM32F437xx) || defined(STM32F429xx) || defined(STM32F439xx) || \ defined(STM32F446xx) || defined(STM32F469xx) || defined(STM32F479xx) /* Exported typedef ----------------------------------------------------------*/ /* Exported types ------------------------------------------------------------*/ /** @defgroup NAND_Exported_Types NAND Exported Types * @{ */ /** * @brief HAL NAND State structures definition */ typedef enum { HAL_NAND_STATE_RESET = 0x00, /*!< NAND not yet initialized or disabled */ HAL_NAND_STATE_READY = 0x01, /*!< NAND initialized and ready for use */ HAL_NAND_STATE_BUSY = 0x02, /*!< NAND internal process is ongoing */ HAL_NAND_STATE_ERROR = 0x03 /*!< NAND error state */ }HAL_NAND_StateTypeDef; /** * @brief NAND Memory electronic signature Structure definition */ typedef struct { /*State = HAL_NAND_STATE_RESET) /** * @} */ /* Exported functions --------------------------------------------------------*/ /** @addtogroup NAND_Exported_Functions NAND Exported Functions * @{ */ /** @addtogroup NAND_Exported_Functions_Group1 Initialization and de-initialization functions * @{ */ /* Initialization/de-initialization functions ********************************/ HAL_StatusTypeDef HAL_NAND_Init(NAND_HandleTypeDef *hnand, FMC_NAND_PCC_TimingTypeDef *ComSpace_Timing, FMC_NAND_PCC_TimingTypeDef *AttSpace_Timing); HAL_StatusTypeDef HAL_NAND_DeInit(NAND_HandleTypeDef *hnand); void HAL_NAND_MspInit(NAND_HandleTypeDef *hnand); void HAL_NAND_MspDeInit(NAND_HandleTypeDef *hnand); void HAL_NAND_IRQHandler(NAND_HandleTypeDef *hnand); void HAL_NAND_ITCallback(NAND_HandleTypeDef *hnand); /** * @} */ /** @addtogroup NAND_Exported_Functions_Group2 Input and Output functions * @{ */ /* IO operation functions ****************************************************/ HAL_StatusTypeDef HAL_NAND_Read_ID(NAND_HandleTypeDef *hnand, NAND_IDTypeDef *pNAND_ID); HAL_StatusTypeDef HAL_NAND_Reset(NAND_HandleTypeDef *hnand); HAL_StatusTypeDef HAL_NAND_Read_Page(NAND_HandleTypeDef *hnand, NAND_AddressTypeDef *pAddress, uint8_t *pBuffer, uint32_t NumPageToRead); HAL_StatusTypeDef HAL_NAND_Write_Page(NAND_HandleTypeDef *hnand, NAND_AddressTypeDef *pAddress, uint8_t *pBuffer, uint32_t NumPageToWrite); HAL_StatusTypeDef HAL_NAND_Read_SpareArea(NAND_HandleTypeDef *hnand, NAND_AddressTypeDef *pAddress, uint8_t *pBuffer, uint32_t NumSpareAreaToRead); HAL_StatusTypeDef HAL_NAND_Write_SpareArea(NAND_HandleTypeDef *hnand, NAND_AddressTypeDef *pAddress, uint8_t *pBuffer, uint32_t NumSpareAreaTowrite); HAL_StatusTypeDef HAL_NAND_Erase_Block(NAND_HandleTypeDef *hnand, NAND_AddressTypeDef *pAddress); uint32_t HAL_NAND_Read_Status(NAND_HandleTypeDef *hnand); uint32_t HAL_NAND_Address_Inc(NAND_HandleTypeDef *hnand, NAND_AddressTypeDef *pAddress); /** * @} */ /** @addtogroup NAND_Exported_Functions_Group3 Peripheral Control functions * @{ */ /* NAND Control functions ****************************************************/ HAL_StatusTypeDef HAL_NAND_ECC_Enable(NAND_HandleTypeDef *hnand); HAL_StatusTypeDef HAL_NAND_ECC_Disable(NAND_HandleTypeDef *hnand); HAL_StatusTypeDef HAL_NAND_GetECC(NAND_HandleTypeDef *hnand, uint32_t *ECCval, uint32_t Timeout); /** * @} */ /** @addtogroup NAND_Exported_Functions_Group4 Peripheral State functions * @{ */ /* NAND State functions *******************************************************/ HAL_NAND_StateTypeDef HAL_NAND_GetState(NAND_HandleTypeDef *hnand); uint32_t HAL_NAND_Read_Status(NAND_HandleTypeDef *hnand); /** * @} */ /** * @} */ /* Private types -------------------------------------------------------------*/ /* Private variables ---------------------------------------------------------*/ /* Private constants ---------------------------------------------------------*/ /** @defgroup NAND_Private_Constants NAND Private Constants * @{ */ #define NAND_DEVICE1 ((uint32_t)0x70000000) #define NAND_DEVICE2 ((uint32_t)0x80000000) #define NAND_WRITE_TIMEOUT ((uint32_t)0x01000000) #define CMD_AREA ((uint32_t)(1<<16)) /* A16 = CLE high */ #define ADDR_AREA ((uint32_t)(1<<17)) /* A17 = ALE high */ #define NAND_CMD_AREA_A ((uint8_t)0x00) #define NAND_CMD_AREA_B ((uint8_t)0x01) #define NAND_CMD_AREA_C ((uint8_t)0x50) #define NAND_CMD_AREA_TRUE1 ((uint8_t)0x30) #define NAND_CMD_WRITE0 ((uint8_t)0x80) #define NAND_CMD_WRITE_TRUE1 ((uint8_t)0x10) #define NAND_CMD_ERASE0 ((uint8_t)0x60) #define NAND_CMD_ERASE1 ((uint8_t)0xD0) #define NAND_CMD_READID ((uint8_t)0x90) #define NAND_CMD_STATUS ((uint8_t)0x70) #define NAND_CMD_LOCK_STATUS ((uint8_t)0x7A) #define NAND_CMD_RESET ((uint8_t)0xFF) /* NAND memory status */ #define NAND_VALID_ADDRESS ((uint32_t)0x00000100) #define NAND_INVALID_ADDRESS ((uint32_t)0x00000200) #define NAND_TIMEOUT_ERROR ((uint32_t)0x00000400) #define NAND_BUSY ((uint32_t)0x00000000) #define NAND_ERROR ((uint32_t)0x00000001) #define NAND_READY ((uint32_t)0x00000040) /** * @} */ /* Private macros ------------------------------------------------------------*/ /** @defgroup NAND_Private_Macros NAND Private Macros * @{ */ /** * @brief NAND memory address computation. * @param __ADDRESS__: NAND memory address. * @param __HANDLE__: NAND handle. * @retval NAND Raw address value */ #define ARRAY_ADDRESS(__ADDRESS__ , __HANDLE__) ((__ADDRESS__)->Page + \ (((__ADDRESS__)->Block + (((__ADDRESS__)->Zone) * ((__HANDLE__)->Info.ZoneSize)))* ((__HANDLE__)->Info.BlockSize))) /** * @brief NAND memory address cycling. * @param __ADDRESS__: NAND memory address. * @retval NAND address cycling value. */ #define ADDR_1ST_CYCLE(__ADDRESS__) (uint8_t)(__ADDRESS__) /* 1st addressing cycle */ #define ADDR_2ND_CYCLE(__ADDRESS__) (uint8_t)((__ADDRESS__) >> 8) /* 2nd addressing cycle */ #define ADDR_3RD_CYCLE(__ADDRESS__) (uint8_t)((__ADDRESS__) >> 16) /* 3rd addressing cycle */ #define ADDR_4TH_CYCLE(__ADDRESS__) (uint8_t)((__ADDRESS__) >> 24) /* 4th addressing cycle */ /** * @} */ #endif /* STM32F405xx || STM32F415xx || STM32F407xx || STM32F417xx ||\ STM32F427xx || STM32F437xx || STM32F429xx || STM32F439xx ||\ STM32F446xx || STM32F469xx || STM32F479xx */ /** * @} */ /** * @} */ /** * @} */ #ifdef __cplusplus } #endif #endif /* __STM32F4xx_HAL_NAND_H */ /************************ (C) COPYRIGHT STMicroelectronics *****END OF FILE****/ ================================================ FILE: Zelig/mbed/TARGET_NUCLEO_F401RE/stm32f4xx_hal_nor.h ================================================ /** ****************************************************************************** * @file stm32f4xx_hal_nor.h * @author MCD Application Team * @version V1.4.1 * @date 09-October-2015 * @brief Header file of NOR HAL module. ****************************************************************************** * @attention * *

© COPYRIGHT(c) 2015 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. * ****************************************************************************** */ /* Define to prevent recursive inclusion -------------------------------------*/ #ifndef __STM32F4xx_HAL_NOR_H #define __STM32F4xx_HAL_NOR_H #ifdef __cplusplus extern "C" { #endif /* Includes ------------------------------------------------------------------*/ #if defined(STM32F405xx) || defined(STM32F415xx) || defined(STM32F407xx) || defined(STM32F417xx) #include "stm32f4xx_ll_fsmc.h" #endif /* STM32F405xx || STM32F415xx || STM32F407xx || STM32F417xx */ #if defined(STM32F427xx) || defined(STM32F437xx) || defined(STM32F429xx) || defined(STM32F439xx) ||\ defined(STM32F446xx) || defined(STM32F469xx) || defined(STM32F479xx) #include "stm32f4xx_ll_fmc.h" #endif /* STM32F427xx || STM32F437xx || STM32F429xx || STM32F439xx || STM32F446xx || STM32F469xx || STM32F479xx */ /** @addtogroup STM32F4xx_HAL_Driver * @{ */ /** @addtogroup NOR * @{ */ #if defined(STM32F405xx) || defined(STM32F415xx) || defined(STM32F407xx) || defined(STM32F417xx) ||\ defined(STM32F427xx) || defined(STM32F437xx) || defined(STM32F429xx) || defined(STM32F439xx) ||\ defined(STM32F446xx) || defined(STM32F469xx) || defined(STM32F479xx) /* Exported typedef ----------------------------------------------------------*/ /** @defgroup NOR_Exported_Types NOR Exported Types * @{ */ /** * @brief HAL SRAM State structures definition */ typedef enum { HAL_NOR_STATE_RESET = 0x00, /*!< NOR not yet initialized or disabled */ HAL_NOR_STATE_READY = 0x01, /*!< NOR initialized and ready for use */ HAL_NOR_STATE_BUSY = 0x02, /*!< NOR internal processing is ongoing */ HAL_NOR_STATE_ERROR = 0x03, /*!< NOR error state */ HAL_NOR_STATE_PROTECTED = 0x04 /*!< NOR NORSRAM device write protected */ }HAL_NOR_StateTypeDef; /** * @brief FMC NOR Status typedef */ typedef enum { HAL_NOR_STATUS_SUCCESS = 0, HAL_NOR_STATUS_ONGOING, HAL_NOR_STATUS_ERROR, HAL_NOR_STATUS_TIMEOUT }HAL_NOR_StatusTypeDef; /** * @brief FMC NOR ID typedef */ typedef struct { uint16_t Manufacturer_Code; /*!< Defines the device's manufacturer code used to identify the memory */ uint16_t Device_Code1; uint16_t Device_Code2; uint16_t Device_Code3; /*!< Defines the device's codes used to identify the memory. These codes can be accessed by performing read operations with specific control signals and addresses set.They can also be accessed by issuing an Auto Select command */ }NOR_IDTypeDef; /** * @brief FMC NOR CFI typedef */ typedef struct { /*!< Defines the information stored in the memory's Common flash interface which contains a description of various electrical and timing parameters, density information and functions supported by the memory */ uint16_t CFI_1; uint16_t CFI_2; uint16_t CFI_3; uint16_t CFI_4; }NOR_CFITypeDef; /** * @brief NOR handle Structure definition */ typedef struct { FMC_NORSRAM_TypeDef *Instance; /*!< Register base address */ FMC_NORSRAM_EXTENDED_TypeDef *Extended; /*!< Extended mode register base address */ FMC_NORSRAM_InitTypeDef Init; /*!< NOR device control configuration parameters */ HAL_LockTypeDef Lock; /*!< NOR locking object */ __IO HAL_NOR_StateTypeDef State; /*!< NOR device access state */ }NOR_HandleTypeDef; /** * @} */ /* Exported constants --------------------------------------------------------*/ /* Exported macros ------------------------------------------------------------*/ /** @defgroup NOR_Exported_Macros NOR Exported Macros * @{ */ /** @brief Reset NOR handle state * @param __HANDLE__: specifies the NOR handle. * @retval None */ #define __HAL_NOR_RESET_HANDLE_STATE(__HANDLE__) ((__HANDLE__)->State = HAL_NOR_STATE_RESET) /** * @} */ /* Exported functions --------------------------------------------------------*/ /** @addtogroup NOR_Exported_Functions * @{ */ /** @addtogroup NOR_Exported_Functions_Group1 * @{ */ /* Initialization/de-initialization functions ********************************/ HAL_StatusTypeDef HAL_NOR_Init(NOR_HandleTypeDef *hnor, FMC_NORSRAM_TimingTypeDef *Timing, FMC_NORSRAM_TimingTypeDef *ExtTiming); HAL_StatusTypeDef HAL_NOR_DeInit(NOR_HandleTypeDef *hnor); void HAL_NOR_MspInit(NOR_HandleTypeDef *hnor); void HAL_NOR_MspDeInit(NOR_HandleTypeDef *hnor); void HAL_NOR_MspWait(NOR_HandleTypeDef *hnor, uint32_t Timeout); /** * @} */ /** @addtogroup NOR_Exported_Functions_Group2 * @{ */ /* I/O operation functions ***************************************************/ HAL_StatusTypeDef HAL_NOR_Read_ID(NOR_HandleTypeDef *hnor, NOR_IDTypeDef *pNOR_ID); HAL_StatusTypeDef HAL_NOR_ReturnToReadMode(NOR_HandleTypeDef *hnor); HAL_StatusTypeDef HAL_NOR_Read(NOR_HandleTypeDef *hnor, uint32_t *pAddress, uint16_t *pData); HAL_StatusTypeDef HAL_NOR_Program(NOR_HandleTypeDef *hnor, uint32_t *pAddress, uint16_t *pData); HAL_StatusTypeDef HAL_NOR_ReadBuffer(NOR_HandleTypeDef *hnor, uint32_t uwAddress, uint16_t *pData, uint32_t uwBufferSize); HAL_StatusTypeDef HAL_NOR_ProgramBuffer(NOR_HandleTypeDef *hnor, uint32_t uwAddress, uint16_t *pData, uint32_t uwBufferSize); HAL_StatusTypeDef HAL_NOR_Erase_Block(NOR_HandleTypeDef *hnor, uint32_t BlockAddress, uint32_t Address); HAL_StatusTypeDef HAL_NOR_Erase_Chip(NOR_HandleTypeDef *hnor, uint32_t Address); HAL_StatusTypeDef HAL_NOR_Read_CFI(NOR_HandleTypeDef *hnor, NOR_CFITypeDef *pNOR_CFI); /** * @} */ /** @addtogroup NOR_Exported_Functions_Group3 * @{ */ /* NOR Control functions *****************************************************/ HAL_StatusTypeDef HAL_NOR_WriteOperation_Enable(NOR_HandleTypeDef *hnor); HAL_StatusTypeDef HAL_NOR_WriteOperation_Disable(NOR_HandleTypeDef *hnor); /** * @} */ /** @addtogroup NOR_Exported_Functions_Group4 * @{ */ /* NOR State functions ********************************************************/ HAL_NOR_StateTypeDef HAL_NOR_GetState(NOR_HandleTypeDef *hnor); HAL_NOR_StatusTypeDef HAL_NOR_GetStatus(NOR_HandleTypeDef *hnor, uint32_t Address, uint32_t Timeout); /** * @} */ /** * @} */ /* Private types -------------------------------------------------------------*/ /* Private variables ---------------------------------------------------------*/ /* Private constants ---------------------------------------------------------*/ /** @defgroup NOR_Private_Constants NOR Private Constants * @{ */ /* NOR device IDs addresses */ #define MC_ADDRESS ((uint16_t)0x0000) #define DEVICE_CODE1_ADDR ((uint16_t)0x0001) #define DEVICE_CODE2_ADDR ((uint16_t)0x000E) #define DEVICE_CODE3_ADDR ((uint16_t)0x000F) /* NOR CFI IDs addresses */ #define CFI1_ADDRESS ((uint16_t)0x61) #define CFI2_ADDRESS ((uint16_t)0x62) #define CFI3_ADDRESS ((uint16_t)0x63) #define CFI4_ADDRESS ((uint16_t)0x64) /* NOR operation wait timeout */ #define NOR_TMEOUT ((uint16_t)0xFFFF) /* NOR memory data width */ #define NOR_MEMORY_8B ((uint8_t)0x0) #define NOR_MEMORY_16B ((uint8_t)0x1) /* NOR memory device read/write start address */ #define NOR_MEMORY_ADRESS1 ((uint32_t)0x60000000) #define NOR_MEMORY_ADRESS2 ((uint32_t)0x64000000) #define NOR_MEMORY_ADRESS3 ((uint32_t)0x68000000) #define NOR_MEMORY_ADRESS4 ((uint32_t)0x6C000000) /** * @} */ /* Private macros ------------------------------------------------------------*/ /** @defgroup NOR_Private_Macros NOR Private Macros * @{ */ /** * @brief NOR memory address shifting. * @param __NOR_ADDRESS__: NOR base address * @param NOR_MEMORY_WIDTH: NOR memory width * @param ADDRESS: NOR memory address * @retval NOR shifted address value */ #define NOR_ADDR_SHIFT(__NOR_ADDRESS__, NOR_MEMORY_WIDTH, ADDRESS) (uint32_t)(((NOR_MEMORY_WIDTH) == NOR_MEMORY_8B)? ((uint32_t)((__NOR_ADDRESS__) + (2 * (ADDRESS)))):\ ((uint32_t)((__NOR_ADDRESS__) + (ADDRESS)))) /** * @brief NOR memory write data to specified address. * @param ADDRESS: NOR memory address * @param DATA: Data to write * @retval None */ #define NOR_WRITE(ADDRESS, DATA) (*(__IO uint16_t *)((uint32_t)(ADDRESS)) = (DATA)) /** * @} */ #endif /* STM32F405xx || STM32F415xx || STM32F407xx || STM32F417xx ||\ STM32F427xx || STM32F437xx || STM32F429xx || STM32F439xx ||\ STM32F446xx || STM32F469xx || STM32F479xx */ /** * @} */ /** * @} */ #ifdef __cplusplus } #endif #endif /* __STM32F4xx_HAL_NOR_H */ /************************ (C) COPYRIGHT STMicroelectronics *****END OF FILE****/ ================================================ FILE: Zelig/mbed/TARGET_NUCLEO_F401RE/stm32f4xx_hal_pccard.h ================================================ /** ****************************************************************************** * @file stm32f4xx_hal_pccard.h * @author MCD Application Team * @version V1.4.1 * @date 09-October-2015 * @brief Header file of PCCARD HAL module. ****************************************************************************** * @attention * *

© COPYRIGHT(c) 2015 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. * ****************************************************************************** */ /* Define to prevent recursive inclusion -------------------------------------*/ #ifndef __STM32F4xx_HAL_PCCARD_H #define __STM32F4xx_HAL_PCCARD_H #ifdef __cplusplus extern "C" { #endif /* Includes ------------------------------------------------------------------*/ #if defined(STM32F405xx) || defined(STM32F415xx) || defined(STM32F407xx) || defined(STM32F417xx) #include "stm32f4xx_ll_fsmc.h" #endif /* STM32F405xx || STM32F415xx || STM32F407xx || STM32F417xx */ #if defined(STM32F427xx) || defined(STM32F437xx) || defined(STM32F429xx) || defined(STM32F439xx) #include "stm32f4xx_ll_fmc.h" #endif /* STM32F427xx || STM32F437xx || STM32F429xx || STM32F439xx */ /** @addtogroup STM32F4xx_HAL_Driver * @{ */ #if defined(STM32F405xx) || defined(STM32F415xx) || defined(STM32F407xx) || defined(STM32F417xx) ||\ defined(STM32F427xx) || defined(STM32F437xx) || defined(STM32F429xx) || defined(STM32F439xx) /** @addtogroup PCCARD * @{ */ /* Exported typedef ----------------------------------------------------------*/ /** @defgroup PCCARD_Exported_Types PCCARD Exported Types * @{ */ /** * @brief HAL PCCARD State structures definition */ typedef enum { HAL_PCCARD_STATE_RESET = 0x00, /*!< PCCARD peripheral not yet initialized or disabled */ HAL_PCCARD_STATE_READY = 0x01, /*!< PCCARD peripheral ready */ HAL_PCCARD_STATE_BUSY = 0x02, /*!< PCCARD peripheral busy */ HAL_PCCARD_STATE_ERROR = 0x04 /*!< PCCARD peripheral error */ }HAL_PCCARD_StateTypeDef; typedef enum { HAL_PCCARD_STATUS_SUCCESS = 0, HAL_PCCARD_STATUS_ONGOING, HAL_PCCARD_STATUS_ERROR, HAL_PCCARD_STATUS_TIMEOUT }HAL_PCCARD_StatusTypeDef; /** * @brief FMC_PCCARD handle Structure definition */ typedef struct { FMC_PCCARD_TypeDef *Instance; /*!< Register base address for PCCARD device */ FMC_PCCARD_InitTypeDef Init; /*!< PCCARD device control configuration parameters */ __IO HAL_PCCARD_StateTypeDef State; /*!< PCCARD device access state */ HAL_LockTypeDef Lock; /*!< PCCARD Lock */ }PCCARD_HandleTypeDef; /** * @} */ /* Exported constants --------------------------------------------------------*/ /* Exported macro ------------------------------------------------------------*/ /** @defgroup PCCARD_Exported_Macros PCCARD Exported Macros * @{ */ /** @brief Reset PCCARD handle state * @param __HANDLE__: specifies the PCCARD handle. * @retval None */ #define __HAL_PCCARD_RESET_HANDLE_STATE(__HANDLE__) ((__HANDLE__)->State = HAL_PCCARD_STATE_RESET) /** * @} */ /* Exported functions --------------------------------------------------------*/ /** @addtogroup PCCARD_Exported_Functions * @{ */ /** @addtogroup PCCARD_Exported_Functions_Group1 * @{ */ /* Initialization/de-initialization functions **********************************/ HAL_StatusTypeDef HAL_PCCARD_Init(PCCARD_HandleTypeDef *hpccard, FMC_NAND_PCC_TimingTypeDef *ComSpaceTiming, FMC_NAND_PCC_TimingTypeDef *AttSpaceTiming, FMC_NAND_PCC_TimingTypeDef *IOSpaceTiming); HAL_StatusTypeDef HAL_PCCARD_DeInit(PCCARD_HandleTypeDef *hpccard); void HAL_PCCARD_MspInit(PCCARD_HandleTypeDef *hpccard); void HAL_PCCARD_MspDeInit(PCCARD_HandleTypeDef *hpccard); /** * @} */ /** @addtogroup PCCARD_Exported_Functions_Group2 * @{ */ /* IO operation functions *****************************************************/ HAL_StatusTypeDef HAL_PCCARD_Read_ID(PCCARD_HandleTypeDef *hpccard, uint8_t CompactFlash_ID[], uint8_t *pStatus); HAL_StatusTypeDef HAL_PCCARD_Write_Sector(PCCARD_HandleTypeDef *hpccard, uint16_t *pBuffer, uint16_t SectorAddress, uint8_t *pStatus); HAL_StatusTypeDef HAL_PCCARD_Read_Sector(PCCARD_HandleTypeDef *hpccard, uint16_t *pBuffer, uint16_t SectorAddress, uint8_t *pStatus); HAL_StatusTypeDef HAL_PCCARD_Erase_Sector(PCCARD_HandleTypeDef *hpccard, uint16_t SectorAddress, uint8_t *pStatus); HAL_StatusTypeDef HAL_PCCARD_Reset(PCCARD_HandleTypeDef *hpccard); void HAL_PCCARD_IRQHandler(PCCARD_HandleTypeDef *hpccard); void HAL_PCCARD_ITCallback(PCCARD_HandleTypeDef *hpccard); /** * @} */ /** @addtogroup PCCARD_Exported_Functions_Group3 * @{ */ /* PCCARD State functions *******************************************************/ HAL_PCCARD_StateTypeDef HAL_PCCARD_GetState(PCCARD_HandleTypeDef *hpccard); HAL_PCCARD_StatusTypeDef HAL_PCCARD_GetStatus(PCCARD_HandleTypeDef *hpccard); HAL_PCCARD_StatusTypeDef HAL_PCCARD_ReadStatus(PCCARD_HandleTypeDef *hpccard); /** * @} */ /** * @} */ /* Private types -------------------------------------------------------------*/ /* Private variables ---------------------------------------------------------*/ /* Private constants ---------------------------------------------------------*/ /** @defgroup PCCARD_Private_Constants PCCARD Private Constants * @{ */ #define PCCARD_DEVICE_ADDRESS ((uint32_t)0x90000000) #define PCCARD_ATTRIBUTE_SPACE_ADDRESS ((uint32_t)0x98000000) /* Attribute space size to @0x9BFF FFFF */ #define PCCARD_COMMON_SPACE_ADDRESS PCCARD_DEVICE_ADDRESS /* Common space size to @0x93FF FFFF */ #define PCCARD_IO_SPACE_ADDRESS ((uint32_t)0x9C000000) /* IO space size to @0x9FFF FFFF */ #define PCCARD_IO_SPACE_PRIMARY_ADDR ((uint32_t)0x9C0001F0) /* IO space size to @0x9FFF FFFF */ /* Flash-ATA registers description */ #define ATA_DATA ((uint8_t)0x00) /* Data register */ #define ATA_SECTOR_COUNT ((uint8_t)0x02) /* Sector Count register */ #define ATA_SECTOR_NUMBER ((uint8_t)0x03) /* Sector Number register */ #define ATA_CYLINDER_LOW ((uint8_t)0x04) /* Cylinder low register */ #define ATA_CYLINDER_HIGH ((uint8_t)0x05) /* Cylinder high register */ #define ATA_CARD_HEAD ((uint8_t)0x06) /* Card/Head register */ #define ATA_STATUS_CMD ((uint8_t)0x07) /* Status(read)/Command(write) register */ #define ATA_STATUS_CMD_ALTERNATE ((uint8_t)0x0E) /* Alternate Status(read)/Command(write) register */ #define ATA_COMMON_DATA_AREA ((uint16_t)0x0400) /* Start of data area (for Common access only!) */ #define ATA_CARD_CONFIGURATION ((uint16_t)0x0202) /* Card Configuration and Status Register */ /* Flash-ATA commands */ #define ATA_READ_SECTOR_CMD ((uint8_t)0x20) #define ATA_WRITE_SECTOR_CMD ((uint8_t)0x30) #define ATA_ERASE_SECTOR_CMD ((uint8_t)0xC0) #define ATA_IDENTIFY_CMD ((uint8_t)0xEC) /* PC Card/Compact Flash status */ #define PCCARD_TIMEOUT_ERROR ((uint8_t)0x60) #define PCCARD_BUSY ((uint8_t)0x80) #define PCCARD_PROGR ((uint8_t)0x01) #define PCCARD_READY ((uint8_t)0x40) #define PCCARD_SECTOR_SIZE ((uint32_t)255) /* In half words */ /** * @} */ /* Compact Flash redefinition */ #define HAL_CF_Init HAL_PCCARD_Init #define HAL_CF_DeInit HAL_PCCARD_DeInit #define HAL_CF_MspInit HAL_PCCARD_MspInit #define HAL_CF_MspDeInit HAL_PCCARD_MspDeInit #define HAL_CF_Read_ID HAL_PCCARD_Read_ID #define HAL_CF_Write_Sector HAL_PCCARD_Write_Sector #define HAL_CF_Read_Sector HAL_PCCARD_Read_Sector #define HAL_CF_Erase_Sector HAL_PCCARD_Erase_Sector #define HAL_CF_Reset HAL_PCCARD_Reset #define HAL_CF_IRQHandler HAL_PCCARD_IRQHandler #define HAL_CF_ITCallback HAL_PCCARD_ITCallback #define HAL_CF_GetState HAL_PCCARD_GetState #define HAL_CF_GetStatus HAL_PCCARD_GetStatus #define HAL_CF_ReadStatus HAL_PCCARD_ReadStatus #define HAL_CF_STATUS_SUCCESS HAL_PCCARD_STATUS_SUCCESS #define HAL_CF_STATUS_ONGOING HAL_PCCARD_STATUS_ONGOING #define HAL_CF_STATUS_ERROR HAL_PCCARD_STATUS_ERROR #define HAL_CF_STATUS_TIMEOUT HAL_PCCARD_STATUS_TIMEOUT #define HAL_CF_StatusTypeDef HAL_PCCARD_StatusTypeDef #define CF_DEVICE_ADDRESS PCCARD_DEVICE_ADDRESS #define CF_ATTRIBUTE_SPACE_ADDRESS PCCARD_ATTRIBUTE_SPACE_ADDRESS #define CF_COMMON_SPACE_ADDRESS PCCARD_COMMON_SPACE_ADDRESS #define CF_IO_SPACE_ADDRESS PCCARD_IO_SPACE_ADDRESS #define CF_IO_SPACE_PRIMARY_ADDR PCCARD_IO_SPACE_PRIMARY_ADDR #define CF_TIMEOUT_ERROR PCCARD_TIMEOUT_ERROR #define CF_BUSY PCCARD_BUSY #define CF_PROGR PCCARD_PROGR #define CF_READY PCCARD_READY #define CF_SECTOR_SIZE PCCARD_SECTOR_SIZE /* Private macros ------------------------------------------------------------*/ /** * @} */ #endif /* STM32F405xx || STM32F415xx || STM32F407xx || STM32F417xx ||\ STM32F427xx || STM32F437xx || STM32F429xx || STM32F439xx */ /** * @} */ #ifdef __cplusplus } #endif #endif /* __STM32F4xx_HAL_PCCARD_H */ /************************ (C) COPYRIGHT STMicroelectronics *****END OF FILE****/ ================================================ FILE: Zelig/mbed/TARGET_NUCLEO_F401RE/stm32f4xx_hal_pcd.h ================================================ /** ****************************************************************************** * @file stm32f4xx_hal_pcd.h * @author MCD Application Team * @version V1.4.1 * @date 09-October-2015 * @brief Header file of PCD HAL module. ****************************************************************************** * @attention * *

© COPYRIGHT(c) 2015 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. * ****************************************************************************** */ /* Define to prevent recursive inclusion -------------------------------------*/ #ifndef __STM32F4xx_HAL_PCD_H #define __STM32F4xx_HAL_PCD_H #ifdef __cplusplus extern "C" { #endif #if defined(STM32F405xx) || defined(STM32F415xx) || defined(STM32F407xx) || defined(STM32F417xx) || \ defined(STM32F427xx) || defined(STM32F437xx) || defined(STM32F429xx) || defined(STM32F439xx) || \ defined(STM32F401xC) || defined(STM32F401xE) || defined(STM32F411xE) || defined(STM32F446xx) || \ defined(STM32F469xx) || defined(STM32F479xx) /* Includes ------------------------------------------------------------------*/ #include "stm32f4xx_ll_usb.h" /** @addtogroup STM32F4xx_HAL_Driver * @{ */ /** @addtogroup PCD * @{ */ /* Exported types ------------------------------------------------------------*/ /** @defgroup PCD_Exported_Types PCD Exported Types * @{ */ /** * @brief PCD State structure definition */ typedef enum { HAL_PCD_STATE_RESET = 0x00, HAL_PCD_STATE_READY = 0x01, HAL_PCD_STATE_ERROR = 0x02, HAL_PCD_STATE_BUSY = 0x03, HAL_PCD_STATE_TIMEOUT = 0x04 } PCD_StateTypeDef; #ifdef USB_OTG_GLPMCFG_LPMEN /* Device LPM suspend state */ typedef enum { LPM_L0 = 0x00, /* on */ LPM_L1 = 0x01, /* LPM L1 sleep */ LPM_L2 = 0x02, /* suspend */ LPM_L3 = 0x03, /* off */ }PCD_LPM_StateTypeDef; #endif /* USB_OTG_GLPMCFG_LPMEN */ typedef USB_OTG_GlobalTypeDef PCD_TypeDef; typedef USB_OTG_CfgTypeDef PCD_InitTypeDef; typedef USB_OTG_EPTypeDef PCD_EPTypeDef ; /** * @brief PCD Handle Structure definition */ typedef struct { PCD_TypeDef *Instance; /*!< Register base address */ PCD_InitTypeDef Init; /*!< PCD required parameters */ PCD_EPTypeDef IN_ep[15]; /*!< IN endpoint parameters */ PCD_EPTypeDef OUT_ep[15]; /*!< OUT endpoint parameters */ HAL_LockTypeDef Lock; /*!< PCD peripheral status */ __IO PCD_StateTypeDef State; /*!< PCD communication state */ uint32_t Setup[12]; /*!< Setup packet buffer */ #ifdef USB_OTG_GLPMCFG_LPMEN PCD_LPM_StateTypeDef LPM_State; /*!< LPM State */ uint32_t BESL; uint32_t lpm_active; /*!< Enable or disable the Link Power Management . This parameter can be set to ENABLE or DISABLE */ #endif /* USB_OTG_GLPMCFG_LPMEN */ #ifdef USB_OTG_GCCFG_BCDEN uint32_t battery_charging_active; /*!< Enable or disable Battery charging. This parameter can be set to ENABLE or DISABLE */ #endif /* USB_OTG_GCCFG_BCDEN */ void *pData; /*!< Pointer to upper stack Handler */ } PCD_HandleTypeDef; /** * @} */ /* Include PCD HAL Extension module */ #include "stm32f4xx_hal_pcd_ex.h" /* Exported constants --------------------------------------------------------*/ /** @defgroup PCD_Exported_Constants PCD Exported Constants * @{ */ /** @defgroup PCD_Speed PCD Speed * @{ */ #define PCD_SPEED_HIGH 0 #define PCD_SPEED_HIGH_IN_FULL 1 #define PCD_SPEED_FULL 2 /** * @} */ /** @defgroup PCD_PHY_Module PCD PHY Module * @{ */ #define PCD_PHY_ULPI 1 #define PCD_PHY_EMBEDDED 2 /** * @} */ /** @defgroup PCD_Turnaround_Timeout Turnaround Timeout Value * @{ */ #ifndef USBD_HS_TRDT_VALUE #define USBD_HS_TRDT_VALUE 9 #endif /* USBD_HS_TRDT_VALUE */ #ifndef USBD_FS_TRDT_VALUE #define USBD_FS_TRDT_VALUE 5 #endif /* USBD_FS_TRDT_VALUE */ /** * @} */ /** * @} */ /* Exported macros -----------------------------------------------------------*/ /** @defgroup PCD_Exported_Macros PCD Exported Macros * @brief macros to handle interrupts and specific clock configurations * @{ */ #define __HAL_PCD_ENABLE(__HANDLE__) USB_EnableGlobalInt ((__HANDLE__)->Instance) #define __HAL_PCD_DISABLE(__HANDLE__) USB_DisableGlobalInt ((__HANDLE__)->Instance) #define __HAL_PCD_GET_FLAG(__HANDLE__, __INTERRUPT__) ((USB_ReadInterrupts((__HANDLE__)->Instance) & (__INTERRUPT__)) == (__INTERRUPT__)) #define __HAL_PCD_CLEAR_FLAG(__HANDLE__, __INTERRUPT__) (((__HANDLE__)->Instance->GINTSTS) &= (__INTERRUPT__)) #define __HAL_PCD_IS_INVALID_INTERRUPT(__HANDLE__) (USB_ReadInterrupts((__HANDLE__)->Instance) == 0) #define __HAL_PCD_UNGATE_PHYCLOCK(__HANDLE__) *(__IO uint32_t *)((uint32_t)((__HANDLE__)->Instance) + USB_OTG_PCGCCTL_BASE) &= \ ~(USB_OTG_PCGCCTL_STOPCLK) #define __HAL_PCD_GATE_PHYCLOCK(__HANDLE__) *(__IO uint32_t *)((uint32_t)((__HANDLE__)->Instance) + USB_OTG_PCGCCTL_BASE) |= USB_OTG_PCGCCTL_STOPCLK #define __HAL_PCD_IS_PHY_SUSPENDED(__HANDLE__) ((*(__IO uint32_t *)((uint32_t)((__HANDLE__)->Instance) + USB_OTG_PCGCCTL_BASE))&0x10) #define USB_OTG_FS_WAKEUP_EXTI_RISING_EDGE ((uint32_t)0x08) #define USB_OTG_FS_WAKEUP_EXTI_FALLING_EDGE ((uint32_t)0x0C) #define USB_OTG_FS_WAKEUP_EXTI_RISING_FALLING_EDGE ((uint32_t)0x10) #define USB_OTG_HS_WAKEUP_EXTI_RISING_EDGE ((uint32_t)0x08) #define USB_OTG_HS_WAKEUP_EXTI_FALLING_EDGE ((uint32_t)0x0C) #define USB_OTG_HS_WAKEUP_EXTI_RISING_FALLING_EDGE ((uint32_t)0x10) #define USB_OTG_HS_WAKEUP_EXTI_LINE ((uint32_t)0x00100000) /*!< External interrupt line 20 Connected to the USB HS EXTI Line */ #define USB_OTG_FS_WAKEUP_EXTI_LINE ((uint32_t)0x00040000) /*!< External interrupt line 18 Connected to the USB FS EXTI Line */ #define __HAL_USB_OTG_HS_WAKEUP_EXTI_ENABLE_IT() EXTI->IMR |= (USB_OTG_HS_WAKEUP_EXTI_LINE) #define __HAL_USB_OTG_HS_WAKEUP_EXTI_DISABLE_IT() EXTI->IMR &= ~(USB_OTG_HS_WAKEUP_EXTI_LINE) #define __HAL_USB_OTG_HS_WAKEUP_EXTI_GET_FLAG() EXTI->PR & (USB_OTG_HS_WAKEUP_EXTI_LINE) #define __HAL_USB_OTG_HS_WAKEUP_EXTI_CLEAR_FLAG() EXTI->PR = (USB_OTG_HS_WAKEUP_EXTI_LINE) #define __HAL_USB_OTG_HS_WAKEUP_EXTI_ENABLE_RISING_EDGE() EXTI->FTSR &= ~(USB_OTG_HS_WAKEUP_EXTI_LINE);\ EXTI->RTSR |= USB_OTG_HS_WAKEUP_EXTI_LINE #define __HAL_USB_OTG_HS_WAKEUP_EXTI_ENABLE_FALLING_EDGE() EXTI->FTSR |= (USB_OTG_HS_WAKEUP_EXTI_LINE);\ EXTI->RTSR &= ~(USB_OTG_HS_WAKEUP_EXTI_LINE) #define __HAL_USB_OTG_HS_WAKEUP_EXTI_ENABLE_RISING_FALLING_EDGE() EXTI->RTSR &= ~(USB_OTG_HS_WAKEUP_EXTI_LINE);\ EXTI->FTSR &= ~(USB_OTG_HS_WAKEUP_EXTI_LINE;)\ EXTI->RTSR |= USB_OTG_HS_WAKEUP_EXTI_LINE;\ EXTI->FTSR |= USB_OTG_HS_WAKEUP_EXTI_LINE #define __HAL_USB_OTG_HS_WAKEUP_EXTI_GENERATE_SWIT() (EXTI->SWIER |= USB_OTG_FS_WAKEUP_EXTI_LINE) #define __HAL_USB_OTG_FS_WAKEUP_EXTI_ENABLE_IT() EXTI->IMR |= USB_OTG_FS_WAKEUP_EXTI_LINE #define __HAL_USB_OTG_FS_WAKEUP_EXTI_DISABLE_IT() EXTI->IMR &= ~(USB_OTG_FS_WAKEUP_EXTI_LINE) #define __HAL_USB_OTG_FS_WAKEUP_EXTI_GET_FLAG() EXTI->PR & (USB_OTG_FS_WAKEUP_EXTI_LINE) #define __HAL_USB_OTG_FS_WAKEUP_EXTI_CLEAR_FLAG() EXTI->PR = USB_OTG_FS_WAKEUP_EXTI_LINE #define __HAL_USB_OTG_FS_WAKEUP_EXTI_ENABLE_RISING_EDGE() EXTI->FTSR &= ~(USB_OTG_FS_WAKEUP_EXTI_LINE);\ EXTI->RTSR |= USB_OTG_FS_WAKEUP_EXTI_LINE #define __HAL_USB_OTG_FS_WAKEUP_EXTI_ENABLE_FALLING_EDGE() EXTI->FTSR |= (USB_OTG_FS_WAKEUP_EXTI_LINE);\ EXTI->RTSR &= ~(USB_OTG_FS_WAKEUP_EXTI_LINE) #define __HAL_USB_OTG_FS_WAKEUP_EXTI_ENABLE_RISING_FALLING_EDGE() EXTI->RTSR &= ~(USB_OTG_FS_WAKEUP_EXTI_LINE);\ EXTI->FTSR &= ~(USB_OTG_FS_WAKEUP_EXTI_LINE);\ EXTI->RTSR |= USB_OTG_FS_WAKEUP_EXTI_LINE;\ EXTI->FTSR |= USB_OTG_FS_WAKEUP_EXTI_LINE #define __HAL_USB_OTG_FS_WAKEUP_EXTI_GENERATE_SWIT() (EXTI->SWIER |= USB_OTG_FS_WAKEUP_EXTI_LINE) /** * @} */ /* Exported functions --------------------------------------------------------*/ /** @addtogroup PCD_Exported_Functions PCD Exported Functions * @{ */ /* Initialization/de-initialization functions ********************************/ /** @addtogroup PCD_Exported_Functions_Group1 Initialization and de-initialization functions * @{ */ HAL_StatusTypeDef HAL_PCD_Init(PCD_HandleTypeDef *hpcd); HAL_StatusTypeDef HAL_PCD_DeInit(PCD_HandleTypeDef *hpcd); void HAL_PCD_MspInit(PCD_HandleTypeDef *hpcd); void HAL_PCD_MspDeInit(PCD_HandleTypeDef *hpcd); /** * @} */ /* I/O operation functions ***************************************************/ /* Non-Blocking mode: Interrupt */ /** @addtogroup PCD_Exported_Functions_Group2 Input and Output operation functions * @{ */ /* Non-Blocking mode: Interrupt */ HAL_StatusTypeDef HAL_PCD_Start(PCD_HandleTypeDef *hpcd); HAL_StatusTypeDef HAL_PCD_Stop(PCD_HandleTypeDef *hpcd); void HAL_PCD_IRQHandler(PCD_HandleTypeDef *hpcd); void HAL_PCD_DataOutStageCallback(PCD_HandleTypeDef *hpcd, uint8_t epnum); void HAL_PCD_DataInStageCallback(PCD_HandleTypeDef *hpcd, uint8_t epnum); void HAL_PCD_SetupStageCallback(PCD_HandleTypeDef *hpcd); void HAL_PCD_SOFCallback(PCD_HandleTypeDef *hpcd); void HAL_PCD_ResetCallback(PCD_HandleTypeDef *hpcd); void HAL_PCD_SuspendCallback(PCD_HandleTypeDef *hpcd); void HAL_PCD_ResumeCallback(PCD_HandleTypeDef *hpcd); void HAL_PCD_ISOOUTIncompleteCallback(PCD_HandleTypeDef *hpcd, uint8_t epnum); void HAL_PCD_ISOINIncompleteCallback(PCD_HandleTypeDef *hpcd, uint8_t epnum); void HAL_PCD_ConnectCallback(PCD_HandleTypeDef *hpcd); void HAL_PCD_DisconnectCallback(PCD_HandleTypeDef *hpcd); /** * @} */ /* Peripheral Control functions **********************************************/ /** @addtogroup PCD_Exported_Functions_Group3 Peripheral Control functions * @{ */ HAL_StatusTypeDef HAL_PCD_DevConnect(PCD_HandleTypeDef *hpcd); HAL_StatusTypeDef HAL_PCD_DevDisconnect(PCD_HandleTypeDef *hpcd); HAL_StatusTypeDef HAL_PCD_SetAddress(PCD_HandleTypeDef *hpcd, uint8_t address); HAL_StatusTypeDef HAL_PCD_EP_Open(PCD_HandleTypeDef *hpcd, uint8_t ep_addr, uint16_t ep_mps, uint8_t ep_type); HAL_StatusTypeDef HAL_PCD_EP_Close(PCD_HandleTypeDef *hpcd, uint8_t ep_addr); HAL_StatusTypeDef HAL_PCD_EP_Receive(PCD_HandleTypeDef *hpcd, uint8_t ep_addr, uint8_t *pBuf, uint32_t len); HAL_StatusTypeDef HAL_PCD_EP_Transmit(PCD_HandleTypeDef *hpcd, uint8_t ep_addr, uint8_t *pBuf, uint32_t len); uint16_t HAL_PCD_EP_GetRxCount(PCD_HandleTypeDef *hpcd, uint8_t ep_addr); HAL_StatusTypeDef HAL_PCD_EP_SetStall(PCD_HandleTypeDef *hpcd, uint8_t ep_addr); HAL_StatusTypeDef HAL_PCD_EP_ClrStall(PCD_HandleTypeDef *hpcd, uint8_t ep_addr); HAL_StatusTypeDef HAL_PCD_EP_Flush(PCD_HandleTypeDef *hpcd, uint8_t ep_addr); HAL_StatusTypeDef HAL_PCD_ActivateRemoteWakeup(PCD_HandleTypeDef *hpcd); HAL_StatusTypeDef HAL_PCD_DeActivateRemoteWakeup(PCD_HandleTypeDef *hpcd); /** * @} */ /* Peripheral State functions ************************************************/ /** @addtogroup PCD_Exported_Functions_Group4 Peripheral State functions * @{ */ PCD_StateTypeDef HAL_PCD_GetState(PCD_HandleTypeDef *hpcd); /** * @} */ /** * @} */ /* Private macros ------------------------------------------------------------*/ /** @defgroup PCD_Private_Macros PCD Private Macros * @{ */ /** @defgroup PCD_Instance_definition PCD Instance definition * @{ */ #if defined(STM32F405xx) || defined(STM32F415xx) || defined(STM32F407xx) || defined(STM32F417xx) || defined(STM32F427xx) || defined(STM32F437xx) ||\ defined(STM32F429xx) || defined(STM32F439xx) || defined(STM32F446xx) || defined(STM32F469xx) || defined(STM32F479xx) #define IS_PCD_ALL_INSTANCE(INSTANCE) (((INSTANCE) == USB_OTG_FS) || \ ((INSTANCE) == USB_OTG_HS)) #elif defined(STM32F401xC) || defined(STM32F401xE) || defined(STM32F411xE) #define IS_PCD_ALL_INSTANCE(INSTANCE) (((INSTANCE) == USB_OTG_FS)) #endif /** * @} */ /** * @} */ /** * @} */ /** * @} */ #endif /* STM32F405xx || STM32F415xx || STM32F407xx || STM32F417xx || STM32F427xx || STM32F437xx || STM32F429xx || STM32F439xx || STM32F401xC || STM32F401xE || STM32F411xE || STM32F446xx || STM32F469xx || STM32F479xx */ #ifdef __cplusplus } #endif #endif /* __STM32F4xx_HAL_PCD_H */ /************************ (C) COPYRIGHT STMicroelectronics *****END OF FILE****/ ================================================ FILE: Zelig/mbed/TARGET_NUCLEO_F401RE/stm32f4xx_hal_pcd_ex.h ================================================ /** ****************************************************************************** * @file stm32f4xx_hal_pcd_ex.h * @author MCD Application Team * @version V1.4.1 * @date 09-October-2015 * @brief Header file of PCD HAL module. ****************************************************************************** * @attention * *

© COPYRIGHT(c) 2015 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. * ****************************************************************************** */ /* Define to prevent recursive inclusion -------------------------------------*/ #ifndef __STM32F4xx_HAL_PCD_EX_H #define __STM32F4xx_HAL_PCD_EX_H #ifdef __cplusplus extern "C" { #endif #if defined(STM32F405xx) || defined(STM32F415xx) || defined(STM32F407xx) || defined(STM32F417xx) || \ defined(STM32F427xx) || defined(STM32F437xx) || defined(STM32F429xx) || defined(STM32F439xx) || \ defined(STM32F401xC) || defined(STM32F401xE) || defined(STM32F411xE) || defined(STM32F446xx) || \ defined(STM32F469xx) || defined(STM32F479xx) /* Includes ------------------------------------------------------------------*/ #include "stm32f4xx_hal_def.h" /** @addtogroup STM32F4xx_HAL_Driver * @{ */ /** @addtogroup PCDEx * @{ */ /* Exported types ------------------------------------------------------------*/ #if defined(STM32F446xx) || defined(STM32F469xx) || defined(STM32F479xx) typedef enum { PCD_LPM_L0_ACTIVE = 0x00, /* on */ PCD_LPM_L1_ACTIVE = 0x01, /* LPM L1 sleep */ }PCD_LPM_MsgTypeDef; #endif /* STM32F446xx || STM32F469xx || STM32F479xx */ /* Exported constants --------------------------------------------------------*/ /* Exported macros -----------------------------------------------------------*/ /* Exported functions --------------------------------------------------------*/ /** @addtogroup PCDEx_Exported_Functions PCD Extended Exported Functions * @{ */ /** @addtogroup PCDEx_Exported_Functions_Group1 Peripheral Control functions * @{ */ HAL_StatusTypeDef HAL_PCDEx_SetTxFiFo(PCD_HandleTypeDef *hpcd, uint8_t fifo, uint16_t size); HAL_StatusTypeDef HAL_PCDEx_SetRxFiFo(PCD_HandleTypeDef *hpcd, uint16_t size); #if defined(STM32F446xx) || defined(STM32F469xx) || defined(STM32F479xx) HAL_StatusTypeDef HAL_PCDEx_ActivateLPM(PCD_HandleTypeDef *hpcd); HAL_StatusTypeDef HAL_PCDEx_DeActivateLPM(PCD_HandleTypeDef *hpcd); void HAL_PCDEx_LPM_Callback(PCD_HandleTypeDef *hpcd, PCD_LPM_MsgTypeDef msg); #endif /* STM32F446xx || STM32F469xx || STM32F479xx */ /** * @} */ /** * @} */ /** * @} */ /** * @} */ #endif /* STM32F405xx || STM32F415xx || STM32F407xx || STM32F417xx || STM32F427xx || STM32F437xx || STM32F429xx || STM32F439xx || STM32F401xC || STM32F401xE || STM32F411xE || STM32F446xx || STM32F469xx || STM32F479xx */ #ifdef __cplusplus } #endif #endif /* __STM32F4xx_HAL_PCD_EX_H */ /************************ (C) COPYRIGHT STMicroelectronics *****END OF FILE****/ ================================================ FILE: Zelig/mbed/TARGET_NUCLEO_F401RE/stm32f4xx_hal_pwr.h ================================================ /** ****************************************************************************** * @file stm32f4xx_hal_pwr.h * @author MCD Application Team * @version V1.4.1 * @date 09-October-2015 * @brief Header file of PWR HAL module. ****************************************************************************** * @attention * *

© COPYRIGHT(c) 2015 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. * ****************************************************************************** */ /* Define to prevent recursive inclusion -------------------------------------*/ #ifndef __STM32F4xx_HAL_PWR_H #define __STM32F4xx_HAL_PWR_H #ifdef __cplusplus extern "C" { #endif /* Includes ------------------------------------------------------------------*/ #include "stm32f4xx_hal_def.h" /** @addtogroup STM32F4xx_HAL_Driver * @{ */ /** @addtogroup PWR * @{ */ /* Exported types ------------------------------------------------------------*/ /** @defgroup PWR_Exported_Types PWR Exported Types * @{ */ /** * @brief PWR PVD configuration structure definition */ typedef struct { uint32_t PVDLevel; /*!< PVDLevel: Specifies the PVD detection level. This parameter can be a value of @ref PWR_PVD_detection_level */ uint32_t Mode; /*!< Mode: Specifies the operating mode for the selected pins. This parameter can be a value of @ref PWR_PVD_Mode */ }PWR_PVDTypeDef; /** * @} */ /* Exported constants --------------------------------------------------------*/ /** @defgroup PWR_Exported_Constants PWR Exported Constants * @{ */ /** @defgroup PWR_WakeUp_Pins PWR WakeUp Pins * @{ */ #define PWR_WAKEUP_PIN1 ((uint32_t)0x00000100) /** * @} */ /** @defgroup PWR_PVD_detection_level PWR PVD detection level * @{ */ #define PWR_PVDLEVEL_0 PWR_CR_PLS_LEV0 #define PWR_PVDLEVEL_1 PWR_CR_PLS_LEV1 #define PWR_PVDLEVEL_2 PWR_CR_PLS_LEV2 #define PWR_PVDLEVEL_3 PWR_CR_PLS_LEV3 #define PWR_PVDLEVEL_4 PWR_CR_PLS_LEV4 #define PWR_PVDLEVEL_5 PWR_CR_PLS_LEV5 #define PWR_PVDLEVEL_6 PWR_CR_PLS_LEV6 #define PWR_PVDLEVEL_7 PWR_CR_PLS_LEV7/* External input analog voltage (Compare internally to VREFINT) */ /** * @} */ /** @defgroup PWR_PVD_Mode PWR PVD Mode * @{ */ #define PWR_PVD_MODE_NORMAL ((uint32_t)0x00000000) /*!< basic mode is used */ #define PWR_PVD_MODE_IT_RISING ((uint32_t)0x00010001) /*!< External Interrupt Mode with Rising edge trigger detection */ #define PWR_PVD_MODE_IT_FALLING ((uint32_t)0x00010002) /*!< External Interrupt Mode with Falling edge trigger detection */ #define PWR_PVD_MODE_IT_RISING_FALLING ((uint32_t)0x00010003) /*!< External Interrupt Mode with Rising/Falling edge trigger detection */ #define PWR_PVD_MODE_EVENT_RISING ((uint32_t)0x00020001) /*!< Event Mode with Rising edge trigger detection */ #define PWR_PVD_MODE_EVENT_FALLING ((uint32_t)0x00020002) /*!< Event Mode with Falling edge trigger detection */ #define PWR_PVD_MODE_EVENT_RISING_FALLING ((uint32_t)0x00020003) /*!< Event Mode with Rising/Falling edge trigger detection */ /** * @} */ /** @defgroup PWR_Regulator_state_in_STOP_mode PWR Regulator state in SLEEP/STOP mode * @{ */ #define PWR_MAINREGULATOR_ON ((uint32_t)0x00000000) #define PWR_LOWPOWERREGULATOR_ON PWR_CR_LPDS /** * @} */ /** @defgroup PWR_SLEEP_mode_entry PWR SLEEP mode entry * @{ */ #define PWR_SLEEPENTRY_WFI ((uint8_t)0x01) #define PWR_SLEEPENTRY_WFE ((uint8_t)0x02) /** * @} */ /** @defgroup PWR_STOP_mode_entry PWR STOP mode entry * @{ */ #define PWR_STOPENTRY_WFI ((uint8_t)0x01) #define PWR_STOPENTRY_WFE ((uint8_t)0x02) /** * @} */ /** @defgroup PWR_Flag PWR Flag * @{ */ #define PWR_FLAG_WU PWR_CSR_WUF #define PWR_FLAG_SB PWR_CSR_SBF #define PWR_FLAG_PVDO PWR_CSR_PVDO #define PWR_FLAG_BRR PWR_CSR_BRR #define PWR_FLAG_VOSRDY PWR_CSR_VOSRDY /** * @} */ /** * @} */ /* Exported macro ------------------------------------------------------------*/ /** @defgroup PWR_Exported_Macro PWR Exported Macro * @{ */ /** @brief Check PWR flag is set or not. * @param __FLAG__: specifies the flag to check. * This parameter can be one of the following values: * @arg PWR_FLAG_WU: Wake Up flag. This flag indicates that a wakeup event * was received from the WKUP pin or from the RTC alarm (Alarm A * or Alarm B), RTC Tamper event, RTC TimeStamp event or RTC Wakeup. * An additional wakeup event is detected if the WKUP pin is enabled * (by setting the EWUP bit) when the WKUP pin level is already high. * @arg PWR_FLAG_SB: StandBy flag. This flag indicates that the system was * resumed from StandBy mode. * @arg PWR_FLAG_PVDO: PVD Output. This flag is valid only if PVD is enabled * by the HAL_PWR_EnablePVD() function. The PVD is stopped by Standby mode * For this reason, this bit is equal to 0 after Standby or reset * until the PVDE bit is set. * @arg PWR_FLAG_BRR: Backup regulator ready flag. This bit is not reset * when the device wakes up from Standby mode or by a system reset * or power reset. * @arg PWR_FLAG_VOSRDY: This flag indicates that the Regulator voltage * scaling output selection is ready. * @retval The new state of __FLAG__ (TRUE or FALSE). */ #define __HAL_PWR_GET_FLAG(__FLAG__) ((PWR->CSR & (__FLAG__)) == (__FLAG__)) /** @brief Clear the PWR's pending flags. * @param __FLAG__: specifies the flag to clear. * This parameter can be one of the following values: * @arg PWR_FLAG_WU: Wake Up flag * @arg PWR_FLAG_SB: StandBy flag */ #define __HAL_PWR_CLEAR_FLAG(__FLAG__) (PWR->CR |= (__FLAG__) << 2) /** * @brief Enable the PVD Exti Line 16. * @retval None. */ #define __HAL_PWR_PVD_EXTI_ENABLE_IT() (EXTI->IMR |= (PWR_EXTI_LINE_PVD)) /** * @brief Disable the PVD EXTI Line 16. * @retval None. */ #define __HAL_PWR_PVD_EXTI_DISABLE_IT() (EXTI->IMR &= ~(PWR_EXTI_LINE_PVD)) /** * @brief Enable event on PVD Exti Line 16. * @retval None. */ #define __HAL_PWR_PVD_EXTI_ENABLE_EVENT() (EXTI->EMR |= (PWR_EXTI_LINE_PVD)) /** * @brief Disable event on PVD Exti Line 16. * @retval None. */ #define __HAL_PWR_PVD_EXTI_DISABLE_EVENT() (EXTI->EMR &= ~(PWR_EXTI_LINE_PVD)) /** * @brief Enable the PVD Extended Interrupt Rising Trigger. * @retval None. */ #define __HAL_PWR_PVD_EXTI_ENABLE_RISING_EDGE() SET_BIT(EXTI->RTSR, PWR_EXTI_LINE_PVD) /** * @brief Disable the PVD Extended Interrupt Rising Trigger. * @retval None. */ #define __HAL_PWR_PVD_EXTI_DISABLE_RISING_EDGE() CLEAR_BIT(EXTI->RTSR, PWR_EXTI_LINE_PVD) /** * @brief Enable the PVD Extended Interrupt Falling Trigger. * @retval None. */ #define __HAL_PWR_PVD_EXTI_ENABLE_FALLING_EDGE() SET_BIT(EXTI->FTSR, PWR_EXTI_LINE_PVD) /** * @brief Disable the PVD Extended Interrupt Falling Trigger. * @retval None. */ #define __HAL_PWR_PVD_EXTI_DISABLE_FALLING_EDGE() CLEAR_BIT(EXTI->FTSR, PWR_EXTI_LINE_PVD) /** * @brief PVD EXTI line configuration: set rising & falling edge trigger. * @retval None. */ #define __HAL_PWR_PVD_EXTI_ENABLE_RISING_FALLING_EDGE() __HAL_PWR_PVD_EXTI_ENABLE_RISING_EDGE();__HAL_PWR_PVD_EXTI_ENABLE_FALLING_EDGE(); /** * @brief Disable the PVD Extended Interrupt Rising & Falling Trigger. * This parameter can be: * @retval None. */ #define __HAL_PWR_PVD_EXTI_DISABLE_RISING_FALLING_EDGE() __HAL_PWR_PVD_EXTI_DISABLE_RISING_EDGE();__HAL_PWR_PVD_EXTI_DISABLE_FALLING_EDGE(); /** * @brief checks whether the specified PVD Exti interrupt flag is set or not. * @retval EXTI PVD Line Status. */ #define __HAL_PWR_PVD_EXTI_GET_FLAG() (EXTI->PR & (PWR_EXTI_LINE_PVD)) /** * @brief Clear the PVD Exti flag. * @retval None. */ #define __HAL_PWR_PVD_EXTI_CLEAR_FLAG() (EXTI->PR = (PWR_EXTI_LINE_PVD)) /** * @brief Generates a Software interrupt on PVD EXTI line. * @retval None */ #define __HAL_PWR_PVD_EXTI_GENERATE_SWIT() (EXTI->SWIER |= (PWR_EXTI_LINE_PVD)) /** * @} */ /* Include PWR HAL Extension module */ #include "stm32f4xx_hal_pwr_ex.h" /* Exported functions --------------------------------------------------------*/ /** @addtogroup PWR_Exported_Functions PWR Exported Functions * @{ */ /** @addtogroup PWR_Exported_Functions_Group1 Initialization and de-initialization functions * @{ */ /* Initialization and de-initialization functions *****************************/ void HAL_PWR_DeInit(void); void HAL_PWR_EnableBkUpAccess(void); void HAL_PWR_DisableBkUpAccess(void); /** * @} */ /** @addtogroup PWR_Exported_Functions_Group2 Peripheral Control functions * @{ */ /* Peripheral Control functions **********************************************/ /* PVD configuration */ void HAL_PWR_ConfigPVD(PWR_PVDTypeDef *sConfigPVD); void HAL_PWR_EnablePVD(void); void HAL_PWR_DisablePVD(void); /* WakeUp pins configuration */ void HAL_PWR_EnableWakeUpPin(uint32_t WakeUpPinx); void HAL_PWR_DisableWakeUpPin(uint32_t WakeUpPinx); /* Low Power modes entry */ void HAL_PWR_EnterSTOPMode(uint32_t Regulator, uint8_t STOPEntry); void HAL_PWR_EnterSLEEPMode(uint32_t Regulator, uint8_t SLEEPEntry); void HAL_PWR_EnterSTANDBYMode(void); /* Power PVD IRQ Handler */ void HAL_PWR_PVD_IRQHandler(void); void HAL_PWR_PVDCallback(void); /* Cortex System Control functions *******************************************/ void HAL_PWR_EnableSleepOnExit(void); void HAL_PWR_DisableSleepOnExit(void); void HAL_PWR_EnableSEVOnPend(void); void HAL_PWR_DisableSEVOnPend(void); /** * @} */ /** * @} */ /* Private types -------------------------------------------------------------*/ /* Private variables ---------------------------------------------------------*/ /* Private constants ---------------------------------------------------------*/ /** @defgroup PWR_Private_Constants PWR Private Constants * @{ */ /** @defgroup PWR_PVD_EXTI_Line PWR PVD EXTI Line * @{ */ #define PWR_EXTI_LINE_PVD ((uint32_t)EXTI_IMR_MR16) /*!< External interrupt line 16 Connected to the PVD EXTI Line */ /** * @} */ /** @defgroup PWR_register_alias_address PWR Register alias address * @{ */ /* ------------- PWR registers bit address in the alias region ---------------*/ #define PWR_OFFSET (PWR_BASE - PERIPH_BASE) #define PWR_CR_OFFSET 0x00 #define PWR_CSR_OFFSET 0x04 #define PWR_CR_OFFSET_BB (PWR_OFFSET + PWR_CR_OFFSET) #define PWR_CSR_OFFSET_BB (PWR_OFFSET + PWR_CSR_OFFSET) /** * @} */ /** @defgroup PWR_CR_register_alias PWR CR Register alias address * @{ */ /* --- CR Register ---*/ /* Alias word address of DBP bit */ #define DBP_BIT_NUMBER POSITION_VAL(PWR_CR_DBP) #define CR_DBP_BB (uint32_t)(PERIPH_BB_BASE + (PWR_CR_OFFSET_BB * 32) + (DBP_BIT_NUMBER * 4)) /* Alias word address of PVDE bit */ #define PVDE_BIT_NUMBER POSITION_VAL(PWR_CR_PVDE) #define CR_PVDE_BB (uint32_t)(PERIPH_BB_BASE + (PWR_CR_OFFSET_BB * 32) + (PVDE_BIT_NUMBER * 4)) /* Alias word address of PMODE bit */ #define PMODE_BIT_NUMBER POSITION_VAL(PWR_CR_PMODE) #define CR_PMODE_BB (uint32_t)(PERIPH_BB_BASE + (PWR_CR_OFFSET_BB * 32) + (PMODE_BIT_NUMBER * 4)) /** * @} */ /** @defgroup PWR_CSR_register_alias PWR CSR Register alias address * @{ */ /* --- CSR Register ---*/ /* Alias word address of EWUP bit */ #define EWUP_BIT_NUMBER POSITION_VAL(PWR_CSR_EWUP) #define CSR_EWUP_BB (PERIPH_BB_BASE + (PWR_CSR_OFFSET_BB * 32) + (EWUP_BIT_NUMBER * 4)) /** * @} */ /** * @} */ /* Private macros ------------------------------------------------------------*/ /** @defgroup PWR_Private_Macros PWR Private Macros * @{ */ /** @defgroup PWR_IS_PWR_Definitions PWR Private macros to check input parameters * @{ */ #define IS_PWR_PVD_LEVEL(LEVEL) (((LEVEL) == PWR_PVDLEVEL_0) || ((LEVEL) == PWR_PVDLEVEL_1)|| \ ((LEVEL) == PWR_PVDLEVEL_2) || ((LEVEL) == PWR_PVDLEVEL_3)|| \ ((LEVEL) == PWR_PVDLEVEL_4) || ((LEVEL) == PWR_PVDLEVEL_5)|| \ ((LEVEL) == PWR_PVDLEVEL_6) || ((LEVEL) == PWR_PVDLEVEL_7)) #define IS_PWR_PVD_MODE(MODE) (((MODE) == PWR_PVD_MODE_IT_RISING)|| ((MODE) == PWR_PVD_MODE_IT_FALLING) || \ ((MODE) == PWR_PVD_MODE_IT_RISING_FALLING) || ((MODE) == PWR_PVD_MODE_EVENT_RISING) || \ ((MODE) == PWR_PVD_MODE_EVENT_FALLING) || ((MODE) == PWR_PVD_MODE_EVENT_RISING_FALLING) || \ ((MODE) == PWR_PVD_MODE_NORMAL)) #define IS_PWR_REGULATOR(REGULATOR) (((REGULATOR) == PWR_MAINREGULATOR_ON) || \ ((REGULATOR) == PWR_LOWPOWERREGULATOR_ON)) #define IS_PWR_SLEEP_ENTRY(ENTRY) (((ENTRY) == PWR_SLEEPENTRY_WFI) || ((ENTRY) == PWR_SLEEPENTRY_WFE)) #define IS_PWR_STOP_ENTRY(ENTRY) (((ENTRY) == PWR_STOPENTRY_WFI) || ((ENTRY) == PWR_STOPENTRY_WFE)) /** * @} */ /** * @} */ /** * @} */ /** * @} */ #ifdef __cplusplus } #endif #endif /* __STM32F4xx_HAL_PWR_H */ /************************ (C) COPYRIGHT STMicroelectronics *****END OF FILE****/ ================================================ FILE: Zelig/mbed/TARGET_NUCLEO_F401RE/stm32f4xx_hal_pwr_ex.h ================================================ /** ****************************************************************************** * @file stm32f4xx_hal_pwr_ex.h * @author MCD Application Team * @version V1.4.1 * @date 09-October-2015 * @brief Header file of PWR HAL Extension module. ****************************************************************************** * @attention * *

© COPYRIGHT(c) 2015 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. * ****************************************************************************** */ /* Define to prevent recursive inclusion -------------------------------------*/ #ifndef __STM32F4xx_HAL_PWR_EX_H #define __STM32F4xx_HAL_PWR_EX_H #ifdef __cplusplus extern "C" { #endif /* Includes ------------------------------------------------------------------*/ #include "stm32f4xx_hal_def.h" /** @addtogroup STM32F4xx_HAL_Driver * @{ */ /** @addtogroup PWREx * @{ */ /* Exported types ------------------------------------------------------------*/ /* Exported constants --------------------------------------------------------*/ /** @defgroup PWREx_Exported_Constants PWREx Exported Constants * @{ */ #if defined(STM32F427xx) || defined(STM32F437xx) || defined(STM32F429xx) || defined(STM32F439xx) ||\ defined(STM32F446xx) || defined(STM32F469xx) || defined(STM32F479xx) /** @defgroup PWREx_Regulator_state_in_UnderDrive_mode PWREx Regulator state in UnderDrive mode * @{ */ #define PWR_MAINREGULATOR_UNDERDRIVE_ON PWR_CR_MRUDS #define PWR_LOWPOWERREGULATOR_UNDERDRIVE_ON ((uint32_t)(PWR_CR_LPDS | PWR_CR_LPUDS)) /** * @} */ /** @defgroup PWREx_Over_Under_Drive_Flag PWREx Over Under Drive Flag * @{ */ #define PWR_FLAG_ODRDY PWR_CSR_ODRDY #define PWR_FLAG_ODSWRDY PWR_CSR_ODSWRDY #define PWR_FLAG_UDRDY PWR_CSR_UDSWRDY /** * @} */ #endif /* STM32F427xx || STM32F437xx || STM32F429xx || STM32F439xx || STM32F446xx || STM32F469xx || STM32F479xx */ /** @defgroup PWREx_Regulator_Voltage_Scale PWREx Regulator Voltage Scale * @{ */ #if defined(STM32F405xx) || defined(STM32F407xx) || defined(STM32F415xx) || defined(STM32F417xx) #define PWR_REGULATOR_VOLTAGE_SCALE1 PWR_CR_VOS /* Scale 1 mode(default value at reset): the maximum value of fHCLK = 168 MHz. */ #define PWR_REGULATOR_VOLTAGE_SCALE2 ((uint32_t)0x00000000) /* Scale 2 mode: the maximum value of fHCLK = 144 MHz. */ #else #define PWR_REGULATOR_VOLTAGE_SCALE1 PWR_CR_VOS /* Scale 1 mode(default value at reset): the maximum value of fHCLK is 168 MHz. It can be extended to 180 MHz by activating the over-drive mode. */ #define PWR_REGULATOR_VOLTAGE_SCALE2 PWR_CR_VOS_1 /* Scale 2 mode: the maximum value of fHCLK is 144 MHz. It can be extended to 168 MHz by activating the over-drive mode. */ #define PWR_REGULATOR_VOLTAGE_SCALE3 PWR_CR_VOS_0 /* Scale 3 mode: the maximum value of fHCLK is 120 MHz. */ #endif /* STM32F405xx || STM32F407xx || STM32F415xx || STM32F417xx */ /** * @} */ #if defined(STM32F410Tx) || defined(STM32F410Cx) || defined(STM32F410Rx) || defined(STM32F446xx) /** @defgroup PWREx_WakeUp_Pins PWREx WakeUp Pins * @{ */ #define PWR_WAKEUP_PIN2 ((uint32_t)0x00000080) #if defined(STM32F410Tx) || defined(STM32F410Cx) || defined(STM32F410Rx) #define PWR_WAKEUP_PIN3 ((uint32_t)0x00000040) #endif /* STM32F410xx */ /** * @} */ #endif /* STM32F410xx || STM32F446xx */ /** * @} */ /* Exported macro ------------------------------------------------------------*/ /** @defgroup PWREx_Exported_Constants PWREx Exported Constants * @{ */ #if defined(STM32F405xx) || defined(STM32F407xx) || defined(STM32F415xx) || defined(STM32F417xx) /** @brief macros configure the main internal regulator output voltage. * @param __REGULATOR__: specifies the regulator output voltage to achieve * a tradeoff between performance and power consumption when the device does * not operate at the maximum frequency (refer to the datasheets for more details). * This parameter can be one of the following values: * @arg PWR_REGULATOR_VOLTAGE_SCALE1: Regulator voltage output Scale 1 mode * @arg PWR_REGULATOR_VOLTAGE_SCALE2: Regulator voltage output Scale 2 mode * @retval None */ #define __HAL_PWR_VOLTAGESCALING_CONFIG(__REGULATOR__) do { \ __IO uint32_t tmpreg; \ MODIFY_REG(PWR->CR, PWR_CR_VOS, (__REGULATOR__)); \ /* Delay after an RCC peripheral clock enabling */ \ tmpreg = READ_BIT(PWR->CR, PWR_CR_VOS); \ UNUSED(tmpreg); \ } while(0) #else /** @brief macros configure the main internal regulator output voltage. * @param __REGULATOR__: specifies the regulator output voltage to achieve * a tradeoff between performance and power consumption when the device does * not operate at the maximum frequency (refer to the datasheets for more details). * This parameter can be one of the following values: * @arg PWR_REGULATOR_VOLTAGE_SCALE1: Regulator voltage output Scale 1 mode * @arg PWR_REGULATOR_VOLTAGE_SCALE2: Regulator voltage output Scale 2 mode * @arg PWR_REGULATOR_VOLTAGE_SCALE3: Regulator voltage output Scale 3 mode * @retval None */ #define __HAL_PWR_VOLTAGESCALING_CONFIG(__REGULATOR__) do { \ __IO uint32_t tmpreg; \ MODIFY_REG(PWR->CR, PWR_CR_VOS, (__REGULATOR__)); \ /* Delay after an RCC peripheral clock enabling */ \ tmpreg = READ_BIT(PWR->CR, PWR_CR_VOS); \ UNUSED(tmpreg); \ } while(0) #endif /* STM32F405xx || STM32F407xx || STM32F415xx || STM32F417xx */ #if defined(STM32F427xx) || defined(STM32F437xx) || defined(STM32F429xx) || defined(STM32F439xx) ||\ defined(STM32F446xx) || defined(STM32F469xx) || defined(STM32F479xx) /** @brief Macros to enable or disable the Over drive mode. * @note These macros can be used only for STM32F42xx/STM3243xx devices. */ #define __HAL_PWR_OVERDRIVE_ENABLE() (*(__IO uint32_t *) CR_ODEN_BB = ENABLE) #define __HAL_PWR_OVERDRIVE_DISABLE() (*(__IO uint32_t *) CR_ODEN_BB = DISABLE) /** @brief Macros to enable or disable the Over drive switching. * @note These macros can be used only for STM32F42xx/STM3243xx devices. */ #define __HAL_PWR_OVERDRIVESWITCHING_ENABLE() (*(__IO uint32_t *) CR_ODSWEN_BB = ENABLE) #define __HAL_PWR_OVERDRIVESWITCHING_DISABLE() (*(__IO uint32_t *) CR_ODSWEN_BB = DISABLE) /** @brief Macros to enable or disable the Under drive mode. * @note This mode is enabled only with STOP low power mode. * In this mode, the 1.2V domain is preserved in reduced leakage mode. This * mode is only available when the main regulator or the low power regulator * is in low voltage mode. * @note If the Under-drive mode was enabled, it is automatically disabled after * exiting Stop mode. * When the voltage regulator operates in Under-drive mode, an additional * startup delay is induced when waking up from Stop mode. */ #define __HAL_PWR_UNDERDRIVE_ENABLE() (PWR->CR |= (uint32_t)PWR_CR_UDEN) #define __HAL_PWR_UNDERDRIVE_DISABLE() (PWR->CR &= (uint32_t)(~PWR_CR_UDEN)) /** @brief Check PWR flag is set or not. * @note These macros can be used only for STM32F42xx/STM3243xx devices. * @param __FLAG__: specifies the flag to check. * This parameter can be one of the following values: * @arg PWR_FLAG_ODRDY: This flag indicates that the Over-drive mode * is ready * @arg PWR_FLAG_ODSWRDY: This flag indicates that the Over-drive mode * switching is ready * @arg PWR_FLAG_UDRDY: This flag indicates that the Under-drive mode * is enabled in Stop mode * @retval The new state of __FLAG__ (TRUE or FALSE). */ #define __HAL_PWR_GET_ODRUDR_FLAG(__FLAG__) ((PWR->CSR & (__FLAG__)) == (__FLAG__)) /** @brief Clear the Under-Drive Ready flag. * @note These macros can be used only for STM32F42xx/STM3243xx devices. */ #define __HAL_PWR_CLEAR_ODRUDR_FLAG() (PWR->CSR |= PWR_FLAG_UDRDY) #endif /* STM32F427xx || STM32F437xx || STM32F429xx || STM32F439xx || STM32F446xx || STM32F469xx || STM32F479xx */ /** * @} */ /* Exported functions --------------------------------------------------------*/ /** @addtogroup PWREx_Exported_Functions PWREx Exported Functions * @{ */ /** @addtogroup PWREx_Exported_Functions_Group1 * @{ */ void HAL_PWREx_EnableFlashPowerDown(void); void HAL_PWREx_DisableFlashPowerDown(void); HAL_StatusTypeDef HAL_PWREx_EnableBkUpReg(void); HAL_StatusTypeDef HAL_PWREx_DisableBkUpReg(void); uint32_t HAL_PWREx_GetVoltageRange(void); HAL_StatusTypeDef HAL_PWREx_ControlVoltageScaling(uint32_t VoltageScaling); #if defined(STM32F469xx) || defined(STM32F479xx) void HAL_PWREx_EnableWakeUpPinPolarityRisingEdge(void); void HAL_PWREx_EnableWakeUpPinPolarityFallingEdge(void); #endif /* STM32F469xx || STM32F479xx */ #if defined(STM32F410Tx) || defined(STM32F410Cx) || defined(STM32F410Rx) || defined(STM32F401xC) ||\ defined(STM32F401xE) || defined(STM32F411xE) void HAL_PWREx_EnableMainRegulatorLowVoltage(void); void HAL_PWREx_DisableMainRegulatorLowVoltage(void); void HAL_PWREx_EnableLowRegulatorLowVoltage(void); void HAL_PWREx_DisableLowRegulatorLowVoltage(void); #endif /* STM32F410xx || STM32F401xC || STM32F401xE || STM32F411xE */ #if defined(STM32F427xx) || defined(STM32F437xx) || defined(STM32F429xx) || defined(STM32F439xx) || defined(STM32F446xx) ||\ defined(STM32F469xx) || defined(STM32F479xx) HAL_StatusTypeDef HAL_PWREx_EnableOverDrive(void); HAL_StatusTypeDef HAL_PWREx_DisableOverDrive(void); HAL_StatusTypeDef HAL_PWREx_EnterUnderDriveSTOPMode(uint32_t Regulator, uint8_t STOPEntry); #endif /* STM32F427xx || STM32F437xx || STM32F429xx || STM32F439xx || STM32F446xx || STM32F469xx || STM32F479xx */ /** * @} */ /** * @} */ /* Private types -------------------------------------------------------------*/ /* Private variables ---------------------------------------------------------*/ /* Private constants ---------------------------------------------------------*/ /** @defgroup PWREx_Private_Constants PWREx Private Constants * @{ */ /** @defgroup PWREx_register_alias_address PWREx Register alias address * @{ */ /* ------------- PWR registers bit address in the alias region ---------------*/ /* --- CR Register ---*/ /* Alias word address of FPDS bit */ #define FPDS_BIT_NUMBER POSITION_VAL(PWR_CR_FPDS) #define CR_FPDS_BB (uint32_t)(PERIPH_BB_BASE + (PWR_CR_OFFSET_BB * 32) + (FPDS_BIT_NUMBER * 4)) /* Alias word address of ODEN bit */ #define ODEN_BIT_NUMBER POSITION_VAL(PWR_CR_ODEN) #define CR_ODEN_BB (uint32_t)(PERIPH_BB_BASE + (PWR_CR_OFFSET_BB * 32) + (ODEN_BIT_NUMBER * 4)) /* Alias word address of ODSWEN bit */ #define ODSWEN_BIT_NUMBER POSITION_VAL(PWR_CR_ODSWEN) #define CR_ODSWEN_BB (uint32_t)(PERIPH_BB_BASE + (PWR_CR_OFFSET_BB * 32) + (ODSWEN_BIT_NUMBER * 4)) /* Alias word address of MRLVDS bit */ #define MRLVDS_BIT_NUMBER POSITION_VAL(PWR_CR_MRLVDS) #define CR_MRLVDS_BB (uint32_t)(PERIPH_BB_BASE + (PWR_CR_OFFSET_BB * 32) + (MRLVDS_BIT_NUMBER * 4)) /* Alias word address of LPLVDS bit */ #define LPLVDS_BIT_NUMBER POSITION_VAL(PWR_CR_LPLVDS) #define CR_LPLVDS_BB (uint32_t)(PERIPH_BB_BASE + (PWR_CR_OFFSET_BB * 32) + (LPLVDS_BIT_NUMBER * 4)) /** * @} */ /** @defgroup PWREx_CSR_register_alias PWRx CSR Register alias address * @{ */ /* --- CSR Register ---*/ /* Alias word address of BRE bit */ #define BRE_BIT_NUMBER POSITION_VAL(PWR_CSR_BRE) #define CSR_BRE_BB (uint32_t)(PERIPH_BB_BASE + (PWR_CSR_OFFSET_BB * 32) + (BRE_BIT_NUMBER * 4)) #if defined(STM32F469xx) || defined(STM32F479xx) /* Alias word address of WUPP bit */ #define WUPP_BIT_NUMBER POSITION_VAL(PWR_CSR_WUPP) #define CSR_WUPP_BB (PERIPH_BB_BASE + (PWR_CSR_OFFSET_BB * 32) + (WUPP_BIT_NUMBER * 4)) #endif /* STM32F469xx || STM32F479xx */ /** * @} */ /** * @} */ /* Private macros ------------------------------------------------------------*/ /** @defgroup PWREx_Private_Macros PWREx Private Macros * @{ */ /** @defgroup PWREx_IS_PWR_Definitions PWREx Private macros to check input parameters * @{ */ #if defined(STM32F427xx) || defined(STM32F437xx) || defined(STM32F429xx) || defined(STM32F439xx) ||\ defined(STM32F446xx) || defined(STM32F469xx) || defined(STM32F479xx) #define IS_PWR_REGULATOR_UNDERDRIVE(REGULATOR) (((REGULATOR) == PWR_MAINREGULATOR_UNDERDRIVE_ON) || \ ((REGULATOR) == PWR_LOWPOWERREGULATOR_UNDERDRIVE_ON)) #endif /* STM32F427xx || STM32F437xx || STM32F429xx || STM32F439xx || STM32F446xx || STM32F469xx || STM32F479xx */ #if defined(STM32F405xx) || defined(STM32F407xx) || defined(STM32F415xx) || defined(STM32F417xx) #define IS_PWR_VOLTAGE_SCALING_RANGE(VOLTAGE) (((VOLTAGE) == PWR_REGULATOR_VOLTAGE_SCALE1) || \ ((VOLTAGE) == PWR_REGULATOR_VOLTAGE_SCALE2)) #else #define IS_PWR_VOLTAGE_SCALING_RANGE(VOLTAGE) (((VOLTAGE) == PWR_REGULATOR_VOLTAGE_SCALE1) || \ ((VOLTAGE) == PWR_REGULATOR_VOLTAGE_SCALE2) || \ ((VOLTAGE) == PWR_REGULATOR_VOLTAGE_SCALE3)) #endif /* STM32F405xx || STM32F407xx || STM32F415xx || STM32F417xx */ #if defined(STM32F446xx) #define IS_PWR_WAKEUP_PIN(PIN) (((PIN) == PWR_WAKEUP_PIN1) || ((PIN) == PWR_WAKEUP_PIN2)) #elif defined(STM32F410Tx) || defined(STM32F410Cx) || defined(STM32F410Rx) #define IS_PWR_WAKEUP_PIN(PIN) (((PIN) == PWR_WAKEUP_PIN1) || ((PIN) == PWR_WAKEUP_PIN2) || \ ((PIN) == PWR_WAKEUP_PIN3)) #else #define IS_PWR_WAKEUP_PIN(PIN) ((PIN) == PWR_WAKEUP_PIN1) #endif /* STM32F446xx */ /** * @} */ /** * @} */ /** * @} */ /** * @} */ #ifdef __cplusplus } #endif #endif /* __STM32F4xx_HAL_PWR_EX_H */ /************************ (C) COPYRIGHT STMicroelectronics *****END OF FILE****/ ================================================ FILE: Zelig/mbed/TARGET_NUCLEO_F401RE/stm32f4xx_hal_qspi.h ================================================ /** ****************************************************************************** * @file stm32f4xx_hal_qspi.h * @author MCD Application Team * @version V1.4.1 * @date 09-October-2015 * @brief Header file of QSPI HAL module. ****************************************************************************** * @attention * *

© COPYRIGHT(c) 2015 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. * ****************************************************************************** */ /* Define to prevent recursive inclusion -------------------------------------*/ #ifndef __STM32F4xx_HAL_QSPI_H #define __STM32F4xx_HAL_QSPI_H #ifdef __cplusplus extern "C" { #endif #if defined(STM32F446xx) || defined(STM32F469xx) || defined(STM32F479xx) /* Includes ------------------------------------------------------------------*/ #include "stm32f4xx_hal_def.h" /** @addtogroup STM32F4xx_HAL_Driver * @{ */ /** @addtogroup QSPI * @{ */ /* Exported types ------------------------------------------------------------*/ /** @defgroup QSPI_Exported_Types QSPI Exported Types * @{ */ /** * @brief QSPI Init structure definition */ typedef struct { uint32_t ClockPrescaler; /* Specifies the prescaler factor for generating clock based on the AHB clock. This parameter can be a number between 0 and 255 */ uint32_t FifoThreshold; /* Specifies the threshold number of bytes in the FIFO (used only in indirect mode) This parameter can be a value between 1 and 32 */ uint32_t SampleShifting; /* Specifies the Sample Shift. The data is sampled 1/2 clock cycle delay later to take in account external signal delays. (It should be QSPI_SAMPLE_SHIFTING_NONE in DDR mode) This parameter can be a value of @ref QSPI_SampleShifting */ uint32_t FlashSize; /* Specifies the Flash Size. FlashSize+1 is effectively the number of address bits required to address the flash memory. The flash capacity can be up to 4GB (addressed using 32 bits) in indirect mode, but the addressable space in memory-mapped mode is limited to 256MB This parameter can be a number between 0 and 31 */ uint32_t ChipSelectHighTime; /* Specifies the Chip Select High Time. ChipSelectHighTime+1 defines the minimum number of clock cycles which the chip select must remain high between commands. This parameter can be a value of @ref QSPI_ChipSelectHighTime */ uint32_t ClockMode; /* Specifies the Clock Mode. It indicates the level that clock takes between commands. This parameter can be a value of @ref QSPI_ClockMode */ uint32_t FlashID; /* Specifies the Flash which will be used, This parameter can be a value of @ref QSPI_Flash_Select */ uint32_t DualFlash; /* Specifies the Dual Flash Mode State This parameter can be a value of @ref QSPI_DualFlash_Mode */ }QSPI_InitTypeDef; /** * @brief HAL QSPI State structures definition */ typedef enum { HAL_QSPI_STATE_RESET = 0x00, /*!< Peripheral not initialized */ HAL_QSPI_STATE_READY = 0x01, /*!< Peripheral initialized and ready for use */ HAL_QSPI_STATE_BUSY = 0x02, /*!< Peripheral in indirect mode and busy */ HAL_QSPI_STATE_BUSY_INDIRECT_TX = 0x12, /*!< Peripheral in indirect mode with transmission ongoing */ HAL_QSPI_STATE_BUSY_INDIRECT_RX = 0x22, /*!< Peripheral in indirect mode with reception ongoing */ HAL_QSPI_STATE_BUSY_AUTO_POLLING = 0x42, /*!< Peripheral in auto polling mode ongoing */ HAL_QSPI_STATE_BUSY_MEM_MAPPED = 0x82, /*!< Peripheral in memory mapped mode ongoing */ HAL_QSPI_STATE_ERROR = 0x04 /*!< Peripheral in error */ }HAL_QSPI_StateTypeDef; /** * @brief QSPI Handle Structure definition */ typedef struct { QUADSPI_TypeDef *Instance; /* QSPI registers base address */ QSPI_InitTypeDef Init; /* QSPI communication parameters */ uint8_t *pTxBuffPtr; /* Pointer to QSPI Tx transfer Buffer */ __IO uint16_t TxXferSize; /* QSPI Tx Transfer size */ __IO uint16_t TxXferCount; /* QSPI Tx Transfer Counter */ uint8_t *pRxBuffPtr; /* Pointer to QSPI Rx transfer Buffer */ __IO uint16_t RxXferSize; /* QSPI Rx Transfer size */ __IO uint16_t RxXferCount; /* QSPI Rx Transfer Counter */ DMA_HandleTypeDef *hdma; /* QSPI Rx/Tx DMA Handle parameters */ __IO HAL_LockTypeDef Lock; /* Locking object */ __IO HAL_QSPI_StateTypeDef State; /* QSPI communication state */ __IO uint32_t ErrorCode; /* QSPI Error code */ uint32_t Timeout; /* Timeout for the QSPI memory access */ }QSPI_HandleTypeDef; /** * @brief QSPI Command structure definition */ typedef struct { uint32_t Instruction; /* Specifies the Instruction to be sent This parameter can be a value (8-bit) between 0x00 and 0xFF */ uint32_t Address; /* Specifies the Address to be sent (Size from 1 to 4 bytes according AddressSize) This parameter can be a value (32-bits) between 0x0 and 0xFFFFFFFF */ uint32_t AlternateBytes; /* Specifies the Alternate Bytes to be sent (Size from 1 to 4 bytes according AlternateBytesSize) This parameter can be a value (32-bits) between 0x0 and 0xFFFFFFFF */ uint32_t AddressSize; /* Specifies the Address Size This parameter can be a value of @ref QSPI_AddressSize */ uint32_t AlternateBytesSize; /* Specifies the Alternate Bytes Size This parameter can be a value of @ref QSPI_AlternateBytesSize */ uint32_t DummyCycles; /* Specifies the Number of Dummy Cycles. This parameter can be a number between 0 and 31 */ uint32_t InstructionMode; /* Specifies the Instruction Mode This parameter can be a value of @ref QSPI_InstructionMode */ uint32_t AddressMode; /* Specifies the Address Mode This parameter can be a value of @ref QSPI_AddressMode */ uint32_t AlternateByteMode; /* Specifies the Alternate Bytes Mode This parameter can be a value of @ref QSPI_AlternateBytesMode */ uint32_t DataMode; /* Specifies the Data Mode (used for dummy cycles and data phases) This parameter can be a value of @ref QSPI_DataMode */ uint32_t NbData; /* Specifies the number of data to transfer. This parameter can be any value between 0 and 0xFFFFFFFF (0 means undefined length until end of memory)*/ uint32_t DdrMode; /* Specifies the double data rate mode for address, alternate byte and data phase This parameter can be a value of @ref QSPI_DdrMode */ uint32_t DdrHoldHalfCycle; /* Specifies the DDR hold half cycle. It delays the data output by one half of system clock in DDR mode. This parameter can be a value of @ref QSPI_DdrHoldHalfCycle */ uint32_t SIOOMode; /* Specifies the send instruction only once mode This parameter can be a value of @ref QSPI_SIOOMode */ }QSPI_CommandTypeDef; /** * @brief QSPI Auto Polling mode configuration structure definition */ typedef struct { uint32_t Match; /* Specifies the value to be compared with the masked status register to get a match. This parameter can be any value between 0 and 0xFFFFFFFF */ uint32_t Mask; /* Specifies the mask to be applied to the status bytes received. This parameter can be any value between 0 and 0xFFFFFFFF */ uint32_t Interval; /* Specifies the number of clock cycles between two read during automatic polling phases. This parameter can be any value between 0 and 0xFFFF */ uint32_t StatusBytesSize; /* Specifies the size of the status bytes received. This parameter can be any value between 1 and 4 */ uint32_t MatchMode; /* Specifies the method used for determining a match. This parameter can be a value of @ref QSPI_MatchMode */ uint32_t AutomaticStop; /* Specifies if automatic polling is stopped after a match. This parameter can be a value of @ref QSPI_AutomaticStop */ }QSPI_AutoPollingTypeDef; /** * @brief QSPI Memory Mapped mode configuration structure definition */ typedef struct { uint32_t TimeOutPeriod; /* Specifies the number of clock to wait when the FIFO is full before to release the chip select. This parameter can be any value between 0 and 0xFFFF */ uint32_t TimeOutActivation; /* Specifies if the time out counter is enabled to release the chip select. This parameter can be a value of @ref QSPI_TimeOutActivation */ }QSPI_MemoryMappedTypeDef; /** * @} */ /* Exported constants --------------------------------------------------------*/ /** @defgroup QSPI_Exported_Constants QSPI Exported Constants * @{ */ /** @defgroup QSPI_ErrorCode QSPI Error Code * @{ */ #define HAL_QSPI_ERROR_NONE ((uint32_t)0x00000000) /*!< No error */ #define HAL_QSPI_ERROR_TIMEOUT ((uint32_t)0x00000001) /*!< Timeout error */ #define HAL_QSPI_ERROR_TRANSFER ((uint32_t)0x00000002) /*!< Transfer error */ #define HAL_QSPI_ERROR_DMA ((uint32_t)0x00000004) /*!< DMA transfer error */ /** * @} */ /** @defgroup QSPI_SampleShifting QSPI Sample Shifting * @{ */ #define QSPI_SAMPLE_SHIFTING_NONE ((uint32_t)0x00000000) /*!State = HAL_QSPI_STATE_RESET) /** @brief Enable QSPI * @param __HANDLE__: specifies the QSPI Handle. * @retval None */ #define __HAL_QSPI_ENABLE(__HANDLE__) SET_BIT((__HANDLE__)->Instance->CR, QUADSPI_CR_EN) /** @brief Disable QSPI * @param __HANDLE__: specifies the QSPI Handle. * @retval None */ #define __HAL_QSPI_DISABLE(__HANDLE__) CLEAR_BIT((__HANDLE__)->Instance->CR, QUADSPI_CR_EN) /** @brief Enables the specified QSPI interrupt. * @param __HANDLE__: specifies the QSPI Handle. * @param __INTERRUPT__: specifies the QSPI interrupt source to enable. * This parameter can be one of the following values: * @arg QSPI_IT_TO: QSPI Time out interrupt * @arg QSPI_IT_SM: QSPI Status match interrupt * @arg QSPI_IT_FT: QSPI FIFO threshold interrupt * @arg QSPI_IT_TC: QSPI Transfer complete interrupt * @arg QSPI_IT_TE: QSPI Transfer error interrupt * @retval None */ #define __HAL_QSPI_ENABLE_IT(__HANDLE__, __INTERRUPT__) SET_BIT((__HANDLE__)->Instance->CR, (__INTERRUPT__)) /** @brief Disables the specified QSPI interrupt. * @param __HANDLE__: specifies the QSPI Handle. * @param __INTERRUPT__: specifies the QSPI interrupt source to disable. * This parameter can be one of the following values: * @arg QSPI_IT_TO: QSPI Timeout interrupt * @arg QSPI_IT_SM: QSPI Status match interrupt * @arg QSPI_IT_FT: QSPI FIFO threshold interrupt * @arg QSPI_IT_TC: QSPI Transfer complete interrupt * @arg QSPI_IT_TE: QSPI Transfer error interrupt * @retval None */ #define __HAL_QSPI_DISABLE_IT(__HANDLE__, __INTERRUPT__) CLEAR_BIT((__HANDLE__)->Instance->CR, (__INTERRUPT__)) /** @brief Checks whether the specified QSPI interrupt source is enabled. * @param __HANDLE__: specifies the QSPI Handle. * @param __INTERRUPT__: specifies the QSPI interrupt source to check. * This parameter can be one of the following values: * @arg QSPI_IT_TO: QSPI Time out interrupt * @arg QSPI_IT_SM: QSPI Status match interrupt * @arg QSPI_IT_FT: QSPI FIFO threshold interrupt * @arg QSPI_IT_TC: QSPI Transfer complete interrupt * @arg QSPI_IT_TE: QSPI Transfer error interrupt * @retval The new state of __INTERRUPT__ (TRUE or FALSE). */ #define __HAL_QSPI_GET_IT_SOURCE(__HANDLE__, __INTERRUPT__) (READ_BIT((__HANDLE__)->Instance->CR, (__INTERRUPT__)) == (__INTERRUPT__)) /** * @brief Get the selected QSPI's flag status. * @param __HANDLE__: specifies the QSPI Handle. * @param __FLAG__: specifies the QSPI flag to check. * This parameter can be one of the following values: * @arg QSPI_FLAG_BUSY: QSPI Busy flag * @arg QSPI_FLAG_TO: QSPI Time out flag * @arg QSPI_FLAG_SM: QSPI Status match flag * @arg QSPI_FLAG_FT: QSPI FIFO threshold flag * @arg QSPI_FLAG_TC: QSPI Transfer complete flag * @arg QSPI_FLAG_TE: QSPI Transfer error flag * @retval None */ #define __HAL_QSPI_GET_FLAG(__HANDLE__, __FLAG__) (READ_BIT((__HANDLE__)->Instance->SR, (__FLAG__)) != 0) /** @brief Clears the specified QSPI's flag status. * @param __HANDLE__: specifies the QSPI Handle. * @param __FLAG__: specifies the QSPI clear register flag that needs to be set * This parameter can be one of the following values: * @arg QSPI_FLAG_TO: QSPI Time out flag * @arg QSPI_FLAG_SM: QSPI Status match flag * @arg QSPI_FLAG_TC: QSPI Transfer complete flag * @arg QSPI_FLAG_TE: QSPI Transfer error flag * @retval None */ #define __HAL_QSPI_CLEAR_FLAG(__HANDLE__, __FLAG__) WRITE_REG((__HANDLE__)->Instance->FCR, (__FLAG__)) /** * @} */ /* Exported functions --------------------------------------------------------*/ /** @addtogroup QSPI_Exported_Functions * @{ */ /** @addtogroup QSPI_Exported_Functions_Group1 * @{ */ /* Initialization/de-initialization functions ********************************/ HAL_StatusTypeDef HAL_QSPI_Init (QSPI_HandleTypeDef *hqspi); HAL_StatusTypeDef HAL_QSPI_DeInit (QSPI_HandleTypeDef *hqspi); void HAL_QSPI_MspInit (QSPI_HandleTypeDef *hqspi); void HAL_QSPI_MspDeInit(QSPI_HandleTypeDef *hqspi); /** * @} */ /** @addtogroup QSPI_Exported_Functions_Group2 * @{ */ /* IO operation functions *****************************************************/ /* QSPI IRQ handler method */ void HAL_QSPI_IRQHandler(QSPI_HandleTypeDef *hqspi); /* QSPI indirect mode */ HAL_StatusTypeDef HAL_QSPI_Command (QSPI_HandleTypeDef *hqspi, QSPI_CommandTypeDef *cmd, uint32_t Timeout); HAL_StatusTypeDef HAL_QSPI_Transmit (QSPI_HandleTypeDef *hqspi, uint8_t *pData, uint32_t Timeout); HAL_StatusTypeDef HAL_QSPI_Receive (QSPI_HandleTypeDef *hqspi, uint8_t *pData, uint32_t Timeout); HAL_StatusTypeDef HAL_QSPI_Command_IT (QSPI_HandleTypeDef *hqspi, QSPI_CommandTypeDef *cmd); HAL_StatusTypeDef HAL_QSPI_Transmit_IT (QSPI_HandleTypeDef *hqspi, uint8_t *pData); HAL_StatusTypeDef HAL_QSPI_Receive_IT (QSPI_HandleTypeDef *hqspi, uint8_t *pData); HAL_StatusTypeDef HAL_QSPI_Transmit_DMA (QSPI_HandleTypeDef *hqspi, uint8_t *pData); HAL_StatusTypeDef HAL_QSPI_Receive_DMA (QSPI_HandleTypeDef *hqspi, uint8_t *pData); /* QSPI status flag polling mode */ HAL_StatusTypeDef HAL_QSPI_AutoPolling (QSPI_HandleTypeDef *hqspi, QSPI_CommandTypeDef *cmd, QSPI_AutoPollingTypeDef *cfg, uint32_t Timeout); HAL_StatusTypeDef HAL_QSPI_AutoPolling_IT(QSPI_HandleTypeDef *hqspi, QSPI_CommandTypeDef *cmd, QSPI_AutoPollingTypeDef *cfg); /* QSPI memory-mapped mode */ HAL_StatusTypeDef HAL_QSPI_MemoryMapped(QSPI_HandleTypeDef *hqspi, QSPI_CommandTypeDef *cmd, QSPI_MemoryMappedTypeDef *cfg); /** * @} */ /** @addtogroup QSPI_Exported_Functions_Group3 * @{ */ /* Callback functions in non-blocking modes ***********************************/ void HAL_QSPI_ErrorCallback (QSPI_HandleTypeDef *hqspi); void HAL_QSPI_FifoThresholdCallback(QSPI_HandleTypeDef *hqspi); /* QSPI indirect mode */ void HAL_QSPI_CmdCpltCallback (QSPI_HandleTypeDef *hqspi); void HAL_QSPI_RxCpltCallback (QSPI_HandleTypeDef *hqspi); void HAL_QSPI_TxCpltCallback (QSPI_HandleTypeDef *hqspi); void HAL_QSPI_RxHalfCpltCallback (QSPI_HandleTypeDef *hqspi); void HAL_QSPI_TxHalfCpltCallback (QSPI_HandleTypeDef *hqspi); /* QSPI status flag polling mode */ void HAL_QSPI_StatusMatchCallback (QSPI_HandleTypeDef *hqspi); /* QSPI memory-mapped mode */ void HAL_QSPI_TimeOutCallback (QSPI_HandleTypeDef *hqspi); /** * @} */ /** @addtogroup QSPI_Exported_Functions_Group4 * @{ */ /* Peripheral Control and State functions ************************************/ HAL_QSPI_StateTypeDef HAL_QSPI_GetState(QSPI_HandleTypeDef *hqspi); uint32_t HAL_QSPI_GetError(QSPI_HandleTypeDef *hqspi); HAL_StatusTypeDef HAL_QSPI_Abort (QSPI_HandleTypeDef *hqspi); void HAL_QSPI_SetTimeout(QSPI_HandleTypeDef *hqspi, uint32_t Timeout); /** * @} */ /** * @} */ /* Private types -------------------------------------------------------------*/ /* Private variables ---------------------------------------------------------*/ /* Private constants ---------------------------------------------------------*/ /** @defgroup QSPI_Private_Constants QSPI Private Constants * @{ */ /** * @} */ /* Private macros ------------------------------------------------------------*/ /** @defgroup QSPI_Private_Macros QSPI Private Macros * @{ */ /** @defgroup QSPI_ClockPrescaler QSPI Clock Prescaler * @{ */ #define IS_QSPI_CLOCK_PRESCALER(PRESCALER) ((PRESCALER) <= 0xFF) /** * @} */ /** @defgroup QSPI_FifoThreshold QSPI Fifo Threshold * @{ */ #define IS_QSPI_FIFO_THRESHOLD(THR) (((THR) > 0) && ((THR) <= 32)) /** * @} */ #define IS_QSPI_SSHIFT(SSHIFT) (((SSHIFT) == QSPI_SAMPLE_SHIFTING_NONE) || \ ((SSHIFT) == QSPI_SAMPLE_SHIFTING_HALFCYCLE)) /** @defgroup QSPI_FlashSize QSPI Flash Size * @{ */ #define IS_QSPI_FLASH_SIZE(FSIZE) (((FSIZE) <= 31)) /** * @} */ #define IS_QSPI_CS_HIGH_TIME(CSHTIME) (((CSHTIME) == QSPI_CS_HIGH_TIME_1_CYCLE) || \ ((CSHTIME) == QSPI_CS_HIGH_TIME_2_CYCLE) || \ ((CSHTIME) == QSPI_CS_HIGH_TIME_3_CYCLE) || \ ((CSHTIME) == QSPI_CS_HIGH_TIME_4_CYCLE) || \ ((CSHTIME) == QSPI_CS_HIGH_TIME_5_CYCLE) || \ ((CSHTIME) == QSPI_CS_HIGH_TIME_6_CYCLE) || \ ((CSHTIME) == QSPI_CS_HIGH_TIME_7_CYCLE) || \ ((CSHTIME) == QSPI_CS_HIGH_TIME_8_CYCLE)) #define IS_QSPI_CLOCK_MODE(CLKMODE) (((CLKMODE) == QSPI_CLOCK_MODE_0) || \ ((CLKMODE) == QSPI_CLOCK_MODE_3)) #define IS_QSPI_FLASH_ID(FLA) (((FLA) == QSPI_FLASH_ID_1) || \ ((FLA) == QSPI_FLASH_ID_2)) #define IS_QSPI_DUAL_FLASH_MODE(MODE) (((MODE) == QSPI_DUALFLASH_ENABLE) || \ ((MODE) == QSPI_DUALFLASH_DISABLE)) /** @defgroup QSPI_Instruction QSPI Instruction * @{ */ #define IS_QSPI_INSTRUCTION(INSTRUCTION) ((INSTRUCTION) <= 0xFF) /** * @} */ #define IS_QSPI_ADDRESS_SIZE(ADDR_SIZE) (((ADDR_SIZE) == QSPI_ADDRESS_8_BITS) || \ ((ADDR_SIZE) == QSPI_ADDRESS_16_BITS) || \ ((ADDR_SIZE) == QSPI_ADDRESS_24_BITS) || \ ((ADDR_SIZE) == QSPI_ADDRESS_32_BITS)) #define IS_QSPI_ALTERNATE_BYTES_SIZE(SIZE) (((SIZE) == QSPI_ALTERNATE_BYTES_8_BITS) || \ ((SIZE) == QSPI_ALTERNATE_BYTES_16_BITS) || \ ((SIZE) == QSPI_ALTERNATE_BYTES_24_BITS) || \ ((SIZE) == QSPI_ALTERNATE_BYTES_32_BITS)) /** @defgroup QSPI_DummyCycles QSPI Dummy Cycles * @{ */ #define IS_QSPI_DUMMY_CYCLES(DCY) ((DCY) <= 31) /** * @} */ #define IS_QSPI_INSTRUCTION_MODE(MODE) (((MODE) == QSPI_INSTRUCTION_NONE) || \ ((MODE) == QSPI_INSTRUCTION_1_LINE) || \ ((MODE) == QSPI_INSTRUCTION_2_LINES) || \ ((MODE) == QSPI_INSTRUCTION_4_LINES)) #define IS_QSPI_ADDRESS_MODE(MODE) (((MODE) == QSPI_ADDRESS_NONE) || \ ((MODE) == QSPI_ADDRESS_1_LINE) || \ ((MODE) == QSPI_ADDRESS_2_LINES) || \ ((MODE) == QSPI_ADDRESS_4_LINES)) #define IS_QSPI_ALTERNATE_BYTES_MODE(MODE) (((MODE) == QSPI_ALTERNATE_BYTES_NONE) || \ ((MODE) == QSPI_ALTERNATE_BYTES_1_LINE) || \ ((MODE) == QSPI_ALTERNATE_BYTES_2_LINES) || \ ((MODE) == QSPI_ALTERNATE_BYTES_4_LINES)) #define IS_QSPI_DATA_MODE(MODE) (((MODE) == QSPI_DATA_NONE) || \ ((MODE) == QSPI_DATA_1_LINE) || \ ((MODE) == QSPI_DATA_2_LINES) || \ ((MODE) == QSPI_DATA_4_LINES)) #define IS_QSPI_DDR_MODE(DDR_MODE) (((DDR_MODE) == QSPI_DDR_MODE_DISABLE) || \ ((DDR_MODE) == QSPI_DDR_MODE_ENABLE)) #define IS_QSPI_DDR_HHC(DDR_HHC) (((DDR_HHC) == QSPI_DDR_HHC_ANALOG_DELAY) || \ ((DDR_HHC) == QSPI_DDR_HHC_HALF_CLK_DELAY)) #define IS_QSPI_SIOO_MODE(SIOO_MODE) (((SIOO_MODE) == QSPI_SIOO_INST_EVERY_CMD) || \ ((SIOO_MODE) == QSPI_SIOO_INST_ONLY_FIRST_CMD)) /** @defgroup QSPI_Interval QSPI Interval * @{ */ #define IS_QSPI_INTERVAL(INTERVAL) ((INTERVAL) <= QUADSPI_PIR_INTERVAL) /** * @} */ /** @defgroup QSPI_StatusBytesSize QSPI Status Bytes Size * @{ */ #define IS_QSPI_STATUS_BYTES_SIZE(SIZE) (((SIZE) >= 1) && ((SIZE) <= 4)) /** * @} */ #define IS_QSPI_MATCH_MODE(MODE) (((MODE) == QSPI_MATCH_MODE_AND) || \ ((MODE) == QSPI_MATCH_MODE_OR)) #define IS_QSPI_AUTOMATIC_STOP(APMS) (((APMS) == QSPI_AUTOMATIC_STOP_DISABLE) || \ ((APMS) == QSPI_AUTOMATIC_STOP_ENABLE)) #define IS_QSPI_TIMEOUT_ACTIVATION(TCEN) (((TCEN) == QSPI_TIMEOUT_COUNTER_DISABLE) || \ ((TCEN) == QSPI_TIMEOUT_COUNTER_ENABLE)) /** @defgroup QSPI_TimeOutPeriod QSPI TimeOut Period * @{ */ #define IS_QSPI_TIMEOUT_PERIOD(PERIOD) ((PERIOD) <= 0xFFFF) /** * @} */ #define IS_QSPI_GET_FLAG(FLAG) (((FLAG) == QSPI_FLAG_BUSY) || \ ((FLAG) == QSPI_FLAG_TO) || \ ((FLAG) == QSPI_FLAG_SM) || \ ((FLAG) == QSPI_FLAG_FT) || \ ((FLAG) == QSPI_FLAG_TC) || \ ((FLAG) == QSPI_FLAG_TE)) #define IS_QSPI_IT(IT) ((((IT) & (uint32_t)0xFFE0FFFF) == 0x00000000) && ((IT) != 0x00000000)) /** * @} */ /* Private functions ---------------------------------------------------------*/ /** @defgroup QSPI_Private_Functions QSPI Private Functions * @{ */ /** * @} */ /** * @} */ /** * @} */ #endif /* STM32F446xx || STM32F469xx || STM32F479xx */ #ifdef __cplusplus } #endif #endif /* __STM32F4xx_HAL_QSPI_H */ /************************ (C) COPYRIGHT STMicroelectronics *****END OF FILE****/ ================================================ FILE: Zelig/mbed/TARGET_NUCLEO_F401RE/stm32f4xx_hal_rcc.h ================================================ /** ****************************************************************************** * @file stm32f4xx_hal_rcc.h * @author MCD Application Team * @version V1.4.1 * @date 09-October-2015 * @brief Header file of RCC HAL module. ****************************************************************************** * @attention * *

© COPYRIGHT(c) 2015 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. * ****************************************************************************** */ /* Define to prevent recursive inclusion -------------------------------------*/ #ifndef __STM32F4xx_HAL_RCC_H #define __STM32F4xx_HAL_RCC_H #ifdef __cplusplus extern "C" { #endif /* Includes ------------------------------------------------------------------*/ #include "stm32f4xx_hal_def.h" /* Include RCC HAL Extended module */ /* (include on top of file since RCC structures are defined in extended file) */ #include "stm32f4xx_hal_rcc_ex.h" /** @addtogroup STM32F4xx_HAL_Driver * @{ */ /** @addtogroup RCC * @{ */ /* Exported types ------------------------------------------------------------*/ /** @defgroup RCC_Exported_Types RCC Exported Types * @{ */ /** * @brief RCC Internal/External Oscillator (HSE, HSI, LSE and LSI) configuration structure definition */ typedef struct { uint32_t OscillatorType; /*!< The oscillators to be configured. This parameter can be a value of @ref RCC_Oscillator_Type */ uint32_t HSEState; /*!< The new state of the HSE. This parameter can be a value of @ref RCC_HSE_Config */ uint32_t LSEState; /*!< The new state of the LSE. This parameter can be a value of @ref RCC_LSE_Config */ uint32_t HSIState; /*!< The new state of the HSI. This parameter can be a value of @ref RCC_HSI_Config */ uint32_t HSICalibrationValue; /*!< The calibration trimming value. This parameter must be a number between Min_Data = 0x00 and Max_Data = 0x1F */ uint32_t LSIState; /*!< The new state of the LSI. This parameter can be a value of @ref RCC_LSI_Config */ RCC_PLLInitTypeDef PLL; /*!< PLL structure parameters */ }RCC_OscInitTypeDef; /** * @brief RCC System, AHB and APB busses clock configuration structure definition */ typedef struct { uint32_t ClockType; /*!< The clock to be configured. This parameter can be a value of @ref RCC_System_Clock_Type */ uint32_t SYSCLKSource; /*!< The clock source (SYSCLKS) used as system clock. This parameter can be a value of @ref RCC_System_Clock_Source */ uint32_t AHBCLKDivider; /*!< The AHB clock (HCLK) divider. This clock is derived from the system clock (SYSCLK). This parameter can be a value of @ref RCC_AHB_Clock_Source */ uint32_t APB1CLKDivider; /*!< The APB1 clock (PCLK1) divider. This clock is derived from the AHB clock (HCLK). This parameter can be a value of @ref RCC_APB1_APB2_Clock_Source */ uint32_t APB2CLKDivider; /*!< The APB2 clock (PCLK2) divider. This clock is derived from the AHB clock (HCLK). This parameter can be a value of @ref RCC_APB1_APB2_Clock_Source */ }RCC_ClkInitTypeDef; /** * @} */ /* Exported constants --------------------------------------------------------*/ /** @defgroup RCC_Exported_Constants RCC Exported Constants * @{ */ /** @defgroup RCC_Oscillator_Type Oscillator Type * @{ */ #define RCC_OSCILLATORTYPE_NONE ((uint32_t)0x00000000) #define RCC_OSCILLATORTYPE_HSE ((uint32_t)0x00000001) #define RCC_OSCILLATORTYPE_HSI ((uint32_t)0x00000002) #define RCC_OSCILLATORTYPE_LSE ((uint32_t)0x00000004) #define RCC_OSCILLATORTYPE_LSI ((uint32_t)0x00000008) /** * @} */ /** @defgroup RCC_HSE_Config HSE Config * @{ */ #define RCC_HSE_OFF ((uint8_t)0x00) #define RCC_HSE_ON ((uint8_t)0x01) #define RCC_HSE_BYPASS ((uint8_t)0x05) /** * @} */ /** @defgroup RCC_LSE_Config LSE Config * @{ */ #define RCC_LSE_OFF ((uint8_t)0x00) #define RCC_LSE_ON ((uint8_t)0x01) #define RCC_LSE_BYPASS ((uint8_t)0x05) /** * @} */ /** @defgroup RCC_HSI_Config HSI Config * @{ */ #define RCC_HSI_OFF ((uint8_t)0x00) #define RCC_HSI_ON ((uint8_t)0x01) /** * @} */ /** @defgroup RCC_LSI_Config LSI Config * @{ */ #define RCC_LSI_OFF ((uint8_t)0x00) #define RCC_LSI_ON ((uint8_t)0x01) /** * @} */ /** @defgroup RCC_PLL_Config PLL Config * @{ */ #define RCC_PLL_NONE ((uint8_t)0x00) #define RCC_PLL_OFF ((uint8_t)0x01) #define RCC_PLL_ON ((uint8_t)0x02) /** * @} */ /** @defgroup RCC_PLLP_Clock_Divider PLLP Clock Divider * @{ */ #define RCC_PLLP_DIV2 ((uint32_t)0x00000002) #define RCC_PLLP_DIV4 ((uint32_t)0x00000004) #define RCC_PLLP_DIV6 ((uint32_t)0x00000006) #define RCC_PLLP_DIV8 ((uint32_t)0x00000008) /** * @} */ /** @defgroup RCC_PLL_Clock_Source PLL Clock Source * @{ */ #define RCC_PLLSOURCE_HSI RCC_PLLCFGR_PLLSRC_HSI #define RCC_PLLSOURCE_HSE RCC_PLLCFGR_PLLSRC_HSE /** * @} */ /** @defgroup RCC_System_Clock_Type System Clock Type * @{ */ #define RCC_CLOCKTYPE_SYSCLK ((uint32_t)0x00000001) #define RCC_CLOCKTYPE_HCLK ((uint32_t)0x00000002) #define RCC_CLOCKTYPE_PCLK1 ((uint32_t)0x00000004) #define RCC_CLOCKTYPE_PCLK2 ((uint32_t)0x00000008) /** * @} */ /** @defgroup RCC_System_Clock_Source System Clock Source * @{ */ #define RCC_SYSCLKSOURCE_HSI RCC_CFGR_SW_HSI #define RCC_SYSCLKSOURCE_HSE RCC_CFGR_SW_HSE #define RCC_SYSCLKSOURCE_PLLCLK RCC_CFGR_SW_PLL #define RCC_SYSCLKSOURCE_PLLRCLK ((uint32_t)(RCC_CFGR_SW_0 | RCC_CFGR_SW_1)) /** * @} */ /** @defgroup RCC_System_Clock_Source_Status System Clock Source Status * @{ */ #define RCC_SYSCLKSOURCE_STATUS_HSI RCC_CFGR_SWS_HSI /*!< HSI used as system clock */ #define RCC_SYSCLKSOURCE_STATUS_HSE RCC_CFGR_SWS_HSE /*!< HSE used as system clock */ #define RCC_SYSCLKSOURCE_STATUS_PLLCLK RCC_CFGR_SWS_PLL /*!< PLL used as system clock */ #define RCC_SYSCLKSOURCE_STATUS_PLLRCLK ((uint32_t)(RCC_CFGR_SW_0 | RCC_CFGR_SW_1)) /*!< PLLR used as system clock */ /** * @} */ /** @defgroup RCC_AHB_Clock_Source AHB Clock Source * @{ */ #define RCC_SYSCLK_DIV1 RCC_CFGR_HPRE_DIV1 #define RCC_SYSCLK_DIV2 RCC_CFGR_HPRE_DIV2 #define RCC_SYSCLK_DIV4 RCC_CFGR_HPRE_DIV4 #define RCC_SYSCLK_DIV8 RCC_CFGR_HPRE_DIV8 #define RCC_SYSCLK_DIV16 RCC_CFGR_HPRE_DIV16 #define RCC_SYSCLK_DIV64 RCC_CFGR_HPRE_DIV64 #define RCC_SYSCLK_DIV128 RCC_CFGR_HPRE_DIV128 #define RCC_SYSCLK_DIV256 RCC_CFGR_HPRE_DIV256 #define RCC_SYSCLK_DIV512 RCC_CFGR_HPRE_DIV512 /** * @} */ /** @defgroup RCC_APB1_APB2_Clock_Source APB1/APB2 Clock Source * @{ */ #define RCC_HCLK_DIV1 RCC_CFGR_PPRE1_DIV1 #define RCC_HCLK_DIV2 RCC_CFGR_PPRE1_DIV2 #define RCC_HCLK_DIV4 RCC_CFGR_PPRE1_DIV4 #define RCC_HCLK_DIV8 RCC_CFGR_PPRE1_DIV8 #define RCC_HCLK_DIV16 RCC_CFGR_PPRE1_DIV16 /** * @} */ /** @defgroup RCC_RTC_Clock_Source RTC Clock Source * @{ */ #define RCC_RTCCLKSOURCE_LSE ((uint32_t)0x00000100) #define RCC_RTCCLKSOURCE_LSI ((uint32_t)0x00000200) #define RCC_RTCCLKSOURCE_HSE_DIV2 ((uint32_t)0x00020300) #define RCC_RTCCLKSOURCE_HSE_DIV3 ((uint32_t)0x00030300) #define RCC_RTCCLKSOURCE_HSE_DIV4 ((uint32_t)0x00040300) #define RCC_RTCCLKSOURCE_HSE_DIV5 ((uint32_t)0x00050300) #define RCC_RTCCLKSOURCE_HSE_DIV6 ((uint32_t)0x00060300) #define RCC_RTCCLKSOURCE_HSE_DIV7 ((uint32_t)0x00070300) #define RCC_RTCCLKSOURCE_HSE_DIV8 ((uint32_t)0x00080300) #define RCC_RTCCLKSOURCE_HSE_DIV9 ((uint32_t)0x00090300) #define RCC_RTCCLKSOURCE_HSE_DIV10 ((uint32_t)0x000A0300) #define RCC_RTCCLKSOURCE_HSE_DIV11 ((uint32_t)0x000B0300) #define RCC_RTCCLKSOURCE_HSE_DIV12 ((uint32_t)0x000C0300) #define RCC_RTCCLKSOURCE_HSE_DIV13 ((uint32_t)0x000D0300) #define RCC_RTCCLKSOURCE_HSE_DIV14 ((uint32_t)0x000E0300) #define RCC_RTCCLKSOURCE_HSE_DIV15 ((uint32_t)0x000F0300) #define RCC_RTCCLKSOURCE_HSE_DIV16 ((uint32_t)0x00100300) #define RCC_RTCCLKSOURCE_HSE_DIV17 ((uint32_t)0x00110300) #define RCC_RTCCLKSOURCE_HSE_DIV18 ((uint32_t)0x00120300) #define RCC_RTCCLKSOURCE_HSE_DIV19 ((uint32_t)0x00130300) #define RCC_RTCCLKSOURCE_HSE_DIV20 ((uint32_t)0x00140300) #define RCC_RTCCLKSOURCE_HSE_DIV21 ((uint32_t)0x00150300) #define RCC_RTCCLKSOURCE_HSE_DIV22 ((uint32_t)0x00160300) #define RCC_RTCCLKSOURCE_HSE_DIV23 ((uint32_t)0x00170300) #define RCC_RTCCLKSOURCE_HSE_DIV24 ((uint32_t)0x00180300) #define RCC_RTCCLKSOURCE_HSE_DIV25 ((uint32_t)0x00190300) #define RCC_RTCCLKSOURCE_HSE_DIV26 ((uint32_t)0x001A0300) #define RCC_RTCCLKSOURCE_HSE_DIV27 ((uint32_t)0x001B0300) #define RCC_RTCCLKSOURCE_HSE_DIV28 ((uint32_t)0x001C0300) #define RCC_RTCCLKSOURCE_HSE_DIV29 ((uint32_t)0x001D0300) #define RCC_RTCCLKSOURCE_HSE_DIV30 ((uint32_t)0x001E0300) #define RCC_RTCCLKSOURCE_HSE_DIV31 ((uint32_t)0x001F0300) /** * @} */ /** @defgroup RCC_MCO_Index MCO Index * @{ */ #define RCC_MCO1 ((uint32_t)0x00000000) #define RCC_MCO2 ((uint32_t)0x00000001) /** * @} */ /** @defgroup RCC_MCO1_Clock_Source MCO1 Clock Source * @{ */ #define RCC_MCO1SOURCE_HSI ((uint32_t)0x00000000) #define RCC_MCO1SOURCE_LSE RCC_CFGR_MCO1_0 #define RCC_MCO1SOURCE_HSE RCC_CFGR_MCO1_1 #define RCC_MCO1SOURCE_PLLCLK RCC_CFGR_MCO1 /** * @} */ /** @defgroup RCC_MCOx_Clock_Prescaler MCOx Clock Prescaler * @{ */ #define RCC_MCODIV_1 ((uint32_t)0x00000000) #define RCC_MCODIV_2 RCC_CFGR_MCO1PRE_2 #define RCC_MCODIV_3 ((uint32_t)RCC_CFGR_MCO1PRE_0 | RCC_CFGR_MCO1PRE_2) #define RCC_MCODIV_4 ((uint32_t)RCC_CFGR_MCO1PRE_1 | RCC_CFGR_MCO1PRE_2) #define RCC_MCODIV_5 RCC_CFGR_MCO1PRE /** * @} */ /** @defgroup RCC_Interrupt Interrupts * @{ */ #define RCC_IT_LSIRDY ((uint8_t)0x01) #define RCC_IT_LSERDY ((uint8_t)0x02) #define RCC_IT_HSIRDY ((uint8_t)0x04) #define RCC_IT_HSERDY ((uint8_t)0x08) #define RCC_IT_PLLRDY ((uint8_t)0x10) #define RCC_IT_PLLI2SRDY ((uint8_t)0x20) #define RCC_IT_CSS ((uint8_t)0x80) /** * @} */ /** @defgroup RCC_Flag Flags * Elements values convention: 0XXYYYYYb * - YYYYY : Flag position in the register * - 0XX : Register index * - 01: CR register * - 10: BDCR register * - 11: CSR register * @{ */ /* Flags in the CR register */ #define RCC_FLAG_HSIRDY ((uint8_t)0x21) #define RCC_FLAG_HSERDY ((uint8_t)0x31) #define RCC_FLAG_PLLRDY ((uint8_t)0x39) #define RCC_FLAG_PLLI2SRDY ((uint8_t)0x3B) /* Flags in the BDCR register */ #define RCC_FLAG_LSERDY ((uint8_t)0x41) /* Flags in the CSR register */ #define RCC_FLAG_LSIRDY ((uint8_t)0x61) #define RCC_FLAG_BORRST ((uint8_t)0x79) #define RCC_FLAG_PINRST ((uint8_t)0x7A) #define RCC_FLAG_PORRST ((uint8_t)0x7B) #define RCC_FLAG_SFTRST ((uint8_t)0x7C) #define RCC_FLAG_IWDGRST ((uint8_t)0x7D) #define RCC_FLAG_WWDGRST ((uint8_t)0x7E) #define RCC_FLAG_LPWRRST ((uint8_t)0x7F) /** * @} */ /** * @} */ /* Exported macro ------------------------------------------------------------*/ /** @defgroup RCC_Exported_Macros RCC Exported Macros * @{ */ /** @defgroup RCC_AHB1_Clock_Enable_Disable AHB1 Peripheral Clock Enable Disable * @brief Enable or disable the AHB1 peripheral clock. * @note After reset, the peripheral clock (used for registers read/write access) * is disabled and the application software has to enable this clock before * using it. * @{ */ #define __HAL_RCC_GPIOA_CLK_ENABLE() do { \ __IO uint32_t tmpreg; \ SET_BIT(RCC->AHB1ENR, RCC_AHB1ENR_GPIOAEN);\ /* Delay after an RCC peripheral clock enabling */ \ tmpreg = READ_BIT(RCC->AHB1ENR, RCC_AHB1ENR_GPIOAEN);\ UNUSED(tmpreg); \ } while(0) #define __HAL_RCC_GPIOB_CLK_ENABLE() do { \ __IO uint32_t tmpreg; \ SET_BIT(RCC->AHB1ENR, RCC_AHB1ENR_GPIOBEN);\ /* Delay after an RCC peripheral clock enabling */ \ tmpreg = READ_BIT(RCC->AHB1ENR, RCC_AHB1ENR_GPIOBEN);\ UNUSED(tmpreg); \ } while(0) #define __HAL_RCC_GPIOC_CLK_ENABLE() do { \ __IO uint32_t tmpreg; \ SET_BIT(RCC->AHB1ENR, RCC_AHB1ENR_GPIOCEN);\ /* Delay after an RCC peripheral clock enabling */ \ tmpreg = READ_BIT(RCC->AHB1ENR, RCC_AHB1ENR_GPIOCEN);\ UNUSED(tmpreg); \ } while(0) #define __HAL_RCC_GPIOH_CLK_ENABLE() do { \ __IO uint32_t tmpreg; \ SET_BIT(RCC->AHB1ENR, RCC_AHB1ENR_GPIOHEN);\ /* Delay after an RCC peripheral clock enabling */ \ tmpreg = READ_BIT(RCC->AHB1ENR, RCC_AHB1ENR_GPIOHEN);\ UNUSED(tmpreg); \ } while(0) #define __HAL_RCC_DMA1_CLK_ENABLE() do { \ __IO uint32_t tmpreg; \ SET_BIT(RCC->AHB1ENR, RCC_AHB1ENR_DMA1EN);\ /* Delay after an RCC peripheral clock enabling */ \ tmpreg = READ_BIT(RCC->AHB1ENR, RCC_AHB1ENR_DMA1EN);\ UNUSED(tmpreg); \ } while(0) #define __HAL_RCC_DMA2_CLK_ENABLE() do { \ __IO uint32_t tmpreg; \ SET_BIT(RCC->AHB1ENR, RCC_AHB1ENR_DMA2EN);\ /* Delay after an RCC peripheral clock enabling */ \ tmpreg = READ_BIT(RCC->AHB1ENR, RCC_AHB1ENR_DMA2EN);\ UNUSED(tmpreg); \ } while(0) #define __HAL_RCC_GPIOA_CLK_DISABLE() (RCC->AHB1ENR &= ~(RCC_AHB1ENR_GPIOAEN)) #define __HAL_RCC_GPIOB_CLK_DISABLE() (RCC->AHB1ENR &= ~(RCC_AHB1ENR_GPIOBEN)) #define __HAL_RCC_GPIOC_CLK_DISABLE() (RCC->AHB1ENR &= ~(RCC_AHB1ENR_GPIOCEN)) #define __HAL_RCC_GPIOH_CLK_DISABLE() (RCC->AHB1ENR &= ~(RCC_AHB1ENR_GPIOHEN)) #define __HAL_RCC_DMA1_CLK_DISABLE() (RCC->AHB1ENR &= ~(RCC_AHB1ENR_DMA1EN)) #define __HAL_RCC_DMA2_CLK_DISABLE() (RCC->AHB1ENR &= ~(RCC_AHB1ENR_DMA2EN)) /** * @} */ /** @defgroup RCC_APB1_Clock_Enable_Disable APB1 Peripheral Clock Enable Disable * @brief Enable or disable the Low Speed APB (APB1) peripheral clock. * @note After reset, the peripheral clock (used for registers read/write access) * is disabled and the application software has to enable this clock before * using it. * @{ */ #define __HAL_RCC_TIM5_CLK_ENABLE() do { \ __IO uint32_t tmpreg; \ SET_BIT(RCC->APB1ENR, RCC_APB1ENR_TIM5EN);\ /* Delay after an RCC peripheral clock enabling */ \ tmpreg = READ_BIT(RCC->APB1ENR, RCC_APB1ENR_TIM5EN);\ UNUSED(tmpreg); \ } while(0) #define __HAL_RCC_WWDG_CLK_ENABLE() do { \ __IO uint32_t tmpreg; \ SET_BIT(RCC->APB1ENR, RCC_APB1ENR_WWDGEN);\ /* Delay after an RCC peripheral clock enabling */ \ tmpreg = READ_BIT(RCC->APB1ENR, RCC_APB1ENR_WWDGEN);\ UNUSED(tmpreg); \ } while(0) #define __HAL_RCC_SPI2_CLK_ENABLE() do { \ __IO uint32_t tmpreg; \ SET_BIT(RCC->APB1ENR, RCC_APB1ENR_SPI2EN);\ /* Delay after an RCC peripheral clock enabling */ \ tmpreg = READ_BIT(RCC->APB1ENR, RCC_APB1ENR_SPI2EN);\ UNUSED(tmpreg); \ } while(0) #define __HAL_RCC_USART2_CLK_ENABLE() do { \ __IO uint32_t tmpreg; \ SET_BIT(RCC->APB1ENR, RCC_APB1ENR_USART2EN);\ /* Delay after an RCC peripheral clock enabling */ \ tmpreg = READ_BIT(RCC->APB1ENR, RCC_APB1ENR_USART2EN);\ UNUSED(tmpreg); \ } while(0) #define __HAL_RCC_I2C1_CLK_ENABLE() do { \ __IO uint32_t tmpreg; \ SET_BIT(RCC->APB1ENR, RCC_APB1ENR_I2C1EN);\ /* Delay after an RCC peripheral clock enabling */ \ tmpreg = READ_BIT(RCC->APB1ENR, RCC_APB1ENR_I2C1EN);\ UNUSED(tmpreg); \ } while(0) #define __HAL_RCC_I2C2_CLK_ENABLE() do { \ __IO uint32_t tmpreg; \ SET_BIT(RCC->APB1ENR, RCC_APB1ENR_I2C2EN);\ /* Delay after an RCC peripheral clock enabling */ \ tmpreg = READ_BIT(RCC->APB1ENR, RCC_APB1ENR_I2C2EN);\ UNUSED(tmpreg); \ } while(0) #define __HAL_RCC_PWR_CLK_ENABLE() do { \ __IO uint32_t tmpreg; \ SET_BIT(RCC->APB1ENR, RCC_APB1ENR_PWREN);\ /* Delay after an RCC peripheral clock enabling */ \ tmpreg = READ_BIT(RCC->APB1ENR, RCC_APB1ENR_PWREN);\ UNUSED(tmpreg); \ } while(0) #define __HAL_RCC_TIM5_CLK_DISABLE() (RCC->APB1ENR &= ~(RCC_APB1ENR_TIM5EN)) #define __HAL_RCC_WWDG_CLK_DISABLE() (RCC->APB1ENR &= ~(RCC_APB1ENR_WWDGEN)) #define __HAL_RCC_SPI2_CLK_DISABLE() (RCC->APB1ENR &= ~(RCC_APB1ENR_SPI2EN)) #define __HAL_RCC_USART2_CLK_DISABLE() (RCC->APB1ENR &= ~(RCC_APB1ENR_USART2EN)) #define __HAL_RCC_I2C1_CLK_DISABLE() (RCC->APB1ENR &= ~(RCC_APB1ENR_I2C1EN)) #define __HAL_RCC_I2C2_CLK_DISABLE() (RCC->APB1ENR &= ~(RCC_APB1ENR_I2C2EN)) #define __HAL_RCC_PWR_CLK_DISABLE() (RCC->APB1ENR &= ~(RCC_APB1ENR_PWREN)) /** * @} */ /** @defgroup RCC_APB2_Clock_Enable_Disable APB2 Peripheral Clock Enable Disable * @brief Enable or disable the High Speed APB (APB2) peripheral clock. * @note After reset, the peripheral clock (used for registers read/write access) * is disabled and the application software has to enable this clock before * using it. * @{ */ #define __HAL_RCC_TIM1_CLK_ENABLE() do { \ __IO uint32_t tmpreg; \ SET_BIT(RCC->APB2ENR, RCC_APB2ENR_TIM1EN);\ /* Delay after an RCC peripheral clock enabling */ \ tmpreg = READ_BIT(RCC->APB2ENR, RCC_APB2ENR_TIM1EN);\ UNUSED(tmpreg); \ } while(0) #define __HAL_RCC_USART1_CLK_ENABLE() do { \ __IO uint32_t tmpreg; \ SET_BIT(RCC->APB2ENR, RCC_APB2ENR_USART1EN);\ /* Delay after an RCC peripheral clock enabling */ \ tmpreg = READ_BIT(RCC->APB2ENR, RCC_APB2ENR_USART1EN);\ UNUSED(tmpreg); \ } while(0) #define __HAL_RCC_USART6_CLK_ENABLE() do { \ __IO uint32_t tmpreg; \ SET_BIT(RCC->APB2ENR, RCC_APB2ENR_USART6EN);\ /* Delay after an RCC peripheral clock enabling */ \ tmpreg = READ_BIT(RCC->APB2ENR, RCC_APB2ENR_USART6EN);\ UNUSED(tmpreg); \ } while(0) #define __HAL_RCC_ADC1_CLK_ENABLE() do { \ __IO uint32_t tmpreg; \ SET_BIT(RCC->APB2ENR, RCC_APB2ENR_ADC1EN);\ /* Delay after an RCC peripheral clock enabling */ \ tmpreg = READ_BIT(RCC->APB2ENR, RCC_APB2ENR_ADC1EN);\ UNUSED(tmpreg); \ } while(0) #define __HAL_RCC_SPI1_CLK_ENABLE() do { \ __IO uint32_t tmpreg; \ SET_BIT(RCC->APB2ENR, RCC_APB2ENR_SPI1EN);\ /* Delay after an RCC peripheral clock enabling */ \ tmpreg = READ_BIT(RCC->APB2ENR, RCC_APB2ENR_SPI1EN);\ UNUSED(tmpreg); \ } while(0) #define __HAL_RCC_SYSCFG_CLK_ENABLE() do { \ __IO uint32_t tmpreg; \ SET_BIT(RCC->APB2ENR, RCC_APB2ENR_SYSCFGEN);\ /* Delay after an RCC peripheral clock enabling */ \ tmpreg = READ_BIT(RCC->APB2ENR, RCC_APB2ENR_SYSCFGEN);\ UNUSED(tmpreg); \ } while(0) #define __HAL_RCC_TIM9_CLK_ENABLE() do { \ __IO uint32_t tmpreg; \ SET_BIT(RCC->APB2ENR, RCC_APB2ENR_TIM9EN);\ /* Delay after an RCC peripheral clock enabling */ \ tmpreg = READ_BIT(RCC->APB2ENR, RCC_APB2ENR_TIM9EN);\ UNUSED(tmpreg); \ } while(0) #define __HAL_RCC_TIM11_CLK_ENABLE() do { \ __IO uint32_t tmpreg; \ SET_BIT(RCC->APB2ENR, RCC_APB2ENR_TIM11EN);\ /* Delay after an RCC peripheral clock enabling */ \ tmpreg = READ_BIT(RCC->APB2ENR, RCC_APB2ENR_TIM11EN);\ UNUSED(tmpreg); \ } while(0) #define __HAL_RCC_TIM1_CLK_DISABLE() (RCC->APB2ENR &= ~(RCC_APB2ENR_TIM1EN)) #define __HAL_RCC_USART1_CLK_DISABLE() (RCC->APB2ENR &= ~(RCC_APB2ENR_USART1EN)) #define __HAL_RCC_USART6_CLK_DISABLE() (RCC->APB2ENR &= ~(RCC_APB2ENR_USART6EN)) #define __HAL_RCC_ADC1_CLK_DISABLE() (RCC->APB2ENR &= ~(RCC_APB2ENR_ADC1EN)) #define __HAL_RCC_SPI1_CLK_DISABLE() (RCC->APB2ENR &= ~(RCC_APB2ENR_SPI1EN)) #define __HAL_RCC_SYSCFG_CLK_DISABLE() (RCC->APB2ENR &= ~(RCC_APB2ENR_SYSCFGEN)) #define __HAL_RCC_TIM9_CLK_DISABLE() (RCC->APB2ENR &= ~(RCC_APB2ENR_TIM9EN)) #define __HAL_RCC_TIM11_CLK_DISABLE() (RCC->APB2ENR &= ~(RCC_APB2ENR_TIM11EN)) /** * @} */ /** @defgroup RCC_AHB1_Force_Release_Reset AHB1 Force Release Reset * @brief Force or release AHB1 peripheral reset. * @{ */ #define __HAL_RCC_AHB1_FORCE_RESET() (RCC->AHB1RSTR = 0xFFFFFFFF) #define __HAL_RCC_GPIOA_FORCE_RESET() (RCC->AHB1RSTR |= (RCC_AHB1RSTR_GPIOARST)) #define __HAL_RCC_GPIOB_FORCE_RESET() (RCC->AHB1RSTR |= (RCC_AHB1RSTR_GPIOBRST)) #define __HAL_RCC_GPIOC_FORCE_RESET() (RCC->AHB1RSTR |= (RCC_AHB1RSTR_GPIOCRST)) #define __HAL_RCC_GPIOH_FORCE_RESET() (RCC->AHB1RSTR |= (RCC_AHB1RSTR_GPIOHRST)) #define __HAL_RCC_DMA1_FORCE_RESET() (RCC->AHB1RSTR |= (RCC_AHB1RSTR_DMA1RST)) #define __HAL_RCC_DMA2_FORCE_RESET() (RCC->AHB1RSTR |= (RCC_AHB1RSTR_DMA2RST)) #define __HAL_RCC_AHB1_RELEASE_RESET() (RCC->AHB1RSTR = 0x00) #define __HAL_RCC_GPIOA_RELEASE_RESET() (RCC->AHB1RSTR &= ~(RCC_AHB1RSTR_GPIOARST)) #define __HAL_RCC_GPIOB_RELEASE_RESET() (RCC->AHB1RSTR &= ~(RCC_AHB1RSTR_GPIOBRST)) #define __HAL_RCC_GPIOC_RELEASE_RESET() (RCC->AHB1RSTR &= ~(RCC_AHB1RSTR_GPIOCRST)) #define __HAL_RCC_GPIOH_RELEASE_RESET() (RCC->AHB1RSTR &= ~(RCC_AHB1RSTR_GPIOHRST)) #define __HAL_RCC_DMA1_RELEASE_RESET() (RCC->AHB1RSTR &= ~(RCC_AHB1RSTR_DMA1RST)) #define __HAL_RCC_DMA2_RELEASE_RESET() (RCC->AHB1RSTR &= ~(RCC_AHB1RSTR_DMA2RST)) /** * @} */ /** @defgroup RCC_APB1_Force_Release_Reset APB1 Force Release Reset * @brief Force or release APB1 peripheral reset. * @{ */ #define __HAL_RCC_APB1_FORCE_RESET() (RCC->APB1RSTR = 0xFFFFFFFF) #define __HAL_RCC_TIM5_FORCE_RESET() (RCC->APB1RSTR |= (RCC_APB1RSTR_TIM5RST)) #define __HAL_RCC_WWDG_FORCE_RESET() (RCC->APB1RSTR |= (RCC_APB1RSTR_WWDGRST)) #define __HAL_RCC_SPI2_FORCE_RESET() (RCC->APB1RSTR |= (RCC_APB1RSTR_SPI2RST)) #define __HAL_RCC_USART2_FORCE_RESET() (RCC->APB1RSTR |= (RCC_APB1RSTR_USART2RST)) #define __HAL_RCC_I2C1_FORCE_RESET() (RCC->APB1RSTR |= (RCC_APB1RSTR_I2C1RST)) #define __HAL_RCC_I2C2_FORCE_RESET() (RCC->APB1RSTR |= (RCC_APB1RSTR_I2C2RST)) #define __HAL_RCC_PWR_FORCE_RESET() (RCC->APB1RSTR |= (RCC_APB1RSTR_PWRRST)) #define __HAL_RCC_APB1_RELEASE_RESET() (RCC->APB1RSTR = 0x00) #define __HAL_RCC_TIM5_RELEASE_RESET() (RCC->APB1RSTR &= ~(RCC_APB1RSTR_TIM5RST)) #define __HAL_RCC_WWDG_RELEASE_RESET() (RCC->APB1RSTR &= ~(RCC_APB1RSTR_WWDGRST)) #define __HAL_RCC_SPI2_RELEASE_RESET() (RCC->APB1RSTR &= ~(RCC_APB1RSTR_SPI2RST)) #define __HAL_RCC_USART2_RELEASE_RESET() (RCC->APB1RSTR &= ~(RCC_APB1RSTR_USART2RST)) #define __HAL_RCC_I2C1_RELEASE_RESET() (RCC->APB1RSTR &= ~(RCC_APB1RSTR_I2C1RST)) #define __HAL_RCC_I2C2_RELEASE_RESET() (RCC->APB1RSTR &= ~(RCC_APB1RSTR_I2C2RST)) #define __HAL_RCC_PWR_RELEASE_RESET() (RCC->APB1RSTR &= ~(RCC_APB1RSTR_PWRRST)) /** * @} */ /** @defgroup RCC_APB2_Force_Release_Reset APB2 Force Release Reset * @brief Force or release APB2 peripheral reset. * @{ */ #define __HAL_RCC_APB2_FORCE_RESET() (RCC->APB2RSTR = 0xFFFFFFFF) #define __HAL_RCC_TIM1_FORCE_RESET() (RCC->APB2RSTR |= (RCC_APB2RSTR_TIM1RST)) #define __HAL_RCC_USART1_FORCE_RESET() (RCC->APB2RSTR |= (RCC_APB2RSTR_USART1RST)) #define __HAL_RCC_USART6_FORCE_RESET() (RCC->APB2RSTR |= (RCC_APB2RSTR_USART6RST)) #define __HAL_RCC_ADC_FORCE_RESET() (RCC->APB2RSTR |= (RCC_APB2RSTR_ADCRST)) #define __HAL_RCC_SPI1_FORCE_RESET() (RCC->APB2RSTR |= (RCC_APB2RSTR_SPI1RST)) #define __HAL_RCC_SYSCFG_FORCE_RESET() (RCC->APB2RSTR |= (RCC_APB2RSTR_SYSCFGRST)) #define __HAL_RCC_TIM9_FORCE_RESET() (RCC->APB2RSTR |= (RCC_APB2RSTR_TIM9RST)) #define __HAL_RCC_TIM11_FORCE_RESET() (RCC->APB2RSTR |= (RCC_APB2RSTR_TIM11RST)) #define __HAL_RCC_APB2_RELEASE_RESET() (RCC->APB2RSTR = 0x00) #define __HAL_RCC_TIM1_RELEASE_RESET() (RCC->APB2RSTR &= ~(RCC_APB2RSTR_TIM1RST)) #define __HAL_RCC_USART1_RELEASE_RESET() (RCC->APB2RSTR &= ~(RCC_APB2RSTR_USART1RST)) #define __HAL_RCC_USART6_RELEASE_RESET() (RCC->APB2RSTR &= ~(RCC_APB2RSTR_USART6RST)) #define __HAL_RCC_ADC_RELEASE_RESET() (RCC->APB2RSTR &= ~(RCC_APB2RSTR_ADCRST)) #define __HAL_RCC_SPI1_RELEASE_RESET() (RCC->APB2RSTR &= ~(RCC_APB2RSTR_SPI1RST)) #define __HAL_RCC_SYSCFG_RELEASE_RESET() (RCC->APB2RSTR &= ~(RCC_APB2RSTR_SYSCFGRST)) #define __HAL_RCC_TIM9_RELEASE_RESET() (RCC->APB2RSTR &= ~(RCC_APB2RSTR_TIM9RST)) #define __HAL_RCC_TIM11_RELEASE_RESET() (RCC->APB2RSTR &= ~(RCC_APB2RSTR_TIM11RST)) /** * @} */ /** @defgroup RCC_AHB1_LowPower_Enable_Disable AHB1 Peripheral Low Power Enable Disable * @brief Enable or disable the AHB1 peripheral clock during Low Power (Sleep) mode. * @note Peripheral clock gating in SLEEP mode can be used to further reduce * power consumption. * @note After wake-up from SLEEP mode, the peripheral clock is enabled again. * @note By default, all peripheral clocks are enabled during SLEEP mode. * @{ */ #define __HAL_RCC_GPIOA_CLK_SLEEP_ENABLE() (RCC->AHB1LPENR |= (RCC_AHB1LPENR_GPIOALPEN)) #define __HAL_RCC_GPIOB_CLK_SLEEP_ENABLE() (RCC->AHB1LPENR |= (RCC_AHB1LPENR_GPIOBLPEN)) #define __HAL_RCC_GPIOC_CLK_SLEEP_ENABLE() (RCC->AHB1LPENR |= (RCC_AHB1LPENR_GPIOCLPEN)) #define __HAL_RCC_GPIOH_CLK_SLEEP_ENABLE() (RCC->AHB1LPENR |= (RCC_AHB1LPENR_GPIOHLPEN)) #define __HAL_RCC_DMA1_CLK_SLEEP_ENABLE() (RCC->AHB1LPENR |= (RCC_AHB1LPENR_DMA1LPEN)) #define __HAL_RCC_DMA2_CLK_SLEEP_ENABLE() (RCC->AHB1LPENR |= (RCC_AHB1LPENR_DMA2LPEN)) #define __HAL_RCC_GPIOA_CLK_SLEEP_DISABLE() (RCC->AHB1LPENR &= ~(RCC_AHB1LPENR_GPIOALPEN)) #define __HAL_RCC_GPIOB_CLK_SLEEP_DISABLE() (RCC->AHB1LPENR &= ~(RCC_AHB1LPENR_GPIOBLPEN)) #define __HAL_RCC_GPIOC_CLK_SLEEP_DISABLE() (RCC->AHB1LPENR &= ~(RCC_AHB1LPENR_GPIOCLPEN)) #define __HAL_RCC_GPIOH_CLK_SLEEP_DISABLE() (RCC->AHB1LPENR &= ~(RCC_AHB1LPENR_GPIOHLPEN)) #define __HAL_RCC_DMA1_CLK_SLEEP_DISABLE() (RCC->AHB1LPENR &= ~(RCC_AHB1LPENR_DMA1LPEN)) #define __HAL_RCC_DMA2_CLK_SLEEP_DISABLE() (RCC->AHB1LPENR &= ~(RCC_AHB1LPENR_DMA2LPEN)) /** * @} */ /** @defgroup RCC_APB1_LowPower_Enable_Disable APB1 Peripheral Low Power Enable Disable * @brief Enable or disable the APB1 peripheral clock during Low Power (Sleep) mode. * @note Peripheral clock gating in SLEEP mode can be used to further reduce * power consumption. * @note After wake-up from SLEEP mode, the peripheral clock is enabled again. * @note By default, all peripheral clocks are enabled during SLEEP mode. * @{ */ #define __HAL_RCC_TIM5_CLK_SLEEP_ENABLE() (RCC->APB1LPENR |= (RCC_APB1LPENR_TIM5LPEN)) #define __HAL_RCC_WWDG_CLK_SLEEP_ENABLE() (RCC->APB1LPENR |= (RCC_APB1LPENR_WWDGLPEN)) #define __HAL_RCC_SPI2_CLK_SLEEP_ENABLE() (RCC->APB1LPENR |= (RCC_APB1LPENR_SPI2LPEN)) #define __HAL_RCC_USART2_CLK_SLEEP_ENABLE() (RCC->APB1LPENR |= (RCC_APB1LPENR_USART2LPEN)) #define __HAL_RCC_I2C1_CLK_SLEEP_ENABLE() (RCC->APB1LPENR |= (RCC_APB1LPENR_I2C1LPEN)) #define __HAL_RCC_I2C2_CLK_SLEEP_ENABLE() (RCC->APB1LPENR |= (RCC_APB1LPENR_I2C2LPEN)) #define __HAL_RCC_PWR_CLK_SLEEP_ENABLE() (RCC->APB1LPENR |= (RCC_APB1LPENR_PWRLPEN)) #define __HAL_RCC_TIM5_CLK_SLEEP_DISABLE() (RCC->APB1LPENR &= ~(RCC_APB1LPENR_TIM5LPEN)) #define __HAL_RCC_WWDG_CLK_SLEEP_DISABLE() (RCC->APB1LPENR &= ~(RCC_APB1LPENR_WWDGLPEN)) #define __HAL_RCC_SPI2_CLK_SLEEP_DISABLE() (RCC->APB1LPENR &= ~(RCC_APB1LPENR_SPI2LPEN)) #define __HAL_RCC_USART2_CLK_SLEEP_DISABLE() (RCC->APB1LPENR &= ~(RCC_APB1LPENR_USART2LPEN)) #define __HAL_RCC_I2C1_CLK_SLEEP_DISABLE() (RCC->APB1LPENR &= ~(RCC_APB1LPENR_I2C1LPEN)) #define __HAL_RCC_I2C2_CLK_SLEEP_DISABLE() (RCC->APB1LPENR &= ~(RCC_APB1LPENR_I2C2LPEN)) #define __HAL_RCC_PWR_CLK_SLEEP_DISABLE() (RCC->APB1LPENR &= ~(RCC_APB1LPENR_PWRLPEN)) /** * @} */ /** @defgroup RCC_APB2_LowPower_Enable_Disable APB2 Peripheral Low Power Enable Disable * @brief Enable or disable the APB2 peripheral clock during Low Power (Sleep) mode. * @note Peripheral clock gating in SLEEP mode can be used to further reduce * power consumption. * @note After wake-up from SLEEP mode, the peripheral clock is enabled again. * @note By default, all peripheral clocks are enabled during SLEEP mode. * @{ */ #define __HAL_RCC_TIM1_CLK_SLEEP_ENABLE() (RCC->APB2LPENR |= (RCC_APB2LPENR_TIM1LPEN)) #define __HAL_RCC_USART1_CLK_SLEEP_ENABLE() (RCC->APB2LPENR |= (RCC_APB2LPENR_USART1LPEN)) #define __HAL_RCC_USART6_CLK_SLEEP_ENABLE() (RCC->APB2LPENR |= (RCC_APB2LPENR_USART6LPEN)) #define __HAL_RCC_ADC1_CLK_SLEEP_ENABLE() (RCC->APB2LPENR |= (RCC_APB2LPENR_ADC1LPEN)) #define __HAL_RCC_SPI1_CLK_SLEEP_ENABLE() (RCC->APB2LPENR |= (RCC_APB2LPENR_SPI1LPEN)) #define __HAL_RCC_SYSCFG_CLK_SLEEP_ENABLE() (RCC->APB2LPENR |= (RCC_APB2LPENR_SYSCFGLPEN)) #define __HAL_RCC_TIM9_CLK_SLEEP_ENABLE() (RCC->APB2LPENR |= (RCC_APB2LPENR_TIM9LPEN)) #define __HAL_RCC_TIM11_CLK_SLEEP_ENABLE() (RCC->APB2LPENR |= (RCC_APB2LPENR_TIM11LPEN)) #define __HAL_RCC_TIM1_CLK_SLEEP_DISABLE() (RCC->APB2LPENR &= ~(RCC_APB2LPENR_TIM1LPEN)) #define __HAL_RCC_USART1_CLK_SLEEP_DISABLE() (RCC->APB2LPENR &= ~(RCC_APB2LPENR_USART1LPEN)) #define __HAL_RCC_USART6_CLK_SLEEP_DISABLE() (RCC->APB2LPENR &= ~(RCC_APB2LPENR_USART6LPEN)) #define __HAL_RCC_ADC1_CLK_SLEEP_DISABLE() (RCC->APB2LPENR &= ~(RCC_APB2LPENR_ADC1LPEN)) #define __HAL_RCC_SPI1_CLK_SLEEP_DISABLE() (RCC->APB2LPENR &= ~(RCC_APB2LPENR_SPI1LPEN)) #define __HAL_RCC_SYSCFG_CLK_SLEEP_DISABLE() (RCC->APB2LPENR &= ~(RCC_APB2LPENR_SYSCFGLPEN)) #define __HAL_RCC_TIM9_CLK_SLEEP_DISABLE() (RCC->APB2LPENR &= ~(RCC_APB2LPENR_TIM9LPEN)) #define __HAL_RCC_TIM11_CLK_SLEEP_DISABLE() (RCC->APB2LPENR &= ~(RCC_APB2LPENR_TIM11LPEN)) /** * @} */ /** @defgroup RCC_HSI_Configuration HSI Configuration * @{ */ /** @brief Macros to enable or disable the Internal High Speed oscillator (HSI). * @note The HSI is stopped by hardware when entering STOP and STANDBY modes. * It is used (enabled by hardware) as system clock source after startup * from Reset, wake-up from STOP and STANDBY mode, or in case of failure * of the HSE used directly or indirectly as system clock (if the Clock * Security System CSS is enabled). * @note HSI can not be stopped if it is used as system clock source. In this case, * you have to select another source of the system clock then stop the HSI. * @note After enabling the HSI, the application software should wait on HSIRDY * flag to be set indicating that HSI clock is stable and can be used as * system clock source. * This parameter can be: ENABLE or DISABLE. * @note When the HSI is stopped, HSIRDY flag goes low after 6 HSI oscillator * clock cycles. */ #define __HAL_RCC_HSI_ENABLE() (*(__IO uint32_t *) RCC_CR_HSION_BB = ENABLE) #define __HAL_RCC_HSI_DISABLE() (*(__IO uint32_t *) RCC_CR_HSION_BB = DISABLE) /** @brief Macro to adjust the Internal High Speed oscillator (HSI) calibration value. * @note The calibration is used to compensate for the variations in voltage * and temperature that influence the frequency of the internal HSI RC. * @param __HSICalibrationValue__: specifies the calibration trimming value. * This parameter must be a number between 0 and 0x1F. */ #define __HAL_RCC_HSI_CALIBRATIONVALUE_ADJUST(__HSICalibrationValue__) (MODIFY_REG(RCC->CR,\ RCC_CR_HSITRIM, (uint32_t)(__HSICalibrationValue__) << POSITION_VAL(RCC_CR_HSITRIM))) /** * @} */ /** @defgroup RCC_LSI_Configuration LSI Configuration * @{ */ /** @brief Macros to enable or disable the Internal Low Speed oscillator (LSI). * @note After enabling the LSI, the application software should wait on * LSIRDY flag to be set indicating that LSI clock is stable and can * be used to clock the IWDG and/or the RTC. * @note LSI can not be disabled if the IWDG is running. * @note When the LSI is stopped, LSIRDY flag goes low after 6 LSI oscillator * clock cycles. */ #define __HAL_RCC_LSI_ENABLE() (*(__IO uint32_t *) RCC_CSR_LSION_BB = ENABLE) #define __HAL_RCC_LSI_DISABLE() (*(__IO uint32_t *) RCC_CSR_LSION_BB = DISABLE) /** * @} */ /** @defgroup RCC_HSE_Configuration HSE Configuration * @{ */ /** * @brief Macro to configure the External High Speed oscillator (HSE). * @note Transition HSE Bypass to HSE On and HSE On to HSE Bypass are not supported by this macro. * User should request a transition to HSE Off first and then HSE On or HSE Bypass. * @note After enabling the HSE (RCC_HSE_ON or RCC_HSE_Bypass), the application * software should wait on HSERDY flag to be set indicating that HSE clock * is stable and can be used to clock the PLL and/or system clock. * @note HSE state can not be changed if it is used directly or through the * PLL as system clock. In this case, you have to select another source * of the system clock then change the HSE state (ex. disable it). * @note The HSE is stopped by hardware when entering STOP and STANDBY modes. * @note This function reset the CSSON bit, so if the clock security system(CSS) * was previously enabled you have to enable it again after calling this * function. * @param __STATE__: specifies the new state of the HSE. * This parameter can be one of the following values: * @arg RCC_HSE_OFF: turn OFF the HSE oscillator, HSERDY flag goes low after * 6 HSE oscillator clock cycles. * @arg RCC_HSE_ON: turn ON the HSE oscillator. * @arg RCC_HSE_BYPASS: HSE oscillator bypassed with external clock. */ #define __HAL_RCC_HSE_CONFIG(__STATE__) (*(__IO uint8_t *) RCC_CR_BYTE2_ADDRESS = (__STATE__)) /** * @} */ /** @defgroup RCC_LSE_Configuration LSE Configuration * @{ */ /** * @brief Macro to configure the External Low Speed oscillator (LSE). * @note Transition LSE Bypass to LSE On and LSE On to LSE Bypass are not supported by this macro. * User should request a transition to LSE Off first and then LSE On or LSE Bypass. * @note As the LSE is in the Backup domain and write access is denied to * this domain after reset, you have to enable write access using * HAL_PWR_EnableBkUpAccess() function before to configure the LSE * (to be done once after reset). * @note After enabling the LSE (RCC_LSE_ON or RCC_LSE_BYPASS), the application * software should wait on LSERDY flag to be set indicating that LSE clock * is stable and can be used to clock the RTC. * @param __STATE__: specifies the new state of the LSE. * This parameter can be one of the following values: * @arg RCC_LSE_OFF: turn OFF the LSE oscillator, LSERDY flag goes low after * 6 LSE oscillator clock cycles. * @arg RCC_LSE_ON: turn ON the LSE oscillator. * @arg RCC_LSE_BYPASS: LSE oscillator bypassed with external clock. */ #define __HAL_RCC_LSE_CONFIG(__STATE__) (*(__IO uint8_t *) RCC_BDCR_BYTE0_ADDRESS = (__STATE__)) /** * @} */ /** @defgroup RCC_Internal_RTC_Clock_Configuration RTC Clock Configuration * @{ */ /** @brief Macros to enable or disable the RTC clock. * @note These macros must be used only after the RTC clock source was selected. */ #define __HAL_RCC_RTC_ENABLE() (*(__IO uint32_t *) RCC_BDCR_RTCEN_BB = ENABLE) #define __HAL_RCC_RTC_DISABLE() (*(__IO uint32_t *) RCC_BDCR_RTCEN_BB = DISABLE) /** @brief Macros to configure the RTC clock (RTCCLK). * @note As the RTC clock configuration bits are in the Backup domain and write * access is denied to this domain after reset, you have to enable write * access using the Power Backup Access macro before to configure * the RTC clock source (to be done once after reset). * @note Once the RTC clock is configured it can't be changed unless the * Backup domain is reset using __HAL_RCC_BackupReset_RELEASE() macro, or by * a Power On Reset (POR). * @param __RTCCLKSource__: specifies the RTC clock source. * This parameter can be one of the following values: * @arg RCC_RTCCLKSOURCE_LSE: LSE selected as RTC clock. * @arg RCC_RTCCLKSOURCE_LSI: LSI selected as RTC clock. * @arg RCC_RTCCLKSOURCE_HSE_DIVx: HSE clock divided by x selected * as RTC clock, where x:[2,31] * @note If the LSE or LSI is used as RTC clock source, the RTC continues to * work in STOP and STANDBY modes, and can be used as wake-up source. * However, when the HSE clock is used as RTC clock source, the RTC * cannot be used in STOP and STANDBY modes. * @note The maximum input clock frequency for RTC is 1MHz (when using HSE as * RTC clock source). */ #define __HAL_RCC_RTC_CLKPRESCALER(__RTCCLKSource__) (((__RTCCLKSource__) & RCC_BDCR_RTCSEL) == RCC_BDCR_RTCSEL) ? \ MODIFY_REG(RCC->CFGR, RCC_CFGR_RTCPRE, ((__RTCCLKSource__) & 0xFFFFCFF)) : CLEAR_BIT(RCC->CFGR, RCC_CFGR_RTCPRE) #define __HAL_RCC_RTC_CONFIG(__RTCCLKSource__) do { __HAL_RCC_RTC_CLKPRESCALER(__RTCCLKSource__); \ RCC->BDCR |= ((__RTCCLKSource__) & 0x00000FFF); \ } while (0) /** @brief Macros to force or release the Backup domain reset. * @note This function resets the RTC peripheral (including the backup registers) * and the RTC clock source selection in RCC_CSR register. * @note The BKPSRAM is not affected by this reset. */ #define __HAL_RCC_BACKUPRESET_FORCE() (*(__IO uint32_t *) RCC_BDCR_BDRST_BB = ENABLE) #define __HAL_RCC_BACKUPRESET_RELEASE() (*(__IO uint32_t *) RCC_BDCR_BDRST_BB = DISABLE) /** * @} */ /** @defgroup RCC_PLL_Configuration PLL Configuration * @{ */ /** @brief Macros to enable or disable the main PLL. * @note After enabling the main PLL, the application software should wait on * PLLRDY flag to be set indicating that PLL clock is stable and can * be used as system clock source. * @note The main PLL can not be disabled if it is used as system clock source * @note The main PLL is disabled by hardware when entering STOP and STANDBY modes. */ #define __HAL_RCC_PLL_ENABLE() (*(__IO uint32_t *) RCC_CR_PLLON_BB = ENABLE) #define __HAL_RCC_PLL_DISABLE() (*(__IO uint32_t *) RCC_CR_PLLON_BB = DISABLE) /** @brief Macro to configure the PLL clock source. * @note This function must be used only when the main PLL is disabled. * @param __PLLSOURCE__: specifies the PLL entry clock source. * This parameter can be one of the following values: * @arg RCC_PLLSOURCE_HSI: HSI oscillator clock selected as PLL clock entry * @arg RCC_PLLSOURCE_HSE: HSE oscillator clock selected as PLL clock entry * */ #define __HAL_RCC_PLL_PLLSOURCE_CONFIG(__PLLSOURCE__) MODIFY_REG(RCC->PLLCFGR, RCC_PLLCFGR_PLLSRC, (__PLLSOURCE__)) /** @brief Macro to configure the PLL multiplication factor. * @note This function must be used only when the main PLL is disabled. * @param __PLLM__: specifies the division factor for PLL VCO input clock * This parameter must be a number between Min_Data = 2 and Max_Data = 63. * @note You have to set the PLLM parameter correctly to ensure that the VCO input * frequency ranges from 1 to 2 MHz. It is recommended to select a frequency * of 2 MHz to limit PLL jitter. * */ #define __HAL_RCC_PLL_PLLM_CONFIG(__PLLM__) MODIFY_REG(RCC->PLLCFGR, RCC_PLLCFGR_PLLM, (__PLLM__)) /** * @} */ /** @defgroup RCC_Get_Clock_source Get Clock source * @{ */ /** * @brief Macro to configure the system clock source. * @param __RCC_SYSCLKSOURCE__: specifies the system clock source. * This parameter can be one of the following values: * - RCC_SYSCLKSOURCE_HSI: HSI oscillator is used as system clock source. * - RCC_SYSCLKSOURCE_HSE: HSE oscillator is used as system clock source. * - RCC_SYSCLKSOURCE_PLLCLK: PLL output is used as system clock source. * - RCC_SYSCLKSOURCE_PLLRCLK: PLLR output is used as system clock source. */ #define __HAL_RCC_SYSCLK_CONFIG(__RCC_SYSCLKSOURCE__) MODIFY_REG(RCC->CFGR, RCC_CFGR_SW, (__RCC_SYSCLKSOURCE__)) /** @brief Macro to get the clock source used as system clock. * @retval The clock source used as system clock. The returned value can be one * of the following: * - RCC_SYSCLKSOURCE_STATUS_HSI: HSI used as system clock. * - RCC_SYSCLKSOURCE_STATUS_HSE: HSE used as system clock. * - RCC_SYSCLKSOURCE_STATUS_PLLCLK: PLL used as system clock. * - RCC_SYSCLKSOURCE_STATUS_PLLRCLK: PLLR used as system clock. */ #define __HAL_RCC_GET_SYSCLK_SOURCE() ((uint32_t)(RCC->CFGR & RCC_CFGR_SWS)) /** @brief Macro to get the oscillator used as PLL clock source. * @retval The oscillator used as PLL clock source. The returned value can be one * of the following: * - RCC_PLLSOURCE_HSI: HSI oscillator is used as PLL clock source. * - RCC_PLLSOURCE_HSE: HSE oscillator is used as PLL clock source. */ #define __HAL_RCC_GET_PLL_OSCSOURCE() ((uint32_t)(RCC->PLLCFGR & RCC_PLLCFGR_PLLSRC)) /** * @} */ /** @defgroup RCCEx_MCOx_Clock_Config RCC Extended MCOx Clock Config * @{ */ /** @brief Macro to configure the MCO1 clock. * @param __MCOCLKSOURCE__ specifies the MCO clock source. * This parameter can be one of the following values: * @arg RCC_MCO1SOURCE_HSI: HSI clock selected as MCO1 source * @arg RCC_MCO1SOURCE_LSE: LSE clock selected as MCO1 source * @arg RCC_MCO1SOURCE_HSE: HSE clock selected as MCO1 source * @arg RCC_MCO1SOURCE_PLLCLK: main PLL clock selected as MCO1 source * @param __MCODIV__ specifies the MCO clock prescaler. * This parameter can be one of the following values: * @arg RCC_MCODIV_1: no division applied to MCOx clock * @arg RCC_MCODIV_2: division by 2 applied to MCOx clock * @arg RCC_MCODIV_3: division by 3 applied to MCOx clock * @arg RCC_MCODIV_4: division by 4 applied to MCOx clock * @arg RCC_MCODIV_5: division by 5 applied to MCOx clock */ #define __HAL_RCC_MCO1_CONFIG(__MCOCLKSOURCE__, __MCODIV__) \ MODIFY_REG(RCC->CFGR, (RCC_CFGR_MCO1 | RCC_CFGR_MCO1PRE), ((__MCOCLKSOURCE__) | (__MCODIV__))) /** @brief Macro to configure the MCO2 clock. * @param __MCOCLKSOURCE__ specifies the MCO clock source. * This parameter can be one of the following values: * @arg RCC_MCO2SOURCE_SYSCLK: System clock (SYSCLK) selected as MCO2 source * @arg RCC_MCO2SOURCE_PLLI2SCLK: PLLI2S clock selected as MCO2 source, available for all STM32F4 devices except STM32F410xx * @arg RCC_MCO2SOURCE_I2SCLK: I2SCLK clock selected as MCO2 source, available only for STM32F410Rx devices * @arg RCC_MCO2SOURCE_HSE: HSE clock selected as MCO2 source * @arg RCC_MCO2SOURCE_PLLCLK: main PLL clock selected as MCO2 source * @param __MCODIV__ specifies the MCO clock prescaler. * This parameter can be one of the following values: * @arg RCC_MCODIV_1: no division applied to MCOx clock * @arg RCC_MCODIV_2: division by 2 applied to MCOx clock * @arg RCC_MCODIV_3: division by 3 applied to MCOx clock * @arg RCC_MCODIV_4: division by 4 applied to MCOx clock * @arg RCC_MCODIV_5: division by 5 applied to MCOx clock * @note For STM32F410Rx devices to output I2SCLK clock on MCO2 you should have * at last one of the SPI clocks enabled (SPI1, SPI2 or SPI5). */ #define __HAL_RCC_MCO2_CONFIG(__MCOCLKSOURCE__, __MCODIV__) \ MODIFY_REG(RCC->CFGR, (RCC_CFGR_MCO2 | RCC_CFGR_MCO2PRE), (__MCOCLKSOURCE__ | (__MCODIV__ << 3))); /** * @} */ /** @defgroup RCC_Flags_Interrupts_Management Flags Interrupts Management * @brief macros to manage the specified RCC Flags and interrupts. * @{ */ /** @brief Enable RCC interrupt (Perform Byte access to RCC_CIR[14:8] bits to enable * the selected interrupts). * @param __INTERRUPT__: specifies the RCC interrupt sources to be enabled. * This parameter can be any combination of the following values: * @arg RCC_IT_LSIRDY: LSI ready interrupt. * @arg RCC_IT_LSERDY: LSE ready interrupt. * @arg RCC_IT_HSIRDY: HSI ready interrupt. * @arg RCC_IT_HSERDY: HSE ready interrupt. * @arg RCC_IT_PLLRDY: Main PLL ready interrupt. * @arg RCC_IT_PLLI2SRDY: PLLI2S ready interrupt. */ #define __HAL_RCC_ENABLE_IT(__INTERRUPT__) (*(__IO uint8_t *) RCC_CIR_BYTE1_ADDRESS |= (__INTERRUPT__)) /** @brief Disable RCC interrupt (Perform Byte access to RCC_CIR[14:8] bits to disable * the selected interrupts). * @param __INTERRUPT__: specifies the RCC interrupt sources to be disabled. * This parameter can be any combination of the following values: * @arg RCC_IT_LSIRDY: LSI ready interrupt. * @arg RCC_IT_LSERDY: LSE ready interrupt. * @arg RCC_IT_HSIRDY: HSI ready interrupt. * @arg RCC_IT_HSERDY: HSE ready interrupt. * @arg RCC_IT_PLLRDY: Main PLL ready interrupt. * @arg RCC_IT_PLLI2SRDY: PLLI2S ready interrupt. */ #define __HAL_RCC_DISABLE_IT(__INTERRUPT__) (*(__IO uint8_t *) RCC_CIR_BYTE1_ADDRESS &= ~(__INTERRUPT__)) /** @brief Clear the RCC's interrupt pending bits (Perform Byte access to RCC_CIR[23:16] * bits to clear the selected interrupt pending bits. * @param __INTERRUPT__: specifies the interrupt pending bit to clear. * This parameter can be any combination of the following values: * @arg RCC_IT_LSIRDY: LSI ready interrupt. * @arg RCC_IT_LSERDY: LSE ready interrupt. * @arg RCC_IT_HSIRDY: HSI ready interrupt. * @arg RCC_IT_HSERDY: HSE ready interrupt. * @arg RCC_IT_PLLRDY: Main PLL ready interrupt. * @arg RCC_IT_PLLI2SRDY: PLLI2S ready interrupt. * @arg RCC_IT_CSS: Clock Security System interrupt */ #define __HAL_RCC_CLEAR_IT(__INTERRUPT__) (*(__IO uint8_t *) RCC_CIR_BYTE2_ADDRESS = (__INTERRUPT__)) /** @brief Check the RCC's interrupt has occurred or not. * @param __INTERRUPT__: specifies the RCC interrupt source to check. * This parameter can be one of the following values: * @arg RCC_IT_LSIRDY: LSI ready interrupt. * @arg RCC_IT_LSERDY: LSE ready interrupt. * @arg RCC_IT_HSIRDY: HSI ready interrupt. * @arg RCC_IT_HSERDY: HSE ready interrupt. * @arg RCC_IT_PLLRDY: Main PLL ready interrupt. * @arg RCC_IT_PLLI2SRDY: PLLI2S ready interrupt. * @arg RCC_IT_CSS: Clock Security System interrupt * @retval The new state of __INTERRUPT__ (TRUE or FALSE). */ #define __HAL_RCC_GET_IT(__INTERRUPT__) ((RCC->CIR & (__INTERRUPT__)) == (__INTERRUPT__)) /** @brief Set RMVF bit to clear the reset flags: RCC_FLAG_PINRST, RCC_FLAG_PORRST, * RCC_FLAG_SFTRST, RCC_FLAG_IWDGRST, RCC_FLAG_WWDGRST and RCC_FLAG_LPWRRST. */ #define __HAL_RCC_CLEAR_RESET_FLAGS() (RCC->CSR |= RCC_CSR_RMVF) /** @brief Check RCC flag is set or not. * @param __FLAG__: specifies the flag to check. * This parameter can be one of the following values: * @arg RCC_FLAG_HSIRDY: HSI oscillator clock ready. * @arg RCC_FLAG_HSERDY: HSE oscillator clock ready. * @arg RCC_FLAG_PLLRDY: Main PLL clock ready. * @arg RCC_FLAG_PLLI2SRDY: PLLI2S clock ready. * @arg RCC_FLAG_LSERDY: LSE oscillator clock ready. * @arg RCC_FLAG_LSIRDY: LSI oscillator clock ready. * @arg RCC_FLAG_BORRST: POR/PDR or BOR reset. * @arg RCC_FLAG_PINRST: Pin reset. * @arg RCC_FLAG_PORRST: POR/PDR reset. * @arg RCC_FLAG_SFTRST: Software reset. * @arg RCC_FLAG_IWDGRST: Independent Watchdog reset. * @arg RCC_FLAG_WWDGRST: Window Watchdog reset. * @arg RCC_FLAG_LPWRRST: Low Power reset. * @retval The new state of __FLAG__ (TRUE or FALSE). */ #define RCC_FLAG_MASK ((uint8_t)0x1F) #define __HAL_RCC_GET_FLAG(__FLAG__) (((((((__FLAG__) >> 5) == 1)? RCC->CR :((((__FLAG__) >> 5) == 2) ? RCC->BDCR :((((__FLAG__) >> 5) == 3)? RCC->CSR :RCC->CIR))) & ((uint32_t)1 << ((__FLAG__) & RCC_FLAG_MASK)))!= 0)? 1 : 0) /** * @} */ /** * @} */ /* Exported functions --------------------------------------------------------*/ /** @addtogroup RCC_Exported_Functions * @{ */ /** @addtogroup RCC_Exported_Functions_Group1 * @{ */ /* Initialization and de-initialization functions ******************************/ void HAL_RCC_DeInit(void); HAL_StatusTypeDef HAL_RCC_OscConfig(RCC_OscInitTypeDef *RCC_OscInitStruct); HAL_StatusTypeDef HAL_RCC_ClockConfig(RCC_ClkInitTypeDef *RCC_ClkInitStruct, uint32_t FLatency); /** * @} */ /** @addtogroup RCC_Exported_Functions_Group2 * @{ */ /* Peripheral Control functions ************************************************/ void HAL_RCC_MCOConfig(uint32_t RCC_MCOx, uint32_t RCC_MCOSource, uint32_t RCC_MCODiv); void HAL_RCC_EnableCSS(void); void HAL_RCC_DisableCSS(void); uint32_t HAL_RCC_GetSysClockFreq(void); uint32_t HAL_RCC_GetHCLKFreq(void); uint32_t HAL_RCC_GetPCLK1Freq(void); uint32_t HAL_RCC_GetPCLK2Freq(void); void HAL_RCC_GetOscConfig(RCC_OscInitTypeDef *RCC_OscInitStruct); void HAL_RCC_GetClockConfig(RCC_ClkInitTypeDef *RCC_ClkInitStruct, uint32_t *pFLatency); /* CSS NMI IRQ handler */ void HAL_RCC_NMI_IRQHandler(void); /* User Callbacks in non blocking mode (IT mode) */ void HAL_RCC_CSSCallback(void); /** * @} */ /** * @} */ /* Private types -------------------------------------------------------------*/ /* Private variables ---------------------------------------------------------*/ /* Private constants ---------------------------------------------------------*/ /** @defgroup RCC_Private_Constants RCC Private Constants * @{ */ /** @defgroup RCC_BitAddress_AliasRegion RCC BitAddress AliasRegion * @brief RCC registers bit address in the alias region * @{ */ #define RCC_OFFSET (RCC_BASE - PERIPH_BASE) /* --- CR Register ---*/ /* Alias word address of HSION bit */ #define RCC_CR_OFFSET (RCC_OFFSET + 0x00) #define RCC_HSION_BIT_NUMBER 0x00 #define RCC_CR_HSION_BB (PERIPH_BB_BASE + (RCC_CR_OFFSET * 32) + (RCC_HSION_BIT_NUMBER * 4)) /* Alias word address of CSSON bit */ #define RCC_CSSON_BIT_NUMBER 0x13 #define RCC_CR_CSSON_BB (PERIPH_BB_BASE + (RCC_CR_OFFSET * 32) + (RCC_CSSON_BIT_NUMBER * 4)) /* Alias word address of PLLON bit */ #define RCC_PLLON_BIT_NUMBER 0x18 #define RCC_CR_PLLON_BB (PERIPH_BB_BASE + (RCC_CR_OFFSET * 32) + (RCC_PLLON_BIT_NUMBER * 4)) /* --- BDCR Register ---*/ /* Alias word address of RTCEN bit */ #define RCC_BDCR_OFFSET (RCC_OFFSET + 0x70) #define RCC_RTCEN_BIT_NUMBER 0x0F #define RCC_BDCR_RTCEN_BB (PERIPH_BB_BASE + (RCC_BDCR_OFFSET * 32) + (RCC_RTCEN_BIT_NUMBER * 4)) /* Alias word address of BDRST bit */ #define RCC_BDRST_BIT_NUMBER 0x10 #define RCC_BDCR_BDRST_BB (PERIPH_BB_BASE + (RCC_BDCR_OFFSET * 32) + (RCC_BDRST_BIT_NUMBER * 4)) /* --- CSR Register ---*/ /* Alias word address of LSION bit */ #define RCC_CSR_OFFSET (RCC_OFFSET + 0x74) #define RCC_LSION_BIT_NUMBER 0x00 #define RCC_CSR_LSION_BB (PERIPH_BB_BASE + (RCC_CSR_OFFSET * 32) + (RCC_LSION_BIT_NUMBER * 4)) /* CR register byte 3 (Bits[23:16]) base address */ #define RCC_CR_BYTE2_ADDRESS ((uint32_t)0x40023802) /* CIR register byte 2 (Bits[15:8]) base address */ #define RCC_CIR_BYTE1_ADDRESS ((uint32_t)(RCC_BASE + 0x0C + 0x01)) /* CIR register byte 3 (Bits[23:16]) base address */ #define RCC_CIR_BYTE2_ADDRESS ((uint32_t)(RCC_BASE + 0x0C + 0x02)) /* BDCR register base address */ #define RCC_BDCR_BYTE0_ADDRESS (PERIPH_BASE + RCC_BDCR_OFFSET) #define RCC_DBP_TIMEOUT_VALUE ((uint32_t)100) #define RCC_LSE_TIMEOUT_VALUE ((uint32_t)100) /* 100 ms */ #define HSE_TIMEOUT_VALUE HSE_STARTUP_TIMEOUT #define HSI_TIMEOUT_VALUE ((uint32_t)100) /* 100 ms */ #define LSI_TIMEOUT_VALUE ((uint32_t)100) /* 100 ms */ /** * @} */ /** * @} */ /* Private macros ------------------------------------------------------------*/ /** @addtogroup RCC_Private_Macros RCC Private Macros * @{ */ /** @defgroup RCC_IS_RCC_Definitions RCC Private macros to check input parameters * @{ */ #define IS_RCC_OSCILLATORTYPE(OSCILLATOR) ((OSCILLATOR) <= 15) #define IS_RCC_HSE(HSE) (((HSE) == RCC_HSE_OFF) || ((HSE) == RCC_HSE_ON) || \ ((HSE) == RCC_HSE_BYPASS)) #define IS_RCC_LSE(LSE) (((LSE) == RCC_LSE_OFF) || ((LSE) == RCC_LSE_ON) || \ ((LSE) == RCC_LSE_BYPASS)) #define IS_RCC_HSI(HSI) (((HSI) == RCC_HSI_OFF) || ((HSI) == RCC_HSI_ON)) #define IS_RCC_LSI(LSI) (((LSI) == RCC_LSI_OFF) || ((LSI) == RCC_LSI_ON)) #define IS_RCC_PLL(PLL) (((PLL) == RCC_PLL_NONE) ||((PLL) == RCC_PLL_OFF) || ((PLL) == RCC_PLL_ON)) #define IS_RCC_PLLSOURCE(SOURCE) (((SOURCE) == RCC_PLLSOURCE_HSI) || \ ((SOURCE) == RCC_PLLSOURCE_HSE)) #define IS_RCC_SYSCLKSOURCE(SOURCE) (((SOURCE) == RCC_SYSCLKSOURCE_HSI) || \ ((SOURCE) == RCC_SYSCLKSOURCE_HSE) || \ ((SOURCE) == RCC_SYSCLKSOURCE_PLLCLK) || \ ((SOURCE) == RCC_SYSCLKSOURCE_PLLRCLK)) #define IS_RCC_PLLM_VALUE(VALUE) ((VALUE) <= 63) #define IS_RCC_PLLN_VALUE(VALUE) ((192 <= (VALUE)) && ((VALUE) <= 432)) #define IS_RCC_PLLP_VALUE(VALUE) (((VALUE) == 2) || ((VALUE) == 4) || ((VALUE) == 6) || ((VALUE) == 8)) #define IS_RCC_PLLQ_VALUE(VALUE) ((4 <= (VALUE)) && ((VALUE) <= 15)) #define IS_RCC_HCLK(HCLK) (((HCLK) == RCC_SYSCLK_DIV1) || ((HCLK) == RCC_SYSCLK_DIV2) || \ ((HCLK) == RCC_SYSCLK_DIV4) || ((HCLK) == RCC_SYSCLK_DIV8) || \ ((HCLK) == RCC_SYSCLK_DIV16) || ((HCLK) == RCC_SYSCLK_DIV64) || \ ((HCLK) == RCC_SYSCLK_DIV128) || ((HCLK) == RCC_SYSCLK_DIV256) || \ ((HCLK) == RCC_SYSCLK_DIV512)) #define IS_RCC_CLOCKTYPE(CLK) ((1 <= (CLK)) && ((CLK) <= 15)) #define IS_RCC_PCLK(PCLK) (((PCLK) == RCC_HCLK_DIV1) || ((PCLK) == RCC_HCLK_DIV2) || \ ((PCLK) == RCC_HCLK_DIV4) || ((PCLK) == RCC_HCLK_DIV8) || \ ((PCLK) == RCC_HCLK_DIV16)) #define IS_RCC_MCO(MCOx) (((MCOx) == RCC_MCO1) || ((MCOx) == RCC_MCO2)) #define IS_RCC_MCO1SOURCE(SOURCE) (((SOURCE) == RCC_MCO1SOURCE_HSI) || ((SOURCE) == RCC_MCO1SOURCE_LSE) || \ ((SOURCE) == RCC_MCO1SOURCE_HSE) || ((SOURCE) == RCC_MCO1SOURCE_PLLCLK)) #define IS_RCC_MCODIV(DIV) (((DIV) == RCC_MCODIV_1) || ((DIV) == RCC_MCODIV_2) || \ ((DIV) == RCC_MCODIV_3) || ((DIV) == RCC_MCODIV_4) || \ ((DIV) == RCC_MCODIV_5)) #define IS_RCC_CALIBRATION_VALUE(VALUE) ((VALUE) <= 0x1F) /** * @} */ /** * @} */ /** * @} */ /** * @} */ #ifdef __cplusplus } #endif #endif /* __STM32F4xx_HAL_RCC_H */ /************************ (C) COPYRIGHT STMicroelectronics *****END OF FILE****/ ================================================ FILE: Zelig/mbed/TARGET_NUCLEO_F401RE/stm32f4xx_hal_rcc_ex.h ================================================ /** ****************************************************************************** * @file stm32f4xx_hal_rcc_ex.h * @author MCD Application Team * @version V1.4.1 * @date 09-October-2015 * @brief Header file of RCC HAL Extension module. ****************************************************************************** * @attention * *

© COPYRIGHT(c) 2015 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. * ****************************************************************************** */ /* Define to prevent recursive inclusion -------------------------------------*/ #ifndef __STM32F4xx_HAL_RCC_EX_H #define __STM32F4xx_HAL_RCC_EX_H #ifdef __cplusplus extern "C" { #endif /* Includes ------------------------------------------------------------------*/ #include "stm32f4xx_hal_def.h" /** @addtogroup STM32F4xx_HAL_Driver * @{ */ /** @addtogroup RCCEx * @{ */ /* Exported types ------------------------------------------------------------*/ /** @defgroup RCCEx_Exported_Types RCCEx Exported Types * @{ */ /** * @brief RCC PLL configuration structure definition */ typedef struct { uint32_t PLLState; /*!< The new state of the PLL. This parameter can be a value of @ref RCC_PLL_Config */ uint32_t PLLSource; /*!< RCC_PLLSource: PLL entry clock source. This parameter must be a value of @ref RCC_PLL_Clock_Source */ uint32_t PLLM; /*!< PLLM: Division factor for PLL VCO input clock. This parameter must be a number between Min_Data = 0 and Max_Data = 63 */ uint32_t PLLN; /*!< PLLN: Multiplication factor for PLL VCO output clock. This parameter must be a number between Min_Data = 192 and Max_Data = 432 */ uint32_t PLLP; /*!< PLLP: Division factor for main system clock (SYSCLK). This parameter must be a value of @ref RCC_PLLP_Clock_Divider */ uint32_t PLLQ; /*!< PLLQ: Division factor for OTG FS, SDIO and RNG clocks. This parameter must be a number between Min_Data = 4 and Max_Data = 15 */ #if defined(STM32F410Tx) || defined(STM32F410Cx) || defined(STM32F410Rx) || defined(STM32F446xx) || defined(STM32F469xx) ||\ defined(STM32F479xx) uint32_t PLLR; /*!< PLLR: PLL division factor for I2S, SAI, SYSTEM, SPDIFRX clocks. This parameter is only available in STM32F410xx/STM32F446xx/STM32F469xx and STM32F479xx devices. This parameter must be a number between Min_Data = 2 and Max_Data = 7 */ #endif /* STM32F410xx || STM32F446xx || STM32F469xx || STM32F479xx */ }RCC_PLLInitTypeDef; #if defined(STM32F446xx) /** * @brief PLLI2S Clock structure definition */ typedef struct { uint32_t PLLI2SM; /*!< Specifies division factor for PLL VCO input clock. This parameter must be a number between Min_Data = 2 and Max_Data = 63 */ uint32_t PLLI2SN; /*!< Specifies the multiplication factor for PLLI2S VCO output clock. This parameter must be a number between Min_Data = 192 and Max_Data = 432 */ uint32_t PLLI2SP; /*!< Specifies division factor for SPDIFRX Clock. This parameter must be a value of @ref RCCEx_PLLI2SP_Clock_Divider */ uint32_t PLLI2SQ; /*!< Specifies the division factor for SAI clock. This parameter must be a number between Min_Data = 2 and Max_Data = 15. This parameter will be used only when PLLI2S is selected as Clock Source SAI */ uint32_t PLLI2SR; /*!< Specifies the division factor for I2S clock. This parameter must be a number between Min_Data = 2 and Max_Data = 7. This parameter will be used only when PLLI2S is selected as Clock Source I2S */ }RCC_PLLI2SInitTypeDef; /** * @brief PLLSAI Clock structure definition */ typedef struct { uint32_t PLLSAIM; /*!< Spcifies division factor for PLL VCO input clock. This parameter must be a number between Min_Data = 2 and Max_Data = 63 */ uint32_t PLLSAIN; /*!< Specifies the multiplication factor for PLLI2S VCO output clock. This parameter must be a number between Min_Data = 192 and Max_Data = 432 */ uint32_t PLLSAIP; /*!< Specifies division factor for OTG FS, SDIO and RNG clocks. This parameter must be a value of @ref RCCEx_PLLSAIP_Clock_Divider */ uint32_t PLLSAIQ; /*!< Specifies the division factor for SAI clock. This parameter must be a number between Min_Data = 2 and Max_Data = 15. This parameter will be used only when PLLSAI is selected as Clock Source SAI */ }RCC_PLLSAIInitTypeDef; /** * @brief RCC extended clocks structure definition */ typedef struct { uint32_t PeriphClockSelection; /*!< The Extended Clock to be configured. This parameter can be a value of @ref RCCEx_Periph_Clock_Selection */ RCC_PLLI2SInitTypeDef PLLI2S; /*!< PLL I2S structure parameters. This parameter will be used only when PLLI2S is selected as Clock Source I2S or SAI */ RCC_PLLSAIInitTypeDef PLLSAI; /*!< PLL SAI structure parameters. This parameter will be used only when PLLI2S is selected as Clock Source SAI or LTDC */ uint32_t PLLI2SDivQ; /*!< Specifies the PLLI2S division factor for SAI1 clock. This parameter must be a number between Min_Data = 1 and Max_Data = 32 This parameter will be used only when PLLI2S is selected as Clock Source SAI */ uint32_t PLLSAIDivQ; /*!< Specifies the PLLI2S division factor for SAI1 clock. This parameter must be a number between Min_Data = 1 and Max_Data = 32 This parameter will be used only when PLLSAI is selected as Clock Source SAI */ uint32_t Sai1ClockSelection; /*!< Specifies SAI1 Clock Source Selection. This parameter can be a value of @ref RCCEx_SAI1_Clock_Source */ uint32_t Sai2ClockSelection; /*!< Specifies SAI2 Clock Source Selection. This parameter can be a value of @ref RCCEx_SAI2_Clock_Source */ uint32_t I2sApb1ClockSelection; /*!< Specifies I2S APB1 Clock Source Selection. This parameter can be a value of @ref RCCEx_I2SAPB1_Clock_Source */ uint32_t I2sApb2ClockSelection; /*!< Specifies I2S APB2 Clock Source Selection. This parameter can be a value of @ref RCCEx_I2SAPB2_Clock_Source */ uint32_t RTCClockSelection; /*!< Specifies RTC Clock Source Selection. This parameter can be a value of @ref RCC_RTC_Clock_Source */ uint32_t SdioClockSelection; /*!< Specifies SDIO Clock Source Selection. This parameter can be a value of @ref RCCEx_SDIO_Clock_Source */ uint32_t CecClockSelection; /*!< Specifies CEC Clock Source Selection. This parameter can be a value of @ref RCCEx_CEC_Clock_Source */ uint32_t Fmpi2c1ClockSelection; /*!< Specifies FMPI2C1 Clock Source Selection. This parameter can be a value of @ref RCCEx_FMPI2C1_Clock_Source */ uint32_t SpdifClockSelection; /*!< Specifies SPDIFRX Clock Source Selection. This parameter can be a value of @ref RCCEx_SPDIFRX_Clock_Source */ uint32_t Clk48ClockSelection; /*!< Specifies CK48 Clock Selection this clock used OTG FS, SDIO and RNG clocks. This parameter can be a value of @ref RCCEx_CK48_Clock_Source */ uint8_t TIMPresSelection; /*!< Specifies TIM Clock Source Selection. This parameter can be a value of @ref RCCEx_TIM_PRescaler_Selection */ }RCC_PeriphCLKInitTypeDef; #endif /* STM32F446xx */ #if defined(STM32F410Tx) || defined(STM32F410Cx) || defined(STM32F410Rx) /** * @brief RCC extended clocks structure definition */ typedef struct { uint32_t PeriphClockSelection; /*!< The Extended Clock to be configured. This parameter can be a value of @ref RCCEx_Periph_Clock_Selection */ uint32_t I2SClockSelection; /*!< Specifies RTC Clock Source Selection. This parameter can be a value of @ref RCCEx_I2S_APB_Clock_Source */ uint32_t RTCClockSelection; /*!< Specifies RTC Clock Source Selection. This parameter can be a value of @ref RCC_RTC_Clock_Source */ uint32_t Lptim1ClockSelection; /*!< Specifies LPTIM1 Clock Source Selection. This parameter can be a value of @ref RCCEx_LPTIM1_Clock_Source */ uint32_t Fmpi2c1ClockSelection; /*!< Specifies FMPI2C1 Clock Source Selection. This parameter can be a value of @ref RCCEx_FMPI2C1_Clock_Source */ uint8_t TIMPresSelection; /*!< Specifies TIM Clock Source Selection. This parameter can be a value of @ref RCCEx_TIM_PRescaler_Selection */ }RCC_PeriphCLKInitTypeDef; #endif /* STM32F410Tx || STM32F410Cx || STM32F410Rx */ #if defined(STM32F427xx) || defined(STM32F437xx) || defined(STM32F429xx) || defined(STM32F439xx) || defined(STM32F469xx) || defined(STM32F479xx) /** * @brief PLLI2S Clock structure definition */ typedef struct { uint32_t PLLI2SN; /*!< Specifies the multiplication factor for PLLI2S VCO output clock. This parameter must be a number between Min_Data = 192 and Max_Data = 432. This parameter will be used only when PLLI2S is selected as Clock Source I2S or SAI */ uint32_t PLLI2SR; /*!< Specifies the division factor for I2S clock. This parameter must be a number between Min_Data = 2 and Max_Data = 7. This parameter will be used only when PLLI2S is selected as Clock Source I2S or SAI */ uint32_t PLLI2SQ; /*!< Specifies the division factor for SAI1 clock. This parameter must be a number between Min_Data = 2 and Max_Data = 15. This parameter will be used only when PLLI2S is selected as Clock Source SAI */ }RCC_PLLI2SInitTypeDef; /** * @brief PLLSAI Clock structure definition */ typedef struct { uint32_t PLLSAIN; /*!< Specifies the multiplication factor for PLLI2S VCO output clock. This parameter must be a number between Min_Data = 192 and Max_Data = 432. This parameter will be used only when PLLSAI is selected as Clock Source SAI or LTDC */ #if defined(STM32F469xx) || defined(STM32F479xx) uint32_t PLLSAIP; /*!< Specifies division factor for OTG FS and SDIO clocks. This parameter is only available in STM32F469xx/STM32F479xx devices. This parameter must be a value of @ref RCCEx_PLLSAIP_Clock_Divider */ #endif /* STM32F469xx || STM32F479xx */ uint32_t PLLSAIQ; /*!< Specifies the division factor for SAI1 clock. This parameter must be a number between Min_Data = 2 and Max_Data = 15. This parameter will be used only when PLLSAI is selected as Clock Source SAI or LTDC */ uint32_t PLLSAIR; /*!< specifies the division factor for LTDC clock This parameter must be a number between Min_Data = 2 and Max_Data = 7. This parameter will be used only when PLLSAI is selected as Clock Source LTDC */ }RCC_PLLSAIInitTypeDef; /** * @brief RCC extended clocks structure definition */ typedef struct { uint32_t PeriphClockSelection; /*!< The Extended Clock to be configured. This parameter can be a value of @ref RCCEx_Periph_Clock_Selection */ RCC_PLLI2SInitTypeDef PLLI2S; /*!< PLL I2S structure parameters. This parameter will be used only when PLLI2S is selected as Clock Source I2S or SAI */ RCC_PLLSAIInitTypeDef PLLSAI; /*!< PLL SAI structure parameters. This parameter will be used only when PLLI2S is selected as Clock Source SAI or LTDC */ uint32_t PLLI2SDivQ; /*!< Specifies the PLLI2S division factor for SAI1 clock. This parameter must be a number between Min_Data = 1 and Max_Data = 32 This parameter will be used only when PLLI2S is selected as Clock Source SAI */ uint32_t PLLSAIDivQ; /*!< Specifies the PLLI2S division factor for SAI1 clock. This parameter must be a number between Min_Data = 1 and Max_Data = 32 This parameter will be used only when PLLSAI is selected as Clock Source SAI */ uint32_t PLLSAIDivR; /*!< Specifies the PLLSAI division factor for LTDC clock. This parameter must be one value of @ref RCCEx_PLLSAI_DIVR */ uint32_t RTCClockSelection; /*!< Specifies RTC Clock Prescalers Selection. This parameter can be a value of @ref RCC_RTC_Clock_Source */ uint8_t TIMPresSelection; /*!< Specifies TIM Clock Prescalers Selection. This parameter can be a value of @ref RCCEx_TIM_PRescaler_Selection */ #if defined(STM32F469xx) || defined(STM32F479xx) uint32_t Clk48ClockSelection; /*!< Specifies CK48 Clock Selection this clock used OTG FS, SDIO and RNG clocks. This parameter can be a value of @ref RCCEx_CK48_Clock_Source */ uint32_t SdioClockSelection; /*!< Specifies SDIO Clock Source Selection. This parameter can be a value of @ref RCCEx_SDIO_Clock_Source */ #endif /* STM32F469xx || STM32F479xx */ }RCC_PeriphCLKInitTypeDef; #endif /* STM32F427xx || STM32F437xx || STM32F429xx || STM32F439xx || STM32F469xx || STM32F479xx */ #if defined(STM32F405xx) || defined(STM32F415xx) || defined(STM32F407xx) || defined(STM32F417xx) ||\ defined(STM32F401xC) || defined(STM32F401xE) || defined(STM32F411xE) /** * @brief PLLI2S Clock structure definition */ typedef struct { #if defined(STM32F411xE) uint32_t PLLI2SM; /*!< PLLM: Division factor for PLLI2S VCO input clock. This parameter must be a number between Min_Data = 2 and Max_Data = 62 */ #endif /* STM32F411xE */ uint32_t PLLI2SN; /*!< Specifies the multiplication factor for PLLI2S VCO output clock. This parameter must be a number between Min_Data = 192 and Max_Data = 432 This parameter will be used only when PLLI2S is selected as Clock Source I2S or SAI */ uint32_t PLLI2SR; /*!< Specifies the division factor for I2S clock. This parameter must be a number between Min_Data = 2 and Max_Data = 7. This parameter will be used only when PLLI2S is selected as Clock Source I2S or SAI */ }RCC_PLLI2SInitTypeDef; /** * @brief RCC extended clocks structure definition */ typedef struct { uint32_t PeriphClockSelection; /*!< The Extended Clock to be configured. This parameter can be a value of @ref RCCEx_Periph_Clock_Selection */ RCC_PLLI2SInitTypeDef PLLI2S; /*!< PLL I2S structure parameters. This parameter will be used only when PLLI2S is selected as Clock Source I2S or SAI */ uint32_t RTCClockSelection; /*!< Specifies RTC Clock Prescalers Selection. This parameter can be a value of @ref RCC_RTC_Clock_Source */ }RCC_PeriphCLKInitTypeDef; #endif /* STM32F405xx || STM32F415xx || STM32F407xx || STM32F417xx || STM32F401xC || STM32F401xE || STM32F411xE */ /** * @} */ /* Exported constants --------------------------------------------------------*/ /** @defgroup RCCEx_Exported_Constants RCCEx Exported Constants * @{ */ /** @defgroup RCCEx_Periph_Clock_Selection RCC Periph Clock Selection * @{ */ /*------------------- Peripheral Clock source for STM32F410xx ----------------*/ #if defined(STM32F410Tx) || defined(STM32F410Cx) || defined(STM32F410Rx) #define RCC_PERIPHCLK_I2S ((uint32_t)0x00000001) #define RCC_PERIPHCLK_TIM ((uint32_t)0x00000002) #define RCC_PERIPHCLK_RTC ((uint32_t)0x00000004) #define RCC_PERIPHCLK_FMPI2C1 ((uint32_t)0x00000008) #define RCC_PERIPHCLK_LPTIM1 ((uint32_t)0x00000010) #endif /* STM32F410Tx || STM32F410Cx || STM32F410Rx */ /*----------------------------------------------------------------------------*/ /*------------------- Peripheral Clock source for STM32F446xx ----------------*/ #if defined(STM32F446xx) #define RCC_PERIPHCLK_I2S_APB1 ((uint32_t)0x00000001) #define RCC_PERIPHCLK_I2S_APB2 ((uint32_t)0x00000002) #define RCC_PERIPHCLK_SAI1 ((uint32_t)0x00000004) #define RCC_PERIPHCLK_SAI2 ((uint32_t)0x00000008) #define RCC_PERIPHCLK_TIM ((uint32_t)0x00000010) #define RCC_PERIPHCLK_RTC ((uint32_t)0x00000020) #define RCC_PERIPHCLK_CEC ((uint32_t)0x00000040) #define RCC_PERIPHCLK_FMPI2C1 ((uint32_t)0x00000080) #define RCC_PERIPHCLK_CK48 ((uint32_t)0x00000100) #define RCC_PERIPHCLK_SDIO ((uint32_t)0x00000200) #define RCC_PERIPHCLK_SPDIFRX ((uint32_t)0x00000400) #define RCC_PERIPHCLK_PLLI2S ((uint32_t)0x00000800) #endif /* STM32F446xx */ /*-----------------------------------------------------------------------------*/ /*----------- Peripheral Clock source for STM32F469xx/STM32F479xx -------------*/ #if defined(STM32F469xx) || defined(STM32F479xx) #define RCC_PERIPHCLK_I2S ((uint32_t)0x00000001) #define RCC_PERIPHCLK_SAI_PLLI2S ((uint32_t)0x00000002) #define RCC_PERIPHCLK_SAI_PLLSAI ((uint32_t)0x00000004) #define RCC_PERIPHCLK_LTDC ((uint32_t)0x00000008) #define RCC_PERIPHCLK_TIM ((uint32_t)0x00000010) #define RCC_PERIPHCLK_RTC ((uint32_t)0x00000020) #define RCC_PERIPHCLK_PLLI2S ((uint32_t)0x00000040) #define RCC_PERIPHCLK_CK48 ((uint32_t)0x00000080) #define RCC_PERIPHCLK_SDIO ((uint32_t)0x00000100) #endif /* STM32F469xx || STM32F479xx */ /*----------------------------------------------------------------------------*/ /*-------- Peripheral Clock source for STM32F42xxx/STM32F43xxx ---------------*/ #if defined(STM32F427xx) || defined(STM32F437xx) || defined(STM32F429xx) || defined(STM32F439xx) #define RCC_PERIPHCLK_I2S ((uint32_t)0x00000001) #define RCC_PERIPHCLK_SAI_PLLI2S ((uint32_t)0x00000002) #define RCC_PERIPHCLK_SAI_PLLSAI ((uint32_t)0x00000004) #define RCC_PERIPHCLK_LTDC ((uint32_t)0x00000008) #define RCC_PERIPHCLK_TIM ((uint32_t)0x00000010) #define RCC_PERIPHCLK_RTC ((uint32_t)0x00000020) #define RCC_PERIPHCLK_PLLI2S ((uint32_t)0x00000040) #endif /* STM32F427xx || STM32F437xx || STM32F429xx || STM32F439xx */ /*----------------------------------------------------------------------------*/ /*-------- Peripheral Clock source for STM32F40xxx/STM32F41xxx ---------------*/ #if defined(STM32F405xx) || defined(STM32F415xx) || defined(STM32F407xx)|| defined(STM32F417xx) ||\ defined(STM32F401xC) || defined(STM32F401xE) || defined(STM32F411xE) #define RCC_PERIPHCLK_I2S ((uint32_t)0x00000001) #define RCC_PERIPHCLK_RTC ((uint32_t)0x00000002) #define RCC_PERIPHCLK_PLLI2S ((uint32_t)0x00000004) #endif /* STM32F405xx || STM32F415xx || STM32F407xx || STM32F417xx || STM32F401xC || STM32F401xE || STM32F411xE */ /*----------------------------------------------------------------------------*/ /** * @} */ #if defined(STM32F405xx) || defined(STM32F415xx) || defined(STM32F407xx) || defined(STM32F417xx) || \ defined(STM32F427xx) || defined(STM32F437xx) || defined(STM32F429xx) || defined(STM32F439xx) || \ defined(STM32F401xC) || defined(STM32F401xE) || defined(STM32F411xE) || defined(STM32F446xx) || \ defined(STM32F469xx) || defined(STM32F479xx) /** @defgroup RCCEx_I2S_Clock_Source I2S Clock Source * @{ */ #define RCC_I2SCLKSOURCE_PLLI2S ((uint32_t)0x00000000) #define RCC_I2SCLKSOURCE_EXT ((uint32_t)0x00000001) /** * @} */ #endif /* STM32F405xx || STM32F415xx || STM32F407xx || STM32F417xx || STM32F427xx || STM32F437xx || STM32F429xx || STM32F439xx || STM32F401xC || STM32F401xE || STM32F411xE || STM32F446xx || STM32F469xx || STM32F479xx */ /** @defgroup RCCEx_PLLSAI_DIVR RCC PLLSAI DIVR * @{ */ #if defined(STM32F427xx) || defined(STM32F437xx) || defined(STM32F429xx) || defined(STM32F439xx) || defined(STM32F446xx) ||\ defined(STM32F469xx) || defined(STM32F479xx) #define RCC_PLLSAIDIVR_2 ((uint32_t)0x00000000) #define RCC_PLLSAIDIVR_4 ((uint32_t)0x00010000) #define RCC_PLLSAIDIVR_8 ((uint32_t)0x00020000) #define RCC_PLLSAIDIVR_16 ((uint32_t)0x00030000) #endif /* STM32F427xx || STM32F437xx || STM32F429xx || STM32F439xx || STM32F446xx || STM32F469xx || STM32F479xx */ /** * @} */ /** @defgroup RCCEx_PLLI2SP_Clock_Divider RCC PLLI2SP Clock Divider * @{ */ #if defined(STM32F446xx) #define RCC_PLLI2SP_DIV2 ((uint32_t)0x00000002) #define RCC_PLLI2SP_DIV4 ((uint32_t)0x00000004) #define RCC_PLLI2SP_DIV6 ((uint32_t)0x00000006) #define RCC_PLLI2SP_DIV8 ((uint32_t)0x00000008) #endif /* STM32F446xx */ /** * @} */ /** @defgroup RCCEx_PLLSAIP_Clock_Divider RCC PLLSAIP Clock Divider * @{ */ #if defined(STM32F446xx) || defined(STM32F469xx) || defined(STM32F479xx) #define RCC_PLLSAIP_DIV2 ((uint32_t)0x00000002) #define RCC_PLLSAIP_DIV4 ((uint32_t)0x00000004) #define RCC_PLLSAIP_DIV6 ((uint32_t)0x00000006) #define RCC_PLLSAIP_DIV8 ((uint32_t)0x00000008) #endif /* STM32F446xx || STM32F469xx || STM32F479xx */ /** * @} */ #if defined(STM32F427xx) || defined(STM32F437xx) || defined(STM32F429xx) || defined(STM32F439xx) || defined(STM32F469xx) || defined(STM32F479xx) /** @defgroup RCCEx_SAI_BlockA_Clock_Source RCC SAI BlockA Clock Source * @{ */ #define RCC_SAIACLKSOURCE_PLLSAI ((uint32_t)0x00000000) #define RCC_SAIACLKSOURCE_PLLI2S ((uint32_t)0x00100000) #define RCC_SAIACLKSOURCE_EXT ((uint32_t)0x00200000) /** * @} */ /** @defgroup RCCEx_SAI_BlockB_Clock_Source RCC SAI BlockB Clock Source * @{ */ #define RCC_SAIBCLKSOURCE_PLLSAI ((uint32_t)0x00000000) #define RCC_SAIBCLKSOURCE_PLLI2S ((uint32_t)0x00400000) #define RCC_SAIBCLKSOURCE_EXT ((uint32_t)0x00800000) /** * @} */ #endif /* STM32F427xx || STM32F437xx || STM32F429xx || STM32F439xx || STM32F469xx || STM32F479xx */ #if defined(STM32F469xx) || defined(STM32F479xx) /** @defgroup RCCEx_CK48_Clock_Source RCC CK48 Clock Source * @{ */ #define RCC_CK48CLKSOURCE_PLLQ ((uint32_t)0x00000000) #define RCC_CK48CLKSOURCE_PLLSAIP ((uint32_t)RCC_DCKCFGR_CK48MSEL) /** * @} */ /** @defgroup RCCEx_SDIO_Clock_Source RCC SDIO Clock Source * @{ */ #define RCC_SDIOCLKSOURCE_CK48 ((uint32_t)0x00000000) #define RCC_SDIOCLKSOURCE_SYSCLK ((uint32_t)RCC_DCKCFGR_SDIOSEL) /** * @} */ /** @defgroup RCCEx_DSI_Clock_Source RCC DSI Clock Source * @{ */ #define RCC_DSICLKSOURCE_DSIPHY ((uint32_t)0x00000000) #define RCC_DSICLKSOURCE_PLLR ((uint32_t)RCC_DCKCFGR_DSISEL) /** * @} */ #endif /* STM32F469xx || STM32F479xx */ #if defined(STM32F446xx) /** @defgroup RCCEx_SAI1_Clock_Source RCC SAI1 Clock Source * @{ */ #define RCC_SAI1CLKSOURCE_PLLSAI ((uint32_t)0x00000000) #define RCC_SAI1CLKSOURCE_PLLI2S ((uint32_t)RCC_DCKCFGR_SAI1SRC_0) #define RCC_SAI1CLKSOURCE_PLLR ((uint32_t)RCC_DCKCFGR_SAI1SRC_1) #define RCC_SAI1CLKSOURCE_EXT ((uint32_t)RCC_DCKCFGR_SAI1SRC) /** * @} */ /** @defgroup RCCEx_SAI2_Clock_Source RCC SAI2 Clock Source * @{ */ #define RCC_SAI2CLKSOURCE_PLLSAI ((uint32_t)0x00000000) #define RCC_SAI2CLKSOURCE_PLLI2S ((uint32_t)RCC_DCKCFGR_SAI2SRC_0) #define RCC_SAI2CLKSOURCE_PLLR ((uint32_t)RCC_DCKCFGR_SAI2SRC_1) #define RCC_SAI2CLKSOURCE_PLLSRC ((uint32_t)RCC_DCKCFGR_SAI2SRC) /** * @} */ /** @defgroup RCCEx_I2SAPB1_Clock_Source RCC I2S APB1 Clock Source * @{ */ #define RCC_I2SAPB1CLKSOURCE_PLLI2S ((uint32_t)0x00000000) #define RCC_I2SAPB1CLKSOURCE_EXT ((uint32_t)RCC_DCKCFGR_I2S1SRC_0) #define RCC_I2SAPB1CLKSOURCE_PLLR ((uint32_t)RCC_DCKCFGR_I2S1SRC_1) #define RCC_I2SAPB1CLKSOURCE_PLLSRC ((uint32_t)RCC_DCKCFGR_I2S1SRC) /** * @} */ /** @defgroup RCCEx_I2SAPB2_Clock_Source RCC I2S APB2 Clock Source * @{ */ #define RCC_I2SAPB2CLKSOURCE_PLLI2S ((uint32_t)0x00000000) #define RCC_I2SAPB2CLKSOURCE_EXT ((uint32_t)RCC_DCKCFGR_I2S2SRC_0) #define RCC_I2SAPB2CLKSOURCE_PLLR ((uint32_t)RCC_DCKCFGR_I2S2SRC_1) #define RCC_I2SAPB2CLKSOURCE_PLLSRC ((uint32_t)RCC_DCKCFGR_I2S2SRC) /** * @} */ /** @defgroup RCCEx_FMPI2C1_Clock_Source RCC FMPI2C1 Clock Source * @{ */ #define RCC_FMPI2C1CLKSOURCE_APB ((uint32_t)0x00000000) #define RCC_FMPI2C1CLKSOURCE_SYSCLK ((uint32_t)RCC_DCKCFGR2_FMPI2C1SEL_0) #define RCC_FMPI2C1CLKSOURCE_HSI ((uint32_t)RCC_DCKCFGR2_FMPI2C1SEL_1) /** * @} */ /** @defgroup RCCEx_CEC_Clock_Source RCC CEC Clock Source * @{ */ #define RCC_CECCLKSOURCE_HSI ((uint32_t)0x00000000) #define RCC_CECCLKSOURCE_LSE ((uint32_t)RCC_DCKCFGR2_CECSEL) /** * @} */ /** @defgroup RCCEx_CK48_Clock_Source RCC CK48 Clock Source * @{ */ #define RCC_CK48CLKSOURCE_PLLQ ((uint32_t)0x00000000) #define RCC_CK48CLKSOURCE_PLLSAIP ((uint32_t)RCC_DCKCFGR2_CK48MSEL) /** * @} */ /** @defgroup RCCEx_SDIO_Clock_Source RCC SDIO Clock Source * @{ */ #define RCC_SDIOCLKSOURCE_CK48 ((uint32_t)0x00000000) #define RCC_SDIOCLKSOURCE_SYSCLK ((uint32_t)RCC_DCKCFGR2_SDIOSEL) /** * @} */ /** @defgroup RCCEx_SPDIFRX_Clock_Source RCC SPDIFRX Clock Source * @{ */ #define RCC_SPDIFRXCLKSOURCE_PLLR ((uint32_t)0x00000000) #define RCC_SPDIFRXCLKSOURCE_PLLI2SP ((uint32_t)RCC_DCKCFGR2_SPDIFRXSEL) /** * @} */ #endif /* STM32F446xx */ #if defined(STM32F410Tx) || defined(STM32F410Cx) || defined(STM32F410Rx) /** @defgroup RCCEx_I2S_APB_Clock_Source RCC I2S APB Clock Source * @{ */ #define RCC_I2SAPBCLKSOURCE_PLLR ((uint32_t)0x00000000) #define RCC_I2SAPBCLKSOURCE_EXT ((uint32_t)RCC_DCKCFGR_I2SSRC_0) #define RCC_I2SAPBCLKSOURCE_PLLSRC ((uint32_t)RCC_DCKCFGR_I2SSRC_1) /** * @} */ /** @defgroup RCCEx_FMPI2C1_Clock_Source RCC FMPI2C1 Clock Source * @{ */ #define RCC_FMPI2C1CLKSOURCE_APB ((uint32_t)0x00000000) #define RCC_FMPI2C1CLKSOURCE_SYSCLK ((uint32_t)RCC_DCKCFGR2_FMPI2C1SEL_0) #define RCC_FMPI2C1CLKSOURCE_HSI ((uint32_t)RCC_DCKCFGR2_FMPI2C1SEL_1) /** * @} */ /** @defgroup RCCEx_LPTIM1_Clock_Source RCC LPTIM1 Clock Source * @{ */ #define RCC_LPTIM1CLKSOURCE_PCLK ((uint32_t)0x00000000) #define RCC_LPTIM1CLKSOURCE_HSI ((uint32_t)RCC_DCKCFGR2_LPTIM1SEL_0) #define RCC_LPTIM1CLKSOURCE_LSI ((uint32_t)RCC_DCKCFGR2_LPTIM1SEL_1) #define RCC_LPTIM1CLKSOURCE_LSE ((uint32_t)RCC_DCKCFGR2_LPTIM1SEL_0 | RCC_DCKCFGR2_LPTIM1SEL_1) /** * @} */ /** @defgroup RCCEx_TIM_PRescaler_Selection RCC TIM PRescaler Selection * @{ */ #define RCC_TIMPRES_DESACTIVATED ((uint8_t)0x00) #define RCC_TIMPRES_ACTIVATED ((uint8_t)0x01) /** * @} */ #endif /* STM32F410Tx || STM32F410Cx || STM32F410Rx */ #if defined(STM32F427xx) || defined(STM32F437xx) || defined(STM32F429xx) || defined(STM32F439xx) ||\ defined(STM32F401xC) || defined(STM32F401xE) || defined(STM32F411xE) || defined(STM32F446xx) ||\ defined(STM32F469xx) || defined(STM32F479xx) /** @defgroup RCCEx_TIM_PRescaler_Selection RCC TIM PRescaler Selection * @{ */ #define RCC_TIMPRES_DESACTIVATED ((uint8_t)0x00) #define RCC_TIMPRES_ACTIVATED ((uint8_t)0x01) /** * @} */ #endif /* STM32F427xx || STM32F437xx || STM32F429xx || STM32F439xx || STM32F401xC || STM32F401xE ||\ STM32F410xx || STM32F411xE || STM32F446xx || STM32F469xx || STM32F479xx */ #if defined(STM32F410Tx) || defined(STM32F410Cx) || defined(STM32F410Rx) || defined(STM32F411xE) ||\ defined(STM32F446xx) || defined(STM32F469xx) || defined(STM32F479xx) /** @defgroup RCCEx_LSE_Dual_Mode_Selection RCC LSE Dual Mode Selection * @{ */ #define RCC_LSE_LOWPOWER_MODE ((uint8_t)0x00) #define RCC_LSE_HIGHDRIVE_MODE ((uint8_t)0x01) /** * @} */ #endif /* STM32F410xx || STM32F411xE || STM32F446xx || STM32F469xx || STM32F479xx */ #if defined(STM32F405xx) || defined(STM32F415xx) || defined(STM32F407xx) || defined(STM32F417xx) || \ defined(STM32F427xx) || defined(STM32F437xx) || defined(STM32F429xx) || defined(STM32F439xx) || \ defined(STM32F401xC) || defined(STM32F401xE) || defined(STM32F411xE) || defined(STM32F446xx) || \ defined(STM32F469xx) || defined(STM32F479xx) /** @defgroup RCC_MCO2_Clock_Source MCO2 Clock Source * @{ */ #define RCC_MCO2SOURCE_SYSCLK ((uint32_t)0x00000000) #define RCC_MCO2SOURCE_PLLI2SCLK RCC_CFGR_MCO2_0 #define RCC_MCO2SOURCE_HSE RCC_CFGR_MCO2_1 #define RCC_MCO2SOURCE_PLLCLK RCC_CFGR_MCO2 /** * @} */ #endif /* STM32F405xx || STM32F415xx || STM32F407xx || STM32F417xx || STM32F427xx || STM32F437xx || STM32F429xx || STM32F439xx || STM32F401xC || STM32F401xE || STM32F411xE || STM32F446xx || STM32F469xx || STM32F479xx */ #if defined(STM32F410Tx) || defined(STM32F410Cx) || defined(STM32F410Rx) /** @defgroup RCC_MCO2_Clock_Source MCO2 Clock Source * @{ */ #define RCC_MCO2SOURCE_SYSCLK ((uint32_t)0x00000000) #define RCC_MCO2SOURCE_I2SCLK RCC_CFGR_MCO2_0 #define RCC_MCO2SOURCE_HSE RCC_CFGR_MCO2_1 #define RCC_MCO2SOURCE_PLLCLK RCC_CFGR_MCO2 /** * @} */ #endif /* STM32F410Tx || STM32F410Cx || STM32F410Rx */ /** * @} */ /* Exported macro ------------------------------------------------------------*/ /** @defgroup RCCEx_Exported_Macros RCCEx Exported Macros * @{ */ /*------------------- STM32F42xxx/STM32F43xxx/STM32F469xx/STM32F479xx --------*/ #if defined(STM32F427xx) || defined(STM32F437xx) || defined(STM32F429xx)|| defined(STM32F439xx) || defined(STM32F469xx) || defined(STM32F479xx) /** @defgroup RCCEx_AHB1_Clock_Enable_Disable AHB1 Peripheral Clock Enable Disable * @brief Enables or disables the AHB1 peripheral clock. * @note After reset, the peripheral clock (used for registers read/write access) * is disabled and the application software has to enable this clock before * using it. */ #define __HAL_RCC_BKPSRAM_CLK_ENABLE() do { \ __IO uint32_t tmpreg; \ SET_BIT(RCC->AHB1ENR, RCC_AHB1ENR_BKPSRAMEN);\ /* Delay after an RCC peripheral clock enabling */ \ tmpreg = READ_BIT(RCC->AHB1ENR, RCC_AHB1ENR_BKPSRAMEN);\ UNUSED(tmpreg); \ } while(0) #define __HAL_RCC_CCMDATARAMEN_CLK_ENABLE() do { \ __IO uint32_t tmpreg; \ SET_BIT(RCC->AHB1ENR, RCC_AHB1ENR_CCMDATARAMEN);\ /* Delay after an RCC peripheral clock enabling */ \ tmpreg = READ_BIT(RCC->AHB1ENR, RCC_AHB1ENR_CCMDATARAMEN);\ UNUSED(tmpreg); \ } while(0) #define __HAL_RCC_CRC_CLK_ENABLE() do { \ __IO uint32_t tmpreg; \ SET_BIT(RCC->AHB1ENR, RCC_AHB1ENR_CRCEN);\ /* Delay after an RCC peripheral clock enabling */ \ tmpreg = READ_BIT(RCC->AHB1ENR, RCC_AHB1ENR_CRCEN);\ UNUSED(tmpreg); \ } while(0) #define __HAL_RCC_GPIOD_CLK_ENABLE() do { \ __IO uint32_t tmpreg; \ SET_BIT(RCC->AHB1ENR, RCC_AHB1ENR_GPIODEN);\ /* Delay after an RCC peripheral clock enabling */ \ tmpreg = READ_BIT(RCC->AHB1ENR, RCC_AHB1ENR_GPIODEN);\ UNUSED(tmpreg); \ } while(0) #define __HAL_RCC_GPIOE_CLK_ENABLE() do { \ __IO uint32_t tmpreg; \ SET_BIT(RCC->AHB1ENR, RCC_AHB1ENR_GPIOEEN);\ /* Delay after an RCC peripheral clock enabling */ \ tmpreg = READ_BIT(RCC->AHB1ENR, RCC_AHB1ENR_GPIOEEN);\ UNUSED(tmpreg); \ } while(0) #define __HAL_RCC_GPIOI_CLK_ENABLE() do { \ __IO uint32_t tmpreg; \ SET_BIT(RCC->AHB1ENR, RCC_AHB1ENR_GPIOIEN);\ /* Delay after an RCC peripheral clock enabling */ \ tmpreg = READ_BIT(RCC->AHB1ENR, RCC_AHB1ENR_GPIOIEN);\ UNUSED(tmpreg); \ } while(0) #define __HAL_RCC_GPIOF_CLK_ENABLE() do { \ __IO uint32_t tmpreg; \ SET_BIT(RCC->AHB1ENR, RCC_AHB1ENR_GPIOFEN);\ /* Delay after an RCC peripheral clock enabling */ \ tmpreg = READ_BIT(RCC->AHB1ENR, RCC_AHB1ENR_GPIOFEN);\ UNUSED(tmpreg); \ } while(0) #define __HAL_RCC_GPIOG_CLK_ENABLE() do { \ __IO uint32_t tmpreg; \ SET_BIT(RCC->AHB1ENR, RCC_AHB1ENR_GPIOGEN);\ /* Delay after an RCC peripheral clock enabling */ \ tmpreg = READ_BIT(RCC->AHB1ENR, RCC_AHB1ENR_GPIOGEN);\ UNUSED(tmpreg); \ } while(0) #define __HAL_RCC_GPIOJ_CLK_ENABLE() do { \ __IO uint32_t tmpreg; \ SET_BIT(RCC->AHB1ENR, RCC_AHB1ENR_GPIOJEN);\ /* Delay after an RCC peripheral clock enabling */ \ tmpreg = READ_BIT(RCC->AHB1ENR, RCC_AHB1ENR_GPIOJEN);\ UNUSED(tmpreg); \ } while(0) #define __HAL_RCC_GPIOK_CLK_ENABLE() do { \ __IO uint32_t tmpreg; \ SET_BIT(RCC->AHB1ENR, RCC_AHB1ENR_GPIOKEN);\ /* Delay after an RCC peripheral clock enabling */ \ tmpreg = READ_BIT(RCC->AHB1ENR, RCC_AHB1ENR_GPIOKEN);\ UNUSED(tmpreg); \ } while(0) #define __HAL_RCC_DMA2D_CLK_ENABLE() do { \ __IO uint32_t tmpreg; \ SET_BIT(RCC->AHB1ENR, RCC_AHB1ENR_DMA2DEN);\ /* Delay after an RCC peripheral clock enabling */ \ tmpreg = READ_BIT(RCC->AHB1ENR, RCC_AHB1ENR_DMA2DEN);\ UNUSED(tmpreg); \ } while(0) #define __HAL_RCC_ETHMAC_CLK_ENABLE() do { \ __IO uint32_t tmpreg; \ SET_BIT(RCC->AHB1ENR, RCC_AHB1ENR_ETHMACEN);\ /* Delay after an RCC peripheral clock enabling */ \ tmpreg = READ_BIT(RCC->AHB1ENR, RCC_AHB1ENR_ETHMACEN);\ UNUSED(tmpreg); \ } while(0) #define __HAL_RCC_ETHMACTX_CLK_ENABLE() do { \ __IO uint32_t tmpreg; \ SET_BIT(RCC->AHB1ENR, RCC_AHB1ENR_ETHMACTXEN);\ /* Delay after an RCC peripheral clock enabling */ \ tmpreg = READ_BIT(RCC->AHB1ENR, RCC_AHB1ENR_ETHMACTXEN);\ UNUSED(tmpreg); \ } while(0) #define __HAL_RCC_ETHMACRX_CLK_ENABLE() do { \ __IO uint32_t tmpreg; \ SET_BIT(RCC->AHB1ENR, RCC_AHB1ENR_ETHMACRXEN);\ /* Delay after an RCC peripheral clock enabling */ \ tmpreg = READ_BIT(RCC->AHB1ENR, RCC_AHB1ENR_ETHMACRXEN);\ UNUSED(tmpreg); \ } while(0) #define __HAL_RCC_ETHMACPTP_CLK_ENABLE() do { \ __IO uint32_t tmpreg; \ SET_BIT(RCC->AHB1ENR, RCC_AHB1ENR_ETHMACPTPEN);\ /* Delay after an RCC peripheral clock enabling */ \ tmpreg = READ_BIT(RCC->AHB1ENR, RCC_AHB1ENR_ETHMACPTPEN);\ UNUSED(tmpreg); \ } while(0) #define __HAL_RCC_USB_OTG_HS_CLK_ENABLE() do { \ __IO uint32_t tmpreg; \ SET_BIT(RCC->AHB1ENR, RCC_AHB1ENR_OTGHSEN);\ /* Delay after an RCC peripheral clock enabling */ \ tmpreg = READ_BIT(RCC->AHB1ENR, RCC_AHB1ENR_OTGHSEN);\ UNUSED(tmpreg); \ } while(0) #define __HAL_RCC_USB_OTG_HS_ULPI_CLK_ENABLE() do { \ __IO uint32_t tmpreg; \ SET_BIT(RCC->AHB1ENR, RCC_AHB1ENR_OTGHSULPIEN);\ /* Delay after an RCC peripheral clock enabling */ \ tmpreg = READ_BIT(RCC->AHB1ENR, RCC_AHB1ENR_OTGHSULPIEN);\ UNUSED(tmpreg); \ } while(0) #define __HAL_RCC_GPIOD_CLK_DISABLE() (RCC->AHB1ENR &= ~(RCC_AHB1ENR_GPIODEN)) #define __HAL_RCC_GPIOE_CLK_DISABLE() (RCC->AHB1ENR &= ~(RCC_AHB1ENR_GPIOEEN)) #define __HAL_RCC_GPIOF_CLK_DISABLE() (RCC->AHB1ENR &= ~(RCC_AHB1ENR_GPIOFEN)) #define __HAL_RCC_GPIOG_CLK_DISABLE() (RCC->AHB1ENR &= ~(RCC_AHB1ENR_GPIOGEN)) #define __HAL_RCC_GPIOI_CLK_DISABLE() (RCC->AHB1ENR &= ~(RCC_AHB1ENR_GPIOIEN)) #define __HAL_RCC_GPIOJ_CLK_DISABLE() (RCC->AHB1ENR &= ~(RCC_AHB1ENR_GPIOJEN)) #define __HAL_RCC_GPIOK_CLK_DISABLE() (RCC->AHB1ENR &= ~(RCC_AHB1ENR_GPIOKEN)) #define __HAL_RCC_DMA2D_CLK_DISABLE() (RCC->AHB1ENR &= ~(RCC_AHB1ENR_DMA2DEN)) #define __HAL_RCC_ETHMAC_CLK_DISABLE() (RCC->AHB1ENR &= ~(RCC_AHB1ENR_ETHMACEN)) #define __HAL_RCC_ETHMACTX_CLK_DISABLE() (RCC->AHB1ENR &= ~(RCC_AHB1ENR_ETHMACTXEN)) #define __HAL_RCC_ETHMACRX_CLK_DISABLE() (RCC->AHB1ENR &= ~(RCC_AHB1ENR_ETHMACRXEN)) #define __HAL_RCC_ETHMACPTP_CLK_DISABLE() (RCC->AHB1ENR &= ~(RCC_AHB1ENR_ETHMACPTPEN)) #define __HAL_RCC_USB_OTG_HS_CLK_DISABLE() (RCC->AHB1ENR &= ~(RCC_AHB1ENR_OTGHSEN)) #define __HAL_RCC_USB_OTG_HS_ULPI_CLK_DISABLE() (RCC->AHB1ENR &= ~(RCC_AHB1ENR_OTGHSULPIEN)) #define __HAL_RCC_BKPSRAM_CLK_DISABLE() (RCC->AHB1ENR &= ~(RCC_AHB1ENR_BKPSRAMEN)) #define __HAL_RCC_CCMDATARAMEN_CLK_DISABLE() (RCC->AHB1ENR &= ~(RCC_AHB1ENR_CCMDATARAMEN)) #define __HAL_RCC_CRC_CLK_DISABLE() (RCC->AHB1ENR &= ~(RCC_AHB1ENR_CRCEN)) /** * @brief Enable ETHERNET clock. */ #define __HAL_RCC_ETH_CLK_ENABLE() do { \ __HAL_RCC_ETHMAC_CLK_ENABLE(); \ __HAL_RCC_ETHMACTX_CLK_ENABLE(); \ __HAL_RCC_ETHMACRX_CLK_ENABLE(); \ } while(0) /** * @brief Disable ETHERNET clock. */ #define __HAL_RCC_ETH_CLK_DISABLE() do { \ __HAL_RCC_ETHMACTX_CLK_DISABLE(); \ __HAL_RCC_ETHMACRX_CLK_DISABLE(); \ __HAL_RCC_ETHMAC_CLK_DISABLE(); \ } while(0) /** * @} */ /** @defgroup RCCEx_AHB2_Clock_Enable_Disable AHB2 Peripheral Clock Enable Disable * @brief Enable or disable the AHB2 peripheral clock. * @note After reset, the peripheral clock (used for registers read/write access) * is disabled and the application software has to enable this clock before * using it. */ #define __HAL_RCC_DCMI_CLK_ENABLE() do { \ __IO uint32_t tmpreg; \ SET_BIT(RCC->AHB2ENR, RCC_AHB2ENR_DCMIEN);\ /* Delay after an RCC peripheral clock enabling */ \ tmpreg = READ_BIT(RCC->AHB2ENR, RCC_AHB2ENR_DCMIEN);\ UNUSED(tmpreg); \ } while(0) #define __HAL_RCC_DCMI_CLK_DISABLE() (RCC->AHB2ENR &= ~(RCC_AHB2ENR_DCMIEN)) #if defined(STM32F437xx)|| defined(STM32F439xx) || defined(STM32F479xx) #define __HAL_RCC_CRYP_CLK_ENABLE() do { \ __IO uint32_t tmpreg; \ SET_BIT(RCC->AHB2ENR, RCC_AHB2ENR_CRYPEN);\ /* Delay after an RCC peripheral clock enabling */ \ tmpreg = READ_BIT(RCC->AHB2ENR, RCC_AHB2ENR_CRYPEN);\ UNUSED(tmpreg); \ } while(0) #define __HAL_RCC_HASH_CLK_ENABLE() do { \ __IO uint32_t tmpreg; \ SET_BIT(RCC->AHB2ENR, RCC_AHB2ENR_HASHEN);\ /* Delay after an RCC peripheral clock enabling */ \ tmpreg = READ_BIT(RCC->AHB2ENR, RCC_AHB2ENR_HASHEN);\ UNUSED(tmpreg); \ } while(0) #define __HAL_RCC_CRYP_CLK_DISABLE() (RCC->AHB2ENR &= ~(RCC_AHB2ENR_CRYPEN)) #define __HAL_RCC_HASH_CLK_DISABLE() (RCC->AHB2ENR &= ~(RCC_AHB2ENR_HASHEN)) #endif /* STM32F437xx || STM32F439xx || STM32F479xx */ /** * @} */ /** @defgroup RCCEX_AHB2_Clock_Enable_Disable AHB2 Peripheral Clock Enable Disable * @brief Enable or disable the AHB2 peripheral clock. * @note After reset, the peripheral clock (used for registers read/write access) * is disabled and the application software has to enable this clock before * using it. * @{ */ #define __HAL_RCC_USB_OTG_FS_CLK_ENABLE() do {(RCC->AHB2ENR |= (RCC_AHB2ENR_OTGFSEN));\ __HAL_RCC_SYSCFG_CLK_ENABLE();\ }while(0) #define __HAL_RCC_USB_OTG_FS_CLK_DISABLE() do { (RCC->AHB2ENR &= ~(RCC_AHB2ENR_OTGFSEN));\ __HAL_RCC_SYSCFG_CLK_DISABLE();\ }while(0) #define __HAL_RCC_RNG_CLK_ENABLE() do { \ __IO uint32_t tmpreg; \ SET_BIT(RCC->AHB2ENR, RCC_AHB2ENR_RNGEN);\ /* Delay after an RCC peripheral clock enabling */ \ tmpreg = READ_BIT(RCC->AHB2ENR, RCC_AHB2ENR_RNGEN);\ UNUSED(tmpreg); \ } while(0) #define __HAL_RCC_RNG_CLK_DISABLE() (RCC->AHB2ENR &= ~(RCC_AHB2ENR_RNGEN)) /** * @} */ /** @defgroup RCCEx_AHB3_Clock_Enable_Disable AHB3 Peripheral Clock Enable Disable * @brief Enables or disables the AHB3 peripheral clock. * @note After reset, the peripheral clock (used for registers read/write access) * is disabled and the application software has to enable this clock before * using it. */ #define __HAL_RCC_FMC_CLK_ENABLE() do { \ __IO uint32_t tmpreg; \ SET_BIT(RCC->AHB3ENR, RCC_AHB3ENR_FMCEN);\ /* Delay after an RCC peripheral clock enabling */ \ tmpreg = READ_BIT(RCC->AHB3ENR, RCC_AHB3ENR_FMCEN);\ UNUSED(tmpreg); \ } while(0) #define __HAL_RCC_FMC_CLK_DISABLE() (RCC->AHB3ENR &= ~(RCC_AHB3ENR_FMCEN)) #if defined(STM32F469xx) || defined(STM32F479xx) #define __HAL_RCC_QSPI_CLK_ENABLE() do { \ __IO uint32_t tmpreg; \ SET_BIT(RCC->AHB3ENR, RCC_AHB3ENR_QSPIEN);\ /* Delay after an RCC peripheral clock enabling */ \ tmpreg = READ_BIT(RCC->AHB3ENR, RCC_AHB3ENR_QSPIEN);\ UNUSED(tmpreg); \ } while(0) #define __HAL_RCC_QSPI_CLK_DISABLE() (RCC->AHB3ENR &= ~(RCC_AHB3ENR_QSPIEN)) #endif /* STM32F469xx || STM32F479xx */ /** * @} */ /** @defgroup RCCEx_APB1_Clock_Enable_Disable APB1 Peripheral Clock Enable Disable * @brief Enable or disable the Low Speed APB (APB1) peripheral clock. * @note After reset, the peripheral clock (used for registers read/write access) * is disabled and the application software has to enable this clock before * using it. */ #define __HAL_RCC_TIM6_CLK_ENABLE() do { \ __IO uint32_t tmpreg; \ SET_BIT(RCC->APB1ENR, RCC_APB1ENR_TIM6EN);\ /* Delay after an RCC peripheral clock enabling */ \ tmpreg = READ_BIT(RCC->APB1ENR, RCC_APB1ENR_TIM6EN);\ UNUSED(tmpreg); \ } while(0) #define __HAL_RCC_TIM7_CLK_ENABLE() do { \ __IO uint32_t tmpreg; \ SET_BIT(RCC->APB1ENR, RCC_APB1ENR_TIM7EN);\ /* Delay after an RCC peripheral clock enabling */ \ tmpreg = READ_BIT(RCC->APB1ENR, RCC_APB1ENR_TIM7EN);\ UNUSED(tmpreg); \ } while(0) #define __HAL_RCC_TIM12_CLK_ENABLE() do { \ __IO uint32_t tmpreg; \ SET_BIT(RCC->APB1ENR, RCC_APB1ENR_TIM12EN);\ /* Delay after an RCC peripheral clock enabling */ \ tmpreg = READ_BIT(RCC->APB1ENR, RCC_APB1ENR_TIM12EN);\ UNUSED(tmpreg); \ } while(0) #define __HAL_RCC_TIM13_CLK_ENABLE() do { \ __IO uint32_t tmpreg; \ SET_BIT(RCC->APB1ENR, RCC_APB1ENR_TIM13EN);\ /* Delay after an RCC peripheral clock enabling */ \ tmpreg = READ_BIT(RCC->APB1ENR, RCC_APB1ENR_TIM13EN);\ UNUSED(tmpreg); \ } while(0) #define __HAL_RCC_TIM14_CLK_ENABLE() do { \ __IO uint32_t tmpreg; \ SET_BIT(RCC->APB1ENR, RCC_APB1ENR_TIM14EN);\ /* Delay after an RCC peripheral clock enabling */ \ tmpreg = READ_BIT(RCC->APB1ENR, RCC_APB1ENR_TIM14EN);\ UNUSED(tmpreg); \ } while(0) #define __HAL_RCC_TIM14_CLK_ENABLE() do { \ __IO uint32_t tmpreg; \ SET_BIT(RCC->APB1ENR, RCC_APB1ENR_TIM14EN);\ /* Delay after an RCC peripheral clock enabling */ \ tmpreg = READ_BIT(RCC->APB1ENR, RCC_APB1ENR_TIM14EN);\ UNUSED(tmpreg); \ } while(0) #define __HAL_RCC_USART3_CLK_ENABLE() do { \ __IO uint32_t tmpreg; \ SET_BIT(RCC->APB1ENR, RCC_APB1ENR_USART3EN);\ /* Delay after an RCC peripheral clock enabling */ \ tmpreg = READ_BIT(RCC->APB1ENR, RCC_APB1ENR_USART3EN);\ UNUSED(tmpreg); \ } while(0) #define __HAL_RCC_UART4_CLK_ENABLE() do { \ __IO uint32_t tmpreg; \ SET_BIT(RCC->APB1ENR, RCC_APB1ENR_UART4EN);\ /* Delay after an RCC peripheral clock enabling */ \ tmpreg = READ_BIT(RCC->APB1ENR, RCC_APB1ENR_UART4EN);\ UNUSED(tmpreg); \ } while(0) #define __HAL_RCC_UART5_CLK_ENABLE() do { \ __IO uint32_t tmpreg; \ SET_BIT(RCC->APB1ENR, RCC_APB1ENR_UART5EN);\ /* Delay after an RCC peripheral clock enabling */ \ tmpreg = READ_BIT(RCC->APB1ENR, RCC_APB1ENR_UART5EN);\ UNUSED(tmpreg); \ } while(0) #define __HAL_RCC_CAN1_CLK_ENABLE() do { \ __IO uint32_t tmpreg; \ SET_BIT(RCC->APB1ENR, RCC_APB1ENR_CAN1EN);\ /* Delay after an RCC peripheral clock enabling */ \ tmpreg = READ_BIT(RCC->APB1ENR, RCC_APB1ENR_CAN1EN);\ UNUSED(tmpreg); \ } while(0) #define __HAL_RCC_CAN2_CLK_ENABLE() do { \ __IO uint32_t tmpreg; \ SET_BIT(RCC->APB1ENR, RCC_APB1ENR_CAN2EN);\ /* Delay after an RCC peripheral clock enabling */ \ tmpreg = READ_BIT(RCC->APB1ENR, RCC_APB1ENR_CAN2EN);\ UNUSED(tmpreg); \ } while(0) #define __HAL_RCC_DAC_CLK_ENABLE() do { \ __IO uint32_t tmpreg; \ SET_BIT(RCC->APB1ENR, RCC_APB1ENR_DACEN);\ /* Delay after an RCC peripheral clock enabling */ \ tmpreg = READ_BIT(RCC->APB1ENR, RCC_APB1ENR_DACEN);\ UNUSED(tmpreg); \ } while(0) #define __HAL_RCC_UART7_CLK_ENABLE() do { \ __IO uint32_t tmpreg; \ SET_BIT(RCC->APB1ENR, RCC_APB1ENR_UART7EN);\ /* Delay after an RCC peripheral clock enabling */ \ tmpreg = READ_BIT(RCC->APB1ENR, RCC_APB1ENR_UART7EN);\ UNUSED(tmpreg); \ } while(0) #define __HAL_RCC_UART8_CLK_ENABLE() do { \ __IO uint32_t tmpreg; \ SET_BIT(RCC->APB1ENR, RCC_APB1ENR_UART8EN);\ /* Delay after an RCC peripheral clock enabling */ \ tmpreg = READ_BIT(RCC->APB1ENR, RCC_APB1ENR_UART8EN);\ UNUSED(tmpreg); \ } while(0) #define __HAL_RCC_TIM2_CLK_ENABLE() do { \ __IO uint32_t tmpreg; \ SET_BIT(RCC->APB1ENR, RCC_APB1ENR_TIM2EN);\ /* Delay after an RCC peripheral clock enabling */ \ tmpreg = READ_BIT(RCC->APB1ENR, RCC_APB1ENR_TIM2EN);\ UNUSED(tmpreg); \ } while(0) #define __HAL_RCC_TIM3_CLK_ENABLE() do { \ __IO uint32_t tmpreg; \ SET_BIT(RCC->APB1ENR, RCC_APB1ENR_TIM3EN);\ /* Delay after an RCC peripheral clock enabling */ \ tmpreg = READ_BIT(RCC->APB1ENR, RCC_APB1ENR_TIM3EN);\ UNUSED(tmpreg); \ } while(0) #define __HAL_RCC_TIM4_CLK_ENABLE() do { \ __IO uint32_t tmpreg; \ SET_BIT(RCC->APB1ENR, RCC_APB1ENR_TIM4EN);\ /* Delay after an RCC peripheral clock enabling */ \ tmpreg = READ_BIT(RCC->APB1ENR, RCC_APB1ENR_TIM4EN);\ UNUSED(tmpreg); \ } while(0) #define __HAL_RCC_SPI3_CLK_ENABLE() do { \ __IO uint32_t tmpreg; \ SET_BIT(RCC->APB1ENR, RCC_APB1ENR_SPI3EN);\ /* Delay after an RCC peripheral clock enabling */ \ tmpreg = READ_BIT(RCC->APB1ENR, RCC_APB1ENR_SPI3EN);\ UNUSED(tmpreg); \ } while(0) #define __HAL_RCC_I2C3_CLK_ENABLE() do { \ __IO uint32_t tmpreg; \ SET_BIT(RCC->APB1ENR, RCC_APB1ENR_I2C3EN);\ /* Delay after an RCC peripheral clock enabling */ \ tmpreg = READ_BIT(RCC->APB1ENR, RCC_APB1ENR_I2C3EN);\ UNUSED(tmpreg); \ } while(0) #define __HAL_RCC_TIM2_CLK_DISABLE() (RCC->APB1ENR &= ~(RCC_APB1ENR_TIM2EN)) #define __HAL_RCC_TIM3_CLK_DISABLE() (RCC->APB1ENR &= ~(RCC_APB1ENR_TIM3EN)) #define __HAL_RCC_TIM4_CLK_DISABLE() (RCC->APB1ENR &= ~(RCC_APB1ENR_TIM4EN)) #define __HAL_RCC_SPI3_CLK_DISABLE() (RCC->APB1ENR &= ~(RCC_APB1ENR_SPI3EN)) #define __HAL_RCC_I2C3_CLK_DISABLE() (RCC->APB1ENR &= ~(RCC_APB1ENR_I2C3EN)) #define __HAL_RCC_TIM6_CLK_DISABLE() (RCC->APB1ENR &= ~(RCC_APB1ENR_TIM6EN)) #define __HAL_RCC_TIM7_CLK_DISABLE() (RCC->APB1ENR &= ~(RCC_APB1ENR_TIM7EN)) #define __HAL_RCC_TIM12_CLK_DISABLE() (RCC->APB1ENR &= ~(RCC_APB1ENR_TIM12EN)) #define __HAL_RCC_TIM13_CLK_DISABLE() (RCC->APB1ENR &= ~(RCC_APB1ENR_TIM13EN)) #define __HAL_RCC_TIM14_CLK_DISABLE() (RCC->APB1ENR &= ~(RCC_APB1ENR_TIM14EN)) #define __HAL_RCC_USART3_CLK_DISABLE() (RCC->APB1ENR &= ~(RCC_APB1ENR_USART3EN)) #define __HAL_RCC_UART4_CLK_DISABLE() (RCC->APB1ENR &= ~(RCC_APB1ENR_UART4EN)) #define __HAL_RCC_UART5_CLK_DISABLE() (RCC->APB1ENR &= ~(RCC_APB1ENR_UART5EN)) #define __HAL_RCC_CAN1_CLK_DISABLE() (RCC->APB1ENR &= ~(RCC_APB1ENR_CAN1EN)) #define __HAL_RCC_CAN2_CLK_DISABLE() (RCC->APB1ENR &= ~(RCC_APB1ENR_CAN2EN)) #define __HAL_RCC_DAC_CLK_DISABLE() (RCC->APB1ENR &= ~(RCC_APB1ENR_DACEN)) #define __HAL_RCC_UART7_CLK_DISABLE() (RCC->APB1ENR &= ~(RCC_APB1ENR_UART7EN)) #define __HAL_RCC_UART8_CLK_DISABLE() (RCC->APB1ENR &= ~(RCC_APB1ENR_UART8EN)) /** * @} */ /** @defgroup RCCEx_APB2_Clock_Enable_Disable APB2 Peripheral Clock Enable Disable * @brief Enable or disable the High Speed APB (APB2) peripheral clock. * @note After reset, the peripheral clock (used for registers read/write access) * is disabled and the application software has to enable this clock before * using it. */ #define __HAL_RCC_TIM8_CLK_ENABLE() do { \ __IO uint32_t tmpreg; \ SET_BIT(RCC->APB2ENR, RCC_APB2ENR_TIM8EN);\ /* Delay after an RCC peripheral clock enabling */ \ tmpreg = READ_BIT(RCC->APB2ENR, RCC_APB2ENR_TIM8EN);\ UNUSED(tmpreg); \ } while(0) #define __HAL_RCC_ADC2_CLK_ENABLE() do { \ __IO uint32_t tmpreg; \ SET_BIT(RCC->APB2ENR, RCC_APB2ENR_ADC2EN);\ /* Delay after an RCC peripheral clock enabling */ \ tmpreg = READ_BIT(RCC->APB2ENR, RCC_APB2ENR_ADC2EN);\ UNUSED(tmpreg); \ } while(0) #define __HAL_RCC_ADC3_CLK_ENABLE() do { \ __IO uint32_t tmpreg; \ SET_BIT(RCC->APB2ENR, RCC_APB2ENR_ADC3EN);\ /* Delay after an RCC peripheral clock enabling */ \ tmpreg = READ_BIT(RCC->APB2ENR, RCC_APB2ENR_ADC3EN);\ UNUSED(tmpreg); \ } while(0) #define __HAL_RCC_SPI5_CLK_ENABLE() do { \ __IO uint32_t tmpreg; \ SET_BIT(RCC->APB2ENR, RCC_APB2ENR_SPI5EN);\ /* Delay after an RCC peripheral clock enabling */ \ tmpreg = READ_BIT(RCC->APB2ENR, RCC_APB2ENR_SPI5EN);\ UNUSED(tmpreg); \ } while(0) #define __HAL_RCC_SPI6_CLK_ENABLE() do { \ __IO uint32_t tmpreg; \ SET_BIT(RCC->APB2ENR, RCC_APB2ENR_SPI6EN);\ /* Delay after an RCC peripheral clock enabling */ \ tmpreg = READ_BIT(RCC->APB2ENR, RCC_APB2ENR_SPI6EN);\ UNUSED(tmpreg); \ } while(0) #define __HAL_RCC_SAI1_CLK_ENABLE() do { \ __IO uint32_t tmpreg; \ SET_BIT(RCC->APB2ENR, RCC_APB2ENR_SAI1EN);\ /* Delay after an RCC peripheral clock enabling */ \ tmpreg = READ_BIT(RCC->APB2ENR, RCC_APB2ENR_SAI1EN);\ UNUSED(tmpreg); \ } while(0) #define __HAL_RCC_SDIO_CLK_ENABLE() do { \ __IO uint32_t tmpreg; \ SET_BIT(RCC->APB2ENR, RCC_APB2ENR_SDIOEN);\ /* Delay after an RCC peripheral clock enabling */ \ tmpreg = READ_BIT(RCC->APB2ENR, RCC_APB2ENR_SDIOEN);\ UNUSED(tmpreg); \ } while(0) #define __HAL_RCC_SPI4_CLK_ENABLE() do { \ __IO uint32_t tmpreg; \ SET_BIT(RCC->APB2ENR, RCC_APB2ENR_SPI4EN);\ /* Delay after an RCC peripheral clock enabling */ \ tmpreg = READ_BIT(RCC->APB2ENR, RCC_APB2ENR_SPI4EN);\ UNUSED(tmpreg); \ } while(0) #define __HAL_RCC_TIM10_CLK_ENABLE() do { \ __IO uint32_t tmpreg; \ SET_BIT(RCC->APB2ENR, RCC_APB2ENR_TIM10EN);\ /* Delay after an RCC peripheral clock enabling */ \ tmpreg = READ_BIT(RCC->APB2ENR, RCC_APB2ENR_TIM10EN);\ UNUSED(tmpreg); \ } while(0) #define __HAL_RCC_SDIO_CLK_DISABLE() (RCC->APB2ENR &= ~(RCC_APB2ENR_SDIOEN)) #define __HAL_RCC_SPI4_CLK_DISABLE() (RCC->APB2ENR &= ~(RCC_APB2ENR_SPI4EN)) #define __HAL_RCC_TIM10_CLK_DISABLE() (RCC->APB2ENR &= ~(RCC_APB2ENR_TIM10EN)) #define __HAL_RCC_TIM8_CLK_DISABLE() (RCC->APB2ENR &= ~(RCC_APB2ENR_TIM8EN)) #define __HAL_RCC_ADC2_CLK_DISABLE() (RCC->APB2ENR &= ~(RCC_APB2ENR_ADC2EN)) #define __HAL_RCC_ADC3_CLK_DISABLE() (RCC->APB2ENR &= ~(RCC_APB2ENR_ADC3EN)) #define __HAL_RCC_SPI5_CLK_DISABLE() (RCC->APB2ENR &= ~(RCC_APB2ENR_SPI5EN)) #define __HAL_RCC_SPI6_CLK_DISABLE() (RCC->APB2ENR &= ~(RCC_APB2ENR_SPI6EN)) #define __HAL_RCC_SAI1_CLK_DISABLE() (RCC->APB2ENR &= ~(RCC_APB2ENR_SAI1EN)) #if defined(STM32F429xx)|| defined(STM32F439xx) || defined(STM32F469xx) || defined(STM32F479xx) #define __HAL_RCC_LTDC_CLK_ENABLE() do { \ __IO uint32_t tmpreg; \ SET_BIT(RCC->APB2ENR, RCC_APB2ENR_LTDCEN);\ /* Delay after an RCC peripheral clock enabling */ \ tmpreg = READ_BIT(RCC->APB2ENR, RCC_APB2ENR_LTDCEN);\ UNUSED(tmpreg); \ } while(0) #define __HAL_RCC_LTDC_CLK_DISABLE() (RCC->APB2ENR &= ~(RCC_APB2ENR_LTDCEN)) #endif /* STM32F429xx || STM32F439xx || STM32F469xx || STM32F479xx */ #if defined(STM32F469xx) || defined(STM32F479xx) #define __HAL_RCC_DSI_CLK_ENABLE() do { \ __IO uint32_t tmpreg; \ SET_BIT(RCC->APB2ENR, RCC_APB2ENR_DSIEN);\ /* Delay after an RCC peripheral clock enabling */ \ tmpreg = READ_BIT(RCC->APB2ENR, RCC_APB2ENR_DSIEN);\ UNUSED(tmpreg); \ } while(0) #define __HAL_RCC_DSI_CLK_DISABLE() (RCC->APB2ENR &= ~(RCC_APB2ENR_DSIEN)) #endif /* STM32F469xx || STM32F479xx */ /** * @} */ /** @defgroup RCCEx_AHB1_Force_Release_Reset AHB1 Force Release Reset * @brief Force or release AHB1 peripheral reset. */ #define __HAL_RCC_GPIOD_FORCE_RESET() (RCC->AHB1RSTR |= (RCC_AHB1RSTR_GPIODRST)) #define __HAL_RCC_GPIOE_FORCE_RESET() (RCC->AHB1RSTR |= (RCC_AHB1RSTR_GPIOERST)) #define __HAL_RCC_GPIOF_FORCE_RESET() (RCC->AHB1RSTR |= (RCC_AHB1RSTR_GPIOFRST)) #define __HAL_RCC_GPIOG_FORCE_RESET() (RCC->AHB1RSTR |= (RCC_AHB1RSTR_GPIOGRST)) #define __HAL_RCC_GPIOI_FORCE_RESET() (RCC->AHB1RSTR |= (RCC_AHB1RSTR_GPIOIRST)) #define __HAL_RCC_ETHMAC_FORCE_RESET() (RCC->AHB1RSTR |= (RCC_AHB1RSTR_ETHMACRST)) #define __HAL_RCC_USB_OTG_HS_FORCE_RESET() (RCC->AHB1RSTR |= (RCC_AHB1RSTR_OTGHRST)) #define __HAL_RCC_GPIOJ_FORCE_RESET() (RCC->AHB1RSTR |= (RCC_AHB1RSTR_GPIOJRST)) #define __HAL_RCC_GPIOK_FORCE_RESET() (RCC->AHB1RSTR |= (RCC_AHB1RSTR_GPIOKRST)) #define __HAL_RCC_DMA2D_FORCE_RESET() (RCC->AHB1RSTR |= (RCC_AHB1RSTR_DMA2DRST)) #define __HAL_RCC_CRC_FORCE_RESET() (RCC->AHB1RSTR |= (RCC_AHB1RSTR_CRCRST)) #define __HAL_RCC_GPIOD_RELEASE_RESET() (RCC->AHB1RSTR &= ~(RCC_AHB1RSTR_GPIODRST)) #define __HAL_RCC_GPIOE_RELEASE_RESET() (RCC->AHB1RSTR &= ~(RCC_AHB1RSTR_GPIOERST)) #define __HAL_RCC_GPIOF_RELEASE_RESET() (RCC->AHB1RSTR &= ~(RCC_AHB1RSTR_GPIOFRST)) #define __HAL_RCC_GPIOG_RELEASE_RESET() (RCC->AHB1RSTR &= ~(RCC_AHB1RSTR_GPIOGRST)) #define __HAL_RCC_GPIOI_RELEASE_RESET() (RCC->AHB1RSTR &= ~(RCC_AHB1RSTR_GPIOIRST)) #define __HAL_RCC_ETHMAC_RELEASE_RESET() (RCC->AHB1RSTR &= ~(RCC_AHB1RSTR_ETHMACRST)) #define __HAL_RCC_USB_OTG_HS_RELEASE_RESET() (RCC->AHB1RSTR &= ~(RCC_AHB1RSTR_OTGHRST)) #define __HAL_RCC_GPIOJ_RELEASE_RESET() (RCC->AHB1RSTR &= ~(RCC_AHB1RSTR_GPIOJRST)) #define __HAL_RCC_GPIOK_RELEASE_RESET() (RCC->AHB1RSTR &= ~(RCC_AHB1RSTR_GPIOKRST)) #define __HAL_RCC_DMA2D_RELEASE_RESET() (RCC->AHB1RSTR &= ~(RCC_AHB1RSTR_DMA2DRST)) #define __HAL_RCC_CRC_RELEASE_RESET() (RCC->AHB1RSTR &= ~(RCC_AHB1RSTR_CRCRST)) /** * @} */ /** @defgroup RCCEx_AHB2_Force_Release_Reset AHB2 Force Release Reset * @brief Force or release AHB2 peripheral reset. * @{ */ #define __HAL_RCC_AHB2_FORCE_RESET() (RCC->AHB2RSTR = 0xFFFFFFFF) #define __HAL_RCC_USB_OTG_FS_FORCE_RESET() (RCC->AHB2RSTR |= (RCC_AHB2RSTR_OTGFSRST)) #define __HAL_RCC_RNG_FORCE_RESET() (RCC->AHB2RSTR |= (RCC_AHB2RSTR_RNGRST)) #define __HAL_RCC_DCMI_FORCE_RESET() (RCC->AHB2RSTR |= (RCC_AHB2RSTR_DCMIRST)) #define __HAL_RCC_AHB2_RELEASE_RESET() (RCC->AHB2RSTR = 0x00) #define __HAL_RCC_USB_OTG_FS_RELEASE_RESET() (RCC->AHB2RSTR &= ~(RCC_AHB2RSTR_OTGFSRST)) #define __HAL_RCC_RNG_RELEASE_RESET() (RCC->AHB2RSTR &= ~(RCC_AHB2RSTR_RNGRST)) #define __HAL_RCC_DCMI_RELEASE_RESET() (RCC->AHB2RSTR &= ~(RCC_AHB2RSTR_DCMIRST)) #if defined(STM32F437xx)|| defined(STM32F439xx) || defined(STM32F479xx) #define __HAL_RCC_CRYP_FORCE_RESET() (RCC->AHB2RSTR |= (RCC_AHB2RSTR_CRYPRST)) #define __HAL_RCC_HASH_FORCE_RESET() (RCC->AHB2RSTR |= (RCC_AHB2RSTR_HASHRST)) #define __HAL_RCC_CRYP_RELEASE_RESET() (RCC->AHB2RSTR &= ~(RCC_AHB2RSTR_CRYPRST)) #define __HAL_RCC_HASH_RELEASE_RESET() (RCC->AHB2RSTR &= ~(RCC_AHB2RSTR_HASHRST)) #endif /* STM32F437xx || STM32F439xx || STM32F479xx */ /** * @} */ /** @defgroup RCCEx_AHB3_Force_Release_Reset AHB3 Force Release Reset * @brief Force or release AHB3 peripheral reset. * @{ */ #define __HAL_RCC_AHB3_FORCE_RESET() (RCC->AHB3RSTR = 0xFFFFFFFF) #define __HAL_RCC_AHB3_RELEASE_RESET() (RCC->AHB3RSTR = 0x00) #define __HAL_RCC_FMC_FORCE_RESET() (RCC->AHB3RSTR |= (RCC_AHB3RSTR_FMCRST)) #define __HAL_RCC_FMC_RELEASE_RESET() (RCC->AHB3RSTR &= ~(RCC_AHB3RSTR_FMCRST)) #if defined(STM32F469xx) || defined(STM32F479xx) #define __HAL_RCC_QSPI_FORCE_RESET() (RCC->AHB3RSTR |= (RCC_AHB3RSTR_QSPIRST)) #define __HAL_RCC_QSPI_RELEASE_RESET() (RCC->AHB3RSTR &= ~(RCC_AHB3RSTR_QSPIRST)) #endif /* STM32F469xx || STM32F479xx */ /** * @} */ /** @defgroup RCCEx_APB1_Force_Release_Reset APB1 Force Release Reset * @brief Force or release APB1 peripheral reset. */ #define __HAL_RCC_TIM6_FORCE_RESET() (RCC->APB1RSTR |= (RCC_APB1RSTR_TIM6RST)) #define __HAL_RCC_TIM7_FORCE_RESET() (RCC->APB1RSTR |= (RCC_APB1RSTR_TIM7RST)) #define __HAL_RCC_TIM12_FORCE_RESET() (RCC->APB1RSTR |= (RCC_APB1RSTR_TIM12RST)) #define __HAL_RCC_TIM13_FORCE_RESET() (RCC->APB1RSTR |= (RCC_APB1RSTR_TIM13RST)) #define __HAL_RCC_TIM14_FORCE_RESET() (RCC->APB1RSTR |= (RCC_APB1RSTR_TIM14RST)) #define __HAL_RCC_USART3_FORCE_RESET() (RCC->APB1RSTR |= (RCC_APB1RSTR_USART3RST)) #define __HAL_RCC_UART4_FORCE_RESET() (RCC->APB1RSTR |= (RCC_APB1RSTR_UART4RST)) #define __HAL_RCC_UART5_FORCE_RESET() (RCC->APB1RSTR |= (RCC_APB1RSTR_UART5RST)) #define __HAL_RCC_CAN1_FORCE_RESET() (RCC->APB1RSTR |= (RCC_APB1RSTR_CAN1RST)) #define __HAL_RCC_CAN2_FORCE_RESET() (RCC->APB1RSTR |= (RCC_APB1RSTR_CAN2RST)) #define __HAL_RCC_DAC_FORCE_RESET() (RCC->APB1RSTR |= (RCC_APB1RSTR_DACRST)) #define __HAL_RCC_UART7_FORCE_RESET() (RCC->APB1RSTR |= (RCC_APB1RSTR_UART7RST)) #define __HAL_RCC_UART8_FORCE_RESET() (RCC->APB1RSTR |= (RCC_APB1RSTR_UART8RST)) #define __HAL_RCC_TIM2_FORCE_RESET() (RCC->APB1RSTR |= (RCC_APB1RSTR_TIM2RST)) #define __HAL_RCC_TIM3_FORCE_RESET() (RCC->APB1RSTR |= (RCC_APB1RSTR_TIM3RST)) #define __HAL_RCC_TIM4_FORCE_RESET() (RCC->APB1RSTR |= (RCC_APB1RSTR_TIM4RST)) #define __HAL_RCC_SPI3_FORCE_RESET() (RCC->APB1RSTR |= (RCC_APB1RSTR_SPI3RST)) #define __HAL_RCC_I2C3_FORCE_RESET() (RCC->APB1RSTR |= (RCC_APB1RSTR_I2C3RST)) #define __HAL_RCC_TIM2_RELEASE_RESET() (RCC->APB1RSTR &= ~(RCC_APB1RSTR_TIM2RST)) #define __HAL_RCC_TIM3_RELEASE_RESET() (RCC->APB1RSTR &= ~(RCC_APB1RSTR_TIM3RST)) #define __HAL_RCC_TIM4_RELEASE_RESET() (RCC->APB1RSTR &= ~(RCC_APB1RSTR_TIM4RST)) #define __HAL_RCC_SPI3_RELEASE_RESET() (RCC->APB1RSTR &= ~(RCC_APB1RSTR_SPI3RST)) #define __HAL_RCC_I2C3_RELEASE_RESET() (RCC->APB1RSTR &= ~(RCC_APB1RSTR_I2C3RST)) #define __HAL_RCC_TIM6_RELEASE_RESET() (RCC->APB1RSTR &= ~(RCC_APB1RSTR_TIM6RST)) #define __HAL_RCC_TIM7_RELEASE_RESET() (RCC->APB1RSTR &= ~(RCC_APB1RSTR_TIM7RST)) #define __HAL_RCC_TIM12_RELEASE_RESET() (RCC->APB1RSTR &= ~(RCC_APB1RSTR_TIM12RST)) #define __HAL_RCC_TIM13_RELEASE_RESET() (RCC->APB1RSTR &= ~(RCC_APB1RSTR_TIM13RST)) #define __HAL_RCC_TIM14_RELEASE_RESET() (RCC->APB1RSTR &= ~(RCC_APB1RSTR_TIM14RST)) #define __HAL_RCC_USART3_RELEASE_RESET() (RCC->APB1RSTR &= ~(RCC_APB1RSTR_USART3RST)) #define __HAL_RCC_UART4_RELEASE_RESET() (RCC->APB1RSTR &= ~(RCC_APB1RSTR_UART4RST)) #define __HAL_RCC_UART5_RELEASE_RESET() (RCC->APB1RSTR &= ~(RCC_APB1RSTR_UART5RST)) #define __HAL_RCC_CAN1_RELEASE_RESET() (RCC->APB1RSTR &= ~(RCC_APB1RSTR_CAN1RST)) #define __HAL_RCC_CAN2_RELEASE_RESET() (RCC->APB1RSTR &= ~(RCC_APB1RSTR_CAN2RST)) #define __HAL_RCC_DAC_RELEASE_RESET() (RCC->APB1RSTR &= ~(RCC_APB1RSTR_DACRST)) #define __HAL_RCC_UART7_RELEASE_RESET() (RCC->APB1RSTR &= ~(RCC_APB1RSTR_UART7RST)) #define __HAL_RCC_UART8_RELEASE_RESET() (RCC->APB1RSTR &= ~(RCC_APB1RSTR_UART8RST)) /** * @} */ /** @defgroup RCCEx_APB2_Force_Release_Reset APB2 Force Release Reset * @brief Force or release APB2 peripheral reset. */ #define __HAL_RCC_TIM8_FORCE_RESET() (RCC->APB2RSTR |= (RCC_APB2RSTR_TIM8RST)) #define __HAL_RCC_SPI5_FORCE_RESET() (RCC->APB2RSTR |= (RCC_APB2RSTR_SPI5RST)) #define __HAL_RCC_SPI6_FORCE_RESET() (RCC->APB2RSTR |= (RCC_APB2RSTR_SPI6RST)) #define __HAL_RCC_SAI1_FORCE_RESET() (RCC->APB2RSTR |= (RCC_APB2RSTR_SAI1RST)) #define __HAL_RCC_SDIO_FORCE_RESET() (RCC->APB2RSTR |= (RCC_APB2RSTR_SDIORST)) #define __HAL_RCC_SPI4_FORCE_RESET() (RCC->APB2RSTR |= (RCC_APB2RSTR_SPI4RST)) #define __HAL_RCC_TIM10_FORCE_RESET() (RCC->APB2RSTR |= (RCC_APB2RSTR_TIM10RST)) #define __HAL_RCC_SDIO_RELEASE_RESET() (RCC->APB2RSTR &= ~(RCC_APB2RSTR_SDIORST)) #define __HAL_RCC_SPI4_RELEASE_RESET() (RCC->APB2RSTR &= ~(RCC_APB2RSTR_SPI4RST)) #define __HAL_RCC_TIM10_RELEASE_RESET()(RCC->APB2RSTR &= ~(RCC_APB2RSTR_TIM10RST)) #define __HAL_RCC_TIM8_RELEASE_RESET() (RCC->APB2RSTR &= ~(RCC_APB2RSTR_TIM8RST)) #define __HAL_RCC_SPI5_RELEASE_RESET() (RCC->APB2RSTR &= ~(RCC_APB2RSTR_SPI5RST)) #define __HAL_RCC_SPI6_RELEASE_RESET() (RCC->APB2RSTR &= ~(RCC_APB2RSTR_SPI6RST)) #define __HAL_RCC_SAI1_RELEASE_RESET() (RCC->APB2RSTR &= ~(RCC_APB2RSTR_SAI1RST)) #if defined(STM32F429xx)|| defined(STM32F439xx) || defined(STM32F469xx) || defined(STM32F479xx) #define __HAL_RCC_LTDC_FORCE_RESET() (RCC->APB2RSTR |= (RCC_APB2RSTR_LTDCRST)) #define __HAL_RCC_LTDC_RELEASE_RESET() (RCC->APB2RSTR &= ~(RCC_APB2RSTR_LTDCRST)) #endif /* STM32F429xx|| STM32F439xx || STM32F469xx || STM32F479xx */ #if defined(STM32F469xx) || defined(STM32F479xx) #define __HAL_RCC_DSI_FORCE_RESET() (RCC->APB2RSTR |= (RCC_APB2RSTR_DSIRST)) #define __HAL_RCC_DSI_RELEASE_RESET() (RCC->APB2RSTR &= ~(RCC_APB2RSTR_DSIRST)) #endif /* STM32F469xx || STM32F479xx */ /** * @} */ /** @defgroup RCCEx_AHB1_LowPower_Enable_Disable AHB1 Peripheral Low Power Enable Disable * @brief Enable or disable the AHB1 peripheral clock during Low Power (Sleep) mode. * @note Peripheral clock gating in SLEEP mode can be used to further reduce * power consumption. * @note After wakeup from SLEEP mode, the peripheral clock is enabled again. * @note By default, all peripheral clocks are enabled during SLEEP mode. */ #define __HAL_RCC_GPIOD_CLK_SLEEP_ENABLE() (RCC->AHB1LPENR |= (RCC_AHB1LPENR_GPIODLPEN)) #define __HAL_RCC_GPIOE_CLK_SLEEP_ENABLE() (RCC->AHB1LPENR |= (RCC_AHB1LPENR_GPIOELPEN)) #define __HAL_RCC_GPIOF_CLK_SLEEP_ENABLE() (RCC->AHB1LPENR |= (RCC_AHB1LPENR_GPIOFLPEN)) #define __HAL_RCC_GPIOG_CLK_SLEEP_ENABLE() (RCC->AHB1LPENR |= (RCC_AHB1LPENR_GPIOGLPEN)) #define __HAL_RCC_GPIOI_CLK_SLEEP_ENABLE() (RCC->AHB1LPENR |= (RCC_AHB1LPENR_GPIOILPEN)) #define __HAL_RCC_SRAM2_CLK_SLEEP_ENABLE() (RCC->AHB1LPENR |= (RCC_AHB1LPENR_SRAM2LPEN)) #define __HAL_RCC_ETHMAC_CLK_SLEEP_ENABLE() (RCC->AHB1LPENR |= (RCC_AHB1LPENR_ETHMACLPEN)) #define __HAL_RCC_ETHMACTX_CLK_SLEEP_ENABLE() (RCC->AHB1LPENR |= (RCC_AHB1LPENR_ETHMACTXLPEN)) #define __HAL_RCC_ETHMACRX_CLK_SLEEP_ENABLE() (RCC->AHB1LPENR |= (RCC_AHB1LPENR_ETHMACRXLPEN)) #define __HAL_RCC_ETHMACPTP_CLK_SLEEP_ENABLE() (RCC->AHB1LPENR |= (RCC_AHB1LPENR_ETHMACPTPLPEN)) #define __HAL_RCC_USB_OTG_HS_CLK_SLEEP_ENABLE() (RCC->AHB1LPENR |= (RCC_AHB1LPENR_OTGHSLPEN)) #define __HAL_RCC_USB_OTG_HS_ULPI_CLK_SLEEP_ENABLE() (RCC->AHB1LPENR |= (RCC_AHB1LPENR_OTGHSULPILPEN)) #define __HAL_RCC_GPIOJ_CLK_SLEEP_ENABLE() (RCC->AHB1LPENR |= (RCC_AHB1LPENR_GPIOJLPEN)) #define __HAL_RCC_GPIOK_CLK_SLEEP_ENABLE() (RCC->AHB1LPENR |= (RCC_AHB1LPENR_GPIOKLPEN)) #define __HAL_RCC_SRAM3_CLK_SLEEP_ENABLE() (RCC->AHB1LPENR |= (RCC_AHB1LPENR_SRAM3LPEN)) #define __HAL_RCC_DMA2D_CLK_SLEEP_ENABLE() (RCC->AHB1LPENR |= (RCC_AHB1LPENR_DMA2DLPEN)) #define __HAL_RCC_CRC_CLK_SLEEP_ENABLE() (RCC->AHB1LPENR |= (RCC_AHB1LPENR_CRCLPEN)) #define __HAL_RCC_FLITF_CLK_SLEEP_ENABLE() (RCC->AHB1LPENR |= (RCC_AHB1LPENR_FLITFLPEN)) #define __HAL_RCC_SRAM1_CLK_SLEEP_ENABLE() (RCC->AHB1LPENR |= (RCC_AHB1LPENR_SRAM1LPEN)) #define __HAL_RCC_BKPSRAM_CLK_SLEEP_ENABLE() (RCC->AHB1LPENR |= (RCC_AHB1LPENR_BKPSRAMLPEN)) #define __HAL_RCC_GPIOD_CLK_SLEEP_DISABLE() (RCC->AHB1LPENR &= ~(RCC_AHB1LPENR_GPIODLPEN)) #define __HAL_RCC_GPIOE_CLK_SLEEP_DISABLE() (RCC->AHB1LPENR &= ~(RCC_AHB1LPENR_GPIOELPEN)) #define __HAL_RCC_GPIOF_CLK_SLEEP_DISABLE() (RCC->AHB1LPENR &= ~(RCC_AHB1LPENR_GPIOFLPEN)) #define __HAL_RCC_GPIOG_CLK_SLEEP_DISABLE() (RCC->AHB1LPENR &= ~(RCC_AHB1LPENR_GPIOGLPEN)) #define __HAL_RCC_GPIOI_CLK_SLEEP_DISABLE() (RCC->AHB1LPENR &= ~(RCC_AHB1LPENR_GPIOILPEN)) #define __HAL_RCC_SRAM2_CLK_SLEEP_DISABLE() (RCC->AHB1LPENR &= ~(RCC_AHB1LPENR_SRAM2LPEN)) #define __HAL_RCC_ETHMAC_CLK_SLEEP_DISABLE() (RCC->AHB1LPENR &= ~(RCC_AHB1LPENR_ETHMACLPEN)) #define __HAL_RCC_ETHMACTX_CLK_SLEEP_DISABLE() (RCC->AHB1LPENR &= ~(RCC_AHB1LPENR_ETHMACTXLPEN)) #define __HAL_RCC_ETHMACRX_CLK_SLEEP_DISABLE() (RCC->AHB1LPENR &= ~(RCC_AHB1LPENR_ETHMACRXLPEN)) #define __HAL_RCC_ETHMACPTP_CLK_SLEEP_DISABLE() (RCC->AHB1LPENR &= ~(RCC_AHB1LPENR_ETHMACPTPLPEN)) #define __HAL_RCC_USB_OTG_HS_CLK_SLEEP_DISABLE() (RCC->AHB1LPENR &= ~(RCC_AHB1LPENR_OTGHSLPEN)) #define __HAL_RCC_USB_OTG_HS_ULPI_CLK_SLEEP_DISABLE() (RCC->AHB1LPENR &= ~(RCC_AHB1LPENR_OTGHSULPILPEN)) #define __HAL_RCC_GPIOJ_CLK_SLEEP_DISABLE() (RCC->AHB1LPENR &= ~(RCC_AHB1LPENR_GPIOJLPEN)) #define __HAL_RCC_GPIOK_CLK_SLEEP_DISABLE() (RCC->AHB1LPENR &= ~(RCC_AHB1LPENR_GPIOKLPEN)) #define __HAL_RCC_DMA2D_CLK_SLEEP_DISABLE() (RCC->AHB1LPENR &= ~(RCC_AHB1LPENR_DMA2DLPEN)) #define __HAL_RCC_CRC_CLK_SLEEP_DISABLE() (RCC->AHB1LPENR &= ~(RCC_AHB1LPENR_CRCLPEN)) #define __HAL_RCC_FLITF_CLK_SLEEP_DISABLE() (RCC->AHB1LPENR &= ~(RCC_AHB1LPENR_FLITFLPEN)) #define __HAL_RCC_SRAM1_CLK_SLEEP_DISABLE() (RCC->AHB1LPENR &= ~(RCC_AHB1LPENR_SRAM1LPEN)) #define __HAL_RCC_BKPSRAM_CLK_SLEEP_DISABLE() (RCC->AHB1LPENR &= ~(RCC_AHB1LPENR_BKPSRAMLPEN)) /** * @} */ /** @defgroup RCCEx_AHB2_LowPower_Enable_Disable AHB2 Peripheral Low Power Enable Disable * @brief Enable or disable the AHB2 peripheral clock during Low Power (Sleep) mode. * @note Peripheral clock gating in SLEEP mode can be used to further reduce * power consumption. * @note After wake-up from SLEEP mode, the peripheral clock is enabled again. * @note By default, all peripheral clocks are enabled during SLEEP mode. * @{ */ #define __HAL_RCC_USB_OTG_FS_CLK_SLEEP_ENABLE() (RCC->AHB2LPENR |= (RCC_AHB2LPENR_OTGFSLPEN)) #define __HAL_RCC_USB_OTG_FS_CLK_SLEEP_DISABLE() (RCC->AHB2LPENR &= ~(RCC_AHB2LPENR_OTGFSLPEN)) #define __HAL_RCC_RNG_CLK_SLEEP_ENABLE() (RCC->AHB2LPENR |= (RCC_AHB2LPENR_RNGLPEN)) #define __HAL_RCC_RNG_CLK_SLEEP_DISABLE() (RCC->AHB2LPENR &= ~(RCC_AHB2LPENR_RNGLPEN)) #define __HAL_RCC_DCMI_CLK_SLEEP_ENABLE() (RCC->AHB2LPENR |= (RCC_AHB2LPENR_DCMILPEN)) #define __HAL_RCC_DCMI_CLK_SLEEP_DISABLE() (RCC->AHB2LPENR &= ~(RCC_AHB2LPENR_DCMILPEN)) #if defined(STM32F437xx)|| defined(STM32F439xx) || defined(STM32F479xx) #define __HAL_RCC_CRYP_CLK_SLEEP_ENABLE() (RCC->AHB2LPENR |= (RCC_AHB2LPENR_CRYPLPEN)) #define __HAL_RCC_HASH_CLK_SLEEP_ENABLE() (RCC->AHB2LPENR |= (RCC_AHB2LPENR_HASHLPEN)) #define __HAL_RCC_CRYP_CLK_SLEEP_DISABLE() (RCC->AHB2LPENR &= ~(RCC_AHB2LPENR_CRYPLPEN)) #define __HAL_RCC_HASH_CLK_SLEEP_DISABLE() (RCC->AHB2LPENR &= ~(RCC_AHB2LPENR_HASHLPEN)) #endif /* STM32F437xx || STM32F439xx || STM32F479xx */ /** * @} */ /** @defgroup RCCEx_AHB3_LowPower_Enable_Disable AHB3 Peripheral Low Power Enable Disable * @brief Enable or disable the AHB3 peripheral clock during Low Power (Sleep) mode. * @note Peripheral clock gating in SLEEP mode can be used to further reduce * power consumption. * @note After wakeup from SLEEP mode, the peripheral clock is enabled again. * @note By default, all peripheral clocks are enabled during SLEEP mode. */ #define __HAL_RCC_FMC_CLK_SLEEP_ENABLE() (RCC->AHB3LPENR |= (RCC_AHB3LPENR_FMCLPEN)) #define __HAL_RCC_FMC_CLK_SLEEP_DISABLE() (RCC->AHB3LPENR &= ~(RCC_AHB3LPENR_FMCLPEN)) #if defined(STM32F469xx) || defined(STM32F479xx) #define __HAL_RCC_QSPI_CLK_SLEEP_ENABLE() (RCC->AHB3LPENR |= (RCC_AHB3LPENR_QSPILPEN)) #define __HAL_RCC_QSPI_CLK_SLEEP_DISABLE() (RCC->AHB3LPENR &= ~(RCC_AHB3LPENR_QSPILPEN)) #endif /* STM32F469xx || STM32F479xx */ /** * @} */ /** @defgroup RCCEx_APB1_LowPower_Enable_Disable APB1 Peripheral Low Power Enable Disable * @brief Enable or disable the APB1 peripheral clock during Low Power (Sleep) mode. * @note Peripheral clock gating in SLEEP mode can be used to further reduce * power consumption. * @note After wakeup from SLEEP mode, the peripheral clock is enabled again. * @note By default, all peripheral clocks are enabled during SLEEP mode. */ #define __HAL_RCC_TIM6_CLK_SLEEP_ENABLE() (RCC->APB1LPENR |= (RCC_APB1LPENR_TIM6LPEN)) #define __HAL_RCC_TIM7_CLK_SLEEP_ENABLE() (RCC->APB1LPENR |= (RCC_APB1LPENR_TIM7LPEN)) #define __HAL_RCC_TIM12_CLK_SLEEP_ENABLE() (RCC->APB1LPENR |= (RCC_APB1LPENR_TIM12LPEN)) #define __HAL_RCC_TIM13_CLK_SLEEP_ENABLE() (RCC->APB1LPENR |= (RCC_APB1LPENR_TIM13LPEN)) #define __HAL_RCC_TIM14_CLK_SLEEP_ENABLE() (RCC->APB1LPENR |= (RCC_APB1LPENR_TIM14LPEN)) #define __HAL_RCC_USART3_CLK_SLEEP_ENABLE() (RCC->APB1LPENR |= (RCC_APB1LPENR_USART3LPEN)) #define __HAL_RCC_UART4_CLK_SLEEP_ENABLE() (RCC->APB1LPENR |= (RCC_APB1LPENR_UART4LPEN)) #define __HAL_RCC_UART5_CLK_SLEEP_ENABLE() (RCC->APB1LPENR |= (RCC_APB1LPENR_UART5LPEN)) #define __HAL_RCC_CAN1_CLK_SLEEP_ENABLE() (RCC->APB1LPENR |= (RCC_APB1LPENR_CAN1LPEN)) #define __HAL_RCC_CAN2_CLK_SLEEP_ENABLE() (RCC->APB1LPENR |= (RCC_APB1LPENR_CAN2LPEN)) #define __HAL_RCC_DAC_CLK_SLEEP_ENABLE() (RCC->APB1LPENR |= (RCC_APB1LPENR_DACLPEN)) #define __HAL_RCC_UART7_CLK_SLEEP_ENABLE() (RCC->APB1LPENR |= (RCC_APB1LPENR_UART7LPEN)) #define __HAL_RCC_UART8_CLK_SLEEP_ENABLE() (RCC->APB1LPENR |= (RCC_APB1LPENR_UART8LPEN)) #define __HAL_RCC_TIM2_CLK_SLEEP_ENABLE() (RCC->APB1LPENR |= (RCC_APB1LPENR_TIM2LPEN)) #define __HAL_RCC_TIM3_CLK_SLEEP_ENABLE() (RCC->APB1LPENR |= (RCC_APB1LPENR_TIM3LPEN)) #define __HAL_RCC_TIM4_CLK_SLEEP_ENABLE() (RCC->APB1LPENR |= (RCC_APB1LPENR_TIM4LPEN)) #define __HAL_RCC_SPI3_CLK_SLEEP_ENABLE() (RCC->APB1LPENR |= (RCC_APB1LPENR_SPI3LPEN)) #define __HAL_RCC_I2C3_CLK_SLEEP_ENABLE() (RCC->APB1LPENR |= (RCC_APB1LPENR_I2C3LPEN)) #define __HAL_RCC_TIM2_CLK_SLEEP_DISABLE() (RCC->APB1LPENR &= ~(RCC_APB1LPENR_TIM2LPEN)) #define __HAL_RCC_TIM3_CLK_SLEEP_DISABLE() (RCC->APB1LPENR &= ~(RCC_APB1LPENR_TIM3LPEN)) #define __HAL_RCC_TIM4_CLK_SLEEP_DISABLE() (RCC->APB1LPENR &= ~(RCC_APB1LPENR_TIM4LPEN)) #define __HAL_RCC_SPI3_CLK_SLEEP_DISABLE() (RCC->APB1LPENR &= ~(RCC_APB1LPENR_SPI3LPEN)) #define __HAL_RCC_I2C3_CLK_SLEEP_DISABLE() (RCC->APB1LPENR &= ~(RCC_APB1LPENR_I2C3LPEN)) #define __HAL_RCC_TIM6_CLK_SLEEP_DISABLE() (RCC->APB1LPENR &= ~(RCC_APB1LPENR_TIM6LPEN)) #define __HAL_RCC_TIM7_CLK_SLEEP_DISABLE() (RCC->APB1LPENR &= ~(RCC_APB1LPENR_TIM7LPEN)) #define __HAL_RCC_TIM12_CLK_SLEEP_DISABLE() (RCC->APB1LPENR &= ~(RCC_APB1LPENR_TIM12LPEN)) #define __HAL_RCC_TIM13_CLK_SLEEP_DISABLE() (RCC->APB1LPENR &= ~(RCC_APB1LPENR_TIM13LPEN)) #define __HAL_RCC_TIM14_CLK_SLEEP_DISABLE() (RCC->APB1LPENR &= ~(RCC_APB1LPENR_TIM14LPEN)) #define __HAL_RCC_USART3_CLK_SLEEP_DISABLE() (RCC->APB1LPENR &= ~(RCC_APB1LPENR_USART3LPEN)) #define __HAL_RCC_UART4_CLK_SLEEP_DISABLE() (RCC->APB1LPENR &= ~(RCC_APB1LPENR_UART4LPEN)) #define __HAL_RCC_UART5_CLK_SLEEP_DISABLE() (RCC->APB1LPENR &= ~(RCC_APB1LPENR_UART5LPEN)) #define __HAL_RCC_CAN1_CLK_SLEEP_DISABLE() (RCC->APB1LPENR &= ~(RCC_APB1LPENR_CAN1LPEN)) #define __HAL_RCC_CAN2_CLK_SLEEP_DISABLE() (RCC->APB1LPENR &= ~(RCC_APB1LPENR_CAN2LPEN)) #define __HAL_RCC_DAC_CLK_SLEEP_DISABLE() (RCC->APB1LPENR &= ~(RCC_APB1LPENR_DACLPEN)) #define __HAL_RCC_UART7_CLK_SLEEP_DISABLE() (RCC->APB1LPENR &= ~(RCC_APB1LPENR_UART7LPEN)) #define __HAL_RCC_UART8_CLK_SLEEP_DISABLE() (RCC->APB1LPENR &= ~(RCC_APB1LPENR_UART8LPEN)) /** * @} */ /** @defgroup RCCEx_APB2_LowPower_Enable_Disable APB2 Peripheral Low Power Enable Disable * @brief Enable or disable the APB2 peripheral clock during Low Power (Sleep) mode. * @note Peripheral clock gating in SLEEP mode can be used to further reduce * power consumption. * @note After wakeup from SLEEP mode, the peripheral clock is enabled again. * @note By default, all peripheral clocks are enabled during SLEEP mode. */ #define __HAL_RCC_TIM8_CLK_SLEEP_ENABLE() (RCC->APB2LPENR |= (RCC_APB2LPENR_TIM8LPEN)) #define __HAL_RCC_ADC2_CLK_SLEEP_ENABLE() (RCC->APB2LPENR |= (RCC_APB2LPENR_ADC2LPEN)) #define __HAL_RCC_ADC3_CLK_SLEEP_ENABLE() (RCC->APB2LPENR |= (RCC_APB2LPENR_ADC3LPEN)) #define __HAL_RCC_SPI5_CLK_SLEEP_ENABLE() (RCC->APB2LPENR |= (RCC_APB2LPENR_SPI5LPEN)) #define __HAL_RCC_SPI6_CLK_SLEEP_ENABLE() (RCC->APB2LPENR |= (RCC_APB2LPENR_SPI6LPEN)) #define __HAL_RCC_SAI1_CLK_SLEEP_ENABLE() (RCC->APB2LPENR |= (RCC_APB2LPENR_SAI1LPEN)) #define __HAL_RCC_SDIO_CLK_SLEEP_ENABLE() (RCC->APB2LPENR |= (RCC_APB2LPENR_SDIOLPEN)) #define __HAL_RCC_SPI4_CLK_SLEEP_ENABLE() (RCC->APB2LPENR |= (RCC_APB2LPENR_SPI4LPEN)) #define __HAL_RCC_TIM10_CLK_SLEEP_ENABLE()(RCC->APB2LPENR |= (RCC_APB2LPENR_TIM10LPEN)) #define __HAL_RCC_SDIO_CLK_SLEEP_DISABLE() (RCC->APB2LPENR &= ~(RCC_APB2LPENR_SDIOLPEN)) #define __HAL_RCC_SPI4_CLK_SLEEP_DISABLE() (RCC->APB2LPENR &= ~(RCC_APB2LPENR_SPI4LPEN)) #define __HAL_RCC_TIM10_CLK_SLEEP_DISABLE()(RCC->APB2LPENR &= ~(RCC_APB2LPENR_TIM10LPEN)) #define __HAL_RCC_TIM8_CLK_SLEEP_DISABLE() (RCC->APB2LPENR &= ~(RCC_APB2LPENR_TIM8LPEN)) #define __HAL_RCC_ADC2_CLK_SLEEP_DISABLE() (RCC->APB2LPENR &= ~(RCC_APB2LPENR_ADC2LPEN)) #define __HAL_RCC_ADC3_CLK_SLEEP_DISABLE() (RCC->APB2LPENR &= ~(RCC_APB2LPENR_ADC3LPEN)) #define __HAL_RCC_SPI5_CLK_SLEEP_DISABLE() (RCC->APB2LPENR &= ~(RCC_APB2LPENR_SPI5LPEN)) #define __HAL_RCC_SPI6_CLK_SLEEP_DISABLE() (RCC->APB2LPENR &= ~(RCC_APB2LPENR_SPI6LPEN)) #define __HAL_RCC_SAI1_CLK_SLEEP_DISABLE() (RCC->APB2LPENR &= ~(RCC_APB2LPENR_SAI1LPEN)) #if defined(STM32F429xx)|| defined(STM32F439xx) || defined(STM32F469xx) || defined(STM32F479xx) #define __HAL_RCC_LTDC_CLK_SLEEP_ENABLE() (RCC->APB2LPENR |= (RCC_APB2LPENR_LTDCLPEN)) #define __HAL_RCC_LTDC_CLK_SLEEP_DISABLE() (RCC->APB2LPENR &= ~(RCC_APB2LPENR_LTDCLPEN)) #endif /* STM32F429xx || STM32F439xx || STM32F469xx || STM32F479xx */ #if defined(STM32F469xx) || defined(STM32F479xx) #define __HAL_RCC_DSI_CLK_SLEEP_ENABLE() (RCC->APB2LPENR |= (RCC_APB2LPENR_DSILPEN)) #define __HAL_RCC_DSI_CLK_SLEEP_DISABLE() (RCC->APB2LPENR &= ~(RCC_APB2LPENR_DSILPEN)) #endif /* STM32F469xx || STM32F479xx */ /** * @} */ #endif /* STM32F427xx || STM32F437xx || STM32F429xx|| STM32F439xx || STM32F469xx || STM32F479xx */ /*----------------------------------------------------------------------------*/ /*----------------------------------- STM32F40xxx/STM32F41xxx-----------------*/ #if defined(STM32F405xx) || defined(STM32F415xx) || defined(STM32F407xx)|| defined(STM32F417xx) /** @defgroup RCCEx_AHB1_Clock_Enable_Disable AHB1 Peripheral Clock Enable Disable * @brief Enables or disables the AHB1 peripheral clock. * @note After reset, the peripheral clock (used for registers read/write access) * is disabled and the application software has to enable this clock before * using it. */ #define __HAL_RCC_BKPSRAM_CLK_ENABLE() do { \ __IO uint32_t tmpreg; \ SET_BIT(RCC->AHB1ENR, RCC_AHB1ENR_BKPSRAMEN);\ /* Delay after an RCC peripheral clock enabling */ \ tmpreg = READ_BIT(RCC->AHB1ENR, RCC_AHB1ENR_BKPSRAMEN);\ UNUSED(tmpreg); \ } while(0) #define __HAL_RCC_CCMDATARAMEN_CLK_ENABLE() do { \ __IO uint32_t tmpreg; \ SET_BIT(RCC->AHB1ENR, RCC_AHB1ENR_CCMDATARAMEN);\ /* Delay after an RCC peripheral clock enabling */ \ tmpreg = READ_BIT(RCC->AHB1ENR, RCC_AHB1ENR_CCMDATARAMEN);\ UNUSED(tmpreg); \ } while(0) #define __HAL_RCC_CRC_CLK_ENABLE() do { \ __IO uint32_t tmpreg; \ SET_BIT(RCC->AHB1ENR, RCC_AHB1ENR_CRCEN);\ /* Delay after an RCC peripheral clock enabling */ \ tmpreg = READ_BIT(RCC->AHB1ENR, RCC_AHB1ENR_CRCEN);\ UNUSED(tmpreg); \ } while(0) #define __HAL_RCC_GPIOD_CLK_ENABLE() do { \ __IO uint32_t tmpreg; \ SET_BIT(RCC->AHB1ENR, RCC_AHB1ENR_GPIODEN);\ /* Delay after an RCC peripheral clock enabling */ \ tmpreg = READ_BIT(RCC->AHB1ENR, RCC_AHB1ENR_GPIODEN);\ UNUSED(tmpreg); \ } while(0) #define __HAL_RCC_GPIOE_CLK_ENABLE() do { \ __IO uint32_t tmpreg; \ SET_BIT(RCC->AHB1ENR, RCC_AHB1ENR_GPIOEEN);\ /* Delay after an RCC peripheral clock enabling */ \ tmpreg = READ_BIT(RCC->AHB1ENR, RCC_AHB1ENR_GPIOEEN);\ UNUSED(tmpreg); \ } while(0) #define __HAL_RCC_GPIOI_CLK_ENABLE() do { \ __IO uint32_t tmpreg; \ SET_BIT(RCC->AHB1ENR, RCC_AHB1ENR_GPIOIEN);\ /* Delay after an RCC peripheral clock enabling */ \ tmpreg = READ_BIT(RCC->AHB1ENR, RCC_AHB1ENR_GPIOIEN);\ UNUSED(tmpreg); \ } while(0) #define __HAL_RCC_GPIOF_CLK_ENABLE() do { \ __IO uint32_t tmpreg; \ SET_BIT(RCC->AHB1ENR, RCC_AHB1ENR_GPIOFEN);\ /* Delay after an RCC peripheral clock enabling */ \ tmpreg = READ_BIT(RCC->AHB1ENR, RCC_AHB1ENR_GPIOFEN);\ UNUSED(tmpreg); \ } while(0) #define __HAL_RCC_GPIOG_CLK_ENABLE() do { \ __IO uint32_t tmpreg; \ SET_BIT(RCC->AHB1ENR, RCC_AHB1ENR_GPIOGEN);\ /* Delay after an RCC peripheral clock enabling */ \ tmpreg = READ_BIT(RCC->AHB1ENR, RCC_AHB1ENR_GPIOGEN);\ UNUSED(tmpreg); \ } while(0) #define __HAL_RCC_USB_OTG_HS_CLK_ENABLE() do { \ __IO uint32_t tmpreg; \ SET_BIT(RCC->AHB1ENR, RCC_AHB1ENR_OTGHSEN);\ /* Delay after an RCC peripheral clock enabling */ \ tmpreg = READ_BIT(RCC->AHB1ENR, RCC_AHB1ENR_OTGHSEN);\ UNUSED(tmpreg); \ } while(0) #define __HAL_RCC_USB_OTG_HS_ULPI_CLK_ENABLE() do { \ __IO uint32_t tmpreg; \ SET_BIT(RCC->AHB1ENR, RCC_AHB1ENR_OTGHSULPIEN);\ /* Delay after an RCC peripheral clock enabling */ \ tmpreg = READ_BIT(RCC->AHB1ENR, RCC_AHB1ENR_OTGHSULPIEN);\ UNUSED(tmpreg); \ } while(0) #define __HAL_RCC_GPIOD_CLK_DISABLE() (RCC->AHB1ENR &= ~(RCC_AHB1ENR_GPIODEN)) #define __HAL_RCC_GPIOE_CLK_DISABLE() (RCC->AHB1ENR &= ~(RCC_AHB1ENR_GPIOEEN)) #define __HAL_RCC_GPIOF_CLK_DISABLE() (RCC->AHB1ENR &= ~(RCC_AHB1ENR_GPIOFEN)) #define __HAL_RCC_GPIOG_CLK_DISABLE() (RCC->AHB1ENR &= ~(RCC_AHB1ENR_GPIOGEN)) #define __HAL_RCC_GPIOI_CLK_DISABLE() (RCC->AHB1ENR &= ~(RCC_AHB1ENR_GPIOIEN)) #define __HAL_RCC_USB_OTG_HS_CLK_DISABLE() (RCC->AHB1ENR &= ~(RCC_AHB1ENR_OTGHSEN)) #define __HAL_RCC_USB_OTG_HS_ULPI_CLK_DISABLE() (RCC->AHB1ENR &= ~(RCC_AHB1ENR_OTGHSULPIEN)) #define __HAL_RCC_BKPSRAM_CLK_DISABLE() (RCC->AHB1ENR &= ~(RCC_AHB1ENR_BKPSRAMEN)) #define __HAL_RCC_CCMDATARAMEN_CLK_DISABLE() (RCC->AHB1ENR &= ~(RCC_AHB1ENR_CCMDATARAMEN)) #define __HAL_RCC_CRC_CLK_DISABLE() (RCC->AHB1ENR &= ~(RCC_AHB1ENR_CRCEN)) #if defined(STM32F407xx)|| defined(STM32F417xx) /** * @brief Enable ETHERNET clock. */ #define __HAL_RCC_ETHMAC_CLK_ENABLE() do { \ __IO uint32_t tmpreg; \ SET_BIT(RCC->AHB1ENR, RCC_AHB1ENR_ETHMACEN);\ /* Delay after an RCC peripheral clock enabling */ \ tmpreg = READ_BIT(RCC->AHB1ENR, RCC_AHB1ENR_ETHMACEN);\ UNUSED(tmpreg); \ } while(0) #define __HAL_RCC_ETHMACTX_CLK_ENABLE() do { \ __IO uint32_t tmpreg; \ SET_BIT(RCC->AHB1ENR, RCC_AHB1ENR_ETHMACTXEN);\ /* Delay after an RCC peripheral clock enabling */ \ tmpreg = READ_BIT(RCC->AHB1ENR, RCC_AHB1ENR_ETHMACTXEN);\ UNUSED(tmpreg); \ } while(0) #define __HAL_RCC_ETHMACRX_CLK_ENABLE() do { \ __IO uint32_t tmpreg; \ SET_BIT(RCC->AHB1ENR, RCC_AHB1ENR_ETHMACRXEN);\ /* Delay after an RCC peripheral clock enabling */ \ tmpreg = READ_BIT(RCC->AHB1ENR, RCC_AHB1ENR_ETHMACRXEN);\ UNUSED(tmpreg); \ } while(0) #define __HAL_RCC_ETHMACPTP_CLK_ENABLE() do { \ __IO uint32_t tmpreg; \ SET_BIT(RCC->AHB1ENR, RCC_AHB1ENR_ETHMACPTPEN);\ /* Delay after an RCC peripheral clock enabling */ \ tmpreg = READ_BIT(RCC->AHB1ENR, RCC_AHB1ENR_ETHMACPTPEN);\ UNUSED(tmpreg); \ } while(0) #define __HAL_RCC_ETH_CLK_ENABLE() do { \ __HAL_RCC_ETHMAC_CLK_ENABLE(); \ __HAL_RCC_ETHMACTX_CLK_ENABLE(); \ __HAL_RCC_ETHMACRX_CLK_ENABLE(); \ } while(0) /** * @brief Disable ETHERNET clock. */ #define __HAL_RCC_ETHMAC_CLK_DISABLE() (RCC->AHB1ENR &= ~(RCC_AHB1ENR_ETHMACEN)) #define __HAL_RCC_ETHMACTX_CLK_DISABLE() (RCC->AHB1ENR &= ~(RCC_AHB1ENR_ETHMACTXEN)) #define __HAL_RCC_ETHMACRX_CLK_DISABLE() (RCC->AHB1ENR &= ~(RCC_AHB1ENR_ETHMACRXEN)) #define __HAL_RCC_ETHMACPTP_CLK_DISABLE() (RCC->AHB1ENR &= ~(RCC_AHB1ENR_ETHMACPTPEN)) #define __HAL_RCC_ETH_CLK_DISABLE() do { \ __HAL_RCC_ETHMACTX_CLK_DISABLE(); \ __HAL_RCC_ETHMACRX_CLK_DISABLE(); \ __HAL_RCC_ETHMAC_CLK_DISABLE(); \ } while(0) #endif /* STM32F407xx || STM32F417xx */ /** * @} */ /** @defgroup RCCEx_AHB2_Clock_Enable_Disable AHB2 Peripheral Clock Enable Disable * @brief Enable or disable the AHB2 peripheral clock. * @note After reset, the peripheral clock (used for registers read/write access) * is disabled and the application software has to enable this clock before * using it. */ #define __HAL_RCC_USB_OTG_FS_CLK_ENABLE() do {(RCC->AHB2ENR |= (RCC_AHB2ENR_OTGFSEN));\ __HAL_RCC_SYSCFG_CLK_ENABLE();\ }while(0) #define __HAL_RCC_USB_OTG_FS_CLK_DISABLE() do { (RCC->AHB2ENR &= ~(RCC_AHB2ENR_OTGFSEN));\ __HAL_RCC_SYSCFG_CLK_DISABLE();\ }while(0) #define __HAL_RCC_RNG_CLK_ENABLE() do { \ __IO uint32_t tmpreg; \ SET_BIT(RCC->AHB2ENR, RCC_AHB2ENR_RNGEN);\ /* Delay after an RCC peripheral clock enabling */ \ tmpreg = READ_BIT(RCC->AHB2ENR, RCC_AHB2ENR_RNGEN);\ UNUSED(tmpreg); \ } while(0) #define __HAL_RCC_RNG_CLK_DISABLE() (RCC->AHB2ENR &= ~(RCC_AHB2ENR_RNGEN)) #if defined(STM32F407xx)|| defined(STM32F417xx) #define __HAL_RCC_DCMI_CLK_ENABLE() do { \ __IO uint32_t tmpreg; \ SET_BIT(RCC->AHB2ENR, RCC_AHB2ENR_DCMIEN);\ /* Delay after an RCC peripheral clock enabling */ \ tmpreg = READ_BIT(RCC->AHB2ENR, RCC_AHB2ENR_DCMIEN);\ UNUSED(tmpreg); \ } while(0) #define __HAL_RCC_DCMI_CLK_DISABLE() (RCC->AHB2ENR &= ~(RCC_AHB2ENR_DCMIEN)) #endif /* STM32F407xx || STM32F417xx */ #if defined(STM32F415xx) || defined(STM32F417xx) #define __HAL_RCC_CRYP_CLK_ENABLE() do { \ __IO uint32_t tmpreg; \ SET_BIT(RCC->AHB2ENR, RCC_AHB2ENR_CRYPEN);\ /* Delay after an RCC peripheral clock enabling */ \ tmpreg = READ_BIT(RCC->AHB2ENR, RCC_AHB2ENR_CRYPEN);\ UNUSED(tmpreg); \ } while(0) #define __HAL_RCC_HASH_CLK_ENABLE() do { \ __IO uint32_t tmpreg; \ SET_BIT(RCC->AHB2ENR, RCC_AHB2ENR_HASHEN);\ /* Delay after an RCC peripheral clock enabling */ \ tmpreg = READ_BIT(RCC->AHB2ENR, RCC_AHB2ENR_HASHEN);\ UNUSED(tmpreg); \ } while(0) #define __HAL_RCC_CRYP_CLK_DISABLE() (RCC->AHB2ENR &= ~(RCC_AHB2ENR_CRYPEN)) #define __HAL_RCC_HASH_CLK_DISABLE() (RCC->AHB2ENR &= ~(RCC_AHB2ENR_HASHEN)) #endif /* STM32F415xx || STM32F417xx */ /** * @} */ /** @defgroup RCCEx_AHB3_Clock_Enable_Disable AHB3 Peripheral Clock Enable Disable * @brief Enables or disables the AHB3 peripheral clock. * @note After reset, the peripheral clock (used for registers read/write access) * is disabled and the application software has to enable this clock before * using it. */ #define __HAL_RCC_FSMC_CLK_ENABLE() do { \ __IO uint32_t tmpreg; \ SET_BIT(RCC->AHB3ENR, RCC_AHB3ENR_FSMCEN);\ /* Delay after an RCC peripheral clock enabling */ \ tmpreg = READ_BIT(RCC->AHB3ENR, RCC_AHB3ENR_FSMCEN);\ UNUSED(tmpreg); \ } while(0) #define __HAL_RCC_FSMC_CLK_DISABLE() (RCC->AHB3ENR &= ~(RCC_AHB3ENR_FSMCEN)) /** * @} */ /** @defgroup RCCEx_APB1_Clock_Enable_Disable APB1 Peripheral Clock Enable Disable * @brief Enable or disable the Low Speed APB (APB1) peripheral clock. * @note After reset, the peripheral clock (used for registers read/write access) * is disabled and the application software has to enable this clock before * using it. */ #define __HAL_RCC_TIM6_CLK_ENABLE() do { \ __IO uint32_t tmpreg; \ SET_BIT(RCC->APB1ENR, RCC_APB1ENR_TIM6EN);\ /* Delay after an RCC peripheral clock enabling */ \ tmpreg = READ_BIT(RCC->APB1ENR, RCC_APB1ENR_TIM6EN);\ UNUSED(tmpreg); \ } while(0) #define __HAL_RCC_TIM7_CLK_ENABLE() do { \ __IO uint32_t tmpreg; \ SET_BIT(RCC->APB1ENR, RCC_APB1ENR_TIM7EN);\ /* Delay after an RCC peripheral clock enabling */ \ tmpreg = READ_BIT(RCC->APB1ENR, RCC_APB1ENR_TIM7EN);\ UNUSED(tmpreg); \ } while(0) #define __HAL_RCC_TIM12_CLK_ENABLE() do { \ __IO uint32_t tmpreg; \ SET_BIT(RCC->APB1ENR, RCC_APB1ENR_TIM12EN);\ /* Delay after an RCC peripheral clock enabling */ \ tmpreg = READ_BIT(RCC->APB1ENR, RCC_APB1ENR_TIM12EN);\ UNUSED(tmpreg); \ } while(0) #define __HAL_RCC_TIM13_CLK_ENABLE() do { \ __IO uint32_t tmpreg; \ SET_BIT(RCC->APB1ENR, RCC_APB1ENR_TIM13EN);\ /* Delay after an RCC peripheral clock enabling */ \ tmpreg = READ_BIT(RCC->APB1ENR, RCC_APB1ENR_TIM13EN);\ UNUSED(tmpreg); \ } while(0) #define __HAL_RCC_TIM14_CLK_ENABLE() do { \ __IO uint32_t tmpreg; \ SET_BIT(RCC->APB1ENR, RCC_APB1ENR_TIM14EN);\ /* Delay after an RCC peripheral clock enabling */ \ tmpreg = READ_BIT(RCC->APB1ENR, RCC_APB1ENR_TIM14EN);\ UNUSED(tmpreg); \ } while(0) #define __HAL_RCC_USART3_CLK_ENABLE() do { \ __IO uint32_t tmpreg; \ SET_BIT(RCC->APB1ENR, RCC_APB1ENR_USART3EN);\ /* Delay after an RCC peripheral clock enabling */ \ tmpreg = READ_BIT(RCC->APB1ENR, RCC_APB1ENR_USART3EN);\ UNUSED(tmpreg); \ } while(0) #define __HAL_RCC_UART4_CLK_ENABLE() do { \ __IO uint32_t tmpreg; \ SET_BIT(RCC->APB1ENR, RCC_APB1ENR_UART4EN);\ /* Delay after an RCC peripheral clock enabling */ \ tmpreg = READ_BIT(RCC->APB1ENR, RCC_APB1ENR_UART4EN);\ UNUSED(tmpreg); \ } while(0) #define __HAL_RCC_UART5_CLK_ENABLE() do { \ __IO uint32_t tmpreg; \ SET_BIT(RCC->APB1ENR, RCC_APB1ENR_UART5EN);\ /* Delay after an RCC peripheral clock enabling */ \ tmpreg = READ_BIT(RCC->APB1ENR, RCC_APB1ENR_UART5EN);\ UNUSED(tmpreg); \ } while(0) #define __HAL_RCC_CAN1_CLK_ENABLE() do { \ __IO uint32_t tmpreg; \ SET_BIT(RCC->APB1ENR, RCC_APB1ENR_CAN1EN);\ /* Delay after an RCC peripheral clock enabling */ \ tmpreg = READ_BIT(RCC->APB1ENR, RCC_APB1ENR_CAN1EN);\ UNUSED(tmpreg); \ } while(0) #define __HAL_RCC_CAN2_CLK_ENABLE() do { \ __IO uint32_t tmpreg; \ SET_BIT(RCC->APB1ENR, RCC_APB1ENR_CAN2EN);\ /* Delay after an RCC peripheral clock enabling */ \ tmpreg = READ_BIT(RCC->APB1ENR, RCC_APB1ENR_CAN2EN);\ UNUSED(tmpreg); \ } while(0) #define __HAL_RCC_DAC_CLK_ENABLE() do { \ __IO uint32_t tmpreg; \ SET_BIT(RCC->APB1ENR, RCC_APB1ENR_DACEN);\ /* Delay after an RCC peripheral clock enabling */ \ tmpreg = READ_BIT(RCC->APB1ENR, RCC_APB1ENR_DACEN);\ UNUSED(tmpreg); \ } while(0) #define __HAL_RCC_TIM2_CLK_ENABLE() do { \ __IO uint32_t tmpreg; \ SET_BIT(RCC->APB1ENR, RCC_APB1ENR_TIM2EN);\ /* Delay after an RCC peripheral clock enabling */ \ tmpreg = READ_BIT(RCC->APB1ENR, RCC_APB1ENR_TIM2EN);\ UNUSED(tmpreg); \ } while(0) #define __HAL_RCC_TIM3_CLK_ENABLE() do { \ __IO uint32_t tmpreg; \ SET_BIT(RCC->APB1ENR, RCC_APB1ENR_TIM3EN);\ /* Delay after an RCC peripheral clock enabling */ \ tmpreg = READ_BIT(RCC->APB1ENR, RCC_APB1ENR_TIM3EN);\ UNUSED(tmpreg); \ } while(0) #define __HAL_RCC_TIM4_CLK_ENABLE() do { \ __IO uint32_t tmpreg; \ SET_BIT(RCC->APB1ENR, RCC_APB1ENR_TIM4EN);\ /* Delay after an RCC peripheral clock enabling */ \ tmpreg = READ_BIT(RCC->APB1ENR, RCC_APB1ENR_TIM4EN);\ UNUSED(tmpreg); \ } while(0) #define __HAL_RCC_SPI3_CLK_ENABLE() do { \ __IO uint32_t tmpreg; \ SET_BIT(RCC->APB1ENR, RCC_APB1ENR_SPI3EN);\ /* Delay after an RCC peripheral clock enabling */ \ tmpreg = READ_BIT(RCC->APB1ENR, RCC_APB1ENR_SPI3EN);\ UNUSED(tmpreg); \ } while(0) #define __HAL_RCC_I2C3_CLK_ENABLE() do { \ __IO uint32_t tmpreg; \ SET_BIT(RCC->APB1ENR, RCC_APB1ENR_I2C3EN);\ /* Delay after an RCC peripheral clock enabling */ \ tmpreg = READ_BIT(RCC->APB1ENR, RCC_APB1ENR_I2C3EN);\ UNUSED(tmpreg); \ } while(0) #define __HAL_RCC_TIM2_CLK_DISABLE() (RCC->APB1ENR &= ~(RCC_APB1ENR_TIM2EN)) #define __HAL_RCC_TIM3_CLK_DISABLE() (RCC->APB1ENR &= ~(RCC_APB1ENR_TIM3EN)) #define __HAL_RCC_TIM4_CLK_DISABLE() (RCC->APB1ENR &= ~(RCC_APB1ENR_TIM4EN)) #define __HAL_RCC_SPI3_CLK_DISABLE() (RCC->APB1ENR &= ~(RCC_APB1ENR_SPI3EN)) #define __HAL_RCC_I2C3_CLK_DISABLE() (RCC->APB1ENR &= ~(RCC_APB1ENR_I2C3EN)) #define __HAL_RCC_TIM6_CLK_DISABLE() (RCC->APB1ENR &= ~(RCC_APB1ENR_TIM6EN)) #define __HAL_RCC_TIM7_CLK_DISABLE() (RCC->APB1ENR &= ~(RCC_APB1ENR_TIM7EN)) #define __HAL_RCC_TIM12_CLK_DISABLE() (RCC->APB1ENR &= ~(RCC_APB1ENR_TIM12EN)) #define __HAL_RCC_TIM13_CLK_DISABLE() (RCC->APB1ENR &= ~(RCC_APB1ENR_TIM13EN)) #define __HAL_RCC_TIM14_CLK_DISABLE() (RCC->APB1ENR &= ~(RCC_APB1ENR_TIM14EN)) #define __HAL_RCC_USART3_CLK_DISABLE() (RCC->APB1ENR &= ~(RCC_APB1ENR_USART3EN)) #define __HAL_RCC_UART4_CLK_DISABLE() (RCC->APB1ENR &= ~(RCC_APB1ENR_UART4EN)) #define __HAL_RCC_UART5_CLK_DISABLE() (RCC->APB1ENR &= ~(RCC_APB1ENR_UART5EN)) #define __HAL_RCC_CAN1_CLK_DISABLE() (RCC->APB1ENR &= ~(RCC_APB1ENR_CAN1EN)) #define __HAL_RCC_CAN2_CLK_DISABLE() (RCC->APB1ENR &= ~(RCC_APB1ENR_CAN2EN)) #define __HAL_RCC_DAC_CLK_DISABLE() (RCC->APB1ENR &= ~(RCC_APB1ENR_DACEN)) /** * @} */ /** @defgroup RCCEx_APB2_Clock_Enable_Disable APB2 Peripheral Clock Enable Disable * @brief Enable or disable the High Speed APB (APB2) peripheral clock. * @note After reset, the peripheral clock (used for registers read/write access) * is disabled and the application software has to enable this clock before * using it. */ #define __HAL_RCC_TIM8_CLK_ENABLE() do { \ __IO uint32_t tmpreg; \ SET_BIT(RCC->APB2ENR, RCC_APB2ENR_TIM8EN);\ /* Delay after an RCC peripheral clock enabling */ \ tmpreg = READ_BIT(RCC->APB2ENR, RCC_APB2ENR_TIM8EN);\ UNUSED(tmpreg); \ } while(0) #define __HAL_RCC_ADC2_CLK_ENABLE() do { \ __IO uint32_t tmpreg; \ SET_BIT(RCC->APB2ENR, RCC_APB2ENR_ADC2EN);\ /* Delay after an RCC peripheral clock enabling */ \ tmpreg = READ_BIT(RCC->APB2ENR, RCC_APB2ENR_ADC2EN);\ UNUSED(tmpreg); \ } while(0) #define __HAL_RCC_ADC3_CLK_ENABLE() do { \ __IO uint32_t tmpreg; \ SET_BIT(RCC->APB2ENR, RCC_APB2ENR_ADC3EN);\ /* Delay after an RCC peripheral clock enabling */ \ tmpreg = READ_BIT(RCC->APB2ENR, RCC_APB2ENR_ADC3EN);\ UNUSED(tmpreg); \ } while(0) #define __HAL_RCC_SDIO_CLK_ENABLE() do { \ __IO uint32_t tmpreg; \ SET_BIT(RCC->APB2ENR, RCC_APB2ENR_SDIOEN);\ /* Delay after an RCC peripheral clock enabling */ \ tmpreg = READ_BIT(RCC->APB2ENR, RCC_APB2ENR_SDIOEN);\ UNUSED(tmpreg); \ } while(0) #define __HAL_RCC_SPI4_CLK_ENABLE() do { \ __IO uint32_t tmpreg; \ SET_BIT(RCC->APB2ENR, RCC_APB2ENR_SPI4EN);\ /* Delay after an RCC peripheral clock enabling */ \ tmpreg = READ_BIT(RCC->APB2ENR, RCC_APB2ENR_SPI4EN);\ UNUSED(tmpreg); \ } while(0) #define __HAL_RCC_TIM10_CLK_ENABLE() do { \ __IO uint32_t tmpreg; \ SET_BIT(RCC->APB2ENR, RCC_APB2ENR_TIM10EN);\ /* Delay after an RCC peripheral clock enabling */ \ tmpreg = READ_BIT(RCC->APB2ENR, RCC_APB2ENR_TIM10EN);\ UNUSED(tmpreg); \ } while(0) #define __HAL_RCC_SDIO_CLK_DISABLE() (RCC->APB2ENR &= ~(RCC_APB2ENR_SDIOEN)) #define __HAL_RCC_SPI4_CLK_DISABLE() (RCC->APB2ENR &= ~(RCC_APB2ENR_SPI4EN)) #define __HAL_RCC_TIM10_CLK_DISABLE() (RCC->APB2ENR &= ~(RCC_APB2ENR_TIM10EN)) #define __HAL_RCC_TIM8_CLK_DISABLE() (RCC->APB2ENR &= ~(RCC_APB2ENR_TIM8EN)) #define __HAL_RCC_ADC2_CLK_DISABLE() (RCC->APB2ENR &= ~(RCC_APB2ENR_ADC2EN)) #define __HAL_RCC_ADC3_CLK_DISABLE() (RCC->APB2ENR &= ~(RCC_APB2ENR_ADC3EN)) /** * @} */ /** @defgroup RCCEx_AHB1_Force_Release_Reset AHB1 Force Release Reset * @brief Force or release AHB1 peripheral reset. */ #define __HAL_RCC_GPIOD_FORCE_RESET() (RCC->AHB1RSTR |= (RCC_AHB1RSTR_GPIODRST)) #define __HAL_RCC_GPIOE_FORCE_RESET() (RCC->AHB1RSTR |= (RCC_AHB1RSTR_GPIOERST)) #define __HAL_RCC_GPIOF_FORCE_RESET() (RCC->AHB1RSTR |= (RCC_AHB1RSTR_GPIOFRST)) #define __HAL_RCC_GPIOG_FORCE_RESET() (RCC->AHB1RSTR |= (RCC_AHB1RSTR_GPIOGRST)) #define __HAL_RCC_GPIOI_FORCE_RESET() (RCC->AHB1RSTR |= (RCC_AHB1RSTR_GPIOIRST)) #define __HAL_RCC_ETHMAC_FORCE_RESET() (RCC->AHB1RSTR |= (RCC_AHB1RSTR_ETHMACRST)) #define __HAL_RCC_USB_OTG_HS_FORCE_RESET() (RCC->AHB1RSTR |= (RCC_AHB1RSTR_OTGHRST)) #define __HAL_RCC_CRC_FORCE_RESET() (RCC->AHB1RSTR |= (RCC_AHB1RSTR_CRCRST)) #define __HAL_RCC_GPIOD_RELEASE_RESET() (RCC->AHB1RSTR &= ~(RCC_AHB1RSTR_GPIODRST)) #define __HAL_RCC_GPIOE_RELEASE_RESET() (RCC->AHB1RSTR &= ~(RCC_AHB1RSTR_GPIOERST)) #define __HAL_RCC_GPIOF_RELEASE_RESET() (RCC->AHB1RSTR &= ~(RCC_AHB1RSTR_GPIOFRST)) #define __HAL_RCC_GPIOG_RELEASE_RESET() (RCC->AHB1RSTR &= ~(RCC_AHB1RSTR_GPIOGRST)) #define __HAL_RCC_GPIOI_RELEASE_RESET() (RCC->AHB1RSTR &= ~(RCC_AHB1RSTR_GPIOIRST)) #define __HAL_RCC_ETHMAC_RELEASE_RESET() (RCC->AHB1RSTR &= ~(RCC_AHB1RSTR_ETHMACRST)) #define __HAL_RCC_USB_OTG_HS_RELEASE_RESET() (RCC->AHB1RSTR &= ~(RCC_AHB1RSTR_OTGHRST)) #define __HAL_RCC_CRC_RELEASE_RESET() (RCC->AHB1RSTR &= ~(RCC_AHB1RSTR_CRCRST)) /** * @} */ /** @defgroup RCCEx_AHB2_Force_Release_Reset AHB2 Force Release Reset * @brief Force or release AHB2 peripheral reset. */ #define __HAL_RCC_AHB2_FORCE_RESET() (RCC->AHB2RSTR = 0xFFFFFFFF) #define __HAL_RCC_AHB2_RELEASE_RESET() (RCC->AHB2RSTR = 0x00) #if defined(STM32F407xx)|| defined(STM32F417xx) #define __HAL_RCC_DCMI_FORCE_RESET() (RCC->AHB2RSTR |= (RCC_AHB2RSTR_DCMIRST)) #define __HAL_RCC_DCMI_RELEASE_RESET() (RCC->AHB2RSTR &= ~(RCC_AHB2RSTR_DCMIRST)) #endif /* STM32F407xx || STM32F417xx */ #if defined(STM32F415xx) || defined(STM32F417xx) #define __HAL_RCC_CRYP_FORCE_RESET() (RCC->AHB2RSTR |= (RCC_AHB2RSTR_CRYPRST)) #define __HAL_RCC_HASH_FORCE_RESET() (RCC->AHB2RSTR |= (RCC_AHB2RSTR_HASHRST)) #define __HAL_RCC_CRYP_RELEASE_RESET() (RCC->AHB2RSTR &= ~(RCC_AHB2RSTR_CRYPRST)) #define __HAL_RCC_HASH_RELEASE_RESET() (RCC->AHB2RSTR &= ~(RCC_AHB2RSTR_HASHRST)) #endif /* STM32F415xx || STM32F417xx */ #define __HAL_RCC_USB_OTG_FS_FORCE_RESET() (RCC->AHB2RSTR |= (RCC_AHB2RSTR_OTGFSRST)) #define __HAL_RCC_USB_OTG_FS_RELEASE_RESET() (RCC->AHB2RSTR &= ~(RCC_AHB2RSTR_OTGFSRST)) #define __HAL_RCC_RNG_FORCE_RESET() (RCC->AHB2RSTR |= (RCC_AHB2RSTR_RNGRST)) #define __HAL_RCC_RNG_RELEASE_RESET() (RCC->AHB2RSTR &= ~(RCC_AHB2RSTR_RNGRST)) /** * @} */ /** @defgroup RCCEx_AHB3_Force_Release_Reset AHB3 Force Release Reset * @brief Force or release AHB3 peripheral reset. * @{ */ #define __HAL_RCC_AHB3_FORCE_RESET() (RCC->AHB3RSTR = 0xFFFFFFFF) #define __HAL_RCC_AHB3_RELEASE_RESET() (RCC->AHB3RSTR = 0x00) #define __HAL_RCC_FSMC_FORCE_RESET() (RCC->AHB3RSTR |= (RCC_AHB3RSTR_FSMCRST)) #define __HAL_RCC_FSMC_RELEASE_RESET() (RCC->AHB3RSTR &= ~(RCC_AHB3RSTR_FSMCRST)) /** * @} */ /** @defgroup RCCEx_APB1_Force_Release_Reset APB1 Force Release Reset * @brief Force or release APB1 peripheral reset. */ #define __HAL_RCC_TIM6_FORCE_RESET() (RCC->APB1RSTR |= (RCC_APB1RSTR_TIM6RST)) #define __HAL_RCC_TIM7_FORCE_RESET() (RCC->APB1RSTR |= (RCC_APB1RSTR_TIM7RST)) #define __HAL_RCC_TIM12_FORCE_RESET() (RCC->APB1RSTR |= (RCC_APB1RSTR_TIM12RST)) #define __HAL_RCC_TIM13_FORCE_RESET() (RCC->APB1RSTR |= (RCC_APB1RSTR_TIM13RST)) #define __HAL_RCC_TIM14_FORCE_RESET() (RCC->APB1RSTR |= (RCC_APB1RSTR_TIM14RST)) #define __HAL_RCC_USART3_FORCE_RESET() (RCC->APB1RSTR |= (RCC_APB1RSTR_USART3RST)) #define __HAL_RCC_UART4_FORCE_RESET() (RCC->APB1RSTR |= (RCC_APB1RSTR_UART4RST)) #define __HAL_RCC_UART5_FORCE_RESET() (RCC->APB1RSTR |= (RCC_APB1RSTR_UART5RST)) #define __HAL_RCC_CAN1_FORCE_RESET() (RCC->APB1RSTR |= (RCC_APB1RSTR_CAN1RST)) #define __HAL_RCC_CAN2_FORCE_RESET() (RCC->APB1RSTR |= (RCC_APB1RSTR_CAN2RST)) #define __HAL_RCC_DAC_FORCE_RESET() (RCC->APB1RSTR |= (RCC_APB1RSTR_DACRST)) #define __HAL_RCC_TIM2_FORCE_RESET() (RCC->APB1RSTR |= (RCC_APB1RSTR_TIM2RST)) #define __HAL_RCC_TIM3_FORCE_RESET() (RCC->APB1RSTR |= (RCC_APB1RSTR_TIM3RST)) #define __HAL_RCC_TIM4_FORCE_RESET() (RCC->APB1RSTR |= (RCC_APB1RSTR_TIM4RST)) #define __HAL_RCC_SPI3_FORCE_RESET() (RCC->APB1RSTR |= (RCC_APB1RSTR_SPI3RST)) #define __HAL_RCC_I2C3_FORCE_RESET() (RCC->APB1RSTR |= (RCC_APB1RSTR_I2C3RST)) #define __HAL_RCC_TIM2_RELEASE_RESET() (RCC->APB1RSTR &= ~(RCC_APB1RSTR_TIM2RST)) #define __HAL_RCC_TIM3_RELEASE_RESET() (RCC->APB1RSTR &= ~(RCC_APB1RSTR_TIM3RST)) #define __HAL_RCC_TIM4_RELEASE_RESET() (RCC->APB1RSTR &= ~(RCC_APB1RSTR_TIM4RST)) #define __HAL_RCC_SPI3_RELEASE_RESET() (RCC->APB1RSTR &= ~(RCC_APB1RSTR_SPI3RST)) #define __HAL_RCC_I2C3_RELEASE_RESET() (RCC->APB1RSTR &= ~(RCC_APB1RSTR_I2C3RST)) #define __HAL_RCC_TIM6_RELEASE_RESET() (RCC->APB1RSTR &= ~(RCC_APB1RSTR_TIM6RST)) #define __HAL_RCC_TIM7_RELEASE_RESET() (RCC->APB1RSTR &= ~(RCC_APB1RSTR_TIM7RST)) #define __HAL_RCC_TIM12_RELEASE_RESET() (RCC->APB1RSTR &= ~(RCC_APB1RSTR_TIM12RST)) #define __HAL_RCC_TIM13_RELEASE_RESET() (RCC->APB1RSTR &= ~(RCC_APB1RSTR_TIM13RST)) #define __HAL_RCC_TIM14_RELEASE_RESET() (RCC->APB1RSTR &= ~(RCC_APB1RSTR_TIM14RST)) #define __HAL_RCC_USART3_RELEASE_RESET() (RCC->APB1RSTR &= ~(RCC_APB1RSTR_USART3RST)) #define __HAL_RCC_UART4_RELEASE_RESET() (RCC->APB1RSTR &= ~(RCC_APB1RSTR_UART4RST)) #define __HAL_RCC_UART5_RELEASE_RESET() (RCC->APB1RSTR &= ~(RCC_APB1RSTR_UART5RST)) #define __HAL_RCC_CAN1_RELEASE_RESET() (RCC->APB1RSTR &= ~(RCC_APB1RSTR_CAN1RST)) #define __HAL_RCC_CAN2_RELEASE_RESET() (RCC->APB1RSTR &= ~(RCC_APB1RSTR_CAN2RST)) #define __HAL_RCC_DAC_RELEASE_RESET() (RCC->APB1RSTR &= ~(RCC_APB1RSTR_DACRST)) /** * @} */ /** @defgroup RCCEx_APB2_Force_Release_Reset APB2 Force Release Reset * @brief Force or release APB2 peripheral reset. */ #define __HAL_RCC_TIM8_FORCE_RESET() (RCC->APB2RSTR |= (RCC_APB2RSTR_TIM8RST)) #define __HAL_RCC_SDIO_FORCE_RESET() (RCC->APB2RSTR |= (RCC_APB2RSTR_SDIORST)) #define __HAL_RCC_SPI4_FORCE_RESET() (RCC->APB2RSTR |= (RCC_APB2RSTR_SPI4RST)) #define __HAL_RCC_TIM10_FORCE_RESET() (RCC->APB2RSTR |= (RCC_APB2RSTR_TIM10RST)) #define __HAL_RCC_SDIO_RELEASE_RESET() (RCC->APB2RSTR &= ~(RCC_APB2RSTR_SDIORST)) #define __HAL_RCC_SPI4_RELEASE_RESET() (RCC->APB2RSTR &= ~(RCC_APB2RSTR_SPI4RST)) #define __HAL_RCC_TIM10_RELEASE_RESET()(RCC->APB2RSTR &= ~(RCC_APB2RSTR_TIM10RST)) #define __HAL_RCC_TIM8_RELEASE_RESET() (RCC->APB2RSTR &= ~(RCC_APB2RSTR_TIM8RST)) /** * @} */ /** @defgroup RCCEx_AHB1_LowPower_Enable_Disable AHB1 Peripheral Low Power Enable Disable * @brief Enable or disable the AHB1 peripheral clock during Low Power (Sleep) mode. * @note Peripheral clock gating in SLEEP mode can be used to further reduce * power consumption. * @note After wakeup from SLEEP mode, the peripheral clock is enabled again. * @note By default, all peripheral clocks are enabled during SLEEP mode. */ #define __HAL_RCC_GPIOD_CLK_SLEEP_ENABLE() (RCC->AHB1LPENR |= (RCC_AHB1LPENR_GPIODLPEN)) #define __HAL_RCC_GPIOE_CLK_SLEEP_ENABLE() (RCC->AHB1LPENR |= (RCC_AHB1LPENR_GPIOELPEN)) #define __HAL_RCC_GPIOF_CLK_SLEEP_ENABLE() (RCC->AHB1LPENR |= (RCC_AHB1LPENR_GPIOFLPEN)) #define __HAL_RCC_GPIOG_CLK_SLEEP_ENABLE() (RCC->AHB1LPENR |= (RCC_AHB1LPENR_GPIOGLPEN)) #define __HAL_RCC_GPIOI_CLK_SLEEP_ENABLE() (RCC->AHB1LPENR |= (RCC_AHB1LPENR_GPIOILPEN)) #define __HAL_RCC_SRAM2_CLK_SLEEP_ENABLE() (RCC->AHB1LPENR |= (RCC_AHB1LPENR_SRAM2LPEN)) #define __HAL_RCC_ETHMAC_CLK_SLEEP_ENABLE() (RCC->AHB1LPENR |= (RCC_AHB1LPENR_ETHMACLPEN)) #define __HAL_RCC_ETHMACTX_CLK_SLEEP_ENABLE() (RCC->AHB1LPENR |= (RCC_AHB1LPENR_ETHMACTXLPEN)) #define __HAL_RCC_ETHMACRX_CLK_SLEEP_ENABLE() (RCC->AHB1LPENR |= (RCC_AHB1LPENR_ETHMACRXLPEN)) #define __HAL_RCC_ETHMACPTP_CLK_SLEEP_ENABLE() (RCC->AHB1LPENR |= (RCC_AHB1LPENR_ETHMACPTPLPEN)) #define __HAL_RCC_USB_OTG_HS_CLK_SLEEP_ENABLE() (RCC->AHB1LPENR |= (RCC_AHB1LPENR_OTGHSLPEN)) #define __HAL_RCC_USB_OTG_HS_ULPI_CLK_SLEEP_ENABLE() (RCC->AHB1LPENR |= (RCC_AHB1LPENR_OTGHSULPILPEN)) #define __HAL_RCC_CRC_CLK_SLEEP_ENABLE() (RCC->AHB1LPENR |= (RCC_AHB1LPENR_CRCLPEN)) #define __HAL_RCC_FLITF_CLK_SLEEP_ENABLE() (RCC->AHB1LPENR |= (RCC_AHB1LPENR_FLITFLPEN)) #define __HAL_RCC_SRAM1_CLK_SLEEP_ENABLE() (RCC->AHB1LPENR |= (RCC_AHB1LPENR_SRAM1LPEN)) #define __HAL_RCC_BKPSRAM_CLK_SLEEP_ENABLE() (RCC->AHB1LPENR |= (RCC_AHB1LPENR_BKPSRAMLPEN)) #define __HAL_RCC_GPIOD_CLK_SLEEP_DISABLE() (RCC->AHB1LPENR &= ~(RCC_AHB1LPENR_GPIODLPEN)) #define __HAL_RCC_GPIOE_CLK_SLEEP_DISABLE() (RCC->AHB1LPENR &= ~(RCC_AHB1LPENR_GPIOELPEN)) #define __HAL_RCC_GPIOF_CLK_SLEEP_DISABLE() (RCC->AHB1LPENR &= ~(RCC_AHB1LPENR_GPIOFLPEN)) #define __HAL_RCC_GPIOG_CLK_SLEEP_DISABLE() (RCC->AHB1LPENR &= ~(RCC_AHB1LPENR_GPIOGLPEN)) #define __HAL_RCC_GPIOI_CLK_SLEEP_DISABLE() (RCC->AHB1LPENR &= ~(RCC_AHB1LPENR_GPIOILPEN)) #define __HAL_RCC_SRAM2_CLK_SLEEP_DISABLE() (RCC->AHB1LPENR &= ~(RCC_AHB1LPENR_SRAM2LPEN)) #define __HAL_RCC_ETHMAC_CLK_SLEEP_DISABLE() (RCC->AHB1LPENR &= ~(RCC_AHB1LPENR_ETHMACLPEN)) #define __HAL_RCC_ETHMACTX_CLK_SLEEP_DISABLE() (RCC->AHB1LPENR &= ~(RCC_AHB1LPENR_ETHMACTXLPEN)) #define __HAL_RCC_ETHMACRX_CLK_SLEEP_DISABLE() (RCC->AHB1LPENR &= ~(RCC_AHB1LPENR_ETHMACRXLPEN)) #define __HAL_RCC_ETHMACPTP_CLK_SLEEP_DISABLE() (RCC->AHB1LPENR &= ~(RCC_AHB1LPENR_ETHMACPTPLPEN)) #define __HAL_RCC_USB_OTG_HS_CLK_SLEEP_DISABLE() (RCC->AHB1LPENR &= ~(RCC_AHB1LPENR_OTGHSLPEN)) #define __HAL_RCC_USB_OTG_HS_ULPI_CLK_SLEEP_DISABLE() (RCC->AHB1LPENR &= ~(RCC_AHB1LPENR_OTGHSULPILPEN)) #define __HAL_RCC_CRC_CLK_SLEEP_DISABLE() (RCC->AHB1LPENR &= ~(RCC_AHB1LPENR_CRCLPEN)) #define __HAL_RCC_FLITF_CLK_SLEEP_DISABLE() (RCC->AHB1LPENR &= ~(RCC_AHB1LPENR_FLITFLPEN)) #define __HAL_RCC_SRAM1_CLK_SLEEP_DISABLE() (RCC->AHB1LPENR &= ~(RCC_AHB1LPENR_SRAM1LPEN)) #define __HAL_RCC_BKPSRAM_CLK_SLEEP_DISABLE() (RCC->AHB1LPENR &= ~(RCC_AHB1LPENR_BKPSRAMLPEN)) /** * @} */ /** @defgroup RCCEx_AHB2_LowPower_Enable_Disable AHB2 Peripheral Low Power Enable Disable * @brief Enable or disable the AHB2 peripheral clock during Low Power (Sleep) mode. * @note Peripheral clock gating in SLEEP mode can be used to further reduce * power consumption. * @note After wake-up from SLEEP mode, the peripheral clock is enabled again. * @note By default, all peripheral clocks are enabled during SLEEP mode. * @{ */ #define __HAL_RCC_USB_OTG_FS_CLK_SLEEP_ENABLE() (RCC->AHB2LPENR |= (RCC_AHB2LPENR_OTGFSLPEN)) #define __HAL_RCC_USB_OTG_FS_CLK_SLEEP_DISABLE() (RCC->AHB2LPENR &= ~(RCC_AHB2LPENR_OTGFSLPEN)) #define __HAL_RCC_RNG_CLK_SLEEP_ENABLE() (RCC->AHB2LPENR |= (RCC_AHB2LPENR_RNGLPEN)) #define __HAL_RCC_RNG_CLK_SLEEP_DISABLE() (RCC->AHB2LPENR &= ~(RCC_AHB2LPENR_RNGLPEN)) #if defined(STM32F407xx)|| defined(STM32F417xx) #define __HAL_RCC_DCMI_CLK_SLEEP_ENABLE() (RCC->AHB2LPENR |= (RCC_AHB2LPENR_DCMILPEN)) #define __HAL_RCC_DCMI_CLK_SLEEP_DISABLE() (RCC->AHB2LPENR &= ~(RCC_AHB2LPENR_DCMILPEN)) #endif /* STM32F407xx || STM32F417xx */ #if defined(STM32F415xx) || defined(STM32F417xx) #define __HAL_RCC_CRYP_CLK_SLEEP_ENABLE() (RCC->AHB2LPENR |= (RCC_AHB2LPENR_CRYPLPEN)) #define __HAL_RCC_HASH_CLK_SLEEP_ENABLE() (RCC->AHB2LPENR |= (RCC_AHB2LPENR_HASHLPEN)) #define __HAL_RCC_CRYP_CLK_SLEEP_DISABLE() (RCC->AHB2LPENR &= ~(RCC_AHB2LPENR_CRYPLPEN)) #define __HAL_RCC_HASH_CLK_SLEEP_DISABLE() (RCC->AHB2LPENR &= ~(RCC_AHB2LPENR_HASHLPEN)) #endif /* STM32F415xx || STM32F417xx */ /** * @} */ /** @defgroup RCCEx_AHB3_LowPower_Enable_Disable AHB3 Peripheral Low Power Enable Disable * @brief Enable or disable the AHB3 peripheral clock during Low Power (Sleep) mode. * @note Peripheral clock gating in SLEEP mode can be used to further reduce * power consumption. * @note After wakeup from SLEEP mode, the peripheral clock is enabled again. * @note By default, all peripheral clocks are enabled during SLEEP mode. */ #define __HAL_RCC_FSMC_CLK_SLEEP_ENABLE() (RCC->AHB3LPENR |= (RCC_AHB3LPENR_FSMCLPEN)) #define __HAL_RCC_FSMC_CLK_SLEEP_DISABLE() (RCC->AHB3LPENR &= ~(RCC_AHB3LPENR_FSMCLPEN)) /** * @} */ /** @defgroup RCCEx_APB1_LowPower_Enable_Disable APB1 Peripheral Low Power Enable Disable * @brief Enable or disable the APB1 peripheral clock during Low Power (Sleep) mode. * @note Peripheral clock gating in SLEEP mode can be used to further reduce * power consumption. * @note After wakeup from SLEEP mode, the peripheral clock is enabled again. * @note By default, all peripheral clocks are enabled during SLEEP mode. */ #define __HAL_RCC_TIM6_CLK_SLEEP_ENABLE() (RCC->APB1LPENR |= (RCC_APB1LPENR_TIM6LPEN)) #define __HAL_RCC_TIM7_CLK_SLEEP_ENABLE() (RCC->APB1LPENR |= (RCC_APB1LPENR_TIM7LPEN)) #define __HAL_RCC_TIM12_CLK_SLEEP_ENABLE() (RCC->APB1LPENR |= (RCC_APB1LPENR_TIM12LPEN)) #define __HAL_RCC_TIM13_CLK_SLEEP_ENABLE() (RCC->APB1LPENR |= (RCC_APB1LPENR_TIM13LPEN)) #define __HAL_RCC_TIM14_CLK_SLEEP_ENABLE() (RCC->APB1LPENR |= (RCC_APB1LPENR_TIM14LPEN)) #define __HAL_RCC_USART3_CLK_SLEEP_ENABLE() (RCC->APB1LPENR |= (RCC_APB1LPENR_USART3LPEN)) #define __HAL_RCC_UART4_CLK_SLEEP_ENABLE() (RCC->APB1LPENR |= (RCC_APB1LPENR_UART4LPEN)) #define __HAL_RCC_UART5_CLK_SLEEP_ENABLE() (RCC->APB1LPENR |= (RCC_APB1LPENR_UART5LPEN)) #define __HAL_RCC_CAN1_CLK_SLEEP_ENABLE() (RCC->APB1LPENR |= (RCC_APB1LPENR_CAN1LPEN)) #define __HAL_RCC_CAN2_CLK_SLEEP_ENABLE() (RCC->APB1LPENR |= (RCC_APB1LPENR_CAN2LPEN)) #define __HAL_RCC_DAC_CLK_SLEEP_ENABLE() (RCC->APB1LPENR |= (RCC_APB1LPENR_DACLPEN)) #define __HAL_RCC_TIM2_CLK_SLEEP_ENABLE() (RCC->APB1LPENR |= (RCC_APB1LPENR_TIM2LPEN)) #define __HAL_RCC_TIM3_CLK_SLEEP_ENABLE() (RCC->APB1LPENR |= (RCC_APB1LPENR_TIM3LPEN)) #define __HAL_RCC_TIM4_CLK_SLEEP_ENABLE() (RCC->APB1LPENR |= (RCC_APB1LPENR_TIM4LPEN)) #define __HAL_RCC_SPI3_CLK_SLEEP_ENABLE() (RCC->APB1LPENR |= (RCC_APB1LPENR_SPI3LPEN)) #define __HAL_RCC_I2C3_CLK_SLEEP_ENABLE() (RCC->APB1LPENR |= (RCC_APB1LPENR_I2C3LPEN)) #define __HAL_RCC_TIM2_CLK_SLEEP_DISABLE() (RCC->APB1LPENR &= ~(RCC_APB1LPENR_TIM2LPEN)) #define __HAL_RCC_TIM3_CLK_SLEEP_DISABLE() (RCC->APB1LPENR &= ~(RCC_APB1LPENR_TIM3LPEN)) #define __HAL_RCC_TIM4_CLK_SLEEP_DISABLE() (RCC->APB1LPENR &= ~(RCC_APB1LPENR_TIM4LPEN)) #define __HAL_RCC_SPI3_CLK_SLEEP_DISABLE() (RCC->APB1LPENR &= ~(RCC_APB1LPENR_SPI3LPEN)) #define __HAL_RCC_I2C3_CLK_SLEEP_DISABLE() (RCC->APB1LPENR &= ~(RCC_APB1LPENR_I2C3LPEN)) #define __HAL_RCC_TIM6_CLK_SLEEP_DISABLE() (RCC->APB1LPENR &= ~(RCC_APB1LPENR_TIM6LPEN)) #define __HAL_RCC_TIM7_CLK_SLEEP_DISABLE() (RCC->APB1LPENR &= ~(RCC_APB1LPENR_TIM7LPEN)) #define __HAL_RCC_TIM12_CLK_SLEEP_DISABLE() (RCC->APB1LPENR &= ~(RCC_APB1LPENR_TIM12LPEN)) #define __HAL_RCC_TIM13_CLK_SLEEP_DISABLE() (RCC->APB1LPENR &= ~(RCC_APB1LPENR_TIM13LPEN)) #define __HAL_RCC_TIM14_CLK_SLEEP_DISABLE() (RCC->APB1LPENR &= ~(RCC_APB1LPENR_TIM14LPEN)) #define __HAL_RCC_USART3_CLK_SLEEP_DISABLE() (RCC->APB1LPENR &= ~(RCC_APB1LPENR_USART3LPEN)) #define __HAL_RCC_UART4_CLK_SLEEP_DISABLE() (RCC->APB1LPENR &= ~(RCC_APB1LPENR_UART4LPEN)) #define __HAL_RCC_UART5_CLK_SLEEP_DISABLE() (RCC->APB1LPENR &= ~(RCC_APB1LPENR_UART5LPEN)) #define __HAL_RCC_CAN1_CLK_SLEEP_DISABLE() (RCC->APB1LPENR &= ~(RCC_APB1LPENR_CAN1LPEN)) #define __HAL_RCC_CAN2_CLK_SLEEP_DISABLE() (RCC->APB1LPENR &= ~(RCC_APB1LPENR_CAN2LPEN)) #define __HAL_RCC_DAC_CLK_SLEEP_DISABLE() (RCC->APB1LPENR &= ~(RCC_APB1LPENR_DACLPEN)) /** * @} */ /** @defgroup RCCEx_APB2_LowPower_Enable_Disable APB2 Peripheral Low Power Enable Disable * @brief Enable or disable the APB2 peripheral clock during Low Power (Sleep) mode. * @note Peripheral clock gating in SLEEP mode can be used to further reduce * power consumption. * @note After wakeup from SLEEP mode, the peripheral clock is enabled again. * @note By default, all peripheral clocks are enabled during SLEEP mode. */ #define __HAL_RCC_TIM8_CLK_SLEEP_ENABLE() (RCC->APB2LPENR |= (RCC_APB2LPENR_TIM8LPEN)) #define __HAL_RCC_ADC2_CLK_SLEEP_ENABLE() (RCC->APB2LPENR |= (RCC_APB2LPENR_ADC2LPEN)) #define __HAL_RCC_ADC3_CLK_SLEEP_ENABLE() (RCC->APB2LPENR |= (RCC_APB2LPENR_ADC3LPEN)) #define __HAL_RCC_SDIO_CLK_SLEEP_ENABLE() (RCC->APB2LPENR |= (RCC_APB2LPENR_SDIOLPEN)) #define __HAL_RCC_SPI4_CLK_SLEEP_ENABLE() (RCC->APB2LPENR |= (RCC_APB2LPENR_SPI4LPEN)) #define __HAL_RCC_TIM10_CLK_SLEEP_ENABLE()(RCC->APB2LPENR |= (RCC_APB2LPENR_TIM10LPEN)) #define __HAL_RCC_SDIO_CLK_SLEEP_DISABLE() (RCC->APB2LPENR &= ~(RCC_APB2LPENR_SDIOLPEN)) #define __HAL_RCC_SPI4_CLK_SLEEP_DISABLE() (RCC->APB2LPENR &= ~(RCC_APB2LPENR_SPI4LPEN)) #define __HAL_RCC_TIM10_CLK_SLEEP_DISABLE()(RCC->APB2LPENR &= ~(RCC_APB2LPENR_TIM10LPEN)) #define __HAL_RCC_TIM8_CLK_SLEEP_DISABLE() (RCC->APB2LPENR &= ~(RCC_APB2LPENR_TIM8LPEN)) #define __HAL_RCC_ADC2_CLK_SLEEP_DISABLE() (RCC->APB2LPENR &= ~(RCC_APB2LPENR_ADC2LPEN)) #define __HAL_RCC_ADC3_CLK_SLEEP_DISABLE() (RCC->APB2LPENR &= ~(RCC_APB2LPENR_ADC3LPEN)) /** * @} */ #endif /* STM32F405xx || STM32F415xx || STM32F407xx || STM32F417xx */ /*----------------------------------------------------------------------------*/ /*------------------------- STM32F401xE/STM32F401xC --------------------------*/ #if defined(STM32F401xC) || defined(STM32F401xE) /** @defgroup RCCEx_AHB1_Clock_Enable_Disable AHB1 Peripheral Clock Enable Disable * @brief Enable or disable the AHB1 peripheral clock. * @note After reset, the peripheral clock (used for registers read/write access) * is disabled and the application software has to enable this clock before * using it. * @{ */ #define __HAL_RCC_GPIOD_CLK_ENABLE() do { \ __IO uint32_t tmpreg; \ SET_BIT(RCC->AHB1ENR, RCC_AHB1ENR_GPIODEN);\ /* Delay after an RCC peripheral clock enabling */ \ tmpreg = READ_BIT(RCC->AHB1ENR, RCC_AHB1ENR_GPIODEN);\ UNUSED(tmpreg); \ } while(0) #define __HAL_RCC_GPIOE_CLK_ENABLE() do { \ __IO uint32_t tmpreg; \ SET_BIT(RCC->AHB1ENR, RCC_AHB1ENR_GPIOEEN);\ /* Delay after an RCC peripheral clock enabling */ \ tmpreg = READ_BIT(RCC->AHB1ENR, RCC_AHB1ENR_GPIOEEN);\ UNUSED(tmpreg); \ } while(0) #define __HAL_RCC_CRC_CLK_ENABLE() do { \ __IO uint32_t tmpreg; \ SET_BIT(RCC->AHB1ENR, RCC_AHB1ENR_CRCEN);\ /* Delay after an RCC peripheral clock enabling */ \ tmpreg = READ_BIT(RCC->AHB1ENR, RCC_AHB1ENR_CRCEN);\ UNUSED(tmpreg); \ } while(0) #define __HAL_RCC_BKPSRAM_CLK_ENABLE() do { \ __IO uint32_t tmpreg; \ SET_BIT(RCC->AHB1ENR, RCC_AHB1ENR_BKPSRAMEN);\ /* Delay after an RCC peripheral clock enabling */ \ tmpreg = READ_BIT(RCC->AHB1ENR, RCC_AHB1ENR_BKPSRAMEN);\ UNUSED(tmpreg); \ } while(0) #define __HAL_RCC_CCMDATARAMEN_CLK_ENABLE() do { \ __IO uint32_t tmpreg; \ SET_BIT(RCC->AHB1ENR, RCC_AHB1ENR_CCMDATARAMEN);\ /* Delay after an RCC peripheral clock enabling */ \ tmpreg = READ_BIT(RCC->AHB1ENR, RCC_AHB1ENR_CCMDATARAMEN);\ UNUSED(tmpreg); \ } while(0) #define __HAL_RCC_GPIOD_CLK_DISABLE() (RCC->AHB1ENR &= ~(RCC_AHB1ENR_GPIODEN)) #define __HAL_RCC_GPIOE_CLK_DISABLE() (RCC->AHB1ENR &= ~(RCC_AHB1ENR_GPIOEEN)) #define __HAL_RCC_CRC_CLK_DISABLE() (RCC->AHB1ENR &= ~(RCC_AHB1ENR_CRCEN)) #define __HAL_RCC_BKPSRAM_CLK_DISABLE() (RCC->AHB1ENR &= ~(RCC_AHB1ENR_BKPSRAMEN)) #define __HAL_RCC_CCMDATARAMEN_CLK_DISABLE() (RCC->AHB1ENR &= ~(RCC_AHB1ENR_CCMDATARAMEN)) /** * @} */ /** @defgroup RCCEx_AHB2_Clock_Enable_Disable AHB2 Peripheral Clock Enable Disable * @brief Enable or disable the AHB2 peripheral clock. * @note After reset, the peripheral clock (used for registers read/write access) * is disabled and the application software has to enable this clock before * using it. * @{ */ #define __HAL_RCC_USB_OTG_FS_CLK_ENABLE() do {(RCC->AHB2ENR |= (RCC_AHB2ENR_OTGFSEN));\ __HAL_RCC_SYSCFG_CLK_ENABLE();\ }while(0) #define __HAL_RCC_USB_OTG_FS_CLK_DISABLE() do { (RCC->AHB2ENR &= ~(RCC_AHB2ENR_OTGFSEN));\ __HAL_RCC_SYSCFG_CLK_DISABLE();\ }while(0) /** * @} */ /** @defgroup RCC_APB1_Clock_Enable_Disable APB1 Peripheral Clock Enable Disable * @brief Enable or disable the Low Speed APB (APB1) peripheral clock. * @note After reset, the peripheral clock (used for registers read/write access) * is disabled and the application software has to enable this clock before * using it. * @{ */ #define __HAL_RCC_TIM2_CLK_ENABLE() do { \ __IO uint32_t tmpreg; \ SET_BIT(RCC->APB1ENR, RCC_APB1ENR_TIM2EN);\ /* Delay after an RCC peripheral clock enabling */ \ tmpreg = READ_BIT(RCC->APB1ENR, RCC_APB1ENR_TIM2EN);\ UNUSED(tmpreg); \ } while(0) #define __HAL_RCC_TIM3_CLK_ENABLE() do { \ __IO uint32_t tmpreg; \ SET_BIT(RCC->APB1ENR, RCC_APB1ENR_TIM3EN);\ /* Delay after an RCC peripheral clock enabling */ \ tmpreg = READ_BIT(RCC->APB1ENR, RCC_APB1ENR_TIM3EN);\ UNUSED(tmpreg); \ } while(0) #define __HAL_RCC_TIM4_CLK_ENABLE() do { \ __IO uint32_t tmpreg; \ SET_BIT(RCC->APB1ENR, RCC_APB1ENR_TIM4EN);\ /* Delay after an RCC peripheral clock enabling */ \ tmpreg = READ_BIT(RCC->APB1ENR, RCC_APB1ENR_TIM4EN);\ UNUSED(tmpreg); \ } while(0) #define __HAL_RCC_SPI3_CLK_ENABLE() do { \ __IO uint32_t tmpreg; \ SET_BIT(RCC->APB1ENR, RCC_APB1ENR_SPI3EN);\ /* Delay after an RCC peripheral clock enabling */ \ tmpreg = READ_BIT(RCC->APB1ENR, RCC_APB1ENR_SPI3EN);\ UNUSED(tmpreg); \ } while(0) #define __HAL_RCC_I2C3_CLK_ENABLE() do { \ __IO uint32_t tmpreg; \ SET_BIT(RCC->APB1ENR, RCC_APB1ENR_I2C3EN);\ /* Delay after an RCC peripheral clock enabling */ \ tmpreg = READ_BIT(RCC->APB1ENR, RCC_APB1ENR_I2C3EN);\ UNUSED(tmpreg); \ } while(0) #define __HAL_RCC_TIM2_CLK_DISABLE() (RCC->APB1ENR &= ~(RCC_APB1ENR_TIM2EN)) #define __HAL_RCC_TIM3_CLK_DISABLE() (RCC->APB1ENR &= ~(RCC_APB1ENR_TIM3EN)) #define __HAL_RCC_TIM4_CLK_DISABLE() (RCC->APB1ENR &= ~(RCC_APB1ENR_TIM4EN)) #define __HAL_RCC_SPI3_CLK_DISABLE() (RCC->APB1ENR &= ~(RCC_APB1ENR_SPI3EN)) #define __HAL_RCC_I2C3_CLK_DISABLE() (RCC->APB1ENR &= ~(RCC_APB1ENR_I2C3EN)) /** * @} */ /** @defgroup RCCEx_APB2_Clock_Enable_Disable APB2 Peripheral Clock Enable Disable * @brief Enable or disable the High Speed APB (APB2) peripheral clock. * @note After reset, the peripheral clock (used for registers read/write access) * is disabled and the application software has to enable this clock before * using it. * @{ */ #define __HAL_RCC_SDIO_CLK_ENABLE() do { \ __IO uint32_t tmpreg; \ SET_BIT(RCC->APB2ENR, RCC_APB2ENR_SDIOEN);\ /* Delay after an RCC peripheral clock enabling */ \ tmpreg = READ_BIT(RCC->APB2ENR, RCC_APB2ENR_SDIOEN);\ UNUSED(tmpreg); \ } while(0) #define __HAL_RCC_SPI4_CLK_ENABLE() do { \ __IO uint32_t tmpreg; \ SET_BIT(RCC->APB2ENR, RCC_APB2ENR_SPI4EN);\ /* Delay after an RCC peripheral clock enabling */ \ tmpreg = READ_BIT(RCC->APB2ENR, RCC_APB2ENR_SPI4EN);\ UNUSED(tmpreg); \ } while(0) #define __HAL_RCC_TIM10_CLK_ENABLE() do { \ __IO uint32_t tmpreg; \ SET_BIT(RCC->APB2ENR, RCC_APB2ENR_TIM10EN);\ /* Delay after an RCC peripheral clock enabling */ \ tmpreg = READ_BIT(RCC->APB2ENR, RCC_APB2ENR_TIM10EN);\ UNUSED(tmpreg); \ } while(0) #define __HAL_RCC_SDIO_CLK_DISABLE() (RCC->APB2ENR &= ~(RCC_APB2ENR_SDIOEN)) #define __HAL_RCC_SPI4_CLK_DISABLE() (RCC->APB2ENR &= ~(RCC_APB2ENR_SPI4EN)) #define __HAL_RCC_TIM10_CLK_DISABLE() (RCC->APB2ENR &= ~(RCC_APB2ENR_TIM10EN)) /** * @} */ /** @defgroup RCCEx_AHB1_Force_Release_Reset AHB1 Force Release Reset * @brief Force or release AHB1 peripheral reset. * @{ */ #define __HAL_RCC_AHB1_FORCE_RESET() (RCC->AHB1RSTR = 0xFFFFFFFF) #define __HAL_RCC_GPIOD_FORCE_RESET() (RCC->AHB1RSTR |= (RCC_AHB1RSTR_GPIODRST)) #define __HAL_RCC_GPIOE_FORCE_RESET() (RCC->AHB1RSTR |= (RCC_AHB1RSTR_GPIOERST)) #define __HAL_RCC_CRC_FORCE_RESET() (RCC->AHB1RSTR |= (RCC_AHB1RSTR_CRCRST)) #define __HAL_RCC_AHB1_RELEASE_RESET() (RCC->AHB1RSTR = 0x00) #define __HAL_RCC_GPIOD_RELEASE_RESET() (RCC->AHB1RSTR &= ~(RCC_AHB1RSTR_GPIODRST)) #define __HAL_RCC_GPIOE_RELEASE_RESET() (RCC->AHB1RSTR &= ~(RCC_AHB1RSTR_GPIOERST)) #define __HAL_RCC_CRC_RELEASE_RESET() (RCC->AHB1RSTR &= ~(RCC_AHB1RSTR_CRCRST)) /** * @} */ /** @defgroup RCCEx_AHB2_Force_Release_Reset AHB2 Force Release Reset * @brief Force or release AHB2 peripheral reset. * @{ */ #define __HAL_RCC_AHB2_FORCE_RESET() (RCC->AHB2RSTR = 0xFFFFFFFF) #define __HAL_RCC_USB_OTG_FS_FORCE_RESET() (RCC->AHB2RSTR |= (RCC_AHB2RSTR_OTGFSRST)) #define __HAL_RCC_AHB2_RELEASE_RESET() (RCC->AHB2RSTR = 0x00) #define __HAL_RCC_USB_OTG_FS_RELEASE_RESET() (RCC->AHB2RSTR &= ~(RCC_AHB2RSTR_OTGFSRST)) /** * @} */ /** @defgroup RCCEx_APB1_Force_Release_Reset APB1 Force Release Reset * @brief Force or release APB1 peripheral reset. * @{ */ #define __HAL_RCC_APB1_FORCE_RESET() (RCC->APB1RSTR = 0xFFFFFFFF) #define __HAL_RCC_TIM2_FORCE_RESET() (RCC->APB1RSTR |= (RCC_APB1RSTR_TIM2RST)) #define __HAL_RCC_TIM3_FORCE_RESET() (RCC->APB1RSTR |= (RCC_APB1RSTR_TIM3RST)) #define __HAL_RCC_TIM4_FORCE_RESET() (RCC->APB1RSTR |= (RCC_APB1RSTR_TIM4RST)) #define __HAL_RCC_SPI3_FORCE_RESET() (RCC->APB1RSTR |= (RCC_APB1RSTR_SPI3RST)) #define __HAL_RCC_I2C3_FORCE_RESET() (RCC->APB1RSTR |= (RCC_APB1RSTR_I2C3RST)) #define __HAL_RCC_APB1_RELEASE_RESET() (RCC->APB1RSTR = 0x00) #define __HAL_RCC_TIM2_RELEASE_RESET() (RCC->APB1RSTR &= ~(RCC_APB1RSTR_TIM2RST)) #define __HAL_RCC_TIM3_RELEASE_RESET() (RCC->APB1RSTR &= ~(RCC_APB1RSTR_TIM3RST)) #define __HAL_RCC_TIM4_RELEASE_RESET() (RCC->APB1RSTR &= ~(RCC_APB1RSTR_TIM4RST)) #define __HAL_RCC_SPI3_RELEASE_RESET() (RCC->APB1RSTR &= ~(RCC_APB1RSTR_SPI3RST)) #define __HAL_RCC_I2C3_RELEASE_RESET() (RCC->APB1RSTR &= ~(RCC_APB1RSTR_I2C3RST)) /** * @} */ /** @defgroup RCCEx_APB2_Force_Release_Reset APB2 Force Release Reset * @brief Force or release APB2 peripheral reset. * @{ */ #define __HAL_RCC_APB2_FORCE_RESET() (RCC->APB2RSTR = 0xFFFFFFFF) #define __HAL_RCC_SDIO_FORCE_RESET() (RCC->APB2RSTR |= (RCC_APB2RSTR_SDIORST)) #define __HAL_RCC_SPI4_FORCE_RESET() (RCC->APB2RSTR |= (RCC_APB2RSTR_SPI4RST)) #define __HAL_RCC_TIM10_FORCE_RESET() (RCC->APB2RSTR |= (RCC_APB2RSTR_TIM10RST)) #define __HAL_RCC_APB2_RELEASE_RESET() (RCC->APB2RSTR = 0x00) #define __HAL_RCC_SDIO_RELEASE_RESET() (RCC->APB2RSTR &= ~(RCC_APB2RSTR_SDIORST)) #define __HAL_RCC_SPI4_RELEASE_RESET() (RCC->APB2RSTR &= ~(RCC_APB2RSTR_SPI4RST)) #define __HAL_RCC_TIM10_RELEASE_RESET() (RCC->APB2RSTR &= ~(RCC_APB2RSTR_TIM10RST)) /** * @} */ /** @defgroup RCCEx_AHB3_Force_Release_Reset AHB3 Force Release Reset * @brief Force or release AHB3 peripheral reset. * @{ */ #define __HAL_RCC_AHB3_FORCE_RESET() (RCC->AHB3RSTR = 0xFFFFFFFF) #define __HAL_RCC_AHB3_RELEASE_RESET() (RCC->AHB3RSTR = 0x00) /** * @} */ /** @defgroup RCCEx_AHB1_LowPower_Enable_Disable AHB1 Peripheral Low Power Enable Disable * @brief Enable or disable the AHB1 peripheral clock during Low Power (Sleep) mode. * @note Peripheral clock gating in SLEEP mode can be used to further reduce * power consumption. * @note After wake-up from SLEEP mode, the peripheral clock is enabled again. * @note By default, all peripheral clocks are enabled during SLEEP mode. * @{ */ #define __HAL_RCC_GPIOD_CLK_SLEEP_ENABLE() (RCC->AHB1LPENR |= (RCC_AHB1LPENR_GPIODLPEN)) #define __HAL_RCC_GPIOE_CLK_SLEEP_ENABLE() (RCC->AHB1LPENR |= (RCC_AHB1LPENR_GPIOELPEN)) #define __HAL_RCC_CRC_CLK_SLEEP_ENABLE() (RCC->AHB1LPENR |= (RCC_AHB1LPENR_CRCLPEN)) #define __HAL_RCC_FLITF_CLK_SLEEP_ENABLE() (RCC->AHB1LPENR |= (RCC_AHB1LPENR_FLITFLPEN)) #define __HAL_RCC_SRAM1_CLK_SLEEP_ENABLE() (RCC->AHB1LPENR |= (RCC_AHB1LPENR_SRAM1LPEN)) #define __HAL_RCC_BKPSRAM_CLK_SLEEP_ENABLE() (RCC->AHB1LPENR |= (RCC_AHB1LPENR_BKPSRAMLPEN)) #define __HAL_RCC_GPIOD_CLK_SLEEP_DISABLE() (RCC->AHB1LPENR &= ~(RCC_AHB1LPENR_GPIODLPEN)) #define __HAL_RCC_GPIOE_CLK_SLEEP_DISABLE() (RCC->AHB1LPENR &= ~(RCC_AHB1LPENR_GPIOELPEN)) #define __HAL_RCC_CRC_CLK_SLEEP_DISABLE() (RCC->AHB1LPENR &= ~(RCC_AHB1LPENR_CRCLPEN)) #define __HAL_RCC_FLITF_CLK_SLEEP_DISABLE() (RCC->AHB1LPENR &= ~(RCC_AHB1LPENR_FLITFLPEN)) #define __HAL_RCC_SRAM1_CLK_SLEEP_DISABLE() (RCC->AHB1LPENR &= ~(RCC_AHB1LPENR_SRAM1LPEN)) #define __HAL_RCC_BKPSRAM_CLK_SLEEP_DISABLE() (RCC->AHB1LPENR &= ~(RCC_AHB1LPENR_BKPSRAMLPEN)) /** * @} */ /** @defgroup RCCEx_AHB2_LowPower_Enable_Disable AHB2 Peripheral Low Power Enable Disable * @brief Enable or disable the AHB2 peripheral clock during Low Power (Sleep) mode. * @note Peripheral clock gating in SLEEP mode can be used to further reduce * power consumption. * @note After wake-up from SLEEP mode, the peripheral clock is enabled again. * @note By default, all peripheral clocks are enabled during SLEEP mode. * @{ */ #define __HAL_RCC_USB_OTG_FS_CLK_SLEEP_ENABLE() (RCC->AHB2LPENR |= (RCC_AHB2LPENR_OTGFSLPEN)) #define __HAL_RCC_USB_OTG_FS_CLK_SLEEP_DISABLE() (RCC->AHB2LPENR &= ~(RCC_AHB2LPENR_OTGFSLPEN)) /** * @} */ /** @defgroup RCCEx_APB1_LowPower_Enable_Disable APB1 Peripheral Low Power Enable Disable * @brief Enable or disable the APB1 peripheral clock during Low Power (Sleep) mode. * @note Peripheral clock gating in SLEEP mode can be used to further reduce * power consumption. * @note After wake-up from SLEEP mode, the peripheral clock is enabled again. * @note By default, all peripheral clocks are enabled during SLEEP mode. * @{ */ #define __HAL_RCC_TIM2_CLK_SLEEP_ENABLE() (RCC->APB1LPENR |= (RCC_APB1LPENR_TIM2LPEN)) #define __HAL_RCC_TIM3_CLK_SLEEP_ENABLE() (RCC->APB1LPENR |= (RCC_APB1LPENR_TIM3LPEN)) #define __HAL_RCC_TIM4_CLK_SLEEP_ENABLE() (RCC->APB1LPENR |= (RCC_APB1LPENR_TIM4LPEN)) #define __HAL_RCC_SPI3_CLK_SLEEP_ENABLE() (RCC->APB1LPENR |= (RCC_APB1LPENR_SPI3LPEN)) #define __HAL_RCC_I2C3_CLK_SLEEP_ENABLE() (RCC->APB1LPENR |= (RCC_APB1LPENR_I2C3LPEN)) #define __HAL_RCC_TIM2_CLK_SLEEP_DISABLE() (RCC->APB1LPENR &= ~(RCC_APB1LPENR_TIM2LPEN)) #define __HAL_RCC_TIM3_CLK_SLEEP_DISABLE() (RCC->APB1LPENR &= ~(RCC_APB1LPENR_TIM3LPEN)) #define __HAL_RCC_TIM4_CLK_SLEEP_DISABLE() (RCC->APB1LPENR &= ~(RCC_APB1LPENR_TIM4LPEN)) #define __HAL_RCC_SPI3_CLK_SLEEP_DISABLE() (RCC->APB1LPENR &= ~(RCC_APB1LPENR_SPI3LPEN)) #define __HAL_RCC_I2C3_CLK_SLEEP_DISABLE() (RCC->APB1LPENR &= ~(RCC_APB1LPENR_I2C3LPEN)) /** * @} */ /** @defgroup RCCEx_APB2_LowPower_Enable_Disable APB2 Peripheral Low Power Enable Disable * @brief Enable or disable the APB2 peripheral clock during Low Power (Sleep) mode. * @note Peripheral clock gating in SLEEP mode can be used to further reduce * power consumption. * @note After wake-up from SLEEP mode, the peripheral clock is enabled again. * @note By default, all peripheral clocks are enabled during SLEEP mode. * @{ */ #define __HAL_RCC_SDIO_CLK_SLEEP_ENABLE() (RCC->APB2LPENR |= (RCC_APB2LPENR_SDIOLPEN)) #define __HAL_RCC_SPI4_CLK_SLEEP_ENABLE() (RCC->APB2LPENR |= (RCC_APB2LPENR_SPI4LPEN)) #define __HAL_RCC_TIM10_CLK_SLEEP_ENABLE() (RCC->APB2LPENR |= (RCC_APB2LPENR_TIM10LPEN)) #define __HAL_RCC_SDIO_CLK_SLEEP_DISABLE() (RCC->APB2LPENR &= ~(RCC_APB2LPENR_SDIOLPEN)) #define __HAL_RCC_SPI4_CLK_SLEEP_DISABLE() (RCC->APB2LPENR &= ~(RCC_APB2LPENR_SPI4LPEN)) #define __HAL_RCC_TIM10_CLK_SLEEP_DISABLE() (RCC->APB2LPENR &= ~(RCC_APB2LPENR_TIM10LPEN)) /** * @} */ #endif /* STM32F401xC || STM32F401xE*/ /*----------------------------------------------------------------------------*/ /*-------------------------------- STM32F410xx -------------------------------*/ #if defined(STM32F410Tx) || defined(STM32F410Cx) || defined(STM32F410Rx) /** @defgroup RCCEx_AHB1_Clock_Enable_Disable AHB1 Peripheral Clock Enable Disable * @brief Enables or disables the AHB1 peripheral clock. * @note After reset, the peripheral clock (used for registers read/write access) * is disabled and the application software has to enable this clock before * using it. */ #define __HAL_RCC_CRC_CLK_ENABLE() do { \ __IO uint32_t tmpreg; \ SET_BIT(RCC->AHB1ENR, RCC_AHB1ENR_CRCEN);\ /* Delay after an RCC peripheral clock enabling */ \ tmpreg = READ_BIT(RCC->AHB1ENR, RCC_AHB1ENR_CRCEN);\ UNUSED(tmpreg); \ } while(0) #define __HAL_RCC_RNG_CLK_ENABLE() do { \ __IO uint32_t tmpreg; \ SET_BIT(RCC->AHB1ENR, RCC_AHB1ENR_RNGEN);\ /* Delay after an RCC peripheral clock enabling */ \ tmpreg = READ_BIT(RCC->AHB1ENR, RCC_AHB1ENR_RNGEN);\ UNUSED(tmpreg); \ } while(0) #define __HAL_RCC_CRC_CLK_DISABLE() (RCC->AHB1ENR &= ~(RCC_AHB1ENR_CRCEN)) #define __HAL_RCC_RNG_CLK_DISABLE() (RCC->AHB1ENR &= ~(RCC_AHB1ENR_RNGEN)) /** * @} */ /** @defgroup RCCEx_APB1_Clock_Enable_Disable APB1 Peripheral Clock Enable Disable * @brief Enable or disable the High Speed APB (APB1) peripheral clock. */ #define __HAL_RCC_TIM6_CLK_ENABLE() do { \ __IO uint32_t tmpreg; \ SET_BIT(RCC->APB1ENR, RCC_APB1ENR_TIM6EN);\ /* Delay after an RCC peripheral clock enabling */ \ tmpreg = READ_BIT(RCC->APB1ENR, RCC_APB1ENR_TIM6EN);\ UNUSED(tmpreg); \ } while(0) #define __HAL_RCC_LPTIM1_CLK_ENABLE() do { \ __IO uint32_t tmpreg; \ SET_BIT(RCC->APB1ENR, RCC_APB1ENR_LPTIM1EN);\ /* Delay after an RCC peripheral clock enabling */ \ tmpreg = READ_BIT(RCC->APB1ENR, RCC_APB1ENR_LPTIM1EN);\ UNUSED(tmpreg); \ } while(0) #define __HAL_RCC_RTCAPB_CLK_ENABLE() do { \ __IO uint32_t tmpreg; \ SET_BIT(RCC->APB1ENR, RCC_APB1ENR_RTCAPBEN);\ /* Delay after an RCC peripheral clock enabling */ \ tmpreg = READ_BIT(RCC->APB1ENR, RCC_APB1ENR_RTCAPBEN);\ UNUSED(tmpreg); \ } while(0) #define __HAL_RCC_FMPI2C1_CLK_ENABLE() do { \ __IO uint32_t tmpreg; \ SET_BIT(RCC->APB1ENR, RCC_APB1ENR_FMPI2C1EN);\ /* Delay after an RCC peripheral clock enabling */ \ tmpreg = READ_BIT(RCC->APB1ENR, RCC_APB1ENR_FMPI2C1EN);\ UNUSED(tmpreg); \ } while(0) #define __HAL_RCC_DAC_CLK_ENABLE() do { \ __IO uint32_t tmpreg; \ SET_BIT(RCC->APB1ENR, RCC_APB1ENR_DACEN);\ /* Delay after an RCC peripheral clock enabling */ \ tmpreg = READ_BIT(RCC->APB1ENR, RCC_APB1ENR_DACEN);\ UNUSED(tmpreg); \ } while(0) #define __HAL_RCC_TIM6_CLK_DISABLE() (RCC->APB1ENR &= ~(RCC_APB1ENR_TIM6EN)) #define __HAL_RCC_RTCAPB_CLK_DISABLE() (RCC->APB1ENR &= ~(RCC_APB1ENR_RTCAPBEN)) #define __HAL_RCC_LPTIM1_CLK_DISABLE() (RCC->APB1ENR &= ~(RCC_APB1ENR_LPTIM1EN)) #define __HAL_RCC_FMPI2C1_CLK_DISABLE() (RCC->APB1ENR &= ~(RCC_APB1ENR_FMPI2C1EN)) #define __HAL_RCC_DAC_CLK_DISABLE() (RCC->APB1ENR &= ~(RCC_APB1ENR_DACEN)) /** * @} */ /** @defgroup RCCEx_APB2_Clock_Enable_Disable APB2 Peripheral Clock Enable Disable * @brief Enable or disable the High Speed APB (APB2) peripheral clock. */ #define __HAL_RCC_SPI5_CLK_ENABLE() do { \ __IO uint32_t tmpreg; \ SET_BIT(RCC->APB2ENR, RCC_APB2ENR_SPI5EN);\ /* Delay after an RCC peripheral clock enabling */ \ tmpreg = READ_BIT(RCC->APB2ENR, RCC_APB2ENR_SPI5EN);\ UNUSED(tmpreg); \ } while(0) #define __HAL_RCC_EXTIT_CLK_ENABLE() do { \ __IO uint32_t tmpreg; \ SET_BIT(RCC->APB2ENR, RCC_APB2ENR_EXTITEN);\ /* Delay after an RCC peripheral clock enabling */ \ tmpreg = READ_BIT(RCC->APB2ENR, RCC_APB2ENR_EXTITEN);\ UNUSED(tmpreg); \ } while(0) #define __HAL_RCC_SPI5_CLK_DISABLE() (RCC->APB2ENR &= ~(RCC_APB2ENR_SPI5EN)) #define __HAL_RCC_EXTIT_CLK_DISABLE() (RCC->APB2ENR &= ~(RCC_APB2ENR_EXTITEN)) /** * @} */ /** @defgroup RCCEx_AHB1_Force_Release_Reset AHB1 Force Release Reset * @brief Force or release AHB1 peripheral reset. */ #define __HAL_RCC_CRC_FORCE_RESET() (RCC->AHB1RSTR |= (RCC_AHB1RSTR_CRCRST)) #define __HAL_RCC_RNG_FORCE_RESET() (RCC->AHB1RSTR |= (RCC_AHB1RSTR_RNGRST)) #define __HAL_RCC_CRC_RELEASE_RESET() (RCC->AHB1RSTR &= ~(RCC_AHB1RSTR_CRCRST)) #define __HAL_RCC_RNG_RELEASE_RESET() (RCC->AHB1RSTR &= ~(RCC_AHB1RSTR_RNGRST)) /** * @} */ /** @defgroup RCCEx_AHB2_Force_Release_Reset AHB2 Force Release Reset * @brief Force or release AHB2 peripheral reset. * @{ */ #define __HAL_RCC_AHB2_FORCE_RESET() #define __HAL_RCC_AHB2_RELEASE_RESET() /** * @} */ /** @defgroup RCCEx_AHB3_Force_Release_Reset AHB3 Force Release Reset * @brief Force or release AHB3 peripheral reset. * @{ */ #define __HAL_RCC_AHB3_FORCE_RESET() #define __HAL_RCC_AHB3_RELEASE_RESET() /** * @} */ /** @defgroup RCCEx_APB1_Force_Release_Reset APB1 Force Release Reset * @brief Force or release APB1 peripheral reset. */ #define __HAL_RCC_TIM6_FORCE_RESET() (RCC->APB1RSTR |= (RCC_APB1RSTR_TIM6RST)) #define __HAL_RCC_LPTIM1_FORCE_RESET() (RCC->APB1RSTR |= (RCC_APB1RSTR_LPTIM1RST)) #define __HAL_RCC_FMPI2C1_FORCE_RESET() (RCC->APB1RSTR |= (RCC_APB1RSTR_FMPI2C1RST)) #define __HAL_RCC_DAC_FORCE_RESET() (RCC->APB1RSTR |= (RCC_APB1RSTR_DACRST)) #define __HAL_RCC_TIM6_RELEASE_RESET() (RCC->APB1RSTR &= ~(RCC_APB1RSTR_TIM6RST)) #define __HAL_RCC_LPTIM1_RELEASE_RESET() (RCC->APB1RSTR &= ~(RCC_APB1RSTR_LPTIM1RST)) #define __HAL_RCC_FMPI2C1_RELEASE_RESET() (RCC->APB1RSTR &= ~(RCC_APB1RSTR_FMPI2C1RST)) #define __HAL_RCC_DAC_RELEASE_RESET() (RCC->APB1RSTR &= ~(RCC_APB1RSTR_DACRST)) /** * @} */ /** @defgroup RCCEx_APB2_Force_Release_Reset APB2 Force Release Reset * @brief Force or release APB2 peripheral reset. */ #define __HAL_RCC_SPI5_FORCE_RESET() (RCC->APB2RSTR |= (RCC_APB2RSTR_SPI5RST)) #define __HAL_RCC_SPI5_RELEASE_RESET() (RCC->APB2RSTR &= ~(RCC_APB2RSTR_SPI5RST)) /** * @} */ /** @defgroup RCCEx_AHB1_LowPower_Enable_Disable AHB1 Peripheral Low Power Enable Disable * @brief Enable or disable the AHB1 peripheral clock during Low Power (Sleep) mode. * @note Peripheral clock gating in SLEEP mode can be used to further reduce * power consumption. * @note After wakeup from SLEEP mode, the peripheral clock is enabled again. * @note By default, all peripheral clocks are enabled during SLEEP mode. */ #define __HAL_RCC_RNG_CLK_SLEEP_ENABLE() (RCC->AHB1LPENR |= (RCC_AHB1LPENR_RNGLPEN)) #define __HAL_RCC_CRC_CLK_SLEEP_ENABLE() (RCC->AHB1LPENR |= (RCC_AHB1LPENR_CRCLPEN)) #define __HAL_RCC_FLITF_CLK_SLEEP_ENABLE() (RCC->AHB1LPENR |= (RCC_AHB1LPENR_FLITFLPEN)) #define __HAL_RCC_SRAM1_CLK_SLEEP_ENABLE() (RCC->AHB1LPENR |= (RCC_AHB1LPENR_SRAM1LPEN)) #define __HAL_RCC_RNG_CLK_SLEEP_DISABLE() (RCC->AHB1LPENR &= ~(RCC_AHB1LPENR_RNGLPEN)) #define __HAL_RCC_CRC_CLK_SLEEP_DISABLE() (RCC->AHB1LPENR &= ~(RCC_AHB1LPENR_CRCLPEN)) #define __HAL_RCC_FLITF_CLK_SLEEP_DISABLE() (RCC->AHB1LPENR &= ~(RCC_AHB1LPENR_FLITFLPEN)) #define __HAL_RCC_SRAM1_CLK_SLEEP_DISABLE() (RCC->AHB1LPENR &= ~(RCC_AHB1LPENR_SRAM1LPEN)) /** * @} */ /** @defgroup RCCEx_APB1_LowPower_Enable_Disable APB1 Peripheral Low Power Enable Disable * @brief Enable or disable the APB1 peripheral clock during Low Power (Sleep) mode. */ #define __HAL_RCC_TIM6_CLK_SLEEP_ENABLE() (RCC->APB1LPENR |= (RCC_APB1LPENR_TIM6LPEN)) #define __HAL_RCC_LPTIM1_CLK_SLEEP_ENABLE() (RCC->APB1LPENR |= (RCC_APB1LPENR_LPTIM1LPEN)) #define __HAL_RCC_RTCAPB_CLK_SLEEP_ENABLE() (RCC->APB1LPENR |= (RCC_APB1LPENR_RTCAPBLPEN)) #define __HAL_RCC_FMPI2C1_CLK_SLEEP_ENABLE() (RCC->APB1LPENR |= (RCC_APB1LPENR_FMPI2C1LPEN)) #define __HAL_RCC_DAC_CLK_SLEEP_ENABLE() (RCC->APB1LPENR |= (RCC_APB1LPENR_DACLPEN)) #define __HAL_RCC_TIM6_CLK_SLEEP_DISABLE() (RCC->APB1LPENR &= ~(RCC_APB1LPENR_TIM6LPEN)) #define __HAL_RCC_LPTIM1_CLK_SLEEP_DISABLE() (RCC->APB1LPENR &= ~(RCC_APB1LPENR_LPTIM1LPEN)) #define __HAL_RCC_RTCAPB_CLK_SLEEP_DISABLE() (RCC->APB1LPENR &= ~(RCC_APB1LPENR_RTCAPBLPEN)) #define __HAL_RCC_FMPI2C1_CLK_SLEEP_DISABLE() (RCC->APB1LPENR &= ~(RCC_APB1LPENR_FMPI2C1LPEN)) #define __HAL_RCC_DAC_CLK_SLEEP_DISABLE() (RCC->APB1LPENR &= ~(RCC_APB1LPENR_DACLPEN)) /** * @} */ /** @defgroup RCCEx_APB2_LowPower_Enable_Disable APB2 Peripheral Low Power Enable Disable * @brief Enable or disable the APB2 peripheral clock during Low Power (Sleep) mode. */ #define __HAL_RCC_SPI5_CLK_SLEEP_ENABLE() (RCC->APB2LPENR |= (RCC_APB2LPENR_SPI5LPEN)) #define __HAL_RCC_EXTIT_CLK_SLEEP_ENABLE() (RCC->APB2LPENR |= (RCC_APB2LPENR_EXTITLPEN)) #define __HAL_RCC_SPI5_CLK_SLEEP_DISABLE() (RCC->APB2LPENR &= ~(RCC_APB2LPENR_SPI5LPEN)) #define __HAL_RCC_EXTIT_CLK_SLEEP_DISABLE() (RCC->APB2LPENR &= ~(RCC_APB2LPENR_EXTITLPEN)) /** * @} */ #endif /* STM32F410Tx || STM32F410Cx || STM32F410Rx */ /*----------------------------------------------------------------------------*/ /*-------------------------------- STM32F411xx -------------------------------*/ #if defined(STM32F411xE) /** @defgroup RCCEx_AHB1_Clock_Enable_Disable AHB1 Peripheral Clock Enable Disable * @brief Enables or disables the AHB1 peripheral clock. * @note After reset, the peripheral clock (used for registers read/write access) * is disabled and the application software has to enable this clock before * using it. */ #define __HAL_RCC_BKPSRAM_CLK_ENABLE() do { \ __IO uint32_t tmpreg; \ SET_BIT(RCC->AHB1ENR, RCC_AHB1ENR_BKPSRAMEN);\ /* Delay after an RCC peripheral clock enabling */ \ tmpreg = READ_BIT(RCC->AHB1ENR, RCC_AHB1ENR_BKPSRAMEN);\ UNUSED(tmpreg); \ } while(0) #define __HAL_RCC_CCMDATARAMEN_CLK_ENABLE() do { \ __IO uint32_t tmpreg; \ SET_BIT(RCC->AHB1ENR, RCC_AHB1ENR_CCMDATARAMEN);\ /* Delay after an RCC peripheral clock enabling */ \ tmpreg = READ_BIT(RCC->AHB1ENR, RCC_AHB1ENR_CCMDATARAMEN);\ UNUSED(tmpreg); \ } while(0) #define __HAL_RCC_GPIOD_CLK_ENABLE() do { \ __IO uint32_t tmpreg; \ SET_BIT(RCC->AHB1ENR, RCC_AHB1ENR_GPIODEN);\ /* Delay after an RCC peripheral clock enabling */ \ tmpreg = READ_BIT(RCC->AHB1ENR, RCC_AHB1ENR_GPIODEN);\ UNUSED(tmpreg); \ } while(0) #define __HAL_RCC_GPIOE_CLK_ENABLE() do { \ __IO uint32_t tmpreg; \ SET_BIT(RCC->AHB1ENR, RCC_AHB1ENR_GPIOEEN);\ /* Delay after an RCC peripheral clock enabling */ \ tmpreg = READ_BIT(RCC->AHB1ENR, RCC_AHB1ENR_GPIOEEN);\ UNUSED(tmpreg); \ } while(0) #define __HAL_RCC_CRC_CLK_ENABLE() do { \ __IO uint32_t tmpreg; \ SET_BIT(RCC->AHB1ENR, RCC_AHB1ENR_CRCEN);\ /* Delay after an RCC peripheral clock enabling */ \ tmpreg = READ_BIT(RCC->AHB1ENR, RCC_AHB1ENR_CRCEN);\ UNUSED(tmpreg); \ } while(0) #define __HAL_RCC_GPIOD_CLK_DISABLE() (RCC->AHB1ENR &= ~(RCC_AHB1ENR_GPIODEN)) #define __HAL_RCC_GPIOE_CLK_DISABLE() (RCC->AHB1ENR &= ~(RCC_AHB1ENR_GPIOEEN)) #define __HAL_RCC_BKPSRAM_CLK_DISABLE() (RCC->AHB1ENR &= ~(RCC_AHB1ENR_BKPSRAMEN)) #define __HAL_RCC_CCMDATARAMEN_CLK_DISABLE() (RCC->AHB1ENR &= ~(RCC_AHB1ENR_CCMDATARAMEN)) #define __HAL_RCC_CRC_CLK_DISABLE() (RCC->AHB1ENR &= ~(RCC_AHB1ENR_CRCEN)) /** * @} */ /** @defgroup RCCEX_AHB2_Clock_Enable_Disable AHB2 Peripheral Clock Enable Disable * @brief Enable or disable the AHB2 peripheral clock. * @note After reset, the peripheral clock (used for registers read/write access) * is disabled and the application software has to enable this clock before * using it. * @{ */ #define __HAL_RCC_USB_OTG_FS_CLK_ENABLE() do {(RCC->AHB2ENR |= (RCC_AHB2ENR_OTGFSEN));\ __HAL_RCC_SYSCFG_CLK_ENABLE();\ }while(0) #define __HAL_RCC_USB_OTG_FS_CLK_DISABLE() do { (RCC->AHB2ENR &= ~(RCC_AHB2ENR_OTGFSEN));\ __HAL_RCC_SYSCFG_CLK_DISABLE();\ }while(0) /** * @} */ /** @defgroup RCCEx_APB1_Clock_Enable_Disable APB1 Peripheral Clock Enable Disable * @brief Enable or disable the Low Speed APB (APB1) peripheral clock. * @note After reset, the peripheral clock (used for registers read/write access) * is disabled and the application software has to enable this clock before * using it. */ #define __HAL_RCC_TIM2_CLK_ENABLE() do { \ __IO uint32_t tmpreg; \ SET_BIT(RCC->APB1ENR, RCC_APB1ENR_TIM2EN);\ /* Delay after an RCC peripheral clock enabling */ \ tmpreg = READ_BIT(RCC->APB1ENR, RCC_APB1ENR_TIM2EN);\ UNUSED(tmpreg); \ } while(0) #define __HAL_RCC_TIM3_CLK_ENABLE() do { \ __IO uint32_t tmpreg; \ SET_BIT(RCC->APB1ENR, RCC_APB1ENR_TIM3EN);\ /* Delay after an RCC peripheral clock enabling */ \ tmpreg = READ_BIT(RCC->APB1ENR, RCC_APB1ENR_TIM3EN);\ UNUSED(tmpreg); \ } while(0) #define __HAL_RCC_TIM4_CLK_ENABLE() do { \ __IO uint32_t tmpreg; \ SET_BIT(RCC->APB1ENR, RCC_APB1ENR_TIM4EN);\ /* Delay after an RCC peripheral clock enabling */ \ tmpreg = READ_BIT(RCC->APB1ENR, RCC_APB1ENR_TIM4EN);\ UNUSED(tmpreg); \ } while(0) #define __HAL_RCC_SPI3_CLK_ENABLE() do { \ __IO uint32_t tmpreg; \ SET_BIT(RCC->APB1ENR, RCC_APB1ENR_SPI3EN);\ /* Delay after an RCC peripheral clock enabling */ \ tmpreg = READ_BIT(RCC->APB1ENR, RCC_APB1ENR_SPI3EN);\ UNUSED(tmpreg); \ } while(0) #define __HAL_RCC_I2C3_CLK_ENABLE() do { \ __IO uint32_t tmpreg; \ SET_BIT(RCC->APB1ENR, RCC_APB1ENR_I2C3EN);\ /* Delay after an RCC peripheral clock enabling */ \ tmpreg = READ_BIT(RCC->APB1ENR, RCC_APB1ENR_I2C3EN);\ UNUSED(tmpreg); \ } while(0) #define __HAL_RCC_TIM2_CLK_DISABLE() (RCC->APB1ENR &= ~(RCC_APB1ENR_TIM2EN)) #define __HAL_RCC_TIM3_CLK_DISABLE() (RCC->APB1ENR &= ~(RCC_APB1ENR_TIM3EN)) #define __HAL_RCC_TIM4_CLK_DISABLE() (RCC->APB1ENR &= ~(RCC_APB1ENR_TIM4EN)) #define __HAL_RCC_SPI3_CLK_DISABLE() (RCC->APB1ENR &= ~(RCC_APB1ENR_SPI3EN)) #define __HAL_RCC_I2C3_CLK_DISABLE() (RCC->APB1ENR &= ~(RCC_APB1ENR_I2C3EN)) /** * @} */ /** @defgroup RCCEx_APB2_Clock_Enable_Disable APB2 Peripheral Clock Enable Disable * @brief Enable or disable the High Speed APB (APB2) peripheral clock. */ #define __HAL_RCC_SPI5_CLK_ENABLE() do { \ __IO uint32_t tmpreg; \ SET_BIT(RCC->APB2ENR, RCC_APB2ENR_SPI5EN);\ /* Delay after an RCC peripheral clock enabling */ \ tmpreg = READ_BIT(RCC->APB2ENR, RCC_APB2ENR_SPI5EN);\ UNUSED(tmpreg); \ } while(0) #define __HAL_RCC_SDIO_CLK_ENABLE() do { \ __IO uint32_t tmpreg; \ SET_BIT(RCC->APB2ENR, RCC_APB2ENR_SDIOEN);\ /* Delay after an RCC peripheral clock enabling */ \ tmpreg = READ_BIT(RCC->APB2ENR, RCC_APB2ENR_SDIOEN);\ UNUSED(tmpreg); \ } while(0) #define __HAL_RCC_SPI4_CLK_ENABLE() do { \ __IO uint32_t tmpreg; \ SET_BIT(RCC->APB2ENR, RCC_APB2ENR_SPI4EN);\ /* Delay after an RCC peripheral clock enabling */ \ tmpreg = READ_BIT(RCC->APB2ENR, RCC_APB2ENR_SPI4EN);\ UNUSED(tmpreg); \ } while(0) #define __HAL_RCC_TIM10_CLK_ENABLE() do { \ __IO uint32_t tmpreg; \ SET_BIT(RCC->APB2ENR, RCC_APB2ENR_TIM10EN);\ /* Delay after an RCC peripheral clock enabling */ \ tmpreg = READ_BIT(RCC->APB2ENR, RCC_APB2ENR_TIM10EN);\ UNUSED(tmpreg); \ } while(0) #define __HAL_RCC_SDIO_CLK_DISABLE() (RCC->APB2ENR &= ~(RCC_APB2ENR_SDIOEN)) #define __HAL_RCC_SPI4_CLK_DISABLE() (RCC->APB2ENR &= ~(RCC_APB2ENR_SPI4EN)) #define __HAL_RCC_TIM10_CLK_DISABLE() (RCC->APB2ENR &= ~(RCC_APB2ENR_TIM10EN)) #define __HAL_RCC_SPI5_CLK_DISABLE() (RCC->APB2ENR &= ~(RCC_APB2ENR_SPI5EN)) /** * @} */ /** @defgroup RCCEx_AHB1_Force_Release_Reset AHB1 Force Release Reset * @brief Force or release AHB1 peripheral reset. */ #define __HAL_RCC_GPIOD_FORCE_RESET() (RCC->AHB1RSTR |= (RCC_AHB1RSTR_GPIODRST)) #define __HAL_RCC_GPIOE_FORCE_RESET() (RCC->AHB1RSTR |= (RCC_AHB1RSTR_GPIOERST)) #define __HAL_RCC_CRC_FORCE_RESET() (RCC->AHB1RSTR |= (RCC_AHB1RSTR_CRCRST)) #define __HAL_RCC_GPIOD_RELEASE_RESET() (RCC->AHB1RSTR &= ~(RCC_AHB1RSTR_GPIODRST)) #define __HAL_RCC_GPIOE_RELEASE_RESET() (RCC->AHB1RSTR &= ~(RCC_AHB1RSTR_GPIOERST)) #define __HAL_RCC_CRC_RELEASE_RESET() (RCC->AHB1RSTR &= ~(RCC_AHB1RSTR_CRCRST)) /** * @} */ /** @defgroup RCCEx_AHB2_Force_Release_Reset AHB2 Force Release Reset * @brief Force or release AHB2 peripheral reset. * @{ */ #define __HAL_RCC_AHB2_FORCE_RESET() (RCC->AHB2RSTR = 0xFFFFFFFF) #define __HAL_RCC_USB_OTG_FS_FORCE_RESET() (RCC->AHB2RSTR |= (RCC_AHB2RSTR_OTGFSRST)) #define __HAL_RCC_AHB2_RELEASE_RESET() (RCC->AHB2RSTR = 0x00) #define __HAL_RCC_USB_OTG_FS_RELEASE_RESET() (RCC->AHB2RSTR &= ~(RCC_AHB2RSTR_OTGFSRST)) /** * @} */ /** @defgroup RCCEx_AHB3_Force_Release_Reset AHB3 Force Release Reset * @brief Force or release AHB3 peripheral reset. * @{ */ #define __HAL_RCC_AHB3_FORCE_RESET() (RCC->AHB3RSTR = 0xFFFFFFFF) #define __HAL_RCC_AHB3_RELEASE_RESET() (RCC->AHB3RSTR = 0x00) /** * @} */ /** @defgroup RCCEx_APB1_Force_Release_Reset APB1 Force Release Reset * @brief Force or release APB1 peripheral reset. */ #define __HAL_RCC_TIM2_FORCE_RESET() (RCC->APB1RSTR |= (RCC_APB1RSTR_TIM2RST)) #define __HAL_RCC_TIM3_FORCE_RESET() (RCC->APB1RSTR |= (RCC_APB1RSTR_TIM3RST)) #define __HAL_RCC_TIM4_FORCE_RESET() (RCC->APB1RSTR |= (RCC_APB1RSTR_TIM4RST)) #define __HAL_RCC_SPI3_FORCE_RESET() (RCC->APB1RSTR |= (RCC_APB1RSTR_SPI3RST)) #define __HAL_RCC_I2C3_FORCE_RESET() (RCC->APB1RSTR |= (RCC_APB1RSTR_I2C3RST)) #define __HAL_RCC_TIM2_RELEASE_RESET() (RCC->APB1RSTR &= ~(RCC_APB1RSTR_TIM2RST)) #define __HAL_RCC_TIM3_RELEASE_RESET() (RCC->APB1RSTR &= ~(RCC_APB1RSTR_TIM3RST)) #define __HAL_RCC_TIM4_RELEASE_RESET() (RCC->APB1RSTR &= ~(RCC_APB1RSTR_TIM4RST)) #define __HAL_RCC_SPI3_RELEASE_RESET() (RCC->APB1RSTR &= ~(RCC_APB1RSTR_SPI3RST)) #define __HAL_RCC_I2C3_RELEASE_RESET() (RCC->APB1RSTR &= ~(RCC_APB1RSTR_I2C3RST)) /** * @} */ /** @defgroup RCCEx_APB2_Force_Release_Reset APB2 Force Release Reset * @brief Force or release APB2 peripheral reset. */ #define __HAL_RCC_SPI5_FORCE_RESET() (RCC->APB2RSTR |= (RCC_APB2RSTR_SPI5RST)) #define __HAL_RCC_SDIO_FORCE_RESET() (RCC->APB2RSTR |= (RCC_APB2RSTR_SDIORST)) #define __HAL_RCC_SPI4_FORCE_RESET() (RCC->APB2RSTR |= (RCC_APB2RSTR_SPI4RST)) #define __HAL_RCC_TIM10_FORCE_RESET() (RCC->APB2RSTR |= (RCC_APB2RSTR_TIM10RST)) #define __HAL_RCC_SDIO_RELEASE_RESET() (RCC->APB2RSTR &= ~(RCC_APB2RSTR_SDIORST)) #define __HAL_RCC_SPI4_RELEASE_RESET() (RCC->APB2RSTR &= ~(RCC_APB2RSTR_SPI4RST)) #define __HAL_RCC_TIM10_RELEASE_RESET() (RCC->APB2RSTR &= ~(RCC_APB2RSTR_TIM10RST)) #define __HAL_RCC_SPI5_RELEASE_RESET() (RCC->APB2RSTR &= ~(RCC_APB2RSTR_SPI5RST)) /** * @} */ /** @defgroup RCCEx_AHB1_LowPower_Enable_Disable AHB1 Peripheral Low Power Enable Disable * @brief Enable or disable the AHB1 peripheral clock during Low Power (Sleep) mode. * @note Peripheral clock gating in SLEEP mode can be used to further reduce * power consumption. * @note After wakeup from SLEEP mode, the peripheral clock is enabled again. * @note By default, all peripheral clocks are enabled during SLEEP mode. */ #define __HAL_RCC_GPIOD_CLK_SLEEP_ENABLE() (RCC->AHB1LPENR |= (RCC_AHB1LPENR_GPIODLPEN)) #define __HAL_RCC_GPIOE_CLK_SLEEP_ENABLE() (RCC->AHB1LPENR |= (RCC_AHB1LPENR_GPIOELPEN)) #define __HAL_RCC_CRC_CLK_SLEEP_ENABLE() (RCC->AHB1LPENR |= (RCC_AHB1LPENR_CRCLPEN)) #define __HAL_RCC_FLITF_CLK_SLEEP_ENABLE() (RCC->AHB1LPENR |= (RCC_AHB1LPENR_FLITFLPEN)) #define __HAL_RCC_SRAM1_CLK_SLEEP_ENABLE() (RCC->AHB1LPENR |= (RCC_AHB1LPENR_SRAM1LPEN)) #define __HAL_RCC_GPIOD_CLK_SLEEP_DISABLE() (RCC->AHB1LPENR &= ~(RCC_AHB1LPENR_GPIODLPEN)) #define __HAL_RCC_GPIOE_CLK_SLEEP_DISABLE() (RCC->AHB1LPENR &= ~(RCC_AHB1LPENR_GPIOELPEN)) #define __HAL_RCC_CRC_CLK_SLEEP_DISABLE() (RCC->AHB1LPENR &= ~(RCC_AHB1LPENR_CRCLPEN)) #define __HAL_RCC_FLITF_CLK_SLEEP_DISABLE() (RCC->AHB1LPENR &= ~(RCC_AHB1LPENR_FLITFLPEN)) #define __HAL_RCC_SRAM1_CLK_SLEEP_DISABLE() (RCC->AHB1LPENR &= ~(RCC_AHB1LPENR_SRAM1LPEN)) /** * @} */ /** @defgroup RCCEx_AHB2_LowPower_Enable_Disable AHB2 Peripheral Low Power Enable Disable * @brief Enable or disable the AHB2 peripheral clock during Low Power (Sleep) mode. * @note Peripheral clock gating in SLEEP mode can be used to further reduce * power consumption. * @note After wake-up from SLEEP mode, the peripheral clock is enabled again. * @note By default, all peripheral clocks are enabled during SLEEP mode. * @{ */ #define __HAL_RCC_USB_OTG_FS_CLK_SLEEP_ENABLE() (RCC->AHB2LPENR |= (RCC_AHB2LPENR_OTGFSLPEN)) #define __HAL_RCC_USB_OTG_FS_CLK_SLEEP_DISABLE() (RCC->AHB2LPENR &= ~(RCC_AHB2LPENR_OTGFSLPEN)) /** * @} */ /** @defgroup RCCEx_APB1_LowPower_Enable_Disable APB1 Peripheral Low Power Enable Disable * @brief Enable or disable the APB1 peripheral clock during Low Power (Sleep) mode. */ #define __HAL_RCC_TIM2_CLK_SLEEP_ENABLE() (RCC->APB1LPENR |= (RCC_APB1LPENR_TIM2LPEN)) #define __HAL_RCC_TIM3_CLK_SLEEP_ENABLE() (RCC->APB1LPENR |= (RCC_APB1LPENR_TIM3LPEN)) #define __HAL_RCC_TIM4_CLK_SLEEP_ENABLE() (RCC->APB1LPENR |= (RCC_APB1LPENR_TIM4LPEN)) #define __HAL_RCC_SPI3_CLK_SLEEP_ENABLE() (RCC->APB1LPENR |= (RCC_APB1LPENR_SPI3LPEN)) #define __HAL_RCC_I2C3_CLK_SLEEP_ENABLE() (RCC->APB1LPENR |= (RCC_APB1LPENR_I2C3LPEN)) #define __HAL_RCC_TIM2_CLK_SLEEP_DISABLE() (RCC->APB1LPENR &= ~(RCC_APB1LPENR_TIM2LPEN)) #define __HAL_RCC_TIM3_CLK_SLEEP_DISABLE() (RCC->APB1LPENR &= ~(RCC_APB1LPENR_TIM3LPEN)) #define __HAL_RCC_TIM4_CLK_SLEEP_DISABLE() (RCC->APB1LPENR &= ~(RCC_APB1LPENR_TIM4LPEN)) #define __HAL_RCC_SPI3_CLK_SLEEP_DISABLE() (RCC->APB1LPENR &= ~(RCC_APB1LPENR_SPI3LPEN)) #define __HAL_RCC_I2C3_CLK_SLEEP_DISABLE() (RCC->APB1LPENR &= ~(RCC_APB1LPENR_I2C3LPEN)) /** * @} */ /** @defgroup RCCEx_APB2_LowPower_Enable_Disable APB2 Peripheral Low Power Enable Disable * @brief Enable or disable the APB2 peripheral clock during Low Power (Sleep) mode. */ #define __HAL_RCC_SPI5_CLK_SLEEP_ENABLE() (RCC->APB2LPENR |= (RCC_APB2LPENR_SPI5LPEN)) #define __HAL_RCC_SDIO_CLK_SLEEP_ENABLE() (RCC->APB2LPENR |= (RCC_APB2LPENR_SDIOLPEN)) #define __HAL_RCC_SPI4_CLK_SLEEP_ENABLE() (RCC->APB2LPENR |= (RCC_APB2LPENR_SPI4LPEN)) #define __HAL_RCC_TIM10_CLK_SLEEP_ENABLE() (RCC->APB2LPENR |= (RCC_APB2LPENR_TIM10LPEN)) #define __HAL_RCC_SDIO_CLK_SLEEP_DISABLE() (RCC->APB2LPENR &= ~(RCC_APB2LPENR_SDIOLPEN)) #define __HAL_RCC_SPI4_CLK_SLEEP_DISABLE() (RCC->APB2LPENR &= ~(RCC_APB2LPENR_SPI4LPEN)) #define __HAL_RCC_TIM10_CLK_SLEEP_DISABLE() (RCC->APB2LPENR &= ~(RCC_APB2LPENR_TIM10LPEN)) #define __HAL_RCC_SPI5_CLK_SLEEP_DISABLE() (RCC->APB2LPENR &= ~(RCC_APB2LPENR_SPI5LPEN)) /** * @} */ #endif /* STM32F411xE */ /*----------------------------------------------------------------------------*/ /*---------------------------------- STM32F446xx -----------------------------*/ #if defined(STM32F446xx) /** @defgroup RCCEx_AHB1_Clock_Enable_Disable AHB1 Peripheral Clock Enable Disable * @brief Enables or disables the AHB1 peripheral clock. * @note After reset, the peripheral clock (used for registers read/write access) * is disabled and the application software has to enable this clock before * using it. */ #define __HAL_RCC_BKPSRAM_CLK_ENABLE() do { \ __IO uint32_t tmpreg; \ SET_BIT(RCC->AHB1ENR, RCC_AHB1ENR_BKPSRAMEN);\ /* Delay after an RCC peripheral clock enabling */ \ tmpreg = READ_BIT(RCC->AHB1ENR, RCC_AHB1ENR_BKPSRAMEN);\ UNUSED(tmpreg); \ } while(0) #define __HAL_RCC_CCMDATARAMEN_CLK_ENABLE() do { \ __IO uint32_t tmpreg; \ SET_BIT(RCC->AHB1ENR, RCC_AHB1ENR_CCMDATARAMEN);\ /* Delay after an RCC peripheral clock enabling */ \ tmpreg = READ_BIT(RCC->AHB1ENR, RCC_AHB1ENR_CCMDATARAMEN);\ UNUSED(tmpreg); \ } while(0) #define __HAL_RCC_CRC_CLK_ENABLE() do { \ __IO uint32_t tmpreg; \ SET_BIT(RCC->AHB1ENR, RCC_AHB1ENR_CRCEN);\ /* Delay after an RCC peripheral clock enabling */ \ tmpreg = READ_BIT(RCC->AHB1ENR, RCC_AHB1ENR_CRCEN);\ UNUSED(tmpreg); \ } while(0) #define __HAL_RCC_GPIOD_CLK_ENABLE() do { \ __IO uint32_t tmpreg; \ SET_BIT(RCC->AHB1ENR, RCC_AHB1ENR_GPIODEN);\ /* Delay after an RCC peripheral clock enabling */ \ tmpreg = READ_BIT(RCC->AHB1ENR, RCC_AHB1ENR_GPIODEN);\ UNUSED(tmpreg); \ } while(0) #define __HAL_RCC_GPIOE_CLK_ENABLE() do { \ __IO uint32_t tmpreg; \ SET_BIT(RCC->AHB1ENR, RCC_AHB1ENR_GPIOEEN);\ /* Delay after an RCC peripheral clock enabling */ \ tmpreg = READ_BIT(RCC->AHB1ENR, RCC_AHB1ENR_GPIOEEN);\ UNUSED(tmpreg); \ } while(0) #define __HAL_RCC_GPIOF_CLK_ENABLE() do { \ __IO uint32_t tmpreg; \ SET_BIT(RCC->AHB1ENR, RCC_AHB1ENR_GPIOFEN);\ /* Delay after an RCC peripheral clock enabling */ \ tmpreg = READ_BIT(RCC->AHB1ENR, RCC_AHB1ENR_GPIOFEN);\ UNUSED(tmpreg); \ } while(0) #define __HAL_RCC_GPIOG_CLK_ENABLE() do { \ __IO uint32_t tmpreg; \ SET_BIT(RCC->AHB1ENR, RCC_AHB1ENR_GPIOGEN);\ /* Delay after an RCC peripheral clock enabling */ \ tmpreg = READ_BIT(RCC->AHB1ENR, RCC_AHB1ENR_GPIOGEN);\ UNUSED(tmpreg); \ } while(0) #define __HAL_RCC_USB_OTG_HS_CLK_ENABLE() do { \ __IO uint32_t tmpreg; \ SET_BIT(RCC->AHB1ENR, RCC_AHB1ENR_OTGHSEN);\ /* Delay after an RCC peripheral clock enabling */ \ tmpreg = READ_BIT(RCC->AHB1ENR, RCC_AHB1ENR_OTGHSEN);\ UNUSED(tmpreg); \ } while(0) #define __HAL_RCC_USB_OTG_HS_ULPI_CLK_ENABLE() do { \ __IO uint32_t tmpreg; \ SET_BIT(RCC->AHB1ENR, RCC_AHB1ENR_OTGHSULPIEN);\ /* Delay after an RCC peripheral clock enabling */ \ tmpreg = READ_BIT(RCC->AHB1ENR, RCC_AHB1ENR_OTGHSULPIEN);\ UNUSED(tmpreg); \ } while(0) #define __HAL_RCC_GPIOD_CLK_DISABLE() (RCC->AHB1ENR &= ~(RCC_AHB1ENR_GPIODEN)) #define __HAL_RCC_GPIOE_CLK_DISABLE() (RCC->AHB1ENR &= ~(RCC_AHB1ENR_GPIOEEN)) #define __HAL_RCC_GPIOF_CLK_DISABLE() (RCC->AHB1ENR &= ~(RCC_AHB1ENR_GPIOFEN)) #define __HAL_RCC_GPIOG_CLK_DISABLE() (RCC->AHB1ENR &= ~(RCC_AHB1ENR_GPIOGEN)) #define __HAL_RCC_USB_OTG_HS_CLK_DISABLE() (RCC->AHB1ENR &= ~(RCC_AHB1ENR_OTGHSEN)) #define __HAL_RCC_USB_OTG_HS_ULPI_CLK_DISABLE() (RCC->AHB1ENR &= ~(RCC_AHB1ENR_OTGHSULPIEN)) #define __HAL_RCC_BKPSRAM_CLK_DISABLE() (RCC->AHB1ENR &= ~(RCC_AHB1ENR_BKPSRAMEN)) #define __HAL_RCC_CCMDATARAMEN_CLK_DISABLE() (RCC->AHB1ENR &= ~(RCC_AHB1ENR_CCMDATARAMEN)) #define __HAL_RCC_CRC_CLK_DISABLE() (RCC->AHB1ENR &= ~(RCC_AHB1ENR_CRCEN)) /** * @} */ /** @defgroup RCCEx_AHB2_Clock_Enable_Disable AHB2 Peripheral Clock Enable Disable * @brief Enable or disable the AHB2 peripheral clock. * @note After reset, the peripheral clock (used for registers read/write access) * is disabled and the application software has to enable this clock before * using it. */ #define __HAL_RCC_DCMI_CLK_ENABLE() do { \ __IO uint32_t tmpreg; \ SET_BIT(RCC->AHB2ENR, RCC_AHB2ENR_DCMIEN);\ /* Delay after an RCC peripheral clock enabling */ \ tmpreg = READ_BIT(RCC->AHB2ENR, RCC_AHB2ENR_DCMIEN);\ UNUSED(tmpreg); \ } while(0) #define __HAL_RCC_DCMI_CLK_DISABLE() (RCC->AHB2ENR &= ~(RCC_AHB2ENR_DCMIEN)) #define __HAL_RCC_USB_OTG_FS_CLK_ENABLE() do {(RCC->AHB2ENR |= (RCC_AHB2ENR_OTGFSEN));\ __HAL_RCC_SYSCFG_CLK_ENABLE();\ }while(0) #define __HAL_RCC_USB_OTG_FS_CLK_DISABLE() do { (RCC->AHB2ENR &= ~(RCC_AHB2ENR_OTGFSEN));\ __HAL_RCC_SYSCFG_CLK_DISABLE();\ }while(0) #define __HAL_RCC_RNG_CLK_ENABLE() do { \ __IO uint32_t tmpreg; \ SET_BIT(RCC->AHB2ENR, RCC_AHB2ENR_RNGEN);\ /* Delay after an RCC peripheral clock enabling */ \ tmpreg = READ_BIT(RCC->AHB2ENR, RCC_AHB2ENR_RNGEN);\ UNUSED(tmpreg); \ } while(0) #define __HAL_RCC_RNG_CLK_DISABLE() (RCC->AHB2ENR &= ~(RCC_AHB2ENR_RNGEN)) /** * @} */ /** @defgroup RCCEx_AHB3_Clock_Enable_Disable AHB3 Peripheral Clock Enable Disable * @brief Enables or disables the AHB3 peripheral clock. * @note After reset, the peripheral clock (used for registers read/write access) * is disabled and the application software has to enable this clock before * using it. */ #define __HAL_RCC_FMC_CLK_ENABLE() do { \ __IO uint32_t tmpreg; \ SET_BIT(RCC->AHB3ENR, RCC_AHB3ENR_FMCEN);\ /* Delay after an RCC peripheral clock enabling */ \ tmpreg = READ_BIT(RCC->AHB3ENR, RCC_AHB3ENR_FMCEN);\ UNUSED(tmpreg); \ } while(0) #define __HAL_RCC_QSPI_CLK_ENABLE() do { \ __IO uint32_t tmpreg; \ SET_BIT(RCC->AHB3ENR, RCC_AHB3ENR_QSPIEN);\ /* Delay after an RCC peripheral clock enabling */ \ tmpreg = READ_BIT(RCC->AHB3ENR, RCC_AHB3ENR_QSPIEN);\ UNUSED(tmpreg); \ } while(0) #define __HAL_RCC_FMC_CLK_DISABLE() (RCC->AHB3ENR &= ~(RCC_AHB3ENR_FMCEN)) #define __HAL_RCC_QSPI_CLK_DISABLE() (RCC->AHB3ENR &= ~(RCC_AHB3ENR_QSPIEN)) /** * @} */ /** @defgroup RCCEx_APB1_Clock_Enable_Disable APB1 Peripheral Clock Enable Disable * @brief Enable or disable the Low Speed APB (APB1) peripheral clock. * @note After reset, the peripheral clock (used for registers read/write access) * is disabled and the application software has to enable this clock before * using it. */ #define __HAL_RCC_TIM6_CLK_ENABLE() do { \ __IO uint32_t tmpreg; \ SET_BIT(RCC->APB1ENR, RCC_APB1ENR_TIM6EN);\ /* Delay after an RCC peripheral clock enabling */ \ tmpreg = READ_BIT(RCC->APB1ENR, RCC_APB1ENR_TIM6EN);\ UNUSED(tmpreg); \ } while(0) #define __HAL_RCC_TIM7_CLK_ENABLE() do { \ __IO uint32_t tmpreg; \ SET_BIT(RCC->APB1ENR, RCC_APB1ENR_TIM7EN);\ /* Delay after an RCC peripheral clock enabling */ \ tmpreg = READ_BIT(RCC->APB1ENR, RCC_APB1ENR_TIM7EN);\ UNUSED(tmpreg); \ } while(0) #define __HAL_RCC_TIM12_CLK_ENABLE() do { \ __IO uint32_t tmpreg; \ SET_BIT(RCC->APB1ENR, RCC_APB1ENR_TIM12EN);\ /* Delay after an RCC peripheral clock enabling */ \ tmpreg = READ_BIT(RCC->APB1ENR, RCC_APB1ENR_TIM12EN);\ UNUSED(tmpreg); \ } while(0) #define __HAL_RCC_TIM13_CLK_ENABLE() do { \ __IO uint32_t tmpreg; \ SET_BIT(RCC->APB1ENR, RCC_APB1ENR_TIM13EN);\ /* Delay after an RCC peripheral clock enabling */ \ tmpreg = READ_BIT(RCC->APB1ENR, RCC_APB1ENR_TIM13EN);\ UNUSED(tmpreg); \ } while(0) #define __HAL_RCC_TIM14_CLK_ENABLE() do { \ __IO uint32_t tmpreg; \ SET_BIT(RCC->APB1ENR, RCC_APB1ENR_TIM14EN);\ /* Delay after an RCC peripheral clock enabling */ \ tmpreg = READ_BIT(RCC->APB1ENR, RCC_APB1ENR_TIM14EN);\ UNUSED(tmpreg); \ } while(0) #define __HAL_RCC_SPDIFRX_CLK_ENABLE() do { \ __IO uint32_t tmpreg; \ SET_BIT(RCC->APB1ENR, RCC_APB1ENR_SPDIFRXEN);\ /* Delay after an RCC peripheral clock enabling */ \ tmpreg = READ_BIT(RCC->APB1ENR, RCC_APB1ENR_SPDIFRXEN);\ UNUSED(tmpreg); \ } while(0) #define __HAL_RCC_USART3_CLK_ENABLE() do { \ __IO uint32_t tmpreg; \ SET_BIT(RCC->APB1ENR, RCC_APB1ENR_USART3EN);\ /* Delay after an RCC peripheral clock enabling */ \ tmpreg = READ_BIT(RCC->APB1ENR, RCC_APB1ENR_USART3EN);\ UNUSED(tmpreg); \ } while(0) #define __HAL_RCC_UART4_CLK_ENABLE() do { \ __IO uint32_t tmpreg; \ SET_BIT(RCC->APB1ENR, RCC_APB1ENR_UART4EN);\ /* Delay after an RCC peripheral clock enabling */ \ tmpreg = READ_BIT(RCC->APB1ENR, RCC_APB1ENR_UART4EN);\ UNUSED(tmpreg); \ } while(0) #define __HAL_RCC_UART5_CLK_ENABLE() do { \ __IO uint32_t tmpreg; \ SET_BIT(RCC->APB1ENR, RCC_APB1ENR_UART5EN);\ /* Delay after an RCC peripheral clock enabling */ \ tmpreg = READ_BIT(RCC->APB1ENR, RCC_APB1ENR_UART5EN);\ UNUSED(tmpreg); \ } while(0) #define __HAL_RCC_FMPI2C1_CLK_ENABLE() do { \ __IO uint32_t tmpreg; \ SET_BIT(RCC->APB1ENR, RCC_APB1ENR_FMPI2C1EN);\ /* Delay after an RCC peripheral clock enabling */ \ tmpreg = READ_BIT(RCC->APB1ENR, RCC_APB1ENR_FMPI2C1EN);\ UNUSED(tmpreg); \ } while(0) #define __HAL_RCC_CAN1_CLK_ENABLE() do { \ __IO uint32_t tmpreg; \ SET_BIT(RCC->APB1ENR, RCC_APB1ENR_CAN1EN);\ /* Delay after an RCC peripheral clock enabling */ \ tmpreg = READ_BIT(RCC->APB1ENR, RCC_APB1ENR_CAN1EN);\ UNUSED(tmpreg); \ } while(0) #define __HAL_RCC_CAN2_CLK_ENABLE() do { \ __IO uint32_t tmpreg; \ SET_BIT(RCC->APB1ENR, RCC_APB1ENR_CAN2EN);\ /* Delay after an RCC peripheral clock enabling */ \ tmpreg = READ_BIT(RCC->APB1ENR, RCC_APB1ENR_CAN2EN);\ UNUSED(tmpreg); \ } while(0) #define __HAL_RCC_CEC_CLK_ENABLE() do { \ __IO uint32_t tmpreg; \ SET_BIT(RCC->APB1ENR, RCC_APB1ENR_CECEN);\ /* Delay after an RCC peripheral clock enabling */ \ tmpreg = READ_BIT(RCC->APB1ENR, RCC_APB1ENR_CECEN);\ UNUSED(tmpreg); \ } while(0) #define __HAL_RCC_DAC_CLK_ENABLE() do { \ __IO uint32_t tmpreg; \ SET_BIT(RCC->APB1ENR, RCC_APB1ENR_DACEN);\ /* Delay after an RCC peripheral clock enabling */ \ tmpreg = READ_BIT(RCC->APB1ENR, RCC_APB1ENR_DACEN);\ UNUSED(tmpreg); \ } while(0) #define __HAL_RCC_TIM2_CLK_ENABLE() do { \ __IO uint32_t tmpreg; \ SET_BIT(RCC->APB1ENR, RCC_APB1ENR_TIM2EN);\ /* Delay after an RCC peripheral clock enabling */ \ tmpreg = READ_BIT(RCC->APB1ENR, RCC_APB1ENR_TIM2EN);\ UNUSED(tmpreg); \ } while(0) #define __HAL_RCC_TIM3_CLK_ENABLE() do { \ __IO uint32_t tmpreg; \ SET_BIT(RCC->APB1ENR, RCC_APB1ENR_TIM3EN);\ /* Delay after an RCC peripheral clock enabling */ \ tmpreg = READ_BIT(RCC->APB1ENR, RCC_APB1ENR_TIM3EN);\ UNUSED(tmpreg); \ } while(0) #define __HAL_RCC_TIM4_CLK_ENABLE() do { \ __IO uint32_t tmpreg; \ SET_BIT(RCC->APB1ENR, RCC_APB1ENR_TIM4EN);\ /* Delay after an RCC peripheral clock enabling */ \ tmpreg = READ_BIT(RCC->APB1ENR, RCC_APB1ENR_TIM4EN);\ UNUSED(tmpreg); \ } while(0) #define __HAL_RCC_SPI3_CLK_ENABLE() do { \ __IO uint32_t tmpreg; \ SET_BIT(RCC->APB1ENR, RCC_APB1ENR_SPI3EN);\ /* Delay after an RCC peripheral clock enabling */ \ tmpreg = READ_BIT(RCC->APB1ENR, RCC_APB1ENR_SPI3EN);\ UNUSED(tmpreg); \ } while(0) #define __HAL_RCC_I2C3_CLK_ENABLE() do { \ __IO uint32_t tmpreg; \ SET_BIT(RCC->APB1ENR, RCC_APB1ENR_I2C3EN);\ /* Delay after an RCC peripheral clock enabling */ \ tmpreg = READ_BIT(RCC->APB1ENR, RCC_APB1ENR_I2C3EN);\ UNUSED(tmpreg); \ } while(0) #define __HAL_RCC_TIM2_CLK_DISABLE() (RCC->APB1ENR &= ~(RCC_APB1ENR_TIM2EN)) #define __HAL_RCC_TIM3_CLK_DISABLE() (RCC->APB1ENR &= ~(RCC_APB1ENR_TIM3EN)) #define __HAL_RCC_TIM4_CLK_DISABLE() (RCC->APB1ENR &= ~(RCC_APB1ENR_TIM4EN)) #define __HAL_RCC_SPI3_CLK_DISABLE() (RCC->APB1ENR &= ~(RCC_APB1ENR_SPI3EN)) #define __HAL_RCC_I2C3_CLK_DISABLE() (RCC->APB1ENR &= ~(RCC_APB1ENR_I2C3EN)) #define __HAL_RCC_TIM6_CLK_DISABLE() (RCC->APB1ENR &= ~(RCC_APB1ENR_TIM6EN)) #define __HAL_RCC_TIM7_CLK_DISABLE() (RCC->APB1ENR &= ~(RCC_APB1ENR_TIM7EN)) #define __HAL_RCC_TIM12_CLK_DISABLE() (RCC->APB1ENR &= ~(RCC_APB1ENR_TIM12EN)) #define __HAL_RCC_TIM13_CLK_DISABLE() (RCC->APB1ENR &= ~(RCC_APB1ENR_TIM13EN)) #define __HAL_RCC_TIM14_CLK_DISABLE() (RCC->APB1ENR &= ~(RCC_APB1ENR_TIM14EN)) #define __HAL_RCC_SPDIFRX_CLK_DISABLE() (RCC->APB1ENR &= ~(RCC_APB1ENR_SPDIFRXEN)) #define __HAL_RCC_USART3_CLK_DISABLE() (RCC->APB1ENR &= ~(RCC_APB1ENR_USART3EN)) #define __HAL_RCC_UART4_CLK_DISABLE() (RCC->APB1ENR &= ~(RCC_APB1ENR_UART4EN)) #define __HAL_RCC_UART5_CLK_DISABLE() (RCC->APB1ENR &= ~(RCC_APB1ENR_UART5EN)) #define __HAL_RCC_FMPI2C1_CLK_DISABLE() (RCC->APB1ENR &= ~(RCC_APB1ENR_FMPI2C1EN)) #define __HAL_RCC_CAN1_CLK_DISABLE() (RCC->APB1ENR &= ~(RCC_APB1ENR_CAN1EN)) #define __HAL_RCC_CAN2_CLK_DISABLE() (RCC->APB1ENR &= ~(RCC_APB1ENR_CAN2EN)) #define __HAL_RCC_CEC_CLK_DISABLE() (RCC->APB1ENR &= ~(RCC_APB1ENR_CECEN)) #define __HAL_RCC_DAC_CLK_DISABLE() (RCC->APB1ENR &= ~(RCC_APB1ENR_DACEN)) /** * @} */ /** @defgroup RCCEx_APB2_Clock_Enable_Disable APB2 Peripheral Clock Enable Disable * @brief Enable or disable the High Speed APB (APB2) peripheral clock. * @note After reset, the peripheral clock (used for registers read/write access) * is disabled and the application software has to enable this clock before * using it. */ #define __HAL_RCC_TIM8_CLK_ENABLE() do { \ __IO uint32_t tmpreg; \ SET_BIT(RCC->APB2ENR, RCC_APB2ENR_TIM8EN);\ /* Delay after an RCC peripheral clock enabling */ \ tmpreg = READ_BIT(RCC->APB2ENR, RCC_APB2ENR_TIM8EN);\ UNUSED(tmpreg); \ } while(0) #define __HAL_RCC_ADC2_CLK_ENABLE() do { \ __IO uint32_t tmpreg; \ SET_BIT(RCC->APB2ENR, RCC_APB2ENR_ADC2EN);\ /* Delay after an RCC peripheral clock enabling */ \ tmpreg = READ_BIT(RCC->APB2ENR, RCC_APB2ENR_ADC2EN);\ UNUSED(tmpreg); \ } while(0) #define __HAL_RCC_ADC3_CLK_ENABLE() do { \ __IO uint32_t tmpreg; \ SET_BIT(RCC->APB2ENR, RCC_APB2ENR_ADC3EN);\ /* Delay after an RCC peripheral clock enabling */ \ tmpreg = READ_BIT(RCC->APB2ENR, RCC_APB2ENR_ADC3EN);\ UNUSED(tmpreg); \ } while(0) #define __HAL_RCC_SAI1_CLK_ENABLE() do { \ __IO uint32_t tmpreg; \ SET_BIT(RCC->APB2ENR, RCC_APB2ENR_SAI1EN);\ /* Delay after an RCC peripheral clock enabling */ \ tmpreg = READ_BIT(RCC->APB2ENR, RCC_APB2ENR_SAI1EN);\ UNUSED(tmpreg); \ } while(0) #define __HAL_RCC_SAI2_CLK_ENABLE() do { \ __IO uint32_t tmpreg; \ SET_BIT(RCC->APB2ENR, RCC_APB2ENR_SAI2EN);\ /* Delay after an RCC peripheral clock enabling */ \ tmpreg = READ_BIT(RCC->APB2ENR, RCC_APB2ENR_SAI2EN);\ UNUSED(tmpreg); \ } while(0) #define __HAL_RCC_SDIO_CLK_ENABLE() do { \ __IO uint32_t tmpreg; \ SET_BIT(RCC->APB2ENR, RCC_APB2ENR_SDIOEN);\ /* Delay after an RCC peripheral clock enabling */ \ tmpreg = READ_BIT(RCC->APB2ENR, RCC_APB2ENR_SDIOEN);\ UNUSED(tmpreg); \ } while(0) #define __HAL_RCC_SPI4_CLK_ENABLE() do { \ __IO uint32_t tmpreg; \ SET_BIT(RCC->APB2ENR, RCC_APB2ENR_SPI4EN);\ /* Delay after an RCC peripheral clock enabling */ \ tmpreg = READ_BIT(RCC->APB2ENR, RCC_APB2ENR_SPI4EN);\ UNUSED(tmpreg); \ } while(0) #define __HAL_RCC_TIM10_CLK_ENABLE() do { \ __IO uint32_t tmpreg; \ SET_BIT(RCC->APB2ENR, RCC_APB2ENR_TIM10EN);\ /* Delay after an RCC peripheral clock enabling */ \ tmpreg = READ_BIT(RCC->APB2ENR, RCC_APB2ENR_TIM10EN);\ UNUSED(tmpreg); \ } while(0) #define __HAL_RCC_SDIO_CLK_DISABLE() (RCC->APB2ENR &= ~(RCC_APB2ENR_SDIOEN)) #define __HAL_RCC_SPI4_CLK_DISABLE() (RCC->APB2ENR &= ~(RCC_APB2ENR_SPI4EN)) #define __HAL_RCC_TIM10_CLK_DISABLE() (RCC->APB2ENR &= ~(RCC_APB2ENR_TIM10EN)) #define __HAL_RCC_TIM8_CLK_DISABLE() (RCC->APB2ENR &= ~(RCC_APB2ENR_TIM8EN)) #define __HAL_RCC_ADC2_CLK_DISABLE() (RCC->APB2ENR &= ~(RCC_APB2ENR_ADC2EN)) #define __HAL_RCC_ADC3_CLK_DISABLE() (RCC->APB2ENR &= ~(RCC_APB2ENR_ADC3EN)) #define __HAL_RCC_SAI1_CLK_DISABLE() (RCC->APB2ENR &= ~(RCC_APB2ENR_SAI1EN)) #define __HAL_RCC_SAI2_CLK_DISABLE() (RCC->APB2ENR &= ~(RCC_APB2ENR_SAI2EN)) /** * @} */ /** @defgroup RCCEx_AHB1_Force_Release_Reset AHB1 Force Release Reset * @brief Force or release AHB1 peripheral reset. */ #define __HAL_RCC_GPIOD_FORCE_RESET() (RCC->AHB1RSTR |= (RCC_AHB1RSTR_GPIODRST)) #define __HAL_RCC_GPIOE_FORCE_RESET() (RCC->AHB1RSTR |= (RCC_AHB1RSTR_GPIOERST)) #define __HAL_RCC_GPIOF_FORCE_RESET() (RCC->AHB1RSTR |= (RCC_AHB1RSTR_GPIOFRST)) #define __HAL_RCC_GPIOG_FORCE_RESET() (RCC->AHB1RSTR |= (RCC_AHB1RSTR_GPIOGRST)) #define __HAL_RCC_USB_OTG_HS_FORCE_RESET() (RCC->AHB1RSTR |= (RCC_AHB1RSTR_OTGHRST)) #define __HAL_RCC_CRC_FORCE_RESET() (RCC->AHB1RSTR |= (RCC_AHB1RSTR_CRCRST)) #define __HAL_RCC_GPIOD_RELEASE_RESET() (RCC->AHB1RSTR &= ~(RCC_AHB1RSTR_GPIODRST)) #define __HAL_RCC_GPIOE_RELEASE_RESET() (RCC->AHB1RSTR &= ~(RCC_AHB1RSTR_GPIOERST)) #define __HAL_RCC_GPIOF_RELEASE_RESET() (RCC->AHB1RSTR &= ~(RCC_AHB1RSTR_GPIOFRST)) #define __HAL_RCC_GPIOG_RELEASE_RESET() (RCC->AHB1RSTR &= ~(RCC_AHB1RSTR_GPIOGRST)) #define __HAL_RCC_USB_OTG_HS_RELEASE_RESET() (RCC->AHB1RSTR &= ~(RCC_AHB1RSTR_OTGHRST)) #define __HAL_RCC_CRC_RELEASE_RESET() (RCC->AHB1RSTR &= ~(RCC_AHB1RSTR_CRCRST)) /** * @} */ /** @defgroup RCCEx_AHB2_Force_Release_Reset AHB2 Force Release Reset * @brief Force or release AHB2 peripheral reset. * @{ */ #define __HAL_RCC_AHB2_FORCE_RESET() (RCC->AHB2RSTR = 0xFFFFFFFF) #define __HAL_RCC_USB_OTG_FS_FORCE_RESET() (RCC->AHB2RSTR |= (RCC_AHB2RSTR_OTGFSRST)) #define __HAL_RCC_RNG_FORCE_RESET() (RCC->AHB2RSTR |= (RCC_AHB2RSTR_RNGRST)) #define __HAL_RCC_DCMI_FORCE_RESET() (RCC->AHB2RSTR |= (RCC_AHB2RSTR_DCMIRST)) #define __HAL_RCC_AHB2_RELEASE_RESET() (RCC->AHB2RSTR = 0x00) #define __HAL_RCC_USB_OTG_FS_RELEASE_RESET() (RCC->AHB2RSTR &= ~(RCC_AHB2RSTR_OTGFSRST)) #define __HAL_RCC_RNG_RELEASE_RESET() (RCC->AHB2RSTR &= ~(RCC_AHB2RSTR_RNGRST)) #define __HAL_RCC_DCMI_RELEASE_RESET() (RCC->AHB2RSTR &= ~(RCC_AHB2RSTR_DCMIRST)) /** * @} */ /** @defgroup RCCEx_AHB3_Force_Release_Reset AHB3 Force Release Reset * @brief Force or release AHB3 peripheral reset. * @{ */ #define __HAL_RCC_AHB3_FORCE_RESET() (RCC->AHB3RSTR = 0xFFFFFFFF) #define __HAL_RCC_AHB3_RELEASE_RESET() (RCC->AHB3RSTR = 0x00) #define __HAL_RCC_FMC_FORCE_RESET() (RCC->AHB3RSTR |= (RCC_AHB3RSTR_FMCRST)) #define __HAL_RCC_QSPI_FORCE_RESET() (RCC->AHB3RSTR |= (RCC_AHB3RSTR_QSPIRST)) #define __HAL_RCC_FMC_RELEASE_RESET() (RCC->AHB3RSTR &= ~(RCC_AHB3RSTR_FMCRST)) #define __HAL_RCC_QSPI_RELEASE_RESET() (RCC->AHB3RSTR &= ~(RCC_AHB3RSTR_QSPIRST)) /** * @} */ /** @defgroup RCCEx_APB1_Force_Release_Reset APB1 Force Release Reset * @brief Force or release APB1 peripheral reset. */ #define __HAL_RCC_TIM6_FORCE_RESET() (RCC->APB1RSTR |= (RCC_APB1RSTR_TIM6RST)) #define __HAL_RCC_TIM7_FORCE_RESET() (RCC->APB1RSTR |= (RCC_APB1RSTR_TIM7RST)) #define __HAL_RCC_TIM12_FORCE_RESET() (RCC->APB1RSTR |= (RCC_APB1RSTR_TIM12RST)) #define __HAL_RCC_TIM13_FORCE_RESET() (RCC->APB1RSTR |= (RCC_APB1RSTR_TIM13RST)) #define __HAL_RCC_TIM14_FORCE_RESET() (RCC->APB1RSTR |= (RCC_APB1RSTR_TIM14RST)) #define __HAL_RCC_SPDIFRX_FORCE_RESET() (RCC->APB1RSTR |= (RCC_APB1RSTR_SPDIFRXRST)) #define __HAL_RCC_USART3_FORCE_RESET() (RCC->APB1RSTR |= (RCC_APB1RSTR_USART3RST)) #define __HAL_RCC_UART4_FORCE_RESET() (RCC->APB1RSTR |= (RCC_APB1RSTR_UART4RST)) #define __HAL_RCC_UART5_FORCE_RESET() (RCC->APB1RSTR |= (RCC_APB1RSTR_UART5RST)) #define __HAL_RCC_FMPI2C1_FORCE_RESET() (RCC->APB1RSTR |= (RCC_APB1RSTR_FMPI2C1RST)) #define __HAL_RCC_CAN1_FORCE_RESET() (RCC->APB1RSTR |= (RCC_APB1RSTR_CAN1RST)) #define __HAL_RCC_CAN2_FORCE_RESET() (RCC->APB1RSTR |= (RCC_APB1RSTR_CAN2RST)) #define __HAL_RCC_CEC_FORCE_RESET() (RCC->APB1RSTR |= (RCC_APB1RSTR_CECRST)) #define __HAL_RCC_DAC_FORCE_RESET() (RCC->APB1RSTR |= (RCC_APB1RSTR_DACRST)) #define __HAL_RCC_TIM2_FORCE_RESET() (RCC->APB1RSTR |= (RCC_APB1RSTR_TIM2RST)) #define __HAL_RCC_TIM3_FORCE_RESET() (RCC->APB1RSTR |= (RCC_APB1RSTR_TIM3RST)) #define __HAL_RCC_TIM4_FORCE_RESET() (RCC->APB1RSTR |= (RCC_APB1RSTR_TIM4RST)) #define __HAL_RCC_SPI3_FORCE_RESET() (RCC->APB1RSTR |= (RCC_APB1RSTR_SPI3RST)) #define __HAL_RCC_I2C3_FORCE_RESET() (RCC->APB1RSTR |= (RCC_APB1RSTR_I2C3RST)) #define __HAL_RCC_TIM2_RELEASE_RESET() (RCC->APB1RSTR &= ~(RCC_APB1RSTR_TIM2RST)) #define __HAL_RCC_TIM3_RELEASE_RESET() (RCC->APB1RSTR &= ~(RCC_APB1RSTR_TIM3RST)) #define __HAL_RCC_TIM4_RELEASE_RESET() (RCC->APB1RSTR &= ~(RCC_APB1RSTR_TIM4RST)) #define __HAL_RCC_SPI3_RELEASE_RESET() (RCC->APB1RSTR &= ~(RCC_APB1RSTR_SPI3RST)) #define __HAL_RCC_I2C3_RELEASE_RESET() (RCC->APB1RSTR &= ~(RCC_APB1RSTR_I2C3RST)) #define __HAL_RCC_TIM6_RELEASE_RESET() (RCC->APB1RSTR &= ~(RCC_APB1RSTR_TIM6RST)) #define __HAL_RCC_TIM7_RELEASE_RESET() (RCC->APB1RSTR &= ~(RCC_APB1RSTR_TIM7RST)) #define __HAL_RCC_TIM12_RELEASE_RESET() (RCC->APB1RSTR &= ~(RCC_APB1RSTR_TIM12RST)) #define __HAL_RCC_TIM13_RELEASE_RESET() (RCC->APB1RSTR &= ~(RCC_APB1RSTR_TIM13RST)) #define __HAL_RCC_TIM14_RELEASE_RESET() (RCC->APB1RSTR &= ~(RCC_APB1RSTR_TIM14RST)) #define __HAL_RCC_SPDIFRX_RELEASE_RESET() (RCC->APB1RSTR &= ~(RCC_APB1RSTR_SPDIFRXRST)) #define __HAL_RCC_USART3_RELEASE_RESET() (RCC->APB1RSTR &= ~(RCC_APB1RSTR_USART3RST)) #define __HAL_RCC_UART4_RELEASE_RESET() (RCC->APB1RSTR &= ~(RCC_APB1RSTR_UART4RST)) #define __HAL_RCC_UART5_RELEASE_RESET() (RCC->APB1RSTR &= ~(RCC_APB1RSTR_UART5RST)) #define __HAL_RCC_FMPI2C1_RELEASE_RESET() (RCC->APB1RSTR &= ~(RCC_APB1RSTR_FMPI2C1RST)) #define __HAL_RCC_CAN1_RELEASE_RESET() (RCC->APB1RSTR &= ~(RCC_APB1RSTR_CAN1RST)) #define __HAL_RCC_CAN2_RELEASE_RESET() (RCC->APB1RSTR &= ~(RCC_APB1RSTR_CAN2RST)) #define __HAL_RCC_CEC_RELEASE_RESET() (RCC->APB1RSTR &= ~(RCC_APB1RSTR_CECRST)) #define __HAL_RCC_DAC_RELEASE_RESET() (RCC->APB1RSTR &= ~(RCC_APB1RSTR_DACRST)) /** * @} */ /** @defgroup RCCEx_APB2_Force_Release_Reset APB2 Force Release Reset * @brief Force or release APB2 peripheral reset. */ #define __HAL_RCC_TIM8_FORCE_RESET() (RCC->APB2RSTR |= (RCC_APB2RSTR_TIM8RST)) #define __HAL_RCC_SAI1_FORCE_RESET() (RCC->APB2RSTR |= (RCC_APB2RSTR_SAI1RST)) #define __HAL_RCC_SAI2_FORCE_RESET() (RCC->APB2RSTR |= (RCC_APB2RSTR_SAI2RST)) #define __HAL_RCC_SDIO_FORCE_RESET() (RCC->APB2RSTR |= (RCC_APB2RSTR_SDIORST)) #define __HAL_RCC_SPI4_FORCE_RESET() (RCC->APB2RSTR |= (RCC_APB2RSTR_SPI4RST)) #define __HAL_RCC_TIM10_FORCE_RESET() (RCC->APB2RSTR |= (RCC_APB2RSTR_TIM10RST)) #define __HAL_RCC_SDIO_RELEASE_RESET() (RCC->APB2RSTR &= ~(RCC_APB2RSTR_SDIORST)) #define __HAL_RCC_SPI4_RELEASE_RESET() (RCC->APB2RSTR &= ~(RCC_APB2RSTR_SPI4RST)) #define __HAL_RCC_TIM10_RELEASE_RESET() (RCC->APB2RSTR &= ~(RCC_APB2RSTR_TIM10RST)) #define __HAL_RCC_TIM8_RELEASE_RESET() (RCC->APB2RSTR &= ~(RCC_APB2RSTR_TIM8RST)) #define __HAL_RCC_SAI1_RELEASE_RESET() (RCC->APB2RSTR &= ~(RCC_APB2RSTR_SAI1RST)) #define __HAL_RCC_SAI2_RELEASE_RESET() (RCC->APB2RSTR &= ~(RCC_APB2RSTR_SAI2RST)) /** * @} */ /** @defgroup RCCEx_AHB1_LowPower_Enable_Disable AHB1 Peripheral Low Power Enable Disable * @brief Enable or disable the AHB1 peripheral clock during Low Power (Sleep) mode. * @note Peripheral clock gating in SLEEP mode can be used to further reduce * power consumption. * @note After wakeup from SLEEP mode, the peripheral clock is enabled again. * @note By default, all peripheral clocks are enabled during SLEEP mode. */ #define __HAL_RCC_GPIOD_CLK_SLEEP_ENABLE() (RCC->AHB1LPENR |= (RCC_AHB1LPENR_GPIODLPEN)) #define __HAL_RCC_GPIOE_CLK_SLEEP_ENABLE() (RCC->AHB1LPENR |= (RCC_AHB1LPENR_GPIOELPEN)) #define __HAL_RCC_GPIOF_CLK_SLEEP_ENABLE() (RCC->AHB1LPENR |= (RCC_AHB1LPENR_GPIOFLPEN)) #define __HAL_RCC_GPIOG_CLK_SLEEP_ENABLE() (RCC->AHB1LPENR |= (RCC_AHB1LPENR_GPIOGLPEN)) #define __HAL_RCC_SRAM2_CLK_SLEEP_ENABLE() (RCC->AHB1LPENR |= (RCC_AHB1LPENR_SRAM2LPEN)) #define __HAL_RCC_USB_OTG_HS_CLK_SLEEP_ENABLE() (RCC->AHB1LPENR |= (RCC_AHB1LPENR_OTGHSLPEN)) #define __HAL_RCC_USB_OTG_HS_ULPI_CLK_SLEEP_ENABLE() (RCC->AHB1LPENR |= (RCC_AHB1LPENR_OTGHSULPILPEN)) #define __HAL_RCC_CRC_CLK_SLEEP_ENABLE() (RCC->AHB1LPENR |= (RCC_AHB1LPENR_CRCLPEN)) #define __HAL_RCC_FLITF_CLK_SLEEP_ENABLE() (RCC->AHB1LPENR |= (RCC_AHB1LPENR_FLITFLPEN)) #define __HAL_RCC_SRAM1_CLK_SLEEP_ENABLE() (RCC->AHB1LPENR |= (RCC_AHB1LPENR_SRAM1LPEN)) #define __HAL_RCC_BKPSRAM_CLK_SLEEP_ENABLE() (RCC->AHB1LPENR |= (RCC_AHB1LPENR_BKPSRAMLPEN)) #define __HAL_RCC_GPIOD_CLK_SLEEP_DISABLE() (RCC->AHB1LPENR &= ~(RCC_AHB1LPENR_GPIODLPEN)) #define __HAL_RCC_GPIOE_CLK_SLEEP_DISABLE() (RCC->AHB1LPENR &= ~(RCC_AHB1LPENR_GPIOELPEN)) #define __HAL_RCC_GPIOF_CLK_SLEEP_DISABLE() (RCC->AHB1LPENR &= ~(RCC_AHB1LPENR_GPIOFLPEN)) #define __HAL_RCC_GPIOG_CLK_SLEEP_DISABLE() (RCC->AHB1LPENR &= ~(RCC_AHB1LPENR_GPIOGLPEN)) #define __HAL_RCC_SRAM2_CLK_SLEEP_DISABLE() (RCC->AHB1LPENR &= ~(RCC_AHB1LPENR_SRAM2LPEN)) #define __HAL_RCC_USB_OTG_HS_CLK_SLEEP_DISABLE() (RCC->AHB1LPENR &= ~(RCC_AHB1LPENR_OTGHSLPEN)) #define __HAL_RCC_USB_OTG_HS_ULPI_CLK_SLEEP_DISABLE() (RCC->AHB1LPENR &= ~(RCC_AHB1LPENR_OTGHSULPILPEN)) #define __HAL_RCC_CRC_CLK_SLEEP_DISABLE() (RCC->AHB1LPENR &= ~(RCC_AHB1LPENR_CRCLPEN)) #define __HAL_RCC_FLITF_CLK_SLEEP_DISABLE() (RCC->AHB1LPENR &= ~(RCC_AHB1LPENR_FLITFLPEN)) #define __HAL_RCC_SRAM1_CLK_SLEEP_DISABLE() (RCC->AHB1LPENR &= ~(RCC_AHB1LPENR_SRAM1LPEN)) #define __HAL_RCC_BKPSRAM_CLK_SLEEP_DISABLE() (RCC->AHB1LPENR &= ~(RCC_AHB1LPENR_BKPSRAMLPEN)) /** * @} */ /** @defgroup RCCEx_AHB2_LowPower_Enable_Disable AHB2 Peripheral Low Power Enable Disable * @brief Enable or disable the AHB2 peripheral clock during Low Power (Sleep) mode. * @note Peripheral clock gating in SLEEP mode can be used to further reduce * power consumption. * @note After wake-up from SLEEP mode, the peripheral clock is enabled again. * @note By default, all peripheral clocks are enabled during SLEEP mode. * @{ */ #define __HAL_RCC_USB_OTG_FS_CLK_SLEEP_ENABLE() (RCC->AHB2LPENR |= (RCC_AHB2LPENR_OTGFSLPEN)) #define __HAL_RCC_USB_OTG_FS_CLK_SLEEP_DISABLE() (RCC->AHB2LPENR &= ~(RCC_AHB2LPENR_OTGFSLPEN)) #define __HAL_RCC_RNG_CLK_SLEEP_ENABLE() (RCC->AHB2LPENR |= (RCC_AHB2LPENR_RNGLPEN)) #define __HAL_RCC_RNG_CLK_SLEEP_DISABLE() (RCC->AHB2LPENR &= ~(RCC_AHB2LPENR_RNGLPEN)) #define __HAL_RCC_DCMI_CLK_SLEEP_ENABLE() (RCC->AHB2LPENR |= (RCC_AHB2LPENR_DCMILPEN)) #define __HAL_RCC_DCMI_CLK_SLEEP_DISABLE() (RCC->AHB2LPENR &= ~(RCC_AHB2LPENR_DCMILPEN)) /** * @} */ /** @defgroup RCCEx_AHB3_LowPower_Enable_Disable AHB3 Peripheral Low Power Enable Disable * @brief Enable or disable the AHB3 peripheral clock during Low Power (Sleep) mode. * @note Peripheral clock gating in SLEEP mode can be used to further reduce * power consumption. * @note After wakeup from SLEEP mode, the peripheral clock is enabled again. * @note By default, all peripheral clocks are enabled during SLEEP mode. */ #define __HAL_RCC_FMC_CLK_SLEEP_ENABLE() (RCC->AHB3LPENR |= (RCC_AHB3LPENR_FMCLPEN)) #define __HAL_RCC_QSPI_CLK_SLEEP_ENABLE() (RCC->AHB3LPENR |= (RCC_AHB3LPENR_QSPILPEN)) #define __HAL_RCC_FMC_CLK_SLEEP_DISABLE() (RCC->AHB3LPENR &= ~(RCC_AHB3LPENR_FMCLPEN)) #define __HAL_RCC_QSPI_CLK_SLEEP_DISABLE() (RCC->AHB3LPENR &= ~(RCC_AHB3LPENR_QSPILPEN)) /** * @} */ /** @defgroup RCCEx_APB1_LowPower_Enable_Disable APB1 Peripheral Low Power Enable Disable * @brief Enable or disable the APB1 peripheral clock during Low Power (Sleep) mode. * @note Peripheral clock gating in SLEEP mode can be used to further reduce * power consumption. * @note After wakeup from SLEEP mode, the peripheral clock is enabled again. * @note By default, all peripheral clocks are enabled during SLEEP mode. */ #define __HAL_RCC_TIM6_CLK_SLEEP_ENABLE() (RCC->APB1LPENR |= (RCC_APB1LPENR_TIM6LPEN)) #define __HAL_RCC_TIM7_CLK_SLEEP_ENABLE() (RCC->APB1LPENR |= (RCC_APB1LPENR_TIM7LPEN)) #define __HAL_RCC_TIM12_CLK_SLEEP_ENABLE() (RCC->APB1LPENR |= (RCC_APB1LPENR_TIM12LPEN)) #define __HAL_RCC_TIM13_CLK_SLEEP_ENABLE() (RCC->APB1LPENR |= (RCC_APB1LPENR_TIM13LPEN)) #define __HAL_RCC_TIM14_CLK_SLEEP_ENABLE() (RCC->APB1LPENR |= (RCC_APB1LPENR_TIM14LPEN)) #define __HAL_RCC_SPDIFRX_CLK_SLEEP_ENABLE() (RCC->APB1LPENR |= (RCC_APB1LPENR_SPDIFRXLPEN)) #define __HAL_RCC_USART3_CLK_SLEEP_ENABLE() (RCC->APB1LPENR |= (RCC_APB1LPENR_USART3LPEN)) #define __HAL_RCC_UART4_CLK_SLEEP_ENABLE() (RCC->APB1LPENR |= (RCC_APB1LPENR_UART4LPEN)) #define __HAL_RCC_UART5_CLK_SLEEP_ENABLE() (RCC->APB1LPENR |= (RCC_APB1LPENR_UART5LPEN)) #define __HAL_RCC_FMPI2C1_CLK_SLEEP_ENABLE() (RCC->APB1LPENR |= (RCC_APB1LPENR_FMPI2C1LPEN)) #define __HAL_RCC_CAN1_CLK_SLEEP_ENABLE() (RCC->APB1LPENR |= (RCC_APB1LPENR_CAN1LPEN)) #define __HAL_RCC_CAN2_CLK_SLEEP_ENABLE() (RCC->APB1LPENR |= (RCC_APB1LPENR_CAN2LPEN)) #define __HAL_RCC_CEC_CLK_SLEEP_ENABLE() (RCC->APB1LPENR |= (RCC_APB1LPENR_CECLPEN)) #define __HAL_RCC_DAC_CLK_SLEEP_ENABLE() (RCC->APB1LPENR |= (RCC_APB1LPENR_DACLPEN)) #define __HAL_RCC_TIM2_CLK_SLEEP_ENABLE() (RCC->APB1LPENR |= (RCC_APB1LPENR_TIM2LPEN)) #define __HAL_RCC_TIM3_CLK_SLEEP_ENABLE() (RCC->APB1LPENR |= (RCC_APB1LPENR_TIM3LPEN)) #define __HAL_RCC_TIM4_CLK_SLEEP_ENABLE() (RCC->APB1LPENR |= (RCC_APB1LPENR_TIM4LPEN)) #define __HAL_RCC_SPI3_CLK_SLEEP_ENABLE() (RCC->APB1LPENR |= (RCC_APB1LPENR_SPI3LPEN)) #define __HAL_RCC_I2C3_CLK_SLEEP_ENABLE() (RCC->APB1LPENR |= (RCC_APB1LPENR_I2C3LPEN)) #define __HAL_RCC_TIM2_CLK_SLEEP_DISABLE() (RCC->APB1LPENR &= ~(RCC_APB1LPENR_TIM2LPEN)) #define __HAL_RCC_TIM3_CLK_SLEEP_DISABLE() (RCC->APB1LPENR &= ~(RCC_APB1LPENR_TIM3LPEN)) #define __HAL_RCC_TIM4_CLK_SLEEP_DISABLE() (RCC->APB1LPENR &= ~(RCC_APB1LPENR_TIM4LPEN)) #define __HAL_RCC_SPI3_CLK_SLEEP_DISABLE() (RCC->APB1LPENR &= ~(RCC_APB1LPENR_SPI3LPEN)) #define __HAL_RCC_I2C3_CLK_SLEEP_DISABLE() (RCC->APB1LPENR &= ~(RCC_APB1LPENR_I2C3LPEN)) #define __HAL_RCC_TIM6_CLK_SLEEP_DISABLE() (RCC->APB1LPENR &= ~(RCC_APB1LPENR_TIM6LPEN)) #define __HAL_RCC_TIM7_CLK_SLEEP_DISABLE() (RCC->APB1LPENR &= ~(RCC_APB1LPENR_TIM7LPEN)) #define __HAL_RCC_TIM12_CLK_SLEEP_DISABLE() (RCC->APB1LPENR &= ~(RCC_APB1LPENR_TIM12LPEN)) #define __HAL_RCC_TIM13_CLK_SLEEP_DISABLE() (RCC->APB1LPENR &= ~(RCC_APB1LPENR_TIM13LPEN)) #define __HAL_RCC_TIM14_CLK_SLEEP_DISABLE() (RCC->APB1LPENR &= ~(RCC_APB1LPENR_TIM14LPEN)) #define __HAL_RCC_SPDIFRX_CLK_SLEEP_DISABLE()(RCC->APB1LPENR &= ~(RCC_APB1LPENR_SPDIFRXLPEN)) #define __HAL_RCC_USART3_CLK_SLEEP_DISABLE() (RCC->APB1LPENR &= ~(RCC_APB1LPENR_USART3LPEN)) #define __HAL_RCC_UART4_CLK_SLEEP_DISABLE() (RCC->APB1LPENR &= ~(RCC_APB1LPENR_UART4LPEN)) #define __HAL_RCC_UART5_CLK_SLEEP_DISABLE() (RCC->APB1LPENR &= ~(RCC_APB1LPENR_UART5LPEN)) #define __HAL_RCC_FMPI2C1_CLK_SLEEP_DISABLE()(RCC->APB1LPENR &= ~(RCC_APB1LPENR_FMPI2C1LPEN)) #define __HAL_RCC_CAN1_CLK_SLEEP_DISABLE() (RCC->APB1LPENR &= ~(RCC_APB1LPENR_CAN1LPEN)) #define __HAL_RCC_CAN2_CLK_SLEEP_DISABLE() (RCC->APB1LPENR &= ~(RCC_APB1LPENR_CAN2LPEN)) #define __HAL_RCC_CEC_CLK_SLEEP_DISABLE() (RCC->APB1LPENR &= ~(RCC_APB1LPENR_CECLPEN)) #define __HAL_RCC_DAC_CLK_SLEEP_DISABLE() (RCC->APB1LPENR &= ~(RCC_APB1LPENR_DACLPEN)) /** * @} */ /** @defgroup RCCEx_APB2_LowPower_Enable_Disable APB2 Peripheral Low Power Enable Disable * @brief Enable or disable the APB2 peripheral clock during Low Power (Sleep) mode. * @note Peripheral clock gating in SLEEP mode can be used to further reduce * power consumption. * @note After wakeup from SLEEP mode, the peripheral clock is enabled again. * @note By default, all peripheral clocks are enabled during SLEEP mode. */ #define __HAL_RCC_TIM8_CLK_SLEEP_ENABLE() (RCC->APB2LPENR |= (RCC_APB2LPENR_TIM8LPEN)) #define __HAL_RCC_ADC2_CLK_SLEEP_ENABLE() (RCC->APB2LPENR |= (RCC_APB2LPENR_ADC2LPEN)) #define __HAL_RCC_ADC3_CLK_SLEEP_ENABLE() (RCC->APB2LPENR |= (RCC_APB2LPENR_ADC3LPEN)) #define __HAL_RCC_SAI1_CLK_SLEEP_ENABLE() (RCC->APB2LPENR |= (RCC_APB2LPENR_SAI1LPEN)) #define __HAL_RCC_SAI2_CLK_SLEEP_ENABLE() (RCC->APB2LPENR |= (RCC_APB2LPENR_SAI2LPEN)) #define __HAL_RCC_SDIO_CLK_SLEEP_ENABLE() (RCC->APB2LPENR |= (RCC_APB2LPENR_SDIOLPEN)) #define __HAL_RCC_SPI4_CLK_SLEEP_ENABLE() (RCC->APB2LPENR |= (RCC_APB2LPENR_SPI4LPEN)) #define __HAL_RCC_TIM10_CLK_SLEEP_ENABLE()(RCC->APB2LPENR |= (RCC_APB2LPENR_TIM10LPEN)) #define __HAL_RCC_SDIO_CLK_SLEEP_DISABLE() (RCC->APB2LPENR &= ~(RCC_APB2LPENR_SDIOLPEN)) #define __HAL_RCC_SPI4_CLK_SLEEP_DISABLE() (RCC->APB2LPENR &= ~(RCC_APB2LPENR_SPI4LPEN)) #define __HAL_RCC_TIM10_CLK_SLEEP_DISABLE()(RCC->APB2LPENR &= ~(RCC_APB2LPENR_TIM10LPEN)) #define __HAL_RCC_TIM8_CLK_SLEEP_DISABLE() (RCC->APB2LPENR &= ~(RCC_APB2LPENR_TIM8LPEN)) #define __HAL_RCC_ADC2_CLK_SLEEP_DISABLE() (RCC->APB2LPENR &= ~(RCC_APB2LPENR_ADC2LPEN)) #define __HAL_RCC_ADC3_CLK_SLEEP_DISABLE() (RCC->APB2LPENR &= ~(RCC_APB2LPENR_ADC3LPEN)) #define __HAL_RCC_SAI1_CLK_SLEEP_DISABLE() (RCC->APB2LPENR &= ~(RCC_APB2LPENR_SAI1LPEN)) #define __HAL_RCC_SAI2_CLK_SLEEP_DISABLE() (RCC->APB2LPENR &= ~(RCC_APB2LPENR_SAI2LPEN)) /** * @} */ #endif /* STM32F446xx */ /*----------------------------------------------------------------------------*/ /*------------------------------- PLL Configuration --------------------------*/ #if defined(STM32F410Tx) || defined(STM32F410Cx) || defined(STM32F410Rx) || defined(STM32F446xx) ||\ defined(STM32F469xx) || defined(STM32F479xx) /** @brief Macro to configure the main PLL clock source, multiplication and division factors. * @note This function must be used only when the main PLL is disabled. * @param __RCC_PLLSource__: specifies the PLL entry clock source. * This parameter can be one of the following values: * @arg RCC_PLLSOURCE_HSI: HSI oscillator clock selected as PLL clock entry * @arg RCC_PLLSOURCE_HSE: HSE oscillator clock selected as PLL clock entry * @note This clock source (RCC_PLLSource) is common for the main PLL and PLLI2S. * @param __PLLM__: specifies the division factor for PLL VCO input clock * This parameter must be a number between Min_Data = 2 and Max_Data = 63. * @note You have to set the PLLM parameter correctly to ensure that the VCO input * frequency ranges from 1 to 2 MHz. It is recommended to select a frequency * of 2 MHz to limit PLL jitter. * @param __PLLN__: specifies the multiplication factor for PLL VCO output clock * This parameter must be a number between Min_Data = 192 and Max_Data = 432. * @note You have to set the PLLN parameter correctly to ensure that the VCO * output frequency is between 192 and 432 MHz. * * @param __PLLP__: specifies the division factor for main system clock (SYSCLK) * This parameter must be a number in the range {2, 4, 6, or 8}. * * @param __PLLQ__: specifies the division factor for OTG FS, SDIO and RNG clocks * This parameter must be a number between Min_Data = 2 and Max_Data = 15. * @note If the USB OTG FS is used in your application, you have to set the * PLLQ parameter correctly to have 48 MHz clock for the USB. However, * the SDIO and RNG need a frequency lower than or equal to 48 MHz to work * correctly. * * @param __PLLR__: PLL division factor for I2S, SAI, SYSTEM, SPDIFRX clocks. * This parameter must be a number between Min_Data = 2 and Max_Data = 7. * @note This parameter is only available in STM32F446xx/STM32F469xx/STM32F479xx devices. * */ #define __HAL_RCC_PLL_CONFIG(__RCC_PLLSource__, __PLLM__, __PLLN__, __PLLP__, __PLLQ__,__PLLR__) \ (RCC->PLLCFGR = ((__RCC_PLLSource__) | (__PLLM__) | \ ((__PLLN__) << POSITION_VAL(RCC_PLLCFGR_PLLN)) | \ ((((__PLLP__) >> 1) -1) << POSITION_VAL(RCC_PLLCFGR_PLLP)) | \ ((__PLLQ__) << POSITION_VAL(RCC_PLLCFGR_PLLQ)) | \ ((__PLLR__) << POSITION_VAL(RCC_PLLCFGR_PLLR)))) #else /** @brief Macro to configure the main PLL clock source, multiplication and division factors. * @note This function must be used only when the main PLL is disabled. * @param __RCC_PLLSource__: specifies the PLL entry clock source. * This parameter can be one of the following values: * @arg RCC_PLLSOURCE_HSI: HSI oscillator clock selected as PLL clock entry * @arg RCC_PLLSOURCE_HSE: HSE oscillator clock selected as PLL clock entry * @note This clock source (RCC_PLLSource) is common for the main PLL and PLLI2S. * @param __PLLM__: specifies the division factor for PLL VCO input clock * This parameter must be a number between Min_Data = 2 and Max_Data = 63. * @note You have to set the PLLM parameter correctly to ensure that the VCO input * frequency ranges from 1 to 2 MHz. It is recommended to select a frequency * of 2 MHz to limit PLL jitter. * @param __PLLN__: specifies the multiplication factor for PLL VCO output clock * This parameter must be a number between Min_Data = 192 and Max_Data = 432. * @note You have to set the PLLN parameter correctly to ensure that the VCO * output frequency is between 192 and 432 MHz. * * @param __PLLP__: specifies the division factor for main system clock (SYSCLK) * This parameter must be a number in the range {2, 4, 6, or 8}. * * @param __PLLQ__: specifies the division factor for OTG FS, SDIO and RNG clocks * This parameter must be a number between Min_Data = 2 and Max_Data = 15. * @note If the USB OTG FS is used in your application, you have to set the * PLLQ parameter correctly to have 48 MHz clock for the USB. However, * the SDIO and RNG need a frequency lower than or equal to 48 MHz to work * correctly. * */ #define __HAL_RCC_PLL_CONFIG(__RCC_PLLSource__, __PLLM__, __PLLN__, __PLLP__, __PLLQ__) \ (RCC->PLLCFGR = (0x20000000 | (__RCC_PLLSource__) | (__PLLM__)| \ ((__PLLN__) << POSITION_VAL(RCC_PLLCFGR_PLLN)) | \ ((((__PLLP__) >> 1) -1) << POSITION_VAL(RCC_PLLCFGR_PLLP)) | \ ((__PLLQ__) << POSITION_VAL(RCC_PLLCFGR_PLLQ)))) #endif /* STM32F410xx || STM32F446xx || STM32F469xx || STM32F479xx */ /*----------------------------------------------------------------------------*/ /*----------------------------PLLI2S Configuration ---------------------------*/ #if defined(STM32F405xx) || defined(STM32F415xx) || defined(STM32F407xx) || defined(STM32F417xx) || \ defined(STM32F427xx) || defined(STM32F437xx) || defined(STM32F429xx) || defined(STM32F439xx) || \ defined(STM32F401xC) || defined(STM32F401xE) || defined(STM32F411xE) || defined(STM32F446xx) || \ defined(STM32F469xx) || defined(STM32F479xx) /** @brief Macros to enable or disable the PLLI2S. * @note The PLLI2S is disabled by hardware when entering STOP and STANDBY modes. */ #define __HAL_RCC_PLLI2S_ENABLE() (*(__IO uint32_t *) RCC_CR_PLLI2SON_BB = ENABLE) #define __HAL_RCC_PLLI2S_DISABLE() (*(__IO uint32_t *) RCC_CR_PLLI2SON_BB = DISABLE) #endif /* STM32F405xx || STM32F415xx || STM32F407xx || STM32F417xx || STM32F427xx || STM32F437xx || STM32F429xx || STM32F439xx || STM32F401xC || STM32F401xE || STM32F411xE || STM32F446xx || STM32F469xx || STM32F479xx */ #if defined(STM32F446xx) /** @brief Macro to configure the PLLI2S clock multiplication and division factors . * @note This macro must be used only when the PLLI2S is disabled. * @note PLLI2S clock source is common with the main PLL (configured in * HAL_RCC_ClockConfig() API). * @param __PLLI2SM__: specifies the division factor for PLLI2S VCO input clock * This parameter must be a number between Min_Data = 2 and Max_Data = 63. * @note You have to set the PLLI2SM parameter correctly to ensure that the VCO input * frequency ranges from 1 to 2 MHz. It is recommended to select a frequency * of 1 MHz to limit PLLI2S jitter. * * @param __PLLI2SN__: specifies the multiplication factor for PLLI2S VCO output clock * This parameter must be a number between Min_Data = 192 and Max_Data = 432. * @note You have to set the PLLI2SN parameter correctly to ensure that the VCO * output frequency is between Min_Data = 192 and Max_Data = 432 MHz. * * @param __PLLI2SP__: specifies division factor for SPDIFRX Clock. * This parameter must be a number in the range {2, 4, 6, or 8}. * @note the PLLI2SP parameter is only available with STM32F446xx Devices * * @param __PLLI2SR__: specifies the division factor for I2S clock * This parameter must be a number between Min_Data = 2 and Max_Data = 7. * @note You have to set the PLLI2SR parameter correctly to not exceed 192 MHz * on the I2S clock frequency. * * @param __PLLI2SQ__: specifies the division factor for SAI clock * This parameter must be a number between Min_Data = 2 and Max_Data = 15. */ #define __HAL_RCC_PLLI2S_CONFIG(__PLLI2SM__, __PLLI2SN__, __PLLI2SP__, __PLLI2SQ__, __PLLI2SR__) \ (RCC->PLLI2SCFGR = ((__PLLI2SM__) |\ ((__PLLI2SN__) << POSITION_VAL(RCC_PLLI2SCFGR_PLLI2SN)) |\ ((((__PLLI2SP__) >> 1) -1) << POSITION_VAL(RCC_PLLI2SCFGR_PLLI2SP)) |\ ((__PLLI2SQ__) << POSITION_VAL(RCC_PLLI2SCFGR_PLLI2SQ)) |\ ((__PLLI2SR__) << POSITION_VAL(RCC_PLLI2SCFGR_PLLI2SR)))) #else /** @brief Macro to configure the PLLI2S clock multiplication and division factors . * @note This macro must be used only when the PLLI2S is disabled. * @note PLLI2S clock source is common with the main PLL (configured in * HAL_RCC_ClockConfig() API). * @param __PLLI2SN__: specifies the multiplication factor for PLLI2S VCO output clock * This parameter must be a number between Min_Data = 192 and Max_Data = 432. * @note You have to set the PLLI2SN parameter correctly to ensure that the VCO * output frequency is between Min_Data = 192 and Max_Data = 432 MHz. * * @param __PLLI2SR__: specifies the division factor for I2S clock * This parameter must be a number between Min_Data = 2 and Max_Data = 7. * @note You have to set the PLLI2SR parameter correctly to not exceed 192 MHz * on the I2S clock frequency. * */ #define __HAL_RCC_PLLI2S_CONFIG(__PLLI2SN__, __PLLI2SR__) \ (RCC->PLLI2SCFGR = (((__PLLI2SN__) << POSITION_VAL(RCC_PLLI2SCFGR_PLLI2SN)) |\ ((__PLLI2SR__) << POSITION_VAL(RCC_PLLI2SCFGR_PLLI2SR)))) #endif /* STM32F446xx */ #if defined(STM32F411xE) /** @brief Macro to configure the PLLI2S clock multiplication and division factors . * @note This macro must be used only when the PLLI2S is disabled. * @note This macro must be used only when the PLLI2S is disabled. * @note PLLI2S clock source is common with the main PLL (configured in * HAL_RCC_ClockConfig() API). * @param __PLLI2SM__: specifies the division factor for PLLI2S VCO input clock * This parameter must be a number between Min_Data = 2 and Max_Data = 63. * @note The PLLI2SM parameter is only used with STM32F411xE/STM32F410xx Devices * @note You have to set the PLLI2SM parameter correctly to ensure that the VCO input * frequency ranges from 1 to 2 MHz. It is recommended to select a frequency * of 2 MHz to limit PLLI2S jitter. * @param __PLLI2SN__: specifies the multiplication factor for PLLI2S VCO output clock * This parameter must be a number between Min_Data = 192 and Max_Data = 432. * @note You have to set the PLLI2SN parameter correctly to ensure that the VCO * output frequency is between Min_Data = 192 and Max_Data = 432 MHz. * @param __PLLI2SR__: specifies the division factor for I2S clock * This parameter must be a number between Min_Data = 2 and Max_Data = 7. * @note You have to set the PLLI2SR parameter correctly to not exceed 192 MHz * on the I2S clock frequency. */ #define __HAL_RCC_PLLI2S_I2SCLK_CONFIG(__PLLI2SM__, __PLLI2SN__, __PLLI2SR__) (RCC->PLLI2SCFGR = ((__PLLI2SM__) |\ ((__PLLI2SN__) << POSITION_VAL(RCC_PLLI2SCFGR_PLLI2SN)) |\ ((__PLLI2SR__) << POSITION_VAL(RCC_PLLI2SCFGR_PLLI2SR)))) #endif /* STM32F411xE */ #if defined(STM32F427xx) || defined(STM32F437xx) || defined(STM32F429xx) || defined(STM32F439xx) || defined(STM32F469xx) || defined(STM32F479xx) /** @brief Macro used by the SAI HAL driver to configure the PLLI2S clock multiplication and division factors. * @note This macro must be used only when the PLLI2S is disabled. * @note PLLI2S clock source is common with the main PLL (configured in * HAL_RCC_ClockConfig() API) * @param __PLLI2SN__: specifies the multiplication factor for PLLI2S VCO output clock. * This parameter must be a number between Min_Data = 192 and Max_Data = 432. * @note You have to set the PLLI2SN parameter correctly to ensure that the VCO * output frequency is between Min_Data = 192 and Max_Data = 432 MHz. * @param __PLLI2SQ__: specifies the division factor for SAI1 clock. * This parameter must be a number between Min_Data = 2 and Max_Data = 15. * @note the PLLI2SQ parameter is only available with STM32F427xx/437xx/429xx/439xx/469xx/479xx * Devices and can be configured using the __HAL_RCC_PLLI2S_PLLSAICLK_CONFIG() macro * @param __PLLI2SR__: specifies the division factor for I2S clock * This parameter must be a number between Min_Data = 2 and Max_Data = 7. * @note You have to set the PLLI2SR parameter correctly to not exceed 192 MHz * on the I2S clock frequency. */ #define __HAL_RCC_PLLI2S_SAICLK_CONFIG(__PLLI2SN__, __PLLI2SQ__, __PLLI2SR__) (RCC->PLLI2SCFGR = ((__PLLI2SN__) << 6) |\ ((__PLLI2SQ__) << 24) |\ ((__PLLI2SR__) << 28)) #endif /* STM32F427xx || STM32F437xx || STM32F429xx || STM32F439xx || STM32F469xx || STM32F479xx */ /*----------------------------------------------------------------------------*/ /*------------------------------ PLLSAI Configuration ------------------------*/ #if defined(STM32F427xx) || defined(STM32F437xx) || defined(STM32F429xx) || defined(STM32F439xx) || defined(STM32F446xx) || defined(STM32F469xx) || defined(STM32F479xx) /** @brief Macros to Enable or Disable the PLLISAI. * @note The PLLSAI is only available with STM32F429x/439x Devices. * @note The PLLSAI is disabled by hardware when entering STOP and STANDBY modes. */ #define __HAL_RCC_PLLSAI_ENABLE() (*(__IO uint32_t *) RCC_CR_PLLSAION_BB = ENABLE) #define __HAL_RCC_PLLSAI_DISABLE() (*(__IO uint32_t *) RCC_CR_PLLSAION_BB = DISABLE) #if defined(STM32F446xx) /** @brief Macro to configure the PLLSAI clock multiplication and division factors. * * @param __PLLSAIM__: specifies the division factor for PLLSAI VCO input clock * This parameter must be a number between Min_Data = 2 and Max_Data = 63. * @note You have to set the PLLSAIM parameter correctly to ensure that the VCO input * frequency ranges from 1 to 2 MHz. It is recommended to select a frequency * of 1 MHz to limit PLLI2S jitter. * @note The PLLSAIM parameter is only used with STM32F446xx Devices * * @param __PLLSAIN__: specifies the multiplication factor for PLLSAI VCO output clock. * This parameter must be a number between Min_Data = 192 and Max_Data = 432. * @note You have to set the PLLSAIN parameter correctly to ensure that the VCO * output frequency is between Min_Data = 192 and Max_Data = 432 MHz. * * @param __PLLSAIP__: specifies division factor for OTG FS, SDIO and RNG clocks. * This parameter must be a number in the range {2, 4, 6, or 8}. * @note the PLLSAIP parameter is only available with STM32F446xx Devices * * @param __PLLSAIQ__: specifies the division factor for SAI clock * This parameter must be a number between Min_Data = 2 and Max_Data = 15. * * @param __PLLSAIR__: specifies the division factor for LTDC clock * This parameter must be a number between Min_Data = 2 and Max_Data = 7. * @note the PLLI2SR parameter is only available with STM32F427/437/429/439xx Devices */ #define __HAL_RCC_PLLSAI_CONFIG(__PLLSAIM__, __PLLSAIN__, __PLLSAIP__, __PLLSAIQ__, __PLLSAIR__) \ (RCC->PLLSAICFGR = ((__PLLSAIM__) | \ ((__PLLSAIN__) << POSITION_VAL(RCC_PLLSAICFGR_PLLSAIN)) | \ ((((__PLLSAIP__) >> 1) -1) << POSITION_VAL(RCC_PLLSAICFGR_PLLSAIP)) | \ ((__PLLSAIQ__) << POSITION_VAL(RCC_PLLSAICFGR_PLLSAIQ)))) #endif /* STM32F446xx */ #if defined(STM32F469xx) || defined(STM32F479xx) /** @brief Macro to configure the PLLSAI clock multiplication and division factors. * * @param __PLLSAIN__: specifies the multiplication factor for PLLSAI VCO output clock. * This parameter must be a number between Min_Data = 192 and Max_Data = 432. * @note You have to set the PLLSAIN parameter correctly to ensure that the VCO * output frequency is between Min_Data = 192 and Max_Data = 432 MHz. * * @param __PLLSAIP__: specifies division factor for SDIO and CLK48 clocks. * This parameter must be a number in the range {2, 4, 6, or 8}. * * @param __PLLSAIQ__: specifies the division factor for SAI clock * This parameter must be a number between Min_Data = 2 and Max_Data = 15. * * @param __PLLSAIR__: specifies the division factor for LTDC clock * This parameter must be a number between Min_Data = 2 and Max_Data = 7. */ #define __HAL_RCC_PLLSAI_CONFIG(__PLLSAIN__, __PLLSAIP__, __PLLSAIQ__, __PLLSAIR__) \ (RCC->PLLSAICFGR = (((__PLLSAIN__) << POSITION_VAL(RCC_PLLSAICFGR_PLLSAIN)) |\ ((((__PLLSAIP__) >> 1) -1) << POSITION_VAL(RCC_PLLSAICFGR_PLLSAIP)) |\ ((__PLLSAIQ__) << POSITION_VAL(RCC_PLLSAICFGR_PLLSAIQ)) |\ ((__PLLSAIR__) << POSITION_VAL(RCC_PLLSAICFGR_PLLSAIR)))) #endif /* STM32F469xx || STM32F479xx */ #if defined(STM32F427xx) || defined(STM32F437xx) || defined(STM32F429xx) || defined(STM32F439xx) /** @brief Macro to configure the PLLSAI clock multiplication and division factors. * * @param __PLLSAIN__: specifies the multiplication factor for PLLSAI VCO output clock. * This parameter must be a number between Min_Data = 192 and Max_Data = 432. * @note You have to set the PLLSAIN parameter correctly to ensure that the VCO * output frequency is between Min_Data = 192 and Max_Data = 432 MHz. * * @param __PLLSAIQ__: specifies the division factor for SAI clock * This parameter must be a number between Min_Data = 2 and Max_Data = 15. * * @param __PLLSAIR__: specifies the division factor for LTDC clock * This parameter must be a number between Min_Data = 2 and Max_Data = 7. * @note the PLLI2SR parameter is only available with STM32F427/437/429/439xx Devices */ #define __HAL_RCC_PLLSAI_CONFIG(__PLLSAIN__, __PLLSAIQ__, __PLLSAIR__) \ (RCC->PLLSAICFGR = (((__PLLSAIN__) << POSITION_VAL(RCC_PLLSAICFGR_PLLSAIN)) | \ ((__PLLSAIQ__) << POSITION_VAL(RCC_PLLSAICFGR_PLLSAIQ)) | \ ((__PLLSAIR__) << POSITION_VAL(RCC_PLLSAICFGR_PLLSAIR)))) #endif /* STM32F427xx || STM32F437xx || STM32F429xx || STM32F439xx */ #endif /* STM32F427xx || STM32F437xx || STM32F429xx || STM32F439xx || STM32F446xx || STM32F469xx || STM32F479xx */ /*----------------------------------------------------------------------------*/ /*------------------- PLLSAI/PLLI2S Dividers Configuration -------------------*/ #if defined(STM32F427xx) || defined(STM32F437xx) || defined(STM32F429xx) || defined(STM32F439xx) || defined(STM32F446xx) ||\ defined(STM32F469xx) || defined(STM32F479xx) /** @brief Macro to configure the SAI clock Divider coming from PLLI2S. * @note This function must be called before enabling the PLLI2S. * @param __PLLI2SDivQ__: specifies the PLLI2S division factor for SAI1 clock. * This parameter must be a number between 1 and 32. * SAI1 clock frequency = f(PLLI2SQ) / __PLLI2SDivQ__ */ #define __HAL_RCC_PLLI2S_PLLSAICLKDIVQ_CONFIG(__PLLI2SDivQ__) (MODIFY_REG(RCC->DCKCFGR, RCC_DCKCFGR_PLLI2SDIVQ, (__PLLI2SDivQ__)-1)) /** @brief Macro to configure the SAI clock Divider coming from PLLSAI. * @note This function must be called before enabling the PLLSAI. * @param __PLLSAIDivQ__: specifies the PLLSAI division factor for SAI1 clock . * This parameter must be a number between Min_Data = 1 and Max_Data = 32. * SAI1 clock frequency = f(PLLSAIQ) / __PLLSAIDivQ__ */ #define __HAL_RCC_PLLSAI_PLLSAICLKDIVQ_CONFIG(__PLLSAIDivQ__) (MODIFY_REG(RCC->DCKCFGR, RCC_DCKCFGR_PLLSAIDIVQ, ((__PLLSAIDivQ__)-1)<<8)) #endif /* STM32F427xx || STM32F437xx || STM32F429xx || STM32F439xx || STM32F446xx || STM32F469xx || STM32F479xx */ #if defined(STM32F427xx) || defined(STM32F437xx) || defined(STM32F429xx) || defined(STM32F439xx) || defined(STM32F469xx) || defined(STM32F479xx) /** @brief Macro to configure the LTDC clock Divider coming from PLLSAI. * * @note The LTDC peripheral is only available with STM32F427/437/429/439/469/479xx Devices. * @note This function must be called before enabling the PLLSAI. * @param __PLLSAIDivR__: specifies the PLLSAI division factor for LTDC clock . * This parameter must be a number between Min_Data = 2 and Max_Data = 16. * LTDC clock frequency = f(PLLSAIR) / __PLLSAIDivR__ */ #define __HAL_RCC_PLLSAI_PLLSAICLKDIVR_CONFIG(__PLLSAIDivR__) (MODIFY_REG(RCC->DCKCFGR, RCC_DCKCFGR_PLLSAIDIVR, (__PLLSAIDivR__))) #endif /* STM32F427xx || STM32F437xx || STM32F429xx || STM32F439xx || STM32F469xx || STM32F479xx */ /*----------------------------------------------------------------------------*/ /*------------------------- Peripheral Clock selection -----------------------*/ #if defined(STM32F405xx) || defined(STM32F415xx) || defined(STM32F407xx) || defined(STM32F417xx) ||\ defined(STM32F427xx) || defined(STM32F437xx) || defined(STM32F429xx) || defined(STM32F439xx) ||\ defined(STM32F401xC) || defined(STM32F401xE) || defined(STM32F411xE) || defined(STM32F469xx) ||\ defined(STM32F479xx) /** @brief Macro to configure the I2S clock source (I2SCLK). * @note This function must be called before enabling the I2S APB clock. * @param __SOURCE__: specifies the I2S clock source. * This parameter can be one of the following values: * @arg RCC_I2SCLKSOURCE_PLLI2S: PLLI2S clock used as I2S clock source. * @arg RCC_I2SCLKSOURCE_EXT: External clock mapped on the I2S_CKIN pin * used as I2S clock source. */ #define __HAL_RCC_I2S_CONFIG(__SOURCE__) (*(__IO uint32_t *) RCC_CFGR_I2SSRC_BB = (__SOURCE__)) #endif /* STM32F40xxx || STM32F41xxx || STM32F42xxx || STM32F43xxx || STM32F469xx || STM32F479xx */ #if defined(STM32F427xx) || defined(STM32F437xx) || defined(STM32F429xx) || defined(STM32F439xx) || defined(STM32F469xx) || defined(STM32F479xx) /** @brief Macro to configure SAI1BlockA clock source selection. * @note The SAI peripheral is only available with STM32F427/437/429/439/469/479xx Devices. * @note This function must be called before enabling PLLSAI, PLLI2S and * the SAI clock. * @param __SOURCE__: specifies the SAI Block A clock source. * This parameter can be one of the following values: * @arg RCC_SAIACLKSOURCE_PLLI2S: PLLI2S_Q clock divided by PLLI2SDIVQ used * as SAI1 Block A clock. * @arg RCC_SAIACLKSOURCE_PLLSAI: PLLISAI_Q clock divided by PLLSAIDIVQ used * as SAI1 Block A clock. * @arg RCC_SAIACLKSOURCE_Ext: External clock mapped on the I2S_CKIN pin * used as SAI1 Block A clock. */ #define __HAL_RCC_SAI_BLOCKACLKSOURCE_CONFIG(__SOURCE__) (MODIFY_REG(RCC->DCKCFGR, RCC_DCKCFGR_SAI1ASRC, (__SOURCE__))) /** @brief Macro to configure SAI1BlockB clock source selection. * @note The SAI peripheral is only available with STM32F427/437/429/439/469/479xx Devices. * @note This function must be called before enabling PLLSAI, PLLI2S and * the SAI clock. * @param __SOURCE__: specifies the SAI Block B clock source. * This parameter can be one of the following values: * @arg RCC_SAIBCLKSOURCE_PLLI2S: PLLI2S_Q clock divided by PLLI2SDIVQ used * as SAI1 Block B clock. * @arg RCC_SAIBCLKSOURCE_PLLSAI: PLLISAI_Q clock divided by PLLSAIDIVQ used * as SAI1 Block B clock. * @arg RCC_SAIBCLKSOURCE_Ext: External clock mapped on the I2S_CKIN pin * used as SAI1 Block B clock. */ #define __HAL_RCC_SAI_BLOCKBCLKSOURCE_CONFIG(__SOURCE__) (MODIFY_REG(RCC->DCKCFGR, RCC_DCKCFGR_SAI1BSRC, (__SOURCE__))) #endif /* STM32F427xx || STM32F437xx || STM32F429xx || STM32F439xx || STM32F469xx || STM32F479xx */ #if defined(STM32F446xx) /** @brief Macro to configure SAI1 clock source selection. * @note This configuration is only available with STM32F446xx Devices. * @note This function must be called before enabling PLL, PLLSAI, PLLI2S and * the SAI clock. * @param __SOURCE__: specifies the SAI1 clock source. * This parameter can be one of the following values: * @arg RCC_SAI1CLKSOURCE_PLLI2S: PLLI2S_Q clock divided by PLLI2SDIVQ used as SAI1 clock. * @arg RCC_SAI1CLKSOURCE_PLLSAI: PLLISAI_Q clock divided by PLLSAIDIVQ used as SAI1 clock. * @arg RCC_SAI1CLKSOURCE_PLLR: PLL VCO Output divided by PLLR used as SAI1 clock. * @arg RCC_SAI1CLKSOURCE_EXT: External clock mapped on the I2S_CKIN pin used as SAI1 clock. */ #define __HAL_RCC_SAI1_CONFIG(__SOURCE__) (MODIFY_REG(RCC->DCKCFGR, RCC_DCKCFGR_SAI1SRC, (__SOURCE__))) /** @brief Macro to Get SAI1 clock source selection. * @note This configuration is only available with STM32F446xx Devices. * @retval The clock source can be one of the following values: * @arg RCC_SAI1CLKSOURCE_PLLI2S: PLLI2S_Q clock divided by PLLI2SDIVQ used as SAI1 clock. * @arg RCC_SAI1CLKSOURCE_PLLSAI: PLLISAI_Q clock divided by PLLSAIDIVQ used as SAI1 clock. * @arg RCC_SAI1CLKSOURCE_PLLR: PLL VCO Output divided by PLLR used as SAI1 clock. * @arg RCC_SAI1CLKSOURCE_EXT: External clock mapped on the I2S_CKIN pin used as SAI1 clock. */ #define __HAL_RCC_GET_SAI1_SOURCE() (READ_BIT(RCC->DCKCFGR, RCC_DCKCFGR_SAI1SRC)) /** @brief Macro to configure SAI2 clock source selection. * @note This configuration is only available with STM32F446xx Devices. * @note This function must be called before enabling PLL, PLLSAI, PLLI2S and * the SAI clock. * @param __SOURCE__: specifies the SAI2 clock source. * This parameter can be one of the following values: * @arg RCC_SAI2CLKSOURCE_PLLI2S: PLLI2S_Q clock divided by PLLI2SDIVQ used as SAI2 clock. * @arg RCC_SAI2CLKSOURCE_PLLSAI: PLLISAI_Q clock divided by PLLSAIDIVQ used as SAI2 clock. * @arg RCC_SAI2CLKSOURCE_PLLR: PLL VCO Output divided by PLLR used as SAI2 clock. * @arg RCC_SAI2CLKSOURCE_PLLSRC: HSI or HSE depending from PLL Source clock used as SAI2 clock. */ #define __HAL_RCC_SAI2_CONFIG(__SOURCE__) (MODIFY_REG(RCC->DCKCFGR, RCC_DCKCFGR_SAI2SRC, (__SOURCE__))) /** @brief Macro to Get SAI2 clock source selection. * @note This configuration is only available with STM32F446xx Devices. * @retval The clock source can be one of the following values: * @arg RCC_SAI2CLKSOURCE_PLLI2S: PLLI2S_Q clock divided by PLLI2SDIVQ used as SAI2 clock. * @arg RCC_SAI2CLKSOURCE_PLLSAI: PLLISAI_Q clock divided by PLLSAIDIVQ used as SAI2 clock. * @arg RCC_SAI2CLKSOURCE_PLLR: PLL VCO Output divided by PLLR used as SAI2 clock. * @arg RCC_SAI2CLKSOURCE_PLLSRC: HSI or HSE depending from PLL Source clock used as SAI2 clock. */ #define __HAL_RCC_GET_SAI2_SOURCE() (READ_BIT(RCC->DCKCFGR, RCC_DCKCFGR_SAI2SRC)) /** @brief Macro to configure I2S APB1 clock source selection. * @note This function must be called before enabling PLL, PLLI2S and the I2S clock. * @param __SOURCE__: specifies the I2S APB1 clock source. * This parameter can be one of the following values: * @arg RCC_I2SAPB1CLKSOURCE_PLLI2S: PLLI2S VCO output clock divided by PLLI2SR used as I2S clock. * @arg RCC_I2SAPB1CLKSOURCE_EXT: External clock mapped on the I2S_CKIN pin used as SAI1 clock. * @arg RCC_I2SAPB1CLKSOURCE_PLLR: PLL VCO Output divided by PLLR used as SAI1 clock. * @arg RCC_I2SAPB1CLKSOURCE_PLLSRC: HSI or HSE depending from PLL source Clock. */ #define __HAL_RCC_I2S_APB1_CONFIG(__SOURCE__) (MODIFY_REG(RCC->DCKCFGR, RCC_DCKCFGR_I2S1SRC, (__SOURCE__))) /** @brief Macro to Get I2S APB1 clock source selection. * @retval The clock source can be one of the following values: * @arg RCC_I2SAPB1CLKSOURCE_PLLI2S: PLLI2S VCO output clock divided by PLLI2SR used as I2S clock. * @arg RCC_I2SAPB1CLKSOURCE_EXT: External clock mapped on the I2S_CKIN pin used as SAI1 clock. * @arg RCC_I2SAPB1CLKSOURCE_PLLR: PLL VCO Output divided by PLLR used as SAI1 clock. * @arg RCC_I2SAPB1CLKSOURCE_PLLSRC: HSI or HSE depending from PLL source Clock. */ #define __HAL_RCC_GET_I2S_APB1_SOURCE() (READ_BIT(RCC->DCKCFGR, RCC_DCKCFGR_I2S1SRC)) /** @brief Macro to configure I2S APB2 clock source selection. * @note This function must be called before enabling PLL, PLLI2S and the I2S clock. * @param __SOURCE__: specifies the SAI Block A clock source. * This parameter can be one of the following values: * @arg RCC_I2SAPB2CLKSOURCE_PLLI2S: PLLI2S VCO output clock divided by PLLI2SR used as I2S clock. * @arg RCC_I2SAPB2CLKSOURCE_EXT: External clock mapped on the I2S_CKIN pin used as SAI1 clock. * @arg RCC_I2SAPB2CLKSOURCE_PLLR: PLL VCO Output divided by PLLR used as SAI1 clock. * @arg RCC_I2SAPB2CLKSOURCE_PLLSRC: HSI or HSE depending from PLL source Clock. */ #define __HAL_RCC_I2S_APB2_CONFIG(__SOURCE__) (MODIFY_REG(RCC->DCKCFGR, RCC_DCKCFGR_I2S2SRC, (__SOURCE__))) /** @brief Macro to Get I2S APB2 clock source selection. * @retval The clock source can be one of the following values: * @arg RCC_I2SAPB2CLKSOURCE_PLLI2S: PLLI2S VCO output clock divided by PLLI2SR used as I2S clock. * @arg RCC_I2SAPB2CLKSOURCE_EXT: External clock mapped on the I2S_CKIN pin used as SAI1 clock. * @arg RCC_I2SAPB2CLKSOURCE_PLLR: PLL VCO Output divided by PLLR used as SAI1 clock. * @arg RCC_I2SAPB2CLKSOURCE_PLLSRC: HSI or HSE depending from PLL source Clock. */ #define __HAL_RCC_GET_I2S_APB2_SOURCE() (READ_BIT(RCC->DCKCFGR, RCC_DCKCFGR_I2S2SRC)) /** @brief Macro to configure the CEC clock. * @param __SOURCE__: specifies the CEC clock source. * This parameter can be one of the following values: * @arg RCC_CECCLKSOURCE_HSI: HSI selected as CEC clock * @arg RCC_CECCLKSOURCE_LSE: LSE selected as CEC clock */ #define __HAL_RCC_CEC_CONFIG(__SOURCE__) (MODIFY_REG(RCC->DCKCFGR2, RCC_DCKCFGR2_CECSEL, (uint32_t)(__SOURCE__))) /** @brief Macro to Get the CEC clock. * @retval The clock source can be one of the following values: * @arg RCC_CECCLKSOURCE_HSI488: HSI selected as CEC clock * @arg RCC_CECCLKSOURCE_LSE: LSE selected as CEC clock */ #define __HAL_RCC_GET_CEC_SOURCE() (READ_BIT(RCC->DCKCFGR2, RCC_DCKCFGR2_CECSEL)) /** @brief Macro to configure the FMPI2C1 clock. * @param __SOURCE__: specifies the FMPI2C1 clock source. * This parameter can be one of the following values: * @arg RCC_FMPI2C1CLKSOURCE_APB: APB selected as FMPI2C1 clock * @arg RCC_FMPI2C1CLKSOURCE_SYSCLK: SYS clock selected as FMPI2C1 clock * @arg RCC_FMPI2C1CLKSOURCE_HSI: HSI selected as FMPI2C1 clock */ #define __HAL_RCC_FMPI2C1_CONFIG(__SOURCE__) (MODIFY_REG(RCC->DCKCFGR2, RCC_DCKCFGR2_FMPI2C1SEL, (uint32_t)(__SOURCE__))) /** @brief Macro to Get the FMPI2C1 clock. * @retval The clock source can be one of the following values: * @arg RCC_FMPI2C1CLKSOURCE_APB: APB selected as FMPI2C1 clock * @arg RCC_FMPI2C1CLKSOURCE_SYSCLK: SYS clock selected as FMPI2C1 clock * @arg RCC_FMPI2C1CLKSOURCE_HSI: HSI selected as FMPI2C1 clock */ #define __HAL_RCC_GET_FMPI2C1_SOURCE() (READ_BIT(RCC->DCKCFGR2, RCC_DCKCFGR2_FMPI2C1SEL)) /** @brief Macro to configure the CLK48 clock. * @param __SOURCE__: specifies the CK48 clock source. * This parameter can be one of the following values: * @arg RCC_CK48CLKSOURCE_PLLQ: PLL VCO Output divided by PLLQ used as CK48 clock. * @arg RCC_CK48CLKSOURCE_PLLSAIP: PLLSAI VCO Output divided by PLLSAIP used as CK48 clock. */ #define __HAL_RCC_CLK48_CONFIG(__SOURCE__) (MODIFY_REG(RCC->DCKCFGR2, RCC_DCKCFGR2_CK48MSEL, (uint32_t)(__SOURCE__))) /** @brief Macro to Get the CLK48 clock. * @retval The clock source can be one of the following values: * @arg RCC_CK48CLKSOURCE_PLLQ: PLL VCO Output divided by PLLQ used as CK48 clock. * @arg RCC_CK48CLKSOURCE_PLLSAIP: PLLSAI VCO Output divided by PLLSAIP used as CK48 clock. */ #define __HAL_RCC_GET_CLK48_SOURCE() (READ_BIT(RCC->DCKCFGR2, RCC_DCKCFGR2_CK48MSEL)) /** @brief Macro to configure the SDIO clock. * @param __SOURCE__: specifies the SDIO clock source. * This parameter can be one of the following values: * @arg RCC_SDIOCLKSOURCE_CK48: CK48 output used as SDIO clock. * @arg RCC_SDIOCLKSOURCE_SYSCLK: System clock output used as SDIO clock. */ #define __HAL_RCC_SDIO_CONFIG(__SOURCE__) (MODIFY_REG(RCC->DCKCFGR2, RCC_DCKCFGR2_SDIOSEL, (uint32_t)(__SOURCE__))) /** @brief Macro to Get the SDIO clock. * @retval The clock source can be one of the following values: * @arg RCC_SDIOCLKSOURCE_CK48: CK48 output used as SDIO clock. * @arg RCC_SDIOCLKSOURCE_SYSCLK: System clock output used as SDIO clock. */ #define __HAL_RCC_GET_SDIO_SOURCE() (READ_BIT(RCC->DCKCFGR2, RCC_DCKCFGR2_SDIOSEL)) /** @brief Macro to configure the SPDIFRX clock. * @param __SOURCE__: specifies the SPDIFRX clock source. * This parameter can be one of the following values: * @arg RCC_SPDIFRXCLKSOURCE_PLLR: PLL VCO Output divided by PLLR used as SPDIFRX clock. * @arg RCC_SPDIFRXCLKSOURCE_PLLI2SP: PLLI2S VCO Output divided by PLLI2SP used as SPDIFRX clock. */ #define __HAL_RCC_SPDIFRX_CONFIG(__SOURCE__) (MODIFY_REG(RCC->DCKCFGR2, RCC_DCKCFGR2_SPDIFRXSEL, (uint32_t)(__SOURCE__))) /** @brief Macro to Get the SPDIFRX clock. * @retval The clock source can be one of the following values: * @arg RCC_SPDIFRXCLKSOURCE_PLLR: PLL VCO Output divided by PLLR used as SPDIFRX clock. * @arg RCC_SPDIFRXCLKSOURCE_PLLI2SP: PLLI2S VCO Output divided by PLLI2SP used as SPDIFRX clock. */ #define __HAL_RCC_GET_SPDIFRX_SOURCE() (READ_BIT(RCC->DCKCFGR2, RCC_DCKCFGR2_SPDIFRXSEL)) #endif /* STM32F446xx */ #if defined(STM32F469xx) || defined(STM32F479xx) /** @brief Macro to configure the CLK48 clock. * @param __SOURCE__: specifies the CK48 clock source. * This parameter can be one of the following values: * @arg RCC_CK48CLKSOURCE_PLLQ: PLL VCO Output divided by PLLQ used as CK48 clock. * @arg RCC_CK48CLKSOURCE_PLLSAIP: PLLSAI VCO Output divided by PLLSAIP used as CK48 clock. */ #define __HAL_RCC_CLK48_CONFIG(__SOURCE__) (MODIFY_REG(RCC->DCKCFGR, RCC_DCKCFGR_CK48MSEL, (uint32_t)(__SOURCE__))) /** @brief Macro to Get the CLK48 clock. * @retval The clock source can be one of the following values: * @arg RCC_CK48CLKSOURCE_PLLQ: PLL VCO Output divided by PLLQ used as CK48 clock. * @arg RCC_CK48CLKSOURCE_PLLSAIP: PLLSAI VCO Output divided by PLLSAIP used as CK48 clock. */ #define __HAL_RCC_GET_CLK48_SOURCE() (READ_BIT(RCC->DCKCFGR, RCC_DCKCFGR_CK48MSEL)) /** @brief Macro to configure the SDIO clock. * @param __SOURCE__: specifies the SDIO clock source. * This parameter can be one of the following values: * @arg RCC_SDIOCLKSOURCE_CK48: CK48 output used as SDIO clock. * @arg RCC_SDIOCLKSOURCE_SYSCLK: System clock output used as SDIO clock. */ #define __HAL_RCC_SDIO_CONFIG(__SOURCE__) (MODIFY_REG(RCC->DCKCFGR, RCC_DCKCFGR_SDIOSEL, (uint32_t)(__SOURCE__))) /** @brief Macro to Get the SDIO clock. * @retval The clock source can be one of the following values: * @arg RCC_SDIOCLKSOURCE_CK48: CK48 output used as SDIO clock. * @arg RCC_SDIOCLKSOURCE_SYSCLK: System clock output used as SDIO clock. */ #define __HAL_RCC_GET_SDIO_SOURCE() (READ_BIT(RCC->DCKCFGR, RCC_DCKCFGR_SDIOSEL)) /** @brief Macro to configure the DSI clock. * @param __SOURCE__: specifies the DSI clock source. * This parameter can be one of the following values: * @arg RCC_DSICLKSOURCE_PLLR: PLLR output used as DSI clock. * @arg RCC_DSICLKSOURCE_DSIPHY: DSI-PHY output used as DSI clock. */ #define __HAL_RCC_DSI_CONFIG(__SOURCE__) (MODIFY_REG(RCC->DCKCFGR, RCC_DCKCFGR_DSISEL, (uint32_t)(__SOURCE__))) /** @brief Macro to Get the DSI clock. * @retval The clock source can be one of the following values: * @arg RCC_DSICLKSOURCE_PLLR: PLLR output used as DSI clock. * @arg RCC_DSICLKSOURCE_DSIPHY: DSI-PHY output used as DSI clock. */ #define __HAL_RCC_GET_DSI_SOURCE() (READ_BIT(RCC->DCKCFGR, RCC_DCKCFGR_DSISEL)) #endif /* STM32F469xx || STM32F479xx */ #if defined(STM32F410Tx) || defined(STM32F410Cx) || defined(STM32F410Rx) /** @brief Macro to configure I2S clock source selection. * @param __SOURCE__: specifies the I2S clock source. * This parameter can be one of the following values: * @arg RCC_I2SAPBCLKSOURCE_PLLR: PLL VCO output clock divided by PLLR. * @arg RCC_I2SAPBCLKSOURCE_EXT: External clock mapped on the I2S_CKIN pin. * @arg RCC_I2SAPBCLKSOURCE_PLLSRC: HSI/HSE depends on PLLSRC. */ #define __HAL_RCC_I2S_CONFIG(__SOURCE__) (MODIFY_REG(RCC->DCKCFGR, RCC_DCKCFGR_I2SSRC, (__SOURCE__))) /** @brief Macro to Get I2S clock source selection. * @retval The clock source can be one of the following values: * @arg RCC_I2SAPBCLKSOURCE_PLLR: PLL VCO output clock divided by PLLR. * @arg RCC_I2SAPBCLKSOURCE_EXT: External clock mapped on the I2S_CKIN pin. * @arg RCC_I2SAPBCLKSOURCE_PLLSRC: HSI/HSE depends on PLLSRC. */ #define __HAL_RCC_GET_I2S_SOURCE() (READ_BIT(RCC->DCKCFGR, RCC_DCKCFGR_I2SSRC)) /** @brief Macro to configure the FMPI2C1 clock. * @param __SOURCE__: specifies the FMPI2C1 clock source. * This parameter can be one of the following values: * @arg RCC_FMPI2C1CLKSOURCE_APB: APB selected as FMPI2C1 clock * @arg RCC_FMPI2C1CLKSOURCE_SYSCLK: SYS clock selected as FMPI2C1 clock * @arg RCC_FMPI2C1CLKSOURCE_HSI: HSI selected as FMPI2C1 clock */ #define __HAL_RCC_FMPI2C1_CONFIG(__SOURCE__) (MODIFY_REG(RCC->DCKCFGR2, RCC_DCKCFGR2_FMPI2C1SEL, (uint32_t)(__SOURCE__))) /** @brief Macro to Get the FMPI2C1 clock. * @retval The clock source can be one of the following values: * @arg RCC_FMPI2C1CLKSOURCE_APB: APB selected as FMPI2C1 clock * @arg RCC_FMPI2C1CLKSOURCE_SYSCLK: SYS clock selected as FMPI2C1 clock * @arg RCC_FMPI2C1CLKSOURCE_HSI: HSI selected as FMPI2C1 clock */ #define __HAL_RCC_GET_FMPI2C1_SOURCE() (READ_BIT(RCC->DCKCFGR2, RCC_DCKCFGR2_FMPI2C1SEL)) /** @brief Macro to configure the LPTIM1 clock. * @param __SOURCE__: specifies the LPTIM1 clock source. * This parameter can be one of the following values: * @arg RCC_LPTIM1CLKSOURCE_PCLK: APB selected as LPTIM1 clock * @arg RCC_LPTIM1CLKSOURCE_HSI: HSI clock selected as LPTIM1 clock * @arg RCC_LPTIM1CLKSOURCE_LSI: LSI selected as LPTIM1 clock * @arg RCC_LPTIM1CLKSOURCE_LSE: LSE selected as LPTIM1 clock */ #define __HAL_RCC_LPTIM1_CONFIG(__SOURCE__) (MODIFY_REG(RCC->DCKCFGR2, RCC_DCKCFGR2_LPTIM1SEL, (uint32_t)(__SOURCE__))) /** @brief Macro to Get the LPTIM1 clock. * @retval The clock source can be one of the following values: * @arg RCC_LPTIM1CLKSOURCE_PCLK: APB selected as LPTIM1 clock * @arg RCC_LPTIM1CLKSOURCE_HSI: HSI clock selected as LPTIM1 clock * @arg RCC_LPTIM1CLKSOURCE_LSI: LSI selected as LPTIM1 clock * @arg RCC_LPTIM1CLKSOURCE_LSE: LSE selected as LPTIM1 clock */ #define __HAL_RCC_GET_LPTIM1_SOURCE() (READ_BIT(RCC->DCKCFGR2, RCC_DCKCFGR2_LPTIM1SEL)) #endif /* STM32F410Tx || STM32F410Cx || STM32F410Rx */ #if defined(STM32F427xx) || defined(STM32F437xx) || defined(STM32F429xx) || defined(STM32F439xx) ||\ defined(STM32F401xC) || defined(STM32F401xE) || defined(STM32F410Tx) || defined(STM32F410Cx) ||\ defined(STM32F410Rx) || defined(STM32F411xE) || defined(STM32F446xx) || defined(STM32F469xx) ||\ defined(STM32F479xx) /** @brief Macro to configure the Timers clocks prescalers * @note This feature is only available with STM32F429x/439x Devices. * @param __PRESC__ : specifies the Timers clocks prescalers selection * This parameter can be one of the following values: * @arg RCC_TIMPRES_DESACTIVATED: The Timers kernels clocks prescaler is * equal to HPRE if PPREx is corresponding to division by 1 or 2, * else it is equal to [(HPRE * PPREx) / 2] if PPREx is corresponding to * division by 4 or more. * @arg RCC_TIMPRES_ACTIVATED: The Timers kernels clocks prescaler is * equal to HPRE if PPREx is corresponding to division by 1, 2 or 4, * else it is equal to [(HPRE * PPREx) / 4] if PPREx is corresponding * to division by 8 or more. */ #define __HAL_RCC_TIMCLKPRESCALER(__PRESC__) (*(__IO uint32_t *) RCC_DCKCFGR_TIMPRE_BB = (__PRESC__)) #endif /* STM32F427xx || STM32F437xx || STM32F429xx || STM32F439xx) || STM32F401xC || STM32F401xE || STM32F410xx || STM32F411xE ||\ STM32F446xx || STM32F469xx || STM32F479xx */ /*----------------------------------------------------------------------------*/ #if defined(STM32F427xx) || defined(STM32F437xx) || defined(STM32F429xx) || defined(STM32F439xx) || defined(STM32F446xx) || defined(STM32F469xx) || defined(STM32F479xx) /** @brief Enable PLLSAI_RDY interrupt. */ #define __HAL_RCC_PLLSAI_ENABLE_IT() (RCC->CIR |= (RCC_CIR_PLLSAIRDYIE)) /** @brief Disable PLLSAI_RDY interrupt. */ #define __HAL_RCC_PLLSAI_DISABLE_IT() (RCC->CIR &= ~(RCC_CIR_PLLSAIRDYIE)) /** @brief Clear the PLLSAI RDY interrupt pending bits. */ #define __HAL_RCC_PLLSAI_CLEAR_IT() (RCC->CIR |= (RCC_CIR_PLLSAIRDYF)) /** @brief Check the PLLSAI RDY interrupt has occurred or not. * @retval The new state (TRUE or FALSE). */ #define __HAL_RCC_PLLSAI_GET_IT() ((RCC->CIR & (RCC_CIR_PLLSAIRDYIE)) == (RCC_CIR_PLLSAIRDYIE)) /** @brief Check PLLSAI RDY flag is set or not. * @retval The new state (TRUE or FALSE). */ #define __HAL_RCC_PLLSAI_GET_FLAG() ((RCC->CR & (RCC_CR_PLLSAIRDY)) == (RCC_CR_PLLSAIRDY)) #endif /* STM32F427xx || STM32F437xx || STM32F429xx || STM32F439xx || STM32F446xx || STM32F469xx || STM32F479xx */ #if defined(STM32F410Tx) || defined(STM32F410Cx) || defined(STM32F410Rx) /** @defgroup RCCEx_MCO1_Enable MCO1 Enable * @brief Macros to enable or disable the RCC MCO1 feature. */ #define __HAL_RCC_MCO1_ENABLE() (*(__IO uint32_t *) RCC_CFGR_MCO1EN_BB = ENABLE) #define __HAL_RCC_MCO1_DISABLE() (*(__IO uint32_t *) RCC_CFGR_MCO1EN_BB = DISABLE) /** * @} */ /** @defgroup RCCEx_MCO2_Enable MCO2 Enable * @brief Macros to enable or disable the RCC MCO2 feature. */ #define __HAL_RCC_MCO2_ENABLE() (*(__IO uint32_t *) RCC_CFGR_MCO2EN_BB = ENABLE) #define __HAL_RCC_MCO2_DISABLE() (*(__IO uint32_t *) RCC_CFGR_MCO2EN_BB = DISABLE) /** * @} */ #endif /* STM32F410Tx || STM32F410Cx || STM32F410Rx */ /** * @} */ /* Exported functions --------------------------------------------------------*/ /** @addtogroup RCCEx_Exported_Functions * @{ */ /** @addtogroup RCCEx_Exported_Functions_Group1 * @{ */ HAL_StatusTypeDef HAL_RCCEx_PeriphCLKConfig(RCC_PeriphCLKInitTypeDef *PeriphClkInit); void HAL_RCCEx_GetPeriphCLKConfig(RCC_PeriphCLKInitTypeDef *PeriphClkInit); #if defined(STM32F446xx) uint32_t HAL_RCCEx_GetPeriphCLKFreq(uint32_t PeriphClk); #endif /* STM32F446xx */ #if defined(STM32F410Tx) || defined(STM32F410Cx) || defined(STM32F410Rx) || defined(STM32F411xE) ||\ defined(STM32F446xx) || defined(STM32F469xx) || defined(STM32F479xx) void HAL_RCCEx_SelectLSEMode(uint8_t Mode); #endif /* STM32F410xx || STM32F411xE || STM32F446xx || STM32F469xx || STM32F479xx */ /** * @} */ /** * @} */ /* Private types -------------------------------------------------------------*/ /* Private variables ---------------------------------------------------------*/ /* Private constants ---------------------------------------------------------*/ /** @defgroup RCCEx_Private_Constants RCCEx Private Constants * @{ */ /** @defgroup RCCEx_BitAddress_AliasRegion RCC BitAddress AliasRegion * @brief RCC registers bit address in the alias region * @{ */ /* --- CR Register ---*/ #if defined(STM32F427xx) || defined(STM32F437xx) || defined(STM32F429xx) || defined(STM32F439xx) ||\ defined(STM32F446xx) || defined(STM32F469xx) || defined(STM32F479xx) /* Alias word address of PLLSAION bit */ #define RCC_PLLSAION_BIT_NUMBER 0x1C #define RCC_CR_PLLSAION_BB (PERIPH_BB_BASE + (RCC_CR_OFFSET * 32) + (RCC_PLLSAION_BIT_NUMBER * 4)) #define PLLSAI_TIMEOUT_VALUE ((uint32_t)100) /* Timeout value fixed to 100 ms */ #endif /* STM32F427xx || STM32F437xx || STM32F429xx || STM32F439xx || STM32F446xx || STM32F469xx || STM32F479xx */ #if defined(STM32F405xx) || defined(STM32F415xx) || defined(STM32F407xx) || defined(STM32F417xx) || \ defined(STM32F427xx) || defined(STM32F437xx) || defined(STM32F429xx) || defined(STM32F439xx) || \ defined(STM32F401xC) || defined(STM32F401xE) || defined(STM32F411xE) || defined(STM32F446xx) || \ defined(STM32F469xx) || defined(STM32F479xx) /* Alias word address of PLLI2SON bit */ #define RCC_PLLI2SON_BIT_NUMBER 0x1A #define RCC_CR_PLLI2SON_BB (PERIPH_BB_BASE + (RCC_CR_OFFSET * 32) + (RCC_PLLI2SON_BIT_NUMBER * 4)) #endif /* STM32F405xx || STM32F415xx || STM32F407xx || STM32F417xx || STM32F427xx || STM32F437xx || STM32F429xx || STM32F439xx || STM32F401xC || STM32F401xE || STM32F411xE || STM32F446xx || STM32F469xx || STM32F479xx */ /* --- DCKCFGR Register ---*/ #if defined(STM32F427xx) || defined(STM32F437xx) || defined(STM32F429xx) || defined(STM32F439xx) ||\ defined(STM32F410Tx) || defined(STM32F410Cx) || defined(STM32F410Rx) || defined(STM32F446xx) ||\ defined(STM32F469xx) || defined(STM32F479xx) /* Alias word address of TIMPRE bit */ #define RCC_DCKCFGR_OFFSET (RCC_OFFSET + 0x8C) #define RCC_TIMPRE_BIT_NUMBER 0x18 #define RCC_DCKCFGR_TIMPRE_BB (PERIPH_BB_BASE + (RCC_DCKCFGR_OFFSET * 32) + (RCC_TIMPRE_BIT_NUMBER * 4)) #endif /* STM32F427xx || STM32F437xx || STM32F429xx || STM32F439xx || STM32F410xx || STM32F446xx || STM32F469xx || STM32F479xx */ /* --- CFGR Register ---*/ #define RCC_CFGR_OFFSET (RCC_OFFSET + 0x08) #if defined(STM32F405xx) || defined(STM32F415xx) || defined(STM32F407xx) || defined(STM32F417xx) || \ defined(STM32F427xx) || defined(STM32F437xx) || defined(STM32F429xx) || defined(STM32F439xx) || \ defined(STM32F401xC) || defined(STM32F401xE) || defined(STM32F411xE) || defined(STM32F446xx) || \ defined(STM32F469xx) || defined(STM32F479xx) /* Alias word address of I2SSRC bit */ #define RCC_I2SSRC_BIT_NUMBER 0x17 #define RCC_CFGR_I2SSRC_BB (PERIPH_BB_BASE + (RCC_CFGR_OFFSET * 32) + (RCC_I2SSRC_BIT_NUMBER * 4)) #define PLLI2S_TIMEOUT_VALUE ((uint32_t)100) /* Timeout value fixed to 100 ms */ #endif /* STM32F405xx || STM32F415xx || STM32F407xx || STM32F417xx || STM32F427xx || STM32F437xx || STM32F429xx || STM32F439xx || STM32F401xC || STM32F401xE || STM32F411xE || STM32F446xx || STM32F469xx || STM32F479xx */ #if defined(STM32F410Tx) || defined(STM32F410Cx) || defined(STM32F410Rx) /* Alias word address of MCO1EN bit */ #define RCC_MCO1EN_BIT_NUMBER 0x8 #define RCC_CFGR_MCO1EN_BB (PERIPH_BB_BASE + (RCC_CFGR_OFFSET * 32) + (RCC_MCO1EN_BIT_NUMBER * 4)) /* Alias word address of MCO2EN bit */ #define RCC_MCO2EN_BIT_NUMBER 0x9 #define RCC_CFGR_MCO2EN_BB (PERIPH_BB_BASE + (RCC_CFGR_OFFSET * 32) + (RCC_MCO2EN_BIT_NUMBER * 4)) #endif /* STM32F410Tx || STM32F410Cx || STM32F410Rx */ #define PLL_TIMEOUT_VALUE ((uint32_t)100) /* 100 ms */ /** * @} */ /** * @} */ /* Private macros ------------------------------------------------------------*/ /** @addtogroup RCCEx_Private_Macros RCCEx Private Macros * @{ */ /** @defgroup RCCEx_IS_RCC_Definitions RCC Private macros to check input parameters * @{ */ #if defined(STM32F427xx) || defined(STM32F437xx) || defined(STM32F429xx)|| defined(STM32F439xx) #define IS_RCC_PERIPHCLOCK(SELECTION) ((1 <= (SELECTION)) && ((SELECTION) <= 0x0000007F)) #endif /* STM32F427xx || STM32F437xx || STM32F429xx || STM32F439xx */ #if defined(STM32F405xx) || defined(STM32F415xx) || defined(STM32F407xx)|| defined(STM32F417xx) ||\ defined(STM32F401xC) || defined(STM32F401xE) || defined(STM32F411xE) #define IS_RCC_PERIPHCLOCK(SELECTION) ((1 <= (SELECTION)) && ((SELECTION) <= 0x00000007)) #endif /* STM32F405xx || STM32F415xx || STM32F407xx || STM32F417xx || STM32F401xC || STM32F401xE || STM32F411xE */ #if defined(STM32F410Tx) || defined(STM32F410Cx) || defined(STM32F410Rx) #define IS_RCC_PERIPHCLOCK(SELECTION) ((1 <= (SELECTION)) && ((SELECTION) <= 0x0000001F)) #endif /* STM32F410Tx || STM32F410Cx || STM32F410Rx */ #if defined(STM32F446xx) #define IS_RCC_PERIPHCLOCK(SELECTION) ((1 <= (SELECTION)) && ((SELECTION) <= 0x00000FFF)) #endif /* STM32F446xx */ #if defined(STM32F469xx) || defined(STM32F479xx) #define IS_RCC_PERIPHCLOCK(SELECTION) ((1 <= (SELECTION)) && ((SELECTION) <= 0x000001FF)) #endif /* STM32F469xx || STM32F479xx */ #define IS_RCC_PLLI2SN_VALUE(VALUE) ((192 <= (VALUE)) && ((VALUE) <= 432)) #define IS_RCC_PLLI2SR_VALUE(VALUE) ((2 <= (VALUE)) && ((VALUE) <= 7)) #if defined(STM32F427xx) || defined(STM32F437xx) || defined(STM32F429xx)|| defined(STM32F439xx) ||\ defined(STM32F446xx) || defined(STM32F469xx) || defined(STM32F479xx) #define IS_RCC_PLLI2SQ_VALUE(VALUE) ((2 <= (VALUE)) && ((VALUE) <= 15)) #define IS_RCC_PLLSAIN_VALUE(VALUE) ((49 <= (VALUE)) && ((VALUE) <= 432)) #define IS_RCC_PLLSAIQ_VALUE(VALUE) ((2 <= (VALUE)) && ((VALUE) <= 15)) #define IS_RCC_PLLSAIR_VALUE(VALUE) ((2 <= (VALUE)) && ((VALUE) <= 7)) #define IS_RCC_PLLSAI_DIVQ_VALUE(VALUE) ((1 <= (VALUE)) && ((VALUE) <= 32)) #define IS_RCC_PLLI2S_DIVQ_VALUE(VALUE) ((1 <= (VALUE)) && ((VALUE) <= 32)) #define IS_RCC_PLLSAI_DIVR_VALUE(VALUE) (((VALUE) == RCC_PLLSAIDIVR_2) ||\ ((VALUE) == RCC_PLLSAIDIVR_4) ||\ ((VALUE) == RCC_PLLSAIDIVR_8) ||\ ((VALUE) == RCC_PLLSAIDIVR_16)) #endif /* STM32F427xx || STM32F437xx || STM32F429xx || STM32F439xx || STM32F446xx || STM32F469xx || STM32F479xx */ #if defined(STM32F411xE) || defined(STM32F446xx) #define IS_RCC_PLLI2SM_VALUE(VALUE) ((VALUE) <= 63) #define IS_RCC_LSE_MODE(MODE) (((MODE) == RCC_LSE_LOWPOWER_MODE) ||\ ((MODE) == RCC_LSE_HIGHDRIVE_MODE)) #endif /* STM32F411xE || STM32F446xx */ #if defined(STM32F410Tx) || defined(STM32F410Cx) || defined(STM32F410Rx) #define IS_RCC_PLLR_VALUE(VALUE) ((2 <= (VALUE)) && ((VALUE) <= 7)) #define IS_RCC_LSE_MODE(MODE) (((MODE) == RCC_LSE_LOWPOWER_MODE) ||\ ((MODE) == RCC_LSE_HIGHDRIVE_MODE)) #define IS_RCC_FMPI2C1CLKSOURCE(SOURCE) (((SOURCE) == RCC_FMPI2C1CLKSOURCE_APB) ||\ ((SOURCE) == RCC_FMPI2C1CLKSOURCE_SYSCLK) ||\ ((SOURCE) == RCC_FMPI2C1CLKSOURCE_HSI)) #define IS_RCC_LPTIM1CLKSOURCE(SOURCE) (((SOURCE) == RCC_LPTIM1CLKSOURCE_PCLK) ||\ ((SOURCE) == RCC_LPTIM1CLKSOURCE_HSI) ||\ ((SOURCE) == RCC_LPTIM1CLKSOURCE_LSI) ||\ ((SOURCE) == RCC_LPTIM1CLKSOURCE_LSE)) #define IS_RCC_I2SAPBCLKSOURCE(SOURCE) (((SOURCE) == RCC_I2SAPBCLKSOURCE_PLLR) ||\ ((SOURCE) == RCC_I2SAPBCLKSOURCE_EXT) ||\ ((SOURCE) == RCC_I2SAPBCLKSOURCE_PLLSRC)) #endif /* STM32F410Tx || STM32F410Cx || STM32F410Rx */ #if defined(STM32F446xx) #define IS_RCC_PLLR_VALUE(VALUE) ((2 <= (VALUE)) && ((VALUE) <= 7)) #define IS_RCC_PLLI2SP_VALUE(VALUE) (((VALUE) == RCC_PLLI2SP_DIV2) ||\ ((VALUE) == RCC_PLLI2SP_DIV4) ||\ ((VALUE) == RCC_PLLI2SP_DIV6) ||\ ((VALUE) == RCC_PLLI2SP_DIV8)) #define IS_RCC_PLLSAIM_VALUE(VALUE) ((VALUE) <= 63) #define IS_RCC_PLLSAIP_VALUE(VALUE) (((VALUE) == RCC_PLLSAIP_DIV2) ||\ ((VALUE) == RCC_PLLSAIP_DIV4) ||\ ((VALUE) == RCC_PLLSAIP_DIV6) ||\ ((VALUE) == RCC_PLLSAIP_DIV8)) #define IS_RCC_SAI1CLKSOURCE(SOURCE) (((SOURCE) == RCC_SAI1CLKSOURCE_PLLSAI) ||\ ((SOURCE) == RCC_SAI1CLKSOURCE_PLLI2S) ||\ ((SOURCE) == RCC_SAI1CLKSOURCE_PLLR) ||\ ((SOURCE) == RCC_SAI1CLKSOURCE_EXT)) #define IS_RCC_SAI2CLKSOURCE(SOURCE) (((SOURCE) == RCC_SAI2CLKSOURCE_PLLSAI) ||\ ((SOURCE) == RCC_SAI2CLKSOURCE_PLLI2S) ||\ ((SOURCE) == RCC_SAI2CLKSOURCE_PLLR) ||\ ((SOURCE) == RCC_SAI2CLKSOURCE_PLLSRC)) #define IS_RCC_I2SAPB1CLKSOURCE(SOURCE) (((SOURCE) == RCC_I2SAPB1CLKSOURCE_PLLI2S) ||\ ((SOURCE) == RCC_I2SAPB1CLKSOURCE_EXT) ||\ ((SOURCE) == RCC_I2SAPB1CLKSOURCE_PLLR) ||\ ((SOURCE) == RCC_I2SAPB1CLKSOURCE_PLLSRC)) #define IS_RCC_I2SAPB2CLKSOURCE(SOURCE) (((SOURCE) == RCC_I2SAPB2CLKSOURCE_PLLI2S) ||\ ((SOURCE) == RCC_I2SAPB2CLKSOURCE_EXT) ||\ ((SOURCE) == RCC_I2SAPB2CLKSOURCE_PLLR) ||\ ((SOURCE) == RCC_I2SAPB2CLKSOURCE_PLLSRC)) #define IS_RCC_FMPI2C1CLKSOURCE(SOURCE) (((SOURCE) == RCC_FMPI2C1CLKSOURCE_APB) ||\ ((SOURCE) == RCC_FMPI2C1CLKSOURCE_SYSCLK) ||\ ((SOURCE) == RCC_FMPI2C1CLKSOURCE_HSI)) #define IS_RCC_CECCLKSOURCE(SOURCE) (((SOURCE) == RCC_CECCLKSOURCE_HSI) ||\ ((SOURCE) == RCC_CECCLKSOURCE_LSE)) #define IS_RCC_CK48CLKSOURCE(SOURCE) (((SOURCE) == RCC_CK48CLKSOURCE_PLLQ) ||\ ((SOURCE) == RCC_CK48CLKSOURCE_PLLSAIP)) #define IS_RCC_SDIOCLKSOURCE(SOURCE) (((SOURCE) == RCC_SDIOCLKSOURCE_CK48) ||\ ((SOURCE) == RCC_SDIOCLKSOURCE_SYSCLK)) #define IS_RCC_SPDIFRXCLKSOURCE(SOURCE) (((SOURCE) == RCC_SPDIFRXCLKSOURCE_PLLR) ||\ ((SOURCE) == RCC_SPDIFRXCLKSOURCE_PLLI2SP)) #endif /* STM32F446xx */ #if defined(STM32F469xx) || defined(STM32F479xx) #define IS_RCC_PLLR_VALUE(VALUE) ((2 <= (VALUE)) && ((VALUE) <= 7)) #define IS_RCC_PLLSAIP_VALUE(VALUE) (((VALUE) == RCC_PLLSAIP_DIV2) ||\ ((VALUE) == RCC_PLLSAIP_DIV4) ||\ ((VALUE) == RCC_PLLSAIP_DIV6) ||\ ((VALUE) == RCC_PLLSAIP_DIV8)) #define IS_RCC_CK48CLKSOURCE(SOURCE) (((SOURCE) == RCC_CK48CLKSOURCE_PLLQ) ||\ ((SOURCE) == RCC_CK48CLKSOURCE_PLLSAIP)) #define IS_RCC_SDIOCLKSOURCE(SOURCE) (((SOURCE) == RCC_SDIOCLKSOURCE_CK48) ||\ ((SOURCE) == RCC_SDIOCLKSOURCE_SYSCLK)) #define IS_RCC_DSIBYTELANECLKSOURCE(SOURCE) (((SOURCE) == RCC_DSICLKSOURCE_PLLR) ||\ ((SOURCE) == RCC_DSICLKSOURCE_DSIPHY)) #define IS_RCC_LSE_MODE(MODE) (((MODE) == RCC_LSE_LOWPOWER_MODE) ||\ ((MODE) == RCC_LSE_HIGHDRIVE_MODE)) #endif /* STM32F469xx || STM32F479xx */ #if defined(STM32F405xx) || defined(STM32F415xx) || defined(STM32F407xx) || defined(STM32F417xx) || \ defined(STM32F427xx) || defined(STM32F437xx) || defined(STM32F429xx) || defined(STM32F439xx) || \ defined(STM32F401xC) || defined(STM32F401xE) || defined(STM32F411xE) || defined(STM32F446xx) || \ defined(STM32F469xx) || defined(STM32F479xx) #define IS_RCC_MCO2SOURCE(SOURCE) (((SOURCE) == RCC_MCO2SOURCE_SYSCLK) || ((SOURCE) == RCC_MCO2SOURCE_PLLI2SCLK)|| \ ((SOURCE) == RCC_MCO2SOURCE_HSE) || ((SOURCE) == RCC_MCO2SOURCE_PLLCLK)) #endif /* STM32F405xx || STM32F415xx || STM32F407xx || STM32F417xx || STM32F427xx || STM32F437xx || STM32F429xx || STM32F439xx || STM32F401xC || STM32F401xE || STM32F411xE || STM32F446xx || STM32F469xx || STM32F479xx */ #if defined(STM32F410Tx) || defined(STM32F410Cx) || defined(STM32F410Rx) #define IS_RCC_MCO2SOURCE(SOURCE) (((SOURCE) == RCC_MCO2SOURCE_SYSCLK) || ((SOURCE) == RCC_MCO2SOURCE_I2SCLK)|| \ ((SOURCE) == RCC_MCO2SOURCE_HSE) || ((SOURCE) == RCC_MCO2SOURCE_PLLCLK)) #endif /* STM32F410Tx || STM32F410Cx || STM32F410Rx */ /** * @} */ /** * @} */ /** * @} */ /** * @} */ #ifdef __cplusplus } #endif #endif /* __STM32F4xx_HAL_RCC_EX_H */ /************************ (C) COPYRIGHT STMicroelectronics *****END OF FILE****/ ================================================ FILE: Zelig/mbed/TARGET_NUCLEO_F401RE/stm32f4xx_hal_rng.h ================================================ /** ****************************************************************************** * @file stm32f4xx_hal_rng.h * @author MCD Application Team * @version V1.4.1 * @date 09-October-2015 * @brief Header file of RNG HAL module. ****************************************************************************** * @attention * *

© COPYRIGHT(c) 2015 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. * ****************************************************************************** */ /* Define to prevent recursive inclusion -------------------------------------*/ #ifndef __STM32F4xx_HAL_RNG_H #define __STM32F4xx_HAL_RNG_H #ifdef __cplusplus extern "C" { #endif #if defined(STM32F405xx) || defined(STM32F415xx) || defined(STM32F407xx) || defined(STM32F417xx) ||\ defined(STM32F427xx) || defined(STM32F437xx) || defined(STM32F429xx) || defined(STM32F439xx) ||\ defined(STM32F410Tx) || defined(STM32F410Cx) || defined(STM32F410Rx) || defined(STM32F469xx) ||\ defined(STM32F479xx) /* Includes ------------------------------------------------------------------*/ #include "stm32f4xx_hal_def.h" /** @addtogroup STM32F4xx_HAL_Driver * @{ */ /** @defgroup RNG RNG * @brief RNG HAL module driver * @{ */ /* Exported types ------------------------------------------------------------*/ /** @defgroup RNG_Exported_Types RNG Exported Types * @{ */ /** @defgroup RNG_Exported_Types_Group1 RNG State Structure definition * @{ */ typedef enum { HAL_RNG_STATE_RESET = 0x00, /*!< RNG not yet initialized or disabled */ HAL_RNG_STATE_READY = 0x01, /*!< RNG initialized and ready for use */ HAL_RNG_STATE_BUSY = 0x02, /*!< RNG internal process is ongoing */ HAL_RNG_STATE_TIMEOUT = 0x03, /*!< RNG timeout state */ HAL_RNG_STATE_ERROR = 0x04 /*!< RNG error state */ }HAL_RNG_StateTypeDef; /** * @} */ /** @defgroup RNG_Exported_Types_Group2 RNG Handle Structure definition * @{ */ typedef struct { RNG_TypeDef *Instance; /*!< Register base address */ HAL_LockTypeDef Lock; /*!< RNG locking object */ __IO HAL_RNG_StateTypeDef State; /*!< RNG communication state */ uint32_t RandomNumber; /*!< Last Generated RNG Data */ }RNG_HandleTypeDef; /** * @} */ /** * @} */ /* Exported constants --------------------------------------------------------*/ /** @defgroup RNG_Exported_Constants RNG Exported Constants * @{ */ /** @defgroup RNG_Exported_Constants_Group1 RNG Interrupt definition * @{ */ #define RNG_IT_DRDY RNG_SR_DRDY /*!< Data Ready interrupt */ #define RNG_IT_CEI RNG_SR_CEIS /*!< Clock error interrupt */ #define RNG_IT_SEI RNG_SR_SEIS /*!< Seed error interrupt */ /** * @} */ /** @defgroup RNG_Exported_Constants_Group2 RNG Flag definition * @{ */ #define RNG_FLAG_DRDY RNG_SR_DRDY /*!< Data ready */ #define RNG_FLAG_CECS RNG_SR_CECS /*!< Clock error current status */ #define RNG_FLAG_SECS RNG_SR_SECS /*!< Seed error current status */ /** * @} */ /** * @} */ /* Exported macros -----------------------------------------------------------*/ /** @defgroup RNG_Exported_Macros RNG Exported Macros * @{ */ /** @brief Reset RNG handle state * @param __HANDLE__: RNG Handle * @retval None */ #define __HAL_RNG_RESET_HANDLE_STATE(__HANDLE__) ((__HANDLE__)->State = HAL_RNG_STATE_RESET) /** * @brief Enables the RNG peripheral. * @param __HANDLE__: RNG Handle * @retval None */ #define __HAL_RNG_ENABLE(__HANDLE__) ((__HANDLE__)->Instance->CR |= RNG_CR_RNGEN) /** * @brief Disables the RNG peripheral. * @param __HANDLE__: RNG Handle * @retval None */ #define __HAL_RNG_DISABLE(__HANDLE__) ((__HANDLE__)->Instance->CR &= ~RNG_CR_RNGEN) /** * @brief Check the selected RNG flag status. * @param __HANDLE__: RNG Handle * @param __FLAG__: RNG flag * This parameter can be one of the following values: * @arg RNG_FLAG_DRDY: Data ready * @arg RNG_FLAG_CECS: Clock error current status * @arg RNG_FLAG_SECS: Seed error current status * @retval The new state of __FLAG__ (SET or RESET). */ #define __HAL_RNG_GET_FLAG(__HANDLE__, __FLAG__) (((__HANDLE__)->Instance->SR & (__FLAG__)) == (__FLAG__)) /** * @brief Clears the selected RNG flag status. * @param __HANDLE__: RNG handle * @param __FLAG__: RNG flag to clear * @note WARNING: This is a dummy macro for HAL code alignment, * flags RNG_FLAG_DRDY, RNG_FLAG_CECS and RNG_FLAG_SECS are read-only. * @retval None */ #define __HAL_RNG_CLEAR_FLAG(__HANDLE__, __FLAG__) /* dummy macro */ /** * @brief Enables the RNG interrupts. * @param __HANDLE__: RNG Handle * @retval None */ #define __HAL_RNG_ENABLE_IT(__HANDLE__) ((__HANDLE__)->Instance->CR |= RNG_CR_IE) /** * @brief Disables the RNG interrupts. * @param __HANDLE__: RNG Handle * @retval None */ #define __HAL_RNG_DISABLE_IT(__HANDLE__) ((__HANDLE__)->Instance->CR &= ~RNG_CR_IE) /** * @brief Checks whether the specified RNG interrupt has occurred or not. * @param __HANDLE__: RNG Handle * @param __INTERRUPT__: specifies the RNG interrupt status flag to check. * This parameter can be one of the following values: * @arg RNG_IT_DRDY: Data ready interrupt * @arg RNG_IT_CEI: Clock error interrupt * @arg RNG_IT_SEI: Seed error interrupt * @retval The new state of __INTERRUPT__ (SET or RESET). */ #define __HAL_RNG_GET_IT(__HANDLE__, __INTERRUPT__) (((__HANDLE__)->Instance->SR & (__INTERRUPT__)) == (__INTERRUPT__)) /** * @brief Clear the RNG interrupt status flags. * @param __HANDLE__: RNG Handle * @param __INTERRUPT__: specifies the RNG interrupt status flag to clear. * This parameter can be one of the following values: * @arg RNG_IT_CEI: Clock error interrupt * @arg RNG_IT_SEI: Seed error interrupt * @note RNG_IT_DRDY flag is read-only, reading RNG_DR register automatically clears RNG_IT_DRDY. * @retval None */ #define __HAL_RNG_CLEAR_IT(__HANDLE__, __INTERRUPT__) (((__HANDLE__)->Instance->SR) = ~(__INTERRUPT__)) /** * @} */ /* Exported functions --------------------------------------------------------*/ /** @defgroup RNG_Exported_Functions RNG Exported Functions * @{ */ /** @defgroup RNG_Exported_Functions_Group1 Initialization and de-initialization functions * @{ */ HAL_StatusTypeDef HAL_RNG_Init(RNG_HandleTypeDef *hrng); HAL_StatusTypeDef HAL_RNG_DeInit (RNG_HandleTypeDef *hrng); void HAL_RNG_MspInit(RNG_HandleTypeDef *hrng); void HAL_RNG_MspDeInit(RNG_HandleTypeDef *hrng); /** * @} */ /** @defgroup RNG_Exported_Functions_Group2 Peripheral Control functions * @{ */ uint32_t HAL_RNG_GetRandomNumber(RNG_HandleTypeDef *hrng); /* Obsolete, use HAL_RNG_GenerateRandomNumber() instead */ uint32_t HAL_RNG_GetRandomNumber_IT(RNG_HandleTypeDef *hrng); /* Obsolete, use HAL_RNG_GenerateRandomNumber_IT() instead */ HAL_StatusTypeDef HAL_RNG_GenerateRandomNumber(RNG_HandleTypeDef *hrng, uint32_t *random32bit); HAL_StatusTypeDef HAL_RNG_GenerateRandomNumber_IT(RNG_HandleTypeDef *hrng); uint32_t HAL_RNG_ReadLastRandomNumber(RNG_HandleTypeDef *hrng); void HAL_RNG_IRQHandler(RNG_HandleTypeDef *hrng); void HAL_RNG_ErrorCallback(RNG_HandleTypeDef *hrng); void HAL_RNG_ReadyDataCallback(RNG_HandleTypeDef* hrng, uint32_t random32bit); /** * @} */ /** @defgroup RNG_Exported_Functions_Group3 Peripheral State functions * @{ */ HAL_RNG_StateTypeDef HAL_RNG_GetState(RNG_HandleTypeDef *hrng); /** * @} */ /** * @} */ /* Private types -------------------------------------------------------------*/ /** @defgroup RNG_Private_Types RNG Private Types * @{ */ /** * @} */ /* Private defines -----------------------------------------------------------*/ /** @defgroup RNG_Private_Defines RNG Private Defines * @{ */ /** * @} */ /* Private variables ---------------------------------------------------------*/ /** @defgroup RNG_Private_Variables RNG Private Variables * @{ */ /** * @} */ /* Private constants ---------------------------------------------------------*/ /** @defgroup RNG_Private_Constants RNG Private Constants * @{ */ /** * @} */ /* Private macros ------------------------------------------------------------*/ /** @defgroup RNG_Private_Macros RNG Private Macros * @{ */ #define IS_RNG_IT(IT) (((IT) == RNG_IT_CEI) || \ ((IT) == RNG_IT_SEI)) #define IS_RNG_FLAG(FLAG) (((FLAG) == RNG_FLAG_DRDY) || \ ((FLAG) == RNG_FLAG_CECS) || \ ((FLAG) == RNG_FLAG_SECS)) /** * @} */ /* Private functions prototypes ----------------------------------------------*/ /** @defgroup RNG_Private_Functions_Prototypes RNG Private Functions Prototypes * @{ */ /** * @} */ /* Private functions ---------------------------------------------------------*/ /** @defgroup RNG_Private_Functions RNG Private Functions * @{ */ /** * @} */ /** * @} */ /** * @} */ #endif /* STM32F405xx || STM32F415xx || STM32F407xx || STM32F417xx || STM32F427xx || STM32F437xx ||\ STM32F429xx || STM32F439xx || STM32F410xx || STM32F469xx || STM32F479xx */ #ifdef __cplusplus } #endif #endif /* __STM32F4xx_HAL_RNG_H */ /************************ (C) COPYRIGHT STMicroelectronics *****END OF FILE****/ ================================================ FILE: Zelig/mbed/TARGET_NUCLEO_F401RE/stm32f4xx_hal_rtc.h ================================================ /** ****************************************************************************** * @file stm32f4xx_hal_rtc.h * @author MCD Application Team * @version V1.4.1 * @date 09-October-2015 * @brief Header file of RTC HAL module. ****************************************************************************** * @attention * *

© COPYRIGHT(c) 2015 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. * ****************************************************************************** */ /* Define to prevent recursive inclusion -------------------------------------*/ #ifndef __STM32F4xx_HAL_RTC_H #define __STM32F4xx_HAL_RTC_H #ifdef __cplusplus extern "C" { #endif /* Includes ------------------------------------------------------------------*/ #include "stm32f4xx_hal_def.h" /** @addtogroup STM32F4xx_HAL_Driver * @{ */ /** @addtogroup RTC * @{ */ /* Exported types ------------------------------------------------------------*/ /** @defgroup RTC_Exported_Types RTC Exported Types * @{ */ /** * @brief HAL State structures definition */ typedef enum { HAL_RTC_STATE_RESET = 0x00, /*!< RTC not yet initialized or disabled */ HAL_RTC_STATE_READY = 0x01, /*!< RTC initialized and ready for use */ HAL_RTC_STATE_BUSY = 0x02, /*!< RTC process is ongoing */ HAL_RTC_STATE_TIMEOUT = 0x03, /*!< RTC timeout state */ HAL_RTC_STATE_ERROR = 0x04 /*!< RTC error state */ }HAL_RTCStateTypeDef; /** * @brief RTC Configuration Structure definition */ typedef struct { uint32_t HourFormat; /*!< Specifies the RTC Hour Format. This parameter can be a value of @ref RTC_Hour_Formats */ uint32_t AsynchPrediv; /*!< Specifies the RTC Asynchronous Predivider value. This parameter must be a number between Min_Data = 0x00 and Max_Data = 0x7F */ uint32_t SynchPrediv; /*!< Specifies the RTC Synchronous Predivider value. This parameter must be a number between Min_Data = 0x00 and Max_Data = 0x7FFF */ uint32_t OutPut; /*!< Specifies which signal will be routed to the RTC output. This parameter can be a value of @ref RTC_Output_selection_Definitions */ uint32_t OutPutPolarity; /*!< Specifies the polarity of the output signal. This parameter can be a value of @ref RTC_Output_Polarity_Definitions */ uint32_t OutPutType; /*!< Specifies the RTC Output Pin mode. This parameter can be a value of @ref RTC_Output_Type_ALARM_OUT */ }RTC_InitTypeDef; /** * @brief RTC Time structure definition */ typedef struct { uint8_t Hours; /*!< Specifies the RTC Time Hour. This parameter must be a number between Min_Data = 0 and Max_Data = 12 if the RTC_HourFormat_12 is selected. This parameter must be a number between Min_Data = 0 and Max_Data = 23 if the RTC_HourFormat_24 is selected */ uint8_t Minutes; /*!< Specifies the RTC Time Minutes. This parameter must be a number between Min_Data = 0 and Max_Data = 59 */ uint8_t Seconds; /*!< Specifies the RTC Time Seconds. This parameter must be a number between Min_Data = 0 and Max_Data = 59 */ uint8_t TimeFormat; /*!< Specifies the RTC AM/PM Time. This parameter can be a value of @ref RTC_AM_PM_Definitions */ uint32_t SubSeconds; /*!< Specifies the RTC_SSR RTC Sub Second register content. This parameter corresponds to a time unit range between [0-1] Second with [1 Sec / SecondFraction +1] granularity */ uint32_t SecondFraction; /*!< Specifies the range or granularity of Sub Second register content corresponding to Synchronous pre-scaler factor value (PREDIV_S) This parameter corresponds to a time unit range between [0-1] Second with [1 Sec / SecondFraction +1] granularity. This field will be used only by HAL_RTC_GetTime function */ uint32_t DayLightSaving; /*!< Specifies DayLight Save Operation. This parameter can be a value of @ref RTC_DayLightSaving_Definitions */ uint32_t StoreOperation; /*!< Specifies RTC_StoreOperation value to be written in the BCK bit in CR register to store the operation. This parameter can be a value of @ref RTC_StoreOperation_Definitions */ }RTC_TimeTypeDef; /** * @brief RTC Date structure definition */ typedef struct { uint8_t WeekDay; /*!< Specifies the RTC Date WeekDay. This parameter can be a value of @ref RTC_WeekDay_Definitions */ uint8_t Month; /*!< Specifies the RTC Date Month (in BCD format). This parameter can be a value of @ref RTC_Month_Date_Definitions */ uint8_t Date; /*!< Specifies the RTC Date. This parameter must be a number between Min_Data = 1 and Max_Data = 31 */ uint8_t Year; /*!< Specifies the RTC Date Year. This parameter must be a number between Min_Data = 0 and Max_Data = 99 */ }RTC_DateTypeDef; /** * @brief RTC Alarm structure definition */ typedef struct { RTC_TimeTypeDef AlarmTime; /*!< Specifies the RTC Alarm Time members */ uint32_t AlarmMask; /*!< Specifies the RTC Alarm Masks. This parameter can be a value of @ref RTC_AlarmMask_Definitions */ uint32_t AlarmSubSecondMask; /*!< Specifies the RTC Alarm SubSeconds Masks. This parameter can be a value of @ref RTC_Alarm_Sub_Seconds_Masks_Definitions */ uint32_t AlarmDateWeekDaySel; /*!< Specifies the RTC Alarm is on Date or WeekDay. This parameter can be a value of @ref RTC_AlarmDateWeekDay_Definitions */ uint8_t AlarmDateWeekDay; /*!< Specifies the RTC Alarm Date/WeekDay. If the Alarm Date is selected, this parameter must be set to a value in the 1-31 range. If the Alarm WeekDay is selected, this parameter can be a value of @ref RTC_WeekDay_Definitions */ uint32_t Alarm; /*!< Specifies the alarm . This parameter can be a value of @ref RTC_Alarms_Definitions */ }RTC_AlarmTypeDef; /** * @brief RTC Handle Structure definition */ typedef struct { RTC_TypeDef *Instance; /*!< Register base address */ RTC_InitTypeDef Init; /*!< RTC required parameters */ HAL_LockTypeDef Lock; /*!< RTC locking object */ __IO HAL_RTCStateTypeDef State; /*!< Time communication state */ }RTC_HandleTypeDef; /** * @} */ /* Exported constants --------------------------------------------------------*/ /** @defgroup RTC_Exported_Constants RTC Exported Constants * @{ */ /** @defgroup RTC_Hour_Formats RTC Hour Formats * @{ */ #define RTC_HOURFORMAT_24 ((uint32_t)0x00000000) #define RTC_HOURFORMAT_12 ((uint32_t)0x00000040) /** * @} */ /** @defgroup RTC_Output_selection_Definitions RTC Output Selection Definitions * @{ */ #define RTC_OUTPUT_DISABLE ((uint32_t)0x00000000) #define RTC_OUTPUT_ALARMA ((uint32_t)0x00200000) #define RTC_OUTPUT_ALARMB ((uint32_t)0x00400000) #define RTC_OUTPUT_WAKEUP ((uint32_t)0x00600000) /** * @} */ /** @defgroup RTC_Output_Polarity_Definitions RTC Output Polarity Definitions * @{ */ #define RTC_OUTPUT_POLARITY_HIGH ((uint32_t)0x00000000) #define RTC_OUTPUT_POLARITY_LOW ((uint32_t)0x00100000) /** * @} */ /** @defgroup RTC_Output_Type_ALARM_OUT RTC Output Type ALARM OUT * @{ */ #define RTC_OUTPUT_TYPE_OPENDRAIN ((uint32_t)0x00000000) #define RTC_OUTPUT_TYPE_PUSHPULL ((uint32_t)0x00040000) /** * @} */ /** @defgroup RTC_AM_PM_Definitions RTC AM PM Definitions * @{ */ #define RTC_HOURFORMAT12_AM ((uint8_t)0x00) #define RTC_HOURFORMAT12_PM ((uint8_t)0x40) /** * @} */ /** @defgroup RTC_DayLightSaving_Definitions RTC DayLight Saving Definitions * @{ */ #define RTC_DAYLIGHTSAVING_SUB1H ((uint32_t)0x00020000) #define RTC_DAYLIGHTSAVING_ADD1H ((uint32_t)0x00010000) #define RTC_DAYLIGHTSAVING_NONE ((uint32_t)0x00000000) /** * @} */ /** @defgroup RTC_StoreOperation_Definitions RTC Store Operation Definitions * @{ */ #define RTC_STOREOPERATION_RESET ((uint32_t)0x00000000) #define RTC_STOREOPERATION_SET ((uint32_t)0x00040000) /** * @} */ /** @defgroup RTC_Input_parameter_format_definitions RTC Input Parameter Format Definitions * @{ */ #define RTC_FORMAT_BIN ((uint32_t)0x000000000) #define RTC_FORMAT_BCD ((uint32_t)0x000000001) /** * @} */ /** @defgroup RTC_Month_Date_Definitions RTC Month Date Definitions * @{ */ /* Coded in BCD format */ #define RTC_MONTH_JANUARY ((uint8_t)0x01) #define RTC_MONTH_FEBRUARY ((uint8_t)0x02) #define RTC_MONTH_MARCH ((uint8_t)0x03) #define RTC_MONTH_APRIL ((uint8_t)0x04) #define RTC_MONTH_MAY ((uint8_t)0x05) #define RTC_MONTH_JUNE ((uint8_t)0x06) #define RTC_MONTH_JULY ((uint8_t)0x07) #define RTC_MONTH_AUGUST ((uint8_t)0x08) #define RTC_MONTH_SEPTEMBER ((uint8_t)0x09) #define RTC_MONTH_OCTOBER ((uint8_t)0x10) #define RTC_MONTH_NOVEMBER ((uint8_t)0x11) #define RTC_MONTH_DECEMBER ((uint8_t)0x12) /** * @} */ /** @defgroup RTC_WeekDay_Definitions RTC WeekDay Definitions * @{ */ #define RTC_WEEKDAY_MONDAY ((uint8_t)0x01) #define RTC_WEEKDAY_TUESDAY ((uint8_t)0x02) #define RTC_WEEKDAY_WEDNESDAY ((uint8_t)0x03) #define RTC_WEEKDAY_THURSDAY ((uint8_t)0x04) #define RTC_WEEKDAY_FRIDAY ((uint8_t)0x05) #define RTC_WEEKDAY_SATURDAY ((uint8_t)0x06) #define RTC_WEEKDAY_SUNDAY ((uint8_t)0x07) /** * @} */ /** @defgroup RTC_AlarmDateWeekDay_Definitions RTC Alarm Date WeekDay Definitions * @{ */ #define RTC_ALARMDATEWEEKDAYSEL_DATE ((uint32_t)0x00000000) #define RTC_ALARMDATEWEEKDAYSEL_WEEKDAY ((uint32_t)0x40000000) /** * @} */ /** @defgroup RTC_AlarmMask_Definitions RTC Alarm Mask Definitions * @{ */ #define RTC_ALARMMASK_NONE ((uint32_t)0x00000000) #define RTC_ALARMMASK_DATEWEEKDAY RTC_ALRMAR_MSK4 #define RTC_ALARMMASK_HOURS RTC_ALRMAR_MSK3 #define RTC_ALARMMASK_MINUTES RTC_ALRMAR_MSK2 #define RTC_ALARMMASK_SECONDS RTC_ALRMAR_MSK1 #define RTC_ALARMMASK_ALL ((uint32_t)0x80808080) /** * @} */ /** @defgroup RTC_Alarms_Definitions RTC Alarms Definitions * @{ */ #define RTC_ALARM_A RTC_CR_ALRAE #define RTC_ALARM_B RTC_CR_ALRBE /** * @} */ /** @defgroup RTC_Alarm_Sub_Seconds_Masks_Definitions RTC Alarm Sub Seconds Masks Definitions * @{ */ #define RTC_ALARMSUBSECONDMASK_ALL ((uint32_t)0x00000000) /*!< All Alarm SS fields are masked. There is no comparison on sub seconds for Alarm */ #define RTC_ALARMSUBSECONDMASK_SS14_1 ((uint32_t)0x01000000) /*!< SS[14:1] are don't care in Alarm comparison. Only SS[0] is compared. */ #define RTC_ALARMSUBSECONDMASK_SS14_2 ((uint32_t)0x02000000) /*!< SS[14:2] are don't care in Alarm comparison. Only SS[1:0] are compared */ #define RTC_ALARMSUBSECONDMASK_SS14_3 ((uint32_t)0x03000000) /*!< SS[14:3] are don't care in Alarm comparison. Only SS[2:0] are compared */ #define RTC_ALARMSUBSECONDMASK_SS14_4 ((uint32_t)0x04000000) /*!< SS[14:4] are don't care in Alarm comparison. Only SS[3:0] are compared */ #define RTC_ALARMSUBSECONDMASK_SS14_5 ((uint32_t)0x05000000) /*!< SS[14:5] are don't care in Alarm comparison. Only SS[4:0] are compared */ #define RTC_ALARMSUBSECONDMASK_SS14_6 ((uint32_t)0x06000000) /*!< SS[14:6] are don't care in Alarm comparison. Only SS[5:0] are compared */ #define RTC_ALARMSUBSECONDMASK_SS14_7 ((uint32_t)0x07000000) /*!< SS[14:7] are don't care in Alarm comparison. Only SS[6:0] are compared */ #define RTC_ALARMSUBSECONDMASK_SS14_8 ((uint32_t)0x08000000) /*!< SS[14:8] are don't care in Alarm comparison. Only SS[7:0] are compared */ #define RTC_ALARMSUBSECONDMASK_SS14_9 ((uint32_t)0x09000000) /*!< SS[14:9] are don't care in Alarm comparison. Only SS[8:0] are compared */ #define RTC_ALARMSUBSECONDMASK_SS14_10 ((uint32_t)0x0A000000) /*!< SS[14:10] are don't care in Alarm comparison. Only SS[9:0] are compared */ #define RTC_ALARMSUBSECONDMASK_SS14_11 ((uint32_t)0x0B000000) /*!< SS[14:11] are don't care in Alarm comparison. Only SS[10:0] are compared */ #define RTC_ALARMSUBSECONDMASK_SS14_12 ((uint32_t)0x0C000000) /*!< SS[14:12] are don't care in Alarm comparison.Only SS[11:0] are compared */ #define RTC_ALARMSUBSECONDMASK_SS14_13 ((uint32_t)0x0D000000) /*!< SS[14:13] are don't care in Alarm comparison. Only SS[12:0] are compared */ #define RTC_ALARMSUBSECONDMASK_SS14 ((uint32_t)0x0E000000) /*!< SS[14] is don't care in Alarm comparison.Only SS[13:0] are compared */ #define RTC_ALARMSUBSECONDMASK_NONE ((uint32_t)0x0F000000) /*!< SS[14:0] are compared and must match to activate alarm. */ /** * @} */ /** @defgroup RTC_Interrupts_Definitions RTC Interrupts Definitions * @{ */ #define RTC_IT_TS ((uint32_t)0x00008000) #define RTC_IT_WUT ((uint32_t)0x00004000) #define RTC_IT_ALRB ((uint32_t)0x00002000) #define RTC_IT_ALRA ((uint32_t)0x00001000) #define RTC_IT_TAMP ((uint32_t)0x00000004) /* Used only to Enable the Tamper Interrupt */ #define RTC_IT_TAMP1 ((uint32_t)0x00020000) #define RTC_IT_TAMP2 ((uint32_t)0x00040000) /** * @} */ /** @defgroup RTC_Flags_Definitions RTC Flags Definitions * @{ */ #define RTC_FLAG_RECALPF ((uint32_t)0x00010000) #define RTC_FLAG_TAMP2F ((uint32_t)0x00004000) #define RTC_FLAG_TAMP1F ((uint32_t)0x00002000) #define RTC_FLAG_TSOVF ((uint32_t)0x00001000) #define RTC_FLAG_TSF ((uint32_t)0x00000800) #define RTC_FLAG_WUTF ((uint32_t)0x00000400) #define RTC_FLAG_ALRBF ((uint32_t)0x00000200) #define RTC_FLAG_ALRAF ((uint32_t)0x00000100) #define RTC_FLAG_INITF ((uint32_t)0x00000040) #define RTC_FLAG_RSF ((uint32_t)0x00000020) #define RTC_FLAG_INITS ((uint32_t)0x00000010) #define RTC_FLAG_SHPF ((uint32_t)0x00000008) #define RTC_FLAG_WUTWF ((uint32_t)0x00000004) #define RTC_FLAG_ALRBWF ((uint32_t)0x00000002) #define RTC_FLAG_ALRAWF ((uint32_t)0x00000001) /** * @} */ /** * @} */ /* Exported macro ------------------------------------------------------------*/ /** @defgroup RTC_Exported_Macros RTC Exported Macros * @{ */ /** @brief Reset RTC handle state * @param __HANDLE__: specifies the RTC handle. * @retval None */ #define __HAL_RTC_RESET_HANDLE_STATE(__HANDLE__) ((__HANDLE__)->State = HAL_RTC_STATE_RESET) /** * @brief Disable the write protection for RTC registers. * @param __HANDLE__: specifies the RTC handle. * @retval None */ #define __HAL_RTC_WRITEPROTECTION_DISABLE(__HANDLE__) \ do{ \ (__HANDLE__)->Instance->WPR = 0xCA; \ (__HANDLE__)->Instance->WPR = 0x53; \ } while(0) /** * @brief Enable the write protection for RTC registers. * @param __HANDLE__: specifies the RTC handle. * @retval None */ #define __HAL_RTC_WRITEPROTECTION_ENABLE(__HANDLE__) \ do{ \ (__HANDLE__)->Instance->WPR = 0xFF; \ } while(0) /** * @brief Enable the RTC ALARMA peripheral. * @param __HANDLE__: specifies the RTC handle. * @retval None */ #define __HAL_RTC_ALARMA_ENABLE(__HANDLE__) ((__HANDLE__)->Instance->CR |= (RTC_CR_ALRAE)) /** * @brief Disable the RTC ALARMA peripheral. * @param __HANDLE__: specifies the RTC handle. * @retval None */ #define __HAL_RTC_ALARMA_DISABLE(__HANDLE__) ((__HANDLE__)->Instance->CR &= ~(RTC_CR_ALRAE)) /** * @brief Enable the RTC ALARMB peripheral. * @param __HANDLE__: specifies the RTC handle. * @retval None */ #define __HAL_RTC_ALARMB_ENABLE(__HANDLE__) ((__HANDLE__)->Instance->CR |= (RTC_CR_ALRBE)) /** * @brief Disable the RTC ALARMB peripheral. * @param __HANDLE__: specifies the RTC handle. * @retval None */ #define __HAL_RTC_ALARMB_DISABLE(__HANDLE__) ((__HANDLE__)->Instance->CR &= ~(RTC_CR_ALRBE)) /** * @brief Enable the RTC Alarm interrupt. * @param __HANDLE__: specifies the RTC handle. * @param __INTERRUPT__: specifies the RTC Alarm interrupt sources to be enabled or disabled. * This parameter can be any combination of the following values: * @arg RTC_IT_ALRA: Alarm A interrupt * @arg RTC_IT_ALRB: Alarm B interrupt * @retval None */ #define __HAL_RTC_ALARM_ENABLE_IT(__HANDLE__, __INTERRUPT__) ((__HANDLE__)->Instance->CR |= (__INTERRUPT__)) /** * @brief Disable the RTC Alarm interrupt. * @param __HANDLE__: specifies the RTC handle. * @param __INTERRUPT__: specifies the RTC Alarm interrupt sources to be enabled or disabled. * This parameter can be any combination of the following values: * @arg RTC_IT_ALRA: Alarm A interrupt * @arg RTC_IT_ALRB: Alarm B interrupt * @retval None */ #define __HAL_RTC_ALARM_DISABLE_IT(__HANDLE__, __INTERRUPT__) ((__HANDLE__)->Instance->CR &= ~(__INTERRUPT__)) /** * @brief Check whether the specified RTC Alarm interrupt has occurred or not. * @param __HANDLE__: specifies the RTC handle. * @param __INTERRUPT__: specifies the RTC Alarm interrupt to check. * This parameter can be: * @arg RTC_IT_ALRA: Alarm A interrupt * @arg RTC_IT_ALRB: Alarm B interrupt * @retval None */ #define __HAL_RTC_ALARM_GET_IT(__HANDLE__, __INTERRUPT__) (((((__HANDLE__)->Instance->ISR)& ((__INTERRUPT__)>> 4)) != RESET)? SET : RESET) /** * @brief Get the selected RTC Alarm's flag status. * @param __HANDLE__: specifies the RTC handle. * @param __FLAG__: specifies the RTC Alarm Flag to check. * This parameter can be: * @arg RTC_FLAG_ALRAF * @arg RTC_FLAG_ALRBF * @arg RTC_FLAG_ALRAWF * @arg RTC_FLAG_ALRBWF * @retval None */ #define __HAL_RTC_ALARM_GET_FLAG(__HANDLE__, __FLAG__) (((((__HANDLE__)->Instance->ISR) & (__FLAG__)) != RESET)? SET : RESET) /** * @brief Clear the RTC Alarm's pending flags. * @param __HANDLE__: specifies the RTC handle. * @param __FLAG__: specifies the RTC Alarm Flag sources to be enabled or disabled. * This parameter can be: * @arg RTC_FLAG_ALRAF * @arg RTC_FLAG_ALRBF * @retval None */ #define __HAL_RTC_ALARM_CLEAR_FLAG(__HANDLE__, __FLAG__) ((__HANDLE__)->Instance->ISR) = (~((__FLAG__) | RTC_ISR_INIT)|((__HANDLE__)->Instance->ISR & RTC_ISR_INIT)) /** * @brief Check whether the specified RTC Alarm interrupt has been enabled or not. * @param __HANDLE__: specifies the RTC handle. * @param __INTERRUPT__: specifies the RTC Alarm interrupt sources to check. * This parameter can be: * @arg RTC_IT_ALRA: Alarm A interrupt * @arg RTC_IT_ALRB: Alarm B interrupt * @retval None */ #define __HAL_RTC_ALARM_GET_IT_SOURCE(__HANDLE__, __INTERRUPT__) (((((__HANDLE__)->Instance->CR) & (__INTERRUPT__)) != RESET) ? SET : RESET) /** * @brief Enable interrupt on the RTC Alarm associated Exti line. * @retval None */ #define __HAL_RTC_ALARM_EXTI_ENABLE_IT() (EXTI->IMR |= RTC_EXTI_LINE_ALARM_EVENT) /** * @brief Disable interrupt on the RTC Alarm associated Exti line. * @retval None */ #define __HAL_RTC_ALARM_EXTI_DISABLE_IT() (EXTI->IMR &= ~(RTC_EXTI_LINE_ALARM_EVENT)) /** * @brief Enable event on the RTC Alarm associated Exti line. * @retval None. */ #define __HAL_RTC_ALARM_EXTI_ENABLE_EVENT() (EXTI->EMR |= RTC_EXTI_LINE_ALARM_EVENT) /** * @brief Disable event on the RTC Alarm associated Exti line. * @retval None. */ #define __HAL_RTC_ALARM_EXTI_DISABLE_EVENT() (EXTI->EMR &= ~(RTC_EXTI_LINE_ALARM_EVENT)) /** * @brief Enable falling edge trigger on the RTC Alarm associated Exti line. * @retval None. */ #define __HAL_RTC_ALARM_EXTI_ENABLE_FALLING_EDGE() (EXTI->FTSR |= RTC_EXTI_LINE_ALARM_EVENT) /** * @brief Disable falling edge trigger on the RTC Alarm associated Exti line. * @retval None. */ #define __HAL_RTC_ALARM_EXTI_DISABLE_FALLING_EDGE() (EXTI->FTSR &= ~(RTC_EXTI_LINE_ALARM_EVENT)) /** * @brief Enable rising edge trigger on the RTC Alarm associated Exti line. * @retval None. */ #define __HAL_RTC_ALARM_EXTI_ENABLE_RISING_EDGE() (EXTI->RTSR |= RTC_EXTI_LINE_ALARM_EVENT) /** * @brief Disable rising edge trigger on the RTC Alarm associated Exti line. * @retval None. */ #define __HAL_RTC_ALARM_EXTI_DISABLE_RISING_EDGE() (EXTI->RTSR &= ~(RTC_EXTI_LINE_ALARM_EVENT)) /** * @brief Enable rising & falling edge trigger on the RTC Alarm associated Exti line. * @retval None. */ #define __HAL_RTC_ALARM_EXTI_ENABLE_RISING_FALLING_EDGE() __HAL_RTC_ALARM_EXTI_ENABLE_RISING_EDGE();__HAL_RTC_ALARM_EXTI_ENABLE_FALLING_EDGE(); /** * @brief Disable rising & falling edge trigger on the RTC Alarm associated Exti line. * @retval None. */ #define __HAL_RTC_ALARM_EXTI_DISABLE_RISING_FALLING_EDGE() __HAL_RTC_ALARM_EXTI_DISABLE_RISING_EDGE();__HAL_RTC_ALARM_EXTI_DISABLE_FALLING_EDGE(); /** * @brief Check whether the RTC Alarm associated Exti line interrupt flag is set or not. * @retval Line Status. */ #define __HAL_RTC_ALARM_EXTI_GET_FLAG() (EXTI->PR & RTC_EXTI_LINE_ALARM_EVENT) /** * @brief Clear the RTC Alarm associated Exti line flag. * @retval None. */ #define __HAL_RTC_ALARM_EXTI_CLEAR_FLAG() (EXTI->PR = RTC_EXTI_LINE_ALARM_EVENT) /** * @brief Generate a Software interrupt on RTC Alarm associated Exti line. * @retval None. */ #define __HAL_RTC_ALARM_EXTI_GENERATE_SWIT() (EXTI->SWIER |= RTC_EXTI_LINE_ALARM_EVENT) /** * @} */ /* Include RTC HAL Extension module */ #include "stm32f4xx_hal_rtc_ex.h" /* Exported functions --------------------------------------------------------*/ /** @addtogroup RTC_Exported_Functions * @{ */ /** @addtogroup RTC_Exported_Functions_Group1 * @{ */ /* Initialization and de-initialization functions ****************************/ HAL_StatusTypeDef HAL_RTC_Init(RTC_HandleTypeDef *hrtc); HAL_StatusTypeDef HAL_RTC_DeInit(RTC_HandleTypeDef *hrtc); void HAL_RTC_MspInit(RTC_HandleTypeDef *hrtc); void HAL_RTC_MspDeInit(RTC_HandleTypeDef *hrtc); /** * @} */ /** @addtogroup RTC_Exported_Functions_Group2 * @{ */ /* RTC Time and Date functions ************************************************/ HAL_StatusTypeDef HAL_RTC_SetTime(RTC_HandleTypeDef *hrtc, RTC_TimeTypeDef *sTime, uint32_t Format); HAL_StatusTypeDef HAL_RTC_GetTime(RTC_HandleTypeDef *hrtc, RTC_TimeTypeDef *sTime, uint32_t Format); HAL_StatusTypeDef HAL_RTC_SetDate(RTC_HandleTypeDef *hrtc, RTC_DateTypeDef *sDate, uint32_t Format); HAL_StatusTypeDef HAL_RTC_GetDate(RTC_HandleTypeDef *hrtc, RTC_DateTypeDef *sDate, uint32_t Format); /** * @} */ /** @addtogroup RTC_Exported_Functions_Group3 * @{ */ /* RTC Alarm functions ********************************************************/ HAL_StatusTypeDef HAL_RTC_SetAlarm(RTC_HandleTypeDef *hrtc, RTC_AlarmTypeDef *sAlarm, uint32_t Format); HAL_StatusTypeDef HAL_RTC_SetAlarm_IT(RTC_HandleTypeDef *hrtc, RTC_AlarmTypeDef *sAlarm, uint32_t Format); HAL_StatusTypeDef HAL_RTC_DeactivateAlarm(RTC_HandleTypeDef *hrtc, uint32_t Alarm); HAL_StatusTypeDef HAL_RTC_GetAlarm(RTC_HandleTypeDef *hrtc, RTC_AlarmTypeDef *sAlarm, uint32_t Alarm, uint32_t Format); void HAL_RTC_AlarmIRQHandler(RTC_HandleTypeDef *hrtc); HAL_StatusTypeDef HAL_RTC_PollForAlarmAEvent(RTC_HandleTypeDef *hrtc, uint32_t Timeout); void HAL_RTC_AlarmAEventCallback(RTC_HandleTypeDef *hrtc); /** * @} */ /** @addtogroup RTC_Exported_Functions_Group4 * @{ */ /* Peripheral Control functions ***********************************************/ HAL_StatusTypeDef HAL_RTC_WaitForSynchro(RTC_HandleTypeDef* hrtc); /** * @} */ /** @addtogroup RTC_Exported_Functions_Group5 * @{ */ /* Peripheral State functions *************************************************/ HAL_RTCStateTypeDef HAL_RTC_GetState(RTC_HandleTypeDef *hrtc); /** * @} */ /** * @} */ /* Private types -------------------------------------------------------------*/ /* Private variables ---------------------------------------------------------*/ /* Private constants ---------------------------------------------------------*/ /** @defgroup RTC_Private_Constants RTC Private Constants * @{ */ /* Masks Definition */ #define RTC_TR_RESERVED_MASK ((uint32_t)0x007F7F7F) #define RTC_DR_RESERVED_MASK ((uint32_t)0x00FFFF3F) #define RTC_INIT_MASK ((uint32_t)0xFFFFFFFF) #define RTC_RSF_MASK ((uint32_t)0xFFFFFF5F) #define RTC_FLAGS_MASK ((uint32_t)(RTC_FLAG_TSOVF | RTC_FLAG_TSF | RTC_FLAG_WUTF | \ RTC_FLAG_ALRBF | RTC_FLAG_ALRAF | RTC_FLAG_INITF | \ RTC_FLAG_RSF | RTC_FLAG_INITS | RTC_FLAG_WUTWF | \ RTC_FLAG_ALRBWF | RTC_FLAG_ALRAWF | RTC_FLAG_TAMP1F | \ RTC_FLAG_RECALPF | RTC_FLAG_SHPF)) #define RTC_TIMEOUT_VALUE 1000 #define RTC_EXTI_LINE_ALARM_EVENT ((uint32_t)EXTI_IMR_MR17) /*!< External interrupt line 17 Connected to the RTC Alarm event */ /** * @} */ /* Private macros ------------------------------------------------------------*/ /** @defgroup RTC_Private_Macros RTC Private Macros * @{ */ /** @defgroup RTC_IS_RTC_Definitions RTC Private macros to check input parameters * @{ */ #define IS_RTC_HOUR_FORMAT(FORMAT) (((FORMAT) == RTC_HOURFORMAT_12) || \ ((FORMAT) == RTC_HOURFORMAT_24)) #define IS_RTC_OUTPUT(OUTPUT) (((OUTPUT) == RTC_OUTPUT_DISABLE) || \ ((OUTPUT) == RTC_OUTPUT_ALARMA) || \ ((OUTPUT) == RTC_OUTPUT_ALARMB) || \ ((OUTPUT) == RTC_OUTPUT_WAKEUP)) #define IS_RTC_OUTPUT_POL(POL) (((POL) == RTC_OUTPUT_POLARITY_HIGH) || \ ((POL) == RTC_OUTPUT_POLARITY_LOW)) #define IS_RTC_OUTPUT_TYPE(TYPE) (((TYPE) == RTC_OUTPUT_TYPE_OPENDRAIN) || \ ((TYPE) == RTC_OUTPUT_TYPE_PUSHPULL)) #define IS_RTC_HOUR12(HOUR) (((HOUR) > (uint32_t)0) && ((HOUR) <= (uint32_t)12)) #define IS_RTC_HOUR24(HOUR) ((HOUR) <= (uint32_t)23) #define IS_RTC_ASYNCH_PREDIV(PREDIV) ((PREDIV) <= (uint32_t)0x7F) #define IS_RTC_SYNCH_PREDIV(PREDIV) ((PREDIV) <= (uint32_t)0x7FFF) #define IS_RTC_MINUTES(MINUTES) ((MINUTES) <= (uint32_t)59) #define IS_RTC_SECONDS(SECONDS) ((SECONDS) <= (uint32_t)59) #define IS_RTC_HOURFORMAT12(PM) (((PM) == RTC_HOURFORMAT12_AM) || ((PM) == RTC_HOURFORMAT12_PM)) #define IS_RTC_DAYLIGHT_SAVING(SAVE) (((SAVE) == RTC_DAYLIGHTSAVING_SUB1H) || \ ((SAVE) == RTC_DAYLIGHTSAVING_ADD1H) || \ ((SAVE) == RTC_DAYLIGHTSAVING_NONE)) #define IS_RTC_STORE_OPERATION(OPERATION) (((OPERATION) == RTC_STOREOPERATION_RESET) || \ ((OPERATION) == RTC_STOREOPERATION_SET)) #define IS_RTC_FORMAT(FORMAT) (((FORMAT) == RTC_FORMAT_BIN) || ((FORMAT) == RTC_FORMAT_BCD)) #define IS_RTC_YEAR(YEAR) ((YEAR) <= (uint32_t)99) #define IS_RTC_MONTH(MONTH) (((MONTH) >= (uint32_t)1) && ((MONTH) <= (uint32_t)12)) #define IS_RTC_DATE(DATE) (((DATE) >= (uint32_t)1) && ((DATE) <= (uint32_t)31)) #define IS_RTC_WEEKDAY(WEEKDAY) (((WEEKDAY) == RTC_WEEKDAY_MONDAY) || \ ((WEEKDAY) == RTC_WEEKDAY_TUESDAY) || \ ((WEEKDAY) == RTC_WEEKDAY_WEDNESDAY) || \ ((WEEKDAY) == RTC_WEEKDAY_THURSDAY) || \ ((WEEKDAY) == RTC_WEEKDAY_FRIDAY) || \ ((WEEKDAY) == RTC_WEEKDAY_SATURDAY) || \ ((WEEKDAY) == RTC_WEEKDAY_SUNDAY)) #define IS_RTC_ALARM_DATE_WEEKDAY_DATE(DATE) (((DATE) >(uint32_t) 0) && ((DATE) <= (uint32_t)31)) #define IS_RTC_ALARM_DATE_WEEKDAY_WEEKDAY(WEEKDAY) (((WEEKDAY) == RTC_WEEKDAY_MONDAY) || \ ((WEEKDAY) == RTC_WEEKDAY_TUESDAY) || \ ((WEEKDAY) == RTC_WEEKDAY_WEDNESDAY) || \ ((WEEKDAY) == RTC_WEEKDAY_THURSDAY) || \ ((WEEKDAY) == RTC_WEEKDAY_FRIDAY) || \ ((WEEKDAY) == RTC_WEEKDAY_SATURDAY) || \ ((WEEKDAY) == RTC_WEEKDAY_SUNDAY)) #define IS_RTC_ALARM_DATE_WEEKDAY_SEL(SEL) (((SEL) == RTC_ALARMDATEWEEKDAYSEL_DATE) || \ ((SEL) == RTC_ALARMDATEWEEKDAYSEL_WEEKDAY)) #define IS_RTC_ALARM_MASK(MASK) (((MASK) & 0x7F7F7F7F) == (uint32_t)RESET) #define IS_RTC_ALARM(ALARM) (((ALARM) == RTC_ALARM_A) || ((ALARM) == RTC_ALARM_B)) #define IS_RTC_ALARM_SUB_SECOND_VALUE(VALUE) ((VALUE) <= (uint32_t)0x00007FFF) #define IS_RTC_ALARM_SUB_SECOND_MASK(MASK) (((MASK) == RTC_ALARMSUBSECONDMASK_ALL) || \ ((MASK) == RTC_ALARMSUBSECONDMASK_SS14_1) || \ ((MASK) == RTC_ALARMSUBSECONDMASK_SS14_2) || \ ((MASK) == RTC_ALARMSUBSECONDMASK_SS14_3) || \ ((MASK) == RTC_ALARMSUBSECONDMASK_SS14_4) || \ ((MASK) == RTC_ALARMSUBSECONDMASK_SS14_5) || \ ((MASK) == RTC_ALARMSUBSECONDMASK_SS14_6) || \ ((MASK) == RTC_ALARMSUBSECONDMASK_SS14_7) || \ ((MASK) == RTC_ALARMSUBSECONDMASK_SS14_8) || \ ((MASK) == RTC_ALARMSUBSECONDMASK_SS14_9) || \ ((MASK) == RTC_ALARMSUBSECONDMASK_SS14_10) || \ ((MASK) == RTC_ALARMSUBSECONDMASK_SS14_11) || \ ((MASK) == RTC_ALARMSUBSECONDMASK_SS14_12) || \ ((MASK) == RTC_ALARMSUBSECONDMASK_SS14_13) || \ ((MASK) == RTC_ALARMSUBSECONDMASK_SS14) || \ ((MASK) == RTC_ALARMSUBSECONDMASK_NONE)) /** * @} */ /** * @} */ /* Private functions ---------------------------------------------------------*/ /** @defgroup RTC_Private_Functions RTC Private Functions * @{ */ HAL_StatusTypeDef RTC_EnterInitMode(RTC_HandleTypeDef* hrtc); uint8_t RTC_ByteToBcd2(uint8_t Value); uint8_t RTC_Bcd2ToByte(uint8_t Value); /** * @} */ /** * @} */ /** * @} */ #ifdef __cplusplus } #endif #endif /* __STM32F4xx_HAL_RTC_H */ /************************ (C) COPYRIGHT STMicroelectronics *****END OF FILE****/ ================================================ FILE: Zelig/mbed/TARGET_NUCLEO_F401RE/stm32f4xx_hal_rtc_ex.h ================================================ /** ****************************************************************************** * @file stm32f4xx_hal_rtc_ex.h * @author MCD Application Team * @version V1.4.1 * @date 09-October-2015 * @brief Header file of RTC HAL Extension module. ****************************************************************************** * @attention * *

© COPYRIGHT(c) 2015 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. * ****************************************************************************** */ /* Define to prevent recursive inclusion -------------------------------------*/ #ifndef __STM32F4xx_HAL_RTC_EX_H #define __STM32F4xx_HAL_RTC_EX_H #ifdef __cplusplus extern "C" { #endif /* Includes ------------------------------------------------------------------*/ #include "stm32f4xx_hal_def.h" /** @addtogroup STM32F4xx_HAL_Driver * @{ */ /** @addtogroup RTCEx * @{ */ /* Exported types ------------------------------------------------------------*/ /** @defgroup RTCEx_Exported_Types RTCEx Exported Types * @{ */ /** * @brief RTC Tamper structure definition */ typedef struct { uint32_t Tamper; /*!< Specifies the Tamper Pin. This parameter can be a value of @ref RTCEx_Tamper_Pins_Definitions */ uint32_t PinSelection; /*!< Specifies the Tamper Pin. This parameter can be a value of @ref RTCEx_Tamper_Pins_Selection */ uint32_t Trigger; /*!< Specifies the Tamper Trigger. This parameter can be a value of @ref RTCEx_Tamper_Trigger_Definitions */ uint32_t Filter; /*!< Specifies the RTC Filter Tamper. This parameter can be a value of @ref RTCEx_Tamper_Filter_Definitions */ uint32_t SamplingFrequency; /*!< Specifies the sampling frequency. This parameter can be a value of @ref RTCEx_Tamper_Sampling_Frequencies_Definitions */ uint32_t PrechargeDuration; /*!< Specifies the Precharge Duration . This parameter can be a value of @ref RTCEx_Tamper_Pin_Precharge_Duration_Definitions */ uint32_t TamperPullUp; /*!< Specifies the Tamper PullUp . This parameter can be a value of @ref RTCEx_Tamper_Pull_UP_Definitions */ uint32_t TimeStampOnTamperDetection; /*!< Specifies the TimeStampOnTamperDetection. This parameter can be a value of @ref RTCEx_Tamper_TimeStampOnTamperDetection_Definitions */ }RTC_TamperTypeDef; /** * @} */ /* Exported constants --------------------------------------------------------*/ /** @defgroup RTCEx_Exported_Constants RTCEx Exported Constants * @{ */ /** @defgroup RTCEx_Backup_Registers_Definitions RTC Backup Registers Definitions * @{ */ #define RTC_BKP_DR0 ((uint32_t)0x00000000) #define RTC_BKP_DR1 ((uint32_t)0x00000001) #define RTC_BKP_DR2 ((uint32_t)0x00000002) #define RTC_BKP_DR3 ((uint32_t)0x00000003) #define RTC_BKP_DR4 ((uint32_t)0x00000004) #define RTC_BKP_DR5 ((uint32_t)0x00000005) #define RTC_BKP_DR6 ((uint32_t)0x00000006) #define RTC_BKP_DR7 ((uint32_t)0x00000007) #define RTC_BKP_DR8 ((uint32_t)0x00000008) #define RTC_BKP_DR9 ((uint32_t)0x00000009) #define RTC_BKP_DR10 ((uint32_t)0x0000000A) #define RTC_BKP_DR11 ((uint32_t)0x0000000B) #define RTC_BKP_DR12 ((uint32_t)0x0000000C) #define RTC_BKP_DR13 ((uint32_t)0x0000000D) #define RTC_BKP_DR14 ((uint32_t)0x0000000E) #define RTC_BKP_DR15 ((uint32_t)0x0000000F) #define RTC_BKP_DR16 ((uint32_t)0x00000010) #define RTC_BKP_DR17 ((uint32_t)0x00000011) #define RTC_BKP_DR18 ((uint32_t)0x00000012) #define RTC_BKP_DR19 ((uint32_t)0x00000013) /** * @} */ /** @defgroup RTCEx_Time_Stamp_Edges_definitions RTC TimeStamp Edges Definitions * @{ */ #define RTC_TIMESTAMPEDGE_RISING ((uint32_t)0x00000000) #define RTC_TIMESTAMPEDGE_FALLING ((uint32_t)0x00000008) /** * @} */ /** @defgroup RTCEx_Tamper_Pins_Definitions RTC Tamper Pins Definitions * @{ */ #define RTC_TAMPER_1 RTC_TAFCR_TAMP1E #define RTC_TAMPER_2 RTC_TAFCR_TAMP2E /** * @} */ /** @defgroup RTCEx_Tamper_Pins_Selection RTC tamper Pins Selection * @{ */ #define RTC_TAMPERPIN_DEFAULT ((uint32_t)0x00000000) #define RTC_TAMPERPIN_POS1 ((uint32_t)0x00010000) /** * @} */ /** @defgroup RTCEx_TimeStamp_Pin_Selection RTC TimeStamp Pins Selection * @{ */ #define RTC_TIMESTAMPPIN_DEFAULT ((uint32_t)0x00000000) #define RTC_TIMESTAMPPIN_POS1 ((uint32_t)0x00020000) /** * @} */ /** @defgroup RTCEx_Tamper_Trigger_Definitions RTC Tamper Triggers Definitions * @{ */ #define RTC_TAMPERTRIGGER_RISINGEDGE ((uint32_t)0x00000000) #define RTC_TAMPERTRIGGER_FALLINGEDGE ((uint32_t)0x00000002) #define RTC_TAMPERTRIGGER_LOWLEVEL RTC_TAMPERTRIGGER_RISINGEDGE #define RTC_TAMPERTRIGGER_HIGHLEVEL RTC_TAMPERTRIGGER_FALLINGEDGE /** * @} */ /** @defgroup RTCEx_Tamper_Filter_Definitions RTC Tamper Filter Definitions * @{ */ #define RTC_TAMPERFILTER_DISABLE ((uint32_t)0x00000000) /*!< Tamper filter is disabled */ #define RTC_TAMPERFILTER_2SAMPLE ((uint32_t)0x00000800) /*!< Tamper is activated after 2 consecutive samples at the active level */ #define RTC_TAMPERFILTER_4SAMPLE ((uint32_t)0x00001000) /*!< Tamper is activated after 4 consecutive samples at the active level */ #define RTC_TAMPERFILTER_8SAMPLE ((uint32_t)0x00001800) /*!< Tamper is activated after 8 consecutive samples at the active level. */ /** * @} */ /** @defgroup RTCEx_Tamper_Sampling_Frequencies_Definitions RTC Tamper Sampling Frequencies Definitions * @{ */ #define RTC_TAMPERSAMPLINGFREQ_RTCCLK_DIV32768 ((uint32_t)0x00000000) /*!< Each of the tamper inputs are sampled with a frequency = RTCCLK / 32768 */ #define RTC_TAMPERSAMPLINGFREQ_RTCCLK_DIV16384 ((uint32_t)0x00000100) /*!< Each of the tamper inputs are sampled with a frequency = RTCCLK / 16384 */ #define RTC_TAMPERSAMPLINGFREQ_RTCCLK_DIV8192 ((uint32_t)0x00000200) /*!< Each of the tamper inputs are sampled with a frequency = RTCCLK / 8192 */ #define RTC_TAMPERSAMPLINGFREQ_RTCCLK_DIV4096 ((uint32_t)0x00000300) /*!< Each of the tamper inputs are sampled with a frequency = RTCCLK / 4096 */ #define RTC_TAMPERSAMPLINGFREQ_RTCCLK_DIV2048 ((uint32_t)0x00000400) /*!< Each of the tamper inputs are sampled with a frequency = RTCCLK / 2048 */ #define RTC_TAMPERSAMPLINGFREQ_RTCCLK_DIV1024 ((uint32_t)0x00000500) /*!< Each of the tamper inputs are sampled with a frequency = RTCCLK / 1024 */ #define RTC_TAMPERSAMPLINGFREQ_RTCCLK_DIV512 ((uint32_t)0x00000600) /*!< Each of the tamper inputs are sampled with a frequency = RTCCLK / 512 */ #define RTC_TAMPERSAMPLINGFREQ_RTCCLK_DIV256 ((uint32_t)0x00000700) /*!< Each of the tamper inputs are sampled with a frequency = RTCCLK / 256 */ /** * @} */ /** @defgroup RTCEx_Tamper_Pin_Precharge_Duration_Definitions RTC Tamper Pin Precharge Duration Definitions * @{ */ #define RTC_TAMPERPRECHARGEDURATION_1RTCCLK ((uint32_t)0x00000000) /*!< Tamper pins are pre-charged before sampling during 1 RTCCLK cycle */ #define RTC_TAMPERPRECHARGEDURATION_2RTCCLK ((uint32_t)0x00002000) /*!< Tamper pins are pre-charged before sampling during 2 RTCCLK cycles */ #define RTC_TAMPERPRECHARGEDURATION_4RTCCLK ((uint32_t)0x00004000) /*!< Tamper pins are pre-charged before sampling during 4 RTCCLK cycles */ #define RTC_TAMPERPRECHARGEDURATION_8RTCCLK ((uint32_t)0x00006000) /*!< Tamper pins are pre-charged before sampling during 8 RTCCLK cycles */ /** * @} */ /** @defgroup RTCEx_Tamper_TimeStampOnTamperDetection_Definitions RTC Tamper TimeStamp On Tamper Detection Definitions * @{ */ #define RTC_TIMESTAMPONTAMPERDETECTION_ENABLE ((uint32_t)RTC_TAFCR_TAMPTS) /*!< TimeStamp on Tamper Detection event saved */ #define RTC_TIMESTAMPONTAMPERDETECTION_DISABLE ((uint32_t)0x00000000) /*!< TimeStamp on Tamper Detection event is not saved */ /** * @} */ /** @defgroup RTCEx_Tamper_Pull_UP_Definitions RTC Tamper Pull Up Definitions * @{ */ #define RTC_TAMPER_PULLUP_ENABLE ((uint32_t)0x00000000) /*!< TimeStamp on Tamper Detection event saved */ #define RTC_TAMPER_PULLUP_DISABLE ((uint32_t)RTC_TAFCR_TAMPPUDIS) /*!< TimeStamp on Tamper Detection event is not saved */ /** * @} */ /** @defgroup RTCEx_Wakeup_Timer_Definitions RTC Wake-up Timer Definitions * @{ */ #define RTC_WAKEUPCLOCK_RTCCLK_DIV16 ((uint32_t)0x00000000) #define RTC_WAKEUPCLOCK_RTCCLK_DIV8 ((uint32_t)0x00000001) #define RTC_WAKEUPCLOCK_RTCCLK_DIV4 ((uint32_t)0x00000002) #define RTC_WAKEUPCLOCK_RTCCLK_DIV2 ((uint32_t)0x00000003) #define RTC_WAKEUPCLOCK_CK_SPRE_16BITS ((uint32_t)0x00000004) #define RTC_WAKEUPCLOCK_CK_SPRE_17BITS ((uint32_t)0x00000006) /** * @} */ /** @defgroup RTCEx_Digital_Calibration_Definitions RTC Digital Calib Definitions * @{ */ #define RTC_CALIBSIGN_POSITIVE ((uint32_t)0x00000000) #define RTC_CALIBSIGN_NEGATIVE ((uint32_t)0x00000080) /** * @} */ /** @defgroup RTCEx_Smooth_calib_period_Definitions RTC Smooth Calib Period Definitions * @{ */ #define RTC_SMOOTHCALIB_PERIOD_32SEC ((uint32_t)0x00000000) /*!< If RTCCLK = 32768 Hz, Smooth calibration period is 32s, else 2exp20 RTCCLK seconds */ #define RTC_SMOOTHCALIB_PERIOD_16SEC ((uint32_t)0x00002000) /*!< If RTCCLK = 32768 Hz, Smooth calibration period is 16s, else 2exp19 RTCCLK seconds */ #define RTC_SMOOTHCALIB_PERIOD_8SEC ((uint32_t)0x00004000) /*!< If RTCCLK = 32768 Hz, Smooth calibration period is 8s, else 2exp18 RTCCLK seconds */ /** * @} */ /** @defgroup RTCEx_Smooth_calib_Plus_pulses_Definitions RTC Smooth Calib Plus Pulses Definitions * @{ */ #define RTC_SMOOTHCALIB_PLUSPULSES_SET ((uint32_t)0x00008000) /*!< The number of RTCCLK pulses added during a X -second window = Y - CALM[8:0] with Y = 512, 256, 128 when X = 32, 16, 8 */ #define RTC_SMOOTHCALIB_PLUSPULSES_RESET ((uint32_t)0x00000000) /*!< The number of RTCCLK pulses subbstited during a 32-second window = CALM[8:0] */ /** * @} */ /** @defgroup RTCEx_Add_1_Second_Parameter_Definitions RTC Add 1 Second Parameter Definitions * @{ */ #define RTC_SHIFTADD1S_RESET ((uint32_t)0x00000000) #define RTC_SHIFTADD1S_SET ((uint32_t)0x80000000) /** * @} */ /** @defgroup RTCEx_Calib_Output_selection_Definitions RTC Calib Output Selection Definitions * @{ */ #define RTC_CALIBOUTPUT_512HZ ((uint32_t)0x00000000) #define RTC_CALIBOUTPUT_1HZ ((uint32_t)0x00080000) /** * @} */ /** * @} */ /* Exported macro ------------------------------------------------------------*/ /** @defgroup RTCEx_Exported_Macros RTCEx Exported Macros * @{ */ /* ---------------------------------WAKEUPTIMER---------------------------------*/ /** @defgroup RTCEx_WakeUp_Timer RTC WakeUp Timer * @{ */ /** * @brief Enable the RTC WakeUp Timer peripheral. * @param __HANDLE__: specifies the RTC handle. * @retval None */ #define __HAL_RTC_WAKEUPTIMER_ENABLE(__HANDLE__) ((__HANDLE__)->Instance->CR |= (RTC_CR_WUTE)) /** * @brief Disable the RTC Wake-up Timer peripheral. * @param __HANDLE__: specifies the RTC handle. * @retval None */ #define __HAL_RTC_WAKEUPTIMER_DISABLE(__HANDLE__) ((__HANDLE__)->Instance->CR &= ~(RTC_CR_WUTE)) /** * @brief Enable the RTC WakeUpTimer interrupt. * @param __HANDLE__: specifies the RTC handle. * @param __INTERRUPT__: specifies the RTC WakeUpTimer interrupt sources to be enabled or disabled. * This parameter can be: * @arg RTC_IT_WUT: WakeUpTimer A interrupt * @retval None */ #define __HAL_RTC_WAKEUPTIMER_ENABLE_IT(__HANDLE__, __INTERRUPT__) ((__HANDLE__)->Instance->CR |= (__INTERRUPT__)) /** * @brief Disable the RTC WakeUpTimer interrupt. * @param __HANDLE__: specifies the RTC handle. * @param __INTERRUPT__: specifies the RTC WakeUpTimer interrupt sources to be enabled or disabled. * This parameter can be: * @arg RTC_IT_WUT: WakeUpTimer A interrupt * @retval None */ #define __HAL_RTC_WAKEUPTIMER_DISABLE_IT(__HANDLE__, __INTERRUPT__) ((__HANDLE__)->Instance->CR &= ~(__INTERRUPT__)) /** * @brief Check whether the specified RTC WakeUpTimer interrupt has occurred or not. * @param __HANDLE__: specifies the RTC handle. * @param __INTERRUPT__: specifies the RTC WakeUpTimer interrupt to check. * This parameter can be: * @arg RTC_IT_WUT: WakeUpTimer A interrupt * @retval None */ #define __HAL_RTC_WAKEUPTIMER_GET_IT(__HANDLE__, __INTERRUPT__) (((((__HANDLE__)->Instance->ISR) & ((__INTERRUPT__)>> 4)) != RESET)? SET : RESET) /** * @brief Check whether the specified RTC Wake Up timer interrupt has been enabled or not. * @param __HANDLE__: specifies the RTC handle. * @param __INTERRUPT__: specifies the RTC Wake Up timer interrupt sources to check. * This parameter can be: * @arg RTC_IT_WUT: WakeUpTimer interrupt * @retval None */ #define __HAL_RTC_WAKEUPTIMER_GET_IT_SOURCE(__HANDLE__, __INTERRUPT__) (((((__HANDLE__)->Instance->CR) & (__INTERRUPT__)) != RESET) ? SET : RESET) /** * @brief Get the selected RTC WakeUpTimer's flag status. * @param __HANDLE__: specifies the RTC handle. * @param __FLAG__: specifies the RTC WakeUpTimer Flag to check. * This parameter can be: * @arg RTC_FLAG_WUTF * @arg RTC_FLAG_WUTWF * @retval None */ #define __HAL_RTC_WAKEUPTIMER_GET_FLAG(__HANDLE__, __FLAG__) (((((__HANDLE__)->Instance->ISR) & (__FLAG__)) != RESET)? SET : RESET) /** * @brief Clear the RTC Wake Up timer's pending flags. * @param __HANDLE__: specifies the RTC handle. * @param __FLAG__: specifies the RTC Tamper Flag sources to be enabled or disabled. * This parameter can be: * @arg RTC_FLAG_WUTF * @retval None */ #define __HAL_RTC_WAKEUPTIMER_CLEAR_FLAG(__HANDLE__, __FLAG__) ((__HANDLE__)->Instance->ISR) = (~((__FLAG__) | RTC_ISR_INIT)|((__HANDLE__)->Instance->ISR & RTC_ISR_INIT)) /** * @brief Enable interrupt on the RTC Wake-up Timer associated Exti line. * @retval None */ #define __HAL_RTC_WAKEUPTIMER_EXTI_ENABLE_IT() (EXTI->IMR |= RTC_EXTI_LINE_WAKEUPTIMER_EVENT) /** * @brief Disable interrupt on the RTC Wake-up Timer associated Exti line. * @retval None */ #define __HAL_RTC_WAKEUPTIMER_EXTI_DISABLE_IT() (EXTI->IMR &= ~(RTC_EXTI_LINE_WAKEUPTIMER_EVENT)) /** * @brief Enable event on the RTC Wake-up Timer associated Exti line. * @retval None. */ #define __HAL_RTC_WAKEUPTIMER_EXTI_ENABLE_EVENT() (EXTI->EMR |= RTC_EXTI_LINE_WAKEUPTIMER_EVENT) /** * @brief Disable event on the RTC Wake-up Timer associated Exti line. * @retval None. */ #define __HAL_RTC_WAKEUPTIMER_EXTI_DISABLE_EVENT() (EXTI->EMR &= ~(RTC_EXTI_LINE_WAKEUPTIMER_EVENT)) /** * @brief Enable falling edge trigger on the RTC Wake-up Timer associated Exti line. * @retval None. */ #define __HAL_RTC_WAKEUPTIMER_EXTI_ENABLE_FALLING_EDGE() (EXTI->FTSR |= RTC_EXTI_LINE_WAKEUPTIMER_EVENT) /** * @brief Disable falling edge trigger on the RTC Wake-up Timer associated Exti line. * @retval None. */ #define __HAL_RTC_WAKEUPTIMER_EXTI_DISABLE_FALLING_EDGE() (EXTI->FTSR &= ~(RTC_EXTI_LINE_WAKEUPTIMER_EVENT)) /** * @brief Enable rising edge trigger on the RTC Wake-up Timer associated Exti line. * @retval None. */ #define __HAL_RTC_WAKEUPTIMER_EXTI_ENABLE_RISING_EDGE() (EXTI->RTSR |= RTC_EXTI_LINE_WAKEUPTIMER_EVENT) /** * @brief Disable rising edge trigger on the RTC Wake-up Timer associated Exti line. * @retval None. */ #define __HAL_RTC_WAKEUPTIMER_EXTI_DISABLE_RISING_EDGE() (EXTI->RTSR &= ~(RTC_EXTI_LINE_WAKEUPTIMER_EVENT)) /** * @brief Enable rising & falling edge trigger on the RTC Wake-up Timer associated Exti line. * @retval None. */ #define __HAL_RTC_WAKEUPTIMER_EXTI_ENABLE_RISING_FALLING_EDGE() __HAL_RTC_WAKEUPTIMER_EXTI_ENABLE_RISING_EDGE();__HAL_RTC_WAKEUPTIMER_EXTI_ENABLE_FALLING_EDGE(); /** * @brief Disable rising & falling edge trigger on the RTC Wake-up Timer associated Exti line. * This parameter can be: * @retval None. */ #define __HAL_RTC_WAKEUPTIMER_EXTI_DISABLE_RISING_FALLING_EDGE() __HAL_RTC_WAKEUPTIMER_EXTI_DISABLE_RISING_EDGE();__HAL_RTC_WAKEUPTIMER_EXTI_DISABLE_FALLING_EDGE(); /** * @brief Check whether the RTC Wake-up Timer associated Exti line interrupt flag is set or not. * @retval Line Status. */ #define __HAL_RTC_WAKEUPTIMER_EXTI_GET_FLAG() (EXTI->PR & RTC_EXTI_LINE_WAKEUPTIMER_EVENT) /** * @brief Clear the RTC Wake-up Timer associated Exti line flag. * @retval None. */ #define __HAL_RTC_WAKEUPTIMER_EXTI_CLEAR_FLAG() (EXTI->PR = RTC_EXTI_LINE_WAKEUPTIMER_EVENT) /** * @brief Generate a Software interrupt on the RTC Wake-up Timer associated Exti line. * @retval None. */ #define __HAL_RTC_WAKEUPTIMER_EXTI_GENERATE_SWIT() (EXTI->SWIER |= RTC_EXTI_LINE_WAKEUPTIMER_EVENT) /** * @} */ /* ---------------------------------TIMESTAMP---------------------------------*/ /** @defgroup RTCEx_Timestamp RTC Timestamp * @{ */ /** * @brief Enable the RTC TimeStamp peripheral. * @param __HANDLE__: specifies the RTC handle. * @retval None */ #define __HAL_RTC_TIMESTAMP_ENABLE(__HANDLE__) ((__HANDLE__)->Instance->CR |= (RTC_CR_TSE)) /** * @brief Disable the RTC TimeStamp peripheral. * @param __HANDLE__: specifies the RTC handle. * @retval None */ #define __HAL_RTC_TIMESTAMP_DISABLE(__HANDLE__) ((__HANDLE__)->Instance->CR &= ~(RTC_CR_TSE)) /** * @brief Enable the RTC TimeStamp interrupt. * @param __HANDLE__: specifies the RTC handle. * @param __INTERRUPT__: specifies the RTC TimeStamp interrupt sources to be enabled or disabled. * This parameter can be: * @arg RTC_IT_TS: TimeStamp interrupt * @retval None */ #define __HAL_RTC_TIMESTAMP_ENABLE_IT(__HANDLE__, __INTERRUPT__) ((__HANDLE__)->Instance->CR |= (__INTERRUPT__)) /** * @brief Disable the RTC TimeStamp interrupt. * @param __HANDLE__: specifies the RTC handle. * @param __INTERRUPT__: specifies the RTC TimeStamp interrupt sources to be enabled or disabled. * This parameter can be: * @arg RTC_IT_TS: TimeStamp interrupt * @retval None */ #define __HAL_RTC_TIMESTAMP_DISABLE_IT(__HANDLE__, __INTERRUPT__) ((__HANDLE__)->Instance->CR &= ~(__INTERRUPT__)) /** * @brief Check whether the specified RTC TimeStamp interrupt has occurred or not. * @param __HANDLE__: specifies the RTC handle. * @param __INTERRUPT__: specifies the RTC TimeStamp interrupt to check. * This parameter can be: * @arg RTC_IT_TS: TimeStamp interrupt * @retval None */ #define __HAL_RTC_TIMESTAMP_GET_IT(__HANDLE__, __INTERRUPT__) (((((__HANDLE__)->Instance->ISR) & ((__INTERRUPT__)>> 4)) != RESET)? SET : RESET) /** * @brief Check whether the specified RTC Time Stamp interrupt has been enabled or not. * @param __HANDLE__: specifies the RTC handle. * @param __INTERRUPT__: specifies the RTC Time Stamp interrupt source to check. * This parameter can be: * @arg RTC_IT_TS: TimeStamp interrupt * @retval None */ #define __HAL_RTC_TIMESTAMP_GET_IT_SOURCE(__HANDLE__, __INTERRUPT__) (((((__HANDLE__)->Instance->CR) & (__INTERRUPT__)) != RESET) ? SET : RESET) /** * @brief Get the selected RTC TimeStamp's flag status. * @param __HANDLE__: specifies the RTC handle. * @param __FLAG__: specifies the RTC TimeStamp flag to check. * This parameter can be: * @arg RTC_FLAG_TSF * @arg RTC_FLAG_TSOVF * @retval None */ #define __HAL_RTC_TIMESTAMP_GET_FLAG(__HANDLE__, __FLAG__) (((((__HANDLE__)->Instance->ISR) & (__FLAG__)) != RESET)? SET : RESET) /** * @brief Clear the RTC Time Stamp's pending flags. * @param __HANDLE__: specifies the RTC handle. * @param __FLAG__: specifies the RTC Alarm Flag sources to be enabled or disabled. * This parameter can be: * @arg RTC_FLAG_TSF * @retval None */ #define __HAL_RTC_TIMESTAMP_CLEAR_FLAG(__HANDLE__, __FLAG__) ((__HANDLE__)->Instance->ISR) = (~((__FLAG__) | RTC_ISR_INIT)|((__HANDLE__)->Instance->ISR & RTC_ISR_INIT)) /** * @} */ /* ---------------------------------TAMPER------------------------------------*/ /** @defgroup RTCEx_Tamper RTC Tamper * @{ */ /** * @brief Enable the RTC Tamper1 input detection. * @param __HANDLE__: specifies the RTC handle. * @retval None */ #define __HAL_RTC_TAMPER1_ENABLE(__HANDLE__) ((__HANDLE__)->Instance->TAFCR |= (RTC_TAFCR_TAMP1E)) /** * @brief Disable the RTC Tamper1 input detection. * @param __HANDLE__: specifies the RTC handle. * @retval None */ #define __HAL_RTC_TAMPER1_DISABLE(__HANDLE__) ((__HANDLE__)->Instance->TAFCR &= ~(RTC_TAFCR_TAMP1E)) /** * @brief Enable the RTC Tamper2 input detection. * @param __HANDLE__: specifies the RTC handle. * @retval None */ #define __HAL_RTC_TAMPER2_ENABLE(__HANDLE__) ((__HANDLE__)->Instance->TAFCR |= (RTC_TAFCR_TAMP2E)) /** * @brief Disable the RTC Tamper2 input detection. * @param __HANDLE__: specifies the RTC handle. * @retval None */ #define __HAL_RTC_TAMPER2_DISABLE(__HANDLE__) ((__HANDLE__)->Instance->TAFCR &= ~(RTC_TAFCR_TAMP2E)) /** * @brief Check whether the specified RTC Tamper interrupt has occurred or not. * @param __HANDLE__: specifies the RTC handle. * @param __INTERRUPT__: specifies the RTC Tamper interrupt to check. * This parameter can be: * @arg RTC_IT_TAMP1 * @arg RTC_IT_TAMP2 * @retval None */ #define __HAL_RTC_TAMPER_GET_IT(__HANDLE__, __INTERRUPT__) (((((__HANDLE__)->Instance->ISR) & ((__INTERRUPT__)>> 4)) != RESET)? SET : RESET) /** * @brief Check whether the specified RTC Tamper interrupt has been enabled or not. * @param __HANDLE__: specifies the RTC handle. * @param __INTERRUPT__: specifies the RTC Tamper interrupt source to check. * This parameter can be: * @arg RTC_IT_TAMP: Tamper interrupt * @retval None */ #define __HAL_RTC_TAMPER_GET_IT_SOURCE(__HANDLE__, __INTERRUPT__) (((((__HANDLE__)->Instance->TAFCR) & (__INTERRUPT__)) != RESET) ? SET : RESET) /** * @brief Get the selected RTC Tamper's flag status. * @param __HANDLE__: specifies the RTC handle. * @param __FLAG__: specifies the RTC Tamper Flag sources to be enabled or disabled. * This parameter can be: * @arg RTC_FLAG_TAMP1F * @arg RTC_FLAG_TAMP2F * @retval None */ #define __HAL_RTC_TAMPER_GET_FLAG(__HANDLE__, __FLAG__) (((((__HANDLE__)->Instance->ISR) & (__FLAG__)) != RESET)? SET : RESET) /** * @brief Clear the RTC Tamper's pending flags. * @param __HANDLE__: specifies the RTC handle. * @param __FLAG__: specifies the RTC Tamper Flag to clear. * This parameter can be: * @arg RTC_FLAG_TAMP1F * @arg RTC_FLAG_TAMP2F * @retval None */ #define __HAL_RTC_TAMPER_CLEAR_FLAG(__HANDLE__, __FLAG__) ((__HANDLE__)->Instance->ISR) = (~((__FLAG__) | RTC_ISR_INIT)|((__HANDLE__)->Instance->ISR & RTC_ISR_INIT)) /** * @} */ /* --------------------------TAMPER/TIMESTAMP---------------------------------*/ /** @defgroup RTCEx_Tamper_Timestamp EXTI RTC Tamper Timestamp EXTI * @{ */ /** * @brief Enable interrupt on the RTC Tamper and Timestamp associated Exti line. * @retval None */ #define __HAL_RTC_TAMPER_TIMESTAMP_EXTI_ENABLE_IT() (EXTI->IMR |= RTC_EXTI_LINE_TAMPER_TIMESTAMP_EVENT) /** * @brief Disable interrupt on the RTC Tamper and Timestamp associated Exti line. * @retval None */ #define __HAL_RTC_TAMPER_TIMESTAMP_EXTI_DISABLE_IT() (EXTI->IMR &= ~(RTC_EXTI_LINE_TAMPER_TIMESTAMP_EVENT)) /** * @brief Enable event on the RTC Tamper and Timestamp associated Exti line. * @retval None. */ #define __HAL_RTC_TAMPER_TIMESTAMP_EXTI_ENABLE_EVENT() (EXTI->EMR |= RTC_EXTI_LINE_TAMPER_TIMESTAMP_EVENT) /** * @brief Disable event on the RTC Tamper and Timestamp associated Exti line. * @retval None. */ #define __HAL_RTC_TAMPER_TIMESTAMP_EXTI_DISABLE_EVENT() (EXTI->EMR &= ~(RTC_EXTI_LINE_TAMPER_TIMESTAMP_EVENT)) /** * @brief Enable falling edge trigger on the RTC Tamper and Timestamp associated Exti line. * @retval None. */ #define __HAL_RTC_TAMPER_TIMESTAMP_EXTI_ENABLE_FALLING_EDGE() (EXTI->FTSR |= RTC_EXTI_LINE_TAMPER_TIMESTAMP_EVENT) /** * @brief Disable falling edge trigger on the RTC Tamper and Timestamp associated Exti line. * @retval None. */ #define __HAL_RTC_TAMPER_TIMESTAMP_EXTI_DISABLE_FALLING_EDGE() (EXTI->FTSR &= ~(RTC_EXTI_LINE_TAMPER_TIMESTAMP_EVENT)) /** * @brief Enable rising edge trigger on the RTC Tamper and Timestamp associated Exti line. * @retval None. */ #define __HAL_RTC_TAMPER_TIMESTAMP_EXTI_ENABLE_RISING_EDGE() (EXTI->RTSR |= RTC_EXTI_LINE_TAMPER_TIMESTAMP_EVENT) /** * @brief Disable rising edge trigger on the RTC Tamper and Timestamp associated Exti line. * @retval None. */ #define __HAL_RTC_TAMPER_TIMESTAMP_EXTI_DISABLE_RISING_EDGE() (EXTI->RTSR &= ~(RTC_EXTI_LINE_TAMPER_TIMESTAMP_EVENT)) /** * @brief Enable rising & falling edge trigger on the RTC Tamper and Timestamp associated Exti line. * @retval None. */ #define __HAL_RTC_TAMPER_TIMESTAMP_EXTI_ENABLE_RISING_FALLING_EDGE() __HAL_RTC_TAMPER_TIMESTAMP_EXTI_ENABLE_RISING_EDGE();__HAL_RTC_TAMPER_TIMESTAMP_EXTI_ENABLE_FALLING_EDGE(); /** * @brief Disable rising & falling edge trigger on the RTC Tamper and Timestamp associated Exti line. * This parameter can be: * @retval None. */ #define __HAL_RTC_TAMPER_TIMESTAMP_EXTI_DISABLE_RISING_FALLING_EDGE() __HAL_RTC_TAMPER_TIMESTAMP_EXTI_DISABLE_RISING_EDGE();__HAL_RTC_TAMPER_TIMESTAMP_EXTI_DISABLE_FALLING_EDGE(); /** * @brief Check whether the RTC Tamper and Timestamp associated Exti line interrupt flag is set or not. * @retval Line Status. */ #define __HAL_RTC_TAMPER_TIMESTAMP_EXTI_GET_FLAG() (EXTI->PR & RTC_EXTI_LINE_TAMPER_TIMESTAMP_EVENT) /** * @brief Clear the RTC Tamper and Timestamp associated Exti line flag. * @retval None. */ #define __HAL_RTC_TAMPER_TIMESTAMP_EXTI_CLEAR_FLAG() (EXTI->PR = RTC_EXTI_LINE_TAMPER_TIMESTAMP_EVENT) /** * @brief Generate a Software interrupt on the RTC Tamper and Timestamp associated Exti line * @retval None. */ #define __HAL_RTC_TAMPER_TIMESTAMP_EXTI_GENERATE_SWIT() (EXTI->SWIER |= RTC_EXTI_LINE_TAMPER_TIMESTAMP_EVENT) /** * @} */ /* ------------------------------Calibration----------------------------------*/ /** @defgroup RTCEx_Calibration RTC Calibration * @{ */ /** * @brief Enable the Coarse calibration process. * @param __HANDLE__: specifies the RTC handle. * @retval None */ #define __HAL_RTC_COARSE_CALIB_ENABLE(__HANDLE__) ((__HANDLE__)->Instance->CR |= (RTC_CR_DCE)) /** * @brief Disable the Coarse calibration process. * @param __HANDLE__: specifies the RTC handle. * @retval None */ #define __HAL_RTC_COARSE_CALIB_DISABLE(__HANDLE__) ((__HANDLE__)->Instance->CR &= ~(RTC_CR_DCE)) /** * @brief Enable the RTC calibration output. * @param __HANDLE__: specifies the RTC handle. * @retval None */ #define __HAL_RTC_CALIBRATION_OUTPUT_ENABLE(__HANDLE__) ((__HANDLE__)->Instance->CR |= (RTC_CR_COE)) /** * @brief Disable the calibration output. * @param __HANDLE__: specifies the RTC handle. * @retval None */ #define __HAL_RTC_CALIBRATION_OUTPUT_DISABLE(__HANDLE__) ((__HANDLE__)->Instance->CR &= ~(RTC_CR_COE)) /** * @brief Enable the clock reference detection. * @param __HANDLE__: specifies the RTC handle. * @retval None */ #define __HAL_RTC_CLOCKREF_DETECTION_ENABLE(__HANDLE__) ((__HANDLE__)->Instance->CR |= (RTC_CR_REFCKON)) /** * @brief Disable the clock reference detection. * @param __HANDLE__: specifies the RTC handle. * @retval None */ #define __HAL_RTC_CLOCKREF_DETECTION_DISABLE(__HANDLE__) ((__HANDLE__)->Instance->CR &= ~(RTC_CR_REFCKON)) /** * @brief Get the selected RTC shift operation's flag status. * @param __HANDLE__: specifies the RTC handle. * @param __FLAG__: specifies the RTC shift operation Flag is pending or not. * This parameter can be: * @arg RTC_FLAG_SHPF * @retval None */ #define __HAL_RTC_SHIFT_GET_FLAG(__HANDLE__, __FLAG__) (((((__HANDLE__)->Instance->ISR) & (__FLAG__)) != RESET)? SET : RESET) /** * @} */ /** * @} */ /* Exported functions --------------------------------------------------------*/ /** @defgroup RTCEx_Exported_Functions RTCEx Exported Functions * @{ */ /** @addtogroup RTCEx_Exported_Functions_Group1 * @{ */ /* RTC TimeStamp and Tamper functions *****************************************/ HAL_StatusTypeDef HAL_RTCEx_SetTimeStamp(RTC_HandleTypeDef *hrtc, uint32_t TimeStampEdge, uint32_t RTC_TimeStampPin); HAL_StatusTypeDef HAL_RTCEx_SetTimeStamp_IT(RTC_HandleTypeDef *hrtc, uint32_t TimeStampEdge, uint32_t RTC_TimeStampPin); HAL_StatusTypeDef HAL_RTCEx_DeactivateTimeStamp(RTC_HandleTypeDef *hrtc); HAL_StatusTypeDef HAL_RTCEx_GetTimeStamp(RTC_HandleTypeDef *hrtc, RTC_TimeTypeDef *sTimeStamp, RTC_DateTypeDef *sTimeStampDate, uint32_t Format); HAL_StatusTypeDef HAL_RTCEx_SetTamper(RTC_HandleTypeDef *hrtc, RTC_TamperTypeDef* sTamper); HAL_StatusTypeDef HAL_RTCEx_SetTamper_IT(RTC_HandleTypeDef *hrtc, RTC_TamperTypeDef* sTamper); HAL_StatusTypeDef HAL_RTCEx_DeactivateTamper(RTC_HandleTypeDef *hrtc, uint32_t Tamper); void HAL_RTCEx_TamperTimeStampIRQHandler(RTC_HandleTypeDef *hrtc); void HAL_RTCEx_Tamper1EventCallback(RTC_HandleTypeDef *hrtc); void HAL_RTCEx_Tamper2EventCallback(RTC_HandleTypeDef *hrtc); void HAL_RTCEx_TimeStampEventCallback(RTC_HandleTypeDef *hrtc); HAL_StatusTypeDef HAL_RTCEx_PollForTimeStampEvent(RTC_HandleTypeDef *hrtc, uint32_t Timeout); HAL_StatusTypeDef HAL_RTCEx_PollForTamper1Event(RTC_HandleTypeDef *hrtc, uint32_t Timeout); HAL_StatusTypeDef HAL_RTCEx_PollForTamper2Event(RTC_HandleTypeDef *hrtc, uint32_t Timeout); /** * @} */ /** @addtogroup RTCEx_Exported_Functions_Group2 * @{ */ /* RTC Wake-up functions ******************************************************/ HAL_StatusTypeDef HAL_RTCEx_SetWakeUpTimer(RTC_HandleTypeDef *hrtc, uint32_t WakeUpCounter, uint32_t WakeUpClock); HAL_StatusTypeDef HAL_RTCEx_SetWakeUpTimer_IT(RTC_HandleTypeDef *hrtc, uint32_t WakeUpCounter, uint32_t WakeUpClock); uint32_t HAL_RTCEx_DeactivateWakeUpTimer(RTC_HandleTypeDef *hrtc); uint32_t HAL_RTCEx_GetWakeUpTimer(RTC_HandleTypeDef *hrtc); void HAL_RTCEx_WakeUpTimerIRQHandler(RTC_HandleTypeDef *hrtc); void HAL_RTCEx_WakeUpTimerEventCallback(RTC_HandleTypeDef *hrtc); HAL_StatusTypeDef HAL_RTCEx_PollForWakeUpTimerEvent(RTC_HandleTypeDef *hrtc, uint32_t Timeout); /** * @} */ /** @addtogroup RTCEx_Exported_Functions_Group3 * @{ */ /* Extension Control functions ************************************************/ void HAL_RTCEx_BKUPWrite(RTC_HandleTypeDef *hrtc, uint32_t BackupRegister, uint32_t Data); uint32_t HAL_RTCEx_BKUPRead(RTC_HandleTypeDef *hrtc, uint32_t BackupRegister); HAL_StatusTypeDef HAL_RTCEx_SetCoarseCalib(RTC_HandleTypeDef *hrtc, uint32_t CalibSign, uint32_t Value); HAL_StatusTypeDef HAL_RTCEx_DeactivateCoarseCalib(RTC_HandleTypeDef *hrtc); HAL_StatusTypeDef HAL_RTCEx_SetSmoothCalib(RTC_HandleTypeDef *hrtc, uint32_t SmoothCalibPeriod, uint32_t SmoothCalibPlusPulses, uint32_t SmouthCalibMinusPulsesValue); HAL_StatusTypeDef HAL_RTCEx_SetSynchroShift(RTC_HandleTypeDef *hrtc, uint32_t ShiftAdd1S, uint32_t ShiftSubFS); HAL_StatusTypeDef HAL_RTCEx_SetCalibrationOutPut(RTC_HandleTypeDef *hrtc, uint32_t CalibOutput); HAL_StatusTypeDef HAL_RTCEx_DeactivateCalibrationOutPut(RTC_HandleTypeDef *hrtc); HAL_StatusTypeDef HAL_RTCEx_SetRefClock(RTC_HandleTypeDef *hrtc); HAL_StatusTypeDef HAL_RTCEx_DeactivateRefClock(RTC_HandleTypeDef *hrtc); HAL_StatusTypeDef HAL_RTCEx_EnableBypassShadow(RTC_HandleTypeDef *hrtc); HAL_StatusTypeDef HAL_RTCEx_DisableBypassShadow(RTC_HandleTypeDef *hrtc); /** * @} */ /** @addtogroup RTCEx_Exported_Functions_Group4 * @{ */ /* Extension RTC features functions *******************************************/ void HAL_RTCEx_AlarmBEventCallback(RTC_HandleTypeDef *hrtc); HAL_StatusTypeDef HAL_RTCEx_PollForAlarmBEvent(RTC_HandleTypeDef *hrtc, uint32_t Timeout); /** * @} */ /** * @} */ /* Private types -------------------------------------------------------------*/ /* Private variables ---------------------------------------------------------*/ /* Private constants ---------------------------------------------------------*/ /** @defgroup RTCEx_Private_Constants RTCEx Private Constants * @{ */ #define RTC_EXTI_LINE_TAMPER_TIMESTAMP_EVENT ((uint32_t)EXTI_IMR_MR21) /*!< External interrupt line 21 Connected to the RTC Tamper and Time Stamp events */ #define RTC_EXTI_LINE_WAKEUPTIMER_EVENT ((uint32_t)EXTI_IMR_MR22) /*!< External interrupt line 22 Connected to the RTC Wake-up event */ /** * @} */ /* Private macros ------------------------------------------------------------*/ /** @defgroup RTCEx_Private_Macros RTCEx Private Macros * @{ */ /** @defgroup RTCEx_IS_RTC_Definitions Private macros to check input parameters * @{ */ #define IS_RTC_BKP(BKP) (((BKP) == RTC_BKP_DR0) || \ ((BKP) == RTC_BKP_DR1) || \ ((BKP) == RTC_BKP_DR2) || \ ((BKP) == RTC_BKP_DR3) || \ ((BKP) == RTC_BKP_DR4) || \ ((BKP) == RTC_BKP_DR5) || \ ((BKP) == RTC_BKP_DR6) || \ ((BKP) == RTC_BKP_DR7) || \ ((BKP) == RTC_BKP_DR8) || \ ((BKP) == RTC_BKP_DR9) || \ ((BKP) == RTC_BKP_DR10) || \ ((BKP) == RTC_BKP_DR11) || \ ((BKP) == RTC_BKP_DR12) || \ ((BKP) == RTC_BKP_DR13) || \ ((BKP) == RTC_BKP_DR14) || \ ((BKP) == RTC_BKP_DR15) || \ ((BKP) == RTC_BKP_DR16) || \ ((BKP) == RTC_BKP_DR17) || \ ((BKP) == RTC_BKP_DR18) || \ ((BKP) == RTC_BKP_DR19)) #define IS_TIMESTAMP_EDGE(EDGE) (((EDGE) == RTC_TIMESTAMPEDGE_RISING) || \ ((EDGE) == RTC_TIMESTAMPEDGE_FALLING)) #define IS_RTC_TAMPER(TAMPER) ((((TAMPER) & ((uint32_t)!(RTC_TAFCR_TAMP1E | RTC_TAFCR_TAMP2E))) == 0x00) && ((TAMPER) != (uint32_t)RESET)) #define IS_RTC_TAMPER_PIN(PIN) (((PIN) == RTC_TAMPERPIN_DEFAULT) || \ ((PIN) == RTC_TAMPERPIN_POS1)) #define IS_RTC_TIMESTAMP_PIN(PIN) (((PIN) == RTC_TIMESTAMPPIN_DEFAULT) || \ ((PIN) == RTC_TIMESTAMPPIN_POS1)) #define IS_RTC_TAMPER_TRIGGER(TRIGGER) (((TRIGGER) == RTC_TAMPERTRIGGER_RISINGEDGE) || \ ((TRIGGER) == RTC_TAMPERTRIGGER_FALLINGEDGE) || \ ((TRIGGER) == RTC_TAMPERTRIGGER_LOWLEVEL) || \ ((TRIGGER) == RTC_TAMPERTRIGGER_HIGHLEVEL)) #define IS_RTC_TAMPER_FILTER(FILTER) (((FILTER) == RTC_TAMPERFILTER_DISABLE) || \ ((FILTER) == RTC_TAMPERFILTER_2SAMPLE) || \ ((FILTER) == RTC_TAMPERFILTER_4SAMPLE) || \ ((FILTER) == RTC_TAMPERFILTER_8SAMPLE)) #define IS_RTC_TAMPER_SAMPLING_FREQ(FREQ) (((FREQ) == RTC_TAMPERSAMPLINGFREQ_RTCCLK_DIV32768)|| \ ((FREQ) == RTC_TAMPERSAMPLINGFREQ_RTCCLK_DIV16384)|| \ ((FREQ) == RTC_TAMPERSAMPLINGFREQ_RTCCLK_DIV8192) || \ ((FREQ) == RTC_TAMPERSAMPLINGFREQ_RTCCLK_DIV4096) || \ ((FREQ) == RTC_TAMPERSAMPLINGFREQ_RTCCLK_DIV2048) || \ ((FREQ) == RTC_TAMPERSAMPLINGFREQ_RTCCLK_DIV1024) || \ ((FREQ) == RTC_TAMPERSAMPLINGFREQ_RTCCLK_DIV512) || \ ((FREQ) == RTC_TAMPERSAMPLINGFREQ_RTCCLK_DIV256)) #define IS_RTC_TAMPER_PRECHARGE_DURATION(DURATION) (((DURATION) == RTC_TAMPERPRECHARGEDURATION_1RTCCLK) || \ ((DURATION) == RTC_TAMPERPRECHARGEDURATION_2RTCCLK) || \ ((DURATION) == RTC_TAMPERPRECHARGEDURATION_4RTCCLK) || \ ((DURATION) == RTC_TAMPERPRECHARGEDURATION_8RTCCLK)) #define IS_RTC_TAMPER_TIMESTAMPONTAMPER_DETECTION(DETECTION) (((DETECTION) == RTC_TIMESTAMPONTAMPERDETECTION_ENABLE) || \ ((DETECTION) == RTC_TIMESTAMPONTAMPERDETECTION_DISABLE)) #define IS_RTC_TAMPER_PULLUP_STATE(STATE) (((STATE) == RTC_TAMPER_PULLUP_ENABLE) || \ ((STATE) == RTC_TAMPER_PULLUP_DISABLE)) #define IS_RTC_WAKEUP_CLOCK(CLOCK) (((CLOCK) == RTC_WAKEUPCLOCK_RTCCLK_DIV16) || \ ((CLOCK) == RTC_WAKEUPCLOCK_RTCCLK_DIV8) || \ ((CLOCK) == RTC_WAKEUPCLOCK_RTCCLK_DIV4) || \ ((CLOCK) == RTC_WAKEUPCLOCK_RTCCLK_DIV2) || \ ((CLOCK) == RTC_WAKEUPCLOCK_CK_SPRE_16BITS) || \ ((CLOCK) == RTC_WAKEUPCLOCK_CK_SPRE_17BITS)) #define IS_RTC_WAKEUP_COUNTER(COUNTER) ((COUNTER) <= 0xFFFF) #define IS_RTC_CALIB_SIGN(SIGN) (((SIGN) == RTC_CALIBSIGN_POSITIVE) || \ ((SIGN) == RTC_CALIBSIGN_NEGATIVE)) #define IS_RTC_CALIB_VALUE(VALUE) ((VALUE) < 0x20) #define IS_RTC_SMOOTH_CALIB_PERIOD(PERIOD) (((PERIOD) == RTC_SMOOTHCALIB_PERIOD_32SEC) || \ ((PERIOD) == RTC_SMOOTHCALIB_PERIOD_16SEC) || \ ((PERIOD) == RTC_SMOOTHCALIB_PERIOD_8SEC)) #define IS_RTC_SMOOTH_CALIB_PLUS(PLUS) (((PLUS) == RTC_SMOOTHCALIB_PLUSPULSES_SET) || \ ((PLUS) == RTC_SMOOTHCALIB_PLUSPULSES_RESET)) #define IS_RTC_SMOOTH_CALIB_MINUS(VALUE) ((VALUE) <= 0x000001FF) #define IS_RTC_SHIFT_ADD1S(SEL) (((SEL) == RTC_SHIFTADD1S_RESET) || \ ((SEL) == RTC_SHIFTADD1S_SET)) #define IS_RTC_SHIFT_SUBFS(FS) ((FS) <= 0x00007FFF) #define IS_RTC_CALIB_OUTPUT(OUTPUT) (((OUTPUT) == RTC_CALIBOUTPUT_512HZ) || \ ((OUTPUT) == RTC_CALIBOUTPUT_1HZ)) /** * @} */ /** * @} */ /** * @} */ /** * @} */ #ifdef __cplusplus } #endif #endif /* __STM32F4xx_HAL_RTC_EX_H */ /************************ (C) COPYRIGHT STMicroelectronics *****END OF FILE****/ ================================================ FILE: Zelig/mbed/TARGET_NUCLEO_F401RE/stm32f4xx_hal_sai.h ================================================ /** ****************************************************************************** * @file stm32f4xx_hal_sai.h * @author MCD Application Team * @version V1.4.1 * @date 09-October-2015 * @brief Header file of SAI HAL module. ****************************************************************************** * @attention * *

© COPYRIGHT(c) 2015 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. * ****************************************************************************** */ /* Define to prevent recursive inclusion -------------------------------------*/ #ifndef __STM32F4xx_HAL_SAI_H #define __STM32F4xx_HAL_SAI_H #ifdef __cplusplus extern "C" { #endif /* Includes ------------------------------------------------------------------*/ #include "stm32f4xx_hal_def.h" /** @addtogroup STM32F4xx_HAL_Driver * @{ */ #if defined(STM32F427xx) || defined(STM32F437xx) || defined(STM32F429xx) || defined(STM32F439xx) ||\ defined(STM32F446xx) || defined(STM32F469xx) || defined(STM32F479xx) /** @addtogroup SAI * @{ */ /* Exported types ------------------------------------------------------------*/ /** @defgroup SAI_Exported_Types SAI Exported Types * @{ */ /** * @brief HAL State structures definition */ typedef enum { HAL_SAI_STATE_RESET = 0x00, /*!< SAI not yet initialized or disabled */ HAL_SAI_STATE_READY = 0x01, /*!< SAI initialized and ready for use */ HAL_SAI_STATE_BUSY = 0x02, /*!< SAI internal process is ongoing */ HAL_SAI_STATE_BUSY_TX = 0x12, /*!< Data transmission process is ongoing */ HAL_SAI_STATE_BUSY_RX = 0x22, /*!< Data reception process is ongoing */ HAL_SAI_STATE_TIMEOUT = 0x03, /*!< SAI timeout state */ HAL_SAI_STATE_ERROR = 0x04 /*!< SAI error state */ }HAL_SAI_StateTypeDef; /** * @brief SAI Callback prototype */ typedef void (*SAIcallback)(void); /** * @brief SAI Init Structure definition */ typedef struct { uint32_t AudioMode; /*!< Specifies the SAI Block audio Mode. This parameter can be a value of @ref SAI_Block_Mode */ uint32_t Synchro; /*!< Specifies SAI Block synchronization This parameter can be a value of @ref SAI_Block_Synchronization */ uint32_t SynchroExt; /*!< Specifies SAI Block synchronization, this setup is common for BLOCKA and BLOCKB This parameter can be a value of @ref SAI_Block_SyncExt */ uint32_t OutputDrive; /*!< Specifies when SAI Block outputs are driven. This parameter can be a value of @ref SAI_Block_Output_Drive @note this value has to be set before enabling the audio block but after the audio block configuration. */ uint32_t NoDivider; /*!< Specifies whether master clock will be divided or not. This parameter can be a value of @ref SAI_Block_NoDivider @note: If bit NODIV in the SAI_xCR1 register is cleared, the frame length should be aligned to a number equal to a power of 2, from 8 to 256. If bit NODIV in the SAI_xCR1 register is set, the frame length can take any of the values without constraint since the input clock of the audio block should be equal to the bit clock. There is no MCLK_x clock which can be output. */ uint32_t FIFOThreshold; /*!< Specifies SAI Block FIFO threshold. This parameter can be a value of @ref SAI_Block_Fifo_Threshold */ uint32_t ClockSource; /*!< Specifies the SAI Block x Clock source. This parameter is not used for STM32F446xx devices. */ uint32_t AudioFrequency; /*!< Specifies the audio frequency sampling. This parameter can be a value of @ref SAI_Audio_Frequency */ uint32_t Mckdiv; /*!< Specifies the master clock divider, the parameter will be used if for AudioFrequency the user choice This parameter must be a number between Min_Data = 0 and Max_Data = 15 */ uint32_t MonoStereoMode; /*!< Specifies if the mono or stereo mode is selected. This parameter can be a value of @ref SAI_Mono_Stereo_Mode */ uint32_t CompandingMode; /*!< Specifies the companding mode type. This parameter can be a value of @ref SAI_Block_Companding_Mode */ uint32_t TriState; /*!< Specifies the companding mode type. This parameter can be a value of @ref SAI_TRIState_Management */ /* This part of the structure is automatically filled if your are using the high level intialisation function HAL_SAI_InitProtocol */ uint32_t Protocol; /*!< Specifies the SAI Block protocol. This parameter can be a value of @ref SAI_Block_Protocol */ uint32_t DataSize; /*!< Specifies the SAI Block data size. This parameter can be a value of @ref SAI_Block_Data_Size */ uint32_t FirstBit; /*!< Specifies whether data transfers start from MSB or LSB bit. This parameter can be a value of @ref SAI_Block_MSB_LSB_transmission */ uint32_t ClockStrobing; /*!< Specifies the SAI Block clock strobing edge sensitivity. This parameter can be a value of @ref SAI_Block_Clock_Strobing */ }SAI_InitTypeDef; /** * @brief SAI Block Frame Init structure definition */ typedef struct { uint32_t FrameLength; /*!< Specifies the Frame length, the number of SCK clocks for each audio frame. This parameter must be a number between Min_Data = 8 and Max_Data = 256. @note: If master clock MCLK_x pin is declared as an output, the frame length should be aligned to a number equal to power of 2 in order to keep in an audio frame, an integer number of MCLK pulses by bit Clock. */ uint32_t ActiveFrameLength; /*!< Specifies the Frame synchronization active level length. This Parameter specifies the length in number of bit clock (SCK + 1) of the active level of FS signal in audio frame. This parameter must be a number between Min_Data = 1 and Max_Data = 128 */ uint32_t FSDefinition; /*!< Specifies the Frame synchronization definition. This parameter can be a value of @ref SAI_Block_FS_Definition */ uint32_t FSPolarity; /*!< Specifies the Frame synchronization Polarity. This parameter can be a value of @ref SAI_Block_FS_Polarity */ uint32_t FSOffset; /*!< Specifies the Frame synchronization Offset. This parameter can be a value of @ref SAI_Block_FS_Offset */ }SAI_FrameInitTypeDef; /** * @brief SAI Block Slot Init Structure definition */ typedef struct { uint32_t FirstBitOffset; /*!< Specifies the position of first data transfer bit in the slot. This parameter must be a number between Min_Data = 0 and Max_Data = 24 */ uint32_t SlotSize; /*!< Specifies the Slot Size. This parameter can be a value of @ref SAI_Block_Slot_Size */ uint32_t SlotNumber; /*!< Specifies the number of slot in the audio frame. This parameter must be a number between Min_Data = 1 and Max_Data = 16 */ uint32_t SlotActive; /*!< Specifies the slots in audio frame that will be activated. This parameter can be a value of @ref SAI_Block_Slot_Active */ }SAI_SlotInitTypeDef; /** * @brief SAI handle Structure definition */ typedef struct __SAI_HandleTypeDef { SAI_Block_TypeDef *Instance; /*!< SAI Blockx registers base address */ SAI_InitTypeDef Init; /*!< SAI communication parameters */ SAI_FrameInitTypeDef FrameInit; /*!< SAI Frame configuration parameters */ SAI_SlotInitTypeDef SlotInit; /*!< SAI Slot configuration parameters */ uint8_t *pBuffPtr; /*!< Pointer to SAI transfer Buffer */ uint16_t XferSize; /*!< SAI transfer size */ uint16_t XferCount; /*!< SAI transfer counter */ DMA_HandleTypeDef *hdmatx; /*!< SAI Tx DMA handle parameters */ DMA_HandleTypeDef *hdmarx; /*!< SAI Rx DMA handle parameters */ SAIcallback mutecallback;/*!< SAI mute callback */ void (*InterruptServiceRoutine)(struct __SAI_HandleTypeDef *hsai); /* function pointer for IRQ handler */ HAL_LockTypeDef Lock; /*!< SAI locking object */ __IO HAL_SAI_StateTypeDef State; /*!< SAI communication state */ __IO uint32_t ErrorCode; /*!< SAI Error code */ }SAI_HandleTypeDef; /** * @} */ /* Exported constants --------------------------------------------------------*/ /** @defgroup SAI_Exported_Constants SAI Exported Constants * @{ */ /** @defgroup SAI_Error_Code SAI Error Code * @{ */ #define HAL_SAI_ERROR_NONE ((uint32_t)0x00000000) /*!< No error */ #define HAL_SAI_ERROR_OVR ((uint32_t)0x00000001) /*!< Overrun Error */ #define HAL_SAI_ERROR_UDR ((uint32_t)0x00000002) /*!< Underrun error */ #define HAL_SAI_ERROR_AFSDET ((uint32_t)0x00000004) /*!< Anticipated Frame synchronisation detection */ #define HAL_SAI_ERROR_LFSDET ((uint32_t)0x00000008) /*!< Late Frame synchronisation detection */ #define HAL_SAI_ERROR_CNREADY ((uint32_t)0x00000010) /*!< codec not ready */ #define HAL_SAI_ERROR_WCKCFG ((uint32_t)0x00000020) /*!< Wrong clock configuration */ #define HAL_SAI_ERROR_TIMEOUT ((uint32_t)0x00000040) /*!< Timeout error */ /** * @} */ /** @defgroup SAI_Block_SyncExt SAI External synchronisation * @{ */ #define SAI_SYNCEXT_DISABLE ((uint32_t)0x00000000) #define SAI_SYNCEXT_IN_ENABLE ((uint32_t)0x00000001) #define SAI_SYNCEXT_OUTBLOCKA_ENABLE ((uint32_t)0x00000002) #define SAI_SYNCEXT_OUTBLOCKB_ENABLE ((uint32_t)0x00000004) /** * @} */ /** @defgroup SAI_Protocol SAI Supported protocol * @{ */ #define SAI_I2S_STANDARD ((uint32_t)0x00000000) #define SAI_I2S_MSBJUSTIFIED ((uint32_t)0x00000001) #define SAI_I2S_LSBJUSTIFIED ((uint32_t)0x00000002) #define SAI_PCM_LONG ((uint32_t)0x00000004) #define SAI_PCM_SHORT ((uint32_t)0x00000008) /** * @} */ /** @defgroup SAI_Protocol_DataSize SAI protocol data size * @{ */ #define SAI_PROTOCOL_DATASIZE_16BIT ((uint32_t)0x00000000) #define SAI_PROTOCOL_DATASIZE_16BITEXTENDED ((uint32_t)0x00000001) #define SAI_PROTOCOL_DATASIZE_24BIT ((uint32_t)0x00000002) #define SAI_PROTOCOL_DATASIZE_32BIT ((uint32_t)0x00000004) /** * @} */ /** @defgroup SAI_Clock_Source SAI Clock Source * @{ */ #define SAI_CLKSOURCE_PLLSAI ((uint32_t)0x00000000) #define SAI_CLKSOURCE_PLLI2S ((uint32_t)0x00100000) #define SAI_CLKSOURCE_EXT ((uint32_t)0x00200000) #define SAI_CLKSOURCE_NA ((uint32_t)0x00400000) /*!< No applicable for STM32F446xx */ /** * @} */ /** @defgroup SAI_Audio_Frequency SAI Audio Frequency * @{ */ #define SAI_AUDIO_FREQUENCY_192K ((uint32_t)192000) #define SAI_AUDIO_FREQUENCY_96K ((uint32_t)96000) #define SAI_AUDIO_FREQUENCY_48K ((uint32_t)48000) #define SAI_AUDIO_FREQUENCY_44K ((uint32_t)44100) #define SAI_AUDIO_FREQUENCY_32K ((uint32_t)32000) #define SAI_AUDIO_FREQUENCY_22K ((uint32_t)22050) #define SAI_AUDIO_FREQUENCY_16K ((uint32_t)16000) #define SAI_AUDIO_FREQUENCY_11K ((uint32_t)11025) #define SAI_AUDIO_FREQUENCY_8K ((uint32_t)8000) #define SAI_AUDIO_FREQUENCY_MCKDIV ((uint32_t)0) /** * @} */ /** @defgroup SAI_Block_Mode SAI Block Mode * @{ */ #define SAI_MODEMASTER_TX ((uint32_t)0x00000000) #define SAI_MODEMASTER_RX ((uint32_t)SAI_xCR1_MODE_0) #define SAI_MODESLAVE_TX ((uint32_t)SAI_xCR1_MODE_1) #define SAI_MODESLAVE_RX ((uint32_t)(SAI_xCR1_MODE_1 | SAI_xCR1_MODE_0)) /** * @} */ /** @defgroup SAI_Block_Protocol SAI Block Protocol * @{ */ #define SAI_FREE_PROTOCOL ((uint32_t)0x00000000) #define SAI_SPDIF_PROTOCOL ((uint32_t)SAI_xCR1_PRTCFG_0) #define SAI_AC97_PROTOCOL ((uint32_t)SAI_xCR1_PRTCFG_1) /** * @} */ /** @defgroup SAI_Block_Data_Size SAI Block Data Size * @{ */ #define SAI_DATASIZE_8 ((uint32_t)SAI_xCR1_DS_1) #define SAI_DATASIZE_10 ((uint32_t)(SAI_xCR1_DS_1 | SAI_xCR1_DS_0)) #define SAI_DATASIZE_16 ((uint32_t)SAI_xCR1_DS_2) #define SAI_DATASIZE_20 ((uint32_t)(SAI_xCR1_DS_2 | SAI_xCR1_DS_0)) #define SAI_DATASIZE_24 ((uint32_t)(SAI_xCR1_DS_2 | SAI_xCR1_DS_1)) #define SAI_DATASIZE_32 ((uint32_t)(SAI_xCR1_DS_2 | SAI_xCR1_DS_1 | SAI_xCR1_DS_0)) /** * @} */ /** @defgroup SAI_Block_MSB_LSB_transmission SAI Block MSB LSB transmission * @{ */ #define SAI_FIRSTBIT_MSB ((uint32_t)0x00000000) #define SAI_FIRSTBIT_LSB ((uint32_t)SAI_xCR1_LSBFIRST) /** * @} */ /** @defgroup SAI_Block_Clock_Strobing SAI Block Clock Strobing * @{ */ #define SAI_CLOCKSTROBING_FALLINGEDGE ((uint32_t)0x00000000) #define SAI_CLOCKSTROBING_RISINGEDGE ((uint32_t)SAI_xCR1_CKSTR) /** * @} */ /** @defgroup SAI_Block_Synchronization SAI Block Synchronization * @{ */ #define SAI_ASYNCHRONOUS ((uint32_t)0x00000000) #define SAI_SYNCHRONOUS ((uint32_t)SAI_xCR1_SYNCEN_0) #define SAI_SYNCHRONOUS_EXT ((uint32_t)SAI_xCR1_SYNCEN_1) /** * @} */ /** @defgroup SAI_Block_Output_Drive SAI Block Output Drive * @{ */ #define SAI_OUTPUTDRIVE_DISABLE ((uint32_t)0x00000000) #define SAI_OUTPUTDRIVE_ENABLE ((uint32_t)SAI_xCR1_OUTDRIV) /** * @} */ /** @defgroup SAI_Block_NoDivider SAI Block NoDivider * @{ */ #define SAI_MASTERDIVIDER_ENABLE ((uint32_t)0x00000000) #define SAI_MASTERDIVIDER_DISABLE ((uint32_t)SAI_xCR1_NODIV) /** * @} */ /** @defgroup SAI_Block_FS_Definition SAI Block FS Definition * @{ */ #define SAI_FS_STARTFRAME ((uint32_t)0x00000000) #define SAI_FS_CHANNEL_IDENTIFICATION ((uint32_t)SAI_xFRCR_FSDEF) /** * @} */ /** @defgroup SAI_Block_FS_Polarity SAI Block FS Polarity * @{ */ #define SAI_FS_ACTIVE_LOW ((uint32_t)0x00000000) #define SAI_FS_ACTIVE_HIGH ((uint32_t)SAI_xFRCR_FSPO) /** * @} */ /** @defgroup SAI_Block_FS_Offset SAI Block FS Offset * @{ */ #define SAI_FS_FIRSTBIT ((uint32_t)0x00000000) #define SAI_FS_BEFOREFIRSTBIT ((uint32_t)SAI_xFRCR_FSOFF) /** * @} */ /** @defgroup SAI_Block_Slot_Size SAI Block Slot Size * @{ */ #define SAI_SLOTSIZE_DATASIZE ((uint32_t)0x00000000) #define SAI_SLOTSIZE_16B ((uint32_t)SAI_xSLOTR_SLOTSZ_0) #define SAI_SLOTSIZE_32B ((uint32_t)SAI_xSLOTR_SLOTSZ_1) /** * @} */ /** @defgroup SAI_Block_Slot_Active SAI Block Slot Active * @{ */ #define SAI_SLOT_NOTACTIVE ((uint32_t)0x00000000) #define SAI_SLOTACTIVE_0 ((uint32_t)0x00010000) #define SAI_SLOTACTIVE_1 ((uint32_t)0x00020000) #define SAI_SLOTACTIVE_2 ((uint32_t)0x00040000) #define SAI_SLOTACTIVE_3 ((uint32_t)0x00080000) #define SAI_SLOTACTIVE_4 ((uint32_t)0x00100000) #define SAI_SLOTACTIVE_5 ((uint32_t)0x00200000) #define SAI_SLOTACTIVE_6 ((uint32_t)0x00400000) #define SAI_SLOTACTIVE_7 ((uint32_t)0x00800000) #define SAI_SLOTACTIVE_8 ((uint32_t)0x01000000) #define SAI_SLOTACTIVE_9 ((uint32_t)0x02000000) #define SAI_SLOTACTIVE_10 ((uint32_t)0x04000000) #define SAI_SLOTACTIVE_11 ((uint32_t)0x08000000) #define SAI_SLOTACTIVE_12 ((uint32_t)0x10000000) #define SAI_SLOTACTIVE_13 ((uint32_t)0x20000000) #define SAI_SLOTACTIVE_14 ((uint32_t)0x40000000) #define SAI_SLOTACTIVE_15 ((uint32_t)0x80000000) #define SAI_SLOTACTIVE_ALL ((uint32_t)0xFFFF0000) /** * @} */ /** @defgroup SAI_Mono_Stereo_Mode SAI Mono Stereo Mode * @{ */ #define SAI_STEREOMODE ((uint32_t)0x00000000) #define SAI_MONOMODE ((uint32_t)SAI_xCR1_MONO) /** * @} */ /** @defgroup SAI_TRIState_Management SAI TRIState Management * @{ */ #define SAI_OUTPUT_NOTRELEASED ((uint32_t)0x00000000) #define SAI_OUTPUT_RELEASED ((uint32_t)SAI_xCR2_TRIS) /** * @} */ /** @defgroup SAI_Block_Fifo_Threshold SAI Block Fifo Threshold * @{ */ #define SAI_FIFOTHRESHOLD_EMPTY ((uint32_t)0x00000000) #define SAI_FIFOTHRESHOLD_1QF ((uint32_t)SAI_xCR2_FTH_0) #define SAI_FIFOTHRESHOLD_HF ((uint32_t)SAI_xCR2_FTH_1) #define SAI_FIFOTHRESHOLD_3QF ((uint32_t)(SAI_xCR2_FTH_1 | SAI_xCR2_FTH_0)) #define SAI_FIFOTHRESHOLD_FULL ((uint32_t)SAI_xCR2_FTH_2) /** * @} */ /** @defgroup SAI_Block_Companding_Mode SAI Block Companding Mode * @{ */ #define SAI_NOCOMPANDING ((uint32_t)0x00000000) #define SAI_ULAW_1CPL_COMPANDING ((uint32_t)SAI_xCR2_COMP_1) #define SAI_ALAW_1CPL_COMPANDING ((uint32_t)(SAI_xCR2_COMP_1 | SAI_xCR2_COMP_0)) #define SAI_ULAW_2CPL_COMPANDING ((uint32_t)(SAI_xCR2_COMP_1 | SAI_xCR2_CPL)) #define SAI_ALAW_2CPL_COMPANDING ((uint32_t)(SAI_xCR2_COMP_1 | SAI_xCR2_COMP_0 | SAI_xCR2_CPL)) /** * @} */ /** @defgroup SAI_Block_Mute_Value SAI Block Mute Value * @{ */ #define SAI_ZERO_VALUE ((uint32_t)0x00000000) #define SAI_LAST_SENT_VALUE ((uint32_t)SAI_xCR2_MUTEVAL) /** * @} */ /** @defgroup SAI_Block_Interrupts_Definition SAI Block Interrupts Definition * @{ */ #define SAI_IT_OVRUDR ((uint32_t)SAI_xIMR_OVRUDRIE) #define SAI_IT_MUTEDET ((uint32_t)SAI_xIMR_MUTEDETIE) #define SAI_IT_WCKCFG ((uint32_t)SAI_xIMR_WCKCFGIE) #define SAI_IT_FREQ ((uint32_t)SAI_xIMR_FREQIE) #define SAI_IT_CNRDY ((uint32_t)SAI_xIMR_CNRDYIE) #define SAI_IT_AFSDET ((uint32_t)SAI_xIMR_AFSDETIE) #define SAI_IT_LFSDET ((uint32_t)SAI_xIMR_LFSDETIE) /** * @} */ /** @defgroup SAI_Block_Flags_Definition SAI Block Flags Definition * @{ */ #define SAI_FLAG_OVRUDR ((uint32_t)SAI_xSR_OVRUDR) #define SAI_FLAG_MUTEDET ((uint32_t)SAI_xSR_MUTEDET) #define SAI_FLAG_WCKCFG ((uint32_t)SAI_xSR_WCKCFG) #define SAI_FLAG_FREQ ((uint32_t)SAI_xSR_FREQ) #define SAI_FLAG_CNRDY ((uint32_t)SAI_xSR_CNRDY) #define SAI_FLAG_AFSDET ((uint32_t)SAI_xSR_AFSDET) #define SAI_FLAG_LFSDET ((uint32_t)SAI_xSR_LFSDET) /** * @} */ /** @defgroup SAI_Block_Fifo_Status_Level SAI Block Fifo Status Level * @{ */ #define SAI_FIFOSTATUS_EMPTY ((uint32_t)0x00000000) #define SAI_FIFOSTATUS_LESS1QUARTERFULL ((uint32_t)0x00010000) #define SAI_FIFOSTATUS_1QUARTERFULL ((uint32_t)0x00020000) #define SAI_FIFOSTATUS_HALFFULL ((uint32_t)0x00030000) #define SAI_FIFOSTATUS_3QUARTERFULL ((uint32_t)0x00040000) #define SAI_FIFOSTATUS_FULL ((uint32_t)0x00050000) /** * @} */ /** * @} */ /* Exported macro ------------------------------------------------------------*/ /** @defgroup SAI_Exported_Macros SAI Exported Macros * @brief macros to handle interrupts and specific configurations * @{ */ /** @brief Reset SAI handle state * @param __HANDLE__: specifies the SAI Handle. * @retval None */ #define __HAL_SAI_RESET_HANDLE_STATE(__HANDLE__) ((__HANDLE__)->State = HAL_SAI_STATE_RESET) /** @brief Enable or disable the specified SAI interrupts. * @param __HANDLE__: specifies the SAI Handle. * @param __INTERRUPT__: specifies the interrupt source to enable or disable. * This parameter can be one of the following values: * @arg SAI_IT_OVRUDR: Overrun underrun interrupt enable * @arg SAI_IT_MUTEDET: Mute detection interrupt enable * @arg SAI_IT_WCKCFG: Wrong Clock Configuration interrupt enable * @arg SAI_IT_FREQ: FIFO request interrupt enable * @arg SAI_IT_CNRDY: Codec not ready interrupt enable * @arg SAI_IT_AFSDET: Anticipated frame synchronization detection interrupt enable * @arg SAI_IT_LFSDET: Late frame synchronization detection interrupt enabl * @retval None */ #define __HAL_SAI_ENABLE_IT(__HANDLE__, __INTERRUPT__) ((__HANDLE__)->Instance->IMR |= (__INTERRUPT__)) #define __HAL_SAI_DISABLE_IT(__HANDLE__, __INTERRUPT__) ((__HANDLE__)->Instance->IMR &= (~(__INTERRUPT__))) /** @brief Check if the specified SAI interrupt source is enabled or disabled. * @param __HANDLE__: specifies the SAI Handle. * This parameter can be SAI where x: 1, 2, or 3 to select the SAI peripheral. * @param __INTERRUPT__: specifies the SAI interrupt source to check. * This parameter can be one of the following values: * @arg SAI_IT_TXE: Tx buffer empty interrupt enable. * @arg SAI_IT_RXNE: Rx buffer not empty interrupt enable. * @arg SAI_IT_ERR: Error interrupt enable. * @retval The new state of __INTERRUPT__ (TRUE or FALSE). */ #define __HAL_SAI_GET_IT_SOURCE(__HANDLE__, __INTERRUPT__) ((((__HANDLE__)->Instance->IMR & (__INTERRUPT__)) == (__INTERRUPT__)) ? SET : RESET) /** @brief Check whether the specified SAI flag is set or not. * @param __HANDLE__: specifies the SAI Handle. * @param __FLAG__: specifies the flag to check. * This parameter can be one of the following values: * @arg SAI_FLAG_OVRUDR: Overrun underrun flag. * @arg SAI_FLAG_MUTEDET: Mute detection flag. * @arg SAI_FLAG_WCKCFG: Wrong Clock Configuration flag. * @arg SAI_FLAG_FREQ: FIFO request flag. * @arg SAI_FLAG_CNRDY: Codec not ready flag. * @arg SAI_FLAG_AFSDET: Anticipated frame synchronization detection flag. * @arg SAI_FLAG_LFSDET: Late frame synchronization detection flag. * @retval The new state of __FLAG__ (TRUE or FALSE). */ #define __HAL_SAI_GET_FLAG(__HANDLE__, __FLAG__) ((((__HANDLE__)->Instance->SR) & (__FLAG__)) == (__FLAG__)) /** @brief Clears the specified SAI pending flag. * @param __HANDLE__: specifies the SAI Handle. * @param __FLAG__: specifies the flag to check. * This parameter can be any combination of the following values: * @arg SAI_FLAG_OVRUDR: Clear Overrun underrun * @arg SAI_FLAG_MUTEDET: Clear Mute detection * @arg SAI_FLAG_WCKCFG: Clear Wrong Clock Configuration * @arg SAI_FLAG_FREQ: Clear FIFO request * @arg SAI_FLAG_CNRDY: Clear Codec not ready * @arg SAI_FLAG_AFSDET: Clear Anticipated frame synchronization detection * @arg SAI_FLAG_LFSDET: Clear Late frame synchronization detection * * @retval None */ #define __HAL_SAI_CLEAR_FLAG(__HANDLE__, __FLAG__) ((__HANDLE__)->Instance->CLRFR = (__FLAG__)) #define __HAL_SAI_ENABLE(__HANDLE__) ((__HANDLE__)->Instance->CR1 |= SAI_xCR1_SAIEN) #define __HAL_SAI_DISABLE(__HANDLE__) ((__HANDLE__)->Instance->CR1 &= ~SAI_xCR1_SAIEN) /** * @} */ /* Include RCC SAI Extension module */ #include "stm32f4xx_hal_sai_ex.h" /* Exported functions --------------------------------------------------------*/ /** @addtogroup SAI_Exported_Functions * @{ */ /* Initialization/de-initialization functions **********************************/ /** @addtogroup SAI_Exported_Functions_Group1 * @{ */ HAL_StatusTypeDef HAL_SAI_InitProtocol(SAI_HandleTypeDef *hsai, uint32_t protocol, uint32_t datasize, uint32_t nbslot); HAL_StatusTypeDef HAL_SAI_Init(SAI_HandleTypeDef *hsai); HAL_StatusTypeDef HAL_SAI_DeInit (SAI_HandleTypeDef *hsai); void HAL_SAI_MspInit(SAI_HandleTypeDef *hsai); void HAL_SAI_MspDeInit(SAI_HandleTypeDef *hsai); /** * @} */ /* I/O operation functions *****************************************************/ /** @addtogroup SAI_Exported_Functions_Group2 * @{ */ /* Blocking mode: Polling */ HAL_StatusTypeDef HAL_SAI_Transmit(SAI_HandleTypeDef *hsai, uint8_t *pData, uint16_t Size, uint32_t Timeout); HAL_StatusTypeDef HAL_SAI_Receive(SAI_HandleTypeDef *hsai, uint8_t *pData, uint16_t Size, uint32_t Timeout); /* Non-Blocking mode: Interrupt */ HAL_StatusTypeDef HAL_SAI_Transmit_IT(SAI_HandleTypeDef *hsai, uint8_t *pData, uint16_t Size); HAL_StatusTypeDef HAL_SAI_Receive_IT(SAI_HandleTypeDef *hsai, uint8_t *pData, uint16_t Size); /* Non-Blocking mode: DMA */ HAL_StatusTypeDef HAL_SAI_Transmit_DMA(SAI_HandleTypeDef *hsai, uint8_t *pData, uint16_t Size); HAL_StatusTypeDef HAL_SAI_Receive_DMA(SAI_HandleTypeDef *hsai, uint8_t *pData, uint16_t Size); HAL_StatusTypeDef HAL_SAI_DMAPause(SAI_HandleTypeDef *hsai); HAL_StatusTypeDef HAL_SAI_DMAResume(SAI_HandleTypeDef *hsai); HAL_StatusTypeDef HAL_SAI_DMAStop(SAI_HandleTypeDef *hsai); /* Abort function */ HAL_StatusTypeDef HAL_SAI_Abort(SAI_HandleTypeDef *hsai); /* Mute management */ HAL_StatusTypeDef HAL_SAI_EnableTxMuteMode(SAI_HandleTypeDef *hsai, uint16_t val); HAL_StatusTypeDef HAL_SAI_DisableTxMuteMode(SAI_HandleTypeDef *hsai); HAL_StatusTypeDef HAL_SAI_EnableRxMuteMode(SAI_HandleTypeDef *hsai, SAIcallback callback, uint16_t counter); HAL_StatusTypeDef HAL_SAI_DisableRxMuteMode(SAI_HandleTypeDef *hsai); /* SAI IRQHandler and Callbacks used in non blocking modes (Interrupt and DMA) */ void HAL_SAI_IRQHandler(SAI_HandleTypeDef *hsai); void HAL_SAI_TxHalfCpltCallback(SAI_HandleTypeDef *hsai); void HAL_SAI_TxCpltCallback(SAI_HandleTypeDef *hsai); void HAL_SAI_RxHalfCpltCallback(SAI_HandleTypeDef *hsai); void HAL_SAI_RxCpltCallback(SAI_HandleTypeDef *hsai); void HAL_SAI_ErrorCallback(SAI_HandleTypeDef *hsai); /** * @} */ /** @addtogroup SAI_Exported_Functions_Group3 * @{ */ /* Peripheral State functions **************************************************/ HAL_SAI_StateTypeDef HAL_SAI_GetState(SAI_HandleTypeDef *hsai); uint32_t HAL_SAI_GetError(SAI_HandleTypeDef *hsai); /** * @} */ /** * @} */ /* Private types -------------------------------------------------------------*/ /** @defgroup SAI_Private_Types SAI Private Types * @{ */ /** * @} */ /* Private variables ---------------------------------------------------------*/ /** @defgroup SAI_Private_Variables SAI Private Variables * @{ */ /** * @} */ /* Private constants ---------------------------------------------------------*/ /** @defgroup SAI_Private_Constants SAI Private Constants * @{ */ /** * @} */ /* Private macros ------------------------------------------------------------*/ /** @addtogroup SAI_Private_Macros * @{ */ #define IS_SAI_BLOCK_SYNCEXT(STATE) (((STATE) == SAI_SYNCEXT_DISABLE) ||\ ((STATE) == SAI_SYNCEXT_IN_ENABLE) ||\ ((STATE) == SAI_SYNCEXT_OUTBLOCKA_ENABLE) ||\ ((STATE) == SAI_SYNCEXT_OUTBLOCKB_ENABLE)) #define IS_SAI_SUPPORTED_PROTOCOL(PROTOCOL) (((PROTOCOL) == SAI_I2S_STANDARD) ||\ ((PROTOCOL) == SAI_I2S_MSBJUSTIFIED) ||\ ((PROTOCOL) == SAI_I2S_LSBJUSTIFIED) ||\ ((PROTOCOL) == SAI_PCM_LONG) ||\ ((PROTOCOL) == SAI_PCM_SHORT)) #define IS_SAI_PROTOCOL_DATASIZE(DATASIZE) (((DATASIZE) == SAI_PROTOCOL_DATASIZE_16BIT) ||\ ((DATASIZE) == SAI_PROTOCOL_DATASIZE_16BITEXTENDED) ||\ ((DATASIZE) == SAI_PROTOCOL_DATASIZE_24BIT) ||\ ((DATASIZE) == SAI_PROTOCOL_DATASIZE_32BIT)) #define IS_SAI_CLK_SOURCE(SOURCE) (((SOURCE) == SAI_CLKSOURCE_PLLSAI) ||\ ((SOURCE) == SAI_CLKSOURCE_PLLI2S) ||\ ((SOURCE) == SAI_CLKSOURCE_EXT)) #define IS_SAI_AUDIO_FREQUENCY(AUDIO) (((AUDIO) == SAI_AUDIO_FREQUENCY_192K) || ((AUDIO) == SAI_AUDIO_FREQUENCY_96K) || \ ((AUDIO) == SAI_AUDIO_FREQUENCY_48K) || ((AUDIO) == SAI_AUDIO_FREQUENCY_44K) || \ ((AUDIO) == SAI_AUDIO_FREQUENCY_32K) || ((AUDIO) == SAI_AUDIO_FREQUENCY_22K) || \ ((AUDIO) == SAI_AUDIO_FREQUENCY_16K) || ((AUDIO) == SAI_AUDIO_FREQUENCY_11K) || \ ((AUDIO) == SAI_AUDIO_FREQUENCY_8K) || ((AUDIO) == SAI_AUDIO_FREQUENCY_MCKDIV)) #define IS_SAI_BLOCK_MODE(MODE) (((MODE) == SAI_MODEMASTER_TX) || \ ((MODE) == SAI_MODEMASTER_RX) || \ ((MODE) == SAI_MODESLAVE_TX) || \ ((MODE) == SAI_MODESLAVE_RX)) #define IS_SAI_BLOCK_PROTOCOL(PROTOCOL) (((PROTOCOL) == SAI_FREE_PROTOCOL) || \ ((PROTOCOL) == SAI_AC97_PROTOCOL) || \ ((PROTOCOL) == SAI_SPDIF_PROTOCOL)) #define IS_SAI_BLOCK_DATASIZE(DATASIZE) (((DATASIZE) == SAI_DATASIZE_8) || \ ((DATASIZE) == SAI_DATASIZE_10) || \ ((DATASIZE) == SAI_DATASIZE_16) || \ ((DATASIZE) == SAI_DATASIZE_20) || \ ((DATASIZE) == SAI_DATASIZE_24) || \ ((DATASIZE) == SAI_DATASIZE_32)) #define IS_SAI_BLOCK_FIRST_BIT(BIT) (((BIT) == SAI_FIRSTBIT_MSB) || \ ((BIT) == SAI_FIRSTBIT_LSB)) #define IS_SAI_BLOCK_CLOCK_STROBING(CLOCK) (((CLOCK) == SAI_CLOCKSTROBING_FALLINGEDGE) || \ ((CLOCK) == SAI_CLOCKSTROBING_RISINGEDGE)) #define IS_SAI_BLOCK_SYNCHRO(SYNCHRO) (((SYNCHRO) == SAI_ASYNCHRONOUS) || \ ((SYNCHRO) == SAI_SYNCHRONOUS) || \ ((SYNCHRO) == SAI_SYNCHRONOUS_EXT)) #define IS_SAI_BLOCK_OUTPUT_DRIVE(DRIVE) (((DRIVE) == SAI_OUTPUTDRIVE_DISABLE) || \ ((DRIVE) == SAI_OUTPUTDRIVE_ENABLE)) #define IS_SAI_BLOCK_NODIVIDER(NODIVIDER) (((NODIVIDER) == SAI_MASTERDIVIDER_ENABLE) || \ ((NODIVIDER) == SAI_MASTERDIVIDER_DISABLE)) #define IS_SAI_BLOCK_FIFO_STATUS(STATUS) (((STATUS) == SAI_FIFOSTATUS_LESS1QUARTERFULL ) || \ ((STATUS) == SAI_FIFOSTATUS_HALFFULL) || \ ((STATUS) == SAI_FIFOSTATUS_1QUARTERFULL) || \ ((STATUS) == SAI_FIFOSTATUS_3QUARTERFULL) || \ ((STATUS) == SAI_FIFOSTATUS_FULL) || \ ((STATUS) == SAI_FIFOSTATUS_EMPTY)) #define IS_SAI_BLOCK_MUTE_COUNTER(COUNTER) ((COUNTER) <= 63) #define IS_SAI_BLOCK_MUTE_VALUE(VALUE) (((VALUE) == SAI_ZERO_VALUE) || \ ((VALUE) == SAI_LAST_SENT_VALUE)) #define IS_SAI_BLOCK_COMPANDING_MODE(MODE) (((MODE) == SAI_NOCOMPANDING) || \ ((MODE) == SAI_ULAW_1CPL_COMPANDING) || \ ((MODE) == SAI_ALAW_1CPL_COMPANDING) || \ ((MODE) == SAI_ULAW_2CPL_COMPANDING) || \ ((MODE) == SAI_ALAW_2CPL_COMPANDING)) #define IS_SAI_BLOCK_FIFO_THRESHOLD(THRESHOLD) (((THRESHOLD) == SAI_FIFOTHRESHOLD_EMPTY) || \ ((THRESHOLD) == SAI_FIFOTHRESHOLD_1QF) || \ ((THRESHOLD) == SAI_FIFOTHRESHOLD_HF) || \ ((THRESHOLD) == SAI_FIFOTHRESHOLD_3QF) || \ ((THRESHOLD) == SAI_FIFOTHRESHOLD_FULL)) #define IS_SAI_BLOCK_TRISTATE_MANAGEMENT(STATE) (((STATE) == SAI_OUTPUT_NOTRELEASED) ||\ ((STATE) == SAI_OUTPUT_RELEASED)) #define IS_SAI_MONO_STEREO_MODE(MODE) (((MODE) == SAI_MONOMODE) ||\ ((MODE) == SAI_STEREOMODE)) #define IS_SAI_SLOT_ACTIVE(ACTIVE) ((((ACTIVE) >> 16 ) > 0) && (((ACTIVE) >> 16 ) <= (SAI_SLOTACTIVE_ALL >> 16))) #define IS_SAI_BLOCK_SLOT_NUMBER(NUMBER) ((1 <= (NUMBER)) && ((NUMBER) <= 16)) #define IS_SAI_BLOCK_SLOT_SIZE(SIZE) (((SIZE) == SAI_SLOTSIZE_DATASIZE) || \ ((SIZE) == SAI_SLOTSIZE_16B) || \ ((SIZE) == SAI_SLOTSIZE_32B)) #define IS_SAI_BLOCK_FIRSTBIT_OFFSET(OFFSET) ((OFFSET) <= 24) #define IS_SAI_BLOCK_FS_OFFSET(OFFSET) (((OFFSET) == SAI_FS_FIRSTBIT) || \ ((OFFSET) == SAI_FS_BEFOREFIRSTBIT)) #define IS_SAI_BLOCK_FS_POLARITY(POLARITY) (((POLARITY) == SAI_FS_ACTIVE_LOW) || \ ((POLARITY) == SAI_FS_ACTIVE_HIGH)) #define IS_SAI_BLOCK_FS_DEFINITION(DEFINITION) (((DEFINITION) == SAI_FS_STARTFRAME) || \ ((DEFINITION) == SAI_FS_CHANNEL_IDENTIFICATION)) #define IS_SAI_BLOCK_MASTER_DIVIDER(DIVIDER) ((DIVIDER) <= 15) #define IS_SAI_BLOCK_FRAME_LENGTH(LENGTH) ((8 <= (LENGTH)) && ((LENGTH) <= 256)) #define IS_SAI_BLOCK_ACTIVE_FRAME(LENGTH) ((1 <= (LENGTH)) && ((LENGTH) <= 128)) /** * @} */ /* Private functions ---------------------------------------------------------*/ /** @defgroup SAI_Private_Functions SAI Private Functions * @{ */ /** * @} */ #endif /* STM32F427xx || STM32F437xx || STM32F429xx || STM32F439xx || STM32F446xx || STM32F469xx || STM32F479xx */ /** * @} */ /** * @} */ #ifdef __cplusplus } #endif #endif /* __STM32F4xx_HAL_SAI_H */ /************************ (C) COPYRIGHT STMicroelectronics *****END OF FILE****/ ================================================ FILE: Zelig/mbed/TARGET_NUCLEO_F401RE/stm32f4xx_hal_sai_ex.h ================================================ /** ****************************************************************************** * @file stm32f4xx_hal_sai_ex.h * @author MCD Application Team * @version V1.4.1 * @date 09-October-2015 * @brief Header file of SAI Extension HAL module. ****************************************************************************** * @attention * *

© COPYRIGHT(c) 2015 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. * ****************************************************************************** */ /* Define to prevent recursive inclusion -------------------------------------*/ #ifndef __STM32F4xx_HAL_SAI_EX_H #define __STM32F4xx_HAL_SAI_EX_H #ifdef __cplusplus extern "C" { #endif /* Includes ------------------------------------------------------------------*/ #include "stm32f4xx_hal_def.h" /** @addtogroup STM32F4xx_HAL_Driver * @{ */ /** @addtogroup SAIEx * @{ */ #if defined(STM32F427xx) || defined(STM32F437xx) || defined(STM32F429xx) || defined(STM32F439xx) ||\ defined(STM32F446xx) || defined(STM32F469xx) || defined(STM32F479xx) /* Exported types ------------------------------------------------------------*/ /* Exported constants --------------------------------------------------------*/ /* Exported functions --------------------------------------------------------*/ /** @addtogroup SAIEx_Exported_Functions * @{ */ /** @addtogroup SAIEx_Exported_Functions_Group1 * @{ */ /* Extended features functions ************************************************/ void SAI_BlockSynchroConfig(SAI_HandleTypeDef *hsai); uint32_t SAI_GetInputClock(SAI_HandleTypeDef *hsai); /** * @} */ /** * @} */ /* Private types -------------------------------------------------------------*/ /* Private variables ---------------------------------------------------------*/ /* Private constants ---------------------------------------------------------*/ /* Private macros ------------------------------------------------------------*/ /* Private functions ---------------------------------------------------------*/ #endif /* STM32F427xx || STM32F437xx || STM32F429xx || STM32F439xx || STM32F446xx || STM32F469xx || STM32F479xx */ /** * @} */ /** * @} */ #ifdef __cplusplus } #endif #endif /* __STM32F4xx_HAL_SAI_EX_H */ /************************ (C) COPYRIGHT STMicroelectronics *****END OF FILE****/ ================================================ FILE: Zelig/mbed/TARGET_NUCLEO_F401RE/stm32f4xx_hal_sd.h ================================================ /** ****************************************************************************** * @file stm32f4xx_hal_sd.h * @author MCD Application Team * @version V1.4.1 * @date 09-October-2015 * @brief Header file of SD HAL module. ****************************************************************************** * @attention * *

© COPYRIGHT(c) 2015 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. * ****************************************************************************** */ /* Define to prevent recursive inclusion -------------------------------------*/ #ifndef __STM32F4xx_HAL_SD_H #define __STM32F4xx_HAL_SD_H #ifdef __cplusplus extern "C" { #endif #if defined(STM32F405xx) || defined(STM32F415xx) || defined(STM32F407xx) || defined(STM32F417xx) || \ defined(STM32F427xx) || defined(STM32F437xx) || defined(STM32F429xx) || defined(STM32F439xx) || \ defined(STM32F401xC) || defined(STM32F401xE) || defined(STM32F411xE) || defined(STM32F446xx) || \ defined(STM32F469xx) || defined(STM32F479xx) /* Includes ------------------------------------------------------------------*/ #include "stm32f4xx_ll_sdmmc.h" /** @addtogroup STM32F4xx_HAL_Driver * @{ */ /** @defgroup SD SD * @brief SD HAL module driver * @{ */ /* Exported types ------------------------------------------------------------*/ /** @defgroup SD_Exported_Types SD Exported Types * @{ */ /** @defgroup SD_Exported_Types_Group1 SD Handle Structure definition * @{ */ #define SD_InitTypeDef SDIO_InitTypeDef #define SD_TypeDef SDIO_TypeDef typedef struct { SD_TypeDef *Instance; /*!< SDIO register base address */ SD_InitTypeDef Init; /*!< SD required parameters */ HAL_LockTypeDef Lock; /*!< SD locking object */ uint32_t CardType; /*!< SD card type */ uint32_t RCA; /*!< SD relative card address */ uint32_t CSD[4]; /*!< SD card specific data table */ uint32_t CID[4]; /*!< SD card identification number table */ __IO uint32_t SdTransferCplt; /*!< SD transfer complete flag in non blocking mode */ __IO uint32_t SdTransferErr; /*!< SD transfer error flag in non blocking mode */ __IO uint32_t DmaTransferCplt; /*!< SD DMA transfer complete flag */ __IO uint32_t SdOperation; /*!< SD transfer operation (read/write) */ DMA_HandleTypeDef *hdmarx; /*!< SD Rx DMA handle parameters */ DMA_HandleTypeDef *hdmatx; /*!< SD Tx DMA handle parameters */ }SD_HandleTypeDef; /** * @} */ /** @defgroup SD_Exported_Types_Group2 Card Specific Data: CSD Register * @{ */ typedef struct { __IO uint8_t CSDStruct; /*!< CSD structure */ __IO uint8_t SysSpecVersion; /*!< System specification version */ __IO uint8_t Reserved1; /*!< Reserved */ __IO uint8_t TAAC; /*!< Data read access time 1 */ __IO uint8_t NSAC; /*!< Data read access time 2 in CLK cycles */ __IO uint8_t MaxBusClkFrec; /*!< Max. bus clock frequency */ __IO uint16_t CardComdClasses; /*!< Card command classes */ __IO uint8_t RdBlockLen; /*!< Max. read data block length */ __IO uint8_t PartBlockRead; /*!< Partial blocks for read allowed */ __IO uint8_t WrBlockMisalign; /*!< Write block misalignment */ __IO uint8_t RdBlockMisalign; /*!< Read block misalignment */ __IO uint8_t DSRImpl; /*!< DSR implemented */ __IO uint8_t Reserved2; /*!< Reserved */ __IO uint32_t DeviceSize; /*!< Device Size */ __IO uint8_t MaxRdCurrentVDDMin; /*!< Max. read current @ VDD min */ __IO uint8_t MaxRdCurrentVDDMax; /*!< Max. read current @ VDD max */ __IO uint8_t MaxWrCurrentVDDMin; /*!< Max. write current @ VDD min */ __IO uint8_t MaxWrCurrentVDDMax; /*!< Max. write current @ VDD max */ __IO uint8_t DeviceSizeMul; /*!< Device size multiplier */ __IO uint8_t EraseGrSize; /*!< Erase group size */ __IO uint8_t EraseGrMul; /*!< Erase group size multiplier */ __IO uint8_t WrProtectGrSize; /*!< Write protect group size */ __IO uint8_t WrProtectGrEnable; /*!< Write protect group enable */ __IO uint8_t ManDeflECC; /*!< Manufacturer default ECC */ __IO uint8_t WrSpeedFact; /*!< Write speed factor */ __IO uint8_t MaxWrBlockLen; /*!< Max. write data block length */ __IO uint8_t WriteBlockPaPartial; /*!< Partial blocks for write allowed */ __IO uint8_t Reserved3; /*!< Reserved */ __IO uint8_t ContentProtectAppli; /*!< Content protection application */ __IO uint8_t FileFormatGrouop; /*!< File format group */ __IO uint8_t CopyFlag; /*!< Copy flag (OTP) */ __IO uint8_t PermWrProtect; /*!< Permanent write protection */ __IO uint8_t TempWrProtect; /*!< Temporary write protection */ __IO uint8_t FileFormat; /*!< File format */ __IO uint8_t ECC; /*!< ECC code */ __IO uint8_t CSD_CRC; /*!< CSD CRC */ __IO uint8_t Reserved4; /*!< Always 1 */ }HAL_SD_CSDTypedef; /** * @} */ /** @defgroup SD_Exported_Types_Group3 Card Identification Data: CID Register * @{ */ typedef struct { __IO uint8_t ManufacturerID; /*!< Manufacturer ID */ __IO uint16_t OEM_AppliID; /*!< OEM/Application ID */ __IO uint32_t ProdName1; /*!< Product Name part1 */ __IO uint8_t ProdName2; /*!< Product Name part2 */ __IO uint8_t ProdRev; /*!< Product Revision */ __IO uint32_t ProdSN; /*!< Product Serial Number */ __IO uint8_t Reserved1; /*!< Reserved1 */ __IO uint16_t ManufactDate; /*!< Manufacturing Date */ __IO uint8_t CID_CRC; /*!< CID CRC */ __IO uint8_t Reserved2; /*!< Always 1 */ }HAL_SD_CIDTypedef; /** * @} */ /** @defgroup SD_Exported_Types_Group4 SD Card Status returned by ACMD13 * @{ */ typedef struct { __IO uint8_t DAT_BUS_WIDTH; /*!< Shows the currently defined data bus width */ __IO uint8_t SECURED_MODE; /*!< Card is in secured mode of operation */ __IO uint16_t SD_CARD_TYPE; /*!< Carries information about card type */ __IO uint32_t SIZE_OF_PROTECTED_AREA; /*!< Carries information about the capacity of protected area */ __IO uint8_t SPEED_CLASS; /*!< Carries information about the speed class of the card */ __IO uint8_t PERFORMANCE_MOVE; /*!< Carries information about the card's performance move */ __IO uint8_t AU_SIZE; /*!< Carries information about the card's allocation unit size */ __IO uint16_t ERASE_SIZE; /*!< Determines the number of AUs to be erased in one operation */ __IO uint8_t ERASE_TIMEOUT; /*!< Determines the timeout for any number of AU erase */ __IO uint8_t ERASE_OFFSET; /*!< Carries information about the erase offset */ }HAL_SD_CardStatusTypedef; /** * @} */ /** @defgroup SD_Exported_Types_Group5 SD Card information structure * @{ */ typedef struct { HAL_SD_CSDTypedef SD_csd; /*!< SD card specific data register */ HAL_SD_CIDTypedef SD_cid; /*!< SD card identification number register */ uint64_t CardCapacity; /*!< Card capacity */ uint32_t CardBlockSize; /*!< Card block size */ uint16_t RCA; /*!< SD relative card address */ uint8_t CardType; /*!< SD card type */ }HAL_SD_CardInfoTypedef; /** * @} */ /** @defgroup SD_Exported_Types_Group6 SD Error status enumeration Structure definition * @{ */ typedef enum { /** * @brief SD specific error defines */ SD_CMD_CRC_FAIL = (1), /*!< Command response received (but CRC check failed) */ SD_DATA_CRC_FAIL = (2), /*!< Data block sent/received (CRC check failed) */ SD_CMD_RSP_TIMEOUT = (3), /*!< Command response timeout */ SD_DATA_TIMEOUT = (4), /*!< Data timeout */ SD_TX_UNDERRUN = (5), /*!< Transmit FIFO underrun */ SD_RX_OVERRUN = (6), /*!< Receive FIFO overrun */ SD_START_BIT_ERR = (7), /*!< Start bit not detected on all data signals in wide bus mode */ SD_CMD_OUT_OF_RANGE = (8), /*!< Command's argument was out of range. */ SD_ADDR_MISALIGNED = (9), /*!< Misaligned address */ SD_BLOCK_LEN_ERR = (10), /*!< Transferred block length is not allowed for the card or the number of transferred bytes does not match the block length */ SD_ERASE_SEQ_ERR = (11), /*!< An error in the sequence of erase command occurs. */ SD_BAD_ERASE_PARAM = (12), /*!< An invalid selection for erase groups */ SD_WRITE_PROT_VIOLATION = (13), /*!< Attempt to program a write protect block */ SD_LOCK_UNLOCK_FAILED = (14), /*!< Sequence or password error has been detected in unlock command or if there was an attempt to access a locked card */ SD_COM_CRC_FAILED = (15), /*!< CRC check of the previous command failed */ SD_ILLEGAL_CMD = (16), /*!< Command is not legal for the card state */ SD_CARD_ECC_FAILED = (17), /*!< Card internal ECC was applied but failed to correct the data */ SD_CC_ERROR = (18), /*!< Internal card controller error */ SD_GENERAL_UNKNOWN_ERROR = (19), /*!< General or unknown error */ SD_STREAM_READ_UNDERRUN = (20), /*!< The card could not sustain data transfer in stream read operation. */ SD_STREAM_WRITE_OVERRUN = (21), /*!< The card could not sustain data programming in stream mode */ SD_CID_CSD_OVERWRITE = (22), /*!< CID/CSD overwrite error */ SD_WP_ERASE_SKIP = (23), /*!< Only partial address space was erased */ SD_CARD_ECC_DISABLED = (24), /*!< Command has been executed without using internal ECC */ SD_ERASE_RESET = (25), /*!< Erase sequence was cleared before executing because an out of erase sequence command was received */ SD_AKE_SEQ_ERROR = (26), /*!< Error in sequence of authentication. */ SD_INVALID_VOLTRANGE = (27), SD_ADDR_OUT_OF_RANGE = (28), SD_SWITCH_ERROR = (29), SD_SDIO_DISABLED = (30), SD_SDIO_FUNCTION_BUSY = (31), SD_SDIO_FUNCTION_FAILED = (32), SD_SDIO_UNKNOWN_FUNCTION = (33), /** * @brief Standard error defines */ SD_INTERNAL_ERROR = (34), SD_NOT_CONFIGURED = (35), SD_REQUEST_PENDING = (36), SD_REQUEST_NOT_APPLICABLE = (37), SD_INVALID_PARAMETER = (38), SD_UNSUPPORTED_FEATURE = (39), SD_UNSUPPORTED_HW = (40), SD_ERROR = (41), SD_OK = (0) }HAL_SD_ErrorTypedef; /** * @} */ /** @defgroup SD_Exported_Types_Group7 SD Transfer state enumeration structure * @{ */ typedef enum { SD_TRANSFER_OK = 0, /*!< Transfer success */ SD_TRANSFER_BUSY = 1, /*!< Transfer is occurring */ SD_TRANSFER_ERROR = 2 /*!< Transfer failed */ }HAL_SD_TransferStateTypedef; /** * @} */ /** @defgroup SD_Exported_Types_Group8 SD Card State enumeration structure * @{ */ typedef enum { SD_CARD_READY = ((uint32_t)0x00000001), /*!< Card state is ready */ SD_CARD_IDENTIFICATION = ((uint32_t)0x00000002), /*!< Card is in identification state */ SD_CARD_STANDBY = ((uint32_t)0x00000003), /*!< Card is in standby state */ SD_CARD_TRANSFER = ((uint32_t)0x00000004), /*!< Card is in transfer state */ SD_CARD_SENDING = ((uint32_t)0x00000005), /*!< Card is sending an operation */ SD_CARD_RECEIVING = ((uint32_t)0x00000006), /*!< Card is receiving operation information */ SD_CARD_PROGRAMMING = ((uint32_t)0x00000007), /*!< Card is in programming state */ SD_CARD_DISCONNECTED = ((uint32_t)0x00000008), /*!< Card is disconnected */ SD_CARD_ERROR = ((uint32_t)0x000000FF) /*!< Card is in error state */ }HAL_SD_CardStateTypedef; /** * @} */ /** @defgroup SD_Exported_Types_Group9 SD Operation enumeration structure * @{ */ typedef enum { SD_READ_SINGLE_BLOCK = 0, /*!< Read single block operation */ SD_READ_MULTIPLE_BLOCK = 1, /*!< Read multiple blocks operation */ SD_WRITE_SINGLE_BLOCK = 2, /*!< Write single block operation */ SD_WRITE_MULTIPLE_BLOCK = 3 /*!< Write multiple blocks operation */ }HAL_SD_OperationTypedef; /** * @} */ /** * @} */ /* Exported constants --------------------------------------------------------*/ /** @defgroup SD_Exported_Constants SD Exported Constants * @{ */ /** * @brief SD Commands Index */ #define SD_CMD_GO_IDLE_STATE ((uint8_t)0) /*!< Resets the SD memory card. */ #define SD_CMD_SEND_OP_COND ((uint8_t)1) /*!< Sends host capacity support information and activates the card's initialization process. */ #define SD_CMD_ALL_SEND_CID ((uint8_t)2) /*!< Asks any card connected to the host to send the CID numbers on the CMD line. */ #define SD_CMD_SET_REL_ADDR ((uint8_t)3) /*!< Asks the card to publish a new relative address (RCA). */ #define SD_CMD_SET_DSR ((uint8_t)4) /*!< Programs the DSR of all cards. */ #define SD_CMD_SDIO_SEN_OP_COND ((uint8_t)5) /*!< Sends host capacity support information (HCS) and asks the accessed card to send its operating condition register (OCR) content in the response on the CMD line. */ #define SD_CMD_HS_SWITCH ((uint8_t)6) /*!< Checks switchable function (mode 0) and switch card function (mode 1). */ #define SD_CMD_SEL_DESEL_CARD ((uint8_t)7) /*!< Selects the card by its own relative address and gets deselected by any other address */ #define SD_CMD_HS_SEND_EXT_CSD ((uint8_t)8) /*!< Sends SD Memory Card interface condition, which includes host supply voltage information and asks the card whether card supports voltage. */ #define SD_CMD_SEND_CSD ((uint8_t)9) /*!< Addressed card sends its card specific data (CSD) on the CMD line. */ #define SD_CMD_SEND_CID ((uint8_t)10) /*!< Addressed card sends its card identification (CID) on the CMD line. */ #define SD_CMD_READ_DAT_UNTIL_STOP ((uint8_t)11) /*!< SD card doesn't support it. */ #define SD_CMD_STOP_TRANSMISSION ((uint8_t)12) /*!< Forces the card to stop transmission. */ #define SD_CMD_SEND_STATUS ((uint8_t)13) /*!< Addressed card sends its status register. */ #define SD_CMD_HS_BUSTEST_READ ((uint8_t)14) #define SD_CMD_GO_INACTIVE_STATE ((uint8_t)15) /*!< Sends an addressed card into the inactive state. */ #define SD_CMD_SET_BLOCKLEN ((uint8_t)16) /*!< Sets the block length (in bytes for SDSC) for all following block commands (read, write, lock). Default block length is fixed to 512 Bytes. Not effective for SDHS and SDXC. */ #define SD_CMD_READ_SINGLE_BLOCK ((uint8_t)17) /*!< Reads single block of size selected by SET_BLOCKLEN in case of SDSC, and a block of fixed 512 bytes in case of SDHC and SDXC. */ #define SD_CMD_READ_MULT_BLOCK ((uint8_t)18) /*!< Continuously transfers data blocks from card to host until interrupted by STOP_TRANSMISSION command. */ #define SD_CMD_HS_BUSTEST_WRITE ((uint8_t)19) /*!< 64 bytes tuning pattern is sent for SDR50 and SDR104. */ #define SD_CMD_WRITE_DAT_UNTIL_STOP ((uint8_t)20) /*!< Speed class control command. */ #define SD_CMD_SET_BLOCK_COUNT ((uint8_t)23) /*!< Specify block count for CMD18 and CMD25. */ #define SD_CMD_WRITE_SINGLE_BLOCK ((uint8_t)24) /*!< Writes single block of size selected by SET_BLOCKLEN in case of SDSC, and a block of fixed 512 bytes in case of SDHC and SDXC. */ #define SD_CMD_WRITE_MULT_BLOCK ((uint8_t)25) /*!< Continuously writes blocks of data until a STOP_TRANSMISSION follows. */ #define SD_CMD_PROG_CID ((uint8_t)26) /*!< Reserved for manufacturers. */ #define SD_CMD_PROG_CSD ((uint8_t)27) /*!< Programming of the programmable bits of the CSD. */ #define SD_CMD_SET_WRITE_PROT ((uint8_t)28) /*!< Sets the write protection bit of the addressed group. */ #define SD_CMD_CLR_WRITE_PROT ((uint8_t)29) /*!< Clears the write protection bit of the addressed group. */ #define SD_CMD_SEND_WRITE_PROT ((uint8_t)30) /*!< Asks the card to send the status of the write protection bits. */ #define SD_CMD_SD_ERASE_GRP_START ((uint8_t)32) /*!< Sets the address of the first write block to be erased. (For SD card only). */ #define SD_CMD_SD_ERASE_GRP_END ((uint8_t)33) /*!< Sets the address of the last write block of the continuous range to be erased. */ #define SD_CMD_ERASE_GRP_START ((uint8_t)35) /*!< Sets the address of the first write block to be erased. Reserved for each command system set by switch function command (CMD6). */ #define SD_CMD_ERASE_GRP_END ((uint8_t)36) /*!< Sets the address of the last write block of the continuous range to be erased. Reserved for each command system set by switch function command (CMD6). */ #define SD_CMD_ERASE ((uint8_t)38) /*!< Reserved for SD security applications. */ #define SD_CMD_FAST_IO ((uint8_t)39) /*!< SD card doesn't support it (Reserved). */ #define SD_CMD_GO_IRQ_STATE ((uint8_t)40) /*!< SD card doesn't support it (Reserved). */ #define SD_CMD_LOCK_UNLOCK ((uint8_t)42) /*!< Sets/resets the password or lock/unlock the card. The size of the data block is set by the SET_BLOCK_LEN command. */ #define SD_CMD_APP_CMD ((uint8_t)55) /*!< Indicates to the card that the next command is an application specific command rather than a standard command. */ #define SD_CMD_GEN_CMD ((uint8_t)56) /*!< Used either to transfer a data block to the card or to get a data block from the card for general purpose/application specific commands. */ #define SD_CMD_NO_CMD ((uint8_t)64) /** * @brief Following commands are SD Card Specific commands. * SDIO_APP_CMD should be sent before sending these commands. */ #define SD_CMD_APP_SD_SET_BUSWIDTH ((uint8_t)6) /*!< (ACMD6) Defines the data bus width to be used for data transfer. The allowed data bus widths are given in SCR register. */ #define SD_CMD_SD_APP_STATUS ((uint8_t)13) /*!< (ACMD13) Sends the SD status. */ #define SD_CMD_SD_APP_SEND_NUM_WRITE_BLOCKS ((uint8_t)22) /*!< (ACMD22) Sends the number of the written (without errors) write blocks. Responds with 32bit+CRC data block. */ #define SD_CMD_SD_APP_OP_COND ((uint8_t)41) /*!< (ACMD41) Sends host capacity support information (HCS) and asks the accessed card to send its operating condition register (OCR) content in the response on the CMD line. */ #define SD_CMD_SD_APP_SET_CLR_CARD_DETECT ((uint8_t)42) /*!< (ACMD42) Connects/Disconnects the 50 KOhm pull-up resistor on CD/DAT3 (pin 1) of the card. */ #define SD_CMD_SD_APP_SEND_SCR ((uint8_t)51) /*!< Reads the SD Configuration Register (SCR). */ #define SD_CMD_SDIO_RW_DIRECT ((uint8_t)52) /*!< For SD I/O card only, reserved for security specification. */ #define SD_CMD_SDIO_RW_EXTENDED ((uint8_t)53) /*!< For SD I/O card only, reserved for security specification. */ /** * @brief Following commands are SD Card Specific security commands. * SD_CMD_APP_CMD should be sent before sending these commands. */ #define SD_CMD_SD_APP_GET_MKB ((uint8_t)43) /*!< For SD card only */ #define SD_CMD_SD_APP_GET_MID ((uint8_t)44) /*!< For SD card only */ #define SD_CMD_SD_APP_SET_CER_RN1 ((uint8_t)45) /*!< For SD card only */ #define SD_CMD_SD_APP_GET_CER_RN2 ((uint8_t)46) /*!< For SD card only */ #define SD_CMD_SD_APP_SET_CER_RES2 ((uint8_t)47) /*!< For SD card only */ #define SD_CMD_SD_APP_GET_CER_RES1 ((uint8_t)48) /*!< For SD card only */ #define SD_CMD_SD_APP_SECURE_READ_MULTIPLE_BLOCK ((uint8_t)18) /*!< For SD card only */ #define SD_CMD_SD_APP_SECURE_WRITE_MULTIPLE_BLOCK ((uint8_t)25) /*!< For SD card only */ #define SD_CMD_SD_APP_SECURE_ERASE ((uint8_t)38) /*!< For SD card only */ #define SD_CMD_SD_APP_CHANGE_SECURE_AREA ((uint8_t)49) /*!< For SD card only */ #define SD_CMD_SD_APP_SECURE_WRITE_MKB ((uint8_t)48) /*!< For SD card only */ /** * @brief Supported SD Memory Cards */ #define STD_CAPACITY_SD_CARD_V1_1 ((uint32_t)0x00000000) #define STD_CAPACITY_SD_CARD_V2_0 ((uint32_t)0x00000001) #define HIGH_CAPACITY_SD_CARD ((uint32_t)0x00000002) #define MULTIMEDIA_CARD ((uint32_t)0x00000003) #define SECURE_DIGITAL_IO_CARD ((uint32_t)0x00000004) #define HIGH_SPEED_MULTIMEDIA_CARD ((uint32_t)0x00000005) #define SECURE_DIGITAL_IO_COMBO_CARD ((uint32_t)0x00000006) #define HIGH_CAPACITY_MMC_CARD ((uint32_t)0x00000007) /** * @} */ /* Exported macro ------------------------------------------------------------*/ /** @defgroup SD_Exported_macros SD Exported Macros * @brief macros to handle interrupts and specific clock configurations * @{ */ /** * @brief Enable the SD device. * @retval None */ #define __HAL_SD_SDIO_ENABLE() __SDIO_ENABLE() /** * @brief Disable the SD device. * @retval None */ #define __HAL_SD_SDIO_DISABLE() __SDIO_DISABLE() /** * @brief Enable the SDIO DMA transfer. * @retval None */ #define __HAL_SD_SDIO_DMA_ENABLE() __SDIO_DMA_ENABLE() /** * @brief Disable the SDIO DMA transfer. * @retval None */ #define __HAL_SD_SDIO_DMA_DISABLE() __SDIO_DMA_DISABLE() /** * @brief Enable the SD device interrupt. * @param __HANDLE__: SD Handle * @param __INTERRUPT__: specifies the SDIO interrupt sources to be enabled. * This parameter can be one or a combination of the following values: * @arg SDIO_IT_CCRCFAIL: Command response received (CRC check failed) interrupt * @arg SDIO_IT_DCRCFAIL: Data block sent/received (CRC check failed) interrupt * @arg SDIO_IT_CTIMEOUT: Command response timeout interrupt * @arg SDIO_IT_DTIMEOUT: Data timeout interrupt * @arg SDIO_IT_TXUNDERR: Transmit FIFO underrun error interrupt * @arg SDIO_IT_RXOVERR: Received FIFO overrun error interrupt * @arg SDIO_IT_CMDREND: Command response received (CRC check passed) interrupt * @arg SDIO_IT_CMDSENT: Command sent (no response required) interrupt * @arg SDIO_IT_DATAEND: Data end (data counter, SDIDCOUNT, is zero) interrupt * @arg SDIO_IT_STBITERR: Start bit not detected on all data signals in wide * bus mode interrupt * @arg SDIO_IT_DBCKEND: Data block sent/received (CRC check passed) interrupt * @arg SDIO_IT_CMDACT: Command transfer in progress interrupt * @arg SDIO_IT_TXACT: Data transmit in progress interrupt * @arg SDIO_IT_RXACT: Data receive in progress interrupt * @arg SDIO_IT_TXFIFOHE: Transmit FIFO Half Empty interrupt * @arg SDIO_IT_RXFIFOHF: Receive FIFO Half Full interrupt * @arg SDIO_IT_TXFIFOF: Transmit FIFO full interrupt * @arg SDIO_IT_RXFIFOF: Receive FIFO full interrupt * @arg SDIO_IT_TXFIFOE: Transmit FIFO empty interrupt * @arg SDIO_IT_RXFIFOE: Receive FIFO empty interrupt * @arg SDIO_IT_TXDAVL: Data available in transmit FIFO interrupt * @arg SDIO_IT_RXDAVL: Data available in receive FIFO interrupt * @arg SDIO_IT_SDIOIT: SD I/O interrupt received interrupt * @arg SDIO_IT_CEATAEND: CE-ATA command completion signal received for CMD61 interrupt * @retval None */ #define __HAL_SD_SDIO_ENABLE_IT(__HANDLE__, __INTERRUPT__) __SDIO_ENABLE_IT((__HANDLE__)->Instance, (__INTERRUPT__)) /** * @brief Disable the SD device interrupt. * @param __HANDLE__: SD Handle * @param __INTERRUPT__: specifies the SDIO interrupt sources to be disabled. * This parameter can be one or a combination of the following values: * @arg SDIO_IT_CCRCFAIL: Command response received (CRC check failed) interrupt * @arg SDIO_IT_DCRCFAIL: Data block sent/received (CRC check failed) interrupt * @arg SDIO_IT_CTIMEOUT: Command response timeout interrupt * @arg SDIO_IT_DTIMEOUT: Data timeout interrupt * @arg SDIO_IT_TXUNDERR: Transmit FIFO underrun error interrupt * @arg SDIO_IT_RXOVERR: Received FIFO overrun error interrupt * @arg SDIO_IT_CMDREND: Command response received (CRC check passed) interrupt * @arg SDIO_IT_CMDSENT: Command sent (no response required) interrupt * @arg SDIO_IT_DATAEND: Data end (data counter, SDIDCOUNT, is zero) interrupt * @arg SDIO_IT_STBITERR: Start bit not detected on all data signals in wide * bus mode interrupt * @arg SDIO_IT_DBCKEND: Data block sent/received (CRC check passed) interrupt * @arg SDIO_IT_CMDACT: Command transfer in progress interrupt * @arg SDIO_IT_TXACT: Data transmit in progress interrupt * @arg SDIO_IT_RXACT: Data receive in progress interrupt * @arg SDIO_IT_TXFIFOHE: Transmit FIFO Half Empty interrupt * @arg SDIO_IT_RXFIFOHF: Receive FIFO Half Full interrupt * @arg SDIO_IT_TXFIFOF: Transmit FIFO full interrupt * @arg SDIO_IT_RXFIFOF: Receive FIFO full interrupt * @arg SDIO_IT_TXFIFOE: Transmit FIFO empty interrupt * @arg SDIO_IT_RXFIFOE: Receive FIFO empty interrupt * @arg SDIO_IT_TXDAVL: Data available in transmit FIFO interrupt * @arg SDIO_IT_RXDAVL: Data available in receive FIFO interrupt * @arg SDIO_IT_SDIOIT: SD I/O interrupt received interrupt * @arg SDIO_IT_CEATAEND: CE-ATA command completion signal received for CMD61 interrupt * @retval None */ #define __HAL_SD_SDIO_DISABLE_IT(__HANDLE__, __INTERRUPT__) __SDIO_DISABLE_IT((__HANDLE__)->Instance, (__INTERRUPT__)) /** * @brief Check whether the specified SD flag is set or not. * @param __HANDLE__: SD Handle * @param __FLAG__: specifies the flag to check. * This parameter can be one of the following values: * @arg SDIO_FLAG_CCRCFAIL: Command response received (CRC check failed) * @arg SDIO_FLAG_DCRCFAIL: Data block sent/received (CRC check failed) * @arg SDIO_FLAG_CTIMEOUT: Command response timeout * @arg SDIO_FLAG_DTIMEOUT: Data timeout * @arg SDIO_FLAG_TXUNDERR: Transmit FIFO underrun error * @arg SDIO_FLAG_RXOVERR: Received FIFO overrun error * @arg SDIO_FLAG_CMDREND: Command response received (CRC check passed) * @arg SDIO_FLAG_CMDSENT: Command sent (no response required) * @arg SDIO_FLAG_DATAEND: Data end (data counter, SDIDCOUNT, is zero) * @arg SDIO_FLAG_STBITERR: Start bit not detected on all data signals in wide bus mode. * @arg SDIO_FLAG_DBCKEND: Data block sent/received (CRC check passed) * @arg SDIO_FLAG_CMDACT: Command transfer in progress * @arg SDIO_FLAG_TXACT: Data transmit in progress * @arg SDIO_FLAG_RXACT: Data receive in progress * @arg SDIO_FLAG_TXFIFOHE: Transmit FIFO Half Empty * @arg SDIO_FLAG_RXFIFOHF: Receive FIFO Half Full * @arg SDIO_FLAG_TXFIFOF: Transmit FIFO full * @arg SDIO_FLAG_RXFIFOF: Receive FIFO full * @arg SDIO_FLAG_TXFIFOE: Transmit FIFO empty * @arg SDIO_FLAG_RXFIFOE: Receive FIFO empty * @arg SDIO_FLAG_TXDAVL: Data available in transmit FIFO * @arg SDIO_FLAG_RXDAVL: Data available in receive FIFO * @arg SDIO_FLAG_SDIOIT: SD I/O interrupt received * @arg SDIO_FLAG_CEATAEND: CE-ATA command completion signal received for CMD61 * @retval The new state of SD FLAG (SET or RESET). */ #define __HAL_SD_SDIO_GET_FLAG(__HANDLE__, __FLAG__) __SDIO_GET_FLAG((__HANDLE__)->Instance, (__FLAG__)) /** * @brief Clear the SD's pending flags. * @param __HANDLE__: SD Handle * @param __FLAG__: specifies the flag to clear. * This parameter can be one or a combination of the following values: * @arg SDIO_FLAG_CCRCFAIL: Command response received (CRC check failed) * @arg SDIO_FLAG_DCRCFAIL: Data block sent/received (CRC check failed) * @arg SDIO_FLAG_CTIMEOUT: Command response timeout * @arg SDIO_FLAG_DTIMEOUT: Data timeout * @arg SDIO_FLAG_TXUNDERR: Transmit FIFO underrun error * @arg SDIO_FLAG_RXOVERR: Received FIFO overrun error * @arg SDIO_FLAG_CMDREND: Command response received (CRC check passed) * @arg SDIO_FLAG_CMDSENT: Command sent (no response required) * @arg SDIO_FLAG_DATAEND: Data end (data counter, SDIDCOUNT, is zero) * @arg SDIO_FLAG_STBITERR: Start bit not detected on all data signals in wide bus mode * @arg SDIO_FLAG_DBCKEND: Data block sent/received (CRC check passed) * @arg SDIO_FLAG_SDIOIT: SD I/O interrupt received * @arg SDIO_FLAG_CEATAEND: CE-ATA command completion signal received for CMD61 * @retval None */ #define __HAL_SD_SDIO_CLEAR_FLAG(__HANDLE__, __FLAG__) __SDIO_CLEAR_FLAG((__HANDLE__)->Instance, (__FLAG__)) /** * @brief Check whether the specified SD interrupt has occurred or not. * @param __HANDLE__: SD Handle * @param __INTERRUPT__: specifies the SDIO interrupt source to check. * This parameter can be one of the following values: * @arg SDIO_IT_CCRCFAIL: Command response received (CRC check failed) interrupt * @arg SDIO_IT_DCRCFAIL: Data block sent/received (CRC check failed) interrupt * @arg SDIO_IT_CTIMEOUT: Command response timeout interrupt * @arg SDIO_IT_DTIMEOUT: Data timeout interrupt * @arg SDIO_IT_TXUNDERR: Transmit FIFO underrun error interrupt * @arg SDIO_IT_RXOVERR: Received FIFO overrun error interrupt * @arg SDIO_IT_CMDREND: Command response received (CRC check passed) interrupt * @arg SDIO_IT_CMDSENT: Command sent (no response required) interrupt * @arg SDIO_IT_DATAEND: Data end (data counter, SDIDCOUNT, is zero) interrupt * @arg SDIO_IT_STBITERR: Start bit not detected on all data signals in wide * bus mode interrupt * @arg SDIO_IT_DBCKEND: Data block sent/received (CRC check passed) interrupt * @arg SDIO_IT_CMDACT: Command transfer in progress interrupt * @arg SDIO_IT_TXACT: Data transmit in progress interrupt * @arg SDIO_IT_RXACT: Data receive in progress interrupt * @arg SDIO_IT_TXFIFOHE: Transmit FIFO Half Empty interrupt * @arg SDIO_IT_RXFIFOHF: Receive FIFO Half Full interrupt * @arg SDIO_IT_TXFIFOF: Transmit FIFO full interrupt * @arg SDIO_IT_RXFIFOF: Receive FIFO full interrupt * @arg SDIO_IT_TXFIFOE: Transmit FIFO empty interrupt * @arg SDIO_IT_RXFIFOE: Receive FIFO empty interrupt * @arg SDIO_IT_TXDAVL: Data available in transmit FIFO interrupt * @arg SDIO_IT_RXDAVL: Data available in receive FIFO interrupt * @arg SDIO_IT_SDIOIT: SD I/O interrupt received interrupt * @arg SDIO_IT_CEATAEND: CE-ATA command completion signal received for CMD61 interrupt * @retval The new state of SD IT (SET or RESET). */ #define __HAL_SD_SDIO_GET_IT (__HANDLE__, __INTERRUPT__) __SDIO_GET_IT ((__HANDLE__)->Instance, __INTERRUPT__) /** * @brief Clear the SD's interrupt pending bits. * @param __HANDLE__ : SD Handle * @param __INTERRUPT__: specifies the interrupt pending bit to clear. * This parameter can be one or a combination of the following values: * @arg SDIO_IT_CCRCFAIL: Command response received (CRC check failed) interrupt * @arg SDIO_IT_DCRCFAIL: Data block sent/received (CRC check failed) interrupt * @arg SDIO_IT_CTIMEOUT: Command response timeout interrupt * @arg SDIO_IT_DTIMEOUT: Data timeout interrupt * @arg SDIO_IT_TXUNDERR: Transmit FIFO underrun error interrupt * @arg SDIO_IT_RXOVERR: Received FIFO overrun error interrupt * @arg SDIO_IT_CMDREND: Command response received (CRC check passed) interrupt * @arg SDIO_IT_CMDSENT: Command sent (no response required) interrupt * @arg SDIO_IT_DATAEND: Data end (data counter, SDIO_DCOUNT, is zero) interrupt * @arg SDIO_IT_STBITERR: Start bit not detected on all data signals in wide * bus mode interrupt * @arg SDIO_IT_SDIOIT: SD I/O interrupt received interrupt * @arg SDIO_IT_CEATAEND: CE-ATA command completion signal received for CMD61 * @retval None */ #define __HAL_SD_SDIO_CLEAR_IT(__HANDLE__, __INTERRUPT__) __SDIO_CLEAR_IT((__HANDLE__)->Instance, (__INTERRUPT__)) /** * @} */ /* Exported functions --------------------------------------------------------*/ /** @defgroup SD_Exported_Functions SD Exported Functions * @{ */ /** @defgroup SD_Exported_Functions_Group1 Initialization and de-initialization functions * @{ */ HAL_SD_ErrorTypedef HAL_SD_Init(SD_HandleTypeDef *hsd, HAL_SD_CardInfoTypedef *SDCardInfo); HAL_StatusTypeDef HAL_SD_DeInit (SD_HandleTypeDef *hsd); void HAL_SD_MspInit(SD_HandleTypeDef *hsd); void HAL_SD_MspDeInit(SD_HandleTypeDef *hsd); /** * @} */ /** @defgroup SD_Exported_Functions_Group2 I/O operation functions * @{ */ /* Blocking mode: Polling */ HAL_SD_ErrorTypedef HAL_SD_ReadBlocks(SD_HandleTypeDef *hsd, uint32_t *pReadBuffer, uint64_t ReadAddr, uint32_t BlockSize, uint32_t NumberOfBlocks); HAL_SD_ErrorTypedef HAL_SD_WriteBlocks(SD_HandleTypeDef *hsd, uint32_t *pWriteBuffer, uint64_t WriteAddr, uint32_t BlockSize, uint32_t NumberOfBlocks); HAL_SD_ErrorTypedef HAL_SD_Erase(SD_HandleTypeDef *hsd, uint64_t startaddr, uint64_t endaddr); /* Non-Blocking mode: Interrupt */ void HAL_SD_IRQHandler(SD_HandleTypeDef *hsd); /* Callback in non blocking modes (DMA) */ void HAL_SD_DMA_RxCpltCallback(DMA_HandleTypeDef *hdma); void HAL_SD_DMA_RxErrorCallback(DMA_HandleTypeDef *hdma); void HAL_SD_DMA_TxCpltCallback(DMA_HandleTypeDef *hdma); void HAL_SD_DMA_TxErrorCallback(DMA_HandleTypeDef *hdma); void HAL_SD_XferCpltCallback(SD_HandleTypeDef *hsd); void HAL_SD_XferErrorCallback(SD_HandleTypeDef *hsd); /* Non-Blocking mode: DMA */ HAL_SD_ErrorTypedef HAL_SD_ReadBlocks_DMA(SD_HandleTypeDef *hsd, uint32_t *pReadBuffer, uint64_t ReadAddr, uint32_t BlockSize, uint32_t NumberOfBlocks); HAL_SD_ErrorTypedef HAL_SD_WriteBlocks_DMA(SD_HandleTypeDef *hsd, uint32_t *pWriteBuffer, uint64_t WriteAddr, uint32_t BlockSize, uint32_t NumberOfBlocks); HAL_SD_ErrorTypedef HAL_SD_CheckWriteOperation(SD_HandleTypeDef *hsd, uint32_t Timeout); HAL_SD_ErrorTypedef HAL_SD_CheckReadOperation(SD_HandleTypeDef *hsd, uint32_t Timeout); /** * @} */ /** @defgroup SD_Exported_Functions_Group3 Peripheral Control functions * @{ */ HAL_SD_ErrorTypedef HAL_SD_Get_CardInfo(SD_HandleTypeDef *hsd, HAL_SD_CardInfoTypedef *pCardInfo); HAL_SD_ErrorTypedef HAL_SD_WideBusOperation_Config(SD_HandleTypeDef *hsd, uint32_t WideMode); HAL_SD_ErrorTypedef HAL_SD_StopTransfer(SD_HandleTypeDef *hsd); HAL_SD_ErrorTypedef HAL_SD_HighSpeed (SD_HandleTypeDef *hsd); /** * @} */ /* Peripheral State functions ************************************************/ /** @defgroup SD_Exported_Functions_Group4 Peripheral State functions * @{ */ HAL_SD_ErrorTypedef HAL_SD_SendSDStatus(SD_HandleTypeDef *hsd, uint32_t *pSDstatus); HAL_SD_ErrorTypedef HAL_SD_GetCardStatus(SD_HandleTypeDef *hsd, HAL_SD_CardStatusTypedef *pCardStatus); HAL_SD_TransferStateTypedef HAL_SD_GetStatus(SD_HandleTypeDef *hsd); /** * @} */ /** * @} */ /* Private types -------------------------------------------------------------*/ /** @defgroup SD_Private_Types SD Private Types * @{ */ /** * @} */ /* Private defines -----------------------------------------------------------*/ /** @defgroup SD_Private_Defines SD Private Defines * @{ */ /** * @} */ /* Private variables ---------------------------------------------------------*/ /** @defgroup SD_Private_Variables SD Private Variables * @{ */ /** * @} */ /* Private constants ---------------------------------------------------------*/ /** @defgroup SD_Private_Constants SD Private Constants * @{ */ /** * @} */ /* Private macros ------------------------------------------------------------*/ /** @defgroup SD_Private_Macros SD Private Macros * @{ */ /** * @} */ /* Private functions prototypes ----------------------------------------------*/ /** @defgroup SD_Private_Functions_Prototypes SD Private Functions Prototypes * @{ */ /** * @} */ /* Private functions ---------------------------------------------------------*/ /** @defgroup SD_Private_Functions SD Private Functions * @{ */ /** * @} */ /** * @} */ /** * @} */ #endif /* STM32F405xx || STM32F415xx || STM32F407xx || STM32F417xx || STM32F427xx || STM32F437xx || STM32F429xx || STM32F439xx || STM32F401xC || STM32F401xE || STM32F411xE || STM32F446xx || STM32F469xx || STM32F479xx */ #ifdef __cplusplus } #endif #endif /* __STM32F4xx_HAL_SD_H */ /************************ (C) COPYRIGHT STMicroelectronics *****END OF FILE****/ ================================================ FILE: Zelig/mbed/TARGET_NUCLEO_F401RE/stm32f4xx_hal_sdram.h ================================================ /** ****************************************************************************** * @file stm32f4xx_hal_sdram.h * @author MCD Application Team * @version V1.4.1 * @date 09-October-2015 * @brief Header file of SDRAM HAL module. ****************************************************************************** * @attention * *

© COPYRIGHT(c) 2015 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. * ****************************************************************************** */ /* Define to prevent recursive inclusion -------------------------------------*/ #ifndef __STM32F4xx_HAL_SDRAM_H #define __STM32F4xx_HAL_SDRAM_H #ifdef __cplusplus extern "C" { #endif #if defined(STM32F427xx) || defined(STM32F437xx) || defined(STM32F429xx) || defined(STM32F439xx) ||\ defined(STM32F446xx) || defined(STM32F469xx) || defined(STM32F479xx) /* Includes ------------------------------------------------------------------*/ #include "stm32f4xx_ll_fmc.h" /** @addtogroup STM32F4xx_HAL_Driver * @{ */ /** @addtogroup SDRAM * @{ */ /* Exported typedef ----------------------------------------------------------*/ /** @defgroup SDRAM_Exported_Types SDRAM Exported Types * @{ */ /** * @brief HAL SDRAM State structure definition */ typedef enum { HAL_SDRAM_STATE_RESET = 0x00, /*!< SDRAM not yet initialized or disabled */ HAL_SDRAM_STATE_READY = 0x01, /*!< SDRAM initialized and ready for use */ HAL_SDRAM_STATE_BUSY = 0x02, /*!< SDRAM internal process is ongoing */ HAL_SDRAM_STATE_ERROR = 0x03, /*!< SDRAM error state */ HAL_SDRAM_STATE_WRITE_PROTECTED = 0x04, /*!< SDRAM device write protected */ HAL_SDRAM_STATE_PRECHARGED = 0x05 /*!< SDRAM device precharged */ }HAL_SDRAM_StateTypeDef; /** * @brief SDRAM handle Structure definition */ typedef struct { FMC_SDRAM_TypeDef *Instance; /*!< Register base address */ FMC_SDRAM_InitTypeDef Init; /*!< SDRAM device configuration parameters */ __IO HAL_SDRAM_StateTypeDef State; /*!< SDRAM access state */ HAL_LockTypeDef Lock; /*!< SDRAM locking object */ DMA_HandleTypeDef *hdma; /*!< Pointer DMA handler */ }SDRAM_HandleTypeDef; /** * @} */ /* Exported constants --------------------------------------------------------*/ /* Exported macro ------------------------------------------------------------*/ /** @defgroup SDRAM_Exported_Macros SDRAM Exported Macros * @{ */ /** @brief Reset SDRAM handle state * @param __HANDLE__: specifies the SDRAM handle. * @retval None */ #define __HAL_SDRAM_RESET_HANDLE_STATE(__HANDLE__) ((__HANDLE__)->State = HAL_SDRAM_STATE_RESET) /** * @} */ /* Exported functions --------------------------------------------------------*/ /** @addtogroup SDRAM_Exported_Functions SDRAM Exported Functions * @{ */ /** @addtogroup SDRAM_Exported_Functions_Group1 * @{ */ /* Initialization/de-initialization functions *********************************/ HAL_StatusTypeDef HAL_SDRAM_Init(SDRAM_HandleTypeDef *hsdram, FMC_SDRAM_TimingTypeDef *Timing); HAL_StatusTypeDef HAL_SDRAM_DeInit(SDRAM_HandleTypeDef *hsdram); void HAL_SDRAM_MspInit(SDRAM_HandleTypeDef *hsdram); void HAL_SDRAM_MspDeInit(SDRAM_HandleTypeDef *hsdram); void HAL_SDRAM_IRQHandler(SDRAM_HandleTypeDef *hsdram); void HAL_SDRAM_RefreshErrorCallback(SDRAM_HandleTypeDef *hsdram); void HAL_SDRAM_DMA_XferCpltCallback(DMA_HandleTypeDef *hdma); void HAL_SDRAM_DMA_XferErrorCallback(DMA_HandleTypeDef *hdma); /** * @} */ /** @addtogroup SDRAM_Exported_Functions_Group2 * @{ */ /* I/O operation functions ****************************************************/ HAL_StatusTypeDef HAL_SDRAM_Read_8b(SDRAM_HandleTypeDef *hsdram, uint32_t *pAddress, uint8_t *pDstBuffer, uint32_t BufferSize); HAL_StatusTypeDef HAL_SDRAM_Write_8b(SDRAM_HandleTypeDef *hsdram, uint32_t *pAddress, uint8_t *pSrcBuffer, uint32_t BufferSize); HAL_StatusTypeDef HAL_SDRAM_Read_16b(SDRAM_HandleTypeDef *hsdram, uint32_t *pAddress, uint16_t *pDstBuffer, uint32_t BufferSize); HAL_StatusTypeDef HAL_SDRAM_Write_16b(SDRAM_HandleTypeDef *hsdram, uint32_t *pAddress, uint16_t *pSrcBuffer, uint32_t BufferSize); HAL_StatusTypeDef HAL_SDRAM_Read_32b(SDRAM_HandleTypeDef *hsdram, uint32_t *pAddress, uint32_t *pDstBuffer, uint32_t BufferSize); HAL_StatusTypeDef HAL_SDRAM_Write_32b(SDRAM_HandleTypeDef *hsdram, uint32_t *pAddress, uint32_t *pSrcBuffer, uint32_t BufferSize); HAL_StatusTypeDef HAL_SDRAM_Read_DMA(SDRAM_HandleTypeDef *hsdram, uint32_t * pAddress, uint32_t *pDstBuffer, uint32_t BufferSize); HAL_StatusTypeDef HAL_SDRAM_Write_DMA(SDRAM_HandleTypeDef *hsdram, uint32_t *pAddress, uint32_t *pSrcBuffer, uint32_t BufferSize); /** * @} */ /** @addtogroup SDRAM_Exported_Functions_Group3 * @{ */ /* SDRAM Control functions *****************************************************/ HAL_StatusTypeDef HAL_SDRAM_WriteProtection_Enable(SDRAM_HandleTypeDef *hsdram); HAL_StatusTypeDef HAL_SDRAM_WriteProtection_Disable(SDRAM_HandleTypeDef *hsdram); HAL_StatusTypeDef HAL_SDRAM_SendCommand(SDRAM_HandleTypeDef *hsdram, FMC_SDRAM_CommandTypeDef *Command, uint32_t Timeout); HAL_StatusTypeDef HAL_SDRAM_ProgramRefreshRate(SDRAM_HandleTypeDef *hsdram, uint32_t RefreshRate); HAL_StatusTypeDef HAL_SDRAM_SetAutoRefreshNumber(SDRAM_HandleTypeDef *hsdram, uint32_t AutoRefreshNumber); uint32_t HAL_SDRAM_GetModeStatus(SDRAM_HandleTypeDef *hsdram); /** * @} */ /** @addtogroup SDRAM_Exported_Functions_Group4 * @{ */ /* SDRAM State functions ********************************************************/ HAL_SDRAM_StateTypeDef HAL_SDRAM_GetState(SDRAM_HandleTypeDef *hsdram); /** * @} */ /** * @} */ /** * @} */ #endif /* STM32F427xx || STM32F437xx || STM32F429xx || STM32F439xx || STM32F446xx || STM32F469xx || STM32F479xx */ /** * @} */ #ifdef __cplusplus } #endif #endif /* __STM32F4xx_HAL_SDRAM_H */ /************************ (C) COPYRIGHT STMicroelectronics *****END OF FILE****/ ================================================ FILE: Zelig/mbed/TARGET_NUCLEO_F401RE/stm32f4xx_hal_smartcard.h ================================================ /** ****************************************************************************** * @file stm32f4xx_hal_smartcard.h * @author MCD Application Team * @version V1.4.1 * @date 09-October-2015 * @brief Header file of SMARTCARD HAL module. ****************************************************************************** * @attention * *

© COPYRIGHT(c) 2015 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. * ****************************************************************************** */ /* Define to prevent recursive inclusion -------------------------------------*/ #ifndef __STM32F4xx_HAL_SMARTCARD_H #define __STM32F4xx_HAL_SMARTCARD_H #ifdef __cplusplus extern "C" { #endif /* Includes ------------------------------------------------------------------*/ #include "stm32f4xx_hal_def.h" /** @addtogroup STM32F4xx_HAL_Driver * @{ */ /** @addtogroup SMARTCARD * @{ */ /* Exported types ------------------------------------------------------------*/ /** @defgroup SMARTCARD_Exported_Types SMARTCARD Exported Types * @{ */ /** * @brief SMARTCARD Init Structure definition */ typedef struct { uint32_t BaudRate; /*!< This member configures the SmartCard communication baud rate. The baud rate is computed using the following formula: - IntegerDivider = ((PCLKx) / (8 * (hirda->Init.BaudRate))) - FractionalDivider = ((IntegerDivider - ((uint32_t) IntegerDivider)) * 8) + 0.5 */ uint32_t WordLength; /*!< Specifies the number of data bits transmitted or received in a frame. This parameter can be a value of @ref SMARTCARD_Word_Length */ uint32_t StopBits; /*!< Specifies the number of stop bits transmitted. This parameter can be a value of @ref SMARTCARD_Stop_Bits */ uint32_t Parity; /*!< Specifies the parity mode. This parameter can be a value of @ref SMARTCARD_Parity @note When parity is enabled, the computed parity is inserted at the MSB position of the transmitted data (9th bit when the word length is set to 9 data bits; 8th bit when the word length is set to 8 data bits).*/ uint32_t Mode; /*!< Specifies whether the Receive or Transmit mode is enabled or disabled. This parameter can be a value of @ref SMARTCARD_Mode */ uint32_t CLKPolarity; /*!< Specifies the steady state of the serial clock. This parameter can be a value of @ref SMARTCARD_Clock_Polarity */ uint32_t CLKPhase; /*!< Specifies the clock transition on which the bit capture is made. This parameter can be a value of @ref SMARTCARD_Clock_Phase */ uint32_t CLKLastBit; /*!< Specifies whether the clock pulse corresponding to the last transmitted data bit (MSB) has to be output on the SCLK pin in synchronous mode. This parameter can be a value of @ref SMARTCARD_Last_Bit */ uint32_t Prescaler; /*!< Specifies the SmartCard Prescaler value used for dividing the system clock to provide the smartcard clock This parameter can be a value of @ref SMARTCARD_Prescaler */ uint32_t GuardTime; /*!< Specifies the SmartCard Guard Time value in terms of number of baud clocks The value given in the register (5 significant bits) is multiplied by 2 to give the division factor of the source clock frequency */ uint32_t NACKState; /*!< Specifies the SmartCard NACK Transmission state. This parameter can be a value of @ref SmartCard_NACK_State */ }SMARTCARD_InitTypeDef; /** * @brief HAL State structures definition */ typedef enum { HAL_SMARTCARD_STATE_RESET = 0x00, /*!< Peripheral is not yet Initialized */ HAL_SMARTCARD_STATE_READY = 0x01, /*!< Peripheral Initialized and ready for use */ HAL_SMARTCARD_STATE_BUSY = 0x02, /*!< an internal process is ongoing */ HAL_SMARTCARD_STATE_BUSY_TX = 0x12, /*!< Data Transmission process is ongoing */ HAL_SMARTCARD_STATE_BUSY_RX = 0x22, /*!< Data Reception process is ongoing */ HAL_SMARTCARD_STATE_BUSY_TX_RX = 0x32, /*!< Data Transmission and Reception process is ongoing */ HAL_SMARTCARD_STATE_TIMEOUT = 0x03, /*!< Timeout state */ HAL_SMARTCARD_STATE_ERROR = 0x04 /*!< Error */ }HAL_SMARTCARD_StateTypeDef; /** * @brief SMARTCARD handle Structure definition */ typedef struct { USART_TypeDef *Instance; /* USART registers base address */ SMARTCARD_InitTypeDef Init; /* SmartCard communication parameters */ uint8_t *pTxBuffPtr; /* Pointer to SmartCard Tx transfer Buffer */ uint16_t TxXferSize; /* SmartCard Tx Transfer size */ uint16_t TxXferCount; /* SmartCard Tx Transfer Counter */ uint8_t *pRxBuffPtr; /* Pointer to SmartCard Rx transfer Buffer */ uint16_t RxXferSize; /* SmartCard Rx Transfer size */ uint16_t RxXferCount; /* SmartCard Rx Transfer Counter */ DMA_HandleTypeDef *hdmatx; /* SmartCard Tx DMA Handle parameters */ DMA_HandleTypeDef *hdmarx; /* SmartCard Rx DMA Handle parameters */ HAL_LockTypeDef Lock; /* Locking object */ __IO HAL_SMARTCARD_StateTypeDef State; /* SmartCard communication state */ __IO uint32_t ErrorCode; /* SmartCard Error code */ }SMARTCARD_HandleTypeDef; /** * @} */ /* Exported constants --------------------------------------------------------*/ /** @defgroup SMARTCARD_Exported_Constants SMARTCARD Exported constants * @{ */ /** @defgroup SMARTCARD_Error_Code SMARTCARD Error Code * @brief SMARTCARD Error Code * @{ */ #define HAL_SMARTCARD_ERROR_NONE ((uint32_t)0x00000000) /*!< No error */ #define HAL_SMARTCARD_ERROR_PE ((uint32_t)0x00000001) /*!< Parity error */ #define HAL_SMARTCARD_ERROR_NE ((uint32_t)0x00000002) /*!< Noise error */ #define HAL_SMARTCARD_ERROR_FE ((uint32_t)0x00000004) /*!< Frame error */ #define HAL_SMARTCARD_ERROR_ORE ((uint32_t)0x00000008) /*!< Overrun error */ #define HAL_SMARTCARD_ERROR_DMA ((uint32_t)0x00000010) /*!< DMA transfer error */ /** * @} */ /** @defgroup SMARTCARD_Word_Length SMARTCARD Word Length * @{ */ #define SMARTCARD_WORDLENGTH_9B ((uint32_t)USART_CR1_M) /** * @} */ /** @defgroup SMARTCARD_Stop_Bits SMARTCARD Number of Stop Bits * @{ */ #define SMARTCARD_STOPBITS_0_5 ((uint32_t)USART_CR2_STOP_0) #define SMARTCARD_STOPBITS_1_5 ((uint32_t)(USART_CR2_STOP_0 | USART_CR2_STOP_1)) /** * @} */ /** @defgroup SMARTCARD_Parity SMARTCARD Parity * @{ */ #define SMARTCARD_PARITY_EVEN ((uint32_t)USART_CR1_PCE) #define SMARTCARD_PARITY_ODD ((uint32_t)(USART_CR1_PCE | USART_CR1_PS)) /** * @} */ /** @defgroup SMARTCARD_Mode SMARTCARD Mode * @{ */ #define SMARTCARD_MODE_RX ((uint32_t)USART_CR1_RE) #define SMARTCARD_MODE_TX ((uint32_t)USART_CR1_TE) #define SMARTCARD_MODE_TX_RX ((uint32_t)(USART_CR1_TE |USART_CR1_RE)) /** * @} */ /** @defgroup SMARTCARD_Clock_Polarity SMARTCARD Clock Polarity * @{ */ #define SMARTCARD_POLARITY_LOW ((uint32_t)0x00000000) #define SMARTCARD_POLARITY_HIGH ((uint32_t)USART_CR2_CPOL) /** * @} */ /** @defgroup SMARTCARD_Clock_Phase SMARTCARD Clock Phase * @{ */ #define SMARTCARD_PHASE_1EDGE ((uint32_t)0x00000000) #define SMARTCARD_PHASE_2EDGE ((uint32_t)USART_CR2_CPHA) /** * @} */ /** @defgroup SMARTCARD_Last_Bit SMARTCARD Last Bit * @{ */ #define SMARTCARD_LASTBIT_DISABLE ((uint32_t)0x00000000) #define SMARTCARD_LASTBIT_ENABLE ((uint32_t)USART_CR2_LBCL) /** * @} */ /** @defgroup SmartCard_NACK_State SMARTCARD NACK State * @{ */ #define SMARTCARD_NACK_ENABLE ((uint32_t)USART_CR3_NACK) #define SMARTCARD_NACK_DISABLE ((uint32_t)0x00000000) /** * @} */ /** @defgroup SmartCard_DMA_Requests SMARTCARD DMA requests * @{ */ #define SMARTCARD_DMAREQ_TX ((uint32_t)USART_CR3_DMAT) #define SMARTCARD_DMAREQ_RX ((uint32_t)USART_CR3_DMAR) /** * @} */ /** @defgroup SMARTCARD_Prescaler SMARTCARD Prescaler * @{ */ #define SMARTCARD_PRESCALER_SYSCLK_DIV2 ((uint32_t)0x00000001) /*!< SYSCLK divided by 2 */ #define SMARTCARD_PRESCALER_SYSCLK_DIV4 ((uint32_t)0x00000002) /*!< SYSCLK divided by 4 */ #define SMARTCARD_PRESCALER_SYSCLK_DIV6 ((uint32_t)0x00000003) /*!< SYSCLK divided by 6 */ #define SMARTCARD_PRESCALER_SYSCLK_DIV8 ((uint32_t)0x00000004) /*!< SYSCLK divided by 8 */ #define SMARTCARD_PRESCALER_SYSCLK_DIV10 ((uint32_t)0x00000005) /*!< SYSCLK divided by 10 */ #define SMARTCARD_PRESCALER_SYSCLK_DIV12 ((uint32_t)0x00000006) /*!< SYSCLK divided by 12 */ #define SMARTCARD_PRESCALER_SYSCLK_DIV14 ((uint32_t)0x00000007) /*!< SYSCLK divided by 14 */ #define SMARTCARD_PRESCALER_SYSCLK_DIV16 ((uint32_t)0x00000008) /*!< SYSCLK divided by 16 */ #define SMARTCARD_PRESCALER_SYSCLK_DIV18 ((uint32_t)0x00000009) /*!< SYSCLK divided by 18 */ #define SMARTCARD_PRESCALER_SYSCLK_DIV20 ((uint32_t)0x0000000A) /*!< SYSCLK divided by 20 */ #define SMARTCARD_PRESCALER_SYSCLK_DIV22 ((uint32_t)0x0000000B) /*!< SYSCLK divided by 22 */ #define SMARTCARD_PRESCALER_SYSCLK_DIV24 ((uint32_t)0x0000000C) /*!< SYSCLK divided by 24 */ #define SMARTCARD_PRESCALER_SYSCLK_DIV26 ((uint32_t)0x0000000D) /*!< SYSCLK divided by 26 */ #define SMARTCARD_PRESCALER_SYSCLK_DIV28 ((uint32_t)0x0000000E) /*!< SYSCLK divided by 28 */ #define SMARTCARD_PRESCALER_SYSCLK_DIV30 ((uint32_t)0x0000000F) /*!< SYSCLK divided by 30 */ #define SMARTCARD_PRESCALER_SYSCLK_DIV32 ((uint32_t)0x00000010) /*!< SYSCLK divided by 32 */ #define SMARTCARD_PRESCALER_SYSCLK_DIV34 ((uint32_t)0x00000011) /*!< SYSCLK divided by 34 */ #define SMARTCARD_PRESCALER_SYSCLK_DIV36 ((uint32_t)0x00000012) /*!< SYSCLK divided by 36 */ #define SMARTCARD_PRESCALER_SYSCLK_DIV38 ((uint32_t)0x00000013) /*!< SYSCLK divided by 38 */ #define SMARTCARD_PRESCALER_SYSCLK_DIV40 ((uint32_t)0x00000014) /*!< SYSCLK divided by 40 */ #define SMARTCARD_PRESCALER_SYSCLK_DIV42 ((uint32_t)0x00000015) /*!< SYSCLK divided by 42 */ #define SMARTCARD_PRESCALER_SYSCLK_DIV44 ((uint32_t)0x00000016) /*!< SYSCLK divided by 44 */ #define SMARTCARD_PRESCALER_SYSCLK_DIV46 ((uint32_t)0x00000017) /*!< SYSCLK divided by 46 */ #define SMARTCARD_PRESCALER_SYSCLK_DIV48 ((uint32_t)0x00000018) /*!< SYSCLK divided by 48 */ #define SMARTCARD_PRESCALER_SYSCLK_DIV50 ((uint32_t)0x00000019) /*!< SYSCLK divided by 50 */ #define SMARTCARD_PRESCALER_SYSCLK_DIV52 ((uint32_t)0x0000001A) /*!< SYSCLK divided by 52 */ #define SMARTCARD_PRESCALER_SYSCLK_DIV54 ((uint32_t)0x0000001B) /*!< SYSCLK divided by 54 */ #define SMARTCARD_PRESCALER_SYSCLK_DIV56 ((uint32_t)0x0000001C) /*!< SYSCLK divided by 56 */ #define SMARTCARD_PRESCALER_SYSCLK_DIV58 ((uint32_t)0x0000001D) /*!< SYSCLK divided by 58 */ #define SMARTCARD_PRESCALER_SYSCLK_DIV60 ((uint32_t)0x0000001E) /*!< SYSCLK divided by 60 */ #define SMARTCARD_PRESCALER_SYSCLK_DIV62 ((uint32_t)0x0000001F) /*!< SYSCLK divided by 62 */ /** * @} */ /** @defgroup SmartCard_Flags SMARTCARD Flags * Elements values convention: 0xXXXX * - 0xXXXX : Flag mask in the SR register * @{ */ #define SMARTCARD_FLAG_TXE ((uint32_t)0x00000080) #define SMARTCARD_FLAG_TC ((uint32_t)0x00000040) #define SMARTCARD_FLAG_RXNE ((uint32_t)0x00000020) #define SMARTCARD_FLAG_IDLE ((uint32_t)0x00000010) #define SMARTCARD_FLAG_ORE ((uint32_t)0x00000008) #define SMARTCARD_FLAG_NE ((uint32_t)0x00000004) #define SMARTCARD_FLAG_FE ((uint32_t)0x00000002) #define SMARTCARD_FLAG_PE ((uint32_t)0x00000001) /** * @} */ /** @defgroup SmartCard_Interrupt_definition SMARTCARD Interrupts Definition * Elements values convention: 0xY000XXXX * - XXXX : Interrupt mask in the XX register * - Y : Interrupt source register (2bits) * - 01: CR1 register * - 10: CR3 register * @{ */ #define SMARTCARD_IT_PE ((uint32_t)(SMARTCARD_CR1_REG_INDEX << 28 | USART_CR1_PEIE)) #define SMARTCARD_IT_TXE ((uint32_t)(SMARTCARD_CR1_REG_INDEX << 28 | USART_CR1_TXEIE)) #define SMARTCARD_IT_TC ((uint32_t)(SMARTCARD_CR1_REG_INDEX << 28 | USART_CR1_TCIE)) #define SMARTCARD_IT_RXNE ((uint32_t)(SMARTCARD_CR1_REG_INDEX << 28 | USART_CR1_RXNEIE)) #define SMARTCARD_IT_IDLE ((uint32_t)(SMARTCARD_CR1_REG_INDEX << 28 | USART_CR1_IDLEIE)) #define SMARTCARD_IT_ERR ((uint32_t)(SMARTCARD_CR3_REG_INDEX << 28 | USART_CR3_EIE)) /** * @} */ /** * @} */ /* Exported macro ------------------------------------------------------------*/ /** @defgroup SMARTCARD_Exported_Macros SMARTCARD Exported Macros * @{ */ /** @brief Reset SMARTCARD handle state * @param __HANDLE__: specifies the SMARTCARD Handle. * @retval None */ #define __HAL_SMARTCARD_RESET_HANDLE_STATE(__HANDLE__) ((__HANDLE__)->State = HAL_SMARTCARD_STATE_RESET) /** @brief Flushs the Smartcard DR register * @param __HANDLE__: specifies the SMARTCARD Handle. */ #define __HAL_SMARTCARD_FLUSH_DRREGISTER(__HANDLE__) ((__HANDLE__)->Instance->DR) /** @brief Checks whether the specified Smartcard flag is set or not. * @param __HANDLE__: specifies the SMARTCARD Handle. * @param __FLAG__: specifies the flag to check. * This parameter can be one of the following values: * @arg SMARTCARD_FLAG_TXE: Transmit data register empty flag * @arg SMARTCARD_FLAG_TC: Transmission Complete flag * @arg SMARTCARD_FLAG_RXNE: Receive data register not empty flag * @arg SMARTCARD_FLAG_IDLE: Idle Line detection flag * @arg SMARTCARD_FLAG_ORE: Overrun Error flag * @arg SMARTCARD_FLAG_NE: Noise Error flag * @arg SMARTCARD_FLAG_FE: Framing Error flag * @arg SMARTCARD_FLAG_PE: Parity Error flag * @retval The new state of __FLAG__ (TRUE or FALSE). */ #define __HAL_SMARTCARD_GET_FLAG(__HANDLE__, __FLAG__) (((__HANDLE__)->Instance->SR & (__FLAG__)) == (__FLAG__)) /** @brief Clears the specified Smartcard pending flags. * @param __HANDLE__: specifies the SMARTCARD Handle. * @param __FLAG__: specifies the flag to check. * This parameter can be any combination of the following values: * @arg SMARTCARD_FLAG_TC: Transmission Complete flag. * @arg SMARTCARD_FLAG_RXNE: Receive data register not empty flag. * * @note PE (Parity error), FE (Framing error), NE (Noise error) and ORE (Overrun * error) flags are cleared by software sequence: a read operation to * USART_SR register followed by a read operation to USART_DR register. * @note RXNE flag can be also cleared by a read to the USART_DR register. * @note TC flag can be also cleared by software sequence: a read operation to * USART_SR register followed by a write operation to USART_DR register. * @note TXE flag is cleared only by a write to the USART_DR register. */ #define __HAL_SMARTCARD_CLEAR_FLAG(__HANDLE__, __FLAG__) ((__HANDLE__)->Instance->SR = ~(__FLAG__)) /** @brief Clear the SMARTCARD PE pending flag. * @param __HANDLE__: specifies the USART Handle. * This parameter can be USARTx where x: 1, 2, 3, 4, 5, 6, 7 or 8 to select the USART or * UART peripheral. * @retval None */ #define __HAL_SMARTCARD_CLEAR_PEFLAG(__HANDLE__) \ do{ \ __IO uint32_t tmpreg; \ tmpreg = (__HANDLE__)->Instance->SR; \ tmpreg = (__HANDLE__)->Instance->DR; \ UNUSED(tmpreg); \ } while(0) /** @brief Clear the SMARTCARD FE pending flag. * @param __HANDLE__: specifies the USART Handle. * This parameter can be USARTx where x: 1, 2, 3, 4, 5, 6, 7 or 8 to select the USART or * UART peripheral. * @retval None */ #define __HAL_SMARTCARD_CLEAR_FEFLAG(__HANDLE__) __HAL_SMARTCARD_CLEAR_PEFLAG(__HANDLE__) /** @brief Clear the SMARTCARD NE pending flag. * @param __HANDLE__: specifies the USART Handle. * This parameter can be USARTx where x: 1, 2, 3, 4, 5, 6, 7 or 8 to select the USART or * UART peripheral. * @retval None */ #define __HAL_SMARTCARD_CLEAR_NEFLAG(__HANDLE__) __HAL_SMARTCARD_CLEAR_PEFLAG(__HANDLE__) /** @brief Clear the SMARTCARD ORE pending flag. * @param __HANDLE__: specifies the USART Handle. * This parameter can be USARTx where x: 1, 2, 3, 4, 5, 6, 7 or 8 to select the USART or * UART peripheral. * @retval None */ #define __HAL_SMARTCARD_CLEAR_OREFLAG(__HANDLE__) __HAL_SMARTCARD_CLEAR_PEFLAG(__HANDLE__) /** @brief Clear the SMARTCARD IDLE pending flag. * @param __HANDLE__: specifies the USART Handle. * This parameter can be USARTx where x: 1, 2, 3, 4, 5, 6, 7 or 8 to select the USART or * UART peripheral. * @retval None */ #define __HAL_SMARTCARD_CLEAR_IDLEFLAG(__HANDLE__) __HAL_SMARTCARD_CLEAR_PEFLAG(__HANDLE__) /** @brief Enables or disables the specified SmartCard interrupts. * @param __HANDLE__: specifies the SMARTCARD Handle. * @param __INTERRUPT__: specifies the SMARTCARD interrupt source to check. * This parameter can be one of the following values: * @arg SMARTCARD_IT_TXE: Transmit Data Register empty interrupt * @arg SMARTCARD_IT_TC: Transmission complete interrupt * @arg SMARTCARD_IT_RXNE: Receive Data register not empty interrupt * @arg SMARTCARD_IT_IDLE: Idle line detection interrupt * @arg SMARTCARD_IT_PE: Parity Error interrupt * @arg SMARTCARD_IT_ERR: Error interrupt(Frame error, noise error, overrun error) */ #define __HAL_SMARTCARD_ENABLE_IT(__HANDLE__, __INTERRUPT__) ((((__INTERRUPT__) >> 28) == 1)? ((__HANDLE__)->Instance->CR1 |= ((__INTERRUPT__) & SMARTCARD_IT_MASK)): \ ((__HANDLE__)->Instance->CR3 |= ((__INTERRUPT__) & SMARTCARD_IT_MASK))) #define __HAL_SMARTCARD_DISABLE_IT(__HANDLE__, __INTERRUPT__) ((((__INTERRUPT__) >> 28) == 1)? ((__HANDLE__)->Instance->CR1 &= ~((__INTERRUPT__) & SMARTCARD_IT_MASK)): \ ((__HANDLE__)->Instance->CR3 &= ~ ((__INTERRUPT__) & SMARTCARD_IT_MASK))) /** @brief Checks whether the specified SmartCard interrupt has occurred or not. * @param __HANDLE__: specifies the SmartCard Handle. * @param __IT__: specifies the SMARTCARD interrupt source to check. * This parameter can be one of the following values: * @arg SMARTCARD_IT_TXE: Transmit Data Register empty interrupt * @arg SMARTCARD_IT_TC: Transmission complete interrupt * @arg SMARTCARD_IT_RXNE: Receive Data register not empty interrupt * @arg SMARTCARD_IT_IDLE: Idle line detection interrupt * @arg SMARTCARD_IT_ERR: Error interrupt * @arg SMARTCARD_IT_PE: Parity Error interrupt * @retval The new state of __IT__ (TRUE or FALSE). */ #define __HAL_SMARTCARD_GET_IT_SOURCE(__HANDLE__, __IT__) (((((__IT__) >> 28) == 1)? (__HANDLE__)->Instance->CR1: (__HANDLE__)->Instance->CR3) & (((uint32_t)(__IT__)) & SMARTCARD_IT_MASK)) /** @brief Macro to enable the SMARTCARD's one bit sample method * @param __HANDLE__: specifies the SMARTCARD Handle. * @retval None */ #define __HAL_SMARTCARD_ONE_BIT_SAMPLE_ENABLE(__HANDLE__) ((__HANDLE__)->Instance->CR3|= USART_CR3_ONEBIT) /** @brief Macro to disable the SMARTCARD's one bit sample method * @param __HANDLE__: specifies the SMARTCARD Handle. * @retval None */ #define __HAL_SMARTCARD_ONE_BIT_SAMPLE_DISABLE(__HANDLE__) ((__HANDLE__)->Instance->CR3 &= (uint16_t)~((uint16_t)USART_CR3_ONEBIT)) /** @brief Enable the USART associated to the SMARTCARD Handle * @param __HANDLE__: specifies the SMARTCARD Handle. * SMARTCARD Handle selects the USARTx peripheral (USART availability and x value depending on device). * @retval None */ #define __HAL_SMARTCARD_ENABLE(__HANDLE__) ((__HANDLE__)->Instance->CR1 |= USART_CR1_UE) /** @brief Disable the USART associated to the SMARTCARD Handle * @param __HANDLE__: specifies the SMARTCARD Handle. * SMARTCARD Handle selects the USARTx peripheral (USART availability and x value depending on device). * @retval None */ #define __HAL_SMARTCARD_DISABLE(__HANDLE__) ((__HANDLE__)->Instance->CR1 &= ~USART_CR1_UE) /** @brief Macros to enable or disable the SmartCard DMA request. * @param __HANDLE__: specifies the SmartCard Handle. * @param __REQUEST__: specifies the SmartCard DMA request. * This parameter can be one of the following values: * @arg SMARTCARD_DMAREQ_TX: SmartCard DMA transmit request * @arg SMARTCARD_DMAREQ_RX: SmartCard DMA receive request */ #define __HAL_SMARTCARD_DMA_REQUEST_ENABLE(__HANDLE__, __REQUEST__) ((__HANDLE__)->Instance->CR3 |= (__REQUEST__)) #define __HAL_SMARTCARD_DMA_REQUEST_DISABLE(__HANDLE__, __REQUEST__) ((__HANDLE__)->Instance->CR3 &= ~(__REQUEST__)) /** * @} */ /* Exported functions --------------------------------------------------------*/ /** @addtogroup SMARTCARD_Exported_Functions * @{ */ /** @addtogroup SMARTCARD_Exported_Functions_Group1 * @{ */ /* Initialization/de-initialization functions **********************************/ HAL_StatusTypeDef HAL_SMARTCARD_Init(SMARTCARD_HandleTypeDef *hsc); HAL_StatusTypeDef HAL_SMARTCARD_ReInit(SMARTCARD_HandleTypeDef *hsc); HAL_StatusTypeDef HAL_SMARTCARD_DeInit(SMARTCARD_HandleTypeDef *hsc); void HAL_SMARTCARD_MspInit(SMARTCARD_HandleTypeDef *hsc); void HAL_SMARTCARD_MspDeInit(SMARTCARD_HandleTypeDef *hsc); /** * @} */ /** @addtogroup SMARTCARD_Exported_Functions_Group2 * @{ */ /* IO operation functions *******************************************************/ HAL_StatusTypeDef HAL_SMARTCARD_Transmit(SMARTCARD_HandleTypeDef *hsc, uint8_t *pData, uint16_t Size, uint32_t Timeout); HAL_StatusTypeDef HAL_SMARTCARD_Receive(SMARTCARD_HandleTypeDef *hsc, uint8_t *pData, uint16_t Size, uint32_t Timeout); HAL_StatusTypeDef HAL_SMARTCARD_Transmit_IT(SMARTCARD_HandleTypeDef *hsc, uint8_t *pData, uint16_t Size); HAL_StatusTypeDef HAL_SMARTCARD_Receive_IT(SMARTCARD_HandleTypeDef *hsc, uint8_t *pData, uint16_t Size); HAL_StatusTypeDef HAL_SMARTCARD_Transmit_DMA(SMARTCARD_HandleTypeDef *hsc, uint8_t *pData, uint16_t Size); HAL_StatusTypeDef HAL_SMARTCARD_Receive_DMA(SMARTCARD_HandleTypeDef *hsc, uint8_t *pData, uint16_t Size); void HAL_SMARTCARD_IRQHandler(SMARTCARD_HandleTypeDef *hsc); void HAL_SMARTCARD_TxCpltCallback(SMARTCARD_HandleTypeDef *hsc); void HAL_SMARTCARD_RxCpltCallback(SMARTCARD_HandleTypeDef *hsc); void HAL_SMARTCARD_ErrorCallback(SMARTCARD_HandleTypeDef *hsc); /** * @} */ /** @addtogroup SMARTCARD_Exported_Functions_Group3 * @{ */ /* Peripheral State functions **************************************************/ HAL_SMARTCARD_StateTypeDef HAL_SMARTCARD_GetState(SMARTCARD_HandleTypeDef *hsc); uint32_t HAL_SMARTCARD_GetError(SMARTCARD_HandleTypeDef *hsc); /** * @} */ /** * @} */ /* Private types -------------------------------------------------------------*/ /* Private variables ---------------------------------------------------------*/ /* Private constants ---------------------------------------------------------*/ /** @defgroup SMARTCARD_Private_Constants SMARTCARD Private Constants * @{ */ /** @brief SMARTCARD interruptions flag mask * */ #define SMARTCARD_IT_MASK ((uint32_t) USART_CR1_PEIE | USART_CR1_TXEIE | USART_CR1_TCIE | USART_CR1_RXNEIE | \ USART_CR1_IDLEIE | USART_CR3_EIE ) #define SMARTCARD_DIV(_PCLK_, _BAUD_) (((_PCLK_)*25)/(4*(_BAUD_))) #define SMARTCARD_DIVMANT(_PCLK_, _BAUD_) (SMARTCARD_DIV((_PCLK_), (_BAUD_))/100) #define SMARTCARD_DIVFRAQ(_PCLK_, _BAUD_) (((SMARTCARD_DIV((_PCLK_), (_BAUD_)) - (SMARTCARD_DIVMANT((_PCLK_), (_BAUD_)) * 100)) * 16 + 50) / 100) #define SMARTCARD_BRR(_PCLK_, _BAUD_) ((SMARTCARD_DIVMANT((_PCLK_), (_BAUD_)) << 4)|(SMARTCARD_DIVFRAQ((_PCLK_), (_BAUD_)) & 0x0F)) #define SMARTCARD_CR1_REG_INDEX 1 #define SMARTCARD_CR3_REG_INDEX 3 /** * @} */ /* Private macros --------------------------------------------------------*/ /** @defgroup SMARTCARD_Private_Macros SMARTCARD Private Macros * @{ */ #define IS_SMARTCARD_WORD_LENGTH(LENGTH) ((LENGTH) == SMARTCARD_WORDLENGTH_9B) #define IS_SMARTCARD_STOPBITS(STOPBITS) (((STOPBITS) == SMARTCARD_STOPBITS_0_5) || \ ((STOPBITS) == SMARTCARD_STOPBITS_1_5)) #define IS_SMARTCARD_PARITY(PARITY) (((PARITY) == SMARTCARD_PARITY_EVEN) || \ ((PARITY) == SMARTCARD_PARITY_ODD)) #define IS_SMARTCARD_MODE(MODE) ((((MODE) & (uint32_t)0x0000FFF3) == 0x00) && ((MODE) != (uint32_t)0x000000)) #define IS_SMARTCARD_POLARITY(CPOL) (((CPOL) == SMARTCARD_POLARITY_LOW) || ((CPOL) == SMARTCARD_POLARITY_HIGH)) #define IS_SMARTCARD_PHASE(CPHA) (((CPHA) == SMARTCARD_PHASE_1EDGE) || ((CPHA) == SMARTCARD_PHASE_2EDGE)) #define IS_SMARTCARD_LASTBIT(LASTBIT) (((LASTBIT) == SMARTCARD_LASTBIT_DISABLE) || \ ((LASTBIT) == SMARTCARD_LASTBIT_ENABLE)) #define IS_SMARTCARD_NACK_STATE(NACK) (((NACK) == SMARTCARD_NACK_ENABLE) || \ ((NACK) == SMARTCARD_NACK_DISABLE)) #define IS_SMARTCARD_BAUDRATE(BAUDRATE) ((BAUDRATE) < 10500001) /** * @} */ /* Private functions ---------------------------------------------------------*/ /** @defgroup SMARTCARD_Private_Functions SMARTCARD Private Functions * @{ */ /** * @} */ /** * @} */ /** * @} */ #ifdef __cplusplus } #endif #endif /* __STM32F4xx_HAL_SMARTCARD_H */ /************************ (C) COPYRIGHT STMicroelectronics *****END OF FILE****/ ================================================ FILE: Zelig/mbed/TARGET_NUCLEO_F401RE/stm32f4xx_hal_spdifrx.h ================================================ /** ****************************************************************************** * @file stm32f4xx_hal_spdifrx.h * @author MCD Application Team * @version V1.4.1 * @date 09-October-2015 * @brief Header file of SPDIFRX HAL module. ****************************************************************************** * @attention * *

© COPYRIGHT(c) 2015 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. * ****************************************************************************** */ /* Define to prevent recursive inclusion -------------------------------------*/ #ifndef __STM32F4xx_HAL_SPDIFRX_H #define __STM32F4xx_HAL_SPDIFRX_H #ifdef __cplusplus extern "C" { #endif #if defined(STM32F446xx) /* Includes ------------------------------------------------------------------*/ #include "stm32f4xx_hal_def.h" /** @addtogroup STM32F4xx_HAL_Driver * @{ */ /** @addtogroup SPDIFRX * @{ */ /* Exported types ------------------------------------------------------------*/ /** @defgroup SPDIFRX_Exported_Types SPDIFRX Exported Types * @{ */ /** * @brief SPDIFRX Init structure definition */ typedef struct { uint32_t InputSelection; /*!< Specifies the SPDIF input selection. This parameter can be a value of @ref SPDIFRX_Input_Selection */ uint32_t Retries; /*!< Specifies the Maximum allowed re-tries during synchronization phase. This parameter can be a value of @ref SPDIFRX_Max_Retries */ uint32_t WaitForActivity; /*!< Specifies the wait for activity on SPDIF selected input. This parameter can be a value of @ref SPDIFRX_Wait_For_Activity. */ uint32_t ChannelSelection; /*!< Specifies whether the control flow will take the channel status from channel A or B. This parameter can be a value of @ref SPDIFRX_Channel_Selection */ uint32_t DataFormat; /*!< Specifies the Data samples format (LSB, MSB, ...). This parameter can be a value of @ref SPDIFRX_Data_Format */ uint32_t StereoMode; /*!< Specifies whether the peripheral is in stereo or mono mode. This parameter can be a value of @ref SPDIFRX_Stereo_Mode */ uint32_t PreambleTypeMask; /*!< Specifies whether The preamble type bits are copied or not into the received frame. This parameter can be a value of @ref SPDIFRX_PT_Mask */ uint32_t ChannelStatusMask; /*!< Specifies whether the channel status and user bits are copied or not into the received frame. This parameter can be a value of @ref SPDIFRX_ChannelStatus_Mask */ uint32_t ValidityBitMask; /*!< Specifies whether the validity bit is copied or not into the received frame. This parameter can be a value of @ref SPDIFRX_V_Mask */ uint32_t ParityErrorMask; /*!< Specifies whether the parity error bit is copied or not into the received frame. This parameter can be a value of @ref SPDIFRX_PE_Mask */ }SPDIFRX_InitTypeDef; /** * @brief SPDIFRX SetDataFormat structure definition */ typedef struct { uint32_t DataFormat; /*!< Specifies the Data samples format (LSB, MSB, ...). This parameter can be a value of @ref SPDIFRX_Data_Format */ uint32_t StereoMode; /*!< Specifies whether the peripheral is in stereo or mono mode. This parameter can be a value of @ref SPDIFRX_Stereo_Mode */ uint32_t PreambleTypeMask; /*!< Specifies whether The preamble type bits are copied or not into the received frame. This parameter can be a value of @ref SPDIFRX_PT_Mask */ uint32_t ChannelStatusMask; /*!< Specifies whether the channel status and user bits are copied or not into the received frame. This parameter can be a value of @ref SPDIFRX_ChannelStatus_Mask */ uint32_t ValidityBitMask; /*!< Specifies whether the validity bit is copied or not into the received frame. This parameter can be a value of @ref SPDIFRX_V_Mask */ uint32_t ParityErrorMask; /*!< Specifies whether the parity error bit is copied or not into the received frame. This parameter can be a value of @ref SPDIFRX_PE_Mask */ }SPDIFRX_SetDataFormatTypeDef; /** * @brief HAL State structures definition */ typedef enum { HAL_SPDIFRX_STATE_RESET = 0x00, /*!< SPDIFRX not yet initialized or disabled */ HAL_SPDIFRX_STATE_READY = 0x01, /*!< SPDIFRX initialized and ready for use */ HAL_SPDIFRX_STATE_BUSY = 0x02, /*!< SPDIFRX internal process is ongoing */ HAL_SPDIFRX_STATE_BUSY_RX = 0x03, /*!< SPDIFRX internal Data Flow RX process is ongoing */ HAL_SPDIFRX_STATE_BUSY_CX = 0x04, /*!< SPDIFRX internal Control Flow RX process is ongoing */ HAL_SPDIFRX_STATE_ERROR = 0x07 /*!< SPDIFRX error state */ }HAL_SPDIFRX_StateTypeDef; /** * @brief SPDIFRX handle Structure definition */ typedef struct { SPDIFRX_TypeDef *Instance; /* SPDIFRX registers base address */ SPDIFRX_InitTypeDef Init; /* SPDIFRX communication parameters */ uint32_t *pRxBuffPtr; /* Pointer to SPDIFRX Rx transfer buffer */ uint32_t *pCsBuffPtr; /* Pointer to SPDIFRX Cx transfer buffer */ __IO uint16_t RxXferSize; /* SPDIFRX Rx transfer size */ __IO uint16_t RxXferCount; /* SPDIFRX Rx transfer counter (This field is initialized at the same value as transfer size at the beginning of the transfer and decremented when a sample is received. NbSamplesReceived = RxBufferSize-RxBufferCount) */ __IO uint16_t CsXferSize; /* SPDIFRX Rx transfer size */ __IO uint16_t CsXferCount; /* SPDIFRX Rx transfer counter (This field is initialized at the same value as transfer size at the beginning of the transfer and decremented when a sample is received. NbSamplesReceived = RxBufferSize-RxBufferCount) */ DMA_HandleTypeDef *hdmaCsRx; /* SPDIFRX EC60958_channel_status and user_information DMA handle parameters */ DMA_HandleTypeDef *hdmaDrRx; /* SPDIFRX Rx DMA handle parameters */ __IO HAL_LockTypeDef Lock; /* SPDIFRX locking object */ __IO HAL_SPDIFRX_StateTypeDef State; /* SPDIFRX communication state */ __IO uint32_t ErrorCode; /* SPDIFRX Error code */ }SPDIFRX_HandleTypeDef; /** * @} */ /* Exported constants --------------------------------------------------------*/ /** @defgroup SPDIFRX_Exported_Constants SPDIFRX Exported Constants * @{ */ /** @defgroup SPDIFRX_ErrorCode SPDIFRX Error Code * @{ */ #define HAL_SPDIFRX_ERROR_NONE ((uint32_t)0x00000000) /*!< No error */ #define HAL_SPDIFRX_ERROR_TIMEOUT ((uint32_t)0x00000001) /*!< Timeout error */ #define HAL_SPDIFRX_ERROR_OVR ((uint32_t)0x00000002) /*!< OVR error */ #define HAL_SPDIFRX_ERROR_PE ((uint32_t)0x00000004) /*!< Parity error */ #define HAL_SPDIFRX_ERROR_DMA ((uint32_t)0x00000008) /*!< DMA transfer error */ #define HAL_SPDIFRX_ERROR_UNKNOWN ((uint32_t)0x00000010) /*!< Unknown Error error */ /** * @} */ /** @defgroup SPDIFRX_Input_Selection SPDIFRX Input Selection * @{ */ #define SPDIFRX_INPUT_IN0 ((uint32_t)0x00000000) #define SPDIFRX_INPUT_IN1 ((uint32_t)0x00010000) #define SPDIFRX_INPUT_IN2 ((uint32_t)0x00020000) #define SPDIFRX_INPUT_IN3 ((uint32_t)0x00030000) /** * @} */ /** @defgroup SPDIFRX_Max_Retries SPDIFRX Maximum Retries * @{ */ #define SPDIFRX_MAXRETRIES_NONE ((uint32_t)0x00000000) #define SPDIFRX_MAXRETRIES_3 ((uint32_t)0x00001000) #define SPDIFRX_MAXRETRIES_15 ((uint32_t)0x00002000) #define SPDIFRX_MAXRETRIES_63 ((uint32_t)0x00003000) /** * @} */ /** @defgroup SPDIFRX_Wait_For_Activity SPDIFRX Wait For Activity * @{ */ #define SPDIFRX_WAITFORACTIVITY_OFF ((uint32_t)0x00000000) #define SPDIFRX_WAITFORACTIVITY_ON ((uint32_t)SPDIFRX_CR_WFA) /** * @} */ /** @defgroup SPDIFRX_PT_Mask SPDIFRX Preamble Type Mask * @{ */ #define SPDIFRX_PREAMBLETYPEMASK_OFF ((uint32_t)0x00000000) #define SPDIFRX_PREAMBLETYPEMASK_ON ((uint32_t)SPDIFRX_CR_PTMSK) /** * @} */ /** @defgroup SPDIFRX_ChannelStatus_Mask SPDIFRX Channel Status Mask * @{ */ #define SPDIFRX_CHANNELSTATUS_OFF ((uint32_t)0x00000000) /* The channel status and user bits are copied into the SPDIF_DR */ #define SPDIFRX_CHANNELSTATUS_ON ((uint32_t)SPDIFRX_CR_CUMSK) /* The channel status and user bits are not copied into the SPDIF_DR, zeros are written instead*/ /** * @} */ /** @defgroup SPDIFRX_V_Mask SPDIFRX Validity Mask * @{ */ #define SPDIFRX_VALIDITYMASK_OFF ((uint32_t)0x00000000) #define SPDIFRX_VALIDITYMASK_ON ((uint32_t)SPDIFRX_CR_VMSK) /** * @} */ /** @defgroup SPDIFRX_PE_Mask SPDIFRX Parity Error Mask * @{ */ #define SPDIFRX_PARITYERRORMASK_OFF ((uint32_t)0x00000000) #define SPDIFRX_PARITYERRORMASK_ON ((uint32_t)SPDIFRX_CR_PMSK) /** * @} */ /** @defgroup SPDIFRX_Channel_Selection SPDIFRX Channel Selection * @{ */ #define SPDIFRX_CHANNEL_A ((uint32_t)0x00000000) #define SPDIFRX_CHANNEL_B ((uint32_t)SPDIFRX_CR_CHSEL) /** * @} */ /** @defgroup SPDIFRX_Data_Format SPDIFRX Data Format * @{ */ #define SPDIFRX_DATAFORMAT_LSB ((uint32_t)0x00000000) #define SPDIFRX_DATAFORMAT_MSB ((uint32_t)0x00000010) #define SPDIFRX_DATAFORMAT_32BITS ((uint32_t)0x00000020) /** * @} */ /** @defgroup SPDIFRX_Stereo_Mode SPDIFRX Stereo Mode * @{ */ #define SPDIFRX_STEREOMODE_DISABLE ((uint32_t)0x00000000) #define SPDIFRX_STEREOMODE_ENABLE ((uint32_t)SPDIFRX_CR_RXSTEO) /** * @} */ /** @defgroup SPDIFRX_State SPDIFRX State * @{ */ #define SPDIFRX_STATE_IDLE ((uint32_t)0xFFFFFFFC) #define SPDIFRX_STATE_SYNC ((uint32_t)0x00000001) #define SPDIFRX_STATE_RCV ((uint32_t)SPDIFRX_CR_SPDIFEN) /** * @} */ /** @defgroup SPDIFRX_Interrupts_Definition SPDIFRX Interrupts Definition * @{ */ #define SPDIFRX_IT_RXNE ((uint32_t)SPDIFRX_IMR_RXNEIE) #define SPDIFRX_IT_CSRNE ((uint32_t)SPDIFRX_IMR_CSRNEIE) #define SPDIFRX_IT_PERRIE ((uint32_t)SPDIFRX_IMR_PERRIE) #define SPDIFRX_IT_OVRIE ((uint32_t)SPDIFRX_IMR_OVRIE) #define SPDIFRX_IT_SBLKIE ((uint32_t)SPDIFRX_IMR_SBLKIE) #define SPDIFRX_IT_SYNCDIE ((uint32_t)SPDIFRX_IMR_SYNCDIE) #define SPDIFRX_IT_IFEIE ((uint32_t)SPDIFRX_IMR_IFEIE ) /** * @} */ /** @defgroup SPDIFRX_Flags_Definition SPDIFRX Flags Definition * @{ */ #define SPDIFRX_FLAG_RXNE ((uint32_t)SPDIFRX_SR_RXNE) #define SPDIFRX_FLAG_CSRNE ((uint32_t)SPDIFRX_SR_CSRNE) #define SPDIFRX_FLAG_PERR ((uint32_t)SPDIFRX_SR_PERR) #define SPDIFRX_FLAG_OVR ((uint32_t)SPDIFRX_SR_OVR) #define SPDIFRX_FLAG_SBD ((uint32_t)SPDIFRX_SR_SBD) #define SPDIFRX_FLAG_SYNCD ((uint32_t)SPDIFRX_SR_SYNCD) #define SPDIFRX_FLAG_FERR ((uint32_t)SPDIFRX_SR_FERR) #define SPDIFRX_FLAG_SERR ((uint32_t)SPDIFRX_SR_SERR) #define SPDIFRX_FLAG_TERR ((uint32_t)SPDIFRX_SR_TERR) /** * @} */ /** * @} */ /* Exported macros -----------------------------------------------------------*/ /** @defgroup SPDIFRX_Exported_macros SPDIFRX Exported Macros * @{ */ /** @brief Reset SPDIFRX handle state * @param __HANDLE__: SPDIFRX handle. * @retval None */ #define __HAL_SPDIFRX_RESET_HANDLE_STATE(__HANDLE__) ((__HANDLE__)->State = (uint16_t)SPDIFRX_CR_SPDIFEN) /** @brief Disable the specified SPDIFRX peripheral (IDLE State). * @param __HANDLE__: specifies the SPDIFRX Handle. * @retval None */ #define __HAL_SPDIFRX_IDLE(__HANDLE__) ((__HANDLE__)->Instance->CR &= SPDIFRX_STATE_IDLE) /** @brief Enable the specified SPDIFRX peripheral (SYNC State). * @param __HANDLE__: specifies the SPDIFRX Handle. * @retval None */ #define __HAL_SPDIFRX_SYNC(__HANDLE__) ((__HANDLE__)->Instance->CR |= SPDIFRX_STATE_SYNC) /** @brief Enable the specified SPDIFRX peripheral (RCV State). * @param __HANDLE__: specifies the SPDIFRX Handle. * @retval None */ #define __HAL_SPDIFRX_RCV(__HANDLE__) ((__HANDLE__)->Instance->CR |= SPDIFRX_STATE_RCV) /** @brief Enable or disable the specified SPDIFRX interrupts. * @param __HANDLE__: specifies the SPDIFRX Handle. * @param __INTERRUPT__: specifies the interrupt source to enable or disable. * This parameter can be one of the following values: * @arg SPDIFRX_IT_RXNE * @arg SPDIFRX_IT_CSRNE * @arg SPDIFRX_IT_PERRIE * @arg SPDIFRX_IT_OVRIE * @arg SPDIFRX_IT_SBLKIE * @arg SPDIFRX_IT_SYNCDIE * @arg SPDIFRX_IT_IFEIE * @retval None */ #define __HAL_SPDIFRX_ENABLE_IT(__HANDLE__, __INTERRUPT__) ((__HANDLE__)->Instance->IMR |= (__INTERRUPT__)) #define __HAL_SPDIFRX_DISABLE_IT(__HANDLE__, __INTERRUPT__) ((__HANDLE__)->Instance->IMR &= (uint16_t)(~(__INTERRUPT__))) /** @brief Checks if the specified SPDIFRX interrupt source is enabled or disabled. * @param __HANDLE__: specifies the SPDIFRX Handle. * @param __INTERRUPT__: specifies the SPDIFRX interrupt source to check. * This parameter can be one of the following values: * @arg SPDIFRX_IT_RXNE * @arg SPDIFRX_IT_CSRNE * @arg SPDIFRX_IT_PERRIE * @arg SPDIFRX_IT_OVRIE * @arg SPDIFRX_IT_SBLKIE * @arg SPDIFRX_IT_SYNCDIE * @arg SPDIFRX_IT_IFEIE * @retval The new state of __IT__ (TRUE or FALSE). */ #define __HAL_SPDIFRX_GET_IT_SOURCE(__HANDLE__, __INTERRUPT__) ((((__HANDLE__)->Instance->IMR & (__INTERRUPT__)) == (__INTERRUPT__)) ? SET : RESET) /** @brief Checks whether the specified SPDIFRX flag is set or not. * @param __HANDLE__: specifies the SPDIFRX Handle. * @param __FLAG__: specifies the flag to check. * This parameter can be one of the following values: * @arg SPDIFRX_FLAG_RXNE * @arg SPDIFRX_FLAG_CSRNE * @arg SPDIFRX_FLAG_PERR * @arg SPDIFRX_FLAG_OVR * @arg SPDIFRX_FLAG_SBD * @arg SPDIFRX_FLAG_SYNCD * @arg SPDIFRX_FLAG_FERR * @arg SPDIFRX_FLAG_SERR * @arg SPDIFRX_FLAG_TERR * @retval The new state of __FLAG__ (TRUE or FALSE). */ #define __HAL_SPDIFRX_GET_FLAG(__HANDLE__, __FLAG__) ((((__HANDLE__)->Instance->SR) & (__FLAG__)) == (__FLAG__)) /** @brief Clears the specified SPDIFRX SR flag, in setting the proper IFCR register bit. * @param __HANDLE__: specifies the USART Handle. * @param __IT_CLEAR__: specifies the interrupt clear register flag that needs to be set * to clear the corresponding interrupt * This parameter can be one of the following values: * @arg SPDIFRX_FLAG_PERR * @arg SPDIFRX_FLAG_OVR * @arg SPDIFRX_SR_SBD * @arg SPDIFRX_SR_SYNCD * @retval None */ #define __HAL_SPDIFRX_CLEAR_IT(__HANDLE__, __IT_CLEAR__) ((__HANDLE__)->Instance->IFCR = (uint32_t)(__IT_CLEAR__)) /** * @} */ /* Exported functions --------------------------------------------------------*/ /** @addtogroup SPDIFRX_Exported_Functions * @{ */ /** @addtogroup SPDIFRX_Exported_Functions_Group1 * @{ */ /* Initialization/de-initialization functions **********************************/ HAL_StatusTypeDef HAL_SPDIFRX_Init(SPDIFRX_HandleTypeDef *hspdif); HAL_StatusTypeDef HAL_SPDIFRX_DeInit (SPDIFRX_HandleTypeDef *hspdif); void HAL_SPDIFRX_MspInit(SPDIFRX_HandleTypeDef *hspdif); void HAL_SPDIFRX_MspDeInit(SPDIFRX_HandleTypeDef *hspdif); HAL_StatusTypeDef HAL_SPDIFRX_SetDataFormat(SPDIFRX_HandleTypeDef *hspdif, SPDIFRX_SetDataFormatTypeDef sDataFormat); /** * @} */ /** @addtogroup SPDIFRX_Exported_Functions_Group2 * @{ */ /* I/O operation functions ***************************************************/ /* Blocking mode: Polling */ HAL_StatusTypeDef HAL_SPDIFRX_ReceiveDataFlow(SPDIFRX_HandleTypeDef *hspdif, uint32_t *pData, uint16_t Size, uint32_t Timeout); HAL_StatusTypeDef HAL_SPDIFRX_ReceiveControlFlow(SPDIFRX_HandleTypeDef *hspdif, uint32_t *pData, uint16_t Size, uint32_t Timeout); /* Non-Blocking mode: Interrupt */ HAL_StatusTypeDef HAL_SPDIFRX_ReceiveControlFlow_IT(SPDIFRX_HandleTypeDef *hspdif, uint32_t *pData, uint16_t Size); HAL_StatusTypeDef HAL_SPDIFRX_ReceiveDataFlow_IT(SPDIFRX_HandleTypeDef *hspdif, uint32_t *pData, uint16_t Size); void HAL_SPDIFRX_IRQHandler(SPDIFRX_HandleTypeDef *hspdif); /* Non-Blocking mode: DMA */ HAL_StatusTypeDef HAL_SPDIFRX_ReceiveControlFlow_DMA(SPDIFRX_HandleTypeDef *hspdif, uint32_t *pData, uint16_t Size); HAL_StatusTypeDef HAL_SPDIFRX_ReceiveDataFlow_DMA(SPDIFRX_HandleTypeDef *hspdif, uint32_t *pData, uint16_t Size); HAL_StatusTypeDef HAL_SPDIFRX_DMAStop(SPDIFRX_HandleTypeDef *hspdif); /* Callbacks used in non blocking modes (Interrupt and DMA) *******************/ void HAL_SPDIFRX_RxHalfCpltCallback(SPDIFRX_HandleTypeDef *hspdif); void HAL_SPDIFRX_RxCpltCallback(SPDIFRX_HandleTypeDef *hspdif); void HAL_SPDIFRX_ErrorCallback(SPDIFRX_HandleTypeDef *hspdif); void HAL_SPDIFRX_CxHalfCpltCallback(SPDIFRX_HandleTypeDef *hspdif); void HAL_SPDIFRX_CxCpltCallback(SPDIFRX_HandleTypeDef *hspdif); /** * @} */ /** @addtogroup SPDIFRX_Exported_Functions_Group3 * @{ */ /* Peripheral Control and State functions ************************************/ HAL_SPDIFRX_StateTypeDef HAL_SPDIFRX_GetState(SPDIFRX_HandleTypeDef *hspdif); uint32_t HAL_SPDIFRX_GetError(SPDIFRX_HandleTypeDef *hspdif); /** * @} */ /** * @} */ /* Private types -------------------------------------------------------------*/ /* Private variables ---------------------------------------------------------*/ /* Private constants ---------------------------------------------------------*/ /* Private macros ------------------------------------------------------------*/ /** @defgroup SPDIFRX_Private_Macros SPDIFRX Private Macros * @{ */ #define IS_SPDIFRX_INPUT_SELECT(INPUT) (((INPUT) == SPDIFRX_INPUT_IN1) || \ ((INPUT) == SPDIFRX_INPUT_IN2) || \ ((INPUT) == SPDIFRX_INPUT_IN3) || \ ((INPUT) == SPDIFRX_INPUT_IN0)) #define IS_SPDIFRX_MAX_RETRIES(RET) (((RET) == SPDIFRX_MAXRETRIES_NONE) || \ ((RET) == SPDIFRX_MAXRETRIES_3) || \ ((RET) == SPDIFRX_MAXRETRIES_15) || \ ((RET) == SPDIFRX_MAXRETRIES_63)) #define IS_SPDIFRX_WAIT_FOR_ACTIVITY(VAL) (((VAL) == SPDIFRX_WAITFORACTIVITY_ON) || \ ((VAL) == SPDIFRX_WAITFORACTIVITY_OFF)) #define IS_PREAMBLE_TYPE_MASK(VAL) (((VAL) == SPDIFRX_PREAMBLETYPEMASK_ON) || \ ((VAL) == SPDIFRX_PREAMBLETYPEMASK_OFF)) #define IS_VALIDITY_MASK(VAL) (((VAL) == SPDIFRX_VALIDITYMASK_OFF) || \ ((VAL) == SPDIFRX_VALIDITYMASK_ON)) #define IS_PARITY_ERROR_MASK(VAL) (((VAL) == SPDIFRX_PARITYERRORMASK_OFF) || \ ((VAL) == SPDIFRX_PARITYERRORMASK_ON)) #define IS_SPDIFRX_CHANNEL(CHANNEL) (((CHANNEL) == SPDIFRX_CHANNEL_A) || \ ((CHANNEL) == SPDIFRX_CHANNEL_B)) #define IS_SPDIFRX_DATA_FORMAT(FORMAT) (((FORMAT) == SPDIFRX_DATAFORMAT_LSB) || \ ((FORMAT) == SPDIFRX_DATAFORMAT_MSB) || \ ((FORMAT) == SPDIFRX_DATAFORMAT_32BITS)) #define IS_STEREO_MODE(MODE) (((MODE) == SPDIFRX_STEREOMODE_DISABLE) || \ ((MODE) == SPDIFRX_STEREOMODE_ENABLE)) #define IS_CHANNEL_STATUS_MASK(VAL) (((VAL) == SPDIFRX_CHANNELSTATUS_ON) || \ ((VAL) == SPDIFRX_CHANNELSTATUS_OFF)) /** * @} */ /* Private functions ---------------------------------------------------------*/ /** @defgroup SPDIFRX_Private_Functions SPDIFRX Private Functions * @{ */ /** * @} */ /** * @} */ /** * @} */ #endif /* STM32F446xx */ #ifdef __cplusplus } #endif #endif /* __STM32F4xx_HAL_SPDIFRX_H */ /************************ (C) COPYRIGHT STMicroelectronics *****END OF FILE****/ ================================================ FILE: Zelig/mbed/TARGET_NUCLEO_F401RE/stm32f4xx_hal_spi.h ================================================ /** ****************************************************************************** * @file stm32f4xx_hal_spi.h * @author MCD Application Team * @version V1.4.1 * @date 09-October-2015 * @brief Header file of SPI HAL module. ****************************************************************************** * @attention * *

© COPYRIGHT(c) 2015 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. * ****************************************************************************** */ /* Define to prevent recursive inclusion -------------------------------------*/ #ifndef __STM32F4xx_HAL_SPI_H #define __STM32F4xx_HAL_SPI_H #ifdef __cplusplus extern "C" { #endif /* Includes ------------------------------------------------------------------*/ #include "stm32f4xx_hal_def.h" /** @addtogroup STM32F4xx_HAL_Driver * @{ */ /** @addtogroup SPI * @{ */ /* Exported types ------------------------------------------------------------*/ /** @defgroup SPI_Exported_Types SPI Exported Types * @{ */ /** * @brief SPI Configuration Structure definition */ typedef struct { uint32_t Mode; /*!< Specifies the SPI operating mode. This parameter can be a value of @ref SPI_mode */ uint32_t Direction; /*!< Specifies the SPI Directional mode state. This parameter can be a value of @ref SPI_Direction_mode */ uint32_t DataSize; /*!< Specifies the SPI data size. This parameter can be a value of @ref SPI_data_size */ uint32_t CLKPolarity; /*!< Specifies the serial clock steady state. This parameter can be a value of @ref SPI_Clock_Polarity */ uint32_t CLKPhase; /*!< Specifies the clock active edge for the bit capture. This parameter can be a value of @ref SPI_Clock_Phase */ uint32_t NSS; /*!< Specifies whether the NSS signal is managed by hardware (NSS pin) or by software using the SSI bit. This parameter can be a value of @ref SPI_Slave_Select_management */ uint32_t BaudRatePrescaler; /*!< Specifies the Baud Rate prescaler value which will be used to configure the transmit and receive SCK clock. This parameter can be a value of @ref SPI_BaudRate_Prescaler @note The communication clock is derived from the master clock. The slave clock does not need to be set */ uint32_t FirstBit; /*!< Specifies whether data transfers start from MSB or LSB bit. This parameter can be a value of @ref SPI_MSB_LSB_transmission */ uint32_t TIMode; /*!< Specifies if the TI mode is enabled or not. This parameter can be a value of @ref SPI_TI_mode */ uint32_t CRCCalculation; /*!< Specifies if the CRC calculation is enabled or not. This parameter can be a value of @ref SPI_CRC_Calculation */ uint32_t CRCPolynomial; /*!< Specifies the polynomial used for the CRC calculation. This parameter must be a number between Min_Data = 0 and Max_Data = 65535 */ }SPI_InitTypeDef; /** * @brief HAL SPI State structure definition */ typedef enum { HAL_SPI_STATE_RESET = 0x00, /*!< SPI not yet initialized or disabled */ HAL_SPI_STATE_READY = 0x01, /*!< SPI initialized and ready for use */ HAL_SPI_STATE_BUSY = 0x02, /*!< SPI process is ongoing */ HAL_SPI_STATE_BUSY_TX = 0x12, /*!< Data Transmission process is ongoing */ HAL_SPI_STATE_BUSY_RX = 0x22, /*!< Data Reception process is ongoing */ HAL_SPI_STATE_BUSY_TX_RX = 0x32, /*!< Data Transmission and Reception process is ongoing */ HAL_SPI_STATE_ERROR = 0x03 /*!< SPI error state */ }HAL_SPI_StateTypeDef; /** * @brief SPI handle Structure definition */ typedef struct __SPI_HandleTypeDef { SPI_TypeDef *Instance; /* SPI registers base address */ SPI_InitTypeDef Init; /* SPI communication parameters */ uint8_t *pTxBuffPtr; /* Pointer to SPI Tx transfer Buffer */ uint16_t TxXferSize; /* SPI Tx transfer size */ uint16_t TxXferCount; /* SPI Tx Transfer Counter */ uint8_t *pRxBuffPtr; /* Pointer to SPI Rx transfer Buffer */ uint16_t RxXferSize; /* SPI Rx transfer size */ uint16_t RxXferCount; /* SPI Rx Transfer Counter */ DMA_HandleTypeDef *hdmatx; /* SPI Tx DMA handle parameters */ DMA_HandleTypeDef *hdmarx; /* SPI Rx DMA handle parameters */ void (*RxISR)(struct __SPI_HandleTypeDef * hspi); /* function pointer on Rx ISR */ void (*TxISR)(struct __SPI_HandleTypeDef * hspi); /* function pointer on Tx ISR */ HAL_LockTypeDef Lock; /* SPI locking object */ __IO HAL_SPI_StateTypeDef State; /* SPI communication state */ __IO uint32_t ErrorCode; /* SPI Error code */ }SPI_HandleTypeDef; /** * @} */ /* Exported constants --------------------------------------------------------*/ /** @defgroup SPI_Exported_Constants SPI Exported Constants * @{ */ /** @defgroup SPI_Error_Code SPI Error Code * @brief SPI Error Code * @{ */ #define HAL_SPI_ERROR_NONE ((uint32_t)0x00000000) /*!< No error */ #define HAL_SPI_ERROR_MODF ((uint32_t)0x00000001) /*!< MODF error */ #define HAL_SPI_ERROR_CRC ((uint32_t)0x00000002) /*!< CRC error */ #define HAL_SPI_ERROR_OVR ((uint32_t)0x00000004) /*!< OVR error */ #define HAL_SPI_ERROR_FRE ((uint32_t)0x00000008) /*!< FRE error */ #define HAL_SPI_ERROR_DMA ((uint32_t)0x00000010) /*!< DMA transfer error */ #define HAL_SPI_ERROR_FLAG ((uint32_t)0x00000020) /*!< Flag: RXNE,TXE, BSY */ /** * @} */ /** @defgroup SPI_mode SPI Mode * @{ */ #define SPI_MODE_SLAVE ((uint32_t)0x00000000) #define SPI_MODE_MASTER (SPI_CR1_MSTR | SPI_CR1_SSI) /** * @} */ /** @defgroup SPI_Direction_mode SPI Direction Mode * @{ */ #define SPI_DIRECTION_2LINES ((uint32_t)0x00000000) #define SPI_DIRECTION_2LINES_RXONLY SPI_CR1_RXONLY #define SPI_DIRECTION_1LINE SPI_CR1_BIDIMODE /** * @} */ /** @defgroup SPI_data_size SPI Data Size * @{ */ #define SPI_DATASIZE_8BIT ((uint32_t)0x00000000) #define SPI_DATASIZE_16BIT SPI_CR1_DFF /** * @} */ /** @defgroup SPI_Clock_Polarity SPI Clock Polarity * @{ */ #define SPI_POLARITY_LOW ((uint32_t)0x00000000) #define SPI_POLARITY_HIGH SPI_CR1_CPOL /** * @} */ /** @defgroup SPI_Clock_Phase SPI Clock Phase * @{ */ #define SPI_PHASE_1EDGE ((uint32_t)0x00000000) #define SPI_PHASE_2EDGE SPI_CR1_CPHA /** * @} */ /** @defgroup SPI_Slave_Select_management SPI Slave Select Management * @{ */ #define SPI_NSS_SOFT SPI_CR1_SSM #define SPI_NSS_HARD_INPUT ((uint32_t)0x00000000) #define SPI_NSS_HARD_OUTPUT ((uint32_t)0x00040000) /** * @} */ /** @defgroup SPI_BaudRate_Prescaler SPI BaudRate Prescaler * @{ */ #define SPI_BAUDRATEPRESCALER_2 ((uint32_t)0x00000000) #define SPI_BAUDRATEPRESCALER_4 ((uint32_t)0x00000008) #define SPI_BAUDRATEPRESCALER_8 ((uint32_t)0x00000010) #define SPI_BAUDRATEPRESCALER_16 ((uint32_t)0x00000018) #define SPI_BAUDRATEPRESCALER_32 ((uint32_t)0x00000020) #define SPI_BAUDRATEPRESCALER_64 ((uint32_t)0x00000028) #define SPI_BAUDRATEPRESCALER_128 ((uint32_t)0x00000030) #define SPI_BAUDRATEPRESCALER_256 ((uint32_t)0x00000038) /** * @} */ /** @defgroup SPI_MSB_LSB_transmission SPI MSB LSB Transsmission * @{ */ #define SPI_FIRSTBIT_MSB ((uint32_t)0x00000000) #define SPI_FIRSTBIT_LSB SPI_CR1_LSBFIRST /** * @} */ /** @defgroup SPI_TI_mode SPI TI Mode * @{ */ #define SPI_TIMODE_DISABLE ((uint32_t)0x00000000) #define SPI_TIMODE_ENABLE SPI_CR2_FRF /** * @} */ /** @defgroup SPI_CRC_Calculation SPI CRC Calculation * @{ */ #define SPI_CRCCALCULATION_DISABLE ((uint32_t)0x00000000) #define SPI_CRCCALCULATION_ENABLE SPI_CR1_CRCEN /** * @} */ /** @defgroup SPI_Interrupt_definition SPI Interrupt Definition * @{ */ #define SPI_IT_TXE SPI_CR2_TXEIE #define SPI_IT_RXNE SPI_CR2_RXNEIE #define SPI_IT_ERR SPI_CR2_ERRIE /** * @} */ /** @defgroup SPI_Flags_definition SPI Flags Definition * @{ */ #define SPI_FLAG_RXNE SPI_SR_RXNE #define SPI_FLAG_TXE SPI_SR_TXE #define SPI_FLAG_CRCERR SPI_SR_CRCERR #define SPI_FLAG_MODF SPI_SR_MODF #define SPI_FLAG_OVR SPI_SR_OVR #define SPI_FLAG_BSY SPI_SR_BSY #define SPI_FLAG_FRE SPI_SR_FRE /** * @} */ /** * @} */ /* Exported macro ------------------------------------------------------------*/ /** @defgroup SPI_Exported_Macros SPI Exported Macros * @{ */ /** @brief Reset SPI handle state * @param __HANDLE__: specifies the SPI handle. * This parameter can be SPI where x: 1, 2, or 3 to select the SPI peripheral. * @retval None */ #define __HAL_SPI_RESET_HANDLE_STATE(__HANDLE__) ((__HANDLE__)->State = HAL_SPI_STATE_RESET) /** @brief Enable or disable the specified SPI interrupts. * @param __HANDLE__: specifies the SPI handle. * This parameter can be SPI where x: 1, 2, or 3 to select the SPI peripheral. * @param __INTERRUPT__: specifies the interrupt source to enable or disable. * This parameter can be one of the following values: * @arg SPI_IT_TXE: Tx buffer empty interrupt enable * @arg SPI_IT_RXNE: RX buffer not empty interrupt enable * @arg SPI_IT_ERR: Error interrupt enable * @retval None */ #define __HAL_SPI_ENABLE_IT(__HANDLE__, __INTERRUPT__) ((__HANDLE__)->Instance->CR2 |= (__INTERRUPT__)) #define __HAL_SPI_DISABLE_IT(__HANDLE__, __INTERRUPT__) ((__HANDLE__)->Instance->CR2 &= (~(__INTERRUPT__))) /** @brief Check if the specified SPI interrupt source is enabled or disabled. * @param __HANDLE__: specifies the SPI handle. * This parameter can be SPI where x: 1, 2, or 3 to select the SPI peripheral. * @param __INTERRUPT__: specifies the SPI interrupt source to check. * This parameter can be one of the following values: * @arg SPI_IT_TXE: Tx buffer empty interrupt enable * @arg SPI_IT_RXNE: RX buffer not empty interrupt enable * @arg SPI_IT_ERR: Error interrupt enable * @retval The new state of __IT__ (TRUE or FALSE). */ #define __HAL_SPI_GET_IT_SOURCE(__HANDLE__, __INTERRUPT__) ((((__HANDLE__)->Instance->CR2 & (__INTERRUPT__)) == (__INTERRUPT__)) ? SET : RESET) /** @brief Check whether the specified SPI flag is set or not. * @param __HANDLE__: specifies the SPI handle. * This parameter can be SPI where x: 1, 2, or 3 to select the SPI peripheral. * @param __FLAG__: specifies the flag to check. * This parameter can be one of the following values: * @arg SPI_FLAG_RXNE: Receive buffer not empty flag * @arg SPI_FLAG_TXE: Transmit buffer empty flag * @arg SPI_FLAG_CRCERR: CRC error flag * @arg SPI_FLAG_MODF: Mode fault flag * @arg SPI_FLAG_OVR: Overrun flag * @arg SPI_FLAG_BSY: Busy flag * @arg SPI_FLAG_FRE: Frame format error flag * @retval The new state of __FLAG__ (TRUE or FALSE). */ #define __HAL_SPI_GET_FLAG(__HANDLE__, __FLAG__) ((((__HANDLE__)->Instance->SR) & (__FLAG__)) == (__FLAG__)) /** @brief Clear the SPI CRCERR pending flag. * @param __HANDLE__: specifies the SPI handle. * This parameter can be SPI where x: 1, 2, or 3 to select the SPI peripheral. * @retval None */ #define __HAL_SPI_CLEAR_CRCERRFLAG(__HANDLE__) ((__HANDLE__)->Instance->SR = ~(SPI_FLAG_CRCERR)) /** @brief Clear the SPI MODF pending flag. * @param __HANDLE__: specifies the SPI handle. * This parameter can be SPI where x: 1, 2, or 3 to select the SPI peripheral. * @retval None */ #define __HAL_SPI_CLEAR_MODFFLAG(__HANDLE__) \ do{ \ __IO uint32_t tmpreg; \ tmpreg = (__HANDLE__)->Instance->SR; \ (__HANDLE__)->Instance->CR1 &= (~SPI_CR1_SPE); \ UNUSED(tmpreg); \ } while(0) /** @brief Clear the SPI OVR pending flag. * @param __HANDLE__: specifies the SPI handle. * This parameter can be SPI where x: 1, 2, or 3 to select the SPI peripheral. * @retval None */ #define __HAL_SPI_CLEAR_OVRFLAG(__HANDLE__) \ do{ \ __IO uint32_t tmpreg; \ tmpreg = (__HANDLE__)->Instance->DR; \ tmpreg = (__HANDLE__)->Instance->SR; \ UNUSED(tmpreg); \ } while(0) /** @brief Clear the SPI FRE pending flag. * @param __HANDLE__: specifies the SPI handle. * This parameter can be SPI where x: 1, 2, or 3 to select the SPI peripheral. * @retval None */ #define __HAL_SPI_CLEAR_FREFLAG(__HANDLE__) \ do{ \ __IO uint32_t tmpreg; \ tmpreg = (__HANDLE__)->Instance->SR; \ UNUSED(tmpreg); \ }while(0) /** @brief Enable SPI * @param __HANDLE__: specifies the SPI Handle. * @retval None */ #define __HAL_SPI_ENABLE(__HANDLE__) ((__HANDLE__)->Instance->CR1 |= SPI_CR1_SPE) /** @brief Disable SPI * @param __HANDLE__: specifies the SPI Handle. * @retval None */ #define __HAL_SPI_DISABLE(__HANDLE__) ((__HANDLE__)->Instance->CR1 &= ~SPI_CR1_SPE) /** * @} */ /* Exported functions --------------------------------------------------------*/ /** @addtogroup SPI_Exported_Functions * @{ */ /** @addtogroup SPI_Exported_Functions_Group1 * @{ */ /* Initialization/de-initialization functions **********************************/ HAL_StatusTypeDef HAL_SPI_Init(SPI_HandleTypeDef *hspi); HAL_StatusTypeDef HAL_SPI_DeInit (SPI_HandleTypeDef *hspi); void HAL_SPI_MspInit(SPI_HandleTypeDef *hspi); void HAL_SPI_MspDeInit(SPI_HandleTypeDef *hspi); /** * @} */ /** @addtogroup SPI_Exported_Functions_Group2 * @{ */ /* I/O operation functions *****************************************************/ HAL_StatusTypeDef HAL_SPI_Transmit(SPI_HandleTypeDef *hspi, uint8_t *pData, uint16_t Size, uint32_t Timeout); HAL_StatusTypeDef HAL_SPI_Receive(SPI_HandleTypeDef *hspi, uint8_t *pData, uint16_t Size, uint32_t Timeout); HAL_StatusTypeDef HAL_SPI_TransmitReceive(SPI_HandleTypeDef *hspi, uint8_t *pTxData, uint8_t *pRxData, uint16_t Size, uint32_t Timeout); HAL_StatusTypeDef HAL_SPI_Transmit_IT(SPI_HandleTypeDef *hspi, uint8_t *pData, uint16_t Size); HAL_StatusTypeDef HAL_SPI_Receive_IT(SPI_HandleTypeDef *hspi, uint8_t *pData, uint16_t Size); HAL_StatusTypeDef HAL_SPI_TransmitReceive_IT(SPI_HandleTypeDef *hspi, uint8_t *pTxData, uint8_t *pRxData, uint16_t Size); HAL_StatusTypeDef HAL_SPI_Transmit_DMA(SPI_HandleTypeDef *hspi, uint8_t *pData, uint16_t Size); HAL_StatusTypeDef HAL_SPI_Receive_DMA(SPI_HandleTypeDef *hspi, uint8_t *pData, uint16_t Size); HAL_StatusTypeDef HAL_SPI_TransmitReceive_DMA(SPI_HandleTypeDef *hspi, uint8_t *pTxData, uint8_t *pRxData, uint16_t Size); HAL_StatusTypeDef HAL_SPI_DMAPause(SPI_HandleTypeDef *hspi); HAL_StatusTypeDef HAL_SPI_DMAResume(SPI_HandleTypeDef *hspi); HAL_StatusTypeDef HAL_SPI_DMAStop(SPI_HandleTypeDef *hspi); void HAL_SPI_IRQHandler(SPI_HandleTypeDef *hspi); void HAL_SPI_TxCpltCallback(SPI_HandleTypeDef *hspi); void HAL_SPI_RxCpltCallback(SPI_HandleTypeDef *hspi); void HAL_SPI_TxRxCpltCallback(SPI_HandleTypeDef *hspi); void HAL_SPI_ErrorCallback(SPI_HandleTypeDef *hspi); void HAL_SPI_TxHalfCpltCallback(SPI_HandleTypeDef *hspi); void HAL_SPI_RxHalfCpltCallback(SPI_HandleTypeDef *hspi); void HAL_SPI_TxRxHalfCpltCallback(SPI_HandleTypeDef *hspi); /** * @} */ /** @addtogroup SPI_Exported_Functions_Group3 * @{ */ /* Peripheral State and Control functions **************************************/ HAL_SPI_StateTypeDef HAL_SPI_GetState(SPI_HandleTypeDef *hspi); uint32_t HAL_SPI_GetError(SPI_HandleTypeDef *hspi); /** * @} */ /** * @} */ /* Private types -------------------------------------------------------------*/ /* Private variables ---------------------------------------------------------*/ /* Private constants ---------------------------------------------------------*/ /** @defgroup SPI_Private_Constants SPI Private Constants * @{ */ /** * @} */ /* Private macros ------------------------------------------------------------*/ /** @defgroup SPI_Private_Macros SPI Private Macros * @{ */ #define IS_SPI_MODE(MODE) (((MODE) == SPI_MODE_SLAVE) || \ ((MODE) == SPI_MODE_MASTER)) #define IS_SPI_DIRECTION_MODE(MODE) (((MODE) == SPI_DIRECTION_2LINES) || \ ((MODE) == SPI_DIRECTION_2LINES_RXONLY) || \ ((MODE) == SPI_DIRECTION_1LINE)) #define IS_SPI_DIRECTION_2LINES_OR_1LINE(MODE) (((MODE) == SPI_DIRECTION_2LINES) || \ ((MODE) == SPI_DIRECTION_1LINE)) #define IS_SPI_DIRECTION_2LINES(MODE) ((MODE) == SPI_DIRECTION_2LINES) #define IS_SPI_DATASIZE(DATASIZE) (((DATASIZE) == SPI_DATASIZE_16BIT) || \ ((DATASIZE) == SPI_DATASIZE_8BIT)) #define IS_SPI_CPOL(CPOL) (((CPOL) == SPI_POLARITY_LOW) || \ ((CPOL) == SPI_POLARITY_HIGH)) #define IS_SPI_CPHA(CPHA) (((CPHA) == SPI_PHASE_1EDGE) || \ ((CPHA) == SPI_PHASE_2EDGE)) #define IS_SPI_NSS(NSS) (((NSS) == SPI_NSS_SOFT) || \ ((NSS) == SPI_NSS_HARD_INPUT) || \ ((NSS) == SPI_NSS_HARD_OUTPUT)) #define IS_SPI_BAUDRATE_PRESCALER(PRESCALER) (((PRESCALER) == SPI_BAUDRATEPRESCALER_2) || \ ((PRESCALER) == SPI_BAUDRATEPRESCALER_4) || \ ((PRESCALER) == SPI_BAUDRATEPRESCALER_8) || \ ((PRESCALER) == SPI_BAUDRATEPRESCALER_16) || \ ((PRESCALER) == SPI_BAUDRATEPRESCALER_32) || \ ((PRESCALER) == SPI_BAUDRATEPRESCALER_64) || \ ((PRESCALER) == SPI_BAUDRATEPRESCALER_128) || \ ((PRESCALER) == SPI_BAUDRATEPRESCALER_256)) #define IS_SPI_FIRST_BIT(BIT) (((BIT) == SPI_FIRSTBIT_MSB) || \ ((BIT) == SPI_FIRSTBIT_LSB)) #define IS_SPI_TIMODE(MODE) (((MODE) == SPI_TIMODE_DISABLE) || \ ((MODE) == SPI_TIMODE_ENABLE)) #define IS_SPI_CRC_CALCULATION(CALCULATION) (((CALCULATION) == SPI_CRCCALCULATION_DISABLE) || \ ((CALCULATION) == SPI_CRCCALCULATION_ENABLE)) #define IS_SPI_CRC_POLYNOMIAL(POLYNOMIAL) (((POLYNOMIAL) >= 0x1) && ((POLYNOMIAL) <= 0xFFFF)) #define SPI_1LINE_TX(__HANDLE__) ((__HANDLE__)->Instance->CR1 |= SPI_CR1_BIDIOE) #define SPI_1LINE_RX(__HANDLE__) ((__HANDLE__)->Instance->CR1 &= ~SPI_CR1_BIDIOE) #define SPI_RESET_CRC(__HANDLE__) do{(__HANDLE__)->Instance->CR1 &= (~SPI_CR1_CRCEN);\ (__HANDLE__)->Instance->CR1 |= SPI_CR1_CRCEN;}while(0) /** * @} */ /* Private functions ---------------------------------------------------------*/ /** @defgroup SPI_Private_Functions SPI Private Functions * @{ */ /** * @} */ /** * @} */ /** * @} */ #ifdef __cplusplus } #endif #endif /* __STM32F4xx_HAL_SPI_H */ /************************ (C) COPYRIGHT STMicroelectronics *****END OF FILE****/ ================================================ FILE: Zelig/mbed/TARGET_NUCLEO_F401RE/stm32f4xx_hal_sram.h ================================================ /** ****************************************************************************** * @file stm32f4xx_hal_sram.h * @author MCD Application Team * @version V1.4.1 * @date 09-October-2015 * @brief Header file of SRAM HAL module. ****************************************************************************** * @attention * *

© COPYRIGHT(c) 2015 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. * ****************************************************************************** */ /* Define to prevent recursive inclusion -------------------------------------*/ #ifndef __STM32F4xx_HAL_SRAM_H #define __STM32F4xx_HAL_SRAM_H #ifdef __cplusplus extern "C" { #endif /* Includes ------------------------------------------------------------------*/ #if defined(STM32F405xx) || defined(STM32F415xx) || defined(STM32F407xx)|| defined(STM32F417xx) #include "stm32f4xx_ll_fsmc.h" #endif /* STM32F405xx || STM32F415xx || STM32F407xx || STM32F417xx */ #if defined(STM32F427xx) || defined(STM32F437xx) || defined(STM32F429xx)|| defined(STM32F439xx) ||\ defined(STM32F446xx) || defined(STM32F469xx) || defined(STM32F479xx) #include "stm32f4xx_ll_fmc.h" #endif /* STM32F427xx || STM32F437xx || STM32F429xx || STM32F439xx || STM32F446xx || STM32F469xx || STM32F479xx */ /** @addtogroup STM32F4xx_HAL_Driver * @{ */ #if defined(STM32F405xx) || defined(STM32F415xx) || defined(STM32F407xx) || defined(STM32F417xx) ||\ defined(STM32F427xx) || defined(STM32F437xx) || defined(STM32F429xx) || defined(STM32F439xx) ||\ defined(STM32F446xx) || defined(STM32F469xx) || defined(STM32F479xx) /** @addtogroup SRAM * @{ */ /* Exported typedef ----------------------------------------------------------*/ /** @defgroup SRAM_Exported_Types SRAM Exported Types * @{ */ /** * @brief HAL SRAM State structures definition */ typedef enum { HAL_SRAM_STATE_RESET = 0x00, /*!< SRAM not yet initialized or disabled */ HAL_SRAM_STATE_READY = 0x01, /*!< SRAM initialized and ready for use */ HAL_SRAM_STATE_BUSY = 0x02, /*!< SRAM internal process is ongoing */ HAL_SRAM_STATE_ERROR = 0x03, /*!< SRAM error state */ HAL_SRAM_STATE_PROTECTED = 0x04 /*!< SRAM peripheral NORSRAM device write protected */ }HAL_SRAM_StateTypeDef; /** * @brief SRAM handle Structure definition */ typedef struct { FMC_NORSRAM_TypeDef *Instance; /*!< Register base address */ FMC_NORSRAM_EXTENDED_TypeDef *Extended; /*!< Extended mode register base address */ FMC_NORSRAM_InitTypeDef Init; /*!< SRAM device control configuration parameters */ HAL_LockTypeDef Lock; /*!< SRAM locking object */ __IO HAL_SRAM_StateTypeDef State; /*!< SRAM device access state */ DMA_HandleTypeDef *hdma; /*!< Pointer DMA handler */ }SRAM_HandleTypeDef; /** * @} */ /* Exported constants --------------------------------------------------------*/ /* Exported macro ------------------------------------------------------------*/ /** @defgroup SRAM_Exported_Macros SRAM Exported Macros * @{ */ /** @brief Reset SRAM handle state * @param __HANDLE__: SRAM handle * @retval None */ #define __HAL_SRAM_RESET_HANDLE_STATE(__HANDLE__) ((__HANDLE__)->State = HAL_SRAM_STATE_RESET) /** * @} */ /* Exported functions --------------------------------------------------------*/ /** @addtogroup SRAM_Exported_Functions * @{ */ /** @addtogroup SRAM_Exported_Functions_Group1 * @{ */ /* Initialization/de-initialization functions **********************************/ HAL_StatusTypeDef HAL_SRAM_Init(SRAM_HandleTypeDef *hsram, FMC_NORSRAM_TimingTypeDef *Timing, FMC_NORSRAM_TimingTypeDef *ExtTiming); HAL_StatusTypeDef HAL_SRAM_DeInit(SRAM_HandleTypeDef *hsram); void HAL_SRAM_MspInit(SRAM_HandleTypeDef *hsram); void HAL_SRAM_MspDeInit(SRAM_HandleTypeDef *hsram); void HAL_SRAM_DMA_XferCpltCallback(DMA_HandleTypeDef *hdma); void HAL_SRAM_DMA_XferErrorCallback(DMA_HandleTypeDef *hdma); /** * @} */ /** @addtogroup SRAM_Exported_Functions_Group2 * @{ */ /* I/O operation functions *****************************************************/ HAL_StatusTypeDef HAL_SRAM_Read_8b(SRAM_HandleTypeDef *hsram, uint32_t *pAddress, uint8_t *pDstBuffer, uint32_t BufferSize); HAL_StatusTypeDef HAL_SRAM_Write_8b(SRAM_HandleTypeDef *hsram, uint32_t *pAddress, uint8_t *pSrcBuffer, uint32_t BufferSize); HAL_StatusTypeDef HAL_SRAM_Read_16b(SRAM_HandleTypeDef *hsram, uint32_t *pAddress, uint16_t *pDstBuffer, uint32_t BufferSize); HAL_StatusTypeDef HAL_SRAM_Write_16b(SRAM_HandleTypeDef *hsram, uint32_t *pAddress, uint16_t *pSrcBuffer, uint32_t BufferSize); HAL_StatusTypeDef HAL_SRAM_Read_32b(SRAM_HandleTypeDef *hsram, uint32_t *pAddress, uint32_t *pDstBuffer, uint32_t BufferSize); HAL_StatusTypeDef HAL_SRAM_Write_32b(SRAM_HandleTypeDef *hsram, uint32_t *pAddress, uint32_t *pSrcBuffer, uint32_t BufferSize); HAL_StatusTypeDef HAL_SRAM_Read_DMA(SRAM_HandleTypeDef *hsram, uint32_t *pAddress, uint32_t *pDstBuffer, uint32_t BufferSize); HAL_StatusTypeDef HAL_SRAM_Write_DMA(SRAM_HandleTypeDef *hsram, uint32_t *pAddress, uint32_t *pSrcBuffer, uint32_t BufferSize); /** * @} */ /** @addtogroup SRAM_Exported_Functions_Group3 * @{ */ /* SRAM Control functions ******************************************************/ HAL_StatusTypeDef HAL_SRAM_WriteOperation_Enable(SRAM_HandleTypeDef *hsram); HAL_StatusTypeDef HAL_SRAM_WriteOperation_Disable(SRAM_HandleTypeDef *hsram); /** * @} */ /** @addtogroup SRAM_Exported_Functions_Group4 * @{ */ /* SRAM State functions *********************************************************/ HAL_SRAM_StateTypeDef HAL_SRAM_GetState(SRAM_HandleTypeDef *hsram); /** * @} */ /** * @} */ /* Private types -------------------------------------------------------------*/ /* Private variables ---------------------------------------------------------*/ /* Private constants ---------------------------------------------------------*/ /* Private macros ------------------------------------------------------------*/ /* Private functions ---------------------------------------------------------*/ /** * @} */ #endif /* STM32F405xx || STM32F415xx || STM32F407xx || STM32F417xx || STM32F427xx || STM32F437xx ||\ STM32F429xx || STM32F439xx || STM32F446xx || STM32F469xx || STM32F479xx */ /** * @} */ #ifdef __cplusplus } #endif #endif /* __STM32F4xx_HAL_SRAM_H */ /************************ (C) COPYRIGHT STMicroelectronics *****END OF FILE****/ ================================================ FILE: Zelig/mbed/TARGET_NUCLEO_F401RE/stm32f4xx_hal_tim.h ================================================ /** ****************************************************************************** * @file stm32f4xx_hal_tim.h * @author MCD Application Team * @version V1.4.1 * @date 09-October-2015 * @brief Header file of TIM HAL module. ****************************************************************************** * @attention * *

© COPYRIGHT(c) 2015 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. * ****************************************************************************** */ /* Define to prevent recursive inclusion -------------------------------------*/ #ifndef __STM32F4xx_HAL_TIM_H #define __STM32F4xx_HAL_TIM_H #ifdef __cplusplus extern "C" { #endif /* Includes ------------------------------------------------------------------*/ #include "stm32f4xx_hal_def.h" /** @addtogroup STM32F4xx_HAL_Driver * @{ */ /** @addtogroup TIM * @{ */ /* Exported types ------------------------------------------------------------*/ /** @defgroup TIM_Exported_Types TIM Exported Types * @{ */ /** * @brief TIM Time base Configuration Structure definition */ typedef struct { uint32_t Prescaler; /*!< Specifies the prescaler value used to divide the TIM clock. This parameter can be a number between Min_Data = 0x0000 and Max_Data = 0xFFFF */ uint32_t CounterMode; /*!< Specifies the counter mode. This parameter can be a value of @ref TIM_Counter_Mode */ uint32_t Period; /*!< Specifies the period value to be loaded into the active Auto-Reload Register at the next update event. This parameter can be a number between Min_Data = 0x0000 and Max_Data = 0xFFFF. */ uint32_t ClockDivision; /*!< Specifies the clock division. This parameter can be a value of @ref TIM_ClockDivision */ uint32_t RepetitionCounter; /*!< Specifies the repetition counter value. Each time the RCR downcounter reaches zero, an update event is generated and counting restarts from the RCR value (N). This means in PWM mode that (N+1) corresponds to: - the number of PWM periods in edge-aligned mode - the number of half PWM period in center-aligned mode This parameter must be a number between Min_Data = 0x00 and Max_Data = 0xFF. @note This parameter is valid only for TIM1 and TIM8. */ } TIM_Base_InitTypeDef; /** * @brief TIM Output Compare Configuration Structure definition */ typedef struct { uint32_t OCMode; /*!< Specifies the TIM mode. This parameter can be a value of @ref TIM_Output_Compare_and_PWM_modes */ uint32_t Pulse; /*!< Specifies the pulse value to be loaded into the Capture Compare Register. This parameter can be a number between Min_Data = 0x0000 and Max_Data = 0xFFFF */ uint32_t OCPolarity; /*!< Specifies the output polarity. This parameter can be a value of @ref TIM_Output_Compare_Polarity */ uint32_t OCNPolarity; /*!< Specifies the complementary output polarity. This parameter can be a value of @ref TIM_Output_Compare_N_Polarity @note This parameter is valid only for TIM1 and TIM8. */ uint32_t OCFastMode; /*!< Specifies the Fast mode state. This parameter can be a value of @ref TIM_Output_Fast_State @note This parameter is valid only in PWM1 and PWM2 mode. */ uint32_t OCIdleState; /*!< Specifies the TIM Output Compare pin state during Idle state. This parameter can be a value of @ref TIM_Output_Compare_Idle_State @note This parameter is valid only for TIM1 and TIM8. */ uint32_t OCNIdleState; /*!< Specifies the TIM Output Compare pin state during Idle state. This parameter can be a value of @ref TIM_Output_Compare_N_Idle_State @note This parameter is valid only for TIM1 and TIM8. */ } TIM_OC_InitTypeDef; /** * @brief TIM One Pulse Mode Configuration Structure definition */ typedef struct { uint32_t OCMode; /*!< Specifies the TIM mode. This parameter can be a value of @ref TIM_Output_Compare_and_PWM_modes */ uint32_t Pulse; /*!< Specifies the pulse value to be loaded into the Capture Compare Register. This parameter can be a number between Min_Data = 0x0000 and Max_Data = 0xFFFF */ uint32_t OCPolarity; /*!< Specifies the output polarity. This parameter can be a value of @ref TIM_Output_Compare_Polarity */ uint32_t OCNPolarity; /*!< Specifies the complementary output polarity. This parameter can be a value of @ref TIM_Output_Compare_N_Polarity @note This parameter is valid only for TIM1 and TIM8. */ uint32_t OCIdleState; /*!< Specifies the TIM Output Compare pin state during Idle state. This parameter can be a value of @ref TIM_Output_Compare_Idle_State @note This parameter is valid only for TIM1 and TIM8. */ uint32_t OCNIdleState; /*!< Specifies the TIM Output Compare pin state during Idle state. This parameter can be a value of @ref TIM_Output_Compare_N_Idle_State @note This parameter is valid only for TIM1 and TIM8. */ uint32_t ICPolarity; /*!< Specifies the active edge of the input signal. This parameter can be a value of @ref TIM_Input_Capture_Polarity */ uint32_t ICSelection; /*!< Specifies the input. This parameter can be a value of @ref TIM_Input_Capture_Selection */ uint32_t ICFilter; /*!< Specifies the input capture filter. This parameter can be a number between Min_Data = 0x0 and Max_Data = 0xF */ } TIM_OnePulse_InitTypeDef; /** * @brief TIM Input Capture Configuration Structure definition */ typedef struct { uint32_t ICPolarity; /*!< Specifies the active edge of the input signal. This parameter can be a value of @ref TIM_Input_Capture_Polarity */ uint32_t ICSelection; /*!< Specifies the input. This parameter can be a value of @ref TIM_Input_Capture_Selection */ uint32_t ICPrescaler; /*!< Specifies the Input Capture Prescaler. This parameter can be a value of @ref TIM_Input_Capture_Prescaler */ uint32_t ICFilter; /*!< Specifies the input capture filter. This parameter can be a number between Min_Data = 0x0 and Max_Data = 0xF */ } TIM_IC_InitTypeDef; /** * @brief TIM Encoder Configuration Structure definition */ typedef struct { uint32_t EncoderMode; /*!< Specifies the active edge of the input signal. This parameter can be a value of @ref TIM_Encoder_Mode */ uint32_t IC1Polarity; /*!< Specifies the active edge of the input signal. This parameter can be a value of @ref TIM_Input_Capture_Polarity */ uint32_t IC1Selection; /*!< Specifies the input. This parameter can be a value of @ref TIM_Input_Capture_Selection */ uint32_t IC1Prescaler; /*!< Specifies the Input Capture Prescaler. This parameter can be a value of @ref TIM_Input_Capture_Prescaler */ uint32_t IC1Filter; /*!< Specifies the input capture filter. This parameter can be a number between Min_Data = 0x0 and Max_Data = 0xF */ uint32_t IC2Polarity; /*!< Specifies the active edge of the input signal. This parameter can be a value of @ref TIM_Input_Capture_Polarity */ uint32_t IC2Selection; /*!< Specifies the input. This parameter can be a value of @ref TIM_Input_Capture_Selection */ uint32_t IC2Prescaler; /*!< Specifies the Input Capture Prescaler. This parameter can be a value of @ref TIM_Input_Capture_Prescaler */ uint32_t IC2Filter; /*!< Specifies the input capture filter. This parameter can be a number between Min_Data = 0x0 and Max_Data = 0xF */ } TIM_Encoder_InitTypeDef; /** * @brief Clock Configuration Handle Structure definition */ typedef struct { uint32_t ClockSource; /*!< TIM clock sources. This parameter can be a value of @ref TIM_Clock_Source */ uint32_t ClockPolarity; /*!< TIM clock polarity. This parameter can be a value of @ref TIM_Clock_Polarity */ uint32_t ClockPrescaler; /*!< TIM clock prescaler. This parameter can be a value of @ref TIM_Clock_Prescaler */ uint32_t ClockFilter; /*!< TIM clock filter. This parameter can be a number between Min_Data = 0x0 and Max_Data = 0xF */ }TIM_ClockConfigTypeDef; /** * @brief Clear Input Configuration Handle Structure definition */ typedef struct { uint32_t ClearInputState; /*!< TIM clear Input state. This parameter can be ENABLE or DISABLE */ uint32_t ClearInputSource; /*!< TIM clear Input sources. This parameter can be a value of @ref TIM_ClearInput_Source */ uint32_t ClearInputPolarity; /*!< TIM Clear Input polarity. This parameter can be a value of @ref TIM_ClearInput_Polarity */ uint32_t ClearInputPrescaler; /*!< TIM Clear Input prescaler. This parameter can be a value of @ref TIM_ClearInput_Prescaler */ uint32_t ClearInputFilter; /*!< TIM Clear Input filter. This parameter can be a number between Min_Data = 0x0 and Max_Data = 0xF */ }TIM_ClearInputConfigTypeDef; /** * @brief TIM Slave configuration Structure definition */ typedef struct { uint32_t SlaveMode; /*!< Slave mode selection This parameter can be a value of @ref TIM_Slave_Mode */ uint32_t InputTrigger; /*!< Input Trigger source This parameter can be a value of @ref TIM_Trigger_Selection */ uint32_t TriggerPolarity; /*!< Input Trigger polarity This parameter can be a value of @ref TIM_Trigger_Polarity */ uint32_t TriggerPrescaler; /*!< Input trigger prescaler This parameter can be a value of @ref TIM_Trigger_Prescaler */ uint32_t TriggerFilter; /*!< Input trigger filter This parameter can be a number between Min_Data = 0x0 and Max_Data = 0xF */ }TIM_SlaveConfigTypeDef; /** * @brief HAL State structures definition */ typedef enum { HAL_TIM_STATE_RESET = 0x00, /*!< Peripheral not yet initialized or disabled */ HAL_TIM_STATE_READY = 0x01, /*!< Peripheral Initialized and ready for use */ HAL_TIM_STATE_BUSY = 0x02, /*!< An internal process is ongoing */ HAL_TIM_STATE_TIMEOUT = 0x03, /*!< Timeout state */ HAL_TIM_STATE_ERROR = 0x04 /*!< Reception process is ongoing */ }HAL_TIM_StateTypeDef; /** * @brief HAL Active channel structures definition */ typedef enum { HAL_TIM_ACTIVE_CHANNEL_1 = 0x01, /*!< The active channel is 1 */ HAL_TIM_ACTIVE_CHANNEL_2 = 0x02, /*!< The active channel is 2 */ HAL_TIM_ACTIVE_CHANNEL_3 = 0x04, /*!< The active channel is 3 */ HAL_TIM_ACTIVE_CHANNEL_4 = 0x08, /*!< The active channel is 4 */ HAL_TIM_ACTIVE_CHANNEL_CLEARED = 0x00 /*!< All active channels cleared */ }HAL_TIM_ActiveChannel; /** * @brief TIM Time Base Handle Structure definition */ typedef struct { TIM_TypeDef *Instance; /*!< Register base address */ TIM_Base_InitTypeDef Init; /*!< TIM Time Base required parameters */ HAL_TIM_ActiveChannel Channel; /*!< Active channel */ DMA_HandleTypeDef *hdma[7]; /*!< DMA Handlers array This array is accessed by a @ref DMA_Handle_index */ HAL_LockTypeDef Lock; /*!< Locking object */ __IO HAL_TIM_StateTypeDef State; /*!< TIM operation state */ }TIM_HandleTypeDef; /** * @} */ /* Exported constants --------------------------------------------------------*/ /** @defgroup TIM_Exported_Constants TIM Exported Constants * @{ */ /** @defgroup TIM_Input_Channel_Polarity TIM Input Channel Polarity * @{ */ #define TIM_INPUTCHANNELPOLARITY_RISING ((uint32_t)0x00000000) /*!< Polarity for TIx source */ #define TIM_INPUTCHANNELPOLARITY_FALLING (TIM_CCER_CC1P) /*!< Polarity for TIx source */ #define TIM_INPUTCHANNELPOLARITY_BOTHEDGE (TIM_CCER_CC1P | TIM_CCER_CC1NP) /*!< Polarity for TIx source */ /** * @} */ /** @defgroup TIM_ETR_Polarity TIM ETR Polarity * @{ */ #define TIM_ETRPOLARITY_INVERTED (TIM_SMCR_ETP) /*!< Polarity for ETR source */ #define TIM_ETRPOLARITY_NONINVERTED ((uint32_t)0x0000) /*!< Polarity for ETR source */ /** * @} */ /** @defgroup TIM_ETR_Prescaler TIM ETR Prescaler * @{ */ #define TIM_ETRPRESCALER_DIV1 ((uint32_t)0x0000) /*!< No prescaler is used */ #define TIM_ETRPRESCALER_DIV2 (TIM_SMCR_ETPS_0) /*!< ETR input source is divided by 2 */ #define TIM_ETRPRESCALER_DIV4 (TIM_SMCR_ETPS_1) /*!< ETR input source is divided by 4 */ #define TIM_ETRPRESCALER_DIV8 (TIM_SMCR_ETPS) /*!< ETR input source is divided by 8 */ /** * @} */ /** @defgroup TIM_Counter_Mode TIM Counter Mode * @{ */ #define TIM_COUNTERMODE_UP ((uint32_t)0x0000) #define TIM_COUNTERMODE_DOWN TIM_CR1_DIR #define TIM_COUNTERMODE_CENTERALIGNED1 TIM_CR1_CMS_0 #define TIM_COUNTERMODE_CENTERALIGNED2 TIM_CR1_CMS_1 #define TIM_COUNTERMODE_CENTERALIGNED3 TIM_CR1_CMS /** * @} */ /** @defgroup TIM_ClockDivision TIM Clock Division * @{ */ #define TIM_CLOCKDIVISION_DIV1 ((uint32_t)0x0000) #define TIM_CLOCKDIVISION_DIV2 (TIM_CR1_CKD_0) #define TIM_CLOCKDIVISION_DIV4 (TIM_CR1_CKD_1) /** * @} */ /** @defgroup TIM_Output_Compare_and_PWM_modes TIM Output Compare and PWM modes * @{ */ #define TIM_OCMODE_TIMING ((uint32_t)0x0000) #define TIM_OCMODE_ACTIVE (TIM_CCMR1_OC1M_0) #define TIM_OCMODE_INACTIVE (TIM_CCMR1_OC1M_1) #define TIM_OCMODE_TOGGLE (TIM_CCMR1_OC1M_0 | TIM_CCMR1_OC1M_1) #define TIM_OCMODE_PWM1 (TIM_CCMR1_OC1M_1 | TIM_CCMR1_OC1M_2) #define TIM_OCMODE_PWM2 (TIM_CCMR1_OC1M) #define TIM_OCMODE_FORCED_ACTIVE (TIM_CCMR1_OC1M_0 | TIM_CCMR1_OC1M_2) #define TIM_OCMODE_FORCED_INACTIVE (TIM_CCMR1_OC1M_2) /** * @} */ /** @defgroup TIM_Output_Fast_State TIM Output Fast State * @{ */ #define TIM_OCFAST_DISABLE ((uint32_t)0x0000) #define TIM_OCFAST_ENABLE (TIM_CCMR1_OC1FE) /** * @} */ /** @defgroup TIM_Output_Compare_Polarity TIM Output Compare Polarity * @{ */ #define TIM_OCPOLARITY_HIGH ((uint32_t)0x0000) #define TIM_OCPOLARITY_LOW (TIM_CCER_CC1P) /** * @} */ /** @defgroup TIM_Output_Compare_N_Polarity TIM Output CompareN Polarity * @{ */ #define TIM_OCNPOLARITY_HIGH ((uint32_t)0x0000) #define TIM_OCNPOLARITY_LOW (TIM_CCER_CC1NP) /** * @} */ /** @defgroup TIM_Output_Compare_Idle_State TIM Output Compare Idle State * @{ */ #define TIM_OCIDLESTATE_SET (TIM_CR2_OIS1) #define TIM_OCIDLESTATE_RESET ((uint32_t)0x0000) /** * @} */ /** @defgroup TIM_Output_Compare_N_Idle_State TIM Output Compare N Idle State * @{ */ #define TIM_OCNIDLESTATE_SET (TIM_CR2_OIS1N) #define TIM_OCNIDLESTATE_RESET ((uint32_t)0x0000) /** * @} */ /** @defgroup TIM_Channel TIM Channel * @{ */ #define TIM_CHANNEL_1 ((uint32_t)0x0000) #define TIM_CHANNEL_2 ((uint32_t)0x0004) #define TIM_CHANNEL_3 ((uint32_t)0x0008) #define TIM_CHANNEL_4 ((uint32_t)0x000C) #define TIM_CHANNEL_ALL ((uint32_t)0x0018) /** * @} */ /** @defgroup TIM_Input_Capture_Polarity TIM Input Capture Polarity * @{ */ #define TIM_ICPOLARITY_RISING TIM_INPUTCHANNELPOLARITY_RISING #define TIM_ICPOLARITY_FALLING TIM_INPUTCHANNELPOLARITY_FALLING #define TIM_ICPOLARITY_BOTHEDGE TIM_INPUTCHANNELPOLARITY_BOTHEDGE /** * @} */ /** @defgroup TIM_Input_Capture_Selection TIM Input Capture Selection * @{ */ #define TIM_ICSELECTION_DIRECTTI (TIM_CCMR1_CC1S_0) /*!< TIM Input 1, 2, 3 or 4 is selected to be connected to IC1, IC2, IC3 or IC4, respectively */ #define TIM_ICSELECTION_INDIRECTTI (TIM_CCMR1_CC1S_1) /*!< TIM Input 1, 2, 3 or 4 is selected to be connected to IC2, IC1, IC4 or IC3, respectively */ #define TIM_ICSELECTION_TRC (TIM_CCMR1_CC1S) /*!< TIM Input 1, 2, 3 or 4 is selected to be connected to TRC */ /** * @} */ /** @defgroup TIM_Input_Capture_Prescaler TIM Input Capture Prescaler * @{ */ #define TIM_ICPSC_DIV1 ((uint32_t)0x0000) /*!< Capture performed each time an edge is detected on the capture input */ #define TIM_ICPSC_DIV2 (TIM_CCMR1_IC1PSC_0) /*!< Capture performed once every 2 events */ #define TIM_ICPSC_DIV4 (TIM_CCMR1_IC1PSC_1) /*!< Capture performed once every 4 events */ #define TIM_ICPSC_DIV8 (TIM_CCMR1_IC1PSC) /*!< Capture performed once every 8 events */ /** * @} */ /** @defgroup TIM_One_Pulse_Mode TIM One Pulse Mode * @{ */ #define TIM_OPMODE_SINGLE (TIM_CR1_OPM) #define TIM_OPMODE_REPETITIVE ((uint32_t)0x0000) /** * @} */ /** @defgroup TIM_Encoder_Mode TIM Encoder Mode * @{ */ #define TIM_ENCODERMODE_TI1 (TIM_SMCR_SMS_0) #define TIM_ENCODERMODE_TI2 (TIM_SMCR_SMS_1) #define TIM_ENCODERMODE_TI12 (TIM_SMCR_SMS_1 | TIM_SMCR_SMS_0) /** * @} */ /** @defgroup TIM_Interrupt_definition TIM Interrupt definition * @{ */ #define TIM_IT_UPDATE (TIM_DIER_UIE) #define TIM_IT_CC1 (TIM_DIER_CC1IE) #define TIM_IT_CC2 (TIM_DIER_CC2IE) #define TIM_IT_CC3 (TIM_DIER_CC3IE) #define TIM_IT_CC4 (TIM_DIER_CC4IE) #define TIM_IT_COM (TIM_DIER_COMIE) #define TIM_IT_TRIGGER (TIM_DIER_TIE) #define TIM_IT_BREAK (TIM_DIER_BIE) /** * @} */ /** @defgroup TIM_Commutation_Source TIM Commutation Source * @{ */ #define TIM_COMMUTATION_TRGI (TIM_CR2_CCUS) #define TIM_COMMUTATION_SOFTWARE ((uint32_t)0x0000) /** * @} */ /** @defgroup TIM_DMA_sources TIM DMA sources * @{ */ #define TIM_DMA_UPDATE (TIM_DIER_UDE) #define TIM_DMA_CC1 (TIM_DIER_CC1DE) #define TIM_DMA_CC2 (TIM_DIER_CC2DE) #define TIM_DMA_CC3 (TIM_DIER_CC3DE) #define TIM_DMA_CC4 (TIM_DIER_CC4DE) #define TIM_DMA_COM (TIM_DIER_COMDE) #define TIM_DMA_TRIGGER (TIM_DIER_TDE) /** * @} */ /** @defgroup TIM_Event_Source TIM Event Source * @{ */ #define TIM_EVENTSOURCE_UPDATE TIM_EGR_UG #define TIM_EVENTSOURCE_CC1 TIM_EGR_CC1G #define TIM_EVENTSOURCE_CC2 TIM_EGR_CC2G #define TIM_EVENTSOURCE_CC3 TIM_EGR_CC3G #define TIM_EVENTSOURCE_CC4 TIM_EGR_CC4G #define TIM_EVENTSOURCE_COM TIM_EGR_COMG #define TIM_EVENTSOURCE_TRIGGER TIM_EGR_TG #define TIM_EVENTSOURCE_BREAK TIM_EGR_BG /** * @} */ /** @defgroup TIM_Flag_definition TIM Flag definition * @{ */ #define TIM_FLAG_UPDATE (TIM_SR_UIF) #define TIM_FLAG_CC1 (TIM_SR_CC1IF) #define TIM_FLAG_CC2 (TIM_SR_CC2IF) #define TIM_FLAG_CC3 (TIM_SR_CC3IF) #define TIM_FLAG_CC4 (TIM_SR_CC4IF) #define TIM_FLAG_COM (TIM_SR_COMIF) #define TIM_FLAG_TRIGGER (TIM_SR_TIF) #define TIM_FLAG_BREAK (TIM_SR_BIF) #define TIM_FLAG_CC1OF (TIM_SR_CC1OF) #define TIM_FLAG_CC2OF (TIM_SR_CC2OF) #define TIM_FLAG_CC3OF (TIM_SR_CC3OF) #define TIM_FLAG_CC4OF (TIM_SR_CC4OF) /** * @} */ /** @defgroup TIM_Clock_Source TIM Clock Source * @{ */ #define TIM_CLOCKSOURCE_ETRMODE2 (TIM_SMCR_ETPS_1) #define TIM_CLOCKSOURCE_INTERNAL (TIM_SMCR_ETPS_0) #define TIM_CLOCKSOURCE_ITR0 ((uint32_t)0x0000) #define TIM_CLOCKSOURCE_ITR1 (TIM_SMCR_TS_0) #define TIM_CLOCKSOURCE_ITR2 (TIM_SMCR_TS_1) #define TIM_CLOCKSOURCE_ITR3 (TIM_SMCR_TS_0 | TIM_SMCR_TS_1) #define TIM_CLOCKSOURCE_TI1ED (TIM_SMCR_TS_2) #define TIM_CLOCKSOURCE_TI1 (TIM_SMCR_TS_0 | TIM_SMCR_TS_2) #define TIM_CLOCKSOURCE_TI2 (TIM_SMCR_TS_1 | TIM_SMCR_TS_2) #define TIM_CLOCKSOURCE_ETRMODE1 (TIM_SMCR_TS) /** * @} */ /** @defgroup TIM_Clock_Polarity TIM Clock Polarity * @{ */ #define TIM_CLOCKPOLARITY_INVERTED TIM_ETRPOLARITY_INVERTED /*!< Polarity for ETRx clock sources */ #define TIM_CLOCKPOLARITY_NONINVERTED TIM_ETRPOLARITY_NONINVERTED /*!< Polarity for ETRx clock sources */ #define TIM_CLOCKPOLARITY_RISING TIM_INPUTCHANNELPOLARITY_RISING /*!< Polarity for TIx clock sources */ #define TIM_CLOCKPOLARITY_FALLING TIM_INPUTCHANNELPOLARITY_FALLING /*!< Polarity for TIx clock sources */ #define TIM_CLOCKPOLARITY_BOTHEDGE TIM_INPUTCHANNELPOLARITY_BOTHEDGE /*!< Polarity for TIx clock sources */ /** * @} */ /** @defgroup TIM_Clock_Prescaler TIM Clock Prescaler * @{ */ #define TIM_CLOCKPRESCALER_DIV1 TIM_ETRPRESCALER_DIV1 /*!< No prescaler is used */ #define TIM_CLOCKPRESCALER_DIV2 TIM_ETRPRESCALER_DIV2 /*!< Prescaler for External ETR Clock: Capture performed once every 2 events. */ #define TIM_CLOCKPRESCALER_DIV4 TIM_ETRPRESCALER_DIV4 /*!< Prescaler for External ETR Clock: Capture performed once every 4 events. */ #define TIM_CLOCKPRESCALER_DIV8 TIM_ETRPRESCALER_DIV8 /*!< Prescaler for External ETR Clock: Capture performed once every 8 events. */ /** * @} */ /** @defgroup TIM_ClearInput_Source TIM Clear Input Source * @{ */ #define TIM_CLEARINPUTSOURCE_ETR ((uint32_t)0x0001) #define TIM_CLEARINPUTSOURCE_NONE ((uint32_t)0x0000) /** * @} */ /** @defgroup TIM_ClearInput_Polarity TIM Clear Input Polarity * @{ */ #define TIM_CLEARINPUTPOLARITY_INVERTED TIM_ETRPOLARITY_INVERTED /*!< Polarity for ETRx pin */ #define TIM_CLEARINPUTPOLARITY_NONINVERTED TIM_ETRPOLARITY_NONINVERTED /*!< Polarity for ETRx pin */ /** * @} */ /** @defgroup TIM_ClearInput_Prescaler TIM Clear Input Prescaler * @{ */ #define TIM_CLEARINPUTPRESCALER_DIV1 TIM_ETRPRESCALER_DIV1 /*!< No prescaler is used */ #define TIM_CLEARINPUTPRESCALER_DIV2 TIM_ETRPRESCALER_DIV2 /*!< Prescaler for External ETR pin: Capture performed once every 2 events. */ #define TIM_CLEARINPUTPRESCALER_DIV4 TIM_ETRPRESCALER_DIV4 /*!< Prescaler for External ETR pin: Capture performed once every 4 events. */ #define TIM_CLEARINPUTPRESCALER_DIV8 TIM_ETRPRESCALER_DIV8 /*!< Prescaler for External ETR pin: Capture performed once every 8 events. */ /** * @} */ /** @defgroup TIM_OSSR_Off_State_Selection_for_Run_mode_state TIM OSSR OffState Selection for Run mode state * @{ */ #define TIM_OSSR_ENABLE (TIM_BDTR_OSSR) #define TIM_OSSR_DISABLE ((uint32_t)0x0000) /** * @} */ /** @defgroup TIM_OSSI_Off_State_Selection_for_Idle_mode_state TIM OSSI OffState Selection for Idle mode state * @{ */ #define TIM_OSSI_ENABLE (TIM_BDTR_OSSI) #define TIM_OSSI_DISABLE ((uint32_t)0x0000) /** * @} */ /** @defgroup TIM_Lock_level TIM Lock level * @{ */ #define TIM_LOCKLEVEL_OFF ((uint32_t)0x0000) #define TIM_LOCKLEVEL_1 (TIM_BDTR_LOCK_0) #define TIM_LOCKLEVEL_2 (TIM_BDTR_LOCK_1) #define TIM_LOCKLEVEL_3 (TIM_BDTR_LOCK) /** * @} */ /** @defgroup TIM_Break_Input_enable_disable TIM Break Input State * @{ */ #define TIM_BREAK_ENABLE (TIM_BDTR_BKE) #define TIM_BREAK_DISABLE ((uint32_t)0x0000) /** * @} */ /** @defgroup TIM_Break_Polarity TIM Break Polarity * @{ */ #define TIM_BREAKPOLARITY_LOW ((uint32_t)0x0000) #define TIM_BREAKPOLARITY_HIGH (TIM_BDTR_BKP) /** * @} */ /** @defgroup TIM_AOE_Bit_Set_Reset TIM AOE Bit State * @{ */ #define TIM_AUTOMATICOUTPUT_ENABLE (TIM_BDTR_AOE) #define TIM_AUTOMATICOUTPUT_DISABLE ((uint32_t)0x0000) /** * @} */ /** @defgroup TIM_Master_Mode_Selection TIM Master Mode Selection * @{ */ #define TIM_TRGO_RESET ((uint32_t)0x0000) #define TIM_TRGO_ENABLE (TIM_CR2_MMS_0) #define TIM_TRGO_UPDATE (TIM_CR2_MMS_1) #define TIM_TRGO_OC1 ((TIM_CR2_MMS_1 | TIM_CR2_MMS_0)) #define TIM_TRGO_OC1REF (TIM_CR2_MMS_2) #define TIM_TRGO_OC2REF ((TIM_CR2_MMS_2 | TIM_CR2_MMS_0)) #define TIM_TRGO_OC3REF ((TIM_CR2_MMS_2 | TIM_CR2_MMS_1)) #define TIM_TRGO_OC4REF ((TIM_CR2_MMS_2 | TIM_CR2_MMS_1 | TIM_CR2_MMS_0)) /** * @} */ /** @defgroup TIM_Slave_Mode TIM Slave Mode * @{ */ #define TIM_SLAVEMODE_DISABLE ((uint32_t)0x0000) #define TIM_SLAVEMODE_RESET ((uint32_t)0x0004) #define TIM_SLAVEMODE_GATED ((uint32_t)0x0005) #define TIM_SLAVEMODE_TRIGGER ((uint32_t)0x0006) #define TIM_SLAVEMODE_EXTERNAL1 ((uint32_t)0x0007) /** * @} */ /** @defgroup TIM_Master_Slave_Mode TIM Master Slave Mode * @{ */ #define TIM_MASTERSLAVEMODE_ENABLE ((uint32_t)0x0080) #define TIM_MASTERSLAVEMODE_DISABLE ((uint32_t)0x0000) /** * @} */ /** @defgroup TIM_Trigger_Selection TIM Trigger Selection * @{ */ #define TIM_TS_ITR0 ((uint32_t)0x0000) #define TIM_TS_ITR1 ((uint32_t)0x0010) #define TIM_TS_ITR2 ((uint32_t)0x0020) #define TIM_TS_ITR3 ((uint32_t)0x0030) #define TIM_TS_TI1F_ED ((uint32_t)0x0040) #define TIM_TS_TI1FP1 ((uint32_t)0x0050) #define TIM_TS_TI2FP2 ((uint32_t)0x0060) #define TIM_TS_ETRF ((uint32_t)0x0070) #define TIM_TS_NONE ((uint32_t)0xFFFF) /** * @} */ /** @defgroup TIM_Trigger_Polarity TIM Trigger Polarity * @{ */ #define TIM_TRIGGERPOLARITY_INVERTED TIM_ETRPOLARITY_INVERTED /*!< Polarity for ETRx trigger sources */ #define TIM_TRIGGERPOLARITY_NONINVERTED TIM_ETRPOLARITY_NONINVERTED /*!< Polarity for ETRx trigger sources */ #define TIM_TRIGGERPOLARITY_RISING TIM_INPUTCHANNELPOLARITY_RISING /*!< Polarity for TIxFPx or TI1_ED trigger sources */ #define TIM_TRIGGERPOLARITY_FALLING TIM_INPUTCHANNELPOLARITY_FALLING /*!< Polarity for TIxFPx or TI1_ED trigger sources */ #define TIM_TRIGGERPOLARITY_BOTHEDGE TIM_INPUTCHANNELPOLARITY_BOTHEDGE /*!< Polarity for TIxFPx or TI1_ED trigger sources */ /** * @} */ /** @defgroup TIM_Trigger_Prescaler TIM Trigger Prescaler * @{ */ #define TIM_TRIGGERPRESCALER_DIV1 TIM_ETRPRESCALER_DIV1 /*!< No prescaler is used */ #define TIM_TRIGGERPRESCALER_DIV2 TIM_ETRPRESCALER_DIV2 /*!< Prescaler for External ETR Trigger: Capture performed once every 2 events. */ #define TIM_TRIGGERPRESCALER_DIV4 TIM_ETRPRESCALER_DIV4 /*!< Prescaler for External ETR Trigger: Capture performed once every 4 events. */ #define TIM_TRIGGERPRESCALER_DIV8 TIM_ETRPRESCALER_DIV8 /*!< Prescaler for External ETR Trigger: Capture performed once every 8 events. */ /** * @} */ /** @defgroup TIM_TI1_Selection TIM TI1 Selection * @{ */ #define TIM_TI1SELECTION_CH1 ((uint32_t)0x0000) #define TIM_TI1SELECTION_XORCOMBINATION (TIM_CR2_TI1S) /** * @} */ /** @defgroup TIM_DMA_Base_address TIM DMA Base address * @{ */ #define TIM_DMABASE_CR1 (0x00000000) #define TIM_DMABASE_CR2 (0x00000001) #define TIM_DMABASE_SMCR (0x00000002) #define TIM_DMABASE_DIER (0x00000003) #define TIM_DMABASE_SR (0x00000004) #define TIM_DMABASE_EGR (0x00000005) #define TIM_DMABASE_CCMR1 (0x00000006) #define TIM_DMABASE_CCMR2 (0x00000007) #define TIM_DMABASE_CCER (0x00000008) #define TIM_DMABASE_CNT (0x00000009) #define TIM_DMABASE_PSC (0x0000000A) #define TIM_DMABASE_ARR (0x0000000B) #define TIM_DMABASE_RCR (0x0000000C) #define TIM_DMABASE_CCR1 (0x0000000D) #define TIM_DMABASE_CCR2 (0x0000000E) #define TIM_DMABASE_CCR3 (0x0000000F) #define TIM_DMABASE_CCR4 (0x00000010) #define TIM_DMABASE_BDTR (0x00000011) #define TIM_DMABASE_DCR (0x00000012) #define TIM_DMABASE_OR (0x00000013) /** * @} */ /** @defgroup TIM_DMA_Burst_Length TIM DMA Burst Length * @{ */ #define TIM_DMABURSTLENGTH_1TRANSFER (0x00000000) #define TIM_DMABURSTLENGTH_2TRANSFERS (0x00000100) #define TIM_DMABURSTLENGTH_3TRANSFERS (0x00000200) #define TIM_DMABURSTLENGTH_4TRANSFERS (0x00000300) #define TIM_DMABURSTLENGTH_5TRANSFERS (0x00000400) #define TIM_DMABURSTLENGTH_6TRANSFERS (0x00000500) #define TIM_DMABURSTLENGTH_7TRANSFERS (0x00000600) #define TIM_DMABURSTLENGTH_8TRANSFERS (0x00000700) #define TIM_DMABURSTLENGTH_9TRANSFERS (0x00000800) #define TIM_DMABURSTLENGTH_10TRANSFERS (0x00000900) #define TIM_DMABURSTLENGTH_11TRANSFERS (0x00000A00) #define TIM_DMABURSTLENGTH_12TRANSFERS (0x00000B00) #define TIM_DMABURSTLENGTH_13TRANSFERS (0x00000C00) #define TIM_DMABURSTLENGTH_14TRANSFERS (0x00000D00) #define TIM_DMABURSTLENGTH_15TRANSFERS (0x00000E00) #define TIM_DMABURSTLENGTH_16TRANSFERS (0x00000F00) #define TIM_DMABURSTLENGTH_17TRANSFERS (0x00001000) #define TIM_DMABURSTLENGTH_18TRANSFERS (0x00001100) /** * @} */ /** @defgroup DMA_Handle_index DMA Handle index * @{ */ #define TIM_DMA_ID_UPDATE ((uint16_t) 0x0) /*!< Index of the DMA handle used for Update DMA requests */ #define TIM_DMA_ID_CC1 ((uint16_t) 0x1) /*!< Index of the DMA handle used for Capture/Compare 1 DMA requests */ #define TIM_DMA_ID_CC2 ((uint16_t) 0x2) /*!< Index of the DMA handle used for Capture/Compare 2 DMA requests */ #define TIM_DMA_ID_CC3 ((uint16_t) 0x3) /*!< Index of the DMA handle used for Capture/Compare 3 DMA requests */ #define TIM_DMA_ID_CC4 ((uint16_t) 0x4) /*!< Index of the DMA handle used for Capture/Compare 4 DMA requests */ #define TIM_DMA_ID_COMMUTATION ((uint16_t) 0x5) /*!< Index of the DMA handle used for Commutation DMA requests */ #define TIM_DMA_ID_TRIGGER ((uint16_t) 0x6) /*!< Index of the DMA handle used for Trigger DMA requests */ /** * @} */ /** @defgroup Channel_CC_State Channel CC State * @{ */ #define TIM_CCx_ENABLE ((uint32_t)0x0001) #define TIM_CCx_DISABLE ((uint32_t)0x0000) #define TIM_CCxN_ENABLE ((uint32_t)0x0004) #define TIM_CCxN_DISABLE ((uint32_t)0x0000) /** * @} */ /** * @} */ /* Exported macro ------------------------------------------------------------*/ /** @defgroup TIM_Exported_Macros TIM Exported Macros * @{ */ /** @brief Reset TIM handle state * @param __HANDLE__: TIM handle * @retval None */ #define __HAL_TIM_RESET_HANDLE_STATE(__HANDLE__) ((__HANDLE__)->State = HAL_TIM_STATE_RESET) /** * @brief Enable the TIM peripheral. * @param __HANDLE__: TIM handle * @retval None */ #define __HAL_TIM_ENABLE(__HANDLE__) ((__HANDLE__)->Instance->CR1|=(TIM_CR1_CEN)) /** * @brief Enable the TIM main Output. * @param __HANDLE__: TIM handle * @retval None */ #define __HAL_TIM_MOE_ENABLE(__HANDLE__) ((__HANDLE__)->Instance->BDTR|=(TIM_BDTR_MOE)) /** * @brief Disable the TIM peripheral. * @param __HANDLE__: TIM handle * @retval None */ #define __HAL_TIM_DISABLE(__HANDLE__) \ do { \ if (((__HANDLE__)->Instance->CCER & TIM_CCER_CCxE_MASK) == 0) \ { \ if(((__HANDLE__)->Instance->CCER & TIM_CCER_CCxNE_MASK) == 0) \ { \ (__HANDLE__)->Instance->CR1 &= ~(TIM_CR1_CEN); \ } \ } \ } while(0) /* The Main Output of a timer instance is disabled only if all the CCx and CCxN channels have been disabled */ /** * @brief Disable the TIM main Output. * @param __HANDLE__: TIM handle * @retval None */ #define __HAL_TIM_MOE_DISABLE(__HANDLE__) \ do { \ if (((__HANDLE__)->Instance->CCER & TIM_CCER_CCxE_MASK) == 0) \ { \ if(((__HANDLE__)->Instance->CCER & TIM_CCER_CCxNE_MASK) == 0) \ { \ (__HANDLE__)->Instance->BDTR &= ~(TIM_BDTR_MOE); \ } \ } \ } while(0) #define __HAL_TIM_ENABLE_IT(__HANDLE__, __INTERRUPT__) ((__HANDLE__)->Instance->DIER |= (__INTERRUPT__)) #define __HAL_TIM_ENABLE_DMA(__HANDLE__, __DMA__) ((__HANDLE__)->Instance->DIER |= (__DMA__)) #define __HAL_TIM_DISABLE_IT(__HANDLE__, __INTERRUPT__) ((__HANDLE__)->Instance->DIER &= ~(__INTERRUPT__)) #define __HAL_TIM_DISABLE_DMA(__HANDLE__, __DMA__) ((__HANDLE__)->Instance->DIER &= ~(__DMA__)) #define __HAL_TIM_GET_FLAG(__HANDLE__, __FLAG__) (((__HANDLE__)->Instance->SR &(__FLAG__)) == (__FLAG__)) #define __HAL_TIM_CLEAR_FLAG(__HANDLE__, __FLAG__) ((__HANDLE__)->Instance->SR = ~(__FLAG__)) #define __HAL_TIM_GET_IT_SOURCE(__HANDLE__, __INTERRUPT__) ((((__HANDLE__)->Instance->DIER & (__INTERRUPT__)) == (__INTERRUPT__)) ? SET : RESET) #define __HAL_TIM_CLEAR_IT(__HANDLE__, __INTERRUPT__) ((__HANDLE__)->Instance->SR = ~(__INTERRUPT__)) #define __HAL_TIM_IS_TIM_COUNTING_DOWN(__HANDLE__) (((__HANDLE__)->Instance->CR1 &(TIM_CR1_DIR)) == (TIM_CR1_DIR)) #define __HAL_TIM_SET_PRESCALER(__HANDLE__, __PRESC__) ((__HANDLE__)->Instance->PSC = (__PRESC__)) #define TIM_SET_ICPRESCALERVALUE(__HANDLE__, __CHANNEL__, __ICPSC__) \ (((__CHANNEL__) == TIM_CHANNEL_1) ? ((__HANDLE__)->Instance->CCMR1 |= (__ICPSC__)) :\ ((__CHANNEL__) == TIM_CHANNEL_2) ? ((__HANDLE__)->Instance->CCMR1 |= ((__ICPSC__) << 8)) :\ ((__CHANNEL__) == TIM_CHANNEL_3) ? ((__HANDLE__)->Instance->CCMR2 |= (__ICPSC__)) :\ ((__HANDLE__)->Instance->CCMR2 |= ((__ICPSC__) << 8))) #define TIM_RESET_ICPRESCALERVALUE(__HANDLE__, __CHANNEL__) \ (((__CHANNEL__) == TIM_CHANNEL_1) ? ((__HANDLE__)->Instance->CCMR1 &= (uint16_t)~TIM_CCMR1_IC1PSC) :\ ((__CHANNEL__) == TIM_CHANNEL_2) ? ((__HANDLE__)->Instance->CCMR1 &= (uint16_t)~TIM_CCMR1_IC2PSC) :\ ((__CHANNEL__) == TIM_CHANNEL_3) ? ((__HANDLE__)->Instance->CCMR2 &= (uint16_t)~TIM_CCMR2_IC3PSC) :\ ((__HANDLE__)->Instance->CCMR2 &= (uint16_t)~TIM_CCMR2_IC4PSC)) #define TIM_SET_CAPTUREPOLARITY(__HANDLE__, __CHANNEL__, __POLARITY__) \ (((__CHANNEL__) == TIM_CHANNEL_1) ? ((__HANDLE__)->Instance->CCER |= (__POLARITY__)) :\ ((__CHANNEL__) == TIM_CHANNEL_2) ? ((__HANDLE__)->Instance->CCER |= ((__POLARITY__) << 4)) :\ ((__CHANNEL__) == TIM_CHANNEL_3) ? ((__HANDLE__)->Instance->CCER |= ((__POLARITY__) << 8)) :\ ((__HANDLE__)->Instance->CCER |= (((__POLARITY__) << 12) & TIM_CCER_CC4P))) #define TIM_RESET_CAPTUREPOLARITY(__HANDLE__, __CHANNEL__) \ (((__CHANNEL__) == TIM_CHANNEL_1) ? ((__HANDLE__)->Instance->CCER &= (uint16_t)~(TIM_CCER_CC1P | TIM_CCER_CC1NP)) :\ ((__CHANNEL__) == TIM_CHANNEL_2) ? ((__HANDLE__)->Instance->CCER &= (uint16_t)~(TIM_CCER_CC2P | TIM_CCER_CC2NP)) :\ ((__CHANNEL__) == TIM_CHANNEL_3) ? ((__HANDLE__)->Instance->CCER &= (uint16_t)~(TIM_CCER_CC3P | TIM_CCER_CC3NP)) :\ ((__HANDLE__)->Instance->CCER &= (uint16_t)~TIM_CCER_CC4P)) /** * @brief Sets the TIM Capture Compare Register value on runtime without * calling another time ConfigChannel function. * @param __HANDLE__: TIM handle. * @param __CHANNEL__ : TIM Channels to be configured. * This parameter can be one of the following values: * @arg TIM_CHANNEL_1: TIM Channel 1 selected * @arg TIM_CHANNEL_2: TIM Channel 2 selected * @arg TIM_CHANNEL_3: TIM Channel 3 selected * @arg TIM_CHANNEL_4: TIM Channel 4 selected * @param __COMPARE__: specifies the Capture Compare register new value. * @retval None */ #define __HAL_TIM_SET_COMPARE(__HANDLE__, __CHANNEL__, __COMPARE__) \ (*(__IO uint32_t *)(&((__HANDLE__)->Instance->CCR1) + ((__CHANNEL__) >> 2)) = (__COMPARE__)) /** * @brief Gets the TIM Capture Compare Register value on runtime * @param __HANDLE__: TIM handle. * @param __CHANNEL__ : TIM Channel associated with the capture compare register * This parameter can be one of the following values: * @arg TIM_CHANNEL_1: get capture/compare 1 register value * @arg TIM_CHANNEL_2: get capture/compare 2 register value * @arg TIM_CHANNEL_3: get capture/compare 3 register value * @arg TIM_CHANNEL_4: get capture/compare 4 register value * @retval None */ #define __HAL_TIM_GET_COMPARE(__HANDLE__, __CHANNEL__) \ (*(__IO uint32_t *)(&((__HANDLE__)->Instance->CCR1) + ((__CHANNEL__) >> 2))) /** * @brief Sets the TIM Counter Register value on runtime. * @param __HANDLE__: TIM handle. * @param __COUNTER__: specifies the Counter register new value. * @retval None */ #define __HAL_TIM_SET_COUNTER(__HANDLE__, __COUNTER__) ((__HANDLE__)->Instance->CNT = (__COUNTER__)) /** * @brief Gets the TIM Counter Register value on runtime. * @param __HANDLE__: TIM handle. * @retval None */ #define __HAL_TIM_GET_COUNTER(__HANDLE__) ((__HANDLE__)->Instance->CNT) /** * @brief Sets the TIM Autoreload Register value on runtime without calling * another time any Init function. * @param __HANDLE__: TIM handle. * @param __AUTORELOAD__: specifies the Counter register new value. * @retval None */ #define __HAL_TIM_SET_AUTORELOAD(__HANDLE__, __AUTORELOAD__) \ do{ \ (__HANDLE__)->Instance->ARR = (__AUTORELOAD__); \ (__HANDLE__)->Init.Period = (__AUTORELOAD__); \ } while(0) /** * @brief Gets the TIM Autoreload Register value on runtime * @param __HANDLE__: TIM handle. * @retval None */ #define __HAL_TIM_GET_AUTORELOAD(__HANDLE__) ((__HANDLE__)->Instance->ARR) /** * @brief Sets the TIM Clock Division value on runtime without calling * another time any Init function. * @param __HANDLE__: TIM handle. * @param __CKD__: specifies the clock division value. * This parameter can be one of the following value: * @arg TIM_CLOCKDIVISION_DIV1 * @arg TIM_CLOCKDIVISION_DIV2 * @arg TIM_CLOCKDIVISION_DIV4 * @retval None */ #define __HAL_TIM_SET_CLOCKDIVISION(__HANDLE__, __CKD__) \ do{ \ (__HANDLE__)->Instance->CR1 &= (uint16_t)(~TIM_CR1_CKD); \ (__HANDLE__)->Instance->CR1 |= (__CKD__); \ (__HANDLE__)->Init.ClockDivision = (__CKD__); \ } while(0) /** * @brief Gets the TIM Clock Division value on runtime * @param __HANDLE__: TIM handle. * @retval None */ #define __HAL_TIM_GET_CLOCKDIVISION(__HANDLE__) ((__HANDLE__)->Instance->CR1 & TIM_CR1_CKD) /** * @brief Sets the TIM Input Capture prescaler on runtime without calling * another time HAL_TIM_IC_ConfigChannel() function. * @param __HANDLE__: TIM handle. * @param __CHANNEL__ : TIM Channels to be configured. * This parameter can be one of the following values: * @arg TIM_CHANNEL_1: TIM Channel 1 selected * @arg TIM_CHANNEL_2: TIM Channel 2 selected * @arg TIM_CHANNEL_3: TIM Channel 3 selected * @arg TIM_CHANNEL_4: TIM Channel 4 selected * @param __ICPSC__: specifies the Input Capture4 prescaler new value. * This parameter can be one of the following values: * @arg TIM_ICPSC_DIV1: no prescaler * @arg TIM_ICPSC_DIV2: capture is done once every 2 events * @arg TIM_ICPSC_DIV4: capture is done once every 4 events * @arg TIM_ICPSC_DIV8: capture is done once every 8 events * @retval None */ #define __HAL_TIM_SET_ICPRESCALER(__HANDLE__, __CHANNEL__, __ICPSC__) \ do{ \ TIM_RESET_ICPRESCALERVALUE((__HANDLE__), (__CHANNEL__)); \ TIM_SET_ICPRESCALERVALUE((__HANDLE__), (__CHANNEL__), (__ICPSC__)); \ } while(0) /** * @brief Gets the TIM Input Capture prescaler on runtime * @param __HANDLE__: TIM handle. * @param __CHANNEL__ : TIM Channels to be configured. * This parameter can be one of the following values: * @arg TIM_CHANNEL_1: get input capture 1 prescaler value * @arg TIM_CHANNEL_2: get input capture 2 prescaler value * @arg TIM_CHANNEL_3: get input capture 3 prescaler value * @arg TIM_CHANNEL_4: get input capture 4 prescaler value * @retval None */ #define __HAL_TIM_GET_ICPRESCALER(__HANDLE__, __CHANNEL__) \ (((__CHANNEL__) == TIM_CHANNEL_1) ? ((__HANDLE__)->Instance->CCMR1 & TIM_CCMR1_IC1PSC) :\ ((__CHANNEL__) == TIM_CHANNEL_2) ? (((__HANDLE__)->Instance->CCMR1 & TIM_CCMR1_IC2PSC) >> 8) :\ ((__CHANNEL__) == TIM_CHANNEL_3) ? ((__HANDLE__)->Instance->CCMR2 & TIM_CCMR2_IC3PSC) :\ (((__HANDLE__)->Instance->CCMR2 & TIM_CCMR2_IC4PSC)) >> 8) /** * @brief Set the Update Request Source (URS) bit of the TIMx_CR1 register * @param __HANDLE__: TIM handle. * @note When the USR bit of the TIMx_CR1 register is set, only counter * overflow/underflow generates an update interrupt or DMA request (if * enabled) * @retval None */ #define __HAL_TIM_URS_ENABLE(__HANDLE__) \ ((__HANDLE__)->Instance->CR1|= (TIM_CR1_URS)) /** * @brief Reset the Update Request Source (URS) bit of the TIMx_CR1 register * @param __HANDLE__: TIM handle. * @note When the USR bit of the TIMx_CR1 register is reset, any of the * following events generate an update interrupt or DMA request (if * enabled): * Counter overflow/underflow * Setting the UG bit * Update generation through the slave mode controller * @retval None */ #define __HAL_TIM_URS_DISABLE(__HANDLE__) \ ((__HANDLE__)->Instance->CR1&=~(TIM_CR1_URS)) /** * @brief Sets the TIM Capture x input polarity on runtime. * @param __HANDLE__: TIM handle. * @param __CHANNEL__: TIM Channels to be configured. * This parameter can be one of the following values: * @arg TIM_CHANNEL_1: TIM Channel 1 selected * @arg TIM_CHANNEL_2: TIM Channel 2 selected * @arg TIM_CHANNEL_3: TIM Channel 3 selected * @arg TIM_CHANNEL_4: TIM Channel 4 selected * @param __POLARITY__: Polarity for TIx source * @arg TIM_INPUTCHANNELPOLARITY_RISING: Rising Edge * @arg TIM_INPUTCHANNELPOLARITY_FALLING: Falling Edge * @arg TIM_INPUTCHANNELPOLARITY_BOTHEDGE: Rising and Falling Edge * @note The polarity TIM_INPUTCHANNELPOLARITY_BOTHEDGE is not authorized for TIM Channel 4. * @retval None */ #define __HAL_TIM_SET_CAPTUREPOLARITY(__HANDLE__, __CHANNEL__, __POLARITY__) \ do{ \ TIM_RESET_CAPTUREPOLARITY((__HANDLE__), (__CHANNEL__)); \ TIM_SET_CAPTUREPOLARITY((__HANDLE__), (__CHANNEL__), (__POLARITY__)); \ }while(0) /** * @} */ /* Include TIM HAL Extension module */ #include "stm32f4xx_hal_tim_ex.h" /* Exported functions --------------------------------------------------------*/ /** @addtogroup TIM_Exported_Functions * @{ */ /** @addtogroup TIM_Exported_Functions_Group1 * @{ */ /* Time Base functions ********************************************************/ HAL_StatusTypeDef HAL_TIM_Base_Init(TIM_HandleTypeDef *htim); HAL_StatusTypeDef HAL_TIM_Base_DeInit(TIM_HandleTypeDef *htim); void HAL_TIM_Base_MspInit(TIM_HandleTypeDef *htim); void HAL_TIM_Base_MspDeInit(TIM_HandleTypeDef *htim); /* Blocking mode: Polling */ HAL_StatusTypeDef HAL_TIM_Base_Start(TIM_HandleTypeDef *htim); HAL_StatusTypeDef HAL_TIM_Base_Stop(TIM_HandleTypeDef *htim); /* Non-Blocking mode: Interrupt */ HAL_StatusTypeDef HAL_TIM_Base_Start_IT(TIM_HandleTypeDef *htim); HAL_StatusTypeDef HAL_TIM_Base_Stop_IT(TIM_HandleTypeDef *htim); /* Non-Blocking mode: DMA */ HAL_StatusTypeDef HAL_TIM_Base_Start_DMA(TIM_HandleTypeDef *htim, uint32_t *pData, uint16_t Length); HAL_StatusTypeDef HAL_TIM_Base_Stop_DMA(TIM_HandleTypeDef *htim); /** * @} */ /** @addtogroup TIM_Exported_Functions_Group2 * @{ */ /* Timer Output Compare functions **********************************************/ HAL_StatusTypeDef HAL_TIM_OC_Init(TIM_HandleTypeDef *htim); HAL_StatusTypeDef HAL_TIM_OC_DeInit(TIM_HandleTypeDef *htim); void HAL_TIM_OC_MspInit(TIM_HandleTypeDef *htim); void HAL_TIM_OC_MspDeInit(TIM_HandleTypeDef *htim); /* Blocking mode: Polling */ HAL_StatusTypeDef HAL_TIM_OC_Start(TIM_HandleTypeDef *htim, uint32_t Channel); HAL_StatusTypeDef HAL_TIM_OC_Stop(TIM_HandleTypeDef *htim, uint32_t Channel); /* Non-Blocking mode: Interrupt */ HAL_StatusTypeDef HAL_TIM_OC_Start_IT(TIM_HandleTypeDef *htim, uint32_t Channel); HAL_StatusTypeDef HAL_TIM_OC_Stop_IT(TIM_HandleTypeDef *htim, uint32_t Channel); /* Non-Blocking mode: DMA */ HAL_StatusTypeDef HAL_TIM_OC_Start_DMA(TIM_HandleTypeDef *htim, uint32_t Channel, uint32_t *pData, uint16_t Length); HAL_StatusTypeDef HAL_TIM_OC_Stop_DMA(TIM_HandleTypeDef *htim, uint32_t Channel); /** * @} */ /** @addtogroup TIM_Exported_Functions_Group3 * @{ */ /* Timer PWM functions *********************************************************/ HAL_StatusTypeDef HAL_TIM_PWM_Init(TIM_HandleTypeDef *htim); HAL_StatusTypeDef HAL_TIM_PWM_DeInit(TIM_HandleTypeDef *htim); void HAL_TIM_PWM_MspInit(TIM_HandleTypeDef *htim); void HAL_TIM_PWM_MspDeInit(TIM_HandleTypeDef *htim); /* Blocking mode: Polling */ HAL_StatusTypeDef HAL_TIM_PWM_Start(TIM_HandleTypeDef *htim, uint32_t Channel); HAL_StatusTypeDef HAL_TIM_PWM_Stop(TIM_HandleTypeDef *htim, uint32_t Channel); /* Non-Blocking mode: Interrupt */ HAL_StatusTypeDef HAL_TIM_PWM_Start_IT(TIM_HandleTypeDef *htim, uint32_t Channel); HAL_StatusTypeDef HAL_TIM_PWM_Stop_IT(TIM_HandleTypeDef *htim, uint32_t Channel); /* Non-Blocking mode: DMA */ HAL_StatusTypeDef HAL_TIM_PWM_Start_DMA(TIM_HandleTypeDef *htim, uint32_t Channel, uint32_t *pData, uint16_t Length); HAL_StatusTypeDef HAL_TIM_PWM_Stop_DMA(TIM_HandleTypeDef *htim, uint32_t Channel); /** * @} */ /** @addtogroup TIM_Exported_Functions_Group4 * @{ */ /* Timer Input Capture functions ***********************************************/ HAL_StatusTypeDef HAL_TIM_IC_Init(TIM_HandleTypeDef *htim); HAL_StatusTypeDef HAL_TIM_IC_DeInit(TIM_HandleTypeDef *htim); void HAL_TIM_IC_MspInit(TIM_HandleTypeDef *htim); void HAL_TIM_IC_MspDeInit(TIM_HandleTypeDef *htim); /* Blocking mode: Polling */ HAL_StatusTypeDef HAL_TIM_IC_Start(TIM_HandleTypeDef *htim, uint32_t Channel); HAL_StatusTypeDef HAL_TIM_IC_Stop(TIM_HandleTypeDef *htim, uint32_t Channel); /* Non-Blocking mode: Interrupt */ HAL_StatusTypeDef HAL_TIM_IC_Start_IT(TIM_HandleTypeDef *htim, uint32_t Channel); HAL_StatusTypeDef HAL_TIM_IC_Stop_IT(TIM_HandleTypeDef *htim, uint32_t Channel); /* Non-Blocking mode: DMA */ HAL_StatusTypeDef HAL_TIM_IC_Start_DMA(TIM_HandleTypeDef *htim, uint32_t Channel, uint32_t *pData, uint16_t Length); HAL_StatusTypeDef HAL_TIM_IC_Stop_DMA(TIM_HandleTypeDef *htim, uint32_t Channel); /** * @} */ /** @addtogroup TIM_Exported_Functions_Group5 * @{ */ /* Timer One Pulse functions ***************************************************/ HAL_StatusTypeDef HAL_TIM_OnePulse_Init(TIM_HandleTypeDef *htim, uint32_t OnePulseMode); HAL_StatusTypeDef HAL_TIM_OnePulse_DeInit(TIM_HandleTypeDef *htim); void HAL_TIM_OnePulse_MspInit(TIM_HandleTypeDef *htim); void HAL_TIM_OnePulse_MspDeInit(TIM_HandleTypeDef *htim); /* Blocking mode: Polling */ HAL_StatusTypeDef HAL_TIM_OnePulse_Start(TIM_HandleTypeDef *htim, uint32_t OutputChannel); HAL_StatusTypeDef HAL_TIM_OnePulse_Stop(TIM_HandleTypeDef *htim, uint32_t OutputChannel); /* Non-Blocking mode: Interrupt */ HAL_StatusTypeDef HAL_TIM_OnePulse_Start_IT(TIM_HandleTypeDef *htim, uint32_t OutputChannel); HAL_StatusTypeDef HAL_TIM_OnePulse_Stop_IT(TIM_HandleTypeDef *htim, uint32_t OutputChannel); /** * @} */ /** @addtogroup TIM_Exported_Functions_Group6 * @{ */ /* Timer Encoder functions *****************************************************/ HAL_StatusTypeDef HAL_TIM_Encoder_Init(TIM_HandleTypeDef *htim, TIM_Encoder_InitTypeDef* sConfig); HAL_StatusTypeDef HAL_TIM_Encoder_DeInit(TIM_HandleTypeDef *htim); void HAL_TIM_Encoder_MspInit(TIM_HandleTypeDef *htim); void HAL_TIM_Encoder_MspDeInit(TIM_HandleTypeDef *htim); /* Blocking mode: Polling */ HAL_StatusTypeDef HAL_TIM_Encoder_Start(TIM_HandleTypeDef *htim, uint32_t Channel); HAL_StatusTypeDef HAL_TIM_Encoder_Stop(TIM_HandleTypeDef *htim, uint32_t Channel); /* Non-Blocking mode: Interrupt */ HAL_StatusTypeDef HAL_TIM_Encoder_Start_IT(TIM_HandleTypeDef *htim, uint32_t Channel); HAL_StatusTypeDef HAL_TIM_Encoder_Stop_IT(TIM_HandleTypeDef *htim, uint32_t Channel); /* Non-Blocking mode: DMA */ HAL_StatusTypeDef HAL_TIM_Encoder_Start_DMA(TIM_HandleTypeDef *htim, uint32_t Channel, uint32_t *pData1, uint32_t *pData2, uint16_t Length); HAL_StatusTypeDef HAL_TIM_Encoder_Stop_DMA(TIM_HandleTypeDef *htim, uint32_t Channel); /** * @} */ /** @addtogroup TIM_Exported_Functions_Group7 * @{ */ /* Interrupt Handler functions **********************************************/ void HAL_TIM_IRQHandler(TIM_HandleTypeDef *htim); /** * @} */ /** @addtogroup TIM_Exported_Functions_Group8 * @{ */ /* Control functions *********************************************************/ HAL_StatusTypeDef HAL_TIM_OC_ConfigChannel(TIM_HandleTypeDef *htim, TIM_OC_InitTypeDef* sConfig, uint32_t Channel); HAL_StatusTypeDef HAL_TIM_PWM_ConfigChannel(TIM_HandleTypeDef *htim, TIM_OC_InitTypeDef* sConfig, uint32_t Channel); HAL_StatusTypeDef HAL_TIM_IC_ConfigChannel(TIM_HandleTypeDef *htim, TIM_IC_InitTypeDef* sConfig, uint32_t Channel); HAL_StatusTypeDef HAL_TIM_OnePulse_ConfigChannel(TIM_HandleTypeDef *htim, TIM_OnePulse_InitTypeDef* sConfig, uint32_t OutputChannel, uint32_t InputChannel); HAL_StatusTypeDef HAL_TIM_ConfigOCrefClear(TIM_HandleTypeDef *htim, TIM_ClearInputConfigTypeDef * sClearInputConfig, uint32_t Channel); HAL_StatusTypeDef HAL_TIM_ConfigClockSource(TIM_HandleTypeDef *htim, TIM_ClockConfigTypeDef * sClockSourceConfig); HAL_StatusTypeDef HAL_TIM_ConfigTI1Input(TIM_HandleTypeDef *htim, uint32_t TI1_Selection); HAL_StatusTypeDef HAL_TIM_SlaveConfigSynchronization(TIM_HandleTypeDef *htim, TIM_SlaveConfigTypeDef * sSlaveConfig); HAL_StatusTypeDef HAL_TIM_SlaveConfigSynchronization_IT(TIM_HandleTypeDef *htim, TIM_SlaveConfigTypeDef * sSlaveConfig); HAL_StatusTypeDef HAL_TIM_DMABurst_WriteStart(TIM_HandleTypeDef *htim, uint32_t BurstBaseAddress, uint32_t BurstRequestSrc, \ uint32_t *BurstBuffer, uint32_t BurstLength); HAL_StatusTypeDef HAL_TIM_DMABurst_WriteStop(TIM_HandleTypeDef *htim, uint32_t BurstRequestSrc); HAL_StatusTypeDef HAL_TIM_DMABurst_ReadStart(TIM_HandleTypeDef *htim, uint32_t BurstBaseAddress, uint32_t BurstRequestSrc, \ uint32_t *BurstBuffer, uint32_t BurstLength); HAL_StatusTypeDef HAL_TIM_DMABurst_ReadStop(TIM_HandleTypeDef *htim, uint32_t BurstRequestSrc); HAL_StatusTypeDef HAL_TIM_GenerateEvent(TIM_HandleTypeDef *htim, uint32_t EventSource); uint32_t HAL_TIM_ReadCapturedValue(TIM_HandleTypeDef *htim, uint32_t Channel); /** * @} */ /** @addtogroup TIM_Exported_Functions_Group9 * @{ */ /* Callback in non blocking modes (Interrupt and DMA) *************************/ void HAL_TIM_PeriodElapsedCallback(TIM_HandleTypeDef *htim); void HAL_TIM_OC_DelayElapsedCallback(TIM_HandleTypeDef *htim); void HAL_TIM_IC_CaptureCallback(TIM_HandleTypeDef *htim); void HAL_TIM_PWM_PulseFinishedCallback(TIM_HandleTypeDef *htim); void HAL_TIM_TriggerCallback(TIM_HandleTypeDef *htim); void HAL_TIM_ErrorCallback(TIM_HandleTypeDef *htim); /** * @} */ /** @addtogroup TIM_Exported_Functions_Group10 * @{ */ /* Peripheral State functions **************************************************/ HAL_TIM_StateTypeDef HAL_TIM_Base_GetState(TIM_HandleTypeDef *htim); HAL_TIM_StateTypeDef HAL_TIM_OC_GetState(TIM_HandleTypeDef *htim); HAL_TIM_StateTypeDef HAL_TIM_PWM_GetState(TIM_HandleTypeDef *htim); HAL_TIM_StateTypeDef HAL_TIM_IC_GetState(TIM_HandleTypeDef *htim); HAL_TIM_StateTypeDef HAL_TIM_OnePulse_GetState(TIM_HandleTypeDef *htim); HAL_TIM_StateTypeDef HAL_TIM_Encoder_GetState(TIM_HandleTypeDef *htim); /** * @} */ /** * @} */ /* Private macros ------------------------------------------------------------*/ /** @defgroup TIM_Private_Macros TIM Private Macros * @{ */ /** @defgroup TIM_IS_TIM_Definitions TIM Private macros to check input parameters * @{ */ #define IS_TIM_COUNTER_MODE(MODE) (((MODE) == TIM_COUNTERMODE_UP) || \ ((MODE) == TIM_COUNTERMODE_DOWN) || \ ((MODE) == TIM_COUNTERMODE_CENTERALIGNED1) || \ ((MODE) == TIM_COUNTERMODE_CENTERALIGNED2) || \ ((MODE) == TIM_COUNTERMODE_CENTERALIGNED3)) #define IS_TIM_CLOCKDIVISION_DIV(DIV) (((DIV) == TIM_CLOCKDIVISION_DIV1) || \ ((DIV) == TIM_CLOCKDIVISION_DIV2) || \ ((DIV) == TIM_CLOCKDIVISION_DIV4)) #define IS_TIM_PWM_MODE(MODE) (((MODE) == TIM_OCMODE_PWM1) || \ ((MODE) == TIM_OCMODE_PWM2)) #define IS_TIM_OC_MODE(MODE) (((MODE) == TIM_OCMODE_TIMING) || \ ((MODE) == TIM_OCMODE_ACTIVE) || \ ((MODE) == TIM_OCMODE_INACTIVE) || \ ((MODE) == TIM_OCMODE_TOGGLE) || \ ((MODE) == TIM_OCMODE_FORCED_ACTIVE) || \ ((MODE) == TIM_OCMODE_FORCED_INACTIVE)) #define IS_TIM_FAST_STATE(STATE) (((STATE) == TIM_OCFAST_DISABLE) || \ ((STATE) == TIM_OCFAST_ENABLE)) #define IS_TIM_OC_POLARITY(POLARITY) (((POLARITY) == TIM_OCPOLARITY_HIGH) || \ ((POLARITY) == TIM_OCPOLARITY_LOW)) #define IS_TIM_OCN_POLARITY(POLARITY) (((POLARITY) == TIM_OCNPOLARITY_HIGH) || \ ((POLARITY) == TIM_OCNPOLARITY_LOW)) #define IS_TIM_OCIDLE_STATE(STATE) (((STATE) == TIM_OCIDLESTATE_SET) || \ ((STATE) == TIM_OCIDLESTATE_RESET)) #define IS_TIM_OCNIDLE_STATE(STATE) (((STATE) == TIM_OCNIDLESTATE_SET) || \ ((STATE) == TIM_OCNIDLESTATE_RESET)) #define IS_TIM_CHANNELS(CHANNEL) (((CHANNEL) == TIM_CHANNEL_1) || \ ((CHANNEL) == TIM_CHANNEL_2) || \ ((CHANNEL) == TIM_CHANNEL_3) || \ ((CHANNEL) == TIM_CHANNEL_4) || \ ((CHANNEL) == TIM_CHANNEL_ALL)) #define IS_TIM_OPM_CHANNELS(CHANNEL) (((CHANNEL) == TIM_CHANNEL_1) || \ ((CHANNEL) == TIM_CHANNEL_2)) #define IS_TIM_COMPLEMENTARY_CHANNELS(CHANNEL) (((CHANNEL) == TIM_CHANNEL_1) || \ ((CHANNEL) == TIM_CHANNEL_2) || \ ((CHANNEL) == TIM_CHANNEL_3)) #define IS_TIM_IC_POLARITY(POLARITY) (((POLARITY) == TIM_ICPOLARITY_RISING) || \ ((POLARITY) == TIM_ICPOLARITY_FALLING) || \ ((POLARITY) == TIM_ICPOLARITY_BOTHEDGE)) #define IS_TIM_IC_SELECTION(SELECTION) (((SELECTION) == TIM_ICSELECTION_DIRECTTI) || \ ((SELECTION) == TIM_ICSELECTION_INDIRECTTI) || \ ((SELECTION) == TIM_ICSELECTION_TRC)) #define IS_TIM_IC_PRESCALER(PRESCALER) (((PRESCALER) == TIM_ICPSC_DIV1) || \ ((PRESCALER) == TIM_ICPSC_DIV2) || \ ((PRESCALER) == TIM_ICPSC_DIV4) || \ ((PRESCALER) == TIM_ICPSC_DIV8)) #define IS_TIM_OPM_MODE(MODE) (((MODE) == TIM_OPMODE_SINGLE) || \ ((MODE) == TIM_OPMODE_REPETITIVE)) #define IS_TIM_DMA_SOURCE(SOURCE) ((((SOURCE) & 0xFFFF80FF) == 0x00000000) && ((SOURCE) != 0x00000000)) #define IS_TIM_ENCODER_MODE(MODE) (((MODE) == TIM_ENCODERMODE_TI1) || \ ((MODE) == TIM_ENCODERMODE_TI2) || \ ((MODE) == TIM_ENCODERMODE_TI12)) #define IS_TIM_EVENT_SOURCE(SOURCE) ((((SOURCE) & 0xFFFFFF00) == 0x00000000) && ((SOURCE) != 0x00000000)) #define IS_TIM_CLOCKSOURCE(CLOCK) (((CLOCK) == TIM_CLOCKSOURCE_INTERNAL) || \ ((CLOCK) == TIM_CLOCKSOURCE_ETRMODE2) || \ ((CLOCK) == TIM_CLOCKSOURCE_ITR0) || \ ((CLOCK) == TIM_CLOCKSOURCE_ITR1) || \ ((CLOCK) == TIM_CLOCKSOURCE_ITR2) || \ ((CLOCK) == TIM_CLOCKSOURCE_ITR3) || \ ((CLOCK) == TIM_CLOCKSOURCE_TI1ED) || \ ((CLOCK) == TIM_CLOCKSOURCE_TI1) || \ ((CLOCK) == TIM_CLOCKSOURCE_TI2) || \ ((CLOCK) == TIM_CLOCKSOURCE_ETRMODE1)) #define IS_TIM_CLOCKPOLARITY(POLARITY) (((POLARITY) == TIM_CLOCKPOLARITY_INVERTED) || \ ((POLARITY) == TIM_CLOCKPOLARITY_NONINVERTED) || \ ((POLARITY) == TIM_CLOCKPOLARITY_RISING) || \ ((POLARITY) == TIM_CLOCKPOLARITY_FALLING) || \ ((POLARITY) == TIM_CLOCKPOLARITY_BOTHEDGE)) #define IS_TIM_CLOCKPRESCALER(PRESCALER) (((PRESCALER) == TIM_CLOCKPRESCALER_DIV1) || \ ((PRESCALER) == TIM_CLOCKPRESCALER_DIV2) || \ ((PRESCALER) == TIM_CLOCKPRESCALER_DIV4) || \ ((PRESCALER) == TIM_CLOCKPRESCALER_DIV8)) #define IS_TIM_CLOCKFILTER(ICFILTER) ((ICFILTER) <= 0xF) #define IS_TIM_CLEARINPUT_SOURCE(SOURCE) (((SOURCE) == TIM_CLEARINPUTSOURCE_NONE) || \ ((SOURCE) == TIM_CLEARINPUTSOURCE_ETR)) #define IS_TIM_CLEARINPUT_POLARITY(POLARITY) (((POLARITY) == TIM_CLEARINPUTPOLARITY_INVERTED) || \ ((POLARITY) == TIM_CLEARINPUTPOLARITY_NONINVERTED)) #define IS_TIM_CLEARINPUT_PRESCALER(PRESCALER) (((PRESCALER) == TIM_CLEARINPUTPRESCALER_DIV1) || \ ((PRESCALER) == TIM_CLEARINPUTPRESCALER_DIV2) || \ ((PRESCALER) == TIM_CLEARINPUTPRESCALER_DIV4) || \ ((PRESCALER) == TIM_CLEARINPUTPRESCALER_DIV8)) #define IS_TIM_CLEARINPUT_FILTER(ICFILTER) ((ICFILTER) <= 0xF) #define IS_TIM_OSSR_STATE(STATE) (((STATE) == TIM_OSSR_ENABLE) || \ ((STATE) == TIM_OSSR_DISABLE)) #define IS_TIM_OSSI_STATE(STATE) (((STATE) == TIM_OSSI_ENABLE) || \ ((STATE) == TIM_OSSI_DISABLE)) #define IS_TIM_LOCK_LEVEL(LEVEL) (((LEVEL) == TIM_LOCKLEVEL_OFF) || \ ((LEVEL) == TIM_LOCKLEVEL_1) || \ ((LEVEL) == TIM_LOCKLEVEL_2) || \ ((LEVEL) == TIM_LOCKLEVEL_3)) #define IS_TIM_BREAK_STATE(STATE) (((STATE) == TIM_BREAK_ENABLE) || \ ((STATE) == TIM_BREAK_DISABLE)) #define IS_TIM_BREAK_POLARITY(POLARITY) (((POLARITY) == TIM_BREAKPOLARITY_LOW) || \ ((POLARITY) == TIM_BREAKPOLARITY_HIGH)) #define IS_TIM_AUTOMATIC_OUTPUT_STATE(STATE) (((STATE) == TIM_AUTOMATICOUTPUT_ENABLE) || \ ((STATE) == TIM_AUTOMATICOUTPUT_DISABLE)) #define IS_TIM_TRGO_SOURCE(SOURCE) (((SOURCE) == TIM_TRGO_RESET) || \ ((SOURCE) == TIM_TRGO_ENABLE) || \ ((SOURCE) == TIM_TRGO_UPDATE) || \ ((SOURCE) == TIM_TRGO_OC1) || \ ((SOURCE) == TIM_TRGO_OC1REF) || \ ((SOURCE) == TIM_TRGO_OC2REF) || \ ((SOURCE) == TIM_TRGO_OC3REF) || \ ((SOURCE) == TIM_TRGO_OC4REF)) #define IS_TIM_SLAVE_MODE(MODE) (((MODE) == TIM_SLAVEMODE_DISABLE) || \ ((MODE) == TIM_SLAVEMODE_GATED) || \ ((MODE) == TIM_SLAVEMODE_RESET) || \ ((MODE) == TIM_SLAVEMODE_TRIGGER) || \ ((MODE) == TIM_SLAVEMODE_EXTERNAL1)) #define IS_TIM_MSM_STATE(STATE) (((STATE) == TIM_MASTERSLAVEMODE_ENABLE) || \ ((STATE) == TIM_MASTERSLAVEMODE_DISABLE)) #define IS_TIM_TRIGGER_SELECTION(SELECTION) (((SELECTION) == TIM_TS_ITR0) || \ ((SELECTION) == TIM_TS_ITR1) || \ ((SELECTION) == TIM_TS_ITR2) || \ ((SELECTION) == TIM_TS_ITR3) || \ ((SELECTION) == TIM_TS_TI1F_ED) || \ ((SELECTION) == TIM_TS_TI1FP1) || \ ((SELECTION) == TIM_TS_TI2FP2) || \ ((SELECTION) == TIM_TS_ETRF)) #define IS_TIM_INTERNAL_TRIGGEREVENT_SELECTION(SELECTION) (((SELECTION) == TIM_TS_ITR0) || \ ((SELECTION) == TIM_TS_ITR1) || \ ((SELECTION) == TIM_TS_ITR2) || \ ((SELECTION) == TIM_TS_ITR3) || \ ((SELECTION) == TIM_TS_NONE)) #define IS_TIM_TRIGGERPOLARITY(POLARITY) (((POLARITY) == TIM_TRIGGERPOLARITY_INVERTED ) || \ ((POLARITY) == TIM_TRIGGERPOLARITY_NONINVERTED) || \ ((POLARITY) == TIM_TRIGGERPOLARITY_RISING ) || \ ((POLARITY) == TIM_TRIGGERPOLARITY_FALLING ) || \ ((POLARITY) == TIM_TRIGGERPOLARITY_BOTHEDGE )) #define IS_TIM_TRIGGERPRESCALER(PRESCALER) (((PRESCALER) == TIM_TRIGGERPRESCALER_DIV1) || \ ((PRESCALER) == TIM_TRIGGERPRESCALER_DIV2) || \ ((PRESCALER) == TIM_TRIGGERPRESCALER_DIV4) || \ ((PRESCALER) == TIM_TRIGGERPRESCALER_DIV8)) #define IS_TIM_TRIGGERFILTER(ICFILTER) ((ICFILTER) <= 0xF) #define IS_TIM_TI1SELECTION(TI1SELECTION) (((TI1SELECTION) == TIM_TI1SELECTION_CH1) || \ ((TI1SELECTION) == TIM_TI1SELECTION_XORCOMBINATION)) #define IS_TIM_DMA_BASE(BASE) (((BASE) == TIM_DMABASE_CR1) || \ ((BASE) == TIM_DMABASE_CR2) || \ ((BASE) == TIM_DMABASE_SMCR) || \ ((BASE) == TIM_DMABASE_DIER) || \ ((BASE) == TIM_DMABASE_SR) || \ ((BASE) == TIM_DMABASE_EGR) || \ ((BASE) == TIM_DMABASE_CCMR1) || \ ((BASE) == TIM_DMABASE_CCMR2) || \ ((BASE) == TIM_DMABASE_CCER) || \ ((BASE) == TIM_DMABASE_CNT) || \ ((BASE) == TIM_DMABASE_PSC) || \ ((BASE) == TIM_DMABASE_ARR) || \ ((BASE) == TIM_DMABASE_RCR) || \ ((BASE) == TIM_DMABASE_CCR1) || \ ((BASE) == TIM_DMABASE_CCR2) || \ ((BASE) == TIM_DMABASE_CCR3) || \ ((BASE) == TIM_DMABASE_CCR4) || \ ((BASE) == TIM_DMABASE_BDTR) || \ ((BASE) == TIM_DMABASE_DCR) || \ ((BASE) == TIM_DMABASE_OR)) #define IS_TIM_DMA_LENGTH(LENGTH) (((LENGTH) == TIM_DMABURSTLENGTH_1TRANSFER) || \ ((LENGTH) == TIM_DMABURSTLENGTH_2TRANSFERS) || \ ((LENGTH) == TIM_DMABURSTLENGTH_3TRANSFERS) || \ ((LENGTH) == TIM_DMABURSTLENGTH_4TRANSFERS) || \ ((LENGTH) == TIM_DMABURSTLENGTH_5TRANSFERS) || \ ((LENGTH) == TIM_DMABURSTLENGTH_6TRANSFERS) || \ ((LENGTH) == TIM_DMABURSTLENGTH_7TRANSFERS) || \ ((LENGTH) == TIM_DMABURSTLENGTH_8TRANSFERS) || \ ((LENGTH) == TIM_DMABURSTLENGTH_9TRANSFERS) || \ ((LENGTH) == TIM_DMABURSTLENGTH_10TRANSFERS) || \ ((LENGTH) == TIM_DMABURSTLENGTH_11TRANSFERS) || \ ((LENGTH) == TIM_DMABURSTLENGTH_12TRANSFERS) || \ ((LENGTH) == TIM_DMABURSTLENGTH_13TRANSFERS) || \ ((LENGTH) == TIM_DMABURSTLENGTH_14TRANSFERS) || \ ((LENGTH) == TIM_DMABURSTLENGTH_15TRANSFERS) || \ ((LENGTH) == TIM_DMABURSTLENGTH_16TRANSFERS) || \ ((LENGTH) == TIM_DMABURSTLENGTH_17TRANSFERS) || \ ((LENGTH) == TIM_DMABURSTLENGTH_18TRANSFERS)) #define IS_TIM_IC_FILTER(ICFILTER) ((ICFILTER) <= 0xF) /** * @} */ /** @defgroup TIM_Mask_Definitions TIM Mask Definition * @{ */ /* The counter of a timer instance is disabled only if all the CCx and CCxN channels have been disabled */ #define TIM_CCER_CCxE_MASK ((uint32_t)(TIM_CCER_CC1E | TIM_CCER_CC2E | TIM_CCER_CC3E | TIM_CCER_CC4E)) #define TIM_CCER_CCxNE_MASK ((uint32_t)(TIM_CCER_CC1NE | TIM_CCER_CC2NE | TIM_CCER_CC3NE)) /** * @} */ /** * @} */ /* Private functions ---------------------------------------------------------*/ /** @defgroup TIM_Private_Functions TIM Private Functions * @{ */ void TIM_Base_SetConfig(TIM_TypeDef *TIMx, TIM_Base_InitTypeDef *Structure); void TIM_TI1_SetConfig(TIM_TypeDef *TIMx, uint32_t TIM_ICPolarity, uint32_t TIM_ICSelection, uint32_t TIM_ICFilter); void TIM_OC2_SetConfig(TIM_TypeDef *TIMx, TIM_OC_InitTypeDef *OC_Config); void TIM_DMADelayPulseCplt(DMA_HandleTypeDef *hdma); void TIM_DMAError(DMA_HandleTypeDef *hdma); void TIM_DMACaptureCplt(DMA_HandleTypeDef *hdma); void TIM_CCxChannelCmd(TIM_TypeDef* TIMx, uint32_t Channel, uint32_t ChannelState); /** * @} */ /** * @} */ /** * @} */ #ifdef __cplusplus } #endif #endif /* __STM32F4xx_HAL_TIM_H */ /************************ (C) COPYRIGHT STMicroelectronics *****END OF FILE****/ ================================================ FILE: Zelig/mbed/TARGET_NUCLEO_F401RE/stm32f4xx_hal_tim_ex.h ================================================ /** ****************************************************************************** * @file stm32f4xx_hal_tim_ex.h * @author MCD Application Team * @version V1.4.1 * @date 09-October-2015 * @brief Header file of TIM HAL Extension module. ****************************************************************************** * @attention * *

© COPYRIGHT(c) 2015 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. * ****************************************************************************** */ /* Define to prevent recursive inclusion -------------------------------------*/ #ifndef __STM32F4xx_HAL_TIM_EX_H #define __STM32F4xx_HAL_TIM_EX_H #ifdef __cplusplus extern "C" { #endif /* Includes ------------------------------------------------------------------*/ #include "stm32f4xx_hal_def.h" /** @addtogroup STM32F4xx_HAL_Driver * @{ */ /** @addtogroup TIMEx * @{ */ /* Exported types ------------------------------------------------------------*/ /** @defgroup TIMEx_Exported_Types TIM Exported Types * @{ */ /** * @brief TIM Hall sensor Configuration Structure definition */ typedef struct { uint32_t IC1Polarity; /*!< Specifies the active edge of the input signal. This parameter can be a value of @ref TIM_Input_Capture_Polarity */ uint32_t IC1Prescaler; /*!< Specifies the Input Capture Prescaler. This parameter can be a value of @ref TIM_Input_Capture_Prescaler */ uint32_t IC1Filter; /*!< Specifies the input capture filter. This parameter can be a number between Min_Data = 0x0 and Max_Data = 0xF */ uint32_t Commutation_Delay; /*!< Specifies the pulse value to be loaded into the Capture Compare Register. This parameter can be a number between Min_Data = 0x0000 and Max_Data = 0xFFFF */ } TIM_HallSensor_InitTypeDef; /** * @brief TIM Master configuration Structure definition */ typedef struct { uint32_t MasterOutputTrigger; /*!< Trigger output (TRGO) selection. This parameter can be a value of @ref TIM_Master_Mode_Selection */ uint32_t MasterSlaveMode; /*!< Master/slave mode selection. This parameter can be a value of @ref TIM_Master_Slave_Mode */ }TIM_MasterConfigTypeDef; /** * @brief TIM Break and Dead time configuration Structure definition */ typedef struct { uint32_t OffStateRunMode; /*!< TIM off state in run mode. This parameter can be a value of @ref TIM_OSSR_Off_State_Selection_for_Run_mode_state */ uint32_t OffStateIDLEMode; /*!< TIM off state in IDLE mode. This parameter can be a value of @ref TIM_OSSI_Off_State_Selection_for_Idle_mode_state */ uint32_t LockLevel; /*!< TIM Lock level. This parameter can be a value of @ref TIM_Lock_level */ uint32_t DeadTime; /*!< TIM dead Time. This parameter can be a number between Min_Data = 0x00 and Max_Data = 0xFF */ uint32_t BreakState; /*!< TIM Break State. This parameter can be a value of @ref TIM_Break_Input_enable_disable */ uint32_t BreakPolarity; /*!< TIM Break input polarity. This parameter can be a value of @ref TIM_Break_Polarity */ uint32_t AutomaticOutput; /*!< TIM Automatic Output Enable state. This parameter can be a value of @ref TIM_AOE_Bit_Set_Reset */ }TIM_BreakDeadTimeConfigTypeDef; /** * @} */ /* Exported constants --------------------------------------------------------*/ /** @defgroup TIMEx_Exported_Constants TIM Exported Constants * @{ */ /** @defgroup TIMEx_Remap TIM Remap * @{ */ #define TIM_TIM2_TIM8_TRGO (0x00000000) #define TIM_TIM2_ETH_PTP (0x00000400) #define TIM_TIM2_USBFS_SOF (0x00000800) #define TIM_TIM2_USBHS_SOF (0x00000C00) #define TIM_TIM5_GPIO (0x00000000) #define TIM_TIM5_LSI (0x00000040) #define TIM_TIM5_LSE (0x00000080) #define TIM_TIM5_RTC (0x000000C0) #define TIM_TIM11_GPIO (0x00000000) #define TIM_TIM11_HSE (0x00000002) #if defined (STM32F446xx) #define TIM_TIM11_SPDIFRX (0x00000001) #endif /* STM32F446xx */ /** * @} */ #if defined(STM32F410Tx) || defined(STM32F410Cx) || defined(STM32F410Rx) /** @defgroup TIMEx_SystemBreakInput TIM System Break Input * @{ */ #define TIM_SYSTEMBREAKINPUT_HARDFAULT ((uint32_t)0x00000001) /* Core Lockup lock output(Hardfault) is connected to Break Input of TIM1 and TIM8 */ #define TIM_SYSTEMBREAKINPUT_PVD ((uint32_t)0x00000004) /* PVD Interrupt is connected to Break Input of TIM1 and TIM8 */ #define TIM_SYSTEMBREAKINPUT_HARDFAULT_PVD ((uint32_t)0x00000005) /* Core Lockup lock output(Hardfault) and PVD Interrupt are connected to Break Input of TIM1 and TIM8 */ /** * @} */ #endif /* STM32F410Tx || STM32F410Cx || STM32F410Rx */ /** * @} */ /* Exported macro ------------------------------------------------------------*/ /* Exported functions --------------------------------------------------------*/ /** @addtogroup TIMEx_Exported_Functions * @{ */ /** @addtogroup TIMEx_Exported_Functions_Group1 * @{ */ /* Timer Hall Sensor functions **********************************************/ HAL_StatusTypeDef HAL_TIMEx_HallSensor_Init(TIM_HandleTypeDef* htim, TIM_HallSensor_InitTypeDef* sConfig); HAL_StatusTypeDef HAL_TIMEx_HallSensor_DeInit(TIM_HandleTypeDef* htim); void HAL_TIMEx_HallSensor_MspInit(TIM_HandleTypeDef* htim); void HAL_TIMEx_HallSensor_MspDeInit(TIM_HandleTypeDef* htim); /* Blocking mode: Polling */ HAL_StatusTypeDef HAL_TIMEx_HallSensor_Start(TIM_HandleTypeDef* htim); HAL_StatusTypeDef HAL_TIMEx_HallSensor_Stop(TIM_HandleTypeDef* htim); /* Non-Blocking mode: Interrupt */ HAL_StatusTypeDef HAL_TIMEx_HallSensor_Start_IT(TIM_HandleTypeDef* htim); HAL_StatusTypeDef HAL_TIMEx_HallSensor_Stop_IT(TIM_HandleTypeDef* htim); /* Non-Blocking mode: DMA */ HAL_StatusTypeDef HAL_TIMEx_HallSensor_Start_DMA(TIM_HandleTypeDef* htim, uint32_t *pData, uint16_t Length); HAL_StatusTypeDef HAL_TIMEx_HallSensor_Stop_DMA(TIM_HandleTypeDef* htim); /** * @} */ /** @addtogroup TIMEx_Exported_Functions_Group2 * @{ */ /* Timer Complementary Output Compare functions *****************************/ /* Blocking mode: Polling */ HAL_StatusTypeDef HAL_TIMEx_OCN_Start(TIM_HandleTypeDef* htim, uint32_t Channel); HAL_StatusTypeDef HAL_TIMEx_OCN_Stop(TIM_HandleTypeDef* htim, uint32_t Channel); /* Non-Blocking mode: Interrupt */ HAL_StatusTypeDef HAL_TIMEx_OCN_Start_IT(TIM_HandleTypeDef* htim, uint32_t Channel); HAL_StatusTypeDef HAL_TIMEx_OCN_Stop_IT(TIM_HandleTypeDef* htim, uint32_t Channel); /* Non-Blocking mode: DMA */ HAL_StatusTypeDef HAL_TIMEx_OCN_Start_DMA(TIM_HandleTypeDef* htim, uint32_t Channel, uint32_t *pData, uint16_t Length); HAL_StatusTypeDef HAL_TIMEx_OCN_Stop_DMA(TIM_HandleTypeDef* htim, uint32_t Channel); /** * @} */ /** @addtogroup TIMEx_Exported_Functions_Group3 * @{ */ /* Timer Complementary PWM functions ****************************************/ /* Blocking mode: Polling */ HAL_StatusTypeDef HAL_TIMEx_PWMN_Start(TIM_HandleTypeDef* htim, uint32_t Channel); HAL_StatusTypeDef HAL_TIMEx_PWMN_Stop(TIM_HandleTypeDef* htim, uint32_t Channel); /* Non-Blocking mode: Interrupt */ HAL_StatusTypeDef HAL_TIMEx_PWMN_Start_IT(TIM_HandleTypeDef* htim, uint32_t Channel); HAL_StatusTypeDef HAL_TIMEx_PWMN_Stop_IT(TIM_HandleTypeDef* htim, uint32_t Channel); /* Non-Blocking mode: DMA */ HAL_StatusTypeDef HAL_TIMEx_PWMN_Start_DMA(TIM_HandleTypeDef* htim, uint32_t Channel, uint32_t *pData, uint16_t Length); HAL_StatusTypeDef HAL_TIMEx_PWMN_Stop_DMA(TIM_HandleTypeDef* htim, uint32_t Channel); /** * @} */ /** @addtogroup TIMEx_Exported_Functions_Group4 * @{ */ /* Timer Complementary One Pulse functions **********************************/ /* Blocking mode: Polling */ HAL_StatusTypeDef HAL_TIMEx_OnePulseN_Start(TIM_HandleTypeDef* htim, uint32_t OutputChannel); HAL_StatusTypeDef HAL_TIMEx_OnePulseN_Stop(TIM_HandleTypeDef* htim, uint32_t OutputChannel); /* Non-Blocking mode: Interrupt */ HAL_StatusTypeDef HAL_TIMEx_OnePulseN_Start_IT(TIM_HandleTypeDef* htim, uint32_t OutputChannel); HAL_StatusTypeDef HAL_TIMEx_OnePulseN_Stop_IT(TIM_HandleTypeDef* htim, uint32_t OutputChannel); /** * @} */ /** @addtogroup TIMEx_Exported_Functions_Group5 * @{ */ /* Extension Control functions ************************************************/ HAL_StatusTypeDef HAL_TIMEx_ConfigCommutationEvent(TIM_HandleTypeDef* htim, uint32_t InputTrigger, uint32_t CommutationSource); HAL_StatusTypeDef HAL_TIMEx_ConfigCommutationEvent_IT(TIM_HandleTypeDef* htim, uint32_t InputTrigger, uint32_t CommutationSource); HAL_StatusTypeDef HAL_TIMEx_ConfigCommutationEvent_DMA(TIM_HandleTypeDef* htim, uint32_t InputTrigger, uint32_t CommutationSource); HAL_StatusTypeDef HAL_TIMEx_MasterConfigSynchronization(TIM_HandleTypeDef* htim, TIM_MasterConfigTypeDef * sMasterConfig); HAL_StatusTypeDef HAL_TIMEx_ConfigBreakDeadTime(TIM_HandleTypeDef* htim, TIM_BreakDeadTimeConfigTypeDef *sBreakDeadTimeConfig); HAL_StatusTypeDef HAL_TIMEx_RemapConfig(TIM_HandleTypeDef* htim, uint32_t Remap); /** * @} */ /** @addtogroup TIMEx_Exported_Functions_Group6 * @{ */ /* Extension Callback *********************************************************/ void HAL_TIMEx_CommutationCallback(TIM_HandleTypeDef* htim); void HAL_TIMEx_BreakCallback(TIM_HandleTypeDef* htim); void TIMEx_DMACommutationCplt(DMA_HandleTypeDef *hdma); /** * @} */ /** @addtogroup TIMEx_Exported_Functions_Group7 * @{ */ /* Extension Peripheral State functions **************************************/ HAL_TIM_StateTypeDef HAL_TIMEx_HallSensor_GetState(TIM_HandleTypeDef* htim); /** * @} */ /** * @} */ /* Private types -------------------------------------------------------------*/ /* Private variables ---------------------------------------------------------*/ /* Private constants ---------------------------------------------------------*/ /* Private macros ------------------------------------------------------------*/ /** @defgroup TIMEx_Private_Macros TIM Private Macros * @{ */ #if defined (STM32F446xx) #define IS_TIM_REMAP(TIM_REMAP) (((TIM_REMAP) == TIM_TIM2_TIM8_TRGO)||\ ((TIM_REMAP) == TIM_TIM2_ETH_PTP)||\ ((TIM_REMAP) == TIM_TIM2_USBFS_SOF)||\ ((TIM_REMAP) == TIM_TIM2_USBHS_SOF)||\ ((TIM_REMAP) == TIM_TIM5_GPIO)||\ ((TIM_REMAP) == TIM_TIM5_LSI)||\ ((TIM_REMAP) == TIM_TIM5_LSE)||\ ((TIM_REMAP) == TIM_TIM5_RTC)||\ ((TIM_REMAP) == TIM_TIM11_GPIO)||\ ((TIM_REMAP) == TIM_TIM11_SPDIFRX)||\ ((TIM_REMAP) == TIM_TIM11_HSE)) #else #define IS_TIM_REMAP(TIM_REMAP) (((TIM_REMAP) == TIM_TIM2_TIM8_TRGO)||\ ((TIM_REMAP) == TIM_TIM2_ETH_PTP)||\ ((TIM_REMAP) == TIM_TIM2_USBFS_SOF)||\ ((TIM_REMAP) == TIM_TIM2_USBHS_SOF)||\ ((TIM_REMAP) == TIM_TIM5_GPIO)||\ ((TIM_REMAP) == TIM_TIM5_LSI)||\ ((TIM_REMAP) == TIM_TIM5_LSE)||\ ((TIM_REMAP) == TIM_TIM5_RTC)||\ ((TIM_REMAP) == TIM_TIM11_GPIO)||\ ((TIM_REMAP) == TIM_TIM11_HSE)) #endif /* STM32F446xx */ #if defined(STM32F410Tx) || defined(STM32F410Cx) || defined(STM32F410Rx) #define IS_TIM_SYSTEMBREAKINPUT(BREAKINPUT) (((BREAKINPUT) == TIM_SYSTEMBREAKINPUT_HARDFAULT)||\ ((BREAKINPUT) == TIM_SYSTEMBREAKINPUT_PVD)||\ ((BREAKINPUT) == TIM_SYSTEMBREAKINPUT_HARDFAULT_PVD)) #endif /* STM32F410Tx || STM32F410Cx || STM32F410Rx */ #define IS_TIM_DEADTIME(DEADTIME) ((DEADTIME) <= 0xFF) /** * @} */ /* Private functions ---------------------------------------------------------*/ /** @defgroup TIMEx_Private_Functions TIM Private Functions * @{ */ /** * @} */ /** * @} */ /** * @} */ #ifdef __cplusplus } #endif #endif /* __STM32F4xx_HAL_TIM_EX_H */ /************************ (C) COPYRIGHT STMicroelectronics *****END OF FILE****/ ================================================ FILE: Zelig/mbed/TARGET_NUCLEO_F401RE/stm32f4xx_hal_uart.h ================================================ /** ****************************************************************************** * @file stm32f4xx_hal_uart.h * @author MCD Application Team * @version V1.4.1 * @date 09-October-2015 * @brief Header file of UART HAL module. ****************************************************************************** * @attention * *

© COPYRIGHT(c) 2015 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. * ****************************************************************************** */ /* Define to prevent recursive inclusion -------------------------------------*/ #ifndef __STM32F4xx_HAL_UART_H #define __STM32F4xx_HAL_UART_H #ifdef __cplusplus extern "C" { #endif /* Includes ------------------------------------------------------------------*/ #include "stm32f4xx_hal_def.h" /** @addtogroup STM32F4xx_HAL_Driver * @{ */ /** @addtogroup UART * @{ */ /* Exported types ------------------------------------------------------------*/ /** @defgroup UART_Exported_Types UART Exported Types * @{ */ /** * @brief UART Init Structure definition */ typedef struct { uint32_t BaudRate; /*!< This member configures the UART communication baud rate. The baud rate is computed using the following formula: - IntegerDivider = ((PCLKx) / (8 * (OVR8+1) * (huart->Init.BaudRate))) - FractionalDivider = ((IntegerDivider - ((uint32_t) IntegerDivider)) * 8 * (OVR8+1)) + 0.5 Where OVR8 is the "oversampling by 8 mode" configuration bit in the CR1 register. */ uint32_t WordLength; /*!< Specifies the number of data bits transmitted or received in a frame. This parameter can be a value of @ref UART_Word_Length */ uint32_t StopBits; /*!< Specifies the number of stop bits transmitted. This parameter can be a value of @ref UART_Stop_Bits */ uint32_t Parity; /*!< Specifies the parity mode. This parameter can be a value of @ref UART_Parity @note When parity is enabled, the computed parity is inserted at the MSB position of the transmitted data (9th bit when the word length is set to 9 data bits; 8th bit when the word length is set to 8 data bits). */ uint32_t Mode; /*!< Specifies whether the Receive or Transmit mode is enabled or disabled. This parameter can be a value of @ref UART_Mode */ uint32_t HwFlowCtl; /*!< Specifies whether the hardware flow control mode is enabled or disabled. This parameter can be a value of @ref UART_Hardware_Flow_Control */ uint32_t OverSampling; /*!< Specifies whether the Over sampling 8 is enabled or disabled, to achieve higher speed (up to fPCLK/8). This parameter can be a value of @ref UART_Over_Sampling */ }UART_InitTypeDef; /** * @brief HAL UART State structures definition */ typedef enum { HAL_UART_STATE_RESET = 0x00, /*!< Peripheral is not yet Initialized */ HAL_UART_STATE_READY = 0x01, /*!< Peripheral Initialized and ready for use */ HAL_UART_STATE_BUSY = 0x02, /*!< an internal process is ongoing */ HAL_UART_STATE_BUSY_TX = 0x12, /*!< Data Transmission process is ongoing */ HAL_UART_STATE_BUSY_RX = 0x22, /*!< Data Reception process is ongoing */ HAL_UART_STATE_BUSY_TX_RX = 0x32, /*!< Data Transmission and Reception process is ongoing */ HAL_UART_STATE_TIMEOUT = 0x03, /*!< Timeout state */ HAL_UART_STATE_ERROR = 0x04 /*!< Error */ }HAL_UART_StateTypeDef; /** * @brief UART handle Structure definition */ typedef struct { USART_TypeDef *Instance; /*!< UART registers base address */ UART_InitTypeDef Init; /*!< UART communication parameters */ uint8_t *pTxBuffPtr; /*!< Pointer to UART Tx transfer Buffer */ uint16_t TxXferSize; /*!< UART Tx Transfer size */ uint16_t TxXferCount; /*!< UART Tx Transfer Counter */ uint8_t *pRxBuffPtr; /*!< Pointer to UART Rx transfer Buffer */ uint16_t RxXferSize; /*!< UART Rx Transfer size */ uint16_t RxXferCount; /*!< UART Rx Transfer Counter */ DMA_HandleTypeDef *hdmatx; /*!< UART Tx DMA Handle parameters */ DMA_HandleTypeDef *hdmarx; /*!< UART Rx DMA Handle parameters */ HAL_LockTypeDef Lock; /*!< Locking object */ __IO HAL_UART_StateTypeDef State; /*!< UART communication state */ __IO uint32_t ErrorCode; /*!< UART Error code */ }UART_HandleTypeDef; /** * @} */ /* Exported constants --------------------------------------------------------*/ /** @defgroup UART_Exported_Constants UART Exported constants * @{ */ /** @defgroup UART_Error_Code UART Error Code * @brief UART Error Code * @{ */ #define HAL_UART_ERROR_NONE ((uint32_t)0x00000000) /*!< No error */ #define HAL_UART_ERROR_PE ((uint32_t)0x00000001) /*!< Parity error */ #define HAL_UART_ERROR_NE ((uint32_t)0x00000002) /*!< Noise error */ #define HAL_UART_ERROR_FE ((uint32_t)0x00000004) /*!< Frame error */ #define HAL_UART_ERROR_ORE ((uint32_t)0x00000008) /*!< Overrun error */ #define HAL_UART_ERROR_DMA ((uint32_t)0x00000010) /*!< DMA transfer error */ /** * @} */ /** @defgroup UART_Word_Length UART Word Length * @{ */ #define UART_WORDLENGTH_8B ((uint32_t)0x00000000) #define UART_WORDLENGTH_9B ((uint32_t)USART_CR1_M) /** * @} */ /** @defgroup UART_Stop_Bits UART Number of Stop Bits * @{ */ #define UART_STOPBITS_1 ((uint32_t)0x00000000) #define UART_STOPBITS_2 ((uint32_t)USART_CR2_STOP_1) /** * @} */ /** @defgroup UART_Parity UART Parity * @{ */ #define UART_PARITY_NONE ((uint32_t)0x00000000) #define UART_PARITY_EVEN ((uint32_t)USART_CR1_PCE) #define UART_PARITY_ODD ((uint32_t)(USART_CR1_PCE | USART_CR1_PS)) /** * @} */ /** @defgroup UART_Hardware_Flow_Control UART Hardware Flow Control * @{ */ #define UART_HWCONTROL_NONE ((uint32_t)0x00000000) #define UART_HWCONTROL_RTS ((uint32_t)USART_CR3_RTSE) #define UART_HWCONTROL_CTS ((uint32_t)USART_CR3_CTSE) #define UART_HWCONTROL_RTS_CTS ((uint32_t)(USART_CR3_RTSE | USART_CR3_CTSE)) /** * @} */ /** @defgroup UART_Mode UART Transfer Mode * @{ */ #define UART_MODE_RX ((uint32_t)USART_CR1_RE) #define UART_MODE_TX ((uint32_t)USART_CR1_TE) #define UART_MODE_TX_RX ((uint32_t)(USART_CR1_TE |USART_CR1_RE)) /** * @} */ /** @defgroup UART_State UART State * @{ */ #define UART_STATE_DISABLE ((uint32_t)0x00000000) #define UART_STATE_ENABLE ((uint32_t)USART_CR1_UE) /** * @} */ /** @defgroup UART_Over_Sampling UART Over Sampling * @{ */ #define UART_OVERSAMPLING_16 ((uint32_t)0x00000000) #define UART_OVERSAMPLING_8 ((uint32_t)USART_CR1_OVER8) /** * @} */ /** @defgroup UART_LIN_Break_Detection_Length UART LIN Break Detection Length * @{ */ #define UART_LINBREAKDETECTLENGTH_10B ((uint32_t)0x00000000) #define UART_LINBREAKDETECTLENGTH_11B ((uint32_t)0x00000020) /** * @} */ /** @defgroup UART_WakeUp_functions UART Wakeup Functions * @{ */ #define UART_WAKEUPMETHOD_IDLELINE ((uint32_t)0x00000000) #define UART_WAKEUPMETHOD_ADDRESSMARK ((uint32_t)0x00000800) /** * @} */ /** @defgroup UART_Flags UART FLags * Elements values convention: 0xXXXX * - 0xXXXX : Flag mask in the SR register * @{ */ #define UART_FLAG_CTS ((uint32_t)USART_SR_CTS) #define UART_FLAG_LBD ((uint32_t)USART_SR_LBD) #define UART_FLAG_TXE ((uint32_t)USART_SR_TXE) #define UART_FLAG_TC ((uint32_t)USART_SR_TC) #define UART_FLAG_RXNE ((uint32_t)USART_SR_RXNE) #define UART_FLAG_IDLE ((uint32_t)USART_SR_IDLE) #define UART_FLAG_ORE ((uint32_t)USART_SR_ORE) #define UART_FLAG_NE ((uint32_t)USART_SR_NE) #define UART_FLAG_FE ((uint32_t)USART_SR_FE) #define UART_FLAG_PE ((uint32_t)USART_SR_PE) /** * @} */ /** @defgroup UART_Interrupt_definition UART Interrupt Definitions * Elements values convention: 0xY000XXXX * - XXXX : Interrupt mask (16 bits) in the Y register * - Y : Interrupt source register (2bits) * - 0001: CR1 register * - 0010: CR2 register * - 0011: CR3 register * * @{ */ #define UART_IT_PE ((uint32_t)(UART_CR1_REG_INDEX << 28 | USART_CR1_PEIE)) #define UART_IT_TXE ((uint32_t)(UART_CR1_REG_INDEX << 28 | USART_CR1_TXEIE)) #define UART_IT_TC ((uint32_t)(UART_CR1_REG_INDEX << 28 | USART_CR1_TCIE)) #define UART_IT_RXNE ((uint32_t)(UART_CR1_REG_INDEX << 28 | USART_CR1_RXNEIE)) #define UART_IT_IDLE ((uint32_t)(UART_CR1_REG_INDEX << 28 | USART_CR1_IDLEIE)) #define UART_IT_LBD ((uint32_t)(UART_CR2_REG_INDEX << 28 | USART_CR2_LBDIE)) #define UART_IT_CTS ((uint32_t)(UART_CR3_REG_INDEX << 28 | USART_CR3_CTSIE)) #define UART_IT_ERR ((uint32_t)(UART_CR3_REG_INDEX << 28 | USART_CR3_EIE)) /** * @} */ /** * @} */ /* Exported macro ------------------------------------------------------------*/ /** @defgroup UART_Exported_Macros UART Exported Macros * @{ */ /** @brief Reset UART handle state * @param __HANDLE__: specifies the UART Handle. * This parameter can be UARTx where x: 1, 2, 3, 4, 5, 6, 7 or 8 to select the USART or * UART peripheral. * @retval None */ #define __HAL_UART_RESET_HANDLE_STATE(__HANDLE__) ((__HANDLE__)->State = HAL_UART_STATE_RESET) /** @brief Flushes the UART DR register * @param __HANDLE__: specifies the UART Handle. */ #define __HAL_UART_FLUSH_DRREGISTER(__HANDLE__) ((__HANDLE__)->Instance->DR) /** @brief Checks whether the specified UART flag is set or not. * @param __HANDLE__: specifies the UART Handle. * This parameter can be UARTx where x: 1, 2, 3, 4, 5, 6, 7 or 8 to select the USART or * UART peripheral. * @param __FLAG__: specifies the flag to check. * This parameter can be one of the following values: * @arg UART_FLAG_CTS: CTS Change flag (not available for UART4 and UART5) * @arg UART_FLAG_LBD: LIN Break detection flag * @arg UART_FLAG_TXE: Transmit data register empty flag * @arg UART_FLAG_TC: Transmission Complete flag * @arg UART_FLAG_RXNE: Receive data register not empty flag * @arg UART_FLAG_IDLE: Idle Line detection flag * @arg UART_FLAG_ORE: Overrun Error flag * @arg UART_FLAG_NE: Noise Error flag * @arg UART_FLAG_FE: Framing Error flag * @arg UART_FLAG_PE: Parity Error flag * @retval The new state of __FLAG__ (TRUE or FALSE). */ #define __HAL_UART_GET_FLAG(__HANDLE__, __FLAG__) (((__HANDLE__)->Instance->SR & (__FLAG__)) == (__FLAG__)) /** @brief Clears the specified UART pending flag. * @param __HANDLE__: specifies the UART Handle. * This parameter can be UARTx where x: 1, 2, 3, 4, 5, 6, 7 or 8 to select the USART or * UART peripheral. * @param __FLAG__: specifies the flag to check. * This parameter can be any combination of the following values: * @arg UART_FLAG_CTS: CTS Change flag (not available for UART4 and UART5). * @arg UART_FLAG_LBD: LIN Break detection flag. * @arg UART_FLAG_TC: Transmission Complete flag. * @arg UART_FLAG_RXNE: Receive data register not empty flag. * * @note PE (Parity error), FE (Framing error), NE (Noise error), ORE (Overrun * error) and IDLE (Idle line detected) flags are cleared by software * sequence: a read operation to USART_SR register followed by a read * operation to USART_DR register. * @note RXNE flag can be also cleared by a read to the USART_DR register. * @note TC flag can be also cleared by software sequence: a read operation to * USART_SR register followed by a write operation to USART_DR register. * @note TXE flag is cleared only by a write to the USART_DR register. * * @retval None */ #define __HAL_UART_CLEAR_FLAG(__HANDLE__, __FLAG__) ((__HANDLE__)->Instance->SR = ~(__FLAG__)) /** @brief Clear the UART PE pending flag. * @param __HANDLE__: specifies the UART Handle. * This parameter can be UARTx where x: 1, 2, 3, 4, 5, 6, 7 or 8 to select the USART or * UART peripheral. * @retval None */ #define __HAL_UART_CLEAR_PEFLAG(__HANDLE__) \ do{ \ __IO uint32_t tmpreg; \ tmpreg = (__HANDLE__)->Instance->SR; \ tmpreg = (__HANDLE__)->Instance->DR; \ UNUSED(tmpreg); \ } while(0) /** @brief Clear the UART FE pending flag. * @param __HANDLE__: specifies the UART Handle. * This parameter can be UARTx where x: 1, 2, 3, 4, 5, 6, 7 or 8 to select the USART or * UART peripheral. * @retval None */ #define __HAL_UART_CLEAR_FEFLAG(__HANDLE__) __HAL_UART_CLEAR_PEFLAG(__HANDLE__) /** @brief Clear the UART NE pending flag. * @param __HANDLE__: specifies the UART Handle. * This parameter can be UARTx where x: 1, 2, 3, 4, 5, 6, 7 or 8 to select the USART or * UART peripheral. * @retval None */ #define __HAL_UART_CLEAR_NEFLAG(__HANDLE__) __HAL_UART_CLEAR_PEFLAG(__HANDLE__) /** @brief Clear the UART ORE pending flag. * @param __HANDLE__: specifies the UART Handle. * This parameter can be UARTx where x: 1, 2, 3, 4, 5, 6, 7 or 8 to select the USART or * UART peripheral. * @retval None */ #define __HAL_UART_CLEAR_OREFLAG(__HANDLE__) __HAL_UART_CLEAR_PEFLAG(__HANDLE__) /** @brief Clear the UART IDLE pending flag. * @param __HANDLE__: specifies the UART Handle. * This parameter can be UARTx where x: 1, 2, 3, 4, 5, 6, 7 or 8 to select the USART or * UART peripheral. * @retval None */ #define __HAL_UART_CLEAR_IDLEFLAG(__HANDLE__) __HAL_UART_CLEAR_PEFLAG(__HANDLE__) /** @brief Enable the specified UART interrupt. * @param __HANDLE__: specifies the UART Handle. * This parameter can be UARTx where x: 1, 2, 3, 4, 5, 6, 7 or 8 to select the USART or * UART peripheral. * @param __INTERRUPT__: specifies the UART interrupt source to enable. * This parameter can be one of the following values: * @arg UART_IT_CTS: CTS change interrupt * @arg UART_IT_LBD: LIN Break detection interrupt * @arg UART_IT_TXE: Transmit Data Register empty interrupt * @arg UART_IT_TC: Transmission complete interrupt * @arg UART_IT_RXNE: Receive Data register not empty interrupt * @arg UART_IT_IDLE: Idle line detection interrupt * @arg UART_IT_PE: Parity Error interrupt * @arg UART_IT_ERR: Error interrupt(Frame error, noise error, overrun error) * @retval None */ #define UART_IT_MASK ((uint32_t)0x0000FFFF) #define __HAL_UART_ENABLE_IT(__HANDLE__, __INTERRUPT__) ((((__INTERRUPT__) >> 28) == 1)? ((__HANDLE__)->Instance->CR1 |= ((__INTERRUPT__) & UART_IT_MASK)): \ (((__INTERRUPT__) >> 28) == 2)? ((__HANDLE__)->Instance->CR2 |= ((__INTERRUPT__) & UART_IT_MASK)): \ ((__HANDLE__)->Instance->CR3 |= ((__INTERRUPT__) & UART_IT_MASK))) /** @brief Disable the specified UART interrupt. * @param __HANDLE__: specifies the UART Handle. * This parameter can be UARTx where x: 1, 2, 3, 4, 5, 6, 7 or 8 to select the USART or * UART peripheral. * @param __INTERRUPT__: specifies the UART interrupt source to disable. * This parameter can be one of the following values: * @arg UART_IT_CTS: CTS change interrupt * @arg UART_IT_LBD: LIN Break detection interrupt * @arg UART_IT_TXE: Transmit Data Register empty interrupt * @arg UART_IT_TC: Transmission complete interrupt * @arg UART_IT_RXNE: Receive Data register not empty interrupt * @arg UART_IT_IDLE: Idle line detection interrupt * @arg UART_IT_PE: Parity Error interrupt * @arg UART_IT_ERR: Error interrupt(Frame error, noise error, overrun error) * @retval None */ #define __HAL_UART_DISABLE_IT(__HANDLE__, __INTERRUPT__) ((((__INTERRUPT__) >> 28) == 1)? ((__HANDLE__)->Instance->CR1 &= ~((__INTERRUPT__) & UART_IT_MASK)): \ (((__INTERRUPT__) >> 28) == 2)? ((__HANDLE__)->Instance->CR2 &= ~((__INTERRUPT__) & UART_IT_MASK)): \ ((__HANDLE__)->Instance->CR3 &= ~ ((__INTERRUPT__) & UART_IT_MASK))) /** @brief Checks whether the specified UART interrupt has occurred or not. * @param __HANDLE__: specifies the UART Handle. * This parameter can be UARTx where x: 1, 2, 3, 4, 5, 6, 7 or 8 to select the USART or * UART peripheral. * @param __IT__: specifies the UART interrupt source to check. * This parameter can be one of the following values: * @arg UART_IT_CTS: CTS change interrupt (not available for UART4 and UART5) * @arg UART_IT_LBD: LIN Break detection interrupt * @arg UART_IT_TXE: Transmit Data Register empty interrupt * @arg UART_IT_TC: Transmission complete interrupt * @arg UART_IT_RXNE: Receive Data register not empty interrupt * @arg UART_IT_IDLE: Idle line detection interrupt * @arg USART_IT_ERR: Error interrupt * @retval The new state of __IT__ (TRUE or FALSE). */ #define __HAL_UART_GET_IT_SOURCE(__HANDLE__, __IT__) (((((__IT__) >> 28) == 1)? (__HANDLE__)->Instance->CR1:(((((uint32_t)(__IT__)) >> 28) == 2)? \ (__HANDLE__)->Instance->CR2 : (__HANDLE__)->Instance->CR3)) & (((uint32_t)(__IT__)) & UART_IT_MASK)) /** @brief Enable CTS flow control * This macro allows to enable CTS hardware flow control for a given UART instance, * without need to call HAL_UART_Init() function. * As involving direct access to UART registers, usage of this macro should be fully endorsed by user. * @note As macro is expected to be used for modifying CTS Hw flow control feature activation, without need * for USART instance Deinit/Init, following conditions for macro call should be fulfilled : * - UART instance should have already been initialised (through call of HAL_UART_Init() ) * - macro could only be called when corresponding UART instance is disabled (i.e __HAL_UART_DISABLE(__HANDLE__)) * and should be followed by an Enable macro (i.e __HAL_UART_ENABLE(__HANDLE__)). * @param __HANDLE__: specifies the UART Handle. * The Handle Instance can be USART1, USART2 or LPUART. * @retval None */ #define __HAL_UART_HWCONTROL_CTS_ENABLE(__HANDLE__) \ do{ \ SET_BIT((__HANDLE__)->Instance->CR3, USART_CR3_CTSE); \ (__HANDLE__)->Init.HwFlowCtl |= USART_CR3_CTSE; \ } while(0) /** @brief Disable CTS flow control * This macro allows to disable CTS hardware flow control for a given UART instance, * without need to call HAL_UART_Init() function. * As involving direct access to UART registers, usage of this macro should be fully endorsed by user. * @note As macro is expected to be used for modifying CTS Hw flow control feature activation, without need * for USART instance Deinit/Init, following conditions for macro call should be fulfilled : * - UART instance should have already been initialised (through call of HAL_UART_Init() ) * - macro could only be called when corresponding UART instance is disabled (i.e __HAL_UART_DISABLE(__HANDLE__)) * and should be followed by an Enable macro (i.e __HAL_UART_ENABLE(__HANDLE__)). * @param __HANDLE__: specifies the UART Handle. * The Handle Instance can be USART1, USART2 or LPUART. * @retval None */ #define __HAL_UART_HWCONTROL_CTS_DISABLE(__HANDLE__) \ do{ \ CLEAR_BIT((__HANDLE__)->Instance->CR3, USART_CR3_CTSE); \ (__HANDLE__)->Init.HwFlowCtl &= ~(USART_CR3_CTSE); \ } while(0) /** @brief Enable RTS flow control * This macro allows to enable RTS hardware flow control for a given UART instance, * without need to call HAL_UART_Init() function. * As involving direct access to UART registers, usage of this macro should be fully endorsed by user. * @note As macro is expected to be used for modifying RTS Hw flow control feature activation, without need * for USART instance Deinit/Init, following conditions for macro call should be fulfilled : * - UART instance should have already been initialised (through call of HAL_UART_Init() ) * - macro could only be called when corresponding UART instance is disabled (i.e __HAL_UART_DISABLE(__HANDLE__)) * and should be followed by an Enable macro (i.e __HAL_UART_ENABLE(__HANDLE__)). * @param __HANDLE__: specifies the UART Handle. * The Handle Instance can be USART1, USART2 or LPUART. * @retval None */ #define __HAL_UART_HWCONTROL_RTS_ENABLE(__HANDLE__) \ do{ \ SET_BIT((__HANDLE__)->Instance->CR3, USART_CR3_RTSE); \ (__HANDLE__)->Init.HwFlowCtl |= USART_CR3_RTSE; \ } while(0) /** @brief Disable RTS flow control * This macro allows to disable RTS hardware flow control for a given UART instance, * without need to call HAL_UART_Init() function. * As involving direct access to UART registers, usage of this macro should be fully endorsed by user. * @note As macro is expected to be used for modifying RTS Hw flow control feature activation, without need * for USART instance Deinit/Init, following conditions for macro call should be fulfilled : * - UART instance should have already been initialised (through call of HAL_UART_Init() ) * - macro could only be called when corresponding UART instance is disabled (i.e __HAL_UART_DISABLE(__HANDLE__)) * and should be followed by an Enable macro (i.e __HAL_UART_ENABLE(__HANDLE__)). * @param __HANDLE__: specifies the UART Handle. * The Handle Instance can be USART1, USART2 or LPUART. * @retval None */ #define __HAL_UART_HWCONTROL_RTS_DISABLE(__HANDLE__) \ do{ \ CLEAR_BIT((__HANDLE__)->Instance->CR3, USART_CR3_RTSE);\ (__HANDLE__)->Init.HwFlowCtl &= ~(USART_CR3_RTSE); \ } while(0) /** @brief macros to enables the UART's one bit sample method * @param __HANDLE__: specifies the UART Handle. * @retval None */ #define __HAL_UART_ONE_BIT_SAMPLE_ENABLE(__HANDLE__) ((__HANDLE__)->Instance->CR3|= USART_CR3_ONEBIT) /** @brief macros to disables the UART's one bit sample method * @param __HANDLE__: specifies the UART Handle. * @retval None */ #define __HAL_UART_ONE_BIT_SAMPLE_DISABLE(__HANDLE__) ((__HANDLE__)->Instance->CR3 &= (uint16_t)~((uint16_t)USART_CR3_ONEBIT)) /** @brief Enable UART * @param __HANDLE__: specifies the UART Handle. * @retval None */ #define __HAL_UART_ENABLE(__HANDLE__) ((__HANDLE__)->Instance->CR1 |= USART_CR1_UE) /** @brief Disable UART * @param __HANDLE__: specifies the UART Handle. * @retval None */ #define __HAL_UART_DISABLE(__HANDLE__) ((__HANDLE__)->Instance->CR1 &= ~USART_CR1_UE) /** * @} */ /* Exported functions --------------------------------------------------------*/ /** @addtogroup UART_Exported_Functions * @{ */ /** @addtogroup UART_Exported_Functions_Group1 * @{ */ /* Initialization/de-initialization functions **********************************/ HAL_StatusTypeDef HAL_UART_Init(UART_HandleTypeDef *huart); HAL_StatusTypeDef HAL_HalfDuplex_Init(UART_HandleTypeDef *huart); HAL_StatusTypeDef HAL_LIN_Init(UART_HandleTypeDef *huart, uint32_t BreakDetectLength); HAL_StatusTypeDef HAL_MultiProcessor_Init(UART_HandleTypeDef *huart, uint8_t Address, uint32_t WakeUpMethod); HAL_StatusTypeDef HAL_UART_DeInit (UART_HandleTypeDef *huart); void HAL_UART_MspInit(UART_HandleTypeDef *huart); void HAL_UART_MspDeInit(UART_HandleTypeDef *huart); /** * @} */ /** @addtogroup UART_Exported_Functions_Group2 * @{ */ /* IO operation functions *******************************************************/ HAL_StatusTypeDef HAL_UART_Transmit(UART_HandleTypeDef *huart, uint8_t *pData, uint16_t Size, uint32_t Timeout); HAL_StatusTypeDef HAL_UART_Receive(UART_HandleTypeDef *huart, uint8_t *pData, uint16_t Size, uint32_t Timeout); HAL_StatusTypeDef HAL_UART_Transmit_IT(UART_HandleTypeDef *huart, uint8_t *pData, uint16_t Size); HAL_StatusTypeDef HAL_UART_Receive_IT(UART_HandleTypeDef *huart, uint8_t *pData, uint16_t Size); HAL_StatusTypeDef HAL_UART_Transmit_DMA(UART_HandleTypeDef *huart, uint8_t *pData, uint16_t Size); HAL_StatusTypeDef HAL_UART_Receive_DMA(UART_HandleTypeDef *huart, uint8_t *pData, uint16_t Size); HAL_StatusTypeDef HAL_UART_DMAPause(UART_HandleTypeDef *huart); HAL_StatusTypeDef HAL_UART_DMAResume(UART_HandleTypeDef *huart); HAL_StatusTypeDef HAL_UART_DMAStop(UART_HandleTypeDef *huart); void HAL_UART_IRQHandler(UART_HandleTypeDef *huart); void HAL_UART_TxCpltCallback(UART_HandleTypeDef *huart); void HAL_UART_TxHalfCpltCallback(UART_HandleTypeDef *huart); void HAL_UART_RxCpltCallback(UART_HandleTypeDef *huart); void HAL_UART_RxHalfCpltCallback(UART_HandleTypeDef *huart); void HAL_UART_ErrorCallback(UART_HandleTypeDef *huart); /** * @} */ /** @addtogroup UART_Exported_Functions_Group3 * @{ */ /* Peripheral Control functions ************************************************/ HAL_StatusTypeDef HAL_LIN_SendBreak(UART_HandleTypeDef *huart); HAL_StatusTypeDef HAL_MultiProcessor_EnterMuteMode(UART_HandleTypeDef *huart); HAL_StatusTypeDef HAL_MultiProcessor_ExitMuteMode(UART_HandleTypeDef *huart); HAL_StatusTypeDef HAL_HalfDuplex_EnableTransmitter(UART_HandleTypeDef *huart); HAL_StatusTypeDef HAL_HalfDuplex_EnableReceiver(UART_HandleTypeDef *huart); /** * @} */ /** @addtogroup UART_Exported_Functions_Group4 * @{ */ /* Peripheral State functions **************************************************/ HAL_UART_StateTypeDef HAL_UART_GetState(UART_HandleTypeDef *huart); uint32_t HAL_UART_GetError(UART_HandleTypeDef *huart); /** * @} */ /** * @} */ /* Private types -------------------------------------------------------------*/ /* Private variables ---------------------------------------------------------*/ /* Private constants ---------------------------------------------------------*/ /** @defgroup UART_Private_Constants UART Private Constants * @{ */ /** @brief UART interruptions flag mask * */ #define UART_CR1_REG_INDEX 1 #define UART_CR2_REG_INDEX 2 #define UART_CR3_REG_INDEX 3 /** * @} */ /* Private macros ------------------------------------------------------------*/ /** @defgroup UART_Private_Macros UART Private Macros * @{ */ #define IS_UART_WORD_LENGTH(LENGTH) (((LENGTH) == UART_WORDLENGTH_8B) || \ ((LENGTH) == UART_WORDLENGTH_9B)) #define IS_UART_LIN_WORD_LENGTH(LENGTH) (((LENGTH) == UART_WORDLENGTH_8B)) #define IS_UART_STOPBITS(STOPBITS) (((STOPBITS) == UART_STOPBITS_1) || \ ((STOPBITS) == UART_STOPBITS_2)) #define IS_UART_PARITY(PARITY) (((PARITY) == UART_PARITY_NONE) || \ ((PARITY) == UART_PARITY_EVEN) || \ ((PARITY) == UART_PARITY_ODD)) #define IS_UART_HARDWARE_FLOW_CONTROL(CONTROL)\ (((CONTROL) == UART_HWCONTROL_NONE) || \ ((CONTROL) == UART_HWCONTROL_RTS) || \ ((CONTROL) == UART_HWCONTROL_CTS) || \ ((CONTROL) == UART_HWCONTROL_RTS_CTS)) #define IS_UART_MODE(MODE) ((((MODE) & (uint32_t)0x0000FFF3) == 0x00) && ((MODE) != (uint32_t)0x000000)) #define IS_UART_STATE(STATE) (((STATE) == UART_STATE_DISABLE) || \ ((STATE) == UART_STATE_ENABLE)) #define IS_UART_OVERSAMPLING(SAMPLING) (((SAMPLING) == UART_OVERSAMPLING_16) || \ ((SAMPLING) == UART_OVERSAMPLING_8)) #define IS_UART_LIN_OVERSAMPLING(SAMPLING) (((SAMPLING) == UART_OVERSAMPLING_16)) #define IS_UART_LIN_BREAK_DETECT_LENGTH(LENGTH) (((LENGTH) == UART_LINBREAKDETECTLENGTH_10B) || \ ((LENGTH) == UART_LINBREAKDETECTLENGTH_11B)) #define IS_UART_WAKEUPMETHOD(WAKEUP) (((WAKEUP) == UART_WAKEUPMETHOD_IDLELINE) || \ ((WAKEUP) == UART_WAKEUPMETHOD_ADDRESSMARK)) #define IS_UART_BAUDRATE(BAUDRATE) ((BAUDRATE) < 10500001) #define IS_UART_ADDRESS(ADDRESS) ((ADDRESS) <= 0xF) #define UART_DIV_SAMPLING16(_PCLK_, _BAUD_) (((_PCLK_)*25)/(4*(_BAUD_))) #define UART_DIVMANT_SAMPLING16(_PCLK_, _BAUD_) (UART_DIV_SAMPLING16((_PCLK_), (_BAUD_))/100) #define UART_DIVFRAQ_SAMPLING16(_PCLK_, _BAUD_) (((UART_DIV_SAMPLING16((_PCLK_), (_BAUD_)) - (UART_DIVMANT_SAMPLING16((_PCLK_), (_BAUD_)) * 100)) * 16 + 50) / 100) #define UART_BRR_SAMPLING16(_PCLK_, _BAUD_) ((UART_DIVMANT_SAMPLING16((_PCLK_), (_BAUD_)) << 4)|(UART_DIVFRAQ_SAMPLING16((_PCLK_), (_BAUD_)) & 0x0F)) #define UART_DIV_SAMPLING8(_PCLK_, _BAUD_) (((_PCLK_)*25)/(2*(_BAUD_))) #define UART_DIVMANT_SAMPLING8(_PCLK_, _BAUD_) (UART_DIV_SAMPLING8((_PCLK_), (_BAUD_))/100) #define UART_DIVFRAQ_SAMPLING8(_PCLK_, _BAUD_) (((UART_DIV_SAMPLING8((_PCLK_), (_BAUD_)) - (UART_DIVMANT_SAMPLING8((_PCLK_), (_BAUD_)) * 100)) * 16 + 50) / 100) #define UART_BRR_SAMPLING8(_PCLK_, _BAUD_) ((UART_DIVMANT_SAMPLING8((_PCLK_), (_BAUD_)) << 4)|(UART_DIVFRAQ_SAMPLING8((_PCLK_), (_BAUD_)) & 0x0F)) /** * @} */ /* Private functions ---------------------------------------------------------*/ /** @defgroup UART_Private_Functions UART Private Functions * @{ */ /** * @} */ /** * @} */ /** * @} */ #ifdef __cplusplus } #endif #endif /* __STM32F4xx_HAL_UART_H */ /************************ (C) COPYRIGHT STMicroelectronics *****END OF FILE****/ ================================================ FILE: Zelig/mbed/TARGET_NUCLEO_F401RE/stm32f4xx_hal_usart.h ================================================ /** ****************************************************************************** * @file stm32f4xx_hal_usart.h * @author MCD Application Team * @version V1.4.1 * @date 09-October-2015 * @brief Header file of USART HAL module. ****************************************************************************** * @attention * *

© COPYRIGHT(c) 2015 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. * ****************************************************************************** */ /* Define to prevent recursive inclusion -------------------------------------*/ #ifndef __STM32F4xx_HAL_USART_H #define __STM32F4xx_HAL_USART_H #ifdef __cplusplus extern "C" { #endif /* Includes ------------------------------------------------------------------*/ #include "stm32f4xx_hal_def.h" /** @addtogroup STM32F4xx_HAL_Driver * @{ */ /** @addtogroup USART * @{ */ /* Exported types ------------------------------------------------------------*/ /** @defgroup USART_Exported_Types USART Exported Types * @{ */ /** * @brief USART Init Structure definition */ typedef struct { uint32_t BaudRate; /*!< This member configures the Usart communication baud rate. The baud rate is computed using the following formula: - IntegerDivider = ((PCLKx) / (8 * (husart->Init.BaudRate))) - FractionalDivider = ((IntegerDivider - ((uint32_t) IntegerDivider)) * 8) + 0.5 */ uint32_t WordLength; /*!< Specifies the number of data bits transmitted or received in a frame. This parameter can be a value of @ref USART_Word_Length */ uint32_t StopBits; /*!< Specifies the number of stop bits transmitted. This parameter can be a value of @ref USART_Stop_Bits */ uint32_t Parity; /*!< Specifies the parity mode. This parameter can be a value of @ref USART_Parity @note When parity is enabled, the computed parity is inserted at the MSB position of the transmitted data (9th bit when the word length is set to 9 data bits; 8th bit when the word length is set to 8 data bits). */ uint32_t Mode; /*!< Specifies whether the Receive or Transmit mode is enabled or disabled. This parameter can be a value of @ref USART_Mode */ uint32_t CLKPolarity; /*!< Specifies the steady state of the serial clock. This parameter can be a value of @ref USART_Clock_Polarity */ uint32_t CLKPhase; /*!< Specifies the clock transition on which the bit capture is made. This parameter can be a value of @ref USART_Clock_Phase */ uint32_t CLKLastBit; /*!< Specifies whether the clock pulse corresponding to the last transmitted data bit (MSB) has to be output on the SCLK pin in synchronous mode. This parameter can be a value of @ref USART_Last_Bit */ }USART_InitTypeDef; /** * @brief HAL State structures definition */ typedef enum { HAL_USART_STATE_RESET = 0x00, /*!< Peripheral is not yet Initialized */ HAL_USART_STATE_READY = 0x01, /*!< Peripheral Initialized and ready for use */ HAL_USART_STATE_BUSY = 0x02, /*!< an internal process is ongoing */ HAL_USART_STATE_BUSY_TX = 0x12, /*!< Data Transmission process is ongoing */ HAL_USART_STATE_BUSY_RX = 0x22, /*!< Data Reception process is ongoing */ HAL_USART_STATE_BUSY_TX_RX = 0x32, /*!< Data Transmission Reception process is ongoing */ HAL_USART_STATE_TIMEOUT = 0x03, /*!< Timeout state */ HAL_USART_STATE_ERROR = 0x04 /*!< Error */ }HAL_USART_StateTypeDef; /** * @brief USART handle Structure definition */ typedef struct { USART_TypeDef *Instance; /* USART registers base address */ USART_InitTypeDef Init; /* Usart communication parameters */ uint8_t *pTxBuffPtr; /* Pointer to Usart Tx transfer Buffer */ uint16_t TxXferSize; /* Usart Tx Transfer size */ __IO uint16_t TxXferCount; /* Usart Tx Transfer Counter */ uint8_t *pRxBuffPtr; /* Pointer to Usart Rx transfer Buffer */ uint16_t RxXferSize; /* Usart Rx Transfer size */ __IO uint16_t RxXferCount; /* Usart Rx Transfer Counter */ DMA_HandleTypeDef *hdmatx; /* Usart Tx DMA Handle parameters */ DMA_HandleTypeDef *hdmarx; /* Usart Rx DMA Handle parameters */ HAL_LockTypeDef Lock; /* Locking object */ __IO HAL_USART_StateTypeDef State; /* Usart communication state */ __IO uint32_t ErrorCode; /* USART Error code */ }USART_HandleTypeDef; /** * @} */ /* Exported constants --------------------------------------------------------*/ /** @defgroup USART_Exported_Constants USART Exported Constants * @{ */ /** @defgroup USART_Error_Code USART Error Code * @brief USART Error Code * @{ */ #define HAL_USART_ERROR_NONE ((uint32_t)0x00000000) /*!< No error */ #define HAL_USART_ERROR_PE ((uint32_t)0x00000001) /*!< Parity error */ #define HAL_USART_ERROR_NE ((uint32_t)0x00000002) /*!< Noise error */ #define HAL_USART_ERROR_FE ((uint32_t)0x00000004) /*!< Frame error */ #define HAL_USART_ERROR_ORE ((uint32_t)0x00000008) /*!< Overrun error */ #define HAL_USART_ERROR_DMA ((uint32_t)0x00000010) /*!< DMA transfer error */ /** * @} */ /** @defgroup USART_Word_Length USART Word Length * @{ */ #define USART_WORDLENGTH_8B ((uint32_t)0x00000000) #define USART_WORDLENGTH_9B ((uint32_t)USART_CR1_M) /** * @} */ /** @defgroup USART_Stop_Bits USART Number of Stop Bits * @{ */ #define USART_STOPBITS_1 ((uint32_t)0x00000000) #define USART_STOPBITS_0_5 ((uint32_t)USART_CR2_STOP_0) #define USART_STOPBITS_2 ((uint32_t)USART_CR2_STOP_1) #define USART_STOPBITS_1_5 ((uint32_t)(USART_CR2_STOP_0 | USART_CR2_STOP_1)) /** * @} */ /** @defgroup USART_Parity USART Parity * @{ */ #define USART_PARITY_NONE ((uint32_t)0x00000000) #define USART_PARITY_EVEN ((uint32_t)USART_CR1_PCE) #define USART_PARITY_ODD ((uint32_t)(USART_CR1_PCE | USART_CR1_PS)) /** * @} */ /** @defgroup USART_Mode USART Mode * @{ */ #define USART_MODE_RX ((uint32_t)USART_CR1_RE) #define USART_MODE_TX ((uint32_t)USART_CR1_TE) #define USART_MODE_TX_RX ((uint32_t)(USART_CR1_TE |USART_CR1_RE)) /** * @} */ /** @defgroup USART_Clock USART Clock * @{ */ #define USART_CLOCK_DISABLE ((uint32_t)0x00000000) #define USART_CLOCK_ENABLE ((uint32_t)USART_CR2_CLKEN) /** * @} */ /** @defgroup USART_Clock_Polarity USART Clock Polarity * @{ */ #define USART_POLARITY_LOW ((uint32_t)0x00000000) #define USART_POLARITY_HIGH ((uint32_t)USART_CR2_CPOL) /** * @} */ /** @defgroup USART_Clock_Phase USART Clock Phase * @{ */ #define USART_PHASE_1EDGE ((uint32_t)0x00000000) #define USART_PHASE_2EDGE ((uint32_t)USART_CR2_CPHA) /** * @} */ /** @defgroup USART_Last_Bit USART Last Bit * @{ */ #define USART_LASTBIT_DISABLE ((uint32_t)0x00000000) #define USART_LASTBIT_ENABLE ((uint32_t)USART_CR2_LBCL) /** * @} */ /** @defgroup USART_NACK_State USART NACK State * @{ */ #define USART_NACK_ENABLE ((uint32_t)USART_CR3_NACK) #define USART_NACK_DISABLE ((uint32_t)0x00000000) /** * @} */ /** @defgroup USART_Flags USART Flags * Elements values convention: 0xXXXX * - 0xXXXX : Flag mask in the SR register * @{ */ #define USART_FLAG_TXE ((uint32_t)0x00000080) #define USART_FLAG_TC ((uint32_t)0x00000040) #define USART_FLAG_RXNE ((uint32_t)0x00000020) #define USART_FLAG_IDLE ((uint32_t)0x00000010) #define USART_FLAG_ORE ((uint32_t)0x00000008) #define USART_FLAG_NE ((uint32_t)0x00000004) #define USART_FLAG_FE ((uint32_t)0x00000002) #define USART_FLAG_PE ((uint32_t)0x00000001) /** * @} */ /** @defgroup USART_Interrupt_definition USART Interrupts Definition * Elements values convention: 0xY000XXXX * - XXXX : Interrupt mask in the XX register * - Y : Interrupt source register (2bits) * - 01: CR1 register * - 10: CR2 register * - 11: CR3 register * * @{ */ #define USART_IT_PE ((uint32_t)(USART_CR1_REG_INDEX << 28 | USART_CR1_PEIE)) #define USART_IT_TXE ((uint32_t)(USART_CR1_REG_INDEX << 28 | USART_CR1_TXEIE)) #define USART_IT_TC ((uint32_t)(USART_CR1_REG_INDEX << 28 | USART_CR1_TCIE)) #define USART_IT_RXNE ((uint32_t)(USART_CR1_REG_INDEX << 28 | USART_CR1_RXNEIE)) #define USART_IT_IDLE ((uint32_t)(USART_CR1_REG_INDEX << 28 | USART_CR1_IDLEIE)) #define USART_IT_LBD ((uint32_t)(USART_CR2_REG_INDEX << 28 | USART_CR2_LBDIE)) #define USART_IT_CTS ((uint32_t)(USART_CR3_REG_INDEX << 28 | USART_CR3_CTSIE)) #define USART_IT_ERR ((uint32_t)(USART_CR3_REG_INDEX << 28 | USART_CR3_EIE)) /** * @} */ /** * @} */ /* Exported macro ------------------------------------------------------------*/ /** @defgroup USART_Exported_Macros USART Exported Macros * @{ */ /** @brief Reset USART handle state * @param __HANDLE__: specifies the USART Handle. * This parameter can be USARTx where x: 1, 2, 3 or 6 to select the USART peripheral. * @retval None */ #define __HAL_USART_RESET_HANDLE_STATE(__HANDLE__) ((__HANDLE__)->State = HAL_USART_STATE_RESET) /** @brief Checks whether the specified Smartcard flag is set or not. * @param __HANDLE__: specifies the USART Handle. * This parameter can be USARTx where x: 1, 2, 3 or 6 to select the USART peripheral. * @param __FLAG__: specifies the flag to check. * This parameter can be one of the following values: * @arg USART_FLAG_TXE: Transmit data register empty flag * @arg USART_FLAG_TC: Transmission Complete flag * @arg USART_FLAG_RXNE: Receive data register not empty flag * @arg USART_FLAG_IDLE: Idle Line detection flag * @arg USART_FLAG_ORE: Overrun Error flag * @arg USART_FLAG_NE: Noise Error flag * @arg USART_FLAG_FE: Framing Error flag * @arg USART_FLAG_PE: Parity Error flag * @retval The new state of __FLAG__ (TRUE or FALSE). */ #define __HAL_USART_GET_FLAG(__HANDLE__, __FLAG__) (((__HANDLE__)->Instance->SR & (__FLAG__)) == (__FLAG__)) /** @brief Clears the specified Smartcard pending flags. * @param __HANDLE__: specifies the USART Handle. * This parameter can be USARTx where x: 1, 2, 3 or 6 to select the USART peripheral. * @param __FLAG__: specifies the flag to check. * This parameter can be any combination of the following values: * @arg USART_FLAG_TC: Transmission Complete flag. * @arg USART_FLAG_RXNE: Receive data register not empty flag. * * @note PE (Parity error), FE (Framing error), NE (Noise error), ORE (Overrun * error) and IDLE (Idle line detected) flags are cleared by software * sequence: a read operation to USART_SR register followed by a read * operation to USART_DR register. * @note RXNE flag can be also cleared by a read to the USART_DR register. * @note TC flag can be also cleared by software sequence: a read operation to * USART_SR register followed by a write operation to USART_DR register. * @note TXE flag is cleared only by a write to the USART_DR register. * * @retval None */ #define __HAL_USART_CLEAR_FLAG(__HANDLE__, __FLAG__) ((__HANDLE__)->Instance->SR = ~(__FLAG__)) /** @brief Clear the USART PE pending flag. * @param __HANDLE__: specifies the USART Handle. * This parameter can be USARTx where x: 1, 2, 3 or 6 to select the USART peripheral. * @retval None */ #define __HAL_USART_CLEAR_PEFLAG(__HANDLE__) \ do{ \ __IO uint32_t tmpreg; \ tmpreg = (__HANDLE__)->Instance->SR; \ tmpreg = (__HANDLE__)->Instance->DR; \ UNUSED(tmpreg); \ } while(0) /** @brief Clear the USART FE pending flag. * @param __HANDLE__: specifies the USART Handle. * This parameter can be USARTx where x: 1, 2, 3 or 6 to select the USART peripheral. * @retval None */ #define __HAL_USART_CLEAR_FEFLAG(__HANDLE__) __HAL_USART_CLEAR_PEFLAG(__HANDLE__) /** @brief Clear the USART NE pending flag. * @param __HANDLE__: specifies the USART Handle. * This parameter can be USARTx where x: 1, 2, 3 or 6 to select the USART peripheral. * @retval None */ #define __HAL_USART_CLEAR_NEFLAG(__HANDLE__) __HAL_USART_CLEAR_PEFLAG(__HANDLE__) /** @brief Clear the UART ORE pending flag. * @param __HANDLE__: specifies the USART Handle. * This parameter can be USARTx where x: 1, 2, 3 or 6 to select the USART peripheral. * @retval None */ #define __HAL_USART_CLEAR_OREFLAG(__HANDLE__) __HAL_USART_CLEAR_PEFLAG(__HANDLE__) /** @brief Clear the USART IDLE pending flag. * @param __HANDLE__: specifies the USART Handle. * This parameter can be USARTx where x: 1, 2, 3 or 6 to select the USART peripheral. * @retval None */ #define __HAL_USART_CLEAR_IDLEFLAG(__HANDLE__) __HAL_USART_CLEAR_PEFLAG(__HANDLE__) /** @brief Enables or disables the specified USART interrupts. * @param __HANDLE__: specifies the USART Handle. * This parameter can be USARTx where x: 1, 2, 3 or 6 to select the USART peripheral. * @param __INTERRUPT__: specifies the USART interrupt source to check. * This parameter can be one of the following values: * @arg USART_IT_TXE: Transmit Data Register empty interrupt * @arg USART_IT_TC: Transmission complete interrupt * @arg USART_IT_RXNE: Receive Data register not empty interrupt * @arg USART_IT_IDLE: Idle line detection interrupt * @arg USART_IT_PE: Parity Error interrupt * @arg USART_IT_ERR: Error interrupt(Frame error, noise error, overrun error) * This parameter can be: ENABLE or DISABLE. * @retval None */ #define __HAL_USART_ENABLE_IT(__HANDLE__, __INTERRUPT__) ((((__INTERRUPT__) >> 28) == 1)? ((__HANDLE__)->Instance->CR1 |= ((__INTERRUPT__) & USART_IT_MASK)): \ (((__INTERRUPT__) >> 28) == 2)? ((__HANDLE__)->Instance->CR2 |= ((__INTERRUPT__) & USART_IT_MASK)): \ ((__HANDLE__)->Instance->CR3 |= ((__INTERRUPT__) & USART_IT_MASK))) #define __HAL_USART_DISABLE_IT(__HANDLE__, __INTERRUPT__) ((((__INTERRUPT__) >> 28) == 1)? ((__HANDLE__)->Instance->CR1 &= ~((__INTERRUPT__) & USART_IT_MASK)): \ (((__INTERRUPT__) >> 28) == 2)? ((__HANDLE__)->Instance->CR2 &= ~((__INTERRUPT__) & USART_IT_MASK)): \ ((__HANDLE__)->Instance->CR3 &= ~ ((__INTERRUPT__) & USART_IT_MASK))) /** @brief Checks whether the specified USART interrupt has occurred or not. * @param __HANDLE__: specifies the USART Handle. * This parameter can be USARTx where x: 1, 2, 3 or 6 to select the USART peripheral. * @param __IT__: specifies the USART interrupt source to check. * This parameter can be one of the following values: * @arg USART_IT_TXE: Transmit Data Register empty interrupt * @arg USART_IT_TC: Transmission complete interrupt * @arg USART_IT_RXNE: Receive Data register not empty interrupt * @arg USART_IT_IDLE: Idle line detection interrupt * @arg USART_IT_ERR: Error interrupt * @arg USART_IT_PE: Parity Error interrupt * @retval The new state of __IT__ (TRUE or FALSE). */ #define __HAL_USART_GET_IT_SOURCE(__HANDLE__, __IT__) (((((__IT__) >> 28) == 1)? (__HANDLE__)->Instance->CR1:(((((uint32_t)(__IT__)) >> 28) == 2)? \ (__HANDLE__)->Instance->CR2 : (__HANDLE__)->Instance->CR3)) & (((uint32_t)(__IT__)) & USART_IT_MASK)) /** @brief Macro to enable the USART's one bit sample method * @param __HANDLE__: specifies the USART Handle. * @retval None */ #define __HAL_USART_ONE_BIT_SAMPLE_ENABLE(__HANDLE__) ((__HANDLE__)->Instance->CR3|= USART_CR3_ONEBIT) /** @brief Macro to disable the USART's one bit sample method * @param __HANDLE__: specifies the USART Handle. * @retval None */ #define __HAL_USART_ONE_BIT_SAMPLE_DISABLE(__HANDLE__) ((__HANDLE__)->Instance->CR3 &= (uint16_t)~((uint16_t)USART_CR3_ONEBIT)) /** @brief Enable USART * @param __HANDLE__: specifies the USART Handle. * USART Handle selects the USARTx peripheral (USART availability and x value depending on device). * @retval None */ #define __HAL_USART_ENABLE(__HANDLE__) ( (__HANDLE__)->Instance->CR1 |= USART_CR1_UE) /** @brief Disable USART * @param __HANDLE__: specifies the USART Handle. * USART Handle selects the USARTx peripheral (USART availability and x value depending on device). * @retval None */ #define __HAL_USART_DISABLE(__HANDLE__) ( (__HANDLE__)->Instance->CR1 &= ~USART_CR1_UE) /** * @} */ /* Exported functions --------------------------------------------------------*/ /** @addtogroup USART_Exported_Functions * @{ */ /** @addtogroup USART_Exported_Functions_Group1 * @{ */ /* Initialization/de-initialization functions **********************************/ HAL_StatusTypeDef HAL_USART_Init(USART_HandleTypeDef *husart); HAL_StatusTypeDef HAL_USART_DeInit(USART_HandleTypeDef *husart); void HAL_USART_MspInit(USART_HandleTypeDef *husart); void HAL_USART_MspDeInit(USART_HandleTypeDef *husart); /** * @} */ /** @addtogroup USART_Exported_Functions_Group2 * @{ */ /* IO operation functions *******************************************************/ HAL_StatusTypeDef HAL_USART_Transmit(USART_HandleTypeDef *husart, uint8_t *pTxData, uint16_t Size, uint32_t Timeout); HAL_StatusTypeDef HAL_USART_Receive(USART_HandleTypeDef *husart, uint8_t *pRxData, uint16_t Size, uint32_t Timeout); HAL_StatusTypeDef HAL_USART_TransmitReceive(USART_HandleTypeDef *husart, uint8_t *pTxData, uint8_t *pRxData, uint16_t Size, uint32_t Timeout); HAL_StatusTypeDef HAL_USART_Transmit_IT(USART_HandleTypeDef *husart, uint8_t *pTxData, uint16_t Size); HAL_StatusTypeDef HAL_USART_Receive_IT(USART_HandleTypeDef *husart, uint8_t *pRxData, uint16_t Size); HAL_StatusTypeDef HAL_USART_TransmitReceive_IT(USART_HandleTypeDef *husart, uint8_t *pTxData, uint8_t *pRxData, uint16_t Size); HAL_StatusTypeDef HAL_USART_Transmit_DMA(USART_HandleTypeDef *husart, uint8_t *pTxData, uint16_t Size); HAL_StatusTypeDef HAL_USART_Receive_DMA(USART_HandleTypeDef *husart, uint8_t *pRxData, uint16_t Size); HAL_StatusTypeDef HAL_USART_TransmitReceive_DMA(USART_HandleTypeDef *husart, uint8_t *pTxData, uint8_t *pRxData, uint16_t Size); HAL_StatusTypeDef HAL_USART_DMAPause(USART_HandleTypeDef *husart); HAL_StatusTypeDef HAL_USART_DMAResume(USART_HandleTypeDef *husart); HAL_StatusTypeDef HAL_USART_DMAStop(USART_HandleTypeDef *husart); void HAL_USART_IRQHandler(USART_HandleTypeDef *husart); void HAL_USART_TxCpltCallback(USART_HandleTypeDef *husart); void HAL_USART_TxHalfCpltCallback(USART_HandleTypeDef *husart); void HAL_USART_RxCpltCallback(USART_HandleTypeDef *husart); void HAL_USART_RxHalfCpltCallback(USART_HandleTypeDef *husart); void HAL_USART_TxRxCpltCallback(USART_HandleTypeDef *husart); void HAL_USART_ErrorCallback(USART_HandleTypeDef *husart); /** * @} */ /** @addtogroup USART_Exported_Functions_Group3 * @{ */ /* Peripheral State functions ************************************************/ HAL_USART_StateTypeDef HAL_USART_GetState(USART_HandleTypeDef *husart); uint32_t HAL_USART_GetError(USART_HandleTypeDef *husart); /** * @} */ /** * @} */ /* Private types -------------------------------------------------------------*/ /* Private variables ---------------------------------------------------------*/ /* Private constants ---------------------------------------------------------*/ /** @defgroup USART_Private_Constants USART Private Constants * @{ */ /** @brief USART interruptions flag mask * */ #define USART_IT_MASK ((uint32_t) USART_CR1_PEIE | USART_CR1_TXEIE | USART_CR1_TCIE | USART_CR1_RXNEIE | \ USART_CR1_IDLEIE | USART_CR2_LBDIE | USART_CR3_CTSIE | USART_CR3_EIE ) #define USART_CR1_REG_INDEX 1 #define USART_CR2_REG_INDEX 2 #define USART_CR3_REG_INDEX 3 /** * @} */ /* Private macros ------------------------------------------------------------*/ /** @defgroup USART_Private_Macros USART Private Macros * @{ */ #define IS_USART_NACK_STATE(NACK) (((NACK) == USART_NACK_ENABLE) || \ ((NACK) == USART_NACK_DISABLE)) #define IS_USART_LASTBIT(LASTBIT) (((LASTBIT) == USART_LASTBIT_DISABLE) || \ ((LASTBIT) == USART_LASTBIT_ENABLE)) #define IS_USART_PHASE(CPHA) (((CPHA) == USART_PHASE_1EDGE) || ((CPHA) == USART_PHASE_2EDGE)) #define IS_USART_POLARITY(CPOL) (((CPOL) == USART_POLARITY_LOW) || ((CPOL) == USART_POLARITY_HIGH)) #define IS_USART_CLOCK(CLOCK) (((CLOCK) == USART_CLOCK_DISABLE) || \ ((CLOCK) == USART_CLOCK_ENABLE)) #define IS_USART_WORD_LENGTH(LENGTH) (((LENGTH) == USART_WORDLENGTH_8B) || \ ((LENGTH) == USART_WORDLENGTH_9B)) #define IS_USART_STOPBITS(STOPBITS) (((STOPBITS) == USART_STOPBITS_1) || \ ((STOPBITS) == USART_STOPBITS_0_5) || \ ((STOPBITS) == USART_STOPBITS_1_5) || \ ((STOPBITS) == USART_STOPBITS_2)) #define IS_USART_PARITY(PARITY) (((PARITY) == USART_PARITY_NONE) || \ ((PARITY) == USART_PARITY_EVEN) || \ ((PARITY) == USART_PARITY_ODD)) #define IS_USART_MODE(MODE) ((((MODE) & (uint32_t)0xFFF3) == 0x00) && ((MODE) != (uint32_t)0x00)) #define IS_USART_BAUDRATE(BAUDRATE) ((BAUDRATE) < 10500001) #define USART_DIV(_PCLK_, _BAUD_) (((_PCLK_)*25)/(2*(_BAUD_))) #define USART_DIVMANT(_PCLK_, _BAUD_) (USART_DIV((_PCLK_), (_BAUD_))/100) #define USART_DIVFRAQ(_PCLK_, _BAUD_) (((USART_DIV((_PCLK_), (_BAUD_)) - (USART_DIVMANT((_PCLK_), (_BAUD_)) * 100)) * 16 + 50) / 100) #define USART_BRR(_PCLK_, _BAUD_) ((USART_DIVMANT((_PCLK_), (_BAUD_)) << 4)|(USART_DIVFRAQ((_PCLK_), (_BAUD_)) & 0x0F)) /** * @} */ /* Private functions ---------------------------------------------------------*/ /** @defgroup USART_Private_Functions USART Private Functions * @{ */ /** * @} */ /** * @} */ /** * @} */ #ifdef __cplusplus } #endif #endif /* __STM32F4xx_HAL_USART_H */ /************************ (C) COPYRIGHT STMicroelectronics *****END OF FILE****/ ================================================ FILE: Zelig/mbed/TARGET_NUCLEO_F401RE/stm32f4xx_hal_wwdg.h ================================================ /** ****************************************************************************** * @file stm32f4xx_hal_wwdg.h * @author MCD Application Team * @version V1.4.1 * @date 09-October-2015 * @brief Header file of WWDG HAL module. ****************************************************************************** * @attention * *

© COPYRIGHT(c) 2015 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. * ****************************************************************************** */ /* Define to prevent recursive inclusion -------------------------------------*/ #ifndef __STM32F4xx_HAL_WWDG_H #define __STM32F4xx_HAL_WWDG_H #ifdef __cplusplus extern "C" { #endif /* Includes ------------------------------------------------------------------*/ #include "stm32f4xx_hal_def.h" /** @addtogroup STM32F4xx_HAL_Driver * @{ */ /** @addtogroup WWDG * @{ */ /* Exported types ------------------------------------------------------------*/ /** @defgroup WWDG_Exported_Types WWDG Exported Types * @{ */ /** * @brief WWDG HAL State Structure definition */ typedef enum { HAL_WWDG_STATE_RESET = 0x00, /*!< WWDG not yet initialized or disabled */ HAL_WWDG_STATE_READY = 0x01, /*!< WWDG initialized and ready for use */ HAL_WWDG_STATE_BUSY = 0x02, /*!< WWDG internal process is ongoing */ HAL_WWDG_STATE_TIMEOUT = 0x03, /*!< WWDG timeout state */ HAL_WWDG_STATE_ERROR = 0x04 /*!< WWDG error state */ }HAL_WWDG_StateTypeDef; /** * @brief WWDG Init structure definition */ typedef struct { uint32_t Prescaler; /*!< Specifies the prescaler value of the WWDG. This parameter can be a value of @ref WWDG_Prescaler */ uint32_t Window; /*!< Specifies the WWDG window value to be compared to the downcounter. This parameter must be a number lower than Max_Data = 0x80 */ uint32_t Counter; /*!< Specifies the WWDG free-running downcounter value. This parameter must be a number between Min_Data = 0x40 and Max_Data = 0x7F */ }WWDG_InitTypeDef; /** * @brief WWDG handle Structure definition */ typedef struct { WWDG_TypeDef *Instance; /*!< Register base address */ WWDG_InitTypeDef Init; /*!< WWDG required parameters */ HAL_LockTypeDef Lock; /*!< WWDG locking object */ __IO HAL_WWDG_StateTypeDef State; /*!< WWDG communication state */ }WWDG_HandleTypeDef; /** * @} */ /* Exported constants --------------------------------------------------------*/ /** @defgroup WWDG_Exported_Constants WWDG Exported Constants * @{ */ /** @defgroup WWDG_Interrupt_definition WWDG Interrupt definition * @{ */ #define WWDG_IT_EWI WWDG_CFR_EWI /*!< Early wakeup interrupt */ /** * @} */ /** @defgroup WWDG_Flag_definition WWDG Flag definition * @brief WWDG Flag definition * @{ */ #define WWDG_FLAG_EWIF WWDG_SR_EWIF /*!< Early wakeup interrupt flag */ /** * @} */ /** @defgroup WWDG_Prescaler WWDG Prescaler * @{ */ #define WWDG_PRESCALER_1 ((uint32_t)0x00000000) /*!< WWDG counter clock = (PCLK1/4096)/1 */ #define WWDG_PRESCALER_2 WWDG_CFR_WDGTB0 /*!< WWDG counter clock = (PCLK1/4096)/2 */ #define WWDG_PRESCALER_4 WWDG_CFR_WDGTB1 /*!< WWDG counter clock = (PCLK1/4096)/4 */ #define WWDG_PRESCALER_8 WWDG_CFR_WDGTB /*!< WWDG counter clock = (PCLK1/4096)/8 */ /** * @} */ /** * @} */ /* Exported macro ------------------------------------------------------------*/ /** @defgroup WWDG_Exported_Macros WWDG Exported Macros * @{ */ /** @brief Reset WWDG handle state * @param __HANDLE__: WWDG handle * @retval None */ #define __HAL_WWDG_RESET_HANDLE_STATE(__HANDLE__) ((__HANDLE__)->State = HAL_WWDG_STATE_RESET) /** * @brief Enables the WWDG peripheral. * @param __HANDLE__: WWDG handle * @retval None */ #define __HAL_WWDG_ENABLE(__HANDLE__) SET_BIT((__HANDLE__)->Instance->CR, WWDG_CR_WDGA) /** * @brief Disables the WWDG peripheral. * @param __HANDLE__: WWDG handle * @note WARNING: This is a dummy macro for HAL code alignment. * Once enable, WWDG Peripheral cannot be disabled except by a system reset. * @retval None */ #define __HAL_WWDG_DISABLE(__HANDLE__) /* dummy macro */ /** * @brief Gets the selected WWDG's it status. * @param __HANDLE__: WWDG handle * @param __INTERRUPT__: specifies the it to check. * This parameter can be one of the following values: * @arg WWDG_FLAG_EWIF: Early wakeup interrupt IT * @retval The new state of WWDG_FLAG (SET or RESET). */ #define __HAL_WWDG_GET_IT(__HANDLE__, __INTERRUPT__) __HAL_WWDG_GET_FLAG((__HANDLE__),(__INTERRUPT__)) /** @brief Clear the WWDG's interrupt pending bits * bits to clear the selected interrupt pending bits. * @param __HANDLE__: WWDG handle * @param __INTERRUPT__: specifies the interrupt pending bit to clear. * This parameter can be one of the following values: * @arg WWDG_FLAG_EWIF: Early wakeup interrupt flag */ #define __HAL_WWDG_CLEAR_IT(__HANDLE__, __INTERRUPT__) __HAL_WWDG_CLEAR_FLAG((__HANDLE__), (__INTERRUPT__)) /** * @brief Enables the WWDG early wakeup interrupt. * @param __HANDLE__: WWDG handle * @param __INTERRUPT__: specifies the interrupt to enable. * This parameter can be one of the following values: * @arg WWDG_IT_EWI: Early wakeup interrupt * @note Once enabled this interrupt cannot be disabled except by a system reset. * @retval None */ #define __HAL_WWDG_ENABLE_IT(__HANDLE__, __INTERRUPT__) SET_BIT((__HANDLE__)->Instance->CFR, (__INTERRUPT__)) /** * @brief Disables the WWDG early wakeup interrupt. * @param __HANDLE__: WWDG handle * @param __INTERRUPT__: specifies the interrupt to disable. * This parameter can be one of the following values: * @arg WWDG_IT_EWI: Early wakeup interrupt * @note WARNING: This is a dummy macro for HAL code alignment. * Once enabled this interrupt cannot be disabled except by a system reset. * @retval None */ #define __HAL_WWDG_DISABLE_IT(__HANDLE__, __INTERRUPT__) /* dummy macro */ /** * @brief Gets the selected WWDG's flag status. * @param __HANDLE__: WWDG handle * @param __FLAG__: specifies the flag to check. * This parameter can be one of the following values: * @arg WWDG_FLAG_EWIF: Early wakeup interrupt flag * @retval The new state of WWDG_FLAG (SET or RESET). */ #define __HAL_WWDG_GET_FLAG(__HANDLE__, __FLAG__) (((__HANDLE__)->Instance->SR & (__FLAG__)) == (__FLAG__)) /** * @brief Clears the WWDG's pending flags. * @param __HANDLE__: WWDG handle * @param __FLAG__: specifies the flag to clear. * This parameter can be one of the following values: * @arg WWDG_FLAG_EWIF: Early wakeup interrupt flag * @retval None */ #define __HAL_WWDG_CLEAR_FLAG(__HANDLE__, __FLAG__) (((__HANDLE__)->Instance->SR) = ~(__FLAG__)) /** @brief Checks if the specified WWDG interrupt source is enabled or disabled. * @param __HANDLE__: WWDG Handle. * @param __INTERRUPT__: specifies the WWDG interrupt source to check. * This parameter can be one of the following values: * @arg WWDG_IT_EWI: Early Wakeup Interrupt * @retval state of __INTERRUPT__ (TRUE or FALSE). */ #define __HAL_WWDG_GET_IT_SOURCE(__HANDLE__, __INTERRUPT__) (((__HANDLE__)->Instance->CFR & (__INTERRUPT__)) == (__INTERRUPT__)) /** * @} */ /* Exported functions --------------------------------------------------------*/ /** @addtogroup WWDG_Exported_Functions * @{ */ /** @addtogroup WWDG_Exported_Functions_Group1 * @{ */ /* Initialization/de-initialization functions **********************************/ HAL_StatusTypeDef HAL_WWDG_Init(WWDG_HandleTypeDef *hwwdg); HAL_StatusTypeDef HAL_WWDG_DeInit(WWDG_HandleTypeDef *hwwdg); void HAL_WWDG_MspInit(WWDG_HandleTypeDef *hwwdg); void HAL_WWDG_MspDeInit(WWDG_HandleTypeDef *hwwdg); void HAL_WWDG_WakeupCallback(WWDG_HandleTypeDef* hwwdg); /** * @} */ /** @addtogroup WWDG_Exported_Functions_Group2 * @{ */ /* I/O operation functions ******************************************************/ HAL_StatusTypeDef HAL_WWDG_Start(WWDG_HandleTypeDef *hwwdg); HAL_StatusTypeDef HAL_WWDG_Start_IT(WWDG_HandleTypeDef *hwwdg); HAL_StatusTypeDef HAL_WWDG_Refresh(WWDG_HandleTypeDef *hwwdg, uint32_t Counter); void HAL_WWDG_IRQHandler(WWDG_HandleTypeDef *hwwdg); /** * @} */ /** @addtogroup WWDG_Exported_Functions_Group3 * @{ */ /* Peripheral State functions **************************************************/ HAL_WWDG_StateTypeDef HAL_WWDG_GetState(WWDG_HandleTypeDef *hwwdg); /** * @} */ /** * @} */ /* Private types -------------------------------------------------------------*/ /* Private variables ---------------------------------------------------------*/ /* Private constants ---------------------------------------------------------*/ /** @defgroup WWDG_Private_Constants WWDG Private Constants * @{ */ /** @defgroup WWDG_BitAddress_AliasRegion WWDG BitAddress * @brief WWDG registers bit address in the alias region * @{ */ /* --- CFR Register ---*/ /* Alias word address of EWI bit */ #define WWDG_CFR_BASE (uint32_t)(WWDG_BASE + 0x04) /** * @} */ /** * @} */ /* Private macros ------------------------------------------------------------*/ /** @defgroup WWDG_Private_Macros WWDG Private Macros * @{ */ #define IS_WWDG_PRESCALER(__PRESCALER__) (((__PRESCALER__) == WWDG_PRESCALER_1) || \ ((__PRESCALER__) == WWDG_PRESCALER_2) || \ ((__PRESCALER__) == WWDG_PRESCALER_4) || \ ((__PRESCALER__) == WWDG_PRESCALER_8)) #define IS_WWDG_WINDOW(__WINDOW__) ((__WINDOW__) <= 0x7F) #define IS_WWDG_COUNTER(__COUNTER__) (((__COUNTER__) >= 0x40) && ((__COUNTER__) <= 0x7F)) /** * @} */ /* Private functions ---------------------------------------------------------*/ /** @defgroup WWDG_Private_Functions WWDG Private Functions * @{ */ /** * @} */ /** * @} */ /** * @} */ #ifdef __cplusplus } #endif #endif /* __STM32F4xx_HAL_WWDG_H */ /************************ (C) COPYRIGHT STMicroelectronics *****END OF FILE****/ ================================================ FILE: Zelig/mbed/TARGET_NUCLEO_F401RE/stm32f4xx_ll_fmc.h ================================================ /** ****************************************************************************** * @file stm32f4xx_ll_fmc.h * @author MCD Application Team * @version V1.4.1 * @date 09-October-2015 * @brief Header file of FMC HAL module. ****************************************************************************** * @attention * *

© COPYRIGHT(c) 2015 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. * ****************************************************************************** */ /* Define to prevent recursive inclusion -------------------------------------*/ #ifndef __STM32F4xx_LL_FMC_H #define __STM32F4xx_LL_FMC_H #ifdef __cplusplus extern "C" { #endif /* Includes ------------------------------------------------------------------*/ #include "stm32f4xx_hal_def.h" /** @addtogroup STM32F4xx_HAL_Driver * @{ */ /** @addtogroup FMC_LL * @{ */ #if defined(STM32F427xx) || defined(STM32F437xx) || defined(STM32F429xx) || defined(STM32F439xx) ||\ defined(STM32F446xx) || defined(STM32F469xx) || defined(STM32F479xx) /* Private types -------------------------------------------------------------*/ /** @defgroup FMC_LL_Private_Types FMC Private Types * @{ */ /** * @brief FMC NORSRAM Configuration Structure definition */ typedef struct { uint32_t NSBank; /*!< Specifies the NORSRAM memory device that will be used. This parameter can be a value of @ref FMC_NORSRAM_Bank */ uint32_t DataAddressMux; /*!< Specifies whether the address and data values are multiplexed on the data bus or not. This parameter can be a value of @ref FMC_Data_Address_Bus_Multiplexing */ uint32_t MemoryType; /*!< Specifies the type of external memory attached to the corresponding memory device. This parameter can be a value of @ref FMC_Memory_Type */ uint32_t MemoryDataWidth; /*!< Specifies the external memory device width. This parameter can be a value of @ref FMC_NORSRAM_Data_Width */ uint32_t BurstAccessMode; /*!< Enables or disables the burst access mode for Flash memory, valid only with synchronous burst Flash memories. This parameter can be a value of @ref FMC_Burst_Access_Mode */ uint32_t WaitSignalPolarity; /*!< Specifies the wait signal polarity, valid only when accessing the Flash memory in burst mode. This parameter can be a value of @ref FMC_Wait_Signal_Polarity */ uint32_t WrapMode; /*!< Enables or disables the Wrapped burst access mode for Flash memory, valid only when accessing Flash memories in burst mode. This parameter can be a value of @ref FMC_Wrap_Mode This mode is not available for the STM32F446/467/479xx devices */ uint32_t WaitSignalActive; /*!< Specifies if the wait signal is asserted by the memory one clock cycle before the wait state or during the wait state, valid only when accessing memories in burst mode. This parameter can be a value of @ref FMC_Wait_Timing */ uint32_t WriteOperation; /*!< Enables or disables the write operation in the selected device by the FMC. This parameter can be a value of @ref FMC_Write_Operation */ uint32_t WaitSignal; /*!< Enables or disables the wait state insertion via wait signal, valid for Flash memory access in burst mode. This parameter can be a value of @ref FMC_Wait_Signal */ uint32_t ExtendedMode; /*!< Enables or disables the extended mode. This parameter can be a value of @ref FMC_Extended_Mode */ uint32_t AsynchronousWait; /*!< Enables or disables wait signal during asynchronous transfers, valid only with asynchronous Flash memories. This parameter can be a value of @ref FMC_AsynchronousWait */ uint32_t WriteBurst; /*!< Enables or disables the write burst operation. This parameter can be a value of @ref FMC_Write_Burst */ uint32_t ContinuousClock; /*!< Enables or disables the FMC clock output to external memory devices. This parameter is only enabled through the FMC_BCR1 register, and don't care through FMC_BCR2..4 registers. This parameter can be a value of @ref FMC_Continous_Clock */ uint32_t WriteFifo; /*!< Enables or disables the write FIFO used by the FMC controller. This parameter is only enabled through the FMC_BCR1 register, and don't care through FMC_BCR2..4 registers. This parameter can be a value of @ref FMC_Write_FIFO This mode is available only for the STM32F446/469/479xx devices */ uint32_t PageSize; /*!< Specifies the memory page size. This parameter can be a value of @ref FMC_Page_Size This mode is available only for the STM32F446xx devices */ }FMC_NORSRAM_InitTypeDef; /** * @brief FMC NORSRAM Timing parameters structure definition */ typedef struct { uint32_t AddressSetupTime; /*!< Defines the number of HCLK cycles to configure the duration of the address setup time. This parameter can be a value between Min_Data = 0 and Max_Data = 15. @note This parameter is not used with synchronous NOR Flash memories. */ uint32_t AddressHoldTime; /*!< Defines the number of HCLK cycles to configure the duration of the address hold time. This parameter can be a value between Min_Data = 1 and Max_Data = 15. @note This parameter is not used with synchronous NOR Flash memories. */ uint32_t DataSetupTime; /*!< Defines the number of HCLK cycles to configure the duration of the data setup time. This parameter can be a value between Min_Data = 1 and Max_Data = 255. @note This parameter is used for SRAMs, ROMs and asynchronous multiplexed NOR Flash memories. */ uint32_t BusTurnAroundDuration; /*!< Defines the number of HCLK cycles to configure the duration of the bus turnaround. This parameter can be a value between Min_Data = 0 and Max_Data = 15. @note This parameter is only used for multiplexed NOR Flash memories. */ uint32_t CLKDivision; /*!< Defines the period of CLK clock output signal, expressed in number of HCLK cycles. This parameter can be a value between Min_Data = 2 and Max_Data = 16. @note This parameter is not used for asynchronous NOR Flash, SRAM or ROM accesses. */ uint32_t DataLatency; /*!< Defines the number of memory clock cycles to issue to the memory before getting the first data. The parameter value depends on the memory type as shown below: - It must be set to 0 in case of a CRAM - It is don't care in asynchronous NOR, SRAM or ROM accesses - It may assume a value between Min_Data = 2 and Max_Data = 17 in NOR Flash memories with synchronous burst mode enable */ uint32_t AccessMode; /*!< Specifies the asynchronous access mode. This parameter can be a value of @ref FMC_Access_Mode */ }FMC_NORSRAM_TimingTypeDef; /** * @brief FMC NAND Configuration Structure definition */ typedef struct { uint32_t NandBank; /*!< Specifies the NAND memory device that will be used. This parameter can be a value of @ref FMC_NAND_Bank */ uint32_t Waitfeature; /*!< Enables or disables the Wait feature for the NAND Memory device. This parameter can be any value of @ref FMC_Wait_feature */ uint32_t MemoryDataWidth; /*!< Specifies the external memory device width. This parameter can be any value of @ref FMC_NAND_Data_Width */ uint32_t EccComputation; /*!< Enables or disables the ECC computation. This parameter can be any value of @ref FMC_ECC */ uint32_t ECCPageSize; /*!< Defines the page size for the extended ECC. This parameter can be any value of @ref FMC_ECC_Page_Size */ uint32_t TCLRSetupTime; /*!< Defines the number of HCLK cycles to configure the delay between CLE low and RE low. This parameter can be a value between Min_Data = 0 and Max_Data = 255 */ uint32_t TARSetupTime; /*!< Defines the number of HCLK cycles to configure the delay between ALE low and RE low. This parameter can be a number between Min_Data = 0 and Max_Data = 255 */ }FMC_NAND_InitTypeDef; /** * @brief FMC NAND/PCCARD Timing parameters structure definition */ typedef struct { uint32_t SetupTime; /*!< Defines the number of HCLK cycles to setup address before the command assertion for NAND-Flash read or write access to common/Attribute or I/O memory space (depending on the memory space timing to be configured). This parameter can be a value between Min_Data = 0 and Max_Data = 255 */ uint32_t WaitSetupTime; /*!< Defines the minimum number of HCLK cycles to assert the command for NAND-Flash read or write access to common/Attribute or I/O memory space (depending on the memory space timing to be configured). This parameter can be a number between Min_Data = 0 and Max_Data = 255 */ uint32_t HoldSetupTime; /*!< Defines the number of HCLK clock cycles to hold address (and data for write access) after the command de-assertion for NAND-Flash read or write access to common/Attribute or I/O memory space (depending on the memory space timing to be configured). This parameter can be a number between Min_Data = 0 and Max_Data = 255 */ uint32_t HiZSetupTime; /*!< Defines the number of HCLK clock cycles during which the data bus is kept in HiZ after the start of a NAND-Flash write access to common/Attribute or I/O memory space (depending on the memory space timing to be configured). This parameter can be a number between Min_Data = 0 and Max_Data = 255 */ }FMC_NAND_PCC_TimingTypeDef; /** * @brief FMC NAND Configuration Structure definition */ typedef struct { uint32_t Waitfeature; /*!< Enables or disables the Wait feature for the PCCARD Memory device. This parameter can be any value of @ref FMC_Wait_feature */ uint32_t TCLRSetupTime; /*!< Defines the number of HCLK cycles to configure the delay between CLE low and RE low. This parameter can be a value between Min_Data = 0 and Max_Data = 255 */ uint32_t TARSetupTime; /*!< Defines the number of HCLK cycles to configure the delay between ALE low and RE low. This parameter can be a number between Min_Data = 0 and Max_Data = 255 */ }FMC_PCCARD_InitTypeDef; /** * @brief FMC SDRAM Configuration Structure definition */ typedef struct { uint32_t SDBank; /*!< Specifies the SDRAM memory device that will be used. This parameter can be a value of @ref FMC_SDRAM_Bank */ uint32_t ColumnBitsNumber; /*!< Defines the number of bits of column address. This parameter can be a value of @ref FMC_SDRAM_Column_Bits_number. */ uint32_t RowBitsNumber; /*!< Defines the number of bits of column address. This parameter can be a value of @ref FMC_SDRAM_Row_Bits_number. */ uint32_t MemoryDataWidth; /*!< Defines the memory device width. This parameter can be a value of @ref FMC_SDRAM_Memory_Bus_Width. */ uint32_t InternalBankNumber; /*!< Defines the number of the device's internal banks. This parameter can be of @ref FMC_SDRAM_Internal_Banks_Number. */ uint32_t CASLatency; /*!< Defines the SDRAM CAS latency in number of memory clock cycles. This parameter can be a value of @ref FMC_SDRAM_CAS_Latency. */ uint32_t WriteProtection; /*!< Enables the SDRAM device to be accessed in write mode. This parameter can be a value of @ref FMC_SDRAM_Write_Protection. */ uint32_t SDClockPeriod; /*!< Define the SDRAM Clock Period for both SDRAM devices and they allow to disable the clock before changing frequency. This parameter can be a value of @ref FMC_SDRAM_Clock_Period. */ uint32_t ReadBurst; /*!< This bit enable the SDRAM controller to anticipate the next read commands during the CAS latency and stores data in the Read FIFO. This parameter can be a value of @ref FMC_SDRAM_Read_Burst. */ uint32_t ReadPipeDelay; /*!< Define the delay in system clock cycles on read data path. This parameter can be a value of @ref FMC_SDRAM_Read_Pipe_Delay. */ }FMC_SDRAM_InitTypeDef; /** * @brief FMC SDRAM Timing parameters structure definition */ typedef struct { uint32_t LoadToActiveDelay; /*!< Defines the delay between a Load Mode Register command and an active or Refresh command in number of memory clock cycles. This parameter can be a value between Min_Data = 1 and Max_Data = 16 */ uint32_t ExitSelfRefreshDelay; /*!< Defines the delay from releasing the self refresh command to issuing the Activate command in number of memory clock cycles. This parameter can be a value between Min_Data = 1 and Max_Data = 16 */ uint32_t SelfRefreshTime; /*!< Defines the minimum Self Refresh period in number of memory clock cycles. This parameter can be a value between Min_Data = 1 and Max_Data = 16 */ uint32_t RowCycleDelay; /*!< Defines the delay between the Refresh command and the Activate command and the delay between two consecutive Refresh commands in number of memory clock cycles. This parameter can be a value between Min_Data = 1 and Max_Data = 16 */ uint32_t WriteRecoveryTime; /*!< Defines the Write recovery Time in number of memory clock cycles. This parameter can be a value between Min_Data = 1 and Max_Data = 16 */ uint32_t RPDelay; /*!< Defines the delay between a Precharge Command and an other command in number of memory clock cycles. This parameter can be a value between Min_Data = 1 and Max_Data = 16 */ uint32_t RCDDelay; /*!< Defines the delay between the Activate Command and a Read/Write command in number of memory clock cycles. This parameter can be a value between Min_Data = 1 and Max_Data = 16 */ }FMC_SDRAM_TimingTypeDef; /** * @brief SDRAM command parameters structure definition */ typedef struct { uint32_t CommandMode; /*!< Defines the command issued to the SDRAM device. This parameter can be a value of @ref FMC_SDRAM_Command_Mode. */ uint32_t CommandTarget; /*!< Defines which device (1 or 2) the command will be issued to. This parameter can be a value of @ref FMC_SDRAM_Command_Target. */ uint32_t AutoRefreshNumber; /*!< Defines the number of consecutive auto refresh command issued in auto refresh mode. This parameter can be a value between Min_Data = 1 and Max_Data = 16 */ uint32_t ModeRegisterDefinition; /*!< Defines the SDRAM Mode register content */ }FMC_SDRAM_CommandTypeDef; /** * @} */ /* Private constants ---------------------------------------------------------*/ /** @defgroup FMC_LL_Private_Constants FMC Private Constants * @{ */ /** @defgroup FMC_LL_NOR_SRAM_Controller FMC NOR/SRAM Controller * @{ */ /** @defgroup FMC_NORSRAM_Bank FMC NOR/SRAM Bank * @{ */ #define FMC_NORSRAM_BANK1 ((uint32_t)0x00000000) #define FMC_NORSRAM_BANK2 ((uint32_t)0x00000002) #define FMC_NORSRAM_BANK3 ((uint32_t)0x00000004) #define FMC_NORSRAM_BANK4 ((uint32_t)0x00000006) /** * @} */ /** @defgroup FMC_Data_Address_Bus_Multiplexing FMC Data Address Bus Multiplexing * @{ */ #define FMC_DATA_ADDRESS_MUX_DISABLE ((uint32_t)0x00000000) #define FMC_DATA_ADDRESS_MUX_ENABLE ((uint32_t)0x00000002) /** * @} */ /** @defgroup FMC_Memory_Type FMC Memory Type * @{ */ #define FMC_MEMORY_TYPE_SRAM ((uint32_t)0x00000000) #define FMC_MEMORY_TYPE_PSRAM ((uint32_t)0x00000004) #define FMC_MEMORY_TYPE_NOR ((uint32_t)0x00000008) /** * @} */ /** @defgroup FMC_NORSRAM_Data_Width FMC NORSRAM Data Width * @{ */ #define FMC_NORSRAM_MEM_BUS_WIDTH_8 ((uint32_t)0x00000000) #define FMC_NORSRAM_MEM_BUS_WIDTH_16 ((uint32_t)0x00000010) #define FMC_NORSRAM_MEM_BUS_WIDTH_32 ((uint32_t)0x00000020) /** * @} */ /** @defgroup FMC_NORSRAM_Flash_Access FMC NOR/SRAM Flash Access * @{ */ #define FMC_NORSRAM_FLASH_ACCESS_ENABLE ((uint32_t)0x00000040) #define FMC_NORSRAM_FLASH_ACCESS_DISABLE ((uint32_t)0x00000000) /** * @} */ /** @defgroup FMC_Burst_Access_Mode FMC Burst Access Mode * @{ */ #define FMC_BURST_ACCESS_MODE_DISABLE ((uint32_t)0x00000000) #define FMC_BURST_ACCESS_MODE_ENABLE ((uint32_t)0x00000100) /** * @} */ /** @defgroup FMC_Wait_Signal_Polarity FMC Wait Signal Polarity * @{ */ #define FMC_WAIT_SIGNAL_POLARITY_LOW ((uint32_t)0x00000000) #define FMC_WAIT_SIGNAL_POLARITY_HIGH ((uint32_t)0x00000200) /** * @} */ /** @defgroup FMC_Wrap_Mode FMC Wrap Mode * @{ */ /** @note This mode is not available for the STM32F446/469/479xx devices */ #define FMC_WRAP_MODE_DISABLE ((uint32_t)0x00000000) #define FMC_WRAP_MODE_ENABLE ((uint32_t)0x00000400) /** * @} */ /** @defgroup FMC_Wait_Timing FMC Wait Timing * @{ */ #define FMC_WAIT_TIMING_BEFORE_WS ((uint32_t)0x00000000) #define FMC_WAIT_TIMING_DURING_WS ((uint32_t)0x00000800) /** * @} */ /** @defgroup FMC_Write_Operation FMC Write Operation * @{ */ #define FMC_WRITE_OPERATION_DISABLE ((uint32_t)0x00000000) #define FMC_WRITE_OPERATION_ENABLE ((uint32_t)0x00001000) /** * @} */ /** @defgroup FMC_Wait_Signal FMC Wait Signal * @{ */ #define FMC_WAIT_SIGNAL_DISABLE ((uint32_t)0x00000000) #define FMC_WAIT_SIGNAL_ENABLE ((uint32_t)0x00002000) /** * @} */ /** @defgroup FMC_Extended_Mode FMC Extended Mode * @{ */ #define FMC_EXTENDED_MODE_DISABLE ((uint32_t)0x00000000) #define FMC_EXTENDED_MODE_ENABLE ((uint32_t)0x00004000) /** * @} */ /** @defgroup FMC_AsynchronousWait FMC Asynchronous Wait * @{ */ #define FMC_ASYNCHRONOUS_WAIT_DISABLE ((uint32_t)0x00000000) #define FMC_ASYNCHRONOUS_WAIT_ENABLE ((uint32_t)0x00008000) /** * @} */ /** @defgroup FMC_Page_Size FMC Page Size * @note These values are available only for the STM32F446/469/479xx devices. * @{ */ #define FMC_PAGE_SIZE_NONE ((uint32_t)0x00000000) #define FMC_PAGE_SIZE_128 ((uint32_t)FMC_BCR1_CPSIZE_0) #define FMC_PAGE_SIZE_256 ((uint32_t)FMC_BCR1_CPSIZE_1) #define FMC_PAGE_SIZE_1024 ((uint32_t)FMC_BCR1_CPSIZE_2) /** * @} */ /** @defgroup FMC_Write_FIFO FMC Write FIFO * @note These values are available only for the STM32F446/469/479xx devices. * @{ */ #define FMC_WRITE_FIFO_DISABLE ((uint32_t)0x00000000) #define FMC_WRITE_FIFO_ENABLE ((uint32_t)FMC_BCR1_WFDIS) /** * @} */ /** @defgroup FMC_Write_Burst FMC Write Burst * @{ */ #define FMC_WRITE_BURST_DISABLE ((uint32_t)0x00000000) #define FMC_WRITE_BURST_ENABLE ((uint32_t)0x00080000) /** * @} */ /** @defgroup FMC_Continous_Clock FMC Continuous Clock * @{ */ #define FMC_CONTINUOUS_CLOCK_SYNC_ONLY ((uint32_t)0x00000000) #define FMC_CONTINUOUS_CLOCK_SYNC_ASYNC ((uint32_t)0x00100000) /** * @} */ /** @defgroup FMC_Access_Mode FMC Access Mode * @{ */ #define FMC_ACCESS_MODE_A ((uint32_t)0x00000000) #define FMC_ACCESS_MODE_B ((uint32_t)0x10000000) #define FMC_ACCESS_MODE_C ((uint32_t)0x20000000) #define FMC_ACCESS_MODE_D ((uint32_t)0x30000000) /** * @} */ /** * @} */ /** @defgroup FMC_LL_NAND_Controller FMC NAND Controller * @{ */ /** @defgroup FMC_NAND_Bank FMC NAND Bank * @{ */ #define FMC_NAND_BANK2 ((uint32_t)0x00000010) #define FMC_NAND_BANK3 ((uint32_t)0x00000100) /** * @} */ /** @defgroup FMC_Wait_feature FMC Wait feature * @{ */ #define FMC_NAND_PCC_WAIT_FEATURE_DISABLE ((uint32_t)0x00000000) #define FMC_NAND_PCC_WAIT_FEATURE_ENABLE ((uint32_t)0x00000002) /** * @} */ /** @defgroup FMC_PCR_Memory_Type FMC PCR Memory Type * @{ */ #define FMC_PCR_MEMORY_TYPE_PCCARD ((uint32_t)0x00000000) #define FMC_PCR_MEMORY_TYPE_NAND ((uint32_t)0x00000008) /** * @} */ /** @defgroup FMC_NAND_Data_Width FMC NAND Data Width * @{ */ #define FMC_NAND_PCC_MEM_BUS_WIDTH_8 ((uint32_t)0x00000000) #define FMC_NAND_PCC_MEM_BUS_WIDTH_16 ((uint32_t)0x00000010) /** * @} */ /** @defgroup FMC_ECC FMC ECC * @{ */ #define FMC_NAND_ECC_DISABLE ((uint32_t)0x00000000) #define FMC_NAND_ECC_ENABLE ((uint32_t)0x00000040) /** * @} */ /** @defgroup FMC_ECC_Page_Size FMC ECC Page Size * @{ */ #define FMC_NAND_ECC_PAGE_SIZE_256BYTE ((uint32_t)0x00000000) #define FMC_NAND_ECC_PAGE_SIZE_512BYTE ((uint32_t)0x00020000) #define FMC_NAND_ECC_PAGE_SIZE_1024BYTE ((uint32_t)0x00040000) #define FMC_NAND_ECC_PAGE_SIZE_2048BYTE ((uint32_t)0x00060000) #define FMC_NAND_ECC_PAGE_SIZE_4096BYTE ((uint32_t)0x00080000) #define FMC_NAND_ECC_PAGE_SIZE_8192BYTE ((uint32_t)0x000A0000) /** * @} */ /** * @} */ /** @defgroup FMC_LL_SDRAM_Controller FMC SDRAM Controller * @{ */ /** @defgroup FMC_SDRAM_Bank FMC SDRAM Bank * @{ */ #define FMC_SDRAM_BANK1 ((uint32_t)0x00000000) #define FMC_SDRAM_BANK2 ((uint32_t)0x00000001) /** * @} */ /** @defgroup FMC_SDRAM_Column_Bits_number FMC SDRAM Column Bits number * @{ */ #define FMC_SDRAM_COLUMN_BITS_NUM_8 ((uint32_t)0x00000000) #define FMC_SDRAM_COLUMN_BITS_NUM_9 ((uint32_t)0x00000001) #define FMC_SDRAM_COLUMN_BITS_NUM_10 ((uint32_t)0x00000002) #define FMC_SDRAM_COLUMN_BITS_NUM_11 ((uint32_t)0x00000003) /** * @} */ /** @defgroup FMC_SDRAM_Row_Bits_number FMC SDRAM Row Bits number * @{ */ #define FMC_SDRAM_ROW_BITS_NUM_11 ((uint32_t)0x00000000) #define FMC_SDRAM_ROW_BITS_NUM_12 ((uint32_t)0x00000004) #define FMC_SDRAM_ROW_BITS_NUM_13 ((uint32_t)0x00000008) /** * @} */ /** @defgroup FMC_SDRAM_Memory_Bus_Width FMC SDRAM Memory Bus Width * @{ */ #define FMC_SDRAM_MEM_BUS_WIDTH_8 ((uint32_t)0x00000000) #define FMC_SDRAM_MEM_BUS_WIDTH_16 ((uint32_t)0x00000010) #define FMC_SDRAM_MEM_BUS_WIDTH_32 ((uint32_t)0x00000020) /** * @} */ /** @defgroup FMC_SDRAM_Internal_Banks_Number FMC SDRAM Internal Banks Number * @{ */ #define FMC_SDRAM_INTERN_BANKS_NUM_2 ((uint32_t)0x00000000) #define FMC_SDRAM_INTERN_BANKS_NUM_4 ((uint32_t)0x00000040) /** * @} */ /** @defgroup FMC_SDRAM_CAS_Latency FMC SDRAM CAS Latency * @{ */ #define FMC_SDRAM_CAS_LATENCY_1 ((uint32_t)0x00000080) #define FMC_SDRAM_CAS_LATENCY_2 ((uint32_t)0x00000100) #define FMC_SDRAM_CAS_LATENCY_3 ((uint32_t)0x00000180) /** * @} */ /** @defgroup FMC_SDRAM_Write_Protection FMC SDRAM Write Protection * @{ */ #define FMC_SDRAM_WRITE_PROTECTION_DISABLE ((uint32_t)0x00000000) #define FMC_SDRAM_WRITE_PROTECTION_ENABLE ((uint32_t)0x00000200) /** * @} */ /** @defgroup FMC_SDRAM_Clock_Period FMC SDRAM Clock Period * @{ */ #define FMC_SDRAM_CLOCK_DISABLE ((uint32_t)0x00000000) #define FMC_SDRAM_CLOCK_PERIOD_2 ((uint32_t)0x00000800) #define FMC_SDRAM_CLOCK_PERIOD_3 ((uint32_t)0x00000C00) /** * @} */ /** @defgroup FMC_SDRAM_Read_Burst FMC SDRAM Read Burst * @{ */ #define FMC_SDRAM_RBURST_DISABLE ((uint32_t)0x00000000) #define FMC_SDRAM_RBURST_ENABLE ((uint32_t)0x00001000) /** * @} */ /** @defgroup FMC_SDRAM_Read_Pipe_Delay FMC SDRAM Read Pipe Delay * @{ */ #define FMC_SDRAM_RPIPE_DELAY_0 ((uint32_t)0x00000000) #define FMC_SDRAM_RPIPE_DELAY_1 ((uint32_t)0x00002000) #define FMC_SDRAM_RPIPE_DELAY_2 ((uint32_t)0x00004000) /** * @} */ /** @defgroup FMC_SDRAM_Command_Mode FMC SDRAM Command Mode * @{ */ #define FMC_SDRAM_CMD_NORMAL_MODE ((uint32_t)0x00000000) #define FMC_SDRAM_CMD_CLK_ENABLE ((uint32_t)0x00000001) #define FMC_SDRAM_CMD_PALL ((uint32_t)0x00000002) #define FMC_SDRAM_CMD_AUTOREFRESH_MODE ((uint32_t)0x00000003) #define FMC_SDRAM_CMD_LOAD_MODE ((uint32_t)0x00000004) #define FMC_SDRAM_CMD_SELFREFRESH_MODE ((uint32_t)0x00000005) #define FMC_SDRAM_CMD_POWERDOWN_MODE ((uint32_t)0x00000006) /** * @} */ /** @defgroup FMC_SDRAM_Command_Target FMC SDRAM Command Target * @{ */ #define FMC_SDRAM_CMD_TARGET_BANK2 FMC_SDCMR_CTB2 #define FMC_SDRAM_CMD_TARGET_BANK1 FMC_SDCMR_CTB1 #define FMC_SDRAM_CMD_TARGET_BANK1_2 ((uint32_t)0x00000018) /** * @} */ /** @defgroup FMC_SDRAM_Mode_Status FMC SDRAM Mode Status * @{ */ #define FMC_SDRAM_NORMAL_MODE ((uint32_t)0x00000000) #define FMC_SDRAM_SELF_REFRESH_MODE FMC_SDSR_MODES1_0 #define FMC_SDRAM_POWER_DOWN_MODE FMC_SDSR_MODES1_1 /** * @} */ /** * @} */ /** @defgroup FMC_LL_Interrupt_definition FMC Interrupt definition * @{ */ #define FMC_IT_RISING_EDGE ((uint32_t)0x00000008) #define FMC_IT_LEVEL ((uint32_t)0x00000010) #define FMC_IT_FALLING_EDGE ((uint32_t)0x00000020) #define FMC_IT_REFRESH_ERROR ((uint32_t)0x00004000) /** * @} */ /** @defgroup FMC_LL_Flag_definition FMC Flag definition * @{ */ #define FMC_FLAG_RISING_EDGE ((uint32_t)0x00000001) #define FMC_FLAG_LEVEL ((uint32_t)0x00000002) #define FMC_FLAG_FALLING_EDGE ((uint32_t)0x00000004) #define FMC_FLAG_FEMPT ((uint32_t)0x00000040) #define FMC_SDRAM_FLAG_REFRESH_IT FMC_SDSR_RE #define FMC_SDRAM_FLAG_BUSY FMC_SDSR_BUSY #define FMC_SDRAM_FLAG_REFRESH_ERROR FMC_SDRTR_CRE /** * @} */ /** @defgroup FMC_LL_Alias_definition FMC Alias definition * @{ */ #if defined(STM32F446xx) || defined(STM32F469xx) || defined(STM32F479xx) #define FMC_NAND_TypeDef FMC_Bank3_TypeDef #else #define FMC_NAND_TypeDef FMC_Bank2_3_TypeDef #define FMC_PCCARD_TypeDef FMC_Bank4_TypeDef #endif /* STM32F446xx || STM32F469xx || STM32F479xx */ #define FMC_NORSRAM_TypeDef FMC_Bank1_TypeDef #define FMC_NORSRAM_EXTENDED_TypeDef FMC_Bank1E_TypeDef #define FMC_SDRAM_TypeDef FMC_Bank5_6_TypeDef #if defined(STM32F446xx) || defined(STM32F469xx) || defined(STM32F479xx) #define FMC_NAND_DEVICE FMC_Bank3 #else #define FMC_NAND_DEVICE FMC_Bank2_3 #define FMC_PCCARD_DEVICE FMC_Bank4 #endif /* STM32F446xx || STM32F469xx || STM32F479xx */ #define FMC_NORSRAM_DEVICE FMC_Bank1 #define FMC_NORSRAM_EXTENDED_DEVICE FMC_Bank1E #define FMC_SDRAM_DEVICE FMC_Bank5_6 /** * @} */ /** * @} */ /* Private macro -------------------------------------------------------------*/ /** @defgroup FMC_LL_Private_Macros FMC Private Macros * @{ */ /** @defgroup FMC_LL_NOR_Macros FMC NOR/SRAM Macros * @brief macros to handle NOR device enable/disable and read/write operations * @{ */ /** * @brief Enable the NORSRAM device access. * @param __INSTANCE__: FMC_NORSRAM Instance * @param __BANK__: FMC_NORSRAM Bank * @retval None */ #define __FMC_NORSRAM_ENABLE(__INSTANCE__, __BANK__) ((__INSTANCE__)->BTCR[(__BANK__)] |= FMC_BCR1_MBKEN) /** * @brief Disable the NORSRAM device access. * @param __INSTANCE__: FMC_NORSRAM Instance * @param __BANK__: FMC_NORSRAM Bank * @retval None */ #define __FMC_NORSRAM_DISABLE(__INSTANCE__, __BANK__) ((__INSTANCE__)->BTCR[(__BANK__)] &= ~FMC_BCR1_MBKEN) /** * @} */ /** @defgroup FMC_LL_NAND_Macros FMC NAND Macros * @brief macros to handle NAND device enable/disable * @{ */ #if defined(STM32F446xx) || defined(STM32F469xx) || defined(STM32F479xx) /** * @brief Enable the NAND device access. * @param __INSTANCE__: FMC_NAND Instance * @param __BANK__: FMC_NAND Bank * @retval None */ #define __FMC_NAND_ENABLE(__INSTANCE__, __BANK__) ((__INSTANCE__)->PCR |= FMC_PCR_PBKEN) /** * @brief Disable the NAND device access. * @param __INSTANCE__: FMC_NAND Instance * @param __BANK__: FMC_NAND Bank * @retval None */ #define __FMC_NAND_DISABLE(__INSTANCE__, __BANK__) ((__INSTANCE__)->PCR &= ~FMC_PCR_PBKEN) #else /* defined(STM32F427xx) || defined(STM32F437xx) || defined(STM32F429xx) || defined(STM32F439xx) */ /** * @brief Enable the NAND device access. * @param __INSTANCE__: FMC_NAND Instance * @param __BANK__: FMC_NAND Bank * @retval None */ #define __FMC_NAND_ENABLE(__INSTANCE__, __BANK__) (((__BANK__) == FMC_NAND_BANK2)? ((__INSTANCE__)->PCR2 |= FMC_PCR2_PBKEN): \ ((__INSTANCE__)->PCR3 |= FMC_PCR3_PBKEN)) /** * @brief Disable the NAND device access. * @param __INSTANCE__: FMC_NAND Instance * @param __BANK__: FMC_NAND Bank * @retval None */ #define __FMC_NAND_DISABLE(__INSTANCE__, __BANK__) (((__BANK__) == FMC_NAND_BANK2)? ((__INSTANCE__)->PCR2 &= ~FMC_PCR2_PBKEN): \ ((__INSTANCE__)->PCR3 &= ~FMC_PCR3_PBKEN)) #endif /* defined(STM32F446xx) || defined(STM32F469xx) || defined(STM32F479xx) */ /** * @} */ #if defined(STM32F427xx) || defined(STM32F437xx) || defined(STM32F429xx) || defined(STM32F439xx) /** @defgroup FMC_LL_PCCARD_Macros FMC PCCARD Macros * @brief macros to handle SRAM read/write operations * @{ */ /** * @brief Enable the PCCARD device access. * @param __INSTANCE__: FMC_PCCARD Instance * @retval None */ #define __FMC_PCCARD_ENABLE(__INSTANCE__) ((__INSTANCE__)->PCR4 |= FMC_PCR4_PBKEN) /** * @brief Disable the PCCARD device access. * @param __INSTANCE__: FMC_PCCARD Instance * @retval None */ #define __FMC_PCCARD_DISABLE(__INSTANCE__) ((__INSTANCE__)->PCR4 &= ~FMC_PCR4_PBKEN) /** * @} */ #endif /* defined(STM32F427xx) || defined(STM32F437xx) || defined(STM32F429xx) || defined(STM32F439xx) */ /** @defgroup FMC_LL_Flag_Interrupt_Macros FMC Flag&Interrupt Macros * @brief macros to handle FMC flags and interrupts * @{ */ #if defined(STM32F446xx) || defined(STM32F469xx) || defined(STM32F479xx) /** * @brief Enable the NAND device interrupt. * @param __INSTANCE__: FMC_NAND instance * @param __BANK__: FMC_NAND Bank * @param __INTERRUPT__: FMC_NAND interrupt * This parameter can be any combination of the following values: * @arg FMC_IT_RISING_EDGE: Interrupt rising edge. * @arg FMC_IT_LEVEL: Interrupt level. * @arg FMC_IT_FALLING_EDGE: Interrupt falling edge. * @retval None */ #define __FMC_NAND_ENABLE_IT(__INSTANCE__, __BANK__, __INTERRUPT__) ((__INSTANCE__)->SR |= (__INTERRUPT__)) /** * @brief Disable the NAND device interrupt. * @param __INSTANCE__: FMC_NAND Instance * @param __BANK__: FMC_NAND Bank * @param __INTERRUPT__: FMC_NAND interrupt * This parameter can be any combination of the following values: * @arg FMC_IT_RISING_EDGE: Interrupt rising edge. * @arg FMC_IT_LEVEL: Interrupt level. * @arg FMC_IT_FALLING_EDGE: Interrupt falling edge. * @retval None */ #define __FMC_NAND_DISABLE_IT(__INSTANCE__, __BANK__, __INTERRUPT__) ((__INSTANCE__)->SR &= ~(__INTERRUPT__)) /** * @brief Get flag status of the NAND device. * @param __INSTANCE__: FMC_NAND Instance * @param __BANK__: FMC_NAND Bank * @param __FLAG__: FMC_NAND flag * This parameter can be any combination of the following values: * @arg FMC_FLAG_RISING_EDGE: Interrupt rising edge flag. * @arg FMC_FLAG_LEVEL: Interrupt level edge flag. * @arg FMC_FLAG_FALLING_EDGE: Interrupt falling edge flag. * @arg FMC_FLAG_FEMPT: FIFO empty flag. * @retval The state of FLAG (SET or RESET). */ #define __FMC_NAND_GET_FLAG(__INSTANCE__, __BANK__, __FLAG__) (((__INSTANCE__)->SR &(__FLAG__)) == (__FLAG__)) /** * @brief Clear flag status of the NAND device. * @param __INSTANCE__: FMC_NAND Instance * @param __BANK__: FMC_NAND Bank * @param __FLAG__: FMC_NAND flag * This parameter can be any combination of the following values: * @arg FMC_FLAG_RISING_EDGE: Interrupt rising edge flag. * @arg FMC_FLAG_LEVEL: Interrupt level edge flag. * @arg FMC_FLAG_FALLING_EDGE: Interrupt falling edge flag. * @arg FMC_FLAG_FEMPT: FIFO empty flag. * @retval None */ #define __FMC_NAND_CLEAR_FLAG(__INSTANCE__, __BANK__, __FLAG__) ((__INSTANCE__)->SR &= ~(__FLAG__)) #else /* defined(STM32F427xx) || defined(STM32F437xx) || defined(STM32F429xx) || defined(STM32F439xx) */ /** * @brief Enable the NAND device interrupt. * @param __INSTANCE__: FMC_NAND instance * @param __BANK__: FMC_NAND Bank * @param __INTERRUPT__: FMC_NAND interrupt * This parameter can be any combination of the following values: * @arg FMC_IT_RISING_EDGE: Interrupt rising edge. * @arg FMC_IT_LEVEL: Interrupt level. * @arg FMC_IT_FALLING_EDGE: Interrupt falling edge. * @retval None */ #define __FMC_NAND_ENABLE_IT(__INSTANCE__, __BANK__, __INTERRUPT__) (((__BANK__) == FMC_NAND_BANK2)? ((__INSTANCE__)->SR2 |= (__INTERRUPT__)): \ ((__INSTANCE__)->SR3 |= (__INTERRUPT__))) /** * @brief Disable the NAND device interrupt. * @param __INSTANCE__: FMC_NAND Instance * @param __BANK__: FMC_NAND Bank * @param __INTERRUPT__: FMC_NAND interrupt * This parameter can be any combination of the following values: * @arg FMC_IT_RISING_EDGE: Interrupt rising edge. * @arg FMC_IT_LEVEL: Interrupt level. * @arg FMC_IT_FALLING_EDGE: Interrupt falling edge. * @retval None */ #define __FMC_NAND_DISABLE_IT(__INSTANCE__, __BANK__, __INTERRUPT__) (((__BANK__) == FMC_NAND_BANK2)? ((__INSTANCE__)->SR2 &= ~(__INTERRUPT__)): \ ((__INSTANCE__)->SR3 &= ~(__INTERRUPT__))) /** * @brief Get flag status of the NAND device. * @param __INSTANCE__: FMC_NAND Instance * @param __BANK__: FMC_NAND Bank * @param __FLAG__: FMC_NAND flag * This parameter can be any combination of the following values: * @arg FMC_FLAG_RISING_EDGE: Interrupt rising edge flag. * @arg FMC_FLAG_LEVEL: Interrupt level edge flag. * @arg FMC_FLAG_FALLING_EDGE: Interrupt falling edge flag. * @arg FMC_FLAG_FEMPT: FIFO empty flag. * @retval The state of FLAG (SET or RESET). */ #define __FMC_NAND_GET_FLAG(__INSTANCE__, __BANK__, __FLAG__) (((__BANK__) == FMC_NAND_BANK2)? (((__INSTANCE__)->SR2 &(__FLAG__)) == (__FLAG__)): \ (((__INSTANCE__)->SR3 &(__FLAG__)) == (__FLAG__))) /** * @brief Clear flag status of the NAND device. * @param __INSTANCE__: FMC_NAND Instance * @param __BANK__: FMC_NAND Bank * @param __FLAG__: FMC_NAND flag * This parameter can be any combination of the following values: * @arg FMC_FLAG_RISING_EDGE: Interrupt rising edge flag. * @arg FMC_FLAG_LEVEL: Interrupt level edge flag. * @arg FMC_FLAG_FALLING_EDGE: Interrupt falling edge flag. * @arg FMC_FLAG_FEMPT: FIFO empty flag. * @retval None */ #define __FMC_NAND_CLEAR_FLAG(__INSTANCE__, __BANK__, __FLAG__) (((__BANK__) == FMC_NAND_BANK2)? ((__INSTANCE__)->SR2 &= ~(__FLAG__)): \ ((__INSTANCE__)->SR3 &= ~(__FLAG__))) #endif /* defined(STM32F446xx) || defined(STM32F469xx) || defined(STM32F479xx) */ #if defined(STM32F427xx) || defined(STM32F437xx) || defined(STM32F429xx) || defined(STM32F439xx) /** * @brief Enable the PCCARD device interrupt. * @param __INSTANCE__: FMC_PCCARD instance * @param __INTERRUPT__: FMC_PCCARD interrupt * This parameter can be any combination of the following values: * @arg FMC_IT_RISING_EDGE: Interrupt rising edge. * @arg FMC_IT_LEVEL: Interrupt level. * @arg FMC_IT_FALLING_EDGE: Interrupt falling edge. * @retval None */ #define __FMC_PCCARD_ENABLE_IT(__INSTANCE__, __INTERRUPT__) ((__INSTANCE__)->SR4 |= (__INTERRUPT__)) /** * @brief Disable the PCCARD device interrupt. * @param __INSTANCE__: FMC_PCCARD instance * @param __INTERRUPT__: FMC_PCCARD interrupt * This parameter can be any combination of the following values: * @arg FMC_IT_RISING_EDGE: Interrupt rising edge. * @arg FMC_IT_LEVEL: Interrupt level. * @arg FMC_IT_FALLING_EDGE: Interrupt falling edge. * @retval None */ #define __FMC_PCCARD_DISABLE_IT(__INSTANCE__, __INTERRUPT__) ((__INSTANCE__)->SR4 &= ~(__INTERRUPT__)) /** * @brief Get flag status of the PCCARD device. * @param __INSTANCE__: FMC_PCCARD instance * @param __FLAG__: FMC_PCCARD flag * This parameter can be any combination of the following values: * @arg FMC_FLAG_RISING_EDGE: Interrupt rising edge flag. * @arg FMC_FLAG_LEVEL: Interrupt level edge flag. * @arg FMC_FLAG_FALLING_EDGE: Interrupt falling edge flag. * @arg FMC_FLAG_FEMPT: FIFO empty flag. * @retval The state of FLAG (SET or RESET). */ #define __FMC_PCCARD_GET_FLAG(__INSTANCE__, __FLAG__) (((__INSTANCE__)->SR4 &(__FLAG__)) == (__FLAG__)) /** * @brief Clear flag status of the PCCARD device. * @param __INSTANCE__: FMC_PCCARD instance * @param __FLAG__: FMC_PCCARD flag * This parameter can be any combination of the following values: * @arg FMC_FLAG_RISING_EDGE: Interrupt rising edge flag. * @arg FMC_FLAG_LEVEL: Interrupt level edge flag. * @arg FMC_FLAG_FALLING_EDGE: Interrupt falling edge flag. * @arg FMC_FLAG_FEMPT: FIFO empty flag. * @retval None */ #define __FMC_PCCARD_CLEAR_FLAG(__INSTANCE__, __FLAG__) ((__INSTANCE__)->SR4 &= ~(__FLAG__)) #endif /* defined(STM32F427xx) || defined(STM32F437xx) || defined(STM32F429xx) || defined(STM32F439xx) */ /** * @brief Enable the SDRAM device interrupt. * @param __INSTANCE__: FMC_SDRAM instance * @param __INTERRUPT__: FMC_SDRAM interrupt * This parameter can be any combination of the following values: * @arg FMC_IT_REFRESH_ERROR: Interrupt refresh error * @retval None */ #define __FMC_SDRAM_ENABLE_IT(__INSTANCE__, __INTERRUPT__) ((__INSTANCE__)->SDRTR |= (__INTERRUPT__)) /** * @brief Disable the SDRAM device interrupt. * @param __INSTANCE__: FMC_SDRAM instance * @param __INTERRUPT__: FMC_SDRAM interrupt * This parameter can be any combination of the following values: * @arg FMC_IT_REFRESH_ERROR: Interrupt refresh error * @retval None */ #define __FMC_SDRAM_DISABLE_IT(__INSTANCE__, __INTERRUPT__) ((__INSTANCE__)->SDRTR &= ~(__INTERRUPT__)) /** * @brief Get flag status of the SDRAM device. * @param __INSTANCE__: FMC_SDRAM instance * @param __FLAG__: FMC_SDRAM flag * This parameter can be any combination of the following values: * @arg FMC_SDRAM_FLAG_REFRESH_IT: Interrupt refresh error. * @arg FMC_SDRAM_FLAG_BUSY: SDRAM busy flag. * @arg FMC_SDRAM_FLAG_REFRESH_ERROR: Refresh error flag. * @retval The state of FLAG (SET or RESET). */ #define __FMC_SDRAM_GET_FLAG(__INSTANCE__, __FLAG__) (((__INSTANCE__)->SDSR &(__FLAG__)) == (__FLAG__)) /** * @brief Clear flag status of the SDRAM device. * @param __INSTANCE__: FMC_SDRAM instance * @param __FLAG__: FMC_SDRAM flag * This parameter can be any combination of the following values: * @arg FMC_SDRAM_FLAG_REFRESH_ERROR * @retval None */ #define __FMC_SDRAM_CLEAR_FLAG(__INSTANCE__, __FLAG__) ((__INSTANCE__)->SDRTR |= (__FLAG__)) /** * @} */ /** @defgroup FSMC_LL_Assert_Macros FSMC Assert Macros * @{ */ #define IS_FMC_NORSRAM_BANK(BANK) (((BANK) == FMC_NORSRAM_BANK1) || \ ((BANK) == FMC_NORSRAM_BANK2) || \ ((BANK) == FMC_NORSRAM_BANK3) || \ ((BANK) == FMC_NORSRAM_BANK4)) #define IS_FMC_MUX(__MUX__) (((__MUX__) == FMC_DATA_ADDRESS_MUX_DISABLE) || \ ((__MUX__) == FMC_DATA_ADDRESS_MUX_ENABLE)) #define IS_FMC_MEMORY(__MEMORY__) (((__MEMORY__) == FMC_MEMORY_TYPE_SRAM) || \ ((__MEMORY__) == FMC_MEMORY_TYPE_PSRAM)|| \ ((__MEMORY__) == FMC_MEMORY_TYPE_NOR)) #define IS_FMC_NORSRAM_MEMORY_WIDTH(__WIDTH__) (((__WIDTH__) == FMC_NORSRAM_MEM_BUS_WIDTH_8) || \ ((__WIDTH__) == FMC_NORSRAM_MEM_BUS_WIDTH_16) || \ ((__WIDTH__) == FMC_NORSRAM_MEM_BUS_WIDTH_32)) #define IS_FMC_ACCESS_MODE(__MODE__) (((__MODE__) == FMC_ACCESS_MODE_A) || \ ((__MODE__) == FMC_ACCESS_MODE_B) || \ ((__MODE__) == FMC_ACCESS_MODE_C) || \ ((__MODE__) == FMC_ACCESS_MODE_D)) #define IS_FMC_NAND_BANK(BANK) (((BANK) == FMC_NAND_BANK2) || \ ((BANK) == FMC_NAND_BANK3)) #define IS_FMC_WAIT_FEATURE(FEATURE) (((FEATURE) == FMC_NAND_PCC_WAIT_FEATURE_DISABLE) || \ ((FEATURE) == FMC_NAND_PCC_WAIT_FEATURE_ENABLE)) #define IS_FMC_NAND_MEMORY_WIDTH(WIDTH) (((WIDTH) == FMC_NAND_PCC_MEM_BUS_WIDTH_8) || \ ((WIDTH) == FMC_NAND_PCC_MEM_BUS_WIDTH_16)) #define IS_FMC_ECC_STATE(STATE) (((STATE) == FMC_NAND_ECC_DISABLE) || \ ((STATE) == FMC_NAND_ECC_ENABLE)) #define IS_FMC_ECCPAGE_SIZE(SIZE) (((SIZE) == FMC_NAND_ECC_PAGE_SIZE_256BYTE) || \ ((SIZE) == FMC_NAND_ECC_PAGE_SIZE_512BYTE) || \ ((SIZE) == FMC_NAND_ECC_PAGE_SIZE_1024BYTE) || \ ((SIZE) == FMC_NAND_ECC_PAGE_SIZE_2048BYTE) || \ ((SIZE) == FMC_NAND_ECC_PAGE_SIZE_4096BYTE) || \ ((SIZE) == FMC_NAND_ECC_PAGE_SIZE_8192BYTE)) #define IS_FMC_TCLR_TIME(TIME) ((TIME) <= 255) #define IS_FMC_TAR_TIME(TIME) ((TIME) <= 255) #define IS_FMC_SETUP_TIME(TIME) ((TIME) <= 255) #define IS_FMC_WAIT_TIME(TIME) ((TIME) <= 255) #define IS_FMC_HOLD_TIME(TIME) ((TIME) <= 255) #define IS_FMC_HIZ_TIME(TIME) ((TIME) <= 255) #define IS_FMC_NORSRAM_DEVICE(__INSTANCE__) ((__INSTANCE__) == FMC_NORSRAM_DEVICE) #define IS_FMC_NORSRAM_EXTENDED_DEVICE(__INSTANCE__) ((__INSTANCE__) == FMC_NORSRAM_EXTENDED_DEVICE) #define IS_FMC_NAND_DEVICE(__INSTANCE__) ((__INSTANCE__) == FMC_NAND_DEVICE) #define IS_FMC_PCCARD_DEVICE(__INSTANCE__) ((__INSTANCE__) == FMC_PCCARD_DEVICE) #define IS_FMC_BURSTMODE(__STATE__) (((__STATE__) == FMC_BURST_ACCESS_MODE_DISABLE) || \ ((__STATE__) == FMC_BURST_ACCESS_MODE_ENABLE)) #define IS_FMC_WAIT_POLARITY(__POLARITY__) (((__POLARITY__) == FMC_WAIT_SIGNAL_POLARITY_LOW) || \ ((__POLARITY__) == FMC_WAIT_SIGNAL_POLARITY_HIGH)) #if defined(STM32F427xx) || defined(STM32F437xx) || defined(STM32F429xx) || defined(STM32F439xx) #define IS_FMC_WRAP_MODE(__MODE__) (((__MODE__) == FMC_WRAP_MODE_DISABLE) || \ ((__MODE__) == FMC_WRAP_MODE_ENABLE)) #endif /* STM32F427xx || STM32F437xx || STM32F429xx || STM32F439xx */ #define IS_FMC_WAIT_SIGNAL_ACTIVE(__ACTIVE__) (((__ACTIVE__) == FMC_WAIT_TIMING_BEFORE_WS) || \ ((__ACTIVE__) == FMC_WAIT_TIMING_DURING_WS)) #define IS_FMC_WRITE_OPERATION(__OPERATION__) (((__OPERATION__) == FMC_WRITE_OPERATION_DISABLE) || \ ((__OPERATION__) == FMC_WRITE_OPERATION_ENABLE)) #define IS_FMC_WAITE_SIGNAL(__SIGNAL__) (((__SIGNAL__) == FMC_WAIT_SIGNAL_DISABLE) || \ ((__SIGNAL__) == FMC_WAIT_SIGNAL_ENABLE)) #define IS_FMC_EXTENDED_MODE(__MODE__) (((__MODE__) == FMC_EXTENDED_MODE_DISABLE) || \ ((__MODE__) == FMC_EXTENDED_MODE_ENABLE)) #define IS_FMC_ASYNWAIT(__STATE__) (((__STATE__) == FMC_ASYNCHRONOUS_WAIT_DISABLE) || \ ((__STATE__) == FMC_ASYNCHRONOUS_WAIT_ENABLE)) #define IS_FMC_WRITE_BURST(__BURST__) (((__BURST__) == FMC_WRITE_BURST_DISABLE) || \ ((__BURST__) == FMC_WRITE_BURST_ENABLE)) #define IS_FMC_CONTINOUS_CLOCK(CCLOCK) (((CCLOCK) == FMC_CONTINUOUS_CLOCK_SYNC_ONLY) || \ ((CCLOCK) == FMC_CONTINUOUS_CLOCK_SYNC_ASYNC)) #define IS_FMC_ADDRESS_SETUP_TIME(__TIME__) ((__TIME__) <= 15) #define IS_FMC_ADDRESS_HOLD_TIME(__TIME__) (((__TIME__) > 0) && ((__TIME__) <= 15)) #define IS_FMC_DATASETUP_TIME(__TIME__) (((__TIME__) > 0) && ((__TIME__) <= 255)) #define IS_FMC_TURNAROUND_TIME(__TIME__) ((__TIME__) <= 15) #define IS_FMC_DATA_LATENCY(__LATENCY__) (((__LATENCY__) > 1) && ((__LATENCY__) <= 17)) #define IS_FMC_CLK_DIV(DIV) (((DIV) > 1) && ((DIV) <= 16)) #define IS_FMC_SDRAM_BANK(BANK) (((BANK) == FMC_SDRAM_BANK1) || \ ((BANK) == FMC_SDRAM_BANK2)) #define IS_FMC_COLUMNBITS_NUMBER(COLUMN) (((COLUMN) == FMC_SDRAM_COLUMN_BITS_NUM_8) || \ ((COLUMN) == FMC_SDRAM_COLUMN_BITS_NUM_9) || \ ((COLUMN) == FMC_SDRAM_COLUMN_BITS_NUM_10) || \ ((COLUMN) == FMC_SDRAM_COLUMN_BITS_NUM_11)) #define IS_FMC_ROWBITS_NUMBER(ROW) (((ROW) == FMC_SDRAM_ROW_BITS_NUM_11) || \ ((ROW) == FMC_SDRAM_ROW_BITS_NUM_12) || \ ((ROW) == FMC_SDRAM_ROW_BITS_NUM_13)) #define IS_FMC_SDMEMORY_WIDTH(WIDTH) (((WIDTH) == FMC_SDRAM_MEM_BUS_WIDTH_8) || \ ((WIDTH) == FMC_SDRAM_MEM_BUS_WIDTH_16) || \ ((WIDTH) == FMC_SDRAM_MEM_BUS_WIDTH_32)) #define IS_FMC_INTERNALBANK_NUMBER(NUMBER) (((NUMBER) == FMC_SDRAM_INTERN_BANKS_NUM_2) || \ ((NUMBER) == FMC_SDRAM_INTERN_BANKS_NUM_4)) #define IS_FMC_CAS_LATENCY(LATENCY) (((LATENCY) == FMC_SDRAM_CAS_LATENCY_1) || \ ((LATENCY) == FMC_SDRAM_CAS_LATENCY_2) || \ ((LATENCY) == FMC_SDRAM_CAS_LATENCY_3)) #define IS_FMC_SDCLOCK_PERIOD(PERIOD) (((PERIOD) == FMC_SDRAM_CLOCK_DISABLE) || \ ((PERIOD) == FMC_SDRAM_CLOCK_PERIOD_2) || \ ((PERIOD) == FMC_SDRAM_CLOCK_PERIOD_3)) #define IS_FMC_READ_BURST(RBURST) (((RBURST) == FMC_SDRAM_RBURST_DISABLE) || \ ((RBURST) == FMC_SDRAM_RBURST_ENABLE)) #define IS_FMC_READPIPE_DELAY(DELAY) (((DELAY) == FMC_SDRAM_RPIPE_DELAY_0) || \ ((DELAY) == FMC_SDRAM_RPIPE_DELAY_1) || \ ((DELAY) == FMC_SDRAM_RPIPE_DELAY_2)) #define IS_FMC_LOADTOACTIVE_DELAY(DELAY) (((DELAY) > 0) && ((DELAY) <= 16)) #define IS_FMC_EXITSELFREFRESH_DELAY(DELAY) (((DELAY) > 0) && ((DELAY) <= 16)) #define IS_FMC_SELFREFRESH_TIME(TIME) (((TIME) > 0) && ((TIME) <= 16)) #define IS_FMC_ROWCYCLE_DELAY(DELAY) (((DELAY) > 0) && ((DELAY) <= 16)) #define IS_FMC_WRITE_RECOVERY_TIME(TIME) (((TIME) > 0) && ((TIME) <= 16)) #define IS_FMC_RP_DELAY(DELAY) (((DELAY) > 0) && ((DELAY) <= 16)) #define IS_FMC_RCD_DELAY(DELAY) (((DELAY) > 0) && ((DELAY) <= 16)) #define IS_FMC_COMMAND_MODE(COMMAND) (((COMMAND) == FMC_SDRAM_CMD_NORMAL_MODE) || \ ((COMMAND) == FMC_SDRAM_CMD_CLK_ENABLE) || \ ((COMMAND) == FMC_SDRAM_CMD_PALL) || \ ((COMMAND) == FMC_SDRAM_CMD_AUTOREFRESH_MODE) || \ ((COMMAND) == FMC_SDRAM_CMD_LOAD_MODE) || \ ((COMMAND) == FMC_SDRAM_CMD_SELFREFRESH_MODE) || \ ((COMMAND) == FMC_SDRAM_CMD_POWERDOWN_MODE)) #define IS_FMC_COMMAND_TARGET(TARGET) (((TARGET) == FMC_SDRAM_CMD_TARGET_BANK1) || \ ((TARGET) == FMC_SDRAM_CMD_TARGET_BANK2) || \ ((TARGET) == FMC_SDRAM_CMD_TARGET_BANK1_2)) #define IS_FMC_AUTOREFRESH_NUMBER(NUMBER) (((NUMBER) > 0) && ((NUMBER) <= 16)) #define IS_FMC_MODE_REGISTER(CONTENT) ((CONTENT) <= 8191) #define IS_FMC_REFRESH_RATE(RATE) ((RATE) <= 8191) #define IS_FMC_SDRAM_DEVICE(INSTANCE) ((INSTANCE) == FMC_SDRAM_DEVICE) #define IS_FMC_WRITE_PROTECTION(WRITE) (((WRITE) == FMC_SDRAM_WRITE_PROTECTION_DISABLE) || \ ((WRITE) == FMC_SDRAM_WRITE_PROTECTION_ENABLE)) #if defined (STM32F446xx) || defined(STM32F469xx) || defined(STM32F479xx) #define IS_FMC_PAGESIZE(SIZE) (((SIZE) == FMC_PAGE_SIZE_NONE) || \ ((SIZE) == FMC_PAGE_SIZE_128) || \ ((SIZE) == FMC_PAGE_SIZE_256) || \ ((SIZE) == FMC_PAGE_SIZE_1024)) #define IS_FMC_WRITE_FIFO(FIFO) (((FIFO) == FMC_WRITE_FIFO_DISABLE) || \ ((FIFO) == FMC_WRITE_FIFO_ENABLE)) #endif /* STM32F446xx || STM32F469xx || STM32F479xx */ /** * @} */ /** * @} */ /* Private functions ---------------------------------------------------------*/ /** @defgroup FMC_LL_Private_Functions FMC LL Private Functions * @{ */ /** @defgroup FMC_LL_NORSRAM NOR SRAM * @{ */ /** @defgroup FMC_LL_NORSRAM_Private_Functions_Group1 NOR SRAM Initialization/de-initialization functions * @{ */ HAL_StatusTypeDef FMC_NORSRAM_Init(FMC_NORSRAM_TypeDef *Device, FMC_NORSRAM_InitTypeDef *Init); HAL_StatusTypeDef FMC_NORSRAM_Timing_Init(FMC_NORSRAM_TypeDef *Device, FMC_NORSRAM_TimingTypeDef *Timing, uint32_t Bank); HAL_StatusTypeDef FMC_NORSRAM_Extended_Timing_Init(FMC_NORSRAM_EXTENDED_TypeDef *Device, FMC_NORSRAM_TimingTypeDef *Timing, uint32_t Bank, uint32_t ExtendedMode); HAL_StatusTypeDef FMC_NORSRAM_DeInit(FMC_NORSRAM_TypeDef *Device, FMC_NORSRAM_EXTENDED_TypeDef *ExDevice, uint32_t Bank); /** * @} */ /** @defgroup FMC_LL_NORSRAM_Private_Functions_Group2 NOR SRAM Control functions * @{ */ HAL_StatusTypeDef FMC_NORSRAM_WriteOperation_Enable(FMC_NORSRAM_TypeDef *Device, uint32_t Bank); HAL_StatusTypeDef FMC_NORSRAM_WriteOperation_Disable(FMC_NORSRAM_TypeDef *Device, uint32_t Bank); /** * @} */ /** * @} */ /** @defgroup FMC_LL_NAND NAND * @{ */ /** @defgroup FMC_LL_NAND_Private_Functions_Group1 NAND Initialization/de-initialization functions * @{ */ HAL_StatusTypeDef FMC_NAND_Init(FMC_NAND_TypeDef *Device, FMC_NAND_InitTypeDef *Init); HAL_StatusTypeDef FMC_NAND_CommonSpace_Timing_Init(FMC_NAND_TypeDef *Device, FMC_NAND_PCC_TimingTypeDef *Timing, uint32_t Bank); HAL_StatusTypeDef FMC_NAND_AttributeSpace_Timing_Init(FMC_NAND_TypeDef *Device, FMC_NAND_PCC_TimingTypeDef *Timing, uint32_t Bank); HAL_StatusTypeDef FMC_NAND_DeInit(FMC_NAND_TypeDef *Device, uint32_t Bank); /** * @} */ /** @defgroup FMC_LL_NAND_Private_Functions_Group2 NAND Control functions * @{ */ HAL_StatusTypeDef FMC_NAND_ECC_Enable(FMC_NAND_TypeDef *Device, uint32_t Bank); HAL_StatusTypeDef FMC_NAND_ECC_Disable(FMC_NAND_TypeDef *Device, uint32_t Bank); HAL_StatusTypeDef FMC_NAND_GetECC(FMC_NAND_TypeDef *Device, uint32_t *ECCval, uint32_t Bank, uint32_t Timeout); /** * @} */ /** * @} */ #if defined(STM32F427xx) || defined(STM32F437xx) || defined(STM32F429xx) || defined(STM32F439xx) /** @defgroup FMC_LL_PCCARD PCCARD * @{ */ /** @defgroup FMC_LL_PCCARD_Private_Functions_Group1 PCCARD Initialization/de-initialization functions * @{ */ HAL_StatusTypeDef FMC_PCCARD_Init(FMC_PCCARD_TypeDef *Device, FMC_PCCARD_InitTypeDef *Init); HAL_StatusTypeDef FMC_PCCARD_CommonSpace_Timing_Init(FMC_PCCARD_TypeDef *Device, FMC_NAND_PCC_TimingTypeDef *Timing); HAL_StatusTypeDef FMC_PCCARD_AttributeSpace_Timing_Init(FMC_PCCARD_TypeDef *Device, FMC_NAND_PCC_TimingTypeDef *Timing); HAL_StatusTypeDef FMC_PCCARD_IOSpace_Timing_Init(FMC_PCCARD_TypeDef *Device, FMC_NAND_PCC_TimingTypeDef *Timing); HAL_StatusTypeDef FMC_PCCARD_DeInit(FMC_PCCARD_TypeDef *Device); /** * @} */ /** * @} */ #endif /* STM32F427xx || STM32F437xx || STM32F429xx || STM32F439xx */ /** @defgroup FMC_LL_SDRAM SDRAM * @{ */ /** @defgroup FMC_LL_SDRAM_Private_Functions_Group1 SDRAM Initialization/de-initialization functions * @{ */ HAL_StatusTypeDef FMC_SDRAM_Init(FMC_SDRAM_TypeDef *Device, FMC_SDRAM_InitTypeDef *Init); HAL_StatusTypeDef FMC_SDRAM_Timing_Init(FMC_SDRAM_TypeDef *Device, FMC_SDRAM_TimingTypeDef *Timing, uint32_t Bank); HAL_StatusTypeDef FMC_SDRAM_DeInit(FMC_SDRAM_TypeDef *Device, uint32_t Bank); /** * @} */ /** @defgroup FMC_LL_SDRAM_Private_Functions_Group2 SDRAM Control functions * @{ */ HAL_StatusTypeDef FMC_SDRAM_WriteProtection_Enable(FMC_SDRAM_TypeDef *Device, uint32_t Bank); HAL_StatusTypeDef FMC_SDRAM_WriteProtection_Disable(FMC_SDRAM_TypeDef *Device, uint32_t Bank); HAL_StatusTypeDef FMC_SDRAM_SendCommand(FMC_SDRAM_TypeDef *Device, FMC_SDRAM_CommandTypeDef *Command, uint32_t Timeout); HAL_StatusTypeDef FMC_SDRAM_ProgramRefreshRate(FMC_SDRAM_TypeDef *Device, uint32_t RefreshRate); HAL_StatusTypeDef FMC_SDRAM_SetAutoRefreshNumber(FMC_SDRAM_TypeDef *Device, uint32_t AutoRefreshNumber); uint32_t FMC_SDRAM_GetModeStatus(FMC_SDRAM_TypeDef *Device, uint32_t Bank); /** * @} */ /** * @} */ /** * @} */ #endif /* STM32F427xx || STM32F437xx || STM32F429xx || STM32F439xx || STM32F446xx || STM32F469xx || STM32F479xx */ /** * @} */ /** * @} */ #ifdef __cplusplus } #endif #endif /* __STM32F4xx_LL_FMC_H */ /************************ (C) COPYRIGHT STMicroelectronics *****END OF FILE****/ ================================================ FILE: Zelig/mbed/TARGET_NUCLEO_F401RE/stm32f4xx_ll_fsmc.h ================================================ /** ****************************************************************************** * @file stm32f4xx_ll_fsmc.h * @author MCD Application Team * @version V1.4.1 * @date 09-October-2015 * @brief Header file of FSMC HAL module. ****************************************************************************** * @attention * *

© COPYRIGHT(c) 2015 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. * ****************************************************************************** */ /* Define to prevent recursive inclusion -------------------------------------*/ #ifndef __STM32F4xx_LL_FSMC_H #define __STM32F4xx_LL_FSMC_H #ifdef __cplusplus extern "C" { #endif /* Includes ------------------------------------------------------------------*/ #include "stm32f4xx_hal_def.h" /** @addtogroup STM32F4xx_HAL_Driver * @{ */ /** @addtogroup FSMC_LL * @{ */ #if defined(STM32F405xx) || defined(STM32F415xx) || defined(STM32F407xx) || defined(STM32F417xx) /* Private types -------------------------------------------------------------*/ /** @defgroup FSMC_LL_Private_Types FSMC Private Types * @{ */ /** * @brief FSMC NORSRAM Configuration Structure definition */ typedef struct { uint32_t NSBank; /*!< Specifies the NORSRAM memory device that will be used. This parameter can be a value of @ref FSMC_NORSRAM_Bank */ uint32_t DataAddressMux; /*!< Specifies whether the address and data values are multiplexed on the data bus or not. This parameter can be a value of @ref FSMC_Data_Address_Bus_Multiplexing */ uint32_t MemoryType; /*!< Specifies the type of external memory attached to the corresponding memory device. This parameter can be a value of @ref FSMC_Memory_Type */ uint32_t MemoryDataWidth; /*!< Specifies the external memory device width. This parameter can be a value of @ref FSMC_NORSRAM_Data_Width */ uint32_t BurstAccessMode; /*!< Enables or disables the burst access mode for Flash memory, valid only with synchronous burst Flash memories. This parameter can be a value of @ref FSMC_Burst_Access_Mode */ uint32_t WaitSignalPolarity; /*!< Specifies the wait signal polarity, valid only when accessing the Flash memory in burst mode. This parameter can be a value of @ref FSMC_Wait_Signal_Polarity */ uint32_t WrapMode; /*!< Enables or disables the Wrapped burst access mode for Flash memory, valid only when accessing Flash memories in burst mode. This parameter can be a value of @ref FSMC_Wrap_Mode */ uint32_t WaitSignalActive; /*!< Specifies if the wait signal is asserted by the memory one clock cycle before the wait state or during the wait state, valid only when accessing memories in burst mode. This parameter can be a value of @ref FSMC_Wait_Timing */ uint32_t WriteOperation; /*!< Enables or disables the write operation in the selected device by the FSMC. This parameter can be a value of @ref FSMC_Write_Operation */ uint32_t WaitSignal; /*!< Enables or disables the wait state insertion via wait signal, valid for Flash memory access in burst mode. This parameter can be a value of @ref FSMC_Wait_Signal */ uint32_t ExtendedMode; /*!< Enables or disables the extended mode. This parameter can be a value of @ref FSMC_Extended_Mode */ uint32_t AsynchronousWait; /*!< Enables or disables wait signal during asynchronous transfers, valid only with asynchronous Flash memories. This parameter can be a value of @ref FSMC_AsynchronousWait */ uint32_t WriteBurst; /*!< Enables or disables the write burst operation. This parameter can be a value of @ref FSMC_Write_Burst */ }FSMC_NORSRAM_InitTypeDef; /** * @brief FSMC NORSRAM Timing parameters structure definition */ typedef struct { uint32_t AddressSetupTime; /*!< Defines the number of HCLK cycles to configure the duration of the address setup time. This parameter can be a value between Min_Data = 0 and Max_Data = 15. @note This parameter is not used with synchronous NOR Flash memories. */ uint32_t AddressHoldTime; /*!< Defines the number of HCLK cycles to configure the duration of the address hold time. This parameter can be a value between Min_Data = 1 and Max_Data = 15. @note This parameter is not used with synchronous NOR Flash memories. */ uint32_t DataSetupTime; /*!< Defines the number of HCLK cycles to configure the duration of the data setup time. This parameter can be a value between Min_Data = 1 and Max_Data = 255. @note This parameter is used for SRAMs, ROMs and asynchronous multiplexed NOR Flash memories. */ uint32_t BusTurnAroundDuration; /*!< Defines the number of HCLK cycles to configure the duration of the bus turnaround. This parameter can be a value between Min_Data = 0 and Max_Data = 15. @note This parameter is only used for multiplexed NOR Flash memories. */ uint32_t CLKDivision; /*!< Defines the period of CLK clock output signal, expressed in number of HCLK cycles. This parameter can be a value between Min_Data = 2 and Max_Data = 16. @note This parameter is not used for asynchronous NOR Flash, SRAM or ROM accesses. */ uint32_t DataLatency; /*!< Defines the number of memory clock cycles to issue to the memory before getting the first data. The parameter value depends on the memory type as shown below: - It must be set to 0 in case of a CRAM - It is don't care in asynchronous NOR, SRAM or ROM accesses - It may assume a value between Min_Data = 2 and Max_Data = 17 in NOR Flash memories with synchronous burst mode enable */ uint32_t AccessMode; /*!< Specifies the asynchronous access mode. This parameter can be a value of @ref FSMC_Access_Mode */ }FSMC_NORSRAM_TimingTypeDef; #if defined(STM32F405xx) || defined(STM32F415xx) || defined(STM32F407xx) || defined(STM32F417xx) /** * @brief FSMC NAND Configuration Structure definition */ typedef struct { uint32_t NandBank; /*!< Specifies the NAND memory device that will be used. This parameter can be a value of @ref FSMC_NAND_Bank */ uint32_t Waitfeature; /*!< Enables or disables the Wait feature for the NAND Memory device. This parameter can be any value of @ref FSMC_Wait_feature */ uint32_t MemoryDataWidth; /*!< Specifies the external memory device width. This parameter can be any value of @ref FSMC_NAND_Data_Width */ uint32_t EccComputation; /*!< Enables or disables the ECC computation. This parameter can be any value of @ref FSMC_ECC */ uint32_t ECCPageSize; /*!< Defines the page size for the extended ECC. This parameter can be any value of @ref FSMC_ECC_Page_Size */ uint32_t TCLRSetupTime; /*!< Defines the number of HCLK cycles to configure the delay between CLE low and RE low. This parameter can be a value between Min_Data = 0 and Max_Data = 255 */ uint32_t TARSetupTime; /*!< Defines the number of HCLK cycles to configure the delay between ALE low and RE low. This parameter can be a number between Min_Data = 0 and Max_Data = 255 */ }FSMC_NAND_InitTypeDef; /** * @brief FSMC NAND/PCCARD Timing parameters structure definition */ typedef struct { uint32_t SetupTime; /*!< Defines the number of HCLK cycles to setup address before the command assertion for NAND-Flash read or write access to common/Attribute or I/O memory space (depending on the memory space timing to be configured). This parameter can be a value between Min_Data = 0 and Max_Data = 255 */ uint32_t WaitSetupTime; /*!< Defines the minimum number of HCLK cycles to assert the command for NAND-Flash read or write access to common/Attribute or I/O memory space (depending on the memory space timing to be configured). This parameter can be a number between Min_Data = 0 and Max_Data = 255 */ uint32_t HoldSetupTime; /*!< Defines the number of HCLK clock cycles to hold address (and data for write access) after the command de-assertion for NAND-Flash read or write access to common/Attribute or I/O memory space (depending on the memory space timing to be configured). This parameter can be a number between Min_Data = 0 and Max_Data = 255 */ uint32_t HiZSetupTime; /*!< Defines the number of HCLK clock cycles during which the data bus is kept in HiZ after the start of a NAND-Flash write access to common/Attribute or I/O memory space (depending on the memory space timing to be configured). This parameter can be a number between Min_Data = 0 and Max_Data = 255 */ }FSMC_NAND_PCC_TimingTypeDef; /** * @brief FSMC NAND Configuration Structure definition */ typedef struct { uint32_t Waitfeature; /*!< Enables or disables the Wait feature for the PCCARD Memory device. This parameter can be any value of @ref FSMC_Wait_feature */ uint32_t TCLRSetupTime; /*!< Defines the number of HCLK cycles to configure the delay between CLE low and RE low. This parameter can be a value between Min_Data = 0 and Max_Data = 255 */ uint32_t TARSetupTime; /*!< Defines the number of HCLK cycles to configure the delay between ALE low and RE low. This parameter can be a number between Min_Data = 0 and Max_Data = 255 */ }FSMC_PCCARD_InitTypeDef; /** * @} */ #endif /* STM32F405xx || STM32F415xx || STM32F407xx || STM32F417xx */ /* Private constants ---------------------------------------------------------*/ /** @defgroup FSMC_LL_Private_Constants FSMC Private Constants * @{ */ /** @defgroup FSMC_LL_NOR_SRAM_Controller FSMC NOR/SRAM Controller * @{ */ /** @defgroup FSMC_NORSRAM_Bank FSMC NOR/SRAM Bank * @{ */ #define FSMC_NORSRAM_BANK1 ((uint32_t)0x00000000) #define FSMC_NORSRAM_BANK2 ((uint32_t)0x00000002) #define FSMC_NORSRAM_BANK3 ((uint32_t)0x00000004) #define FSMC_NORSRAM_BANK4 ((uint32_t)0x00000006) /** * @} */ /** @defgroup FSMC_Data_Address_Bus_Multiplexing FSMC Data Address Bus Multiplexing * @{ */ #define FSMC_DATA_ADDRESS_MUX_DISABLE ((uint32_t)0x00000000) #define FSMC_DATA_ADDRESS_MUX_ENABLE ((uint32_t)0x00000002) /** * @} */ /** @defgroup FSMC_Memory_Type FSMC Memory Type * @{ */ #define FSMC_MEMORY_TYPE_SRAM ((uint32_t)0x00000000) #define FSMC_MEMORY_TYPE_PSRAM ((uint32_t)0x00000004) #define FSMC_MEMORY_TYPE_NOR ((uint32_t)0x00000008) /** * @} */ /** @defgroup FSMC_NORSRAM_Data_Width FSMC NOR/SRAM Data Width * @{ */ #define FSMC_NORSRAM_MEM_BUS_WIDTH_8 ((uint32_t)0x00000000) #define FSMC_NORSRAM_MEM_BUS_WIDTH_16 ((uint32_t)0x00000010) #define FSMC_NORSRAM_MEM_BUS_WIDTH_32 ((uint32_t)0x00000020) /** * @} */ /** @defgroup FSMC_NORSRAM_Flash_Access FSMC NOR/SRAM Flash Access * @{ */ #define FSMC_NORSRAM_FLASH_ACCESS_ENABLE ((uint32_t)0x00000040) #define FSMC_NORSRAM_FLASH_ACCESS_DISABLE ((uint32_t)0x00000000) /** * @} */ /** @defgroup FSMC_Burst_Access_Mode FSMC Burst Access Mode * @{ */ #define FSMC_BURST_ACCESS_MODE_DISABLE ((uint32_t)0x00000000) #define FSMC_BURST_ACCESS_MODE_ENABLE ((uint32_t)0x00000100) /** * @} */ /** @defgroup FSMC_Wait_Signal_Polarity FSMC Wait Signal Polarity * @{ */ #define FSMC_WAIT_SIGNAL_POLARITY_LOW ((uint32_t)0x00000000) #define FSMC_WAIT_SIGNAL_POLARITY_HIGH ((uint32_t)0x00000200) /** * @} */ /** @defgroup FSMC_Wrap_Mode FSMC Wrap Mode * @{ */ #define FSMC_WRAP_MODE_DISABLE ((uint32_t)0x00000000) #define FSMC_WRAP_MODE_ENABLE ((uint32_t)0x00000400) /** * @} */ /** @defgroup FSMC_Wait_Timing FSMC Wait Timing * @{ */ #define FSMC_WAIT_TIMING_BEFORE_WS ((uint32_t)0x00000000) #define FSMC_WAIT_TIMING_DURING_WS ((uint32_t)0x00000800) /** * @} */ /** @defgroup FSMC_Write_Operation FSMC Write Operation * @{ */ #define FSMC_WRITE_OPERATION_DISABLE ((uint32_t)0x00000000) #define FSMC_WRITE_OPERATION_ENABLE ((uint32_t)0x00001000) /** * @} */ /** @defgroup FSMC_Wait_Signal FSMC Wait Signal * @{ */ #define FSMC_WAIT_SIGNAL_DISABLE ((uint32_t)0x00000000) #define FSMC_WAIT_SIGNAL_ENABLE ((uint32_t)0x00002000) /** * @} */ /** @defgroup FSMC_Extended_Mode FSMC Extended Mode * @{ */ #define FSMC_EXTENDED_MODE_DISABLE ((uint32_t)0x00000000) #define FSMC_EXTENDED_MODE_ENABLE ((uint32_t)0x00004000) /** * @} */ /** @defgroup FSMC_AsynchronousWait FSMC Asynchronous Wait * @{ */ #define FSMC_ASYNCHRONOUS_WAIT_DISABLE ((uint32_t)0x00000000) #define FSMC_ASYNCHRONOUS_WAIT_ENABLE ((uint32_t)0x00008000) /** * @} */ /** @defgroup FSMC_Write_Burst FSMC Write Burst * @{ */ #define FSMC_WRITE_BURST_DISABLE ((uint32_t)0x00000000) #define FSMC_WRITE_BURST_ENABLE ((uint32_t)0x00080000) /** * @} */ /** @defgroup FSMC_Continous_Clock FSMC Continous Clock * @{ */ #define FSMC_CONTINUOUS_CLOCK_SYNC_ONLY ((uint32_t)0x00000000) #define FSMC_CONTINUOUS_CLOCK_SYNC_ASYNC ((uint32_t)0x00100000) /** * @} */ /** @defgroup FSMC_Access_Mode FSMC Access Mode * @{ */ #define FSMC_ACCESS_MODE_A ((uint32_t)0x00000000) #define FSMC_ACCESS_MODE_B ((uint32_t)0x10000000) #define FSMC_ACCESS_MODE_C ((uint32_t)0x20000000) #define FSMC_ACCESS_MODE_D ((uint32_t)0x30000000) /** * @} */ /** * @} */ #if defined(STM32F405xx) || defined(STM32F415xx) || defined(STM32F407xx) || defined(STM32F417xx) /** @defgroup FSMC_LL_NAND_Controller FSMC NAND and PCCARD Controller * @{ */ /** @defgroup FSMC_NAND_Bank FSMC NAND Bank * @{ */ #define FSMC_NAND_BANK2 ((uint32_t)0x00000010) #define FSMC_NAND_BANK3 ((uint32_t)0x00000100) /** * @} */ /** @defgroup FSMC_Wait_feature FSMC Wait feature * @{ */ #define FSMC_NAND_PCC_WAIT_FEATURE_DISABLE ((uint32_t)0x00000000) #define FSMC_NAND_PCC_WAIT_FEATURE_ENABLE ((uint32_t)0x00000002) /** * @} */ /** @defgroup FSMC_PCR_Memory_Type FSMC PCR Memory Type * @{ */ #define FSMC_PCR_MEMORY_TYPE_PCCARD ((uint32_t)0x00000000) #define FSMC_PCR_MEMORY_TYPE_NAND ((uint32_t)0x00000008) /** * @} */ /** @defgroup FSMC_NAND_Data_Width FSMC NAND Data Width * @{ */ #define FSMC_NAND_PCC_MEM_BUS_WIDTH_8 ((uint32_t)0x00000000) #define FSMC_NAND_PCC_MEM_BUS_WIDTH_16 ((uint32_t)0x00000010) /** * @} */ /** @defgroup FSMC_ECC FSMC ECC * @{ */ #define FSMC_NAND_ECC_DISABLE ((uint32_t)0x00000000) #define FSMC_NAND_ECC_ENABLE ((uint32_t)0x00000040) /** * @} */ /** @defgroup FSMC_ECC_Page_Size FSMC ECC Page Size * @{ */ #define FSMC_NAND_ECC_PAGE_SIZE_256BYTE ((uint32_t)0x00000000) #define FSMC_NAND_ECC_PAGE_SIZE_512BYTE ((uint32_t)0x00020000) #define FSMC_NAND_ECC_PAGE_SIZE_1024BYTE ((uint32_t)0x00040000) #define FSMC_NAND_ECC_PAGE_SIZE_2048BYTE ((uint32_t)0x00060000) #define FSMC_NAND_ECC_PAGE_SIZE_4096BYTE ((uint32_t)0x00080000) #define FSMC_NAND_ECC_PAGE_SIZE_8192BYTE ((uint32_t)0x000A0000) /** * @} */ /** * @} */ #endif /* STM32F405xx || STM32F415xx || STM32F407xx || STM32F417xx */ /** @defgroup FSMC_LL_Interrupt_definition FSMC Interrupt definition * @{ */ #define FSMC_IT_RISING_EDGE ((uint32_t)0x00000008) #define FSMC_IT_LEVEL ((uint32_t)0x00000010) #define FSMC_IT_FALLING_EDGE ((uint32_t)0x00000020) #define FSMC_IT_REFRESH_ERROR ((uint32_t)0x00004000) /** * @} */ /** @defgroup FSMC_LL_Flag_definition FSMC Flag definition * @{ */ #define FSMC_FLAG_RISING_EDGE ((uint32_t)0x00000001) #define FSMC_FLAG_LEVEL ((uint32_t)0x00000002) #define FSMC_FLAG_FALLING_EDGE ((uint32_t)0x00000004) #define FSMC_FLAG_FEMPT ((uint32_t)0x00000040) /** * @} */ /** @defgroup FSMC_LL_Alias_definition FSMC Alias definition * @{ */ #define FSMC_NORSRAM_TypeDef FSMC_Bank1_TypeDef #define FSMC_NORSRAM_EXTENDED_TypeDef FSMC_Bank1E_TypeDef #if defined(STM32F405xx) || defined(STM32F415xx) || defined(STM32F407xx) || defined(STM32F417xx) #define FSMC_NAND_TypeDef FSMC_Bank2_3_TypeDef #define FSMC_PCCARD_TypeDef FSMC_Bank4_TypeDef #endif /* STM32F405xx || STM32F415xx || STM32F407xx || STM32F417xx */ #define FSMC_NORSRAM_DEVICE FSMC_Bank1 #define FSMC_NORSRAM_EXTENDED_DEVICE FSMC_Bank1E #if defined(STM32F405xx) || defined(STM32F415xx) || defined(STM32F407xx) || defined(STM32F417xx) #define FSMC_NAND_DEVICE FSMC_Bank2_3 #define FSMC_PCCARD_DEVICE FSMC_Bank4 #endif /* STM32F405xx || STM32F415xx || STM32F407xx || STM32F417xx */ #define FMC_NORSRAM_TypeDef FSMC_NORSRAM_TypeDef #define FMC_NORSRAM_EXTENDED_TypeDef FSMC_NORSRAM_EXTENDED_TypeDef #define FMC_NORSRAM_InitTypeDef FSMC_NORSRAM_InitTypeDef #define FMC_NORSRAM_TimingTypeDef FSMC_NORSRAM_TimingTypeDef #define FMC_NORSRAM_Init FSMC_NORSRAM_Init #define FMC_NORSRAM_Timing_Init FSMC_NORSRAM_Timing_Init #define FMC_NORSRAM_Extended_Timing_Init FSMC_NORSRAM_Extended_Timing_Init #define FMC_NORSRAM_DeInit FSMC_NORSRAM_DeInit #define FMC_NORSRAM_WriteOperation_Enable FSMC_NORSRAM_WriteOperation_Enable #define FMC_NORSRAM_WriteOperation_Disable FSMC_NORSRAM_WriteOperation_Disable #define __FMC_NORSRAM_ENABLE __FSMC_NORSRAM_ENABLE #define __FMC_NORSRAM_DISABLE __FSMC_NORSRAM_DISABLE #if defined(STM32F405xx) || defined(STM32F415xx) || defined(STM32F407xx) || defined(STM32F417xx) #define FMC_NAND_InitTypeDef FSMC_NAND_InitTypeDef #define FMC_PCCARD_InitTypeDef FSMC_PCCARD_InitTypeDef #define FMC_NAND_PCC_TimingTypeDef FSMC_NAND_PCC_TimingTypeDef #define FMC_NAND_Init FSMC_NAND_Init #define FMC_NAND_CommonSpace_Timing_Init FSMC_NAND_CommonSpace_Timing_Init #define FMC_NAND_AttributeSpace_Timing_Init FSMC_NAND_AttributeSpace_Timing_Init #define FMC_NAND_DeInit FSMC_NAND_DeInit #define FMC_NAND_ECC_Enable FSMC_NAND_ECC_Enable #define FMC_NAND_ECC_Disable FSMC_NAND_ECC_Disable #define FMC_NAND_GetECC FSMC_NAND_GetECC #define FMC_PCCARD_Init FSMC_PCCARD_Init #define FMC_PCCARD_CommonSpace_Timing_Init FSMC_PCCARD_CommonSpace_Timing_Init #define FMC_PCCARD_AttributeSpace_Timing_Init FSMC_PCCARD_AttributeSpace_Timing_Init #define FMC_PCCARD_IOSpace_Timing_Init FSMC_PCCARD_IOSpace_Timing_Init #define FMC_PCCARD_DeInit FSMC_PCCARD_DeInit #define __FMC_NAND_ENABLE __FSMC_NAND_ENABLE #define __FMC_NAND_DISABLE __FSMC_NAND_DISABLE #define __FMC_PCCARD_ENABLE __FSMC_PCCARD_ENABLE #define __FMC_PCCARD_DISABLE __FSMC_PCCARD_DISABLE #define __FMC_NAND_ENABLE_IT __FSMC_NAND_ENABLE_IT #define __FMC_NAND_DISABLE_IT __FSMC_NAND_DISABLE_IT #define __FMC_NAND_GET_FLAG __FSMC_NAND_GET_FLAG #define __FMC_NAND_CLEAR_FLAG __FSMC_NAND_CLEAR_FLAG #define __FMC_PCCARD_ENABLE_IT __FSMC_PCCARD_ENABLE_IT #define __FMC_PCCARD_DISABLE_IT __FSMC_PCCARD_DISABLE_IT #define __FMC_PCCARD_GET_FLAG __FSMC_PCCARD_GET_FLAG #define __FMC_PCCARD_CLEAR_FLAG __FSMC_PCCARD_CLEAR_FLAG #endif /* STM32F405xx || STM32F415xx || STM32F407xx || STM32F417xx */ #define FMC_NORSRAM_TypeDef FSMC_NORSRAM_TypeDef #define FMC_NORSRAM_EXTENDED_TypeDef FSMC_NORSRAM_EXTENDED_TypeDef #if defined(STM32F405xx) || defined(STM32F415xx) || defined(STM32F407xx) || defined(STM32F417xx) #define FMC_NAND_TypeDef FSMC_NAND_TypeDef #define FMC_PCCARD_TypeDef FSMC_PCCARD_TypeDef #endif /* STM32F405xx || STM32F415xx || STM32F407xx || STM32F417xx */ #define FMC_NORSRAM_DEVICE FSMC_NORSRAM_DEVICE #define FMC_NORSRAM_EXTENDED_DEVICE FSMC_NORSRAM_EXTENDED_DEVICE #if defined(STM32F405xx) || defined(STM32F415xx) || defined(STM32F407xx) || defined(STM32F417xx) #define FMC_NAND_DEVICE FSMC_NAND_DEVICE #define FMC_PCCARD_DEVICE FSMC_PCCARD_DEVICE #define FMC_NAND_BANK2 FSMC_NAND_BANK2 #endif /* STM32F405xx || STM32F415xx || STM32F407xx || STM32F417xx */ #define FMC_NORSRAM_BANK1 FSMC_NORSRAM_BANK1 #define FMC_NORSRAM_BANK2 FSMC_NORSRAM_BANK2 #define FMC_NORSRAM_BANK3 FSMC_NORSRAM_BANK3 #define FMC_IT_RISING_EDGE FSMC_IT_RISING_EDGE #define FMC_IT_LEVEL FSMC_IT_LEVEL #define FMC_IT_FALLING_EDGE FSMC_IT_FALLING_EDGE #define FMC_IT_REFRESH_ERROR FSMC_IT_REFRESH_ERROR #define FMC_FLAG_RISING_EDGE FSMC_FLAG_RISING_EDGE #define FMC_FLAG_LEVEL FSMC_FLAG_LEVEL #define FMC_FLAG_FALLING_EDGE FSMC_FLAG_FALLING_EDGE #define FMC_FLAG_FEMPT FSMC_FLAG_FEMPT /** * @} */ /** * @} */ /* Private macro -------------------------------------------------------------*/ /** @defgroup FSMC_LL_Private_Macros FSMC Private Macros * @{ */ /** @defgroup FSMC_LL_NOR_Macros FSMC NOR/SRAM Exported Macros * @brief macros to handle NOR device enable/disable and read/write operations * @{ */ /** * @brief Enable the NORSRAM device access. * @param __INSTANCE__: FSMC_NORSRAM Instance * @param __BANK__: FSMC_NORSRAM Bank * @retval none */ #define __FSMC_NORSRAM_ENABLE(__INSTANCE__, __BANK__) ((__INSTANCE__)->BTCR[(__BANK__)] |= FSMC_BCR1_MBKEN) /** * @brief Disable the NORSRAM device access. * @param __INSTANCE__: FSMC_NORSRAM Instance * @param __BANK__: FSMC_NORSRAM Bank * @retval none */ #define __FSMC_NORSRAM_DISABLE(__INSTANCE__, __BANK__) ((__INSTANCE__)->BTCR[(__BANK__)] &= ~FSMC_BCR1_MBKEN) /** * @} */ /** @defgroup FSMC_LL_NAND_Macros FSMC NAND Macros * @brief macros to handle NAND device enable/disable * @{ */ #if defined(STM32F405xx) || defined(STM32F415xx) || defined(STM32F407xx) || defined(STM32F417xx) /** * @brief Enable the NAND device access. * @param __INSTANCE__: FSMC_NAND Instance * @param __BANK__: FSMC_NAND Bank * @retval none */ #define __FSMC_NAND_ENABLE(__INSTANCE__, __BANK__) (((__BANK__) == FSMC_NAND_BANK2)? ((__INSTANCE__)->PCR2 |= FSMC_PCR2_PBKEN): \ ((__INSTANCE__)->PCR3 |= FSMC_PCR3_PBKEN)) /** * @brief Disable the NAND device access. * @param __INSTANCE__: FSMC_NAND Instance * @param __BANK__: FSMC_NAND Bank * @retval none */ #define __FSMC_NAND_DISABLE(__INSTANCE__, __BANK__) (((__BANK__) == FSMC_NAND_BANK2)? ((__INSTANCE__)->PCR2 &= ~FSMC_PCR2_PBKEN): \ ((__INSTANCE__)->PCR3 &= ~FSMC_PCR3_PBKEN)) /** * @} */ /** @defgroup FSMC_LL_PCCARD_Macros FSMC PCCARD Macros * @brief macros to handle SRAM read/write operations * @{ */ /** * @brief Enable the PCCARD device access. * @param __INSTANCE__: FSMC_PCCARD Instance * @retval none */ #define __FSMC_PCCARD_ENABLE(__INSTANCE__) ((__INSTANCE__)->PCR4 |= FSMC_PCR4_PBKEN) /** * @brief Disable the PCCARD device access. * @param __INSTANCE__: FSMC_PCCARD Instance * @retval none */ #define __FSMC_PCCARD_DISABLE(__INSTANCE__) ((__INSTANCE__)->PCR4 &= ~FSMC_PCR4_PBKEN) /** * @} */ /** @defgroup FSMC_LL_Flag_Interrupt_Macros FSMC Flag&Interrupt Macros * @brief macros to handle FSMC flags and interrupts * @{ */ /** * @brief Enable the NAND device interrupt. * @param __INSTANCE__: FSMC_NAND Instance * @param __BANK__: FSMC_NAND Bank * @param __INTERRUPT__: FSMC_NAND interrupt * This parameter can be any combination of the following values: * @arg FSMC_IT_RISING_EDGE: Interrupt rising edge. * @arg FSMC_IT_LEVEL: Interrupt level. * @arg FSMC_IT_FALLING_EDGE: Interrupt falling edge. * @retval None */ #define __FSMC_NAND_ENABLE_IT(__INSTANCE__, __BANK__, __INTERRUPT__) (((__BANK__) == FSMC_NAND_BANK2)? ((__INSTANCE__)->SR2 |= (__INTERRUPT__)): \ ((__INSTANCE__)->SR3 |= (__INTERRUPT__))) /** * @brief Disable the NAND device interrupt. * @param __INSTANCE__: FSMC_NAND Instance * @param __BANK__: FSMC_NAND Bank * @param __INTERRUPT__: FSMC_NAND interrupt * This parameter can be any combination of the following values: * @arg FSMC_IT_RISING_EDGE: Interrupt rising edge. * @arg FSMC_IT_LEVEL: Interrupt level. * @arg FSMC_IT_FALLING_EDGE: Interrupt falling edge. * @retval None */ #define __FSMC_NAND_DISABLE_IT(__INSTANCE__, __BANK__, __INTERRUPT__) (((__BANK__) == FSMC_NAND_BANK2)? ((__INSTANCE__)->SR2 &= ~(__INTERRUPT__)): \ ((__INSTANCE__)->SR3 &= ~(__INTERRUPT__))) /** * @brief Get flag status of the NAND device. * @param __INSTANCE__: FSMC_NAND Instance * @param __BANK__ : FSMC_NAND Bank * @param __FLAG__ : FSMC_NAND flag * This parameter can be any combination of the following values: * @arg FSMC_FLAG_RISING_EDGE: Interrupt rising edge flag. * @arg FSMC_FLAG_LEVEL: Interrupt level edge flag. * @arg FSMC_FLAG_FALLING_EDGE: Interrupt falling edge flag. * @arg FSMC_FLAG_FEMPT: FIFO empty flag. * @retval The state of FLAG (SET or RESET). */ #define __FSMC_NAND_GET_FLAG(__INSTANCE__, __BANK__, __FLAG__) (((__BANK__) == FSMC_NAND_BANK2)? (((__INSTANCE__)->SR2 &(__FLAG__)) == (__FLAG__)): \ (((__INSTANCE__)->SR3 &(__FLAG__)) == (__FLAG__))) /** * @brief Clear flag status of the NAND device. * @param __INSTANCE__: FSMC_NAND Instance * @param __BANK__: FSMC_NAND Bank * @param __FLAG__: FSMC_NAND flag * This parameter can be any combination of the following values: * @arg FSMC_FLAG_RISING_EDGE: Interrupt rising edge flag. * @arg FSMC_FLAG_LEVEL: Interrupt level edge flag. * @arg FSMC_FLAG_FALLING_EDGE: Interrupt falling edge flag. * @arg FSMC_FLAG_FEMPT: FIFO empty flag. * @retval None */ #define __FSMC_NAND_CLEAR_FLAG(__INSTANCE__, __BANK__, __FLAG__) (((__BANK__) == FSMC_NAND_BANK2)? ((__INSTANCE__)->SR2 &= ~(__FLAG__)): \ ((__INSTANCE__)->SR3 &= ~(__FLAG__))) /** * @brief Enable the PCCARD device interrupt. * @param __INSTANCE__: FSMC_PCCARD Instance * @param __INTERRUPT__: FSMC_PCCARD interrupt * This parameter can be any combination of the following values: * @arg FSMC_IT_RISING_EDGE: Interrupt rising edge. * @arg FSMC_IT_LEVEL: Interrupt level. * @arg FSMC_IT_FALLING_EDGE: Interrupt falling edge. * @retval None */ #define __FSMC_PCCARD_ENABLE_IT(__INSTANCE__, __INTERRUPT__) ((__INSTANCE__)->SR4 |= (__INTERRUPT__)) /** * @brief Disable the PCCARD device interrupt. * @param __INSTANCE__: FSMC_PCCARD Instance * @param __INTERRUPT__: FSMC_PCCARD interrupt * This parameter can be any combination of the following values: * @arg FSMC_IT_RISING_EDGE: Interrupt rising edge. * @arg FSMC_IT_LEVEL: Interrupt level. * @arg FSMC_IT_FALLING_EDGE: Interrupt falling edge. * @retval None */ #define __FSMC_PCCARD_DISABLE_IT(__INSTANCE__, __INTERRUPT__) ((__INSTANCE__)->SR4 &= ~(__INTERRUPT__)) /** * @brief Get flag status of the PCCARD device. * @param __INSTANCE__: FSMC_PCCARD Instance * @param __FLAG__: FSMC_PCCARD flag * This parameter can be any combination of the following values: * @arg FSMC_FLAG_RISING_EDGE: Interrupt rising edge flag. * @arg FSMC_FLAG_LEVEL: Interrupt level edge flag. * @arg FSMC_FLAG_FALLING_EDGE: Interrupt falling edge flag. * @arg FSMC_FLAG_FEMPT: FIFO empty flag. * @retval The state of FLAG (SET or RESET). */ #define __FSMC_PCCARD_GET_FLAG(__INSTANCE__, __FLAG__) (((__INSTANCE__)->SR4 &(__FLAG__)) == (__FLAG__)) /** * @brief Clear flag status of the PCCARD device. * @param __INSTANCE__: FSMC_PCCARD Instance * @param __FLAG__: FSMC_PCCARD flag * This parameter can be any combination of the following values: * @arg FSMC_FLAG_RISING_EDGE: Interrupt rising edge flag. * @arg FSMC_FLAG_LEVEL: Interrupt level edge flag. * @arg FSMC_FLAG_FALLING_EDGE: Interrupt falling edge flag. * @arg FSMC_FLAG_FEMPT: FIFO empty flag. * @retval None */ #define __FSMC_PCCARD_CLEAR_FLAG(__INSTANCE__, __FLAG__) ((__INSTANCE__)->SR4 &= ~(__FLAG__)) /** * @} */ #endif /* STM32F405xx || STM32F415xx || STM32F407xx || STM32F417xx */ /** @defgroup FSMC_LL_Assert_Macros FSMC Assert Macros * @{ */ #define IS_FSMC_NORSRAM_BANK(__BANK__) (((__BANK__) == FSMC_NORSRAM_BANK1) || \ ((__BANK__) == FSMC_NORSRAM_BANK2) || \ ((__BANK__) == FSMC_NORSRAM_BANK3) || \ ((__BANK__) == FSMC_NORSRAM_BANK4)) #define IS_FSMC_MUX(__MUX__) (((__MUX__) == FSMC_DATA_ADDRESS_MUX_DISABLE) || \ ((__MUX__) == FSMC_DATA_ADDRESS_MUX_ENABLE)) #define IS_FSMC_MEMORY(__MEMORY__) (((__MEMORY__) == FSMC_MEMORY_TYPE_SRAM) || \ ((__MEMORY__) == FSMC_MEMORY_TYPE_PSRAM)|| \ ((__MEMORY__) == FSMC_MEMORY_TYPE_NOR)) #define IS_FSMC_NORSRAM_MEMORY_WIDTH(__WIDTH__) (((__WIDTH__) == FSMC_NORSRAM_MEM_BUS_WIDTH_8) || \ ((__WIDTH__) == FSMC_NORSRAM_MEM_BUS_WIDTH_16) || \ ((__WIDTH__) == FSMC_NORSRAM_MEM_BUS_WIDTH_32)) #define IS_FSMC_ACCESS_MODE(__MODE__) (((__MODE__) == FSMC_ACCESS_MODE_A) || \ ((__MODE__) == FSMC_ACCESS_MODE_B) || \ ((__MODE__) == FSMC_ACCESS_MODE_C) || \ ((__MODE__) == FSMC_ACCESS_MODE_D)) #define IS_FSMC_NAND_BANK(BANK) (((BANK) == FSMC_NAND_BANK2) || \ ((BANK) == FSMC_NAND_BANK3)) #define IS_FSMC_WAIT_FEATURE(FEATURE) (((FEATURE) == FSMC_NAND_PCC_WAIT_FEATURE_DISABLE) || \ ((FEATURE) == FSMC_NAND_PCC_WAIT_FEATURE_ENABLE)) #define IS_FSMC_NAND_MEMORY_WIDTH(WIDTH) (((WIDTH) == FSMC_NAND_PCC_MEM_BUS_WIDTH_8) || \ ((WIDTH) == FSMC_NAND_PCC_MEM_BUS_WIDTH_16)) #define IS_FSMC_ECC_STATE(STATE) (((STATE) == FSMC_NAND_ECC_DISABLE) || \ ((STATE) == FSMC_NAND_ECC_ENABLE)) #define IS_FSMC_ECCPAGE_SIZE(SIZE) (((SIZE) == FSMC_NAND_ECC_PAGE_SIZE_256BYTE) || \ ((SIZE) == FSMC_NAND_ECC_PAGE_SIZE_512BYTE) || \ ((SIZE) == FSMC_NAND_ECC_PAGE_SIZE_1024BYTE) || \ ((SIZE) == FSMC_NAND_ECC_PAGE_SIZE_2048BYTE) || \ ((SIZE) == FSMC_NAND_ECC_PAGE_SIZE_4096BYTE) || \ ((SIZE) == FSMC_NAND_ECC_PAGE_SIZE_8192BYTE)) #define IS_FSMC_TCLR_TIME(TIME) ((TIME) <= 255) #define IS_FSMC_TAR_TIME(TIME) ((TIME) <= 255) #define IS_FSMC_SETUP_TIME(TIME) ((TIME) <= 255) #define IS_FSMC_WAIT_TIME(TIME) ((TIME) <= 255) #define IS_FSMC_HOLD_TIME(TIME) ((TIME) <= 255) #define IS_FSMC_HIZ_TIME(TIME) ((TIME) <= 255) #define IS_FSMC_NORSRAM_DEVICE(__INSTANCE__) ((__INSTANCE__) == FSMC_NORSRAM_DEVICE) #define IS_FSMC_NORSRAM_EXTENDED_DEVICE(__INSTANCE__) ((__INSTANCE__) == FSMC_NORSRAM_EXTENDED_DEVICE) #define IS_FSMC_NAND_DEVICE(INSTANCE) ((INSTANCE) == FSMC_NAND_DEVICE) #define IS_FSMC_PCCARD_DEVICE(INSTANCE) ((INSTANCE) == FSMC_PCCARD_DEVICE) #define IS_FSMC_BURSTMODE(__STATE__) (((__STATE__) == FSMC_BURST_ACCESS_MODE_DISABLE) || \ ((__STATE__) == FSMC_BURST_ACCESS_MODE_ENABLE)) #define IS_FSMC_WAIT_POLARITY(__POLARITY__) (((__POLARITY__) == FSMC_WAIT_SIGNAL_POLARITY_LOW) || \ ((__POLARITY__) == FSMC_WAIT_SIGNAL_POLARITY_HIGH)) #define IS_FSMC_WRAP_MODE(__MODE__) (((__MODE__) == FSMC_WRAP_MODE_DISABLE) || \ ((__MODE__) == FSMC_WRAP_MODE_ENABLE)) #define IS_FSMC_WAIT_SIGNAL_ACTIVE(__ACTIVE__) (((__ACTIVE__) == FSMC_WAIT_TIMING_BEFORE_WS) || \ ((__ACTIVE__) == FSMC_WAIT_TIMING_DURING_WS)) #define IS_FSMC_WRITE_OPERATION(__OPERATION__) (((__OPERATION__) == FSMC_WRITE_OPERATION_DISABLE) || \ ((__OPERATION__) == FSMC_WRITE_OPERATION_ENABLE)) #define IS_FSMC_WAITE_SIGNAL(__SIGNAL__) (((__SIGNAL__) == FSMC_WAIT_SIGNAL_DISABLE) || \ ((__SIGNAL__) == FSMC_WAIT_SIGNAL_ENABLE)) #define IS_FSMC_EXTENDED_MODE(__MODE__) (((__MODE__) == FSMC_EXTENDED_MODE_DISABLE) || \ ((__MODE__) == FSMC_EXTENDED_MODE_ENABLE)) #define IS_FSMC_ASYNWAIT(__STATE__) (((__STATE__) == FSMC_ASYNCHRONOUS_WAIT_DISABLE) || \ ((__STATE__) == FSMC_ASYNCHRONOUS_WAIT_ENABLE)) #define IS_FSMC_DATA_LATENCY(__LATENCY__) (((__LATENCY__) > 1) && ((__LATENCY__) <= 17)) #define IS_FSMC_WRITE_BURST(__BURST__) (((__BURST__) == FSMC_WRITE_BURST_DISABLE) || \ ((__BURST__) == FSMC_WRITE_BURST_ENABLE)) #define IS_FSMC_ADDRESS_SETUP_TIME(__TIME__) ((__TIME__) <= 15) #define IS_FSMC_ADDRESS_HOLD_TIME(__TIME__) (((__TIME__) > 0) && ((__TIME__) <= 15)) #define IS_FSMC_DATASETUP_TIME(__TIME__) (((__TIME__) > 0) && ((__TIME__) <= 255)) #define IS_FSMC_TURNAROUND_TIME(__TIME__) ((__TIME__) <= 15) #define IS_FSMC_CONTINOUS_CLOCK(CCLOCK) (((CCLOCK) == FSMC_CONTINUOUS_CLOCK_SYNC_ONLY) || \ ((CCLOCK) == FSMC_CONTINUOUS_CLOCK_SYNC_ASYNC)) #define IS_FSMC_CLK_DIV(DIV) (((DIV) > 1) && ((DIV) <= 16)) /** * @} */ /** * @} */ /* Private functions ---------------------------------------------------------*/ /** @defgroup FSMC_LL_Private_Functions FSMC LL Private Functions * @{ */ /** @defgroup FSMC_LL_NORSRAM NOR SRAM * @{ */ /** @defgroup FSMC_LL_NORSRAM_Private_Functions_Group1 NOR SRAM Initialization/de-initialization functions * @{ */ HAL_StatusTypeDef FSMC_NORSRAM_Init(FSMC_NORSRAM_TypeDef *Device, FSMC_NORSRAM_InitTypeDef *Init); HAL_StatusTypeDef FSMC_NORSRAM_Timing_Init(FSMC_NORSRAM_TypeDef *Device, FSMC_NORSRAM_TimingTypeDef *Timing, uint32_t Bank); HAL_StatusTypeDef FSMC_NORSRAM_Extended_Timing_Init(FSMC_NORSRAM_EXTENDED_TypeDef *Device, FSMC_NORSRAM_TimingTypeDef *Timing, uint32_t Bank, uint32_t ExtendedMode); HAL_StatusTypeDef FSMC_NORSRAM_DeInit(FSMC_NORSRAM_TypeDef *Device, FSMC_NORSRAM_EXTENDED_TypeDef *ExDevice, uint32_t Bank); /** * @} */ /** @defgroup FSMC_LL_NORSRAM_Private_Functions_Group2 NOR SRAM Control functions * @{ */ HAL_StatusTypeDef FSMC_NORSRAM_WriteOperation_Enable(FSMC_NORSRAM_TypeDef *Device, uint32_t Bank); HAL_StatusTypeDef FSMC_NORSRAM_WriteOperation_Disable(FSMC_NORSRAM_TypeDef *Device, uint32_t Bank); /** * @} */ /** * @} */ #if defined(STM32F405xx) || defined(STM32F415xx) || defined(STM32F407xx) || defined(STM32F417xx) /** @defgroup FSMC_LL_NAND NAND * @{ */ /** @defgroup FSMC_LL_NAND_Private_Functions_Group1 NAND Initialization/de-initialization functions * @{ */ HAL_StatusTypeDef FSMC_NAND_Init(FSMC_NAND_TypeDef *Device, FSMC_NAND_InitTypeDef *Init); HAL_StatusTypeDef FSMC_NAND_CommonSpace_Timing_Init(FSMC_NAND_TypeDef *Device, FSMC_NAND_PCC_TimingTypeDef *Timing, uint32_t Bank); HAL_StatusTypeDef FSMC_NAND_AttributeSpace_Timing_Init(FSMC_NAND_TypeDef *Device, FSMC_NAND_PCC_TimingTypeDef *Timing, uint32_t Bank); HAL_StatusTypeDef FSMC_NAND_DeInit(FSMC_NAND_TypeDef *Device, uint32_t Bank); /** * @} */ /** @defgroup FSMC_LL_NAND_Private_Functions_Group2 NAND Control functions * @{ */ HAL_StatusTypeDef FSMC_NAND_ECC_Enable(FSMC_NAND_TypeDef *Device, uint32_t Bank); HAL_StatusTypeDef FSMC_NAND_ECC_Disable(FSMC_NAND_TypeDef *Device, uint32_t Bank); HAL_StatusTypeDef FSMC_NAND_GetECC(FSMC_NAND_TypeDef *Device, uint32_t *ECCval, uint32_t Bank, uint32_t Timeout); /** * @} */ /** * @} */ /** @defgroup FSMC_LL_PCCARD PCCARD * @{ */ /** @defgroup FSMC_LL_PCCARD_Private_Functions_Group1 PCCARD Initialization/de-initialization functions * @{ */ HAL_StatusTypeDef FSMC_PCCARD_Init(FSMC_PCCARD_TypeDef *Device, FSMC_PCCARD_InitTypeDef *Init); HAL_StatusTypeDef FSMC_PCCARD_CommonSpace_Timing_Init(FSMC_PCCARD_TypeDef *Device, FSMC_NAND_PCC_TimingTypeDef *Timing); HAL_StatusTypeDef FSMC_PCCARD_AttributeSpace_Timing_Init(FSMC_PCCARD_TypeDef *Device, FSMC_NAND_PCC_TimingTypeDef *Timing); HAL_StatusTypeDef FSMC_PCCARD_IOSpace_Timing_Init(FSMC_PCCARD_TypeDef *Device, FSMC_NAND_PCC_TimingTypeDef *Timing); HAL_StatusTypeDef FSMC_PCCARD_DeInit(FSMC_PCCARD_TypeDef *Device); /** * @} */ /** * @} */ #endif /* STM32F405xx || STM32F415xx || STM32F407xx || STM32F417xx */ /** * @} */ #endif /* STM32F405xx || STM32F415xx || STM32F407xx || STM32F417xx */ /** * @} */ /** * @} */ #ifdef __cplusplus } #endif #endif /* __STM32F4xx_LL_FSMC_H */ /************************ (C) COPYRIGHT STMicroelectronics *****END OF FILE****/ ================================================ FILE: Zelig/mbed/TARGET_NUCLEO_F401RE/stm32f4xx_ll_sdmmc.h ================================================ /** ****************************************************************************** * @file stm32f4xx_ll_sdmmc.h * @author MCD Application Team * @version V1.4.1 * @date 09-October-2015 * @brief Header file of SDMMC HAL module. ****************************************************************************** * @attention * *

© COPYRIGHT(c) 2015 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. * ****************************************************************************** */ /* Define to prevent recursive inclusion -------------------------------------*/ #ifndef __STM32F4xx_LL_SDMMC_H #define __STM32F4xx_LL_SDMMC_H #ifdef __cplusplus extern "C" { #endif #if defined(STM32F405xx) || defined(STM32F415xx) || defined(STM32F407xx) || defined(STM32F417xx) || \ defined(STM32F427xx) || defined(STM32F437xx) || defined(STM32F429xx) || defined(STM32F439xx) || \ defined(STM32F401xC) || defined(STM32F401xE) || defined(STM32F411xE) || defined(STM32F446xx) || \ defined(STM32F469xx) || defined(STM32F479xx) /* Includes ------------------------------------------------------------------*/ #include "stm32f4xx_hal_def.h" /** @addtogroup STM32F4xx_Driver * @{ */ /** @addtogroup SDMMC_LL * @{ */ /* Exported types ------------------------------------------------------------*/ /** @defgroup SDMMC_LL_Exported_Types SDMMC_LL Exported Types * @{ */ /** * @brief SDMMC Configuration Structure definition */ typedef struct { uint32_t ClockEdge; /*!< Specifies the clock transition on which the bit capture is made. This parameter can be a value of @ref SDIO_Clock_Edge */ uint32_t ClockBypass; /*!< Specifies whether the SDIO Clock divider bypass is enabled or disabled. This parameter can be a value of @ref SDIO_Clock_Bypass */ uint32_t ClockPowerSave; /*!< Specifies whether SDIO Clock output is enabled or disabled when the bus is idle. This parameter can be a value of @ref SDIO_Clock_Power_Save */ uint32_t BusWide; /*!< Specifies the SDIO bus width. This parameter can be a value of @ref SDIO_Bus_Wide */ uint32_t HardwareFlowControl; /*!< Specifies whether the SDIO hardware flow control is enabled or disabled. This parameter can be a value of @ref SDIO_Hardware_Flow_Control */ uint32_t ClockDiv; /*!< Specifies the clock frequency of the SDIO controller. This parameter can be a value between Min_Data = 0 and Max_Data = 255 */ }SDIO_InitTypeDef; /** * @brief SDIO Command Control structure */ typedef struct { uint32_t Argument; /*!< Specifies the SDIO command argument which is sent to a card as part of a command message. If a command contains an argument, it must be loaded into this register before writing the command to the command register. */ uint32_t CmdIndex; /*!< Specifies the SDIO command index. It must be Min_Data = 0 and Max_Data = 64 */ uint32_t Response; /*!< Specifies the SDIO response type. This parameter can be a value of @ref SDIO_Response_Type */ uint32_t WaitForInterrupt; /*!< Specifies whether SDIO wait for interrupt request is enabled or disabled. This parameter can be a value of @ref SDIO_Wait_Interrupt_State */ uint32_t CPSM; /*!< Specifies whether SDIO Command path state machine (CPSM) is enabled or disabled. This parameter can be a value of @ref SDIO_CPSM_State */ }SDIO_CmdInitTypeDef; /** * @brief SDIO Data Control structure */ typedef struct { uint32_t DataTimeOut; /*!< Specifies the data timeout period in card bus clock periods. */ uint32_t DataLength; /*!< Specifies the number of data bytes to be transferred. */ uint32_t DataBlockSize; /*!< Specifies the data block size for block transfer. This parameter can be a value of @ref SDIO_Data_Block_Size */ uint32_t TransferDir; /*!< Specifies the data transfer direction, whether the transfer is a read or write. This parameter can be a value of @ref SDIO_Transfer_Direction */ uint32_t TransferMode; /*!< Specifies whether data transfer is in stream or block mode. This parameter can be a value of @ref SDIO_Transfer_Type */ uint32_t DPSM; /*!< Specifies whether SDIO Data path state machine (DPSM) is enabled or disabled. This parameter can be a value of @ref SDIO_DPSM_State */ }SDIO_DataInitTypeDef; /** * @} */ /* Exported constants --------------------------------------------------------*/ /** @defgroup SDMMC_LL_Exported_Constants SDMMC_LL Exported Constants * @{ */ /** @defgroup SDIO_Clock_Edge Clock Edge * @{ */ #define SDIO_CLOCK_EDGE_RISING ((uint32_t)0x00000000) #define SDIO_CLOCK_EDGE_FALLING SDIO_CLKCR_NEGEDGE #define IS_SDIO_CLOCK_EDGE(EDGE) (((EDGE) == SDIO_CLOCK_EDGE_RISING) || \ ((EDGE) == SDIO_CLOCK_EDGE_FALLING)) /** * @} */ /** @defgroup SDIO_Clock_Bypass Clock Bypass * @{ */ #define SDIO_CLOCK_BYPASS_DISABLE ((uint32_t)0x00000000) #define SDIO_CLOCK_BYPASS_ENABLE SDIO_CLKCR_BYPASS #define IS_SDIO_CLOCK_BYPASS(BYPASS) (((BYPASS) == SDIO_CLOCK_BYPASS_DISABLE) || \ ((BYPASS) == SDIO_CLOCK_BYPASS_ENABLE)) /** * @} */ /** @defgroup SDIO_Clock_Power_Save Clock Power Saving * @{ */ #define SDIO_CLOCK_POWER_SAVE_DISABLE ((uint32_t)0x00000000) #define SDIO_CLOCK_POWER_SAVE_ENABLE SDIO_CLKCR_PWRSAV #define IS_SDIO_CLOCK_POWER_SAVE(SAVE) (((SAVE) == SDIO_CLOCK_POWER_SAVE_DISABLE) || \ ((SAVE) == SDIO_CLOCK_POWER_SAVE_ENABLE)) /** * @} */ /** @defgroup SDIO_Bus_Wide Bus Width * @{ */ #define SDIO_BUS_WIDE_1B ((uint32_t)0x00000000) #define SDIO_BUS_WIDE_4B SDIO_CLKCR_WIDBUS_0 #define SDIO_BUS_WIDE_8B SDIO_CLKCR_WIDBUS_1 #define IS_SDIO_BUS_WIDE(WIDE) (((WIDE) == SDIO_BUS_WIDE_1B) || \ ((WIDE) == SDIO_BUS_WIDE_4B) || \ ((WIDE) == SDIO_BUS_WIDE_8B)) /** * @} */ /** @defgroup SDIO_Hardware_Flow_Control Hardware Flow Control * @{ */ #define SDIO_HARDWARE_FLOW_CONTROL_DISABLE ((uint32_t)0x00000000) #define SDIO_HARDWARE_FLOW_CONTROL_ENABLE SDIO_CLKCR_HWFC_EN #define IS_SDIO_HARDWARE_FLOW_CONTROL(CONTROL) (((CONTROL) == SDIO_HARDWARE_FLOW_CONTROL_DISABLE) || \ ((CONTROL) == SDIO_HARDWARE_FLOW_CONTROL_ENABLE)) /** * @} */ /** @defgroup SDIO_Clock_Division Clock Division * @{ */ #define IS_SDIO_CLKDIV(DIV) ((DIV) <= 0xFF) /** * @} */ /** @defgroup SDIO_Command_Index Command Index * @{ */ #define IS_SDIO_CMD_INDEX(INDEX) ((INDEX) < 0x40) /** * @} */ /** @defgroup SDIO_Response_Type Response Type * @{ */ #define SDIO_RESPONSE_NO ((uint32_t)0x00000000) #define SDIO_RESPONSE_SHORT SDIO_CMD_WAITRESP_0 #define SDIO_RESPONSE_LONG SDIO_CMD_WAITRESP #define IS_SDIO_RESPONSE(RESPONSE) (((RESPONSE) == SDIO_RESPONSE_NO) || \ ((RESPONSE) == SDIO_RESPONSE_SHORT) || \ ((RESPONSE) == SDIO_RESPONSE_LONG)) /** * @} */ /** @defgroup SDIO_Wait_Interrupt_State Wait Interrupt * @{ */ #define SDIO_WAIT_NO ((uint32_t)0x00000000) #define SDIO_WAIT_IT SDIO_CMD_WAITINT #define SDIO_WAIT_PEND SDIO_CMD_WAITPEND #define IS_SDIO_WAIT(WAIT) (((WAIT) == SDIO_WAIT_NO) || \ ((WAIT) == SDIO_WAIT_IT) || \ ((WAIT) == SDIO_WAIT_PEND)) /** * @} */ /** @defgroup SDIO_CPSM_State CPSM State * @{ */ #define SDIO_CPSM_DISABLE ((uint32_t)0x00000000) #define SDIO_CPSM_ENABLE SDIO_CMD_CPSMEN #define IS_SDIO_CPSM(CPSM) (((CPSM) == SDIO_CPSM_DISABLE) || \ ((CPSM) == SDIO_CPSM_ENABLE)) /** * @} */ /** @defgroup SDIO_Response_Registers Response Register * @{ */ #define SDIO_RESP1 ((uint32_t)0x00000000) #define SDIO_RESP2 ((uint32_t)0x00000004) #define SDIO_RESP3 ((uint32_t)0x00000008) #define SDIO_RESP4 ((uint32_t)0x0000000C) #define IS_SDIO_RESP(RESP) (((RESP) == SDIO_RESP1) || \ ((RESP) == SDIO_RESP2) || \ ((RESP) == SDIO_RESP3) || \ ((RESP) == SDIO_RESP4)) /** * @} */ /** @defgroup SDIO_Data_Length Data Lenght * @{ */ #define IS_SDIO_DATA_LENGTH(LENGTH) ((LENGTH) <= 0x01FFFFFF) /** * @} */ /** @defgroup SDIO_Data_Block_Size Data Block Size * @{ */ #define SDIO_DATABLOCK_SIZE_1B ((uint32_t)0x00000000) #define SDIO_DATABLOCK_SIZE_2B SDIO_DCTRL_DBLOCKSIZE_0 #define SDIO_DATABLOCK_SIZE_4B SDIO_DCTRL_DBLOCKSIZE_1 #define SDIO_DATABLOCK_SIZE_8B ((uint32_t)0x00000030) #define SDIO_DATABLOCK_SIZE_16B SDIO_DCTRL_DBLOCKSIZE_2 #define SDIO_DATABLOCK_SIZE_32B ((uint32_t)0x00000050) #define SDIO_DATABLOCK_SIZE_64B ((uint32_t)0x00000060) #define SDIO_DATABLOCK_SIZE_128B ((uint32_t)0x00000070) #define SDIO_DATABLOCK_SIZE_256B SDIO_DCTRL_DBLOCKSIZE_3 #define SDIO_DATABLOCK_SIZE_512B ((uint32_t)0x00000090) #define SDIO_DATABLOCK_SIZE_1024B ((uint32_t)0x000000A0) #define SDIO_DATABLOCK_SIZE_2048B ((uint32_t)0x000000B0) #define SDIO_DATABLOCK_SIZE_4096B ((uint32_t)0x000000C0) #define SDIO_DATABLOCK_SIZE_8192B ((uint32_t)0x000000D0) #define SDIO_DATABLOCK_SIZE_16384B ((uint32_t)0x000000E0) #define IS_SDIO_BLOCK_SIZE(SIZE) (((SIZE) == SDIO_DATABLOCK_SIZE_1B) || \ ((SIZE) == SDIO_DATABLOCK_SIZE_2B) || \ ((SIZE) == SDIO_DATABLOCK_SIZE_4B) || \ ((SIZE) == SDIO_DATABLOCK_SIZE_8B) || \ ((SIZE) == SDIO_DATABLOCK_SIZE_16B) || \ ((SIZE) == SDIO_DATABLOCK_SIZE_32B) || \ ((SIZE) == SDIO_DATABLOCK_SIZE_64B) || \ ((SIZE) == SDIO_DATABLOCK_SIZE_128B) || \ ((SIZE) == SDIO_DATABLOCK_SIZE_256B) || \ ((SIZE) == SDIO_DATABLOCK_SIZE_512B) || \ ((SIZE) == SDIO_DATABLOCK_SIZE_1024B) || \ ((SIZE) == SDIO_DATABLOCK_SIZE_2048B) || \ ((SIZE) == SDIO_DATABLOCK_SIZE_4096B) || \ ((SIZE) == SDIO_DATABLOCK_SIZE_8192B) || \ ((SIZE) == SDIO_DATABLOCK_SIZE_16384B)) /** * @} */ /** @defgroup SDIO_Transfer_Direction Transfer Direction * @{ */ #define SDIO_TRANSFER_DIR_TO_CARD ((uint32_t)0x00000000) #define SDIO_TRANSFER_DIR_TO_SDIO SDIO_DCTRL_DTDIR #define IS_SDIO_TRANSFER_DIR(DIR) (((DIR) == SDIO_TRANSFER_DIR_TO_CARD) || \ ((DIR) == SDIO_TRANSFER_DIR_TO_SDIO)) /** * @} */ /** @defgroup SDIO_Transfer_Type Transfer Type * @{ */ #define SDIO_TRANSFER_MODE_BLOCK ((uint32_t)0x00000000) #define SDIO_TRANSFER_MODE_STREAM SDIO_DCTRL_DTMODE #define IS_SDIO_TRANSFER_MODE(MODE) (((MODE) == SDIO_TRANSFER_MODE_BLOCK) || \ ((MODE) == SDIO_TRANSFER_MODE_STREAM)) /** * @} */ /** @defgroup SDIO_DPSM_State DPSM State * @{ */ #define SDIO_DPSM_DISABLE ((uint32_t)0x00000000) #define SDIO_DPSM_ENABLE SDIO_DCTRL_DTEN #define IS_SDIO_DPSM(DPSM) (((DPSM) == SDIO_DPSM_DISABLE) ||\ ((DPSM) == SDIO_DPSM_ENABLE)) /** * @} */ /** @defgroup SDIO_Read_Wait_Mode Read Wait Mode * @{ */ #define SDIO_READ_WAIT_MODE_DATA2 ((uint32_t)0x00000000) #define SDIO_READ_WAIT_MODE_CLK ((uint32_t)0x00000001) #define IS_SDIO_READWAIT_MODE(MODE) (((MODE) == SDIO_READ_WAIT_MODE_CLK) || \ ((MODE) == SDIO_READ_WAIT_MODE_DATA2)) /** * @} */ /** @defgroup SDIO_Interrupt_sources Interrupt Sources * @{ */ #define SDIO_IT_CCRCFAIL SDIO_STA_CCRCFAIL #define SDIO_IT_DCRCFAIL SDIO_STA_DCRCFAIL #define SDIO_IT_CTIMEOUT SDIO_STA_CTIMEOUT #define SDIO_IT_DTIMEOUT SDIO_STA_DTIMEOUT #define SDIO_IT_TXUNDERR SDIO_STA_TXUNDERR #define SDIO_IT_RXOVERR SDIO_STA_RXOVERR #define SDIO_IT_CMDREND SDIO_STA_CMDREND #define SDIO_IT_CMDSENT SDIO_STA_CMDSENT #define SDIO_IT_DATAEND SDIO_STA_DATAEND #define SDIO_IT_STBITERR SDIO_STA_STBITERR #define SDIO_IT_DBCKEND SDIO_STA_DBCKEND #define SDIO_IT_CMDACT SDIO_STA_CMDACT #define SDIO_IT_TXACT SDIO_STA_TXACT #define SDIO_IT_RXACT SDIO_STA_RXACT #define SDIO_IT_TXFIFOHE SDIO_STA_TXFIFOHE #define SDIO_IT_RXFIFOHF SDIO_STA_RXFIFOHF #define SDIO_IT_TXFIFOF SDIO_STA_TXFIFOF #define SDIO_IT_RXFIFOF SDIO_STA_RXFIFOF #define SDIO_IT_TXFIFOE SDIO_STA_TXFIFOE #define SDIO_IT_RXFIFOE SDIO_STA_RXFIFOE #define SDIO_IT_TXDAVL SDIO_STA_TXDAVL #define SDIO_IT_RXDAVL SDIO_STA_RXDAVL #define SDIO_IT_SDIOIT SDIO_STA_SDIOIT #define SDIO_IT_CEATAEND SDIO_STA_CEATAEND /** * @} */ /** @defgroup SDIO_Flags Flags * @{ */ #define SDIO_FLAG_CCRCFAIL SDIO_STA_CCRCFAIL #define SDIO_FLAG_DCRCFAIL SDIO_STA_DCRCFAIL #define SDIO_FLAG_CTIMEOUT SDIO_STA_CTIMEOUT #define SDIO_FLAG_DTIMEOUT SDIO_STA_DTIMEOUT #define SDIO_FLAG_TXUNDERR SDIO_STA_TXUNDERR #define SDIO_FLAG_RXOVERR SDIO_STA_RXOVERR #define SDIO_FLAG_CMDREND SDIO_STA_CMDREND #define SDIO_FLAG_CMDSENT SDIO_STA_CMDSENT #define SDIO_FLAG_DATAEND SDIO_STA_DATAEND #define SDIO_FLAG_STBITERR SDIO_STA_STBITERR #define SDIO_FLAG_DBCKEND SDIO_STA_DBCKEND #define SDIO_FLAG_CMDACT SDIO_STA_CMDACT #define SDIO_FLAG_TXACT SDIO_STA_TXACT #define SDIO_FLAG_RXACT SDIO_STA_RXACT #define SDIO_FLAG_TXFIFOHE SDIO_STA_TXFIFOHE #define SDIO_FLAG_RXFIFOHF SDIO_STA_RXFIFOHF #define SDIO_FLAG_TXFIFOF SDIO_STA_TXFIFOF #define SDIO_FLAG_RXFIFOF SDIO_STA_RXFIFOF #define SDIO_FLAG_TXFIFOE SDIO_STA_TXFIFOE #define SDIO_FLAG_RXFIFOE SDIO_STA_RXFIFOE #define SDIO_FLAG_TXDAVL SDIO_STA_TXDAVL #define SDIO_FLAG_RXDAVL SDIO_STA_RXDAVL #define SDIO_FLAG_SDIOIT SDIO_STA_SDIOIT #define SDIO_FLAG_CEATAEND SDIO_STA_CEATAEND /** * @} */ /** * @} */ /* Exported macro ------------------------------------------------------------*/ /** @defgroup SDMMC_LL_Exported_macros SDMMC_LL Exported Macros * @{ */ /** @defgroup SDMMC_LL_Alias_Region Bit Address in the alias region * @{ */ /* ------------ SDIO registers bit address in the alias region -------------- */ #define SDIO_OFFSET (SDIO_BASE - PERIPH_BASE) /* --- CLKCR Register ---*/ /* Alias word address of CLKEN bit */ #define CLKCR_OFFSET (SDIO_OFFSET + 0x04) #define CLKEN_BITNUMBER 0x08 #define CLKCR_CLKEN_BB (PERIPH_BB_BASE + (CLKCR_OFFSET * 32) + (CLKEN_BITNUMBER * 4)) /* --- CMD Register ---*/ /* Alias word address of SDIOSUSPEND bit */ #define CMD_OFFSET (SDIO_OFFSET + 0x0C) #define SDIOSUSPEND_BITNUMBER 0x0B #define CMD_SDIOSUSPEND_BB (PERIPH_BB_BASE + (CMD_OFFSET * 32) + (SDIOSUSPEND_BITNUMBER * 4)) /* Alias word address of ENCMDCOMPL bit */ #define ENCMDCOMPL_BITNUMBER 0x0C #define CMD_ENCMDCOMPL_BB (PERIPH_BB_BASE + (CMD_OFFSET * 32) + (ENCMDCOMPL_BITNUMBER * 4)) /* Alias word address of NIEN bit */ #define NIEN_BITNUMBER 0x0D #define CMD_NIEN_BB (PERIPH_BB_BASE + (CMD_OFFSET * 32) + (NIEN_BITNUMBER * 4)) /* Alias word address of ATACMD bit */ #define ATACMD_BITNUMBER 0x0E #define CMD_ATACMD_BB (PERIPH_BB_BASE + (CMD_OFFSET * 32) + (ATACMD_BITNUMBER * 4)) /* --- DCTRL Register ---*/ /* Alias word address of DMAEN bit */ #define DCTRL_OFFSET (SDIO_OFFSET + 0x2C) #define DMAEN_BITNUMBER 0x03 #define DCTRL_DMAEN_BB (PERIPH_BB_BASE + (DCTRL_OFFSET * 32) + (DMAEN_BITNUMBER * 4)) /* Alias word address of RWSTART bit */ #define RWSTART_BITNUMBER 0x08 #define DCTRL_RWSTART_BB (PERIPH_BB_BASE + (DCTRL_OFFSET * 32) + (RWSTART_BITNUMBER * 4)) /* Alias word address of RWSTOP bit */ #define RWSTOP_BITNUMBER 0x09 #define DCTRL_RWSTOP_BB (PERIPH_BB_BASE + (DCTRL_OFFSET * 32) + (RWSTOP_BITNUMBER * 4)) /* Alias word address of RWMOD bit */ #define RWMOD_BITNUMBER 0x0A #define DCTRL_RWMOD_BB (PERIPH_BB_BASE + (DCTRL_OFFSET * 32) + (RWMOD_BITNUMBER * 4)) /* Alias word address of SDIOEN bit */ #define SDIOEN_BITNUMBER 0x0B #define DCTRL_SDIOEN_BB (PERIPH_BB_BASE + (DCTRL_OFFSET * 32) + (SDIOEN_BITNUMBER * 4)) /** * @} */ /** @defgroup SDMMC_LL_Register Bits And Addresses Definitions * @brief SDMMC_LL registers bit address in the alias region * @{ */ /* ---------------------- SDIO registers bit mask --------------------------- */ /* --- CLKCR Register ---*/ /* CLKCR register clear mask */ #define CLKCR_CLEAR_MASK ((uint32_t)(SDIO_CLKCR_CLKDIV | SDIO_CLKCR_PWRSAV |\ SDIO_CLKCR_BYPASS | SDIO_CLKCR_WIDBUS |\ SDIO_CLKCR_NEGEDGE | SDIO_CLKCR_HWFC_EN)) /* --- PWRCTRL Register ---*/ /* --- DCTRL Register ---*/ /* SDIO DCTRL Clear Mask */ #define DCTRL_CLEAR_MASK ((uint32_t)(SDIO_DCTRL_DTEN | SDIO_DCTRL_DTDIR |\ SDIO_DCTRL_DTMODE | SDIO_DCTRL_DBLOCKSIZE)) /* --- CMD Register ---*/ /* CMD Register clear mask */ #define CMD_CLEAR_MASK ((uint32_t)(SDIO_CMD_CMDINDEX | SDIO_CMD_WAITRESP |\ SDIO_CMD_WAITINT | SDIO_CMD_WAITPEND |\ SDIO_CMD_CPSMEN | SDIO_CMD_SDIOSUSPEND)) /* SDIO RESP Registers Address */ #define SDIO_RESP_ADDR ((uint32_t)(SDIO_BASE + 0x14)) /* SDIO Initialization Frequency (400KHz max) */ #define SDIO_INIT_CLK_DIV ((uint8_t)0x76) /* SDIO Data Transfer Frequency (25MHz max) */ #define SDIO_TRANSFER_CLK_DIV ((uint8_t)0x0) /** * @} */ /** @defgroup SDMMC_LL_Interrupt_Clock Interrupt And Clock Configuration * @brief macros to handle interrupts and specific clock configurations * @{ */ /** * @brief Enable the SDIO device. * @retval None */ #define __SDIO_ENABLE() (*(__IO uint32_t *)CLKCR_CLKEN_BB = ENABLE) /** * @brief Disable the SDIO device. * @retval None */ #define __SDIO_DISABLE() (*(__IO uint32_t *)CLKCR_CLKEN_BB = DISABLE) /** * @brief Enable the SDIO DMA transfer. * @retval None */ #define __SDIO_DMA_ENABLE() (*(__IO uint32_t *)DCTRL_DMAEN_BB = ENABLE) /** * @brief Disable the SDIO DMA transfer. * @retval None */ #define __SDIO_DMA_DISABLE() (*(__IO uint32_t *)DCTRL_DMAEN_BB = DISABLE) /** * @brief Enable the SDIO device interrupt. * @param __INSTANCE__ : Pointer to SDIO register base * @param __INTERRUPT__ : specifies the SDIO interrupt sources to be enabled. * This parameter can be one or a combination of the following values: * @arg SDIO_IT_CCRCFAIL: Command response received (CRC check failed) interrupt * @arg SDIO_IT_DCRCFAIL: Data block sent/received (CRC check failed) interrupt * @arg SDIO_IT_CTIMEOUT: Command response timeout interrupt * @arg SDIO_IT_DTIMEOUT: Data timeout interrupt * @arg SDIO_IT_TXUNDERR: Transmit FIFO underrun error interrupt * @arg SDIO_IT_RXOVERR: Received FIFO overrun error interrupt * @arg SDIO_IT_CMDREND: Command response received (CRC check passed) interrupt * @arg SDIO_IT_CMDSENT: Command sent (no response required) interrupt * @arg SDIO_IT_DATAEND: Data end (data counter, SDIDCOUNT, is zero) interrupt * @arg SDIO_IT_STBITERR: Start bit not detected on all data signals in wide * bus mode interrupt * @arg SDIO_IT_DBCKEND: Data block sent/received (CRC check passed) interrupt * @arg SDIO_IT_CMDACT: Command transfer in progress interrupt * @arg SDIO_IT_TXACT: Data transmit in progress interrupt * @arg SDIO_IT_RXACT: Data receive in progress interrupt * @arg SDIO_IT_TXFIFOHE: Transmit FIFO Half Empty interrupt * @arg SDIO_IT_RXFIFOHF: Receive FIFO Half Full interrupt * @arg SDIO_IT_TXFIFOF: Transmit FIFO full interrupt * @arg SDIO_IT_RXFIFOF: Receive FIFO full interrupt * @arg SDIO_IT_TXFIFOE: Transmit FIFO empty interrupt * @arg SDIO_IT_RXFIFOE: Receive FIFO empty interrupt * @arg SDIO_IT_TXDAVL: Data available in transmit FIFO interrupt * @arg SDIO_IT_RXDAVL: Data available in receive FIFO interrupt * @arg SDIO_IT_SDIOIT: SD I/O interrupt received interrupt * @arg SDIO_IT_CEATAEND: CE-ATA command completion signal received for CMD61 interrupt * @retval None */ #define __SDIO_ENABLE_IT(__INSTANCE__, __INTERRUPT__) ((__INSTANCE__)->MASK |= (__INTERRUPT__)) /** * @brief Disable the SDIO device interrupt. * @param __INSTANCE__ : Pointer to SDIO register base * @param __INTERRUPT__ : specifies the SDIO interrupt sources to be disabled. * This parameter can be one or a combination of the following values: * @arg SDIO_IT_CCRCFAIL: Command response received (CRC check failed) interrupt * @arg SDIO_IT_DCRCFAIL: Data block sent/received (CRC check failed) interrupt * @arg SDIO_IT_CTIMEOUT: Command response timeout interrupt * @arg SDIO_IT_DTIMEOUT: Data timeout interrupt * @arg SDIO_IT_TXUNDERR: Transmit FIFO underrun error interrupt * @arg SDIO_IT_RXOVERR: Received FIFO overrun error interrupt * @arg SDIO_IT_CMDREND: Command response received (CRC check passed) interrupt * @arg SDIO_IT_CMDSENT: Command sent (no response required) interrupt * @arg SDIO_IT_DATAEND: Data end (data counter, SDIDCOUNT, is zero) interrupt * @arg SDIO_IT_STBITERR: Start bit not detected on all data signals in wide * bus mode interrupt * @arg SDIO_IT_DBCKEND: Data block sent/received (CRC check passed) interrupt * @arg SDIO_IT_CMDACT: Command transfer in progress interrupt * @arg SDIO_IT_TXACT: Data transmit in progress interrupt * @arg SDIO_IT_RXACT: Data receive in progress interrupt * @arg SDIO_IT_TXFIFOHE: Transmit FIFO Half Empty interrupt * @arg SDIO_IT_RXFIFOHF: Receive FIFO Half Full interrupt * @arg SDIO_IT_TXFIFOF: Transmit FIFO full interrupt * @arg SDIO_IT_RXFIFOF: Receive FIFO full interrupt * @arg SDIO_IT_TXFIFOE: Transmit FIFO empty interrupt * @arg SDIO_IT_RXFIFOE: Receive FIFO empty interrupt * @arg SDIO_IT_TXDAVL: Data available in transmit FIFO interrupt * @arg SDIO_IT_RXDAVL: Data available in receive FIFO interrupt * @arg SDIO_IT_SDIOIT: SD I/O interrupt received interrupt * @arg SDIO_IT_CEATAEND: CE-ATA command completion signal received for CMD61 interrupt * @retval None */ #define __SDIO_DISABLE_IT(__INSTANCE__, __INTERRUPT__) ((__INSTANCE__)->MASK &= ~(__INTERRUPT__)) /** * @brief Checks whether the specified SDIO flag is set or not. * @param __INSTANCE__ : Pointer to SDIO register base * @param __FLAG__: specifies the flag to check. * This parameter can be one of the following values: * @arg SDIO_FLAG_CCRCFAIL: Command response received (CRC check failed) * @arg SDIO_FLAG_DCRCFAIL: Data block sent/received (CRC check failed) * @arg SDIO_FLAG_CTIMEOUT: Command response timeout * @arg SDIO_FLAG_DTIMEOUT: Data timeout * @arg SDIO_FLAG_TXUNDERR: Transmit FIFO underrun error * @arg SDIO_FLAG_RXOVERR: Received FIFO overrun error * @arg SDIO_FLAG_CMDREND: Command response received (CRC check passed) * @arg SDIO_FLAG_CMDSENT: Command sent (no response required) * @arg SDIO_FLAG_DATAEND: Data end (data counter, SDIDCOUNT, is zero) * @arg SDIO_FLAG_STBITERR: Start bit not detected on all data signals in wide bus mode. * @arg SDIO_FLAG_DBCKEND: Data block sent/received (CRC check passed) * @arg SDIO_FLAG_CMDACT: Command transfer in progress * @arg SDIO_FLAG_TXACT: Data transmit in progress * @arg SDIO_FLAG_RXACT: Data receive in progress * @arg SDIO_FLAG_TXFIFOHE: Transmit FIFO Half Empty * @arg SDIO_FLAG_RXFIFOHF: Receive FIFO Half Full * @arg SDIO_FLAG_TXFIFOF: Transmit FIFO full * @arg SDIO_FLAG_RXFIFOF: Receive FIFO full * @arg SDIO_FLAG_TXFIFOE: Transmit FIFO empty * @arg SDIO_FLAG_RXFIFOE: Receive FIFO empty * @arg SDIO_FLAG_TXDAVL: Data available in transmit FIFO * @arg SDIO_FLAG_RXDAVL: Data available in receive FIFO * @arg SDIO_FLAG_SDIOIT: SD I/O interrupt received * @arg SDIO_FLAG_CEATAEND: CE-ATA command completion signal received for CMD61 * @retval The new state of SDIO_FLAG (SET or RESET). */ #define __SDIO_GET_FLAG(__INSTANCE__, __FLAG__) (((__INSTANCE__)->STA &(__FLAG__)) != RESET) /** * @brief Clears the SDIO pending flags. * @param __INSTANCE__ : Pointer to SDIO register base * @param __FLAG__: specifies the flag to clear. * This parameter can be one or a combination of the following values: * @arg SDIO_FLAG_CCRCFAIL: Command response received (CRC check failed) * @arg SDIO_FLAG_DCRCFAIL: Data block sent/received (CRC check failed) * @arg SDIO_FLAG_CTIMEOUT: Command response timeout * @arg SDIO_FLAG_DTIMEOUT: Data timeout * @arg SDIO_FLAG_TXUNDERR: Transmit FIFO underrun error * @arg SDIO_FLAG_RXOVERR: Received FIFO overrun error * @arg SDIO_FLAG_CMDREND: Command response received (CRC check passed) * @arg SDIO_FLAG_CMDSENT: Command sent (no response required) * @arg SDIO_FLAG_DATAEND: Data end (data counter, SDIDCOUNT, is zero) * @arg SDIO_FLAG_STBITERR: Start bit not detected on all data signals in wide bus mode * @arg SDIO_FLAG_DBCKEND: Data block sent/received (CRC check passed) * @arg SDIO_FLAG_SDIOIT: SD I/O interrupt received * @arg SDIO_FLAG_CEATAEND: CE-ATA command completion signal received for CMD61 * @retval None */ #define __SDIO_CLEAR_FLAG(__INSTANCE__, __FLAG__) ((__INSTANCE__)->ICR = (__FLAG__)) /** * @brief Checks whether the specified SDIO interrupt has occurred or not. * @param __INSTANCE__ : Pointer to SDIO register base * @param __INTERRUPT__: specifies the SDIO interrupt source to check. * This parameter can be one of the following values: * @arg SDIO_IT_CCRCFAIL: Command response received (CRC check failed) interrupt * @arg SDIO_IT_DCRCFAIL: Data block sent/received (CRC check failed) interrupt * @arg SDIO_IT_CTIMEOUT: Command response timeout interrupt * @arg SDIO_IT_DTIMEOUT: Data timeout interrupt * @arg SDIO_IT_TXUNDERR: Transmit FIFO underrun error interrupt * @arg SDIO_IT_RXOVERR: Received FIFO overrun error interrupt * @arg SDIO_IT_CMDREND: Command response received (CRC check passed) interrupt * @arg SDIO_IT_CMDSENT: Command sent (no response required) interrupt * @arg SDIO_IT_DATAEND: Data end (data counter, SDIDCOUNT, is zero) interrupt * @arg SDIO_IT_STBITERR: Start bit not detected on all data signals in wide * bus mode interrupt * @arg SDIO_IT_DBCKEND: Data block sent/received (CRC check passed) interrupt * @arg SDIO_IT_CMDACT: Command transfer in progress interrupt * @arg SDIO_IT_TXACT: Data transmit in progress interrupt * @arg SDIO_IT_RXACT: Data receive in progress interrupt * @arg SDIO_IT_TXFIFOHE: Transmit FIFO Half Empty interrupt * @arg SDIO_IT_RXFIFOHF: Receive FIFO Half Full interrupt * @arg SDIO_IT_TXFIFOF: Transmit FIFO full interrupt * @arg SDIO_IT_RXFIFOF: Receive FIFO full interrupt * @arg SDIO_IT_TXFIFOE: Transmit FIFO empty interrupt * @arg SDIO_IT_RXFIFOE: Receive FIFO empty interrupt * @arg SDIO_IT_TXDAVL: Data available in transmit FIFO interrupt * @arg SDIO_IT_RXDAVL: Data available in receive FIFO interrupt * @arg SDIO_IT_SDIOIT: SD I/O interrupt received interrupt * @arg SDIO_IT_CEATAEND: CE-ATA command completion signal received for CMD61 interrupt * @retval The new state of SDIO_IT (SET or RESET). */ #define __SDIO_GET_IT (__INSTANCE__, __INTERRUPT__) (((__INSTANCE__)->STA &(__INTERRUPT__)) == (__INTERRUPT__)) /** * @brief Clears the SDIO's interrupt pending bits. * @param __INSTANCE__ : Pointer to SDIO register base * @param __INTERRUPT__: specifies the interrupt pending bit to clear. * This parameter can be one or a combination of the following values: * @arg SDIO_IT_CCRCFAIL: Command response received (CRC check failed) interrupt * @arg SDIO_IT_DCRCFAIL: Data block sent/received (CRC check failed) interrupt * @arg SDIO_IT_CTIMEOUT: Command response timeout interrupt * @arg SDIO_IT_DTIMEOUT: Data timeout interrupt * @arg SDIO_IT_TXUNDERR: Transmit FIFO underrun error interrupt * @arg SDIO_IT_RXOVERR: Received FIFO overrun error interrupt * @arg SDIO_IT_CMDREND: Command response received (CRC check passed) interrupt * @arg SDIO_IT_CMDSENT: Command sent (no response required) interrupt * @arg SDIO_IT_DATAEND: Data end (data counter, SDIO_DCOUNT, is zero) interrupt * @arg SDIO_IT_STBITERR: Start bit not detected on all data signals in wide * bus mode interrupt * @arg SDIO_IT_SDIOIT: SD I/O interrupt received interrupt * @arg SDIO_IT_CEATAEND: CE-ATA command completion signal received for CMD61 * @retval None */ #define __SDIO_CLEAR_IT(__INSTANCE__, __INTERRUPT__) ((__INSTANCE__)->ICR = (__INTERRUPT__)) /** * @brief Enable Start the SD I/O Read Wait operation. * @retval None */ #define __SDIO_START_READWAIT_ENABLE() (*(__IO uint32_t *) DCTRL_RWSTART_BB = ENABLE) /** * @brief Disable Start the SD I/O Read Wait operations. * @retval None */ #define __SDIO_START_READWAIT_DISABLE() (*(__IO uint32_t *) DCTRL_RWSTART_BB = DISABLE) /** * @brief Enable Start the SD I/O Read Wait operation. * @retval None */ #define __SDIO_STOP_READWAIT_ENABLE() (*(__IO uint32_t *) DCTRL_RWSTOP_BB = ENABLE) /** * @brief Disable Stop the SD I/O Read Wait operations. * @retval None */ #define __SDIO_STOP_READWAIT_DISABLE() (*(__IO uint32_t *) DCTRL_RWSTOP_BB = DISABLE) /** * @brief Enable the SD I/O Mode Operation. * @retval None */ #define __SDIO_OPERATION_ENABLE() (*(__IO uint32_t *) DCTRL_SDIOEN_BB = ENABLE) /** * @brief Disable the SD I/O Mode Operation. * @retval None */ #define __SDIO_OPERATION_DISABLE() (*(__IO uint32_t *) DCTRL_SDIOEN_BB = DISABLE) /** * @brief Enable the SD I/O Suspend command sending. * @retval None */ #define __SDIO_SUSPEND_CMD_ENABLE() (*(__IO uint32_t *) CMD_SDIOSUSPEND_BB = ENABLE) /** * @brief Disable the SD I/O Suspend command sending. * @retval None */ #define __SDIO_SUSPEND_CMD_DISABLE() (*(__IO uint32_t *) CMD_SDIOSUSPEND_BB = DISABLE) #if defined(STM32F405xx) || defined(STM32F415xx) || defined(STM32F407xx) || defined(STM32F417xx) ||\ defined(STM32F427xx) || defined(STM32F437xx) || defined(STM32F429xx) || defined(STM32F439xx) ||\ defined(STM32F401xC) || defined(STM32F401xE) || defined(STM32F411xE) /** * @brief Enable the command completion signal. * @retval None */ #define __SDIO_CEATA_CMD_COMPLETION_ENABLE() (*(__IO uint32_t *) CMD_ENCMDCOMPL_BB = ENABLE) /** * @brief Disable the command completion signal. * @retval None */ #define __SDIO_CEATA_CMD_COMPLETION_DISABLE() (*(__IO uint32_t *) CMD_ENCMDCOMPL_BB = DISABLE) /** * @brief Enable the CE-ATA interrupt. * @retval None */ #define __SDIO_CEATA_ENABLE_IT() (*(__IO uint32_t *) CMD_NIEN_BB = (uint32_t)0) /** * @brief Disable the CE-ATA interrupt. * @retval None */ #define __SDIO_CEATA_DISABLE_IT() (*(__IO uint32_t *) CMD_NIEN_BB = (uint32_t)1) /** * @brief Enable send CE-ATA command (CMD61). * @retval None */ #define __SDIO_CEATA_SENDCMD_ENABLE() (*(__IO uint32_t *) CMD_ATACMD_BB = ENABLE) /** * @brief Disable send CE-ATA command (CMD61). * @retval None */ #define __SDIO_CEATA_SENDCMD_DISABLE() (*(__IO uint32_t *) CMD_ATACMD_BB = DISABLE) #endif /* STM32F405xx || STM32F415xx || STM32F407xx || STM32F417xx || STM32F401xC || STM32F401xE || STM32F411xE ||\ STM32F427xx || STM32F437xx || STM32F429xx || STM32F439xx */ /** * @} */ /** * @} */ /* Exported functions --------------------------------------------------------*/ /** @addtogroup SDMMC_LL_Exported_Functions * @{ */ /* Initialization/de-initialization functions **********************************/ /** @addtogroup HAL_SDMMC_LL_Group1 * @{ */ HAL_StatusTypeDef SDIO_Init(SDIO_TypeDef *SDIOx, SDIO_InitTypeDef Init); /** * @} */ /* I/O operation functions *****************************************************/ /** @addtogroup HAL_SDMMC_LL_Group2 * @{ */ /* Blocking mode: Polling */ uint32_t SDIO_ReadFIFO(SDIO_TypeDef *SDIOx); HAL_StatusTypeDef SDIO_WriteFIFO(SDIO_TypeDef *SDIOx, uint32_t *pWriteData); /** * @} */ /* Peripheral Control functions ************************************************/ /** @addtogroup HAL_SDMMC_LL_Group3 * @{ */ HAL_StatusTypeDef SDIO_PowerState_ON(SDIO_TypeDef *SDIOx); HAL_StatusTypeDef SDIO_PowerState_OFF(SDIO_TypeDef *SDIOx); uint32_t SDIO_GetPowerState(SDIO_TypeDef *SDIOx); /* Command path state machine (CPSM) management functions */ HAL_StatusTypeDef SDIO_SendCommand(SDIO_TypeDef *SDIOx, SDIO_CmdInitTypeDef *SDIO_CmdInitStruct); uint8_t SDIO_GetCommandResponse(SDIO_TypeDef *SDIOx); uint32_t SDIO_GetResponse(uint32_t SDIO_RESP); /* Data path state machine (DPSM) management functions */ HAL_StatusTypeDef SDIO_DataConfig(SDIO_TypeDef *SDIOx, SDIO_DataInitTypeDef* SDIO_DataInitStruct); uint32_t SDIO_GetDataCounter(SDIO_TypeDef *SDIOx); uint32_t SDIO_GetFIFOCount(SDIO_TypeDef *SDIOx); /* SDIO IO Cards mode management functions */ HAL_StatusTypeDef SDIO_SetSDIOReadWaitMode(uint32_t SDIO_ReadWaitMode); /** * @} */ /** * @} */ /** * @} */ /** * @} */ #endif /* STM32F405xx || STM32F415xx || STM32F407xx || STM32F417xx || STM32F427xx || STM32F437xx || STM32F429xx || STM32F439xx || STM32F401xC || STM32F401xE || STM32F411xE || STM32F446xx || STM32F469xx || STM32F479xx */ #ifdef __cplusplus } #endif #endif /* __STM32F4xx_LL_SDMMC_H */ /************************ (C) COPYRIGHT STMicroelectronics *****END OF FILE****/ ================================================ FILE: Zelig/mbed/TARGET_NUCLEO_F401RE/stm32f4xx_ll_usb.h ================================================ /** ****************************************************************************** * @file stm32f4xx_ll_usb.h * @author MCD Application Team * @version V1.4.1 * @date 09-October-2015 * @brief Header file of USB Core HAL module. ****************************************************************************** * @attention * *

© COPYRIGHT(c) 2015 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. * ****************************************************************************** */ /* Define to prevent recursive inclusion -------------------------------------*/ #ifndef __STM32F4xx_LL_USB_H #define __STM32F4xx_LL_USB_H #ifdef __cplusplus extern "C" { #endif #if defined(STM32F405xx) || defined(STM32F415xx) || defined(STM32F407xx) || defined(STM32F417xx) || \ defined(STM32F427xx) || defined(STM32F437xx) || defined(STM32F429xx) || defined(STM32F439xx) || \ defined(STM32F401xC) || defined(STM32F401xE) || defined(STM32F411xE) || defined(STM32F446xx) || \ defined(STM32F469xx) || defined(STM32F479xx) /* Includes ------------------------------------------------------------------*/ #include "stm32f4xx_hal_def.h" /** @addtogroup STM32F4xx_HAL * @{ */ /** @addtogroup USB_Core * @{ */ /* Exported types ------------------------------------------------------------*/ /** * @brief USB Mode definition */ typedef enum { USB_OTG_DEVICE_MODE = 0, USB_OTG_HOST_MODE = 1, USB_OTG_DRD_MODE = 2 }USB_OTG_ModeTypeDef; /** * @brief URB States definition */ typedef enum { URB_IDLE = 0, URB_DONE, URB_NOTREADY, URB_NYET, URB_ERROR, URB_STALL }USB_OTG_URBStateTypeDef; /** * @brief Host channel States definition */ typedef enum { HC_IDLE = 0, HC_XFRC, HC_HALTED, HC_NAK, HC_NYET, HC_STALL, HC_XACTERR, HC_BBLERR, HC_DATATGLERR }USB_OTG_HCStateTypeDef; /** * @brief PCD Initialization Structure definition */ typedef struct { uint32_t dev_endpoints; /*!< Device Endpoints number. This parameter depends on the used USB core. This parameter must be a number between Min_Data = 1 and Max_Data = 15 */ uint32_t Host_channels; /*!< Host Channels number. This parameter Depends on the used USB core. This parameter must be a number between Min_Data = 1 and Max_Data = 15 */ uint32_t speed; /*!< USB Core speed. This parameter can be any value of @ref USB_Core_Speed_ */ uint32_t dma_enable; /*!< Enable or disable of the USB embedded DMA. */ uint32_t ep0_mps; /*!< Set the Endpoint 0 Max Packet size. This parameter can be any value of @ref USB_EP0_MPS_ */ uint32_t phy_itface; /*!< Select the used PHY interface. This parameter can be any value of @ref USB_Core_PHY_ */ uint32_t Sof_enable; /*!< Enable or disable the output of the SOF signal. */ uint32_t low_power_enable; /*!< Enable or disable the low power mode. */ uint32_t lpm_enable; /*!< Enable or disable Link Power Management. */ uint32_t battery_charging_enable; /*!< Enable or disable Battery charging. */ uint32_t vbus_sensing_enable; /*!< Enable or disable the VBUS Sensing feature. */ uint32_t use_dedicated_ep1; /*!< Enable or disable the use of the dedicated EP1 interrupt. */ uint32_t use_external_vbus; /*!< Enable or disable the use of the external VBUS. */ }USB_OTG_CfgTypeDef; typedef struct { uint8_t num; /*!< Endpoint number This parameter must be a number between Min_Data = 1 and Max_Data = 15 */ uint8_t is_in; /*!< Endpoint direction This parameter must be a number between Min_Data = 0 and Max_Data = 1 */ uint8_t is_stall; /*!< Endpoint stall condition This parameter must be a number between Min_Data = 0 and Max_Data = 1 */ uint8_t type; /*!< Endpoint type This parameter can be any value of @ref USB_EP_Type_ */ uint8_t data_pid_start; /*!< Initial data PID This parameter must be a number between Min_Data = 0 and Max_Data = 1 */ uint8_t even_odd_frame; /*!< IFrame parity This parameter must be a number between Min_Data = 0 and Max_Data = 1 */ uint16_t tx_fifo_num; /*!< Transmission FIFO number This parameter must be a number between Min_Data = 1 and Max_Data = 15 */ uint32_t maxpacket; /*!< Endpoint Max packet size This parameter must be a number between Min_Data = 0 and Max_Data = 64KB */ uint8_t *xfer_buff; /*!< Pointer to transfer buffer */ uint32_t dma_addr; /*!< 32 bits aligned transfer buffer address */ uint32_t xfer_len; /*!< Current transfer length */ uint32_t xfer_count; /*!< Partial transfer length in case of multi packet transfer */ }USB_OTG_EPTypeDef; typedef struct { uint8_t dev_addr ; /*!< USB device address. This parameter must be a number between Min_Data = 1 and Max_Data = 255 */ uint8_t ch_num; /*!< Host channel number. This parameter must be a number between Min_Data = 1 and Max_Data = 15 */ uint8_t ep_num; /*!< Endpoint number. This parameter must be a number between Min_Data = 1 and Max_Data = 15 */ uint8_t ep_is_in; /*!< Endpoint direction This parameter must be a number between Min_Data = 0 and Max_Data = 1 */ uint8_t speed; /*!< USB Host speed. This parameter can be any value of @ref USB_Core_Speed_ */ uint8_t do_ping; /*!< Enable or disable the use of the PING protocol for HS mode. */ uint8_t process_ping; /*!< Execute the PING protocol for HS mode. */ uint8_t ep_type; /*!< Endpoint Type. This parameter can be any value of @ref USB_EP_Type_ */ uint16_t max_packet; /*!< Endpoint Max packet size. This parameter must be a number between Min_Data = 0 and Max_Data = 64KB */ uint8_t data_pid; /*!< Initial data PID. This parameter must be a number between Min_Data = 0 and Max_Data = 1 */ uint8_t *xfer_buff; /*!< Pointer to transfer buffer. */ uint32_t xfer_len; /*!< Current transfer length. */ uint32_t xfer_count; /*!< Partial transfer length in case of multi packet transfer. */ uint8_t toggle_in; /*!< IN transfer current toggle flag. This parameter must be a number between Min_Data = 0 and Max_Data = 1 */ uint8_t toggle_out; /*!< OUT transfer current toggle flag This parameter must be a number between Min_Data = 0 and Max_Data = 1 */ uint32_t dma_addr; /*!< 32 bits aligned transfer buffer address. */ uint32_t ErrCnt; /*!< Host channel error count.*/ USB_OTG_URBStateTypeDef urb_state; /*!< URB state. This parameter can be any value of @ref USB_OTG_URBStateTypeDef */ USB_OTG_HCStateTypeDef state; /*!< Host Channel state. This parameter can be any value of @ref USB_OTG_HCStateTypeDef */ }USB_OTG_HCTypeDef; /* Exported constants --------------------------------------------------------*/ /** @defgroup PCD_Exported_Constants PCD Exported Constants * @{ */ /** @defgroup USB_Core_Mode_ USB Core Mode * @{ */ #define USB_OTG_MODE_DEVICE 0 #define USB_OTG_MODE_HOST 1 #define USB_OTG_MODE_DRD 2 /** * @} */ /** @defgroup USB_Core_Speed_ USB Core Speed * @{ */ #define USB_OTG_SPEED_HIGH 0 #define USB_OTG_SPEED_HIGH_IN_FULL 1 #define USB_OTG_SPEED_LOW 2 #define USB_OTG_SPEED_FULL 3 /** * @} */ /** @defgroup USB_Core_PHY_ USB Core PHY * @{ */ #define USB_OTG_ULPI_PHY 1 #define USB_OTG_EMBEDDED_PHY 2 /** * @} */ /** @defgroup USB_Core_MPS_ USB Core MPS * @{ */ #define USB_OTG_HS_MAX_PACKET_SIZE 512 #define USB_OTG_FS_MAX_PACKET_SIZE 64 #define USB_OTG_MAX_EP0_SIZE 64 /** * @} */ /** @defgroup USB_Core_Phy_Frequency_ USB Core Phy Frequency * @{ */ #define DSTS_ENUMSPD_HS_PHY_30MHZ_OR_60MHZ (0 << 1) #define DSTS_ENUMSPD_FS_PHY_30MHZ_OR_60MHZ (1 << 1) #define DSTS_ENUMSPD_LS_PHY_6MHZ (2 << 1) #define DSTS_ENUMSPD_FS_PHY_48MHZ (3 << 1) /** * @} */ /** @defgroup USB_CORE_Frame_Interval_ USB CORE Frame Interval * @{ */ #define DCFG_FRAME_INTERVAL_80 0 #define DCFG_FRAME_INTERVAL_85 1 #define DCFG_FRAME_INTERVAL_90 2 #define DCFG_FRAME_INTERVAL_95 3 /** * @} */ /** @defgroup USB_EP0_MPS_ USB EP0 MPS * @{ */ #define DEP0CTL_MPS_64 0 #define DEP0CTL_MPS_32 1 #define DEP0CTL_MPS_16 2 #define DEP0CTL_MPS_8 3 /** * @} */ /** @defgroup USB_EP_Speed_ USB EP Speed * @{ */ #define EP_SPEED_LOW 0 #define EP_SPEED_FULL 1 #define EP_SPEED_HIGH 2 /** * @} */ /** @defgroup USB_EP_Type_ USB EP Type * @{ */ #define EP_TYPE_CTRL 0 #define EP_TYPE_ISOC 1 #define EP_TYPE_BULK 2 #define EP_TYPE_INTR 3 #define EP_TYPE_MSK 3 /** * @} */ /** @defgroup USB_STS_Defines_ USB STS Defines * @{ */ #define STS_GOUT_NAK 1 #define STS_DATA_UPDT 2 #define STS_XFER_COMP 3 #define STS_SETUP_COMP 4 #define STS_SETUP_UPDT 6 /** * @} */ /** @defgroup HCFG_SPEED_Defines_ HCFG SPEED Defines * @{ */ #define HCFG_30_60_MHZ 0 #define HCFG_48_MHZ 1 #define HCFG_6_MHZ 2 /** * @} */ /** @defgroup HPRT0_PRTSPD_SPEED_Defines_ HPRT0 PRTSPD SPEED Defines * @{ */ #define HPRT0_PRTSPD_HIGH_SPEED 0 #define HPRT0_PRTSPD_FULL_SPEED 1 #define HPRT0_PRTSPD_LOW_SPEED 2 /** * @} */ #define HCCHAR_CTRL 0 #define HCCHAR_ISOC 1 #define HCCHAR_BULK 2 #define HCCHAR_INTR 3 #define HC_PID_DATA0 0 #define HC_PID_DATA2 1 #define HC_PID_DATA1 2 #define HC_PID_SETUP 3 #define GRXSTS_PKTSTS_IN 2 #define GRXSTS_PKTSTS_IN_XFER_COMP 3 #define GRXSTS_PKTSTS_DATA_TOGGLE_ERR 5 #define GRXSTS_PKTSTS_CH_HALTED 7 #define USBx_PCGCCTL *(__IO uint32_t *)((uint32_t)USBx + USB_OTG_PCGCCTL_BASE) #define USBx_HPRT0 *(__IO uint32_t *)((uint32_t)USBx + USB_OTG_HOST_PORT_BASE) #define USBx_DEVICE ((USB_OTG_DeviceTypeDef *)((uint32_t )USBx + USB_OTG_DEVICE_BASE)) #define USBx_INEP(i) ((USB_OTG_INEndpointTypeDef *)((uint32_t)USBx + USB_OTG_IN_ENDPOINT_BASE + (i)*USB_OTG_EP_REG_SIZE)) #define USBx_OUTEP(i) ((USB_OTG_OUTEndpointTypeDef *)((uint32_t)USBx + USB_OTG_OUT_ENDPOINT_BASE + (i)*USB_OTG_EP_REG_SIZE)) #define USBx_DFIFO(i) *(__IO uint32_t *)((uint32_t)USBx + USB_OTG_FIFO_BASE + (i) * USB_OTG_FIFO_SIZE) #define USBx_HOST ((USB_OTG_HostTypeDef *)((uint32_t )USBx + USB_OTG_HOST_BASE)) #define USBx_HC(i) ((USB_OTG_HostChannelTypeDef *)((uint32_t)USBx + USB_OTG_HOST_CHANNEL_BASE + (i)*USB_OTG_HOST_CHANNEL_SIZE)) /** * @} */ /* Exported macro ------------------------------------------------------------*/ #define USB_MASK_INTERRUPT(__INSTANCE__, __INTERRUPT__) ((__INSTANCE__)->GINTMSK &= ~(__INTERRUPT__)) #define USB_UNMASK_INTERRUPT(__INSTANCE__, __INTERRUPT__) ((__INSTANCE__)->GINTMSK |= (__INTERRUPT__)) #define CLEAR_IN_EP_INTR(__EPNUM__, __INTERRUPT__) (USBx_INEP(__EPNUM__)->DIEPINT = (__INTERRUPT__)) #define CLEAR_OUT_EP_INTR(__EPNUM__, __INTERRUPT__) (USBx_OUTEP(__EPNUM__)->DOEPINT = (__INTERRUPT__)) /* Exported functions --------------------------------------------------------*/ HAL_StatusTypeDef USB_CoreInit(USB_OTG_GlobalTypeDef *USBx, USB_OTG_CfgTypeDef Init); HAL_StatusTypeDef USB_DevInit(USB_OTG_GlobalTypeDef *USBx, USB_OTG_CfgTypeDef Init); HAL_StatusTypeDef USB_EnableGlobalInt(USB_OTG_GlobalTypeDef *USBx); HAL_StatusTypeDef USB_DisableGlobalInt(USB_OTG_GlobalTypeDef *USBx); HAL_StatusTypeDef USB_SetCurrentMode(USB_OTG_GlobalTypeDef *USBx , USB_OTG_ModeTypeDef mode); HAL_StatusTypeDef USB_SetDevSpeed(USB_OTG_GlobalTypeDef *USBx , uint8_t speed); HAL_StatusTypeDef USB_FlushRxFifo (USB_OTG_GlobalTypeDef *USBx); HAL_StatusTypeDef USB_FlushTxFifo (USB_OTG_GlobalTypeDef *USBx, uint32_t num ); HAL_StatusTypeDef USB_ActivateEndpoint(USB_OTG_GlobalTypeDef *USBx, USB_OTG_EPTypeDef *ep); HAL_StatusTypeDef USB_DeactivateEndpoint(USB_OTG_GlobalTypeDef *USBx, USB_OTG_EPTypeDef *ep); HAL_StatusTypeDef USB_ActivateDedicatedEndpoint(USB_OTG_GlobalTypeDef *USBx, USB_OTG_EPTypeDef *ep); HAL_StatusTypeDef USB_DeactivateDedicatedEndpoint(USB_OTG_GlobalTypeDef *USBx, USB_OTG_EPTypeDef *ep); HAL_StatusTypeDef USB_EPStartXfer(USB_OTG_GlobalTypeDef *USBx , USB_OTG_EPTypeDef *ep, uint8_t dma); HAL_StatusTypeDef USB_EP0StartXfer(USB_OTG_GlobalTypeDef *USBx , USB_OTG_EPTypeDef *ep, uint8_t dma); HAL_StatusTypeDef USB_WritePacket(USB_OTG_GlobalTypeDef *USBx, uint8_t *src, uint8_t ch_ep_num, uint16_t len, uint8_t dma); void * USB_ReadPacket(USB_OTG_GlobalTypeDef *USBx, uint8_t *dest, uint16_t len); HAL_StatusTypeDef USB_EPSetStall(USB_OTG_GlobalTypeDef *USBx , USB_OTG_EPTypeDef *ep); HAL_StatusTypeDef USB_EPClearStall(USB_OTG_GlobalTypeDef *USBx , USB_OTG_EPTypeDef *ep); HAL_StatusTypeDef USB_SetDevAddress (USB_OTG_GlobalTypeDef *USBx, uint8_t address); HAL_StatusTypeDef USB_DevConnect (USB_OTG_GlobalTypeDef *USBx); HAL_StatusTypeDef USB_DevDisconnect (USB_OTG_GlobalTypeDef *USBx); HAL_StatusTypeDef USB_StopDevice(USB_OTG_GlobalTypeDef *USBx); HAL_StatusTypeDef USB_ActivateSetup (USB_OTG_GlobalTypeDef *USBx); HAL_StatusTypeDef USB_EP0_OutStart(USB_OTG_GlobalTypeDef *USBx, uint8_t dma, uint8_t *psetup); uint8_t USB_GetDevSpeed(USB_OTG_GlobalTypeDef *USBx); uint32_t USB_GetMode(USB_OTG_GlobalTypeDef *USBx); uint32_t USB_ReadInterrupts (USB_OTG_GlobalTypeDef *USBx); uint32_t USB_ReadDevAllOutEpInterrupt (USB_OTG_GlobalTypeDef *USBx); uint32_t USB_ReadDevOutEPInterrupt (USB_OTG_GlobalTypeDef *USBx , uint8_t epnum); uint32_t USB_ReadDevAllInEpInterrupt (USB_OTG_GlobalTypeDef *USBx); uint32_t USB_ReadDevInEPInterrupt (USB_OTG_GlobalTypeDef *USBx , uint8_t epnum); void USB_ClearInterrupts (USB_OTG_GlobalTypeDef *USBx, uint32_t interrupt); HAL_StatusTypeDef USB_HostInit (USB_OTG_GlobalTypeDef *USBx, USB_OTG_CfgTypeDef cfg); HAL_StatusTypeDef USB_InitFSLSPClkSel(USB_OTG_GlobalTypeDef *USBx , uint8_t freq); HAL_StatusTypeDef USB_ResetPort(USB_OTG_GlobalTypeDef *USBx); HAL_StatusTypeDef USB_DriveVbus (USB_OTG_GlobalTypeDef *USBx, uint8_t state); uint32_t USB_GetHostSpeed (USB_OTG_GlobalTypeDef *USBx); uint32_t USB_GetCurrentFrame (USB_OTG_GlobalTypeDef *USBx); HAL_StatusTypeDef USB_HC_Init(USB_OTG_GlobalTypeDef *USBx, uint8_t ch_num, uint8_t epnum, uint8_t dev_address, uint8_t speed, uint8_t ep_type, uint16_t mps); HAL_StatusTypeDef USB_HC_StartXfer(USB_OTG_GlobalTypeDef *USBx, USB_OTG_HCTypeDef *hc, uint8_t dma); uint32_t USB_HC_ReadInterrupt (USB_OTG_GlobalTypeDef *USBx); HAL_StatusTypeDef USB_HC_Halt(USB_OTG_GlobalTypeDef *USBx , uint8_t hc_num); HAL_StatusTypeDef USB_DoPing(USB_OTG_GlobalTypeDef *USBx , uint8_t ch_num); HAL_StatusTypeDef USB_StopHost(USB_OTG_GlobalTypeDef *USBx); /** * @} */ /** * @} */ #endif /* STM32F405xx || STM32F415xx || STM32F407xx || STM32F417xx || STM32F427xx || STM32F437xx || STM32F429xx || STM32F439xx || STM32F401xC || STM32F401xE || STM32F411xE || STM32F446xx || STM32F469xx || STM32F479xx */ #ifdef __cplusplus } #endif #endif /* __STM32F4xx_LL_USB_H */ /************************ (C) COPYRIGHT STMicroelectronics *****END OF FILE****/ ================================================ FILE: Zelig/mbed/TARGET_NUCLEO_F401RE/system_stm32f4xx.h ================================================ /** ****************************************************************************** * @file system_stm32f4xx.h * @author MCD Application Team * @version V2.3.2 * @date 26-June-2015 * @brief CMSIS Cortex-M4 Device System Source File for STM32F4xx devices. ****************************************************************************** * @attention * *

© COPYRIGHT(c) 2015 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. * ****************************************************************************** */ /** @addtogroup CMSIS * @{ */ /** @addtogroup stm32f4xx_system * @{ */ /** * @brief Define to prevent recursive inclusion */ #ifndef __SYSTEM_STM32F4XX_H #define __SYSTEM_STM32F4XX_H #ifdef __cplusplus extern "C" { #endif /** @addtogroup STM32F4xx_System_Includes * @{ */ /** * @} */ /** @addtogroup STM32F4xx_System_Exported_types * @{ */ /* This variable is updated in three ways: 1) by calling CMSIS function SystemCoreClockUpdate() 2) by calling HAL API function HAL_RCC_GetSysClockFreq() 3) each time HAL_RCC_ClockConfig() is called to configure the system clock frequency Note: If you use this function to configure the system clock; then there is no need to call the 2 first functions listed above, since SystemCoreClock variable is updated automatically. */ extern uint32_t SystemCoreClock; /*!< System Clock Frequency (Core Clock) */ /** * @} */ /** @addtogroup STM32F4xx_System_Exported_Constants * @{ */ /** * @} */ /** @addtogroup STM32F4xx_System_Exported_Macros * @{ */ /** * @} */ /** @addtogroup STM32F4xx_System_Exported_Functions * @{ */ extern void SystemInit(void); extern void SystemCoreClockUpdate(void); extern void SetSysClock(void); /** * @} */ #ifdef __cplusplus } #endif #endif /*__SYSTEM_STM32F4XX_H */ /** * @} */ /** * @} */ /************************ (C) COPYRIGHT STMicroelectronics *****END OF FILE****/ ================================================ FILE: Zelig/mbed/TARGET_NUCLEO_F411RE/TARGET_STM/TARGET_STM32F4/PeripheralPins.h ================================================ /* mbed Microcontroller Library ******************************************************************************* * Copyright (c) 2014, STMicroelectronics * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * 1. Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * 3. Neither the name of 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. ******************************************************************************* */ #ifndef MBED_PERIPHERALPINS_H #define MBED_PERIPHERALPINS_H #include "pinmap.h" #include "PeripheralNames.h" //*** ADC *** extern const PinMap PinMap_ADC[]; //*** DAC *** extern const PinMap PinMap_DAC[]; //*** I2C *** extern const PinMap PinMap_I2C_SDA[]; extern const PinMap PinMap_I2C_SCL[]; //*** PWM *** extern const PinMap PinMap_PWM[]; //*** SERIAL *** extern const PinMap PinMap_UART_TX[]; extern const PinMap PinMap_UART_RX[]; //*** SPI *** extern const PinMap PinMap_SPI_MOSI[]; extern const PinMap PinMap_SPI_MISO[]; extern const PinMap PinMap_SPI_SCLK[]; extern const PinMap PinMap_SPI_SSEL[]; #endif ================================================ FILE: Zelig/mbed/TARGET_NUCLEO_F411RE/TARGET_STM/TARGET_STM32F4/TARGET_NUCLEO_F411RE/PeripheralNames.h ================================================ /* mbed Microcontroller Library ******************************************************************************* * Copyright (c) 2014, STMicroelectronics * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * 1. Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * 3. Neither the name of 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. ******************************************************************************* */ #ifndef MBED_PERIPHERALNAMES_H #define MBED_PERIPHERALNAMES_H #include "cmsis.h" #ifdef __cplusplus extern "C" { #endif typedef enum { ADC_1 = (int)ADC1_BASE } ADCName; typedef enum { UART_1 = (int)USART1_BASE, UART_2 = (int)USART2_BASE, UART_6 = (int)USART6_BASE } UARTName; #define STDIO_UART_TX PA_2 #define STDIO_UART_RX PA_3 #define STDIO_UART UART_2 typedef enum { SPI_1 = (int)SPI1_BASE, SPI_2 = (int)SPI2_BASE, SPI_3 = (int)SPI3_BASE, SPI_4 = (int)SPI4_BASE, SPI_5 = (int)SPI5_BASE } SPIName; typedef enum { I2C_1 = (int)I2C1_BASE, I2C_2 = (int)I2C2_BASE, I2C_3 = (int)I2C3_BASE } I2CName; typedef enum { PWM_1 = (int)TIM1_BASE, PWM_2 = (int)TIM2_BASE, PWM_3 = (int)TIM3_BASE, PWM_4 = (int)TIM4_BASE, PWM_5 = (int)TIM5_BASE, PWM_9 = (int)TIM9_BASE, PWM_10 = (int)TIM10_BASE, PWM_11 = (int)TIM11_BASE } PWMName; #ifdef __cplusplus } #endif #endif ================================================ FILE: Zelig/mbed/TARGET_NUCLEO_F411RE/TARGET_STM/TARGET_STM32F4/TARGET_NUCLEO_F411RE/PinNames.h ================================================ /* mbed Microcontroller Library ******************************************************************************* * Copyright (c) 2014, STMicroelectronics * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * 1. Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * 3. Neither the name of 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. ******************************************************************************* */ #ifndef MBED_PINNAMES_H #define MBED_PINNAMES_H #include "cmsis.h" #ifdef __cplusplus extern "C" { #endif // See stm32f4xx_hal_gpio.h and stm32f4xx_hal_gpio_ex.h for values of MODE, PUPD and AFNUM #define STM_PIN_DATA(MODE, PUPD, AFNUM) ((int)(((AFNUM) << 7) | ((PUPD) << 4) | ((MODE) << 0))) #define STM_PIN_DATA_EXT(MODE, PUPD, AFNUM, CHANNEL, INVERTED) ((int)(((INVERTED & 0x01) << 15) | ((CHANNEL & 0x0F) << 11) | ((AFNUM & 0x0F) << 7) | ((PUPD & 0x07) << 4) | ((MODE & 0x0F) << 0))) #define STM_PIN_MODE(X) (((X) >> 0) & 0x0F) #define STM_PIN_PUPD(X) (((X) >> 4) & 0x07) #define STM_PIN_AFNUM(X) (((X) >> 7) & 0x0F) #define STM_PIN_CHANNEL(X) (((X) >> 11) & 0x0F) #define STM_PIN_INVERTED(X) (((X) >> 15) & 0x01) #define STM_MODE_INPUT (0) #define STM_MODE_OUTPUT_PP (1) #define STM_MODE_OUTPUT_OD (2) #define STM_MODE_AF_PP (3) #define STM_MODE_AF_OD (4) #define STM_MODE_ANALOG (5) #define STM_MODE_IT_RISING (6) #define STM_MODE_IT_FALLING (7) #define STM_MODE_IT_RISING_FALLING (8) #define STM_MODE_EVT_RISING (9) #define STM_MODE_EVT_FALLING (10) #define STM_MODE_EVT_RISING_FALLING (11) #define STM_MODE_IT_EVT_RESET (12) // High nibble = port number (0=A, 1=B, 2=C, 3=D, 4=E, 5=F, 6=G, 7=H) // Low nibble = pin number #define STM_PORT(X) (((uint32_t)(X) >> 4) & 0xF) #define STM_PIN(X) ((uint32_t)(X) & 0xF) typedef enum { PIN_INPUT, PIN_OUTPUT } PinDirection; typedef enum { PA_0 = 0x00, PA_1 = 0x01, PA_2 = 0x02, PA_3 = 0x03, PA_4 = 0x04, PA_5 = 0x05, PA_6 = 0x06, PA_7 = 0x07, PA_8 = 0x08, PA_9 = 0x09, PA_10 = 0x0A, PA_11 = 0x0B, PA_12 = 0x0C, PA_13 = 0x0D, PA_14 = 0x0E, PA_15 = 0x0F, PB_0 = 0x10, PB_1 = 0x11, PB_2 = 0x12, PB_3 = 0x13, PB_4 = 0x14, PB_5 = 0x15, PB_6 = 0x16, PB_7 = 0x17, PB_8 = 0x18, PB_9 = 0x19, PB_10 = 0x1A, PB_12 = 0x1C, PB_13 = 0x1D, PB_14 = 0x1E, PB_15 = 0x1F, PC_0 = 0x20, PC_1 = 0x21, PC_2 = 0x22, PC_3 = 0x23, PC_4 = 0x24, PC_5 = 0x25, PC_6 = 0x26, PC_7 = 0x27, PC_8 = 0x28, PC_9 = 0x29, PC_10 = 0x2A, PC_11 = 0x2B, PC_12 = 0x2C, PC_13 = 0x2D, PC_14 = 0x2E, PC_15 = 0x2F, PD_2 = 0x32, PH_0 = 0x70, PH_1 = 0x71, // Arduino connector namings A0 = PA_0, A1 = PA_1, A2 = PA_4, A3 = PB_0, A4 = PC_1, A5 = PC_0, D0 = PA_3, D1 = PA_2, D2 = PA_10, D3 = PB_3, D4 = PB_5, D5 = PB_4, D6 = PB_10, D7 = PA_8, D8 = PA_9, D9 = PC_7, D10 = PB_6, D11 = PA_7, D12 = PA_6, D13 = PA_5, D14 = PB_9, D15 = PB_8, // Generic signals namings LED1 = PA_5, LED2 = PA_5, LED3 = PA_5, LED4 = PA_5, USER_BUTTON = PC_13, SERIAL_TX = PA_2, SERIAL_RX = PA_3, USBTX = PA_2, USBRX = PA_3, I2C_SCL = PB_8, I2C_SDA = PB_9, SPI_MOSI = PA_7, SPI_MISO = PA_6, SPI_SCK = PA_5, SPI_CS = PB_6, PWM_OUT = PB_3, // Not connected NC = (int)0xFFFFFFFF } PinName; typedef enum { PullNone = 0, PullUp = 1, PullDown = 2, OpenDrain = 3, PullDefault = PullNone } PinMode; #ifdef __cplusplus } #endif #endif ================================================ FILE: Zelig/mbed/TARGET_NUCLEO_F411RE/TARGET_STM/TARGET_STM32F4/TARGET_NUCLEO_F411RE/PortNames.h ================================================ /* mbed Microcontroller Library ******************************************************************************* * Copyright (c) 2014, STMicroelectronics * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * 1. Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * 3. Neither the name of 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. ******************************************************************************* */ #ifndef MBED_PORTNAMES_H #define MBED_PORTNAMES_H #ifdef __cplusplus extern "C" { #endif typedef enum { PortA = 0, PortB = 1, PortC = 2, PortD = 3, PortE = 4, PortH = 7 } PortName; #ifdef __cplusplus } #endif #endif ================================================ FILE: Zelig/mbed/TARGET_NUCLEO_F411RE/TARGET_STM/TARGET_STM32F4/TARGET_NUCLEO_F411RE/device.h ================================================ /* mbed Microcontroller Library ******************************************************************************* * Copyright (c) 2015, STMicroelectronics * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * 1. Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * 3. Neither the name of 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. ******************************************************************************* */ #ifndef MBED_DEVICE_H #define MBED_DEVICE_H #define DEVICE_PORTIN 1 #define DEVICE_PORTOUT 1 #define DEVICE_PORTINOUT 1 #define DEVICE_INTERRUPTIN 1 #define DEVICE_ANALOGIN 1 #define DEVICE_ANALOGOUT 0 // Not present on this device #define DEVICE_SERIAL 1 #define DEVICE_I2C 1 #define DEVICE_I2CSLAVE 1 #define DEVICE_SPI 1 #define DEVICE_SPISLAVE 1 #define DEVICE_RTC 1 #define DEVICE_PWMOUT 1 #define DEVICE_SLEEP 1 //======================================= #define DEVICE_SEMIHOST 0 #define DEVICE_LOCALFILESYSTEM 0 #define DEVICE_ID_LENGTH 24 #define DEVICE_DEBUG_AWARENESS 0 #define DEVICE_STDIO_MESSAGES 1 #define DEVICE_ERROR_RED 1 #define LED_RED LED1 #include "objects.h" #endif ================================================ FILE: Zelig/mbed/TARGET_NUCLEO_F411RE/TARGET_STM/TARGET_STM32F4/TARGET_NUCLEO_F411RE/objects.h ================================================ /* mbed Microcontroller Library ******************************************************************************* * Copyright (c) 2014, STMicroelectronics * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * 1. Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * 3. Neither the name of 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. ******************************************************************************* */ #ifndef MBED_OBJECTS_H #define MBED_OBJECTS_H #include "cmsis.h" #include "PortNames.h" #include "PeripheralNames.h" #include "PinNames.h" #ifdef __cplusplus extern "C" { #endif struct gpio_irq_s { IRQn_Type irq_n; uint32_t irq_index; uint32_t event; PinName pin; }; struct port_s { PortName port; uint32_t mask; PinDirection direction; __IO uint32_t *reg_in; __IO uint32_t *reg_out; }; struct analogin_s { ADCName adc; PinName pin; uint8_t channel; }; struct serial_s { UARTName uart; int index; // Used by irq uint32_t baudrate; uint32_t databits; uint32_t stopbits; uint32_t parity; PinName pin_tx; PinName pin_rx; }; struct spi_s { SPIName spi; uint32_t bits; uint32_t cpol; uint32_t cpha; uint32_t mode; uint32_t nss; uint32_t br_presc; PinName pin_miso; PinName pin_mosi; PinName pin_sclk; PinName pin_ssel; }; struct i2c_s { I2CName i2c; uint32_t slave; }; struct pwmout_s { PWMName pwm; PinName pin; uint32_t period; uint32_t pulse; uint8_t channel; uint8_t inverted; }; #include "gpio_object.h" #ifdef __cplusplus } #endif #endif ================================================ FILE: Zelig/mbed/TARGET_NUCLEO_F411RE/TARGET_STM/TARGET_STM32F4/gpio_object.h ================================================ /* mbed Microcontroller Library ******************************************************************************* * Copyright (c) 2014, STMicroelectronics * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * 1. Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * 3. Neither the name of 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. ******************************************************************************* */ #ifndef MBED_GPIO_OBJECT_H #define MBED_GPIO_OBJECT_H #include "mbed_assert.h" #include "cmsis.h" #include "PortNames.h" #include "PeripheralNames.h" #include "PinNames.h" #ifdef __cplusplus extern "C" { #endif typedef struct { PinName pin; uint32_t mask; __IO uint32_t *reg_in; __IO uint32_t *reg_set_clr; } gpio_t; static inline void gpio_write(gpio_t *obj, int value) { MBED_ASSERT(obj->pin != (PinName)NC); if (value) { *obj->reg_set_clr = obj->mask; } else { *obj->reg_set_clr = obj->mask << 16; } } static inline int gpio_read(gpio_t *obj) { MBED_ASSERT(obj->pin != (PinName)NC); return ((*obj->reg_in & obj->mask) ? 1 : 0); } static inline int gpio_is_connected(const gpio_t *obj) { return obj->pin != (PinName)NC; } #ifdef __cplusplus } #endif #endif ================================================ FILE: Zelig/mbed/TARGET_NUCLEO_F411RE/TOOLCHAIN_GCC_ARM/STM32F411XE.ld ================================================ /* Linker script to configure memory regions. */ MEMORY { FLASH (rx) : ORIGIN = 0x08000000, LENGTH = 512K RAM (rwx) : ORIGIN = 0x20000198, LENGTH = 128k - 0x198 } /* Linker script to place sections and symbol values. Should be used together * with other linker script that defines memory regions FLASH and RAM. * It references following symbols, which must be defined in code: * Reset_Handler : Entry of reset handler * * It defines following symbols, which code can use without definition: * __exidx_start * __exidx_end * __etext * __data_start__ * __preinit_array_start * __preinit_array_end * __init_array_start * __init_array_end * __fini_array_start * __fini_array_end * __data_end__ * __bss_start__ * __bss_end__ * __end__ * end * __HeapLimit * __StackLimit * __StackTop * __stack * _estack */ ENTRY(Reset_Handler) SECTIONS { .text : { KEEP(*(.isr_vector)) *(.text*) KEEP(*(.init)) KEEP(*(.fini)) /* .ctors */ *crtbegin.o(.ctors) *crtbegin?.o(.ctors) *(EXCLUDE_FILE(*crtend?.o *crtend.o) .ctors) *(SORT(.ctors.*)) *(.ctors) /* .dtors */ *crtbegin.o(.dtors) *crtbegin?.o(.dtors) *(EXCLUDE_FILE(*crtend?.o *crtend.o) .dtors) *(SORT(.dtors.*)) *(.dtors) *(.rodata*) KEEP(*(.eh_frame*)) } > FLASH .ARM.extab : { *(.ARM.extab* .gnu.linkonce.armextab.*) } > FLASH __exidx_start = .; .ARM.exidx : { *(.ARM.exidx* .gnu.linkonce.armexidx.*) } > FLASH __exidx_end = .; __etext = .; _sidata = .; .data : AT (__etext) { __data_start__ = .; _sdata = .; *(vtable) *(.data*) . = ALIGN(4); /* preinit data */ PROVIDE_HIDDEN (__preinit_array_start = .); KEEP(*(.preinit_array)) PROVIDE_HIDDEN (__preinit_array_end = .); . = ALIGN(4); /* init data */ PROVIDE_HIDDEN (__init_array_start = .); KEEP(*(SORT(.init_array.*))) KEEP(*(.init_array)) PROVIDE_HIDDEN (__init_array_end = .); . = ALIGN(4); /* finit data */ PROVIDE_HIDDEN (__fini_array_start = .); KEEP(*(SORT(.fini_array.*))) KEEP(*(.fini_array)) PROVIDE_HIDDEN (__fini_array_end = .); KEEP(*(.jcr*)) . = ALIGN(4); /* All data end */ __data_end__ = .; _edata = .; } > RAM .bss : { . = ALIGN(4); __bss_start__ = .; _sbss = .; *(.bss*) *(COMMON) . = ALIGN(4); __bss_end__ = .; _ebss = .; } > RAM .heap (COPY): { __end__ = .; end = __end__; *(.heap*) __HeapLimit = .; } > RAM /* .stack_dummy section doesn't contains any symbols. It is only * used for linker to calculate size of stack sections, and assign * values to stack symbols later */ .stack_dummy (COPY): { *(.stack*) } > RAM /* * The section '.managed_exception_thread' is a LLILUM Specific addition to pad * the stack space at the bottom with enough space to build a managed array. * Assuming that the stack bottom (_StackLimit) is 8 bytes aligned, we add * 16 bytes that will contain the array ObjectHeader and the length member (see * ArrayImpl.cs). This way we do preserve stack alignment. */ .stack_dummy_managed_exception_thread : { *(.managed_exception_thread) } > RAM /* Set stack top to end of RAM, and stack limit move down by * size of stack_dummy section */ __StackTop = ORIGIN(RAM) + LENGTH(RAM); _estack = __StackTop; __StackLimit = __StackTop - SIZEOF(.stack_dummy) + SIZEOF(.stack_dummy_managed_exception_thread); PROVIDE(__stack = __StackTop); /* Check if data + heap + stack exceeds RAM limit */ ASSERT(__StackLimit >= __HeapLimit, "region RAM overflowed with stack") } ================================================ FILE: Zelig/mbed/TARGET_NUCLEO_F411RE/arm_common_tables.h ================================================ /* ---------------------------------------------------------------------- * Copyright (C) 2010-2014 ARM Limited. All rights reserved. * * $Date: 19. March 2015 * $Revision: V.1.4.5 * * Project: CMSIS DSP Library * Title: arm_common_tables.h * * Description: This file has extern declaration for common tables like Bitreverse, reciprocal etc which are used across different functions * * Target Processor: Cortex-M4/Cortex-M3 * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * - Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * - Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * - Neither the name of ARM LIMITED nor the names of its contributors * may be used to endorse or promote products derived from this * software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * -------------------------------------------------------------------- */ #ifndef _ARM_COMMON_TABLES_H #define _ARM_COMMON_TABLES_H #include "arm_math.h" extern const uint16_t armBitRevTable[1024]; extern const q15_t armRecipTableQ15[64]; extern const q31_t armRecipTableQ31[64]; //extern const q31_t realCoefAQ31[1024]; //extern const q31_t realCoefBQ31[1024]; extern const float32_t twiddleCoef_16[32]; extern const float32_t twiddleCoef_32[64]; extern const float32_t twiddleCoef_64[128]; extern const float32_t twiddleCoef_128[256]; extern const float32_t twiddleCoef_256[512]; extern const float32_t twiddleCoef_512[1024]; extern const float32_t twiddleCoef_1024[2048]; extern const float32_t twiddleCoef_2048[4096]; extern const float32_t twiddleCoef_4096[8192]; #define twiddleCoef twiddleCoef_4096 extern const q31_t twiddleCoef_16_q31[24]; extern const q31_t twiddleCoef_32_q31[48]; extern const q31_t twiddleCoef_64_q31[96]; extern const q31_t twiddleCoef_128_q31[192]; extern const q31_t twiddleCoef_256_q31[384]; extern const q31_t twiddleCoef_512_q31[768]; extern const q31_t twiddleCoef_1024_q31[1536]; extern const q31_t twiddleCoef_2048_q31[3072]; extern const q31_t twiddleCoef_4096_q31[6144]; extern const q15_t twiddleCoef_16_q15[24]; extern const q15_t twiddleCoef_32_q15[48]; extern const q15_t twiddleCoef_64_q15[96]; extern const q15_t twiddleCoef_128_q15[192]; extern const q15_t twiddleCoef_256_q15[384]; extern const q15_t twiddleCoef_512_q15[768]; extern const q15_t twiddleCoef_1024_q15[1536]; extern const q15_t twiddleCoef_2048_q15[3072]; extern const q15_t twiddleCoef_4096_q15[6144]; extern const float32_t twiddleCoef_rfft_32[32]; extern const float32_t twiddleCoef_rfft_64[64]; extern const float32_t twiddleCoef_rfft_128[128]; extern const float32_t twiddleCoef_rfft_256[256]; extern const float32_t twiddleCoef_rfft_512[512]; extern const float32_t twiddleCoef_rfft_1024[1024]; extern const float32_t twiddleCoef_rfft_2048[2048]; extern const float32_t twiddleCoef_rfft_4096[4096]; /* floating-point bit reversal tables */ #define ARMBITREVINDEXTABLE__16_TABLE_LENGTH ((uint16_t)20 ) #define ARMBITREVINDEXTABLE__32_TABLE_LENGTH ((uint16_t)48 ) #define ARMBITREVINDEXTABLE__64_TABLE_LENGTH ((uint16_t)56 ) #define ARMBITREVINDEXTABLE_128_TABLE_LENGTH ((uint16_t)208 ) #define ARMBITREVINDEXTABLE_256_TABLE_LENGTH ((uint16_t)440 ) #define ARMBITREVINDEXTABLE_512_TABLE_LENGTH ((uint16_t)448 ) #define ARMBITREVINDEXTABLE1024_TABLE_LENGTH ((uint16_t)1800) #define ARMBITREVINDEXTABLE2048_TABLE_LENGTH ((uint16_t)3808) #define ARMBITREVINDEXTABLE4096_TABLE_LENGTH ((uint16_t)4032) extern const uint16_t armBitRevIndexTable16[ARMBITREVINDEXTABLE__16_TABLE_LENGTH]; extern const uint16_t armBitRevIndexTable32[ARMBITREVINDEXTABLE__32_TABLE_LENGTH]; extern const uint16_t armBitRevIndexTable64[ARMBITREVINDEXTABLE__64_TABLE_LENGTH]; extern const uint16_t armBitRevIndexTable128[ARMBITREVINDEXTABLE_128_TABLE_LENGTH]; extern const uint16_t armBitRevIndexTable256[ARMBITREVINDEXTABLE_256_TABLE_LENGTH]; extern const uint16_t armBitRevIndexTable512[ARMBITREVINDEXTABLE_512_TABLE_LENGTH]; extern const uint16_t armBitRevIndexTable1024[ARMBITREVINDEXTABLE1024_TABLE_LENGTH]; extern const uint16_t armBitRevIndexTable2048[ARMBITREVINDEXTABLE2048_TABLE_LENGTH]; extern const uint16_t armBitRevIndexTable4096[ARMBITREVINDEXTABLE4096_TABLE_LENGTH]; /* fixed-point bit reversal tables */ #define ARMBITREVINDEXTABLE_FIXED___16_TABLE_LENGTH ((uint16_t)12 ) #define ARMBITREVINDEXTABLE_FIXED___32_TABLE_LENGTH ((uint16_t)24 ) #define ARMBITREVINDEXTABLE_FIXED___64_TABLE_LENGTH ((uint16_t)56 ) #define ARMBITREVINDEXTABLE_FIXED__128_TABLE_LENGTH ((uint16_t)112 ) #define ARMBITREVINDEXTABLE_FIXED__256_TABLE_LENGTH ((uint16_t)240 ) #define ARMBITREVINDEXTABLE_FIXED__512_TABLE_LENGTH ((uint16_t)480 ) #define ARMBITREVINDEXTABLE_FIXED_1024_TABLE_LENGTH ((uint16_t)992 ) #define ARMBITREVINDEXTABLE_FIXED_2048_TABLE_LENGTH ((uint16_t)1984) #define ARMBITREVINDEXTABLE_FIXED_4096_TABLE_LENGTH ((uint16_t)4032) extern const uint16_t armBitRevIndexTable_fixed_16[ARMBITREVINDEXTABLE_FIXED___16_TABLE_LENGTH]; extern const uint16_t armBitRevIndexTable_fixed_32[ARMBITREVINDEXTABLE_FIXED___32_TABLE_LENGTH]; extern const uint16_t armBitRevIndexTable_fixed_64[ARMBITREVINDEXTABLE_FIXED___64_TABLE_LENGTH]; extern const uint16_t armBitRevIndexTable_fixed_128[ARMBITREVINDEXTABLE_FIXED__128_TABLE_LENGTH]; extern const uint16_t armBitRevIndexTable_fixed_256[ARMBITREVINDEXTABLE_FIXED__256_TABLE_LENGTH]; extern const uint16_t armBitRevIndexTable_fixed_512[ARMBITREVINDEXTABLE_FIXED__512_TABLE_LENGTH]; extern const uint16_t armBitRevIndexTable_fixed_1024[ARMBITREVINDEXTABLE_FIXED_1024_TABLE_LENGTH]; extern const uint16_t armBitRevIndexTable_fixed_2048[ARMBITREVINDEXTABLE_FIXED_2048_TABLE_LENGTH]; extern const uint16_t armBitRevIndexTable_fixed_4096[ARMBITREVINDEXTABLE_FIXED_4096_TABLE_LENGTH]; /* Tables for Fast Math Sine and Cosine */ extern const float32_t sinTable_f32[FAST_MATH_TABLE_SIZE + 1]; extern const q31_t sinTable_q31[FAST_MATH_TABLE_SIZE + 1]; extern const q15_t sinTable_q15[FAST_MATH_TABLE_SIZE + 1]; #endif /* ARM_COMMON_TABLES_H */ ================================================ FILE: Zelig/mbed/TARGET_NUCLEO_F411RE/arm_const_structs.h ================================================ /* ---------------------------------------------------------------------- * Copyright (C) 2010-2014 ARM Limited. All rights reserved. * * $Date: 19. March 2015 * $Revision: V.1.4.5 * * Project: CMSIS DSP Library * Title: arm_const_structs.h * * Description: This file has constant structs that are initialized for * user convenience. For example, some can be given as * arguments to the arm_cfft_f32() function. * * Target Processor: Cortex-M4/Cortex-M3 * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * - Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * - Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * - Neither the name of ARM LIMITED nor the names of its contributors * may be used to endorse or promote products derived from this * software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * -------------------------------------------------------------------- */ #ifndef _ARM_CONST_STRUCTS_H #define _ARM_CONST_STRUCTS_H #include "arm_math.h" #include "arm_common_tables.h" extern const arm_cfft_instance_f32 arm_cfft_sR_f32_len16; extern const arm_cfft_instance_f32 arm_cfft_sR_f32_len32; extern const arm_cfft_instance_f32 arm_cfft_sR_f32_len64; extern const arm_cfft_instance_f32 arm_cfft_sR_f32_len128; extern const arm_cfft_instance_f32 arm_cfft_sR_f32_len256; extern const arm_cfft_instance_f32 arm_cfft_sR_f32_len512; extern const arm_cfft_instance_f32 arm_cfft_sR_f32_len1024; extern const arm_cfft_instance_f32 arm_cfft_sR_f32_len2048; extern const arm_cfft_instance_f32 arm_cfft_sR_f32_len4096; extern const arm_cfft_instance_q31 arm_cfft_sR_q31_len16; extern const arm_cfft_instance_q31 arm_cfft_sR_q31_len32; extern const arm_cfft_instance_q31 arm_cfft_sR_q31_len64; extern const arm_cfft_instance_q31 arm_cfft_sR_q31_len128; extern const arm_cfft_instance_q31 arm_cfft_sR_q31_len256; extern const arm_cfft_instance_q31 arm_cfft_sR_q31_len512; extern const arm_cfft_instance_q31 arm_cfft_sR_q31_len1024; extern const arm_cfft_instance_q31 arm_cfft_sR_q31_len2048; extern const arm_cfft_instance_q31 arm_cfft_sR_q31_len4096; extern const arm_cfft_instance_q15 arm_cfft_sR_q15_len16; extern const arm_cfft_instance_q15 arm_cfft_sR_q15_len32; extern const arm_cfft_instance_q15 arm_cfft_sR_q15_len64; extern const arm_cfft_instance_q15 arm_cfft_sR_q15_len128; extern const arm_cfft_instance_q15 arm_cfft_sR_q15_len256; extern const arm_cfft_instance_q15 arm_cfft_sR_q15_len512; extern const arm_cfft_instance_q15 arm_cfft_sR_q15_len1024; extern const arm_cfft_instance_q15 arm_cfft_sR_q15_len2048; extern const arm_cfft_instance_q15 arm_cfft_sR_q15_len4096; #endif ================================================ FILE: Zelig/mbed/TARGET_NUCLEO_F411RE/arm_math.h ================================================ /* ---------------------------------------------------------------------- * Copyright (C) 2010-2015 ARM Limited. All rights reserved. * * $Date: 19. March 2015 * $Revision: V.1.4.5 * * Project: CMSIS DSP Library * Title: arm_math.h * * Description: Public header file for CMSIS DSP Library * * Target Processor: Cortex-M7/Cortex-M4/Cortex-M3/Cortex-M0 * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * - Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * - Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * - Neither the name of ARM LIMITED nor the names of its contributors * may be used to endorse or promote products derived from this * software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * -------------------------------------------------------------------- */ /** \mainpage CMSIS DSP Software Library * * Introduction * ------------ * * This user manual describes the CMSIS DSP software library, * a suite of common signal processing functions for use on Cortex-M processor based devices. * * The library is divided into a number of functions each covering a specific category: * - Basic math functions * - Fast math functions * - Complex math functions * - Filters * - Matrix functions * - Transforms * - Motor control functions * - Statistical functions * - Support functions * - Interpolation functions * * The library has separate functions for operating on 8-bit integers, 16-bit integers, * 32-bit integer and 32-bit floating-point values. * * Using the Library * ------------ * * The library installer contains prebuilt versions of the libraries in the Lib folder. * - arm_cortexM7lfdp_math.lib (Little endian and Double Precision Floating Point Unit on Cortex-M7) * - arm_cortexM7bfdp_math.lib (Big endian and Double Precision Floating Point Unit on Cortex-M7) * - arm_cortexM7lfsp_math.lib (Little endian and Single Precision Floating Point Unit on Cortex-M7) * - arm_cortexM7bfsp_math.lib (Big endian and Single Precision Floating Point Unit on Cortex-M7) * - arm_cortexM7l_math.lib (Little endian on Cortex-M7) * - arm_cortexM7b_math.lib (Big endian on Cortex-M7) * - arm_cortexM4lf_math.lib (Little endian and Floating Point Unit on Cortex-M4) * - arm_cortexM4bf_math.lib (Big endian and Floating Point Unit on Cortex-M4) * - arm_cortexM4l_math.lib (Little endian on Cortex-M4) * - arm_cortexM4b_math.lib (Big endian on Cortex-M4) * - arm_cortexM3l_math.lib (Little endian on Cortex-M3) * - arm_cortexM3b_math.lib (Big endian on Cortex-M3) * - arm_cortexM0l_math.lib (Little endian on Cortex-M0 / CortexM0+) * - arm_cortexM0b_math.lib (Big endian on Cortex-M0 / CortexM0+) * * The library functions are declared in the public file arm_math.h which is placed in the Include folder. * Simply include this file and link the appropriate library in the application and begin calling the library functions. The Library supports single * public header file arm_math.h for Cortex-M7/M4/M3/M0/M0+ with little endian and big endian. Same header file will be used for floating point unit(FPU) variants. * Define the appropriate pre processor MACRO ARM_MATH_CM7 or ARM_MATH_CM4 or ARM_MATH_CM3 or * ARM_MATH_CM0 or ARM_MATH_CM0PLUS depending on the target processor in the application. * * Examples * -------- * * The library ships with a number of examples which demonstrate how to use the library functions. * * Toolchain Support * ------------ * * The library has been developed and tested with MDK-ARM version 5.14.0.0 * The library is being tested in GCC and IAR toolchains and updates on this activity will be made available shortly. * * Building the Library * ------------ * * The library installer contains a project file to re build libraries on MDK-ARM Tool chain in the CMSIS\\DSP_Lib\\Source\\ARM folder. * - arm_cortexM_math.uvprojx * * * The libraries can be built by opening the arm_cortexM_math.uvprojx project in MDK-ARM, selecting a specific target, and defining the optional pre processor MACROs detailed above. * * Pre-processor Macros * ------------ * * Each library project have differant pre-processor macros. * * - UNALIGNED_SUPPORT_DISABLE: * * Define macro UNALIGNED_SUPPORT_DISABLE, If the silicon does not support unaligned memory access * * - ARM_MATH_BIG_ENDIAN: * * Define macro ARM_MATH_BIG_ENDIAN to build the library for big endian targets. By default library builds for little endian targets. * * - ARM_MATH_MATRIX_CHECK: * * Define macro ARM_MATH_MATRIX_CHECK for checking on the input and output sizes of matrices * * - ARM_MATH_ROUNDING: * * Define macro ARM_MATH_ROUNDING for rounding on support functions * * - ARM_MATH_CMx: * * Define macro ARM_MATH_CM4 for building the library on Cortex-M4 target, ARM_MATH_CM3 for building library on Cortex-M3 target * and ARM_MATH_CM0 for building library on Cortex-M0 target, ARM_MATH_CM0PLUS for building library on Cortex-M0+ target, and * ARM_MATH_CM7 for building the library on cortex-M7. * * - __FPU_PRESENT: * * Initialize macro __FPU_PRESENT = 1 when building on FPU supported Targets. Enable this macro for M4bf and M4lf libraries * *
* CMSIS-DSP in ARM::CMSIS Pack * ----------------------------- * * The following files relevant to CMSIS-DSP are present in the ARM::CMSIS Pack directories: * |File/Folder |Content | * |------------------------------|------------------------------------------------------------------------| * |\b CMSIS\\Documentation\\DSP | This documentation | * |\b CMSIS\\DSP_Lib | Software license agreement (license.txt) | * |\b CMSIS\\DSP_Lib\\Examples | Example projects demonstrating the usage of the library functions | * |\b CMSIS\\DSP_Lib\\Source | Source files for rebuilding the library | * *
* Revision History of CMSIS-DSP * ------------ * Please refer to \ref ChangeLog_pg. * * Copyright Notice * ------------ * * Copyright (C) 2010-2015 ARM Limited. All rights reserved. */ /** * @defgroup groupMath Basic Math Functions */ /** * @defgroup groupFastMath Fast Math Functions * This set of functions provides a fast approximation to sine, cosine, and square root. * As compared to most of the other functions in the CMSIS math library, the fast math functions * operate on individual values and not arrays. * There are separate functions for Q15, Q31, and floating-point data. * */ /** * @defgroup groupCmplxMath Complex Math Functions * This set of functions operates on complex data vectors. * The data in the complex arrays is stored in an interleaved fashion * (real, imag, real, imag, ...). * In the API functions, the number of samples in a complex array refers * to the number of complex values; the array contains twice this number of * real values. */ /** * @defgroup groupFilters Filtering Functions */ /** * @defgroup groupMatrix Matrix Functions * * This set of functions provides basic matrix math operations. * The functions operate on matrix data structures. For example, * the type * definition for the floating-point matrix structure is shown * below: *
 *     typedef struct
 *     {
 *       uint16_t numRows;     // number of rows of the matrix.
 *       uint16_t numCols;     // number of columns of the matrix.
 *       float32_t *pData;     // points to the data of the matrix.
 *     } arm_matrix_instance_f32;
 * 
* There are similar definitions for Q15 and Q31 data types. * * The structure specifies the size of the matrix and then points to * an array of data. The array is of size numRows X numCols * and the values are arranged in row order. That is, the * matrix element (i, j) is stored at: *
 *     pData[i*numCols + j]
 * 
* * \par Init Functions * There is an associated initialization function for each type of matrix * data structure. * The initialization function sets the values of the internal structure fields. * Refer to the function arm_mat_init_f32(), arm_mat_init_q31() * and arm_mat_init_q15() for floating-point, Q31 and Q15 types, respectively. * * \par * Use of the initialization function is optional. However, if initialization function is used * then the instance structure cannot be placed into a const data section. * To place the instance structure in a const data * section, manually initialize the data structure. For example: *
 * arm_matrix_instance_f32 S = {nRows, nColumns, pData};
 * arm_matrix_instance_q31 S = {nRows, nColumns, pData};
 * arm_matrix_instance_q15 S = {nRows, nColumns, pData};
 * 
* where nRows specifies the number of rows, nColumns * specifies the number of columns, and pData points to the * data array. * * \par Size Checking * By default all of the matrix functions perform size checking on the input and * output matrices. For example, the matrix addition function verifies that the * two input matrices and the output matrix all have the same number of rows and * columns. If the size check fails the functions return: *
 *     ARM_MATH_SIZE_MISMATCH
 * 
* Otherwise the functions return *
 *     ARM_MATH_SUCCESS
 * 
* There is some overhead associated with this matrix size checking. * The matrix size checking is enabled via the \#define *
 *     ARM_MATH_MATRIX_CHECK
 * 
* within the library project settings. By default this macro is defined * and size checking is enabled. By changing the project settings and * undefining this macro size checking is eliminated and the functions * run a bit faster. With size checking disabled the functions always * return ARM_MATH_SUCCESS. */ /** * @defgroup groupTransforms Transform Functions */ /** * @defgroup groupController Controller Functions */ /** * @defgroup groupStats Statistics Functions */ /** * @defgroup groupSupport Support Functions */ /** * @defgroup groupInterpolation Interpolation Functions * These functions perform 1- and 2-dimensional interpolation of data. * Linear interpolation is used for 1-dimensional data and * bilinear interpolation is used for 2-dimensional data. */ /** * @defgroup groupExamples Examples */ #ifndef _ARM_MATH_H #define _ARM_MATH_H #define __CMSIS_GENERIC /* disable NVIC and Systick functions */ #if defined(ARM_MATH_CM7) #include "core_cm7.h" #elif defined (ARM_MATH_CM4) #include "core_cm4.h" #elif defined (ARM_MATH_CM3) #include "core_cm3.h" #elif defined (ARM_MATH_CM0) #include "core_cm0.h" #define ARM_MATH_CM0_FAMILY #elif defined (ARM_MATH_CM0PLUS) #include "core_cm0plus.h" #define ARM_MATH_CM0_FAMILY #else #error "Define according the used Cortex core ARM_MATH_CM7, ARM_MATH_CM4, ARM_MATH_CM3, ARM_MATH_CM0PLUS or ARM_MATH_CM0" #endif #undef __CMSIS_GENERIC /* enable NVIC and Systick functions */ #include "string.h" #include "math.h" #ifdef __cplusplus extern "C" { #endif /** * @brief Macros required for reciprocal calculation in Normalized LMS */ #define DELTA_Q31 (0x100) #define DELTA_Q15 0x5 #define INDEX_MASK 0x0000003F #ifndef PI #define PI 3.14159265358979f #endif /** * @brief Macros required for SINE and COSINE Fast math approximations */ #define FAST_MATH_TABLE_SIZE 512 #define FAST_MATH_Q31_SHIFT (32 - 10) #define FAST_MATH_Q15_SHIFT (16 - 10) #define CONTROLLER_Q31_SHIFT (32 - 9) #define TABLE_SIZE 256 #define TABLE_SPACING_Q31 0x400000 #define TABLE_SPACING_Q15 0x80 /** * @brief Macros required for SINE and COSINE Controller functions */ /* 1.31(q31) Fixed value of 2/360 */ /* -1 to +1 is divided into 360 values so total spacing is (2/360) */ #define INPUT_SPACING 0xB60B61 /** * @brief Macro for Unaligned Support */ #ifndef UNALIGNED_SUPPORT_DISABLE #define ALIGN4 #else #if defined (__GNUC__) #define ALIGN4 __attribute__((aligned(4))) #else #define ALIGN4 __align(4) #endif #endif /* #ifndef UNALIGNED_SUPPORT_DISABLE */ /** * @brief Error status returned by some functions in the library. */ typedef enum { ARM_MATH_SUCCESS = 0, /**< No error */ ARM_MATH_ARGUMENT_ERROR = -1, /**< One or more arguments are incorrect */ ARM_MATH_LENGTH_ERROR = -2, /**< Length of data buffer is incorrect */ ARM_MATH_SIZE_MISMATCH = -3, /**< Size of matrices is not compatible with the operation. */ ARM_MATH_NANINF = -4, /**< Not-a-number (NaN) or infinity is generated */ ARM_MATH_SINGULAR = -5, /**< Generated by matrix inversion if the input matrix is singular and cannot be inverted. */ ARM_MATH_TEST_FAILURE = -6 /**< Test Failed */ } arm_status; /** * @brief 8-bit fractional data type in 1.7 format. */ typedef int8_t q7_t; /** * @brief 16-bit fractional data type in 1.15 format. */ typedef int16_t q15_t; /** * @brief 32-bit fractional data type in 1.31 format. */ typedef int32_t q31_t; /** * @brief 64-bit fractional data type in 1.63 format. */ typedef int64_t q63_t; /** * @brief 32-bit floating-point type definition. */ typedef float float32_t; /** * @brief 64-bit floating-point type definition. */ typedef double float64_t; /** * @brief definition to read/write two 16 bit values. */ #if defined __CC_ARM #define __SIMD32_TYPE int32_t __packed #define CMSIS_UNUSED __attribute__((unused)) #elif defined __ICCARM__ #define __SIMD32_TYPE int32_t __packed #define CMSIS_UNUSED #elif defined __GNUC__ #define __SIMD32_TYPE int32_t #define CMSIS_UNUSED __attribute__((unused)) #elif defined __CSMC__ /* Cosmic */ #define __SIMD32_TYPE int32_t #define CMSIS_UNUSED #elif defined __TASKING__ #define __SIMD32_TYPE __unaligned int32_t #define CMSIS_UNUSED #else #error Unknown compiler #endif #define __SIMD32(addr) (*(__SIMD32_TYPE **) & (addr)) #define __SIMD32_CONST(addr) ((__SIMD32_TYPE *)(addr)) #define _SIMD32_OFFSET(addr) (*(__SIMD32_TYPE *) (addr)) #define __SIMD64(addr) (*(int64_t **) & (addr)) #if defined (ARM_MATH_CM3) || defined (ARM_MATH_CM0_FAMILY) /** * @brief definition to pack two 16 bit values. */ #define __PKHBT(ARG1, ARG2, ARG3) ( (((int32_t)(ARG1) << 0) & (int32_t)0x0000FFFF) | \ (((int32_t)(ARG2) << ARG3) & (int32_t)0xFFFF0000) ) #define __PKHTB(ARG1, ARG2, ARG3) ( (((int32_t)(ARG1) << 0) & (int32_t)0xFFFF0000) | \ (((int32_t)(ARG2) >> ARG3) & (int32_t)0x0000FFFF) ) #endif /** * @brief definition to pack four 8 bit values. */ #ifndef ARM_MATH_BIG_ENDIAN #define __PACKq7(v0,v1,v2,v3) ( (((int32_t)(v0) << 0) & (int32_t)0x000000FF) | \ (((int32_t)(v1) << 8) & (int32_t)0x0000FF00) | \ (((int32_t)(v2) << 16) & (int32_t)0x00FF0000) | \ (((int32_t)(v3) << 24) & (int32_t)0xFF000000) ) #else #define __PACKq7(v0,v1,v2,v3) ( (((int32_t)(v3) << 0) & (int32_t)0x000000FF) | \ (((int32_t)(v2) << 8) & (int32_t)0x0000FF00) | \ (((int32_t)(v1) << 16) & (int32_t)0x00FF0000) | \ (((int32_t)(v0) << 24) & (int32_t)0xFF000000) ) #endif /** * @brief Clips Q63 to Q31 values. */ static __INLINE q31_t clip_q63_to_q31( q63_t x) { return ((q31_t) (x >> 32) != ((q31_t) x >> 31)) ? ((0x7FFFFFFF ^ ((q31_t) (x >> 63)))) : (q31_t) x; } /** * @brief Clips Q63 to Q15 values. */ static __INLINE q15_t clip_q63_to_q15( q63_t x) { return ((q31_t) (x >> 32) != ((q31_t) x >> 31)) ? ((0x7FFF ^ ((q15_t) (x >> 63)))) : (q15_t) (x >> 15); } /** * @brief Clips Q31 to Q7 values. */ static __INLINE q7_t clip_q31_to_q7( q31_t x) { return ((q31_t) (x >> 24) != ((q31_t) x >> 23)) ? ((0x7F ^ ((q7_t) (x >> 31)))) : (q7_t) x; } /** * @brief Clips Q31 to Q15 values. */ static __INLINE q15_t clip_q31_to_q15( q31_t x) { return ((q31_t) (x >> 16) != ((q31_t) x >> 15)) ? ((0x7FFF ^ ((q15_t) (x >> 31)))) : (q15_t) x; } /** * @brief Multiplies 32 X 64 and returns 32 bit result in 2.30 format. */ static __INLINE q63_t mult32x64( q63_t x, q31_t y) { return ((((q63_t) (x & 0x00000000FFFFFFFF) * y) >> 32) + (((q63_t) (x >> 32) * y))); } //#if defined (ARM_MATH_CM0_FAMILY) && defined ( __CC_ARM ) //#define __CLZ __clz //#endif //note: function can be removed when all toolchain support __CLZ for Cortex-M0 #if defined (ARM_MATH_CM0_FAMILY) && ((defined (__ICCARM__)) ) static __INLINE uint32_t __CLZ( q31_t data); static __INLINE uint32_t __CLZ( q31_t data) { uint32_t count = 0; uint32_t mask = 0x80000000; while((data & mask) == 0) { count += 1u; mask = mask >> 1u; } return (count); } #endif /** * @brief Function to Calculates 1/in (reciprocal) value of Q31 Data type. */ static __INLINE uint32_t arm_recip_q31( q31_t in, q31_t * dst, q31_t * pRecipTable) { uint32_t out, tempVal; uint32_t index, i; uint32_t signBits; if(in > 0) { signBits = __CLZ(in) - 1; } else { signBits = __CLZ(-in) - 1; } /* Convert input sample to 1.31 format */ in = in << signBits; /* calculation of index for initial approximated Val */ index = (uint32_t) (in >> 24u); index = (index & INDEX_MASK); /* 1.31 with exp 1 */ out = pRecipTable[index]; /* calculation of reciprocal value */ /* running approximation for two iterations */ for (i = 0u; i < 2u; i++) { tempVal = (q31_t) (((q63_t) in * out) >> 31u); tempVal = 0x7FFFFFFF - tempVal; /* 1.31 with exp 1 */ //out = (q31_t) (((q63_t) out * tempVal) >> 30u); out = (q31_t) clip_q63_to_q31(((q63_t) out * tempVal) >> 30u); } /* write output */ *dst = out; /* return num of signbits of out = 1/in value */ return (signBits + 1u); } /** * @brief Function to Calculates 1/in (reciprocal) value of Q15 Data type. */ static __INLINE uint32_t arm_recip_q15( q15_t in, q15_t * dst, q15_t * pRecipTable) { uint32_t out = 0, tempVal = 0; uint32_t index = 0, i = 0; uint32_t signBits = 0; if(in > 0) { signBits = __CLZ(in) - 17; } else { signBits = __CLZ(-in) - 17; } /* Convert input sample to 1.15 format */ in = in << signBits; /* calculation of index for initial approximated Val */ index = in >> 8; index = (index & INDEX_MASK); /* 1.15 with exp 1 */ out = pRecipTable[index]; /* calculation of reciprocal value */ /* running approximation for two iterations */ for (i = 0; i < 2; i++) { tempVal = (q15_t) (((q31_t) in * out) >> 15); tempVal = 0x7FFF - tempVal; /* 1.15 with exp 1 */ out = (q15_t) (((q31_t) out * tempVal) >> 14); } /* write output */ *dst = out; /* return num of signbits of out = 1/in value */ return (signBits + 1); } /* * @brief C custom defined intrinisic function for only M0 processors */ #if defined(ARM_MATH_CM0_FAMILY) static __INLINE q31_t __SSAT( q31_t x, uint32_t y) { int32_t posMax, negMin; uint32_t i; posMax = 1; for (i = 0; i < (y - 1); i++) { posMax = posMax * 2; } if(x > 0) { posMax = (posMax - 1); if(x > posMax) { x = posMax; } } else { negMin = -posMax; if(x < negMin) { x = negMin; } } return (x); } #endif /* end of ARM_MATH_CM0_FAMILY */ /* * @brief C custom defined intrinsic function for M3 and M0 processors */ #if defined (ARM_MATH_CM3) || defined (ARM_MATH_CM0_FAMILY) /* * @brief C custom defined QADD8 for M3 and M0 processors */ static __INLINE q31_t __QADD8( q31_t x, q31_t y) { q31_t sum; q7_t r, s, t, u; r = (q7_t) x; s = (q7_t) y; r = __SSAT((q31_t) (r + s), 8); s = __SSAT(((q31_t) (((x << 16) >> 24) + ((y << 16) >> 24))), 8); t = __SSAT(((q31_t) (((x << 8) >> 24) + ((y << 8) >> 24))), 8); u = __SSAT(((q31_t) ((x >> 24) + (y >> 24))), 8); sum = (((q31_t) u << 24) & 0xFF000000) | (((q31_t) t << 16) & 0x00FF0000) | (((q31_t) s << 8) & 0x0000FF00) | (r & 0x000000FF); return sum; } /* * @brief C custom defined QSUB8 for M3 and M0 processors */ static __INLINE q31_t __QSUB8( q31_t x, q31_t y) { q31_t sum; q31_t r, s, t, u; r = (q7_t) x; s = (q7_t) y; r = __SSAT((r - s), 8); s = __SSAT(((q31_t) (((x << 16) >> 24) - ((y << 16) >> 24))), 8) << 8; t = __SSAT(((q31_t) (((x << 8) >> 24) - ((y << 8) >> 24))), 8) << 16; u = __SSAT(((q31_t) ((x >> 24) - (y >> 24))), 8) << 24; sum = (u & 0xFF000000) | (t & 0x00FF0000) | (s & 0x0000FF00) | (r & 0x000000FF); return sum; } /* * @brief C custom defined QADD16 for M3 and M0 processors */ /* * @brief C custom defined QADD16 for M3 and M0 processors */ static __INLINE q31_t __QADD16( q31_t x, q31_t y) { q31_t sum; q31_t r, s; r = (q15_t) x; s = (q15_t) y; r = __SSAT(r + s, 16); s = __SSAT(((q31_t) ((x >> 16) + (y >> 16))), 16) << 16; sum = (s & 0xFFFF0000) | (r & 0x0000FFFF); return sum; } /* * @brief C custom defined SHADD16 for M3 and M0 processors */ static __INLINE q31_t __SHADD16( q31_t x, q31_t y) { q31_t sum; q31_t r, s; r = (q15_t) x; s = (q15_t) y; r = ((r >> 1) + (s >> 1)); s = ((q31_t) ((x >> 17) + (y >> 17))) << 16; sum = (s & 0xFFFF0000) | (r & 0x0000FFFF); return sum; } /* * @brief C custom defined QSUB16 for M3 and M0 processors */ static __INLINE q31_t __QSUB16( q31_t x, q31_t y) { q31_t sum; q31_t r, s; r = (q15_t) x; s = (q15_t) y; r = __SSAT(r - s, 16); s = __SSAT(((q31_t) ((x >> 16) - (y >> 16))), 16) << 16; sum = (s & 0xFFFF0000) | (r & 0x0000FFFF); return sum; } /* * @brief C custom defined SHSUB16 for M3 and M0 processors */ static __INLINE q31_t __SHSUB16( q31_t x, q31_t y) { q31_t diff; q31_t r, s; r = (q15_t) x; s = (q15_t) y; r = ((r >> 1) - (s >> 1)); s = (((x >> 17) - (y >> 17)) << 16); diff = (s & 0xFFFF0000) | (r & 0x0000FFFF); return diff; } /* * @brief C custom defined QASX for M3 and M0 processors */ static __INLINE q31_t __QASX( q31_t x, q31_t y) { q31_t sum = 0; sum = ((sum + clip_q31_to_q15((q31_t) ((q15_t) (x >> 16) + (q15_t) y))) << 16) + clip_q31_to_q15((q31_t) ((q15_t) x - (q15_t) (y >> 16))); return sum; } /* * @brief C custom defined SHASX for M3 and M0 processors */ static __INLINE q31_t __SHASX( q31_t x, q31_t y) { q31_t sum; q31_t r, s; r = (q15_t) x; s = (q15_t) y; r = ((r >> 1) - (y >> 17)); s = (((x >> 17) + (s >> 1)) << 16); sum = (s & 0xFFFF0000) | (r & 0x0000FFFF); return sum; } /* * @brief C custom defined QSAX for M3 and M0 processors */ static __INLINE q31_t __QSAX( q31_t x, q31_t y) { q31_t sum = 0; sum = ((sum + clip_q31_to_q15((q31_t) ((q15_t) (x >> 16) - (q15_t) y))) << 16) + clip_q31_to_q15((q31_t) ((q15_t) x + (q15_t) (y >> 16))); return sum; } /* * @brief C custom defined SHSAX for M3 and M0 processors */ static __INLINE q31_t __SHSAX( q31_t x, q31_t y) { q31_t sum; q31_t r, s; r = (q15_t) x; s = (q15_t) y; r = ((r >> 1) + (y >> 17)); s = (((x >> 17) - (s >> 1)) << 16); sum = (s & 0xFFFF0000) | (r & 0x0000FFFF); return sum; } /* * @brief C custom defined SMUSDX for M3 and M0 processors */ static __INLINE q31_t __SMUSDX( q31_t x, q31_t y) { return ((q31_t) (((q15_t) x * (q15_t) (y >> 16)) - ((q15_t) (x >> 16) * (q15_t) y))); } /* * @brief C custom defined SMUADX for M3 and M0 processors */ static __INLINE q31_t __SMUADX( q31_t x, q31_t y) { return ((q31_t) (((q15_t) x * (q15_t) (y >> 16)) + ((q15_t) (x >> 16) * (q15_t) y))); } /* * @brief C custom defined QADD for M3 and M0 processors */ static __INLINE q31_t __QADD( q31_t x, q31_t y) { return clip_q63_to_q31((q63_t) x + y); } /* * @brief C custom defined QSUB for M3 and M0 processors */ static __INLINE q31_t __QSUB( q31_t x, q31_t y) { return clip_q63_to_q31((q63_t) x - y); } /* * @brief C custom defined SMLAD for M3 and M0 processors */ static __INLINE q31_t __SMLAD( q31_t x, q31_t y, q31_t sum) { return (sum + ((q15_t) (x >> 16) * (q15_t) (y >> 16)) + ((q15_t) x * (q15_t) y)); } /* * @brief C custom defined SMLADX for M3 and M0 processors */ static __INLINE q31_t __SMLADX( q31_t x, q31_t y, q31_t sum) { return (sum + ((q15_t) (x >> 16) * (q15_t) (y)) + ((q15_t) x * (q15_t) (y >> 16))); } /* * @brief C custom defined SMLSDX for M3 and M0 processors */ static __INLINE q31_t __SMLSDX( q31_t x, q31_t y, q31_t sum) { return (sum - ((q15_t) (x >> 16) * (q15_t) (y)) + ((q15_t) x * (q15_t) (y >> 16))); } /* * @brief C custom defined SMLALD for M3 and M0 processors */ static __INLINE q63_t __SMLALD( q31_t x, q31_t y, q63_t sum) { return (sum + ((q15_t) (x >> 16) * (q15_t) (y >> 16)) + ((q15_t) x * (q15_t) y)); } /* * @brief C custom defined SMLALDX for M3 and M0 processors */ static __INLINE q63_t __SMLALDX( q31_t x, q31_t y, q63_t sum) { return (sum + ((q15_t) (x >> 16) * (q15_t) y)) + ((q15_t) x * (q15_t) (y >> 16)); } /* * @brief C custom defined SMUAD for M3 and M0 processors */ static __INLINE q31_t __SMUAD( q31_t x, q31_t y) { return (((x >> 16) * (y >> 16)) + (((x << 16) >> 16) * ((y << 16) >> 16))); } /* * @brief C custom defined SMUSD for M3 and M0 processors */ static __INLINE q31_t __SMUSD( q31_t x, q31_t y) { return (-((x >> 16) * (y >> 16)) + (((x << 16) >> 16) * ((y << 16) >> 16))); } /* * @brief C custom defined SXTB16 for M3 and M0 processors */ static __INLINE q31_t __SXTB16( q31_t x) { return ((((x << 24) >> 24) & 0x0000FFFF) | (((x << 8) >> 8) & 0xFFFF0000)); } #endif /* defined (ARM_MATH_CM3) || defined (ARM_MATH_CM0_FAMILY) */ /** * @brief Instance structure for the Q7 FIR filter. */ typedef struct { uint16_t numTaps; /**< number of filter coefficients in the filter. */ q7_t *pState; /**< points to the state variable array. The array is of length numTaps+blockSize-1. */ q7_t *pCoeffs; /**< points to the coefficient array. The array is of length numTaps.*/ } arm_fir_instance_q7; /** * @brief Instance structure for the Q15 FIR filter. */ typedef struct { uint16_t numTaps; /**< number of filter coefficients in the filter. */ q15_t *pState; /**< points to the state variable array. The array is of length numTaps+blockSize-1. */ q15_t *pCoeffs; /**< points to the coefficient array. The array is of length numTaps.*/ } arm_fir_instance_q15; /** * @brief Instance structure for the Q31 FIR filter. */ typedef struct { uint16_t numTaps; /**< number of filter coefficients in the filter. */ q31_t *pState; /**< points to the state variable array. The array is of length numTaps+blockSize-1. */ q31_t *pCoeffs; /**< points to the coefficient array. The array is of length numTaps. */ } arm_fir_instance_q31; /** * @brief Instance structure for the floating-point FIR filter. */ typedef struct { uint16_t numTaps; /**< number of filter coefficients in the filter. */ float32_t *pState; /**< points to the state variable array. The array is of length numTaps+blockSize-1. */ float32_t *pCoeffs; /**< points to the coefficient array. The array is of length numTaps. */ } arm_fir_instance_f32; /** * @brief Processing function for the Q7 FIR filter. * @param[in] *S points to an instance of the Q7 FIR filter structure. * @param[in] *pSrc points to the block of input data. * @param[out] *pDst points to the block of output data. * @param[in] blockSize number of samples to process. * @return none. */ void arm_fir_q7( const arm_fir_instance_q7 * S, q7_t * pSrc, q7_t * pDst, uint32_t blockSize); /** * @brief Initialization function for the Q7 FIR filter. * @param[in,out] *S points to an instance of the Q7 FIR structure. * @param[in] numTaps Number of filter coefficients in the filter. * @param[in] *pCoeffs points to the filter coefficients. * @param[in] *pState points to the state buffer. * @param[in] blockSize number of samples that are processed. * @return none */ void arm_fir_init_q7( arm_fir_instance_q7 * S, uint16_t numTaps, q7_t * pCoeffs, q7_t * pState, uint32_t blockSize); /** * @brief Processing function for the Q15 FIR filter. * @param[in] *S points to an instance of the Q15 FIR structure. * @param[in] *pSrc points to the block of input data. * @param[out] *pDst points to the block of output data. * @param[in] blockSize number of samples to process. * @return none. */ void arm_fir_q15( const arm_fir_instance_q15 * S, q15_t * pSrc, q15_t * pDst, uint32_t blockSize); /** * @brief Processing function for the fast Q15 FIR filter for Cortex-M3 and Cortex-M4. * @param[in] *S points to an instance of the Q15 FIR filter structure. * @param[in] *pSrc points to the block of input data. * @param[out] *pDst points to the block of output data. * @param[in] blockSize number of samples to process. * @return none. */ void arm_fir_fast_q15( const arm_fir_instance_q15 * S, q15_t * pSrc, q15_t * pDst, uint32_t blockSize); /** * @brief Initialization function for the Q15 FIR filter. * @param[in,out] *S points to an instance of the Q15 FIR filter structure. * @param[in] numTaps Number of filter coefficients in the filter. Must be even and greater than or equal to 4. * @param[in] *pCoeffs points to the filter coefficients. * @param[in] *pState points to the state buffer. * @param[in] blockSize number of samples that are processed at a time. * @return The function returns ARM_MATH_SUCCESS if initialization was successful or ARM_MATH_ARGUMENT_ERROR if * numTaps is not a supported value. */ arm_status arm_fir_init_q15( arm_fir_instance_q15 * S, uint16_t numTaps, q15_t * pCoeffs, q15_t * pState, uint32_t blockSize); /** * @brief Processing function for the Q31 FIR filter. * @param[in] *S points to an instance of the Q31 FIR filter structure. * @param[in] *pSrc points to the block of input data. * @param[out] *pDst points to the block of output data. * @param[in] blockSize number of samples to process. * @return none. */ void arm_fir_q31( const arm_fir_instance_q31 * S, q31_t * pSrc, q31_t * pDst, uint32_t blockSize); /** * @brief Processing function for the fast Q31 FIR filter for Cortex-M3 and Cortex-M4. * @param[in] *S points to an instance of the Q31 FIR structure. * @param[in] *pSrc points to the block of input data. * @param[out] *pDst points to the block of output data. * @param[in] blockSize number of samples to process. * @return none. */ void arm_fir_fast_q31( const arm_fir_instance_q31 * S, q31_t * pSrc, q31_t * pDst, uint32_t blockSize); /** * @brief Initialization function for the Q31 FIR filter. * @param[in,out] *S points to an instance of the Q31 FIR structure. * @param[in] numTaps Number of filter coefficients in the filter. * @param[in] *pCoeffs points to the filter coefficients. * @param[in] *pState points to the state buffer. * @param[in] blockSize number of samples that are processed at a time. * @return none. */ void arm_fir_init_q31( arm_fir_instance_q31 * S, uint16_t numTaps, q31_t * pCoeffs, q31_t * pState, uint32_t blockSize); /** * @brief Processing function for the floating-point FIR filter. * @param[in] *S points to an instance of the floating-point FIR structure. * @param[in] *pSrc points to the block of input data. * @param[out] *pDst points to the block of output data. * @param[in] blockSize number of samples to process. * @return none. */ void arm_fir_f32( const arm_fir_instance_f32 * S, float32_t * pSrc, float32_t * pDst, uint32_t blockSize); /** * @brief Initialization function for the floating-point FIR filter. * @param[in,out] *S points to an instance of the floating-point FIR filter structure. * @param[in] numTaps Number of filter coefficients in the filter. * @param[in] *pCoeffs points to the filter coefficients. * @param[in] *pState points to the state buffer. * @param[in] blockSize number of samples that are processed at a time. * @return none. */ void arm_fir_init_f32( arm_fir_instance_f32 * S, uint16_t numTaps, float32_t * pCoeffs, float32_t * pState, uint32_t blockSize); /** * @brief Instance structure for the Q15 Biquad cascade filter. */ typedef struct { int8_t numStages; /**< number of 2nd order stages in the filter. Overall order is 2*numStages. */ q15_t *pState; /**< Points to the array of state coefficients. The array is of length 4*numStages. */ q15_t *pCoeffs; /**< Points to the array of coefficients. The array is of length 5*numStages. */ int8_t postShift; /**< Additional shift, in bits, applied to each output sample. */ } arm_biquad_casd_df1_inst_q15; /** * @brief Instance structure for the Q31 Biquad cascade filter. */ typedef struct { uint32_t numStages; /**< number of 2nd order stages in the filter. Overall order is 2*numStages. */ q31_t *pState; /**< Points to the array of state coefficients. The array is of length 4*numStages. */ q31_t *pCoeffs; /**< Points to the array of coefficients. The array is of length 5*numStages. */ uint8_t postShift; /**< Additional shift, in bits, applied to each output sample. */ } arm_biquad_casd_df1_inst_q31; /** * @brief Instance structure for the floating-point Biquad cascade filter. */ typedef struct { uint32_t numStages; /**< number of 2nd order stages in the filter. Overall order is 2*numStages. */ float32_t *pState; /**< Points to the array of state coefficients. The array is of length 4*numStages. */ float32_t *pCoeffs; /**< Points to the array of coefficients. The array is of length 5*numStages. */ } arm_biquad_casd_df1_inst_f32; /** * @brief Processing function for the Q15 Biquad cascade filter. * @param[in] *S points to an instance of the Q15 Biquad cascade structure. * @param[in] *pSrc points to the block of input data. * @param[out] *pDst points to the block of output data. * @param[in] blockSize number of samples to process. * @return none. */ void arm_biquad_cascade_df1_q15( const arm_biquad_casd_df1_inst_q15 * S, q15_t * pSrc, q15_t * pDst, uint32_t blockSize); /** * @brief Initialization function for the Q15 Biquad cascade filter. * @param[in,out] *S points to an instance of the Q15 Biquad cascade structure. * @param[in] numStages number of 2nd order stages in the filter. * @param[in] *pCoeffs points to the filter coefficients. * @param[in] *pState points to the state buffer. * @param[in] postShift Shift to be applied to the output. Varies according to the coefficients format * @return none */ void arm_biquad_cascade_df1_init_q15( arm_biquad_casd_df1_inst_q15 * S, uint8_t numStages, q15_t * pCoeffs, q15_t * pState, int8_t postShift); /** * @brief Fast but less precise processing function for the Q15 Biquad cascade filter for Cortex-M3 and Cortex-M4. * @param[in] *S points to an instance of the Q15 Biquad cascade structure. * @param[in] *pSrc points to the block of input data. * @param[out] *pDst points to the block of output data. * @param[in] blockSize number of samples to process. * @return none. */ void arm_biquad_cascade_df1_fast_q15( const arm_biquad_casd_df1_inst_q15 * S, q15_t * pSrc, q15_t * pDst, uint32_t blockSize); /** * @brief Processing function for the Q31 Biquad cascade filter * @param[in] *S points to an instance of the Q31 Biquad cascade structure. * @param[in] *pSrc points to the block of input data. * @param[out] *pDst points to the block of output data. * @param[in] blockSize number of samples to process. * @return none. */ void arm_biquad_cascade_df1_q31( const arm_biquad_casd_df1_inst_q31 * S, q31_t * pSrc, q31_t * pDst, uint32_t blockSize); /** * @brief Fast but less precise processing function for the Q31 Biquad cascade filter for Cortex-M3 and Cortex-M4. * @param[in] *S points to an instance of the Q31 Biquad cascade structure. * @param[in] *pSrc points to the block of input data. * @param[out] *pDst points to the block of output data. * @param[in] blockSize number of samples to process. * @return none. */ void arm_biquad_cascade_df1_fast_q31( const arm_biquad_casd_df1_inst_q31 * S, q31_t * pSrc, q31_t * pDst, uint32_t blockSize); /** * @brief Initialization function for the Q31 Biquad cascade filter. * @param[in,out] *S points to an instance of the Q31 Biquad cascade structure. * @param[in] numStages number of 2nd order stages in the filter. * @param[in] *pCoeffs points to the filter coefficients. * @param[in] *pState points to the state buffer. * @param[in] postShift Shift to be applied to the output. Varies according to the coefficients format * @return none */ void arm_biquad_cascade_df1_init_q31( arm_biquad_casd_df1_inst_q31 * S, uint8_t numStages, q31_t * pCoeffs, q31_t * pState, int8_t postShift); /** * @brief Processing function for the floating-point Biquad cascade filter. * @param[in] *S points to an instance of the floating-point Biquad cascade structure. * @param[in] *pSrc points to the block of input data. * @param[out] *pDst points to the block of output data. * @param[in] blockSize number of samples to process. * @return none. */ void arm_biquad_cascade_df1_f32( const arm_biquad_casd_df1_inst_f32 * S, float32_t * pSrc, float32_t * pDst, uint32_t blockSize); /** * @brief Initialization function for the floating-point Biquad cascade filter. * @param[in,out] *S points to an instance of the floating-point Biquad cascade structure. * @param[in] numStages number of 2nd order stages in the filter. * @param[in] *pCoeffs points to the filter coefficients. * @param[in] *pState points to the state buffer. * @return none */ void arm_biquad_cascade_df1_init_f32( arm_biquad_casd_df1_inst_f32 * S, uint8_t numStages, float32_t * pCoeffs, float32_t * pState); /** * @brief Instance structure for the floating-point matrix structure. */ typedef struct { uint16_t numRows; /**< number of rows of the matrix. */ uint16_t numCols; /**< number of columns of the matrix. */ float32_t *pData; /**< points to the data of the matrix. */ } arm_matrix_instance_f32; /** * @brief Instance structure for the floating-point matrix structure. */ typedef struct { uint16_t numRows; /**< number of rows of the matrix. */ uint16_t numCols; /**< number of columns of the matrix. */ float64_t *pData; /**< points to the data of the matrix. */ } arm_matrix_instance_f64; /** * @brief Instance structure for the Q15 matrix structure. */ typedef struct { uint16_t numRows; /**< number of rows of the matrix. */ uint16_t numCols; /**< number of columns of the matrix. */ q15_t *pData; /**< points to the data of the matrix. */ } arm_matrix_instance_q15; /** * @brief Instance structure for the Q31 matrix structure. */ typedef struct { uint16_t numRows; /**< number of rows of the matrix. */ uint16_t numCols; /**< number of columns of the matrix. */ q31_t *pData; /**< points to the data of the matrix. */ } arm_matrix_instance_q31; /** * @brief Floating-point matrix addition. * @param[in] *pSrcA points to the first input matrix structure * @param[in] *pSrcB points to the second input matrix structure * @param[out] *pDst points to output matrix structure * @return The function returns either * ARM_MATH_SIZE_MISMATCH or ARM_MATH_SUCCESS based on the outcome of size checking. */ arm_status arm_mat_add_f32( const arm_matrix_instance_f32 * pSrcA, const arm_matrix_instance_f32 * pSrcB, arm_matrix_instance_f32 * pDst); /** * @brief Q15 matrix addition. * @param[in] *pSrcA points to the first input matrix structure * @param[in] *pSrcB points to the second input matrix structure * @param[out] *pDst points to output matrix structure * @return The function returns either * ARM_MATH_SIZE_MISMATCH or ARM_MATH_SUCCESS based on the outcome of size checking. */ arm_status arm_mat_add_q15( const arm_matrix_instance_q15 * pSrcA, const arm_matrix_instance_q15 * pSrcB, arm_matrix_instance_q15 * pDst); /** * @brief Q31 matrix addition. * @param[in] *pSrcA points to the first input matrix structure * @param[in] *pSrcB points to the second input matrix structure * @param[out] *pDst points to output matrix structure * @return The function returns either * ARM_MATH_SIZE_MISMATCH or ARM_MATH_SUCCESS based on the outcome of size checking. */ arm_status arm_mat_add_q31( const arm_matrix_instance_q31 * pSrcA, const arm_matrix_instance_q31 * pSrcB, arm_matrix_instance_q31 * pDst); /** * @brief Floating-point, complex, matrix multiplication. * @param[in] *pSrcA points to the first input matrix structure * @param[in] *pSrcB points to the second input matrix structure * @param[out] *pDst points to output matrix structure * @return The function returns either * ARM_MATH_SIZE_MISMATCH or ARM_MATH_SUCCESS based on the outcome of size checking. */ arm_status arm_mat_cmplx_mult_f32( const arm_matrix_instance_f32 * pSrcA, const arm_matrix_instance_f32 * pSrcB, arm_matrix_instance_f32 * pDst); /** * @brief Q15, complex, matrix multiplication. * @param[in] *pSrcA points to the first input matrix structure * @param[in] *pSrcB points to the second input matrix structure * @param[out] *pDst points to output matrix structure * @return The function returns either * ARM_MATH_SIZE_MISMATCH or ARM_MATH_SUCCESS based on the outcome of size checking. */ arm_status arm_mat_cmplx_mult_q15( const arm_matrix_instance_q15 * pSrcA, const arm_matrix_instance_q15 * pSrcB, arm_matrix_instance_q15 * pDst, q15_t * pScratch); /** * @brief Q31, complex, matrix multiplication. * @param[in] *pSrcA points to the first input matrix structure * @param[in] *pSrcB points to the second input matrix structure * @param[out] *pDst points to output matrix structure * @return The function returns either * ARM_MATH_SIZE_MISMATCH or ARM_MATH_SUCCESS based on the outcome of size checking. */ arm_status arm_mat_cmplx_mult_q31( const arm_matrix_instance_q31 * pSrcA, const arm_matrix_instance_q31 * pSrcB, arm_matrix_instance_q31 * pDst); /** * @brief Floating-point matrix transpose. * @param[in] *pSrc points to the input matrix * @param[out] *pDst points to the output matrix * @return The function returns either ARM_MATH_SIZE_MISMATCH * or ARM_MATH_SUCCESS based on the outcome of size checking. */ arm_status arm_mat_trans_f32( const arm_matrix_instance_f32 * pSrc, arm_matrix_instance_f32 * pDst); /** * @brief Q15 matrix transpose. * @param[in] *pSrc points to the input matrix * @param[out] *pDst points to the output matrix * @return The function returns either ARM_MATH_SIZE_MISMATCH * or ARM_MATH_SUCCESS based on the outcome of size checking. */ arm_status arm_mat_trans_q15( const arm_matrix_instance_q15 * pSrc, arm_matrix_instance_q15 * pDst); /** * @brief Q31 matrix transpose. * @param[in] *pSrc points to the input matrix * @param[out] *pDst points to the output matrix * @return The function returns either ARM_MATH_SIZE_MISMATCH * or ARM_MATH_SUCCESS based on the outcome of size checking. */ arm_status arm_mat_trans_q31( const arm_matrix_instance_q31 * pSrc, arm_matrix_instance_q31 * pDst); /** * @brief Floating-point matrix multiplication * @param[in] *pSrcA points to the first input matrix structure * @param[in] *pSrcB points to the second input matrix structure * @param[out] *pDst points to output matrix structure * @return The function returns either * ARM_MATH_SIZE_MISMATCH or ARM_MATH_SUCCESS based on the outcome of size checking. */ arm_status arm_mat_mult_f32( const arm_matrix_instance_f32 * pSrcA, const arm_matrix_instance_f32 * pSrcB, arm_matrix_instance_f32 * pDst); /** * @brief Q15 matrix multiplication * @param[in] *pSrcA points to the first input matrix structure * @param[in] *pSrcB points to the second input matrix structure * @param[out] *pDst points to output matrix structure * @param[in] *pState points to the array for storing intermediate results * @return The function returns either * ARM_MATH_SIZE_MISMATCH or ARM_MATH_SUCCESS based on the outcome of size checking. */ arm_status arm_mat_mult_q15( const arm_matrix_instance_q15 * pSrcA, const arm_matrix_instance_q15 * pSrcB, arm_matrix_instance_q15 * pDst, q15_t * pState); /** * @brief Q15 matrix multiplication (fast variant) for Cortex-M3 and Cortex-M4 * @param[in] *pSrcA points to the first input matrix structure * @param[in] *pSrcB points to the second input matrix structure * @param[out] *pDst points to output matrix structure * @param[in] *pState points to the array for storing intermediate results * @return The function returns either * ARM_MATH_SIZE_MISMATCH or ARM_MATH_SUCCESS based on the outcome of size checking. */ arm_status arm_mat_mult_fast_q15( const arm_matrix_instance_q15 * pSrcA, const arm_matrix_instance_q15 * pSrcB, arm_matrix_instance_q15 * pDst, q15_t * pState); /** * @brief Q31 matrix multiplication * @param[in] *pSrcA points to the first input matrix structure * @param[in] *pSrcB points to the second input matrix structure * @param[out] *pDst points to output matrix structure * @return The function returns either * ARM_MATH_SIZE_MISMATCH or ARM_MATH_SUCCESS based on the outcome of size checking. */ arm_status arm_mat_mult_q31( const arm_matrix_instance_q31 * pSrcA, const arm_matrix_instance_q31 * pSrcB, arm_matrix_instance_q31 * pDst); /** * @brief Q31 matrix multiplication (fast variant) for Cortex-M3 and Cortex-M4 * @param[in] *pSrcA points to the first input matrix structure * @param[in] *pSrcB points to the second input matrix structure * @param[out] *pDst points to output matrix structure * @return The function returns either * ARM_MATH_SIZE_MISMATCH or ARM_MATH_SUCCESS based on the outcome of size checking. */ arm_status arm_mat_mult_fast_q31( const arm_matrix_instance_q31 * pSrcA, const arm_matrix_instance_q31 * pSrcB, arm_matrix_instance_q31 * pDst); /** * @brief Floating-point matrix subtraction * @param[in] *pSrcA points to the first input matrix structure * @param[in] *pSrcB points to the second input matrix structure * @param[out] *pDst points to output matrix structure * @return The function returns either * ARM_MATH_SIZE_MISMATCH or ARM_MATH_SUCCESS based on the outcome of size checking. */ arm_status arm_mat_sub_f32( const arm_matrix_instance_f32 * pSrcA, const arm_matrix_instance_f32 * pSrcB, arm_matrix_instance_f32 * pDst); /** * @brief Q15 matrix subtraction * @param[in] *pSrcA points to the first input matrix structure * @param[in] *pSrcB points to the second input matrix structure * @param[out] *pDst points to output matrix structure * @return The function returns either * ARM_MATH_SIZE_MISMATCH or ARM_MATH_SUCCESS based on the outcome of size checking. */ arm_status arm_mat_sub_q15( const arm_matrix_instance_q15 * pSrcA, const arm_matrix_instance_q15 * pSrcB, arm_matrix_instance_q15 * pDst); /** * @brief Q31 matrix subtraction * @param[in] *pSrcA points to the first input matrix structure * @param[in] *pSrcB points to the second input matrix structure * @param[out] *pDst points to output matrix structure * @return The function returns either * ARM_MATH_SIZE_MISMATCH or ARM_MATH_SUCCESS based on the outcome of size checking. */ arm_status arm_mat_sub_q31( const arm_matrix_instance_q31 * pSrcA, const arm_matrix_instance_q31 * pSrcB, arm_matrix_instance_q31 * pDst); /** * @brief Floating-point matrix scaling. * @param[in] *pSrc points to the input matrix * @param[in] scale scale factor * @param[out] *pDst points to the output matrix * @return The function returns either * ARM_MATH_SIZE_MISMATCH or ARM_MATH_SUCCESS based on the outcome of size checking. */ arm_status arm_mat_scale_f32( const arm_matrix_instance_f32 * pSrc, float32_t scale, arm_matrix_instance_f32 * pDst); /** * @brief Q15 matrix scaling. * @param[in] *pSrc points to input matrix * @param[in] scaleFract fractional portion of the scale factor * @param[in] shift number of bits to shift the result by * @param[out] *pDst points to output matrix * @return The function returns either * ARM_MATH_SIZE_MISMATCH or ARM_MATH_SUCCESS based on the outcome of size checking. */ arm_status arm_mat_scale_q15( const arm_matrix_instance_q15 * pSrc, q15_t scaleFract, int32_t shift, arm_matrix_instance_q15 * pDst); /** * @brief Q31 matrix scaling. * @param[in] *pSrc points to input matrix * @param[in] scaleFract fractional portion of the scale factor * @param[in] shift number of bits to shift the result by * @param[out] *pDst points to output matrix structure * @return The function returns either * ARM_MATH_SIZE_MISMATCH or ARM_MATH_SUCCESS based on the outcome of size checking. */ arm_status arm_mat_scale_q31( const arm_matrix_instance_q31 * pSrc, q31_t scaleFract, int32_t shift, arm_matrix_instance_q31 * pDst); /** * @brief Q31 matrix initialization. * @param[in,out] *S points to an instance of the floating-point matrix structure. * @param[in] nRows number of rows in the matrix. * @param[in] nColumns number of columns in the matrix. * @param[in] *pData points to the matrix data array. * @return none */ void arm_mat_init_q31( arm_matrix_instance_q31 * S, uint16_t nRows, uint16_t nColumns, q31_t * pData); /** * @brief Q15 matrix initialization. * @param[in,out] *S points to an instance of the floating-point matrix structure. * @param[in] nRows number of rows in the matrix. * @param[in] nColumns number of columns in the matrix. * @param[in] *pData points to the matrix data array. * @return none */ void arm_mat_init_q15( arm_matrix_instance_q15 * S, uint16_t nRows, uint16_t nColumns, q15_t * pData); /** * @brief Floating-point matrix initialization. * @param[in,out] *S points to an instance of the floating-point matrix structure. * @param[in] nRows number of rows in the matrix. * @param[in] nColumns number of columns in the matrix. * @param[in] *pData points to the matrix data array. * @return none */ void arm_mat_init_f32( arm_matrix_instance_f32 * S, uint16_t nRows, uint16_t nColumns, float32_t * pData); /** * @brief Instance structure for the Q15 PID Control. */ typedef struct { q15_t A0; /**< The derived gain, A0 = Kp + Ki + Kd . */ #ifdef ARM_MATH_CM0_FAMILY q15_t A1; q15_t A2; #else q31_t A1; /**< The derived gain A1 = -Kp - 2Kd | Kd.*/ #endif q15_t state[3]; /**< The state array of length 3. */ q15_t Kp; /**< The proportional gain. */ q15_t Ki; /**< The integral gain. */ q15_t Kd; /**< The derivative gain. */ } arm_pid_instance_q15; /** * @brief Instance structure for the Q31 PID Control. */ typedef struct { q31_t A0; /**< The derived gain, A0 = Kp + Ki + Kd . */ q31_t A1; /**< The derived gain, A1 = -Kp - 2Kd. */ q31_t A2; /**< The derived gain, A2 = Kd . */ q31_t state[3]; /**< The state array of length 3. */ q31_t Kp; /**< The proportional gain. */ q31_t Ki; /**< The integral gain. */ q31_t Kd; /**< The derivative gain. */ } arm_pid_instance_q31; /** * @brief Instance structure for the floating-point PID Control. */ typedef struct { float32_t A0; /**< The derived gain, A0 = Kp + Ki + Kd . */ float32_t A1; /**< The derived gain, A1 = -Kp - 2Kd. */ float32_t A2; /**< The derived gain, A2 = Kd . */ float32_t state[3]; /**< The state array of length 3. */ float32_t Kp; /**< The proportional gain. */ float32_t Ki; /**< The integral gain. */ float32_t Kd; /**< The derivative gain. */ } arm_pid_instance_f32; /** * @brief Initialization function for the floating-point PID Control. * @param[in,out] *S points to an instance of the PID structure. * @param[in] resetStateFlag flag to reset the state. 0 = no change in state 1 = reset the state. * @return none. */ void arm_pid_init_f32( arm_pid_instance_f32 * S, int32_t resetStateFlag); /** * @brief Reset function for the floating-point PID Control. * @param[in,out] *S is an instance of the floating-point PID Control structure * @return none */ void arm_pid_reset_f32( arm_pid_instance_f32 * S); /** * @brief Initialization function for the Q31 PID Control. * @param[in,out] *S points to an instance of the Q15 PID structure. * @param[in] resetStateFlag flag to reset the state. 0 = no change in state 1 = reset the state. * @return none. */ void arm_pid_init_q31( arm_pid_instance_q31 * S, int32_t resetStateFlag); /** * @brief Reset function for the Q31 PID Control. * @param[in,out] *S points to an instance of the Q31 PID Control structure * @return none */ void arm_pid_reset_q31( arm_pid_instance_q31 * S); /** * @brief Initialization function for the Q15 PID Control. * @param[in,out] *S points to an instance of the Q15 PID structure. * @param[in] resetStateFlag flag to reset the state. 0 = no change in state 1 = reset the state. * @return none. */ void arm_pid_init_q15( arm_pid_instance_q15 * S, int32_t resetStateFlag); /** * @brief Reset function for the Q15 PID Control. * @param[in,out] *S points to an instance of the q15 PID Control structure * @return none */ void arm_pid_reset_q15( arm_pid_instance_q15 * S); /** * @brief Instance structure for the floating-point Linear Interpolate function. */ typedef struct { uint32_t nValues; /**< nValues */ float32_t x1; /**< x1 */ float32_t xSpacing; /**< xSpacing */ float32_t *pYData; /**< pointer to the table of Y values */ } arm_linear_interp_instance_f32; /** * @brief Instance structure for the floating-point bilinear interpolation function. */ typedef struct { uint16_t numRows; /**< number of rows in the data table. */ uint16_t numCols; /**< number of columns in the data table. */ float32_t *pData; /**< points to the data table. */ } arm_bilinear_interp_instance_f32; /** * @brief Instance structure for the Q31 bilinear interpolation function. */ typedef struct { uint16_t numRows; /**< number of rows in the data table. */ uint16_t numCols; /**< number of columns in the data table. */ q31_t *pData; /**< points to the data table. */ } arm_bilinear_interp_instance_q31; /** * @brief Instance structure for the Q15 bilinear interpolation function. */ typedef struct { uint16_t numRows; /**< number of rows in the data table. */ uint16_t numCols; /**< number of columns in the data table. */ q15_t *pData; /**< points to the data table. */ } arm_bilinear_interp_instance_q15; /** * @brief Instance structure for the Q15 bilinear interpolation function. */ typedef struct { uint16_t numRows; /**< number of rows in the data table. */ uint16_t numCols; /**< number of columns in the data table. */ q7_t *pData; /**< points to the data table. */ } arm_bilinear_interp_instance_q7; /** * @brief Q7 vector multiplication. * @param[in] *pSrcA points to the first input vector * @param[in] *pSrcB points to the second input vector * @param[out] *pDst points to the output vector * @param[in] blockSize number of samples in each vector * @return none. */ void arm_mult_q7( q7_t * pSrcA, q7_t * pSrcB, q7_t * pDst, uint32_t blockSize); /** * @brief Q15 vector multiplication. * @param[in] *pSrcA points to the first input vector * @param[in] *pSrcB points to the second input vector * @param[out] *pDst points to the output vector * @param[in] blockSize number of samples in each vector * @return none. */ void arm_mult_q15( q15_t * pSrcA, q15_t * pSrcB, q15_t * pDst, uint32_t blockSize); /** * @brief Q31 vector multiplication. * @param[in] *pSrcA points to the first input vector * @param[in] *pSrcB points to the second input vector * @param[out] *pDst points to the output vector * @param[in] blockSize number of samples in each vector * @return none. */ void arm_mult_q31( q31_t * pSrcA, q31_t * pSrcB, q31_t * pDst, uint32_t blockSize); /** * @brief Floating-point vector multiplication. * @param[in] *pSrcA points to the first input vector * @param[in] *pSrcB points to the second input vector * @param[out] *pDst points to the output vector * @param[in] blockSize number of samples in each vector * @return none. */ void arm_mult_f32( float32_t * pSrcA, float32_t * pSrcB, float32_t * pDst, uint32_t blockSize); /** * @brief Instance structure for the Q15 CFFT/CIFFT function. */ typedef struct { uint16_t fftLen; /**< length of the FFT. */ uint8_t ifftFlag; /**< flag that selects forward (ifftFlag=0) or inverse (ifftFlag=1) transform. */ uint8_t bitReverseFlag; /**< flag that enables (bitReverseFlag=1) or disables (bitReverseFlag=0) bit reversal of output. */ q15_t *pTwiddle; /**< points to the Sin twiddle factor table. */ uint16_t *pBitRevTable; /**< points to the bit reversal table. */ uint16_t twidCoefModifier; /**< twiddle coefficient modifier that supports different size FFTs with the same twiddle factor table. */ uint16_t bitRevFactor; /**< bit reversal modifier that supports different size FFTs with the same bit reversal table. */ } arm_cfft_radix2_instance_q15; /* Deprecated */ arm_status arm_cfft_radix2_init_q15( arm_cfft_radix2_instance_q15 * S, uint16_t fftLen, uint8_t ifftFlag, uint8_t bitReverseFlag); /* Deprecated */ void arm_cfft_radix2_q15( const arm_cfft_radix2_instance_q15 * S, q15_t * pSrc); /** * @brief Instance structure for the Q15 CFFT/CIFFT function. */ typedef struct { uint16_t fftLen; /**< length of the FFT. */ uint8_t ifftFlag; /**< flag that selects forward (ifftFlag=0) or inverse (ifftFlag=1) transform. */ uint8_t bitReverseFlag; /**< flag that enables (bitReverseFlag=1) or disables (bitReverseFlag=0) bit reversal of output. */ q15_t *pTwiddle; /**< points to the twiddle factor table. */ uint16_t *pBitRevTable; /**< points to the bit reversal table. */ uint16_t twidCoefModifier; /**< twiddle coefficient modifier that supports different size FFTs with the same twiddle factor table. */ uint16_t bitRevFactor; /**< bit reversal modifier that supports different size FFTs with the same bit reversal table. */ } arm_cfft_radix4_instance_q15; /* Deprecated */ arm_status arm_cfft_radix4_init_q15( arm_cfft_radix4_instance_q15 * S, uint16_t fftLen, uint8_t ifftFlag, uint8_t bitReverseFlag); /* Deprecated */ void arm_cfft_radix4_q15( const arm_cfft_radix4_instance_q15 * S, q15_t * pSrc); /** * @brief Instance structure for the Radix-2 Q31 CFFT/CIFFT function. */ typedef struct { uint16_t fftLen; /**< length of the FFT. */ uint8_t ifftFlag; /**< flag that selects forward (ifftFlag=0) or inverse (ifftFlag=1) transform. */ uint8_t bitReverseFlag; /**< flag that enables (bitReverseFlag=1) or disables (bitReverseFlag=0) bit reversal of output. */ q31_t *pTwiddle; /**< points to the Twiddle factor table. */ uint16_t *pBitRevTable; /**< points to the bit reversal table. */ uint16_t twidCoefModifier; /**< twiddle coefficient modifier that supports different size FFTs with the same twiddle factor table. */ uint16_t bitRevFactor; /**< bit reversal modifier that supports different size FFTs with the same bit reversal table. */ } arm_cfft_radix2_instance_q31; /* Deprecated */ arm_status arm_cfft_radix2_init_q31( arm_cfft_radix2_instance_q31 * S, uint16_t fftLen, uint8_t ifftFlag, uint8_t bitReverseFlag); /* Deprecated */ void arm_cfft_radix2_q31( const arm_cfft_radix2_instance_q31 * S, q31_t * pSrc); /** * @brief Instance structure for the Q31 CFFT/CIFFT function. */ typedef struct { uint16_t fftLen; /**< length of the FFT. */ uint8_t ifftFlag; /**< flag that selects forward (ifftFlag=0) or inverse (ifftFlag=1) transform. */ uint8_t bitReverseFlag; /**< flag that enables (bitReverseFlag=1) or disables (bitReverseFlag=0) bit reversal of output. */ q31_t *pTwiddle; /**< points to the twiddle factor table. */ uint16_t *pBitRevTable; /**< points to the bit reversal table. */ uint16_t twidCoefModifier; /**< twiddle coefficient modifier that supports different size FFTs with the same twiddle factor table. */ uint16_t bitRevFactor; /**< bit reversal modifier that supports different size FFTs with the same bit reversal table. */ } arm_cfft_radix4_instance_q31; /* Deprecated */ void arm_cfft_radix4_q31( const arm_cfft_radix4_instance_q31 * S, q31_t * pSrc); /* Deprecated */ arm_status arm_cfft_radix4_init_q31( arm_cfft_radix4_instance_q31 * S, uint16_t fftLen, uint8_t ifftFlag, uint8_t bitReverseFlag); /** * @brief Instance structure for the floating-point CFFT/CIFFT function. */ typedef struct { uint16_t fftLen; /**< length of the FFT. */ uint8_t ifftFlag; /**< flag that selects forward (ifftFlag=0) or inverse (ifftFlag=1) transform. */ uint8_t bitReverseFlag; /**< flag that enables (bitReverseFlag=1) or disables (bitReverseFlag=0) bit reversal of output. */ float32_t *pTwiddle; /**< points to the Twiddle factor table. */ uint16_t *pBitRevTable; /**< points to the bit reversal table. */ uint16_t twidCoefModifier; /**< twiddle coefficient modifier that supports different size FFTs with the same twiddle factor table. */ uint16_t bitRevFactor; /**< bit reversal modifier that supports different size FFTs with the same bit reversal table. */ float32_t onebyfftLen; /**< value of 1/fftLen. */ } arm_cfft_radix2_instance_f32; /* Deprecated */ arm_status arm_cfft_radix2_init_f32( arm_cfft_radix2_instance_f32 * S, uint16_t fftLen, uint8_t ifftFlag, uint8_t bitReverseFlag); /* Deprecated */ void arm_cfft_radix2_f32( const arm_cfft_radix2_instance_f32 * S, float32_t * pSrc); /** * @brief Instance structure for the floating-point CFFT/CIFFT function. */ typedef struct { uint16_t fftLen; /**< length of the FFT. */ uint8_t ifftFlag; /**< flag that selects forward (ifftFlag=0) or inverse (ifftFlag=1) transform. */ uint8_t bitReverseFlag; /**< flag that enables (bitReverseFlag=1) or disables (bitReverseFlag=0) bit reversal of output. */ float32_t *pTwiddle; /**< points to the Twiddle factor table. */ uint16_t *pBitRevTable; /**< points to the bit reversal table. */ uint16_t twidCoefModifier; /**< twiddle coefficient modifier that supports different size FFTs with the same twiddle factor table. */ uint16_t bitRevFactor; /**< bit reversal modifier that supports different size FFTs with the same bit reversal table. */ float32_t onebyfftLen; /**< value of 1/fftLen. */ } arm_cfft_radix4_instance_f32; /* Deprecated */ arm_status arm_cfft_radix4_init_f32( arm_cfft_radix4_instance_f32 * S, uint16_t fftLen, uint8_t ifftFlag, uint8_t bitReverseFlag); /* Deprecated */ void arm_cfft_radix4_f32( const arm_cfft_radix4_instance_f32 * S, float32_t * pSrc); /** * @brief Instance structure for the fixed-point CFFT/CIFFT function. */ typedef struct { uint16_t fftLen; /**< length of the FFT. */ const q15_t *pTwiddle; /**< points to the Twiddle factor table. */ const uint16_t *pBitRevTable; /**< points to the bit reversal table. */ uint16_t bitRevLength; /**< bit reversal table length. */ } arm_cfft_instance_q15; void arm_cfft_q15( const arm_cfft_instance_q15 * S, q15_t * p1, uint8_t ifftFlag, uint8_t bitReverseFlag); /** * @brief Instance structure for the fixed-point CFFT/CIFFT function. */ typedef struct { uint16_t fftLen; /**< length of the FFT. */ const q31_t *pTwiddle; /**< points to the Twiddle factor table. */ const uint16_t *pBitRevTable; /**< points to the bit reversal table. */ uint16_t bitRevLength; /**< bit reversal table length. */ } arm_cfft_instance_q31; void arm_cfft_q31( const arm_cfft_instance_q31 * S, q31_t * p1, uint8_t ifftFlag, uint8_t bitReverseFlag); /** * @brief Instance structure for the floating-point CFFT/CIFFT function. */ typedef struct { uint16_t fftLen; /**< length of the FFT. */ const float32_t *pTwiddle; /**< points to the Twiddle factor table. */ const uint16_t *pBitRevTable; /**< points to the bit reversal table. */ uint16_t bitRevLength; /**< bit reversal table length. */ } arm_cfft_instance_f32; void arm_cfft_f32( const arm_cfft_instance_f32 * S, float32_t * p1, uint8_t ifftFlag, uint8_t bitReverseFlag); /** * @brief Instance structure for the Q15 RFFT/RIFFT function. */ typedef struct { uint32_t fftLenReal; /**< length of the real FFT. */ uint8_t ifftFlagR; /**< flag that selects forward (ifftFlagR=0) or inverse (ifftFlagR=1) transform. */ uint8_t bitReverseFlagR; /**< flag that enables (bitReverseFlagR=1) or disables (bitReverseFlagR=0) bit reversal of output. */ uint32_t twidCoefRModifier; /**< twiddle coefficient modifier that supports different size FFTs with the same twiddle factor table. */ q15_t *pTwiddleAReal; /**< points to the real twiddle factor table. */ q15_t *pTwiddleBReal; /**< points to the imag twiddle factor table. */ const arm_cfft_instance_q15 *pCfft; /**< points to the complex FFT instance. */ } arm_rfft_instance_q15; arm_status arm_rfft_init_q15( arm_rfft_instance_q15 * S, uint32_t fftLenReal, uint32_t ifftFlagR, uint32_t bitReverseFlag); void arm_rfft_q15( const arm_rfft_instance_q15 * S, q15_t * pSrc, q15_t * pDst); /** * @brief Instance structure for the Q31 RFFT/RIFFT function. */ typedef struct { uint32_t fftLenReal; /**< length of the real FFT. */ uint8_t ifftFlagR; /**< flag that selects forward (ifftFlagR=0) or inverse (ifftFlagR=1) transform. */ uint8_t bitReverseFlagR; /**< flag that enables (bitReverseFlagR=1) or disables (bitReverseFlagR=0) bit reversal of output. */ uint32_t twidCoefRModifier; /**< twiddle coefficient modifier that supports different size FFTs with the same twiddle factor table. */ q31_t *pTwiddleAReal; /**< points to the real twiddle factor table. */ q31_t *pTwiddleBReal; /**< points to the imag twiddle factor table. */ const arm_cfft_instance_q31 *pCfft; /**< points to the complex FFT instance. */ } arm_rfft_instance_q31; arm_status arm_rfft_init_q31( arm_rfft_instance_q31 * S, uint32_t fftLenReal, uint32_t ifftFlagR, uint32_t bitReverseFlag); void arm_rfft_q31( const arm_rfft_instance_q31 * S, q31_t * pSrc, q31_t * pDst); /** * @brief Instance structure for the floating-point RFFT/RIFFT function. */ typedef struct { uint32_t fftLenReal; /**< length of the real FFT. */ uint16_t fftLenBy2; /**< length of the complex FFT. */ uint8_t ifftFlagR; /**< flag that selects forward (ifftFlagR=0) or inverse (ifftFlagR=1) transform. */ uint8_t bitReverseFlagR; /**< flag that enables (bitReverseFlagR=1) or disables (bitReverseFlagR=0) bit reversal of output. */ uint32_t twidCoefRModifier; /**< twiddle coefficient modifier that supports different size FFTs with the same twiddle factor table. */ float32_t *pTwiddleAReal; /**< points to the real twiddle factor table. */ float32_t *pTwiddleBReal; /**< points to the imag twiddle factor table. */ arm_cfft_radix4_instance_f32 *pCfft; /**< points to the complex FFT instance. */ } arm_rfft_instance_f32; arm_status arm_rfft_init_f32( arm_rfft_instance_f32 * S, arm_cfft_radix4_instance_f32 * S_CFFT, uint32_t fftLenReal, uint32_t ifftFlagR, uint32_t bitReverseFlag); void arm_rfft_f32( const arm_rfft_instance_f32 * S, float32_t * pSrc, float32_t * pDst); /** * @brief Instance structure for the floating-point RFFT/RIFFT function. */ typedef struct { arm_cfft_instance_f32 Sint; /**< Internal CFFT structure. */ uint16_t fftLenRFFT; /**< length of the real sequence */ float32_t * pTwiddleRFFT; /**< Twiddle factors real stage */ } arm_rfft_fast_instance_f32 ; arm_status arm_rfft_fast_init_f32 ( arm_rfft_fast_instance_f32 * S, uint16_t fftLen); void arm_rfft_fast_f32( arm_rfft_fast_instance_f32 * S, float32_t * p, float32_t * pOut, uint8_t ifftFlag); /** * @brief Instance structure for the floating-point DCT4/IDCT4 function. */ typedef struct { uint16_t N; /**< length of the DCT4. */ uint16_t Nby2; /**< half of the length of the DCT4. */ float32_t normalize; /**< normalizing factor. */ float32_t *pTwiddle; /**< points to the twiddle factor table. */ float32_t *pCosFactor; /**< points to the cosFactor table. */ arm_rfft_instance_f32 *pRfft; /**< points to the real FFT instance. */ arm_cfft_radix4_instance_f32 *pCfft; /**< points to the complex FFT instance. */ } arm_dct4_instance_f32; /** * @brief Initialization function for the floating-point DCT4/IDCT4. * @param[in,out] *S points to an instance of floating-point DCT4/IDCT4 structure. * @param[in] *S_RFFT points to an instance of floating-point RFFT/RIFFT structure. * @param[in] *S_CFFT points to an instance of floating-point CFFT/CIFFT structure. * @param[in] N length of the DCT4. * @param[in] Nby2 half of the length of the DCT4. * @param[in] normalize normalizing factor. * @return arm_status function returns ARM_MATH_SUCCESS if initialization is successful or ARM_MATH_ARGUMENT_ERROR if fftLenReal is not a supported transform length. */ arm_status arm_dct4_init_f32( arm_dct4_instance_f32 * S, arm_rfft_instance_f32 * S_RFFT, arm_cfft_radix4_instance_f32 * S_CFFT, uint16_t N, uint16_t Nby2, float32_t normalize); /** * @brief Processing function for the floating-point DCT4/IDCT4. * @param[in] *S points to an instance of the floating-point DCT4/IDCT4 structure. * @param[in] *pState points to state buffer. * @param[in,out] *pInlineBuffer points to the in-place input and output buffer. * @return none. */ void arm_dct4_f32( const arm_dct4_instance_f32 * S, float32_t * pState, float32_t * pInlineBuffer); /** * @brief Instance structure for the Q31 DCT4/IDCT4 function. */ typedef struct { uint16_t N; /**< length of the DCT4. */ uint16_t Nby2; /**< half of the length of the DCT4. */ q31_t normalize; /**< normalizing factor. */ q31_t *pTwiddle; /**< points to the twiddle factor table. */ q31_t *pCosFactor; /**< points to the cosFactor table. */ arm_rfft_instance_q31 *pRfft; /**< points to the real FFT instance. */ arm_cfft_radix4_instance_q31 *pCfft; /**< points to the complex FFT instance. */ } arm_dct4_instance_q31; /** * @brief Initialization function for the Q31 DCT4/IDCT4. * @param[in,out] *S points to an instance of Q31 DCT4/IDCT4 structure. * @param[in] *S_RFFT points to an instance of Q31 RFFT/RIFFT structure * @param[in] *S_CFFT points to an instance of Q31 CFFT/CIFFT structure * @param[in] N length of the DCT4. * @param[in] Nby2 half of the length of the DCT4. * @param[in] normalize normalizing factor. * @return arm_status function returns ARM_MATH_SUCCESS if initialization is successful or ARM_MATH_ARGUMENT_ERROR if N is not a supported transform length. */ arm_status arm_dct4_init_q31( arm_dct4_instance_q31 * S, arm_rfft_instance_q31 * S_RFFT, arm_cfft_radix4_instance_q31 * S_CFFT, uint16_t N, uint16_t Nby2, q31_t normalize); /** * @brief Processing function for the Q31 DCT4/IDCT4. * @param[in] *S points to an instance of the Q31 DCT4 structure. * @param[in] *pState points to state buffer. * @param[in,out] *pInlineBuffer points to the in-place input and output buffer. * @return none. */ void arm_dct4_q31( const arm_dct4_instance_q31 * S, q31_t * pState, q31_t * pInlineBuffer); /** * @brief Instance structure for the Q15 DCT4/IDCT4 function. */ typedef struct { uint16_t N; /**< length of the DCT4. */ uint16_t Nby2; /**< half of the length of the DCT4. */ q15_t normalize; /**< normalizing factor. */ q15_t *pTwiddle; /**< points to the twiddle factor table. */ q15_t *pCosFactor; /**< points to the cosFactor table. */ arm_rfft_instance_q15 *pRfft; /**< points to the real FFT instance. */ arm_cfft_radix4_instance_q15 *pCfft; /**< points to the complex FFT instance. */ } arm_dct4_instance_q15; /** * @brief Initialization function for the Q15 DCT4/IDCT4. * @param[in,out] *S points to an instance of Q15 DCT4/IDCT4 structure. * @param[in] *S_RFFT points to an instance of Q15 RFFT/RIFFT structure. * @param[in] *S_CFFT points to an instance of Q15 CFFT/CIFFT structure. * @param[in] N length of the DCT4. * @param[in] Nby2 half of the length of the DCT4. * @param[in] normalize normalizing factor. * @return arm_status function returns ARM_MATH_SUCCESS if initialization is successful or ARM_MATH_ARGUMENT_ERROR if N is not a supported transform length. */ arm_status arm_dct4_init_q15( arm_dct4_instance_q15 * S, arm_rfft_instance_q15 * S_RFFT, arm_cfft_radix4_instance_q15 * S_CFFT, uint16_t N, uint16_t Nby2, q15_t normalize); /** * @brief Processing function for the Q15 DCT4/IDCT4. * @param[in] *S points to an instance of the Q15 DCT4 structure. * @param[in] *pState points to state buffer. * @param[in,out] *pInlineBuffer points to the in-place input and output buffer. * @return none. */ void arm_dct4_q15( const arm_dct4_instance_q15 * S, q15_t * pState, q15_t * pInlineBuffer); /** * @brief Floating-point vector addition. * @param[in] *pSrcA points to the first input vector * @param[in] *pSrcB points to the second input vector * @param[out] *pDst points to the output vector * @param[in] blockSize number of samples in each vector * @return none. */ void arm_add_f32( float32_t * pSrcA, float32_t * pSrcB, float32_t * pDst, uint32_t blockSize); /** * @brief Q7 vector addition. * @param[in] *pSrcA points to the first input vector * @param[in] *pSrcB points to the second input vector * @param[out] *pDst points to the output vector * @param[in] blockSize number of samples in each vector * @return none. */ void arm_add_q7( q7_t * pSrcA, q7_t * pSrcB, q7_t * pDst, uint32_t blockSize); /** * @brief Q15 vector addition. * @param[in] *pSrcA points to the first input vector * @param[in] *pSrcB points to the second input vector * @param[out] *pDst points to the output vector * @param[in] blockSize number of samples in each vector * @return none. */ void arm_add_q15( q15_t * pSrcA, q15_t * pSrcB, q15_t * pDst, uint32_t blockSize); /** * @brief Q31 vector addition. * @param[in] *pSrcA points to the first input vector * @param[in] *pSrcB points to the second input vector * @param[out] *pDst points to the output vector * @param[in] blockSize number of samples in each vector * @return none. */ void arm_add_q31( q31_t * pSrcA, q31_t * pSrcB, q31_t * pDst, uint32_t blockSize); /** * @brief Floating-point vector subtraction. * @param[in] *pSrcA points to the first input vector * @param[in] *pSrcB points to the second input vector * @param[out] *pDst points to the output vector * @param[in] blockSize number of samples in each vector * @return none. */ void arm_sub_f32( float32_t * pSrcA, float32_t * pSrcB, float32_t * pDst, uint32_t blockSize); /** * @brief Q7 vector subtraction. * @param[in] *pSrcA points to the first input vector * @param[in] *pSrcB points to the second input vector * @param[out] *pDst points to the output vector * @param[in] blockSize number of samples in each vector * @return none. */ void arm_sub_q7( q7_t * pSrcA, q7_t * pSrcB, q7_t * pDst, uint32_t blockSize); /** * @brief Q15 vector subtraction. * @param[in] *pSrcA points to the first input vector * @param[in] *pSrcB points to the second input vector * @param[out] *pDst points to the output vector * @param[in] blockSize number of samples in each vector * @return none. */ void arm_sub_q15( q15_t * pSrcA, q15_t * pSrcB, q15_t * pDst, uint32_t blockSize); /** * @brief Q31 vector subtraction. * @param[in] *pSrcA points to the first input vector * @param[in] *pSrcB points to the second input vector * @param[out] *pDst points to the output vector * @param[in] blockSize number of samples in each vector * @return none. */ void arm_sub_q31( q31_t * pSrcA, q31_t * pSrcB, q31_t * pDst, uint32_t blockSize); /** * @brief Multiplies a floating-point vector by a scalar. * @param[in] *pSrc points to the input vector * @param[in] scale scale factor to be applied * @param[out] *pDst points to the output vector * @param[in] blockSize number of samples in the vector * @return none. */ void arm_scale_f32( float32_t * pSrc, float32_t scale, float32_t * pDst, uint32_t blockSize); /** * @brief Multiplies a Q7 vector by a scalar. * @param[in] *pSrc points to the input vector * @param[in] scaleFract fractional portion of the scale value * @param[in] shift number of bits to shift the result by * @param[out] *pDst points to the output vector * @param[in] blockSize number of samples in the vector * @return none. */ void arm_scale_q7( q7_t * pSrc, q7_t scaleFract, int8_t shift, q7_t * pDst, uint32_t blockSize); /** * @brief Multiplies a Q15 vector by a scalar. * @param[in] *pSrc points to the input vector * @param[in] scaleFract fractional portion of the scale value * @param[in] shift number of bits to shift the result by * @param[out] *pDst points to the output vector * @param[in] blockSize number of samples in the vector * @return none. */ void arm_scale_q15( q15_t * pSrc, q15_t scaleFract, int8_t shift, q15_t * pDst, uint32_t blockSize); /** * @brief Multiplies a Q31 vector by a scalar. * @param[in] *pSrc points to the input vector * @param[in] scaleFract fractional portion of the scale value * @param[in] shift number of bits to shift the result by * @param[out] *pDst points to the output vector * @param[in] blockSize number of samples in the vector * @return none. */ void arm_scale_q31( q31_t * pSrc, q31_t scaleFract, int8_t shift, q31_t * pDst, uint32_t blockSize); /** * @brief Q7 vector absolute value. * @param[in] *pSrc points to the input buffer * @param[out] *pDst points to the output buffer * @param[in] blockSize number of samples in each vector * @return none. */ void arm_abs_q7( q7_t * pSrc, q7_t * pDst, uint32_t blockSize); /** * @brief Floating-point vector absolute value. * @param[in] *pSrc points to the input buffer * @param[out] *pDst points to the output buffer * @param[in] blockSize number of samples in each vector * @return none. */ void arm_abs_f32( float32_t * pSrc, float32_t * pDst, uint32_t blockSize); /** * @brief Q15 vector absolute value. * @param[in] *pSrc points to the input buffer * @param[out] *pDst points to the output buffer * @param[in] blockSize number of samples in each vector * @return none. */ void arm_abs_q15( q15_t * pSrc, q15_t * pDst, uint32_t blockSize); /** * @brief Q31 vector absolute value. * @param[in] *pSrc points to the input buffer * @param[out] *pDst points to the output buffer * @param[in] blockSize number of samples in each vector * @return none. */ void arm_abs_q31( q31_t * pSrc, q31_t * pDst, uint32_t blockSize); /** * @brief Dot product of floating-point vectors. * @param[in] *pSrcA points to the first input vector * @param[in] *pSrcB points to the second input vector * @param[in] blockSize number of samples in each vector * @param[out] *result output result returned here * @return none. */ void arm_dot_prod_f32( float32_t * pSrcA, float32_t * pSrcB, uint32_t blockSize, float32_t * result); /** * @brief Dot product of Q7 vectors. * @param[in] *pSrcA points to the first input vector * @param[in] *pSrcB points to the second input vector * @param[in] blockSize number of samples in each vector * @param[out] *result output result returned here * @return none. */ void arm_dot_prod_q7( q7_t * pSrcA, q7_t * pSrcB, uint32_t blockSize, q31_t * result); /** * @brief Dot product of Q15 vectors. * @param[in] *pSrcA points to the first input vector * @param[in] *pSrcB points to the second input vector * @param[in] blockSize number of samples in each vector * @param[out] *result output result returned here * @return none. */ void arm_dot_prod_q15( q15_t * pSrcA, q15_t * pSrcB, uint32_t blockSize, q63_t * result); /** * @brief Dot product of Q31 vectors. * @param[in] *pSrcA points to the first input vector * @param[in] *pSrcB points to the second input vector * @param[in] blockSize number of samples in each vector * @param[out] *result output result returned here * @return none. */ void arm_dot_prod_q31( q31_t * pSrcA, q31_t * pSrcB, uint32_t blockSize, q63_t * result); /** * @brief Shifts the elements of a Q7 vector a specified number of bits. * @param[in] *pSrc points to the input vector * @param[in] shiftBits number of bits to shift. A positive value shifts left; a negative value shifts right. * @param[out] *pDst points to the output vector * @param[in] blockSize number of samples in the vector * @return none. */ void arm_shift_q7( q7_t * pSrc, int8_t shiftBits, q7_t * pDst, uint32_t blockSize); /** * @brief Shifts the elements of a Q15 vector a specified number of bits. * @param[in] *pSrc points to the input vector * @param[in] shiftBits number of bits to shift. A positive value shifts left; a negative value shifts right. * @param[out] *pDst points to the output vector * @param[in] blockSize number of samples in the vector * @return none. */ void arm_shift_q15( q15_t * pSrc, int8_t shiftBits, q15_t * pDst, uint32_t blockSize); /** * @brief Shifts the elements of a Q31 vector a specified number of bits. * @param[in] *pSrc points to the input vector * @param[in] shiftBits number of bits to shift. A positive value shifts left; a negative value shifts right. * @param[out] *pDst points to the output vector * @param[in] blockSize number of samples in the vector * @return none. */ void arm_shift_q31( q31_t * pSrc, int8_t shiftBits, q31_t * pDst, uint32_t blockSize); /** * @brief Adds a constant offset to a floating-point vector. * @param[in] *pSrc points to the input vector * @param[in] offset is the offset to be added * @param[out] *pDst points to the output vector * @param[in] blockSize number of samples in the vector * @return none. */ void arm_offset_f32( float32_t * pSrc, float32_t offset, float32_t * pDst, uint32_t blockSize); /** * @brief Adds a constant offset to a Q7 vector. * @param[in] *pSrc points to the input vector * @param[in] offset is the offset to be added * @param[out] *pDst points to the output vector * @param[in] blockSize number of samples in the vector * @return none. */ void arm_offset_q7( q7_t * pSrc, q7_t offset, q7_t * pDst, uint32_t blockSize); /** * @brief Adds a constant offset to a Q15 vector. * @param[in] *pSrc points to the input vector * @param[in] offset is the offset to be added * @param[out] *pDst points to the output vector * @param[in] blockSize number of samples in the vector * @return none. */ void arm_offset_q15( q15_t * pSrc, q15_t offset, q15_t * pDst, uint32_t blockSize); /** * @brief Adds a constant offset to a Q31 vector. * @param[in] *pSrc points to the input vector * @param[in] offset is the offset to be added * @param[out] *pDst points to the output vector * @param[in] blockSize number of samples in the vector * @return none. */ void arm_offset_q31( q31_t * pSrc, q31_t offset, q31_t * pDst, uint32_t blockSize); /** * @brief Negates the elements of a floating-point vector. * @param[in] *pSrc points to the input vector * @param[out] *pDst points to the output vector * @param[in] blockSize number of samples in the vector * @return none. */ void arm_negate_f32( float32_t * pSrc, float32_t * pDst, uint32_t blockSize); /** * @brief Negates the elements of a Q7 vector. * @param[in] *pSrc points to the input vector * @param[out] *pDst points to the output vector * @param[in] blockSize number of samples in the vector * @return none. */ void arm_negate_q7( q7_t * pSrc, q7_t * pDst, uint32_t blockSize); /** * @brief Negates the elements of a Q15 vector. * @param[in] *pSrc points to the input vector * @param[out] *pDst points to the output vector * @param[in] blockSize number of samples in the vector * @return none. */ void arm_negate_q15( q15_t * pSrc, q15_t * pDst, uint32_t blockSize); /** * @brief Negates the elements of a Q31 vector. * @param[in] *pSrc points to the input vector * @param[out] *pDst points to the output vector * @param[in] blockSize number of samples in the vector * @return none. */ void arm_negate_q31( q31_t * pSrc, q31_t * pDst, uint32_t blockSize); /** * @brief Copies the elements of a floating-point vector. * @param[in] *pSrc input pointer * @param[out] *pDst output pointer * @param[in] blockSize number of samples to process * @return none. */ void arm_copy_f32( float32_t * pSrc, float32_t * pDst, uint32_t blockSize); /** * @brief Copies the elements of a Q7 vector. * @param[in] *pSrc input pointer * @param[out] *pDst output pointer * @param[in] blockSize number of samples to process * @return none. */ void arm_copy_q7( q7_t * pSrc, q7_t * pDst, uint32_t blockSize); /** * @brief Copies the elements of a Q15 vector. * @param[in] *pSrc input pointer * @param[out] *pDst output pointer * @param[in] blockSize number of samples to process * @return none. */ void arm_copy_q15( q15_t * pSrc, q15_t * pDst, uint32_t blockSize); /** * @brief Copies the elements of a Q31 vector. * @param[in] *pSrc input pointer * @param[out] *pDst output pointer * @param[in] blockSize number of samples to process * @return none. */ void arm_copy_q31( q31_t * pSrc, q31_t * pDst, uint32_t blockSize); /** * @brief Fills a constant value into a floating-point vector. * @param[in] value input value to be filled * @param[out] *pDst output pointer * @param[in] blockSize number of samples to process * @return none. */ void arm_fill_f32( float32_t value, float32_t * pDst, uint32_t blockSize); /** * @brief Fills a constant value into a Q7 vector. * @param[in] value input value to be filled * @param[out] *pDst output pointer * @param[in] blockSize number of samples to process * @return none. */ void arm_fill_q7( q7_t value, q7_t * pDst, uint32_t blockSize); /** * @brief Fills a constant value into a Q15 vector. * @param[in] value input value to be filled * @param[out] *pDst output pointer * @param[in] blockSize number of samples to process * @return none. */ void arm_fill_q15( q15_t value, q15_t * pDst, uint32_t blockSize); /** * @brief Fills a constant value into a Q31 vector. * @param[in] value input value to be filled * @param[out] *pDst output pointer * @param[in] blockSize number of samples to process * @return none. */ void arm_fill_q31( q31_t value, q31_t * pDst, uint32_t blockSize); /** * @brief Convolution of floating-point sequences. * @param[in] *pSrcA points to the first input sequence. * @param[in] srcALen length of the first input sequence. * @param[in] *pSrcB points to the second input sequence. * @param[in] srcBLen length of the second input sequence. * @param[out] *pDst points to the location where the output result is written. Length srcALen+srcBLen-1. * @return none. */ void arm_conv_f32( float32_t * pSrcA, uint32_t srcALen, float32_t * pSrcB, uint32_t srcBLen, float32_t * pDst); /** * @brief Convolution of Q15 sequences. * @param[in] *pSrcA points to the first input sequence. * @param[in] srcALen length of the first input sequence. * @param[in] *pSrcB points to the second input sequence. * @param[in] srcBLen length of the second input sequence. * @param[out] *pDst points to the block of output data Length srcALen+srcBLen-1. * @param[in] *pScratch1 points to scratch buffer of size max(srcALen, srcBLen) + 2*min(srcALen, srcBLen) - 2. * @param[in] *pScratch2 points to scratch buffer of size min(srcALen, srcBLen). * @return none. */ void arm_conv_opt_q15( q15_t * pSrcA, uint32_t srcALen, q15_t * pSrcB, uint32_t srcBLen, q15_t * pDst, q15_t * pScratch1, q15_t * pScratch2); /** * @brief Convolution of Q15 sequences. * @param[in] *pSrcA points to the first input sequence. * @param[in] srcALen length of the first input sequence. * @param[in] *pSrcB points to the second input sequence. * @param[in] srcBLen length of the second input sequence. * @param[out] *pDst points to the location where the output result is written. Length srcALen+srcBLen-1. * @return none. */ void arm_conv_q15( q15_t * pSrcA, uint32_t srcALen, q15_t * pSrcB, uint32_t srcBLen, q15_t * pDst); /** * @brief Convolution of Q15 sequences (fast version) for Cortex-M3 and Cortex-M4 * @param[in] *pSrcA points to the first input sequence. * @param[in] srcALen length of the first input sequence. * @param[in] *pSrcB points to the second input sequence. * @param[in] srcBLen length of the second input sequence. * @param[out] *pDst points to the block of output data Length srcALen+srcBLen-1. * @return none. */ void arm_conv_fast_q15( q15_t * pSrcA, uint32_t srcALen, q15_t * pSrcB, uint32_t srcBLen, q15_t * pDst); /** * @brief Convolution of Q15 sequences (fast version) for Cortex-M3 and Cortex-M4 * @param[in] *pSrcA points to the first input sequence. * @param[in] srcALen length of the first input sequence. * @param[in] *pSrcB points to the second input sequence. * @param[in] srcBLen length of the second input sequence. * @param[out] *pDst points to the block of output data Length srcALen+srcBLen-1. * @param[in] *pScratch1 points to scratch buffer of size max(srcALen, srcBLen) + 2*min(srcALen, srcBLen) - 2. * @param[in] *pScratch2 points to scratch buffer of size min(srcALen, srcBLen). * @return none. */ void arm_conv_fast_opt_q15( q15_t * pSrcA, uint32_t srcALen, q15_t * pSrcB, uint32_t srcBLen, q15_t * pDst, q15_t * pScratch1, q15_t * pScratch2); /** * @brief Convolution of Q31 sequences. * @param[in] *pSrcA points to the first input sequence. * @param[in] srcALen length of the first input sequence. * @param[in] *pSrcB points to the second input sequence. * @param[in] srcBLen length of the second input sequence. * @param[out] *pDst points to the block of output data Length srcALen+srcBLen-1. * @return none. */ void arm_conv_q31( q31_t * pSrcA, uint32_t srcALen, q31_t * pSrcB, uint32_t srcBLen, q31_t * pDst); /** * @brief Convolution of Q31 sequences (fast version) for Cortex-M3 and Cortex-M4 * @param[in] *pSrcA points to the first input sequence. * @param[in] srcALen length of the first input sequence. * @param[in] *pSrcB points to the second input sequence. * @param[in] srcBLen length of the second input sequence. * @param[out] *pDst points to the block of output data Length srcALen+srcBLen-1. * @return none. */ void arm_conv_fast_q31( q31_t * pSrcA, uint32_t srcALen, q31_t * pSrcB, uint32_t srcBLen, q31_t * pDst); /** * @brief Convolution of Q7 sequences. * @param[in] *pSrcA points to the first input sequence. * @param[in] srcALen length of the first input sequence. * @param[in] *pSrcB points to the second input sequence. * @param[in] srcBLen length of the second input sequence. * @param[out] *pDst points to the block of output data Length srcALen+srcBLen-1. * @param[in] *pScratch1 points to scratch buffer(of type q15_t) of size max(srcALen, srcBLen) + 2*min(srcALen, srcBLen) - 2. * @param[in] *pScratch2 points to scratch buffer (of type q15_t) of size min(srcALen, srcBLen). * @return none. */ void arm_conv_opt_q7( q7_t * pSrcA, uint32_t srcALen, q7_t * pSrcB, uint32_t srcBLen, q7_t * pDst, q15_t * pScratch1, q15_t * pScratch2); /** * @brief Convolution of Q7 sequences. * @param[in] *pSrcA points to the first input sequence. * @param[in] srcALen length of the first input sequence. * @param[in] *pSrcB points to the second input sequence. * @param[in] srcBLen length of the second input sequence. * @param[out] *pDst points to the block of output data Length srcALen+srcBLen-1. * @return none. */ void arm_conv_q7( q7_t * pSrcA, uint32_t srcALen, q7_t * pSrcB, uint32_t srcBLen, q7_t * pDst); /** * @brief Partial convolution of floating-point sequences. * @param[in] *pSrcA points to the first input sequence. * @param[in] srcALen length of the first input sequence. * @param[in] *pSrcB points to the second input sequence. * @param[in] srcBLen length of the second input sequence. * @param[out] *pDst points to the block of output data * @param[in] firstIndex is the first output sample to start with. * @param[in] numPoints is the number of output points to be computed. * @return Returns either ARM_MATH_SUCCESS if the function completed correctly or ARM_MATH_ARGUMENT_ERROR if the requested subset is not in the range [0 srcALen+srcBLen-2]. */ arm_status arm_conv_partial_f32( float32_t * pSrcA, uint32_t srcALen, float32_t * pSrcB, uint32_t srcBLen, float32_t * pDst, uint32_t firstIndex, uint32_t numPoints); /** * @brief Partial convolution of Q15 sequences. * @param[in] *pSrcA points to the first input sequence. * @param[in] srcALen length of the first input sequence. * @param[in] *pSrcB points to the second input sequence. * @param[in] srcBLen length of the second input sequence. * @param[out] *pDst points to the block of output data * @param[in] firstIndex is the first output sample to start with. * @param[in] numPoints is the number of output points to be computed. * @param[in] * pScratch1 points to scratch buffer of size max(srcALen, srcBLen) + 2*min(srcALen, srcBLen) - 2. * @param[in] * pScratch2 points to scratch buffer of size min(srcALen, srcBLen). * @return Returns either ARM_MATH_SUCCESS if the function completed correctly or ARM_MATH_ARGUMENT_ERROR if the requested subset is not in the range [0 srcALen+srcBLen-2]. */ arm_status arm_conv_partial_opt_q15( q15_t * pSrcA, uint32_t srcALen, q15_t * pSrcB, uint32_t srcBLen, q15_t * pDst, uint32_t firstIndex, uint32_t numPoints, q15_t * pScratch1, q15_t * pScratch2); /** * @brief Partial convolution of Q15 sequences. * @param[in] *pSrcA points to the first input sequence. * @param[in] srcALen length of the first input sequence. * @param[in] *pSrcB points to the second input sequence. * @param[in] srcBLen length of the second input sequence. * @param[out] *pDst points to the block of output data * @param[in] firstIndex is the first output sample to start with. * @param[in] numPoints is the number of output points to be computed. * @return Returns either ARM_MATH_SUCCESS if the function completed correctly or ARM_MATH_ARGUMENT_ERROR if the requested subset is not in the range [0 srcALen+srcBLen-2]. */ arm_status arm_conv_partial_q15( q15_t * pSrcA, uint32_t srcALen, q15_t * pSrcB, uint32_t srcBLen, q15_t * pDst, uint32_t firstIndex, uint32_t numPoints); /** * @brief Partial convolution of Q15 sequences (fast version) for Cortex-M3 and Cortex-M4 * @param[in] *pSrcA points to the first input sequence. * @param[in] srcALen length of the first input sequence. * @param[in] *pSrcB points to the second input sequence. * @param[in] srcBLen length of the second input sequence. * @param[out] *pDst points to the block of output data * @param[in] firstIndex is the first output sample to start with. * @param[in] numPoints is the number of output points to be computed. * @return Returns either ARM_MATH_SUCCESS if the function completed correctly or ARM_MATH_ARGUMENT_ERROR if the requested subset is not in the range [0 srcALen+srcBLen-2]. */ arm_status arm_conv_partial_fast_q15( q15_t * pSrcA, uint32_t srcALen, q15_t * pSrcB, uint32_t srcBLen, q15_t * pDst, uint32_t firstIndex, uint32_t numPoints); /** * @brief Partial convolution of Q15 sequences (fast version) for Cortex-M3 and Cortex-M4 * @param[in] *pSrcA points to the first input sequence. * @param[in] srcALen length of the first input sequence. * @param[in] *pSrcB points to the second input sequence. * @param[in] srcBLen length of the second input sequence. * @param[out] *pDst points to the block of output data * @param[in] firstIndex is the first output sample to start with. * @param[in] numPoints is the number of output points to be computed. * @param[in] * pScratch1 points to scratch buffer of size max(srcALen, srcBLen) + 2*min(srcALen, srcBLen) - 2. * @param[in] * pScratch2 points to scratch buffer of size min(srcALen, srcBLen). * @return Returns either ARM_MATH_SUCCESS if the function completed correctly or ARM_MATH_ARGUMENT_ERROR if the requested subset is not in the range [0 srcALen+srcBLen-2]. */ arm_status arm_conv_partial_fast_opt_q15( q15_t * pSrcA, uint32_t srcALen, q15_t * pSrcB, uint32_t srcBLen, q15_t * pDst, uint32_t firstIndex, uint32_t numPoints, q15_t * pScratch1, q15_t * pScratch2); /** * @brief Partial convolution of Q31 sequences. * @param[in] *pSrcA points to the first input sequence. * @param[in] srcALen length of the first input sequence. * @param[in] *pSrcB points to the second input sequence. * @param[in] srcBLen length of the second input sequence. * @param[out] *pDst points to the block of output data * @param[in] firstIndex is the first output sample to start with. * @param[in] numPoints is the number of output points to be computed. * @return Returns either ARM_MATH_SUCCESS if the function completed correctly or ARM_MATH_ARGUMENT_ERROR if the requested subset is not in the range [0 srcALen+srcBLen-2]. */ arm_status arm_conv_partial_q31( q31_t * pSrcA, uint32_t srcALen, q31_t * pSrcB, uint32_t srcBLen, q31_t * pDst, uint32_t firstIndex, uint32_t numPoints); /** * @brief Partial convolution of Q31 sequences (fast version) for Cortex-M3 and Cortex-M4 * @param[in] *pSrcA points to the first input sequence. * @param[in] srcALen length of the first input sequence. * @param[in] *pSrcB points to the second input sequence. * @param[in] srcBLen length of the second input sequence. * @param[out] *pDst points to the block of output data * @param[in] firstIndex is the first output sample to start with. * @param[in] numPoints is the number of output points to be computed. * @return Returns either ARM_MATH_SUCCESS if the function completed correctly or ARM_MATH_ARGUMENT_ERROR if the requested subset is not in the range [0 srcALen+srcBLen-2]. */ arm_status arm_conv_partial_fast_q31( q31_t * pSrcA, uint32_t srcALen, q31_t * pSrcB, uint32_t srcBLen, q31_t * pDst, uint32_t firstIndex, uint32_t numPoints); /** * @brief Partial convolution of Q7 sequences * @param[in] *pSrcA points to the first input sequence. * @param[in] srcALen length of the first input sequence. * @param[in] *pSrcB points to the second input sequence. * @param[in] srcBLen length of the second input sequence. * @param[out] *pDst points to the block of output data * @param[in] firstIndex is the first output sample to start with. * @param[in] numPoints is the number of output points to be computed. * @param[in] *pScratch1 points to scratch buffer(of type q15_t) of size max(srcALen, srcBLen) + 2*min(srcALen, srcBLen) - 2. * @param[in] *pScratch2 points to scratch buffer (of type q15_t) of size min(srcALen, srcBLen). * @return Returns either ARM_MATH_SUCCESS if the function completed correctly or ARM_MATH_ARGUMENT_ERROR if the requested subset is not in the range [0 srcALen+srcBLen-2]. */ arm_status arm_conv_partial_opt_q7( q7_t * pSrcA, uint32_t srcALen, q7_t * pSrcB, uint32_t srcBLen, q7_t * pDst, uint32_t firstIndex, uint32_t numPoints, q15_t * pScratch1, q15_t * pScratch2); /** * @brief Partial convolution of Q7 sequences. * @param[in] *pSrcA points to the first input sequence. * @param[in] srcALen length of the first input sequence. * @param[in] *pSrcB points to the second input sequence. * @param[in] srcBLen length of the second input sequence. * @param[out] *pDst points to the block of output data * @param[in] firstIndex is the first output sample to start with. * @param[in] numPoints is the number of output points to be computed. * @return Returns either ARM_MATH_SUCCESS if the function completed correctly or ARM_MATH_ARGUMENT_ERROR if the requested subset is not in the range [0 srcALen+srcBLen-2]. */ arm_status arm_conv_partial_q7( q7_t * pSrcA, uint32_t srcALen, q7_t * pSrcB, uint32_t srcBLen, q7_t * pDst, uint32_t firstIndex, uint32_t numPoints); /** * @brief Instance structure for the Q15 FIR decimator. */ typedef struct { uint8_t M; /**< decimation factor. */ uint16_t numTaps; /**< number of coefficients in the filter. */ q15_t *pCoeffs; /**< points to the coefficient array. The array is of length numTaps.*/ q15_t *pState; /**< points to the state variable array. The array is of length numTaps+blockSize-1. */ } arm_fir_decimate_instance_q15; /** * @brief Instance structure for the Q31 FIR decimator. */ typedef struct { uint8_t M; /**< decimation factor. */ uint16_t numTaps; /**< number of coefficients in the filter. */ q31_t *pCoeffs; /**< points to the coefficient array. The array is of length numTaps.*/ q31_t *pState; /**< points to the state variable array. The array is of length numTaps+blockSize-1. */ } arm_fir_decimate_instance_q31; /** * @brief Instance structure for the floating-point FIR decimator. */ typedef struct { uint8_t M; /**< decimation factor. */ uint16_t numTaps; /**< number of coefficients in the filter. */ float32_t *pCoeffs; /**< points to the coefficient array. The array is of length numTaps.*/ float32_t *pState; /**< points to the state variable array. The array is of length numTaps+blockSize-1. */ } arm_fir_decimate_instance_f32; /** * @brief Processing function for the floating-point FIR decimator. * @param[in] *S points to an instance of the floating-point FIR decimator structure. * @param[in] *pSrc points to the block of input data. * @param[out] *pDst points to the block of output data * @param[in] blockSize number of input samples to process per call. * @return none */ void arm_fir_decimate_f32( const arm_fir_decimate_instance_f32 * S, float32_t * pSrc, float32_t * pDst, uint32_t blockSize); /** * @brief Initialization function for the floating-point FIR decimator. * @param[in,out] *S points to an instance of the floating-point FIR decimator structure. * @param[in] numTaps number of coefficients in the filter. * @param[in] M decimation factor. * @param[in] *pCoeffs points to the filter coefficients. * @param[in] *pState points to the state buffer. * @param[in] blockSize number of input samples to process per call. * @return The function returns ARM_MATH_SUCCESS if initialization is successful or ARM_MATH_LENGTH_ERROR if * blockSize is not a multiple of M. */ arm_status arm_fir_decimate_init_f32( arm_fir_decimate_instance_f32 * S, uint16_t numTaps, uint8_t M, float32_t * pCoeffs, float32_t * pState, uint32_t blockSize); /** * @brief Processing function for the Q15 FIR decimator. * @param[in] *S points to an instance of the Q15 FIR decimator structure. * @param[in] *pSrc points to the block of input data. * @param[out] *pDst points to the block of output data * @param[in] blockSize number of input samples to process per call. * @return none */ void arm_fir_decimate_q15( const arm_fir_decimate_instance_q15 * S, q15_t * pSrc, q15_t * pDst, uint32_t blockSize); /** * @brief Processing function for the Q15 FIR decimator (fast variant) for Cortex-M3 and Cortex-M4. * @param[in] *S points to an instance of the Q15 FIR decimator structure. * @param[in] *pSrc points to the block of input data. * @param[out] *pDst points to the block of output data * @param[in] blockSize number of input samples to process per call. * @return none */ void arm_fir_decimate_fast_q15( const arm_fir_decimate_instance_q15 * S, q15_t * pSrc, q15_t * pDst, uint32_t blockSize); /** * @brief Initialization function for the Q15 FIR decimator. * @param[in,out] *S points to an instance of the Q15 FIR decimator structure. * @param[in] numTaps number of coefficients in the filter. * @param[in] M decimation factor. * @param[in] *pCoeffs points to the filter coefficients. * @param[in] *pState points to the state buffer. * @param[in] blockSize number of input samples to process per call. * @return The function returns ARM_MATH_SUCCESS if initialization is successful or ARM_MATH_LENGTH_ERROR if * blockSize is not a multiple of M. */ arm_status arm_fir_decimate_init_q15( arm_fir_decimate_instance_q15 * S, uint16_t numTaps, uint8_t M, q15_t * pCoeffs, q15_t * pState, uint32_t blockSize); /** * @brief Processing function for the Q31 FIR decimator. * @param[in] *S points to an instance of the Q31 FIR decimator structure. * @param[in] *pSrc points to the block of input data. * @param[out] *pDst points to the block of output data * @param[in] blockSize number of input samples to process per call. * @return none */ void arm_fir_decimate_q31( const arm_fir_decimate_instance_q31 * S, q31_t * pSrc, q31_t * pDst, uint32_t blockSize); /** * @brief Processing function for the Q31 FIR decimator (fast variant) for Cortex-M3 and Cortex-M4. * @param[in] *S points to an instance of the Q31 FIR decimator structure. * @param[in] *pSrc points to the block of input data. * @param[out] *pDst points to the block of output data * @param[in] blockSize number of input samples to process per call. * @return none */ void arm_fir_decimate_fast_q31( arm_fir_decimate_instance_q31 * S, q31_t * pSrc, q31_t * pDst, uint32_t blockSize); /** * @brief Initialization function for the Q31 FIR decimator. * @param[in,out] *S points to an instance of the Q31 FIR decimator structure. * @param[in] numTaps number of coefficients in the filter. * @param[in] M decimation factor. * @param[in] *pCoeffs points to the filter coefficients. * @param[in] *pState points to the state buffer. * @param[in] blockSize number of input samples to process per call. * @return The function returns ARM_MATH_SUCCESS if initialization is successful or ARM_MATH_LENGTH_ERROR if * blockSize is not a multiple of M. */ arm_status arm_fir_decimate_init_q31( arm_fir_decimate_instance_q31 * S, uint16_t numTaps, uint8_t M, q31_t * pCoeffs, q31_t * pState, uint32_t blockSize); /** * @brief Instance structure for the Q15 FIR interpolator. */ typedef struct { uint8_t L; /**< upsample factor. */ uint16_t phaseLength; /**< length of each polyphase filter component. */ q15_t *pCoeffs; /**< points to the coefficient array. The array is of length L*phaseLength. */ q15_t *pState; /**< points to the state variable array. The array is of length blockSize+phaseLength-1. */ } arm_fir_interpolate_instance_q15; /** * @brief Instance structure for the Q31 FIR interpolator. */ typedef struct { uint8_t L; /**< upsample factor. */ uint16_t phaseLength; /**< length of each polyphase filter component. */ q31_t *pCoeffs; /**< points to the coefficient array. The array is of length L*phaseLength. */ q31_t *pState; /**< points to the state variable array. The array is of length blockSize+phaseLength-1. */ } arm_fir_interpolate_instance_q31; /** * @brief Instance structure for the floating-point FIR interpolator. */ typedef struct { uint8_t L; /**< upsample factor. */ uint16_t phaseLength; /**< length of each polyphase filter component. */ float32_t *pCoeffs; /**< points to the coefficient array. The array is of length L*phaseLength. */ float32_t *pState; /**< points to the state variable array. The array is of length phaseLength+numTaps-1. */ } arm_fir_interpolate_instance_f32; /** * @brief Processing function for the Q15 FIR interpolator. * @param[in] *S points to an instance of the Q15 FIR interpolator structure. * @param[in] *pSrc points to the block of input data. * @param[out] *pDst points to the block of output data. * @param[in] blockSize number of input samples to process per call. * @return none. */ void arm_fir_interpolate_q15( const arm_fir_interpolate_instance_q15 * S, q15_t * pSrc, q15_t * pDst, uint32_t blockSize); /** * @brief Initialization function for the Q15 FIR interpolator. * @param[in,out] *S points to an instance of the Q15 FIR interpolator structure. * @param[in] L upsample factor. * @param[in] numTaps number of filter coefficients in the filter. * @param[in] *pCoeffs points to the filter coefficient buffer. * @param[in] *pState points to the state buffer. * @param[in] blockSize number of input samples to process per call. * @return The function returns ARM_MATH_SUCCESS if initialization is successful or ARM_MATH_LENGTH_ERROR if * the filter length numTaps is not a multiple of the interpolation factor L. */ arm_status arm_fir_interpolate_init_q15( arm_fir_interpolate_instance_q15 * S, uint8_t L, uint16_t numTaps, q15_t * pCoeffs, q15_t * pState, uint32_t blockSize); /** * @brief Processing function for the Q31 FIR interpolator. * @param[in] *S points to an instance of the Q15 FIR interpolator structure. * @param[in] *pSrc points to the block of input data. * @param[out] *pDst points to the block of output data. * @param[in] blockSize number of input samples to process per call. * @return none. */ void arm_fir_interpolate_q31( const arm_fir_interpolate_instance_q31 * S, q31_t * pSrc, q31_t * pDst, uint32_t blockSize); /** * @brief Initialization function for the Q31 FIR interpolator. * @param[in,out] *S points to an instance of the Q31 FIR interpolator structure. * @param[in] L upsample factor. * @param[in] numTaps number of filter coefficients in the filter. * @param[in] *pCoeffs points to the filter coefficient buffer. * @param[in] *pState points to the state buffer. * @param[in] blockSize number of input samples to process per call. * @return The function returns ARM_MATH_SUCCESS if initialization is successful or ARM_MATH_LENGTH_ERROR if * the filter length numTaps is not a multiple of the interpolation factor L. */ arm_status arm_fir_interpolate_init_q31( arm_fir_interpolate_instance_q31 * S, uint8_t L, uint16_t numTaps, q31_t * pCoeffs, q31_t * pState, uint32_t blockSize); /** * @brief Processing function for the floating-point FIR interpolator. * @param[in] *S points to an instance of the floating-point FIR interpolator structure. * @param[in] *pSrc points to the block of input data. * @param[out] *pDst points to the block of output data. * @param[in] blockSize number of input samples to process per call. * @return none. */ void arm_fir_interpolate_f32( const arm_fir_interpolate_instance_f32 * S, float32_t * pSrc, float32_t * pDst, uint32_t blockSize); /** * @brief Initialization function for the floating-point FIR interpolator. * @param[in,out] *S points to an instance of the floating-point FIR interpolator structure. * @param[in] L upsample factor. * @param[in] numTaps number of filter coefficients in the filter. * @param[in] *pCoeffs points to the filter coefficient buffer. * @param[in] *pState points to the state buffer. * @param[in] blockSize number of input samples to process per call. * @return The function returns ARM_MATH_SUCCESS if initialization is successful or ARM_MATH_LENGTH_ERROR if * the filter length numTaps is not a multiple of the interpolation factor L. */ arm_status arm_fir_interpolate_init_f32( arm_fir_interpolate_instance_f32 * S, uint8_t L, uint16_t numTaps, float32_t * pCoeffs, float32_t * pState, uint32_t blockSize); /** * @brief Instance structure for the high precision Q31 Biquad cascade filter. */ typedef struct { uint8_t numStages; /**< number of 2nd order stages in the filter. Overall order is 2*numStages. */ q63_t *pState; /**< points to the array of state coefficients. The array is of length 4*numStages. */ q31_t *pCoeffs; /**< points to the array of coefficients. The array is of length 5*numStages. */ uint8_t postShift; /**< additional shift, in bits, applied to each output sample. */ } arm_biquad_cas_df1_32x64_ins_q31; /** * @param[in] *S points to an instance of the high precision Q31 Biquad cascade filter structure. * @param[in] *pSrc points to the block of input data. * @param[out] *pDst points to the block of output data * @param[in] blockSize number of samples to process. * @return none. */ void arm_biquad_cas_df1_32x64_q31( const arm_biquad_cas_df1_32x64_ins_q31 * S, q31_t * pSrc, q31_t * pDst, uint32_t blockSize); /** * @param[in,out] *S points to an instance of the high precision Q31 Biquad cascade filter structure. * @param[in] numStages number of 2nd order stages in the filter. * @param[in] *pCoeffs points to the filter coefficients. * @param[in] *pState points to the state buffer. * @param[in] postShift shift to be applied to the output. Varies according to the coefficients format * @return none */ void arm_biquad_cas_df1_32x64_init_q31( arm_biquad_cas_df1_32x64_ins_q31 * S, uint8_t numStages, q31_t * pCoeffs, q63_t * pState, uint8_t postShift); /** * @brief Instance structure for the floating-point transposed direct form II Biquad cascade filter. */ typedef struct { uint8_t numStages; /**< number of 2nd order stages in the filter. Overall order is 2*numStages. */ float32_t *pState; /**< points to the array of state coefficients. The array is of length 2*numStages. */ float32_t *pCoeffs; /**< points to the array of coefficients. The array is of length 5*numStages. */ } arm_biquad_cascade_df2T_instance_f32; /** * @brief Instance structure for the floating-point transposed direct form II Biquad cascade filter. */ typedef struct { uint8_t numStages; /**< number of 2nd order stages in the filter. Overall order is 2*numStages. */ float32_t *pState; /**< points to the array of state coefficients. The array is of length 4*numStages. */ float32_t *pCoeffs; /**< points to the array of coefficients. The array is of length 5*numStages. */ } arm_biquad_cascade_stereo_df2T_instance_f32; /** * @brief Instance structure for the floating-point transposed direct form II Biquad cascade filter. */ typedef struct { uint8_t numStages; /**< number of 2nd order stages in the filter. Overall order is 2*numStages. */ float64_t *pState; /**< points to the array of state coefficients. The array is of length 2*numStages. */ float64_t *pCoeffs; /**< points to the array of coefficients. The array is of length 5*numStages. */ } arm_biquad_cascade_df2T_instance_f64; /** * @brief Processing function for the floating-point transposed direct form II Biquad cascade filter. * @param[in] *S points to an instance of the filter data structure. * @param[in] *pSrc points to the block of input data. * @param[out] *pDst points to the block of output data * @param[in] blockSize number of samples to process. * @return none. */ void arm_biquad_cascade_df2T_f32( const arm_biquad_cascade_df2T_instance_f32 * S, float32_t * pSrc, float32_t * pDst, uint32_t blockSize); /** * @brief Processing function for the floating-point transposed direct form II Biquad cascade filter. 2 channels * @param[in] *S points to an instance of the filter data structure. * @param[in] *pSrc points to the block of input data. * @param[out] *pDst points to the block of output data * @param[in] blockSize number of samples to process. * @return none. */ void arm_biquad_cascade_stereo_df2T_f32( const arm_biquad_cascade_stereo_df2T_instance_f32 * S, float32_t * pSrc, float32_t * pDst, uint32_t blockSize); /** * @brief Processing function for the floating-point transposed direct form II Biquad cascade filter. * @param[in] *S points to an instance of the filter data structure. * @param[in] *pSrc points to the block of input data. * @param[out] *pDst points to the block of output data * @param[in] blockSize number of samples to process. * @return none. */ void arm_biquad_cascade_df2T_f64( const arm_biquad_cascade_df2T_instance_f64 * S, float64_t * pSrc, float64_t * pDst, uint32_t blockSize); /** * @brief Initialization function for the floating-point transposed direct form II Biquad cascade filter. * @param[in,out] *S points to an instance of the filter data structure. * @param[in] numStages number of 2nd order stages in the filter. * @param[in] *pCoeffs points to the filter coefficients. * @param[in] *pState points to the state buffer. * @return none */ void arm_biquad_cascade_df2T_init_f32( arm_biquad_cascade_df2T_instance_f32 * S, uint8_t numStages, float32_t * pCoeffs, float32_t * pState); /** * @brief Initialization function for the floating-point transposed direct form II Biquad cascade filter. * @param[in,out] *S points to an instance of the filter data structure. * @param[in] numStages number of 2nd order stages in the filter. * @param[in] *pCoeffs points to the filter coefficients. * @param[in] *pState points to the state buffer. * @return none */ void arm_biquad_cascade_stereo_df2T_init_f32( arm_biquad_cascade_stereo_df2T_instance_f32 * S, uint8_t numStages, float32_t * pCoeffs, float32_t * pState); /** * @brief Initialization function for the floating-point transposed direct form II Biquad cascade filter. * @param[in,out] *S points to an instance of the filter data structure. * @param[in] numStages number of 2nd order stages in the filter. * @param[in] *pCoeffs points to the filter coefficients. * @param[in] *pState points to the state buffer. * @return none */ void arm_biquad_cascade_df2T_init_f64( arm_biquad_cascade_df2T_instance_f64 * S, uint8_t numStages, float64_t * pCoeffs, float64_t * pState); /** * @brief Instance structure for the Q15 FIR lattice filter. */ typedef struct { uint16_t numStages; /**< number of filter stages. */ q15_t *pState; /**< points to the state variable array. The array is of length numStages. */ q15_t *pCoeffs; /**< points to the coefficient array. The array is of length numStages. */ } arm_fir_lattice_instance_q15; /** * @brief Instance structure for the Q31 FIR lattice filter. */ typedef struct { uint16_t numStages; /**< number of filter stages. */ q31_t *pState; /**< points to the state variable array. The array is of length numStages. */ q31_t *pCoeffs; /**< points to the coefficient array. The array is of length numStages. */ } arm_fir_lattice_instance_q31; /** * @brief Instance structure for the floating-point FIR lattice filter. */ typedef struct { uint16_t numStages; /**< number of filter stages. */ float32_t *pState; /**< points to the state variable array. The array is of length numStages. */ float32_t *pCoeffs; /**< points to the coefficient array. The array is of length numStages. */ } arm_fir_lattice_instance_f32; /** * @brief Initialization function for the Q15 FIR lattice filter. * @param[in] *S points to an instance of the Q15 FIR lattice structure. * @param[in] numStages number of filter stages. * @param[in] *pCoeffs points to the coefficient buffer. The array is of length numStages. * @param[in] *pState points to the state buffer. The array is of length numStages. * @return none. */ void arm_fir_lattice_init_q15( arm_fir_lattice_instance_q15 * S, uint16_t numStages, q15_t * pCoeffs, q15_t * pState); /** * @brief Processing function for the Q15 FIR lattice filter. * @param[in] *S points to an instance of the Q15 FIR lattice structure. * @param[in] *pSrc points to the block of input data. * @param[out] *pDst points to the block of output data. * @param[in] blockSize number of samples to process. * @return none. */ void arm_fir_lattice_q15( const arm_fir_lattice_instance_q15 * S, q15_t * pSrc, q15_t * pDst, uint32_t blockSize); /** * @brief Initialization function for the Q31 FIR lattice filter. * @param[in] *S points to an instance of the Q31 FIR lattice structure. * @param[in] numStages number of filter stages. * @param[in] *pCoeffs points to the coefficient buffer. The array is of length numStages. * @param[in] *pState points to the state buffer. The array is of length numStages. * @return none. */ void arm_fir_lattice_init_q31( arm_fir_lattice_instance_q31 * S, uint16_t numStages, q31_t * pCoeffs, q31_t * pState); /** * @brief Processing function for the Q31 FIR lattice filter. * @param[in] *S points to an instance of the Q31 FIR lattice structure. * @param[in] *pSrc points to the block of input data. * @param[out] *pDst points to the block of output data * @param[in] blockSize number of samples to process. * @return none. */ void arm_fir_lattice_q31( const arm_fir_lattice_instance_q31 * S, q31_t * pSrc, q31_t * pDst, uint32_t blockSize); /** * @brief Initialization function for the floating-point FIR lattice filter. * @param[in] *S points to an instance of the floating-point FIR lattice structure. * @param[in] numStages number of filter stages. * @param[in] *pCoeffs points to the coefficient buffer. The array is of length numStages. * @param[in] *pState points to the state buffer. The array is of length numStages. * @return none. */ void arm_fir_lattice_init_f32( arm_fir_lattice_instance_f32 * S, uint16_t numStages, float32_t * pCoeffs, float32_t * pState); /** * @brief Processing function for the floating-point FIR lattice filter. * @param[in] *S points to an instance of the floating-point FIR lattice structure. * @param[in] *pSrc points to the block of input data. * @param[out] *pDst points to the block of output data * @param[in] blockSize number of samples to process. * @return none. */ void arm_fir_lattice_f32( const arm_fir_lattice_instance_f32 * S, float32_t * pSrc, float32_t * pDst, uint32_t blockSize); /** * @brief Instance structure for the Q15 IIR lattice filter. */ typedef struct { uint16_t numStages; /**< number of stages in the filter. */ q15_t *pState; /**< points to the state variable array. The array is of length numStages+blockSize. */ q15_t *pkCoeffs; /**< points to the reflection coefficient array. The array is of length numStages. */ q15_t *pvCoeffs; /**< points to the ladder coefficient array. The array is of length numStages+1. */ } arm_iir_lattice_instance_q15; /** * @brief Instance structure for the Q31 IIR lattice filter. */ typedef struct { uint16_t numStages; /**< number of stages in the filter. */ q31_t *pState; /**< points to the state variable array. The array is of length numStages+blockSize. */ q31_t *pkCoeffs; /**< points to the reflection coefficient array. The array is of length numStages. */ q31_t *pvCoeffs; /**< points to the ladder coefficient array. The array is of length numStages+1. */ } arm_iir_lattice_instance_q31; /** * @brief Instance structure for the floating-point IIR lattice filter. */ typedef struct { uint16_t numStages; /**< number of stages in the filter. */ float32_t *pState; /**< points to the state variable array. The array is of length numStages+blockSize. */ float32_t *pkCoeffs; /**< points to the reflection coefficient array. The array is of length numStages. */ float32_t *pvCoeffs; /**< points to the ladder coefficient array. The array is of length numStages+1. */ } arm_iir_lattice_instance_f32; /** * @brief Processing function for the floating-point IIR lattice filter. * @param[in] *S points to an instance of the floating-point IIR lattice structure. * @param[in] *pSrc points to the block of input data. * @param[out] *pDst points to the block of output data. * @param[in] blockSize number of samples to process. * @return none. */ void arm_iir_lattice_f32( const arm_iir_lattice_instance_f32 * S, float32_t * pSrc, float32_t * pDst, uint32_t blockSize); /** * @brief Initialization function for the floating-point IIR lattice filter. * @param[in] *S points to an instance of the floating-point IIR lattice structure. * @param[in] numStages number of stages in the filter. * @param[in] *pkCoeffs points to the reflection coefficient buffer. The array is of length numStages. * @param[in] *pvCoeffs points to the ladder coefficient buffer. The array is of length numStages+1. * @param[in] *pState points to the state buffer. The array is of length numStages+blockSize-1. * @param[in] blockSize number of samples to process. * @return none. */ void arm_iir_lattice_init_f32( arm_iir_lattice_instance_f32 * S, uint16_t numStages, float32_t * pkCoeffs, float32_t * pvCoeffs, float32_t * pState, uint32_t blockSize); /** * @brief Processing function for the Q31 IIR lattice filter. * @param[in] *S points to an instance of the Q31 IIR lattice structure. * @param[in] *pSrc points to the block of input data. * @param[out] *pDst points to the block of output data. * @param[in] blockSize number of samples to process. * @return none. */ void arm_iir_lattice_q31( const arm_iir_lattice_instance_q31 * S, q31_t * pSrc, q31_t * pDst, uint32_t blockSize); /** * @brief Initialization function for the Q31 IIR lattice filter. * @param[in] *S points to an instance of the Q31 IIR lattice structure. * @param[in] numStages number of stages in the filter. * @param[in] *pkCoeffs points to the reflection coefficient buffer. The array is of length numStages. * @param[in] *pvCoeffs points to the ladder coefficient buffer. The array is of length numStages+1. * @param[in] *pState points to the state buffer. The array is of length numStages+blockSize. * @param[in] blockSize number of samples to process. * @return none. */ void arm_iir_lattice_init_q31( arm_iir_lattice_instance_q31 * S, uint16_t numStages, q31_t * pkCoeffs, q31_t * pvCoeffs, q31_t * pState, uint32_t blockSize); /** * @brief Processing function for the Q15 IIR lattice filter. * @param[in] *S points to an instance of the Q15 IIR lattice structure. * @param[in] *pSrc points to the block of input data. * @param[out] *pDst points to the block of output data. * @param[in] blockSize number of samples to process. * @return none. */ void arm_iir_lattice_q15( const arm_iir_lattice_instance_q15 * S, q15_t * pSrc, q15_t * pDst, uint32_t blockSize); /** * @brief Initialization function for the Q15 IIR lattice filter. * @param[in] *S points to an instance of the fixed-point Q15 IIR lattice structure. * @param[in] numStages number of stages in the filter. * @param[in] *pkCoeffs points to reflection coefficient buffer. The array is of length numStages. * @param[in] *pvCoeffs points to ladder coefficient buffer. The array is of length numStages+1. * @param[in] *pState points to state buffer. The array is of length numStages+blockSize. * @param[in] blockSize number of samples to process per call. * @return none. */ void arm_iir_lattice_init_q15( arm_iir_lattice_instance_q15 * S, uint16_t numStages, q15_t * pkCoeffs, q15_t * pvCoeffs, q15_t * pState, uint32_t blockSize); /** * @brief Instance structure for the floating-point LMS filter. */ typedef struct { uint16_t numTaps; /**< number of coefficients in the filter. */ float32_t *pState; /**< points to the state variable array. The array is of length numTaps+blockSize-1. */ float32_t *pCoeffs; /**< points to the coefficient array. The array is of length numTaps. */ float32_t mu; /**< step size that controls filter coefficient updates. */ } arm_lms_instance_f32; /** * @brief Processing function for floating-point LMS filter. * @param[in] *S points to an instance of the floating-point LMS filter structure. * @param[in] *pSrc points to the block of input data. * @param[in] *pRef points to the block of reference data. * @param[out] *pOut points to the block of output data. * @param[out] *pErr points to the block of error data. * @param[in] blockSize number of samples to process. * @return none. */ void arm_lms_f32( const arm_lms_instance_f32 * S, float32_t * pSrc, float32_t * pRef, float32_t * pOut, float32_t * pErr, uint32_t blockSize); /** * @brief Initialization function for floating-point LMS filter. * @param[in] *S points to an instance of the floating-point LMS filter structure. * @param[in] numTaps number of filter coefficients. * @param[in] *pCoeffs points to the coefficient buffer. * @param[in] *pState points to state buffer. * @param[in] mu step size that controls filter coefficient updates. * @param[in] blockSize number of samples to process. * @return none. */ void arm_lms_init_f32( arm_lms_instance_f32 * S, uint16_t numTaps, float32_t * pCoeffs, float32_t * pState, float32_t mu, uint32_t blockSize); /** * @brief Instance structure for the Q15 LMS filter. */ typedef struct { uint16_t numTaps; /**< number of coefficients in the filter. */ q15_t *pState; /**< points to the state variable array. The array is of length numTaps+blockSize-1. */ q15_t *pCoeffs; /**< points to the coefficient array. The array is of length numTaps. */ q15_t mu; /**< step size that controls filter coefficient updates. */ uint32_t postShift; /**< bit shift applied to coefficients. */ } arm_lms_instance_q15; /** * @brief Initialization function for the Q15 LMS filter. * @param[in] *S points to an instance of the Q15 LMS filter structure. * @param[in] numTaps number of filter coefficients. * @param[in] *pCoeffs points to the coefficient buffer. * @param[in] *pState points to the state buffer. * @param[in] mu step size that controls filter coefficient updates. * @param[in] blockSize number of samples to process. * @param[in] postShift bit shift applied to coefficients. * @return none. */ void arm_lms_init_q15( arm_lms_instance_q15 * S, uint16_t numTaps, q15_t * pCoeffs, q15_t * pState, q15_t mu, uint32_t blockSize, uint32_t postShift); /** * @brief Processing function for Q15 LMS filter. * @param[in] *S points to an instance of the Q15 LMS filter structure. * @param[in] *pSrc points to the block of input data. * @param[in] *pRef points to the block of reference data. * @param[out] *pOut points to the block of output data. * @param[out] *pErr points to the block of error data. * @param[in] blockSize number of samples to process. * @return none. */ void arm_lms_q15( const arm_lms_instance_q15 * S, q15_t * pSrc, q15_t * pRef, q15_t * pOut, q15_t * pErr, uint32_t blockSize); /** * @brief Instance structure for the Q31 LMS filter. */ typedef struct { uint16_t numTaps; /**< number of coefficients in the filter. */ q31_t *pState; /**< points to the state variable array. The array is of length numTaps+blockSize-1. */ q31_t *pCoeffs; /**< points to the coefficient array. The array is of length numTaps. */ q31_t mu; /**< step size that controls filter coefficient updates. */ uint32_t postShift; /**< bit shift applied to coefficients. */ } arm_lms_instance_q31; /** * @brief Processing function for Q31 LMS filter. * @param[in] *S points to an instance of the Q15 LMS filter structure. * @param[in] *pSrc points to the block of input data. * @param[in] *pRef points to the block of reference data. * @param[out] *pOut points to the block of output data. * @param[out] *pErr points to the block of error data. * @param[in] blockSize number of samples to process. * @return none. */ void arm_lms_q31( const arm_lms_instance_q31 * S, q31_t * pSrc, q31_t * pRef, q31_t * pOut, q31_t * pErr, uint32_t blockSize); /** * @brief Initialization function for Q31 LMS filter. * @param[in] *S points to an instance of the Q31 LMS filter structure. * @param[in] numTaps number of filter coefficients. * @param[in] *pCoeffs points to coefficient buffer. * @param[in] *pState points to state buffer. * @param[in] mu step size that controls filter coefficient updates. * @param[in] blockSize number of samples to process. * @param[in] postShift bit shift applied to coefficients. * @return none. */ void arm_lms_init_q31( arm_lms_instance_q31 * S, uint16_t numTaps, q31_t * pCoeffs, q31_t * pState, q31_t mu, uint32_t blockSize, uint32_t postShift); /** * @brief Instance structure for the floating-point normalized LMS filter. */ typedef struct { uint16_t numTaps; /**< number of coefficients in the filter. */ float32_t *pState; /**< points to the state variable array. The array is of length numTaps+blockSize-1. */ float32_t *pCoeffs; /**< points to the coefficient array. The array is of length numTaps. */ float32_t mu; /**< step size that control filter coefficient updates. */ float32_t energy; /**< saves previous frame energy. */ float32_t x0; /**< saves previous input sample. */ } arm_lms_norm_instance_f32; /** * @brief Processing function for floating-point normalized LMS filter. * @param[in] *S points to an instance of the floating-point normalized LMS filter structure. * @param[in] *pSrc points to the block of input data. * @param[in] *pRef points to the block of reference data. * @param[out] *pOut points to the block of output data. * @param[out] *pErr points to the block of error data. * @param[in] blockSize number of samples to process. * @return none. */ void arm_lms_norm_f32( arm_lms_norm_instance_f32 * S, float32_t * pSrc, float32_t * pRef, float32_t * pOut, float32_t * pErr, uint32_t blockSize); /** * @brief Initialization function for floating-point normalized LMS filter. * @param[in] *S points to an instance of the floating-point LMS filter structure. * @param[in] numTaps number of filter coefficients. * @param[in] *pCoeffs points to coefficient buffer. * @param[in] *pState points to state buffer. * @param[in] mu step size that controls filter coefficient updates. * @param[in] blockSize number of samples to process. * @return none. */ void arm_lms_norm_init_f32( arm_lms_norm_instance_f32 * S, uint16_t numTaps, float32_t * pCoeffs, float32_t * pState, float32_t mu, uint32_t blockSize); /** * @brief Instance structure for the Q31 normalized LMS filter. */ typedef struct { uint16_t numTaps; /**< number of coefficients in the filter. */ q31_t *pState; /**< points to the state variable array. The array is of length numTaps+blockSize-1. */ q31_t *pCoeffs; /**< points to the coefficient array. The array is of length numTaps. */ q31_t mu; /**< step size that controls filter coefficient updates. */ uint8_t postShift; /**< bit shift applied to coefficients. */ q31_t *recipTable; /**< points to the reciprocal initial value table. */ q31_t energy; /**< saves previous frame energy. */ q31_t x0; /**< saves previous input sample. */ } arm_lms_norm_instance_q31; /** * @brief Processing function for Q31 normalized LMS filter. * @param[in] *S points to an instance of the Q31 normalized LMS filter structure. * @param[in] *pSrc points to the block of input data. * @param[in] *pRef points to the block of reference data. * @param[out] *pOut points to the block of output data. * @param[out] *pErr points to the block of error data. * @param[in] blockSize number of samples to process. * @return none. */ void arm_lms_norm_q31( arm_lms_norm_instance_q31 * S, q31_t * pSrc, q31_t * pRef, q31_t * pOut, q31_t * pErr, uint32_t blockSize); /** * @brief Initialization function for Q31 normalized LMS filter. * @param[in] *S points to an instance of the Q31 normalized LMS filter structure. * @param[in] numTaps number of filter coefficients. * @param[in] *pCoeffs points to coefficient buffer. * @param[in] *pState points to state buffer. * @param[in] mu step size that controls filter coefficient updates. * @param[in] blockSize number of samples to process. * @param[in] postShift bit shift applied to coefficients. * @return none. */ void arm_lms_norm_init_q31( arm_lms_norm_instance_q31 * S, uint16_t numTaps, q31_t * pCoeffs, q31_t * pState, q31_t mu, uint32_t blockSize, uint8_t postShift); /** * @brief Instance structure for the Q15 normalized LMS filter. */ typedef struct { uint16_t numTaps; /**< Number of coefficients in the filter. */ q15_t *pState; /**< points to the state variable array. The array is of length numTaps+blockSize-1. */ q15_t *pCoeffs; /**< points to the coefficient array. The array is of length numTaps. */ q15_t mu; /**< step size that controls filter coefficient updates. */ uint8_t postShift; /**< bit shift applied to coefficients. */ q15_t *recipTable; /**< Points to the reciprocal initial value table. */ q15_t energy; /**< saves previous frame energy. */ q15_t x0; /**< saves previous input sample. */ } arm_lms_norm_instance_q15; /** * @brief Processing function for Q15 normalized LMS filter. * @param[in] *S points to an instance of the Q15 normalized LMS filter structure. * @param[in] *pSrc points to the block of input data. * @param[in] *pRef points to the block of reference data. * @param[out] *pOut points to the block of output data. * @param[out] *pErr points to the block of error data. * @param[in] blockSize number of samples to process. * @return none. */ void arm_lms_norm_q15( arm_lms_norm_instance_q15 * S, q15_t * pSrc, q15_t * pRef, q15_t * pOut, q15_t * pErr, uint32_t blockSize); /** * @brief Initialization function for Q15 normalized LMS filter. * @param[in] *S points to an instance of the Q15 normalized LMS filter structure. * @param[in] numTaps number of filter coefficients. * @param[in] *pCoeffs points to coefficient buffer. * @param[in] *pState points to state buffer. * @param[in] mu step size that controls filter coefficient updates. * @param[in] blockSize number of samples to process. * @param[in] postShift bit shift applied to coefficients. * @return none. */ void arm_lms_norm_init_q15( arm_lms_norm_instance_q15 * S, uint16_t numTaps, q15_t * pCoeffs, q15_t * pState, q15_t mu, uint32_t blockSize, uint8_t postShift); /** * @brief Correlation of floating-point sequences. * @param[in] *pSrcA points to the first input sequence. * @param[in] srcALen length of the first input sequence. * @param[in] *pSrcB points to the second input sequence. * @param[in] srcBLen length of the second input sequence. * @param[out] *pDst points to the block of output data Length 2 * max(srcALen, srcBLen) - 1. * @return none. */ void arm_correlate_f32( float32_t * pSrcA, uint32_t srcALen, float32_t * pSrcB, uint32_t srcBLen, float32_t * pDst); /** * @brief Correlation of Q15 sequences * @param[in] *pSrcA points to the first input sequence. * @param[in] srcALen length of the first input sequence. * @param[in] *pSrcB points to the second input sequence. * @param[in] srcBLen length of the second input sequence. * @param[out] *pDst points to the block of output data Length 2 * max(srcALen, srcBLen) - 1. * @param[in] *pScratch points to scratch buffer of size max(srcALen, srcBLen) + 2*min(srcALen, srcBLen) - 2. * @return none. */ void arm_correlate_opt_q15( q15_t * pSrcA, uint32_t srcALen, q15_t * pSrcB, uint32_t srcBLen, q15_t * pDst, q15_t * pScratch); /** * @brief Correlation of Q15 sequences. * @param[in] *pSrcA points to the first input sequence. * @param[in] srcALen length of the first input sequence. * @param[in] *pSrcB points to the second input sequence. * @param[in] srcBLen length of the second input sequence. * @param[out] *pDst points to the block of output data Length 2 * max(srcALen, srcBLen) - 1. * @return none. */ void arm_correlate_q15( q15_t * pSrcA, uint32_t srcALen, q15_t * pSrcB, uint32_t srcBLen, q15_t * pDst); /** * @brief Correlation of Q15 sequences (fast version) for Cortex-M3 and Cortex-M4. * @param[in] *pSrcA points to the first input sequence. * @param[in] srcALen length of the first input sequence. * @param[in] *pSrcB points to the second input sequence. * @param[in] srcBLen length of the second input sequence. * @param[out] *pDst points to the block of output data Length 2 * max(srcALen, srcBLen) - 1. * @return none. */ void arm_correlate_fast_q15( q15_t * pSrcA, uint32_t srcALen, q15_t * pSrcB, uint32_t srcBLen, q15_t * pDst); /** * @brief Correlation of Q15 sequences (fast version) for Cortex-M3 and Cortex-M4. * @param[in] *pSrcA points to the first input sequence. * @param[in] srcALen length of the first input sequence. * @param[in] *pSrcB points to the second input sequence. * @param[in] srcBLen length of the second input sequence. * @param[out] *pDst points to the block of output data Length 2 * max(srcALen, srcBLen) - 1. * @param[in] *pScratch points to scratch buffer of size max(srcALen, srcBLen) + 2*min(srcALen, srcBLen) - 2. * @return none. */ void arm_correlate_fast_opt_q15( q15_t * pSrcA, uint32_t srcALen, q15_t * pSrcB, uint32_t srcBLen, q15_t * pDst, q15_t * pScratch); /** * @brief Correlation of Q31 sequences. * @param[in] *pSrcA points to the first input sequence. * @param[in] srcALen length of the first input sequence. * @param[in] *pSrcB points to the second input sequence. * @param[in] srcBLen length of the second input sequence. * @param[out] *pDst points to the block of output data Length 2 * max(srcALen, srcBLen) - 1. * @return none. */ void arm_correlate_q31( q31_t * pSrcA, uint32_t srcALen, q31_t * pSrcB, uint32_t srcBLen, q31_t * pDst); /** * @brief Correlation of Q31 sequences (fast version) for Cortex-M3 and Cortex-M4 * @param[in] *pSrcA points to the first input sequence. * @param[in] srcALen length of the first input sequence. * @param[in] *pSrcB points to the second input sequence. * @param[in] srcBLen length of the second input sequence. * @param[out] *pDst points to the block of output data Length 2 * max(srcALen, srcBLen) - 1. * @return none. */ void arm_correlate_fast_q31( q31_t * pSrcA, uint32_t srcALen, q31_t * pSrcB, uint32_t srcBLen, q31_t * pDst); /** * @brief Correlation of Q7 sequences. * @param[in] *pSrcA points to the first input sequence. * @param[in] srcALen length of the first input sequence. * @param[in] *pSrcB points to the second input sequence. * @param[in] srcBLen length of the second input sequence. * @param[out] *pDst points to the block of output data Length 2 * max(srcALen, srcBLen) - 1. * @param[in] *pScratch1 points to scratch buffer(of type q15_t) of size max(srcALen, srcBLen) + 2*min(srcALen, srcBLen) - 2. * @param[in] *pScratch2 points to scratch buffer (of type q15_t) of size min(srcALen, srcBLen). * @return none. */ void arm_correlate_opt_q7( q7_t * pSrcA, uint32_t srcALen, q7_t * pSrcB, uint32_t srcBLen, q7_t * pDst, q15_t * pScratch1, q15_t * pScratch2); /** * @brief Correlation of Q7 sequences. * @param[in] *pSrcA points to the first input sequence. * @param[in] srcALen length of the first input sequence. * @param[in] *pSrcB points to the second input sequence. * @param[in] srcBLen length of the second input sequence. * @param[out] *pDst points to the block of output data Length 2 * max(srcALen, srcBLen) - 1. * @return none. */ void arm_correlate_q7( q7_t * pSrcA, uint32_t srcALen, q7_t * pSrcB, uint32_t srcBLen, q7_t * pDst); /** * @brief Instance structure for the floating-point sparse FIR filter. */ typedef struct { uint16_t numTaps; /**< number of coefficients in the filter. */ uint16_t stateIndex; /**< state buffer index. Points to the oldest sample in the state buffer. */ float32_t *pState; /**< points to the state buffer array. The array is of length maxDelay+blockSize-1. */ float32_t *pCoeffs; /**< points to the coefficient array. The array is of length numTaps.*/ uint16_t maxDelay; /**< maximum offset specified by the pTapDelay array. */ int32_t *pTapDelay; /**< points to the array of delay values. The array is of length numTaps. */ } arm_fir_sparse_instance_f32; /** * @brief Instance structure for the Q31 sparse FIR filter. */ typedef struct { uint16_t numTaps; /**< number of coefficients in the filter. */ uint16_t stateIndex; /**< state buffer index. Points to the oldest sample in the state buffer. */ q31_t *pState; /**< points to the state buffer array. The array is of length maxDelay+blockSize-1. */ q31_t *pCoeffs; /**< points to the coefficient array. The array is of length numTaps.*/ uint16_t maxDelay; /**< maximum offset specified by the pTapDelay array. */ int32_t *pTapDelay; /**< points to the array of delay values. The array is of length numTaps. */ } arm_fir_sparse_instance_q31; /** * @brief Instance structure for the Q15 sparse FIR filter. */ typedef struct { uint16_t numTaps; /**< number of coefficients in the filter. */ uint16_t stateIndex; /**< state buffer index. Points to the oldest sample in the state buffer. */ q15_t *pState; /**< points to the state buffer array. The array is of length maxDelay+blockSize-1. */ q15_t *pCoeffs; /**< points to the coefficient array. The array is of length numTaps.*/ uint16_t maxDelay; /**< maximum offset specified by the pTapDelay array. */ int32_t *pTapDelay; /**< points to the array of delay values. The array is of length numTaps. */ } arm_fir_sparse_instance_q15; /** * @brief Instance structure for the Q7 sparse FIR filter. */ typedef struct { uint16_t numTaps; /**< number of coefficients in the filter. */ uint16_t stateIndex; /**< state buffer index. Points to the oldest sample in the state buffer. */ q7_t *pState; /**< points to the state buffer array. The array is of length maxDelay+blockSize-1. */ q7_t *pCoeffs; /**< points to the coefficient array. The array is of length numTaps.*/ uint16_t maxDelay; /**< maximum offset specified by the pTapDelay array. */ int32_t *pTapDelay; /**< points to the array of delay values. The array is of length numTaps. */ } arm_fir_sparse_instance_q7; /** * @brief Processing function for the floating-point sparse FIR filter. * @param[in] *S points to an instance of the floating-point sparse FIR structure. * @param[in] *pSrc points to the block of input data. * @param[out] *pDst points to the block of output data * @param[in] *pScratchIn points to a temporary buffer of size blockSize. * @param[in] blockSize number of input samples to process per call. * @return none. */ void arm_fir_sparse_f32( arm_fir_sparse_instance_f32 * S, float32_t * pSrc, float32_t * pDst, float32_t * pScratchIn, uint32_t blockSize); /** * @brief Initialization function for the floating-point sparse FIR filter. * @param[in,out] *S points to an instance of the floating-point sparse FIR structure. * @param[in] numTaps number of nonzero coefficients in the filter. * @param[in] *pCoeffs points to the array of filter coefficients. * @param[in] *pState points to the state buffer. * @param[in] *pTapDelay points to the array of offset times. * @param[in] maxDelay maximum offset time supported. * @param[in] blockSize number of samples that will be processed per block. * @return none */ void arm_fir_sparse_init_f32( arm_fir_sparse_instance_f32 * S, uint16_t numTaps, float32_t * pCoeffs, float32_t * pState, int32_t * pTapDelay, uint16_t maxDelay, uint32_t blockSize); /** * @brief Processing function for the Q31 sparse FIR filter. * @param[in] *S points to an instance of the Q31 sparse FIR structure. * @param[in] *pSrc points to the block of input data. * @param[out] *pDst points to the block of output data * @param[in] *pScratchIn points to a temporary buffer of size blockSize. * @param[in] blockSize number of input samples to process per call. * @return none. */ void arm_fir_sparse_q31( arm_fir_sparse_instance_q31 * S, q31_t * pSrc, q31_t * pDst, q31_t * pScratchIn, uint32_t blockSize); /** * @brief Initialization function for the Q31 sparse FIR filter. * @param[in,out] *S points to an instance of the Q31 sparse FIR structure. * @param[in] numTaps number of nonzero coefficients in the filter. * @param[in] *pCoeffs points to the array of filter coefficients. * @param[in] *pState points to the state buffer. * @param[in] *pTapDelay points to the array of offset times. * @param[in] maxDelay maximum offset time supported. * @param[in] blockSize number of samples that will be processed per block. * @return none */ void arm_fir_sparse_init_q31( arm_fir_sparse_instance_q31 * S, uint16_t numTaps, q31_t * pCoeffs, q31_t * pState, int32_t * pTapDelay, uint16_t maxDelay, uint32_t blockSize); /** * @brief Processing function for the Q15 sparse FIR filter. * @param[in] *S points to an instance of the Q15 sparse FIR structure. * @param[in] *pSrc points to the block of input data. * @param[out] *pDst points to the block of output data * @param[in] *pScratchIn points to a temporary buffer of size blockSize. * @param[in] *pScratchOut points to a temporary buffer of size blockSize. * @param[in] blockSize number of input samples to process per call. * @return none. */ void arm_fir_sparse_q15( arm_fir_sparse_instance_q15 * S, q15_t * pSrc, q15_t * pDst, q15_t * pScratchIn, q31_t * pScratchOut, uint32_t blockSize); /** * @brief Initialization function for the Q15 sparse FIR filter. * @param[in,out] *S points to an instance of the Q15 sparse FIR structure. * @param[in] numTaps number of nonzero coefficients in the filter. * @param[in] *pCoeffs points to the array of filter coefficients. * @param[in] *pState points to the state buffer. * @param[in] *pTapDelay points to the array of offset times. * @param[in] maxDelay maximum offset time supported. * @param[in] blockSize number of samples that will be processed per block. * @return none */ void arm_fir_sparse_init_q15( arm_fir_sparse_instance_q15 * S, uint16_t numTaps, q15_t * pCoeffs, q15_t * pState, int32_t * pTapDelay, uint16_t maxDelay, uint32_t blockSize); /** * @brief Processing function for the Q7 sparse FIR filter. * @param[in] *S points to an instance of the Q7 sparse FIR structure. * @param[in] *pSrc points to the block of input data. * @param[out] *pDst points to the block of output data * @param[in] *pScratchIn points to a temporary buffer of size blockSize. * @param[in] *pScratchOut points to a temporary buffer of size blockSize. * @param[in] blockSize number of input samples to process per call. * @return none. */ void arm_fir_sparse_q7( arm_fir_sparse_instance_q7 * S, q7_t * pSrc, q7_t * pDst, q7_t * pScratchIn, q31_t * pScratchOut, uint32_t blockSize); /** * @brief Initialization function for the Q7 sparse FIR filter. * @param[in,out] *S points to an instance of the Q7 sparse FIR structure. * @param[in] numTaps number of nonzero coefficients in the filter. * @param[in] *pCoeffs points to the array of filter coefficients. * @param[in] *pState points to the state buffer. * @param[in] *pTapDelay points to the array of offset times. * @param[in] maxDelay maximum offset time supported. * @param[in] blockSize number of samples that will be processed per block. * @return none */ void arm_fir_sparse_init_q7( arm_fir_sparse_instance_q7 * S, uint16_t numTaps, q7_t * pCoeffs, q7_t * pState, int32_t * pTapDelay, uint16_t maxDelay, uint32_t blockSize); /* * @brief Floating-point sin_cos function. * @param[in] theta input value in degrees * @param[out] *pSinVal points to the processed sine output. * @param[out] *pCosVal points to the processed cos output. * @return none. */ void arm_sin_cos_f32( float32_t theta, float32_t * pSinVal, float32_t * pCcosVal); /* * @brief Q31 sin_cos function. * @param[in] theta scaled input value in degrees * @param[out] *pSinVal points to the processed sine output. * @param[out] *pCosVal points to the processed cosine output. * @return none. */ void arm_sin_cos_q31( q31_t theta, q31_t * pSinVal, q31_t * pCosVal); /** * @brief Floating-point complex conjugate. * @param[in] *pSrc points to the input vector * @param[out] *pDst points to the output vector * @param[in] numSamples number of complex samples in each vector * @return none. */ void arm_cmplx_conj_f32( float32_t * pSrc, float32_t * pDst, uint32_t numSamples); /** * @brief Q31 complex conjugate. * @param[in] *pSrc points to the input vector * @param[out] *pDst points to the output vector * @param[in] numSamples number of complex samples in each vector * @return none. */ void arm_cmplx_conj_q31( q31_t * pSrc, q31_t * pDst, uint32_t numSamples); /** * @brief Q15 complex conjugate. * @param[in] *pSrc points to the input vector * @param[out] *pDst points to the output vector * @param[in] numSamples number of complex samples in each vector * @return none. */ void arm_cmplx_conj_q15( q15_t * pSrc, q15_t * pDst, uint32_t numSamples); /** * @brief Floating-point complex magnitude squared * @param[in] *pSrc points to the complex input vector * @param[out] *pDst points to the real output vector * @param[in] numSamples number of complex samples in the input vector * @return none. */ void arm_cmplx_mag_squared_f32( float32_t * pSrc, float32_t * pDst, uint32_t numSamples); /** * @brief Q31 complex magnitude squared * @param[in] *pSrc points to the complex input vector * @param[out] *pDst points to the real output vector * @param[in] numSamples number of complex samples in the input vector * @return none. */ void arm_cmplx_mag_squared_q31( q31_t * pSrc, q31_t * pDst, uint32_t numSamples); /** * @brief Q15 complex magnitude squared * @param[in] *pSrc points to the complex input vector * @param[out] *pDst points to the real output vector * @param[in] numSamples number of complex samples in the input vector * @return none. */ void arm_cmplx_mag_squared_q15( q15_t * pSrc, q15_t * pDst, uint32_t numSamples); /** * @ingroup groupController */ /** * @defgroup PID PID Motor Control * * A Proportional Integral Derivative (PID) controller is a generic feedback control * loop mechanism widely used in industrial control systems. * A PID controller is the most commonly used type of feedback controller. * * This set of functions implements (PID) controllers * for Q15, Q31, and floating-point data types. The functions operate on a single sample * of data and each call to the function returns a single processed value. * S points to an instance of the PID control data structure. in * is the input sample value. The functions return the output value. * * \par Algorithm: *
   *    y[n] = y[n-1] + A0 * x[n] + A1 * x[n-1] + A2 * x[n-2]
   *    A0 = Kp + Ki + Kd
   *    A1 = (-Kp ) - (2 * Kd )
   *    A2 = Kd  
* * \par * where \c Kp is proportional constant, \c Ki is Integral constant and \c Kd is Derivative constant * * \par * \image html PID.gif "Proportional Integral Derivative Controller" * * \par * The PID controller calculates an "error" value as the difference between * the measured output and the reference input. * The controller attempts to minimize the error by adjusting the process control inputs. * The proportional value determines the reaction to the current error, * the integral value determines the reaction based on the sum of recent errors, * and the derivative value determines the reaction based on the rate at which the error has been changing. * * \par Instance Structure * The Gains A0, A1, A2 and state variables for a PID controller are stored together in an instance data structure. * A separate instance structure must be defined for each PID Controller. * There are separate instance structure declarations for each of the 3 supported data types. * * \par Reset Functions * There is also an associated reset function for each data type which clears the state array. * * \par Initialization Functions * There is also an associated initialization function for each data type. * The initialization function performs the following operations: * - Initializes the Gains A0, A1, A2 from Kp,Ki, Kd gains. * - Zeros out the values in the state buffer. * * \par * Instance structure cannot be placed into a const data section and it is recommended to use the initialization function. * * \par Fixed-Point Behavior * Care must be taken when using the fixed-point versions of the PID Controller functions. * In particular, the overflow and saturation behavior of the accumulator used in each function must be considered. * Refer to the function specific documentation below for usage guidelines. */ /** * @addtogroup PID * @{ */ /** * @brief Process function for the floating-point PID Control. * @param[in,out] *S is an instance of the floating-point PID Control structure * @param[in] in input sample to process * @return out processed output sample. */ static __INLINE float32_t arm_pid_f32( arm_pid_instance_f32 * S, float32_t in) { float32_t out; /* y[n] = y[n-1] + A0 * x[n] + A1 * x[n-1] + A2 * x[n-2] */ out = (S->A0 * in) + (S->A1 * S->state[0]) + (S->A2 * S->state[1]) + (S->state[2]); /* Update state */ S->state[1] = S->state[0]; S->state[0] = in; S->state[2] = out; /* return to application */ return (out); } /** * @brief Process function for the Q31 PID Control. * @param[in,out] *S points to an instance of the Q31 PID Control structure * @param[in] in input sample to process * @return out processed output sample. * * Scaling and Overflow Behavior: * \par * The function is implemented using an internal 64-bit accumulator. * The accumulator has a 2.62 format and maintains full precision of the intermediate multiplication results but provides only a single guard bit. * Thus, if the accumulator result overflows it wraps around rather than clip. * In order to avoid overflows completely the input signal must be scaled down by 2 bits as there are four additions. * After all multiply-accumulates are performed, the 2.62 accumulator is truncated to 1.32 format and then saturated to 1.31 format. */ static __INLINE q31_t arm_pid_q31( arm_pid_instance_q31 * S, q31_t in) { q63_t acc; q31_t out; /* acc = A0 * x[n] */ acc = (q63_t) S->A0 * in; /* acc += A1 * x[n-1] */ acc += (q63_t) S->A1 * S->state[0]; /* acc += A2 * x[n-2] */ acc += (q63_t) S->A2 * S->state[1]; /* convert output to 1.31 format to add y[n-1] */ out = (q31_t) (acc >> 31u); /* out += y[n-1] */ out += S->state[2]; /* Update state */ S->state[1] = S->state[0]; S->state[0] = in; S->state[2] = out; /* return to application */ return (out); } /** * @brief Process function for the Q15 PID Control. * @param[in,out] *S points to an instance of the Q15 PID Control structure * @param[in] in input sample to process * @return out processed output sample. * * Scaling and Overflow Behavior: * \par * The function is implemented using a 64-bit internal accumulator. * Both Gains and state variables are represented in 1.15 format and multiplications yield a 2.30 result. * The 2.30 intermediate results are accumulated in a 64-bit accumulator in 34.30 format. * There is no risk of internal overflow with this approach and the full precision of intermediate multiplications is preserved. * After all additions have been performed, the accumulator is truncated to 34.15 format by discarding low 15 bits. * Lastly, the accumulator is saturated to yield a result in 1.15 format. */ static __INLINE q15_t arm_pid_q15( arm_pid_instance_q15 * S, q15_t in) { q63_t acc; q15_t out; #ifndef ARM_MATH_CM0_FAMILY __SIMD32_TYPE *vstate; /* Implementation of PID controller */ /* acc = A0 * x[n] */ acc = (q31_t) __SMUAD(S->A0, in); /* acc += A1 * x[n-1] + A2 * x[n-2] */ vstate = __SIMD32_CONST(S->state); acc = __SMLALD(S->A1, (q31_t) *vstate, acc); #else /* acc = A0 * x[n] */ acc = ((q31_t) S->A0) * in; /* acc += A1 * x[n-1] + A2 * x[n-2] */ acc += (q31_t) S->A1 * S->state[0]; acc += (q31_t) S->A2 * S->state[1]; #endif /* acc += y[n-1] */ acc += (q31_t) S->state[2] << 15; /* saturate the output */ out = (q15_t) (__SSAT((acc >> 15), 16)); /* Update state */ S->state[1] = S->state[0]; S->state[0] = in; S->state[2] = out; /* return to application */ return (out); } /** * @} end of PID group */ /** * @brief Floating-point matrix inverse. * @param[in] *src points to the instance of the input floating-point matrix structure. * @param[out] *dst points to the instance of the output floating-point matrix structure. * @return The function returns ARM_MATH_SIZE_MISMATCH, if the dimensions do not match. * If the input matrix is singular (does not have an inverse), then the algorithm terminates and returns error status ARM_MATH_SINGULAR. */ arm_status arm_mat_inverse_f32( const arm_matrix_instance_f32 * src, arm_matrix_instance_f32 * dst); /** * @brief Floating-point matrix inverse. * @param[in] *src points to the instance of the input floating-point matrix structure. * @param[out] *dst points to the instance of the output floating-point matrix structure. * @return The function returns ARM_MATH_SIZE_MISMATCH, if the dimensions do not match. * If the input matrix is singular (does not have an inverse), then the algorithm terminates and returns error status ARM_MATH_SINGULAR. */ arm_status arm_mat_inverse_f64( const arm_matrix_instance_f64 * src, arm_matrix_instance_f64 * dst); /** * @ingroup groupController */ /** * @defgroup clarke Vector Clarke Transform * Forward Clarke transform converts the instantaneous stator phases into a two-coordinate time invariant vector. * Generally the Clarke transform uses three-phase currents Ia, Ib and Ic to calculate currents * in the two-phase orthogonal stator axis Ialpha and Ibeta. * When Ialpha is superposed with Ia as shown in the figure below * \image html clarke.gif Stator current space vector and its components in (a,b). * and Ia + Ib + Ic = 0, in this condition Ialpha and Ibeta * can be calculated using only Ia and Ib. * * The function operates on a single sample of data and each call to the function returns the processed output. * The library provides separate functions for Q31 and floating-point data types. * \par Algorithm * \image html clarkeFormula.gif * where Ia and Ib are the instantaneous stator phases and * pIalpha and pIbeta are the two coordinates of time invariant vector. * \par Fixed-Point Behavior * Care must be taken when using the Q31 version of the Clarke transform. * In particular, the overflow and saturation behavior of the accumulator used must be considered. * Refer to the function specific documentation below for usage guidelines. */ /** * @addtogroup clarke * @{ */ /** * * @brief Floating-point Clarke transform * @param[in] Ia input three-phase coordinate a * @param[in] Ib input three-phase coordinate b * @param[out] *pIalpha points to output two-phase orthogonal vector axis alpha * @param[out] *pIbeta points to output two-phase orthogonal vector axis beta * @return none. */ static __INLINE void arm_clarke_f32( float32_t Ia, float32_t Ib, float32_t * pIalpha, float32_t * pIbeta) { /* Calculate pIalpha using the equation, pIalpha = Ia */ *pIalpha = Ia; /* Calculate pIbeta using the equation, pIbeta = (1/sqrt(3)) * Ia + (2/sqrt(3)) * Ib */ *pIbeta = ((float32_t) 0.57735026919 * Ia + (float32_t) 1.15470053838 * Ib); } /** * @brief Clarke transform for Q31 version * @param[in] Ia input three-phase coordinate a * @param[in] Ib input three-phase coordinate b * @param[out] *pIalpha points to output two-phase orthogonal vector axis alpha * @param[out] *pIbeta points to output two-phase orthogonal vector axis beta * @return none. * * Scaling and Overflow Behavior: * \par * The function is implemented using an internal 32-bit accumulator. * The accumulator maintains 1.31 format by truncating lower 31 bits of the intermediate multiplication in 2.62 format. * There is saturation on the addition, hence there is no risk of overflow. */ static __INLINE void arm_clarke_q31( q31_t Ia, q31_t Ib, q31_t * pIalpha, q31_t * pIbeta) { q31_t product1, product2; /* Temporary variables used to store intermediate results */ /* Calculating pIalpha from Ia by equation pIalpha = Ia */ *pIalpha = Ia; /* Intermediate product is calculated by (1/(sqrt(3)) * Ia) */ product1 = (q31_t) (((q63_t) Ia * 0x24F34E8B) >> 30); /* Intermediate product is calculated by (2/sqrt(3) * Ib) */ product2 = (q31_t) (((q63_t) Ib * 0x49E69D16) >> 30); /* pIbeta is calculated by adding the intermediate products */ *pIbeta = __QADD(product1, product2); } /** * @} end of clarke group */ /** * @brief Converts the elements of the Q7 vector to Q31 vector. * @param[in] *pSrc input pointer * @param[out] *pDst output pointer * @param[in] blockSize number of samples to process * @return none. */ void arm_q7_to_q31( q7_t * pSrc, q31_t * pDst, uint32_t blockSize); /** * @ingroup groupController */ /** * @defgroup inv_clarke Vector Inverse Clarke Transform * Inverse Clarke transform converts the two-coordinate time invariant vector into instantaneous stator phases. * * The function operates on a single sample of data and each call to the function returns the processed output. * The library provides separate functions for Q31 and floating-point data types. * \par Algorithm * \image html clarkeInvFormula.gif * where pIa and pIb are the instantaneous stator phases and * Ialpha and Ibeta are the two coordinates of time invariant vector. * \par Fixed-Point Behavior * Care must be taken when using the Q31 version of the Clarke transform. * In particular, the overflow and saturation behavior of the accumulator used must be considered. * Refer to the function specific documentation below for usage guidelines. */ /** * @addtogroup inv_clarke * @{ */ /** * @brief Floating-point Inverse Clarke transform * @param[in] Ialpha input two-phase orthogonal vector axis alpha * @param[in] Ibeta input two-phase orthogonal vector axis beta * @param[out] *pIa points to output three-phase coordinate a * @param[out] *pIb points to output three-phase coordinate b * @return none. */ static __INLINE void arm_inv_clarke_f32( float32_t Ialpha, float32_t Ibeta, float32_t * pIa, float32_t * pIb) { /* Calculating pIa from Ialpha by equation pIa = Ialpha */ *pIa = Ialpha; /* Calculating pIb from Ialpha and Ibeta by equation pIb = -(1/2) * Ialpha + (sqrt(3)/2) * Ibeta */ *pIb = -0.5 * Ialpha + (float32_t) 0.8660254039 *Ibeta; } /** * @brief Inverse Clarke transform for Q31 version * @param[in] Ialpha input two-phase orthogonal vector axis alpha * @param[in] Ibeta input two-phase orthogonal vector axis beta * @param[out] *pIa points to output three-phase coordinate a * @param[out] *pIb points to output three-phase coordinate b * @return none. * * Scaling and Overflow Behavior: * \par * The function is implemented using an internal 32-bit accumulator. * The accumulator maintains 1.31 format by truncating lower 31 bits of the intermediate multiplication in 2.62 format. * There is saturation on the subtraction, hence there is no risk of overflow. */ static __INLINE void arm_inv_clarke_q31( q31_t Ialpha, q31_t Ibeta, q31_t * pIa, q31_t * pIb) { q31_t product1, product2; /* Temporary variables used to store intermediate results */ /* Calculating pIa from Ialpha by equation pIa = Ialpha */ *pIa = Ialpha; /* Intermediate product is calculated by (1/(2*sqrt(3)) * Ia) */ product1 = (q31_t) (((q63_t) (Ialpha) * (0x40000000)) >> 31); /* Intermediate product is calculated by (1/sqrt(3) * pIb) */ product2 = (q31_t) (((q63_t) (Ibeta) * (0x6ED9EBA1)) >> 31); /* pIb is calculated by subtracting the products */ *pIb = __QSUB(product2, product1); } /** * @} end of inv_clarke group */ /** * @brief Converts the elements of the Q7 vector to Q15 vector. * @param[in] *pSrc input pointer * @param[out] *pDst output pointer * @param[in] blockSize number of samples to process * @return none. */ void arm_q7_to_q15( q7_t * pSrc, q15_t * pDst, uint32_t blockSize); /** * @ingroup groupController */ /** * @defgroup park Vector Park Transform * * Forward Park transform converts the input two-coordinate vector to flux and torque components. * The Park transform can be used to realize the transformation of the Ialpha and the Ibeta currents * from the stationary to the moving reference frame and control the spatial relationship between * the stator vector current and rotor flux vector. * If we consider the d axis aligned with the rotor flux, the diagram below shows the * current vector and the relationship from the two reference frames: * \image html park.gif "Stator current space vector and its component in (a,b) and in the d,q rotating reference frame" * * The function operates on a single sample of data and each call to the function returns the processed output. * The library provides separate functions for Q31 and floating-point data types. * \par Algorithm * \image html parkFormula.gif * where Ialpha and Ibeta are the stator vector components, * pId and pIq are rotor vector components and cosVal and sinVal are the * cosine and sine values of theta (rotor flux position). * \par Fixed-Point Behavior * Care must be taken when using the Q31 version of the Park transform. * In particular, the overflow and saturation behavior of the accumulator used must be considered. * Refer to the function specific documentation below for usage guidelines. */ /** * @addtogroup park * @{ */ /** * @brief Floating-point Park transform * @param[in] Ialpha input two-phase vector coordinate alpha * @param[in] Ibeta input two-phase vector coordinate beta * @param[out] *pId points to output rotor reference frame d * @param[out] *pIq points to output rotor reference frame q * @param[in] sinVal sine value of rotation angle theta * @param[in] cosVal cosine value of rotation angle theta * @return none. * * The function implements the forward Park transform. * */ static __INLINE void arm_park_f32( float32_t Ialpha, float32_t Ibeta, float32_t * pId, float32_t * pIq, float32_t sinVal, float32_t cosVal) { /* Calculate pId using the equation, pId = Ialpha * cosVal + Ibeta * sinVal */ *pId = Ialpha * cosVal + Ibeta * sinVal; /* Calculate pIq using the equation, pIq = - Ialpha * sinVal + Ibeta * cosVal */ *pIq = -Ialpha * sinVal + Ibeta * cosVal; } /** * @brief Park transform for Q31 version * @param[in] Ialpha input two-phase vector coordinate alpha * @param[in] Ibeta input two-phase vector coordinate beta * @param[out] *pId points to output rotor reference frame d * @param[out] *pIq points to output rotor reference frame q * @param[in] sinVal sine value of rotation angle theta * @param[in] cosVal cosine value of rotation angle theta * @return none. * * Scaling and Overflow Behavior: * \par * The function is implemented using an internal 32-bit accumulator. * The accumulator maintains 1.31 format by truncating lower 31 bits of the intermediate multiplication in 2.62 format. * There is saturation on the addition and subtraction, hence there is no risk of overflow. */ static __INLINE void arm_park_q31( q31_t Ialpha, q31_t Ibeta, q31_t * pId, q31_t * pIq, q31_t sinVal, q31_t cosVal) { q31_t product1, product2; /* Temporary variables used to store intermediate results */ q31_t product3, product4; /* Temporary variables used to store intermediate results */ /* Intermediate product is calculated by (Ialpha * cosVal) */ product1 = (q31_t) (((q63_t) (Ialpha) * (cosVal)) >> 31); /* Intermediate product is calculated by (Ibeta * sinVal) */ product2 = (q31_t) (((q63_t) (Ibeta) * (sinVal)) >> 31); /* Intermediate product is calculated by (Ialpha * sinVal) */ product3 = (q31_t) (((q63_t) (Ialpha) * (sinVal)) >> 31); /* Intermediate product is calculated by (Ibeta * cosVal) */ product4 = (q31_t) (((q63_t) (Ibeta) * (cosVal)) >> 31); /* Calculate pId by adding the two intermediate products 1 and 2 */ *pId = __QADD(product1, product2); /* Calculate pIq by subtracting the two intermediate products 3 from 4 */ *pIq = __QSUB(product4, product3); } /** * @} end of park group */ /** * @brief Converts the elements of the Q7 vector to floating-point vector. * @param[in] *pSrc is input pointer * @param[out] *pDst is output pointer * @param[in] blockSize is the number of samples to process * @return none. */ void arm_q7_to_float( q7_t * pSrc, float32_t * pDst, uint32_t blockSize); /** * @ingroup groupController */ /** * @defgroup inv_park Vector Inverse Park transform * Inverse Park transform converts the input flux and torque components to two-coordinate vector. * * The function operates on a single sample of data and each call to the function returns the processed output. * The library provides separate functions for Q31 and floating-point data types. * \par Algorithm * \image html parkInvFormula.gif * where pIalpha and pIbeta are the stator vector components, * Id and Iq are rotor vector components and cosVal and sinVal are the * cosine and sine values of theta (rotor flux position). * \par Fixed-Point Behavior * Care must be taken when using the Q31 version of the Park transform. * In particular, the overflow and saturation behavior of the accumulator used must be considered. * Refer to the function specific documentation below for usage guidelines. */ /** * @addtogroup inv_park * @{ */ /** * @brief Floating-point Inverse Park transform * @param[in] Id input coordinate of rotor reference frame d * @param[in] Iq input coordinate of rotor reference frame q * @param[out] *pIalpha points to output two-phase orthogonal vector axis alpha * @param[out] *pIbeta points to output two-phase orthogonal vector axis beta * @param[in] sinVal sine value of rotation angle theta * @param[in] cosVal cosine value of rotation angle theta * @return none. */ static __INLINE void arm_inv_park_f32( float32_t Id, float32_t Iq, float32_t * pIalpha, float32_t * pIbeta, float32_t sinVal, float32_t cosVal) { /* Calculate pIalpha using the equation, pIalpha = Id * cosVal - Iq * sinVal */ *pIalpha = Id * cosVal - Iq * sinVal; /* Calculate pIbeta using the equation, pIbeta = Id * sinVal + Iq * cosVal */ *pIbeta = Id * sinVal + Iq * cosVal; } /** * @brief Inverse Park transform for Q31 version * @param[in] Id input coordinate of rotor reference frame d * @param[in] Iq input coordinate of rotor reference frame q * @param[out] *pIalpha points to output two-phase orthogonal vector axis alpha * @param[out] *pIbeta points to output two-phase orthogonal vector axis beta * @param[in] sinVal sine value of rotation angle theta * @param[in] cosVal cosine value of rotation angle theta * @return none. * * Scaling and Overflow Behavior: * \par * The function is implemented using an internal 32-bit accumulator. * The accumulator maintains 1.31 format by truncating lower 31 bits of the intermediate multiplication in 2.62 format. * There is saturation on the addition, hence there is no risk of overflow. */ static __INLINE void arm_inv_park_q31( q31_t Id, q31_t Iq, q31_t * pIalpha, q31_t * pIbeta, q31_t sinVal, q31_t cosVal) { q31_t product1, product2; /* Temporary variables used to store intermediate results */ q31_t product3, product4; /* Temporary variables used to store intermediate results */ /* Intermediate product is calculated by (Id * cosVal) */ product1 = (q31_t) (((q63_t) (Id) * (cosVal)) >> 31); /* Intermediate product is calculated by (Iq * sinVal) */ product2 = (q31_t) (((q63_t) (Iq) * (sinVal)) >> 31); /* Intermediate product is calculated by (Id * sinVal) */ product3 = (q31_t) (((q63_t) (Id) * (sinVal)) >> 31); /* Intermediate product is calculated by (Iq * cosVal) */ product4 = (q31_t) (((q63_t) (Iq) * (cosVal)) >> 31); /* Calculate pIalpha by using the two intermediate products 1 and 2 */ *pIalpha = __QSUB(product1, product2); /* Calculate pIbeta by using the two intermediate products 3 and 4 */ *pIbeta = __QADD(product4, product3); } /** * @} end of Inverse park group */ /** * @brief Converts the elements of the Q31 vector to floating-point vector. * @param[in] *pSrc is input pointer * @param[out] *pDst is output pointer * @param[in] blockSize is the number of samples to process * @return none. */ void arm_q31_to_float( q31_t * pSrc, float32_t * pDst, uint32_t blockSize); /** * @ingroup groupInterpolation */ /** * @defgroup LinearInterpolate Linear Interpolation * * Linear interpolation is a method of curve fitting using linear polynomials. * Linear interpolation works by effectively drawing a straight line between two neighboring samples and returning the appropriate point along that line * * \par * \image html LinearInterp.gif "Linear interpolation" * * \par * A Linear Interpolate function calculates an output value(y), for the input(x) * using linear interpolation of the input values x0, x1( nearest input values) and the output values y0 and y1(nearest output values) * * \par Algorithm: *
   *       y = y0 + (x - x0) * ((y1 - y0)/(x1-x0))
   *       where x0, x1 are nearest values of input x
   *             y0, y1 are nearest values to output y
   * 
* * \par * This set of functions implements Linear interpolation process * for Q7, Q15, Q31, and floating-point data types. The functions operate on a single * sample of data and each call to the function returns a single processed value. * S points to an instance of the Linear Interpolate function data structure. * x is the input sample value. The functions returns the output value. * * \par * if x is outside of the table boundary, Linear interpolation returns first value of the table * if x is below input range and returns last value of table if x is above range. */ /** * @addtogroup LinearInterpolate * @{ */ /** * @brief Process function for the floating-point Linear Interpolation Function. * @param[in,out] *S is an instance of the floating-point Linear Interpolation structure * @param[in] x input sample to process * @return y processed output sample. * */ static __INLINE float32_t arm_linear_interp_f32( arm_linear_interp_instance_f32 * S, float32_t x) { float32_t y; float32_t x0, x1; /* Nearest input values */ float32_t y0, y1; /* Nearest output values */ float32_t xSpacing = S->xSpacing; /* spacing between input values */ int32_t i; /* Index variable */ float32_t *pYData = S->pYData; /* pointer to output table */ /* Calculation of index */ i = (int32_t) ((x - S->x1) / xSpacing); if(i < 0) { /* Iniatilize output for below specified range as least output value of table */ y = pYData[0]; } else if((uint32_t)i >= S->nValues) { /* Iniatilize output for above specified range as last output value of table */ y = pYData[S->nValues - 1]; } else { /* Calculation of nearest input values */ x0 = S->x1 + i * xSpacing; x1 = S->x1 + (i + 1) * xSpacing; /* Read of nearest output values */ y0 = pYData[i]; y1 = pYData[i + 1]; /* Calculation of output */ y = y0 + (x - x0) * ((y1 - y0) / (x1 - x0)); } /* returns output value */ return (y); } /** * * @brief Process function for the Q31 Linear Interpolation Function. * @param[in] *pYData pointer to Q31 Linear Interpolation table * @param[in] x input sample to process * @param[in] nValues number of table values * @return y processed output sample. * * \par * Input sample x is in 12.20 format which contains 12 bits for table index and 20 bits for fractional part. * This function can support maximum of table size 2^12. * */ static __INLINE q31_t arm_linear_interp_q31( q31_t * pYData, q31_t x, uint32_t nValues) { q31_t y; /* output */ q31_t y0, y1; /* Nearest output values */ q31_t fract; /* fractional part */ int32_t index; /* Index to read nearest output values */ /* Input is in 12.20 format */ /* 12 bits for the table index */ /* Index value calculation */ index = ((x & 0xFFF00000) >> 20); if(index >= (int32_t)(nValues - 1)) { return (pYData[nValues - 1]); } else if(index < 0) { return (pYData[0]); } else { /* 20 bits for the fractional part */ /* shift left by 11 to keep fract in 1.31 format */ fract = (x & 0x000FFFFF) << 11; /* Read two nearest output values from the index in 1.31(q31) format */ y0 = pYData[index]; y1 = pYData[index + 1u]; /* Calculation of y0 * (1-fract) and y is in 2.30 format */ y = ((q31_t) ((q63_t) y0 * (0x7FFFFFFF - fract) >> 32)); /* Calculation of y0 * (1-fract) + y1 *fract and y is in 2.30 format */ y += ((q31_t) (((q63_t) y1 * fract) >> 32)); /* Convert y to 1.31 format */ return (y << 1u); } } /** * * @brief Process function for the Q15 Linear Interpolation Function. * @param[in] *pYData pointer to Q15 Linear Interpolation table * @param[in] x input sample to process * @param[in] nValues number of table values * @return y processed output sample. * * \par * Input sample x is in 12.20 format which contains 12 bits for table index and 20 bits for fractional part. * This function can support maximum of table size 2^12. * */ static __INLINE q15_t arm_linear_interp_q15( q15_t * pYData, q31_t x, uint32_t nValues) { q63_t y; /* output */ q15_t y0, y1; /* Nearest output values */ q31_t fract; /* fractional part */ int32_t index; /* Index to read nearest output values */ /* Input is in 12.20 format */ /* 12 bits for the table index */ /* Index value calculation */ index = ((x & 0xFFF00000) >> 20u); if(index >= (int32_t)(nValues - 1)) { return (pYData[nValues - 1]); } else if(index < 0) { return (pYData[0]); } else { /* 20 bits for the fractional part */ /* fract is in 12.20 format */ fract = (x & 0x000FFFFF); /* Read two nearest output values from the index */ y0 = pYData[index]; y1 = pYData[index + 1u]; /* Calculation of y0 * (1-fract) and y is in 13.35 format */ y = ((q63_t) y0 * (0xFFFFF - fract)); /* Calculation of (y0 * (1-fract) + y1 * fract) and y is in 13.35 format */ y += ((q63_t) y1 * (fract)); /* convert y to 1.15 format */ return (y >> 20); } } /** * * @brief Process function for the Q7 Linear Interpolation Function. * @param[in] *pYData pointer to Q7 Linear Interpolation table * @param[in] x input sample to process * @param[in] nValues number of table values * @return y processed output sample. * * \par * Input sample x is in 12.20 format which contains 12 bits for table index and 20 bits for fractional part. * This function can support maximum of table size 2^12. */ static __INLINE q7_t arm_linear_interp_q7( q7_t * pYData, q31_t x, uint32_t nValues) { q31_t y; /* output */ q7_t y0, y1; /* Nearest output values */ q31_t fract; /* fractional part */ uint32_t index; /* Index to read nearest output values */ /* Input is in 12.20 format */ /* 12 bits for the table index */ /* Index value calculation */ if (x < 0) { return (pYData[0]); } index = (x >> 20) & 0xfff; if(index >= (nValues - 1)) { return (pYData[nValues - 1]); } else { /* 20 bits for the fractional part */ /* fract is in 12.20 format */ fract = (x & 0x000FFFFF); /* Read two nearest output values from the index and are in 1.7(q7) format */ y0 = pYData[index]; y1 = pYData[index + 1u]; /* Calculation of y0 * (1-fract ) and y is in 13.27(q27) format */ y = ((y0 * (0xFFFFF - fract))); /* Calculation of y1 * fract + y0 * (1-fract) and y is in 13.27(q27) format */ y += (y1 * fract); /* convert y to 1.7(q7) format */ return (y >> 20u); } } /** * @} end of LinearInterpolate group */ /** * @brief Fast approximation to the trigonometric sine function for floating-point data. * @param[in] x input value in radians. * @return sin(x). */ float32_t arm_sin_f32( float32_t x); /** * @brief Fast approximation to the trigonometric sine function for Q31 data. * @param[in] x Scaled input value in radians. * @return sin(x). */ q31_t arm_sin_q31( q31_t x); /** * @brief Fast approximation to the trigonometric sine function for Q15 data. * @param[in] x Scaled input value in radians. * @return sin(x). */ q15_t arm_sin_q15( q15_t x); /** * @brief Fast approximation to the trigonometric cosine function for floating-point data. * @param[in] x input value in radians. * @return cos(x). */ float32_t arm_cos_f32( float32_t x); /** * @brief Fast approximation to the trigonometric cosine function for Q31 data. * @param[in] x Scaled input value in radians. * @return cos(x). */ q31_t arm_cos_q31( q31_t x); /** * @brief Fast approximation to the trigonometric cosine function for Q15 data. * @param[in] x Scaled input value in radians. * @return cos(x). */ q15_t arm_cos_q15( q15_t x); /** * @ingroup groupFastMath */ /** * @defgroup SQRT Square Root * * Computes the square root of a number. * There are separate functions for Q15, Q31, and floating-point data types. * The square root function is computed using the Newton-Raphson algorithm. * This is an iterative algorithm of the form: *
   *      x1 = x0 - f(x0)/f'(x0)
   * 
* where x1 is the current estimate, * x0 is the previous estimate, and * f'(x0) is the derivative of f() evaluated at x0. * For the square root function, the algorithm reduces to: *
   *     x0 = in/2                         [initial guess]
   *     x1 = 1/2 * ( x0 + in / x0)        [each iteration]
   * 
*/ /** * @addtogroup SQRT * @{ */ /** * @brief Floating-point square root function. * @param[in] in input value. * @param[out] *pOut square root of input value. * @return The function returns ARM_MATH_SUCCESS if input value is positive value or ARM_MATH_ARGUMENT_ERROR if * in is negative value and returns zero output for negative values. */ static __INLINE arm_status arm_sqrt_f32( float32_t in, float32_t * pOut) { if(in >= 0.0f) { // #if __FPU_USED #if (__FPU_USED == 1) && defined ( __CC_ARM ) *pOut = __sqrtf(in); #else *pOut = sqrtf(in); #endif return (ARM_MATH_SUCCESS); } else { *pOut = 0.0f; return (ARM_MATH_ARGUMENT_ERROR); } } /** * @brief Q31 square root function. * @param[in] in input value. The range of the input value is [0 +1) or 0x00000000 to 0x7FFFFFFF. * @param[out] *pOut square root of input value. * @return The function returns ARM_MATH_SUCCESS if input value is positive value or ARM_MATH_ARGUMENT_ERROR if * in is negative value and returns zero output for negative values. */ arm_status arm_sqrt_q31( q31_t in, q31_t * pOut); /** * @brief Q15 square root function. * @param[in] in input value. The range of the input value is [0 +1) or 0x0000 to 0x7FFF. * @param[out] *pOut square root of input value. * @return The function returns ARM_MATH_SUCCESS if input value is positive value or ARM_MATH_ARGUMENT_ERROR if * in is negative value and returns zero output for negative values. */ arm_status arm_sqrt_q15( q15_t in, q15_t * pOut); /** * @} end of SQRT group */ /** * @brief floating-point Circular write function. */ static __INLINE void arm_circularWrite_f32( int32_t * circBuffer, int32_t L, uint16_t * writeOffset, int32_t bufferInc, const int32_t * src, int32_t srcInc, uint32_t blockSize) { uint32_t i = 0u; int32_t wOffset; /* Copy the value of Index pointer that points * to the current location where the input samples to be copied */ wOffset = *writeOffset; /* Loop over the blockSize */ i = blockSize; while(i > 0u) { /* copy the input sample to the circular buffer */ circBuffer[wOffset] = *src; /* Update the input pointer */ src += srcInc; /* Circularly update wOffset. Watch out for positive and negative value */ wOffset += bufferInc; if(wOffset >= L) wOffset -= L; /* Decrement the loop counter */ i--; } /* Update the index pointer */ *writeOffset = wOffset; } /** * @brief floating-point Circular Read function. */ static __INLINE void arm_circularRead_f32( int32_t * circBuffer, int32_t L, int32_t * readOffset, int32_t bufferInc, int32_t * dst, int32_t * dst_base, int32_t dst_length, int32_t dstInc, uint32_t blockSize) { uint32_t i = 0u; int32_t rOffset, dst_end; /* Copy the value of Index pointer that points * to the current location from where the input samples to be read */ rOffset = *readOffset; dst_end = (int32_t) (dst_base + dst_length); /* Loop over the blockSize */ i = blockSize; while(i > 0u) { /* copy the sample from the circular buffer to the destination buffer */ *dst = circBuffer[rOffset]; /* Update the input pointer */ dst += dstInc; if(dst == (int32_t *) dst_end) { dst = dst_base; } /* Circularly update rOffset. Watch out for positive and negative value */ rOffset += bufferInc; if(rOffset >= L) { rOffset -= L; } /* Decrement the loop counter */ i--; } /* Update the index pointer */ *readOffset = rOffset; } /** * @brief Q15 Circular write function. */ static __INLINE void arm_circularWrite_q15( q15_t * circBuffer, int32_t L, uint16_t * writeOffset, int32_t bufferInc, const q15_t * src, int32_t srcInc, uint32_t blockSize) { uint32_t i = 0u; int32_t wOffset; /* Copy the value of Index pointer that points * to the current location where the input samples to be copied */ wOffset = *writeOffset; /* Loop over the blockSize */ i = blockSize; while(i > 0u) { /* copy the input sample to the circular buffer */ circBuffer[wOffset] = *src; /* Update the input pointer */ src += srcInc; /* Circularly update wOffset. Watch out for positive and negative value */ wOffset += bufferInc; if(wOffset >= L) wOffset -= L; /* Decrement the loop counter */ i--; } /* Update the index pointer */ *writeOffset = wOffset; } /** * @brief Q15 Circular Read function. */ static __INLINE void arm_circularRead_q15( q15_t * circBuffer, int32_t L, int32_t * readOffset, int32_t bufferInc, q15_t * dst, q15_t * dst_base, int32_t dst_length, int32_t dstInc, uint32_t blockSize) { uint32_t i = 0; int32_t rOffset, dst_end; /* Copy the value of Index pointer that points * to the current location from where the input samples to be read */ rOffset = *readOffset; dst_end = (int32_t) (dst_base + dst_length); /* Loop over the blockSize */ i = blockSize; while(i > 0u) { /* copy the sample from the circular buffer to the destination buffer */ *dst = circBuffer[rOffset]; /* Update the input pointer */ dst += dstInc; if(dst == (q15_t *) dst_end) { dst = dst_base; } /* Circularly update wOffset. Watch out for positive and negative value */ rOffset += bufferInc; if(rOffset >= L) { rOffset -= L; } /* Decrement the loop counter */ i--; } /* Update the index pointer */ *readOffset = rOffset; } /** * @brief Q7 Circular write function. */ static __INLINE void arm_circularWrite_q7( q7_t * circBuffer, int32_t L, uint16_t * writeOffset, int32_t bufferInc, const q7_t * src, int32_t srcInc, uint32_t blockSize) { uint32_t i = 0u; int32_t wOffset; /* Copy the value of Index pointer that points * to the current location where the input samples to be copied */ wOffset = *writeOffset; /* Loop over the blockSize */ i = blockSize; while(i > 0u) { /* copy the input sample to the circular buffer */ circBuffer[wOffset] = *src; /* Update the input pointer */ src += srcInc; /* Circularly update wOffset. Watch out for positive and negative value */ wOffset += bufferInc; if(wOffset >= L) wOffset -= L; /* Decrement the loop counter */ i--; } /* Update the index pointer */ *writeOffset = wOffset; } /** * @brief Q7 Circular Read function. */ static __INLINE void arm_circularRead_q7( q7_t * circBuffer, int32_t L, int32_t * readOffset, int32_t bufferInc, q7_t * dst, q7_t * dst_base, int32_t dst_length, int32_t dstInc, uint32_t blockSize) { uint32_t i = 0; int32_t rOffset, dst_end; /* Copy the value of Index pointer that points * to the current location from where the input samples to be read */ rOffset = *readOffset; dst_end = (int32_t) (dst_base + dst_length); /* Loop over the blockSize */ i = blockSize; while(i > 0u) { /* copy the sample from the circular buffer to the destination buffer */ *dst = circBuffer[rOffset]; /* Update the input pointer */ dst += dstInc; if(dst == (q7_t *) dst_end) { dst = dst_base; } /* Circularly update rOffset. Watch out for positive and negative value */ rOffset += bufferInc; if(rOffset >= L) { rOffset -= L; } /* Decrement the loop counter */ i--; } /* Update the index pointer */ *readOffset = rOffset; } /** * @brief Sum of the squares of the elements of a Q31 vector. * @param[in] *pSrc is input pointer * @param[in] blockSize is the number of samples to process * @param[out] *pResult is output value. * @return none. */ void arm_power_q31( q31_t * pSrc, uint32_t blockSize, q63_t * pResult); /** * @brief Sum of the squares of the elements of a floating-point vector. * @param[in] *pSrc is input pointer * @param[in] blockSize is the number of samples to process * @param[out] *pResult is output value. * @return none. */ void arm_power_f32( float32_t * pSrc, uint32_t blockSize, float32_t * pResult); /** * @brief Sum of the squares of the elements of a Q15 vector. * @param[in] *pSrc is input pointer * @param[in] blockSize is the number of samples to process * @param[out] *pResult is output value. * @return none. */ void arm_power_q15( q15_t * pSrc, uint32_t blockSize, q63_t * pResult); /** * @brief Sum of the squares of the elements of a Q7 vector. * @param[in] *pSrc is input pointer * @param[in] blockSize is the number of samples to process * @param[out] *pResult is output value. * @return none. */ void arm_power_q7( q7_t * pSrc, uint32_t blockSize, q31_t * pResult); /** * @brief Mean value of a Q7 vector. * @param[in] *pSrc is input pointer * @param[in] blockSize is the number of samples to process * @param[out] *pResult is output value. * @return none. */ void arm_mean_q7( q7_t * pSrc, uint32_t blockSize, q7_t * pResult); /** * @brief Mean value of a Q15 vector. * @param[in] *pSrc is input pointer * @param[in] blockSize is the number of samples to process * @param[out] *pResult is output value. * @return none. */ void arm_mean_q15( q15_t * pSrc, uint32_t blockSize, q15_t * pResult); /** * @brief Mean value of a Q31 vector. * @param[in] *pSrc is input pointer * @param[in] blockSize is the number of samples to process * @param[out] *pResult is output value. * @return none. */ void arm_mean_q31( q31_t * pSrc, uint32_t blockSize, q31_t * pResult); /** * @brief Mean value of a floating-point vector. * @param[in] *pSrc is input pointer * @param[in] blockSize is the number of samples to process * @param[out] *pResult is output value. * @return none. */ void arm_mean_f32( float32_t * pSrc, uint32_t blockSize, float32_t * pResult); /** * @brief Variance of the elements of a floating-point vector. * @param[in] *pSrc is input pointer * @param[in] blockSize is the number of samples to process * @param[out] *pResult is output value. * @return none. */ void arm_var_f32( float32_t * pSrc, uint32_t blockSize, float32_t * pResult); /** * @brief Variance of the elements of a Q31 vector. * @param[in] *pSrc is input pointer * @param[in] blockSize is the number of samples to process * @param[out] *pResult is output value. * @return none. */ void arm_var_q31( q31_t * pSrc, uint32_t blockSize, q31_t * pResult); /** * @brief Variance of the elements of a Q15 vector. * @param[in] *pSrc is input pointer * @param[in] blockSize is the number of samples to process * @param[out] *pResult is output value. * @return none. */ void arm_var_q15( q15_t * pSrc, uint32_t blockSize, q15_t * pResult); /** * @brief Root Mean Square of the elements of a floating-point vector. * @param[in] *pSrc is input pointer * @param[in] blockSize is the number of samples to process * @param[out] *pResult is output value. * @return none. */ void arm_rms_f32( float32_t * pSrc, uint32_t blockSize, float32_t * pResult); /** * @brief Root Mean Square of the elements of a Q31 vector. * @param[in] *pSrc is input pointer * @param[in] blockSize is the number of samples to process * @param[out] *pResult is output value. * @return none. */ void arm_rms_q31( q31_t * pSrc, uint32_t blockSize, q31_t * pResult); /** * @brief Root Mean Square of the elements of a Q15 vector. * @param[in] *pSrc is input pointer * @param[in] blockSize is the number of samples to process * @param[out] *pResult is output value. * @return none. */ void arm_rms_q15( q15_t * pSrc, uint32_t blockSize, q15_t * pResult); /** * @brief Standard deviation of the elements of a floating-point vector. * @param[in] *pSrc is input pointer * @param[in] blockSize is the number of samples to process * @param[out] *pResult is output value. * @return none. */ void arm_std_f32( float32_t * pSrc, uint32_t blockSize, float32_t * pResult); /** * @brief Standard deviation of the elements of a Q31 vector. * @param[in] *pSrc is input pointer * @param[in] blockSize is the number of samples to process * @param[out] *pResult is output value. * @return none. */ void arm_std_q31( q31_t * pSrc, uint32_t blockSize, q31_t * pResult); /** * @brief Standard deviation of the elements of a Q15 vector. * @param[in] *pSrc is input pointer * @param[in] blockSize is the number of samples to process * @param[out] *pResult is output value. * @return none. */ void arm_std_q15( q15_t * pSrc, uint32_t blockSize, q15_t * pResult); /** * @brief Floating-point complex magnitude * @param[in] *pSrc points to the complex input vector * @param[out] *pDst points to the real output vector * @param[in] numSamples number of complex samples in the input vector * @return none. */ void arm_cmplx_mag_f32( float32_t * pSrc, float32_t * pDst, uint32_t numSamples); /** * @brief Q31 complex magnitude * @param[in] *pSrc points to the complex input vector * @param[out] *pDst points to the real output vector * @param[in] numSamples number of complex samples in the input vector * @return none. */ void arm_cmplx_mag_q31( q31_t * pSrc, q31_t * pDst, uint32_t numSamples); /** * @brief Q15 complex magnitude * @param[in] *pSrc points to the complex input vector * @param[out] *pDst points to the real output vector * @param[in] numSamples number of complex samples in the input vector * @return none. */ void arm_cmplx_mag_q15( q15_t * pSrc, q15_t * pDst, uint32_t numSamples); /** * @brief Q15 complex dot product * @param[in] *pSrcA points to the first input vector * @param[in] *pSrcB points to the second input vector * @param[in] numSamples number of complex samples in each vector * @param[out] *realResult real part of the result returned here * @param[out] *imagResult imaginary part of the result returned here * @return none. */ void arm_cmplx_dot_prod_q15( q15_t * pSrcA, q15_t * pSrcB, uint32_t numSamples, q31_t * realResult, q31_t * imagResult); /** * @brief Q31 complex dot product * @param[in] *pSrcA points to the first input vector * @param[in] *pSrcB points to the second input vector * @param[in] numSamples number of complex samples in each vector * @param[out] *realResult real part of the result returned here * @param[out] *imagResult imaginary part of the result returned here * @return none. */ void arm_cmplx_dot_prod_q31( q31_t * pSrcA, q31_t * pSrcB, uint32_t numSamples, q63_t * realResult, q63_t * imagResult); /** * @brief Floating-point complex dot product * @param[in] *pSrcA points to the first input vector * @param[in] *pSrcB points to the second input vector * @param[in] numSamples number of complex samples in each vector * @param[out] *realResult real part of the result returned here * @param[out] *imagResult imaginary part of the result returned here * @return none. */ void arm_cmplx_dot_prod_f32( float32_t * pSrcA, float32_t * pSrcB, uint32_t numSamples, float32_t * realResult, float32_t * imagResult); /** * @brief Q15 complex-by-real multiplication * @param[in] *pSrcCmplx points to the complex input vector * @param[in] *pSrcReal points to the real input vector * @param[out] *pCmplxDst points to the complex output vector * @param[in] numSamples number of samples in each vector * @return none. */ void arm_cmplx_mult_real_q15( q15_t * pSrcCmplx, q15_t * pSrcReal, q15_t * pCmplxDst, uint32_t numSamples); /** * @brief Q31 complex-by-real multiplication * @param[in] *pSrcCmplx points to the complex input vector * @param[in] *pSrcReal points to the real input vector * @param[out] *pCmplxDst points to the complex output vector * @param[in] numSamples number of samples in each vector * @return none. */ void arm_cmplx_mult_real_q31( q31_t * pSrcCmplx, q31_t * pSrcReal, q31_t * pCmplxDst, uint32_t numSamples); /** * @brief Floating-point complex-by-real multiplication * @param[in] *pSrcCmplx points to the complex input vector * @param[in] *pSrcReal points to the real input vector * @param[out] *pCmplxDst points to the complex output vector * @param[in] numSamples number of samples in each vector * @return none. */ void arm_cmplx_mult_real_f32( float32_t * pSrcCmplx, float32_t * pSrcReal, float32_t * pCmplxDst, uint32_t numSamples); /** * @brief Minimum value of a Q7 vector. * @param[in] *pSrc is input pointer * @param[in] blockSize is the number of samples to process * @param[out] *result is output pointer * @param[in] index is the array index of the minimum value in the input buffer. * @return none. */ void arm_min_q7( q7_t * pSrc, uint32_t blockSize, q7_t * result, uint32_t * index); /** * @brief Minimum value of a Q15 vector. * @param[in] *pSrc is input pointer * @param[in] blockSize is the number of samples to process * @param[out] *pResult is output pointer * @param[in] *pIndex is the array index of the minimum value in the input buffer. * @return none. */ void arm_min_q15( q15_t * pSrc, uint32_t blockSize, q15_t * pResult, uint32_t * pIndex); /** * @brief Minimum value of a Q31 vector. * @param[in] *pSrc is input pointer * @param[in] blockSize is the number of samples to process * @param[out] *pResult is output pointer * @param[out] *pIndex is the array index of the minimum value in the input buffer. * @return none. */ void arm_min_q31( q31_t * pSrc, uint32_t blockSize, q31_t * pResult, uint32_t * pIndex); /** * @brief Minimum value of a floating-point vector. * @param[in] *pSrc is input pointer * @param[in] blockSize is the number of samples to process * @param[out] *pResult is output pointer * @param[out] *pIndex is the array index of the minimum value in the input buffer. * @return none. */ void arm_min_f32( float32_t * pSrc, uint32_t blockSize, float32_t * pResult, uint32_t * pIndex); /** * @brief Maximum value of a Q7 vector. * @param[in] *pSrc points to the input buffer * @param[in] blockSize length of the input vector * @param[out] *pResult maximum value returned here * @param[out] *pIndex index of maximum value returned here * @return none. */ void arm_max_q7( q7_t * pSrc, uint32_t blockSize, q7_t * pResult, uint32_t * pIndex); /** * @brief Maximum value of a Q15 vector. * @param[in] *pSrc points to the input buffer * @param[in] blockSize length of the input vector * @param[out] *pResult maximum value returned here * @param[out] *pIndex index of maximum value returned here * @return none. */ void arm_max_q15( q15_t * pSrc, uint32_t blockSize, q15_t * pResult, uint32_t * pIndex); /** * @brief Maximum value of a Q31 vector. * @param[in] *pSrc points to the input buffer * @param[in] blockSize length of the input vector * @param[out] *pResult maximum value returned here * @param[out] *pIndex index of maximum value returned here * @return none. */ void arm_max_q31( q31_t * pSrc, uint32_t blockSize, q31_t * pResult, uint32_t * pIndex); /** * @brief Maximum value of a floating-point vector. * @param[in] *pSrc points to the input buffer * @param[in] blockSize length of the input vector * @param[out] *pResult maximum value returned here * @param[out] *pIndex index of maximum value returned here * @return none. */ void arm_max_f32( float32_t * pSrc, uint32_t blockSize, float32_t * pResult, uint32_t * pIndex); /** * @brief Q15 complex-by-complex multiplication * @param[in] *pSrcA points to the first input vector * @param[in] *pSrcB points to the second input vector * @param[out] *pDst points to the output vector * @param[in] numSamples number of complex samples in each vector * @return none. */ void arm_cmplx_mult_cmplx_q15( q15_t * pSrcA, q15_t * pSrcB, q15_t * pDst, uint32_t numSamples); /** * @brief Q31 complex-by-complex multiplication * @param[in] *pSrcA points to the first input vector * @param[in] *pSrcB points to the second input vector * @param[out] *pDst points to the output vector * @param[in] numSamples number of complex samples in each vector * @return none. */ void arm_cmplx_mult_cmplx_q31( q31_t * pSrcA, q31_t * pSrcB, q31_t * pDst, uint32_t numSamples); /** * @brief Floating-point complex-by-complex multiplication * @param[in] *pSrcA points to the first input vector * @param[in] *pSrcB points to the second input vector * @param[out] *pDst points to the output vector * @param[in] numSamples number of complex samples in each vector * @return none. */ void arm_cmplx_mult_cmplx_f32( float32_t * pSrcA, float32_t * pSrcB, float32_t * pDst, uint32_t numSamples); /** * @brief Converts the elements of the floating-point vector to Q31 vector. * @param[in] *pSrc points to the floating-point input vector * @param[out] *pDst points to the Q31 output vector * @param[in] blockSize length of the input vector * @return none. */ void arm_float_to_q31( float32_t * pSrc, q31_t * pDst, uint32_t blockSize); /** * @brief Converts the elements of the floating-point vector to Q15 vector. * @param[in] *pSrc points to the floating-point input vector * @param[out] *pDst points to the Q15 output vector * @param[in] blockSize length of the input vector * @return none */ void arm_float_to_q15( float32_t * pSrc, q15_t * pDst, uint32_t blockSize); /** * @brief Converts the elements of the floating-point vector to Q7 vector. * @param[in] *pSrc points to the floating-point input vector * @param[out] *pDst points to the Q7 output vector * @param[in] blockSize length of the input vector * @return none */ void arm_float_to_q7( float32_t * pSrc, q7_t * pDst, uint32_t blockSize); /** * @brief Converts the elements of the Q31 vector to Q15 vector. * @param[in] *pSrc is input pointer * @param[out] *pDst is output pointer * @param[in] blockSize is the number of samples to process * @return none. */ void arm_q31_to_q15( q31_t * pSrc, q15_t * pDst, uint32_t blockSize); /** * @brief Converts the elements of the Q31 vector to Q7 vector. * @param[in] *pSrc is input pointer * @param[out] *pDst is output pointer * @param[in] blockSize is the number of samples to process * @return none. */ void arm_q31_to_q7( q31_t * pSrc, q7_t * pDst, uint32_t blockSize); /** * @brief Converts the elements of the Q15 vector to floating-point vector. * @param[in] *pSrc is input pointer * @param[out] *pDst is output pointer * @param[in] blockSize is the number of samples to process * @return none. */ void arm_q15_to_float( q15_t * pSrc, float32_t * pDst, uint32_t blockSize); /** * @brief Converts the elements of the Q15 vector to Q31 vector. * @param[in] *pSrc is input pointer * @param[out] *pDst is output pointer * @param[in] blockSize is the number of samples to process * @return none. */ void arm_q15_to_q31( q15_t * pSrc, q31_t * pDst, uint32_t blockSize); /** * @brief Converts the elements of the Q15 vector to Q7 vector. * @param[in] *pSrc is input pointer * @param[out] *pDst is output pointer * @param[in] blockSize is the number of samples to process * @return none. */ void arm_q15_to_q7( q15_t * pSrc, q7_t * pDst, uint32_t blockSize); /** * @ingroup groupInterpolation */ /** * @defgroup BilinearInterpolate Bilinear Interpolation * * Bilinear interpolation is an extension of linear interpolation applied to a two dimensional grid. * The underlying function f(x, y) is sampled on a regular grid and the interpolation process * determines values between the grid points. * Bilinear interpolation is equivalent to two step linear interpolation, first in the x-dimension and then in the y-dimension. * Bilinear interpolation is often used in image processing to rescale images. * The CMSIS DSP library provides bilinear interpolation functions for Q7, Q15, Q31, and floating-point data types. * * Algorithm * \par * The instance structure used by the bilinear interpolation functions describes a two dimensional data table. * For floating-point, the instance structure is defined as: *
   *   typedef struct
   *   {
   *     uint16_t numRows;
   *     uint16_t numCols;
   *     float32_t *pData;
   * } arm_bilinear_interp_instance_f32;
   * 
* * \par * where numRows specifies the number of rows in the table; * numCols specifies the number of columns in the table; * and pData points to an array of size numRows*numCols values. * The data table pTable is organized in row order and the supplied data values fall on integer indexes. * That is, table element (x,y) is located at pTable[x + y*numCols] where x and y are integers. * * \par * Let (x, y) specify the desired interpolation point. Then define: *
   *     XF = floor(x)
   *     YF = floor(y)
   * 
* \par * The interpolated output point is computed as: *
   *  f(x, y) = f(XF, YF) * (1-(x-XF)) * (1-(y-YF))
   *           + f(XF+1, YF) * (x-XF)*(1-(y-YF))
   *           + f(XF, YF+1) * (1-(x-XF))*(y-YF)
   *           + f(XF+1, YF+1) * (x-XF)*(y-YF)
   * 
* Note that the coordinates (x, y) contain integer and fractional components. * The integer components specify which portion of the table to use while the * fractional components control the interpolation processor. * * \par * if (x,y) are outside of the table boundary, Bilinear interpolation returns zero output. */ /** * @addtogroup BilinearInterpolate * @{ */ /** * * @brief Floating-point bilinear interpolation. * @param[in,out] *S points to an instance of the interpolation structure. * @param[in] X interpolation coordinate. * @param[in] Y interpolation coordinate. * @return out interpolated value. */ static __INLINE float32_t arm_bilinear_interp_f32( const arm_bilinear_interp_instance_f32 * S, float32_t X, float32_t Y) { float32_t out; float32_t f00, f01, f10, f11; float32_t *pData = S->pData; int32_t xIndex, yIndex, index; float32_t xdiff, ydiff; float32_t b1, b2, b3, b4; xIndex = (int32_t) X; yIndex = (int32_t) Y; /* Care taken for table outside boundary */ /* Returns zero output when values are outside table boundary */ if(xIndex < 0 || xIndex > (S->numRows - 1) || yIndex < 0 || yIndex > (S->numCols - 1)) { return (0); } /* Calculation of index for two nearest points in X-direction */ index = (xIndex - 1) + (yIndex - 1) * S->numCols; /* Read two nearest points in X-direction */ f00 = pData[index]; f01 = pData[index + 1]; /* Calculation of index for two nearest points in Y-direction */ index = (xIndex - 1) + (yIndex) * S->numCols; /* Read two nearest points in Y-direction */ f10 = pData[index]; f11 = pData[index + 1]; /* Calculation of intermediate values */ b1 = f00; b2 = f01 - f00; b3 = f10 - f00; b4 = f00 - f01 - f10 + f11; /* Calculation of fractional part in X */ xdiff = X - xIndex; /* Calculation of fractional part in Y */ ydiff = Y - yIndex; /* Calculation of bi-linear interpolated output */ out = b1 + b2 * xdiff + b3 * ydiff + b4 * xdiff * ydiff; /* return to application */ return (out); } /** * * @brief Q31 bilinear interpolation. * @param[in,out] *S points to an instance of the interpolation structure. * @param[in] X interpolation coordinate in 12.20 format. * @param[in] Y interpolation coordinate in 12.20 format. * @return out interpolated value. */ static __INLINE q31_t arm_bilinear_interp_q31( arm_bilinear_interp_instance_q31 * S, q31_t X, q31_t Y) { q31_t out; /* Temporary output */ q31_t acc = 0; /* output */ q31_t xfract, yfract; /* X, Y fractional parts */ q31_t x1, x2, y1, y2; /* Nearest output values */ int32_t rI, cI; /* Row and column indices */ q31_t *pYData = S->pData; /* pointer to output table values */ uint32_t nCols = S->numCols; /* num of rows */ /* Input is in 12.20 format */ /* 12 bits for the table index */ /* Index value calculation */ rI = ((X & 0xFFF00000) >> 20u); /* Input is in 12.20 format */ /* 12 bits for the table index */ /* Index value calculation */ cI = ((Y & 0xFFF00000) >> 20u); /* Care taken for table outside boundary */ /* Returns zero output when values are outside table boundary */ if(rI < 0 || rI > (S->numRows - 1) || cI < 0 || cI > (S->numCols - 1)) { return (0); } /* 20 bits for the fractional part */ /* shift left xfract by 11 to keep 1.31 format */ xfract = (X & 0x000FFFFF) << 11u; /* Read two nearest output values from the index */ x1 = pYData[(rI) + nCols * (cI)]; x2 = pYData[(rI) + nCols * (cI) + 1u]; /* 20 bits for the fractional part */ /* shift left yfract by 11 to keep 1.31 format */ yfract = (Y & 0x000FFFFF) << 11u; /* Read two nearest output values from the index */ y1 = pYData[(rI) + nCols * (cI + 1)]; y2 = pYData[(rI) + nCols * (cI + 1) + 1u]; /* Calculation of x1 * (1-xfract ) * (1-yfract) and acc is in 3.29(q29) format */ out = ((q31_t) (((q63_t) x1 * (0x7FFFFFFF - xfract)) >> 32)); acc = ((q31_t) (((q63_t) out * (0x7FFFFFFF - yfract)) >> 32)); /* x2 * (xfract) * (1-yfract) in 3.29(q29) and adding to acc */ out = ((q31_t) ((q63_t) x2 * (0x7FFFFFFF - yfract) >> 32)); acc += ((q31_t) ((q63_t) out * (xfract) >> 32)); /* y1 * (1 - xfract) * (yfract) in 3.29(q29) and adding to acc */ out = ((q31_t) ((q63_t) y1 * (0x7FFFFFFF - xfract) >> 32)); acc += ((q31_t) ((q63_t) out * (yfract) >> 32)); /* y2 * (xfract) * (yfract) in 3.29(q29) and adding to acc */ out = ((q31_t) ((q63_t) y2 * (xfract) >> 32)); acc += ((q31_t) ((q63_t) out * (yfract) >> 32)); /* Convert acc to 1.31(q31) format */ return (acc << 2u); } /** * @brief Q15 bilinear interpolation. * @param[in,out] *S points to an instance of the interpolation structure. * @param[in] X interpolation coordinate in 12.20 format. * @param[in] Y interpolation coordinate in 12.20 format. * @return out interpolated value. */ static __INLINE q15_t arm_bilinear_interp_q15( arm_bilinear_interp_instance_q15 * S, q31_t X, q31_t Y) { q63_t acc = 0; /* output */ q31_t out; /* Temporary output */ q15_t x1, x2, y1, y2; /* Nearest output values */ q31_t xfract, yfract; /* X, Y fractional parts */ int32_t rI, cI; /* Row and column indices */ q15_t *pYData = S->pData; /* pointer to output table values */ uint32_t nCols = S->numCols; /* num of rows */ /* Input is in 12.20 format */ /* 12 bits for the table index */ /* Index value calculation */ rI = ((X & 0xFFF00000) >> 20); /* Input is in 12.20 format */ /* 12 bits for the table index */ /* Index value calculation */ cI = ((Y & 0xFFF00000) >> 20); /* Care taken for table outside boundary */ /* Returns zero output when values are outside table boundary */ if(rI < 0 || rI > (S->numRows - 1) || cI < 0 || cI > (S->numCols - 1)) { return (0); } /* 20 bits for the fractional part */ /* xfract should be in 12.20 format */ xfract = (X & 0x000FFFFF); /* Read two nearest output values from the index */ x1 = pYData[(rI) + nCols * (cI)]; x2 = pYData[(rI) + nCols * (cI) + 1u]; /* 20 bits for the fractional part */ /* yfract should be in 12.20 format */ yfract = (Y & 0x000FFFFF); /* Read two nearest output values from the index */ y1 = pYData[(rI) + nCols * (cI + 1)]; y2 = pYData[(rI) + nCols * (cI + 1) + 1u]; /* Calculation of x1 * (1-xfract ) * (1-yfract) and acc is in 13.51 format */ /* x1 is in 1.15(q15), xfract in 12.20 format and out is in 13.35 format */ /* convert 13.35 to 13.31 by right shifting and out is in 1.31 */ out = (q31_t) (((q63_t) x1 * (0xFFFFF - xfract)) >> 4u); acc = ((q63_t) out * (0xFFFFF - yfract)); /* x2 * (xfract) * (1-yfract) in 1.51 and adding to acc */ out = (q31_t) (((q63_t) x2 * (0xFFFFF - yfract)) >> 4u); acc += ((q63_t) out * (xfract)); /* y1 * (1 - xfract) * (yfract) in 1.51 and adding to acc */ out = (q31_t) (((q63_t) y1 * (0xFFFFF - xfract)) >> 4u); acc += ((q63_t) out * (yfract)); /* y2 * (xfract) * (yfract) in 1.51 and adding to acc */ out = (q31_t) (((q63_t) y2 * (xfract)) >> 4u); acc += ((q63_t) out * (yfract)); /* acc is in 13.51 format and down shift acc by 36 times */ /* Convert out to 1.15 format */ return (acc >> 36); } /** * @brief Q7 bilinear interpolation. * @param[in,out] *S points to an instance of the interpolation structure. * @param[in] X interpolation coordinate in 12.20 format. * @param[in] Y interpolation coordinate in 12.20 format. * @return out interpolated value. */ static __INLINE q7_t arm_bilinear_interp_q7( arm_bilinear_interp_instance_q7 * S, q31_t X, q31_t Y) { q63_t acc = 0; /* output */ q31_t out; /* Temporary output */ q31_t xfract, yfract; /* X, Y fractional parts */ q7_t x1, x2, y1, y2; /* Nearest output values */ int32_t rI, cI; /* Row and column indices */ q7_t *pYData = S->pData; /* pointer to output table values */ uint32_t nCols = S->numCols; /* num of rows */ /* Input is in 12.20 format */ /* 12 bits for the table index */ /* Index value calculation */ rI = ((X & 0xFFF00000) >> 20); /* Input is in 12.20 format */ /* 12 bits for the table index */ /* Index value calculation */ cI = ((Y & 0xFFF00000) >> 20); /* Care taken for table outside boundary */ /* Returns zero output when values are outside table boundary */ if(rI < 0 || rI > (S->numRows - 1) || cI < 0 || cI > (S->numCols - 1)) { return (0); } /* 20 bits for the fractional part */ /* xfract should be in 12.20 format */ xfract = (X & 0x000FFFFF); /* Read two nearest output values from the index */ x1 = pYData[(rI) + nCols * (cI)]; x2 = pYData[(rI) + nCols * (cI) + 1u]; /* 20 bits for the fractional part */ /* yfract should be in 12.20 format */ yfract = (Y & 0x000FFFFF); /* Read two nearest output values from the index */ y1 = pYData[(rI) + nCols * (cI + 1)]; y2 = pYData[(rI) + nCols * (cI + 1) + 1u]; /* Calculation of x1 * (1-xfract ) * (1-yfract) and acc is in 16.47 format */ out = ((x1 * (0xFFFFF - xfract))); acc = (((q63_t) out * (0xFFFFF - yfract))); /* x2 * (xfract) * (1-yfract) in 2.22 and adding to acc */ out = ((x2 * (0xFFFFF - yfract))); acc += (((q63_t) out * (xfract))); /* y1 * (1 - xfract) * (yfract) in 2.22 and adding to acc */ out = ((y1 * (0xFFFFF - xfract))); acc += (((q63_t) out * (yfract))); /* y2 * (xfract) * (yfract) in 2.22 and adding to acc */ out = ((y2 * (yfract))); acc += (((q63_t) out * (xfract))); /* acc in 16.47 format and down shift by 40 to convert to 1.7 format */ return (acc >> 40); } /** * @} end of BilinearInterpolate group */ //SMMLAR #define multAcc_32x32_keep32_R(a, x, y) \ a = (q31_t) (((((q63_t) a) << 32) + ((q63_t) x * y) + 0x80000000LL ) >> 32) //SMMLSR #define multSub_32x32_keep32_R(a, x, y) \ a = (q31_t) (((((q63_t) a) << 32) - ((q63_t) x * y) + 0x80000000LL ) >> 32) //SMMULR #define mult_32x32_keep32_R(a, x, y) \ a = (q31_t) (((q63_t) x * y + 0x80000000LL ) >> 32) //SMMLA #define multAcc_32x32_keep32(a, x, y) \ a += (q31_t) (((q63_t) x * y) >> 32) //SMMLS #define multSub_32x32_keep32(a, x, y) \ a -= (q31_t) (((q63_t) x * y) >> 32) //SMMUL #define mult_32x32_keep32(a, x, y) \ a = (q31_t) (((q63_t) x * y ) >> 32) #if defined ( __CC_ARM ) //Keil //Enter low optimization region - place directly above function definition #ifdef ARM_MATH_CM4 #define LOW_OPTIMIZATION_ENTER \ _Pragma ("push") \ _Pragma ("O1") #else #define LOW_OPTIMIZATION_ENTER #endif //Exit low optimization region - place directly after end of function definition #ifdef ARM_MATH_CM4 #define LOW_OPTIMIZATION_EXIT \ _Pragma ("pop") #else #define LOW_OPTIMIZATION_EXIT #endif //Enter low optimization region - place directly above function definition #define IAR_ONLY_LOW_OPTIMIZATION_ENTER //Exit low optimization region - place directly after end of function definition #define IAR_ONLY_LOW_OPTIMIZATION_EXIT #elif defined(__ICCARM__) //IAR //Enter low optimization region - place directly above function definition #ifdef ARM_MATH_CM4 #define LOW_OPTIMIZATION_ENTER \ _Pragma ("optimize=low") #else #define LOW_OPTIMIZATION_ENTER #endif //Exit low optimization region - place directly after end of function definition #define LOW_OPTIMIZATION_EXIT //Enter low optimization region - place directly above function definition #ifdef ARM_MATH_CM4 #define IAR_ONLY_LOW_OPTIMIZATION_ENTER \ _Pragma ("optimize=low") #else #define IAR_ONLY_LOW_OPTIMIZATION_ENTER #endif //Exit low optimization region - place directly after end of function definition #define IAR_ONLY_LOW_OPTIMIZATION_EXIT #elif defined(__GNUC__) #define LOW_OPTIMIZATION_ENTER __attribute__(( optimize("-O1") )) #define LOW_OPTIMIZATION_EXIT #define IAR_ONLY_LOW_OPTIMIZATION_ENTER #define IAR_ONLY_LOW_OPTIMIZATION_EXIT #elif defined(__CSMC__) // Cosmic #define LOW_OPTIMIZATION_ENTER #define LOW_OPTIMIZATION_EXIT #define IAR_ONLY_LOW_OPTIMIZATION_ENTER #define IAR_ONLY_LOW_OPTIMIZATION_EXIT #elif defined(__TASKING__) // TASKING #define LOW_OPTIMIZATION_ENTER #define LOW_OPTIMIZATION_EXIT #define IAR_ONLY_LOW_OPTIMIZATION_ENTER #define IAR_ONLY_LOW_OPTIMIZATION_EXIT #endif #ifdef __cplusplus } #endif #endif /* _ARM_MATH_H */ /** * * End of file. */ ================================================ FILE: Zelig/mbed/TARGET_NUCLEO_F411RE/cmsis.h ================================================ /* mbed Microcontroller Library * A generic CMSIS include header ******************************************************************************* * Copyright (c) 2014, STMicroelectronics * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * 1. Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * 3. Neither the name of 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. ******************************************************************************* */ #ifndef MBED_CMSIS_H #define MBED_CMSIS_H #include "stm32f4xx.h" #include "cmsis_nvic.h" #endif ================================================ FILE: Zelig/mbed/TARGET_NUCLEO_F411RE/cmsis_nvic.h ================================================ /* mbed Microcontroller Library * CMSIS-style functionality to support dynamic vectors ******************************************************************************* * Copyright (c) 2014, STMicroelectronics * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * 1. Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * 3. Neither the name of 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. ******************************************************************************* */ #ifndef MBED_CMSIS_NVIC_H #define MBED_CMSIS_NVIC_H // STM32F411RE // CORE: 16 vectors = 64 bytes from 0x00 to 0x3F // MCU Peripherals: 86 vectors = 344 bytes from 0x40 to 0x197 // Total: 102 vectors = 408 bytes (0x198) to be reserved in RAM #define NVIC_NUM_VECTORS 102 #define NVIC_USER_IRQ_OFFSET 16 #include "cmsis.h" #ifdef __cplusplus extern "C" { #endif void NVIC_SetVector(IRQn_Type IRQn, uint32_t vector); uint32_t NVIC_GetVector(IRQn_Type IRQn); #ifdef __cplusplus } #endif #endif ================================================ FILE: Zelig/mbed/TARGET_NUCLEO_F411RE/core_ca9.h ================================================ /**************************************************************************//** * @file core_ca9.h * @brief CMSIS Cortex-A9 Core Peripheral Access Layer Header File * @version * @date 25 March 2013 * * @note * ******************************************************************************/ /* Copyright (c) 2009 - 2012 ARM LIMITED All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: - Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. - Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. - Neither the name of ARM 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 COPYRIGHT HOLDERS AND 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. ---------------------------------------------------------------------------*/ #if defined ( __ICCARM__ ) #pragma system_include /* treat file as system include file for MISRA check */ #endif #ifdef __cplusplus extern "C" { #endif #ifndef __CORE_CA9_H_GENERIC #define __CORE_CA9_H_GENERIC /** \page CMSIS_MISRA_Exceptions MISRA-C:2004 Compliance Exceptions CMSIS violates the following MISRA-C:2004 rules: \li Required Rule 8.5, object/function definition in header file.
Function definitions in header files are used to allow 'inlining'. \li Required Rule 18.4, declaration of union type or object of union type: '{...}'.
Unions are used for effective representation of core registers. \li Advisory Rule 19.7, Function-like macro defined.
Function-like macros are used to allow more efficient code. */ /******************************************************************************* * CMSIS definitions ******************************************************************************/ /** \ingroup Cortex_A9 @{ */ /* CMSIS CA9 definitions */ #define __CA9_CMSIS_VERSION_MAIN (0x03) /*!< [31:16] CMSIS HAL main version */ #define __CA9_CMSIS_VERSION_SUB (0x10) /*!< [15:0] CMSIS HAL sub version */ #define __CA9_CMSIS_VERSION ((__CA9_CMSIS_VERSION_MAIN << 16) | \ __CA9_CMSIS_VERSION_SUB ) /*!< CMSIS HAL version number */ #define __CORTEX_A (0x09) /*!< Cortex-A Core */ #if defined ( __CC_ARM ) #define __ASM __asm /*!< asm keyword for ARM Compiler */ #define __INLINE __inline /*!< inline keyword for ARM Compiler */ #define __STATIC_INLINE static __inline #define __STATIC_ASM static __asm #elif defined ( __ICCARM__ ) #define __ASM __asm /*!< asm keyword for IAR Compiler */ #define __INLINE inline /*!< inline keyword for IAR Compiler. Only available in High optimization mode! */ #define __STATIC_INLINE static inline #define __STATIC_ASM static __asm #elif defined ( __TMS470__ ) #define __ASM __asm /*!< asm keyword for TI CCS Compiler */ #define __STATIC_INLINE static inline #define __STATIC_ASM static __asm #elif defined ( __GNUC__ ) #define __ASM __asm /*!< asm keyword for GNU Compiler */ #define __INLINE inline /*!< inline keyword for GNU Compiler */ #define __STATIC_INLINE static inline #define __STATIC_ASM static __asm #elif defined ( __TASKING__ ) #define __ASM __asm /*!< asm keyword for TASKING Compiler */ #define __INLINE inline /*!< inline keyword for TASKING Compiler */ #define __STATIC_INLINE static inline #define __STATIC_ASM static __asm #endif /** __FPU_USED indicates whether an FPU is used or not. For this, __FPU_PRESENT has to be checked prior to making use of FPU specific registers and functions. */ #if defined ( __CC_ARM ) #if defined __TARGET_FPU_VFP #if (__FPU_PRESENT == 1) #define __FPU_USED 1 #else #warning "Compiler generates FPU instructions for a device without an FPU (check __FPU_PRESENT)" #define __FPU_USED 0 #endif #else #define __FPU_USED 0 #endif #elif defined ( __ICCARM__ ) #if defined __ARMVFP__ #if (__FPU_PRESENT == 1) #define __FPU_USED 1 #else #warning "Compiler generates FPU instructions for a device without an FPU (check __FPU_PRESENT)" #define __FPU_USED 0 #endif #else #define __FPU_USED 0 #endif #elif defined ( __TMS470__ ) #if defined __TI_VFP_SUPPORT__ #if (__FPU_PRESENT == 1) #define __FPU_USED 1 #else #warning "Compiler generates FPU instructions for a device without an FPU (check __FPU_PRESENT)" #define __FPU_USED 0 #endif #else #define __FPU_USED 0 #endif #elif defined ( __GNUC__ ) #if defined (__VFP_FP__) && !defined(__SOFTFP__) #if (__FPU_PRESENT == 1) #define __FPU_USED 1 #else #warning "Compiler generates FPU instructions for a device without an FPU (check __FPU_PRESENT)" #define __FPU_USED 0 #endif #else #define __FPU_USED 0 #endif #elif defined ( __TASKING__ ) #if defined __FPU_VFP__ #if (__FPU_PRESENT == 1) #define __FPU_USED 1 #else #error "Compiler generates FPU instructions for a device without an FPU (check __FPU_PRESENT)" #define __FPU_USED 0 #endif #else #define __FPU_USED 0 #endif #endif #include /*!< standard types definitions */ #include "core_caInstr.h" /*!< Core Instruction Access */ #include "core_caFunc.h" /*!< Core Function Access */ #include "core_cm4_simd.h" /*!< Compiler specific SIMD Intrinsics */ #endif /* __CORE_CA9_H_GENERIC */ #ifndef __CMSIS_GENERIC #ifndef __CORE_CA9_H_DEPENDANT #define __CORE_CA9_H_DEPENDANT /* check device defines and use defaults */ #if defined __CHECK_DEVICE_DEFINES #ifndef __CA9_REV #define __CA9_REV 0x0000 #warning "__CA9_REV not defined in device header file; using default!" #endif #ifndef __FPU_PRESENT #define __FPU_PRESENT 1 #warning "__FPU_PRESENT not defined in device header file; using default!" #endif #ifndef __Vendor_SysTickConfig #define __Vendor_SysTickConfig 1 #endif #if __Vendor_SysTickConfig == 0 #error "__Vendor_SysTickConfig set to 0, but vendor systick timer must be supplied for Cortex-A9" #endif #endif /* IO definitions (access restrictions to peripheral registers) */ /** \defgroup CMSIS_glob_defs CMSIS Global Defines IO Type Qualifiers are used \li to specify the access to peripheral variables. \li for automatic generation of peripheral register debug information. */ #ifdef __cplusplus #define __I volatile /*!< Defines 'read only' permissions */ #else #define __I volatile const /*!< Defines 'read only' permissions */ #endif #define __O volatile /*!< Defines 'write only' permissions */ #define __IO volatile /*!< Defines 'read / write' permissions */ /*@} end of group Cortex_A9 */ /******************************************************************************* * Register Abstraction ******************************************************************************/ /** \defgroup CMSIS_core_register Defines and Type Definitions \brief Type definitions and defines for Cortex-A processor based devices. */ /** \ingroup CMSIS_core_register \defgroup CMSIS_CORE Status and Control Registers \brief Core Register type definitions. @{ */ /** \brief Union type to access the Application Program Status Register (APSR). */ typedef union { struct { uint32_t _reserved0:16; /*!< bit: 0..15 Reserved */ uint32_t GE:4; /*!< bit: 16..19 Greater than or Equal flags */ uint32_t reserved1:7; /*!< bit: 20..23 Reserved */ uint32_t Q:1; /*!< bit: 27 Saturation condition flag */ uint32_t V:1; /*!< bit: 28 Overflow condition code flag */ uint32_t C:1; /*!< bit: 29 Carry condition code flag */ uint32_t Z:1; /*!< bit: 30 Zero condition code flag */ uint32_t N:1; /*!< bit: 31 Negative condition code flag */ } b; /*!< Structure used for bit access */ uint32_t w; /*!< Type used for word access */ } APSR_Type; /*@} end of group CMSIS_CORE */ /*@} end of CMSIS_Core_FPUFunctions */ #endif /* __CORE_CA9_H_GENERIC */ #endif /* __CMSIS_GENERIC */ #ifdef __cplusplus } #endif ================================================ FILE: Zelig/mbed/TARGET_NUCLEO_F411RE/core_caFunc.h ================================================ /**************************************************************************//** * @file core_caFunc.h * @brief CMSIS Cortex-A Core Function Access Header File * @version V3.10 * @date 30 Oct 2013 * * @note * ******************************************************************************/ /* Copyright (c) 2009 - 2013 ARM LIMITED All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: - Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. - Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. - Neither the name of ARM 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 COPYRIGHT HOLDERS AND 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. ---------------------------------------------------------------------------*/ #ifndef __CORE_CAFUNC_H__ #define __CORE_CAFUNC_H__ /* ########################### Core Function Access ########################### */ /** \ingroup CMSIS_Core_FunctionInterface \defgroup CMSIS_Core_RegAccFunctions CMSIS Core Register Access Functions @{ */ #if defined ( __CC_ARM ) /*------------------RealView Compiler -----------------*/ /* ARM armcc specific functions */ #if (__ARMCC_VERSION < 400677) #error "Please use ARM Compiler Toolchain V4.0.677 or later!" #endif #define MODE_USR 0x10 #define MODE_FIQ 0x11 #define MODE_IRQ 0x12 #define MODE_SVC 0x13 #define MODE_MON 0x16 #define MODE_ABT 0x17 #define MODE_HYP 0x1A #define MODE_UND 0x1B #define MODE_SYS 0x1F /** \brief Get APSR Register This function returns the content of the APSR Register. \return APSR Register value */ __STATIC_INLINE uint32_t __get_APSR(void) { register uint32_t __regAPSR __ASM("apsr"); return(__regAPSR); } /** \brief Get CPSR Register This function returns the content of the CPSR Register. \return CPSR Register value */ __STATIC_INLINE uint32_t __get_CPSR(void) { register uint32_t __regCPSR __ASM("cpsr"); return(__regCPSR); } /** \brief Set Stack Pointer This function assigns the given value to the current stack pointer. \param [in] topOfStack Stack Pointer value to set */ register uint32_t __regSP __ASM("sp"); __STATIC_INLINE void __set_SP(uint32_t topOfStack) { __regSP = topOfStack; } /** \brief Get link register This function returns the value of the link register \return Value of link register */ register uint32_t __reglr __ASM("lr"); __STATIC_INLINE uint32_t __get_LR(void) { return(__reglr); } /** \brief Set link register This function sets the value of the link register \param [in] lr LR value to set */ __STATIC_INLINE void __set_LR(uint32_t lr) { __reglr = lr; } /** \brief Set Process Stack Pointer This function assigns the given value to the USR/SYS Stack Pointer (PSP). \param [in] topOfProcStack USR/SYS Stack Pointer value to set */ __STATIC_ASM void __set_PSP(uint32_t topOfProcStack) { ARM PRESERVE8 BIC R0, R0, #7 ;ensure stack is 8-byte aligned MRS R1, CPSR CPS #MODE_SYS ;no effect in USR mode MOV SP, R0 MSR CPSR_c, R1 ;no effect in USR mode ISB BX LR } /** \brief Set User Mode This function changes the processor state to User Mode */ __STATIC_ASM void __set_CPS_USR(void) { ARM CPS #MODE_USR BX LR } /** \brief Enable FIQ This function enables FIQ interrupts by clearing the F-bit in the CPSR. Can only be executed in Privileged modes. */ #define __enable_fault_irq __enable_fiq /** \brief Disable FIQ This function disables FIQ interrupts by setting the F-bit in the CPSR. Can only be executed in Privileged modes. */ #define __disable_fault_irq __disable_fiq /** \brief Get FPSCR This function returns the current value of the Floating Point Status/Control register. \return Floating Point Status/Control register value */ __STATIC_INLINE uint32_t __get_FPSCR(void) { #if (__FPU_PRESENT == 1) && (__FPU_USED == 1) register uint32_t __regfpscr __ASM("fpscr"); return(__regfpscr); #else return(0); #endif } /** \brief Set FPSCR This function assigns the given value to the Floating Point Status/Control register. \param [in] fpscr Floating Point Status/Control value to set */ __STATIC_INLINE void __set_FPSCR(uint32_t fpscr) { #if (__FPU_PRESENT == 1) && (__FPU_USED == 1) register uint32_t __regfpscr __ASM("fpscr"); __regfpscr = (fpscr); #endif } /** \brief Get FPEXC This function returns the current value of the Floating Point Exception Control register. \return Floating Point Exception Control register value */ __STATIC_INLINE uint32_t __get_FPEXC(void) { #if (__FPU_PRESENT == 1) register uint32_t __regfpexc __ASM("fpexc"); return(__regfpexc); #else return(0); #endif } /** \brief Set FPEXC This function assigns the given value to the Floating Point Exception Control register. \param [in] fpscr Floating Point Exception Control value to set */ __STATIC_INLINE void __set_FPEXC(uint32_t fpexc) { #if (__FPU_PRESENT == 1) register uint32_t __regfpexc __ASM("fpexc"); __regfpexc = (fpexc); #endif } /** \brief Get CPACR This function returns the current value of the Coprocessor Access Control register. \return Coprocessor Access Control register value */ __STATIC_INLINE uint32_t __get_CPACR(void) { register uint32_t __regCPACR __ASM("cp15:0:c1:c0:2"); return __regCPACR; } /** \brief Set CPACR This function assigns the given value to the Coprocessor Access Control register. \param [in] cpacr Coprocessor Acccess Control value to set */ __STATIC_INLINE void __set_CPACR(uint32_t cpacr) { register uint32_t __regCPACR __ASM("cp15:0:c1:c0:2"); __regCPACR = cpacr; __ISB(); } /** \brief Get CBAR This function returns the value of the Configuration Base Address register. \return Configuration Base Address register value */ __STATIC_INLINE uint32_t __get_CBAR() { register uint32_t __regCBAR __ASM("cp15:4:c15:c0:0"); return(__regCBAR); } /** \brief Get TTBR0 This function returns the value of the Translation Table Base Register 0. \return Translation Table Base Register 0 value */ __STATIC_INLINE uint32_t __get_TTBR0() { register uint32_t __regTTBR0 __ASM("cp15:0:c2:c0:0"); return(__regTTBR0); } /** \brief Set TTBR0 This function assigns the given value to the Translation Table Base Register 0. \param [in] ttbr0 Translation Table Base Register 0 value to set */ __STATIC_INLINE void __set_TTBR0(uint32_t ttbr0) { register uint32_t __regTTBR0 __ASM("cp15:0:c2:c0:0"); __regTTBR0 = ttbr0; __ISB(); } /** \brief Get DACR This function returns the value of the Domain Access Control Register. \return Domain Access Control Register value */ __STATIC_INLINE uint32_t __get_DACR() { register uint32_t __regDACR __ASM("cp15:0:c3:c0:0"); return(__regDACR); } /** \brief Set DACR This function assigns the given value to the Domain Access Control Register. \param [in] dacr Domain Access Control Register value to set */ __STATIC_INLINE void __set_DACR(uint32_t dacr) { register uint32_t __regDACR __ASM("cp15:0:c3:c0:0"); __regDACR = dacr; __ISB(); } /******************************** Cache and BTAC enable ****************************************************/ /** \brief Set SCTLR This function assigns the given value to the System Control Register. \param [in] sctlr System Control Register value to set */ __STATIC_INLINE void __set_SCTLR(uint32_t sctlr) { register uint32_t __regSCTLR __ASM("cp15:0:c1:c0:0"); __regSCTLR = sctlr; } /** \brief Get SCTLR This function returns the value of the System Control Register. \return System Control Register value */ __STATIC_INLINE uint32_t __get_SCTLR() { register uint32_t __regSCTLR __ASM("cp15:0:c1:c0:0"); return(__regSCTLR); } /** \brief Enable Caches Enable Caches */ __STATIC_INLINE void __enable_caches(void) { // Set I bit 12 to enable I Cache // Set C bit 2 to enable D Cache __set_SCTLR( __get_SCTLR() | (1 << 12) | (1 << 2)); } /** \brief Disable Caches Disable Caches */ __STATIC_INLINE void __disable_caches(void) { // Clear I bit 12 to disable I Cache // Clear C bit 2 to disable D Cache __set_SCTLR( __get_SCTLR() & ~(1 << 12) & ~(1 << 2)); __ISB(); } /** \brief Enable BTAC Enable BTAC */ __STATIC_INLINE void __enable_btac(void) { // Set Z bit 11 to enable branch prediction __set_SCTLR( __get_SCTLR() | (1 << 11)); __ISB(); } /** \brief Disable BTAC Disable BTAC */ __STATIC_INLINE void __disable_btac(void) { // Clear Z bit 11 to disable branch prediction __set_SCTLR( __get_SCTLR() & ~(1 << 11)); } /** \brief Enable MMU Enable MMU */ __STATIC_INLINE void __enable_mmu(void) { // Set M bit 0 to enable the MMU // Set AFE bit to enable simplified access permissions model // Clear TRE bit to disable TEX remap and A bit to disable strict alignment fault checking __set_SCTLR( (__get_SCTLR() & ~(1 << 28) & ~(1 << 1)) | 1 | (1 << 29)); __ISB(); } /** \brief Disable MMU Disable MMU */ __STATIC_INLINE void __disable_mmu(void) { // Clear M bit 0 to disable the MMU __set_SCTLR( __get_SCTLR() & ~1); __ISB(); } /******************************** TLB maintenance operations ************************************************/ /** \brief Invalidate the whole tlb TLBIALL. Invalidate the whole tlb */ __STATIC_INLINE void __ca9u_inv_tlb_all(void) { register uint32_t __TLBIALL __ASM("cp15:0:c8:c7:0"); __TLBIALL = 0; __DSB(); __ISB(); } /******************************** BTB maintenance operations ************************************************/ /** \brief Invalidate entire branch predictor array BPIALL. Branch Predictor Invalidate All. */ __STATIC_INLINE void __v7_inv_btac(void) { register uint32_t __BPIALL __ASM("cp15:0:c7:c5:6"); __BPIALL = 0; __DSB(); //ensure completion of the invalidation __ISB(); //ensure instruction fetch path sees new state } /******************************** L1 cache operations ******************************************************/ /** \brief Invalidate the whole I$ ICIALLU. Instruction Cache Invalidate All to PoU */ __STATIC_INLINE void __v7_inv_icache_all(void) { register uint32_t __ICIALLU __ASM("cp15:0:c7:c5:0"); __ICIALLU = 0; __DSB(); //ensure completion of the invalidation __ISB(); //ensure instruction fetch path sees new I cache state } /** \brief Clean D$ by MVA DCCMVAC. Data cache clean by MVA to PoC */ __STATIC_INLINE void __v7_clean_dcache_mva(void *va) { register uint32_t __DCCMVAC __ASM("cp15:0:c7:c10:1"); __DCCMVAC = (uint32_t)va; __DMB(); //ensure the ordering of data cache maintenance operations and their effects } /** \brief Invalidate D$ by MVA DCIMVAC. Data cache invalidate by MVA to PoC */ __STATIC_INLINE void __v7_inv_dcache_mva(void *va) { register uint32_t __DCIMVAC __ASM("cp15:0:c7:c6:1"); __DCIMVAC = (uint32_t)va; __DMB(); //ensure the ordering of data cache maintenance operations and their effects } /** \brief Clean and Invalidate D$ by MVA DCCIMVAC. Data cache clean and invalidate by MVA to PoC */ __STATIC_INLINE void __v7_clean_inv_dcache_mva(void *va) { register uint32_t __DCCIMVAC __ASM("cp15:0:c7:c14:1"); __DCCIMVAC = (uint32_t)va; __DMB(); //ensure the ordering of data cache maintenance operations and their effects } /** \brief Clean and Invalidate the entire data or unified cache Generic mechanism for cleaning/invalidating the entire data or unified cache to the point of coherency. */ #pragma push #pragma arm __STATIC_ASM void __v7_all_cache(uint32_t op) { ARM PUSH {R4-R11} MRC p15, 1, R6, c0, c0, 1 // Read CLIDR ANDS R3, R6, #0x07000000 // Extract coherency level MOV R3, R3, LSR #23 // Total cache levels << 1 BEQ Finished // If 0, no need to clean MOV R10, #0 // R10 holds current cache level << 1 Loop1 ADD R2, R10, R10, LSR #1 // R2 holds cache "Set" position MOV R1, R6, LSR R2 // Bottom 3 bits are the Cache-type for this level AND R1, R1, #7 // Isolate those lower 3 bits CMP R1, #2 BLT Skip // No cache or only instruction cache at this level MCR p15, 2, R10, c0, c0, 0 // Write the Cache Size selection register ISB // ISB to sync the change to the CacheSizeID reg MRC p15, 1, R1, c0, c0, 0 // Reads current Cache Size ID register AND R2, R1, #7 // Extract the line length field ADD R2, R2, #4 // Add 4 for the line length offset (log2 16 bytes) LDR R4, =0x3FF ANDS R4, R4, R1, LSR #3 // R4 is the max number on the way size (right aligned) CLZ R5, R4 // R5 is the bit position of the way size increment LDR R7, =0x7FFF ANDS R7, R7, R1, LSR #13 // R7 is the max number of the index size (right aligned) Loop2 MOV R9, R4 // R9 working copy of the max way size (right aligned) Loop3 ORR R11, R10, R9, LSL R5 // Factor in the Way number and cache number into R11 ORR R11, R11, R7, LSL R2 // Factor in the Set number CMP R0, #0 BNE Dccsw MCR p15, 0, R11, c7, c6, 2 // DCISW. Invalidate by Set/Way B cont Dccsw CMP R0, #1 BNE Dccisw MCR p15, 0, R11, c7, c10, 2 // DCCSW. Clean by Set/Way B cont Dccisw MCR p15, 0, R11, c7, c14, 2 // DCCISW. Clean and Invalidate by Set/Way cont SUBS R9, R9, #1 // Decrement the Way number BGE Loop3 SUBS R7, R7, #1 // Decrement the Set number BGE Loop2 Skip ADD R10, R10, #2 // Increment the cache number CMP R3, R10 BGT Loop1 Finished DSB POP {R4-R11} BX lr } #pragma pop /** \brief Invalidate the whole D$ DCISW. Invalidate by Set/Way */ __STATIC_INLINE void __v7_inv_dcache_all(void) { __v7_all_cache(0); } /** \brief Clean the whole D$ DCCSW. Clean by Set/Way */ __STATIC_INLINE void __v7_clean_dcache_all(void) { __v7_all_cache(1); } /** \brief Clean and invalidate the whole D$ DCCISW. Clean and Invalidate by Set/Way */ __STATIC_INLINE void __v7_clean_inv_dcache_all(void) { __v7_all_cache(2); } #include "core_ca_mmu.h" #elif (defined (__ICCARM__)) /*---------------- ICC Compiler ---------------------*/ #error IAR Compiler support not implemented for Cortex-A #elif (defined (__GNUC__)) /*------------------ GNU Compiler ---------------------*/ /* GNU gcc specific functions */ #define MODE_USR 0x10 #define MODE_FIQ 0x11 #define MODE_IRQ 0x12 #define MODE_SVC 0x13 #define MODE_MON 0x16 #define MODE_ABT 0x17 #define MODE_HYP 0x1A #define MODE_UND 0x1B #define MODE_SYS 0x1F __attribute__( ( always_inline ) ) __STATIC_INLINE void __enable_irq(void) { __ASM volatile ("cpsie i"); } /** \brief Disable IRQ Interrupts This function disables IRQ interrupts by setting the I-bit in the CPSR. Can only be executed in Privileged modes. */ __attribute__( ( always_inline ) ) __STATIC_INLINE uint32_t __disable_irq(void) { uint32_t result; __ASM volatile ("mrs %0, cpsr" : "=r" (result)); __ASM volatile ("cpsid i"); return(result & 0x80); } /** \brief Get APSR Register This function returns the content of the APSR Register. \return APSR Register value */ __attribute__( ( always_inline ) ) __STATIC_INLINE uint32_t __get_APSR(void) { #if 1 register uint32_t __regAPSR; __ASM volatile ("mrs %0, apsr" : "=r" (__regAPSR) ); #else register uint32_t __regAPSR __ASM("apsr"); #endif return(__regAPSR); } /** \brief Get CPSR Register This function returns the content of the CPSR Register. \return CPSR Register value */ __attribute__( ( always_inline ) ) __STATIC_INLINE uint32_t __get_CPSR(void) { #if 1 register uint32_t __regCPSR; __ASM volatile ("mrs %0, cpsr" : "=r" (__regCPSR)); #else register uint32_t __regCPSR __ASM("cpsr"); #endif return(__regCPSR); } #if 0 /** \brief Set Stack Pointer This function assigns the given value to the current stack pointer. \param [in] topOfStack Stack Pointer value to set */ __attribute__( ( always_inline ) ) __STATIC_INLINE void __set_SP(uint32_t topOfStack) { register uint32_t __regSP __ASM("sp"); __regSP = topOfStack; } #endif /** \brief Get link register This function returns the value of the link register \return Value of link register */ __attribute__( ( always_inline ) ) __STATIC_INLINE uint32_t __get_LR(void) { register uint32_t __reglr __ASM("lr"); return(__reglr); } #if 0 /** \brief Set link register This function sets the value of the link register \param [in] lr LR value to set */ __attribute__( ( always_inline ) ) __STATIC_INLINE void __set_LR(uint32_t lr) { register uint32_t __reglr __ASM("lr"); __reglr = lr; } #endif /** \brief Set Process Stack Pointer This function assigns the given value to the USR/SYS Stack Pointer (PSP). \param [in] topOfProcStack USR/SYS Stack Pointer value to set */ __attribute__( ( always_inline ) ) __STATIC_INLINE void __set_PSP(uint32_t topOfProcStack) { __asm__ volatile ( ".ARM;" ".eabi_attribute Tag_ABI_align8_preserved,1;" "BIC R0, R0, #7;" /* ;ensure stack is 8-byte aligned */ "MRS R1, CPSR;" "CPS %0;" /* ;no effect in USR mode */ "MOV SP, R0;" "MSR CPSR_c, R1;" /* ;no effect in USR mode */ "ISB;" //"BX LR;" : : "i"(MODE_SYS) : "r0", "r1"); return; } /** \brief Set User Mode This function changes the processor state to User Mode */ __attribute__( ( always_inline ) ) __STATIC_INLINE void __set_CPS_USR(void) { __asm__ volatile ( ".ARM;" "CPS %0;" //"BX LR;" : : "i"(MODE_USR) : ); return; } /** \brief Enable FIQ This function enables FIQ interrupts by clearing the F-bit in the CPSR. Can only be executed in Privileged modes. */ #define __enable_fault_irq() __asm__ volatile ("cpsie f") /** \brief Disable FIQ This function disables FIQ interrupts by setting the F-bit in the CPSR. Can only be executed in Privileged modes. */ #define __disable_fault_irq() __asm__ volatile ("cpsid f") /** \brief Get FPSCR This function returns the current value of the Floating Point Status/Control register. \return Floating Point Status/Control register value */ __attribute__( ( always_inline ) ) __STATIC_INLINE uint32_t __get_FPSCR(void) { #if (__FPU_PRESENT == 1) && (__FPU_USED == 1) #if 1 uint32_t result; __ASM volatile ("vmrs %0, fpscr" : "=r" (result) ); return (result); #else register uint32_t __regfpscr __ASM("fpscr"); return(__regfpscr); #endif #else return(0); #endif } /** \brief Set FPSCR This function assigns the given value to the Floating Point Status/Control register. \param [in] fpscr Floating Point Status/Control value to set */ __attribute__( ( always_inline ) ) __STATIC_INLINE void __set_FPSCR(uint32_t fpscr) { #if (__FPU_PRESENT == 1) && (__FPU_USED == 1) #if 1 __ASM volatile ("vmsr fpscr, %0" : : "r" (fpscr) ); #else register uint32_t __regfpscr __ASM("fpscr"); __regfpscr = (fpscr); #endif #endif } /** \brief Get FPEXC This function returns the current value of the Floating Point Exception Control register. \return Floating Point Exception Control register value */ __attribute__( ( always_inline ) ) __STATIC_INLINE uint32_t __get_FPEXC(void) { #if (__FPU_PRESENT == 1) #if 1 uint32_t result; __ASM volatile ("vmrs %0, fpexc" : "=r" (result)); return (result); #else register uint32_t __regfpexc __ASM("fpexc"); return(__regfpexc); #endif #else return(0); #endif } /** \brief Set FPEXC This function assigns the given value to the Floating Point Exception Control register. \param [in] fpscr Floating Point Exception Control value to set */ __attribute__( ( always_inline ) ) __STATIC_INLINE void __set_FPEXC(uint32_t fpexc) { #if (__FPU_PRESENT == 1) #if 1 __ASM volatile ("vmsr fpexc, %0" : : "r" (fpexc)); #else register uint32_t __regfpexc __ASM("fpexc"); __regfpexc = (fpexc); #endif #endif } /** \brief Get CPACR This function returns the current value of the Coprocessor Access Control register. \return Coprocessor Access Control register value */ __attribute__( ( always_inline ) ) __STATIC_INLINE uint32_t __get_CPACR(void) { #if 1 register uint32_t __regCPACR; __ASM volatile ("mrc p15, 0, %0, c1, c0, 2" : "=r" (__regCPACR)); #else register uint32_t __regCPACR __ASM("cp15:0:c1:c0:2"); #endif return __regCPACR; } /** \brief Set CPACR This function assigns the given value to the Coprocessor Access Control register. \param [in] cpacr Coprocessor Acccess Control value to set */ __attribute__( ( always_inline ) ) __STATIC_INLINE void __set_CPACR(uint32_t cpacr) { #if 1 __ASM volatile ("mcr p15, 0, %0, c1, c0, 2" : : "r" (cpacr)); #else register uint32_t __regCPACR __ASM("cp15:0:c1:c0:2"); __regCPACR = cpacr; #endif __ISB(); } /** \brief Get CBAR This function returns the value of the Configuration Base Address register. \return Configuration Base Address register value */ __attribute__( ( always_inline ) ) __STATIC_INLINE uint32_t __get_CBAR() { #if 1 register uint32_t __regCBAR; __ASM volatile ("mrc p15, 4, %0, c15, c0, 0" : "=r" (__regCBAR)); #else register uint32_t __regCBAR __ASM("cp15:4:c15:c0:0"); #endif return(__regCBAR); } /** \brief Get TTBR0 This function returns the value of the Translation Table Base Register 0. \return Translation Table Base Register 0 value */ __attribute__( ( always_inline ) ) __STATIC_INLINE uint32_t __get_TTBR0() { #if 1 register uint32_t __regTTBR0; __ASM volatile ("mrc p15, 0, %0, c2, c0, 0" : "=r" (__regTTBR0)); #else register uint32_t __regTTBR0 __ASM("cp15:0:c2:c0:0"); #endif return(__regTTBR0); } /** \brief Set TTBR0 This function assigns the given value to the Translation Table Base Register 0. \param [in] ttbr0 Translation Table Base Register 0 value to set */ __attribute__( ( always_inline ) ) __STATIC_INLINE void __set_TTBR0(uint32_t ttbr0) { #if 1 __ASM volatile ("mcr p15, 0, %0, c2, c0, 0" : : "r" (ttbr0)); #else register uint32_t __regTTBR0 __ASM("cp15:0:c2:c0:0"); __regTTBR0 = ttbr0; #endif __ISB(); } /** \brief Get DACR This function returns the value of the Domain Access Control Register. \return Domain Access Control Register value */ __attribute__( ( always_inline ) ) __STATIC_INLINE uint32_t __get_DACR() { #if 1 register uint32_t __regDACR; __ASM volatile ("mrc p15, 0, %0, c3, c0, 0" : "=r" (__regDACR)); #else register uint32_t __regDACR __ASM("cp15:0:c3:c0:0"); #endif return(__regDACR); } /** \brief Set DACR This function assigns the given value to the Domain Access Control Register. \param [in] dacr Domain Access Control Register value to set */ __attribute__( ( always_inline ) ) __STATIC_INLINE void __set_DACR(uint32_t dacr) { #if 1 __ASM volatile ("mcr p15, 0, %0, c3, c0, 0" : : "r" (dacr)); #else register uint32_t __regDACR __ASM("cp15:0:c3:c0:0"); __regDACR = dacr; #endif __ISB(); } /******************************** Cache and BTAC enable ****************************************************/ /** \brief Set SCTLR This function assigns the given value to the System Control Register. \param [in] sctlr System Control Register value to set */ __attribute__( ( always_inline ) ) __STATIC_INLINE void __set_SCTLR(uint32_t sctlr) { #if 1 __ASM volatile ("mcr p15, 0, %0, c1, c0, 0" : : "r" (sctlr)); #else register uint32_t __regSCTLR __ASM("cp15:0:c1:c0:0"); __regSCTLR = sctlr; #endif } /** \brief Get SCTLR This function returns the value of the System Control Register. \return System Control Register value */ __attribute__( ( always_inline ) ) __STATIC_INLINE uint32_t __get_SCTLR() { #if 1 register uint32_t __regSCTLR; __ASM volatile ("mrc p15, 0, %0, c1, c0, 0" : "=r" (__regSCTLR)); #else register uint32_t __regSCTLR __ASM("cp15:0:c1:c0:0"); #endif return(__regSCTLR); } /** \brief Enable Caches Enable Caches */ __attribute__( ( always_inline ) ) __STATIC_INLINE void __enable_caches(void) { // Set I bit 12 to enable I Cache // Set C bit 2 to enable D Cache __set_SCTLR( __get_SCTLR() | (1 << 12) | (1 << 2)); } /** \brief Disable Caches Disable Caches */ __attribute__( ( always_inline ) ) __STATIC_INLINE void __disable_caches(void) { // Clear I bit 12 to disable I Cache // Clear C bit 2 to disable D Cache __set_SCTLR( __get_SCTLR() & ~(1 << 12) & ~(1 << 2)); __ISB(); } /** \brief Enable BTAC Enable BTAC */ __attribute__( ( always_inline ) ) __STATIC_INLINE void __enable_btac(void) { // Set Z bit 11 to enable branch prediction __set_SCTLR( __get_SCTLR() | (1 << 11)); __ISB(); } /** \brief Disable BTAC Disable BTAC */ __attribute__( ( always_inline ) ) __STATIC_INLINE void __disable_btac(void) { // Clear Z bit 11 to disable branch prediction __set_SCTLR( __get_SCTLR() & ~(1 << 11)); } /** \brief Enable MMU Enable MMU */ __attribute__( ( always_inline ) ) __STATIC_INLINE void __enable_mmu(void) { // Set M bit 0 to enable the MMU // Set AFE bit to enable simplified access permissions model // Clear TRE bit to disable TEX remap and A bit to disable strict alignment fault checking __set_SCTLR( (__get_SCTLR() & ~(1 << 28) & ~(1 << 1)) | 1 | (1 << 29)); __ISB(); } /** \brief Disable MMU Disable MMU */ __attribute__( ( always_inline ) ) __STATIC_INLINE void __disable_mmu(void) { // Clear M bit 0 to disable the MMU __set_SCTLR( __get_SCTLR() & ~1); __ISB(); } /******************************** TLB maintenance operations ************************************************/ /** \brief Invalidate the whole tlb TLBIALL. Invalidate the whole tlb */ __attribute__( ( always_inline ) ) __STATIC_INLINE void __ca9u_inv_tlb_all(void) { #if 1 __ASM volatile ("mcr p15, 0, %0, c8, c7, 0" : : "r" (0)); #else register uint32_t __TLBIALL __ASM("cp15:0:c8:c7:0"); __TLBIALL = 0; #endif __DSB(); __ISB(); } /******************************** BTB maintenance operations ************************************************/ /** \brief Invalidate entire branch predictor array BPIALL. Branch Predictor Invalidate All. */ __attribute__( ( always_inline ) ) __STATIC_INLINE void __v7_inv_btac(void) { #if 1 __ASM volatile ("mcr p15, 0, %0, c7, c5, 6" : : "r" (0)); #else register uint32_t __BPIALL __ASM("cp15:0:c7:c5:6"); __BPIALL = 0; #endif __DSB(); //ensure completion of the invalidation __ISB(); //ensure instruction fetch path sees new state } /******************************** L1 cache operations ******************************************************/ /** \brief Invalidate the whole I$ ICIALLU. Instruction Cache Invalidate All to PoU */ __attribute__( ( always_inline ) ) __STATIC_INLINE void __v7_inv_icache_all(void) { #if 1 __ASM volatile ("mcr p15, 0, %0, c7, c5, 0" : : "r" (0)); #else register uint32_t __ICIALLU __ASM("cp15:0:c7:c5:0"); __ICIALLU = 0; #endif __DSB(); //ensure completion of the invalidation __ISB(); //ensure instruction fetch path sees new I cache state } /** \brief Clean D$ by MVA DCCMVAC. Data cache clean by MVA to PoC */ __attribute__( ( always_inline ) ) __STATIC_INLINE void __v7_clean_dcache_mva(void *va) { #if 1 __ASM volatile ("mcr p15, 0, %0, c7, c10, 1" : : "r" ((uint32_t)va)); #else register uint32_t __DCCMVAC __ASM("cp15:0:c7:c10:1"); __DCCMVAC = (uint32_t)va; #endif __DMB(); //ensure the ordering of data cache maintenance operations and their effects } /** \brief Invalidate D$ by MVA DCIMVAC. Data cache invalidate by MVA to PoC */ __attribute__( ( always_inline ) ) __STATIC_INLINE void __v7_inv_dcache_mva(void *va) { #if 1 __ASM volatile ("mcr p15, 0, %0, c7, c6, 1" : : "r" ((uint32_t)va)); #else register uint32_t __DCIMVAC __ASM("cp15:0:c7:c6:1"); __DCIMVAC = (uint32_t)va; #endif __DMB(); //ensure the ordering of data cache maintenance operations and their effects } /** \brief Clean and Invalidate D$ by MVA DCCIMVAC. Data cache clean and invalidate by MVA to PoC */ __attribute__( ( always_inline ) ) __STATIC_INLINE void __v7_clean_inv_dcache_mva(void *va) { #if 1 __ASM volatile ("mcr p15, 0, %0, c7, c14, 1" : : "r" ((uint32_t)va)); #else register uint32_t __DCCIMVAC __ASM("cp15:0:c7:c14:1"); __DCCIMVAC = (uint32_t)va; #endif __DMB(); //ensure the ordering of data cache maintenance operations and their effects } /** \brief Clean and Invalidate the entire data or unified cache Generic mechanism for cleaning/invalidating the entire data or unified cache to the point of coherency. */ extern void __v7_all_cache(uint32_t op); /** \brief Invalidate the whole D$ DCISW. Invalidate by Set/Way */ __attribute__( ( always_inline ) ) __STATIC_INLINE void __v7_inv_dcache_all(void) { __v7_all_cache(0); } /** \brief Clean the whole D$ DCCSW. Clean by Set/Way */ __attribute__( ( always_inline ) ) __STATIC_INLINE void __v7_clean_dcache_all(void) { __v7_all_cache(1); } /** \brief Clean and invalidate the whole D$ DCCISW. Clean and Invalidate by Set/Way */ __attribute__( ( always_inline ) ) __STATIC_INLINE void __v7_clean_inv_dcache_all(void) { __v7_all_cache(2); } #include "core_ca_mmu.h" #elif (defined (__TASKING__)) /*--------------- TASKING Compiler -----------------*/ #error TASKING Compiler support not implemented for Cortex-A #endif /*@} end of CMSIS_Core_RegAccFunctions */ #endif /* __CORE_CAFUNC_H__ */ ================================================ FILE: Zelig/mbed/TARGET_NUCLEO_F411RE/core_caInstr.h ================================================ /**************************************************************************//** * @file core_caInstr.h * @brief CMSIS Cortex-A9 Core Peripheral Access Layer Header File * @version * @date 04. December 2012 * * @note * ******************************************************************************/ /* Copyright (c) 2009 - 2012 ARM LIMITED All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: - Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. - Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. - Neither the name of ARM 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 COPYRIGHT HOLDERS AND 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. ---------------------------------------------------------------------------*/ #ifndef __CORE_CAINSTR_H__ #define __CORE_CAINSTR_H__ #define __CORTEX_M 0x3 #include "core_cmInstr.h" #undef __CORTEX_M #endif ================================================ FILE: Zelig/mbed/TARGET_NUCLEO_F411RE/core_ca_mmu.h ================================================ ;/**************************************************************************//** ; * @file core_ca_mmu.h ; * @brief MMU Startup File for A9_MP Device Series ; * @version V1.01 ; * @date 10 Sept 2014 ; * ; * @note ; * ; ******************************************************************************/ ;/* Copyright (c) 2012-2014 ARM LIMITED ; ; All rights reserved. ; Redistribution and use in source and binary forms, with or without ; modification, are permitted provided that the following conditions are met: ; - Redistributions of source code must retain the above copyright ; notice, this list of conditions and the following disclaimer. ; - Redistributions in binary form must reproduce the above copyright ; notice, this list of conditions and the following disclaimer in the ; documentation and/or other materials provided with the distribution. ; - Neither the name of ARM 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 COPYRIGHT HOLDERS AND CONTRIBUTORS BE ; LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR ; CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF ; SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS ; INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN ; CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ; ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE ; POSSIBILITY OF SUCH DAMAGE. ; ---------------------------------------------------------------------------*/ #ifdef __cplusplus extern "C" { #endif #ifndef _MMU_FUNC_H #define _MMU_FUNC_H #define SECTION_DESCRIPTOR (0x2) #define SECTION_MASK (0xFFFFFFFC) #define SECTION_TEXCB_MASK (0xFFFF8FF3) #define SECTION_B_SHIFT (2) #define SECTION_C_SHIFT (3) #define SECTION_TEX0_SHIFT (12) #define SECTION_TEX1_SHIFT (13) #define SECTION_TEX2_SHIFT (14) #define SECTION_XN_MASK (0xFFFFFFEF) #define SECTION_XN_SHIFT (4) #define SECTION_DOMAIN_MASK (0xFFFFFE1F) #define SECTION_DOMAIN_SHIFT (5) #define SECTION_P_MASK (0xFFFFFDFF) #define SECTION_P_SHIFT (9) #define SECTION_AP_MASK (0xFFFF73FF) #define SECTION_AP_SHIFT (10) #define SECTION_AP2_SHIFT (15) #define SECTION_S_MASK (0xFFFEFFFF) #define SECTION_S_SHIFT (16) #define SECTION_NG_MASK (0xFFFDFFFF) #define SECTION_NG_SHIFT (17) #define SECTION_NS_MASK (0xFFF7FFFF) #define SECTION_NS_SHIFT (19) #define PAGE_L1_DESCRIPTOR (0x1) #define PAGE_L1_MASK (0xFFFFFFFC) #define PAGE_L2_4K_DESC (0x2) #define PAGE_L2_4K_MASK (0xFFFFFFFD) #define PAGE_L2_64K_DESC (0x1) #define PAGE_L2_64K_MASK (0xFFFFFFFC) #define PAGE_4K_TEXCB_MASK (0xFFFFFE33) #define PAGE_4K_B_SHIFT (2) #define PAGE_4K_C_SHIFT (3) #define PAGE_4K_TEX0_SHIFT (6) #define PAGE_4K_TEX1_SHIFT (7) #define PAGE_4K_TEX2_SHIFT (8) #define PAGE_64K_TEXCB_MASK (0xFFFF8FF3) #define PAGE_64K_B_SHIFT (2) #define PAGE_64K_C_SHIFT (3) #define PAGE_64K_TEX0_SHIFT (12) #define PAGE_64K_TEX1_SHIFT (13) #define PAGE_64K_TEX2_SHIFT (14) #define PAGE_TEXCB_MASK (0xFFFF8FF3) #define PAGE_B_SHIFT (2) #define PAGE_C_SHIFT (3) #define PAGE_TEX_SHIFT (12) #define PAGE_XN_4K_MASK (0xFFFFFFFE) #define PAGE_XN_4K_SHIFT (0) #define PAGE_XN_64K_MASK (0xFFFF7FFF) #define PAGE_XN_64K_SHIFT (15) #define PAGE_DOMAIN_MASK (0xFFFFFE1F) #define PAGE_DOMAIN_SHIFT (5) #define PAGE_P_MASK (0xFFFFFDFF) #define PAGE_P_SHIFT (9) #define PAGE_AP_MASK (0xFFFFFDCF) #define PAGE_AP_SHIFT (4) #define PAGE_AP2_SHIFT (9) #define PAGE_S_MASK (0xFFFFFBFF) #define PAGE_S_SHIFT (10) #define PAGE_NG_MASK (0xFFFFF7FF) #define PAGE_NG_SHIFT (11) #define PAGE_NS_MASK (0xFFFFFFF7) #define PAGE_NS_SHIFT (3) #define OFFSET_1M (0x00100000) #define OFFSET_64K (0x00010000) #define OFFSET_4K (0x00001000) #define DESCRIPTOR_FAULT (0x00000000) /* ########################### MMU Function Access ########################### */ /** \ingroup MMU_FunctionInterface \defgroup MMU_Functions MMU Functions Interface @{ */ /* Attributes enumerations */ /* Region size attributes */ typedef enum { SECTION, PAGE_4k, PAGE_64k, } mmu_region_size_Type; /* Region type attributes */ typedef enum { NORMAL, DEVICE, SHARED_DEVICE, NON_SHARED_DEVICE, STRONGLY_ORDERED } mmu_memory_Type; /* Region cacheability attributes */ typedef enum { NON_CACHEABLE, WB_WA, WT, WB_NO_WA, } mmu_cacheability_Type; /* Region parity check attributes */ typedef enum { ECC_DISABLED, ECC_ENABLED, } mmu_ecc_check_Type; /* Region execution attributes */ typedef enum { EXECUTE, NON_EXECUTE, } mmu_execute_Type; /* Region global attributes */ typedef enum { GLOBAL, NON_GLOBAL, } mmu_global_Type; /* Region shareability attributes */ typedef enum { NON_SHARED, SHARED, } mmu_shared_Type; /* Region security attributes */ typedef enum { SECURE, NON_SECURE, } mmu_secure_Type; /* Region access attributes */ typedef enum { NO_ACCESS, RW, READ, } mmu_access_Type; /* Memory Region definition */ typedef struct RegionStruct { mmu_region_size_Type rg_t; mmu_memory_Type mem_t; uint8_t domain; mmu_cacheability_Type inner_norm_t; mmu_cacheability_Type outer_norm_t; mmu_ecc_check_Type e_t; mmu_execute_Type xn_t; mmu_global_Type g_t; mmu_secure_Type sec_t; mmu_access_Type priv_t; mmu_access_Type user_t; mmu_shared_Type sh_t; } mmu_region_attributes_Type; /** \brief Set section execution-never attribute The function sets section execution-never attribute \param [out] descriptor_l1 L1 descriptor. \param [in] xn Section execution-never attribute : EXECUTE , NON_EXECUTE. \return 0 */ __STATIC_INLINE int __xn_section(uint32_t *descriptor_l1, mmu_execute_Type xn) { *descriptor_l1 &= SECTION_XN_MASK; *descriptor_l1 |= ((xn & 0x1) << SECTION_XN_SHIFT); return 0; } /** \brief Set section domain The function sets section domain \param [out] descriptor_l1 L1 descriptor. \param [in] domain Section domain \return 0 */ __STATIC_INLINE int __domain_section(uint32_t *descriptor_l1, uint8_t domain) { *descriptor_l1 &= SECTION_DOMAIN_MASK; *descriptor_l1 |= ((domain & 0xF) << SECTION_DOMAIN_SHIFT); return 0; } /** \brief Set section parity check The function sets section parity check \param [out] descriptor_l1 L1 descriptor. \param [in] p_bit Parity check: ECC_DISABLED, ECC_ENABLED \return 0 */ __STATIC_INLINE int __p_section(uint32_t *descriptor_l1, mmu_ecc_check_Type p_bit) { *descriptor_l1 &= SECTION_P_MASK; *descriptor_l1 |= ((p_bit & 0x1) << SECTION_P_SHIFT); return 0; } /** \brief Set section access privileges The function sets section access privileges \param [out] descriptor_l1 L1 descriptor. \param [in] user User Level Access: NO_ACCESS, RW, READ \param [in] priv Privilege Level Access: NO_ACCESS, RW, READ \param [in] afe Access flag enable \return 0 */ __STATIC_INLINE int __ap_section(uint32_t *descriptor_l1, mmu_access_Type user, mmu_access_Type priv, uint32_t afe) { uint32_t ap = 0; if (afe == 0) { //full access if ((priv == NO_ACCESS) && (user == NO_ACCESS)) { ap = 0x0; } else if ((priv == RW) && (user == NO_ACCESS)) { ap = 0x1; } else if ((priv == RW) && (user == READ)) { ap = 0x2; } else if ((priv == RW) && (user == RW)) { ap = 0x3; } else if ((priv == READ) && (user == NO_ACCESS)) { ap = 0x5; } else if ((priv == READ) && (user == READ)) { ap = 0x7; } } else { //Simplified access if ((priv == RW) && (user == NO_ACCESS)) { ap = 0x1; } else if ((priv == RW) && (user == RW)) { ap = 0x3; } else if ((priv == READ) && (user == NO_ACCESS)) { ap = 0x5; } else if ((priv == READ) && (user == READ)) { ap = 0x7; } } *descriptor_l1 &= SECTION_AP_MASK; *descriptor_l1 |= (ap & 0x3) << SECTION_AP_SHIFT; *descriptor_l1 |= ((ap & 0x4)>>2) << SECTION_AP2_SHIFT; return 0; } /** \brief Set section shareability The function sets section shareability \param [out] descriptor_l1 L1 descriptor. \param [in] s_bit Section shareability: NON_SHARED, SHARED \return 0 */ __STATIC_INLINE int __shared_section(uint32_t *descriptor_l1, mmu_shared_Type s_bit) { *descriptor_l1 &= SECTION_S_MASK; *descriptor_l1 |= ((s_bit & 0x1) << SECTION_S_SHIFT); return 0; } /** \brief Set section Global attribute The function sets section Global attribute \param [out] descriptor_l1 L1 descriptor. \param [in] g_bit Section attribute: GLOBAL, NON_GLOBAL \return 0 */ __STATIC_INLINE int __global_section(uint32_t *descriptor_l1, mmu_global_Type g_bit) { *descriptor_l1 &= SECTION_NG_MASK; *descriptor_l1 |= ((g_bit & 0x1) << SECTION_NG_SHIFT); return 0; } /** \brief Set section Security attribute The function sets section Global attribute \param [out] descriptor_l1 L1 descriptor. \param [in] s_bit Section Security attribute: SECURE, NON_SECURE \return 0 */ __STATIC_INLINE int __secure_section(uint32_t *descriptor_l1, mmu_secure_Type s_bit) { *descriptor_l1 &= SECTION_NS_MASK; *descriptor_l1 |= ((s_bit & 0x1) << SECTION_NS_SHIFT); return 0; } /* Page 4k or 64k */ /** \brief Set 4k/64k page execution-never attribute The function sets 4k/64k page execution-never attribute \param [out] descriptor_l2 L2 descriptor. \param [in] xn Page execution-never attribute : EXECUTE , NON_EXECUTE. \param [in] page Page size: PAGE_4k, PAGE_64k, \return 0 */ __STATIC_INLINE int __xn_page(uint32_t *descriptor_l2, mmu_execute_Type xn, mmu_region_size_Type page) { if (page == PAGE_4k) { *descriptor_l2 &= PAGE_XN_4K_MASK; *descriptor_l2 |= ((xn & 0x1) << PAGE_XN_4K_SHIFT); } else { *descriptor_l2 &= PAGE_XN_64K_MASK; *descriptor_l2 |= ((xn & 0x1) << PAGE_XN_64K_SHIFT); } return 0; } /** \brief Set 4k/64k page domain The function sets 4k/64k page domain \param [out] descriptor_l1 L1 descriptor. \param [in] domain Page domain \return 0 */ __STATIC_INLINE int __domain_page(uint32_t *descriptor_l1, uint8_t domain) { *descriptor_l1 &= PAGE_DOMAIN_MASK; *descriptor_l1 |= ((domain & 0xf) << PAGE_DOMAIN_SHIFT); return 0; } /** \brief Set 4k/64k page parity check The function sets 4k/64k page parity check \param [out] descriptor_l1 L1 descriptor. \param [in] p_bit Parity check: ECC_DISABLED, ECC_ENABLED \return 0 */ __STATIC_INLINE int __p_page(uint32_t *descriptor_l1, mmu_ecc_check_Type p_bit) { *descriptor_l1 &= SECTION_P_MASK; *descriptor_l1 |= ((p_bit & 0x1) << SECTION_P_SHIFT); return 0; } /** \brief Set 4k/64k page access privileges The function sets 4k/64k page access privileges \param [out] descriptor_l2 L2 descriptor. \param [in] user User Level Access: NO_ACCESS, RW, READ \param [in] priv Privilege Level Access: NO_ACCESS, RW, READ \param [in] afe Access flag enable \return 0 */ __STATIC_INLINE int __ap_page(uint32_t *descriptor_l2, mmu_access_Type user, mmu_access_Type priv, uint32_t afe) { uint32_t ap = 0; if (afe == 0) { //full access if ((priv == NO_ACCESS) && (user == NO_ACCESS)) { ap = 0x0; } else if ((priv == RW) && (user == NO_ACCESS)) { ap = 0x1; } else if ((priv == RW) && (user == READ)) { ap = 0x2; } else if ((priv == RW) && (user == RW)) { ap = 0x3; } else if ((priv == READ) && (user == NO_ACCESS)) { ap = 0x5; } else if ((priv == READ) && (user == READ)) { ap = 0x6; } } else { //Simplified access if ((priv == RW) && (user == NO_ACCESS)) { ap = 0x1; } else if ((priv == RW) && (user == RW)) { ap = 0x3; } else if ((priv == READ) && (user == NO_ACCESS)) { ap = 0x5; } else if ((priv == READ) && (user == READ)) { ap = 0x7; } } *descriptor_l2 &= PAGE_AP_MASK; *descriptor_l2 |= (ap & 0x3) << PAGE_AP_SHIFT; *descriptor_l2 |= ((ap & 0x4)>>2) << PAGE_AP2_SHIFT; return 0; } /** \brief Set 4k/64k page shareability The function sets 4k/64k page shareability \param [out] descriptor_l2 L2 descriptor. \param [in] s_bit 4k/64k page shareability: NON_SHARED, SHARED \return 0 */ __STATIC_INLINE int __shared_page(uint32_t *descriptor_l2, mmu_shared_Type s_bit) { *descriptor_l2 &= PAGE_S_MASK; *descriptor_l2 |= ((s_bit & 0x1) << PAGE_S_SHIFT); return 0; } /** \brief Set 4k/64k page Global attribute The function sets 4k/64k page Global attribute \param [out] descriptor_l2 L2 descriptor. \param [in] g_bit 4k/64k page attribute: GLOBAL, NON_GLOBAL \return 0 */ __STATIC_INLINE int __global_page(uint32_t *descriptor_l2, mmu_global_Type g_bit) { *descriptor_l2 &= PAGE_NG_MASK; *descriptor_l2 |= ((g_bit & 0x1) << PAGE_NG_SHIFT); return 0; } /** \brief Set 4k/64k page Security attribute The function sets 4k/64k page Global attribute \param [out] descriptor_l1 L1 descriptor. \param [in] s_bit 4k/64k page Security attribute: SECURE, NON_SECURE \return 0 */ __STATIC_INLINE int __secure_page(uint32_t *descriptor_l1, mmu_secure_Type s_bit) { *descriptor_l1 &= PAGE_NS_MASK; *descriptor_l1 |= ((s_bit & 0x1) << PAGE_NS_SHIFT); return 0; } /** \brief Set Section memory attributes The function sets section memory attributes \param [out] descriptor_l1 L1 descriptor. \param [in] mem Section memory type: NORMAL, DEVICE, SHARED_DEVICE, NON_SHARED_DEVICE, STRONGLY_ORDERED \param [in] outer Outer cacheability: NON_CACHEABLE, WB_WA, WT, WB_NO_WA, \param [in] inner Inner cacheability: NON_CACHEABLE, WB_WA, WT, WB_NO_WA, \return 0 */ __STATIC_INLINE int __memory_section(uint32_t *descriptor_l1, mmu_memory_Type mem, mmu_cacheability_Type outer, mmu_cacheability_Type inner) { *descriptor_l1 &= SECTION_TEXCB_MASK; if (STRONGLY_ORDERED == mem) { return 0; } else if (SHARED_DEVICE == mem) { *descriptor_l1 |= (1 << SECTION_B_SHIFT); } else if (NON_SHARED_DEVICE == mem) { *descriptor_l1 |= (1 << SECTION_TEX1_SHIFT); } else if (NORMAL == mem) { *descriptor_l1 |= 1 << SECTION_TEX2_SHIFT; switch(inner) { case NON_CACHEABLE: break; case WB_WA: *descriptor_l1 |= (1 << SECTION_B_SHIFT); break; case WT: *descriptor_l1 |= 1 << SECTION_C_SHIFT; break; case WB_NO_WA: *descriptor_l1 |= (1 << SECTION_B_SHIFT) | (1 << SECTION_C_SHIFT); break; } switch(outer) { case NON_CACHEABLE: break; case WB_WA: *descriptor_l1 |= (1 << SECTION_TEX0_SHIFT); break; case WT: *descriptor_l1 |= 1 << SECTION_TEX1_SHIFT; break; case WB_NO_WA: *descriptor_l1 |= (1 << SECTION_TEX0_SHIFT) | (1 << SECTION_TEX0_SHIFT); break; } } return 0; } /** \brief Set 4k/64k page memory attributes The function sets 4k/64k page memory attributes \param [out] descriptor_l2 L2 descriptor. \param [in] mem 4k/64k page memory type: NORMAL, DEVICE, SHARED_DEVICE, NON_SHARED_DEVICE, STRONGLY_ORDERED \param [in] outer Outer cacheability: NON_CACHEABLE, WB_WA, WT, WB_NO_WA, \param [in] inner Inner cacheability: NON_CACHEABLE, WB_WA, WT, WB_NO_WA, \return 0 */ __STATIC_INLINE int __memory_page(uint32_t *descriptor_l2, mmu_memory_Type mem, mmu_cacheability_Type outer, mmu_cacheability_Type inner, mmu_region_size_Type page) { *descriptor_l2 &= PAGE_4K_TEXCB_MASK; if (page == PAGE_64k) { //same as section __memory_section(descriptor_l2, mem, outer, inner); } else { if (STRONGLY_ORDERED == mem) { return 0; } else if (SHARED_DEVICE == mem) { *descriptor_l2 |= (1 << PAGE_4K_B_SHIFT); } else if (NON_SHARED_DEVICE == mem) { *descriptor_l2 |= (1 << PAGE_4K_TEX1_SHIFT); } else if (NORMAL == mem) { *descriptor_l2 |= 1 << PAGE_4K_TEX2_SHIFT; switch(inner) { case NON_CACHEABLE: break; case WB_WA: *descriptor_l2 |= (1 << PAGE_4K_B_SHIFT); break; case WT: *descriptor_l2 |= 1 << PAGE_4K_C_SHIFT; break; case WB_NO_WA: *descriptor_l2 |= (1 << PAGE_4K_B_SHIFT) | (1 << PAGE_4K_C_SHIFT); break; } switch(outer) { case NON_CACHEABLE: break; case WB_WA: *descriptor_l2 |= (1 << PAGE_4K_TEX0_SHIFT); break; case WT: *descriptor_l2 |= 1 << PAGE_4K_TEX1_SHIFT; break; case WB_NO_WA: *descriptor_l2 |= (1 << PAGE_4K_TEX0_SHIFT) | (1 << PAGE_4K_TEX0_SHIFT); break; } } } return 0; } /** \brief Create a L1 section descriptor The function creates a section descriptor. Assumptions: - 16MB super sections not supported - TEX remap disabled, so memory type and attributes are described directly by bits in the descriptor - Functions always return 0 \param [out] descriptor L1 descriptor \param [out] descriptor2 L2 descriptor \param [in] reg Section attributes \return 0 */ __STATIC_INLINE int __get_section_descriptor(uint32_t *descriptor, mmu_region_attributes_Type reg) { *descriptor = 0; __memory_section(descriptor, reg.mem_t, reg.outer_norm_t, reg.inner_norm_t); __xn_section(descriptor,reg.xn_t); __domain_section(descriptor, reg.domain); __p_section(descriptor, reg.e_t); __ap_section(descriptor, reg.priv_t, reg.user_t, 1); __shared_section(descriptor,reg.sh_t); __global_section(descriptor,reg.g_t); __secure_section(descriptor,reg.sec_t); *descriptor &= SECTION_MASK; *descriptor |= SECTION_DESCRIPTOR; return 0; } /** \brief Create a L1 and L2 4k/64k page descriptor The function creates a 4k/64k page descriptor. Assumptions: - TEX remap disabled, so memory type and attributes are described directly by bits in the descriptor - Functions always return 0 \param [out] descriptor L1 descriptor \param [out] descriptor2 L2 descriptor \param [in] reg 4k/64k page attributes \return 0 */ __STATIC_INLINE int __get_page_descriptor(uint32_t *descriptor, uint32_t *descriptor2, mmu_region_attributes_Type reg) { *descriptor = 0; *descriptor2 = 0; switch (reg.rg_t) { case PAGE_4k: __memory_page(descriptor2, reg.mem_t, reg.outer_norm_t, reg.inner_norm_t, PAGE_4k); __xn_page(descriptor2, reg.xn_t, PAGE_4k); __domain_page(descriptor, reg.domain); __p_page(descriptor, reg.e_t); __ap_page(descriptor2, reg.priv_t, reg.user_t, 1); __shared_page(descriptor2,reg.sh_t); __global_page(descriptor2,reg.g_t); __secure_page(descriptor,reg.sec_t); *descriptor &= PAGE_L1_MASK; *descriptor |= PAGE_L1_DESCRIPTOR; *descriptor2 &= PAGE_L2_4K_MASK; *descriptor2 |= PAGE_L2_4K_DESC; break; case PAGE_64k: __memory_page(descriptor2, reg.mem_t, reg.outer_norm_t, reg.inner_norm_t, PAGE_64k); __xn_page(descriptor2, reg.xn_t, PAGE_64k); __domain_page(descriptor, reg.domain); __p_page(descriptor, reg.e_t); __ap_page(descriptor2, reg.priv_t, reg.user_t, 1); __shared_page(descriptor2,reg.sh_t); __global_page(descriptor2,reg.g_t); __secure_page(descriptor,reg.sec_t); *descriptor &= PAGE_L1_MASK; *descriptor |= PAGE_L1_DESCRIPTOR; *descriptor2 &= PAGE_L2_64K_MASK; *descriptor2 |= PAGE_L2_64K_DESC; break; case SECTION: //error break; } return 0; } /** \brief Create a 1MB Section \param [in] ttb Translation table base address \param [in] base_address Section base address \param [in] count Number of sections to create \param [in] descriptor_l1 L1 descriptor (region attributes) */ __STATIC_INLINE void __TTSection(uint32_t *ttb, uint32_t base_address, uint32_t count, uint32_t descriptor_l1) { uint32_t offset; uint32_t entry; uint32_t i; offset = base_address >> 20; entry = (base_address & 0xFFF00000) | descriptor_l1; //4 bytes aligned ttb = ttb + offset; for (i = 0; i < count; i++ ) { //4 bytes aligned *ttb++ = entry; entry += OFFSET_1M; } } /** \brief Create a 4k page entry \param [in] ttb L1 table base address \param [in] base_address 4k base address \param [in] count Number of 4k pages to create \param [in] descriptor_l1 L1 descriptor (region attributes) \param [in] ttb_l2 L2 table base address \param [in] descriptor_l2 L2 descriptor (region attributes) */ __STATIC_INLINE void __TTPage_4k(uint32_t *ttb, uint32_t base_address, uint32_t count, uint32_t descriptor_l1, uint32_t *ttb_l2, uint32_t descriptor_l2 ) { uint32_t offset, offset2; uint32_t entry, entry2; uint32_t i; offset = base_address >> 20; entry = ((int)ttb_l2 & 0xFFFFFC00) | descriptor_l1; //4 bytes aligned ttb += offset; //create l1_entry *ttb = entry; offset2 = (base_address & 0xff000) >> 12; ttb_l2 += offset2; entry2 = (base_address & 0xFFFFF000) | descriptor_l2; for (i = 0; i < count; i++ ) { //4 bytes aligned *ttb_l2++ = entry2; entry2 += OFFSET_4K; } } /** \brief Create a 64k page entry \param [in] ttb L1 table base address \param [in] base_address 64k base address \param [in] count Number of 64k pages to create \param [in] descriptor_l1 L1 descriptor (region attributes) \param [in] ttb_l2 L2 table base address \param [in] descriptor_l2 L2 descriptor (region attributes) */ __STATIC_INLINE void __TTPage_64k(uint32_t *ttb, uint32_t base_address, uint32_t count, uint32_t descriptor_l1, uint32_t *ttb_l2, uint32_t descriptor_l2 ) { uint32_t offset, offset2; uint32_t entry, entry2; uint32_t i,j; offset = base_address >> 20; entry = ((int)ttb_l2 & 0xFFFFFC00) | descriptor_l1; //4 bytes aligned ttb += offset; //create l1_entry *ttb = entry; offset2 = (base_address & 0xff000) >> 12; ttb_l2 += offset2; entry2 = (base_address & 0xFFFF0000) | descriptor_l2; for (i = 0; i < count; i++ ) { //create 16 entries for (j = 0; j < 16; j++) //4 bytes aligned *ttb_l2++ = entry2; entry2 += OFFSET_64K; } } /*@} end of MMU_Functions */ #endif #ifdef __cplusplus } #endif ================================================ FILE: Zelig/mbed/TARGET_NUCLEO_F411RE/core_cm0.h ================================================ /**************************************************************************//** * @file core_cm0.h * @brief CMSIS Cortex-M0 Core Peripheral Access Layer Header File * @version V4.10 * @date 18. March 2015 * * @note * ******************************************************************************/ /* Copyright (c) 2009 - 2015 ARM LIMITED All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: - Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. - Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. - Neither the name of ARM 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 COPYRIGHT HOLDERS AND 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. ---------------------------------------------------------------------------*/ #if defined ( __ICCARM__ ) #pragma system_include /* treat file as system include file for MISRA check */ #endif #ifndef __CORE_CM0_H_GENERIC #define __CORE_CM0_H_GENERIC #ifdef __cplusplus extern "C" { #endif /** \page CMSIS_MISRA_Exceptions MISRA-C:2004 Compliance Exceptions CMSIS violates the following MISRA-C:2004 rules: \li Required Rule 8.5, object/function definition in header file.
Function definitions in header files are used to allow 'inlining'. \li Required Rule 18.4, declaration of union type or object of union type: '{...}'.
Unions are used for effective representation of core registers. \li Advisory Rule 19.7, Function-like macro defined.
Function-like macros are used to allow more efficient code. */ /******************************************************************************* * CMSIS definitions ******************************************************************************/ /** \ingroup Cortex_M0 @{ */ /* CMSIS CM0 definitions */ #define __CM0_CMSIS_VERSION_MAIN (0x04) /*!< [31:16] CMSIS HAL main version */ #define __CM0_CMSIS_VERSION_SUB (0x00) /*!< [15:0] CMSIS HAL sub version */ #define __CM0_CMSIS_VERSION ((__CM0_CMSIS_VERSION_MAIN << 16) | \ __CM0_CMSIS_VERSION_SUB ) /*!< CMSIS HAL version number */ #define __CORTEX_M (0x00) /*!< Cortex-M Core */ #if defined ( __CC_ARM ) #define __ASM __asm /*!< asm keyword for ARM Compiler */ #define __INLINE __inline /*!< inline keyword for ARM Compiler */ #define __STATIC_INLINE static __inline #elif defined ( __GNUC__ ) #define __ASM __asm /*!< asm keyword for GNU Compiler */ #define __INLINE inline /*!< inline keyword for GNU Compiler */ #define __STATIC_INLINE static inline #elif defined ( __ICCARM__ ) #define __ASM __asm /*!< asm keyword for IAR Compiler */ #define __INLINE inline /*!< inline keyword for IAR Compiler. Only available in High optimization mode! */ #define __STATIC_INLINE static inline #elif defined ( __TMS470__ ) #define __ASM __asm /*!< asm keyword for TI CCS Compiler */ #define __STATIC_INLINE static inline #elif defined ( __TASKING__ ) #define __ASM __asm /*!< asm keyword for TASKING Compiler */ #define __INLINE inline /*!< inline keyword for TASKING Compiler */ #define __STATIC_INLINE static inline #elif defined ( __CSMC__ ) #define __packed #define __ASM _asm /*!< asm keyword for COSMIC Compiler */ #define __INLINE inline /*use -pc99 on compile line !< inline keyword for COSMIC Compiler */ #define __STATIC_INLINE static inline #endif /** __FPU_USED indicates whether an FPU is used or not. This core does not support an FPU at all */ #define __FPU_USED 0 #if defined ( __CC_ARM ) #if defined __TARGET_FPU_VFP #warning "Compiler generates FPU instructions for a device without an FPU (check __FPU_PRESENT)" #endif #elif defined ( __GNUC__ ) #if defined (__VFP_FP__) && !defined(__SOFTFP__) #warning "Compiler generates FPU instructions for a device without an FPU (check __FPU_PRESENT)" #endif #elif defined ( __ICCARM__ ) #if defined __ARMVFP__ #warning "Compiler generates FPU instructions for a device without an FPU (check __FPU_PRESENT)" #endif #elif defined ( __TMS470__ ) #if defined __TI__VFP_SUPPORT____ #warning "Compiler generates FPU instructions for a device without an FPU (check __FPU_PRESENT)" #endif #elif defined ( __TASKING__ ) #if defined __FPU_VFP__ #error "Compiler generates FPU instructions for a device without an FPU (check __FPU_PRESENT)" #endif #elif defined ( __CSMC__ ) /* Cosmic */ #if ( __CSMC__ & 0x400) // FPU present for parser #error "Compiler generates FPU instructions for a device without an FPU (check __FPU_PRESENT)" #endif #endif #include /* standard types definitions */ #include /* Core Instruction Access */ #include /* Core Function Access */ #ifdef __cplusplus } #endif #endif /* __CORE_CM0_H_GENERIC */ #ifndef __CMSIS_GENERIC #ifndef __CORE_CM0_H_DEPENDANT #define __CORE_CM0_H_DEPENDANT #ifdef __cplusplus extern "C" { #endif /* check device defines and use defaults */ #if defined __CHECK_DEVICE_DEFINES #ifndef __CM0_REV #define __CM0_REV 0x0000 #warning "__CM0_REV not defined in device header file; using default!" #endif #ifndef __NVIC_PRIO_BITS #define __NVIC_PRIO_BITS 2 #warning "__NVIC_PRIO_BITS not defined in device header file; using default!" #endif #ifndef __Vendor_SysTickConfig #define __Vendor_SysTickConfig 0 #warning "__Vendor_SysTickConfig not defined in device header file; using default!" #endif #endif /* IO definitions (access restrictions to peripheral registers) */ /** \defgroup CMSIS_glob_defs CMSIS Global Defines IO Type Qualifiers are used \li to specify the access to peripheral variables. \li for automatic generation of peripheral register debug information. */ #ifdef __cplusplus #define __I volatile /*!< Defines 'read only' permissions */ #else #define __I volatile const /*!< Defines 'read only' permissions */ #endif #define __O volatile /*!< Defines 'write only' permissions */ #define __IO volatile /*!< Defines 'read / write' permissions */ /*@} end of group Cortex_M0 */ /******************************************************************************* * Register Abstraction Core Register contain: - Core Register - Core NVIC Register - Core SCB Register - Core SysTick Register ******************************************************************************/ /** \defgroup CMSIS_core_register Defines and Type Definitions \brief Type definitions and defines for Cortex-M processor based devices. */ /** \ingroup CMSIS_core_register \defgroup CMSIS_CORE Status and Control Registers \brief Core Register type definitions. @{ */ /** \brief Union type to access the Application Program Status Register (APSR). */ typedef union { struct { uint32_t _reserved0:28; /*!< bit: 0..27 Reserved */ uint32_t V:1; /*!< bit: 28 Overflow condition code flag */ uint32_t C:1; /*!< bit: 29 Carry condition code flag */ uint32_t Z:1; /*!< bit: 30 Zero condition code flag */ uint32_t N:1; /*!< bit: 31 Negative condition code flag */ } b; /*!< Structure used for bit access */ uint32_t w; /*!< Type used for word access */ } APSR_Type; /* APSR Register Definitions */ #define APSR_N_Pos 31 /*!< APSR: N Position */ #define APSR_N_Msk (1UL << APSR_N_Pos) /*!< APSR: N Mask */ #define APSR_Z_Pos 30 /*!< APSR: Z Position */ #define APSR_Z_Msk (1UL << APSR_Z_Pos) /*!< APSR: Z Mask */ #define APSR_C_Pos 29 /*!< APSR: C Position */ #define APSR_C_Msk (1UL << APSR_C_Pos) /*!< APSR: C Mask */ #define APSR_V_Pos 28 /*!< APSR: V Position */ #define APSR_V_Msk (1UL << APSR_V_Pos) /*!< APSR: V Mask */ /** \brief Union type to access the Interrupt Program Status Register (IPSR). */ typedef union { struct { uint32_t ISR:9; /*!< bit: 0.. 8 Exception number */ uint32_t _reserved0:23; /*!< bit: 9..31 Reserved */ } b; /*!< Structure used for bit access */ uint32_t w; /*!< Type used for word access */ } IPSR_Type; /* IPSR Register Definitions */ #define IPSR_ISR_Pos 0 /*!< IPSR: ISR Position */ #define IPSR_ISR_Msk (0x1FFUL /*<< IPSR_ISR_Pos*/) /*!< IPSR: ISR Mask */ /** \brief Union type to access the Special-Purpose Program Status Registers (xPSR). */ typedef union { struct { uint32_t ISR:9; /*!< bit: 0.. 8 Exception number */ uint32_t _reserved0:15; /*!< bit: 9..23 Reserved */ uint32_t T:1; /*!< bit: 24 Thumb bit (read 0) */ uint32_t _reserved1:3; /*!< bit: 25..27 Reserved */ uint32_t V:1; /*!< bit: 28 Overflow condition code flag */ uint32_t C:1; /*!< bit: 29 Carry condition code flag */ uint32_t Z:1; /*!< bit: 30 Zero condition code flag */ uint32_t N:1; /*!< bit: 31 Negative condition code flag */ } b; /*!< Structure used for bit access */ uint32_t w; /*!< Type used for word access */ } xPSR_Type; /* xPSR Register Definitions */ #define xPSR_N_Pos 31 /*!< xPSR: N Position */ #define xPSR_N_Msk (1UL << xPSR_N_Pos) /*!< xPSR: N Mask */ #define xPSR_Z_Pos 30 /*!< xPSR: Z Position */ #define xPSR_Z_Msk (1UL << xPSR_Z_Pos) /*!< xPSR: Z Mask */ #define xPSR_C_Pos 29 /*!< xPSR: C Position */ #define xPSR_C_Msk (1UL << xPSR_C_Pos) /*!< xPSR: C Mask */ #define xPSR_V_Pos 28 /*!< xPSR: V Position */ #define xPSR_V_Msk (1UL << xPSR_V_Pos) /*!< xPSR: V Mask */ #define xPSR_T_Pos 24 /*!< xPSR: T Position */ #define xPSR_T_Msk (1UL << xPSR_T_Pos) /*!< xPSR: T Mask */ #define xPSR_ISR_Pos 0 /*!< xPSR: ISR Position */ #define xPSR_ISR_Msk (0x1FFUL /*<< xPSR_ISR_Pos*/) /*!< xPSR: ISR Mask */ /** \brief Union type to access the Control Registers (CONTROL). */ typedef union { struct { uint32_t _reserved0:1; /*!< bit: 0 Reserved */ uint32_t SPSEL:1; /*!< bit: 1 Stack to be used */ uint32_t _reserved1:30; /*!< bit: 2..31 Reserved */ } b; /*!< Structure used for bit access */ uint32_t w; /*!< Type used for word access */ } CONTROL_Type; /* CONTROL Register Definitions */ #define CONTROL_SPSEL_Pos 1 /*!< CONTROL: SPSEL Position */ #define CONTROL_SPSEL_Msk (1UL << CONTROL_SPSEL_Pos) /*!< CONTROL: SPSEL Mask */ /*@} end of group CMSIS_CORE */ /** \ingroup CMSIS_core_register \defgroup CMSIS_NVIC Nested Vectored Interrupt Controller (NVIC) \brief Type definitions for the NVIC Registers @{ */ /** \brief Structure type to access the Nested Vectored Interrupt Controller (NVIC). */ typedef struct { __IO uint32_t ISER[1]; /*!< Offset: 0x000 (R/W) Interrupt Set Enable Register */ uint32_t RESERVED0[31]; __IO uint32_t ICER[1]; /*!< Offset: 0x080 (R/W) Interrupt Clear Enable Register */ uint32_t RSERVED1[31]; __IO uint32_t ISPR[1]; /*!< Offset: 0x100 (R/W) Interrupt Set Pending Register */ uint32_t RESERVED2[31]; __IO uint32_t ICPR[1]; /*!< Offset: 0x180 (R/W) Interrupt Clear Pending Register */ uint32_t RESERVED3[31]; uint32_t RESERVED4[64]; __IO uint32_t IP[8]; /*!< Offset: 0x300 (R/W) Interrupt Priority Register */ } NVIC_Type; /*@} end of group CMSIS_NVIC */ /** \ingroup CMSIS_core_register \defgroup CMSIS_SCB System Control Block (SCB) \brief Type definitions for the System Control Block Registers @{ */ /** \brief Structure type to access the System Control Block (SCB). */ typedef struct { __I uint32_t CPUID; /*!< Offset: 0x000 (R/ ) CPUID Base Register */ __IO uint32_t ICSR; /*!< Offset: 0x004 (R/W) Interrupt Control and State Register */ uint32_t RESERVED0; __IO uint32_t AIRCR; /*!< Offset: 0x00C (R/W) Application Interrupt and Reset Control Register */ __IO uint32_t SCR; /*!< Offset: 0x010 (R/W) System Control Register */ __IO uint32_t CCR; /*!< Offset: 0x014 (R/W) Configuration Control Register */ uint32_t RESERVED1; __IO uint32_t SHP[2]; /*!< Offset: 0x01C (R/W) System Handlers Priority Registers. [0] is RESERVED */ __IO uint32_t SHCSR; /*!< Offset: 0x024 (R/W) System Handler Control and State Register */ } SCB_Type; /* SCB CPUID Register Definitions */ #define SCB_CPUID_IMPLEMENTER_Pos 24 /*!< SCB CPUID: IMPLEMENTER Position */ #define SCB_CPUID_IMPLEMENTER_Msk (0xFFUL << SCB_CPUID_IMPLEMENTER_Pos) /*!< SCB CPUID: IMPLEMENTER Mask */ #define SCB_CPUID_VARIANT_Pos 20 /*!< SCB CPUID: VARIANT Position */ #define SCB_CPUID_VARIANT_Msk (0xFUL << SCB_CPUID_VARIANT_Pos) /*!< SCB CPUID: VARIANT Mask */ #define SCB_CPUID_ARCHITECTURE_Pos 16 /*!< SCB CPUID: ARCHITECTURE Position */ #define SCB_CPUID_ARCHITECTURE_Msk (0xFUL << SCB_CPUID_ARCHITECTURE_Pos) /*!< SCB CPUID: ARCHITECTURE Mask */ #define SCB_CPUID_PARTNO_Pos 4 /*!< SCB CPUID: PARTNO Position */ #define SCB_CPUID_PARTNO_Msk (0xFFFUL << SCB_CPUID_PARTNO_Pos) /*!< SCB CPUID: PARTNO Mask */ #define SCB_CPUID_REVISION_Pos 0 /*!< SCB CPUID: REVISION Position */ #define SCB_CPUID_REVISION_Msk (0xFUL /*<< SCB_CPUID_REVISION_Pos*/) /*!< SCB CPUID: REVISION Mask */ /* SCB Interrupt Control State Register Definitions */ #define SCB_ICSR_NMIPENDSET_Pos 31 /*!< SCB ICSR: NMIPENDSET Position */ #define SCB_ICSR_NMIPENDSET_Msk (1UL << SCB_ICSR_NMIPENDSET_Pos) /*!< SCB ICSR: NMIPENDSET Mask */ #define SCB_ICSR_PENDSVSET_Pos 28 /*!< SCB ICSR: PENDSVSET Position */ #define SCB_ICSR_PENDSVSET_Msk (1UL << SCB_ICSR_PENDSVSET_Pos) /*!< SCB ICSR: PENDSVSET Mask */ #define SCB_ICSR_PENDSVCLR_Pos 27 /*!< SCB ICSR: PENDSVCLR Position */ #define SCB_ICSR_PENDSVCLR_Msk (1UL << SCB_ICSR_PENDSVCLR_Pos) /*!< SCB ICSR: PENDSVCLR Mask */ #define SCB_ICSR_PENDSTSET_Pos 26 /*!< SCB ICSR: PENDSTSET Position */ #define SCB_ICSR_PENDSTSET_Msk (1UL << SCB_ICSR_PENDSTSET_Pos) /*!< SCB ICSR: PENDSTSET Mask */ #define SCB_ICSR_PENDSTCLR_Pos 25 /*!< SCB ICSR: PENDSTCLR Position */ #define SCB_ICSR_PENDSTCLR_Msk (1UL << SCB_ICSR_PENDSTCLR_Pos) /*!< SCB ICSR: PENDSTCLR Mask */ #define SCB_ICSR_ISRPREEMPT_Pos 23 /*!< SCB ICSR: ISRPREEMPT Position */ #define SCB_ICSR_ISRPREEMPT_Msk (1UL << SCB_ICSR_ISRPREEMPT_Pos) /*!< SCB ICSR: ISRPREEMPT Mask */ #define SCB_ICSR_ISRPENDING_Pos 22 /*!< SCB ICSR: ISRPENDING Position */ #define SCB_ICSR_ISRPENDING_Msk (1UL << SCB_ICSR_ISRPENDING_Pos) /*!< SCB ICSR: ISRPENDING Mask */ #define SCB_ICSR_VECTPENDING_Pos 12 /*!< SCB ICSR: VECTPENDING Position */ #define SCB_ICSR_VECTPENDING_Msk (0x1FFUL << SCB_ICSR_VECTPENDING_Pos) /*!< SCB ICSR: VECTPENDING Mask */ #define SCB_ICSR_VECTACTIVE_Pos 0 /*!< SCB ICSR: VECTACTIVE Position */ #define SCB_ICSR_VECTACTIVE_Msk (0x1FFUL /*<< SCB_ICSR_VECTACTIVE_Pos*/) /*!< SCB ICSR: VECTACTIVE Mask */ /* SCB Application Interrupt and Reset Control Register Definitions */ #define SCB_AIRCR_VECTKEY_Pos 16 /*!< SCB AIRCR: VECTKEY Position */ #define SCB_AIRCR_VECTKEY_Msk (0xFFFFUL << SCB_AIRCR_VECTKEY_Pos) /*!< SCB AIRCR: VECTKEY Mask */ #define SCB_AIRCR_VECTKEYSTAT_Pos 16 /*!< SCB AIRCR: VECTKEYSTAT Position */ #define SCB_AIRCR_VECTKEYSTAT_Msk (0xFFFFUL << SCB_AIRCR_VECTKEYSTAT_Pos) /*!< SCB AIRCR: VECTKEYSTAT Mask */ #define SCB_AIRCR_ENDIANESS_Pos 15 /*!< SCB AIRCR: ENDIANESS Position */ #define SCB_AIRCR_ENDIANESS_Msk (1UL << SCB_AIRCR_ENDIANESS_Pos) /*!< SCB AIRCR: ENDIANESS Mask */ #define SCB_AIRCR_SYSRESETREQ_Pos 2 /*!< SCB AIRCR: SYSRESETREQ Position */ #define SCB_AIRCR_SYSRESETREQ_Msk (1UL << SCB_AIRCR_SYSRESETREQ_Pos) /*!< SCB AIRCR: SYSRESETREQ Mask */ #define SCB_AIRCR_VECTCLRACTIVE_Pos 1 /*!< SCB AIRCR: VECTCLRACTIVE Position */ #define SCB_AIRCR_VECTCLRACTIVE_Msk (1UL << SCB_AIRCR_VECTCLRACTIVE_Pos) /*!< SCB AIRCR: VECTCLRACTIVE Mask */ /* SCB System Control Register Definitions */ #define SCB_SCR_SEVONPEND_Pos 4 /*!< SCB SCR: SEVONPEND Position */ #define SCB_SCR_SEVONPEND_Msk (1UL << SCB_SCR_SEVONPEND_Pos) /*!< SCB SCR: SEVONPEND Mask */ #define SCB_SCR_SLEEPDEEP_Pos 2 /*!< SCB SCR: SLEEPDEEP Position */ #define SCB_SCR_SLEEPDEEP_Msk (1UL << SCB_SCR_SLEEPDEEP_Pos) /*!< SCB SCR: SLEEPDEEP Mask */ #define SCB_SCR_SLEEPONEXIT_Pos 1 /*!< SCB SCR: SLEEPONEXIT Position */ #define SCB_SCR_SLEEPONEXIT_Msk (1UL << SCB_SCR_SLEEPONEXIT_Pos) /*!< SCB SCR: SLEEPONEXIT Mask */ /* SCB Configuration Control Register Definitions */ #define SCB_CCR_STKALIGN_Pos 9 /*!< SCB CCR: STKALIGN Position */ #define SCB_CCR_STKALIGN_Msk (1UL << SCB_CCR_STKALIGN_Pos) /*!< SCB CCR: STKALIGN Mask */ #define SCB_CCR_UNALIGN_TRP_Pos 3 /*!< SCB CCR: UNALIGN_TRP Position */ #define SCB_CCR_UNALIGN_TRP_Msk (1UL << SCB_CCR_UNALIGN_TRP_Pos) /*!< SCB CCR: UNALIGN_TRP Mask */ /* SCB System Handler Control and State Register Definitions */ #define SCB_SHCSR_SVCALLPENDED_Pos 15 /*!< SCB SHCSR: SVCALLPENDED Position */ #define SCB_SHCSR_SVCALLPENDED_Msk (1UL << SCB_SHCSR_SVCALLPENDED_Pos) /*!< SCB SHCSR: SVCALLPENDED Mask */ /*@} end of group CMSIS_SCB */ /** \ingroup CMSIS_core_register \defgroup CMSIS_SysTick System Tick Timer (SysTick) \brief Type definitions for the System Timer Registers. @{ */ /** \brief Structure type to access the System Timer (SysTick). */ typedef struct { __IO uint32_t CTRL; /*!< Offset: 0x000 (R/W) SysTick Control and Status Register */ __IO uint32_t LOAD; /*!< Offset: 0x004 (R/W) SysTick Reload Value Register */ __IO uint32_t VAL; /*!< Offset: 0x008 (R/W) SysTick Current Value Register */ __I uint32_t CALIB; /*!< Offset: 0x00C (R/ ) SysTick Calibration Register */ } SysTick_Type; /* SysTick Control / Status Register Definitions */ #define SysTick_CTRL_COUNTFLAG_Pos 16 /*!< SysTick CTRL: COUNTFLAG Position */ #define SysTick_CTRL_COUNTFLAG_Msk (1UL << SysTick_CTRL_COUNTFLAG_Pos) /*!< SysTick CTRL: COUNTFLAG Mask */ #define SysTick_CTRL_CLKSOURCE_Pos 2 /*!< SysTick CTRL: CLKSOURCE Position */ #define SysTick_CTRL_CLKSOURCE_Msk (1UL << SysTick_CTRL_CLKSOURCE_Pos) /*!< SysTick CTRL: CLKSOURCE Mask */ #define SysTick_CTRL_TICKINT_Pos 1 /*!< SysTick CTRL: TICKINT Position */ #define SysTick_CTRL_TICKINT_Msk (1UL << SysTick_CTRL_TICKINT_Pos) /*!< SysTick CTRL: TICKINT Mask */ #define SysTick_CTRL_ENABLE_Pos 0 /*!< SysTick CTRL: ENABLE Position */ #define SysTick_CTRL_ENABLE_Msk (1UL /*<< SysTick_CTRL_ENABLE_Pos*/) /*!< SysTick CTRL: ENABLE Mask */ /* SysTick Reload Register Definitions */ #define SysTick_LOAD_RELOAD_Pos 0 /*!< SysTick LOAD: RELOAD Position */ #define SysTick_LOAD_RELOAD_Msk (0xFFFFFFUL /*<< SysTick_LOAD_RELOAD_Pos*/) /*!< SysTick LOAD: RELOAD Mask */ /* SysTick Current Register Definitions */ #define SysTick_VAL_CURRENT_Pos 0 /*!< SysTick VAL: CURRENT Position */ #define SysTick_VAL_CURRENT_Msk (0xFFFFFFUL /*<< SysTick_VAL_CURRENT_Pos*/) /*!< SysTick VAL: CURRENT Mask */ /* SysTick Calibration Register Definitions */ #define SysTick_CALIB_NOREF_Pos 31 /*!< SysTick CALIB: NOREF Position */ #define SysTick_CALIB_NOREF_Msk (1UL << SysTick_CALIB_NOREF_Pos) /*!< SysTick CALIB: NOREF Mask */ #define SysTick_CALIB_SKEW_Pos 30 /*!< SysTick CALIB: SKEW Position */ #define SysTick_CALIB_SKEW_Msk (1UL << SysTick_CALIB_SKEW_Pos) /*!< SysTick CALIB: SKEW Mask */ #define SysTick_CALIB_TENMS_Pos 0 /*!< SysTick CALIB: TENMS Position */ #define SysTick_CALIB_TENMS_Msk (0xFFFFFFUL /*<< SysTick_CALIB_TENMS_Pos*/) /*!< SysTick CALIB: TENMS Mask */ /*@} end of group CMSIS_SysTick */ /** \ingroup CMSIS_core_register \defgroup CMSIS_CoreDebug Core Debug Registers (CoreDebug) \brief Cortex-M0 Core Debug Registers (DCB registers, SHCSR, and DFSR) are only accessible over DAP and not via processor. Therefore they are not covered by the Cortex-M0 header file. @{ */ /*@} end of group CMSIS_CoreDebug */ /** \ingroup CMSIS_core_register \defgroup CMSIS_core_base Core Definitions \brief Definitions for base addresses, unions, and structures. @{ */ /* Memory mapping of Cortex-M0 Hardware */ #define SCS_BASE (0xE000E000UL) /*!< System Control Space Base Address */ #define SysTick_BASE (SCS_BASE + 0x0010UL) /*!< SysTick Base Address */ #define NVIC_BASE (SCS_BASE + 0x0100UL) /*!< NVIC Base Address */ #define SCB_BASE (SCS_BASE + 0x0D00UL) /*!< System Control Block Base Address */ #define SCB ((SCB_Type *) SCB_BASE ) /*!< SCB configuration struct */ #define SysTick ((SysTick_Type *) SysTick_BASE ) /*!< SysTick configuration struct */ #define NVIC ((NVIC_Type *) NVIC_BASE ) /*!< NVIC configuration struct */ /*@} */ /******************************************************************************* * Hardware Abstraction Layer Core Function Interface contains: - Core NVIC Functions - Core SysTick Functions - Core Register Access Functions ******************************************************************************/ /** \defgroup CMSIS_Core_FunctionInterface Functions and Instructions Reference */ /* ########################## NVIC functions #################################### */ /** \ingroup CMSIS_Core_FunctionInterface \defgroup CMSIS_Core_NVICFunctions NVIC Functions \brief Functions that manage interrupts and exceptions via the NVIC. @{ */ /* Interrupt Priorities are WORD accessible only under ARMv6M */ /* The following MACROS handle generation of the register offset and byte masks */ #define _BIT_SHIFT(IRQn) ( ((((uint32_t)(int32_t)(IRQn)) ) & 0x03UL) * 8UL) #define _SHP_IDX(IRQn) ( (((((uint32_t)(int32_t)(IRQn)) & 0x0FUL)-8UL) >> 2UL) ) #define _IP_IDX(IRQn) ( (((uint32_t)(int32_t)(IRQn)) >> 2UL) ) /** \brief Enable External Interrupt The function enables a device-specific interrupt in the NVIC interrupt controller. \param [in] IRQn External interrupt number. Value cannot be negative. */ __STATIC_INLINE void NVIC_EnableIRQ(IRQn_Type IRQn) { NVIC->ISER[0] = (uint32_t)(1UL << (((uint32_t)(int32_t)IRQn) & 0x1FUL)); } /** \brief Disable External Interrupt The function disables a device-specific interrupt in the NVIC interrupt controller. \param [in] IRQn External interrupt number. Value cannot be negative. */ __STATIC_INLINE void NVIC_DisableIRQ(IRQn_Type IRQn) { NVIC->ICER[0] = (uint32_t)(1UL << (((uint32_t)(int32_t)IRQn) & 0x1FUL)); } /** \brief Get Pending Interrupt The function reads the pending register in the NVIC and returns the pending bit for the specified interrupt. \param [in] IRQn Interrupt number. \return 0 Interrupt status is not pending. \return 1 Interrupt status is pending. */ __STATIC_INLINE uint32_t NVIC_GetPendingIRQ(IRQn_Type IRQn) { return((uint32_t)(((NVIC->ISPR[0] & (1UL << (((uint32_t)(int32_t)IRQn) & 0x1FUL))) != 0UL) ? 1UL : 0UL)); } /** \brief Set Pending Interrupt The function sets the pending bit of an external interrupt. \param [in] IRQn Interrupt number. Value cannot be negative. */ __STATIC_INLINE void NVIC_SetPendingIRQ(IRQn_Type IRQn) { NVIC->ISPR[0] = (uint32_t)(1UL << (((uint32_t)(int32_t)IRQn) & 0x1FUL)); } /** \brief Clear Pending Interrupt The function clears the pending bit of an external interrupt. \param [in] IRQn External interrupt number. Value cannot be negative. */ __STATIC_INLINE void NVIC_ClearPendingIRQ(IRQn_Type IRQn) { NVIC->ICPR[0] = (uint32_t)(1UL << (((uint32_t)(int32_t)IRQn) & 0x1FUL)); } /** \brief Set Interrupt Priority The function sets the priority of an interrupt. \note The priority cannot be set for every core interrupt. \param [in] IRQn Interrupt number. \param [in] priority Priority to set. */ __STATIC_INLINE void NVIC_SetPriority(IRQn_Type IRQn, uint32_t priority) { if((int32_t)(IRQn) < 0) { SCB->SHP[_SHP_IDX(IRQn)] = ((uint32_t)(SCB->SHP[_SHP_IDX(IRQn)] & ~(0xFFUL << _BIT_SHIFT(IRQn))) | (((priority << (8 - __NVIC_PRIO_BITS)) & (uint32_t)0xFFUL) << _BIT_SHIFT(IRQn))); } else { NVIC->IP[_IP_IDX(IRQn)] = ((uint32_t)(NVIC->IP[_IP_IDX(IRQn)] & ~(0xFFUL << _BIT_SHIFT(IRQn))) | (((priority << (8 - __NVIC_PRIO_BITS)) & (uint32_t)0xFFUL) << _BIT_SHIFT(IRQn))); } } /** \brief Get Interrupt Priority The function reads the priority of an interrupt. The interrupt number can be positive to specify an external (device specific) interrupt, or negative to specify an internal (core) interrupt. \param [in] IRQn Interrupt number. \return Interrupt Priority. Value is aligned automatically to the implemented priority bits of the microcontroller. */ __STATIC_INLINE uint32_t NVIC_GetPriority(IRQn_Type IRQn) { if((int32_t)(IRQn) < 0) { return((uint32_t)(((SCB->SHP[_SHP_IDX(IRQn)] >> _BIT_SHIFT(IRQn) ) & (uint32_t)0xFFUL) >> (8 - __NVIC_PRIO_BITS))); } else { return((uint32_t)(((NVIC->IP[ _IP_IDX(IRQn)] >> _BIT_SHIFT(IRQn) ) & (uint32_t)0xFFUL) >> (8 - __NVIC_PRIO_BITS))); } } /** \brief System Reset The function initiates a system reset request to reset the MCU. */ __STATIC_INLINE void NVIC_SystemReset(void) { __DSB(); /* Ensure all outstanding memory accesses included buffered write are completed before reset */ SCB->AIRCR = ((0x5FAUL << SCB_AIRCR_VECTKEY_Pos) | SCB_AIRCR_SYSRESETREQ_Msk); __DSB(); /* Ensure completion of memory access */ while(1) { __NOP(); } /* wait until reset */ } /*@} end of CMSIS_Core_NVICFunctions */ /* ################################## SysTick function ############################################ */ /** \ingroup CMSIS_Core_FunctionInterface \defgroup CMSIS_Core_SysTickFunctions SysTick Functions \brief Functions that configure the System. @{ */ #if (__Vendor_SysTickConfig == 0) /** \brief System Tick Configuration The function initializes the System Timer and its interrupt, and starts the System Tick Timer. Counter is in free running mode to generate periodic interrupts. \param [in] ticks Number of ticks between two interrupts. \return 0 Function succeeded. \return 1 Function failed. \note When the variable __Vendor_SysTickConfig is set to 1, then the function SysTick_Config is not included. In this case, the file device.h must contain a vendor-specific implementation of this function. */ __STATIC_INLINE uint32_t SysTick_Config(uint32_t ticks) { if ((ticks - 1UL) > SysTick_LOAD_RELOAD_Msk) { return (1UL); } /* Reload value impossible */ SysTick->LOAD = (uint32_t)(ticks - 1UL); /* set reload register */ NVIC_SetPriority (SysTick_IRQn, (1UL << __NVIC_PRIO_BITS) - 1UL); /* set Priority for Systick Interrupt */ SysTick->VAL = 0UL; /* Load the SysTick Counter Value */ SysTick->CTRL = SysTick_CTRL_CLKSOURCE_Msk | SysTick_CTRL_TICKINT_Msk | SysTick_CTRL_ENABLE_Msk; /* Enable SysTick IRQ and SysTick Timer */ return (0UL); /* Function successful */ } #endif /*@} end of CMSIS_Core_SysTickFunctions */ #ifdef __cplusplus } #endif #endif /* __CORE_CM0_H_DEPENDANT */ #endif /* __CMSIS_GENERIC */ ================================================ FILE: Zelig/mbed/TARGET_NUCLEO_F411RE/core_cm0plus.h ================================================ /**************************************************************************//** * @file core_cm0plus.h * @brief CMSIS Cortex-M0+ Core Peripheral Access Layer Header File * @version V4.10 * @date 18. March 2015 * * @note * ******************************************************************************/ /* Copyright (c) 2009 - 2015 ARM LIMITED All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: - Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. - Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. - Neither the name of ARM 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 COPYRIGHT HOLDERS AND 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. ---------------------------------------------------------------------------*/ #if defined ( __ICCARM__ ) #pragma system_include /* treat file as system include file for MISRA check */ #endif #ifndef __CORE_CM0PLUS_H_GENERIC #define __CORE_CM0PLUS_H_GENERIC #ifdef __cplusplus extern "C" { #endif /** \page CMSIS_MISRA_Exceptions MISRA-C:2004 Compliance Exceptions CMSIS violates the following MISRA-C:2004 rules: \li Required Rule 8.5, object/function definition in header file.
Function definitions in header files are used to allow 'inlining'. \li Required Rule 18.4, declaration of union type or object of union type: '{...}'.
Unions are used for effective representation of core registers. \li Advisory Rule 19.7, Function-like macro defined.
Function-like macros are used to allow more efficient code. */ /******************************************************************************* * CMSIS definitions ******************************************************************************/ /** \ingroup Cortex-M0+ @{ */ /* CMSIS CM0P definitions */ #define __CM0PLUS_CMSIS_VERSION_MAIN (0x04) /*!< [31:16] CMSIS HAL main version */ #define __CM0PLUS_CMSIS_VERSION_SUB (0x00) /*!< [15:0] CMSIS HAL sub version */ #define __CM0PLUS_CMSIS_VERSION ((__CM0PLUS_CMSIS_VERSION_MAIN << 16) | \ __CM0PLUS_CMSIS_VERSION_SUB) /*!< CMSIS HAL version number */ #define __CORTEX_M (0x00) /*!< Cortex-M Core */ #if defined ( __CC_ARM ) #define __ASM __asm /*!< asm keyword for ARM Compiler */ #define __INLINE __inline /*!< inline keyword for ARM Compiler */ #define __STATIC_INLINE static __inline #elif defined ( __GNUC__ ) #define __ASM __asm /*!< asm keyword for GNU Compiler */ #define __INLINE inline /*!< inline keyword for GNU Compiler */ #define __STATIC_INLINE static inline #elif defined ( __ICCARM__ ) #define __ASM __asm /*!< asm keyword for IAR Compiler */ #define __INLINE inline /*!< inline keyword for IAR Compiler. Only available in High optimization mode! */ #define __STATIC_INLINE static inline #elif defined ( __TMS470__ ) #define __ASM __asm /*!< asm keyword for TI CCS Compiler */ #define __STATIC_INLINE static inline #elif defined ( __TASKING__ ) #define __ASM __asm /*!< asm keyword for TASKING Compiler */ #define __INLINE inline /*!< inline keyword for TASKING Compiler */ #define __STATIC_INLINE static inline #elif defined ( __CSMC__ ) #define __packed #define __ASM _asm /*!< asm keyword for COSMIC Compiler */ #define __INLINE inline /*use -pc99 on compile line !< inline keyword for COSMIC Compiler */ #define __STATIC_INLINE static inline #endif /** __FPU_USED indicates whether an FPU is used or not. This core does not support an FPU at all */ #define __FPU_USED 0 #if defined ( __CC_ARM ) #if defined __TARGET_FPU_VFP #warning "Compiler generates FPU instructions for a device without an FPU (check __FPU_PRESENT)" #endif #elif defined ( __GNUC__ ) #if defined (__VFP_FP__) && !defined(__SOFTFP__) #warning "Compiler generates FPU instructions for a device without an FPU (check __FPU_PRESENT)" #endif #elif defined ( __ICCARM__ ) #if defined __ARMVFP__ #warning "Compiler generates FPU instructions for a device without an FPU (check __FPU_PRESENT)" #endif #elif defined ( __TMS470__ ) #if defined __TI__VFP_SUPPORT____ #warning "Compiler generates FPU instructions for a device without an FPU (check __FPU_PRESENT)" #endif #elif defined ( __TASKING__ ) #if defined __FPU_VFP__ #error "Compiler generates FPU instructions for a device without an FPU (check __FPU_PRESENT)" #endif #elif defined ( __CSMC__ ) /* Cosmic */ #if ( __CSMC__ & 0x400) // FPU present for parser #error "Compiler generates FPU instructions for a device without an FPU (check __FPU_PRESENT)" #endif #endif #include /* standard types definitions */ #include /* Core Instruction Access */ #include /* Core Function Access */ #ifdef __cplusplus } #endif #endif /* __CORE_CM0PLUS_H_GENERIC */ #ifndef __CMSIS_GENERIC #ifndef __CORE_CM0PLUS_H_DEPENDANT #define __CORE_CM0PLUS_H_DEPENDANT #ifdef __cplusplus extern "C" { #endif /* check device defines and use defaults */ #if defined __CHECK_DEVICE_DEFINES #ifndef __CM0PLUS_REV #define __CM0PLUS_REV 0x0000 #warning "__CM0PLUS_REV not defined in device header file; using default!" #endif #ifndef __MPU_PRESENT #define __MPU_PRESENT 0 #warning "__MPU_PRESENT not defined in device header file; using default!" #endif #ifndef __VTOR_PRESENT #define __VTOR_PRESENT 0 #warning "__VTOR_PRESENT not defined in device header file; using default!" #endif #ifndef __NVIC_PRIO_BITS #define __NVIC_PRIO_BITS 2 #warning "__NVIC_PRIO_BITS not defined in device header file; using default!" #endif #ifndef __Vendor_SysTickConfig #define __Vendor_SysTickConfig 0 #warning "__Vendor_SysTickConfig not defined in device header file; using default!" #endif #endif /* IO definitions (access restrictions to peripheral registers) */ /** \defgroup CMSIS_glob_defs CMSIS Global Defines IO Type Qualifiers are used \li to specify the access to peripheral variables. \li for automatic generation of peripheral register debug information. */ #ifdef __cplusplus #define __I volatile /*!< Defines 'read only' permissions */ #else #define __I volatile const /*!< Defines 'read only' permissions */ #endif #define __O volatile /*!< Defines 'write only' permissions */ #define __IO volatile /*!< Defines 'read / write' permissions */ /*@} end of group Cortex-M0+ */ /******************************************************************************* * Register Abstraction Core Register contain: - Core Register - Core NVIC Register - Core SCB Register - Core SysTick Register - Core MPU Register ******************************************************************************/ /** \defgroup CMSIS_core_register Defines and Type Definitions \brief Type definitions and defines for Cortex-M processor based devices. */ /** \ingroup CMSIS_core_register \defgroup CMSIS_CORE Status and Control Registers \brief Core Register type definitions. @{ */ /** \brief Union type to access the Application Program Status Register (APSR). */ typedef union { struct { uint32_t _reserved0:28; /*!< bit: 0..27 Reserved */ uint32_t V:1; /*!< bit: 28 Overflow condition code flag */ uint32_t C:1; /*!< bit: 29 Carry condition code flag */ uint32_t Z:1; /*!< bit: 30 Zero condition code flag */ uint32_t N:1; /*!< bit: 31 Negative condition code flag */ } b; /*!< Structure used for bit access */ uint32_t w; /*!< Type used for word access */ } APSR_Type; /* APSR Register Definitions */ #define APSR_N_Pos 31 /*!< APSR: N Position */ #define APSR_N_Msk (1UL << APSR_N_Pos) /*!< APSR: N Mask */ #define APSR_Z_Pos 30 /*!< APSR: Z Position */ #define APSR_Z_Msk (1UL << APSR_Z_Pos) /*!< APSR: Z Mask */ #define APSR_C_Pos 29 /*!< APSR: C Position */ #define APSR_C_Msk (1UL << APSR_C_Pos) /*!< APSR: C Mask */ #define APSR_V_Pos 28 /*!< APSR: V Position */ #define APSR_V_Msk (1UL << APSR_V_Pos) /*!< APSR: V Mask */ /** \brief Union type to access the Interrupt Program Status Register (IPSR). */ typedef union { struct { uint32_t ISR:9; /*!< bit: 0.. 8 Exception number */ uint32_t _reserved0:23; /*!< bit: 9..31 Reserved */ } b; /*!< Structure used for bit access */ uint32_t w; /*!< Type used for word access */ } IPSR_Type; /* IPSR Register Definitions */ #define IPSR_ISR_Pos 0 /*!< IPSR: ISR Position */ #define IPSR_ISR_Msk (0x1FFUL /*<< IPSR_ISR_Pos*/) /*!< IPSR: ISR Mask */ /** \brief Union type to access the Special-Purpose Program Status Registers (xPSR). */ typedef union { struct { uint32_t ISR:9; /*!< bit: 0.. 8 Exception number */ uint32_t _reserved0:15; /*!< bit: 9..23 Reserved */ uint32_t T:1; /*!< bit: 24 Thumb bit (read 0) */ uint32_t _reserved1:3; /*!< bit: 25..27 Reserved */ uint32_t V:1; /*!< bit: 28 Overflow condition code flag */ uint32_t C:1; /*!< bit: 29 Carry condition code flag */ uint32_t Z:1; /*!< bit: 30 Zero condition code flag */ uint32_t N:1; /*!< bit: 31 Negative condition code flag */ } b; /*!< Structure used for bit access */ uint32_t w; /*!< Type used for word access */ } xPSR_Type; /* xPSR Register Definitions */ #define xPSR_N_Pos 31 /*!< xPSR: N Position */ #define xPSR_N_Msk (1UL << xPSR_N_Pos) /*!< xPSR: N Mask */ #define xPSR_Z_Pos 30 /*!< xPSR: Z Position */ #define xPSR_Z_Msk (1UL << xPSR_Z_Pos) /*!< xPSR: Z Mask */ #define xPSR_C_Pos 29 /*!< xPSR: C Position */ #define xPSR_C_Msk (1UL << xPSR_C_Pos) /*!< xPSR: C Mask */ #define xPSR_V_Pos 28 /*!< xPSR: V Position */ #define xPSR_V_Msk (1UL << xPSR_V_Pos) /*!< xPSR: V Mask */ #define xPSR_T_Pos 24 /*!< xPSR: T Position */ #define xPSR_T_Msk (1UL << xPSR_T_Pos) /*!< xPSR: T Mask */ #define xPSR_ISR_Pos 0 /*!< xPSR: ISR Position */ #define xPSR_ISR_Msk (0x1FFUL /*<< xPSR_ISR_Pos*/) /*!< xPSR: ISR Mask */ /** \brief Union type to access the Control Registers (CONTROL). */ typedef union { struct { uint32_t nPRIV:1; /*!< bit: 0 Execution privilege in Thread mode */ uint32_t SPSEL:1; /*!< bit: 1 Stack to be used */ uint32_t _reserved1:30; /*!< bit: 2..31 Reserved */ } b; /*!< Structure used for bit access */ uint32_t w; /*!< Type used for word access */ } CONTROL_Type; /* CONTROL Register Definitions */ #define CONTROL_SPSEL_Pos 1 /*!< CONTROL: SPSEL Position */ #define CONTROL_SPSEL_Msk (1UL << CONTROL_SPSEL_Pos) /*!< CONTROL: SPSEL Mask */ #define CONTROL_nPRIV_Pos 0 /*!< CONTROL: nPRIV Position */ #define CONTROL_nPRIV_Msk (1UL /*<< CONTROL_nPRIV_Pos*/) /*!< CONTROL: nPRIV Mask */ /*@} end of group CMSIS_CORE */ /** \ingroup CMSIS_core_register \defgroup CMSIS_NVIC Nested Vectored Interrupt Controller (NVIC) \brief Type definitions for the NVIC Registers @{ */ /** \brief Structure type to access the Nested Vectored Interrupt Controller (NVIC). */ typedef struct { __IO uint32_t ISER[1]; /*!< Offset: 0x000 (R/W) Interrupt Set Enable Register */ uint32_t RESERVED0[31]; __IO uint32_t ICER[1]; /*!< Offset: 0x080 (R/W) Interrupt Clear Enable Register */ uint32_t RSERVED1[31]; __IO uint32_t ISPR[1]; /*!< Offset: 0x100 (R/W) Interrupt Set Pending Register */ uint32_t RESERVED2[31]; __IO uint32_t ICPR[1]; /*!< Offset: 0x180 (R/W) Interrupt Clear Pending Register */ uint32_t RESERVED3[31]; uint32_t RESERVED4[64]; __IO uint32_t IP[8]; /*!< Offset: 0x300 (R/W) Interrupt Priority Register */ } NVIC_Type; /*@} end of group CMSIS_NVIC */ /** \ingroup CMSIS_core_register \defgroup CMSIS_SCB System Control Block (SCB) \brief Type definitions for the System Control Block Registers @{ */ /** \brief Structure type to access the System Control Block (SCB). */ typedef struct { __I uint32_t CPUID; /*!< Offset: 0x000 (R/ ) CPUID Base Register */ __IO uint32_t ICSR; /*!< Offset: 0x004 (R/W) Interrupt Control and State Register */ #if (__VTOR_PRESENT == 1) __IO uint32_t VTOR; /*!< Offset: 0x008 (R/W) Vector Table Offset Register */ #else uint32_t RESERVED0; #endif __IO uint32_t AIRCR; /*!< Offset: 0x00C (R/W) Application Interrupt and Reset Control Register */ __IO uint32_t SCR; /*!< Offset: 0x010 (R/W) System Control Register */ __IO uint32_t CCR; /*!< Offset: 0x014 (R/W) Configuration Control Register */ uint32_t RESERVED1; __IO uint32_t SHP[2]; /*!< Offset: 0x01C (R/W) System Handlers Priority Registers. [0] is RESERVED */ __IO uint32_t SHCSR; /*!< Offset: 0x024 (R/W) System Handler Control and State Register */ } SCB_Type; /* SCB CPUID Register Definitions */ #define SCB_CPUID_IMPLEMENTER_Pos 24 /*!< SCB CPUID: IMPLEMENTER Position */ #define SCB_CPUID_IMPLEMENTER_Msk (0xFFUL << SCB_CPUID_IMPLEMENTER_Pos) /*!< SCB CPUID: IMPLEMENTER Mask */ #define SCB_CPUID_VARIANT_Pos 20 /*!< SCB CPUID: VARIANT Position */ #define SCB_CPUID_VARIANT_Msk (0xFUL << SCB_CPUID_VARIANT_Pos) /*!< SCB CPUID: VARIANT Mask */ #define SCB_CPUID_ARCHITECTURE_Pos 16 /*!< SCB CPUID: ARCHITECTURE Position */ #define SCB_CPUID_ARCHITECTURE_Msk (0xFUL << SCB_CPUID_ARCHITECTURE_Pos) /*!< SCB CPUID: ARCHITECTURE Mask */ #define SCB_CPUID_PARTNO_Pos 4 /*!< SCB CPUID: PARTNO Position */ #define SCB_CPUID_PARTNO_Msk (0xFFFUL << SCB_CPUID_PARTNO_Pos) /*!< SCB CPUID: PARTNO Mask */ #define SCB_CPUID_REVISION_Pos 0 /*!< SCB CPUID: REVISION Position */ #define SCB_CPUID_REVISION_Msk (0xFUL /*<< SCB_CPUID_REVISION_Pos*/) /*!< SCB CPUID: REVISION Mask */ /* SCB Interrupt Control State Register Definitions */ #define SCB_ICSR_NMIPENDSET_Pos 31 /*!< SCB ICSR: NMIPENDSET Position */ #define SCB_ICSR_NMIPENDSET_Msk (1UL << SCB_ICSR_NMIPENDSET_Pos) /*!< SCB ICSR: NMIPENDSET Mask */ #define SCB_ICSR_PENDSVSET_Pos 28 /*!< SCB ICSR: PENDSVSET Position */ #define SCB_ICSR_PENDSVSET_Msk (1UL << SCB_ICSR_PENDSVSET_Pos) /*!< SCB ICSR: PENDSVSET Mask */ #define SCB_ICSR_PENDSVCLR_Pos 27 /*!< SCB ICSR: PENDSVCLR Position */ #define SCB_ICSR_PENDSVCLR_Msk (1UL << SCB_ICSR_PENDSVCLR_Pos) /*!< SCB ICSR: PENDSVCLR Mask */ #define SCB_ICSR_PENDSTSET_Pos 26 /*!< SCB ICSR: PENDSTSET Position */ #define SCB_ICSR_PENDSTSET_Msk (1UL << SCB_ICSR_PENDSTSET_Pos) /*!< SCB ICSR: PENDSTSET Mask */ #define SCB_ICSR_PENDSTCLR_Pos 25 /*!< SCB ICSR: PENDSTCLR Position */ #define SCB_ICSR_PENDSTCLR_Msk (1UL << SCB_ICSR_PENDSTCLR_Pos) /*!< SCB ICSR: PENDSTCLR Mask */ #define SCB_ICSR_ISRPREEMPT_Pos 23 /*!< SCB ICSR: ISRPREEMPT Position */ #define SCB_ICSR_ISRPREEMPT_Msk (1UL << SCB_ICSR_ISRPREEMPT_Pos) /*!< SCB ICSR: ISRPREEMPT Mask */ #define SCB_ICSR_ISRPENDING_Pos 22 /*!< SCB ICSR: ISRPENDING Position */ #define SCB_ICSR_ISRPENDING_Msk (1UL << SCB_ICSR_ISRPENDING_Pos) /*!< SCB ICSR: ISRPENDING Mask */ #define SCB_ICSR_VECTPENDING_Pos 12 /*!< SCB ICSR: VECTPENDING Position */ #define SCB_ICSR_VECTPENDING_Msk (0x1FFUL << SCB_ICSR_VECTPENDING_Pos) /*!< SCB ICSR: VECTPENDING Mask */ #define SCB_ICSR_VECTACTIVE_Pos 0 /*!< SCB ICSR: VECTACTIVE Position */ #define SCB_ICSR_VECTACTIVE_Msk (0x1FFUL /*<< SCB_ICSR_VECTACTIVE_Pos*/) /*!< SCB ICSR: VECTACTIVE Mask */ #if (__VTOR_PRESENT == 1) /* SCB Interrupt Control State Register Definitions */ #define SCB_VTOR_TBLOFF_Pos 8 /*!< SCB VTOR: TBLOFF Position */ #define SCB_VTOR_TBLOFF_Msk (0xFFFFFFUL << SCB_VTOR_TBLOFF_Pos) /*!< SCB VTOR: TBLOFF Mask */ #endif /* SCB Application Interrupt and Reset Control Register Definitions */ #define SCB_AIRCR_VECTKEY_Pos 16 /*!< SCB AIRCR: VECTKEY Position */ #define SCB_AIRCR_VECTKEY_Msk (0xFFFFUL << SCB_AIRCR_VECTKEY_Pos) /*!< SCB AIRCR: VECTKEY Mask */ #define SCB_AIRCR_VECTKEYSTAT_Pos 16 /*!< SCB AIRCR: VECTKEYSTAT Position */ #define SCB_AIRCR_VECTKEYSTAT_Msk (0xFFFFUL << SCB_AIRCR_VECTKEYSTAT_Pos) /*!< SCB AIRCR: VECTKEYSTAT Mask */ #define SCB_AIRCR_ENDIANESS_Pos 15 /*!< SCB AIRCR: ENDIANESS Position */ #define SCB_AIRCR_ENDIANESS_Msk (1UL << SCB_AIRCR_ENDIANESS_Pos) /*!< SCB AIRCR: ENDIANESS Mask */ #define SCB_AIRCR_SYSRESETREQ_Pos 2 /*!< SCB AIRCR: SYSRESETREQ Position */ #define SCB_AIRCR_SYSRESETREQ_Msk (1UL << SCB_AIRCR_SYSRESETREQ_Pos) /*!< SCB AIRCR: SYSRESETREQ Mask */ #define SCB_AIRCR_VECTCLRACTIVE_Pos 1 /*!< SCB AIRCR: VECTCLRACTIVE Position */ #define SCB_AIRCR_VECTCLRACTIVE_Msk (1UL << SCB_AIRCR_VECTCLRACTIVE_Pos) /*!< SCB AIRCR: VECTCLRACTIVE Mask */ /* SCB System Control Register Definitions */ #define SCB_SCR_SEVONPEND_Pos 4 /*!< SCB SCR: SEVONPEND Position */ #define SCB_SCR_SEVONPEND_Msk (1UL << SCB_SCR_SEVONPEND_Pos) /*!< SCB SCR: SEVONPEND Mask */ #define SCB_SCR_SLEEPDEEP_Pos 2 /*!< SCB SCR: SLEEPDEEP Position */ #define SCB_SCR_SLEEPDEEP_Msk (1UL << SCB_SCR_SLEEPDEEP_Pos) /*!< SCB SCR: SLEEPDEEP Mask */ #define SCB_SCR_SLEEPONEXIT_Pos 1 /*!< SCB SCR: SLEEPONEXIT Position */ #define SCB_SCR_SLEEPONEXIT_Msk (1UL << SCB_SCR_SLEEPONEXIT_Pos) /*!< SCB SCR: SLEEPONEXIT Mask */ /* SCB Configuration Control Register Definitions */ #define SCB_CCR_STKALIGN_Pos 9 /*!< SCB CCR: STKALIGN Position */ #define SCB_CCR_STKALIGN_Msk (1UL << SCB_CCR_STKALIGN_Pos) /*!< SCB CCR: STKALIGN Mask */ #define SCB_CCR_UNALIGN_TRP_Pos 3 /*!< SCB CCR: UNALIGN_TRP Position */ #define SCB_CCR_UNALIGN_TRP_Msk (1UL << SCB_CCR_UNALIGN_TRP_Pos) /*!< SCB CCR: UNALIGN_TRP Mask */ /* SCB System Handler Control and State Register Definitions */ #define SCB_SHCSR_SVCALLPENDED_Pos 15 /*!< SCB SHCSR: SVCALLPENDED Position */ #define SCB_SHCSR_SVCALLPENDED_Msk (1UL << SCB_SHCSR_SVCALLPENDED_Pos) /*!< SCB SHCSR: SVCALLPENDED Mask */ /*@} end of group CMSIS_SCB */ /** \ingroup CMSIS_core_register \defgroup CMSIS_SysTick System Tick Timer (SysTick) \brief Type definitions for the System Timer Registers. @{ */ /** \brief Structure type to access the System Timer (SysTick). */ typedef struct { __IO uint32_t CTRL; /*!< Offset: 0x000 (R/W) SysTick Control and Status Register */ __IO uint32_t LOAD; /*!< Offset: 0x004 (R/W) SysTick Reload Value Register */ __IO uint32_t VAL; /*!< Offset: 0x008 (R/W) SysTick Current Value Register */ __I uint32_t CALIB; /*!< Offset: 0x00C (R/ ) SysTick Calibration Register */ } SysTick_Type; /* SysTick Control / Status Register Definitions */ #define SysTick_CTRL_COUNTFLAG_Pos 16 /*!< SysTick CTRL: COUNTFLAG Position */ #define SysTick_CTRL_COUNTFLAG_Msk (1UL << SysTick_CTRL_COUNTFLAG_Pos) /*!< SysTick CTRL: COUNTFLAG Mask */ #define SysTick_CTRL_CLKSOURCE_Pos 2 /*!< SysTick CTRL: CLKSOURCE Position */ #define SysTick_CTRL_CLKSOURCE_Msk (1UL << SysTick_CTRL_CLKSOURCE_Pos) /*!< SysTick CTRL: CLKSOURCE Mask */ #define SysTick_CTRL_TICKINT_Pos 1 /*!< SysTick CTRL: TICKINT Position */ #define SysTick_CTRL_TICKINT_Msk (1UL << SysTick_CTRL_TICKINT_Pos) /*!< SysTick CTRL: TICKINT Mask */ #define SysTick_CTRL_ENABLE_Pos 0 /*!< SysTick CTRL: ENABLE Position */ #define SysTick_CTRL_ENABLE_Msk (1UL /*<< SysTick_CTRL_ENABLE_Pos*/) /*!< SysTick CTRL: ENABLE Mask */ /* SysTick Reload Register Definitions */ #define SysTick_LOAD_RELOAD_Pos 0 /*!< SysTick LOAD: RELOAD Position */ #define SysTick_LOAD_RELOAD_Msk (0xFFFFFFUL /*<< SysTick_LOAD_RELOAD_Pos*/) /*!< SysTick LOAD: RELOAD Mask */ /* SysTick Current Register Definitions */ #define SysTick_VAL_CURRENT_Pos 0 /*!< SysTick VAL: CURRENT Position */ #define SysTick_VAL_CURRENT_Msk (0xFFFFFFUL /*<< SysTick_VAL_CURRENT_Pos*/) /*!< SysTick VAL: CURRENT Mask */ /* SysTick Calibration Register Definitions */ #define SysTick_CALIB_NOREF_Pos 31 /*!< SysTick CALIB: NOREF Position */ #define SysTick_CALIB_NOREF_Msk (1UL << SysTick_CALIB_NOREF_Pos) /*!< SysTick CALIB: NOREF Mask */ #define SysTick_CALIB_SKEW_Pos 30 /*!< SysTick CALIB: SKEW Position */ #define SysTick_CALIB_SKEW_Msk (1UL << SysTick_CALIB_SKEW_Pos) /*!< SysTick CALIB: SKEW Mask */ #define SysTick_CALIB_TENMS_Pos 0 /*!< SysTick CALIB: TENMS Position */ #define SysTick_CALIB_TENMS_Msk (0xFFFFFFUL /*<< SysTick_CALIB_TENMS_Pos*/) /*!< SysTick CALIB: TENMS Mask */ /*@} end of group CMSIS_SysTick */ #if (__MPU_PRESENT == 1) /** \ingroup CMSIS_core_register \defgroup CMSIS_MPU Memory Protection Unit (MPU) \brief Type definitions for the Memory Protection Unit (MPU) @{ */ /** \brief Structure type to access the Memory Protection Unit (MPU). */ typedef struct { __I uint32_t TYPE; /*!< Offset: 0x000 (R/ ) MPU Type Register */ __IO uint32_t CTRL; /*!< Offset: 0x004 (R/W) MPU Control Register */ __IO uint32_t RNR; /*!< Offset: 0x008 (R/W) MPU Region RNRber Register */ __IO uint32_t RBAR; /*!< Offset: 0x00C (R/W) MPU Region Base Address Register */ __IO uint32_t RASR; /*!< Offset: 0x010 (R/W) MPU Region Attribute and Size Register */ } MPU_Type; /* MPU Type Register */ #define MPU_TYPE_IREGION_Pos 16 /*!< MPU TYPE: IREGION Position */ #define MPU_TYPE_IREGION_Msk (0xFFUL << MPU_TYPE_IREGION_Pos) /*!< MPU TYPE: IREGION Mask */ #define MPU_TYPE_DREGION_Pos 8 /*!< MPU TYPE: DREGION Position */ #define MPU_TYPE_DREGION_Msk (0xFFUL << MPU_TYPE_DREGION_Pos) /*!< MPU TYPE: DREGION Mask */ #define MPU_TYPE_SEPARATE_Pos 0 /*!< MPU TYPE: SEPARATE Position */ #define MPU_TYPE_SEPARATE_Msk (1UL /*<< MPU_TYPE_SEPARATE_Pos*/) /*!< MPU TYPE: SEPARATE Mask */ /* MPU Control Register */ #define MPU_CTRL_PRIVDEFENA_Pos 2 /*!< MPU CTRL: PRIVDEFENA Position */ #define MPU_CTRL_PRIVDEFENA_Msk (1UL << MPU_CTRL_PRIVDEFENA_Pos) /*!< MPU CTRL: PRIVDEFENA Mask */ #define MPU_CTRL_HFNMIENA_Pos 1 /*!< MPU CTRL: HFNMIENA Position */ #define MPU_CTRL_HFNMIENA_Msk (1UL << MPU_CTRL_HFNMIENA_Pos) /*!< MPU CTRL: HFNMIENA Mask */ #define MPU_CTRL_ENABLE_Pos 0 /*!< MPU CTRL: ENABLE Position */ #define MPU_CTRL_ENABLE_Msk (1UL /*<< MPU_CTRL_ENABLE_Pos*/) /*!< MPU CTRL: ENABLE Mask */ /* MPU Region Number Register */ #define MPU_RNR_REGION_Pos 0 /*!< MPU RNR: REGION Position */ #define MPU_RNR_REGION_Msk (0xFFUL /*<< MPU_RNR_REGION_Pos*/) /*!< MPU RNR: REGION Mask */ /* MPU Region Base Address Register */ #define MPU_RBAR_ADDR_Pos 8 /*!< MPU RBAR: ADDR Position */ #define MPU_RBAR_ADDR_Msk (0xFFFFFFUL << MPU_RBAR_ADDR_Pos) /*!< MPU RBAR: ADDR Mask */ #define MPU_RBAR_VALID_Pos 4 /*!< MPU RBAR: VALID Position */ #define MPU_RBAR_VALID_Msk (1UL << MPU_RBAR_VALID_Pos) /*!< MPU RBAR: VALID Mask */ #define MPU_RBAR_REGION_Pos 0 /*!< MPU RBAR: REGION Position */ #define MPU_RBAR_REGION_Msk (0xFUL /*<< MPU_RBAR_REGION_Pos*/) /*!< MPU RBAR: REGION Mask */ /* MPU Region Attribute and Size Register */ #define MPU_RASR_ATTRS_Pos 16 /*!< MPU RASR: MPU Region Attribute field Position */ #define MPU_RASR_ATTRS_Msk (0xFFFFUL << MPU_RASR_ATTRS_Pos) /*!< MPU RASR: MPU Region Attribute field Mask */ #define MPU_RASR_XN_Pos 28 /*!< MPU RASR: ATTRS.XN Position */ #define MPU_RASR_XN_Msk (1UL << MPU_RASR_XN_Pos) /*!< MPU RASR: ATTRS.XN Mask */ #define MPU_RASR_AP_Pos 24 /*!< MPU RASR: ATTRS.AP Position */ #define MPU_RASR_AP_Msk (0x7UL << MPU_RASR_AP_Pos) /*!< MPU RASR: ATTRS.AP Mask */ #define MPU_RASR_TEX_Pos 19 /*!< MPU RASR: ATTRS.TEX Position */ #define MPU_RASR_TEX_Msk (0x7UL << MPU_RASR_TEX_Pos) /*!< MPU RASR: ATTRS.TEX Mask */ #define MPU_RASR_S_Pos 18 /*!< MPU RASR: ATTRS.S Position */ #define MPU_RASR_S_Msk (1UL << MPU_RASR_S_Pos) /*!< MPU RASR: ATTRS.S Mask */ #define MPU_RASR_C_Pos 17 /*!< MPU RASR: ATTRS.C Position */ #define MPU_RASR_C_Msk (1UL << MPU_RASR_C_Pos) /*!< MPU RASR: ATTRS.C Mask */ #define MPU_RASR_B_Pos 16 /*!< MPU RASR: ATTRS.B Position */ #define MPU_RASR_B_Msk (1UL << MPU_RASR_B_Pos) /*!< MPU RASR: ATTRS.B Mask */ #define MPU_RASR_SRD_Pos 8 /*!< MPU RASR: Sub-Region Disable Position */ #define MPU_RASR_SRD_Msk (0xFFUL << MPU_RASR_SRD_Pos) /*!< MPU RASR: Sub-Region Disable Mask */ #define MPU_RASR_SIZE_Pos 1 /*!< MPU RASR: Region Size Field Position */ #define MPU_RASR_SIZE_Msk (0x1FUL << MPU_RASR_SIZE_Pos) /*!< MPU RASR: Region Size Field Mask */ #define MPU_RASR_ENABLE_Pos 0 /*!< MPU RASR: Region enable bit Position */ #define MPU_RASR_ENABLE_Msk (1UL /*<< MPU_RASR_ENABLE_Pos*/) /*!< MPU RASR: Region enable bit Disable Mask */ /*@} end of group CMSIS_MPU */ #endif /** \ingroup CMSIS_core_register \defgroup CMSIS_CoreDebug Core Debug Registers (CoreDebug) \brief Cortex-M0+ Core Debug Registers (DCB registers, SHCSR, and DFSR) are only accessible over DAP and not via processor. Therefore they are not covered by the Cortex-M0 header file. @{ */ /*@} end of group CMSIS_CoreDebug */ /** \ingroup CMSIS_core_register \defgroup CMSIS_core_base Core Definitions \brief Definitions for base addresses, unions, and structures. @{ */ /* Memory mapping of Cortex-M0+ Hardware */ #define SCS_BASE (0xE000E000UL) /*!< System Control Space Base Address */ #define SysTick_BASE (SCS_BASE + 0x0010UL) /*!< SysTick Base Address */ #define NVIC_BASE (SCS_BASE + 0x0100UL) /*!< NVIC Base Address */ #define SCB_BASE (SCS_BASE + 0x0D00UL) /*!< System Control Block Base Address */ #define SCB ((SCB_Type *) SCB_BASE ) /*!< SCB configuration struct */ #define SysTick ((SysTick_Type *) SysTick_BASE ) /*!< SysTick configuration struct */ #define NVIC ((NVIC_Type *) NVIC_BASE ) /*!< NVIC configuration struct */ #if (__MPU_PRESENT == 1) #define MPU_BASE (SCS_BASE + 0x0D90UL) /*!< Memory Protection Unit */ #define MPU ((MPU_Type *) MPU_BASE ) /*!< Memory Protection Unit */ #endif /*@} */ /******************************************************************************* * Hardware Abstraction Layer Core Function Interface contains: - Core NVIC Functions - Core SysTick Functions - Core Register Access Functions ******************************************************************************/ /** \defgroup CMSIS_Core_FunctionInterface Functions and Instructions Reference */ /* ########################## NVIC functions #################################### */ /** \ingroup CMSIS_Core_FunctionInterface \defgroup CMSIS_Core_NVICFunctions NVIC Functions \brief Functions that manage interrupts and exceptions via the NVIC. @{ */ /* Interrupt Priorities are WORD accessible only under ARMv6M */ /* The following MACROS handle generation of the register offset and byte masks */ #define _BIT_SHIFT(IRQn) ( ((((uint32_t)(int32_t)(IRQn)) ) & 0x03UL) * 8UL) #define _SHP_IDX(IRQn) ( (((((uint32_t)(int32_t)(IRQn)) & 0x0FUL)-8UL) >> 2UL) ) #define _IP_IDX(IRQn) ( (((uint32_t)(int32_t)(IRQn)) >> 2UL) ) /** \brief Enable External Interrupt The function enables a device-specific interrupt in the NVIC interrupt controller. \param [in] IRQn External interrupt number. Value cannot be negative. */ __STATIC_INLINE void NVIC_EnableIRQ(IRQn_Type IRQn) { NVIC->ISER[0] = (uint32_t)(1UL << (((uint32_t)(int32_t)IRQn) & 0x1FUL)); } /** \brief Disable External Interrupt The function disables a device-specific interrupt in the NVIC interrupt controller. \param [in] IRQn External interrupt number. Value cannot be negative. */ __STATIC_INLINE void NVIC_DisableIRQ(IRQn_Type IRQn) { NVIC->ICER[0] = (uint32_t)(1UL << (((uint32_t)(int32_t)IRQn) & 0x1FUL)); } /** \brief Get Pending Interrupt The function reads the pending register in the NVIC and returns the pending bit for the specified interrupt. \param [in] IRQn Interrupt number. \return 0 Interrupt status is not pending. \return 1 Interrupt status is pending. */ __STATIC_INLINE uint32_t NVIC_GetPendingIRQ(IRQn_Type IRQn) { return((uint32_t)(((NVIC->ISPR[0] & (1UL << (((uint32_t)(int32_t)IRQn) & 0x1FUL))) != 0UL) ? 1UL : 0UL)); } /** \brief Set Pending Interrupt The function sets the pending bit of an external interrupt. \param [in] IRQn Interrupt number. Value cannot be negative. */ __STATIC_INLINE void NVIC_SetPendingIRQ(IRQn_Type IRQn) { NVIC->ISPR[0] = (uint32_t)(1UL << (((uint32_t)(int32_t)IRQn) & 0x1FUL)); } /** \brief Clear Pending Interrupt The function clears the pending bit of an external interrupt. \param [in] IRQn External interrupt number. Value cannot be negative. */ __STATIC_INLINE void NVIC_ClearPendingIRQ(IRQn_Type IRQn) { NVIC->ICPR[0] = (uint32_t)(1UL << (((uint32_t)(int32_t)IRQn) & 0x1FUL)); } /** \brief Set Interrupt Priority The function sets the priority of an interrupt. \note The priority cannot be set for every core interrupt. \param [in] IRQn Interrupt number. \param [in] priority Priority to set. */ __STATIC_INLINE void NVIC_SetPriority(IRQn_Type IRQn, uint32_t priority) { if((int32_t)(IRQn) < 0) { SCB->SHP[_SHP_IDX(IRQn)] = ((uint32_t)(SCB->SHP[_SHP_IDX(IRQn)] & ~(0xFFUL << _BIT_SHIFT(IRQn))) | (((priority << (8 - __NVIC_PRIO_BITS)) & (uint32_t)0xFFUL) << _BIT_SHIFT(IRQn))); } else { NVIC->IP[_IP_IDX(IRQn)] = ((uint32_t)(NVIC->IP[_IP_IDX(IRQn)] & ~(0xFFUL << _BIT_SHIFT(IRQn))) | (((priority << (8 - __NVIC_PRIO_BITS)) & (uint32_t)0xFFUL) << _BIT_SHIFT(IRQn))); } } /** \brief Get Interrupt Priority The function reads the priority of an interrupt. The interrupt number can be positive to specify an external (device specific) interrupt, or negative to specify an internal (core) interrupt. \param [in] IRQn Interrupt number. \return Interrupt Priority. Value is aligned automatically to the implemented priority bits of the microcontroller. */ __STATIC_INLINE uint32_t NVIC_GetPriority(IRQn_Type IRQn) { if((int32_t)(IRQn) < 0) { return((uint32_t)(((SCB->SHP[_SHP_IDX(IRQn)] >> _BIT_SHIFT(IRQn) ) & (uint32_t)0xFFUL) >> (8 - __NVIC_PRIO_BITS))); } else { return((uint32_t)(((NVIC->IP[ _IP_IDX(IRQn)] >> _BIT_SHIFT(IRQn) ) & (uint32_t)0xFFUL) >> (8 - __NVIC_PRIO_BITS))); } } /** \brief System Reset The function initiates a system reset request to reset the MCU. */ __STATIC_INLINE void NVIC_SystemReset(void) { __DSB(); /* Ensure all outstanding memory accesses included buffered write are completed before reset */ SCB->AIRCR = ((0x5FAUL << SCB_AIRCR_VECTKEY_Pos) | SCB_AIRCR_SYSRESETREQ_Msk); __DSB(); /* Ensure completion of memory access */ while(1) { __NOP(); } /* wait until reset */ } /*@} end of CMSIS_Core_NVICFunctions */ /* ################################## SysTick function ############################################ */ /** \ingroup CMSIS_Core_FunctionInterface \defgroup CMSIS_Core_SysTickFunctions SysTick Functions \brief Functions that configure the System. @{ */ #if (__Vendor_SysTickConfig == 0) /** \brief System Tick Configuration The function initializes the System Timer and its interrupt, and starts the System Tick Timer. Counter is in free running mode to generate periodic interrupts. \param [in] ticks Number of ticks between two interrupts. \return 0 Function succeeded. \return 1 Function failed. \note When the variable __Vendor_SysTickConfig is set to 1, then the function SysTick_Config is not included. In this case, the file device.h must contain a vendor-specific implementation of this function. */ __STATIC_INLINE uint32_t SysTick_Config(uint32_t ticks) { if ((ticks - 1UL) > SysTick_LOAD_RELOAD_Msk) {return (1UL);} /* Reload value impossible */ SysTick->LOAD = (uint32_t)(ticks - 1UL); /* set reload register */ NVIC_SetPriority (SysTick_IRQn, (1UL << __NVIC_PRIO_BITS) - 1UL); /* set Priority for Systick Interrupt */ SysTick->VAL = 0UL; /* Load the SysTick Counter Value */ SysTick->CTRL = SysTick_CTRL_CLKSOURCE_Msk | SysTick_CTRL_TICKINT_Msk | SysTick_CTRL_ENABLE_Msk; /* Enable SysTick IRQ and SysTick Timer */ return (0UL); /* Function successful */ } #endif /*@} end of CMSIS_Core_SysTickFunctions */ #ifdef __cplusplus } #endif #endif /* __CORE_CM0PLUS_H_DEPENDANT */ #endif /* __CMSIS_GENERIC */ ================================================ FILE: Zelig/mbed/TARGET_NUCLEO_F411RE/core_cm3.h ================================================ /**************************************************************************//** * @file core_cm3.h * @brief CMSIS Cortex-M3 Core Peripheral Access Layer Header File * @version V4.10 * @date 18. March 2015 * * @note * ******************************************************************************/ /* Copyright (c) 2009 - 2015 ARM LIMITED All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: - Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. - Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. - Neither the name of ARM 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 COPYRIGHT HOLDERS AND 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. ---------------------------------------------------------------------------*/ #if defined ( __ICCARM__ ) #pragma system_include /* treat file as system include file for MISRA check */ #endif #ifndef __CORE_CM3_H_GENERIC #define __CORE_CM3_H_GENERIC #ifdef __cplusplus extern "C" { #endif /** \page CMSIS_MISRA_Exceptions MISRA-C:2004 Compliance Exceptions CMSIS violates the following MISRA-C:2004 rules: \li Required Rule 8.5, object/function definition in header file.
Function definitions in header files are used to allow 'inlining'. \li Required Rule 18.4, declaration of union type or object of union type: '{...}'.
Unions are used for effective representation of core registers. \li Advisory Rule 19.7, Function-like macro defined.
Function-like macros are used to allow more efficient code. */ /******************************************************************************* * CMSIS definitions ******************************************************************************/ /** \ingroup Cortex_M3 @{ */ /* CMSIS CM3 definitions */ #define __CM3_CMSIS_VERSION_MAIN (0x04) /*!< [31:16] CMSIS HAL main version */ #define __CM3_CMSIS_VERSION_SUB (0x00) /*!< [15:0] CMSIS HAL sub version */ #define __CM3_CMSIS_VERSION ((__CM3_CMSIS_VERSION_MAIN << 16) | \ __CM3_CMSIS_VERSION_SUB ) /*!< CMSIS HAL version number */ #define __CORTEX_M (0x03) /*!< Cortex-M Core */ #if defined ( __CC_ARM ) #define __ASM __asm /*!< asm keyword for ARM Compiler */ #define __INLINE __inline /*!< inline keyword for ARM Compiler */ #define __STATIC_INLINE static __inline #elif defined ( __GNUC__ ) #define __ASM __asm /*!< asm keyword for GNU Compiler */ #define __INLINE inline /*!< inline keyword for GNU Compiler */ #define __STATIC_INLINE static inline #elif defined ( __ICCARM__ ) #define __ASM __asm /*!< asm keyword for IAR Compiler */ #define __INLINE inline /*!< inline keyword for IAR Compiler. Only available in High optimization mode! */ #define __STATIC_INLINE static inline #elif defined ( __TMS470__ ) #define __ASM __asm /*!< asm keyword for TI CCS Compiler */ #define __STATIC_INLINE static inline #elif defined ( __TASKING__ ) #define __ASM __asm /*!< asm keyword for TASKING Compiler */ #define __INLINE inline /*!< inline keyword for TASKING Compiler */ #define __STATIC_INLINE static inline #elif defined ( __CSMC__ ) #define __packed #define __ASM _asm /*!< asm keyword for COSMIC Compiler */ #define __INLINE inline /*use -pc99 on compile line !< inline keyword for COSMIC Compiler */ #define __STATIC_INLINE static inline #endif /** __FPU_USED indicates whether an FPU is used or not. This core does not support an FPU at all */ #define __FPU_USED 0 #if defined ( __CC_ARM ) #if defined __TARGET_FPU_VFP #warning "Compiler generates FPU instructions for a device without an FPU (check __FPU_PRESENT)" #endif #elif defined ( __GNUC__ ) #if defined (__VFP_FP__) && !defined(__SOFTFP__) #warning "Compiler generates FPU instructions for a device without an FPU (check __FPU_PRESENT)" #endif #elif defined ( __ICCARM__ ) #if defined __ARMVFP__ #warning "Compiler generates FPU instructions for a device without an FPU (check __FPU_PRESENT)" #endif #elif defined ( __TMS470__ ) #if defined __TI__VFP_SUPPORT____ #warning "Compiler generates FPU instructions for a device without an FPU (check __FPU_PRESENT)" #endif #elif defined ( __TASKING__ ) #if defined __FPU_VFP__ #error "Compiler generates FPU instructions for a device without an FPU (check __FPU_PRESENT)" #endif #elif defined ( __CSMC__ ) /* Cosmic */ #if ( __CSMC__ & 0x400) // FPU present for parser #error "Compiler generates FPU instructions for a device without an FPU (check __FPU_PRESENT)" #endif #endif #include /* standard types definitions */ #include /* Core Instruction Access */ #include /* Core Function Access */ #ifdef __cplusplus } #endif #endif /* __CORE_CM3_H_GENERIC */ #ifndef __CMSIS_GENERIC #ifndef __CORE_CM3_H_DEPENDANT #define __CORE_CM3_H_DEPENDANT #ifdef __cplusplus extern "C" { #endif /* check device defines and use defaults */ #if defined __CHECK_DEVICE_DEFINES #ifndef __CM3_REV #define __CM3_REV 0x0200 #warning "__CM3_REV not defined in device header file; using default!" #endif #ifndef __MPU_PRESENT #define __MPU_PRESENT 0 #warning "__MPU_PRESENT not defined in device header file; using default!" #endif #ifndef __NVIC_PRIO_BITS #define __NVIC_PRIO_BITS 4 #warning "__NVIC_PRIO_BITS not defined in device header file; using default!" #endif #ifndef __Vendor_SysTickConfig #define __Vendor_SysTickConfig 0 #warning "__Vendor_SysTickConfig not defined in device header file; using default!" #endif #endif /* IO definitions (access restrictions to peripheral registers) */ /** \defgroup CMSIS_glob_defs CMSIS Global Defines IO Type Qualifiers are used \li to specify the access to peripheral variables. \li for automatic generation of peripheral register debug information. */ #ifdef __cplusplus #define __I volatile /*!< Defines 'read only' permissions */ #else #define __I volatile const /*!< Defines 'read only' permissions */ #endif #define __O volatile /*!< Defines 'write only' permissions */ #define __IO volatile /*!< Defines 'read / write' permissions */ /*@} end of group Cortex_M3 */ /******************************************************************************* * Register Abstraction Core Register contain: - Core Register - Core NVIC Register - Core SCB Register - Core SysTick Register - Core Debug Register - Core MPU Register ******************************************************************************/ /** \defgroup CMSIS_core_register Defines and Type Definitions \brief Type definitions and defines for Cortex-M processor based devices. */ /** \ingroup CMSIS_core_register \defgroup CMSIS_CORE Status and Control Registers \brief Core Register type definitions. @{ */ /** \brief Union type to access the Application Program Status Register (APSR). */ typedef union { struct { uint32_t _reserved0:27; /*!< bit: 0..26 Reserved */ uint32_t Q:1; /*!< bit: 27 Saturation condition flag */ uint32_t V:1; /*!< bit: 28 Overflow condition code flag */ uint32_t C:1; /*!< bit: 29 Carry condition code flag */ uint32_t Z:1; /*!< bit: 30 Zero condition code flag */ uint32_t N:1; /*!< bit: 31 Negative condition code flag */ } b; /*!< Structure used for bit access */ uint32_t w; /*!< Type used for word access */ } APSR_Type; /* APSR Register Definitions */ #define APSR_N_Pos 31 /*!< APSR: N Position */ #define APSR_N_Msk (1UL << APSR_N_Pos) /*!< APSR: N Mask */ #define APSR_Z_Pos 30 /*!< APSR: Z Position */ #define APSR_Z_Msk (1UL << APSR_Z_Pos) /*!< APSR: Z Mask */ #define APSR_C_Pos 29 /*!< APSR: C Position */ #define APSR_C_Msk (1UL << APSR_C_Pos) /*!< APSR: C Mask */ #define APSR_V_Pos 28 /*!< APSR: V Position */ #define APSR_V_Msk (1UL << APSR_V_Pos) /*!< APSR: V Mask */ #define APSR_Q_Pos 27 /*!< APSR: Q Position */ #define APSR_Q_Msk (1UL << APSR_Q_Pos) /*!< APSR: Q Mask */ /** \brief Union type to access the Interrupt Program Status Register (IPSR). */ typedef union { struct { uint32_t ISR:9; /*!< bit: 0.. 8 Exception number */ uint32_t _reserved0:23; /*!< bit: 9..31 Reserved */ } b; /*!< Structure used for bit access */ uint32_t w; /*!< Type used for word access */ } IPSR_Type; /* IPSR Register Definitions */ #define IPSR_ISR_Pos 0 /*!< IPSR: ISR Position */ #define IPSR_ISR_Msk (0x1FFUL /*<< IPSR_ISR_Pos*/) /*!< IPSR: ISR Mask */ /** \brief Union type to access the Special-Purpose Program Status Registers (xPSR). */ typedef union { struct { uint32_t ISR:9; /*!< bit: 0.. 8 Exception number */ uint32_t _reserved0:15; /*!< bit: 9..23 Reserved */ uint32_t T:1; /*!< bit: 24 Thumb bit (read 0) */ uint32_t IT:2; /*!< bit: 25..26 saved IT state (read 0) */ uint32_t Q:1; /*!< bit: 27 Saturation condition flag */ uint32_t V:1; /*!< bit: 28 Overflow condition code flag */ uint32_t C:1; /*!< bit: 29 Carry condition code flag */ uint32_t Z:1; /*!< bit: 30 Zero condition code flag */ uint32_t N:1; /*!< bit: 31 Negative condition code flag */ } b; /*!< Structure used for bit access */ uint32_t w; /*!< Type used for word access */ } xPSR_Type; /* xPSR Register Definitions */ #define xPSR_N_Pos 31 /*!< xPSR: N Position */ #define xPSR_N_Msk (1UL << xPSR_N_Pos) /*!< xPSR: N Mask */ #define xPSR_Z_Pos 30 /*!< xPSR: Z Position */ #define xPSR_Z_Msk (1UL << xPSR_Z_Pos) /*!< xPSR: Z Mask */ #define xPSR_C_Pos 29 /*!< xPSR: C Position */ #define xPSR_C_Msk (1UL << xPSR_C_Pos) /*!< xPSR: C Mask */ #define xPSR_V_Pos 28 /*!< xPSR: V Position */ #define xPSR_V_Msk (1UL << xPSR_V_Pos) /*!< xPSR: V Mask */ #define xPSR_Q_Pos 27 /*!< xPSR: Q Position */ #define xPSR_Q_Msk (1UL << xPSR_Q_Pos) /*!< xPSR: Q Mask */ #define xPSR_IT_Pos 25 /*!< xPSR: IT Position */ #define xPSR_IT_Msk (3UL << xPSR_IT_Pos) /*!< xPSR: IT Mask */ #define xPSR_T_Pos 24 /*!< xPSR: T Position */ #define xPSR_T_Msk (1UL << xPSR_T_Pos) /*!< xPSR: T Mask */ #define xPSR_ISR_Pos 0 /*!< xPSR: ISR Position */ #define xPSR_ISR_Msk (0x1FFUL /*<< xPSR_ISR_Pos*/) /*!< xPSR: ISR Mask */ /** \brief Union type to access the Control Registers (CONTROL). */ typedef union { struct { uint32_t nPRIV:1; /*!< bit: 0 Execution privilege in Thread mode */ uint32_t SPSEL:1; /*!< bit: 1 Stack to be used */ uint32_t _reserved1:30; /*!< bit: 2..31 Reserved */ } b; /*!< Structure used for bit access */ uint32_t w; /*!< Type used for word access */ } CONTROL_Type; /* CONTROL Register Definitions */ #define CONTROL_SPSEL_Pos 1 /*!< CONTROL: SPSEL Position */ #define CONTROL_SPSEL_Msk (1UL << CONTROL_SPSEL_Pos) /*!< CONTROL: SPSEL Mask */ #define CONTROL_nPRIV_Pos 0 /*!< CONTROL: nPRIV Position */ #define CONTROL_nPRIV_Msk (1UL /*<< CONTROL_nPRIV_Pos*/) /*!< CONTROL: nPRIV Mask */ /*@} end of group CMSIS_CORE */ /** \ingroup CMSIS_core_register \defgroup CMSIS_NVIC Nested Vectored Interrupt Controller (NVIC) \brief Type definitions for the NVIC Registers @{ */ /** \brief Structure type to access the Nested Vectored Interrupt Controller (NVIC). */ typedef struct { __IO uint32_t ISER[8]; /*!< Offset: 0x000 (R/W) Interrupt Set Enable Register */ uint32_t RESERVED0[24]; __IO uint32_t ICER[8]; /*!< Offset: 0x080 (R/W) Interrupt Clear Enable Register */ uint32_t RSERVED1[24]; __IO uint32_t ISPR[8]; /*!< Offset: 0x100 (R/W) Interrupt Set Pending Register */ uint32_t RESERVED2[24]; __IO uint32_t ICPR[8]; /*!< Offset: 0x180 (R/W) Interrupt Clear Pending Register */ uint32_t RESERVED3[24]; __IO uint32_t IABR[8]; /*!< Offset: 0x200 (R/W) Interrupt Active bit Register */ uint32_t RESERVED4[56]; __IO uint8_t IP[240]; /*!< Offset: 0x300 (R/W) Interrupt Priority Register (8Bit wide) */ uint32_t RESERVED5[644]; __O uint32_t STIR; /*!< Offset: 0xE00 ( /W) Software Trigger Interrupt Register */ } NVIC_Type; /* Software Triggered Interrupt Register Definitions */ #define NVIC_STIR_INTID_Pos 0 /*!< STIR: INTLINESNUM Position */ #define NVIC_STIR_INTID_Msk (0x1FFUL /*<< NVIC_STIR_INTID_Pos*/) /*!< STIR: INTLINESNUM Mask */ /*@} end of group CMSIS_NVIC */ /** \ingroup CMSIS_core_register \defgroup CMSIS_SCB System Control Block (SCB) \brief Type definitions for the System Control Block Registers @{ */ /** \brief Structure type to access the System Control Block (SCB). */ typedef struct { __I uint32_t CPUID; /*!< Offset: 0x000 (R/ ) CPUID Base Register */ __IO uint32_t ICSR; /*!< Offset: 0x004 (R/W) Interrupt Control and State Register */ __IO uint32_t VTOR; /*!< Offset: 0x008 (R/W) Vector Table Offset Register */ __IO uint32_t AIRCR; /*!< Offset: 0x00C (R/W) Application Interrupt and Reset Control Register */ __IO uint32_t SCR; /*!< Offset: 0x010 (R/W) System Control Register */ __IO uint32_t CCR; /*!< Offset: 0x014 (R/W) Configuration Control Register */ __IO uint8_t SHP[12]; /*!< Offset: 0x018 (R/W) System Handlers Priority Registers (4-7, 8-11, 12-15) */ __IO uint32_t SHCSR; /*!< Offset: 0x024 (R/W) System Handler Control and State Register */ __IO uint32_t CFSR; /*!< Offset: 0x028 (R/W) Configurable Fault Status Register */ __IO uint32_t HFSR; /*!< Offset: 0x02C (R/W) HardFault Status Register */ __IO uint32_t DFSR; /*!< Offset: 0x030 (R/W) Debug Fault Status Register */ __IO uint32_t MMFAR; /*!< Offset: 0x034 (R/W) MemManage Fault Address Register */ __IO uint32_t BFAR; /*!< Offset: 0x038 (R/W) BusFault Address Register */ __IO uint32_t AFSR; /*!< Offset: 0x03C (R/W) Auxiliary Fault Status Register */ __I uint32_t PFR[2]; /*!< Offset: 0x040 (R/ ) Processor Feature Register */ __I uint32_t DFR; /*!< Offset: 0x048 (R/ ) Debug Feature Register */ __I uint32_t ADR; /*!< Offset: 0x04C (R/ ) Auxiliary Feature Register */ __I uint32_t MMFR[4]; /*!< Offset: 0x050 (R/ ) Memory Model Feature Register */ __I uint32_t ISAR[5]; /*!< Offset: 0x060 (R/ ) Instruction Set Attributes Register */ uint32_t RESERVED0[5]; __IO uint32_t CPACR; /*!< Offset: 0x088 (R/W) Coprocessor Access Control Register */ } SCB_Type; /* SCB CPUID Register Definitions */ #define SCB_CPUID_IMPLEMENTER_Pos 24 /*!< SCB CPUID: IMPLEMENTER Position */ #define SCB_CPUID_IMPLEMENTER_Msk (0xFFUL << SCB_CPUID_IMPLEMENTER_Pos) /*!< SCB CPUID: IMPLEMENTER Mask */ #define SCB_CPUID_VARIANT_Pos 20 /*!< SCB CPUID: VARIANT Position */ #define SCB_CPUID_VARIANT_Msk (0xFUL << SCB_CPUID_VARIANT_Pos) /*!< SCB CPUID: VARIANT Mask */ #define SCB_CPUID_ARCHITECTURE_Pos 16 /*!< SCB CPUID: ARCHITECTURE Position */ #define SCB_CPUID_ARCHITECTURE_Msk (0xFUL << SCB_CPUID_ARCHITECTURE_Pos) /*!< SCB CPUID: ARCHITECTURE Mask */ #define SCB_CPUID_PARTNO_Pos 4 /*!< SCB CPUID: PARTNO Position */ #define SCB_CPUID_PARTNO_Msk (0xFFFUL << SCB_CPUID_PARTNO_Pos) /*!< SCB CPUID: PARTNO Mask */ #define SCB_CPUID_REVISION_Pos 0 /*!< SCB CPUID: REVISION Position */ #define SCB_CPUID_REVISION_Msk (0xFUL /*<< SCB_CPUID_REVISION_Pos*/) /*!< SCB CPUID: REVISION Mask */ /* SCB Interrupt Control State Register Definitions */ #define SCB_ICSR_NMIPENDSET_Pos 31 /*!< SCB ICSR: NMIPENDSET Position */ #define SCB_ICSR_NMIPENDSET_Msk (1UL << SCB_ICSR_NMIPENDSET_Pos) /*!< SCB ICSR: NMIPENDSET Mask */ #define SCB_ICSR_PENDSVSET_Pos 28 /*!< SCB ICSR: PENDSVSET Position */ #define SCB_ICSR_PENDSVSET_Msk (1UL << SCB_ICSR_PENDSVSET_Pos) /*!< SCB ICSR: PENDSVSET Mask */ #define SCB_ICSR_PENDSVCLR_Pos 27 /*!< SCB ICSR: PENDSVCLR Position */ #define SCB_ICSR_PENDSVCLR_Msk (1UL << SCB_ICSR_PENDSVCLR_Pos) /*!< SCB ICSR: PENDSVCLR Mask */ #define SCB_ICSR_PENDSTSET_Pos 26 /*!< SCB ICSR: PENDSTSET Position */ #define SCB_ICSR_PENDSTSET_Msk (1UL << SCB_ICSR_PENDSTSET_Pos) /*!< SCB ICSR: PENDSTSET Mask */ #define SCB_ICSR_PENDSTCLR_Pos 25 /*!< SCB ICSR: PENDSTCLR Position */ #define SCB_ICSR_PENDSTCLR_Msk (1UL << SCB_ICSR_PENDSTCLR_Pos) /*!< SCB ICSR: PENDSTCLR Mask */ #define SCB_ICSR_ISRPREEMPT_Pos 23 /*!< SCB ICSR: ISRPREEMPT Position */ #define SCB_ICSR_ISRPREEMPT_Msk (1UL << SCB_ICSR_ISRPREEMPT_Pos) /*!< SCB ICSR: ISRPREEMPT Mask */ #define SCB_ICSR_ISRPENDING_Pos 22 /*!< SCB ICSR: ISRPENDING Position */ #define SCB_ICSR_ISRPENDING_Msk (1UL << SCB_ICSR_ISRPENDING_Pos) /*!< SCB ICSR: ISRPENDING Mask */ #define SCB_ICSR_VECTPENDING_Pos 12 /*!< SCB ICSR: VECTPENDING Position */ #define SCB_ICSR_VECTPENDING_Msk (0x1FFUL << SCB_ICSR_VECTPENDING_Pos) /*!< SCB ICSR: VECTPENDING Mask */ #define SCB_ICSR_RETTOBASE_Pos 11 /*!< SCB ICSR: RETTOBASE Position */ #define SCB_ICSR_RETTOBASE_Msk (1UL << SCB_ICSR_RETTOBASE_Pos) /*!< SCB ICSR: RETTOBASE Mask */ #define SCB_ICSR_VECTACTIVE_Pos 0 /*!< SCB ICSR: VECTACTIVE Position */ #define SCB_ICSR_VECTACTIVE_Msk (0x1FFUL /*<< SCB_ICSR_VECTACTIVE_Pos*/) /*!< SCB ICSR: VECTACTIVE Mask */ /* SCB Vector Table Offset Register Definitions */ #if (__CM3_REV < 0x0201) /* core r2p1 */ #define SCB_VTOR_TBLBASE_Pos 29 /*!< SCB VTOR: TBLBASE Position */ #define SCB_VTOR_TBLBASE_Msk (1UL << SCB_VTOR_TBLBASE_Pos) /*!< SCB VTOR: TBLBASE Mask */ #define SCB_VTOR_TBLOFF_Pos 7 /*!< SCB VTOR: TBLOFF Position */ #define SCB_VTOR_TBLOFF_Msk (0x3FFFFFUL << SCB_VTOR_TBLOFF_Pos) /*!< SCB VTOR: TBLOFF Mask */ #else #define SCB_VTOR_TBLOFF_Pos 7 /*!< SCB VTOR: TBLOFF Position */ #define SCB_VTOR_TBLOFF_Msk (0x1FFFFFFUL << SCB_VTOR_TBLOFF_Pos) /*!< SCB VTOR: TBLOFF Mask */ #endif /* SCB Application Interrupt and Reset Control Register Definitions */ #define SCB_AIRCR_VECTKEY_Pos 16 /*!< SCB AIRCR: VECTKEY Position */ #define SCB_AIRCR_VECTKEY_Msk (0xFFFFUL << SCB_AIRCR_VECTKEY_Pos) /*!< SCB AIRCR: VECTKEY Mask */ #define SCB_AIRCR_VECTKEYSTAT_Pos 16 /*!< SCB AIRCR: VECTKEYSTAT Position */ #define SCB_AIRCR_VECTKEYSTAT_Msk (0xFFFFUL << SCB_AIRCR_VECTKEYSTAT_Pos) /*!< SCB AIRCR: VECTKEYSTAT Mask */ #define SCB_AIRCR_ENDIANESS_Pos 15 /*!< SCB AIRCR: ENDIANESS Position */ #define SCB_AIRCR_ENDIANESS_Msk (1UL << SCB_AIRCR_ENDIANESS_Pos) /*!< SCB AIRCR: ENDIANESS Mask */ #define SCB_AIRCR_PRIGROUP_Pos 8 /*!< SCB AIRCR: PRIGROUP Position */ #define SCB_AIRCR_PRIGROUP_Msk (7UL << SCB_AIRCR_PRIGROUP_Pos) /*!< SCB AIRCR: PRIGROUP Mask */ #define SCB_AIRCR_SYSRESETREQ_Pos 2 /*!< SCB AIRCR: SYSRESETREQ Position */ #define SCB_AIRCR_SYSRESETREQ_Msk (1UL << SCB_AIRCR_SYSRESETREQ_Pos) /*!< SCB AIRCR: SYSRESETREQ Mask */ #define SCB_AIRCR_VECTCLRACTIVE_Pos 1 /*!< SCB AIRCR: VECTCLRACTIVE Position */ #define SCB_AIRCR_VECTCLRACTIVE_Msk (1UL << SCB_AIRCR_VECTCLRACTIVE_Pos) /*!< SCB AIRCR: VECTCLRACTIVE Mask */ #define SCB_AIRCR_VECTRESET_Pos 0 /*!< SCB AIRCR: VECTRESET Position */ #define SCB_AIRCR_VECTRESET_Msk (1UL /*<< SCB_AIRCR_VECTRESET_Pos*/) /*!< SCB AIRCR: VECTRESET Mask */ /* SCB System Control Register Definitions */ #define SCB_SCR_SEVONPEND_Pos 4 /*!< SCB SCR: SEVONPEND Position */ #define SCB_SCR_SEVONPEND_Msk (1UL << SCB_SCR_SEVONPEND_Pos) /*!< SCB SCR: SEVONPEND Mask */ #define SCB_SCR_SLEEPDEEP_Pos 2 /*!< SCB SCR: SLEEPDEEP Position */ #define SCB_SCR_SLEEPDEEP_Msk (1UL << SCB_SCR_SLEEPDEEP_Pos) /*!< SCB SCR: SLEEPDEEP Mask */ #define SCB_SCR_SLEEPONEXIT_Pos 1 /*!< SCB SCR: SLEEPONEXIT Position */ #define SCB_SCR_SLEEPONEXIT_Msk (1UL << SCB_SCR_SLEEPONEXIT_Pos) /*!< SCB SCR: SLEEPONEXIT Mask */ /* SCB Configuration Control Register Definitions */ #define SCB_CCR_STKALIGN_Pos 9 /*!< SCB CCR: STKALIGN Position */ #define SCB_CCR_STKALIGN_Msk (1UL << SCB_CCR_STKALIGN_Pos) /*!< SCB CCR: STKALIGN Mask */ #define SCB_CCR_BFHFNMIGN_Pos 8 /*!< SCB CCR: BFHFNMIGN Position */ #define SCB_CCR_BFHFNMIGN_Msk (1UL << SCB_CCR_BFHFNMIGN_Pos) /*!< SCB CCR: BFHFNMIGN Mask */ #define SCB_CCR_DIV_0_TRP_Pos 4 /*!< SCB CCR: DIV_0_TRP Position */ #define SCB_CCR_DIV_0_TRP_Msk (1UL << SCB_CCR_DIV_0_TRP_Pos) /*!< SCB CCR: DIV_0_TRP Mask */ #define SCB_CCR_UNALIGN_TRP_Pos 3 /*!< SCB CCR: UNALIGN_TRP Position */ #define SCB_CCR_UNALIGN_TRP_Msk (1UL << SCB_CCR_UNALIGN_TRP_Pos) /*!< SCB CCR: UNALIGN_TRP Mask */ #define SCB_CCR_USERSETMPEND_Pos 1 /*!< SCB CCR: USERSETMPEND Position */ #define SCB_CCR_USERSETMPEND_Msk (1UL << SCB_CCR_USERSETMPEND_Pos) /*!< SCB CCR: USERSETMPEND Mask */ #define SCB_CCR_NONBASETHRDENA_Pos 0 /*!< SCB CCR: NONBASETHRDENA Position */ #define SCB_CCR_NONBASETHRDENA_Msk (1UL /*<< SCB_CCR_NONBASETHRDENA_Pos*/) /*!< SCB CCR: NONBASETHRDENA Mask */ /* SCB System Handler Control and State Register Definitions */ #define SCB_SHCSR_USGFAULTENA_Pos 18 /*!< SCB SHCSR: USGFAULTENA Position */ #define SCB_SHCSR_USGFAULTENA_Msk (1UL << SCB_SHCSR_USGFAULTENA_Pos) /*!< SCB SHCSR: USGFAULTENA Mask */ #define SCB_SHCSR_BUSFAULTENA_Pos 17 /*!< SCB SHCSR: BUSFAULTENA Position */ #define SCB_SHCSR_BUSFAULTENA_Msk (1UL << SCB_SHCSR_BUSFAULTENA_Pos) /*!< SCB SHCSR: BUSFAULTENA Mask */ #define SCB_SHCSR_MEMFAULTENA_Pos 16 /*!< SCB SHCSR: MEMFAULTENA Position */ #define SCB_SHCSR_MEMFAULTENA_Msk (1UL << SCB_SHCSR_MEMFAULTENA_Pos) /*!< SCB SHCSR: MEMFAULTENA Mask */ #define SCB_SHCSR_SVCALLPENDED_Pos 15 /*!< SCB SHCSR: SVCALLPENDED Position */ #define SCB_SHCSR_SVCALLPENDED_Msk (1UL << SCB_SHCSR_SVCALLPENDED_Pos) /*!< SCB SHCSR: SVCALLPENDED Mask */ #define SCB_SHCSR_BUSFAULTPENDED_Pos 14 /*!< SCB SHCSR: BUSFAULTPENDED Position */ #define SCB_SHCSR_BUSFAULTPENDED_Msk (1UL << SCB_SHCSR_BUSFAULTPENDED_Pos) /*!< SCB SHCSR: BUSFAULTPENDED Mask */ #define SCB_SHCSR_MEMFAULTPENDED_Pos 13 /*!< SCB SHCSR: MEMFAULTPENDED Position */ #define SCB_SHCSR_MEMFAULTPENDED_Msk (1UL << SCB_SHCSR_MEMFAULTPENDED_Pos) /*!< SCB SHCSR: MEMFAULTPENDED Mask */ #define SCB_SHCSR_USGFAULTPENDED_Pos 12 /*!< SCB SHCSR: USGFAULTPENDED Position */ #define SCB_SHCSR_USGFAULTPENDED_Msk (1UL << SCB_SHCSR_USGFAULTPENDED_Pos) /*!< SCB SHCSR: USGFAULTPENDED Mask */ #define SCB_SHCSR_SYSTICKACT_Pos 11 /*!< SCB SHCSR: SYSTICKACT Position */ #define SCB_SHCSR_SYSTICKACT_Msk (1UL << SCB_SHCSR_SYSTICKACT_Pos) /*!< SCB SHCSR: SYSTICKACT Mask */ #define SCB_SHCSR_PENDSVACT_Pos 10 /*!< SCB SHCSR: PENDSVACT Position */ #define SCB_SHCSR_PENDSVACT_Msk (1UL << SCB_SHCSR_PENDSVACT_Pos) /*!< SCB SHCSR: PENDSVACT Mask */ #define SCB_SHCSR_MONITORACT_Pos 8 /*!< SCB SHCSR: MONITORACT Position */ #define SCB_SHCSR_MONITORACT_Msk (1UL << SCB_SHCSR_MONITORACT_Pos) /*!< SCB SHCSR: MONITORACT Mask */ #define SCB_SHCSR_SVCALLACT_Pos 7 /*!< SCB SHCSR: SVCALLACT Position */ #define SCB_SHCSR_SVCALLACT_Msk (1UL << SCB_SHCSR_SVCALLACT_Pos) /*!< SCB SHCSR: SVCALLACT Mask */ #define SCB_SHCSR_USGFAULTACT_Pos 3 /*!< SCB SHCSR: USGFAULTACT Position */ #define SCB_SHCSR_USGFAULTACT_Msk (1UL << SCB_SHCSR_USGFAULTACT_Pos) /*!< SCB SHCSR: USGFAULTACT Mask */ #define SCB_SHCSR_BUSFAULTACT_Pos 1 /*!< SCB SHCSR: BUSFAULTACT Position */ #define SCB_SHCSR_BUSFAULTACT_Msk (1UL << SCB_SHCSR_BUSFAULTACT_Pos) /*!< SCB SHCSR: BUSFAULTACT Mask */ #define SCB_SHCSR_MEMFAULTACT_Pos 0 /*!< SCB SHCSR: MEMFAULTACT Position */ #define SCB_SHCSR_MEMFAULTACT_Msk (1UL /*<< SCB_SHCSR_MEMFAULTACT_Pos*/) /*!< SCB SHCSR: MEMFAULTACT Mask */ /* SCB Configurable Fault Status Registers Definitions */ #define SCB_CFSR_USGFAULTSR_Pos 16 /*!< SCB CFSR: Usage Fault Status Register Position */ #define SCB_CFSR_USGFAULTSR_Msk (0xFFFFUL << SCB_CFSR_USGFAULTSR_Pos) /*!< SCB CFSR: Usage Fault Status Register Mask */ #define SCB_CFSR_BUSFAULTSR_Pos 8 /*!< SCB CFSR: Bus Fault Status Register Position */ #define SCB_CFSR_BUSFAULTSR_Msk (0xFFUL << SCB_CFSR_BUSFAULTSR_Pos) /*!< SCB CFSR: Bus Fault Status Register Mask */ #define SCB_CFSR_MEMFAULTSR_Pos 0 /*!< SCB CFSR: Memory Manage Fault Status Register Position */ #define SCB_CFSR_MEMFAULTSR_Msk (0xFFUL /*<< SCB_CFSR_MEMFAULTSR_Pos*/) /*!< SCB CFSR: Memory Manage Fault Status Register Mask */ /* SCB Hard Fault Status Registers Definitions */ #define SCB_HFSR_DEBUGEVT_Pos 31 /*!< SCB HFSR: DEBUGEVT Position */ #define SCB_HFSR_DEBUGEVT_Msk (1UL << SCB_HFSR_DEBUGEVT_Pos) /*!< SCB HFSR: DEBUGEVT Mask */ #define SCB_HFSR_FORCED_Pos 30 /*!< SCB HFSR: FORCED Position */ #define SCB_HFSR_FORCED_Msk (1UL << SCB_HFSR_FORCED_Pos) /*!< SCB HFSR: FORCED Mask */ #define SCB_HFSR_VECTTBL_Pos 1 /*!< SCB HFSR: VECTTBL Position */ #define SCB_HFSR_VECTTBL_Msk (1UL << SCB_HFSR_VECTTBL_Pos) /*!< SCB HFSR: VECTTBL Mask */ /* SCB Debug Fault Status Register Definitions */ #define SCB_DFSR_EXTERNAL_Pos 4 /*!< SCB DFSR: EXTERNAL Position */ #define SCB_DFSR_EXTERNAL_Msk (1UL << SCB_DFSR_EXTERNAL_Pos) /*!< SCB DFSR: EXTERNAL Mask */ #define SCB_DFSR_VCATCH_Pos 3 /*!< SCB DFSR: VCATCH Position */ #define SCB_DFSR_VCATCH_Msk (1UL << SCB_DFSR_VCATCH_Pos) /*!< SCB DFSR: VCATCH Mask */ #define SCB_DFSR_DWTTRAP_Pos 2 /*!< SCB DFSR: DWTTRAP Position */ #define SCB_DFSR_DWTTRAP_Msk (1UL << SCB_DFSR_DWTTRAP_Pos) /*!< SCB DFSR: DWTTRAP Mask */ #define SCB_DFSR_BKPT_Pos 1 /*!< SCB DFSR: BKPT Position */ #define SCB_DFSR_BKPT_Msk (1UL << SCB_DFSR_BKPT_Pos) /*!< SCB DFSR: BKPT Mask */ #define SCB_DFSR_HALTED_Pos 0 /*!< SCB DFSR: HALTED Position */ #define SCB_DFSR_HALTED_Msk (1UL /*<< SCB_DFSR_HALTED_Pos*/) /*!< SCB DFSR: HALTED Mask */ /*@} end of group CMSIS_SCB */ /** \ingroup CMSIS_core_register \defgroup CMSIS_SCnSCB System Controls not in SCB (SCnSCB) \brief Type definitions for the System Control and ID Register not in the SCB @{ */ /** \brief Structure type to access the System Control and ID Register not in the SCB. */ typedef struct { uint32_t RESERVED0[1]; __I uint32_t ICTR; /*!< Offset: 0x004 (R/ ) Interrupt Controller Type Register */ #if ((defined __CM3_REV) && (__CM3_REV >= 0x200)) __IO uint32_t ACTLR; /*!< Offset: 0x008 (R/W) Auxiliary Control Register */ #else uint32_t RESERVED1[1]; #endif } SCnSCB_Type; /* Interrupt Controller Type Register Definitions */ #define SCnSCB_ICTR_INTLINESNUM_Pos 0 /*!< ICTR: INTLINESNUM Position */ #define SCnSCB_ICTR_INTLINESNUM_Msk (0xFUL /*<< SCnSCB_ICTR_INTLINESNUM_Pos*/) /*!< ICTR: INTLINESNUM Mask */ /* Auxiliary Control Register Definitions */ #define SCnSCB_ACTLR_DISFOLD_Pos 2 /*!< ACTLR: DISFOLD Position */ #define SCnSCB_ACTLR_DISFOLD_Msk (1UL << SCnSCB_ACTLR_DISFOLD_Pos) /*!< ACTLR: DISFOLD Mask */ #define SCnSCB_ACTLR_DISDEFWBUF_Pos 1 /*!< ACTLR: DISDEFWBUF Position */ #define SCnSCB_ACTLR_DISDEFWBUF_Msk (1UL << SCnSCB_ACTLR_DISDEFWBUF_Pos) /*!< ACTLR: DISDEFWBUF Mask */ #define SCnSCB_ACTLR_DISMCYCINT_Pos 0 /*!< ACTLR: DISMCYCINT Position */ #define SCnSCB_ACTLR_DISMCYCINT_Msk (1UL /*<< SCnSCB_ACTLR_DISMCYCINT_Pos*/) /*!< ACTLR: DISMCYCINT Mask */ /*@} end of group CMSIS_SCnotSCB */ /** \ingroup CMSIS_core_register \defgroup CMSIS_SysTick System Tick Timer (SysTick) \brief Type definitions for the System Timer Registers. @{ */ /** \brief Structure type to access the System Timer (SysTick). */ typedef struct { __IO uint32_t CTRL; /*!< Offset: 0x000 (R/W) SysTick Control and Status Register */ __IO uint32_t LOAD; /*!< Offset: 0x004 (R/W) SysTick Reload Value Register */ __IO uint32_t VAL; /*!< Offset: 0x008 (R/W) SysTick Current Value Register */ __I uint32_t CALIB; /*!< Offset: 0x00C (R/ ) SysTick Calibration Register */ } SysTick_Type; /* SysTick Control / Status Register Definitions */ #define SysTick_CTRL_COUNTFLAG_Pos 16 /*!< SysTick CTRL: COUNTFLAG Position */ #define SysTick_CTRL_COUNTFLAG_Msk (1UL << SysTick_CTRL_COUNTFLAG_Pos) /*!< SysTick CTRL: COUNTFLAG Mask */ #define SysTick_CTRL_CLKSOURCE_Pos 2 /*!< SysTick CTRL: CLKSOURCE Position */ #define SysTick_CTRL_CLKSOURCE_Msk (1UL << SysTick_CTRL_CLKSOURCE_Pos) /*!< SysTick CTRL: CLKSOURCE Mask */ #define SysTick_CTRL_TICKINT_Pos 1 /*!< SysTick CTRL: TICKINT Position */ #define SysTick_CTRL_TICKINT_Msk (1UL << SysTick_CTRL_TICKINT_Pos) /*!< SysTick CTRL: TICKINT Mask */ #define SysTick_CTRL_ENABLE_Pos 0 /*!< SysTick CTRL: ENABLE Position */ #define SysTick_CTRL_ENABLE_Msk (1UL /*<< SysTick_CTRL_ENABLE_Pos*/) /*!< SysTick CTRL: ENABLE Mask */ /* SysTick Reload Register Definitions */ #define SysTick_LOAD_RELOAD_Pos 0 /*!< SysTick LOAD: RELOAD Position */ #define SysTick_LOAD_RELOAD_Msk (0xFFFFFFUL /*<< SysTick_LOAD_RELOAD_Pos*/) /*!< SysTick LOAD: RELOAD Mask */ /* SysTick Current Register Definitions */ #define SysTick_VAL_CURRENT_Pos 0 /*!< SysTick VAL: CURRENT Position */ #define SysTick_VAL_CURRENT_Msk (0xFFFFFFUL /*<< SysTick_VAL_CURRENT_Pos*/) /*!< SysTick VAL: CURRENT Mask */ /* SysTick Calibration Register Definitions */ #define SysTick_CALIB_NOREF_Pos 31 /*!< SysTick CALIB: NOREF Position */ #define SysTick_CALIB_NOREF_Msk (1UL << SysTick_CALIB_NOREF_Pos) /*!< SysTick CALIB: NOREF Mask */ #define SysTick_CALIB_SKEW_Pos 30 /*!< SysTick CALIB: SKEW Position */ #define SysTick_CALIB_SKEW_Msk (1UL << SysTick_CALIB_SKEW_Pos) /*!< SysTick CALIB: SKEW Mask */ #define SysTick_CALIB_TENMS_Pos 0 /*!< SysTick CALIB: TENMS Position */ #define SysTick_CALIB_TENMS_Msk (0xFFFFFFUL /*<< SysTick_CALIB_TENMS_Pos*/) /*!< SysTick CALIB: TENMS Mask */ /*@} end of group CMSIS_SysTick */ /** \ingroup CMSIS_core_register \defgroup CMSIS_ITM Instrumentation Trace Macrocell (ITM) \brief Type definitions for the Instrumentation Trace Macrocell (ITM) @{ */ /** \brief Structure type to access the Instrumentation Trace Macrocell Register (ITM). */ typedef struct { __O union { __O uint8_t u8; /*!< Offset: 0x000 ( /W) ITM Stimulus Port 8-bit */ __O uint16_t u16; /*!< Offset: 0x000 ( /W) ITM Stimulus Port 16-bit */ __O uint32_t u32; /*!< Offset: 0x000 ( /W) ITM Stimulus Port 32-bit */ } PORT [32]; /*!< Offset: 0x000 ( /W) ITM Stimulus Port Registers */ uint32_t RESERVED0[864]; __IO uint32_t TER; /*!< Offset: 0xE00 (R/W) ITM Trace Enable Register */ uint32_t RESERVED1[15]; __IO uint32_t TPR; /*!< Offset: 0xE40 (R/W) ITM Trace Privilege Register */ uint32_t RESERVED2[15]; __IO uint32_t TCR; /*!< Offset: 0xE80 (R/W) ITM Trace Control Register */ uint32_t RESERVED3[29]; __O uint32_t IWR; /*!< Offset: 0xEF8 ( /W) ITM Integration Write Register */ __I uint32_t IRR; /*!< Offset: 0xEFC (R/ ) ITM Integration Read Register */ __IO uint32_t IMCR; /*!< Offset: 0xF00 (R/W) ITM Integration Mode Control Register */ uint32_t RESERVED4[43]; __O uint32_t LAR; /*!< Offset: 0xFB0 ( /W) ITM Lock Access Register */ __I uint32_t LSR; /*!< Offset: 0xFB4 (R/ ) ITM Lock Status Register */ uint32_t RESERVED5[6]; __I uint32_t PID4; /*!< Offset: 0xFD0 (R/ ) ITM Peripheral Identification Register #4 */ __I uint32_t PID5; /*!< Offset: 0xFD4 (R/ ) ITM Peripheral Identification Register #5 */ __I uint32_t PID6; /*!< Offset: 0xFD8 (R/ ) ITM Peripheral Identification Register #6 */ __I uint32_t PID7; /*!< Offset: 0xFDC (R/ ) ITM Peripheral Identification Register #7 */ __I uint32_t PID0; /*!< Offset: 0xFE0 (R/ ) ITM Peripheral Identification Register #0 */ __I uint32_t PID1; /*!< Offset: 0xFE4 (R/ ) ITM Peripheral Identification Register #1 */ __I uint32_t PID2; /*!< Offset: 0xFE8 (R/ ) ITM Peripheral Identification Register #2 */ __I uint32_t PID3; /*!< Offset: 0xFEC (R/ ) ITM Peripheral Identification Register #3 */ __I uint32_t CID0; /*!< Offset: 0xFF0 (R/ ) ITM Component Identification Register #0 */ __I uint32_t CID1; /*!< Offset: 0xFF4 (R/ ) ITM Component Identification Register #1 */ __I uint32_t CID2; /*!< Offset: 0xFF8 (R/ ) ITM Component Identification Register #2 */ __I uint32_t CID3; /*!< Offset: 0xFFC (R/ ) ITM Component Identification Register #3 */ } ITM_Type; /* ITM Trace Privilege Register Definitions */ #define ITM_TPR_PRIVMASK_Pos 0 /*!< ITM TPR: PRIVMASK Position */ #define ITM_TPR_PRIVMASK_Msk (0xFUL /*<< ITM_TPR_PRIVMASK_Pos*/) /*!< ITM TPR: PRIVMASK Mask */ /* ITM Trace Control Register Definitions */ #define ITM_TCR_BUSY_Pos 23 /*!< ITM TCR: BUSY Position */ #define ITM_TCR_BUSY_Msk (1UL << ITM_TCR_BUSY_Pos) /*!< ITM TCR: BUSY Mask */ #define ITM_TCR_TraceBusID_Pos 16 /*!< ITM TCR: ATBID Position */ #define ITM_TCR_TraceBusID_Msk (0x7FUL << ITM_TCR_TraceBusID_Pos) /*!< ITM TCR: ATBID Mask */ #define ITM_TCR_GTSFREQ_Pos 10 /*!< ITM TCR: Global timestamp frequency Position */ #define ITM_TCR_GTSFREQ_Msk (3UL << ITM_TCR_GTSFREQ_Pos) /*!< ITM TCR: Global timestamp frequency Mask */ #define ITM_TCR_TSPrescale_Pos 8 /*!< ITM TCR: TSPrescale Position */ #define ITM_TCR_TSPrescale_Msk (3UL << ITM_TCR_TSPrescale_Pos) /*!< ITM TCR: TSPrescale Mask */ #define ITM_TCR_SWOENA_Pos 4 /*!< ITM TCR: SWOENA Position */ #define ITM_TCR_SWOENA_Msk (1UL << ITM_TCR_SWOENA_Pos) /*!< ITM TCR: SWOENA Mask */ #define ITM_TCR_DWTENA_Pos 3 /*!< ITM TCR: DWTENA Position */ #define ITM_TCR_DWTENA_Msk (1UL << ITM_TCR_DWTENA_Pos) /*!< ITM TCR: DWTENA Mask */ #define ITM_TCR_SYNCENA_Pos 2 /*!< ITM TCR: SYNCENA Position */ #define ITM_TCR_SYNCENA_Msk (1UL << ITM_TCR_SYNCENA_Pos) /*!< ITM TCR: SYNCENA Mask */ #define ITM_TCR_TSENA_Pos 1 /*!< ITM TCR: TSENA Position */ #define ITM_TCR_TSENA_Msk (1UL << ITM_TCR_TSENA_Pos) /*!< ITM TCR: TSENA Mask */ #define ITM_TCR_ITMENA_Pos 0 /*!< ITM TCR: ITM Enable bit Position */ #define ITM_TCR_ITMENA_Msk (1UL /*<< ITM_TCR_ITMENA_Pos*/) /*!< ITM TCR: ITM Enable bit Mask */ /* ITM Integration Write Register Definitions */ #define ITM_IWR_ATVALIDM_Pos 0 /*!< ITM IWR: ATVALIDM Position */ #define ITM_IWR_ATVALIDM_Msk (1UL /*<< ITM_IWR_ATVALIDM_Pos*/) /*!< ITM IWR: ATVALIDM Mask */ /* ITM Integration Read Register Definitions */ #define ITM_IRR_ATREADYM_Pos 0 /*!< ITM IRR: ATREADYM Position */ #define ITM_IRR_ATREADYM_Msk (1UL /*<< ITM_IRR_ATREADYM_Pos*/) /*!< ITM IRR: ATREADYM Mask */ /* ITM Integration Mode Control Register Definitions */ #define ITM_IMCR_INTEGRATION_Pos 0 /*!< ITM IMCR: INTEGRATION Position */ #define ITM_IMCR_INTEGRATION_Msk (1UL /*<< ITM_IMCR_INTEGRATION_Pos*/) /*!< ITM IMCR: INTEGRATION Mask */ /* ITM Lock Status Register Definitions */ #define ITM_LSR_ByteAcc_Pos 2 /*!< ITM LSR: ByteAcc Position */ #define ITM_LSR_ByteAcc_Msk (1UL << ITM_LSR_ByteAcc_Pos) /*!< ITM LSR: ByteAcc Mask */ #define ITM_LSR_Access_Pos 1 /*!< ITM LSR: Access Position */ #define ITM_LSR_Access_Msk (1UL << ITM_LSR_Access_Pos) /*!< ITM LSR: Access Mask */ #define ITM_LSR_Present_Pos 0 /*!< ITM LSR: Present Position */ #define ITM_LSR_Present_Msk (1UL /*<< ITM_LSR_Present_Pos*/) /*!< ITM LSR: Present Mask */ /*@}*/ /* end of group CMSIS_ITM */ /** \ingroup CMSIS_core_register \defgroup CMSIS_DWT Data Watchpoint and Trace (DWT) \brief Type definitions for the Data Watchpoint and Trace (DWT) @{ */ /** \brief Structure type to access the Data Watchpoint and Trace Register (DWT). */ typedef struct { __IO uint32_t CTRL; /*!< Offset: 0x000 (R/W) Control Register */ __IO uint32_t CYCCNT; /*!< Offset: 0x004 (R/W) Cycle Count Register */ __IO uint32_t CPICNT; /*!< Offset: 0x008 (R/W) CPI Count Register */ __IO uint32_t EXCCNT; /*!< Offset: 0x00C (R/W) Exception Overhead Count Register */ __IO uint32_t SLEEPCNT; /*!< Offset: 0x010 (R/W) Sleep Count Register */ __IO uint32_t LSUCNT; /*!< Offset: 0x014 (R/W) LSU Count Register */ __IO uint32_t FOLDCNT; /*!< Offset: 0x018 (R/W) Folded-instruction Count Register */ __I uint32_t PCSR; /*!< Offset: 0x01C (R/ ) Program Counter Sample Register */ __IO uint32_t COMP0; /*!< Offset: 0x020 (R/W) Comparator Register 0 */ __IO uint32_t MASK0; /*!< Offset: 0x024 (R/W) Mask Register 0 */ __IO uint32_t FUNCTION0; /*!< Offset: 0x028 (R/W) Function Register 0 */ uint32_t RESERVED0[1]; __IO uint32_t COMP1; /*!< Offset: 0x030 (R/W) Comparator Register 1 */ __IO uint32_t MASK1; /*!< Offset: 0x034 (R/W) Mask Register 1 */ __IO uint32_t FUNCTION1; /*!< Offset: 0x038 (R/W) Function Register 1 */ uint32_t RESERVED1[1]; __IO uint32_t COMP2; /*!< Offset: 0x040 (R/W) Comparator Register 2 */ __IO uint32_t MASK2; /*!< Offset: 0x044 (R/W) Mask Register 2 */ __IO uint32_t FUNCTION2; /*!< Offset: 0x048 (R/W) Function Register 2 */ uint32_t RESERVED2[1]; __IO uint32_t COMP3; /*!< Offset: 0x050 (R/W) Comparator Register 3 */ __IO uint32_t MASK3; /*!< Offset: 0x054 (R/W) Mask Register 3 */ __IO uint32_t FUNCTION3; /*!< Offset: 0x058 (R/W) Function Register 3 */ } DWT_Type; /* DWT Control Register Definitions */ #define DWT_CTRL_NUMCOMP_Pos 28 /*!< DWT CTRL: NUMCOMP Position */ #define DWT_CTRL_NUMCOMP_Msk (0xFUL << DWT_CTRL_NUMCOMP_Pos) /*!< DWT CTRL: NUMCOMP Mask */ #define DWT_CTRL_NOTRCPKT_Pos 27 /*!< DWT CTRL: NOTRCPKT Position */ #define DWT_CTRL_NOTRCPKT_Msk (0x1UL << DWT_CTRL_NOTRCPKT_Pos) /*!< DWT CTRL: NOTRCPKT Mask */ #define DWT_CTRL_NOEXTTRIG_Pos 26 /*!< DWT CTRL: NOEXTTRIG Position */ #define DWT_CTRL_NOEXTTRIG_Msk (0x1UL << DWT_CTRL_NOEXTTRIG_Pos) /*!< DWT CTRL: NOEXTTRIG Mask */ #define DWT_CTRL_NOCYCCNT_Pos 25 /*!< DWT CTRL: NOCYCCNT Position */ #define DWT_CTRL_NOCYCCNT_Msk (0x1UL << DWT_CTRL_NOCYCCNT_Pos) /*!< DWT CTRL: NOCYCCNT Mask */ #define DWT_CTRL_NOPRFCNT_Pos 24 /*!< DWT CTRL: NOPRFCNT Position */ #define DWT_CTRL_NOPRFCNT_Msk (0x1UL << DWT_CTRL_NOPRFCNT_Pos) /*!< DWT CTRL: NOPRFCNT Mask */ #define DWT_CTRL_CYCEVTENA_Pos 22 /*!< DWT CTRL: CYCEVTENA Position */ #define DWT_CTRL_CYCEVTENA_Msk (0x1UL << DWT_CTRL_CYCEVTENA_Pos) /*!< DWT CTRL: CYCEVTENA Mask */ #define DWT_CTRL_FOLDEVTENA_Pos 21 /*!< DWT CTRL: FOLDEVTENA Position */ #define DWT_CTRL_FOLDEVTENA_Msk (0x1UL << DWT_CTRL_FOLDEVTENA_Pos) /*!< DWT CTRL: FOLDEVTENA Mask */ #define DWT_CTRL_LSUEVTENA_Pos 20 /*!< DWT CTRL: LSUEVTENA Position */ #define DWT_CTRL_LSUEVTENA_Msk (0x1UL << DWT_CTRL_LSUEVTENA_Pos) /*!< DWT CTRL: LSUEVTENA Mask */ #define DWT_CTRL_SLEEPEVTENA_Pos 19 /*!< DWT CTRL: SLEEPEVTENA Position */ #define DWT_CTRL_SLEEPEVTENA_Msk (0x1UL << DWT_CTRL_SLEEPEVTENA_Pos) /*!< DWT CTRL: SLEEPEVTENA Mask */ #define DWT_CTRL_EXCEVTENA_Pos 18 /*!< DWT CTRL: EXCEVTENA Position */ #define DWT_CTRL_EXCEVTENA_Msk (0x1UL << DWT_CTRL_EXCEVTENA_Pos) /*!< DWT CTRL: EXCEVTENA Mask */ #define DWT_CTRL_CPIEVTENA_Pos 17 /*!< DWT CTRL: CPIEVTENA Position */ #define DWT_CTRL_CPIEVTENA_Msk (0x1UL << DWT_CTRL_CPIEVTENA_Pos) /*!< DWT CTRL: CPIEVTENA Mask */ #define DWT_CTRL_EXCTRCENA_Pos 16 /*!< DWT CTRL: EXCTRCENA Position */ #define DWT_CTRL_EXCTRCENA_Msk (0x1UL << DWT_CTRL_EXCTRCENA_Pos) /*!< DWT CTRL: EXCTRCENA Mask */ #define DWT_CTRL_PCSAMPLENA_Pos 12 /*!< DWT CTRL: PCSAMPLENA Position */ #define DWT_CTRL_PCSAMPLENA_Msk (0x1UL << DWT_CTRL_PCSAMPLENA_Pos) /*!< DWT CTRL: PCSAMPLENA Mask */ #define DWT_CTRL_SYNCTAP_Pos 10 /*!< DWT CTRL: SYNCTAP Position */ #define DWT_CTRL_SYNCTAP_Msk (0x3UL << DWT_CTRL_SYNCTAP_Pos) /*!< DWT CTRL: SYNCTAP Mask */ #define DWT_CTRL_CYCTAP_Pos 9 /*!< DWT CTRL: CYCTAP Position */ #define DWT_CTRL_CYCTAP_Msk (0x1UL << DWT_CTRL_CYCTAP_Pos) /*!< DWT CTRL: CYCTAP Mask */ #define DWT_CTRL_POSTINIT_Pos 5 /*!< DWT CTRL: POSTINIT Position */ #define DWT_CTRL_POSTINIT_Msk (0xFUL << DWT_CTRL_POSTINIT_Pos) /*!< DWT CTRL: POSTINIT Mask */ #define DWT_CTRL_POSTPRESET_Pos 1 /*!< DWT CTRL: POSTPRESET Position */ #define DWT_CTRL_POSTPRESET_Msk (0xFUL << DWT_CTRL_POSTPRESET_Pos) /*!< DWT CTRL: POSTPRESET Mask */ #define DWT_CTRL_CYCCNTENA_Pos 0 /*!< DWT CTRL: CYCCNTENA Position */ #define DWT_CTRL_CYCCNTENA_Msk (0x1UL /*<< DWT_CTRL_CYCCNTENA_Pos*/) /*!< DWT CTRL: CYCCNTENA Mask */ /* DWT CPI Count Register Definitions */ #define DWT_CPICNT_CPICNT_Pos 0 /*!< DWT CPICNT: CPICNT Position */ #define DWT_CPICNT_CPICNT_Msk (0xFFUL /*<< DWT_CPICNT_CPICNT_Pos*/) /*!< DWT CPICNT: CPICNT Mask */ /* DWT Exception Overhead Count Register Definitions */ #define DWT_EXCCNT_EXCCNT_Pos 0 /*!< DWT EXCCNT: EXCCNT Position */ #define DWT_EXCCNT_EXCCNT_Msk (0xFFUL /*<< DWT_EXCCNT_EXCCNT_Pos*/) /*!< DWT EXCCNT: EXCCNT Mask */ /* DWT Sleep Count Register Definitions */ #define DWT_SLEEPCNT_SLEEPCNT_Pos 0 /*!< DWT SLEEPCNT: SLEEPCNT Position */ #define DWT_SLEEPCNT_SLEEPCNT_Msk (0xFFUL /*<< DWT_SLEEPCNT_SLEEPCNT_Pos*/) /*!< DWT SLEEPCNT: SLEEPCNT Mask */ /* DWT LSU Count Register Definitions */ #define DWT_LSUCNT_LSUCNT_Pos 0 /*!< DWT LSUCNT: LSUCNT Position */ #define DWT_LSUCNT_LSUCNT_Msk (0xFFUL /*<< DWT_LSUCNT_LSUCNT_Pos*/) /*!< DWT LSUCNT: LSUCNT Mask */ /* DWT Folded-instruction Count Register Definitions */ #define DWT_FOLDCNT_FOLDCNT_Pos 0 /*!< DWT FOLDCNT: FOLDCNT Position */ #define DWT_FOLDCNT_FOLDCNT_Msk (0xFFUL /*<< DWT_FOLDCNT_FOLDCNT_Pos*/) /*!< DWT FOLDCNT: FOLDCNT Mask */ /* DWT Comparator Mask Register Definitions */ #define DWT_MASK_MASK_Pos 0 /*!< DWT MASK: MASK Position */ #define DWT_MASK_MASK_Msk (0x1FUL /*<< DWT_MASK_MASK_Pos*/) /*!< DWT MASK: MASK Mask */ /* DWT Comparator Function Register Definitions */ #define DWT_FUNCTION_MATCHED_Pos 24 /*!< DWT FUNCTION: MATCHED Position */ #define DWT_FUNCTION_MATCHED_Msk (0x1UL << DWT_FUNCTION_MATCHED_Pos) /*!< DWT FUNCTION: MATCHED Mask */ #define DWT_FUNCTION_DATAVADDR1_Pos 16 /*!< DWT FUNCTION: DATAVADDR1 Position */ #define DWT_FUNCTION_DATAVADDR1_Msk (0xFUL << DWT_FUNCTION_DATAVADDR1_Pos) /*!< DWT FUNCTION: DATAVADDR1 Mask */ #define DWT_FUNCTION_DATAVADDR0_Pos 12 /*!< DWT FUNCTION: DATAVADDR0 Position */ #define DWT_FUNCTION_DATAVADDR0_Msk (0xFUL << DWT_FUNCTION_DATAVADDR0_Pos) /*!< DWT FUNCTION: DATAVADDR0 Mask */ #define DWT_FUNCTION_DATAVSIZE_Pos 10 /*!< DWT FUNCTION: DATAVSIZE Position */ #define DWT_FUNCTION_DATAVSIZE_Msk (0x3UL << DWT_FUNCTION_DATAVSIZE_Pos) /*!< DWT FUNCTION: DATAVSIZE Mask */ #define DWT_FUNCTION_LNK1ENA_Pos 9 /*!< DWT FUNCTION: LNK1ENA Position */ #define DWT_FUNCTION_LNK1ENA_Msk (0x1UL << DWT_FUNCTION_LNK1ENA_Pos) /*!< DWT FUNCTION: LNK1ENA Mask */ #define DWT_FUNCTION_DATAVMATCH_Pos 8 /*!< DWT FUNCTION: DATAVMATCH Position */ #define DWT_FUNCTION_DATAVMATCH_Msk (0x1UL << DWT_FUNCTION_DATAVMATCH_Pos) /*!< DWT FUNCTION: DATAVMATCH Mask */ #define DWT_FUNCTION_CYCMATCH_Pos 7 /*!< DWT FUNCTION: CYCMATCH Position */ #define DWT_FUNCTION_CYCMATCH_Msk (0x1UL << DWT_FUNCTION_CYCMATCH_Pos) /*!< DWT FUNCTION: CYCMATCH Mask */ #define DWT_FUNCTION_EMITRANGE_Pos 5 /*!< DWT FUNCTION: EMITRANGE Position */ #define DWT_FUNCTION_EMITRANGE_Msk (0x1UL << DWT_FUNCTION_EMITRANGE_Pos) /*!< DWT FUNCTION: EMITRANGE Mask */ #define DWT_FUNCTION_FUNCTION_Pos 0 /*!< DWT FUNCTION: FUNCTION Position */ #define DWT_FUNCTION_FUNCTION_Msk (0xFUL /*<< DWT_FUNCTION_FUNCTION_Pos*/) /*!< DWT FUNCTION: FUNCTION Mask */ /*@}*/ /* end of group CMSIS_DWT */ /** \ingroup CMSIS_core_register \defgroup CMSIS_TPI Trace Port Interface (TPI) \brief Type definitions for the Trace Port Interface (TPI) @{ */ /** \brief Structure type to access the Trace Port Interface Register (TPI). */ typedef struct { __IO uint32_t SSPSR; /*!< Offset: 0x000 (R/ ) Supported Parallel Port Size Register */ __IO uint32_t CSPSR; /*!< Offset: 0x004 (R/W) Current Parallel Port Size Register */ uint32_t RESERVED0[2]; __IO uint32_t ACPR; /*!< Offset: 0x010 (R/W) Asynchronous Clock Prescaler Register */ uint32_t RESERVED1[55]; __IO uint32_t SPPR; /*!< Offset: 0x0F0 (R/W) Selected Pin Protocol Register */ uint32_t RESERVED2[131]; __I uint32_t FFSR; /*!< Offset: 0x300 (R/ ) Formatter and Flush Status Register */ __IO uint32_t FFCR; /*!< Offset: 0x304 (R/W) Formatter and Flush Control Register */ __I uint32_t FSCR; /*!< Offset: 0x308 (R/ ) Formatter Synchronization Counter Register */ uint32_t RESERVED3[759]; __I uint32_t TRIGGER; /*!< Offset: 0xEE8 (R/ ) TRIGGER */ __I uint32_t FIFO0; /*!< Offset: 0xEEC (R/ ) Integration ETM Data */ __I uint32_t ITATBCTR2; /*!< Offset: 0xEF0 (R/ ) ITATBCTR2 */ uint32_t RESERVED4[1]; __I uint32_t ITATBCTR0; /*!< Offset: 0xEF8 (R/ ) ITATBCTR0 */ __I uint32_t FIFO1; /*!< Offset: 0xEFC (R/ ) Integration ITM Data */ __IO uint32_t ITCTRL; /*!< Offset: 0xF00 (R/W) Integration Mode Control */ uint32_t RESERVED5[39]; __IO uint32_t CLAIMSET; /*!< Offset: 0xFA0 (R/W) Claim tag set */ __IO uint32_t CLAIMCLR; /*!< Offset: 0xFA4 (R/W) Claim tag clear */ uint32_t RESERVED7[8]; __I uint32_t DEVID; /*!< Offset: 0xFC8 (R/ ) TPIU_DEVID */ __I uint32_t DEVTYPE; /*!< Offset: 0xFCC (R/ ) TPIU_DEVTYPE */ } TPI_Type; /* TPI Asynchronous Clock Prescaler Register Definitions */ #define TPI_ACPR_PRESCALER_Pos 0 /*!< TPI ACPR: PRESCALER Position */ #define TPI_ACPR_PRESCALER_Msk (0x1FFFUL /*<< TPI_ACPR_PRESCALER_Pos*/) /*!< TPI ACPR: PRESCALER Mask */ /* TPI Selected Pin Protocol Register Definitions */ #define TPI_SPPR_TXMODE_Pos 0 /*!< TPI SPPR: TXMODE Position */ #define TPI_SPPR_TXMODE_Msk (0x3UL /*<< TPI_SPPR_TXMODE_Pos*/) /*!< TPI SPPR: TXMODE Mask */ /* TPI Formatter and Flush Status Register Definitions */ #define TPI_FFSR_FtNonStop_Pos 3 /*!< TPI FFSR: FtNonStop Position */ #define TPI_FFSR_FtNonStop_Msk (0x1UL << TPI_FFSR_FtNonStop_Pos) /*!< TPI FFSR: FtNonStop Mask */ #define TPI_FFSR_TCPresent_Pos 2 /*!< TPI FFSR: TCPresent Position */ #define TPI_FFSR_TCPresent_Msk (0x1UL << TPI_FFSR_TCPresent_Pos) /*!< TPI FFSR: TCPresent Mask */ #define TPI_FFSR_FtStopped_Pos 1 /*!< TPI FFSR: FtStopped Position */ #define TPI_FFSR_FtStopped_Msk (0x1UL << TPI_FFSR_FtStopped_Pos) /*!< TPI FFSR: FtStopped Mask */ #define TPI_FFSR_FlInProg_Pos 0 /*!< TPI FFSR: FlInProg Position */ #define TPI_FFSR_FlInProg_Msk (0x1UL /*<< TPI_FFSR_FlInProg_Pos*/) /*!< TPI FFSR: FlInProg Mask */ /* TPI Formatter and Flush Control Register Definitions */ #define TPI_FFCR_TrigIn_Pos 8 /*!< TPI FFCR: TrigIn Position */ #define TPI_FFCR_TrigIn_Msk (0x1UL << TPI_FFCR_TrigIn_Pos) /*!< TPI FFCR: TrigIn Mask */ #define TPI_FFCR_EnFCont_Pos 1 /*!< TPI FFCR: EnFCont Position */ #define TPI_FFCR_EnFCont_Msk (0x1UL << TPI_FFCR_EnFCont_Pos) /*!< TPI FFCR: EnFCont Mask */ /* TPI TRIGGER Register Definitions */ #define TPI_TRIGGER_TRIGGER_Pos 0 /*!< TPI TRIGGER: TRIGGER Position */ #define TPI_TRIGGER_TRIGGER_Msk (0x1UL /*<< TPI_TRIGGER_TRIGGER_Pos*/) /*!< TPI TRIGGER: TRIGGER Mask */ /* TPI Integration ETM Data Register Definitions (FIFO0) */ #define TPI_FIFO0_ITM_ATVALID_Pos 29 /*!< TPI FIFO0: ITM_ATVALID Position */ #define TPI_FIFO0_ITM_ATVALID_Msk (0x3UL << TPI_FIFO0_ITM_ATVALID_Pos) /*!< TPI FIFO0: ITM_ATVALID Mask */ #define TPI_FIFO0_ITM_bytecount_Pos 27 /*!< TPI FIFO0: ITM_bytecount Position */ #define TPI_FIFO0_ITM_bytecount_Msk (0x3UL << TPI_FIFO0_ITM_bytecount_Pos) /*!< TPI FIFO0: ITM_bytecount Mask */ #define TPI_FIFO0_ETM_ATVALID_Pos 26 /*!< TPI FIFO0: ETM_ATVALID Position */ #define TPI_FIFO0_ETM_ATVALID_Msk (0x3UL << TPI_FIFO0_ETM_ATVALID_Pos) /*!< TPI FIFO0: ETM_ATVALID Mask */ #define TPI_FIFO0_ETM_bytecount_Pos 24 /*!< TPI FIFO0: ETM_bytecount Position */ #define TPI_FIFO0_ETM_bytecount_Msk (0x3UL << TPI_FIFO0_ETM_bytecount_Pos) /*!< TPI FIFO0: ETM_bytecount Mask */ #define TPI_FIFO0_ETM2_Pos 16 /*!< TPI FIFO0: ETM2 Position */ #define TPI_FIFO0_ETM2_Msk (0xFFUL << TPI_FIFO0_ETM2_Pos) /*!< TPI FIFO0: ETM2 Mask */ #define TPI_FIFO0_ETM1_Pos 8 /*!< TPI FIFO0: ETM1 Position */ #define TPI_FIFO0_ETM1_Msk (0xFFUL << TPI_FIFO0_ETM1_Pos) /*!< TPI FIFO0: ETM1 Mask */ #define TPI_FIFO0_ETM0_Pos 0 /*!< TPI FIFO0: ETM0 Position */ #define TPI_FIFO0_ETM0_Msk (0xFFUL /*<< TPI_FIFO0_ETM0_Pos*/) /*!< TPI FIFO0: ETM0 Mask */ /* TPI ITATBCTR2 Register Definitions */ #define TPI_ITATBCTR2_ATREADY_Pos 0 /*!< TPI ITATBCTR2: ATREADY Position */ #define TPI_ITATBCTR2_ATREADY_Msk (0x1UL /*<< TPI_ITATBCTR2_ATREADY_Pos*/) /*!< TPI ITATBCTR2: ATREADY Mask */ /* TPI Integration ITM Data Register Definitions (FIFO1) */ #define TPI_FIFO1_ITM_ATVALID_Pos 29 /*!< TPI FIFO1: ITM_ATVALID Position */ #define TPI_FIFO1_ITM_ATVALID_Msk (0x3UL << TPI_FIFO1_ITM_ATVALID_Pos) /*!< TPI FIFO1: ITM_ATVALID Mask */ #define TPI_FIFO1_ITM_bytecount_Pos 27 /*!< TPI FIFO1: ITM_bytecount Position */ #define TPI_FIFO1_ITM_bytecount_Msk (0x3UL << TPI_FIFO1_ITM_bytecount_Pos) /*!< TPI FIFO1: ITM_bytecount Mask */ #define TPI_FIFO1_ETM_ATVALID_Pos 26 /*!< TPI FIFO1: ETM_ATVALID Position */ #define TPI_FIFO1_ETM_ATVALID_Msk (0x3UL << TPI_FIFO1_ETM_ATVALID_Pos) /*!< TPI FIFO1: ETM_ATVALID Mask */ #define TPI_FIFO1_ETM_bytecount_Pos 24 /*!< TPI FIFO1: ETM_bytecount Position */ #define TPI_FIFO1_ETM_bytecount_Msk (0x3UL << TPI_FIFO1_ETM_bytecount_Pos) /*!< TPI FIFO1: ETM_bytecount Mask */ #define TPI_FIFO1_ITM2_Pos 16 /*!< TPI FIFO1: ITM2 Position */ #define TPI_FIFO1_ITM2_Msk (0xFFUL << TPI_FIFO1_ITM2_Pos) /*!< TPI FIFO1: ITM2 Mask */ #define TPI_FIFO1_ITM1_Pos 8 /*!< TPI FIFO1: ITM1 Position */ #define TPI_FIFO1_ITM1_Msk (0xFFUL << TPI_FIFO1_ITM1_Pos) /*!< TPI FIFO1: ITM1 Mask */ #define TPI_FIFO1_ITM0_Pos 0 /*!< TPI FIFO1: ITM0 Position */ #define TPI_FIFO1_ITM0_Msk (0xFFUL /*<< TPI_FIFO1_ITM0_Pos*/) /*!< TPI FIFO1: ITM0 Mask */ /* TPI ITATBCTR0 Register Definitions */ #define TPI_ITATBCTR0_ATREADY_Pos 0 /*!< TPI ITATBCTR0: ATREADY Position */ #define TPI_ITATBCTR0_ATREADY_Msk (0x1UL /*<< TPI_ITATBCTR0_ATREADY_Pos*/) /*!< TPI ITATBCTR0: ATREADY Mask */ /* TPI Integration Mode Control Register Definitions */ #define TPI_ITCTRL_Mode_Pos 0 /*!< TPI ITCTRL: Mode Position */ #define TPI_ITCTRL_Mode_Msk (0x1UL /*<< TPI_ITCTRL_Mode_Pos*/) /*!< TPI ITCTRL: Mode Mask */ /* TPI DEVID Register Definitions */ #define TPI_DEVID_NRZVALID_Pos 11 /*!< TPI DEVID: NRZVALID Position */ #define TPI_DEVID_NRZVALID_Msk (0x1UL << TPI_DEVID_NRZVALID_Pos) /*!< TPI DEVID: NRZVALID Mask */ #define TPI_DEVID_MANCVALID_Pos 10 /*!< TPI DEVID: MANCVALID Position */ #define TPI_DEVID_MANCVALID_Msk (0x1UL << TPI_DEVID_MANCVALID_Pos) /*!< TPI DEVID: MANCVALID Mask */ #define TPI_DEVID_PTINVALID_Pos 9 /*!< TPI DEVID: PTINVALID Position */ #define TPI_DEVID_PTINVALID_Msk (0x1UL << TPI_DEVID_PTINVALID_Pos) /*!< TPI DEVID: PTINVALID Mask */ #define TPI_DEVID_MinBufSz_Pos 6 /*!< TPI DEVID: MinBufSz Position */ #define TPI_DEVID_MinBufSz_Msk (0x7UL << TPI_DEVID_MinBufSz_Pos) /*!< TPI DEVID: MinBufSz Mask */ #define TPI_DEVID_AsynClkIn_Pos 5 /*!< TPI DEVID: AsynClkIn Position */ #define TPI_DEVID_AsynClkIn_Msk (0x1UL << TPI_DEVID_AsynClkIn_Pos) /*!< TPI DEVID: AsynClkIn Mask */ #define TPI_DEVID_NrTraceInput_Pos 0 /*!< TPI DEVID: NrTraceInput Position */ #define TPI_DEVID_NrTraceInput_Msk (0x1FUL /*<< TPI_DEVID_NrTraceInput_Pos*/) /*!< TPI DEVID: NrTraceInput Mask */ /* TPI DEVTYPE Register Definitions */ #define TPI_DEVTYPE_MajorType_Pos 4 /*!< TPI DEVTYPE: MajorType Position */ #define TPI_DEVTYPE_MajorType_Msk (0xFUL << TPI_DEVTYPE_MajorType_Pos) /*!< TPI DEVTYPE: MajorType Mask */ #define TPI_DEVTYPE_SubType_Pos 0 /*!< TPI DEVTYPE: SubType Position */ #define TPI_DEVTYPE_SubType_Msk (0xFUL /*<< TPI_DEVTYPE_SubType_Pos*/) /*!< TPI DEVTYPE: SubType Mask */ /*@}*/ /* end of group CMSIS_TPI */ #if (__MPU_PRESENT == 1) /** \ingroup CMSIS_core_register \defgroup CMSIS_MPU Memory Protection Unit (MPU) \brief Type definitions for the Memory Protection Unit (MPU) @{ */ /** \brief Structure type to access the Memory Protection Unit (MPU). */ typedef struct { __I uint32_t TYPE; /*!< Offset: 0x000 (R/ ) MPU Type Register */ __IO uint32_t CTRL; /*!< Offset: 0x004 (R/W) MPU Control Register */ __IO uint32_t RNR; /*!< Offset: 0x008 (R/W) MPU Region RNRber Register */ __IO uint32_t RBAR; /*!< Offset: 0x00C (R/W) MPU Region Base Address Register */ __IO uint32_t RASR; /*!< Offset: 0x010 (R/W) MPU Region Attribute and Size Register */ __IO uint32_t RBAR_A1; /*!< Offset: 0x014 (R/W) MPU Alias 1 Region Base Address Register */ __IO uint32_t RASR_A1; /*!< Offset: 0x018 (R/W) MPU Alias 1 Region Attribute and Size Register */ __IO uint32_t RBAR_A2; /*!< Offset: 0x01C (R/W) MPU Alias 2 Region Base Address Register */ __IO uint32_t RASR_A2; /*!< Offset: 0x020 (R/W) MPU Alias 2 Region Attribute and Size Register */ __IO uint32_t RBAR_A3; /*!< Offset: 0x024 (R/W) MPU Alias 3 Region Base Address Register */ __IO uint32_t RASR_A3; /*!< Offset: 0x028 (R/W) MPU Alias 3 Region Attribute and Size Register */ } MPU_Type; /* MPU Type Register */ #define MPU_TYPE_IREGION_Pos 16 /*!< MPU TYPE: IREGION Position */ #define MPU_TYPE_IREGION_Msk (0xFFUL << MPU_TYPE_IREGION_Pos) /*!< MPU TYPE: IREGION Mask */ #define MPU_TYPE_DREGION_Pos 8 /*!< MPU TYPE: DREGION Position */ #define MPU_TYPE_DREGION_Msk (0xFFUL << MPU_TYPE_DREGION_Pos) /*!< MPU TYPE: DREGION Mask */ #define MPU_TYPE_SEPARATE_Pos 0 /*!< MPU TYPE: SEPARATE Position */ #define MPU_TYPE_SEPARATE_Msk (1UL /*<< MPU_TYPE_SEPARATE_Pos*/) /*!< MPU TYPE: SEPARATE Mask */ /* MPU Control Register */ #define MPU_CTRL_PRIVDEFENA_Pos 2 /*!< MPU CTRL: PRIVDEFENA Position */ #define MPU_CTRL_PRIVDEFENA_Msk (1UL << MPU_CTRL_PRIVDEFENA_Pos) /*!< MPU CTRL: PRIVDEFENA Mask */ #define MPU_CTRL_HFNMIENA_Pos 1 /*!< MPU CTRL: HFNMIENA Position */ #define MPU_CTRL_HFNMIENA_Msk (1UL << MPU_CTRL_HFNMIENA_Pos) /*!< MPU CTRL: HFNMIENA Mask */ #define MPU_CTRL_ENABLE_Pos 0 /*!< MPU CTRL: ENABLE Position */ #define MPU_CTRL_ENABLE_Msk (1UL /*<< MPU_CTRL_ENABLE_Pos*/) /*!< MPU CTRL: ENABLE Mask */ /* MPU Region Number Register */ #define MPU_RNR_REGION_Pos 0 /*!< MPU RNR: REGION Position */ #define MPU_RNR_REGION_Msk (0xFFUL /*<< MPU_RNR_REGION_Pos*/) /*!< MPU RNR: REGION Mask */ /* MPU Region Base Address Register */ #define MPU_RBAR_ADDR_Pos 5 /*!< MPU RBAR: ADDR Position */ #define MPU_RBAR_ADDR_Msk (0x7FFFFFFUL << MPU_RBAR_ADDR_Pos) /*!< MPU RBAR: ADDR Mask */ #define MPU_RBAR_VALID_Pos 4 /*!< MPU RBAR: VALID Position */ #define MPU_RBAR_VALID_Msk (1UL << MPU_RBAR_VALID_Pos) /*!< MPU RBAR: VALID Mask */ #define MPU_RBAR_REGION_Pos 0 /*!< MPU RBAR: REGION Position */ #define MPU_RBAR_REGION_Msk (0xFUL /*<< MPU_RBAR_REGION_Pos*/) /*!< MPU RBAR: REGION Mask */ /* MPU Region Attribute and Size Register */ #define MPU_RASR_ATTRS_Pos 16 /*!< MPU RASR: MPU Region Attribute field Position */ #define MPU_RASR_ATTRS_Msk (0xFFFFUL << MPU_RASR_ATTRS_Pos) /*!< MPU RASR: MPU Region Attribute field Mask */ #define MPU_RASR_XN_Pos 28 /*!< MPU RASR: ATTRS.XN Position */ #define MPU_RASR_XN_Msk (1UL << MPU_RASR_XN_Pos) /*!< MPU RASR: ATTRS.XN Mask */ #define MPU_RASR_AP_Pos 24 /*!< MPU RASR: ATTRS.AP Position */ #define MPU_RASR_AP_Msk (0x7UL << MPU_RASR_AP_Pos) /*!< MPU RASR: ATTRS.AP Mask */ #define MPU_RASR_TEX_Pos 19 /*!< MPU RASR: ATTRS.TEX Position */ #define MPU_RASR_TEX_Msk (0x7UL << MPU_RASR_TEX_Pos) /*!< MPU RASR: ATTRS.TEX Mask */ #define MPU_RASR_S_Pos 18 /*!< MPU RASR: ATTRS.S Position */ #define MPU_RASR_S_Msk (1UL << MPU_RASR_S_Pos) /*!< MPU RASR: ATTRS.S Mask */ #define MPU_RASR_C_Pos 17 /*!< MPU RASR: ATTRS.C Position */ #define MPU_RASR_C_Msk (1UL << MPU_RASR_C_Pos) /*!< MPU RASR: ATTRS.C Mask */ #define MPU_RASR_B_Pos 16 /*!< MPU RASR: ATTRS.B Position */ #define MPU_RASR_B_Msk (1UL << MPU_RASR_B_Pos) /*!< MPU RASR: ATTRS.B Mask */ #define MPU_RASR_SRD_Pos 8 /*!< MPU RASR: Sub-Region Disable Position */ #define MPU_RASR_SRD_Msk (0xFFUL << MPU_RASR_SRD_Pos) /*!< MPU RASR: Sub-Region Disable Mask */ #define MPU_RASR_SIZE_Pos 1 /*!< MPU RASR: Region Size Field Position */ #define MPU_RASR_SIZE_Msk (0x1FUL << MPU_RASR_SIZE_Pos) /*!< MPU RASR: Region Size Field Mask */ #define MPU_RASR_ENABLE_Pos 0 /*!< MPU RASR: Region enable bit Position */ #define MPU_RASR_ENABLE_Msk (1UL /*<< MPU_RASR_ENABLE_Pos*/) /*!< MPU RASR: Region enable bit Disable Mask */ /*@} end of group CMSIS_MPU */ #endif /** \ingroup CMSIS_core_register \defgroup CMSIS_CoreDebug Core Debug Registers (CoreDebug) \brief Type definitions for the Core Debug Registers @{ */ /** \brief Structure type to access the Core Debug Register (CoreDebug). */ typedef struct { __IO uint32_t DHCSR; /*!< Offset: 0x000 (R/W) Debug Halting Control and Status Register */ __O uint32_t DCRSR; /*!< Offset: 0x004 ( /W) Debug Core Register Selector Register */ __IO uint32_t DCRDR; /*!< Offset: 0x008 (R/W) Debug Core Register Data Register */ __IO uint32_t DEMCR; /*!< Offset: 0x00C (R/W) Debug Exception and Monitor Control Register */ } CoreDebug_Type; /* Debug Halting Control and Status Register */ #define CoreDebug_DHCSR_DBGKEY_Pos 16 /*!< CoreDebug DHCSR: DBGKEY Position */ #define CoreDebug_DHCSR_DBGKEY_Msk (0xFFFFUL << CoreDebug_DHCSR_DBGKEY_Pos) /*!< CoreDebug DHCSR: DBGKEY Mask */ #define CoreDebug_DHCSR_S_RESET_ST_Pos 25 /*!< CoreDebug DHCSR: S_RESET_ST Position */ #define CoreDebug_DHCSR_S_RESET_ST_Msk (1UL << CoreDebug_DHCSR_S_RESET_ST_Pos) /*!< CoreDebug DHCSR: S_RESET_ST Mask */ #define CoreDebug_DHCSR_S_RETIRE_ST_Pos 24 /*!< CoreDebug DHCSR: S_RETIRE_ST Position */ #define CoreDebug_DHCSR_S_RETIRE_ST_Msk (1UL << CoreDebug_DHCSR_S_RETIRE_ST_Pos) /*!< CoreDebug DHCSR: S_RETIRE_ST Mask */ #define CoreDebug_DHCSR_S_LOCKUP_Pos 19 /*!< CoreDebug DHCSR: S_LOCKUP Position */ #define CoreDebug_DHCSR_S_LOCKUP_Msk (1UL << CoreDebug_DHCSR_S_LOCKUP_Pos) /*!< CoreDebug DHCSR: S_LOCKUP Mask */ #define CoreDebug_DHCSR_S_SLEEP_Pos 18 /*!< CoreDebug DHCSR: S_SLEEP Position */ #define CoreDebug_DHCSR_S_SLEEP_Msk (1UL << CoreDebug_DHCSR_S_SLEEP_Pos) /*!< CoreDebug DHCSR: S_SLEEP Mask */ #define CoreDebug_DHCSR_S_HALT_Pos 17 /*!< CoreDebug DHCSR: S_HALT Position */ #define CoreDebug_DHCSR_S_HALT_Msk (1UL << CoreDebug_DHCSR_S_HALT_Pos) /*!< CoreDebug DHCSR: S_HALT Mask */ #define CoreDebug_DHCSR_S_REGRDY_Pos 16 /*!< CoreDebug DHCSR: S_REGRDY Position */ #define CoreDebug_DHCSR_S_REGRDY_Msk (1UL << CoreDebug_DHCSR_S_REGRDY_Pos) /*!< CoreDebug DHCSR: S_REGRDY Mask */ #define CoreDebug_DHCSR_C_SNAPSTALL_Pos 5 /*!< CoreDebug DHCSR: C_SNAPSTALL Position */ #define CoreDebug_DHCSR_C_SNAPSTALL_Msk (1UL << CoreDebug_DHCSR_C_SNAPSTALL_Pos) /*!< CoreDebug DHCSR: C_SNAPSTALL Mask */ #define CoreDebug_DHCSR_C_MASKINTS_Pos 3 /*!< CoreDebug DHCSR: C_MASKINTS Position */ #define CoreDebug_DHCSR_C_MASKINTS_Msk (1UL << CoreDebug_DHCSR_C_MASKINTS_Pos) /*!< CoreDebug DHCSR: C_MASKINTS Mask */ #define CoreDebug_DHCSR_C_STEP_Pos 2 /*!< CoreDebug DHCSR: C_STEP Position */ #define CoreDebug_DHCSR_C_STEP_Msk (1UL << CoreDebug_DHCSR_C_STEP_Pos) /*!< CoreDebug DHCSR: C_STEP Mask */ #define CoreDebug_DHCSR_C_HALT_Pos 1 /*!< CoreDebug DHCSR: C_HALT Position */ #define CoreDebug_DHCSR_C_HALT_Msk (1UL << CoreDebug_DHCSR_C_HALT_Pos) /*!< CoreDebug DHCSR: C_HALT Mask */ #define CoreDebug_DHCSR_C_DEBUGEN_Pos 0 /*!< CoreDebug DHCSR: C_DEBUGEN Position */ #define CoreDebug_DHCSR_C_DEBUGEN_Msk (1UL /*<< CoreDebug_DHCSR_C_DEBUGEN_Pos*/) /*!< CoreDebug DHCSR: C_DEBUGEN Mask */ /* Debug Core Register Selector Register */ #define CoreDebug_DCRSR_REGWnR_Pos 16 /*!< CoreDebug DCRSR: REGWnR Position */ #define CoreDebug_DCRSR_REGWnR_Msk (1UL << CoreDebug_DCRSR_REGWnR_Pos) /*!< CoreDebug DCRSR: REGWnR Mask */ #define CoreDebug_DCRSR_REGSEL_Pos 0 /*!< CoreDebug DCRSR: REGSEL Position */ #define CoreDebug_DCRSR_REGSEL_Msk (0x1FUL /*<< CoreDebug_DCRSR_REGSEL_Pos*/) /*!< CoreDebug DCRSR: REGSEL Mask */ /* Debug Exception and Monitor Control Register */ #define CoreDebug_DEMCR_TRCENA_Pos 24 /*!< CoreDebug DEMCR: TRCENA Position */ #define CoreDebug_DEMCR_TRCENA_Msk (1UL << CoreDebug_DEMCR_TRCENA_Pos) /*!< CoreDebug DEMCR: TRCENA Mask */ #define CoreDebug_DEMCR_MON_REQ_Pos 19 /*!< CoreDebug DEMCR: MON_REQ Position */ #define CoreDebug_DEMCR_MON_REQ_Msk (1UL << CoreDebug_DEMCR_MON_REQ_Pos) /*!< CoreDebug DEMCR: MON_REQ Mask */ #define CoreDebug_DEMCR_MON_STEP_Pos 18 /*!< CoreDebug DEMCR: MON_STEP Position */ #define CoreDebug_DEMCR_MON_STEP_Msk (1UL << CoreDebug_DEMCR_MON_STEP_Pos) /*!< CoreDebug DEMCR: MON_STEP Mask */ #define CoreDebug_DEMCR_MON_PEND_Pos 17 /*!< CoreDebug DEMCR: MON_PEND Position */ #define CoreDebug_DEMCR_MON_PEND_Msk (1UL << CoreDebug_DEMCR_MON_PEND_Pos) /*!< CoreDebug DEMCR: MON_PEND Mask */ #define CoreDebug_DEMCR_MON_EN_Pos 16 /*!< CoreDebug DEMCR: MON_EN Position */ #define CoreDebug_DEMCR_MON_EN_Msk (1UL << CoreDebug_DEMCR_MON_EN_Pos) /*!< CoreDebug DEMCR: MON_EN Mask */ #define CoreDebug_DEMCR_VC_HARDERR_Pos 10 /*!< CoreDebug DEMCR: VC_HARDERR Position */ #define CoreDebug_DEMCR_VC_HARDERR_Msk (1UL << CoreDebug_DEMCR_VC_HARDERR_Pos) /*!< CoreDebug DEMCR: VC_HARDERR Mask */ #define CoreDebug_DEMCR_VC_INTERR_Pos 9 /*!< CoreDebug DEMCR: VC_INTERR Position */ #define CoreDebug_DEMCR_VC_INTERR_Msk (1UL << CoreDebug_DEMCR_VC_INTERR_Pos) /*!< CoreDebug DEMCR: VC_INTERR Mask */ #define CoreDebug_DEMCR_VC_BUSERR_Pos 8 /*!< CoreDebug DEMCR: VC_BUSERR Position */ #define CoreDebug_DEMCR_VC_BUSERR_Msk (1UL << CoreDebug_DEMCR_VC_BUSERR_Pos) /*!< CoreDebug DEMCR: VC_BUSERR Mask */ #define CoreDebug_DEMCR_VC_STATERR_Pos 7 /*!< CoreDebug DEMCR: VC_STATERR Position */ #define CoreDebug_DEMCR_VC_STATERR_Msk (1UL << CoreDebug_DEMCR_VC_STATERR_Pos) /*!< CoreDebug DEMCR: VC_STATERR Mask */ #define CoreDebug_DEMCR_VC_CHKERR_Pos 6 /*!< CoreDebug DEMCR: VC_CHKERR Position */ #define CoreDebug_DEMCR_VC_CHKERR_Msk (1UL << CoreDebug_DEMCR_VC_CHKERR_Pos) /*!< CoreDebug DEMCR: VC_CHKERR Mask */ #define CoreDebug_DEMCR_VC_NOCPERR_Pos 5 /*!< CoreDebug DEMCR: VC_NOCPERR Position */ #define CoreDebug_DEMCR_VC_NOCPERR_Msk (1UL << CoreDebug_DEMCR_VC_NOCPERR_Pos) /*!< CoreDebug DEMCR: VC_NOCPERR Mask */ #define CoreDebug_DEMCR_VC_MMERR_Pos 4 /*!< CoreDebug DEMCR: VC_MMERR Position */ #define CoreDebug_DEMCR_VC_MMERR_Msk (1UL << CoreDebug_DEMCR_VC_MMERR_Pos) /*!< CoreDebug DEMCR: VC_MMERR Mask */ #define CoreDebug_DEMCR_VC_CORERESET_Pos 0 /*!< CoreDebug DEMCR: VC_CORERESET Position */ #define CoreDebug_DEMCR_VC_CORERESET_Msk (1UL /*<< CoreDebug_DEMCR_VC_CORERESET_Pos*/) /*!< CoreDebug DEMCR: VC_CORERESET Mask */ /*@} end of group CMSIS_CoreDebug */ /** \ingroup CMSIS_core_register \defgroup CMSIS_core_base Core Definitions \brief Definitions for base addresses, unions, and structures. @{ */ /* Memory mapping of Cortex-M3 Hardware */ #define SCS_BASE (0xE000E000UL) /*!< System Control Space Base Address */ #define ITM_BASE (0xE0000000UL) /*!< ITM Base Address */ #define DWT_BASE (0xE0001000UL) /*!< DWT Base Address */ #define TPI_BASE (0xE0040000UL) /*!< TPI Base Address */ #define CoreDebug_BASE (0xE000EDF0UL) /*!< Core Debug Base Address */ #define SysTick_BASE (SCS_BASE + 0x0010UL) /*!< SysTick Base Address */ #define NVIC_BASE (SCS_BASE + 0x0100UL) /*!< NVIC Base Address */ #define SCB_BASE (SCS_BASE + 0x0D00UL) /*!< System Control Block Base Address */ #define SCnSCB ((SCnSCB_Type *) SCS_BASE ) /*!< System control Register not in SCB */ #define SCB ((SCB_Type *) SCB_BASE ) /*!< SCB configuration struct */ #define SysTick ((SysTick_Type *) SysTick_BASE ) /*!< SysTick configuration struct */ #define NVIC ((NVIC_Type *) NVIC_BASE ) /*!< NVIC configuration struct */ #define ITM ((ITM_Type *) ITM_BASE ) /*!< ITM configuration struct */ #define DWT ((DWT_Type *) DWT_BASE ) /*!< DWT configuration struct */ #define TPI ((TPI_Type *) TPI_BASE ) /*!< TPI configuration struct */ #define CoreDebug ((CoreDebug_Type *) CoreDebug_BASE) /*!< Core Debug configuration struct */ #if (__MPU_PRESENT == 1) #define MPU_BASE (SCS_BASE + 0x0D90UL) /*!< Memory Protection Unit */ #define MPU ((MPU_Type *) MPU_BASE ) /*!< Memory Protection Unit */ #endif /*@} */ /******************************************************************************* * Hardware Abstraction Layer Core Function Interface contains: - Core NVIC Functions - Core SysTick Functions - Core Debug Functions - Core Register Access Functions ******************************************************************************/ /** \defgroup CMSIS_Core_FunctionInterface Functions and Instructions Reference */ /* ########################## NVIC functions #################################### */ /** \ingroup CMSIS_Core_FunctionInterface \defgroup CMSIS_Core_NVICFunctions NVIC Functions \brief Functions that manage interrupts and exceptions via the NVIC. @{ */ /** \brief Set Priority Grouping The function sets the priority grouping field using the required unlock sequence. The parameter PriorityGroup is assigned to the field SCB->AIRCR [10:8] PRIGROUP field. Only values from 0..7 are used. In case of a conflict between priority grouping and available priority bits (__NVIC_PRIO_BITS), the smallest possible priority group is set. \param [in] PriorityGroup Priority grouping field. */ __STATIC_INLINE void NVIC_SetPriorityGrouping(uint32_t PriorityGroup) { uint32_t reg_value; uint32_t PriorityGroupTmp = (PriorityGroup & (uint32_t)0x07UL); /* only values 0..7 are used */ reg_value = SCB->AIRCR; /* read old register configuration */ reg_value &= ~((uint32_t)(SCB_AIRCR_VECTKEY_Msk | SCB_AIRCR_PRIGROUP_Msk)); /* clear bits to change */ reg_value = (reg_value | ((uint32_t)0x5FAUL << SCB_AIRCR_VECTKEY_Pos) | (PriorityGroupTmp << 8) ); /* Insert write key and priorty group */ SCB->AIRCR = reg_value; } /** \brief Get Priority Grouping The function reads the priority grouping field from the NVIC Interrupt Controller. \return Priority grouping field (SCB->AIRCR [10:8] PRIGROUP field). */ __STATIC_INLINE uint32_t NVIC_GetPriorityGrouping(void) { return ((uint32_t)((SCB->AIRCR & SCB_AIRCR_PRIGROUP_Msk) >> SCB_AIRCR_PRIGROUP_Pos)); } /** \brief Enable External Interrupt The function enables a device-specific interrupt in the NVIC interrupt controller. \param [in] IRQn External interrupt number. Value cannot be negative. */ __STATIC_INLINE void NVIC_EnableIRQ(IRQn_Type IRQn) { NVIC->ISER[(((uint32_t)(int32_t)IRQn) >> 5UL)] = (uint32_t)(1UL << (((uint32_t)(int32_t)IRQn) & 0x1FUL)); } /** \brief Disable External Interrupt The function disables a device-specific interrupt in the NVIC interrupt controller. \param [in] IRQn External interrupt number. Value cannot be negative. */ __STATIC_INLINE void NVIC_DisableIRQ(IRQn_Type IRQn) { NVIC->ICER[(((uint32_t)(int32_t)IRQn) >> 5UL)] = (uint32_t)(1UL << (((uint32_t)(int32_t)IRQn) & 0x1FUL)); } /** \brief Get Pending Interrupt The function reads the pending register in the NVIC and returns the pending bit for the specified interrupt. \param [in] IRQn Interrupt number. \return 0 Interrupt status is not pending. \return 1 Interrupt status is pending. */ __STATIC_INLINE uint32_t NVIC_GetPendingIRQ(IRQn_Type IRQn) { return((uint32_t)(((NVIC->ISPR[(((uint32_t)(int32_t)IRQn) >> 5UL)] & (1UL << (((uint32_t)(int32_t)IRQn) & 0x1FUL))) != 0UL) ? 1UL : 0UL)); } /** \brief Set Pending Interrupt The function sets the pending bit of an external interrupt. \param [in] IRQn Interrupt number. Value cannot be negative. */ __STATIC_INLINE void NVIC_SetPendingIRQ(IRQn_Type IRQn) { NVIC->ISPR[(((uint32_t)(int32_t)IRQn) >> 5UL)] = (uint32_t)(1UL << (((uint32_t)(int32_t)IRQn) & 0x1FUL)); } /** \brief Clear Pending Interrupt The function clears the pending bit of an external interrupt. \param [in] IRQn External interrupt number. Value cannot be negative. */ __STATIC_INLINE void NVIC_ClearPendingIRQ(IRQn_Type IRQn) { NVIC->ICPR[(((uint32_t)(int32_t)IRQn) >> 5UL)] = (uint32_t)(1UL << (((uint32_t)(int32_t)IRQn) & 0x1FUL)); } /** \brief Get Active Interrupt The function reads the active register in NVIC and returns the active bit. \param [in] IRQn Interrupt number. \return 0 Interrupt status is not active. \return 1 Interrupt status is active. */ __STATIC_INLINE uint32_t NVIC_GetActive(IRQn_Type IRQn) { return((uint32_t)(((NVIC->IABR[(((uint32_t)(int32_t)IRQn) >> 5UL)] & (1UL << (((uint32_t)(int32_t)IRQn) & 0x1FUL))) != 0UL) ? 1UL : 0UL)); } /** \brief Set Interrupt Priority The function sets the priority of an interrupt. \note The priority cannot be set for every core interrupt. \param [in] IRQn Interrupt number. \param [in] priority Priority to set. */ __STATIC_INLINE void NVIC_SetPriority(IRQn_Type IRQn, uint32_t priority) { if((int32_t)IRQn < 0) { SCB->SHP[(((uint32_t)(int32_t)IRQn) & 0xFUL)-4UL] = (uint8_t)((priority << (8 - __NVIC_PRIO_BITS)) & (uint32_t)0xFFUL); } else { NVIC->IP[((uint32_t)(int32_t)IRQn)] = (uint8_t)((priority << (8 - __NVIC_PRIO_BITS)) & (uint32_t)0xFFUL); } } /** \brief Get Interrupt Priority The function reads the priority of an interrupt. The interrupt number can be positive to specify an external (device specific) interrupt, or negative to specify an internal (core) interrupt. \param [in] IRQn Interrupt number. \return Interrupt Priority. Value is aligned automatically to the implemented priority bits of the microcontroller. */ __STATIC_INLINE uint32_t NVIC_GetPriority(IRQn_Type IRQn) { if((int32_t)IRQn < 0) { return(((uint32_t)SCB->SHP[(((uint32_t)(int32_t)IRQn) & 0xFUL)-4UL] >> (8 - __NVIC_PRIO_BITS))); } else { return(((uint32_t)NVIC->IP[((uint32_t)(int32_t)IRQn)] >> (8 - __NVIC_PRIO_BITS))); } } /** \brief Encode Priority The function encodes the priority for an interrupt with the given priority group, preemptive priority value, and subpriority value. In case of a conflict between priority grouping and available priority bits (__NVIC_PRIO_BITS), the smallest possible priority group is set. \param [in] PriorityGroup Used priority group. \param [in] PreemptPriority Preemptive priority value (starting from 0). \param [in] SubPriority Subpriority value (starting from 0). \return Encoded priority. Value can be used in the function \ref NVIC_SetPriority(). */ __STATIC_INLINE uint32_t NVIC_EncodePriority (uint32_t PriorityGroup, uint32_t PreemptPriority, uint32_t SubPriority) { uint32_t PriorityGroupTmp = (PriorityGroup & (uint32_t)0x07UL); /* only values 0..7 are used */ uint32_t PreemptPriorityBits; uint32_t SubPriorityBits; PreemptPriorityBits = ((7UL - PriorityGroupTmp) > (uint32_t)(__NVIC_PRIO_BITS)) ? (uint32_t)(__NVIC_PRIO_BITS) : (uint32_t)(7UL - PriorityGroupTmp); SubPriorityBits = ((PriorityGroupTmp + (uint32_t)(__NVIC_PRIO_BITS)) < (uint32_t)7UL) ? (uint32_t)0UL : (uint32_t)((PriorityGroupTmp - 7UL) + (uint32_t)(__NVIC_PRIO_BITS)); return ( ((PreemptPriority & (uint32_t)((1UL << (PreemptPriorityBits)) - 1UL)) << SubPriorityBits) | ((SubPriority & (uint32_t)((1UL << (SubPriorityBits )) - 1UL))) ); } /** \brief Decode Priority The function decodes an interrupt priority value with a given priority group to preemptive priority value and subpriority value. In case of a conflict between priority grouping and available priority bits (__NVIC_PRIO_BITS) the smallest possible priority group is set. \param [in] Priority Priority value, which can be retrieved with the function \ref NVIC_GetPriority(). \param [in] PriorityGroup Used priority group. \param [out] pPreemptPriority Preemptive priority value (starting from 0). \param [out] pSubPriority Subpriority value (starting from 0). */ __STATIC_INLINE void NVIC_DecodePriority (uint32_t Priority, uint32_t PriorityGroup, uint32_t* pPreemptPriority, uint32_t* pSubPriority) { uint32_t PriorityGroupTmp = (PriorityGroup & (uint32_t)0x07UL); /* only values 0..7 are used */ uint32_t PreemptPriorityBits; uint32_t SubPriorityBits; PreemptPriorityBits = ((7UL - PriorityGroupTmp) > (uint32_t)(__NVIC_PRIO_BITS)) ? (uint32_t)(__NVIC_PRIO_BITS) : (uint32_t)(7UL - PriorityGroupTmp); SubPriorityBits = ((PriorityGroupTmp + (uint32_t)(__NVIC_PRIO_BITS)) < (uint32_t)7UL) ? (uint32_t)0UL : (uint32_t)((PriorityGroupTmp - 7UL) + (uint32_t)(__NVIC_PRIO_BITS)); *pPreemptPriority = (Priority >> SubPriorityBits) & (uint32_t)((1UL << (PreemptPriorityBits)) - 1UL); *pSubPriority = (Priority ) & (uint32_t)((1UL << (SubPriorityBits )) - 1UL); } /** \brief System Reset The function initiates a system reset request to reset the MCU. */ __STATIC_INLINE void NVIC_SystemReset(void) { __DSB(); /* Ensure all outstanding memory accesses included buffered write are completed before reset */ SCB->AIRCR = (uint32_t)((0x5FAUL << SCB_AIRCR_VECTKEY_Pos) | (SCB->AIRCR & SCB_AIRCR_PRIGROUP_Msk) | SCB_AIRCR_SYSRESETREQ_Msk ); /* Keep priority group unchanged */ __DSB(); /* Ensure completion of memory access */ while(1) { __NOP(); } /* wait until reset */ } /*@} end of CMSIS_Core_NVICFunctions */ /* ################################## SysTick function ############################################ */ /** \ingroup CMSIS_Core_FunctionInterface \defgroup CMSIS_Core_SysTickFunctions SysTick Functions \brief Functions that configure the System. @{ */ #if (__Vendor_SysTickConfig == 0) /** \brief System Tick Configuration The function initializes the System Timer and its interrupt, and starts the System Tick Timer. Counter is in free running mode to generate periodic interrupts. \param [in] ticks Number of ticks between two interrupts. \return 0 Function succeeded. \return 1 Function failed. \note When the variable __Vendor_SysTickConfig is set to 1, then the function SysTick_Config is not included. In this case, the file device.h must contain a vendor-specific implementation of this function. */ __STATIC_INLINE uint32_t SysTick_Config(uint32_t ticks) { if ((ticks - 1UL) > SysTick_LOAD_RELOAD_Msk) { return (1UL); } /* Reload value impossible */ SysTick->LOAD = (uint32_t)(ticks - 1UL); /* set reload register */ NVIC_SetPriority (SysTick_IRQn, (1UL << __NVIC_PRIO_BITS) - 1UL); /* set Priority for Systick Interrupt */ SysTick->VAL = 0UL; /* Load the SysTick Counter Value */ SysTick->CTRL = SysTick_CTRL_CLKSOURCE_Msk | SysTick_CTRL_TICKINT_Msk | SysTick_CTRL_ENABLE_Msk; /* Enable SysTick IRQ and SysTick Timer */ return (0UL); /* Function successful */ } #endif /*@} end of CMSIS_Core_SysTickFunctions */ /* ##################################### Debug In/Output function ########################################### */ /** \ingroup CMSIS_Core_FunctionInterface \defgroup CMSIS_core_DebugFunctions ITM Functions \brief Functions that access the ITM debug interface. @{ */ extern volatile int32_t ITM_RxBuffer; /*!< External variable to receive characters. */ #define ITM_RXBUFFER_EMPTY 0x5AA55AA5 /*!< Value identifying \ref ITM_RxBuffer is ready for next character. */ /** \brief ITM Send Character The function transmits a character via the ITM channel 0, and \li Just returns when no debugger is connected that has booked the output. \li Is blocking when a debugger is connected, but the previous character sent has not been transmitted. \param [in] ch Character to transmit. \returns Character to transmit. */ __STATIC_INLINE uint32_t ITM_SendChar (uint32_t ch) { if (((ITM->TCR & ITM_TCR_ITMENA_Msk) != 0UL) && /* ITM enabled */ ((ITM->TER & 1UL ) != 0UL) ) /* ITM Port #0 enabled */ { while (ITM->PORT[0].u32 == 0UL) { __NOP(); } ITM->PORT[0].u8 = (uint8_t)ch; } return (ch); } /** \brief ITM Receive Character The function inputs a character via the external variable \ref ITM_RxBuffer. \return Received character. \return -1 No character pending. */ __STATIC_INLINE int32_t ITM_ReceiveChar (void) { int32_t ch = -1; /* no character available */ if (ITM_RxBuffer != ITM_RXBUFFER_EMPTY) { ch = ITM_RxBuffer; ITM_RxBuffer = ITM_RXBUFFER_EMPTY; /* ready for next character */ } return (ch); } /** \brief ITM Check Character The function checks whether a character is pending for reading in the variable \ref ITM_RxBuffer. \return 0 No character available. \return 1 Character available. */ __STATIC_INLINE int32_t ITM_CheckChar (void) { if (ITM_RxBuffer == ITM_RXBUFFER_EMPTY) { return (0); /* no character available */ } else { return (1); /* character available */ } } /*@} end of CMSIS_core_DebugFunctions */ #ifdef __cplusplus } #endif #endif /* __CORE_CM3_H_DEPENDANT */ #endif /* __CMSIS_GENERIC */ ================================================ FILE: Zelig/mbed/TARGET_NUCLEO_F411RE/core_cm4.h ================================================ /**************************************************************************//** * @file core_cm4.h * @brief CMSIS Cortex-M4 Core Peripheral Access Layer Header File * @version V4.10 * @date 18. March 2015 * * @note * ******************************************************************************/ /* Copyright (c) 2009 - 2015 ARM LIMITED All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: - Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. - Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. - Neither the name of ARM 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 COPYRIGHT HOLDERS AND 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. ---------------------------------------------------------------------------*/ #if defined ( __ICCARM__ ) #pragma system_include /* treat file as system include file for MISRA check */ #endif #ifndef __CORE_CM4_H_GENERIC #define __CORE_CM4_H_GENERIC #ifdef __cplusplus extern "C" { #endif /** \page CMSIS_MISRA_Exceptions MISRA-C:2004 Compliance Exceptions CMSIS violates the following MISRA-C:2004 rules: \li Required Rule 8.5, object/function definition in header file.
Function definitions in header files are used to allow 'inlining'. \li Required Rule 18.4, declaration of union type or object of union type: '{...}'.
Unions are used for effective representation of core registers. \li Advisory Rule 19.7, Function-like macro defined.
Function-like macros are used to allow more efficient code. */ /******************************************************************************* * CMSIS definitions ******************************************************************************/ /** \ingroup Cortex_M4 @{ */ /* CMSIS CM4 definitions */ #define __CM4_CMSIS_VERSION_MAIN (0x04) /*!< [31:16] CMSIS HAL main version */ #define __CM4_CMSIS_VERSION_SUB (0x00) /*!< [15:0] CMSIS HAL sub version */ #define __CM4_CMSIS_VERSION ((__CM4_CMSIS_VERSION_MAIN << 16) | \ __CM4_CMSIS_VERSION_SUB ) /*!< CMSIS HAL version number */ #define __CORTEX_M (0x04) /*!< Cortex-M Core */ #if defined ( __CC_ARM ) #define __ASM __asm /*!< asm keyword for ARM Compiler */ #define __INLINE __inline /*!< inline keyword for ARM Compiler */ #define __STATIC_INLINE static __inline #elif defined ( __GNUC__ ) #define __ASM __asm /*!< asm keyword for GNU Compiler */ #define __INLINE inline /*!< inline keyword for GNU Compiler */ #define __STATIC_INLINE static inline #elif defined ( __ICCARM__ ) #define __ASM __asm /*!< asm keyword for IAR Compiler */ #define __INLINE inline /*!< inline keyword for IAR Compiler. Only available in High optimization mode! */ #define __STATIC_INLINE static inline #elif defined ( __TMS470__ ) #define __ASM __asm /*!< asm keyword for TI CCS Compiler */ #define __STATIC_INLINE static inline #elif defined ( __TASKING__ ) #define __ASM __asm /*!< asm keyword for TASKING Compiler */ #define __INLINE inline /*!< inline keyword for TASKING Compiler */ #define __STATIC_INLINE static inline #elif defined ( __CSMC__ ) #define __packed #define __ASM _asm /*!< asm keyword for COSMIC Compiler */ #define __INLINE inline /*use -pc99 on compile line !< inline keyword for COSMIC Compiler */ #define __STATIC_INLINE static inline #endif /** __FPU_USED indicates whether an FPU is used or not. For this, __FPU_PRESENT has to be checked prior to making use of FPU specific registers and functions. */ #if defined ( __CC_ARM ) #if defined __TARGET_FPU_VFP #if (__FPU_PRESENT == 1) #define __FPU_USED 1 #else #warning "Compiler generates FPU instructions for a device without an FPU (check __FPU_PRESENT)" #define __FPU_USED 0 #endif #else #define __FPU_USED 0 #endif #elif defined ( __GNUC__ ) #if defined (__VFP_FP__) && !defined(__SOFTFP__) #if (__FPU_PRESENT == 1) #define __FPU_USED 1 #else #warning "Compiler generates FPU instructions for a device without an FPU (check __FPU_PRESENT)" #define __FPU_USED 0 #endif #else #define __FPU_USED 0 #endif #elif defined ( __ICCARM__ ) #if defined __ARMVFP__ #if (__FPU_PRESENT == 1) #define __FPU_USED 1 #else #warning "Compiler generates FPU instructions for a device without an FPU (check __FPU_PRESENT)" #define __FPU_USED 0 #endif #else #define __FPU_USED 0 #endif #elif defined ( __TMS470__ ) #if defined __TI_VFP_SUPPORT__ #if (__FPU_PRESENT == 1) #define __FPU_USED 1 #else #warning "Compiler generates FPU instructions for a device without an FPU (check __FPU_PRESENT)" #define __FPU_USED 0 #endif #else #define __FPU_USED 0 #endif #elif defined ( __TASKING__ ) #if defined __FPU_VFP__ #if (__FPU_PRESENT == 1) #define __FPU_USED 1 #else #error "Compiler generates FPU instructions for a device without an FPU (check __FPU_PRESENT)" #define __FPU_USED 0 #endif #else #define __FPU_USED 0 #endif #elif defined ( __CSMC__ ) /* Cosmic */ #if ( __CSMC__ & 0x400) // FPU present for parser #if (__FPU_PRESENT == 1) #define __FPU_USED 1 #else #error "Compiler generates FPU instructions for a device without an FPU (check __FPU_PRESENT)" #define __FPU_USED 0 #endif #else #define __FPU_USED 0 #endif #endif #include /* standard types definitions */ #include /* Core Instruction Access */ #include /* Core Function Access */ #include /* Compiler specific SIMD Intrinsics */ #ifdef __cplusplus } #endif #endif /* __CORE_CM4_H_GENERIC */ #ifndef __CMSIS_GENERIC #ifndef __CORE_CM4_H_DEPENDANT #define __CORE_CM4_H_DEPENDANT #ifdef __cplusplus extern "C" { #endif /* check device defines and use defaults */ #if defined __CHECK_DEVICE_DEFINES #ifndef __CM4_REV #define __CM4_REV 0x0000 #warning "__CM4_REV not defined in device header file; using default!" #endif #ifndef __FPU_PRESENT #define __FPU_PRESENT 0 #warning "__FPU_PRESENT not defined in device header file; using default!" #endif #ifndef __MPU_PRESENT #define __MPU_PRESENT 0 #warning "__MPU_PRESENT not defined in device header file; using default!" #endif #ifndef __NVIC_PRIO_BITS #define __NVIC_PRIO_BITS 4 #warning "__NVIC_PRIO_BITS not defined in device header file; using default!" #endif #ifndef __Vendor_SysTickConfig #define __Vendor_SysTickConfig 0 #warning "__Vendor_SysTickConfig not defined in device header file; using default!" #endif #endif /* IO definitions (access restrictions to peripheral registers) */ /** \defgroup CMSIS_glob_defs CMSIS Global Defines IO Type Qualifiers are used \li to specify the access to peripheral variables. \li for automatic generation of peripheral register debug information. */ #ifdef __cplusplus #define __I volatile /*!< Defines 'read only' permissions */ #else #define __I volatile const /*!< Defines 'read only' permissions */ #endif #define __O volatile /*!< Defines 'write only' permissions */ #define __IO volatile /*!< Defines 'read / write' permissions */ /*@} end of group Cortex_M4 */ /******************************************************************************* * Register Abstraction Core Register contain: - Core Register - Core NVIC Register - Core SCB Register - Core SysTick Register - Core Debug Register - Core MPU Register - Core FPU Register ******************************************************************************/ /** \defgroup CMSIS_core_register Defines and Type Definitions \brief Type definitions and defines for Cortex-M processor based devices. */ /** \ingroup CMSIS_core_register \defgroup CMSIS_CORE Status and Control Registers \brief Core Register type definitions. @{ */ /** \brief Union type to access the Application Program Status Register (APSR). */ typedef union { struct { uint32_t _reserved0:16; /*!< bit: 0..15 Reserved */ uint32_t GE:4; /*!< bit: 16..19 Greater than or Equal flags */ uint32_t _reserved1:7; /*!< bit: 20..26 Reserved */ uint32_t Q:1; /*!< bit: 27 Saturation condition flag */ uint32_t V:1; /*!< bit: 28 Overflow condition code flag */ uint32_t C:1; /*!< bit: 29 Carry condition code flag */ uint32_t Z:1; /*!< bit: 30 Zero condition code flag */ uint32_t N:1; /*!< bit: 31 Negative condition code flag */ } b; /*!< Structure used for bit access */ uint32_t w; /*!< Type used for word access */ } APSR_Type; /* APSR Register Definitions */ #define APSR_N_Pos 31 /*!< APSR: N Position */ #define APSR_N_Msk (1UL << APSR_N_Pos) /*!< APSR: N Mask */ #define APSR_Z_Pos 30 /*!< APSR: Z Position */ #define APSR_Z_Msk (1UL << APSR_Z_Pos) /*!< APSR: Z Mask */ #define APSR_C_Pos 29 /*!< APSR: C Position */ #define APSR_C_Msk (1UL << APSR_C_Pos) /*!< APSR: C Mask */ #define APSR_V_Pos 28 /*!< APSR: V Position */ #define APSR_V_Msk (1UL << APSR_V_Pos) /*!< APSR: V Mask */ #define APSR_Q_Pos 27 /*!< APSR: Q Position */ #define APSR_Q_Msk (1UL << APSR_Q_Pos) /*!< APSR: Q Mask */ #define APSR_GE_Pos 16 /*!< APSR: GE Position */ #define APSR_GE_Msk (0xFUL << APSR_GE_Pos) /*!< APSR: GE Mask */ /** \brief Union type to access the Interrupt Program Status Register (IPSR). */ typedef union { struct { uint32_t ISR:9; /*!< bit: 0.. 8 Exception number */ uint32_t _reserved0:23; /*!< bit: 9..31 Reserved */ } b; /*!< Structure used for bit access */ uint32_t w; /*!< Type used for word access */ } IPSR_Type; /* IPSR Register Definitions */ #define IPSR_ISR_Pos 0 /*!< IPSR: ISR Position */ #define IPSR_ISR_Msk (0x1FFUL /*<< IPSR_ISR_Pos*/) /*!< IPSR: ISR Mask */ /** \brief Union type to access the Special-Purpose Program Status Registers (xPSR). */ typedef union { struct { uint32_t ISR:9; /*!< bit: 0.. 8 Exception number */ uint32_t _reserved0:7; /*!< bit: 9..15 Reserved */ uint32_t GE:4; /*!< bit: 16..19 Greater than or Equal flags */ uint32_t _reserved1:4; /*!< bit: 20..23 Reserved */ uint32_t T:1; /*!< bit: 24 Thumb bit (read 0) */ uint32_t IT:2; /*!< bit: 25..26 saved IT state (read 0) */ uint32_t Q:1; /*!< bit: 27 Saturation condition flag */ uint32_t V:1; /*!< bit: 28 Overflow condition code flag */ uint32_t C:1; /*!< bit: 29 Carry condition code flag */ uint32_t Z:1; /*!< bit: 30 Zero condition code flag */ uint32_t N:1; /*!< bit: 31 Negative condition code flag */ } b; /*!< Structure used for bit access */ uint32_t w; /*!< Type used for word access */ } xPSR_Type; /* xPSR Register Definitions */ #define xPSR_N_Pos 31 /*!< xPSR: N Position */ #define xPSR_N_Msk (1UL << xPSR_N_Pos) /*!< xPSR: N Mask */ #define xPSR_Z_Pos 30 /*!< xPSR: Z Position */ #define xPSR_Z_Msk (1UL << xPSR_Z_Pos) /*!< xPSR: Z Mask */ #define xPSR_C_Pos 29 /*!< xPSR: C Position */ #define xPSR_C_Msk (1UL << xPSR_C_Pos) /*!< xPSR: C Mask */ #define xPSR_V_Pos 28 /*!< xPSR: V Position */ #define xPSR_V_Msk (1UL << xPSR_V_Pos) /*!< xPSR: V Mask */ #define xPSR_Q_Pos 27 /*!< xPSR: Q Position */ #define xPSR_Q_Msk (1UL << xPSR_Q_Pos) /*!< xPSR: Q Mask */ #define xPSR_IT_Pos 25 /*!< xPSR: IT Position */ #define xPSR_IT_Msk (3UL << xPSR_IT_Pos) /*!< xPSR: IT Mask */ #define xPSR_T_Pos 24 /*!< xPSR: T Position */ #define xPSR_T_Msk (1UL << xPSR_T_Pos) /*!< xPSR: T Mask */ #define xPSR_GE_Pos 16 /*!< xPSR: GE Position */ #define xPSR_GE_Msk (0xFUL << xPSR_GE_Pos) /*!< xPSR: GE Mask */ #define xPSR_ISR_Pos 0 /*!< xPSR: ISR Position */ #define xPSR_ISR_Msk (0x1FFUL /*<< xPSR_ISR_Pos*/) /*!< xPSR: ISR Mask */ /** \brief Union type to access the Control Registers (CONTROL). */ typedef union { struct { uint32_t nPRIV:1; /*!< bit: 0 Execution privilege in Thread mode */ uint32_t SPSEL:1; /*!< bit: 1 Stack to be used */ uint32_t FPCA:1; /*!< bit: 2 FP extension active flag */ uint32_t _reserved0:29; /*!< bit: 3..31 Reserved */ } b; /*!< Structure used for bit access */ uint32_t w; /*!< Type used for word access */ } CONTROL_Type; /* CONTROL Register Definitions */ #define CONTROL_FPCA_Pos 2 /*!< CONTROL: FPCA Position */ #define CONTROL_FPCA_Msk (1UL << CONTROL_FPCA_Pos) /*!< CONTROL: FPCA Mask */ #define CONTROL_SPSEL_Pos 1 /*!< CONTROL: SPSEL Position */ #define CONTROL_SPSEL_Msk (1UL << CONTROL_SPSEL_Pos) /*!< CONTROL: SPSEL Mask */ #define CONTROL_nPRIV_Pos 0 /*!< CONTROL: nPRIV Position */ #define CONTROL_nPRIV_Msk (1UL /*<< CONTROL_nPRIV_Pos*/) /*!< CONTROL: nPRIV Mask */ /*@} end of group CMSIS_CORE */ /** \ingroup CMSIS_core_register \defgroup CMSIS_NVIC Nested Vectored Interrupt Controller (NVIC) \brief Type definitions for the NVIC Registers @{ */ /** \brief Structure type to access the Nested Vectored Interrupt Controller (NVIC). */ typedef struct { __IO uint32_t ISER[8]; /*!< Offset: 0x000 (R/W) Interrupt Set Enable Register */ uint32_t RESERVED0[24]; __IO uint32_t ICER[8]; /*!< Offset: 0x080 (R/W) Interrupt Clear Enable Register */ uint32_t RSERVED1[24]; __IO uint32_t ISPR[8]; /*!< Offset: 0x100 (R/W) Interrupt Set Pending Register */ uint32_t RESERVED2[24]; __IO uint32_t ICPR[8]; /*!< Offset: 0x180 (R/W) Interrupt Clear Pending Register */ uint32_t RESERVED3[24]; __IO uint32_t IABR[8]; /*!< Offset: 0x200 (R/W) Interrupt Active bit Register */ uint32_t RESERVED4[56]; __IO uint8_t IP[240]; /*!< Offset: 0x300 (R/W) Interrupt Priority Register (8Bit wide) */ uint32_t RESERVED5[644]; __O uint32_t STIR; /*!< Offset: 0xE00 ( /W) Software Trigger Interrupt Register */ } NVIC_Type; /* Software Triggered Interrupt Register Definitions */ #define NVIC_STIR_INTID_Pos 0 /*!< STIR: INTLINESNUM Position */ #define NVIC_STIR_INTID_Msk (0x1FFUL /*<< NVIC_STIR_INTID_Pos*/) /*!< STIR: INTLINESNUM Mask */ /*@} end of group CMSIS_NVIC */ /** \ingroup CMSIS_core_register \defgroup CMSIS_SCB System Control Block (SCB) \brief Type definitions for the System Control Block Registers @{ */ /** \brief Structure type to access the System Control Block (SCB). */ typedef struct { __I uint32_t CPUID; /*!< Offset: 0x000 (R/ ) CPUID Base Register */ __IO uint32_t ICSR; /*!< Offset: 0x004 (R/W) Interrupt Control and State Register */ __IO uint32_t VTOR; /*!< Offset: 0x008 (R/W) Vector Table Offset Register */ __IO uint32_t AIRCR; /*!< Offset: 0x00C (R/W) Application Interrupt and Reset Control Register */ __IO uint32_t SCR; /*!< Offset: 0x010 (R/W) System Control Register */ __IO uint32_t CCR; /*!< Offset: 0x014 (R/W) Configuration Control Register */ __IO uint8_t SHP[12]; /*!< Offset: 0x018 (R/W) System Handlers Priority Registers (4-7, 8-11, 12-15) */ __IO uint32_t SHCSR; /*!< Offset: 0x024 (R/W) System Handler Control and State Register */ __IO uint32_t CFSR; /*!< Offset: 0x028 (R/W) Configurable Fault Status Register */ __IO uint32_t HFSR; /*!< Offset: 0x02C (R/W) HardFault Status Register */ __IO uint32_t DFSR; /*!< Offset: 0x030 (R/W) Debug Fault Status Register */ __IO uint32_t MMFAR; /*!< Offset: 0x034 (R/W) MemManage Fault Address Register */ __IO uint32_t BFAR; /*!< Offset: 0x038 (R/W) BusFault Address Register */ __IO uint32_t AFSR; /*!< Offset: 0x03C (R/W) Auxiliary Fault Status Register */ __I uint32_t PFR[2]; /*!< Offset: 0x040 (R/ ) Processor Feature Register */ __I uint32_t DFR; /*!< Offset: 0x048 (R/ ) Debug Feature Register */ __I uint32_t ADR; /*!< Offset: 0x04C (R/ ) Auxiliary Feature Register */ __I uint32_t MMFR[4]; /*!< Offset: 0x050 (R/ ) Memory Model Feature Register */ __I uint32_t ISAR[5]; /*!< Offset: 0x060 (R/ ) Instruction Set Attributes Register */ uint32_t RESERVED0[5]; __IO uint32_t CPACR; /*!< Offset: 0x088 (R/W) Coprocessor Access Control Register */ } SCB_Type; /* SCB CPUID Register Definitions */ #define SCB_CPUID_IMPLEMENTER_Pos 24 /*!< SCB CPUID: IMPLEMENTER Position */ #define SCB_CPUID_IMPLEMENTER_Msk (0xFFUL << SCB_CPUID_IMPLEMENTER_Pos) /*!< SCB CPUID: IMPLEMENTER Mask */ #define SCB_CPUID_VARIANT_Pos 20 /*!< SCB CPUID: VARIANT Position */ #define SCB_CPUID_VARIANT_Msk (0xFUL << SCB_CPUID_VARIANT_Pos) /*!< SCB CPUID: VARIANT Mask */ #define SCB_CPUID_ARCHITECTURE_Pos 16 /*!< SCB CPUID: ARCHITECTURE Position */ #define SCB_CPUID_ARCHITECTURE_Msk (0xFUL << SCB_CPUID_ARCHITECTURE_Pos) /*!< SCB CPUID: ARCHITECTURE Mask */ #define SCB_CPUID_PARTNO_Pos 4 /*!< SCB CPUID: PARTNO Position */ #define SCB_CPUID_PARTNO_Msk (0xFFFUL << SCB_CPUID_PARTNO_Pos) /*!< SCB CPUID: PARTNO Mask */ #define SCB_CPUID_REVISION_Pos 0 /*!< SCB CPUID: REVISION Position */ #define SCB_CPUID_REVISION_Msk (0xFUL /*<< SCB_CPUID_REVISION_Pos*/) /*!< SCB CPUID: REVISION Mask */ /* SCB Interrupt Control State Register Definitions */ #define SCB_ICSR_NMIPENDSET_Pos 31 /*!< SCB ICSR: NMIPENDSET Position */ #define SCB_ICSR_NMIPENDSET_Msk (1UL << SCB_ICSR_NMIPENDSET_Pos) /*!< SCB ICSR: NMIPENDSET Mask */ #define SCB_ICSR_PENDSVSET_Pos 28 /*!< SCB ICSR: PENDSVSET Position */ #define SCB_ICSR_PENDSVSET_Msk (1UL << SCB_ICSR_PENDSVSET_Pos) /*!< SCB ICSR: PENDSVSET Mask */ #define SCB_ICSR_PENDSVCLR_Pos 27 /*!< SCB ICSR: PENDSVCLR Position */ #define SCB_ICSR_PENDSVCLR_Msk (1UL << SCB_ICSR_PENDSVCLR_Pos) /*!< SCB ICSR: PENDSVCLR Mask */ #define SCB_ICSR_PENDSTSET_Pos 26 /*!< SCB ICSR: PENDSTSET Position */ #define SCB_ICSR_PENDSTSET_Msk (1UL << SCB_ICSR_PENDSTSET_Pos) /*!< SCB ICSR: PENDSTSET Mask */ #define SCB_ICSR_PENDSTCLR_Pos 25 /*!< SCB ICSR: PENDSTCLR Position */ #define SCB_ICSR_PENDSTCLR_Msk (1UL << SCB_ICSR_PENDSTCLR_Pos) /*!< SCB ICSR: PENDSTCLR Mask */ #define SCB_ICSR_ISRPREEMPT_Pos 23 /*!< SCB ICSR: ISRPREEMPT Position */ #define SCB_ICSR_ISRPREEMPT_Msk (1UL << SCB_ICSR_ISRPREEMPT_Pos) /*!< SCB ICSR: ISRPREEMPT Mask */ #define SCB_ICSR_ISRPENDING_Pos 22 /*!< SCB ICSR: ISRPENDING Position */ #define SCB_ICSR_ISRPENDING_Msk (1UL << SCB_ICSR_ISRPENDING_Pos) /*!< SCB ICSR: ISRPENDING Mask */ #define SCB_ICSR_VECTPENDING_Pos 12 /*!< SCB ICSR: VECTPENDING Position */ #define SCB_ICSR_VECTPENDING_Msk (0x1FFUL << SCB_ICSR_VECTPENDING_Pos) /*!< SCB ICSR: VECTPENDING Mask */ #define SCB_ICSR_RETTOBASE_Pos 11 /*!< SCB ICSR: RETTOBASE Position */ #define SCB_ICSR_RETTOBASE_Msk (1UL << SCB_ICSR_RETTOBASE_Pos) /*!< SCB ICSR: RETTOBASE Mask */ #define SCB_ICSR_VECTACTIVE_Pos 0 /*!< SCB ICSR: VECTACTIVE Position */ #define SCB_ICSR_VECTACTIVE_Msk (0x1FFUL /*<< SCB_ICSR_VECTACTIVE_Pos*/) /*!< SCB ICSR: VECTACTIVE Mask */ /* SCB Vector Table Offset Register Definitions */ #define SCB_VTOR_TBLOFF_Pos 7 /*!< SCB VTOR: TBLOFF Position */ #define SCB_VTOR_TBLOFF_Msk (0x1FFFFFFUL << SCB_VTOR_TBLOFF_Pos) /*!< SCB VTOR: TBLOFF Mask */ /* SCB Application Interrupt and Reset Control Register Definitions */ #define SCB_AIRCR_VECTKEY_Pos 16 /*!< SCB AIRCR: VECTKEY Position */ #define SCB_AIRCR_VECTKEY_Msk (0xFFFFUL << SCB_AIRCR_VECTKEY_Pos) /*!< SCB AIRCR: VECTKEY Mask */ #define SCB_AIRCR_VECTKEYSTAT_Pos 16 /*!< SCB AIRCR: VECTKEYSTAT Position */ #define SCB_AIRCR_VECTKEYSTAT_Msk (0xFFFFUL << SCB_AIRCR_VECTKEYSTAT_Pos) /*!< SCB AIRCR: VECTKEYSTAT Mask */ #define SCB_AIRCR_ENDIANESS_Pos 15 /*!< SCB AIRCR: ENDIANESS Position */ #define SCB_AIRCR_ENDIANESS_Msk (1UL << SCB_AIRCR_ENDIANESS_Pos) /*!< SCB AIRCR: ENDIANESS Mask */ #define SCB_AIRCR_PRIGROUP_Pos 8 /*!< SCB AIRCR: PRIGROUP Position */ #define SCB_AIRCR_PRIGROUP_Msk (7UL << SCB_AIRCR_PRIGROUP_Pos) /*!< SCB AIRCR: PRIGROUP Mask */ #define SCB_AIRCR_SYSRESETREQ_Pos 2 /*!< SCB AIRCR: SYSRESETREQ Position */ #define SCB_AIRCR_SYSRESETREQ_Msk (1UL << SCB_AIRCR_SYSRESETREQ_Pos) /*!< SCB AIRCR: SYSRESETREQ Mask */ #define SCB_AIRCR_VECTCLRACTIVE_Pos 1 /*!< SCB AIRCR: VECTCLRACTIVE Position */ #define SCB_AIRCR_VECTCLRACTIVE_Msk (1UL << SCB_AIRCR_VECTCLRACTIVE_Pos) /*!< SCB AIRCR: VECTCLRACTIVE Mask */ #define SCB_AIRCR_VECTRESET_Pos 0 /*!< SCB AIRCR: VECTRESET Position */ #define SCB_AIRCR_VECTRESET_Msk (1UL /*<< SCB_AIRCR_VECTRESET_Pos*/) /*!< SCB AIRCR: VECTRESET Mask */ /* SCB System Control Register Definitions */ #define SCB_SCR_SEVONPEND_Pos 4 /*!< SCB SCR: SEVONPEND Position */ #define SCB_SCR_SEVONPEND_Msk (1UL << SCB_SCR_SEVONPEND_Pos) /*!< SCB SCR: SEVONPEND Mask */ #define SCB_SCR_SLEEPDEEP_Pos 2 /*!< SCB SCR: SLEEPDEEP Position */ #define SCB_SCR_SLEEPDEEP_Msk (1UL << SCB_SCR_SLEEPDEEP_Pos) /*!< SCB SCR: SLEEPDEEP Mask */ #define SCB_SCR_SLEEPONEXIT_Pos 1 /*!< SCB SCR: SLEEPONEXIT Position */ #define SCB_SCR_SLEEPONEXIT_Msk (1UL << SCB_SCR_SLEEPONEXIT_Pos) /*!< SCB SCR: SLEEPONEXIT Mask */ /* SCB Configuration Control Register Definitions */ #define SCB_CCR_STKALIGN_Pos 9 /*!< SCB CCR: STKALIGN Position */ #define SCB_CCR_STKALIGN_Msk (1UL << SCB_CCR_STKALIGN_Pos) /*!< SCB CCR: STKALIGN Mask */ #define SCB_CCR_BFHFNMIGN_Pos 8 /*!< SCB CCR: BFHFNMIGN Position */ #define SCB_CCR_BFHFNMIGN_Msk (1UL << SCB_CCR_BFHFNMIGN_Pos) /*!< SCB CCR: BFHFNMIGN Mask */ #define SCB_CCR_DIV_0_TRP_Pos 4 /*!< SCB CCR: DIV_0_TRP Position */ #define SCB_CCR_DIV_0_TRP_Msk (1UL << SCB_CCR_DIV_0_TRP_Pos) /*!< SCB CCR: DIV_0_TRP Mask */ #define SCB_CCR_UNALIGN_TRP_Pos 3 /*!< SCB CCR: UNALIGN_TRP Position */ #define SCB_CCR_UNALIGN_TRP_Msk (1UL << SCB_CCR_UNALIGN_TRP_Pos) /*!< SCB CCR: UNALIGN_TRP Mask */ #define SCB_CCR_USERSETMPEND_Pos 1 /*!< SCB CCR: USERSETMPEND Position */ #define SCB_CCR_USERSETMPEND_Msk (1UL << SCB_CCR_USERSETMPEND_Pos) /*!< SCB CCR: USERSETMPEND Mask */ #define SCB_CCR_NONBASETHRDENA_Pos 0 /*!< SCB CCR: NONBASETHRDENA Position */ #define SCB_CCR_NONBASETHRDENA_Msk (1UL /*<< SCB_CCR_NONBASETHRDENA_Pos*/) /*!< SCB CCR: NONBASETHRDENA Mask */ /* SCB System Handler Control and State Register Definitions */ #define SCB_SHCSR_USGFAULTENA_Pos 18 /*!< SCB SHCSR: USGFAULTENA Position */ #define SCB_SHCSR_USGFAULTENA_Msk (1UL << SCB_SHCSR_USGFAULTENA_Pos) /*!< SCB SHCSR: USGFAULTENA Mask */ #define SCB_SHCSR_BUSFAULTENA_Pos 17 /*!< SCB SHCSR: BUSFAULTENA Position */ #define SCB_SHCSR_BUSFAULTENA_Msk (1UL << SCB_SHCSR_BUSFAULTENA_Pos) /*!< SCB SHCSR: BUSFAULTENA Mask */ #define SCB_SHCSR_MEMFAULTENA_Pos 16 /*!< SCB SHCSR: MEMFAULTENA Position */ #define SCB_SHCSR_MEMFAULTENA_Msk (1UL << SCB_SHCSR_MEMFAULTENA_Pos) /*!< SCB SHCSR: MEMFAULTENA Mask */ #define SCB_SHCSR_SVCALLPENDED_Pos 15 /*!< SCB SHCSR: SVCALLPENDED Position */ #define SCB_SHCSR_SVCALLPENDED_Msk (1UL << SCB_SHCSR_SVCALLPENDED_Pos) /*!< SCB SHCSR: SVCALLPENDED Mask */ #define SCB_SHCSR_BUSFAULTPENDED_Pos 14 /*!< SCB SHCSR: BUSFAULTPENDED Position */ #define SCB_SHCSR_BUSFAULTPENDED_Msk (1UL << SCB_SHCSR_BUSFAULTPENDED_Pos) /*!< SCB SHCSR: BUSFAULTPENDED Mask */ #define SCB_SHCSR_MEMFAULTPENDED_Pos 13 /*!< SCB SHCSR: MEMFAULTPENDED Position */ #define SCB_SHCSR_MEMFAULTPENDED_Msk (1UL << SCB_SHCSR_MEMFAULTPENDED_Pos) /*!< SCB SHCSR: MEMFAULTPENDED Mask */ #define SCB_SHCSR_USGFAULTPENDED_Pos 12 /*!< SCB SHCSR: USGFAULTPENDED Position */ #define SCB_SHCSR_USGFAULTPENDED_Msk (1UL << SCB_SHCSR_USGFAULTPENDED_Pos) /*!< SCB SHCSR: USGFAULTPENDED Mask */ #define SCB_SHCSR_SYSTICKACT_Pos 11 /*!< SCB SHCSR: SYSTICKACT Position */ #define SCB_SHCSR_SYSTICKACT_Msk (1UL << SCB_SHCSR_SYSTICKACT_Pos) /*!< SCB SHCSR: SYSTICKACT Mask */ #define SCB_SHCSR_PENDSVACT_Pos 10 /*!< SCB SHCSR: PENDSVACT Position */ #define SCB_SHCSR_PENDSVACT_Msk (1UL << SCB_SHCSR_PENDSVACT_Pos) /*!< SCB SHCSR: PENDSVACT Mask */ #define SCB_SHCSR_MONITORACT_Pos 8 /*!< SCB SHCSR: MONITORACT Position */ #define SCB_SHCSR_MONITORACT_Msk (1UL << SCB_SHCSR_MONITORACT_Pos) /*!< SCB SHCSR: MONITORACT Mask */ #define SCB_SHCSR_SVCALLACT_Pos 7 /*!< SCB SHCSR: SVCALLACT Position */ #define SCB_SHCSR_SVCALLACT_Msk (1UL << SCB_SHCSR_SVCALLACT_Pos) /*!< SCB SHCSR: SVCALLACT Mask */ #define SCB_SHCSR_USGFAULTACT_Pos 3 /*!< SCB SHCSR: USGFAULTACT Position */ #define SCB_SHCSR_USGFAULTACT_Msk (1UL << SCB_SHCSR_USGFAULTACT_Pos) /*!< SCB SHCSR: USGFAULTACT Mask */ #define SCB_SHCSR_BUSFAULTACT_Pos 1 /*!< SCB SHCSR: BUSFAULTACT Position */ #define SCB_SHCSR_BUSFAULTACT_Msk (1UL << SCB_SHCSR_BUSFAULTACT_Pos) /*!< SCB SHCSR: BUSFAULTACT Mask */ #define SCB_SHCSR_MEMFAULTACT_Pos 0 /*!< SCB SHCSR: MEMFAULTACT Position */ #define SCB_SHCSR_MEMFAULTACT_Msk (1UL /*<< SCB_SHCSR_MEMFAULTACT_Pos*/) /*!< SCB SHCSR: MEMFAULTACT Mask */ /* SCB Configurable Fault Status Registers Definitions */ #define SCB_CFSR_USGFAULTSR_Pos 16 /*!< SCB CFSR: Usage Fault Status Register Position */ #define SCB_CFSR_USGFAULTSR_Msk (0xFFFFUL << SCB_CFSR_USGFAULTSR_Pos) /*!< SCB CFSR: Usage Fault Status Register Mask */ #define SCB_CFSR_BUSFAULTSR_Pos 8 /*!< SCB CFSR: Bus Fault Status Register Position */ #define SCB_CFSR_BUSFAULTSR_Msk (0xFFUL << SCB_CFSR_BUSFAULTSR_Pos) /*!< SCB CFSR: Bus Fault Status Register Mask */ #define SCB_CFSR_MEMFAULTSR_Pos 0 /*!< SCB CFSR: Memory Manage Fault Status Register Position */ #define SCB_CFSR_MEMFAULTSR_Msk (0xFFUL /*<< SCB_CFSR_MEMFAULTSR_Pos*/) /*!< SCB CFSR: Memory Manage Fault Status Register Mask */ /* SCB Hard Fault Status Registers Definitions */ #define SCB_HFSR_DEBUGEVT_Pos 31 /*!< SCB HFSR: DEBUGEVT Position */ #define SCB_HFSR_DEBUGEVT_Msk (1UL << SCB_HFSR_DEBUGEVT_Pos) /*!< SCB HFSR: DEBUGEVT Mask */ #define SCB_HFSR_FORCED_Pos 30 /*!< SCB HFSR: FORCED Position */ #define SCB_HFSR_FORCED_Msk (1UL << SCB_HFSR_FORCED_Pos) /*!< SCB HFSR: FORCED Mask */ #define SCB_HFSR_VECTTBL_Pos 1 /*!< SCB HFSR: VECTTBL Position */ #define SCB_HFSR_VECTTBL_Msk (1UL << SCB_HFSR_VECTTBL_Pos) /*!< SCB HFSR: VECTTBL Mask */ /* SCB Debug Fault Status Register Definitions */ #define SCB_DFSR_EXTERNAL_Pos 4 /*!< SCB DFSR: EXTERNAL Position */ #define SCB_DFSR_EXTERNAL_Msk (1UL << SCB_DFSR_EXTERNAL_Pos) /*!< SCB DFSR: EXTERNAL Mask */ #define SCB_DFSR_VCATCH_Pos 3 /*!< SCB DFSR: VCATCH Position */ #define SCB_DFSR_VCATCH_Msk (1UL << SCB_DFSR_VCATCH_Pos) /*!< SCB DFSR: VCATCH Mask */ #define SCB_DFSR_DWTTRAP_Pos 2 /*!< SCB DFSR: DWTTRAP Position */ #define SCB_DFSR_DWTTRAP_Msk (1UL << SCB_DFSR_DWTTRAP_Pos) /*!< SCB DFSR: DWTTRAP Mask */ #define SCB_DFSR_BKPT_Pos 1 /*!< SCB DFSR: BKPT Position */ #define SCB_DFSR_BKPT_Msk (1UL << SCB_DFSR_BKPT_Pos) /*!< SCB DFSR: BKPT Mask */ #define SCB_DFSR_HALTED_Pos 0 /*!< SCB DFSR: HALTED Position */ #define SCB_DFSR_HALTED_Msk (1UL /*<< SCB_DFSR_HALTED_Pos*/) /*!< SCB DFSR: HALTED Mask */ /*@} end of group CMSIS_SCB */ /** \ingroup CMSIS_core_register \defgroup CMSIS_SCnSCB System Controls not in SCB (SCnSCB) \brief Type definitions for the System Control and ID Register not in the SCB @{ */ /** \brief Structure type to access the System Control and ID Register not in the SCB. */ typedef struct { uint32_t RESERVED0[1]; __I uint32_t ICTR; /*!< Offset: 0x004 (R/ ) Interrupt Controller Type Register */ __IO uint32_t ACTLR; /*!< Offset: 0x008 (R/W) Auxiliary Control Register */ } SCnSCB_Type; /* Interrupt Controller Type Register Definitions */ #define SCnSCB_ICTR_INTLINESNUM_Pos 0 /*!< ICTR: INTLINESNUM Position */ #define SCnSCB_ICTR_INTLINESNUM_Msk (0xFUL /*<< SCnSCB_ICTR_INTLINESNUM_Pos*/) /*!< ICTR: INTLINESNUM Mask */ /* Auxiliary Control Register Definitions */ #define SCnSCB_ACTLR_DISOOFP_Pos 9 /*!< ACTLR: DISOOFP Position */ #define SCnSCB_ACTLR_DISOOFP_Msk (1UL << SCnSCB_ACTLR_DISOOFP_Pos) /*!< ACTLR: DISOOFP Mask */ #define SCnSCB_ACTLR_DISFPCA_Pos 8 /*!< ACTLR: DISFPCA Position */ #define SCnSCB_ACTLR_DISFPCA_Msk (1UL << SCnSCB_ACTLR_DISFPCA_Pos) /*!< ACTLR: DISFPCA Mask */ #define SCnSCB_ACTLR_DISFOLD_Pos 2 /*!< ACTLR: DISFOLD Position */ #define SCnSCB_ACTLR_DISFOLD_Msk (1UL << SCnSCB_ACTLR_DISFOLD_Pos) /*!< ACTLR: DISFOLD Mask */ #define SCnSCB_ACTLR_DISDEFWBUF_Pos 1 /*!< ACTLR: DISDEFWBUF Position */ #define SCnSCB_ACTLR_DISDEFWBUF_Msk (1UL << SCnSCB_ACTLR_DISDEFWBUF_Pos) /*!< ACTLR: DISDEFWBUF Mask */ #define SCnSCB_ACTLR_DISMCYCINT_Pos 0 /*!< ACTLR: DISMCYCINT Position */ #define SCnSCB_ACTLR_DISMCYCINT_Msk (1UL /*<< SCnSCB_ACTLR_DISMCYCINT_Pos*/) /*!< ACTLR: DISMCYCINT Mask */ /*@} end of group CMSIS_SCnotSCB */ /** \ingroup CMSIS_core_register \defgroup CMSIS_SysTick System Tick Timer (SysTick) \brief Type definitions for the System Timer Registers. @{ */ /** \brief Structure type to access the System Timer (SysTick). */ typedef struct { __IO uint32_t CTRL; /*!< Offset: 0x000 (R/W) SysTick Control and Status Register */ __IO uint32_t LOAD; /*!< Offset: 0x004 (R/W) SysTick Reload Value Register */ __IO uint32_t VAL; /*!< Offset: 0x008 (R/W) SysTick Current Value Register */ __I uint32_t CALIB; /*!< Offset: 0x00C (R/ ) SysTick Calibration Register */ } SysTick_Type; /* SysTick Control / Status Register Definitions */ #define SysTick_CTRL_COUNTFLAG_Pos 16 /*!< SysTick CTRL: COUNTFLAG Position */ #define SysTick_CTRL_COUNTFLAG_Msk (1UL << SysTick_CTRL_COUNTFLAG_Pos) /*!< SysTick CTRL: COUNTFLAG Mask */ #define SysTick_CTRL_CLKSOURCE_Pos 2 /*!< SysTick CTRL: CLKSOURCE Position */ #define SysTick_CTRL_CLKSOURCE_Msk (1UL << SysTick_CTRL_CLKSOURCE_Pos) /*!< SysTick CTRL: CLKSOURCE Mask */ #define SysTick_CTRL_TICKINT_Pos 1 /*!< SysTick CTRL: TICKINT Position */ #define SysTick_CTRL_TICKINT_Msk (1UL << SysTick_CTRL_TICKINT_Pos) /*!< SysTick CTRL: TICKINT Mask */ #define SysTick_CTRL_ENABLE_Pos 0 /*!< SysTick CTRL: ENABLE Position */ #define SysTick_CTRL_ENABLE_Msk (1UL /*<< SysTick_CTRL_ENABLE_Pos*/) /*!< SysTick CTRL: ENABLE Mask */ /* SysTick Reload Register Definitions */ #define SysTick_LOAD_RELOAD_Pos 0 /*!< SysTick LOAD: RELOAD Position */ #define SysTick_LOAD_RELOAD_Msk (0xFFFFFFUL /*<< SysTick_LOAD_RELOAD_Pos*/) /*!< SysTick LOAD: RELOAD Mask */ /* SysTick Current Register Definitions */ #define SysTick_VAL_CURRENT_Pos 0 /*!< SysTick VAL: CURRENT Position */ #define SysTick_VAL_CURRENT_Msk (0xFFFFFFUL /*<< SysTick_VAL_CURRENT_Pos*/) /*!< SysTick VAL: CURRENT Mask */ /* SysTick Calibration Register Definitions */ #define SysTick_CALIB_NOREF_Pos 31 /*!< SysTick CALIB: NOREF Position */ #define SysTick_CALIB_NOREF_Msk (1UL << SysTick_CALIB_NOREF_Pos) /*!< SysTick CALIB: NOREF Mask */ #define SysTick_CALIB_SKEW_Pos 30 /*!< SysTick CALIB: SKEW Position */ #define SysTick_CALIB_SKEW_Msk (1UL << SysTick_CALIB_SKEW_Pos) /*!< SysTick CALIB: SKEW Mask */ #define SysTick_CALIB_TENMS_Pos 0 /*!< SysTick CALIB: TENMS Position */ #define SysTick_CALIB_TENMS_Msk (0xFFFFFFUL /*<< SysTick_CALIB_TENMS_Pos*/) /*!< SysTick CALIB: TENMS Mask */ /*@} end of group CMSIS_SysTick */ /** \ingroup CMSIS_core_register \defgroup CMSIS_ITM Instrumentation Trace Macrocell (ITM) \brief Type definitions for the Instrumentation Trace Macrocell (ITM) @{ */ /** \brief Structure type to access the Instrumentation Trace Macrocell Register (ITM). */ typedef struct { __O union { __O uint8_t u8; /*!< Offset: 0x000 ( /W) ITM Stimulus Port 8-bit */ __O uint16_t u16; /*!< Offset: 0x000 ( /W) ITM Stimulus Port 16-bit */ __O uint32_t u32; /*!< Offset: 0x000 ( /W) ITM Stimulus Port 32-bit */ } PORT [32]; /*!< Offset: 0x000 ( /W) ITM Stimulus Port Registers */ uint32_t RESERVED0[864]; __IO uint32_t TER; /*!< Offset: 0xE00 (R/W) ITM Trace Enable Register */ uint32_t RESERVED1[15]; __IO uint32_t TPR; /*!< Offset: 0xE40 (R/W) ITM Trace Privilege Register */ uint32_t RESERVED2[15]; __IO uint32_t TCR; /*!< Offset: 0xE80 (R/W) ITM Trace Control Register */ uint32_t RESERVED3[29]; __O uint32_t IWR; /*!< Offset: 0xEF8 ( /W) ITM Integration Write Register */ __I uint32_t IRR; /*!< Offset: 0xEFC (R/ ) ITM Integration Read Register */ __IO uint32_t IMCR; /*!< Offset: 0xF00 (R/W) ITM Integration Mode Control Register */ uint32_t RESERVED4[43]; __O uint32_t LAR; /*!< Offset: 0xFB0 ( /W) ITM Lock Access Register */ __I uint32_t LSR; /*!< Offset: 0xFB4 (R/ ) ITM Lock Status Register */ uint32_t RESERVED5[6]; __I uint32_t PID4; /*!< Offset: 0xFD0 (R/ ) ITM Peripheral Identification Register #4 */ __I uint32_t PID5; /*!< Offset: 0xFD4 (R/ ) ITM Peripheral Identification Register #5 */ __I uint32_t PID6; /*!< Offset: 0xFD8 (R/ ) ITM Peripheral Identification Register #6 */ __I uint32_t PID7; /*!< Offset: 0xFDC (R/ ) ITM Peripheral Identification Register #7 */ __I uint32_t PID0; /*!< Offset: 0xFE0 (R/ ) ITM Peripheral Identification Register #0 */ __I uint32_t PID1; /*!< Offset: 0xFE4 (R/ ) ITM Peripheral Identification Register #1 */ __I uint32_t PID2; /*!< Offset: 0xFE8 (R/ ) ITM Peripheral Identification Register #2 */ __I uint32_t PID3; /*!< Offset: 0xFEC (R/ ) ITM Peripheral Identification Register #3 */ __I uint32_t CID0; /*!< Offset: 0xFF0 (R/ ) ITM Component Identification Register #0 */ __I uint32_t CID1; /*!< Offset: 0xFF4 (R/ ) ITM Component Identification Register #1 */ __I uint32_t CID2; /*!< Offset: 0xFF8 (R/ ) ITM Component Identification Register #2 */ __I uint32_t CID3; /*!< Offset: 0xFFC (R/ ) ITM Component Identification Register #3 */ } ITM_Type; /* ITM Trace Privilege Register Definitions */ #define ITM_TPR_PRIVMASK_Pos 0 /*!< ITM TPR: PRIVMASK Position */ #define ITM_TPR_PRIVMASK_Msk (0xFUL /*<< ITM_TPR_PRIVMASK_Pos*/) /*!< ITM TPR: PRIVMASK Mask */ /* ITM Trace Control Register Definitions */ #define ITM_TCR_BUSY_Pos 23 /*!< ITM TCR: BUSY Position */ #define ITM_TCR_BUSY_Msk (1UL << ITM_TCR_BUSY_Pos) /*!< ITM TCR: BUSY Mask */ #define ITM_TCR_TraceBusID_Pos 16 /*!< ITM TCR: ATBID Position */ #define ITM_TCR_TraceBusID_Msk (0x7FUL << ITM_TCR_TraceBusID_Pos) /*!< ITM TCR: ATBID Mask */ #define ITM_TCR_GTSFREQ_Pos 10 /*!< ITM TCR: Global timestamp frequency Position */ #define ITM_TCR_GTSFREQ_Msk (3UL << ITM_TCR_GTSFREQ_Pos) /*!< ITM TCR: Global timestamp frequency Mask */ #define ITM_TCR_TSPrescale_Pos 8 /*!< ITM TCR: TSPrescale Position */ #define ITM_TCR_TSPrescale_Msk (3UL << ITM_TCR_TSPrescale_Pos) /*!< ITM TCR: TSPrescale Mask */ #define ITM_TCR_SWOENA_Pos 4 /*!< ITM TCR: SWOENA Position */ #define ITM_TCR_SWOENA_Msk (1UL << ITM_TCR_SWOENA_Pos) /*!< ITM TCR: SWOENA Mask */ #define ITM_TCR_DWTENA_Pos 3 /*!< ITM TCR: DWTENA Position */ #define ITM_TCR_DWTENA_Msk (1UL << ITM_TCR_DWTENA_Pos) /*!< ITM TCR: DWTENA Mask */ #define ITM_TCR_SYNCENA_Pos 2 /*!< ITM TCR: SYNCENA Position */ #define ITM_TCR_SYNCENA_Msk (1UL << ITM_TCR_SYNCENA_Pos) /*!< ITM TCR: SYNCENA Mask */ #define ITM_TCR_TSENA_Pos 1 /*!< ITM TCR: TSENA Position */ #define ITM_TCR_TSENA_Msk (1UL << ITM_TCR_TSENA_Pos) /*!< ITM TCR: TSENA Mask */ #define ITM_TCR_ITMENA_Pos 0 /*!< ITM TCR: ITM Enable bit Position */ #define ITM_TCR_ITMENA_Msk (1UL /*<< ITM_TCR_ITMENA_Pos*/) /*!< ITM TCR: ITM Enable bit Mask */ /* ITM Integration Write Register Definitions */ #define ITM_IWR_ATVALIDM_Pos 0 /*!< ITM IWR: ATVALIDM Position */ #define ITM_IWR_ATVALIDM_Msk (1UL /*<< ITM_IWR_ATVALIDM_Pos*/) /*!< ITM IWR: ATVALIDM Mask */ /* ITM Integration Read Register Definitions */ #define ITM_IRR_ATREADYM_Pos 0 /*!< ITM IRR: ATREADYM Position */ #define ITM_IRR_ATREADYM_Msk (1UL /*<< ITM_IRR_ATREADYM_Pos*/) /*!< ITM IRR: ATREADYM Mask */ /* ITM Integration Mode Control Register Definitions */ #define ITM_IMCR_INTEGRATION_Pos 0 /*!< ITM IMCR: INTEGRATION Position */ #define ITM_IMCR_INTEGRATION_Msk (1UL /*<< ITM_IMCR_INTEGRATION_Pos*/) /*!< ITM IMCR: INTEGRATION Mask */ /* ITM Lock Status Register Definitions */ #define ITM_LSR_ByteAcc_Pos 2 /*!< ITM LSR: ByteAcc Position */ #define ITM_LSR_ByteAcc_Msk (1UL << ITM_LSR_ByteAcc_Pos) /*!< ITM LSR: ByteAcc Mask */ #define ITM_LSR_Access_Pos 1 /*!< ITM LSR: Access Position */ #define ITM_LSR_Access_Msk (1UL << ITM_LSR_Access_Pos) /*!< ITM LSR: Access Mask */ #define ITM_LSR_Present_Pos 0 /*!< ITM LSR: Present Position */ #define ITM_LSR_Present_Msk (1UL /*<< ITM_LSR_Present_Pos*/) /*!< ITM LSR: Present Mask */ /*@}*/ /* end of group CMSIS_ITM */ /** \ingroup CMSIS_core_register \defgroup CMSIS_DWT Data Watchpoint and Trace (DWT) \brief Type definitions for the Data Watchpoint and Trace (DWT) @{ */ /** \brief Structure type to access the Data Watchpoint and Trace Register (DWT). */ typedef struct { __IO uint32_t CTRL; /*!< Offset: 0x000 (R/W) Control Register */ __IO uint32_t CYCCNT; /*!< Offset: 0x004 (R/W) Cycle Count Register */ __IO uint32_t CPICNT; /*!< Offset: 0x008 (R/W) CPI Count Register */ __IO uint32_t EXCCNT; /*!< Offset: 0x00C (R/W) Exception Overhead Count Register */ __IO uint32_t SLEEPCNT; /*!< Offset: 0x010 (R/W) Sleep Count Register */ __IO uint32_t LSUCNT; /*!< Offset: 0x014 (R/W) LSU Count Register */ __IO uint32_t FOLDCNT; /*!< Offset: 0x018 (R/W) Folded-instruction Count Register */ __I uint32_t PCSR; /*!< Offset: 0x01C (R/ ) Program Counter Sample Register */ __IO uint32_t COMP0; /*!< Offset: 0x020 (R/W) Comparator Register 0 */ __IO uint32_t MASK0; /*!< Offset: 0x024 (R/W) Mask Register 0 */ __IO uint32_t FUNCTION0; /*!< Offset: 0x028 (R/W) Function Register 0 */ uint32_t RESERVED0[1]; __IO uint32_t COMP1; /*!< Offset: 0x030 (R/W) Comparator Register 1 */ __IO uint32_t MASK1; /*!< Offset: 0x034 (R/W) Mask Register 1 */ __IO uint32_t FUNCTION1; /*!< Offset: 0x038 (R/W) Function Register 1 */ uint32_t RESERVED1[1]; __IO uint32_t COMP2; /*!< Offset: 0x040 (R/W) Comparator Register 2 */ __IO uint32_t MASK2; /*!< Offset: 0x044 (R/W) Mask Register 2 */ __IO uint32_t FUNCTION2; /*!< Offset: 0x048 (R/W) Function Register 2 */ uint32_t RESERVED2[1]; __IO uint32_t COMP3; /*!< Offset: 0x050 (R/W) Comparator Register 3 */ __IO uint32_t MASK3; /*!< Offset: 0x054 (R/W) Mask Register 3 */ __IO uint32_t FUNCTION3; /*!< Offset: 0x058 (R/W) Function Register 3 */ } DWT_Type; /* DWT Control Register Definitions */ #define DWT_CTRL_NUMCOMP_Pos 28 /*!< DWT CTRL: NUMCOMP Position */ #define DWT_CTRL_NUMCOMP_Msk (0xFUL << DWT_CTRL_NUMCOMP_Pos) /*!< DWT CTRL: NUMCOMP Mask */ #define DWT_CTRL_NOTRCPKT_Pos 27 /*!< DWT CTRL: NOTRCPKT Position */ #define DWT_CTRL_NOTRCPKT_Msk (0x1UL << DWT_CTRL_NOTRCPKT_Pos) /*!< DWT CTRL: NOTRCPKT Mask */ #define DWT_CTRL_NOEXTTRIG_Pos 26 /*!< DWT CTRL: NOEXTTRIG Position */ #define DWT_CTRL_NOEXTTRIG_Msk (0x1UL << DWT_CTRL_NOEXTTRIG_Pos) /*!< DWT CTRL: NOEXTTRIG Mask */ #define DWT_CTRL_NOCYCCNT_Pos 25 /*!< DWT CTRL: NOCYCCNT Position */ #define DWT_CTRL_NOCYCCNT_Msk (0x1UL << DWT_CTRL_NOCYCCNT_Pos) /*!< DWT CTRL: NOCYCCNT Mask */ #define DWT_CTRL_NOPRFCNT_Pos 24 /*!< DWT CTRL: NOPRFCNT Position */ #define DWT_CTRL_NOPRFCNT_Msk (0x1UL << DWT_CTRL_NOPRFCNT_Pos) /*!< DWT CTRL: NOPRFCNT Mask */ #define DWT_CTRL_CYCEVTENA_Pos 22 /*!< DWT CTRL: CYCEVTENA Position */ #define DWT_CTRL_CYCEVTENA_Msk (0x1UL << DWT_CTRL_CYCEVTENA_Pos) /*!< DWT CTRL: CYCEVTENA Mask */ #define DWT_CTRL_FOLDEVTENA_Pos 21 /*!< DWT CTRL: FOLDEVTENA Position */ #define DWT_CTRL_FOLDEVTENA_Msk (0x1UL << DWT_CTRL_FOLDEVTENA_Pos) /*!< DWT CTRL: FOLDEVTENA Mask */ #define DWT_CTRL_LSUEVTENA_Pos 20 /*!< DWT CTRL: LSUEVTENA Position */ #define DWT_CTRL_LSUEVTENA_Msk (0x1UL << DWT_CTRL_LSUEVTENA_Pos) /*!< DWT CTRL: LSUEVTENA Mask */ #define DWT_CTRL_SLEEPEVTENA_Pos 19 /*!< DWT CTRL: SLEEPEVTENA Position */ #define DWT_CTRL_SLEEPEVTENA_Msk (0x1UL << DWT_CTRL_SLEEPEVTENA_Pos) /*!< DWT CTRL: SLEEPEVTENA Mask */ #define DWT_CTRL_EXCEVTENA_Pos 18 /*!< DWT CTRL: EXCEVTENA Position */ #define DWT_CTRL_EXCEVTENA_Msk (0x1UL << DWT_CTRL_EXCEVTENA_Pos) /*!< DWT CTRL: EXCEVTENA Mask */ #define DWT_CTRL_CPIEVTENA_Pos 17 /*!< DWT CTRL: CPIEVTENA Position */ #define DWT_CTRL_CPIEVTENA_Msk (0x1UL << DWT_CTRL_CPIEVTENA_Pos) /*!< DWT CTRL: CPIEVTENA Mask */ #define DWT_CTRL_EXCTRCENA_Pos 16 /*!< DWT CTRL: EXCTRCENA Position */ #define DWT_CTRL_EXCTRCENA_Msk (0x1UL << DWT_CTRL_EXCTRCENA_Pos) /*!< DWT CTRL: EXCTRCENA Mask */ #define DWT_CTRL_PCSAMPLENA_Pos 12 /*!< DWT CTRL: PCSAMPLENA Position */ #define DWT_CTRL_PCSAMPLENA_Msk (0x1UL << DWT_CTRL_PCSAMPLENA_Pos) /*!< DWT CTRL: PCSAMPLENA Mask */ #define DWT_CTRL_SYNCTAP_Pos 10 /*!< DWT CTRL: SYNCTAP Position */ #define DWT_CTRL_SYNCTAP_Msk (0x3UL << DWT_CTRL_SYNCTAP_Pos) /*!< DWT CTRL: SYNCTAP Mask */ #define DWT_CTRL_CYCTAP_Pos 9 /*!< DWT CTRL: CYCTAP Position */ #define DWT_CTRL_CYCTAP_Msk (0x1UL << DWT_CTRL_CYCTAP_Pos) /*!< DWT CTRL: CYCTAP Mask */ #define DWT_CTRL_POSTINIT_Pos 5 /*!< DWT CTRL: POSTINIT Position */ #define DWT_CTRL_POSTINIT_Msk (0xFUL << DWT_CTRL_POSTINIT_Pos) /*!< DWT CTRL: POSTINIT Mask */ #define DWT_CTRL_POSTPRESET_Pos 1 /*!< DWT CTRL: POSTPRESET Position */ #define DWT_CTRL_POSTPRESET_Msk (0xFUL << DWT_CTRL_POSTPRESET_Pos) /*!< DWT CTRL: POSTPRESET Mask */ #define DWT_CTRL_CYCCNTENA_Pos 0 /*!< DWT CTRL: CYCCNTENA Position */ #define DWT_CTRL_CYCCNTENA_Msk (0x1UL /*<< DWT_CTRL_CYCCNTENA_Pos*/) /*!< DWT CTRL: CYCCNTENA Mask */ /* DWT CPI Count Register Definitions */ #define DWT_CPICNT_CPICNT_Pos 0 /*!< DWT CPICNT: CPICNT Position */ #define DWT_CPICNT_CPICNT_Msk (0xFFUL /*<< DWT_CPICNT_CPICNT_Pos*/) /*!< DWT CPICNT: CPICNT Mask */ /* DWT Exception Overhead Count Register Definitions */ #define DWT_EXCCNT_EXCCNT_Pos 0 /*!< DWT EXCCNT: EXCCNT Position */ #define DWT_EXCCNT_EXCCNT_Msk (0xFFUL /*<< DWT_EXCCNT_EXCCNT_Pos*/) /*!< DWT EXCCNT: EXCCNT Mask */ /* DWT Sleep Count Register Definitions */ #define DWT_SLEEPCNT_SLEEPCNT_Pos 0 /*!< DWT SLEEPCNT: SLEEPCNT Position */ #define DWT_SLEEPCNT_SLEEPCNT_Msk (0xFFUL /*<< DWT_SLEEPCNT_SLEEPCNT_Pos*/) /*!< DWT SLEEPCNT: SLEEPCNT Mask */ /* DWT LSU Count Register Definitions */ #define DWT_LSUCNT_LSUCNT_Pos 0 /*!< DWT LSUCNT: LSUCNT Position */ #define DWT_LSUCNT_LSUCNT_Msk (0xFFUL /*<< DWT_LSUCNT_LSUCNT_Pos*/) /*!< DWT LSUCNT: LSUCNT Mask */ /* DWT Folded-instruction Count Register Definitions */ #define DWT_FOLDCNT_FOLDCNT_Pos 0 /*!< DWT FOLDCNT: FOLDCNT Position */ #define DWT_FOLDCNT_FOLDCNT_Msk (0xFFUL /*<< DWT_FOLDCNT_FOLDCNT_Pos*/) /*!< DWT FOLDCNT: FOLDCNT Mask */ /* DWT Comparator Mask Register Definitions */ #define DWT_MASK_MASK_Pos 0 /*!< DWT MASK: MASK Position */ #define DWT_MASK_MASK_Msk (0x1FUL /*<< DWT_MASK_MASK_Pos*/) /*!< DWT MASK: MASK Mask */ /* DWT Comparator Function Register Definitions */ #define DWT_FUNCTION_MATCHED_Pos 24 /*!< DWT FUNCTION: MATCHED Position */ #define DWT_FUNCTION_MATCHED_Msk (0x1UL << DWT_FUNCTION_MATCHED_Pos) /*!< DWT FUNCTION: MATCHED Mask */ #define DWT_FUNCTION_DATAVADDR1_Pos 16 /*!< DWT FUNCTION: DATAVADDR1 Position */ #define DWT_FUNCTION_DATAVADDR1_Msk (0xFUL << DWT_FUNCTION_DATAVADDR1_Pos) /*!< DWT FUNCTION: DATAVADDR1 Mask */ #define DWT_FUNCTION_DATAVADDR0_Pos 12 /*!< DWT FUNCTION: DATAVADDR0 Position */ #define DWT_FUNCTION_DATAVADDR0_Msk (0xFUL << DWT_FUNCTION_DATAVADDR0_Pos) /*!< DWT FUNCTION: DATAVADDR0 Mask */ #define DWT_FUNCTION_DATAVSIZE_Pos 10 /*!< DWT FUNCTION: DATAVSIZE Position */ #define DWT_FUNCTION_DATAVSIZE_Msk (0x3UL << DWT_FUNCTION_DATAVSIZE_Pos) /*!< DWT FUNCTION: DATAVSIZE Mask */ #define DWT_FUNCTION_LNK1ENA_Pos 9 /*!< DWT FUNCTION: LNK1ENA Position */ #define DWT_FUNCTION_LNK1ENA_Msk (0x1UL << DWT_FUNCTION_LNK1ENA_Pos) /*!< DWT FUNCTION: LNK1ENA Mask */ #define DWT_FUNCTION_DATAVMATCH_Pos 8 /*!< DWT FUNCTION: DATAVMATCH Position */ #define DWT_FUNCTION_DATAVMATCH_Msk (0x1UL << DWT_FUNCTION_DATAVMATCH_Pos) /*!< DWT FUNCTION: DATAVMATCH Mask */ #define DWT_FUNCTION_CYCMATCH_Pos 7 /*!< DWT FUNCTION: CYCMATCH Position */ #define DWT_FUNCTION_CYCMATCH_Msk (0x1UL << DWT_FUNCTION_CYCMATCH_Pos) /*!< DWT FUNCTION: CYCMATCH Mask */ #define DWT_FUNCTION_EMITRANGE_Pos 5 /*!< DWT FUNCTION: EMITRANGE Position */ #define DWT_FUNCTION_EMITRANGE_Msk (0x1UL << DWT_FUNCTION_EMITRANGE_Pos) /*!< DWT FUNCTION: EMITRANGE Mask */ #define DWT_FUNCTION_FUNCTION_Pos 0 /*!< DWT FUNCTION: FUNCTION Position */ #define DWT_FUNCTION_FUNCTION_Msk (0xFUL /*<< DWT_FUNCTION_FUNCTION_Pos*/) /*!< DWT FUNCTION: FUNCTION Mask */ /*@}*/ /* end of group CMSIS_DWT */ /** \ingroup CMSIS_core_register \defgroup CMSIS_TPI Trace Port Interface (TPI) \brief Type definitions for the Trace Port Interface (TPI) @{ */ /** \brief Structure type to access the Trace Port Interface Register (TPI). */ typedef struct { __IO uint32_t SSPSR; /*!< Offset: 0x000 (R/ ) Supported Parallel Port Size Register */ __IO uint32_t CSPSR; /*!< Offset: 0x004 (R/W) Current Parallel Port Size Register */ uint32_t RESERVED0[2]; __IO uint32_t ACPR; /*!< Offset: 0x010 (R/W) Asynchronous Clock Prescaler Register */ uint32_t RESERVED1[55]; __IO uint32_t SPPR; /*!< Offset: 0x0F0 (R/W) Selected Pin Protocol Register */ uint32_t RESERVED2[131]; __I uint32_t FFSR; /*!< Offset: 0x300 (R/ ) Formatter and Flush Status Register */ __IO uint32_t FFCR; /*!< Offset: 0x304 (R/W) Formatter and Flush Control Register */ __I uint32_t FSCR; /*!< Offset: 0x308 (R/ ) Formatter Synchronization Counter Register */ uint32_t RESERVED3[759]; __I uint32_t TRIGGER; /*!< Offset: 0xEE8 (R/ ) TRIGGER */ __I uint32_t FIFO0; /*!< Offset: 0xEEC (R/ ) Integration ETM Data */ __I uint32_t ITATBCTR2; /*!< Offset: 0xEF0 (R/ ) ITATBCTR2 */ uint32_t RESERVED4[1]; __I uint32_t ITATBCTR0; /*!< Offset: 0xEF8 (R/ ) ITATBCTR0 */ __I uint32_t FIFO1; /*!< Offset: 0xEFC (R/ ) Integration ITM Data */ __IO uint32_t ITCTRL; /*!< Offset: 0xF00 (R/W) Integration Mode Control */ uint32_t RESERVED5[39]; __IO uint32_t CLAIMSET; /*!< Offset: 0xFA0 (R/W) Claim tag set */ __IO uint32_t CLAIMCLR; /*!< Offset: 0xFA4 (R/W) Claim tag clear */ uint32_t RESERVED7[8]; __I uint32_t DEVID; /*!< Offset: 0xFC8 (R/ ) TPIU_DEVID */ __I uint32_t DEVTYPE; /*!< Offset: 0xFCC (R/ ) TPIU_DEVTYPE */ } TPI_Type; /* TPI Asynchronous Clock Prescaler Register Definitions */ #define TPI_ACPR_PRESCALER_Pos 0 /*!< TPI ACPR: PRESCALER Position */ #define TPI_ACPR_PRESCALER_Msk (0x1FFFUL /*<< TPI_ACPR_PRESCALER_Pos*/) /*!< TPI ACPR: PRESCALER Mask */ /* TPI Selected Pin Protocol Register Definitions */ #define TPI_SPPR_TXMODE_Pos 0 /*!< TPI SPPR: TXMODE Position */ #define TPI_SPPR_TXMODE_Msk (0x3UL /*<< TPI_SPPR_TXMODE_Pos*/) /*!< TPI SPPR: TXMODE Mask */ /* TPI Formatter and Flush Status Register Definitions */ #define TPI_FFSR_FtNonStop_Pos 3 /*!< TPI FFSR: FtNonStop Position */ #define TPI_FFSR_FtNonStop_Msk (0x1UL << TPI_FFSR_FtNonStop_Pos) /*!< TPI FFSR: FtNonStop Mask */ #define TPI_FFSR_TCPresent_Pos 2 /*!< TPI FFSR: TCPresent Position */ #define TPI_FFSR_TCPresent_Msk (0x1UL << TPI_FFSR_TCPresent_Pos) /*!< TPI FFSR: TCPresent Mask */ #define TPI_FFSR_FtStopped_Pos 1 /*!< TPI FFSR: FtStopped Position */ #define TPI_FFSR_FtStopped_Msk (0x1UL << TPI_FFSR_FtStopped_Pos) /*!< TPI FFSR: FtStopped Mask */ #define TPI_FFSR_FlInProg_Pos 0 /*!< TPI FFSR: FlInProg Position */ #define TPI_FFSR_FlInProg_Msk (0x1UL /*<< TPI_FFSR_FlInProg_Pos*/) /*!< TPI FFSR: FlInProg Mask */ /* TPI Formatter and Flush Control Register Definitions */ #define TPI_FFCR_TrigIn_Pos 8 /*!< TPI FFCR: TrigIn Position */ #define TPI_FFCR_TrigIn_Msk (0x1UL << TPI_FFCR_TrigIn_Pos) /*!< TPI FFCR: TrigIn Mask */ #define TPI_FFCR_EnFCont_Pos 1 /*!< TPI FFCR: EnFCont Position */ #define TPI_FFCR_EnFCont_Msk (0x1UL << TPI_FFCR_EnFCont_Pos) /*!< TPI FFCR: EnFCont Mask */ /* TPI TRIGGER Register Definitions */ #define TPI_TRIGGER_TRIGGER_Pos 0 /*!< TPI TRIGGER: TRIGGER Position */ #define TPI_TRIGGER_TRIGGER_Msk (0x1UL /*<< TPI_TRIGGER_TRIGGER_Pos*/) /*!< TPI TRIGGER: TRIGGER Mask */ /* TPI Integration ETM Data Register Definitions (FIFO0) */ #define TPI_FIFO0_ITM_ATVALID_Pos 29 /*!< TPI FIFO0: ITM_ATVALID Position */ #define TPI_FIFO0_ITM_ATVALID_Msk (0x3UL << TPI_FIFO0_ITM_ATVALID_Pos) /*!< TPI FIFO0: ITM_ATVALID Mask */ #define TPI_FIFO0_ITM_bytecount_Pos 27 /*!< TPI FIFO0: ITM_bytecount Position */ #define TPI_FIFO0_ITM_bytecount_Msk (0x3UL << TPI_FIFO0_ITM_bytecount_Pos) /*!< TPI FIFO0: ITM_bytecount Mask */ #define TPI_FIFO0_ETM_ATVALID_Pos 26 /*!< TPI FIFO0: ETM_ATVALID Position */ #define TPI_FIFO0_ETM_ATVALID_Msk (0x3UL << TPI_FIFO0_ETM_ATVALID_Pos) /*!< TPI FIFO0: ETM_ATVALID Mask */ #define TPI_FIFO0_ETM_bytecount_Pos 24 /*!< TPI FIFO0: ETM_bytecount Position */ #define TPI_FIFO0_ETM_bytecount_Msk (0x3UL << TPI_FIFO0_ETM_bytecount_Pos) /*!< TPI FIFO0: ETM_bytecount Mask */ #define TPI_FIFO0_ETM2_Pos 16 /*!< TPI FIFO0: ETM2 Position */ #define TPI_FIFO0_ETM2_Msk (0xFFUL << TPI_FIFO0_ETM2_Pos) /*!< TPI FIFO0: ETM2 Mask */ #define TPI_FIFO0_ETM1_Pos 8 /*!< TPI FIFO0: ETM1 Position */ #define TPI_FIFO0_ETM1_Msk (0xFFUL << TPI_FIFO0_ETM1_Pos) /*!< TPI FIFO0: ETM1 Mask */ #define TPI_FIFO0_ETM0_Pos 0 /*!< TPI FIFO0: ETM0 Position */ #define TPI_FIFO0_ETM0_Msk (0xFFUL /*<< TPI_FIFO0_ETM0_Pos*/) /*!< TPI FIFO0: ETM0 Mask */ /* TPI ITATBCTR2 Register Definitions */ #define TPI_ITATBCTR2_ATREADY_Pos 0 /*!< TPI ITATBCTR2: ATREADY Position */ #define TPI_ITATBCTR2_ATREADY_Msk (0x1UL /*<< TPI_ITATBCTR2_ATREADY_Pos*/) /*!< TPI ITATBCTR2: ATREADY Mask */ /* TPI Integration ITM Data Register Definitions (FIFO1) */ #define TPI_FIFO1_ITM_ATVALID_Pos 29 /*!< TPI FIFO1: ITM_ATVALID Position */ #define TPI_FIFO1_ITM_ATVALID_Msk (0x3UL << TPI_FIFO1_ITM_ATVALID_Pos) /*!< TPI FIFO1: ITM_ATVALID Mask */ #define TPI_FIFO1_ITM_bytecount_Pos 27 /*!< TPI FIFO1: ITM_bytecount Position */ #define TPI_FIFO1_ITM_bytecount_Msk (0x3UL << TPI_FIFO1_ITM_bytecount_Pos) /*!< TPI FIFO1: ITM_bytecount Mask */ #define TPI_FIFO1_ETM_ATVALID_Pos 26 /*!< TPI FIFO1: ETM_ATVALID Position */ #define TPI_FIFO1_ETM_ATVALID_Msk (0x3UL << TPI_FIFO1_ETM_ATVALID_Pos) /*!< TPI FIFO1: ETM_ATVALID Mask */ #define TPI_FIFO1_ETM_bytecount_Pos 24 /*!< TPI FIFO1: ETM_bytecount Position */ #define TPI_FIFO1_ETM_bytecount_Msk (0x3UL << TPI_FIFO1_ETM_bytecount_Pos) /*!< TPI FIFO1: ETM_bytecount Mask */ #define TPI_FIFO1_ITM2_Pos 16 /*!< TPI FIFO1: ITM2 Position */ #define TPI_FIFO1_ITM2_Msk (0xFFUL << TPI_FIFO1_ITM2_Pos) /*!< TPI FIFO1: ITM2 Mask */ #define TPI_FIFO1_ITM1_Pos 8 /*!< TPI FIFO1: ITM1 Position */ #define TPI_FIFO1_ITM1_Msk (0xFFUL << TPI_FIFO1_ITM1_Pos) /*!< TPI FIFO1: ITM1 Mask */ #define TPI_FIFO1_ITM0_Pos 0 /*!< TPI FIFO1: ITM0 Position */ #define TPI_FIFO1_ITM0_Msk (0xFFUL /*<< TPI_FIFO1_ITM0_Pos*/) /*!< TPI FIFO1: ITM0 Mask */ /* TPI ITATBCTR0 Register Definitions */ #define TPI_ITATBCTR0_ATREADY_Pos 0 /*!< TPI ITATBCTR0: ATREADY Position */ #define TPI_ITATBCTR0_ATREADY_Msk (0x1UL /*<< TPI_ITATBCTR0_ATREADY_Pos*/) /*!< TPI ITATBCTR0: ATREADY Mask */ /* TPI Integration Mode Control Register Definitions */ #define TPI_ITCTRL_Mode_Pos 0 /*!< TPI ITCTRL: Mode Position */ #define TPI_ITCTRL_Mode_Msk (0x1UL /*<< TPI_ITCTRL_Mode_Pos*/) /*!< TPI ITCTRL: Mode Mask */ /* TPI DEVID Register Definitions */ #define TPI_DEVID_NRZVALID_Pos 11 /*!< TPI DEVID: NRZVALID Position */ #define TPI_DEVID_NRZVALID_Msk (0x1UL << TPI_DEVID_NRZVALID_Pos) /*!< TPI DEVID: NRZVALID Mask */ #define TPI_DEVID_MANCVALID_Pos 10 /*!< TPI DEVID: MANCVALID Position */ #define TPI_DEVID_MANCVALID_Msk (0x1UL << TPI_DEVID_MANCVALID_Pos) /*!< TPI DEVID: MANCVALID Mask */ #define TPI_DEVID_PTINVALID_Pos 9 /*!< TPI DEVID: PTINVALID Position */ #define TPI_DEVID_PTINVALID_Msk (0x1UL << TPI_DEVID_PTINVALID_Pos) /*!< TPI DEVID: PTINVALID Mask */ #define TPI_DEVID_MinBufSz_Pos 6 /*!< TPI DEVID: MinBufSz Position */ #define TPI_DEVID_MinBufSz_Msk (0x7UL << TPI_DEVID_MinBufSz_Pos) /*!< TPI DEVID: MinBufSz Mask */ #define TPI_DEVID_AsynClkIn_Pos 5 /*!< TPI DEVID: AsynClkIn Position */ #define TPI_DEVID_AsynClkIn_Msk (0x1UL << TPI_DEVID_AsynClkIn_Pos) /*!< TPI DEVID: AsynClkIn Mask */ #define TPI_DEVID_NrTraceInput_Pos 0 /*!< TPI DEVID: NrTraceInput Position */ #define TPI_DEVID_NrTraceInput_Msk (0x1FUL /*<< TPI_DEVID_NrTraceInput_Pos*/) /*!< TPI DEVID: NrTraceInput Mask */ /* TPI DEVTYPE Register Definitions */ #define TPI_DEVTYPE_MajorType_Pos 4 /*!< TPI DEVTYPE: MajorType Position */ #define TPI_DEVTYPE_MajorType_Msk (0xFUL << TPI_DEVTYPE_MajorType_Pos) /*!< TPI DEVTYPE: MajorType Mask */ #define TPI_DEVTYPE_SubType_Pos 0 /*!< TPI DEVTYPE: SubType Position */ #define TPI_DEVTYPE_SubType_Msk (0xFUL /*<< TPI_DEVTYPE_SubType_Pos*/) /*!< TPI DEVTYPE: SubType Mask */ /*@}*/ /* end of group CMSIS_TPI */ #if (__MPU_PRESENT == 1) /** \ingroup CMSIS_core_register \defgroup CMSIS_MPU Memory Protection Unit (MPU) \brief Type definitions for the Memory Protection Unit (MPU) @{ */ /** \brief Structure type to access the Memory Protection Unit (MPU). */ typedef struct { __I uint32_t TYPE; /*!< Offset: 0x000 (R/ ) MPU Type Register */ __IO uint32_t CTRL; /*!< Offset: 0x004 (R/W) MPU Control Register */ __IO uint32_t RNR; /*!< Offset: 0x008 (R/W) MPU Region RNRber Register */ __IO uint32_t RBAR; /*!< Offset: 0x00C (R/W) MPU Region Base Address Register */ __IO uint32_t RASR; /*!< Offset: 0x010 (R/W) MPU Region Attribute and Size Register */ __IO uint32_t RBAR_A1; /*!< Offset: 0x014 (R/W) MPU Alias 1 Region Base Address Register */ __IO uint32_t RASR_A1; /*!< Offset: 0x018 (R/W) MPU Alias 1 Region Attribute and Size Register */ __IO uint32_t RBAR_A2; /*!< Offset: 0x01C (R/W) MPU Alias 2 Region Base Address Register */ __IO uint32_t RASR_A2; /*!< Offset: 0x020 (R/W) MPU Alias 2 Region Attribute and Size Register */ __IO uint32_t RBAR_A3; /*!< Offset: 0x024 (R/W) MPU Alias 3 Region Base Address Register */ __IO uint32_t RASR_A3; /*!< Offset: 0x028 (R/W) MPU Alias 3 Region Attribute and Size Register */ } MPU_Type; /* MPU Type Register */ #define MPU_TYPE_IREGION_Pos 16 /*!< MPU TYPE: IREGION Position */ #define MPU_TYPE_IREGION_Msk (0xFFUL << MPU_TYPE_IREGION_Pos) /*!< MPU TYPE: IREGION Mask */ #define MPU_TYPE_DREGION_Pos 8 /*!< MPU TYPE: DREGION Position */ #define MPU_TYPE_DREGION_Msk (0xFFUL << MPU_TYPE_DREGION_Pos) /*!< MPU TYPE: DREGION Mask */ #define MPU_TYPE_SEPARATE_Pos 0 /*!< MPU TYPE: SEPARATE Position */ #define MPU_TYPE_SEPARATE_Msk (1UL /*<< MPU_TYPE_SEPARATE_Pos*/) /*!< MPU TYPE: SEPARATE Mask */ /* MPU Control Register */ #define MPU_CTRL_PRIVDEFENA_Pos 2 /*!< MPU CTRL: PRIVDEFENA Position */ #define MPU_CTRL_PRIVDEFENA_Msk (1UL << MPU_CTRL_PRIVDEFENA_Pos) /*!< MPU CTRL: PRIVDEFENA Mask */ #define MPU_CTRL_HFNMIENA_Pos 1 /*!< MPU CTRL: HFNMIENA Position */ #define MPU_CTRL_HFNMIENA_Msk (1UL << MPU_CTRL_HFNMIENA_Pos) /*!< MPU CTRL: HFNMIENA Mask */ #define MPU_CTRL_ENABLE_Pos 0 /*!< MPU CTRL: ENABLE Position */ #define MPU_CTRL_ENABLE_Msk (1UL /*<< MPU_CTRL_ENABLE_Pos*/) /*!< MPU CTRL: ENABLE Mask */ /* MPU Region Number Register */ #define MPU_RNR_REGION_Pos 0 /*!< MPU RNR: REGION Position */ #define MPU_RNR_REGION_Msk (0xFFUL /*<< MPU_RNR_REGION_Pos*/) /*!< MPU RNR: REGION Mask */ /* MPU Region Base Address Register */ #define MPU_RBAR_ADDR_Pos 5 /*!< MPU RBAR: ADDR Position */ #define MPU_RBAR_ADDR_Msk (0x7FFFFFFUL << MPU_RBAR_ADDR_Pos) /*!< MPU RBAR: ADDR Mask */ #define MPU_RBAR_VALID_Pos 4 /*!< MPU RBAR: VALID Position */ #define MPU_RBAR_VALID_Msk (1UL << MPU_RBAR_VALID_Pos) /*!< MPU RBAR: VALID Mask */ #define MPU_RBAR_REGION_Pos 0 /*!< MPU RBAR: REGION Position */ #define MPU_RBAR_REGION_Msk (0xFUL /*<< MPU_RBAR_REGION_Pos*/) /*!< MPU RBAR: REGION Mask */ /* MPU Region Attribute and Size Register */ #define MPU_RASR_ATTRS_Pos 16 /*!< MPU RASR: MPU Region Attribute field Position */ #define MPU_RASR_ATTRS_Msk (0xFFFFUL << MPU_RASR_ATTRS_Pos) /*!< MPU RASR: MPU Region Attribute field Mask */ #define MPU_RASR_XN_Pos 28 /*!< MPU RASR: ATTRS.XN Position */ #define MPU_RASR_XN_Msk (1UL << MPU_RASR_XN_Pos) /*!< MPU RASR: ATTRS.XN Mask */ #define MPU_RASR_AP_Pos 24 /*!< MPU RASR: ATTRS.AP Position */ #define MPU_RASR_AP_Msk (0x7UL << MPU_RASR_AP_Pos) /*!< MPU RASR: ATTRS.AP Mask */ #define MPU_RASR_TEX_Pos 19 /*!< MPU RASR: ATTRS.TEX Position */ #define MPU_RASR_TEX_Msk (0x7UL << MPU_RASR_TEX_Pos) /*!< MPU RASR: ATTRS.TEX Mask */ #define MPU_RASR_S_Pos 18 /*!< MPU RASR: ATTRS.S Position */ #define MPU_RASR_S_Msk (1UL << MPU_RASR_S_Pos) /*!< MPU RASR: ATTRS.S Mask */ #define MPU_RASR_C_Pos 17 /*!< MPU RASR: ATTRS.C Position */ #define MPU_RASR_C_Msk (1UL << MPU_RASR_C_Pos) /*!< MPU RASR: ATTRS.C Mask */ #define MPU_RASR_B_Pos 16 /*!< MPU RASR: ATTRS.B Position */ #define MPU_RASR_B_Msk (1UL << MPU_RASR_B_Pos) /*!< MPU RASR: ATTRS.B Mask */ #define MPU_RASR_SRD_Pos 8 /*!< MPU RASR: Sub-Region Disable Position */ #define MPU_RASR_SRD_Msk (0xFFUL << MPU_RASR_SRD_Pos) /*!< MPU RASR: Sub-Region Disable Mask */ #define MPU_RASR_SIZE_Pos 1 /*!< MPU RASR: Region Size Field Position */ #define MPU_RASR_SIZE_Msk (0x1FUL << MPU_RASR_SIZE_Pos) /*!< MPU RASR: Region Size Field Mask */ #define MPU_RASR_ENABLE_Pos 0 /*!< MPU RASR: Region enable bit Position */ #define MPU_RASR_ENABLE_Msk (1UL /*<< MPU_RASR_ENABLE_Pos*/) /*!< MPU RASR: Region enable bit Disable Mask */ /*@} end of group CMSIS_MPU */ #endif #if (__FPU_PRESENT == 1) /** \ingroup CMSIS_core_register \defgroup CMSIS_FPU Floating Point Unit (FPU) \brief Type definitions for the Floating Point Unit (FPU) @{ */ /** \brief Structure type to access the Floating Point Unit (FPU). */ typedef struct { uint32_t RESERVED0[1]; __IO uint32_t FPCCR; /*!< Offset: 0x004 (R/W) Floating-Point Context Control Register */ __IO uint32_t FPCAR; /*!< Offset: 0x008 (R/W) Floating-Point Context Address Register */ __IO uint32_t FPDSCR; /*!< Offset: 0x00C (R/W) Floating-Point Default Status Control Register */ __I uint32_t MVFR0; /*!< Offset: 0x010 (R/ ) Media and FP Feature Register 0 */ __I uint32_t MVFR1; /*!< Offset: 0x014 (R/ ) Media and FP Feature Register 1 */ } FPU_Type; /* Floating-Point Context Control Register */ #define FPU_FPCCR_ASPEN_Pos 31 /*!< FPCCR: ASPEN bit Position */ #define FPU_FPCCR_ASPEN_Msk (1UL << FPU_FPCCR_ASPEN_Pos) /*!< FPCCR: ASPEN bit Mask */ #define FPU_FPCCR_LSPEN_Pos 30 /*!< FPCCR: LSPEN Position */ #define FPU_FPCCR_LSPEN_Msk (1UL << FPU_FPCCR_LSPEN_Pos) /*!< FPCCR: LSPEN bit Mask */ #define FPU_FPCCR_MONRDY_Pos 8 /*!< FPCCR: MONRDY Position */ #define FPU_FPCCR_MONRDY_Msk (1UL << FPU_FPCCR_MONRDY_Pos) /*!< FPCCR: MONRDY bit Mask */ #define FPU_FPCCR_BFRDY_Pos 6 /*!< FPCCR: BFRDY Position */ #define FPU_FPCCR_BFRDY_Msk (1UL << FPU_FPCCR_BFRDY_Pos) /*!< FPCCR: BFRDY bit Mask */ #define FPU_FPCCR_MMRDY_Pos 5 /*!< FPCCR: MMRDY Position */ #define FPU_FPCCR_MMRDY_Msk (1UL << FPU_FPCCR_MMRDY_Pos) /*!< FPCCR: MMRDY bit Mask */ #define FPU_FPCCR_HFRDY_Pos 4 /*!< FPCCR: HFRDY Position */ #define FPU_FPCCR_HFRDY_Msk (1UL << FPU_FPCCR_HFRDY_Pos) /*!< FPCCR: HFRDY bit Mask */ #define FPU_FPCCR_THREAD_Pos 3 /*!< FPCCR: processor mode bit Position */ #define FPU_FPCCR_THREAD_Msk (1UL << FPU_FPCCR_THREAD_Pos) /*!< FPCCR: processor mode active bit Mask */ #define FPU_FPCCR_USER_Pos 1 /*!< FPCCR: privilege level bit Position */ #define FPU_FPCCR_USER_Msk (1UL << FPU_FPCCR_USER_Pos) /*!< FPCCR: privilege level bit Mask */ #define FPU_FPCCR_LSPACT_Pos 0 /*!< FPCCR: Lazy state preservation active bit Position */ #define FPU_FPCCR_LSPACT_Msk (1UL /*<< FPU_FPCCR_LSPACT_Pos*/) /*!< FPCCR: Lazy state preservation active bit Mask */ /* Floating-Point Context Address Register */ #define FPU_FPCAR_ADDRESS_Pos 3 /*!< FPCAR: ADDRESS bit Position */ #define FPU_FPCAR_ADDRESS_Msk (0x1FFFFFFFUL << FPU_FPCAR_ADDRESS_Pos) /*!< FPCAR: ADDRESS bit Mask */ /* Floating-Point Default Status Control Register */ #define FPU_FPDSCR_AHP_Pos 26 /*!< FPDSCR: AHP bit Position */ #define FPU_FPDSCR_AHP_Msk (1UL << FPU_FPDSCR_AHP_Pos) /*!< FPDSCR: AHP bit Mask */ #define FPU_FPDSCR_DN_Pos 25 /*!< FPDSCR: DN bit Position */ #define FPU_FPDSCR_DN_Msk (1UL << FPU_FPDSCR_DN_Pos) /*!< FPDSCR: DN bit Mask */ #define FPU_FPDSCR_FZ_Pos 24 /*!< FPDSCR: FZ bit Position */ #define FPU_FPDSCR_FZ_Msk (1UL << FPU_FPDSCR_FZ_Pos) /*!< FPDSCR: FZ bit Mask */ #define FPU_FPDSCR_RMode_Pos 22 /*!< FPDSCR: RMode bit Position */ #define FPU_FPDSCR_RMode_Msk (3UL << FPU_FPDSCR_RMode_Pos) /*!< FPDSCR: RMode bit Mask */ /* Media and FP Feature Register 0 */ #define FPU_MVFR0_FP_rounding_modes_Pos 28 /*!< MVFR0: FP rounding modes bits Position */ #define FPU_MVFR0_FP_rounding_modes_Msk (0xFUL << FPU_MVFR0_FP_rounding_modes_Pos) /*!< MVFR0: FP rounding modes bits Mask */ #define FPU_MVFR0_Short_vectors_Pos 24 /*!< MVFR0: Short vectors bits Position */ #define FPU_MVFR0_Short_vectors_Msk (0xFUL << FPU_MVFR0_Short_vectors_Pos) /*!< MVFR0: Short vectors bits Mask */ #define FPU_MVFR0_Square_root_Pos 20 /*!< MVFR0: Square root bits Position */ #define FPU_MVFR0_Square_root_Msk (0xFUL << FPU_MVFR0_Square_root_Pos) /*!< MVFR0: Square root bits Mask */ #define FPU_MVFR0_Divide_Pos 16 /*!< MVFR0: Divide bits Position */ #define FPU_MVFR0_Divide_Msk (0xFUL << FPU_MVFR0_Divide_Pos) /*!< MVFR0: Divide bits Mask */ #define FPU_MVFR0_FP_excep_trapping_Pos 12 /*!< MVFR0: FP exception trapping bits Position */ #define FPU_MVFR0_FP_excep_trapping_Msk (0xFUL << FPU_MVFR0_FP_excep_trapping_Pos) /*!< MVFR0: FP exception trapping bits Mask */ #define FPU_MVFR0_Double_precision_Pos 8 /*!< MVFR0: Double-precision bits Position */ #define FPU_MVFR0_Double_precision_Msk (0xFUL << FPU_MVFR0_Double_precision_Pos) /*!< MVFR0: Double-precision bits Mask */ #define FPU_MVFR0_Single_precision_Pos 4 /*!< MVFR0: Single-precision bits Position */ #define FPU_MVFR0_Single_precision_Msk (0xFUL << FPU_MVFR0_Single_precision_Pos) /*!< MVFR0: Single-precision bits Mask */ #define FPU_MVFR0_A_SIMD_registers_Pos 0 /*!< MVFR0: A_SIMD registers bits Position */ #define FPU_MVFR0_A_SIMD_registers_Msk (0xFUL /*<< FPU_MVFR0_A_SIMD_registers_Pos*/) /*!< MVFR0: A_SIMD registers bits Mask */ /* Media and FP Feature Register 1 */ #define FPU_MVFR1_FP_fused_MAC_Pos 28 /*!< MVFR1: FP fused MAC bits Position */ #define FPU_MVFR1_FP_fused_MAC_Msk (0xFUL << FPU_MVFR1_FP_fused_MAC_Pos) /*!< MVFR1: FP fused MAC bits Mask */ #define FPU_MVFR1_FP_HPFP_Pos 24 /*!< MVFR1: FP HPFP bits Position */ #define FPU_MVFR1_FP_HPFP_Msk (0xFUL << FPU_MVFR1_FP_HPFP_Pos) /*!< MVFR1: FP HPFP bits Mask */ #define FPU_MVFR1_D_NaN_mode_Pos 4 /*!< MVFR1: D_NaN mode bits Position */ #define FPU_MVFR1_D_NaN_mode_Msk (0xFUL << FPU_MVFR1_D_NaN_mode_Pos) /*!< MVFR1: D_NaN mode bits Mask */ #define FPU_MVFR1_FtZ_mode_Pos 0 /*!< MVFR1: FtZ mode bits Position */ #define FPU_MVFR1_FtZ_mode_Msk (0xFUL /*<< FPU_MVFR1_FtZ_mode_Pos*/) /*!< MVFR1: FtZ mode bits Mask */ /*@} end of group CMSIS_FPU */ #endif /** \ingroup CMSIS_core_register \defgroup CMSIS_CoreDebug Core Debug Registers (CoreDebug) \brief Type definitions for the Core Debug Registers @{ */ /** \brief Structure type to access the Core Debug Register (CoreDebug). */ typedef struct { __IO uint32_t DHCSR; /*!< Offset: 0x000 (R/W) Debug Halting Control and Status Register */ __O uint32_t DCRSR; /*!< Offset: 0x004 ( /W) Debug Core Register Selector Register */ __IO uint32_t DCRDR; /*!< Offset: 0x008 (R/W) Debug Core Register Data Register */ __IO uint32_t DEMCR; /*!< Offset: 0x00C (R/W) Debug Exception and Monitor Control Register */ } CoreDebug_Type; /* Debug Halting Control and Status Register */ #define CoreDebug_DHCSR_DBGKEY_Pos 16 /*!< CoreDebug DHCSR: DBGKEY Position */ #define CoreDebug_DHCSR_DBGKEY_Msk (0xFFFFUL << CoreDebug_DHCSR_DBGKEY_Pos) /*!< CoreDebug DHCSR: DBGKEY Mask */ #define CoreDebug_DHCSR_S_RESET_ST_Pos 25 /*!< CoreDebug DHCSR: S_RESET_ST Position */ #define CoreDebug_DHCSR_S_RESET_ST_Msk (1UL << CoreDebug_DHCSR_S_RESET_ST_Pos) /*!< CoreDebug DHCSR: S_RESET_ST Mask */ #define CoreDebug_DHCSR_S_RETIRE_ST_Pos 24 /*!< CoreDebug DHCSR: S_RETIRE_ST Position */ #define CoreDebug_DHCSR_S_RETIRE_ST_Msk (1UL << CoreDebug_DHCSR_S_RETIRE_ST_Pos) /*!< CoreDebug DHCSR: S_RETIRE_ST Mask */ #define CoreDebug_DHCSR_S_LOCKUP_Pos 19 /*!< CoreDebug DHCSR: S_LOCKUP Position */ #define CoreDebug_DHCSR_S_LOCKUP_Msk (1UL << CoreDebug_DHCSR_S_LOCKUP_Pos) /*!< CoreDebug DHCSR: S_LOCKUP Mask */ #define CoreDebug_DHCSR_S_SLEEP_Pos 18 /*!< CoreDebug DHCSR: S_SLEEP Position */ #define CoreDebug_DHCSR_S_SLEEP_Msk (1UL << CoreDebug_DHCSR_S_SLEEP_Pos) /*!< CoreDebug DHCSR: S_SLEEP Mask */ #define CoreDebug_DHCSR_S_HALT_Pos 17 /*!< CoreDebug DHCSR: S_HALT Position */ #define CoreDebug_DHCSR_S_HALT_Msk (1UL << CoreDebug_DHCSR_S_HALT_Pos) /*!< CoreDebug DHCSR: S_HALT Mask */ #define CoreDebug_DHCSR_S_REGRDY_Pos 16 /*!< CoreDebug DHCSR: S_REGRDY Position */ #define CoreDebug_DHCSR_S_REGRDY_Msk (1UL << CoreDebug_DHCSR_S_REGRDY_Pos) /*!< CoreDebug DHCSR: S_REGRDY Mask */ #define CoreDebug_DHCSR_C_SNAPSTALL_Pos 5 /*!< CoreDebug DHCSR: C_SNAPSTALL Position */ #define CoreDebug_DHCSR_C_SNAPSTALL_Msk (1UL << CoreDebug_DHCSR_C_SNAPSTALL_Pos) /*!< CoreDebug DHCSR: C_SNAPSTALL Mask */ #define CoreDebug_DHCSR_C_MASKINTS_Pos 3 /*!< CoreDebug DHCSR: C_MASKINTS Position */ #define CoreDebug_DHCSR_C_MASKINTS_Msk (1UL << CoreDebug_DHCSR_C_MASKINTS_Pos) /*!< CoreDebug DHCSR: C_MASKINTS Mask */ #define CoreDebug_DHCSR_C_STEP_Pos 2 /*!< CoreDebug DHCSR: C_STEP Position */ #define CoreDebug_DHCSR_C_STEP_Msk (1UL << CoreDebug_DHCSR_C_STEP_Pos) /*!< CoreDebug DHCSR: C_STEP Mask */ #define CoreDebug_DHCSR_C_HALT_Pos 1 /*!< CoreDebug DHCSR: C_HALT Position */ #define CoreDebug_DHCSR_C_HALT_Msk (1UL << CoreDebug_DHCSR_C_HALT_Pos) /*!< CoreDebug DHCSR: C_HALT Mask */ #define CoreDebug_DHCSR_C_DEBUGEN_Pos 0 /*!< CoreDebug DHCSR: C_DEBUGEN Position */ #define CoreDebug_DHCSR_C_DEBUGEN_Msk (1UL /*<< CoreDebug_DHCSR_C_DEBUGEN_Pos*/) /*!< CoreDebug DHCSR: C_DEBUGEN Mask */ /* Debug Core Register Selector Register */ #define CoreDebug_DCRSR_REGWnR_Pos 16 /*!< CoreDebug DCRSR: REGWnR Position */ #define CoreDebug_DCRSR_REGWnR_Msk (1UL << CoreDebug_DCRSR_REGWnR_Pos) /*!< CoreDebug DCRSR: REGWnR Mask */ #define CoreDebug_DCRSR_REGSEL_Pos 0 /*!< CoreDebug DCRSR: REGSEL Position */ #define CoreDebug_DCRSR_REGSEL_Msk (0x1FUL /*<< CoreDebug_DCRSR_REGSEL_Pos*/) /*!< CoreDebug DCRSR: REGSEL Mask */ /* Debug Exception and Monitor Control Register */ #define CoreDebug_DEMCR_TRCENA_Pos 24 /*!< CoreDebug DEMCR: TRCENA Position */ #define CoreDebug_DEMCR_TRCENA_Msk (1UL << CoreDebug_DEMCR_TRCENA_Pos) /*!< CoreDebug DEMCR: TRCENA Mask */ #define CoreDebug_DEMCR_MON_REQ_Pos 19 /*!< CoreDebug DEMCR: MON_REQ Position */ #define CoreDebug_DEMCR_MON_REQ_Msk (1UL << CoreDebug_DEMCR_MON_REQ_Pos) /*!< CoreDebug DEMCR: MON_REQ Mask */ #define CoreDebug_DEMCR_MON_STEP_Pos 18 /*!< CoreDebug DEMCR: MON_STEP Position */ #define CoreDebug_DEMCR_MON_STEP_Msk (1UL << CoreDebug_DEMCR_MON_STEP_Pos) /*!< CoreDebug DEMCR: MON_STEP Mask */ #define CoreDebug_DEMCR_MON_PEND_Pos 17 /*!< CoreDebug DEMCR: MON_PEND Position */ #define CoreDebug_DEMCR_MON_PEND_Msk (1UL << CoreDebug_DEMCR_MON_PEND_Pos) /*!< CoreDebug DEMCR: MON_PEND Mask */ #define CoreDebug_DEMCR_MON_EN_Pos 16 /*!< CoreDebug DEMCR: MON_EN Position */ #define CoreDebug_DEMCR_MON_EN_Msk (1UL << CoreDebug_DEMCR_MON_EN_Pos) /*!< CoreDebug DEMCR: MON_EN Mask */ #define CoreDebug_DEMCR_VC_HARDERR_Pos 10 /*!< CoreDebug DEMCR: VC_HARDERR Position */ #define CoreDebug_DEMCR_VC_HARDERR_Msk (1UL << CoreDebug_DEMCR_VC_HARDERR_Pos) /*!< CoreDebug DEMCR: VC_HARDERR Mask */ #define CoreDebug_DEMCR_VC_INTERR_Pos 9 /*!< CoreDebug DEMCR: VC_INTERR Position */ #define CoreDebug_DEMCR_VC_INTERR_Msk (1UL << CoreDebug_DEMCR_VC_INTERR_Pos) /*!< CoreDebug DEMCR: VC_INTERR Mask */ #define CoreDebug_DEMCR_VC_BUSERR_Pos 8 /*!< CoreDebug DEMCR: VC_BUSERR Position */ #define CoreDebug_DEMCR_VC_BUSERR_Msk (1UL << CoreDebug_DEMCR_VC_BUSERR_Pos) /*!< CoreDebug DEMCR: VC_BUSERR Mask */ #define CoreDebug_DEMCR_VC_STATERR_Pos 7 /*!< CoreDebug DEMCR: VC_STATERR Position */ #define CoreDebug_DEMCR_VC_STATERR_Msk (1UL << CoreDebug_DEMCR_VC_STATERR_Pos) /*!< CoreDebug DEMCR: VC_STATERR Mask */ #define CoreDebug_DEMCR_VC_CHKERR_Pos 6 /*!< CoreDebug DEMCR: VC_CHKERR Position */ #define CoreDebug_DEMCR_VC_CHKERR_Msk (1UL << CoreDebug_DEMCR_VC_CHKERR_Pos) /*!< CoreDebug DEMCR: VC_CHKERR Mask */ #define CoreDebug_DEMCR_VC_NOCPERR_Pos 5 /*!< CoreDebug DEMCR: VC_NOCPERR Position */ #define CoreDebug_DEMCR_VC_NOCPERR_Msk (1UL << CoreDebug_DEMCR_VC_NOCPERR_Pos) /*!< CoreDebug DEMCR: VC_NOCPERR Mask */ #define CoreDebug_DEMCR_VC_MMERR_Pos 4 /*!< CoreDebug DEMCR: VC_MMERR Position */ #define CoreDebug_DEMCR_VC_MMERR_Msk (1UL << CoreDebug_DEMCR_VC_MMERR_Pos) /*!< CoreDebug DEMCR: VC_MMERR Mask */ #define CoreDebug_DEMCR_VC_CORERESET_Pos 0 /*!< CoreDebug DEMCR: VC_CORERESET Position */ #define CoreDebug_DEMCR_VC_CORERESET_Msk (1UL /*<< CoreDebug_DEMCR_VC_CORERESET_Pos*/) /*!< CoreDebug DEMCR: VC_CORERESET Mask */ /*@} end of group CMSIS_CoreDebug */ /** \ingroup CMSIS_core_register \defgroup CMSIS_core_base Core Definitions \brief Definitions for base addresses, unions, and structures. @{ */ /* Memory mapping of Cortex-M4 Hardware */ #define SCS_BASE (0xE000E000UL) /*!< System Control Space Base Address */ #define ITM_BASE (0xE0000000UL) /*!< ITM Base Address */ #define DWT_BASE (0xE0001000UL) /*!< DWT Base Address */ #define TPI_BASE (0xE0040000UL) /*!< TPI Base Address */ #define CoreDebug_BASE (0xE000EDF0UL) /*!< Core Debug Base Address */ #define SysTick_BASE (SCS_BASE + 0x0010UL) /*!< SysTick Base Address */ #define NVIC_BASE (SCS_BASE + 0x0100UL) /*!< NVIC Base Address */ #define SCB_BASE (SCS_BASE + 0x0D00UL) /*!< System Control Block Base Address */ #define SCnSCB ((SCnSCB_Type *) SCS_BASE ) /*!< System control Register not in SCB */ #define SCB ((SCB_Type *) SCB_BASE ) /*!< SCB configuration struct */ #define SysTick ((SysTick_Type *) SysTick_BASE ) /*!< SysTick configuration struct */ #define NVIC ((NVIC_Type *) NVIC_BASE ) /*!< NVIC configuration struct */ #define ITM ((ITM_Type *) ITM_BASE ) /*!< ITM configuration struct */ #define DWT ((DWT_Type *) DWT_BASE ) /*!< DWT configuration struct */ #define TPI ((TPI_Type *) TPI_BASE ) /*!< TPI configuration struct */ #define CoreDebug ((CoreDebug_Type *) CoreDebug_BASE) /*!< Core Debug configuration struct */ #if (__MPU_PRESENT == 1) #define MPU_BASE (SCS_BASE + 0x0D90UL) /*!< Memory Protection Unit */ #define MPU ((MPU_Type *) MPU_BASE ) /*!< Memory Protection Unit */ #endif #if (__FPU_PRESENT == 1) #define FPU_BASE (SCS_BASE + 0x0F30UL) /*!< Floating Point Unit */ #define FPU ((FPU_Type *) FPU_BASE ) /*!< Floating Point Unit */ #endif /*@} */ /******************************************************************************* * Hardware Abstraction Layer Core Function Interface contains: - Core NVIC Functions - Core SysTick Functions - Core Debug Functions - Core Register Access Functions ******************************************************************************/ /** \defgroup CMSIS_Core_FunctionInterface Functions and Instructions Reference */ /* ########################## NVIC functions #################################### */ /** \ingroup CMSIS_Core_FunctionInterface \defgroup CMSIS_Core_NVICFunctions NVIC Functions \brief Functions that manage interrupts and exceptions via the NVIC. @{ */ /** \brief Set Priority Grouping The function sets the priority grouping field using the required unlock sequence. The parameter PriorityGroup is assigned to the field SCB->AIRCR [10:8] PRIGROUP field. Only values from 0..7 are used. In case of a conflict between priority grouping and available priority bits (__NVIC_PRIO_BITS), the smallest possible priority group is set. \param [in] PriorityGroup Priority grouping field. */ __STATIC_INLINE void NVIC_SetPriorityGrouping(uint32_t PriorityGroup) { uint32_t reg_value; uint32_t PriorityGroupTmp = (PriorityGroup & (uint32_t)0x07UL); /* only values 0..7 are used */ reg_value = SCB->AIRCR; /* read old register configuration */ reg_value &= ~((uint32_t)(SCB_AIRCR_VECTKEY_Msk | SCB_AIRCR_PRIGROUP_Msk)); /* clear bits to change */ reg_value = (reg_value | ((uint32_t)0x5FAUL << SCB_AIRCR_VECTKEY_Pos) | (PriorityGroupTmp << 8) ); /* Insert write key and priorty group */ SCB->AIRCR = reg_value; } /** \brief Get Priority Grouping The function reads the priority grouping field from the NVIC Interrupt Controller. \return Priority grouping field (SCB->AIRCR [10:8] PRIGROUP field). */ __STATIC_INLINE uint32_t NVIC_GetPriorityGrouping(void) { return ((uint32_t)((SCB->AIRCR & SCB_AIRCR_PRIGROUP_Msk) >> SCB_AIRCR_PRIGROUP_Pos)); } /** \brief Enable External Interrupt The function enables a device-specific interrupt in the NVIC interrupt controller. \param [in] IRQn External interrupt number. Value cannot be negative. */ __STATIC_INLINE void NVIC_EnableIRQ(IRQn_Type IRQn) { NVIC->ISER[(((uint32_t)(int32_t)IRQn) >> 5UL)] = (uint32_t)(1UL << (((uint32_t)(int32_t)IRQn) & 0x1FUL)); } /** \brief Disable External Interrupt The function disables a device-specific interrupt in the NVIC interrupt controller. \param [in] IRQn External interrupt number. Value cannot be negative. */ __STATIC_INLINE void NVIC_DisableIRQ(IRQn_Type IRQn) { NVIC->ICER[(((uint32_t)(int32_t)IRQn) >> 5UL)] = (uint32_t)(1UL << (((uint32_t)(int32_t)IRQn) & 0x1FUL)); } /** \brief Get Pending Interrupt The function reads the pending register in the NVIC and returns the pending bit for the specified interrupt. \param [in] IRQn Interrupt number. \return 0 Interrupt status is not pending. \return 1 Interrupt status is pending. */ __STATIC_INLINE uint32_t NVIC_GetPendingIRQ(IRQn_Type IRQn) { return((uint32_t)(((NVIC->ISPR[(((uint32_t)(int32_t)IRQn) >> 5UL)] & (1UL << (((uint32_t)(int32_t)IRQn) & 0x1FUL))) != 0UL) ? 1UL : 0UL)); } /** \brief Set Pending Interrupt The function sets the pending bit of an external interrupt. \param [in] IRQn Interrupt number. Value cannot be negative. */ __STATIC_INLINE void NVIC_SetPendingIRQ(IRQn_Type IRQn) { NVIC->ISPR[(((uint32_t)(int32_t)IRQn) >> 5UL)] = (uint32_t)(1UL << (((uint32_t)(int32_t)IRQn) & 0x1FUL)); } /** \brief Clear Pending Interrupt The function clears the pending bit of an external interrupt. \param [in] IRQn External interrupt number. Value cannot be negative. */ __STATIC_INLINE void NVIC_ClearPendingIRQ(IRQn_Type IRQn) { NVIC->ICPR[(((uint32_t)(int32_t)IRQn) >> 5UL)] = (uint32_t)(1UL << (((uint32_t)(int32_t)IRQn) & 0x1FUL)); } /** \brief Get Active Interrupt The function reads the active register in NVIC and returns the active bit. \param [in] IRQn Interrupt number. \return 0 Interrupt status is not active. \return 1 Interrupt status is active. */ __STATIC_INLINE uint32_t NVIC_GetActive(IRQn_Type IRQn) { return((uint32_t)(((NVIC->IABR[(((uint32_t)(int32_t)IRQn) >> 5UL)] & (1UL << (((uint32_t)(int32_t)IRQn) & 0x1FUL))) != 0UL) ? 1UL : 0UL)); } /** \brief Set Interrupt Priority The function sets the priority of an interrupt. \note The priority cannot be set for every core interrupt. \param [in] IRQn Interrupt number. \param [in] priority Priority to set. */ __STATIC_INLINE void NVIC_SetPriority(IRQn_Type IRQn, uint32_t priority) { if((int32_t)IRQn < 0) { SCB->SHP[(((uint32_t)(int32_t)IRQn) & 0xFUL)-4UL] = (uint8_t)((priority << (8 - __NVIC_PRIO_BITS)) & (uint32_t)0xFFUL); } else { NVIC->IP[((uint32_t)(int32_t)IRQn)] = (uint8_t)((priority << (8 - __NVIC_PRIO_BITS)) & (uint32_t)0xFFUL); } } /** \brief Get Interrupt Priority The function reads the priority of an interrupt. The interrupt number can be positive to specify an external (device specific) interrupt, or negative to specify an internal (core) interrupt. \param [in] IRQn Interrupt number. \return Interrupt Priority. Value is aligned automatically to the implemented priority bits of the microcontroller. */ __STATIC_INLINE uint32_t NVIC_GetPriority(IRQn_Type IRQn) { if((int32_t)IRQn < 0) { return(((uint32_t)SCB->SHP[(((uint32_t)(int32_t)IRQn) & 0xFUL)-4UL] >> (8 - __NVIC_PRIO_BITS))); } else { return(((uint32_t)NVIC->IP[((uint32_t)(int32_t)IRQn)] >> (8 - __NVIC_PRIO_BITS))); } } /** \brief Encode Priority The function encodes the priority for an interrupt with the given priority group, preemptive priority value, and subpriority value. In case of a conflict between priority grouping and available priority bits (__NVIC_PRIO_BITS), the smallest possible priority group is set. \param [in] PriorityGroup Used priority group. \param [in] PreemptPriority Preemptive priority value (starting from 0). \param [in] SubPriority Subpriority value (starting from 0). \return Encoded priority. Value can be used in the function \ref NVIC_SetPriority(). */ __STATIC_INLINE uint32_t NVIC_EncodePriority (uint32_t PriorityGroup, uint32_t PreemptPriority, uint32_t SubPriority) { uint32_t PriorityGroupTmp = (PriorityGroup & (uint32_t)0x07UL); /* only values 0..7 are used */ uint32_t PreemptPriorityBits; uint32_t SubPriorityBits; PreemptPriorityBits = ((7UL - PriorityGroupTmp) > (uint32_t)(__NVIC_PRIO_BITS)) ? (uint32_t)(__NVIC_PRIO_BITS) : (uint32_t)(7UL - PriorityGroupTmp); SubPriorityBits = ((PriorityGroupTmp + (uint32_t)(__NVIC_PRIO_BITS)) < (uint32_t)7UL) ? (uint32_t)0UL : (uint32_t)((PriorityGroupTmp - 7UL) + (uint32_t)(__NVIC_PRIO_BITS)); return ( ((PreemptPriority & (uint32_t)((1UL << (PreemptPriorityBits)) - 1UL)) << SubPriorityBits) | ((SubPriority & (uint32_t)((1UL << (SubPriorityBits )) - 1UL))) ); } /** \brief Decode Priority The function decodes an interrupt priority value with a given priority group to preemptive priority value and subpriority value. In case of a conflict between priority grouping and available priority bits (__NVIC_PRIO_BITS) the smallest possible priority group is set. \param [in] Priority Priority value, which can be retrieved with the function \ref NVIC_GetPriority(). \param [in] PriorityGroup Used priority group. \param [out] pPreemptPriority Preemptive priority value (starting from 0). \param [out] pSubPriority Subpriority value (starting from 0). */ __STATIC_INLINE void NVIC_DecodePriority (uint32_t Priority, uint32_t PriorityGroup, uint32_t* pPreemptPriority, uint32_t* pSubPriority) { uint32_t PriorityGroupTmp = (PriorityGroup & (uint32_t)0x07UL); /* only values 0..7 are used */ uint32_t PreemptPriorityBits; uint32_t SubPriorityBits; PreemptPriorityBits = ((7UL - PriorityGroupTmp) > (uint32_t)(__NVIC_PRIO_BITS)) ? (uint32_t)(__NVIC_PRIO_BITS) : (uint32_t)(7UL - PriorityGroupTmp); SubPriorityBits = ((PriorityGroupTmp + (uint32_t)(__NVIC_PRIO_BITS)) < (uint32_t)7UL) ? (uint32_t)0UL : (uint32_t)((PriorityGroupTmp - 7UL) + (uint32_t)(__NVIC_PRIO_BITS)); *pPreemptPriority = (Priority >> SubPriorityBits) & (uint32_t)((1UL << (PreemptPriorityBits)) - 1UL); *pSubPriority = (Priority ) & (uint32_t)((1UL << (SubPriorityBits )) - 1UL); } /** \brief System Reset The function initiates a system reset request to reset the MCU. */ __STATIC_INLINE void NVIC_SystemReset(void) { __DSB(); /* Ensure all outstanding memory accesses included buffered write are completed before reset */ SCB->AIRCR = (uint32_t)((0x5FAUL << SCB_AIRCR_VECTKEY_Pos) | (SCB->AIRCR & SCB_AIRCR_PRIGROUP_Msk) | SCB_AIRCR_SYSRESETREQ_Msk ); /* Keep priority group unchanged */ __DSB(); /* Ensure completion of memory access */ while(1) { __NOP(); } /* wait until reset */ } /*@} end of CMSIS_Core_NVICFunctions */ /* ################################## SysTick function ############################################ */ /** \ingroup CMSIS_Core_FunctionInterface \defgroup CMSIS_Core_SysTickFunctions SysTick Functions \brief Functions that configure the System. @{ */ #if (__Vendor_SysTickConfig == 0) /** \brief System Tick Configuration The function initializes the System Timer and its interrupt, and starts the System Tick Timer. Counter is in free running mode to generate periodic interrupts. \param [in] ticks Number of ticks between two interrupts. \return 0 Function succeeded. \return 1 Function failed. \note When the variable __Vendor_SysTickConfig is set to 1, then the function SysTick_Config is not included. In this case, the file device.h must contain a vendor-specific implementation of this function. */ __STATIC_INLINE uint32_t SysTick_Config(uint32_t ticks) { if ((ticks - 1UL) > SysTick_LOAD_RELOAD_Msk) { return (1UL); } /* Reload value impossible */ SysTick->LOAD = (uint32_t)(ticks - 1UL); /* set reload register */ NVIC_SetPriority (SysTick_IRQn, (1UL << __NVIC_PRIO_BITS) - 1UL); /* set Priority for Systick Interrupt */ SysTick->VAL = 0UL; /* Load the SysTick Counter Value */ SysTick->CTRL = SysTick_CTRL_CLKSOURCE_Msk | SysTick_CTRL_TICKINT_Msk | SysTick_CTRL_ENABLE_Msk; /* Enable SysTick IRQ and SysTick Timer */ return (0UL); /* Function successful */ } #endif /*@} end of CMSIS_Core_SysTickFunctions */ /* ##################################### Debug In/Output function ########################################### */ /** \ingroup CMSIS_Core_FunctionInterface \defgroup CMSIS_core_DebugFunctions ITM Functions \brief Functions that access the ITM debug interface. @{ */ extern volatile int32_t ITM_RxBuffer; /*!< External variable to receive characters. */ #define ITM_RXBUFFER_EMPTY 0x5AA55AA5 /*!< Value identifying \ref ITM_RxBuffer is ready for next character. */ /** \brief ITM Send Character The function transmits a character via the ITM channel 0, and \li Just returns when no debugger is connected that has booked the output. \li Is blocking when a debugger is connected, but the previous character sent has not been transmitted. \param [in] ch Character to transmit. \returns Character to transmit. */ __STATIC_INLINE uint32_t ITM_SendChar (uint32_t ch) { if (((ITM->TCR & ITM_TCR_ITMENA_Msk) != 0UL) && /* ITM enabled */ ((ITM->TER & 1UL ) != 0UL) ) /* ITM Port #0 enabled */ { while (ITM->PORT[0].u32 == 0UL) { __NOP(); } ITM->PORT[0].u8 = (uint8_t)ch; } return (ch); } /** \brief ITM Receive Character The function inputs a character via the external variable \ref ITM_RxBuffer. \return Received character. \return -1 No character pending. */ __STATIC_INLINE int32_t ITM_ReceiveChar (void) { int32_t ch = -1; /* no character available */ if (ITM_RxBuffer != ITM_RXBUFFER_EMPTY) { ch = ITM_RxBuffer; ITM_RxBuffer = ITM_RXBUFFER_EMPTY; /* ready for next character */ } return (ch); } /** \brief ITM Check Character The function checks whether a character is pending for reading in the variable \ref ITM_RxBuffer. \return 0 No character available. \return 1 Character available. */ __STATIC_INLINE int32_t ITM_CheckChar (void) { if (ITM_RxBuffer == ITM_RXBUFFER_EMPTY) { return (0); /* no character available */ } else { return (1); /* character available */ } } /*@} end of CMSIS_core_DebugFunctions */ #ifdef __cplusplus } #endif #endif /* __CORE_CM4_H_DEPENDANT */ #endif /* __CMSIS_GENERIC */ ================================================ FILE: Zelig/mbed/TARGET_NUCLEO_F411RE/core_cm4_simd.h ================================================ /**************************************************************************//** * @file core_cm4_simd.h * @brief CMSIS Cortex-M4 SIMD Header File * @version V3.20 * @date 25. February 2013 * * @note * ******************************************************************************/ /* Copyright (c) 2009 - 2013 ARM LIMITED All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: - Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. - Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. - Neither the name of ARM 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 COPYRIGHT HOLDERS AND CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. ---------------------------------------------------------------------------*/ #ifdef __cplusplus extern "C" { #endif #ifndef __CORE_CM4_SIMD_H #define __CORE_CM4_SIMD_H /******************************************************************************* * Hardware Abstraction Layer ******************************************************************************/ /* ################### Compiler specific Intrinsics ########################### */ /** \defgroup CMSIS_SIMD_intrinsics CMSIS SIMD Intrinsics Access to dedicated SIMD instructions @{ */ #if defined ( __CC_ARM ) /*------------------RealView Compiler -----------------*/ /* ARM armcc specific functions */ /*------ CM4 SIMD Intrinsics -----------------------------------------------------*/ #define __SADD8 __sadd8 #define __QADD8 __qadd8 #define __SHADD8 __shadd8 #define __UADD8 __uadd8 #define __UQADD8 __uqadd8 #define __UHADD8 __uhadd8 #define __SSUB8 __ssub8 #define __QSUB8 __qsub8 #define __SHSUB8 __shsub8 #define __USUB8 __usub8 #define __UQSUB8 __uqsub8 #define __UHSUB8 __uhsub8 #define __SADD16 __sadd16 #define __QADD16 __qadd16 #define __SHADD16 __shadd16 #define __UADD16 __uadd16 #define __UQADD16 __uqadd16 #define __UHADD16 __uhadd16 #define __SSUB16 __ssub16 #define __QSUB16 __qsub16 #define __SHSUB16 __shsub16 #define __USUB16 __usub16 #define __UQSUB16 __uqsub16 #define __UHSUB16 __uhsub16 #define __SASX __sasx #define __QASX __qasx #define __SHASX __shasx #define __UASX __uasx #define __UQASX __uqasx #define __UHASX __uhasx #define __SSAX __ssax #define __QSAX __qsax #define __SHSAX __shsax #define __USAX __usax #define __UQSAX __uqsax #define __UHSAX __uhsax #define __USAD8 __usad8 #define __USADA8 __usada8 #define __SSAT16 __ssat16 #define __USAT16 __usat16 #define __UXTB16 __uxtb16 #define __UXTAB16 __uxtab16 #define __SXTB16 __sxtb16 #define __SXTAB16 __sxtab16 #define __SMUAD __smuad #define __SMUADX __smuadx #define __SMLAD __smlad #define __SMLADX __smladx #define __SMLALD __smlald #define __SMLALDX __smlaldx #define __SMUSD __smusd #define __SMUSDX __smusdx #define __SMLSD __smlsd #define __SMLSDX __smlsdx #define __SMLSLD __smlsld #define __SMLSLDX __smlsldx #define __SEL __sel #define __QADD __qadd #define __QSUB __qsub #define __PKHBT(ARG1,ARG2,ARG3) ( ((((uint32_t)(ARG1)) ) & 0x0000FFFFUL) | \ ((((uint32_t)(ARG2)) << (ARG3)) & 0xFFFF0000UL) ) #define __PKHTB(ARG1,ARG2,ARG3) ( ((((uint32_t)(ARG1)) ) & 0xFFFF0000UL) | \ ((((uint32_t)(ARG2)) >> (ARG3)) & 0x0000FFFFUL) ) #define __SMMLA(ARG1,ARG2,ARG3) ( (int32_t)((((int64_t)(ARG1) * (ARG2)) + \ ((int64_t)(ARG3) << 32) ) >> 32)) /*-- End CM4 SIMD Intrinsics -----------------------------------------------------*/ #elif defined ( __ICCARM__ ) /*------------------ ICC Compiler -------------------*/ /* IAR iccarm specific functions */ /*------ CM4 SIMD Intrinsics -----------------------------------------------------*/ #include /*-- End CM4 SIMD Intrinsics -----------------------------------------------------*/ #elif defined ( __TMS470__ ) /*---------------- TI CCS Compiler ------------------*/ /* TI CCS specific functions */ /*------ CM4 SIMD Intrinsics -----------------------------------------------------*/ #include /*-- End CM4 SIMD Intrinsics -----------------------------------------------------*/ #elif defined ( __GNUC__ ) /*------------------ GNU Compiler ---------------------*/ /* GNU gcc specific functions */ /*------ CM4 SIMD Intrinsics -----------------------------------------------------*/ __attribute__( ( always_inline ) ) __STATIC_INLINE uint32_t __SADD8(uint32_t op1, uint32_t op2) { uint32_t result; __ASM volatile ("sadd8 %0, %1, %2" : "=r" (result) : "r" (op1), "r" (op2) ); return(result); } __attribute__( ( always_inline ) ) __STATIC_INLINE uint32_t __QADD8(uint32_t op1, uint32_t op2) { uint32_t result; __ASM volatile ("qadd8 %0, %1, %2" : "=r" (result) : "r" (op1), "r" (op2) ); return(result); } __attribute__( ( always_inline ) ) __STATIC_INLINE uint32_t __SHADD8(uint32_t op1, uint32_t op2) { uint32_t result; __ASM volatile ("shadd8 %0, %1, %2" : "=r" (result) : "r" (op1), "r" (op2) ); return(result); } __attribute__( ( always_inline ) ) __STATIC_INLINE uint32_t __UADD8(uint32_t op1, uint32_t op2) { uint32_t result; __ASM volatile ("uadd8 %0, %1, %2" : "=r" (result) : "r" (op1), "r" (op2) ); return(result); } __attribute__( ( always_inline ) ) __STATIC_INLINE uint32_t __UQADD8(uint32_t op1, uint32_t op2) { uint32_t result; __ASM volatile ("uqadd8 %0, %1, %2" : "=r" (result) : "r" (op1), "r" (op2) ); return(result); } __attribute__( ( always_inline ) ) __STATIC_INLINE uint32_t __UHADD8(uint32_t op1, uint32_t op2) { uint32_t result; __ASM volatile ("uhadd8 %0, %1, %2" : "=r" (result) : "r" (op1), "r" (op2) ); return(result); } __attribute__( ( always_inline ) ) __STATIC_INLINE uint32_t __SSUB8(uint32_t op1, uint32_t op2) { uint32_t result; __ASM volatile ("ssub8 %0, %1, %2" : "=r" (result) : "r" (op1), "r" (op2) ); return(result); } __attribute__( ( always_inline ) ) __STATIC_INLINE uint32_t __QSUB8(uint32_t op1, uint32_t op2) { uint32_t result; __ASM volatile ("qsub8 %0, %1, %2" : "=r" (result) : "r" (op1), "r" (op2) ); return(result); } __attribute__( ( always_inline ) ) __STATIC_INLINE uint32_t __SHSUB8(uint32_t op1, uint32_t op2) { uint32_t result; __ASM volatile ("shsub8 %0, %1, %2" : "=r" (result) : "r" (op1), "r" (op2) ); return(result); } __attribute__( ( always_inline ) ) __STATIC_INLINE uint32_t __USUB8(uint32_t op1, uint32_t op2) { uint32_t result; __ASM volatile ("usub8 %0, %1, %2" : "=r" (result) : "r" (op1), "r" (op2) ); return(result); } __attribute__( ( always_inline ) ) __STATIC_INLINE uint32_t __UQSUB8(uint32_t op1, uint32_t op2) { uint32_t result; __ASM volatile ("uqsub8 %0, %1, %2" : "=r" (result) : "r" (op1), "r" (op2) ); return(result); } __attribute__( ( always_inline ) ) __STATIC_INLINE uint32_t __UHSUB8(uint32_t op1, uint32_t op2) { uint32_t result; __ASM volatile ("uhsub8 %0, %1, %2" : "=r" (result) : "r" (op1), "r" (op2) ); return(result); } __attribute__( ( always_inline ) ) __STATIC_INLINE uint32_t __SADD16(uint32_t op1, uint32_t op2) { uint32_t result; __ASM volatile ("sadd16 %0, %1, %2" : "=r" (result) : "r" (op1), "r" (op2) ); return(result); } __attribute__( ( always_inline ) ) __STATIC_INLINE uint32_t __QADD16(uint32_t op1, uint32_t op2) { uint32_t result; __ASM volatile ("qadd16 %0, %1, %2" : "=r" (result) : "r" (op1), "r" (op2) ); return(result); } __attribute__( ( always_inline ) ) __STATIC_INLINE uint32_t __SHADD16(uint32_t op1, uint32_t op2) { uint32_t result; __ASM volatile ("shadd16 %0, %1, %2" : "=r" (result) : "r" (op1), "r" (op2) ); return(result); } __attribute__( ( always_inline ) ) __STATIC_INLINE uint32_t __UADD16(uint32_t op1, uint32_t op2) { uint32_t result; __ASM volatile ("uadd16 %0, %1, %2" : "=r" (result) : "r" (op1), "r" (op2) ); return(result); } __attribute__( ( always_inline ) ) __STATIC_INLINE uint32_t __UQADD16(uint32_t op1, uint32_t op2) { uint32_t result; __ASM volatile ("uqadd16 %0, %1, %2" : "=r" (result) : "r" (op1), "r" (op2) ); return(result); } __attribute__( ( always_inline ) ) __STATIC_INLINE uint32_t __UHADD16(uint32_t op1, uint32_t op2) { uint32_t result; __ASM volatile ("uhadd16 %0, %1, %2" : "=r" (result) : "r" (op1), "r" (op2) ); return(result); } __attribute__( ( always_inline ) ) __STATIC_INLINE uint32_t __SSUB16(uint32_t op1, uint32_t op2) { uint32_t result; __ASM volatile ("ssub16 %0, %1, %2" : "=r" (result) : "r" (op1), "r" (op2) ); return(result); } __attribute__( ( always_inline ) ) __STATIC_INLINE uint32_t __QSUB16(uint32_t op1, uint32_t op2) { uint32_t result; __ASM volatile ("qsub16 %0, %1, %2" : "=r" (result) : "r" (op1), "r" (op2) ); return(result); } __attribute__( ( always_inline ) ) __STATIC_INLINE uint32_t __SHSUB16(uint32_t op1, uint32_t op2) { uint32_t result; __ASM volatile ("shsub16 %0, %1, %2" : "=r" (result) : "r" (op1), "r" (op2) ); return(result); } __attribute__( ( always_inline ) ) __STATIC_INLINE uint32_t __USUB16(uint32_t op1, uint32_t op2) { uint32_t result; __ASM volatile ("usub16 %0, %1, %2" : "=r" (result) : "r" (op1), "r" (op2) ); return(result); } __attribute__( ( always_inline ) ) __STATIC_INLINE uint32_t __UQSUB16(uint32_t op1, uint32_t op2) { uint32_t result; __ASM volatile ("uqsub16 %0, %1, %2" : "=r" (result) : "r" (op1), "r" (op2) ); return(result); } __attribute__( ( always_inline ) ) __STATIC_INLINE uint32_t __UHSUB16(uint32_t op1, uint32_t op2) { uint32_t result; __ASM volatile ("uhsub16 %0, %1, %2" : "=r" (result) : "r" (op1), "r" (op2) ); return(result); } __attribute__( ( always_inline ) ) __STATIC_INLINE uint32_t __SASX(uint32_t op1, uint32_t op2) { uint32_t result; __ASM volatile ("sasx %0, %1, %2" : "=r" (result) : "r" (op1), "r" (op2) ); return(result); } __attribute__( ( always_inline ) ) __STATIC_INLINE uint32_t __QASX(uint32_t op1, uint32_t op2) { uint32_t result; __ASM volatile ("qasx %0, %1, %2" : "=r" (result) : "r" (op1), "r" (op2) ); return(result); } __attribute__( ( always_inline ) ) __STATIC_INLINE uint32_t __SHASX(uint32_t op1, uint32_t op2) { uint32_t result; __ASM volatile ("shasx %0, %1, %2" : "=r" (result) : "r" (op1), "r" (op2) ); return(result); } __attribute__( ( always_inline ) ) __STATIC_INLINE uint32_t __UASX(uint32_t op1, uint32_t op2) { uint32_t result; __ASM volatile ("uasx %0, %1, %2" : "=r" (result) : "r" (op1), "r" (op2) ); return(result); } __attribute__( ( always_inline ) ) __STATIC_INLINE uint32_t __UQASX(uint32_t op1, uint32_t op2) { uint32_t result; __ASM volatile ("uqasx %0, %1, %2" : "=r" (result) : "r" (op1), "r" (op2) ); return(result); } __attribute__( ( always_inline ) ) __STATIC_INLINE uint32_t __UHASX(uint32_t op1, uint32_t op2) { uint32_t result; __ASM volatile ("uhasx %0, %1, %2" : "=r" (result) : "r" (op1), "r" (op2) ); return(result); } __attribute__( ( always_inline ) ) __STATIC_INLINE uint32_t __SSAX(uint32_t op1, uint32_t op2) { uint32_t result; __ASM volatile ("ssax %0, %1, %2" : "=r" (result) : "r" (op1), "r" (op2) ); return(result); } __attribute__( ( always_inline ) ) __STATIC_INLINE uint32_t __QSAX(uint32_t op1, uint32_t op2) { uint32_t result; __ASM volatile ("qsax %0, %1, %2" : "=r" (result) : "r" (op1), "r" (op2) ); return(result); } __attribute__( ( always_inline ) ) __STATIC_INLINE uint32_t __SHSAX(uint32_t op1, uint32_t op2) { uint32_t result; __ASM volatile ("shsax %0, %1, %2" : "=r" (result) : "r" (op1), "r" (op2) ); return(result); } __attribute__( ( always_inline ) ) __STATIC_INLINE uint32_t __USAX(uint32_t op1, uint32_t op2) { uint32_t result; __ASM volatile ("usax %0, %1, %2" : "=r" (result) : "r" (op1), "r" (op2) ); return(result); } __attribute__( ( always_inline ) ) __STATIC_INLINE uint32_t __UQSAX(uint32_t op1, uint32_t op2) { uint32_t result; __ASM volatile ("uqsax %0, %1, %2" : "=r" (result) : "r" (op1), "r" (op2) ); return(result); } __attribute__( ( always_inline ) ) __STATIC_INLINE uint32_t __UHSAX(uint32_t op1, uint32_t op2) { uint32_t result; __ASM volatile ("uhsax %0, %1, %2" : "=r" (result) : "r" (op1), "r" (op2) ); return(result); } __attribute__( ( always_inline ) ) __STATIC_INLINE uint32_t __USAD8(uint32_t op1, uint32_t op2) { uint32_t result; __ASM volatile ("usad8 %0, %1, %2" : "=r" (result) : "r" (op1), "r" (op2) ); return(result); } __attribute__( ( always_inline ) ) __STATIC_INLINE uint32_t __USADA8(uint32_t op1, uint32_t op2, uint32_t op3) { uint32_t result; __ASM volatile ("usada8 %0, %1, %2, %3" : "=r" (result) : "r" (op1), "r" (op2), "r" (op3) ); return(result); } #define __SSAT16(ARG1,ARG2) \ ({ \ uint32_t __RES, __ARG1 = (ARG1); \ __ASM ("ssat16 %0, %1, %2" : "=r" (__RES) : "I" (ARG2), "r" (__ARG1) ); \ __RES; \ }) #define __USAT16(ARG1,ARG2) \ ({ \ uint32_t __RES, __ARG1 = (ARG1); \ __ASM ("usat16 %0, %1, %2" : "=r" (__RES) : "I" (ARG2), "r" (__ARG1) ); \ __RES; \ }) __attribute__( ( always_inline ) ) __STATIC_INLINE uint32_t __UXTB16(uint32_t op1) { uint32_t result; __ASM volatile ("uxtb16 %0, %1" : "=r" (result) : "r" (op1)); return(result); } __attribute__( ( always_inline ) ) __STATIC_INLINE uint32_t __UXTAB16(uint32_t op1, uint32_t op2) { uint32_t result; __ASM volatile ("uxtab16 %0, %1, %2" : "=r" (result) : "r" (op1), "r" (op2) ); return(result); } __attribute__( ( always_inline ) ) __STATIC_INLINE uint32_t __SXTB16(uint32_t op1) { uint32_t result; __ASM volatile ("sxtb16 %0, %1" : "=r" (result) : "r" (op1)); return(result); } __attribute__( ( always_inline ) ) __STATIC_INLINE uint32_t __SXTAB16(uint32_t op1, uint32_t op2) { uint32_t result; __ASM volatile ("sxtab16 %0, %1, %2" : "=r" (result) : "r" (op1), "r" (op2) ); return(result); } __attribute__( ( always_inline ) ) __STATIC_INLINE uint32_t __SMUAD (uint32_t op1, uint32_t op2) { uint32_t result; __ASM volatile ("smuad %0, %1, %2" : "=r" (result) : "r" (op1), "r" (op2) ); return(result); } __attribute__( ( always_inline ) ) __STATIC_INLINE uint32_t __SMUADX (uint32_t op1, uint32_t op2) { uint32_t result; __ASM volatile ("smuadx %0, %1, %2" : "=r" (result) : "r" (op1), "r" (op2) ); return(result); } __attribute__( ( always_inline ) ) __STATIC_INLINE uint32_t __SMLAD (uint32_t op1, uint32_t op2, uint32_t op3) { uint32_t result; __ASM volatile ("smlad %0, %1, %2, %3" : "=r" (result) : "r" (op1), "r" (op2), "r" (op3) ); return(result); } __attribute__( ( always_inline ) ) __STATIC_INLINE uint32_t __SMLADX (uint32_t op1, uint32_t op2, uint32_t op3) { uint32_t result; __ASM volatile ("smladx %0, %1, %2, %3" : "=r" (result) : "r" (op1), "r" (op2), "r" (op3) ); return(result); } #define __SMLALD(ARG1,ARG2,ARG3) \ ({ \ uint32_t __ARG1 = (ARG1), __ARG2 = (ARG2), __ARG3_H = (uint32_t)((uint64_t)(ARG3) >> 32), __ARG3_L = (uint32_t)((uint64_t)(ARG3) & 0xFFFFFFFFUL); \ __ASM volatile ("smlald %0, %1, %2, %3" : "=r" (__ARG3_L), "=r" (__ARG3_H) : "r" (__ARG1), "r" (__ARG2), "0" (__ARG3_L), "1" (__ARG3_H) ); \ (uint64_t)(((uint64_t)__ARG3_H << 32) | __ARG3_L); \ }) #define __SMLALDX(ARG1,ARG2,ARG3) \ ({ \ uint32_t __ARG1 = (ARG1), __ARG2 = (ARG2), __ARG3_H = (uint32_t)((uint64_t)(ARG3) >> 32), __ARG3_L = (uint32_t)((uint64_t)(ARG3) & 0xFFFFFFFFUL); \ __ASM volatile ("smlaldx %0, %1, %2, %3" : "=r" (__ARG3_L), "=r" (__ARG3_H) : "r" (__ARG1), "r" (__ARG2), "0" (__ARG3_L), "1" (__ARG3_H) ); \ (uint64_t)(((uint64_t)__ARG3_H << 32) | __ARG3_L); \ }) __attribute__( ( always_inline ) ) __STATIC_INLINE uint32_t __SMUSD (uint32_t op1, uint32_t op2) { uint32_t result; __ASM volatile ("smusd %0, %1, %2" : "=r" (result) : "r" (op1), "r" (op2) ); return(result); } __attribute__( ( always_inline ) ) __STATIC_INLINE uint32_t __SMUSDX (uint32_t op1, uint32_t op2) { uint32_t result; __ASM volatile ("smusdx %0, %1, %2" : "=r" (result) : "r" (op1), "r" (op2) ); return(result); } __attribute__( ( always_inline ) ) __STATIC_INLINE uint32_t __SMLSD (uint32_t op1, uint32_t op2, uint32_t op3) { uint32_t result; __ASM volatile ("smlsd %0, %1, %2, %3" : "=r" (result) : "r" (op1), "r" (op2), "r" (op3) ); return(result); } __attribute__( ( always_inline ) ) __STATIC_INLINE uint32_t __SMLSDX (uint32_t op1, uint32_t op2, uint32_t op3) { uint32_t result; __ASM volatile ("smlsdx %0, %1, %2, %3" : "=r" (result) : "r" (op1), "r" (op2), "r" (op3) ); return(result); } #define __SMLSLD(ARG1,ARG2,ARG3) \ ({ \ uint32_t __ARG1 = (ARG1), __ARG2 = (ARG2), __ARG3_H = (uint32_t)((ARG3) >> 32), __ARG3_L = (uint32_t)((ARG3) & 0xFFFFFFFFUL); \ __ASM volatile ("smlsld %0, %1, %2, %3" : "=r" (__ARG3_L), "=r" (__ARG3_H) : "r" (__ARG1), "r" (__ARG2), "0" (__ARG3_L), "1" (__ARG3_H) ); \ (uint64_t)(((uint64_t)__ARG3_H << 32) | __ARG3_L); \ }) #define __SMLSLDX(ARG1,ARG2,ARG3) \ ({ \ uint32_t __ARG1 = (ARG1), __ARG2 = (ARG2), __ARG3_H = (uint32_t)((ARG3) >> 32), __ARG3_L = (uint32_t)((ARG3) & 0xFFFFFFFFUL); \ __ASM volatile ("smlsldx %0, %1, %2, %3" : "=r" (__ARG3_L), "=r" (__ARG3_H) : "r" (__ARG1), "r" (__ARG2), "0" (__ARG3_L), "1" (__ARG3_H) ); \ (uint64_t)(((uint64_t)__ARG3_H << 32) | __ARG3_L); \ }) __attribute__( ( always_inline ) ) __STATIC_INLINE uint32_t __SEL (uint32_t op1, uint32_t op2) { uint32_t result; __ASM volatile ("sel %0, %1, %2" : "=r" (result) : "r" (op1), "r" (op2) ); return(result); } __attribute__( ( always_inline ) ) __STATIC_INLINE uint32_t __QADD(uint32_t op1, uint32_t op2) { uint32_t result; __ASM volatile ("qadd %0, %1, %2" : "=r" (result) : "r" (op1), "r" (op2) ); return(result); } __attribute__( ( always_inline ) ) __STATIC_INLINE uint32_t __QSUB(uint32_t op1, uint32_t op2) { uint32_t result; __ASM volatile ("qsub %0, %1, %2" : "=r" (result) : "r" (op1), "r" (op2) ); return(result); } #define __PKHBT(ARG1,ARG2,ARG3) \ ({ \ uint32_t __RES, __ARG1 = (ARG1), __ARG2 = (ARG2); \ __ASM ("pkhbt %0, %1, %2, lsl %3" : "=r" (__RES) : "r" (__ARG1), "r" (__ARG2), "I" (ARG3) ); \ __RES; \ }) #define __PKHTB(ARG1,ARG2,ARG3) \ ({ \ uint32_t __RES, __ARG1 = (ARG1), __ARG2 = (ARG2); \ if (ARG3 == 0) \ __ASM ("pkhtb %0, %1, %2" : "=r" (__RES) : "r" (__ARG1), "r" (__ARG2) ); \ else \ __ASM ("pkhtb %0, %1, %2, asr %3" : "=r" (__RES) : "r" (__ARG1), "r" (__ARG2), "I" (ARG3) ); \ __RES; \ }) __attribute__( ( always_inline ) ) __STATIC_INLINE uint32_t __SMMLA (int32_t op1, int32_t op2, int32_t op3) { int32_t result; __ASM volatile ("smmla %0, %1, %2, %3" : "=r" (result): "r" (op1), "r" (op2), "r" (op3) ); return(result); } /*-- End CM4 SIMD Intrinsics -----------------------------------------------------*/ #elif defined ( __TASKING__ ) /*------------------ TASKING Compiler --------------*/ /* TASKING carm specific functions */ /*------ CM4 SIMD Intrinsics -----------------------------------------------------*/ /* not yet supported */ /*-- End CM4 SIMD Intrinsics -----------------------------------------------------*/ #endif /*@} end of group CMSIS_SIMD_intrinsics */ #endif /* __CORE_CM4_SIMD_H */ #ifdef __cplusplus } #endif ================================================ FILE: Zelig/mbed/TARGET_NUCLEO_F411RE/core_cm7.h ================================================ /**************************************************************************//** * @file core_cm7.h * @brief CMSIS Cortex-M7 Core Peripheral Access Layer Header File * @version V4.10 * @date 18. March 2015 * * @note * ******************************************************************************/ /* Copyright (c) 2009 - 2015 ARM LIMITED All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: - Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. - Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. - Neither the name of ARM 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 COPYRIGHT HOLDERS AND 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. ---------------------------------------------------------------------------*/ #if defined ( __ICCARM__ ) #pragma system_include /* treat file as system include file for MISRA check */ #endif #ifndef __CORE_CM7_H_GENERIC #define __CORE_CM7_H_GENERIC #ifdef __cplusplus extern "C" { #endif /** \page CMSIS_MISRA_Exceptions MISRA-C:2004 Compliance Exceptions CMSIS violates the following MISRA-C:2004 rules: \li Required Rule 8.5, object/function definition in header file.
Function definitions in header files are used to allow 'inlining'. \li Required Rule 18.4, declaration of union type or object of union type: '{...}'.
Unions are used for effective representation of core registers. \li Advisory Rule 19.7, Function-like macro defined.
Function-like macros are used to allow more efficient code. */ /******************************************************************************* * CMSIS definitions ******************************************************************************/ /** \ingroup Cortex_M7 @{ */ /* CMSIS CM7 definitions */ #define __CM7_CMSIS_VERSION_MAIN (0x04) /*!< [31:16] CMSIS HAL main version */ #define __CM7_CMSIS_VERSION_SUB (0x00) /*!< [15:0] CMSIS HAL sub version */ #define __CM7_CMSIS_VERSION ((__CM7_CMSIS_VERSION_MAIN << 16) | \ __CM7_CMSIS_VERSION_SUB ) /*!< CMSIS HAL version number */ #define __CORTEX_M (0x07) /*!< Cortex-M Core */ #if defined ( __CC_ARM ) #define __ASM __asm /*!< asm keyword for ARM Compiler */ #define __INLINE __inline /*!< inline keyword for ARM Compiler */ #define __STATIC_INLINE static __inline #elif defined ( __GNUC__ ) #define __ASM __asm /*!< asm keyword for GNU Compiler */ #define __INLINE inline /*!< inline keyword for GNU Compiler */ #define __STATIC_INLINE static inline #elif defined ( __ICCARM__ ) #define __ASM __asm /*!< asm keyword for IAR Compiler */ #define __INLINE inline /*!< inline keyword for IAR Compiler. Only available in High optimization mode! */ #define __STATIC_INLINE static inline #elif defined ( __TMS470__ ) #define __ASM __asm /*!< asm keyword for TI CCS Compiler */ #define __STATIC_INLINE static inline #elif defined ( __TASKING__ ) #define __ASM __asm /*!< asm keyword for TASKING Compiler */ #define __INLINE inline /*!< inline keyword for TASKING Compiler */ #define __STATIC_INLINE static inline #elif defined ( __CSMC__ ) #define __packed #define __ASM _asm /*!< asm keyword for COSMIC Compiler */ #define __INLINE inline /*use -pc99 on compile line !< inline keyword for COSMIC Compiler */ #define __STATIC_INLINE static inline #endif /** __FPU_USED indicates whether an FPU is used or not. For this, __FPU_PRESENT has to be checked prior to making use of FPU specific registers and functions. */ #if defined ( __CC_ARM ) #if defined __TARGET_FPU_VFP #if (__FPU_PRESENT == 1) #define __FPU_USED 1 #else #warning "Compiler generates FPU instructions for a device without an FPU (check __FPU_PRESENT)" #define __FPU_USED 0 #endif #else #define __FPU_USED 0 #endif #elif defined ( __GNUC__ ) #if defined (__VFP_FP__) && !defined(__SOFTFP__) #if (__FPU_PRESENT == 1) #define __FPU_USED 1 #else #warning "Compiler generates FPU instructions for a device without an FPU (check __FPU_PRESENT)" #define __FPU_USED 0 #endif #else #define __FPU_USED 0 #endif #elif defined ( __ICCARM__ ) #if defined __ARMVFP__ #if (__FPU_PRESENT == 1) #define __FPU_USED 1 #else #warning "Compiler generates FPU instructions for a device without an FPU (check __FPU_PRESENT)" #define __FPU_USED 0 #endif #else #define __FPU_USED 0 #endif #elif defined ( __TMS470__ ) #if defined __TI_VFP_SUPPORT__ #if (__FPU_PRESENT == 1) #define __FPU_USED 1 #else #warning "Compiler generates FPU instructions for a device without an FPU (check __FPU_PRESENT)" #define __FPU_USED 0 #endif #else #define __FPU_USED 0 #endif #elif defined ( __TASKING__ ) #if defined __FPU_VFP__ #if (__FPU_PRESENT == 1) #define __FPU_USED 1 #else #error "Compiler generates FPU instructions for a device without an FPU (check __FPU_PRESENT)" #define __FPU_USED 0 #endif #else #define __FPU_USED 0 #endif #elif defined ( __CSMC__ ) /* Cosmic */ #if ( __CSMC__ & 0x400) // FPU present for parser #if (__FPU_PRESENT == 1) #define __FPU_USED 1 #else #error "Compiler generates FPU instructions for a device without an FPU (check __FPU_PRESENT)" #define __FPU_USED 0 #endif #else #define __FPU_USED 0 #endif #endif #include /* standard types definitions */ #include /* Core Instruction Access */ #include /* Core Function Access */ #include /* Compiler specific SIMD Intrinsics */ #ifdef __cplusplus } #endif #endif /* __CORE_CM7_H_GENERIC */ #ifndef __CMSIS_GENERIC #ifndef __CORE_CM7_H_DEPENDANT #define __CORE_CM7_H_DEPENDANT #ifdef __cplusplus extern "C" { #endif /* check device defines and use defaults */ #if defined __CHECK_DEVICE_DEFINES #ifndef __CM7_REV #define __CM7_REV 0x0000 #warning "__CM7_REV not defined in device header file; using default!" #endif #ifndef __FPU_PRESENT #define __FPU_PRESENT 0 #warning "__FPU_PRESENT not defined in device header file; using default!" #endif #ifndef __MPU_PRESENT #define __MPU_PRESENT 0 #warning "__MPU_PRESENT not defined in device header file; using default!" #endif #ifndef __ICACHE_PRESENT #define __ICACHE_PRESENT 0 #warning "__ICACHE_PRESENT not defined in device header file; using default!" #endif #ifndef __DCACHE_PRESENT #define __DCACHE_PRESENT 0 #warning "__DCACHE_PRESENT not defined in device header file; using default!" #endif #ifndef __DTCM_PRESENT #define __DTCM_PRESENT 0 #warning "__DTCM_PRESENT not defined in device header file; using default!" #endif #ifndef __NVIC_PRIO_BITS #define __NVIC_PRIO_BITS 3 #warning "__NVIC_PRIO_BITS not defined in device header file; using default!" #endif #ifndef __Vendor_SysTickConfig #define __Vendor_SysTickConfig 0 #warning "__Vendor_SysTickConfig not defined in device header file; using default!" #endif #endif /* IO definitions (access restrictions to peripheral registers) */ /** \defgroup CMSIS_glob_defs CMSIS Global Defines IO Type Qualifiers are used \li to specify the access to peripheral variables. \li for automatic generation of peripheral register debug information. */ #ifdef __cplusplus #define __I volatile /*!< Defines 'read only' permissions */ #else #define __I volatile const /*!< Defines 'read only' permissions */ #endif #define __O volatile /*!< Defines 'write only' permissions */ #define __IO volatile /*!< Defines 'read / write' permissions */ /*@} end of group Cortex_M7 */ /******************************************************************************* * Register Abstraction Core Register contain: - Core Register - Core NVIC Register - Core SCB Register - Core SysTick Register - Core Debug Register - Core MPU Register - Core FPU Register ******************************************************************************/ /** \defgroup CMSIS_core_register Defines and Type Definitions \brief Type definitions and defines for Cortex-M processor based devices. */ /** \ingroup CMSIS_core_register \defgroup CMSIS_CORE Status and Control Registers \brief Core Register type definitions. @{ */ /** \brief Union type to access the Application Program Status Register (APSR). */ typedef union { struct { uint32_t _reserved0:16; /*!< bit: 0..15 Reserved */ uint32_t GE:4; /*!< bit: 16..19 Greater than or Equal flags */ uint32_t _reserved1:7; /*!< bit: 20..26 Reserved */ uint32_t Q:1; /*!< bit: 27 Saturation condition flag */ uint32_t V:1; /*!< bit: 28 Overflow condition code flag */ uint32_t C:1; /*!< bit: 29 Carry condition code flag */ uint32_t Z:1; /*!< bit: 30 Zero condition code flag */ uint32_t N:1; /*!< bit: 31 Negative condition code flag */ } b; /*!< Structure used for bit access */ uint32_t w; /*!< Type used for word access */ } APSR_Type; /* APSR Register Definitions */ #define APSR_N_Pos 31 /*!< APSR: N Position */ #define APSR_N_Msk (1UL << APSR_N_Pos) /*!< APSR: N Mask */ #define APSR_Z_Pos 30 /*!< APSR: Z Position */ #define APSR_Z_Msk (1UL << APSR_Z_Pos) /*!< APSR: Z Mask */ #define APSR_C_Pos 29 /*!< APSR: C Position */ #define APSR_C_Msk (1UL << APSR_C_Pos) /*!< APSR: C Mask */ #define APSR_V_Pos 28 /*!< APSR: V Position */ #define APSR_V_Msk (1UL << APSR_V_Pos) /*!< APSR: V Mask */ #define APSR_Q_Pos 27 /*!< APSR: Q Position */ #define APSR_Q_Msk (1UL << APSR_Q_Pos) /*!< APSR: Q Mask */ #define APSR_GE_Pos 16 /*!< APSR: GE Position */ #define APSR_GE_Msk (0xFUL << APSR_GE_Pos) /*!< APSR: GE Mask */ /** \brief Union type to access the Interrupt Program Status Register (IPSR). */ typedef union { struct { uint32_t ISR:9; /*!< bit: 0.. 8 Exception number */ uint32_t _reserved0:23; /*!< bit: 9..31 Reserved */ } b; /*!< Structure used for bit access */ uint32_t w; /*!< Type used for word access */ } IPSR_Type; /* IPSR Register Definitions */ #define IPSR_ISR_Pos 0 /*!< IPSR: ISR Position */ #define IPSR_ISR_Msk (0x1FFUL /*<< IPSR_ISR_Pos*/) /*!< IPSR: ISR Mask */ /** \brief Union type to access the Special-Purpose Program Status Registers (xPSR). */ typedef union { struct { uint32_t ISR:9; /*!< bit: 0.. 8 Exception number */ uint32_t _reserved0:7; /*!< bit: 9..15 Reserved */ uint32_t GE:4; /*!< bit: 16..19 Greater than or Equal flags */ uint32_t _reserved1:4; /*!< bit: 20..23 Reserved */ uint32_t T:1; /*!< bit: 24 Thumb bit (read 0) */ uint32_t IT:2; /*!< bit: 25..26 saved IT state (read 0) */ uint32_t Q:1; /*!< bit: 27 Saturation condition flag */ uint32_t V:1; /*!< bit: 28 Overflow condition code flag */ uint32_t C:1; /*!< bit: 29 Carry condition code flag */ uint32_t Z:1; /*!< bit: 30 Zero condition code flag */ uint32_t N:1; /*!< bit: 31 Negative condition code flag */ } b; /*!< Structure used for bit access */ uint32_t w; /*!< Type used for word access */ } xPSR_Type; /* xPSR Register Definitions */ #define xPSR_N_Pos 31 /*!< xPSR: N Position */ #define xPSR_N_Msk (1UL << xPSR_N_Pos) /*!< xPSR: N Mask */ #define xPSR_Z_Pos 30 /*!< xPSR: Z Position */ #define xPSR_Z_Msk (1UL << xPSR_Z_Pos) /*!< xPSR: Z Mask */ #define xPSR_C_Pos 29 /*!< xPSR: C Position */ #define xPSR_C_Msk (1UL << xPSR_C_Pos) /*!< xPSR: C Mask */ #define xPSR_V_Pos 28 /*!< xPSR: V Position */ #define xPSR_V_Msk (1UL << xPSR_V_Pos) /*!< xPSR: V Mask */ #define xPSR_Q_Pos 27 /*!< xPSR: Q Position */ #define xPSR_Q_Msk (1UL << xPSR_Q_Pos) /*!< xPSR: Q Mask */ #define xPSR_IT_Pos 25 /*!< xPSR: IT Position */ #define xPSR_IT_Msk (3UL << xPSR_IT_Pos) /*!< xPSR: IT Mask */ #define xPSR_T_Pos 24 /*!< xPSR: T Position */ #define xPSR_T_Msk (1UL << xPSR_T_Pos) /*!< xPSR: T Mask */ #define xPSR_GE_Pos 16 /*!< xPSR: GE Position */ #define xPSR_GE_Msk (0xFUL << xPSR_GE_Pos) /*!< xPSR: GE Mask */ #define xPSR_ISR_Pos 0 /*!< xPSR: ISR Position */ #define xPSR_ISR_Msk (0x1FFUL /*<< xPSR_ISR_Pos*/) /*!< xPSR: ISR Mask */ /** \brief Union type to access the Control Registers (CONTROL). */ typedef union { struct { uint32_t nPRIV:1; /*!< bit: 0 Execution privilege in Thread mode */ uint32_t SPSEL:1; /*!< bit: 1 Stack to be used */ uint32_t FPCA:1; /*!< bit: 2 FP extension active flag */ uint32_t _reserved0:29; /*!< bit: 3..31 Reserved */ } b; /*!< Structure used for bit access */ uint32_t w; /*!< Type used for word access */ } CONTROL_Type; /* CONTROL Register Definitions */ #define CONTROL_FPCA_Pos 2 /*!< CONTROL: FPCA Position */ #define CONTROL_FPCA_Msk (1UL << CONTROL_FPCA_Pos) /*!< CONTROL: FPCA Mask */ #define CONTROL_SPSEL_Pos 1 /*!< CONTROL: SPSEL Position */ #define CONTROL_SPSEL_Msk (1UL << CONTROL_SPSEL_Pos) /*!< CONTROL: SPSEL Mask */ #define CONTROL_nPRIV_Pos 0 /*!< CONTROL: nPRIV Position */ #define CONTROL_nPRIV_Msk (1UL /*<< CONTROL_nPRIV_Pos*/) /*!< CONTROL: nPRIV Mask */ /*@} end of group CMSIS_CORE */ /** \ingroup CMSIS_core_register \defgroup CMSIS_NVIC Nested Vectored Interrupt Controller (NVIC) \brief Type definitions for the NVIC Registers @{ */ /** \brief Structure type to access the Nested Vectored Interrupt Controller (NVIC). */ typedef struct { __IO uint32_t ISER[8]; /*!< Offset: 0x000 (R/W) Interrupt Set Enable Register */ uint32_t RESERVED0[24]; __IO uint32_t ICER[8]; /*!< Offset: 0x080 (R/W) Interrupt Clear Enable Register */ uint32_t RSERVED1[24]; __IO uint32_t ISPR[8]; /*!< Offset: 0x100 (R/W) Interrupt Set Pending Register */ uint32_t RESERVED2[24]; __IO uint32_t ICPR[8]; /*!< Offset: 0x180 (R/W) Interrupt Clear Pending Register */ uint32_t RESERVED3[24]; __IO uint32_t IABR[8]; /*!< Offset: 0x200 (R/W) Interrupt Active bit Register */ uint32_t RESERVED4[56]; __IO uint8_t IP[240]; /*!< Offset: 0x300 (R/W) Interrupt Priority Register (8Bit wide) */ uint32_t RESERVED5[644]; __O uint32_t STIR; /*!< Offset: 0xE00 ( /W) Software Trigger Interrupt Register */ } NVIC_Type; /* Software Triggered Interrupt Register Definitions */ #define NVIC_STIR_INTID_Pos 0 /*!< STIR: INTLINESNUM Position */ #define NVIC_STIR_INTID_Msk (0x1FFUL /*<< NVIC_STIR_INTID_Pos*/) /*!< STIR: INTLINESNUM Mask */ /*@} end of group CMSIS_NVIC */ /** \ingroup CMSIS_core_register \defgroup CMSIS_SCB System Control Block (SCB) \brief Type definitions for the System Control Block Registers @{ */ /** \brief Structure type to access the System Control Block (SCB). */ typedef struct { __I uint32_t CPUID; /*!< Offset: 0x000 (R/ ) CPUID Base Register */ __IO uint32_t ICSR; /*!< Offset: 0x004 (R/W) Interrupt Control and State Register */ __IO uint32_t VTOR; /*!< Offset: 0x008 (R/W) Vector Table Offset Register */ __IO uint32_t AIRCR; /*!< Offset: 0x00C (R/W) Application Interrupt and Reset Control Register */ __IO uint32_t SCR; /*!< Offset: 0x010 (R/W) System Control Register */ __IO uint32_t CCR; /*!< Offset: 0x014 (R/W) Configuration Control Register */ __IO uint8_t SHPR[12]; /*!< Offset: 0x018 (R/W) System Handlers Priority Registers (4-7, 8-11, 12-15) */ __IO uint32_t SHCSR; /*!< Offset: 0x024 (R/W) System Handler Control and State Register */ __IO uint32_t CFSR; /*!< Offset: 0x028 (R/W) Configurable Fault Status Register */ __IO uint32_t HFSR; /*!< Offset: 0x02C (R/W) HardFault Status Register */ __IO uint32_t DFSR; /*!< Offset: 0x030 (R/W) Debug Fault Status Register */ __IO uint32_t MMFAR; /*!< Offset: 0x034 (R/W) MemManage Fault Address Register */ __IO uint32_t BFAR; /*!< Offset: 0x038 (R/W) BusFault Address Register */ __IO uint32_t AFSR; /*!< Offset: 0x03C (R/W) Auxiliary Fault Status Register */ __I uint32_t ID_PFR[2]; /*!< Offset: 0x040 (R/ ) Processor Feature Register */ __I uint32_t ID_DFR; /*!< Offset: 0x048 (R/ ) Debug Feature Register */ __I uint32_t ID_AFR; /*!< Offset: 0x04C (R/ ) Auxiliary Feature Register */ __I uint32_t ID_MFR[4]; /*!< Offset: 0x050 (R/ ) Memory Model Feature Register */ __I uint32_t ID_ISAR[5]; /*!< Offset: 0x060 (R/ ) Instruction Set Attributes Register */ uint32_t RESERVED0[1]; __I uint32_t CLIDR; /*!< Offset: 0x078 (R/ ) Cache Level ID register */ __I uint32_t CTR; /*!< Offset: 0x07C (R/ ) Cache Type register */ __I uint32_t CCSIDR; /*!< Offset: 0x080 (R/ ) Cache Size ID Register */ __IO uint32_t CSSELR; /*!< Offset: 0x084 (R/W) Cache Size Selection Register */ __IO uint32_t CPACR; /*!< Offset: 0x088 (R/W) Coprocessor Access Control Register */ uint32_t RESERVED3[93]; __O uint32_t STIR; /*!< Offset: 0x200 ( /W) Software Triggered Interrupt Register */ uint32_t RESERVED4[15]; __I uint32_t MVFR0; /*!< Offset: 0x240 (R/ ) Media and VFP Feature Register 0 */ __I uint32_t MVFR1; /*!< Offset: 0x244 (R/ ) Media and VFP Feature Register 1 */ __I uint32_t MVFR2; /*!< Offset: 0x248 (R/ ) Media and VFP Feature Register 1 */ uint32_t RESERVED5[1]; __O uint32_t ICIALLU; /*!< Offset: 0x250 ( /W) I-Cache Invalidate All to PoU */ uint32_t RESERVED6[1]; __O uint32_t ICIMVAU; /*!< Offset: 0x258 ( /W) I-Cache Invalidate by MVA to PoU */ __O uint32_t DCIMVAC; /*!< Offset: 0x25C ( /W) D-Cache Invalidate by MVA to PoC */ __O uint32_t DCISW; /*!< Offset: 0x260 ( /W) D-Cache Invalidate by Set-way */ __O uint32_t DCCMVAU; /*!< Offset: 0x264 ( /W) D-Cache Clean by MVA to PoU */ __O uint32_t DCCMVAC; /*!< Offset: 0x268 ( /W) D-Cache Clean by MVA to PoC */ __O uint32_t DCCSW; /*!< Offset: 0x26C ( /W) D-Cache Clean by Set-way */ __O uint32_t DCCIMVAC; /*!< Offset: 0x270 ( /W) D-Cache Clean and Invalidate by MVA to PoC */ __O uint32_t DCCISW; /*!< Offset: 0x274 ( /W) D-Cache Clean and Invalidate by Set-way */ uint32_t RESERVED7[6]; __IO uint32_t ITCMCR; /*!< Offset: 0x290 (R/W) Instruction Tightly-Coupled Memory Control Register */ __IO uint32_t DTCMCR; /*!< Offset: 0x294 (R/W) Data Tightly-Coupled Memory Control Registers */ __IO uint32_t AHBPCR; /*!< Offset: 0x298 (R/W) AHBP Control Register */ __IO uint32_t CACR; /*!< Offset: 0x29C (R/W) L1 Cache Control Register */ __IO uint32_t AHBSCR; /*!< Offset: 0x2A0 (R/W) AHB Slave Control Register */ uint32_t RESERVED8[1]; __IO uint32_t ABFSR; /*!< Offset: 0x2A8 (R/W) Auxiliary Bus Fault Status Register */ } SCB_Type; /* SCB CPUID Register Definitions */ #define SCB_CPUID_IMPLEMENTER_Pos 24 /*!< SCB CPUID: IMPLEMENTER Position */ #define SCB_CPUID_IMPLEMENTER_Msk (0xFFUL << SCB_CPUID_IMPLEMENTER_Pos) /*!< SCB CPUID: IMPLEMENTER Mask */ #define SCB_CPUID_VARIANT_Pos 20 /*!< SCB CPUID: VARIANT Position */ #define SCB_CPUID_VARIANT_Msk (0xFUL << SCB_CPUID_VARIANT_Pos) /*!< SCB CPUID: VARIANT Mask */ #define SCB_CPUID_ARCHITECTURE_Pos 16 /*!< SCB CPUID: ARCHITECTURE Position */ #define SCB_CPUID_ARCHITECTURE_Msk (0xFUL << SCB_CPUID_ARCHITECTURE_Pos) /*!< SCB CPUID: ARCHITECTURE Mask */ #define SCB_CPUID_PARTNO_Pos 4 /*!< SCB CPUID: PARTNO Position */ #define SCB_CPUID_PARTNO_Msk (0xFFFUL << SCB_CPUID_PARTNO_Pos) /*!< SCB CPUID: PARTNO Mask */ #define SCB_CPUID_REVISION_Pos 0 /*!< SCB CPUID: REVISION Position */ #define SCB_CPUID_REVISION_Msk (0xFUL /*<< SCB_CPUID_REVISION_Pos*/) /*!< SCB CPUID: REVISION Mask */ /* SCB Interrupt Control State Register Definitions */ #define SCB_ICSR_NMIPENDSET_Pos 31 /*!< SCB ICSR: NMIPENDSET Position */ #define SCB_ICSR_NMIPENDSET_Msk (1UL << SCB_ICSR_NMIPENDSET_Pos) /*!< SCB ICSR: NMIPENDSET Mask */ #define SCB_ICSR_PENDSVSET_Pos 28 /*!< SCB ICSR: PENDSVSET Position */ #define SCB_ICSR_PENDSVSET_Msk (1UL << SCB_ICSR_PENDSVSET_Pos) /*!< SCB ICSR: PENDSVSET Mask */ #define SCB_ICSR_PENDSVCLR_Pos 27 /*!< SCB ICSR: PENDSVCLR Position */ #define SCB_ICSR_PENDSVCLR_Msk (1UL << SCB_ICSR_PENDSVCLR_Pos) /*!< SCB ICSR: PENDSVCLR Mask */ #define SCB_ICSR_PENDSTSET_Pos 26 /*!< SCB ICSR: PENDSTSET Position */ #define SCB_ICSR_PENDSTSET_Msk (1UL << SCB_ICSR_PENDSTSET_Pos) /*!< SCB ICSR: PENDSTSET Mask */ #define SCB_ICSR_PENDSTCLR_Pos 25 /*!< SCB ICSR: PENDSTCLR Position */ #define SCB_ICSR_PENDSTCLR_Msk (1UL << SCB_ICSR_PENDSTCLR_Pos) /*!< SCB ICSR: PENDSTCLR Mask */ #define SCB_ICSR_ISRPREEMPT_Pos 23 /*!< SCB ICSR: ISRPREEMPT Position */ #define SCB_ICSR_ISRPREEMPT_Msk (1UL << SCB_ICSR_ISRPREEMPT_Pos) /*!< SCB ICSR: ISRPREEMPT Mask */ #define SCB_ICSR_ISRPENDING_Pos 22 /*!< SCB ICSR: ISRPENDING Position */ #define SCB_ICSR_ISRPENDING_Msk (1UL << SCB_ICSR_ISRPENDING_Pos) /*!< SCB ICSR: ISRPENDING Mask */ #define SCB_ICSR_VECTPENDING_Pos 12 /*!< SCB ICSR: VECTPENDING Position */ #define SCB_ICSR_VECTPENDING_Msk (0x1FFUL << SCB_ICSR_VECTPENDING_Pos) /*!< SCB ICSR: VECTPENDING Mask */ #define SCB_ICSR_RETTOBASE_Pos 11 /*!< SCB ICSR: RETTOBASE Position */ #define SCB_ICSR_RETTOBASE_Msk (1UL << SCB_ICSR_RETTOBASE_Pos) /*!< SCB ICSR: RETTOBASE Mask */ #define SCB_ICSR_VECTACTIVE_Pos 0 /*!< SCB ICSR: VECTACTIVE Position */ #define SCB_ICSR_VECTACTIVE_Msk (0x1FFUL /*<< SCB_ICSR_VECTACTIVE_Pos*/) /*!< SCB ICSR: VECTACTIVE Mask */ /* SCB Vector Table Offset Register Definitions */ #define SCB_VTOR_TBLOFF_Pos 7 /*!< SCB VTOR: TBLOFF Position */ #define SCB_VTOR_TBLOFF_Msk (0x1FFFFFFUL << SCB_VTOR_TBLOFF_Pos) /*!< SCB VTOR: TBLOFF Mask */ /* SCB Application Interrupt and Reset Control Register Definitions */ #define SCB_AIRCR_VECTKEY_Pos 16 /*!< SCB AIRCR: VECTKEY Position */ #define SCB_AIRCR_VECTKEY_Msk (0xFFFFUL << SCB_AIRCR_VECTKEY_Pos) /*!< SCB AIRCR: VECTKEY Mask */ #define SCB_AIRCR_VECTKEYSTAT_Pos 16 /*!< SCB AIRCR: VECTKEYSTAT Position */ #define SCB_AIRCR_VECTKEYSTAT_Msk (0xFFFFUL << SCB_AIRCR_VECTKEYSTAT_Pos) /*!< SCB AIRCR: VECTKEYSTAT Mask */ #define SCB_AIRCR_ENDIANESS_Pos 15 /*!< SCB AIRCR: ENDIANESS Position */ #define SCB_AIRCR_ENDIANESS_Msk (1UL << SCB_AIRCR_ENDIANESS_Pos) /*!< SCB AIRCR: ENDIANESS Mask */ #define SCB_AIRCR_PRIGROUP_Pos 8 /*!< SCB AIRCR: PRIGROUP Position */ #define SCB_AIRCR_PRIGROUP_Msk (7UL << SCB_AIRCR_PRIGROUP_Pos) /*!< SCB AIRCR: PRIGROUP Mask */ #define SCB_AIRCR_SYSRESETREQ_Pos 2 /*!< SCB AIRCR: SYSRESETREQ Position */ #define SCB_AIRCR_SYSRESETREQ_Msk (1UL << SCB_AIRCR_SYSRESETREQ_Pos) /*!< SCB AIRCR: SYSRESETREQ Mask */ #define SCB_AIRCR_VECTCLRACTIVE_Pos 1 /*!< SCB AIRCR: VECTCLRACTIVE Position */ #define SCB_AIRCR_VECTCLRACTIVE_Msk (1UL << SCB_AIRCR_VECTCLRACTIVE_Pos) /*!< SCB AIRCR: VECTCLRACTIVE Mask */ #define SCB_AIRCR_VECTRESET_Pos 0 /*!< SCB AIRCR: VECTRESET Position */ #define SCB_AIRCR_VECTRESET_Msk (1UL /*<< SCB_AIRCR_VECTRESET_Pos*/) /*!< SCB AIRCR: VECTRESET Mask */ /* SCB System Control Register Definitions */ #define SCB_SCR_SEVONPEND_Pos 4 /*!< SCB SCR: SEVONPEND Position */ #define SCB_SCR_SEVONPEND_Msk (1UL << SCB_SCR_SEVONPEND_Pos) /*!< SCB SCR: SEVONPEND Mask */ #define SCB_SCR_SLEEPDEEP_Pos 2 /*!< SCB SCR: SLEEPDEEP Position */ #define SCB_SCR_SLEEPDEEP_Msk (1UL << SCB_SCR_SLEEPDEEP_Pos) /*!< SCB SCR: SLEEPDEEP Mask */ #define SCB_SCR_SLEEPONEXIT_Pos 1 /*!< SCB SCR: SLEEPONEXIT Position */ #define SCB_SCR_SLEEPONEXIT_Msk (1UL << SCB_SCR_SLEEPONEXIT_Pos) /*!< SCB SCR: SLEEPONEXIT Mask */ /* SCB Configuration Control Register Definitions */ #define SCB_CCR_BP_Pos 18 /*!< SCB CCR: Branch prediction enable bit Position */ #define SCB_CCR_BP_Msk (1UL << SCB_CCR_BP_Pos) /*!< SCB CCR: Branch prediction enable bit Mask */ #define SCB_CCR_IC_Pos 17 /*!< SCB CCR: Instruction cache enable bit Position */ #define SCB_CCR_IC_Msk (1UL << SCB_CCR_IC_Pos) /*!< SCB CCR: Instruction cache enable bit Mask */ #define SCB_CCR_DC_Pos 16 /*!< SCB CCR: Cache enable bit Position */ #define SCB_CCR_DC_Msk (1UL << SCB_CCR_DC_Pos) /*!< SCB CCR: Cache enable bit Mask */ #define SCB_CCR_STKALIGN_Pos 9 /*!< SCB CCR: STKALIGN Position */ #define SCB_CCR_STKALIGN_Msk (1UL << SCB_CCR_STKALIGN_Pos) /*!< SCB CCR: STKALIGN Mask */ #define SCB_CCR_BFHFNMIGN_Pos 8 /*!< SCB CCR: BFHFNMIGN Position */ #define SCB_CCR_BFHFNMIGN_Msk (1UL << SCB_CCR_BFHFNMIGN_Pos) /*!< SCB CCR: BFHFNMIGN Mask */ #define SCB_CCR_DIV_0_TRP_Pos 4 /*!< SCB CCR: DIV_0_TRP Position */ #define SCB_CCR_DIV_0_TRP_Msk (1UL << SCB_CCR_DIV_0_TRP_Pos) /*!< SCB CCR: DIV_0_TRP Mask */ #define SCB_CCR_UNALIGN_TRP_Pos 3 /*!< SCB CCR: UNALIGN_TRP Position */ #define SCB_CCR_UNALIGN_TRP_Msk (1UL << SCB_CCR_UNALIGN_TRP_Pos) /*!< SCB CCR: UNALIGN_TRP Mask */ #define SCB_CCR_USERSETMPEND_Pos 1 /*!< SCB CCR: USERSETMPEND Position */ #define SCB_CCR_USERSETMPEND_Msk (1UL << SCB_CCR_USERSETMPEND_Pos) /*!< SCB CCR: USERSETMPEND Mask */ #define SCB_CCR_NONBASETHRDENA_Pos 0 /*!< SCB CCR: NONBASETHRDENA Position */ #define SCB_CCR_NONBASETHRDENA_Msk (1UL /*<< SCB_CCR_NONBASETHRDENA_Pos*/) /*!< SCB CCR: NONBASETHRDENA Mask */ /* SCB System Handler Control and State Register Definitions */ #define SCB_SHCSR_USGFAULTENA_Pos 18 /*!< SCB SHCSR: USGFAULTENA Position */ #define SCB_SHCSR_USGFAULTENA_Msk (1UL << SCB_SHCSR_USGFAULTENA_Pos) /*!< SCB SHCSR: USGFAULTENA Mask */ #define SCB_SHCSR_BUSFAULTENA_Pos 17 /*!< SCB SHCSR: BUSFAULTENA Position */ #define SCB_SHCSR_BUSFAULTENA_Msk (1UL << SCB_SHCSR_BUSFAULTENA_Pos) /*!< SCB SHCSR: BUSFAULTENA Mask */ #define SCB_SHCSR_MEMFAULTENA_Pos 16 /*!< SCB SHCSR: MEMFAULTENA Position */ #define SCB_SHCSR_MEMFAULTENA_Msk (1UL << SCB_SHCSR_MEMFAULTENA_Pos) /*!< SCB SHCSR: MEMFAULTENA Mask */ #define SCB_SHCSR_SVCALLPENDED_Pos 15 /*!< SCB SHCSR: SVCALLPENDED Position */ #define SCB_SHCSR_SVCALLPENDED_Msk (1UL << SCB_SHCSR_SVCALLPENDED_Pos) /*!< SCB SHCSR: SVCALLPENDED Mask */ #define SCB_SHCSR_BUSFAULTPENDED_Pos 14 /*!< SCB SHCSR: BUSFAULTPENDED Position */ #define SCB_SHCSR_BUSFAULTPENDED_Msk (1UL << SCB_SHCSR_BUSFAULTPENDED_Pos) /*!< SCB SHCSR: BUSFAULTPENDED Mask */ #define SCB_SHCSR_MEMFAULTPENDED_Pos 13 /*!< SCB SHCSR: MEMFAULTPENDED Position */ #define SCB_SHCSR_MEMFAULTPENDED_Msk (1UL << SCB_SHCSR_MEMFAULTPENDED_Pos) /*!< SCB SHCSR: MEMFAULTPENDED Mask */ #define SCB_SHCSR_USGFAULTPENDED_Pos 12 /*!< SCB SHCSR: USGFAULTPENDED Position */ #define SCB_SHCSR_USGFAULTPENDED_Msk (1UL << SCB_SHCSR_USGFAULTPENDED_Pos) /*!< SCB SHCSR: USGFAULTPENDED Mask */ #define SCB_SHCSR_SYSTICKACT_Pos 11 /*!< SCB SHCSR: SYSTICKACT Position */ #define SCB_SHCSR_SYSTICKACT_Msk (1UL << SCB_SHCSR_SYSTICKACT_Pos) /*!< SCB SHCSR: SYSTICKACT Mask */ #define SCB_SHCSR_PENDSVACT_Pos 10 /*!< SCB SHCSR: PENDSVACT Position */ #define SCB_SHCSR_PENDSVACT_Msk (1UL << SCB_SHCSR_PENDSVACT_Pos) /*!< SCB SHCSR: PENDSVACT Mask */ #define SCB_SHCSR_MONITORACT_Pos 8 /*!< SCB SHCSR: MONITORACT Position */ #define SCB_SHCSR_MONITORACT_Msk (1UL << SCB_SHCSR_MONITORACT_Pos) /*!< SCB SHCSR: MONITORACT Mask */ #define SCB_SHCSR_SVCALLACT_Pos 7 /*!< SCB SHCSR: SVCALLACT Position */ #define SCB_SHCSR_SVCALLACT_Msk (1UL << SCB_SHCSR_SVCALLACT_Pos) /*!< SCB SHCSR: SVCALLACT Mask */ #define SCB_SHCSR_USGFAULTACT_Pos 3 /*!< SCB SHCSR: USGFAULTACT Position */ #define SCB_SHCSR_USGFAULTACT_Msk (1UL << SCB_SHCSR_USGFAULTACT_Pos) /*!< SCB SHCSR: USGFAULTACT Mask */ #define SCB_SHCSR_BUSFAULTACT_Pos 1 /*!< SCB SHCSR: BUSFAULTACT Position */ #define SCB_SHCSR_BUSFAULTACT_Msk (1UL << SCB_SHCSR_BUSFAULTACT_Pos) /*!< SCB SHCSR: BUSFAULTACT Mask */ #define SCB_SHCSR_MEMFAULTACT_Pos 0 /*!< SCB SHCSR: MEMFAULTACT Position */ #define SCB_SHCSR_MEMFAULTACT_Msk (1UL /*<< SCB_SHCSR_MEMFAULTACT_Pos*/) /*!< SCB SHCSR: MEMFAULTACT Mask */ /* SCB Configurable Fault Status Registers Definitions */ #define SCB_CFSR_USGFAULTSR_Pos 16 /*!< SCB CFSR: Usage Fault Status Register Position */ #define SCB_CFSR_USGFAULTSR_Msk (0xFFFFUL << SCB_CFSR_USGFAULTSR_Pos) /*!< SCB CFSR: Usage Fault Status Register Mask */ #define SCB_CFSR_BUSFAULTSR_Pos 8 /*!< SCB CFSR: Bus Fault Status Register Position */ #define SCB_CFSR_BUSFAULTSR_Msk (0xFFUL << SCB_CFSR_BUSFAULTSR_Pos) /*!< SCB CFSR: Bus Fault Status Register Mask */ #define SCB_CFSR_MEMFAULTSR_Pos 0 /*!< SCB CFSR: Memory Manage Fault Status Register Position */ #define SCB_CFSR_MEMFAULTSR_Msk (0xFFUL /*<< SCB_CFSR_MEMFAULTSR_Pos*/) /*!< SCB CFSR: Memory Manage Fault Status Register Mask */ /* SCB Hard Fault Status Registers Definitions */ #define SCB_HFSR_DEBUGEVT_Pos 31 /*!< SCB HFSR: DEBUGEVT Position */ #define SCB_HFSR_DEBUGEVT_Msk (1UL << SCB_HFSR_DEBUGEVT_Pos) /*!< SCB HFSR: DEBUGEVT Mask */ #define SCB_HFSR_FORCED_Pos 30 /*!< SCB HFSR: FORCED Position */ #define SCB_HFSR_FORCED_Msk (1UL << SCB_HFSR_FORCED_Pos) /*!< SCB HFSR: FORCED Mask */ #define SCB_HFSR_VECTTBL_Pos 1 /*!< SCB HFSR: VECTTBL Position */ #define SCB_HFSR_VECTTBL_Msk (1UL << SCB_HFSR_VECTTBL_Pos) /*!< SCB HFSR: VECTTBL Mask */ /* SCB Debug Fault Status Register Definitions */ #define SCB_DFSR_EXTERNAL_Pos 4 /*!< SCB DFSR: EXTERNAL Position */ #define SCB_DFSR_EXTERNAL_Msk (1UL << SCB_DFSR_EXTERNAL_Pos) /*!< SCB DFSR: EXTERNAL Mask */ #define SCB_DFSR_VCATCH_Pos 3 /*!< SCB DFSR: VCATCH Position */ #define SCB_DFSR_VCATCH_Msk (1UL << SCB_DFSR_VCATCH_Pos) /*!< SCB DFSR: VCATCH Mask */ #define SCB_DFSR_DWTTRAP_Pos 2 /*!< SCB DFSR: DWTTRAP Position */ #define SCB_DFSR_DWTTRAP_Msk (1UL << SCB_DFSR_DWTTRAP_Pos) /*!< SCB DFSR: DWTTRAP Mask */ #define SCB_DFSR_BKPT_Pos 1 /*!< SCB DFSR: BKPT Position */ #define SCB_DFSR_BKPT_Msk (1UL << SCB_DFSR_BKPT_Pos) /*!< SCB DFSR: BKPT Mask */ #define SCB_DFSR_HALTED_Pos 0 /*!< SCB DFSR: HALTED Position */ #define SCB_DFSR_HALTED_Msk (1UL /*<< SCB_DFSR_HALTED_Pos*/) /*!< SCB DFSR: HALTED Mask */ /* Cache Level ID register */ #define SCB_CLIDR_LOUU_Pos 27 /*!< SCB CLIDR: LoUU Position */ #define SCB_CLIDR_LOUU_Msk (7UL << SCB_CLIDR_LOUU_Pos) /*!< SCB CLIDR: LoUU Mask */ #define SCB_CLIDR_LOC_Pos 24 /*!< SCB CLIDR: LoC Position */ #define SCB_CLIDR_LOC_Msk (7UL << SCB_CLIDR_FORMAT_Pos) /*!< SCB CLIDR: LoC Mask */ /* Cache Type register */ #define SCB_CTR_FORMAT_Pos 29 /*!< SCB CTR: Format Position */ #define SCB_CTR_FORMAT_Msk (7UL << SCB_CTR_FORMAT_Pos) /*!< SCB CTR: Format Mask */ #define SCB_CTR_CWG_Pos 24 /*!< SCB CTR: CWG Position */ #define SCB_CTR_CWG_Msk (0xFUL << SCB_CTR_CWG_Pos) /*!< SCB CTR: CWG Mask */ #define SCB_CTR_ERG_Pos 20 /*!< SCB CTR: ERG Position */ #define SCB_CTR_ERG_Msk (0xFUL << SCB_CTR_ERG_Pos) /*!< SCB CTR: ERG Mask */ #define SCB_CTR_DMINLINE_Pos 16 /*!< SCB CTR: DminLine Position */ #define SCB_CTR_DMINLINE_Msk (0xFUL << SCB_CTR_DMINLINE_Pos) /*!< SCB CTR: DminLine Mask */ #define SCB_CTR_IMINLINE_Pos 0 /*!< SCB CTR: ImInLine Position */ #define SCB_CTR_IMINLINE_Msk (0xFUL /*<< SCB_CTR_IMINLINE_Pos*/) /*!< SCB CTR: ImInLine Mask */ /* Cache Size ID Register */ #define SCB_CCSIDR_WT_Pos 31 /*!< SCB CCSIDR: WT Position */ #define SCB_CCSIDR_WT_Msk (7UL << SCB_CCSIDR_WT_Pos) /*!< SCB CCSIDR: WT Mask */ #define SCB_CCSIDR_WB_Pos 30 /*!< SCB CCSIDR: WB Position */ #define SCB_CCSIDR_WB_Msk (7UL << SCB_CCSIDR_WB_Pos) /*!< SCB CCSIDR: WB Mask */ #define SCB_CCSIDR_RA_Pos 29 /*!< SCB CCSIDR: RA Position */ #define SCB_CCSIDR_RA_Msk (7UL << SCB_CCSIDR_RA_Pos) /*!< SCB CCSIDR: RA Mask */ #define SCB_CCSIDR_WA_Pos 28 /*!< SCB CCSIDR: WA Position */ #define SCB_CCSIDR_WA_Msk (7UL << SCB_CCSIDR_WA_Pos) /*!< SCB CCSIDR: WA Mask */ #define SCB_CCSIDR_NUMSETS_Pos 13 /*!< SCB CCSIDR: NumSets Position */ #define SCB_CCSIDR_NUMSETS_Msk (0x7FFFUL << SCB_CCSIDR_NUMSETS_Pos) /*!< SCB CCSIDR: NumSets Mask */ #define SCB_CCSIDR_ASSOCIATIVITY_Pos 3 /*!< SCB CCSIDR: Associativity Position */ #define SCB_CCSIDR_ASSOCIATIVITY_Msk (0x3FFUL << SCB_CCSIDR_ASSOCIATIVITY_Pos) /*!< SCB CCSIDR: Associativity Mask */ #define SCB_CCSIDR_LINESIZE_Pos 0 /*!< SCB CCSIDR: LineSize Position */ #define SCB_CCSIDR_LINESIZE_Msk (7UL /*<< SCB_CCSIDR_LINESIZE_Pos*/) /*!< SCB CCSIDR: LineSize Mask */ /* Cache Size Selection Register */ #define SCB_CSSELR_LEVEL_Pos 1 /*!< SCB CSSELR: Level Position */ #define SCB_CSSELR_LEVEL_Msk (7UL << SCB_CSSELR_LEVEL_Pos) /*!< SCB CSSELR: Level Mask */ #define SCB_CSSELR_IND_Pos 0 /*!< SCB CSSELR: InD Position */ #define SCB_CSSELR_IND_Msk (1UL /*<< SCB_CSSELR_IND_Pos*/) /*!< SCB CSSELR: InD Mask */ /* SCB Software Triggered Interrupt Register */ #define SCB_STIR_INTID_Pos 0 /*!< SCB STIR: INTID Position */ #define SCB_STIR_INTID_Msk (0x1FFUL /*<< SCB_STIR_INTID_Pos*/) /*!< SCB STIR: INTID Mask */ /* Instruction Tightly-Coupled Memory Control Register*/ #define SCB_ITCMCR_SZ_Pos 3 /*!< SCB ITCMCR: SZ Position */ #define SCB_ITCMCR_SZ_Msk (0xFUL << SCB_ITCMCR_SZ_Pos) /*!< SCB ITCMCR: SZ Mask */ #define SCB_ITCMCR_RETEN_Pos 2 /*!< SCB ITCMCR: RETEN Position */ #define SCB_ITCMCR_RETEN_Msk (1UL << SCB_ITCMCR_RETEN_Pos) /*!< SCB ITCMCR: RETEN Mask */ #define SCB_ITCMCR_RMW_Pos 1 /*!< SCB ITCMCR: RMW Position */ #define SCB_ITCMCR_RMW_Msk (1UL << SCB_ITCMCR_RMW_Pos) /*!< SCB ITCMCR: RMW Mask */ #define SCB_ITCMCR_EN_Pos 0 /*!< SCB ITCMCR: EN Position */ #define SCB_ITCMCR_EN_Msk (1UL /*<< SCB_ITCMCR_EN_Pos*/) /*!< SCB ITCMCR: EN Mask */ /* Data Tightly-Coupled Memory Control Registers */ #define SCB_DTCMCR_SZ_Pos 3 /*!< SCB DTCMCR: SZ Position */ #define SCB_DTCMCR_SZ_Msk (0xFUL << SCB_DTCMCR_SZ_Pos) /*!< SCB DTCMCR: SZ Mask */ #define SCB_DTCMCR_RETEN_Pos 2 /*!< SCB DTCMCR: RETEN Position */ #define SCB_DTCMCR_RETEN_Msk (1UL << SCB_DTCMCR_RETEN_Pos) /*!< SCB DTCMCR: RETEN Mask */ #define SCB_DTCMCR_RMW_Pos 1 /*!< SCB DTCMCR: RMW Position */ #define SCB_DTCMCR_RMW_Msk (1UL << SCB_DTCMCR_RMW_Pos) /*!< SCB DTCMCR: RMW Mask */ #define SCB_DTCMCR_EN_Pos 0 /*!< SCB DTCMCR: EN Position */ #define SCB_DTCMCR_EN_Msk (1UL /*<< SCB_DTCMCR_EN_Pos*/) /*!< SCB DTCMCR: EN Mask */ /* AHBP Control Register */ #define SCB_AHBPCR_SZ_Pos 1 /*!< SCB AHBPCR: SZ Position */ #define SCB_AHBPCR_SZ_Msk (7UL << SCB_AHBPCR_SZ_Pos) /*!< SCB AHBPCR: SZ Mask */ #define SCB_AHBPCR_EN_Pos 0 /*!< SCB AHBPCR: EN Position */ #define SCB_AHBPCR_EN_Msk (1UL /*<< SCB_AHBPCR_EN_Pos*/) /*!< SCB AHBPCR: EN Mask */ /* L1 Cache Control Register */ #define SCB_CACR_FORCEWT_Pos 2 /*!< SCB CACR: FORCEWT Position */ #define SCB_CACR_FORCEWT_Msk (1UL << SCB_CACR_FORCEWT_Pos) /*!< SCB CACR: FORCEWT Mask */ #define SCB_CACR_ECCEN_Pos 1 /*!< SCB CACR: ECCEN Position */ #define SCB_CACR_ECCEN_Msk (1UL << SCB_CACR_ECCEN_Pos) /*!< SCB CACR: ECCEN Mask */ #define SCB_CACR_SIWT_Pos 0 /*!< SCB CACR: SIWT Position */ #define SCB_CACR_SIWT_Msk (1UL /*<< SCB_CACR_SIWT_Pos*/) /*!< SCB CACR: SIWT Mask */ /* AHBS control register */ #define SCB_AHBSCR_INITCOUNT_Pos 11 /*!< SCB AHBSCR: INITCOUNT Position */ #define SCB_AHBSCR_INITCOUNT_Msk (0x1FUL << SCB_AHBPCR_INITCOUNT_Pos) /*!< SCB AHBSCR: INITCOUNT Mask */ #define SCB_AHBSCR_TPRI_Pos 2 /*!< SCB AHBSCR: TPRI Position */ #define SCB_AHBSCR_TPRI_Msk (0x1FFUL << SCB_AHBPCR_TPRI_Pos) /*!< SCB AHBSCR: TPRI Mask */ #define SCB_AHBSCR_CTL_Pos 0 /*!< SCB AHBSCR: CTL Position*/ #define SCB_AHBSCR_CTL_Msk (3UL /*<< SCB_AHBPCR_CTL_Pos*/) /*!< SCB AHBSCR: CTL Mask */ /* Auxiliary Bus Fault Status Register */ #define SCB_ABFSR_AXIMTYPE_Pos 8 /*!< SCB ABFSR: AXIMTYPE Position*/ #define SCB_ABFSR_AXIMTYPE_Msk (3UL << SCB_ABFSR_AXIMTYPE_Pos) /*!< SCB ABFSR: AXIMTYPE Mask */ #define SCB_ABFSR_EPPB_Pos 4 /*!< SCB ABFSR: EPPB Position*/ #define SCB_ABFSR_EPPB_Msk (1UL << SCB_ABFSR_EPPB_Pos) /*!< SCB ABFSR: EPPB Mask */ #define SCB_ABFSR_AXIM_Pos 3 /*!< SCB ABFSR: AXIM Position*/ #define SCB_ABFSR_AXIM_Msk (1UL << SCB_ABFSR_AXIM_Pos) /*!< SCB ABFSR: AXIM Mask */ #define SCB_ABFSR_AHBP_Pos 2 /*!< SCB ABFSR: AHBP Position*/ #define SCB_ABFSR_AHBP_Msk (1UL << SCB_ABFSR_AHBP_Pos) /*!< SCB ABFSR: AHBP Mask */ #define SCB_ABFSR_DTCM_Pos 1 /*!< SCB ABFSR: DTCM Position*/ #define SCB_ABFSR_DTCM_Msk (1UL << SCB_ABFSR_DTCM_Pos) /*!< SCB ABFSR: DTCM Mask */ #define SCB_ABFSR_ITCM_Pos 0 /*!< SCB ABFSR: ITCM Position*/ #define SCB_ABFSR_ITCM_Msk (1UL /*<< SCB_ABFSR_ITCM_Pos*/) /*!< SCB ABFSR: ITCM Mask */ /*@} end of group CMSIS_SCB */ /** \ingroup CMSIS_core_register \defgroup CMSIS_SCnSCB System Controls not in SCB (SCnSCB) \brief Type definitions for the System Control and ID Register not in the SCB @{ */ /** \brief Structure type to access the System Control and ID Register not in the SCB. */ typedef struct { uint32_t RESERVED0[1]; __I uint32_t ICTR; /*!< Offset: 0x004 (R/ ) Interrupt Controller Type Register */ __IO uint32_t ACTLR; /*!< Offset: 0x008 (R/W) Auxiliary Control Register */ } SCnSCB_Type; /* Interrupt Controller Type Register Definitions */ #define SCnSCB_ICTR_INTLINESNUM_Pos 0 /*!< ICTR: INTLINESNUM Position */ #define SCnSCB_ICTR_INTLINESNUM_Msk (0xFUL /*<< SCnSCB_ICTR_INTLINESNUM_Pos*/) /*!< ICTR: INTLINESNUM Mask */ /* Auxiliary Control Register Definitions */ #define SCnSCB_ACTLR_DISITMATBFLUSH_Pos 12 /*!< ACTLR: DISITMATBFLUSH Position */ #define SCnSCB_ACTLR_DISITMATBFLUSH_Msk (1UL << SCnSCB_ACTLR_DISITMATBFLUSH_Pos) /*!< ACTLR: DISITMATBFLUSH Mask */ #define SCnSCB_ACTLR_DISRAMODE_Pos 11 /*!< ACTLR: DISRAMODE Position */ #define SCnSCB_ACTLR_DISRAMODE_Msk (1UL << SCnSCB_ACTLR_DISRAMODE_Pos) /*!< ACTLR: DISRAMODE Mask */ #define SCnSCB_ACTLR_FPEXCODIS_Pos 10 /*!< ACTLR: FPEXCODIS Position */ #define SCnSCB_ACTLR_FPEXCODIS_Msk (1UL << SCnSCB_ACTLR_FPEXCODIS_Pos) /*!< ACTLR: FPEXCODIS Mask */ #define SCnSCB_ACTLR_DISFOLD_Pos 2 /*!< ACTLR: DISFOLD Position */ #define SCnSCB_ACTLR_DISFOLD_Msk (1UL << SCnSCB_ACTLR_DISFOLD_Pos) /*!< ACTLR: DISFOLD Mask */ #define SCnSCB_ACTLR_DISMCYCINT_Pos 0 /*!< ACTLR: DISMCYCINT Position */ #define SCnSCB_ACTLR_DISMCYCINT_Msk (1UL /*<< SCnSCB_ACTLR_DISMCYCINT_Pos*/) /*!< ACTLR: DISMCYCINT Mask */ /*@} end of group CMSIS_SCnotSCB */ /** \ingroup CMSIS_core_register \defgroup CMSIS_SysTick System Tick Timer (SysTick) \brief Type definitions for the System Timer Registers. @{ */ /** \brief Structure type to access the System Timer (SysTick). */ typedef struct { __IO uint32_t CTRL; /*!< Offset: 0x000 (R/W) SysTick Control and Status Register */ __IO uint32_t LOAD; /*!< Offset: 0x004 (R/W) SysTick Reload Value Register */ __IO uint32_t VAL; /*!< Offset: 0x008 (R/W) SysTick Current Value Register */ __I uint32_t CALIB; /*!< Offset: 0x00C (R/ ) SysTick Calibration Register */ } SysTick_Type; /* SysTick Control / Status Register Definitions */ #define SysTick_CTRL_COUNTFLAG_Pos 16 /*!< SysTick CTRL: COUNTFLAG Position */ #define SysTick_CTRL_COUNTFLAG_Msk (1UL << SysTick_CTRL_COUNTFLAG_Pos) /*!< SysTick CTRL: COUNTFLAG Mask */ #define SysTick_CTRL_CLKSOURCE_Pos 2 /*!< SysTick CTRL: CLKSOURCE Position */ #define SysTick_CTRL_CLKSOURCE_Msk (1UL << SysTick_CTRL_CLKSOURCE_Pos) /*!< SysTick CTRL: CLKSOURCE Mask */ #define SysTick_CTRL_TICKINT_Pos 1 /*!< SysTick CTRL: TICKINT Position */ #define SysTick_CTRL_TICKINT_Msk (1UL << SysTick_CTRL_TICKINT_Pos) /*!< SysTick CTRL: TICKINT Mask */ #define SysTick_CTRL_ENABLE_Pos 0 /*!< SysTick CTRL: ENABLE Position */ #define SysTick_CTRL_ENABLE_Msk (1UL /*<< SysTick_CTRL_ENABLE_Pos*/) /*!< SysTick CTRL: ENABLE Mask */ /* SysTick Reload Register Definitions */ #define SysTick_LOAD_RELOAD_Pos 0 /*!< SysTick LOAD: RELOAD Position */ #define SysTick_LOAD_RELOAD_Msk (0xFFFFFFUL /*<< SysTick_LOAD_RELOAD_Pos*/) /*!< SysTick LOAD: RELOAD Mask */ /* SysTick Current Register Definitions */ #define SysTick_VAL_CURRENT_Pos 0 /*!< SysTick VAL: CURRENT Position */ #define SysTick_VAL_CURRENT_Msk (0xFFFFFFUL /*<< SysTick_VAL_CURRENT_Pos*/) /*!< SysTick VAL: CURRENT Mask */ /* SysTick Calibration Register Definitions */ #define SysTick_CALIB_NOREF_Pos 31 /*!< SysTick CALIB: NOREF Position */ #define SysTick_CALIB_NOREF_Msk (1UL << SysTick_CALIB_NOREF_Pos) /*!< SysTick CALIB: NOREF Mask */ #define SysTick_CALIB_SKEW_Pos 30 /*!< SysTick CALIB: SKEW Position */ #define SysTick_CALIB_SKEW_Msk (1UL << SysTick_CALIB_SKEW_Pos) /*!< SysTick CALIB: SKEW Mask */ #define SysTick_CALIB_TENMS_Pos 0 /*!< SysTick CALIB: TENMS Position */ #define SysTick_CALIB_TENMS_Msk (0xFFFFFFUL /*<< SysTick_CALIB_TENMS_Pos*/) /*!< SysTick CALIB: TENMS Mask */ /*@} end of group CMSIS_SysTick */ /** \ingroup CMSIS_core_register \defgroup CMSIS_ITM Instrumentation Trace Macrocell (ITM) \brief Type definitions for the Instrumentation Trace Macrocell (ITM) @{ */ /** \brief Structure type to access the Instrumentation Trace Macrocell Register (ITM). */ typedef struct { __O union { __O uint8_t u8; /*!< Offset: 0x000 ( /W) ITM Stimulus Port 8-bit */ __O uint16_t u16; /*!< Offset: 0x000 ( /W) ITM Stimulus Port 16-bit */ __O uint32_t u32; /*!< Offset: 0x000 ( /W) ITM Stimulus Port 32-bit */ } PORT [32]; /*!< Offset: 0x000 ( /W) ITM Stimulus Port Registers */ uint32_t RESERVED0[864]; __IO uint32_t TER; /*!< Offset: 0xE00 (R/W) ITM Trace Enable Register */ uint32_t RESERVED1[15]; __IO uint32_t TPR; /*!< Offset: 0xE40 (R/W) ITM Trace Privilege Register */ uint32_t RESERVED2[15]; __IO uint32_t TCR; /*!< Offset: 0xE80 (R/W) ITM Trace Control Register */ uint32_t RESERVED3[29]; __O uint32_t IWR; /*!< Offset: 0xEF8 ( /W) ITM Integration Write Register */ __I uint32_t IRR; /*!< Offset: 0xEFC (R/ ) ITM Integration Read Register */ __IO uint32_t IMCR; /*!< Offset: 0xF00 (R/W) ITM Integration Mode Control Register */ uint32_t RESERVED4[43]; __O uint32_t LAR; /*!< Offset: 0xFB0 ( /W) ITM Lock Access Register */ __I uint32_t LSR; /*!< Offset: 0xFB4 (R/ ) ITM Lock Status Register */ uint32_t RESERVED5[6]; __I uint32_t PID4; /*!< Offset: 0xFD0 (R/ ) ITM Peripheral Identification Register #4 */ __I uint32_t PID5; /*!< Offset: 0xFD4 (R/ ) ITM Peripheral Identification Register #5 */ __I uint32_t PID6; /*!< Offset: 0xFD8 (R/ ) ITM Peripheral Identification Register #6 */ __I uint32_t PID7; /*!< Offset: 0xFDC (R/ ) ITM Peripheral Identification Register #7 */ __I uint32_t PID0; /*!< Offset: 0xFE0 (R/ ) ITM Peripheral Identification Register #0 */ __I uint32_t PID1; /*!< Offset: 0xFE4 (R/ ) ITM Peripheral Identification Register #1 */ __I uint32_t PID2; /*!< Offset: 0xFE8 (R/ ) ITM Peripheral Identification Register #2 */ __I uint32_t PID3; /*!< Offset: 0xFEC (R/ ) ITM Peripheral Identification Register #3 */ __I uint32_t CID0; /*!< Offset: 0xFF0 (R/ ) ITM Component Identification Register #0 */ __I uint32_t CID1; /*!< Offset: 0xFF4 (R/ ) ITM Component Identification Register #1 */ __I uint32_t CID2; /*!< Offset: 0xFF8 (R/ ) ITM Component Identification Register #2 */ __I uint32_t CID3; /*!< Offset: 0xFFC (R/ ) ITM Component Identification Register #3 */ } ITM_Type; /* ITM Trace Privilege Register Definitions */ #define ITM_TPR_PRIVMASK_Pos 0 /*!< ITM TPR: PRIVMASK Position */ #define ITM_TPR_PRIVMASK_Msk (0xFUL /*<< ITM_TPR_PRIVMASK_Pos*/) /*!< ITM TPR: PRIVMASK Mask */ /* ITM Trace Control Register Definitions */ #define ITM_TCR_BUSY_Pos 23 /*!< ITM TCR: BUSY Position */ #define ITM_TCR_BUSY_Msk (1UL << ITM_TCR_BUSY_Pos) /*!< ITM TCR: BUSY Mask */ #define ITM_TCR_TraceBusID_Pos 16 /*!< ITM TCR: ATBID Position */ #define ITM_TCR_TraceBusID_Msk (0x7FUL << ITM_TCR_TraceBusID_Pos) /*!< ITM TCR: ATBID Mask */ #define ITM_TCR_GTSFREQ_Pos 10 /*!< ITM TCR: Global timestamp frequency Position */ #define ITM_TCR_GTSFREQ_Msk (3UL << ITM_TCR_GTSFREQ_Pos) /*!< ITM TCR: Global timestamp frequency Mask */ #define ITM_TCR_TSPrescale_Pos 8 /*!< ITM TCR: TSPrescale Position */ #define ITM_TCR_TSPrescale_Msk (3UL << ITM_TCR_TSPrescale_Pos) /*!< ITM TCR: TSPrescale Mask */ #define ITM_TCR_SWOENA_Pos 4 /*!< ITM TCR: SWOENA Position */ #define ITM_TCR_SWOENA_Msk (1UL << ITM_TCR_SWOENA_Pos) /*!< ITM TCR: SWOENA Mask */ #define ITM_TCR_DWTENA_Pos 3 /*!< ITM TCR: DWTENA Position */ #define ITM_TCR_DWTENA_Msk (1UL << ITM_TCR_DWTENA_Pos) /*!< ITM TCR: DWTENA Mask */ #define ITM_TCR_SYNCENA_Pos 2 /*!< ITM TCR: SYNCENA Position */ #define ITM_TCR_SYNCENA_Msk (1UL << ITM_TCR_SYNCENA_Pos) /*!< ITM TCR: SYNCENA Mask */ #define ITM_TCR_TSENA_Pos 1 /*!< ITM TCR: TSENA Position */ #define ITM_TCR_TSENA_Msk (1UL << ITM_TCR_TSENA_Pos) /*!< ITM TCR: TSENA Mask */ #define ITM_TCR_ITMENA_Pos 0 /*!< ITM TCR: ITM Enable bit Position */ #define ITM_TCR_ITMENA_Msk (1UL /*<< ITM_TCR_ITMENA_Pos*/) /*!< ITM TCR: ITM Enable bit Mask */ /* ITM Integration Write Register Definitions */ #define ITM_IWR_ATVALIDM_Pos 0 /*!< ITM IWR: ATVALIDM Position */ #define ITM_IWR_ATVALIDM_Msk (1UL /*<< ITM_IWR_ATVALIDM_Pos*/) /*!< ITM IWR: ATVALIDM Mask */ /* ITM Integration Read Register Definitions */ #define ITM_IRR_ATREADYM_Pos 0 /*!< ITM IRR: ATREADYM Position */ #define ITM_IRR_ATREADYM_Msk (1UL /*<< ITM_IRR_ATREADYM_Pos*/) /*!< ITM IRR: ATREADYM Mask */ /* ITM Integration Mode Control Register Definitions */ #define ITM_IMCR_INTEGRATION_Pos 0 /*!< ITM IMCR: INTEGRATION Position */ #define ITM_IMCR_INTEGRATION_Msk (1UL /*<< ITM_IMCR_INTEGRATION_Pos*/) /*!< ITM IMCR: INTEGRATION Mask */ /* ITM Lock Status Register Definitions */ #define ITM_LSR_ByteAcc_Pos 2 /*!< ITM LSR: ByteAcc Position */ #define ITM_LSR_ByteAcc_Msk (1UL << ITM_LSR_ByteAcc_Pos) /*!< ITM LSR: ByteAcc Mask */ #define ITM_LSR_Access_Pos 1 /*!< ITM LSR: Access Position */ #define ITM_LSR_Access_Msk (1UL << ITM_LSR_Access_Pos) /*!< ITM LSR: Access Mask */ #define ITM_LSR_Present_Pos 0 /*!< ITM LSR: Present Position */ #define ITM_LSR_Present_Msk (1UL /*<< ITM_LSR_Present_Pos*/) /*!< ITM LSR: Present Mask */ /*@}*/ /* end of group CMSIS_ITM */ /** \ingroup CMSIS_core_register \defgroup CMSIS_DWT Data Watchpoint and Trace (DWT) \brief Type definitions for the Data Watchpoint and Trace (DWT) @{ */ /** \brief Structure type to access the Data Watchpoint and Trace Register (DWT). */ typedef struct { __IO uint32_t CTRL; /*!< Offset: 0x000 (R/W) Control Register */ __IO uint32_t CYCCNT; /*!< Offset: 0x004 (R/W) Cycle Count Register */ __IO uint32_t CPICNT; /*!< Offset: 0x008 (R/W) CPI Count Register */ __IO uint32_t EXCCNT; /*!< Offset: 0x00C (R/W) Exception Overhead Count Register */ __IO uint32_t SLEEPCNT; /*!< Offset: 0x010 (R/W) Sleep Count Register */ __IO uint32_t LSUCNT; /*!< Offset: 0x014 (R/W) LSU Count Register */ __IO uint32_t FOLDCNT; /*!< Offset: 0x018 (R/W) Folded-instruction Count Register */ __I uint32_t PCSR; /*!< Offset: 0x01C (R/ ) Program Counter Sample Register */ __IO uint32_t COMP0; /*!< Offset: 0x020 (R/W) Comparator Register 0 */ __IO uint32_t MASK0; /*!< Offset: 0x024 (R/W) Mask Register 0 */ __IO uint32_t FUNCTION0; /*!< Offset: 0x028 (R/W) Function Register 0 */ uint32_t RESERVED0[1]; __IO uint32_t COMP1; /*!< Offset: 0x030 (R/W) Comparator Register 1 */ __IO uint32_t MASK1; /*!< Offset: 0x034 (R/W) Mask Register 1 */ __IO uint32_t FUNCTION1; /*!< Offset: 0x038 (R/W) Function Register 1 */ uint32_t RESERVED1[1]; __IO uint32_t COMP2; /*!< Offset: 0x040 (R/W) Comparator Register 2 */ __IO uint32_t MASK2; /*!< Offset: 0x044 (R/W) Mask Register 2 */ __IO uint32_t FUNCTION2; /*!< Offset: 0x048 (R/W) Function Register 2 */ uint32_t RESERVED2[1]; __IO uint32_t COMP3; /*!< Offset: 0x050 (R/W) Comparator Register 3 */ __IO uint32_t MASK3; /*!< Offset: 0x054 (R/W) Mask Register 3 */ __IO uint32_t FUNCTION3; /*!< Offset: 0x058 (R/W) Function Register 3 */ uint32_t RESERVED3[981]; __O uint32_t LAR; /*!< Offset: 0xFB0 ( W) Lock Access Register */ __I uint32_t LSR; /*!< Offset: 0xFB4 (R ) Lock Status Register */ } DWT_Type; /* DWT Control Register Definitions */ #define DWT_CTRL_NUMCOMP_Pos 28 /*!< DWT CTRL: NUMCOMP Position */ #define DWT_CTRL_NUMCOMP_Msk (0xFUL << DWT_CTRL_NUMCOMP_Pos) /*!< DWT CTRL: NUMCOMP Mask */ #define DWT_CTRL_NOTRCPKT_Pos 27 /*!< DWT CTRL: NOTRCPKT Position */ #define DWT_CTRL_NOTRCPKT_Msk (0x1UL << DWT_CTRL_NOTRCPKT_Pos) /*!< DWT CTRL: NOTRCPKT Mask */ #define DWT_CTRL_NOEXTTRIG_Pos 26 /*!< DWT CTRL: NOEXTTRIG Position */ #define DWT_CTRL_NOEXTTRIG_Msk (0x1UL << DWT_CTRL_NOEXTTRIG_Pos) /*!< DWT CTRL: NOEXTTRIG Mask */ #define DWT_CTRL_NOCYCCNT_Pos 25 /*!< DWT CTRL: NOCYCCNT Position */ #define DWT_CTRL_NOCYCCNT_Msk (0x1UL << DWT_CTRL_NOCYCCNT_Pos) /*!< DWT CTRL: NOCYCCNT Mask */ #define DWT_CTRL_NOPRFCNT_Pos 24 /*!< DWT CTRL: NOPRFCNT Position */ #define DWT_CTRL_NOPRFCNT_Msk (0x1UL << DWT_CTRL_NOPRFCNT_Pos) /*!< DWT CTRL: NOPRFCNT Mask */ #define DWT_CTRL_CYCEVTENA_Pos 22 /*!< DWT CTRL: CYCEVTENA Position */ #define DWT_CTRL_CYCEVTENA_Msk (0x1UL << DWT_CTRL_CYCEVTENA_Pos) /*!< DWT CTRL: CYCEVTENA Mask */ #define DWT_CTRL_FOLDEVTENA_Pos 21 /*!< DWT CTRL: FOLDEVTENA Position */ #define DWT_CTRL_FOLDEVTENA_Msk (0x1UL << DWT_CTRL_FOLDEVTENA_Pos) /*!< DWT CTRL: FOLDEVTENA Mask */ #define DWT_CTRL_LSUEVTENA_Pos 20 /*!< DWT CTRL: LSUEVTENA Position */ #define DWT_CTRL_LSUEVTENA_Msk (0x1UL << DWT_CTRL_LSUEVTENA_Pos) /*!< DWT CTRL: LSUEVTENA Mask */ #define DWT_CTRL_SLEEPEVTENA_Pos 19 /*!< DWT CTRL: SLEEPEVTENA Position */ #define DWT_CTRL_SLEEPEVTENA_Msk (0x1UL << DWT_CTRL_SLEEPEVTENA_Pos) /*!< DWT CTRL: SLEEPEVTENA Mask */ #define DWT_CTRL_EXCEVTENA_Pos 18 /*!< DWT CTRL: EXCEVTENA Position */ #define DWT_CTRL_EXCEVTENA_Msk (0x1UL << DWT_CTRL_EXCEVTENA_Pos) /*!< DWT CTRL: EXCEVTENA Mask */ #define DWT_CTRL_CPIEVTENA_Pos 17 /*!< DWT CTRL: CPIEVTENA Position */ #define DWT_CTRL_CPIEVTENA_Msk (0x1UL << DWT_CTRL_CPIEVTENA_Pos) /*!< DWT CTRL: CPIEVTENA Mask */ #define DWT_CTRL_EXCTRCENA_Pos 16 /*!< DWT CTRL: EXCTRCENA Position */ #define DWT_CTRL_EXCTRCENA_Msk (0x1UL << DWT_CTRL_EXCTRCENA_Pos) /*!< DWT CTRL: EXCTRCENA Mask */ #define DWT_CTRL_PCSAMPLENA_Pos 12 /*!< DWT CTRL: PCSAMPLENA Position */ #define DWT_CTRL_PCSAMPLENA_Msk (0x1UL << DWT_CTRL_PCSAMPLENA_Pos) /*!< DWT CTRL: PCSAMPLENA Mask */ #define DWT_CTRL_SYNCTAP_Pos 10 /*!< DWT CTRL: SYNCTAP Position */ #define DWT_CTRL_SYNCTAP_Msk (0x3UL << DWT_CTRL_SYNCTAP_Pos) /*!< DWT CTRL: SYNCTAP Mask */ #define DWT_CTRL_CYCTAP_Pos 9 /*!< DWT CTRL: CYCTAP Position */ #define DWT_CTRL_CYCTAP_Msk (0x1UL << DWT_CTRL_CYCTAP_Pos) /*!< DWT CTRL: CYCTAP Mask */ #define DWT_CTRL_POSTINIT_Pos 5 /*!< DWT CTRL: POSTINIT Position */ #define DWT_CTRL_POSTINIT_Msk (0xFUL << DWT_CTRL_POSTINIT_Pos) /*!< DWT CTRL: POSTINIT Mask */ #define DWT_CTRL_POSTPRESET_Pos 1 /*!< DWT CTRL: POSTPRESET Position */ #define DWT_CTRL_POSTPRESET_Msk (0xFUL << DWT_CTRL_POSTPRESET_Pos) /*!< DWT CTRL: POSTPRESET Mask */ #define DWT_CTRL_CYCCNTENA_Pos 0 /*!< DWT CTRL: CYCCNTENA Position */ #define DWT_CTRL_CYCCNTENA_Msk (0x1UL /*<< DWT_CTRL_CYCCNTENA_Pos*/) /*!< DWT CTRL: CYCCNTENA Mask */ /* DWT CPI Count Register Definitions */ #define DWT_CPICNT_CPICNT_Pos 0 /*!< DWT CPICNT: CPICNT Position */ #define DWT_CPICNT_CPICNT_Msk (0xFFUL /*<< DWT_CPICNT_CPICNT_Pos*/) /*!< DWT CPICNT: CPICNT Mask */ /* DWT Exception Overhead Count Register Definitions */ #define DWT_EXCCNT_EXCCNT_Pos 0 /*!< DWT EXCCNT: EXCCNT Position */ #define DWT_EXCCNT_EXCCNT_Msk (0xFFUL /*<< DWT_EXCCNT_EXCCNT_Pos*/) /*!< DWT EXCCNT: EXCCNT Mask */ /* DWT Sleep Count Register Definitions */ #define DWT_SLEEPCNT_SLEEPCNT_Pos 0 /*!< DWT SLEEPCNT: SLEEPCNT Position */ #define DWT_SLEEPCNT_SLEEPCNT_Msk (0xFFUL /*<< DWT_SLEEPCNT_SLEEPCNT_Pos*/) /*!< DWT SLEEPCNT: SLEEPCNT Mask */ /* DWT LSU Count Register Definitions */ #define DWT_LSUCNT_LSUCNT_Pos 0 /*!< DWT LSUCNT: LSUCNT Position */ #define DWT_LSUCNT_LSUCNT_Msk (0xFFUL /*<< DWT_LSUCNT_LSUCNT_Pos*/) /*!< DWT LSUCNT: LSUCNT Mask */ /* DWT Folded-instruction Count Register Definitions */ #define DWT_FOLDCNT_FOLDCNT_Pos 0 /*!< DWT FOLDCNT: FOLDCNT Position */ #define DWT_FOLDCNT_FOLDCNT_Msk (0xFFUL /*<< DWT_FOLDCNT_FOLDCNT_Pos*/) /*!< DWT FOLDCNT: FOLDCNT Mask */ /* DWT Comparator Mask Register Definitions */ #define DWT_MASK_MASK_Pos 0 /*!< DWT MASK: MASK Position */ #define DWT_MASK_MASK_Msk (0x1FUL /*<< DWT_MASK_MASK_Pos*/) /*!< DWT MASK: MASK Mask */ /* DWT Comparator Function Register Definitions */ #define DWT_FUNCTION_MATCHED_Pos 24 /*!< DWT FUNCTION: MATCHED Position */ #define DWT_FUNCTION_MATCHED_Msk (0x1UL << DWT_FUNCTION_MATCHED_Pos) /*!< DWT FUNCTION: MATCHED Mask */ #define DWT_FUNCTION_DATAVADDR1_Pos 16 /*!< DWT FUNCTION: DATAVADDR1 Position */ #define DWT_FUNCTION_DATAVADDR1_Msk (0xFUL << DWT_FUNCTION_DATAVADDR1_Pos) /*!< DWT FUNCTION: DATAVADDR1 Mask */ #define DWT_FUNCTION_DATAVADDR0_Pos 12 /*!< DWT FUNCTION: DATAVADDR0 Position */ #define DWT_FUNCTION_DATAVADDR0_Msk (0xFUL << DWT_FUNCTION_DATAVADDR0_Pos) /*!< DWT FUNCTION: DATAVADDR0 Mask */ #define DWT_FUNCTION_DATAVSIZE_Pos 10 /*!< DWT FUNCTION: DATAVSIZE Position */ #define DWT_FUNCTION_DATAVSIZE_Msk (0x3UL << DWT_FUNCTION_DATAVSIZE_Pos) /*!< DWT FUNCTION: DATAVSIZE Mask */ #define DWT_FUNCTION_LNK1ENA_Pos 9 /*!< DWT FUNCTION: LNK1ENA Position */ #define DWT_FUNCTION_LNK1ENA_Msk (0x1UL << DWT_FUNCTION_LNK1ENA_Pos) /*!< DWT FUNCTION: LNK1ENA Mask */ #define DWT_FUNCTION_DATAVMATCH_Pos 8 /*!< DWT FUNCTION: DATAVMATCH Position */ #define DWT_FUNCTION_DATAVMATCH_Msk (0x1UL << DWT_FUNCTION_DATAVMATCH_Pos) /*!< DWT FUNCTION: DATAVMATCH Mask */ #define DWT_FUNCTION_CYCMATCH_Pos 7 /*!< DWT FUNCTION: CYCMATCH Position */ #define DWT_FUNCTION_CYCMATCH_Msk (0x1UL << DWT_FUNCTION_CYCMATCH_Pos) /*!< DWT FUNCTION: CYCMATCH Mask */ #define DWT_FUNCTION_EMITRANGE_Pos 5 /*!< DWT FUNCTION: EMITRANGE Position */ #define DWT_FUNCTION_EMITRANGE_Msk (0x1UL << DWT_FUNCTION_EMITRANGE_Pos) /*!< DWT FUNCTION: EMITRANGE Mask */ #define DWT_FUNCTION_FUNCTION_Pos 0 /*!< DWT FUNCTION: FUNCTION Position */ #define DWT_FUNCTION_FUNCTION_Msk (0xFUL /*<< DWT_FUNCTION_FUNCTION_Pos*/) /*!< DWT FUNCTION: FUNCTION Mask */ /*@}*/ /* end of group CMSIS_DWT */ /** \ingroup CMSIS_core_register \defgroup CMSIS_TPI Trace Port Interface (TPI) \brief Type definitions for the Trace Port Interface (TPI) @{ */ /** \brief Structure type to access the Trace Port Interface Register (TPI). */ typedef struct { __IO uint32_t SSPSR; /*!< Offset: 0x000 (R/ ) Supported Parallel Port Size Register */ __IO uint32_t CSPSR; /*!< Offset: 0x004 (R/W) Current Parallel Port Size Register */ uint32_t RESERVED0[2]; __IO uint32_t ACPR; /*!< Offset: 0x010 (R/W) Asynchronous Clock Prescaler Register */ uint32_t RESERVED1[55]; __IO uint32_t SPPR; /*!< Offset: 0x0F0 (R/W) Selected Pin Protocol Register */ uint32_t RESERVED2[131]; __I uint32_t FFSR; /*!< Offset: 0x300 (R/ ) Formatter and Flush Status Register */ __IO uint32_t FFCR; /*!< Offset: 0x304 (R/W) Formatter and Flush Control Register */ __I uint32_t FSCR; /*!< Offset: 0x308 (R/ ) Formatter Synchronization Counter Register */ uint32_t RESERVED3[759]; __I uint32_t TRIGGER; /*!< Offset: 0xEE8 (R/ ) TRIGGER */ __I uint32_t FIFO0; /*!< Offset: 0xEEC (R/ ) Integration ETM Data */ __I uint32_t ITATBCTR2; /*!< Offset: 0xEF0 (R/ ) ITATBCTR2 */ uint32_t RESERVED4[1]; __I uint32_t ITATBCTR0; /*!< Offset: 0xEF8 (R/ ) ITATBCTR0 */ __I uint32_t FIFO1; /*!< Offset: 0xEFC (R/ ) Integration ITM Data */ __IO uint32_t ITCTRL; /*!< Offset: 0xF00 (R/W) Integration Mode Control */ uint32_t RESERVED5[39]; __IO uint32_t CLAIMSET; /*!< Offset: 0xFA0 (R/W) Claim tag set */ __IO uint32_t CLAIMCLR; /*!< Offset: 0xFA4 (R/W) Claim tag clear */ uint32_t RESERVED7[8]; __I uint32_t DEVID; /*!< Offset: 0xFC8 (R/ ) TPIU_DEVID */ __I uint32_t DEVTYPE; /*!< Offset: 0xFCC (R/ ) TPIU_DEVTYPE */ } TPI_Type; /* TPI Asynchronous Clock Prescaler Register Definitions */ #define TPI_ACPR_PRESCALER_Pos 0 /*!< TPI ACPR: PRESCALER Position */ #define TPI_ACPR_PRESCALER_Msk (0x1FFFUL /*<< TPI_ACPR_PRESCALER_Pos*/) /*!< TPI ACPR: PRESCALER Mask */ /* TPI Selected Pin Protocol Register Definitions */ #define TPI_SPPR_TXMODE_Pos 0 /*!< TPI SPPR: TXMODE Position */ #define TPI_SPPR_TXMODE_Msk (0x3UL /*<< TPI_SPPR_TXMODE_Pos*/) /*!< TPI SPPR: TXMODE Mask */ /* TPI Formatter and Flush Status Register Definitions */ #define TPI_FFSR_FtNonStop_Pos 3 /*!< TPI FFSR: FtNonStop Position */ #define TPI_FFSR_FtNonStop_Msk (0x1UL << TPI_FFSR_FtNonStop_Pos) /*!< TPI FFSR: FtNonStop Mask */ #define TPI_FFSR_TCPresent_Pos 2 /*!< TPI FFSR: TCPresent Position */ #define TPI_FFSR_TCPresent_Msk (0x1UL << TPI_FFSR_TCPresent_Pos) /*!< TPI FFSR: TCPresent Mask */ #define TPI_FFSR_FtStopped_Pos 1 /*!< TPI FFSR: FtStopped Position */ #define TPI_FFSR_FtStopped_Msk (0x1UL << TPI_FFSR_FtStopped_Pos) /*!< TPI FFSR: FtStopped Mask */ #define TPI_FFSR_FlInProg_Pos 0 /*!< TPI FFSR: FlInProg Position */ #define TPI_FFSR_FlInProg_Msk (0x1UL /*<< TPI_FFSR_FlInProg_Pos*/) /*!< TPI FFSR: FlInProg Mask */ /* TPI Formatter and Flush Control Register Definitions */ #define TPI_FFCR_TrigIn_Pos 8 /*!< TPI FFCR: TrigIn Position */ #define TPI_FFCR_TrigIn_Msk (0x1UL << TPI_FFCR_TrigIn_Pos) /*!< TPI FFCR: TrigIn Mask */ #define TPI_FFCR_EnFCont_Pos 1 /*!< TPI FFCR: EnFCont Position */ #define TPI_FFCR_EnFCont_Msk (0x1UL << TPI_FFCR_EnFCont_Pos) /*!< TPI FFCR: EnFCont Mask */ /* TPI TRIGGER Register Definitions */ #define TPI_TRIGGER_TRIGGER_Pos 0 /*!< TPI TRIGGER: TRIGGER Position */ #define TPI_TRIGGER_TRIGGER_Msk (0x1UL /*<< TPI_TRIGGER_TRIGGER_Pos*/) /*!< TPI TRIGGER: TRIGGER Mask */ /* TPI Integration ETM Data Register Definitions (FIFO0) */ #define TPI_FIFO0_ITM_ATVALID_Pos 29 /*!< TPI FIFO0: ITM_ATVALID Position */ #define TPI_FIFO0_ITM_ATVALID_Msk (0x3UL << TPI_FIFO0_ITM_ATVALID_Pos) /*!< TPI FIFO0: ITM_ATVALID Mask */ #define TPI_FIFO0_ITM_bytecount_Pos 27 /*!< TPI FIFO0: ITM_bytecount Position */ #define TPI_FIFO0_ITM_bytecount_Msk (0x3UL << TPI_FIFO0_ITM_bytecount_Pos) /*!< TPI FIFO0: ITM_bytecount Mask */ #define TPI_FIFO0_ETM_ATVALID_Pos 26 /*!< TPI FIFO0: ETM_ATVALID Position */ #define TPI_FIFO0_ETM_ATVALID_Msk (0x3UL << TPI_FIFO0_ETM_ATVALID_Pos) /*!< TPI FIFO0: ETM_ATVALID Mask */ #define TPI_FIFO0_ETM_bytecount_Pos 24 /*!< TPI FIFO0: ETM_bytecount Position */ #define TPI_FIFO0_ETM_bytecount_Msk (0x3UL << TPI_FIFO0_ETM_bytecount_Pos) /*!< TPI FIFO0: ETM_bytecount Mask */ #define TPI_FIFO0_ETM2_Pos 16 /*!< TPI FIFO0: ETM2 Position */ #define TPI_FIFO0_ETM2_Msk (0xFFUL << TPI_FIFO0_ETM2_Pos) /*!< TPI FIFO0: ETM2 Mask */ #define TPI_FIFO0_ETM1_Pos 8 /*!< TPI FIFO0: ETM1 Position */ #define TPI_FIFO0_ETM1_Msk (0xFFUL << TPI_FIFO0_ETM1_Pos) /*!< TPI FIFO0: ETM1 Mask */ #define TPI_FIFO0_ETM0_Pos 0 /*!< TPI FIFO0: ETM0 Position */ #define TPI_FIFO0_ETM0_Msk (0xFFUL /*<< TPI_FIFO0_ETM0_Pos*/) /*!< TPI FIFO0: ETM0 Mask */ /* TPI ITATBCTR2 Register Definitions */ #define TPI_ITATBCTR2_ATREADY_Pos 0 /*!< TPI ITATBCTR2: ATREADY Position */ #define TPI_ITATBCTR2_ATREADY_Msk (0x1UL /*<< TPI_ITATBCTR2_ATREADY_Pos*/) /*!< TPI ITATBCTR2: ATREADY Mask */ /* TPI Integration ITM Data Register Definitions (FIFO1) */ #define TPI_FIFO1_ITM_ATVALID_Pos 29 /*!< TPI FIFO1: ITM_ATVALID Position */ #define TPI_FIFO1_ITM_ATVALID_Msk (0x3UL << TPI_FIFO1_ITM_ATVALID_Pos) /*!< TPI FIFO1: ITM_ATVALID Mask */ #define TPI_FIFO1_ITM_bytecount_Pos 27 /*!< TPI FIFO1: ITM_bytecount Position */ #define TPI_FIFO1_ITM_bytecount_Msk (0x3UL << TPI_FIFO1_ITM_bytecount_Pos) /*!< TPI FIFO1: ITM_bytecount Mask */ #define TPI_FIFO1_ETM_ATVALID_Pos 26 /*!< TPI FIFO1: ETM_ATVALID Position */ #define TPI_FIFO1_ETM_ATVALID_Msk (0x3UL << TPI_FIFO1_ETM_ATVALID_Pos) /*!< TPI FIFO1: ETM_ATVALID Mask */ #define TPI_FIFO1_ETM_bytecount_Pos 24 /*!< TPI FIFO1: ETM_bytecount Position */ #define TPI_FIFO1_ETM_bytecount_Msk (0x3UL << TPI_FIFO1_ETM_bytecount_Pos) /*!< TPI FIFO1: ETM_bytecount Mask */ #define TPI_FIFO1_ITM2_Pos 16 /*!< TPI FIFO1: ITM2 Position */ #define TPI_FIFO1_ITM2_Msk (0xFFUL << TPI_FIFO1_ITM2_Pos) /*!< TPI FIFO1: ITM2 Mask */ #define TPI_FIFO1_ITM1_Pos 8 /*!< TPI FIFO1: ITM1 Position */ #define TPI_FIFO1_ITM1_Msk (0xFFUL << TPI_FIFO1_ITM1_Pos) /*!< TPI FIFO1: ITM1 Mask */ #define TPI_FIFO1_ITM0_Pos 0 /*!< TPI FIFO1: ITM0 Position */ #define TPI_FIFO1_ITM0_Msk (0xFFUL /*<< TPI_FIFO1_ITM0_Pos*/) /*!< TPI FIFO1: ITM0 Mask */ /* TPI ITATBCTR0 Register Definitions */ #define TPI_ITATBCTR0_ATREADY_Pos 0 /*!< TPI ITATBCTR0: ATREADY Position */ #define TPI_ITATBCTR0_ATREADY_Msk (0x1UL /*<< TPI_ITATBCTR0_ATREADY_Pos*/) /*!< TPI ITATBCTR0: ATREADY Mask */ /* TPI Integration Mode Control Register Definitions */ #define TPI_ITCTRL_Mode_Pos 0 /*!< TPI ITCTRL: Mode Position */ #define TPI_ITCTRL_Mode_Msk (0x1UL /*<< TPI_ITCTRL_Mode_Pos*/) /*!< TPI ITCTRL: Mode Mask */ /* TPI DEVID Register Definitions */ #define TPI_DEVID_NRZVALID_Pos 11 /*!< TPI DEVID: NRZVALID Position */ #define TPI_DEVID_NRZVALID_Msk (0x1UL << TPI_DEVID_NRZVALID_Pos) /*!< TPI DEVID: NRZVALID Mask */ #define TPI_DEVID_MANCVALID_Pos 10 /*!< TPI DEVID: MANCVALID Position */ #define TPI_DEVID_MANCVALID_Msk (0x1UL << TPI_DEVID_MANCVALID_Pos) /*!< TPI DEVID: MANCVALID Mask */ #define TPI_DEVID_PTINVALID_Pos 9 /*!< TPI DEVID: PTINVALID Position */ #define TPI_DEVID_PTINVALID_Msk (0x1UL << TPI_DEVID_PTINVALID_Pos) /*!< TPI DEVID: PTINVALID Mask */ #define TPI_DEVID_MinBufSz_Pos 6 /*!< TPI DEVID: MinBufSz Position */ #define TPI_DEVID_MinBufSz_Msk (0x7UL << TPI_DEVID_MinBufSz_Pos) /*!< TPI DEVID: MinBufSz Mask */ #define TPI_DEVID_AsynClkIn_Pos 5 /*!< TPI DEVID: AsynClkIn Position */ #define TPI_DEVID_AsynClkIn_Msk (0x1UL << TPI_DEVID_AsynClkIn_Pos) /*!< TPI DEVID: AsynClkIn Mask */ #define TPI_DEVID_NrTraceInput_Pos 0 /*!< TPI DEVID: NrTraceInput Position */ #define TPI_DEVID_NrTraceInput_Msk (0x1FUL /*<< TPI_DEVID_NrTraceInput_Pos*/) /*!< TPI DEVID: NrTraceInput Mask */ /* TPI DEVTYPE Register Definitions */ #define TPI_DEVTYPE_MajorType_Pos 4 /*!< TPI DEVTYPE: MajorType Position */ #define TPI_DEVTYPE_MajorType_Msk (0xFUL << TPI_DEVTYPE_MajorType_Pos) /*!< TPI DEVTYPE: MajorType Mask */ #define TPI_DEVTYPE_SubType_Pos 0 /*!< TPI DEVTYPE: SubType Position */ #define TPI_DEVTYPE_SubType_Msk (0xFUL /*<< TPI_DEVTYPE_SubType_Pos*/) /*!< TPI DEVTYPE: SubType Mask */ /*@}*/ /* end of group CMSIS_TPI */ #if (__MPU_PRESENT == 1) /** \ingroup CMSIS_core_register \defgroup CMSIS_MPU Memory Protection Unit (MPU) \brief Type definitions for the Memory Protection Unit (MPU) @{ */ /** \brief Structure type to access the Memory Protection Unit (MPU). */ typedef struct { __I uint32_t TYPE; /*!< Offset: 0x000 (R/ ) MPU Type Register */ __IO uint32_t CTRL; /*!< Offset: 0x004 (R/W) MPU Control Register */ __IO uint32_t RNR; /*!< Offset: 0x008 (R/W) MPU Region RNRber Register */ __IO uint32_t RBAR; /*!< Offset: 0x00C (R/W) MPU Region Base Address Register */ __IO uint32_t RASR; /*!< Offset: 0x010 (R/W) MPU Region Attribute and Size Register */ __IO uint32_t RBAR_A1; /*!< Offset: 0x014 (R/W) MPU Alias 1 Region Base Address Register */ __IO uint32_t RASR_A1; /*!< Offset: 0x018 (R/W) MPU Alias 1 Region Attribute and Size Register */ __IO uint32_t RBAR_A2; /*!< Offset: 0x01C (R/W) MPU Alias 2 Region Base Address Register */ __IO uint32_t RASR_A2; /*!< Offset: 0x020 (R/W) MPU Alias 2 Region Attribute and Size Register */ __IO uint32_t RBAR_A3; /*!< Offset: 0x024 (R/W) MPU Alias 3 Region Base Address Register */ __IO uint32_t RASR_A3; /*!< Offset: 0x028 (R/W) MPU Alias 3 Region Attribute and Size Register */ } MPU_Type; /* MPU Type Register */ #define MPU_TYPE_IREGION_Pos 16 /*!< MPU TYPE: IREGION Position */ #define MPU_TYPE_IREGION_Msk (0xFFUL << MPU_TYPE_IREGION_Pos) /*!< MPU TYPE: IREGION Mask */ #define MPU_TYPE_DREGION_Pos 8 /*!< MPU TYPE: DREGION Position */ #define MPU_TYPE_DREGION_Msk (0xFFUL << MPU_TYPE_DREGION_Pos) /*!< MPU TYPE: DREGION Mask */ #define MPU_TYPE_SEPARATE_Pos 0 /*!< MPU TYPE: SEPARATE Position */ #define MPU_TYPE_SEPARATE_Msk (1UL /*<< MPU_TYPE_SEPARATE_Pos*/) /*!< MPU TYPE: SEPARATE Mask */ /* MPU Control Register */ #define MPU_CTRL_PRIVDEFENA_Pos 2 /*!< MPU CTRL: PRIVDEFENA Position */ #define MPU_CTRL_PRIVDEFENA_Msk (1UL << MPU_CTRL_PRIVDEFENA_Pos) /*!< MPU CTRL: PRIVDEFENA Mask */ #define MPU_CTRL_HFNMIENA_Pos 1 /*!< MPU CTRL: HFNMIENA Position */ #define MPU_CTRL_HFNMIENA_Msk (1UL << MPU_CTRL_HFNMIENA_Pos) /*!< MPU CTRL: HFNMIENA Mask */ #define MPU_CTRL_ENABLE_Pos 0 /*!< MPU CTRL: ENABLE Position */ #define MPU_CTRL_ENABLE_Msk (1UL /*<< MPU_CTRL_ENABLE_Pos*/) /*!< MPU CTRL: ENABLE Mask */ /* MPU Region Number Register */ #define MPU_RNR_REGION_Pos 0 /*!< MPU RNR: REGION Position */ #define MPU_RNR_REGION_Msk (0xFFUL /*<< MPU_RNR_REGION_Pos*/) /*!< MPU RNR: REGION Mask */ /* MPU Region Base Address Register */ #define MPU_RBAR_ADDR_Pos 5 /*!< MPU RBAR: ADDR Position */ #define MPU_RBAR_ADDR_Msk (0x7FFFFFFUL << MPU_RBAR_ADDR_Pos) /*!< MPU RBAR: ADDR Mask */ #define MPU_RBAR_VALID_Pos 4 /*!< MPU RBAR: VALID Position */ #define MPU_RBAR_VALID_Msk (1UL << MPU_RBAR_VALID_Pos) /*!< MPU RBAR: VALID Mask */ #define MPU_RBAR_REGION_Pos 0 /*!< MPU RBAR: REGION Position */ #define MPU_RBAR_REGION_Msk (0xFUL /*<< MPU_RBAR_REGION_Pos*/) /*!< MPU RBAR: REGION Mask */ /* MPU Region Attribute and Size Register */ #define MPU_RASR_ATTRS_Pos 16 /*!< MPU RASR: MPU Region Attribute field Position */ #define MPU_RASR_ATTRS_Msk (0xFFFFUL << MPU_RASR_ATTRS_Pos) /*!< MPU RASR: MPU Region Attribute field Mask */ #define MPU_RASR_XN_Pos 28 /*!< MPU RASR: ATTRS.XN Position */ #define MPU_RASR_XN_Msk (1UL << MPU_RASR_XN_Pos) /*!< MPU RASR: ATTRS.XN Mask */ #define MPU_RASR_AP_Pos 24 /*!< MPU RASR: ATTRS.AP Position */ #define MPU_RASR_AP_Msk (0x7UL << MPU_RASR_AP_Pos) /*!< MPU RASR: ATTRS.AP Mask */ #define MPU_RASR_TEX_Pos 19 /*!< MPU RASR: ATTRS.TEX Position */ #define MPU_RASR_TEX_Msk (0x7UL << MPU_RASR_TEX_Pos) /*!< MPU RASR: ATTRS.TEX Mask */ #define MPU_RASR_S_Pos 18 /*!< MPU RASR: ATTRS.S Position */ #define MPU_RASR_S_Msk (1UL << MPU_RASR_S_Pos) /*!< MPU RASR: ATTRS.S Mask */ #define MPU_RASR_C_Pos 17 /*!< MPU RASR: ATTRS.C Position */ #define MPU_RASR_C_Msk (1UL << MPU_RASR_C_Pos) /*!< MPU RASR: ATTRS.C Mask */ #define MPU_RASR_B_Pos 16 /*!< MPU RASR: ATTRS.B Position */ #define MPU_RASR_B_Msk (1UL << MPU_RASR_B_Pos) /*!< MPU RASR: ATTRS.B Mask */ #define MPU_RASR_SRD_Pos 8 /*!< MPU RASR: Sub-Region Disable Position */ #define MPU_RASR_SRD_Msk (0xFFUL << MPU_RASR_SRD_Pos) /*!< MPU RASR: Sub-Region Disable Mask */ #define MPU_RASR_SIZE_Pos 1 /*!< MPU RASR: Region Size Field Position */ #define MPU_RASR_SIZE_Msk (0x1FUL << MPU_RASR_SIZE_Pos) /*!< MPU RASR: Region Size Field Mask */ #define MPU_RASR_ENABLE_Pos 0 /*!< MPU RASR: Region enable bit Position */ #define MPU_RASR_ENABLE_Msk (1UL /*<< MPU_RASR_ENABLE_Pos*/) /*!< MPU RASR: Region enable bit Disable Mask */ /*@} end of group CMSIS_MPU */ #endif #if (__FPU_PRESENT == 1) /** \ingroup CMSIS_core_register \defgroup CMSIS_FPU Floating Point Unit (FPU) \brief Type definitions for the Floating Point Unit (FPU) @{ */ /** \brief Structure type to access the Floating Point Unit (FPU). */ typedef struct { uint32_t RESERVED0[1]; __IO uint32_t FPCCR; /*!< Offset: 0x004 (R/W) Floating-Point Context Control Register */ __IO uint32_t FPCAR; /*!< Offset: 0x008 (R/W) Floating-Point Context Address Register */ __IO uint32_t FPDSCR; /*!< Offset: 0x00C (R/W) Floating-Point Default Status Control Register */ __I uint32_t MVFR0; /*!< Offset: 0x010 (R/ ) Media and FP Feature Register 0 */ __I uint32_t MVFR1; /*!< Offset: 0x014 (R/ ) Media and FP Feature Register 1 */ __I uint32_t MVFR2; /*!< Offset: 0x018 (R/ ) Media and FP Feature Register 2 */ } FPU_Type; /* Floating-Point Context Control Register */ #define FPU_FPCCR_ASPEN_Pos 31 /*!< FPCCR: ASPEN bit Position */ #define FPU_FPCCR_ASPEN_Msk (1UL << FPU_FPCCR_ASPEN_Pos) /*!< FPCCR: ASPEN bit Mask */ #define FPU_FPCCR_LSPEN_Pos 30 /*!< FPCCR: LSPEN Position */ #define FPU_FPCCR_LSPEN_Msk (1UL << FPU_FPCCR_LSPEN_Pos) /*!< FPCCR: LSPEN bit Mask */ #define FPU_FPCCR_MONRDY_Pos 8 /*!< FPCCR: MONRDY Position */ #define FPU_FPCCR_MONRDY_Msk (1UL << FPU_FPCCR_MONRDY_Pos) /*!< FPCCR: MONRDY bit Mask */ #define FPU_FPCCR_BFRDY_Pos 6 /*!< FPCCR: BFRDY Position */ #define FPU_FPCCR_BFRDY_Msk (1UL << FPU_FPCCR_BFRDY_Pos) /*!< FPCCR: BFRDY bit Mask */ #define FPU_FPCCR_MMRDY_Pos 5 /*!< FPCCR: MMRDY Position */ #define FPU_FPCCR_MMRDY_Msk (1UL << FPU_FPCCR_MMRDY_Pos) /*!< FPCCR: MMRDY bit Mask */ #define FPU_FPCCR_HFRDY_Pos 4 /*!< FPCCR: HFRDY Position */ #define FPU_FPCCR_HFRDY_Msk (1UL << FPU_FPCCR_HFRDY_Pos) /*!< FPCCR: HFRDY bit Mask */ #define FPU_FPCCR_THREAD_Pos 3 /*!< FPCCR: processor mode bit Position */ #define FPU_FPCCR_THREAD_Msk (1UL << FPU_FPCCR_THREAD_Pos) /*!< FPCCR: processor mode active bit Mask */ #define FPU_FPCCR_USER_Pos 1 /*!< FPCCR: privilege level bit Position */ #define FPU_FPCCR_USER_Msk (1UL << FPU_FPCCR_USER_Pos) /*!< FPCCR: privilege level bit Mask */ #define FPU_FPCCR_LSPACT_Pos 0 /*!< FPCCR: Lazy state preservation active bit Position */ #define FPU_FPCCR_LSPACT_Msk (1UL /*<< FPU_FPCCR_LSPACT_Pos*/) /*!< FPCCR: Lazy state preservation active bit Mask */ /* Floating-Point Context Address Register */ #define FPU_FPCAR_ADDRESS_Pos 3 /*!< FPCAR: ADDRESS bit Position */ #define FPU_FPCAR_ADDRESS_Msk (0x1FFFFFFFUL << FPU_FPCAR_ADDRESS_Pos) /*!< FPCAR: ADDRESS bit Mask */ /* Floating-Point Default Status Control Register */ #define FPU_FPDSCR_AHP_Pos 26 /*!< FPDSCR: AHP bit Position */ #define FPU_FPDSCR_AHP_Msk (1UL << FPU_FPDSCR_AHP_Pos) /*!< FPDSCR: AHP bit Mask */ #define FPU_FPDSCR_DN_Pos 25 /*!< FPDSCR: DN bit Position */ #define FPU_FPDSCR_DN_Msk (1UL << FPU_FPDSCR_DN_Pos) /*!< FPDSCR: DN bit Mask */ #define FPU_FPDSCR_FZ_Pos 24 /*!< FPDSCR: FZ bit Position */ #define FPU_FPDSCR_FZ_Msk (1UL << FPU_FPDSCR_FZ_Pos) /*!< FPDSCR: FZ bit Mask */ #define FPU_FPDSCR_RMode_Pos 22 /*!< FPDSCR: RMode bit Position */ #define FPU_FPDSCR_RMode_Msk (3UL << FPU_FPDSCR_RMode_Pos) /*!< FPDSCR: RMode bit Mask */ /* Media and FP Feature Register 0 */ #define FPU_MVFR0_FP_rounding_modes_Pos 28 /*!< MVFR0: FP rounding modes bits Position */ #define FPU_MVFR0_FP_rounding_modes_Msk (0xFUL << FPU_MVFR0_FP_rounding_modes_Pos) /*!< MVFR0: FP rounding modes bits Mask */ #define FPU_MVFR0_Short_vectors_Pos 24 /*!< MVFR0: Short vectors bits Position */ #define FPU_MVFR0_Short_vectors_Msk (0xFUL << FPU_MVFR0_Short_vectors_Pos) /*!< MVFR0: Short vectors bits Mask */ #define FPU_MVFR0_Square_root_Pos 20 /*!< MVFR0: Square root bits Position */ #define FPU_MVFR0_Square_root_Msk (0xFUL << FPU_MVFR0_Square_root_Pos) /*!< MVFR0: Square root bits Mask */ #define FPU_MVFR0_Divide_Pos 16 /*!< MVFR0: Divide bits Position */ #define FPU_MVFR0_Divide_Msk (0xFUL << FPU_MVFR0_Divide_Pos) /*!< MVFR0: Divide bits Mask */ #define FPU_MVFR0_FP_excep_trapping_Pos 12 /*!< MVFR0: FP exception trapping bits Position */ #define FPU_MVFR0_FP_excep_trapping_Msk (0xFUL << FPU_MVFR0_FP_excep_trapping_Pos) /*!< MVFR0: FP exception trapping bits Mask */ #define FPU_MVFR0_Double_precision_Pos 8 /*!< MVFR0: Double-precision bits Position */ #define FPU_MVFR0_Double_precision_Msk (0xFUL << FPU_MVFR0_Double_precision_Pos) /*!< MVFR0: Double-precision bits Mask */ #define FPU_MVFR0_Single_precision_Pos 4 /*!< MVFR0: Single-precision bits Position */ #define FPU_MVFR0_Single_precision_Msk (0xFUL << FPU_MVFR0_Single_precision_Pos) /*!< MVFR0: Single-precision bits Mask */ #define FPU_MVFR0_A_SIMD_registers_Pos 0 /*!< MVFR0: A_SIMD registers bits Position */ #define FPU_MVFR0_A_SIMD_registers_Msk (0xFUL /*<< FPU_MVFR0_A_SIMD_registers_Pos*/) /*!< MVFR0: A_SIMD registers bits Mask */ /* Media and FP Feature Register 1 */ #define FPU_MVFR1_FP_fused_MAC_Pos 28 /*!< MVFR1: FP fused MAC bits Position */ #define FPU_MVFR1_FP_fused_MAC_Msk (0xFUL << FPU_MVFR1_FP_fused_MAC_Pos) /*!< MVFR1: FP fused MAC bits Mask */ #define FPU_MVFR1_FP_HPFP_Pos 24 /*!< MVFR1: FP HPFP bits Position */ #define FPU_MVFR1_FP_HPFP_Msk (0xFUL << FPU_MVFR1_FP_HPFP_Pos) /*!< MVFR1: FP HPFP bits Mask */ #define FPU_MVFR1_D_NaN_mode_Pos 4 /*!< MVFR1: D_NaN mode bits Position */ #define FPU_MVFR1_D_NaN_mode_Msk (0xFUL << FPU_MVFR1_D_NaN_mode_Pos) /*!< MVFR1: D_NaN mode bits Mask */ #define FPU_MVFR1_FtZ_mode_Pos 0 /*!< MVFR1: FtZ mode bits Position */ #define FPU_MVFR1_FtZ_mode_Msk (0xFUL /*<< FPU_MVFR1_FtZ_mode_Pos*/) /*!< MVFR1: FtZ mode bits Mask */ /* Media and FP Feature Register 2 */ /*@} end of group CMSIS_FPU */ #endif /** \ingroup CMSIS_core_register \defgroup CMSIS_CoreDebug Core Debug Registers (CoreDebug) \brief Type definitions for the Core Debug Registers @{ */ /** \brief Structure type to access the Core Debug Register (CoreDebug). */ typedef struct { __IO uint32_t DHCSR; /*!< Offset: 0x000 (R/W) Debug Halting Control and Status Register */ __O uint32_t DCRSR; /*!< Offset: 0x004 ( /W) Debug Core Register Selector Register */ __IO uint32_t DCRDR; /*!< Offset: 0x008 (R/W) Debug Core Register Data Register */ __IO uint32_t DEMCR; /*!< Offset: 0x00C (R/W) Debug Exception and Monitor Control Register */ } CoreDebug_Type; /* Debug Halting Control and Status Register */ #define CoreDebug_DHCSR_DBGKEY_Pos 16 /*!< CoreDebug DHCSR: DBGKEY Position */ #define CoreDebug_DHCSR_DBGKEY_Msk (0xFFFFUL << CoreDebug_DHCSR_DBGKEY_Pos) /*!< CoreDebug DHCSR: DBGKEY Mask */ #define CoreDebug_DHCSR_S_RESET_ST_Pos 25 /*!< CoreDebug DHCSR: S_RESET_ST Position */ #define CoreDebug_DHCSR_S_RESET_ST_Msk (1UL << CoreDebug_DHCSR_S_RESET_ST_Pos) /*!< CoreDebug DHCSR: S_RESET_ST Mask */ #define CoreDebug_DHCSR_S_RETIRE_ST_Pos 24 /*!< CoreDebug DHCSR: S_RETIRE_ST Position */ #define CoreDebug_DHCSR_S_RETIRE_ST_Msk (1UL << CoreDebug_DHCSR_S_RETIRE_ST_Pos) /*!< CoreDebug DHCSR: S_RETIRE_ST Mask */ #define CoreDebug_DHCSR_S_LOCKUP_Pos 19 /*!< CoreDebug DHCSR: S_LOCKUP Position */ #define CoreDebug_DHCSR_S_LOCKUP_Msk (1UL << CoreDebug_DHCSR_S_LOCKUP_Pos) /*!< CoreDebug DHCSR: S_LOCKUP Mask */ #define CoreDebug_DHCSR_S_SLEEP_Pos 18 /*!< CoreDebug DHCSR: S_SLEEP Position */ #define CoreDebug_DHCSR_S_SLEEP_Msk (1UL << CoreDebug_DHCSR_S_SLEEP_Pos) /*!< CoreDebug DHCSR: S_SLEEP Mask */ #define CoreDebug_DHCSR_S_HALT_Pos 17 /*!< CoreDebug DHCSR: S_HALT Position */ #define CoreDebug_DHCSR_S_HALT_Msk (1UL << CoreDebug_DHCSR_S_HALT_Pos) /*!< CoreDebug DHCSR: S_HALT Mask */ #define CoreDebug_DHCSR_S_REGRDY_Pos 16 /*!< CoreDebug DHCSR: S_REGRDY Position */ #define CoreDebug_DHCSR_S_REGRDY_Msk (1UL << CoreDebug_DHCSR_S_REGRDY_Pos) /*!< CoreDebug DHCSR: S_REGRDY Mask */ #define CoreDebug_DHCSR_C_SNAPSTALL_Pos 5 /*!< CoreDebug DHCSR: C_SNAPSTALL Position */ #define CoreDebug_DHCSR_C_SNAPSTALL_Msk (1UL << CoreDebug_DHCSR_C_SNAPSTALL_Pos) /*!< CoreDebug DHCSR: C_SNAPSTALL Mask */ #define CoreDebug_DHCSR_C_MASKINTS_Pos 3 /*!< CoreDebug DHCSR: C_MASKINTS Position */ #define CoreDebug_DHCSR_C_MASKINTS_Msk (1UL << CoreDebug_DHCSR_C_MASKINTS_Pos) /*!< CoreDebug DHCSR: C_MASKINTS Mask */ #define CoreDebug_DHCSR_C_STEP_Pos 2 /*!< CoreDebug DHCSR: C_STEP Position */ #define CoreDebug_DHCSR_C_STEP_Msk (1UL << CoreDebug_DHCSR_C_STEP_Pos) /*!< CoreDebug DHCSR: C_STEP Mask */ #define CoreDebug_DHCSR_C_HALT_Pos 1 /*!< CoreDebug DHCSR: C_HALT Position */ #define CoreDebug_DHCSR_C_HALT_Msk (1UL << CoreDebug_DHCSR_C_HALT_Pos) /*!< CoreDebug DHCSR: C_HALT Mask */ #define CoreDebug_DHCSR_C_DEBUGEN_Pos 0 /*!< CoreDebug DHCSR: C_DEBUGEN Position */ #define CoreDebug_DHCSR_C_DEBUGEN_Msk (1UL /*<< CoreDebug_DHCSR_C_DEBUGEN_Pos*/) /*!< CoreDebug DHCSR: C_DEBUGEN Mask */ /* Debug Core Register Selector Register */ #define CoreDebug_DCRSR_REGWnR_Pos 16 /*!< CoreDebug DCRSR: REGWnR Position */ #define CoreDebug_DCRSR_REGWnR_Msk (1UL << CoreDebug_DCRSR_REGWnR_Pos) /*!< CoreDebug DCRSR: REGWnR Mask */ #define CoreDebug_DCRSR_REGSEL_Pos 0 /*!< CoreDebug DCRSR: REGSEL Position */ #define CoreDebug_DCRSR_REGSEL_Msk (0x1FUL /*<< CoreDebug_DCRSR_REGSEL_Pos*/) /*!< CoreDebug DCRSR: REGSEL Mask */ /* Debug Exception and Monitor Control Register */ #define CoreDebug_DEMCR_TRCENA_Pos 24 /*!< CoreDebug DEMCR: TRCENA Position */ #define CoreDebug_DEMCR_TRCENA_Msk (1UL << CoreDebug_DEMCR_TRCENA_Pos) /*!< CoreDebug DEMCR: TRCENA Mask */ #define CoreDebug_DEMCR_MON_REQ_Pos 19 /*!< CoreDebug DEMCR: MON_REQ Position */ #define CoreDebug_DEMCR_MON_REQ_Msk (1UL << CoreDebug_DEMCR_MON_REQ_Pos) /*!< CoreDebug DEMCR: MON_REQ Mask */ #define CoreDebug_DEMCR_MON_STEP_Pos 18 /*!< CoreDebug DEMCR: MON_STEP Position */ #define CoreDebug_DEMCR_MON_STEP_Msk (1UL << CoreDebug_DEMCR_MON_STEP_Pos) /*!< CoreDebug DEMCR: MON_STEP Mask */ #define CoreDebug_DEMCR_MON_PEND_Pos 17 /*!< CoreDebug DEMCR: MON_PEND Position */ #define CoreDebug_DEMCR_MON_PEND_Msk (1UL << CoreDebug_DEMCR_MON_PEND_Pos) /*!< CoreDebug DEMCR: MON_PEND Mask */ #define CoreDebug_DEMCR_MON_EN_Pos 16 /*!< CoreDebug DEMCR: MON_EN Position */ #define CoreDebug_DEMCR_MON_EN_Msk (1UL << CoreDebug_DEMCR_MON_EN_Pos) /*!< CoreDebug DEMCR: MON_EN Mask */ #define CoreDebug_DEMCR_VC_HARDERR_Pos 10 /*!< CoreDebug DEMCR: VC_HARDERR Position */ #define CoreDebug_DEMCR_VC_HARDERR_Msk (1UL << CoreDebug_DEMCR_VC_HARDERR_Pos) /*!< CoreDebug DEMCR: VC_HARDERR Mask */ #define CoreDebug_DEMCR_VC_INTERR_Pos 9 /*!< CoreDebug DEMCR: VC_INTERR Position */ #define CoreDebug_DEMCR_VC_INTERR_Msk (1UL << CoreDebug_DEMCR_VC_INTERR_Pos) /*!< CoreDebug DEMCR: VC_INTERR Mask */ #define CoreDebug_DEMCR_VC_BUSERR_Pos 8 /*!< CoreDebug DEMCR: VC_BUSERR Position */ #define CoreDebug_DEMCR_VC_BUSERR_Msk (1UL << CoreDebug_DEMCR_VC_BUSERR_Pos) /*!< CoreDebug DEMCR: VC_BUSERR Mask */ #define CoreDebug_DEMCR_VC_STATERR_Pos 7 /*!< CoreDebug DEMCR: VC_STATERR Position */ #define CoreDebug_DEMCR_VC_STATERR_Msk (1UL << CoreDebug_DEMCR_VC_STATERR_Pos) /*!< CoreDebug DEMCR: VC_STATERR Mask */ #define CoreDebug_DEMCR_VC_CHKERR_Pos 6 /*!< CoreDebug DEMCR: VC_CHKERR Position */ #define CoreDebug_DEMCR_VC_CHKERR_Msk (1UL << CoreDebug_DEMCR_VC_CHKERR_Pos) /*!< CoreDebug DEMCR: VC_CHKERR Mask */ #define CoreDebug_DEMCR_VC_NOCPERR_Pos 5 /*!< CoreDebug DEMCR: VC_NOCPERR Position */ #define CoreDebug_DEMCR_VC_NOCPERR_Msk (1UL << CoreDebug_DEMCR_VC_NOCPERR_Pos) /*!< CoreDebug DEMCR: VC_NOCPERR Mask */ #define CoreDebug_DEMCR_VC_MMERR_Pos 4 /*!< CoreDebug DEMCR: VC_MMERR Position */ #define CoreDebug_DEMCR_VC_MMERR_Msk (1UL << CoreDebug_DEMCR_VC_MMERR_Pos) /*!< CoreDebug DEMCR: VC_MMERR Mask */ #define CoreDebug_DEMCR_VC_CORERESET_Pos 0 /*!< CoreDebug DEMCR: VC_CORERESET Position */ #define CoreDebug_DEMCR_VC_CORERESET_Msk (1UL /*<< CoreDebug_DEMCR_VC_CORERESET_Pos*/) /*!< CoreDebug DEMCR: VC_CORERESET Mask */ /*@} end of group CMSIS_CoreDebug */ /** \ingroup CMSIS_core_register \defgroup CMSIS_core_base Core Definitions \brief Definitions for base addresses, unions, and structures. @{ */ /* Memory mapping of Cortex-M4 Hardware */ #define SCS_BASE (0xE000E000UL) /*!< System Control Space Base Address */ #define ITM_BASE (0xE0000000UL) /*!< ITM Base Address */ #define DWT_BASE (0xE0001000UL) /*!< DWT Base Address */ #define TPI_BASE (0xE0040000UL) /*!< TPI Base Address */ #define CoreDebug_BASE (0xE000EDF0UL) /*!< Core Debug Base Address */ #define SysTick_BASE (SCS_BASE + 0x0010UL) /*!< SysTick Base Address */ #define NVIC_BASE (SCS_BASE + 0x0100UL) /*!< NVIC Base Address */ #define SCB_BASE (SCS_BASE + 0x0D00UL) /*!< System Control Block Base Address */ #define SCnSCB ((SCnSCB_Type *) SCS_BASE ) /*!< System control Register not in SCB */ #define SCB ((SCB_Type *) SCB_BASE ) /*!< SCB configuration struct */ #define SysTick ((SysTick_Type *) SysTick_BASE ) /*!< SysTick configuration struct */ #define NVIC ((NVIC_Type *) NVIC_BASE ) /*!< NVIC configuration struct */ #define ITM ((ITM_Type *) ITM_BASE ) /*!< ITM configuration struct */ #define DWT ((DWT_Type *) DWT_BASE ) /*!< DWT configuration struct */ #define TPI ((TPI_Type *) TPI_BASE ) /*!< TPI configuration struct */ #define CoreDebug ((CoreDebug_Type *) CoreDebug_BASE) /*!< Core Debug configuration struct */ #if (__MPU_PRESENT == 1) #define MPU_BASE (SCS_BASE + 0x0D90UL) /*!< Memory Protection Unit */ #define MPU ((MPU_Type *) MPU_BASE ) /*!< Memory Protection Unit */ #endif #if (__FPU_PRESENT == 1) #define FPU_BASE (SCS_BASE + 0x0F30UL) /*!< Floating Point Unit */ #define FPU ((FPU_Type *) FPU_BASE ) /*!< Floating Point Unit */ #endif /*@} */ /******************************************************************************* * Hardware Abstraction Layer Core Function Interface contains: - Core NVIC Functions - Core SysTick Functions - Core Debug Functions - Core Register Access Functions ******************************************************************************/ /** \defgroup CMSIS_Core_FunctionInterface Functions and Instructions Reference */ /* ########################## NVIC functions #################################### */ /** \ingroup CMSIS_Core_FunctionInterface \defgroup CMSIS_Core_NVICFunctions NVIC Functions \brief Functions that manage interrupts and exceptions via the NVIC. @{ */ /** \brief Set Priority Grouping The function sets the priority grouping field using the required unlock sequence. The parameter PriorityGroup is assigned to the field SCB->AIRCR [10:8] PRIGROUP field. Only values from 0..7 are used. In case of a conflict between priority grouping and available priority bits (__NVIC_PRIO_BITS), the smallest possible priority group is set. \param [in] PriorityGroup Priority grouping field. */ __STATIC_INLINE void NVIC_SetPriorityGrouping(uint32_t PriorityGroup) { uint32_t reg_value; uint32_t PriorityGroupTmp = (PriorityGroup & (uint32_t)0x07UL); /* only values 0..7 are used */ reg_value = SCB->AIRCR; /* read old register configuration */ reg_value &= ~((uint32_t)(SCB_AIRCR_VECTKEY_Msk | SCB_AIRCR_PRIGROUP_Msk)); /* clear bits to change */ reg_value = (reg_value | ((uint32_t)0x5FAUL << SCB_AIRCR_VECTKEY_Pos) | (PriorityGroupTmp << 8) ); /* Insert write key and priorty group */ SCB->AIRCR = reg_value; } /** \brief Get Priority Grouping The function reads the priority grouping field from the NVIC Interrupt Controller. \return Priority grouping field (SCB->AIRCR [10:8] PRIGROUP field). */ __STATIC_INLINE uint32_t NVIC_GetPriorityGrouping(void) { return ((uint32_t)((SCB->AIRCR & SCB_AIRCR_PRIGROUP_Msk) >> SCB_AIRCR_PRIGROUP_Pos)); } /** \brief Enable External Interrupt The function enables a device-specific interrupt in the NVIC interrupt controller. \param [in] IRQn External interrupt number. Value cannot be negative. */ __STATIC_INLINE void NVIC_EnableIRQ(IRQn_Type IRQn) { NVIC->ISER[(((uint32_t)(int32_t)IRQn) >> 5UL)] = (uint32_t)(1UL << (((uint32_t)(int32_t)IRQn) & 0x1FUL)); } /** \brief Disable External Interrupt The function disables a device-specific interrupt in the NVIC interrupt controller. \param [in] IRQn External interrupt number. Value cannot be negative. */ __STATIC_INLINE void NVIC_DisableIRQ(IRQn_Type IRQn) { NVIC->ICER[(((uint32_t)(int32_t)IRQn) >> 5UL)] = (uint32_t)(1UL << (((uint32_t)(int32_t)IRQn) & 0x1FUL)); } /** \brief Get Pending Interrupt The function reads the pending register in the NVIC and returns the pending bit for the specified interrupt. \param [in] IRQn Interrupt number. \return 0 Interrupt status is not pending. \return 1 Interrupt status is pending. */ __STATIC_INLINE uint32_t NVIC_GetPendingIRQ(IRQn_Type IRQn) { return((uint32_t)(((NVIC->ISPR[(((uint32_t)(int32_t)IRQn) >> 5UL)] & (1UL << (((uint32_t)(int32_t)IRQn) & 0x1FUL))) != 0UL) ? 1UL : 0UL)); } /** \brief Set Pending Interrupt The function sets the pending bit of an external interrupt. \param [in] IRQn Interrupt number. Value cannot be negative. */ __STATIC_INLINE void NVIC_SetPendingIRQ(IRQn_Type IRQn) { NVIC->ISPR[(((uint32_t)(int32_t)IRQn) >> 5UL)] = (uint32_t)(1UL << (((uint32_t)(int32_t)IRQn) & 0x1FUL)); } /** \brief Clear Pending Interrupt The function clears the pending bit of an external interrupt. \param [in] IRQn External interrupt number. Value cannot be negative. */ __STATIC_INLINE void NVIC_ClearPendingIRQ(IRQn_Type IRQn) { NVIC->ICPR[(((uint32_t)(int32_t)IRQn) >> 5UL)] = (uint32_t)(1UL << (((uint32_t)(int32_t)IRQn) & 0x1FUL)); } /** \brief Get Active Interrupt The function reads the active register in NVIC and returns the active bit. \param [in] IRQn Interrupt number. \return 0 Interrupt status is not active. \return 1 Interrupt status is active. */ __STATIC_INLINE uint32_t NVIC_GetActive(IRQn_Type IRQn) { return((uint32_t)(((NVIC->IABR[(((uint32_t)(int32_t)IRQn) >> 5UL)] & (1UL << (((uint32_t)(int32_t)IRQn) & 0x1FUL))) != 0UL) ? 1UL : 0UL)); } /** \brief Set Interrupt Priority The function sets the priority of an interrupt. \note The priority cannot be set for every core interrupt. \param [in] IRQn Interrupt number. \param [in] priority Priority to set. */ __STATIC_INLINE void NVIC_SetPriority(IRQn_Type IRQn, uint32_t priority) { if((int32_t)IRQn < 0) { SCB->SHPR[(((uint32_t)(int32_t)IRQn) & 0xFUL)-4UL] = (uint8_t)((priority << (8 - __NVIC_PRIO_BITS)) & (uint32_t)0xFFUL); } else { NVIC->IP[((uint32_t)(int32_t)IRQn)] = (uint8_t)((priority << (8 - __NVIC_PRIO_BITS)) & (uint32_t)0xFFUL); } } /** \brief Get Interrupt Priority The function reads the priority of an interrupt. The interrupt number can be positive to specify an external (device specific) interrupt, or negative to specify an internal (core) interrupt. \param [in] IRQn Interrupt number. \return Interrupt Priority. Value is aligned automatically to the implemented priority bits of the microcontroller. */ __STATIC_INLINE uint32_t NVIC_GetPriority(IRQn_Type IRQn) { if((int32_t)IRQn < 0) { return(((uint32_t)SCB->SHPR[(((uint32_t)(int32_t)IRQn) & 0xFUL)-4UL] >> (8 - __NVIC_PRIO_BITS))); } else { return(((uint32_t)NVIC->IP[((uint32_t)(int32_t)IRQn)] >> (8 - __NVIC_PRIO_BITS))); } } /** \brief Encode Priority The function encodes the priority for an interrupt with the given priority group, preemptive priority value, and subpriority value. In case of a conflict between priority grouping and available priority bits (__NVIC_PRIO_BITS), the smallest possible priority group is set. \param [in] PriorityGroup Used priority group. \param [in] PreemptPriority Preemptive priority value (starting from 0). \param [in] SubPriority Subpriority value (starting from 0). \return Encoded priority. Value can be used in the function \ref NVIC_SetPriority(). */ __STATIC_INLINE uint32_t NVIC_EncodePriority (uint32_t PriorityGroup, uint32_t PreemptPriority, uint32_t SubPriority) { uint32_t PriorityGroupTmp = (PriorityGroup & (uint32_t)0x07UL); /* only values 0..7 are used */ uint32_t PreemptPriorityBits; uint32_t SubPriorityBits; PreemptPriorityBits = ((7UL - PriorityGroupTmp) > (uint32_t)(__NVIC_PRIO_BITS)) ? (uint32_t)(__NVIC_PRIO_BITS) : (uint32_t)(7UL - PriorityGroupTmp); SubPriorityBits = ((PriorityGroupTmp + (uint32_t)(__NVIC_PRIO_BITS)) < (uint32_t)7UL) ? (uint32_t)0UL : (uint32_t)((PriorityGroupTmp - 7UL) + (uint32_t)(__NVIC_PRIO_BITS)); return ( ((PreemptPriority & (uint32_t)((1UL << (PreemptPriorityBits)) - 1UL)) << SubPriorityBits) | ((SubPriority & (uint32_t)((1UL << (SubPriorityBits )) - 1UL))) ); } /** \brief Decode Priority The function decodes an interrupt priority value with a given priority group to preemptive priority value and subpriority value. In case of a conflict between priority grouping and available priority bits (__NVIC_PRIO_BITS) the smallest possible priority group is set. \param [in] Priority Priority value, which can be retrieved with the function \ref NVIC_GetPriority(). \param [in] PriorityGroup Used priority group. \param [out] pPreemptPriority Preemptive priority value (starting from 0). \param [out] pSubPriority Subpriority value (starting from 0). */ __STATIC_INLINE void NVIC_DecodePriority (uint32_t Priority, uint32_t PriorityGroup, uint32_t* pPreemptPriority, uint32_t* pSubPriority) { uint32_t PriorityGroupTmp = (PriorityGroup & (uint32_t)0x07UL); /* only values 0..7 are used */ uint32_t PreemptPriorityBits; uint32_t SubPriorityBits; PreemptPriorityBits = ((7UL - PriorityGroupTmp) > (uint32_t)(__NVIC_PRIO_BITS)) ? (uint32_t)(__NVIC_PRIO_BITS) : (uint32_t)(7UL - PriorityGroupTmp); SubPriorityBits = ((PriorityGroupTmp + (uint32_t)(__NVIC_PRIO_BITS)) < (uint32_t)7UL) ? (uint32_t)0UL : (uint32_t)((PriorityGroupTmp - 7UL) + (uint32_t)(__NVIC_PRIO_BITS)); *pPreemptPriority = (Priority >> SubPriorityBits) & (uint32_t)((1UL << (PreemptPriorityBits)) - 1UL); *pSubPriority = (Priority ) & (uint32_t)((1UL << (SubPriorityBits )) - 1UL); } /** \brief System Reset The function initiates a system reset request to reset the MCU. */ __STATIC_INLINE void NVIC_SystemReset(void) { __DSB(); /* Ensure all outstanding memory accesses included buffered write are completed before reset */ SCB->AIRCR = (uint32_t)((0x5FAUL << SCB_AIRCR_VECTKEY_Pos) | (SCB->AIRCR & SCB_AIRCR_PRIGROUP_Msk) | SCB_AIRCR_SYSRESETREQ_Msk ); /* Keep priority group unchanged */ __DSB(); /* Ensure completion of memory access */ while(1) { __NOP(); } /* wait until reset */ } /*@} end of CMSIS_Core_NVICFunctions */ /* ########################## FPU functions #################################### */ /** \ingroup CMSIS_Core_FunctionInterface \defgroup CMSIS_Core_FpuFunctions FPU Functions \brief Function that provides FPU type. @{ */ /** \fn uint32_t SCB_GetFPUType(void) \brief get FPU type \returns - \b 0: No FPU - \b 1: Single precision FPU - \b 2: Double + Single precision FPU */ __STATIC_INLINE uint32_t SCB_GetFPUType(void) { uint32_t mvfr0; mvfr0 = SCB->MVFR0; if ((mvfr0 & 0x00000FF0UL) == 0x220UL) { return 2UL; // Double + Single precision FPU } else if ((mvfr0 & 0x00000FF0UL) == 0x020UL) { return 1UL; // Single precision FPU } else { return 0UL; // No FPU } } /*@} end of CMSIS_Core_FpuFunctions */ /* ########################## Cache functions #################################### */ /** \ingroup CMSIS_Core_FunctionInterface \defgroup CMSIS_Core_CacheFunctions Cache Functions \brief Functions that configure Instruction and Data cache. @{ */ /* Cache Size ID Register Macros */ #define CCSIDR_WAYS(x) (((x) & SCB_CCSIDR_ASSOCIATIVITY_Msk) >> SCB_CCSIDR_ASSOCIATIVITY_Pos) #define CCSIDR_SETS(x) (((x) & SCB_CCSIDR_NUMSETS_Msk ) >> SCB_CCSIDR_NUMSETS_Pos ) #define CCSIDR_LSSHIFT(x) (((x) & SCB_CCSIDR_LINESIZE_Msk ) /*>> SCB_CCSIDR_LINESIZE_Pos*/ ) /** \brief Enable I-Cache The function turns on I-Cache */ __STATIC_INLINE void SCB_EnableICache (void) { #if (__ICACHE_PRESENT == 1) __DSB(); __ISB(); SCB->ICIALLU = 0UL; // invalidate I-Cache SCB->CCR |= (uint32_t)SCB_CCR_IC_Msk; // enable I-Cache __DSB(); __ISB(); #endif } /** \brief Disable I-Cache The function turns off I-Cache */ __STATIC_INLINE void SCB_DisableICache (void) { #if (__ICACHE_PRESENT == 1) __DSB(); __ISB(); SCB->CCR &= ~(uint32_t)SCB_CCR_IC_Msk; // disable I-Cache SCB->ICIALLU = 0UL; // invalidate I-Cache __DSB(); __ISB(); #endif } /** \brief Invalidate I-Cache The function invalidates I-Cache */ __STATIC_INLINE void SCB_InvalidateICache (void) { #if (__ICACHE_PRESENT == 1) __DSB(); __ISB(); SCB->ICIALLU = 0UL; __DSB(); __ISB(); #endif } /** \brief Enable D-Cache The function turns on D-Cache */ __STATIC_INLINE void SCB_EnableDCache (void) { #if (__DCACHE_PRESENT == 1) uint32_t ccsidr, sshift, wshift, sw; uint32_t sets, ways; SCB->CSSELR = (0UL << 1) | 0UL; // Level 1 data cache ccsidr = SCB->CCSIDR; sets = (uint32_t)(CCSIDR_SETS(ccsidr)); sshift = (uint32_t)(CCSIDR_LSSHIFT(ccsidr) + 4UL); ways = (uint32_t)(CCSIDR_WAYS(ccsidr)); wshift = (uint32_t)((uint32_t)__CLZ(ways) & 0x1FUL); __DSB(); do { // invalidate D-Cache uint32_t tmpways = ways; do { sw = ((tmpways << wshift) | (sets << sshift)); SCB->DCISW = sw; } while(tmpways--); } while(sets--); __DSB(); SCB->CCR |= (uint32_t)SCB_CCR_DC_Msk; // enable D-Cache __DSB(); __ISB(); #endif } /** \brief Disable D-Cache The function turns off D-Cache */ __STATIC_INLINE void SCB_DisableDCache (void) { #if (__DCACHE_PRESENT == 1) uint32_t ccsidr, sshift, wshift, sw; uint32_t sets, ways; SCB->CSSELR = (0UL << 1) | 0UL; // Level 1 data cache ccsidr = SCB->CCSIDR; sets = (uint32_t)(CCSIDR_SETS(ccsidr)); sshift = (uint32_t)(CCSIDR_LSSHIFT(ccsidr) + 4UL); ways = (uint32_t)(CCSIDR_WAYS(ccsidr)); wshift = (uint32_t)((uint32_t)__CLZ(ways) & 0x1FUL); __DSB(); SCB->CCR &= ~(uint32_t)SCB_CCR_DC_Msk; // disable D-Cache do { // clean & invalidate D-Cache uint32_t tmpways = ways; do { sw = ((tmpways << wshift) | (sets << sshift)); SCB->DCCISW = sw; } while(tmpways--); } while(sets--); __DSB(); __ISB(); #endif } /** \brief Invalidate D-Cache The function invalidates D-Cache */ __STATIC_INLINE void SCB_InvalidateDCache (void) { #if (__DCACHE_PRESENT == 1) uint32_t ccsidr, sshift, wshift, sw; uint32_t sets, ways; SCB->CSSELR = (0UL << 1) | 0UL; // Level 1 data cache ccsidr = SCB->CCSIDR; sets = (uint32_t)(CCSIDR_SETS(ccsidr)); sshift = (uint32_t)(CCSIDR_LSSHIFT(ccsidr) + 4UL); ways = (uint32_t)(CCSIDR_WAYS(ccsidr)); wshift = (uint32_t)((uint32_t)__CLZ(ways) & 0x1FUL); __DSB(); do { // invalidate D-Cache uint32_t tmpways = ways; do { sw = ((tmpways << wshift) | (sets << sshift)); SCB->DCISW = sw; } while(tmpways--); } while(sets--); __DSB(); __ISB(); #endif } /** \brief Clean D-Cache The function cleans D-Cache */ __STATIC_INLINE void SCB_CleanDCache (void) { #if (__DCACHE_PRESENT == 1) uint32_t ccsidr, sshift, wshift, sw; uint32_t sets, ways; SCB->CSSELR = (0UL << 1) | 0UL; // Level 1 data cache ccsidr = SCB->CCSIDR; sets = (uint32_t)(CCSIDR_SETS(ccsidr)); sshift = (uint32_t)(CCSIDR_LSSHIFT(ccsidr) + 4UL); ways = (uint32_t)(CCSIDR_WAYS(ccsidr)); wshift = (uint32_t)((uint32_t)__CLZ(ways) & 0x1FUL); __DSB(); do { // clean D-Cache uint32_t tmpways = ways; do { sw = ((tmpways << wshift) | (sets << sshift)); SCB->DCCSW = sw; } while(tmpways--); } while(sets--); __DSB(); __ISB(); #endif } /** \brief Clean & Invalidate D-Cache The function cleans and Invalidates D-Cache */ __STATIC_INLINE void SCB_CleanInvalidateDCache (void) { #if (__DCACHE_PRESENT == 1) uint32_t ccsidr, sshift, wshift, sw; uint32_t sets, ways; SCB->CSSELR = (0UL << 1) | 0UL; // Level 1 data cache ccsidr = SCB->CCSIDR; sets = (uint32_t)(CCSIDR_SETS(ccsidr)); sshift = (uint32_t)(CCSIDR_LSSHIFT(ccsidr) + 4UL); ways = (uint32_t)(CCSIDR_WAYS(ccsidr)); wshift = (uint32_t)((uint32_t)__CLZ(ways) & 0x1FUL); __DSB(); do { // clean & invalidate D-Cache uint32_t tmpways = ways; do { sw = ((tmpways << wshift) | (sets << sshift)); SCB->DCCISW = sw; } while(tmpways--); } while(sets--); __DSB(); __ISB(); #endif } /** \fn void SCB_InvalidateDCache_by_Addr(volatile uint32_t *addr, int32_t dsize) \brief D-Cache Invalidate by address \param[in] addr address (aligned to 32-byte boundary) \param[in] dsize size of memory block (in number of bytes) */ __STATIC_INLINE void SCB_InvalidateDCache_by_Addr (uint32_t *addr, int32_t dsize) { #if (__DCACHE_PRESENT == 1) int32_t op_size = dsize; uint32_t op_addr = (uint32_t)addr; uint32_t linesize = 32UL; // in Cortex-M7 size of cache line is fixed to 8 words (32 bytes) __DSB(); while (op_size > 0) { SCB->DCIMVAC = op_addr; op_addr += linesize; op_size -= (int32_t)linesize; } __DSB(); __ISB(); #endif } /** \fn void SCB_CleanDCache_by_Addr(volatile uint32_t *addr, int32_t dsize) \brief D-Cache Clean by address \param[in] addr address (aligned to 32-byte boundary) \param[in] dsize size of memory block (in number of bytes) */ __STATIC_INLINE void SCB_CleanDCache_by_Addr (uint32_t *addr, int32_t dsize) { #if (__DCACHE_PRESENT == 1) int32_t op_size = dsize; uint32_t op_addr = (uint32_t) addr; uint32_t linesize = 32UL; // in Cortex-M7 size of cache line is fixed to 8 words (32 bytes) __DSB(); while (op_size > 0) { SCB->DCCMVAC = op_addr; op_addr += linesize; op_size -= (int32_t)linesize; } __DSB(); __ISB(); #endif } /** \fn void SCB_CleanInvalidateDCache_by_Addr(volatile uint32_t *addr, int32_t dsize) \brief D-Cache Clean and Invalidate by address \param[in] addr address (aligned to 32-byte boundary) \param[in] dsize size of memory block (in number of bytes) */ __STATIC_INLINE void SCB_CleanInvalidateDCache_by_Addr (uint32_t *addr, int32_t dsize) { #if (__DCACHE_PRESENT == 1) int32_t op_size = dsize; uint32_t op_addr = (uint32_t) addr; uint32_t linesize = 32UL; // in Cortex-M7 size of cache line is fixed to 8 words (32 bytes) __DSB(); while (op_size > 0) { SCB->DCCIMVAC = op_addr; op_addr += linesize; op_size -= (int32_t)linesize; } __DSB(); __ISB(); #endif } /*@} end of CMSIS_Core_CacheFunctions */ /* ################################## SysTick function ############################################ */ /** \ingroup CMSIS_Core_FunctionInterface \defgroup CMSIS_Core_SysTickFunctions SysTick Functions \brief Functions that configure the System. @{ */ #if (__Vendor_SysTickConfig == 0) /** \brief System Tick Configuration The function initializes the System Timer and its interrupt, and starts the System Tick Timer. Counter is in free running mode to generate periodic interrupts. \param [in] ticks Number of ticks between two interrupts. \return 0 Function succeeded. \return 1 Function failed. \note When the variable __Vendor_SysTickConfig is set to 1, then the function SysTick_Config is not included. In this case, the file device.h must contain a vendor-specific implementation of this function. */ __STATIC_INLINE uint32_t SysTick_Config(uint32_t ticks) { if ((ticks - 1UL) > SysTick_LOAD_RELOAD_Msk) { return (1UL); } /* Reload value impossible */ SysTick->LOAD = (uint32_t)(ticks - 1UL); /* set reload register */ NVIC_SetPriority (SysTick_IRQn, (1UL << __NVIC_PRIO_BITS) - 1UL); /* set Priority for Systick Interrupt */ SysTick->VAL = 0UL; /* Load the SysTick Counter Value */ SysTick->CTRL = SysTick_CTRL_CLKSOURCE_Msk | SysTick_CTRL_TICKINT_Msk | SysTick_CTRL_ENABLE_Msk; /* Enable SysTick IRQ and SysTick Timer */ return (0UL); /* Function successful */ } #endif /*@} end of CMSIS_Core_SysTickFunctions */ /* ##################################### Debug In/Output function ########################################### */ /** \ingroup CMSIS_Core_FunctionInterface \defgroup CMSIS_core_DebugFunctions ITM Functions \brief Functions that access the ITM debug interface. @{ */ extern volatile int32_t ITM_RxBuffer; /*!< External variable to receive characters. */ #define ITM_RXBUFFER_EMPTY 0x5AA55AA5 /*!< Value identifying \ref ITM_RxBuffer is ready for next character. */ /** \brief ITM Send Character The function transmits a character via the ITM channel 0, and \li Just returns when no debugger is connected that has booked the output. \li Is blocking when a debugger is connected, but the previous character sent has not been transmitted. \param [in] ch Character to transmit. \returns Character to transmit. */ __STATIC_INLINE uint32_t ITM_SendChar (uint32_t ch) { if (((ITM->TCR & ITM_TCR_ITMENA_Msk) != 0UL) && /* ITM enabled */ ((ITM->TER & 1UL ) != 0UL) ) /* ITM Port #0 enabled */ { while (ITM->PORT[0].u32 == 0UL) { __NOP(); } ITM->PORT[0].u8 = (uint8_t)ch; } return (ch); } /** \brief ITM Receive Character The function inputs a character via the external variable \ref ITM_RxBuffer. \return Received character. \return -1 No character pending. */ __STATIC_INLINE int32_t ITM_ReceiveChar (void) { int32_t ch = -1; /* no character available */ if (ITM_RxBuffer != ITM_RXBUFFER_EMPTY) { ch = ITM_RxBuffer; ITM_RxBuffer = ITM_RXBUFFER_EMPTY; /* ready for next character */ } return (ch); } /** \brief ITM Check Character The function checks whether a character is pending for reading in the variable \ref ITM_RxBuffer. \return 0 No character available. \return 1 Character available. */ __STATIC_INLINE int32_t ITM_CheckChar (void) { if (ITM_RxBuffer == ITM_RXBUFFER_EMPTY) { return (0); /* no character available */ } else { return (1); /* character available */ } } /*@} end of CMSIS_core_DebugFunctions */ #ifdef __cplusplus } #endif #endif /* __CORE_CM7_H_DEPENDANT */ #endif /* __CMSIS_GENERIC */ ================================================ FILE: Zelig/mbed/TARGET_NUCLEO_F411RE/core_cmFunc.h ================================================ /**************************************************************************//** * @file core_cmFunc.h * @brief CMSIS Cortex-M Core Function Access Header File * @version V4.10 * @date 18. March 2015 * * @note * ******************************************************************************/ /* Copyright (c) 2009 - 2015 ARM LIMITED All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: - Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. - Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. - Neither the name of ARM 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 COPYRIGHT HOLDERS AND 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. ---------------------------------------------------------------------------*/ #ifndef __CORE_CMFUNC_H #define __CORE_CMFUNC_H /* ########################### Core Function Access ########################### */ /** \ingroup CMSIS_Core_FunctionInterface \defgroup CMSIS_Core_RegAccFunctions CMSIS Core Register Access Functions @{ */ #if defined ( __CC_ARM ) /*------------------RealView Compiler -----------------*/ /* ARM armcc specific functions */ #if (__ARMCC_VERSION < 400677) #error "Please use ARM Compiler Toolchain V4.0.677 or later!" #endif /* intrinsic void __enable_irq(); */ /* intrinsic void __disable_irq(); */ /** \brief Get Control Register This function returns the content of the Control Register. \return Control Register value */ __STATIC_INLINE uint32_t __get_CONTROL(void) { register uint32_t __regControl __ASM("control"); return(__regControl); } /** \brief Set Control Register This function writes the given value to the Control Register. \param [in] control Control Register value to set */ __STATIC_INLINE void __set_CONTROL(uint32_t control) { register uint32_t __regControl __ASM("control"); __regControl = control; } /** \brief Get IPSR Register This function returns the content of the IPSR Register. \return IPSR Register value */ __STATIC_INLINE uint32_t __get_IPSR(void) { register uint32_t __regIPSR __ASM("ipsr"); return(__regIPSR); } /** \brief Get APSR Register This function returns the content of the APSR Register. \return APSR Register value */ __STATIC_INLINE uint32_t __get_APSR(void) { register uint32_t __regAPSR __ASM("apsr"); return(__regAPSR); } /** \brief Get xPSR Register This function returns the content of the xPSR Register. \return xPSR Register value */ __STATIC_INLINE uint32_t __get_xPSR(void) { register uint32_t __regXPSR __ASM("xpsr"); return(__regXPSR); } /** \brief Get Process Stack Pointer This function returns the current value of the Process Stack Pointer (PSP). \return PSP Register value */ __STATIC_INLINE uint32_t __get_PSP(void) { register uint32_t __regProcessStackPointer __ASM("psp"); return(__regProcessStackPointer); } /** \brief Set Process Stack Pointer This function assigns the given value to the Process Stack Pointer (PSP). \param [in] topOfProcStack Process Stack Pointer value to set */ __STATIC_INLINE void __set_PSP(uint32_t topOfProcStack) { register uint32_t __regProcessStackPointer __ASM("psp"); __regProcessStackPointer = topOfProcStack; } /** \brief Get Main Stack Pointer This function returns the current value of the Main Stack Pointer (MSP). \return MSP Register value */ __STATIC_INLINE uint32_t __get_MSP(void) { register uint32_t __regMainStackPointer __ASM("msp"); return(__regMainStackPointer); } /** \brief Set Main Stack Pointer This function assigns the given value to the Main Stack Pointer (MSP). \param [in] topOfMainStack Main Stack Pointer value to set */ __STATIC_INLINE void __set_MSP(uint32_t topOfMainStack) { register uint32_t __regMainStackPointer __ASM("msp"); __regMainStackPointer = topOfMainStack; } /** \brief Get Priority Mask This function returns the current state of the priority mask bit from the Priority Mask Register. \return Priority Mask value */ __STATIC_INLINE uint32_t __get_PRIMASK(void) { register uint32_t __regPriMask __ASM("primask"); return(__regPriMask); } /** \brief Set Priority Mask This function assigns the given value to the Priority Mask Register. \param [in] priMask Priority Mask */ __STATIC_INLINE void __set_PRIMASK(uint32_t priMask) { register uint32_t __regPriMask __ASM("primask"); __regPriMask = (priMask); } #if (__CORTEX_M >= 0x03) || (__CORTEX_SC >= 300) /** \brief Enable FIQ This function enables FIQ interrupts by clearing the F-bit in the CPSR. Can only be executed in Privileged modes. */ #define __enable_fault_irq __enable_fiq /** \brief Disable FIQ This function disables FIQ interrupts by setting the F-bit in the CPSR. Can only be executed in Privileged modes. */ #define __disable_fault_irq __disable_fiq /** \brief Get Base Priority This function returns the current value of the Base Priority register. \return Base Priority register value */ __STATIC_INLINE uint32_t __get_BASEPRI(void) { register uint32_t __regBasePri __ASM("basepri"); return(__regBasePri); } /** \brief Set Base Priority This function assigns the given value to the Base Priority register. \param [in] basePri Base Priority value to set */ __STATIC_INLINE void __set_BASEPRI(uint32_t basePri) { register uint32_t __regBasePri __ASM("basepri"); __regBasePri = (basePri & 0xff); } /** \brief Set Base Priority with condition This function assigns the given value to the Base Priority register only if BASEPRI masking is disabled, or the new value increases the BASEPRI priority level. \param [in] basePri Base Priority value to set */ __STATIC_INLINE void __set_BASEPRI_MAX(uint32_t basePri) { register uint32_t __regBasePriMax __ASM("basepri_max"); __regBasePriMax = (basePri & 0xff); } /** \brief Get Fault Mask This function returns the current value of the Fault Mask register. \return Fault Mask register value */ __STATIC_INLINE uint32_t __get_FAULTMASK(void) { register uint32_t __regFaultMask __ASM("faultmask"); return(__regFaultMask); } /** \brief Set Fault Mask This function assigns the given value to the Fault Mask register. \param [in] faultMask Fault Mask value to set */ __STATIC_INLINE void __set_FAULTMASK(uint32_t faultMask) { register uint32_t __regFaultMask __ASM("faultmask"); __regFaultMask = (faultMask & (uint32_t)1); } #endif /* (__CORTEX_M >= 0x03) || (__CORTEX_SC >= 300) */ #if (__CORTEX_M == 0x04) || (__CORTEX_M == 0x07) /** \brief Get FPSCR This function returns the current value of the Floating Point Status/Control register. \return Floating Point Status/Control register value */ __STATIC_INLINE uint32_t __get_FPSCR(void) { #if (__FPU_PRESENT == 1) && (__FPU_USED == 1) register uint32_t __regfpscr __ASM("fpscr"); return(__regfpscr); #else return(0); #endif } /** \brief Set FPSCR This function assigns the given value to the Floating Point Status/Control register. \param [in] fpscr Floating Point Status/Control value to set */ __STATIC_INLINE void __set_FPSCR(uint32_t fpscr) { #if (__FPU_PRESENT == 1) && (__FPU_USED == 1) register uint32_t __regfpscr __ASM("fpscr"); __regfpscr = (fpscr); #endif } #endif /* (__CORTEX_M == 0x04) || (__CORTEX_M == 0x07) */ #elif defined ( __GNUC__ ) /*------------------ GNU Compiler ---------------------*/ /* GNU gcc specific functions */ /** \brief Enable IRQ Interrupts This function enables IRQ interrupts by clearing the I-bit in the CPSR. Can only be executed in Privileged modes. */ __attribute__( ( always_inline ) ) __STATIC_INLINE void __enable_irq(void) { __ASM volatile ("cpsie i" : : : "memory"); } /** \brief Disable IRQ Interrupts This function disables IRQ interrupts by setting the I-bit in the CPSR. Can only be executed in Privileged modes. */ __attribute__( ( always_inline ) ) __STATIC_INLINE void __disable_irq(void) { __ASM volatile ("cpsid i" : : : "memory"); } /** \brief Get Control Register This function returns the content of the Control Register. \return Control Register value */ __attribute__( ( always_inline ) ) __STATIC_INLINE uint32_t __get_CONTROL(void) { uint32_t result; __ASM volatile ("MRS %0, control" : "=r" (result) ); return(result); } /** \brief Set Control Register This function writes the given value to the Control Register. \param [in] control Control Register value to set */ __attribute__( ( always_inline ) ) __STATIC_INLINE void __set_CONTROL(uint32_t control) { __ASM volatile ("MSR control, %0" : : "r" (control) : "memory"); } /** \brief Get IPSR Register This function returns the content of the IPSR Register. \return IPSR Register value */ __attribute__( ( always_inline ) ) __STATIC_INLINE uint32_t __get_IPSR(void) { uint32_t result; __ASM volatile ("MRS %0, ipsr" : "=r" (result) ); return(result); } /** \brief Get APSR Register This function returns the content of the APSR Register. \return APSR Register value */ __attribute__( ( always_inline ) ) __STATIC_INLINE uint32_t __get_APSR(void) { uint32_t result; __ASM volatile ("MRS %0, apsr" : "=r" (result) ); return(result); } /** \brief Get xPSR Register This function returns the content of the xPSR Register. \return xPSR Register value */ __attribute__( ( always_inline ) ) __STATIC_INLINE uint32_t __get_xPSR(void) { uint32_t result; __ASM volatile ("MRS %0, xpsr" : "=r" (result) ); return(result); } /** \brief Get Process Stack Pointer This function returns the current value of the Process Stack Pointer (PSP). \return PSP Register value */ __attribute__( ( always_inline ) ) __STATIC_INLINE uint32_t __get_PSP(void) { register uint32_t result; __ASM volatile ("MRS %0, psp\n" : "=r" (result) ); return(result); } /** \brief Set Process Stack Pointer This function assigns the given value to the Process Stack Pointer (PSP). \param [in] topOfProcStack Process Stack Pointer value to set */ __attribute__( ( always_inline ) ) __STATIC_INLINE void __set_PSP(uint32_t topOfProcStack) { __ASM volatile ("MSR psp, %0\n" : : "r" (topOfProcStack) : "sp"); } /** \brief Get Main Stack Pointer This function returns the current value of the Main Stack Pointer (MSP). \return MSP Register value */ __attribute__( ( always_inline ) ) __STATIC_INLINE uint32_t __get_MSP(void) { register uint32_t result; __ASM volatile ("MRS %0, msp\n" : "=r" (result) ); return(result); } /** \brief Set Main Stack Pointer This function assigns the given value to the Main Stack Pointer (MSP). \param [in] topOfMainStack Main Stack Pointer value to set */ __attribute__( ( always_inline ) ) __STATIC_INLINE void __set_MSP(uint32_t topOfMainStack) { __ASM volatile ("MSR msp, %0\n" : : "r" (topOfMainStack) : "sp"); } /** \brief Get Priority Mask This function returns the current state of the priority mask bit from the Priority Mask Register. \return Priority Mask value */ __attribute__( ( always_inline ) ) __STATIC_INLINE uint32_t __get_PRIMASK(void) { uint32_t result; __ASM volatile ("MRS %0, primask" : "=r" (result) ); return(result); } /** \brief Set Priority Mask This function assigns the given value to the Priority Mask Register. \param [in] priMask Priority Mask */ __attribute__( ( always_inline ) ) __STATIC_INLINE void __set_PRIMASK(uint32_t priMask) { __ASM volatile ("MSR primask, %0" : : "r" (priMask) : "memory"); } #if (__CORTEX_M >= 0x03) /** \brief Enable FIQ This function enables FIQ interrupts by clearing the F-bit in the CPSR. Can only be executed in Privileged modes. */ __attribute__( ( always_inline ) ) __STATIC_INLINE void __enable_fault_irq(void) { __ASM volatile ("cpsie f" : : : "memory"); } /** \brief Disable FIQ This function disables FIQ interrupts by setting the F-bit in the CPSR. Can only be executed in Privileged modes. */ __attribute__( ( always_inline ) ) __STATIC_INLINE void __disable_fault_irq(void) { __ASM volatile ("cpsid f" : : : "memory"); } /** \brief Get Base Priority This function returns the current value of the Base Priority register. \return Base Priority register value */ __attribute__( ( always_inline ) ) __STATIC_INLINE uint32_t __get_BASEPRI(void) { uint32_t result; __ASM volatile ("MRS %0, basepri" : "=r" (result) ); return(result); } /** \brief Set Base Priority This function assigns the given value to the Base Priority register. \param [in] basePri Base Priority value to set */ __attribute__( ( always_inline ) ) __STATIC_INLINE void __set_BASEPRI(uint32_t value) { __ASM volatile ("MSR basepri, %0" : : "r" (value) : "memory"); } /** \brief Set Base Priority with condition This function assigns the given value to the Base Priority register only if BASEPRI masking is disabled, or the new value increases the BASEPRI priority level. \param [in] basePri Base Priority value to set */ __attribute__( ( always_inline ) ) __STATIC_INLINE void __set_BASEPRI_MAX(uint32_t value) { __ASM volatile ("MSR basepri_max, %0" : : "r" (value) : "memory"); } /** \brief Get Fault Mask This function returns the current value of the Fault Mask register. \return Fault Mask register value */ __attribute__( ( always_inline ) ) __STATIC_INLINE uint32_t __get_FAULTMASK(void) { uint32_t result; __ASM volatile ("MRS %0, faultmask" : "=r" (result) ); return(result); } /** \brief Set Fault Mask This function assigns the given value to the Fault Mask register. \param [in] faultMask Fault Mask value to set */ __attribute__( ( always_inline ) ) __STATIC_INLINE void __set_FAULTMASK(uint32_t faultMask) { __ASM volatile ("MSR faultmask, %0" : : "r" (faultMask) : "memory"); } #endif /* (__CORTEX_M >= 0x03) */ #if (__CORTEX_M == 0x04) || (__CORTEX_M == 0x07) /** \brief Get FPSCR This function returns the current value of the Floating Point Status/Control register. \return Floating Point Status/Control register value */ __attribute__( ( always_inline ) ) __STATIC_INLINE uint32_t __get_FPSCR(void) { #if (__FPU_PRESENT == 1) && (__FPU_USED == 1) uint32_t result; /* Empty asm statement works as a scheduling barrier */ __ASM volatile (""); __ASM volatile ("VMRS %0, fpscr" : "=r" (result) ); __ASM volatile (""); return(result); #else return(0); #endif } /** \brief Set FPSCR This function assigns the given value to the Floating Point Status/Control register. \param [in] fpscr Floating Point Status/Control value to set */ __attribute__( ( always_inline ) ) __STATIC_INLINE void __set_FPSCR(uint32_t fpscr) { #if (__FPU_PRESENT == 1) && (__FPU_USED == 1) /* Empty asm statement works as a scheduling barrier */ __ASM volatile (""); __ASM volatile ("VMSR fpscr, %0" : : "r" (fpscr) : "vfpcc"); __ASM volatile (""); #endif } #endif /* (__CORTEX_M == 0x04) || (__CORTEX_M == 0x07) */ #elif defined ( __ICCARM__ ) /*------------------ ICC Compiler -------------------*/ /* IAR iccarm specific functions */ #include #elif defined ( __TMS470__ ) /*---------------- TI CCS Compiler ------------------*/ /* TI CCS specific functions */ #include #elif defined ( __TASKING__ ) /*------------------ TASKING Compiler --------------*/ /* TASKING carm specific functions */ /* * The CMSIS functions have been implemented as intrinsics in the compiler. * Please use "carm -?i" to get an up to date list of all intrinsics, * Including the CMSIS ones. */ #elif defined ( __CSMC__ ) /*------------------ COSMIC Compiler -------------------*/ /* Cosmic specific functions */ #include #endif /*@} end of CMSIS_Core_RegAccFunctions */ #endif /* __CORE_CMFUNC_H */ ================================================ FILE: Zelig/mbed/TARGET_NUCLEO_F411RE/core_cmInstr.h ================================================ /**************************************************************************//** * @file core_cmInstr.h * @brief CMSIS Cortex-M Core Instruction Access Header File * @version V4.10 * @date 18. March 2015 * * @note * ******************************************************************************/ /* Copyright (c) 2009 - 2014 ARM LIMITED All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: - Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. - Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. - Neither the name of ARM 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 COPYRIGHT HOLDERS AND 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. ---------------------------------------------------------------------------*/ #ifndef __CORE_CMINSTR_H #define __CORE_CMINSTR_H /* ########################## Core Instruction Access ######################### */ /** \defgroup CMSIS_Core_InstructionInterface CMSIS Core Instruction Interface Access to dedicated instructions @{ */ #if defined ( __CC_ARM ) /*------------------RealView Compiler -----------------*/ /* ARM armcc specific functions */ #if (__ARMCC_VERSION < 400677) #error "Please use ARM Compiler Toolchain V4.0.677 or later!" #endif /** \brief No Operation No Operation does nothing. This instruction can be used for code alignment purposes. */ #define __NOP __nop /** \brief Wait For Interrupt Wait For Interrupt is a hint instruction that suspends execution until one of a number of events occurs. */ #define __WFI __wfi /** \brief Wait For Event Wait For Event is a hint instruction that permits the processor to enter a low-power state until one of a number of events occurs. */ #define __WFE __wfe /** \brief Send Event Send Event is a hint instruction. It causes an event to be signaled to the CPU. */ #define __SEV __sev /** \brief Instruction Synchronization Barrier Instruction Synchronization Barrier flushes the pipeline in the processor, so that all instructions following the ISB are fetched from cache or memory, after the instruction has been completed. */ #define __ISB() do {\ __schedule_barrier();\ __isb(0xF);\ __schedule_barrier();\ } while (0) /** \brief Data Synchronization Barrier This function acts as a special kind of Data Memory Barrier. It completes when all explicit memory accesses before this instruction complete. */ #define __DSB() do {\ __schedule_barrier();\ __dsb(0xF);\ __schedule_barrier();\ } while (0) /** \brief Data Memory Barrier This function ensures the apparent order of the explicit memory operations before and after the instruction, without ensuring their completion. */ #define __DMB() do {\ __schedule_barrier();\ __dmb(0xF);\ __schedule_barrier();\ } while (0) /** \brief Reverse byte order (32 bit) This function reverses the byte order in integer value. \param [in] value Value to reverse \return Reversed value */ #define __REV __rev /** \brief Reverse byte order (16 bit) This function reverses the byte order in two unsigned short values. \param [in] value Value to reverse \return Reversed value */ #ifndef __NO_EMBEDDED_ASM __attribute__((section(".rev16_text"))) __STATIC_INLINE __ASM uint32_t __REV16(uint32_t value) { rev16 r0, r0 bx lr } #endif /** \brief Reverse byte order in signed short value This function reverses the byte order in a signed short value with sign extension to integer. \param [in] value Value to reverse \return Reversed value */ #ifndef __NO_EMBEDDED_ASM __attribute__((section(".revsh_text"))) __STATIC_INLINE __ASM int32_t __REVSH(int32_t value) { revsh r0, r0 bx lr } #endif /** \brief Rotate Right in unsigned value (32 bit) This function Rotate Right (immediate) provides the value of the contents of a register rotated by a variable number of bits. \param [in] value Value to rotate \param [in] value Number of Bits to rotate \return Rotated value */ #define __ROR __ror /** \brief Breakpoint This function causes the processor to enter Debug state. Debug tools can use this to investigate system state when the instruction at a particular address is reached. \param [in] value is ignored by the processor. If required, a debugger can use it to store additional information about the breakpoint. */ #define __BKPT(value) __breakpoint(value) /** \brief Reverse bit order of value This function reverses the bit order of the given value. \param [in] value Value to reverse \return Reversed value */ #if (__CORTEX_M >= 0x03) || (__CORTEX_SC >= 300) #define __RBIT __rbit #else __attribute__((always_inline)) __STATIC_INLINE uint32_t __RBIT(uint32_t value) { uint32_t result; int32_t s = 4 /*sizeof(v)*/ * 8 - 1; // extra shift needed at end result = value; // r will be reversed bits of v; first get LSB of v for (value >>= 1; value; value >>= 1) { result <<= 1; result |= value & 1; s--; } result <<= s; // shift when v's highest bits are zero return(result); } #endif /** \brief Count leading zeros This function counts the number of leading zeros of a data value. \param [in] value Value to count the leading zeros \return number of leading zeros in value */ #define __CLZ __clz #if (__CORTEX_M >= 0x03) || (__CORTEX_SC >= 300) /** \brief LDR Exclusive (8 bit) This function executes a exclusive LDR instruction for 8 bit value. \param [in] ptr Pointer to data \return value of type uint8_t at (*ptr) */ #define __LDREXB(ptr) ((uint8_t ) __ldrex(ptr)) /** \brief LDR Exclusive (16 bit) This function executes a exclusive LDR instruction for 16 bit values. \param [in] ptr Pointer to data \return value of type uint16_t at (*ptr) */ #define __LDREXH(ptr) ((uint16_t) __ldrex(ptr)) /** \brief LDR Exclusive (32 bit) This function executes a exclusive LDR instruction for 32 bit values. \param [in] ptr Pointer to data \return value of type uint32_t at (*ptr) */ #define __LDREXW(ptr) ((uint32_t ) __ldrex(ptr)) /** \brief STR Exclusive (8 bit) This function executes a exclusive STR instruction for 8 bit values. \param [in] value Value to store \param [in] ptr Pointer to location \return 0 Function succeeded \return 1 Function failed */ #define __STREXB(value, ptr) __strex(value, ptr) /** \brief STR Exclusive (16 bit) This function executes a exclusive STR instruction for 16 bit values. \param [in] value Value to store \param [in] ptr Pointer to location \return 0 Function succeeded \return 1 Function failed */ #define __STREXH(value, ptr) __strex(value, ptr) /** \brief STR Exclusive (32 bit) This function executes a exclusive STR instruction for 32 bit values. \param [in] value Value to store \param [in] ptr Pointer to location \return 0 Function succeeded \return 1 Function failed */ #define __STREXW(value, ptr) __strex(value, ptr) /** \brief Remove the exclusive lock This function removes the exclusive lock which is created by LDREX. */ #define __CLREX __clrex /** \brief Signed Saturate This function saturates a signed value. \param [in] value Value to be saturated \param [in] sat Bit position to saturate to (1..32) \return Saturated value */ #define __SSAT __ssat /** \brief Unsigned Saturate This function saturates an unsigned value. \param [in] value Value to be saturated \param [in] sat Bit position to saturate to (0..31) \return Saturated value */ #define __USAT __usat /** \brief Rotate Right with Extend (32 bit) This function moves each bit of a bitstring right by one bit. The carry input is shifted in at the left end of the bitstring. \param [in] value Value to rotate \return Rotated value */ #ifndef __NO_EMBEDDED_ASM __attribute__((section(".rrx_text"))) __STATIC_INLINE __ASM uint32_t __RRX(uint32_t value) { rrx r0, r0 bx lr } #endif /** \brief LDRT Unprivileged (8 bit) This function executes a Unprivileged LDRT instruction for 8 bit value. \param [in] ptr Pointer to data \return value of type uint8_t at (*ptr) */ #define __LDRBT(ptr) ((uint8_t ) __ldrt(ptr)) /** \brief LDRT Unprivileged (16 bit) This function executes a Unprivileged LDRT instruction for 16 bit values. \param [in] ptr Pointer to data \return value of type uint16_t at (*ptr) */ #define __LDRHT(ptr) ((uint16_t) __ldrt(ptr)) /** \brief LDRT Unprivileged (32 bit) This function executes a Unprivileged LDRT instruction for 32 bit values. \param [in] ptr Pointer to data \return value of type uint32_t at (*ptr) */ #define __LDRT(ptr) ((uint32_t ) __ldrt(ptr)) /** \brief STRT Unprivileged (8 bit) This function executes a Unprivileged STRT instruction for 8 bit values. \param [in] value Value to store \param [in] ptr Pointer to location */ #define __STRBT(value, ptr) __strt(value, ptr) /** \brief STRT Unprivileged (16 bit) This function executes a Unprivileged STRT instruction for 16 bit values. \param [in] value Value to store \param [in] ptr Pointer to location */ #define __STRHT(value, ptr) __strt(value, ptr) /** \brief STRT Unprivileged (32 bit) This function executes a Unprivileged STRT instruction for 32 bit values. \param [in] value Value to store \param [in] ptr Pointer to location */ #define __STRT(value, ptr) __strt(value, ptr) #endif /* (__CORTEX_M >= 0x03) || (__CORTEX_SC >= 300) */ #elif defined ( __GNUC__ ) /*------------------ GNU Compiler ---------------------*/ /* GNU gcc specific functions */ /* Define macros for porting to both thumb1 and thumb2. * For thumb1, use low register (r0-r7), specified by constrant "l" * Otherwise, use general registers, specified by constrant "r" */ #if defined (__thumb__) && !defined (__thumb2__) #define __CMSIS_GCC_OUT_REG(r) "=l" (r) #define __CMSIS_GCC_USE_REG(r) "l" (r) #else #define __CMSIS_GCC_OUT_REG(r) "=r" (r) #define __CMSIS_GCC_USE_REG(r) "r" (r) #endif /** \brief No Operation No Operation does nothing. This instruction can be used for code alignment purposes. */ __attribute__((always_inline)) __STATIC_INLINE void __NOP(void) { __ASM volatile ("nop"); } /** \brief Wait For Interrupt Wait For Interrupt is a hint instruction that suspends execution until one of a number of events occurs. */ __attribute__((always_inline)) __STATIC_INLINE void __WFI(void) { __ASM volatile ("wfi"); } /** \brief Wait For Event Wait For Event is a hint instruction that permits the processor to enter a low-power state until one of a number of events occurs. */ __attribute__((always_inline)) __STATIC_INLINE void __WFE(void) { __ASM volatile ("wfe"); } /** \brief Send Event Send Event is a hint instruction. It causes an event to be signaled to the CPU. */ __attribute__((always_inline)) __STATIC_INLINE void __SEV(void) { __ASM volatile ("sev"); } /** \brief Instruction Synchronization Barrier Instruction Synchronization Barrier flushes the pipeline in the processor, so that all instructions following the ISB are fetched from cache or memory, after the instruction has been completed. */ __attribute__((always_inline)) __STATIC_INLINE void __ISB(void) { __ASM volatile ("isb 0xF":::"memory"); } /** \brief Data Synchronization Barrier This function acts as a special kind of Data Memory Barrier. It completes when all explicit memory accesses before this instruction complete. */ __attribute__((always_inline)) __STATIC_INLINE void __DSB(void) { __ASM volatile ("dsb 0xF":::"memory"); } /** \brief Data Memory Barrier This function ensures the apparent order of the explicit memory operations before and after the instruction, without ensuring their completion. */ __attribute__((always_inline)) __STATIC_INLINE void __DMB(void) { __ASM volatile ("dmb 0xF":::"memory"); } /** \brief Reverse byte order (32 bit) This function reverses the byte order in integer value. \param [in] value Value to reverse \return Reversed value */ __attribute__((always_inline)) __STATIC_INLINE uint32_t __REV(uint32_t value) { #if (__GNUC__ > 4) || (__GNUC__ == 4 && __GNUC_MINOR__ >= 5) return __builtin_bswap32(value); #else uint32_t result; __ASM volatile ("rev %0, %1" : __CMSIS_GCC_OUT_REG (result) : __CMSIS_GCC_USE_REG (value) ); return(result); #endif } /** \brief Reverse byte order (16 bit) This function reverses the byte order in two unsigned short values. \param [in] value Value to reverse \return Reversed value */ __attribute__((always_inline)) __STATIC_INLINE uint32_t __REV16(uint32_t value) { uint32_t result; __ASM volatile ("rev16 %0, %1" : __CMSIS_GCC_OUT_REG (result) : __CMSIS_GCC_USE_REG (value) ); return(result); } /** \brief Reverse byte order in signed short value This function reverses the byte order in a signed short value with sign extension to integer. \param [in] value Value to reverse \return Reversed value */ __attribute__((always_inline)) __STATIC_INLINE int32_t __REVSH(int32_t value) { #if (__GNUC__ > 4) || (__GNUC__ == 4 && __GNUC_MINOR__ >= 8) return (short)__builtin_bswap16(value); #else uint32_t result; __ASM volatile ("revsh %0, %1" : __CMSIS_GCC_OUT_REG (result) : __CMSIS_GCC_USE_REG (value) ); return(result); #endif } /** \brief Rotate Right in unsigned value (32 bit) This function Rotate Right (immediate) provides the value of the contents of a register rotated by a variable number of bits. \param [in] value Value to rotate \param [in] value Number of Bits to rotate \return Rotated value */ __attribute__((always_inline)) __STATIC_INLINE uint32_t __ROR(uint32_t op1, uint32_t op2) { return (op1 >> op2) | (op1 << (32 - op2)); } /** \brief Breakpoint This function causes the processor to enter Debug state. Debug tools can use this to investigate system state when the instruction at a particular address is reached. \param [in] value is ignored by the processor. If required, a debugger can use it to store additional information about the breakpoint. */ #define __BKPT(value) __ASM volatile ("bkpt "#value) /** \brief Reverse bit order of value This function reverses the bit order of the given value. \param [in] value Value to reverse \return Reversed value */ __attribute__((always_inline)) __STATIC_INLINE uint32_t __RBIT(uint32_t value) { uint32_t result; #if (__CORTEX_M >= 0x03) || (__CORTEX_SC >= 300) __ASM volatile ("rbit %0, %1" : "=r" (result) : "r" (value) ); #else int32_t s = 4 /*sizeof(v)*/ * 8 - 1; // extra shift needed at end result = value; // r will be reversed bits of v; first get LSB of v for (value >>= 1; value; value >>= 1) { result <<= 1; result |= value & 1; s--; } result <<= s; // shift when v's highest bits are zero #endif return(result); } /** \brief Count leading zeros This function counts the number of leading zeros of a data value. \param [in] value Value to count the leading zeros \return number of leading zeros in value */ #define __CLZ __builtin_clz #if (__CORTEX_M >= 0x03) || (__CORTEX_SC >= 300) /** \brief LDR Exclusive (8 bit) This function executes a exclusive LDR instruction for 8 bit value. \param [in] ptr Pointer to data \return value of type uint8_t at (*ptr) */ __attribute__((always_inline)) __STATIC_INLINE uint8_t __LDREXB(volatile uint8_t *addr) { uint32_t result; #if (__GNUC__ > 4) || (__GNUC__ == 4 && __GNUC_MINOR__ >= 8) __ASM volatile ("ldrexb %0, %1" : "=r" (result) : "Q" (*addr) ); #else /* Prior to GCC 4.8, "Q" will be expanded to [rx, #0] which is not accepted by assembler. So has to use following less efficient pattern. */ __ASM volatile ("ldrexb %0, [%1]" : "=r" (result) : "r" (addr) : "memory" ); #endif return ((uint8_t) result); /* Add explicit type cast here */ } /** \brief LDR Exclusive (16 bit) This function executes a exclusive LDR instruction for 16 bit values. \param [in] ptr Pointer to data \return value of type uint16_t at (*ptr) */ __attribute__((always_inline)) __STATIC_INLINE uint16_t __LDREXH(volatile uint16_t *addr) { uint32_t result; #if (__GNUC__ > 4) || (__GNUC__ == 4 && __GNUC_MINOR__ >= 8) __ASM volatile ("ldrexh %0, %1" : "=r" (result) : "Q" (*addr) ); #else /* Prior to GCC 4.8, "Q" will be expanded to [rx, #0] which is not accepted by assembler. So has to use following less efficient pattern. */ __ASM volatile ("ldrexh %0, [%1]" : "=r" (result) : "r" (addr) : "memory" ); #endif return ((uint16_t) result); /* Add explicit type cast here */ } /** \brief LDR Exclusive (32 bit) This function executes a exclusive LDR instruction for 32 bit values. \param [in] ptr Pointer to data \return value of type uint32_t at (*ptr) */ __attribute__((always_inline)) __STATIC_INLINE uint32_t __LDREXW(volatile uint32_t *addr) { uint32_t result; __ASM volatile ("ldrex %0, %1" : "=r" (result) : "Q" (*addr) ); return(result); } /** \brief STR Exclusive (8 bit) This function executes a exclusive STR instruction for 8 bit values. \param [in] value Value to store \param [in] ptr Pointer to location \return 0 Function succeeded \return 1 Function failed */ __attribute__((always_inline)) __STATIC_INLINE uint32_t __STREXB(uint8_t value, volatile uint8_t *addr) { uint32_t result; __ASM volatile ("strexb %0, %2, %1" : "=&r" (result), "=Q" (*addr) : "r" ((uint32_t)value) ); return(result); } /** \brief STR Exclusive (16 bit) This function executes a exclusive STR instruction for 16 bit values. \param [in] value Value to store \param [in] ptr Pointer to location \return 0 Function succeeded \return 1 Function failed */ __attribute__((always_inline)) __STATIC_INLINE uint32_t __STREXH(uint16_t value, volatile uint16_t *addr) { uint32_t result; __ASM volatile ("strexh %0, %2, %1" : "=&r" (result), "=Q" (*addr) : "r" ((uint32_t)value) ); return(result); } /** \brief STR Exclusive (32 bit) This function executes a exclusive STR instruction for 32 bit values. \param [in] value Value to store \param [in] ptr Pointer to location \return 0 Function succeeded \return 1 Function failed */ __attribute__((always_inline)) __STATIC_INLINE uint32_t __STREXW(uint32_t value, volatile uint32_t *addr) { uint32_t result; __ASM volatile ("strex %0, %2, %1" : "=&r" (result), "=Q" (*addr) : "r" (value) ); return(result); } /** \brief Remove the exclusive lock This function removes the exclusive lock which is created by LDREX. */ __attribute__((always_inline)) __STATIC_INLINE void __CLREX(void) { __ASM volatile ("clrex" ::: "memory"); } /** \brief Signed Saturate This function saturates a signed value. \param [in] value Value to be saturated \param [in] sat Bit position to saturate to (1..32) \return Saturated value */ #define __SSAT(ARG1,ARG2) \ ({ \ uint32_t __RES, __ARG1 = (ARG1); \ __ASM ("ssat %0, %1, %2" : "=r" (__RES) : "I" (ARG2), "r" (__ARG1) ); \ __RES; \ }) /** \brief Unsigned Saturate This function saturates an unsigned value. \param [in] value Value to be saturated \param [in] sat Bit position to saturate to (0..31) \return Saturated value */ #define __USAT(ARG1,ARG2) \ ({ \ uint32_t __RES, __ARG1 = (ARG1); \ __ASM ("usat %0, %1, %2" : "=r" (__RES) : "I" (ARG2), "r" (__ARG1) ); \ __RES; \ }) /** \brief Rotate Right with Extend (32 bit) This function moves each bit of a bitstring right by one bit. The carry input is shifted in at the left end of the bitstring. \param [in] value Value to rotate \return Rotated value */ __attribute__((always_inline)) __STATIC_INLINE uint32_t __RRX(uint32_t value) { uint32_t result; __ASM volatile ("rrx %0, %1" : __CMSIS_GCC_OUT_REG (result) : __CMSIS_GCC_USE_REG (value) ); return(result); } /** \brief LDRT Unprivileged (8 bit) This function executes a Unprivileged LDRT instruction for 8 bit value. \param [in] ptr Pointer to data \return value of type uint8_t at (*ptr) */ __attribute__((always_inline)) __STATIC_INLINE uint8_t __LDRBT(volatile uint8_t *addr) { uint32_t result; #if (__GNUC__ > 4) || (__GNUC__ == 4 && __GNUC_MINOR__ >= 8) __ASM volatile ("ldrbt %0, %1" : "=r" (result) : "Q" (*addr) ); #else /* Prior to GCC 4.8, "Q" will be expanded to [rx, #0] which is not accepted by assembler. So has to use following less efficient pattern. */ __ASM volatile ("ldrbt %0, [%1]" : "=r" (result) : "r" (addr) : "memory" ); #endif return ((uint8_t) result); /* Add explicit type cast here */ } /** \brief LDRT Unprivileged (16 bit) This function executes a Unprivileged LDRT instruction for 16 bit values. \param [in] ptr Pointer to data \return value of type uint16_t at (*ptr) */ __attribute__((always_inline)) __STATIC_INLINE uint16_t __LDRHT(volatile uint16_t *addr) { uint32_t result; #if (__GNUC__ > 4) || (__GNUC__ == 4 && __GNUC_MINOR__ >= 8) __ASM volatile ("ldrht %0, %1" : "=r" (result) : "Q" (*addr) ); #else /* Prior to GCC 4.8, "Q" will be expanded to [rx, #0] which is not accepted by assembler. So has to use following less efficient pattern. */ __ASM volatile ("ldrht %0, [%1]" : "=r" (result) : "r" (addr) : "memory" ); #endif return ((uint16_t) result); /* Add explicit type cast here */ } /** \brief LDRT Unprivileged (32 bit) This function executes a Unprivileged LDRT instruction for 32 bit values. \param [in] ptr Pointer to data \return value of type uint32_t at (*ptr) */ __attribute__((always_inline)) __STATIC_INLINE uint32_t __LDRT(volatile uint32_t *addr) { uint32_t result; __ASM volatile ("ldrt %0, %1" : "=r" (result) : "Q" (*addr) ); return(result); } /** \brief STRT Unprivileged (8 bit) This function executes a Unprivileged STRT instruction for 8 bit values. \param [in] value Value to store \param [in] ptr Pointer to location */ __attribute__((always_inline)) __STATIC_INLINE void __STRBT(uint8_t value, volatile uint8_t *addr) { __ASM volatile ("strbt %1, %0" : "=Q" (*addr) : "r" ((uint32_t)value) ); } /** \brief STRT Unprivileged (16 bit) This function executes a Unprivileged STRT instruction for 16 bit values. \param [in] value Value to store \param [in] ptr Pointer to location */ __attribute__((always_inline)) __STATIC_INLINE void __STRHT(uint16_t value, volatile uint16_t *addr) { __ASM volatile ("strht %1, %0" : "=Q" (*addr) : "r" ((uint32_t)value) ); } /** \brief STRT Unprivileged (32 bit) This function executes a Unprivileged STRT instruction for 32 bit values. \param [in] value Value to store \param [in] ptr Pointer to location */ __attribute__((always_inline)) __STATIC_INLINE void __STRT(uint32_t value, volatile uint32_t *addr) { __ASM volatile ("strt %1, %0" : "=Q" (*addr) : "r" (value) ); } #endif /* (__CORTEX_M >= 0x03) || (__CORTEX_SC >= 300) */ #elif defined ( __ICCARM__ ) /*------------------ ICC Compiler -------------------*/ /* IAR iccarm specific functions */ #include #elif defined ( __TMS470__ ) /*---------------- TI CCS Compiler ------------------*/ /* TI CCS specific functions */ #include #elif defined ( __TASKING__ ) /*------------------ TASKING Compiler --------------*/ /* TASKING carm specific functions */ /* * The CMSIS functions have been implemented as intrinsics in the compiler. * Please use "carm -?i" to get an up to date list of all intrinsics, * Including the CMSIS ones. */ #elif defined ( __CSMC__ ) /*------------------ COSMIC Compiler -------------------*/ /* Cosmic specific functions */ #include #endif /*@}*/ /* end of group CMSIS_Core_InstructionInterface */ #endif /* __CORE_CMINSTR_H */ ================================================ FILE: Zelig/mbed/TARGET_NUCLEO_F411RE/core_cmSimd.h ================================================ /**************************************************************************//** * @file core_cmSimd.h * @brief CMSIS Cortex-M SIMD Header File * @version V4.10 * @date 18. March 2015 * * @note * ******************************************************************************/ /* Copyright (c) 2009 - 2014 ARM LIMITED All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: - Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. - Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. - Neither the name of ARM 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 COPYRIGHT HOLDERS AND 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. ---------------------------------------------------------------------------*/ #if defined ( __ICCARM__ ) #pragma system_include /* treat file as system include file for MISRA check */ #endif #ifndef __CORE_CMSIMD_H #define __CORE_CMSIMD_H #ifdef __cplusplus extern "C" { #endif /******************************************************************************* * Hardware Abstraction Layer ******************************************************************************/ /* ################### Compiler specific Intrinsics ########################### */ /** \defgroup CMSIS_SIMD_intrinsics CMSIS SIMD Intrinsics Access to dedicated SIMD instructions @{ */ #if defined ( __CC_ARM ) /*------------------RealView Compiler -----------------*/ /* ARM armcc specific functions */ #define __SADD8 __sadd8 #define __QADD8 __qadd8 #define __SHADD8 __shadd8 #define __UADD8 __uadd8 #define __UQADD8 __uqadd8 #define __UHADD8 __uhadd8 #define __SSUB8 __ssub8 #define __QSUB8 __qsub8 #define __SHSUB8 __shsub8 #define __USUB8 __usub8 #define __UQSUB8 __uqsub8 #define __UHSUB8 __uhsub8 #define __SADD16 __sadd16 #define __QADD16 __qadd16 #define __SHADD16 __shadd16 #define __UADD16 __uadd16 #define __UQADD16 __uqadd16 #define __UHADD16 __uhadd16 #define __SSUB16 __ssub16 #define __QSUB16 __qsub16 #define __SHSUB16 __shsub16 #define __USUB16 __usub16 #define __UQSUB16 __uqsub16 #define __UHSUB16 __uhsub16 #define __SASX __sasx #define __QASX __qasx #define __SHASX __shasx #define __UASX __uasx #define __UQASX __uqasx #define __UHASX __uhasx #define __SSAX __ssax #define __QSAX __qsax #define __SHSAX __shsax #define __USAX __usax #define __UQSAX __uqsax #define __UHSAX __uhsax #define __USAD8 __usad8 #define __USADA8 __usada8 #define __SSAT16 __ssat16 #define __USAT16 __usat16 #define __UXTB16 __uxtb16 #define __UXTAB16 __uxtab16 #define __SXTB16 __sxtb16 #define __SXTAB16 __sxtab16 #define __SMUAD __smuad #define __SMUADX __smuadx #define __SMLAD __smlad #define __SMLADX __smladx #define __SMLALD __smlald #define __SMLALDX __smlaldx #define __SMUSD __smusd #define __SMUSDX __smusdx #define __SMLSD __smlsd #define __SMLSDX __smlsdx #define __SMLSLD __smlsld #define __SMLSLDX __smlsldx #define __SEL __sel #define __QADD __qadd #define __QSUB __qsub #define __PKHBT(ARG1,ARG2,ARG3) ( ((((uint32_t)(ARG1)) ) & 0x0000FFFFUL) | \ ((((uint32_t)(ARG2)) << (ARG3)) & 0xFFFF0000UL) ) #define __PKHTB(ARG1,ARG2,ARG3) ( ((((uint32_t)(ARG1)) ) & 0xFFFF0000UL) | \ ((((uint32_t)(ARG2)) >> (ARG3)) & 0x0000FFFFUL) ) #define __SMMLA(ARG1,ARG2,ARG3) ( (int32_t)((((int64_t)(ARG1) * (ARG2)) + \ ((int64_t)(ARG3) << 32) ) >> 32)) #elif defined ( __GNUC__ ) /*------------------ GNU Compiler ---------------------*/ /* GNU gcc specific functions */ __attribute__( ( always_inline ) ) __STATIC_INLINE uint32_t __SADD8(uint32_t op1, uint32_t op2) { uint32_t result; __ASM volatile ("sadd8 %0, %1, %2" : "=r" (result) : "r" (op1), "r" (op2) ); return(result); } __attribute__( ( always_inline ) ) __STATIC_INLINE uint32_t __QADD8(uint32_t op1, uint32_t op2) { uint32_t result; __ASM volatile ("qadd8 %0, %1, %2" : "=r" (result) : "r" (op1), "r" (op2) ); return(result); } __attribute__( ( always_inline ) ) __STATIC_INLINE uint32_t __SHADD8(uint32_t op1, uint32_t op2) { uint32_t result; __ASM volatile ("shadd8 %0, %1, %2" : "=r" (result) : "r" (op1), "r" (op2) ); return(result); } __attribute__( ( always_inline ) ) __STATIC_INLINE uint32_t __UADD8(uint32_t op1, uint32_t op2) { uint32_t result; __ASM volatile ("uadd8 %0, %1, %2" : "=r" (result) : "r" (op1), "r" (op2) ); return(result); } __attribute__( ( always_inline ) ) __STATIC_INLINE uint32_t __UQADD8(uint32_t op1, uint32_t op2) { uint32_t result; __ASM volatile ("uqadd8 %0, %1, %2" : "=r" (result) : "r" (op1), "r" (op2) ); return(result); } __attribute__( ( always_inline ) ) __STATIC_INLINE uint32_t __UHADD8(uint32_t op1, uint32_t op2) { uint32_t result; __ASM volatile ("uhadd8 %0, %1, %2" : "=r" (result) : "r" (op1), "r" (op2) ); return(result); } __attribute__( ( always_inline ) ) __STATIC_INLINE uint32_t __SSUB8(uint32_t op1, uint32_t op2) { uint32_t result; __ASM volatile ("ssub8 %0, %1, %2" : "=r" (result) : "r" (op1), "r" (op2) ); return(result); } __attribute__( ( always_inline ) ) __STATIC_INLINE uint32_t __QSUB8(uint32_t op1, uint32_t op2) { uint32_t result; __ASM volatile ("qsub8 %0, %1, %2" : "=r" (result) : "r" (op1), "r" (op2) ); return(result); } __attribute__( ( always_inline ) ) __STATIC_INLINE uint32_t __SHSUB8(uint32_t op1, uint32_t op2) { uint32_t result; __ASM volatile ("shsub8 %0, %1, %2" : "=r" (result) : "r" (op1), "r" (op2) ); return(result); } __attribute__( ( always_inline ) ) __STATIC_INLINE uint32_t __USUB8(uint32_t op1, uint32_t op2) { uint32_t result; __ASM volatile ("usub8 %0, %1, %2" : "=r" (result) : "r" (op1), "r" (op2) ); return(result); } __attribute__( ( always_inline ) ) __STATIC_INLINE uint32_t __UQSUB8(uint32_t op1, uint32_t op2) { uint32_t result; __ASM volatile ("uqsub8 %0, %1, %2" : "=r" (result) : "r" (op1), "r" (op2) ); return(result); } __attribute__( ( always_inline ) ) __STATIC_INLINE uint32_t __UHSUB8(uint32_t op1, uint32_t op2) { uint32_t result; __ASM volatile ("uhsub8 %0, %1, %2" : "=r" (result) : "r" (op1), "r" (op2) ); return(result); } __attribute__( ( always_inline ) ) __STATIC_INLINE uint32_t __SADD16(uint32_t op1, uint32_t op2) { uint32_t result; __ASM volatile ("sadd16 %0, %1, %2" : "=r" (result) : "r" (op1), "r" (op2) ); return(result); } __attribute__( ( always_inline ) ) __STATIC_INLINE uint32_t __QADD16(uint32_t op1, uint32_t op2) { uint32_t result; __ASM volatile ("qadd16 %0, %1, %2" : "=r" (result) : "r" (op1), "r" (op2) ); return(result); } __attribute__( ( always_inline ) ) __STATIC_INLINE uint32_t __SHADD16(uint32_t op1, uint32_t op2) { uint32_t result; __ASM volatile ("shadd16 %0, %1, %2" : "=r" (result) : "r" (op1), "r" (op2) ); return(result); } __attribute__( ( always_inline ) ) __STATIC_INLINE uint32_t __UADD16(uint32_t op1, uint32_t op2) { uint32_t result; __ASM volatile ("uadd16 %0, %1, %2" : "=r" (result) : "r" (op1), "r" (op2) ); return(result); } __attribute__( ( always_inline ) ) __STATIC_INLINE uint32_t __UQADD16(uint32_t op1, uint32_t op2) { uint32_t result; __ASM volatile ("uqadd16 %0, %1, %2" : "=r" (result) : "r" (op1), "r" (op2) ); return(result); } __attribute__( ( always_inline ) ) __STATIC_INLINE uint32_t __UHADD16(uint32_t op1, uint32_t op2) { uint32_t result; __ASM volatile ("uhadd16 %0, %1, %2" : "=r" (result) : "r" (op1), "r" (op2) ); return(result); } __attribute__( ( always_inline ) ) __STATIC_INLINE uint32_t __SSUB16(uint32_t op1, uint32_t op2) { uint32_t result; __ASM volatile ("ssub16 %0, %1, %2" : "=r" (result) : "r" (op1), "r" (op2) ); return(result); } __attribute__( ( always_inline ) ) __STATIC_INLINE uint32_t __QSUB16(uint32_t op1, uint32_t op2) { uint32_t result; __ASM volatile ("qsub16 %0, %1, %2" : "=r" (result) : "r" (op1), "r" (op2) ); return(result); } __attribute__( ( always_inline ) ) __STATIC_INLINE uint32_t __SHSUB16(uint32_t op1, uint32_t op2) { uint32_t result; __ASM volatile ("shsub16 %0, %1, %2" : "=r" (result) : "r" (op1), "r" (op2) ); return(result); } __attribute__( ( always_inline ) ) __STATIC_INLINE uint32_t __USUB16(uint32_t op1, uint32_t op2) { uint32_t result; __ASM volatile ("usub16 %0, %1, %2" : "=r" (result) : "r" (op1), "r" (op2) ); return(result); } __attribute__( ( always_inline ) ) __STATIC_INLINE uint32_t __UQSUB16(uint32_t op1, uint32_t op2) { uint32_t result; __ASM volatile ("uqsub16 %0, %1, %2" : "=r" (result) : "r" (op1), "r" (op2) ); return(result); } __attribute__( ( always_inline ) ) __STATIC_INLINE uint32_t __UHSUB16(uint32_t op1, uint32_t op2) { uint32_t result; __ASM volatile ("uhsub16 %0, %1, %2" : "=r" (result) : "r" (op1), "r" (op2) ); return(result); } __attribute__( ( always_inline ) ) __STATIC_INLINE uint32_t __SASX(uint32_t op1, uint32_t op2) { uint32_t result; __ASM volatile ("sasx %0, %1, %2" : "=r" (result) : "r" (op1), "r" (op2) ); return(result); } __attribute__( ( always_inline ) ) __STATIC_INLINE uint32_t __QASX(uint32_t op1, uint32_t op2) { uint32_t result; __ASM volatile ("qasx %0, %1, %2" : "=r" (result) : "r" (op1), "r" (op2) ); return(result); } __attribute__( ( always_inline ) ) __STATIC_INLINE uint32_t __SHASX(uint32_t op1, uint32_t op2) { uint32_t result; __ASM volatile ("shasx %0, %1, %2" : "=r" (result) : "r" (op1), "r" (op2) ); return(result); } __attribute__( ( always_inline ) ) __STATIC_INLINE uint32_t __UASX(uint32_t op1, uint32_t op2) { uint32_t result; __ASM volatile ("uasx %0, %1, %2" : "=r" (result) : "r" (op1), "r" (op2) ); return(result); } __attribute__( ( always_inline ) ) __STATIC_INLINE uint32_t __UQASX(uint32_t op1, uint32_t op2) { uint32_t result; __ASM volatile ("uqasx %0, %1, %2" : "=r" (result) : "r" (op1), "r" (op2) ); return(result); } __attribute__( ( always_inline ) ) __STATIC_INLINE uint32_t __UHASX(uint32_t op1, uint32_t op2) { uint32_t result; __ASM volatile ("uhasx %0, %1, %2" : "=r" (result) : "r" (op1), "r" (op2) ); return(result); } __attribute__( ( always_inline ) ) __STATIC_INLINE uint32_t __SSAX(uint32_t op1, uint32_t op2) { uint32_t result; __ASM volatile ("ssax %0, %1, %2" : "=r" (result) : "r" (op1), "r" (op2) ); return(result); } __attribute__( ( always_inline ) ) __STATIC_INLINE uint32_t __QSAX(uint32_t op1, uint32_t op2) { uint32_t result; __ASM volatile ("qsax %0, %1, %2" : "=r" (result) : "r" (op1), "r" (op2) ); return(result); } __attribute__( ( always_inline ) ) __STATIC_INLINE uint32_t __SHSAX(uint32_t op1, uint32_t op2) { uint32_t result; __ASM volatile ("shsax %0, %1, %2" : "=r" (result) : "r" (op1), "r" (op2) ); return(result); } __attribute__( ( always_inline ) ) __STATIC_INLINE uint32_t __USAX(uint32_t op1, uint32_t op2) { uint32_t result; __ASM volatile ("usax %0, %1, %2" : "=r" (result) : "r" (op1), "r" (op2) ); return(result); } __attribute__( ( always_inline ) ) __STATIC_INLINE uint32_t __UQSAX(uint32_t op1, uint32_t op2) { uint32_t result; __ASM volatile ("uqsax %0, %1, %2" : "=r" (result) : "r" (op1), "r" (op2) ); return(result); } __attribute__( ( always_inline ) ) __STATIC_INLINE uint32_t __UHSAX(uint32_t op1, uint32_t op2) { uint32_t result; __ASM volatile ("uhsax %0, %1, %2" : "=r" (result) : "r" (op1), "r" (op2) ); return(result); } __attribute__( ( always_inline ) ) __STATIC_INLINE uint32_t __USAD8(uint32_t op1, uint32_t op2) { uint32_t result; __ASM volatile ("usad8 %0, %1, %2" : "=r" (result) : "r" (op1), "r" (op2) ); return(result); } __attribute__( ( always_inline ) ) __STATIC_INLINE uint32_t __USADA8(uint32_t op1, uint32_t op2, uint32_t op3) { uint32_t result; __ASM volatile ("usada8 %0, %1, %2, %3" : "=r" (result) : "r" (op1), "r" (op2), "r" (op3) ); return(result); } #define __SSAT16(ARG1,ARG2) \ ({ \ uint32_t __RES, __ARG1 = (ARG1); \ __ASM ("ssat16 %0, %1, %2" : "=r" (__RES) : "I" (ARG2), "r" (__ARG1) ); \ __RES; \ }) #define __USAT16(ARG1,ARG2) \ ({ \ uint32_t __RES, __ARG1 = (ARG1); \ __ASM ("usat16 %0, %1, %2" : "=r" (__RES) : "I" (ARG2), "r" (__ARG1) ); \ __RES; \ }) __attribute__( ( always_inline ) ) __STATIC_INLINE uint32_t __UXTB16(uint32_t op1) { uint32_t result; __ASM volatile ("uxtb16 %0, %1" : "=r" (result) : "r" (op1)); return(result); } __attribute__( ( always_inline ) ) __STATIC_INLINE uint32_t __UXTAB16(uint32_t op1, uint32_t op2) { uint32_t result; __ASM volatile ("uxtab16 %0, %1, %2" : "=r" (result) : "r" (op1), "r" (op2) ); return(result); } __attribute__( ( always_inline ) ) __STATIC_INLINE uint32_t __SXTB16(uint32_t op1) { uint32_t result; __ASM volatile ("sxtb16 %0, %1" : "=r" (result) : "r" (op1)); return(result); } __attribute__( ( always_inline ) ) __STATIC_INLINE uint32_t __SXTAB16(uint32_t op1, uint32_t op2) { uint32_t result; __ASM volatile ("sxtab16 %0, %1, %2" : "=r" (result) : "r" (op1), "r" (op2) ); return(result); } __attribute__( ( always_inline ) ) __STATIC_INLINE uint32_t __SMUAD (uint32_t op1, uint32_t op2) { uint32_t result; __ASM volatile ("smuad %0, %1, %2" : "=r" (result) : "r" (op1), "r" (op2) ); return(result); } __attribute__( ( always_inline ) ) __STATIC_INLINE uint32_t __SMUADX (uint32_t op1, uint32_t op2) { uint32_t result; __ASM volatile ("smuadx %0, %1, %2" : "=r" (result) : "r" (op1), "r" (op2) ); return(result); } __attribute__( ( always_inline ) ) __STATIC_INLINE uint32_t __SMLAD (uint32_t op1, uint32_t op2, uint32_t op3) { uint32_t result; __ASM volatile ("smlad %0, %1, %2, %3" : "=r" (result) : "r" (op1), "r" (op2), "r" (op3) ); return(result); } __attribute__( ( always_inline ) ) __STATIC_INLINE uint32_t __SMLADX (uint32_t op1, uint32_t op2, uint32_t op3) { uint32_t result; __ASM volatile ("smladx %0, %1, %2, %3" : "=r" (result) : "r" (op1), "r" (op2), "r" (op3) ); return(result); } __attribute__( ( always_inline ) ) __STATIC_INLINE uint64_t __SMLALD (uint32_t op1, uint32_t op2, uint64_t acc) { union llreg_u{ uint32_t w32[2]; uint64_t w64; } llr; llr.w64 = acc; #ifndef __ARMEB__ // Little endian __ASM volatile ("smlald %0, %1, %2, %3" : "=r" (llr.w32[0]), "=r" (llr.w32[1]): "r" (op1), "r" (op2) , "0" (llr.w32[0]), "1" (llr.w32[1]) ); #else // Big endian __ASM volatile ("smlald %0, %1, %2, %3" : "=r" (llr.w32[1]), "=r" (llr.w32[0]): "r" (op1), "r" (op2) , "0" (llr.w32[1]), "1" (llr.w32[0]) ); #endif return(llr.w64); } __attribute__( ( always_inline ) ) __STATIC_INLINE uint64_t __SMLALDX (uint32_t op1, uint32_t op2, uint64_t acc) { union llreg_u{ uint32_t w32[2]; uint64_t w64; } llr; llr.w64 = acc; #ifndef __ARMEB__ // Little endian __ASM volatile ("smlaldx %0, %1, %2, %3" : "=r" (llr.w32[0]), "=r" (llr.w32[1]): "r" (op1), "r" (op2) , "0" (llr.w32[0]), "1" (llr.w32[1]) ); #else // Big endian __ASM volatile ("smlaldx %0, %1, %2, %3" : "=r" (llr.w32[1]), "=r" (llr.w32[0]): "r" (op1), "r" (op2) , "0" (llr.w32[1]), "1" (llr.w32[0]) ); #endif return(llr.w64); } __attribute__( ( always_inline ) ) __STATIC_INLINE uint32_t __SMUSD (uint32_t op1, uint32_t op2) { uint32_t result; __ASM volatile ("smusd %0, %1, %2" : "=r" (result) : "r" (op1), "r" (op2) ); return(result); } __attribute__( ( always_inline ) ) __STATIC_INLINE uint32_t __SMUSDX (uint32_t op1, uint32_t op2) { uint32_t result; __ASM volatile ("smusdx %0, %1, %2" : "=r" (result) : "r" (op1), "r" (op2) ); return(result); } __attribute__( ( always_inline ) ) __STATIC_INLINE uint32_t __SMLSD (uint32_t op1, uint32_t op2, uint32_t op3) { uint32_t result; __ASM volatile ("smlsd %0, %1, %2, %3" : "=r" (result) : "r" (op1), "r" (op2), "r" (op3) ); return(result); } __attribute__( ( always_inline ) ) __STATIC_INLINE uint32_t __SMLSDX (uint32_t op1, uint32_t op2, uint32_t op3) { uint32_t result; __ASM volatile ("smlsdx %0, %1, %2, %3" : "=r" (result) : "r" (op1), "r" (op2), "r" (op3) ); return(result); } __attribute__( ( always_inline ) ) __STATIC_INLINE uint64_t __SMLSLD (uint32_t op1, uint32_t op2, uint64_t acc) { union llreg_u{ uint32_t w32[2]; uint64_t w64; } llr; llr.w64 = acc; #ifndef __ARMEB__ // Little endian __ASM volatile ("smlsld %0, %1, %2, %3" : "=r" (llr.w32[0]), "=r" (llr.w32[1]): "r" (op1), "r" (op2) , "0" (llr.w32[0]), "1" (llr.w32[1]) ); #else // Big endian __ASM volatile ("smlsld %0, %1, %2, %3" : "=r" (llr.w32[1]), "=r" (llr.w32[0]): "r" (op1), "r" (op2) , "0" (llr.w32[1]), "1" (llr.w32[0]) ); #endif return(llr.w64); } __attribute__( ( always_inline ) ) __STATIC_INLINE uint64_t __SMLSLDX (uint32_t op1, uint32_t op2, uint64_t acc) { union llreg_u{ uint32_t w32[2]; uint64_t w64; } llr; llr.w64 = acc; #ifndef __ARMEB__ // Little endian __ASM volatile ("smlsldx %0, %1, %2, %3" : "=r" (llr.w32[0]), "=r" (llr.w32[1]): "r" (op1), "r" (op2) , "0" (llr.w32[0]), "1" (llr.w32[1]) ); #else // Big endian __ASM volatile ("smlsldx %0, %1, %2, %3" : "=r" (llr.w32[1]), "=r" (llr.w32[0]): "r" (op1), "r" (op2) , "0" (llr.w32[1]), "1" (llr.w32[0]) ); #endif return(llr.w64); } __attribute__( ( always_inline ) ) __STATIC_INLINE uint32_t __SEL (uint32_t op1, uint32_t op2) { uint32_t result; __ASM volatile ("sel %0, %1, %2" : "=r" (result) : "r" (op1), "r" (op2) ); return(result); } __attribute__( ( always_inline ) ) __STATIC_INLINE uint32_t __QADD(uint32_t op1, uint32_t op2) { uint32_t result; __ASM volatile ("qadd %0, %1, %2" : "=r" (result) : "r" (op1), "r" (op2) ); return(result); } __attribute__( ( always_inline ) ) __STATIC_INLINE uint32_t __QSUB(uint32_t op1, uint32_t op2) { uint32_t result; __ASM volatile ("qsub %0, %1, %2" : "=r" (result) : "r" (op1), "r" (op2) ); return(result); } #define __PKHBT(ARG1,ARG2,ARG3) \ ({ \ uint32_t __RES, __ARG1 = (ARG1), __ARG2 = (ARG2); \ __ASM ("pkhbt %0, %1, %2, lsl %3" : "=r" (__RES) : "r" (__ARG1), "r" (__ARG2), "I" (ARG3) ); \ __RES; \ }) #define __PKHTB(ARG1,ARG2,ARG3) \ ({ \ uint32_t __RES, __ARG1 = (ARG1), __ARG2 = (ARG2); \ if (ARG3 == 0) \ __ASM ("pkhtb %0, %1, %2" : "=r" (__RES) : "r" (__ARG1), "r" (__ARG2) ); \ else \ __ASM ("pkhtb %0, %1, %2, asr %3" : "=r" (__RES) : "r" (__ARG1), "r" (__ARG2), "I" (ARG3) ); \ __RES; \ }) __attribute__( ( always_inline ) ) __STATIC_INLINE uint32_t __SMMLA (int32_t op1, int32_t op2, int32_t op3) { int32_t result; __ASM volatile ("smmla %0, %1, %2, %3" : "=r" (result): "r" (op1), "r" (op2), "r" (op3) ); return(result); } #elif defined ( __ICCARM__ ) /*------------------ ICC Compiler -------------------*/ /* IAR iccarm specific functions */ #include #elif defined ( __TMS470__ ) /*---------------- TI CCS Compiler ------------------*/ /* TI CCS specific functions */ #include #elif defined ( __TASKING__ ) /*------------------ TASKING Compiler --------------*/ /* TASKING carm specific functions */ /* not yet supported */ #elif defined ( __CSMC__ ) /*------------------ COSMIC Compiler -------------------*/ /* Cosmic specific functions */ #include #endif /*@} end of group CMSIS_SIMD_intrinsics */ #ifdef __cplusplus } #endif #endif /* __CORE_CMSIMD_H */ ================================================ FILE: Zelig/mbed/TARGET_NUCLEO_F411RE/core_sc000.h ================================================ /**************************************************************************//** * @file core_sc000.h * @brief CMSIS SC000 Core Peripheral Access Layer Header File * @version V4.10 * @date 18. March 2015 * * @note * ******************************************************************************/ /* Copyright (c) 2009 - 2015 ARM LIMITED All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: - Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. - Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. - Neither the name of ARM 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 COPYRIGHT HOLDERS AND 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. ---------------------------------------------------------------------------*/ #if defined ( __ICCARM__ ) #pragma system_include /* treat file as system include file for MISRA check */ #endif #ifndef __CORE_SC000_H_GENERIC #define __CORE_SC000_H_GENERIC #ifdef __cplusplus extern "C" { #endif /** \page CMSIS_MISRA_Exceptions MISRA-C:2004 Compliance Exceptions CMSIS violates the following MISRA-C:2004 rules: \li Required Rule 8.5, object/function definition in header file.
Function definitions in header files are used to allow 'inlining'. \li Required Rule 18.4, declaration of union type or object of union type: '{...}'.
Unions are used for effective representation of core registers. \li Advisory Rule 19.7, Function-like macro defined.
Function-like macros are used to allow more efficient code. */ /******************************************************************************* * CMSIS definitions ******************************************************************************/ /** \ingroup SC000 @{ */ /* CMSIS SC000 definitions */ #define __SC000_CMSIS_VERSION_MAIN (0x04) /*!< [31:16] CMSIS HAL main version */ #define __SC000_CMSIS_VERSION_SUB (0x00) /*!< [15:0] CMSIS HAL sub version */ #define __SC000_CMSIS_VERSION ((__SC000_CMSIS_VERSION_MAIN << 16) | \ __SC000_CMSIS_VERSION_SUB ) /*!< CMSIS HAL version number */ #define __CORTEX_SC (000) /*!< Cortex secure core */ #if defined ( __CC_ARM ) #define __ASM __asm /*!< asm keyword for ARM Compiler */ #define __INLINE __inline /*!< inline keyword for ARM Compiler */ #define __STATIC_INLINE static __inline #elif defined ( __GNUC__ ) #define __ASM __asm /*!< asm keyword for GNU Compiler */ #define __INLINE inline /*!< inline keyword for GNU Compiler */ #define __STATIC_INLINE static inline #elif defined ( __ICCARM__ ) #define __ASM __asm /*!< asm keyword for IAR Compiler */ #define __INLINE inline /*!< inline keyword for IAR Compiler. Only available in High optimization mode! */ #define __STATIC_INLINE static inline #elif defined ( __TMS470__ ) #define __ASM __asm /*!< asm keyword for TI CCS Compiler */ #define __STATIC_INLINE static inline #elif defined ( __TASKING__ ) #define __ASM __asm /*!< asm keyword for TASKING Compiler */ #define __INLINE inline /*!< inline keyword for TASKING Compiler */ #define __STATIC_INLINE static inline #elif defined ( __CSMC__ ) #define __packed #define __ASM _asm /*!< asm keyword for COSMIC Compiler */ #define __INLINE inline /*use -pc99 on compile line !< inline keyword for COSMIC Compiler */ #define __STATIC_INLINE static inline #endif /** __FPU_USED indicates whether an FPU is used or not. This core does not support an FPU at all */ #define __FPU_USED 0 #if defined ( __CC_ARM ) #if defined __TARGET_FPU_VFP #warning "Compiler generates FPU instructions for a device without an FPU (check __FPU_PRESENT)" #endif #elif defined ( __GNUC__ ) #if defined (__VFP_FP__) && !defined(__SOFTFP__) #warning "Compiler generates FPU instructions for a device without an FPU (check __FPU_PRESENT)" #endif #elif defined ( __ICCARM__ ) #if defined __ARMVFP__ #warning "Compiler generates FPU instructions for a device without an FPU (check __FPU_PRESENT)" #endif #elif defined ( __TMS470__ ) #if defined __TI__VFP_SUPPORT____ #warning "Compiler generates FPU instructions for a device without an FPU (check __FPU_PRESENT)" #endif #elif defined ( __TASKING__ ) #if defined __FPU_VFP__ #error "Compiler generates FPU instructions for a device without an FPU (check __FPU_PRESENT)" #endif #elif defined ( __CSMC__ ) /* Cosmic */ #if ( __CSMC__ & 0x400) // FPU present for parser #error "Compiler generates FPU instructions for a device without an FPU (check __FPU_PRESENT)" #endif #endif #include /* standard types definitions */ #include /* Core Instruction Access */ #include /* Core Function Access */ #ifdef __cplusplus } #endif #endif /* __CORE_SC000_H_GENERIC */ #ifndef __CMSIS_GENERIC #ifndef __CORE_SC000_H_DEPENDANT #define __CORE_SC000_H_DEPENDANT #ifdef __cplusplus extern "C" { #endif /* check device defines and use defaults */ #if defined __CHECK_DEVICE_DEFINES #ifndef __SC000_REV #define __SC000_REV 0x0000 #warning "__SC000_REV not defined in device header file; using default!" #endif #ifndef __MPU_PRESENT #define __MPU_PRESENT 0 #warning "__MPU_PRESENT not defined in device header file; using default!" #endif #ifndef __NVIC_PRIO_BITS #define __NVIC_PRIO_BITS 2 #warning "__NVIC_PRIO_BITS not defined in device header file; using default!" #endif #ifndef __Vendor_SysTickConfig #define __Vendor_SysTickConfig 0 #warning "__Vendor_SysTickConfig not defined in device header file; using default!" #endif #endif /* IO definitions (access restrictions to peripheral registers) */ /** \defgroup CMSIS_glob_defs CMSIS Global Defines IO Type Qualifiers are used \li to specify the access to peripheral variables. \li for automatic generation of peripheral register debug information. */ #ifdef __cplusplus #define __I volatile /*!< Defines 'read only' permissions */ #else #define __I volatile const /*!< Defines 'read only' permissions */ #endif #define __O volatile /*!< Defines 'write only' permissions */ #define __IO volatile /*!< Defines 'read / write' permissions */ /*@} end of group SC000 */ /******************************************************************************* * Register Abstraction Core Register contain: - Core Register - Core NVIC Register - Core SCB Register - Core SysTick Register - Core MPU Register ******************************************************************************/ /** \defgroup CMSIS_core_register Defines and Type Definitions \brief Type definitions and defines for Cortex-M processor based devices. */ /** \ingroup CMSIS_core_register \defgroup CMSIS_CORE Status and Control Registers \brief Core Register type definitions. @{ */ /** \brief Union type to access the Application Program Status Register (APSR). */ typedef union { struct { uint32_t _reserved0:28; /*!< bit: 0..27 Reserved */ uint32_t V:1; /*!< bit: 28 Overflow condition code flag */ uint32_t C:1; /*!< bit: 29 Carry condition code flag */ uint32_t Z:1; /*!< bit: 30 Zero condition code flag */ uint32_t N:1; /*!< bit: 31 Negative condition code flag */ } b; /*!< Structure used for bit access */ uint32_t w; /*!< Type used for word access */ } APSR_Type; /* APSR Register Definitions */ #define APSR_N_Pos 31 /*!< APSR: N Position */ #define APSR_N_Msk (1UL << APSR_N_Pos) /*!< APSR: N Mask */ #define APSR_Z_Pos 30 /*!< APSR: Z Position */ #define APSR_Z_Msk (1UL << APSR_Z_Pos) /*!< APSR: Z Mask */ #define APSR_C_Pos 29 /*!< APSR: C Position */ #define APSR_C_Msk (1UL << APSR_C_Pos) /*!< APSR: C Mask */ #define APSR_V_Pos 28 /*!< APSR: V Position */ #define APSR_V_Msk (1UL << APSR_V_Pos) /*!< APSR: V Mask */ /** \brief Union type to access the Interrupt Program Status Register (IPSR). */ typedef union { struct { uint32_t ISR:9; /*!< bit: 0.. 8 Exception number */ uint32_t _reserved0:23; /*!< bit: 9..31 Reserved */ } b; /*!< Structure used for bit access */ uint32_t w; /*!< Type used for word access */ } IPSR_Type; /* IPSR Register Definitions */ #define IPSR_ISR_Pos 0 /*!< IPSR: ISR Position */ #define IPSR_ISR_Msk (0x1FFUL /*<< IPSR_ISR_Pos*/) /*!< IPSR: ISR Mask */ /** \brief Union type to access the Special-Purpose Program Status Registers (xPSR). */ typedef union { struct { uint32_t ISR:9; /*!< bit: 0.. 8 Exception number */ uint32_t _reserved0:15; /*!< bit: 9..23 Reserved */ uint32_t T:1; /*!< bit: 24 Thumb bit (read 0) */ uint32_t _reserved1:3; /*!< bit: 25..27 Reserved */ uint32_t V:1; /*!< bit: 28 Overflow condition code flag */ uint32_t C:1; /*!< bit: 29 Carry condition code flag */ uint32_t Z:1; /*!< bit: 30 Zero condition code flag */ uint32_t N:1; /*!< bit: 31 Negative condition code flag */ } b; /*!< Structure used for bit access */ uint32_t w; /*!< Type used for word access */ } xPSR_Type; /* xPSR Register Definitions */ #define xPSR_N_Pos 31 /*!< xPSR: N Position */ #define xPSR_N_Msk (1UL << xPSR_N_Pos) /*!< xPSR: N Mask */ #define xPSR_Z_Pos 30 /*!< xPSR: Z Position */ #define xPSR_Z_Msk (1UL << xPSR_Z_Pos) /*!< xPSR: Z Mask */ #define xPSR_C_Pos 29 /*!< xPSR: C Position */ #define xPSR_C_Msk (1UL << xPSR_C_Pos) /*!< xPSR: C Mask */ #define xPSR_V_Pos 28 /*!< xPSR: V Position */ #define xPSR_V_Msk (1UL << xPSR_V_Pos) /*!< xPSR: V Mask */ #define xPSR_T_Pos 24 /*!< xPSR: T Position */ #define xPSR_T_Msk (1UL << xPSR_T_Pos) /*!< xPSR: T Mask */ #define xPSR_ISR_Pos 0 /*!< xPSR: ISR Position */ #define xPSR_ISR_Msk (0x1FFUL /*<< xPSR_ISR_Pos*/) /*!< xPSR: ISR Mask */ /** \brief Union type to access the Control Registers (CONTROL). */ typedef union { struct { uint32_t _reserved0:1; /*!< bit: 0 Reserved */ uint32_t SPSEL:1; /*!< bit: 1 Stack to be used */ uint32_t _reserved1:30; /*!< bit: 2..31 Reserved */ } b; /*!< Structure used for bit access */ uint32_t w; /*!< Type used for word access */ } CONTROL_Type; /* CONTROL Register Definitions */ #define CONTROL_SPSEL_Pos 1 /*!< CONTROL: SPSEL Position */ #define CONTROL_SPSEL_Msk (1UL << CONTROL_SPSEL_Pos) /*!< CONTROL: SPSEL Mask */ /*@} end of group CMSIS_CORE */ /** \ingroup CMSIS_core_register \defgroup CMSIS_NVIC Nested Vectored Interrupt Controller (NVIC) \brief Type definitions for the NVIC Registers @{ */ /** \brief Structure type to access the Nested Vectored Interrupt Controller (NVIC). */ typedef struct { __IO uint32_t ISER[1]; /*!< Offset: 0x000 (R/W) Interrupt Set Enable Register */ uint32_t RESERVED0[31]; __IO uint32_t ICER[1]; /*!< Offset: 0x080 (R/W) Interrupt Clear Enable Register */ uint32_t RSERVED1[31]; __IO uint32_t ISPR[1]; /*!< Offset: 0x100 (R/W) Interrupt Set Pending Register */ uint32_t RESERVED2[31]; __IO uint32_t ICPR[1]; /*!< Offset: 0x180 (R/W) Interrupt Clear Pending Register */ uint32_t RESERVED3[31]; uint32_t RESERVED4[64]; __IO uint32_t IP[8]; /*!< Offset: 0x300 (R/W) Interrupt Priority Register */ } NVIC_Type; /*@} end of group CMSIS_NVIC */ /** \ingroup CMSIS_core_register \defgroup CMSIS_SCB System Control Block (SCB) \brief Type definitions for the System Control Block Registers @{ */ /** \brief Structure type to access the System Control Block (SCB). */ typedef struct { __I uint32_t CPUID; /*!< Offset: 0x000 (R/ ) CPUID Base Register */ __IO uint32_t ICSR; /*!< Offset: 0x004 (R/W) Interrupt Control and State Register */ __IO uint32_t VTOR; /*!< Offset: 0x008 (R/W) Vector Table Offset Register */ __IO uint32_t AIRCR; /*!< Offset: 0x00C (R/W) Application Interrupt and Reset Control Register */ __IO uint32_t SCR; /*!< Offset: 0x010 (R/W) System Control Register */ __IO uint32_t CCR; /*!< Offset: 0x014 (R/W) Configuration Control Register */ uint32_t RESERVED0[1]; __IO uint32_t SHP[2]; /*!< Offset: 0x01C (R/W) System Handlers Priority Registers. [0] is RESERVED */ __IO uint32_t SHCSR; /*!< Offset: 0x024 (R/W) System Handler Control and State Register */ uint32_t RESERVED1[154]; __IO uint32_t SFCR; /*!< Offset: 0x290 (R/W) Security Features Control Register */ } SCB_Type; /* SCB CPUID Register Definitions */ #define SCB_CPUID_IMPLEMENTER_Pos 24 /*!< SCB CPUID: IMPLEMENTER Position */ #define SCB_CPUID_IMPLEMENTER_Msk (0xFFUL << SCB_CPUID_IMPLEMENTER_Pos) /*!< SCB CPUID: IMPLEMENTER Mask */ #define SCB_CPUID_VARIANT_Pos 20 /*!< SCB CPUID: VARIANT Position */ #define SCB_CPUID_VARIANT_Msk (0xFUL << SCB_CPUID_VARIANT_Pos) /*!< SCB CPUID: VARIANT Mask */ #define SCB_CPUID_ARCHITECTURE_Pos 16 /*!< SCB CPUID: ARCHITECTURE Position */ #define SCB_CPUID_ARCHITECTURE_Msk (0xFUL << SCB_CPUID_ARCHITECTURE_Pos) /*!< SCB CPUID: ARCHITECTURE Mask */ #define SCB_CPUID_PARTNO_Pos 4 /*!< SCB CPUID: PARTNO Position */ #define SCB_CPUID_PARTNO_Msk (0xFFFUL << SCB_CPUID_PARTNO_Pos) /*!< SCB CPUID: PARTNO Mask */ #define SCB_CPUID_REVISION_Pos 0 /*!< SCB CPUID: REVISION Position */ #define SCB_CPUID_REVISION_Msk (0xFUL /*<< SCB_CPUID_REVISION_Pos*/) /*!< SCB CPUID: REVISION Mask */ /* SCB Interrupt Control State Register Definitions */ #define SCB_ICSR_NMIPENDSET_Pos 31 /*!< SCB ICSR: NMIPENDSET Position */ #define SCB_ICSR_NMIPENDSET_Msk (1UL << SCB_ICSR_NMIPENDSET_Pos) /*!< SCB ICSR: NMIPENDSET Mask */ #define SCB_ICSR_PENDSVSET_Pos 28 /*!< SCB ICSR: PENDSVSET Position */ #define SCB_ICSR_PENDSVSET_Msk (1UL << SCB_ICSR_PENDSVSET_Pos) /*!< SCB ICSR: PENDSVSET Mask */ #define SCB_ICSR_PENDSVCLR_Pos 27 /*!< SCB ICSR: PENDSVCLR Position */ #define SCB_ICSR_PENDSVCLR_Msk (1UL << SCB_ICSR_PENDSVCLR_Pos) /*!< SCB ICSR: PENDSVCLR Mask */ #define SCB_ICSR_PENDSTSET_Pos 26 /*!< SCB ICSR: PENDSTSET Position */ #define SCB_ICSR_PENDSTSET_Msk (1UL << SCB_ICSR_PENDSTSET_Pos) /*!< SCB ICSR: PENDSTSET Mask */ #define SCB_ICSR_PENDSTCLR_Pos 25 /*!< SCB ICSR: PENDSTCLR Position */ #define SCB_ICSR_PENDSTCLR_Msk (1UL << SCB_ICSR_PENDSTCLR_Pos) /*!< SCB ICSR: PENDSTCLR Mask */ #define SCB_ICSR_ISRPREEMPT_Pos 23 /*!< SCB ICSR: ISRPREEMPT Position */ #define SCB_ICSR_ISRPREEMPT_Msk (1UL << SCB_ICSR_ISRPREEMPT_Pos) /*!< SCB ICSR: ISRPREEMPT Mask */ #define SCB_ICSR_ISRPENDING_Pos 22 /*!< SCB ICSR: ISRPENDING Position */ #define SCB_ICSR_ISRPENDING_Msk (1UL << SCB_ICSR_ISRPENDING_Pos) /*!< SCB ICSR: ISRPENDING Mask */ #define SCB_ICSR_VECTPENDING_Pos 12 /*!< SCB ICSR: VECTPENDING Position */ #define SCB_ICSR_VECTPENDING_Msk (0x1FFUL << SCB_ICSR_VECTPENDING_Pos) /*!< SCB ICSR: VECTPENDING Mask */ #define SCB_ICSR_VECTACTIVE_Pos 0 /*!< SCB ICSR: VECTACTIVE Position */ #define SCB_ICSR_VECTACTIVE_Msk (0x1FFUL /*<< SCB_ICSR_VECTACTIVE_Pos*/) /*!< SCB ICSR: VECTACTIVE Mask */ /* SCB Interrupt Control State Register Definitions */ #define SCB_VTOR_TBLOFF_Pos 7 /*!< SCB VTOR: TBLOFF Position */ #define SCB_VTOR_TBLOFF_Msk (0x1FFFFFFUL << SCB_VTOR_TBLOFF_Pos) /*!< SCB VTOR: TBLOFF Mask */ /* SCB Application Interrupt and Reset Control Register Definitions */ #define SCB_AIRCR_VECTKEY_Pos 16 /*!< SCB AIRCR: VECTKEY Position */ #define SCB_AIRCR_VECTKEY_Msk (0xFFFFUL << SCB_AIRCR_VECTKEY_Pos) /*!< SCB AIRCR: VECTKEY Mask */ #define SCB_AIRCR_VECTKEYSTAT_Pos 16 /*!< SCB AIRCR: VECTKEYSTAT Position */ #define SCB_AIRCR_VECTKEYSTAT_Msk (0xFFFFUL << SCB_AIRCR_VECTKEYSTAT_Pos) /*!< SCB AIRCR: VECTKEYSTAT Mask */ #define SCB_AIRCR_ENDIANESS_Pos 15 /*!< SCB AIRCR: ENDIANESS Position */ #define SCB_AIRCR_ENDIANESS_Msk (1UL << SCB_AIRCR_ENDIANESS_Pos) /*!< SCB AIRCR: ENDIANESS Mask */ #define SCB_AIRCR_SYSRESETREQ_Pos 2 /*!< SCB AIRCR: SYSRESETREQ Position */ #define SCB_AIRCR_SYSRESETREQ_Msk (1UL << SCB_AIRCR_SYSRESETREQ_Pos) /*!< SCB AIRCR: SYSRESETREQ Mask */ #define SCB_AIRCR_VECTCLRACTIVE_Pos 1 /*!< SCB AIRCR: VECTCLRACTIVE Position */ #define SCB_AIRCR_VECTCLRACTIVE_Msk (1UL << SCB_AIRCR_VECTCLRACTIVE_Pos) /*!< SCB AIRCR: VECTCLRACTIVE Mask */ /* SCB System Control Register Definitions */ #define SCB_SCR_SEVONPEND_Pos 4 /*!< SCB SCR: SEVONPEND Position */ #define SCB_SCR_SEVONPEND_Msk (1UL << SCB_SCR_SEVONPEND_Pos) /*!< SCB SCR: SEVONPEND Mask */ #define SCB_SCR_SLEEPDEEP_Pos 2 /*!< SCB SCR: SLEEPDEEP Position */ #define SCB_SCR_SLEEPDEEP_Msk (1UL << SCB_SCR_SLEEPDEEP_Pos) /*!< SCB SCR: SLEEPDEEP Mask */ #define SCB_SCR_SLEEPONEXIT_Pos 1 /*!< SCB SCR: SLEEPONEXIT Position */ #define SCB_SCR_SLEEPONEXIT_Msk (1UL << SCB_SCR_SLEEPONEXIT_Pos) /*!< SCB SCR: SLEEPONEXIT Mask */ /* SCB Configuration Control Register Definitions */ #define SCB_CCR_STKALIGN_Pos 9 /*!< SCB CCR: STKALIGN Position */ #define SCB_CCR_STKALIGN_Msk (1UL << SCB_CCR_STKALIGN_Pos) /*!< SCB CCR: STKALIGN Mask */ #define SCB_CCR_UNALIGN_TRP_Pos 3 /*!< SCB CCR: UNALIGN_TRP Position */ #define SCB_CCR_UNALIGN_TRP_Msk (1UL << SCB_CCR_UNALIGN_TRP_Pos) /*!< SCB CCR: UNALIGN_TRP Mask */ /* SCB System Handler Control and State Register Definitions */ #define SCB_SHCSR_SVCALLPENDED_Pos 15 /*!< SCB SHCSR: SVCALLPENDED Position */ #define SCB_SHCSR_SVCALLPENDED_Msk (1UL << SCB_SHCSR_SVCALLPENDED_Pos) /*!< SCB SHCSR: SVCALLPENDED Mask */ /*@} end of group CMSIS_SCB */ /** \ingroup CMSIS_core_register \defgroup CMSIS_SCnSCB System Controls not in SCB (SCnSCB) \brief Type definitions for the System Control and ID Register not in the SCB @{ */ /** \brief Structure type to access the System Control and ID Register not in the SCB. */ typedef struct { uint32_t RESERVED0[2]; __IO uint32_t ACTLR; /*!< Offset: 0x008 (R/W) Auxiliary Control Register */ } SCnSCB_Type; /* Auxiliary Control Register Definitions */ #define SCnSCB_ACTLR_DISMCYCINT_Pos 0 /*!< ACTLR: DISMCYCINT Position */ #define SCnSCB_ACTLR_DISMCYCINT_Msk (1UL /*<< SCnSCB_ACTLR_DISMCYCINT_Pos*/) /*!< ACTLR: DISMCYCINT Mask */ /*@} end of group CMSIS_SCnotSCB */ /** \ingroup CMSIS_core_register \defgroup CMSIS_SysTick System Tick Timer (SysTick) \brief Type definitions for the System Timer Registers. @{ */ /** \brief Structure type to access the System Timer (SysTick). */ typedef struct { __IO uint32_t CTRL; /*!< Offset: 0x000 (R/W) SysTick Control and Status Register */ __IO uint32_t LOAD; /*!< Offset: 0x004 (R/W) SysTick Reload Value Register */ __IO uint32_t VAL; /*!< Offset: 0x008 (R/W) SysTick Current Value Register */ __I uint32_t CALIB; /*!< Offset: 0x00C (R/ ) SysTick Calibration Register */ } SysTick_Type; /* SysTick Control / Status Register Definitions */ #define SysTick_CTRL_COUNTFLAG_Pos 16 /*!< SysTick CTRL: COUNTFLAG Position */ #define SysTick_CTRL_COUNTFLAG_Msk (1UL << SysTick_CTRL_COUNTFLAG_Pos) /*!< SysTick CTRL: COUNTFLAG Mask */ #define SysTick_CTRL_CLKSOURCE_Pos 2 /*!< SysTick CTRL: CLKSOURCE Position */ #define SysTick_CTRL_CLKSOURCE_Msk (1UL << SysTick_CTRL_CLKSOURCE_Pos) /*!< SysTick CTRL: CLKSOURCE Mask */ #define SysTick_CTRL_TICKINT_Pos 1 /*!< SysTick CTRL: TICKINT Position */ #define SysTick_CTRL_TICKINT_Msk (1UL << SysTick_CTRL_TICKINT_Pos) /*!< SysTick CTRL: TICKINT Mask */ #define SysTick_CTRL_ENABLE_Pos 0 /*!< SysTick CTRL: ENABLE Position */ #define SysTick_CTRL_ENABLE_Msk (1UL /*<< SysTick_CTRL_ENABLE_Pos*/) /*!< SysTick CTRL: ENABLE Mask */ /* SysTick Reload Register Definitions */ #define SysTick_LOAD_RELOAD_Pos 0 /*!< SysTick LOAD: RELOAD Position */ #define SysTick_LOAD_RELOAD_Msk (0xFFFFFFUL /*<< SysTick_LOAD_RELOAD_Pos*/) /*!< SysTick LOAD: RELOAD Mask */ /* SysTick Current Register Definitions */ #define SysTick_VAL_CURRENT_Pos 0 /*!< SysTick VAL: CURRENT Position */ #define SysTick_VAL_CURRENT_Msk (0xFFFFFFUL /*<< SysTick_VAL_CURRENT_Pos*/) /*!< SysTick VAL: CURRENT Mask */ /* SysTick Calibration Register Definitions */ #define SysTick_CALIB_NOREF_Pos 31 /*!< SysTick CALIB: NOREF Position */ #define SysTick_CALIB_NOREF_Msk (1UL << SysTick_CALIB_NOREF_Pos) /*!< SysTick CALIB: NOREF Mask */ #define SysTick_CALIB_SKEW_Pos 30 /*!< SysTick CALIB: SKEW Position */ #define SysTick_CALIB_SKEW_Msk (1UL << SysTick_CALIB_SKEW_Pos) /*!< SysTick CALIB: SKEW Mask */ #define SysTick_CALIB_TENMS_Pos 0 /*!< SysTick CALIB: TENMS Position */ #define SysTick_CALIB_TENMS_Msk (0xFFFFFFUL /*<< SysTick_CALIB_TENMS_Pos*/) /*!< SysTick CALIB: TENMS Mask */ /*@} end of group CMSIS_SysTick */ #if (__MPU_PRESENT == 1) /** \ingroup CMSIS_core_register \defgroup CMSIS_MPU Memory Protection Unit (MPU) \brief Type definitions for the Memory Protection Unit (MPU) @{ */ /** \brief Structure type to access the Memory Protection Unit (MPU). */ typedef struct { __I uint32_t TYPE; /*!< Offset: 0x000 (R/ ) MPU Type Register */ __IO uint32_t CTRL; /*!< Offset: 0x004 (R/W) MPU Control Register */ __IO uint32_t RNR; /*!< Offset: 0x008 (R/W) MPU Region RNRber Register */ __IO uint32_t RBAR; /*!< Offset: 0x00C (R/W) MPU Region Base Address Register */ __IO uint32_t RASR; /*!< Offset: 0x010 (R/W) MPU Region Attribute and Size Register */ } MPU_Type; /* MPU Type Register */ #define MPU_TYPE_IREGION_Pos 16 /*!< MPU TYPE: IREGION Position */ #define MPU_TYPE_IREGION_Msk (0xFFUL << MPU_TYPE_IREGION_Pos) /*!< MPU TYPE: IREGION Mask */ #define MPU_TYPE_DREGION_Pos 8 /*!< MPU TYPE: DREGION Position */ #define MPU_TYPE_DREGION_Msk (0xFFUL << MPU_TYPE_DREGION_Pos) /*!< MPU TYPE: DREGION Mask */ #define MPU_TYPE_SEPARATE_Pos 0 /*!< MPU TYPE: SEPARATE Position */ #define MPU_TYPE_SEPARATE_Msk (1UL /*<< MPU_TYPE_SEPARATE_Pos*/) /*!< MPU TYPE: SEPARATE Mask */ /* MPU Control Register */ #define MPU_CTRL_PRIVDEFENA_Pos 2 /*!< MPU CTRL: PRIVDEFENA Position */ #define MPU_CTRL_PRIVDEFENA_Msk (1UL << MPU_CTRL_PRIVDEFENA_Pos) /*!< MPU CTRL: PRIVDEFENA Mask */ #define MPU_CTRL_HFNMIENA_Pos 1 /*!< MPU CTRL: HFNMIENA Position */ #define MPU_CTRL_HFNMIENA_Msk (1UL << MPU_CTRL_HFNMIENA_Pos) /*!< MPU CTRL: HFNMIENA Mask */ #define MPU_CTRL_ENABLE_Pos 0 /*!< MPU CTRL: ENABLE Position */ #define MPU_CTRL_ENABLE_Msk (1UL /*<< MPU_CTRL_ENABLE_Pos*/) /*!< MPU CTRL: ENABLE Mask */ /* MPU Region Number Register */ #define MPU_RNR_REGION_Pos 0 /*!< MPU RNR: REGION Position */ #define MPU_RNR_REGION_Msk (0xFFUL /*<< MPU_RNR_REGION_Pos*/) /*!< MPU RNR: REGION Mask */ /* MPU Region Base Address Register */ #define MPU_RBAR_ADDR_Pos 8 /*!< MPU RBAR: ADDR Position */ #define MPU_RBAR_ADDR_Msk (0xFFFFFFUL << MPU_RBAR_ADDR_Pos) /*!< MPU RBAR: ADDR Mask */ #define MPU_RBAR_VALID_Pos 4 /*!< MPU RBAR: VALID Position */ #define MPU_RBAR_VALID_Msk (1UL << MPU_RBAR_VALID_Pos) /*!< MPU RBAR: VALID Mask */ #define MPU_RBAR_REGION_Pos 0 /*!< MPU RBAR: REGION Position */ #define MPU_RBAR_REGION_Msk (0xFUL /*<< MPU_RBAR_REGION_Pos*/) /*!< MPU RBAR: REGION Mask */ /* MPU Region Attribute and Size Register */ #define MPU_RASR_ATTRS_Pos 16 /*!< MPU RASR: MPU Region Attribute field Position */ #define MPU_RASR_ATTRS_Msk (0xFFFFUL << MPU_RASR_ATTRS_Pos) /*!< MPU RASR: MPU Region Attribute field Mask */ #define MPU_RASR_XN_Pos 28 /*!< MPU RASR: ATTRS.XN Position */ #define MPU_RASR_XN_Msk (1UL << MPU_RASR_XN_Pos) /*!< MPU RASR: ATTRS.XN Mask */ #define MPU_RASR_AP_Pos 24 /*!< MPU RASR: ATTRS.AP Position */ #define MPU_RASR_AP_Msk (0x7UL << MPU_RASR_AP_Pos) /*!< MPU RASR: ATTRS.AP Mask */ #define MPU_RASR_TEX_Pos 19 /*!< MPU RASR: ATTRS.TEX Position */ #define MPU_RASR_TEX_Msk (0x7UL << MPU_RASR_TEX_Pos) /*!< MPU RASR: ATTRS.TEX Mask */ #define MPU_RASR_S_Pos 18 /*!< MPU RASR: ATTRS.S Position */ #define MPU_RASR_S_Msk (1UL << MPU_RASR_S_Pos) /*!< MPU RASR: ATTRS.S Mask */ #define MPU_RASR_C_Pos 17 /*!< MPU RASR: ATTRS.C Position */ #define MPU_RASR_C_Msk (1UL << MPU_RASR_C_Pos) /*!< MPU RASR: ATTRS.C Mask */ #define MPU_RASR_B_Pos 16 /*!< MPU RASR: ATTRS.B Position */ #define MPU_RASR_B_Msk (1UL << MPU_RASR_B_Pos) /*!< MPU RASR: ATTRS.B Mask */ #define MPU_RASR_SRD_Pos 8 /*!< MPU RASR: Sub-Region Disable Position */ #define MPU_RASR_SRD_Msk (0xFFUL << MPU_RASR_SRD_Pos) /*!< MPU RASR: Sub-Region Disable Mask */ #define MPU_RASR_SIZE_Pos 1 /*!< MPU RASR: Region Size Field Position */ #define MPU_RASR_SIZE_Msk (0x1FUL << MPU_RASR_SIZE_Pos) /*!< MPU RASR: Region Size Field Mask */ #define MPU_RASR_ENABLE_Pos 0 /*!< MPU RASR: Region enable bit Position */ #define MPU_RASR_ENABLE_Msk (1UL /*<< MPU_RASR_ENABLE_Pos*/) /*!< MPU RASR: Region enable bit Disable Mask */ /*@} end of group CMSIS_MPU */ #endif /** \ingroup CMSIS_core_register \defgroup CMSIS_CoreDebug Core Debug Registers (CoreDebug) \brief SC000 Core Debug Registers (DCB registers, SHCSR, and DFSR) are only accessible over DAP and not via processor. Therefore they are not covered by the Cortex-M0 header file. @{ */ /*@} end of group CMSIS_CoreDebug */ /** \ingroup CMSIS_core_register \defgroup CMSIS_core_base Core Definitions \brief Definitions for base addresses, unions, and structures. @{ */ /* Memory mapping of SC000 Hardware */ #define SCS_BASE (0xE000E000UL) /*!< System Control Space Base Address */ #define SysTick_BASE (SCS_BASE + 0x0010UL) /*!< SysTick Base Address */ #define NVIC_BASE (SCS_BASE + 0x0100UL) /*!< NVIC Base Address */ #define SCB_BASE (SCS_BASE + 0x0D00UL) /*!< System Control Block Base Address */ #define SCnSCB ((SCnSCB_Type *) SCS_BASE ) /*!< System control Register not in SCB */ #define SCB ((SCB_Type *) SCB_BASE ) /*!< SCB configuration struct */ #define SysTick ((SysTick_Type *) SysTick_BASE ) /*!< SysTick configuration struct */ #define NVIC ((NVIC_Type *) NVIC_BASE ) /*!< NVIC configuration struct */ #if (__MPU_PRESENT == 1) #define MPU_BASE (SCS_BASE + 0x0D90UL) /*!< Memory Protection Unit */ #define MPU ((MPU_Type *) MPU_BASE ) /*!< Memory Protection Unit */ #endif /*@} */ /******************************************************************************* * Hardware Abstraction Layer Core Function Interface contains: - Core NVIC Functions - Core SysTick Functions - Core Register Access Functions ******************************************************************************/ /** \defgroup CMSIS_Core_FunctionInterface Functions and Instructions Reference */ /* ########################## NVIC functions #################################### */ /** \ingroup CMSIS_Core_FunctionInterface \defgroup CMSIS_Core_NVICFunctions NVIC Functions \brief Functions that manage interrupts and exceptions via the NVIC. @{ */ /* Interrupt Priorities are WORD accessible only under ARMv6M */ /* The following MACROS handle generation of the register offset and byte masks */ #define _BIT_SHIFT(IRQn) ( ((((uint32_t)(int32_t)(IRQn)) ) & 0x03UL) * 8UL) #define _SHP_IDX(IRQn) ( (((((uint32_t)(int32_t)(IRQn)) & 0x0FUL)-8UL) >> 2UL) ) #define _IP_IDX(IRQn) ( (((uint32_t)(int32_t)(IRQn)) >> 2UL) ) /** \brief Enable External Interrupt The function enables a device-specific interrupt in the NVIC interrupt controller. \param [in] IRQn External interrupt number. Value cannot be negative. */ __STATIC_INLINE void NVIC_EnableIRQ(IRQn_Type IRQn) { NVIC->ISER[0] = (uint32_t)(1UL << (((uint32_t)(int32_t)IRQn) & 0x1FUL)); } /** \brief Disable External Interrupt The function disables a device-specific interrupt in the NVIC interrupt controller. \param [in] IRQn External interrupt number. Value cannot be negative. */ __STATIC_INLINE void NVIC_DisableIRQ(IRQn_Type IRQn) { NVIC->ICER[0] = (uint32_t)(1UL << (((uint32_t)(int32_t)IRQn) & 0x1FUL)); } /** \brief Get Pending Interrupt The function reads the pending register in the NVIC and returns the pending bit for the specified interrupt. \param [in] IRQn Interrupt number. \return 0 Interrupt status is not pending. \return 1 Interrupt status is pending. */ __STATIC_INLINE uint32_t NVIC_GetPendingIRQ(IRQn_Type IRQn) { return((uint32_t)(((NVIC->ISPR[0] & (1UL << (((uint32_t)(int32_t)IRQn) & 0x1FUL))) != 0UL) ? 1UL : 0UL)); } /** \brief Set Pending Interrupt The function sets the pending bit of an external interrupt. \param [in] IRQn Interrupt number. Value cannot be negative. */ __STATIC_INLINE void NVIC_SetPendingIRQ(IRQn_Type IRQn) { NVIC->ISPR[0] = (uint32_t)(1UL << (((uint32_t)(int32_t)IRQn) & 0x1FUL)); } /** \brief Clear Pending Interrupt The function clears the pending bit of an external interrupt. \param [in] IRQn External interrupt number. Value cannot be negative. */ __STATIC_INLINE void NVIC_ClearPendingIRQ(IRQn_Type IRQn) { NVIC->ICPR[0] = (uint32_t)(1UL << (((uint32_t)(int32_t)IRQn) & 0x1FUL)); } /** \brief Set Interrupt Priority The function sets the priority of an interrupt. \note The priority cannot be set for every core interrupt. \param [in] IRQn Interrupt number. \param [in] priority Priority to set. */ __STATIC_INLINE void NVIC_SetPriority(IRQn_Type IRQn, uint32_t priority) { if((int32_t)(IRQn) < 0) { SCB->SHP[_SHP_IDX(IRQn)] = ((uint32_t)(SCB->SHP[_SHP_IDX(IRQn)] & ~(0xFFUL << _BIT_SHIFT(IRQn))) | (((priority << (8 - __NVIC_PRIO_BITS)) & (uint32_t)0xFFUL) << _BIT_SHIFT(IRQn))); } else { NVIC->IP[_IP_IDX(IRQn)] = ((uint32_t)(NVIC->IP[_IP_IDX(IRQn)] & ~(0xFFUL << _BIT_SHIFT(IRQn))) | (((priority << (8 - __NVIC_PRIO_BITS)) & (uint32_t)0xFFUL) << _BIT_SHIFT(IRQn))); } } /** \brief Get Interrupt Priority The function reads the priority of an interrupt. The interrupt number can be positive to specify an external (device specific) interrupt, or negative to specify an internal (core) interrupt. \param [in] IRQn Interrupt number. \return Interrupt Priority. Value is aligned automatically to the implemented priority bits of the microcontroller. */ __STATIC_INLINE uint32_t NVIC_GetPriority(IRQn_Type IRQn) { if((int32_t)(IRQn) < 0) { return((uint32_t)(((SCB->SHP[_SHP_IDX(IRQn)] >> _BIT_SHIFT(IRQn) ) & (uint32_t)0xFFUL) >> (8 - __NVIC_PRIO_BITS))); } else { return((uint32_t)(((NVIC->IP[ _IP_IDX(IRQn)] >> _BIT_SHIFT(IRQn) ) & (uint32_t)0xFFUL) >> (8 - __NVIC_PRIO_BITS))); } } /** \brief System Reset The function initiates a system reset request to reset the MCU. */ __STATIC_INLINE void NVIC_SystemReset(void) { __DSB(); /* Ensure all outstanding memory accesses included buffered write are completed before reset */ SCB->AIRCR = ((0x5FAUL << SCB_AIRCR_VECTKEY_Pos) | SCB_AIRCR_SYSRESETREQ_Msk); __DSB(); /* Ensure completion of memory access */ while(1) { __NOP(); } /* wait until reset */ } /*@} end of CMSIS_Core_NVICFunctions */ /* ################################## SysTick function ############################################ */ /** \ingroup CMSIS_Core_FunctionInterface \defgroup CMSIS_Core_SysTickFunctions SysTick Functions \brief Functions that configure the System. @{ */ #if (__Vendor_SysTickConfig == 0) /** \brief System Tick Configuration The function initializes the System Timer and its interrupt, and starts the System Tick Timer. Counter is in free running mode to generate periodic interrupts. \param [in] ticks Number of ticks between two interrupts. \return 0 Function succeeded. \return 1 Function failed. \note When the variable __Vendor_SysTickConfig is set to 1, then the function SysTick_Config is not included. In this case, the file device.h must contain a vendor-specific implementation of this function. */ __STATIC_INLINE uint32_t SysTick_Config(uint32_t ticks) { if ((ticks - 1UL) > SysTick_LOAD_RELOAD_Msk) {return (1UL);} /* Reload value impossible */ SysTick->LOAD = (uint32_t)(ticks - 1UL); /* set reload register */ NVIC_SetPriority (SysTick_IRQn, (1UL << __NVIC_PRIO_BITS) - 1UL); /* set Priority for Systick Interrupt */ SysTick->VAL = 0UL; /* Load the SysTick Counter Value */ SysTick->CTRL = SysTick_CTRL_CLKSOURCE_Msk | SysTick_CTRL_TICKINT_Msk | SysTick_CTRL_ENABLE_Msk; /* Enable SysTick IRQ and SysTick Timer */ return (0UL); /* Function successful */ } #endif /*@} end of CMSIS_Core_SysTickFunctions */ #ifdef __cplusplus } #endif #endif /* __CORE_SC000_H_DEPENDANT */ #endif /* __CMSIS_GENERIC */ ================================================ FILE: Zelig/mbed/TARGET_NUCLEO_F411RE/core_sc300.h ================================================ /**************************************************************************//** * @file core_sc300.h * @brief CMSIS SC300 Core Peripheral Access Layer Header File * @version V4.10 * @date 18. March 2015 * * @note * ******************************************************************************/ /* Copyright (c) 2009 - 2015 ARM LIMITED All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: - Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. - Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. - Neither the name of ARM 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 COPYRIGHT HOLDERS AND 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. ---------------------------------------------------------------------------*/ #if defined ( __ICCARM__ ) #pragma system_include /* treat file as system include file for MISRA check */ #endif #ifndef __CORE_SC300_H_GENERIC #define __CORE_SC300_H_GENERIC #ifdef __cplusplus extern "C" { #endif /** \page CMSIS_MISRA_Exceptions MISRA-C:2004 Compliance Exceptions CMSIS violates the following MISRA-C:2004 rules: \li Required Rule 8.5, object/function definition in header file.
Function definitions in header files are used to allow 'inlining'. \li Required Rule 18.4, declaration of union type or object of union type: '{...}'.
Unions are used for effective representation of core registers. \li Advisory Rule 19.7, Function-like macro defined.
Function-like macros are used to allow more efficient code. */ /******************************************************************************* * CMSIS definitions ******************************************************************************/ /** \ingroup SC3000 @{ */ /* CMSIS SC300 definitions */ #define __SC300_CMSIS_VERSION_MAIN (0x04) /*!< [31:16] CMSIS HAL main version */ #define __SC300_CMSIS_VERSION_SUB (0x00) /*!< [15:0] CMSIS HAL sub version */ #define __SC300_CMSIS_VERSION ((__SC300_CMSIS_VERSION_MAIN << 16) | \ __SC300_CMSIS_VERSION_SUB ) /*!< CMSIS HAL version number */ #define __CORTEX_SC (300) /*!< Cortex secure core */ #if defined ( __CC_ARM ) #define __ASM __asm /*!< asm keyword for ARM Compiler */ #define __INLINE __inline /*!< inline keyword for ARM Compiler */ #define __STATIC_INLINE static __inline #elif defined ( __GNUC__ ) #define __ASM __asm /*!< asm keyword for GNU Compiler */ #define __INLINE inline /*!< inline keyword for GNU Compiler */ #define __STATIC_INLINE static inline #elif defined ( __ICCARM__ ) #define __ASM __asm /*!< asm keyword for IAR Compiler */ #define __INLINE inline /*!< inline keyword for IAR Compiler. Only available in High optimization mode! */ #define __STATIC_INLINE static inline #elif defined ( __TMS470__ ) #define __ASM __asm /*!< asm keyword for TI CCS Compiler */ #define __STATIC_INLINE static inline #elif defined ( __TASKING__ ) #define __ASM __asm /*!< asm keyword for TASKING Compiler */ #define __INLINE inline /*!< inline keyword for TASKING Compiler */ #define __STATIC_INLINE static inline #elif defined ( __CSMC__ ) #define __packed #define __ASM _asm /*!< asm keyword for COSMIC Compiler */ #define __INLINE inline /*use -pc99 on compile line !< inline keyword for COSMIC Compiler */ #define __STATIC_INLINE static inline #endif /** __FPU_USED indicates whether an FPU is used or not. This core does not support an FPU at all */ #define __FPU_USED 0 #if defined ( __CC_ARM ) #if defined __TARGET_FPU_VFP #warning "Compiler generates FPU instructions for a device without an FPU (check __FPU_PRESENT)" #endif #elif defined ( __GNUC__ ) #if defined (__VFP_FP__) && !defined(__SOFTFP__) #warning "Compiler generates FPU instructions for a device without an FPU (check __FPU_PRESENT)" #endif #elif defined ( __ICCARM__ ) #if defined __ARMVFP__ #warning "Compiler generates FPU instructions for a device without an FPU (check __FPU_PRESENT)" #endif #elif defined ( __TMS470__ ) #if defined __TI__VFP_SUPPORT____ #warning "Compiler generates FPU instructions for a device without an FPU (check __FPU_PRESENT)" #endif #elif defined ( __TASKING__ ) #if defined __FPU_VFP__ #error "Compiler generates FPU instructions for a device without an FPU (check __FPU_PRESENT)" #endif #elif defined ( __CSMC__ ) /* Cosmic */ #if ( __CSMC__ & 0x400) // FPU present for parser #error "Compiler generates FPU instructions for a device without an FPU (check __FPU_PRESENT)" #endif #endif #include /* standard types definitions */ #include /* Core Instruction Access */ #include /* Core Function Access */ #ifdef __cplusplus } #endif #endif /* __CORE_SC300_H_GENERIC */ #ifndef __CMSIS_GENERIC #ifndef __CORE_SC300_H_DEPENDANT #define __CORE_SC300_H_DEPENDANT #ifdef __cplusplus extern "C" { #endif /* check device defines and use defaults */ #if defined __CHECK_DEVICE_DEFINES #ifndef __SC300_REV #define __SC300_REV 0x0000 #warning "__SC300_REV not defined in device header file; using default!" #endif #ifndef __MPU_PRESENT #define __MPU_PRESENT 0 #warning "__MPU_PRESENT not defined in device header file; using default!" #endif #ifndef __NVIC_PRIO_BITS #define __NVIC_PRIO_BITS 4 #warning "__NVIC_PRIO_BITS not defined in device header file; using default!" #endif #ifndef __Vendor_SysTickConfig #define __Vendor_SysTickConfig 0 #warning "__Vendor_SysTickConfig not defined in device header file; using default!" #endif #endif /* IO definitions (access restrictions to peripheral registers) */ /** \defgroup CMSIS_glob_defs CMSIS Global Defines IO Type Qualifiers are used \li to specify the access to peripheral variables. \li for automatic generation of peripheral register debug information. */ #ifdef __cplusplus #define __I volatile /*!< Defines 'read only' permissions */ #else #define __I volatile const /*!< Defines 'read only' permissions */ #endif #define __O volatile /*!< Defines 'write only' permissions */ #define __IO volatile /*!< Defines 'read / write' permissions */ /*@} end of group SC300 */ /******************************************************************************* * Register Abstraction Core Register contain: - Core Register - Core NVIC Register - Core SCB Register - Core SysTick Register - Core Debug Register - Core MPU Register ******************************************************************************/ /** \defgroup CMSIS_core_register Defines and Type Definitions \brief Type definitions and defines for Cortex-M processor based devices. */ /** \ingroup CMSIS_core_register \defgroup CMSIS_CORE Status and Control Registers \brief Core Register type definitions. @{ */ /** \brief Union type to access the Application Program Status Register (APSR). */ typedef union { struct { uint32_t _reserved0:27; /*!< bit: 0..26 Reserved */ uint32_t Q:1; /*!< bit: 27 Saturation condition flag */ uint32_t V:1; /*!< bit: 28 Overflow condition code flag */ uint32_t C:1; /*!< bit: 29 Carry condition code flag */ uint32_t Z:1; /*!< bit: 30 Zero condition code flag */ uint32_t N:1; /*!< bit: 31 Negative condition code flag */ } b; /*!< Structure used for bit access */ uint32_t w; /*!< Type used for word access */ } APSR_Type; /* APSR Register Definitions */ #define APSR_N_Pos 31 /*!< APSR: N Position */ #define APSR_N_Msk (1UL << APSR_N_Pos) /*!< APSR: N Mask */ #define APSR_Z_Pos 30 /*!< APSR: Z Position */ #define APSR_Z_Msk (1UL << APSR_Z_Pos) /*!< APSR: Z Mask */ #define APSR_C_Pos 29 /*!< APSR: C Position */ #define APSR_C_Msk (1UL << APSR_C_Pos) /*!< APSR: C Mask */ #define APSR_V_Pos 28 /*!< APSR: V Position */ #define APSR_V_Msk (1UL << APSR_V_Pos) /*!< APSR: V Mask */ #define APSR_Q_Pos 27 /*!< APSR: Q Position */ #define APSR_Q_Msk (1UL << APSR_Q_Pos) /*!< APSR: Q Mask */ /** \brief Union type to access the Interrupt Program Status Register (IPSR). */ typedef union { struct { uint32_t ISR:9; /*!< bit: 0.. 8 Exception number */ uint32_t _reserved0:23; /*!< bit: 9..31 Reserved */ } b; /*!< Structure used for bit access */ uint32_t w; /*!< Type used for word access */ } IPSR_Type; /* IPSR Register Definitions */ #define IPSR_ISR_Pos 0 /*!< IPSR: ISR Position */ #define IPSR_ISR_Msk (0x1FFUL /*<< IPSR_ISR_Pos*/) /*!< IPSR: ISR Mask */ /** \brief Union type to access the Special-Purpose Program Status Registers (xPSR). */ typedef union { struct { uint32_t ISR:9; /*!< bit: 0.. 8 Exception number */ uint32_t _reserved0:15; /*!< bit: 9..23 Reserved */ uint32_t T:1; /*!< bit: 24 Thumb bit (read 0) */ uint32_t IT:2; /*!< bit: 25..26 saved IT state (read 0) */ uint32_t Q:1; /*!< bit: 27 Saturation condition flag */ uint32_t V:1; /*!< bit: 28 Overflow condition code flag */ uint32_t C:1; /*!< bit: 29 Carry condition code flag */ uint32_t Z:1; /*!< bit: 30 Zero condition code flag */ uint32_t N:1; /*!< bit: 31 Negative condition code flag */ } b; /*!< Structure used for bit access */ uint32_t w; /*!< Type used for word access */ } xPSR_Type; /* xPSR Register Definitions */ #define xPSR_N_Pos 31 /*!< xPSR: N Position */ #define xPSR_N_Msk (1UL << xPSR_N_Pos) /*!< xPSR: N Mask */ #define xPSR_Z_Pos 30 /*!< xPSR: Z Position */ #define xPSR_Z_Msk (1UL << xPSR_Z_Pos) /*!< xPSR: Z Mask */ #define xPSR_C_Pos 29 /*!< xPSR: C Position */ #define xPSR_C_Msk (1UL << xPSR_C_Pos) /*!< xPSR: C Mask */ #define xPSR_V_Pos 28 /*!< xPSR: V Position */ #define xPSR_V_Msk (1UL << xPSR_V_Pos) /*!< xPSR: V Mask */ #define xPSR_Q_Pos 27 /*!< xPSR: Q Position */ #define xPSR_Q_Msk (1UL << xPSR_Q_Pos) /*!< xPSR: Q Mask */ #define xPSR_IT_Pos 25 /*!< xPSR: IT Position */ #define xPSR_IT_Msk (3UL << xPSR_IT_Pos) /*!< xPSR: IT Mask */ #define xPSR_T_Pos 24 /*!< xPSR: T Position */ #define xPSR_T_Msk (1UL << xPSR_T_Pos) /*!< xPSR: T Mask */ #define xPSR_ISR_Pos 0 /*!< xPSR: ISR Position */ #define xPSR_ISR_Msk (0x1FFUL /*<< xPSR_ISR_Pos*/) /*!< xPSR: ISR Mask */ /** \brief Union type to access the Control Registers (CONTROL). */ typedef union { struct { uint32_t nPRIV:1; /*!< bit: 0 Execution privilege in Thread mode */ uint32_t SPSEL:1; /*!< bit: 1 Stack to be used */ uint32_t _reserved1:30; /*!< bit: 2..31 Reserved */ } b; /*!< Structure used for bit access */ uint32_t w; /*!< Type used for word access */ } CONTROL_Type; /* CONTROL Register Definitions */ #define CONTROL_SPSEL_Pos 1 /*!< CONTROL: SPSEL Position */ #define CONTROL_SPSEL_Msk (1UL << CONTROL_SPSEL_Pos) /*!< CONTROL: SPSEL Mask */ #define CONTROL_nPRIV_Pos 0 /*!< CONTROL: nPRIV Position */ #define CONTROL_nPRIV_Msk (1UL /*<< CONTROL_nPRIV_Pos*/) /*!< CONTROL: nPRIV Mask */ /*@} end of group CMSIS_CORE */ /** \ingroup CMSIS_core_register \defgroup CMSIS_NVIC Nested Vectored Interrupt Controller (NVIC) \brief Type definitions for the NVIC Registers @{ */ /** \brief Structure type to access the Nested Vectored Interrupt Controller (NVIC). */ typedef struct { __IO uint32_t ISER[8]; /*!< Offset: 0x000 (R/W) Interrupt Set Enable Register */ uint32_t RESERVED0[24]; __IO uint32_t ICER[8]; /*!< Offset: 0x080 (R/W) Interrupt Clear Enable Register */ uint32_t RSERVED1[24]; __IO uint32_t ISPR[8]; /*!< Offset: 0x100 (R/W) Interrupt Set Pending Register */ uint32_t RESERVED2[24]; __IO uint32_t ICPR[8]; /*!< Offset: 0x180 (R/W) Interrupt Clear Pending Register */ uint32_t RESERVED3[24]; __IO uint32_t IABR[8]; /*!< Offset: 0x200 (R/W) Interrupt Active bit Register */ uint32_t RESERVED4[56]; __IO uint8_t IP[240]; /*!< Offset: 0x300 (R/W) Interrupt Priority Register (8Bit wide) */ uint32_t RESERVED5[644]; __O uint32_t STIR; /*!< Offset: 0xE00 ( /W) Software Trigger Interrupt Register */ } NVIC_Type; /* Software Triggered Interrupt Register Definitions */ #define NVIC_STIR_INTID_Pos 0 /*!< STIR: INTLINESNUM Position */ #define NVIC_STIR_INTID_Msk (0x1FFUL /*<< NVIC_STIR_INTID_Pos*/) /*!< STIR: INTLINESNUM Mask */ /*@} end of group CMSIS_NVIC */ /** \ingroup CMSIS_core_register \defgroup CMSIS_SCB System Control Block (SCB) \brief Type definitions for the System Control Block Registers @{ */ /** \brief Structure type to access the System Control Block (SCB). */ typedef struct { __I uint32_t CPUID; /*!< Offset: 0x000 (R/ ) CPUID Base Register */ __IO uint32_t ICSR; /*!< Offset: 0x004 (R/W) Interrupt Control and State Register */ __IO uint32_t VTOR; /*!< Offset: 0x008 (R/W) Vector Table Offset Register */ __IO uint32_t AIRCR; /*!< Offset: 0x00C (R/W) Application Interrupt and Reset Control Register */ __IO uint32_t SCR; /*!< Offset: 0x010 (R/W) System Control Register */ __IO uint32_t CCR; /*!< Offset: 0x014 (R/W) Configuration Control Register */ __IO uint8_t SHP[12]; /*!< Offset: 0x018 (R/W) System Handlers Priority Registers (4-7, 8-11, 12-15) */ __IO uint32_t SHCSR; /*!< Offset: 0x024 (R/W) System Handler Control and State Register */ __IO uint32_t CFSR; /*!< Offset: 0x028 (R/W) Configurable Fault Status Register */ __IO uint32_t HFSR; /*!< Offset: 0x02C (R/W) HardFault Status Register */ __IO uint32_t DFSR; /*!< Offset: 0x030 (R/W) Debug Fault Status Register */ __IO uint32_t MMFAR; /*!< Offset: 0x034 (R/W) MemManage Fault Address Register */ __IO uint32_t BFAR; /*!< Offset: 0x038 (R/W) BusFault Address Register */ __IO uint32_t AFSR; /*!< Offset: 0x03C (R/W) Auxiliary Fault Status Register */ __I uint32_t PFR[2]; /*!< Offset: 0x040 (R/ ) Processor Feature Register */ __I uint32_t DFR; /*!< Offset: 0x048 (R/ ) Debug Feature Register */ __I uint32_t ADR; /*!< Offset: 0x04C (R/ ) Auxiliary Feature Register */ __I uint32_t MMFR[4]; /*!< Offset: 0x050 (R/ ) Memory Model Feature Register */ __I uint32_t ISAR[5]; /*!< Offset: 0x060 (R/ ) Instruction Set Attributes Register */ uint32_t RESERVED0[5]; __IO uint32_t CPACR; /*!< Offset: 0x088 (R/W) Coprocessor Access Control Register */ uint32_t RESERVED1[129]; __IO uint32_t SFCR; /*!< Offset: 0x290 (R/W) Security Features Control Register */ } SCB_Type; /* SCB CPUID Register Definitions */ #define SCB_CPUID_IMPLEMENTER_Pos 24 /*!< SCB CPUID: IMPLEMENTER Position */ #define SCB_CPUID_IMPLEMENTER_Msk (0xFFUL << SCB_CPUID_IMPLEMENTER_Pos) /*!< SCB CPUID: IMPLEMENTER Mask */ #define SCB_CPUID_VARIANT_Pos 20 /*!< SCB CPUID: VARIANT Position */ #define SCB_CPUID_VARIANT_Msk (0xFUL << SCB_CPUID_VARIANT_Pos) /*!< SCB CPUID: VARIANT Mask */ #define SCB_CPUID_ARCHITECTURE_Pos 16 /*!< SCB CPUID: ARCHITECTURE Position */ #define SCB_CPUID_ARCHITECTURE_Msk (0xFUL << SCB_CPUID_ARCHITECTURE_Pos) /*!< SCB CPUID: ARCHITECTURE Mask */ #define SCB_CPUID_PARTNO_Pos 4 /*!< SCB CPUID: PARTNO Position */ #define SCB_CPUID_PARTNO_Msk (0xFFFUL << SCB_CPUID_PARTNO_Pos) /*!< SCB CPUID: PARTNO Mask */ #define SCB_CPUID_REVISION_Pos 0 /*!< SCB CPUID: REVISION Position */ #define SCB_CPUID_REVISION_Msk (0xFUL /*<< SCB_CPUID_REVISION_Pos*/) /*!< SCB CPUID: REVISION Mask */ /* SCB Interrupt Control State Register Definitions */ #define SCB_ICSR_NMIPENDSET_Pos 31 /*!< SCB ICSR: NMIPENDSET Position */ #define SCB_ICSR_NMIPENDSET_Msk (1UL << SCB_ICSR_NMIPENDSET_Pos) /*!< SCB ICSR: NMIPENDSET Mask */ #define SCB_ICSR_PENDSVSET_Pos 28 /*!< SCB ICSR: PENDSVSET Position */ #define SCB_ICSR_PENDSVSET_Msk (1UL << SCB_ICSR_PENDSVSET_Pos) /*!< SCB ICSR: PENDSVSET Mask */ #define SCB_ICSR_PENDSVCLR_Pos 27 /*!< SCB ICSR: PENDSVCLR Position */ #define SCB_ICSR_PENDSVCLR_Msk (1UL << SCB_ICSR_PENDSVCLR_Pos) /*!< SCB ICSR: PENDSVCLR Mask */ #define SCB_ICSR_PENDSTSET_Pos 26 /*!< SCB ICSR: PENDSTSET Position */ #define SCB_ICSR_PENDSTSET_Msk (1UL << SCB_ICSR_PENDSTSET_Pos) /*!< SCB ICSR: PENDSTSET Mask */ #define SCB_ICSR_PENDSTCLR_Pos 25 /*!< SCB ICSR: PENDSTCLR Position */ #define SCB_ICSR_PENDSTCLR_Msk (1UL << SCB_ICSR_PENDSTCLR_Pos) /*!< SCB ICSR: PENDSTCLR Mask */ #define SCB_ICSR_ISRPREEMPT_Pos 23 /*!< SCB ICSR: ISRPREEMPT Position */ #define SCB_ICSR_ISRPREEMPT_Msk (1UL << SCB_ICSR_ISRPREEMPT_Pos) /*!< SCB ICSR: ISRPREEMPT Mask */ #define SCB_ICSR_ISRPENDING_Pos 22 /*!< SCB ICSR: ISRPENDING Position */ #define SCB_ICSR_ISRPENDING_Msk (1UL << SCB_ICSR_ISRPENDING_Pos) /*!< SCB ICSR: ISRPENDING Mask */ #define SCB_ICSR_VECTPENDING_Pos 12 /*!< SCB ICSR: VECTPENDING Position */ #define SCB_ICSR_VECTPENDING_Msk (0x1FFUL << SCB_ICSR_VECTPENDING_Pos) /*!< SCB ICSR: VECTPENDING Mask */ #define SCB_ICSR_RETTOBASE_Pos 11 /*!< SCB ICSR: RETTOBASE Position */ #define SCB_ICSR_RETTOBASE_Msk (1UL << SCB_ICSR_RETTOBASE_Pos) /*!< SCB ICSR: RETTOBASE Mask */ #define SCB_ICSR_VECTACTIVE_Pos 0 /*!< SCB ICSR: VECTACTIVE Position */ #define SCB_ICSR_VECTACTIVE_Msk (0x1FFUL /*<< SCB_ICSR_VECTACTIVE_Pos*/) /*!< SCB ICSR: VECTACTIVE Mask */ /* SCB Vector Table Offset Register Definitions */ #define SCB_VTOR_TBLBASE_Pos 29 /*!< SCB VTOR: TBLBASE Position */ #define SCB_VTOR_TBLBASE_Msk (1UL << SCB_VTOR_TBLBASE_Pos) /*!< SCB VTOR: TBLBASE Mask */ #define SCB_VTOR_TBLOFF_Pos 7 /*!< SCB VTOR: TBLOFF Position */ #define SCB_VTOR_TBLOFF_Msk (0x3FFFFFUL << SCB_VTOR_TBLOFF_Pos) /*!< SCB VTOR: TBLOFF Mask */ /* SCB Application Interrupt and Reset Control Register Definitions */ #define SCB_AIRCR_VECTKEY_Pos 16 /*!< SCB AIRCR: VECTKEY Position */ #define SCB_AIRCR_VECTKEY_Msk (0xFFFFUL << SCB_AIRCR_VECTKEY_Pos) /*!< SCB AIRCR: VECTKEY Mask */ #define SCB_AIRCR_VECTKEYSTAT_Pos 16 /*!< SCB AIRCR: VECTKEYSTAT Position */ #define SCB_AIRCR_VECTKEYSTAT_Msk (0xFFFFUL << SCB_AIRCR_VECTKEYSTAT_Pos) /*!< SCB AIRCR: VECTKEYSTAT Mask */ #define SCB_AIRCR_ENDIANESS_Pos 15 /*!< SCB AIRCR: ENDIANESS Position */ #define SCB_AIRCR_ENDIANESS_Msk (1UL << SCB_AIRCR_ENDIANESS_Pos) /*!< SCB AIRCR: ENDIANESS Mask */ #define SCB_AIRCR_PRIGROUP_Pos 8 /*!< SCB AIRCR: PRIGROUP Position */ #define SCB_AIRCR_PRIGROUP_Msk (7UL << SCB_AIRCR_PRIGROUP_Pos) /*!< SCB AIRCR: PRIGROUP Mask */ #define SCB_AIRCR_SYSRESETREQ_Pos 2 /*!< SCB AIRCR: SYSRESETREQ Position */ #define SCB_AIRCR_SYSRESETREQ_Msk (1UL << SCB_AIRCR_SYSRESETREQ_Pos) /*!< SCB AIRCR: SYSRESETREQ Mask */ #define SCB_AIRCR_VECTCLRACTIVE_Pos 1 /*!< SCB AIRCR: VECTCLRACTIVE Position */ #define SCB_AIRCR_VECTCLRACTIVE_Msk (1UL << SCB_AIRCR_VECTCLRACTIVE_Pos) /*!< SCB AIRCR: VECTCLRACTIVE Mask */ #define SCB_AIRCR_VECTRESET_Pos 0 /*!< SCB AIRCR: VECTRESET Position */ #define SCB_AIRCR_VECTRESET_Msk (1UL /*<< SCB_AIRCR_VECTRESET_Pos*/) /*!< SCB AIRCR: VECTRESET Mask */ /* SCB System Control Register Definitions */ #define SCB_SCR_SEVONPEND_Pos 4 /*!< SCB SCR: SEVONPEND Position */ #define SCB_SCR_SEVONPEND_Msk (1UL << SCB_SCR_SEVONPEND_Pos) /*!< SCB SCR: SEVONPEND Mask */ #define SCB_SCR_SLEEPDEEP_Pos 2 /*!< SCB SCR: SLEEPDEEP Position */ #define SCB_SCR_SLEEPDEEP_Msk (1UL << SCB_SCR_SLEEPDEEP_Pos) /*!< SCB SCR: SLEEPDEEP Mask */ #define SCB_SCR_SLEEPONEXIT_Pos 1 /*!< SCB SCR: SLEEPONEXIT Position */ #define SCB_SCR_SLEEPONEXIT_Msk (1UL << SCB_SCR_SLEEPONEXIT_Pos) /*!< SCB SCR: SLEEPONEXIT Mask */ /* SCB Configuration Control Register Definitions */ #define SCB_CCR_STKALIGN_Pos 9 /*!< SCB CCR: STKALIGN Position */ #define SCB_CCR_STKALIGN_Msk (1UL << SCB_CCR_STKALIGN_Pos) /*!< SCB CCR: STKALIGN Mask */ #define SCB_CCR_BFHFNMIGN_Pos 8 /*!< SCB CCR: BFHFNMIGN Position */ #define SCB_CCR_BFHFNMIGN_Msk (1UL << SCB_CCR_BFHFNMIGN_Pos) /*!< SCB CCR: BFHFNMIGN Mask */ #define SCB_CCR_DIV_0_TRP_Pos 4 /*!< SCB CCR: DIV_0_TRP Position */ #define SCB_CCR_DIV_0_TRP_Msk (1UL << SCB_CCR_DIV_0_TRP_Pos) /*!< SCB CCR: DIV_0_TRP Mask */ #define SCB_CCR_UNALIGN_TRP_Pos 3 /*!< SCB CCR: UNALIGN_TRP Position */ #define SCB_CCR_UNALIGN_TRP_Msk (1UL << SCB_CCR_UNALIGN_TRP_Pos) /*!< SCB CCR: UNALIGN_TRP Mask */ #define SCB_CCR_USERSETMPEND_Pos 1 /*!< SCB CCR: USERSETMPEND Position */ #define SCB_CCR_USERSETMPEND_Msk (1UL << SCB_CCR_USERSETMPEND_Pos) /*!< SCB CCR: USERSETMPEND Mask */ #define SCB_CCR_NONBASETHRDENA_Pos 0 /*!< SCB CCR: NONBASETHRDENA Position */ #define SCB_CCR_NONBASETHRDENA_Msk (1UL /*<< SCB_CCR_NONBASETHRDENA_Pos*/) /*!< SCB CCR: NONBASETHRDENA Mask */ /* SCB System Handler Control and State Register Definitions */ #define SCB_SHCSR_USGFAULTENA_Pos 18 /*!< SCB SHCSR: USGFAULTENA Position */ #define SCB_SHCSR_USGFAULTENA_Msk (1UL << SCB_SHCSR_USGFAULTENA_Pos) /*!< SCB SHCSR: USGFAULTENA Mask */ #define SCB_SHCSR_BUSFAULTENA_Pos 17 /*!< SCB SHCSR: BUSFAULTENA Position */ #define SCB_SHCSR_BUSFAULTENA_Msk (1UL << SCB_SHCSR_BUSFAULTENA_Pos) /*!< SCB SHCSR: BUSFAULTENA Mask */ #define SCB_SHCSR_MEMFAULTENA_Pos 16 /*!< SCB SHCSR: MEMFAULTENA Position */ #define SCB_SHCSR_MEMFAULTENA_Msk (1UL << SCB_SHCSR_MEMFAULTENA_Pos) /*!< SCB SHCSR: MEMFAULTENA Mask */ #define SCB_SHCSR_SVCALLPENDED_Pos 15 /*!< SCB SHCSR: SVCALLPENDED Position */ #define SCB_SHCSR_SVCALLPENDED_Msk (1UL << SCB_SHCSR_SVCALLPENDED_Pos) /*!< SCB SHCSR: SVCALLPENDED Mask */ #define SCB_SHCSR_BUSFAULTPENDED_Pos 14 /*!< SCB SHCSR: BUSFAULTPENDED Position */ #define SCB_SHCSR_BUSFAULTPENDED_Msk (1UL << SCB_SHCSR_BUSFAULTPENDED_Pos) /*!< SCB SHCSR: BUSFAULTPENDED Mask */ #define SCB_SHCSR_MEMFAULTPENDED_Pos 13 /*!< SCB SHCSR: MEMFAULTPENDED Position */ #define SCB_SHCSR_MEMFAULTPENDED_Msk (1UL << SCB_SHCSR_MEMFAULTPENDED_Pos) /*!< SCB SHCSR: MEMFAULTPENDED Mask */ #define SCB_SHCSR_USGFAULTPENDED_Pos 12 /*!< SCB SHCSR: USGFAULTPENDED Position */ #define SCB_SHCSR_USGFAULTPENDED_Msk (1UL << SCB_SHCSR_USGFAULTPENDED_Pos) /*!< SCB SHCSR: USGFAULTPENDED Mask */ #define SCB_SHCSR_SYSTICKACT_Pos 11 /*!< SCB SHCSR: SYSTICKACT Position */ #define SCB_SHCSR_SYSTICKACT_Msk (1UL << SCB_SHCSR_SYSTICKACT_Pos) /*!< SCB SHCSR: SYSTICKACT Mask */ #define SCB_SHCSR_PENDSVACT_Pos 10 /*!< SCB SHCSR: PENDSVACT Position */ #define SCB_SHCSR_PENDSVACT_Msk (1UL << SCB_SHCSR_PENDSVACT_Pos) /*!< SCB SHCSR: PENDSVACT Mask */ #define SCB_SHCSR_MONITORACT_Pos 8 /*!< SCB SHCSR: MONITORACT Position */ #define SCB_SHCSR_MONITORACT_Msk (1UL << SCB_SHCSR_MONITORACT_Pos) /*!< SCB SHCSR: MONITORACT Mask */ #define SCB_SHCSR_SVCALLACT_Pos 7 /*!< SCB SHCSR: SVCALLACT Position */ #define SCB_SHCSR_SVCALLACT_Msk (1UL << SCB_SHCSR_SVCALLACT_Pos) /*!< SCB SHCSR: SVCALLACT Mask */ #define SCB_SHCSR_USGFAULTACT_Pos 3 /*!< SCB SHCSR: USGFAULTACT Position */ #define SCB_SHCSR_USGFAULTACT_Msk (1UL << SCB_SHCSR_USGFAULTACT_Pos) /*!< SCB SHCSR: USGFAULTACT Mask */ #define SCB_SHCSR_BUSFAULTACT_Pos 1 /*!< SCB SHCSR: BUSFAULTACT Position */ #define SCB_SHCSR_BUSFAULTACT_Msk (1UL << SCB_SHCSR_BUSFAULTACT_Pos) /*!< SCB SHCSR: BUSFAULTACT Mask */ #define SCB_SHCSR_MEMFAULTACT_Pos 0 /*!< SCB SHCSR: MEMFAULTACT Position */ #define SCB_SHCSR_MEMFAULTACT_Msk (1UL /*<< SCB_SHCSR_MEMFAULTACT_Pos*/) /*!< SCB SHCSR: MEMFAULTACT Mask */ /* SCB Configurable Fault Status Registers Definitions */ #define SCB_CFSR_USGFAULTSR_Pos 16 /*!< SCB CFSR: Usage Fault Status Register Position */ #define SCB_CFSR_USGFAULTSR_Msk (0xFFFFUL << SCB_CFSR_USGFAULTSR_Pos) /*!< SCB CFSR: Usage Fault Status Register Mask */ #define SCB_CFSR_BUSFAULTSR_Pos 8 /*!< SCB CFSR: Bus Fault Status Register Position */ #define SCB_CFSR_BUSFAULTSR_Msk (0xFFUL << SCB_CFSR_BUSFAULTSR_Pos) /*!< SCB CFSR: Bus Fault Status Register Mask */ #define SCB_CFSR_MEMFAULTSR_Pos 0 /*!< SCB CFSR: Memory Manage Fault Status Register Position */ #define SCB_CFSR_MEMFAULTSR_Msk (0xFFUL /*<< SCB_CFSR_MEMFAULTSR_Pos*/) /*!< SCB CFSR: Memory Manage Fault Status Register Mask */ /* SCB Hard Fault Status Registers Definitions */ #define SCB_HFSR_DEBUGEVT_Pos 31 /*!< SCB HFSR: DEBUGEVT Position */ #define SCB_HFSR_DEBUGEVT_Msk (1UL << SCB_HFSR_DEBUGEVT_Pos) /*!< SCB HFSR: DEBUGEVT Mask */ #define SCB_HFSR_FORCED_Pos 30 /*!< SCB HFSR: FORCED Position */ #define SCB_HFSR_FORCED_Msk (1UL << SCB_HFSR_FORCED_Pos) /*!< SCB HFSR: FORCED Mask */ #define SCB_HFSR_VECTTBL_Pos 1 /*!< SCB HFSR: VECTTBL Position */ #define SCB_HFSR_VECTTBL_Msk (1UL << SCB_HFSR_VECTTBL_Pos) /*!< SCB HFSR: VECTTBL Mask */ /* SCB Debug Fault Status Register Definitions */ #define SCB_DFSR_EXTERNAL_Pos 4 /*!< SCB DFSR: EXTERNAL Position */ #define SCB_DFSR_EXTERNAL_Msk (1UL << SCB_DFSR_EXTERNAL_Pos) /*!< SCB DFSR: EXTERNAL Mask */ #define SCB_DFSR_VCATCH_Pos 3 /*!< SCB DFSR: VCATCH Position */ #define SCB_DFSR_VCATCH_Msk (1UL << SCB_DFSR_VCATCH_Pos) /*!< SCB DFSR: VCATCH Mask */ #define SCB_DFSR_DWTTRAP_Pos 2 /*!< SCB DFSR: DWTTRAP Position */ #define SCB_DFSR_DWTTRAP_Msk (1UL << SCB_DFSR_DWTTRAP_Pos) /*!< SCB DFSR: DWTTRAP Mask */ #define SCB_DFSR_BKPT_Pos 1 /*!< SCB DFSR: BKPT Position */ #define SCB_DFSR_BKPT_Msk (1UL << SCB_DFSR_BKPT_Pos) /*!< SCB DFSR: BKPT Mask */ #define SCB_DFSR_HALTED_Pos 0 /*!< SCB DFSR: HALTED Position */ #define SCB_DFSR_HALTED_Msk (1UL /*<< SCB_DFSR_HALTED_Pos*/) /*!< SCB DFSR: HALTED Mask */ /*@} end of group CMSIS_SCB */ /** \ingroup CMSIS_core_register \defgroup CMSIS_SCnSCB System Controls not in SCB (SCnSCB) \brief Type definitions for the System Control and ID Register not in the SCB @{ */ /** \brief Structure type to access the System Control and ID Register not in the SCB. */ typedef struct { uint32_t RESERVED0[1]; __I uint32_t ICTR; /*!< Offset: 0x004 (R/ ) Interrupt Controller Type Register */ uint32_t RESERVED1[1]; } SCnSCB_Type; /* Interrupt Controller Type Register Definitions */ #define SCnSCB_ICTR_INTLINESNUM_Pos 0 /*!< ICTR: INTLINESNUM Position */ #define SCnSCB_ICTR_INTLINESNUM_Msk (0xFUL /*<< SCnSCB_ICTR_INTLINESNUM_Pos*/) /*!< ICTR: INTLINESNUM Mask */ /*@} end of group CMSIS_SCnotSCB */ /** \ingroup CMSIS_core_register \defgroup CMSIS_SysTick System Tick Timer (SysTick) \brief Type definitions for the System Timer Registers. @{ */ /** \brief Structure type to access the System Timer (SysTick). */ typedef struct { __IO uint32_t CTRL; /*!< Offset: 0x000 (R/W) SysTick Control and Status Register */ __IO uint32_t LOAD; /*!< Offset: 0x004 (R/W) SysTick Reload Value Register */ __IO uint32_t VAL; /*!< Offset: 0x008 (R/W) SysTick Current Value Register */ __I uint32_t CALIB; /*!< Offset: 0x00C (R/ ) SysTick Calibration Register */ } SysTick_Type; /* SysTick Control / Status Register Definitions */ #define SysTick_CTRL_COUNTFLAG_Pos 16 /*!< SysTick CTRL: COUNTFLAG Position */ #define SysTick_CTRL_COUNTFLAG_Msk (1UL << SysTick_CTRL_COUNTFLAG_Pos) /*!< SysTick CTRL: COUNTFLAG Mask */ #define SysTick_CTRL_CLKSOURCE_Pos 2 /*!< SysTick CTRL: CLKSOURCE Position */ #define SysTick_CTRL_CLKSOURCE_Msk (1UL << SysTick_CTRL_CLKSOURCE_Pos) /*!< SysTick CTRL: CLKSOURCE Mask */ #define SysTick_CTRL_TICKINT_Pos 1 /*!< SysTick CTRL: TICKINT Position */ #define SysTick_CTRL_TICKINT_Msk (1UL << SysTick_CTRL_TICKINT_Pos) /*!< SysTick CTRL: TICKINT Mask */ #define SysTick_CTRL_ENABLE_Pos 0 /*!< SysTick CTRL: ENABLE Position */ #define SysTick_CTRL_ENABLE_Msk (1UL /*<< SysTick_CTRL_ENABLE_Pos*/) /*!< SysTick CTRL: ENABLE Mask */ /* SysTick Reload Register Definitions */ #define SysTick_LOAD_RELOAD_Pos 0 /*!< SysTick LOAD: RELOAD Position */ #define SysTick_LOAD_RELOAD_Msk (0xFFFFFFUL /*<< SysTick_LOAD_RELOAD_Pos*/) /*!< SysTick LOAD: RELOAD Mask */ /* SysTick Current Register Definitions */ #define SysTick_VAL_CURRENT_Pos 0 /*!< SysTick VAL: CURRENT Position */ #define SysTick_VAL_CURRENT_Msk (0xFFFFFFUL /*<< SysTick_VAL_CURRENT_Pos*/) /*!< SysTick VAL: CURRENT Mask */ /* SysTick Calibration Register Definitions */ #define SysTick_CALIB_NOREF_Pos 31 /*!< SysTick CALIB: NOREF Position */ #define SysTick_CALIB_NOREF_Msk (1UL << SysTick_CALIB_NOREF_Pos) /*!< SysTick CALIB: NOREF Mask */ #define SysTick_CALIB_SKEW_Pos 30 /*!< SysTick CALIB: SKEW Position */ #define SysTick_CALIB_SKEW_Msk (1UL << SysTick_CALIB_SKEW_Pos) /*!< SysTick CALIB: SKEW Mask */ #define SysTick_CALIB_TENMS_Pos 0 /*!< SysTick CALIB: TENMS Position */ #define SysTick_CALIB_TENMS_Msk (0xFFFFFFUL /*<< SysTick_CALIB_TENMS_Pos*/) /*!< SysTick CALIB: TENMS Mask */ /*@} end of group CMSIS_SysTick */ /** \ingroup CMSIS_core_register \defgroup CMSIS_ITM Instrumentation Trace Macrocell (ITM) \brief Type definitions for the Instrumentation Trace Macrocell (ITM) @{ */ /** \brief Structure type to access the Instrumentation Trace Macrocell Register (ITM). */ typedef struct { __O union { __O uint8_t u8; /*!< Offset: 0x000 ( /W) ITM Stimulus Port 8-bit */ __O uint16_t u16; /*!< Offset: 0x000 ( /W) ITM Stimulus Port 16-bit */ __O uint32_t u32; /*!< Offset: 0x000 ( /W) ITM Stimulus Port 32-bit */ } PORT [32]; /*!< Offset: 0x000 ( /W) ITM Stimulus Port Registers */ uint32_t RESERVED0[864]; __IO uint32_t TER; /*!< Offset: 0xE00 (R/W) ITM Trace Enable Register */ uint32_t RESERVED1[15]; __IO uint32_t TPR; /*!< Offset: 0xE40 (R/W) ITM Trace Privilege Register */ uint32_t RESERVED2[15]; __IO uint32_t TCR; /*!< Offset: 0xE80 (R/W) ITM Trace Control Register */ uint32_t RESERVED3[29]; __O uint32_t IWR; /*!< Offset: 0xEF8 ( /W) ITM Integration Write Register */ __I uint32_t IRR; /*!< Offset: 0xEFC (R/ ) ITM Integration Read Register */ __IO uint32_t IMCR; /*!< Offset: 0xF00 (R/W) ITM Integration Mode Control Register */ uint32_t RESERVED4[43]; __O uint32_t LAR; /*!< Offset: 0xFB0 ( /W) ITM Lock Access Register */ __I uint32_t LSR; /*!< Offset: 0xFB4 (R/ ) ITM Lock Status Register */ uint32_t RESERVED5[6]; __I uint32_t PID4; /*!< Offset: 0xFD0 (R/ ) ITM Peripheral Identification Register #4 */ __I uint32_t PID5; /*!< Offset: 0xFD4 (R/ ) ITM Peripheral Identification Register #5 */ __I uint32_t PID6; /*!< Offset: 0xFD8 (R/ ) ITM Peripheral Identification Register #6 */ __I uint32_t PID7; /*!< Offset: 0xFDC (R/ ) ITM Peripheral Identification Register #7 */ __I uint32_t PID0; /*!< Offset: 0xFE0 (R/ ) ITM Peripheral Identification Register #0 */ __I uint32_t PID1; /*!< Offset: 0xFE4 (R/ ) ITM Peripheral Identification Register #1 */ __I uint32_t PID2; /*!< Offset: 0xFE8 (R/ ) ITM Peripheral Identification Register #2 */ __I uint32_t PID3; /*!< Offset: 0xFEC (R/ ) ITM Peripheral Identification Register #3 */ __I uint32_t CID0; /*!< Offset: 0xFF0 (R/ ) ITM Component Identification Register #0 */ __I uint32_t CID1; /*!< Offset: 0xFF4 (R/ ) ITM Component Identification Register #1 */ __I uint32_t CID2; /*!< Offset: 0xFF8 (R/ ) ITM Component Identification Register #2 */ __I uint32_t CID3; /*!< Offset: 0xFFC (R/ ) ITM Component Identification Register #3 */ } ITM_Type; /* ITM Trace Privilege Register Definitions */ #define ITM_TPR_PRIVMASK_Pos 0 /*!< ITM TPR: PRIVMASK Position */ #define ITM_TPR_PRIVMASK_Msk (0xFUL /*<< ITM_TPR_PRIVMASK_Pos*/) /*!< ITM TPR: PRIVMASK Mask */ /* ITM Trace Control Register Definitions */ #define ITM_TCR_BUSY_Pos 23 /*!< ITM TCR: BUSY Position */ #define ITM_TCR_BUSY_Msk (1UL << ITM_TCR_BUSY_Pos) /*!< ITM TCR: BUSY Mask */ #define ITM_TCR_TraceBusID_Pos 16 /*!< ITM TCR: ATBID Position */ #define ITM_TCR_TraceBusID_Msk (0x7FUL << ITM_TCR_TraceBusID_Pos) /*!< ITM TCR: ATBID Mask */ #define ITM_TCR_GTSFREQ_Pos 10 /*!< ITM TCR: Global timestamp frequency Position */ #define ITM_TCR_GTSFREQ_Msk (3UL << ITM_TCR_GTSFREQ_Pos) /*!< ITM TCR: Global timestamp frequency Mask */ #define ITM_TCR_TSPrescale_Pos 8 /*!< ITM TCR: TSPrescale Position */ #define ITM_TCR_TSPrescale_Msk (3UL << ITM_TCR_TSPrescale_Pos) /*!< ITM TCR: TSPrescale Mask */ #define ITM_TCR_SWOENA_Pos 4 /*!< ITM TCR: SWOENA Position */ #define ITM_TCR_SWOENA_Msk (1UL << ITM_TCR_SWOENA_Pos) /*!< ITM TCR: SWOENA Mask */ #define ITM_TCR_DWTENA_Pos 3 /*!< ITM TCR: DWTENA Position */ #define ITM_TCR_DWTENA_Msk (1UL << ITM_TCR_DWTENA_Pos) /*!< ITM TCR: DWTENA Mask */ #define ITM_TCR_SYNCENA_Pos 2 /*!< ITM TCR: SYNCENA Position */ #define ITM_TCR_SYNCENA_Msk (1UL << ITM_TCR_SYNCENA_Pos) /*!< ITM TCR: SYNCENA Mask */ #define ITM_TCR_TSENA_Pos 1 /*!< ITM TCR: TSENA Position */ #define ITM_TCR_TSENA_Msk (1UL << ITM_TCR_TSENA_Pos) /*!< ITM TCR: TSENA Mask */ #define ITM_TCR_ITMENA_Pos 0 /*!< ITM TCR: ITM Enable bit Position */ #define ITM_TCR_ITMENA_Msk (1UL /*<< ITM_TCR_ITMENA_Pos*/) /*!< ITM TCR: ITM Enable bit Mask */ /* ITM Integration Write Register Definitions */ #define ITM_IWR_ATVALIDM_Pos 0 /*!< ITM IWR: ATVALIDM Position */ #define ITM_IWR_ATVALIDM_Msk (1UL /*<< ITM_IWR_ATVALIDM_Pos*/) /*!< ITM IWR: ATVALIDM Mask */ /* ITM Integration Read Register Definitions */ #define ITM_IRR_ATREADYM_Pos 0 /*!< ITM IRR: ATREADYM Position */ #define ITM_IRR_ATREADYM_Msk (1UL /*<< ITM_IRR_ATREADYM_Pos*/) /*!< ITM IRR: ATREADYM Mask */ /* ITM Integration Mode Control Register Definitions */ #define ITM_IMCR_INTEGRATION_Pos 0 /*!< ITM IMCR: INTEGRATION Position */ #define ITM_IMCR_INTEGRATION_Msk (1UL /*<< ITM_IMCR_INTEGRATION_Pos*/) /*!< ITM IMCR: INTEGRATION Mask */ /* ITM Lock Status Register Definitions */ #define ITM_LSR_ByteAcc_Pos 2 /*!< ITM LSR: ByteAcc Position */ #define ITM_LSR_ByteAcc_Msk (1UL << ITM_LSR_ByteAcc_Pos) /*!< ITM LSR: ByteAcc Mask */ #define ITM_LSR_Access_Pos 1 /*!< ITM LSR: Access Position */ #define ITM_LSR_Access_Msk (1UL << ITM_LSR_Access_Pos) /*!< ITM LSR: Access Mask */ #define ITM_LSR_Present_Pos 0 /*!< ITM LSR: Present Position */ #define ITM_LSR_Present_Msk (1UL /*<< ITM_LSR_Present_Pos*/) /*!< ITM LSR: Present Mask */ /*@}*/ /* end of group CMSIS_ITM */ /** \ingroup CMSIS_core_register \defgroup CMSIS_DWT Data Watchpoint and Trace (DWT) \brief Type definitions for the Data Watchpoint and Trace (DWT) @{ */ /** \brief Structure type to access the Data Watchpoint and Trace Register (DWT). */ typedef struct { __IO uint32_t CTRL; /*!< Offset: 0x000 (R/W) Control Register */ __IO uint32_t CYCCNT; /*!< Offset: 0x004 (R/W) Cycle Count Register */ __IO uint32_t CPICNT; /*!< Offset: 0x008 (R/W) CPI Count Register */ __IO uint32_t EXCCNT; /*!< Offset: 0x00C (R/W) Exception Overhead Count Register */ __IO uint32_t SLEEPCNT; /*!< Offset: 0x010 (R/W) Sleep Count Register */ __IO uint32_t LSUCNT; /*!< Offset: 0x014 (R/W) LSU Count Register */ __IO uint32_t FOLDCNT; /*!< Offset: 0x018 (R/W) Folded-instruction Count Register */ __I uint32_t PCSR; /*!< Offset: 0x01C (R/ ) Program Counter Sample Register */ __IO uint32_t COMP0; /*!< Offset: 0x020 (R/W) Comparator Register 0 */ __IO uint32_t MASK0; /*!< Offset: 0x024 (R/W) Mask Register 0 */ __IO uint32_t FUNCTION0; /*!< Offset: 0x028 (R/W) Function Register 0 */ uint32_t RESERVED0[1]; __IO uint32_t COMP1; /*!< Offset: 0x030 (R/W) Comparator Register 1 */ __IO uint32_t MASK1; /*!< Offset: 0x034 (R/W) Mask Register 1 */ __IO uint32_t FUNCTION1; /*!< Offset: 0x038 (R/W) Function Register 1 */ uint32_t RESERVED1[1]; __IO uint32_t COMP2; /*!< Offset: 0x040 (R/W) Comparator Register 2 */ __IO uint32_t MASK2; /*!< Offset: 0x044 (R/W) Mask Register 2 */ __IO uint32_t FUNCTION2; /*!< Offset: 0x048 (R/W) Function Register 2 */ uint32_t RESERVED2[1]; __IO uint32_t COMP3; /*!< Offset: 0x050 (R/W) Comparator Register 3 */ __IO uint32_t MASK3; /*!< Offset: 0x054 (R/W) Mask Register 3 */ __IO uint32_t FUNCTION3; /*!< Offset: 0x058 (R/W) Function Register 3 */ } DWT_Type; /* DWT Control Register Definitions */ #define DWT_CTRL_NUMCOMP_Pos 28 /*!< DWT CTRL: NUMCOMP Position */ #define DWT_CTRL_NUMCOMP_Msk (0xFUL << DWT_CTRL_NUMCOMP_Pos) /*!< DWT CTRL: NUMCOMP Mask */ #define DWT_CTRL_NOTRCPKT_Pos 27 /*!< DWT CTRL: NOTRCPKT Position */ #define DWT_CTRL_NOTRCPKT_Msk (0x1UL << DWT_CTRL_NOTRCPKT_Pos) /*!< DWT CTRL: NOTRCPKT Mask */ #define DWT_CTRL_NOEXTTRIG_Pos 26 /*!< DWT CTRL: NOEXTTRIG Position */ #define DWT_CTRL_NOEXTTRIG_Msk (0x1UL << DWT_CTRL_NOEXTTRIG_Pos) /*!< DWT CTRL: NOEXTTRIG Mask */ #define DWT_CTRL_NOCYCCNT_Pos 25 /*!< DWT CTRL: NOCYCCNT Position */ #define DWT_CTRL_NOCYCCNT_Msk (0x1UL << DWT_CTRL_NOCYCCNT_Pos) /*!< DWT CTRL: NOCYCCNT Mask */ #define DWT_CTRL_NOPRFCNT_Pos 24 /*!< DWT CTRL: NOPRFCNT Position */ #define DWT_CTRL_NOPRFCNT_Msk (0x1UL << DWT_CTRL_NOPRFCNT_Pos) /*!< DWT CTRL: NOPRFCNT Mask */ #define DWT_CTRL_CYCEVTENA_Pos 22 /*!< DWT CTRL: CYCEVTENA Position */ #define DWT_CTRL_CYCEVTENA_Msk (0x1UL << DWT_CTRL_CYCEVTENA_Pos) /*!< DWT CTRL: CYCEVTENA Mask */ #define DWT_CTRL_FOLDEVTENA_Pos 21 /*!< DWT CTRL: FOLDEVTENA Position */ #define DWT_CTRL_FOLDEVTENA_Msk (0x1UL << DWT_CTRL_FOLDEVTENA_Pos) /*!< DWT CTRL: FOLDEVTENA Mask */ #define DWT_CTRL_LSUEVTENA_Pos 20 /*!< DWT CTRL: LSUEVTENA Position */ #define DWT_CTRL_LSUEVTENA_Msk (0x1UL << DWT_CTRL_LSUEVTENA_Pos) /*!< DWT CTRL: LSUEVTENA Mask */ #define DWT_CTRL_SLEEPEVTENA_Pos 19 /*!< DWT CTRL: SLEEPEVTENA Position */ #define DWT_CTRL_SLEEPEVTENA_Msk (0x1UL << DWT_CTRL_SLEEPEVTENA_Pos) /*!< DWT CTRL: SLEEPEVTENA Mask */ #define DWT_CTRL_EXCEVTENA_Pos 18 /*!< DWT CTRL: EXCEVTENA Position */ #define DWT_CTRL_EXCEVTENA_Msk (0x1UL << DWT_CTRL_EXCEVTENA_Pos) /*!< DWT CTRL: EXCEVTENA Mask */ #define DWT_CTRL_CPIEVTENA_Pos 17 /*!< DWT CTRL: CPIEVTENA Position */ #define DWT_CTRL_CPIEVTENA_Msk (0x1UL << DWT_CTRL_CPIEVTENA_Pos) /*!< DWT CTRL: CPIEVTENA Mask */ #define DWT_CTRL_EXCTRCENA_Pos 16 /*!< DWT CTRL: EXCTRCENA Position */ #define DWT_CTRL_EXCTRCENA_Msk (0x1UL << DWT_CTRL_EXCTRCENA_Pos) /*!< DWT CTRL: EXCTRCENA Mask */ #define DWT_CTRL_PCSAMPLENA_Pos 12 /*!< DWT CTRL: PCSAMPLENA Position */ #define DWT_CTRL_PCSAMPLENA_Msk (0x1UL << DWT_CTRL_PCSAMPLENA_Pos) /*!< DWT CTRL: PCSAMPLENA Mask */ #define DWT_CTRL_SYNCTAP_Pos 10 /*!< DWT CTRL: SYNCTAP Position */ #define DWT_CTRL_SYNCTAP_Msk (0x3UL << DWT_CTRL_SYNCTAP_Pos) /*!< DWT CTRL: SYNCTAP Mask */ #define DWT_CTRL_CYCTAP_Pos 9 /*!< DWT CTRL: CYCTAP Position */ #define DWT_CTRL_CYCTAP_Msk (0x1UL << DWT_CTRL_CYCTAP_Pos) /*!< DWT CTRL: CYCTAP Mask */ #define DWT_CTRL_POSTINIT_Pos 5 /*!< DWT CTRL: POSTINIT Position */ #define DWT_CTRL_POSTINIT_Msk (0xFUL << DWT_CTRL_POSTINIT_Pos) /*!< DWT CTRL: POSTINIT Mask */ #define DWT_CTRL_POSTPRESET_Pos 1 /*!< DWT CTRL: POSTPRESET Position */ #define DWT_CTRL_POSTPRESET_Msk (0xFUL << DWT_CTRL_POSTPRESET_Pos) /*!< DWT CTRL: POSTPRESET Mask */ #define DWT_CTRL_CYCCNTENA_Pos 0 /*!< DWT CTRL: CYCCNTENA Position */ #define DWT_CTRL_CYCCNTENA_Msk (0x1UL /*<< DWT_CTRL_CYCCNTENA_Pos*/) /*!< DWT CTRL: CYCCNTENA Mask */ /* DWT CPI Count Register Definitions */ #define DWT_CPICNT_CPICNT_Pos 0 /*!< DWT CPICNT: CPICNT Position */ #define DWT_CPICNT_CPICNT_Msk (0xFFUL /*<< DWT_CPICNT_CPICNT_Pos*/) /*!< DWT CPICNT: CPICNT Mask */ /* DWT Exception Overhead Count Register Definitions */ #define DWT_EXCCNT_EXCCNT_Pos 0 /*!< DWT EXCCNT: EXCCNT Position */ #define DWT_EXCCNT_EXCCNT_Msk (0xFFUL /*<< DWT_EXCCNT_EXCCNT_Pos*/) /*!< DWT EXCCNT: EXCCNT Mask */ /* DWT Sleep Count Register Definitions */ #define DWT_SLEEPCNT_SLEEPCNT_Pos 0 /*!< DWT SLEEPCNT: SLEEPCNT Position */ #define DWT_SLEEPCNT_SLEEPCNT_Msk (0xFFUL /*<< DWT_SLEEPCNT_SLEEPCNT_Pos*/) /*!< DWT SLEEPCNT: SLEEPCNT Mask */ /* DWT LSU Count Register Definitions */ #define DWT_LSUCNT_LSUCNT_Pos 0 /*!< DWT LSUCNT: LSUCNT Position */ #define DWT_LSUCNT_LSUCNT_Msk (0xFFUL /*<< DWT_LSUCNT_LSUCNT_Pos*/) /*!< DWT LSUCNT: LSUCNT Mask */ /* DWT Folded-instruction Count Register Definitions */ #define DWT_FOLDCNT_FOLDCNT_Pos 0 /*!< DWT FOLDCNT: FOLDCNT Position */ #define DWT_FOLDCNT_FOLDCNT_Msk (0xFFUL /*<< DWT_FOLDCNT_FOLDCNT_Pos*/) /*!< DWT FOLDCNT: FOLDCNT Mask */ /* DWT Comparator Mask Register Definitions */ #define DWT_MASK_MASK_Pos 0 /*!< DWT MASK: MASK Position */ #define DWT_MASK_MASK_Msk (0x1FUL /*<< DWT_MASK_MASK_Pos*/) /*!< DWT MASK: MASK Mask */ /* DWT Comparator Function Register Definitions */ #define DWT_FUNCTION_MATCHED_Pos 24 /*!< DWT FUNCTION: MATCHED Position */ #define DWT_FUNCTION_MATCHED_Msk (0x1UL << DWT_FUNCTION_MATCHED_Pos) /*!< DWT FUNCTION: MATCHED Mask */ #define DWT_FUNCTION_DATAVADDR1_Pos 16 /*!< DWT FUNCTION: DATAVADDR1 Position */ #define DWT_FUNCTION_DATAVADDR1_Msk (0xFUL << DWT_FUNCTION_DATAVADDR1_Pos) /*!< DWT FUNCTION: DATAVADDR1 Mask */ #define DWT_FUNCTION_DATAVADDR0_Pos 12 /*!< DWT FUNCTION: DATAVADDR0 Position */ #define DWT_FUNCTION_DATAVADDR0_Msk (0xFUL << DWT_FUNCTION_DATAVADDR0_Pos) /*!< DWT FUNCTION: DATAVADDR0 Mask */ #define DWT_FUNCTION_DATAVSIZE_Pos 10 /*!< DWT FUNCTION: DATAVSIZE Position */ #define DWT_FUNCTION_DATAVSIZE_Msk (0x3UL << DWT_FUNCTION_DATAVSIZE_Pos) /*!< DWT FUNCTION: DATAVSIZE Mask */ #define DWT_FUNCTION_LNK1ENA_Pos 9 /*!< DWT FUNCTION: LNK1ENA Position */ #define DWT_FUNCTION_LNK1ENA_Msk (0x1UL << DWT_FUNCTION_LNK1ENA_Pos) /*!< DWT FUNCTION: LNK1ENA Mask */ #define DWT_FUNCTION_DATAVMATCH_Pos 8 /*!< DWT FUNCTION: DATAVMATCH Position */ #define DWT_FUNCTION_DATAVMATCH_Msk (0x1UL << DWT_FUNCTION_DATAVMATCH_Pos) /*!< DWT FUNCTION: DATAVMATCH Mask */ #define DWT_FUNCTION_CYCMATCH_Pos 7 /*!< DWT FUNCTION: CYCMATCH Position */ #define DWT_FUNCTION_CYCMATCH_Msk (0x1UL << DWT_FUNCTION_CYCMATCH_Pos) /*!< DWT FUNCTION: CYCMATCH Mask */ #define DWT_FUNCTION_EMITRANGE_Pos 5 /*!< DWT FUNCTION: EMITRANGE Position */ #define DWT_FUNCTION_EMITRANGE_Msk (0x1UL << DWT_FUNCTION_EMITRANGE_Pos) /*!< DWT FUNCTION: EMITRANGE Mask */ #define DWT_FUNCTION_FUNCTION_Pos 0 /*!< DWT FUNCTION: FUNCTION Position */ #define DWT_FUNCTION_FUNCTION_Msk (0xFUL /*<< DWT_FUNCTION_FUNCTION_Pos*/) /*!< DWT FUNCTION: FUNCTION Mask */ /*@}*/ /* end of group CMSIS_DWT */ /** \ingroup CMSIS_core_register \defgroup CMSIS_TPI Trace Port Interface (TPI) \brief Type definitions for the Trace Port Interface (TPI) @{ */ /** \brief Structure type to access the Trace Port Interface Register (TPI). */ typedef struct { __IO uint32_t SSPSR; /*!< Offset: 0x000 (R/ ) Supported Parallel Port Size Register */ __IO uint32_t CSPSR; /*!< Offset: 0x004 (R/W) Current Parallel Port Size Register */ uint32_t RESERVED0[2]; __IO uint32_t ACPR; /*!< Offset: 0x010 (R/W) Asynchronous Clock Prescaler Register */ uint32_t RESERVED1[55]; __IO uint32_t SPPR; /*!< Offset: 0x0F0 (R/W) Selected Pin Protocol Register */ uint32_t RESERVED2[131]; __I uint32_t FFSR; /*!< Offset: 0x300 (R/ ) Formatter and Flush Status Register */ __IO uint32_t FFCR; /*!< Offset: 0x304 (R/W) Formatter and Flush Control Register */ __I uint32_t FSCR; /*!< Offset: 0x308 (R/ ) Formatter Synchronization Counter Register */ uint32_t RESERVED3[759]; __I uint32_t TRIGGER; /*!< Offset: 0xEE8 (R/ ) TRIGGER */ __I uint32_t FIFO0; /*!< Offset: 0xEEC (R/ ) Integration ETM Data */ __I uint32_t ITATBCTR2; /*!< Offset: 0xEF0 (R/ ) ITATBCTR2 */ uint32_t RESERVED4[1]; __I uint32_t ITATBCTR0; /*!< Offset: 0xEF8 (R/ ) ITATBCTR0 */ __I uint32_t FIFO1; /*!< Offset: 0xEFC (R/ ) Integration ITM Data */ __IO uint32_t ITCTRL; /*!< Offset: 0xF00 (R/W) Integration Mode Control */ uint32_t RESERVED5[39]; __IO uint32_t CLAIMSET; /*!< Offset: 0xFA0 (R/W) Claim tag set */ __IO uint32_t CLAIMCLR; /*!< Offset: 0xFA4 (R/W) Claim tag clear */ uint32_t RESERVED7[8]; __I uint32_t DEVID; /*!< Offset: 0xFC8 (R/ ) TPIU_DEVID */ __I uint32_t DEVTYPE; /*!< Offset: 0xFCC (R/ ) TPIU_DEVTYPE */ } TPI_Type; /* TPI Asynchronous Clock Prescaler Register Definitions */ #define TPI_ACPR_PRESCALER_Pos 0 /*!< TPI ACPR: PRESCALER Position */ #define TPI_ACPR_PRESCALER_Msk (0x1FFFUL /*<< TPI_ACPR_PRESCALER_Pos*/) /*!< TPI ACPR: PRESCALER Mask */ /* TPI Selected Pin Protocol Register Definitions */ #define TPI_SPPR_TXMODE_Pos 0 /*!< TPI SPPR: TXMODE Position */ #define TPI_SPPR_TXMODE_Msk (0x3UL /*<< TPI_SPPR_TXMODE_Pos*/) /*!< TPI SPPR: TXMODE Mask */ /* TPI Formatter and Flush Status Register Definitions */ #define TPI_FFSR_FtNonStop_Pos 3 /*!< TPI FFSR: FtNonStop Position */ #define TPI_FFSR_FtNonStop_Msk (0x1UL << TPI_FFSR_FtNonStop_Pos) /*!< TPI FFSR: FtNonStop Mask */ #define TPI_FFSR_TCPresent_Pos 2 /*!< TPI FFSR: TCPresent Position */ #define TPI_FFSR_TCPresent_Msk (0x1UL << TPI_FFSR_TCPresent_Pos) /*!< TPI FFSR: TCPresent Mask */ #define TPI_FFSR_FtStopped_Pos 1 /*!< TPI FFSR: FtStopped Position */ #define TPI_FFSR_FtStopped_Msk (0x1UL << TPI_FFSR_FtStopped_Pos) /*!< TPI FFSR: FtStopped Mask */ #define TPI_FFSR_FlInProg_Pos 0 /*!< TPI FFSR: FlInProg Position */ #define TPI_FFSR_FlInProg_Msk (0x1UL /*<< TPI_FFSR_FlInProg_Pos*/) /*!< TPI FFSR: FlInProg Mask */ /* TPI Formatter and Flush Control Register Definitions */ #define TPI_FFCR_TrigIn_Pos 8 /*!< TPI FFCR: TrigIn Position */ #define TPI_FFCR_TrigIn_Msk (0x1UL << TPI_FFCR_TrigIn_Pos) /*!< TPI FFCR: TrigIn Mask */ #define TPI_FFCR_EnFCont_Pos 1 /*!< TPI FFCR: EnFCont Position */ #define TPI_FFCR_EnFCont_Msk (0x1UL << TPI_FFCR_EnFCont_Pos) /*!< TPI FFCR: EnFCont Mask */ /* TPI TRIGGER Register Definitions */ #define TPI_TRIGGER_TRIGGER_Pos 0 /*!< TPI TRIGGER: TRIGGER Position */ #define TPI_TRIGGER_TRIGGER_Msk (0x1UL /*<< TPI_TRIGGER_TRIGGER_Pos*/) /*!< TPI TRIGGER: TRIGGER Mask */ /* TPI Integration ETM Data Register Definitions (FIFO0) */ #define TPI_FIFO0_ITM_ATVALID_Pos 29 /*!< TPI FIFO0: ITM_ATVALID Position */ #define TPI_FIFO0_ITM_ATVALID_Msk (0x3UL << TPI_FIFO0_ITM_ATVALID_Pos) /*!< TPI FIFO0: ITM_ATVALID Mask */ #define TPI_FIFO0_ITM_bytecount_Pos 27 /*!< TPI FIFO0: ITM_bytecount Position */ #define TPI_FIFO0_ITM_bytecount_Msk (0x3UL << TPI_FIFO0_ITM_bytecount_Pos) /*!< TPI FIFO0: ITM_bytecount Mask */ #define TPI_FIFO0_ETM_ATVALID_Pos 26 /*!< TPI FIFO0: ETM_ATVALID Position */ #define TPI_FIFO0_ETM_ATVALID_Msk (0x3UL << TPI_FIFO0_ETM_ATVALID_Pos) /*!< TPI FIFO0: ETM_ATVALID Mask */ #define TPI_FIFO0_ETM_bytecount_Pos 24 /*!< TPI FIFO0: ETM_bytecount Position */ #define TPI_FIFO0_ETM_bytecount_Msk (0x3UL << TPI_FIFO0_ETM_bytecount_Pos) /*!< TPI FIFO0: ETM_bytecount Mask */ #define TPI_FIFO0_ETM2_Pos 16 /*!< TPI FIFO0: ETM2 Position */ #define TPI_FIFO0_ETM2_Msk (0xFFUL << TPI_FIFO0_ETM2_Pos) /*!< TPI FIFO0: ETM2 Mask */ #define TPI_FIFO0_ETM1_Pos 8 /*!< TPI FIFO0: ETM1 Position */ #define TPI_FIFO0_ETM1_Msk (0xFFUL << TPI_FIFO0_ETM1_Pos) /*!< TPI FIFO0: ETM1 Mask */ #define TPI_FIFO0_ETM0_Pos 0 /*!< TPI FIFO0: ETM0 Position */ #define TPI_FIFO0_ETM0_Msk (0xFFUL /*<< TPI_FIFO0_ETM0_Pos*/) /*!< TPI FIFO0: ETM0 Mask */ /* TPI ITATBCTR2 Register Definitions */ #define TPI_ITATBCTR2_ATREADY_Pos 0 /*!< TPI ITATBCTR2: ATREADY Position */ #define TPI_ITATBCTR2_ATREADY_Msk (0x1UL /*<< TPI_ITATBCTR2_ATREADY_Pos*/) /*!< TPI ITATBCTR2: ATREADY Mask */ /* TPI Integration ITM Data Register Definitions (FIFO1) */ #define TPI_FIFO1_ITM_ATVALID_Pos 29 /*!< TPI FIFO1: ITM_ATVALID Position */ #define TPI_FIFO1_ITM_ATVALID_Msk (0x3UL << TPI_FIFO1_ITM_ATVALID_Pos) /*!< TPI FIFO1: ITM_ATVALID Mask */ #define TPI_FIFO1_ITM_bytecount_Pos 27 /*!< TPI FIFO1: ITM_bytecount Position */ #define TPI_FIFO1_ITM_bytecount_Msk (0x3UL << TPI_FIFO1_ITM_bytecount_Pos) /*!< TPI FIFO1: ITM_bytecount Mask */ #define TPI_FIFO1_ETM_ATVALID_Pos 26 /*!< TPI FIFO1: ETM_ATVALID Position */ #define TPI_FIFO1_ETM_ATVALID_Msk (0x3UL << TPI_FIFO1_ETM_ATVALID_Pos) /*!< TPI FIFO1: ETM_ATVALID Mask */ #define TPI_FIFO1_ETM_bytecount_Pos 24 /*!< TPI FIFO1: ETM_bytecount Position */ #define TPI_FIFO1_ETM_bytecount_Msk (0x3UL << TPI_FIFO1_ETM_bytecount_Pos) /*!< TPI FIFO1: ETM_bytecount Mask */ #define TPI_FIFO1_ITM2_Pos 16 /*!< TPI FIFO1: ITM2 Position */ #define TPI_FIFO1_ITM2_Msk (0xFFUL << TPI_FIFO1_ITM2_Pos) /*!< TPI FIFO1: ITM2 Mask */ #define TPI_FIFO1_ITM1_Pos 8 /*!< TPI FIFO1: ITM1 Position */ #define TPI_FIFO1_ITM1_Msk (0xFFUL << TPI_FIFO1_ITM1_Pos) /*!< TPI FIFO1: ITM1 Mask */ #define TPI_FIFO1_ITM0_Pos 0 /*!< TPI FIFO1: ITM0 Position */ #define TPI_FIFO1_ITM0_Msk (0xFFUL /*<< TPI_FIFO1_ITM0_Pos*/) /*!< TPI FIFO1: ITM0 Mask */ /* TPI ITATBCTR0 Register Definitions */ #define TPI_ITATBCTR0_ATREADY_Pos 0 /*!< TPI ITATBCTR0: ATREADY Position */ #define TPI_ITATBCTR0_ATREADY_Msk (0x1UL /*<< TPI_ITATBCTR0_ATREADY_Pos*/) /*!< TPI ITATBCTR0: ATREADY Mask */ /* TPI Integration Mode Control Register Definitions */ #define TPI_ITCTRL_Mode_Pos 0 /*!< TPI ITCTRL: Mode Position */ #define TPI_ITCTRL_Mode_Msk (0x1UL /*<< TPI_ITCTRL_Mode_Pos*/) /*!< TPI ITCTRL: Mode Mask */ /* TPI DEVID Register Definitions */ #define TPI_DEVID_NRZVALID_Pos 11 /*!< TPI DEVID: NRZVALID Position */ #define TPI_DEVID_NRZVALID_Msk (0x1UL << TPI_DEVID_NRZVALID_Pos) /*!< TPI DEVID: NRZVALID Mask */ #define TPI_DEVID_MANCVALID_Pos 10 /*!< TPI DEVID: MANCVALID Position */ #define TPI_DEVID_MANCVALID_Msk (0x1UL << TPI_DEVID_MANCVALID_Pos) /*!< TPI DEVID: MANCVALID Mask */ #define TPI_DEVID_PTINVALID_Pos 9 /*!< TPI DEVID: PTINVALID Position */ #define TPI_DEVID_PTINVALID_Msk (0x1UL << TPI_DEVID_PTINVALID_Pos) /*!< TPI DEVID: PTINVALID Mask */ #define TPI_DEVID_MinBufSz_Pos 6 /*!< TPI DEVID: MinBufSz Position */ #define TPI_DEVID_MinBufSz_Msk (0x7UL << TPI_DEVID_MinBufSz_Pos) /*!< TPI DEVID: MinBufSz Mask */ #define TPI_DEVID_AsynClkIn_Pos 5 /*!< TPI DEVID: AsynClkIn Position */ #define TPI_DEVID_AsynClkIn_Msk (0x1UL << TPI_DEVID_AsynClkIn_Pos) /*!< TPI DEVID: AsynClkIn Mask */ #define TPI_DEVID_NrTraceInput_Pos 0 /*!< TPI DEVID: NrTraceInput Position */ #define TPI_DEVID_NrTraceInput_Msk (0x1FUL /*<< TPI_DEVID_NrTraceInput_Pos*/) /*!< TPI DEVID: NrTraceInput Mask */ /* TPI DEVTYPE Register Definitions */ #define TPI_DEVTYPE_MajorType_Pos 4 /*!< TPI DEVTYPE: MajorType Position */ #define TPI_DEVTYPE_MajorType_Msk (0xFUL << TPI_DEVTYPE_MajorType_Pos) /*!< TPI DEVTYPE: MajorType Mask */ #define TPI_DEVTYPE_SubType_Pos 0 /*!< TPI DEVTYPE: SubType Position */ #define TPI_DEVTYPE_SubType_Msk (0xFUL /*<< TPI_DEVTYPE_SubType_Pos*/) /*!< TPI DEVTYPE: SubType Mask */ /*@}*/ /* end of group CMSIS_TPI */ #if (__MPU_PRESENT == 1) /** \ingroup CMSIS_core_register \defgroup CMSIS_MPU Memory Protection Unit (MPU) \brief Type definitions for the Memory Protection Unit (MPU) @{ */ /** \brief Structure type to access the Memory Protection Unit (MPU). */ typedef struct { __I uint32_t TYPE; /*!< Offset: 0x000 (R/ ) MPU Type Register */ __IO uint32_t CTRL; /*!< Offset: 0x004 (R/W) MPU Control Register */ __IO uint32_t RNR; /*!< Offset: 0x008 (R/W) MPU Region RNRber Register */ __IO uint32_t RBAR; /*!< Offset: 0x00C (R/W) MPU Region Base Address Register */ __IO uint32_t RASR; /*!< Offset: 0x010 (R/W) MPU Region Attribute and Size Register */ __IO uint32_t RBAR_A1; /*!< Offset: 0x014 (R/W) MPU Alias 1 Region Base Address Register */ __IO uint32_t RASR_A1; /*!< Offset: 0x018 (R/W) MPU Alias 1 Region Attribute and Size Register */ __IO uint32_t RBAR_A2; /*!< Offset: 0x01C (R/W) MPU Alias 2 Region Base Address Register */ __IO uint32_t RASR_A2; /*!< Offset: 0x020 (R/W) MPU Alias 2 Region Attribute and Size Register */ __IO uint32_t RBAR_A3; /*!< Offset: 0x024 (R/W) MPU Alias 3 Region Base Address Register */ __IO uint32_t RASR_A3; /*!< Offset: 0x028 (R/W) MPU Alias 3 Region Attribute and Size Register */ } MPU_Type; /* MPU Type Register */ #define MPU_TYPE_IREGION_Pos 16 /*!< MPU TYPE: IREGION Position */ #define MPU_TYPE_IREGION_Msk (0xFFUL << MPU_TYPE_IREGION_Pos) /*!< MPU TYPE: IREGION Mask */ #define MPU_TYPE_DREGION_Pos 8 /*!< MPU TYPE: DREGION Position */ #define MPU_TYPE_DREGION_Msk (0xFFUL << MPU_TYPE_DREGION_Pos) /*!< MPU TYPE: DREGION Mask */ #define MPU_TYPE_SEPARATE_Pos 0 /*!< MPU TYPE: SEPARATE Position */ #define MPU_TYPE_SEPARATE_Msk (1UL /*<< MPU_TYPE_SEPARATE_Pos*/) /*!< MPU TYPE: SEPARATE Mask */ /* MPU Control Register */ #define MPU_CTRL_PRIVDEFENA_Pos 2 /*!< MPU CTRL: PRIVDEFENA Position */ #define MPU_CTRL_PRIVDEFENA_Msk (1UL << MPU_CTRL_PRIVDEFENA_Pos) /*!< MPU CTRL: PRIVDEFENA Mask */ #define MPU_CTRL_HFNMIENA_Pos 1 /*!< MPU CTRL: HFNMIENA Position */ #define MPU_CTRL_HFNMIENA_Msk (1UL << MPU_CTRL_HFNMIENA_Pos) /*!< MPU CTRL: HFNMIENA Mask */ #define MPU_CTRL_ENABLE_Pos 0 /*!< MPU CTRL: ENABLE Position */ #define MPU_CTRL_ENABLE_Msk (1UL /*<< MPU_CTRL_ENABLE_Pos*/) /*!< MPU CTRL: ENABLE Mask */ /* MPU Region Number Register */ #define MPU_RNR_REGION_Pos 0 /*!< MPU RNR: REGION Position */ #define MPU_RNR_REGION_Msk (0xFFUL /*<< MPU_RNR_REGION_Pos*/) /*!< MPU RNR: REGION Mask */ /* MPU Region Base Address Register */ #define MPU_RBAR_ADDR_Pos 5 /*!< MPU RBAR: ADDR Position */ #define MPU_RBAR_ADDR_Msk (0x7FFFFFFUL << MPU_RBAR_ADDR_Pos) /*!< MPU RBAR: ADDR Mask */ #define MPU_RBAR_VALID_Pos 4 /*!< MPU RBAR: VALID Position */ #define MPU_RBAR_VALID_Msk (1UL << MPU_RBAR_VALID_Pos) /*!< MPU RBAR: VALID Mask */ #define MPU_RBAR_REGION_Pos 0 /*!< MPU RBAR: REGION Position */ #define MPU_RBAR_REGION_Msk (0xFUL /*<< MPU_RBAR_REGION_Pos*/) /*!< MPU RBAR: REGION Mask */ /* MPU Region Attribute and Size Register */ #define MPU_RASR_ATTRS_Pos 16 /*!< MPU RASR: MPU Region Attribute field Position */ #define MPU_RASR_ATTRS_Msk (0xFFFFUL << MPU_RASR_ATTRS_Pos) /*!< MPU RASR: MPU Region Attribute field Mask */ #define MPU_RASR_XN_Pos 28 /*!< MPU RASR: ATTRS.XN Position */ #define MPU_RASR_XN_Msk (1UL << MPU_RASR_XN_Pos) /*!< MPU RASR: ATTRS.XN Mask */ #define MPU_RASR_AP_Pos 24 /*!< MPU RASR: ATTRS.AP Position */ #define MPU_RASR_AP_Msk (0x7UL << MPU_RASR_AP_Pos) /*!< MPU RASR: ATTRS.AP Mask */ #define MPU_RASR_TEX_Pos 19 /*!< MPU RASR: ATTRS.TEX Position */ #define MPU_RASR_TEX_Msk (0x7UL << MPU_RASR_TEX_Pos) /*!< MPU RASR: ATTRS.TEX Mask */ #define MPU_RASR_S_Pos 18 /*!< MPU RASR: ATTRS.S Position */ #define MPU_RASR_S_Msk (1UL << MPU_RASR_S_Pos) /*!< MPU RASR: ATTRS.S Mask */ #define MPU_RASR_C_Pos 17 /*!< MPU RASR: ATTRS.C Position */ #define MPU_RASR_C_Msk (1UL << MPU_RASR_C_Pos) /*!< MPU RASR: ATTRS.C Mask */ #define MPU_RASR_B_Pos 16 /*!< MPU RASR: ATTRS.B Position */ #define MPU_RASR_B_Msk (1UL << MPU_RASR_B_Pos) /*!< MPU RASR: ATTRS.B Mask */ #define MPU_RASR_SRD_Pos 8 /*!< MPU RASR: Sub-Region Disable Position */ #define MPU_RASR_SRD_Msk (0xFFUL << MPU_RASR_SRD_Pos) /*!< MPU RASR: Sub-Region Disable Mask */ #define MPU_RASR_SIZE_Pos 1 /*!< MPU RASR: Region Size Field Position */ #define MPU_RASR_SIZE_Msk (0x1FUL << MPU_RASR_SIZE_Pos) /*!< MPU RASR: Region Size Field Mask */ #define MPU_RASR_ENABLE_Pos 0 /*!< MPU RASR: Region enable bit Position */ #define MPU_RASR_ENABLE_Msk (1UL /*<< MPU_RASR_ENABLE_Pos*/) /*!< MPU RASR: Region enable bit Disable Mask */ /*@} end of group CMSIS_MPU */ #endif /** \ingroup CMSIS_core_register \defgroup CMSIS_CoreDebug Core Debug Registers (CoreDebug) \brief Type definitions for the Core Debug Registers @{ */ /** \brief Structure type to access the Core Debug Register (CoreDebug). */ typedef struct { __IO uint32_t DHCSR; /*!< Offset: 0x000 (R/W) Debug Halting Control and Status Register */ __O uint32_t DCRSR; /*!< Offset: 0x004 ( /W) Debug Core Register Selector Register */ __IO uint32_t DCRDR; /*!< Offset: 0x008 (R/W) Debug Core Register Data Register */ __IO uint32_t DEMCR; /*!< Offset: 0x00C (R/W) Debug Exception and Monitor Control Register */ } CoreDebug_Type; /* Debug Halting Control and Status Register */ #define CoreDebug_DHCSR_DBGKEY_Pos 16 /*!< CoreDebug DHCSR: DBGKEY Position */ #define CoreDebug_DHCSR_DBGKEY_Msk (0xFFFFUL << CoreDebug_DHCSR_DBGKEY_Pos) /*!< CoreDebug DHCSR: DBGKEY Mask */ #define CoreDebug_DHCSR_S_RESET_ST_Pos 25 /*!< CoreDebug DHCSR: S_RESET_ST Position */ #define CoreDebug_DHCSR_S_RESET_ST_Msk (1UL << CoreDebug_DHCSR_S_RESET_ST_Pos) /*!< CoreDebug DHCSR: S_RESET_ST Mask */ #define CoreDebug_DHCSR_S_RETIRE_ST_Pos 24 /*!< CoreDebug DHCSR: S_RETIRE_ST Position */ #define CoreDebug_DHCSR_S_RETIRE_ST_Msk (1UL << CoreDebug_DHCSR_S_RETIRE_ST_Pos) /*!< CoreDebug DHCSR: S_RETIRE_ST Mask */ #define CoreDebug_DHCSR_S_LOCKUP_Pos 19 /*!< CoreDebug DHCSR: S_LOCKUP Position */ #define CoreDebug_DHCSR_S_LOCKUP_Msk (1UL << CoreDebug_DHCSR_S_LOCKUP_Pos) /*!< CoreDebug DHCSR: S_LOCKUP Mask */ #define CoreDebug_DHCSR_S_SLEEP_Pos 18 /*!< CoreDebug DHCSR: S_SLEEP Position */ #define CoreDebug_DHCSR_S_SLEEP_Msk (1UL << CoreDebug_DHCSR_S_SLEEP_Pos) /*!< CoreDebug DHCSR: S_SLEEP Mask */ #define CoreDebug_DHCSR_S_HALT_Pos 17 /*!< CoreDebug DHCSR: S_HALT Position */ #define CoreDebug_DHCSR_S_HALT_Msk (1UL << CoreDebug_DHCSR_S_HALT_Pos) /*!< CoreDebug DHCSR: S_HALT Mask */ #define CoreDebug_DHCSR_S_REGRDY_Pos 16 /*!< CoreDebug DHCSR: S_REGRDY Position */ #define CoreDebug_DHCSR_S_REGRDY_Msk (1UL << CoreDebug_DHCSR_S_REGRDY_Pos) /*!< CoreDebug DHCSR: S_REGRDY Mask */ #define CoreDebug_DHCSR_C_SNAPSTALL_Pos 5 /*!< CoreDebug DHCSR: C_SNAPSTALL Position */ #define CoreDebug_DHCSR_C_SNAPSTALL_Msk (1UL << CoreDebug_DHCSR_C_SNAPSTALL_Pos) /*!< CoreDebug DHCSR: C_SNAPSTALL Mask */ #define CoreDebug_DHCSR_C_MASKINTS_Pos 3 /*!< CoreDebug DHCSR: C_MASKINTS Position */ #define CoreDebug_DHCSR_C_MASKINTS_Msk (1UL << CoreDebug_DHCSR_C_MASKINTS_Pos) /*!< CoreDebug DHCSR: C_MASKINTS Mask */ #define CoreDebug_DHCSR_C_STEP_Pos 2 /*!< CoreDebug DHCSR: C_STEP Position */ #define CoreDebug_DHCSR_C_STEP_Msk (1UL << CoreDebug_DHCSR_C_STEP_Pos) /*!< CoreDebug DHCSR: C_STEP Mask */ #define CoreDebug_DHCSR_C_HALT_Pos 1 /*!< CoreDebug DHCSR: C_HALT Position */ #define CoreDebug_DHCSR_C_HALT_Msk (1UL << CoreDebug_DHCSR_C_HALT_Pos) /*!< CoreDebug DHCSR: C_HALT Mask */ #define CoreDebug_DHCSR_C_DEBUGEN_Pos 0 /*!< CoreDebug DHCSR: C_DEBUGEN Position */ #define CoreDebug_DHCSR_C_DEBUGEN_Msk (1UL /*<< CoreDebug_DHCSR_C_DEBUGEN_Pos*/) /*!< CoreDebug DHCSR: C_DEBUGEN Mask */ /* Debug Core Register Selector Register */ #define CoreDebug_DCRSR_REGWnR_Pos 16 /*!< CoreDebug DCRSR: REGWnR Position */ #define CoreDebug_DCRSR_REGWnR_Msk (1UL << CoreDebug_DCRSR_REGWnR_Pos) /*!< CoreDebug DCRSR: REGWnR Mask */ #define CoreDebug_DCRSR_REGSEL_Pos 0 /*!< CoreDebug DCRSR: REGSEL Position */ #define CoreDebug_DCRSR_REGSEL_Msk (0x1FUL /*<< CoreDebug_DCRSR_REGSEL_Pos*/) /*!< CoreDebug DCRSR: REGSEL Mask */ /* Debug Exception and Monitor Control Register */ #define CoreDebug_DEMCR_TRCENA_Pos 24 /*!< CoreDebug DEMCR: TRCENA Position */ #define CoreDebug_DEMCR_TRCENA_Msk (1UL << CoreDebug_DEMCR_TRCENA_Pos) /*!< CoreDebug DEMCR: TRCENA Mask */ #define CoreDebug_DEMCR_MON_REQ_Pos 19 /*!< CoreDebug DEMCR: MON_REQ Position */ #define CoreDebug_DEMCR_MON_REQ_Msk (1UL << CoreDebug_DEMCR_MON_REQ_Pos) /*!< CoreDebug DEMCR: MON_REQ Mask */ #define CoreDebug_DEMCR_MON_STEP_Pos 18 /*!< CoreDebug DEMCR: MON_STEP Position */ #define CoreDebug_DEMCR_MON_STEP_Msk (1UL << CoreDebug_DEMCR_MON_STEP_Pos) /*!< CoreDebug DEMCR: MON_STEP Mask */ #define CoreDebug_DEMCR_MON_PEND_Pos 17 /*!< CoreDebug DEMCR: MON_PEND Position */ #define CoreDebug_DEMCR_MON_PEND_Msk (1UL << CoreDebug_DEMCR_MON_PEND_Pos) /*!< CoreDebug DEMCR: MON_PEND Mask */ #define CoreDebug_DEMCR_MON_EN_Pos 16 /*!< CoreDebug DEMCR: MON_EN Position */ #define CoreDebug_DEMCR_MON_EN_Msk (1UL << CoreDebug_DEMCR_MON_EN_Pos) /*!< CoreDebug DEMCR: MON_EN Mask */ #define CoreDebug_DEMCR_VC_HARDERR_Pos 10 /*!< CoreDebug DEMCR: VC_HARDERR Position */ #define CoreDebug_DEMCR_VC_HARDERR_Msk (1UL << CoreDebug_DEMCR_VC_HARDERR_Pos) /*!< CoreDebug DEMCR: VC_HARDERR Mask */ #define CoreDebug_DEMCR_VC_INTERR_Pos 9 /*!< CoreDebug DEMCR: VC_INTERR Position */ #define CoreDebug_DEMCR_VC_INTERR_Msk (1UL << CoreDebug_DEMCR_VC_INTERR_Pos) /*!< CoreDebug DEMCR: VC_INTERR Mask */ #define CoreDebug_DEMCR_VC_BUSERR_Pos 8 /*!< CoreDebug DEMCR: VC_BUSERR Position */ #define CoreDebug_DEMCR_VC_BUSERR_Msk (1UL << CoreDebug_DEMCR_VC_BUSERR_Pos) /*!< CoreDebug DEMCR: VC_BUSERR Mask */ #define CoreDebug_DEMCR_VC_STATERR_Pos 7 /*!< CoreDebug DEMCR: VC_STATERR Position */ #define CoreDebug_DEMCR_VC_STATERR_Msk (1UL << CoreDebug_DEMCR_VC_STATERR_Pos) /*!< CoreDebug DEMCR: VC_STATERR Mask */ #define CoreDebug_DEMCR_VC_CHKERR_Pos 6 /*!< CoreDebug DEMCR: VC_CHKERR Position */ #define CoreDebug_DEMCR_VC_CHKERR_Msk (1UL << CoreDebug_DEMCR_VC_CHKERR_Pos) /*!< CoreDebug DEMCR: VC_CHKERR Mask */ #define CoreDebug_DEMCR_VC_NOCPERR_Pos 5 /*!< CoreDebug DEMCR: VC_NOCPERR Position */ #define CoreDebug_DEMCR_VC_NOCPERR_Msk (1UL << CoreDebug_DEMCR_VC_NOCPERR_Pos) /*!< CoreDebug DEMCR: VC_NOCPERR Mask */ #define CoreDebug_DEMCR_VC_MMERR_Pos 4 /*!< CoreDebug DEMCR: VC_MMERR Position */ #define CoreDebug_DEMCR_VC_MMERR_Msk (1UL << CoreDebug_DEMCR_VC_MMERR_Pos) /*!< CoreDebug DEMCR: VC_MMERR Mask */ #define CoreDebug_DEMCR_VC_CORERESET_Pos 0 /*!< CoreDebug DEMCR: VC_CORERESET Position */ #define CoreDebug_DEMCR_VC_CORERESET_Msk (1UL /*<< CoreDebug_DEMCR_VC_CORERESET_Pos*/) /*!< CoreDebug DEMCR: VC_CORERESET Mask */ /*@} end of group CMSIS_CoreDebug */ /** \ingroup CMSIS_core_register \defgroup CMSIS_core_base Core Definitions \brief Definitions for base addresses, unions, and structures. @{ */ /* Memory mapping of Cortex-M3 Hardware */ #define SCS_BASE (0xE000E000UL) /*!< System Control Space Base Address */ #define ITM_BASE (0xE0000000UL) /*!< ITM Base Address */ #define DWT_BASE (0xE0001000UL) /*!< DWT Base Address */ #define TPI_BASE (0xE0040000UL) /*!< TPI Base Address */ #define CoreDebug_BASE (0xE000EDF0UL) /*!< Core Debug Base Address */ #define SysTick_BASE (SCS_BASE + 0x0010UL) /*!< SysTick Base Address */ #define NVIC_BASE (SCS_BASE + 0x0100UL) /*!< NVIC Base Address */ #define SCB_BASE (SCS_BASE + 0x0D00UL) /*!< System Control Block Base Address */ #define SCnSCB ((SCnSCB_Type *) SCS_BASE ) /*!< System control Register not in SCB */ #define SCB ((SCB_Type *) SCB_BASE ) /*!< SCB configuration struct */ #define SysTick ((SysTick_Type *) SysTick_BASE ) /*!< SysTick configuration struct */ #define NVIC ((NVIC_Type *) NVIC_BASE ) /*!< NVIC configuration struct */ #define ITM ((ITM_Type *) ITM_BASE ) /*!< ITM configuration struct */ #define DWT ((DWT_Type *) DWT_BASE ) /*!< DWT configuration struct */ #define TPI ((TPI_Type *) TPI_BASE ) /*!< TPI configuration struct */ #define CoreDebug ((CoreDebug_Type *) CoreDebug_BASE) /*!< Core Debug configuration struct */ #if (__MPU_PRESENT == 1) #define MPU_BASE (SCS_BASE + 0x0D90UL) /*!< Memory Protection Unit */ #define MPU ((MPU_Type *) MPU_BASE ) /*!< Memory Protection Unit */ #endif /*@} */ /******************************************************************************* * Hardware Abstraction Layer Core Function Interface contains: - Core NVIC Functions - Core SysTick Functions - Core Debug Functions - Core Register Access Functions ******************************************************************************/ /** \defgroup CMSIS_Core_FunctionInterface Functions and Instructions Reference */ /* ########################## NVIC functions #################################### */ /** \ingroup CMSIS_Core_FunctionInterface \defgroup CMSIS_Core_NVICFunctions NVIC Functions \brief Functions that manage interrupts and exceptions via the NVIC. @{ */ /** \brief Set Priority Grouping The function sets the priority grouping field using the required unlock sequence. The parameter PriorityGroup is assigned to the field SCB->AIRCR [10:8] PRIGROUP field. Only values from 0..7 are used. In case of a conflict between priority grouping and available priority bits (__NVIC_PRIO_BITS), the smallest possible priority group is set. \param [in] PriorityGroup Priority grouping field. */ __STATIC_INLINE void NVIC_SetPriorityGrouping(uint32_t PriorityGroup) { uint32_t reg_value; uint32_t PriorityGroupTmp = (PriorityGroup & (uint32_t)0x07UL); /* only values 0..7 are used */ reg_value = SCB->AIRCR; /* read old register configuration */ reg_value &= ~((uint32_t)(SCB_AIRCR_VECTKEY_Msk | SCB_AIRCR_PRIGROUP_Msk)); /* clear bits to change */ reg_value = (reg_value | ((uint32_t)0x5FAUL << SCB_AIRCR_VECTKEY_Pos) | (PriorityGroupTmp << 8) ); /* Insert write key and priorty group */ SCB->AIRCR = reg_value; } /** \brief Get Priority Grouping The function reads the priority grouping field from the NVIC Interrupt Controller. \return Priority grouping field (SCB->AIRCR [10:8] PRIGROUP field). */ __STATIC_INLINE uint32_t NVIC_GetPriorityGrouping(void) { return ((uint32_t)((SCB->AIRCR & SCB_AIRCR_PRIGROUP_Msk) >> SCB_AIRCR_PRIGROUP_Pos)); } /** \brief Enable External Interrupt The function enables a device-specific interrupt in the NVIC interrupt controller. \param [in] IRQn External interrupt number. Value cannot be negative. */ __STATIC_INLINE void NVIC_EnableIRQ(IRQn_Type IRQn) { NVIC->ISER[(((uint32_t)(int32_t)IRQn) >> 5UL)] = (uint32_t)(1UL << (((uint32_t)(int32_t)IRQn) & 0x1FUL)); } /** \brief Disable External Interrupt The function disables a device-specific interrupt in the NVIC interrupt controller. \param [in] IRQn External interrupt number. Value cannot be negative. */ __STATIC_INLINE void NVIC_DisableIRQ(IRQn_Type IRQn) { NVIC->ICER[(((uint32_t)(int32_t)IRQn) >> 5UL)] = (uint32_t)(1UL << (((uint32_t)(int32_t)IRQn) & 0x1FUL)); } /** \brief Get Pending Interrupt The function reads the pending register in the NVIC and returns the pending bit for the specified interrupt. \param [in] IRQn Interrupt number. \return 0 Interrupt status is not pending. \return 1 Interrupt status is pending. */ __STATIC_INLINE uint32_t NVIC_GetPendingIRQ(IRQn_Type IRQn) { return((uint32_t)(((NVIC->ISPR[(((uint32_t)(int32_t)IRQn) >> 5UL)] & (1UL << (((uint32_t)(int32_t)IRQn) & 0x1FUL))) != 0UL) ? 1UL : 0UL)); } /** \brief Set Pending Interrupt The function sets the pending bit of an external interrupt. \param [in] IRQn Interrupt number. Value cannot be negative. */ __STATIC_INLINE void NVIC_SetPendingIRQ(IRQn_Type IRQn) { NVIC->ISPR[(((uint32_t)(int32_t)IRQn) >> 5UL)] = (uint32_t)(1UL << (((uint32_t)(int32_t)IRQn) & 0x1FUL)); } /** \brief Clear Pending Interrupt The function clears the pending bit of an external interrupt. \param [in] IRQn External interrupt number. Value cannot be negative. */ __STATIC_INLINE void NVIC_ClearPendingIRQ(IRQn_Type IRQn) { NVIC->ICPR[(((uint32_t)(int32_t)IRQn) >> 5UL)] = (uint32_t)(1UL << (((uint32_t)(int32_t)IRQn) & 0x1FUL)); } /** \brief Get Active Interrupt The function reads the active register in NVIC and returns the active bit. \param [in] IRQn Interrupt number. \return 0 Interrupt status is not active. \return 1 Interrupt status is active. */ __STATIC_INLINE uint32_t NVIC_GetActive(IRQn_Type IRQn) { return((uint32_t)(((NVIC->IABR[(((uint32_t)(int32_t)IRQn) >> 5UL)] & (1UL << (((uint32_t)(int32_t)IRQn) & 0x1FUL))) != 0UL) ? 1UL : 0UL)); } /** \brief Set Interrupt Priority The function sets the priority of an interrupt. \note The priority cannot be set for every core interrupt. \param [in] IRQn Interrupt number. \param [in] priority Priority to set. */ __STATIC_INLINE void NVIC_SetPriority(IRQn_Type IRQn, uint32_t priority) { if((int32_t)IRQn < 0) { SCB->SHP[(((uint32_t)(int32_t)IRQn) & 0xFUL)-4UL] = (uint8_t)((priority << (8 - __NVIC_PRIO_BITS)) & (uint32_t)0xFFUL); } else { NVIC->IP[((uint32_t)(int32_t)IRQn)] = (uint8_t)((priority << (8 - __NVIC_PRIO_BITS)) & (uint32_t)0xFFUL); } } /** \brief Get Interrupt Priority The function reads the priority of an interrupt. The interrupt number can be positive to specify an external (device specific) interrupt, or negative to specify an internal (core) interrupt. \param [in] IRQn Interrupt number. \return Interrupt Priority. Value is aligned automatically to the implemented priority bits of the microcontroller. */ __STATIC_INLINE uint32_t NVIC_GetPriority(IRQn_Type IRQn) { if((int32_t)IRQn < 0) { return(((uint32_t)SCB->SHP[(((uint32_t)(int32_t)IRQn) & 0xFUL)-4UL] >> (8 - __NVIC_PRIO_BITS))); } else { return(((uint32_t)NVIC->IP[((uint32_t)(int32_t)IRQn)] >> (8 - __NVIC_PRIO_BITS))); } } /** \brief Encode Priority The function encodes the priority for an interrupt with the given priority group, preemptive priority value, and subpriority value. In case of a conflict between priority grouping and available priority bits (__NVIC_PRIO_BITS), the smallest possible priority group is set. \param [in] PriorityGroup Used priority group. \param [in] PreemptPriority Preemptive priority value (starting from 0). \param [in] SubPriority Subpriority value (starting from 0). \return Encoded priority. Value can be used in the function \ref NVIC_SetPriority(). */ __STATIC_INLINE uint32_t NVIC_EncodePriority (uint32_t PriorityGroup, uint32_t PreemptPriority, uint32_t SubPriority) { uint32_t PriorityGroupTmp = (PriorityGroup & (uint32_t)0x07UL); /* only values 0..7 are used */ uint32_t PreemptPriorityBits; uint32_t SubPriorityBits; PreemptPriorityBits = ((7UL - PriorityGroupTmp) > (uint32_t)(__NVIC_PRIO_BITS)) ? (uint32_t)(__NVIC_PRIO_BITS) : (uint32_t)(7UL - PriorityGroupTmp); SubPriorityBits = ((PriorityGroupTmp + (uint32_t)(__NVIC_PRIO_BITS)) < (uint32_t)7UL) ? (uint32_t)0UL : (uint32_t)((PriorityGroupTmp - 7UL) + (uint32_t)(__NVIC_PRIO_BITS)); return ( ((PreemptPriority & (uint32_t)((1UL << (PreemptPriorityBits)) - 1UL)) << SubPriorityBits) | ((SubPriority & (uint32_t)((1UL << (SubPriorityBits )) - 1UL))) ); } /** \brief Decode Priority The function decodes an interrupt priority value with a given priority group to preemptive priority value and subpriority value. In case of a conflict between priority grouping and available priority bits (__NVIC_PRIO_BITS) the smallest possible priority group is set. \param [in] Priority Priority value, which can be retrieved with the function \ref NVIC_GetPriority(). \param [in] PriorityGroup Used priority group. \param [out] pPreemptPriority Preemptive priority value (starting from 0). \param [out] pSubPriority Subpriority value (starting from 0). */ __STATIC_INLINE void NVIC_DecodePriority (uint32_t Priority, uint32_t PriorityGroup, uint32_t* pPreemptPriority, uint32_t* pSubPriority) { uint32_t PriorityGroupTmp = (PriorityGroup & (uint32_t)0x07UL); /* only values 0..7 are used */ uint32_t PreemptPriorityBits; uint32_t SubPriorityBits; PreemptPriorityBits = ((7UL - PriorityGroupTmp) > (uint32_t)(__NVIC_PRIO_BITS)) ? (uint32_t)(__NVIC_PRIO_BITS) : (uint32_t)(7UL - PriorityGroupTmp); SubPriorityBits = ((PriorityGroupTmp + (uint32_t)(__NVIC_PRIO_BITS)) < (uint32_t)7UL) ? (uint32_t)0UL : (uint32_t)((PriorityGroupTmp - 7UL) + (uint32_t)(__NVIC_PRIO_BITS)); *pPreemptPriority = (Priority >> SubPriorityBits) & (uint32_t)((1UL << (PreemptPriorityBits)) - 1UL); *pSubPriority = (Priority ) & (uint32_t)((1UL << (SubPriorityBits )) - 1UL); } /** \brief System Reset The function initiates a system reset request to reset the MCU. */ __STATIC_INLINE void NVIC_SystemReset(void) { __DSB(); /* Ensure all outstanding memory accesses included buffered write are completed before reset */ SCB->AIRCR = (uint32_t)((0x5FAUL << SCB_AIRCR_VECTKEY_Pos) | (SCB->AIRCR & SCB_AIRCR_PRIGROUP_Msk) | SCB_AIRCR_SYSRESETREQ_Msk ); /* Keep priority group unchanged */ __DSB(); /* Ensure completion of memory access */ while(1) { __NOP(); } /* wait until reset */ } /*@} end of CMSIS_Core_NVICFunctions */ /* ################################## SysTick function ############################################ */ /** \ingroup CMSIS_Core_FunctionInterface \defgroup CMSIS_Core_SysTickFunctions SysTick Functions \brief Functions that configure the System. @{ */ #if (__Vendor_SysTickConfig == 0) /** \brief System Tick Configuration The function initializes the System Timer and its interrupt, and starts the System Tick Timer. Counter is in free running mode to generate periodic interrupts. \param [in] ticks Number of ticks between two interrupts. \return 0 Function succeeded. \return 1 Function failed. \note When the variable __Vendor_SysTickConfig is set to 1, then the function SysTick_Config is not included. In this case, the file device.h must contain a vendor-specific implementation of this function. */ __STATIC_INLINE uint32_t SysTick_Config(uint32_t ticks) { if ((ticks - 1UL) > SysTick_LOAD_RELOAD_Msk) { return (1UL); } /* Reload value impossible */ SysTick->LOAD = (uint32_t)(ticks - 1UL); /* set reload register */ NVIC_SetPriority (SysTick_IRQn, (1UL << __NVIC_PRIO_BITS) - 1UL); /* set Priority for Systick Interrupt */ SysTick->VAL = 0UL; /* Load the SysTick Counter Value */ SysTick->CTRL = SysTick_CTRL_CLKSOURCE_Msk | SysTick_CTRL_TICKINT_Msk | SysTick_CTRL_ENABLE_Msk; /* Enable SysTick IRQ and SysTick Timer */ return (0UL); /* Function successful */ } #endif /*@} end of CMSIS_Core_SysTickFunctions */ /* ##################################### Debug In/Output function ########################################### */ /** \ingroup CMSIS_Core_FunctionInterface \defgroup CMSIS_core_DebugFunctions ITM Functions \brief Functions that access the ITM debug interface. @{ */ extern volatile int32_t ITM_RxBuffer; /*!< External variable to receive characters. */ #define ITM_RXBUFFER_EMPTY 0x5AA55AA5 /*!< Value identifying \ref ITM_RxBuffer is ready for next character. */ /** \brief ITM Send Character The function transmits a character via the ITM channel 0, and \li Just returns when no debugger is connected that has booked the output. \li Is blocking when a debugger is connected, but the previous character sent has not been transmitted. \param [in] ch Character to transmit. \returns Character to transmit. */ __STATIC_INLINE uint32_t ITM_SendChar (uint32_t ch) { if (((ITM->TCR & ITM_TCR_ITMENA_Msk) != 0UL) && /* ITM enabled */ ((ITM->TER & 1UL ) != 0UL) ) /* ITM Port #0 enabled */ { while (ITM->PORT[0].u32 == 0UL) { __NOP(); } ITM->PORT[0].u8 = (uint8_t)ch; } return (ch); } /** \brief ITM Receive Character The function inputs a character via the external variable \ref ITM_RxBuffer. \return Received character. \return -1 No character pending. */ __STATIC_INLINE int32_t ITM_ReceiveChar (void) { int32_t ch = -1; /* no character available */ if (ITM_RxBuffer != ITM_RXBUFFER_EMPTY) { ch = ITM_RxBuffer; ITM_RxBuffer = ITM_RXBUFFER_EMPTY; /* ready for next character */ } return (ch); } /** \brief ITM Check Character The function checks whether a character is pending for reading in the variable \ref ITM_RxBuffer. \return 0 No character available. \return 1 Character available. */ __STATIC_INLINE int32_t ITM_CheckChar (void) { if (ITM_RxBuffer == ITM_RXBUFFER_EMPTY) { return (0); /* no character available */ } else { return (1); /* character available */ } } /*@} end of CMSIS_core_DebugFunctions */ #ifdef __cplusplus } #endif #endif /* __CORE_SC300_H_DEPENDANT */ #endif /* __CMSIS_GENERIC */ ================================================ FILE: Zelig/mbed/TARGET_NUCLEO_F411RE/hal_tick.h ================================================ /** ****************************************************************************** * @file hal_tick.h * @author MCD Application Team * @brief Initialization of HAL tick ****************************************************************************** * @attention * *

© COPYRIGHT(c) 2014 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. * ****************************************************************************** */ #ifndef __HAL_TICK_H #define __HAL_TICK_H #ifdef __cplusplus extern "C" { #endif #include "stm32f4xx.h" #include "cmsis_nvic.h" #define TIM_MST TIM5 #define TIM_MST_IRQ TIM5_IRQn #define TIM_MST_RCC __TIM5_CLK_ENABLE() #define TIM_MST_RESET_ON __TIM5_FORCE_RESET() #define TIM_MST_RESET_OFF __TIM5_RELEASE_RESET() #define HAL_TICK_DELAY (1000) // 1 ms #ifdef __cplusplus } #endif #endif // __HAL_TICK_H /************************ (C) COPYRIGHT STMicroelectronics *****END OF FILE****/ ================================================ FILE: Zelig/mbed/TARGET_NUCLEO_F411RE/stm32_hal_legacy.h ================================================ /** ****************************************************************************** * @file stm32_hal_legacy.h * @author MCD Application Team * @version V1.4.1 * @date 09-October-2015 * @brief This file contains aliases definition for the STM32Cube HAL constants * macros and functions maintained for legacy purpose. ****************************************************************************** * @attention * *

© COPYRIGHT(c) 2015 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. * ****************************************************************************** */ /* Define to prevent recursive inclusion -------------------------------------*/ #ifndef __STM32_HAL_LEGACY #define __STM32_HAL_LEGACY #ifdef __cplusplus extern "C" { #endif /* Includes ------------------------------------------------------------------*/ /* Exported types ------------------------------------------------------------*/ /* Exported constants --------------------------------------------------------*/ /** @defgroup HAL_AES_Aliased_Defines HAL CRYP Aliased Defines maintained for legacy purpose * @{ */ #define AES_FLAG_RDERR CRYP_FLAG_RDERR #define AES_FLAG_WRERR CRYP_FLAG_WRERR #define AES_CLEARFLAG_CCF CRYP_CLEARFLAG_CCF #define AES_CLEARFLAG_RDERR CRYP_CLEARFLAG_RDERR #define AES_CLEARFLAG_WRERR CRYP_CLEARFLAG_WRERR /** * @} */ /** @defgroup HAL_ADC_Aliased_Defines HAL ADC Aliased Defines maintained for legacy purpose * @{ */ #define ADC_RESOLUTION12b ADC_RESOLUTION_12B #define ADC_RESOLUTION10b ADC_RESOLUTION_10B #define ADC_RESOLUTION8b ADC_RESOLUTION_8B #define ADC_RESOLUTION6b ADC_RESOLUTION_6B #define OVR_DATA_OVERWRITTEN ADC_OVR_DATA_OVERWRITTEN #define OVR_DATA_PRESERVED ADC_OVR_DATA_PRESERVED #define EOC_SINGLE_CONV ADC_EOC_SINGLE_CONV #define EOC_SEQ_CONV ADC_EOC_SEQ_CONV #define EOC_SINGLE_SEQ_CONV ADC_EOC_SINGLE_SEQ_CONV #define REGULAR_GROUP ADC_REGULAR_GROUP #define INJECTED_GROUP ADC_INJECTED_GROUP #define REGULAR_INJECTED_GROUP ADC_REGULAR_INJECTED_GROUP #define AWD_EVENT ADC_AWD_EVENT #define AWD1_EVENT ADC_AWD1_EVENT #define AWD2_EVENT ADC_AWD2_EVENT #define AWD3_EVENT ADC_AWD3_EVENT #define OVR_EVENT ADC_OVR_EVENT #define JQOVF_EVENT ADC_JQOVF_EVENT #define ALL_CHANNELS ADC_ALL_CHANNELS #define REGULAR_CHANNELS ADC_REGULAR_CHANNELS #define INJECTED_CHANNELS ADC_INJECTED_CHANNELS #define SYSCFG_FLAG_SENSOR_ADC ADC_FLAG_SENSOR #define SYSCFG_FLAG_VREF_ADC ADC_FLAG_VREFINT #define ADC_CLOCKPRESCALER_PCLK_DIV1 ADC_CLOCK_SYNC_PCLK_DIV1 #define ADC_CLOCKPRESCALER_PCLK_DIV2 ADC_CLOCK_SYNC_PCLK_DIV2 #define ADC_CLOCKPRESCALER_PCLK_DIV4 ADC_CLOCK_SYNC_PCLK_DIV4 #define ADC_CLOCKPRESCALER_PCLK_DIV6 ADC_CLOCK_SYNC_PCLK_DIV6 #define ADC_CLOCKPRESCALER_PCLK_DIV8 ADC_CLOCK_SYNC_PCLK_DIV8 #define ADC_EXTERNALTRIG0_T6_TRGO ADC_EXTERNALTRIGCONV_T6_TRGO #define ADC_EXTERNALTRIG1_T21_CC2 ADC_EXTERNALTRIGCONV_T21_CC2 #define ADC_EXTERNALTRIG2_T2_TRGO ADC_EXTERNALTRIGCONV_T2_TRGO #define ADC_EXTERNALTRIG3_T2_CC4 ADC_EXTERNALTRIGCONV_T2_CC4 #define ADC_EXTERNALTRIG4_T22_TRGO ADC_EXTERNALTRIGCONV_T22_TRGO #define ADC_EXTERNALTRIG7_EXT_IT11 ADC_EXTERNALTRIGCONV_EXT_IT11 #define ADC_CLOCK_ASYNC ADC_CLOCK_ASYNC_DIV1 #define ADC_EXTERNALTRIG_EDGE_NONE ADC_EXTERNALTRIGCONVEDGE_NONE #define ADC_EXTERNALTRIG_EDGE_RISING ADC_EXTERNALTRIGCONVEDGE_RISING #define ADC_EXTERNALTRIG_EDGE_FALLING ADC_EXTERNALTRIGCONVEDGE_FALLING #define ADC_EXTERNALTRIG_EDGE_RISINGFALLING ADC_EXTERNALTRIGCONVEDGE_RISINGFALLING /** * @} */ /** @defgroup HAL_CEC_Aliased_Defines HAL CEC Aliased Defines maintained for legacy purpose * @{ */ #define __HAL_CEC_GET_IT __HAL_CEC_GET_FLAG /** * @} */ /** @defgroup HAL_COMP_Aliased_Defines HAL COMP Aliased Defines maintained for legacy purpose * @{ */ #define COMP_WINDOWMODE_DISABLED COMP_WINDOWMODE_DISABLE #define COMP_WINDOWMODE_ENABLED COMP_WINDOWMODE_ENABLE #define COMP_EXTI_LINE_COMP1_EVENT COMP_EXTI_LINE_COMP1 #define COMP_EXTI_LINE_COMP2_EVENT COMP_EXTI_LINE_COMP2 /** * @} */ /** @defgroup HAL_CRC_Aliased_Defines HAL CRC Aliased Defines maintained for legacy purpose * @{ */ #define CRC_OUTPUTDATA_INVERSION_DISABLED CRC_OUTPUTDATA_INVERSION_DISABLE #define CRC_OUTPUTDATA_INVERSION_ENABLED CRC_OUTPUTDATA_INVERSION_ENABLE /** * @} */ /** @defgroup HAL_DAC_Aliased_Defines HAL DAC Aliased Defines maintained for legacy purpose * @{ */ #define DAC1_CHANNEL_1 DAC_CHANNEL_1 #define DAC1_CHANNEL_2 DAC_CHANNEL_2 #define DAC2_CHANNEL_1 DAC_CHANNEL_1 #define DAC_WAVE_NONE ((uint32_t)0x00000000) #define DAC_WAVE_NOISE ((uint32_t)DAC_CR_WAVE1_0) #define DAC_WAVE_TRIANGLE ((uint32_t)DAC_CR_WAVE1_1) #define DAC_WAVEGENERATION_NONE DAC_WAVE_NONE #define DAC_WAVEGENERATION_NOISE DAC_WAVE_NOISE #define DAC_WAVEGENERATION_TRIANGLE DAC_WAVE_TRIANGLE /** * @} */ /** @defgroup HAL_DMA_Aliased_Defines HAL DMA Aliased Defines maintained for legacy purpose * @{ */ #define HAL_REMAPDMA_ADC_DMA_CH2 DMA_REMAP_ADC_DMA_CH2 #define HAL_REMAPDMA_USART1_TX_DMA_CH4 DMA_REMAP_USART1_TX_DMA_CH4 #define HAL_REMAPDMA_USART1_RX_DMA_CH5 DMA_REMAP_USART1_RX_DMA_CH5 #define HAL_REMAPDMA_TIM16_DMA_CH4 DMA_REMAP_TIM16_DMA_CH4 #define HAL_REMAPDMA_TIM17_DMA_CH2 DMA_REMAP_TIM17_DMA_CH2 #define HAL_REMAPDMA_USART3_DMA_CH32 DMA_REMAP_USART3_DMA_CH32 #define HAL_REMAPDMA_TIM16_DMA_CH6 DMA_REMAP_TIM16_DMA_CH6 #define HAL_REMAPDMA_TIM17_DMA_CH7 DMA_REMAP_TIM17_DMA_CH7 #define HAL_REMAPDMA_SPI2_DMA_CH67 DMA_REMAP_SPI2_DMA_CH67 #define HAL_REMAPDMA_USART2_DMA_CH67 DMA_REMAP_USART2_DMA_CH67 #define HAL_REMAPDMA_USART3_DMA_CH32 DMA_REMAP_USART3_DMA_CH32 #define HAL_REMAPDMA_I2C1_DMA_CH76 DMA_REMAP_I2C1_DMA_CH76 #define HAL_REMAPDMA_TIM1_DMA_CH6 DMA_REMAP_TIM1_DMA_CH6 #define HAL_REMAPDMA_TIM2_DMA_CH7 DMA_REMAP_TIM2_DMA_CH7 #define HAL_REMAPDMA_TIM3_DMA_CH6 DMA_REMAP_TIM3_DMA_CH6 #define IS_HAL_REMAPDMA IS_DMA_REMAP #define __HAL_REMAPDMA_CHANNEL_ENABLE __HAL_DMA_REMAP_CHANNEL_ENABLE #define __HAL_REMAPDMA_CHANNEL_DISABLE __HAL_DMA_REMAP_CHANNEL_DISABLE /** * @} */ /** @defgroup HAL_FLASH_Aliased_Defines HAL FLASH Aliased Defines maintained for legacy purpose * @{ */ #define TYPEPROGRAM_BYTE FLASH_TYPEPROGRAM_BYTE #define TYPEPROGRAM_HALFWORD FLASH_TYPEPROGRAM_HALFWORD #define TYPEPROGRAM_WORD FLASH_TYPEPROGRAM_WORD #define TYPEPROGRAM_DOUBLEWORD FLASH_TYPEPROGRAM_DOUBLEWORD #define TYPEERASE_SECTORS FLASH_TYPEERASE_SECTORS #define TYPEERASE_PAGES FLASH_TYPEERASE_PAGES #define TYPEERASE_PAGEERASE FLASH_TYPEERASE_PAGES #define TYPEERASE_MASSERASE FLASH_TYPEERASE_MASSERASE #define WRPSTATE_DISABLE OB_WRPSTATE_DISABLE #define WRPSTATE_ENABLE OB_WRPSTATE_ENABLE #define HAL_FLASH_TIMEOUT_VALUE FLASH_TIMEOUT_VALUE #define OBEX_PCROP OPTIONBYTE_PCROP #define OBEX_BOOTCONFIG OPTIONBYTE_BOOTCONFIG #define PCROPSTATE_DISABLE OB_PCROP_STATE_DISABLE #define PCROPSTATE_ENABLE OB_PCROP_STATE_ENABLE #define TYPEERASEDATA_BYTE FLASH_TYPEERASEDATA_BYTE #define TYPEERASEDATA_HALFWORD FLASH_TYPEERASEDATA_HALFWORD #define TYPEERASEDATA_WORD FLASH_TYPEERASEDATA_WORD #define TYPEPROGRAMDATA_BYTE FLASH_TYPEPROGRAMDATA_BYTE #define TYPEPROGRAMDATA_HALFWORD FLASH_TYPEPROGRAMDATA_HALFWORD #define TYPEPROGRAMDATA_WORD FLASH_TYPEPROGRAMDATA_WORD #define TYPEPROGRAMDATA_FASTBYTE FLASH_TYPEPROGRAMDATA_FASTBYTE #define TYPEPROGRAMDATA_FASTHALFWORD FLASH_TYPEPROGRAMDATA_FASTHALFWORD #define TYPEPROGRAMDATA_FASTWORD FLASH_TYPEPROGRAMDATA_FASTWORD #define PAGESIZE FLASH_PAGE_SIZE #define TYPEPROGRAM_FASTBYTE FLASH_TYPEPROGRAM_BYTE #define TYPEPROGRAM_FASTHALFWORD FLASH_TYPEPROGRAM_HALFWORD #define TYPEPROGRAM_FASTWORD FLASH_TYPEPROGRAM_WORD #define VOLTAGE_RANGE_1 FLASH_VOLTAGE_RANGE_1 #define VOLTAGE_RANGE_2 FLASH_VOLTAGE_RANGE_2 #define VOLTAGE_RANGE_3 FLASH_VOLTAGE_RANGE_3 #define VOLTAGE_RANGE_4 FLASH_VOLTAGE_RANGE_4 #define TYPEPROGRAM_FAST FLASH_TYPEPROGRAM_FAST #define TYPEPROGRAM_FAST_AND_LAST FLASH_TYPEPROGRAM_FAST_AND_LAST #define WRPAREA_BANK1_AREAA OB_WRPAREA_BANK1_AREAA #define WRPAREA_BANK1_AREAB OB_WRPAREA_BANK1_AREAB #define WRPAREA_BANK2_AREAA OB_WRPAREA_BANK2_AREAA #define WRPAREA_BANK2_AREAB OB_WRPAREA_BANK2_AREAB #define IWDG_STDBY_FREEZE OB_IWDG_STDBY_FREEZE #define IWDG_STDBY_ACTIVE OB_IWDG_STDBY_RUN #define IWDG_STOP_FREEZE OB_IWDG_STOP_FREEZE #define IWDG_STOP_ACTIVE OB_IWDG_STOP_RUN #define FLASH_ERROR_NONE HAL_FLASH_ERROR_NONE #define FLASH_ERROR_RD HAL_FLASH_ERROR_RD #define FLASH_ERROR_PG HAL_FLASH_ERROR_PROG #define FLASH_ERROR_PGP HAL_FLASH_ERROR_PGS #define FLASH_ERROR_WRP HAL_FLASH_ERROR_WRP #define FLASH_ERROR_OPTV HAL_FLASH_ERROR_OPTV #define FLASH_ERROR_OPTVUSR HAL_FLASH_ERROR_OPTVUSR #define FLASH_ERROR_PROG HAL_FLASH_ERROR_PROG #define FLASH_ERROR_OP HAL_FLASH_ERROR_OPERATION #define FLASH_ERROR_PGA HAL_FLASH_ERROR_PGA #define FLASH_ERROR_SIZE HAL_FLASH_ERROR_SIZE #define FLASH_ERROR_SIZ HAL_FLASH_ERROR_SIZE #define FLASH_ERROR_PGS HAL_FLASH_ERROR_PGS #define FLASH_ERROR_MIS HAL_FLASH_ERROR_MIS #define FLASH_ERROR_FAST HAL_FLASH_ERROR_FAST #define FLASH_ERROR_FWWERR HAL_FLASH_ERROR_FWWERR #define FLASH_ERROR_NOTZERO HAL_FLASH_ERROR_NOTZERO #define FLASH_ERROR_OPERATION HAL_FLASH_ERROR_OPERATION #define FLASH_ERROR_ERS HAL_FLASH_ERROR_ERS #define OB_WDG_SW OB_IWDG_SW #define OB_WDG_HW OB_IWDG_HW #define OB_SDADC12_VDD_MONITOR_SET OB_SDACD_VDD_MONITOR_SET #define OB_SDADC12_VDD_MONITOR_RESET OB_SDACD_VDD_MONITOR_RESET #define OB_RAM_PARITY_CHECK_SET OB_SRAM_PARITY_SET #define OB_RAM_PARITY_CHECK_RESET OB_SRAM_PARITY_RESET #define IS_OB_SDADC12_VDD_MONITOR IS_OB_SDACD_VDD_MONITOR #define OB_RDP_LEVEL0 OB_RDP_LEVEL_0 #define OB_RDP_LEVEL1 OB_RDP_LEVEL_1 #define OB_RDP_LEVEL2 OB_RDP_LEVEL_2 /** * @} */ /** @defgroup HAL_SYSCFG_Aliased_Defines HAL SYSCFG Aliased Defines maintained for legacy purpose * @{ */ #define HAL_SYSCFG_FASTMODEPLUS_I2C_PA9 I2C_FASTMODEPLUS_PA9 #define HAL_SYSCFG_FASTMODEPLUS_I2C_PA10 I2C_FASTMODEPLUS_PA10 #define HAL_SYSCFG_FASTMODEPLUS_I2C_PB6 I2C_FASTMODEPLUS_PB6 #define HAL_SYSCFG_FASTMODEPLUS_I2C_PB7 I2C_FASTMODEPLUS_PB7 #define HAL_SYSCFG_FASTMODEPLUS_I2C_PB8 I2C_FASTMODEPLUS_PB8 #define HAL_SYSCFG_FASTMODEPLUS_I2C_PB9 I2C_FASTMODEPLUS_PB9 #define HAL_SYSCFG_FASTMODEPLUS_I2C1 I2C_FASTMODEPLUS_I2C1 #define HAL_SYSCFG_FASTMODEPLUS_I2C2 I2C_FASTMODEPLUS_I2C2 #define HAL_SYSCFG_FASTMODEPLUS_I2C3 I2C_FASTMODEPLUS_I2C3 /** * @} */ /** @defgroup LL_FMC_Aliased_Defines LL FMC Aliased Defines maintained for compatibility purpose * @{ */ #if defined(STM32L4) || defined(STM32F7) #define FMC_NAND_PCC_WAIT_FEATURE_DISABLE FMC_NAND_WAIT_FEATURE_DISABLE #define FMC_NAND_PCC_WAIT_FEATURE_ENABLE FMC_NAND_WAIT_FEATURE_ENABLE #define FMC_NAND_PCC_MEM_BUS_WIDTH_8 FMC_NAND_MEM_BUS_WIDTH_8 #define FMC_NAND_PCC_MEM_BUS_WIDTH_16 FMC_NAND_MEM_BUS_WIDTH_16 #else #define FMC_NAND_WAIT_FEATURE_DISABLE FMC_NAND_PCC_WAIT_FEATURE_DISABLE #define FMC_NAND_WAIT_FEATURE_ENABLE FMC_NAND_PCC_WAIT_FEATURE_ENABLE #define FMC_NAND_MEM_BUS_WIDTH_8 FMC_NAND_PCC_MEM_BUS_WIDTH_8 #define FMC_NAND_MEM_BUS_WIDTH_16 FMC_NAND_PCC_MEM_BUS_WIDTH_16 #endif /** * @} */ /** @defgroup LL_FSMC_Aliased_Defines LL FSMC Aliased Defines maintained for legacy purpose * @{ */ #define FSMC_NORSRAM_TYPEDEF FSMC_NORSRAM_TypeDef #define FSMC_NORSRAM_EXTENDED_TYPEDEF FSMC_NORSRAM_EXTENDED_TypeDef /** * @} */ /** @defgroup HAL_GPIO_Aliased_Macros HAL GPIO Aliased Macros maintained for legacy purpose * @{ */ #define GET_GPIO_SOURCE GPIO_GET_INDEX #define GET_GPIO_INDEX GPIO_GET_INDEX #if defined(STM32F4) #define GPIO_AF12_SDMMC GPIO_AF12_SDIO #define GPIO_AF12_SDMMC1 GPIO_AF12_SDIO #endif #if defined(STM32F7) #define GPIO_AF12_SDIO GPIO_AF12_SDMMC1 #define GPIO_AF12_SDMMC GPIO_AF12_SDMMC1 #endif #if defined(STM32L4) #define GPIO_AF12_SDIO GPIO_AF12_SDMMC1 #define GPIO_AF12_SDMMC GPIO_AF12_SDMMC1 #endif #define GPIO_AF0_LPTIM GPIO_AF0_LPTIM1 #define GPIO_AF1_LPTIM GPIO_AF1_LPTIM1 #define GPIO_AF2_LPTIM GPIO_AF2_LPTIM1 #if defined(STM32L0) || defined(STM32F4) #define GPIO_SPEED_LOW GPIO_SPEED_FREQ_LOW #define GPIO_SPEED_MEDIUM GPIO_SPEED_FREQ_MEDIUM #define GPIO_SPEED_FAST GPIO_SPEED_FREQ_HIGH #define GPIO_SPEED_HIGH GPIO_SPEED_FREQ_VERY_HIGH #endif /* STM32L0 || STM32F4 */ /** * @} */ /** @defgroup HAL_HRTIM_Aliased_Macros HAL HRTIM Aliased Macros maintained for legacy purpose * @{ */ #define HRTIM_TIMDELAYEDPROTECTION_DISABLED HRTIM_TIMER_A_B_C_DELAYEDPROTECTION_DISABLED #define HRTIM_TIMDELAYEDPROTECTION_DELAYEDOUT1_EEV68 HRTIM_TIMER_A_B_C_DELAYEDPROTECTION_DELAYEDOUT1_EEV6 #define HRTIM_TIMDELAYEDPROTECTION_DELAYEDOUT2_EEV68 HRTIM_TIMER_A_B_C_DELAYEDPROTECTION_DELAYEDOUT2_EEV6 #define HRTIM_TIMDELAYEDPROTECTION_DELAYEDBOTH_EEV68 HRTIM_TIMER_A_B_C_DELAYEDPROTECTION_DELAYEDBOTH_EEV6 #define HRTIM_TIMDELAYEDPROTECTION_BALANCED_EEV68 HRTIM_TIMER_A_B_C_DELAYEDPROTECTION_BALANCED_EEV6 #define HRTIM_TIMDELAYEDPROTECTION_DELAYEDOUT1_DEEV79 HRTIM_TIMER_A_B_C_DELAYEDPROTECTION_DELAYEDOUT1_DEEV7 #define HRTIM_TIMDELAYEDPROTECTION_DELAYEDOUT2_DEEV79 HRTIM_TIMER_A_B_C_DELAYEDPROTECTION_DELAYEDOUT2_DEEV7 #define HRTIM_TIMDELAYEDPROTECTION_DELAYEDBOTH_EEV79 HRTIM_TIMER_A_B_C_DELAYEDPROTECTION_DELAYEDBOTH_EEV7 #define HRTIM_TIMDELAYEDPROTECTION_BALANCED_EEV79 HRTIM_TIMER_A_B_C_DELAYEDPROTECTION_BALANCED_EEV7 /** * @} */ /** @defgroup HAL_I2C_Aliased_Defines HAL I2C Aliased Defines maintained for legacy purpose * @{ */ #define I2C_DUALADDRESS_DISABLED I2C_DUALADDRESS_DISABLE #define I2C_DUALADDRESS_ENABLED I2C_DUALADDRESS_ENABLE #define I2C_GENERALCALL_DISABLED I2C_GENERALCALL_DISABLE #define I2C_GENERALCALL_ENABLED I2C_GENERALCALL_ENABLE #define I2C_NOSTRETCH_DISABLED I2C_NOSTRETCH_DISABLE #define I2C_NOSTRETCH_ENABLED I2C_NOSTRETCH_ENABLE #define I2C_ANALOGFILTER_ENABLED I2C_ANALOGFILTER_ENABLE #define I2C_ANALOGFILTER_DISABLED I2C_ANALOGFILTER_DISABLE /** * @} */ /** @defgroup HAL_IRDA_Aliased_Defines HAL IRDA Aliased Defines maintained for legacy purpose * @{ */ #define IRDA_ONE_BIT_SAMPLE_DISABLED IRDA_ONE_BIT_SAMPLE_DISABLE #define IRDA_ONE_BIT_SAMPLE_ENABLED IRDA_ONE_BIT_SAMPLE_ENABLE /** * @} */ /** @defgroup HAL_IWDG_Aliased_Defines HAL IWDG Aliased Defines maintained for legacy purpose * @{ */ #define KR_KEY_RELOAD IWDG_KEY_RELOAD #define KR_KEY_ENABLE IWDG_KEY_ENABLE #define KR_KEY_EWA IWDG_KEY_WRITE_ACCESS_ENABLE #define KR_KEY_DWA IWDG_KEY_WRITE_ACCESS_DISABLE /** * @} */ /** @defgroup HAL_LPTIM_Aliased_Defines HAL LPTIM Aliased Defines maintained for legacy purpose * @{ */ #define LPTIM_CLOCKSAMPLETIME_DIRECTTRANSISTION LPTIM_CLOCKSAMPLETIME_DIRECTTRANSITION #define LPTIM_CLOCKSAMPLETIME_2TRANSISTIONS LPTIM_CLOCKSAMPLETIME_2TRANSITIONS #define LPTIM_CLOCKSAMPLETIME_4TRANSISTIONS LPTIM_CLOCKSAMPLETIME_4TRANSITIONS #define LPTIM_CLOCKSAMPLETIME_8TRANSISTIONS LPTIM_CLOCKSAMPLETIME_8TRANSITIONS #define LPTIM_CLOCKPOLARITY_RISINGEDGE LPTIM_CLOCKPOLARITY_RISING #define LPTIM_CLOCKPOLARITY_FALLINGEDGE LPTIM_CLOCKPOLARITY_FALLING #define LPTIM_CLOCKPOLARITY_BOTHEDGES LPTIM_CLOCKPOLARITY_RISING_FALLING #define LPTIM_TRIGSAMPLETIME_DIRECTTRANSISTION LPTIM_TRIGSAMPLETIME_DIRECTTRANSITION #define LPTIM_TRIGSAMPLETIME_2TRANSISTIONS LPTIM_TRIGSAMPLETIME_2TRANSITIONS #define LPTIM_TRIGSAMPLETIME_4TRANSISTIONS LPTIM_TRIGSAMPLETIME_4TRANSITIONS #define LPTIM_TRIGSAMPLETIME_8TRANSISTIONS LPTIM_TRIGSAMPLETIME_8TRANSITIONS /* The following 3 definition have also been present in a temporary version of lptim.h */ /* They need to be renamed also to the right name, just in case */ #define LPTIM_TRIGSAMPLETIME_2TRANSITION LPTIM_TRIGSAMPLETIME_2TRANSITIONS #define LPTIM_TRIGSAMPLETIME_4TRANSITION LPTIM_TRIGSAMPLETIME_4TRANSITIONS #define LPTIM_TRIGSAMPLETIME_8TRANSITION LPTIM_TRIGSAMPLETIME_8TRANSITIONS /** * @} */ /** @defgroup HAL_NAND_Aliased_Defines HAL NAND Aliased Defines maintained for legacy purpose * @{ */ #define NAND_AddressTypedef NAND_AddressTypeDef #define __ARRAY_ADDRESS ARRAY_ADDRESS #define __ADDR_1st_CYCLE ADDR_1ST_CYCLE #define __ADDR_2nd_CYCLE ADDR_2ND_CYCLE #define __ADDR_3rd_CYCLE ADDR_3RD_CYCLE #define __ADDR_4th_CYCLE ADDR_4TH_CYCLE /** * @} */ /** @defgroup HAL_NOR_Aliased_Defines HAL NOR Aliased Defines maintained for legacy purpose * @{ */ #define NOR_StatusTypedef HAL_NOR_StatusTypeDef #define NOR_SUCCESS HAL_NOR_STATUS_SUCCESS #define NOR_ONGOING HAL_NOR_STATUS_ONGOING #define NOR_ERROR HAL_NOR_STATUS_ERROR #define NOR_TIMEOUT HAL_NOR_STATUS_TIMEOUT #define __NOR_WRITE NOR_WRITE #define __NOR_ADDR_SHIFT NOR_ADDR_SHIFT /** * @} */ /** @defgroup HAL_OPAMP_Aliased_Defines HAL OPAMP Aliased Defines maintained for legacy purpose * @{ */ #define OPAMP_NONINVERTINGINPUT_VP0 OPAMP_NONINVERTINGINPUT_IO0 #define OPAMP_NONINVERTINGINPUT_VP1 OPAMP_NONINVERTINGINPUT_IO1 #define OPAMP_NONINVERTINGINPUT_VP2 OPAMP_NONINVERTINGINPUT_IO2 #define OPAMP_NONINVERTINGINPUT_VP3 OPAMP_NONINVERTINGINPUT_IO3 #define OPAMP_SEC_NONINVERTINGINPUT_VP0 OPAMP_SEC_NONINVERTINGINPUT_IO0 #define OPAMP_SEC_NONINVERTINGINPUT_VP1 OPAMP_SEC_NONINVERTINGINPUT_IO1 #define OPAMP_SEC_NONINVERTINGINPUT_VP2 OPAMP_SEC_NONINVERTINGINPUT_IO2 #define OPAMP_SEC_NONINVERTINGINPUT_VP3 OPAMP_SEC_NONINVERTINGINPUT_IO3 #define OPAMP_INVERTINGINPUT_VM0 OPAMP_INVERTINGINPUT_IO0 #define OPAMP_INVERTINGINPUT_VM1 OPAMP_INVERTINGINPUT_IO1 #define IOPAMP_INVERTINGINPUT_VM0 OPAMP_INVERTINGINPUT_IO0 #define IOPAMP_INVERTINGINPUT_VM1 OPAMP_INVERTINGINPUT_IO1 #define OPAMP_SEC_INVERTINGINPUT_VM0 OPAMP_SEC_INVERTINGINPUT_IO0 #define OPAMP_SEC_INVERTINGINPUT_VM1 OPAMP_SEC_INVERTINGINPUT_IO1 #define OPAMP_INVERTINGINPUT_VINM OPAMP_SEC_INVERTINGINPUT_IO1 #define OPAMP_PGACONNECT_NO OPAMP_PGA_CONNECT_INVERTINGINPUT_NO #define OPAMP_PGACONNECT_VM0 OPAMP_PGA_CONNECT_INVERTINGINPUT_IO0 #define OPAMP_PGACONNECT_VM1 OPAMP_PGA_CONNECT_INVERTINGINPUT_IO1 /** * @} */ /** @defgroup HAL_I2S_Aliased_Defines HAL I2S Aliased Defines maintained for legacy purpose * @{ */ #define I2S_STANDARD_PHILLIPS I2S_STANDARD_PHILIPS /** * @} */ /** @defgroup HAL_PCCARD_Aliased_Defines HAL PCCARD Aliased Defines maintained for legacy purpose * @{ */ /* Compact Flash-ATA registers description */ #define CF_DATA ATA_DATA #define CF_SECTOR_COUNT ATA_SECTOR_COUNT #define CF_SECTOR_NUMBER ATA_SECTOR_NUMBER #define CF_CYLINDER_LOW ATA_CYLINDER_LOW #define CF_CYLINDER_HIGH ATA_CYLINDER_HIGH #define CF_CARD_HEAD ATA_CARD_HEAD #define CF_STATUS_CMD ATA_STATUS_CMD #define CF_STATUS_CMD_ALTERNATE ATA_STATUS_CMD_ALTERNATE #define CF_COMMON_DATA_AREA ATA_COMMON_DATA_AREA /* Compact Flash-ATA commands */ #define CF_READ_SECTOR_CMD ATA_READ_SECTOR_CMD #define CF_WRITE_SECTOR_CMD ATA_WRITE_SECTOR_CMD #define CF_ERASE_SECTOR_CMD ATA_ERASE_SECTOR_CMD #define CF_IDENTIFY_CMD ATA_IDENTIFY_CMD #define PCCARD_StatusTypedef HAL_PCCARD_StatusTypeDef #define PCCARD_SUCCESS HAL_PCCARD_STATUS_SUCCESS #define PCCARD_ONGOING HAL_PCCARD_STATUS_ONGOING #define PCCARD_ERROR HAL_PCCARD_STATUS_ERROR #define PCCARD_TIMEOUT HAL_PCCARD_STATUS_TIMEOUT /** * @} */ /** @defgroup HAL_RTC_Aliased_Defines HAL RTC Aliased Defines maintained for legacy purpose * @{ */ #define FORMAT_BIN RTC_FORMAT_BIN #define FORMAT_BCD RTC_FORMAT_BCD #define RTC_ALARMSUBSECONDMASK_None RTC_ALARMSUBSECONDMASK_NONE #define RTC_TAMPERERASEBACKUP_ENABLED RTC_TAMPER_ERASE_BACKUP_ENABLE #define RTC_TAMPERERASEBACKUP_DISABLED RTC_TAMPER_ERASE_BACKUP_DISABLE #define RTC_TAMPERMASK_FLAG_DISABLED RTC_TAMPERMASK_FLAG_DISABLE #define RTC_TAMPERMASK_FLAG_ENABLED RTC_TAMPERMASK_FLAG_ENABLE #define RTC_MASKTAMPERFLAG_DISABLED RTC_TAMPERMASK_FLAG_DISABLE #define RTC_MASKTAMPERFLAG_ENABLED RTC_TAMPERMASK_FLAG_ENABLE #define RTC_TAMPERERASEBACKUP_ENABLED RTC_TAMPER_ERASE_BACKUP_ENABLE #define RTC_TAMPERERASEBACKUP_DISABLED RTC_TAMPER_ERASE_BACKUP_DISABLE #define RTC_MASKTAMPERFLAG_DISABLED RTC_TAMPERMASK_FLAG_DISABLE #define RTC_MASKTAMPERFLAG_ENABLED RTC_TAMPERMASK_FLAG_ENABLE #define RTC_TAMPER1_2_INTERRUPT RTC_ALL_TAMPER_INTERRUPT #define RTC_TAMPER1_2_3_INTERRUPT RTC_ALL_TAMPER_INTERRUPT #define RTC_TIMESTAMPPIN_PC13 RTC_TIMESTAMPPIN_DEFAULT #define RTC_TIMESTAMPPIN_PA0 RTC_TIMESTAMPPIN_POS1 #define RTC_TIMESTAMPPIN_PI8 RTC_TIMESTAMPPIN_POS1 #define RTC_TIMESTAMPPIN_PC1 RTC_TIMESTAMPPIN_POS2 #define RTC_OUTPUT_REMAP_PC13 RTC_OUTPUT_REMAP_NONE #define RTC_OUTPUT_REMAP_PB14 RTC_OUTPUT_REMAP_POS1 #define RTC_OUTPUT_REMAP_PB2 RTC_OUTPUT_REMAP_POS1 #define RTC_TAMPERPIN_PC13 RTC_TAMPERPIN_DEFAULT #define RTC_TAMPERPIN_PA0 RTC_TAMPERPIN_POS1 #define RTC_TAMPERPIN_PI8 RTC_TAMPERPIN_POS1 /** * @} */ /** @defgroup HAL_SMARTCARD_Aliased_Defines HAL SMARTCARD Aliased Defines maintained for legacy purpose * @{ */ #define SMARTCARD_NACK_ENABLED SMARTCARD_NACK_ENABLE #define SMARTCARD_NACK_DISABLED SMARTCARD_NACK_DISABLE #define SMARTCARD_ONEBIT_SAMPLING_DISABLED SMARTCARD_ONE_BIT_SAMPLE_DISABLE #define SMARTCARD_ONEBIT_SAMPLING_ENABLED SMARTCARD_ONE_BIT_SAMPLE_ENABLE #define SMARTCARD_ONEBIT_SAMPLING_DISABLE SMARTCARD_ONE_BIT_SAMPLE_DISABLE #define SMARTCARD_ONEBIT_SAMPLING_ENABLE SMARTCARD_ONE_BIT_SAMPLE_ENABLE #define SMARTCARD_TIMEOUT_DISABLED SMARTCARD_TIMEOUT_DISABLE #define SMARTCARD_TIMEOUT_ENABLED SMARTCARD_TIMEOUT_ENABLE #define SMARTCARD_LASTBIT_DISABLED SMARTCARD_LASTBIT_DISABLE #define SMARTCARD_LASTBIT_ENABLED SMARTCARD_LASTBIT_ENABLE /** * @} */ /** @defgroup HAL_SMBUS_Aliased_Defines HAL SMBUS Aliased Defines maintained for legacy purpose * @{ */ #define SMBUS_DUALADDRESS_DISABLED SMBUS_DUALADDRESS_DISABLE #define SMBUS_DUALADDRESS_ENABLED SMBUS_DUALADDRESS_ENABLE #define SMBUS_GENERALCALL_DISABLED SMBUS_GENERALCALL_DISABLE #define SMBUS_GENERALCALL_ENABLED SMBUS_GENERALCALL_ENABLE #define SMBUS_NOSTRETCH_DISABLED SMBUS_NOSTRETCH_DISABLE #define SMBUS_NOSTRETCH_ENABLED SMBUS_NOSTRETCH_ENABLE #define SMBUS_ANALOGFILTER_ENABLED SMBUS_ANALOGFILTER_ENABLE #define SMBUS_ANALOGFILTER_DISABLED SMBUS_ANALOGFILTER_DISABLE #define SMBUS_PEC_DISABLED SMBUS_PEC_DISABLE #define SMBUS_PEC_ENABLED SMBUS_PEC_ENABLE #define HAL_SMBUS_STATE_SLAVE_LISTEN HAL_SMBUS_STATE_LISTEN /** * @} */ /** @defgroup HAL_SPI_Aliased_Defines HAL SPI Aliased Defines maintained for legacy purpose * @{ */ #define SPI_TIMODE_DISABLED SPI_TIMODE_DISABLE #define SPI_TIMODE_ENABLED SPI_TIMODE_ENABLE #define SPI_CRCCALCULATION_DISABLED SPI_CRCCALCULATION_DISABLE #define SPI_CRCCALCULATION_ENABLED SPI_CRCCALCULATION_ENABLE #define SPI_NSS_PULSE_DISABLED SPI_NSS_PULSE_DISABLE #define SPI_NSS_PULSE_ENABLED SPI_NSS_PULSE_ENABLE /** * @} */ /** @defgroup HAL_TIM_Aliased_Defines HAL TIM Aliased Defines maintained for legacy purpose * @{ */ #define CCER_CCxE_MASK TIM_CCER_CCxE_MASK #define CCER_CCxNE_MASK TIM_CCER_CCxNE_MASK #define TIM_DMABase_CR1 TIM_DMABASE_CR1 #define TIM_DMABase_CR2 TIM_DMABASE_CR2 #define TIM_DMABase_SMCR TIM_DMABASE_SMCR #define TIM_DMABase_DIER TIM_DMABASE_DIER #define TIM_DMABase_SR TIM_DMABASE_SR #define TIM_DMABase_EGR TIM_DMABASE_EGR #define TIM_DMABase_CCMR1 TIM_DMABASE_CCMR1 #define TIM_DMABase_CCMR2 TIM_DMABASE_CCMR2 #define TIM_DMABase_CCER TIM_DMABASE_CCER #define TIM_DMABase_CNT TIM_DMABASE_CNT #define TIM_DMABase_PSC TIM_DMABASE_PSC #define TIM_DMABase_ARR TIM_DMABASE_ARR #define TIM_DMABase_RCR TIM_DMABASE_RCR #define TIM_DMABase_CCR1 TIM_DMABASE_CCR1 #define TIM_DMABase_CCR2 TIM_DMABASE_CCR2 #define TIM_DMABase_CCR3 TIM_DMABASE_CCR3 #define TIM_DMABase_CCR4 TIM_DMABASE_CCR4 #define TIM_DMABase_BDTR TIM_DMABASE_BDTR #define TIM_DMABase_DCR TIM_DMABASE_DCR #define TIM_DMABase_DMAR TIM_DMABASE_DMAR #define TIM_DMABase_OR1 TIM_DMABASE_OR1 #define TIM_DMABase_CCMR3 TIM_DMABASE_CCMR3 #define TIM_DMABase_CCR5 TIM_DMABASE_CCR5 #define TIM_DMABase_CCR6 TIM_DMABASE_CCR6 #define TIM_DMABase_OR2 TIM_DMABASE_OR2 #define TIM_DMABase_OR3 TIM_DMABASE_OR3 #define TIM_DMABase_OR TIM_DMABASE_OR #define TIM_EventSource_Update TIM_EVENTSOURCE_UPDATE #define TIM_EventSource_CC1 TIM_EVENTSOURCE_CC1 #define TIM_EventSource_CC2 TIM_EVENTSOURCE_CC2 #define TIM_EventSource_CC3 TIM_EVENTSOURCE_CC3 #define TIM_EventSource_CC4 TIM_EVENTSOURCE_CC4 #define TIM_EventSource_COM TIM_EVENTSOURCE_COM #define TIM_EventSource_Trigger TIM_EVENTSOURCE_TRIGGER #define TIM_EventSource_Break TIM_EVENTSOURCE_BREAK #define TIM_EventSource_Break2 TIM_EVENTSOURCE_BREAK2 #define TIM_DMABurstLength_1Transfer TIM_DMABURSTLENGTH_1TRANSFER #define TIM_DMABurstLength_2Transfers TIM_DMABURSTLENGTH_2TRANSFERS #define TIM_DMABurstLength_3Transfers TIM_DMABURSTLENGTH_3TRANSFERS #define TIM_DMABurstLength_4Transfers TIM_DMABURSTLENGTH_4TRANSFERS #define TIM_DMABurstLength_5Transfers TIM_DMABURSTLENGTH_5TRANSFERS #define TIM_DMABurstLength_6Transfers TIM_DMABURSTLENGTH_6TRANSFERS #define TIM_DMABurstLength_7Transfers TIM_DMABURSTLENGTH_7TRANSFERS #define TIM_DMABurstLength_8Transfers TIM_DMABURSTLENGTH_8TRANSFERS #define TIM_DMABurstLength_9Transfers TIM_DMABURSTLENGTH_9TRANSFERS #define TIM_DMABurstLength_10Transfers TIM_DMABURSTLENGTH_10TRANSFERS #define TIM_DMABurstLength_11Transfers TIM_DMABURSTLENGTH_11TRANSFERS #define TIM_DMABurstLength_12Transfers TIM_DMABURSTLENGTH_12TRANSFERS #define TIM_DMABurstLength_13Transfers TIM_DMABURSTLENGTH_13TRANSFERS #define TIM_DMABurstLength_14Transfers TIM_DMABURSTLENGTH_14TRANSFERS #define TIM_DMABurstLength_15Transfers TIM_DMABURSTLENGTH_15TRANSFERS #define TIM_DMABurstLength_16Transfers TIM_DMABURSTLENGTH_16TRANSFERS #define TIM_DMABurstLength_17Transfers TIM_DMABURSTLENGTH_17TRANSFERS #define TIM_DMABurstLength_18Transfers TIM_DMABURSTLENGTH_18TRANSFERS /** * @} */ /** @defgroup HAL_TSC_Aliased_Defines HAL TSC Aliased Defines maintained for legacy purpose * @{ */ #define TSC_SYNC_POL_FALL TSC_SYNC_POLARITY_FALLING #define TSC_SYNC_POL_RISE_HIGH TSC_SYNC_POLARITY_RISING /** * @} */ /** @defgroup HAL_UART_Aliased_Defines HAL UART Aliased Defines maintained for legacy purpose * @{ */ #define UART_ONEBIT_SAMPLING_DISABLED UART_ONE_BIT_SAMPLE_DISABLE #define UART_ONEBIT_SAMPLING_ENABLED UART_ONE_BIT_SAMPLE_ENABLE #define UART_ONE_BIT_SAMPLE_DISABLED UART_ONE_BIT_SAMPLE_DISABLE #define UART_ONE_BIT_SAMPLE_ENABLED UART_ONE_BIT_SAMPLE_ENABLE #define __HAL_UART_ONEBIT_ENABLE __HAL_UART_ONE_BIT_SAMPLE_ENABLE #define __HAL_UART_ONEBIT_DISABLE __HAL_UART_ONE_BIT_SAMPLE_DISABLE #define __DIV_SAMPLING16 UART_DIV_SAMPLING16 #define __DIVMANT_SAMPLING16 UART_DIVMANT_SAMPLING16 #define __DIVFRAQ_SAMPLING16 UART_DIVFRAQ_SAMPLING16 #define __UART_BRR_SAMPLING16 UART_BRR_SAMPLING16 #define __DIV_SAMPLING8 UART_DIV_SAMPLING8 #define __DIVMANT_SAMPLING8 UART_DIVMANT_SAMPLING8 #define __DIVFRAQ_SAMPLING8 UART_DIVFRAQ_SAMPLING8 #define __UART_BRR_SAMPLING8 UART_BRR_SAMPLING8 #define UART_WAKEUPMETHODE_IDLELINE UART_WAKEUPMETHOD_IDLELINE #define UART_WAKEUPMETHODE_ADDRESSMARK UART_WAKEUPMETHOD_ADDRESSMARK /** * @} */ /** @defgroup HAL_USART_Aliased_Defines HAL USART Aliased Defines maintained for legacy purpose * @{ */ #define USART_CLOCK_DISABLED USART_CLOCK_DISABLE #define USART_CLOCK_ENABLED USART_CLOCK_ENABLE #define USARTNACK_ENABLED USART_NACK_ENABLE #define USARTNACK_DISABLED USART_NACK_DISABLE /** * @} */ /** @defgroup HAL_WWDG_Aliased_Defines HAL WWDG Aliased Defines maintained for legacy purpose * @{ */ #define CFR_BASE WWDG_CFR_BASE /** * @} */ /** @defgroup HAL_CAN_Aliased_Defines HAL CAN Aliased Defines maintained for legacy purpose * @{ */ #define CAN_FilterFIFO0 CAN_FILTER_FIFO0 #define CAN_FilterFIFO1 CAN_FILTER_FIFO1 #define CAN_IT_RQCP0 CAN_IT_TME #define CAN_IT_RQCP1 CAN_IT_TME #define CAN_IT_RQCP2 CAN_IT_TME #define INAK_TIMEOUT CAN_TIMEOUT_VALUE #define SLAK_TIMEOUT CAN_TIMEOUT_VALUE #define CAN_TXSTATUS_FAILED ((uint8_t)0x00) #define CAN_TXSTATUS_OK ((uint8_t)0x01) #define CAN_TXSTATUS_PENDING ((uint8_t)0x02) /** * @} */ /** @defgroup HAL_ETH_Aliased_Defines HAL ETH Aliased Defines maintained for legacy purpose * @{ */ #define VLAN_TAG ETH_VLAN_TAG #define MIN_ETH_PAYLOAD ETH_MIN_ETH_PAYLOAD #define MAX_ETH_PAYLOAD ETH_MAX_ETH_PAYLOAD #define JUMBO_FRAME_PAYLOAD ETH_JUMBO_FRAME_PAYLOAD #define MACMIIAR_CR_MASK ETH_MACMIIAR_CR_MASK #define MACCR_CLEAR_MASK ETH_MACCR_CLEAR_MASK #define MACFCR_CLEAR_MASK ETH_MACFCR_CLEAR_MASK #define DMAOMR_CLEAR_MASK ETH_DMAOMR_CLEAR_MASK #define ETH_MMCCR ((uint32_t)0x00000100) #define ETH_MMCRIR ((uint32_t)0x00000104) #define ETH_MMCTIR ((uint32_t)0x00000108) #define ETH_MMCRIMR ((uint32_t)0x0000010C) #define ETH_MMCTIMR ((uint32_t)0x00000110) #define ETH_MMCTGFSCCR ((uint32_t)0x0000014C) #define ETH_MMCTGFMSCCR ((uint32_t)0x00000150) #define ETH_MMCTGFCR ((uint32_t)0x00000168) #define ETH_MMCRFCECR ((uint32_t)0x00000194) #define ETH_MMCRFAECR ((uint32_t)0x00000198) #define ETH_MMCRGUFCR ((uint32_t)0x000001C4) /** * @} */ /** @defgroup HAL_PPP_Aliased_Defines HAL PPP Aliased Defines maintained for legacy purpose * @{ */ /** * @} */ /* Exported functions --------------------------------------------------------*/ /** @defgroup HAL_CRYP_Aliased_Functions HAL CRYP Aliased Functions maintained for legacy purpose * @{ */ #define HAL_CRYP_ComputationCpltCallback HAL_CRYPEx_ComputationCpltCallback /** * @} */ /** @defgroup HAL_HASH_Aliased_Functions HAL HASH Aliased Functions maintained for legacy purpose * @{ */ #define HAL_HMAC_MD5_Finish HAL_HASH_MD5_Finish #define HAL_HMAC_SHA1_Finish HAL_HASH_SHA1_Finish #define HAL_HMAC_SHA224_Finish HAL_HASH_SHA224_Finish #define HAL_HMAC_SHA256_Finish HAL_HASH_SHA256_Finish /*HASH Algorithm Selection*/ #define HASH_AlgoSelection_SHA1 HASH_ALGOSELECTION_SHA1 #define HASH_AlgoSelection_SHA224 HASH_ALGOSELECTION_SHA224 #define HASH_AlgoSelection_SHA256 HASH_ALGOSELECTION_SHA256 #define HASH_AlgoSelection_MD5 HASH_ALGOSELECTION_MD5 #define HASH_AlgoMode_HASH HASH_ALGOMODE_HASH #define HASH_AlgoMode_HMAC HASH_ALGOMODE_HMAC #define HASH_HMACKeyType_ShortKey HASH_HMAC_KEYTYPE_SHORTKEY #define HASH_HMACKeyType_LongKey HASH_HMAC_KEYTYPE_LONGKEY /** * @} */ /** @defgroup HAL_Aliased_Functions HAL Generic Aliased Functions maintained for legacy purpose * @{ */ #define HAL_EnableDBGSleepMode HAL_DBGMCU_EnableDBGSleepMode #define HAL_DisableDBGSleepMode HAL_DBGMCU_DisableDBGSleepMode #define HAL_EnableDBGStopMode HAL_DBGMCU_EnableDBGStopMode #define HAL_DisableDBGStopMode HAL_DBGMCU_DisableDBGStopMode #define HAL_EnableDBGStandbyMode HAL_DBGMCU_EnableDBGStandbyMode #define HAL_DisableDBGStandbyMode HAL_DBGMCU_DisableDBGStandbyMode #define HAL_DBG_LowPowerConfig(Periph, cmd) (((cmd)==ENABLE)? HAL_DBGMCU_DBG_EnableLowPowerConfig(Periph) : HAL_DBGMCU_DBG_DisableLowPowerConfig(Periph)) #define HAL_VREFINT_OutputSelect HAL_SYSCFG_VREFINT_OutputSelect #define HAL_Lock_Cmd(cmd) (((cmd)==ENABLE) ? HAL_SYSCFG_Enable_Lock_VREFINT() : HAL_SYSCFG_Disable_Lock_VREFINT()) #define HAL_VREFINT_Cmd(cmd) (((cmd)==ENABLE)? HAL_SYSCFG_EnableVREFINT() : HAL_SYSCFG_DisableVREFINT()) #define HAL_ADC_EnableBuffer_Cmd(cmd) (((cmd)==ENABLE) ? HAL_ADCEx_EnableVREFINT() : HAL_ADCEx_DisableVREFINT()) #define HAL_ADC_EnableBufferSensor_Cmd(cmd) (((cmd)==ENABLE) ? HAL_ADCEx_EnableVREFINTTempSensor() : HAL_ADCEx_DisableVREFINTTempSensor()) /** * @} */ /** @defgroup HAL_FLASH_Aliased_Functions HAL FLASH Aliased Functions maintained for legacy purpose * @{ */ #define FLASH_HalfPageProgram HAL_FLASHEx_HalfPageProgram #define FLASH_EnableRunPowerDown HAL_FLASHEx_EnableRunPowerDown #define FLASH_DisableRunPowerDown HAL_FLASHEx_DisableRunPowerDown #define HAL_DATA_EEPROMEx_Unlock HAL_FLASHEx_DATAEEPROM_Unlock #define HAL_DATA_EEPROMEx_Lock HAL_FLASHEx_DATAEEPROM_Lock #define HAL_DATA_EEPROMEx_Erase HAL_FLASHEx_DATAEEPROM_Erase #define HAL_DATA_EEPROMEx_Program HAL_FLASHEx_DATAEEPROM_Program /** * @} */ /** @defgroup HAL_I2C_Aliased_Functions HAL I2C Aliased Functions maintained for legacy purpose * @{ */ #define HAL_I2CEx_AnalogFilter_Config HAL_I2CEx_ConfigAnalogFilter #define HAL_I2CEx_DigitalFilter_Config HAL_I2CEx_ConfigDigitalFilter #define HAL_I2CFastModePlusConfig(SYSCFG_I2CFastModePlus, cmd) (((cmd)==ENABLE)? HAL_I2CEx_EnableFastModePlus(SYSCFG_I2CFastModePlus): HAL_I2CEx_DisableFastModePlus(SYSCFG_I2CFastModePlus)) /** * @} */ /** @defgroup HAL_PWR_Aliased HAL PWR Aliased maintained for legacy purpose * @{ */ #define HAL_PWR_PVDConfig HAL_PWR_ConfigPVD #define HAL_PWR_DisableBkUpReg HAL_PWREx_DisableBkUpReg #define HAL_PWR_DisableFlashPowerDown HAL_PWREx_DisableFlashPowerDown #define HAL_PWR_DisableVddio2Monitor HAL_PWREx_DisableVddio2Monitor #define HAL_PWR_EnableBkUpReg HAL_PWREx_EnableBkUpReg #define HAL_PWR_EnableFlashPowerDown HAL_PWREx_EnableFlashPowerDown #define HAL_PWR_EnableVddio2Monitor HAL_PWREx_EnableVddio2Monitor #define HAL_PWR_PVD_PVM_IRQHandler HAL_PWREx_PVD_PVM_IRQHandler #define HAL_PWR_PVDLevelConfig HAL_PWR_ConfigPVD #define HAL_PWR_Vddio2Monitor_IRQHandler HAL_PWREx_Vddio2Monitor_IRQHandler #define HAL_PWR_Vddio2MonitorCallback HAL_PWREx_Vddio2MonitorCallback #define HAL_PWREx_ActivateOverDrive HAL_PWREx_EnableOverDrive #define HAL_PWREx_DeactivateOverDrive HAL_PWREx_DisableOverDrive #define HAL_PWREx_DisableSDADCAnalog HAL_PWREx_DisableSDADC #define HAL_PWREx_EnableSDADCAnalog HAL_PWREx_EnableSDADC #define HAL_PWREx_PVMConfig HAL_PWREx_ConfigPVM #define PWR_MODE_NORMAL PWR_PVD_MODE_NORMAL #define PWR_MODE_IT_RISING PWR_PVD_MODE_IT_RISING #define PWR_MODE_IT_FALLING PWR_PVD_MODE_IT_FALLING #define PWR_MODE_IT_RISING_FALLING PWR_PVD_MODE_IT_RISING_FALLING #define PWR_MODE_EVENT_RISING PWR_PVD_MODE_EVENT_RISING #define PWR_MODE_EVENT_FALLING PWR_PVD_MODE_EVENT_FALLING #define PWR_MODE_EVENT_RISING_FALLING PWR_PVD_MODE_EVENT_RISING_FALLING #define CR_OFFSET_BB PWR_CR_OFFSET_BB #define CSR_OFFSET_BB PWR_CSR_OFFSET_BB #define DBP_BitNumber DBP_BIT_NUMBER #define PVDE_BitNumber PVDE_BIT_NUMBER #define PMODE_BitNumber PMODE_BIT_NUMBER #define EWUP_BitNumber EWUP_BIT_NUMBER #define FPDS_BitNumber FPDS_BIT_NUMBER #define ODEN_BitNumber ODEN_BIT_NUMBER #define ODSWEN_BitNumber ODSWEN_BIT_NUMBER #define MRLVDS_BitNumber MRLVDS_BIT_NUMBER #define LPLVDS_BitNumber LPLVDS_BIT_NUMBER #define BRE_BitNumber BRE_BIT_NUMBER #define PWR_MODE_EVT PWR_PVD_MODE_NORMAL /** * @} */ /** @defgroup HAL_SMBUS_Aliased_Functions HAL SMBUS Aliased Functions maintained for legacy purpose * @{ */ #define HAL_SMBUS_Slave_Listen_IT HAL_SMBUS_EnableListen_IT #define HAL_SMBUS_SlaveAddrCallback HAL_SMBUS_AddrCallback #define HAL_SMBUS_SlaveListenCpltCallback HAL_SMBUS_ListenCpltCallback /** * @} */ /** @defgroup HAL_SPI_Aliased_Functions HAL SPI Aliased Functions maintained for legacy purpose * @{ */ #define HAL_SPI_FlushRxFifo HAL_SPIEx_FlushRxFifo /** * @} */ /** @defgroup HAL_TIM_Aliased_Functions HAL TIM Aliased Functions maintained for legacy purpose * @{ */ #define HAL_TIM_DMADelayPulseCplt TIM_DMADelayPulseCplt #define HAL_TIM_DMAError TIM_DMAError #define HAL_TIM_DMACaptureCplt TIM_DMACaptureCplt #define HAL_TIMEx_DMACommutationCplt TIMEx_DMACommutationCplt /** * @} */ /** @defgroup HAL_UART_Aliased_Functions HAL UART Aliased Functions maintained for legacy purpose * @{ */ #define HAL_UART_WakeupCallback HAL_UARTEx_WakeupCallback /** * @} */ /** @defgroup HAL_LTDC_Aliased_Functions HAL LTDC Aliased Functions maintained for legacy purpose * @{ */ #define HAL_LTDC_LineEvenCallback HAL_LTDC_LineEventCallback /** * @} */ /** @defgroup HAL_PPP_Aliased_Functions HAL PPP Aliased Functions maintained for legacy purpose * @{ */ /** * @} */ /* Exported macros ------------------------------------------------------------*/ /** @defgroup HAL_AES_Aliased_Macros HAL CRYP Aliased Macros maintained for legacy purpose * @{ */ #define AES_IT_CC CRYP_IT_CC #define AES_IT_ERR CRYP_IT_ERR #define AES_FLAG_CCF CRYP_FLAG_CCF /** * @} */ /** @defgroup HAL_Aliased_Macros HAL Generic Aliased Macros maintained for legacy purpose * @{ */ #define __HAL_GET_BOOT_MODE __HAL_SYSCFG_GET_BOOT_MODE #define __HAL_REMAPMEMORY_FLASH __HAL_SYSCFG_REMAPMEMORY_FLASH #define __HAL_REMAPMEMORY_SYSTEMFLASH __HAL_SYSCFG_REMAPMEMORY_SYSTEMFLASH #define __HAL_REMAPMEMORY_SRAM __HAL_SYSCFG_REMAPMEMORY_SRAM #define __HAL_REMAPMEMORY_FMC __HAL_SYSCFG_REMAPMEMORY_FMC #define __HAL_REMAPMEMORY_FMC_SDRAM __HAL_SYSCFG_REMAPMEMORY_FMC_SDRAM #define __HAL_REMAPMEMORY_FSMC __HAL_SYSCFG_REMAPMEMORY_FSMC #define __HAL_REMAPMEMORY_QUADSPI __HAL_SYSCFG_REMAPMEMORY_QUADSPI #define __HAL_FMC_BANK __HAL_SYSCFG_FMC_BANK #define __HAL_GET_FLAG __HAL_SYSCFG_GET_FLAG #define __HAL_CLEAR_FLAG __HAL_SYSCFG_CLEAR_FLAG #define __HAL_VREFINT_OUT_ENABLE __HAL_SYSCFG_VREFINT_OUT_ENABLE #define __HAL_VREFINT_OUT_DISABLE __HAL_SYSCFG_VREFINT_OUT_DISABLE #define SYSCFG_FLAG_VREF_READY SYSCFG_FLAG_VREFINT_READY #define SYSCFG_FLAG_RC48 RCC_FLAG_HSI48 #define IS_SYSCFG_FASTMODEPLUS_CONFIG IS_I2C_FASTMODEPLUS #define UFB_MODE_BitNumber UFB_MODE_BIT_NUMBER #define CMP_PD_BitNumber CMP_PD_BIT_NUMBER /** * @} */ /** @defgroup HAL_ADC_Aliased_Macros HAL ADC Aliased Macros maintained for legacy purpose * @{ */ #define __ADC_ENABLE __HAL_ADC_ENABLE #define __ADC_DISABLE __HAL_ADC_DISABLE #define __HAL_ADC_ENABLING_CONDITIONS ADC_ENABLING_CONDITIONS #define __HAL_ADC_DISABLING_CONDITIONS ADC_DISABLING_CONDITIONS #define __HAL_ADC_IS_ENABLED ADC_IS_ENABLE #define __ADC_IS_ENABLED ADC_IS_ENABLE #define __HAL_ADC_IS_SOFTWARE_START_REGULAR ADC_IS_SOFTWARE_START_REGULAR #define __HAL_ADC_IS_SOFTWARE_START_INJECTED ADC_IS_SOFTWARE_START_INJECTED #define __HAL_ADC_IS_CONVERSION_ONGOING_REGULAR_INJECTED ADC_IS_CONVERSION_ONGOING_REGULAR_INJECTED #define __HAL_ADC_IS_CONVERSION_ONGOING_REGULAR ADC_IS_CONVERSION_ONGOING_REGULAR #define __HAL_ADC_IS_CONVERSION_ONGOING_INJECTED ADC_IS_CONVERSION_ONGOING_INJECTED #define __HAL_ADC_IS_CONVERSION_ONGOING ADC_IS_CONVERSION_ONGOING #define __HAL_ADC_CLEAR_ERRORCODE ADC_CLEAR_ERRORCODE #define __HAL_ADC_GET_RESOLUTION ADC_GET_RESOLUTION #define __HAL_ADC_JSQR_RK ADC_JSQR_RK #define __HAL_ADC_CFGR_AWD1CH ADC_CFGR_AWD1CH_SHIFT #define __HAL_ADC_CFGR_AWD23CR ADC_CFGR_AWD23CR #define __HAL_ADC_CFGR_INJECT_AUTO_CONVERSION ADC_CFGR_INJECT_AUTO_CONVERSION #define __HAL_ADC_CFGR_INJECT_CONTEXT_QUEUE ADC_CFGR_INJECT_CONTEXT_QUEUE #define __HAL_ADC_CFGR_INJECT_DISCCONTINUOUS ADC_CFGR_INJECT_DISCCONTINUOUS #define __HAL_ADC_CFGR_REG_DISCCONTINUOUS ADC_CFGR_REG_DISCCONTINUOUS #define __HAL_ADC_CFGR_DISCONTINUOUS_NUM ADC_CFGR_DISCONTINUOUS_NUM #define __HAL_ADC_CFGR_AUTOWAIT ADC_CFGR_AUTOWAIT #define __HAL_ADC_CFGR_CONTINUOUS ADC_CFGR_CONTINUOUS #define __HAL_ADC_CFGR_OVERRUN ADC_CFGR_OVERRUN #define __HAL_ADC_CFGR_DMACONTREQ ADC_CFGR_DMACONTREQ #define __HAL_ADC_CFGR_EXTSEL ADC_CFGR_EXTSEL_SET #define __HAL_ADC_JSQR_JEXTSEL ADC_JSQR_JEXTSEL_SET #define __HAL_ADC_OFR_CHANNEL ADC_OFR_CHANNEL #define __HAL_ADC_DIFSEL_CHANNEL ADC_DIFSEL_CHANNEL #define __HAL_ADC_CALFACT_DIFF_SET ADC_CALFACT_DIFF_SET #define __HAL_ADC_CALFACT_DIFF_GET ADC_CALFACT_DIFF_GET #define __HAL_ADC_TRX_HIGHTHRESHOLD ADC_TRX_HIGHTHRESHOLD #define __HAL_ADC_OFFSET_SHIFT_RESOLUTION ADC_OFFSET_SHIFT_RESOLUTION #define __HAL_ADC_AWD1THRESHOLD_SHIFT_RESOLUTION ADC_AWD1THRESHOLD_SHIFT_RESOLUTION #define __HAL_ADC_AWD23THRESHOLD_SHIFT_RESOLUTION ADC_AWD23THRESHOLD_SHIFT_RESOLUTION #define __HAL_ADC_COMMON_REGISTER ADC_COMMON_REGISTER #define __HAL_ADC_COMMON_CCR_MULTI ADC_COMMON_CCR_MULTI #define __HAL_ADC_MULTIMODE_IS_ENABLED ADC_MULTIMODE_IS_ENABLE #define __ADC_MULTIMODE_IS_ENABLED ADC_MULTIMODE_IS_ENABLE #define __HAL_ADC_NONMULTIMODE_OR_MULTIMODEMASTER ADC_NONMULTIMODE_OR_MULTIMODEMASTER #define __HAL_ADC_COMMON_ADC_OTHER ADC_COMMON_ADC_OTHER #define __HAL_ADC_MULTI_SLAVE ADC_MULTI_SLAVE #define __HAL_ADC_SQR1_L ADC_SQR1_L_SHIFT #define __HAL_ADC_JSQR_JL ADC_JSQR_JL_SHIFT #define __HAL_ADC_JSQR_RK_JL ADC_JSQR_RK_JL #define __HAL_ADC_CR1_DISCONTINUOUS_NUM ADC_CR1_DISCONTINUOUS_NUM #define __HAL_ADC_CR1_SCAN ADC_CR1_SCAN_SET #define __HAL_ADC_CONVCYCLES_MAX_RANGE ADC_CONVCYCLES_MAX_RANGE #define __HAL_ADC_CLOCK_PRESCALER_RANGE ADC_CLOCK_PRESCALER_RANGE #define __HAL_ADC_GET_CLOCK_PRESCALER ADC_GET_CLOCK_PRESCALER #define __HAL_ADC_SQR1 ADC_SQR1 #define __HAL_ADC_SMPR1 ADC_SMPR1 #define __HAL_ADC_SMPR2 ADC_SMPR2 #define __HAL_ADC_SQR3_RK ADC_SQR3_RK #define __HAL_ADC_SQR2_RK ADC_SQR2_RK #define __HAL_ADC_SQR1_RK ADC_SQR1_RK #define __HAL_ADC_CR2_CONTINUOUS ADC_CR2_CONTINUOUS #define __HAL_ADC_CR1_DISCONTINUOUS ADC_CR1_DISCONTINUOUS #define __HAL_ADC_CR1_SCANCONV ADC_CR1_SCANCONV #define __HAL_ADC_CR2_EOCSelection ADC_CR2_EOCSelection #define __HAL_ADC_CR2_DMAContReq ADC_CR2_DMAContReq #define __HAL_ADC_GET_RESOLUTION ADC_GET_RESOLUTION #define __HAL_ADC_JSQR ADC_JSQR #define __HAL_ADC_CHSELR_CHANNEL ADC_CHSELR_CHANNEL #define __HAL_ADC_CFGR1_REG_DISCCONTINUOUS ADC_CFGR1_REG_DISCCONTINUOUS #define __HAL_ADC_CFGR1_AUTOOFF ADC_CFGR1_AUTOOFF #define __HAL_ADC_CFGR1_AUTOWAIT ADC_CFGR1_AUTOWAIT #define __HAL_ADC_CFGR1_CONTINUOUS ADC_CFGR1_CONTINUOUS #define __HAL_ADC_CFGR1_OVERRUN ADC_CFGR1_OVERRUN #define __HAL_ADC_CFGR1_SCANDIR ADC_CFGR1_SCANDIR #define __HAL_ADC_CFGR1_DMACONTREQ ADC_CFGR1_DMACONTREQ /** * @} */ /** @defgroup HAL_DAC_Aliased_Macros HAL DAC Aliased Macros maintained for legacy purpose * @{ */ #define __HAL_DHR12R1_ALIGNEMENT DAC_DHR12R1_ALIGNMENT #define __HAL_DHR12R2_ALIGNEMENT DAC_DHR12R2_ALIGNMENT #define __HAL_DHR12RD_ALIGNEMENT DAC_DHR12RD_ALIGNMENT #define IS_DAC_GENERATE_WAVE IS_DAC_WAVE /** * @} */ /** @defgroup HAL_DBGMCU_Aliased_Macros HAL DBGMCU Aliased Macros maintained for legacy purpose * @{ */ #define __HAL_FREEZE_TIM1_DBGMCU __HAL_DBGMCU_FREEZE_TIM1 #define __HAL_UNFREEZE_TIM1_DBGMCU __HAL_DBGMCU_UNFREEZE_TIM1 #define __HAL_FREEZE_TIM2_DBGMCU __HAL_DBGMCU_FREEZE_TIM2 #define __HAL_UNFREEZE_TIM2_DBGMCU __HAL_DBGMCU_UNFREEZE_TIM2 #define __HAL_FREEZE_TIM3_DBGMCU __HAL_DBGMCU_FREEZE_TIM3 #define __HAL_UNFREEZE_TIM3_DBGMCU __HAL_DBGMCU_UNFREEZE_TIM3 #define __HAL_FREEZE_TIM4_DBGMCU __HAL_DBGMCU_FREEZE_TIM4 #define __HAL_UNFREEZE_TIM4_DBGMCU __HAL_DBGMCU_UNFREEZE_TIM4 #define __HAL_FREEZE_TIM5_DBGMCU __HAL_DBGMCU_FREEZE_TIM5 #define __HAL_UNFREEZE_TIM5_DBGMCU __HAL_DBGMCU_UNFREEZE_TIM5 #define __HAL_FREEZE_TIM6_DBGMCU __HAL_DBGMCU_FREEZE_TIM6 #define __HAL_UNFREEZE_TIM6_DBGMCU __HAL_DBGMCU_UNFREEZE_TIM6 #define __HAL_FREEZE_TIM7_DBGMCU __HAL_DBGMCU_FREEZE_TIM7 #define __HAL_UNFREEZE_TIM7_DBGMCU __HAL_DBGMCU_UNFREEZE_TIM7 #define __HAL_FREEZE_TIM8_DBGMCU __HAL_DBGMCU_FREEZE_TIM8 #define __HAL_UNFREEZE_TIM8_DBGMCU __HAL_DBGMCU_UNFREEZE_TIM8 #define __HAL_FREEZE_TIM9_DBGMCU __HAL_DBGMCU_FREEZE_TIM9 #define __HAL_UNFREEZE_TIM9_DBGMCU __HAL_DBGMCU_UNFREEZE_TIM9 #define __HAL_FREEZE_TIM10_DBGMCU __HAL_DBGMCU_FREEZE_TIM10 #define __HAL_UNFREEZE_TIM10_DBGMCU __HAL_DBGMCU_UNFREEZE_TIM10 #define __HAL_FREEZE_TIM11_DBGMCU __HAL_DBGMCU_FREEZE_TIM11 #define __HAL_UNFREEZE_TIM11_DBGMCU __HAL_DBGMCU_UNFREEZE_TIM11 #define __HAL_FREEZE_TIM12_DBGMCU __HAL_DBGMCU_FREEZE_TIM12 #define __HAL_UNFREEZE_TIM12_DBGMCU __HAL_DBGMCU_UNFREEZE_TIM12 #define __HAL_FREEZE_TIM13_DBGMCU __HAL_DBGMCU_FREEZE_TIM13 #define __HAL_UNFREEZE_TIM13_DBGMCU __HAL_DBGMCU_UNFREEZE_TIM13 #define __HAL_FREEZE_TIM14_DBGMCU __HAL_DBGMCU_FREEZE_TIM14 #define __HAL_UNFREEZE_TIM14_DBGMCU __HAL_DBGMCU_UNFREEZE_TIM14 #define __HAL_FREEZE_CAN2_DBGMCU __HAL_DBGMCU_FREEZE_CAN2 #define __HAL_UNFREEZE_CAN2_DBGMCU __HAL_DBGMCU_UNFREEZE_CAN2 #define __HAL_FREEZE_TIM15_DBGMCU __HAL_DBGMCU_FREEZE_TIM15 #define __HAL_UNFREEZE_TIM15_DBGMCU __HAL_DBGMCU_UNFREEZE_TIM15 #define __HAL_FREEZE_TIM16_DBGMCU __HAL_DBGMCU_FREEZE_TIM16 #define __HAL_UNFREEZE_TIM16_DBGMCU __HAL_DBGMCU_UNFREEZE_TIM16 #define __HAL_FREEZE_TIM17_DBGMCU __HAL_DBGMCU_FREEZE_TIM17 #define __HAL_UNFREEZE_TIM17_DBGMCU __HAL_DBGMCU_UNFREEZE_TIM17 #define __HAL_FREEZE_RTC_DBGMCU __HAL_DBGMCU_FREEZE_RTC #define __HAL_UNFREEZE_RTC_DBGMCU __HAL_DBGMCU_UNFREEZE_RTC #define __HAL_FREEZE_WWDG_DBGMCU __HAL_DBGMCU_FREEZE_WWDG #define __HAL_UNFREEZE_WWDG_DBGMCU __HAL_DBGMCU_UNFREEZE_WWDG #define __HAL_FREEZE_IWDG_DBGMCU __HAL_DBGMCU_FREEZE_IWDG #define __HAL_UNFREEZE_IWDG_DBGMCU __HAL_DBGMCU_UNFREEZE_IWDG #define __HAL_FREEZE_I2C1_TIMEOUT_DBGMCU __HAL_DBGMCU_FREEZE_I2C1_TIMEOUT #define __HAL_UNFREEZE_I2C1_TIMEOUT_DBGMCU __HAL_DBGMCU_UNFREEZE_I2C1_TIMEOUT #define __HAL_FREEZE_I2C2_TIMEOUT_DBGMCU __HAL_DBGMCU_FREEZE_I2C2_TIMEOUT #define __HAL_UNFREEZE_I2C2_TIMEOUT_DBGMCU __HAL_DBGMCU_UNFREEZE_I2C2_TIMEOUT #define __HAL_FREEZE_I2C3_TIMEOUT_DBGMCU __HAL_DBGMCU_FREEZE_I2C3_TIMEOUT #define __HAL_UNFREEZE_I2C3_TIMEOUT_DBGMCU __HAL_DBGMCU_UNFREEZE_I2C3_TIMEOUT #define __HAL_FREEZE_CAN1_DBGMCU __HAL_DBGMCU_FREEZE_CAN1 #define __HAL_UNFREEZE_CAN1_DBGMCU __HAL_DBGMCU_UNFREEZE_CAN1 #define __HAL_FREEZE_LPTIM1_DBGMCU __HAL_DBGMCU_FREEZE_LPTIM1 #define __HAL_UNFREEZE_LPTIM1_DBGMCU __HAL_DBGMCU_UNFREEZE_LPTIM1 #define __HAL_FREEZE_LPTIM2_DBGMCU __HAL_DBGMCU_FREEZE_LPTIM2 #define __HAL_UNFREEZE_LPTIM2_DBGMCU __HAL_DBGMCU_UNFREEZE_LPTIM2 /** * @} */ /** @defgroup HAL_COMP_Aliased_Macros HAL COMP Aliased Macros maintained for legacy purpose * @{ */ #define __HAL_COMP_EXTI_RISING_IT_ENABLE(__EXTILINE__) (((__EXTILINE__) == COMP_EXTI_LINE_COMP1) ? __HAL_COMP_COMP1_EXTI_ENABLE_RISING_EDGE() : \ __HAL_COMP_COMP2_EXTI_ENABLE_RISING_EDGE()) #define __HAL_COMP_EXTI_RISING_IT_DISABLE(__EXTILINE__) (((__EXTILINE__) == COMP_EXTI_LINE_COMP1) ? __HAL_COMP_COMP1_EXTI_ENABLE_RISING_EDGE() : \ __HAL_COMP_COMP2_EXTI_DISABLE_RISING_EDGE()) #define __HAL_COMP_EXTI_FALLING_IT_ENABLE(__EXTILINE__) (((__EXTILINE__) == COMP_EXTI_LINE_COMP1) ? __HAL_COMP_COMP1_EXTI_ENABLE_FALLING_EDGE() : \ __HAL_COMP_COMP2_EXTI_ENABLE_FALLING_EDGE()) #define __HAL_COMP_EXTI_FALLING_IT_DISABLE(__EXTILINE__) (((__EXTILINE__) == COMP_EXTI_LINE_COMP1) ? __HAL_COMP_COMP1_EXTI_ENABLE_FALLING_EDGE() : \ __HAL_COMP_COMP2_EXTI_DISABLE_FALLING_EDGE()) #define __HAL_COMP_EXTI_ENABLE_IT(__EXTILINE__) (((__EXTILINE__) == COMP_EXTI_LINE_COMP1) ? __HAL_COMP_COMP1_EXTI_ENABLE_IT() : \ __HAL_COMP_COMP2_EXTI_ENABLE_IT()) #define __HAL_COMP_EXTI_DISABLE_IT(__EXTILINE__) (((__EXTILINE__) == COMP_EXTI_LINE_COMP1) ? __HAL_COMP_COMP1_EXTI_DISABLE_IT() : \ __HAL_COMP_COMP2_EXTI_DISABLE_IT()) #define __HAL_COMP_EXTI_GET_FLAG(__FLAG__) (((__FLAG__) == COMP_EXTI_LINE_COMP1) ? __HAL_COMP_COMP1_EXTI_GET_FLAG() : \ __HAL_COMP_COMP2_EXTI_GET_FLAG()) #define __HAL_COMP_EXTI_CLEAR_FLAG(__FLAG__) (((__FLAG__) == COMP_EXTI_LINE_COMP1) ? __HAL_COMP_COMP1_EXTI_CLEAR_FLAG() : \ __HAL_COMP_COMP2_EXTI_CLEAR_FLAG()) #define __HAL_COMP_GET_EXTI_LINE COMP_GET_EXTI_LINE /** * @} */ /** @defgroup HAL_DAC_Aliased_Macros HAL DAC Aliased Macros maintained for legacy purpose * @{ */ #define IS_DAC_WAVE(WAVE) (((WAVE) == DAC_WAVE_NONE) || \ ((WAVE) == DAC_WAVE_NOISE)|| \ ((WAVE) == DAC_WAVE_TRIANGLE)) /** * @} */ /** @defgroup HAL_FLASH_Aliased_Macros HAL FLASH Aliased Macros maintained for legacy purpose * @{ */ #define IS_WRPAREA IS_OB_WRPAREA #define IS_TYPEPROGRAM IS_FLASH_TYPEPROGRAM #define IS_TYPEPROGRAMFLASH IS_FLASH_TYPEPROGRAM #define IS_TYPEERASE IS_FLASH_TYPEERASE #define IS_NBSECTORS IS_FLASH_NBSECTORS #define IS_OB_WDG_SOURCE IS_OB_IWDG_SOURCE /** * @} */ /** @defgroup HAL_I2C_Aliased_Macros HAL I2C Aliased Macros maintained for legacy purpose * @{ */ #define __HAL_I2C_RESET_CR2 I2C_RESET_CR2 #define __HAL_I2C_GENERATE_START I2C_GENERATE_START #define __HAL_I2C_FREQ_RANGE I2C_FREQ_RANGE #define __HAL_I2C_RISE_TIME I2C_RISE_TIME #define __HAL_I2C_SPEED_STANDARD I2C_SPEED_STANDARD #define __HAL_I2C_SPEED_FAST I2C_SPEED_FAST #define __HAL_I2C_SPEED I2C_SPEED #define __HAL_I2C_7BIT_ADD_WRITE I2C_7BIT_ADD_WRITE #define __HAL_I2C_7BIT_ADD_READ I2C_7BIT_ADD_READ #define __HAL_I2C_10BIT_ADDRESS I2C_10BIT_ADDRESS #define __HAL_I2C_10BIT_HEADER_WRITE I2C_10BIT_HEADER_WRITE #define __HAL_I2C_10BIT_HEADER_READ I2C_10BIT_HEADER_READ #define __HAL_I2C_MEM_ADD_MSB I2C_MEM_ADD_MSB #define __HAL_I2C_MEM_ADD_LSB I2C_MEM_ADD_LSB #define __HAL_I2C_FREQRANGE I2C_FREQRANGE /** * @} */ /** @defgroup HAL_I2S_Aliased_Macros HAL I2S Aliased Macros maintained for legacy purpose * @{ */ #define IS_I2S_INSTANCE IS_I2S_ALL_INSTANCE #define IS_I2S_INSTANCE_EXT IS_I2S_ALL_INSTANCE_EXT /** * @} */ /** @defgroup HAL_IRDA_Aliased_Macros HAL IRDA Aliased Macros maintained for legacy purpose * @{ */ #define __IRDA_DISABLE __HAL_IRDA_DISABLE #define __IRDA_ENABLE __HAL_IRDA_ENABLE #define __HAL_IRDA_GETCLOCKSOURCE IRDA_GETCLOCKSOURCE #define __HAL_IRDA_MASK_COMPUTATION IRDA_MASK_COMPUTATION #define __IRDA_GETCLOCKSOURCE IRDA_GETCLOCKSOURCE #define __IRDA_MASK_COMPUTATION IRDA_MASK_COMPUTATION #define IS_IRDA_ONEBIT_SAMPLE IS_IRDA_ONE_BIT_SAMPLE /** * @} */ /** @defgroup HAL_IWDG_Aliased_Macros HAL IWDG Aliased Macros maintained for legacy purpose * @{ */ #define __HAL_IWDG_ENABLE_WRITE_ACCESS IWDG_ENABLE_WRITE_ACCESS #define __HAL_IWDG_DISABLE_WRITE_ACCESS IWDG_DISABLE_WRITE_ACCESS /** * @} */ /** @defgroup HAL_LPTIM_Aliased_Macros HAL LPTIM Aliased Macros maintained for legacy purpose * @{ */ #define __HAL_LPTIM_ENABLE_INTERRUPT __HAL_LPTIM_ENABLE_IT #define __HAL_LPTIM_DISABLE_INTERRUPT __HAL_LPTIM_DISABLE_IT #define __HAL_LPTIM_GET_ITSTATUS __HAL_LPTIM_GET_IT_SOURCE /** * @} */ /** @defgroup HAL_OPAMP_Aliased_Macros HAL OPAMP Aliased Macros maintained for legacy purpose * @{ */ #define __OPAMP_CSR_OPAXPD OPAMP_CSR_OPAXPD #define __OPAMP_CSR_S3SELX OPAMP_CSR_S3SELX #define __OPAMP_CSR_S4SELX OPAMP_CSR_S4SELX #define __OPAMP_CSR_S5SELX OPAMP_CSR_S5SELX #define __OPAMP_CSR_S6SELX OPAMP_CSR_S6SELX #define __OPAMP_CSR_OPAXCAL_L OPAMP_CSR_OPAXCAL_L #define __OPAMP_CSR_OPAXCAL_H OPAMP_CSR_OPAXCAL_H #define __OPAMP_CSR_OPAXLPM OPAMP_CSR_OPAXLPM #define __OPAMP_CSR_ALL_SWITCHES OPAMP_CSR_ALL_SWITCHES #define __OPAMP_CSR_ANAWSELX OPAMP_CSR_ANAWSELX #define __OPAMP_CSR_OPAXCALOUT OPAMP_CSR_OPAXCALOUT #define __OPAMP_OFFSET_TRIM_BITSPOSITION OPAMP_OFFSET_TRIM_BITSPOSITION #define __OPAMP_OFFSET_TRIM_SET OPAMP_OFFSET_TRIM_SET /** * @} */ /** @defgroup HAL_PWR_Aliased_Macros HAL PWR Aliased Macros maintained for legacy purpose * @{ */ #define __HAL_PVD_EVENT_DISABLE __HAL_PWR_PVD_EXTI_DISABLE_EVENT #define __HAL_PVD_EVENT_ENABLE __HAL_PWR_PVD_EXTI_ENABLE_EVENT #define __HAL_PVD_EXTI_FALLINGTRIGGER_DISABLE __HAL_PWR_PVD_EXTI_DISABLE_FALLING_EDGE #define __HAL_PVD_EXTI_FALLINGTRIGGER_ENABLE __HAL_PWR_PVD_EXTI_ENABLE_FALLING_EDGE #define __HAL_PVD_EXTI_RISINGTRIGGER_DISABLE __HAL_PWR_PVD_EXTI_DISABLE_RISING_EDGE #define __HAL_PVD_EXTI_RISINGTRIGGER_ENABLE __HAL_PWR_PVD_EXTI_ENABLE_RISING_EDGE #define __HAL_PVM_EVENT_DISABLE __HAL_PWR_PVM_EVENT_DISABLE #define __HAL_PVM_EVENT_ENABLE __HAL_PWR_PVM_EVENT_ENABLE #define __HAL_PVM_EXTI_FALLINGTRIGGER_DISABLE __HAL_PWR_PVM_EXTI_FALLINGTRIGGER_DISABLE #define __HAL_PVM_EXTI_FALLINGTRIGGER_ENABLE __HAL_PWR_PVM_EXTI_FALLINGTRIGGER_ENABLE #define __HAL_PVM_EXTI_RISINGTRIGGER_DISABLE __HAL_PWR_PVM_EXTI_RISINGTRIGGER_DISABLE #define __HAL_PVM_EXTI_RISINGTRIGGER_ENABLE __HAL_PWR_PVM_EXTI_RISINGTRIGGER_ENABLE #define __HAL_PWR_INTERNALWAKEUP_DISABLE HAL_PWREx_DisableInternalWakeUpLine #define __HAL_PWR_INTERNALWAKEUP_ENABLE HAL_PWREx_EnableInternalWakeUpLine #define __HAL_PWR_PULL_UP_DOWN_CONFIG_DISABLE HAL_PWREx_DisablePullUpPullDownConfig #define __HAL_PWR_PULL_UP_DOWN_CONFIG_ENABLE HAL_PWREx_EnablePullUpPullDownConfig #define __HAL_PWR_PVD_EXTI_CLEAR_EGDE_TRIGGER() __HAL_PWR_PVD_EXTI_DISABLE_RISING_EDGE();__HAL_PWR_PVD_EXTI_DISABLE_FALLING_EDGE() #define __HAL_PWR_PVD_EXTI_EVENT_DISABLE __HAL_PWR_PVD_EXTI_DISABLE_EVENT #define __HAL_PWR_PVD_EXTI_EVENT_ENABLE __HAL_PWR_PVD_EXTI_ENABLE_EVENT #define __HAL_PWR_PVD_EXTI_FALLINGTRIGGER_DISABLE __HAL_PWR_PVD_EXTI_DISABLE_FALLING_EDGE #define __HAL_PWR_PVD_EXTI_FALLINGTRIGGER_ENABLE __HAL_PWR_PVD_EXTI_ENABLE_FALLING_EDGE #define __HAL_PWR_PVD_EXTI_RISINGTRIGGER_DISABLE __HAL_PWR_PVD_EXTI_DISABLE_RISING_EDGE #define __HAL_PWR_PVD_EXTI_RISINGTRIGGER_ENABLE __HAL_PWR_PVD_EXTI_ENABLE_RISING_EDGE #define __HAL_PWR_PVD_EXTI_SET_FALLING_EGDE_TRIGGER __HAL_PWR_PVD_EXTI_ENABLE_FALLING_EDGE #define __HAL_PWR_PVD_EXTI_SET_RISING_EDGE_TRIGGER __HAL_PWR_PVD_EXTI_ENABLE_RISING_EDGE #define __HAL_PWR_PVM_DISABLE() HAL_PWREx_DisablePVM1();HAL_PWREx_DisablePVM2();HAL_PWREx_DisablePVM3();HAL_PWREx_DisablePVM4() #define __HAL_PWR_PVM_ENABLE() HAL_PWREx_EnablePVM1();HAL_PWREx_EnablePVM2();HAL_PWREx_EnablePVM3();HAL_PWREx_EnablePVM4() #define __HAL_PWR_SRAM2CONTENT_PRESERVE_DISABLE HAL_PWREx_DisableSRAM2ContentRetention #define __HAL_PWR_SRAM2CONTENT_PRESERVE_ENABLE HAL_PWREx_EnableSRAM2ContentRetention #define __HAL_PWR_VDDIO2_DISABLE HAL_PWREx_DisableVddIO2 #define __HAL_PWR_VDDIO2_ENABLE HAL_PWREx_EnableVddIO2 #define __HAL_PWR_VDDIO2_EXTI_CLEAR_EGDE_TRIGGER __HAL_PWR_VDDIO2_EXTI_DISABLE_FALLING_EDGE #define __HAL_PWR_VDDIO2_EXTI_SET_FALLING_EGDE_TRIGGER __HAL_PWR_VDDIO2_EXTI_ENABLE_FALLING_EDGE #define __HAL_PWR_VDDUSB_DISABLE HAL_PWREx_DisableVddUSB #define __HAL_PWR_VDDUSB_ENABLE HAL_PWREx_EnableVddUSB #if defined (STM32F4) #define __HAL_PVD_EXTI_ENABLE_IT(PWR_EXTI_LINE_PVD) __HAL_PWR_PVD_EXTI_ENABLE_IT() #define __HAL_PVD_EXTI_DISABLE_IT(PWR_EXTI_LINE_PVD) __HAL_PWR_PVD_EXTI_DISABLE_IT() #define __HAL_PVD_EXTI_GET_FLAG(PWR_EXTI_LINE_PVD) __HAL_PWR_PVD_EXTI_GET_FLAG() #define __HAL_PVD_EXTI_CLEAR_FLAG(PWR_EXTI_LINE_PVD) __HAL_PWR_PVD_EXTI_CLEAR_FLAG() #define __HAL_PVD_EXTI_GENERATE_SWIT(PWR_EXTI_LINE_PVD) __HAL_PWR_PVD_EXTI_GENERATE_SWIT() #else #define __HAL_PVD_EXTI_CLEAR_FLAG __HAL_PWR_PVD_EXTI_CLEAR_FLAG #define __HAL_PVD_EXTI_DISABLE_IT __HAL_PWR_PVD_EXTI_DISABLE_IT #define __HAL_PVD_EXTI_ENABLE_IT __HAL_PWR_PVD_EXTI_ENABLE_IT #define __HAL_PVD_EXTI_GENERATE_SWIT __HAL_PWR_PVD_EXTI_GENERATE_SWIT #define __HAL_PVD_EXTI_GET_FLAG __HAL_PWR_PVD_EXTI_GET_FLAG #endif /* STM32F4 */ /** * @} */ /** @defgroup HAL_RCC_Aliased HAL RCC Aliased maintained for legacy purpose * @{ */ #define RCC_StopWakeUpClock_MSI RCC_STOP_WAKEUPCLOCK_MSI #define RCC_StopWakeUpClock_HSI RCC_STOP_WAKEUPCLOCK_HSI #define HAL_RCC_CCSCallback HAL_RCC_CSSCallback #define HAL_RC48_EnableBuffer_Cmd(cmd) (((cmd)==ENABLE) ? HAL_RCCEx_EnableHSI48_VREFINT() : HAL_RCCEx_DisableHSI48_VREFINT()) #define __ADC_CLK_DISABLE __HAL_RCC_ADC_CLK_DISABLE #define __ADC_CLK_ENABLE __HAL_RCC_ADC_CLK_ENABLE #define __ADC_CLK_SLEEP_DISABLE __HAL_RCC_ADC_CLK_SLEEP_DISABLE #define __ADC_CLK_SLEEP_ENABLE __HAL_RCC_ADC_CLK_SLEEP_ENABLE #define __ADC_FORCE_RESET __HAL_RCC_ADC_FORCE_RESET #define __ADC_RELEASE_RESET __HAL_RCC_ADC_RELEASE_RESET #define __ADC1_CLK_DISABLE __HAL_RCC_ADC1_CLK_DISABLE #define __ADC1_CLK_ENABLE __HAL_RCC_ADC1_CLK_ENABLE #define __ADC1_FORCE_RESET __HAL_RCC_ADC1_FORCE_RESET #define __ADC1_RELEASE_RESET __HAL_RCC_ADC1_RELEASE_RESET #define __ADC1_CLK_SLEEP_ENABLE __HAL_RCC_ADC1_CLK_SLEEP_ENABLE #define __ADC1_CLK_SLEEP_DISABLE __HAL_RCC_ADC1_CLK_SLEEP_DISABLE #define __ADC2_CLK_DISABLE __HAL_RCC_ADC2_CLK_DISABLE #define __ADC2_CLK_ENABLE __HAL_RCC_ADC2_CLK_ENABLE #define __ADC2_FORCE_RESET __HAL_RCC_ADC2_FORCE_RESET #define __ADC2_RELEASE_RESET __HAL_RCC_ADC2_RELEASE_RESET #define __ADC3_CLK_DISABLE __HAL_RCC_ADC3_CLK_DISABLE #define __ADC3_CLK_ENABLE __HAL_RCC_ADC3_CLK_ENABLE #define __ADC3_FORCE_RESET __HAL_RCC_ADC3_FORCE_RESET #define __ADC3_RELEASE_RESET __HAL_RCC_ADC3_RELEASE_RESET #define __AES_CLK_DISABLE __HAL_RCC_AES_CLK_DISABLE #define __AES_CLK_ENABLE __HAL_RCC_AES_CLK_ENABLE #define __AES_CLK_SLEEP_DISABLE __HAL_RCC_AES_CLK_SLEEP_DISABLE #define __AES_CLK_SLEEP_ENABLE __HAL_RCC_AES_CLK_SLEEP_ENABLE #define __AES_FORCE_RESET __HAL_RCC_AES_FORCE_RESET #define __AES_RELEASE_RESET __HAL_RCC_AES_RELEASE_RESET #define __CRYP_CLK_SLEEP_ENABLE __HAL_RCC_CRYP_CLK_SLEEP_ENABLE #define __CRYP_CLK_SLEEP_DISABLE __HAL_RCC_CRYP_CLK_SLEEP_DISABLE #define __CRYP_CLK_ENABLE __HAL_RCC_CRYP_CLK_ENABLE #define __CRYP_CLK_DISABLE __HAL_RCC_CRYP_CLK_DISABLE #define __CRYP_FORCE_RESET __HAL_RCC_CRYP_FORCE_RESET #define __CRYP_RELEASE_RESET __HAL_RCC_CRYP_RELEASE_RESET #define __AFIO_CLK_DISABLE __HAL_RCC_AFIO_CLK_DISABLE #define __AFIO_CLK_ENABLE __HAL_RCC_AFIO_CLK_ENABLE #define __AFIO_FORCE_RESET __HAL_RCC_AFIO_FORCE_RESET #define __AFIO_RELEASE_RESET __HAL_RCC_AFIO_RELEASE_RESET #define __AHB_FORCE_RESET __HAL_RCC_AHB_FORCE_RESET #define __AHB_RELEASE_RESET __HAL_RCC_AHB_RELEASE_RESET #define __AHB1_FORCE_RESET __HAL_RCC_AHB1_FORCE_RESET #define __AHB1_RELEASE_RESET __HAL_RCC_AHB1_RELEASE_RESET #define __AHB2_FORCE_RESET __HAL_RCC_AHB2_FORCE_RESET #define __AHB2_RELEASE_RESET __HAL_RCC_AHB2_RELEASE_RESET #define __AHB3_FORCE_RESET __HAL_RCC_AHB3_FORCE_RESET #define __AHB3_RELEASE_RESET __HAL_RCC_AHB3_RELEASE_RESET #define __APB1_FORCE_RESET __HAL_RCC_APB1_FORCE_RESET #define __APB1_RELEASE_RESET __HAL_RCC_APB1_RELEASE_RESET #define __APB2_FORCE_RESET __HAL_RCC_APB2_FORCE_RESET #define __APB2_RELEASE_RESET __HAL_RCC_APB2_RELEASE_RESET #define __BKP_CLK_DISABLE __HAL_RCC_BKP_CLK_DISABLE #define __BKP_CLK_ENABLE __HAL_RCC_BKP_CLK_ENABLE #define __BKP_FORCE_RESET __HAL_RCC_BKP_FORCE_RESET #define __BKP_RELEASE_RESET __HAL_RCC_BKP_RELEASE_RESET #define __CAN1_CLK_DISABLE __HAL_RCC_CAN1_CLK_DISABLE #define __CAN1_CLK_ENABLE __HAL_RCC_CAN1_CLK_ENABLE #define __CAN1_CLK_SLEEP_DISABLE __HAL_RCC_CAN1_CLK_SLEEP_DISABLE #define __CAN1_CLK_SLEEP_ENABLE __HAL_RCC_CAN1_CLK_SLEEP_ENABLE #define __CAN1_FORCE_RESET __HAL_RCC_CAN1_FORCE_RESET #define __CAN1_RELEASE_RESET __HAL_RCC_CAN1_RELEASE_RESET #define __CAN_CLK_DISABLE __HAL_RCC_CAN1_CLK_DISABLE #define __CAN_CLK_ENABLE __HAL_RCC_CAN1_CLK_ENABLE #define __CAN_FORCE_RESET __HAL_RCC_CAN1_FORCE_RESET #define __CAN_RELEASE_RESET __HAL_RCC_CAN1_RELEASE_RESET #define __CAN2_CLK_DISABLE __HAL_RCC_CAN2_CLK_DISABLE #define __CAN2_CLK_ENABLE __HAL_RCC_CAN2_CLK_ENABLE #define __CAN2_FORCE_RESET __HAL_RCC_CAN2_FORCE_RESET #define __CAN2_RELEASE_RESET __HAL_RCC_CAN2_RELEASE_RESET #define __CEC_CLK_DISABLE __HAL_RCC_CEC_CLK_DISABLE #define __CEC_CLK_ENABLE __HAL_RCC_CEC_CLK_ENABLE #define __COMP_CLK_DISABLE __HAL_RCC_COMP_CLK_DISABLE #define __COMP_CLK_ENABLE __HAL_RCC_COMP_CLK_ENABLE #define __COMP_FORCE_RESET __HAL_RCC_COMP_FORCE_RESET #define __COMP_RELEASE_RESET __HAL_RCC_COMP_RELEASE_RESET #define __COMP_CLK_SLEEP_ENABLE __HAL_RCC_COMP_CLK_SLEEP_ENABLE #define __COMP_CLK_SLEEP_DISABLE __HAL_RCC_COMP_CLK_SLEEP_DISABLE #define __CEC_FORCE_RESET __HAL_RCC_CEC_FORCE_RESET #define __CEC_RELEASE_RESET __HAL_RCC_CEC_RELEASE_RESET #define __CRC_CLK_DISABLE __HAL_RCC_CRC_CLK_DISABLE #define __CRC_CLK_ENABLE __HAL_RCC_CRC_CLK_ENABLE #define __CRC_CLK_SLEEP_DISABLE __HAL_RCC_CRC_CLK_SLEEP_DISABLE #define __CRC_CLK_SLEEP_ENABLE __HAL_RCC_CRC_CLK_SLEEP_ENABLE #define __CRC_FORCE_RESET __HAL_RCC_CRC_FORCE_RESET #define __CRC_RELEASE_RESET __HAL_RCC_CRC_RELEASE_RESET #define __DAC_CLK_DISABLE __HAL_RCC_DAC_CLK_DISABLE #define __DAC_CLK_ENABLE __HAL_RCC_DAC_CLK_ENABLE #define __DAC_FORCE_RESET __HAL_RCC_DAC_FORCE_RESET #define __DAC_RELEASE_RESET __HAL_RCC_DAC_RELEASE_RESET #define __DAC1_CLK_DISABLE __HAL_RCC_DAC1_CLK_DISABLE #define __DAC1_CLK_ENABLE __HAL_RCC_DAC1_CLK_ENABLE #define __DAC1_CLK_SLEEP_DISABLE __HAL_RCC_DAC1_CLK_SLEEP_DISABLE #define __DAC1_CLK_SLEEP_ENABLE __HAL_RCC_DAC1_CLK_SLEEP_ENABLE #define __DAC1_FORCE_RESET __HAL_RCC_DAC1_FORCE_RESET #define __DAC1_RELEASE_RESET __HAL_RCC_DAC1_RELEASE_RESET #define __DBGMCU_CLK_ENABLE __HAL_RCC_DBGMCU_CLK_ENABLE #define __DBGMCU_CLK_DISABLE __HAL_RCC_DBGMCU_CLK_DISABLE #define __DBGMCU_FORCE_RESET __HAL_RCC_DBGMCU_FORCE_RESET #define __DBGMCU_RELEASE_RESET __HAL_RCC_DBGMCU_RELEASE_RESET #define __DFSDM_CLK_DISABLE __HAL_RCC_DFSDM_CLK_DISABLE #define __DFSDM_CLK_ENABLE __HAL_RCC_DFSDM_CLK_ENABLE #define __DFSDM_CLK_SLEEP_DISABLE __HAL_RCC_DFSDM_CLK_SLEEP_DISABLE #define __DFSDM_CLK_SLEEP_ENABLE __HAL_RCC_DFSDM_CLK_SLEEP_ENABLE #define __DFSDM_FORCE_RESET __HAL_RCC_DFSDM_FORCE_RESET #define __DFSDM_RELEASE_RESET __HAL_RCC_DFSDM_RELEASE_RESET #define __DMA1_CLK_DISABLE __HAL_RCC_DMA1_CLK_DISABLE #define __DMA1_CLK_ENABLE __HAL_RCC_DMA1_CLK_ENABLE #define __DMA1_CLK_SLEEP_DISABLE __HAL_RCC_DMA1_CLK_SLEEP_DISABLE #define __DMA1_CLK_SLEEP_ENABLE __HAL_RCC_DMA1_CLK_SLEEP_ENABLE #define __DMA1_FORCE_RESET __HAL_RCC_DMA1_FORCE_RESET #define __DMA1_RELEASE_RESET __HAL_RCC_DMA1_RELEASE_RESET #define __DMA2_CLK_DISABLE __HAL_RCC_DMA2_CLK_DISABLE #define __DMA2_CLK_ENABLE __HAL_RCC_DMA2_CLK_ENABLE #define __DMA2_CLK_SLEEP_DISABLE __HAL_RCC_DMA2_CLK_SLEEP_DISABLE #define __DMA2_CLK_SLEEP_ENABLE __HAL_RCC_DMA2_CLK_SLEEP_ENABLE #define __DMA2_FORCE_RESET __HAL_RCC_DMA2_FORCE_RESET #define __DMA2_RELEASE_RESET __HAL_RCC_DMA2_RELEASE_RESET #define __ETHMAC_CLK_DISABLE __HAL_RCC_ETHMAC_CLK_DISABLE #define __ETHMAC_CLK_ENABLE __HAL_RCC_ETHMAC_CLK_ENABLE #define __ETHMAC_FORCE_RESET __HAL_RCC_ETHMAC_FORCE_RESET #define __ETHMAC_RELEASE_RESET __HAL_RCC_ETHMAC_RELEASE_RESET #define __ETHMACRX_CLK_DISABLE __HAL_RCC_ETHMACRX_CLK_DISABLE #define __ETHMACRX_CLK_ENABLE __HAL_RCC_ETHMACRX_CLK_ENABLE #define __ETHMACTX_CLK_DISABLE __HAL_RCC_ETHMACTX_CLK_DISABLE #define __ETHMACTX_CLK_ENABLE __HAL_RCC_ETHMACTX_CLK_ENABLE #define __FIREWALL_CLK_DISABLE __HAL_RCC_FIREWALL_CLK_DISABLE #define __FIREWALL_CLK_ENABLE __HAL_RCC_FIREWALL_CLK_ENABLE #define __FLASH_CLK_DISABLE __HAL_RCC_FLASH_CLK_DISABLE #define __FLASH_CLK_ENABLE __HAL_RCC_FLASH_CLK_ENABLE #define __FLASH_CLK_SLEEP_DISABLE __HAL_RCC_FLASH_CLK_SLEEP_DISABLE #define __FLASH_CLK_SLEEP_ENABLE __HAL_RCC_FLASH_CLK_SLEEP_ENABLE #define __FLASH_FORCE_RESET __HAL_RCC_FLASH_FORCE_RESET #define __FLASH_RELEASE_RESET __HAL_RCC_FLASH_RELEASE_RESET #define __FLITF_CLK_DISABLE __HAL_RCC_FLITF_CLK_DISABLE #define __FLITF_CLK_ENABLE __HAL_RCC_FLITF_CLK_ENABLE #define __FLITF_FORCE_RESET __HAL_RCC_FLITF_FORCE_RESET #define __FLITF_RELEASE_RESET __HAL_RCC_FLITF_RELEASE_RESET #define __FLITF_CLK_SLEEP_ENABLE __HAL_RCC_FLITF_CLK_SLEEP_ENABLE #define __FLITF_CLK_SLEEP_DISABLE __HAL_RCC_FLITF_CLK_SLEEP_DISABLE #define __FMC_CLK_DISABLE __HAL_RCC_FMC_CLK_DISABLE #define __FMC_CLK_ENABLE __HAL_RCC_FMC_CLK_ENABLE #define __FMC_CLK_SLEEP_DISABLE __HAL_RCC_FMC_CLK_SLEEP_DISABLE #define __FMC_CLK_SLEEP_ENABLE __HAL_RCC_FMC_CLK_SLEEP_ENABLE #define __FMC_FORCE_RESET __HAL_RCC_FMC_FORCE_RESET #define __FMC_RELEASE_RESET __HAL_RCC_FMC_RELEASE_RESET #define __FSMC_CLK_DISABLE __HAL_RCC_FSMC_CLK_DISABLE #define __FSMC_CLK_ENABLE __HAL_RCC_FSMC_CLK_ENABLE #define __GPIOA_CLK_DISABLE __HAL_RCC_GPIOA_CLK_DISABLE #define __GPIOA_CLK_ENABLE __HAL_RCC_GPIOA_CLK_ENABLE #define __GPIOA_CLK_SLEEP_DISABLE __HAL_RCC_GPIOA_CLK_SLEEP_DISABLE #define __GPIOA_CLK_SLEEP_ENABLE __HAL_RCC_GPIOA_CLK_SLEEP_ENABLE #define __GPIOA_FORCE_RESET __HAL_RCC_GPIOA_FORCE_RESET #define __GPIOA_RELEASE_RESET __HAL_RCC_GPIOA_RELEASE_RESET #define __GPIOB_CLK_DISABLE __HAL_RCC_GPIOB_CLK_DISABLE #define __GPIOB_CLK_ENABLE __HAL_RCC_GPIOB_CLK_ENABLE #define __GPIOB_CLK_SLEEP_DISABLE __HAL_RCC_GPIOB_CLK_SLEEP_DISABLE #define __GPIOB_CLK_SLEEP_ENABLE __HAL_RCC_GPIOB_CLK_SLEEP_ENABLE #define __GPIOB_FORCE_RESET __HAL_RCC_GPIOB_FORCE_RESET #define __GPIOB_RELEASE_RESET __HAL_RCC_GPIOB_RELEASE_RESET #define __GPIOC_CLK_DISABLE __HAL_RCC_GPIOC_CLK_DISABLE #define __GPIOC_CLK_ENABLE __HAL_RCC_GPIOC_CLK_ENABLE #define __GPIOC_CLK_SLEEP_DISABLE __HAL_RCC_GPIOC_CLK_SLEEP_DISABLE #define __GPIOC_CLK_SLEEP_ENABLE __HAL_RCC_GPIOC_CLK_SLEEP_ENABLE #define __GPIOC_FORCE_RESET __HAL_RCC_GPIOC_FORCE_RESET #define __GPIOC_RELEASE_RESET __HAL_RCC_GPIOC_RELEASE_RESET #define __GPIOD_CLK_DISABLE __HAL_RCC_GPIOD_CLK_DISABLE #define __GPIOD_CLK_ENABLE __HAL_RCC_GPIOD_CLK_ENABLE #define __GPIOD_CLK_SLEEP_DISABLE __HAL_RCC_GPIOD_CLK_SLEEP_DISABLE #define __GPIOD_CLK_SLEEP_ENABLE __HAL_RCC_GPIOD_CLK_SLEEP_ENABLE #define __GPIOD_FORCE_RESET __HAL_RCC_GPIOD_FORCE_RESET #define __GPIOD_RELEASE_RESET __HAL_RCC_GPIOD_RELEASE_RESET #define __GPIOE_CLK_DISABLE __HAL_RCC_GPIOE_CLK_DISABLE #define __GPIOE_CLK_ENABLE __HAL_RCC_GPIOE_CLK_ENABLE #define __GPIOE_CLK_SLEEP_DISABLE __HAL_RCC_GPIOE_CLK_SLEEP_DISABLE #define __GPIOE_CLK_SLEEP_ENABLE __HAL_RCC_GPIOE_CLK_SLEEP_ENABLE #define __GPIOE_FORCE_RESET __HAL_RCC_GPIOE_FORCE_RESET #define __GPIOE_RELEASE_RESET __HAL_RCC_GPIOE_RELEASE_RESET #define __GPIOF_CLK_DISABLE __HAL_RCC_GPIOF_CLK_DISABLE #define __GPIOF_CLK_ENABLE __HAL_RCC_GPIOF_CLK_ENABLE #define __GPIOF_CLK_SLEEP_DISABLE __HAL_RCC_GPIOF_CLK_SLEEP_DISABLE #define __GPIOF_CLK_SLEEP_ENABLE __HAL_RCC_GPIOF_CLK_SLEEP_ENABLE #define __GPIOF_FORCE_RESET __HAL_RCC_GPIOF_FORCE_RESET #define __GPIOF_RELEASE_RESET __HAL_RCC_GPIOF_RELEASE_RESET #define __GPIOG_CLK_DISABLE __HAL_RCC_GPIOG_CLK_DISABLE #define __GPIOG_CLK_ENABLE __HAL_RCC_GPIOG_CLK_ENABLE #define __GPIOG_CLK_SLEEP_DISABLE __HAL_RCC_GPIOG_CLK_SLEEP_DISABLE #define __GPIOG_CLK_SLEEP_ENABLE __HAL_RCC_GPIOG_CLK_SLEEP_ENABLE #define __GPIOG_FORCE_RESET __HAL_RCC_GPIOG_FORCE_RESET #define __GPIOG_RELEASE_RESET __HAL_RCC_GPIOG_RELEASE_RESET #define __GPIOH_CLK_DISABLE __HAL_RCC_GPIOH_CLK_DISABLE #define __GPIOH_CLK_ENABLE __HAL_RCC_GPIOH_CLK_ENABLE #define __GPIOH_CLK_SLEEP_DISABLE __HAL_RCC_GPIOH_CLK_SLEEP_DISABLE #define __GPIOH_CLK_SLEEP_ENABLE __HAL_RCC_GPIOH_CLK_SLEEP_ENABLE #define __GPIOH_FORCE_RESET __HAL_RCC_GPIOH_FORCE_RESET #define __GPIOH_RELEASE_RESET __HAL_RCC_GPIOH_RELEASE_RESET #define __I2C1_CLK_DISABLE __HAL_RCC_I2C1_CLK_DISABLE #define __I2C1_CLK_ENABLE __HAL_RCC_I2C1_CLK_ENABLE #define __I2C1_CLK_SLEEP_DISABLE __HAL_RCC_I2C1_CLK_SLEEP_DISABLE #define __I2C1_CLK_SLEEP_ENABLE __HAL_RCC_I2C1_CLK_SLEEP_ENABLE #define __I2C1_FORCE_RESET __HAL_RCC_I2C1_FORCE_RESET #define __I2C1_RELEASE_RESET __HAL_RCC_I2C1_RELEASE_RESET #define __I2C2_CLK_DISABLE __HAL_RCC_I2C2_CLK_DISABLE #define __I2C2_CLK_ENABLE __HAL_RCC_I2C2_CLK_ENABLE #define __I2C2_CLK_SLEEP_DISABLE __HAL_RCC_I2C2_CLK_SLEEP_DISABLE #define __I2C2_CLK_SLEEP_ENABLE __HAL_RCC_I2C2_CLK_SLEEP_ENABLE #define __I2C2_FORCE_RESET __HAL_RCC_I2C2_FORCE_RESET #define __I2C2_RELEASE_RESET __HAL_RCC_I2C2_RELEASE_RESET #define __I2C3_CLK_DISABLE __HAL_RCC_I2C3_CLK_DISABLE #define __I2C3_CLK_ENABLE __HAL_RCC_I2C3_CLK_ENABLE #define __I2C3_CLK_SLEEP_DISABLE __HAL_RCC_I2C3_CLK_SLEEP_DISABLE #define __I2C3_CLK_SLEEP_ENABLE __HAL_RCC_I2C3_CLK_SLEEP_ENABLE #define __I2C3_FORCE_RESET __HAL_RCC_I2C3_FORCE_RESET #define __I2C3_RELEASE_RESET __HAL_RCC_I2C3_RELEASE_RESET #define __LCD_CLK_DISABLE __HAL_RCC_LCD_CLK_DISABLE #define __LCD_CLK_ENABLE __HAL_RCC_LCD_CLK_ENABLE #define __LCD_CLK_SLEEP_DISABLE __HAL_RCC_LCD_CLK_SLEEP_DISABLE #define __LCD_CLK_SLEEP_ENABLE __HAL_RCC_LCD_CLK_SLEEP_ENABLE #define __LCD_FORCE_RESET __HAL_RCC_LCD_FORCE_RESET #define __LCD_RELEASE_RESET __HAL_RCC_LCD_RELEASE_RESET #define __LPTIM1_CLK_DISABLE __HAL_RCC_LPTIM1_CLK_DISABLE #define __LPTIM1_CLK_ENABLE __HAL_RCC_LPTIM1_CLK_ENABLE #define __LPTIM1_CLK_SLEEP_DISABLE __HAL_RCC_LPTIM1_CLK_SLEEP_DISABLE #define __LPTIM1_CLK_SLEEP_ENABLE __HAL_RCC_LPTIM1_CLK_SLEEP_ENABLE #define __LPTIM1_FORCE_RESET __HAL_RCC_LPTIM1_FORCE_RESET #define __LPTIM1_RELEASE_RESET __HAL_RCC_LPTIM1_RELEASE_RESET #define __LPTIM2_CLK_DISABLE __HAL_RCC_LPTIM2_CLK_DISABLE #define __LPTIM2_CLK_ENABLE __HAL_RCC_LPTIM2_CLK_ENABLE #define __LPTIM2_CLK_SLEEP_DISABLE __HAL_RCC_LPTIM2_CLK_SLEEP_DISABLE #define __LPTIM2_CLK_SLEEP_ENABLE __HAL_RCC_LPTIM2_CLK_SLEEP_ENABLE #define __LPTIM2_FORCE_RESET __HAL_RCC_LPTIM2_FORCE_RESET #define __LPTIM2_RELEASE_RESET __HAL_RCC_LPTIM2_RELEASE_RESET #define __LPUART1_CLK_DISABLE __HAL_RCC_LPUART1_CLK_DISABLE #define __LPUART1_CLK_ENABLE __HAL_RCC_LPUART1_CLK_ENABLE #define __LPUART1_CLK_SLEEP_DISABLE __HAL_RCC_LPUART1_CLK_SLEEP_DISABLE #define __LPUART1_CLK_SLEEP_ENABLE __HAL_RCC_LPUART1_CLK_SLEEP_ENABLE #define __LPUART1_FORCE_RESET __HAL_RCC_LPUART1_FORCE_RESET #define __LPUART1_RELEASE_RESET __HAL_RCC_LPUART1_RELEASE_RESET #define __OPAMP_CLK_DISABLE __HAL_RCC_OPAMP_CLK_DISABLE #define __OPAMP_CLK_ENABLE __HAL_RCC_OPAMP_CLK_ENABLE #define __OPAMP_CLK_SLEEP_DISABLE __HAL_RCC_OPAMP_CLK_SLEEP_DISABLE #define __OPAMP_CLK_SLEEP_ENABLE __HAL_RCC_OPAMP_CLK_SLEEP_ENABLE #define __OPAMP_FORCE_RESET __HAL_RCC_OPAMP_FORCE_RESET #define __OPAMP_RELEASE_RESET __HAL_RCC_OPAMP_RELEASE_RESET #define __OTGFS_CLK_DISABLE __HAL_RCC_OTGFS_CLK_DISABLE #define __OTGFS_CLK_ENABLE __HAL_RCC_OTGFS_CLK_ENABLE #define __OTGFS_CLK_SLEEP_DISABLE __HAL_RCC_OTGFS_CLK_SLEEP_DISABLE #define __OTGFS_CLK_SLEEP_ENABLE __HAL_RCC_OTGFS_CLK_SLEEP_ENABLE #define __OTGFS_FORCE_RESET __HAL_RCC_OTGFS_FORCE_RESET #define __OTGFS_RELEASE_RESET __HAL_RCC_OTGFS_RELEASE_RESET #define __PWR_CLK_DISABLE __HAL_RCC_PWR_CLK_DISABLE #define __PWR_CLK_ENABLE __HAL_RCC_PWR_CLK_ENABLE #define __PWR_CLK_SLEEP_DISABLE __HAL_RCC_PWR_CLK_SLEEP_DISABLE #define __PWR_CLK_SLEEP_ENABLE __HAL_RCC_PWR_CLK_SLEEP_ENABLE #define __PWR_FORCE_RESET __HAL_RCC_PWR_FORCE_RESET #define __PWR_RELEASE_RESET __HAL_RCC_PWR_RELEASE_RESET #define __QSPI_CLK_DISABLE __HAL_RCC_QSPI_CLK_DISABLE #define __QSPI_CLK_ENABLE __HAL_RCC_QSPI_CLK_ENABLE #define __QSPI_CLK_SLEEP_DISABLE __HAL_RCC_QSPI_CLK_SLEEP_DISABLE #define __QSPI_CLK_SLEEP_ENABLE __HAL_RCC_QSPI_CLK_SLEEP_ENABLE #define __QSPI_FORCE_RESET __HAL_RCC_QSPI_FORCE_RESET #define __QSPI_RELEASE_RESET __HAL_RCC_QSPI_RELEASE_RESET #define __RNG_CLK_DISABLE __HAL_RCC_RNG_CLK_DISABLE #define __RNG_CLK_ENABLE __HAL_RCC_RNG_CLK_ENABLE #define __RNG_CLK_SLEEP_DISABLE __HAL_RCC_RNG_CLK_SLEEP_DISABLE #define __RNG_CLK_SLEEP_ENABLE __HAL_RCC_RNG_CLK_SLEEP_ENABLE #define __RNG_FORCE_RESET __HAL_RCC_RNG_FORCE_RESET #define __RNG_RELEASE_RESET __HAL_RCC_RNG_RELEASE_RESET #define __SAI1_CLK_DISABLE __HAL_RCC_SAI1_CLK_DISABLE #define __SAI1_CLK_ENABLE __HAL_RCC_SAI1_CLK_ENABLE #define __SAI1_CLK_SLEEP_DISABLE __HAL_RCC_SAI1_CLK_SLEEP_DISABLE #define __SAI1_CLK_SLEEP_ENABLE __HAL_RCC_SAI1_CLK_SLEEP_ENABLE #define __SAI1_FORCE_RESET __HAL_RCC_SAI1_FORCE_RESET #define __SAI1_RELEASE_RESET __HAL_RCC_SAI1_RELEASE_RESET #define __SAI2_CLK_DISABLE __HAL_RCC_SAI2_CLK_DISABLE #define __SAI2_CLK_ENABLE __HAL_RCC_SAI2_CLK_ENABLE #define __SAI2_CLK_SLEEP_DISABLE __HAL_RCC_SAI2_CLK_SLEEP_DISABLE #define __SAI2_CLK_SLEEP_ENABLE __HAL_RCC_SAI2_CLK_SLEEP_ENABLE #define __SAI2_FORCE_RESET __HAL_RCC_SAI2_FORCE_RESET #define __SAI2_RELEASE_RESET __HAL_RCC_SAI2_RELEASE_RESET #define __SDIO_CLK_DISABLE __HAL_RCC_SDIO_CLK_DISABLE #define __SDIO_CLK_ENABLE __HAL_RCC_SDIO_CLK_ENABLE #define __SDMMC_CLK_DISABLE __HAL_RCC_SDMMC_CLK_DISABLE #define __SDMMC_CLK_ENABLE __HAL_RCC_SDMMC_CLK_ENABLE #define __SDMMC_CLK_SLEEP_DISABLE __HAL_RCC_SDMMC_CLK_SLEEP_DISABLE #define __SDMMC_CLK_SLEEP_ENABLE __HAL_RCC_SDMMC_CLK_SLEEP_ENABLE #define __SDMMC_FORCE_RESET __HAL_RCC_SDMMC_FORCE_RESET #define __SDMMC_RELEASE_RESET __HAL_RCC_SDMMC_RELEASE_RESET #define __SPI1_CLK_DISABLE __HAL_RCC_SPI1_CLK_DISABLE #define __SPI1_CLK_ENABLE __HAL_RCC_SPI1_CLK_ENABLE #define __SPI1_CLK_SLEEP_DISABLE __HAL_RCC_SPI1_CLK_SLEEP_DISABLE #define __SPI1_CLK_SLEEP_ENABLE __HAL_RCC_SPI1_CLK_SLEEP_ENABLE #define __SPI1_FORCE_RESET __HAL_RCC_SPI1_FORCE_RESET #define __SPI1_RELEASE_RESET __HAL_RCC_SPI1_RELEASE_RESET #define __SPI2_CLK_DISABLE __HAL_RCC_SPI2_CLK_DISABLE #define __SPI2_CLK_ENABLE __HAL_RCC_SPI2_CLK_ENABLE #define __SPI2_CLK_SLEEP_DISABLE __HAL_RCC_SPI2_CLK_SLEEP_DISABLE #define __SPI2_CLK_SLEEP_ENABLE __HAL_RCC_SPI2_CLK_SLEEP_ENABLE #define __SPI2_FORCE_RESET __HAL_RCC_SPI2_FORCE_RESET #define __SPI2_RELEASE_RESET __HAL_RCC_SPI2_RELEASE_RESET #define __SPI3_CLK_DISABLE __HAL_RCC_SPI3_CLK_DISABLE #define __SPI3_CLK_ENABLE __HAL_RCC_SPI3_CLK_ENABLE #define __SPI3_CLK_SLEEP_DISABLE __HAL_RCC_SPI3_CLK_SLEEP_DISABLE #define __SPI3_CLK_SLEEP_ENABLE __HAL_RCC_SPI3_CLK_SLEEP_ENABLE #define __SPI3_FORCE_RESET __HAL_RCC_SPI3_FORCE_RESET #define __SPI3_RELEASE_RESET __HAL_RCC_SPI3_RELEASE_RESET #define __SRAM_CLK_DISABLE __HAL_RCC_SRAM_CLK_DISABLE #define __SRAM_CLK_ENABLE __HAL_RCC_SRAM_CLK_ENABLE #define __SRAM1_CLK_SLEEP_DISABLE __HAL_RCC_SRAM1_CLK_SLEEP_DISABLE #define __SRAM1_CLK_SLEEP_ENABLE __HAL_RCC_SRAM1_CLK_SLEEP_ENABLE #define __SRAM2_CLK_SLEEP_DISABLE __HAL_RCC_SRAM2_CLK_SLEEP_DISABLE #define __SRAM2_CLK_SLEEP_ENABLE __HAL_RCC_SRAM2_CLK_SLEEP_ENABLE #define __SWPMI1_CLK_DISABLE __HAL_RCC_SWPMI1_CLK_DISABLE #define __SWPMI1_CLK_ENABLE __HAL_RCC_SWPMI1_CLK_ENABLE #define __SWPMI1_CLK_SLEEP_DISABLE __HAL_RCC_SWPMI1_CLK_SLEEP_DISABLE #define __SWPMI1_CLK_SLEEP_ENABLE __HAL_RCC_SWPMI1_CLK_SLEEP_ENABLE #define __SWPMI1_FORCE_RESET __HAL_RCC_SWPMI1_FORCE_RESET #define __SWPMI1_RELEASE_RESET __HAL_RCC_SWPMI1_RELEASE_RESET #define __SYSCFG_CLK_DISABLE __HAL_RCC_SYSCFG_CLK_DISABLE #define __SYSCFG_CLK_ENABLE __HAL_RCC_SYSCFG_CLK_ENABLE #define __SYSCFG_CLK_SLEEP_DISABLE __HAL_RCC_SYSCFG_CLK_SLEEP_DISABLE #define __SYSCFG_CLK_SLEEP_ENABLE __HAL_RCC_SYSCFG_CLK_SLEEP_ENABLE #define __SYSCFG_FORCE_RESET __HAL_RCC_SYSCFG_FORCE_RESET #define __SYSCFG_RELEASE_RESET __HAL_RCC_SYSCFG_RELEASE_RESET #define __TIM1_CLK_DISABLE __HAL_RCC_TIM1_CLK_DISABLE #define __TIM1_CLK_ENABLE __HAL_RCC_TIM1_CLK_ENABLE #define __TIM1_CLK_SLEEP_DISABLE __HAL_RCC_TIM1_CLK_SLEEP_DISABLE #define __TIM1_CLK_SLEEP_ENABLE __HAL_RCC_TIM1_CLK_SLEEP_ENABLE #define __TIM1_FORCE_RESET __HAL_RCC_TIM1_FORCE_RESET #define __TIM1_RELEASE_RESET __HAL_RCC_TIM1_RELEASE_RESET #define __TIM10_CLK_DISABLE __HAL_RCC_TIM10_CLK_DISABLE #define __TIM10_CLK_ENABLE __HAL_RCC_TIM10_CLK_ENABLE #define __TIM10_FORCE_RESET __HAL_RCC_TIM10_FORCE_RESET #define __TIM10_RELEASE_RESET __HAL_RCC_TIM10_RELEASE_RESET #define __TIM11_CLK_DISABLE __HAL_RCC_TIM11_CLK_DISABLE #define __TIM11_CLK_ENABLE __HAL_RCC_TIM11_CLK_ENABLE #define __TIM11_FORCE_RESET __HAL_RCC_TIM11_FORCE_RESET #define __TIM11_RELEASE_RESET __HAL_RCC_TIM11_RELEASE_RESET #define __TIM12_CLK_DISABLE __HAL_RCC_TIM12_CLK_DISABLE #define __TIM12_CLK_ENABLE __HAL_RCC_TIM12_CLK_ENABLE #define __TIM12_FORCE_RESET __HAL_RCC_TIM12_FORCE_RESET #define __TIM12_RELEASE_RESET __HAL_RCC_TIM12_RELEASE_RESET #define __TIM13_CLK_DISABLE __HAL_RCC_TIM13_CLK_DISABLE #define __TIM13_CLK_ENABLE __HAL_RCC_TIM13_CLK_ENABLE #define __TIM13_FORCE_RESET __HAL_RCC_TIM13_FORCE_RESET #define __TIM13_RELEASE_RESET __HAL_RCC_TIM13_RELEASE_RESET #define __TIM14_CLK_DISABLE __HAL_RCC_TIM14_CLK_DISABLE #define __TIM14_CLK_ENABLE __HAL_RCC_TIM14_CLK_ENABLE #define __TIM14_FORCE_RESET __HAL_RCC_TIM14_FORCE_RESET #define __TIM14_RELEASE_RESET __HAL_RCC_TIM14_RELEASE_RESET #define __TIM15_CLK_DISABLE __HAL_RCC_TIM15_CLK_DISABLE #define __TIM15_CLK_ENABLE __HAL_RCC_TIM15_CLK_ENABLE #define __TIM15_CLK_SLEEP_DISABLE __HAL_RCC_TIM15_CLK_SLEEP_DISABLE #define __TIM15_CLK_SLEEP_ENABLE __HAL_RCC_TIM15_CLK_SLEEP_ENABLE #define __TIM15_FORCE_RESET __HAL_RCC_TIM15_FORCE_RESET #define __TIM15_RELEASE_RESET __HAL_RCC_TIM15_RELEASE_RESET #define __TIM16_CLK_DISABLE __HAL_RCC_TIM16_CLK_DISABLE #define __TIM16_CLK_ENABLE __HAL_RCC_TIM16_CLK_ENABLE #define __TIM16_CLK_SLEEP_DISABLE __HAL_RCC_TIM16_CLK_SLEEP_DISABLE #define __TIM16_CLK_SLEEP_ENABLE __HAL_RCC_TIM16_CLK_SLEEP_ENABLE #define __TIM16_FORCE_RESET __HAL_RCC_TIM16_FORCE_RESET #define __TIM16_RELEASE_RESET __HAL_RCC_TIM16_RELEASE_RESET #define __TIM17_CLK_DISABLE __HAL_RCC_TIM17_CLK_DISABLE #define __TIM17_CLK_ENABLE __HAL_RCC_TIM17_CLK_ENABLE #define __TIM17_CLK_SLEEP_DISABLE __HAL_RCC_TIM17_CLK_SLEEP_DISABLE #define __TIM17_CLK_SLEEP_ENABLE __HAL_RCC_TIM17_CLK_SLEEP_ENABLE #define __TIM17_FORCE_RESET __HAL_RCC_TIM17_FORCE_RESET #define __TIM17_RELEASE_RESET __HAL_RCC_TIM17_RELEASE_RESET #define __TIM2_CLK_DISABLE __HAL_RCC_TIM2_CLK_DISABLE #define __TIM2_CLK_ENABLE __HAL_RCC_TIM2_CLK_ENABLE #define __TIM2_CLK_SLEEP_DISABLE __HAL_RCC_TIM2_CLK_SLEEP_DISABLE #define __TIM2_CLK_SLEEP_ENABLE __HAL_RCC_TIM2_CLK_SLEEP_ENABLE #define __TIM2_FORCE_RESET __HAL_RCC_TIM2_FORCE_RESET #define __TIM2_RELEASE_RESET __HAL_RCC_TIM2_RELEASE_RESET #define __TIM3_CLK_DISABLE __HAL_RCC_TIM3_CLK_DISABLE #define __TIM3_CLK_ENABLE __HAL_RCC_TIM3_CLK_ENABLE #define __TIM3_CLK_SLEEP_DISABLE __HAL_RCC_TIM3_CLK_SLEEP_DISABLE #define __TIM3_CLK_SLEEP_ENABLE __HAL_RCC_TIM3_CLK_SLEEP_ENABLE #define __TIM3_FORCE_RESET __HAL_RCC_TIM3_FORCE_RESET #define __TIM3_RELEASE_RESET __HAL_RCC_TIM3_RELEASE_RESET #define __TIM4_CLK_DISABLE __HAL_RCC_TIM4_CLK_DISABLE #define __TIM4_CLK_ENABLE __HAL_RCC_TIM4_CLK_ENABLE #define __TIM4_CLK_SLEEP_DISABLE __HAL_RCC_TIM4_CLK_SLEEP_DISABLE #define __TIM4_CLK_SLEEP_ENABLE __HAL_RCC_TIM4_CLK_SLEEP_ENABLE #define __TIM4_FORCE_RESET __HAL_RCC_TIM4_FORCE_RESET #define __TIM4_RELEASE_RESET __HAL_RCC_TIM4_RELEASE_RESET #define __TIM5_CLK_DISABLE __HAL_RCC_TIM5_CLK_DISABLE #define __TIM5_CLK_ENABLE __HAL_RCC_TIM5_CLK_ENABLE #define __TIM5_CLK_SLEEP_DISABLE __HAL_RCC_TIM5_CLK_SLEEP_DISABLE #define __TIM5_CLK_SLEEP_ENABLE __HAL_RCC_TIM5_CLK_SLEEP_ENABLE #define __TIM5_FORCE_RESET __HAL_RCC_TIM5_FORCE_RESET #define __TIM5_RELEASE_RESET __HAL_RCC_TIM5_RELEASE_RESET #define __TIM6_CLK_DISABLE __HAL_RCC_TIM6_CLK_DISABLE #define __TIM6_CLK_ENABLE __HAL_RCC_TIM6_CLK_ENABLE #define __TIM6_CLK_SLEEP_DISABLE __HAL_RCC_TIM6_CLK_SLEEP_DISABLE #define __TIM6_CLK_SLEEP_ENABLE __HAL_RCC_TIM6_CLK_SLEEP_ENABLE #define __TIM6_FORCE_RESET __HAL_RCC_TIM6_FORCE_RESET #define __TIM6_RELEASE_RESET __HAL_RCC_TIM6_RELEASE_RESET #define __TIM7_CLK_DISABLE __HAL_RCC_TIM7_CLK_DISABLE #define __TIM7_CLK_ENABLE __HAL_RCC_TIM7_CLK_ENABLE #define __TIM7_CLK_SLEEP_DISABLE __HAL_RCC_TIM7_CLK_SLEEP_DISABLE #define __TIM7_CLK_SLEEP_ENABLE __HAL_RCC_TIM7_CLK_SLEEP_ENABLE #define __TIM7_FORCE_RESET __HAL_RCC_TIM7_FORCE_RESET #define __TIM7_RELEASE_RESET __HAL_RCC_TIM7_RELEASE_RESET #define __TIM8_CLK_DISABLE __HAL_RCC_TIM8_CLK_DISABLE #define __TIM8_CLK_ENABLE __HAL_RCC_TIM8_CLK_ENABLE #define __TIM8_CLK_SLEEP_DISABLE __HAL_RCC_TIM8_CLK_SLEEP_DISABLE #define __TIM8_CLK_SLEEP_ENABLE __HAL_RCC_TIM8_CLK_SLEEP_ENABLE #define __TIM8_FORCE_RESET __HAL_RCC_TIM8_FORCE_RESET #define __TIM8_RELEASE_RESET __HAL_RCC_TIM8_RELEASE_RESET #define __TIM9_CLK_DISABLE __HAL_RCC_TIM9_CLK_DISABLE #define __TIM9_CLK_ENABLE __HAL_RCC_TIM9_CLK_ENABLE #define __TIM9_FORCE_RESET __HAL_RCC_TIM9_FORCE_RESET #define __TIM9_RELEASE_RESET __HAL_RCC_TIM9_RELEASE_RESET #define __TSC_CLK_DISABLE __HAL_RCC_TSC_CLK_DISABLE #define __TSC_CLK_ENABLE __HAL_RCC_TSC_CLK_ENABLE #define __TSC_CLK_SLEEP_DISABLE __HAL_RCC_TSC_CLK_SLEEP_DISABLE #define __TSC_CLK_SLEEP_ENABLE __HAL_RCC_TSC_CLK_SLEEP_ENABLE #define __TSC_FORCE_RESET __HAL_RCC_TSC_FORCE_RESET #define __TSC_RELEASE_RESET __HAL_RCC_TSC_RELEASE_RESET #define __UART4_CLK_DISABLE __HAL_RCC_UART4_CLK_DISABLE #define __UART4_CLK_ENABLE __HAL_RCC_UART4_CLK_ENABLE #define __UART4_CLK_SLEEP_DISABLE __HAL_RCC_UART4_CLK_SLEEP_DISABLE #define __UART4_CLK_SLEEP_ENABLE __HAL_RCC_UART4_CLK_SLEEP_ENABLE #define __UART4_FORCE_RESET __HAL_RCC_UART4_FORCE_RESET #define __UART4_RELEASE_RESET __HAL_RCC_UART4_RELEASE_RESET #define __UART5_CLK_DISABLE __HAL_RCC_UART5_CLK_DISABLE #define __UART5_CLK_ENABLE __HAL_RCC_UART5_CLK_ENABLE #define __UART5_CLK_SLEEP_DISABLE __HAL_RCC_UART5_CLK_SLEEP_DISABLE #define __UART5_CLK_SLEEP_ENABLE __HAL_RCC_UART5_CLK_SLEEP_ENABLE #define __UART5_FORCE_RESET __HAL_RCC_UART5_FORCE_RESET #define __UART5_RELEASE_RESET __HAL_RCC_UART5_RELEASE_RESET #define __USART1_CLK_DISABLE __HAL_RCC_USART1_CLK_DISABLE #define __USART1_CLK_ENABLE __HAL_RCC_USART1_CLK_ENABLE #define __USART1_CLK_SLEEP_DISABLE __HAL_RCC_USART1_CLK_SLEEP_DISABLE #define __USART1_CLK_SLEEP_ENABLE __HAL_RCC_USART1_CLK_SLEEP_ENABLE #define __USART1_FORCE_RESET __HAL_RCC_USART1_FORCE_RESET #define __USART1_RELEASE_RESET __HAL_RCC_USART1_RELEASE_RESET #define __USART2_CLK_DISABLE __HAL_RCC_USART2_CLK_DISABLE #define __USART2_CLK_ENABLE __HAL_RCC_USART2_CLK_ENABLE #define __USART2_CLK_SLEEP_DISABLE __HAL_RCC_USART2_CLK_SLEEP_DISABLE #define __USART2_CLK_SLEEP_ENABLE __HAL_RCC_USART2_CLK_SLEEP_ENABLE #define __USART2_FORCE_RESET __HAL_RCC_USART2_FORCE_RESET #define __USART2_RELEASE_RESET __HAL_RCC_USART2_RELEASE_RESET #define __USART3_CLK_DISABLE __HAL_RCC_USART3_CLK_DISABLE #define __USART3_CLK_ENABLE __HAL_RCC_USART3_CLK_ENABLE #define __USART3_CLK_SLEEP_DISABLE __HAL_RCC_USART3_CLK_SLEEP_DISABLE #define __USART3_CLK_SLEEP_ENABLE __HAL_RCC_USART3_CLK_SLEEP_ENABLE #define __USART3_FORCE_RESET __HAL_RCC_USART3_FORCE_RESET #define __USART3_RELEASE_RESET __HAL_RCC_USART3_RELEASE_RESET #define __USART4_CLK_DISABLE __HAL_RCC_USART4_CLK_DISABLE #define __USART4_CLK_ENABLE __HAL_RCC_USART4_CLK_ENABLE #define __USART4_CLK_SLEEP_ENABLE __HAL_RCC_USART4_CLK_SLEEP_ENABLE #define __USART4_CLK_SLEEP_DISABLE __HAL_RCC_USART4_CLK_SLEEP_DISABLE #define __USART4_FORCE_RESET __HAL_RCC_USART4_FORCE_RESET #define __USART4_RELEASE_RESET __HAL_RCC_USART4_RELEASE_RESET #define __USART5_CLK_DISABLE __HAL_RCC_USART5_CLK_DISABLE #define __USART5_CLK_ENABLE __HAL_RCC_USART5_CLK_ENABLE #define __USART5_CLK_SLEEP_ENABLE __HAL_RCC_USART5_CLK_SLEEP_ENABLE #define __USART5_CLK_SLEEP_DISABLE __HAL_RCC_USART5_CLK_SLEEP_DISABLE #define __USART5_FORCE_RESET __HAL_RCC_USART5_FORCE_RESET #define __USART5_RELEASE_RESET __HAL_RCC_USART5_RELEASE_RESET #define __USART7_CLK_DISABLE __HAL_RCC_USART7_CLK_DISABLE #define __USART7_CLK_ENABLE __HAL_RCC_USART7_CLK_ENABLE #define __USART7_FORCE_RESET __HAL_RCC_USART7_FORCE_RESET #define __USART7_RELEASE_RESET __HAL_RCC_USART7_RELEASE_RESET #define __USART8_CLK_DISABLE __HAL_RCC_USART8_CLK_DISABLE #define __USART8_CLK_ENABLE __HAL_RCC_USART8_CLK_ENABLE #define __USART8_FORCE_RESET __HAL_RCC_USART8_FORCE_RESET #define __USART8_RELEASE_RESET __HAL_RCC_USART8_RELEASE_RESET #define __USB_CLK_DISABLE __HAL_RCC_USB_CLK_DISABLE #define __USB_CLK_ENABLE __HAL_RCC_USB_CLK_ENABLE #define __USB_FORCE_RESET __HAL_RCC_USB_FORCE_RESET #define __USB_CLK_SLEEP_ENABLE __HAL_RCC_USB_CLK_SLEEP_ENABLE #define __USB_CLK_SLEEP_DISABLE __HAL_RCC_USB_CLK_SLEEP_DISABLE #define __USB_OTG_FS_CLK_DISABLE __HAL_RCC_USB_OTG_FS_CLK_DISABLE #define __USB_OTG_FS_CLK_ENABLE __HAL_RCC_USB_OTG_FS_CLK_ENABLE #define __USB_RELEASE_RESET __HAL_RCC_USB_RELEASE_RESET #define __WWDG_CLK_DISABLE __HAL_RCC_WWDG_CLK_DISABLE #define __WWDG_CLK_ENABLE __HAL_RCC_WWDG_CLK_ENABLE #define __WWDG_CLK_SLEEP_DISABLE __HAL_RCC_WWDG_CLK_SLEEP_DISABLE #define __WWDG_CLK_SLEEP_ENABLE __HAL_RCC_WWDG_CLK_SLEEP_ENABLE #define __WWDG_FORCE_RESET __HAL_RCC_WWDG_FORCE_RESET #define __WWDG_RELEASE_RESET __HAL_RCC_WWDG_RELEASE_RESET #define __TIM21_CLK_ENABLE __HAL_RCC_TIM21_CLK_ENABLE #define __TIM21_CLK_DISABLE __HAL_RCC_TIM21_CLK_DISABLE #define __TIM21_FORCE_RESET __HAL_RCC_TIM21_FORCE_RESET #define __TIM21_RELEASE_RESET __HAL_RCC_TIM21_RELEASE_RESET #define __TIM21_CLK_SLEEP_ENABLE __HAL_RCC_TIM21_CLK_SLEEP_ENABLE #define __TIM21_CLK_SLEEP_DISABLE __HAL_RCC_TIM21_CLK_SLEEP_DISABLE #define __TIM22_CLK_ENABLE __HAL_RCC_TIM22_CLK_ENABLE #define __TIM22_CLK_DISABLE __HAL_RCC_TIM22_CLK_DISABLE #define __TIM22_FORCE_RESET __HAL_RCC_TIM22_FORCE_RESET #define __TIM22_RELEASE_RESET __HAL_RCC_TIM22_RELEASE_RESET #define __TIM22_CLK_SLEEP_ENABLE __HAL_RCC_TIM22_CLK_SLEEP_ENABLE #define __TIM22_CLK_SLEEP_DISABLE __HAL_RCC_TIM22_CLK_SLEEP_DISABLE #define __CRS_CLK_DISABLE __HAL_RCC_CRS_CLK_DISABLE #define __CRS_CLK_ENABLE __HAL_RCC_CRS_CLK_ENABLE #define __CRS_CLK_SLEEP_DISABLE __HAL_RCC_CRS_CLK_SLEEP_DISABLE #define __CRS_CLK_SLEEP_ENABLE __HAL_RCC_CRS_CLK_SLEEP_ENABLE #define __CRS_FORCE_RESET __HAL_RCC_CRS_FORCE_RESET #define __CRS_RELEASE_RESET __HAL_RCC_CRS_RELEASE_RESET #define __RCC_BACKUPRESET_FORCE __HAL_RCC_BACKUPRESET_FORCE #define __RCC_BACKUPRESET_RELEASE __HAL_RCC_BACKUPRESET_RELEASE #define __USB_OTG_FS_FORCE_RESET __HAL_RCC_USB_OTG_FS_FORCE_RESET #define __USB_OTG_FS_RELEASE_RESET __HAL_RCC_USB_OTG_FS_RELEASE_RESET #define __USB_OTG_FS_CLK_SLEEP_ENABLE __HAL_RCC_USB_OTG_FS_CLK_SLEEP_ENABLE #define __USB_OTG_FS_CLK_SLEEP_DISABLE __HAL_RCC_USB_OTG_FS_CLK_SLEEP_DISABLE #define __USB_OTG_HS_CLK_DISABLE __HAL_RCC_USB_OTG_HS_CLK_DISABLE #define __USB_OTG_HS_CLK_ENABLE __HAL_RCC_USB_OTG_HS_CLK_ENABLE #define __USB_OTG_HS_ULPI_CLK_ENABLE __HAL_RCC_USB_OTG_HS_ULPI_CLK_ENABLE #define __USB_OTG_HS_ULPI_CLK_DISABLE __HAL_RCC_USB_OTG_HS_ULPI_CLK_DISABLE #define __TIM9_CLK_SLEEP_ENABLE __HAL_RCC_TIM9_CLK_SLEEP_ENABLE #define __TIM9_CLK_SLEEP_DISABLE __HAL_RCC_TIM9_CLK_SLEEP_DISABLE #define __TIM10_CLK_SLEEP_ENABLE __HAL_RCC_TIM10_CLK_SLEEP_ENABLE #define __TIM10_CLK_SLEEP_DISABLE __HAL_RCC_TIM10_CLK_SLEEP_DISABLE #define __TIM11_CLK_SLEEP_ENABLE __HAL_RCC_TIM11_CLK_SLEEP_ENABLE #define __TIM11_CLK_SLEEP_DISABLE __HAL_RCC_TIM11_CLK_SLEEP_DISABLE #define __ETHMACPTP_CLK_SLEEP_ENABLE __HAL_RCC_ETHMACPTP_CLK_SLEEP_ENABLE #define __ETHMACPTP_CLK_SLEEP_DISABLE __HAL_RCC_ETHMACPTP_CLK_SLEEP_DISABLE #define __ETHMACPTP_CLK_ENABLE __HAL_RCC_ETHMACPTP_CLK_ENABLE #define __ETHMACPTP_CLK_DISABLE __HAL_RCC_ETHMACPTP_CLK_DISABLE #define __HASH_CLK_ENABLE __HAL_RCC_HASH_CLK_ENABLE #define __HASH_FORCE_RESET __HAL_RCC_HASH_FORCE_RESET #define __HASH_RELEASE_RESET __HAL_RCC_HASH_RELEASE_RESET #define __HASH_CLK_SLEEP_ENABLE __HAL_RCC_HASH_CLK_SLEEP_ENABLE #define __HASH_CLK_SLEEP_DISABLE __HAL_RCC_HASH_CLK_SLEEP_DISABLE #define __HASH_CLK_DISABLE __HAL_RCC_HASH_CLK_DISABLE #define __SPI5_CLK_ENABLE __HAL_RCC_SPI5_CLK_ENABLE #define __SPI5_CLK_DISABLE __HAL_RCC_SPI5_CLK_DISABLE #define __SPI5_FORCE_RESET __HAL_RCC_SPI5_FORCE_RESET #define __SPI5_RELEASE_RESET __HAL_RCC_SPI5_RELEASE_RESET #define __SPI5_CLK_SLEEP_ENABLE __HAL_RCC_SPI5_CLK_SLEEP_ENABLE #define __SPI5_CLK_SLEEP_DISABLE __HAL_RCC_SPI5_CLK_SLEEP_DISABLE #define __SPI6_CLK_ENABLE __HAL_RCC_SPI6_CLK_ENABLE #define __SPI6_CLK_DISABLE __HAL_RCC_SPI6_CLK_DISABLE #define __SPI6_FORCE_RESET __HAL_RCC_SPI6_FORCE_RESET #define __SPI6_RELEASE_RESET __HAL_RCC_SPI6_RELEASE_RESET #define __SPI6_CLK_SLEEP_ENABLE __HAL_RCC_SPI6_CLK_SLEEP_ENABLE #define __SPI6_CLK_SLEEP_DISABLE __HAL_RCC_SPI6_CLK_SLEEP_DISABLE #define __LTDC_CLK_ENABLE __HAL_RCC_LTDC_CLK_ENABLE #define __LTDC_CLK_DISABLE __HAL_RCC_LTDC_CLK_DISABLE #define __LTDC_FORCE_RESET __HAL_RCC_LTDC_FORCE_RESET #define __LTDC_RELEASE_RESET __HAL_RCC_LTDC_RELEASE_RESET #define __LTDC_CLK_SLEEP_ENABLE __HAL_RCC_LTDC_CLK_SLEEP_ENABLE #define __ETHMAC_CLK_SLEEP_ENABLE __HAL_RCC_ETHMAC_CLK_SLEEP_ENABLE #define __ETHMAC_CLK_SLEEP_DISABLE __HAL_RCC_ETHMAC_CLK_SLEEP_DISABLE #define __ETHMACTX_CLK_SLEEP_ENABLE __HAL_RCC_ETHMACTX_CLK_SLEEP_ENABLE #define __ETHMACTX_CLK_SLEEP_DISABLE __HAL_RCC_ETHMACTX_CLK_SLEEP_DISABLE #define __ETHMACRX_CLK_SLEEP_ENABLE __HAL_RCC_ETHMACRX_CLK_SLEEP_ENABLE #define __ETHMACRX_CLK_SLEEP_DISABLE __HAL_RCC_ETHMACRX_CLK_SLEEP_DISABLE #define __TIM12_CLK_SLEEP_ENABLE __HAL_RCC_TIM12_CLK_SLEEP_ENABLE #define __TIM12_CLK_SLEEP_DISABLE __HAL_RCC_TIM12_CLK_SLEEP_DISABLE #define __TIM13_CLK_SLEEP_ENABLE __HAL_RCC_TIM13_CLK_SLEEP_ENABLE #define __TIM13_CLK_SLEEP_DISABLE __HAL_RCC_TIM13_CLK_SLEEP_DISABLE #define __TIM14_CLK_SLEEP_ENABLE __HAL_RCC_TIM14_CLK_SLEEP_ENABLE #define __TIM14_CLK_SLEEP_DISABLE __HAL_RCC_TIM14_CLK_SLEEP_DISABLE #define __BKPSRAM_CLK_ENABLE __HAL_RCC_BKPSRAM_CLK_ENABLE #define __BKPSRAM_CLK_DISABLE __HAL_RCC_BKPSRAM_CLK_DISABLE #define __BKPSRAM_CLK_SLEEP_ENABLE __HAL_RCC_BKPSRAM_CLK_SLEEP_ENABLE #define __BKPSRAM_CLK_SLEEP_DISABLE __HAL_RCC_BKPSRAM_CLK_SLEEP_DISABLE #define __CCMDATARAMEN_CLK_ENABLE __HAL_RCC_CCMDATARAMEN_CLK_ENABLE #define __CCMDATARAMEN_CLK_DISABLE __HAL_RCC_CCMDATARAMEN_CLK_DISABLE #define __USART6_CLK_ENABLE __HAL_RCC_USART6_CLK_ENABLE #define __USART6_CLK_DISABLE __HAL_RCC_USART6_CLK_DISABLE #define __USART6_FORCE_RESET __HAL_RCC_USART6_FORCE_RESET #define __USART6_RELEASE_RESET __HAL_RCC_USART6_RELEASE_RESET #define __USART6_CLK_SLEEP_ENABLE __HAL_RCC_USART6_CLK_SLEEP_ENABLE #define __USART6_CLK_SLEEP_DISABLE __HAL_RCC_USART6_CLK_SLEEP_DISABLE #define __SPI4_CLK_ENABLE __HAL_RCC_SPI4_CLK_ENABLE #define __SPI4_CLK_DISABLE __HAL_RCC_SPI4_CLK_DISABLE #define __SPI4_FORCE_RESET __HAL_RCC_SPI4_FORCE_RESET #define __SPI4_RELEASE_RESET __HAL_RCC_SPI4_RELEASE_RESET #define __SPI4_CLK_SLEEP_ENABLE __HAL_RCC_SPI4_CLK_SLEEP_ENABLE #define __SPI4_CLK_SLEEP_DISABLE __HAL_RCC_SPI4_CLK_SLEEP_DISABLE #define __GPIOI_CLK_ENABLE __HAL_RCC_GPIOI_CLK_ENABLE #define __GPIOI_CLK_DISABLE __HAL_RCC_GPIOI_CLK_DISABLE #define __GPIOI_FORCE_RESET __HAL_RCC_GPIOI_FORCE_RESET #define __GPIOI_RELEASE_RESET __HAL_RCC_GPIOI_RELEASE_RESET #define __GPIOI_CLK_SLEEP_ENABLE __HAL_RCC_GPIOI_CLK_SLEEP_ENABLE #define __GPIOI_CLK_SLEEP_DISABLE __HAL_RCC_GPIOI_CLK_SLEEP_DISABLE #define __GPIOJ_CLK_ENABLE __HAL_RCC_GPIOJ_CLK_ENABLE #define __GPIOJ_CLK_DISABLE __HAL_RCC_GPIOJ_CLK_DISABLE #define __GPIOJ_FORCE_RESET __HAL_RCC_GPIOJ_FORCE_RESET #define __GPIOJ_RELEASE_RESET __HAL_RCC_GPIOJ_RELEASE_RESET #define __GPIOJ_CLK_SLEEP_ENABLE __HAL_RCC_GPIOJ_CLK_SLEEP_ENABLE #define __GPIOJ_CLK_SLEEP_DISABLE __HAL_RCC_GPIOJ_CLK_SLEEP_DISABLE #define __GPIOK_CLK_ENABLE __HAL_RCC_GPIOK_CLK_ENABLE #define __GPIOK_CLK_DISABLE __HAL_RCC_GPIOK_CLK_DISABLE #define __GPIOK_RELEASE_RESET __HAL_RCC_GPIOK_RELEASE_RESET #define __GPIOK_CLK_SLEEP_ENABLE __HAL_RCC_GPIOK_CLK_SLEEP_ENABLE #define __GPIOK_CLK_SLEEP_DISABLE __HAL_RCC_GPIOK_CLK_SLEEP_DISABLE #define __ETH_CLK_ENABLE __HAL_RCC_ETH_CLK_ENABLE #define __ETH_CLK_DISABLE __HAL_RCC_ETH_CLK_DISABLE #define __DCMI_CLK_ENABLE __HAL_RCC_DCMI_CLK_ENABLE #define __DCMI_CLK_DISABLE __HAL_RCC_DCMI_CLK_DISABLE #define __DCMI_FORCE_RESET __HAL_RCC_DCMI_FORCE_RESET #define __DCMI_RELEASE_RESET __HAL_RCC_DCMI_RELEASE_RESET #define __DCMI_CLK_SLEEP_ENABLE __HAL_RCC_DCMI_CLK_SLEEP_ENABLE #define __DCMI_CLK_SLEEP_DISABLE __HAL_RCC_DCMI_CLK_SLEEP_DISABLE #define __UART7_CLK_ENABLE __HAL_RCC_UART7_CLK_ENABLE #define __UART7_CLK_DISABLE __HAL_RCC_UART7_CLK_DISABLE #define __UART7_RELEASE_RESET __HAL_RCC_UART7_RELEASE_RESET #define __UART7_FORCE_RESET __HAL_RCC_UART7_FORCE_RESET #define __UART7_CLK_SLEEP_ENABLE __HAL_RCC_UART7_CLK_SLEEP_ENABLE #define __UART7_CLK_SLEEP_DISABLE __HAL_RCC_UART7_CLK_SLEEP_DISABLE #define __UART8_CLK_ENABLE __HAL_RCC_UART8_CLK_ENABLE #define __UART8_CLK_DISABLE __HAL_RCC_UART8_CLK_DISABLE #define __UART8_FORCE_RESET __HAL_RCC_UART8_FORCE_RESET #define __UART8_RELEASE_RESET __HAL_RCC_UART8_RELEASE_RESET #define __UART8_CLK_SLEEP_ENABLE __HAL_RCC_UART8_CLK_SLEEP_ENABLE #define __UART8_CLK_SLEEP_DISABLE __HAL_RCC_UART8_CLK_SLEEP_DISABLE #define __OTGHS_CLK_SLEEP_ENABLE __HAL_RCC_USB_OTG_HS_CLK_SLEEP_ENABLE #define __OTGHS_CLK_SLEEP_DISABLE __HAL_RCC_USB_OTG_HS_CLK_SLEEP_DISABLE #define __OTGHS_FORCE_RESET __HAL_RCC_USB_OTG_HS_FORCE_RESET #define __OTGHS_RELEASE_RESET __HAL_RCC_USB_OTG_HS_RELEASE_RESET #define __OTGHSULPI_CLK_SLEEP_ENABLE __HAL_RCC_USB_OTG_HS_ULPI_CLK_SLEEP_ENABLE #define __OTGHSULPI_CLK_SLEEP_DISABLE __HAL_RCC_USB_OTG_HS_ULPI_CLK_SLEEP_DISABLE #define __HAL_RCC_OTGHS_CLK_SLEEP_ENABLE __HAL_RCC_USB_OTG_HS_CLK_SLEEP_ENABLE #define __HAL_RCC_OTGHS_CLK_SLEEP_DISABLE __HAL_RCC_USB_OTG_HS_CLK_SLEEP_DISABLE #define __HAL_RCC_OTGHS_IS_CLK_SLEEP_ENABLED __HAL_RCC_USB_OTG_HS_IS_CLK_SLEEP_ENABLED #define __HAL_RCC_OTGHS_IS_CLK_SLEEP_DISABLED __HAL_RCC_USB_OTG_HS_IS_CLK_SLEEP_DISABLED #define __HAL_RCC_OTGHS_FORCE_RESET __HAL_RCC_USB_OTG_HS_FORCE_RESET #define __HAL_RCC_OTGHS_RELEASE_RESET __HAL_RCC_USB_OTG_HS_RELEASE_RESET #define __HAL_RCC_OTGHSULPI_CLK_SLEEP_ENABLE __HAL_RCC_USB_OTG_HS_ULPI_CLK_SLEEP_ENABLE #define __HAL_RCC_OTGHSULPI_CLK_SLEEP_DISABLE __HAL_RCC_USB_OTG_HS_ULPI_CLK_SLEEP_DISABLE #define __HAL_RCC_OTGHSULPI_IS_CLK_SLEEP_ENABLED __HAL_RCC_USB_OTG_HS_ULPI_IS_CLK_SLEEP_ENABLED #define __HAL_RCC_OTGHSULPI_IS_CLK_SLEEP_DISABLED __HAL_RCC_USB_OTG_HS_ULPI_IS_CLK_SLEEP_DISABLED #define __CRYP_FORCE_RESET __HAL_RCC_CRYP_FORCE_RESET #define __SRAM3_CLK_SLEEP_ENABLE __HAL_RCC_SRAM3_CLK_SLEEP_ENABLE #define __CAN2_CLK_SLEEP_ENABLE __HAL_RCC_CAN2_CLK_SLEEP_ENABLE #define __CAN2_CLK_SLEEP_DISABLE __HAL_RCC_CAN2_CLK_SLEEP_DISABLE #define __DAC_CLK_SLEEP_ENABLE __HAL_RCC_DAC_CLK_SLEEP_ENABLE #define __DAC_CLK_SLEEP_DISABLE __HAL_RCC_DAC_CLK_SLEEP_DISABLE #define __ADC2_CLK_SLEEP_ENABLE __HAL_RCC_ADC2_CLK_SLEEP_ENABLE #define __ADC2_CLK_SLEEP_DISABLE __HAL_RCC_ADC2_CLK_SLEEP_DISABLE #define __ADC3_CLK_SLEEP_ENABLE __HAL_RCC_ADC3_CLK_SLEEP_ENABLE #define __ADC3_CLK_SLEEP_DISABLE __HAL_RCC_ADC3_CLK_SLEEP_DISABLE #define __FSMC_FORCE_RESET __HAL_RCC_FSMC_FORCE_RESET #define __FSMC_RELEASE_RESET __HAL_RCC_FSMC_RELEASE_RESET #define __FSMC_CLK_SLEEP_ENABLE __HAL_RCC_FSMC_CLK_SLEEP_ENABLE #define __FSMC_CLK_SLEEP_DISABLE __HAL_RCC_FSMC_CLK_SLEEP_DISABLE #define __SDIO_FORCE_RESET __HAL_RCC_SDIO_FORCE_RESET #define __SDIO_RELEASE_RESET __HAL_RCC_SDIO_RELEASE_RESET #define __SDIO_CLK_SLEEP_DISABLE __HAL_RCC_SDIO_CLK_SLEEP_DISABLE #define __SDIO_CLK_SLEEP_ENABLE __HAL_RCC_SDIO_CLK_SLEEP_ENABLE #define __DMA2D_CLK_ENABLE __HAL_RCC_DMA2D_CLK_ENABLE #define __DMA2D_CLK_DISABLE __HAL_RCC_DMA2D_CLK_DISABLE #define __DMA2D_FORCE_RESET __HAL_RCC_DMA2D_FORCE_RESET #define __DMA2D_RELEASE_RESET __HAL_RCC_DMA2D_RELEASE_RESET #define __DMA2D_CLK_SLEEP_ENABLE __HAL_RCC_DMA2D_CLK_SLEEP_ENABLE #define __DMA2D_CLK_SLEEP_DISABLE __HAL_RCC_DMA2D_CLK_SLEEP_DISABLE /* alias define maintained for legacy */ #define __HAL_RCC_OTGFS_FORCE_RESET __HAL_RCC_USB_OTG_FS_FORCE_RESET #define __HAL_RCC_OTGFS_RELEASE_RESET __HAL_RCC_USB_OTG_FS_RELEASE_RESET #define __ADC12_CLK_ENABLE __HAL_RCC_ADC12_CLK_ENABLE #define __ADC12_CLK_DISABLE __HAL_RCC_ADC12_CLK_DISABLE #define __ADC34_CLK_ENABLE __HAL_RCC_ADC34_CLK_ENABLE #define __ADC34_CLK_DISABLE __HAL_RCC_ADC34_CLK_DISABLE #define __ADC12_CLK_ENABLE __HAL_RCC_ADC12_CLK_ENABLE #define __ADC12_CLK_DISABLE __HAL_RCC_ADC12_CLK_DISABLE #define __DAC2_CLK_ENABLE __HAL_RCC_DAC2_CLK_ENABLE #define __DAC2_CLK_DISABLE __HAL_RCC_DAC2_CLK_DISABLE #define __TIM18_CLK_ENABLE __HAL_RCC_TIM18_CLK_ENABLE #define __TIM18_CLK_DISABLE __HAL_RCC_TIM18_CLK_DISABLE #define __TIM19_CLK_ENABLE __HAL_RCC_TIM19_CLK_ENABLE #define __TIM19_CLK_DISABLE __HAL_RCC_TIM19_CLK_DISABLE #define __TIM20_CLK_ENABLE __HAL_RCC_TIM20_CLK_ENABLE #define __TIM20_CLK_DISABLE __HAL_RCC_TIM20_CLK_DISABLE #define __HRTIM1_CLK_ENABLE __HAL_RCC_HRTIM1_CLK_ENABLE #define __HRTIM1_CLK_DISABLE __HAL_RCC_HRTIM1_CLK_DISABLE #define __SDADC1_CLK_ENABLE __HAL_RCC_SDADC1_CLK_ENABLE #define __SDADC2_CLK_ENABLE __HAL_RCC_SDADC2_CLK_ENABLE #define __SDADC3_CLK_ENABLE __HAL_RCC_SDADC3_CLK_ENABLE #define __SDADC1_CLK_DISABLE __HAL_RCC_SDADC1_CLK_DISABLE #define __SDADC2_CLK_DISABLE __HAL_RCC_SDADC2_CLK_DISABLE #define __SDADC3_CLK_DISABLE __HAL_RCC_SDADC3_CLK_DISABLE #define __ADC12_FORCE_RESET __HAL_RCC_ADC12_FORCE_RESET #define __ADC12_RELEASE_RESET __HAL_RCC_ADC12_RELEASE_RESET #define __ADC34_FORCE_RESET __HAL_RCC_ADC34_FORCE_RESET #define __ADC34_RELEASE_RESET __HAL_RCC_ADC34_RELEASE_RESET #define __ADC12_FORCE_RESET __HAL_RCC_ADC12_FORCE_RESET #define __ADC12_RELEASE_RESET __HAL_RCC_ADC12_RELEASE_RESET #define __DAC2_FORCE_RESET __HAL_RCC_DAC2_FORCE_RESET #define __DAC2_RELEASE_RESET __HAL_RCC_DAC2_RELEASE_RESET #define __TIM18_FORCE_RESET __HAL_RCC_TIM18_FORCE_RESET #define __TIM18_RELEASE_RESET __HAL_RCC_TIM18_RELEASE_RESET #define __TIM19_FORCE_RESET __HAL_RCC_TIM19_FORCE_RESET #define __TIM19_RELEASE_RESET __HAL_RCC_TIM19_RELEASE_RESET #define __TIM20_FORCE_RESET __HAL_RCC_TIM20_FORCE_RESET #define __TIM20_RELEASE_RESET __HAL_RCC_TIM20_RELEASE_RESET #define __HRTIM1_FORCE_RESET __HAL_RCC_HRTIM1_FORCE_RESET #define __HRTIM1_RELEASE_RESET __HAL_RCC_HRTIM1_RELEASE_RESET #define __SDADC1_FORCE_RESET __HAL_RCC_SDADC1_FORCE_RESET #define __SDADC2_FORCE_RESET __HAL_RCC_SDADC2_FORCE_RESET #define __SDADC3_FORCE_RESET __HAL_RCC_SDADC3_FORCE_RESET #define __SDADC1_RELEASE_RESET __HAL_RCC_SDADC1_RELEASE_RESET #define __SDADC2_RELEASE_RESET __HAL_RCC_SDADC2_RELEASE_RESET #define __SDADC3_RELEASE_RESET __HAL_RCC_SDADC3_RELEASE_RESET #define __ADC1_IS_CLK_ENABLED __HAL_RCC_ADC1_IS_CLK_ENABLED #define __ADC1_IS_CLK_DISABLED __HAL_RCC_ADC1_IS_CLK_DISABLED #define __ADC12_IS_CLK_ENABLED __HAL_RCC_ADC12_IS_CLK_ENABLED #define __ADC12_IS_CLK_DISABLED __HAL_RCC_ADC12_IS_CLK_DISABLED #define __ADC34_IS_CLK_ENABLED __HAL_RCC_ADC34_IS_CLK_ENABLED #define __ADC34_IS_CLK_DISABLED __HAL_RCC_ADC34_IS_CLK_DISABLED #define __CEC_IS_CLK_ENABLED __HAL_RCC_CEC_IS_CLK_ENABLED #define __CEC_IS_CLK_DISABLED __HAL_RCC_CEC_IS_CLK_DISABLED #define __CRC_IS_CLK_ENABLED __HAL_RCC_CRC_IS_CLK_ENABLED #define __CRC_IS_CLK_DISABLED __HAL_RCC_CRC_IS_CLK_DISABLED #define __DAC1_IS_CLK_ENABLED __HAL_RCC_DAC1_IS_CLK_ENABLED #define __DAC1_IS_CLK_DISABLED __HAL_RCC_DAC1_IS_CLK_DISABLED #define __DAC2_IS_CLK_ENABLED __HAL_RCC_DAC2_IS_CLK_ENABLED #define __DAC2_IS_CLK_DISABLED __HAL_RCC_DAC2_IS_CLK_DISABLED #define __DMA1_IS_CLK_ENABLED __HAL_RCC_DMA1_IS_CLK_ENABLED #define __DMA1_IS_CLK_DISABLED __HAL_RCC_DMA1_IS_CLK_DISABLED #define __DMA2_IS_CLK_ENABLED __HAL_RCC_DMA2_IS_CLK_ENABLED #define __DMA2_IS_CLK_DISABLED __HAL_RCC_DMA2_IS_CLK_DISABLED #define __FLITF_IS_CLK_ENABLED __HAL_RCC_FLITF_IS_CLK_ENABLED #define __FLITF_IS_CLK_DISABLED __HAL_RCC_FLITF_IS_CLK_DISABLED #define __FMC_IS_CLK_ENABLED __HAL_RCC_FMC_IS_CLK_ENABLED #define __FMC_IS_CLK_DISABLED __HAL_RCC_FMC_IS_CLK_DISABLED #define __GPIOA_IS_CLK_ENABLED __HAL_RCC_GPIOA_IS_CLK_ENABLED #define __GPIOA_IS_CLK_DISABLED __HAL_RCC_GPIOA_IS_CLK_DISABLED #define __GPIOB_IS_CLK_ENABLED __HAL_RCC_GPIOB_IS_CLK_ENABLED #define __GPIOB_IS_CLK_DISABLED __HAL_RCC_GPIOB_IS_CLK_DISABLED #define __GPIOC_IS_CLK_ENABLED __HAL_RCC_GPIOC_IS_CLK_ENABLED #define __GPIOC_IS_CLK_DISABLED __HAL_RCC_GPIOC_IS_CLK_DISABLED #define __GPIOD_IS_CLK_ENABLED __HAL_RCC_GPIOD_IS_CLK_ENABLED #define __GPIOD_IS_CLK_DISABLED __HAL_RCC_GPIOD_IS_CLK_DISABLED #define __GPIOE_IS_CLK_ENABLED __HAL_RCC_GPIOE_IS_CLK_ENABLED #define __GPIOE_IS_CLK_DISABLED __HAL_RCC_GPIOE_IS_CLK_DISABLED #define __GPIOF_IS_CLK_ENABLED __HAL_RCC_GPIOF_IS_CLK_ENABLED #define __GPIOF_IS_CLK_DISABLED __HAL_RCC_GPIOF_IS_CLK_DISABLED #define __GPIOG_IS_CLK_ENABLED __HAL_RCC_GPIOG_IS_CLK_ENABLED #define __GPIOG_IS_CLK_DISABLED __HAL_RCC_GPIOG_IS_CLK_DISABLED #define __GPIOH_IS_CLK_ENABLED __HAL_RCC_GPIOH_IS_CLK_ENABLED #define __GPIOH_IS_CLK_DISABLED __HAL_RCC_GPIOH_IS_CLK_DISABLED #define __HRTIM1_IS_CLK_ENABLED __HAL_RCC_HRTIM1_IS_CLK_ENABLED #define __HRTIM1_IS_CLK_DISABLED __HAL_RCC_HRTIM1_IS_CLK_DISABLED #define __I2C1_IS_CLK_ENABLED __HAL_RCC_I2C1_IS_CLK_ENABLED #define __I2C1_IS_CLK_DISABLED __HAL_RCC_I2C1_IS_CLK_DISABLED #define __I2C2_IS_CLK_ENABLED __HAL_RCC_I2C2_IS_CLK_ENABLED #define __I2C2_IS_CLK_DISABLED __HAL_RCC_I2C2_IS_CLK_DISABLED #define __I2C3_IS_CLK_ENABLED __HAL_RCC_I2C3_IS_CLK_ENABLED #define __I2C3_IS_CLK_DISABLED __HAL_RCC_I2C3_IS_CLK_DISABLED #define __PWR_IS_CLK_ENABLED __HAL_RCC_PWR_IS_CLK_ENABLED #define __PWR_IS_CLK_DISABLED __HAL_RCC_PWR_IS_CLK_DISABLED #define __SYSCFG_IS_CLK_ENABLED __HAL_RCC_SYSCFG_IS_CLK_ENABLED #define __SYSCFG_IS_CLK_DISABLED __HAL_RCC_SYSCFG_IS_CLK_DISABLED #define __SPI1_IS_CLK_ENABLED __HAL_RCC_SPI1_IS_CLK_ENABLED #define __SPI1_IS_CLK_DISABLED __HAL_RCC_SPI1_IS_CLK_DISABLED #define __SPI2_IS_CLK_ENABLED __HAL_RCC_SPI2_IS_CLK_ENABLED #define __SPI2_IS_CLK_DISABLED __HAL_RCC_SPI2_IS_CLK_DISABLED #define __SPI3_IS_CLK_ENABLED __HAL_RCC_SPI3_IS_CLK_ENABLED #define __SPI3_IS_CLK_DISABLED __HAL_RCC_SPI3_IS_CLK_DISABLED #define __SPI4_IS_CLK_ENABLED __HAL_RCC_SPI4_IS_CLK_ENABLED #define __SPI4_IS_CLK_DISABLED __HAL_RCC_SPI4_IS_CLK_DISABLED #define __SDADC1_IS_CLK_ENABLED __HAL_RCC_SDADC1_IS_CLK_ENABLED #define __SDADC1_IS_CLK_DISABLED __HAL_RCC_SDADC1_IS_CLK_DISABLED #define __SDADC2_IS_CLK_ENABLED __HAL_RCC_SDADC2_IS_CLK_ENABLED #define __SDADC2_IS_CLK_DISABLED __HAL_RCC_SDADC2_IS_CLK_DISABLED #define __SDADC3_IS_CLK_ENABLED __HAL_RCC_SDADC3_IS_CLK_ENABLED #define __SDADC3_IS_CLK_DISABLED __HAL_RCC_SDADC3_IS_CLK_DISABLED #define __SRAM_IS_CLK_ENABLED __HAL_RCC_SRAM_IS_CLK_ENABLED #define __SRAM_IS_CLK_DISABLED __HAL_RCC_SRAM_IS_CLK_DISABLED #define __TIM1_IS_CLK_ENABLED __HAL_RCC_TIM1_IS_CLK_ENABLED #define __TIM1_IS_CLK_DISABLED __HAL_RCC_TIM1_IS_CLK_DISABLED #define __TIM2_IS_CLK_ENABLED __HAL_RCC_TIM2_IS_CLK_ENABLED #define __TIM2_IS_CLK_DISABLED __HAL_RCC_TIM2_IS_CLK_DISABLED #define __TIM3_IS_CLK_ENABLED __HAL_RCC_TIM3_IS_CLK_ENABLED #define __TIM3_IS_CLK_DISABLED __HAL_RCC_TIM3_IS_CLK_DISABLED #define __TIM4_IS_CLK_ENABLED __HAL_RCC_TIM4_IS_CLK_ENABLED #define __TIM4_IS_CLK_DISABLED __HAL_RCC_TIM4_IS_CLK_DISABLED #define __TIM5_IS_CLK_ENABLED __HAL_RCC_TIM5_IS_CLK_ENABLED #define __TIM5_IS_CLK_DISABLED __HAL_RCC_TIM5_IS_CLK_DISABLED #define __TIM6_IS_CLK_ENABLED __HAL_RCC_TIM6_IS_CLK_ENABLED #define __TIM6_IS_CLK_DISABLED __HAL_RCC_TIM6_IS_CLK_DISABLED #define __TIM7_IS_CLK_ENABLED __HAL_RCC_TIM7_IS_CLK_ENABLED #define __TIM7_IS_CLK_DISABLED __HAL_RCC_TIM7_IS_CLK_DISABLED #define __TIM8_IS_CLK_ENABLED __HAL_RCC_TIM8_IS_CLK_ENABLED #define __TIM8_IS_CLK_DISABLED __HAL_RCC_TIM8_IS_CLK_DISABLED #define __TIM12_IS_CLK_ENABLED __HAL_RCC_TIM12_IS_CLK_ENABLED #define __TIM12_IS_CLK_DISABLED __HAL_RCC_TIM12_IS_CLK_DISABLED #define __TIM13_IS_CLK_ENABLED __HAL_RCC_TIM13_IS_CLK_ENABLED #define __TIM13_IS_CLK_DISABLED __HAL_RCC_TIM13_IS_CLK_DISABLED #define __TIM14_IS_CLK_ENABLED __HAL_RCC_TIM14_IS_CLK_ENABLED #define __TIM14_IS_CLK_DISABLED __HAL_RCC_TIM14_IS_CLK_DISABLED #define __TIM15_IS_CLK_ENABLED __HAL_RCC_TIM15_IS_CLK_ENABLED #define __TIM15_IS_CLK_DISABLED __HAL_RCC_TIM15_IS_CLK_DISABLED #define __TIM16_IS_CLK_ENABLED __HAL_RCC_TIM16_IS_CLK_ENABLED #define __TIM16_IS_CLK_DISABLED __HAL_RCC_TIM16_IS_CLK_DISABLED #define __TIM17_IS_CLK_ENABLED __HAL_RCC_TIM17_IS_CLK_ENABLED #define __TIM17_IS_CLK_DISABLED __HAL_RCC_TIM17_IS_CLK_DISABLED #define __TIM18_IS_CLK_ENABLED __HAL_RCC_TIM18_IS_CLK_ENABLED #define __TIM18_IS_CLK_DISABLED __HAL_RCC_TIM18_IS_CLK_DISABLED #define __TIM19_IS_CLK_ENABLED __HAL_RCC_TIM19_IS_CLK_ENABLED #define __TIM19_IS_CLK_DISABLED __HAL_RCC_TIM19_IS_CLK_DISABLED #define __TIM20_IS_CLK_ENABLED __HAL_RCC_TIM20_IS_CLK_ENABLED #define __TIM20_IS_CLK_DISABLED __HAL_RCC_TIM20_IS_CLK_DISABLED #define __TSC_IS_CLK_ENABLED __HAL_RCC_TSC_IS_CLK_ENABLED #define __TSC_IS_CLK_DISABLED __HAL_RCC_TSC_IS_CLK_DISABLED #define __UART4_IS_CLK_ENABLED __HAL_RCC_UART4_IS_CLK_ENABLED #define __UART4_IS_CLK_DISABLED __HAL_RCC_UART4_IS_CLK_DISABLED #define __UART5_IS_CLK_ENABLED __HAL_RCC_UART5_IS_CLK_ENABLED #define __UART5_IS_CLK_DISABLED __HAL_RCC_UART5_IS_CLK_DISABLED #define __USART1_IS_CLK_ENABLED __HAL_RCC_USART1_IS_CLK_ENABLED #define __USART1_IS_CLK_DISABLED __HAL_RCC_USART1_IS_CLK_DISABLED #define __USART2_IS_CLK_ENABLED __HAL_RCC_USART2_IS_CLK_ENABLED #define __USART2_IS_CLK_DISABLED __HAL_RCC_USART2_IS_CLK_DISABLED #define __USART3_IS_CLK_ENABLED __HAL_RCC_USART3_IS_CLK_ENABLED #define __USART3_IS_CLK_DISABLED __HAL_RCC_USART3_IS_CLK_DISABLED #define __USB_IS_CLK_ENABLED __HAL_RCC_USB_IS_CLK_ENABLED #define __USB_IS_CLK_DISABLED __HAL_RCC_USB_IS_CLK_DISABLED #define __WWDG_IS_CLK_ENABLED __HAL_RCC_WWDG_IS_CLK_ENABLED #define __WWDG_IS_CLK_DISABLED __HAL_RCC_WWDG_IS_CLK_DISABLED #if defined(STM32F4) #define __HAL_RCC_SDMMC1_CLK_ENABLE __HAL_RCC_SDIO_CLK_ENABLE #define __HAL_RCC_SDMMC1_FORCE_RESET __HAL_RCC_SDIO_FORCE_RESET #define __HAL_RCC_SDMMC1_RELEASE_RESET __HAL_RCC_SDIO_RELEASE_RESET #define __HAL_RCC_SDMMC1_CLK_SLEEP_ENABLE __HAL_RCC_SDIO_CLK_SLEEP_ENABLE #define __HAL_RCC_SDMMC1_CLK_SLEEP_DISABLE __HAL_RCC_SDIO_CLK_SLEEP_DISABLE #define __HAL_RCC_SDMMC1_CLK_ENABLE __HAL_RCC_SDIO_CLK_ENABLE #define __HAL_RCC_SDMMC1_CLK_DISABLE __HAL_RCC_SDIO_CLK_DISABLE #define Sdmmc1ClockSelection SdioClockSelection #define RCC_PERIPHCLK_SDMMC1 RCC_PERIPHCLK_SDIO #define RCC_SDMMC1CLKSOURCE_CLK48 RCC_SDIOCLKSOURCE_CK48 #define RCC_SDMMC1CLKSOURCE_SYSCLK RCC_SDIOCLKSOURCE_SYSCLK #define __HAL_RCC_SDMMC1_CONFIG __HAL_RCC_SDIO_CONFIG #define __HAL_RCC_GET_SDMMC1_SOURCE __HAL_RCC_GET_SDIO_SOURCE #endif #if defined(STM32F7) || defined(STM32L4) #define __HAL_RCC_SDIO_CLK_ENABLE __HAL_RCC_SDMMC1_CLK_ENABLE #define __HAL_RCC_SDIO_FORCE_RESET __HAL_RCC_SDMMC1_FORCE_RESET #define __HAL_RCC_SDIO_RELEASE_RESET __HAL_RCC_SDMMC1_RELEASE_RESET #define __HAL_RCC_SDIO_CLK_SLEEP_ENABLE __HAL_RCC_SDMMC1_CLK_SLEEP_ENABLE #define __HAL_RCC_SDIO_CLK_SLEEP_DISABLE __HAL_RCC_SDMMC1_CLK_SLEEP_DISABLE #define __HAL_RCC_SDIO_CLK_ENABLE __HAL_RCC_SDMMC1_CLK_ENABLE #define __HAL_RCC_SDIO_CLK_DISABLE __HAL_RCC_SDMMC1_CLK_DISABLE #define SdioClockSelection Sdmmc1ClockSelection #define RCC_PERIPHCLK_SDIO RCC_PERIPHCLK_SDMMC1 #define __HAL_RCC_SDIO_CONFIG __HAL_RCC_SDMMC1_CONFIG #define __HAL_RCC_GET_SDIO_SOURCE __HAL_RCC_GET_SDMMC1_SOURCE #endif #if defined(STM32F7) #define RCC_SDIOCLKSOURCE_CK48 RCC_SDMMC1CLKSOURCE_CLK48 #define RCC_SDIOCLKSOURCE_SYSCLK RCC_SDMMC1CLKSOURCE_SYSCLK #endif #define __HAL_RCC_I2SCLK __HAL_RCC_I2S_CONFIG #define __HAL_RCC_I2SCLK_CONFIG __HAL_RCC_I2S_CONFIG #define __RCC_PLLSRC RCC_GET_PLL_OSCSOURCE #define IS_RCC_MSIRANGE IS_RCC_MSI_CLOCK_RANGE #define IS_RCC_RTCCLK_SOURCE IS_RCC_RTCCLKSOURCE #define IS_RCC_SYSCLK_DIV IS_RCC_HCLK #define IS_RCC_HCLK_DIV IS_RCC_PCLK #define RCC_IT_HSI14 RCC_IT_HSI14RDY #define IS_RCC_MCOSOURCE IS_RCC_MCO1SOURCE #define __HAL_RCC_MCO_CONFIG __HAL_RCC_MCO1_CONFIG #define RCC_MCO_NODIV RCC_MCODIV_1 #define RCC_MCO_DIV1 RCC_MCODIV_1 #define RCC_MCO_DIV2 RCC_MCODIV_2 #define RCC_MCO_DIV4 RCC_MCODIV_4 #define RCC_MCO_DIV8 RCC_MCODIV_8 #define RCC_MCO_DIV16 RCC_MCODIV_16 #define RCC_MCO_DIV32 RCC_MCODIV_32 #define RCC_MCO_DIV64 RCC_MCODIV_64 #define RCC_MCO_DIV128 RCC_MCODIV_128 #define RCC_MCOSOURCE_NONE RCC_MCO1SOURCE_NOCLOCK #define RCC_MCOSOURCE_LSI RCC_MCO1SOURCE_LSI #define RCC_MCOSOURCE_LSE RCC_MCO1SOURCE_LSE #define RCC_MCOSOURCE_SYSCLK RCC_MCO1SOURCE_SYSCLK #define RCC_MCOSOURCE_HSI RCC_MCO1SOURCE_HSI #define RCC_MCOSOURCE_HSI14 RCC_MCO1SOURCE_HSI14 #define RCC_MCOSOURCE_HSI48 RCC_MCO1SOURCE_HSI48 #define RCC_MCOSOURCE_HSE RCC_MCO1SOURCE_HSE #define RCC_MCOSOURCE_PLLCLK_DIV1 RCC_MCO1SOURCE_PLLCLK #define RCC_MCOSOURCE_PLLCLK_NODIV RCC_MCO1SOURCE_PLLCLK #define RCC_MCOSOURCE_PLLCLK_DIV2 RCC_MCO1SOURCE_PLLCLK_DIV2 #define RCC_RTCCLKSOURCE_NONE RCC_RTCCLKSOURCE_NO_CLK #define RCC_USBCLK_PLLSAI1 RCC_USBCLKSOURCE_PLLSAI1 #define RCC_USBCLK_PLL RCC_USBCLKSOURCE_PLL #define RCC_USBCLK_MSI RCC_USBCLKSOURCE_MSI #define RCC_USBCLKSOURCE_PLLCLK RCC_USBCLKSOURCE_PLL #define RCC_USBPLLCLK_DIV1 RCC_USBCLKSOURCE_PLL #define RCC_USBPLLCLK_DIV1_5 RCC_USBCLKSOURCE_PLL_DIV1_5 #define RCC_USBPLLCLK_DIV2 RCC_USBCLKSOURCE_PLL_DIV2 #define RCC_USBPLLCLK_DIV3 RCC_USBCLKSOURCE_PLL_DIV3 #define HSION_BitNumber RCC_HSION_BIT_NUMBER #define HSION_BITNUMBER RCC_HSION_BIT_NUMBER #define HSEON_BitNumber RCC_HSEON_BIT_NUMBER #define HSEON_BITNUMBER RCC_HSEON_BIT_NUMBER #define MSION_BITNUMBER RCC_MSION_BIT_NUMBER #define CSSON_BitNumber RCC_CSSON_BIT_NUMBER #define CSSON_BITNUMBER RCC_CSSON_BIT_NUMBER #define PLLON_BitNumber RCC_PLLON_BIT_NUMBER #define PLLON_BITNUMBER RCC_PLLON_BIT_NUMBER #define PLLI2SON_BitNumber RCC_PLLI2SON_BIT_NUMBER #define I2SSRC_BitNumber RCC_I2SSRC_BIT_NUMBER #define RTCEN_BitNumber RCC_RTCEN_BIT_NUMBER #define RTCEN_BITNUMBER RCC_RTCEN_BIT_NUMBER #define BDRST_BitNumber RCC_BDRST_BIT_NUMBER #define BDRST_BITNUMBER RCC_BDRST_BIT_NUMBER #define RTCRST_BITNUMBER RCC_RTCRST_BIT_NUMBER #define LSION_BitNumber RCC_LSION_BIT_NUMBER #define LSION_BITNUMBER RCC_LSION_BIT_NUMBER #define LSEON_BitNumber RCC_LSEON_BIT_NUMBER #define LSEON_BITNUMBER RCC_LSEON_BIT_NUMBER #define LSEBYP_BITNUMBER RCC_LSEBYP_BIT_NUMBER #define PLLSAION_BitNumber RCC_PLLSAION_BIT_NUMBER #define TIMPRE_BitNumber RCC_TIMPRE_BIT_NUMBER #define RMVF_BitNumber RCC_RMVF_BIT_NUMBER #define RMVF_BITNUMBER RCC_RMVF_BIT_NUMBER #define RCC_CR2_HSI14TRIM_BitNumber RCC_HSI14TRIM_BIT_NUMBER #define CR_BYTE2_ADDRESS RCC_CR_BYTE2_ADDRESS #define CIR_BYTE1_ADDRESS RCC_CIR_BYTE1_ADDRESS #define CIR_BYTE2_ADDRESS RCC_CIR_BYTE2_ADDRESS #define BDCR_BYTE0_ADDRESS RCC_BDCR_BYTE0_ADDRESS #define DBP_TIMEOUT_VALUE RCC_DBP_TIMEOUT_VALUE #define LSE_TIMEOUT_VALUE RCC_LSE_TIMEOUT_VALUE #define CR_HSION_BB RCC_CR_HSION_BB #define CR_CSSON_BB RCC_CR_CSSON_BB #define CR_PLLON_BB RCC_CR_PLLON_BB #define CR_PLLI2SON_BB RCC_CR_PLLI2SON_BB #define CR_MSION_BB RCC_CR_MSION_BB #define CSR_LSION_BB RCC_CSR_LSION_BB #define CSR_LSEON_BB RCC_CSR_LSEON_BB #define CSR_LSEBYP_BB RCC_CSR_LSEBYP_BB #define CSR_RTCEN_BB RCC_CSR_RTCEN_BB #define CSR_RTCRST_BB RCC_CSR_RTCRST_BB #define CFGR_I2SSRC_BB RCC_CFGR_I2SSRC_BB #define BDCR_RTCEN_BB RCC_BDCR_RTCEN_BB #define BDCR_BDRST_BB RCC_BDCR_BDRST_BB #define CR_HSEON_BB RCC_CR_HSEON_BB #define CSR_RMVF_BB RCC_CSR_RMVF_BB #define CR_PLLSAION_BB RCC_CR_PLLSAION_BB #define DCKCFGR_TIMPRE_BB RCC_DCKCFGR_TIMPRE_BB /** * @} */ /** @defgroup HAL_RNG_Aliased_Macros HAL RNG Aliased Macros maintained for legacy purpose * @{ */ #define HAL_RNG_ReadyCallback(__HANDLE__) HAL_RNG_ReadyDataCallback((__HANDLE__), uint32_t random32bit) /** * @} */ /** @defgroup HAL_RTC_Aliased_Macros HAL RTC Aliased Macros maintained for legacy purpose * @{ */ #define __HAL_RTC_CLEAR_FLAG __HAL_RTC_EXTI_CLEAR_FLAG #define __HAL_RTC_DISABLE_IT __HAL_RTC_EXTI_DISABLE_IT #define __HAL_RTC_ENABLE_IT __HAL_RTC_EXTI_ENABLE_IT #if defined (STM32F1) #define __HAL_RTC_EXTI_CLEAR_FLAG(RTC_EXTI_LINE_ALARM_EVENT) __HAL_RTC_ALARM_EXTI_CLEAR_FLAG() #define __HAL_RTC_EXTI_ENABLE_IT(RTC_EXTI_LINE_ALARM_EVENT) __HAL_RTC_ALARM_EXTI_ENABLE_IT() #define __HAL_RTC_EXTI_DISABLE_IT(RTC_EXTI_LINE_ALARM_EVENT) __HAL_RTC_ALARM_EXTI_DISABLE_IT() #define __HAL_RTC_EXTI_GET_FLAG(RTC_EXTI_LINE_ALARM_EVENT) __HAL_RTC_ALARM_EXTI_GET_FLAG() #define __HAL_RTC_EXTI_GENERATE_SWIT(RTC_EXTI_LINE_ALARM_EVENT) __HAL_RTC_ALARM_EXTI_GENERATE_SWIT() #else #define __HAL_RTC_EXTI_CLEAR_FLAG(__EXTI_LINE__) (((__EXTI_LINE__) == RTC_EXTI_LINE_ALARM_EVENT) ? __HAL_RTC_ALARM_EXTI_CLEAR_FLAG() : \ (((__EXTI_LINE__) == RTC_EXTI_LINE_WAKEUPTIMER_EVENT) ? __HAL_RTC_WAKEUPTIMER_EXTI_CLEAR_FLAG() : \ __HAL_RTC_TAMPER_TIMESTAMP_EXTI_CLEAR_FLAG())) #define __HAL_RTC_EXTI_ENABLE_IT(__EXTI_LINE__) (((__EXTI_LINE__) == RTC_EXTI_LINE_ALARM_EVENT) ? __HAL_RTC_ALARM_EXTI_ENABLE_IT() : \ (((__EXTI_LINE__) == RTC_EXTI_LINE_WAKEUPTIMER_EVENT) ? __HAL_RTC_WAKEUPTIMER_EXTI_ENABLE_IT() : \ __HAL_RTC_TAMPER_TIMESTAMP_EXTI_ENABLE_IT())) #define __HAL_RTC_EXTI_DISABLE_IT(__EXTI_LINE__) (((__EXTI_LINE__) == RTC_EXTI_LINE_ALARM_EVENT) ? __HAL_RTC_ALARM_EXTI_DISABLE_IT() : \ (((__EXTI_LINE__) == RTC_EXTI_LINE_WAKEUPTIMER_EVENT) ? __HAL_RTC_WAKEUPTIMER_EXTI_DISABLE_IT() : \ __HAL_RTC_TAMPER_TIMESTAMP_EXTI_DISABLE_IT())) #define __HAL_RTC_EXTI_GET_FLAG(__EXTI_LINE__) (((__EXTI_LINE__) == RTC_EXTI_LINE_ALARM_EVENT) ? __HAL_RTC_ALARM_EXTI_GET_FLAG() : \ (((__EXTI_LINE__) == RTC_EXTI_LINE_WAKEUPTIMER_EVENT) ? __HAL_RTC_WAKEUPTIMER_EXTI_GET_FLAG() : \ __HAL_RTC_TAMPER_TIMESTAMP_EXTI_GET_FLAG())) #define __HAL_RTC_EXTI_GENERATE_SWIT(__EXTI_LINE__) (((__EXTI_LINE__) == RTC_EXTI_LINE_ALARM_EVENT) ? __HAL_RTC_ALARM_EXTI_GENERATE_SWIT() : \ (((__EXTI_LINE__) == RTC_EXTI_LINE_WAKEUPTIMER_EVENT) ? __HAL_RTC_WAKEUPTIMER_EXTI_GENERATE_SWIT() : \ __HAL_RTC_TAMPER_TIMESTAMP_EXTI_GENERATE_SWIT())) #endif /* STM32F1 */ #define IS_ALARM IS_RTC_ALARM #define IS_ALARM_MASK IS_RTC_ALARM_MASK #define IS_TAMPER IS_RTC_TAMPER #define IS_TAMPER_ERASE_MODE IS_RTC_TAMPER_ERASE_MODE #define IS_TAMPER_FILTER IS_RTC_TAMPER_FILTER #define IS_TAMPER_INTERRUPT IS_RTC_TAMPER_INTERRUPT #define IS_TAMPER_MASKFLAG_STATE IS_RTC_TAMPER_MASKFLAG_STATE #define IS_TAMPER_PRECHARGE_DURATION IS_RTC_TAMPER_PRECHARGE_DURATION #define IS_TAMPER_PULLUP_STATE IS_RTC_TAMPER_PULLUP_STATE #define IS_TAMPER_SAMPLING_FREQ IS_RTC_TAMPER_SAMPLING_FREQ #define IS_TAMPER_TIMESTAMPONTAMPER_DETECTION IS_RTC_TAMPER_TIMESTAMPONTAMPER_DETECTION #define IS_TAMPER_TRIGGER IS_RTC_TAMPER_TRIGGER #define IS_WAKEUP_CLOCK IS_RTC_WAKEUP_CLOCK #define IS_WAKEUP_COUNTER IS_RTC_WAKEUP_COUNTER #define __RTC_WRITEPROTECTION_ENABLE __HAL_RTC_WRITEPROTECTION_ENABLE #define __RTC_WRITEPROTECTION_DISABLE __HAL_RTC_WRITEPROTECTION_DISABLE /** * @} */ /** @defgroup HAL_SD_Aliased_Macros HAL SD Aliased Macros maintained for legacy purpose * @{ */ #define SD_OCR_CID_CSD_OVERWRIETE SD_OCR_CID_CSD_OVERWRITE #define SD_CMD_SD_APP_STAUS SD_CMD_SD_APP_STATUS #if defined(STM32F4) #define SD_SDMMC_DISABLED SD_SDIO_DISABLED #define SD_SDMMC_FUNCTION_BUSY SD_SDIO_FUNCTION_BUSY #define SD_SDMMC_FUNCTION_FAILED SD_SDIO_FUNCTION_FAILED #define SD_SDMMC_UNKNOWN_FUNCTION SD_SDIO_UNKNOWN_FUNCTION #define SD_CMD_SDMMC_SEN_OP_COND SD_CMD_SDIO_SEN_OP_COND #define SD_CMD_SDMMC_RW_DIRECT SD_CMD_SDIO_RW_DIRECT #define SD_CMD_SDMMC_RW_EXTENDED SD_CMD_SDIO_RW_EXTENDED #define __HAL_SD_SDMMC_ENABLE __HAL_SD_SDIO_ENABLE #define __HAL_SD_SDMMC_DISABLE __HAL_SD_SDIO_DISABLE #define __HAL_SD_SDMMC_DMA_ENABLE __HAL_SD_SDIO_DMA_ENABLE #define __HAL_SD_SDMMC_DMA_DISABLE __HAL_SD_SDIO_DMA_DISABL #define __HAL_SD_SDMMC_ENABLE_IT __HAL_SD_SDIO_ENABLE_IT #define __HAL_SD_SDMMC_DISABLE_IT __HAL_SD_SDIO_DISABLE_IT #define __HAL_SD_SDMMC_GET_FLAG __HAL_SD_SDIO_GET_FLAG #define __HAL_SD_SDMMC_CLEAR_FLAG __HAL_SD_SDIO_CLEAR_FLAG #define __HAL_SD_SDMMC_GET_IT __HAL_SD_SDIO_GET_IT #define __HAL_SD_SDMMC_CLEAR_IT __HAL_SD_SDIO_CLEAR_IT #define SDMMC_STATIC_FLAGS SDIO_STATIC_FLAGS #define SDMMC_CMD0TIMEOUT SDIO_CMD0TIMEOUT #define SD_SDMMC_SEND_IF_COND SD_SDIO_SEND_IF_COND /* alias CMSIS */ #define SDMMC1_IRQn SDIO_IRQn #define SDMMC1_IRQHandler SDIO_IRQHandler #endif #if defined(STM32F7) || defined(STM32L4) #define SD_SDIO_DISABLED SD_SDMMC_DISABLED #define SD_SDIO_FUNCTION_BUSY SD_SDMMC_FUNCTION_BUSY #define SD_SDIO_FUNCTION_FAILED SD_SDMMC_FUNCTION_FAILED #define SD_SDIO_UNKNOWN_FUNCTION SD_SDMMC_UNKNOWN_FUNCTION #define SD_CMD_SDIO_SEN_OP_COND SD_CMD_SDMMC_SEN_OP_COND #define SD_CMD_SDIO_RW_DIRECT SD_CMD_SDMMC_RW_DIRECT #define SD_CMD_SDIO_RW_EXTENDED SD_CMD_SDMMC_RW_EXTENDED #define __HAL_SD_SDIO_ENABLE __HAL_SD_SDMMC_ENABLE #define __HAL_SD_SDIO_DISABLE __HAL_SD_SDMMC_DISABLE #define __HAL_SD_SDIO_DMA_ENABLE __HAL_SD_SDMMC_DMA_ENABLE #define __HAL_SD_SDIO_DMA_DISABL __HAL_SD_SDMMC_DMA_DISABLE #define __HAL_SD_SDIO_ENABLE_IT __HAL_SD_SDMMC_ENABLE_IT #define __HAL_SD_SDIO_DISABLE_IT __HAL_SD_SDMMC_DISABLE_IT #define __HAL_SD_SDIO_GET_FLAG __HAL_SD_SDMMC_GET_FLAG #define __HAL_SD_SDIO_CLEAR_FLAG __HAL_SD_SDMMC_CLEAR_FLAG #define __HAL_SD_SDIO_GET_IT __HAL_SD_SDMMC_GET_IT #define __HAL_SD_SDIO_CLEAR_IT __HAL_SD_SDMMC_CLEAR_IT #define SDIO_STATIC_FLAGS SDMMC_STATIC_FLAGS #define SDIO_CMD0TIMEOUT SDMMC_CMD0TIMEOUT #define SD_SDIO_SEND_IF_COND SD_SDMMC_SEND_IF_COND /* alias CMSIS for compatibilities */ #define SDIO_IRQn SDMMC1_IRQn #define SDIO_IRQHandler SDMMC1_IRQHandler #endif /** * @} */ /** @defgroup HAL_SMARTCARD_Aliased_Macros HAL SMARTCARD Aliased Macros maintained for legacy purpose * @{ */ #define __SMARTCARD_ENABLE_IT __HAL_SMARTCARD_ENABLE_IT #define __SMARTCARD_DISABLE_IT __HAL_SMARTCARD_DISABLE_IT #define __SMARTCARD_ENABLE __HAL_SMARTCARD_ENABLE #define __SMARTCARD_DISABLE __HAL_SMARTCARD_DISABLE #define __SMARTCARD_DMA_REQUEST_ENABLE __HAL_SMARTCARD_DMA_REQUEST_ENABLE #define __SMARTCARD_DMA_REQUEST_DISABLE __HAL_SMARTCARD_DMA_REQUEST_DISABLE #define __HAL_SMARTCARD_GETCLOCKSOURCE SMARTCARD_GETCLOCKSOURCE #define __SMARTCARD_GETCLOCKSOURCE SMARTCARD_GETCLOCKSOURCE #define IS_SMARTCARD_ONEBIT_SAMPLING IS_SMARTCARD_ONE_BIT_SAMPLE /** * @} */ /** @defgroup HAL_SMBUS_Aliased_Macros HAL SMBUS Aliased Macros maintained for legacy purpose * @{ */ #define __HAL_SMBUS_RESET_CR1 SMBUS_RESET_CR1 #define __HAL_SMBUS_RESET_CR2 SMBUS_RESET_CR2 #define __HAL_SMBUS_GENERATE_START SMBUS_GENERATE_START #define __HAL_SMBUS_GET_ADDR_MATCH SMBUS_GET_ADDR_MATCH #define __HAL_SMBUS_GET_DIR SMBUS_GET_DIR #define __HAL_SMBUS_GET_STOP_MODE SMBUS_GET_STOP_MODE #define __HAL_SMBUS_GET_PEC_MODE SMBUS_GET_PEC_MODE #define __HAL_SMBUS_GET_ALERT_ENABLED SMBUS_GET_ALERT_ENABLED /** * @} */ /** @defgroup HAL_SPI_Aliased_Macros HAL SPI Aliased Macros maintained for legacy purpose * @{ */ #define __HAL_SPI_1LINE_TX SPI_1LINE_TX #define __HAL_SPI_1LINE_RX SPI_1LINE_RX #define __HAL_SPI_RESET_CRC SPI_RESET_CRC /** * @} */ /** @defgroup HAL_UART_Aliased_Macros HAL UART Aliased Macros maintained for legacy purpose * @{ */ #define __HAL_UART_GETCLOCKSOURCE UART_GETCLOCKSOURCE #define __HAL_UART_MASK_COMPUTATION UART_MASK_COMPUTATION #define __UART_GETCLOCKSOURCE UART_GETCLOCKSOURCE #define __UART_MASK_COMPUTATION UART_MASK_COMPUTATION #define IS_UART_WAKEUPMETHODE IS_UART_WAKEUPMETHOD #define IS_UART_ONEBIT_SAMPLE IS_UART_ONE_BIT_SAMPLE #define IS_UART_ONEBIT_SAMPLING IS_UART_ONE_BIT_SAMPLE /** * @} */ /** @defgroup HAL_USART_Aliased_Macros HAL USART Aliased Macros maintained for legacy purpose * @{ */ #define __USART_ENABLE_IT __HAL_USART_ENABLE_IT #define __USART_DISABLE_IT __HAL_USART_DISABLE_IT #define __USART_ENABLE __HAL_USART_ENABLE #define __USART_DISABLE __HAL_USART_DISABLE #define __HAL_USART_GETCLOCKSOURCE USART_GETCLOCKSOURCE #define __USART_GETCLOCKSOURCE USART_GETCLOCKSOURCE /** * @} */ /** @defgroup HAL_USB_Aliased_Macros HAL USB Aliased Macros maintained for legacy purpose * @{ */ #define USB_EXTI_LINE_WAKEUP USB_WAKEUP_EXTI_LINE #define USB_FS_EXTI_TRIGGER_RISING_EDGE USB_OTG_FS_WAKEUP_EXTI_RISING_EDGE #define USB_FS_EXTI_TRIGGER_FALLING_EDGE USB_OTG_FS_WAKEUP_EXTI_FALLING_EDGE #define USB_FS_EXTI_TRIGGER_BOTH_EDGE USB_OTG_FS_WAKEUP_EXTI_RISING_FALLING_EDGE #define USB_FS_EXTI_LINE_WAKEUP USB_OTG_FS_WAKEUP_EXTI_LINE #define USB_HS_EXTI_TRIGGER_RISING_EDGE USB_OTG_HS_WAKEUP_EXTI_RISING_EDGE #define USB_HS_EXTI_TRIGGER_FALLING_EDGE USB_OTG_HS_WAKEUP_EXTI_FALLING_EDGE #define USB_HS_EXTI_TRIGGER_BOTH_EDGE USB_OTG_HS_WAKEUP_EXTI_RISING_FALLING_EDGE #define USB_HS_EXTI_LINE_WAKEUP USB_OTG_HS_WAKEUP_EXTI_LINE #define __HAL_USB_EXTI_ENABLE_IT __HAL_USB_WAKEUP_EXTI_ENABLE_IT #define __HAL_USB_EXTI_DISABLE_IT __HAL_USB_WAKEUP_EXTI_DISABLE_IT #define __HAL_USB_EXTI_GET_FLAG __HAL_USB_WAKEUP_EXTI_GET_FLAG #define __HAL_USB_EXTI_CLEAR_FLAG __HAL_USB_WAKEUP_EXTI_CLEAR_FLAG #define __HAL_USB_EXTI_SET_RISING_EDGE_TRIGGER __HAL_USB_WAKEUP_EXTI_ENABLE_RISING_EDGE #define __HAL_USB_EXTI_SET_FALLING_EDGE_TRIGGER __HAL_USB_WAKEUP_EXTI_ENABLE_FALLING_EDGE #define __HAL_USB_EXTI_SET_FALLINGRISING_TRIGGER __HAL_USB_WAKEUP_EXTI_ENABLE_RISING_FALLING_EDGE #define __HAL_USB_FS_EXTI_ENABLE_IT __HAL_USB_OTG_FS_WAKEUP_EXTI_ENABLE_IT #define __HAL_USB_FS_EXTI_DISABLE_IT __HAL_USB_OTG_FS_WAKEUP_EXTI_DISABLE_IT #define __HAL_USB_FS_EXTI_GET_FLAG __HAL_USB_OTG_FS_WAKEUP_EXTI_GET_FLAG #define __HAL_USB_FS_EXTI_CLEAR_FLAG __HAL_USB_OTG_FS_WAKEUP_EXTI_CLEAR_FLAG #define __HAL_USB_FS_EXTI_SET_RISING_EGDE_TRIGGER __HAL_USB_OTG_FS_WAKEUP_EXTI_ENABLE_RISING_EDGE #define __HAL_USB_FS_EXTI_SET_FALLING_EGDE_TRIGGER __HAL_USB_OTG_FS_WAKEUP_EXTI_ENABLE_FALLING_EDGE #define __HAL_USB_FS_EXTI_SET_FALLINGRISING_TRIGGER __HAL_USB_OTG_FS_WAKEUP_EXTI_ENABLE_RISING_FALLING_EDGE #define __HAL_USB_FS_EXTI_GENERATE_SWIT __HAL_USB_OTG_FS_WAKEUP_EXTI_GENERATE_SWIT #define __HAL_USB_HS_EXTI_ENABLE_IT __HAL_USB_OTG_HS_WAKEUP_EXTI_ENABLE_IT #define __HAL_USB_HS_EXTI_DISABLE_IT __HAL_USB_OTG_HS_WAKEUP_EXTI_DISABLE_IT #define __HAL_USB_HS_EXTI_GET_FLAG __HAL_USB_OTG_HS_WAKEUP_EXTI_GET_FLAG #define __HAL_USB_HS_EXTI_CLEAR_FLAG __HAL_USB_OTG_HS_WAKEUP_EXTI_CLEAR_FLAG #define __HAL_USB_HS_EXTI_SET_RISING_EGDE_TRIGGER __HAL_USB_OTG_HS_WAKEUP_EXTI_ENABLE_RISING_EDGE #define __HAL_USB_HS_EXTI_SET_FALLING_EGDE_TRIGGER __HAL_USB_OTG_HS_WAKEUP_EXTI_ENABLE_FALLING_EDGE #define __HAL_USB_HS_EXTI_SET_FALLINGRISING_TRIGGER __HAL_USB_OTG_HS_WAKEUP_EXTI_ENABLE_RISING_FALLING_EDGE #define __HAL_USB_HS_EXTI_GENERATE_SWIT __HAL_USB_OTG_HS_WAKEUP_EXTI_GENERATE_SWIT #define HAL_PCD_ActiveRemoteWakeup HAL_PCD_ActivateRemoteWakeup #define HAL_PCD_DeActiveRemoteWakeup HAL_PCD_DeActivateRemoteWakeup #define HAL_PCD_SetTxFiFo HAL_PCDEx_SetTxFiFo #define HAL_PCD_SetRxFiFo HAL_PCDEx_SetRxFiFo /** * @} */ /** @defgroup HAL_TIM_Aliased_Macros HAL TIM Aliased Macros maintained for legacy purpose * @{ */ #define __HAL_TIM_SetICPrescalerValue TIM_SET_ICPRESCALERVALUE #define __HAL_TIM_ResetICPrescalerValue TIM_RESET_ICPRESCALERVALUE #define TIM_GET_ITSTATUS __HAL_TIM_GET_IT_SOURCE #define TIM_GET_CLEAR_IT __HAL_TIM_CLEAR_IT #define __HAL_TIM_GET_ITSTATUS __HAL_TIM_GET_IT_SOURCE #define __HAL_TIM_DIRECTION_STATUS __HAL_TIM_IS_TIM_COUNTING_DOWN #define __HAL_TIM_PRESCALER __HAL_TIM_SET_PRESCALER #define __HAL_TIM_SetCounter __HAL_TIM_SET_COUNTER #define __HAL_TIM_GetCounter __HAL_TIM_GET_COUNTER #define __HAL_TIM_SetAutoreload __HAL_TIM_SET_AUTORELOAD #define __HAL_TIM_GetAutoreload __HAL_TIM_GET_AUTORELOAD #define __HAL_TIM_SetClockDivision __HAL_TIM_SET_CLOCKDIVISION #define __HAL_TIM_GetClockDivision __HAL_TIM_GET_CLOCKDIVISION #define __HAL_TIM_SetICPrescaler __HAL_TIM_SET_ICPRESCALER #define __HAL_TIM_GetICPrescaler __HAL_TIM_GET_ICPRESCALER #define __HAL_TIM_SetCompare __HAL_TIM_SET_COMPARE #define __HAL_TIM_GetCompare __HAL_TIM_GET_COMPARE #define TIM_TS_ITR0 ((uint32_t)0x0000) #define TIM_TS_ITR1 ((uint32_t)0x0010) #define TIM_TS_ITR2 ((uint32_t)0x0020) #define TIM_TS_ITR3 ((uint32_t)0x0030) #define IS_TIM_INTERNAL_TRIGGER_SELECTION(SELECTION) (((SELECTION) == TIM_TS_ITR0) || \ ((SELECTION) == TIM_TS_ITR1) || \ ((SELECTION) == TIM_TS_ITR2) || \ ((SELECTION) == TIM_TS_ITR3)) #define TIM_CHANNEL_1 ((uint32_t)0x0000) #define TIM_CHANNEL_2 ((uint32_t)0x0004) #define IS_TIM_PWMI_CHANNELS(CHANNEL) (((CHANNEL) == TIM_CHANNEL_1) || \ ((CHANNEL) == TIM_CHANNEL_2)) #define TIM_OUTPUTNSTATE_DISABLE ((uint32_t)0x0000) #define TIM_OUTPUTNSTATE_ENABLE (TIM_CCER_CC1NE) #define IS_TIM_OUTPUTN_STATE(STATE) (((STATE) == TIM_OUTPUTNSTATE_DISABLE) || \ ((STATE) == TIM_OUTPUTNSTATE_ENABLE)) #define TIM_OUTPUTSTATE_DISABLE ((uint32_t)0x0000) #define TIM_OUTPUTSTATE_ENABLE (TIM_CCER_CC1E) #define IS_TIM_OUTPUT_STATE(STATE) (((STATE) == TIM_OUTPUTSTATE_DISABLE) || \ ((STATE) == TIM_OUTPUTSTATE_ENABLE)) /** * @} */ /** @defgroup HAL_ETH_Aliased_Macros HAL ETH Aliased Macros maintained for legacy purpose * @{ */ #define __HAL_ETH_EXTI_ENABLE_IT __HAL_ETH_WAKEUP_EXTI_ENABLE_IT #define __HAL_ETH_EXTI_DISABLE_IT __HAL_ETH_WAKEUP_EXTI_DISABLE_IT #define __HAL_ETH_EXTI_GET_FLAG __HAL_ETH_WAKEUP_EXTI_GET_FLAG #define __HAL_ETH_EXTI_CLEAR_FLAG __HAL_ETH_WAKEUP_EXTI_CLEAR_FLAG #define __HAL_ETH_EXTI_SET_RISING_EGDE_TRIGGER __HAL_ETH_WAKEUP_EXTI_ENABLE_RISING_EDGE_TRIGGER #define __HAL_ETH_EXTI_SET_FALLING_EGDE_TRIGGER __HAL_ETH_WAKEUP_EXTI_ENABLE_FALLING_EDGE_TRIGGER #define __HAL_ETH_EXTI_SET_FALLINGRISING_TRIGGER __HAL_ETH_WAKEUP_EXTI_ENABLE_FALLINGRISING_TRIGGER #define ETH_PROMISCIOUSMODE_ENABLE ETH_PROMISCUOUS_MODE_ENABLE #define ETH_PROMISCIOUSMODE_DISABLE ETH_PROMISCUOUS_MODE_DISABLE #define IS_ETH_PROMISCIOUS_MODE IS_ETH_PROMISCUOUS_MODE /** * @} */ /** @defgroup HAL_LTDC_Aliased_Macros HAL LTDC Aliased Macros maintained for legacy purpose * @{ */ #define __HAL_LTDC_LAYER LTDC_LAYER /** * @} */ /** @defgroup HAL_SAI_Aliased_Macros HAL SAI Aliased Macros maintained for legacy purpose * @{ */ #define SAI_OUTPUTDRIVE_DISABLED SAI_OUTPUTDRIVE_DISABLE #define SAI_OUTPUTDRIVE_ENABLED SAI_OUTPUTDRIVE_ENABLE #define SAI_MASTERDIVIDER_ENABLED SAI_MASTERDIVIDER_ENABLE #define SAI_MASTERDIVIDER_DISABLED SAI_MASTERDIVIDER_DISABLE #define SAI_STREOMODE SAI_STEREOMODE #define SAI_FIFOStatus_Empty SAI_FIFOSTATUS_EMPTY #define SAI_FIFOStatus_Less1QuarterFull SAI_FIFOSTATUS_LESS1QUARTERFULL #define SAI_FIFOStatus_1QuarterFull SAI_FIFOSTATUS_1QUARTERFULL #define SAI_FIFOStatus_HalfFull SAI_FIFOSTATUS_HALFFULL #define SAI_FIFOStatus_3QuartersFull SAI_FIFOSTATUS_3QUARTERFULL #define SAI_FIFOStatus_Full SAI_FIFOSTATUS_FULL #define IS_SAI_BLOCK_MONO_STREO_MODE IS_SAI_BLOCK_MONO_STEREO_MODE /** * @} */ /** @defgroup HAL_PPP_Aliased_Macros HAL PPP Aliased Macros maintained for legacy purpose * @{ */ /** * @} */ #ifdef __cplusplus } #endif #endif /* ___STM32_HAL_LEGACY */ /************************ (C) COPYRIGHT STMicroelectronics *****END OF FILE****/ ================================================ FILE: Zelig/mbed/TARGET_NUCLEO_F411RE/stm32f411xe.h ================================================ /** ****************************************************************************** * @file stm32f411xe.h * @author MCD Application Team * @version V2.3.2 * @date 26-June-2015 * @brief CMSIS STM32F411xExx Device Peripheral Access Layer Header File. * * This file contains: * - Data structures and the address mapping for all peripherals * - Peripheral's registers declarations and bits definition * - Macros to access peripherals registers hardware * ****************************************************************************** * @attention * *

© COPYRIGHT(c) 2015 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. * ****************************************************************************** */ /** @addtogroup CMSIS * @{ */ /** @addtogroup stm32f401xe * @{ */ #ifndef __STM32F401xE_H #define __STM32F401xE_H #ifdef __cplusplus extern "C" { #endif /* __cplusplus */ /** @addtogroup Configuration_section_for_CMSIS * @{ */ /** * @brief Configuration of the Cortex-M4 Processor and Core Peripherals */ #define __CM4_REV 0x0001 /*!< Core revision r0p1 */ #define __MPU_PRESENT 1 /*!< STM32F4XX provides an MPU */ #define __NVIC_PRIO_BITS 4 /*!< STM32F4XX uses 4 Bits for the Priority Levels */ #define __Vendor_SysTickConfig 0 /*!< Set to 1 if different SysTick Config is used */ #define __FPU_PRESENT 1 /*!< FPU present */ /** * @} */ /** @addtogroup Peripheral_interrupt_number_definition * @{ */ /** * @brief STM32F4XX Interrupt Number Definition, according to the selected device * in @ref Library_configuration_section */ typedef enum { /****** Cortex-M4 Processor Exceptions Numbers ****************************************************************/ NonMaskableInt_IRQn = -14, /*!< 2 Non Maskable Interrupt */ MemoryManagement_IRQn = -12, /*!< 4 Cortex-M4 Memory Management Interrupt */ BusFault_IRQn = -11, /*!< 5 Cortex-M4 Bus Fault Interrupt */ UsageFault_IRQn = -10, /*!< 6 Cortex-M4 Usage Fault Interrupt */ SVCall_IRQn = -5, /*!< 11 Cortex-M4 SV Call Interrupt */ DebugMonitor_IRQn = -4, /*!< 12 Cortex-M4 Debug Monitor Interrupt */ PendSV_IRQn = -2, /*!< 14 Cortex-M4 Pend SV Interrupt */ SysTick_IRQn = -1, /*!< 15 Cortex-M4 System Tick Interrupt */ /****** STM32 specific Interrupt Numbers **********************************************************************/ WWDG_IRQn = 0, /*!< Window WatchDog Interrupt */ PVD_IRQn = 1, /*!< PVD through EXTI Line detection Interrupt */ TAMP_STAMP_IRQn = 2, /*!< Tamper and TimeStamp interrupts through the EXTI line */ RTC_WKUP_IRQn = 3, /*!< RTC Wakeup interrupt through the EXTI line */ FLASH_IRQn = 4, /*!< FLASH global Interrupt */ RCC_IRQn = 5, /*!< RCC global Interrupt */ EXTI0_IRQn = 6, /*!< EXTI Line0 Interrupt */ EXTI1_IRQn = 7, /*!< EXTI Line1 Interrupt */ EXTI2_IRQn = 8, /*!< EXTI Line2 Interrupt */ EXTI3_IRQn = 9, /*!< EXTI Line3 Interrupt */ EXTI4_IRQn = 10, /*!< EXTI Line4 Interrupt */ DMA1_Stream0_IRQn = 11, /*!< DMA1 Stream 0 global Interrupt */ DMA1_Stream1_IRQn = 12, /*!< DMA1 Stream 1 global Interrupt */ DMA1_Stream2_IRQn = 13, /*!< DMA1 Stream 2 global Interrupt */ DMA1_Stream3_IRQn = 14, /*!< DMA1 Stream 3 global Interrupt */ DMA1_Stream4_IRQn = 15, /*!< DMA1 Stream 4 global Interrupt */ DMA1_Stream5_IRQn = 16, /*!< DMA1 Stream 5 global Interrupt */ DMA1_Stream6_IRQn = 17, /*!< DMA1 Stream 6 global Interrupt */ ADC_IRQn = 18, /*!< ADC1, ADC2 and ADC3 global Interrupts */ EXTI9_5_IRQn = 23, /*!< External Line[9:5] Interrupts */ TIM1_BRK_TIM9_IRQn = 24, /*!< TIM1 Break interrupt and TIM9 global interrupt */ TIM1_UP_TIM10_IRQn = 25, /*!< TIM1 Update Interrupt and TIM10 global interrupt */ TIM1_TRG_COM_TIM11_IRQn = 26, /*!< TIM1 Trigger and Commutation Interrupt and TIM11 global interrupt */ TIM1_CC_IRQn = 27, /*!< TIM1 Capture Compare Interrupt */ TIM2_IRQn = 28, /*!< TIM2 global Interrupt */ TIM3_IRQn = 29, /*!< TIM3 global Interrupt */ TIM4_IRQn = 30, /*!< TIM4 global Interrupt */ I2C1_EV_IRQn = 31, /*!< I2C1 Event Interrupt */ I2C1_ER_IRQn = 32, /*!< I2C1 Error Interrupt */ I2C2_EV_IRQn = 33, /*!< I2C2 Event Interrupt */ I2C2_ER_IRQn = 34, /*!< I2C2 Error Interrupt */ SPI1_IRQn = 35, /*!< SPI1 global Interrupt */ SPI2_IRQn = 36, /*!< SPI2 global Interrupt */ USART1_IRQn = 37, /*!< USART1 global Interrupt */ USART2_IRQn = 38, /*!< USART2 global Interrupt */ EXTI15_10_IRQn = 40, /*!< External Line[15:10] Interrupts */ RTC_Alarm_IRQn = 41, /*!< RTC Alarm (A and B) through EXTI Line Interrupt */ OTG_FS_WKUP_IRQn = 42, /*!< USB OTG FS Wakeup through EXTI line interrupt */ DMA1_Stream7_IRQn = 47, /*!< DMA1 Stream7 Interrupt */ SDIO_IRQn = 49, /*!< SDIO global Interrupt */ TIM5_IRQn = 50, /*!< TIM5 global Interrupt */ SPI3_IRQn = 51, /*!< SPI3 global Interrupt */ DMA2_Stream0_IRQn = 56, /*!< DMA2 Stream 0 global Interrupt */ DMA2_Stream1_IRQn = 57, /*!< DMA2 Stream 1 global Interrupt */ DMA2_Stream2_IRQn = 58, /*!< DMA2 Stream 2 global Interrupt */ DMA2_Stream3_IRQn = 59, /*!< DMA2 Stream 3 global Interrupt */ DMA2_Stream4_IRQn = 60, /*!< DMA2 Stream 4 global Interrupt */ OTG_FS_IRQn = 67, /*!< USB OTG FS global Interrupt */ DMA2_Stream5_IRQn = 68, /*!< DMA2 Stream 5 global interrupt */ DMA2_Stream6_IRQn = 69, /*!< DMA2 Stream 6 global interrupt */ DMA2_Stream7_IRQn = 70, /*!< DMA2 Stream 7 global interrupt */ USART6_IRQn = 71, /*!< USART6 global interrupt */ I2C3_EV_IRQn = 72, /*!< I2C3 event interrupt */ I2C3_ER_IRQn = 73, /*!< I2C3 error interrupt */ FPU_IRQn = 81, /*!< FPU global interrupt */ SPI4_IRQn = 84, /*!< SPI4 global Interrupt */ SPI5_IRQn = 85 /*!< SPI5 global Interrupt */ } IRQn_Type; /** * @} */ #include "core_cm4.h" /* Cortex-M4 processor and core peripherals */ #include "system_stm32f4xx.h" #include /** @addtogroup Peripheral_registers_structures * @{ */ /** * @brief Analog to Digital Converter */ typedef struct { __IO uint32_t SR; /*!< ADC status register, Address offset: 0x00 */ __IO uint32_t CR1; /*!< ADC control register 1, Address offset: 0x04 */ __IO uint32_t CR2; /*!< ADC control register 2, Address offset: 0x08 */ __IO uint32_t SMPR1; /*!< ADC sample time register 1, Address offset: 0x0C */ __IO uint32_t SMPR2; /*!< ADC sample time register 2, Address offset: 0x10 */ __IO uint32_t JOFR1; /*!< ADC injected channel data offset register 1, Address offset: 0x14 */ __IO uint32_t JOFR2; /*!< ADC injected channel data offset register 2, Address offset: 0x18 */ __IO uint32_t JOFR3; /*!< ADC injected channel data offset register 3, Address offset: 0x1C */ __IO uint32_t JOFR4; /*!< ADC injected channel data offset register 4, Address offset: 0x20 */ __IO uint32_t HTR; /*!< ADC watchdog higher threshold register, Address offset: 0x24 */ __IO uint32_t LTR; /*!< ADC watchdog lower threshold register, Address offset: 0x28 */ __IO uint32_t SQR1; /*!< ADC regular sequence register 1, Address offset: 0x2C */ __IO uint32_t SQR2; /*!< ADC regular sequence register 2, Address offset: 0x30 */ __IO uint32_t SQR3; /*!< ADC regular sequence register 3, Address offset: 0x34 */ __IO uint32_t JSQR; /*!< ADC injected sequence register, Address offset: 0x38*/ __IO uint32_t JDR1; /*!< ADC injected data register 1, Address offset: 0x3C */ __IO uint32_t JDR2; /*!< ADC injected data register 2, Address offset: 0x40 */ __IO uint32_t JDR3; /*!< ADC injected data register 3, Address offset: 0x44 */ __IO uint32_t JDR4; /*!< ADC injected data register 4, Address offset: 0x48 */ __IO uint32_t DR; /*!< ADC regular data register, Address offset: 0x4C */ } ADC_TypeDef; typedef struct { __IO uint32_t CSR; /*!< ADC Common status register, Address offset: ADC1 base address + 0x300 */ __IO uint32_t CCR; /*!< ADC common control register, Address offset: ADC1 base address + 0x304 */ __IO uint32_t CDR; /*!< ADC common regular data register for dual AND triple modes, Address offset: ADC1 base address + 0x308 */ } ADC_Common_TypeDef; /** * @brief CRC calculation unit */ typedef struct { __IO uint32_t DR; /*!< CRC Data register, Address offset: 0x00 */ __IO uint8_t IDR; /*!< CRC Independent data register, Address offset: 0x04 */ uint8_t RESERVED0; /*!< Reserved, 0x05 */ uint16_t RESERVED1; /*!< Reserved, 0x06 */ __IO uint32_t CR; /*!< CRC Control register, Address offset: 0x08 */ } CRC_TypeDef; /** * @brief Debug MCU */ typedef struct { __IO uint32_t IDCODE; /*!< MCU device ID code, Address offset: 0x00 */ __IO uint32_t CR; /*!< Debug MCU configuration register, Address offset: 0x04 */ __IO uint32_t APB1FZ; /*!< Debug MCU APB1 freeze register, Address offset: 0x08 */ __IO uint32_t APB2FZ; /*!< Debug MCU APB2 freeze register, Address offset: 0x0C */ }DBGMCU_TypeDef; /** * @brief DMA Controller */ typedef struct { __IO uint32_t CR; /*!< DMA stream x configuration register */ __IO uint32_t NDTR; /*!< DMA stream x number of data register */ __IO uint32_t PAR; /*!< DMA stream x peripheral address register */ __IO uint32_t M0AR; /*!< DMA stream x memory 0 address register */ __IO uint32_t M1AR; /*!< DMA stream x memory 1 address register */ __IO uint32_t FCR; /*!< DMA stream x FIFO control register */ } DMA_Stream_TypeDef; typedef struct { __IO uint32_t LISR; /*!< DMA low interrupt status register, Address offset: 0x00 */ __IO uint32_t HISR; /*!< DMA high interrupt status register, Address offset: 0x04 */ __IO uint32_t LIFCR; /*!< DMA low interrupt flag clear register, Address offset: 0x08 */ __IO uint32_t HIFCR; /*!< DMA high interrupt flag clear register, Address offset: 0x0C */ } DMA_TypeDef; /** * @brief External Interrupt/Event Controller */ typedef struct { __IO uint32_t IMR; /*!< EXTI Interrupt mask register, Address offset: 0x00 */ __IO uint32_t EMR; /*!< EXTI Event mask register, Address offset: 0x04 */ __IO uint32_t RTSR; /*!< EXTI Rising trigger selection register, Address offset: 0x08 */ __IO uint32_t FTSR; /*!< EXTI Falling trigger selection register, Address offset: 0x0C */ __IO uint32_t SWIER; /*!< EXTI Software interrupt event register, Address offset: 0x10 */ __IO uint32_t PR; /*!< EXTI Pending register, Address offset: 0x14 */ } EXTI_TypeDef; /** * @brief FLASH Registers */ typedef struct { __IO uint32_t ACR; /*!< FLASH access control register, Address offset: 0x00 */ __IO uint32_t KEYR; /*!< FLASH key register, Address offset: 0x04 */ __IO uint32_t OPTKEYR; /*!< FLASH option key register, Address offset: 0x08 */ __IO uint32_t SR; /*!< FLASH status register, Address offset: 0x0C */ __IO uint32_t CR; /*!< FLASH control register, Address offset: 0x10 */ __IO uint32_t OPTCR; /*!< FLASH option control register , Address offset: 0x14 */ __IO uint32_t OPTCR1; /*!< FLASH option control register 1, Address offset: 0x18 */ } FLASH_TypeDef; /** * @brief General Purpose I/O */ typedef struct { __IO uint32_t MODER; /*!< GPIO port mode register, Address offset: 0x00 */ __IO uint32_t OTYPER; /*!< GPIO port output type register, Address offset: 0x04 */ __IO uint32_t OSPEEDR; /*!< GPIO port output speed register, Address offset: 0x08 */ __IO uint32_t PUPDR; /*!< GPIO port pull-up/pull-down register, Address offset: 0x0C */ __IO uint32_t IDR; /*!< GPIO port input data register, Address offset: 0x10 */ __IO uint32_t ODR; /*!< GPIO port output data register, Address offset: 0x14 */ __IO uint32_t BSRR; /*!< GPIO port bit set/reset register, Address offset: 0x18 */ __IO uint32_t LCKR; /*!< GPIO port configuration lock register, Address offset: 0x1C */ __IO uint32_t AFR[2]; /*!< GPIO alternate function registers, Address offset: 0x20-0x24 */ } GPIO_TypeDef; /** * @brief System configuration controller */ typedef struct { __IO uint32_t MEMRMP; /*!< SYSCFG memory remap register, Address offset: 0x00 */ __IO uint32_t PMC; /*!< SYSCFG peripheral mode configuration register, Address offset: 0x04 */ __IO uint32_t EXTICR[4]; /*!< SYSCFG external interrupt configuration registers, Address offset: 0x08-0x14 */ uint32_t RESERVED[2]; /*!< Reserved, 0x18-0x1C */ __IO uint32_t CMPCR; /*!< SYSCFG Compensation cell control register, Address offset: 0x20 */ } SYSCFG_TypeDef; /** * @brief Inter-integrated Circuit Interface */ typedef struct { __IO uint32_t CR1; /*!< I2C Control register 1, Address offset: 0x00 */ __IO uint32_t CR2; /*!< I2C Control register 2, Address offset: 0x04 */ __IO uint32_t OAR1; /*!< I2C Own address register 1, Address offset: 0x08 */ __IO uint32_t OAR2; /*!< I2C Own address register 2, Address offset: 0x0C */ __IO uint32_t DR; /*!< I2C Data register, Address offset: 0x10 */ __IO uint32_t SR1; /*!< I2C Status register 1, Address offset: 0x14 */ __IO uint32_t SR2; /*!< I2C Status register 2, Address offset: 0x18 */ __IO uint32_t CCR; /*!< I2C Clock control register, Address offset: 0x1C */ __IO uint32_t TRISE; /*!< I2C TRISE register, Address offset: 0x20 */ __IO uint32_t FLTR; /*!< I2C FLTR register, Address offset: 0x24 */ } I2C_TypeDef; /** * @brief Independent WATCHDOG */ typedef struct { __IO uint32_t KR; /*!< IWDG Key register, Address offset: 0x00 */ __IO uint32_t PR; /*!< IWDG Prescaler register, Address offset: 0x04 */ __IO uint32_t RLR; /*!< IWDG Reload register, Address offset: 0x08 */ __IO uint32_t SR; /*!< IWDG Status register, Address offset: 0x0C */ } IWDG_TypeDef; /** * @brief Power Control */ typedef struct { __IO uint32_t CR; /*!< PWR power control register, Address offset: 0x00 */ __IO uint32_t CSR; /*!< PWR power control/status register, Address offset: 0x04 */ } PWR_TypeDef; /** * @brief Reset and Clock Control */ typedef struct { __IO uint32_t CR; /*!< RCC clock control register, Address offset: 0x00 */ __IO uint32_t PLLCFGR; /*!< RCC PLL configuration register, Address offset: 0x04 */ __IO uint32_t CFGR; /*!< RCC clock configuration register, Address offset: 0x08 */ __IO uint32_t CIR; /*!< RCC clock interrupt register, Address offset: 0x0C */ __IO uint32_t AHB1RSTR; /*!< RCC AHB1 peripheral reset register, Address offset: 0x10 */ __IO uint32_t AHB2RSTR; /*!< RCC AHB2 peripheral reset register, Address offset: 0x14 */ __IO uint32_t AHB3RSTR; /*!< RCC AHB3 peripheral reset register, Address offset: 0x18 */ uint32_t RESERVED0; /*!< Reserved, 0x1C */ __IO uint32_t APB1RSTR; /*!< RCC APB1 peripheral reset register, Address offset: 0x20 */ __IO uint32_t APB2RSTR; /*!< RCC APB2 peripheral reset register, Address offset: 0x24 */ uint32_t RESERVED1[2]; /*!< Reserved, 0x28-0x2C */ __IO uint32_t AHB1ENR; /*!< RCC AHB1 peripheral clock register, Address offset: 0x30 */ __IO uint32_t AHB2ENR; /*!< RCC AHB2 peripheral clock register, Address offset: 0x34 */ __IO uint32_t AHB3ENR; /*!< RCC AHB3 peripheral clock register, Address offset: 0x38 */ uint32_t RESERVED2; /*!< Reserved, 0x3C */ __IO uint32_t APB1ENR; /*!< RCC APB1 peripheral clock enable register, Address offset: 0x40 */ __IO uint32_t APB2ENR; /*!< RCC APB2 peripheral clock enable register, Address offset: 0x44 */ uint32_t RESERVED3[2]; /*!< Reserved, 0x48-0x4C */ __IO uint32_t AHB1LPENR; /*!< RCC AHB1 peripheral clock enable in low power mode register, Address offset: 0x50 */ __IO uint32_t AHB2LPENR; /*!< RCC AHB2 peripheral clock enable in low power mode register, Address offset: 0x54 */ __IO uint32_t AHB3LPENR; /*!< RCC AHB3 peripheral clock enable in low power mode register, Address offset: 0x58 */ uint32_t RESERVED4; /*!< Reserved, 0x5C */ __IO uint32_t APB1LPENR; /*!< RCC APB1 peripheral clock enable in low power mode register, Address offset: 0x60 */ __IO uint32_t APB2LPENR; /*!< RCC APB2 peripheral clock enable in low power mode register, Address offset: 0x64 */ uint32_t RESERVED5[2]; /*!< Reserved, 0x68-0x6C */ __IO uint32_t BDCR; /*!< RCC Backup domain control register, Address offset: 0x70 */ __IO uint32_t CSR; /*!< RCC clock control & status register, Address offset: 0x74 */ uint32_t RESERVED6[2]; /*!< Reserved, 0x78-0x7C */ __IO uint32_t SSCGR; /*!< RCC spread spectrum clock generation register, Address offset: 0x80 */ __IO uint32_t PLLI2SCFGR; /*!< RCC PLLI2S configuration register, Address offset: 0x84 */ } RCC_TypeDef; /** * @brief Real-Time Clock */ typedef struct { __IO uint32_t TR; /*!< RTC time register, Address offset: 0x00 */ __IO uint32_t DR; /*!< RTC date register, Address offset: 0x04 */ __IO uint32_t CR; /*!< RTC control register, Address offset: 0x08 */ __IO uint32_t ISR; /*!< RTC initialization and status register, Address offset: 0x0C */ __IO uint32_t PRER; /*!< RTC prescaler register, Address offset: 0x10 */ __IO uint32_t WUTR; /*!< RTC wakeup timer register, Address offset: 0x14 */ __IO uint32_t CALIBR; /*!< RTC calibration register, Address offset: 0x18 */ __IO uint32_t ALRMAR; /*!< RTC alarm A register, Address offset: 0x1C */ __IO uint32_t ALRMBR; /*!< RTC alarm B register, Address offset: 0x20 */ __IO uint32_t WPR; /*!< RTC write protection register, Address offset: 0x24 */ __IO uint32_t SSR; /*!< RTC sub second register, Address offset: 0x28 */ __IO uint32_t SHIFTR; /*!< RTC shift control register, Address offset: 0x2C */ __IO uint32_t TSTR; /*!< RTC time stamp time register, Address offset: 0x30 */ __IO uint32_t TSDR; /*!< RTC time stamp date register, Address offset: 0x34 */ __IO uint32_t TSSSR; /*!< RTC time-stamp sub second register, Address offset: 0x38 */ __IO uint32_t CALR; /*!< RTC calibration register, Address offset: 0x3C */ __IO uint32_t TAFCR; /*!< RTC tamper and alternate function configuration register, Address offset: 0x40 */ __IO uint32_t ALRMASSR;/*!< RTC alarm A sub second register, Address offset: 0x44 */ __IO uint32_t ALRMBSSR;/*!< RTC alarm B sub second register, Address offset: 0x48 */ uint32_t RESERVED7; /*!< Reserved, 0x4C */ __IO uint32_t BKP0R; /*!< RTC backup register 1, Address offset: 0x50 */ __IO uint32_t BKP1R; /*!< RTC backup register 1, Address offset: 0x54 */ __IO uint32_t BKP2R; /*!< RTC backup register 2, Address offset: 0x58 */ __IO uint32_t BKP3R; /*!< RTC backup register 3, Address offset: 0x5C */ __IO uint32_t BKP4R; /*!< RTC backup register 4, Address offset: 0x60 */ __IO uint32_t BKP5R; /*!< RTC backup register 5, Address offset: 0x64 */ __IO uint32_t BKP6R; /*!< RTC backup register 6, Address offset: 0x68 */ __IO uint32_t BKP7R; /*!< RTC backup register 7, Address offset: 0x6C */ __IO uint32_t BKP8R; /*!< RTC backup register 8, Address offset: 0x70 */ __IO uint32_t BKP9R; /*!< RTC backup register 9, Address offset: 0x74 */ __IO uint32_t BKP10R; /*!< RTC backup register 10, Address offset: 0x78 */ __IO uint32_t BKP11R; /*!< RTC backup register 11, Address offset: 0x7C */ __IO uint32_t BKP12R; /*!< RTC backup register 12, Address offset: 0x80 */ __IO uint32_t BKP13R; /*!< RTC backup register 13, Address offset: 0x84 */ __IO uint32_t BKP14R; /*!< RTC backup register 14, Address offset: 0x88 */ __IO uint32_t BKP15R; /*!< RTC backup register 15, Address offset: 0x8C */ __IO uint32_t BKP16R; /*!< RTC backup register 16, Address offset: 0x90 */ __IO uint32_t BKP17R; /*!< RTC backup register 17, Address offset: 0x94 */ __IO uint32_t BKP18R; /*!< RTC backup register 18, Address offset: 0x98 */ __IO uint32_t BKP19R; /*!< RTC backup register 19, Address offset: 0x9C */ } RTC_TypeDef; /** * @brief SD host Interface */ typedef struct { __IO uint32_t POWER; /*!< SDIO power control register, Address offset: 0x00 */ __IO uint32_t CLKCR; /*!< SDI clock control register, Address offset: 0x04 */ __IO uint32_t ARG; /*!< SDIO argument register, Address offset: 0x08 */ __IO uint32_t CMD; /*!< SDIO command register, Address offset: 0x0C */ __I uint32_t RESPCMD; /*!< SDIO command response register, Address offset: 0x10 */ __I uint32_t RESP1; /*!< SDIO response 1 register, Address offset: 0x14 */ __I uint32_t RESP2; /*!< SDIO response 2 register, Address offset: 0x18 */ __I uint32_t RESP3; /*!< SDIO response 3 register, Address offset: 0x1C */ __I uint32_t RESP4; /*!< SDIO response 4 register, Address offset: 0x20 */ __IO uint32_t DTIMER; /*!< SDIO data timer register, Address offset: 0x24 */ __IO uint32_t DLEN; /*!< SDIO data length register, Address offset: 0x28 */ __IO uint32_t DCTRL; /*!< SDIO data control register, Address offset: 0x2C */ __I uint32_t DCOUNT; /*!< SDIO data counter register, Address offset: 0x30 */ __I uint32_t STA; /*!< SDIO status register, Address offset: 0x34 */ __IO uint32_t ICR; /*!< SDIO interrupt clear register, Address offset: 0x38 */ __IO uint32_t MASK; /*!< SDIO mask register, Address offset: 0x3C */ uint32_t RESERVED0[2]; /*!< Reserved, 0x40-0x44 */ __I uint32_t FIFOCNT; /*!< SDIO FIFO counter register, Address offset: 0x48 */ uint32_t RESERVED1[13]; /*!< Reserved, 0x4C-0x7C */ __IO uint32_t FIFO; /*!< SDIO data FIFO register, Address offset: 0x80 */ } SDIO_TypeDef; /** * @brief Serial Peripheral Interface */ typedef struct { __IO uint32_t CR1; /*!< SPI control register 1 (not used in I2S mode), Address offset: 0x00 */ __IO uint32_t CR2; /*!< SPI control register 2, Address offset: 0x04 */ __IO uint32_t SR; /*!< SPI status register, Address offset: 0x08 */ __IO uint32_t DR; /*!< SPI data register, Address offset: 0x0C */ __IO uint32_t CRCPR; /*!< SPI CRC polynomial register (not used in I2S mode), Address offset: 0x10 */ __IO uint32_t RXCRCR; /*!< SPI RX CRC register (not used in I2S mode), Address offset: 0x14 */ __IO uint32_t TXCRCR; /*!< SPI TX CRC register (not used in I2S mode), Address offset: 0x18 */ __IO uint32_t I2SCFGR; /*!< SPI_I2S configuration register, Address offset: 0x1C */ __IO uint32_t I2SPR; /*!< SPI_I2S prescaler register, Address offset: 0x20 */ } SPI_TypeDef; /** * @brief TIM */ typedef struct { __IO uint32_t CR1; /*!< TIM control register 1, Address offset: 0x00 */ __IO uint32_t CR2; /*!< TIM control register 2, Address offset: 0x04 */ __IO uint32_t SMCR; /*!< TIM slave mode control register, Address offset: 0x08 */ __IO uint32_t DIER; /*!< TIM DMA/interrupt enable register, Address offset: 0x0C */ __IO uint32_t SR; /*!< TIM status register, Address offset: 0x10 */ __IO uint32_t EGR; /*!< TIM event generation register, Address offset: 0x14 */ __IO uint32_t CCMR1; /*!< TIM capture/compare mode register 1, Address offset: 0x18 */ __IO uint32_t CCMR2; /*!< TIM capture/compare mode register 2, Address offset: 0x1C */ __IO uint32_t CCER; /*!< TIM capture/compare enable register, Address offset: 0x20 */ __IO uint32_t CNT; /*!< TIM counter register, Address offset: 0x24 */ __IO uint32_t PSC; /*!< TIM prescaler, Address offset: 0x28 */ __IO uint32_t ARR; /*!< TIM auto-reload register, Address offset: 0x2C */ __IO uint32_t RCR; /*!< TIM repetition counter register, Address offset: 0x30 */ __IO uint32_t CCR1; /*!< TIM capture/compare register 1, Address offset: 0x34 */ __IO uint32_t CCR2; /*!< TIM capture/compare register 2, Address offset: 0x38 */ __IO uint32_t CCR3; /*!< TIM capture/compare register 3, Address offset: 0x3C */ __IO uint32_t CCR4; /*!< TIM capture/compare register 4, Address offset: 0x40 */ __IO uint32_t BDTR; /*!< TIM break and dead-time register, Address offset: 0x44 */ __IO uint32_t DCR; /*!< TIM DMA control register, Address offset: 0x48 */ __IO uint32_t DMAR; /*!< TIM DMA address for full transfer, Address offset: 0x4C */ __IO uint32_t OR; /*!< TIM option register, Address offset: 0x50 */ } TIM_TypeDef; /** * @brief Universal Synchronous Asynchronous Receiver Transmitter */ typedef struct { __IO uint32_t SR; /*!< USART Status register, Address offset: 0x00 */ __IO uint32_t DR; /*!< USART Data register, Address offset: 0x04 */ __IO uint32_t BRR; /*!< USART Baud rate register, Address offset: 0x08 */ __IO uint32_t CR1; /*!< USART Control register 1, Address offset: 0x0C */ __IO uint32_t CR2; /*!< USART Control register 2, Address offset: 0x10 */ __IO uint32_t CR3; /*!< USART Control register 3, Address offset: 0x14 */ __IO uint32_t GTPR; /*!< USART Guard time and prescaler register, Address offset: 0x18 */ } USART_TypeDef; /** * @brief Window WATCHDOG */ typedef struct { __IO uint32_t CR; /*!< WWDG Control register, Address offset: 0x00 */ __IO uint32_t CFR; /*!< WWDG Configuration register, Address offset: 0x04 */ __IO uint32_t SR; /*!< WWDG Status register, Address offset: 0x08 */ } WWDG_TypeDef; /** * @brief __USB_OTG_Core_register */ typedef struct { __IO uint32_t GOTGCTL; /*!< USB_OTG Control and Status Register Address offset : 0x00 */ __IO uint32_t GOTGINT; /*!< USB_OTG Interrupt Register Address offset : 0x04 */ __IO uint32_t GAHBCFG; /*!< Core AHB Configuration Register Address offset : 0x08 */ __IO uint32_t GUSBCFG; /*!< Core USB Configuration Register Address offset : 0x0C */ __IO uint32_t GRSTCTL; /*!< Core Reset Register Address offset : 0x10 */ __IO uint32_t GINTSTS; /*!< Core Interrupt Register Address offset : 0x14 */ __IO uint32_t GINTMSK; /*!< Core Interrupt Mask Register Address offset : 0x18 */ __IO uint32_t GRXSTSR; /*!< Receive Sts Q Read Register Address offset : 0x1C */ __IO uint32_t GRXSTSP; /*!< Receive Sts Q Read & POP Register Address offset : 0x20 */ __IO uint32_t GRXFSIZ; /* Receive FIFO Size Register Address offset : 0x24 */ __IO uint32_t DIEPTXF0_HNPTXFSIZ; /*!< EP0 / Non Periodic Tx FIFO Size Register Address offset : 0x28 */ __IO uint32_t HNPTXSTS; /*!< Non Periodic Tx FIFO/Queue Sts reg Address offset : 0x2C */ uint32_t Reserved30[2]; /* Reserved Address offset : 0x30 */ __IO uint32_t GCCFG; /*!< General Purpose IO Register Address offset : 0x38 */ __IO uint32_t CID; /*!< User ID Register Address offset : 0x3C */ uint32_t Reserved40[48]; /*!< Reserved Address offset : 0x40-0xFF */ __IO uint32_t HPTXFSIZ; /*!< Host Periodic Tx FIFO Size Reg Address offset : 0x100 */ __IO uint32_t DIEPTXF[0x0F]; /*!< dev Periodic Transmit FIFO */ } USB_OTG_GlobalTypeDef; /** * @brief __device_Registers */ typedef struct { __IO uint32_t DCFG; /*!< dev Configuration Register Address offset : 0x800 */ __IO uint32_t DCTL; /*!< dev Control Register Address offset : 0x804 */ __IO uint32_t DSTS; /*!< dev Status Register (RO) Address offset : 0x808 */ uint32_t Reserved0C; /*!< Reserved Address offset : 0x80C */ __IO uint32_t DIEPMSK; /* !< dev IN Endpoint Mask Address offset : 0x810 */ __IO uint32_t DOEPMSK; /*!< dev OUT Endpoint Mask Address offset : 0x814 */ __IO uint32_t DAINT; /*!< dev All Endpoints Itr Reg Address offset : 0x818 */ __IO uint32_t DAINTMSK; /*!< dev All Endpoints Itr Mask Address offset : 0x81C */ uint32_t Reserved20; /*!< Reserved Address offset : 0x820 */ uint32_t Reserved9; /*!< Reserved Address offset : 0x824 */ __IO uint32_t DVBUSDIS; /*!< dev VBUS discharge Register Address offset : 0x828 */ __IO uint32_t DVBUSPULSE; /*!< dev VBUS Pulse Register Address offset : 0x82C */ __IO uint32_t DTHRCTL; /*!< dev thr Address offset : 0x830 */ __IO uint32_t DIEPEMPMSK; /*!< dev empty msk Address offset : 0x834 */ __IO uint32_t DEACHINT; /*!< dedicated EP interrupt Address offset : 0x838 */ __IO uint32_t DEACHMSK; /*!< dedicated EP msk Address offset : 0x83C */ uint32_t Reserved40; /*!< dedicated EP mask Address offset : 0x840 */ __IO uint32_t DINEP1MSK; /*!< dedicated EP mask Address offset : 0x844 */ uint32_t Reserved44[15]; /*!< Reserved Address offset : 0x844-0x87C */ __IO uint32_t DOUTEP1MSK; /*!< dedicated EP msk Address offset : 0x884 */ } USB_OTG_DeviceTypeDef; /** * @brief __IN_Endpoint-Specific_Register */ typedef struct { __IO uint32_t DIEPCTL; /* dev IN Endpoint Control Reg 900h + (ep_num * 20h) + 00h */ uint32_t Reserved04; /* Reserved 900h + (ep_num * 20h) + 04h */ __IO uint32_t DIEPINT; /* dev IN Endpoint Itr Reg 900h + (ep_num * 20h) + 08h */ uint32_t Reserved0C; /* Reserved 900h + (ep_num * 20h) + 0Ch */ __IO uint32_t DIEPTSIZ; /* IN Endpoint Txfer Size 900h + (ep_num * 20h) + 10h */ __IO uint32_t DIEPDMA; /* IN Endpoint DMA Address Reg 900h + (ep_num * 20h) + 14h */ __IO uint32_t DTXFSTS; /*IN Endpoint Tx FIFO Status Reg 900h + (ep_num * 20h) + 18h */ uint32_t Reserved18; /* Reserved 900h+(ep_num*20h)+1Ch-900h+ (ep_num * 20h) + 1Ch */ } USB_OTG_INEndpointTypeDef; /** * @brief __OUT_Endpoint-Specific_Registers */ typedef struct { __IO uint32_t DOEPCTL; /* dev OUT Endpoint Control Reg B00h + (ep_num * 20h) + 00h*/ uint32_t Reserved04; /* Reserved B00h + (ep_num * 20h) + 04h*/ __IO uint32_t DOEPINT; /* dev OUT Endpoint Itr Reg B00h + (ep_num * 20h) + 08h*/ uint32_t Reserved0C; /* Reserved B00h + (ep_num * 20h) + 0Ch*/ __IO uint32_t DOEPTSIZ; /* dev OUT Endpoint Txfer Size B00h + (ep_num * 20h) + 10h*/ __IO uint32_t DOEPDMA; /* dev OUT Endpoint DMA Address B00h + (ep_num * 20h) + 14h*/ uint32_t Reserved18[2]; /* Reserved B00h + (ep_num * 20h) + 18h - B00h + (ep_num * 20h) + 1Ch*/ } USB_OTG_OUTEndpointTypeDef; /** * @brief __Host_Mode_Register_Structures */ typedef struct { __IO uint32_t HCFG; /* Host Configuration Register 400h*/ __IO uint32_t HFIR; /* Host Frame Interval Register 404h*/ __IO uint32_t HFNUM; /* Host Frame Nbr/Frame Remaining 408h*/ uint32_t Reserved40C; /* Reserved 40Ch*/ __IO uint32_t HPTXSTS; /* Host Periodic Tx FIFO/ Queue Status 410h*/ __IO uint32_t HAINT; /* Host All Channels Interrupt Register 414h*/ __IO uint32_t HAINTMSK; /* Host All Channels Interrupt Mask 418h*/ } USB_OTG_HostTypeDef; /** * @brief __Host_Channel_Specific_Registers */ typedef struct { __IO uint32_t HCCHAR; __IO uint32_t HCSPLT; __IO uint32_t HCINT; __IO uint32_t HCINTMSK; __IO uint32_t HCTSIZ; __IO uint32_t HCDMA; uint32_t Reserved[2]; } USB_OTG_HostChannelTypeDef; /** * @brief Peripheral_memory_map */ #define FLASH_BASE ((uint32_t)0x08000000) /*!< FLASH(up to 1 MB) base address in the alias region */ #define CCMDATARAM_BASE ((uint32_t)0x10000000) /*!< CCM(core coupled memory) data RAM(64 KB) base address in the alias region */ #define SRAM1_BASE ((uint32_t)0x20000000) /*!< SRAM1(112 KB) base address in the alias region */ #define SRAM2_BASE ((uint32_t)0x2001C000) /*!< SRAM2(16 KB) base address in the alias region */ #define PERIPH_BASE ((uint32_t)0x40000000) /*!< Peripheral base address in the alias region */ #define BKPSRAM_BASE ((uint32_t)0x40024000) /*!< Backup SRAM(4 KB) base address in the alias region */ #define SRAM1_BB_BASE ((uint32_t)0x22000000) /*!< SRAM1(112 KB) base address in the bit-band region */ #define SRAM2_BB_BASE ((uint32_t)0x22380000) /*!< SRAM2(16 KB) base address in the bit-band region */ #define PERIPH_BB_BASE ((uint32_t)0x42000000) /*!< Peripheral base address in the bit-band region */ #define BKPSRAM_BB_BASE ((uint32_t)0x42480000) /*!< Backup SRAM(4 KB) base address in the bit-band region */ #define FLASH_END ((uint32_t)0x0807FFFF) /*!< FLASH end address */ /* Legacy defines */ #define SRAM_BASE SRAM1_BASE #define SRAM_BB_BASE SRAM1_BB_BASE /*!< Peripheral memory map */ #define APB1PERIPH_BASE PERIPH_BASE #define APB2PERIPH_BASE (PERIPH_BASE + 0x00010000) #define AHB1PERIPH_BASE (PERIPH_BASE + 0x00020000) #define AHB2PERIPH_BASE (PERIPH_BASE + 0x10000000) /*!< APB1 peripherals */ #define TIM2_BASE (APB1PERIPH_BASE + 0x0000) #define TIM3_BASE (APB1PERIPH_BASE + 0x0400) #define TIM4_BASE (APB1PERIPH_BASE + 0x0800) #define TIM5_BASE (APB1PERIPH_BASE + 0x0C00) #define RTC_BASE (APB1PERIPH_BASE + 0x2800) #define WWDG_BASE (APB1PERIPH_BASE + 0x2C00) #define IWDG_BASE (APB1PERIPH_BASE + 0x3000) #define I2S2ext_BASE (APB1PERIPH_BASE + 0x3400) #define SPI2_BASE (APB1PERIPH_BASE + 0x3800) #define SPI3_BASE (APB1PERIPH_BASE + 0x3C00) #define I2S3ext_BASE (APB1PERIPH_BASE + 0x4000) #define USART2_BASE (APB1PERIPH_BASE + 0x4400) #define I2C1_BASE (APB1PERIPH_BASE + 0x5400) #define I2C2_BASE (APB1PERIPH_BASE + 0x5800) #define I2C3_BASE (APB1PERIPH_BASE + 0x5C00) #define PWR_BASE (APB1PERIPH_BASE + 0x7000) /*!< APB2 peripherals */ #define TIM1_BASE (APB2PERIPH_BASE + 0x0000) #define USART1_BASE (APB2PERIPH_BASE + 0x1000) #define USART6_BASE (APB2PERIPH_BASE + 0x1400) #define ADC1_BASE (APB2PERIPH_BASE + 0x2000) #define ADC_BASE (APB2PERIPH_BASE + 0x2300) #define SDIO_BASE (APB2PERIPH_BASE + 0x2C00) #define SPI1_BASE (APB2PERIPH_BASE + 0x3000) #define SPI4_BASE (APB2PERIPH_BASE + 0x3400) #define SYSCFG_BASE (APB2PERIPH_BASE + 0x3800) #define EXTI_BASE (APB2PERIPH_BASE + 0x3C00) #define TIM9_BASE (APB2PERIPH_BASE + 0x4000) #define TIM10_BASE (APB2PERIPH_BASE + 0x4400) #define TIM11_BASE (APB2PERIPH_BASE + 0x4800) #define SPI5_BASE (APB2PERIPH_BASE + 0x5000) /*!< AHB1 peripherals */ #define GPIOA_BASE (AHB1PERIPH_BASE + 0x0000) #define GPIOB_BASE (AHB1PERIPH_BASE + 0x0400) #define GPIOC_BASE (AHB1PERIPH_BASE + 0x0800) #define GPIOD_BASE (AHB1PERIPH_BASE + 0x0C00) #define GPIOE_BASE (AHB1PERIPH_BASE + 0x1000) #define GPIOH_BASE (AHB1PERIPH_BASE + 0x1C00) #define CRC_BASE (AHB1PERIPH_BASE + 0x3000) #define RCC_BASE (AHB1PERIPH_BASE + 0x3800) #define FLASH_R_BASE (AHB1PERIPH_BASE + 0x3C00) #define DMA1_BASE (AHB1PERIPH_BASE + 0x6000) #define DMA1_Stream0_BASE (DMA1_BASE + 0x010) #define DMA1_Stream1_BASE (DMA1_BASE + 0x028) #define DMA1_Stream2_BASE (DMA1_BASE + 0x040) #define DMA1_Stream3_BASE (DMA1_BASE + 0x058) #define DMA1_Stream4_BASE (DMA1_BASE + 0x070) #define DMA1_Stream5_BASE (DMA1_BASE + 0x088) #define DMA1_Stream6_BASE (DMA1_BASE + 0x0A0) #define DMA1_Stream7_BASE (DMA1_BASE + 0x0B8) #define DMA2_BASE (AHB1PERIPH_BASE + 0x6400) #define DMA2_Stream0_BASE (DMA2_BASE + 0x010) #define DMA2_Stream1_BASE (DMA2_BASE + 0x028) #define DMA2_Stream2_BASE (DMA2_BASE + 0x040) #define DMA2_Stream3_BASE (DMA2_BASE + 0x058) #define DMA2_Stream4_BASE (DMA2_BASE + 0x070) #define DMA2_Stream5_BASE (DMA2_BASE + 0x088) #define DMA2_Stream6_BASE (DMA2_BASE + 0x0A0) #define DMA2_Stream7_BASE (DMA2_BASE + 0x0B8) /* Debug MCU registers base address */ #define DBGMCU_BASE ((uint32_t )0xE0042000) /*!< USB registers base address */ #define USB_OTG_FS_PERIPH_BASE ((uint32_t )0x50000000) #define USB_OTG_GLOBAL_BASE ((uint32_t )0x000) #define USB_OTG_DEVICE_BASE ((uint32_t )0x800) #define USB_OTG_IN_ENDPOINT_BASE ((uint32_t )0x900) #define USB_OTG_OUT_ENDPOINT_BASE ((uint32_t )0xB00) #define USB_OTG_EP_REG_SIZE ((uint32_t )0x20) #define USB_OTG_HOST_BASE ((uint32_t )0x400) #define USB_OTG_HOST_PORT_BASE ((uint32_t )0x440) #define USB_OTG_HOST_CHANNEL_BASE ((uint32_t )0x500) #define USB_OTG_HOST_CHANNEL_SIZE ((uint32_t )0x20) #define USB_OTG_PCGCCTL_BASE ((uint32_t )0xE00) #define USB_OTG_FIFO_BASE ((uint32_t )0x1000) #define USB_OTG_FIFO_SIZE ((uint32_t )0x1000) /** * @} */ /** @addtogroup Peripheral_declaration * @{ */ #define TIM2 ((TIM_TypeDef *) TIM2_BASE) #define TIM3 ((TIM_TypeDef *) TIM3_BASE) #define TIM4 ((TIM_TypeDef *) TIM4_BASE) #define TIM5 ((TIM_TypeDef *) TIM5_BASE) #define RTC ((RTC_TypeDef *) RTC_BASE) #define WWDG ((WWDG_TypeDef *) WWDG_BASE) #define IWDG ((IWDG_TypeDef *) IWDG_BASE) #define I2S2ext ((SPI_TypeDef *) I2S2ext_BASE) #define SPI2 ((SPI_TypeDef *) SPI2_BASE) #define SPI3 ((SPI_TypeDef *) SPI3_BASE) #define I2S3ext ((SPI_TypeDef *) I2S3ext_BASE) #define USART2 ((USART_TypeDef *) USART2_BASE) #define I2C1 ((I2C_TypeDef *) I2C1_BASE) #define I2C2 ((I2C_TypeDef *) I2C2_BASE) #define I2C3 ((I2C_TypeDef *) I2C3_BASE) #define PWR ((PWR_TypeDef *) PWR_BASE) #define TIM1 ((TIM_TypeDef *) TIM1_BASE) #define USART1 ((USART_TypeDef *) USART1_BASE) #define USART6 ((USART_TypeDef *) USART6_BASE) #define ADC ((ADC_Common_TypeDef *) ADC_BASE) #define ADC1 ((ADC_TypeDef *) ADC1_BASE) #define SDIO ((SDIO_TypeDef *) SDIO_BASE) #define SPI1 ((SPI_TypeDef *) SPI1_BASE) #define SPI4 ((SPI_TypeDef *) SPI4_BASE) #define SYSCFG ((SYSCFG_TypeDef *) SYSCFG_BASE) #define EXTI ((EXTI_TypeDef *) EXTI_BASE) #define TIM9 ((TIM_TypeDef *) TIM9_BASE) #define TIM10 ((TIM_TypeDef *) TIM10_BASE) #define TIM11 ((TIM_TypeDef *) TIM11_BASE) #define SPI5 ((SPI_TypeDef *) SPI5_BASE) #define GPIOA ((GPIO_TypeDef *) GPIOA_BASE) #define GPIOB ((GPIO_TypeDef *) GPIOB_BASE) #define GPIOC ((GPIO_TypeDef *) GPIOC_BASE) #define GPIOD ((GPIO_TypeDef *) GPIOD_BASE) #define GPIOE ((GPIO_TypeDef *) GPIOE_BASE) #define GPIOH ((GPIO_TypeDef *) GPIOH_BASE) #define CRC ((CRC_TypeDef *) CRC_BASE) #define RCC ((RCC_TypeDef *) RCC_BASE) #define FLASH ((FLASH_TypeDef *) FLASH_R_BASE) #define DMA1 ((DMA_TypeDef *) DMA1_BASE) #define DMA1_Stream0 ((DMA_Stream_TypeDef *) DMA1_Stream0_BASE) #define DMA1_Stream1 ((DMA_Stream_TypeDef *) DMA1_Stream1_BASE) #define DMA1_Stream2 ((DMA_Stream_TypeDef *) DMA1_Stream2_BASE) #define DMA1_Stream3 ((DMA_Stream_TypeDef *) DMA1_Stream3_BASE) #define DMA1_Stream4 ((DMA_Stream_TypeDef *) DMA1_Stream4_BASE) #define DMA1_Stream5 ((DMA_Stream_TypeDef *) DMA1_Stream5_BASE) #define DMA1_Stream6 ((DMA_Stream_TypeDef *) DMA1_Stream6_BASE) #define DMA1_Stream7 ((DMA_Stream_TypeDef *) DMA1_Stream7_BASE) #define DMA2 ((DMA_TypeDef *) DMA2_BASE) #define DMA2_Stream0 ((DMA_Stream_TypeDef *) DMA2_Stream0_BASE) #define DMA2_Stream1 ((DMA_Stream_TypeDef *) DMA2_Stream1_BASE) #define DMA2_Stream2 ((DMA_Stream_TypeDef *) DMA2_Stream2_BASE) #define DMA2_Stream3 ((DMA_Stream_TypeDef *) DMA2_Stream3_BASE) #define DMA2_Stream4 ((DMA_Stream_TypeDef *) DMA2_Stream4_BASE) #define DMA2_Stream5 ((DMA_Stream_TypeDef *) DMA2_Stream5_BASE) #define DMA2_Stream6 ((DMA_Stream_TypeDef *) DMA2_Stream6_BASE) #define DMA2_Stream7 ((DMA_Stream_TypeDef *) DMA2_Stream7_BASE) #define DBGMCU ((DBGMCU_TypeDef *) DBGMCU_BASE) #define USB_OTG_FS ((USB_OTG_GlobalTypeDef *) USB_OTG_FS_PERIPH_BASE) /** * @} */ /** @addtogroup Exported_constants * @{ */ /** @addtogroup Peripheral_Registers_Bits_Definition * @{ */ /******************************************************************************/ /* Peripheral Registers_Bits_Definition */ /******************************************************************************/ /******************************************************************************/ /* */ /* Analog to Digital Converter */ /* */ /******************************************************************************/ /******************** Bit definition for ADC_SR register ********************/ #define ADC_SR_AWD ((uint32_t)0x00000001) /*!
© COPYRIGHT(c) 2015 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. * ****************************************************************************** */ /** @addtogroup CMSIS * @{ */ /** @addtogroup stm32f4xx * @{ */ #ifndef __STM32F4xx_H #define __STM32F4xx_H #ifdef __cplusplus extern "C" { #endif /* __cplusplus */ /** @addtogroup Library_configuration_section * @{ */ /** * @brief STM32 Family */ #if !defined (STM32F4) #define STM32F4 #endif /* STM32F4 */ /* Uncomment the line below according to the target STM32 device used in your application */ #if !defined (STM32F405xx) && !defined (STM32F415xx) && !defined (STM32F407xx) && !defined (STM32F417xx) && \ !defined (STM32F427xx) && !defined (STM32F437xx) && !defined (STM32F429xx) && !defined (STM32F439xx) && \ !defined (STM32F401xC) && !defined (STM32F401xE) && !defined (STM32F411xE) && !defined (STM32F446xx) /* #define STM32F405xx */ /*!< STM32F405RG, STM32F405VG and STM32F405ZG Devices */ /* #define STM32F415xx */ /*!< STM32F415RG, STM32F415VG and STM32F415ZG Devices */ /* #define STM32F407xx */ /*!< STM32F407VG, STM32F407VE, STM32F407ZG, STM32F407ZE, STM32F407IG and STM32F407IE Devices */ /* #define STM32F417xx */ /*!< STM32F417VG, STM32F417VE, STM32F417ZG, STM32F417ZE, STM32F417IG and STM32F417IE Devices */ /* #define STM32F427xx */ /*!< STM32F427VG, STM32F427VI, STM32F427ZG, STM32F427ZI, STM32F427IG and STM32F427II Devices */ /* #define STM32F437xx */ /*!< STM32F437VG, STM32F437VI, STM32F437ZG, STM32F437ZI, STM32F437IG and STM32F437II Devices */ /* #define STM32F429xx */ /*!< STM32F429VG, STM32F429VI, STM32F429ZG, STM32F429ZI, STM32F429BG, STM32F429BI, STM32F429NG, STM32F439NI, STM32F429IG and STM32F429II Devices */ /* #define STM32F439xx */ /*!< STM32F439VG, STM32F439VI, STM32F439ZG, STM32F439ZI, STM32F439BG, STM32F439BI, STM32F439NG, STM32F439NI, STM32F439IG and STM32F439II Devices */ /* #define STM32F401xC */ /*!< STM32F401CB, STM32F401CC, STM32F401RB, STM32F401RC, STM32F401VB and STM32F401VC Devices */ /* #define STM32F401xE */ /*!< STM32F401CD, STM32F401RD, STM32F401VD, STM32F401CE, STM32F401RE and STM32F401VE Devices */ #define STM32F411xE /*!< STM32F411CD, STM32F411RD, STM32F411VD, STM32F411CE, STM32F411RE and STM32F411VE Devices */ /* #define STM32F446xx */ /*!< STM32F446MC, STM32F446ME, STM32F446RC, STM32F446RE, STM32F446VC, STM32F446VE, STM32F446ZC, and STM32F446ZE Devices */ #endif /* Tip: To avoid modifying this file each time you need to switch between these devices, you can define the device in your toolchain compiler preprocessor. */ #if !defined (USE_HAL_DRIVER) /** * @brief Comment the line below if you will not use the peripherals drivers. In this case, these drivers will not be included and the application code will be based on direct access to peripherals registers */ #define USE_HAL_DRIVER #endif /* USE_HAL_DRIVER */ /** * @brief CMSIS Device version number V2.3.2 */ #define __STM32F4xx_CMSIS_DEVICE_VERSION_MAIN (0x02) /*!< [31:24] main version */ #define __STM32F4xx_CMSIS_DEVICE_VERSION_SUB1 (0x03) /*!< [23:16] sub1 version */ #define __STM32F4xx_CMSIS_DEVICE_VERSION_SUB2 (0x02) /*!< [15:8] sub2 version */ #define __STM32F4xx_CMSIS_DEVICE_VERSION_RC (0x00) /*!< [7:0] release candidate */ #define __STM32F4xx_CMSIS_DEVICE_VERSION ((__STM32F4xx_CMSIS_DEVICE_VERSION_MAIN << 24)\ |(__STM32F4xx_CMSIS_DEVICE_VERSION_SUB1 << 16)\ |(__STM32F4xx_CMSIS_DEVICE_VERSION_SUB2 << 8 )\ |(__STM32F4xx_CMSIS_DEVICE_VERSION)) /** * @} */ /** @addtogroup Device_Included * @{ */ #if defined(STM32F405xx) #include "stm32f405xx.h" #elif defined(STM32F415xx) #include "stm32f415xx.h" #elif defined(STM32F407xx) #include "stm32f407xx.h" #elif defined(STM32F417xx) #include "stm32f417xx.h" #elif defined(STM32F427xx) #include "stm32f427xx.h" #elif defined(STM32F437xx) #include "stm32f437xx.h" #elif defined(STM32F429xx) #include "stm32f429xx.h" #elif defined(STM32F439xx) #include "stm32f439xx.h" #elif defined(STM32F401xC) #include "stm32f401xc.h" #elif defined(STM32F401xE) #include "stm32f401xe.h" #elif defined(STM32F411xE) #include "stm32f411xe.h" #elif defined(STM32F446xx) #include "stm32f446xx.h" #else #error "Please select first the target STM32F4xx device used in your application (in stm32f4xx.h file)" #endif /** * @} */ /** @addtogroup Exported_types * @{ */ typedef enum { RESET = 0, SET = !RESET } FlagStatus, ITStatus; typedef enum { DISABLE = 0, ENABLE = !DISABLE } FunctionalState; #define IS_FUNCTIONAL_STATE(STATE) (((STATE) == DISABLE) || ((STATE) == ENABLE)) typedef enum { ERROR = 0, SUCCESS = !ERROR } ErrorStatus; /** * @} */ /** @addtogroup Exported_macro * @{ */ #define SET_BIT(REG, BIT) ((REG) |= (BIT)) #define CLEAR_BIT(REG, BIT) ((REG) &= ~(BIT)) #define READ_BIT(REG, BIT) ((REG) & (BIT)) #define CLEAR_REG(REG) ((REG) = (0x0)) #define WRITE_REG(REG, VAL) ((REG) = (VAL)) #define READ_REG(REG) ((REG)) #define MODIFY_REG(REG, CLEARMASK, SETMASK) WRITE_REG((REG), (((READ_REG(REG)) & (~(CLEARMASK))) | (SETMASK))) #define POSITION_VAL(VAL) (__CLZ(__RBIT(VAL))) /** * @} */ #if defined (USE_HAL_DRIVER) #include "stm32f4xx_hal.h" #endif /* USE_HAL_DRIVER */ #ifdef __cplusplus } #endif /* __cplusplus */ #endif /* __STM32F4xx_H */ /** * @} */ /** * @} */ /************************ (C) COPYRIGHT STMicroelectronics *****END OF FILE****/ ================================================ FILE: Zelig/mbed/TARGET_NUCLEO_F411RE/stm32f4xx_hal.h ================================================ /** ****************************************************************************** * @file stm32f4xx_hal.h * @author MCD Application Team * @version V1.4.1 * @date 09-October-2015 * @brief This file contains all the functions prototypes for the HAL * module driver. ****************************************************************************** * @attention * *

© COPYRIGHT(c) 2015 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. * ****************************************************************************** */ /* Define to prevent recursive inclusion -------------------------------------*/ #ifndef __STM32F4xx_HAL_H #define __STM32F4xx_HAL_H #ifdef __cplusplus extern "C" { #endif /* Includes ------------------------------------------------------------------*/ #include "stm32f4xx_hal_conf.h" /** @addtogroup STM32F4xx_HAL_Driver * @{ */ /** @addtogroup HAL * @{ */ /* Exported types ------------------------------------------------------------*/ /* Exported constants --------------------------------------------------------*/ /* Exported macro ------------------------------------------------------------*/ /** @defgroup HAL_Exported_Macros HAL Exported Macros * @{ */ /** @brief Freeze/Unfreeze Peripherals in Debug mode */ #define __HAL_DBGMCU_FREEZE_TIM2() (DBGMCU->APB1FZ |= (DBGMCU_APB1_FZ_DBG_TIM2_STOP)) #define __HAL_DBGMCU_FREEZE_TIM3() (DBGMCU->APB1FZ |= (DBGMCU_APB1_FZ_DBG_TIM3_STOP)) #define __HAL_DBGMCU_FREEZE_TIM4() (DBGMCU->APB1FZ |= (DBGMCU_APB1_FZ_DBG_TIM4_STOP)) #define __HAL_DBGMCU_FREEZE_TIM5() (DBGMCU->APB1FZ |= (DBGMCU_APB1_FZ_DBG_TIM5_STOP)) #define __HAL_DBGMCU_FREEZE_TIM6() (DBGMCU->APB1FZ |= (DBGMCU_APB1_FZ_DBG_TIM6_STOP)) #define __HAL_DBGMCU_FREEZE_TIM7() (DBGMCU->APB1FZ |= (DBGMCU_APB1_FZ_DBG_TIM7_STOP)) #define __HAL_DBGMCU_FREEZE_TIM12() (DBGMCU->APB1FZ |= (DBGMCU_APB1_FZ_DBG_TIM12_STOP)) #define __HAL_DBGMCU_FREEZE_TIM13() (DBGMCU->APB1FZ |= (DBGMCU_APB1_FZ_DBG_TIM13_STOP)) #define __HAL_DBGMCU_FREEZE_TIM14() (DBGMCU->APB1FZ |= (DBGMCU_APB1_FZ_DBG_TIM14_STOP)) #define __HAL_DBGMCU_FREEZE_RTC() (DBGMCU->APB1FZ |= (DBGMCU_APB1_FZ_DBG_RTC_STOP)) #define __HAL_DBGMCU_FREEZE_WWDG() (DBGMCU->APB1FZ |= (DBGMCU_APB1_FZ_DBG_WWDG_STOP)) #define __HAL_DBGMCU_FREEZE_IWDG() (DBGMCU->APB1FZ |= (DBGMCU_APB1_FZ_DBG_IWDG_STOP)) #define __HAL_DBGMCU_FREEZE_I2C1_TIMEOUT() (DBGMCU->APB1FZ |= (DBGMCU_APB1_FZ_DBG_I2C1_SMBUS_TIMEOUT)) #define __HAL_DBGMCU_FREEZE_I2C2_TIMEOUT() (DBGMCU->APB1FZ |= (DBGMCU_APB1_FZ_DBG_I2C2_SMBUS_TIMEOUT)) #define __HAL_DBGMCU_FREEZE_I2C3_TIMEOUT() (DBGMCU->APB1FZ |= (DBGMCU_APB1_FZ_DBG_I2C3_SMBUS_TIMEOUT)) #define __HAL_DBGMCU_FREEZE_CAN1() (DBGMCU->APB1FZ |= (DBGMCU_APB1_FZ_DBG_CAN1_STOP)) #define __HAL_DBGMCU_FREEZE_CAN2() (DBGMCU->APB1FZ |= (DBGMCU_APB1_FZ_DBG_CAN2_STOP)) #define __HAL_DBGMCU_FREEZE_TIM1() (DBGMCU->APB2FZ |= (DBGMCU_APB2_FZ_DBG_TIM1_STOP)) #define __HAL_DBGMCU_FREEZE_TIM8() (DBGMCU->APB2FZ |= (DBGMCU_APB2_FZ_DBG_TIM8_STOP)) #define __HAL_DBGMCU_FREEZE_TIM9() (DBGMCU->APB2FZ |= (DBGMCU_APB2_FZ_DBG_TIM9_STOP)) #define __HAL_DBGMCU_FREEZE_TIM10() (DBGMCU->APB2FZ |= (DBGMCU_APB2_FZ_DBG_TIM10_STOP)) #define __HAL_DBGMCU_FREEZE_TIM11() (DBGMCU->APB2FZ |= (DBGMCU_APB2_FZ_DBG_TIM11_STOP)) #define __HAL_DBGMCU_UNFREEZE_TIM2() (DBGMCU->APB1FZ &= ~(DBGMCU_APB1_FZ_DBG_TIM2_STOP)) #define __HAL_DBGMCU_UNFREEZE_TIM3() (DBGMCU->APB1FZ &= ~(DBGMCU_APB1_FZ_DBG_TIM3_STOP)) #define __HAL_DBGMCU_UNFREEZE_TIM4() (DBGMCU->APB1FZ &= ~(DBGMCU_APB1_FZ_DBG_TIM4_STOP)) #define __HAL_DBGMCU_UNFREEZE_TIM5() (DBGMCU->APB1FZ &= ~(DBGMCU_APB1_FZ_DBG_TIM5_STOP)) #define __HAL_DBGMCU_UNFREEZE_TIM6() (DBGMCU->APB1FZ &= ~(DBGMCU_APB1_FZ_DBG_TIM6_STOP)) #define __HAL_DBGMCU_UNFREEZE_TIM7() (DBGMCU->APB1FZ &= ~(DBGMCU_APB1_FZ_DBG_TIM7_STOP)) #define __HAL_DBGMCU_UNFREEZE_TIM12() (DBGMCU->APB1FZ &= ~(DBGMCU_APB1_FZ_DBG_TIM12_STOP)) #define __HAL_DBGMCU_UNFREEZE_TIM13() (DBGMCU->APB1FZ &= ~(DBGMCU_APB1_FZ_DBG_TIM13_STOP)) #define __HAL_DBGMCU_UNFREEZE_TIM14() (DBGMCU->APB1FZ &= ~(DBGMCU_APB1_FZ_DBG_TIM14_STOP)) #define __HAL_DBGMCU_UNFREEZE_RTC() (DBGMCU->APB1FZ &= ~(DBGMCU_APB1_FZ_DBG_RTC_STOP)) #define __HAL_DBGMCU_UNFREEZE_WWDG() (DBGMCU->APB1FZ &= ~(DBGMCU_APB1_FZ_DBG_WWDG_STOP)) #define __HAL_DBGMCU_UNFREEZE_IWDG() (DBGMCU->APB1FZ &= ~(DBGMCU_APB1_FZ_DBG_IWDG_STOP)) #define __HAL_DBGMCU_UNFREEZE_I2C1_TIMEOUT() (DBGMCU->APB1FZ &= ~(DBGMCU_APB1_FZ_DBG_I2C1_SMBUS_TIMEOUT)) #define __HAL_DBGMCU_UNFREEZE_I2C2_TIMEOUT() (DBGMCU->APB1FZ &= ~(DBGMCU_APB1_FZ_DBG_I2C2_SMBUS_TIMEOUT)) #define __HAL_DBGMCU_UNFREEZE_I2C3_TIMEOUT() (DBGMCU->APB1FZ &= ~(DBGMCU_APB1_FZ_DBG_I2C3_SMBUS_TIMEOUT)) #define __HAL_DBGMCU_UNFREEZE_CAN1() (DBGMCU->APB1FZ &= ~(DBGMCU_APB1_FZ_DBG_CAN1_STOP)) #define __HAL_DBGMCU_UNFREEZE_CAN2() (DBGMCU->APB1FZ &= ~(DBGMCU_APB1_FZ_DBG_CAN2_STOP)) #define __HAL_DBGMCU_UNFREEZE_TIM1() (DBGMCU->APB2FZ &= ~(DBGMCU_APB2_FZ_DBG_TIM1_STOP)) #define __HAL_DBGMCU_UNFREEZE_TIM8() (DBGMCU->APB2FZ &= ~(DBGMCU_APB2_FZ_DBG_TIM8_STOP)) #define __HAL_DBGMCU_UNFREEZE_TIM9() (DBGMCU->APB2FZ &= ~(DBGMCU_APB2_FZ_DBG_TIM9_STOP)) #define __HAL_DBGMCU_UNFREEZE_TIM10() (DBGMCU->APB2FZ &= ~(DBGMCU_APB2_FZ_DBG_TIM10_STOP)) #define __HAL_DBGMCU_UNFREEZE_TIM11() (DBGMCU->APB2FZ &= ~(DBGMCU_APB2_FZ_DBG_TIM11_STOP)) /** @brief Main Flash memory mapped at 0x00000000 */ #define __HAL_SYSCFG_REMAPMEMORY_FLASH() (SYSCFG->MEMRMP &= ~(SYSCFG_MEMRMP_MEM_MODE)) /** @brief System Flash memory mapped at 0x00000000 */ #define __HAL_SYSCFG_REMAPMEMORY_SYSTEMFLASH() do {SYSCFG->MEMRMP &= ~(SYSCFG_MEMRMP_MEM_MODE);\ SYSCFG->MEMRMP |= SYSCFG_MEMRMP_MEM_MODE_0;\ }while(0); /** @brief Embedded SRAM mapped at 0x00000000 */ #define __HAL_SYSCFG_REMAPMEMORY_SRAM() do {SYSCFG->MEMRMP &= ~(SYSCFG_MEMRMP_MEM_MODE);\ SYSCFG->MEMRMP |= (SYSCFG_MEMRMP_MEM_MODE_0 | SYSCFG_MEMRMP_MEM_MODE_1);\ }while(0); #if defined(STM32F405xx) || defined(STM32F415xx) || defined(STM32F407xx)|| defined(STM32F417xx) /** @brief FSMC Bank1 (NOR/PSRAM 1 and 2) mapped at 0x00000000 */ #define __HAL_SYSCFG_REMAPMEMORY_FSMC() do {SYSCFG->MEMRMP &= ~(SYSCFG_MEMRMP_MEM_MODE);\ SYSCFG->MEMRMP |= (SYSCFG_MEMRMP_MEM_MODE_1);\ }while(0); #endif /* STM32F405xx || STM32F415xx || STM32F407xx || STM32F417xx */ #if defined(STM32F427xx) || defined(STM32F437xx) || defined(STM32F429xx)|| defined(STM32F439xx) ||\ defined(STM32F469xx) || defined(STM32F479xx) /** @brief FMC Bank1 (NOR/PSRAM 1 and 2) mapped at 0x00000000 */ #define __HAL_SYSCFG_REMAPMEMORY_FMC() do {SYSCFG->MEMRMP &= ~(SYSCFG_MEMRMP_MEM_MODE);\ SYSCFG->MEMRMP |= (SYSCFG_MEMRMP_MEM_MODE_1);\ }while(0); /** @brief FMC/SDRAM Bank 1 and 2 mapped at 0x00000000 */ #define __HAL_SYSCFG_REMAPMEMORY_FMC_SDRAM() do {SYSCFG->MEMRMP &= ~(SYSCFG_MEMRMP_MEM_MODE);\ SYSCFG->MEMRMP |= (SYSCFG_MEMRMP_MEM_MODE_2);\ }while(0); #endif /* STM32F427xx || STM32F437xx || STM32F429xx || STM32F439xx || STM32F469xx || STM32F479xx */ #if defined(STM32F410Tx) || defined(STM32F410Cx) || defined(STM32F410Rx) /** @defgroup Cortex_Lockup_Enable Cortex Lockup Enable * @{ */ /** @brief SYSCFG Break Lockup lock * Enables and locks the connection of Cortex-M4 LOCKUP (Hardfault) output to TIM1/8 input * @note The selected configuration is locked and can be unlocked by system reset */ #define __HAL_SYSCFG_BREAK_PVD_LOCK() do {SYSCFG->CFGR2 &= ~(SYSCFG_CFGR2_PVD_LOCK); \ SYSCFG->CFGR2 |= SYSCFG_CFGR2_PVD_LOCK; \ }while(0) /** * @} */ /** @defgroup PVD_Lock_Enable PVD Lock * @{ */ /** @brief SYSCFG Break PVD lock * Enables and locks the PVD connection with Timer1/8 Break Input, , as well as the PVDE and PLS[2:0] in the PWR_CR register * @note The selected configuration is locked and can be unlocked by system reset */ #define __HAL_SYSCFG_BREAK_LOCKUP_LOCK() do {SYSCFG->CFGR2 &= ~(SYSCFG_CFGR2_LOCKUP_LOCK); \ SYSCFG->CFGR2 |= SYSCFG_CFGR2_LOCKUP_LOCK; \ }while(0) /** * @} */ #endif /* STM32F410Tx || STM32F410Cx || STM32F410Rx */ /** * @} */ /* Exported functions --------------------------------------------------------*/ /** @addtogroup HAL_Exported_Functions * @{ */ /** @addtogroup HAL_Exported_Functions_Group1 * @{ */ /* Initialization and de-initialization functions ******************************/ HAL_StatusTypeDef HAL_Init(void); HAL_StatusTypeDef HAL_DeInit(void); void HAL_MspInit(void); void HAL_MspDeInit(void); HAL_StatusTypeDef HAL_InitTick (uint32_t TickPriority); /** * @} */ /** @addtogroup HAL_Exported_Functions_Group2 * @{ */ /* Peripheral Control functions ************************************************/ void HAL_IncTick(void); void HAL_Delay(__IO uint32_t Delay); uint32_t HAL_GetTick(void); void HAL_SuspendTick(void); void HAL_ResumeTick(void); uint32_t HAL_GetHalVersion(void); uint32_t HAL_GetREVID(void); uint32_t HAL_GetDEVID(void); void HAL_DBGMCU_EnableDBGSleepMode(void); void HAL_DBGMCU_DisableDBGSleepMode(void); void HAL_DBGMCU_EnableDBGStopMode(void); void HAL_DBGMCU_DisableDBGStopMode(void); void HAL_DBGMCU_EnableDBGStandbyMode(void); void HAL_DBGMCU_DisableDBGStandbyMode(void); void HAL_EnableCompensationCell(void); void HAL_DisableCompensationCell(void); #if defined(STM32F427xx) || defined(STM32F437xx) || defined(STM32F429xx)|| defined(STM32F439xx) ||\ defined(STM32F469xx) || defined(STM32F479xx) void HAL_EnableMemorySwappingBank(void); void HAL_DisableMemorySwappingBank(void); #endif /* STM32F427xx || STM32F437xx || STM32F429xx || STM32F439xx || STM32F469xx || STM32F479xx */ /** * @} */ /** * @} */ /* Private types -------------------------------------------------------------*/ /* Private variables ---------------------------------------------------------*/ /** @defgroup HAL_Private_Variables HAL Private Variables * @{ */ /** * @} */ /* Private constants ---------------------------------------------------------*/ /** @defgroup HAL_Private_Constants HAL Private Constants * @{ */ /** * @} */ /* Private macros ------------------------------------------------------------*/ /* Private functions ---------------------------------------------------------*/ /** * @} */ /** * @} */ #ifdef __cplusplus } #endif #endif /* __STM32F4xx_HAL_H */ /************************ (C) COPYRIGHT STMicroelectronics *****END OF FILE****/ ================================================ FILE: Zelig/mbed/TARGET_NUCLEO_F411RE/stm32f4xx_hal_adc.h ================================================ /** ****************************************************************************** * @file stm32f4xx_hal_adc.h * @author MCD Application Team * @version V1.4.1 * @date 09-October-2015 * @brief Header file containing functions prototypes of ADC HAL library. ****************************************************************************** * @attention * *

© COPYRIGHT(c) 2015 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. * ****************************************************************************** */ /* Define to prevent recursive inclusion -------------------------------------*/ #ifndef __STM32F4xx_ADC_H #define __STM32F4xx_ADC_H #ifdef __cplusplus extern "C" { #endif /* Includes ------------------------------------------------------------------*/ #include "stm32f4xx_hal_def.h" /** @addtogroup STM32F4xx_HAL_Driver * @{ */ /** @addtogroup ADC * @{ */ /* Exported types ------------------------------------------------------------*/ /** @defgroup ADC_Exported_Types ADC Exported Types * @{ */ /** * @brief HAL State structures definition */ typedef enum { HAL_ADC_STATE_RESET = 0x00, /*!< ADC not yet initialized or disabled */ HAL_ADC_STATE_READY = 0x01, /*!< ADC peripheral ready for use */ HAL_ADC_STATE_BUSY = 0x02, /*!< An internal process is ongoing */ HAL_ADC_STATE_BUSY_REG = 0x12, /*!< Regular conversion is ongoing */ HAL_ADC_STATE_BUSY_INJ = 0x22, /*!< Injected conversion is ongoing */ HAL_ADC_STATE_BUSY_INJ_REG = 0x32, /*!< Injected and regular conversion are ongoing */ HAL_ADC_STATE_TIMEOUT = 0x03, /*!< Timeout state */ HAL_ADC_STATE_ERROR = 0x04, /*!< ADC state error */ HAL_ADC_STATE_EOC = 0x05, /*!< Conversion is completed */ HAL_ADC_STATE_EOC_REG = 0x15, /*!< Regular conversion is completed */ HAL_ADC_STATE_EOC_INJ = 0x25, /*!< Injected conversion is completed */ HAL_ADC_STATE_EOC_INJ_REG = 0x35, /*!< Injected and regular conversion are completed */ HAL_ADC_STATE_AWD = 0x06 /*!< ADC state analog watchdog */ }HAL_ADC_StateTypeDef; /** * @brief ADC Init structure definition */ typedef struct { uint32_t ClockPrescaler; /*!< Select the frequency of the clock to the ADC. The clock is common for all the ADCs. This parameter can be a value of @ref ADC_ClockPrescaler */ uint32_t Resolution; /*!< Configures the ADC resolution dual mode. This parameter can be a value of @ref ADC_Resolution */ uint32_t DataAlign; /*!< Specifies whether the ADC data alignment is left or right. This parameter can be a value of @ref ADC_data_align */ uint32_t ScanConvMode; /*!< Specifies whether the conversion is performed in Scan (multi channels) or Single (one channel) mode. This parameter can be set to ENABLE or DISABLE */ uint32_t EOCSelection; /*!< Specifies whether the EOC flag is set at the end of single channel conversion or at the end of all conversions. This parameter can be a value of @ref ADC_EOCSelection Note: Impact on overrun when not using DMA: When EOCSelection is set to ADC_EOC_SINGLE_CONV, overrun detection is automatically enabled, in this case each conversion data must be read. To perform ADC conversions without having to read all conversion data, this parameter must be set to ADC_EOC_SEQ_CONV */ uint32_t ContinuousConvMode; /*!< Specifies whether the conversion is performed in Continuous or Single mode. This parameter can be set to ENABLE or DISABLE. */ uint32_t DMAContinuousRequests; /*!< Specifies whether the DMA requests is performed in Continuous or in Single mode. This parameter can be set to ENABLE or DISABLE. */ uint32_t NbrOfConversion; /*!< Specifies the number of ADC conversions that will be done using the sequencer for regular channel group. This parameter must be a number between Min_Data = 1 and Max_Data = 16. */ uint32_t DiscontinuousConvMode; /*!< Specifies whether the conversion is performed in Discontinuous or not for regular channels. This parameter can be set to ENABLE or DISABLE. */ uint32_t NbrOfDiscConversion; /*!< Specifies the number of ADC discontinuous conversions that will be done using the sequencer for regular channel group. This parameter must be a number between Min_Data = 1 and Max_Data = 8. */ uint32_t ExternalTrigConv; /*!< Selects the external event used to trigger the conversion start of regular group. If set to ADC_SOFTWARE_START, external triggers are disabled. This parameter can be a value of @ref ADC_External_trigger_Source_Regular Note: This parameter can be modified only if there is no conversion is ongoing. */ uint32_t ExternalTrigConvEdge; /*!< Selects the external trigger edge of regular group. If trigger is set to ADC_SOFTWARE_START, this parameter is discarded. This parameter can be a value of @ref ADC_External_trigger_edge_Regular Note: This parameter can be modified only if there is no conversion is ongoing. */ }ADC_InitTypeDef; /** * @brief ADC handle Structure definition */ typedef struct { ADC_TypeDef *Instance; /*!< Register base address */ ADC_InitTypeDef Init; /*!< ADC required parameters */ __IO uint32_t NbrOfCurrentConversionRank; /*!< ADC number of current conversion rank */ DMA_HandleTypeDef *DMA_Handle; /*!< Pointer DMA Handler */ HAL_LockTypeDef Lock; /*!< ADC locking object */ __IO HAL_ADC_StateTypeDef State; /*!< ADC communication state */ __IO uint32_t ErrorCode; /*!< ADC Error code */ }ADC_HandleTypeDef; /** * @brief ADC Configuration regular Channel structure definition */ typedef struct { uint32_t Channel; /*!< The ADC channel to configure. This parameter can be a value of @ref ADC_channels */ uint32_t Rank; /*!< The rank in the regular group sequencer. This parameter must be a number between Min_Data = 1 and Max_Data = 16 */ uint32_t SamplingTime; /*!< The sample time value to be set for the selected channel. This parameter can be a value of @ref ADC_sampling_times */ uint32_t Offset; /*!< Reserved for future use, can be set to 0 */ }ADC_ChannelConfTypeDef; /** * @brief ADC Configuration multi-mode structure definition */ typedef struct { uint32_t WatchdogMode; /*!< Configures the ADC analog watchdog mode. This parameter can be a value of @ref ADC_analog_watchdog_selection */ uint32_t HighThreshold; /*!< Configures the ADC analog watchdog High threshold value. This parameter must be a 12-bit value. */ uint32_t LowThreshold; /*!< Configures the ADC analog watchdog High threshold value. This parameter must be a 12-bit value. */ uint32_t Channel; /*!< Configures ADC channel for the analog watchdog. This parameter has an effect only if watchdog mode is configured on single channel This parameter can be a value of @ref ADC_channels */ uint32_t ITMode; /*!< Specifies whether the analog watchdog is configured is interrupt mode or in polling mode. This parameter can be set to ENABLE or DISABLE */ uint32_t WatchdogNumber; /*!< Reserved for future use, can be set to 0 */ }ADC_AnalogWDGConfTypeDef; /** * @} */ /* Exported constants --------------------------------------------------------*/ /** @defgroup ADC_Exported_Constants ADC Exported Constants * @{ */ /** @defgroup ADC_Error_Code ADC Error Code * @{ */ #define HAL_ADC_ERROR_NONE ((uint32_t)0x00) /*!< No error */ #define HAL_ADC_ERROR_OVR ((uint32_t)0x01) /*!< OVR error */ #define HAL_ADC_ERROR_DMA ((uint32_t)0x02) /*!< DMA transfer error */ /** * @} */ /** @defgroup ADC_ClockPrescaler ADC Clock Prescaler * @{ */ #define ADC_CLOCK_SYNC_PCLK_DIV2 ((uint32_t)0x00000000) #define ADC_CLOCK_SYNC_PCLK_DIV4 ((uint32_t)ADC_CCR_ADCPRE_0) #define ADC_CLOCK_SYNC_PCLK_DIV6 ((uint32_t)ADC_CCR_ADCPRE_1) #define ADC_CLOCK_SYNC_PCLK_DIV8 ((uint32_t)ADC_CCR_ADCPRE) /** * @} */ /** @defgroup ADC_delay_between_2_sampling_phases ADC Delay Between 2 Sampling Phases * @{ */ #define ADC_TWOSAMPLINGDELAY_5CYCLES ((uint32_t)0x00000000) #define ADC_TWOSAMPLINGDELAY_6CYCLES ((uint32_t)ADC_CCR_DELAY_0) #define ADC_TWOSAMPLINGDELAY_7CYCLES ((uint32_t)ADC_CCR_DELAY_1) #define ADC_TWOSAMPLINGDELAY_8CYCLES ((uint32_t)(ADC_CCR_DELAY_1 | ADC_CCR_DELAY_0)) #define ADC_TWOSAMPLINGDELAY_9CYCLES ((uint32_t)ADC_CCR_DELAY_2) #define ADC_TWOSAMPLINGDELAY_10CYCLES ((uint32_t)(ADC_CCR_DELAY_2 | ADC_CCR_DELAY_0)) #define ADC_TWOSAMPLINGDELAY_11CYCLES ((uint32_t)(ADC_CCR_DELAY_2 | ADC_CCR_DELAY_1)) #define ADC_TWOSAMPLINGDELAY_12CYCLES ((uint32_t)(ADC_CCR_DELAY_2 | ADC_CCR_DELAY_1 | ADC_CCR_DELAY_0)) #define ADC_TWOSAMPLINGDELAY_13CYCLES ((uint32_t)ADC_CCR_DELAY_3) #define ADC_TWOSAMPLINGDELAY_14CYCLES ((uint32_t)(ADC_CCR_DELAY_3 | ADC_CCR_DELAY_0)) #define ADC_TWOSAMPLINGDELAY_15CYCLES ((uint32_t)(ADC_CCR_DELAY_3 | ADC_CCR_DELAY_1)) #define ADC_TWOSAMPLINGDELAY_16CYCLES ((uint32_t)(ADC_CCR_DELAY_3 | ADC_CCR_DELAY_1 | ADC_CCR_DELAY_0)) #define ADC_TWOSAMPLINGDELAY_17CYCLES ((uint32_t)(ADC_CCR_DELAY_3 | ADC_CCR_DELAY_2)) #define ADC_TWOSAMPLINGDELAY_18CYCLES ((uint32_t)(ADC_CCR_DELAY_3 | ADC_CCR_DELAY_2 | ADC_CCR_DELAY_0)) #define ADC_TWOSAMPLINGDELAY_19CYCLES ((uint32_t)(ADC_CCR_DELAY_3 | ADC_CCR_DELAY_2 | ADC_CCR_DELAY_1)) #define ADC_TWOSAMPLINGDELAY_20CYCLES ((uint32_t)ADC_CCR_DELAY) /** * @} */ /** @defgroup ADC_Resolution ADC Resolution * @{ */ #define ADC_RESOLUTION_12B ((uint32_t)0x00000000) #define ADC_RESOLUTION_10B ((uint32_t)ADC_CR1_RES_0) #define ADC_RESOLUTION_8B ((uint32_t)ADC_CR1_RES_1) #define ADC_RESOLUTION_6B ((uint32_t)ADC_CR1_RES) /** * @} */ /** @defgroup ADC_External_trigger_edge_Regular ADC External Trigger Edge Regular * @{ */ #define ADC_EXTERNALTRIGCONVEDGE_NONE ((uint32_t)0x00000000) #define ADC_EXTERNALTRIGCONVEDGE_RISING ((uint32_t)ADC_CR2_EXTEN_0) #define ADC_EXTERNALTRIGCONVEDGE_FALLING ((uint32_t)ADC_CR2_EXTEN_1) #define ADC_EXTERNALTRIGCONVEDGE_RISINGFALLING ((uint32_t)ADC_CR2_EXTEN) /** * @} */ /** @defgroup ADC_External_trigger_Source_Regular ADC External Trigger Source Regular * @{ */ /* Note: Parameter ADC_SOFTWARE_START is a software parameter used for */ /* compatibility with other STM32 devices. */ #define ADC_EXTERNALTRIGCONV_T1_CC1 ((uint32_t)0x00000000) #define ADC_EXTERNALTRIGCONV_T1_CC2 ((uint32_t)ADC_CR2_EXTSEL_0) #define ADC_EXTERNALTRIGCONV_T1_CC3 ((uint32_t)ADC_CR2_EXTSEL_1) #define ADC_EXTERNALTRIGCONV_T2_CC2 ((uint32_t)(ADC_CR2_EXTSEL_1 | ADC_CR2_EXTSEL_0)) #define ADC_EXTERNALTRIGCONV_T2_CC3 ((uint32_t)ADC_CR2_EXTSEL_2) #define ADC_EXTERNALTRIGCONV_T2_CC4 ((uint32_t)(ADC_CR2_EXTSEL_2 | ADC_CR2_EXTSEL_0)) #define ADC_EXTERNALTRIGCONV_T2_TRGO ((uint32_t)(ADC_CR2_EXTSEL_2 | ADC_CR2_EXTSEL_1)) #define ADC_EXTERNALTRIGCONV_T3_CC1 ((uint32_t)(ADC_CR2_EXTSEL_2 | ADC_CR2_EXTSEL_1 | ADC_CR2_EXTSEL_0)) #define ADC_EXTERNALTRIGCONV_T3_TRGO ((uint32_t)ADC_CR2_EXTSEL_3) #define ADC_EXTERNALTRIGCONV_T4_CC4 ((uint32_t)(ADC_CR2_EXTSEL_3 | ADC_CR2_EXTSEL_0)) #define ADC_EXTERNALTRIGCONV_T5_CC1 ((uint32_t)(ADC_CR2_EXTSEL_3 | ADC_CR2_EXTSEL_1)) #define ADC_EXTERNALTRIGCONV_T5_CC2 ((uint32_t)(ADC_CR2_EXTSEL_3 | ADC_CR2_EXTSEL_1 | ADC_CR2_EXTSEL_0)) #define ADC_EXTERNALTRIGCONV_T5_CC3 ((uint32_t)(ADC_CR2_EXTSEL_3 | ADC_CR2_EXTSEL_2)) #define ADC_EXTERNALTRIGCONV_T8_CC1 ((uint32_t)(ADC_CR2_EXTSEL_3 | ADC_CR2_EXTSEL_2 | ADC_CR2_EXTSEL_0)) #define ADC_EXTERNALTRIGCONV_T8_TRGO ((uint32_t)(ADC_CR2_EXTSEL_3 | ADC_CR2_EXTSEL_2 | ADC_CR2_EXTSEL_1)) #define ADC_EXTERNALTRIGCONV_Ext_IT11 ((uint32_t)ADC_CR2_EXTSEL) #define ADC_SOFTWARE_START ((uint32_t)ADC_CR2_EXTSEL + 1) /** * @} */ /** @defgroup ADC_data_align ADC Data Align * @{ */ #define ADC_DATAALIGN_RIGHT ((uint32_t)0x00000000) #define ADC_DATAALIGN_LEFT ((uint32_t)ADC_CR2_ALIGN) /** * @} */ /** @defgroup ADC_channels ADC Common Channels * @{ */ #define ADC_CHANNEL_0 ((uint32_t)0x00000000) #define ADC_CHANNEL_1 ((uint32_t)ADC_CR1_AWDCH_0) #define ADC_CHANNEL_2 ((uint32_t)ADC_CR1_AWDCH_1) #define ADC_CHANNEL_3 ((uint32_t)(ADC_CR1_AWDCH_1 | ADC_CR1_AWDCH_0)) #define ADC_CHANNEL_4 ((uint32_t)ADC_CR1_AWDCH_2) #define ADC_CHANNEL_5 ((uint32_t)(ADC_CR1_AWDCH_2 | ADC_CR1_AWDCH_0)) #define ADC_CHANNEL_6 ((uint32_t)(ADC_CR1_AWDCH_2 | ADC_CR1_AWDCH_1)) #define ADC_CHANNEL_7 ((uint32_t)(ADC_CR1_AWDCH_2 | ADC_CR1_AWDCH_1 | ADC_CR1_AWDCH_0)) #define ADC_CHANNEL_8 ((uint32_t)ADC_CR1_AWDCH_3) #define ADC_CHANNEL_9 ((uint32_t)(ADC_CR1_AWDCH_3 | ADC_CR1_AWDCH_0)) #define ADC_CHANNEL_10 ((uint32_t)(ADC_CR1_AWDCH_3 | ADC_CR1_AWDCH_1)) #define ADC_CHANNEL_11 ((uint32_t)(ADC_CR1_AWDCH_3 | ADC_CR1_AWDCH_1 | ADC_CR1_AWDCH_0)) #define ADC_CHANNEL_12 ((uint32_t)(ADC_CR1_AWDCH_3 | ADC_CR1_AWDCH_2)) #define ADC_CHANNEL_13 ((uint32_t)(ADC_CR1_AWDCH_3 | ADC_CR1_AWDCH_2 | ADC_CR1_AWDCH_0)) #define ADC_CHANNEL_14 ((uint32_t)(ADC_CR1_AWDCH_3 | ADC_CR1_AWDCH_2 | ADC_CR1_AWDCH_1)) #define ADC_CHANNEL_15 ((uint32_t)(ADC_CR1_AWDCH_3 | ADC_CR1_AWDCH_2 | ADC_CR1_AWDCH_1 | ADC_CR1_AWDCH_0)) #define ADC_CHANNEL_16 ((uint32_t)ADC_CR1_AWDCH_4) #define ADC_CHANNEL_17 ((uint32_t)(ADC_CR1_AWDCH_4 | ADC_CR1_AWDCH_0)) #define ADC_CHANNEL_18 ((uint32_t)(ADC_CR1_AWDCH_4 | ADC_CR1_AWDCH_1)) #define ADC_CHANNEL_VREFINT ((uint32_t)ADC_CHANNEL_17) #define ADC_CHANNEL_VBAT ((uint32_t)ADC_CHANNEL_18) /** * @} */ /** @defgroup ADC_sampling_times ADC Sampling Times * @{ */ #define ADC_SAMPLETIME_3CYCLES ((uint32_t)0x00000000) #define ADC_SAMPLETIME_15CYCLES ((uint32_t)ADC_SMPR1_SMP10_0) #define ADC_SAMPLETIME_28CYCLES ((uint32_t)ADC_SMPR1_SMP10_1) #define ADC_SAMPLETIME_56CYCLES ((uint32_t)(ADC_SMPR1_SMP10_1 | ADC_SMPR1_SMP10_0)) #define ADC_SAMPLETIME_84CYCLES ((uint32_t)ADC_SMPR1_SMP10_2) #define ADC_SAMPLETIME_112CYCLES ((uint32_t)(ADC_SMPR1_SMP10_2 | ADC_SMPR1_SMP10_0)) #define ADC_SAMPLETIME_144CYCLES ((uint32_t)(ADC_SMPR1_SMP10_2 | ADC_SMPR1_SMP10_1)) #define ADC_SAMPLETIME_480CYCLES ((uint32_t)ADC_SMPR1_SMP10) /** * @} */ /** @defgroup ADC_EOCSelection ADC EOC Selection * @{ */ #define ADC_EOC_SEQ_CONV ((uint32_t)0x00000000) #define ADC_EOC_SINGLE_CONV ((uint32_t)0x00000001) #define ADC_EOC_SINGLE_SEQ_CONV ((uint32_t)0x00000002) /*!< reserved for future use */ /** * @} */ /** @defgroup ADC_Event_type ADC Event Type * @{ */ #define ADC_AWD_EVENT ((uint32_t)ADC_FLAG_AWD) #define ADC_OVR_EVENT ((uint32_t)ADC_FLAG_OVR) /** * @} */ /** @defgroup ADC_analog_watchdog_selection ADC Analog Watchdog Selection * @{ */ #define ADC_ANALOGWATCHDOG_SINGLE_REG ((uint32_t)(ADC_CR1_AWDSGL | ADC_CR1_AWDEN)) #define ADC_ANALOGWATCHDOG_SINGLE_INJEC ((uint32_t)(ADC_CR1_AWDSGL | ADC_CR1_JAWDEN)) #define ADC_ANALOGWATCHDOG_SINGLE_REGINJEC ((uint32_t)(ADC_CR1_AWDSGL | ADC_CR1_AWDEN | ADC_CR1_JAWDEN)) #define ADC_ANALOGWATCHDOG_ALL_REG ((uint32_t)ADC_CR1_AWDEN) #define ADC_ANALOGWATCHDOG_ALL_INJEC ((uint32_t)ADC_CR1_JAWDEN) #define ADC_ANALOGWATCHDOG_ALL_REGINJEC ((uint32_t)(ADC_CR1_AWDEN | ADC_CR1_JAWDEN)) #define ADC_ANALOGWATCHDOG_NONE ((uint32_t)0x00000000) /** * @} */ /** @defgroup ADC_interrupts_definition ADC Interrupts Definition * @{ */ #define ADC_IT_EOC ((uint32_t)ADC_CR1_EOCIE) #define ADC_IT_AWD ((uint32_t)ADC_CR1_AWDIE) #define ADC_IT_JEOC ((uint32_t)ADC_CR1_JEOCIE) #define ADC_IT_OVR ((uint32_t)ADC_CR1_OVRIE) /** * @} */ /** @defgroup ADC_flags_definition ADC Flags Definition * @{ */ #define ADC_FLAG_AWD ((uint32_t)ADC_SR_AWD) #define ADC_FLAG_EOC ((uint32_t)ADC_SR_EOC) #define ADC_FLAG_JEOC ((uint32_t)ADC_SR_JEOC) #define ADC_FLAG_JSTRT ((uint32_t)ADC_SR_JSTRT) #define ADC_FLAG_STRT ((uint32_t)ADC_SR_STRT) #define ADC_FLAG_OVR ((uint32_t)ADC_SR_OVR) /** * @} */ /** @defgroup ADC_channels_type ADC Channels Type * @{ */ #define ADC_ALL_CHANNELS ((uint32_t)0x00000001) #define ADC_REGULAR_CHANNELS ((uint32_t)0x00000002) /*!< reserved for future use */ #define ADC_INJECTED_CHANNELS ((uint32_t)0x00000003) /*!< reserved for future use */ /** * @} */ /** * @} */ /* Exported macro ------------------------------------------------------------*/ /** @defgroup ADC_Exported_Macros ADC Exported Macros * @{ */ /** @brief Reset ADC handle state * @param __HANDLE__: ADC handle * @retval None */ #define __HAL_ADC_RESET_HANDLE_STATE(__HANDLE__) ((__HANDLE__)->State = HAL_ADC_STATE_RESET) /** * @brief Enable the ADC peripheral. * @param __HANDLE__: ADC handle * @retval None */ #define __HAL_ADC_ENABLE(__HANDLE__) ((__HANDLE__)->Instance->CR2 |= ADC_CR2_ADON) /** * @brief Disable the ADC peripheral. * @param __HANDLE__: ADC handle * @retval None */ #define __HAL_ADC_DISABLE(__HANDLE__) ((__HANDLE__)->Instance->CR2 &= ~ADC_CR2_ADON) /** * @brief Enable the ADC end of conversion interrupt. * @param __HANDLE__: specifies the ADC Handle. * @param __INTERRUPT__: ADC Interrupt. * @retval None */ #define __HAL_ADC_ENABLE_IT(__HANDLE__, __INTERRUPT__) (((__HANDLE__)->Instance->CR1) |= (__INTERRUPT__)) /** * @brief Disable the ADC end of conversion interrupt. * @param __HANDLE__: specifies the ADC Handle. * @param __INTERRUPT__: ADC interrupt. * @retval None */ #define __HAL_ADC_DISABLE_IT(__HANDLE__, __INTERRUPT__) (((__HANDLE__)->Instance->CR1) &= ~(__INTERRUPT__)) /** @brief Check if the specified ADC interrupt source is enabled or disabled. * @param __HANDLE__: specifies the ADC Handle. * @param __INTERRUPT__: specifies the ADC interrupt source to check. * @retval The new state of __IT__ (TRUE or FALSE). */ #define __HAL_ADC_GET_IT_SOURCE(__HANDLE__, __INTERRUPT__) (((__HANDLE__)->Instance->CR1 & (__INTERRUPT__)) == (__INTERRUPT__)) /** * @brief Clear the ADC's pending flags. * @param __HANDLE__: specifies the ADC Handle. * @param __FLAG__: ADC flag. * @retval None */ #define __HAL_ADC_CLEAR_FLAG(__HANDLE__, __FLAG__) (((__HANDLE__)->Instance->SR) = ~(__FLAG__)) /** * @brief Get the selected ADC's flag status. * @param __HANDLE__: specifies the ADC Handle. * @param __FLAG__: ADC flag. * @retval None */ #define __HAL_ADC_GET_FLAG(__HANDLE__, __FLAG__) ((((__HANDLE__)->Instance->SR) & (__FLAG__)) == (__FLAG__)) /** * @} */ /* Include ADC HAL Extension module */ #include "stm32f4xx_hal_adc_ex.h" /* Exported functions --------------------------------------------------------*/ /** @addtogroup ADC_Exported_Functions * @{ */ /** @addtogroup ADC_Exported_Functions_Group1 * @{ */ /* Initialization/de-initialization functions ***********************************/ HAL_StatusTypeDef HAL_ADC_Init(ADC_HandleTypeDef* hadc); HAL_StatusTypeDef HAL_ADC_DeInit(ADC_HandleTypeDef *hadc); void HAL_ADC_MspInit(ADC_HandleTypeDef* hadc); void HAL_ADC_MspDeInit(ADC_HandleTypeDef* hadc); /** * @} */ /** @addtogroup ADC_Exported_Functions_Group2 * @{ */ /* I/O operation functions ******************************************************/ HAL_StatusTypeDef HAL_ADC_Start(ADC_HandleTypeDef* hadc); HAL_StatusTypeDef HAL_ADC_Stop(ADC_HandleTypeDef* hadc); HAL_StatusTypeDef HAL_ADC_PollForConversion(ADC_HandleTypeDef* hadc, uint32_t Timeout); HAL_StatusTypeDef HAL_ADC_PollForEvent(ADC_HandleTypeDef* hadc, uint32_t EventType, uint32_t Timeout); HAL_StatusTypeDef HAL_ADC_Start_IT(ADC_HandleTypeDef* hadc); HAL_StatusTypeDef HAL_ADC_Stop_IT(ADC_HandleTypeDef* hadc); void HAL_ADC_IRQHandler(ADC_HandleTypeDef* hadc); HAL_StatusTypeDef HAL_ADC_Start_DMA(ADC_HandleTypeDef* hadc, uint32_t* pData, uint32_t Length); HAL_StatusTypeDef HAL_ADC_Stop_DMA(ADC_HandleTypeDef* hadc); uint32_t HAL_ADC_GetValue(ADC_HandleTypeDef* hadc); void HAL_ADC_ConvCpltCallback(ADC_HandleTypeDef* hadc); void HAL_ADC_ConvHalfCpltCallback(ADC_HandleTypeDef* hadc); void HAL_ADC_LevelOutOfWindowCallback(ADC_HandleTypeDef* hadc); void HAL_ADC_ErrorCallback(ADC_HandleTypeDef *hadc); /** * @} */ /** @addtogroup ADC_Exported_Functions_Group3 * @{ */ /* Peripheral Control functions *************************************************/ HAL_StatusTypeDef HAL_ADC_ConfigChannel(ADC_HandleTypeDef* hadc, ADC_ChannelConfTypeDef* sConfig); HAL_StatusTypeDef HAL_ADC_AnalogWDGConfig(ADC_HandleTypeDef* hadc, ADC_AnalogWDGConfTypeDef* AnalogWDGConfig); /** * @} */ /** @addtogroup ADC_Exported_Functions_Group4 * @{ */ /* Peripheral State functions ***************************************************/ HAL_ADC_StateTypeDef HAL_ADC_GetState(ADC_HandleTypeDef* hadc); uint32_t HAL_ADC_GetError(ADC_HandleTypeDef *hadc); /** * @} */ /** * @} */ /* Private types -------------------------------------------------------------*/ /* Private variables ---------------------------------------------------------*/ /* Private constants ---------------------------------------------------------*/ /** @defgroup ADC_Private_Constants ADC Private Constants * @{ */ /* Delay for ADC stabilization time. */ /* Maximum delay is 1us (refer to device datasheet, parameter tSTAB). */ /* Unit: us */ #define ADC_STAB_DELAY_US ((uint32_t) 3) /* Delay for temperature sensor stabilization time. */ /* Maximum delay is 10us (refer to device datasheet, parameter tSTART). */ /* Unit: us */ #define ADC_TEMPSENSOR_DELAY_US ((uint32_t) 10) /** * @} */ /* Private macros ------------------------------------------------------------*/ /** @defgroup ADC_Private_Macros ADC Private Macros * @{ */ #define IS_ADC_CLOCKPRESCALER(ADC_CLOCK) (((ADC_CLOCK) == ADC_CLOCK_SYNC_PCLK_DIV2) || \ ((ADC_CLOCK) == ADC_CLOCK_SYNC_PCLK_DIV4) || \ ((ADC_CLOCK) == ADC_CLOCK_SYNC_PCLK_DIV6) || \ ((ADC_CLOCK) == ADC_CLOCK_SYNC_PCLK_DIV8)) #define IS_ADC_SAMPLING_DELAY(DELAY) (((DELAY) == ADC_TWOSAMPLINGDELAY_5CYCLES) || \ ((DELAY) == ADC_TWOSAMPLINGDELAY_6CYCLES) || \ ((DELAY) == ADC_TWOSAMPLINGDELAY_7CYCLES) || \ ((DELAY) == ADC_TWOSAMPLINGDELAY_8CYCLES) || \ ((DELAY) == ADC_TWOSAMPLINGDELAY_9CYCLES) || \ ((DELAY) == ADC_TWOSAMPLINGDELAY_10CYCLES) || \ ((DELAY) == ADC_TWOSAMPLINGDELAY_11CYCLES) || \ ((DELAY) == ADC_TWOSAMPLINGDELAY_12CYCLES) || \ ((DELAY) == ADC_TWOSAMPLINGDELAY_13CYCLES) || \ ((DELAY) == ADC_TWOSAMPLINGDELAY_14CYCLES) || \ ((DELAY) == ADC_TWOSAMPLINGDELAY_15CYCLES) || \ ((DELAY) == ADC_TWOSAMPLINGDELAY_16CYCLES) || \ ((DELAY) == ADC_TWOSAMPLINGDELAY_17CYCLES) || \ ((DELAY) == ADC_TWOSAMPLINGDELAY_18CYCLES) || \ ((DELAY) == ADC_TWOSAMPLINGDELAY_19CYCLES) || \ ((DELAY) == ADC_TWOSAMPLINGDELAY_20CYCLES)) #define IS_ADC_RESOLUTION(RESOLUTION) (((RESOLUTION) == ADC_RESOLUTION_12B) || \ ((RESOLUTION) == ADC_RESOLUTION_10B) || \ ((RESOLUTION) == ADC_RESOLUTION_8B) || \ ((RESOLUTION) == ADC_RESOLUTION_6B)) #define IS_ADC_EXT_TRIG_EDGE(EDGE) (((EDGE) == ADC_EXTERNALTRIGCONVEDGE_NONE) || \ ((EDGE) == ADC_EXTERNALTRIGCONVEDGE_RISING) || \ ((EDGE) == ADC_EXTERNALTRIGCONVEDGE_FALLING) || \ ((EDGE) == ADC_EXTERNALTRIGCONVEDGE_RISINGFALLING)) #define IS_ADC_EXT_TRIG(REGTRIG) (((REGTRIG) == ADC_EXTERNALTRIGCONV_T1_CC1) || \ ((REGTRIG) == ADC_EXTERNALTRIGCONV_T1_CC2) || \ ((REGTRIG) == ADC_EXTERNALTRIGCONV_T1_CC3) || \ ((REGTRIG) == ADC_EXTERNALTRIGCONV_T2_CC2) || \ ((REGTRIG) == ADC_EXTERNALTRIGCONV_T2_CC3) || \ ((REGTRIG) == ADC_EXTERNALTRIGCONV_T2_CC4) || \ ((REGTRIG) == ADC_EXTERNALTRIGCONV_T2_TRGO) || \ ((REGTRIG) == ADC_EXTERNALTRIGCONV_T3_CC1) || \ ((REGTRIG) == ADC_EXTERNALTRIGCONV_T3_TRGO) || \ ((REGTRIG) == ADC_EXTERNALTRIGCONV_T4_CC4) || \ ((REGTRIG) == ADC_EXTERNALTRIGCONV_T5_CC1) || \ ((REGTRIG) == ADC_EXTERNALTRIGCONV_T5_CC2) || \ ((REGTRIG) == ADC_EXTERNALTRIGCONV_T5_CC3) || \ ((REGTRIG) == ADC_EXTERNALTRIGCONV_T8_CC1) || \ ((REGTRIG) == ADC_EXTERNALTRIGCONV_T8_TRGO) || \ ((REGTRIG) == ADC_EXTERNALTRIGCONV_Ext_IT11)|| \ ((REGTRIG) == ADC_SOFTWARE_START)) #define IS_ADC_DATA_ALIGN(ALIGN) (((ALIGN) == ADC_DATAALIGN_RIGHT) || \ ((ALIGN) == ADC_DATAALIGN_LEFT)) #define IS_ADC_SAMPLE_TIME(TIME) (((TIME) == ADC_SAMPLETIME_3CYCLES) || \ ((TIME) == ADC_SAMPLETIME_15CYCLES) || \ ((TIME) == ADC_SAMPLETIME_28CYCLES) || \ ((TIME) == ADC_SAMPLETIME_56CYCLES) || \ ((TIME) == ADC_SAMPLETIME_84CYCLES) || \ ((TIME) == ADC_SAMPLETIME_112CYCLES) || \ ((TIME) == ADC_SAMPLETIME_144CYCLES) || \ ((TIME) == ADC_SAMPLETIME_480CYCLES)) #define IS_ADC_EOCSelection(EOCSelection) (((EOCSelection) == ADC_EOC_SINGLE_CONV) || \ ((EOCSelection) == ADC_EOC_SEQ_CONV) || \ ((EOCSelection) == ADC_EOC_SINGLE_SEQ_CONV)) #define IS_ADC_EVENT_TYPE(EVENT) (((EVENT) == ADC_AWD_EVENT) || \ ((EVENT) == ADC_OVR_EVENT)) #define IS_ADC_ANALOG_WATCHDOG(WATCHDOG) (((WATCHDOG) == ADC_ANALOGWATCHDOG_SINGLE_REG) || \ ((WATCHDOG) == ADC_ANALOGWATCHDOG_SINGLE_INJEC) || \ ((WATCHDOG) == ADC_ANALOGWATCHDOG_SINGLE_REGINJEC) || \ ((WATCHDOG) == ADC_ANALOGWATCHDOG_ALL_REG) || \ ((WATCHDOG) == ADC_ANALOGWATCHDOG_ALL_INJEC) || \ ((WATCHDOG) == ADC_ANALOGWATCHDOG_ALL_REGINJEC) || \ ((WATCHDOG) == ADC_ANALOGWATCHDOG_NONE)) #define IS_ADC_CHANNELS_TYPE(CHANNEL_TYPE) (((CHANNEL_TYPE) == ADC_ALL_CHANNELS) || \ ((CHANNEL_TYPE) == ADC_REGULAR_CHANNELS) || \ ((CHANNEL_TYPE) == ADC_INJECTED_CHANNELS)) #define IS_ADC_THRESHOLD(THRESHOLD) ((THRESHOLD) <= ((uint32_t)0xFFF)) #define IS_ADC_REGULAR_LENGTH(LENGTH) (((LENGTH) >= ((uint32_t)1)) && ((LENGTH) <= ((uint32_t)16))) #define IS_ADC_REGULAR_RANK(RANK) (((RANK) >= ((uint32_t)1)) && ((RANK) <= ((uint32_t)16))) #define IS_ADC_REGULAR_DISC_NUMBER(NUMBER) (((NUMBER) >= ((uint32_t)1)) && ((NUMBER) <= ((uint32_t)8))) #define IS_ADC_RANGE(RESOLUTION, ADC_VALUE) \ ((((RESOLUTION) == ADC_RESOLUTION_12B) && ((ADC_VALUE) <= ((uint32_t)0x0FFF))) || \ (((RESOLUTION) == ADC_RESOLUTION_10B) && ((ADC_VALUE) <= ((uint32_t)0x03FF))) || \ (((RESOLUTION) == ADC_RESOLUTION_8B) && ((ADC_VALUE) <= ((uint32_t)0x00FF))) || \ (((RESOLUTION) == ADC_RESOLUTION_6B) && ((ADC_VALUE) <= ((uint32_t)0x003F)))) /** * @brief Set ADC Regular channel sequence length. * @param _NbrOfConversion_: Regular channel sequence length. * @retval None */ #define ADC_SQR1(_NbrOfConversion_) (((_NbrOfConversion_) - (uint8_t)1) << 20) /** * @brief Set the ADC's sample time for channel numbers between 10 and 18. * @param _SAMPLETIME_: Sample time parameter. * @param _CHANNELNB_: Channel number. * @retval None */ #define ADC_SMPR1(_SAMPLETIME_, _CHANNELNB_) ((_SAMPLETIME_) << (3 * (((uint32_t)((uint16_t)(_CHANNELNB_))) - 10))) /** * @brief Set the ADC's sample time for channel numbers between 0 and 9. * @param _SAMPLETIME_: Sample time parameter. * @param _CHANNELNB_: Channel number. * @retval None */ #define ADC_SMPR2(_SAMPLETIME_, _CHANNELNB_) ((_SAMPLETIME_) << (3 * ((uint32_t)((uint16_t)(_CHANNELNB_))))) /** * @brief Set the selected regular channel rank for rank between 1 and 6. * @param _CHANNELNB_: Channel number. * @param _RANKNB_: Rank number. * @retval None */ #define ADC_SQR3_RK(_CHANNELNB_, _RANKNB_) (((uint32_t)((uint16_t)(_CHANNELNB_))) << (5 * ((_RANKNB_) - 1))) /** * @brief Set the selected regular channel rank for rank between 7 and 12. * @param _CHANNELNB_: Channel number. * @param _RANKNB_: Rank number. * @retval None */ #define ADC_SQR2_RK(_CHANNELNB_, _RANKNB_) (((uint32_t)((uint16_t)(_CHANNELNB_))) << (5 * ((_RANKNB_) - 7))) /** * @brief Set the selected regular channel rank for rank between 13 and 16. * @param _CHANNELNB_: Channel number. * @param _RANKNB_: Rank number. * @retval None */ #define ADC_SQR1_RK(_CHANNELNB_, _RANKNB_) (((uint32_t)((uint16_t)(_CHANNELNB_))) << (5 * ((_RANKNB_) - 13))) /** * @brief Enable ADC continuous conversion mode. * @param _CONTINUOUS_MODE_: Continuous mode. * @retval None */ #define ADC_CR2_CONTINUOUS(_CONTINUOUS_MODE_) ((_CONTINUOUS_MODE_) << 1) /** * @brief Configures the number of discontinuous conversions for the regular group channels. * @param _NBR_DISCONTINUOUSCONV_: Number of discontinuous conversions. * @retval None */ #define ADC_CR1_DISCONTINUOUS(_NBR_DISCONTINUOUSCONV_) (((_NBR_DISCONTINUOUSCONV_) - 1) << POSITION_VAL(ADC_CR1_DISCNUM)) /** * @brief Enable ADC scan mode. * @param _SCANCONV_MODE_: Scan conversion mode. * @retval None */ #define ADC_CR1_SCANCONV(_SCANCONV_MODE_) ((_SCANCONV_MODE_) << 8) /** * @brief Enable the ADC end of conversion selection. * @param _EOCSelection_MODE_: End of conversion selection mode. * @retval None */ #define ADC_CR2_EOCSelection(_EOCSelection_MODE_) ((_EOCSelection_MODE_) << 10) /** * @brief Enable the ADC DMA continuous request. * @param _DMAContReq_MODE_: DMA continuous request mode. * @retval None */ #define ADC_CR2_DMAContReq(_DMAContReq_MODE_) ((_DMAContReq_MODE_) << 9) /** * @brief Return resolution bits in CR1 register. * @param __HANDLE__: ADC handle * @retval None */ #define ADC_GET_RESOLUTION(__HANDLE__) (((__HANDLE__)->Instance->CR1) & ADC_CR1_RES) /** * @} */ /* Private functions ---------------------------------------------------------*/ /** @defgroup ADC_Private_Functions ADC Private Functions * @{ */ /** * @} */ /** * @} */ /** * @} */ #ifdef __cplusplus } #endif #endif /*__STM32F4xx_ADC_H */ /************************ (C) COPYRIGHT STMicroelectronics *****END OF FILE****/ ================================================ FILE: Zelig/mbed/TARGET_NUCLEO_F411RE/stm32f4xx_hal_adc_ex.h ================================================ /** ****************************************************************************** * @file stm32f4xx_hal_adc_ex.h * @author MCD Application Team * @version V1.4.1 * @date 09-October-2015 * @brief Header file of ADC HAL module. ****************************************************************************** * @attention * *

© COPYRIGHT(c) 2015 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. * ****************************************************************************** */ /* Define to prevent recursive inclusion -------------------------------------*/ #ifndef __STM32F4xx_ADC_EX_H #define __STM32F4xx_ADC_EX_H #ifdef __cplusplus extern "C" { #endif /* Includes ------------------------------------------------------------------*/ #include "stm32f4xx_hal_def.h" /** @addtogroup STM32F4xx_HAL_Driver * @{ */ /** @addtogroup ADCEx * @{ */ /* Exported types ------------------------------------------------------------*/ /** @defgroup ADCEx_Exported_Types ADC Exported Types * @{ */ /** * @brief ADC Configuration injected Channel structure definition */ typedef struct { uint32_t InjectedChannel; /*!< Configure the ADC injected channel. This parameter can be a value of @ref ADC_channels */ uint32_t InjectedRank; /*!< The rank in the injected group sequencer This parameter must be a number between Min_Data = 1 and Max_Data = 4. */ uint32_t InjectedSamplingTime; /*!< The sample time value to be set for the selected channel. This parameter can be a value of @ref ADC_sampling_times */ uint32_t InjectedOffset; /*!< Defines the offset to be subtracted from the raw converted data when convert injected channels. This parameter must be a number between Min_Data = 0x000 and Max_Data = 0xFFF. */ uint32_t InjectedNbrOfConversion; /*!< Specifies the number of ADC conversions that will be done using the sequencer for injected channel group. This parameter must be a number between Min_Data = 1 and Max_Data = 4. */ uint32_t AutoInjectedConv; /*!< Enables or disables the selected ADC automatic injected group conversion after regular one */ uint32_t InjectedDiscontinuousConvMode; /*!< Specifies whether the conversion is performed in Discontinuous mode or not for injected channels. This parameter can be set to ENABLE or DISABLE. */ uint32_t ExternalTrigInjecConvEdge; /*!< Select the external trigger edge and enable the trigger of an injected channels. This parameter can be a value of @ref ADCEx_External_trigger_edge_Injected */ uint32_t ExternalTrigInjecConv; /*!< Select the external event used to trigger the start of conversion of a injected channels. This parameter can be a value of @ref ADCEx_External_trigger_Source_Injected */ }ADC_InjectionConfTypeDef; /** * @brief ADC Configuration multi-mode structure definition */ typedef struct { uint32_t Mode; /*!< Configures the ADC to operate in independent or multi mode. This parameter can be a value of @ref ADCEx_Common_mode */ uint32_t DMAAccessMode; /*!< Configures the Direct memory access mode for multi ADC mode. This parameter can be a value of @ref ADCEx_Direct_memory_access_mode_for_multi_mode */ uint32_t TwoSamplingDelay; /*!< Configures the Delay between 2 sampling phases. This parameter can be a value of @ref ADC_delay_between_2_sampling_phases */ }ADC_MultiModeTypeDef; /** * @} */ /* Exported constants --------------------------------------------------------*/ /** @defgroup ADCEx_Exported_Constants ADC Exported Constants * @{ */ /** @defgroup ADCEx_Common_mode ADC Common Mode * @{ */ #define ADC_MODE_INDEPENDENT ((uint32_t)0x00000000) #define ADC_DUALMODE_REGSIMULT_INJECSIMULT ((uint32_t)ADC_CCR_MULTI_0) #define ADC_DUALMODE_REGSIMULT_ALTERTRIG ((uint32_t)ADC_CCR_MULTI_1) #define ADC_DUALMODE_INJECSIMULT ((uint32_t)(ADC_CCR_MULTI_2 | ADC_CCR_MULTI_0)) #define ADC_DUALMODE_REGSIMULT ((uint32_t)(ADC_CCR_MULTI_2 | ADC_CCR_MULTI_1)) #define ADC_DUALMODE_INTERL ((uint32_t)(ADC_CCR_MULTI_2 | ADC_CCR_MULTI_1 | ADC_CCR_MULTI_0)) #define ADC_DUALMODE_ALTERTRIG ((uint32_t)(ADC_CCR_MULTI_3 | ADC_CCR_MULTI_0)) #define ADC_TRIPLEMODE_REGSIMULT_INJECSIMULT ((uint32_t)(ADC_CCR_MULTI_4 | ADC_CCR_MULTI_0)) #define ADC_TRIPLEMODE_REGSIMULT_AlterTrig ((uint32_t)(ADC_CCR_MULTI_4 | ADC_CCR_MULTI_1)) #define ADC_TRIPLEMODE_INJECSIMULT ((uint32_t)(ADC_CCR_MULTI_4 | ADC_CCR_MULTI_2 | ADC_CCR_MULTI_0)) #define ADC_TRIPLEMODE_REGSIMULT ((uint32_t)(ADC_CCR_MULTI_4 | ADC_CCR_MULTI_2 | ADC_CCR_MULTI_1)) #define ADC_TRIPLEMODE_INTERL ((uint32_t)(ADC_CCR_MULTI_4 | ADC_CCR_MULTI_2 | ADC_CCR_MULTI_1 | ADC_CCR_MULTI_0)) #define ADC_TRIPLEMODE_ALTERTRIG ((uint32_t)(ADC_CCR_MULTI_4 | ADC_CCR_MULTI_3 | ADC_CCR_MULTI_0)) /** * @} */ /** @defgroup ADCEx_Direct_memory_access_mode_for_multi_mode ADC Direct Memory Access Mode For Multi Mode * @{ */ #define ADC_DMAACCESSMODE_DISABLED ((uint32_t)0x00000000) /*!< DMA mode disabled */ #define ADC_DMAACCESSMODE_1 ((uint32_t)ADC_CCR_DMA_0) /*!< DMA mode 1 enabled (2 / 3 half-words one by one - 1 then 2 then 3)*/ #define ADC_DMAACCESSMODE_2 ((uint32_t)ADC_CCR_DMA_1) /*!< DMA mode 2 enabled (2 / 3 half-words by pairs - 2&1 then 1&3 then 3&2)*/ #define ADC_DMAACCESSMODE_3 ((uint32_t)ADC_CCR_DMA) /*!< DMA mode 3 enabled (2 / 3 bytes by pairs - 2&1 then 1&3 then 3&2) */ /** * @} */ /** @defgroup ADCEx_External_trigger_edge_Injected ADC External Trigger Edge Injected * @{ */ #define ADC_EXTERNALTRIGINJECCONVEDGE_NONE ((uint32_t)0x00000000) #define ADC_EXTERNALTRIGINJECCONVEDGE_RISING ((uint32_t)ADC_CR2_JEXTEN_0) #define ADC_EXTERNALTRIGINJECCONVEDGE_FALLING ((uint32_t)ADC_CR2_JEXTEN_1) #define ADC_EXTERNALTRIGINJECCONVEDGE_RISINGFALLING ((uint32_t)ADC_CR2_JEXTEN) /** * @} */ /** @defgroup ADCEx_External_trigger_Source_Injected ADC External Trigger Source Injected * @{ */ #define ADC_EXTERNALTRIGINJECCONV_T1_CC4 ((uint32_t)0x00000000) #define ADC_EXTERNALTRIGINJECCONV_T1_TRGO ((uint32_t)ADC_CR2_JEXTSEL_0) #define ADC_EXTERNALTRIGINJECCONV_T2_CC1 ((uint32_t)ADC_CR2_JEXTSEL_1) #define ADC_EXTERNALTRIGINJECCONV_T2_TRGO ((uint32_t)(ADC_CR2_JEXTSEL_1 | ADC_CR2_JEXTSEL_0)) #define ADC_EXTERNALTRIGINJECCONV_T3_CC2 ((uint32_t)ADC_CR2_JEXTSEL_2) #define ADC_EXTERNALTRIGINJECCONV_T3_CC4 ((uint32_t)(ADC_CR2_JEXTSEL_2 | ADC_CR2_JEXTSEL_0)) #define ADC_EXTERNALTRIGINJECCONV_T4_CC1 ((uint32_t)(ADC_CR2_JEXTSEL_2 | ADC_CR2_JEXTSEL_1)) #define ADC_EXTERNALTRIGINJECCONV_T4_CC2 ((uint32_t)(ADC_CR2_JEXTSEL_2 | ADC_CR2_JEXTSEL_1 | ADC_CR2_JEXTSEL_0)) #define ADC_EXTERNALTRIGINJECCONV_T4_CC3 ((uint32_t)ADC_CR2_JEXTSEL_3) #define ADC_EXTERNALTRIGINJECCONV_T4_TRGO ((uint32_t)(ADC_CR2_JEXTSEL_3 | ADC_CR2_JEXTSEL_0)) #define ADC_EXTERNALTRIGINJECCONV_T5_CC4 ((uint32_t)(ADC_CR2_JEXTSEL_3 | ADC_CR2_JEXTSEL_1)) #define ADC_EXTERNALTRIGINJECCONV_T5_TRGO ((uint32_t)(ADC_CR2_JEXTSEL_3 | ADC_CR2_JEXTSEL_1 | ADC_CR2_JEXTSEL_0)) #define ADC_EXTERNALTRIGINJECCONV_T8_CC2 ((uint32_t)(ADC_CR2_JEXTSEL_3 | ADC_CR2_JEXTSEL_2)) #define ADC_EXTERNALTRIGINJECCONV_T8_CC3 ((uint32_t)(ADC_CR2_JEXTSEL_3 | ADC_CR2_JEXTSEL_2 | ADC_CR2_JEXTSEL_0)) #define ADC_EXTERNALTRIGINJECCONV_T8_CC4 ((uint32_t)(ADC_CR2_JEXTSEL_3 | ADC_CR2_JEXTSEL_2 | ADC_CR2_JEXTSEL_1)) #define ADC_EXTERNALTRIGINJECCONV_EXT_IT15 ((uint32_t)ADC_CR2_JEXTSEL) #define ADC_INJECTED_SOFTWARE_START ((uint32_t)ADC_CR2_JEXTSEL + 1) /** * @} */ /** @defgroup ADCEx_injected_channel_selection ADC Injected Channel Selection * @{ */ #define ADC_INJECTED_RANK_1 ((uint32_t)0x00000001) #define ADC_INJECTED_RANK_2 ((uint32_t)0x00000002) #define ADC_INJECTED_RANK_3 ((uint32_t)0x00000003) #define ADC_INJECTED_RANK_4 ((uint32_t)0x00000004) /** * @} */ /** @defgroup ADCEx_channels ADC Specific Channels * @{ */ #if defined(STM32F405xx) || defined(STM32F415xx) || defined(STM32F407xx) || defined(STM32F417xx) || \ defined(STM32F401xC) || defined(STM32F401xE) || defined(STM32F410Tx) || defined(STM32F410Cx) || \ defined(STM32F410Rx) || defined(STM32F412xG) #define ADC_CHANNEL_TEMPSENSOR ((uint32_t)ADC_CHANNEL_16) #endif /* STM32F405xx || STM32F415xx || STM32F407xx || STM32F417xx || STM32F401xC || STM32F401xE || STM32F410xx || STM32F412xG */ #if defined(STM32F411xE) || defined(STM32F427xx) || defined(STM32F437xx) || defined(STM32F429xx) || defined(STM32F439xx) || \ defined(STM32F446xx) || defined(STM32F469xx) || defined(STM32F479xx) #define ADC_CHANNEL_DIFFERENCIATION_TEMPSENSOR_VBAT ((uint32_t)0x10000000) /* Dummy bit for driver internal usage, not used in ADC channel setting registers CR1 or SQRx */ #define ADC_CHANNEL_TEMPSENSOR ((uint32_t)ADC_CHANNEL_18 | ADC_CHANNEL_DIFFERENCIATION_TEMPSENSOR_VBAT) #endif /* STM32F411xE || STM32F427xx || STM32F437xx || STM32F429xx || STM32F439xx || STM32F446xx || STM32F469xx || STM32F479xx */ /** * @} */ /** * @} */ /* Exported macro ------------------------------------------------------------*/ /** @defgroup ADC_Exported_Macros ADC Exported Macros * @{ */ /** * @} */ /* Exported functions --------------------------------------------------------*/ /** @addtogroup ADCEx_Exported_Functions * @{ */ /** @addtogroup ADCEx_Exported_Functions_Group1 * @{ */ /* I/O operation functions ******************************************************/ HAL_StatusTypeDef HAL_ADCEx_InjectedStart(ADC_HandleTypeDef* hadc); HAL_StatusTypeDef HAL_ADCEx_InjectedStop(ADC_HandleTypeDef* hadc); HAL_StatusTypeDef HAL_ADCEx_InjectedPollForConversion(ADC_HandleTypeDef* hadc, uint32_t Timeout); HAL_StatusTypeDef HAL_ADCEx_InjectedStart_IT(ADC_HandleTypeDef* hadc); HAL_StatusTypeDef HAL_ADCEx_InjectedStop_IT(ADC_HandleTypeDef* hadc); uint32_t HAL_ADCEx_InjectedGetValue(ADC_HandleTypeDef* hadc, uint32_t InjectedRank); HAL_StatusTypeDef HAL_ADCEx_MultiModeStart_DMA(ADC_HandleTypeDef* hadc, uint32_t* pData, uint32_t Length); HAL_StatusTypeDef HAL_ADCEx_MultiModeStop_DMA(ADC_HandleTypeDef* hadc); uint32_t HAL_ADCEx_MultiModeGetValue(ADC_HandleTypeDef* hadc); void HAL_ADCEx_InjectedConvCpltCallback(ADC_HandleTypeDef* hadc); /* Peripheral Control functions *************************************************/ HAL_StatusTypeDef HAL_ADCEx_InjectedConfigChannel(ADC_HandleTypeDef* hadc,ADC_InjectionConfTypeDef* sConfigInjected); HAL_StatusTypeDef HAL_ADCEx_MultiModeConfigChannel(ADC_HandleTypeDef* hadc, ADC_MultiModeTypeDef* multimode); /** * @} */ /** * @} */ /* Private types -------------------------------------------------------------*/ /* Private variables ---------------------------------------------------------*/ /* Private constants ---------------------------------------------------------*/ /** @defgroup ADCEx_Private_Constants ADC Private Constants * @{ */ /** * @} */ /* Private macros ------------------------------------------------------------*/ /** @defgroup ADCEx_Private_Macros ADC Private Macros * @{ */ #if defined(STM32F405xx) || defined(STM32F415xx) || defined(STM32F407xx) || defined(STM32F417xx) || \ defined(STM32F401xC) || defined(STM32F401xE) || defined(STM32F410Tx) || defined(STM32F410Cx) || \ defined(STM32F410Rx) || defined(STM32F411xE) || defined(STM32F412xG) #define IS_ADC_CHANNEL(CHANNEL) ((CHANNEL) <= ADC_CHANNEL_18) #endif /* STM32F405xx || STM32F415xx || STM32F407xx || STM32F417xx || STM32F401xC || STM32F401xE || STM32F410xx || STM32F411xE || STM32F412xG */ #if defined(STM32F427xx) || defined(STM32F437xx) || defined(STM32F429xx) || defined(STM32F439xx) || \ defined(STM32F446xx) || defined(STM32F469xx) || defined(STM32F479xx) #define IS_ADC_CHANNEL(CHANNEL) (((CHANNEL) <= ADC_CHANNEL_18) || \ ((CHANNEL) == ADC_CHANNEL_TEMPSENSOR)) #endif /* STM32F427xx || STM32F437xx || STM32F429xx || STM32F439xx || STM32F446xx || STM32F469xx || STM32F479xx */ #define IS_ADC_MODE(MODE) (((MODE) == ADC_MODE_INDEPENDENT) || \ ((MODE) == ADC_DUALMODE_REGSIMULT_INJECSIMULT) || \ ((MODE) == ADC_DUALMODE_REGSIMULT_ALTERTRIG) || \ ((MODE) == ADC_DUALMODE_INJECSIMULT) || \ ((MODE) == ADC_DUALMODE_REGSIMULT) || \ ((MODE) == ADC_DUALMODE_INTERL) || \ ((MODE) == ADC_DUALMODE_ALTERTRIG) || \ ((MODE) == ADC_TRIPLEMODE_REGSIMULT_INJECSIMULT) || \ ((MODE) == ADC_TRIPLEMODE_REGSIMULT_AlterTrig) || \ ((MODE) == ADC_TRIPLEMODE_INJECSIMULT) || \ ((MODE) == ADC_TRIPLEMODE_REGSIMULT) || \ ((MODE) == ADC_TRIPLEMODE_INTERL) || \ ((MODE) == ADC_TRIPLEMODE_ALTERTRIG)) #define IS_ADC_DMA_ACCESS_MODE(MODE) (((MODE) == ADC_DMAACCESSMODE_DISABLED) || \ ((MODE) == ADC_DMAACCESSMODE_1) || \ ((MODE) == ADC_DMAACCESSMODE_2) || \ ((MODE) == ADC_DMAACCESSMODE_3)) #define IS_ADC_EXT_INJEC_TRIG_EDGE(EDGE) (((EDGE) == ADC_EXTERNALTRIGINJECCONVEDGE_NONE) || \ ((EDGE) == ADC_EXTERNALTRIGINJECCONVEDGE_RISING) || \ ((EDGE) == ADC_EXTERNALTRIGINJECCONVEDGE_FALLING) || \ ((EDGE) == ADC_EXTERNALTRIGINJECCONVEDGE_RISINGFALLING)) #define IS_ADC_EXT_INJEC_TRIG(INJTRIG) (((INJTRIG) == ADC_EXTERNALTRIGINJECCONV_T1_CC4) || \ ((INJTRIG) == ADC_EXTERNALTRIGINJECCONV_T1_TRGO) || \ ((INJTRIG) == ADC_EXTERNALTRIGINJECCONV_T2_CC1) || \ ((INJTRIG) == ADC_EXTERNALTRIGINJECCONV_T2_TRGO) || \ ((INJTRIG) == ADC_EXTERNALTRIGINJECCONV_T3_CC2) || \ ((INJTRIG) == ADC_EXTERNALTRIGINJECCONV_T3_CC4) || \ ((INJTRIG) == ADC_EXTERNALTRIGINJECCONV_T4_CC1) || \ ((INJTRIG) == ADC_EXTERNALTRIGINJECCONV_T4_CC2) || \ ((INJTRIG) == ADC_EXTERNALTRIGINJECCONV_T4_CC3) || \ ((INJTRIG) == ADC_EXTERNALTRIGINJECCONV_T4_TRGO) || \ ((INJTRIG) == ADC_EXTERNALTRIGINJECCONV_T5_CC4) || \ ((INJTRIG) == ADC_EXTERNALTRIGINJECCONV_T5_TRGO) || \ ((INJTRIG) == ADC_EXTERNALTRIGINJECCONV_T8_CC2) || \ ((INJTRIG) == ADC_EXTERNALTRIGINJECCONV_T8_CC3) || \ ((INJTRIG) == ADC_EXTERNALTRIGINJECCONV_T8_CC4) || \ ((INJTRIG) == ADC_EXTERNALTRIGINJECCONV_EXT_IT15)|| \ ((INJTRIG) == ADC_INJECTED_SOFTWARE_START)) #define IS_ADC_INJECTED_LENGTH(LENGTH) (((LENGTH) >= ((uint32_t)1)) && ((LENGTH) <= ((uint32_t)4))) #define IS_ADC_INJECTED_RANK(RANK) (((RANK) >= ((uint32_t)1)) && ((RANK) <= ((uint32_t)4))) /** * @brief Set the selected injected Channel rank. * @param _CHANNELNB_: Channel number. * @param _RANKNB_: Rank number. * @param _JSQR_JL_: Sequence length. * @retval None */ #define ADC_JSQR(_CHANNELNB_, _RANKNB_, _JSQR_JL_) (((uint32_t)((uint16_t)(_CHANNELNB_))) << (5 * (uint8_t)(((_RANKNB_) + 3) - (_JSQR_JL_)))) /** * @} */ /* Private functions ---------------------------------------------------------*/ /** @defgroup ADCEx_Private_Functions ADC Private Functions * @{ */ /** * @} */ /** * @} */ /** * @} */ #ifdef __cplusplus } #endif #endif /*__STM32F4xx_ADC_EX_H */ /************************ (C) COPYRIGHT STMicroelectronics *****END OF FILE****/ ================================================ FILE: Zelig/mbed/TARGET_NUCLEO_F411RE/stm32f4xx_hal_can.h ================================================ /** ****************************************************************************** * @file stm32f4xx_hal_can.h * @author MCD Application Team * @version V1.4.1 * @date 09-October-2015 * @brief Header file of CAN HAL module. ****************************************************************************** * @attention * *

© COPYRIGHT(c) 2015 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. * ****************************************************************************** */ /* Define to prevent recursive inclusion -------------------------------------*/ #ifndef __STM32F4xx_HAL_CAN_H #define __STM32F4xx_HAL_CAN_H #ifdef __cplusplus extern "C" { #endif #if defined(STM32F405xx) || defined(STM32F415xx) || defined(STM32F407xx) || defined(STM32F417xx) ||\ defined(STM32F427xx) || defined(STM32F437xx) || defined(STM32F429xx) || defined(STM32F439xx) ||\ defined(STM32F446xx) || defined(STM32F469xx) || defined(STM32F479xx) /* Includes ------------------------------------------------------------------*/ #include "stm32f4xx_hal_def.h" /** @addtogroup STM32F4xx_HAL_Driver * @{ */ /** @addtogroup CAN * @{ */ /* Exported types ------------------------------------------------------------*/ /** @defgroup CAN_Exported_Types CAN Exported Types * @{ */ /** * @brief HAL State structures definition */ typedef enum { HAL_CAN_STATE_RESET = 0x00, /*!< CAN not yet initialized or disabled */ HAL_CAN_STATE_READY = 0x01, /*!< CAN initialized and ready for use */ HAL_CAN_STATE_BUSY = 0x02, /*!< CAN process is ongoing */ HAL_CAN_STATE_BUSY_TX = 0x12, /*!< CAN process is ongoing */ HAL_CAN_STATE_BUSY_RX = 0x22, /*!< CAN process is ongoing */ HAL_CAN_STATE_BUSY_TX_RX = 0x32, /*!< CAN process is ongoing */ HAL_CAN_STATE_TIMEOUT = 0x03, /*!< Timeout state */ HAL_CAN_STATE_ERROR = 0x04 /*!< CAN error state */ }HAL_CAN_StateTypeDef; /** * @brief CAN init structure definition */ typedef struct { uint32_t Prescaler; /*!< Specifies the length of a time quantum. This parameter must be a number between Min_Data = 1 and Max_Data = 1024 */ uint32_t Mode; /*!< Specifies the CAN operating mode. This parameter can be a value of @ref CAN_operating_mode */ uint32_t SJW; /*!< Specifies the maximum number of time quanta the CAN hardware is allowed to lengthen or shorten a bit to perform resynchronization. This parameter can be a value of @ref CAN_synchronisation_jump_width */ uint32_t BS1; /*!< Specifies the number of time quanta in Bit Segment 1. This parameter can be a value of @ref CAN_time_quantum_in_bit_segment_1 */ uint32_t BS2; /*!< Specifies the number of time quanta in Bit Segment 2. This parameter can be a value of @ref CAN_time_quantum_in_bit_segment_2 */ uint32_t TTCM; /*!< Enable or disable the time triggered communication mode. This parameter can be set to ENABLE or DISABLE. */ uint32_t ABOM; /*!< Enable or disable the automatic bus-off management. This parameter can be set to ENABLE or DISABLE */ uint32_t AWUM; /*!< Enable or disable the automatic wake-up mode. This parameter can be set to ENABLE or DISABLE */ uint32_t NART; /*!< Enable or disable the non-automatic retransmission mode. This parameter can be set to ENABLE or DISABLE */ uint32_t RFLM; /*!< Enable or disable the receive FIFO Locked mode. This parameter can be set to ENABLE or DISABLE */ uint32_t TXFP; /*!< Enable or disable the transmit FIFO priority. This parameter can be set to ENABLE or DISABLE */ }CAN_InitTypeDef; /** * @brief CAN filter configuration structure definition */ typedef struct { uint32_t FilterIdHigh; /*!< Specifies the filter identification number (MSBs for a 32-bit configuration, first one for a 16-bit configuration). This parameter must be a number between Min_Data = 0x0000 and Max_Data = 0xFFFF */ uint32_t FilterIdLow; /*!< Specifies the filter identification number (LSBs for a 32-bit configuration, second one for a 16-bit configuration). This parameter must be a number between Min_Data = 0x0000 and Max_Data = 0xFFFF */ uint32_t FilterMaskIdHigh; /*!< Specifies the filter mask number or identification number, according to the mode (MSBs for a 32-bit configuration, first one for a 16-bit configuration). This parameter must be a number between Min_Data = 0x0000 and Max_Data = 0xFFFF */ uint32_t FilterMaskIdLow; /*!< Specifies the filter mask number or identification number, according to the mode (LSBs for a 32-bit configuration, second one for a 16-bit configuration). This parameter must be a number between Min_Data = 0x0000 and Max_Data = 0xFFFF */ uint32_t FilterFIFOAssignment; /*!< Specifies the FIFO (0 or 1) which will be assigned to the filter. This parameter can be a value of @ref CAN_filter_FIFO */ uint32_t FilterNumber; /*!< Specifies the filter which will be initialized. This parameter must be a number between Min_Data = 0 and Max_Data = 27 */ uint32_t FilterMode; /*!< Specifies the filter mode to be initialized. This parameter can be a value of @ref CAN_filter_mode */ uint32_t FilterScale; /*!< Specifies the filter scale. This parameter can be a value of @ref CAN_filter_scale */ uint32_t FilterActivation; /*!< Enable or disable the filter. This parameter can be set to ENABLE or DISABLE. */ uint32_t BankNumber; /*!< Select the start slave bank filter. This parameter must be a number between Min_Data = 0 and Max_Data = 28 */ }CAN_FilterConfTypeDef; /** * @brief CAN Tx message structure definition */ typedef struct { uint32_t StdId; /*!< Specifies the standard identifier. This parameter must be a number between Min_Data = 0 and Max_Data = 0x7FF */ uint32_t ExtId; /*!< Specifies the extended identifier. This parameter must be a number between Min_Data = 0 and Max_Data = 0x1FFFFFFF */ uint32_t IDE; /*!< Specifies the type of identifier for the message that will be transmitted. This parameter can be a value of @ref CAN_Identifier_Type */ uint32_t RTR; /*!< Specifies the type of frame for the message that will be transmitted. This parameter can be a value of @ref CAN_remote_transmission_request */ uint32_t DLC; /*!< Specifies the length of the frame that will be transmitted. This parameter must be a number between Min_Data = 0 and Max_Data = 8 */ uint8_t Data[8]; /*!< Contains the data to be transmitted. This parameter must be a number between Min_Data = 0 and Max_Data = 0xFF */ }CanTxMsgTypeDef; /** * @brief CAN Rx message structure definition */ typedef struct { uint32_t StdId; /*!< Specifies the standard identifier. This parameter must be a number between Min_Data = 0 and Max_Data = 0x7FF */ uint32_t ExtId; /*!< Specifies the extended identifier. This parameter must be a number between Min_Data = 0 and Max_Data = 0x1FFFFFFF */ uint32_t IDE; /*!< Specifies the type of identifier for the message that will be received. This parameter can be a value of @ref CAN_Identifier_Type */ uint32_t RTR; /*!< Specifies the type of frame for the received message. This parameter can be a value of @ref CAN_remote_transmission_request */ uint32_t DLC; /*!< Specifies the length of the frame that will be received. This parameter must be a number between Min_Data = 0 and Max_Data = 8 */ uint8_t Data[8]; /*!< Contains the data to be received. This parameter must be a number between Min_Data = 0 and Max_Data = 0xFF */ uint32_t FMI; /*!< Specifies the index of the filter the message stored in the mailbox passes through. This parameter must be a number between Min_Data = 0 and Max_Data = 0xFF */ uint32_t FIFONumber; /*!< Specifies the receive FIFO number. This parameter can be CAN_FIFO0 or CAN_FIFO1 */ }CanRxMsgTypeDef; /** * @brief CAN handle Structure definition */ typedef struct { CAN_TypeDef *Instance; /*!< Register base address */ CAN_InitTypeDef Init; /*!< CAN required parameters */ CanTxMsgTypeDef* pTxMsg; /*!< Pointer to transmit structure */ CanRxMsgTypeDef* pRxMsg; /*!< Pointer to reception structure */ __IO HAL_CAN_StateTypeDef State; /*!< CAN communication state */ HAL_LockTypeDef Lock; /*!< CAN locking object */ __IO uint32_t ErrorCode; /*!< CAN Error code */ }CAN_HandleTypeDef; /** * @} */ /* Exported constants --------------------------------------------------------*/ /** @defgroup CAN_Exported_Constants CAN Exported Constants * @{ */ /** @defgroup HAL_CAN_Error_Code HAL CAN Error Code * @{ */ #define HAL_CAN_ERROR_NONE 0x00 /*!< No error */ #define HAL_CAN_ERROR_EWG 0x01 /*!< EWG error */ #define HAL_CAN_ERROR_EPV 0x02 /*!< EPV error */ #define HAL_CAN_ERROR_BOF 0x04 /*!< BOF error */ #define HAL_CAN_ERROR_STF 0x08 /*!< Stuff error */ #define HAL_CAN_ERROR_FOR 0x10 /*!< Form error */ #define HAL_CAN_ERROR_ACK 0x20 /*!< Acknowledgment error */ #define HAL_CAN_ERROR_BR 0x40 /*!< Bit recessive */ #define HAL_CAN_ERROR_BD 0x80 /*!< LEC dominant */ #define HAL_CAN_ERROR_CRC 0x100 /*!< LEC transfer error */ /** * @} */ /** @defgroup CAN_InitStatus CAN InitStatus * @{ */ #define CAN_INITSTATUS_FAILED ((uint8_t)0x00) /*!< CAN initialization failed */ #define CAN_INITSTATUS_SUCCESS ((uint8_t)0x01) /*!< CAN initialization OK */ /** * @} */ /** @defgroup CAN_operating_mode CAN Operating Mode * @{ */ #define CAN_MODE_NORMAL ((uint32_t)0x00000000) /*!< Normal mode */ #define CAN_MODE_LOOPBACK ((uint32_t)CAN_BTR_LBKM) /*!< Loopback mode */ #define CAN_MODE_SILENT ((uint32_t)CAN_BTR_SILM) /*!< Silent mode */ #define CAN_MODE_SILENT_LOOPBACK ((uint32_t)(CAN_BTR_LBKM | CAN_BTR_SILM)) /*!< Loopback combined with silent mode */ /** * @} */ /** @defgroup CAN_synchronisation_jump_width CAN Synchronisation Jump Width * @{ */ #define CAN_SJW_1TQ ((uint32_t)0x00000000) /*!< 1 time quantum */ #define CAN_SJW_2TQ ((uint32_t)CAN_BTR_SJW_0) /*!< 2 time quantum */ #define CAN_SJW_3TQ ((uint32_t)CAN_BTR_SJW_1) /*!< 3 time quantum */ #define CAN_SJW_4TQ ((uint32_t)CAN_BTR_SJW) /*!< 4 time quantum */ /** * @} */ /** @defgroup CAN_time_quantum_in_bit_segment_1 CAN Time Quantum in bit segment 1 * @{ */ #define CAN_BS1_1TQ ((uint32_t)0x00000000) /*!< 1 time quantum */ #define CAN_BS1_2TQ ((uint32_t)CAN_BTR_TS1_0) /*!< 2 time quantum */ #define CAN_BS1_3TQ ((uint32_t)CAN_BTR_TS1_1) /*!< 3 time quantum */ #define CAN_BS1_4TQ ((uint32_t)(CAN_BTR_TS1_1 | CAN_BTR_TS1_0)) /*!< 4 time quantum */ #define CAN_BS1_5TQ ((uint32_t)CAN_BTR_TS1_2) /*!< 5 time quantum */ #define CAN_BS1_6TQ ((uint32_t)(CAN_BTR_TS1_2 | CAN_BTR_TS1_0)) /*!< 6 time quantum */ #define CAN_BS1_7TQ ((uint32_t)(CAN_BTR_TS1_2 | CAN_BTR_TS1_1)) /*!< 7 time quantum */ #define CAN_BS1_8TQ ((uint32_t)(CAN_BTR_TS1_2 | CAN_BTR_TS1_1 | CAN_BTR_TS1_0)) /*!< 8 time quantum */ #define CAN_BS1_9TQ ((uint32_t)CAN_BTR_TS1_3) /*!< 9 time quantum */ #define CAN_BS1_10TQ ((uint32_t)(CAN_BTR_TS1_3 | CAN_BTR_TS1_0)) /*!< 10 time quantum */ #define CAN_BS1_11TQ ((uint32_t)(CAN_BTR_TS1_3 | CAN_BTR_TS1_1)) /*!< 11 time quantum */ #define CAN_BS1_12TQ ((uint32_t)(CAN_BTR_TS1_3 | CAN_BTR_TS1_1 | CAN_BTR_TS1_0)) /*!< 12 time quantum */ #define CAN_BS1_13TQ ((uint32_t)(CAN_BTR_TS1_3 | CAN_BTR_TS1_2)) /*!< 13 time quantum */ #define CAN_BS1_14TQ ((uint32_t)(CAN_BTR_TS1_3 | CAN_BTR_TS1_2 | CAN_BTR_TS1_0)) /*!< 14 time quantum */ #define CAN_BS1_15TQ ((uint32_t)(CAN_BTR_TS1_3 | CAN_BTR_TS1_2 | CAN_BTR_TS1_1)) /*!< 15 time quantum */ #define CAN_BS1_16TQ ((uint32_t)CAN_BTR_TS1) /*!< 16 time quantum */ /** * @} */ /** @defgroup CAN_time_quantum_in_bit_segment_2 CAN Time Quantum in bit segment 2 * @{ */ #define CAN_BS2_1TQ ((uint32_t)0x00000000) /*!< 1 time quantum */ #define CAN_BS2_2TQ ((uint32_t)CAN_BTR_TS2_0) /*!< 2 time quantum */ #define CAN_BS2_3TQ ((uint32_t)CAN_BTR_TS2_1) /*!< 3 time quantum */ #define CAN_BS2_4TQ ((uint32_t)(CAN_BTR_TS2_1 | CAN_BTR_TS2_0)) /*!< 4 time quantum */ #define CAN_BS2_5TQ ((uint32_t)CAN_BTR_TS2_2) /*!< 5 time quantum */ #define CAN_BS2_6TQ ((uint32_t)(CAN_BTR_TS2_2 | CAN_BTR_TS2_0)) /*!< 6 time quantum */ #define CAN_BS2_7TQ ((uint32_t)(CAN_BTR_TS2_2 | CAN_BTR_TS2_1)) /*!< 7 time quantum */ #define CAN_BS2_8TQ ((uint32_t)CAN_BTR_TS2) /*!< 8 time quantum */ /** * @} */ /** @defgroup CAN_filter_mode CAN Filter Mode * @{ */ #define CAN_FILTERMODE_IDMASK ((uint8_t)0x00) /*!< Identifier mask mode */ #define CAN_FILTERMODE_IDLIST ((uint8_t)0x01) /*!< Identifier list mode */ /** * @} */ /** @defgroup CAN_filter_scale CAN Filter Scale * @{ */ #define CAN_FILTERSCALE_16BIT ((uint8_t)0x00) /*!< Two 16-bit filters */ #define CAN_FILTERSCALE_32BIT ((uint8_t)0x01) /*!< One 32-bit filter */ /** * @} */ /** @defgroup CAN_filter_FIFO CAN Filter FIFO * @{ */ #define CAN_FILTER_FIFO0 ((uint8_t)0x00) /*!< Filter FIFO 0 assignment for filter x */ #define CAN_FILTER_FIFO1 ((uint8_t)0x01) /*!< Filter FIFO 1 assignment for filter x */ /** * @} */ /** @defgroup CAN_Identifier_Type CAN Identifier Type * @{ */ #define CAN_ID_STD ((uint32_t)0x00000000) /*!< Standard Id */ #define CAN_ID_EXT ((uint32_t)0x00000004) /*!< Extended Id */ /** * @} */ /** @defgroup CAN_remote_transmission_request CAN Remote Transmission Request * @{ */ #define CAN_RTR_DATA ((uint32_t)0x00000000) /*!< Data frame */ #define CAN_RTR_REMOTE ((uint32_t)0x00000002) /*!< Remote frame */ /** * @} */ /** @defgroup CAN_receive_FIFO_number_constants CAN Receive FIFO Number Constants * @{ */ #define CAN_FIFO0 ((uint8_t)0x00) /*!< CAN FIFO 0 used to receive */ #define CAN_FIFO1 ((uint8_t)0x01) /*!< CAN FIFO 1 used to receive */ /** * @} */ /** @defgroup CAN_flags CAN Flags * @{ */ /* If the flag is 0x3XXXXXXX, it means that it can be used with CAN_GetFlagStatus() and CAN_ClearFlag() functions. */ /* If the flag is 0x1XXXXXXX, it means that it can only be used with CAN_GetFlagStatus() function. */ /* Transmit Flags */ #define CAN_FLAG_RQCP0 ((uint32_t)0x00000500) /*!< Request MailBox0 flag */ #define CAN_FLAG_RQCP1 ((uint32_t)0x00000508) /*!< Request MailBox1 flag */ #define CAN_FLAG_RQCP2 ((uint32_t)0x00000510) /*!< Request MailBox2 flag */ #define CAN_FLAG_TXOK0 ((uint32_t)0x00000501) /*!< Transmission OK MailBox0 flag */ #define CAN_FLAG_TXOK1 ((uint32_t)0x00000509) /*!< Transmission OK MailBox1 flag */ #define CAN_FLAG_TXOK2 ((uint32_t)0x00000511) /*!< Transmission OK MailBox2 flag */ #define CAN_FLAG_TME0 ((uint32_t)0x0000051A) /*!< Transmit mailbox 0 empty flag */ #define CAN_FLAG_TME1 ((uint32_t)0x0000051B) /*!< Transmit mailbox 0 empty flag */ #define CAN_FLAG_TME2 ((uint32_t)0x0000051C) /*!< Transmit mailbox 0 empty flag */ /* Receive Flags */ #define CAN_FLAG_FF0 ((uint32_t)0x00000203) /*!< FIFO 0 Full flag */ #define CAN_FLAG_FOV0 ((uint32_t)0x00000204) /*!< FIFO 0 Overrun flag */ #define CAN_FLAG_FF1 ((uint32_t)0x00000403) /*!< FIFO 1 Full flag */ #define CAN_FLAG_FOV1 ((uint32_t)0x00000404) /*!< FIFO 1 Overrun flag */ /* Operating Mode Flags */ #define CAN_FLAG_WKU ((uint32_t)0x00000103) /*!< Wake up flag */ #define CAN_FLAG_SLAK ((uint32_t)0x00000101) /*!< Sleep acknowledge flag */ #define CAN_FLAG_SLAKI ((uint32_t)0x00000104) /*!< Sleep acknowledge flag */ /* @note When SLAK interrupt is disabled (SLKIE=0), no polling on SLAKI is possible. In this case the SLAK bit can be polled.*/ /* Error Flags */ #define CAN_FLAG_EWG ((uint32_t)0x00000300) /*!< Error warning flag */ #define CAN_FLAG_EPV ((uint32_t)0x00000301) /*!< Error passive flag */ #define CAN_FLAG_BOF ((uint32_t)0x00000302) /*!< Bus-Off flag */ /** * @} */ /** @defgroup CAN_Interrupts CAN Interrupts * @{ */ #define CAN_IT_TME ((uint32_t)CAN_IER_TMEIE) /*!< Transmit mailbox empty interrupt */ /* Receive Interrupts */ #define CAN_IT_FMP0 ((uint32_t)CAN_IER_FMPIE0) /*!< FIFO 0 message pending interrupt */ #define CAN_IT_FF0 ((uint32_t)CAN_IER_FFIE0) /*!< FIFO 0 full interrupt */ #define CAN_IT_FOV0 ((uint32_t)CAN_IER_FOVIE0) /*!< FIFO 0 overrun interrupt */ #define CAN_IT_FMP1 ((uint32_t)CAN_IER_FMPIE1) /*!< FIFO 1 message pending interrupt */ #define CAN_IT_FF1 ((uint32_t)CAN_IER_FFIE1) /*!< FIFO 1 full interrupt */ #define CAN_IT_FOV1 ((uint32_t)CAN_IER_FOVIE1) /*!< FIFO 1 overrun interrupt */ /* Operating Mode Interrupts */ #define CAN_IT_WKU ((uint32_t)CAN_IER_WKUIE) /*!< Wake-up interrupt */ #define CAN_IT_SLK ((uint32_t)CAN_IER_SLKIE) /*!< Sleep acknowledge interrupt */ /* Error Interrupts */ #define CAN_IT_EWG ((uint32_t)CAN_IER_EWGIE) /*!< Error warning interrupt */ #define CAN_IT_EPV ((uint32_t)CAN_IER_EPVIE) /*!< Error passive interrupt */ #define CAN_IT_BOF ((uint32_t)CAN_IER_BOFIE) /*!< Bus-off interrupt */ #define CAN_IT_LEC ((uint32_t)CAN_IER_LECIE) /*!< Last error code interrupt */ #define CAN_IT_ERR ((uint32_t)CAN_IER_ERRIE) /*!< Error Interrupt */ /** * @} */ /** @defgroup CAN_Mailboxes_Definition CAN Mailboxes Definition * @{ */ #define CAN_TXMAILBOX_0 ((uint8_t)0x00) #define CAN_TXMAILBOX_1 ((uint8_t)0x01) #define CAN_TXMAILBOX_2 ((uint8_t)0x02) /** * @} */ /** * @} */ /* Exported macro ------------------------------------------------------------*/ /** @defgroup CAN_Exported_Macros CAN Exported Macros * @{ */ /** @brief Reset CAN handle state * @param __HANDLE__: specifies the CAN Handle. * @retval None */ #define __HAL_CAN_RESET_HANDLE_STATE(__HANDLE__) ((__HANDLE__)->State = HAL_CAN_STATE_RESET) /** * @brief Enable the specified CAN interrupts. * @param __HANDLE__: CAN handle * @param __INTERRUPT__: CAN Interrupt * @retval None */ #define __HAL_CAN_ENABLE_IT(__HANDLE__, __INTERRUPT__) (((__HANDLE__)->Instance->IER) |= (__INTERRUPT__)) /** * @brief Disable the specified CAN interrupts. * @param __HANDLE__: CAN handle * @param __INTERRUPT__: CAN Interrupt * @retval None */ #define __HAL_CAN_DISABLE_IT(__HANDLE__, __INTERRUPT__) (((__HANDLE__)->Instance->IER) &= ~(__INTERRUPT__)) /** * @brief Return the number of pending received messages. * @param __HANDLE__: CAN handle * @param __FIFONUMBER__: Receive FIFO number, CAN_FIFO0 or CAN_FIFO1. * @retval The number of pending message. */ #define __HAL_CAN_MSG_PENDING(__HANDLE__, __FIFONUMBER__) (((__FIFONUMBER__) == CAN_FIFO0)? \ ((uint8_t)((__HANDLE__)->Instance->RF0R&(uint32_t)0x03)) : ((uint8_t)((__HANDLE__)->Instance->RF1R&(uint32_t)0x03))) /** @brief Check whether the specified CAN flag is set or not. * @param __HANDLE__: CAN Handle * @param __FLAG__: specifies the flag to check. * This parameter can be one of the following values: * @arg CAN_TSR_RQCP0: Request MailBox0 Flag * @arg CAN_TSR_RQCP1: Request MailBox1 Flag * @arg CAN_TSR_RQCP2: Request MailBox2 Flag * @arg CAN_FLAG_TXOK0: Transmission OK MailBox0 Flag * @arg CAN_FLAG_TXOK1: Transmission OK MailBox1 Flag * @arg CAN_FLAG_TXOK2: Transmission OK MailBox2 Flag * @arg CAN_FLAG_TME0: Transmit mailbox 0 empty Flag * @arg CAN_FLAG_TME1: Transmit mailbox 1 empty Flag * @arg CAN_FLAG_TME2: Transmit mailbox 2 empty Flag * @arg CAN_FLAG_FMP0: FIFO 0 Message Pending Flag * @arg CAN_FLAG_FF0: FIFO 0 Full Flag * @arg CAN_FLAG_FOV0: FIFO 0 Overrun Flag * @arg CAN_FLAG_FMP1: FIFO 1 Message Pending Flag * @arg CAN_FLAG_FF1: FIFO 1 Full Flag * @arg CAN_FLAG_FOV1: FIFO 1 Overrun Flag * @arg CAN_FLAG_WKU: Wake up Flag * @arg CAN_FLAG_SLAK: Sleep acknowledge Flag * @arg CAN_FLAG_SLAKI: Sleep acknowledge Flag * @arg CAN_FLAG_EWG: Error Warning Flag * @arg CAN_FLAG_EPV: Error Passive Flag * @arg CAN_FLAG_BOF: Bus-Off Flag * @retval The new state of __FLAG__ (TRUE or FALSE). */ #define __HAL_CAN_GET_FLAG(__HANDLE__, __FLAG__) \ ((((__FLAG__) >> 8) == 5)? ((((__HANDLE__)->Instance->TSR) & (1 << ((__FLAG__) & CAN_FLAG_MASK))) == (1 << ((__FLAG__) & CAN_FLAG_MASK))): \ (((__FLAG__) >> 8) == 2)? ((((__HANDLE__)->Instance->RF0R) & (1 << ((__FLAG__) & CAN_FLAG_MASK))) == (1 << ((__FLAG__) & CAN_FLAG_MASK))): \ (((__FLAG__) >> 8) == 4)? ((((__HANDLE__)->Instance->RF1R) & (1 << ((__FLAG__) & CAN_FLAG_MASK))) == (1 << ((__FLAG__) & CAN_FLAG_MASK))): \ (((__FLAG__) >> 8) == 1)? ((((__HANDLE__)->Instance->MSR) & (1 << ((__FLAG__) & CAN_FLAG_MASK))) == (1 << ((__FLAG__) & CAN_FLAG_MASK))): \ ((((__HANDLE__)->Instance->ESR) & (1 << ((__FLAG__) & CAN_FLAG_MASK))) == (1 << ((__FLAG__) & CAN_FLAG_MASK)))) /** @brief Clear the specified CAN pending flag. * @param __HANDLE__: CAN Handle. * @param __FLAG__: specifies the flag to check. * This parameter can be one of the following values: * @arg CAN_TSR_RQCP0: Request MailBox0 Flag * @arg CAN_TSR_RQCP1: Request MailBox1 Flag * @arg CAN_TSR_RQCP2: Request MailBox2 Flag * @arg CAN_FLAG_TXOK0: Transmission OK MailBox0 Flag * @arg CAN_FLAG_TXOK1: Transmission OK MailBox1 Flag * @arg CAN_FLAG_TXOK2: Transmission OK MailBox2 Flag * @arg CAN_FLAG_TME0: Transmit mailbox 0 empty Flag * @arg CAN_FLAG_TME1: Transmit mailbox 1 empty Flag * @arg CAN_FLAG_TME2: Transmit mailbox 2 empty Flag * @arg CAN_FLAG_FMP0: FIFO 0 Message Pending Flag * @arg CAN_FLAG_FF0: FIFO 0 Full Flag * @arg CAN_FLAG_FOV0: FIFO 0 Overrun Flag * @arg CAN_FLAG_FMP1: FIFO 1 Message Pending Flag * @arg CAN_FLAG_FF1: FIFO 1 Full Flag * @arg CAN_FLAG_FOV1: FIFO 1 Overrun Flag * @arg CAN_FLAG_WKU: Wake up Flag * @arg CAN_FLAG_SLAK: Sleep acknowledge Flag * @arg CAN_FLAG_SLAKI: Sleep acknowledge Flag * @arg CAN_FLAG_EWG: Error Warning Flag * @arg CAN_FLAG_EPV: Error Passive Flag * @arg CAN_FLAG_BOF: Bus-Off Flag * @retval The new state of __FLAG__ (TRUE or FALSE). */ #define __HAL_CAN_CLEAR_FLAG(__HANDLE__, __FLAG__) \ ((((__FLAG__) >> 8) == 5)? (((__HANDLE__)->Instance->TSR) = ~((uint32_t)1 << ((__FLAG__) & CAN_FLAG_MASK))): \ (((__FLAG__) >> 8) == 2)? (((__HANDLE__)->Instance->RF0R) = ~((uint32_t)1 << ((__FLAG__) & CAN_FLAG_MASK))): \ (((__FLAG__) >> 8) == 4)? (((__HANDLE__)->Instance->RF1R) = ~((uint32_t)1 << ((__FLAG__) & CAN_FLAG_MASK))): \ (((__FLAG__) >> 8) == 1)? (((__HANDLE__)->Instance->MSR) = ~((uint32_t)1 << ((__FLAG__) & CAN_FLAG_MASK))): \ (((__HANDLE__)->Instance->ESR) = ~((uint32_t)1 << ((__FLAG__) & CAN_FLAG_MASK)))) /** @brief Check if the specified CAN interrupt source is enabled or disabled. * @param __HANDLE__: CAN Handle * @param __INTERRUPT__: specifies the CAN interrupt source to check. * This parameter can be one of the following values: * @arg CAN_IT_TME: Transmit mailbox empty interrupt enable * @arg CAN_IT_FMP0: FIFO0 message pending interrupt enable * @arg CAN_IT_FMP1: FIFO1 message pending interrupt enable * @retval The new state of __IT__ (TRUE or FALSE). */ #define __HAL_CAN_GET_IT_SOURCE(__HANDLE__, __INTERRUPT__) ((((__HANDLE__)->Instance->IER & (__INTERRUPT__)) == (__INTERRUPT__)) ? SET : RESET) /** * @brief Check the transmission status of a CAN Frame. * @param __HANDLE__: CAN Handle * @param __TRANSMITMAILBOX__: the number of the mailbox that is used for transmission. * @retval The new status of transmission (TRUE or FALSE). */ #define __HAL_CAN_TRANSMIT_STATUS(__HANDLE__, __TRANSMITMAILBOX__)\ (((__TRANSMITMAILBOX__) == CAN_TXMAILBOX_0)? ((((__HANDLE__)->Instance->TSR) & (CAN_TSR_RQCP0 | CAN_TSR_TXOK0 | CAN_TSR_TME0)) == (CAN_TSR_RQCP0 | CAN_TSR_TXOK0 | CAN_TSR_TME0)) :\ ((__TRANSMITMAILBOX__) == CAN_TXMAILBOX_1)? ((((__HANDLE__)->Instance->TSR) & (CAN_TSR_RQCP1 | CAN_TSR_TXOK1 | CAN_TSR_TME1)) == (CAN_TSR_RQCP1 | CAN_TSR_TXOK1 | CAN_TSR_TME1)) :\ ((((__HANDLE__)->Instance->TSR) & (CAN_TSR_RQCP2 | CAN_TSR_TXOK2 | CAN_TSR_TME2)) == (CAN_TSR_RQCP2 | CAN_TSR_TXOK2 | CAN_TSR_TME2))) /** * @brief Release the specified receive FIFO. * @param __HANDLE__: CAN handle * @param __FIFONUMBER__: Receive FIFO number, CAN_FIFO0 or CAN_FIFO1. * @retval None */ #define __HAL_CAN_FIFO_RELEASE(__HANDLE__, __FIFONUMBER__) (((__FIFONUMBER__) == CAN_FIFO0)? \ ((__HANDLE__)->Instance->RF0R |= CAN_RF0R_RFOM0) : ((__HANDLE__)->Instance->RF1R |= CAN_RF1R_RFOM1)) /** * @brief Cancel a transmit request. * @param __HANDLE__: CAN Handle * @param __TRANSMITMAILBOX__: the number of the mailbox that is used for transmission. * @retval None */ #define __HAL_CAN_CANCEL_TRANSMIT(__HANDLE__, __TRANSMITMAILBOX__)\ (((__TRANSMITMAILBOX__) == CAN_TXMAILBOX_0)? ((__HANDLE__)->Instance->TSR |= CAN_TSR_ABRQ0) :\ ((__TRANSMITMAILBOX__) == CAN_TXMAILBOX_1)? ((__HANDLE__)->Instance->TSR |= CAN_TSR_ABRQ1) :\ ((__HANDLE__)->Instance->TSR |= CAN_TSR_ABRQ2)) /** * @brief Enable or disable the DBG Freeze for CAN. * @param __HANDLE__: CAN Handle * @param __NEWSTATE__: new state of the CAN peripheral. * This parameter can be: ENABLE (CAN reception/transmission is frozen * during debug. Reception FIFOs can still be accessed/controlled normally) * or DISABLE (CAN is working during debug). * @retval None */ #define __HAL_CAN_DBG_FREEZE(__HANDLE__, __NEWSTATE__) (((__NEWSTATE__) == ENABLE)? \ ((__HANDLE__)->Instance->MCR |= CAN_MCR_DBF) : ((__HANDLE__)->Instance->MCR &= ~CAN_MCR_DBF)) /** * @} */ /* Exported functions --------------------------------------------------------*/ /** @addtogroup CAN_Exported_Functions * @{ */ /** @addtogroup CAN_Exported_Functions_Group1 * @{ */ /* Initialization/de-initialization functions ***********************************/ HAL_StatusTypeDef HAL_CAN_Init(CAN_HandleTypeDef* hcan); HAL_StatusTypeDef HAL_CAN_ConfigFilter(CAN_HandleTypeDef* hcan, CAN_FilterConfTypeDef* sFilterConfig); HAL_StatusTypeDef HAL_CAN_DeInit(CAN_HandleTypeDef* hcan); void HAL_CAN_MspInit(CAN_HandleTypeDef* hcan); void HAL_CAN_MspDeInit(CAN_HandleTypeDef* hcan); /** * @} */ /** @addtogroup CAN_Exported_Functions_Group2 * @{ */ /* I/O operation functions ******************************************************/ HAL_StatusTypeDef HAL_CAN_Transmit(CAN_HandleTypeDef *hcan, uint32_t Timeout); HAL_StatusTypeDef HAL_CAN_Transmit_IT(CAN_HandleTypeDef *hcan); HAL_StatusTypeDef HAL_CAN_Receive(CAN_HandleTypeDef *hcan, uint8_t FIFONumber, uint32_t Timeout); HAL_StatusTypeDef HAL_CAN_Receive_IT(CAN_HandleTypeDef *hcan, uint8_t FIFONumber); HAL_StatusTypeDef HAL_CAN_Sleep(CAN_HandleTypeDef *hcan); HAL_StatusTypeDef HAL_CAN_WakeUp(CAN_HandleTypeDef *hcan); void HAL_CAN_IRQHandler(CAN_HandleTypeDef* hcan); void HAL_CAN_TxCpltCallback(CAN_HandleTypeDef* hcan); void HAL_CAN_RxCpltCallback(CAN_HandleTypeDef* hcan); void HAL_CAN_ErrorCallback(CAN_HandleTypeDef *hcan); /** * @} */ /** @addtogroup CAN_Exported_Functions_Group3 * @{ */ /* Peripheral State functions ***************************************************/ uint32_t HAL_CAN_GetError(CAN_HandleTypeDef *hcan); HAL_CAN_StateTypeDef HAL_CAN_GetState(CAN_HandleTypeDef* hcan); /** * @} */ /** * @} */ /* Private types -------------------------------------------------------------*/ /** @defgroup CAN_Private_Types CAN Private Types * @{ */ /** * @} */ /* Private variables ---------------------------------------------------------*/ /** @defgroup CAN_Private_Variables CAN Private Variables * @{ */ /** * @} */ /* Private constants ---------------------------------------------------------*/ /** @defgroup CAN_Private_Constants CAN Private Constants * @{ */ #define CAN_TXSTATUS_NOMAILBOX ((uint8_t)0x04) /*!< CAN cell did not provide CAN_TxStatus_NoMailBox */ #define CAN_FLAG_MASK ((uint32_t)0x000000FF) /** * @} */ /* Private macros ------------------------------------------------------------*/ /** @defgroup CAN_Private_Macros CAN Private Macros * @{ */ #define IS_CAN_MODE(MODE) (((MODE) == CAN_MODE_NORMAL) || \ ((MODE) == CAN_MODE_LOOPBACK)|| \ ((MODE) == CAN_MODE_SILENT) || \ ((MODE) == CAN_MODE_SILENT_LOOPBACK)) #define IS_CAN_SJW(SJW) (((SJW) == CAN_SJW_1TQ) || ((SJW) == CAN_SJW_2TQ)|| \ ((SJW) == CAN_SJW_3TQ) || ((SJW) == CAN_SJW_4TQ)) #define IS_CAN_BS1(BS1) ((BS1) <= CAN_BS1_16TQ) #define IS_CAN_BS2(BS2) ((BS2) <= CAN_BS2_8TQ) #define IS_CAN_PRESCALER(PRESCALER) (((PRESCALER) >= 1) && ((PRESCALER) <= 1024)) #define IS_CAN_FILTER_NUMBER(NUMBER) ((NUMBER) <= 27) #define IS_CAN_FILTER_MODE(MODE) (((MODE) == CAN_FILTERMODE_IDMASK) || \ ((MODE) == CAN_FILTERMODE_IDLIST)) #define IS_CAN_FILTER_SCALE(SCALE) (((SCALE) == CAN_FILTERSCALE_16BIT) || \ ((SCALE) == CAN_FILTERSCALE_32BIT)) #define IS_CAN_FILTER_FIFO(FIFO) (((FIFO) == CAN_FILTER_FIFO0) || \ ((FIFO) == CAN_FILTER_FIFO1)) #define IS_CAN_BANKNUMBER(BANKNUMBER) ((BANKNUMBER) <= 28) #define IS_CAN_TRANSMITMAILBOX(TRANSMITMAILBOX) ((TRANSMITMAILBOX) <= ((uint8_t)0x02)) #define IS_CAN_STDID(STDID) ((STDID) <= ((uint32_t)0x7FF)) #define IS_CAN_EXTID(EXTID) ((EXTID) <= ((uint32_t)0x1FFFFFFF)) #define IS_CAN_DLC(DLC) ((DLC) <= ((uint8_t)0x08)) #define IS_CAN_IDTYPE(IDTYPE) (((IDTYPE) == CAN_ID_STD) || \ ((IDTYPE) == CAN_ID_EXT)) #define IS_CAN_RTR(RTR) (((RTR) == CAN_RTR_DATA) || ((RTR) == CAN_RTR_REMOTE)) #define IS_CAN_FIFO(FIFO) (((FIFO) == CAN_FIFO0) || ((FIFO) == CAN_FIFO1)) /** * @} */ /* Private functions ---------------------------------------------------------*/ /** @defgroup CAN_Private_Functions CAN Private Functions * @{ */ /** * @} */ #endif /* STM32F405xx || STM32F415xx || STM32F407xx || STM32F417xx || STM32F427xx || STM32F437xx ||\ STM32F429xx || STM32F439xx || STM32F446xx || STM32F469xx || STM32F479xx */ /** * @} */ /** * @} */ #ifdef __cplusplus } #endif #endif /* __STM32F4xx_CAN_H */ /************************ (C) COPYRIGHT STMicroelectronics *****END OF FILE****/ ================================================ FILE: Zelig/mbed/TARGET_NUCLEO_F411RE/stm32f4xx_hal_cec.h ================================================ /** ****************************************************************************** * @file stm32f4xx_hal_cec.h * @author MCD Application Team * @version V1.4.1 * @date 09-October-2015 * @brief Header file of CEC HAL module. ****************************************************************************** * @attention * *

© COPYRIGHT(c) 2015 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. * ****************************************************************************** */ /* Define to prevent recursive inclusion -------------------------------------*/ #ifndef __STM32F4xx_HAL_CEC_H #define __STM32F4xx_HAL_CEC_H #ifdef __cplusplus extern "C" { #endif #if defined(STM32F446xx) /* Includes ------------------------------------------------------------------*/ #include "stm32f4xx_hal_def.h" /** @addtogroup STM32F4xx_HAL_Driver * @{ */ /** @addtogroup CEC * @{ */ /* Exported types ------------------------------------------------------------*/ /** @defgroup CEC_Exported_Types CEC Exported Types * @{ */ /** * @brief CEC Init Structure definition */ typedef struct { uint32_t SignalFreeTime; /*!< Set SFT field, specifies the Signal Free Time. It can be one of @ref CEC_Signal_Free_Time and belongs to the set {0,...,7} where 0x0 is the default configuration else means 0.5 + (SignalFreeTime - 1) nominal data bit periods */ uint32_t Tolerance; /*!< Set RXTOL bit, specifies the tolerance accepted on the received waveforms, it can be a value of @ref CEC_Tolerance : it is either CEC_STANDARD_TOLERANCE or CEC_EXTENDED_TOLERANCE */ uint32_t BRERxStop; /*!< Set BRESTP bit @ref CEC_BRERxStop : specifies whether or not a Bit Rising Error stops the reception. CEC_NO_RX_STOP_ON_BRE: reception is not stopped. CEC_RX_STOP_ON_BRE: reception is stopped. */ uint32_t BREErrorBitGen; /*!< Set BREGEN bit @ref CEC_BREErrorBitGen : specifies whether or not an Error-Bit is generated on the CEC line upon Bit Rising Error detection. CEC_BRE_ERRORBIT_NO_GENERATION: no error-bit generation. CEC_BRE_ERRORBIT_GENERATION: error-bit generation if BRESTP is set. */ uint32_t LBPEErrorBitGen; /*!< Set LBPEGEN bit @ref CEC_LBPEErrorBitGen : specifies whether or not an Error-Bit is generated on the CEC line upon Long Bit Period Error detection. CEC_LBPE_ERRORBIT_NO_GENERATION: no error-bit generation. CEC_LBPE_ERRORBIT_GENERATION: error-bit generation. */ uint32_t BroadcastMsgNoErrorBitGen; /*!< Set BRDNOGEN bit @ref CEC_BroadCastMsgErrorBitGen : allows to avoid an Error-Bit generation on the CEC line upon an error detected on a broadcast message. It supersedes BREGEN and LBPEGEN bits for a broadcast message error handling. It can take two values: 1) CEC_BROADCASTERROR_ERRORBIT_GENERATION. a) BRE detection: error-bit generation on the CEC line if BRESTP=CEC_RX_STOP_ON_BRE and BREGEN=CEC_BRE_ERRORBIT_NO_GENERATION. b) LBPE detection: error-bit generation on the CEC line if LBPGEN=CEC_LBPE_ERRORBIT_NO_GENERATION. 2) CEC_BROADCASTERROR_NO_ERRORBIT_GENERATION. no error-bit generation in case neither a) nor b) are satisfied. Additionally, there is no error-bit generation in case of Short Bit Period Error detection in a broadcast message while LSTN bit is set. */ uint32_t SignalFreeTimeOption; /*!< Set SFTOP bit @ref CEC_SFT_Option : specifies when SFT timer starts. CEC_SFT_START_ON_TXSOM SFT: timer starts when TXSOM is set by software. CEC_SFT_START_ON_TX_RX_END: SFT timer starts automatically at the end of message transmission/reception. */ uint32_t OwnAddress; /*!< Set OAR field, specifies CEC device address within a 15-bit long field */ uint32_t ListenMode; /*!< Set LSTN bit @ref CEC_Listening_Mode : specifies device listening mode. It can take two values: CEC_REDUCED_LISTENING_MODE: CEC peripheral receives only message addressed to its own address (OAR). Messages addressed to different destination are ignored. Broadcast messages are always received. CEC_FULL_LISTENING_MODE: CEC peripheral receives messages addressed to its own address (OAR) with positive acknowledge. Messages addressed to different destination are received, but without interfering with the CEC bus: no acknowledge sent. */ uint8_t InitiatorAddress; /* Initiator address (source logical address, sent in each header) */ }CEC_InitTypeDef; /** * @brief HAL CEC State structures definition */ typedef enum { HAL_CEC_STATE_RESET = 0x00, /*!< Peripheral Reset state */ HAL_CEC_STATE_READY = 0x01, /*!< Peripheral Initialized and ready for use */ HAL_CEC_STATE_BUSY = 0x02, /*!< an internal process is ongoing */ HAL_CEC_STATE_BUSY_TX = 0x03, /*!< Data Transmission process is ongoing */ HAL_CEC_STATE_BUSY_RX = 0x04, /*!< Data Reception process is ongoing */ HAL_CEC_STATE_STANDBY_RX = 0x05, /*!< IP ready to receive, doesn't prevent IP to transmit */ HAL_CEC_STATE_TIMEOUT = 0x06, /*!< Timeout state */ HAL_CEC_STATE_ERROR = 0x07 /*!< State Error */ }HAL_CEC_StateTypeDef; /** * @brief CEC handle Structure definition */ typedef struct { CEC_TypeDef *Instance; /* CEC registers base address */ CEC_InitTypeDef Init; /* CEC communication parameters */ uint8_t *pTxBuffPtr; /* Pointer to CEC Tx transfer Buffer */ uint16_t TxXferCount; /* CEC Tx Transfer Counter */ uint8_t *pRxBuffPtr; /* Pointer to CEC Rx transfer Buffer */ uint16_t RxXferSize; /* CEC Rx Transfer size, 0: header received only */ uint32_t ErrorCode; /* For errors handling purposes, copy of ISR register in case error is reported */ HAL_LockTypeDef Lock; /* Locking object */ HAL_CEC_StateTypeDef State; /* CEC communication state */ }CEC_HandleTypeDef; /** * @} */ /* Exported constants --------------------------------------------------------*/ /** @defgroup CEC_Exported_Constants CEC Exported Constants * @{ */ /** @defgroup CEC_Error_Code CEC Error Code * @{ */ #define HAL_CEC_ERROR_NONE (uint32_t) 0x0 /*!< no error */ #define HAL_CEC_ERROR_RXOVR CEC_ISR_RXOVR /*!< CEC Rx-Overrun */ #define HAL_CEC_ERROR_BRE CEC_ISR_BRE /*!< CEC Rx Bit Rising Error */ #define HAL_CEC_ERROR_SBPE CEC_ISR_SBPE /*!< CEC Rx Short Bit period Error */ #define HAL_CEC_ERROR_LBPE CEC_ISR_LBPE /*!< CEC Rx Long Bit period Error */ #define HAL_CEC_ERROR_RXACKE CEC_ISR_RXACKE /*!< CEC Rx Missing Acknowledge */ #define HAL_CEC_ERROR_ARBLST CEC_ISR_ARBLST /*!< CEC Arbitration Lost */ #define HAL_CEC_ERROR_TXUDR CEC_ISR_TXUDR /*!< CEC Tx-Buffer Underrun */ #define HAL_CEC_ERROR_TXERR CEC_ISR_TXERR /*!< CEC Tx-Error */ #define HAL_CEC_ERROR_TXACKE CEC_ISR_TXACKE /*!< CEC Tx Missing Acknowledge */ /** * @} */ /** @defgroup CEC_Signal_Free_Time CEC Signal Free Time setting parameter * @{ */ #define CEC_DEFAULT_SFT ((uint32_t)0x00000000) #define CEC_0_5_BITPERIOD_SFT ((uint32_t)0x00000001) #define CEC_1_5_BITPERIOD_SFT ((uint32_t)0x00000002) #define CEC_2_5_BITPERIOD_SFT ((uint32_t)0x00000003) #define CEC_3_5_BITPERIOD_SFT ((uint32_t)0x00000004) #define CEC_4_5_BITPERIOD_SFT ((uint32_t)0x00000005) #define CEC_5_5_BITPERIOD_SFT ((uint32_t)0x00000006) #define CEC_6_5_BITPERIOD_SFT ((uint32_t)0x00000007) /** * @} */ /** @defgroup CEC_Tolerance CEC Receiver Tolerance * @{ */ #define CEC_STANDARD_TOLERANCE ((uint32_t)0x00000000) #define CEC_EXTENDED_TOLERANCE ((uint32_t)CEC_CFGR_RXTOL) /** * @} */ /** @defgroup CEC_BRERxStop CEC Reception Stop on Error * @{ */ #define CEC_NO_RX_STOP_ON_BRE ((uint32_t)0x00000000) #define CEC_RX_STOP_ON_BRE ((uint32_t)CEC_CFGR_BRESTP) /** * @} */ /** @defgroup CEC_BREErrorBitGen CEC Error Bit Generation if Bit Rise Error reported * @{ */ #define CEC_BRE_ERRORBIT_NO_GENERATION ((uint32_t)0x00000000) #define CEC_BRE_ERRORBIT_GENERATION ((uint32_t)CEC_CFGR_BREGEN) /** * @} */ /** @defgroup CEC_LBPEErrorBitGen CEC Error Bit Generation if Long Bit Period Error reported * @{ */ #define CEC_LBPE_ERRORBIT_NO_GENERATION ((uint32_t)0x00000000) #define CEC_LBPE_ERRORBIT_GENERATION ((uint32_t)CEC_CFGR_LBPEGEN) /** * @} */ /** @defgroup CEC_BroadCastMsgErrorBitGen CEC Error Bit Generation on Broadcast message * @{ */ #define CEC_BROADCASTERROR_ERRORBIT_GENERATION ((uint32_t)0x00000000) #define CEC_BROADCASTERROR_NO_ERRORBIT_GENERATION ((uint32_t)CEC_CFGR_BRDNOGEN) /** * @} */ /** @defgroup CEC_SFT_Option CEC Signal Free Time start option * @{ */ #define CEC_SFT_START_ON_TXSOM ((uint32_t)0x00000000) #define CEC_SFT_START_ON_TX_RX_END ((uint32_t)CEC_CFGR_SFTOPT) /** * @} */ /** @defgroup CEC_Listening_Mode CEC Listening mode option * @{ */ #define CEC_REDUCED_LISTENING_MODE ((uint32_t)0x00000000) #define CEC_FULL_LISTENING_MODE ((uint32_t)CEC_CFGR_LSTN) /** * @} */ /** @defgroup CEC_OAR_Position CEC Device Own Address position in CEC CFGR register * @{ */ #define CEC_CFGR_OAR_LSB_POS ((uint32_t) 16) /** * @} */ /** @defgroup CEC_Initiator_Position CEC Initiator logical address position in message header * @{ */ #define CEC_INITIATOR_LSB_POS ((uint32_t) 4) /** * @} */ /** @defgroup CEC_Interrupts_Definitions CEC Interrupts definition * @{ */ #define CEC_IT_TXACKE CEC_IER_TXACKEIE #define CEC_IT_TXERR CEC_IER_TXERRIE #define CEC_IT_TXUDR CEC_IER_TXUDRIE #define CEC_IT_TXEND CEC_IER_TXENDIE #define CEC_IT_TXBR CEC_IER_TXBRIE #define CEC_IT_ARBLST CEC_IER_ARBLSTIE #define CEC_IT_RXACKE CEC_IER_RXACKEIE #define CEC_IT_LBPE CEC_IER_LBPEIE #define CEC_IT_SBPE CEC_IER_SBPEIE #define CEC_IT_BRE CEC_IER_BREIE #define CEC_IT_RXOVR CEC_IER_RXOVRIE #define CEC_IT_RXEND CEC_IER_RXENDIE #define CEC_IT_RXBR CEC_IER_RXBRIE /** * @} */ /** @defgroup CEC_Flags_Definitions CEC Flags definition * @{ */ #define CEC_FLAG_TXACKE CEC_ISR_TXACKE #define CEC_FLAG_TXERR CEC_ISR_TXERR #define CEC_FLAG_TXUDR CEC_ISR_TXUDR #define CEC_FLAG_TXEND CEC_ISR_TXEND #define CEC_FLAG_TXBR CEC_ISR_TXBR #define CEC_FLAG_ARBLST CEC_ISR_ARBLST #define CEC_FLAG_RXACKE CEC_ISR_RXACKE #define CEC_FLAG_LBPE CEC_ISR_LBPE #define CEC_FLAG_SBPE CEC_ISR_SBPE #define CEC_FLAG_BRE CEC_ISR_BRE #define CEC_FLAG_RXOVR CEC_ISR_RXOVR #define CEC_FLAG_RXEND CEC_ISR_RXEND #define CEC_FLAG_RXBR CEC_ISR_RXBR /** * @} */ /** @defgroup CEC_ALL_ERROR CEC all RX or TX errors flags * @{ */ #define CEC_ISR_ALL_ERROR ((uint32_t)CEC_ISR_RXOVR|CEC_ISR_BRE|CEC_ISR_SBPE|CEC_ISR_LBPE|CEC_ISR_RXACKE|\ CEC_ISR_ARBLST|CEC_ISR_TXUDR|CEC_ISR_TXERR|CEC_ISR_TXACKE) /** * @} */ /** @defgroup CEC_IER_ALL_RX CEC all RX errors interrupts enabling flag * @{ */ #define CEC_IER_RX_ALL_ERR ((uint32_t)CEC_IER_RXACKEIE|CEC_IER_LBPEIE|CEC_IER_SBPEIE|CEC_IER_BREIE|CEC_IER_RXOVRIE) /** * @} */ /** @defgroup CEC_IER_ALL_TX CEC all TX errors interrupts enabling flag * @{ */ #define CEC_IER_TX_ALL_ERR ((uint32_t)CEC_IER_TXACKEIE|CEC_IER_TXERRIE|CEC_IER_TXUDRIE|CEC_IER_ARBLSTIE) /** * @} */ /** * @} */ /* Exported macros -----------------------------------------------------------*/ /** @defgroup CEC_Exported_Macros CEC Exported Macros * @{ */ /** @brief Reset CEC handle state * @param __HANDLE__: CEC handle. * @retval None */ #define __HAL_CEC_RESET_HANDLE_STATE(__HANDLE__) ((__HANDLE__)->State = HAL_CEC_STATE_RESET) /** @brief Checks whether or not the specified CEC interrupt flag is set. * @param __HANDLE__: specifies the CEC Handle. * @param __FLAG__: specifies the interrupt to check. * @arg CEC_FLAG_TXACKE: Tx Missing acknowledge Error * @arg CEC_FLAG_TXERR: Tx Error. * @arg CEC_FLAG_TXUDR: Tx-Buffer Underrun. * @arg CEC_FLAG_TXEND: End of transmission (successful transmission of the last byte). * @arg CEC_FLAG_TXBR: Tx-Byte Request. * @arg CEC_FLAG_ARBLST: Arbitration Lost * @arg CEC_FLAG_RXACKE: Rx-Missing Acknowledge * @arg CEC_FLAG_LBPE: Rx Long period Error * @arg CEC_FLAG_SBPE: Rx Short period Error * @arg CEC_FLAG_BRE: Rx Bit Rissing Error * @arg CEC_FLAG_RXOVR: Rx Overrun. * @arg CEC_FLAG_RXEND: End Of Reception. * @arg CEC_FLAG_RXBR: Rx-Byte Received. * @retval ITStatus */ #define __HAL_CEC_GET_FLAG(__HANDLE__, __FLAG__) ((__HANDLE__)->Instance->ISR & (__FLAG__)) /** @brief Clears the interrupt or status flag when raised (write at 1) * @param __HANDLE__: specifies the CEC Handle. * @param __FLAG__: specifies the interrupt/status flag to clear. * This parameter can be one of the following values: * @arg CEC_FLAG_TXACKE: Tx Missing acknowledge Error * @arg CEC_FLAG_TXERR: Tx Error. * @arg CEC_FLAG_TXUDR: Tx-Buffer Underrun. * @arg CEC_FLAG_TXEND: End of transmission (successful transmission of the last byte). * @arg CEC_FLAG_TXBR: Tx-Byte Request. * @arg CEC_FLAG_ARBLST: Arbitration Lost * @arg CEC_FLAG_RXACKE: Rx-Missing Acknowledge * @arg CEC_FLAG_LBPE: Rx Long period Error * @arg CEC_FLAG_SBPE: Rx Short period Error * @arg CEC_FLAG_BRE: Rx Bit Rissing Error * @arg CEC_FLAG_RXOVR: Rx Overrun. * @arg CEC_FLAG_RXEND: End Of Reception. * @arg CEC_FLAG_RXBR: Rx-Byte Received. * @retval none */ #define __HAL_CEC_CLEAR_FLAG(__HANDLE__, __FLAG__) ((__HANDLE__)->Instance->ISR |= (__FLAG__)) /** @brief Enables the specified CEC interrupt. * @param __HANDLE__: specifies the CEC Handle. * @param __INTERRUPT__: specifies the CEC interrupt to enable. * This parameter can be one of the following values: * @arg CEC_IT_TXACKE: Tx Missing acknowledge Error IT Enable * @arg CEC_IT_TXERR: Tx Error IT Enable * @arg CEC_IT_TXUDR: Tx-Buffer Underrun IT Enable * @arg CEC_IT_TXEND: End of transmission IT Enable * @arg CEC_IT_TXBR: Tx-Byte Request IT Enable * @arg CEC_IT_ARBLST: Arbitration Lost IT Enable * @arg CEC_IT_RXACKE: Rx-Missing Acknowledge IT Enable * @arg CEC_IT_LBPE: Rx Long period Error IT Enable * @arg CEC_IT_SBPE: Rx Short period Error IT Enable * @arg CEC_IT_BRE: Rx Bit Rising Error IT Enable * @arg CEC_IT_RXOVR: Rx Overrun IT Enable * @arg CEC_IT_RXEND: End Of Reception IT Enable * @arg CEC_IT_RXBR: Rx-Byte Received IT Enable * @retval none */ #define __HAL_CEC_ENABLE_IT(__HANDLE__, __INTERRUPT__) ((__HANDLE__)->Instance->IER |= (__INTERRUPT__)) /** @brief Disables the specified CEC interrupt. * @param __HANDLE__: specifies the CEC Handle. * @param __INTERRUPT__: specifies the CEC interrupt to disable. * This parameter can be one of the following values: * @arg CEC_IT_TXACKE: Tx Missing acknowledge Error IT Enable * @arg CEC_IT_TXERR: Tx Error IT Enable * @arg CEC_IT_TXUDR: Tx-Buffer Underrun IT Enable * @arg CEC_IT_TXEND: End of transmission IT Enable * @arg CEC_IT_TXBR: Tx-Byte Request IT Enable * @arg CEC_IT_ARBLST: Arbitration Lost IT Enable * @arg CEC_IT_RXACKE: Rx-Missing Acknowledge IT Enable * @arg CEC_IT_LBPE: Rx Long period Error IT Enable * @arg CEC_IT_SBPE: Rx Short period Error IT Enable * @arg CEC_IT_BRE: Rx Bit Rising Error IT Enable * @arg CEC_IT_RXOVR: Rx Overrun IT Enable * @arg CEC_IT_RXEND: End Of Reception IT Enable * @arg CEC_IT_RXBR: Rx-Byte Received IT Enable * @retval none */ #define __HAL_CEC_DISABLE_IT(__HANDLE__, __INTERRUPT__) ((__HANDLE__)->Instance->IER &= (~(__INTERRUPT__))) /** @brief Checks whether or not the specified CEC interrupt is enabled. * @param __HANDLE__: specifies the CEC Handle. * @param __INTERRUPT__: specifies the CEC interrupt to check. * This parameter can be one of the following values: * @arg CEC_IT_TXACKE: Tx Missing acknowledge Error IT Enable * @arg CEC_IT_TXERR: Tx Error IT Enable * @arg CEC_IT_TXUDR: Tx-Buffer Underrun IT Enable * @arg CEC_IT_TXEND: End of transmission IT Enable * @arg CEC_IT_TXBR: Tx-Byte Request IT Enable * @arg CEC_IT_ARBLST: Arbitration Lost IT Enable * @arg CEC_IT_RXACKE: Rx-Missing Acknowledge IT Enable * @arg CEC_IT_LBPE: Rx Long period Error IT Enable * @arg CEC_IT_SBPE: Rx Short period Error IT Enable * @arg CEC_IT_BRE: Rx Bit Rising Error IT Enable * @arg CEC_IT_RXOVR: Rx Overrun IT Enable * @arg CEC_IT_RXEND: End Of Reception IT Enable * @arg CEC_IT_RXBR: Rx-Byte Received IT Enable * @retval FlagStatus */ #define __HAL_CEC_GET_IT_SOURCE(__HANDLE__, __INTERRUPT__) ((__HANDLE__)->Instance->IER & (__INTERRUPT__)) /** @brief Enables the CEC device * @param __HANDLE__: specifies the CEC Handle. * @retval none */ #define __HAL_CEC_ENABLE(__HANDLE__) ((__HANDLE__)->Instance->CR |= CEC_CR_CECEN) /** @brief Disables the CEC device * @param __HANDLE__: specifies the CEC Handle. * @retval none */ #define __HAL_CEC_DISABLE(__HANDLE__) ((__HANDLE__)->Instance->CR &= ~CEC_CR_CECEN) /** @brief Set Transmission Start flag * @param __HANDLE__: specifies the CEC Handle. * @retval none */ #define __HAL_CEC_FIRST_BYTE_TX_SET(__HANDLE__) ((__HANDLE__)->Instance->CR |= CEC_CR_TXSOM) /** @brief Set Transmission End flag * @param __HANDLE__: specifies the CEC Handle. * @retval none * If the CEC message consists of only one byte, TXEOM must be set before of TXSOM. */ #define __HAL_CEC_LAST_BYTE_TX_SET(__HANDLE__) ((__HANDLE__)->Instance->CR |= CEC_CR_TXEOM) /** @brief Get Transmission Start flag * @param __HANDLE__: specifies the CEC Handle. * @retval FlagStatus */ #define __HAL_CEC_GET_TRANSMISSION_START_FLAG(__HANDLE__) ((__HANDLE__)->Instance->CR & CEC_CR_TXSOM) /** @brief Get Transmission End flag * @param __HANDLE__: specifies the CEC Handle. * @retval FlagStatus */ #define __HAL_CEC_GET_TRANSMISSION_END_FLAG(__HANDLE__) ((__HANDLE__)->Instance->CR & CEC_CR_TXEOM) /** @brief Clear OAR register * @param __HANDLE__: specifies the CEC Handle. * @retval none */ #define __HAL_CEC_CLEAR_OAR(__HANDLE__) CLEAR_BIT((__HANDLE__)->Instance->CFGR, CEC_CFGR_OAR) /** @brief Set OAR register (without resetting previously set address in case of multi-address mode) * To reset OAR, __HAL_CEC_CLEAR_OAR() needs to be called beforehand * @param __HANDLE__: specifies the CEC Handle. * @param __ADDRESS__: Own Address value (CEC logical address is identified by bit position) * @retval none */ #define __HAL_CEC_SET_OAR(__HANDLE__,__ADDRESS__) SET_BIT((__HANDLE__)->Instance->CFGR, (__ADDRESS__)<< CEC_CFGR_OAR_LSB_POS) /** * @} */ /* Exported functions --------------------------------------------------------*/ /** @addtogroup CEC_Exported_Functions * @{ */ /** @addtogroup CEC_Exported_Functions_Group1 * @{ */ /* Initialization and de-initialization functions ****************************/ HAL_StatusTypeDef HAL_CEC_Init(CEC_HandleTypeDef *hcec); HAL_StatusTypeDef HAL_CEC_DeInit(CEC_HandleTypeDef *hcec); void HAL_CEC_MspInit(CEC_HandleTypeDef *hcec); void HAL_CEC_MspDeInit(CEC_HandleTypeDef *hcec); /** * @} */ /** @addtogroup CEC_Exported_Functions_Group2 * @{ */ /* I/O operation functions ***************************************************/ HAL_StatusTypeDef HAL_CEC_Transmit(CEC_HandleTypeDef *hcec, uint8_t DestinationAddress, uint8_t *pData, uint32_t Size, uint32_t Timeout); HAL_StatusTypeDef HAL_CEC_Receive(CEC_HandleTypeDef *hcec, uint8_t *pData, uint32_t Timeout); HAL_StatusTypeDef HAL_CEC_Transmit_IT(CEC_HandleTypeDef *hcec, uint8_t DestinationAddress, uint8_t *pData, uint32_t Size); HAL_StatusTypeDef HAL_CEC_Receive_IT(CEC_HandleTypeDef *hcec, uint8_t *pData); uint32_t HAL_CEC_GetReceivedFrameSize(CEC_HandleTypeDef *hcec); void HAL_CEC_IRQHandler(CEC_HandleTypeDef *hcec); void HAL_CEC_TxCpltCallback(CEC_HandleTypeDef *hcec); void HAL_CEC_RxCpltCallback(CEC_HandleTypeDef *hcec); void HAL_CEC_ErrorCallback(CEC_HandleTypeDef *hcec); /** * @} */ /** @addtogroup CEC_Exported_Functions_Group3 * @{ */ /* Peripheral State functions ************************************************/ HAL_CEC_StateTypeDef HAL_CEC_GetState(CEC_HandleTypeDef *hcec); uint32_t HAL_CEC_GetError(CEC_HandleTypeDef *hcec); /** * @} */ /** * @} */ /* Private types -------------------------------------------------------------*/ /** @defgroup CEC_Private_Types CEC Private Types * @{ */ /** * @} */ /* Private variables ---------------------------------------------------------*/ /** @defgroup CEC_Private_Variables CEC Private Variables * @{ */ /** * @} */ /* Private constants ---------------------------------------------------------*/ /** @defgroup CEC_Private_Constants CEC Private Constants * @{ */ /** * @} */ /* Private macros ------------------------------------------------------------*/ /** @defgroup CEC_Private_Macros CEC Private Macros * @{ */ #define IS_CEC_SIGNALFREETIME(__SFT__) ((__SFT__) <= CEC_CFGR_SFT) #define IS_CEC_TOLERANCE(__RXTOL__) (((__RXTOL__) == CEC_STANDARD_TOLERANCE) || \ ((__RXTOL__) == CEC_EXTENDED_TOLERANCE)) #define IS_CEC_BRERXSTOP(__BRERXSTOP__) (((__BRERXSTOP__) == CEC_NO_RX_STOP_ON_BRE) || \ ((__BRERXSTOP__) == CEC_RX_STOP_ON_BRE)) #define IS_CEC_BREERRORBITGEN(__ERRORBITGEN__) (((__ERRORBITGEN__) == CEC_BRE_ERRORBIT_NO_GENERATION) || \ ((__ERRORBITGEN__) == CEC_BRE_ERRORBIT_GENERATION)) #define IS_CEC_LBPEERRORBITGEN(__ERRORBITGEN__) (((__ERRORBITGEN__) == CEC_LBPE_ERRORBIT_NO_GENERATION) || \ ((__ERRORBITGEN__) == CEC_LBPE_ERRORBIT_GENERATION)) #define IS_CEC_BROADCASTERROR_NO_ERRORBIT_GENERATION(__ERRORBITGEN__) (((__ERRORBITGEN__) == CEC_BROADCASTERROR_ERRORBIT_GENERATION) || \ ((__ERRORBITGEN__) == CEC_BROADCASTERROR_NO_ERRORBIT_GENERATION)) #define IS_CEC_SFTOP(__SFTOP__) (((__SFTOP__) == CEC_SFT_START_ON_TXSOM) || \ ((__SFTOP__) == CEC_SFT_START_ON_TX_RX_END)) #define IS_CEC_LISTENING_MODE(__MODE__) (((__MODE__) == CEC_REDUCED_LISTENING_MODE) || \ ((__MODE__) == CEC_FULL_LISTENING_MODE)) /** @brief Check CEC device Own Address Register (OAR) setting. * OAR address is written in a 15-bit field within CEC_CFGR register. * @param __ADDRESS__: CEC own address. * @retval Test result (TRUE or FALSE). */ #define IS_CEC_OAR_ADDRESS(__ADDRESS__) ((__ADDRESS__) <= 0x07FFF) /** @brief Check CEC initiator or destination logical address setting. * Initiator and destination addresses are coded over 4 bits. * @param __ADDRESS__: CEC initiator or logical address. * @retval Test result (TRUE or FALSE). */ #define IS_CEC_ADDRESS(__ADDRESS__) ((__ADDRESS__) <= 0xF) /** @brief Check CEC message size. * The message size is the payload size: without counting the header, * it varies from 0 byte (ping operation, one header only, no payload) to * 15 bytes (1 opcode and up to 14 operands following the header). * @param __SIZE__: CEC message size. * @retval Test result (TRUE or FALSE). */ #define IS_CEC_MSGSIZE(__SIZE__) ((__SIZE__) <= 0xF) /** * @} */ /* Private functions ---------------------------------------------------------*/ /** @defgroup CEC_Private_Functions CEC Private Functions * @{ */ /** * @} */ /** * @} */ /** * @} */ #endif /* STM32F446xx */ #ifdef __cplusplus } #endif #endif /* __STM32F4xx_HAL_CEC_H */ /************************ (C) COPYRIGHT STMicroelectronics *****END OF FILE****/ ================================================ FILE: Zelig/mbed/TARGET_NUCLEO_F411RE/stm32f4xx_hal_conf.h ================================================ /** ****************************************************************************** * @file stm32f4xx_hal_conf.h * @author MCD Application Team * @version V1.1.0 * @date 26-December-2014 * @brief HAL configuration file ****************************************************************************** * @attention * *

© COPYRIGHT(c) 2014 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. * ****************************************************************************** */ /* Define to prevent recursive inclusion -------------------------------------*/ #ifndef __STM32F4xx_HAL_CONF_H #define __STM32F4xx_HAL_CONF_H #ifdef __cplusplus extern "C" { #endif /* Exported types ------------------------------------------------------------*/ /* Exported constants --------------------------------------------------------*/ /* ########################## Module Selection ############################## */ /** * @brief This is the list of modules to be used in the HAL driver */ #define HAL_MODULE_ENABLED #define HAL_ADC_MODULE_ENABLED #define HAL_CAN_MODULE_ENABLED #define HAL_CRC_MODULE_ENABLED #define HAL_CRYP_MODULE_ENABLED #define HAL_DAC_MODULE_ENABLED #define HAL_DCMI_MODULE_ENABLED #define HAL_DMA_MODULE_ENABLED /* #define HAL_DMA2D_MODULE_ENABLED */ #define HAL_ETH_MODULE_ENABLED #define HAL_FLASH_MODULE_ENABLED #define HAL_NAND_MODULE_ENABLED #define HAL_NOR_MODULE_ENABLED #define HAL_PCCARD_MODULE_ENABLED #define HAL_SRAM_MODULE_ENABLED /* #define HAL_SDRAM_MODULE_ENABLED */ #define HAL_HASH_MODULE_ENABLED #define HAL_GPIO_MODULE_ENABLED #define HAL_I2C_MODULE_ENABLED #define HAL_I2S_MODULE_ENABLED #define HAL_IWDG_MODULE_ENABLED #define HAL_LTDC_MODULE_ENABLED #define HAL_PWR_MODULE_ENABLED #define HAL_RCC_MODULE_ENABLED #define HAL_RNG_MODULE_ENABLED #define HAL_RTC_MODULE_ENABLED /* #define HAL_SAI_MODULE_ENABLED */ #define HAL_SD_MODULE_ENABLED #define HAL_SPI_MODULE_ENABLED #define HAL_TIM_MODULE_ENABLED #define HAL_UART_MODULE_ENABLED #define HAL_USART_MODULE_ENABLED #define HAL_IRDA_MODULE_ENABLED #define HAL_SMARTCARD_MODULE_ENABLED #define HAL_WWDG_MODULE_ENABLED #define HAL_CORTEX_MODULE_ENABLED #define HAL_PCD_MODULE_ENABLED #define HAL_HCD_MODULE_ENABLED /* ########################## HSE/HSI Values adaptation ##################### */ /** * @brief Adjust the value of External High Speed oscillator (HSE) used in your application. * This value is used by the RCC HAL module to compute the system frequency * (when HSE is used as system clock source, directly or through the PLL). */ #if !defined (HSE_VALUE) #define HSE_VALUE ((uint32_t)8000000) /*!< Value of the External oscillator in Hz */ #endif /* HSE_VALUE */ #if !defined (HSE_STARTUP_TIMEOUT) #define HSE_STARTUP_TIMEOUT ((uint32_t)200) /*!< Time out for HSE start up, in ms */ #endif /* HSE_STARTUP_TIMEOUT */ /** * @brief Internal High Speed oscillator (HSI) value. * This value is used by the RCC HAL module to compute the system frequency * (when HSI is used as system clock source, directly or through the PLL). */ #if !defined (HSI_VALUE) #define HSI_VALUE ((uint32_t)16000000) /*!< Value of the Internal oscillator in Hz*/ #endif /* HSI_VALUE */ /** * @brief Internal Low Speed oscillator (LSI) value. */ #if !defined (LSI_VALUE) #define LSI_VALUE ((uint32_t)32000) #endif /* LSI_VALUE */ /*!< Value of the Internal Low Speed oscillator in Hz The real value may vary depending on the variations in voltage and temperature. */ /** * @brief External Low Speed oscillator (LSE) value. */ #if !defined (LSE_VALUE) #define LSE_VALUE ((uint32_t)32768) /*!< Value of the External Low Speed oscillator in Hz */ #endif /* LSE_VALUE */ /** * @brief External clock source for I2S peripheral * This value is used by the I2S HAL module to compute the I2S clock source * frequency, this source is inserted directly through I2S_CKIN pad. */ #if !defined (EXTERNAL_CLOCK_VALUE) #define EXTERNAL_CLOCK_VALUE ((uint32_t)12288000) /*!< Value of the Internal oscillator in Hz*/ #endif /* EXTERNAL_CLOCK_VALUE */ /* Tip: To avoid modifying this file each time you need to use different HSE, === you can define the HSE value in your toolchain compiler preprocessor. */ /* ########################### System Configuration ######################### */ /** * @brief This is the HAL system configuration section */ #define VDD_VALUE ((uint32_t)3300) /*!< Value of VDD in mv */ #define TICK_INT_PRIORITY ((uint32_t)0x0F) /*!< tick interrupt priority */ #define USE_RTOS 0 #define PREFETCH_ENABLE 1 #define INSTRUCTION_CACHE_ENABLE 1 #define DATA_CACHE_ENABLE 1 /* ########################## Assert Selection ############################## */ /** * @brief Uncomment the line below to expanse the "assert_param" macro in the * HAL drivers code */ /* #define USE_FULL_ASSERT 1 */ /* ################## Ethernet peripheral configuration ##################### */ /* Section 1 : Ethernet peripheral configuration */ /* MAC ADDRESS: MAC_ADDR0:MAC_ADDR1:MAC_ADDR2:MAC_ADDR3:MAC_ADDR4:MAC_ADDR5 */ #define MAC_ADDR0 2 #define MAC_ADDR1 0 #define MAC_ADDR2 0 #define MAC_ADDR3 0 #define MAC_ADDR4 0 #define MAC_ADDR5 0 /* Definition of the Ethernet driver buffers size and count */ #define ETH_RX_BUF_SIZE ETH_MAX_PACKET_SIZE /* buffer size for receive */ #define ETH_TX_BUF_SIZE ETH_MAX_PACKET_SIZE /* buffer size for transmit */ #define ETH_RXBUFNB ((uint32_t)4) /* 4 Rx buffers of size ETH_RX_BUF_SIZE */ #define ETH_TXBUFNB ((uint32_t)4) /* 4 Tx buffers of size ETH_TX_BUF_SIZE */ /* Section 2: PHY configuration section */ /* DP83848 PHY Address*/ #define DP83848_PHY_ADDRESS 0x01 /* PHY Reset delay these values are based on a 1 ms Systick interrupt*/ #define PHY_RESET_DELAY ((uint32_t)0x000000FF) /* PHY Configuration delay */ #define PHY_CONFIG_DELAY ((uint32_t)0x00000FFF) #define PHY_READ_TO ((uint32_t)0x0000FFFF) #define PHY_WRITE_TO ((uint32_t)0x0000FFFF) /* Section 3: Common PHY Registers */ #define PHY_BCR ((uint16_t)0x00) /*!< Transceiver Basic Control Register */ #define PHY_BSR ((uint16_t)0x01) /*!< Transceiver Basic Status Register */ #define PHY_RESET ((uint16_t)0x8000) /*!< PHY Reset */ #define PHY_LOOPBACK ((uint16_t)0x4000) /*!< Select loop-back mode */ #define PHY_FULLDUPLEX_100M ((uint16_t)0x2100) /*!< Set the full-duplex mode at 100 Mb/s */ #define PHY_HALFDUPLEX_100M ((uint16_t)0x2000) /*!< Set the half-duplex mode at 100 Mb/s */ #define PHY_FULLDUPLEX_10M ((uint16_t)0x0100) /*!< Set the full-duplex mode at 10 Mb/s */ #define PHY_HALFDUPLEX_10M ((uint16_t)0x0000) /*!< Set the half-duplex mode at 10 Mb/s */ #define PHY_AUTONEGOTIATION ((uint16_t)0x1000) /*!< Enable auto-negotiation function */ #define PHY_RESTART_AUTONEGOTIATION ((uint16_t)0x0200) /*!< Restart auto-negotiation function */ #define PHY_POWERDOWN ((uint16_t)0x0800) /*!< Select the power down mode */ #define PHY_ISOLATE ((uint16_t)0x0400) /*!< Isolate PHY from MII */ #define PHY_AUTONEGO_COMPLETE ((uint16_t)0x0020) /*!< Auto-Negotiation process completed */ #define PHY_LINKED_STATUS ((uint16_t)0x0004) /*!< Valid link established */ #define PHY_JABBER_DETECTION ((uint16_t)0x0002) /*!< Jabber condition detected */ /* Section 4: Extended PHY Registers */ #define PHY_SR ((uint16_t)0x10) /*!< PHY status register Offset */ #define PHY_MICR ((uint16_t)0x11) /*!< MII Interrupt Control Register */ #define PHY_MISR ((uint16_t)0x12) /*!< MII Interrupt Status and Misc. Control Register */ #define PHY_LINK_STATUS ((uint16_t)0x0001) /*!< PHY Link mask */ #define PHY_SPEED_STATUS ((uint16_t)0x0002) /*!< PHY Speed mask */ #define PHY_DUPLEX_STATUS ((uint16_t)0x0004) /*!< PHY Duplex mask */ #define PHY_MICR_INT_EN ((uint16_t)0x0002) /*!< PHY Enable interrupts */ #define PHY_MICR_INT_OE ((uint16_t)0x0001) /*!< PHY Enable output interrupt events */ #define PHY_MISR_LINK_INT_EN ((uint16_t)0x0020) /*!< Enable Interrupt on change of link status */ #define PHY_LINK_INTERRUPT ((uint16_t)0x2000) /*!< PHY link status interrupt mask */ /* Includes ------------------------------------------------------------------*/ /** * @brief Include module's header file */ #ifdef HAL_RCC_MODULE_ENABLED #include "stm32f4xx_hal_rcc.h" #endif /* HAL_RCC_MODULE_ENABLED */ #ifdef HAL_GPIO_MODULE_ENABLED #include "stm32f4xx_hal_gpio.h" #endif /* HAL_GPIO_MODULE_ENABLED */ #ifdef HAL_DMA_MODULE_ENABLED #include "stm32f4xx_hal_dma.h" #endif /* HAL_DMA_MODULE_ENABLED */ #ifdef HAL_CORTEX_MODULE_ENABLED #include "stm32f4xx_hal_cortex.h" #endif /* HAL_CORTEX_MODULE_ENABLED */ #ifdef HAL_ADC_MODULE_ENABLED #include "stm32f4xx_hal_adc.h" #endif /* HAL_ADC_MODULE_ENABLED */ #ifdef HAL_CAN_MODULE_ENABLED #include "stm32f4xx_hal_can.h" #endif /* HAL_CAN_MODULE_ENABLED */ #ifdef HAL_CRC_MODULE_ENABLED #include "stm32f4xx_hal_crc.h" #endif /* HAL_CRC_MODULE_ENABLED */ #ifdef HAL_CRYP_MODULE_ENABLED #include "stm32f4xx_hal_cryp.h" #endif /* HAL_CRYP_MODULE_ENABLED */ #ifdef HAL_DMA2D_MODULE_ENABLED #include "stm32f4xx_hal_dma2d.h" #endif /* HAL_DMA2D_MODULE_ENABLED */ #ifdef HAL_DAC_MODULE_ENABLED #include "stm32f4xx_hal_dac.h" #endif /* HAL_DAC_MODULE_ENABLED */ #ifdef HAL_DCMI_MODULE_ENABLED #include "stm32f4xx_hal_dcmi.h" #endif /* HAL_DCMI_MODULE_ENABLED */ #ifdef HAL_ETH_MODULE_ENABLED #include "stm32f4xx_hal_eth.h" #endif /* HAL_ETH_MODULE_ENABLED */ #ifdef HAL_FLASH_MODULE_ENABLED #include "stm32f4xx_hal_flash.h" #endif /* HAL_FLASH_MODULE_ENABLED */ #ifdef HAL_SRAM_MODULE_ENABLED #include "stm32f4xx_hal_sram.h" #endif /* HAL_SRAM_MODULE_ENABLED */ #ifdef HAL_NOR_MODULE_ENABLED #include "stm32f4xx_hal_nor.h" #endif /* HAL_NOR_MODULE_ENABLED */ #ifdef HAL_NAND_MODULE_ENABLED #include "stm32f4xx_hal_nand.h" #endif /* HAL_NAND_MODULE_ENABLED */ #ifdef HAL_PCCARD_MODULE_ENABLED #include "stm32f4xx_hal_pccard.h" #endif /* HAL_PCCARD_MODULE_ENABLED */ #ifdef HAL_SDRAM_MODULE_ENABLED #include "stm32f4xx_hal_sdram.h" #endif /* HAL_SDRAM_MODULE_ENABLED */ #ifdef HAL_HASH_MODULE_ENABLED #include "stm32f4xx_hal_hash.h" #endif /* HAL_HASH_MODULE_ENABLED */ #ifdef HAL_I2C_MODULE_ENABLED #include "stm32f4xx_hal_i2c.h" #endif /* HAL_I2C_MODULE_ENABLED */ #ifdef HAL_I2S_MODULE_ENABLED #include "stm32f4xx_hal_i2s.h" #endif /* HAL_I2S_MODULE_ENABLED */ #ifdef HAL_IWDG_MODULE_ENABLED #include "stm32f4xx_hal_iwdg.h" #endif /* HAL_IWDG_MODULE_ENABLED */ #ifdef HAL_LTDC_MODULE_ENABLED #include "stm32f4xx_hal_ltdc.h" #endif /* HAL_LTDC_MODULE_ENABLED */ #ifdef HAL_PWR_MODULE_ENABLED #include "stm32f4xx_hal_pwr.h" #endif /* HAL_PWR_MODULE_ENABLED */ #ifdef HAL_RNG_MODULE_ENABLED #include "stm32f4xx_hal_rng.h" #endif /* HAL_RNG_MODULE_ENABLED */ #ifdef HAL_RTC_MODULE_ENABLED #include "stm32f4xx_hal_rtc.h" #endif /* HAL_RTC_MODULE_ENABLED */ #ifdef HAL_SAI_MODULE_ENABLED #include "stm32f4xx_hal_sai.h" #endif /* HAL_SAI_MODULE_ENABLED */ #ifdef HAL_SD_MODULE_ENABLED #include "stm32f4xx_hal_sd.h" #endif /* HAL_SD_MODULE_ENABLED */ #ifdef HAL_SPI_MODULE_ENABLED #include "stm32f4xx_hal_spi.h" #endif /* HAL_SPI_MODULE_ENABLED */ #ifdef HAL_TIM_MODULE_ENABLED #include "stm32f4xx_hal_tim.h" #endif /* HAL_TIM_MODULE_ENABLED */ #ifdef HAL_UART_MODULE_ENABLED #include "stm32f4xx_hal_uart.h" #endif /* HAL_UART_MODULE_ENABLED */ #ifdef HAL_USART_MODULE_ENABLED #include "stm32f4xx_hal_usart.h" #endif /* HAL_USART_MODULE_ENABLED */ #ifdef HAL_IRDA_MODULE_ENABLED #include "stm32f4xx_hal_irda.h" #endif /* HAL_IRDA_MODULE_ENABLED */ #ifdef HAL_SMARTCARD_MODULE_ENABLED #include "stm32f4xx_hal_smartcard.h" #endif /* HAL_SMARTCARD_MODULE_ENABLED */ #ifdef HAL_WWDG_MODULE_ENABLED #include "stm32f4xx_hal_wwdg.h" #endif /* HAL_WWDG_MODULE_ENABLED */ #ifdef HAL_PCD_MODULE_ENABLED #include "stm32f4xx_hal_pcd.h" #endif /* HAL_PCD_MODULE_ENABLED */ #ifdef HAL_HCD_MODULE_ENABLED #include "stm32f4xx_hal_hcd.h" #endif /* HAL_HCD_MODULE_ENABLED */ /* Exported macro ------------------------------------------------------------*/ #ifdef USE_FULL_ASSERT /** * @brief The assert_param macro is used for function's parameters check. * @param expr: If expr is false, it calls assert_failed function * which reports the name of the source file and the source * line number of the call that failed. * If expr is true, it returns no value. * @retval None */ #define assert_param(expr) ((expr) ? (void)0 : assert_failed((uint8_t *)__FILE__, __LINE__)) /* Exported functions ------------------------------------------------------- */ void assert_failed(uint8_t* file, uint32_t line); #else #define assert_param(expr) ((void)0) #endif /* USE_FULL_ASSERT */ #ifdef __cplusplus } #endif #endif /* __STM32F4xx_HAL_CONF_H */ /************************ (C) COPYRIGHT STMicroelectronics *****END OF FILE****/ ================================================ FILE: Zelig/mbed/TARGET_NUCLEO_F411RE/stm32f4xx_hal_conf_template.h ================================================ /** ****************************************************************************** * @file stm32f4xx_hal_conf_template.h * @author MCD Application Team * @version V1.4.1 * @date 09-October-2015 * @brief HAL configuration template file. * This file should be copied to the application folder and renamed * to stm32f4xx_hal_conf.h. ****************************************************************************** * @attention * *

© COPYRIGHT(c) 2015 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. * ****************************************************************************** */ /* Define to prevent recursive inclusion -------------------------------------*/ #ifndef __STM32F4xx_HAL_CONF_H #define __STM32F4xx_HAL_CONF_H #ifdef __cplusplus extern "C" { #endif /* Exported types ------------------------------------------------------------*/ /* Exported constants --------------------------------------------------------*/ /* ########################## Module Selection ############################## */ /** * @brief This is the list of modules to be used in the HAL driver */ #define HAL_MODULE_ENABLED #define HAL_ADC_MODULE_ENABLED #define HAL_CAN_MODULE_ENABLED #define HAL_CRC_MODULE_ENABLED #define HAL_CEC_MODULE_ENABLED #define HAL_CRYP_MODULE_ENABLED #define HAL_DAC_MODULE_ENABLED #define HAL_DCMI_MODULE_ENABLED #define HAL_DMA_MODULE_ENABLED #define HAL_DMA2D_MODULE_ENABLED #define HAL_ETH_MODULE_ENABLED #define HAL_FLASH_MODULE_ENABLED #define HAL_NAND_MODULE_ENABLED #define HAL_NOR_MODULE_ENABLED #define HAL_PCCARD_MODULE_ENABLED #define HAL_SRAM_MODULE_ENABLED #define HAL_SDRAM_MODULE_ENABLED #define HAL_HASH_MODULE_ENABLED #define HAL_GPIO_MODULE_ENABLED #define HAL_I2C_MODULE_ENABLED #define HAL_I2S_MODULE_ENABLED #define HAL_IWDG_MODULE_ENABLED #define HAL_LTDC_MODULE_ENABLED #define HAL_DSI_MODULE_ENABLED #define HAL_PWR_MODULE_ENABLED #define HAL_QSPI_MODULE_ENABLED #define HAL_RCC_MODULE_ENABLED #define HAL_RNG_MODULE_ENABLED #define HAL_RTC_MODULE_ENABLED #define HAL_SAI_MODULE_ENABLED #define HAL_SD_MODULE_ENABLED #define HAL_SPI_MODULE_ENABLED #define HAL_TIM_MODULE_ENABLED #define HAL_UART_MODULE_ENABLED #define HAL_USART_MODULE_ENABLED #define HAL_IRDA_MODULE_ENABLED #define HAL_SMARTCARD_MODULE_ENABLED #define HAL_WWDG_MODULE_ENABLED #define HAL_CORTEX_MODULE_ENABLED #define HAL_PCD_MODULE_ENABLED #define HAL_HCD_MODULE_ENABLED #define HAL_FMPI2C_MODULE_ENABLED #define HAL_SPDIFRX_MODULE_ENABLED #define HAL_LPTIM_MODULE_ENABLED /* ########################## HSE/HSI Values adaptation ##################### */ /** * @brief Adjust the value of External High Speed oscillator (HSE) used in your application. * This value is used by the RCC HAL module to compute the system frequency * (when HSE is used as system clock source, directly or through the PLL). */ #if !defined (HSE_VALUE) #define HSE_VALUE ((uint32_t)25000000) /*!< Value of the External oscillator in Hz */ #endif /* HSE_VALUE */ #if !defined (HSE_STARTUP_TIMEOUT) #define HSE_STARTUP_TIMEOUT ((uint32_t)5000) /*!< Time out for HSE start up, in ms */ #endif /* HSE_STARTUP_TIMEOUT */ /** * @brief Internal High Speed oscillator (HSI) value. * This value is used by the RCC HAL module to compute the system frequency * (when HSI is used as system clock source, directly or through the PLL). */ #if !defined (HSI_VALUE) #define HSI_VALUE ((uint32_t)16000000) /*!< Value of the Internal oscillator in Hz*/ #endif /* HSI_VALUE */ /** * @brief Internal Low Speed oscillator (LSI) value. */ #if !defined (LSI_VALUE) #define LSI_VALUE ((uint32_t)32000) /*!< LSI Typical Value in Hz*/ #endif /* LSI_VALUE */ /*!< Value of the Internal Low Speed oscillator in Hz The real value may vary depending on the variations in voltage and temperature.*/ /** * @brief External Low Speed oscillator (LSE) value. */ #if !defined (LSE_VALUE) #define LSE_VALUE ((uint32_t)32768) /*!< Value of the External Low Speed oscillator in Hz */ #endif /* LSE_VALUE */ /** * @brief External clock source for I2S peripheral * This value is used by the I2S HAL module to compute the I2S clock source * frequency, this source is inserted directly through I2S_CKIN pad. */ #if !defined (EXTERNAL_CLOCK_VALUE) #define EXTERNAL_CLOCK_VALUE ((uint32_t)12288000) /*!< Value of the Internal oscillator in Hz*/ #endif /* EXTERNAL_CLOCK_VALUE */ /* Tip: To avoid modifying this file each time you need to use different HSE, === you can define the HSE value in your toolchain compiler preprocessor. */ /* ########################### System Configuration ######################### */ /** * @brief This is the HAL system configuration section */ #define VDD_VALUE ((uint32_t)3300) /*!< Value of VDD in mv */ #define TICK_INT_PRIORITY ((uint32_t)0x0F) /*!< tick interrupt priority */ #define USE_RTOS 0 #define PREFETCH_ENABLE 1 #define INSTRUCTION_CACHE_ENABLE 1 #define DATA_CACHE_ENABLE 1 /* ########################## Assert Selection ############################## */ /** * @brief Uncomment the line below to expanse the "assert_param" macro in the * HAL drivers code */ /* #define USE_FULL_ASSERT 1 */ /* ################## Ethernet peripheral configuration ##################### */ /* Section 1 : Ethernet peripheral configuration */ /* MAC ADDRESS: MAC_ADDR0:MAC_ADDR1:MAC_ADDR2:MAC_ADDR3:MAC_ADDR4:MAC_ADDR5 */ #define MAC_ADDR0 2 #define MAC_ADDR1 0 #define MAC_ADDR2 0 #define MAC_ADDR3 0 #define MAC_ADDR4 0 #define MAC_ADDR5 0 /* Definition of the Ethernet driver buffers size and count */ #define ETH_RX_BUF_SIZE ETH_MAX_PACKET_SIZE /* buffer size for receive */ #define ETH_TX_BUF_SIZE ETH_MAX_PACKET_SIZE /* buffer size for transmit */ #define ETH_RXBUFNB ((uint32_t)4) /* 4 Rx buffers of size ETH_RX_BUF_SIZE */ #define ETH_TXBUFNB ((uint32_t)4) /* 4 Tx buffers of size ETH_TX_BUF_SIZE */ /* Section 2: PHY configuration section */ /* DP83848 PHY Address*/ #define DP83848_PHY_ADDRESS 0x01 /* PHY Reset delay these values are based on a 1 ms Systick interrupt*/ #define PHY_RESET_DELAY ((uint32_t)0x000000FF) /* PHY Configuration delay */ #define PHY_CONFIG_DELAY ((uint32_t)0x00000FFF) #define PHY_READ_TO ((uint32_t)0x0000FFFF) #define PHY_WRITE_TO ((uint32_t)0x0000FFFF) /* Section 3: Common PHY Registers */ #define PHY_BCR ((uint16_t)0x00) /*!< Transceiver Basic Control Register */ #define PHY_BSR ((uint16_t)0x01) /*!< Transceiver Basic Status Register */ #define PHY_RESET ((uint16_t)0x8000) /*!< PHY Reset */ #define PHY_LOOPBACK ((uint16_t)0x4000) /*!< Select loop-back mode */ #define PHY_FULLDUPLEX_100M ((uint16_t)0x2100) /*!< Set the full-duplex mode at 100 Mb/s */ #define PHY_HALFDUPLEX_100M ((uint16_t)0x2000) /*!< Set the half-duplex mode at 100 Mb/s */ #define PHY_FULLDUPLEX_10M ((uint16_t)0x0100) /*!< Set the full-duplex mode at 10 Mb/s */ #define PHY_HALFDUPLEX_10M ((uint16_t)0x0000) /*!< Set the half-duplex mode at 10 Mb/s */ #define PHY_AUTONEGOTIATION ((uint16_t)0x1000) /*!< Enable auto-negotiation function */ #define PHY_RESTART_AUTONEGOTIATION ((uint16_t)0x0200) /*!< Restart auto-negotiation function */ #define PHY_POWERDOWN ((uint16_t)0x0800) /*!< Select the power down mode */ #define PHY_ISOLATE ((uint16_t)0x0400) /*!< Isolate PHY from MII */ #define PHY_AUTONEGO_COMPLETE ((uint16_t)0x0020) /*!< Auto-Negotiation process completed */ #define PHY_LINKED_STATUS ((uint16_t)0x0004) /*!< Valid link established */ #define PHY_JABBER_DETECTION ((uint16_t)0x0002) /*!< Jabber condition detected */ /* Section 4: Extended PHY Registers */ #define PHY_SR ((uint16_t)0x10) /*!< PHY status register Offset */ #define PHY_MICR ((uint16_t)0x11) /*!< MII Interrupt Control Register */ #define PHY_MISR ((uint16_t)0x12) /*!< MII Interrupt Status and Misc. Control Register */ #define PHY_LINK_STATUS ((uint16_t)0x0001) /*!< PHY Link mask */ #define PHY_SPEED_STATUS ((uint16_t)0x0002) /*!< PHY Speed mask */ #define PHY_DUPLEX_STATUS ((uint16_t)0x0004) /*!< PHY Duplex mask */ #define PHY_MICR_INT_EN ((uint16_t)0x0002) /*!< PHY Enable interrupts */ #define PHY_MICR_INT_OE ((uint16_t)0x0001) /*!< PHY Enable output interrupt events */ #define PHY_MISR_LINK_INT_EN ((uint16_t)0x0020) /*!< Enable Interrupt on change of link status */ #define PHY_LINK_INTERRUPT ((uint16_t)0x2000) /*!< PHY link status interrupt mask */ /* Includes ------------------------------------------------------------------*/ /** * @brief Include module's header file */ #ifdef HAL_RCC_MODULE_ENABLED #include "stm32f4xx_hal_rcc.h" #endif /* HAL_RCC_MODULE_ENABLED */ #ifdef HAL_GPIO_MODULE_ENABLED #include "stm32f4xx_hal_gpio.h" #endif /* HAL_GPIO_MODULE_ENABLED */ #ifdef HAL_DMA_MODULE_ENABLED #include "stm32f4xx_hal_dma.h" #endif /* HAL_DMA_MODULE_ENABLED */ #ifdef HAL_CORTEX_MODULE_ENABLED #include "stm32f4xx_hal_cortex.h" #endif /* HAL_CORTEX_MODULE_ENABLED */ #ifdef HAL_ADC_MODULE_ENABLED #include "stm32f4xx_hal_adc.h" #endif /* HAL_ADC_MODULE_ENABLED */ #ifdef HAL_CAN_MODULE_ENABLED #include "stm32f4xx_hal_can.h" #endif /* HAL_CAN_MODULE_ENABLED */ #ifdef HAL_CRC_MODULE_ENABLED #include "stm32f4xx_hal_crc.h" #endif /* HAL_CRC_MODULE_ENABLED */ #ifdef HAL_CRYP_MODULE_ENABLED #include "stm32f4xx_hal_cryp.h" #endif /* HAL_CRYP_MODULE_ENABLED */ #ifdef HAL_DMA2D_MODULE_ENABLED #include "stm32f4xx_hal_dma2d.h" #endif /* HAL_DMA2D_MODULE_ENABLED */ #ifdef HAL_DAC_MODULE_ENABLED #include "stm32f4xx_hal_dac.h" #endif /* HAL_DAC_MODULE_ENABLED */ #ifdef HAL_DCMI_MODULE_ENABLED #include "stm32f4xx_hal_dcmi.h" #endif /* HAL_DCMI_MODULE_ENABLED */ #ifdef HAL_ETH_MODULE_ENABLED #include "stm32f4xx_hal_eth.h" #endif /* HAL_ETH_MODULE_ENABLED */ #ifdef HAL_FLASH_MODULE_ENABLED #include "stm32f4xx_hal_flash.h" #endif /* HAL_FLASH_MODULE_ENABLED */ #ifdef HAL_SRAM_MODULE_ENABLED #include "stm32f4xx_hal_sram.h" #endif /* HAL_SRAM_MODULE_ENABLED */ #ifdef HAL_NOR_MODULE_ENABLED #include "stm32f4xx_hal_nor.h" #endif /* HAL_NOR_MODULE_ENABLED */ #ifdef HAL_NAND_MODULE_ENABLED #include "stm32f4xx_hal_nand.h" #endif /* HAL_NAND_MODULE_ENABLED */ #ifdef HAL_PCCARD_MODULE_ENABLED #include "stm32f4xx_hal_pccard.h" #endif /* HAL_PCCARD_MODULE_ENABLED */ #ifdef HAL_SDRAM_MODULE_ENABLED #include "stm32f4xx_hal_sdram.h" #endif /* HAL_SDRAM_MODULE_ENABLED */ #ifdef HAL_HASH_MODULE_ENABLED #include "stm32f4xx_hal_hash.h" #endif /* HAL_HASH_MODULE_ENABLED */ #ifdef HAL_I2C_MODULE_ENABLED #include "stm32f4xx_hal_i2c.h" #endif /* HAL_I2C_MODULE_ENABLED */ #ifdef HAL_I2S_MODULE_ENABLED #include "stm32f4xx_hal_i2s.h" #endif /* HAL_I2S_MODULE_ENABLED */ #ifdef HAL_IWDG_MODULE_ENABLED #include "stm32f4xx_hal_iwdg.h" #endif /* HAL_IWDG_MODULE_ENABLED */ #ifdef HAL_LTDC_MODULE_ENABLED #include "stm32f4xx_hal_ltdc.h" #endif /* HAL_LTDC_MODULE_ENABLED */ #ifdef HAL_PWR_MODULE_ENABLED #include "stm32f4xx_hal_pwr.h" #endif /* HAL_PWR_MODULE_ENABLED */ #ifdef HAL_RNG_MODULE_ENABLED #include "stm32f4xx_hal_rng.h" #endif /* HAL_RNG_MODULE_ENABLED */ #ifdef HAL_RTC_MODULE_ENABLED #include "stm32f4xx_hal_rtc.h" #endif /* HAL_RTC_MODULE_ENABLED */ #ifdef HAL_SAI_MODULE_ENABLED #include "stm32f4xx_hal_sai.h" #endif /* HAL_SAI_MODULE_ENABLED */ #ifdef HAL_SD_MODULE_ENABLED #include "stm32f4xx_hal_sd.h" #endif /* HAL_SD_MODULE_ENABLED */ #ifdef HAL_SPI_MODULE_ENABLED #include "stm32f4xx_hal_spi.h" #endif /* HAL_SPI_MODULE_ENABLED */ #ifdef HAL_TIM_MODULE_ENABLED #include "stm32f4xx_hal_tim.h" #endif /* HAL_TIM_MODULE_ENABLED */ #ifdef HAL_UART_MODULE_ENABLED #include "stm32f4xx_hal_uart.h" #endif /* HAL_UART_MODULE_ENABLED */ #ifdef HAL_USART_MODULE_ENABLED #include "stm32f4xx_hal_usart.h" #endif /* HAL_USART_MODULE_ENABLED */ #ifdef HAL_IRDA_MODULE_ENABLED #include "stm32f4xx_hal_irda.h" #endif /* HAL_IRDA_MODULE_ENABLED */ #ifdef HAL_SMARTCARD_MODULE_ENABLED #include "stm32f4xx_hal_smartcard.h" #endif /* HAL_SMARTCARD_MODULE_ENABLED */ #ifdef HAL_WWDG_MODULE_ENABLED #include "stm32f4xx_hal_wwdg.h" #endif /* HAL_WWDG_MODULE_ENABLED */ #ifdef HAL_PCD_MODULE_ENABLED #include "stm32f4xx_hal_pcd.h" #endif /* HAL_PCD_MODULE_ENABLED */ #ifdef HAL_HCD_MODULE_ENABLED #include "stm32f4xx_hal_hcd.h" #endif /* HAL_HCD_MODULE_ENABLED */ #ifdef HAL_DSI_MODULE_ENABLED #include "stm32f4xx_hal_dsi.h" #endif /* HAL_DSI_MODULE_ENABLED */ #ifdef HAL_QSPI_MODULE_ENABLED #include "stm32f4xx_hal_qspi.h" #endif /* HAL_QSPI_MODULE_ENABLED */ #ifdef HAL_CEC_MODULE_ENABLED #include "stm32f4xx_hal_cec.h" #endif /* HAL_CEC_MODULE_ENABLED */ #ifdef HAL_FMPI2C_MODULE_ENABLED #include "stm32f4xx_hal_fmpi2c.h" #endif /* HAL_FMPI2C_MODULE_ENABLED */ #ifdef HAL_SPDIFRX_MODULE_ENABLED #include "stm32f4xx_hal_spdifrx.h" #endif /* HAL_SPDIFRX_MODULE_ENABLED */ #ifdef HAL_LPTIM_MODULE_ENABLED #include "stm32f4xx_hal_lptim.h" #endif /* HAL_LPTIM_MODULE_ENABLED */ /* Exported macro ------------------------------------------------------------*/ #ifdef USE_FULL_ASSERT /** * @brief The assert_param macro is used for function's parameters check. * @param expr: If expr is false, it calls assert_failed function * which reports the name of the source file and the source * line number of the call that failed. * If expr is true, it returns no value. * @retval None */ #define assert_param(expr) ((expr) ? (void)0 : assert_failed((uint8_t *)__FILE__, __LINE__)) /* Exported functions ------------------------------------------------------- */ void assert_failed(uint8_t* file, uint32_t line); #else #define assert_param(expr) ((void)0) #endif /* USE_FULL_ASSERT */ #ifdef __cplusplus } #endif #endif /* __STM32F4xx_HAL_CONF_H */ /************************ (C) COPYRIGHT STMicroelectronics *****END OF FILE****/ ================================================ FILE: Zelig/mbed/TARGET_NUCLEO_F411RE/stm32f4xx_hal_cortex.h ================================================ /** ****************************************************************************** * @file stm32f4xx_hal_cortex.h * @author MCD Application Team * @version V1.4.1 * @date 09-October-2015 * @brief Header file of CORTEX HAL module. ****************************************************************************** * @attention * *

© COPYRIGHT(c) 2015 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. * ****************************************************************************** */ /* Define to prevent recursive inclusion -------------------------------------*/ #ifndef __STM32F4xx_HAL_CORTEX_H #define __STM32F4xx_HAL_CORTEX_H #ifdef __cplusplus extern "C" { #endif /* Includes ------------------------------------------------------------------*/ #include "stm32f4xx_hal_def.h" /** @addtogroup STM32F4xx_HAL_Driver * @{ */ /** @addtogroup CORTEX * @{ */ /* Exported types ------------------------------------------------------------*/ /** @defgroup CORTEX_Exported_Types Cortex Exported Types * @{ */ #if (__MPU_PRESENT == 1) /** @defgroup CORTEX_MPU_Region_Initialization_Structure_definition MPU Region Initialization Structure Definition * @brief MPU Region initialization structure * @{ */ typedef struct { uint8_t Enable; /*!< Specifies the status of the region. This parameter can be a value of @ref CORTEX_MPU_Region_Enable */ uint8_t Number; /*!< Specifies the number of the region to protect. This parameter can be a value of @ref CORTEX_MPU_Region_Number */ uint32_t BaseAddress; /*!< Specifies the base address of the region to protect. */ uint8_t Size; /*!< Specifies the size of the region to protect. This parameter can be a value of @ref CORTEX_MPU_Region_Size */ uint8_t SubRegionDisable; /*!< Specifies the number of the subregion protection to disable. This parameter must be a number between Min_Data = 0x00 and Max_Data = 0xFF */ uint8_t TypeExtField; /*!< Specifies the TEX field level. This parameter can be a value of @ref CORTEX_MPU_TEX_Levels */ uint8_t AccessPermission; /*!< Specifies the region access permission type. This parameter can be a value of @ref CORTEX_MPU_Region_Permission_Attributes */ uint8_t DisableExec; /*!< Specifies the instruction access status. This parameter can be a value of @ref CORTEX_MPU_Instruction_Access */ uint8_t IsShareable; /*!< Specifies the shareability status of the protected region. This parameter can be a value of @ref CORTEX_MPU_Access_Shareable */ uint8_t IsCacheable; /*!< Specifies the cacheable status of the region protected. This parameter can be a value of @ref CORTEX_MPU_Access_Cacheable */ uint8_t IsBufferable; /*!< Specifies the bufferable status of the protected region. This parameter can be a value of @ref CORTEX_MPU_Access_Bufferable */ }MPU_Region_InitTypeDef; /** * @} */ #endif /* __MPU_PRESENT */ /** * @} */ /* Exported constants --------------------------------------------------------*/ /** @defgroup CORTEX_Exported_Constants CORTEX Exported Constants * @{ */ /** @defgroup CORTEX_Preemption_Priority_Group CORTEX Preemption Priority Group * @{ */ #define NVIC_PRIORITYGROUP_0 ((uint32_t)0x00000007) /*!< 0 bits for pre-emption priority 4 bits for subpriority */ #define NVIC_PRIORITYGROUP_1 ((uint32_t)0x00000006) /*!< 1 bits for pre-emption priority 3 bits for subpriority */ #define NVIC_PRIORITYGROUP_2 ((uint32_t)0x00000005) /*!< 2 bits for pre-emption priority 2 bits for subpriority */ #define NVIC_PRIORITYGROUP_3 ((uint32_t)0x00000004) /*!< 3 bits for pre-emption priority 1 bits for subpriority */ #define NVIC_PRIORITYGROUP_4 ((uint32_t)0x00000003) /*!< 4 bits for pre-emption priority 0 bits for subpriority */ /** * @} */ /** @defgroup CORTEX_SysTick_clock_source CORTEX _SysTick clock source * @{ */ #define SYSTICK_CLKSOURCE_HCLK_DIV8 ((uint32_t)0x00000000) #define SYSTICK_CLKSOURCE_HCLK ((uint32_t)0x00000004) /** * @} */ #if (__MPU_PRESENT == 1) /** @defgroup CORTEX_MPU_HFNMI_PRIVDEF_Control MPU HFNMI and PRIVILEGED Access control * @{ */ #define MPU_HFNMI_PRIVDEF_NONE ((uint32_t)0x00000000) #define MPU_HARDFAULT_NMI ((uint32_t)0x00000002) #define MPU_PRIVILEGED_DEFAULT ((uint32_t)0x00000004) #define MPU_HFNMI_PRIVDEF ((uint32_t)0x00000006) /** * @} */ /** @defgroup CORTEX_MPU_Region_Enable CORTEX MPU Region Enable * @{ */ #define MPU_REGION_ENABLE ((uint8_t)0x01) #define MPU_REGION_DISABLE ((uint8_t)0x00) /** * @} */ /** @defgroup CORTEX_MPU_Instruction_Access CORTEX MPU Instruction Access * @{ */ #define MPU_INSTRUCTION_ACCESS_ENABLE ((uint8_t)0x00) #define MPU_INSTRUCTION_ACCESS_DISABLE ((uint8_t)0x01) /** * @} */ /** @defgroup CORTEX_MPU_Access_Shareable CORTEX MPU Instruction Access Shareable * @{ */ #define MPU_ACCESS_SHAREABLE ((uint8_t)0x01) #define MPU_ACCESS_NOT_SHAREABLE ((uint8_t)0x00) /** * @} */ /** @defgroup CORTEX_MPU_Access_Cacheable CORTEX MPU Instruction Access Cacheable * @{ */ #define MPU_ACCESS_CACHEABLE ((uint8_t)0x01) #define MPU_ACCESS_NOT_CACHEABLE ((uint8_t)0x00) /** * @} */ /** @defgroup CORTEX_MPU_Access_Bufferable CORTEX MPU Instruction Access Bufferable * @{ */ #define MPU_ACCESS_BUFFERABLE ((uint8_t)0x01) #define MPU_ACCESS_NOT_BUFFERABLE ((uint8_t)0x00) /** * @} */ /** @defgroup CORTEX_MPU_TEX_Levels MPU TEX Levels * @{ */ #define MPU_TEX_LEVEL0 ((uint8_t)0x00) #define MPU_TEX_LEVEL1 ((uint8_t)0x01) #define MPU_TEX_LEVEL2 ((uint8_t)0x02) /** * @} */ /** @defgroup CORTEX_MPU_Region_Size CORTEX MPU Region Size * @{ */ #define MPU_REGION_SIZE_32B ((uint8_t)0x04) #define MPU_REGION_SIZE_64B ((uint8_t)0x05) #define MPU_REGION_SIZE_128B ((uint8_t)0x06) #define MPU_REGION_SIZE_256B ((uint8_t)0x07) #define MPU_REGION_SIZE_512B ((uint8_t)0x08) #define MPU_REGION_SIZE_1KB ((uint8_t)0x09) #define MPU_REGION_SIZE_2KB ((uint8_t)0x0A) #define MPU_REGION_SIZE_4KB ((uint8_t)0x0B) #define MPU_REGION_SIZE_8KB ((uint8_t)0x0C) #define MPU_REGION_SIZE_16KB ((uint8_t)0x0D) #define MPU_REGION_SIZE_32KB ((uint8_t)0x0E) #define MPU_REGION_SIZE_64KB ((uint8_t)0x0F) #define MPU_REGION_SIZE_128KB ((uint8_t)0x10) #define MPU_REGION_SIZE_256KB ((uint8_t)0x11) #define MPU_REGION_SIZE_512KB ((uint8_t)0x12) #define MPU_REGION_SIZE_1MB ((uint8_t)0x13) #define MPU_REGION_SIZE_2MB ((uint8_t)0x14) #define MPU_REGION_SIZE_4MB ((uint8_t)0x15) #define MPU_REGION_SIZE_8MB ((uint8_t)0x16) #define MPU_REGION_SIZE_16MB ((uint8_t)0x17) #define MPU_REGION_SIZE_32MB ((uint8_t)0x18) #define MPU_REGION_SIZE_64MB ((uint8_t)0x19) #define MPU_REGION_SIZE_128MB ((uint8_t)0x1A) #define MPU_REGION_SIZE_256MB ((uint8_t)0x1B) #define MPU_REGION_SIZE_512MB ((uint8_t)0x1C) #define MPU_REGION_SIZE_1GB ((uint8_t)0x1D) #define MPU_REGION_SIZE_2GB ((uint8_t)0x1E) #define MPU_REGION_SIZE_4GB ((uint8_t)0x1F) /** * @} */ /** @defgroup CORTEX_MPU_Region_Permission_Attributes CORTEX MPU Region Permission Attributes * @{ */ #define MPU_REGION_NO_ACCESS ((uint8_t)0x00) #define MPU_REGION_PRIV_RW ((uint8_t)0x01) #define MPU_REGION_PRIV_RW_URO ((uint8_t)0x02) #define MPU_REGION_FULL_ACCESS ((uint8_t)0x03) #define MPU_REGION_PRIV_RO ((uint8_t)0x05) #define MPU_REGION_PRIV_RO_URO ((uint8_t)0x06) /** * @} */ /** @defgroup CORTEX_MPU_Region_Number CORTEX MPU Region Number * @{ */ #define MPU_REGION_NUMBER0 ((uint8_t)0x00) #define MPU_REGION_NUMBER1 ((uint8_t)0x01) #define MPU_REGION_NUMBER2 ((uint8_t)0x02) #define MPU_REGION_NUMBER3 ((uint8_t)0x03) #define MPU_REGION_NUMBER4 ((uint8_t)0x04) #define MPU_REGION_NUMBER5 ((uint8_t)0x05) #define MPU_REGION_NUMBER6 ((uint8_t)0x06) #define MPU_REGION_NUMBER7 ((uint8_t)0x07) /** * @} */ #endif /* __MPU_PRESENT */ /** * @} */ /* Exported Macros -----------------------------------------------------------*/ /** @defgroup CORTEX_Exported_Macros CORTEX Exported Macros * @{ */ /** @brief Configures the SysTick clock source. * @param __CLKSRC__: specifies the SysTick clock source. * This parameter can be one of the following values: * @arg SYSTICK_CLKSOURCE_HCLK_DIV8: AHB clock divided by 8 selected as SysTick clock source. * @arg SYSTICK_CLKSOURCE_HCLK: AHB clock selected as SysTick clock source. * @retval None */ #define __HAL_CORTEX_SYSTICKCLK_CONFIG(__CLKSRC__) \ do { \ if ((__CLKSRC__) == SYSTICK_CLKSOURCE_HCLK) \ { \ SysTick->CTRL |= SYSTICK_CLKSOURCE_HCLK; \ } \ else \ SysTick->CTRL &= ~SYSTICK_CLKSOURCE_HCLK; \ } while(0) /** * @} */ /* Exported functions --------------------------------------------------------*/ /** @addtogroup CORTEX_Exported_Functions * @{ */ /** @addtogroup CORTEX_Exported_Functions_Group1 * @{ */ /* Initialization and de-initialization functions *****************************/ void HAL_NVIC_SetPriorityGrouping(uint32_t PriorityGroup); void HAL_NVIC_SetPriority(IRQn_Type IRQn, uint32_t PreemptPriority, uint32_t SubPriority); void HAL_NVIC_EnableIRQ(IRQn_Type IRQn); void HAL_NVIC_DisableIRQ(IRQn_Type IRQn); void HAL_NVIC_SystemReset(void); uint32_t HAL_SYSTICK_Config(uint32_t TicksNumb); /** * @} */ /** @addtogroup CORTEX_Exported_Functions_Group2 * @{ */ /* Peripheral Control functions ***********************************************/ #if (__MPU_PRESENT == 1) void HAL_MPU_ConfigRegion(MPU_Region_InitTypeDef *MPU_Init); #endif /* __MPU_PRESENT */ uint32_t HAL_NVIC_GetPriorityGrouping(void); void HAL_NVIC_GetPriority(IRQn_Type IRQn, uint32_t PriorityGroup, uint32_t* pPreemptPriority, uint32_t* pSubPriority); uint32_t HAL_NVIC_GetPendingIRQ(IRQn_Type IRQn); void HAL_NVIC_SetPendingIRQ(IRQn_Type IRQn); void HAL_NVIC_ClearPendingIRQ(IRQn_Type IRQn); uint32_t HAL_NVIC_GetActive(IRQn_Type IRQn); void HAL_SYSTICK_CLKSourceConfig(uint32_t CLKSource); void HAL_SYSTICK_IRQHandler(void); void HAL_SYSTICK_Callback(void); /** * @} */ /** * @} */ /* Private types -------------------------------------------------------------*/ /* Private variables ---------------------------------------------------------*/ /* Private constants ---------------------------------------------------------*/ /* Private macros ------------------------------------------------------------*/ /** @defgroup CORTEX_Private_Macros CORTEX Private Macros * @{ */ #define IS_NVIC_PRIORITY_GROUP(GROUP) (((GROUP) == NVIC_PRIORITYGROUP_0) || \ ((GROUP) == NVIC_PRIORITYGROUP_1) || \ ((GROUP) == NVIC_PRIORITYGROUP_2) || \ ((GROUP) == NVIC_PRIORITYGROUP_3) || \ ((GROUP) == NVIC_PRIORITYGROUP_4)) #define IS_NVIC_PREEMPTION_PRIORITY(PRIORITY) ((PRIORITY) < 0x10) #define IS_NVIC_SUB_PRIORITY(PRIORITY) ((PRIORITY) < 0x10) #define IS_NVIC_DEVICE_IRQ(IRQ) ((IRQ) >= 0x00) #define IS_SYSTICK_CLK_SOURCE(SOURCE) (((SOURCE) == SYSTICK_CLKSOURCE_HCLK) || \ ((SOURCE) == SYSTICK_CLKSOURCE_HCLK_DIV8)) #if (__MPU_PRESENT == 1) #define IS_MPU_REGION_ENABLE(STATE) (((STATE) == MPU_REGION_ENABLE) || \ ((STATE) == MPU_REGION_DISABLE)) #define IS_MPU_INSTRUCTION_ACCESS(STATE) (((STATE) == MPU_INSTRUCTION_ACCESS_ENABLE) || \ ((STATE) == MPU_INSTRUCTION_ACCESS_DISABLE)) #define IS_MPU_ACCESS_SHAREABLE(STATE) (((STATE) == MPU_ACCESS_SHAREABLE) || \ ((STATE) == MPU_ACCESS_NOT_SHAREABLE)) #define IS_MPU_ACCESS_CACHEABLE(STATE) (((STATE) == MPU_ACCESS_CACHEABLE) || \ ((STATE) == MPU_ACCESS_NOT_CACHEABLE)) #define IS_MPU_ACCESS_BUFFERABLE(STATE) (((STATE) == MPU_ACCESS_BUFFERABLE) || \ ((STATE) == MPU_ACCESS_NOT_BUFFERABLE)) #define IS_MPU_TEX_LEVEL(TYPE) (((TYPE) == MPU_TEX_LEVEL0) || \ ((TYPE) == MPU_TEX_LEVEL1) || \ ((TYPE) == MPU_TEX_LEVEL2)) #define IS_MPU_REGION_PERMISSION_ATTRIBUTE(TYPE) (((TYPE) == MPU_REGION_NO_ACCESS) || \ ((TYPE) == MPU_REGION_PRIV_RW) || \ ((TYPE) == MPU_REGION_PRIV_RW_URO) || \ ((TYPE) == MPU_REGION_FULL_ACCESS) || \ ((TYPE) == MPU_REGION_PRIV_RO) || \ ((TYPE) == MPU_REGION_PRIV_RO_URO)) #define IS_MPU_REGION_NUMBER(NUMBER) (((NUMBER) == MPU_REGION_NUMBER0) || \ ((NUMBER) == MPU_REGION_NUMBER1) || \ ((NUMBER) == MPU_REGION_NUMBER2) || \ ((NUMBER) == MPU_REGION_NUMBER3) || \ ((NUMBER) == MPU_REGION_NUMBER4) || \ ((NUMBER) == MPU_REGION_NUMBER5) || \ ((NUMBER) == MPU_REGION_NUMBER6) || \ ((NUMBER) == MPU_REGION_NUMBER7)) #define IS_MPU_REGION_SIZE(SIZE) (((SIZE) == MPU_REGION_SIZE_32B) || \ ((SIZE) == MPU_REGION_SIZE_64B) || \ ((SIZE) == MPU_REGION_SIZE_128B) || \ ((SIZE) == MPU_REGION_SIZE_256B) || \ ((SIZE) == MPU_REGION_SIZE_512B) || \ ((SIZE) == MPU_REGION_SIZE_1KB) || \ ((SIZE) == MPU_REGION_SIZE_2KB) || \ ((SIZE) == MPU_REGION_SIZE_4KB) || \ ((SIZE) == MPU_REGION_SIZE_8KB) || \ ((SIZE) == MPU_REGION_SIZE_16KB) || \ ((SIZE) == MPU_REGION_SIZE_32KB) || \ ((SIZE) == MPU_REGION_SIZE_64KB) || \ ((SIZE) == MPU_REGION_SIZE_128KB) || \ ((SIZE) == MPU_REGION_SIZE_256KB) || \ ((SIZE) == MPU_REGION_SIZE_512KB) || \ ((SIZE) == MPU_REGION_SIZE_1MB) || \ ((SIZE) == MPU_REGION_SIZE_2MB) || \ ((SIZE) == MPU_REGION_SIZE_4MB) || \ ((SIZE) == MPU_REGION_SIZE_8MB) || \ ((SIZE) == MPU_REGION_SIZE_16MB) || \ ((SIZE) == MPU_REGION_SIZE_32MB) || \ ((SIZE) == MPU_REGION_SIZE_64MB) || \ ((SIZE) == MPU_REGION_SIZE_128MB) || \ ((SIZE) == MPU_REGION_SIZE_256MB) || \ ((SIZE) == MPU_REGION_SIZE_512MB) || \ ((SIZE) == MPU_REGION_SIZE_1GB) || \ ((SIZE) == MPU_REGION_SIZE_2GB) || \ ((SIZE) == MPU_REGION_SIZE_4GB)) #define IS_MPU_SUB_REGION_DISABLE(SUBREGION) ((SUBREGION) < (uint16_t)0x00FF) #endif /* __MPU_PRESENT */ /** * @} */ /* Private functions ---------------------------------------------------------*/ /** @defgroup CORTEX_Private_Functions CORTEX Private Functions * @brief CORTEX private functions * @{ */ #if (__MPU_PRESENT == 1) /** * @brief Disables the MPU * @retval None */ __STATIC_INLINE void HAL_MPU_Disable(void) { /* Disable fault exceptions */ SCB->SHCSR &= ~SCB_SHCSR_MEMFAULTENA_Msk; /* Disable the MPU */ MPU->CTRL &= ~MPU_CTRL_ENABLE_Msk; } /** * @brief Enables the MPU * @param MPU_Control: Specifies the control mode of the MPU during hard fault, * NMI, FAULTMASK and privileged access to the default memory * This parameter can be one of the following values: * @arg MPU_HFNMI_PRIVDEF_NONE * @arg MPU_HARDFAULT_NMI * @arg MPU_PRIVILEGED_DEFAULT * @arg MPU_HFNMI_PRIVDEF * @retval None */ __STATIC_INLINE void HAL_MPU_Enable(uint32_t MPU_Control) { /* Enable the MPU */ MPU->CTRL = MPU_Control | MPU_CTRL_ENABLE_Msk; /* Enable fault exceptions */ SCB->SHCSR |= SCB_SHCSR_MEMFAULTENA_Msk; } #endif /* __MPU_PRESENT */ /** * @} */ /** * @} */ /** * @} */ #ifdef __cplusplus } #endif #endif /* __STM32F4xx_HAL_CORTEX_H */ /************************ (C) COPYRIGHT STMicroelectronics *****END OF FILE****/ ================================================ FILE: Zelig/mbed/TARGET_NUCLEO_F411RE/stm32f4xx_hal_crc.h ================================================ /** ****************************************************************************** * @file stm32f4xx_hal_crc.h * @author MCD Application Team * @version V1.4.1 * @date 09-October-2015 * @brief Header file of CRC HAL module. ****************************************************************************** * @attention * *

© COPYRIGHT(c) 2015 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. * ****************************************************************************** */ /* Define to prevent recursive inclusion -------------------------------------*/ #ifndef __STM32F4xx_HAL_CRC_H #define __STM32F4xx_HAL_CRC_H #ifdef __cplusplus extern "C" { #endif /* Includes ------------------------------------------------------------------*/ #include "stm32f4xx_hal_def.h" /** @addtogroup STM32F4xx_HAL_Driver * @{ */ /** @defgroup CRC CRC * @brief CRC HAL module driver * @{ */ /* Exported types ------------------------------------------------------------*/ /** @defgroup CRC_Exported_Types CRC Exported Types * @{ */ /** @defgroup CRC_Exported_Types_Group1 CRC State Structure definition * @{ */ typedef enum { HAL_CRC_STATE_RESET = 0x00, /*!< CRC not yet initialized or disabled */ HAL_CRC_STATE_READY = 0x01, /*!< CRC initialized and ready for use */ HAL_CRC_STATE_BUSY = 0x02, /*!< CRC internal process is ongoing */ HAL_CRC_STATE_TIMEOUT = 0x03, /*!< CRC timeout state */ HAL_CRC_STATE_ERROR = 0x04 /*!< CRC error state */ }HAL_CRC_StateTypeDef; /** * @} */ /** @defgroup CRC_Exported_Types_Group2 CRC Handle Structure definition * @{ */ typedef struct { CRC_TypeDef *Instance; /*!< Register base address */ HAL_LockTypeDef Lock; /*!< CRC locking object */ __IO HAL_CRC_StateTypeDef State; /*!< CRC communication state */ }CRC_HandleTypeDef; /** * @} */ /** * @} */ /* Exported constants --------------------------------------------------------*/ /* Exported macro ------------------------------------------------------------*/ /** @defgroup CRC_Exported_Macros CRC Exported Macros * @{ */ /** @brief Resets CRC handle state * @param __HANDLE__: CRC handle * @retval None */ #define __HAL_CRC_RESET_HANDLE_STATE(__HANDLE__) ((__HANDLE__)->State = HAL_CRC_STATE_RESET) /** * @brief Resets CRC Data Register. * @param __HANDLE__: CRC handle * @retval None */ #define __HAL_CRC_DR_RESET(__HANDLE__) ((__HANDLE__)->Instance->CR |= CRC_CR_RESET) /** * @brief Stores a 8-bit data in the Independent Data(ID) register. * @param __HANDLE__: CRC handle * @param __VALUE__: 8-bit value to be stored in the ID register * @retval None */ #define __HAL_CRC_SET_IDR(__HANDLE__, __VALUE__) (WRITE_REG((__HANDLE__)->Instance->IDR, (__VALUE__))) /** * @brief Returns the 8-bit data stored in the Independent Data(ID) register. * @param __HANDLE__: CRC handle * @retval 8-bit value of the ID register */ #define __HAL_CRC_GET_IDR(__HANDLE__) (((__HANDLE__)->Instance->IDR) & CRC_IDR_IDR) /** * @} */ /* Exported functions --------------------------------------------------------*/ /** @defgroup CRC_Exported_Functions CRC Exported Functions * @{ */ /** @defgroup CRC_Exported_Functions_Group1 Initialization and de-initialization functions * @{ */ HAL_StatusTypeDef HAL_CRC_Init(CRC_HandleTypeDef *hcrc); HAL_StatusTypeDef HAL_CRC_DeInit (CRC_HandleTypeDef *hcrc); void HAL_CRC_MspInit(CRC_HandleTypeDef *hcrc); void HAL_CRC_MspDeInit(CRC_HandleTypeDef *hcrc); /** * @} */ /** @defgroup CRC_Exported_Functions_Group2 Peripheral Control functions * @{ */ uint32_t HAL_CRC_Accumulate(CRC_HandleTypeDef *hcrc, uint32_t pBuffer[], uint32_t BufferLength); uint32_t HAL_CRC_Calculate(CRC_HandleTypeDef *hcrc, uint32_t pBuffer[], uint32_t BufferLength); /** * @} */ /** @defgroup CRC_Exported_Functions_Group3 Peripheral State functions * @{ */ HAL_CRC_StateTypeDef HAL_CRC_GetState(CRC_HandleTypeDef *hcrc); /** * @} */ /** * @} */ /* Private types -------------------------------------------------------------*/ /** @defgroup CRC_Private_Types CRC Private Types * @{ */ /** * @} */ /* Private defines -----------------------------------------------------------*/ /** @defgroup CRC_Private_Defines CRC Private Defines * @{ */ /** * @} */ /* Private variables ---------------------------------------------------------*/ /** @defgroup CRC_Private_Variables CRC Private Variables * @{ */ /** * @} */ /* Private constants ---------------------------------------------------------*/ /** @defgroup CRC_Private_Constants CRC Private Constants * @{ */ /** * @} */ /* Private macros ------------------------------------------------------------*/ /** @defgroup CRC_Private_Macros CRC Private Macros * @{ */ /** * @} */ /* Private functions prototypes ----------------------------------------------*/ /** @defgroup CRC_Private_Functions_Prototypes CRC Private Functions Prototypes * @{ */ /** * @} */ /* Private functions ---------------------------------------------------------*/ /** @defgroup CRC_Private_Functions CRC Private Functions * @{ */ /** * @} */ /** * @} */ /** * @} */ #ifdef __cplusplus } #endif #endif /* __STM32F4xx_HAL_CRC_H */ /************************ (C) COPYRIGHT STMicroelectronics *****END OF FILE****/ ================================================ FILE: Zelig/mbed/TARGET_NUCLEO_F411RE/stm32f4xx_hal_cryp.h ================================================ /** ****************************************************************************** * @file stm32f4xx_hal_cryp.h * @author MCD Application Team * @version V1.4.1 * @date 09-October-2015 * @brief Header file of CRYP HAL module. ****************************************************************************** * @attention * *

© COPYRIGHT(c) 2015 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. * ****************************************************************************** */ /* Define to prevent recursive inclusion -------------------------------------*/ #ifndef __STM32F4xx_HAL_CRYP_H #define __STM32F4xx_HAL_CRYP_H #ifdef __cplusplus extern "C" { #endif #if defined(STM32F415xx) || defined(STM32F417xx) || defined(STM32F437xx) || defined(STM32F439xx) || defined(STM32F479xx) /* Includes ------------------------------------------------------------------*/ #include "stm32f4xx_hal_def.h" /** @addtogroup STM32F4xx_HAL_Driver * @{ */ /** @addtogroup CRYP * @{ */ /* Exported types ------------------------------------------------------------*/ /** @defgroup CRYP_Exported_Types CRYP Exported Types * @{ */ /** @defgroup CRYP_Exported_Types_Group1 CRYP Configuration Structure definition * @{ */ typedef struct { uint32_t DataType; /*!< 32-bit data, 16-bit data, 8-bit data or 1-bit string. This parameter can be a value of @ref CRYP CRYP_Data_Type */ uint32_t KeySize; /*!< Used only in AES mode only : 128, 192 or 256 bit key length. This parameter can be a value of @ref CRYP CRYP_Key_Size */ uint8_t* pKey; /*!< The key used for encryption/decryption */ uint8_t* pInitVect; /*!< The initialization vector used also as initialization counter in CTR mode */ uint8_t IVSize; /*!< The size of initialization vector. This parameter (called nonce size in CCM) is used only in AES-128/192/256 encryption/decryption CCM mode */ uint8_t TagSize; /*!< The size of returned authentication TAG. This parameter is used only in AES-128/192/256 encryption/decryption CCM mode */ uint8_t* Header; /*!< The header used in GCM and CCM modes */ uint32_t HeaderSize; /*!< The size of header buffer in bytes */ uint8_t* pScratch; /*!< Scratch buffer used to append the header. It's size must be equal to header size + 21 bytes. This parameter is used only in AES-128/192/256 encryption/decryption CCM mode */ }CRYP_InitTypeDef; /** * @} */ /** @defgroup CRYP_Exported_Types_Group2 CRYP State structures definition * @{ */ typedef enum { HAL_CRYP_STATE_RESET = 0x00, /*!< CRYP not yet initialized or disabled */ HAL_CRYP_STATE_READY = 0x01, /*!< CRYP initialized and ready for use */ HAL_CRYP_STATE_BUSY = 0x02, /*!< CRYP internal processing is ongoing */ HAL_CRYP_STATE_TIMEOUT = 0x03, /*!< CRYP timeout state */ HAL_CRYP_STATE_ERROR = 0x04 /*!< CRYP error state */ }HAL_CRYP_STATETypeDef; /** * @} */ /** @defgroup CRYP_Exported_Types_Group3 CRYP phase structures definition * @{ */ typedef enum { HAL_CRYP_PHASE_READY = 0x01, /*!< CRYP peripheral is ready for initialization. */ HAL_CRYP_PHASE_PROCESS = 0x02, /*!< CRYP peripheral is in processing phase */ HAL_CRYP_PHASE_FINAL = 0x03 /*!< CRYP peripheral is in final phase This is relevant only with CCM and GCM modes */ }HAL_PhaseTypeDef; /** * @} */ /** @defgroup CRYP_Exported_Types_Group4 CRYP handle Structure definition * @{ */ typedef struct { CRYP_TypeDef *Instance; /*!< CRYP registers base address */ CRYP_InitTypeDef Init; /*!< CRYP required parameters */ uint8_t *pCrypInBuffPtr; /*!< Pointer to CRYP processing (encryption, decryption,...) buffer */ uint8_t *pCrypOutBuffPtr; /*!< Pointer to CRYP processing (encryption, decryption,...) buffer */ __IO uint16_t CrypInCount; /*!< Counter of inputed data */ __IO uint16_t CrypOutCount; /*!< Counter of outputted data */ HAL_StatusTypeDef Status; /*!< CRYP peripheral status */ HAL_PhaseTypeDef Phase; /*!< CRYP peripheral phase */ DMA_HandleTypeDef *hdmain; /*!< CRYP In DMA handle parameters */ DMA_HandleTypeDef *hdmaout; /*!< CRYP Out DMA handle parameters */ HAL_LockTypeDef Lock; /*!< CRYP locking object */ __IO HAL_CRYP_STATETypeDef State; /*!< CRYP peripheral state */ }CRYP_HandleTypeDef; /** * @} */ /** * @} */ /* Exported constants --------------------------------------------------------*/ /** @defgroup CRYP_Exported_Constants CRYP Exported Constants * @{ */ /** @defgroup CRYP_Exported_Constants_Group1 CRYP CRYP_Key_Size * @{ */ #define CRYP_KEYSIZE_128B ((uint32_t)0x00000000) #define CRYP_KEYSIZE_192B CRYP_CR_KEYSIZE_0 #define CRYP_KEYSIZE_256B CRYP_CR_KEYSIZE_1 /** * @} */ /** @defgroup CRYP_Exported_Constants_Group2 CRYP CRYP_Data_Type * @{ */ #define CRYP_DATATYPE_32B ((uint32_t)0x00000000) #define CRYP_DATATYPE_16B CRYP_CR_DATATYPE_0 #define CRYP_DATATYPE_8B CRYP_CR_DATATYPE_1 #define CRYP_DATATYPE_1B CRYP_CR_DATATYPE /** * @} */ /** @defgroup CRYP_Exported_Constants_Group3 CRYP CRYP_AlgoModeDirection * @{ */ #define CRYP_CR_ALGOMODE_DIRECTION ((uint32_t)0x0008003C) #define CRYP_CR_ALGOMODE_TDES_ECB_ENCRYPT ((uint32_t)0x00000000) #define CRYP_CR_ALGOMODE_TDES_ECB_DECRYPT ((uint32_t)0x00000004) #define CRYP_CR_ALGOMODE_TDES_CBC_ENCRYPT ((uint32_t)0x00000008) #define CRYP_CR_ALGOMODE_TDES_CBC_DECRYPT ((uint32_t)0x0000000C) #define CRYP_CR_ALGOMODE_DES_ECB_ENCRYPT ((uint32_t)0x00000010) #define CRYP_CR_ALGOMODE_DES_ECB_DECRYPT ((uint32_t)0x00000014) #define CRYP_CR_ALGOMODE_DES_CBC_ENCRYPT ((uint32_t)0x00000018) #define CRYP_CR_ALGOMODE_DES_CBC_DECRYPT ((uint32_t)0x0000001C) #define CRYP_CR_ALGOMODE_AES_ECB_ENCRYPT ((uint32_t)0x00000020) #define CRYP_CR_ALGOMODE_AES_ECB_DECRYPT ((uint32_t)0x00000024) #define CRYP_CR_ALGOMODE_AES_CBC_ENCRYPT ((uint32_t)0x00000028) #define CRYP_CR_ALGOMODE_AES_CBC_DECRYPT ((uint32_t)0x0000002C) #define CRYP_CR_ALGOMODE_AES_CTR_ENCRYPT ((uint32_t)0x00000030) #define CRYP_CR_ALGOMODE_AES_CTR_DECRYPT ((uint32_t)0x00000034) /** * @} */ /** @defgroup CRYP_Exported_Constants_Group4 CRYP CRYP_Interrupt * @{ */ #define CRYP_IT_INI ((uint32_t)CRYP_IMSCR_INIM) /*!< Input FIFO Interrupt */ #define CRYP_IT_OUTI ((uint32_t)CRYP_IMSCR_OUTIM) /*!< Output FIFO Interrupt */ /** * @} */ /** @defgroup CRYP_Exported_Constants_Group5 CRYP CRYP_Flags * @{ */ #define CRYP_FLAG_BUSY ((uint32_t)0x00000010) /*!< The CRYP core is currently processing a block of data or a key preparation (for AES decryption). */ #define CRYP_FLAG_IFEM ((uint32_t)0x00000001) /*!< Input FIFO is empty */ #define CRYP_FLAG_IFNF ((uint32_t)0x00000002) /*!< Input FIFO is not Full */ #define CRYP_FLAG_OFNE ((uint32_t)0x00000004) /*!< Output FIFO is not empty */ #define CRYP_FLAG_OFFU ((uint32_t)0x00000008) /*!< Output FIFO is Full */ #define CRYP_FLAG_OUTRIS ((uint32_t)0x01000002) /*!< Output FIFO service raw interrupt status */ #define CRYP_FLAG_INRIS ((uint32_t)0x01000001) /*!< Input FIFO service raw interrupt status */ /** * @} */ /** * @} */ /* Exported macro ------------------------------------------------------------*/ /** @defgroup CRYP_Exported_Macros CRYP Exported Macros * @{ */ /** @brief Reset CRYP handle state * @param __HANDLE__: specifies the CRYP handle. * @retval None */ #define __HAL_CRYP_RESET_HANDLE_STATE(__HANDLE__) ((__HANDLE__)->State = HAL_CRYP_STATE_RESET) /** * @brief Enable/Disable the CRYP peripheral. * @param __HANDLE__: specifies the CRYP handle. * @retval None */ #define __HAL_CRYP_ENABLE(__HANDLE__) ((__HANDLE__)->Instance->CR |= CRYP_CR_CRYPEN) #define __HAL_CRYP_DISABLE(__HANDLE__) ((__HANDLE__)->Instance->CR &= ~CRYP_CR_CRYPEN) /** * @brief Flush the data FIFO. * @param __HANDLE__: specifies the CRYP handle. * @retval None */ #define __HAL_CRYP_FIFO_FLUSH(__HANDLE__) ((__HANDLE__)->Instance->CR |= CRYP_CR_FFLUSH) /** * @brief Set the algorithm mode: AES-ECB, AES-CBC, AES-CTR, DES-ECB, DES-CBC. * @param __HANDLE__: specifies the CRYP handle. * @param MODE: The algorithm mode. * @retval None */ #define __HAL_CRYP_SET_MODE(__HANDLE__, MODE) ((__HANDLE__)->Instance->CR |= (uint32_t)(MODE)) /** @brief Check whether the specified CRYP flag is set or not. * @param __HANDLE__: specifies the CRYP handle. * @param __FLAG__: specifies the flag to check. * This parameter can be one of the following values: * @arg CRYP_FLAG_BUSY: The CRYP core is currently processing a block of data * or a key preparation (for AES decryption). * @arg CRYP_FLAG_IFEM: Input FIFO is empty * @arg CRYP_FLAG_IFNF: Input FIFO is not full * @arg CRYP_FLAG_INRIS: Input FIFO service raw interrupt is pending * @arg CRYP_FLAG_OFNE: Output FIFO is not empty * @arg CRYP_FLAG_OFFU: Output FIFO is full * @arg CRYP_FLAG_OUTRIS: Input FIFO service raw interrupt is pending * @retval The new state of __FLAG__ (TRUE or FALSE). */ #define __HAL_CRYP_GET_FLAG(__HANDLE__, __FLAG__) ((((uint8_t)((__FLAG__) >> 24)) == 0x01)?((((__HANDLE__)->Instance->RISR) & ((__FLAG__) & CRYP_FLAG_MASK)) == ((__FLAG__) & CRYP_FLAG_MASK)): \ ((((__HANDLE__)->Instance->RISR) & ((__FLAG__) & CRYP_FLAG_MASK)) == ((__FLAG__) & CRYP_FLAG_MASK))) /** @brief Check whether the specified CRYP interrupt is set or not. * @param __HANDLE__: specifies the CRYP handle. * @param __INTERRUPT__: specifies the interrupt to check. * This parameter can be one of the following values: * @arg CRYP_IT_INRIS: Input FIFO service raw interrupt is pending * @arg CRYP_IT_OUTRIS: Output FIFO service raw interrupt is pending * @retval The new state of __INTERRUPT__ (TRUE or FALSE). */ #define __HAL_CRYP_GET_IT(__HANDLE__, __INTERRUPT__) (((__HANDLE__)->Instance->MISR & (__INTERRUPT__)) == (__INTERRUPT__)) /** * @brief Enable the CRYP interrupt. * @param __HANDLE__: specifies the CRYP handle. * @param __INTERRUPT__: CRYP Interrupt. * @retval None */ #define __HAL_CRYP_ENABLE_IT(__HANDLE__, __INTERRUPT__) (((__HANDLE__)->Instance->IMSCR) |= (__INTERRUPT__)) /** * @brief Disable the CRYP interrupt. * @param __HANDLE__: specifies the CRYP handle. * @param __INTERRUPT__: CRYP interrupt. * @retval None */ #define __HAL_CRYP_DISABLE_IT(__HANDLE__, __INTERRUPT__) (((__HANDLE__)->Instance->IMSCR) &= ~(__INTERRUPT__)) /** * @} */ /* Include CRYP HAL Extension module */ #include "stm32f4xx_hal_cryp_ex.h" /* Exported functions --------------------------------------------------------*/ /** @defgroup CRYP_Exported_Functions CRYP Exported Functions * @{ */ /** @addtogroup CRYP_Exported_Functions_Group1 * @{ */ HAL_StatusTypeDef HAL_CRYP_Init(CRYP_HandleTypeDef *hcryp); HAL_StatusTypeDef HAL_CRYP_DeInit(CRYP_HandleTypeDef *hcryp); void HAL_CRYP_MspInit(CRYP_HandleTypeDef *hcryp); void HAL_CRYP_MspDeInit(CRYP_HandleTypeDef *hcryp); /** * @} */ /** @addtogroup CRYP_Exported_Functions_Group2 * @{ */ /* AES encryption/decryption using polling ***********************************/ HAL_StatusTypeDef HAL_CRYP_AESECB_Encrypt(CRYP_HandleTypeDef *hcryp, uint8_t *pPlainData, uint16_t Size, uint8_t *pCypherData, uint32_t Timeout); HAL_StatusTypeDef HAL_CRYP_AESECB_Decrypt(CRYP_HandleTypeDef *hcryp, uint8_t *pCypherData, uint16_t Size, uint8_t *pPlainData, uint32_t Timeout); HAL_StatusTypeDef HAL_CRYP_AESCBC_Encrypt(CRYP_HandleTypeDef *hcryp, uint8_t *pPlainData, uint16_t Size, uint8_t *pCypherData, uint32_t Timeout); HAL_StatusTypeDef HAL_CRYP_AESCBC_Decrypt(CRYP_HandleTypeDef *hcryp, uint8_t *pCypherData, uint16_t Size, uint8_t *pPlainData, uint32_t Timeout); HAL_StatusTypeDef HAL_CRYP_AESCTR_Encrypt(CRYP_HandleTypeDef *hcryp, uint8_t *pPlainData, uint16_t Size, uint8_t *pCypherData, uint32_t Timeout); HAL_StatusTypeDef HAL_CRYP_AESCTR_Decrypt(CRYP_HandleTypeDef *hcryp, uint8_t *pCypherData, uint16_t Size, uint8_t *pPlainData, uint32_t Timeout); /* AES encryption/decryption using interrupt *********************************/ HAL_StatusTypeDef HAL_CRYP_AESECB_Encrypt_IT(CRYP_HandleTypeDef *hcryp, uint8_t *pPlainData, uint16_t Size, uint8_t *pCypherData); HAL_StatusTypeDef HAL_CRYP_AESCBC_Encrypt_IT(CRYP_HandleTypeDef *hcryp, uint8_t *pPlainData, uint16_t Size, uint8_t *pCypherData); HAL_StatusTypeDef HAL_CRYP_AESCTR_Encrypt_IT(CRYP_HandleTypeDef *hcryp, uint8_t *pPlainData, uint16_t Size, uint8_t *pCypherData); HAL_StatusTypeDef HAL_CRYP_AESECB_Decrypt_IT(CRYP_HandleTypeDef *hcryp, uint8_t *pCypherData, uint16_t Size, uint8_t *pPlainData); HAL_StatusTypeDef HAL_CRYP_AESCTR_Decrypt_IT(CRYP_HandleTypeDef *hcryp, uint8_t *pCypherData, uint16_t Size, uint8_t *pPlainData); HAL_StatusTypeDef HAL_CRYP_AESCBC_Decrypt_IT(CRYP_HandleTypeDef *hcryp, uint8_t *pCypherData, uint16_t Size, uint8_t *pPlainData); /* AES encryption/decryption using DMA ***************************************/ HAL_StatusTypeDef HAL_CRYP_AESECB_Encrypt_DMA(CRYP_HandleTypeDef *hcryp, uint8_t *pPlainData, uint16_t Size, uint8_t *pCypherData); HAL_StatusTypeDef HAL_CRYP_AESECB_Decrypt_DMA(CRYP_HandleTypeDef *hcryp, uint8_t *pCypherData, uint16_t Size, uint8_t *pPlainData); HAL_StatusTypeDef HAL_CRYP_AESCBC_Encrypt_DMA(CRYP_HandleTypeDef *hcryp, uint8_t *pPlainData, uint16_t Size, uint8_t *pCypherData); HAL_StatusTypeDef HAL_CRYP_AESCBC_Decrypt_DMA(CRYP_HandleTypeDef *hcryp, uint8_t *pCypherData, uint16_t Size, uint8_t *pPlainData); HAL_StatusTypeDef HAL_CRYP_AESCTR_Encrypt_DMA(CRYP_HandleTypeDef *hcryp, uint8_t *pPlainData, uint16_t Size, uint8_t *pCypherData); HAL_StatusTypeDef HAL_CRYP_AESCTR_Decrypt_DMA(CRYP_HandleTypeDef *hcryp, uint8_t *pCypherData, uint16_t Size, uint8_t *pPlainData); /** * @} */ /** @addtogroup CRYP_Exported_Functions_Group3 * @{ */ /* DES encryption/decryption using polling ***********************************/ HAL_StatusTypeDef HAL_CRYP_DESECB_Encrypt(CRYP_HandleTypeDef *hcryp, uint8_t *pPlainData, uint16_t Size, uint8_t *pCypherData, uint32_t Timeout); HAL_StatusTypeDef HAL_CRYP_DESCBC_Encrypt(CRYP_HandleTypeDef *hcryp, uint8_t *pPlainData, uint16_t Size, uint8_t *pCypherData, uint32_t Timeout); HAL_StatusTypeDef HAL_CRYP_DESECB_Decrypt(CRYP_HandleTypeDef *hcryp, uint8_t *pPlainData, uint16_t Size, uint8_t *pCypherData, uint32_t Timeout); HAL_StatusTypeDef HAL_CRYP_DESCBC_Decrypt(CRYP_HandleTypeDef *hcryp, uint8_t *pPlainData, uint16_t Size, uint8_t *pCypherData, uint32_t Timeout); /* DES encryption/decryption using interrupt *********************************/ HAL_StatusTypeDef HAL_CRYP_DESECB_Encrypt_IT(CRYP_HandleTypeDef *hcryp, uint8_t *pPlainData, uint16_t Size, uint8_t *pCypherData); HAL_StatusTypeDef HAL_CRYP_DESECB_Decrypt_IT(CRYP_HandleTypeDef *hcryp, uint8_t *pCypherData, uint16_t Size, uint8_t *pPlainData); HAL_StatusTypeDef HAL_CRYP_DESCBC_Encrypt_IT(CRYP_HandleTypeDef *hcryp, uint8_t *pPlainData, uint16_t Size, uint8_t *pCypherData); HAL_StatusTypeDef HAL_CRYP_DESCBC_Decrypt_IT(CRYP_HandleTypeDef *hcryp, uint8_t *pCypherData, uint16_t Size, uint8_t *pPlainData); /* DES encryption/decryption using DMA ***************************************/ HAL_StatusTypeDef HAL_CRYP_DESECB_Encrypt_DMA(CRYP_HandleTypeDef *hcryp, uint8_t *pPlainData, uint16_t Size, uint8_t *pCypherData); HAL_StatusTypeDef HAL_CRYP_DESECB_Decrypt_DMA(CRYP_HandleTypeDef *hcryp, uint8_t *pCypherData, uint16_t Size, uint8_t *pPlainData); HAL_StatusTypeDef HAL_CRYP_DESCBC_Encrypt_DMA(CRYP_HandleTypeDef *hcryp, uint8_t *pPlainData, uint16_t Size, uint8_t *pCypherData); HAL_StatusTypeDef HAL_CRYP_DESCBC_Decrypt_DMA(CRYP_HandleTypeDef *hcryp, uint8_t *pCypherData, uint16_t Size, uint8_t *pPlainData); /** * @} */ /** @addtogroup CRYP_Exported_Functions_Group4 * @{ */ /* TDES encryption/decryption using polling **********************************/ HAL_StatusTypeDef HAL_CRYP_TDESECB_Encrypt(CRYP_HandleTypeDef *hcryp, uint8_t *pPlainData, uint16_t Size, uint8_t *pCypherData, uint32_t Timeout); HAL_StatusTypeDef HAL_CRYP_TDESCBC_Encrypt(CRYP_HandleTypeDef *hcryp, uint8_t *pPlainData, uint16_t Size, uint8_t *pCypherData, uint32_t Timeout); HAL_StatusTypeDef HAL_CRYP_TDESECB_Decrypt(CRYP_HandleTypeDef *hcryp, uint8_t *pCypherData, uint16_t Size, uint8_t *pPlainData, uint32_t Timeout); HAL_StatusTypeDef HAL_CRYP_TDESCBC_Decrypt(CRYP_HandleTypeDef *hcryp, uint8_t *pCypherData, uint16_t Size, uint8_t *pPlainData, uint32_t Timeout); /* TDES encryption/decryption using interrupt ********************************/ HAL_StatusTypeDef HAL_CRYP_TDESECB_Encrypt_IT(CRYP_HandleTypeDef *hcryp, uint8_t *pPlainData, uint16_t Size, uint8_t *pCypherData); HAL_StatusTypeDef HAL_CRYP_TDESECB_Decrypt_IT(CRYP_HandleTypeDef *hcryp, uint8_t *pCypherData, uint16_t Size, uint8_t *pPlainData); HAL_StatusTypeDef HAL_CRYP_TDESCBC_Encrypt_IT(CRYP_HandleTypeDef *hcryp, uint8_t *pPlainData, uint16_t Size, uint8_t *pCypherData); HAL_StatusTypeDef HAL_CRYP_TDESCBC_Decrypt_IT(CRYP_HandleTypeDef *hcryp, uint8_t *pCypherData, uint16_t Size, uint8_t *pPlainData); /* TDES encryption/decryption using DMA **************************************/ HAL_StatusTypeDef HAL_CRYP_TDESECB_Encrypt_DMA(CRYP_HandleTypeDef *hcryp, uint8_t *pPlainData, uint16_t Size, uint8_t *pCypherData); HAL_StatusTypeDef HAL_CRYP_TDESECB_Decrypt_DMA(CRYP_HandleTypeDef *hcryp, uint8_t *pCypherData, uint16_t Size, uint8_t *pPlainData); HAL_StatusTypeDef HAL_CRYP_TDESCBC_Encrypt_DMA(CRYP_HandleTypeDef *hcryp, uint8_t *pPlainData, uint16_t Size, uint8_t *pCypherData); HAL_StatusTypeDef HAL_CRYP_TDESCBC_Decrypt_DMA(CRYP_HandleTypeDef *hcryp, uint8_t *pCypherData, uint16_t Size, uint8_t *pPlainData); /** * @} */ /** @addtogroup CRYP_Exported_Functions_Group5 * @{ */ void HAL_CRYP_InCpltCallback(CRYP_HandleTypeDef *hcryp); void HAL_CRYP_OutCpltCallback(CRYP_HandleTypeDef *hcryp); void HAL_CRYP_ErrorCallback(CRYP_HandleTypeDef *hcryp); /** * @} */ /** @addtogroup CRYP_Exported_Functions_Group6 * @{ */ void HAL_CRYP_IRQHandler(CRYP_HandleTypeDef *hcryp); /** * @} */ /** @addtogroup CRYP_Exported_Functions_Group7 * @{ */ HAL_CRYP_STATETypeDef HAL_CRYP_GetState(CRYP_HandleTypeDef *hcryp); /** * @} */ /** * @} */ /* Private types -------------------------------------------------------------*/ /** @defgroup CRYP_Private_Types CRYP Private Types * @{ */ /** * @} */ /* Private variables ---------------------------------------------------------*/ /** @defgroup CRYP_Private_Variables CRYP Private Variables * @{ */ /** * @} */ /* Private constants ---------------------------------------------------------*/ /** @defgroup CRYP_Private_Constants CRYP Private Constants * @{ */ #define CRYP_FLAG_MASK ((uint32_t)0x0000001F) /** * @} */ /* Private macros ------------------------------------------------------------*/ /** @defgroup CRYP_Private_Macros CRYP Private Macros * @{ */ #define IS_CRYP_KEYSIZE(__KEYSIZE__) (((__KEYSIZE__) == CRYP_KEYSIZE_128B) || \ ((__KEYSIZE__) == CRYP_KEYSIZE_192B) || \ ((__KEYSIZE__) == CRYP_KEYSIZE_256B)) #define IS_CRYP_DATATYPE(__DATATYPE__) (((__DATATYPE__) == CRYP_DATATYPE_32B) || \ ((__DATATYPE__) == CRYP_DATATYPE_16B) || \ ((__DATATYPE__) == CRYP_DATATYPE_8B) || \ ((__DATATYPE__) == CRYP_DATATYPE_1B)) /** * @} */ /* Private functions ---------------------------------------------------------*/ /** @defgroup CRYP_Private_Functions CRYP Private Functions * @{ */ /** * @} */ #endif /* STM32F415xx || STM32F417xx || STM32F437xx || STM32F439xx || STM32F479xx */ /** * @} */ /** * @} */ #ifdef __cplusplus } #endif #endif /* __STM32F4xx_HAL_CRYP_H */ /************************ (C) COPYRIGHT STMicroelectronics *****END OF FILE****/ ================================================ FILE: Zelig/mbed/TARGET_NUCLEO_F411RE/stm32f4xx_hal_cryp_ex.h ================================================ /** ****************************************************************************** * @file stm32f4xx_hal_cryp_ex.h * @author MCD Application Team * @version V1.4.1 * @date 09-October-2015 * @brief Header file of CRYP HAL Extension module. ****************************************************************************** * @attention * *

© COPYRIGHT(c) 2015 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. * ****************************************************************************** */ /* Define to prevent recursive inclusion -------------------------------------*/ #ifndef __STM32F4xx_HAL_CRYP_EX_H #define __STM32F4xx_HAL_CRYP_EX_H #ifdef __cplusplus extern "C" { #endif #if defined(STM32F437xx) || defined(STM32F439xx) || defined(STM32F479xx) /* Includes ------------------------------------------------------------------*/ #include "stm32f4xx_hal_def.h" /** @addtogroup STM32F4xx_HAL_Driver * @{ */ /** @addtogroup CRYPEx * @{ */ /* Exported types ------------------------------------------------------------*/ /* Exported constants --------------------------------------------------------*/ /** @defgroup CRYPEx_Exported_Constants CRYPEx Exported Constants * @{ */ /** @defgroup CRYPEx_Exported_Constants_Group1 CRYP AlgoModeDirection * @{ */ #define CRYP_CR_ALGOMODE_AES_GCM_ENCRYPT ((uint32_t)0x00080000) #define CRYP_CR_ALGOMODE_AES_GCM_DECRYPT ((uint32_t)0x00080004) #define CRYP_CR_ALGOMODE_AES_CCM_ENCRYPT ((uint32_t)0x00080008) #define CRYP_CR_ALGOMODE_AES_CCM_DECRYPT ((uint32_t)0x0008000C) /** * @} */ /** @defgroup CRYPEx_Exported_Constants_Group3 CRYP PhaseConfig * @brief The phases are relevant only to AES-GCM and AES-CCM * @{ */ #define CRYP_PHASE_INIT ((uint32_t)0x00000000) #define CRYP_PHASE_HEADER CRYP_CR_GCM_CCMPH_0 #define CRYP_PHASE_PAYLOAD CRYP_CR_GCM_CCMPH_1 #define CRYP_PHASE_FINAL CRYP_CR_GCM_CCMPH /** * @} */ /** * @} */ /* Exported macro ------------------------------------------------------------*/ /** @defgroup CRYPEx_Exported_Macros CRYP Exported Macros * @{ */ /** * @brief Set the phase: Init, header, payload, final. * This is relevant only for GCM and CCM modes. * @param __HANDLE__: specifies the CRYP handle. * @param __PHASE__: The phase. * @retval None */ #define __HAL_CRYP_SET_PHASE(__HANDLE__, __PHASE__) do{(__HANDLE__)->Instance->CR &= (uint32_t)(~CRYP_CR_GCM_CCMPH);\ (__HANDLE__)->Instance->CR |= (uint32_t)(__PHASE__);\ }while(0) /** * @} */ /* Exported functions --------------------------------------------------------*/ /** @defgroup CRYPEx_Exported_Functions CRYPEx Exported Functions * @{ */ /** @addtogroup CRYPEx_Exported_Functions_Group1 * @{ */ /* AES encryption/decryption using polling ***********************************/ HAL_StatusTypeDef HAL_CRYPEx_AESGCM_Encrypt(CRYP_HandleTypeDef *hcryp, uint8_t *pPlainData, uint16_t Size, uint8_t *pCypherData, uint32_t Timeout); HAL_StatusTypeDef HAL_CRYPEx_AESGCM_Decrypt(CRYP_HandleTypeDef *hcryp, uint8_t *pCypherData, uint16_t Size, uint8_t *pPlainData, uint32_t Timeout); HAL_StatusTypeDef HAL_CRYPEx_AESGCM_Finish(CRYP_HandleTypeDef *hcryp, uint32_t Size, uint8_t *AuthTag, uint32_t Timeout); HAL_StatusTypeDef HAL_CRYPEx_AESCCM_Encrypt(CRYP_HandleTypeDef *hcryp, uint8_t *pPlainData, uint16_t Size, uint8_t *pCypherData, uint32_t Timeout); HAL_StatusTypeDef HAL_CRYPEx_AESCCM_Decrypt(CRYP_HandleTypeDef *hcryp, uint8_t *pCypherData, uint16_t Size, uint8_t *pPlainData, uint32_t Timeout); HAL_StatusTypeDef HAL_CRYPEx_AESCCM_Finish(CRYP_HandleTypeDef *hcryp, uint8_t *AuthTag, uint32_t Timeout); /* AES encryption/decryption using interrupt *********************************/ HAL_StatusTypeDef HAL_CRYPEx_AESGCM_Encrypt_IT(CRYP_HandleTypeDef *hcryp, uint8_t *pPlainData, uint16_t Size, uint8_t *pCypherData); HAL_StatusTypeDef HAL_CRYPEx_AESGCM_Decrypt_IT(CRYP_HandleTypeDef *hcryp, uint8_t *pCypherData, uint16_t Size, uint8_t *pPlainData); HAL_StatusTypeDef HAL_CRYPEx_AESCCM_Encrypt_IT(CRYP_HandleTypeDef *hcryp, uint8_t *pPlainData, uint16_t Size, uint8_t *pCypherData); HAL_StatusTypeDef HAL_CRYPEx_AESCCM_Decrypt_IT(CRYP_HandleTypeDef *hcryp, uint8_t *pCypherData, uint16_t Size, uint8_t *pPlainData); /* AES encryption/decryption using DMA ***************************************/ HAL_StatusTypeDef HAL_CRYPEx_AESGCM_Encrypt_DMA(CRYP_HandleTypeDef *hcryp, uint8_t *pPlainData, uint16_t Size, uint8_t *pCypherData); HAL_StatusTypeDef HAL_CRYPEx_AESGCM_Decrypt_DMA(CRYP_HandleTypeDef *hcryp, uint8_t *pCypherData, uint16_t Size, uint8_t *pPlainData); HAL_StatusTypeDef HAL_CRYPEx_AESCCM_Encrypt_DMA(CRYP_HandleTypeDef *hcryp, uint8_t *pPlainData, uint16_t Size, uint8_t *pCypherData); HAL_StatusTypeDef HAL_CRYPEx_AESCCM_Decrypt_DMA(CRYP_HandleTypeDef *hcryp, uint8_t *pCypherData, uint16_t Size, uint8_t *pPlainData); /** * @} */ /** @addtogroup CRYPEx_Exported_Functions_Group2 * @{ */ void HAL_CRYPEx_GCMCCM_IRQHandler(CRYP_HandleTypeDef *hcryp); /** * @} */ /** * @} */ /* Private types -------------------------------------------------------------*/ /** @defgroup CRYPEx_Private_Types CRYPEx Private Types * @{ */ /** * @} */ /* Private variables ---------------------------------------------------------*/ /** @defgroup CRYPEx_Private_Variables CRYPEx Private Variables * @{ */ /** * @} */ /* Private constants ---------------------------------------------------------*/ /** @defgroup CRYPEx_Private_Constants CRYPEx Private Constants * @{ */ /** * @} */ /* Private macros ------------------------------------------------------------*/ /** @defgroup CRYPEx_Private_Macros CRYPEx Private Macros * @{ */ /** * @} */ /* Private functions ---------------------------------------------------------*/ /** @defgroup CRYPEx_Private_Functions CRYPEx Private Functions * @{ */ /** * @} */ #endif /* STM32F437xx || STM32F439xx || STM32F479xx */ /** * @} */ /** * @} */ #ifdef __cplusplus } #endif #endif /* __STM32F4xx_HAL_CRYP_EX_H */ /************************ (C) COPYRIGHT STMicroelectronics *****END OF FILE****/ ================================================ FILE: Zelig/mbed/TARGET_NUCLEO_F411RE/stm32f4xx_hal_dac.h ================================================ /** ****************************************************************************** * @file stm32f4xx_hal_dac.h * @author MCD Application Team * @version V1.4.1 * @date 09-October-2015 * @brief Header file of DAC HAL module. ****************************************************************************** * @attention * *

© COPYRIGHT(c) 2015 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. * ****************************************************************************** */ /* Define to prevent recursive inclusion -------------------------------------*/ #ifndef __STM32F4xx_HAL_DAC_H #define __STM32F4xx_HAL_DAC_H #ifdef __cplusplus extern "C" { #endif #if defined(STM32F405xx) || defined(STM32F415xx) || defined(STM32F407xx) || defined(STM32F417xx) ||\ defined(STM32F427xx) || defined(STM32F437xx) || defined(STM32F429xx) || defined(STM32F439xx) ||\ defined(STM32F410Tx) || defined(STM32F410Cx) || defined(STM32F410Rx) || defined(STM32F446xx) ||\ defined(STM32F469xx) || defined(STM32F479xx) /* Includes ------------------------------------------------------------------*/ #include "stm32f4xx_hal_def.h" /** @addtogroup STM32F4xx_HAL_Driver * @{ */ /** @addtogroup DAC * @{ */ /* Exported types ------------------------------------------------------------*/ /** @defgroup DAC_Exported_Types DAC Exported Types * @{ */ /** * @brief HAL State structures definition */ typedef enum { HAL_DAC_STATE_RESET = 0x00, /*!< DAC not yet initialized or disabled */ HAL_DAC_STATE_READY = 0x01, /*!< DAC initialized and ready for use */ HAL_DAC_STATE_BUSY = 0x02, /*!< DAC internal processing is ongoing */ HAL_DAC_STATE_TIMEOUT = 0x03, /*!< DAC timeout state */ HAL_DAC_STATE_ERROR = 0x04 /*!< DAC error state */ }HAL_DAC_StateTypeDef; /** * @brief DAC handle Structure definition */ typedef struct { DAC_TypeDef *Instance; /*!< Register base address */ __IO HAL_DAC_StateTypeDef State; /*!< DAC communication state */ HAL_LockTypeDef Lock; /*!< DAC locking object */ DMA_HandleTypeDef *DMA_Handle1; /*!< Pointer DMA handler for channel 1 */ DMA_HandleTypeDef *DMA_Handle2; /*!< Pointer DMA handler for channel 2 */ __IO uint32_t ErrorCode; /*!< DAC Error code */ }DAC_HandleTypeDef; /** * @brief DAC Configuration regular Channel structure definition */ typedef struct { uint32_t DAC_Trigger; /*!< Specifies the external trigger for the selected DAC channel. This parameter can be a value of @ref DAC_trigger_selection */ uint32_t DAC_OutputBuffer; /*!< Specifies whether the DAC channel output buffer is enabled or disabled. This parameter can be a value of @ref DAC_output_buffer */ }DAC_ChannelConfTypeDef; /** * @} */ /* Exported constants --------------------------------------------------------*/ /** @defgroup DAC_Exported_Constants DAC Exported Constants * @{ */ /** @defgroup DAC_Error_Code DAC Error Code * @{ */ #define HAL_DAC_ERROR_NONE 0x00 /*!< No error */ #define HAL_DAC_ERROR_DMAUNDERRUNCH1 0x01 /*!< DAC channel1 DAM underrun error */ #define HAL_DAC_ERROR_DMAUNDERRUNCH2 0x02 /*!< DAC channel2 DAM underrun error */ #define HAL_DAC_ERROR_DMA 0x04 /*!< DMA error */ /** * @} */ /** @defgroup DAC_trigger_selection DAC Trigger Selection * @{ */ #define DAC_TRIGGER_NONE ((uint32_t)0x00000000) /*!< Conversion is automatic once the DAC1_DHRxxxx register has been loaded, and not by external trigger */ #define DAC_TRIGGER_T2_TRGO ((uint32_t)(DAC_CR_TSEL1_2 | DAC_CR_TEN1)) /*!< TIM2 TRGO selected as external conversion trigger for DAC channel */ #define DAC_TRIGGER_T4_TRGO ((uint32_t)(DAC_CR_TSEL1_2 | DAC_CR_TSEL1_0 | DAC_CR_TEN1)) /*!< TIM4 TRGO selected as external conversion trigger for DAC channel */ #define DAC_TRIGGER_T5_TRGO ((uint32_t)(DAC_CR_TSEL1_1 | DAC_CR_TSEL1_0 | DAC_CR_TEN1)) /*!< TIM5 TRGO selected as external conversion trigger for DAC channel */ #define DAC_TRIGGER_T6_TRGO ((uint32_t)DAC_CR_TEN1) /*!< TIM6 TRGO selected as external conversion trigger for DAC channel */ #define DAC_TRIGGER_T7_TRGO ((uint32_t)(DAC_CR_TSEL1_1 | DAC_CR_TEN1)) /*!< TIM7 TRGO selected as external conversion trigger for DAC channel */ #define DAC_TRIGGER_T8_TRGO ((uint32_t)(DAC_CR_TSEL1_0 | DAC_CR_TEN1)) /*!< TIM8 TRGO selected as external conversion trigger for DAC channel */ #define DAC_TRIGGER_EXT_IT9 ((uint32_t)(DAC_CR_TSEL1_2 | DAC_CR_TSEL1_1 | DAC_CR_TEN1)) /*!< EXTI Line9 event selected as external conversion trigger for DAC channel */ #define DAC_TRIGGER_SOFTWARE ((uint32_t)(DAC_CR_TSEL1 | DAC_CR_TEN1)) /*!< Conversion started by software trigger for DAC channel */ /** * @} */ /** @defgroup DAC_output_buffer DAC Output Buffer * @{ */ #define DAC_OUTPUTBUFFER_ENABLE ((uint32_t)0x00000000) #define DAC_OUTPUTBUFFER_DISABLE ((uint32_t)DAC_CR_BOFF1) /** * @} */ /** @defgroup DAC_Channel_selection DAC Channel Selection * @{ */ #define DAC_CHANNEL_1 ((uint32_t)0x00000000) #define DAC_CHANNEL_2 ((uint32_t)0x00000010) /** * @} */ /** @defgroup DAC_data_alignment DAC Data Alignment * @{ */ #define DAC_ALIGN_12B_R ((uint32_t)0x00000000) #define DAC_ALIGN_12B_L ((uint32_t)0x00000004) #define DAC_ALIGN_8B_R ((uint32_t)0x00000008) /** * @} */ /** @defgroup DAC_flags_definition DAC Flags Definition * @{ */ #define DAC_FLAG_DMAUDR1 ((uint32_t)DAC_SR_DMAUDR1) #define DAC_FLAG_DMAUDR2 ((uint32_t)DAC_SR_DMAUDR2) /** * @} */ /** @defgroup DAC_IT_definition DAC IT Definition * @{ */ #define DAC_IT_DMAUDR1 ((uint32_t)DAC_SR_DMAUDR1) #define DAC_IT_DMAUDR2 ((uint32_t)DAC_SR_DMAUDR2) /** * @} */ /** * @} */ /* Exported macro ------------------------------------------------------------*/ /** @defgroup DAC_Exported_Macros DAC Exported Macros * @{ */ /** @brief Reset DAC handle state * @param __HANDLE__: specifies the DAC handle. * @retval None */ #define __HAL_DAC_RESET_HANDLE_STATE(__HANDLE__) ((__HANDLE__)->State = HAL_DAC_STATE_RESET) /** @brief Enable the DAC channel * @param __HANDLE__: specifies the DAC handle. * @param __DAC_Channel__: specifies the DAC channel * @retval None */ #define __HAL_DAC_ENABLE(__HANDLE__, __DAC_Channel__) ((__HANDLE__)->Instance->CR |= (DAC_CR_EN1 << (__DAC_Channel__))) /** @brief Disable the DAC channel * @param __HANDLE__: specifies the DAC handle * @param __DAC_Channel__: specifies the DAC channel. * @retval None */ #define __HAL_DAC_DISABLE(__HANDLE__, __DAC_Channel__) ((__HANDLE__)->Instance->CR &= ~(DAC_CR_EN1 << (__DAC_Channel__))) /** @brief Enable the DAC interrupt * @param __HANDLE__: specifies the DAC handle * @param __INTERRUPT__: specifies the DAC interrupt. * @retval None */ #define __HAL_DAC_ENABLE_IT(__HANDLE__, __INTERRUPT__) (((__HANDLE__)->Instance->CR) |= (__INTERRUPT__)) /** @brief Disable the DAC interrupt * @param __HANDLE__: specifies the DAC handle * @param __INTERRUPT__: specifies the DAC interrupt. * @retval None */ #define __HAL_DAC_DISABLE_IT(__HANDLE__, __INTERRUPT__) (((__HANDLE__)->Instance->CR) &= ~(__INTERRUPT__)) /** @brief Checks if the specified DAC interrupt source is enabled or disabled. * @param __HANDLE__: DAC handle * @param __INTERRUPT__: DAC interrupt source to check * This parameter can be any combination of the following values: * @arg DAC_IT_DMAUDR1: DAC channel 1 DMA underrun interrupt * @arg DAC_IT_DMAUDR2: DAC channel 2 DMA underrun interrupt * @retval State of interruption (SET or RESET) */ #define __HAL_DAC_GET_IT_SOURCE(__HANDLE__, __INTERRUPT__) (((__HANDLE__)->Instance->CR & (__INTERRUPT__)) == (__INTERRUPT__)) /** @brief Get the selected DAC's flag status. * @param __HANDLE__: specifies the DAC handle. * @param __FLAG__: specifies the flag to clear. * This parameter can be any combination of the following values: * @arg DAC_FLAG_DMAUDR1: DMA underrun 1 flag * @arg DAC_FLAG_DMAUDR2: DMA underrun 2 flag * @retval None */ #define __HAL_DAC_GET_FLAG(__HANDLE__, __FLAG__) ((((__HANDLE__)->Instance->SR) & (__FLAG__)) == (__FLAG__)) /** @brief Clear the DAC's flag. * @param __HANDLE__: specifies the DAC handle. * @param __FLAG__: specifies the flag to clear. * This parameter can be any combination of the following values: * @arg DAC_FLAG_DMAUDR1: DMA underrun 1 flag * @arg DAC_FLAG_DMAUDR2: DMA underrun 2 flag * @retval None */ #define __HAL_DAC_CLEAR_FLAG(__HANDLE__, __FLAG__) (((__HANDLE__)->Instance->SR) = (__FLAG__)) /** * @} */ /* Include DAC HAL Extension module */ #include "stm32f4xx_hal_dac_ex.h" /* Exported functions --------------------------------------------------------*/ /** @addtogroup DAC_Exported_Functions * @{ */ /** @addtogroup DAC_Exported_Functions_Group1 * @{ */ /* Initialization/de-initialization functions *********************************/ HAL_StatusTypeDef HAL_DAC_Init(DAC_HandleTypeDef* hdac); HAL_StatusTypeDef HAL_DAC_DeInit(DAC_HandleTypeDef* hdac); void HAL_DAC_MspInit(DAC_HandleTypeDef* hdac); void HAL_DAC_MspDeInit(DAC_HandleTypeDef* hdac); /** * @} */ /** @addtogroup DAC_Exported_Functions_Group2 * @{ */ /* I/O operation functions ****************************************************/ HAL_StatusTypeDef HAL_DAC_Start(DAC_HandleTypeDef* hdac, uint32_t Channel); HAL_StatusTypeDef HAL_DAC_Stop(DAC_HandleTypeDef* hdac, uint32_t Channel); HAL_StatusTypeDef HAL_DAC_Start_DMA(DAC_HandleTypeDef* hdac, uint32_t Channel, uint32_t* pData, uint32_t Length, uint32_t Alignment); HAL_StatusTypeDef HAL_DAC_Stop_DMA(DAC_HandleTypeDef* hdac, uint32_t Channel); uint32_t HAL_DAC_GetValue(DAC_HandleTypeDef* hdac, uint32_t Channel); /** * @} */ /** @addtogroup DAC_Exported_Functions_Group3 * @{ */ /* Peripheral Control functions ***********************************************/ HAL_StatusTypeDef HAL_DAC_ConfigChannel(DAC_HandleTypeDef* hdac, DAC_ChannelConfTypeDef* sConfig, uint32_t Channel); HAL_StatusTypeDef HAL_DAC_SetValue(DAC_HandleTypeDef* hdac, uint32_t Channel, uint32_t Alignment, uint32_t Data); /** * @} */ /** @addtogroup DAC_Exported_Functions_Group4 * @{ */ /* Peripheral State functions *************************************************/ HAL_DAC_StateTypeDef HAL_DAC_GetState(DAC_HandleTypeDef* hdac); void HAL_DAC_IRQHandler(DAC_HandleTypeDef* hdac); uint32_t HAL_DAC_GetError(DAC_HandleTypeDef *hdac); void HAL_DAC_ConvCpltCallbackCh1(DAC_HandleTypeDef* hdac); void HAL_DAC_ConvHalfCpltCallbackCh1(DAC_HandleTypeDef* hdac); void HAL_DAC_ErrorCallbackCh1(DAC_HandleTypeDef *hdac); void HAL_DAC_DMAUnderrunCallbackCh1(DAC_HandleTypeDef *hdac); /** * @} */ /** * @} */ /* Private types -------------------------------------------------------------*/ /* Private variables ---------------------------------------------------------*/ /* Private constants ---------------------------------------------------------*/ /** @defgroup DAC_Private_Constants DAC Private Constants * @{ */ /** * @} */ /* Private macros ------------------------------------------------------------*/ /** @defgroup DAC_Private_Macros DAC Private Macros * @{ */ #define IS_DAC_DATA(DATA) ((DATA) <= 0xFFF0) #define IS_DAC_ALIGN(ALIGN) (((ALIGN) == DAC_ALIGN_12B_R) || \ ((ALIGN) == DAC_ALIGN_12B_L) || \ ((ALIGN) == DAC_ALIGN_8B_R)) #define IS_DAC_CHANNEL(CHANNEL) (((CHANNEL) == DAC_CHANNEL_1) || \ ((CHANNEL) == DAC_CHANNEL_2)) #define IS_DAC_OUTPUT_BUFFER_STATE(STATE) (((STATE) == DAC_OUTPUTBUFFER_ENABLE) || \ ((STATE) == DAC_OUTPUTBUFFER_DISABLE)) #define IS_DAC_TRIGGER(TRIGGER) (((TRIGGER) == DAC_TRIGGER_NONE) || \ ((TRIGGER) == DAC_TRIGGER_T2_TRGO) || \ ((TRIGGER) == DAC_TRIGGER_T8_TRGO) || \ ((TRIGGER) == DAC_TRIGGER_T7_TRGO) || \ ((TRIGGER) == DAC_TRIGGER_T5_TRGO) || \ ((TRIGGER) == DAC_TRIGGER_T6_TRGO) || \ ((TRIGGER) == DAC_TRIGGER_T4_TRGO) || \ ((TRIGGER) == DAC_TRIGGER_EXT_IT9) || \ ((TRIGGER) == DAC_TRIGGER_SOFTWARE)) /** @brief Set DHR12R1 alignment * @param __ALIGNMENT__: specifies the DAC alignment * @retval None */ #define DAC_DHR12R1_ALIGNMENT(__ALIGNMENT__) (((uint32_t)0x00000008) + (__ALIGNMENT__)) /** @brief Set DHR12R2 alignment * @param __ALIGNMENT__: specifies the DAC alignment * @retval None */ #define DAC_DHR12R2_ALIGNMENT(__ALIGNMENT__) (((uint32_t)0x00000014) + (__ALIGNMENT__)) /** @brief Set DHR12RD alignment * @param __ALIGNMENT__: specifies the DAC alignment * @retval None */ #define DAC_DHR12RD_ALIGNMENT(__ALIGNMENT__) (((uint32_t)0x00000020) + (__ALIGNMENT__)) /** * @} */ /* Private functions ---------------------------------------------------------*/ /** @defgroup DAC_Private_Functions DAC Private Functions * @{ */ /** * @} */ #endif /* STM32F405xx || STM32F415xx || STM32F407xx || STM32F417xx ||\ STM32F427xx || STM32F437xx || STM32F429xx || STM32F439xx ||\ STM32F410xx || STM32F446xx || STM32F469xx || STM32F479xx */ /** * @} */ /** * @} */ #ifdef __cplusplus } #endif #endif /*__STM32F4xx_HAL_DAC_H */ /************************ (C) COPYRIGHT STMicroelectronics *****END OF FILE****/ ================================================ FILE: Zelig/mbed/TARGET_NUCLEO_F411RE/stm32f4xx_hal_dac_ex.h ================================================ /** ****************************************************************************** * @file stm32f4xx_hal_dac.h * @author MCD Application Team * @version V1.4.1 * @date 09-October-2015 * @brief Header file of DAC HAL Extension module. ****************************************************************************** * @attention * *

© COPYRIGHT(c) 2015 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. * ****************************************************************************** */ /* Define to prevent recursive inclusion -------------------------------------*/ #ifndef __STM32F4xx_HAL_DAC_EX_H #define __STM32F4xx_HAL_DAC_EX_H #ifdef __cplusplus extern "C" { #endif #if defined(STM32F405xx) || defined(STM32F415xx) || defined(STM32F407xx) || defined(STM32F417xx) ||\ defined(STM32F427xx) || defined(STM32F437xx) || defined(STM32F429xx) || defined(STM32F439xx) ||\ defined(STM32F410Tx) || defined(STM32F410Cx) || defined(STM32F410Rx) || defined(STM32F446xx) ||\ defined(STM32F469xx) || defined(STM32F479xx) /* Includes ------------------------------------------------------------------*/ #include "stm32f4xx_hal_def.h" /** @addtogroup STM32F4xx_HAL_Driver * @{ */ /** @addtogroup DACEx * @{ */ /* Exported types ------------------------------------------------------------*/ /* Exported constants --------------------------------------------------------*/ /** @defgroup DACEx_Exported_Constants DAC Exported Constants * @{ */ /** @defgroup DACEx_lfsrunmask_triangleamplitude DAC LFS Run Mask Triangle Amplitude * @{ */ #define DAC_LFSRUNMASK_BIT0 ((uint32_t)0x00000000) /*!< Unmask DAC channel LFSR bit0 for noise wave generation */ #define DAC_LFSRUNMASK_BITS1_0 ((uint32_t)DAC_CR_MAMP1_0) /*!< Unmask DAC channel LFSR bit[1:0] for noise wave generation */ #define DAC_LFSRUNMASK_BITS2_0 ((uint32_t)DAC_CR_MAMP1_1) /*!< Unmask DAC channel LFSR bit[2:0] for noise wave generation */ #define DAC_LFSRUNMASK_BITS3_0 ((uint32_t)DAC_CR_MAMP1_1 | DAC_CR_MAMP1_0)/*!< Unmask DAC channel LFSR bit[3:0] for noise wave generation */ #define DAC_LFSRUNMASK_BITS4_0 ((uint32_t)DAC_CR_MAMP1_2) /*!< Unmask DAC channel LFSR bit[4:0] for noise wave generation */ #define DAC_LFSRUNMASK_BITS5_0 ((uint32_t)DAC_CR_MAMP1_2 | DAC_CR_MAMP1_0) /*!< Unmask DAC channel LFSR bit[5:0] for noise wave generation */ #define DAC_LFSRUNMASK_BITS6_0 ((uint32_t)DAC_CR_MAMP1_2 | DAC_CR_MAMP1_1) /*!< Unmask DAC channel LFSR bit[6:0] for noise wave generation */ #define DAC_LFSRUNMASK_BITS7_0 ((uint32_t)DAC_CR_MAMP1_2 | DAC_CR_MAMP1_1 | DAC_CR_MAMP1_0) /*!< Unmask DAC channel LFSR bit[7:0] for noise wave generation */ #define DAC_LFSRUNMASK_BITS8_0 ((uint32_t)DAC_CR_MAMP1_3) /*!< Unmask DAC channel LFSR bit[8:0] for noise wave generation */ #define DAC_LFSRUNMASK_BITS9_0 ((uint32_t)DAC_CR_MAMP1_3 | DAC_CR_MAMP1_0) /*!< Unmask DAC channel LFSR bit[9:0] for noise wave generation */ #define DAC_LFSRUNMASK_BITS10_0 ((uint32_t)DAC_CR_MAMP1_3 | DAC_CR_MAMP1_1) /*!< Unmask DAC channel LFSR bit[10:0] for noise wave generation */ #define DAC_LFSRUNMASK_BITS11_0 ((uint32_t)DAC_CR_MAMP1_3 | DAC_CR_MAMP1_1 | DAC_CR_MAMP1_0) /*!< Unmask DAC channel LFSR bit[11:0] for noise wave generation */ #define DAC_TRIANGLEAMPLITUDE_1 ((uint32_t)0x00000000) /*!< Select max triangle amplitude of 1 */ #define DAC_TRIANGLEAMPLITUDE_3 ((uint32_t)DAC_CR_MAMP1_0) /*!< Select max triangle amplitude of 3 */ #define DAC_TRIANGLEAMPLITUDE_7 ((uint32_t)DAC_CR_MAMP1_1) /*!< Select max triangle amplitude of 7 */ #define DAC_TRIANGLEAMPLITUDE_15 ((uint32_t)DAC_CR_MAMP1_1 | DAC_CR_MAMP1_0) /*!< Select max triangle amplitude of 15 */ #define DAC_TRIANGLEAMPLITUDE_31 ((uint32_t)DAC_CR_MAMP1_2) /*!< Select max triangle amplitude of 31 */ #define DAC_TRIANGLEAMPLITUDE_63 ((uint32_t)DAC_CR_MAMP1_2 | DAC_CR_MAMP1_0) /*!< Select max triangle amplitude of 63 */ #define DAC_TRIANGLEAMPLITUDE_127 ((uint32_t)DAC_CR_MAMP1_2 | DAC_CR_MAMP1_1) /*!< Select max triangle amplitude of 127 */ #define DAC_TRIANGLEAMPLITUDE_255 ((uint32_t)DAC_CR_MAMP1_2 | DAC_CR_MAMP1_1 | DAC_CR_MAMP1_0) /*!< Select max triangle amplitude of 255 */ #define DAC_TRIANGLEAMPLITUDE_511 ((uint32_t)DAC_CR_MAMP1_3) /*!< Select max triangle amplitude of 511 */ #define DAC_TRIANGLEAMPLITUDE_1023 ((uint32_t)DAC_CR_MAMP1_3 | DAC_CR_MAMP1_0) /*!< Select max triangle amplitude of 1023 */ #define DAC_TRIANGLEAMPLITUDE_2047 ((uint32_t)DAC_CR_MAMP1_3 | DAC_CR_MAMP1_1) /*!< Select max triangle amplitude of 2047 */ #define DAC_TRIANGLEAMPLITUDE_4095 ((uint32_t)DAC_CR_MAMP1_3 | DAC_CR_MAMP1_1 | DAC_CR_MAMP1_0) /*!< Select max triangle amplitude of 4095 */ /** * @} */ /** * @} */ /* Exported macro ------------------------------------------------------------*/ /* Exported functions --------------------------------------------------------*/ /** @addtogroup DACEx_Exported_Functions * @{ */ /** @addtogroup DACEx_Exported_Functions_Group1 * @{ */ /* Extension features functions ***********************************************/ uint32_t HAL_DACEx_DualGetValue(DAC_HandleTypeDef* hdac); HAL_StatusTypeDef HAL_DACEx_TriangleWaveGenerate(DAC_HandleTypeDef* hdac, uint32_t Channel, uint32_t Amplitude); HAL_StatusTypeDef HAL_DACEx_NoiseWaveGenerate(DAC_HandleTypeDef* hdac, uint32_t Channel, uint32_t Amplitude); HAL_StatusTypeDef HAL_DACEx_DualSetValue(DAC_HandleTypeDef* hdac, uint32_t Alignment, uint32_t Data1, uint32_t Data2); void HAL_DACEx_ConvCpltCallbackCh2(DAC_HandleTypeDef* hdac); void HAL_DACEx_ConvHalfCpltCallbackCh2(DAC_HandleTypeDef* hdac); void HAL_DACEx_ErrorCallbackCh2(DAC_HandleTypeDef* hdac); void HAL_DACEx_DMAUnderrunCallbackCh2(DAC_HandleTypeDef* hdac); /** * @} */ /** * @} */ /* Private types -------------------------------------------------------------*/ /* Private variables ---------------------------------------------------------*/ /* Private constants ---------------------------------------------------------*/ /** @defgroup DACEx_Private_Constants DAC Private Constants * @{ */ /** * @} */ /* Private macros ------------------------------------------------------------*/ /** @defgroup DACEx_Private_Macros DAC Private Macros * @{ */ #define IS_DAC_LFSR_UNMASK_TRIANGLE_AMPLITUDE(VALUE) (((VALUE) == DAC_LFSRUNMASK_BIT0) || \ ((VALUE) == DAC_LFSRUNMASK_BITS1_0) || \ ((VALUE) == DAC_LFSRUNMASK_BITS2_0) || \ ((VALUE) == DAC_LFSRUNMASK_BITS3_0) || \ ((VALUE) == DAC_LFSRUNMASK_BITS4_0) || \ ((VALUE) == DAC_LFSRUNMASK_BITS5_0) || \ ((VALUE) == DAC_LFSRUNMASK_BITS6_0) || \ ((VALUE) == DAC_LFSRUNMASK_BITS7_0) || \ ((VALUE) == DAC_LFSRUNMASK_BITS8_0) || \ ((VALUE) == DAC_LFSRUNMASK_BITS9_0) || \ ((VALUE) == DAC_LFSRUNMASK_BITS10_0) || \ ((VALUE) == DAC_LFSRUNMASK_BITS11_0) || \ ((VALUE) == DAC_TRIANGLEAMPLITUDE_1) || \ ((VALUE) == DAC_TRIANGLEAMPLITUDE_3) || \ ((VALUE) == DAC_TRIANGLEAMPLITUDE_7) || \ ((VALUE) == DAC_TRIANGLEAMPLITUDE_15) || \ ((VALUE) == DAC_TRIANGLEAMPLITUDE_31) || \ ((VALUE) == DAC_TRIANGLEAMPLITUDE_63) || \ ((VALUE) == DAC_TRIANGLEAMPLITUDE_127) || \ ((VALUE) == DAC_TRIANGLEAMPLITUDE_255) || \ ((VALUE) == DAC_TRIANGLEAMPLITUDE_511) || \ ((VALUE) == DAC_TRIANGLEAMPLITUDE_1023) || \ ((VALUE) == DAC_TRIANGLEAMPLITUDE_2047) || \ ((VALUE) == DAC_TRIANGLEAMPLITUDE_4095)) /** * @} */ /* Private functions ---------------------------------------------------------*/ /** @defgroup DACEx_Private_Functions DAC Private Functions * @{ */ void DAC_DMAConvCpltCh2(DMA_HandleTypeDef *hdma); void DAC_DMAErrorCh2(DMA_HandleTypeDef *hdma); void DAC_DMAHalfConvCpltCh2(DMA_HandleTypeDef *hdma); /** * @} */ #endif /* STM32F405xx || STM32F415xx || STM32F407xx || STM32F417xx ||\ STM32F427xx || STM32F437xx || STM32F429xx || STM32F439xx ||\ STM32F410xx || STM32F446xx || STM32F469xx || STM32F479xx */ /** * @} */ /** * @} */ #ifdef __cplusplus } #endif #endif /*__STM32F4xx_HAL_DAC_EX_H */ /************************ (C) COPYRIGHT STMicroelectronics *****END OF FILE****/ ================================================ FILE: Zelig/mbed/TARGET_NUCLEO_F411RE/stm32f4xx_hal_dcmi.h ================================================ /** ****************************************************************************** * @file stm32f4xx_hal_dcmi.h * @author MCD Application Team * @version V1.4.1 * @date 09-October-2015 * @brief Header file of DCMI HAL module. ****************************************************************************** * @attention * *

© COPYRIGHT(c) 2015 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. * ****************************************************************************** */ /* Define to prevent recursive inclusion -------------------------------------*/ #ifndef __STM32F4xx_HAL_DCMI_H #define __STM32F4xx_HAL_DCMI_H #ifdef __cplusplus extern "C" { #endif #if defined(STM32F407xx) || defined(STM32F417xx) || defined(STM32F427xx) || defined(STM32F437xx) ||\ defined(STM32F429xx) || defined(STM32F439xx) || defined(STM32F446xx) || defined(STM32F469xx) ||\ defined(STM32F479xx) /* Includes ------------------------------------------------------------------*/ #include "stm32f4xx_hal_def.h" /* Include DCMI HAL Extended module */ /* (include on top of file since DCMI structures are defined in extended file) */ #include "stm32f4xx_hal_dcmi_ex.h" /** @addtogroup STM32F4xx_HAL_Driver * @{ */ /** @addtogroup DCMI DCMI * @brief DCMI HAL module driver * @{ */ /* Exported types ------------------------------------------------------------*/ /** @defgroup DCMI_Exported_Types DCMI Exported Types * @{ */ /** * @brief DCMI Error source */ typedef enum { DCMI_ERROR_SYNC = 1, /*!< Synchronisation error */ DCMI_OVERRUN = 2, /*!< DCMI Overrun */ }DCMI_ErrorTypeDef; /** * @brief HAL DCMI State structures definition */ typedef enum { HAL_DCMI_STATE_RESET = 0x00, /*!< DCMI not yet initialized or disabled */ HAL_DCMI_STATE_READY = 0x01, /*!< DCMI initialized and ready for use */ HAL_DCMI_STATE_BUSY = 0x02, /*!< DCMI internal processing is ongoing */ HAL_DCMI_STATE_TIMEOUT = 0x03, /*!< DCMI timeout state */ HAL_DCMI_STATE_ERROR = 0x04 /*!< DCMI error state */ }HAL_DCMI_StateTypeDef; /** * @brief DCMI handle Structure definition */ typedef struct { DCMI_TypeDef *Instance; /*!< DCMI Register base address */ DCMI_InitTypeDef Init; /*!< DCMI parameters */ HAL_LockTypeDef Lock; /*!< DCMI locking object */ __IO HAL_DCMI_StateTypeDef State; /*!< DCMI state */ __IO uint32_t XferCount; /*!< DMA transfer counter */ __IO uint32_t XferSize; /*!< DMA transfer size */ uint32_t XferTransferNumber; /*!< DMA transfer number */ uint32_t pBuffPtr; /*!< Pointer to DMA output buffer */ DMA_HandleTypeDef *DMA_Handle; /*!< Pointer to the DMA handler */ __IO uint32_t ErrorCode; /*!< DCMI Error code */ }DCMI_HandleTypeDef; /** * @} */ /* Exported constants --------------------------------------------------------*/ /** @defgroup DCMI_Exported_Constants DCMI Exported Constants * @{ */ /** @defgroup DCMI_Error_Code DCMI Error Code * @{ */ #define HAL_DCMI_ERROR_NONE ((uint32_t)0x00000000) /*!< No error */ #define HAL_DCMI_ERROR_OVF ((uint32_t)0x00000001) /*!< Overflow error */ #define HAL_DCMI_ERROR_SYNC ((uint32_t)0x00000002) /*!< Synchronization error */ #define HAL_DCMI_ERROR_TIMEOUT ((uint32_t)0x00000020) /*!< Timeout error */ /** * @} */ /** @defgroup DCMI_Capture_Mode DCMI Capture Mode * @{ */ #define DCMI_MODE_CONTINUOUS ((uint32_t)0x00000000) /*!< The received data are transferred continuously into the destination memory through the DMA */ #define DCMI_MODE_SNAPSHOT ((uint32_t)DCMI_CR_CM) /*!< Once activated, the interface waits for the start of frame and then transfers a single frame through the DMA */ /** * @} */ /** @defgroup DCMI_Synchronization_Mode DCMI Synchronization Mode * @{ */ #define DCMI_SYNCHRO_HARDWARE ((uint32_t)0x00000000) /*!< Hardware synchronization data capture (frame/line start/stop) is synchronized with the HSYNC/VSYNC signals */ #define DCMI_SYNCHRO_EMBEDDED ((uint32_t)DCMI_CR_ESS) /*!< Embedded synchronization data capture is synchronized with synchronization codes embedded in the data flow */ /** * @} */ /** @defgroup DCMI_PIXCK_Polarity DCMI PIXCK Polarity * @{ */ #define DCMI_PCKPOLARITY_FALLING ((uint32_t)0x00000000) /*!< Pixel clock active on Falling edge */ #define DCMI_PCKPOLARITY_RISING ((uint32_t)DCMI_CR_PCKPOL) /*!< Pixel clock active on Rising edge */ /** * @} */ /** @defgroup DCMI_VSYNC_Polarity DCMI VSYNC Polarity * @{ */ #define DCMI_VSPOLARITY_LOW ((uint32_t)0x00000000) /*!< Vertical synchronization active Low */ #define DCMI_VSPOLARITY_HIGH ((uint32_t)DCMI_CR_VSPOL) /*!< Vertical synchronization active High */ /** * @} */ /** @defgroup DCMI_HSYNC_Polarity DCMI HSYNC Polarity * @{ */ #define DCMI_HSPOLARITY_LOW ((uint32_t)0x00000000) /*!< Horizontal synchronization active Low */ #define DCMI_HSPOLARITY_HIGH ((uint32_t)DCMI_CR_HSPOL) /*!< Horizontal synchronization active High */ /** * @} */ /** @defgroup DCMI_MODE_JPEG DCMI MODE JPEG * @{ */ #define DCMI_JPEG_DISABLE ((uint32_t)0x00000000) /*!< Mode JPEG Disabled */ #define DCMI_JPEG_ENABLE ((uint32_t)DCMI_CR_JPEG) /*!< Mode JPEG Enabled */ /** * @} */ /** @defgroup DCMI_Capture_Rate DCMI Capture Rate * @{ */ #define DCMI_CR_ALL_FRAME ((uint32_t)0x00000000) /*!< All frames are captured */ #define DCMI_CR_ALTERNATE_2_FRAME ((uint32_t)DCMI_CR_FCRC_0) /*!< Every alternate frame captured */ #define DCMI_CR_ALTERNATE_4_FRAME ((uint32_t)DCMI_CR_FCRC_1) /*!< One frame in 4 frames captured */ /** * @} */ /** @defgroup DCMI_Extended_Data_Mode DCMI Extended Data Mode * @{ */ #define DCMI_EXTEND_DATA_8B ((uint32_t)0x00000000) /*!< Interface captures 8-bit data on every pixel clock */ #define DCMI_EXTEND_DATA_10B ((uint32_t)DCMI_CR_EDM_0) /*!< Interface captures 10-bit data on every pixel clock */ #define DCMI_EXTEND_DATA_12B ((uint32_t)DCMI_CR_EDM_1) /*!< Interface captures 12-bit data on every pixel clock */ #define DCMI_EXTEND_DATA_14B ((uint32_t)(DCMI_CR_EDM_0 | DCMI_CR_EDM_1)) /*!< Interface captures 14-bit data on every pixel clock */ /** * @} */ /** @defgroup DCMI_Window_Coordinate DCMI Window Coordinate * @{ */ #define DCMI_WINDOW_COORDINATE ((uint32_t)0x3FFF) /*!< Window coordinate */ /** * @} */ /** @defgroup DCMI_Window_Height DCMI Window Height * @{ */ #define DCMI_WINDOW_HEIGHT ((uint32_t)0x1FFF) /*!< Window Height */ /** * @} */ /** @defgroup DCMI_interrupt_sources DCMI interrupt sources * @{ */ #define DCMI_IT_FRAME ((uint32_t)DCMI_IER_FRAME_IE) #define DCMI_IT_OVF ((uint32_t)DCMI_IER_OVF_IE) #define DCMI_IT_ERR ((uint32_t)DCMI_IER_ERR_IE) #define DCMI_IT_VSYNC ((uint32_t)DCMI_IER_VSYNC_IE) #define DCMI_IT_LINE ((uint32_t)DCMI_IER_LINE_IE) /** * @} */ /** @defgroup DCMI_Flags DCMI Flags * @{ */ /** * @brief DCMI SR register */ #define DCMI_FLAG_HSYNC ((uint32_t)0x2001) #define DCMI_FLAG_VSYNC ((uint32_t)0x2002) #define DCMI_FLAG_FNE ((uint32_t)0x2004) /** * @brief DCMI RISR register */ #define DCMI_FLAG_FRAMERI ((uint32_t)DCMI_RISR_FRAME_RIS) #define DCMI_FLAG_OVFRI ((uint32_t)DCMI_RISR_OVF_RIS) #define DCMI_FLAG_ERRRI ((uint32_t)DCMI_RISR_ERR_RIS) #define DCMI_FLAG_VSYNCRI ((uint32_t)DCMI_RISR_VSYNC_RIS) #define DCMI_FLAG_LINERI ((uint32_t)DCMI_RISR_LINE_RIS) /** * @brief DCMI MISR register */ #define DCMI_FLAG_FRAMEMI ((uint32_t)0x1001) #define DCMI_FLAG_OVFMI ((uint32_t)0x1002) #define DCMI_FLAG_ERRMI ((uint32_t)0x1004) #define DCMI_FLAG_VSYNCMI ((uint32_t)0x1008) #define DCMI_FLAG_LINEMI ((uint32_t)0x1010) /** * @} */ /** * @} */ /* Exported macro ------------------------------------------------------------*/ /** @defgroup DCMI_Exported_Macros DCMI Exported Macros * @{ */ /** @brief Reset DCMI handle state * @param __HANDLE__: specifies the DCMI handle. * @retval None */ #define __HAL_DCMI_RESET_HANDLE_STATE(__HANDLE__) ((__HANDLE__)->State = HAL_DCMI_STATE_RESET) /** * @brief Enable the DCMI. * @param __HANDLE__: DCMI handle * @retval None */ #define __HAL_DCMI_ENABLE(__HANDLE__) ((__HANDLE__)->Instance->CR |= DCMI_CR_ENABLE) /** * @brief Disable the DCMI. * @param __HANDLE__: DCMI handle * @retval None */ #define __HAL_DCMI_DISABLE(__HANDLE__) ((__HANDLE__)->Instance->CR &= ~(DCMI_CR_ENABLE)) /* Interrupt & Flag management */ /** * @brief Get the DCMI pending flags. * @param __HANDLE__: DCMI handle * @param __FLAG__: Get the specified flag. * This parameter can be any combination of the following values: * @arg DCMI_FLAG_FRAMERI: Frame capture complete flag mask * @arg DCMI_FLAG_OVFRI: Overflow flag mask * @arg DCMI_FLAG_ERRRI: Synchronization error flag mask * @arg DCMI_FLAG_VSYNCRI: VSYNC flag mask * @arg DCMI_FLAG_LINERI: Line flag mask * @retval The state of FLAG. */ #define __HAL_DCMI_GET_FLAG(__HANDLE__, __FLAG__)\ ((((__FLAG__) & 0x3000) == 0x0)? ((__HANDLE__)->Instance->RISR & (__FLAG__)) :\ (((__FLAG__) & 0x2000) == 0x0)? ((__HANDLE__)->Instance->MISR & (__FLAG__)) : ((__HANDLE__)->Instance->SR & (__FLAG__))) /** * @brief Clear the DCMI pending flags. * @param __HANDLE__: DCMI handle * @param __FLAG__: specifies the flag to clear. * This parameter can be any combination of the following values: * @arg DCMI_FLAG_FRAMERI: Frame capture complete flag mask * @arg DCMI_FLAG_OVFRI: Overflow flag mask * @arg DCMI_FLAG_ERRRI: Synchronization error flag mask * @arg DCMI_FLAG_VSYNCRI: VSYNC flag mask * @arg DCMI_FLAG_LINERI: Line flag mask * @retval None */ #define __HAL_DCMI_CLEAR_FLAG(__HANDLE__, __FLAG__) ((__HANDLE__)->Instance->ICR = (__FLAG__)) /** * @brief Enable the specified DCMI interrupts. * @param __HANDLE__: DCMI handle * @param __INTERRUPT__: specifies the DCMI interrupt sources to be enabled. * This parameter can be any combination of the following values: * @arg DCMI_IT_FRAME: Frame capture complete interrupt mask * @arg DCMI_IT_OVF: Overflow interrupt mask * @arg DCMI_IT_ERR: Synchronization error interrupt mask * @arg DCMI_IT_VSYNC: VSYNC interrupt mask * @arg DCMI_IT_LINE: Line interrupt mask * @retval None */ #define __HAL_DCMI_ENABLE_IT(__HANDLE__, __INTERRUPT__) ((__HANDLE__)->Instance->IER |= (__INTERRUPT__)) /** * @brief Disable the specified DCMI interrupts. * @param __HANDLE__: DCMI handle * @param __INTERRUPT__: specifies the DCMI interrupt sources to be enabled. * This parameter can be any combination of the following values: * @arg DCMI_IT_FRAME: Frame capture complete interrupt mask * @arg DCMI_IT_OVF: Overflow interrupt mask * @arg DCMI_IT_ERR: Synchronization error interrupt mask * @arg DCMI_IT_VSYNC: VSYNC interrupt mask * @arg DCMI_IT_LINE: Line interrupt mask * @retval None */ #define __HAL_DCMI_DISABLE_IT(__HANDLE__, __INTERRUPT__) ((__HANDLE__)->Instance->IER &= ~(__INTERRUPT__)) /** * @brief Check whether the specified DCMI interrupt has occurred or not. * @param __HANDLE__: DCMI handle * @param __INTERRUPT__: specifies the DCMI interrupt source to check. * This parameter can be one of the following values: * @arg DCMI_IT_FRAME: Frame capture complete interrupt mask * @arg DCMI_IT_OVF: Overflow interrupt mask * @arg DCMI_IT_ERR: Synchronization error interrupt mask * @arg DCMI_IT_VSYNC: VSYNC interrupt mask * @arg DCMI_IT_LINE: Line interrupt mask * @retval The state of INTERRUPT. */ #define __HAL_DCMI_GET_IT_SOURCE(__HANDLE__, __INTERRUPT__) ((__HANDLE__)->Instance->MISR & (__INTERRUPT__)) /** * @} */ /* Exported functions --------------------------------------------------------*/ /** @addtogroup DCMI_Exported_Functions * @{ */ /** @addtogroup DCMI_Exported_Functions_Group1 * @{ */ /* Initialization and de-initialization functions *****************************/ HAL_StatusTypeDef HAL_DCMI_Init(DCMI_HandleTypeDef *hdcmi); HAL_StatusTypeDef HAL_DCMI_DeInit(DCMI_HandleTypeDef *hdcmi); void HAL_DCMI_MspInit(DCMI_HandleTypeDef* hdcmi); void HAL_DCMI_MspDeInit(DCMI_HandleTypeDef* hdcmi); /** * @} */ /** @addtogroup DCMI_Exported_Functions_Group2 * @{ */ /* IO operation functions *****************************************************/ HAL_StatusTypeDef HAL_DCMI_Start_DMA(DCMI_HandleTypeDef* hdcmi, uint32_t DCMI_Mode, uint32_t pData, uint32_t Length); HAL_StatusTypeDef HAL_DCMI_Stop(DCMI_HandleTypeDef* hdcmi); void HAL_DCMI_ErrorCallback(DCMI_HandleTypeDef *hdcmi); void HAL_DCMI_LineEventCallback(DCMI_HandleTypeDef *hdcmi); void HAL_DCMI_FrameEventCallback(DCMI_HandleTypeDef *hdcmi); void HAL_DCMI_VsyncEventCallback(DCMI_HandleTypeDef *hdcmi); void HAL_DCMI_IRQHandler(DCMI_HandleTypeDef *hdcmi); /** * @} */ /** @addtogroup DCMI_Exported_Functions_Group3 * @{ */ /* Peripheral Control functions ***********************************************/ HAL_StatusTypeDef HAL_DCMI_ConfigCROP(DCMI_HandleTypeDef *hdcmi, uint32_t X0, uint32_t Y0, uint32_t XSize, uint32_t YSize); HAL_StatusTypeDef HAL_DCMI_EnableCROP(DCMI_HandleTypeDef *hdcmi); HAL_StatusTypeDef HAL_DCMI_DisableCROP(DCMI_HandleTypeDef *hdcmi); /** * @} */ /** @addtogroup DCMI_Exported_Functions_Group4 * @{ */ /* Peripheral State functions *************************************************/ HAL_DCMI_StateTypeDef HAL_DCMI_GetState(DCMI_HandleTypeDef *hdcmi); uint32_t HAL_DCMI_GetError(DCMI_HandleTypeDef *hdcmi); /** * @} */ /** * @} */ /* Private types -------------------------------------------------------------*/ /* Private variables ---------------------------------------------------------*/ /* Private constants ---------------------------------------------------------*/ /* Private macro -------------------------------------------------------------*/ /** @defgroup DCMI_Private_Macros DCMI Private Macros * @{ */ #define IS_DCMI_CAPTURE_MODE(MODE)(((MODE) == DCMI_MODE_CONTINUOUS) || \ ((MODE) == DCMI_MODE_SNAPSHOT)) #define IS_DCMI_SYNCHRO(MODE)(((MODE) == DCMI_SYNCHRO_HARDWARE) || \ ((MODE) == DCMI_SYNCHRO_EMBEDDED)) #define IS_DCMI_PCKPOLARITY(POLARITY)(((POLARITY) == DCMI_PCKPOLARITY_FALLING) || \ ((POLARITY) == DCMI_PCKPOLARITY_RISING)) #define IS_DCMI_VSPOLARITY(POLARITY)(((POLARITY) == DCMI_VSPOLARITY_LOW) || \ ((POLARITY) == DCMI_VSPOLARITY_HIGH)) #define IS_DCMI_HSPOLARITY(POLARITY)(((POLARITY) == DCMI_HSPOLARITY_LOW) || \ ((POLARITY) == DCMI_HSPOLARITY_HIGH)) #define IS_DCMI_MODE_JPEG(JPEG_MODE)(((JPEG_MODE) == DCMI_JPEG_DISABLE) || \ ((JPEG_MODE) == DCMI_JPEG_ENABLE)) #define IS_DCMI_CAPTURE_RATE(RATE) (((RATE) == DCMI_CR_ALL_FRAME) || \ ((RATE) == DCMI_CR_ALTERNATE_2_FRAME) || \ ((RATE) == DCMI_CR_ALTERNATE_4_FRAME)) #define IS_DCMI_EXTENDED_DATA(DATA)(((DATA) == DCMI_EXTEND_DATA_8B) || \ ((DATA) == DCMI_EXTEND_DATA_10B) || \ ((DATA) == DCMI_EXTEND_DATA_12B) || \ ((DATA) == DCMI_EXTEND_DATA_14B)) #define IS_DCMI_WINDOW_COORDINATE(COORDINATE) ((COORDINATE) <= DCMI_WINDOW_COORDINATE) #define IS_DCMI_WINDOW_HEIGHT(HEIGHT) ((HEIGHT) <= DCMI_WINDOW_HEIGHT) /** * @} */ /* Private functions ---------------------------------------------------------*/ /** @addtogroup DCMI_Private_Functions DCMI Private Functions * @{ */ /** * @} */ #endif /* STM32F407xx || STM32F417xx || STM32F427xx || STM32F437xx ||\ STM32F429xx || STM32F439xx || STM32F446xx || STM32F469xx ||\ STM32F479xx */ /** * @} */ /** * @} */ #ifdef __cplusplus } #endif #endif /* __STM32F4xx_HAL_DCMI_H */ /************************ (C) COPYRIGHT STMicroelectronics *****END OF FILE****/ ================================================ FILE: Zelig/mbed/TARGET_NUCLEO_F411RE/stm32f4xx_hal_dcmi_ex.h ================================================ /** ****************************************************************************** * @file stm32f4xx_hal_dcmi_ex.h * @author MCD Application Team * @version V1.4.1 * @date 09-October-2015 * @brief Header file of DCMI Extension HAL module. ****************************************************************************** * @attention * *

© COPYRIGHT(c) 2015 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. * ****************************************************************************** */ /* Define to prevent recursive inclusion -------------------------------------*/ #ifndef __STM32F4xx_HAL_DCMI_EX_H #define __STM32F4xx_HAL_DCMI_EX_H #ifdef __cplusplus extern "C" { #endif #if defined(STM32F407xx) || defined(STM32F417xx) || defined(STM32F427xx) || defined(STM32F437xx) ||\ defined(STM32F429xx) || defined(STM32F439xx) || defined(STM32F446xx) || defined(STM32F469xx) ||\ defined(STM32F479xx) /* Includes ------------------------------------------------------------------*/ #include "stm32f4xx_hal_def.h" /** @addtogroup STM32F4xx_HAL_Driver * @{ */ /** @addtogroup DCMIEx * @brief DCMI HAL module driver * @{ */ /* Exported types ------------------------------------------------------------*/ /** @defgroup DCMIEx_Exported_Types DCMI Extended Exported Types * @{ */ /** * @brief DCMIEx Embedded Synchronisation CODE Init structure definition */ typedef struct { uint8_t FrameStartCode; /*!< Specifies the code of the frame start delimiter. */ uint8_t LineStartCode; /*!< Specifies the code of the line start delimiter. */ uint8_t LineEndCode; /*!< Specifies the code of the line end delimiter. */ uint8_t FrameEndCode; /*!< Specifies the code of the frame end delimiter. */ }DCMI_CodesInitTypeDef; /** * @brief DCMI Init structure definition */ typedef struct { uint32_t SynchroMode; /*!< Specifies the Synchronization Mode: Hardware or Embedded. This parameter can be a value of @ref DCMI_Synchronization_Mode */ uint32_t PCKPolarity; /*!< Specifies the Pixel clock polarity: Falling or Rising. This parameter can be a value of @ref DCMI_PIXCK_Polarity */ uint32_t VSPolarity; /*!< Specifies the Vertical synchronization polarity: High or Low. This parameter can be a value of @ref DCMI_VSYNC_Polarity */ uint32_t HSPolarity; /*!< Specifies the Horizontal synchronization polarity: High or Low. This parameter can be a value of @ref DCMI_HSYNC_Polarity */ uint32_t CaptureRate; /*!< Specifies the frequency of frame capture: All, 1/2 or 1/4. This parameter can be a value of @ref DCMI_Capture_Rate */ uint32_t ExtendedDataMode; /*!< Specifies the data width: 8-bit, 10-bit, 12-bit or 14-bit. This parameter can be a value of @ref DCMI_Extended_Data_Mode */ DCMI_CodesInitTypeDef SyncroCode; /*!< Specifies the code of the frame start delimiter. */ uint32_t JPEGMode; /*!< Enable or Disable the JPEG mode. This parameter can be a value of @ref DCMI_MODE_JPEG */ #if defined(STM32F446xx) || defined(STM32F469xx) || defined(STM32F479xx) uint32_t ByteSelectMode; /*!< Specifies the data to be captured by the interface This parameter can be a value of @ref DCMIEx_Byte_Select_Mode */ uint32_t ByteSelectStart; /*!< Specifies if the data to be captured by the interface is even or odd This parameter can be a value of @ref DCMIEx_Byte_Select_Start */ uint32_t LineSelectMode; /*!< Specifies the line of data to be captured by the interface This parameter can be a value of @ref DCMIEx_Line_Select_Mode */ uint32_t LineSelectStart; /*!< Specifies if the line of data to be captured by the interface is even or odd This parameter can be a value of @ref DCMIEx_Line_Select_Start */ #endif /* STM32F446xx || STM32F469xx || STM32F479xx */ }DCMI_InitTypeDef; /** * @} */ /* Exported constants --------------------------------------------------------*/ #if defined(STM32F446xx) || defined(STM32F469xx) || defined(STM32F479xx) /** @defgroup DCMIEx_Exported_Constants DCMI Exported Constants * @{ */ /** @defgroup DCMIEx_Byte_Select_Mode DCMI Byte Select Mode * @{ */ #define DCMI_BSM_ALL ((uint32_t)0x00000000) /*!< Interface captures all received data */ #define DCMI_BSM_OTHER ((uint32_t)DCMI_CR_BSM_0) /*!< Interface captures every other byte from the received data */ #define DCMI_BSM_ALTERNATE_4 ((uint32_t)DCMI_CR_BSM_1) /*!< Interface captures one byte out of four */ #define DCMI_BSM_ALTERNATE_2 ((uint32_t)(DCMI_CR_BSM_0 | DCMI_CR_BSM_1)) /*!< Interface captures two bytes out of four */ /** * @} */ /** @defgroup DCMIEx_Byte_Select_Start DCMI Byte Select Start * @{ */ #define DCMI_OEBS_ODD ((uint32_t)0x00000000) /*!< Interface captures first data from the frame/line start, second one being dropped */ #define DCMI_OEBS_EVEN ((uint32_t)DCMI_CR_OEBS) /*!< Interface captures second data from the frame/line start, first one being dropped */ /** * @} */ /** @defgroup DCMIEx_Line_Select_Mode DCMI Line Select Mode * @{ */ #define DCMI_LSM_ALL ((uint32_t)0x00000000) /*!< Interface captures all received lines */ #define DCMI_LSM_ALTERNATE_2 ((uint32_t)DCMI_CR_LSM) /*!< Interface captures one line out of two */ /** * @} */ /** @defgroup DCMIEx_Line_Select_Start DCMI Line Select Start * @{ */ #define DCMI_OELS_ODD ((uint32_t)0x00000000) /*!< Interface captures first line from the frame start, second one being dropped */ #define DCMI_OELS_EVEN ((uint32_t)DCMI_CR_OELS) /*!< Interface captures second line from the frame start, first one being dropped */ /** * @} */ /** * @} */ /* Exported macro ------------------------------------------------------------*/ /* Exported functions --------------------------------------------------------*/ /* Private types -------------------------------------------------------------*/ /* Private variables ---------------------------------------------------------*/ /* Private constants ---------------------------------------------------------*/ /* Private macro -------------------------------------------------------------*/ /** @defgroup DCMIEx_Private_Macros DCMI Extended Private Macros * @{ */ #define IS_DCMI_BYTE_SELECT_MODE(MODE)(((MODE) == DCMI_BSM_ALL) || \ ((MODE) == DCMI_BSM_OTHER) || \ ((MODE) == DCMI_BSM_ALTERNATE_4) || \ ((MODE) == DCMI_BSM_ALTERNATE_2)) #define IS_DCMI_BYTE_SELECT_START(POLARITY)(((POLARITY) == DCMI_OEBS_ODD) || \ ((POLARITY) == DCMI_OEBS_EVEN)) #define IS_DCMI_LINE_SELECT_MODE(MODE)(((MODE) == DCMI_LSM_ALL) || \ ((MODE) == DCMI_LSM_ALTERNATE_2)) #define IS_DCMI_LINE_SELECT_START(POLARITY)(((POLARITY) == DCMI_OELS_ODD) || \ ((POLARITY) == DCMI_OELS_EVEN)) #endif /* STM32F446xx || STM32F469xx || STM32F479xx */ /** * @} */ /* Private functions ---------------------------------------------------------*/ #endif /* STM32F407xx || STM32F417xx || STM32F427xx || STM32F437xx ||\ STM32F429xx || STM32F439xx || STM32F446xx || STM32F469xx ||\ STM32F479xx */ /** * @} */ /** * @} */ #ifdef __cplusplus } #endif #endif /* __STM32F4xx_HAL_DCMI_H */ /************************ (C) COPYRIGHT STMicroelectronics *****END OF FILE****/ ================================================ FILE: Zelig/mbed/TARGET_NUCLEO_F411RE/stm32f4xx_hal_def.h ================================================ /** ****************************************************************************** * @file stm32f4xx_hal_def.h * @author MCD Application Team * @version V1.4.1 * @date 09-October-2015 * @brief This file contains HAL common defines, enumeration, macros and * structures definitions. ****************************************************************************** * @attention * *

© COPYRIGHT(c) 2015 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. * ****************************************************************************** */ /* Define to prevent recursive inclusion -------------------------------------*/ #ifndef __STM32F4xx_HAL_DEF #define __STM32F4xx_HAL_DEF #ifdef __cplusplus extern "C" { #endif /* Includes ------------------------------------------------------------------*/ #include "stm32f4xx.h" #include "stm32_hal_legacy.h" #include /* Exported types ------------------------------------------------------------*/ /** * @brief HAL Status structures definition */ typedef enum { HAL_OK = 0x00, HAL_ERROR = 0x01, HAL_BUSY = 0x02, HAL_TIMEOUT = 0x03 } HAL_StatusTypeDef; /** * @brief HAL Lock structures definition */ typedef enum { HAL_UNLOCKED = 0x00, HAL_LOCKED = 0x01 } HAL_LockTypeDef; /* Exported macro ------------------------------------------------------------*/ #define HAL_MAX_DELAY 0xFFFFFFFF #define HAL_IS_BIT_SET(REG, BIT) (((REG) & (BIT)) != RESET) #define HAL_IS_BIT_CLR(REG, BIT) (((REG) & (BIT)) == RESET) #define __HAL_LINKDMA(__HANDLE__, __PPP_DMA_FIELD__, __DMA_HANDLE__) \ do{ \ (__HANDLE__)->__PPP_DMA_FIELD__ = &(__DMA_HANDLE__); \ (__DMA_HANDLE__).Parent = (__HANDLE__); \ } while(0) #define UNUSED(x) ((void)(x)) /** @brief Reset the Handle's State field. * @param __HANDLE__: specifies the Peripheral Handle. * @note This macro can be used for the following purpose: * - When the Handle is declared as local variable; before passing it as parameter * to HAL_PPP_Init() for the first time, it is mandatory to use this macro * to set to 0 the Handle's "State" field. * Otherwise, "State" field may have any random value and the first time the function * HAL_PPP_Init() is called, the low level hardware initialization will be missed * (i.e. HAL_PPP_MspInit() will not be executed). * - When there is a need to reconfigure the low level hardware: instead of calling * HAL_PPP_DeInit() then HAL_PPP_Init(), user can make a call to this macro then HAL_PPP_Init(). * In this later function, when the Handle's "State" field is set to 0, it will execute the function * HAL_PPP_MspInit() which will reconfigure the low level hardware. * @retval None */ #define __HAL_RESET_HANDLE_STATE(__HANDLE__) ((__HANDLE__)->State = 0) #if (USE_RTOS == 1) /* Reserved for future use */ #error USE_RTOS should be 0 in the current HAL release #else #define __HAL_LOCK(__HANDLE__) \ do{ \ if((__HANDLE__)->Lock == HAL_LOCKED) \ { \ return HAL_BUSY; \ } \ else \ { \ (__HANDLE__)->Lock = HAL_LOCKED; \ } \ }while (0) #define __HAL_UNLOCK(__HANDLE__) \ do{ \ (__HANDLE__)->Lock = HAL_UNLOCKED; \ }while (0) #endif /* USE_RTOS */ #if defined ( __GNUC__ ) #ifndef __weak #define __weak __attribute__((weak)) #endif /* __weak */ #ifndef __packed #define __packed __attribute__((__packed__)) #endif /* __packed */ #endif /* __GNUC__ */ /* Macro to get variable aligned on 4-bytes, for __ICCARM__ the directive "#pragma data_alignment=4" must be used instead */ #if defined (__GNUC__) /* GNU Compiler */ #ifndef __ALIGN_END #define __ALIGN_END __attribute__ ((aligned (4))) #endif /* __ALIGN_END */ #ifndef __ALIGN_BEGIN #define __ALIGN_BEGIN #endif /* __ALIGN_BEGIN */ #else #ifndef __ALIGN_END #define __ALIGN_END #endif /* __ALIGN_END */ #ifndef __ALIGN_BEGIN #if defined (__CC_ARM) /* ARM Compiler */ #define __ALIGN_BEGIN __align(4) #elif defined (__ICCARM__) /* IAR Compiler */ #define __ALIGN_BEGIN #endif /* __CC_ARM */ #endif /* __ALIGN_BEGIN */ #endif /* __GNUC__ */ /** * @brief __RAM_FUNC definition */ #if defined ( __CC_ARM ) /* ARM Compiler ------------ RAM functions are defined using the toolchain options. Functions that are executed in RAM should reside in a separate source module. Using the 'Options for File' dialog you can simply change the 'Code / Const' area of a module to a memory space in physical RAM. Available memory areas are declared in the 'Target' tab of the 'Options for Target' dialog. */ #define __RAM_FUNC HAL_StatusTypeDef #elif defined ( __ICCARM__ ) /* ICCARM Compiler --------------- RAM functions are defined using a specific toolchain keyword "__ramfunc". */ #define __RAM_FUNC __ramfunc HAL_StatusTypeDef #elif defined ( __GNUC__ ) /* GNU Compiler ------------ RAM functions are defined using a specific toolchain attribute "__attribute__((section(".RamFunc")))". */ #define __RAM_FUNC HAL_StatusTypeDef __attribute__((section(".RamFunc"))) #endif /** * @brief __NOINLINE definition */ #if defined ( __CC_ARM ) || defined ( __GNUC__ ) /* ARM & GNUCompiler ---------------- */ #define __NOINLINE __attribute__ ( (noinline) ) #elif defined ( __ICCARM__ ) /* ICCARM Compiler --------------- */ #define __NOINLINE _Pragma("optimize = no_inline") #endif #ifdef __cplusplus } #endif #endif /* ___STM32F4xx_HAL_DEF */ /************************ (C) COPYRIGHT STMicroelectronics *****END OF FILE****/ ================================================ FILE: Zelig/mbed/TARGET_NUCLEO_F411RE/stm32f4xx_hal_dma.h ================================================ /** ****************************************************************************** * @file stm32f4xx_hal_dma.h * @author MCD Application Team * @version V1.4.1 * @date 09-October-2015 * @brief Header file of DMA HAL module. ****************************************************************************** * @attention * *

© COPYRIGHT(c) 2015 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. * ****************************************************************************** */ /* Define to prevent recursive inclusion -------------------------------------*/ #ifndef __STM32F4xx_HAL_DMA_H #define __STM32F4xx_HAL_DMA_H #ifdef __cplusplus extern "C" { #endif /* Includes ------------------------------------------------------------------*/ #include "stm32f4xx_hal_def.h" /** @addtogroup STM32F4xx_HAL_Driver * @{ */ /** @addtogroup DMA * @{ */ /* Exported types ------------------------------------------------------------*/ /** @defgroup DMA_Exported_Types DMA Exported Types * @brief DMA Exported Types * @{ */ /** * @brief DMA Configuration Structure definition */ typedef struct { uint32_t Channel; /*!< Specifies the channel used for the specified stream. This parameter can be a value of @ref DMA_Channel_selection */ uint32_t Direction; /*!< Specifies if the data will be transferred from memory to peripheral, from memory to memory or from peripheral to memory. This parameter can be a value of @ref DMA_Data_transfer_direction */ uint32_t PeriphInc; /*!< Specifies whether the Peripheral address register should be incremented or not. This parameter can be a value of @ref DMA_Peripheral_incremented_mode */ uint32_t MemInc; /*!< Specifies whether the memory address register should be incremented or not. This parameter can be a value of @ref DMA_Memory_incremented_mode */ uint32_t PeriphDataAlignment; /*!< Specifies the Peripheral data width. This parameter can be a value of @ref DMA_Peripheral_data_size */ uint32_t MemDataAlignment; /*!< Specifies the Memory data width. This parameter can be a value of @ref DMA_Memory_data_size */ uint32_t Mode; /*!< Specifies the operation mode of the DMAy Streamx. This parameter can be a value of @ref DMA_mode @note The circular buffer mode cannot be used if the memory-to-memory data transfer is configured on the selected Stream */ uint32_t Priority; /*!< Specifies the software priority for the DMAy Streamx. This parameter can be a value of @ref DMA_Priority_level */ uint32_t FIFOMode; /*!< Specifies if the FIFO mode or Direct mode will be used for the specified stream. This parameter can be a value of @ref DMA_FIFO_direct_mode @note The Direct mode (FIFO mode disabled) cannot be used if the memory-to-memory data transfer is configured on the selected stream */ uint32_t FIFOThreshold; /*!< Specifies the FIFO threshold level. This parameter can be a value of @ref DMA_FIFO_threshold_level */ uint32_t MemBurst; /*!< Specifies the Burst transfer configuration for the memory transfers. It specifies the amount of data to be transferred in a single non interruptible transaction. This parameter can be a value of @ref DMA_Memory_burst @note The burst mode is possible only if the address Increment mode is enabled. */ uint32_t PeriphBurst; /*!< Specifies the Burst transfer configuration for the peripheral transfers. It specifies the amount of data to be transferred in a single non interruptable transaction. This parameter can be a value of @ref DMA_Peripheral_burst @note The burst mode is possible only if the address Increment mode is enabled. */ }DMA_InitTypeDef; /** * @brief HAL DMA State structures definition */ typedef enum { HAL_DMA_STATE_RESET = 0x00, /*!< DMA not yet initialized or disabled */ HAL_DMA_STATE_READY = 0x01, /*!< DMA initialized and ready for use */ HAL_DMA_STATE_READY_MEM0 = 0x11, /*!< DMA Mem0 process success */ HAL_DMA_STATE_READY_MEM1 = 0x21, /*!< DMA Mem1 process success */ HAL_DMA_STATE_READY_HALF_MEM0 = 0x31, /*!< DMA Mem0 Half process success */ HAL_DMA_STATE_READY_HALF_MEM1 = 0x41, /*!< DMA Mem1 Half process success */ HAL_DMA_STATE_BUSY = 0x02, /*!< DMA process is ongoing */ HAL_DMA_STATE_BUSY_MEM0 = 0x12, /*!< DMA Mem0 process is ongoing */ HAL_DMA_STATE_BUSY_MEM1 = 0x22, /*!< DMA Mem1 process is ongoing */ HAL_DMA_STATE_TIMEOUT = 0x03, /*!< DMA timeout state */ HAL_DMA_STATE_ERROR = 0x04, /*!< DMA error state */ }HAL_DMA_StateTypeDef; /** * @brief HAL DMA Error Code structure definition */ typedef enum { HAL_DMA_FULL_TRANSFER = 0x00, /*!< Full transfer */ HAL_DMA_HALF_TRANSFER = 0x01, /*!< Half Transfer */ }HAL_DMA_LevelCompleteTypeDef; /** * @brief DMA handle Structure definition */ typedef struct __DMA_HandleTypeDef { DMA_Stream_TypeDef *Instance; /*!< Register base address */ DMA_InitTypeDef Init; /*!< DMA communication parameters */ HAL_LockTypeDef Lock; /*!< DMA locking object */ __IO HAL_DMA_StateTypeDef State; /*!< DMA transfer state */ void *Parent; /*!< Parent object state */ void (* XferCpltCallback)( struct __DMA_HandleTypeDef * hdma); /*!< DMA transfer complete callback */ void (* XferHalfCpltCallback)( struct __DMA_HandleTypeDef * hdma); /*!< DMA Half transfer complete callback */ void (* XferM1CpltCallback)( struct __DMA_HandleTypeDef * hdma); /*!< DMA transfer complete Memory1 callback */ void (* XferErrorCallback)( struct __DMA_HandleTypeDef * hdma); /*!< DMA transfer error callback */ __IO uint32_t ErrorCode; /*!< DMA Error code */ uint32_t StreamBaseAddress; /*!< DMA Stream Base Address */ uint32_t StreamIndex; /*!< DMA Stream Index */ }DMA_HandleTypeDef; /** * @} */ /* Exported constants --------------------------------------------------------*/ /** @defgroup DMA_Exported_Constants DMA Exported Constants * @brief DMA Exported constants * @{ */ /** @defgroup DMA_Error_Code DMA Error Code * @brief DMA Error Code * @{ */ #define HAL_DMA_ERROR_NONE ((uint32_t)0x00000000) /*!< No error */ #define HAL_DMA_ERROR_TE ((uint32_t)0x00000001) /*!< Transfer error */ #define HAL_DMA_ERROR_FE ((uint32_t)0x00000002) /*!< FIFO error */ #define HAL_DMA_ERROR_DME ((uint32_t)0x00000004) /*!< Direct Mode error */ #define HAL_DMA_ERROR_TIMEOUT ((uint32_t)0x00000020) /*!< Timeout error */ /** * @} */ /** @defgroup DMA_Channel_selection DMA Channel selection * @brief DMA channel selection * @{ */ #define DMA_CHANNEL_0 ((uint32_t)0x00000000) /*!< DMA Channel 0 */ #define DMA_CHANNEL_1 ((uint32_t)0x02000000) /*!< DMA Channel 1 */ #define DMA_CHANNEL_2 ((uint32_t)0x04000000) /*!< DMA Channel 2 */ #define DMA_CHANNEL_3 ((uint32_t)0x06000000) /*!< DMA Channel 3 */ #define DMA_CHANNEL_4 ((uint32_t)0x08000000) /*!< DMA Channel 4 */ #define DMA_CHANNEL_5 ((uint32_t)0x0A000000) /*!< DMA Channel 5 */ #define DMA_CHANNEL_6 ((uint32_t)0x0C000000) /*!< DMA Channel 6 */ #define DMA_CHANNEL_7 ((uint32_t)0x0E000000) /*!< DMA Channel 7 */ /** * @} */ /** @defgroup DMA_Data_transfer_direction DMA Data transfer direction * @brief DMA data transfer direction * @{ */ #define DMA_PERIPH_TO_MEMORY ((uint32_t)0x00000000) /*!< Peripheral to memory direction */ #define DMA_MEMORY_TO_PERIPH ((uint32_t)DMA_SxCR_DIR_0) /*!< Memory to peripheral direction */ #define DMA_MEMORY_TO_MEMORY ((uint32_t)DMA_SxCR_DIR_1) /*!< Memory to memory direction */ /** * @} */ /** @defgroup DMA_Peripheral_incremented_mode DMA Peripheral incremented mode * @brief DMA peripheral incremented mode * @{ */ #define DMA_PINC_ENABLE ((uint32_t)DMA_SxCR_PINC) /*!< Peripheral increment mode enable */ #define DMA_PINC_DISABLE ((uint32_t)0x00000000) /*!< Peripheral increment mode disable */ /** * @} */ /** @defgroup DMA_Memory_incremented_mode DMA Memory incremented mode * @brief DMA memory incremented mode * @{ */ #define DMA_MINC_ENABLE ((uint32_t)DMA_SxCR_MINC) /*!< Memory increment mode enable */ #define DMA_MINC_DISABLE ((uint32_t)0x00000000) /*!< Memory increment mode disable */ /** * @} */ /** @defgroup DMA_Peripheral_data_size DMA Peripheral data size * @brief DMA peripheral data size * @{ */ #define DMA_PDATAALIGN_BYTE ((uint32_t)0x00000000) /*!< Peripheral data alignment: Byte */ #define DMA_PDATAALIGN_HALFWORD ((uint32_t)DMA_SxCR_PSIZE_0) /*!< Peripheral data alignment: HalfWord */ #define DMA_PDATAALIGN_WORD ((uint32_t)DMA_SxCR_PSIZE_1) /*!< Peripheral data alignment: Word */ /** * @} */ /** @defgroup DMA_Memory_data_size DMA Memory data size * @brief DMA memory data size * @{ */ #define DMA_MDATAALIGN_BYTE ((uint32_t)0x00000000) /*!< Memory data alignment: Byte */ #define DMA_MDATAALIGN_HALFWORD ((uint32_t)DMA_SxCR_MSIZE_0) /*!< Memory data alignment: HalfWord */ #define DMA_MDATAALIGN_WORD ((uint32_t)DMA_SxCR_MSIZE_1) /*!< Memory data alignment: Word */ /** * @} */ /** @defgroup DMA_mode DMA mode * @brief DMA mode * @{ */ #define DMA_NORMAL ((uint32_t)0x00000000) /*!< Normal mode */ #define DMA_CIRCULAR ((uint32_t)DMA_SxCR_CIRC) /*!< Circular mode */ #define DMA_PFCTRL ((uint32_t)DMA_SxCR_PFCTRL) /*!< Peripheral flow control mode */ /** * @} */ /** @defgroup DMA_Priority_level DMA Priority level * @brief DMA priority levels * @{ */ #define DMA_PRIORITY_LOW ((uint32_t)0x00000000) /*!< Priority level: Low */ #define DMA_PRIORITY_MEDIUM ((uint32_t)DMA_SxCR_PL_0) /*!< Priority level: Medium */ #define DMA_PRIORITY_HIGH ((uint32_t)DMA_SxCR_PL_1) /*!< Priority level: High */ #define DMA_PRIORITY_VERY_HIGH ((uint32_t)DMA_SxCR_PL) /*!< Priority level: Very High */ /** * @} */ /** @defgroup DMA_FIFO_direct_mode DMA FIFO direct mode * @brief DMA FIFO direct mode * @{ */ #define DMA_FIFOMODE_DISABLE ((uint32_t)0x00000000) /*!< FIFO mode disable */ #define DMA_FIFOMODE_ENABLE ((uint32_t)DMA_SxFCR_DMDIS) /*!< FIFO mode enable */ /** * @} */ /** @defgroup DMA_FIFO_threshold_level DMA FIFO threshold level * @brief DMA FIFO level * @{ */ #define DMA_FIFO_THRESHOLD_1QUARTERFULL ((uint32_t)0x00000000) /*!< FIFO threshold 1 quart full configuration */ #define DMA_FIFO_THRESHOLD_HALFFULL ((uint32_t)DMA_SxFCR_FTH_0) /*!< FIFO threshold half full configuration */ #define DMA_FIFO_THRESHOLD_3QUARTERSFULL ((uint32_t)DMA_SxFCR_FTH_1) /*!< FIFO threshold 3 quarts full configuration */ #define DMA_FIFO_THRESHOLD_FULL ((uint32_t)DMA_SxFCR_FTH) /*!< FIFO threshold full configuration */ /** * @} */ /** @defgroup DMA_Memory_burst DMA Memory burst * @brief DMA memory burst * @{ */ #define DMA_MBURST_SINGLE ((uint32_t)0x00000000) #define DMA_MBURST_INC4 ((uint32_t)DMA_SxCR_MBURST_0) #define DMA_MBURST_INC8 ((uint32_t)DMA_SxCR_MBURST_1) #define DMA_MBURST_INC16 ((uint32_t)DMA_SxCR_MBURST) /** * @} */ /** @defgroup DMA_Peripheral_burst DMA Peripheral burst * @brief DMA peripheral burst * @{ */ #define DMA_PBURST_SINGLE ((uint32_t)0x00000000) #define DMA_PBURST_INC4 ((uint32_t)DMA_SxCR_PBURST_0) #define DMA_PBURST_INC8 ((uint32_t)DMA_SxCR_PBURST_1) #define DMA_PBURST_INC16 ((uint32_t)DMA_SxCR_PBURST) /** * @} */ /** @defgroup DMA_interrupt_enable_definitions DMA interrupt enable definitions * @brief DMA interrupts definition * @{ */ #define DMA_IT_TC ((uint32_t)DMA_SxCR_TCIE) #define DMA_IT_HT ((uint32_t)DMA_SxCR_HTIE) #define DMA_IT_TE ((uint32_t)DMA_SxCR_TEIE) #define DMA_IT_DME ((uint32_t)DMA_SxCR_DMEIE) #define DMA_IT_FE ((uint32_t)0x00000080) /** * @} */ /** @defgroup DMA_flag_definitions DMA flag definitions * @brief DMA flag definitions * @{ */ #define DMA_FLAG_FEIF0_4 ((uint32_t)0x00800001) #define DMA_FLAG_DMEIF0_4 ((uint32_t)0x00800004) #define DMA_FLAG_TEIF0_4 ((uint32_t)0x00000008) #define DMA_FLAG_HTIF0_4 ((uint32_t)0x00000010) #define DMA_FLAG_TCIF0_4 ((uint32_t)0x00000020) #define DMA_FLAG_FEIF1_5 ((uint32_t)0x00000040) #define DMA_FLAG_DMEIF1_5 ((uint32_t)0x00000100) #define DMA_FLAG_TEIF1_5 ((uint32_t)0x00000200) #define DMA_FLAG_HTIF1_5 ((uint32_t)0x00000400) #define DMA_FLAG_TCIF1_5 ((uint32_t)0x00000800) #define DMA_FLAG_FEIF2_6 ((uint32_t)0x00010000) #define DMA_FLAG_DMEIF2_6 ((uint32_t)0x00040000) #define DMA_FLAG_TEIF2_6 ((uint32_t)0x00080000) #define DMA_FLAG_HTIF2_6 ((uint32_t)0x00100000) #define DMA_FLAG_TCIF2_6 ((uint32_t)0x00200000) #define DMA_FLAG_FEIF3_7 ((uint32_t)0x00400000) #define DMA_FLAG_DMEIF3_7 ((uint32_t)0x01000000) #define DMA_FLAG_TEIF3_7 ((uint32_t)0x02000000) #define DMA_FLAG_HTIF3_7 ((uint32_t)0x04000000) #define DMA_FLAG_TCIF3_7 ((uint32_t)0x08000000) /** * @} */ /** * @} */ /* Exported macro ------------------------------------------------------------*/ /** @brief Reset DMA handle state * @param __HANDLE__: specifies the DMA handle. * @retval None */ #define __HAL_DMA_RESET_HANDLE_STATE(__HANDLE__) ((__HANDLE__)->State = HAL_DMA_STATE_RESET) /** * @brief Return the current DMA Stream FIFO filled level. * @param __HANDLE__: DMA handle * @retval The FIFO filling state. * - DMA_FIFOStatus_Less1QuarterFull: when FIFO is less than 1 quarter-full * and not empty. * - DMA_FIFOStatus_1QuarterFull: if more than 1 quarter-full. * - DMA_FIFOStatus_HalfFull: if more than 1 half-full. * - DMA_FIFOStatus_3QuartersFull: if more than 3 quarters-full. * - DMA_FIFOStatus_Empty: when FIFO is empty * - DMA_FIFOStatus_Full: when FIFO is full */ #define __HAL_DMA_GET_FS(__HANDLE__) (((__HANDLE__)->Instance->FCR & (DMA_SxFCR_FS))) /** * @brief Enable the specified DMA Stream. * @param __HANDLE__: DMA handle * @retval None */ #define __HAL_DMA_ENABLE(__HANDLE__) ((__HANDLE__)->Instance->CR |= DMA_SxCR_EN) /** * @brief Disable the specified DMA Stream. * @param __HANDLE__: DMA handle * @retval None */ #define __HAL_DMA_DISABLE(__HANDLE__) ((__HANDLE__)->Instance->CR &= ~DMA_SxCR_EN) /* Interrupt & Flag management */ /** * @brief Return the current DMA Stream transfer complete flag. * @param __HANDLE__: DMA handle * @retval The specified transfer complete flag index. */ #define __HAL_DMA_GET_TC_FLAG_INDEX(__HANDLE__) \ (((uint32_t)((__HANDLE__)->Instance) == ((uint32_t)DMA1_Stream0))? DMA_FLAG_TCIF0_4 :\ ((uint32_t)((__HANDLE__)->Instance) == ((uint32_t)DMA2_Stream0))? DMA_FLAG_TCIF0_4 :\ ((uint32_t)((__HANDLE__)->Instance) == ((uint32_t)DMA1_Stream4))? DMA_FLAG_TCIF0_4 :\ ((uint32_t)((__HANDLE__)->Instance) == ((uint32_t)DMA2_Stream4))? DMA_FLAG_TCIF0_4 :\ ((uint32_t)((__HANDLE__)->Instance) == ((uint32_t)DMA1_Stream1))? DMA_FLAG_TCIF1_5 :\ ((uint32_t)((__HANDLE__)->Instance) == ((uint32_t)DMA2_Stream1))? DMA_FLAG_TCIF1_5 :\ ((uint32_t)((__HANDLE__)->Instance) == ((uint32_t)DMA1_Stream5))? DMA_FLAG_TCIF1_5 :\ ((uint32_t)((__HANDLE__)->Instance) == ((uint32_t)DMA2_Stream5))? DMA_FLAG_TCIF1_5 :\ ((uint32_t)((__HANDLE__)->Instance) == ((uint32_t)DMA1_Stream2))? DMA_FLAG_TCIF2_6 :\ ((uint32_t)((__HANDLE__)->Instance) == ((uint32_t)DMA2_Stream2))? DMA_FLAG_TCIF2_6 :\ ((uint32_t)((__HANDLE__)->Instance) == ((uint32_t)DMA1_Stream6))? DMA_FLAG_TCIF2_6 :\ ((uint32_t)((__HANDLE__)->Instance) == ((uint32_t)DMA2_Stream6))? DMA_FLAG_TCIF2_6 :\ DMA_FLAG_TCIF3_7) /** * @brief Return the current DMA Stream half transfer complete flag. * @param __HANDLE__: DMA handle * @retval The specified half transfer complete flag index. */ #define __HAL_DMA_GET_HT_FLAG_INDEX(__HANDLE__)\ (((uint32_t)((__HANDLE__)->Instance) == ((uint32_t)DMA1_Stream0))? DMA_FLAG_HTIF0_4 :\ ((uint32_t)((__HANDLE__)->Instance) == ((uint32_t)DMA2_Stream0))? DMA_FLAG_HTIF0_4 :\ ((uint32_t)((__HANDLE__)->Instance) == ((uint32_t)DMA1_Stream4))? DMA_FLAG_HTIF0_4 :\ ((uint32_t)((__HANDLE__)->Instance) == ((uint32_t)DMA2_Stream4))? DMA_FLAG_HTIF0_4 :\ ((uint32_t)((__HANDLE__)->Instance) == ((uint32_t)DMA1_Stream1))? DMA_FLAG_HTIF1_5 :\ ((uint32_t)((__HANDLE__)->Instance) == ((uint32_t)DMA2_Stream1))? DMA_FLAG_HTIF1_5 :\ ((uint32_t)((__HANDLE__)->Instance) == ((uint32_t)DMA1_Stream5))? DMA_FLAG_HTIF1_5 :\ ((uint32_t)((__HANDLE__)->Instance) == ((uint32_t)DMA2_Stream5))? DMA_FLAG_HTIF1_5 :\ ((uint32_t)((__HANDLE__)->Instance) == ((uint32_t)DMA1_Stream2))? DMA_FLAG_HTIF2_6 :\ ((uint32_t)((__HANDLE__)->Instance) == ((uint32_t)DMA2_Stream2))? DMA_FLAG_HTIF2_6 :\ ((uint32_t)((__HANDLE__)->Instance) == ((uint32_t)DMA1_Stream6))? DMA_FLAG_HTIF2_6 :\ ((uint32_t)((__HANDLE__)->Instance) == ((uint32_t)DMA2_Stream6))? DMA_FLAG_HTIF2_6 :\ DMA_FLAG_HTIF3_7) /** * @brief Return the current DMA Stream transfer error flag. * @param __HANDLE__: DMA handle * @retval The specified transfer error flag index. */ #define __HAL_DMA_GET_TE_FLAG_INDEX(__HANDLE__)\ (((uint32_t)((__HANDLE__)->Instance) == ((uint32_t)DMA1_Stream0))? DMA_FLAG_TEIF0_4 :\ ((uint32_t)((__HANDLE__)->Instance) == ((uint32_t)DMA2_Stream0))? DMA_FLAG_TEIF0_4 :\ ((uint32_t)((__HANDLE__)->Instance) == ((uint32_t)DMA1_Stream4))? DMA_FLAG_TEIF0_4 :\ ((uint32_t)((__HANDLE__)->Instance) == ((uint32_t)DMA2_Stream4))? DMA_FLAG_TEIF0_4 :\ ((uint32_t)((__HANDLE__)->Instance) == ((uint32_t)DMA1_Stream1))? DMA_FLAG_TEIF1_5 :\ ((uint32_t)((__HANDLE__)->Instance) == ((uint32_t)DMA2_Stream1))? DMA_FLAG_TEIF1_5 :\ ((uint32_t)((__HANDLE__)->Instance) == ((uint32_t)DMA1_Stream5))? DMA_FLAG_TEIF1_5 :\ ((uint32_t)((__HANDLE__)->Instance) == ((uint32_t)DMA2_Stream5))? DMA_FLAG_TEIF1_5 :\ ((uint32_t)((__HANDLE__)->Instance) == ((uint32_t)DMA1_Stream2))? DMA_FLAG_TEIF2_6 :\ ((uint32_t)((__HANDLE__)->Instance) == ((uint32_t)DMA2_Stream2))? DMA_FLAG_TEIF2_6 :\ ((uint32_t)((__HANDLE__)->Instance) == ((uint32_t)DMA1_Stream6))? DMA_FLAG_TEIF2_6 :\ ((uint32_t)((__HANDLE__)->Instance) == ((uint32_t)DMA2_Stream6))? DMA_FLAG_TEIF2_6 :\ DMA_FLAG_TEIF3_7) /** * @brief Return the current DMA Stream FIFO error flag. * @param __HANDLE__: DMA handle * @retval The specified FIFO error flag index. */ #define __HAL_DMA_GET_FE_FLAG_INDEX(__HANDLE__)\ (((uint32_t)((__HANDLE__)->Instance) == ((uint32_t)DMA1_Stream0))? DMA_FLAG_FEIF0_4 :\ ((uint32_t)((__HANDLE__)->Instance) == ((uint32_t)DMA2_Stream0))? DMA_FLAG_FEIF0_4 :\ ((uint32_t)((__HANDLE__)->Instance) == ((uint32_t)DMA1_Stream4))? DMA_FLAG_FEIF0_4 :\ ((uint32_t)((__HANDLE__)->Instance) == ((uint32_t)DMA2_Stream4))? DMA_FLAG_FEIF0_4 :\ ((uint32_t)((__HANDLE__)->Instance) == ((uint32_t)DMA1_Stream1))? DMA_FLAG_FEIF1_5 :\ ((uint32_t)((__HANDLE__)->Instance) == ((uint32_t)DMA2_Stream1))? DMA_FLAG_FEIF1_5 :\ ((uint32_t)((__HANDLE__)->Instance) == ((uint32_t)DMA1_Stream5))? DMA_FLAG_FEIF1_5 :\ ((uint32_t)((__HANDLE__)->Instance) == ((uint32_t)DMA2_Stream5))? DMA_FLAG_FEIF1_5 :\ ((uint32_t)((__HANDLE__)->Instance) == ((uint32_t)DMA1_Stream2))? DMA_FLAG_FEIF2_6 :\ ((uint32_t)((__HANDLE__)->Instance) == ((uint32_t)DMA2_Stream2))? DMA_FLAG_FEIF2_6 :\ ((uint32_t)((__HANDLE__)->Instance) == ((uint32_t)DMA1_Stream6))? DMA_FLAG_FEIF2_6 :\ ((uint32_t)((__HANDLE__)->Instance) == ((uint32_t)DMA2_Stream6))? DMA_FLAG_FEIF2_6 :\ DMA_FLAG_FEIF3_7) /** * @brief Return the current DMA Stream direct mode error flag. * @param __HANDLE__: DMA handle * @retval The specified direct mode error flag index. */ #define __HAL_DMA_GET_DME_FLAG_INDEX(__HANDLE__)\ (((uint32_t)((__HANDLE__)->Instance) == ((uint32_t)DMA1_Stream0))? DMA_FLAG_DMEIF0_4 :\ ((uint32_t)((__HANDLE__)->Instance) == ((uint32_t)DMA2_Stream0))? DMA_FLAG_DMEIF0_4 :\ ((uint32_t)((__HANDLE__)->Instance) == ((uint32_t)DMA1_Stream4))? DMA_FLAG_DMEIF0_4 :\ ((uint32_t)((__HANDLE__)->Instance) == ((uint32_t)DMA2_Stream4))? DMA_FLAG_DMEIF0_4 :\ ((uint32_t)((__HANDLE__)->Instance) == ((uint32_t)DMA1_Stream1))? DMA_FLAG_DMEIF1_5 :\ ((uint32_t)((__HANDLE__)->Instance) == ((uint32_t)DMA2_Stream1))? DMA_FLAG_DMEIF1_5 :\ ((uint32_t)((__HANDLE__)->Instance) == ((uint32_t)DMA1_Stream5))? DMA_FLAG_DMEIF1_5 :\ ((uint32_t)((__HANDLE__)->Instance) == ((uint32_t)DMA2_Stream5))? DMA_FLAG_DMEIF1_5 :\ ((uint32_t)((__HANDLE__)->Instance) == ((uint32_t)DMA1_Stream2))? DMA_FLAG_DMEIF2_6 :\ ((uint32_t)((__HANDLE__)->Instance) == ((uint32_t)DMA2_Stream2))? DMA_FLAG_DMEIF2_6 :\ ((uint32_t)((__HANDLE__)->Instance) == ((uint32_t)DMA1_Stream6))? DMA_FLAG_DMEIF2_6 :\ ((uint32_t)((__HANDLE__)->Instance) == ((uint32_t)DMA2_Stream6))? DMA_FLAG_DMEIF2_6 :\ DMA_FLAG_DMEIF3_7) /** * @brief Get the DMA Stream pending flags. * @param __HANDLE__: DMA handle * @param __FLAG__: Get the specified flag. * This parameter can be any combination of the following values: * @arg DMA_FLAG_TCIFx: Transfer complete flag. * @arg DMA_FLAG_HTIFx: Half transfer complete flag. * @arg DMA_FLAG_TEIFx: Transfer error flag. * @arg DMA_FLAG_DMEIFx: Direct mode error flag. * @arg DMA_FLAG_FEIFx: FIFO error flag. * Where x can be 0_4, 1_5, 2_6 or 3_7 to select the DMA Stream flag. * @retval The state of FLAG (SET or RESET). */ #define __HAL_DMA_GET_FLAG(__HANDLE__, __FLAG__)\ (((uint32_t)((__HANDLE__)->Instance) > (uint32_t)DMA2_Stream3)? (DMA2->HISR & (__FLAG__)) :\ ((uint32_t)((__HANDLE__)->Instance) > (uint32_t)DMA1_Stream7)? (DMA2->LISR & (__FLAG__)) :\ ((uint32_t)((__HANDLE__)->Instance) > (uint32_t)DMA1_Stream3)? (DMA1->HISR & (__FLAG__)) : (DMA1->LISR & (__FLAG__))) /** * @brief Clear the DMA Stream pending flags. * @param __HANDLE__: DMA handle * @param __FLAG__: specifies the flag to clear. * This parameter can be any combination of the following values: * @arg DMA_FLAG_TCIFx: Transfer complete flag. * @arg DMA_FLAG_HTIFx: Half transfer complete flag. * @arg DMA_FLAG_TEIFx: Transfer error flag. * @arg DMA_FLAG_DMEIFx: Direct mode error flag. * @arg DMA_FLAG_FEIFx: FIFO error flag. * Where x can be 0_4, 1_5, 2_6 or 3_7 to select the DMA Stream flag. * @retval None */ #define __HAL_DMA_CLEAR_FLAG(__HANDLE__, __FLAG__) \ (((uint32_t)((__HANDLE__)->Instance) > (uint32_t)DMA2_Stream3)? (DMA2->HIFCR = (__FLAG__)) :\ ((uint32_t)((__HANDLE__)->Instance) > (uint32_t)DMA1_Stream7)? (DMA2->LIFCR = (__FLAG__)) :\ ((uint32_t)((__HANDLE__)->Instance) > (uint32_t)DMA1_Stream3)? (DMA1->HIFCR = (__FLAG__)) : (DMA1->LIFCR = (__FLAG__))) /** * @brief Enable the specified DMA Stream interrupts. * @param __HANDLE__: DMA handle * @param __INTERRUPT__: specifies the DMA interrupt sources to be enabled or disabled. * This parameter can be any combination of the following values: * @arg DMA_IT_TC: Transfer complete interrupt mask. * @arg DMA_IT_HT: Half transfer complete interrupt mask. * @arg DMA_IT_TE: Transfer error interrupt mask. * @arg DMA_IT_FE: FIFO error interrupt mask. * @arg DMA_IT_DME: Direct mode error interrupt. * @retval None */ #define __HAL_DMA_ENABLE_IT(__HANDLE__, __INTERRUPT__) (((__INTERRUPT__) != DMA_IT_FE)? \ ((__HANDLE__)->Instance->CR |= (__INTERRUPT__)) : ((__HANDLE__)->Instance->FCR |= (__INTERRUPT__))) /** * @brief Disable the specified DMA Stream interrupts. * @param __HANDLE__: DMA handle * @param __INTERRUPT__: specifies the DMA interrupt sources to be enabled or disabled. * This parameter can be any combination of the following values: * @arg DMA_IT_TC: Transfer complete interrupt mask. * @arg DMA_IT_HT: Half transfer complete interrupt mask. * @arg DMA_IT_TE: Transfer error interrupt mask. * @arg DMA_IT_FE: FIFO error interrupt mask. * @arg DMA_IT_DME: Direct mode error interrupt. * @retval None */ #define __HAL_DMA_DISABLE_IT(__HANDLE__, __INTERRUPT__) (((__INTERRUPT__) != DMA_IT_FE)? \ ((__HANDLE__)->Instance->CR &= ~(__INTERRUPT__)) : ((__HANDLE__)->Instance->FCR &= ~(__INTERRUPT__))) /** * @brief Check whether the specified DMA Stream interrupt is enabled or disabled. * @param __HANDLE__: DMA handle * @param __INTERRUPT__: specifies the DMA interrupt source to check. * This parameter can be one of the following values: * @arg DMA_IT_TC: Transfer complete interrupt mask. * @arg DMA_IT_HT: Half transfer complete interrupt mask. * @arg DMA_IT_TE: Transfer error interrupt mask. * @arg DMA_IT_FE: FIFO error interrupt mask. * @arg DMA_IT_DME: Direct mode error interrupt. * @retval The state of DMA_IT. */ #define __HAL_DMA_GET_IT_SOURCE(__HANDLE__, __INTERRUPT__) (((__INTERRUPT__) != DMA_IT_FE)? \ ((__HANDLE__)->Instance->CR & (__INTERRUPT__)) : \ ((__HANDLE__)->Instance->FCR & (__INTERRUPT__))) /** * @brief Writes the number of data units to be transferred on the DMA Stream. * @param __HANDLE__: DMA handle * @param __COUNTER__: Number of data units to be transferred (from 0 to 65535) * Number of data items depends only on the Peripheral data format. * * @note If Peripheral data format is Bytes: number of data units is equal * to total number of bytes to be transferred. * * @note If Peripheral data format is Half-Word: number of data units is * equal to total number of bytes to be transferred / 2. * * @note If Peripheral data format is Word: number of data units is equal * to total number of bytes to be transferred / 4. * * @retval The number of remaining data units in the current DMAy Streamx transfer. */ #define __HAL_DMA_SET_COUNTER(__HANDLE__, __COUNTER__) ((__HANDLE__)->Instance->NDTR = (uint16_t)(__COUNTER__)) /** * @brief Returns the number of remaining data units in the current DMAy Streamx transfer. * @param __HANDLE__: DMA handle * * @retval The number of remaining data units in the current DMA Stream transfer. */ #define __HAL_DMA_GET_COUNTER(__HANDLE__) ((__HANDLE__)->Instance->NDTR) /* Include DMA HAL Extension module */ #include "stm32f4xx_hal_dma_ex.h" /* Exported functions --------------------------------------------------------*/ /** @defgroup DMA_Exported_Functions DMA Exported Functions * @brief DMA Exported functions * @{ */ /** @defgroup DMA_Exported_Functions_Group1 Initialization and de-initialization functions * @brief Initialization and de-initialization functions * @{ */ HAL_StatusTypeDef HAL_DMA_Init(DMA_HandleTypeDef *hdma); HAL_StatusTypeDef HAL_DMA_DeInit(DMA_HandleTypeDef *hdma); /** * @} */ /** @defgroup DMA_Exported_Functions_Group2 I/O operation functions * @brief I/O operation functions * @{ */ HAL_StatusTypeDef HAL_DMA_Start (DMA_HandleTypeDef *hdma, uint32_t SrcAddress, uint32_t DstAddress, uint32_t DataLength); HAL_StatusTypeDef HAL_DMA_Start_IT(DMA_HandleTypeDef *hdma, uint32_t SrcAddress, uint32_t DstAddress, uint32_t DataLength); HAL_StatusTypeDef HAL_DMA_Abort(DMA_HandleTypeDef *hdma); HAL_StatusTypeDef HAL_DMA_PollForTransfer(DMA_HandleTypeDef *hdma, uint32_t CompleteLevel, uint32_t Timeout); void HAL_DMA_IRQHandler(DMA_HandleTypeDef *hdma); /** * @} */ /** @defgroup DMA_Exported_Functions_Group3 Peripheral State functions * @brief Peripheral State functions * @{ */ HAL_DMA_StateTypeDef HAL_DMA_GetState(DMA_HandleTypeDef *hdma); uint32_t HAL_DMA_GetError(DMA_HandleTypeDef *hdma); /** * @} */ /** * @} */ /* Private Constants -------------------------------------------------------------*/ /** @defgroup DMA_Private_Constants DMA Private Constants * @brief DMA private defines and constants * @{ */ /** * @} */ /* Private macros ------------------------------------------------------------*/ /** @defgroup DMA_Private_Macros DMA Private Macros * @brief DMA private macros * @{ */ #define IS_DMA_CHANNEL(CHANNEL) (((CHANNEL) == DMA_CHANNEL_0) || \ ((CHANNEL) == DMA_CHANNEL_1) || \ ((CHANNEL) == DMA_CHANNEL_2) || \ ((CHANNEL) == DMA_CHANNEL_3) || \ ((CHANNEL) == DMA_CHANNEL_4) || \ ((CHANNEL) == DMA_CHANNEL_5) || \ ((CHANNEL) == DMA_CHANNEL_6) || \ ((CHANNEL) == DMA_CHANNEL_7)) #define IS_DMA_DIRECTION(DIRECTION) (((DIRECTION) == DMA_PERIPH_TO_MEMORY ) || \ ((DIRECTION) == DMA_MEMORY_TO_PERIPH) || \ ((DIRECTION) == DMA_MEMORY_TO_MEMORY)) #define IS_DMA_BUFFER_SIZE(SIZE) (((SIZE) >= 0x1) && ((SIZE) < 0x10000)) #define IS_DMA_PERIPHERAL_INC_STATE(STATE) (((STATE) == DMA_PINC_ENABLE) || \ ((STATE) == DMA_PINC_DISABLE)) #define IS_DMA_MEMORY_INC_STATE(STATE) (((STATE) == DMA_MINC_ENABLE) || \ ((STATE) == DMA_MINC_DISABLE)) #define IS_DMA_PERIPHERAL_DATA_SIZE(SIZE) (((SIZE) == DMA_PDATAALIGN_BYTE) || \ ((SIZE) == DMA_PDATAALIGN_HALFWORD) || \ ((SIZE) == DMA_PDATAALIGN_WORD)) #define IS_DMA_MEMORY_DATA_SIZE(SIZE) (((SIZE) == DMA_MDATAALIGN_BYTE) || \ ((SIZE) == DMA_MDATAALIGN_HALFWORD) || \ ((SIZE) == DMA_MDATAALIGN_WORD )) #define IS_DMA_MODE(MODE) (((MODE) == DMA_NORMAL ) || \ ((MODE) == DMA_CIRCULAR) || \ ((MODE) == DMA_PFCTRL)) #define IS_DMA_PRIORITY(PRIORITY) (((PRIORITY) == DMA_PRIORITY_LOW ) || \ ((PRIORITY) == DMA_PRIORITY_MEDIUM) || \ ((PRIORITY) == DMA_PRIORITY_HIGH) || \ ((PRIORITY) == DMA_PRIORITY_VERY_HIGH)) #define IS_DMA_FIFO_MODE_STATE(STATE) (((STATE) == DMA_FIFOMODE_DISABLE ) || \ ((STATE) == DMA_FIFOMODE_ENABLE)) #define IS_DMA_FIFO_THRESHOLD(THRESHOLD) (((THRESHOLD) == DMA_FIFO_THRESHOLD_1QUARTERFULL ) || \ ((THRESHOLD) == DMA_FIFO_THRESHOLD_HALFFULL) || \ ((THRESHOLD) == DMA_FIFO_THRESHOLD_3QUARTERSFULL) || \ ((THRESHOLD) == DMA_FIFO_THRESHOLD_FULL)) #define IS_DMA_MEMORY_BURST(BURST) (((BURST) == DMA_MBURST_SINGLE) || \ ((BURST) == DMA_MBURST_INC4) || \ ((BURST) == DMA_MBURST_INC8) || \ ((BURST) == DMA_MBURST_INC16)) #define IS_DMA_PERIPHERAL_BURST(BURST) (((BURST) == DMA_PBURST_SINGLE) || \ ((BURST) == DMA_PBURST_INC4) || \ ((BURST) == DMA_PBURST_INC8) || \ ((BURST) == DMA_PBURST_INC16)) /** * @} */ /* Private functions ---------------------------------------------------------*/ /** @defgroup DMA_Private_Functions DMA Private Functions * @brief DMA private functions * @{ */ /** * @} */ /** * @} */ /** * @} */ #ifdef __cplusplus } #endif #endif /* __STM32F4xx_HAL_DMA_H */ /************************ (C) COPYRIGHT STMicroelectronics *****END OF FILE****/ ================================================ FILE: Zelig/mbed/TARGET_NUCLEO_F411RE/stm32f4xx_hal_dma2d.h ================================================ /** ****************************************************************************** * @file stm32f4xx_hal_dma2d.h * @author MCD Application Team * @version V1.4.1 * @date 09-October-2015 * @brief Header file of DMA2D HAL module. ****************************************************************************** * @attention * *

© COPYRIGHT(c) 2015 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. * ****************************************************************************** */ /* Define to prevent recursive inclusion -------------------------------------*/ #ifndef __STM32F4xx_HAL_DMA2D_H #define __STM32F4xx_HAL_DMA2D_H #ifdef __cplusplus extern "C" { #endif #if defined(STM32F427xx) || defined(STM32F437xx) || defined(STM32F429xx) || defined(STM32F439xx) ||\ defined(STM32F469xx) || defined(STM32F479xx) /* Includes ------------------------------------------------------------------*/ #include "stm32f4xx_hal_def.h" /** @addtogroup STM32F4xx_HAL_Driver * @{ */ /** @defgroup DMA2D DMA2D * @brief DMA2D HAL module driver * @{ */ /* Exported types ------------------------------------------------------------*/ /** @defgroup DMA2D_Exported_Types DMA2D Exported Types * @{ */ #define MAX_DMA2D_LAYER 2 /** * @brief DMA2D color Structure definition */ typedef struct { uint32_t Blue; /*!< Configures the blue value. This parameter must be a number between Min_Data = 0x00 and Max_Data = 0xFF. */ uint32_t Green; /*!< Configures the green value. This parameter must be a number between Min_Data = 0x00 and Max_Data = 0xFF. */ uint32_t Red; /*!< Configures the red value. This parameter must be a number between Min_Data = 0x00 and Max_Data = 0xFF. */ } DMA2D_ColorTypeDef; /** * @brief DMA2D CLUT Structure definition */ typedef struct { uint32_t *pCLUT; /*!< Configures the DMA2D CLUT memory address.*/ uint32_t CLUTColorMode; /*!< configures the DMA2D CLUT color mode. This parameter can be one value of @ref DMA2D_CLUT_CM */ uint32_t Size; /*!< configures the DMA2D CLUT size. This parameter must be a number between Min_Data = 0x00 and Max_Data = 0xFF.*/ } DMA2D_CLUTCfgTypeDef; /** * @brief DMA2D Init structure definition */ typedef struct { uint32_t Mode; /*!< configures the DMA2D transfer mode. This parameter can be one value of @ref DMA2D_Mode */ uint32_t ColorMode; /*!< configures the color format of the output image. This parameter can be one value of @ref DMA2D_Color_Mode */ uint32_t OutputOffset; /*!< Specifies the Offset value. This parameter must be a number between Min_Data = 0x0000 and Max_Data = 0x3FFF. */ } DMA2D_InitTypeDef; /** * @brief DMA2D Layer structure definition */ typedef struct { uint32_t InputOffset; /*!< configures the DMA2D foreground offset. This parameter must be a number between Min_Data = 0x0000 and Max_Data = 0x3FFF. */ uint32_t InputColorMode; /*!< configures the DMA2D foreground color mode . This parameter can be one value of @ref DMA2D_Input_Color_Mode */ uint32_t AlphaMode; /*!< configures the DMA2D foreground alpha mode. This parameter can be one value of @ref DMA2D_ALPHA_MODE */ uint32_t InputAlpha; /*!< Specifies the DMA2D foreground alpha value and color value in case of A8 or A4 color mode. This parameter must be a number between Min_Data = 0x00000000 and Max_Data = 0xFFFFFFFF in case of A8 or A4 color mode (ARGB). Otherwise, This parameter must be a number between Min_Data = 0x00 and Max_Data = 0xFF.*/ } DMA2D_LayerCfgTypeDef; /** * @brief HAL DMA2D State structures definition */ typedef enum { HAL_DMA2D_STATE_RESET = 0x00, /*!< DMA2D not yet initialized or disabled */ HAL_DMA2D_STATE_READY = 0x01, /*!< Peripheral Initialized and ready for use */ HAL_DMA2D_STATE_BUSY = 0x02, /*!< an internal process is ongoing */ HAL_DMA2D_STATE_TIMEOUT = 0x03, /*!< Timeout state */ HAL_DMA2D_STATE_ERROR = 0x04, /*!< DMA2D state error */ HAL_DMA2D_STATE_SUSPEND = 0x05 /*!< DMA2D process is suspended */ }HAL_DMA2D_StateTypeDef; /** * @brief DMA2D handle Structure definition */ typedef struct __DMA2D_HandleTypeDef { DMA2D_TypeDef *Instance; /*!< DMA2D Register base address */ DMA2D_InitTypeDef Init; /*!< DMA2D communication parameters */ void (* XferCpltCallback)(struct __DMA2D_HandleTypeDef * hdma2d); /*!< DMA2D transfer complete callback */ void (* XferErrorCallback)(struct __DMA2D_HandleTypeDef * hdma2d); /*!< DMA2D transfer error callback */ DMA2D_LayerCfgTypeDef LayerCfg[MAX_DMA2D_LAYER]; /*!< DMA2D Layers parameters */ HAL_LockTypeDef Lock; /*!< DMA2D Lock */ __IO HAL_DMA2D_StateTypeDef State; /*!< DMA2D transfer state */ __IO uint32_t ErrorCode; /*!< DMA2D Error code */ } DMA2D_HandleTypeDef; /** * @} */ /* Exported constants --------------------------------------------------------*/ /** @defgroup DMA2D_Exported_Constants DMA2D Exported Constants * @{ */ /** @defgroup DMA2D_Error_Code DMA2D Error Code * @{ */ #define HAL_DMA2D_ERROR_NONE ((uint32_t)0x00000000) /*!< No error */ #define HAL_DMA2D_ERROR_TE ((uint32_t)0x00000001) /*!< Transfer error */ #define HAL_DMA2D_ERROR_CE ((uint32_t)0x00000002) /*!< Configuration error */ #define HAL_DMA2D_ERROR_TIMEOUT ((uint32_t)0x00000020) /*!< Timeout error */ /** * @} */ /** @defgroup DMA2D_Mode DMA2D Mode * @{ */ #define DMA2D_M2M ((uint32_t)0x00000000) /*!< DMA2D memory to memory transfer mode */ #define DMA2D_M2M_PFC ((uint32_t)0x00010000) /*!< DMA2D memory to memory with pixel format conversion transfer mode */ #define DMA2D_M2M_BLEND ((uint32_t)0x00020000) /*!< DMA2D memory to memory with blending transfer mode */ #define DMA2D_R2M ((uint32_t)0x00030000) /*!< DMA2D register to memory transfer mode */ /** * @} */ /** @defgroup DMA2D_Color_Mode DMA2D Color Mode * @{ */ #define DMA2D_ARGB8888 ((uint32_t)0x00000000) /*!< ARGB8888 DMA2D color mode */ #define DMA2D_RGB888 ((uint32_t)0x00000001) /*!< RGB888 DMA2D color mode */ #define DMA2D_RGB565 ((uint32_t)0x00000002) /*!< RGB565 DMA2D color mode */ #define DMA2D_ARGB1555 ((uint32_t)0x00000003) /*!< ARGB1555 DMA2D color mode */ #define DMA2D_ARGB4444 ((uint32_t)0x00000004) /*!< ARGB4444 DMA2D color mode */ /** * @} */ /** @defgroup DMA2D_COLOR_VALUE DMA2D COLOR VALUE * @{ */ #define COLOR_VALUE ((uint32_t)0x000000FF) /*!< color value mask */ /** * @} */ /** @defgroup DMA2D_SIZE DMA2D SIZE * @{ */ #define DMA2D_PIXEL (DMA2D_NLR_PL >> 16) /*!< DMA2D pixel per line */ #define DMA2D_LINE DMA2D_NLR_NL /*!< DMA2D number of line */ /** * @} */ /** @defgroup DMA2D_Offset DMA2D Offset * @{ */ #define DMA2D_OFFSET DMA2D_FGOR_LO /*!< Line Offset */ /** * @} */ /** @defgroup DMA2D_Input_Color_Mode DMA2D Input Color Mode * @{ */ #define CM_ARGB8888 ((uint32_t)0x00000000) /*!< ARGB8888 color mode */ #define CM_RGB888 ((uint32_t)0x00000001) /*!< RGB888 color mode */ #define CM_RGB565 ((uint32_t)0x00000002) /*!< RGB565 color mode */ #define CM_ARGB1555 ((uint32_t)0x00000003) /*!< ARGB1555 color mode */ #define CM_ARGB4444 ((uint32_t)0x00000004) /*!< ARGB4444 color mode */ #define CM_L8 ((uint32_t)0x00000005) /*!< L8 color mode */ #define CM_AL44 ((uint32_t)0x00000006) /*!< AL44 color mode */ #define CM_AL88 ((uint32_t)0x00000007) /*!< AL88 color mode */ #define CM_L4 ((uint32_t)0x00000008) /*!< L4 color mode */ #define CM_A8 ((uint32_t)0x00000009) /*!< A8 color mode */ #define CM_A4 ((uint32_t)0x0000000A) /*!< A4 color mode */ /** * @} */ /** @defgroup DMA2D_ALPHA_MODE DMA2D ALPHA MODE * @{ */ #define DMA2D_NO_MODIF_ALPHA ((uint32_t)0x00000000) /*!< No modification of the alpha channel value */ #define DMA2D_REPLACE_ALPHA ((uint32_t)0x00000001) /*!< Replace original alpha channel value by programmed alpha value */ #define DMA2D_COMBINE_ALPHA ((uint32_t)0x00000002) /*!< Replace original alpha channel value by programmed alpha value with original alpha channel value */ /** * @} */ /** @defgroup DMA2D_CLUT_CM DMA2D CLUT CM * @{ */ #define DMA2D_CCM_ARGB8888 ((uint32_t)0x00000000) /*!< ARGB8888 DMA2D C-LUT color mode */ #define DMA2D_CCM_RGB888 ((uint32_t)0x00000001) /*!< RGB888 DMA2D C-LUT color mode */ /** * @} */ /** @defgroup DMA2D_Size_Clut DMA2D Size Clut * @{ */ #define DMA2D_CLUT_SIZE (DMA2D_FGPFCCR_CS >> 8) /*!< DMA2D C-LUT size */ /** * @} */ /** @defgroup DMA2D_DeadTime DMA2D DeadTime * @{ */ #define LINE_WATERMARK DMA2D_LWR_LW /** * @} */ /** @defgroup DMA2D_Interrupts DMA2D Interrupts * @{ */ #define DMA2D_IT_CE DMA2D_CR_CEIE /*!< Configuration Error Interrupt */ #define DMA2D_IT_CTC DMA2D_CR_CTCIE /*!< C-LUT Transfer Complete Interrupt */ #define DMA2D_IT_CAE DMA2D_CR_CAEIE /*!< C-LUT Access Error Interrupt */ #define DMA2D_IT_TW DMA2D_CR_TWIE /*!< Transfer Watermark Interrupt */ #define DMA2D_IT_TC DMA2D_CR_TCIE /*!< Transfer Complete Interrupt */ #define DMA2D_IT_TE DMA2D_CR_TEIE /*!< Transfer Error Interrupt */ /** * @} */ /** @defgroup DMA2D_Flag DMA2D Flag * @{ */ #define DMA2D_FLAG_CE DMA2D_ISR_CEIF /*!< Configuration Error Interrupt Flag */ #define DMA2D_FLAG_CTC DMA2D_ISR_CTCIF /*!< C-LUT Transfer Complete Interrupt Flag */ #define DMA2D_FLAG_CAE DMA2D_ISR_CAEIF /*!< C-LUT Access Error Interrupt Flag */ #define DMA2D_FLAG_TW DMA2D_ISR_TWIF /*!< Transfer Watermark Interrupt Flag */ #define DMA2D_FLAG_TC DMA2D_ISR_TCIF /*!< Transfer Complete Interrupt Flag */ #define DMA2D_FLAG_TE DMA2D_ISR_TEIF /*!< Transfer Error Interrupt Flag */ /** * @} */ /** * @} */ /* Exported macro ------------------------------------------------------------*/ /** @defgroup DMA2D_Exported_Macros DMA2D Exported Macros * @{ */ /** @brief Reset DMA2D handle state * @param __HANDLE__: specifies the DMA2D handle. * @retval None */ #define __HAL_DMA2D_RESET_HANDLE_STATE(__HANDLE__) ((__HANDLE__)->State = HAL_DMA2D_STATE_RESET) /** * @brief Enable the DMA2D. * @param __HANDLE__: DMA2D handle * @retval None. */ #define __HAL_DMA2D_ENABLE(__HANDLE__) ((__HANDLE__)->Instance->CR |= DMA2D_CR_START) /** * @brief Disable the DMA2D. * @param __HANDLE__: DMA2D handle * @retval None. */ #define __HAL_DMA2D_DISABLE(__HANDLE__) ((__HANDLE__)->Instance->CR &= ~DMA2D_CR_START) /* Interrupt & Flag management */ /** * @brief Get the DMA2D pending flags. * @param __HANDLE__: DMA2D handle * @param __FLAG__: Get the specified flag. * This parameter can be any combination of the following values: * @arg DMA2D_FLAG_CE: Configuration error flag * @arg DMA2D_FLAG_CTC: C-LUT transfer complete flag * @arg DMA2D_FLAG_CAE: C-LUT access error flag * @arg DMA2D_FLAG_TW: Transfer Watermark flag * @arg DMA2D_FLAG_TC: Transfer complete flag * @arg DMA2D_FLAG_TE: Transfer error flag * @retval The state of FLAG. */ #define __HAL_DMA2D_GET_FLAG(__HANDLE__, __FLAG__) ((__HANDLE__)->Instance->ISR & (__FLAG__)) /** * @brief Clears the DMA2D pending flags. * @param __HANDLE__: DMA2D handle * @param __FLAG__: specifies the flag to clear. * This parameter can be any combination of the following values: * @arg DMA2D_FLAG_CE: Configuration error flag * @arg DMA2D_FLAG_CTC: C-LUT transfer complete flag * @arg DMA2D_FLAG_CAE: C-LUT access error flag * @arg DMA2D_FLAG_TW: Transfer Watermark flag * @arg DMA2D_FLAG_TC: Transfer complete flag * @arg DMA2D_FLAG_TE: Transfer error flag * @retval None */ #define __HAL_DMA2D_CLEAR_FLAG(__HANDLE__, __FLAG__) ((__HANDLE__)->Instance->IFCR = (__FLAG__)) /** * @brief Enables the specified DMA2D interrupts. * @param __HANDLE__: DMA2D handle * @param __INTERRUPT__: specifies the DMA2D interrupt sources to be enabled. * This parameter can be any combination of the following values: * @arg DMA2D_IT_CE: Configuration error interrupt mask * @arg DMA2D_IT_CTC: C-LUT transfer complete interrupt mask * @arg DMA2D_IT_CAE: C-LUT access error interrupt mask * @arg DMA2D_IT_TW: Transfer Watermark interrupt mask * @arg DMA2D_IT_TC: Transfer complete interrupt mask * @arg DMA2D_IT_TE: Transfer error interrupt mask * @retval None */ #define __HAL_DMA2D_ENABLE_IT(__HANDLE__, __INTERRUPT__) ((__HANDLE__)->Instance->CR |= (__INTERRUPT__)) /** * @brief Disables the specified DMA2D interrupts. * @param __HANDLE__: DMA2D handle * @param __INTERRUPT__: specifies the DMA2D interrupt sources to be disabled. * This parameter can be any combination of the following values: * @arg DMA2D_IT_CE: Configuration error interrupt mask * @arg DMA2D_IT_CTC: C-LUT transfer complete interrupt mask * @arg DMA2D_IT_CAE: C-LUT access error interrupt mask * @arg DMA2D_IT_TW: Transfer Watermark interrupt mask * @arg DMA2D_IT_TC: Transfer complete interrupt mask * @arg DMA2D_IT_TE: Transfer error interrupt mask * @retval None */ #define __HAL_DMA2D_DISABLE_IT(__HANDLE__, __INTERRUPT__) ((__HANDLE__)->Instance->CR &= ~(__INTERRUPT__)) /** * @brief Checks whether the specified DMA2D interrupt has occurred or not. * @param __HANDLE__: DMA2D handle * @param __INTERRUPT__: specifies the DMA2D interrupt source to check. * This parameter can be one of the following values: * @arg DMA2D_IT_CE: Configuration error interrupt mask * @arg DMA2D_IT_CTC: C-LUT transfer complete interrupt mask * @arg DMA2D_IT_CAE: C-LUT access error interrupt mask * @arg DMA2D_IT_TW: Transfer Watermark interrupt mask * @arg DMA2D_IT_TC: Transfer complete interrupt mask * @arg DMA2D_IT_TE: Transfer error interrupt mask * @retval The state of INTERRUPT. */ #define __HAL_DMA2D_GET_IT_SOURCE(__HANDLE__, __INTERRUPT__) ((__HANDLE__)->Instance->CR & (__INTERRUPT__)) /** * @} */ /* Exported functions --------------------------------------------------------*/ /** @defgroup DMA2D_Exported_Functions DMA2D Exported Functions * @{ */ /* Initialization and de-initialization functions *******************************/ HAL_StatusTypeDef HAL_DMA2D_Init(DMA2D_HandleTypeDef *hdma2d); HAL_StatusTypeDef HAL_DMA2D_DeInit (DMA2D_HandleTypeDef *hdma2d); void HAL_DMA2D_MspInit(DMA2D_HandleTypeDef* hdma2d); void HAL_DMA2D_MspDeInit(DMA2D_HandleTypeDef* hdma2d); /* IO operation functions *******************************************************/ HAL_StatusTypeDef HAL_DMA2D_Start(DMA2D_HandleTypeDef *hdma2d, uint32_t pdata, uint32_t DstAddress, uint32_t Width, uint32_t Height); HAL_StatusTypeDef HAL_DMA2D_BlendingStart(DMA2D_HandleTypeDef *hdma2d, uint32_t SrcAddress1, uint32_t SrcAddress2, uint32_t DstAddress, uint32_t Width, uint32_t Height); HAL_StatusTypeDef HAL_DMA2D_Start_IT(DMA2D_HandleTypeDef *hdma2d, uint32_t pdata, uint32_t DstAddress, uint32_t Width, uint32_t Height); HAL_StatusTypeDef HAL_DMA2D_BlendingStart_IT(DMA2D_HandleTypeDef *hdma2d, uint32_t SrcAddress1, uint32_t SrcAddress2, uint32_t DstAddress, uint32_t Width, uint32_t Height); HAL_StatusTypeDef HAL_DMA2D_Suspend(DMA2D_HandleTypeDef *hdma2d); HAL_StatusTypeDef HAL_DMA2D_Resume(DMA2D_HandleTypeDef *hdma2d); HAL_StatusTypeDef HAL_DMA2D_Abort(DMA2D_HandleTypeDef *hdma2d); HAL_StatusTypeDef HAL_DMA2D_PollForTransfer(DMA2D_HandleTypeDef *hdma2d, uint32_t Timeout); void HAL_DMA2D_IRQHandler(DMA2D_HandleTypeDef *hdma2d); /* Peripheral Control functions *************************************************/ HAL_StatusTypeDef HAL_DMA2D_ConfigLayer(DMA2D_HandleTypeDef *hdma2d, uint32_t LayerIdx); HAL_StatusTypeDef HAL_DMA2D_ConfigCLUT(DMA2D_HandleTypeDef *hdma2d, DMA2D_CLUTCfgTypeDef CLUTCfg, uint32_t LayerIdx); HAL_StatusTypeDef HAL_DMA2D_EnableCLUT(DMA2D_HandleTypeDef *hdma2d, uint32_t LayerIdx); HAL_StatusTypeDef HAL_DMA2D_DisableCLUT(DMA2D_HandleTypeDef *hdma2d, uint32_t LayerIdx); HAL_StatusTypeDef HAL_DMA2D_ProgramLineEvent(DMA2D_HandleTypeDef *hdma2d, uint32_t Line); /* Peripheral State functions ***************************************************/ HAL_DMA2D_StateTypeDef HAL_DMA2D_GetState(DMA2D_HandleTypeDef *hdma2d); uint32_t HAL_DMA2D_GetError(DMA2D_HandleTypeDef *hdma2d); /** * @} */ /* Private types -------------------------------------------------------------*/ /** @defgroup DMA2D_Private_Types DMA2D Private Types * @{ */ /** * @} */ /* Private defines -------------------------------------------------------------*/ /** @defgroup DMA2D_Private_Defines DMA2D Private Defines * @{ */ /** * @} */ /* Private variables ---------------------------------------------------------*/ /** @defgroup DMA2D_Private_Variables DMA2D Private Variables * @{ */ /** * @} */ /* Private constants ---------------------------------------------------------*/ /** @defgroup DMA2D_Private_Constants DMA2D Private Constants * @{ */ /** * @} */ /* Private macros ------------------------------------------------------------*/ /** @defgroup DMA2D_Private_Macros DMA2D Private Macros * @{ */ #define IS_DMA2D_LAYER(LAYER) ((LAYER) <= MAX_DMA2D_LAYER) #define IS_DMA2D_MODE(MODE) (((MODE) == DMA2D_M2M) || ((MODE) == DMA2D_M2M_PFC) || \ ((MODE) == DMA2D_M2M_BLEND) || ((MODE) == DMA2D_R2M)) #define IS_DMA2D_CMODE(MODE_ARGB) (((MODE_ARGB) == DMA2D_ARGB8888) || ((MODE_ARGB) == DMA2D_RGB888) || \ ((MODE_ARGB) == DMA2D_RGB565) || ((MODE_ARGB) == DMA2D_ARGB1555) || \ ((MODE_ARGB) == DMA2D_ARGB4444)) #define IS_DMA2D_COLOR(COLOR) ((COLOR) <= COLOR_VALUE) #define IS_DMA2D_LINE(LINE) ((LINE) <= DMA2D_LINE) #define IS_DMA2D_PIXEL(PIXEL) ((PIXEL) <= DMA2D_PIXEL) #define IS_DMA2D_OFFSET(OOFFSET) ((OOFFSET) <= DMA2D_OFFSET) #define IS_DMA2D_INPUT_COLOR_MODE(INPUT_CM) (((INPUT_CM) == CM_ARGB8888) || ((INPUT_CM) == CM_RGB888) || \ ((INPUT_CM) == CM_RGB565) || ((INPUT_CM) == CM_ARGB1555) || \ ((INPUT_CM) == CM_ARGB4444) || ((INPUT_CM) == CM_L8) || \ ((INPUT_CM) == CM_AL44) || ((INPUT_CM) == CM_AL88) || \ ((INPUT_CM) == CM_L4) || ((INPUT_CM) == CM_A8) || \ ((INPUT_CM) == CM_A4)) #define IS_DMA2D_ALPHA_MODE(AlphaMode) (((AlphaMode) == DMA2D_NO_MODIF_ALPHA) || \ ((AlphaMode) == DMA2D_REPLACE_ALPHA) || \ ((AlphaMode) == DMA2D_COMBINE_ALPHA)) #define IS_DMA2D_CLUT_CM(CLUT_CM) (((CLUT_CM) == DMA2D_CCM_ARGB8888) || ((CLUT_CM) == DMA2D_CCM_RGB888)) #define IS_DMA2D_CLUT_SIZE(CLUT_SIZE) ((CLUT_SIZE) <= DMA2D_CLUT_SIZE) #define IS_DMA2D_LineWatermark(LineWatermark) ((LineWatermark) <= LINE_WATERMARK) /** * @} */ /* Private functions prototypes ---------------------------------------------------------*/ /** @defgroup DMA2D_Private_Functions_Prototypes DMA2D Private Functions Prototypes * @{ */ /** * @} */ /* Private functions ---------------------------------------------------------*/ /** @defgroup DMA2D_Private_Functions DMA2D Private Functions * @{ */ /** * @} */ /** * @} */ /** * @} */ #endif /* STM32F427xx || STM32F437xx || STM32F429xx || STM32F439xx || STM32F469xx || STM32F479xx */ #ifdef __cplusplus } #endif #endif /* __STM32F4xx_HAL_DMA2D_H */ /************************ (C) COPYRIGHT STMicroelectronics *****END OF FILE****/ ================================================ FILE: Zelig/mbed/TARGET_NUCLEO_F411RE/stm32f4xx_hal_dma_ex.h ================================================ /** ****************************************************************************** * @file stm32f4xx_hal_dma_ex.h * @author MCD Application Team * @version V1.4.1 * @date 09-October-2015 * @brief Header file of DMA HAL extension module. ****************************************************************************** * @attention * *

© COPYRIGHT(c) 2015 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. * ****************************************************************************** */ /* Define to prevent recursive inclusion -------------------------------------*/ #ifndef __STM32F4xx_HAL_DMA_EX_H #define __STM32F4xx_HAL_DMA_EX_H #ifdef __cplusplus extern "C" { #endif /* Includes ------------------------------------------------------------------*/ #include "stm32f4xx_hal_def.h" /** @addtogroup STM32F4xx_HAL_Driver * @{ */ /** @addtogroup DMAEx * @{ */ /* Exported types ------------------------------------------------------------*/ /** @defgroup DMAEx_Exported_Types DMAEx Exported Types * @brief DMAEx Exported types * @{ */ /** * @brief HAL DMA Memory definition */ typedef enum { MEMORY0 = 0x00, /*!< Memory 0 */ MEMORY1 = 0x01, /*!< Memory 1 */ }HAL_DMA_MemoryTypeDef; /** * @} */ /* Exported functions --------------------------------------------------------*/ /** @defgroup DMAEx_Exported_Functions DMAEx Exported Functions * @brief DMAEx Exported functions * @{ */ /** @defgroup DMAEx_Exported_Functions_Group1 Extended features functions * @brief Extended features functions * @{ */ /* IO operation functions *******************************************************/ HAL_StatusTypeDef HAL_DMAEx_MultiBufferStart(DMA_HandleTypeDef *hdma, uint32_t SrcAddress, uint32_t DstAddress, uint32_t SecondMemAddress, uint32_t DataLength); HAL_StatusTypeDef HAL_DMAEx_MultiBufferStart_IT(DMA_HandleTypeDef *hdma, uint32_t SrcAddress, uint32_t DstAddress, uint32_t SecondMemAddress, uint32_t DataLength); HAL_StatusTypeDef HAL_DMAEx_ChangeMemory(DMA_HandleTypeDef *hdma, uint32_t Address, HAL_DMA_MemoryTypeDef memory); /** * @} */ /** * @} */ /* Private functions ---------------------------------------------------------*/ /** @defgroup DMAEx_Private_Functions DMAEx Private Functions * @brief DMAEx Private functions * @{ */ /** * @} */ /** * @} */ /** * @} */ #ifdef __cplusplus } #endif #endif /*__STM32F4xx_HAL_DMA_EX_H*/ /************************ (C) COPYRIGHT STMicroelectronics *****END OF FILE****/ ================================================ FILE: Zelig/mbed/TARGET_NUCLEO_F411RE/stm32f4xx_hal_dsi.h ================================================ /** ****************************************************************************** * @file stm32f4xx_hal_dsi.h * @author MCD Application Team * @version V1.4.1 * @date 09-October-2015 * @brief Header file of DSI HAL module. ****************************************************************************** * @attention * *

© COPYRIGHT(c) 2015 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. * ****************************************************************************** */ /* Define to prevent recursive inclusion -------------------------------------*/ #ifndef __STM32F4xx_HAL_DSI_H #define __STM32F4xx_HAL_DSI_H #ifdef __cplusplus extern "C" { #endif #if defined(STM32F469xx) || defined(STM32F479xx) /* Includes ------------------------------------------------------------------*/ #include "stm32f4xx_hal_def.h" /** @addtogroup STM32F4xx_HAL_Driver * @{ */ /** @defgroup DSI DSI * @brief DSI HAL module driver * @{ */ /* Exported types ------------------------------------------------------------*/ /** * @brief DSI Init Structure definition */ typedef struct { uint32_t AutomaticClockLaneControl; /*!< Automatic clock lane control This parameter can be any value of @ref DSI_Automatic_Clk_Lane_Control */ uint32_t TXEscapeCkdiv; /*!< TX Escape clock division The values 0 and 1 stop the TX_ESC clock generation */ uint32_t NumberOfLanes; /*!< Number of lanes This parameter can be any value of @ref DSI_Number_Of_Lanes */ }DSI_InitTypeDef; /** * @brief DSI PLL Clock structure definition */ typedef struct { uint32_t PLLNDIV; /*!< PLL Loop Division Factor This parameter must be a value between 10 and 125 */ uint32_t PLLIDF; /*!< PLL Input Division Factor This parameter can be any value of @ref DSI_PLL_IDF */ uint32_t PLLODF; /*!< PLL Output Division Factor This parameter can be any value of @ref DSI_PLL_ODF */ }DSI_PLLInitTypeDef; /** * @brief DSI Video mode configuration */ typedef struct { uint32_t VirtualChannelID; /*!< Virtual channel ID */ uint32_t ColorCoding; /*!< Color coding for LTDC interface This parameter can be any value of @ref DSI_Color_Coding */ uint32_t LooselyPacked; /*!< Enable or disable loosely packed stream (needed only when using 18-bit configuration). This parameter can be any value of @ref DSI_LooselyPacked */ uint32_t Mode; /*!< Video mode type This parameter can be any value of @ref DSI_Video_Mode_Type */ uint32_t PacketSize; /*!< Video packet size */ uint32_t NumberOfChunks; /*!< Number of chunks */ uint32_t NullPacketSize; /*!< Null packet size */ uint32_t HSPolarity; /*!< HSYNC pin polarity This parameter can be any value of @ref DSI_HSYNC_Polarity */ uint32_t VSPolarity; /*!< VSYNC pin polarity This parameter can be any value of @ref DSI_VSYNC_Polarity */ uint32_t DEPolarity; /*!< Data Enable pin polarity This parameter can be any value of @ref DSI_DATA_ENABLE_Polarity */ uint32_t HorizontalSyncActive; /*!< Horizontal synchronism active duration (in lane byte clock cycles) */ uint32_t HorizontalBackPorch; /*!< Horizontal back-porch duration (in lane byte clock cycles) */ uint32_t HorizontalLine; /*!< Horizontal line duration (in lane byte clock cycles) */ uint32_t VerticalSyncActive; /*!< Vertical synchronism active duration */ uint32_t VerticalBackPorch; /*!< Vertical back-porch duration */ uint32_t VerticalFrontPorch; /*!< Vertical front-porch duration */ uint32_t VerticalActive; /*!< Vertical active duration */ uint32_t LPCommandEnable; /*!< Low-power command enable This parameter can be any value of @ref DSI_LP_Command */ uint32_t LPLargestPacketSize; /*!< The size, in bytes, of the low power largest packet that can fit in a line during VSA, VBP and VFP regions */ uint32_t LPVACTLargestPacketSize; /*!< The size, in bytes, of the low power largest packet that can fit in a line during VACT region */ uint32_t LPHorizontalFrontPorchEnable; /*!< Low-power horizontal front-porch enable This parameter can be any value of @ref DSI_LP_HFP */ uint32_t LPHorizontalBackPorchEnable; /*!< Low-power horizontal back-porch enable This parameter can be any value of @ref DSI_LP_HBP */ uint32_t LPVerticalActiveEnable; /*!< Low-power vertical active enable This parameter can be any value of @ref DSI_LP_VACT */ uint32_t LPVerticalFrontPorchEnable; /*!< Low-power vertical front-porch enable This parameter can be any value of @ref DSI_LP_VFP */ uint32_t LPVerticalBackPorchEnable; /*!< Low-power vertical back-porch enable This parameter can be any value of @ref DSI_LP_VBP */ uint32_t LPVerticalSyncActiveEnable; /*!< Low-power vertical sync active enable This parameter can be any value of @ref DSI_LP_VSYNC */ uint32_t FrameBTAAcknowledgeEnable; /*!< Frame bus-turn-around acknowledge enable This parameter can be any value of @ref DSI_FBTA_acknowledge */ }DSI_VidCfgTypeDef; /** * @brief DSI Adapted command mode configuration */ typedef struct { uint32_t VirtualChannelID; /*!< Virtual channel ID */ uint32_t ColorCoding; /*!< Color coding for LTDC interface This parameter can be any value of @ref DSI_Color_Coding */ uint32_t CommandSize; /*!< Maximum allowed size for an LTDC write memory command, measured in pixels. This parameter can be any value between 0x00 and 0xFFFF */ uint32_t TearingEffectSource; /*!< Tearing effect source This parameter can be any value of @ref DSI_TearingEffectSource */ uint32_t TearingEffectPolarity; /*!< Tearing effect pin polarity This parameter can be any value of @ref DSI_TearingEffectPolarity */ uint32_t HSPolarity; /*!< HSYNC pin polarity This parameter can be any value of @ref DSI_HSYNC_Polarity */ uint32_t VSPolarity; /*!< VSYNC pin polarity This parameter can be any value of @ref DSI_VSYNC_Polarity */ uint32_t DEPolarity; /*!< Data Enable pin polarity This parameter can be any value of @ref DSI_DATA_ENABLE_Polarity */ uint32_t VSyncPol; /*!< VSync edge on which the LTDC is halted This parameter can be any value of @ref DSI_Vsync_Polarity */ uint32_t AutomaticRefresh; /*!< Automatic refresh mode This parameter can be any value of @ref DSI_AutomaticRefresh */ uint32_t TEAcknowledgeRequest; /*!< Tearing Effect Acknowledge Request Enable This parameter can be any value of @ref DSI_TE_AcknowledgeRequest */ }DSI_CmdCfgTypeDef; /** * @brief DSI command transmission mode configuration */ typedef struct { uint32_t LPGenShortWriteNoP; /*!< Generic Short Write Zero parameters Transmission This parameter can be any value of @ref DSI_LP_LPGenShortWriteNoP */ uint32_t LPGenShortWriteOneP; /*!< Generic Short Write One parameter Transmission This parameter can be any value of @ref DSI_LP_LPGenShortWriteOneP */ uint32_t LPGenShortWriteTwoP; /*!< Generic Short Write Two parameters Transmission This parameter can be any value of @ref DSI_LP_LPGenShortWriteTwoP */ uint32_t LPGenShortReadNoP; /*!< Generic Short Read Zero parameters Transmission This parameter can be any value of @ref DSI_LP_LPGenShortReadNoP */ uint32_t LPGenShortReadOneP; /*!< Generic Short Read One parameter Transmission This parameter can be any value of @ref DSI_LP_LPGenShortReadOneP */ uint32_t LPGenShortReadTwoP; /*!< Generic Short Read Two parameters Transmission This parameter can be any value of @ref DSI_LP_LPGenShortReadTwoP */ uint32_t LPGenLongWrite; /*!< Generic Long Write Transmission This parameter can be any value of @ref DSI_LP_LPGenLongWrite */ uint32_t LPDcsShortWriteNoP; /*!< DCS Short Write Zero parameters Transmission This parameter can be any value of @ref DSI_LP_LPDcsShortWriteNoP */ uint32_t LPDcsShortWriteOneP; /*!< DCS Short Write One parameter Transmission This parameter can be any value of @ref DSI_LP_LPDcsShortWriteOneP */ uint32_t LPDcsShortReadNoP; /*!< DCS Short Read Zero parameters Transmission This parameter can be any value of @ref DSI_LP_LPDcsShortReadNoP */ uint32_t LPDcsLongWrite; /*!< DCS Long Write Transmission This parameter can be any value of @ref DSI_LP_LPDcsLongWrite */ uint32_t LPMaxReadPacket; /*!< Maximum Read Packet Size Transmission This parameter can be any value of @ref DSI_LP_LPMaxReadPacket */ uint32_t AcknowledgeRequest; /*!< Acknowledge Request Enable This parameter can be any value of @ref DSI_AcknowledgeRequest */ }DSI_LPCmdTypeDef; /** * @brief DSI PHY Timings definition */ typedef struct { uint32_t ClockLaneHS2LPTime; /*!< The maximum time that the D-PHY clock lane takes to go from high-speed to low-power transmission */ uint32_t ClockLaneLP2HSTime; /*!< The maximum time that the D-PHY clock lane takes to go from low-power to high-speed transmission */ uint32_t DataLaneHS2LPTime; /*!< The maximum time that the D-PHY data lanes takes to go from high-speed to low-power transmission */ uint32_t DataLaneLP2HSTime; /*!< The maximum time that the D-PHY data lanes takes to go from low-power to high-speed transmission */ uint32_t DataLaneMaxReadTime; /*!< The maximum time required to perform a read command */ uint32_t StopWaitTime; /*!< The minimum wait period to request a High-Speed transmission after the Stop state */ }DSI_PHY_TimerTypeDef; /** * @brief DSI HOST Timeouts definition */ typedef struct { uint32_t TimeoutCkdiv; /*!< Time-out clock division */ uint32_t HighSpeedTransmissionTimeout; /*!< High-speed transmission time-out */ uint32_t LowPowerReceptionTimeout; /*!< Low-power reception time-out */ uint32_t HighSpeedReadTimeout; /*!< High-speed read time-out */ uint32_t LowPowerReadTimeout; /*!< Low-power read time-out */ uint32_t HighSpeedWriteTimeout; /*!< High-speed write time-out */ uint32_t HighSpeedWritePrespMode; /*!< High-speed write presp mode This parameter can be any value of @ref DSI_HS_PrespMode */ uint32_t LowPowerWriteTimeout; /*!< Low-speed write time-out */ uint32_t BTATimeout; /*!< BTA time-out */ }DSI_HOST_TimeoutTypeDef; /** * @brief DSI States Structure definition */ typedef enum { HAL_DSI_STATE_RESET = 0x00, HAL_DSI_STATE_READY = 0x01, HAL_DSI_STATE_ERROR = 0x02, HAL_DSI_STATE_BUSY = 0x03, HAL_DSI_STATE_TIMEOUT = 0x04 }HAL_DSI_StateTypeDef; /** * @brief DSI Handle Structure definition */ typedef struct { DSI_TypeDef *Instance; /*!< Register base address */ DSI_InitTypeDef Init; /*!< DSI required parameters */ HAL_LockTypeDef Lock; /*!< DSI peripheral status */ __IO HAL_DSI_StateTypeDef State; /*!< DSI communication state */ __IO uint32_t ErrorCode; /*!< DSI Error code */ uint32_t ErrorMsk; /*!< DSI Error monitoring mask */ }DSI_HandleTypeDef; /* Exported constants --------------------------------------------------------*/ /** @defgroup DSI_DCS_Command DSI DCS Command * @{ */ #define DSI_ENTER_IDLE_MODE 0x39 #define DSI_ENTER_INVERT_MODE 0x21 #define DSI_ENTER_NORMAL_MODE 0x13 #define DSI_ENTER_PARTIAL_MODE 0x12 #define DSI_ENTER_SLEEP_MODE 0x10 #define DSI_EXIT_IDLE_MODE 0x38 #define DSI_EXIT_INVERT_MODE 0x20 #define DSI_EXIT_SLEEP_MODE 0x11 #define DSI_GET_3D_CONTROL 0x3F #define DSI_GET_ADDRESS_MODE 0x0B #define DSI_GET_BLUE_CHANNEL 0x08 #define DSI_GET_DIAGNOSTIC_RESULT 0x0F #define DSI_GET_DISPLAY_MODE 0x0D #define DSI_GET_GREEN_CHANNEL 0x07 #define DSI_GET_PIXEL_FORMAT 0x0C #define DSI_GET_POWER_MODE 0x0A #define DSI_GET_RED_CHANNEL 0x06 #define DSI_GET_SCANLINE 0x45 #define DSI_GET_SIGNAL_MODE 0x0E #define DSI_NOP 0x00 #define DSI_READ_DDB_CONTINUE 0xA8 #define DSI_READ_DDB_START 0xA1 #define DSI_READ_MEMORY_CONTINUE 0x3E #define DSI_READ_MEMORY_START 0x2E #define DSI_SET_3D_CONTROL 0x3D #define DSI_SET_ADDRESS_MODE 0x36 #define DSI_SET_COLUMN_ADDRESS 0x2A #define DSI_SET_DISPLAY_OFF 0x28 #define DSI_SET_DISPLAY_ON 0x29 #define DSI_SET_GAMMA_CURVE 0x26 #define DSI_SET_PAGE_ADDRESS 0x2B #define DSI_SET_PARTIAL_COLUMNS 0x31 #define DSI_SET_PARTIAL_ROWS 0x30 #define DSI_SET_PIXEL_FORMAT 0x3A #define DSI_SET_SCROLL_AREA 0x33 #define DSI_SET_SCROLL_START 0x37 #define DSI_SET_TEAR_OFF 0x34 #define DSI_SET_TEAR_ON 0x35 #define DSI_SET_TEAR_SCANLINE 0x44 #define DSI_SET_VSYNC_TIMING 0x40 #define DSI_SOFT_RESET 0x01 #define DSI_WRITE_LUT 0x2D #define DSI_WRITE_MEMORY_CONTINUE 0x3C #define DSI_WRITE_MEMORY_START 0x2C /** * @} */ /** @defgroup DSI_Video_Mode_Type DSI Video Mode Type * @{ */ #define DSI_VID_MODE_NB_PULSES 0 #define DSI_VID_MODE_NB_EVENTS 1 #define DSI_VID_MODE_BURST 2 /** * @} */ /** @defgroup DSI_Color_Mode DSI Color Mode * @{ */ #define DSI_COLOR_MODE_FULL 0 #define DSI_COLOR_MODE_EIGHT DSI_WCR_COLM /** * @} */ /** @defgroup DSI_ShutDown DSI ShutDown * @{ */ #define DSI_DISPLAY_ON 0 #define DSI_DISPLAY_OFF DSI_WCR_SHTDN /** * @} */ /** @defgroup DSI_LP_Command DSI LP Command * @{ */ #define DSI_LP_COMMAND_DISABLE 0 #define DSI_LP_COMMAND_ENABLE DSI_VMCR_LPCE /** * @} */ /** @defgroup DSI_LP_HFP DSI LP HFP * @{ */ #define DSI_LP_HFP_DISABLE 0 #define DSI_LP_HFP_ENABLE DSI_VMCR_LPHFPE /** * @} */ /** @defgroup DSI_LP_HBP DSI LP HBP * @{ */ #define DSI_LP_HBP_DISABLE 0 #define DSI_LP_HBP_ENABLE DSI_VMCR_LPHBPE /** * @} */ /** @defgroup DSI_LP_VACT DSI LP VACT * @{ */ #define DSI_LP_VACT_DISABLE 0 #define DSI_LP_VACT_ENABLE DSI_VMCR_LPVAE /** * @} */ /** @defgroup DSI_LP_VFP DSI LP VFP * @{ */ #define DSI_LP_VFP_DISABLE 0 #define DSI_LP_VFP_ENABLE DSI_VMCR_LPVFPE /** * @} */ /** @defgroup DSI_LP_VBP DSI LP VBP * @{ */ #define DSI_LP_VBP_DISABLE 0 #define DSI_LP_VBP_ENABLE DSI_VMCR_LPVBPE /** * @} */ /** @defgroup DSI_LP_VSYNC DSI LP VSYNC * @{ */ #define DSI_LP_VSYNC_DISABLE 0 #define DSI_LP_VSYNC_ENABLE DSI_VMCR_LPVSAE /** * @} */ /** @defgroup DSI_FBTA_acknowledge DSI FBTA Acknowledge * @{ */ #define DSI_FBTAA_DISABLE 0 #define DSI_FBTAA_ENABLE DSI_VMCR_FBTAAE /** * @} */ /** @defgroup DSI_TearingEffectSource DSI Tearing Effect Source * @{ */ #define DSI_TE_DSILINK 0 #define DSI_TE_EXTERNAL DSI_WCFGR_TESRC /** * @} */ /** @defgroup DSI_TearingEffectPolarity DSI Tearing Effect Polarity * @{ */ #define DSI_TE_RISING_EDGE 0 #define DSI_TE_FALLING_EDGE DSI_WCFGR_TEPOL /** * @} */ /** @defgroup DSI_Vsync_Polarity DSI Vsync Polarity * @{ */ #define DSI_VSYNC_FALLING 0 #define DSI_VSYNC_RISING DSI_WCFGR_VSPOL /** * @} */ /** @defgroup DSI_AutomaticRefresh DSI Automatic Refresh * @{ */ #define DSI_AR_DISABLE 0 #define DSI_AR_ENABLE DSI_WCFGR_AR /** * @} */ /** @defgroup DSI_TE_AcknowledgeRequest DSI TE Acknowledge Request * @{ */ #define DSI_TE_ACKNOWLEDGE_DISABLE 0 #define DSI_TE_ACKNOWLEDGE_ENABLE DSI_CMCR_TEARE /** * @} */ /** @defgroup DSI_AcknowledgeRequest DSI Acknowledge Request * @{ */ #define DSI_ACKNOWLEDGE_DISABLE 0 #define DSI_ACKNOWLEDGE_ENABLE DSI_CMCR_ARE /** * @} */ /** @defgroup DSI_LP_LPGenShortWriteNoP DSI LP LPGen Short Write NoP * @{ */ #define DSI_LP_GSW0P_DISABLE 0 #define DSI_LP_GSW0P_ENABLE DSI_CMCR_GSW0TX /** * @} */ /** @defgroup DSI_LP_LPGenShortWriteOneP DSI LP LPGen Short Write OneP * @{ */ #define DSI_LP_GSW1P_DISABLE 0 #define DSI_LP_GSW1P_ENABLE DSI_CMCR_GSW1TX /** * @} */ /** @defgroup DSI_LP_LPGenShortWriteTwoP DSI LP LPGen Short Write TwoP * @{ */ #define DSI_LP_GSW2P_DISABLE 0 #define DSI_LP_GSW2P_ENABLE DSI_CMCR_GSW2TX /** * @} */ /** @defgroup DSI_LP_LPGenShortReadNoP DSI LP LPGen Short Read NoP * @{ */ #define DSI_LP_GSR0P_DISABLE 0 #define DSI_LP_GSR0P_ENABLE DSI_CMCR_GSR0TX /** * @} */ /** @defgroup DSI_LP_LPGenShortReadOneP DSI LP LPGen Short Read OneP * @{ */ #define DSI_LP_GSR1P_DISABLE 0 #define DSI_LP_GSR1P_ENABLE DSI_CMCR_GSR1TX /** * @} */ /** @defgroup DSI_LP_LPGenShortReadTwoP DSI LP LPGen Short Read TwoP * @{ */ #define DSI_LP_GSR2P_DISABLE 0 #define DSI_LP_GSR2P_ENABLE DSI_CMCR_GSR2TX /** * @} */ /** @defgroup DSI_LP_LPGenLongWrite DSI LP LPGen LongWrite * @{ */ #define DSI_LP_GLW_DISABLE 0 #define DSI_LP_GLW_ENABLE DSI_CMCR_GLWTX /** * @} */ /** @defgroup DSI_LP_LPDcsShortWriteNoP DSI LP LPDcs Short Write NoP * @{ */ #define DSI_LP_DSW0P_DISABLE 0 #define DSI_LP_DSW0P_ENABLE DSI_CMCR_DSW0TX /** * @} */ /** @defgroup DSI_LP_LPDcsShortWriteOneP DSI LP LPDcs Short Write OneP * @{ */ #define DSI_LP_DSW1P_DISABLE 0 #define DSI_LP_DSW1P_ENABLE DSI_CMCR_DSW1TX /** * @} */ /** @defgroup DSI_LP_LPDcsShortReadNoP DSI LP LPDcs Short Read NoP * @{ */ #define DSI_LP_DSR0P_DISABLE 0 #define DSI_LP_DSR0P_ENABLE DSI_CMCR_DSR0TX /** * @} */ /** @defgroup DSI_LP_LPDcsLongWrite DSI LP LPDcs Long Write * @{ */ #define DSI_LP_DLW_DISABLE 0 #define DSI_LP_DLW_ENABLE DSI_CMCR_DLWTX /** * @} */ /** @defgroup DSI_LP_LPMaxReadPacket DSI LP LPMax Read Packet * @{ */ #define DSI_LP_MRDP_DISABLE 0 #define DSI_LP_MRDP_ENABLE DSI_CMCR_MRDPS /** * @} */ /** @defgroup DSI_HS_PrespMode DSI HS Presp Mode * @{ */ #define DSI_HS_PM_DISABLE 0 #define DSI_HS_PM_ENABLE DSI_TCCR3_PM /** * @} */ /** @defgroup DSI_Automatic_Clk_Lane_Control DSI Automatic Clk Lane Control * @{ */ #define DSI_AUTO_CLK_LANE_CTRL_DISABLE 0 #define DSI_AUTO_CLK_LANE_CTRL_ENABLE DSI_CLCR_ACR /** * @} */ /** @defgroup DSI_Number_Of_Lanes DSI Number Of Lanes * @{ */ #define DSI_ONE_DATA_LANE 0 #define DSI_TWO_DATA_LANES 1 /** * @} */ /** @defgroup DSI_FlowControl DSI Flow Control * @{ */ #define DSI_FLOW_CONTROL_CRC_RX DSI_PCR_CRCRXE #define DSI_FLOW_CONTROL_ECC_RX DSI_PCR_ECCRXE #define DSI_FLOW_CONTROL_BTA DSI_PCR_BTAE #define DSI_FLOW_CONTROL_EOTP_RX DSI_PCR_ETRXE #define DSI_FLOW_CONTROL_EOTP_TX DSI_PCR_ETTXE #define DSI_FLOW_CONTROL_ALL (DSI_FLOW_CONTROL_CRC_RX | DSI_FLOW_CONTROL_ECC_RX | \ DSI_FLOW_CONTROL_BTA | DSI_FLOW_CONTROL_EOTP_RX | \ DSI_FLOW_CONTROL_EOTP_TX) /** * @} */ /** @defgroup DSI_Color_Coding DSI Color Coding * @{ */ #define DSI_RGB565 ((uint32_t)0x00000000) /*!< The values 0x00000001 and 0x00000002 can also be used for the RGB565 color mode configuration */ #define DSI_RGB666 ((uint32_t)0x00000003) /*!< The value 0x00000004 can also be used for the RGB666 color mode configuration */ #define DSI_RGB888 ((uint32_t)0x00000005) /** * @} */ /** @defgroup DSI_LooselyPacked DSI Loosely Packed * @{ */ #define DSI_LOOSELY_PACKED_ENABLE DSI_LCOLCR_LPE #define DSI_LOOSELY_PACKED_DISABLE 0 /** * @} */ /** @defgroup DSI_HSYNC_Polarity DSI HSYNC Polarity * @{ */ #define DSI_HSYNC_ACTIVE_HIGH 0 #define DSI_HSYNC_ACTIVE_LOW DSI_LPCR_HSP /** * @} */ /** @defgroup DSI_VSYNC_Polarity DSI VSYNC Polarity * @{ */ #define DSI_VSYNC_ACTIVE_HIGH 0 #define DSI_VSYNC_ACTIVE_LOW DSI_LPCR_VSP /** * @} */ /** @defgroup DSI_DATA_ENABLE_Polarity DSI DATA ENABLE Polarity * @{ */ #define DSI_DATA_ENABLE_ACTIVE_HIGH 0 #define DSI_DATA_ENABLE_ACTIVE_LOW DSI_LPCR_DEP /** * @} */ /** @defgroup DSI_PLL_IDF DSI PLL IDF * @{ */ #define DSI_PLL_IN_DIV1 ((uint32_t)0x00000001) #define DSI_PLL_IN_DIV2 ((uint32_t)0x00000002) #define DSI_PLL_IN_DIV3 ((uint32_t)0x00000003) #define DSI_PLL_IN_DIV4 ((uint32_t)0x00000004) #define DSI_PLL_IN_DIV5 ((uint32_t)0x00000005) #define DSI_PLL_IN_DIV6 ((uint32_t)0x00000006) #define DSI_PLL_IN_DIV7 ((uint32_t)0x00000007) /** * @} */ /** @defgroup DSI_PLL_ODF DSI PLL ODF * @{ */ #define DSI_PLL_OUT_DIV1 ((uint32_t)0x00000000) #define DSI_PLL_OUT_DIV2 ((uint32_t)0x00000001) #define DSI_PLL_OUT_DIV4 ((uint32_t)0x00000002) #define DSI_PLL_OUT_DIV8 ((uint32_t)0x00000003) /** * @} */ /** @defgroup DSI_Flags DSI Flags * @{ */ #define DSI_FLAG_TE DSI_WISR_TEIF #define DSI_FLAG_ER DSI_WISR_ERIF #define DSI_FLAG_BUSY DSI_WISR_BUSY #define DSI_FLAG_PLLLS DSI_WISR_PLLLS #define DSI_FLAG_PLLL DSI_WISR_PLLLIF #define DSI_FLAG_PLLU DSI_WISR_PLLUIF #define DSI_FLAG_RRS DSI_WISR_RRS #define DSI_FLAG_RR DSI_WISR_RRIF /** * @} */ /** @defgroup DSI_Interrupts DSI Interrupts * @{ */ #define DSI_IT_TE DSI_WIER_TEIE #define DSI_IT_ER DSI_WIER_ERIE #define DSI_IT_PLLL DSI_WIER_PLLLIE #define DSI_IT_PLLU DSI_WIER_PLLUIE #define DSI_IT_RR DSI_WIER_RRIE /** * @} */ /** @defgroup DSI_SHORT_WRITE_PKT_Data_Type DSI SHORT WRITE PKT Data Type * @{ */ #define DSI_DCS_SHORT_PKT_WRITE_P0 ((uint32_t)0x00000005) /*!< DCS short write, no parameters */ #define DSI_DCS_SHORT_PKT_WRITE_P1 ((uint32_t)0x00000015) /*!< DCS short write, one parameter */ #define DSI_GEN_SHORT_PKT_WRITE_P0 ((uint32_t)0x00000003) /*!< Generic short write, no parameters */ #define DSI_GEN_SHORT_PKT_WRITE_P1 ((uint32_t)0x00000013) /*!< Generic short write, one parameter */ #define DSI_GEN_SHORT_PKT_WRITE_P2 ((uint32_t)0x00000023) /*!< Generic short write, two parameters */ /** * @} */ /** @defgroup DSI_LONG_WRITE_PKT_Data_Type DSI LONG WRITE PKT Data Type * @{ */ #define DSI_DCS_LONG_PKT_WRITE ((uint32_t)0x00000039) /*!< DCS long write */ #define DSI_GEN_LONG_PKT_WRITE ((uint32_t)0x00000029) /*!< Generic long write */ /** * @} */ /** @defgroup DSI_SHORT_READ_PKT_Data_Type DSI SHORT READ PKT Data Type * @{ */ #define DSI_DCS_SHORT_PKT_READ ((uint32_t)0x00000006) /*!< DCS short read */ #define DSI_GEN_SHORT_PKT_READ_P0 ((uint32_t)0x00000004) /*!< Generic short read, no parameters */ #define DSI_GEN_SHORT_PKT_READ_P1 ((uint32_t)0x00000014) /*!< Generic short read, one parameter */ #define DSI_GEN_SHORT_PKT_READ_P2 ((uint32_t)0x00000024) /*!< Generic short read, two parameters */ /** * @} */ /** @defgroup DSI_Error_Data_Type DSI Error Data Type * @{ */ #define HAL_DSI_ERROR_NONE 0 #define HAL_DSI_ERROR_ACK ((uint32_t)0x00000001) /*!< acknowledge errors */ #define HAL_DSI_ERROR_PHY ((uint32_t)0x00000002) /*!< PHY related errors */ #define HAL_DSI_ERROR_TX ((uint32_t)0x00000004) /*!< transmission error */ #define HAL_DSI_ERROR_RX ((uint32_t)0x00000008) /*!< reception error */ #define HAL_DSI_ERROR_ECC ((uint32_t)0x00000010) /*!< ECC errors */ #define HAL_DSI_ERROR_CRC ((uint32_t)0x00000020) /*!< CRC error */ #define HAL_DSI_ERROR_PSE ((uint32_t)0x00000040) /*!< Packet Size error */ #define HAL_DSI_ERROR_EOT ((uint32_t)0x00000080) /*!< End Of Transmission error */ #define HAL_DSI_ERROR_OVF ((uint32_t)0x00000100) /*!< FIFO overflow error */ #define HAL_DSI_ERROR_GEN ((uint32_t)0x00000200) /*!< Generic FIFO related errors */ /** * @} */ /** @defgroup DSI_Lane_Group DSI Lane Group * @{ */ #define DSI_CLOCK_LANE ((uint32_t)0x00000000) #define DSI_DATA_LANES ((uint32_t)0x00000001) /** * @} */ /** @defgroup DSI_Communication_Delay DSI Communication Delay * @{ */ #define DSI_SLEW_RATE_HSTX ((uint32_t)0x00000000) #define DSI_SLEW_RATE_LPTX ((uint32_t)0x00000001) #define DSI_HS_DELAY ((uint32_t)0x00000002) /** * @} */ /** @defgroup DSI_CustomLane DSI CustomLane * @{ */ #define DSI_SWAP_LANE_PINS ((uint32_t)0x00000000) #define DSI_INVERT_HS_SIGNAL ((uint32_t)0x00000001) /** * @} */ /** @defgroup DSI_Lane_Select DSI Lane Select * @{ */ #define DSI_CLOCK_LANE ((uint32_t)0x00000000) #define DSI_DATA_LANE0 ((uint32_t)0x00000001) #define DSI_DATA_LANE1 ((uint32_t)0x00000002) /** * @} */ /** @defgroup DSI_PHY_Timing DSI PHY Timing * @{ */ #define DSI_TCLK_POST ((uint32_t)0x00000000) #define DSI_TLPX_CLK ((uint32_t)0x00000001) #define DSI_THS_EXIT ((uint32_t)0x00000002) #define DSI_TLPX_DATA ((uint32_t)0x00000003) #define DSI_THS_ZERO ((uint32_t)0x00000004) #define DSI_THS_TRAIL ((uint32_t)0x00000005) #define DSI_THS_PREPARE ((uint32_t)0x00000006) #define DSI_TCLK_ZERO ((uint32_t)0x00000007) #define DSI_TCLK_PREPARE ((uint32_t)0x00000008) /** * @} */ /* Exported macros -----------------------------------------------------------*/ /** * @brief Enables the DSI host. * @param __HANDLE__: DSI handle * @retval None. */ #define __HAL_DSI_ENABLE(__HANDLE__) ((__HANDLE__)->Instance->CR |= DSI_CR_EN) /** * @brief Disables the DSI host. * @param __HANDLE__: DSI handle * @retval None. */ #define __HAL_DSI_DISABLE(__HANDLE__) ((__HANDLE__)->Instance->CR &= ~DSI_CR_EN) /** * @brief Enables the DSI wrapper. * @param __HANDLE__: DSI handle * @retval None. */ #define __HAL_DSI_WRAPPER_ENABLE(__HANDLE__) ((__HANDLE__)->Instance->WCR |= DSI_WCR_DSIEN) /** * @brief Disable the DSI wrapper. * @param __HANDLE__: DSI handle * @retval None. */ #define __HAL_DSI_WRAPPER_DISABLE(__HANDLE__) ((__HANDLE__)->Instance->WCR &= ~DSI_WCR_DSIEN) /** * @brief Enables the DSI PLL. * @param __HANDLE__: DSI handle * @retval None. */ #define __HAL_DSI_PLL_ENABLE(__HANDLE__) ((__HANDLE__)->Instance->WRPCR |= DSI_WRPCR_PLLEN) /** * @brief Disables the DSI PLL. * @param __HANDLE__: DSI handle * @retval None. */ #define __HAL_DSI_PLL_DISABLE(__HANDLE__) ((__HANDLE__)->Instance->WRPCR &= ~DSI_WRPCR_PLLEN) /** * @brief Enables the DSI regulator. * @param __HANDLE__: DSI handle * @retval None. */ #define __HAL_DSI_REG_ENABLE(__HANDLE__) ((__HANDLE__)->Instance->WRPCR |= DSI_WRPCR_REGEN) /** * @brief Disables the DSI regulator. * @param __HANDLE__: DSI handle * @retval None. */ #define __HAL_DSI_REG_DISABLE(__HANDLE__) ((__HANDLE__)->Instance->WRPCR &= ~DSI_WRPCR_REGEN) /** * @brief Get the DSI pending flags. * @param __HANDLE__: DSI handle. * @param __FLAG__: Get the specified flag. * This parameter can be any combination of the following values: * @arg DSI_FLAG_TE : Tearing Effect Interrupt Flag * @arg DSI_FLAG_ER : End of Refresh Interrupt Flag * @arg DSI_FLAG_BUSY : Busy Flag * @arg DSI_FLAG_PLLLS: PLL Lock Status * @arg DSI_FLAG_PLLL : PLL Lock Interrupt Flag * @arg DSI_FLAG_PLLU : PLL Unlock Interrupt Flag * @arg DSI_FLAG_RRS : Regulator Ready Flag * @arg DSI_FLAG_RR : Regulator Ready Interrupt Flag * @retval The state of FLAG (SET or RESET). */ #define __HAL_DSI_GET_FLAG(__HANDLE__, __FLAG__) ((__HANDLE__)->Instance->WISR & (__FLAG__)) /** * @brief Clears the DSI pending flags. * @param __HANDLE__: DSI handle. * @param __FLAG__: specifies the flag to clear. * This parameter can be any combination of the following values: * @arg DSI_FLAG_TE : Tearing Effect Interrupt Flag * @arg DSI_FLAG_ER : End of Refresh Interrupt Flag * @arg DSI_FLAG_PLLL : PLL Lock Interrupt Flag * @arg DSI_FLAG_PLLU : PLL Unlock Interrupt Flag * @arg DSI_FLAG_RR : Regulator Ready Interrupt Flag * @retval None */ #define __HAL_DSI_CLEAR_FLAG(__HANDLE__, __FLAG__) ((__HANDLE__)->Instance->WIFCR = (__FLAG__)) /** * @brief Enables the specified DSI interrupts. * @param __HANDLE__: DSI handle. * @param __INTERRUPT__: specifies the DSI interrupt sources to be enabled. * This parameter can be any combination of the following values: * @arg DSI_IT_TE : Tearing Effect Interrupt * @arg DSI_IT_ER : End of Refresh Interrupt * @arg DSI_IT_PLLL: PLL Lock Interrupt * @arg DSI_IT_PLLU: PLL Unlock Interrupt * @arg DSI_IT_RR : Regulator Ready Interrupt * @retval None */ #define __HAL_DSI_ENABLE_IT(__HANDLE__, __INTERRUPT__) ((__HANDLE__)->Instance->WIER |= (__INTERRUPT__)) /** * @brief Disables the specified DSI interrupts. * @param __HANDLE__: DSI handle * @param __INTERRUPT__: specifies the DSI interrupt sources to be disabled. * This parameter can be any combination of the following values: * @arg DSI_IT_TE : Tearing Effect Interrupt * @arg DSI_IT_ER : End of Refresh Interrupt * @arg DSI_IT_PLLL: PLL Lock Interrupt * @arg DSI_IT_PLLU: PLL Unlock Interrupt * @arg DSI_IT_RR : Regulator Ready Interrupt * @retval None */ #define __HAL_DSI_DISABLE_IT(__HANDLE__, __INTERRUPT__) ((__HANDLE__)->Instance->WIER &= ~(__INTERRUPT__)) /** * @brief Checks whether the specified DSI interrupt has occurred or not. * @param __HANDLE__: DSI handle * @param __INTERRUPT__: specifies the DSI interrupt source to check. * This parameter can be one of the following values: * @arg DSI_IT_TE : Tearing Effect Interrupt * @arg DSI_IT_ER : End of Refresh Interrupt * @arg DSI_IT_PLLL: PLL Lock Interrupt * @arg DSI_IT_PLLU: PLL Unlock Interrupt * @arg DSI_IT_RR : Regulator Ready Interrupt * @retval The state of INTERRUPT (SET or RESET). */ #define __HAL_DSI_GET_IT_SOURCE(__HANDLE__, __INTERRUPT__) ((__HANDLE__)->Instance->WISR & (__INTERRUPT__)) /* Exported functions --------------------------------------------------------*/ /** @defgroup DSI_Exported_Functions DSI Exported Functions * @{ */ HAL_StatusTypeDef HAL_DSI_Init(DSI_HandleTypeDef *hdsi, DSI_PLLInitTypeDef *PLLInit); HAL_StatusTypeDef HAL_DSI_DeInit(DSI_HandleTypeDef *hdsi); void HAL_DSI_MspInit(DSI_HandleTypeDef *hdsi); void HAL_DSI_MspDeInit(DSI_HandleTypeDef *hdsi); void HAL_DSI_IRQHandler(DSI_HandleTypeDef *hdsi); void HAL_DSI_TearingEffectCallback(DSI_HandleTypeDef *hdsi); void HAL_DSI_EndOfRefreshCallback(DSI_HandleTypeDef *hdsi); void HAL_DSI_ErrorCallback(DSI_HandleTypeDef *hdsi); HAL_StatusTypeDef HAL_DSI_SetGenericVCID(DSI_HandleTypeDef *hdsi, uint32_t VirtualChannelID); HAL_StatusTypeDef HAL_DSI_ConfigVideoMode(DSI_HandleTypeDef *hdsi, DSI_VidCfgTypeDef *VidCfg); HAL_StatusTypeDef HAL_DSI_ConfigAdaptedCommandMode(DSI_HandleTypeDef *hdsi, DSI_CmdCfgTypeDef *CmdCfg); HAL_StatusTypeDef HAL_DSI_ConfigCommand(DSI_HandleTypeDef *hdsi, DSI_LPCmdTypeDef *LPCmd); HAL_StatusTypeDef HAL_DSI_ConfigFlowControl(DSI_HandleTypeDef *hdsi, uint32_t FlowControl); HAL_StatusTypeDef HAL_DSI_ConfigPhyTimer(DSI_HandleTypeDef *hdsi, DSI_PHY_TimerTypeDef *PhyTimings); HAL_StatusTypeDef HAL_DSI_ConfigHostTimeouts(DSI_HandleTypeDef *hdsi, DSI_HOST_TimeoutTypeDef *HostTimeouts); HAL_StatusTypeDef HAL_DSI_Start(DSI_HandleTypeDef *hdsi); HAL_StatusTypeDef HAL_DSI_Stop(DSI_HandleTypeDef *hdsi); HAL_StatusTypeDef HAL_DSI_Refresh(DSI_HandleTypeDef *hdsi); HAL_StatusTypeDef HAL_DSI_ColorMode(DSI_HandleTypeDef *hdsi, uint32_t ColorMode); HAL_StatusTypeDef HAL_DSI_Shutdown(DSI_HandleTypeDef *hdsi, uint32_t Shutdown); HAL_StatusTypeDef HAL_DSI_ShortWrite(DSI_HandleTypeDef *hdsi, uint32_t ChannelID, uint32_t Mode, uint32_t Param1, uint32_t Param2); HAL_StatusTypeDef HAL_DSI_LongWrite(DSI_HandleTypeDef *hdsi, uint32_t ChannelID, uint32_t Mode, uint32_t Nbparams, uint32_t Param1, uint8_t* ParametersTable); HAL_StatusTypeDef HAL_DSI_Read(DSI_HandleTypeDef *hdsi, uint32_t ChannelNbr, uint8_t* Array, uint32_t Size, uint32_t Mode, uint32_t DCSCmd, uint8_t* ParametersTable); HAL_StatusTypeDef HAL_DSI_EnterULPMData(DSI_HandleTypeDef *hdsi); HAL_StatusTypeDef HAL_DSI_ExitULPMData(DSI_HandleTypeDef *hdsi); HAL_StatusTypeDef HAL_DSI_EnterULPM(DSI_HandleTypeDef *hdsi); HAL_StatusTypeDef HAL_DSI_ExitULPM(DSI_HandleTypeDef *hdsi); HAL_StatusTypeDef HAL_DSI_PatternGeneratorStart(DSI_HandleTypeDef *hdsi, uint32_t Mode, uint32_t Orientation); HAL_StatusTypeDef HAL_DSI_PatternGeneratorStop(DSI_HandleTypeDef *hdsi); HAL_StatusTypeDef HAL_DSI_SetSlewRateAndDelayTuning(DSI_HandleTypeDef *hdsi, uint32_t CommDelay, uint32_t Lane, uint32_t Value); HAL_StatusTypeDef HAL_DSI_SetLowPowerRXFilter(DSI_HandleTypeDef *hdsi, uint32_t Frequency); HAL_StatusTypeDef HAL_DSI_SetSDD(DSI_HandleTypeDef *hdsi, FunctionalState State); HAL_StatusTypeDef HAL_DSI_SetLanePinsConfiguration(DSI_HandleTypeDef *hdsi, uint32_t CustomLane, uint32_t Lane, FunctionalState State); HAL_StatusTypeDef HAL_DSI_SetPHYTimings(DSI_HandleTypeDef *hdsi, uint32_t Timing, FunctionalState State, uint32_t Value); HAL_StatusTypeDef HAL_DSI_ForceTXStopMode(DSI_HandleTypeDef *hdsi, uint32_t Lane, FunctionalState State); HAL_StatusTypeDef HAL_DSI_ForceRXLowPower(DSI_HandleTypeDef *hdsi, FunctionalState State); HAL_StatusTypeDef HAL_DSI_ForceDataLanesInRX(DSI_HandleTypeDef *hdsi, FunctionalState State); HAL_StatusTypeDef HAL_DSI_SetPullDown(DSI_HandleTypeDef *hdsi, FunctionalState State); HAL_StatusTypeDef HAL_DSI_SetContentionDetectionOff(DSI_HandleTypeDef *hdsi, FunctionalState State); uint32_t HAL_DSI_GetError(DSI_HandleTypeDef *hdsi); HAL_StatusTypeDef HAL_DSI_ConfigErrorMonitor(DSI_HandleTypeDef *hdsi, uint32_t ActiveErrors); HAL_DSI_StateTypeDef HAL_DSI_GetState(DSI_HandleTypeDef *hdsi); /** * @} */ /* Private types -------------------------------------------------------------*/ /** @defgroup DSI_Private_Types DSI Private Types * @{ */ /** * @} */ /* Private defines -----------------------------------------------------------*/ /** @defgroup DSI_Private_Defines DSI Private Defines * @{ */ /** * @} */ /* Private variables ---------------------------------------------------------*/ /** @defgroup DSI_Private_Variables DSI Private Variables * @{ */ /** * @} */ /* Private constants ---------------------------------------------------------*/ /** @defgroup DSI_Private_Constants DSI Private Constants * @{ */ #define DSI_MAX_RETURN_PKT_SIZE ((uint32_t)0x00000037) /*!< Maximum return packet configuration */ /** * @} */ /* Private macros ------------------------------------------------------------*/ /** @defgroup DSI_Private_Macros DSI Private Macros * @{ */ #define IS_DSI_PLL_NDIV(NDIV) ((10 <= (NDIV)) && ((NDIV) <= 125)) #define IS_DSI_PLL_IDF(IDF) (((IDF) == DSI_PLL_IN_DIV1) || \ ((IDF) == DSI_PLL_IN_DIV2) || \ ((IDF) == DSI_PLL_IN_DIV3) || \ ((IDF) == DSI_PLL_IN_DIV4) || \ ((IDF) == DSI_PLL_IN_DIV5) || \ ((IDF) == DSI_PLL_IN_DIV6) || \ ((IDF) == DSI_PLL_IN_DIV7)) #define IS_DSI_PLL_ODF(ODF) (((ODF) == DSI_PLL_OUT_DIV1) || \ ((ODF) == DSI_PLL_OUT_DIV2) || \ ((ODF) == DSI_PLL_OUT_DIV4) || \ ((ODF) == DSI_PLL_OUT_DIV8)) #define IS_DSI_AUTO_CLKLANE_CONTROL(AutoClkLane) (((AutoClkLane) == DSI_AUTO_CLK_LANE_CTRL_DISABLE) || ((AutoClkLane) == DSI_AUTO_CLK_LANE_CTRL_ENABLE)) #define IS_DSI_NUMBER_OF_LANES(NumberOfLanes) (((NumberOfLanes) == DSI_ONE_DATA_LANE) || ((NumberOfLanes) == DSI_TWO_DATA_LANES)) #define IS_DSI_FLOW_CONTROL(FlowControl) (((FlowControl) | DSI_FLOW_CONTROL_ALL) == DSI_FLOW_CONTROL_ALL) #define IS_DSI_COLOR_CODING(ColorCoding) ((ColorCoding) <= 5) #define IS_DSI_LOOSELY_PACKED(LooselyPacked) (((LooselyPacked) == DSI_LOOSELY_PACKED_ENABLE) || ((LooselyPacked) == DSI_LOOSELY_PACKED_DISABLE)) #define IS_DSI_DE_POLARITY(DataEnable) (((DataEnable) == DSI_DATA_ENABLE_ACTIVE_HIGH) || ((DataEnable) == DSI_DATA_ENABLE_ACTIVE_LOW)) #define IS_DSI_VSYNC_POLARITY(VSYNC) (((VSYNC) == DSI_VSYNC_ACTIVE_HIGH) || ((VSYNC) == DSI_VSYNC_ACTIVE_LOW)) #define IS_DSI_HSYNC_POLARITY(HSYNC) (((HSYNC) == DSI_HSYNC_ACTIVE_HIGH) || ((HSYNC) == DSI_HSYNC_ACTIVE_LOW)) #define IS_DSI_VIDEO_MODE_TYPE(VideoModeType) (((VideoModeType) == DSI_VID_MODE_NB_PULSES) || \ ((VideoModeType) == DSI_VID_MODE_NB_EVENTS) || \ ((VideoModeType) == DSI_VID_MODE_BURST)) #define IS_DSI_COLOR_MODE(ColorMode) (((ColorMode) == DSI_COLOR_MODE_FULL) || ((ColorMode) == DSI_COLOR_MODE_EIGHT)) #define IS_DSI_SHUT_DOWN(ShutDown) (((ShutDown) == DSI_DISPLAY_ON) || ((ShutDown) == DSI_DISPLAY_OFF)) #define IS_DSI_LP_COMMAND(LPCommand) (((LPCommand) == DSI_LP_COMMAND_DISABLE) || ((LPCommand) == DSI_LP_COMMAND_ENABLE)) #define IS_DSI_LP_HFP(LPHFP) (((LPHFP) == DSI_LP_HFP_DISABLE) || ((LPHFP) == DSI_LP_HFP_ENABLE)) #define IS_DSI_LP_HBP(LPHBP) (((LPHBP) == DSI_LP_HBP_DISABLE) || ((LPHBP) == DSI_LP_HBP_ENABLE)) #define IS_DSI_LP_VACTIVE(LPVActive) (((LPVActive) == DSI_LP_VACT_DISABLE) || ((LPVActive) == DSI_LP_VACT_ENABLE)) #define IS_DSI_LP_VFP(LPVFP) (((LPVFP) == DSI_LP_VFP_DISABLE) || ((LPVFP) == DSI_LP_VFP_ENABLE)) #define IS_DSI_LP_VBP(LPVBP) (((LPVBP) == DSI_LP_VBP_DISABLE) || ((LPVBP) == DSI_LP_VBP_ENABLE)) #define IS_DSI_LP_VSYNC(LPVSYNC) (((LPVSYNC) == DSI_LP_VSYNC_DISABLE) || ((LPVSYNC) == DSI_LP_VSYNC_ENABLE)) #define IS_DSI_FBTAA(FrameBTAAcknowledge) (((FrameBTAAcknowledge) == DSI_FBTAA_DISABLE) || ((FrameBTAAcknowledge) == DSI_FBTAA_ENABLE)) #define IS_DSI_TE_SOURCE(TESource) (((TESource) == DSI_TE_DSILINK) || ((TESource) == DSI_TE_EXTERNAL)) #define IS_DSI_TE_POLARITY(TEPolarity) (((TEPolarity) == DSI_TE_RISING_EDGE) || ((TEPolarity) == DSI_TE_FALLING_EDGE)) #define IS_DSI_AUTOMATIC_REFRESH(AutomaticRefresh) (((AutomaticRefresh) == DSI_AR_DISABLE) || ((AutomaticRefresh) == DSI_AR_ENABLE)) #define IS_DSI_VS_POLARITY(VSPolarity) (((VSPolarity) == DSI_VSYNC_FALLING) || ((VSPolarity) == DSI_VSYNC_RISING)) #define IS_DSI_TE_ACK_REQUEST(TEAcknowledgeRequest) (((TEAcknowledgeRequest) == DSI_TE_ACKNOWLEDGE_DISABLE) || ((TEAcknowledgeRequest) == DSI_TE_ACKNOWLEDGE_ENABLE)) #define IS_DSI_ACK_REQUEST(AcknowledgeRequest) (((AcknowledgeRequest) == DSI_ACKNOWLEDGE_DISABLE) || ((AcknowledgeRequest) == DSI_ACKNOWLEDGE_ENABLE)) #define IS_DSI_LP_GSW0P(LP_GSW0P) (((LP_GSW0P) == DSI_LP_GSW0P_DISABLE) || ((LP_GSW0P) == DSI_LP_GSW0P_ENABLE)) #define IS_DSI_LP_GSW1P(LP_GSW1P) (((LP_GSW1P) == DSI_LP_GSW1P_DISABLE) || ((LP_GSW1P) == DSI_LP_GSW1P_ENABLE)) #define IS_DSI_LP_GSW2P(LP_GSW2P) (((LP_GSW2P) == DSI_LP_GSW2P_DISABLE) || ((LP_GSW2P) == DSI_LP_GSW2P_ENABLE)) #define IS_DSI_LP_GSR0P(LP_GSR0P) (((LP_GSR0P) == DSI_LP_GSR0P_DISABLE) || ((LP_GSR0P) == DSI_LP_GSR0P_ENABLE)) #define IS_DSI_LP_GSR1P(LP_GSR1P) (((LP_GSR1P) == DSI_LP_GSR1P_DISABLE) || ((LP_GSR1P) == DSI_LP_GSR1P_ENABLE)) #define IS_DSI_LP_GSR2P(LP_GSR2P) (((LP_GSR2P) == DSI_LP_GSR2P_DISABLE) || ((LP_GSR2P) == DSI_LP_GSR2P_ENABLE)) #define IS_DSI_LP_GLW(LP_GLW) (((LP_GLW) == DSI_LP_GLW_DISABLE) || ((LP_GLW) == DSI_LP_GLW_ENABLE)) #define IS_DSI_LP_DSW0P(LP_DSW0P) (((LP_DSW0P) == DSI_LP_DSW0P_DISABLE) || ((LP_DSW0P) == DSI_LP_DSW0P_ENABLE)) #define IS_DSI_LP_DSW1P(LP_DSW1P) (((LP_DSW1P) == DSI_LP_DSW1P_DISABLE) || ((LP_DSW1P) == DSI_LP_DSW1P_ENABLE)) #define IS_DSI_LP_DSR0P(LP_DSR0P) (((LP_DSR0P) == DSI_LP_DSR0P_DISABLE) || ((LP_DSR0P) == DSI_LP_DSR0P_ENABLE)) #define IS_DSI_LP_DLW(LP_DLW) (((LP_DLW) == DSI_LP_DLW_DISABLE) || ((LP_DLW) == DSI_LP_DLW_ENABLE)) #define IS_DSI_LP_MRDP(LP_MRDP) (((LP_MRDP) == DSI_LP_MRDP_DISABLE) || ((LP_MRDP) == DSI_LP_MRDP_ENABLE)) #define IS_DSI_SHORT_WRITE_PACKET_TYPE(MODE) (((MODE) == DSI_DCS_SHORT_PKT_WRITE_P0) || \ ((MODE) == DSI_DCS_SHORT_PKT_WRITE_P1) || \ ((MODE) == DSI_GEN_SHORT_PKT_WRITE_P0) || \ ((MODE) == DSI_GEN_SHORT_PKT_WRITE_P1) || \ ((MODE) == DSI_GEN_SHORT_PKT_WRITE_P2)) #define IS_DSI_LONG_WRITE_PACKET_TYPE(MODE) (((MODE) == DSI_DCS_LONG_PKT_WRITE) || \ ((MODE) == DSI_GEN_LONG_PKT_WRITE)) #define IS_DSI_READ_PACKET_TYPE(MODE) (((MODE) == DSI_DCS_SHORT_PKT_READ) || \ ((MODE) == DSI_GEN_SHORT_PKT_READ_P0) || \ ((MODE) == DSI_GEN_SHORT_PKT_READ_P1) || \ ((MODE) == DSI_GEN_SHORT_PKT_READ_P2)) #define IS_DSI_COMMUNICATION_DELAY(CommDelay) (((CommDelay) == DSI_SLEW_RATE_HSTX) || ((CommDelay) == DSI_SLEW_RATE_LPTX) || ((CommDelay) == DSI_HS_DELAY)) #define IS_DSI_LANE_GROUP(Lane) (((Lane) == DSI_CLOCK_LANE) || ((Lane) == DSI_DATA_LANES)) #define IS_DSI_CUSTOM_LANE(CustomLane) (((CustomLane) == DSI_SWAP_LANE_PINS) || ((CustomLane) == DSI_INVERT_HS_SIGNAL)) #define IS_DSI_LANE(Lane) (((Lane) == DSI_CLOCK_LANE) || ((Lane) == DSI_DATA_LANE0) || ((Lane) == DSI_DATA_LANE1)) #define IS_DSI_PHY_TIMING(Timing) (((Timing) == DSI_TCLK_POST ) || \ ((Timing) == DSI_TLPX_CLK ) || \ ((Timing) == DSI_THS_EXIT ) || \ ((Timing) == DSI_TLPX_DATA ) || \ ((Timing) == DSI_THS_ZERO ) || \ ((Timing) == DSI_THS_TRAIL ) || \ ((Timing) == DSI_THS_PREPARE ) || \ ((Timing) == DSI_TCLK_ZERO ) || \ ((Timing) == DSI_TCLK_PREPARE)) /** * @} */ /* Private functions prototypes ----------------------------------------------*/ /** @defgroup DSI_Private_Functions_Prototypes DSI Private Functions Prototypes * @{ */ /** * @} */ /* Private functions ---------------------------------------------------------*/ /** @defgroup DSI_Private_Functions DSI Private Functions * @{ */ /** * @} */ /** * @} */ /** * @} */ #endif /* STM32F469xx || STM32F479xx */ #ifdef __cplusplus } #endif #endif /* __STM32F4xx_HAL_DSI_H */ /************************ (C) COPYRIGHT STMicroelectronics *****END OF FILE****/ ================================================ FILE: Zelig/mbed/TARGET_NUCLEO_F411RE/stm32f4xx_hal_eth.h ================================================ /** ****************************************************************************** * @file stm32f4xx_hal_eth.h * @author MCD Application Team * @version V1.4.1 * @date 09-October-2015 * @brief Header file of ETH HAL module. ****************************************************************************** * @attention * *

© COPYRIGHT(c) 2015 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. * ****************************************************************************** */ /* Define to prevent recursive inclusion -------------------------------------*/ #ifndef __STM32F4xx_HAL_ETH_H #define __STM32F4xx_HAL_ETH_H #ifdef __cplusplus extern "C" { #endif #if defined(STM32F407xx) || defined(STM32F417xx) || defined(STM32F427xx) || defined(STM32F437xx) ||\ defined(STM32F429xx) || defined(STM32F439xx) || defined(STM32F469xx) || defined(STM32F479xx) /* Includes ------------------------------------------------------------------*/ #include "stm32f4xx_hal_def.h" /** @addtogroup STM32F4xx_HAL_Driver * @{ */ /** @addtogroup ETH * @{ */ /** @addtogroup ETH_Private_Macros * @{ */ #define IS_ETH_PHY_ADDRESS(ADDRESS) ((ADDRESS) <= 0x20) #define IS_ETH_AUTONEGOTIATION(CMD) (((CMD) == ETH_AUTONEGOTIATION_ENABLE) || \ ((CMD) == ETH_AUTONEGOTIATION_DISABLE)) #define IS_ETH_SPEED(SPEED) (((SPEED) == ETH_SPEED_10M) || \ ((SPEED) == ETH_SPEED_100M)) #define IS_ETH_DUPLEX_MODE(MODE) (((MODE) == ETH_MODE_FULLDUPLEX) || \ ((MODE) == ETH_MODE_HALFDUPLEX)) #define IS_ETH_RX_MODE(MODE) (((MODE) == ETH_RXPOLLING_MODE) || \ ((MODE) == ETH_RXINTERRUPT_MODE)) #define IS_ETH_CHECKSUM_MODE(MODE) (((MODE) == ETH_CHECKSUM_BY_HARDWARE) || \ ((MODE) == ETH_CHECKSUM_BY_SOFTWARE)) #define IS_ETH_MEDIA_INTERFACE(MODE) (((MODE) == ETH_MEDIA_INTERFACE_MII) || \ ((MODE) == ETH_MEDIA_INTERFACE_RMII)) #define IS_ETH_WATCHDOG(CMD) (((CMD) == ETH_WATCHDOG_ENABLE) || \ ((CMD) == ETH_WATCHDOG_DISABLE)) #define IS_ETH_JABBER(CMD) (((CMD) == ETH_JABBER_ENABLE) || \ ((CMD) == ETH_JABBER_DISABLE)) #define IS_ETH_INTER_FRAME_GAP(GAP) (((GAP) == ETH_INTERFRAMEGAP_96BIT) || \ ((GAP) == ETH_INTERFRAMEGAP_88BIT) || \ ((GAP) == ETH_INTERFRAMEGAP_80BIT) || \ ((GAP) == ETH_INTERFRAMEGAP_72BIT) || \ ((GAP) == ETH_INTERFRAMEGAP_64BIT) || \ ((GAP) == ETH_INTERFRAMEGAP_56BIT) || \ ((GAP) == ETH_INTERFRAMEGAP_48BIT) || \ ((GAP) == ETH_INTERFRAMEGAP_40BIT)) #define IS_ETH_CARRIER_SENSE(CMD) (((CMD) == ETH_CARRIERSENCE_ENABLE) || \ ((CMD) == ETH_CARRIERSENCE_DISABLE)) #define IS_ETH_RECEIVE_OWN(CMD) (((CMD) == ETH_RECEIVEOWN_ENABLE) || \ ((CMD) == ETH_RECEIVEOWN_DISABLE)) #define IS_ETH_LOOPBACK_MODE(CMD) (((CMD) == ETH_LOOPBACKMODE_ENABLE) || \ ((CMD) == ETH_LOOPBACKMODE_DISABLE)) #define IS_ETH_CHECKSUM_OFFLOAD(CMD) (((CMD) == ETH_CHECKSUMOFFLAOD_ENABLE) || \ ((CMD) == ETH_CHECKSUMOFFLAOD_DISABLE)) #define IS_ETH_RETRY_TRANSMISSION(CMD) (((CMD) == ETH_RETRYTRANSMISSION_ENABLE) || \ ((CMD) == ETH_RETRYTRANSMISSION_DISABLE)) #define IS_ETH_AUTOMATIC_PADCRC_STRIP(CMD) (((CMD) == ETH_AUTOMATICPADCRCSTRIP_ENABLE) || \ ((CMD) == ETH_AUTOMATICPADCRCSTRIP_DISABLE)) #define IS_ETH_BACKOFF_LIMIT(LIMIT) (((LIMIT) == ETH_BACKOFFLIMIT_10) || \ ((LIMIT) == ETH_BACKOFFLIMIT_8) || \ ((LIMIT) == ETH_BACKOFFLIMIT_4) || \ ((LIMIT) == ETH_BACKOFFLIMIT_1)) #define IS_ETH_DEFERRAL_CHECK(CMD) (((CMD) == ETH_DEFFERRALCHECK_ENABLE) || \ ((CMD) == ETH_DEFFERRALCHECK_DISABLE)) #define IS_ETH_RECEIVE_ALL(CMD) (((CMD) == ETH_RECEIVEALL_ENABLE) || \ ((CMD) == ETH_RECEIVEAll_DISABLE)) #define IS_ETH_SOURCE_ADDR_FILTER(CMD) (((CMD) == ETH_SOURCEADDRFILTER_NORMAL_ENABLE) || \ ((CMD) == ETH_SOURCEADDRFILTER_INVERSE_ENABLE) || \ ((CMD) == ETH_SOURCEADDRFILTER_DISABLE)) #define IS_ETH_CONTROL_FRAMES(PASS) (((PASS) == ETH_PASSCONTROLFRAMES_BLOCKALL) || \ ((PASS) == ETH_PASSCONTROLFRAMES_FORWARDALL) || \ ((PASS) == ETH_PASSCONTROLFRAMES_FORWARDPASSEDADDRFILTER)) #define IS_ETH_BROADCAST_FRAMES_RECEPTION(CMD) (((CMD) == ETH_BROADCASTFRAMESRECEPTION_ENABLE) || \ ((CMD) == ETH_BROADCASTFRAMESRECEPTION_DISABLE)) #define IS_ETH_DESTINATION_ADDR_FILTER(FILTER) (((FILTER) == ETH_DESTINATIONADDRFILTER_NORMAL) || \ ((FILTER) == ETH_DESTINATIONADDRFILTER_INVERSE)) #define IS_ETH_PROMISCUOUS_MODE(CMD) (((CMD) == ETH_PROMISCUOUS_MODE_ENABLE) || \ ((CMD) == ETH_PROMISCUOUS_MODE_DISABLE)) #define IS_ETH_MULTICAST_FRAMES_FILTER(FILTER) (((FILTER) == ETH_MULTICASTFRAMESFILTER_PERFECTHASHTABLE) || \ ((FILTER) == ETH_MULTICASTFRAMESFILTER_HASHTABLE) || \ ((FILTER) == ETH_MULTICASTFRAMESFILTER_PERFECT) || \ ((FILTER) == ETH_MULTICASTFRAMESFILTER_NONE)) #define IS_ETH_UNICAST_FRAMES_FILTER(FILTER) (((FILTER) == ETH_UNICASTFRAMESFILTER_PERFECTHASHTABLE) || \ ((FILTER) == ETH_UNICASTFRAMESFILTER_HASHTABLE) || \ ((FILTER) == ETH_UNICASTFRAMESFILTER_PERFECT)) #define IS_ETH_PAUSE_TIME(TIME) ((TIME) <= 0xFFFF) #define IS_ETH_ZEROQUANTA_PAUSE(CMD) (((CMD) == ETH_ZEROQUANTAPAUSE_ENABLE) || \ ((CMD) == ETH_ZEROQUANTAPAUSE_DISABLE)) #define IS_ETH_PAUSE_LOW_THRESHOLD(THRESHOLD) (((THRESHOLD) == ETH_PAUSELOWTHRESHOLD_MINUS4) || \ ((THRESHOLD) == ETH_PAUSELOWTHRESHOLD_MINUS28) || \ ((THRESHOLD) == ETH_PAUSELOWTHRESHOLD_MINUS144) || \ ((THRESHOLD) == ETH_PAUSELOWTHRESHOLD_MINUS256)) #define IS_ETH_UNICAST_PAUSE_FRAME_DETECT(CMD) (((CMD) == ETH_UNICASTPAUSEFRAMEDETECT_ENABLE) || \ ((CMD) == ETH_UNICASTPAUSEFRAMEDETECT_DISABLE)) #define IS_ETH_RECEIVE_FLOWCONTROL(CMD) (((CMD) == ETH_RECEIVEFLOWCONTROL_ENABLE) || \ ((CMD) == ETH_RECEIVEFLOWCONTROL_DISABLE)) #define IS_ETH_TRANSMIT_FLOWCONTROL(CMD) (((CMD) == ETH_TRANSMITFLOWCONTROL_ENABLE) || \ ((CMD) == ETH_TRANSMITFLOWCONTROL_DISABLE)) #define IS_ETH_VLAN_TAG_COMPARISON(COMPARISON) (((COMPARISON) == ETH_VLANTAGCOMPARISON_12BIT) || \ ((COMPARISON) == ETH_VLANTAGCOMPARISON_16BIT)) #define IS_ETH_VLAN_TAG_IDENTIFIER(IDENTIFIER) ((IDENTIFIER) <= 0xFFFF) #define IS_ETH_MAC_ADDRESS0123(ADDRESS) (((ADDRESS) == ETH_MAC_ADDRESS0) || \ ((ADDRESS) == ETH_MAC_ADDRESS1) || \ ((ADDRESS) == ETH_MAC_ADDRESS2) || \ ((ADDRESS) == ETH_MAC_ADDRESS3)) #define IS_ETH_MAC_ADDRESS123(ADDRESS) (((ADDRESS) == ETH_MAC_ADDRESS1) || \ ((ADDRESS) == ETH_MAC_ADDRESS2) || \ ((ADDRESS) == ETH_MAC_ADDRESS3)) #define IS_ETH_MAC_ADDRESS_FILTER(FILTER) (((FILTER) == ETH_MAC_ADDRESSFILTER_SA) || \ ((FILTER) == ETH_MAC_ADDRESSFILTER_DA)) #define IS_ETH_MAC_ADDRESS_MASK(MASK) (((MASK) == ETH_MAC_ADDRESSMASK_BYTE6) || \ ((MASK) == ETH_MAC_ADDRESSMASK_BYTE5) || \ ((MASK) == ETH_MAC_ADDRESSMASK_BYTE4) || \ ((MASK) == ETH_MAC_ADDRESSMASK_BYTE3) || \ ((MASK) == ETH_MAC_ADDRESSMASK_BYTE2) || \ ((MASK) == ETH_MAC_ADDRESSMASK_BYTE1)) #define IS_ETH_DROP_TCPIP_CHECKSUM_FRAME(CMD) (((CMD) == ETH_DROPTCPIPCHECKSUMERRORFRAME_ENABLE) || \ ((CMD) == ETH_DROPTCPIPCHECKSUMERRORFRAME_DISABLE)) #define IS_ETH_RECEIVE_STORE_FORWARD(CMD) (((CMD) == ETH_RECEIVESTOREFORWARD_ENABLE) || \ ((CMD) == ETH_RECEIVESTOREFORWARD_DISABLE)) #define IS_ETH_FLUSH_RECEIVE_FRAME(CMD) (((CMD) == ETH_FLUSHRECEIVEDFRAME_ENABLE) || \ ((CMD) == ETH_FLUSHRECEIVEDFRAME_DISABLE)) #define IS_ETH_TRANSMIT_STORE_FORWARD(CMD) (((CMD) == ETH_TRANSMITSTOREFORWARD_ENABLE) || \ ((CMD) == ETH_TRANSMITSTOREFORWARD_DISABLE)) #define IS_ETH_TRANSMIT_THRESHOLD_CONTROL(THRESHOLD) (((THRESHOLD) == ETH_TRANSMITTHRESHOLDCONTROL_64BYTES) || \ ((THRESHOLD) == ETH_TRANSMITTHRESHOLDCONTROL_128BYTES) || \ ((THRESHOLD) == ETH_TRANSMITTHRESHOLDCONTROL_192BYTES) || \ ((THRESHOLD) == ETH_TRANSMITTHRESHOLDCONTROL_256BYTES) || \ ((THRESHOLD) == ETH_TRANSMITTHRESHOLDCONTROL_40BYTES) || \ ((THRESHOLD) == ETH_TRANSMITTHRESHOLDCONTROL_32BYTES) || \ ((THRESHOLD) == ETH_TRANSMITTHRESHOLDCONTROL_24BYTES) || \ ((THRESHOLD) == ETH_TRANSMITTHRESHOLDCONTROL_16BYTES)) #define IS_ETH_FORWARD_ERROR_FRAMES(CMD) (((CMD) == ETH_FORWARDERRORFRAMES_ENABLE) || \ ((CMD) == ETH_FORWARDERRORFRAMES_DISABLE)) #define IS_ETH_FORWARD_UNDERSIZED_GOOD_FRAMES(CMD) (((CMD) == ETH_FORWARDUNDERSIZEDGOODFRAMES_ENABLE) || \ ((CMD) == ETH_FORWARDUNDERSIZEDGOODFRAMES_DISABLE)) #define IS_ETH_RECEIVE_THRESHOLD_CONTROL(THRESHOLD) (((THRESHOLD) == ETH_RECEIVEDTHRESHOLDCONTROL_64BYTES) || \ ((THRESHOLD) == ETH_RECEIVEDTHRESHOLDCONTROL_32BYTES) || \ ((THRESHOLD) == ETH_RECEIVEDTHRESHOLDCONTROL_96BYTES) || \ ((THRESHOLD) == ETH_RECEIVEDTHRESHOLDCONTROL_128BYTES)) #define IS_ETH_SECOND_FRAME_OPERATE(CMD) (((CMD) == ETH_SECONDFRAMEOPERARTE_ENABLE) || \ ((CMD) == ETH_SECONDFRAMEOPERARTE_DISABLE)) #define IS_ETH_ADDRESS_ALIGNED_BEATS(CMD) (((CMD) == ETH_ADDRESSALIGNEDBEATS_ENABLE) || \ ((CMD) == ETH_ADDRESSALIGNEDBEATS_DISABLE)) #define IS_ETH_FIXED_BURST(CMD) (((CMD) == ETH_FIXEDBURST_ENABLE) || \ ((CMD) == ETH_FIXEDBURST_DISABLE)) #define IS_ETH_RXDMA_BURST_LENGTH(LENGTH) (((LENGTH) == ETH_RXDMABURSTLENGTH_1BEAT) || \ ((LENGTH) == ETH_RXDMABURSTLENGTH_2BEAT) || \ ((LENGTH) == ETH_RXDMABURSTLENGTH_4BEAT) || \ ((LENGTH) == ETH_RXDMABURSTLENGTH_8BEAT) || \ ((LENGTH) == ETH_RXDMABURSTLENGTH_16BEAT) || \ ((LENGTH) == ETH_RXDMABURSTLENGTH_32BEAT) || \ ((LENGTH) == ETH_RXDMABURSTLENGTH_4XPBL_4BEAT) || \ ((LENGTH) == ETH_RXDMABURSTLENGTH_4XPBL_8BEAT) || \ ((LENGTH) == ETH_RXDMABURSTLENGTH_4XPBL_16BEAT) || \ ((LENGTH) == ETH_RXDMABURSTLENGTH_4XPBL_32BEAT) || \ ((LENGTH) == ETH_RXDMABURSTLENGTH_4XPBL_64BEAT) || \ ((LENGTH) == ETH_RXDMABURSTLENGTH_4XPBL_128BEAT)) #define IS_ETH_TXDMA_BURST_LENGTH(LENGTH) (((LENGTH) == ETH_TXDMABURSTLENGTH_1BEAT) || \ ((LENGTH) == ETH_TXDMABURSTLENGTH_2BEAT) || \ ((LENGTH) == ETH_TXDMABURSTLENGTH_4BEAT) || \ ((LENGTH) == ETH_TXDMABURSTLENGTH_8BEAT) || \ ((LENGTH) == ETH_TXDMABURSTLENGTH_16BEAT) || \ ((LENGTH) == ETH_TXDMABURSTLENGTH_32BEAT) || \ ((LENGTH) == ETH_TXDMABURSTLENGTH_4XPBL_4BEAT) || \ ((LENGTH) == ETH_TXDMABURSTLENGTH_4XPBL_8BEAT) || \ ((LENGTH) == ETH_TXDMABURSTLENGTH_4XPBL_16BEAT) || \ ((LENGTH) == ETH_TXDMABURSTLENGTH_4XPBL_32BEAT) || \ ((LENGTH) == ETH_TXDMABURSTLENGTH_4XPBL_64BEAT) || \ ((LENGTH) == ETH_TXDMABURSTLENGTH_4XPBL_128BEAT)) #define IS_ETH_DMA_DESC_SKIP_LENGTH(LENGTH) ((LENGTH) <= 0x1F) #define IS_ETH_DMA_ARBITRATION_ROUNDROBIN_RXTX(RATIO) (((RATIO) == ETH_DMAARBITRATION_ROUNDROBIN_RXTX_1_1) || \ ((RATIO) == ETH_DMAARBITRATION_ROUNDROBIN_RXTX_2_1) || \ ((RATIO) == ETH_DMAARBITRATION_ROUNDROBIN_RXTX_3_1) || \ ((RATIO) == ETH_DMAARBITRATION_ROUNDROBIN_RXTX_4_1) || \ ((RATIO) == ETH_DMAARBITRATION_RXPRIORTX)) #define IS_ETH_DMATXDESC_GET_FLAG(FLAG) (((FLAG) == ETH_DMATXDESC_OWN) || \ ((FLAG) == ETH_DMATXDESC_IC) || \ ((FLAG) == ETH_DMATXDESC_LS) || \ ((FLAG) == ETH_DMATXDESC_FS) || \ ((FLAG) == ETH_DMATXDESC_DC) || \ ((FLAG) == ETH_DMATXDESC_DP) || \ ((FLAG) == ETH_DMATXDESC_TTSE) || \ ((FLAG) == ETH_DMATXDESC_TER) || \ ((FLAG) == ETH_DMATXDESC_TCH) || \ ((FLAG) == ETH_DMATXDESC_TTSS) || \ ((FLAG) == ETH_DMATXDESC_IHE) || \ ((FLAG) == ETH_DMATXDESC_ES) || \ ((FLAG) == ETH_DMATXDESC_JT) || \ ((FLAG) == ETH_DMATXDESC_FF) || \ ((FLAG) == ETH_DMATXDESC_PCE) || \ ((FLAG) == ETH_DMATXDESC_LCA) || \ ((FLAG) == ETH_DMATXDESC_NC) || \ ((FLAG) == ETH_DMATXDESC_LCO) || \ ((FLAG) == ETH_DMATXDESC_EC) || \ ((FLAG) == ETH_DMATXDESC_VF) || \ ((FLAG) == ETH_DMATXDESC_CC) || \ ((FLAG) == ETH_DMATXDESC_ED) || \ ((FLAG) == ETH_DMATXDESC_UF) || \ ((FLAG) == ETH_DMATXDESC_DB)) #define IS_ETH_DMA_TXDESC_SEGMENT(SEGMENT) (((SEGMENT) == ETH_DMATXDESC_LASTSEGMENTS) || \ ((SEGMENT) == ETH_DMATXDESC_FIRSTSEGMENT)) #define IS_ETH_DMA_TXDESC_CHECKSUM(CHECKSUM) (((CHECKSUM) == ETH_DMATXDESC_CHECKSUMBYPASS) || \ ((CHECKSUM) == ETH_DMATXDESC_CHECKSUMIPV4HEADER) || \ ((CHECKSUM) == ETH_DMATXDESC_CHECKSUMTCPUDPICMPSEGMENT) || \ ((CHECKSUM) == ETH_DMATXDESC_CHECKSUMTCPUDPICMPFULL)) #define IS_ETH_DMATXDESC_BUFFER_SIZE(SIZE) ((SIZE) <= 0x1FFF) #define IS_ETH_DMARXDESC_GET_FLAG(FLAG) (((FLAG) == ETH_DMARXDESC_OWN) || \ ((FLAG) == ETH_DMARXDESC_AFM) || \ ((FLAG) == ETH_DMARXDESC_ES) || \ ((FLAG) == ETH_DMARXDESC_DE) || \ ((FLAG) == ETH_DMARXDESC_SAF) || \ ((FLAG) == ETH_DMARXDESC_LE) || \ ((FLAG) == ETH_DMARXDESC_OE) || \ ((FLAG) == ETH_DMARXDESC_VLAN) || \ ((FLAG) == ETH_DMARXDESC_FS) || \ ((FLAG) == ETH_DMARXDESC_LS) || \ ((FLAG) == ETH_DMARXDESC_IPV4HCE) || \ ((FLAG) == ETH_DMARXDESC_LC) || \ ((FLAG) == ETH_DMARXDESC_FT) || \ ((FLAG) == ETH_DMARXDESC_RWT) || \ ((FLAG) == ETH_DMARXDESC_RE) || \ ((FLAG) == ETH_DMARXDESC_DBE) || \ ((FLAG) == ETH_DMARXDESC_CE) || \ ((FLAG) == ETH_DMARXDESC_MAMPCE)) #define IS_ETH_DMA_RXDESC_BUFFER(BUFFER) (((BUFFER) == ETH_DMARXDESC_BUFFER1) || \ ((BUFFER) == ETH_DMARXDESC_BUFFER2)) #define IS_ETH_PMT_GET_FLAG(FLAG) (((FLAG) == ETH_PMT_FLAG_WUFR) || \ ((FLAG) == ETH_PMT_FLAG_MPR)) #define IS_ETH_DMA_FLAG(FLAG) ((((FLAG) & (uint32_t)0xC7FE1800) == 0x00) && ((FLAG) != 0x00)) #define IS_ETH_DMA_GET_FLAG(FLAG) (((FLAG) == ETH_DMA_FLAG_TST) || ((FLAG) == ETH_DMA_FLAG_PMT) || \ ((FLAG) == ETH_DMA_FLAG_MMC) || ((FLAG) == ETH_DMA_FLAG_DATATRANSFERERROR) || \ ((FLAG) == ETH_DMA_FLAG_READWRITEERROR) || ((FLAG) == ETH_DMA_FLAG_ACCESSERROR) || \ ((FLAG) == ETH_DMA_FLAG_NIS) || ((FLAG) == ETH_DMA_FLAG_AIS) || \ ((FLAG) == ETH_DMA_FLAG_ER) || ((FLAG) == ETH_DMA_FLAG_FBE) || \ ((FLAG) == ETH_DMA_FLAG_ET) || ((FLAG) == ETH_DMA_FLAG_RWT) || \ ((FLAG) == ETH_DMA_FLAG_RPS) || ((FLAG) == ETH_DMA_FLAG_RBU) || \ ((FLAG) == ETH_DMA_FLAG_R) || ((FLAG) == ETH_DMA_FLAG_TU) || \ ((FLAG) == ETH_DMA_FLAG_RO) || ((FLAG) == ETH_DMA_FLAG_TJT) || \ ((FLAG) == ETH_DMA_FLAG_TBU) || ((FLAG) == ETH_DMA_FLAG_TPS) || \ ((FLAG) == ETH_DMA_FLAG_T)) #define IS_ETH_MAC_IT(IT) ((((IT) & (uint32_t)0xFFFFFDF1) == 0x00) && ((IT) != 0x00)) #define IS_ETH_MAC_GET_IT(IT) (((IT) == ETH_MAC_IT_TST) || ((IT) == ETH_MAC_IT_MMCT) || \ ((IT) == ETH_MAC_IT_MMCR) || ((IT) == ETH_MAC_IT_MMC) || \ ((IT) == ETH_MAC_IT_PMT)) #define IS_ETH_MAC_GET_FLAG(FLAG) (((FLAG) == ETH_MAC_FLAG_TST) || ((FLAG) == ETH_MAC_FLAG_MMCT) || \ ((FLAG) == ETH_MAC_FLAG_MMCR) || ((FLAG) == ETH_MAC_FLAG_MMC) || \ ((FLAG) == ETH_MAC_FLAG_PMT)) #define IS_ETH_DMA_IT(IT) ((((IT) & (uint32_t)0xC7FE1800) == 0x00) && ((IT) != 0x00)) #define IS_ETH_DMA_GET_IT(IT) (((IT) == ETH_DMA_IT_TST) || ((IT) == ETH_DMA_IT_PMT) || \ ((IT) == ETH_DMA_IT_MMC) || ((IT) == ETH_DMA_IT_NIS) || \ ((IT) == ETH_DMA_IT_AIS) || ((IT) == ETH_DMA_IT_ER) || \ ((IT) == ETH_DMA_IT_FBE) || ((IT) == ETH_DMA_IT_ET) || \ ((IT) == ETH_DMA_IT_RWT) || ((IT) == ETH_DMA_IT_RPS) || \ ((IT) == ETH_DMA_IT_RBU) || ((IT) == ETH_DMA_IT_R) || \ ((IT) == ETH_DMA_IT_TU) || ((IT) == ETH_DMA_IT_RO) || \ ((IT) == ETH_DMA_IT_TJT) || ((IT) == ETH_DMA_IT_TBU) || \ ((IT) == ETH_DMA_IT_TPS) || ((IT) == ETH_DMA_IT_T)) #define IS_ETH_DMA_GET_OVERFLOW(OVERFLOW) (((OVERFLOW) == ETH_DMA_OVERFLOW_RXFIFOCOUNTER) || \ ((OVERFLOW) == ETH_DMA_OVERFLOW_MISSEDFRAMECOUNTER)) #define IS_ETH_MMC_IT(IT) (((((IT) & (uint32_t)0xFFDF3FFF) == 0x00) || (((IT) & (uint32_t)0xEFFDFF9F) == 0x00)) && \ ((IT) != 0x00)) #define IS_ETH_MMC_GET_IT(IT) (((IT) == ETH_MMC_IT_TGF) || ((IT) == ETH_MMC_IT_TGFMSC) || \ ((IT) == ETH_MMC_IT_TGFSC) || ((IT) == ETH_MMC_IT_RGUF) || \ ((IT) == ETH_MMC_IT_RFAE) || ((IT) == ETH_MMC_IT_RFCE)) #define IS_ETH_ENHANCED_DESCRIPTOR_FORMAT(CMD) (((CMD) == ETH_DMAENHANCEDDESCRIPTOR_ENABLE) || \ ((CMD) == ETH_DMAENHANCEDDESCRIPTOR_DISABLE)) /** * @} */ /** @addtogroup ETH_Private_Defines * @{ */ /* Delay to wait when writing to some Ethernet registers */ #define ETH_REG_WRITE_DELAY ((uint32_t)0x00000001) /* ETHERNET Errors */ #define ETH_SUCCESS ((uint32_t)0) #define ETH_ERROR ((uint32_t)1) /* ETHERNET DMA Tx descriptors Collision Count Shift */ #define ETH_DMATXDESC_COLLISION_COUNTSHIFT ((uint32_t)3) /* ETHERNET DMA Tx descriptors Buffer2 Size Shift */ #define ETH_DMATXDESC_BUFFER2_SIZESHIFT ((uint32_t)16) /* ETHERNET DMA Rx descriptors Frame Length Shift */ #define ETH_DMARXDESC_FRAME_LENGTHSHIFT ((uint32_t)16) /* ETHERNET DMA Rx descriptors Buffer2 Size Shift */ #define ETH_DMARXDESC_BUFFER2_SIZESHIFT ((uint32_t)16) /* ETHERNET DMA Rx descriptors Frame length Shift */ #define ETH_DMARXDESC_FRAMELENGTHSHIFT ((uint32_t)16) /* ETHERNET MAC address offsets */ #define ETH_MAC_ADDR_HBASE (uint32_t)(ETH_MAC_BASE + (uint32_t)0x40) /* ETHERNET MAC address high offset */ #define ETH_MAC_ADDR_LBASE (uint32_t)(ETH_MAC_BASE + (uint32_t)0x44) /* ETHERNET MAC address low offset */ /* ETHERNET MACMIIAR register Mask */ #define ETH_MACMIIAR_CR_MASK ((uint32_t)0xFFFFFFE3) /* ETHERNET MACCR register Mask */ #define ETH_MACCR_CLEAR_MASK ((uint32_t)0xFF20810F) /* ETHERNET MACFCR register Mask */ #define ETH_MACFCR_CLEAR_MASK ((uint32_t)0x0000FF41) /* ETHERNET DMAOMR register Mask */ #define ETH_DMAOMR_CLEAR_MASK ((uint32_t)0xF8DE3F23) /* ETHERNET Remote Wake-up frame register length */ #define ETH_WAKEUP_REGISTER_LENGTH 8 /* ETHERNET Missed frames counter Shift */ #define ETH_DMA_RX_OVERFLOW_MISSEDFRAMES_COUNTERSHIFT 17 /** * @} */ /* Exported types ------------------------------------------------------------*/ /** @defgroup ETH_Exported_Types ETH Exported Types * @{ */ /** * @brief HAL State structures definition */ typedef enum { HAL_ETH_STATE_RESET = 0x00, /*!< Peripheral not yet Initialized or disabled */ HAL_ETH_STATE_READY = 0x01, /*!< Peripheral Initialized and ready for use */ HAL_ETH_STATE_BUSY = 0x02, /*!< an internal process is ongoing */ HAL_ETH_STATE_BUSY_TX = 0x12, /*!< Data Transmission process is ongoing */ HAL_ETH_STATE_BUSY_RX = 0x22, /*!< Data Reception process is ongoing */ HAL_ETH_STATE_BUSY_TX_RX = 0x32, /*!< Data Transmission and Reception process is ongoing */ HAL_ETH_STATE_BUSY_WR = 0x42, /*!< Write process is ongoing */ HAL_ETH_STATE_BUSY_RD = 0x82, /*!< Read process is ongoing */ HAL_ETH_STATE_TIMEOUT = 0x03, /*!< Timeout state */ HAL_ETH_STATE_ERROR = 0x04 /*!< Reception process is ongoing */ }HAL_ETH_StateTypeDef; /** * @brief ETH Init Structure definition */ typedef struct { uint32_t AutoNegotiation; /*!< Selects or not the AutoNegotiation mode for the external PHY The AutoNegotiation allows an automatic setting of the Speed (10/100Mbps) and the mode (half/full-duplex). This parameter can be a value of @ref ETH_AutoNegotiation */ uint32_t Speed; /*!< Sets the Ethernet speed: 10/100 Mbps. This parameter can be a value of @ref ETH_Speed */ uint32_t DuplexMode; /*!< Selects the MAC duplex mode: Half-Duplex or Full-Duplex mode This parameter can be a value of @ref ETH_Duplex_Mode */ uint16_t PhyAddress; /*!< Ethernet PHY address. This parameter must be a number between Min_Data = 0 and Max_Data = 32 */ uint8_t *MACAddr; /*!< MAC Address of used Hardware: must be pointer on an array of 6 bytes */ uint32_t RxMode; /*!< Selects the Ethernet Rx mode: Polling mode, Interrupt mode. This parameter can be a value of @ref ETH_Rx_Mode */ uint32_t ChecksumMode; /*!< Selects if the checksum is check by hardware or by software. This parameter can be a value of @ref ETH_Checksum_Mode */ uint32_t MediaInterface ; /*!< Selects the media-independent interface or the reduced media-independent interface. This parameter can be a value of @ref ETH_Media_Interface */ } ETH_InitTypeDef; /** * @brief ETH MAC Configuration Structure definition */ typedef struct { uint32_t Watchdog; /*!< Selects or not the Watchdog timer When enabled, the MAC allows no more then 2048 bytes to be received. When disabled, the MAC can receive up to 16384 bytes. This parameter can be a value of @ref ETH_Watchdog */ uint32_t Jabber; /*!< Selects or not Jabber timer When enabled, the MAC allows no more then 2048 bytes to be sent. When disabled, the MAC can send up to 16384 bytes. This parameter can be a value of @ref ETH_Jabber */ uint32_t InterFrameGap; /*!< Selects the minimum IFG between frames during transmission. This parameter can be a value of @ref ETH_Inter_Frame_Gap */ uint32_t CarrierSense; /*!< Selects or not the Carrier Sense. This parameter can be a value of @ref ETH_Carrier_Sense */ uint32_t ReceiveOwn; /*!< Selects or not the ReceiveOwn, ReceiveOwn allows the reception of frames when the TX_EN signal is asserted in Half-Duplex mode. This parameter can be a value of @ref ETH_Receive_Own */ uint32_t LoopbackMode; /*!< Selects or not the internal MAC MII Loopback mode. This parameter can be a value of @ref ETH_Loop_Back_Mode */ uint32_t ChecksumOffload; /*!< Selects or not the IPv4 checksum checking for received frame payloads' TCP/UDP/ICMP headers. This parameter can be a value of @ref ETH_Checksum_Offload */ uint32_t RetryTransmission; /*!< Selects or not the MAC attempt retries transmission, based on the settings of BL, when a collision occurs (Half-Duplex mode). This parameter can be a value of @ref ETH_Retry_Transmission */ uint32_t AutomaticPadCRCStrip; /*!< Selects or not the Automatic MAC Pad/CRC Stripping. This parameter can be a value of @ref ETH_Automatic_Pad_CRC_Strip */ uint32_t BackOffLimit; /*!< Selects the BackOff limit value. This parameter can be a value of @ref ETH_Back_Off_Limit */ uint32_t DeferralCheck; /*!< Selects or not the deferral check function (Half-Duplex mode). This parameter can be a value of @ref ETH_Deferral_Check */ uint32_t ReceiveAll; /*!< Selects or not all frames reception by the MAC (No filtering). This parameter can be a value of @ref ETH_Receive_All */ uint32_t SourceAddrFilter; /*!< Selects the Source Address Filter mode. This parameter can be a value of @ref ETH_Source_Addr_Filter */ uint32_t PassControlFrames; /*!< Sets the forwarding mode of the control frames (including unicast and multicast PAUSE frames) This parameter can be a value of @ref ETH_Pass_Control_Frames */ uint32_t BroadcastFramesReception; /*!< Selects or not the reception of Broadcast Frames. This parameter can be a value of @ref ETH_Broadcast_Frames_Reception */ uint32_t DestinationAddrFilter; /*!< Sets the destination filter mode for both unicast and multicast frames. This parameter can be a value of @ref ETH_Destination_Addr_Filter */ uint32_t PromiscuousMode; /*!< Selects or not the Promiscuous Mode This parameter can be a value of @ref ETH_Promiscuous_Mode */ uint32_t MulticastFramesFilter; /*!< Selects the Multicast Frames filter mode: None/HashTableFilter/PerfectFilter/PerfectHashTableFilter. This parameter can be a value of @ref ETH_Multicast_Frames_Filter */ uint32_t UnicastFramesFilter; /*!< Selects the Unicast Frames filter mode: HashTableFilter/PerfectFilter/PerfectHashTableFilter. This parameter can be a value of @ref ETH_Unicast_Frames_Filter */ uint32_t HashTableHigh; /*!< This field holds the higher 32 bits of Hash table. This parameter must be a number between Min_Data = 0x0 and Max_Data = 0xFFFFFFFF */ uint32_t HashTableLow; /*!< This field holds the lower 32 bits of Hash table. This parameter must be a number between Min_Data = 0x0 and Max_Data = 0xFFFFFFFF */ uint32_t PauseTime; /*!< This field holds the value to be used in the Pause Time field in the transmit control frame. This parameter must be a number between Min_Data = 0x0 and Max_Data = 0xFFFF */ uint32_t ZeroQuantaPause; /*!< Selects or not the automatic generation of Zero-Quanta Pause Control frames. This parameter can be a value of @ref ETH_Zero_Quanta_Pause */ uint32_t PauseLowThreshold; /*!< This field configures the threshold of the PAUSE to be checked for automatic retransmission of PAUSE Frame. This parameter can be a value of @ref ETH_Pause_Low_Threshold */ uint32_t UnicastPauseFrameDetect; /*!< Selects or not the MAC detection of the Pause frames (with MAC Address0 unicast address and unique multicast address). This parameter can be a value of @ref ETH_Unicast_Pause_Frame_Detect */ uint32_t ReceiveFlowControl; /*!< Enables or disables the MAC to decode the received Pause frame and disable its transmitter for a specified time (Pause Time) This parameter can be a value of @ref ETH_Receive_Flow_Control */ uint32_t TransmitFlowControl; /*!< Enables or disables the MAC to transmit Pause frames (Full-Duplex mode) or the MAC back-pressure operation (Half-Duplex mode) This parameter can be a value of @ref ETH_Transmit_Flow_Control */ uint32_t VLANTagComparison; /*!< Selects the 12-bit VLAN identifier or the complete 16-bit VLAN tag for comparison and filtering. This parameter can be a value of @ref ETH_VLAN_Tag_Comparison */ uint32_t VLANTagIdentifier; /*!< Holds the VLAN tag identifier for receive frames */ } ETH_MACInitTypeDef; /** * @brief ETH DMA Configuration Structure definition */ typedef struct { uint32_t DropTCPIPChecksumErrorFrame; /*!< Selects or not the Dropping of TCP/IP Checksum Error Frames. This parameter can be a value of @ref ETH_Drop_TCP_IP_Checksum_Error_Frame */ uint32_t ReceiveStoreForward; /*!< Enables or disables the Receive store and forward mode. This parameter can be a value of @ref ETH_Receive_Store_Forward */ uint32_t FlushReceivedFrame; /*!< Enables or disables the flushing of received frames. This parameter can be a value of @ref ETH_Flush_Received_Frame */ uint32_t TransmitStoreForward; /*!< Enables or disables Transmit store and forward mode. This parameter can be a value of @ref ETH_Transmit_Store_Forward */ uint32_t TransmitThresholdControl; /*!< Selects or not the Transmit Threshold Control. This parameter can be a value of @ref ETH_Transmit_Threshold_Control */ uint32_t ForwardErrorFrames; /*!< Selects or not the forward to the DMA of erroneous frames. This parameter can be a value of @ref ETH_Forward_Error_Frames */ uint32_t ForwardUndersizedGoodFrames; /*!< Enables or disables the Rx FIFO to forward Undersized frames (frames with no Error and length less than 64 bytes) including pad-bytes and CRC) This parameter can be a value of @ref ETH_Forward_Undersized_Good_Frames */ uint32_t ReceiveThresholdControl; /*!< Selects the threshold level of the Receive FIFO. This parameter can be a value of @ref ETH_Receive_Threshold_Control */ uint32_t SecondFrameOperate; /*!< Selects or not the Operate on second frame mode, which allows the DMA to process a second frame of Transmit data even before obtaining the status for the first frame. This parameter can be a value of @ref ETH_Second_Frame_Operate */ uint32_t AddressAlignedBeats; /*!< Enables or disables the Address Aligned Beats. This parameter can be a value of @ref ETH_Address_Aligned_Beats */ uint32_t FixedBurst; /*!< Enables or disables the AHB Master interface fixed burst transfers. This parameter can be a value of @ref ETH_Fixed_Burst */ uint32_t RxDMABurstLength; /*!< Indicates the maximum number of beats to be transferred in one Rx DMA transaction. This parameter can be a value of @ref ETH_Rx_DMA_Burst_Length */ uint32_t TxDMABurstLength; /*!< Indicates the maximum number of beats to be transferred in one Tx DMA transaction. This parameter can be a value of @ref ETH_Tx_DMA_Burst_Length */ uint32_t EnhancedDescriptorFormat; /*!< Enables the enhanced descriptor format. This parameter can be a value of @ref ETH_DMA_Enhanced_descriptor_format */ uint32_t DescriptorSkipLength; /*!< Specifies the number of word to skip between two unchained descriptors (Ring mode) This parameter must be a number between Min_Data = 0 and Max_Data = 32 */ uint32_t DMAArbitration; /*!< Selects the DMA Tx/Rx arbitration. This parameter can be a value of @ref ETH_DMA_Arbitration */ } ETH_DMAInitTypeDef; /** * @brief ETH DMA Descriptors data structure definition */ typedef struct { __IO uint32_t Status; /*!< Status */ uint32_t ControlBufferSize; /*!< Control and Buffer1, Buffer2 lengths */ uint32_t Buffer1Addr; /*!< Buffer1 address pointer */ uint32_t Buffer2NextDescAddr; /*!< Buffer2 or next descriptor address pointer */ /*!< Enhanced ETHERNET DMA PTP Descriptors */ uint32_t ExtendedStatus; /*!< Extended status for PTP receive descriptor */ uint32_t Reserved1; /*!< Reserved */ uint32_t TimeStampLow; /*!< Time Stamp Low value for transmit and receive */ uint32_t TimeStampHigh; /*!< Time Stamp High value for transmit and receive */ } ETH_DMADescTypeDef; /** * @brief Received Frame Informations structure definition */ typedef struct { ETH_DMADescTypeDef *FSRxDesc; /*!< First Segment Rx Desc */ ETH_DMADescTypeDef *LSRxDesc; /*!< Last Segment Rx Desc */ uint32_t SegCount; /*!< Segment count */ uint32_t length; /*!< Frame length */ uint32_t buffer; /*!< Frame buffer */ } ETH_DMARxFrameInfos; /** * @brief ETH Handle Structure definition */ typedef struct { ETH_TypeDef *Instance; /*!< Register base address */ ETH_InitTypeDef Init; /*!< Ethernet Init Configuration */ uint32_t LinkStatus; /*!< Ethernet link status */ ETH_DMADescTypeDef *RxDesc; /*!< Rx descriptor to Get */ ETH_DMADescTypeDef *TxDesc; /*!< Tx descriptor to Set */ ETH_DMARxFrameInfos RxFrameInfos; /*!< last Rx frame infos */ __IO HAL_ETH_StateTypeDef State; /*!< ETH communication state */ HAL_LockTypeDef Lock; /*!< ETH Lock */ } ETH_HandleTypeDef; /** * @} */ /* Exported constants --------------------------------------------------------*/ /** @defgroup ETH_Exported_Constants ETH Exported Constants * @{ */ /** @defgroup ETH_Buffers_setting ETH Buffers setting * @{ */ #define ETH_MAX_PACKET_SIZE ((uint32_t)1524) /*!< ETH_HEADER + ETH_EXTRA + ETH_VLAN_TAG + ETH_MAX_ETH_PAYLOAD + ETH_CRC */ #define ETH_HEADER ((uint32_t)14) /*!< 6 byte Dest addr, 6 byte Src addr, 2 byte length/type */ #define ETH_CRC ((uint32_t)4) /*!< Ethernet CRC */ #define ETH_EXTRA ((uint32_t)2) /*!< Extra bytes in some cases */ #define ETH_VLAN_TAG ((uint32_t)4) /*!< optional 802.1q VLAN Tag */ #define ETH_MIN_ETH_PAYLOAD ((uint32_t)46) /*!< Minimum Ethernet payload size */ #define ETH_MAX_ETH_PAYLOAD ((uint32_t)1500) /*!< Maximum Ethernet payload size */ #define ETH_JUMBO_FRAME_PAYLOAD ((uint32_t)9000) /*!< Jumbo frame payload size */ /* Ethernet driver receive buffers are organized in a chained linked-list, when an ethernet packet is received, the Rx-DMA will transfer the packet from RxFIFO to the driver receive buffers memory. Depending on the size of the received ethernet packet and the size of each ethernet driver receive buffer, the received packet can take one or more ethernet driver receive buffer. In below are defined the size of one ethernet driver receive buffer ETH_RX_BUF_SIZE and the total count of the driver receive buffers ETH_RXBUFNB. The configured value for ETH_RX_BUF_SIZE and ETH_RXBUFNB are only provided as example, they can be reconfigured in the application layer to fit the application needs */ /* Here we configure each Ethernet driver receive buffer to fit the Max size Ethernet packet */ #ifndef ETH_RX_BUF_SIZE #define ETH_RX_BUF_SIZE ETH_MAX_PACKET_SIZE #endif /* 5 Ethernet driver receive buffers are used (in a chained linked list)*/ #ifndef ETH_RXBUFNB #define ETH_RXBUFNB ((uint32_t)5 /* 5 Rx buffers of size ETH_RX_BUF_SIZE */ #endif /* Ethernet driver transmit buffers are organized in a chained linked-list, when an ethernet packet is transmitted, Tx-DMA will transfer the packet from the driver transmit buffers memory to the TxFIFO. Depending on the size of the Ethernet packet to be transmitted and the size of each ethernet driver transmit buffer, the packet to be transmitted can take one or more ethernet driver transmit buffer. In below are defined the size of one ethernet driver transmit buffer ETH_TX_BUF_SIZE and the total count of the driver transmit buffers ETH_TXBUFNB. The configured value for ETH_TX_BUF_SIZE and ETH_TXBUFNB are only provided as example, they can be reconfigured in the application layer to fit the application needs */ /* Here we configure each Ethernet driver transmit buffer to fit the Max size Ethernet packet */ #ifndef ETH_TX_BUF_SIZE #define ETH_TX_BUF_SIZE ETH_MAX_PACKET_SIZE #endif /* 5 ethernet driver transmit buffers are used (in a chained linked list)*/ #ifndef ETH_TXBUFNB #define ETH_TXBUFNB ((uint32_t)5 /* 5 Tx buffers of size ETH_TX_BUF_SIZE */ #endif /** * @} */ /** @defgroup ETH_DMA_TX_Descriptor ETH DMA TX Descriptor * @{ */ /* DMA Tx Descriptor ----------------------------------------------------------------------------------------------- TDES0 | OWN(31) | CTRL[30:26] | Reserved[25:24] | CTRL[23:20] | Reserved[19:17] | Status[16:0] | ----------------------------------------------------------------------------------------------- TDES1 | Reserved[31:29] | Buffer2 ByteCount[28:16] | Reserved[15:13] | Buffer1 ByteCount[12:0] | ----------------------------------------------------------------------------------------------- TDES2 | Buffer1 Address [31:0] | ----------------------------------------------------------------------------------------------- TDES3 | Buffer2 Address [31:0] / Next Descriptor Address [31:0] | ----------------------------------------------------------------------------------------------- */ /** * @brief Bit definition of TDES0 register: DMA Tx descriptor status register */ #define ETH_DMATXDESC_OWN ((uint32_t)0x80000000) /*!< OWN bit: descriptor is owned by DMA engine */ #define ETH_DMATXDESC_IC ((uint32_t)0x40000000) /*!< Interrupt on Completion */ #define ETH_DMATXDESC_LS ((uint32_t)0x20000000) /*!< Last Segment */ #define ETH_DMATXDESC_FS ((uint32_t)0x10000000) /*!< First Segment */ #define ETH_DMATXDESC_DC ((uint32_t)0x08000000) /*!< Disable CRC */ #define ETH_DMATXDESC_DP ((uint32_t)0x04000000) /*!< Disable Padding */ #define ETH_DMATXDESC_TTSE ((uint32_t)0x02000000) /*!< Transmit Time Stamp Enable */ #define ETH_DMATXDESC_CIC ((uint32_t)0x00C00000) /*!< Checksum Insertion Control: 4 cases */ #define ETH_DMATXDESC_CIC_BYPASS ((uint32_t)0x00000000) /*!< Do Nothing: Checksum Engine is bypassed */ #define ETH_DMATXDESC_CIC_IPV4HEADER ((uint32_t)0x00400000) /*!< IPV4 header Checksum Insertion */ #define ETH_DMATXDESC_CIC_TCPUDPICMP_SEGMENT ((uint32_t)0x00800000) /*!< TCP/UDP/ICMP Checksum Insertion calculated over segment only */ #define ETH_DMATXDESC_CIC_TCPUDPICMP_FULL ((uint32_t)0x00C00000) /*!< TCP/UDP/ICMP Checksum Insertion fully calculated */ #define ETH_DMATXDESC_TER ((uint32_t)0x00200000) /*!< Transmit End of Ring */ #define ETH_DMATXDESC_TCH ((uint32_t)0x00100000) /*!< Second Address Chained */ #define ETH_DMATXDESC_TTSS ((uint32_t)0x00020000) /*!< Tx Time Stamp Status */ #define ETH_DMATXDESC_IHE ((uint32_t)0x00010000) /*!< IP Header Error */ #define ETH_DMATXDESC_ES ((uint32_t)0x00008000) /*!< Error summary: OR of the following bits: UE || ED || EC || LCO || NC || LCA || FF || JT */ #define ETH_DMATXDESC_JT ((uint32_t)0x00004000) /*!< Jabber Timeout */ #define ETH_DMATXDESC_FF ((uint32_t)0x00002000) /*!< Frame Flushed: DMA/MTL flushed the frame due to SW flush */ #define ETH_DMATXDESC_PCE ((uint32_t)0x00001000) /*!< Payload Checksum Error */ #define ETH_DMATXDESC_LCA ((uint32_t)0x00000800) /*!< Loss of Carrier: carrier lost during transmission */ #define ETH_DMATXDESC_NC ((uint32_t)0x00000400) /*!< No Carrier: no carrier signal from the transceiver */ #define ETH_DMATXDESC_LCO ((uint32_t)0x00000200) /*!< Late Collision: transmission aborted due to collision */ #define ETH_DMATXDESC_EC ((uint32_t)0x00000100) /*!< Excessive Collision: transmission aborted after 16 collisions */ #define ETH_DMATXDESC_VF ((uint32_t)0x00000080) /*!< VLAN Frame */ #define ETH_DMATXDESC_CC ((uint32_t)0x00000078) /*!< Collision Count */ #define ETH_DMATXDESC_ED ((uint32_t)0x00000004) /*!< Excessive Deferral */ #define ETH_DMATXDESC_UF ((uint32_t)0x00000002) /*!< Underflow Error: late data arrival from the memory */ #define ETH_DMATXDESC_DB ((uint32_t)0x00000001) /*!< Deferred Bit */ /** * @brief Bit definition of TDES1 register */ #define ETH_DMATXDESC_TBS2 ((uint32_t)0x1FFF0000) /*!< Transmit Buffer2 Size */ #define ETH_DMATXDESC_TBS1 ((uint32_t)0x00001FFF) /*!< Transmit Buffer1 Size */ /** * @brief Bit definition of TDES2 register */ #define ETH_DMATXDESC_B1AP ((uint32_t)0xFFFFFFFF) /*!< Buffer1 Address Pointer */ /** * @brief Bit definition of TDES3 register */ #define ETH_DMATXDESC_B2AP ((uint32_t)0xFFFFFFFF) /*!< Buffer2 Address Pointer */ /*--------------------------------------------------------------------------------------------- TDES6 | Transmit Time Stamp Low [31:0] | ----------------------------------------------------------------------------------------------- TDES7 | Transmit Time Stamp High [31:0] | ----------------------------------------------------------------------------------------------*/ /* Bit definition of TDES6 register */ #define ETH_DMAPTPTXDESC_TTSL ((uint32_t)0xFFFFFFFF) /* Transmit Time Stamp Low */ /* Bit definition of TDES7 register */ #define ETH_DMAPTPTXDESC_TTSH ((uint32_t)0xFFFFFFFF) /* Transmit Time Stamp High */ /** * @} */ /** @defgroup ETH_DMA_RX_Descriptor ETH DMA RX Descriptor * @{ */ /* DMA Rx Descriptor -------------------------------------------------------------------------------------------------------------------- RDES0 | OWN(31) | Status [30:0] | --------------------------------------------------------------------------------------------------------------------- RDES1 | CTRL(31) | Reserved[30:29] | Buffer2 ByteCount[28:16] | CTRL[15:14] | Reserved(13) | Buffer1 ByteCount[12:0] | --------------------------------------------------------------------------------------------------------------------- RDES2 | Buffer1 Address [31:0] | --------------------------------------------------------------------------------------------------------------------- RDES3 | Buffer2 Address [31:0] / Next Descriptor Address [31:0] | --------------------------------------------------------------------------------------------------------------------- */ /** * @brief Bit definition of RDES0 register: DMA Rx descriptor status register */ #define ETH_DMARXDESC_OWN ((uint32_t)0x80000000) /*!< OWN bit: descriptor is owned by DMA engine */ #define ETH_DMARXDESC_AFM ((uint32_t)0x40000000) /*!< DA Filter Fail for the rx frame */ #define ETH_DMARXDESC_FL ((uint32_t)0x3FFF0000) /*!< Receive descriptor frame length */ #define ETH_DMARXDESC_ES ((uint32_t)0x00008000) /*!< Error summary: OR of the following bits: DE || OE || IPC || LC || RWT || RE || CE */ #define ETH_DMARXDESC_DE ((uint32_t)0x00004000) /*!< Descriptor error: no more descriptors for receive frame */ #define ETH_DMARXDESC_SAF ((uint32_t)0x00002000) /*!< SA Filter Fail for the received frame */ #define ETH_DMARXDESC_LE ((uint32_t)0x00001000) /*!< Frame size not matching with length field */ #define ETH_DMARXDESC_OE ((uint32_t)0x00000800) /*!< Overflow Error: Frame was damaged due to buffer overflow */ #define ETH_DMARXDESC_VLAN ((uint32_t)0x00000400) /*!< VLAN Tag: received frame is a VLAN frame */ #define ETH_DMARXDESC_FS ((uint32_t)0x00000200) /*!< First descriptor of the frame */ #define ETH_DMARXDESC_LS ((uint32_t)0x00000100) /*!< Last descriptor of the frame */ #define ETH_DMARXDESC_IPV4HCE ((uint32_t)0x00000080) /*!< IPC Checksum Error: Rx Ipv4 header checksum error */ #define ETH_DMARXDESC_LC ((uint32_t)0x00000040) /*!< Late collision occurred during reception */ #define ETH_DMARXDESC_FT ((uint32_t)0x00000020) /*!< Frame type - Ethernet, otherwise 802.3 */ #define ETH_DMARXDESC_RWT ((uint32_t)0x00000010) /*!< Receive Watchdog Timeout: watchdog timer expired during reception */ #define ETH_DMARXDESC_RE ((uint32_t)0x00000008) /*!< Receive error: error reported by MII interface */ #define ETH_DMARXDESC_DBE ((uint32_t)0x00000004) /*!< Dribble bit error: frame contains non int multiple of 8 bits */ #define ETH_DMARXDESC_CE ((uint32_t)0x00000002) /*!< CRC error */ #define ETH_DMARXDESC_MAMPCE ((uint32_t)0x00000001) /*!< Rx MAC Address/Payload Checksum Error: Rx MAC address matched/ Rx Payload Checksum Error */ /** * @brief Bit definition of RDES1 register */ #define ETH_DMARXDESC_DIC ((uint32_t)0x80000000) /*!< Disable Interrupt on Completion */ #define ETH_DMARXDESC_RBS2 ((uint32_t)0x1FFF0000) /*!< Receive Buffer2 Size */ #define ETH_DMARXDESC_RER ((uint32_t)0x00008000) /*!< Receive End of Ring */ #define ETH_DMARXDESC_RCH ((uint32_t)0x00004000) /*!< Second Address Chained */ #define ETH_DMARXDESC_RBS1 ((uint32_t)0x00001FFF) /*!< Receive Buffer1 Size */ /** * @brief Bit definition of RDES2 register */ #define ETH_DMARXDESC_B1AP ((uint32_t)0xFFFFFFFF) /*!< Buffer1 Address Pointer */ /** * @brief Bit definition of RDES3 register */ #define ETH_DMARXDESC_B2AP ((uint32_t)0xFFFFFFFF) /*!< Buffer2 Address Pointer */ /*--------------------------------------------------------------------------------------------------------------------- RDES4 | Reserved[31:15] | Extended Status [14:0] | --------------------------------------------------------------------------------------------------------------------- RDES5 | Reserved[31:0] | --------------------------------------------------------------------------------------------------------------------- RDES6 | Receive Time Stamp Low [31:0] | --------------------------------------------------------------------------------------------------------------------- RDES7 | Receive Time Stamp High [31:0] | --------------------------------------------------------------------------------------------------------------------*/ /* Bit definition of RDES4 register */ #define ETH_DMAPTPRXDESC_PTPV ((uint32_t)0x00002000) /* PTP Version */ #define ETH_DMAPTPRXDESC_PTPFT ((uint32_t)0x00001000) /* PTP Frame Type */ #define ETH_DMAPTPRXDESC_PTPMT ((uint32_t)0x00000F00) /* PTP Message Type */ #define ETH_DMAPTPRXDESC_PTPMT_SYNC ((uint32_t)0x00000100) /* SYNC message (all clock types) */ #define ETH_DMAPTPRXDESC_PTPMT_FOLLOWUP ((uint32_t)0x00000200) /* FollowUp message (all clock types) */ #define ETH_DMAPTPRXDESC_PTPMT_DELAYREQ ((uint32_t)0x00000300) /* DelayReq message (all clock types) */ #define ETH_DMAPTPRXDESC_PTPMT_DELAYRESP ((uint32_t)0x00000400) /* DelayResp message (all clock types) */ #define ETH_DMAPTPRXDESC_PTPMT_PDELAYREQ_ANNOUNCE ((uint32_t)0x00000500) /* PdelayReq message (peer-to-peer transparent clock) or Announce message (Ordinary or Boundary clock) */ #define ETH_DMAPTPRXDESC_PTPMT_PDELAYRESP_MANAG ((uint32_t)0x00000600) /* PdelayResp message (peer-to-peer transparent clock) or Management message (Ordinary or Boundary clock) */ #define ETH_DMAPTPRXDESC_PTPMT_PDELAYRESPFOLLOWUP_SIGNAL ((uint32_t)0x00000700) /* PdelayRespFollowUp message (peer-to-peer transparent clock) or Signaling message (Ordinary or Boundary clock) */ #define ETH_DMAPTPRXDESC_IPV6PR ((uint32_t)0x00000080) /* IPv6 Packet Received */ #define ETH_DMAPTPRXDESC_IPV4PR ((uint32_t)0x00000040) /* IPv4 Packet Received */ #define ETH_DMAPTPRXDESC_IPCB ((uint32_t)0x00000020) /* IP Checksum Bypassed */ #define ETH_DMAPTPRXDESC_IPPE ((uint32_t)0x00000010) /* IP Payload Error */ #define ETH_DMAPTPRXDESC_IPHE ((uint32_t)0x00000008) /* IP Header Error */ #define ETH_DMAPTPRXDESC_IPPT ((uint32_t)0x00000007) /* IP Payload Type */ #define ETH_DMAPTPRXDESC_IPPT_UDP ((uint32_t)0x00000001) /* UDP payload encapsulated in the IP datagram */ #define ETH_DMAPTPRXDESC_IPPT_TCP ((uint32_t)0x00000002) /* TCP payload encapsulated in the IP datagram */ #define ETH_DMAPTPRXDESC_IPPT_ICMP ((uint32_t)0x00000003) /* ICMP payload encapsulated in the IP datagram */ /* Bit definition of RDES6 register */ #define ETH_DMAPTPRXDESC_RTSL ((uint32_t)0xFFFFFFFF) /* Receive Time Stamp Low */ /* Bit definition of RDES7 register */ #define ETH_DMAPTPRXDESC_RTSH ((uint32_t)0xFFFFFFFF) /* Receive Time Stamp High */ /** * @} */ /** @defgroup ETH_AutoNegotiation ETH AutoNegotiation * @{ */ #define ETH_AUTONEGOTIATION_ENABLE ((uint32_t)0x00000001) #define ETH_AUTONEGOTIATION_DISABLE ((uint32_t)0x00000000) /** * @} */ /** @defgroup ETH_Speed ETH Speed * @{ */ #define ETH_SPEED_10M ((uint32_t)0x00000000) #define ETH_SPEED_100M ((uint32_t)0x00004000) /** * @} */ /** @defgroup ETH_Duplex_Mode ETH Duplex Mode * @{ */ #define ETH_MODE_FULLDUPLEX ((uint32_t)0x00000800) #define ETH_MODE_HALFDUPLEX ((uint32_t)0x00000000) /** * @} */ /** @defgroup ETH_Rx_Mode ETH Rx Mode * @{ */ #define ETH_RXPOLLING_MODE ((uint32_t)0x00000000) #define ETH_RXINTERRUPT_MODE ((uint32_t)0x00000001) /** * @} */ /** @defgroup ETH_Checksum_Mode ETH Checksum Mode * @{ */ #define ETH_CHECKSUM_BY_HARDWARE ((uint32_t)0x00000000) #define ETH_CHECKSUM_BY_SOFTWARE ((uint32_t)0x00000001) /** * @} */ /** @defgroup ETH_Media_Interface ETH Media Interface * @{ */ #define ETH_MEDIA_INTERFACE_MII ((uint32_t)0x00000000) #define ETH_MEDIA_INTERFACE_RMII ((uint32_t)SYSCFG_PMC_MII_RMII_SEL) /** * @} */ /** @defgroup ETH_Watchdog ETH Watchdog * @{ */ #define ETH_WATCHDOG_ENABLE ((uint32_t)0x00000000) #define ETH_WATCHDOG_DISABLE ((uint32_t)0x00800000) /** * @} */ /** @defgroup ETH_Jabber ETH Jabber * @{ */ #define ETH_JABBER_ENABLE ((uint32_t)0x00000000) #define ETH_JABBER_DISABLE ((uint32_t)0x00400000) /** * @} */ /** @defgroup ETH_Inter_Frame_Gap ETH Inter Frame Gap * @{ */ #define ETH_INTERFRAMEGAP_96BIT ((uint32_t)0x00000000) /*!< minimum IFG between frames during transmission is 96Bit */ #define ETH_INTERFRAMEGAP_88BIT ((uint32_t)0x00020000) /*!< minimum IFG between frames during transmission is 88Bit */ #define ETH_INTERFRAMEGAP_80BIT ((uint32_t)0x00040000) /*!< minimum IFG between frames during transmission is 80Bit */ #define ETH_INTERFRAMEGAP_72BIT ((uint32_t)0x00060000) /*!< minimum IFG between frames during transmission is 72Bit */ #define ETH_INTERFRAMEGAP_64BIT ((uint32_t)0x00080000) /*!< minimum IFG between frames during transmission is 64Bit */ #define ETH_INTERFRAMEGAP_56BIT ((uint32_t)0x000A0000) /*!< minimum IFG between frames during transmission is 56Bit */ #define ETH_INTERFRAMEGAP_48BIT ((uint32_t)0x000C0000) /*!< minimum IFG between frames during transmission is 48Bit */ #define ETH_INTERFRAMEGAP_40BIT ((uint32_t)0x000E0000) /*!< minimum IFG between frames during transmission is 40Bit */ /** * @} */ /** @defgroup ETH_Carrier_Sense ETH Carrier Sense * @{ */ #define ETH_CARRIERSENCE_ENABLE ((uint32_t)0x00000000) #define ETH_CARRIERSENCE_DISABLE ((uint32_t)0x00010000) /** * @} */ /** @defgroup ETH_Receive_Own ETH Receive Own * @{ */ #define ETH_RECEIVEOWN_ENABLE ((uint32_t)0x00000000) #define ETH_RECEIVEOWN_DISABLE ((uint32_t)0x00002000) /** * @} */ /** @defgroup ETH_Loop_Back_Mode ETH Loop Back Mode * @{ */ #define ETH_LOOPBACKMODE_ENABLE ((uint32_t)0x00001000) #define ETH_LOOPBACKMODE_DISABLE ((uint32_t)0x00000000) /** * @} */ /** @defgroup ETH_Checksum_Offload ETH Checksum Offload * @{ */ #define ETH_CHECKSUMOFFLAOD_ENABLE ((uint32_t)0x00000400) #define ETH_CHECKSUMOFFLAOD_DISABLE ((uint32_t)0x00000000) /** * @} */ /** @defgroup ETH_Retry_Transmission ETH Retry Transmission * @{ */ #define ETH_RETRYTRANSMISSION_ENABLE ((uint32_t)0x00000000) #define ETH_RETRYTRANSMISSION_DISABLE ((uint32_t)0x00000200) /** * @} */ /** @defgroup ETH_Automatic_Pad_CRC_Strip ETH Automatic Pad CRC Strip * @{ */ #define ETH_AUTOMATICPADCRCSTRIP_ENABLE ((uint32_t)0x00000080) #define ETH_AUTOMATICPADCRCSTRIP_DISABLE ((uint32_t)0x00000000) /** * @} */ /** @defgroup ETH_Back_Off_Limit ETH Back Off Limit * @{ */ #define ETH_BACKOFFLIMIT_10 ((uint32_t)0x00000000) #define ETH_BACKOFFLIMIT_8 ((uint32_t)0x00000020) #define ETH_BACKOFFLIMIT_4 ((uint32_t)0x00000040) #define ETH_BACKOFFLIMIT_1 ((uint32_t)0x00000060) /** * @} */ /** @defgroup ETH_Deferral_Check ETH Deferral Check * @{ */ #define ETH_DEFFERRALCHECK_ENABLE ((uint32_t)0x00000010) #define ETH_DEFFERRALCHECK_DISABLE ((uint32_t)0x00000000) /** * @} */ /** @defgroup ETH_Receive_All ETH Receive All * @{ */ #define ETH_RECEIVEALL_ENABLE ((uint32_t)0x80000000) #define ETH_RECEIVEAll_DISABLE ((uint32_t)0x00000000) /** * @} */ /** @defgroup ETH_Source_Addr_Filter ETH Source Addr Filter * @{ */ #define ETH_SOURCEADDRFILTER_NORMAL_ENABLE ((uint32_t)0x00000200) #define ETH_SOURCEADDRFILTER_INVERSE_ENABLE ((uint32_t)0x00000300) #define ETH_SOURCEADDRFILTER_DISABLE ((uint32_t)0x00000000) /** * @} */ /** @defgroup ETH_Pass_Control_Frames ETH Pass Control Frames * @{ */ #define ETH_PASSCONTROLFRAMES_BLOCKALL ((uint32_t)0x00000040) /*!< MAC filters all control frames from reaching the application */ #define ETH_PASSCONTROLFRAMES_FORWARDALL ((uint32_t)0x00000080) /*!< MAC forwards all control frames to application even if they fail the Address Filter */ #define ETH_PASSCONTROLFRAMES_FORWARDPASSEDADDRFILTER ((uint32_t)0x000000C0) /*!< MAC forwards control frames that pass the Address Filter. */ /** * @} */ /** @defgroup ETH_Broadcast_Frames_Reception ETH Broadcast Frames Reception * @{ */ #define ETH_BROADCASTFRAMESRECEPTION_ENABLE ((uint32_t)0x00000000) #define ETH_BROADCASTFRAMESRECEPTION_DISABLE ((uint32_t)0x00000020) /** * @} */ /** @defgroup ETH_Destination_Addr_Filter ETH Destination Addr Filter * @{ */ #define ETH_DESTINATIONADDRFILTER_NORMAL ((uint32_t)0x00000000) #define ETH_DESTINATIONADDRFILTER_INVERSE ((uint32_t)0x00000008) /** * @} */ /** @defgroup ETH_Promiscuous_Mode ETH Promiscuous Mode * @{ */ #define ETH_PROMISCUOUS_MODE_ENABLE ((uint32_t)0x00000001) #define ETH_PROMISCUOUS_MODE_DISABLE ((uint32_t)0x00000000) /** * @} */ /** @defgroup ETH_Multicast_Frames_Filter ETH Multicast Frames Filter * @{ */ #define ETH_MULTICASTFRAMESFILTER_PERFECTHASHTABLE ((uint32_t)0x00000404) #define ETH_MULTICASTFRAMESFILTER_HASHTABLE ((uint32_t)0x00000004) #define ETH_MULTICASTFRAMESFILTER_PERFECT ((uint32_t)0x00000000) #define ETH_MULTICASTFRAMESFILTER_NONE ((uint32_t)0x00000010) /** * @} */ /** @defgroup ETH_Unicast_Frames_Filter ETH Unicast Frames Filter * @{ */ #define ETH_UNICASTFRAMESFILTER_PERFECTHASHTABLE ((uint32_t)0x00000402) #define ETH_UNICASTFRAMESFILTER_HASHTABLE ((uint32_t)0x00000002) #define ETH_UNICASTFRAMESFILTER_PERFECT ((uint32_t)0x00000000) /** * @} */ /** @defgroup ETH_Zero_Quanta_Pause ETH Zero Quanta Pause * @{ */ #define ETH_ZEROQUANTAPAUSE_ENABLE ((uint32_t)0x00000000) #define ETH_ZEROQUANTAPAUSE_DISABLE ((uint32_t)0x00000080) /** * @} */ /** @defgroup ETH_Pause_Low_Threshold ETH Pause Low Threshold * @{ */ #define ETH_PAUSELOWTHRESHOLD_MINUS4 ((uint32_t)0x00000000) /*!< Pause time minus 4 slot times */ #define ETH_PAUSELOWTHRESHOLD_MINUS28 ((uint32_t)0x00000010) /*!< Pause time minus 28 slot times */ #define ETH_PAUSELOWTHRESHOLD_MINUS144 ((uint32_t)0x00000020) /*!< Pause time minus 144 slot times */ #define ETH_PAUSELOWTHRESHOLD_MINUS256 ((uint32_t)0x00000030) /*!< Pause time minus 256 slot times */ /** * @} */ /** @defgroup ETH_Unicast_Pause_Frame_Detect ETH Unicast Pause Frame Detect * @{ */ #define ETH_UNICASTPAUSEFRAMEDETECT_ENABLE ((uint32_t)0x00000008) #define ETH_UNICASTPAUSEFRAMEDETECT_DISABLE ((uint32_t)0x00000000) /** * @} */ /** @defgroup ETH_Receive_Flow_Control ETH Receive Flow Control * @{ */ #define ETH_RECEIVEFLOWCONTROL_ENABLE ((uint32_t)0x00000004) #define ETH_RECEIVEFLOWCONTROL_DISABLE ((uint32_t)0x00000000) /** * @} */ /** @defgroup ETH_Transmit_Flow_Control ETH Transmit Flow Control * @{ */ #define ETH_TRANSMITFLOWCONTROL_ENABLE ((uint32_t)0x00000002) #define ETH_TRANSMITFLOWCONTROL_DISABLE ((uint32_t)0x00000000) /** * @} */ /** @defgroup ETH_VLAN_Tag_Comparison ETH VLAN Tag Comparison * @{ */ #define ETH_VLANTAGCOMPARISON_12BIT ((uint32_t)0x00010000) #define ETH_VLANTAGCOMPARISON_16BIT ((uint32_t)0x00000000) /** * @} */ /** @defgroup ETH_MAC_addresses ETH MAC addresses * @{ */ #define ETH_MAC_ADDRESS0 ((uint32_t)0x00000000) #define ETH_MAC_ADDRESS1 ((uint32_t)0x00000008) #define ETH_MAC_ADDRESS2 ((uint32_t)0x00000010) #define ETH_MAC_ADDRESS3 ((uint32_t)0x00000018) /** * @} */ /** @defgroup ETH_MAC_addresses_filter_SA_DA ETH MAC addresses filter SA DA * @{ */ #define ETH_MAC_ADDRESSFILTER_SA ((uint32_t)0x00000000) #define ETH_MAC_ADDRESSFILTER_DA ((uint32_t)0x00000008) /** * @} */ /** @defgroup ETH_MAC_addresses_filter_Mask_bytes ETH MAC addresses filter Mask bytes * @{ */ #define ETH_MAC_ADDRESSMASK_BYTE6 ((uint32_t)0x20000000) /*!< Mask MAC Address high reg bits [15:8] */ #define ETH_MAC_ADDRESSMASK_BYTE5 ((uint32_t)0x10000000) /*!< Mask MAC Address high reg bits [7:0] */ #define ETH_MAC_ADDRESSMASK_BYTE4 ((uint32_t)0x08000000) /*!< Mask MAC Address low reg bits [31:24] */ #define ETH_MAC_ADDRESSMASK_BYTE3 ((uint32_t)0x04000000) /*!< Mask MAC Address low reg bits [23:16] */ #define ETH_MAC_ADDRESSMASK_BYTE2 ((uint32_t)0x02000000) /*!< Mask MAC Address low reg bits [15:8] */ #define ETH_MAC_ADDRESSMASK_BYTE1 ((uint32_t)0x01000000) /*!< Mask MAC Address low reg bits [70] */ /** * @} */ /** @defgroup ETH_MAC_Debug_flags ETH MAC Debug flags * @{ */ #define ETH_MAC_TXFIFO_FULL ((uint32_t)0x02000000) /* Tx FIFO full */ #define ETH_MAC_TXFIFONOT_EMPTY ((uint32_t)0x01000000) /* Tx FIFO not empty */ #define ETH_MAC_TXFIFO_WRITE_ACTIVE ((uint32_t)0x00400000) /* Tx FIFO write active */ #define ETH_MAC_TXFIFO_IDLE ((uint32_t)0x00000000) /* Tx FIFO read status: Idle */ #define ETH_MAC_TXFIFO_READ ((uint32_t)0x00100000) /* Tx FIFO read status: Read (transferring data to the MAC transmitter) */ #define ETH_MAC_TXFIFO_WAITING ((uint32_t)0x00200000) /* Tx FIFO read status: Waiting for TxStatus from MAC transmitter */ #define ETH_MAC_TXFIFO_WRITING ((uint32_t)0x00300000) /* Tx FIFO read status: Writing the received TxStatus or flushing the TxFIFO */ #define ETH_MAC_TRANSMISSION_PAUSE ((uint32_t)0x00080000) /* MAC transmitter in pause */ #define ETH_MAC_TRANSMITFRAMECONTROLLER_IDLE ((uint32_t)0x00000000) /* MAC transmit frame controller: Idle */ #define ETH_MAC_TRANSMITFRAMECONTROLLER_WAITING ((uint32_t)0x00020000) /* MAC transmit frame controller: Waiting for Status of previous frame or IFG/backoff period to be over */ #define ETH_MAC_TRANSMITFRAMECONTROLLER_GENRATING_PCF ((uint32_t)0x00040000) /* MAC transmit frame controller: Generating and transmitting a Pause control frame (in full duplex mode) */ #define ETH_MAC_TRANSMITFRAMECONTROLLER_TRANSFERRING ((uint32_t)0x00060000) /* MAC transmit frame controller: Transferring input frame for transmission */ #define ETH_MAC_MII_TRANSMIT_ACTIVE ((uint32_t)0x00010000) /* MAC MII transmit engine active */ #define ETH_MAC_RXFIFO_EMPTY ((uint32_t)0x00000000) /* Rx FIFO fill level: empty */ #define ETH_MAC_RXFIFO_BELOW_THRESHOLD ((uint32_t)0x00000100) /* Rx FIFO fill level: fill-level below flow-control de-activate threshold */ #define ETH_MAC_RXFIFO_ABOVE_THRESHOLD ((uint32_t)0x00000200) /* Rx FIFO fill level: fill-level above flow-control activate threshold */ #define ETH_MAC_RXFIFO_FULL ((uint32_t)0x00000300) /* Rx FIFO fill level: full */ #define ETH_MAC_READCONTROLLER_IDLE ((uint32_t)0x00000000) /* Rx FIFO read controller IDLE state */ #define ETH_MAC_READCONTROLLER_READING_DATA ((uint32_t)0x00000020) /* Rx FIFO read controller Reading frame data */ #define ETH_MAC_READCONTROLLER_READING_STATUS ((uint32_t)0x00000040) /* Rx FIFO read controller Reading frame status (or time-stamp) */ #define ETH_MAC_READCONTROLLER_FLUSHING ((uint32_t)0x00000060) /* Rx FIFO read controller Flushing the frame data and status */ #define ETH_MAC_RXFIFO_WRITE_ACTIVE ((uint32_t)0x00000010) /* Rx FIFO write controller active */ #define ETH_MAC_SMALL_FIFO_NOTACTIVE ((uint32_t)0x00000000) /* MAC small FIFO read / write controllers not active */ #define ETH_MAC_SMALL_FIFO_READ_ACTIVE ((uint32_t)0x00000002) /* MAC small FIFO read controller active */ #define ETH_MAC_SMALL_FIFO_WRITE_ACTIVE ((uint32_t)0x00000004) /* MAC small FIFO write controller active */ #define ETH_MAC_SMALL_FIFO_RW_ACTIVE ((uint32_t)0x00000006) /* MAC small FIFO read / write controllers active */ #define ETH_MAC_MII_RECEIVE_PROTOCOL_ACTIVE ((uint32_t)0x00000001) /* MAC MII receive protocol engine active */ /** * @} */ /** @defgroup ETH_Drop_TCP_IP_Checksum_Error_Frame ETH Drop TCP IP Checksum Error Frame * @{ */ #define ETH_DROPTCPIPCHECKSUMERRORFRAME_ENABLE ((uint32_t)0x00000000) #define ETH_DROPTCPIPCHECKSUMERRORFRAME_DISABLE ((uint32_t)0x04000000) /** * @} */ /** @defgroup ETH_Receive_Store_Forward ETH Receive Store Forward * @{ */ #define ETH_RECEIVESTOREFORWARD_ENABLE ((uint32_t)0x02000000) #define ETH_RECEIVESTOREFORWARD_DISABLE ((uint32_t)0x00000000) /** * @} */ /** @defgroup ETH_Flush_Received_Frame ETH Flush Received Frame * @{ */ #define ETH_FLUSHRECEIVEDFRAME_ENABLE ((uint32_t)0x00000000) #define ETH_FLUSHRECEIVEDFRAME_DISABLE ((uint32_t)0x01000000) /** * @} */ /** @defgroup ETH_Transmit_Store_Forward ETH Transmit Store Forward * @{ */ #define ETH_TRANSMITSTOREFORWARD_ENABLE ((uint32_t)0x00200000) #define ETH_TRANSMITSTOREFORWARD_DISABLE ((uint32_t)0x00000000) /** * @} */ /** @defgroup ETH_Transmit_Threshold_Control ETH Transmit Threshold Control * @{ */ #define ETH_TRANSMITTHRESHOLDCONTROL_64BYTES ((uint32_t)0x00000000) /*!< threshold level of the MTL Transmit FIFO is 64 Bytes */ #define ETH_TRANSMITTHRESHOLDCONTROL_128BYTES ((uint32_t)0x00004000) /*!< threshold level of the MTL Transmit FIFO is 128 Bytes */ #define ETH_TRANSMITTHRESHOLDCONTROL_192BYTES ((uint32_t)0x00008000) /*!< threshold level of the MTL Transmit FIFO is 192 Bytes */ #define ETH_TRANSMITTHRESHOLDCONTROL_256BYTES ((uint32_t)0x0000C000) /*!< threshold level of the MTL Transmit FIFO is 256 Bytes */ #define ETH_TRANSMITTHRESHOLDCONTROL_40BYTES ((uint32_t)0x00010000) /*!< threshold level of the MTL Transmit FIFO is 40 Bytes */ #define ETH_TRANSMITTHRESHOLDCONTROL_32BYTES ((uint32_t)0x00014000) /*!< threshold level of the MTL Transmit FIFO is 32 Bytes */ #define ETH_TRANSMITTHRESHOLDCONTROL_24BYTES ((uint32_t)0x00018000) /*!< threshold level of the MTL Transmit FIFO is 24 Bytes */ #define ETH_TRANSMITTHRESHOLDCONTROL_16BYTES ((uint32_t)0x0001C000) /*!< threshold level of the MTL Transmit FIFO is 16 Bytes */ /** * @} */ /** @defgroup ETH_Forward_Error_Frames ETH Forward Error Frames * @{ */ #define ETH_FORWARDERRORFRAMES_ENABLE ((uint32_t)0x00000080) #define ETH_FORWARDERRORFRAMES_DISABLE ((uint32_t)0x00000000) /** * @} */ /** @defgroup ETH_Forward_Undersized_Good_Frames ETH Forward Undersized Good Frames * @{ */ #define ETH_FORWARDUNDERSIZEDGOODFRAMES_ENABLE ((uint32_t)0x00000040) #define ETH_FORWARDUNDERSIZEDGOODFRAMES_DISABLE ((uint32_t)0x00000000) /** * @} */ /** @defgroup ETH_Receive_Threshold_Control ETH Receive Threshold Control * @{ */ #define ETH_RECEIVEDTHRESHOLDCONTROL_64BYTES ((uint32_t)0x00000000) /*!< threshold level of the MTL Receive FIFO is 64 Bytes */ #define ETH_RECEIVEDTHRESHOLDCONTROL_32BYTES ((uint32_t)0x00000008) /*!< threshold level of the MTL Receive FIFO is 32 Bytes */ #define ETH_RECEIVEDTHRESHOLDCONTROL_96BYTES ((uint32_t)0x00000010) /*!< threshold level of the MTL Receive FIFO is 96 Bytes */ #define ETH_RECEIVEDTHRESHOLDCONTROL_128BYTES ((uint32_t)0x00000018) /*!< threshold level of the MTL Receive FIFO is 128 Bytes */ /** * @} */ /** @defgroup ETH_Second_Frame_Operate ETH Second Frame Operate * @{ */ #define ETH_SECONDFRAMEOPERARTE_ENABLE ((uint32_t)0x00000004) #define ETH_SECONDFRAMEOPERARTE_DISABLE ((uint32_t)0x00000000) /** * @} */ /** @defgroup ETH_Address_Aligned_Beats ETH Address Aligned Beats * @{ */ #define ETH_ADDRESSALIGNEDBEATS_ENABLE ((uint32_t)0x02000000) #define ETH_ADDRESSALIGNEDBEATS_DISABLE ((uint32_t)0x00000000) /** * @} */ /** @defgroup ETH_Fixed_Burst ETH Fixed Burst * @{ */ #define ETH_FIXEDBURST_ENABLE ((uint32_t)0x00010000) #define ETH_FIXEDBURST_DISABLE ((uint32_t)0x00000000) /** * @} */ /** @defgroup ETH_Rx_DMA_Burst_Length ETH Rx DMA Burst Length * @{ */ #define ETH_RXDMABURSTLENGTH_1BEAT ((uint32_t)0x00020000) /*!< maximum number of beats to be transferred in one RxDMA transaction is 1 */ #define ETH_RXDMABURSTLENGTH_2BEAT ((uint32_t)0x00040000) /*!< maximum number of beats to be transferred in one RxDMA transaction is 2 */ #define ETH_RXDMABURSTLENGTH_4BEAT ((uint32_t)0x00080000) /*!< maximum number of beats to be transferred in one RxDMA transaction is 4 */ #define ETH_RXDMABURSTLENGTH_8BEAT ((uint32_t)0x00100000) /*!< maximum number of beats to be transferred in one RxDMA transaction is 8 */ #define ETH_RXDMABURSTLENGTH_16BEAT ((uint32_t)0x00200000) /*!< maximum number of beats to be transferred in one RxDMA transaction is 16 */ #define ETH_RXDMABURSTLENGTH_32BEAT ((uint32_t)0x00400000) /*!< maximum number of beats to be transferred in one RxDMA transaction is 32 */ #define ETH_RXDMABURSTLENGTH_4XPBL_4BEAT ((uint32_t)0x01020000) /*!< maximum number of beats to be transferred in one RxDMA transaction is 4 */ #define ETH_RXDMABURSTLENGTH_4XPBL_8BEAT ((uint32_t)0x01040000) /*!< maximum number of beats to be transferred in one RxDMA transaction is 8 */ #define ETH_RXDMABURSTLENGTH_4XPBL_16BEAT ((uint32_t)0x01080000) /*!< maximum number of beats to be transferred in one RxDMA transaction is 16 */ #define ETH_RXDMABURSTLENGTH_4XPBL_32BEAT ((uint32_t)0x01100000) /*!< maximum number of beats to be transferred in one RxDMA transaction is 32 */ #define ETH_RXDMABURSTLENGTH_4XPBL_64BEAT ((uint32_t)0x01200000) /*!< maximum number of beats to be transferred in one RxDMA transaction is 64 */ #define ETH_RXDMABURSTLENGTH_4XPBL_128BEAT ((uint32_t)0x01400000) /*!< maximum number of beats to be transferred in one RxDMA transaction is 128 */ /** * @} */ /** @defgroup ETH_Tx_DMA_Burst_Length ETH Tx DMA Burst Length * @{ */ #define ETH_TXDMABURSTLENGTH_1BEAT ((uint32_t)0x00000100) /*!< maximum number of beats to be transferred in one TxDMA (or both) transaction is 1 */ #define ETH_TXDMABURSTLENGTH_2BEAT ((uint32_t)0x00000200) /*!< maximum number of beats to be transferred in one TxDMA (or both) transaction is 2 */ #define ETH_TXDMABURSTLENGTH_4BEAT ((uint32_t)0x00000400) /*!< maximum number of beats to be transferred in one TxDMA (or both) transaction is 4 */ #define ETH_TXDMABURSTLENGTH_8BEAT ((uint32_t)0x00000800) /*!< maximum number of beats to be transferred in one TxDMA (or both) transaction is 8 */ #define ETH_TXDMABURSTLENGTH_16BEAT ((uint32_t)0x00001000) /*!< maximum number of beats to be transferred in one TxDMA (or both) transaction is 16 */ #define ETH_TXDMABURSTLENGTH_32BEAT ((uint32_t)0x00002000) /*!< maximum number of beats to be transferred in one TxDMA (or both) transaction is 32 */ #define ETH_TXDMABURSTLENGTH_4XPBL_4BEAT ((uint32_t)0x01000100) /*!< maximum number of beats to be transferred in one TxDMA (or both) transaction is 4 */ #define ETH_TXDMABURSTLENGTH_4XPBL_8BEAT ((uint32_t)0x01000200) /*!< maximum number of beats to be transferred in one TxDMA (or both) transaction is 8 */ #define ETH_TXDMABURSTLENGTH_4XPBL_16BEAT ((uint32_t)0x01000400) /*!< maximum number of beats to be transferred in one TxDMA (or both) transaction is 16 */ #define ETH_TXDMABURSTLENGTH_4XPBL_32BEAT ((uint32_t)0x01000800) /*!< maximum number of beats to be transferred in one TxDMA (or both) transaction is 32 */ #define ETH_TXDMABURSTLENGTH_4XPBL_64BEAT ((uint32_t)0x01001000) /*!< maximum number of beats to be transferred in one TxDMA (or both) transaction is 64 */ #define ETH_TXDMABURSTLENGTH_4XPBL_128BEAT ((uint32_t)0x01002000) /*!< maximum number of beats to be transferred in one TxDMA (or both) transaction is 128 */ /** * @} */ /** @defgroup ETH_DMA_Enhanced_descriptor_format ETH DMA Enhanced descriptor format * @{ */ #define ETH_DMAENHANCEDDESCRIPTOR_ENABLE ((uint32_t)0x00000080) #define ETH_DMAENHANCEDDESCRIPTOR_DISABLE ((uint32_t)0x00000000) /** * @} */ /** @defgroup ETH_DMA_Arbitration ETH DMA Arbitration * @{ */ #define ETH_DMAARBITRATION_ROUNDROBIN_RXTX_1_1 ((uint32_t)0x00000000) #define ETH_DMAARBITRATION_ROUNDROBIN_RXTX_2_1 ((uint32_t)0x00004000) #define ETH_DMAARBITRATION_ROUNDROBIN_RXTX_3_1 ((uint32_t)0x00008000) #define ETH_DMAARBITRATION_ROUNDROBIN_RXTX_4_1 ((uint32_t)0x0000C000) #define ETH_DMAARBITRATION_RXPRIORTX ((uint32_t)0x00000002) /** * @} */ /** @defgroup ETH_DMA_Tx_descriptor_segment ETH DMA Tx descriptor segment * @{ */ #define ETH_DMATXDESC_LASTSEGMENTS ((uint32_t)0x40000000) /*!< Last Segment */ #define ETH_DMATXDESC_FIRSTSEGMENT ((uint32_t)0x20000000) /*!< First Segment */ /** * @} */ /** @defgroup ETH_DMA_Tx_descriptor_Checksum_Insertion_Control ETH DMA Tx descriptor Checksum Insertion Control * @{ */ #define ETH_DMATXDESC_CHECKSUMBYPASS ((uint32_t)0x00000000) /*!< Checksum engine bypass */ #define ETH_DMATXDESC_CHECKSUMIPV4HEADER ((uint32_t)0x00400000) /*!< IPv4 header checksum insertion */ #define ETH_DMATXDESC_CHECKSUMTCPUDPICMPSEGMENT ((uint32_t)0x00800000) /*!< TCP/UDP/ICMP checksum insertion. Pseudo header checksum is assumed to be present */ #define ETH_DMATXDESC_CHECKSUMTCPUDPICMPFULL ((uint32_t)0x00C00000) /*!< TCP/UDP/ICMP checksum fully in hardware including pseudo header */ /** * @} */ /** @defgroup ETH_DMA_Rx_descriptor_buffers ETH DMA Rx descriptor buffers * @{ */ #define ETH_DMARXDESC_BUFFER1 ((uint32_t)0x00000000) /*!< DMA Rx Desc Buffer1 */ #define ETH_DMARXDESC_BUFFER2 ((uint32_t)0x00000001) /*!< DMA Rx Desc Buffer2 */ /** * @} */ /** @defgroup ETH_PMT_Flags ETH PMT Flags * @{ */ #define ETH_PMT_FLAG_WUFFRPR ((uint32_t)0x80000000) /*!< Wake-Up Frame Filter Register Pointer Reset */ #define ETH_PMT_FLAG_WUFR ((uint32_t)0x00000040) /*!< Wake-Up Frame Received */ #define ETH_PMT_FLAG_MPR ((uint32_t)0x00000020) /*!< Magic Packet Received */ /** * @} */ /** @defgroup ETH_MMC_Tx_Interrupts ETH MMC Tx Interrupts * @{ */ #define ETH_MMC_IT_TGF ((uint32_t)0x00200000) /*!< When Tx good frame counter reaches half the maximum value */ #define ETH_MMC_IT_TGFMSC ((uint32_t)0x00008000) /*!< When Tx good multi col counter reaches half the maximum value */ #define ETH_MMC_IT_TGFSC ((uint32_t)0x00004000) /*!< When Tx good single col counter reaches half the maximum value */ /** * @} */ /** @defgroup ETH_MMC_Rx_Interrupts ETH MMC Rx Interrupts * @{ */ #define ETH_MMC_IT_RGUF ((uint32_t)0x10020000) /*!< When Rx good unicast frames counter reaches half the maximum value */ #define ETH_MMC_IT_RFAE ((uint32_t)0x10000040) /*!< When Rx alignment error counter reaches half the maximum value */ #define ETH_MMC_IT_RFCE ((uint32_t)0x10000020) /*!< When Rx crc error counter reaches half the maximum value */ /** * @} */ /** @defgroup ETH_MAC_Flags ETH MAC Flags * @{ */ #define ETH_MAC_FLAG_TST ((uint32_t)0x00000200) /*!< Time stamp trigger flag (on MAC) */ #define ETH_MAC_FLAG_MMCT ((uint32_t)0x00000040) /*!< MMC transmit flag */ #define ETH_MAC_FLAG_MMCR ((uint32_t)0x00000020) /*!< MMC receive flag */ #define ETH_MAC_FLAG_MMC ((uint32_t)0x00000010) /*!< MMC flag (on MAC) */ #define ETH_MAC_FLAG_PMT ((uint32_t)0x00000008) /*!< PMT flag (on MAC) */ /** * @} */ /** @defgroup ETH_DMA_Flags ETH DMA Flags * @{ */ #define ETH_DMA_FLAG_TST ((uint32_t)0x20000000) /*!< Time-stamp trigger interrupt (on DMA) */ #define ETH_DMA_FLAG_PMT ((uint32_t)0x10000000) /*!< PMT interrupt (on DMA) */ #define ETH_DMA_FLAG_MMC ((uint32_t)0x08000000) /*!< MMC interrupt (on DMA) */ #define ETH_DMA_FLAG_DATATRANSFERERROR ((uint32_t)0x00800000) /*!< Error bits 0-Rx DMA, 1-Tx DMA */ #define ETH_DMA_FLAG_READWRITEERROR ((uint32_t)0x01000000) /*!< Error bits 0-write transfer, 1-read transfer */ #define ETH_DMA_FLAG_ACCESSERROR ((uint32_t)0x02000000) /*!< Error bits 0-data buffer, 1-desc. access */ #define ETH_DMA_FLAG_NIS ((uint32_t)0x00010000) /*!< Normal interrupt summary flag */ #define ETH_DMA_FLAG_AIS ((uint32_t)0x00008000) /*!< Abnormal interrupt summary flag */ #define ETH_DMA_FLAG_ER ((uint32_t)0x00004000) /*!< Early receive flag */ #define ETH_DMA_FLAG_FBE ((uint32_t)0x00002000) /*!< Fatal bus error flag */ #define ETH_DMA_FLAG_ET ((uint32_t)0x00000400) /*!< Early transmit flag */ #define ETH_DMA_FLAG_RWT ((uint32_t)0x00000200) /*!< Receive watchdog timeout flag */ #define ETH_DMA_FLAG_RPS ((uint32_t)0x00000100) /*!< Receive process stopped flag */ #define ETH_DMA_FLAG_RBU ((uint32_t)0x00000080) /*!< Receive buffer unavailable flag */ #define ETH_DMA_FLAG_R ((uint32_t)0x00000040) /*!< Receive flag */ #define ETH_DMA_FLAG_TU ((uint32_t)0x00000020) /*!< Underflow flag */ #define ETH_DMA_FLAG_RO ((uint32_t)0x00000010) /*!< Overflow flag */ #define ETH_DMA_FLAG_TJT ((uint32_t)0x00000008) /*!< Transmit jabber timeout flag */ #define ETH_DMA_FLAG_TBU ((uint32_t)0x00000004) /*!< Transmit buffer unavailable flag */ #define ETH_DMA_FLAG_TPS ((uint32_t)0x00000002) /*!< Transmit process stopped flag */ #define ETH_DMA_FLAG_T ((uint32_t)0x00000001) /*!< Transmit flag */ /** * @} */ /** @defgroup ETH_MAC_Interrupts ETH MAC Interrupts * @{ */ #define ETH_MAC_IT_TST ((uint32_t)0x00000200) /*!< Time stamp trigger interrupt (on MAC) */ #define ETH_MAC_IT_MMCT ((uint32_t)0x00000040) /*!< MMC transmit interrupt */ #define ETH_MAC_IT_MMCR ((uint32_t)0x00000020) /*!< MMC receive interrupt */ #define ETH_MAC_IT_MMC ((uint32_t)0x00000010) /*!< MMC interrupt (on MAC) */ #define ETH_MAC_IT_PMT ((uint32_t)0x00000008) /*!< PMT interrupt (on MAC) */ /** * @} */ /** @defgroup ETH_DMA_Interrupts ETH DMA Interrupts * @{ */ #define ETH_DMA_IT_TST ((uint32_t)0x20000000) /*!< Time-stamp trigger interrupt (on DMA) */ #define ETH_DMA_IT_PMT ((uint32_t)0x10000000) /*!< PMT interrupt (on DMA) */ #define ETH_DMA_IT_MMC ((uint32_t)0x08000000) /*!< MMC interrupt (on DMA) */ #define ETH_DMA_IT_NIS ((uint32_t)0x00010000) /*!< Normal interrupt summary */ #define ETH_DMA_IT_AIS ((uint32_t)0x00008000) /*!< Abnormal interrupt summary */ #define ETH_DMA_IT_ER ((uint32_t)0x00004000) /*!< Early receive interrupt */ #define ETH_DMA_IT_FBE ((uint32_t)0x00002000) /*!< Fatal bus error interrupt */ #define ETH_DMA_IT_ET ((uint32_t)0x00000400) /*!< Early transmit interrupt */ #define ETH_DMA_IT_RWT ((uint32_t)0x00000200) /*!< Receive watchdog timeout interrupt */ #define ETH_DMA_IT_RPS ((uint32_t)0x00000100) /*!< Receive process stopped interrupt */ #define ETH_DMA_IT_RBU ((uint32_t)0x00000080) /*!< Receive buffer unavailable interrupt */ #define ETH_DMA_IT_R ((uint32_t)0x00000040) /*!< Receive interrupt */ #define ETH_DMA_IT_TU ((uint32_t)0x00000020) /*!< Underflow interrupt */ #define ETH_DMA_IT_RO ((uint32_t)0x00000010) /*!< Overflow interrupt */ #define ETH_DMA_IT_TJT ((uint32_t)0x00000008) /*!< Transmit jabber timeout interrupt */ #define ETH_DMA_IT_TBU ((uint32_t)0x00000004) /*!< Transmit buffer unavailable interrupt */ #define ETH_DMA_IT_TPS ((uint32_t)0x00000002) /*!< Transmit process stopped interrupt */ #define ETH_DMA_IT_T ((uint32_t)0x00000001) /*!< Transmit interrupt */ /** * @} */ /** @defgroup ETH_DMA_transmit_process_state ETH DMA transmit process state * @{ */ #define ETH_DMA_TRANSMITPROCESS_STOPPED ((uint32_t)0x00000000) /*!< Stopped - Reset or Stop Tx Command issued */ #define ETH_DMA_TRANSMITPROCESS_FETCHING ((uint32_t)0x00100000) /*!< Running - fetching the Tx descriptor */ #define ETH_DMA_TRANSMITPROCESS_WAITING ((uint32_t)0x00200000) /*!< Running - waiting for status */ #define ETH_DMA_TRANSMITPROCESS_READING ((uint32_t)0x00300000) /*!< Running - reading the data from host memory */ #define ETH_DMA_TRANSMITPROCESS_SUSPENDED ((uint32_t)0x00600000) /*!< Suspended - Tx Descriptor unavailable */ #define ETH_DMA_TRANSMITPROCESS_CLOSING ((uint32_t)0x00700000) /*!< Running - closing Rx descriptor */ /** * @} */ /** @defgroup ETH_DMA_receive_process_state ETH DMA receive process state * @{ */ #define ETH_DMA_RECEIVEPROCESS_STOPPED ((uint32_t)0x00000000) /*!< Stopped - Reset or Stop Rx Command issued */ #define ETH_DMA_RECEIVEPROCESS_FETCHING ((uint32_t)0x00020000) /*!< Running - fetching the Rx descriptor */ #define ETH_DMA_RECEIVEPROCESS_WAITING ((uint32_t)0x00060000) /*!< Running - waiting for packet */ #define ETH_DMA_RECEIVEPROCESS_SUSPENDED ((uint32_t)0x00080000) /*!< Suspended - Rx Descriptor unavailable */ #define ETH_DMA_RECEIVEPROCESS_CLOSING ((uint32_t)0x000A0000) /*!< Running - closing descriptor */ #define ETH_DMA_RECEIVEPROCESS_QUEUING ((uint32_t)0x000E0000) /*!< Running - queuing the receive frame into host memory */ /** * @} */ /** @defgroup ETH_DMA_overflow ETH DMA overflow * @{ */ #define ETH_DMA_OVERFLOW_RXFIFOCOUNTER ((uint32_t)0x10000000) /*!< Overflow bit for FIFO overflow counter */ #define ETH_DMA_OVERFLOW_MISSEDFRAMECOUNTER ((uint32_t)0x00010000) /*!< Overflow bit for missed frame counter */ /** * @} */ /** @defgroup ETH_EXTI_LINE_WAKEUP ETH EXTI LINE WAKEUP * @{ */ #define ETH_EXTI_LINE_WAKEUP ((uint32_t)0x00080000) /*!< External interrupt line 19 Connected to the ETH EXTI Line */ /** * @} */ /** * @} */ /* Exported macro ------------------------------------------------------------*/ /** @defgroup ETH_Exported_Macros ETH Exported Macros * @brief macros to handle interrupts and specific clock configurations * @{ */ /** @brief Reset ETH handle state * @param __HANDLE__: specifies the ETH handle. * @retval None */ #define __HAL_ETH_RESET_HANDLE_STATE(__HANDLE__) ((__HANDLE__)->State = HAL_ETH_STATE_RESET) /** * @brief Checks whether the specified ETHERNET DMA Tx Desc flag is set or not. * @param __HANDLE__: ETH Handle * @param __FLAG__: specifies the flag of TDES0 to check. * @retval the ETH_DMATxDescFlag (SET or RESET). */ #define __HAL_ETH_DMATXDESC_GET_FLAG(__HANDLE__, __FLAG__) ((__HANDLE__)->TxDesc->Status & (__FLAG__) == (__FLAG__)) /** * @brief Checks whether the specified ETHERNET DMA Rx Desc flag is set or not. * @param __HANDLE__: ETH Handle * @param __FLAG__: specifies the flag of RDES0 to check. * @retval the ETH_DMATxDescFlag (SET or RESET). */ #define __HAL_ETH_DMARXDESC_GET_FLAG(__HANDLE__, __FLAG__) ((__HANDLE__)->RxDesc->Status & (__FLAG__) == (__FLAG__)) /** * @brief Enables the specified DMA Rx Desc receive interrupt. * @param __HANDLE__: ETH Handle * @retval None */ #define __HAL_ETH_DMARXDESC_ENABLE_IT(__HANDLE__) ((__HANDLE__)->RxDesc->ControlBufferSize &=(~(uint32_t)ETH_DMARXDESC_DIC)) /** * @brief Disables the specified DMA Rx Desc receive interrupt. * @param __HANDLE__: ETH Handle * @retval None */ #define __HAL_ETH_DMARXDESC_DISABLE_IT(__HANDLE__) ((__HANDLE__)->RxDesc->ControlBufferSize |= ETH_DMARXDESC_DIC) /** * @brief Set the specified DMA Rx Desc Own bit. * @param __HANDLE__: ETH Handle * @retval None */ #define __HAL_ETH_DMARXDESC_SET_OWN_BIT(__HANDLE__) ((__HANDLE__)->RxDesc->Status |= ETH_DMARXDESC_OWN) /** * @brief Returns the specified ETHERNET DMA Tx Desc collision count. * @param __HANDLE__: ETH Handle * @retval The Transmit descriptor collision counter value. */ #define __HAL_ETH_DMATXDESC_GET_COLLISION_COUNT(__HANDLE__) (((__HANDLE__)->TxDesc->Status & ETH_DMATXDESC_CC) >> ETH_DMATXDESC_COLLISION_COUNTSHIFT) /** * @brief Set the specified DMA Tx Desc Own bit. * @param __HANDLE__: ETH Handle * @retval None */ #define __HAL_ETH_DMATXDESC_SET_OWN_BIT(__HANDLE__) ((__HANDLE__)->TxDesc->Status |= ETH_DMATXDESC_OWN) /** * @brief Enables the specified DMA Tx Desc Transmit interrupt. * @param __HANDLE__: ETH Handle * @retval None */ #define __HAL_ETH_DMATXDESC_ENABLE_IT(__HANDLE__) ((__HANDLE__)->TxDesc->Status |= ETH_DMATXDESC_IC) /** * @brief Disables the specified DMA Tx Desc Transmit interrupt. * @param __HANDLE__: ETH Handle * @retval None */ #define __HAL_ETH_DMATXDESC_DISABLE_IT(__HANDLE__) ((__HANDLE__)->TxDesc->Status &= ~ETH_DMATXDESC_IC) /** * @brief Selects the specified ETHERNET DMA Tx Desc Checksum Insertion. * @param __HANDLE__: ETH Handle * @param __CHECKSUM__: specifies is the DMA Tx desc checksum insertion. * This parameter can be one of the following values: * @arg ETH_DMATXDESC_CHECKSUMBYPASS : Checksum bypass * @arg ETH_DMATXDESC_CHECKSUMIPV4HEADER : IPv4 header checksum * @arg ETH_DMATXDESC_CHECKSUMTCPUDPICMPSEGMENT : TCP/UDP/ICMP checksum. Pseudo header checksum is assumed to be present * @arg ETH_DMATXDESC_CHECKSUMTCPUDPICMPFULL : TCP/UDP/ICMP checksum fully in hardware including pseudo header * @retval None */ #define __HAL_ETH_DMATXDESC_CHECKSUM_INSERTION(__HANDLE__, __CHECKSUM__) ((__HANDLE__)->TxDesc->Status |= (__CHECKSUM__)) /** * @brief Enables the DMA Tx Desc CRC. * @param __HANDLE__: ETH Handle * @retval None */ #define __HAL_ETH_DMATXDESC_CRC_ENABLE(__HANDLE__) ((__HANDLE__)->TxDesc->Status &= ~ETH_DMATXDESC_DC) /** * @brief Disables the DMA Tx Desc CRC. * @param __HANDLE__: ETH Handle * @retval None */ #define __HAL_ETH_DMATXDESC_CRC_DISABLE(__HANDLE__) ((__HANDLE__)->TxDesc->Status |= ETH_DMATXDESC_DC) /** * @brief Enables the DMA Tx Desc padding for frame shorter than 64 bytes. * @param __HANDLE__: ETH Handle * @retval None */ #define __HAL_ETH_DMATXDESC_SHORT_FRAME_PADDING_ENABLE(__HANDLE__) ((__HANDLE__)->TxDesc->Status &= ~ETH_DMATXDESC_DP) /** * @brief Disables the DMA Tx Desc padding for frame shorter than 64 bytes. * @param __HANDLE__: ETH Handle * @retval None */ #define __HAL_ETH_DMATXDESC_SHORT_FRAME_PADDING_DISABLE(__HANDLE__) ((__HANDLE__)->TxDesc->Status |= ETH_DMATXDESC_DP) /** * @brief Enables the specified ETHERNET MAC interrupts. * @param __HANDLE__ : ETH Handle * @param __INTERRUPT__: specifies the ETHERNET MAC interrupt sources to be * enabled or disabled. * This parameter can be any combination of the following values: * @arg ETH_MAC_IT_TST : Time stamp trigger interrupt * @arg ETH_MAC_IT_PMT : PMT interrupt * @retval None */ #define __HAL_ETH_MAC_ENABLE_IT(__HANDLE__, __INTERRUPT__) ((__HANDLE__)->Instance->MACIMR |= (__INTERRUPT__)) /** * @brief Disables the specified ETHERNET MAC interrupts. * @param __HANDLE__ : ETH Handle * @param __INTERRUPT__: specifies the ETHERNET MAC interrupt sources to be * enabled or disabled. * This parameter can be any combination of the following values: * @arg ETH_MAC_IT_TST : Time stamp trigger interrupt * @arg ETH_MAC_IT_PMT : PMT interrupt * @retval None */ #define __HAL_ETH_MAC_DISABLE_IT(__HANDLE__, __INTERRUPT__) ((__HANDLE__)->Instance->MACIMR &= ~(__INTERRUPT__)) /** * @brief Initiate a Pause Control Frame (Full-duplex only). * @param __HANDLE__: ETH Handle * @retval None */ #define __HAL_ETH_INITIATE_PAUSE_CONTROL_FRAME(__HANDLE__) ((__HANDLE__)->Instance->MACFCR |= ETH_MACFCR_FCBBPA) /** * @brief Checks whether the ETHERNET flow control busy bit is set or not. * @param __HANDLE__: ETH Handle * @retval The new state of flow control busy status bit (SET or RESET). */ #define __HAL_ETH_GET_FLOW_CONTROL_BUSY_STATUS(__HANDLE__) (((__HANDLE__)->Instance->MACFCR & ETH_MACFCR_FCBBPA) == ETH_MACFCR_FCBBPA) /** * @brief Enables the MAC Back Pressure operation activation (Half-duplex only). * @param __HANDLE__: ETH Handle * @retval None */ #define __HAL_ETH_BACK_PRESSURE_ACTIVATION_ENABLE(__HANDLE__) ((__HANDLE__)->Instance->MACFCR |= ETH_MACFCR_FCBBPA) /** * @brief Disables the MAC BackPressure operation activation (Half-duplex only). * @param __HANDLE__: ETH Handle * @retval None */ #define __HAL_ETH_BACK_PRESSURE_ACTIVATION_DISABLE(__HANDLE__) ((__HANDLE__)->Instance->MACFCR &= ~ETH_MACFCR_FCBBPA) /** * @brief Checks whether the specified ETHERNET MAC flag is set or not. * @param __HANDLE__: ETH Handle * @param __FLAG__: specifies the flag to check. * This parameter can be one of the following values: * @arg ETH_MAC_FLAG_TST : Time stamp trigger flag * @arg ETH_MAC_FLAG_MMCT : MMC transmit flag * @arg ETH_MAC_FLAG_MMCR : MMC receive flag * @arg ETH_MAC_FLAG_MMC : MMC flag * @arg ETH_MAC_FLAG_PMT : PMT flag * @retval The state of ETHERNET MAC flag. */ #define __HAL_ETH_MAC_GET_FLAG(__HANDLE__, __FLAG__) (((__HANDLE__)->Instance->MACSR &( __FLAG__)) == ( __FLAG__)) /** * @brief Enables the specified ETHERNET DMA interrupts. * @param __HANDLE__ : ETH Handle * @param __INTERRUPT__: specifies the ETHERNET DMA interrupt sources to be * enabled @ref ETH_DMA_Interrupts * @retval None */ #define __HAL_ETH_DMA_ENABLE_IT(__HANDLE__, __INTERRUPT__) ((__HANDLE__)->Instance->DMAIER |= (__INTERRUPT__)) /** * @brief Disables the specified ETHERNET DMA interrupts. * @param __HANDLE__ : ETH Handle * @param __INTERRUPT__: specifies the ETHERNET DMA interrupt sources to be * disabled. @ref ETH_DMA_Interrupts * @retval None */ #define __HAL_ETH_DMA_DISABLE_IT(__HANDLE__, __INTERRUPT__) ((__HANDLE__)->Instance->DMAIER &= ~(__INTERRUPT__)) /** * @brief Clears the ETHERNET DMA IT pending bit. * @param __HANDLE__ : ETH Handle * @param __INTERRUPT__: specifies the interrupt pending bit to clear. @ref ETH_DMA_Interrupts * @retval None */ #define __HAL_ETH_DMA_CLEAR_IT(__HANDLE__, __INTERRUPT__) ((__HANDLE__)->Instance->DMASR =(__INTERRUPT__)) /** * @brief Checks whether the specified ETHERNET DMA flag is set or not. * @param __HANDLE__: ETH Handle * @param __FLAG__: specifies the flag to check. @ref ETH_DMA_Flags * @retval The new state of ETH_DMA_FLAG (SET or RESET). */ #define __HAL_ETH_DMA_GET_FLAG(__HANDLE__, __FLAG__) (((__HANDLE__)->Instance->DMASR &( __FLAG__)) == ( __FLAG__)) /** * @brief Checks whether the specified ETHERNET DMA flag is set or not. * @param __HANDLE__: ETH Handle * @param __FLAG__: specifies the flag to clear. @ref ETH_DMA_Flags * @retval The new state of ETH_DMA_FLAG (SET or RESET). */ #define __HAL_ETH_DMA_CLEAR_FLAG(__HANDLE__, __FLAG__) ((__HANDLE__)->Instance->DMASR = (__FLAG__)) /** * @brief Checks whether the specified ETHERNET DMA overflow flag is set or not. * @param __HANDLE__: ETH Handle * @param __OVERFLOW__: specifies the DMA overflow flag to check. * This parameter can be one of the following values: * @arg ETH_DMA_OVERFLOW_RXFIFOCOUNTER : Overflow for FIFO Overflows Counter * @arg ETH_DMA_OVERFLOW_MISSEDFRAMECOUNTER : Overflow for Buffer Unavailable Missed Frame Counter * @retval The state of ETHERNET DMA overflow Flag (SET or RESET). */ #define __HAL_ETH_GET_DMA_OVERFLOW_STATUS(__HANDLE__, __OVERFLOW__) (((__HANDLE__)->Instance->DMAMFBOCR & (__OVERFLOW__)) == (__OVERFLOW__)) /** * @brief Set the DMA Receive status watchdog timer register value * @param __HANDLE__: ETH Handle * @param __VALUE__: DMA Receive status watchdog timer register value * @retval None */ #define __HAL_ETH_SET_RECEIVE_WATCHDOG_TIMER(__HANDLE__, __VALUE__) ((__HANDLE__)->Instance->DMARSWTR = (__VALUE__)) /** * @brief Enables any unicast packet filtered by the MAC address * recognition to be a wake-up frame. * @param __HANDLE__: ETH Handle. * @retval None */ #define __HAL_ETH_GLOBAL_UNICAST_WAKEUP_ENABLE(__HANDLE__) ((__HANDLE__)->Instance->MACPMTCSR |= ETH_MACPMTCSR_GU) /** * @brief Disables any unicast packet filtered by the MAC address * recognition to be a wake-up frame. * @param __HANDLE__: ETH Handle. * @retval None */ #define __HAL_ETH_GLOBAL_UNICAST_WAKEUP_DISABLE(__HANDLE__) ((__HANDLE__)->Instance->MACPMTCSR &= ~ETH_MACPMTCSR_GU) /** * @brief Enables the MAC Wake-Up Frame Detection. * @param __HANDLE__: ETH Handle. * @retval None */ #define __HAL_ETH_WAKEUP_FRAME_DETECTION_ENABLE(__HANDLE__) ((__HANDLE__)->Instance->MACPMTCSR |= ETH_MACPMTCSR_WFE) /** * @brief Disables the MAC Wake-Up Frame Detection. * @param __HANDLE__: ETH Handle. * @retval None */ #define __HAL_ETH_WAKEUP_FRAME_DETECTION_DISABLE(__HANDLE__) ((__HANDLE__)->Instance->MACPMTCSR &= ~ETH_MACPMTCSR_WFE) /** * @brief Enables the MAC Magic Packet Detection. * @param __HANDLE__: ETH Handle. * @retval None */ #define __HAL_ETH_MAGIC_PACKET_DETECTION_ENABLE(__HANDLE__) ((__HANDLE__)->Instance->MACPMTCSR |= ETH_MACPMTCSR_MPE) /** * @brief Disables the MAC Magic Packet Detection. * @param __HANDLE__: ETH Handle. * @retval None */ #define __HAL_ETH_MAGIC_PACKET_DETECTION_DISABLE(__HANDLE__) ((__HANDLE__)->Instance->MACPMTCSR &= ~ETH_MACPMTCSR_WFE) /** * @brief Enables the MAC Power Down. * @param __HANDLE__: ETH Handle * @retval None */ #define __HAL_ETH_POWER_DOWN_ENABLE(__HANDLE__) ((__HANDLE__)->Instance->MACPMTCSR |= ETH_MACPMTCSR_PD) /** * @brief Disables the MAC Power Down. * @param __HANDLE__: ETH Handle * @retval None */ #define __HAL_ETH_POWER_DOWN_DISABLE(__HANDLE__) ((__HANDLE__)->Instance->MACPMTCSR &= ~ETH_MACPMTCSR_PD) /** * @brief Checks whether the specified ETHERNET PMT flag is set or not. * @param __HANDLE__: ETH Handle. * @param __FLAG__: specifies the flag to check. * This parameter can be one of the following values: * @arg ETH_PMT_FLAG_WUFFRPR : Wake-Up Frame Filter Register Pointer Reset * @arg ETH_PMT_FLAG_WUFR : Wake-Up Frame Received * @arg ETH_PMT_FLAG_MPR : Magic Packet Received * @retval The new state of ETHERNET PMT Flag (SET or RESET). */ #define __HAL_ETH_GET_PMT_FLAG_STATUS(__HANDLE__, __FLAG__) (((__HANDLE__)->Instance->MACPMTCSR &( __FLAG__)) == ( __FLAG__)) /** * @brief Preset and Initialize the MMC counters to almost-full value: 0xFFFF_FFF0 (full - 16) * @param __HANDLE__: ETH Handle. * @retval None */ #define __HAL_ETH_MMC_COUNTER_FULL_PRESET(__HANDLE__) ((__HANDLE__)->Instance->MMCCR |= (ETH_MMCCR_MCFHP | ETH_MMCCR_MCP)) /** * @brief Preset and Initialize the MMC counters to almost-half value: 0x7FFF_FFF0 (half - 16) * @param __HANDLE__: ETH Handle. * @retval None */ #define __HAL_ETH_MMC_COUNTER_HALF_PRESET(__HANDLE__) do{(__HANDLE__)->Instance->MMCCR &= ~ETH_MMCCR_MCFHP;\ (__HANDLE__)->Instance->MMCCR |= ETH_MMCCR_MCP;} while (0) /** * @brief Enables the MMC Counter Freeze. * @param __HANDLE__: ETH Handle. * @retval None */ #define __HAL_ETH_MMC_COUNTER_FREEZE_ENABLE(__HANDLE__) ((__HANDLE__)->Instance->MMCCR |= ETH_MMCCR_MCF) /** * @brief Disables the MMC Counter Freeze. * @param __HANDLE__: ETH Handle. * @retval None */ #define __HAL_ETH_MMC_COUNTER_FREEZE_DISABLE(__HANDLE__) ((__HANDLE__)->Instance->MMCCR &= ~ETH_MMCCR_MCF) /** * @brief Enables the MMC Reset On Read. * @param __HANDLE__: ETH Handle. * @retval None */ #define __HAL_ETH_ETH_MMC_RESET_ONREAD_ENABLE(__HANDLE__) ((__HANDLE__)->Instance->MMCCR |= ETH_MMCCR_ROR) /** * @brief Disables the MMC Reset On Read. * @param __HANDLE__: ETH Handle. * @retval None */ #define __HAL_ETH_ETH_MMC_RESET_ONREAD_DISABLE(__HANDLE__) ((__HANDLE__)->Instance->MMCCR &= ~ETH_MMCCR_ROR) /** * @brief Enables the MMC Counter Stop Rollover. * @param __HANDLE__: ETH Handle. * @retval None */ #define __HAL_ETH_ETH_MMC_COUNTER_ROLLOVER_ENABLE(__HANDLE__) ((__HANDLE__)->Instance->MMCCR &= ~ETH_MMCCR_CSR) /** * @brief Disables the MMC Counter Stop Rollover. * @param __HANDLE__: ETH Handle. * @retval None */ #define __HAL_ETH_ETH_MMC_COUNTER_ROLLOVER_DISABLE(__HANDLE__) ((__HANDLE__)->Instance->MMCCR |= ETH_MMCCR_CSR) /** * @brief Resets the MMC Counters. * @param __HANDLE__: ETH Handle. * @retval None */ #define __HAL_ETH_MMC_COUNTERS_RESET(__HANDLE__) ((__HANDLE__)->Instance->MMCCR |= ETH_MMCCR_CR) /** * @brief Enables the specified ETHERNET MMC Rx interrupts. * @param __HANDLE__: ETH Handle. * @param __INTERRUPT__: specifies the ETHERNET MMC interrupt sources to be enabled or disabled. * This parameter can be one of the following values: * @arg ETH_MMC_IT_RGUF : When Rx good unicast frames counter reaches half the maximum value * @arg ETH_MMC_IT_RFAE : When Rx alignment error counter reaches half the maximum value * @arg ETH_MMC_IT_RFCE : When Rx crc error counter reaches half the maximum value * @retval None */ #define __HAL_ETH_MMC_RX_IT_ENABLE(__HANDLE__, __INTERRUPT__) (__HANDLE__)->Instance->MMCRIMR &= ~((__INTERRUPT__) & 0xEFFFFFFF) /** * @brief Disables the specified ETHERNET MMC Rx interrupts. * @param __HANDLE__: ETH Handle. * @param __INTERRUPT__: specifies the ETHERNET MMC interrupt sources to be enabled or disabled. * This parameter can be one of the following values: * @arg ETH_MMC_IT_RGUF : When Rx good unicast frames counter reaches half the maximum value * @arg ETH_MMC_IT_RFAE : When Rx alignment error counter reaches half the maximum value * @arg ETH_MMC_IT_RFCE : When Rx crc error counter reaches half the maximum value * @retval None */ #define __HAL_ETH_MMC_RX_IT_DISABLE(__HANDLE__, __INTERRUPT__) (__HANDLE__)->Instance->MMCRIMR |= ((__INTERRUPT__) & 0xEFFFFFFF) /** * @brief Enables the specified ETHERNET MMC Tx interrupts. * @param __HANDLE__: ETH Handle. * @param __INTERRUPT__: specifies the ETHERNET MMC interrupt sources to be enabled or disabled. * This parameter can be one of the following values: * @arg ETH_MMC_IT_TGF : When Tx good frame counter reaches half the maximum value * @arg ETH_MMC_IT_TGFMSC: When Tx good multi col counter reaches half the maximum value * @arg ETH_MMC_IT_TGFSC : When Tx good single col counter reaches half the maximum value * @retval None */ #define __HAL_ETH_MMC_TX_IT_ENABLE(__HANDLE__, __INTERRUPT__) ((__HANDLE__)->Instance->MMCRIMR &= ~ (__INTERRUPT__)) /** * @brief Disables the specified ETHERNET MMC Tx interrupts. * @param __HANDLE__: ETH Handle. * @param __INTERRUPT__: specifies the ETHERNET MMC interrupt sources to be enabled or disabled. * This parameter can be one of the following values: * @arg ETH_MMC_IT_TGF : When Tx good frame counter reaches half the maximum value * @arg ETH_MMC_IT_TGFMSC: When Tx good multi col counter reaches half the maximum value * @arg ETH_MMC_IT_TGFSC : When Tx good single col counter reaches half the maximum value * @retval None */ #define __HAL_ETH_MMC_TX_IT_DISABLE(__HANDLE__, __INTERRUPT__) ((__HANDLE__)->Instance->MMCRIMR |= (__INTERRUPT__)) /** * @brief Enables the ETH External interrupt line. * @retval None */ #define __HAL_ETH_WAKEUP_EXTI_ENABLE_IT() EXTI->IMR |= (ETH_EXTI_LINE_WAKEUP) /** * @brief Disables the ETH External interrupt line. * @retval None */ #define __HAL_ETH_WAKEUP_EXTI_DISABLE_IT() EXTI->IMR &= ~(ETH_EXTI_LINE_WAKEUP) /** * @brief Enable event on ETH External event line. * @retval None. */ #define __HAL_ETH_WAKEUP_EXTI_ENABLE_EVENT() EXTI->EMR |= (ETH_EXTI_LINE_WAKEUP) /** * @brief Disable event on ETH External event line * @retval None. */ #define __HAL_ETH_WAKEUP_EXTI_DISABLE_EVENT() EXTI->EMR &= ~(ETH_EXTI_LINE_WAKEUP) /** * @brief Get flag of the ETH External interrupt line. * @retval None */ #define __HAL_ETH_WAKEUP_EXTI_GET_FLAG() EXTI->PR & (ETH_EXTI_LINE_WAKEUP) /** * @brief Clear flag of the ETH External interrupt line. * @retval None */ #define __HAL_ETH_WAKEUP_EXTI_CLEAR_FLAG() EXTI->PR = (ETH_EXTI_LINE_WAKEUP) /** * @brief Enables rising edge trigger to the ETH External interrupt line. * @retval None */ #define __HAL_ETH_WAKEUP_EXTI_ENABLE_RISING_EDGE_TRIGGER() EXTI->RTSR |= ETH_EXTI_LINE_WAKEUP /** * @brief Disables the rising edge trigger to the ETH External interrupt line. * @retval None */ #define __HAL_ETH_WAKEUP_EXTI_DISABLE_RISING_EDGE_TRIGGER() EXTI->RTSR &= ~(ETH_EXTI_LINE_WAKEUP) /** * @brief Enables falling edge trigger to the ETH External interrupt line. * @retval None */ #define __HAL_ETH_WAKEUP_EXTI_ENABLE_FALLING_EDGE_TRIGGER() EXTI->FTSR |= (ETH_EXTI_LINE_WAKEUP) /** * @brief Disables falling edge trigger to the ETH External interrupt line. * @retval None */ #define __HAL_ETH_WAKEUP_EXTI_DISABLE_FALLING_EDGE_TRIGGER() EXTI->FTSR &= ~(ETH_EXTI_LINE_WAKEUP) /** * @brief Enables rising/falling edge trigger to the ETH External interrupt line. * @retval None */ #define __HAL_ETH_WAKEUP_EXTI_ENABLE_FALLINGRISING_TRIGGER() EXTI->RTSR |= ETH_EXTI_LINE_WAKEUP;\ EXTI->FTSR |= ETH_EXTI_LINE_WAKEUP /** * @brief Disables rising/falling edge trigger to the ETH External interrupt line. * @retval None */ #define __HAL_ETH_WAKEUP_EXTI_DISABLE_FALLINGRISING_TRIGGER() EXTI->RTSR &= ~(ETH_EXTI_LINE_WAKEUP);\ EXTI->FTSR &= ~(ETH_EXTI_LINE_WAKEUP) /** * @brief Generate a Software interrupt on selected EXTI line. * @retval None. */ #define __HAL_ETH_WAKEUP_EXTI_GENERATE_SWIT() EXTI->SWIER|= ETH_EXTI_LINE_WAKEUP /** * @} */ /* Exported functions --------------------------------------------------------*/ /** @addtogroup ETH_Exported_Functions * @{ */ /* Initialization and de-initialization functions ****************************/ /** @addtogroup ETH_Exported_Functions_Group1 * @{ */ HAL_StatusTypeDef HAL_ETH_Init(ETH_HandleTypeDef *heth); HAL_StatusTypeDef HAL_ETH_DeInit(ETH_HandleTypeDef *heth); void HAL_ETH_MspInit(ETH_HandleTypeDef *heth); void HAL_ETH_MspDeInit(ETH_HandleTypeDef *heth); HAL_StatusTypeDef HAL_ETH_DMATxDescListInit(ETH_HandleTypeDef *heth, ETH_DMADescTypeDef *DMATxDescTab, uint8_t* TxBuff, uint32_t TxBuffCount); HAL_StatusTypeDef HAL_ETH_DMARxDescListInit(ETH_HandleTypeDef *heth, ETH_DMADescTypeDef *DMARxDescTab, uint8_t *RxBuff, uint32_t RxBuffCount); /** * @} */ /* IO operation functions ****************************************************/ /** @addtogroup ETH_Exported_Functions_Group2 * @{ */ HAL_StatusTypeDef HAL_ETH_TransmitFrame(ETH_HandleTypeDef *heth, uint32_t FrameLength); HAL_StatusTypeDef HAL_ETH_GetReceivedFrame(ETH_HandleTypeDef *heth); /* Communication with PHY functions*/ HAL_StatusTypeDef HAL_ETH_ReadPHYRegister(ETH_HandleTypeDef *heth, uint16_t PHYReg, uint32_t *RegValue); HAL_StatusTypeDef HAL_ETH_WritePHYRegister(ETH_HandleTypeDef *heth, uint16_t PHYReg, uint32_t RegValue); /* Non-Blocking mode: Interrupt */ HAL_StatusTypeDef HAL_ETH_GetReceivedFrame_IT(ETH_HandleTypeDef *heth); void HAL_ETH_IRQHandler(ETH_HandleTypeDef *heth); /* Callback in non blocking modes (Interrupt) */ void HAL_ETH_TxCpltCallback(ETH_HandleTypeDef *heth); void HAL_ETH_RxCpltCallback(ETH_HandleTypeDef *heth); void HAL_ETH_ErrorCallback(ETH_HandleTypeDef *heth); /** * @} */ /* Peripheral Control functions **********************************************/ /** @addtogroup ETH_Exported_Functions_Group3 * @{ */ HAL_StatusTypeDef HAL_ETH_Start(ETH_HandleTypeDef *heth); HAL_StatusTypeDef HAL_ETH_Stop(ETH_HandleTypeDef *heth); HAL_StatusTypeDef HAL_ETH_ConfigMAC(ETH_HandleTypeDef *heth, ETH_MACInitTypeDef *macconf); HAL_StatusTypeDef HAL_ETH_ConfigDMA(ETH_HandleTypeDef *heth, ETH_DMAInitTypeDef *dmaconf); /** * @} */ /* Peripheral State functions ************************************************/ /** @addtogroup ETH_Exported_Functions_Group4 * @{ */ HAL_ETH_StateTypeDef HAL_ETH_GetState(ETH_HandleTypeDef *heth); /** * @} */ /** * @} */ /** * @} */ /** * @} */ #endif /* STM32F405xx || STM32F415xx || STM32F407xx || STM32F417xx || STM32F427xx ||\ STM32F437xx || STM32F429xx || STM32F439xx || STM32F469xx || STM32F479xx */ #ifdef __cplusplus } #endif #endif /* __STM32F4xx_HAL_ETH_H */ /************************ (C) COPYRIGHT STMicroelectronics *****END OF FILE****/ ================================================ FILE: Zelig/mbed/TARGET_NUCLEO_F411RE/stm32f4xx_hal_flash.h ================================================ /** ****************************************************************************** * @file stm32f4xx_hal_flash.h * @author MCD Application Team * @version V1.4.1 * @date 09-October-2015 * @brief Header file of FLASH HAL module. ****************************************************************************** * @attention * *

© COPYRIGHT(c) 2015 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. * ****************************************************************************** */ /* Define to prevent recursive inclusion -------------------------------------*/ #ifndef __STM32F4xx_HAL_FLASH_H #define __STM32F4xx_HAL_FLASH_H #ifdef __cplusplus extern "C" { #endif /* Includes ------------------------------------------------------------------*/ #include "stm32f4xx_hal_def.h" /** @addtogroup STM32F4xx_HAL_Driver * @{ */ /** @addtogroup FLASH * @{ */ /* Exported types ------------------------------------------------------------*/ /** @defgroup FLASH_Exported_Types FLASH Exported Types * @{ */ /** * @brief FLASH Procedure structure definition */ typedef enum { FLASH_PROC_NONE = 0, FLASH_PROC_SECTERASE, FLASH_PROC_MASSERASE, FLASH_PROC_PROGRAM } FLASH_ProcedureTypeDef; /** * @brief FLASH handle Structure definition */ typedef struct { __IO FLASH_ProcedureTypeDef ProcedureOnGoing; /*Internal variable to indicate which procedure is ongoing or not in IT context*/ __IO uint32_t NbSectorsToErase; /*Internal variable to save the remaining sectors to erase in IT context*/ __IO uint8_t VoltageForErase; /*Internal variable to provide voltage range selected by user in IT context*/ __IO uint32_t Sector; /*Internal variable to define the current sector which is erasing*/ __IO uint32_t Bank; /*Internal variable to save current bank selected during mass erase*/ __IO uint32_t Address; /*Internal variable to save address selected for program*/ HAL_LockTypeDef Lock; /* FLASH locking object */ __IO uint32_t ErrorCode; /* FLASH error code */ }FLASH_ProcessTypeDef; /** * @} */ /* Exported constants --------------------------------------------------------*/ /** @defgroup FLASH_Exported_Constants FLASH Exported Constants * @{ */ /** @defgroup FLASH_Error_Code FLASH Error Code * @brief FLASH Error Code * @{ */ #define HAL_FLASH_ERROR_NONE ((uint32_t)0x00000000) /*!< No error */ #define HAL_FLASH_ERROR_RD ((uint32_t)0x00000001) /*!< Read Protection error */ #define HAL_FLASH_ERROR_PGS ((uint32_t)0x00000002) /*!< Programming Sequence error */ #define HAL_FLASH_ERROR_PGP ((uint32_t)0x00000004) /*!< Programming Parallelism error */ #define HAL_FLASH_ERROR_PGA ((uint32_t)0x00000008) /*!< Programming Alignment error */ #define HAL_FLASH_ERROR_WRP ((uint32_t)0x00000010) /*!< Write protection error */ #define HAL_FLASH_ERROR_OPERATION ((uint32_t)0x00000020) /*!< Operation Error */ /** * @} */ /** @defgroup FLASH_Type_Program FLASH Type Program * @{ */ #define FLASH_TYPEPROGRAM_BYTE ((uint32_t)0x00) /*!< Program byte (8-bit) at a specified address */ #define FLASH_TYPEPROGRAM_HALFWORD ((uint32_t)0x01) /*!< Program a half-word (16-bit) at a specified address */ #define FLASH_TYPEPROGRAM_WORD ((uint32_t)0x02) /*!< Program a word (32-bit) at a specified address */ #define FLASH_TYPEPROGRAM_DOUBLEWORD ((uint32_t)0x03) /*!< Program a double word (64-bit) at a specified address */ /** * @} */ /** @defgroup FLASH_Flag_definition FLASH Flag definition * @brief Flag definition * @{ */ #define FLASH_FLAG_EOP FLASH_SR_EOP /*!< FLASH End of Operation flag */ #define FLASH_FLAG_OPERR FLASH_SR_SOP /*!< FLASH operation Error flag */ #define FLASH_FLAG_WRPERR FLASH_SR_WRPERR /*!< FLASH Write protected error flag */ #define FLASH_FLAG_PGAERR FLASH_SR_PGAERR /*!< FLASH Programming Alignment error flag */ #define FLASH_FLAG_PGPERR FLASH_SR_PGPERR /*!< FLASH Programming Parallelism error flag */ #define FLASH_FLAG_PGSERR FLASH_SR_PGSERR /*!< FLASH Programming Sequence error flag */ #define FLASH_FLAG_RDERR ((uint32_t)0x00000100) /*!< Read Protection error flag (PCROP) */ #define FLASH_FLAG_BSY FLASH_SR_BSY /*!< FLASH Busy flag */ /** * @} */ /** @defgroup FLASH_Interrupt_definition FLASH Interrupt definition * @brief FLASH Interrupt definition * @{ */ #define FLASH_IT_EOP FLASH_CR_EOPIE /*!< End of FLASH Operation Interrupt source */ #define FLASH_IT_ERR ((uint32_t)0x02000000) /*!< Error Interrupt source */ /** * @} */ /** @defgroup FLASH_Program_Parallelism FLASH Program Parallelism * @{ */ #define FLASH_PSIZE_BYTE ((uint32_t)0x00000000) #define FLASH_PSIZE_HALF_WORD ((uint32_t)0x00000100) #define FLASH_PSIZE_WORD ((uint32_t)0x00000200) #define FLASH_PSIZE_DOUBLE_WORD ((uint32_t)0x00000300) #define CR_PSIZE_MASK ((uint32_t)0xFFFFFCFF) /** * @} */ /** @defgroup FLASH_Keys FLASH Keys * @{ */ #define RDP_KEY ((uint16_t)0x00A5) #define FLASH_KEY1 ((uint32_t)0x45670123) #define FLASH_KEY2 ((uint32_t)0xCDEF89AB) #define FLASH_OPT_KEY1 ((uint32_t)0x08192A3B) #define FLASH_OPT_KEY2 ((uint32_t)0x4C5D6E7F) /** * @} */ /** * @} */ /* Exported macro ------------------------------------------------------------*/ /** @defgroup FLASH_Exported_Macros FLASH Exported Macros * @{ */ /** * @brief Set the FLASH Latency. * @param __LATENCY__: FLASH Latency * The value of this parameter depend on device used within the same series * @retval none */ #define __HAL_FLASH_SET_LATENCY(__LATENCY__) (*(__IO uint8_t *)ACR_BYTE0_ADDRESS = (uint8_t)(__LATENCY__)) /** * @brief Get the FLASH Latency. * @retval FLASH Latency * The value of this parameter depend on device used within the same series */ #define __HAL_FLASH_GET_LATENCY() (READ_BIT((FLASH->ACR), FLASH_ACR_LATENCY)) /** * @brief Enable the FLASH prefetch buffer. * @retval none */ #define __HAL_FLASH_PREFETCH_BUFFER_ENABLE() (FLASH->ACR |= FLASH_ACR_PRFTEN) /** * @brief Disable the FLASH prefetch buffer. * @retval none */ #define __HAL_FLASH_PREFETCH_BUFFER_DISABLE() (FLASH->ACR &= (~FLASH_ACR_PRFTEN)) /** * @brief Enable the FLASH instruction cache. * @retval none */ #define __HAL_FLASH_INSTRUCTION_CACHE_ENABLE() (FLASH->ACR |= FLASH_ACR_ICEN) /** * @brief Disable the FLASH instruction cache. * @retval none */ #define __HAL_FLASH_INSTRUCTION_CACHE_DISABLE() (FLASH->ACR &= (~FLASH_ACR_ICEN)) /** * @brief Enable the FLASH data cache. * @retval none */ #define __HAL_FLASH_DATA_CACHE_ENABLE() (FLASH->ACR |= FLASH_ACR_DCEN) /** * @brief Disable the FLASH data cache. * @retval none */ #define __HAL_FLASH_DATA_CACHE_DISABLE() (FLASH->ACR &= (~FLASH_ACR_DCEN)) /** * @brief Resets the FLASH instruction Cache. * @note This function must be used only when the Instruction Cache is disabled. * @retval None */ #define __HAL_FLASH_INSTRUCTION_CACHE_RESET() do {FLASH->ACR |= FLASH_ACR_ICRST; \ FLASH->ACR &= ~FLASH_ACR_ICRST; \ }while(0) /** * @brief Resets the FLASH data Cache. * @note This function must be used only when the data Cache is disabled. * @retval None */ #define __HAL_FLASH_DATA_CACHE_RESET() do {FLASH->ACR |= FLASH_ACR_DCRST; \ FLASH->ACR &= ~FLASH_ACR_DCRST; \ }while(0) /** * @brief Enable the specified FLASH interrupt. * @param __INTERRUPT__ : FLASH interrupt * This parameter can be any combination of the following values: * @arg FLASH_IT_EOP: End of FLASH Operation Interrupt * @arg FLASH_IT_ERR: Error Interrupt * @retval none */ #define __HAL_FLASH_ENABLE_IT(__INTERRUPT__) (FLASH->CR |= (__INTERRUPT__)) /** * @brief Disable the specified FLASH interrupt. * @param __INTERRUPT__ : FLASH interrupt * This parameter can be any combination of the following values: * @arg FLASH_IT_EOP: End of FLASH Operation Interrupt * @arg FLASH_IT_ERR: Error Interrupt * @retval none */ #define __HAL_FLASH_DISABLE_IT(__INTERRUPT__) (FLASH->CR &= ~(uint32_t)(__INTERRUPT__)) /** * @brief Get the specified FLASH flag status. * @param __FLAG__: specifies the FLASH flag to check. * This parameter can be one of the following values: * @arg FLASH_FLAG_EOP : FLASH End of Operation flag * @arg FLASH_FLAG_OPERR : FLASH operation Error flag * @arg FLASH_FLAG_WRPERR: FLASH Write protected error flag * @arg FLASH_FLAG_PGAERR: FLASH Programming Alignment error flag * @arg FLASH_FLAG_PGPERR: FLASH Programming Parallelism error flag * @arg FLASH_FLAG_PGSERR: FLASH Programming Sequence error flag * @arg FLASH_FLAG_RDERR : FLASH Read Protection error flag (PCROP) * @arg FLASH_FLAG_BSY : FLASH Busy flag * @retval The new state of __FLAG__ (SET or RESET). */ #define __HAL_FLASH_GET_FLAG(__FLAG__) ((FLASH->SR & (__FLAG__))) /** * @brief Clear the specified FLASH flag. * @param __FLAG__: specifies the FLASH flags to clear. * This parameter can be any combination of the following values: * @arg FLASH_FLAG_EOP : FLASH End of Operation flag * @arg FLASH_FLAG_OPERR : FLASH operation Error flag * @arg FLASH_FLAG_WRPERR: FLASH Write protected error flag * @arg FLASH_FLAG_PGAERR: FLASH Programming Alignment error flag * @arg FLASH_FLAG_PGPERR: FLASH Programming Parallelism error flag * @arg FLASH_FLAG_PGSERR: FLASH Programming Sequence error flag * @arg FLASH_FLAG_RDERR : FLASH Read Protection error flag (PCROP) * @retval none */ #define __HAL_FLASH_CLEAR_FLAG(__FLAG__) (FLASH->SR = (__FLAG__)) /** * @} */ /* Include FLASH HAL Extension module */ #include "stm32f4xx_hal_flash_ex.h" #include "stm32f4xx_hal_flash_ramfunc.h" /* Exported functions --------------------------------------------------------*/ /** @addtogroup FLASH_Exported_Functions * @{ */ /** @addtogroup FLASH_Exported_Functions_Group1 * @{ */ /* Program operation functions ***********************************************/ HAL_StatusTypeDef HAL_FLASH_Program(uint32_t TypeProgram, uint32_t Address, uint64_t Data); HAL_StatusTypeDef HAL_FLASH_Program_IT(uint32_t TypeProgram, uint32_t Address, uint64_t Data); /* FLASH IRQ handler method */ void HAL_FLASH_IRQHandler(void); /* Callbacks in non blocking modes */ void HAL_FLASH_EndOfOperationCallback(uint32_t ReturnValue); void HAL_FLASH_OperationErrorCallback(uint32_t ReturnValue); /** * @} */ /** @addtogroup FLASH_Exported_Functions_Group2 * @{ */ /* Peripheral Control functions **********************************************/ HAL_StatusTypeDef HAL_FLASH_Unlock(void); HAL_StatusTypeDef HAL_FLASH_Lock(void); HAL_StatusTypeDef HAL_FLASH_OB_Unlock(void); HAL_StatusTypeDef HAL_FLASH_OB_Lock(void); /* Option bytes control */ HAL_StatusTypeDef HAL_FLASH_OB_Launch(void); /** * @} */ /** @addtogroup FLASH_Exported_Functions_Group3 * @{ */ /* Peripheral State functions ************************************************/ uint32_t HAL_FLASH_GetError(void); HAL_StatusTypeDef FLASH_WaitForLastOperation(uint32_t Timeout); /** * @} */ /** * @} */ /* Private types -------------------------------------------------------------*/ /* Private variables ---------------------------------------------------------*/ /** @defgroup FLASH_Private_Variables FLASH Private Variables * @{ */ /** * @} */ /* Private constants ---------------------------------------------------------*/ /** @defgroup FLASH_Private_Constants FLASH Private Constants * @{ */ /** * @brief ACR register byte 0 (Bits[7:0]) base address */ #define ACR_BYTE0_ADDRESS ((uint32_t)0x40023C00) /** * @brief OPTCR register byte 0 (Bits[7:0]) base address */ #define OPTCR_BYTE0_ADDRESS ((uint32_t)0x40023C14) /** * @brief OPTCR register byte 1 (Bits[15:8]) base address */ #define OPTCR_BYTE1_ADDRESS ((uint32_t)0x40023C15) /** * @brief OPTCR register byte 2 (Bits[23:16]) base address */ #define OPTCR_BYTE2_ADDRESS ((uint32_t)0x40023C16) /** * @brief OPTCR register byte 3 (Bits[31:24]) base address */ #define OPTCR_BYTE3_ADDRESS ((uint32_t)0x40023C17) /** * @} */ /* Private macros ------------------------------------------------------------*/ /** @defgroup FLASH_Private_Macros FLASH Private Macros * @{ */ /** @defgroup FLASH_IS_FLASH_Definitions FLASH Private macros to check input parameters * @{ */ #define IS_FLASH_TYPEPROGRAM(VALUE)(((VALUE) == FLASH_TYPEPROGRAM_BYTE) || \ ((VALUE) == FLASH_TYPEPROGRAM_HALFWORD) || \ ((VALUE) == FLASH_TYPEPROGRAM_WORD) || \ ((VALUE) == FLASH_TYPEPROGRAM_DOUBLEWORD)) /** * @} */ /** * @} */ /* Private functions ---------------------------------------------------------*/ /** @defgroup FLASH_Private_Functions FLASH Private Functions * @{ */ /** * @} */ /** * @} */ /** * @} */ #ifdef __cplusplus } #endif #endif /* __STM32F4xx_HAL_FLASH_H */ /************************ (C) COPYRIGHT STMicroelectronics *****END OF FILE****/ ================================================ FILE: Zelig/mbed/TARGET_NUCLEO_F411RE/stm32f4xx_hal_flash_ex.h ================================================ /** ****************************************************************************** * @file stm32f4xx_hal_flash_ex.h * @author MCD Application Team * @version V1.4.1 * @date 09-October-2015 * @brief Header file of FLASH HAL Extension module. ****************************************************************************** * @attention * *

© COPYRIGHT(c) 2015 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. * ****************************************************************************** */ /* Define to prevent recursive inclusion -------------------------------------*/ #ifndef __STM32F4xx_HAL_FLASH_EX_H #define __STM32F4xx_HAL_FLASH_EX_H #ifdef __cplusplus extern "C" { #endif /* Includes ------------------------------------------------------------------*/ #include "stm32f4xx_hal_def.h" /** @addtogroup STM32F4xx_HAL_Driver * @{ */ /** @addtogroup FLASHEx * @{ */ /* Exported types ------------------------------------------------------------*/ /** @defgroup FLASHEx_Exported_Types FLASH Exported Types * @{ */ /** * @brief FLASH Erase structure definition */ typedef struct { uint32_t TypeErase; /*!< Mass erase or sector Erase. This parameter can be a value of @ref FLASHEx_Type_Erase */ uint32_t Banks; /*!< Select banks to erase when Mass erase is enabled. This parameter must be a value of @ref FLASHEx_Banks */ uint32_t Sector; /*!< Initial FLASH sector to erase when Mass erase is disabled This parameter must be a value of @ref FLASHEx_Sectors */ uint32_t NbSectors; /*!< Number of sectors to be erased. This parameter must be a value between 1 and (max number of sectors - value of Initial sector)*/ uint32_t VoltageRange;/*!< The device voltage range which defines the erase parallelism This parameter must be a value of @ref FLASHEx_Voltage_Range */ } FLASH_EraseInitTypeDef; /** * @brief FLASH Option Bytes Program structure definition */ typedef struct { uint32_t OptionType; /*!< Option byte to be configured. This parameter can be a value of @ref FLASHEx_Option_Type */ uint32_t WRPState; /*!< Write protection activation or deactivation. This parameter can be a value of @ref FLASHEx_WRP_State */ uint32_t WRPSector; /*!< Specifies the sector(s) to be write protected. The value of this parameter depend on device used within the same series */ uint32_t Banks; /*!< Select banks for WRP activation/deactivation of all sectors. This parameter must be a value of @ref FLASHEx_Banks */ uint32_t RDPLevel; /*!< Set the read protection level. This parameter can be a value of @ref FLASHEx_Option_Bytes_Read_Protection */ uint32_t BORLevel; /*!< Set the BOR Level. This parameter can be a value of @ref FLASHEx_BOR_Reset_Level */ uint8_t USERConfig; /*!< Program the FLASH User Option Byte: IWDG_SW / RST_STOP / RST_STDBY. */ } FLASH_OBProgramInitTypeDef; /** * @brief FLASH Advanced Option Bytes Program structure definition */ #if defined(STM32F427xx) || defined(STM32F437xx) || defined(STM32F429xx) || defined(STM32F439xx) ||\ defined(STM32F401xC) || defined(STM32F401xE) || defined(STM32F410Tx) || defined(STM32F410Cx) ||\ defined(STM32F410Rx) || defined(STM32F411xE) || defined(STM32F446xx) || defined(STM32F469xx) ||\ defined(STM32F479xx) typedef struct { uint32_t OptionType; /*!< Option byte to be configured for extension. This parameter can be a value of @ref FLASHEx_Advanced_Option_Type */ uint32_t PCROPState; /*!< PCROP activation or deactivation. This parameter can be a value of @ref FLASHEx_PCROP_State */ #if defined(STM32F401xC) || defined(STM32F401xE) || defined(STM32F410Tx) || defined(STM32F410Cx) || defined(STM32F410Rx) || defined(STM32F411xE) || defined(STM32F446xx) uint16_t Sectors; /*!< specifies the sector(s) set for PCROP. This parameter can be a value of @ref FLASHEx_Option_Bytes_PC_ReadWrite_Protection */ #endif /* STM32F401xC || STM32F401xE || STM32F410xx || STM32F411xE || STM32F446xx */ #if defined(STM32F427xx) || defined(STM32F437xx) || defined(STM32F429xx) || defined(STM32F439xx) || defined(STM32F469xx) || defined(STM32F479xx) uint32_t Banks; /*!< Select banks for PCROP activation/deactivation of all sectors. This parameter must be a value of @ref FLASHEx_Banks */ uint16_t SectorsBank1; /*!< Specifies the sector(s) set for PCROP for Bank1. This parameter can be a value of @ref FLASHEx_Option_Bytes_PC_ReadWrite_Protection */ uint16_t SectorsBank2; /*!< Specifies the sector(s) set for PCROP for Bank2. This parameter can be a value of @ref FLASHEx_Option_Bytes_PC_ReadWrite_Protection */ uint8_t BootConfig; /*!< Specifies Option bytes for boot config. This parameter can be a value of @ref FLASHEx_Dual_Boot */ #endif /*STM32F427xx || STM32F437xx || STM32F429xx || STM32F439xx || STM32F469xx || STM32F479xx */ } FLASH_AdvOBProgramInitTypeDef; #endif /* STM32F427xx || STM32F437xx || STM32F429xx || STM32F439xx || STM32F401xC || STM32F401xE || STM32F410xx || STM32F411xE || STM32F446xx || STM32F469xx || STM32F479xx */ /** * @} */ /* Exported constants --------------------------------------------------------*/ /** @defgroup FLASHEx_Exported_Constants FLASH Exported Constants * @{ */ /** @defgroup FLASHEx_Type_Erase FLASH Type Erase * @{ */ #define FLASH_TYPEERASE_SECTORS ((uint32_t)0x00) /*!< Sectors erase only */ #define FLASH_TYPEERASE_MASSERASE ((uint32_t)0x01) /*!< Flash Mass erase activation */ /** * @} */ /** @defgroup FLASHEx_Voltage_Range FLASH Voltage Range * @{ */ #define FLASH_VOLTAGE_RANGE_1 ((uint32_t)0x00) /*!< Device operating range: 1.8V to 2.1V */ #define FLASH_VOLTAGE_RANGE_2 ((uint32_t)0x01) /*!< Device operating range: 2.1V to 2.7V */ #define FLASH_VOLTAGE_RANGE_3 ((uint32_t)0x02) /*!< Device operating range: 2.7V to 3.6V */ #define FLASH_VOLTAGE_RANGE_4 ((uint32_t)0x03) /*!< Device operating range: 2.7V to 3.6V + External Vpp */ /** * @} */ /** @defgroup FLASHEx_WRP_State FLASH WRP State * @{ */ #define OB_WRPSTATE_DISABLE ((uint32_t)0x00) /*!< Disable the write protection of the desired bank 1 sectors */ #define OB_WRPSTATE_ENABLE ((uint32_t)0x01) /*!< Enable the write protection of the desired bank 1 sectors */ /** * @} */ /** @defgroup FLASHEx_Option_Type FLASH Option Type * @{ */ #define OPTIONBYTE_WRP ((uint32_t)0x01) /*!< WRP option byte configuration */ #define OPTIONBYTE_RDP ((uint32_t)0x02) /*!< RDP option byte configuration */ #define OPTIONBYTE_USER ((uint32_t)0x04) /*!< USER option byte configuration */ #define OPTIONBYTE_BOR ((uint32_t)0x08) /*!< BOR option byte configuration */ /** * @} */ /** @defgroup FLASHEx_Option_Bytes_Read_Protection FLASH Option Bytes Read Protection * @{ */ #define OB_RDP_LEVEL_0 ((uint8_t)0xAA) #define OB_RDP_LEVEL_1 ((uint8_t)0x55) #define OB_RDP_LEVEL_2 ((uint8_t)0xCC) /*!< Warning: When enabling read protection level 2 it s no more possible to go back to level 1 or 0 */ /** * @} */ /** @defgroup FLASHEx_Option_Bytes_IWatchdog FLASH Option Bytes IWatchdog * @{ */ #define OB_IWDG_SW ((uint8_t)0x20) /*!< Software IWDG selected */ #define OB_IWDG_HW ((uint8_t)0x00) /*!< Hardware IWDG selected */ /** * @} */ /** @defgroup FLASHEx_Option_Bytes_nRST_STOP FLASH Option Bytes nRST_STOP * @{ */ #define OB_STOP_NO_RST ((uint8_t)0x40) /*!< No reset generated when entering in STOP */ #define OB_STOP_RST ((uint8_t)0x00) /*!< Reset generated when entering in STOP */ /** * @} */ /** @defgroup FLASHEx_Option_Bytes_nRST_STDBY FLASH Option Bytes nRST_STDBY * @{ */ #define OB_STDBY_NO_RST ((uint8_t)0x80) /*!< No reset generated when entering in STANDBY */ #define OB_STDBY_RST ((uint8_t)0x00) /*!< Reset generated when entering in STANDBY */ /** * @} */ /** @defgroup FLASHEx_BOR_Reset_Level FLASH BOR Reset Level * @{ */ #define OB_BOR_LEVEL3 ((uint8_t)0x00) /*!< Supply voltage ranges from 2.70 to 3.60 V */ #define OB_BOR_LEVEL2 ((uint8_t)0x04) /*!< Supply voltage ranges from 2.40 to 2.70 V */ #define OB_BOR_LEVEL1 ((uint8_t)0x08) /*!< Supply voltage ranges from 2.10 to 2.40 V */ #define OB_BOR_OFF ((uint8_t)0x0C) /*!< Supply voltage ranges from 1.62 to 2.10 V */ /** * @} */ #if defined(STM32F427xx) || defined(STM32F437xx) || defined(STM32F429xx) || defined(STM32F439xx) ||\ defined(STM32F401xC) || defined(STM32F401xE) || defined(STM32F410Tx) || defined(STM32F410Cx) ||\ defined(STM32F410Rx) || defined(STM32F411xE) || defined(STM32F446xx) || defined(STM32F469xx) ||\ defined(STM32F479xx) /** @defgroup FLASHEx_PCROP_State FLASH PCROP State * @{ */ #define OB_PCROP_STATE_DISABLE ((uint32_t)0x00) /*!< Disable PCROP */ #define OB_PCROP_STATE_ENABLE ((uint32_t)0x01) /*!< Enable PCROP */ /** * @} */ #endif /* STM32F427xx || STM32F437xx || STM32F429xx || STM32F439xx || STM32F401xC || STM32F401xE ||\ STM32F410xx || STM32F411xE || STM32F446xx || STM32F469xx || STM32F479xx */ /** @defgroup FLASHEx_Advanced_Option_Type FLASH Advanced Option Type * @{ */ #if defined(STM32F427xx) || defined(STM32F437xx) || defined(STM32F429xx) || defined(STM32F439xx) ||\ defined(STM32F469xx) || defined(STM32F479xx) #define OPTIONBYTE_PCROP ((uint32_t)0x01) /*!< PCROP option byte configuration */ #define OPTIONBYTE_BOOTCONFIG ((uint32_t)0x02) /*!< BOOTConfig option byte configuration */ #endif /* STM32F427xx || STM32F437xx || STM32F429xx || STM32F439xx || STM32F469xx || STM32F479xx */ #if defined(STM32F401xC) || defined(STM32F401xE) || defined(STM32F410Tx) || defined(STM32F410Cx) ||\ defined(STM32F410Rx) || defined(STM32F411xE) || defined(STM32F446xx) #define OPTIONBYTE_PCROP ((uint32_t)0x01) /*!= FLASH_BASE) && ((ADDRESS) <= FLASH_END)) #define IS_FLASH_NBSECTORS(NBSECTORS) (((NBSECTORS) != 0) && ((NBSECTORS) <= FLASH_SECTOR_TOTAL)) #if defined(STM32F427xx) || defined(STM32F437xx) || defined(STM32F429xx) || defined(STM32F439xx) || defined(STM32F469xx) || defined(STM32F479xx) #define IS_OB_WRP_SECTOR(SECTOR)((((SECTOR) & (uint32_t)0xFF000000) == 0x00000000) && ((SECTOR) != 0x00000000)) #endif /* STM32F427xx || STM32F437xx || STM32F429xx || STM32F439xx || STM32F469xx || STM32F479xx */ #if defined(STM32F405xx) || defined(STM32F415xx) || defined(STM32F407xx) || defined(STM32F417xx) #define IS_OB_WRP_SECTOR(SECTOR)((((SECTOR) & (uint32_t)0xFFFFF000) == 0x00000000) && ((SECTOR) != 0x00000000)) #endif /* STM32F405xx || STM32F415xx || STM32F407xx || STM32F417xx */ #if defined(STM32F401xC) #define IS_OB_WRP_SECTOR(SECTOR)((((SECTOR) & (uint32_t)0xFFFFF000) == 0x00000000) && ((SECTOR) != 0x00000000)) #endif /* STM32F401xC */ #if defined(STM32F410Tx) || defined(STM32F410Cx) || defined(STM32F410Rx) #define IS_OB_WRP_SECTOR(SECTOR)((((SECTOR) & (uint32_t)0xFFFFF000) == 0x00000000) && ((SECTOR) != 0x00000000)) #endif /* STM32F410Tx || STM32F410Cx || STM32F410Rx */ #if defined(STM32F401xE) || defined(STM32F411xE) || defined(STM32F446xx) #define IS_OB_WRP_SECTOR(SECTOR)((((SECTOR) & (uint32_t)0xFFFFF000) == 0x00000000) && ((SECTOR) != 0x00000000)) #endif /* STM32F401xE || STM32F411xE || STM32F446xx */ #if defined(STM32F427xx) || defined(STM32F437xx) || defined(STM32F429xx) || defined(STM32F439xx) || defined(STM32F469xx) || defined(STM32F479xx) #define IS_OB_PCROP(SECTOR)((((SECTOR) & (uint32_t)0xFFFFF000) == 0x00000000) && ((SECTOR) != 0x00000000)) #endif /* STM32F427xx || STM32F437xx || STM32F429xx || STM32F439xx || STM32F469xx || STM32F479xx */ #if defined(STM32F401xC) #define IS_OB_PCROP(SECTOR)((((SECTOR) & (uint32_t)0xFFFFF000) == 0x00000000) && ((SECTOR) != 0x00000000)) #endif /* STM32F401xC */ #if defined(STM32F410Tx) || defined(STM32F410Cx) || defined(STM32F410Rx) #define IS_OB_PCROP(SECTOR)((((SECTOR) & (uint32_t)0xFFFFF000) == 0x00000000) && ((SECTOR) != 0x00000000)) #endif /* STM32F410Tx || STM32F410Cx || STM32F410Rx */ #if defined(STM32F401xE) || defined(STM32F411xE) || defined(STM32F446xx) #define IS_OB_PCROP(SECTOR)((((SECTOR) & (uint32_t)0xFFFFF000) == 0x00000000) && ((SECTOR) != 0x00000000)) #endif /* STM32F401xE || STM32F411xE || STM32F446xx */ #if defined(STM32F427xx) || defined(STM32F437xx) || defined(STM32F429xx) || defined(STM32F439xx) ||\ defined(STM32F469xx) || defined(STM32F479xx) #define IS_OB_BOOT(BOOT) (((BOOT) == OB_DUAL_BOOT_ENABLE) || ((BOOT) == OB_DUAL_BOOT_DISABLE)) #endif /* STM32F427xx || STM32F437xx || STM32F429xx || STM32F439xx || STM32F469xx || STM32F479xx */ #if defined(STM32F427xx) || defined(STM32F437xx) || defined(STM32F429xx) || defined(STM32F439xx) ||\ defined(STM32F401xC) || defined(STM32F401xE) || defined(STM32F410Tx) || defined(STM32F410Cx) ||\ defined(STM32F410Rx) || defined(STM32F411xE) || defined(STM32F446xx) || defined(STM32F469xx) ||\ defined(STM32F479xx) #define IS_OB_PCROP_SELECT(PCROP) (((PCROP) == OB_PCROP_SELECTED) || ((PCROP) == OB_PCROP_DESELECTED)) #endif /* STM32F427xx || STM32F437xx || STM32F429xx || STM32F439xx || STM32F401xC || STM32F401xE ||\ STM32F410xx || STM32F411xE || STM32F446xx || STM32F469xx || STM32F479xx */ /** * @} */ /** * @} */ /* Private functions ---------------------------------------------------------*/ /** @defgroup FLASHEx_Private_Functions FLASH Private Functions * @{ */ void FLASH_Erase_Sector(uint32_t Sector, uint8_t VoltageRange); /** * @} */ /** * @} */ /** * @} */ #ifdef __cplusplus } #endif #endif /* __STM32F4xx_HAL_FLASH_EX_H */ /************************ (C) COPYRIGHT STMicroelectronics *****END OF FILE****/ ================================================ FILE: Zelig/mbed/TARGET_NUCLEO_F411RE/stm32f4xx_hal_flash_ramfunc.h ================================================ /** ****************************************************************************** * @file stm32f4xx_hal_flash_ramfunc.h * @author MCD Application Team * @version V1.4.1 * @date 09-October-2015 * @brief Header file of FLASH RAMFUNC driver. ****************************************************************************** * @attention * *

© COPYRIGHT(c) 2015 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. * ****************************************************************************** */ /* Define to prevent recursive inclusion -------------------------------------*/ #ifndef __STM32F4xx_FLASH_RAMFUNC_H #define __STM32F4xx_FLASH_RAMFUNC_H #ifdef __cplusplus extern "C" { #endif #if defined(STM32F410Tx) || defined(STM32F410Cx) || defined(STM32F410Rx) || defined(STM32F411xE) || defined(STM32F446xx) /* Includes ------------------------------------------------------------------*/ #include "stm32f4xx_hal_def.h" /** @addtogroup STM32F4xx_HAL_Driver * @{ */ /** @addtogroup FLASHRAMFUNC * @{ */ /* Exported types ------------------------------------------------------------*/ /* Exported macro ------------------------------------------------------------*/ /* Exported functions --------------------------------------------------------*/ /** @addtogroup FLASHRAMFUNC_Exported_Functions * @{ */ /** @addtogroup FLASHRAMFUNC_Exported_Functions_Group1 * @{ */ __RAM_FUNC HAL_FLASHEx_StopFlashInterfaceClk(void); __RAM_FUNC HAL_FLASHEx_StartFlashInterfaceClk(void); __RAM_FUNC HAL_FLASHEx_EnableFlashSleepMode(void); __RAM_FUNC HAL_FLASHEx_DisableFlashSleepMode(void); /** * @} */ /** * @} */ /** * @} */ /** * @} */ #endif /* STM32F410xx || STM32F411xE || STM32F446xx */ #ifdef __cplusplus } #endif #endif /* __STM32F4xx_FLASH_RAMFUNC_H */ /************************ (C) COPYRIGHT STMicroelectronics *****END OF FILE****/ ================================================ FILE: Zelig/mbed/TARGET_NUCLEO_F411RE/stm32f4xx_hal_fmpi2c.h ================================================ /** ****************************************************************************** * @file stm32f4xx_hal_fmpi2c.h * @author MCD Application Team * @version V1.4.1 * @date 09-October-2015 * @brief Header file of FMPI2C HAL module. ****************************************************************************** * @attention * *

© COPYRIGHT(c) 2015 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. * ****************************************************************************** */ /* Define to prevent recursive inclusion -------------------------------------*/ #ifndef __STM32F4xx_HAL_FMPI2C_H #define __STM32F4xx_HAL_FMPI2C_H #ifdef __cplusplus extern "C" { #endif #if defined(STM32F410Tx) || defined(STM32F410Cx) || defined(STM32F410Rx) || defined(STM32F446xx) /* Includes ------------------------------------------------------------------*/ #include "stm32f4xx_hal_def.h" /** @addtogroup STM32F4xx_HAL_Driver * @{ */ /** @addtogroup FMPI2C * @{ */ /* Exported types ------------------------------------------------------------*/ /** @defgroup FMPI2C_Exported_Types FMPI2C Exported Types * @{ */ /** * @brief FMPI2C Configuration Structure definition */ typedef struct { uint32_t Timing; /*!< Specifies the FMPI2C_TIMINGR_register value. This parameter calculated by referring to FMPI2C initialization section in Reference manual */ uint32_t OwnAddress1; /*!< Specifies the first device own address. This parameter can be a 7-bit or 10-bit address. */ uint32_t AddressingMode; /*!< Specifies if 7-bit or 10-bit addressing mode is selected. This parameter can be a value of @ref FMPI2C_addressing_mode */ uint32_t DualAddressMode; /*!< Specifies if dual addressing mode is selected. This parameter can be a value of @ref FMPI2C_dual_addressing_mode */ uint32_t OwnAddress2; /*!< Specifies the second device own address if dual addressing mode is selected This parameter can be a 7-bit address. */ uint32_t OwnAddress2Masks; /*!< Specifies the acknoledge mask address second device own address if dual addressing mode is selected This parameter can be a value of @ref FMPI2C_own_address2_masks */ uint32_t GeneralCallMode; /*!< Specifies if general call mode is selected. This parameter can be a value of @ref FMPI2C_general_call_addressing_mode */ uint32_t NoStretchMode; /*!< Specifies if nostretch mode is selected. This parameter can be a value of @ref FMPI2C_nostretch_mode */ }FMPI2C_InitTypeDef; /** * @brief HAL State structures definition */ typedef enum { HAL_FMPI2C_STATE_RESET = 0x00, /*!< FMPI2C not yet initialized or disabled */ HAL_FMPI2C_STATE_READY = 0x01, /*!< FMPI2C initialized and ready for use */ HAL_FMPI2C_STATE_BUSY = 0x02, /*!< FMPI2C internal process is ongoing */ HAL_FMPI2C_STATE_MASTER_BUSY_TX = 0x12, /*!< Master Data Transmission process is ongoing */ HAL_FMPI2C_STATE_MASTER_BUSY_RX = 0x22, /*!< Master Data Reception process is ongoing */ HAL_FMPI2C_STATE_SLAVE_BUSY_TX = 0x32, /*!< Slave Data Transmission process is ongoing */ HAL_FMPI2C_STATE_SLAVE_BUSY_RX = 0x42, /*!< Slave Data Reception process is ongoing */ HAL_FMPI2C_STATE_MEM_BUSY_TX = 0x52, /*!< Memory Data Transmission process is ongoing */ HAL_FMPI2C_STATE_MEM_BUSY_RX = 0x62, /*!< Memory Data Reception process is ongoing */ HAL_FMPI2C_STATE_TIMEOUT = 0x03, /*!< Timeout state */ HAL_FMPI2C_STATE_ERROR = 0x04 /*!< Reception process is ongoing */ }HAL_FMPI2C_StateTypeDef; /** * @brief HAL FMPI2C Error Code structure definition */ typedef enum { HAL_FMPI2C_ERROR_NONE = 0x00, /*!< No error */ HAL_FMPI2C_ERROR_BERR = 0x01, /*!< BERR error */ HAL_FMPI2C_ERROR_ARLO = 0x02, /*!< ARLO error */ HAL_FMPI2C_ERROR_AF = 0x04, /*!< ACKF error */ HAL_FMPI2C_ERROR_OVR = 0x08, /*!< OVR error */ HAL_FMPI2C_ERROR_DMA = 0x10, /*!< DMA transfer error */ HAL_FMPI2C_ERROR_TIMEOUT = 0x20, /*!< Timeout error */ HAL_FMPI2C_ERROR_SIZE = 0x40 /*!< Size Management error */ }HAL_FMPI2C_ErrorTypeDef; /** * @brief FMPI2C handle Structure definition */ typedef struct { FMPI2C_TypeDef *Instance; /*!< FMPI2C registers base address */ FMPI2C_InitTypeDef Init; /*!< FMPI2C communication parameters */ uint8_t *pBuffPtr; /*!< Pointer to FMPI2C transfer buffer */ uint16_t XferSize; /*!< FMPI2C transfer size */ __IO uint16_t XferCount; /*!< FMPI2C transfer counter */ DMA_HandleTypeDef *hdmatx; /*!< FMPI2C Tx DMA handle parameters */ DMA_HandleTypeDef *hdmarx; /*!< FMPI2C Rx DMA handle parameters */ HAL_LockTypeDef Lock; /*!< FMPI2C locking object */ __IO HAL_FMPI2C_StateTypeDef State; /*!< FMPI2C communication state */ __IO HAL_FMPI2C_ErrorTypeDef ErrorCode; /* FMPI2C Error code */ }FMPI2C_HandleTypeDef; /** * @} */ /* Exported constants --------------------------------------------------------*/ /** @defgroup FMPI2C_Exported_Constants FMPI2C Exported Constants * @{ */ /** @defgroup FMPI2C_addressing_mode FMPI2C addressing mode * @{ */ #define FMPI2C_ADDRESSINGMODE_7BIT ((uint32_t)0x00000001) #define FMPI2C_ADDRESSINGMODE_10BIT ((uint32_t)0x00000002) /** * @} */ /** @defgroup FMPI2C_dual_addressing_mode FMPI2C dual addressing mode * @{ */ #define FMPI2C_DUALADDRESS_DISABLE ((uint32_t)0x00000000) #define FMPI2C_DUALADDRESS_ENABLE FMPI2C_OAR2_OA2EN /** * @} */ /** @defgroup FMPI2C_own_address2_masks FMPI2C own address2 masks * @{ */ #define FMPI2C_OA2_NOMASK ((uint8_t)0x00) #define FMPI2C_OA2_MASK01 ((uint8_t)0x01) #define FMPI2C_OA2_MASK02 ((uint8_t)0x02) #define FMPI2C_OA2_MASK03 ((uint8_t)0x03) #define FMPI2C_OA2_MASK04 ((uint8_t)0x04) #define FMPI2C_OA2_MASK05 ((uint8_t)0x05) #define FMPI2C_OA2_MASK06 ((uint8_t)0x06) #define FMPI2C_OA2_MASK07 ((uint8_t)0x07) /** * @} */ /** @defgroup FMPI2C_general_call_addressing_mode FMPI2C general call addressing mode * @{ */ #define FMPI2C_GENERALCALL_DISABLE ((uint32_t)0x00000000) #define FMPI2C_GENERALCALL_ENABLE FMPI2C_CR1_GCEN /** * @} */ /** @defgroup FMPI2C_nostretch_mode FMPI2C nostretch mode * @{ */ #define FMPI2C_NOSTRETCH_DISABLE ((uint32_t)0x00000000) #define FMPI2C_NOSTRETCH_ENABLE FMPI2C_CR1_NOSTRETCH /** * @} */ /** @defgroup FMPI2C_Memory_Address_Size FMPI2C Memory Address Size * @{ */ #define FMPI2C_MEMADD_SIZE_8BIT ((uint32_t)0x00000001) #define FMPI2C_MEMADD_SIZE_16BIT ((uint32_t)0x00000002) /** * @} */ /** @defgroup FMPI2C_ReloadEndMode_definition FMPI2C ReloadEndMode definition * @{ */ #define FMPI2C_RELOAD_MODE FMPI2C_CR2_RELOAD #define FMPI2C_AUTOEND_MODE FMPI2C_CR2_AUTOEND #define FMPI2C_SOFTEND_MODE ((uint32_t)0x00000000) /** * @} */ /** @defgroup FMPI2C_StartStopMode_definition FMPI2C StartStopMode definition * @{ */ #define FMPI2C_NO_STARTSTOP ((uint32_t)0x00000000) #define FMPI2C_GENERATE_STOP FMPI2C_CR2_STOP #define FMPI2C_GENERATE_START_READ (uint32_t)(FMPI2C_CR2_START | FMPI2C_CR2_RD_WRN) #define FMPI2C_GENERATE_START_WRITE FMPI2C_CR2_START /** * @} */ /** @defgroup FMPI2C_Interrupt_configuration_definition FMPI2C Interrupt configuration definition * @brief FMPI2C Interrupt definition * Elements values convention: 0xXXXXXXXX * - XXXXXXXX : Interrupt control mask * @{ */ #define FMPI2C_IT_ERRI FMPI2C_CR1_ERRIE #define FMPI2C_IT_TCI FMPI2C_CR1_TCIE #define FMPI2C_IT_STOPI FMPI2C_CR1_STOPIE #define FMPI2C_IT_NACKI FMPI2C_CR1_NACKIE #define FMPI2C_IT_ADDRI FMPI2C_CR1_ADDRIE #define FMPI2C_IT_RXI FMPI2C_CR1_RXIE #define FMPI2C_IT_TXI FMPI2C_CR1_TXIE /** * @} */ /** @defgroup FMPI2C_Flag_definition FMPI2C Flag definition * @{ */ #define FMPI2C_FLAG_TXE FMPI2C_ISR_TXE #define FMPI2C_FLAG_TXIS FMPI2C_ISR_TXIS #define FMPI2C_FLAG_RXNE FMPI2C_ISR_RXNE #define FMPI2C_FLAG_ADDR FMPI2C_ISR_ADDR #define FMPI2C_FLAG_AF FMPI2C_ISR_NACKF #define FMPI2C_FLAG_STOPF FMPI2C_ISR_STOPF #define FMPI2C_FLAG_TC FMPI2C_ISR_TC #define FMPI2C_FLAG_TCR FMPI2C_ISR_TCR #define FMPI2C_FLAG_BERR FMPI2C_ISR_BERR #define FMPI2C_FLAG_ARLO FMPI2C_ISR_ARLO #define FMPI2C_FLAG_OVR FMPI2C_ISR_OVR #define FMPI2C_FLAG_PECERR FMPI2C_ISR_PECERR #define FMPI2C_FLAG_TIMEOUT FMPI2C_ISR_TIMEOUT #define FMPI2C_FLAG_ALERT FMPI2C_ISR_ALERT #define FMPI2C_FLAG_BUSY FMPI2C_ISR_BUSY #define FMPI2C_FLAG_DIR FMPI2C_ISR_DIR /** * @} */ /** * @} */ /* Exported macro ------------------------------------------------------------*/ /** @defgroup FMPI2C_Exported_Macros FMPI2C Exported Macros * @{ */ /** @brief Reset FMPI2C handle state * @param __HANDLE__: specifies the FMPI2C Handle. * This parameter can be FMPI2C where x: 1 or 2 to select the FMPI2C peripheral. * @retval None */ #define __HAL_FMPI2C_RESET_HANDLE_STATE(__HANDLE__) ((__HANDLE__)->State = HAL_FMPI2C_STATE_RESET) /** @brief Enables or disables the specified FMPI2C interrupts. * @param __HANDLE__: specifies the FMPI2C Handle. * This parameter can be FMPI2C where x: 1 or 2 to select the FMPI2C peripheral. * @param __INTERRUPT__: specifies the interrupt source to enable or disable. * This parameter can be one of the following values: * @arg FMPI2C_IT_ERRI: Errors interrupt enable * @arg FMPI2C_IT_TCI: Transfer complete interrupt enable * @arg FMPI2C_IT_STOPI: STOP detection interrupt enable * @arg FMPI2C_IT_NACKI: NACK received interrupt enable * @arg FMPI2C_IT_ADDRI: Address match interrupt enable * @arg FMPI2C_IT_RXI: RX interrupt enable * @arg FMPI2C_IT_TXI: TX interrupt enable * * @retval None */ #define __HAL_FMPI2C_ENABLE_IT(__HANDLE__, __INTERRUPT__) ((__HANDLE__)->Instance->CR1 |= (__INTERRUPT__)) #define __HAL_FMPI2C_DISABLE_IT(__HANDLE__, __INTERRUPT__) ((__HANDLE__)->Instance->CR1 &= (~(__INTERRUPT__))) /** @brief Checks if the specified FMPI2C interrupt source is enabled or disabled. * @param __HANDLE__: specifies the FMPI2C Handle. * This parameter can be FMPI2C where x: 1 or 2 to select the FMPI2C peripheral. * @param __INTERRUPT__: specifies the FMPI2C interrupt source to check. * This parameter can be one of the following values: * @arg FMPI2C_IT_ERRI: Errors interrupt enable * @arg FMPI2C_IT_TCI: Transfer complete interrupt enable * @arg FMPI2C_IT_STOPI: STOP detection interrupt enable * @arg FMPI2C_IT_NACKI: NACK received interrupt enable * @arg FMPI2C_IT_ADDRI: Address match interrupt enable * @arg FMPI2C_IT_RXI: RX interrupt enable * @arg FMPI2C_IT_TXI: TX interrupt enable * * @retval The new state of __IT__ (TRUE or FALSE). */ #define __HAL_FMPI2C_GET_IT_SOURCE(__HANDLE__, __INTERRUPT__) ((((__HANDLE__)->Instance->CR1 & (__INTERRUPT__)) == (__INTERRUPT__)) ? SET : RESET) /** @brief Checks whether the specified FMPI2C flag is set or not. * @param __HANDLE__: specifies the FMPI2C Handle. * This parameter can be FMPI2C where x: 1 or 2 to select the FMPI2C peripheral. * @param __FLAG__: specifies the flag to check. * This parameter can be one of the following values: * @arg FMPI2C_FLAG_TXE: Transmit data register empty * @arg FMPI2C_FLAG_TXIS: Transmit interrupt status * @arg FMPI2C_FLAG_RXNE: Receive data register not empty * @arg FMPI2C_FLAG_ADDR: Address matched (slave mode) * @arg FMPI2C_FLAG_AF: Acknowledge failure received flag * @arg FMPI2C_FLAG_STOPF: STOP detection flag * @arg FMPI2C_FLAG_TC: Transfer complete (master mode) * @arg FMPI2C_FLAG_TCR: Transfer complete reload * @arg FMPI2C_FLAG_BERR: Bus error * @arg FMPI2C_FLAG_ARLO: Arbitration lost * @arg FMPI2C_FLAG_OVR: Overrun/Underrun * @arg FMPI2C_FLAG_PECERR: PEC error in reception * @arg FMPI2C_FLAG_TIMEOUT: Timeout or Tlow detection flag * @arg FMPI2C_FLAG_ALERT: SMBus alert * @arg FMPI2C_FLAG_BUSY: Bus busy * @arg FMPI2C_FLAG_DIR: Transfer direction (slave mode) * * @retval The new state of __FLAG__ (TRUE or FALSE). */ #define __HAL_FMPI2C_GET_FLAG(__HANDLE__, __FLAG__) (((((__HANDLE__)->Instance->ISR) & ((__FLAG__) & FMPI2C_FLAG_MASK)) == ((__FLAG__) & FMPI2C_FLAG_MASK))) /** @brief Clears the FMPI2C pending flags which are cleared by writing 1 in a specific bit. * @param __HANDLE__: specifies the FMPI2C Handle. * This parameter can be FMPI2C where x: 1 or 2 to select the FMPI2C peripheral. * @param __FLAG__: specifies the flag to clear. * This parameter can be any combination of the following values: * @arg FMPI2C_FLAG_ADDR: Address matched (slave mode) * @arg FMPI2C_FLAG_AF: Acknowledge failure received flag * @arg FMPI2C_FLAG_STOPF: STOP detection flag * @arg FMPI2C_FLAG_BERR: Bus error * @arg FMPI2C_FLAG_ARLO: Arbitration lost * @arg FMPI2C_FLAG_OVR: Overrun/Underrun * @arg FMPI2C_FLAG_PECERR: PEC error in reception * @arg FMPI2C_FLAG_TIMEOUT: Timeout or Tlow detection flag * @arg FMPI2C_FLAG_ALERT: SMBus alert * * @retval None */ #define __HAL_FMPI2C_CLEAR_FLAG(__HANDLE__, __FLAG__) ((__HANDLE__)->Instance->ICR = ((__FLAG__) & FMPI2C_FLAG_MASK)) #define __HAL_FMPI2C_ENABLE(__HANDLE__) ((__HANDLE__)->Instance->CR1 |= FMPI2C_CR1_PE) #define __HAL_FMPI2C_DISABLE(__HANDLE__) ((__HANDLE__)->Instance->CR1 &= ~FMPI2C_CR1_PE) #define __HAL_FMPI2C_RESET_CR2(__HANDLE__) ((__HANDLE__)->Instance->CR2 &= (uint32_t)~((uint32_t)(FMPI2C_CR2_SADD | FMPI2C_CR2_HEAD10R | FMPI2C_CR2_NBYTES | FMPI2C_CR2_RELOAD | FMPI2C_CR2_RD_WRN))) #define __HAL_FMPI2C_MEM_ADD_MSB(__ADDRESS__) ((uint8_t)((uint16_t)(((uint16_t)((__ADDRESS__) & (uint16_t)(0xFF00))) >> 8))) #define __HAL_FMPI2C_MEM_ADD_LSB(__ADDRESS__) ((uint8_t)((uint16_t)((__ADDRESS__) & (uint16_t)(0x00FF)))) #define __HAL_FMPI2C_GENERATE_START(__ADDMODE__,__ADDRESS__) (((__ADDMODE__) == FMPI2C_ADDRESSINGMODE_7BIT) ? (uint32_t)((((uint32_t)(__ADDRESS__) & (FMPI2C_CR2_SADD)) | (FMPI2C_CR2_START) | (FMPI2C_CR2_AUTOEND)) & (~FMPI2C_CR2_RD_WRN)) : \ (uint32_t)((((uint32_t)(__ADDRESS__) & (FMPI2C_CR2_SADD)) | (FMPI2C_CR2_ADD10) | (FMPI2C_CR2_START)) & (~FMPI2C_CR2_RD_WRN))) #define IS_FMPI2C_OWN_ADDRESS1(ADDRESS1) ((ADDRESS1) <= (uint32_t)0x000003FF) #define IS_FMPI2C_OWN_ADDRESS2(ADDRESS2) ((ADDRESS2) <= (uint16_t)0x00FF) /** * @} */ /* Include FMPI2C HAL Extension module */ #include "stm32f4xx_hal_fmpi2c_ex.h" /* Exported functions --------------------------------------------------------*/ /** @addtogroup FMPI2C_Exported_Functions * @{ */ /** @addtogroup FMPI2C_Exported_Functions_Group1 * @{ */ /* Initialization/de-initialization functions**********************************/ HAL_StatusTypeDef HAL_FMPI2C_Init(FMPI2C_HandleTypeDef *hFMPI2C); HAL_StatusTypeDef HAL_FMPI2C_DeInit (FMPI2C_HandleTypeDef *hFMPI2C); void HAL_FMPI2C_MspInit(FMPI2C_HandleTypeDef *hFMPI2C); void HAL_FMPI2C_MspDeInit(FMPI2C_HandleTypeDef *hFMPI2C); /** * @} */ /** @addtogroup FMPI2C_Exported_Functions_Group2 * @{ */ /* I/O operation functions ***************************************************/ /******* Blocking mode: Polling */ HAL_StatusTypeDef HAL_FMPI2C_Master_Transmit(FMPI2C_HandleTypeDef *hFMPI2C, uint16_t DevAddress, uint8_t *pData, uint16_t Size, uint32_t Timeout); HAL_StatusTypeDef HAL_FMPI2C_Master_Receive(FMPI2C_HandleTypeDef *hFMPI2C, uint16_t DevAddress, uint8_t *pData, uint16_t Size, uint32_t Timeout); HAL_StatusTypeDef HAL_FMPI2C_Slave_Transmit(FMPI2C_HandleTypeDef *hFMPI2C, uint8_t *pData, uint16_t Size, uint32_t Timeout); HAL_StatusTypeDef HAL_FMPI2C_Slave_Receive(FMPI2C_HandleTypeDef *hFMPI2C, uint8_t *pData, uint16_t Size, uint32_t Timeout); HAL_StatusTypeDef HAL_FMPI2C_Mem_Write(FMPI2C_HandleTypeDef *hFMPI2C, uint16_t DevAddress, uint16_t MemAddress, uint16_t MemAddSize, uint8_t *pData, uint16_t Size, uint32_t Timeout); HAL_StatusTypeDef HAL_FMPI2C_Mem_Read(FMPI2C_HandleTypeDef *hFMPI2C, uint16_t DevAddress, uint16_t MemAddress, uint16_t MemAddSize, uint8_t *pData, uint16_t Size, uint32_t Timeout); HAL_StatusTypeDef HAL_FMPI2C_IsDeviceReady(FMPI2C_HandleTypeDef *hFMPI2C, uint16_t DevAddress, uint32_t Trials, uint32_t Timeout); /******* Non-Blocking mode: Interrupt */ HAL_StatusTypeDef HAL_FMPI2C_Master_Transmit_IT(FMPI2C_HandleTypeDef *hFMPI2C, uint16_t DevAddress, uint8_t *pData, uint16_t Size); HAL_StatusTypeDef HAL_FMPI2C_Master_Receive_IT(FMPI2C_HandleTypeDef *hFMPI2C, uint16_t DevAddress, uint8_t *pData, uint16_t Size); HAL_StatusTypeDef HAL_FMPI2C_Slave_Transmit_IT(FMPI2C_HandleTypeDef *hFMPI2C, uint8_t *pData, uint16_t Size); HAL_StatusTypeDef HAL_FMPI2C_Slave_Receive_IT(FMPI2C_HandleTypeDef *hFMPI2C, uint8_t *pData, uint16_t Size); HAL_StatusTypeDef HAL_FMPI2C_Mem_Write_IT(FMPI2C_HandleTypeDef *hFMPI2C, uint16_t DevAddress, uint16_t MemAddress, uint16_t MemAddSize, uint8_t *pData, uint16_t Size); HAL_StatusTypeDef HAL_FMPI2C_Mem_Read_IT(FMPI2C_HandleTypeDef *hFMPI2C, uint16_t DevAddress, uint16_t MemAddress, uint16_t MemAddSize, uint8_t *pData, uint16_t Size); /******* Non-Blocking mode: DMA */ HAL_StatusTypeDef HAL_FMPI2C_Master_Transmit_DMA(FMPI2C_HandleTypeDef *hFMPI2C, uint16_t DevAddress, uint8_t *pData, uint16_t Size); HAL_StatusTypeDef HAL_FMPI2C_Master_Receive_DMA(FMPI2C_HandleTypeDef *hFMPI2C, uint16_t DevAddress, uint8_t *pData, uint16_t Size); HAL_StatusTypeDef HAL_FMPI2C_Slave_Transmit_DMA(FMPI2C_HandleTypeDef *hFMPI2C, uint8_t *pData, uint16_t Size); HAL_StatusTypeDef HAL_FMPI2C_Slave_Receive_DMA(FMPI2C_HandleTypeDef *hFMPI2C, uint8_t *pData, uint16_t Size); HAL_StatusTypeDef HAL_FMPI2C_Mem_Write_DMA(FMPI2C_HandleTypeDef *hFMPI2C, uint16_t DevAddress, uint16_t MemAddress, uint16_t MemAddSize, uint8_t *pData, uint16_t Size); HAL_StatusTypeDef HAL_FMPI2C_Mem_Read_DMA(FMPI2C_HandleTypeDef *hFMPI2C, uint16_t DevAddress, uint16_t MemAddress, uint16_t MemAddSize, uint8_t *pData, uint16_t Size); /******* FMPI2C IRQHandler and Callbacks used in non blocking modes (Interrupt and DMA) */ void HAL_FMPI2C_EV_IRQHandler(FMPI2C_HandleTypeDef *hFMPI2C); void HAL_FMPI2C_ER_IRQHandler(FMPI2C_HandleTypeDef *hFMPI2C); void HAL_FMPI2C_MasterTxCpltCallback(FMPI2C_HandleTypeDef *hFMPI2C); void HAL_FMPI2C_MasterRxCpltCallback(FMPI2C_HandleTypeDef *hFMPI2C); void HAL_FMPI2C_SlaveTxCpltCallback(FMPI2C_HandleTypeDef *hFMPI2C); void HAL_FMPI2C_SlaveRxCpltCallback(FMPI2C_HandleTypeDef *hFMPI2C); void HAL_FMPI2C_MemTxCpltCallback(FMPI2C_HandleTypeDef *hFMPI2C); void HAL_FMPI2C_MemRxCpltCallback(FMPI2C_HandleTypeDef *hFMPI2C); void HAL_FMPI2C_ErrorCallback(FMPI2C_HandleTypeDef *hFMPI2C); /** * @} */ /** @addtogroup FMPI2C_Exported_Functions_Group3 * @{ */ /* Peripheral State functions ************************************************/ HAL_FMPI2C_StateTypeDef HAL_FMPI2C_GetState(FMPI2C_HandleTypeDef *hFMPI2C); uint32_t HAL_FMPI2C_GetError(FMPI2C_HandleTypeDef *hFMPI2C); /** * @} */ /** * @} */ /* Private types -------------------------------------------------------------*/ /* Private variables ---------------------------------------------------------*/ /* Private constants ---------------------------------------------------------*/ /** @defgroup FMPI2C_Private_Constants FMPI2C Private Constants * @{ */ #define FMPI2C_FLAG_MASK ((uint32_t)0x0001FFFF) /** * @} */ /* Private macros ------------------------------------------------------------*/ /** @defgroup FMPI2C_Private_Macros FMPI2C Private Macros * @{ */ #define IS_FMPI2C_ADDRESSING_MODE(MODE) (((MODE) == FMPI2C_ADDRESSINGMODE_7BIT) || \ ((MODE) == FMPI2C_ADDRESSINGMODE_10BIT)) #define IS_FMPI2C_DUAL_ADDRESS(ADDRESS) (((ADDRESS) == FMPI2C_DUALADDRESS_DISABLE) || \ ((ADDRESS) == FMPI2C_DUALADDRESS_ENABLE)) #define IS_FMPI2C_OWN_ADDRESS2_MASK(MASK) (((MASK) == FMPI2C_OA2_NOMASK) || \ ((MASK) == FMPI2C_OA2_MASK01) || \ ((MASK) == FMPI2C_OA2_MASK02) || \ ((MASK) == FMPI2C_OA2_MASK03) || \ ((MASK) == FMPI2C_OA2_MASK04) || \ ((MASK) == FMPI2C_OA2_MASK05) || \ ((MASK) == FMPI2C_OA2_MASK06) || \ ((MASK) == FMPI2C_OA2_MASK07)) #define IS_FMPI2C_GENERAL_CALL(CALL) (((CALL) == FMPI2C_GENERALCALL_DISABLE) || \ ((CALL) == FMPI2C_GENERALCALL_ENABLE)) #define IS_FMPI2C_NO_STRETCH(STRETCH) (((STRETCH) == FMPI2C_NOSTRETCH_DISABLE) || \ ((STRETCH) == FMPI2C_NOSTRETCH_ENABLE)) #define IS_FMPI2C_MEMADD_SIZE(SIZE) (((SIZE) == FMPI2C_MEMADD_SIZE_8BIT) || \ ((SIZE) == FMPI2C_MEMADD_SIZE_16BIT)) #define IS_TRANSFER_MODE(MODE) (((MODE) == FMPI2C_RELOAD_MODE) || \ ((MODE) == FMPI2C_AUTOEND_MODE) || \ ((MODE) == FMPI2C_SOFTEND_MODE)) #define IS_TRANSFER_REQUEST(REQUEST) (((REQUEST) == FMPI2C_GENERATE_STOP) || \ ((REQUEST) == FMPI2C_GENERATE_START_READ) || \ ((REQUEST) == FMPI2C_GENERATE_START_WRITE) || \ ((REQUEST) == FMPI2C_NO_STARTSTOP)) /** * @} */ /* Private functions ---------------------------------------------------------*/ /** @defgroup FMPI2C_Private_Functions FMPI2C Private Functions * @brief FMPI2C private functions * @{ */ /** * @} */ /** * @} */ /** * @} */ #endif /* STM32F410xx || STM32F446xx */ #ifdef __cplusplus } #endif #endif /* __STM32F4xx_HAL_FMPI2C_H */ /************************ (C) COPYRIGHT STMicroelectronics *****END OF FILE****/ ================================================ FILE: Zelig/mbed/TARGET_NUCLEO_F411RE/stm32f4xx_hal_fmpi2c_ex.h ================================================ /** ****************************************************************************** * @file stm32f4xx_hal_fmpi2c_ex.h * @author MCD Application Team * @version V1.4.1 * @date 09-October-2015 * @brief Header file of FMPI2C HAL Extension module. ****************************************************************************** * @attention * *

© COPYRIGHT(c) 2015 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. * ****************************************************************************** */ /* Define to prevent recursive inclusion -------------------------------------*/ #ifndef __STM32F4xx_HAL_FMPI2C_EX_H #define __STM32F4xx_HAL_FMPI2C_EX_H #ifdef __cplusplus extern "C" { #endif #if defined(STM32F410Tx) || defined(STM32F410Cx) || defined(STM32F410Rx) || defined(STM32F446xx) /* Includes ------------------------------------------------------------------*/ #include "stm32f4xx_hal_def.h" /** @addtogroup STM32F4xx_HAL_Driver * @{ */ /** @addtogroup FMPI2CEx * @{ */ /* Exported types ------------------------------------------------------------*/ /* Exported constants --------------------------------------------------------*/ /** @defgroup FMPI2CEx_Exported_Constants FMPI2C Exported Constants * @{ */ /** @defgroup FMPI2CEx_Analog_Filter FMPI2C Analog Filter * @{ */ #define FMPI2C_ANALOGFILTER_ENABLE ((uint32_t)0x00000000) #define FMPI2C_ANALOGFILTER_DISABLE FMPI2C_CR1_ANFOFF /** * @} */ /** @defgroup FMPI2CEx_FastModePlus FMPI2C Fast Mode Plus * @{ */ #define FMPI2C_FASTMODEPLUS_SCL SYSCFG_CFGR_FMPI2C1_SCL /*!< Enable Fast Mode Plus on FMPI2C1 SCL pins */ #define FMPI2C_FASTMODEPLUS_SDA SYSCFG_CFGR_FMPI2C1_SDA /*!< Enable Fast Mode Plus on FMPI2C1 SDA pins */ /** * @} */ /** * @} */ /* Exported macro ------------------------------------------------------------*/ /* Exported functions --------------------------------------------------------*/ /** @addtogroup FMPI2CEx_Exported_Functions * @{ */ /** @addtogroup FMPI2CEx_Exported_Functions_Group1 * @{ */ /* Peripheral Control functions ************************************************/ HAL_StatusTypeDef HAL_FMPI2CEx_AnalogFilter_Config(FMPI2C_HandleTypeDef *hFMPI2C, uint32_t AnalogFilter); HAL_StatusTypeDef HAL_FMPI2CEx_DigitalFilter_Config(FMPI2C_HandleTypeDef *hFMPI2C, uint32_t DigitalFilter); HAL_StatusTypeDef HAL_FMPI2CEx_EnableWakeUp (FMPI2C_HandleTypeDef *hFMPI2C); HAL_StatusTypeDef HAL_FMPI2CEx_DisableWakeUp (FMPI2C_HandleTypeDef *hFMPI2C); void HAL_FMPI2CEx_EnableFastModePlus(uint32_t ConfigFastModePlus); void HAL_FMPI2CEx_DisableFastModePlus(uint32_t ConfigFastModePlus); /** * @} */ /** * @} */ /* Private types -------------------------------------------------------------*/ /* Private variables ---------------------------------------------------------*/ /* Private constants ---------------------------------------------------------*/ /** @defgroup I2CEx_Private_Constants I2C Private Constants * @{ */ /** * @} */ /* Private macros ------------------------------------------------------------*/ /** @defgroup I2CEx_Private_Macros I2C Private Macros * @{ */ #define IS_FMPI2C_ANALOG_FILTER(FILTER) (((FILTER) == FMPI2C_ANALOGFILTER_ENABLE) || \ ((FILTER) == FMPI2C_ANALOGFILTER_DISABLE)) #define IS_FMPI2C_DIGITAL_FILTER(FILTER) ((FILTER) <= 0x0000000F) #define IS_FMPI2C_FASTMODEPLUS(__CONFIG__) ((((__CONFIG__) & (FMPI2C_FASTMODEPLUS_SCL)) == FMPI2C_FASTMODEPLUS_SCL) || \ (((__CONFIG__) & (FMPI2C_FASTMODEPLUS_SDA)) == FMPI2C_FASTMODEPLUS_SDA)) /** * @} */ /** * @} */ /** * @} */ #endif /* STM32F410xx || STM32F446xx */ #ifdef __cplusplus } #endif #endif /* __STM32F4xx_HAL_FMPI2C_EX_H */ /************************ (C) COPYRIGHT STMicroelectronics *****END OF FILE****/ ================================================ FILE: Zelig/mbed/TARGET_NUCLEO_F411RE/stm32f4xx_hal_gpio.h ================================================ /** ****************************************************************************** * @file stm32f4xx_hal_gpio.h * @author MCD Application Team * @version V1.4.1 * @date 09-October-2015 * @brief Header file of GPIO HAL module. ****************************************************************************** * @attention * *

© COPYRIGHT(c) 2015 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. * ****************************************************************************** */ /* Define to prevent recursive inclusion -------------------------------------*/ #ifndef __STM32F4xx_HAL_GPIO_H #define __STM32F4xx_HAL_GPIO_H #ifdef __cplusplus extern "C" { #endif /* Includes ------------------------------------------------------------------*/ #include "stm32f4xx_hal_def.h" /** @addtogroup STM32F4xx_HAL_Driver * @{ */ /** @addtogroup GPIO * @{ */ /* Exported types ------------------------------------------------------------*/ /** @defgroup GPIO_Exported_Types GPIO Exported Types * @{ */ /** * @brief GPIO Init structure definition */ typedef struct { uint32_t Pin; /*!< Specifies the GPIO pins to be configured. This parameter can be any value of @ref GPIO_pins_define */ uint32_t Mode; /*!< Specifies the operating mode for the selected pins. This parameter can be a value of @ref GPIO_mode_define */ uint32_t Pull; /*!< Specifies the Pull-up or Pull-Down activation for the selected pins. This parameter can be a value of @ref GPIO_pull_define */ uint32_t Speed; /*!< Specifies the speed for the selected pins. This parameter can be a value of @ref GPIO_speed_define */ uint32_t Alternate; /*!< Peripheral to be connected to the selected pins. This parameter can be a value of @ref GPIO_Alternate_function_selection */ }GPIO_InitTypeDef; /** * @brief GPIO Bit SET and Bit RESET enumeration */ typedef enum { GPIO_PIN_RESET = 0, GPIO_PIN_SET }GPIO_PinState; /** * @} */ /* Exported constants --------------------------------------------------------*/ /** @defgroup GPIO_Exported_Constants GPIO Exported Constants * @{ */ /** @defgroup GPIO_pins_define GPIO pins define * @{ */ #define GPIO_PIN_0 ((uint16_t)0x0001) /* Pin 0 selected */ #define GPIO_PIN_1 ((uint16_t)0x0002) /* Pin 1 selected */ #define GPIO_PIN_2 ((uint16_t)0x0004) /* Pin 2 selected */ #define GPIO_PIN_3 ((uint16_t)0x0008) /* Pin 3 selected */ #define GPIO_PIN_4 ((uint16_t)0x0010) /* Pin 4 selected */ #define GPIO_PIN_5 ((uint16_t)0x0020) /* Pin 5 selected */ #define GPIO_PIN_6 ((uint16_t)0x0040) /* Pin 6 selected */ #define GPIO_PIN_7 ((uint16_t)0x0080) /* Pin 7 selected */ #define GPIO_PIN_8 ((uint16_t)0x0100) /* Pin 8 selected */ #define GPIO_PIN_9 ((uint16_t)0x0200) /* Pin 9 selected */ #define GPIO_PIN_10 ((uint16_t)0x0400) /* Pin 10 selected */ #define GPIO_PIN_11 ((uint16_t)0x0800) /* Pin 11 selected */ #define GPIO_PIN_12 ((uint16_t)0x1000) /* Pin 12 selected */ #define GPIO_PIN_13 ((uint16_t)0x2000) /* Pin 13 selected */ #define GPIO_PIN_14 ((uint16_t)0x4000) /* Pin 14 selected */ #define GPIO_PIN_15 ((uint16_t)0x8000) /* Pin 15 selected */ #define GPIO_PIN_All ((uint16_t)0xFFFF) /* All pins selected */ #define GPIO_PIN_MASK ((uint32_t)0x0000FFFF) /* PIN mask for assert test */ /** * @} */ /** @defgroup GPIO_mode_define GPIO mode define * @brief GPIO Configuration Mode * Elements values convention: 0xX0yz00YZ * - X : GPIO mode or EXTI Mode * - y : External IT or Event trigger detection * - z : IO configuration on External IT or Event * - Y : Output type (Push Pull or Open Drain) * - Z : IO Direction mode (Input, Output, Alternate or Analog) * @{ */ #define GPIO_MODE_INPUT ((uint32_t)0x00000000) /*!< Input Floating Mode */ #define GPIO_MODE_OUTPUT_PP ((uint32_t)0x00000001) /*!< Output Push Pull Mode */ #define GPIO_MODE_OUTPUT_OD ((uint32_t)0x00000011) /*!< Output Open Drain Mode */ #define GPIO_MODE_AF_PP ((uint32_t)0x00000002) /*!< Alternate Function Push Pull Mode */ #define GPIO_MODE_AF_OD ((uint32_t)0x00000012) /*!< Alternate Function Open Drain Mode */ #define GPIO_MODE_ANALOG ((uint32_t)0x00000003) /*!< Analog Mode */ #define GPIO_MODE_IT_RISING ((uint32_t)0x10110000) /*!< External Interrupt Mode with Rising edge trigger detection */ #define GPIO_MODE_IT_FALLING ((uint32_t)0x10210000) /*!< External Interrupt Mode with Falling edge trigger detection */ #define GPIO_MODE_IT_RISING_FALLING ((uint32_t)0x10310000) /*!< External Interrupt Mode with Rising/Falling edge trigger detection */ #define GPIO_MODE_EVT_RISING ((uint32_t)0x10120000) /*!< External Event Mode with Rising edge trigger detection */ #define GPIO_MODE_EVT_FALLING ((uint32_t)0x10220000) /*!< External Event Mode with Falling edge trigger detection */ #define GPIO_MODE_EVT_RISING_FALLING ((uint32_t)0x10320000) /*!< External Event Mode with Rising/Falling edge trigger detection */ /** * @} */ /** @defgroup GPIO_speed_define GPIO speed define * @brief GPIO Output Maximum frequency * @{ */ #define GPIO_SPEED_FREQ_LOW ((uint32_t)0x00000000) /*!< IO works at 2 MHz, please refer to the product datasheet */ #define GPIO_SPEED_FREQ_MEDIUM ((uint32_t)0x00000001) /*!< range 12,5 MHz to 50 MHz, please refer to the product datasheet */ #define GPIO_SPEED_FREQ_HIGH ((uint32_t)0x00000002) /*!< range 25 MHz to 100 MHz, please refer to the product datasheet */ #define GPIO_SPEED_FREQ_VERY_HIGH ((uint32_t)0x00000003) /*!< range 50 MHz to 200 MHz, please refer to the product datasheet */ /** * @} */ /** @defgroup GPIO_pull_define GPIO pull define * @brief GPIO Pull-Up or Pull-Down Activation * @{ */ #define GPIO_NOPULL ((uint32_t)0x00000000) /*!< No Pull-up or Pull-down activation */ #define GPIO_PULLUP ((uint32_t)0x00000001) /*!< Pull-up activation */ #define GPIO_PULLDOWN ((uint32_t)0x00000002) /*!< Pull-down activation */ /** * @} */ /** * @} */ /* Exported macro ------------------------------------------------------------*/ /** @defgroup GPIO_Exported_Macros GPIO Exported Macros * @{ */ /** * @brief Checks whether the specified EXTI line flag is set or not. * @param __EXTI_LINE__: specifies the EXTI line flag to check. * This parameter can be GPIO_PIN_x where x can be(0..15) * @retval The new state of __EXTI_LINE__ (SET or RESET). */ #define __HAL_GPIO_EXTI_GET_FLAG(__EXTI_LINE__) (EXTI->PR & (__EXTI_LINE__)) /** * @brief Clears the EXTI's line pending flags. * @param __EXTI_LINE__: specifies the EXTI lines flags to clear. * This parameter can be any combination of GPIO_PIN_x where x can be (0..15) * @retval None */ #define __HAL_GPIO_EXTI_CLEAR_FLAG(__EXTI_LINE__) (EXTI->PR = (__EXTI_LINE__)) /** * @brief Checks whether the specified EXTI line is asserted or not. * @param __EXTI_LINE__: specifies the EXTI line to check. * This parameter can be GPIO_PIN_x where x can be(0..15) * @retval The new state of __EXTI_LINE__ (SET or RESET). */ #define __HAL_GPIO_EXTI_GET_IT(__EXTI_LINE__) (EXTI->PR & (__EXTI_LINE__)) /** * @brief Clears the EXTI's line pending bits. * @param __EXTI_LINE__: specifies the EXTI lines to clear. * This parameter can be any combination of GPIO_PIN_x where x can be (0..15) * @retval None */ #define __HAL_GPIO_EXTI_CLEAR_IT(__EXTI_LINE__) (EXTI->PR = (__EXTI_LINE__)) /** * @brief Generates a Software interrupt on selected EXTI line. * @param __EXTI_LINE__: specifies the EXTI line to check. * This parameter can be GPIO_PIN_x where x can be(0..15) * @retval None */ #define __HAL_GPIO_EXTI_GENERATE_SWIT(__EXTI_LINE__) (EXTI->SWIER |= (__EXTI_LINE__)) /** * @} */ /* Include GPIO HAL Extension module */ #include "stm32f4xx_hal_gpio_ex.h" /* Exported functions --------------------------------------------------------*/ /** @addtogroup GPIO_Exported_Functions * @{ */ /** @addtogroup GPIO_Exported_Functions_Group1 * @{ */ /* Initialization and de-initialization functions *****************************/ void HAL_GPIO_Init(GPIO_TypeDef *GPIOx, GPIO_InitTypeDef *GPIO_Init); void HAL_GPIO_DeInit(GPIO_TypeDef *GPIOx, uint32_t GPIO_Pin); /** * @} */ /** @addtogroup GPIO_Exported_Functions_Group2 * @{ */ /* IO operation functions *****************************************************/ GPIO_PinState HAL_GPIO_ReadPin(GPIO_TypeDef* GPIOx, uint16_t GPIO_Pin); void HAL_GPIO_WritePin(GPIO_TypeDef* GPIOx, uint16_t GPIO_Pin, GPIO_PinState PinState); void HAL_GPIO_TogglePin(GPIO_TypeDef* GPIOx, uint16_t GPIO_Pin); HAL_StatusTypeDef HAL_GPIO_LockPin(GPIO_TypeDef* GPIOx, uint16_t GPIO_Pin); void HAL_GPIO_EXTI_IRQHandler(uint16_t GPIO_Pin); void HAL_GPIO_EXTI_Callback(uint16_t GPIO_Pin); /** * @} */ /** * @} */ /* Private types -------------------------------------------------------------*/ /* Private variables ---------------------------------------------------------*/ /* Private constants ---------------------------------------------------------*/ /** @defgroup GPIO_Private_Constants GPIO Private Constants * @{ */ /** * @} */ /* Private macros ------------------------------------------------------------*/ /** @defgroup GPIO_Private_Macros GPIO Private Macros * @{ */ #define IS_GPIO_PIN_ACTION(ACTION) (((ACTION) == GPIO_PIN_RESET) || ((ACTION) == GPIO_PIN_SET)) #define IS_GPIO_PIN(PIN) (((PIN) & GPIO_PIN_MASK ) != (uint32_t)0x00) #define IS_GPIO_MODE(MODE) (((MODE) == GPIO_MODE_INPUT) ||\ ((MODE) == GPIO_MODE_OUTPUT_PP) ||\ ((MODE) == GPIO_MODE_OUTPUT_OD) ||\ ((MODE) == GPIO_MODE_AF_PP) ||\ ((MODE) == GPIO_MODE_AF_OD) ||\ ((MODE) == GPIO_MODE_IT_RISING) ||\ ((MODE) == GPIO_MODE_IT_FALLING) ||\ ((MODE) == GPIO_MODE_IT_RISING_FALLING) ||\ ((MODE) == GPIO_MODE_EVT_RISING) ||\ ((MODE) == GPIO_MODE_EVT_FALLING) ||\ ((MODE) == GPIO_MODE_EVT_RISING_FALLING) ||\ ((MODE) == GPIO_MODE_ANALOG)) #define IS_GPIO_SPEED(SPEED) (((SPEED) == GPIO_SPEED_FREQ_LOW) || ((SPEED) == GPIO_SPEED_FREQ_MEDIUM) || \ ((SPEED) == GPIO_SPEED_FREQ_HIGH) || ((SPEED) == GPIO_SPEED_FREQ_VERY_HIGH)) #define IS_GPIO_PULL(PULL) (((PULL) == GPIO_NOPULL) || ((PULL) == GPIO_PULLUP) || \ ((PULL) == GPIO_PULLDOWN)) /** * @} */ /* Private functions ---------------------------------------------------------*/ /** @defgroup GPIO_Private_Functions GPIO Private Functions * @{ */ /** * @} */ /** * @} */ /** * @} */ #ifdef __cplusplus } #endif #endif /* __STM32F4xx_HAL_GPIO_H */ /************************ (C) COPYRIGHT STMicroelectronics *****END OF FILE****/ ================================================ FILE: Zelig/mbed/TARGET_NUCLEO_F411RE/stm32f4xx_hal_gpio_ex.h ================================================ /** ****************************************************************************** * @file stm32f4xx_hal_gpio_ex.h * @author MCD Application Team * @version V1.4.1 * @date 09-October-2015 * @brief Header file of GPIO HAL Extension module. ****************************************************************************** * @attention * *

© COPYRIGHT(c) 2015 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. * ****************************************************************************** */ /* Define to prevent recursive inclusion -------------------------------------*/ #ifndef __STM32F4xx_HAL_GPIO_EX_H #define __STM32F4xx_HAL_GPIO_EX_H #ifdef __cplusplus extern "C" { #endif /* Includes ------------------------------------------------------------------*/ #include "stm32f4xx_hal_def.h" /** @addtogroup STM32F4xx_HAL_Driver * @{ */ /** @defgroup GPIOEx GPIOEx * @{ */ /* Exported types ------------------------------------------------------------*/ /* Exported constants --------------------------------------------------------*/ /** @defgroup GPIOEx_Exported_Constants GPIO Exported Constants * @{ */ /** @defgroup GPIO_Alternate_function_selection GPIO Alternate Function Selection * @{ */ /*------------------------------------------ STM32F429xx/STM32F439xx ---------*/ #if defined(STM32F429xx) || defined(STM32F439xx) /** * @brief AF 0 selection */ #define GPIO_AF0_RTC_50Hz ((uint8_t)0x00) /* RTC_50Hz Alternate Function mapping */ #define GPIO_AF0_MCO ((uint8_t)0x00) /* MCO (MCO1 and MCO2) Alternate Function mapping */ #define GPIO_AF0_TAMPER ((uint8_t)0x00) /* TAMPER (TAMPER_1 and TAMPER_2) Alternate Function mapping */ #define GPIO_AF0_SWJ ((uint8_t)0x00) /* SWJ (SWD and JTAG) Alternate Function mapping */ #define GPIO_AF0_TRACE ((uint8_t)0x00) /* TRACE Alternate Function mapping */ /** * @brief AF 1 selection */ #define GPIO_AF1_TIM1 ((uint8_t)0x01) /* TIM1 Alternate Function mapping */ #define GPIO_AF1_TIM2 ((uint8_t)0x01) /* TIM2 Alternate Function mapping */ /** * @brief AF 2 selection */ #define GPIO_AF2_TIM3 ((uint8_t)0x02) /* TIM3 Alternate Function mapping */ #define GPIO_AF2_TIM4 ((uint8_t)0x02) /* TIM4 Alternate Function mapping */ #define GPIO_AF2_TIM5 ((uint8_t)0x02) /* TIM5 Alternate Function mapping */ /** * @brief AF 3 selection */ #define GPIO_AF3_TIM8 ((uint8_t)0x03) /* TIM8 Alternate Function mapping */ #define GPIO_AF3_TIM9 ((uint8_t)0x03) /* TIM9 Alternate Function mapping */ #define GPIO_AF3_TIM10 ((uint8_t)0x03) /* TIM10 Alternate Function mapping */ #define GPIO_AF3_TIM11 ((uint8_t)0x03) /* TIM11 Alternate Function mapping */ /** * @brief AF 4 selection */ #define GPIO_AF4_I2C1 ((uint8_t)0x04) /* I2C1 Alternate Function mapping */ #define GPIO_AF4_I2C2 ((uint8_t)0x04) /* I2C2 Alternate Function mapping */ #define GPIO_AF4_I2C3 ((uint8_t)0x04) /* I2C3 Alternate Function mapping */ /** * @brief AF 5 selection */ #define GPIO_AF5_SPI1 ((uint8_t)0x05) /* SPI1 Alternate Function mapping */ #define GPIO_AF5_SPI2 ((uint8_t)0x05) /* SPI2/I2S2 Alternate Function mapping */ #define GPIO_AF5_SPI3 ((uint8_t)0x05) /* SPI3/I2S3 Alternate Function mapping */ #define GPIO_AF5_SPI4 ((uint8_t)0x05) /* SPI4 Alternate Function mapping */ #define GPIO_AF5_SPI5 ((uint8_t)0x05) /* SPI5 Alternate Function mapping */ #define GPIO_AF5_SPI6 ((uint8_t)0x05) /* SPI6 Alternate Function mapping */ #define GPIO_AF5_I2S3ext ((uint8_t)0x05) /* I2S3ext_SD Alternate Function mapping */ /** * @brief AF 6 selection */ #define GPIO_AF6_SPI3 ((uint8_t)0x06) /* SPI3/I2S3 Alternate Function mapping */ #define GPIO_AF6_I2S2ext ((uint8_t)0x06) /* I2S2ext_SD Alternate Function mapping */ #define GPIO_AF6_SAI1 ((uint8_t)0x06) /* SAI1 Alternate Function mapping */ /** * @brief AF 7 selection */ #define GPIO_AF7_USART1 ((uint8_t)0x07) /* USART1 Alternate Function mapping */ #define GPIO_AF7_USART2 ((uint8_t)0x07) /* USART2 Alternate Function mapping */ #define GPIO_AF7_USART3 ((uint8_t)0x07) /* USART3 Alternate Function mapping */ #define GPIO_AF7_I2S3ext ((uint8_t)0x07) /* I2S3ext_SD Alternate Function mapping */ /** * @brief AF 8 selection */ #define GPIO_AF8_UART4 ((uint8_t)0x08) /* UART4 Alternate Function mapping */ #define GPIO_AF8_UART5 ((uint8_t)0x08) /* UART5 Alternate Function mapping */ #define GPIO_AF8_USART6 ((uint8_t)0x08) /* USART6 Alternate Function mapping */ #define GPIO_AF8_UART7 ((uint8_t)0x08) /* UART7 Alternate Function mapping */ #define GPIO_AF8_UART8 ((uint8_t)0x08) /* UART8 Alternate Function mapping */ /** * @brief AF 9 selection */ #define GPIO_AF9_CAN1 ((uint8_t)0x09) /* CAN1 Alternate Function mapping */ #define GPIO_AF9_CAN2 ((uint8_t)0x09) /* CAN2 Alternate Function mapping */ #define GPIO_AF9_TIM12 ((uint8_t)0x09) /* TIM12 Alternate Function mapping */ #define GPIO_AF9_TIM13 ((uint8_t)0x09) /* TIM13 Alternate Function mapping */ #define GPIO_AF9_TIM14 ((uint8_t)0x09) /* TIM14 Alternate Function mapping */ #define GPIO_AF9_LTDC ((uint8_t)0x09) /* LCD-TFT Alternate Function mapping */ /** * @brief AF 10 selection */ #define GPIO_AF10_OTG_FS ((uint8_t)0xA) /* OTG_FS Alternate Function mapping */ #define GPIO_AF10_OTG_HS ((uint8_t)0xA) /* OTG_HS Alternate Function mapping */ /** * @brief AF 11 selection */ #define GPIO_AF11_ETH ((uint8_t)0x0B) /* ETHERNET Alternate Function mapping */ /** * @brief AF 12 selection */ #define GPIO_AF12_FMC ((uint8_t)0xC) /* FMC Alternate Function mapping */ #define GPIO_AF12_OTG_HS_FS ((uint8_t)0xC) /* OTG HS configured in FS, Alternate Function mapping */ #define GPIO_AF12_SDIO ((uint8_t)0xC) /* SDIO Alternate Function mapping */ /** * @brief AF 13 selection */ #define GPIO_AF13_DCMI ((uint8_t)0x0D) /* DCMI Alternate Function mapping */ /** * @brief AF 14 selection */ #define GPIO_AF14_LTDC ((uint8_t)0x0E) /* LCD-TFT Alternate Function mapping */ /** * @brief AF 15 selection */ #define GPIO_AF15_EVENTOUT ((uint8_t)0x0F) /* EVENTOUT Alternate Function mapping */ #endif /* STM32F429xx || STM32F439xx */ /*----------------------------------------------------------------------------*/ /*---------------------------------- STM32F427xx/STM32F437xx------------------*/ #if defined(STM32F427xx) || defined(STM32F437xx) /** * @brief AF 0 selection */ #define GPIO_AF0_RTC_50Hz ((uint8_t)0x00) /* RTC_50Hz Alternate Function mapping */ #define GPIO_AF0_MCO ((uint8_t)0x00) /* MCO (MCO1 and MCO2) Alternate Function mapping */ #define GPIO_AF0_TAMPER ((uint8_t)0x00) /* TAMPER (TAMPER_1 and TAMPER_2) Alternate Function mapping */ #define GPIO_AF0_SWJ ((uint8_t)0x00) /* SWJ (SWD and JTAG) Alternate Function mapping */ #define GPIO_AF0_TRACE ((uint8_t)0x00) /* TRACE Alternate Function mapping */ /** * @brief AF 1 selection */ #define GPIO_AF1_TIM1 ((uint8_t)0x01) /* TIM1 Alternate Function mapping */ #define GPIO_AF1_TIM2 ((uint8_t)0x01) /* TIM2 Alternate Function mapping */ /** * @brief AF 2 selection */ #define GPIO_AF2_TIM3 ((uint8_t)0x02) /* TIM3 Alternate Function mapping */ #define GPIO_AF2_TIM4 ((uint8_t)0x02) /* TIM4 Alternate Function mapping */ #define GPIO_AF2_TIM5 ((uint8_t)0x02) /* TIM5 Alternate Function mapping */ /** * @brief AF 3 selection */ #define GPIO_AF3_TIM8 ((uint8_t)0x03) /* TIM8 Alternate Function mapping */ #define GPIO_AF3_TIM9 ((uint8_t)0x03) /* TIM9 Alternate Function mapping */ #define GPIO_AF3_TIM10 ((uint8_t)0x03) /* TIM10 Alternate Function mapping */ #define GPIO_AF3_TIM11 ((uint8_t)0x03) /* TIM11 Alternate Function mapping */ /** * @brief AF 4 selection */ #define GPIO_AF4_I2C1 ((uint8_t)0x04) /* I2C1 Alternate Function mapping */ #define GPIO_AF4_I2C2 ((uint8_t)0x04) /* I2C2 Alternate Function mapping */ #define GPIO_AF4_I2C3 ((uint8_t)0x04) /* I2C3 Alternate Function mapping */ /** * @brief AF 5 selection */ #define GPIO_AF5_SPI1 ((uint8_t)0x05) /* SPI1 Alternate Function mapping */ #define GPIO_AF5_SPI2 ((uint8_t)0x05) /* SPI2/I2S2 Alternate Function mapping */ #define GPIO_AF5_SPI3 ((uint8_t)0x05) /* SPI3/I2S3 Alternate Function mapping */ #define GPIO_AF5_SPI4 ((uint8_t)0x05) /* SPI4 Alternate Function mapping */ #define GPIO_AF5_SPI5 ((uint8_t)0x05) /* SPI5 Alternate Function mapping */ #define GPIO_AF5_SPI6 ((uint8_t)0x05) /* SPI6 Alternate Function mapping */ /** @brief GPIO_Legacy */ #define GPIO_AF5_I2S3ext GPIO_AF5_SPI3 /* I2S3ext_SD Alternate Function mapping */ /** * @brief AF 6 selection */ #define GPIO_AF6_SPI3 ((uint8_t)0x06) /* SPI3/I2S3 Alternate Function mapping */ #define GPIO_AF6_I2S2ext ((uint8_t)0x06) /* I2S2ext_SD Alternate Function mapping */ #define GPIO_AF6_SAI1 ((uint8_t)0x06) /* SAI1 Alternate Function mapping */ /** * @brief AF 7 selection */ #define GPIO_AF7_USART1 ((uint8_t)0x07) /* USART1 Alternate Function mapping */ #define GPIO_AF7_USART2 ((uint8_t)0x07) /* USART2 Alternate Function mapping */ #define GPIO_AF7_USART3 ((uint8_t)0x07) /* USART3 Alternate Function mapping */ #define GPIO_AF7_I2S3ext ((uint8_t)0x07) /* I2S3ext_SD Alternate Function mapping */ /** * @brief AF 8 selection */ #define GPIO_AF8_UART4 ((uint8_t)0x08) /* UART4 Alternate Function mapping */ #define GPIO_AF8_UART5 ((uint8_t)0x08) /* UART5 Alternate Function mapping */ #define GPIO_AF8_USART6 ((uint8_t)0x08) /* USART6 Alternate Function mapping */ #define GPIO_AF8_UART7 ((uint8_t)0x08) /* UART7 Alternate Function mapping */ #define GPIO_AF8_UART8 ((uint8_t)0x08) /* UART8 Alternate Function mapping */ /** * @brief AF 9 selection */ #define GPIO_AF9_CAN1 ((uint8_t)0x09) /* CAN1 Alternate Function mapping */ #define GPIO_AF9_CAN2 ((uint8_t)0x09) /* CAN2 Alternate Function mapping */ #define GPIO_AF9_TIM12 ((uint8_t)0x09) /* TIM12 Alternate Function mapping */ #define GPIO_AF9_TIM13 ((uint8_t)0x09) /* TIM13 Alternate Function mapping */ #define GPIO_AF9_TIM14 ((uint8_t)0x09) /* TIM14 Alternate Function mapping */ /** * @brief AF 10 selection */ #define GPIO_AF10_OTG_FS ((uint8_t)0xA) /* OTG_FS Alternate Function mapping */ #define GPIO_AF10_OTG_HS ((uint8_t)0xA) /* OTG_HS Alternate Function mapping */ /** * @brief AF 11 selection */ #define GPIO_AF11_ETH ((uint8_t)0x0B) /* ETHERNET Alternate Function mapping */ /** * @brief AF 12 selection */ #define GPIO_AF12_FMC ((uint8_t)0xC) /* FMC Alternate Function mapping */ #define GPIO_AF12_OTG_HS_FS ((uint8_t)0xC) /* OTG HS configured in FS, Alternate Function mapping */ #define GPIO_AF12_SDIO ((uint8_t)0xC) /* SDIO Alternate Function mapping */ /** * @brief AF 13 selection */ #define GPIO_AF13_DCMI ((uint8_t)0x0D) /* DCMI Alternate Function mapping */ /** * @brief AF 15 selection */ #define GPIO_AF15_EVENTOUT ((uint8_t)0x0F) /* EVENTOUT Alternate Function mapping */ #endif /* STM32F427xx || STM32F437xx */ /*----------------------------------------------------------------------------*/ /*---------------------------------- STM32F407xx/STM32F417xx------------------*/ #if defined(STM32F407xx) || defined(STM32F417xx) /** * @brief AF 0 selection */ #define GPIO_AF0_RTC_50Hz ((uint8_t)0x00) /* RTC_50Hz Alternate Function mapping */ #define GPIO_AF0_MCO ((uint8_t)0x00) /* MCO (MCO1 and MCO2) Alternate Function mapping */ #define GPIO_AF0_TAMPER ((uint8_t)0x00) /* TAMPER (TAMPER_1 and TAMPER_2) Alternate Function mapping */ #define GPIO_AF0_SWJ ((uint8_t)0x00) /* SWJ (SWD and JTAG) Alternate Function mapping */ #define GPIO_AF0_TRACE ((uint8_t)0x00) /* TRACE Alternate Function mapping */ /** * @brief AF 1 selection */ #define GPIO_AF1_TIM1 ((uint8_t)0x01) /* TIM1 Alternate Function mapping */ #define GPIO_AF1_TIM2 ((uint8_t)0x01) /* TIM2 Alternate Function mapping */ /** * @brief AF 2 selection */ #define GPIO_AF2_TIM3 ((uint8_t)0x02) /* TIM3 Alternate Function mapping */ #define GPIO_AF2_TIM4 ((uint8_t)0x02) /* TIM4 Alternate Function mapping */ #define GPIO_AF2_TIM5 ((uint8_t)0x02) /* TIM5 Alternate Function mapping */ /** * @brief AF 3 selection */ #define GPIO_AF3_TIM8 ((uint8_t)0x03) /* TIM8 Alternate Function mapping */ #define GPIO_AF3_TIM9 ((uint8_t)0x03) /* TIM9 Alternate Function mapping */ #define GPIO_AF3_TIM10 ((uint8_t)0x03) /* TIM10 Alternate Function mapping */ #define GPIO_AF3_TIM11 ((uint8_t)0x03) /* TIM11 Alternate Function mapping */ /** * @brief AF 4 selection */ #define GPIO_AF4_I2C1 ((uint8_t)0x04) /* I2C1 Alternate Function mapping */ #define GPIO_AF4_I2C2 ((uint8_t)0x04) /* I2C2 Alternate Function mapping */ #define GPIO_AF4_I2C3 ((uint8_t)0x04) /* I2C3 Alternate Function mapping */ /** * @brief AF 5 selection */ #define GPIO_AF5_SPI1 ((uint8_t)0x05) /* SPI1 Alternate Function mapping */ #define GPIO_AF5_SPI2 ((uint8_t)0x05) /* SPI2/I2S2 Alternate Function mapping */ #define GPIO_AF5_I2S3ext ((uint8_t)0x05) /* I2S3ext_SD Alternate Function mapping */ /** * @brief AF 6 selection */ #define GPIO_AF6_SPI3 ((uint8_t)0x06) /* SPI3/I2S3 Alternate Function mapping */ #define GPIO_AF6_I2S2ext ((uint8_t)0x06) /* I2S2ext_SD Alternate Function mapping */ /** * @brief AF 7 selection */ #define GPIO_AF7_USART1 ((uint8_t)0x07) /* USART1 Alternate Function mapping */ #define GPIO_AF7_USART2 ((uint8_t)0x07) /* USART2 Alternate Function mapping */ #define GPIO_AF7_USART3 ((uint8_t)0x07) /* USART3 Alternate Function mapping */ #define GPIO_AF7_I2S3ext ((uint8_t)0x07) /* I2S3ext_SD Alternate Function mapping */ /** * @brief AF 8 selection */ #define GPIO_AF8_UART4 ((uint8_t)0x08) /* UART4 Alternate Function mapping */ #define GPIO_AF8_UART5 ((uint8_t)0x08) /* UART5 Alternate Function mapping */ #define GPIO_AF8_USART6 ((uint8_t)0x08) /* USART6 Alternate Function mapping */ /** * @brief AF 9 selection */ #define GPIO_AF9_CAN1 ((uint8_t)0x09) /* CAN1 Alternate Function mapping */ #define GPIO_AF9_CAN2 ((uint8_t)0x09) /* CAN2 Alternate Function mapping */ #define GPIO_AF9_TIM12 ((uint8_t)0x09) /* TIM12 Alternate Function mapping */ #define GPIO_AF9_TIM13 ((uint8_t)0x09) /* TIM13 Alternate Function mapping */ #define GPIO_AF9_TIM14 ((uint8_t)0x09) /* TIM14 Alternate Function mapping */ /** * @brief AF 10 selection */ #define GPIO_AF10_OTG_FS ((uint8_t)0xA) /* OTG_FS Alternate Function mapping */ #define GPIO_AF10_OTG_HS ((uint8_t)0xA) /* OTG_HS Alternate Function mapping */ /** * @brief AF 11 selection */ #define GPIO_AF11_ETH ((uint8_t)0x0B) /* ETHERNET Alternate Function mapping */ /** * @brief AF 12 selection */ #define GPIO_AF12_FSMC ((uint8_t)0xC) /* FSMC Alternate Function mapping */ #define GPIO_AF12_OTG_HS_FS ((uint8_t)0xC) /* OTG HS configured in FS, Alternate Function mapping */ #define GPIO_AF12_SDIO ((uint8_t)0xC) /* SDIO Alternate Function mapping */ /** * @brief AF 13 selection */ #define GPIO_AF13_DCMI ((uint8_t)0x0D) /* DCMI Alternate Function mapping */ /** * @brief AF 15 selection */ #define GPIO_AF15_EVENTOUT ((uint8_t)0x0F) /* EVENTOUT Alternate Function mapping */ #endif /* STM32F407xx || STM32F417xx */ /*----------------------------------------------------------------------------*/ /*---------------------------------- STM32F405xx/STM32F415xx------------------*/ #if defined(STM32F405xx) || defined(STM32F415xx) /** * @brief AF 0 selection */ #define GPIO_AF0_RTC_50Hz ((uint8_t)0x00) /* RTC_50Hz Alternate Function mapping */ #define GPIO_AF0_MCO ((uint8_t)0x00) /* MCO (MCO1 and MCO2) Alternate Function mapping */ #define GPIO_AF0_TAMPER ((uint8_t)0x00) /* TAMPER (TAMPER_1 and TAMPER_2) Alternate Function mapping */ #define GPIO_AF0_SWJ ((uint8_t)0x00) /* SWJ (SWD and JTAG) Alternate Function mapping */ #define GPIO_AF0_TRACE ((uint8_t)0x00) /* TRACE Alternate Function mapping */ /** * @brief AF 1 selection */ #define GPIO_AF1_TIM1 ((uint8_t)0x01) /* TIM1 Alternate Function mapping */ #define GPIO_AF1_TIM2 ((uint8_t)0x01) /* TIM2 Alternate Function mapping */ /** * @brief AF 2 selection */ #define GPIO_AF2_TIM3 ((uint8_t)0x02) /* TIM3 Alternate Function mapping */ #define GPIO_AF2_TIM4 ((uint8_t)0x02) /* TIM4 Alternate Function mapping */ #define GPIO_AF2_TIM5 ((uint8_t)0x02) /* TIM5 Alternate Function mapping */ /** * @brief AF 3 selection */ #define GPIO_AF3_TIM8 ((uint8_t)0x03) /* TIM8 Alternate Function mapping */ #define GPIO_AF3_TIM9 ((uint8_t)0x03) /* TIM9 Alternate Function mapping */ #define GPIO_AF3_TIM10 ((uint8_t)0x03) /* TIM10 Alternate Function mapping */ #define GPIO_AF3_TIM11 ((uint8_t)0x03) /* TIM11 Alternate Function mapping */ /** * @brief AF 4 selection */ #define GPIO_AF4_I2C1 ((uint8_t)0x04) /* I2C1 Alternate Function mapping */ #define GPIO_AF4_I2C2 ((uint8_t)0x04) /* I2C2 Alternate Function mapping */ #define GPIO_AF4_I2C3 ((uint8_t)0x04) /* I2C3 Alternate Function mapping */ /** * @brief AF 5 selection */ #define GPIO_AF5_SPI1 ((uint8_t)0x05) /* SPI1 Alternate Function mapping */ #define GPIO_AF5_SPI2 ((uint8_t)0x05) /* SPI2/I2S2 Alternate Function mapping */ #define GPIO_AF5_I2S3ext ((uint8_t)0x05) /* I2S3ext_SD Alternate Function mapping */ /** * @brief AF 6 selection */ #define GPIO_AF6_SPI3 ((uint8_t)0x06) /* SPI3/I2S3 Alternate Function mapping */ #define GPIO_AF6_I2S2ext ((uint8_t)0x06) /* I2S2ext_SD Alternate Function mapping */ /** * @brief AF 7 selection */ #define GPIO_AF7_USART1 ((uint8_t)0x07) /* USART1 Alternate Function mapping */ #define GPIO_AF7_USART2 ((uint8_t)0x07) /* USART2 Alternate Function mapping */ #define GPIO_AF7_USART3 ((uint8_t)0x07) /* USART3 Alternate Function mapping */ #define GPIO_AF7_I2S3ext ((uint8_t)0x07) /* I2S3ext_SD Alternate Function mapping */ /** * @brief AF 8 selection */ #define GPIO_AF8_UART4 ((uint8_t)0x08) /* UART4 Alternate Function mapping */ #define GPIO_AF8_UART5 ((uint8_t)0x08) /* UART5 Alternate Function mapping */ #define GPIO_AF8_USART6 ((uint8_t)0x08) /* USART6 Alternate Function mapping */ /** * @brief AF 9 selection */ #define GPIO_AF9_CAN1 ((uint8_t)0x09) /* CAN1 Alternate Function mapping */ #define GPIO_AF9_CAN2 ((uint8_t)0x09) /* CAN2 Alternate Function mapping */ #define GPIO_AF9_TIM12 ((uint8_t)0x09) /* TIM12 Alternate Function mapping */ #define GPIO_AF9_TIM13 ((uint8_t)0x09) /* TIM13 Alternate Function mapping */ #define GPIO_AF9_TIM14 ((uint8_t)0x09) /* TIM14 Alternate Function mapping */ /** * @brief AF 10 selection */ #define GPIO_AF10_OTG_FS ((uint8_t)0xA) /* OTG_FS Alternate Function mapping */ #define GPIO_AF10_OTG_HS ((uint8_t)0xA) /* OTG_HS Alternate Function mapping */ /** * @brief AF 12 selection */ #define GPIO_AF12_FSMC ((uint8_t)0xC) /* FSMC Alternate Function mapping */ #define GPIO_AF12_OTG_HS_FS ((uint8_t)0xC) /* OTG HS configured in FS, Alternate Function mapping */ #define GPIO_AF12_SDIO ((uint8_t)0xC) /* SDIO Alternate Function mapping */ /** * @brief AF 15 selection */ #define GPIO_AF15_EVENTOUT ((uint8_t)0x0F) /* EVENTOUT Alternate Function mapping */ #endif /* STM32F405xx || STM32F415xx */ /*----------------------------------------------------------------------------*/ /*---------------------------------------- STM32F401xx------------------------*/ #if defined(STM32F401xC) || defined(STM32F401xE) /** * @brief AF 0 selection */ #define GPIO_AF0_RTC_50Hz ((uint8_t)0x00) /* RTC_50Hz Alternate Function mapping */ #define GPIO_AF0_MCO ((uint8_t)0x00) /* MCO (MCO1 and MCO2) Alternate Function mapping */ #define GPIO_AF0_TAMPER ((uint8_t)0x00) /* TAMPER (TAMPER_1 and TAMPER_2) Alternate Function mapping */ #define GPIO_AF0_SWJ ((uint8_t)0x00) /* SWJ (SWD and JTAG) Alternate Function mapping */ #define GPIO_AF0_TRACE ((uint8_t)0x00) /* TRACE Alternate Function mapping */ /** * @brief AF 1 selection */ #define GPIO_AF1_TIM1 ((uint8_t)0x01) /* TIM1 Alternate Function mapping */ #define GPIO_AF1_TIM2 ((uint8_t)0x01) /* TIM2 Alternate Function mapping */ /** * @brief AF 2 selection */ #define GPIO_AF2_TIM3 ((uint8_t)0x02) /* TIM3 Alternate Function mapping */ #define GPIO_AF2_TIM4 ((uint8_t)0x02) /* TIM4 Alternate Function mapping */ #define GPIO_AF2_TIM5 ((uint8_t)0x02) /* TIM5 Alternate Function mapping */ /** * @brief AF 3 selection */ #define GPIO_AF3_TIM9 ((uint8_t)0x03) /* TIM9 Alternate Function mapping */ #define GPIO_AF3_TIM10 ((uint8_t)0x03) /* TIM10 Alternate Function mapping */ #define GPIO_AF3_TIM11 ((uint8_t)0x03) /* TIM11 Alternate Function mapping */ /** * @brief AF 4 selection */ #define GPIO_AF4_I2C1 ((uint8_t)0x04) /* I2C1 Alternate Function mapping */ #define GPIO_AF4_I2C2 ((uint8_t)0x04) /* I2C2 Alternate Function mapping */ #define GPIO_AF4_I2C3 ((uint8_t)0x04) /* I2C3 Alternate Function mapping */ /** * @brief AF 5 selection */ #define GPIO_AF5_SPI1 ((uint8_t)0x05) /* SPI1 Alternate Function mapping */ #define GPIO_AF5_SPI2 ((uint8_t)0x05) /* SPI2/I2S2 Alternate Function mapping */ #define GPIO_AF5_SPI4 ((uint8_t)0x05) /* SPI4 Alternate Function mapping */ #define GPIO_AF5_I2S3ext ((uint8_t)0x05) /* I2S3ext_SD Alternate Function mapping */ /** * @brief AF 6 selection */ #define GPIO_AF6_SPI3 ((uint8_t)0x06) /* SPI3/I2S3 Alternate Function mapping */ #define GPIO_AF6_I2S2ext ((uint8_t)0x06) /* I2S2ext_SD Alternate Function mapping */ /** * @brief AF 7 selection */ #define GPIO_AF7_USART1 ((uint8_t)0x07) /* USART1 Alternate Function mapping */ #define GPIO_AF7_USART2 ((uint8_t)0x07) /* USART2 Alternate Function mapping */ #define GPIO_AF7_I2S3ext ((uint8_t)0x07) /* I2S3ext_SD Alternate Function mapping */ /** * @brief AF 8 selection */ #define GPIO_AF8_USART6 ((uint8_t)0x08) /* USART6 Alternate Function mapping */ /** * @brief AF 9 selection */ #define GPIO_AF9_TIM14 ((uint8_t)0x09) /* TIM14 Alternate Function mapping */ #define GPIO_AF9_I2C2 ((uint8_t)0x09) /* I2C2 Alternate Function mapping */ #define GPIO_AF9_I2C3 ((uint8_t)0x09) /* I2C3 Alternate Function mapping */ /** * @brief AF 10 selection */ #define GPIO_AF10_OTG_FS ((uint8_t)0xA) /* OTG_FS Alternate Function mapping */ /** * @brief AF 12 selection */ #define GPIO_AF12_SDIO ((uint8_t)0xC) /* SDIO Alternate Function mapping */ /** * @brief AF 15 selection */ #define GPIO_AF15_EVENTOUT ((uint8_t)0x0F) /* EVENTOUT Alternate Function mapping */ #endif /* STM32F401xC || STM32F401xE */ /*----------------------------------------------------------------------------*/ /*---------------------------------------- STM32F411xx------------------------*/ #if defined(STM32F411xE) /** * @brief AF 0 selection */ #define GPIO_AF0_RTC_50Hz ((uint8_t)0x00) /* RTC_50Hz Alternate Function mapping */ #define GPIO_AF0_MCO ((uint8_t)0x00) /* MCO (MCO1 and MCO2) Alternate Function mapping */ #define GPIO_AF0_TAMPER ((uint8_t)0x00) /* TAMPER (TAMPER_1 and TAMPER_2) Alternate Function mapping */ #define GPIO_AF0_SWJ ((uint8_t)0x00) /* SWJ (SWD and JTAG) Alternate Function mapping */ #define GPIO_AF0_TRACE ((uint8_t)0x00) /* TRACE Alternate Function mapping */ /** * @brief AF 1 selection */ #define GPIO_AF1_TIM1 ((uint8_t)0x01) /* TIM1 Alternate Function mapping */ #define GPIO_AF1_TIM2 ((uint8_t)0x01) /* TIM2 Alternate Function mapping */ /** * @brief AF 2 selection */ #define GPIO_AF2_TIM3 ((uint8_t)0x02) /* TIM3 Alternate Function mapping */ #define GPIO_AF2_TIM4 ((uint8_t)0x02) /* TIM4 Alternate Function mapping */ #define GPIO_AF2_TIM5 ((uint8_t)0x02) /* TIM5 Alternate Function mapping */ /** * @brief AF 3 selection */ #define GPIO_AF3_TIM9 ((uint8_t)0x03) /* TIM9 Alternate Function mapping */ #define GPIO_AF3_TIM10 ((uint8_t)0x03) /* TIM10 Alternate Function mapping */ #define GPIO_AF3_TIM11 ((uint8_t)0x03) /* TIM11 Alternate Function mapping */ /** * @brief AF 4 selection */ #define GPIO_AF4_I2C1 ((uint8_t)0x04) /* I2C1 Alternate Function mapping */ #define GPIO_AF4_I2C2 ((uint8_t)0x04) /* I2C2 Alternate Function mapping */ #define GPIO_AF4_I2C3 ((uint8_t)0x04) /* I2C3 Alternate Function mapping */ /** * @brief AF 5 selection */ #define GPIO_AF5_SPI1 ((uint8_t)0x05) /* SPI1/I2S1 Alternate Function mapping */ #define GPIO_AF5_SPI2 ((uint8_t)0x05) /* SPI2/I2S2 Alternate Function mapping */ #define GPIO_AF5_SPI3 ((uint8_t)0x05) /* SPI3/I2S3 Alternate Function mapping */ #define GPIO_AF5_SPI4 ((uint8_t)0x05) /* SPI4 Alternate Function mapping */ #define GPIO_AF5_I2S3ext ((uint8_t)0x05) /* I2S3ext_SD Alternate Function mapping */ /** * @brief AF 6 selection */ #define GPIO_AF6_SPI2 ((uint8_t)0x06) /* I2S2 Alternate Function mapping */ #define GPIO_AF6_SPI3 ((uint8_t)0x06) /* SPI3/I2S3 Alternate Function mapping */ #define GPIO_AF6_SPI4 ((uint8_t)0x06) /* SPI4/I2S4 Alternate Function mapping */ #define GPIO_AF6_SPI5 ((uint8_t)0x06) /* SPI5/I2S5 Alternate Function mapping */ #define GPIO_AF6_I2S2ext ((uint8_t)0x06) /* I2S2ext_SD Alternate Function mapping */ /** * @brief AF 7 selection */ #define GPIO_AF7_SPI3 ((uint8_t)0x07) /* SPI3/I2S3 Alternate Function mapping */ #define GPIO_AF7_USART1 ((uint8_t)0x07) /* USART1 Alternate Function mapping */ #define GPIO_AF7_USART2 ((uint8_t)0x07) /* USART2 Alternate Function mapping */ #define GPIO_AF7_I2S3ext ((uint8_t)0x07) /* I2S3ext_SD Alternate Function mapping */ /** * @brief AF 8 selection */ #define GPIO_AF8_USART6 ((uint8_t)0x08) /* USART6 Alternate Function mapping */ /** * @brief AF 9 selection */ #define GPIO_AF9_TIM14 ((uint8_t)0x09) /* TIM14 Alternate Function mapping */ #define GPIO_AF9_I2C2 ((uint8_t)0x09) /* I2C2 Alternate Function mapping */ #define GPIO_AF9_I2C3 ((uint8_t)0x09) /* I2C3 Alternate Function mapping */ /** * @brief AF 10 selection */ #define GPIO_AF10_OTG_FS ((uint8_t)0xA) /* OTG_FS Alternate Function mapping */ /** * @brief AF 12 selection */ #define GPIO_AF12_SDIO ((uint8_t)0xC) /* SDIO Alternate Function mapping */ /** * @brief AF 15 selection */ #define GPIO_AF15_EVENTOUT ((uint8_t)0x0F) /* EVENTOUT Alternate Function mapping */ #endif /* STM32F411xE */ /*---------------------------------------- STM32F410xx------------------------*/ #if defined(STM32F410Tx) || defined(STM32F410Cx) || defined(STM32F410Rx) /** * @brief AF 0 selection */ #define GPIO_AF0_RTC_50Hz ((uint8_t)0x00) /* RTC_50Hz Alternate Function mapping */ #define GPIO_AF0_MCO ((uint8_t)0x00) /* MCO (MCO1 and MCO2) Alternate Function mapping */ #define GPIO_AF0_TAMPER ((uint8_t)0x00) /* TAMPER (TAMPER_1 and TAMPER_2) Alternate Function mapping */ #define GPIO_AF0_SWJ ((uint8_t)0x00) /* SWJ (SWD and JTAG) Alternate Function mapping */ #define GPIO_AF0_TRACE ((uint8_t)0x00) /* TRACE Alternate Function mapping */ /** * @brief AF 1 selection */ #define GPIO_AF1_TIM1 ((uint8_t)0x01) /* TIM1 Alternate Function mapping */ #define GPIO_AF1_LPTIM1 ((uint8_t)0x01) /* LPTIM1 Alternate Function mapping */ /** * @brief AF 2 selection */ #define GPIO_AF2_TIM5 ((uint8_t)0x02) /* TIM5 Alternate Function mapping */ /** * @brief AF 3 selection */ #define GPIO_AF3_TIM9 ((uint8_t)0x03) /* TIM9 Alternate Function mapping */ #define GPIO_AF3_TIM11 ((uint8_t)0x03) /* TIM11 Alternate Function mapping */ /** * @brief AF 4 selection */ #define GPIO_AF4_I2C1 ((uint8_t)0x04) /* I2C1 Alternate Function mapping */ #define GPIO_AF4_I2C2 ((uint8_t)0x04) /* I2C2 Alternate Function mapping */ #define GPIO_AF4_FMPI2C1 ((uint8_t)0x04) /* FMPI2C1 Alternate Function mapping */ /** * @brief AF 5 selection */ #define GPIO_AF5_SPI1 ((uint8_t)0x05) /* SPI1/I2S1 Alternate Function mapping */ #if defined(STM32F410Cx) || defined(STM32F410Rx) #define GPIO_AF5_SPI2 ((uint8_t)0x05) /* SPI2/I2S2 Alternate Function mapping */ #endif /* STM32F410Cx || STM32F410Rx */ /** * @brief AF 6 selection */ #define GPIO_AF6_SPI1 ((uint8_t)0x06) /* SPI1 Alternate Function mapping */ #if defined(STM32F410Cx) || defined(STM32F410Rx) #define GPIO_AF6_SPI2 ((uint8_t)0x06) /* I2S2 Alternate Function mapping */ #endif /* STM32F410Cx || STM32F410Rx */ #define GPIO_AF6_SPI5 ((uint8_t)0x06) /* SPI5/I2S5 Alternate Function mapping */ /** * @brief AF 7 selection */ #define GPIO_AF7_USART1 ((uint8_t)0x07) /* USART1 Alternate Function mapping */ #define GPIO_AF7_USART2 ((uint8_t)0x07) /* USART2 Alternate Function mapping */ /** * @brief AF 8 selection */ #define GPIO_AF8_USART6 ((uint8_t)0x08) /* USART6 Alternate Function mapping */ /** * @brief AF 9 selection */ #define GPIO_AF9_I2C2 ((uint8_t)0x09) /* I2C2 Alternate Function mapping */ #define GPIO_AF9_FMPI2C1 ((uint8_t)0x09) /* FMPI2C1 Alternate Function mapping */ /** * @brief AF 15 selection */ #define GPIO_AF15_EVENTOUT ((uint8_t)0x0F) /* EVENTOUT Alternate Function mapping */ #endif /* STM32F410Tx || STM32F410Cx || STM32F410Rx */ /*---------------------------------------- STM32F446xx -----------------------*/ #if defined(STM32F446xx) /** * @brief AF 0 selection */ #define GPIO_AF0_RTC_50Hz ((uint8_t)0x00) /* RTC_50Hz Alternate Function mapping */ #define GPIO_AF0_MCO ((uint8_t)0x00) /* MCO (MCO1 and MCO2) Alternate Function mapping */ #define GPIO_AF0_TAMPER ((uint8_t)0x00) /* TAMPER (TAMPER_1 and TAMPER_2) Alternate Function mapping */ #define GPIO_AF0_SWJ ((uint8_t)0x00) /* SWJ (SWD and JTAG) Alternate Function mapping */ #define GPIO_AF0_TRACE ((uint8_t)0x00) /* TRACE Alternate Function mapping */ /** * @brief AF 1 selection */ #define GPIO_AF1_TIM1 ((uint8_t)0x01) /* TIM1 Alternate Function mapping */ #define GPIO_AF1_TIM2 ((uint8_t)0x01) /* TIM2 Alternate Function mapping */ /** * @brief AF 2 selection */ #define GPIO_AF2_TIM3 ((uint8_t)0x02) /* TIM3 Alternate Function mapping */ #define GPIO_AF2_TIM4 ((uint8_t)0x02) /* TIM4 Alternate Function mapping */ #define GPIO_AF2_TIM5 ((uint8_t)0x02) /* TIM5 Alternate Function mapping */ /** * @brief AF 3 selection */ #define GPIO_AF3_TIM8 ((uint8_t)0x03) /* TIM8 Alternate Function mapping */ #define GPIO_AF3_TIM9 ((uint8_t)0x03) /* TIM9 Alternate Function mapping */ #define GPIO_AF3_TIM10 ((uint8_t)0x03) /* TIM10 Alternate Function mapping */ #define GPIO_AF3_TIM11 ((uint8_t)0x03) /* TIM11 Alternate Function mapping */ #define GPIO_AF3_CEC ((uint8_t)0x03) /* CEC Alternate Function mapping */ /** * @brief AF 4 selection */ #define GPIO_AF4_I2C1 ((uint8_t)0x04) /* I2C1 Alternate Function mapping */ #define GPIO_AF4_I2C2 ((uint8_t)0x04) /* I2C2 Alternate Function mapping */ #define GPIO_AF4_I2C3 ((uint8_t)0x04) /* I2C3 Alternate Function mapping */ #define GPIO_AF4_FMPI2C1 ((uint8_t)0x04) /* FMPI2C1 Alternate Function mapping */ #define GPIO_AF4_CEC ((uint8_t)0x04) /* CEC Alternate Function mapping */ /** * @brief AF 5 selection */ #define GPIO_AF5_SPI1 ((uint8_t)0x05) /* SPI1/I2S1 Alternate Function mapping */ #define GPIO_AF5_SPI2 ((uint8_t)0x05) /* SPI2/I2S2 Alternate Function mapping */ #define GPIO_AF5_SPI3 ((uint8_t)0x05) /* SPI3/I2S3 Alternate Function mapping */ #define GPIO_AF5_SPI4 ((uint8_t)0x05) /* SPI4 Alternate Function mapping */ /** * @brief AF 6 selection */ #define GPIO_AF6_SPI2 ((uint8_t)0x06) /* SPI2/I2S2 Alternate Function mapping */ #define GPIO_AF6_SPI3 ((uint8_t)0x06) /* SPI3/I2S3 Alternate Function mapping */ #define GPIO_AF6_SPI4 ((uint8_t)0x06) /* SPI4 Alternate Function mapping */ #define GPIO_AF6_SAI1 ((uint8_t)0x06) /* SAI1 Alternate Function mapping */ /** * @brief AF 7 selection */ #define GPIO_AF7_USART1 ((uint8_t)0x07) /* USART1 Alternate Function mapping */ #define GPIO_AF7_USART2 ((uint8_t)0x07) /* USART2 Alternate Function mapping */ #define GPIO_AF7_USART3 ((uint8_t)0x07) /* USART3 Alternate Function mapping */ #define GPIO_AF7_UART5 ((uint8_t)0x07) /* UART5 Alternate Function mapping */ #define GPIO_AF7_SPI2 ((uint8_t)0x07) /* SPI2/I2S2 Alternate Function mapping */ #define GPIO_AF7_SPI3 ((uint8_t)0x07) /* SPI3/I2S3 Alternate Function mapping */ #define GPIO_AF7_SPDIFRX ((uint8_t)0x07) /* SPDIFRX Alternate Function mapping */ /** * @brief AF 8 selection */ #define GPIO_AF8_UART4 ((uint8_t)0x08) /* UART4 Alternate Function mapping */ #define GPIO_AF8_UART5 ((uint8_t)0x08) /* UART5 Alternate Function mapping */ #define GPIO_AF8_USART6 ((uint8_t)0x08) /* USART6 Alternate Function mapping */ #define GPIO_AF8_SPDIFRX ((uint8_t)0x08) /* SPDIFRX Alternate Function mapping */ #define GPIO_AF8_SAI2 ((uint8_t)0x08) /* SAI2 Alternate Function mapping */ /** * @brief AF 9 selection */ #define GPIO_AF9_CAN1 ((uint8_t)0x09) /* CAN1 Alternate Function mapping */ #define GPIO_AF9_CAN2 ((uint8_t)0x09) /* CAN2 Alternate Function mapping */ #define GPIO_AF9_TIM12 ((uint8_t)0x09) /* TIM12 Alternate Function mapping */ #define GPIO_AF9_TIM13 ((uint8_t)0x09) /* TIM13 Alternate Function mapping */ #define GPIO_AF9_TIM14 ((uint8_t)0x09) /* TIM14 Alternate Function mapping */ #define GPIO_AF9_QSPI ((uint8_t)0x09) /* QSPI Alternate Function mapping */ /** * @brief AF 10 selection */ #define GPIO_AF10_OTG_FS ((uint8_t)0xA) /* OTG_FS Alternate Function mapping */ #define GPIO_AF10_OTG_HS ((uint8_t)0xA) /* OTG_HS Alternate Function mapping */ #define GPIO_AF10_SAI2 ((uint8_t)0xA) /* SAI2 Alternate Function mapping */ #define GPIO_AF10_QSPI ((uint8_t)0xA) /* QSPI Alternate Function mapping */ /** * @brief AF 11 selection */ #define GPIO_AF11_ETH ((uint8_t)0x0B) /* ETHERNET Alternate Function mapping */ /** * @brief AF 12 selection */ #define GPIO_AF12_FMC ((uint8_t)0xC) /* FMC Alternate Function mapping */ #define GPIO_AF12_OTG_HS_FS ((uint8_t)0xC) /* OTG HS configured in FS, Alternate Function mapping */ #define GPIO_AF12_SDIO ((uint8_t)0xC) /* SDIO Alternate Function mapping */ /** * @brief AF 13 selection */ #define GPIO_AF13_DCMI ((uint8_t)0x0D) /* DCMI Alternate Function mapping */ /** * @brief AF 15 selection */ #define GPIO_AF15_EVENTOUT ((uint8_t)0x0F) /* EVENTOUT Alternate Function mapping */ #endif /* STM32F446xx */ /*----------------------------------------------------------------------------*/ /*-------------------------------- STM32F469xx/STM32F479xx--------------------*/ #if defined(STM32F469xx) || defined(STM32F479xx) /** * @brief AF 0 selection */ #define GPIO_AF0_RTC_50Hz ((uint8_t)0x00) /* RTC_50Hz Alternate Function mapping */ #define GPIO_AF0_MCO ((uint8_t)0x00) /* MCO (MCO1 and MCO2) Alternate Function mapping */ #define GPIO_AF0_TAMPER ((uint8_t)0x00) /* TAMPER (TAMPER_1 and TAMPER_2) Alternate Function mapping */ #define GPIO_AF0_SWJ ((uint8_t)0x00) /* SWJ (SWD and JTAG) Alternate Function mapping */ #define GPIO_AF0_TRACE ((uint8_t)0x00) /* TRACE Alternate Function mapping */ /** * @brief AF 1 selection */ #define GPIO_AF1_TIM1 ((uint8_t)0x01) /* TIM1 Alternate Function mapping */ #define GPIO_AF1_TIM2 ((uint8_t)0x01) /* TIM2 Alternate Function mapping */ /** * @brief AF 2 selection */ #define GPIO_AF2_TIM3 ((uint8_t)0x02) /* TIM3 Alternate Function mapping */ #define GPIO_AF2_TIM4 ((uint8_t)0x02) /* TIM4 Alternate Function mapping */ #define GPIO_AF2_TIM5 ((uint8_t)0x02) /* TIM5 Alternate Function mapping */ /** * @brief AF 3 selection */ #define GPIO_AF3_TIM8 ((uint8_t)0x03) /* TIM8 Alternate Function mapping */ #define GPIO_AF3_TIM9 ((uint8_t)0x03) /* TIM9 Alternate Function mapping */ #define GPIO_AF3_TIM10 ((uint8_t)0x03) /* TIM10 Alternate Function mapping */ #define GPIO_AF3_TIM11 ((uint8_t)0x03) /* TIM11 Alternate Function mapping */ /** * @brief AF 4 selection */ #define GPIO_AF4_I2C1 ((uint8_t)0x04) /* I2C1 Alternate Function mapping */ #define GPIO_AF4_I2C2 ((uint8_t)0x04) /* I2C2 Alternate Function mapping */ #define GPIO_AF4_I2C3 ((uint8_t)0x04) /* I2C3 Alternate Function mapping */ /** * @brief AF 5 selection */ #define GPIO_AF5_SPI1 ((uint8_t)0x05) /* SPI1 Alternate Function mapping */ #define GPIO_AF5_SPI2 ((uint8_t)0x05) /* SPI2/I2S2 Alternate Function mapping */ #define GPIO_AF5_SPI3 ((uint8_t)0x05) /* SPI3/I2S3 Alternate Function mapping */ #define GPIO_AF5_SPI4 ((uint8_t)0x05) /* SPI4 Alternate Function mapping */ #define GPIO_AF5_SPI5 ((uint8_t)0x05) /* SPI5 Alternate Function mapping */ #define GPIO_AF5_SPI6 ((uint8_t)0x05) /* SPI6 Alternate Function mapping */ #define GPIO_AF5_I2S3ext ((uint8_t)0x05) /* I2S3ext_SD Alternate Function mapping */ /** * @brief AF 6 selection */ #define GPIO_AF6_SPI3 ((uint8_t)0x06) /* SPI3/I2S3 Alternate Function mapping */ #define GPIO_AF6_I2S2ext ((uint8_t)0x06) /* I2S2ext_SD Alternate Function mapping */ #define GPIO_AF6_SAI1 ((uint8_t)0x06) /* SAI1 Alternate Function mapping */ /** * @brief AF 7 selection */ #define GPIO_AF7_USART1 ((uint8_t)0x07) /* USART1 Alternate Function mapping */ #define GPIO_AF7_USART2 ((uint8_t)0x07) /* USART2 Alternate Function mapping */ #define GPIO_AF7_USART3 ((uint8_t)0x07) /* USART3 Alternate Function mapping */ #define GPIO_AF7_I2S3ext ((uint8_t)0x07) /* I2S3ext_SD Alternate Function mapping */ /** * @brief AF 8 selection */ #define GPIO_AF8_UART4 ((uint8_t)0x08) /* UART4 Alternate Function mapping */ #define GPIO_AF8_UART5 ((uint8_t)0x08) /* UART5 Alternate Function mapping */ #define GPIO_AF8_USART6 ((uint8_t)0x08) /* USART6 Alternate Function mapping */ #define GPIO_AF8_UART7 ((uint8_t)0x08) /* UART7 Alternate Function mapping */ #define GPIO_AF8_UART8 ((uint8_t)0x08) /* UART8 Alternate Function mapping */ /** * @brief AF 9 selection */ #define GPIO_AF9_CAN1 ((uint8_t)0x09) /* CAN1 Alternate Function mapping */ #define GPIO_AF9_CAN2 ((uint8_t)0x09) /* CAN2 Alternate Function mapping */ #define GPIO_AF9_TIM12 ((uint8_t)0x09) /* TIM12 Alternate Function mapping */ #define GPIO_AF9_TIM13 ((uint8_t)0x09) /* TIM13 Alternate Function mapping */ #define GPIO_AF9_TIM14 ((uint8_t)0x09) /* TIM14 Alternate Function mapping */ #define GPIO_AF9_LTDC ((uint8_t)0x09) /* LCD-TFT Alternate Function mapping */ #define GPIO_AF9_QSPI ((uint8_t)0x09) /* QSPI Alternate Function mapping */ /** * @brief AF 10 selection */ #define GPIO_AF10_OTG_FS ((uint8_t)0xA) /* OTG_FS Alternate Function mapping */ #define GPIO_AF10_OTG_HS ((uint8_t)0xA) /* OTG_HS Alternate Function mapping */ #define GPIO_AF10_QSPI ((uint8_t)0xA) /* QSPI Alternate Function mapping */ /** * @brief AF 11 selection */ #define GPIO_AF11_ETH ((uint8_t)0x0B) /* ETHERNET Alternate Function mapping */ /** * @brief AF 12 selection */ #define GPIO_AF12_FMC ((uint8_t)0xC) /* FMC Alternate Function mapping */ #define GPIO_AF12_OTG_HS_FS ((uint8_t)0xC) /* OTG HS configured in FS, Alternate Function mapping */ #define GPIO_AF12_SDIO ((uint8_t)0xC) /* SDIO Alternate Function mapping */ /** * @brief AF 13 selection */ #define GPIO_AF13_DCMI ((uint8_t)0x0D) /* DCMI Alternate Function mapping */ #define GPIO_AF13_DSI ((uint8_t)0x0D) /* DSI Alternate Function mapping */ /** * @brief AF 14 selection */ #define GPIO_AF14_LTDC ((uint8_t)0x0E) /* LCD-TFT Alternate Function mapping */ /** * @brief AF 15 selection */ #define GPIO_AF15_EVENTOUT ((uint8_t)0x0F) /* EVENTOUT Alternate Function mapping */ #endif /* STM32F469xx || STM32F479xx */ /*----------------------------------------------------------------------------*/ /** * @} */ /** * @} */ /* Exported macro ------------------------------------------------------------*/ /** @defgroup GPIOEx_Exported_Macros GPIO Exported Macros * @{ */ /** * @} */ /* Exported functions --------------------------------------------------------*/ /** @defgroup GPIOEx_Exported_Functions GPIO Exported Functions * @{ */ /** * @} */ /* Private types -------------------------------------------------------------*/ /* Private variables ---------------------------------------------------------*/ /* Private constants ---------------------------------------------------------*/ /** @defgroup GPIOEx_Private_Constants GPIO Private Constants * @{ */ /** * @} */ /* Private macros ------------------------------------------------------------*/ /** @defgroup GPIOEx_Private_Macros GPIO Private Macros * @{ */ /** @defgroup GPIOEx_Get_Port_Index GPIO Get Port Index * @{ */ #if defined(STM32F405xx) || defined(STM32F415xx) || defined(STM32F407xx) || defined(STM32F417xx) #define GPIO_GET_INDEX(__GPIOx__) (uint8_t)(((__GPIOx__) == (GPIOA))? 0U :\ ((__GPIOx__) == (GPIOB))? 1U :\ ((__GPIOx__) == (GPIOC))? 2U :\ ((__GPIOx__) == (GPIOD))? 3U :\ ((__GPIOx__) == (GPIOE))? 4U :\ ((__GPIOx__) == (GPIOF))? 5U :\ ((__GPIOx__) == (GPIOG))? 6U :\ ((__GPIOx__) == (GPIOH))? 7U :\ ((__GPIOx__) == (GPIOI))? 8U : 9U) #endif /* STM32F405xx || STM32F415xx || STM32F407xx || STM32F417xx */ #if defined(STM32F427xx) || defined(STM32F437xx) || defined(STM32F429xx) || defined(STM32F439xx) ||\ defined(STM32F469xx) || defined(STM32F479xx) #define GPIO_GET_INDEX(__GPIOx__) (uint8_t)(((__GPIOx__) == (GPIOA))? 0U :\ ((__GPIOx__) == (GPIOB))? 1U :\ ((__GPIOx__) == (GPIOC))? 2U :\ ((__GPIOx__) == (GPIOD))? 3U :\ ((__GPIOx__) == (GPIOE))? 4U :\ ((__GPIOx__) == (GPIOF))? 5U :\ ((__GPIOx__) == (GPIOG))? 6U :\ ((__GPIOx__) == (GPIOH))? 7U :\ ((__GPIOx__) == (GPIOI))? 8U :\ ((__GPIOx__) == (GPIOJ))? 9U : 10U) #endif /* STM32F427xx || STM32F437xx || STM32F429xx || STM32F439xx || STM32F469xx || STM32F479xx */ #if defined(STM32F410Tx) || defined(STM32F410Cx) || defined(STM32F410Rx) #define GPIO_GET_INDEX(__GPIOx__) (uint8_t)(((__GPIOx__) == (GPIOA))? 0U :\ ((__GPIOx__) == (GPIOB))? 1U :\ ((__GPIOx__) == (GPIOC))? 2U :\ ((__GPIOx__) == (GPIOH))? 7U : 8U) #endif /* STM32F410Tx || STM32F410Cx || STM32F410Rx */ #if defined(STM32F401xC) || defined(STM32F401xE) || defined(STM32F411xE) #define GPIO_GET_INDEX(__GPIOx__) (uint8_t)(((__GPIOx__) == (GPIOA))? 0U :\ ((__GPIOx__) == (GPIOB))? 1U :\ ((__GPIOx__) == (GPIOC))? 2U :\ ((__GPIOx__) == (GPIOD))? 3U :\ ((__GPIOx__) == (GPIOE))? 4U : 5U) #endif /* STM32F401xC || STM32F401xE || STM32F411xE */ #if defined(STM32F446xx) #define GPIO_GET_INDEX(__GPIOx__) (uint8_t)(((__GPIOx__) == (GPIOA))? 0U :\ ((__GPIOx__) == (GPIOB))? 1U :\ ((__GPIOx__) == (GPIOC))? 2U :\ ((__GPIOx__) == (GPIOD))? 3U :\ ((__GPIOx__) == (GPIOE))? 4U :\ ((__GPIOx__) == (GPIOF))? 5U :\ ((__GPIOx__) == (GPIOG))? 6U : 8U) #endif /* STM32F446xx */ /** * @} */ /** @defgroup GPIOEx_IS_Alternat_function_selection GPIO Check Alternate Function * @{ */ /*------------------------- STM32F429xx/STM32F439xx---------------------------*/ #if defined(STM32F429xx) || defined(STM32F439xx) #define IS_GPIO_AF(AF) (((AF) == GPIO_AF0_RTC_50Hz) || ((AF) == GPIO_AF9_TIM14) || \ ((AF) == GPIO_AF0_MCO) || ((AF) == GPIO_AF0_TAMPER) || \ ((AF) == GPIO_AF0_SWJ) || ((AF) == GPIO_AF0_TRACE) || \ ((AF) == GPIO_AF1_TIM1) || ((AF) == GPIO_AF1_TIM2) || \ ((AF) == GPIO_AF2_TIM3) || ((AF) == GPIO_AF2_TIM4) || \ ((AF) == GPIO_AF2_TIM5) || ((AF) == GPIO_AF3_TIM8) || \ ((AF) == GPIO_AF4_I2C1) || ((AF) == GPIO_AF4_I2C2) || \ ((AF) == GPIO_AF4_I2C3) || ((AF) == GPIO_AF5_SPI1) || \ ((AF) == GPIO_AF5_SPI2) || ((AF) == GPIO_AF9_TIM13) || \ ((AF) == GPIO_AF6_SPI3) || ((AF) == GPIO_AF9_TIM12) || \ ((AF) == GPIO_AF7_USART1) || ((AF) == GPIO_AF7_USART2) || \ ((AF) == GPIO_AF7_USART3) || ((AF) == GPIO_AF8_UART4) || \ ((AF) == GPIO_AF8_UART5) || ((AF) == GPIO_AF8_USART6) || \ ((AF) == GPIO_AF9_CAN1) || ((AF) == GPIO_AF9_CAN2) || \ ((AF) == GPIO_AF10_OTG_FS) || ((AF) == GPIO_AF10_OTG_HS) || \ ((AF) == GPIO_AF11_ETH) || ((AF) == GPIO_AF12_OTG_HS_FS) || \ ((AF) == GPIO_AF12_SDIO) || ((AF) == GPIO_AF13_DCMI) || \ ((AF) == GPIO_AF15_EVENTOUT) || ((AF) == GPIO_AF5_SPI4) || \ ((AF) == GPIO_AF5_SPI5) || ((AF) == GPIO_AF5_SPI6) || \ ((AF) == GPIO_AF8_UART7) || ((AF) == GPIO_AF8_UART8) || \ ((AF) == GPIO_AF12_FMC) || ((AF) == GPIO_AF6_SAI1) || \ ((AF) == GPIO_AF14_LTDC)) #endif /* STM32F429xx || STM32F439xx */ /*----------------------------------------------------------------------------*/ /*---------------------------------- STM32F427xx/STM32F437xx------------------*/ #if defined(STM32F427xx) || defined(STM32F437xx) #define IS_GPIO_AF(AF) (((AF) == GPIO_AF0_RTC_50Hz) || ((AF) == GPIO_AF9_TIM14) || \ ((AF) == GPIO_AF0_MCO) || ((AF) == GPIO_AF0_TAMPER) || \ ((AF) == GPIO_AF0_SWJ) || ((AF) == GPIO_AF0_TRACE) || \ ((AF) == GPIO_AF1_TIM1) || ((AF) == GPIO_AF1_TIM2) || \ ((AF) == GPIO_AF2_TIM3) || ((AF) == GPIO_AF2_TIM4) || \ ((AF) == GPIO_AF2_TIM5) || ((AF) == GPIO_AF3_TIM8) || \ ((AF) == GPIO_AF4_I2C1) || ((AF) == GPIO_AF4_I2C2) || \ ((AF) == GPIO_AF4_I2C3) || ((AF) == GPIO_AF5_SPI1) || \ ((AF) == GPIO_AF5_SPI2) || ((AF) == GPIO_AF9_TIM13) || \ ((AF) == GPIO_AF6_SPI3) || ((AF) == GPIO_AF9_TIM12) || \ ((AF) == GPIO_AF7_USART1) || ((AF) == GPIO_AF7_USART2) || \ ((AF) == GPIO_AF7_USART3) || ((AF) == GPIO_AF8_UART4) || \ ((AF) == GPIO_AF8_UART5) || ((AF) == GPIO_AF8_USART6) || \ ((AF) == GPIO_AF9_CAN1) || ((AF) == GPIO_AF9_CAN2) || \ ((AF) == GPIO_AF10_OTG_FS) || ((AF) == GPIO_AF10_OTG_HS) || \ ((AF) == GPIO_AF11_ETH) || ((AF) == GPIO_AF12_OTG_HS_FS) || \ ((AF) == GPIO_AF12_SDIO) || ((AF) == GPIO_AF13_DCMI) || \ ((AF) == GPIO_AF15_EVENTOUT) || ((AF) == GPIO_AF5_SPI4) || \ ((AF) == GPIO_AF5_SPI5) || ((AF) == GPIO_AF5_SPI6) || \ ((AF) == GPIO_AF8_UART7) || ((AF) == GPIO_AF8_UART8) || \ ((AF) == GPIO_AF12_FMC) || ((AF) == GPIO_AF6_SAI1)) #endif /* STM32F427xx || STM32F437xx */ /*----------------------------------------------------------------------------*/ /*---------------------------------- STM32F407xx/STM32F417xx------------------*/ #if defined(STM32F407xx) || defined(STM32F417xx) #define IS_GPIO_AF(AF) (((AF) == GPIO_AF0_RTC_50Hz) || ((AF) == GPIO_AF9_TIM14) || \ ((AF) == GPIO_AF0_MCO) || ((AF) == GPIO_AF0_TAMPER) || \ ((AF) == GPIO_AF0_SWJ) || ((AF) == GPIO_AF0_TRACE) || \ ((AF) == GPIO_AF1_TIM1) || ((AF) == GPIO_AF1_TIM2) || \ ((AF) == GPIO_AF2_TIM3) || ((AF) == GPIO_AF2_TIM4) || \ ((AF) == GPIO_AF2_TIM5) || ((AF) == GPIO_AF3_TIM8) || \ ((AF) == GPIO_AF4_I2C1) || ((AF) == GPIO_AF4_I2C2) || \ ((AF) == GPIO_AF4_I2C3) || ((AF) == GPIO_AF5_SPI1) || \ ((AF) == GPIO_AF5_SPI2) || ((AF) == GPIO_AF9_TIM13) || \ ((AF) == GPIO_AF6_SPI3) || ((AF) == GPIO_AF9_TIM12) || \ ((AF) == GPIO_AF7_USART1) || ((AF) == GPIO_AF7_USART2) || \ ((AF) == GPIO_AF7_USART3) || ((AF) == GPIO_AF8_UART4) || \ ((AF) == GPIO_AF8_UART5) || ((AF) == GPIO_AF8_USART6) || \ ((AF) == GPIO_AF9_CAN1) || ((AF) == GPIO_AF9_CAN2) || \ ((AF) == GPIO_AF10_OTG_FS) || ((AF) == GPIO_AF10_OTG_HS) || \ ((AF) == GPIO_AF11_ETH) || ((AF) == GPIO_AF12_OTG_HS_FS) || \ ((AF) == GPIO_AF12_SDIO) || ((AF) == GPIO_AF13_DCMI) || \ ((AF) == GPIO_AF12_FSMC) || ((AF) == GPIO_AF15_EVENTOUT)) #endif /* STM32F407xx || STM32F417xx */ /*----------------------------------------------------------------------------*/ /*---------------------------------- STM32F405xx/STM32F415xx------------------*/ #if defined(STM32F405xx) || defined(STM32F415xx) #define IS_GPIO_AF(AF) (((AF) == GPIO_AF0_RTC_50Hz) || ((AF) == GPIO_AF9_TIM14) || \ ((AF) == GPIO_AF0_MCO) || ((AF) == GPIO_AF0_TAMPER) || \ ((AF) == GPIO_AF0_SWJ) || ((AF) == GPIO_AF0_TRACE) || \ ((AF) == GPIO_AF1_TIM1) || ((AF) == GPIO_AF1_TIM2) || \ ((AF) == GPIO_AF2_TIM3) || ((AF) == GPIO_AF2_TIM4) || \ ((AF) == GPIO_AF2_TIM5) || ((AF) == GPIO_AF3_TIM8) || \ ((AF) == GPIO_AF4_I2C1) || ((AF) == GPIO_AF4_I2C2) || \ ((AF) == GPIO_AF4_I2C3) || ((AF) == GPIO_AF5_SPI1) || \ ((AF) == GPIO_AF5_SPI2) || ((AF) == GPIO_AF9_TIM13) || \ ((AF) == GPIO_AF6_SPI3) || ((AF) == GPIO_AF9_TIM12) || \ ((AF) == GPIO_AF7_USART1) || ((AF) == GPIO_AF7_USART2) || \ ((AF) == GPIO_AF7_USART3) || ((AF) == GPIO_AF8_UART4) || \ ((AF) == GPIO_AF8_UART5) || ((AF) == GPIO_AF8_USART6) || \ ((AF) == GPIO_AF9_CAN1) || ((AF) == GPIO_AF9_CAN2) || \ ((AF) == GPIO_AF10_OTG_FS) || ((AF) == GPIO_AF10_OTG_HS) || \ ((AF) == GPIO_AF12_OTG_HS_FS) || ((AF) == GPIO_AF12_SDIO) || \ ((AF) == GPIO_AF12_FSMC) || ((AF) == GPIO_AF15_EVENTOUT)) #endif /* STM32F405xx || STM32F415xx */ /*----------------------------------------------------------------------------*/ /*---------------------------------------- STM32F401xx------------------------*/ #if defined(STM32F401xC) || defined(STM32F401xE) #define IS_GPIO_AF(AF) (((AF) == GPIO_AF0_RTC_50Hz) || ((AF) == GPIO_AF9_TIM14) || \ ((AF) == GPIO_AF0_MCO) || ((AF) == GPIO_AF0_TAMPER) || \ ((AF) == GPIO_AF0_SWJ) || ((AF) == GPIO_AF0_TRACE) || \ ((AF) == GPIO_AF1_TIM1) || ((AF) == GPIO_AF1_TIM2) || \ ((AF) == GPIO_AF2_TIM3) || ((AF) == GPIO_AF2_TIM4) || \ ((AF) == GPIO_AF2_TIM5) || ((AF) == GPIO_AF4_I2C1) || \ ((AF) == GPIO_AF4_I2C2) || ((AF) == GPIO_AF4_I2C3) || \ ((AF) == GPIO_AF5_SPI1) || ((AF) == GPIO_AF5_SPI2) || \ ((AF) == GPIO_AF6_SPI3) || ((AF) == GPIO_AF5_SPI4) || \ ((AF) == GPIO_AF7_USART1) || ((AF) == GPIO_AF7_USART2) || \ ((AF) == GPIO_AF8_USART6) || ((AF) == GPIO_AF10_OTG_FS) || \ ((AF) == GPIO_AF9_I2C2) || ((AF) == GPIO_AF9_I2C3) || \ ((AF) == GPIO_AF12_SDIO) || ((AF) == GPIO_AF15_EVENTOUT)) #endif /* STM32F401xC || STM32F401xE */ /*----------------------------------------------------------------------------*/ /*---------------------------------------- STM32F410xx------------------------*/ #if defined(STM32F410Tx) || defined(STM32F410Cx) || defined(STM32F410Rx) #define IS_GPIO_AF(AF) (((AF) < 10) || ((AF) == 15)) #endif /* STM32F410Tx || STM32F410Cx || STM32F410Rx */ /*---------------------------------------- STM32F411xx------------------------*/ #if defined(STM32F411xE) #define IS_GPIO_AF(AF) (((AF) == GPIO_AF0_RTC_50Hz) || ((AF) == GPIO_AF9_TIM14) || \ ((AF) == GPIO_AF0_MCO) || ((AF) == GPIO_AF0_TAMPER) || \ ((AF) == GPIO_AF0_SWJ) || ((AF) == GPIO_AF0_TRACE) || \ ((AF) == GPIO_AF1_TIM1) || ((AF) == GPIO_AF1_TIM2) || \ ((AF) == GPIO_AF2_TIM3) || ((AF) == GPIO_AF2_TIM4) || \ ((AF) == GPIO_AF2_TIM5) || ((AF) == GPIO_AF4_I2C1) || \ ((AF) == GPIO_AF4_I2C2) || ((AF) == GPIO_AF4_I2C3) || \ ((AF) == GPIO_AF5_SPI1) || ((AF) == GPIO_AF5_SPI2) || \ ((AF) == GPIO_AF5_SPI3) || ((AF) == GPIO_AF6_SPI4) || \ ((AF) == GPIO_AF6_SPI3) || ((AF) == GPIO_AF5_SPI4) || \ ((AF) == GPIO_AF6_SPI5) || ((AF) == GPIO_AF7_SPI3) || \ ((AF) == GPIO_AF7_USART1) || ((AF) == GPIO_AF7_USART2) || \ ((AF) == GPIO_AF8_USART6) || ((AF) == GPIO_AF10_OTG_FS) || \ ((AF) == GPIO_AF9_I2C2) || ((AF) == GPIO_AF9_I2C3) || \ ((AF) == GPIO_AF12_SDIO) || ((AF) == GPIO_AF15_EVENTOUT)) #endif /* STM32F411xE */ /*----------------------------------------------------------------------------*/ /*----------------------------------------------- STM32F446xx ----------------*/ #if defined(STM32F446xx) #define IS_GPIO_AF(AF) (((AF) == GPIO_AF0_RTC_50Hz) || ((AF) == GPIO_AF9_TIM14) || \ ((AF) == GPIO_AF0_MCO) || ((AF) == GPIO_AF0_TAMPER) || \ ((AF) == GPIO_AF0_SWJ) || ((AF) == GPIO_AF0_TRACE) || \ ((AF) == GPIO_AF1_TIM1) || ((AF) == GPIO_AF1_TIM2) || \ ((AF) == GPIO_AF2_TIM3) || ((AF) == GPIO_AF2_TIM4) || \ ((AF) == GPIO_AF2_TIM5) || ((AF) == GPIO_AF3_TIM8) || \ ((AF) == GPIO_AF4_I2C1) || ((AF) == GPIO_AF4_I2C2) || \ ((AF) == GPIO_AF4_I2C3) || ((AF) == GPIO_AF5_SPI1) || \ ((AF) == GPIO_AF5_SPI2) || ((AF) == GPIO_AF9_TIM13) || \ ((AF) == GPIO_AF6_SPI3) || ((AF) == GPIO_AF9_TIM12) || \ ((AF) == GPIO_AF7_USART1) || ((AF) == GPIO_AF7_USART2) || \ ((AF) == GPIO_AF7_USART3) || ((AF) == GPIO_AF8_UART4) || \ ((AF) == GPIO_AF8_UART5) || ((AF) == GPIO_AF8_USART6) || \ ((AF) == GPIO_AF9_CAN1) || ((AF) == GPIO_AF9_CAN2) || \ ((AF) == GPIO_AF10_OTG_FS) || ((AF) == GPIO_AF10_OTG_HS) || \ ((AF) == GPIO_AF11_ETH) || ((AF) == GPIO_AF12_OTG_HS_FS) || \ ((AF) == GPIO_AF12_SDIO) || ((AF) == GPIO_AF13_DCMI) || \ ((AF) == GPIO_AF15_EVENTOUT) || ((AF) == GPIO_AF5_SPI4) || \ ((AF) == GPIO_AF12_FMC) || ((AF) == GPIO_AF6_SAI1) || \ ((AF) == GPIO_AF3_CEC) || ((AF) == GPIO_AF4_CEC) || \ ((AF) == GPIO_AF5_SPI3) || ((AF) == GPIO_AF6_SPI2) || \ ((AF) == GPIO_AF6_SPI4) || ((AF) == GPIO_AF7_UART5) || \ ((AF) == GPIO_AF7_SPI2) || ((AF) == GPIO_AF7_SPI3) || \ ((AF) == GPIO_AF7_SPDIFRX) || ((AF) == GPIO_AF8_SPDIFRX) || \ ((AF) == GPIO_AF8_SAI2) || ((AF) == GPIO_AF9_QSPI) || \ ((AF) == GPIO_AF10_SAI2) || ((AF) == GPIO_AF10_QSPI)) #endif /* STM32F446xx */ /*----------------------------------------------------------------------------*/ /*------------------------------------------- STM32F469xx/STM32F479xx --------*/ #if defined(STM32F469xx) || defined(STM32F479xx) #define IS_GPIO_AF(AF) (((AF) == GPIO_AF0_RTC_50Hz) || ((AF) == GPIO_AF9_TIM14) || \ ((AF) == GPIO_AF0_MCO) || ((AF) == GPIO_AF0_TAMPER) || \ ((AF) == GPIO_AF0_SWJ) || ((AF) == GPIO_AF0_TRACE) || \ ((AF) == GPIO_AF1_TIM1) || ((AF) == GPIO_AF1_TIM2) || \ ((AF) == GPIO_AF2_TIM3) || ((AF) == GPIO_AF2_TIM4) || \ ((AF) == GPIO_AF2_TIM5) || ((AF) == GPIO_AF3_TIM8) || \ ((AF) == GPIO_AF4_I2C1) || ((AF) == GPIO_AF4_I2C2) || \ ((AF) == GPIO_AF4_I2C3) || ((AF) == GPIO_AF5_SPI1) || \ ((AF) == GPIO_AF5_SPI2) || ((AF) == GPIO_AF9_TIM13) || \ ((AF) == GPIO_AF6_SPI3) || ((AF) == GPIO_AF9_TIM12) || \ ((AF) == GPIO_AF7_USART1) || ((AF) == GPIO_AF7_USART2) || \ ((AF) == GPIO_AF7_USART3) || ((AF) == GPIO_AF8_UART4) || \ ((AF) == GPIO_AF8_UART5) || ((AF) == GPIO_AF8_USART6) || \ ((AF) == GPIO_AF9_CAN1) || ((AF) == GPIO_AF9_CAN2) || \ ((AF) == GPIO_AF10_OTG_FS) || ((AF) == GPIO_AF10_OTG_HS) || \ ((AF) == GPIO_AF11_ETH) || ((AF) == GPIO_AF12_OTG_HS_FS) || \ ((AF) == GPIO_AF12_SDIO) || ((AF) == GPIO_AF13_DCMI) || \ ((AF) == GPIO_AF15_EVENTOUT) || ((AF) == GPIO_AF5_SPI4) || \ ((AF) == GPIO_AF5_SPI5) || ((AF) == GPIO_AF5_SPI6) || \ ((AF) == GPIO_AF8_UART7) || ((AF) == GPIO_AF8_UART8) || \ ((AF) == GPIO_AF12_FMC) || ((AF) == GPIO_AF6_SAI1) || \ ((AF) == GPIO_AF14_LTDC) || ((AF) == GPIO_AF13_DSI) || \ ((AF) == GPIO_AF9_QSPI) || ((AF) == GPIO_AF10_QSPI)) #endif /* STM32F469xx || STM32F479xx */ /*----------------------------------------------------------------------------*/ /** * @} */ /** * @} */ /* Private functions ---------------------------------------------------------*/ /** @defgroup GPIOEx_Private_Functions GPIO Private Functions * @{ */ /** * @} */ /** * @} */ /** * @} */ #ifdef __cplusplus } #endif #endif /* __STM32F4xx_HAL_GPIO_EX_H */ /************************ (C) COPYRIGHT STMicroelectronics *****END OF FILE****/ ================================================ FILE: Zelig/mbed/TARGET_NUCLEO_F411RE/stm32f4xx_hal_hash.h ================================================ /** ****************************************************************************** * @file stm32f4xx_hal_hash.h * @author MCD Application Team * @version V1.4.1 * @date 09-October-2015 * @brief Header file of HASH HAL module. ****************************************************************************** * @attention * *

© COPYRIGHT(c) 2015 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. * ****************************************************************************** */ /* Define to prevent recursive inclusion -------------------------------------*/ #ifndef __STM32F4xx_HAL_HASH_H #define __STM32F4xx_HAL_HASH_H #ifdef __cplusplus extern "C" { #endif #if defined(STM32F415xx) || defined(STM32F417xx) || defined(STM32F437xx) || defined(STM32F439xx) || defined(STM32F479xx) /* Includes ------------------------------------------------------------------*/ #include "stm32f4xx_hal_def.h" /** @addtogroup STM32F4xx_HAL_Driver * @{ */ /** @addtogroup HASH * @brief HASH HAL module driver * @{ */ /* Exported types ------------------------------------------------------------*/ /** @defgroup HASH_Exported_Types HASH Exported Types * @{ */ /** @defgroup HASH_Exported_Types_Group1 HASH Configuration Structure definition * @{ */ typedef struct { uint32_t DataType; /*!< 32-bit data, 16-bit data, 8-bit data or 1-bit string. This parameter can be a value of @ref HASH DataType */ uint32_t KeySize; /*!< The key size is used only in HMAC operation */ uint8_t* pKey; /*!< The key is used only in HMAC operation */ }HASH_InitTypeDef; /** * @} */ /** @defgroup HASH_Exported_Types_Group2 HASH State structures definition * @{ */ typedef enum { HAL_HASH_STATE_RESET = 0x00, /*!< HASH not yet initialized or disabled */ HAL_HASH_STATE_READY = 0x01, /*!< HASH initialized and ready for use */ HAL_HASH_STATE_BUSY = 0x02, /*!< HASH internal process is ongoing */ HAL_HASH_STATE_TIMEOUT = 0x03, /*!< HASH timeout state */ HAL_HASH_STATE_ERROR = 0x04 /*!< HASH error state */ }HAL_HASH_STATETypeDef; /** * @} */ /** @defgroup HASH_Exported_Types_Group3 HASH phase structures definition * @{ */ typedef enum { HAL_HASH_PHASE_READY = 0x01, /*!< HASH peripheral is ready for initialization */ HAL_HASH_PHASE_PROCESS = 0x02, /*!< HASH peripheral is in processing phase */ }HAL_HASHPhaseTypeDef; /** * @} */ /** @defgroup HASH_Exported_Types_Group4 HASH Handle structures definition * @{ */ typedef struct { HASH_InitTypeDef Init; /*!< HASH required parameters */ uint8_t *pHashInBuffPtr; /*!< Pointer to input buffer */ uint8_t *pHashOutBuffPtr; /*!< Pointer to input buffer */ __IO uint32_t HashBuffSize; /*!< Size of buffer to be processed */ __IO uint32_t HashInCount; /*!< Counter of inputed data */ __IO uint32_t HashITCounter; /*!< Counter of issued interrupts */ HAL_StatusTypeDef Status; /*!< HASH peripheral status */ HAL_HASHPhaseTypeDef Phase; /*!< HASH peripheral phase */ DMA_HandleTypeDef *hdmain; /*!< HASH In DMA handle parameters */ HAL_LockTypeDef Lock; /*!< HASH locking object */ __IO HAL_HASH_STATETypeDef State; /*!< HASH peripheral state */ } HASH_HandleTypeDef; /** * @} */ /** * @} */ /* Exported constants --------------------------------------------------------*/ /** @defgroup HASH_Exported_Constants HASH Exported Constants * @{ */ /** @defgroup HASH_Exported_Constants_Group1 HASH Algorithm Selection * @{ */ #define HASH_ALGOSELECTION_SHA1 ((uint32_t)0x0000) /*!< HASH function is SHA1 */ #define HASH_ALGOSELECTION_SHA224 HASH_CR_ALGO_1 /*!< HASH function is SHA224 */ #define HASH_ALGOSELECTION_SHA256 HASH_CR_ALGO /*!< HASH function is SHA256 */ #define HASH_ALGOSELECTION_MD5 HASH_CR_ALGO_0 /*!< HASH function is MD5 */ /** * @} */ /** @defgroup HASH_Exported_Constants_Group2 HASH Algorithm Mode * @{ */ #define HASH_ALGOMODE_HASH ((uint32_t)0x00000000) /*!< Algorithm is HASH */ #define HASH_ALGOMODE_HMAC HASH_CR_MODE /*!< Algorithm is HMAC */ /** * @} */ /** @defgroup HASH_Exported_Constants_Group3 HASH DataType * @{ */ #define HASH_DATATYPE_32B ((uint32_t)0x0000) /*!< 32-bit data. No swapping */ #define HASH_DATATYPE_16B HASH_CR_DATATYPE_0 /*!< 16-bit data. Each half word is swapped */ #define HASH_DATATYPE_8B HASH_CR_DATATYPE_1 /*!< 8-bit data. All bytes are swapped */ #define HASH_DATATYPE_1B HASH_CR_DATATYPE /*!< 1-bit data. In the word all bits are swapped */ /** * @} */ /** @defgroup HASH_Exported_Constants_Group4 HASH HMAC Long key * @brief HASH HMAC Long key used only for HMAC mode * @{ */ #define HASH_HMAC_KEYTYPE_SHORTKEY ((uint32_t)0x00000000) /*!< HMAC Key is <= 64 bytes */ #define HASH_HMAC_KEYTYPE_LONGKEY HASH_CR_LKEY /*!< HMAC Key is > 64 bytes */ /** * @} */ /** @defgroup HASH_Exported_Constants_Group5 HASH Flags definition * @{ */ #define HASH_FLAG_DINIS HASH_SR_DINIS /*!< 16 locations are free in the DIN : A new block can be entered into the input buffer */ #define HASH_FLAG_DCIS HASH_SR_DCIS /*!< Digest calculation complete */ #define HASH_FLAG_DMAS HASH_SR_DMAS /*!< DMA interface is enabled (DMAE=1) or a transfer is ongoing */ #define HASH_FLAG_BUSY HASH_SR_BUSY /*!< The hash core is Busy : processing a block of data */ #define HASH_FLAG_DINNE HASH_CR_DINNE /*!< DIN not empty : The input buffer contains at least one word of data */ /** * @} */ /** @defgroup HASH_Exported_Constants_Group6 HASH Interrupts definition * @{ */ #define HASH_IT_DINI HASH_IMR_DINIE /*!< A new block can be entered into the input buffer (DIN) */ #define HASH_IT_DCI HASH_IMR_DCIE /*!< Digest calculation complete */ /** * @} */ /** * @} */ /* Exported macro ------------------------------------------------------------*/ /** @defgroup HASH_Exported_Macros HASH Exported Macros * @{ */ /** @brief Reset HASH handle state * @param __HANDLE__: specifies the HASH handle. * @retval None */ #define __HAL_HASH_RESET_HANDLE_STATE(__HANDLE__) ((__HANDLE__)->State = HAL_HASH_STATE_RESET) /** @brief Check whether the specified HASH flag is set or not. * @param __FLAG__: specifies the flag to check. * This parameter can be one of the following values: * @arg HASH_FLAG_DINIS: A new block can be entered into the input buffer. * @arg HASH_FLAG_DCIS: Digest calculation complete * @arg HASH_FLAG_DMAS: DMA interface is enabled (DMAE=1) or a transfer is ongoing * @arg HASH_FLAG_BUSY: The hash core is Busy : processing a block of data * @arg HASH_FLAG_DINNE: DIN not empty : The input buffer contains at least one word of data * @retval The new state of __FLAG__ (TRUE or FALSE). */ #define __HAL_HASH_GET_FLAG(__FLAG__) (((__FLAG__) > 8U) ? ((HASH->CR & (__FLAG__)) == (__FLAG__)) :\ ((HASH->SR & (__FLAG__)) == (__FLAG__))) /** * @brief Enable the multiple DMA mode. * This feature is available only in STM32F429x and STM32F439x devices. * @retval None */ #define __HAL_HASH_SET_MDMAT() HASH->CR |= HASH_CR_MDMAT /** * @brief Disable the multiple DMA mode. * @retval None */ #define __HAL_HASH_RESET_MDMAT() HASH->CR &= (uint32_t)(~HASH_CR_MDMAT) /** * @brief Start the digest computation * @retval None */ #define __HAL_HASH_START_DIGEST() HASH->STR |= HASH_STR_DCAL /** * @brief Set the number of valid bits in last word written in Data register * @param SIZE: size in byte of last data written in Data register. * @retval None */ #define __HAL_HASH_SET_NBVALIDBITS(SIZE) do{HASH->STR &= ~(HASH_STR_NBLW);\ HASH->STR |= 8 * ((SIZE) % 4);\ }while(0) /** * @} */ /* Include HASH HAL Extension module */ #include "stm32f4xx_hal_hash_ex.h" /* Exported functions --------------------------------------------------------*/ /** @defgroup HASH_Exported_Functions HASH Exported Functions * @{ */ /** @addtogroup HASH_Exported_Functions_Group1 * @{ */ HAL_StatusTypeDef HAL_HASH_Init(HASH_HandleTypeDef *hhash); HAL_StatusTypeDef HAL_HASH_DeInit(HASH_HandleTypeDef *hhash); /** * @} */ /** @addtogroup HASH_Exported_Functions_Group2 * @{ */ HAL_StatusTypeDef HAL_HASH_SHA1_Start(HASH_HandleTypeDef *hhash, uint8_t *pInBuffer, uint32_t Size, uint8_t* pOutBuffer, uint32_t Timeout); HAL_StatusTypeDef HAL_HASH_MD5_Start(HASH_HandleTypeDef *hhash, uint8_t *pInBuffer, uint32_t Size, uint8_t* pOutBuffer, uint32_t Timeout); HAL_StatusTypeDef HAL_HASH_MD5_Accumulate(HASH_HandleTypeDef *hhash, uint8_t *pInBuffer, uint32_t Size); HAL_StatusTypeDef HAL_HASH_SHA1_Accumulate(HASH_HandleTypeDef *hhash, uint8_t *pInBuffer, uint32_t Size); /** * @} */ /** @addtogroup HASH_Exported_Functions_Group3 * @{ */ HAL_StatusTypeDef HAL_HMAC_SHA1_Start(HASH_HandleTypeDef *hhash, uint8_t *pInBuffer, uint32_t Size, uint8_t* pOutBuffer, uint32_t Timeout); HAL_StatusTypeDef HAL_HMAC_MD5_Start(HASH_HandleTypeDef *hhash, uint8_t *pInBuffer, uint32_t Size, uint8_t* pOutBuffer, uint32_t Timeout); /** * @} */ /** @addtogroup HASH_Exported_Functions_Group4 * @{ */ HAL_StatusTypeDef HAL_HASH_SHA1_Start_IT(HASH_HandleTypeDef *hhash, uint8_t *pInBuffer, uint32_t Size, uint8_t* pOutBuffer); HAL_StatusTypeDef HAL_HASH_MD5_Start_IT(HASH_HandleTypeDef *hhash, uint8_t *pInBuffer, uint32_t Size, uint8_t* pOutBuffer); /** * @} */ /** @addtogroup HASH_Exported_Functions_Group5 * @{ */ HAL_StatusTypeDef HAL_HASH_SHA1_Start_DMA(HASH_HandleTypeDef *hhash, uint8_t *pInBuffer, uint32_t Size); HAL_StatusTypeDef HAL_HASH_SHA1_Finish(HASH_HandleTypeDef *hhash, uint8_t* pOutBuffer, uint32_t Timeout); HAL_StatusTypeDef HAL_HASH_MD5_Start_DMA(HASH_HandleTypeDef *hhash, uint8_t *pInBuffer, uint32_t Size); HAL_StatusTypeDef HAL_HASH_MD5_Finish(HASH_HandleTypeDef *hhash, uint8_t* pOutBuffer, uint32_t Timeout); /** * @} */ /** @addtogroup HASH_Exported_Functions_Group6 * @{ */ HAL_StatusTypeDef HAL_HMAC_SHA1_Start_DMA(HASH_HandleTypeDef *hhash, uint8_t *pInBuffer, uint32_t Size); HAL_StatusTypeDef HAL_HMAC_MD5_Start_DMA(HASH_HandleTypeDef *hhash, uint8_t *pInBuffer, uint32_t Size); /** * @} */ /** @addtogroup HASH_Exported_Functions_Group7 * @{ */ void HAL_HASH_IRQHandler(HASH_HandleTypeDef *hhash); /** * @} */ /** @addtogroup HASH_Exported_Functions_Group8 * @{ */ HAL_HASH_STATETypeDef HAL_HASH_GetState(HASH_HandleTypeDef *hhash); void HAL_HASH_MspInit(HASH_HandleTypeDef *hhash); void HAL_HASH_MspDeInit(HASH_HandleTypeDef *hhash); void HAL_HASH_InCpltCallback(HASH_HandleTypeDef *hhash); void HAL_HASH_DgstCpltCallback(HASH_HandleTypeDef *hhash); void HAL_HASH_ErrorCallback(HASH_HandleTypeDef *hhash); /** * @} */ /** * @} */ /* Private types -------------------------------------------------------------*/ /** @defgroup HASH_Private_Types HASH Private Types * @{ */ /** * @} */ /* Private variables ---------------------------------------------------------*/ /** @defgroup HASH_Private_Variables HASH Private Variables * @{ */ /** * @} */ /* Private constants ---------------------------------------------------------*/ /** @defgroup HASH_Private_Constants HASH Private Constants * @{ */ /** * @} */ /* Private macros ------------------------------------------------------------*/ /** @defgroup HASH_Private_Macros HASH Private Macros * @{ */ #define IS_HASH_ALGOSELECTION(__ALGOSELECTION__) (((__ALGOSELECTION__) == HASH_ALGOSELECTION_SHA1) || \ ((__ALGOSELECTION__) == HASH_ALGOSELECTION_SHA224) || \ ((__ALGOSELECTION__) == HASH_ALGOSELECTION_SHA256) || \ ((__ALGOSELECTION__) == HASH_ALGOSELECTION_MD5)) #define IS_HASH_ALGOMODE(__ALGOMODE__) (((__ALGOMODE__) == HASH_ALGOMODE_HASH) || \ ((__ALGOMODE__) == HASH_ALGOMODE_HMAC)) #define IS_HASH_DATATYPE(__DATATYPE__) (((__DATATYPE__) == HASH_DATATYPE_32B)|| \ ((__DATATYPE__) == HASH_DATATYPE_16B)|| \ ((__DATATYPE__) == HASH_DATATYPE_8B) || \ ((__DATATYPE__) == HASH_DATATYPE_1B)) #define IS_HASH_HMAC_KEYTYPE(__KEYTYPE__) (((__KEYTYPE__) == HASH_HMAC_KEYTYPE_SHORTKEY) || \ ((__KEYTYPE__) == HASH_HMAC_KEYTYPE_LONGKEY)) #define IS_HASH_SHA1_BUFFER_SIZE(__SIZE__) ((((__SIZE__)%4) != 0)? 0U: 1U) /** * @} */ /* Private functions ---------------------------------------------------------*/ /** @defgroup HASH_Private_Functions HASH Private Functions * @{ */ /** * @} */ #endif /* STM32F415xx || STM32F417xx || STM32F437xx || STM32F439xx || STM32F479xx */ /** * @} */ /** * @} */ #ifdef __cplusplus } #endif #endif /* __STM32F4xx_HAL_HASH_H */ /************************ (C) COPYRIGHT STMicroelectronics *****END OF FILE****/ ================================================ FILE: Zelig/mbed/TARGET_NUCLEO_F411RE/stm32f4xx_hal_hash_ex.h ================================================ /** ****************************************************************************** * @file stm32f4xx_hal_hash_ex.h * @author MCD Application Team * @version V1.4.1 * @date 09-October-2015 * @brief Header file of HASH HAL Extension module. ****************************************************************************** * @attention * *

© COPYRIGHT(c) 2015 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. * ****************************************************************************** */ /* Define to prevent recursive inclusion -------------------------------------*/ #ifndef __STM32F4xx_HAL_HASH_EX_H #define __STM32F4xx_HAL_HASH_EX_H #ifdef __cplusplus extern "C" { #endif #if defined(STM32F437xx) || defined(STM32F439xx) || defined(STM32F479xx) /* Includes ------------------------------------------------------------------*/ #include "stm32f4xx_hal_def.h" /** @addtogroup STM32F4xx_HAL_Driver * @{ */ /** @addtogroup HASHEx * @brief HASHEx HAL Extension module driver * @{ */ /* Exported types ------------------------------------------------------------*/ /* Exported constants --------------------------------------------------------*/ /* Exported macro ------------------------------------------------------------*/ /* Exported functions --------------------------------------------------------*/ /** @defgroup HASHEx_Exported_Functions HASHEx Exported Functions * @{ */ /** @defgroup HASHEx_Exported_Functions_Group1 HASHEx processing using polling functions * @{ */ HAL_StatusTypeDef HAL_HASHEx_SHA224_Start(HASH_HandleTypeDef *hhash, uint8_t *pInBuffer, uint32_t Size, uint8_t* pOutBuffer, uint32_t Timeout); HAL_StatusTypeDef HAL_HASHEx_SHA256_Start(HASH_HandleTypeDef *hhash, uint8_t *pInBuffer, uint32_t Size, uint8_t* pOutBuffer, uint32_t Timeout); HAL_StatusTypeDef HAL_HASHEx_SHA224_Accumulate(HASH_HandleTypeDef *hhash, uint8_t *pInBuffer, uint32_t Size); HAL_StatusTypeDef HAL_HASHEx_SHA256_Accumulate(HASH_HandleTypeDef *hhash, uint8_t *pInBuffer, uint32_t Size); /** * @} */ /** @defgroup HASHEx_Exported_Functions_Group2 HMAC processing using polling functions * @{ */ HAL_StatusTypeDef HAL_HMACEx_SHA224_Start(HASH_HandleTypeDef *hhash, uint8_t *pInBuffer, uint32_t Size, uint8_t* pOutBuffer, uint32_t Timeout); HAL_StatusTypeDef HAL_HMACEx_SHA256_Start(HASH_HandleTypeDef *hhash, uint8_t *pInBuffer, uint32_t Size, uint8_t* pOutBuffer, uint32_t Timeout); /** * @} */ /** @defgroup HASHEx_Exported_Functions_Group3 HASHEx processing using functions * @{ */ HAL_StatusTypeDef HAL_HASHEx_SHA224_Start_IT(HASH_HandleTypeDef *hhash, uint8_t *pInBuffer, uint32_t Size, uint8_t* pOutBuffer); HAL_StatusTypeDef HAL_HASHEx_SHA256_Start_IT(HASH_HandleTypeDef *hhash, uint8_t *pInBuffer, uint32_t Size, uint8_t* pOutBuffer); /** * @} */ /** @defgroup HASHEx_Exported_Functions_Group4 HASHEx processing using DMA * @{ */ HAL_StatusTypeDef HAL_HASHEx_SHA224_Start_DMA(HASH_HandleTypeDef *hhash, uint8_t *pInBuffer, uint32_t Size); HAL_StatusTypeDef HAL_HASHEx_SHA224_Finish(HASH_HandleTypeDef *hhash, uint8_t* pOutBuffer, uint32_t Timeout); HAL_StatusTypeDef HAL_HASHEx_SHA256_Start_DMA(HASH_HandleTypeDef *hhash, uint8_t *pInBuffer, uint32_t Size); HAL_StatusTypeDef HAL_HASHEx_SHA256_Finish(HASH_HandleTypeDef *hhash, uint8_t* pOutBuffer, uint32_t Timeout); /** * @} */ /** @defgroup HASHEx_Exported_Functions_Group5 HMAC processing using DMA * @{ */ HAL_StatusTypeDef HAL_HMACEx_SHA224_Start_DMA(HASH_HandleTypeDef *hhash, uint8_t *pInBuffer, uint32_t Size); HAL_StatusTypeDef HAL_HMACEx_SHA256_Start_DMA(HASH_HandleTypeDef *hhash, uint8_t *pInBuffer, uint32_t Size); /** * @} */ /** @defgroup HASHEx_Exported_Functions_Group6 HASHEx processing functions * @{ */ void HAL_HASHEx_IRQHandler(HASH_HandleTypeDef *hhash); /** * @} */ /** * @} */ /* Private types -------------------------------------------------------------*/ /** @defgroup HASHEx_Private_Types HASHEx Private Types * @{ */ /** * @} */ /* Private variables ---------------------------------------------------------*/ /** @defgroup HASHEx_Private_Variables HASHEx Private Variables * @{ */ /** * @} */ /* Private constants ---------------------------------------------------------*/ /** @defgroup HASHEx_Private_Constants HASHEx Private Constants * @{ */ /** * @} */ /* Private macros ------------------------------------------------------------*/ /** @defgroup HASHEx_Private_Macros HASHEx Private Macros * @{ */ /** * @} */ /* Private functions ---------------------------------------------------------*/ /** @defgroup HASHEx_Private_Functions HASHEx Private Functions * @{ */ /** * @} */ #endif /* STM32F437xx || STM32F439xx || STM32F479xx */ /** * @} */ /** * @} */ #ifdef __cplusplus } #endif #endif /* __STM32F4xx_HAL_HASH_EX_H */ /************************ (C) COPYRIGHT STMicroelectronics *****END OF FILE****/ ================================================ FILE: Zelig/mbed/TARGET_NUCLEO_F411RE/stm32f4xx_hal_hcd.h ================================================ /** ****************************************************************************** * @file stm32f4xx_hal_hcd.h * @author MCD Application Team * @version V1.4.1 * @date 09-October-2015 * @brief Header file of HCD HAL module. ****************************************************************************** * @attention * *

© COPYRIGHT(c) 2015 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. * ****************************************************************************** */ /* Define to prevent recursive inclusion -------------------------------------*/ #ifndef __STM32F4xx_HAL_HCD_H #define __STM32F4xx_HAL_HCD_H #ifdef __cplusplus extern "C" { #endif #if defined(STM32F405xx) || defined(STM32F415xx) || defined(STM32F407xx) || defined(STM32F417xx) || \ defined(STM32F427xx) || defined(STM32F437xx) || defined(STM32F429xx) || defined(STM32F439xx) || \ defined(STM32F401xC) || defined(STM32F401xE) || defined(STM32F411xE) || defined(STM32F446xx) || \ defined(STM32F469xx) || defined(STM32F479xx) /* Includes ------------------------------------------------------------------*/ #include "stm32f4xx_ll_usb.h" /** @addtogroup STM32F4xx_HAL_Driver * @{ */ /** @addtogroup HCD * @{ */ /* Exported types ------------------------------------------------------------*/ /** @defgroup HCD_Exported_Types HCD Exported Types * @{ */ /** @defgroup HCD_Exported_Types_Group1 HCD State Structure definition * @{ */ typedef enum { HAL_HCD_STATE_RESET = 0x00, HAL_HCD_STATE_READY = 0x01, HAL_HCD_STATE_ERROR = 0x02, HAL_HCD_STATE_BUSY = 0x03, HAL_HCD_STATE_TIMEOUT = 0x04 } HCD_StateTypeDef; typedef USB_OTG_GlobalTypeDef HCD_TypeDef; typedef USB_OTG_CfgTypeDef HCD_InitTypeDef; typedef USB_OTG_HCTypeDef HCD_HCTypeDef ; typedef USB_OTG_URBStateTypeDef HCD_URBStateTypeDef ; typedef USB_OTG_HCStateTypeDef HCD_HCStateTypeDef ; /** * @} */ /** @defgroup HCD_Exported_Types_Group2 HCD Handle Structure definition * @{ */ typedef struct { HCD_TypeDef *Instance; /*!< Register base address */ HCD_InitTypeDef Init; /*!< HCD required parameters */ HCD_HCTypeDef hc[15]; /*!< Host channels parameters */ HAL_LockTypeDef Lock; /*!< HCD peripheral status */ __IO HCD_StateTypeDef State; /*!< HCD communication state */ void *pData; /*!< Pointer Stack Handler */ } HCD_HandleTypeDef; /** * @} */ /** * @} */ /* Exported constants --------------------------------------------------------*/ /** @defgroup HCD_Exported_Constants HCD Exported Constants * @{ */ /** @defgroup HCD_Speed HCD Speed * @{ */ #define HCD_SPEED_HIGH 0 #define HCD_SPEED_LOW 2 #define HCD_SPEED_FULL 3 /** * @} */ /** @defgroup HCD_PHY_Module HCD PHY Module * @{ */ #define HCD_PHY_ULPI 1 #define HCD_PHY_EMBEDDED 2 /** * @} */ /** * @} */ /* Exported macro ------------------------------------------------------------*/ /** @defgroup HCD_Exported_Macros HCD Exported Macros * @brief macros to handle interrupts and specific clock configurations * @{ */ #define __HAL_HCD_ENABLE(__HANDLE__) USB_EnableGlobalInt ((__HANDLE__)->Instance) #define __HAL_HCD_DISABLE(__HANDLE__) USB_DisableGlobalInt ((__HANDLE__)->Instance) #define __HAL_HCD_GET_FLAG(__HANDLE__, __INTERRUPT__) ((USB_ReadInterrupts((__HANDLE__)->Instance) & (__INTERRUPT__)) == (__INTERRUPT__)) #define __HAL_HCD_CLEAR_FLAG(__HANDLE__, __INTERRUPT__) (((__HANDLE__)->Instance->GINTSTS) = (__INTERRUPT__)) #define __HAL_HCD_IS_INVALID_INTERRUPT(__HANDLE__) (USB_ReadInterrupts((__HANDLE__)->Instance) == 0) #define __HAL_HCD_CLEAR_HC_INT(chnum, __INTERRUPT__) (USBx_HC(chnum)->HCINT = (__INTERRUPT__)) #define __HAL_HCD_MASK_HALT_HC_INT(chnum) (USBx_HC(chnum)->HCINTMSK &= ~USB_OTG_HCINTMSK_CHHM) #define __HAL_HCD_UNMASK_HALT_HC_INT(chnum) (USBx_HC(chnum)->HCINTMSK |= USB_OTG_HCINTMSK_CHHM) #define __HAL_HCD_MASK_ACK_HC_INT(chnum) (USBx_HC(chnum)->HCINTMSK &= ~USB_OTG_HCINTMSK_ACKM) #define __HAL_HCD_UNMASK_ACK_HC_INT(chnum) (USBx_HC(chnum)->HCINTMSK |= USB_OTG_HCINTMSK_ACKM) /** * @} */ /* Exported functions --------------------------------------------------------*/ /** @addtogroup HCD_Exported_Functions HCD Exported Functions * @{ */ /* Initialization/de-initialization functions ********************************/ /** @addtogroup HCD_Exported_Functions_Group1 Initialization and de-initialization functions * @{ */ HAL_StatusTypeDef HAL_HCD_Init(HCD_HandleTypeDef *hhcd); HAL_StatusTypeDef HAL_HCD_DeInit(HCD_HandleTypeDef *hhcd); HAL_StatusTypeDef HAL_HCD_HC_Init(HCD_HandleTypeDef *hhcd, uint8_t ch_num, uint8_t epnum, uint8_t dev_address, uint8_t speed, uint8_t ep_type, uint16_t mps); HAL_StatusTypeDef HAL_HCD_HC_Halt(HCD_HandleTypeDef *hhcd, uint8_t ch_num); void HAL_HCD_MspInit(HCD_HandleTypeDef *hhcd); void HAL_HCD_MspDeInit(HCD_HandleTypeDef *hhcd); /** * @} */ /* I/O operation functions ***************************************************/ /** @addtogroup HCD_Exported_Functions_Group2 Input and Output operation functions * @{ */ HAL_StatusTypeDef HAL_HCD_HC_SubmitRequest(HCD_HandleTypeDef *hhcd, uint8_t pipe, uint8_t direction, uint8_t ep_type, uint8_t token, uint8_t* pbuff, uint16_t length, uint8_t do_ping); /* Non-Blocking mode: Interrupt */ void HAL_HCD_IRQHandler(HCD_HandleTypeDef *hhcd); void HAL_HCD_SOF_Callback(HCD_HandleTypeDef *hhcd); void HAL_HCD_Connect_Callback(HCD_HandleTypeDef *hhcd); void HAL_HCD_Disconnect_Callback(HCD_HandleTypeDef *hhcd); void HAL_HCD_HC_NotifyURBChange_Callback(HCD_HandleTypeDef *hhcd, uint8_t chnum, HCD_URBStateTypeDef urb_state); /** * @} */ /* Peripheral Control functions **********************************************/ /** @addtogroup HCD_Exported_Functions_Group3 Peripheral Control functions * @{ */ HAL_StatusTypeDef HAL_HCD_ResetPort(HCD_HandleTypeDef *hhcd); HAL_StatusTypeDef HAL_HCD_Start(HCD_HandleTypeDef *hhcd); HAL_StatusTypeDef HAL_HCD_Stop(HCD_HandleTypeDef *hhcd); /** * @} */ /* Peripheral State functions ************************************************/ /** @addtogroup HCD_Exported_Functions_Group4 Peripheral State functions * @{ */ HCD_StateTypeDef HAL_HCD_GetState(HCD_HandleTypeDef *hhcd); HCD_URBStateTypeDef HAL_HCD_HC_GetURBState(HCD_HandleTypeDef *hhcd, uint8_t chnum); uint32_t HAL_HCD_HC_GetXferCount(HCD_HandleTypeDef *hhcd, uint8_t chnum); HCD_HCStateTypeDef HAL_HCD_HC_GetState(HCD_HandleTypeDef *hhcd, uint8_t chnum); uint32_t HAL_HCD_GetCurrentFrame(HCD_HandleTypeDef *hhcd); uint32_t HAL_HCD_GetCurrentSpeed(HCD_HandleTypeDef *hhcd); /** * @} */ /** * @} */ /* Private macros ------------------------------------------------------------*/ /** @defgroup HCD_Private_Macros HCD Private Macros * @{ */ /** @defgroup HCD_Instance_definition HCD Instance definition * @{ */ #if defined(STM32F405xx) || defined(STM32F415xx) || defined(STM32F407xx) || defined(STM32F417xx) || defined(STM32F427xx) ||\ defined(STM32F437xx) || defined(STM32F429xx) || defined(STM32F439xx) || defined(STM32F446xx) || defined(STM32F469xx) ||\ defined(STM32F479xx) #define IS_HCD_ALL_INSTANCE(INSTANCE) (((INSTANCE) == USB_OTG_FS) || \ ((INSTANCE) == USB_OTG_HS)) #elif defined(STM32F401xC) || defined(STM32F401xE) || defined(STM32F411xE) #define IS_HCD_ALL_INSTANCE(INSTANCE) (((INSTANCE) == USB_OTG_FS)) #endif /** * @} */ /** * @} */ /** * @} */ /** * @} */ #endif /* STM32F405xx || STM32F415xx || STM32F407xx || STM32F417xx || STM32F427xx || STM32F437xx || STM32F429xx || STM32F439xx || STM32F401xC || STM32F401xE || STM32F411xE || STM32F446xx || STM32F469xx || STM32F479xx */ #ifdef __cplusplus } #endif #endif /* __STM32F4xx_HAL_HCD_H */ /************************ (C) COPYRIGHT STMicroelectronics *****END OF FILE****/ ================================================ FILE: Zelig/mbed/TARGET_NUCLEO_F411RE/stm32f4xx_hal_i2c.h ================================================ /** ****************************************************************************** * @file stm32f4xx_hal_i2c.h * @author MCD Application Team * @version V1.4.1 * @date 09-October-2015 * @brief Header file of I2C HAL module. ****************************************************************************** * @attention * *

© COPYRIGHT(c) 2015 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. * ****************************************************************************** */ /* Define to prevent recursive inclusion -------------------------------------*/ #ifndef __STM32F4xx_HAL_I2C_H #define __STM32F4xx_HAL_I2C_H #ifdef __cplusplus extern "C" { #endif /* Includes ------------------------------------------------------------------*/ #include "stm32f4xx_hal_def.h" /** @addtogroup STM32F4xx_HAL_Driver * @{ */ /** @addtogroup I2C * @{ */ /* Exported types ------------------------------------------------------------*/ /** @defgroup I2C_Exported_Types I2C Exported Types * @{ */ /** * @brief I2C Configuration Structure definition */ typedef struct { uint32_t ClockSpeed; /*!< Specifies the clock frequency. This parameter must be set to a value lower than 400kHz */ uint32_t DutyCycle; /*!< Specifies the I2C fast mode duty cycle. This parameter can be a value of @ref I2C_duty_cycle_in_fast_mode */ uint32_t OwnAddress1; /*!< Specifies the first device own address. This parameter can be a 7-bit or 10-bit address. */ uint32_t AddressingMode; /*!< Specifies if 7-bit or 10-bit addressing mode is selected. This parameter can be a value of @ref I2C_addressing_mode */ uint32_t DualAddressMode; /*!< Specifies if dual addressing mode is selected. This parameter can be a value of @ref I2C_dual_addressing_mode */ uint32_t OwnAddress2; /*!< Specifies the second device own address if dual addressing mode is selected This parameter can be a 7-bit address. */ uint32_t GeneralCallMode; /*!< Specifies if general call mode is selected. This parameter can be a value of @ref I2C_general_call_addressing_mode */ uint32_t NoStretchMode; /*!< Specifies if nostretch mode is selected. This parameter can be a value of @ref I2C_nostretch_mode */ }I2C_InitTypeDef; /** * @brief HAL State structures definition */ typedef enum { HAL_I2C_STATE_RESET = 0x00, /*!< I2C not yet initialized or disabled */ HAL_I2C_STATE_READY = 0x01, /*!< I2C initialized and ready for use */ HAL_I2C_STATE_BUSY = 0x02, /*!< I2C internal process is ongoing */ HAL_I2C_STATE_BUSY_TX = 0x12, /*!< Data Transmission process is ongoing */ HAL_I2C_STATE_BUSY_RX = 0x22, /*!< Data Reception process is ongoing */ HAL_I2C_STATE_MEM_BUSY_TX = 0x32, /*!< Memory Data Transmission process is ongoing */ HAL_I2C_STATE_MEM_BUSY_RX = 0x42, /*!< Memory Data Reception process is ongoing */ HAL_I2C_STATE_TIMEOUT = 0x03, /*!< I2C timeout state */ HAL_I2C_STATE_ERROR = 0x04 /*!< I2C error state */ }HAL_I2C_StateTypeDef; /** * @brief I2C handle Structure definition */ typedef struct { I2C_TypeDef *Instance; /*!< I2C registers base address */ I2C_InitTypeDef Init; /*!< I2C communication parameters */ uint8_t *pBuffPtr; /*!< Pointer to I2C transfer buffer */ uint16_t XferSize; /*!< I2C transfer size */ __IO uint16_t XferCount; /*!< I2C transfer counter */ DMA_HandleTypeDef *hdmatx; /*!< I2C Tx DMA handle parameters */ DMA_HandleTypeDef *hdmarx; /*!< I2C Rx DMA handle parameters */ HAL_LockTypeDef Lock; /*!< I2C locking object */ __IO HAL_I2C_StateTypeDef State; /*!< I2C communication state */ __IO uint32_t ErrorCode; /*!< I2C Error code */ }I2C_HandleTypeDef; /** * @} */ /* Exported constants --------------------------------------------------------*/ /** @defgroup I2C_Exported_Constants I2C Exported Constants * @{ */ /** @defgroup I2C_Error_Code I2C Error Code * @brief I2C Error Code * @{ */ #define HAL_I2C_ERROR_NONE ((uint32_t)0x00000000) /*!< No error */ #define HAL_I2C_ERROR_BERR ((uint32_t)0x00000001) /*!< BERR error */ #define HAL_I2C_ERROR_ARLO ((uint32_t)0x00000002) /*!< ARLO error */ #define HAL_I2C_ERROR_AF ((uint32_t)0x00000004) /*!< AF error */ #define HAL_I2C_ERROR_OVR ((uint32_t)0x00000008) /*!< OVR error */ #define HAL_I2C_ERROR_DMA ((uint32_t)0x00000010) /*!< DMA transfer error */ #define HAL_I2C_ERROR_TIMEOUT ((uint32_t)0x00000020) /*!< Timeout Error */ /** * @} */ /** @defgroup I2C_duty_cycle_in_fast_mode I2C duty cycle in fast mode * @{ */ #define I2C_DUTYCYCLE_2 ((uint32_t)0x00000000) #define I2C_DUTYCYCLE_16_9 I2C_CCR_DUTY /** * @} */ /** @defgroup I2C_addressing_mode I2C addressing mode * @{ */ #define I2C_ADDRESSINGMODE_7BIT ((uint32_t)0x00004000) #define I2C_ADDRESSINGMODE_10BIT (I2C_OAR1_ADDMODE | ((uint32_t)0x00004000)) /** * @} */ /** @defgroup I2C_dual_addressing_mode I2C dual addressing mode * @{ */ #define I2C_DUALADDRESS_DISABLE ((uint32_t)0x00000000) #define I2C_DUALADDRESS_ENABLE I2C_OAR2_ENDUAL /** * @} */ /** @defgroup I2C_general_call_addressing_mode I2C general call addressing mode * @{ */ #define I2C_GENERALCALL_DISABLE ((uint32_t)0x00000000) #define I2C_GENERALCALL_ENABLE I2C_CR1_ENGC /** * @} */ /** @defgroup I2C_nostretch_mode I2C nostretch mode * @{ */ #define I2C_NOSTRETCH_DISABLE ((uint32_t)0x00000000) #define I2C_NOSTRETCH_ENABLE I2C_CR1_NOSTRETCH /** * @} */ /** @defgroup I2C_Memory_Address_Size I2C Memory Address Size * @{ */ #define I2C_MEMADD_SIZE_8BIT ((uint32_t)0x00000001) #define I2C_MEMADD_SIZE_16BIT ((uint32_t)0x00000010) /** * @} */ /** @defgroup I2C_Interrupt_configuration_definition I2C Interrupt configuration definition * @{ */ #define I2C_IT_BUF I2C_CR2_ITBUFEN #define I2C_IT_EVT I2C_CR2_ITEVTEN #define I2C_IT_ERR I2C_CR2_ITERREN /** * @} */ /** @defgroup I2C_Flag_definition I2C Flag definition * @{ */ #define I2C_FLAG_SMBALERT ((uint32_t)0x00018000) #define I2C_FLAG_TIMEOUT ((uint32_t)0x00014000) #define I2C_FLAG_PECERR ((uint32_t)0x00011000) #define I2C_FLAG_OVR ((uint32_t)0x00010800) #define I2C_FLAG_AF ((uint32_t)0x00010400) #define I2C_FLAG_ARLO ((uint32_t)0x00010200) #define I2C_FLAG_BERR ((uint32_t)0x00010100) #define I2C_FLAG_TXE ((uint32_t)0x00010080) #define I2C_FLAG_RXNE ((uint32_t)0x00010040) #define I2C_FLAG_STOPF ((uint32_t)0x00010010) #define I2C_FLAG_ADD10 ((uint32_t)0x00010008) #define I2C_FLAG_BTF ((uint32_t)0x00010004) #define I2C_FLAG_ADDR ((uint32_t)0x00010002) #define I2C_FLAG_SB ((uint32_t)0x00010001) #define I2C_FLAG_DUALF ((uint32_t)0x00100080) #define I2C_FLAG_SMBHOST ((uint32_t)0x00100040) #define I2C_FLAG_SMBDEFAULT ((uint32_t)0x00100020) #define I2C_FLAG_GENCALL ((uint32_t)0x00100010) #define I2C_FLAG_TRA ((uint32_t)0x00100004) #define I2C_FLAG_BUSY ((uint32_t)0x00100002) #define I2C_FLAG_MSL ((uint32_t)0x00100001) /** * @} */ /** * @} */ /* Exported macro ------------------------------------------------------------*/ /** @defgroup I2C_Exported_Macros I2C Exported Macros * @{ */ /** @brief Reset I2C handle state * @param __HANDLE__: specifies the I2C Handle. * This parameter can be I2C where x: 1, 2, or 3 to select the I2C peripheral. * @retval None */ #define __HAL_I2C_RESET_HANDLE_STATE(__HANDLE__) ((__HANDLE__)->State = HAL_I2C_STATE_RESET) /** @brief Enable or disable the specified I2C interrupts. * @param __HANDLE__: specifies the I2C Handle. * This parameter can be I2C where x: 1, 2, or 3 to select the I2C peripheral. * @param __INTERRUPT__: specifies the interrupt source to enable or disable. * This parameter can be one of the following values: * @arg I2C_IT_BUF: Buffer interrupt enable * @arg I2C_IT_EVT: Event interrupt enable * @arg I2C_IT_ERR: Error interrupt enable * @retval None */ #define __HAL_I2C_ENABLE_IT(__HANDLE__, __INTERRUPT__) ((__HANDLE__)->Instance->CR2 |= (__INTERRUPT__)) #define __HAL_I2C_DISABLE_IT(__HANDLE__, __INTERRUPT__) ((__HANDLE__)->Instance->CR2 &= (~(__INTERRUPT__))) /** @brief Checks if the specified I2C interrupt source is enabled or disabled. * @param __HANDLE__: specifies the I2C Handle. * This parameter can be I2C where x: 1, 2, or 3 to select the I2C peripheral. * @param __INTERRUPT__: specifies the I2C interrupt source to check. * This parameter can be one of the following values: * @arg I2C_IT_BUF: Buffer interrupt enable * @arg I2C_IT_EVT: Event interrupt enable * @arg I2C_IT_ERR: Error interrupt enable * @retval The new state of __INTERRUPT__ (TRUE or FALSE). */ #define __HAL_I2C_GET_IT_SOURCE(__HANDLE__, __INTERRUPT__) ((((__HANDLE__)->Instance->CR2 & (__INTERRUPT__)) == (__INTERRUPT__)) ? SET : RESET) /** @brief Checks whether the specified I2C flag is set or not. * @param __HANDLE__: specifies the I2C Handle. * This parameter can be I2C where x: 1, 2, or 3 to select the I2C peripheral. * @param __FLAG__: specifies the flag to check. * This parameter can be one of the following values: * @arg I2C_FLAG_SMBALERT: SMBus Alert flag * @arg I2C_FLAG_TIMEOUT: Timeout or Tlow error flag * @arg I2C_FLAG_PECERR: PEC error in reception flag * @arg I2C_FLAG_OVR: Overrun/Underrun flag * @arg I2C_FLAG_AF: Acknowledge failure flag * @arg I2C_FLAG_ARLO: Arbitration lost flag * @arg I2C_FLAG_BERR: Bus error flag * @arg I2C_FLAG_TXE: Data register empty flag * @arg I2C_FLAG_RXNE: Data register not empty flag * @arg I2C_FLAG_STOPF: Stop detection flag * @arg I2C_FLAG_ADD10: 10-bit header sent flag * @arg I2C_FLAG_BTF: Byte transfer finished flag * @arg I2C_FLAG_ADDR: Address sent flag * Address matched flag * @arg I2C_FLAG_SB: Start bit flag * @arg I2C_FLAG_DUALF: Dual flag * @arg I2C_FLAG_SMBHOST: SMBus host header * @arg I2C_FLAG_SMBDEFAULT: SMBus default header * @arg I2C_FLAG_GENCALL: General call header flag * @arg I2C_FLAG_TRA: Transmitter/Receiver flag * @arg I2C_FLAG_BUSY: Bus busy flag * @arg I2C_FLAG_MSL: Master/Slave flag * @retval The new state of __FLAG__ (TRUE or FALSE). */ #define __HAL_I2C_GET_FLAG(__HANDLE__, __FLAG__) ((((uint8_t)((__FLAG__) >> 16)) == 0x01)?((((__HANDLE__)->Instance->SR1) & ((__FLAG__) & I2C_FLAG_MASK)) == ((__FLAG__) & I2C_FLAG_MASK)): \ ((((__HANDLE__)->Instance->SR2) & ((__FLAG__) & I2C_FLAG_MASK)) == ((__FLAG__) & I2C_FLAG_MASK))) /** @brief Clears the I2C pending flags which are cleared by writing 0 in a specific bit. * @param __HANDLE__: specifies the I2C Handle. * This parameter can be I2C where x: 1, 2, or 3 to select the I2C peripheral. * @param __FLAG__: specifies the flag to clear. * This parameter can be any combination of the following values: * @arg I2C_FLAG_SMBALERT: SMBus Alert flag * @arg I2C_FLAG_TIMEOUT: Timeout or Tlow error flag * @arg I2C_FLAG_PECERR: PEC error in reception flag * @arg I2C_FLAG_OVR: Overrun/Underrun flag (Slave mode) * @arg I2C_FLAG_AF: Acknowledge failure flag * @arg I2C_FLAG_ARLO: Arbitration lost flag (Master mode) * @arg I2C_FLAG_BERR: Bus error flag * @retval None */ #define __HAL_I2C_CLEAR_FLAG(__HANDLE__, __FLAG__) ((__HANDLE__)->Instance->SR1 = ~((__FLAG__) & I2C_FLAG_MASK)) /** @brief Clears the I2C ADDR pending flag. * @param __HANDLE__: specifies the I2C Handle. * This parameter can be I2C where x: 1, 2, or 3 to select the I2C peripheral. * @retval None */ #define __HAL_I2C_CLEAR_ADDRFLAG(__HANDLE__) \ do{ \ __IO uint32_t tmpreg; \ tmpreg = (__HANDLE__)->Instance->SR1; \ tmpreg = (__HANDLE__)->Instance->SR2; \ UNUSED(tmpreg); \ } while(0) /** @brief Clears the I2C STOPF pending flag. * @param __HANDLE__: specifies the I2C Handle. * This parameter can be I2C where x: 1, 2, or 3 to select the I2C peripheral. * @retval None */ #define __HAL_I2C_CLEAR_STOPFLAG(__HANDLE__) \ do{ \ __IO uint32_t tmpreg; \ tmpreg = (__HANDLE__)->Instance->SR1; \ (__HANDLE__)->Instance->CR1 |= I2C_CR1_PE; \ UNUSED(tmpreg); \ } while(0) #define __HAL_I2C_ENABLE(__HANDLE__) ((__HANDLE__)->Instance->CR1 |= I2C_CR1_PE) #define __HAL_I2C_DISABLE(__HANDLE__) ((__HANDLE__)->Instance->CR1 &= ~I2C_CR1_PE) /** * @} */ /* Include I2C HAL Extension module */ #include "stm32f4xx_hal_i2c_ex.h" /* Exported functions --------------------------------------------------------*/ /** @addtogroup I2C_Exported_Functions * @{ */ /** @addtogroup I2C_Exported_Functions_Group1 * @{ */ /* Initialization/de-initialization functions **********************************/ HAL_StatusTypeDef HAL_I2C_Init(I2C_HandleTypeDef *hi2c); HAL_StatusTypeDef HAL_I2C_DeInit (I2C_HandleTypeDef *hi2c); void HAL_I2C_MspInit(I2C_HandleTypeDef *hi2c); void HAL_I2C_MspDeInit(I2C_HandleTypeDef *hi2c); /** * @} */ /** @addtogroup I2C_Exported_Functions_Group2 * @{ */ /* I/O operation functions *****************************************************/ /******* Blocking mode: Polling */ HAL_StatusTypeDef HAL_I2C_Master_Transmit(I2C_HandleTypeDef *hi2c, uint16_t DevAddress, uint8_t *pData, uint16_t Size, uint32_t Timeout); HAL_StatusTypeDef HAL_I2C_Master_Receive(I2C_HandleTypeDef *hi2c, uint16_t DevAddress, uint8_t *pData, uint16_t Size, uint32_t Timeout); HAL_StatusTypeDef HAL_I2C_Slave_Transmit(I2C_HandleTypeDef *hi2c, uint8_t *pData, uint16_t Size, uint32_t Timeout); HAL_StatusTypeDef HAL_I2C_Slave_Receive(I2C_HandleTypeDef *hi2c, uint8_t *pData, uint16_t Size, uint32_t Timeout); HAL_StatusTypeDef HAL_I2C_Mem_Write(I2C_HandleTypeDef *hi2c, uint16_t DevAddress, uint16_t MemAddress, uint16_t MemAddSize, uint8_t *pData, uint16_t Size, uint32_t Timeout); HAL_StatusTypeDef HAL_I2C_Mem_Read(I2C_HandleTypeDef *hi2c, uint16_t DevAddress, uint16_t MemAddress, uint16_t MemAddSize, uint8_t *pData, uint16_t Size, uint32_t Timeout); HAL_StatusTypeDef HAL_I2C_IsDeviceReady(I2C_HandleTypeDef *hi2c, uint16_t DevAddress, uint32_t Trials, uint32_t Timeout); /******* Non-Blocking mode: Interrupt */ HAL_StatusTypeDef HAL_I2C_Master_Transmit_IT(I2C_HandleTypeDef *hi2c, uint16_t DevAddress, uint8_t *pData, uint16_t Size); HAL_StatusTypeDef HAL_I2C_Master_Receive_IT(I2C_HandleTypeDef *hi2c, uint16_t DevAddress, uint8_t *pData, uint16_t Size); HAL_StatusTypeDef HAL_I2C_Slave_Transmit_IT(I2C_HandleTypeDef *hi2c, uint8_t *pData, uint16_t Size); HAL_StatusTypeDef HAL_I2C_Slave_Receive_IT(I2C_HandleTypeDef *hi2c, uint8_t *pData, uint16_t Size); HAL_StatusTypeDef HAL_I2C_Mem_Write_IT(I2C_HandleTypeDef *hi2c, uint16_t DevAddress, uint16_t MemAddress, uint16_t MemAddSize, uint8_t *pData, uint16_t Size); HAL_StatusTypeDef HAL_I2C_Mem_Read_IT(I2C_HandleTypeDef *hi2c, uint16_t DevAddress, uint16_t MemAddress, uint16_t MemAddSize, uint8_t *pData, uint16_t Size); /******* Non-Blocking mode: DMA */ HAL_StatusTypeDef HAL_I2C_Master_Transmit_DMA(I2C_HandleTypeDef *hi2c, uint16_t DevAddress, uint8_t *pData, uint16_t Size); HAL_StatusTypeDef HAL_I2C_Master_Receive_DMA(I2C_HandleTypeDef *hi2c, uint16_t DevAddress, uint8_t *pData, uint16_t Size); HAL_StatusTypeDef HAL_I2C_Slave_Transmit_DMA(I2C_HandleTypeDef *hi2c, uint8_t *pData, uint16_t Size); HAL_StatusTypeDef HAL_I2C_Slave_Receive_DMA(I2C_HandleTypeDef *hi2c, uint8_t *pData, uint16_t Size); HAL_StatusTypeDef HAL_I2C_Mem_Write_DMA(I2C_HandleTypeDef *hi2c, uint16_t DevAddress, uint16_t MemAddress, uint16_t MemAddSize, uint8_t *pData, uint16_t Size); HAL_StatusTypeDef HAL_I2C_Mem_Read_DMA(I2C_HandleTypeDef *hi2c, uint16_t DevAddress, uint16_t MemAddress, uint16_t MemAddSize, uint8_t *pData, uint16_t Size); /******* I2C IRQHandler and Callbacks used in non blocking modes (Interrupt and DMA) */ void HAL_I2C_EV_IRQHandler(I2C_HandleTypeDef *hi2c); void HAL_I2C_ER_IRQHandler(I2C_HandleTypeDef *hi2c); void HAL_I2C_MasterTxCpltCallback(I2C_HandleTypeDef *hi2c); void HAL_I2C_MasterRxCpltCallback(I2C_HandleTypeDef *hi2c); void HAL_I2C_SlaveTxCpltCallback(I2C_HandleTypeDef *hi2c); void HAL_I2C_SlaveRxCpltCallback(I2C_HandleTypeDef *hi2c); void HAL_I2C_MemTxCpltCallback(I2C_HandleTypeDef *hi2c); void HAL_I2C_MemRxCpltCallback(I2C_HandleTypeDef *hi2c); void HAL_I2C_ErrorCallback(I2C_HandleTypeDef *hi2c); /** * @} */ /** @addtogroup I2C_Exported_Functions_Group3 * @{ */ /* Peripheral Control and State functions **************************************/ HAL_I2C_StateTypeDef HAL_I2C_GetState(I2C_HandleTypeDef *hi2c); uint32_t HAL_I2C_GetError(I2C_HandleTypeDef *hi2c); /** * @} */ /** * @} */ /* Private types -------------------------------------------------------------*/ /* Private variables ---------------------------------------------------------*/ /* Private constants ---------------------------------------------------------*/ /** @defgroup I2C_Private_Constants I2C Private Constants * @{ */ #define I2C_FLAG_MASK ((uint32_t)0x0000FFFF) /** * @} */ /* Private macros ------------------------------------------------------------*/ /** @defgroup I2C_Private_Macros I2C Private Macros * @{ */ #define I2C_FREQRANGE(__PCLK__) ((__PCLK__)/1000000) #define I2C_RISE_TIME(__FREQRANGE__, __SPEED__) (((__SPEED__) <= 100000) ? ((__FREQRANGE__) + 1) : ((((__FREQRANGE__) * 300) / 1000) + 1)) #define I2C_SPEED_STANDARD(__PCLK__, __SPEED__) (((((__PCLK__)/((__SPEED__) << 1)) & I2C_CCR_CCR) < 4)? 4:((__PCLK__) / ((__SPEED__) << 1))) #define I2C_SPEED_FAST(__PCLK__, __SPEED__, __DUTYCYCLE__) (((__DUTYCYCLE__) == I2C_DUTYCYCLE_2)? ((__PCLK__) / ((__SPEED__) * 3)) : (((__PCLK__) / ((__SPEED__) * 25)) | I2C_DUTYCYCLE_16_9)) #define I2C_SPEED(__PCLK__, __SPEED__, __DUTYCYCLE__) (((__SPEED__) <= 100000)? (I2C_SPEED_STANDARD((__PCLK__), (__SPEED__))) : \ ((I2C_SPEED_FAST((__PCLK__), (__SPEED__), (__DUTYCYCLE__)) & I2C_CCR_CCR) == 0)? 1 : \ ((I2C_SPEED_FAST((__PCLK__), (__SPEED__), (__DUTYCYCLE__))) | I2C_CCR_FS)) #define I2C_7BIT_ADD_WRITE(__ADDRESS__) ((uint8_t)((__ADDRESS__) & (~I2C_OAR1_ADD0))) #define I2C_7BIT_ADD_READ(__ADDRESS__) ((uint8_t)((__ADDRESS__) | I2C_OAR1_ADD0)) #define I2C_10BIT_ADDRESS(__ADDRESS__) ((uint8_t)((uint16_t)((__ADDRESS__) & (uint16_t)(0x00FF)))) #define I2C_10BIT_HEADER_WRITE(__ADDRESS__) ((uint8_t)((uint16_t)((uint16_t)(((uint16_t)((__ADDRESS__) & (uint16_t)(0x0300))) >> 7) | (uint16_t)(0xF0)))) #define I2C_10BIT_HEADER_READ(__ADDRESS__) ((uint8_t)((uint16_t)((uint16_t)(((uint16_t)((__ADDRESS__) & (uint16_t)(0x0300))) >> 7) | (uint16_t)(0xF1)))) #define I2C_MEM_ADD_MSB(__ADDRESS__) ((uint8_t)((uint16_t)(((uint16_t)((__ADDRESS__) & (uint16_t)(0xFF00))) >> 8))) #define I2C_MEM_ADD_LSB(__ADDRESS__) ((uint8_t)((uint16_t)((__ADDRESS__) & (uint16_t)(0x00FF)))) /** @defgroup I2C_IS_RTC_Definitions I2C Private macros to check input parameters * @{ */ #define IS_I2C_DUTY_CYCLE(CYCLE) (((CYCLE) == I2C_DUTYCYCLE_2) || \ ((CYCLE) == I2C_DUTYCYCLE_16_9)) #define IS_I2C_ADDRESSING_MODE(ADDRESS) (((ADDRESS) == I2C_ADDRESSINGMODE_7BIT) || \ ((ADDRESS) == I2C_ADDRESSINGMODE_10BIT)) #define IS_I2C_DUAL_ADDRESS(ADDRESS) (((ADDRESS) == I2C_DUALADDRESS_DISABLE) || \ ((ADDRESS) == I2C_DUALADDRESS_ENABLE)) #define IS_I2C_GENERAL_CALL(CALL) (((CALL) == I2C_GENERALCALL_DISABLE) || \ ((CALL) == I2C_GENERALCALL_ENABLE)) #define IS_I2C_NO_STRETCH(STRETCH) (((STRETCH) == I2C_NOSTRETCH_DISABLE) || \ ((STRETCH) == I2C_NOSTRETCH_ENABLE)) #define IS_I2C_MEMADD_SIZE(SIZE) (((SIZE) == I2C_MEMADD_SIZE_8BIT) || \ ((SIZE) == I2C_MEMADD_SIZE_16BIT)) #define IS_I2C_CLOCK_SPEED(SPEED) (((SPEED) > 0) && ((SPEED) <= 400000)) #define IS_I2C_OWN_ADDRESS1(ADDRESS1) (((ADDRESS1) & (uint32_t)(0xFFFFFC00)) == 0) #define IS_I2C_OWN_ADDRESS2(ADDRESS2) (((ADDRESS2) & (uint32_t)(0xFFFFFF01)) == 0) /** * @} */ /** * @} */ /* Private functions ---------------------------------------------------------*/ /** @defgroup I2C_Private_Functions I2C Private Functions * @{ */ /** * @} */ /** * @} */ /** * @} */ #ifdef __cplusplus } #endif #endif /* __STM32F4xx_HAL_I2C_H */ /************************ (C) COPYRIGHT STMicroelectronics *****END OF FILE****/ ================================================ FILE: Zelig/mbed/TARGET_NUCLEO_F411RE/stm32f4xx_hal_i2c_ex.h ================================================ /** ****************************************************************************** * @file stm32f4xx_hal_i2c_ex.h * @author MCD Application Team * @version V1.4.1 * @date 09-October-2015 * @brief Header file of I2C HAL Extension module. ****************************************************************************** * @attention * *

© COPYRIGHT(c) 2015 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. * ****************************************************************************** */ /* Define to prevent recursive inclusion -------------------------------------*/ #ifndef __STM32F4xx_HAL_I2C_EX_H #define __STM32F4xx_HAL_I2C_EX_H #ifdef __cplusplus extern "C" { #endif #if defined(STM32F427xx) || defined(STM32F437xx) || defined(STM32F429xx) || defined(STM32F439xx) ||\ defined(STM32F401xC) || defined(STM32F401xE) || defined(STM32F411xE) || defined(STM32F446xx) ||\ defined(STM32F469xx) || defined(STM32F479xx) /* Includes ------------------------------------------------------------------*/ #include "stm32f4xx_hal_def.h" /** @addtogroup STM32F4xx_HAL_Driver * @{ */ /** @addtogroup I2CEx * @{ */ /* Exported types ------------------------------------------------------------*/ /* Exported constants --------------------------------------------------------*/ /** @defgroup I2CEx_Exported_Constants I2C Exported Constants * @{ */ /** @defgroup I2CEx_Analog_Filter I2C Analog Filter * @{ */ #define I2C_ANALOGFILTER_ENABLE ((uint32_t)0x00000000) #define I2C_ANALOGFILTER_DISABLE I2C_FLTR_ANOFF /** * @} */ /** * @} */ /* Exported macro ------------------------------------------------------------*/ /* Exported functions --------------------------------------------------------*/ /** @addtogroup I2CEx_Exported_Functions * @{ */ /** @addtogroup I2CEx_Exported_Functions_Group1 * @{ */ /* Peripheral Control functions ************************************************/ HAL_StatusTypeDef HAL_I2CEx_ConfigAnalogFilter(I2C_HandleTypeDef *hi2c, uint32_t AnalogFilter); HAL_StatusTypeDef HAL_I2CEx_ConfigDigitalFilter(I2C_HandleTypeDef *hi2c, uint32_t DigitalFilter); /** * @} */ /** * @} */ /* Private types -------------------------------------------------------------*/ /* Private variables ---------------------------------------------------------*/ /* Private constants ---------------------------------------------------------*/ /** @defgroup I2CEx_Private_Constants I2C Private Constants * @{ */ /** * @} */ /* Private macros ------------------------------------------------------------*/ /** @defgroup I2CEx_Private_Macros I2C Private Macros * @{ */ #define IS_I2C_ANALOG_FILTER(FILTER) (((FILTER) == I2C_ANALOGFILTER_ENABLE) || \ ((FILTER) == I2C_ANALOGFILTER_DISABLE)) #define IS_I2C_DIGITAL_FILTER(FILTER) ((FILTER) <= 0x0000000F) /** * @} */ /** * @} */ /** * @} */ #endif /* STM32F427xx || STM32F429xx || STM32F437xx || STM32F439xx || STM32F401xC ||\ STM32F401xE || STM32F411xE || STM32F446xx || STM32F469xx || STM32F479xx */ #ifdef __cplusplus } #endif #endif /* __STM32F4xx_HAL_I2C_EX_H */ /************************ (C) COPYRIGHT STMicroelectronics *****END OF FILE****/ ================================================ FILE: Zelig/mbed/TARGET_NUCLEO_F411RE/stm32f4xx_hal_i2s.h ================================================ /** ****************************************************************************** * @file stm32f4xx_hal_i2s.h * @author MCD Application Team * @version V1.4.1 * @date 09-October-2015 * @brief Header file of I2S HAL module. ****************************************************************************** * @attention * *

© COPYRIGHT(c) 2015 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. * ****************************************************************************** */ /* Define to prevent recursive inclusion -------------------------------------*/ #ifndef __STM32F4xx_HAL_I2S_H #define __STM32F4xx_HAL_I2S_H #ifdef __cplusplus extern "C" { #endif /* Includes ------------------------------------------------------------------*/ #include "stm32f4xx_hal_def.h" /** @addtogroup STM32F4xx_HAL_Driver * @{ */ /** @addtogroup I2S * @{ */ /* Exported types ------------------------------------------------------------*/ /** @defgroup I2S_Exported_Types I2S Exported Types * @{ */ /** * @brief I2S Init structure definition */ typedef struct { uint32_t Mode; /*!< Specifies the I2S operating mode. This parameter can be a value of @ref I2S_Mode */ uint32_t Standard; /*!< Specifies the standard used for the I2S communication. This parameter can be a value of @ref I2S_Standard */ uint32_t DataFormat; /*!< Specifies the data format for the I2S communication. This parameter can be a value of @ref I2S_Data_Format */ uint32_t MCLKOutput; /*!< Specifies whether the I2S MCLK output is enabled or not. This parameter can be a value of @ref I2S_MCLK_Output */ uint32_t AudioFreq; /*!< Specifies the frequency selected for the I2S communication. This parameter can be a value of @ref I2S_Audio_Frequency */ uint32_t CPOL; /*!< Specifies the idle state of the I2S clock. This parameter can be a value of @ref I2S_Clock_Polarity */ uint32_t ClockSource; /*!< Specifies the I2S Clock Source. This parameter can be a value of @ref I2S_Clock_Source */ uint32_t FullDuplexMode; /*!< Specifies the I2S FullDuplex mode. This parameter can be a value of @ref I2S_FullDuplex_Mode */ }I2S_InitTypeDef; /** * @brief HAL State structures definition */ typedef enum { HAL_I2S_STATE_RESET = 0x00, /*!< I2S not yet initialized or disabled */ HAL_I2S_STATE_READY = 0x01, /*!< I2S initialized and ready for use */ HAL_I2S_STATE_BUSY = 0x02, /*!< I2S internal process is ongoing */ HAL_I2S_STATE_BUSY_TX = 0x12, /*!< Data Transmission process is ongoing */ HAL_I2S_STATE_BUSY_RX = 0x22, /*!< Data Reception process is ongoing */ HAL_I2S_STATE_BUSY_TX_RX = 0x32, /*!< Data Transmission and Reception process is ongoing */ HAL_I2S_STATE_TIMEOUT = 0x03, /*!< I2S timeout state */ HAL_I2S_STATE_ERROR = 0x04 /*!< I2S error state */ }HAL_I2S_StateTypeDef; /** * @brief I2S handle Structure definition */ typedef struct { SPI_TypeDef *Instance; /* I2S registers base address */ I2S_InitTypeDef Init; /* I2S communication parameters */ uint16_t *pTxBuffPtr; /* Pointer to I2S Tx transfer buffer */ __IO uint16_t TxXferSize; /* I2S Tx transfer size */ __IO uint16_t TxXferCount; /* I2S Tx transfer Counter */ uint16_t *pRxBuffPtr; /* Pointer to I2S Rx transfer buffer */ __IO uint16_t RxXferSize; /* I2S Rx transfer size */ __IO uint16_t RxXferCount; /* I2S Rx transfer counter */ DMA_HandleTypeDef *hdmatx; /* I2S Tx DMA handle parameters */ DMA_HandleTypeDef *hdmarx; /* I2S Rx DMA handle parameters */ __IO HAL_LockTypeDef Lock; /* I2S locking object */ __IO HAL_I2S_StateTypeDef State; /* I2S communication state */ __IO uint32_t ErrorCode; /* I2S Error code */ }I2S_HandleTypeDef; /** * @} */ /* Exported constants --------------------------------------------------------*/ /** @defgroup I2S_Exported_Constants I2S Exported Constants * @{ */ /** @defgroup I2S_Error_Code I2S Error Code * @brief I2S Error Code * @{ */ #define HAL_I2S_ERROR_NONE ((uint32_t)0x00000000) /*!< No error */ #define HAL_I2S_ERROR_UDR ((uint32_t)0x00000001) /*!< I2S Underrun error */ #define HAL_I2S_ERROR_OVR ((uint32_t)0x00000002) /*!< I2S Overrun error */ #define HAL_I2SEX_ERROR_UDR ((uint32_t)0x00000004) /*!< I2S extended Underrun error */ #define HAL_I2SEX_ERROR_OVR ((uint32_t)0x00000008) /*!< I2S extended Overrun error */ #define HAL_I2S_ERROR_FRE ((uint32_t)0x00000010) /*!< I2S Frame format error */ #define HAL_I2S_ERROR_DMA ((uint32_t)0x00000020) /*!< DMA transfer error */ /** * @} */ /** @defgroup I2S_Mode I2S Mode * @{ */ #define I2S_MODE_SLAVE_TX ((uint32_t)0x00000000) #define I2S_MODE_SLAVE_RX ((uint32_t)0x00000100) #define I2S_MODE_MASTER_TX ((uint32_t)0x00000200) #define I2S_MODE_MASTER_RX ((uint32_t)0x00000300) /** * @} */ /** @defgroup I2S_Standard I2S Standard * @{ */ #define I2S_STANDARD_PHILIPS ((uint32_t)0x00000000) #define I2S_STANDARD_MSB ((uint32_t)0x00000010) #define I2S_STANDARD_LSB ((uint32_t)0x00000020) #define I2S_STANDARD_PCM_SHORT ((uint32_t)0x00000030) #define I2S_STANDARD_PCM_LONG ((uint32_t)0x000000B0) /** * @} */ /** @defgroup I2S_Data_Format I2S Data Format * @{ */ #define I2S_DATAFORMAT_16B ((uint32_t)0x00000000) #define I2S_DATAFORMAT_16B_EXTENDED ((uint32_t)0x00000001) #define I2S_DATAFORMAT_24B ((uint32_t)0x00000003) #define I2S_DATAFORMAT_32B ((uint32_t)0x00000005) /** * @} */ /** @defgroup I2S_MCLK_Output I2S Mclk Output * @{ */ #define I2S_MCLKOUTPUT_ENABLE ((uint32_t)SPI_I2SPR_MCKOE) #define I2S_MCLKOUTPUT_DISABLE ((uint32_t)0x00000000) /** * @} */ /** @defgroup I2S_Audio_Frequency I2S Audio Frequency * @{ */ #define I2S_AUDIOFREQ_192K ((uint32_t)192000) #define I2S_AUDIOFREQ_96K ((uint32_t)96000) #define I2S_AUDIOFREQ_48K ((uint32_t)48000) #define I2S_AUDIOFREQ_44K ((uint32_t)44100) #define I2S_AUDIOFREQ_32K ((uint32_t)32000) #define I2S_AUDIOFREQ_22K ((uint32_t)22050) #define I2S_AUDIOFREQ_16K ((uint32_t)16000) #define I2S_AUDIOFREQ_11K ((uint32_t)11025) #define I2S_AUDIOFREQ_8K ((uint32_t)8000) #define I2S_AUDIOFREQ_DEFAULT ((uint32_t)2) /** * @} */ /** @defgroup I2S_FullDuplex_Mode I2S FullDuplex Mode * @{ */ #define I2S_FULLDUPLEXMODE_DISABLE ((uint32_t)0x00000000) #define I2S_FULLDUPLEXMODE_ENABLE ((uint32_t)0x00000001) /** * @} */ /** @defgroup I2S_Clock_Polarity I2S Clock Polarity * @{ */ #define I2S_CPOL_LOW ((uint32_t)0x00000000) #define I2S_CPOL_HIGH ((uint32_t)SPI_I2SCFGR_CKPOL) /** * @} */ /** @defgroup I2S_Interrupts_Definition I2S Interrupts Definition * @{ */ #define I2S_IT_TXE SPI_CR2_TXEIE #define I2S_IT_RXNE SPI_CR2_RXNEIE #define I2S_IT_ERR SPI_CR2_ERRIE /** * @} */ /** @defgroup I2S_Flags_Definition I2S Flags Definition * @{ */ #define I2S_FLAG_TXE SPI_SR_TXE #define I2S_FLAG_RXNE SPI_SR_RXNE #define I2S_FLAG_UDR SPI_SR_UDR #define I2S_FLAG_OVR SPI_SR_OVR #define I2S_FLAG_FRE SPI_SR_FRE #define I2S_FLAG_CHSIDE SPI_SR_CHSIDE #define I2S_FLAG_BSY SPI_SR_BSY /** * @} */ /** * @} */ /* Exported macro ------------------------------------------------------------*/ /** @defgroup I2S_Exported_Macros I2S Exported Macros * @{ */ /** @brief Reset I2S handle state * @param __HANDLE__: specifies the I2S Handle. * @retval None */ #define __HAL_I2S_RESET_HANDLE_STATE(__HANDLE__) ((__HANDLE__)->State = HAL_I2S_STATE_RESET) /** @brief Enable or disable the specified SPI peripheral (in I2S mode). * @param __HANDLE__: specifies the I2S Handle. * @retval None */ #define __HAL_I2S_ENABLE(__HANDLE__) ((__HANDLE__)->Instance->I2SCFGR |= SPI_I2SCFGR_I2SE) #define __HAL_I2S_DISABLE(__HANDLE__) ((__HANDLE__)->Instance->I2SCFGR &= ~SPI_I2SCFGR_I2SE) /** @brief Enable or disable the specified I2S interrupts. * @param __HANDLE__: specifies the I2S Handle. * @param __INTERRUPT__: specifies the interrupt source to enable or disable. * This parameter can be one of the following values: * @arg I2S_IT_TXE: Tx buffer empty interrupt enable * @arg I2S_IT_RXNE: RX buffer not empty interrupt enable * @arg I2S_IT_ERR: Error interrupt enable * @retval None */ #define __HAL_I2S_ENABLE_IT(__HANDLE__, __INTERRUPT__) ((__HANDLE__)->Instance->CR2 |= (__INTERRUPT__)) #define __HAL_I2S_DISABLE_IT(__HANDLE__, __INTERRUPT__) ((__HANDLE__)->Instance->CR2 &= ~(__INTERRUPT__)) /** @brief Checks if the specified I2S interrupt source is enabled or disabled. * @param __HANDLE__: specifies the I2S Handle. * This parameter can be I2S where x: 1, 2, or 3 to select the I2S peripheral. * @param __INTERRUPT__: specifies the I2S interrupt source to check. * This parameter can be one of the following values: * @arg I2S_IT_TXE: Tx buffer empty interrupt enable * @arg I2S_IT_RXNE: RX buffer not empty interrupt enable * @arg I2S_IT_ERR: Error interrupt enable * @retval The new state of __IT__ (TRUE or FALSE). */ #define __HAL_I2S_GET_IT_SOURCE(__HANDLE__, __INTERRUPT__) ((((__HANDLE__)->Instance->CR2 & (__INTERRUPT__)) == (__INTERRUPT__)) ? SET : RESET) /** @brief Checks whether the specified I2S flag is set or not. * @param __HANDLE__: specifies the I2S Handle. * @param __FLAG__: specifies the flag to check. * This parameter can be one of the following values: * @arg I2S_FLAG_RXNE: Receive buffer not empty flag * @arg I2S_FLAG_TXE: Transmit buffer empty flag * @arg I2S_FLAG_UDR: Underrun flag * @arg I2S_FLAG_OVR: Overrun flag * @arg I2S_FLAG_FRE: Frame error flag * @arg I2S_FLAG_CHSIDE: Channel Side flag * @arg I2S_FLAG_BSY: Busy flag * @retval The new state of __FLAG__ (TRUE or FALSE). */ #define __HAL_I2S_GET_FLAG(__HANDLE__, __FLAG__) ((((__HANDLE__)->Instance->SR) & (__FLAG__)) == (__FLAG__)) /** @brief Clears the I2S OVR pending flag. * @param __HANDLE__: specifies the I2S Handle. * @retval None */ #define __HAL_I2S_CLEAR_OVRFLAG(__HANDLE__) \ do{ \ __IO uint32_t tmpreg; \ tmpreg = (__HANDLE__)->Instance->DR; \ tmpreg = (__HANDLE__)->Instance->SR; \ UNUSED(tmpreg); \ } while(0) /** @brief Clears the I2S UDR pending flag. * @param __HANDLE__: specifies the I2S Handle. * @retval None */ #define __HAL_I2S_CLEAR_UDRFLAG(__HANDLE__) \ do{ \ __IO uint32_t tmpreg; \ tmpreg = (__HANDLE__)->Instance->SR; \ UNUSED(tmpreg); \ } while(0) /** * @} */ /* Include I2S Extension module */ #include "stm32f4xx_hal_i2s_ex.h" /* Exported functions --------------------------------------------------------*/ /** @addtogroup I2S_Exported_Functions * @{ */ /** @addtogroup I2S_Exported_Functions_Group1 * @{ */ /* Initialization/de-initialization functions **********************************/ HAL_StatusTypeDef HAL_I2S_Init(I2S_HandleTypeDef *hi2s); HAL_StatusTypeDef HAL_I2S_DeInit (I2S_HandleTypeDef *hi2s); void HAL_I2S_MspInit(I2S_HandleTypeDef *hi2s); void HAL_I2S_MspDeInit(I2S_HandleTypeDef *hi2s); /** * @} */ /** @addtogroup I2S_Exported_Functions_Group2 * @{ */ /* I/O operation functions *****************************************************/ /* Blocking mode: Polling */ HAL_StatusTypeDef HAL_I2S_Transmit(I2S_HandleTypeDef *hi2s, uint16_t *pData, uint16_t Size, uint32_t Timeout); HAL_StatusTypeDef HAL_I2S_Receive(I2S_HandleTypeDef *hi2s, uint16_t *pData, uint16_t Size, uint32_t Timeout); /* Non-Blocking mode: Interrupt */ HAL_StatusTypeDef HAL_I2S_Transmit_IT(I2S_HandleTypeDef *hi2s, uint16_t *pData, uint16_t Size); HAL_StatusTypeDef HAL_I2S_Receive_IT(I2S_HandleTypeDef *hi2s, uint16_t *pData, uint16_t Size); void HAL_I2S_IRQHandler(I2S_HandleTypeDef *hi2s); /* Non-Blocking mode: DMA */ HAL_StatusTypeDef HAL_I2S_Transmit_DMA(I2S_HandleTypeDef *hi2s, uint16_t *pData, uint16_t Size); HAL_StatusTypeDef HAL_I2S_Receive_DMA(I2S_HandleTypeDef *hi2s, uint16_t *pData, uint16_t Size); HAL_StatusTypeDef HAL_I2S_DMAPause(I2S_HandleTypeDef *hi2s); HAL_StatusTypeDef HAL_I2S_DMAResume(I2S_HandleTypeDef *hi2s); HAL_StatusTypeDef HAL_I2S_DMAStop(I2S_HandleTypeDef *hi2s); /* Peripheral Control and State functions **************************************/ HAL_I2S_StateTypeDef HAL_I2S_GetState(I2S_HandleTypeDef *hi2s); uint32_t HAL_I2S_GetError(I2S_HandleTypeDef *hi2s); /* Callbacks used in non blocking modes (Interrupt and DMA) *******************/ void HAL_I2S_TxHalfCpltCallback(I2S_HandleTypeDef *hi2s); void HAL_I2S_TxCpltCallback(I2S_HandleTypeDef *hi2s); void HAL_I2S_RxHalfCpltCallback(I2S_HandleTypeDef *hi2s); void HAL_I2S_RxCpltCallback(I2S_HandleTypeDef *hi2s); void HAL_I2S_ErrorCallback(I2S_HandleTypeDef *hi2s); /** * @} */ /** * @} */ /* Private types -------------------------------------------------------------*/ /* Private variables ---------------------------------------------------------*/ /* Private constants ---------------------------------------------------------*/ /** @defgroup I2S_Private_Constants I2S Private Constants * @{ */ /** * @} */ /* Private macros ------------------------------------------------------------*/ /** @defgroup I2S_Private_Macros I2S Private Macros * @{ */ #define IS_I2S_MODE(MODE) (((MODE) == I2S_MODE_SLAVE_TX) || \ ((MODE) == I2S_MODE_SLAVE_RX) || \ ((MODE) == I2S_MODE_MASTER_TX) || \ ((MODE) == I2S_MODE_MASTER_RX)) #define IS_I2S_STANDARD(STANDARD) (((STANDARD) == I2S_STANDARD_PHILIPS) || \ ((STANDARD) == I2S_STANDARD_MSB) || \ ((STANDARD) == I2S_STANDARD_LSB) || \ ((STANDARD) == I2S_STANDARD_PCM_SHORT) || \ ((STANDARD) == I2S_STANDARD_PCM_LONG)) #define IS_I2S_DATA_FORMAT(FORMAT) (((FORMAT) == I2S_DATAFORMAT_16B) || \ ((FORMAT) == I2S_DATAFORMAT_16B_EXTENDED) || \ ((FORMAT) == I2S_DATAFORMAT_24B) || \ ((FORMAT) == I2S_DATAFORMAT_32B)) #define IS_I2S_MCLK_OUTPUT(OUTPUT) (((OUTPUT) == I2S_MCLKOUTPUT_ENABLE) || \ ((OUTPUT) == I2S_MCLKOUTPUT_DISABLE)) #define IS_I2S_AUDIO_FREQ(FREQ) ((((FREQ) >= I2S_AUDIOFREQ_8K) && \ ((FREQ) <= I2S_AUDIOFREQ_192K)) || \ ((FREQ) == I2S_AUDIOFREQ_DEFAULT)) #define IS_I2S_FULLDUPLEX_MODE(MODE) (((MODE) == I2S_FULLDUPLEXMODE_DISABLE) || \ ((MODE) == I2S_FULLDUPLEXMODE_ENABLE)) #define IS_I2S_CPOL(CPOL) (((CPOL) == I2S_CPOL_LOW) || \ ((CPOL) == I2S_CPOL_HIGH)) /** * @} */ /* Private functions ---------------------------------------------------------*/ /** @defgroup I2S_Private_Functions I2S Private Functions * @{ */ void I2S_DMATxCplt(DMA_HandleTypeDef *hdma); void I2S_DMATxHalfCplt(DMA_HandleTypeDef *hdma); void I2S_DMARxCplt(DMA_HandleTypeDef *hdma); void I2S_DMARxHalfCplt(DMA_HandleTypeDef *hdma); void I2S_DMAError(DMA_HandleTypeDef *hdma); HAL_StatusTypeDef I2S_WaitFlagStateUntilTimeout(I2S_HandleTypeDef *hi2s, uint32_t Flag, uint32_t Status, uint32_t Timeout); HAL_StatusTypeDef I2S_Transmit_IT(I2S_HandleTypeDef *hi2s); HAL_StatusTypeDef I2S_Receive_IT(I2S_HandleTypeDef *hi2s); /** * @} */ /** * @} */ /** * @} */ #ifdef __cplusplus } #endif #endif /* __STM32F4xx_HAL_I2S_H */ /************************ (C) COPYRIGHT STMicroelectronics *****END OF FILE****/ ================================================ FILE: Zelig/mbed/TARGET_NUCLEO_F411RE/stm32f4xx_hal_i2s_ex.h ================================================ /** ****************************************************************************** * @file stm32f4xx_hal_i2s_ex.h * @author MCD Application Team * @version V1.4.1 * @date 09-October-2015 * @brief Header file of I2S HAL module. ****************************************************************************** * @attention * *

© COPYRIGHT(c) 2015 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. * ****************************************************************************** */ /* Define to prevent recursive inclusion -------------------------------------*/ #ifndef __STM32F4xx_HAL_I2S_EX_H #define __STM32F4xx_HAL_I2S_EX_H #ifdef __cplusplus extern "C" { #endif /* Includes ------------------------------------------------------------------*/ #include "stm32f4xx_hal_def.h" /** @addtogroup STM32F4xx_HAL_Driver * @{ */ /** @addtogroup I2SEx * @{ */ /* Exported types ------------------------------------------------------------*/ /** @defgroup I2SEx_Exported_Types I2S Exported Types * @{ */ /** * @} */ /* Exported constants --------------------------------------------------------*/ /** @defgroup I2SEx_Exported_Constants I2S Exported Constants * @{ */ /** @defgroup I2S_Clock_Source I2S Clock Source * @{ */ #if defined(STM32F405xx) || defined(STM32F415xx) || defined(STM32F407xx) || defined(STM32F417xx) || \ defined(STM32F427xx) || defined(STM32F437xx) || defined(STM32F429xx) || defined(STM32F439xx) || \ defined(STM32F401xC) || defined(STM32F401xE) || defined(STM32F411xE) || defined(STM32F469xx) || \ defined(STM32F479xx) #define I2S_CLOCK_PLL ((uint32_t)0x00000000) #define I2S_CLOCK_EXTERNAL ((uint32_t)0x00000001) #endif /* STM32F405xx || STM32F415xx || STM32F407xx || STM32F417xx || STM32F427xx || STM32F437xx || STM32F429xx || STM32F439xx || STM32F401xC || STM32F401xE || STM32F411xE || STM32F469xx || STM32F479xx */ #if defined(STM32F446xx) #define I2S_CLOCK_PLL ((uint32_t)0x00000000) #define I2S_CLOCK_EXTERNAL ((uint32_t)0x00000001) #define I2S_CLOCK_PLLR ((uint32_t)0x00000002) #define I2S_CLOCK_PLLSRC ((uint32_t)0x00000003) #endif /* STM32F446xx */ #if defined(STM32F410Tx) || defined(STM32F410Cx) || defined(STM32F410Rx) #define I2S_CLOCK_PLLSRC ((uint32_t)0x00000000) #define I2S_CLOCK_EXTERNAL ((uint32_t)0x00000001) #define I2S_CLOCK_PLLR ((uint32_t)0x00000002) #endif /* STM32F410Tx || STM32F410Cx || STM32F410Rx */ /** * @} */ /** * @} */ /* Exported macro ------------------------------------------------------------*/ /** @defgroup I2SEx_Exported_Macros I2S Exported Macros * @{ */ /** * @} */ /* Exported functions --------------------------------------------------------*/ /** @addtogroup I2SEx_Exported_Functions * @{ */ /** @addtogroup I2SEx_Exported_Functions_Group1 * @{ */ /* Extended features functions **************************************************/ /* Blocking mode: Polling */ HAL_StatusTypeDef HAL_I2SEx_TransmitReceive(I2S_HandleTypeDef *hi2s, uint16_t *pTxData, uint16_t *pRxData, uint16_t Size, uint32_t Timeout); /* Non-Blocking mode: Interrupt */ HAL_StatusTypeDef HAL_I2SEx_TransmitReceive_IT(I2S_HandleTypeDef *hi2s, uint16_t *pTxData, uint16_t *pRxData, uint16_t Size); /* Non-Blocking mode: DMA */ HAL_StatusTypeDef HAL_I2SEx_TransmitReceive_DMA(I2S_HandleTypeDef *hi2s, uint16_t *pTxData, uint16_t *pRxData, uint16_t Size); /** * @} */ /** * @} */ /* Private types -------------------------------------------------------------*/ /* Private variables ---------------------------------------------------------*/ /* Private constants ---------------------------------------------------------*/ /** @defgroup I2SEx_Private_Constants I2S Private Constants * @{ */ /** * @} */ /* Private macros ------------------------------------------------------------*/ /** @defgroup I2SEx_Private_Macros I2S Private Macros * @{ */ #if defined(STM32F405xx) || defined(STM32F415xx) || defined(STM32F407xx) || defined(STM32F417xx) || \ defined(STM32F427xx) || defined(STM32F437xx) || defined(STM32F429xx) || defined(STM32F439xx) || \ defined(STM32F401xC) || defined(STM32F401xE) || defined(STM32F411xE) || defined(STM32F469xx) || \ defined(STM32F479xx) #define IS_I2S_CLOCKSOURCE(CLOCK) (((CLOCK) == I2S_CLOCK_EXTERNAL) ||\ ((CLOCK) == I2S_CLOCK_PLL)) #endif /* STM32F405xx || STM32F415xx || STM32F407xx || STM32F417xx || STM32F427xx || STM32F437xx || STM32F429xx || STM32F439xx || STM32F401xC || STM32F401xE || STM32F411xE || STM32F469xx || STM32F479xx */ #if defined(STM32F446xx) #define IS_I2S_CLOCKSOURCE(CLOCK) (((CLOCK) == I2S_CLOCK_EXTERNAL) ||\ ((CLOCK) == I2S_CLOCK_PLL) ||\ ((CLOCK) == I2S_CLOCK_PLLSRC) ||\ ((CLOCK) == I2S_CLOCK_PLLR)) #endif /* STM32F446xx */ #if defined(STM32F410Tx) || defined(STM32F410Cx) || defined(STM32F410Rx) #define IS_I2S_CLOCKSOURCE(CLOCK) (((CLOCK) == I2S_CLOCK_EXTERNAL) ||\ ((CLOCK) == I2S_CLOCK_PLLSRC) ||\ ((CLOCK) == I2S_CLOCK_PLLR)) #endif /* STM32F410Tx || STM32F410Cx || STM32F410Rx */ #if defined(STM32F405xx) || defined(STM32F415xx) || defined(STM32F407xx) || defined(STM32F417xx) || \ defined(STM32F427xx) || defined(STM32F437xx) || defined(STM32F429xx) || defined(STM32F439xx) || \ defined(STM32F401xC) || defined(STM32F401xE) || defined(STM32F410Cx) || defined(STM32F410Rx) || \ defined(STM32F411xE) || defined(STM32F446xx) || defined(STM32F469xx) || defined(STM32F479xx) #define I2SxEXT(__INSTANCE__) ((__INSTANCE__) == (SPI2)? (SPI_TypeDef *)(I2S2ext_BASE): (SPI_TypeDef *)(I2S3ext_BASE)) #endif /* STM32F405xx || STM32F415xx || STM32F407xx || STM32F417xx || STM32F427xx || STM32F437xx || STM32F429xx || STM32F439xx || STM32F401xC || STM32F401xE || STM32F410Cx || STM32F410Rx || STM32F411xE || STM32F446xx || STM32F469xx || STM32F479xx */ /** * @} */ /* Private functions ---------------------------------------------------------*/ /** @defgroup I2SEx_Private_Functions I2S Private Functions * @{ */ HAL_StatusTypeDef I2SEx_TransmitReceive_IT(I2S_HandleTypeDef *hi2s); uint32_t I2S_GetInputClock(I2S_HandleTypeDef *hi2s); /** * @} */ /** * @} */ /** * @} */ #ifdef __cplusplus } #endif #endif /* __STM32F4xx_HAL_I2S_EX_H */ /************************ (C) COPYRIGHT STMicroelectronics *****END OF FILE****/ ================================================ FILE: Zelig/mbed/TARGET_NUCLEO_F411RE/stm32f4xx_hal_irda.h ================================================ /** ****************************************************************************** * @file stm32f4xx_hal_irda.h * @author MCD Application Team * @version V1.4.1 * @date 09-October-2015 * @brief Header file of IRDA HAL module. ****************************************************************************** * @attention * *

© COPYRIGHT(c) 2015 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. * ****************************************************************************** */ /* Define to prevent recursive inclusion -------------------------------------*/ #ifndef __STM32F4xx_HAL_IRDA_H #define __STM32F4xx_HAL_IRDA_H #ifdef __cplusplus extern "C" { #endif /* Includes ------------------------------------------------------------------*/ #include "stm32f4xx_hal_def.h" /** @addtogroup STM32F4xx_HAL_Driver * @{ */ /** @addtogroup IRDA * @{ */ /* Exported types ------------------------------------------------------------*/ /** @defgroup IRDA_Exported_Types IRDA Exported Types * @{ */ /** * @brief IRDA Init Structure definition */ typedef struct { uint32_t BaudRate; /*!< This member configures the IRDA communication baud rate. The baud rate is computed using the following formula: - IntegerDivider = ((PCLKx) / (8 * (hirda->Init.BaudRate))) - FractionalDivider = ((IntegerDivider - ((uint32_t) IntegerDivider)) * 8) + 0.5 */ uint32_t WordLength; /*!< Specifies the number of data bits transmitted or received in a frame. This parameter can be a value of @ref IRDA_Word_Length */ uint32_t Parity; /*!< Specifies the parity mode. This parameter can be a value of @ref IRDA_Parity @note When parity is enabled, the computed parity is inserted at the MSB position of the transmitted data (9th bit when the word length is set to 9 data bits; 8th bit when the word length is set to 8 data bits). */ uint32_t Mode; /*!< Specifies wether the Receive or Transmit mode is enabled or disabled. This parameter can be a value of @ref IRDA_Mode */ uint8_t Prescaler; /*!< Specifies the Prescaler */ uint32_t IrDAMode; /*!< Specifies the IrDA mode This parameter can be a value of @ref IRDA_Low_Power */ }IRDA_InitTypeDef; /** * @brief HAL State structures definition */ typedef enum { HAL_IRDA_STATE_RESET = 0x00, /*!< Peripheral is not yet Initialized */ HAL_IRDA_STATE_READY = 0x01, /*!< Peripheral Initialized and ready for use */ HAL_IRDA_STATE_BUSY = 0x02, /*!< An internal process is ongoing */ HAL_IRDA_STATE_BUSY_TX = 0x12, /*!< Data Transmission process is ongoing */ HAL_IRDA_STATE_BUSY_RX = 0x22, /*!< Data Reception process is ongoing */ HAL_IRDA_STATE_BUSY_TX_RX = 0x32, /*!< Data Transmission and Reception process is ongoing */ HAL_IRDA_STATE_TIMEOUT = 0x03, /*!< Timeout state */ HAL_IRDA_STATE_ERROR = 0x04 /*!< Error */ }HAL_IRDA_StateTypeDef; /** * @brief IRDA handle Structure definition */ typedef struct { USART_TypeDef *Instance; /* USART registers base address */ IRDA_InitTypeDef Init; /* IRDA communication parameters */ uint8_t *pTxBuffPtr; /* Pointer to IRDA Tx transfer Buffer */ uint16_t TxXferSize; /* IRDA Tx Transfer size */ uint16_t TxXferCount; /* IRDA Tx Transfer Counter */ uint8_t *pRxBuffPtr; /* Pointer to IRDA Rx transfer Buffer */ uint16_t RxXferSize; /* IRDA Rx Transfer size */ uint16_t RxXferCount; /* IRDA Rx Transfer Counter */ DMA_HandleTypeDef *hdmatx; /* IRDA Tx DMA Handle parameters */ DMA_HandleTypeDef *hdmarx; /* IRDA Rx DMA Handle parameters */ HAL_LockTypeDef Lock; /* Locking object */ __IO HAL_IRDA_StateTypeDef State; /* IRDA communication state */ __IO uint32_t ErrorCode; /* IRDA Error code */ }IRDA_HandleTypeDef; /** * @} */ /* Exported constants --------------------------------------------------------*/ /** @defgroup IRDA_Exported_Constants IRDA Exported constants * @{ */ /** @defgroup IRDA_Error_Code IRDA Error Code * @brief IRDA Error Code * @{ */ #define HAL_IRDA_ERROR_NONE ((uint32_t)0x00000000) /*!< No error */ #define HAL_IRDA_ERROR_PE ((uint32_t)0x00000001) /*!< Parity error */ #define HAL_IRDA_ERROR_NE ((uint32_t)0x00000002) /*!< Noise error */ #define HAL_IRDA_ERROR_FE ((uint32_t)0x00000004) /*!< Frame error */ #define HAL_IRDA_ERROR_ORE ((uint32_t)0x00000008) /*!< Overrun error */ #define HAL_IRDA_ERROR_DMA ((uint32_t)0x00000010) /*!< DMA transfer error */ /** * @} */ /** @defgroup IRDA_Word_Length IRDA Word Length * @{ */ #define IRDA_WORDLENGTH_8B ((uint32_t)0x00000000) #define IRDA_WORDLENGTH_9B ((uint32_t)USART_CR1_M) /** * @} */ /** @defgroup IRDA_Parity IRDA Parity * @{ */ #define IRDA_PARITY_NONE ((uint32_t)0x00000000) #define IRDA_PARITY_EVEN ((uint32_t)USART_CR1_PCE) #define IRDA_PARITY_ODD ((uint32_t)(USART_CR1_PCE | USART_CR1_PS)) /** * @} */ /** @defgroup IRDA_Mode IRDA Transfer Mode * @{ */ #define IRDA_MODE_RX ((uint32_t)USART_CR1_RE) #define IRDA_MODE_TX ((uint32_t)USART_CR1_TE) #define IRDA_MODE_TX_RX ((uint32_t)(USART_CR1_TE |USART_CR1_RE)) /** * @} */ /** @defgroup IRDA_Low_Power IRDA Low Power * @{ */ #define IRDA_POWERMODE_LOWPOWER ((uint32_t)USART_CR3_IRLP) #define IRDA_POWERMODE_NORMAL ((uint32_t)0x00000000) /** * @} */ /** @defgroup IRDA_Flags IRDA Flags * Elements values convention: 0xXXXX * - 0xXXXX : Flag mask in the SR register * @{ */ #define IRDA_FLAG_TXE ((uint32_t)0x00000080) #define IRDA_FLAG_TC ((uint32_t)0x00000040) #define IRDA_FLAG_RXNE ((uint32_t)0x00000020) #define IRDA_FLAG_IDLE ((uint32_t)0x00000010) #define IRDA_FLAG_ORE ((uint32_t)0x00000008) #define IRDA_FLAG_NE ((uint32_t)0x00000004) #define IRDA_FLAG_FE ((uint32_t)0x00000002) #define IRDA_FLAG_PE ((uint32_t)0x00000001) /** * @} */ /** @defgroup IRDA_Interrupt_definition IRDA Interrupt Definitions * Elements values convention: 0xY000XXXX * - XXXX : Interrupt mask in the XX register * - Y : Interrupt source register (2bits) * - 01: CR1 register * - 10: CR2 register * - 11: CR3 register * @{ */ #define IRDA_IT_PE ((uint32_t)(IRDA_CR1_REG_INDEX << 28 | USART_CR1_PEIE)) #define IRDA_IT_TXE ((uint32_t)(IRDA_CR1_REG_INDEX << 28 | USART_CR1_TXEIE)) #define IRDA_IT_TC ((uint32_t)(IRDA_CR1_REG_INDEX << 28 | USART_CR1_TCIE)) #define IRDA_IT_RXNE ((uint32_t)(IRDA_CR1_REG_INDEX << 28 | USART_CR1_RXNEIE)) #define IRDA_IT_IDLE ((uint32_t)(IRDA_CR1_REG_INDEX << 28 | USART_CR1_IDLEIE)) #define IRDA_IT_LBD ((uint32_t)(IRDA_CR2_REG_INDEX << 28 | USART_CR2_LBDIE)) #define IRDA_IT_CTS ((uint32_t)(IRDA_CR3_REG_INDEX << 28 | USART_CR3_CTSIE)) #define IRDA_IT_ERR ((uint32_t)(IRDA_CR3_REG_INDEX << 28 | USART_CR3_EIE)) /** * @} */ /** * @} */ /* Exported macro ------------------------------------------------------------*/ /** @defgroup IRDA_Exported_Macros IRDA Exported Macros * @{ */ /** @brief Reset IRDA handle state * @param __HANDLE__: specifies the USART Handle. * This parameter can be USARTx where x: 1, 2, 3, 4, 5, 6, 7 or 8 to select the USART or * UART peripheral. * @retval None */ #define __HAL_IRDA_RESET_HANDLE_STATE(__HANDLE__) ((__HANDLE__)->State = HAL_IRDA_STATE_RESET) /** @brief Flushs the IRDA DR register * @param __HANDLE__: specifies the USART Handle. * This parameter can be USARTx where x: 1, 2, 3, 4, 5, 6, 7 or 8 to select the USART or * UART peripheral. */ #define __HAL_IRDA_FLUSH_DRREGISTER(__HANDLE__) ((__HANDLE__)->Instance->DR) /** @brief Checks whether the specified IRDA flag is set or not. * @param __HANDLE__: specifies the USART Handle. * This parameter can be USARTx where x: 1, 2, 3, 4, 5, 6, 7 or 8 to select the USART or * UART peripheral. * @param __FLAG__: specifies the flag to check. * This parameter can be one of the following values: * @arg IRDA_FLAG_TXE: Transmit data register empty flag * @arg IRDA_FLAG_TC: Transmission Complete flag * @arg IRDA_FLAG_RXNE: Receive data register not empty flag * @arg IRDA_FLAG_IDLE: Idle Line detection flag * @arg IRDA_FLAG_ORE: OverRun Error flag * @arg IRDA_FLAG_NE: Noise Error flag * @arg IRDA_FLAG_FE: Framing Error flag * @arg IRDA_FLAG_PE: Parity Error flag * @retval The new state of __FLAG__ (TRUE or FALSE). */ #define __HAL_IRDA_GET_FLAG(__HANDLE__, __FLAG__) (((__HANDLE__)->Instance->SR & (__FLAG__)) == (__FLAG__)) /** @brief Clears the specified IRDA pending flag. * @param __HANDLE__: specifies the USART Handle. * This parameter can be USARTx where x: 1, 2, 3, 4, 5, 6, 7 or 8 to select the USART or * UART peripheral. * @param __FLAG__: specifies the flag to check. * This parameter can be any combination of the following values: * @arg IRDA_FLAG_TC: Transmission Complete flag. * @arg IRDA_FLAG_RXNE: Receive data register not empty flag. * * @note PE (Parity error), FE (Framing error), NE (Noise error), ORE (OverRun * error) and IDLE (Idle line detected) flags are cleared by software * sequence: a read operation to USART_SR register followed by a read * operation to USART_DR register. * @note RXNE flag can be also cleared by a read to the USART_DR register. * @note TC flag can be also cleared by software sequence: a read operation to * USART_SR register followed by a write operation to USART_DR register. * @note TXE flag is cleared only by a write to the USART_DR register. * * @retval None */ #define __HAL_IRDA_CLEAR_FLAG(__HANDLE__, __FLAG__) ((__HANDLE__)->Instance->SR = ~(__FLAG__)) /** @brief Clear the IRDA PE pending flag. * @param __HANDLE__: specifies the USART Handle. * This parameter can be USARTx where x: 1, 2, 3, 4, 5, 6, 7 or 8 to select the USART or * UART peripheral. * @retval None */ #define __HAL_IRDA_CLEAR_PEFLAG(__HANDLE__) \ do{ \ __IO uint32_t tmpreg; \ tmpreg = (__HANDLE__)->Instance->SR; \ UNUSED(tmpreg); \ } while(0) /** @brief Clear the IRDA FE pending flag. * @param __HANDLE__: specifies the USART Handle. * This parameter can be USARTx where x: 1, 2, 3, 4, 5, 6, 7 or 8 to select the USART or * UART peripheral. * @retval None */ #define __HAL_IRDA_CLEAR_FEFLAG(__HANDLE__) __HAL_IRDA_CLEAR_PEFLAG(__HANDLE__) /** @brief Clear the IRDA NE pending flag. * @param __HANDLE__: specifies the USART Handle. * This parameter can be USARTx where x: 1, 2, 3, 4, 5, 6, 7 or 8 to select the USART or * UART peripheral. * @retval None */ #define __HAL_IRDA_CLEAR_NEFLAG(__HANDLE__) __HAL_IRDA_CLEAR_PEFLAG(__HANDLE__) /** @brief Clear the IRDA ORE pending flag. * @param __HANDLE__: specifies the USART Handle. * This parameter can be USARTx where x: 1, 2, 3, 4, 5, 6, 7 or 8 to select the USART or * UART peripheral. * @retval None */ #define __HAL_IRDA_CLEAR_OREFLAG(__HANDLE__) __HAL_IRDA_CLEAR_PEFLAG(__HANDLE__) /** @brief Clear the IRDA IDLE pending flag. * @param __HANDLE__: specifies the USART Handle. * This parameter can be USARTx where x: 1, 2, 3, 4, 5, 6, 7 or 8 to select the USART or * UART peripheral. * @retval None */ #define __HAL_IRDA_CLEAR_IDLEFLAG(__HANDLE__) __HAL_IRDA_CLEAR_PEFLAG(__HANDLE__) /** @brief Enables or disables the specified IRDA interrupt. * @param __HANDLE__: specifies the USART Handle. * This parameter can be USARTx where x: 1, 2, 3, 4, 5, 6, 7 or 8 to select the USART or * UART peripheral. * @param __INTERRUPT__: specifies the IRDA interrupt source to check. * This parameter can be one of the following values: * @arg IRDA_IT_TXE: Transmit Data Register empty interrupt * @arg IRDA_IT_TC: Transmission complete interrupt * @arg IRDA_IT_RXNE: Receive Data register not empty interrupt * @arg IRDA_IT_IDLE: Idle line detection interrupt * @arg IRDA_IT_PE: Parity Error interrupt * @arg IRDA_IT_ERR: Error interrupt(Frame error, noise error, overrun error) * @retval None */ #define __HAL_IRDA_ENABLE_IT(__HANDLE__, __INTERRUPT__) ((((__INTERRUPT__) >> 28) == 1)? ((__HANDLE__)->Instance->CR1 |= ((__INTERRUPT__) & IRDA_IT_MASK)): \ (((__INTERRUPT__) >> 28) == 2)? ((__HANDLE__)->Instance->CR2 |= ((__INTERRUPT__) & IRDA_IT_MASK)): \ ((__HANDLE__)->Instance->CR3 |= ((__INTERRUPT__) & IRDA_IT_MASK))) #define __HAL_IRDA_DISABLE_IT(__HANDLE__, __INTERRUPT__) ((((__INTERRUPT__) >> 28) == 1)? ((__HANDLE__)->Instance->CR1 &= ~((__INTERRUPT__) & IRDA_IT_MASK)): \ (((__INTERRUPT__) >> 28) == 2)? ((__HANDLE__)->Instance->CR2 &= ~((__INTERRUPT__) & IRDA_IT_MASK)): \ ((__HANDLE__)->Instance->CR3 &= ~ ((__INTERRUPT__) & IRDA_IT_MASK))) /** @brief Checks whether the specified IRDA interrupt has occurred or not. * @param __HANDLE__: specifies the USART Handle. * This parameter can be USARTx where x: 1, 2, 3, 4, 5, 6, 7 or 8 to select the USART or * UART peripheral. * @param __IT__: specifies the IRDA interrupt source to check. * This parameter can be one of the following values: * @arg IRDA_IT_TXE: Transmit Data Register empty interrupt * @arg IRDA_IT_TC: Transmission complete interrupt * @arg IRDA_IT_RXNE: Receive Data register not empty interrupt * @arg IRDA_IT_IDLE: Idle line detection interrupt * @arg USART_IT_ERR: Error interrupt * @arg IRDA_IT_PE: Parity Error interrupt * @retval The new state of __IT__ (TRUE or FALSE). */ #define __HAL_IRDA_GET_IT_SOURCE(__HANDLE__, __IT__) (((((__IT__) >> 28) == 1)? (__HANDLE__)->Instance->CR1:(((((uint32_t)(__IT__)) >> 28) == 2)? \ (__HANDLE__)->Instance->CR2 : (__HANDLE__)->Instance->CR3)) & (((uint32_t)(__IT__)) & IRDA_IT_MASK)) /** @brief Macro to enable the IRDA's one bit sample method * @param __HANDLE__: specifies the IRDA Handle. * @retval None */ #define __HAL_IRDA_ONE_BIT_SAMPLE_ENABLE(__HANDLE__) ((__HANDLE__)->Instance->CR3|= USART_CR3_ONEBIT) /** @brief Macro to disable the IRDA's one bit sample method * @param __HANDLE__: specifies the IRDA Handle. * @retval None */ #define __HAL_IRDA_ONE_BIT_SAMPLE_DISABLE(__HANDLE__) ((__HANDLE__)->Instance->CR3 &= (uint16_t)~((uint16_t)USART_CR3_ONEBIT)) /** @brief Enable UART/USART associated to IRDA Handle * @param __HANDLE__: specifies the IRDA Handle. * IRDA Handle selects the USARTx or UARTy peripheral * (USART,UART availability and x,y values depending on device). * @retval None */ #define __HAL_IRDA_ENABLE(__HANDLE__) ((__HANDLE__)->Instance->CR1 |= USART_CR1_UE) /** @brief Disable UART/USART associated to IRDA Handle * @param __HANDLE__: specifies the IRDA Handle. * IRDA Handle selects the USARTx or UARTy peripheral * (USART,UART availability and x,y values depending on device). * @retval None */ #define __HAL_IRDA_DISABLE(__HANDLE__) ((__HANDLE__)->Instance->CR1 &= ~USART_CR1_UE) /** * @} */ /* Exported functions --------------------------------------------------------*/ /** @addtogroup IRDA_Exported_Functions * @{ */ /** @addtogroup IRDA_Exported_Functions_Group1 * @{ */ /* Initialization/de-initialization functions **********************************/ HAL_StatusTypeDef HAL_IRDA_Init(IRDA_HandleTypeDef *hirda); HAL_StatusTypeDef HAL_IRDA_DeInit(IRDA_HandleTypeDef *hirda); void HAL_IRDA_MspInit(IRDA_HandleTypeDef *hirda); void HAL_IRDA_MspDeInit(IRDA_HandleTypeDef *hirda); /** * @} */ /** @addtogroup IRDA_Exported_Functions_Group2 * @{ */ /* IO operation functions *******************************************************/ HAL_StatusTypeDef HAL_IRDA_Transmit(IRDA_HandleTypeDef *hirda, uint8_t *pData, uint16_t Size, uint32_t Timeout); HAL_StatusTypeDef HAL_IRDA_Receive(IRDA_HandleTypeDef *hirda, uint8_t *pData, uint16_t Size, uint32_t Timeout); HAL_StatusTypeDef HAL_IRDA_Transmit_IT(IRDA_HandleTypeDef *hirda, uint8_t *pData, uint16_t Size); HAL_StatusTypeDef HAL_IRDA_Receive_IT(IRDA_HandleTypeDef *hirda, uint8_t *pData, uint16_t Size); HAL_StatusTypeDef HAL_IRDA_Transmit_DMA(IRDA_HandleTypeDef *hirda, uint8_t *pData, uint16_t Size); HAL_StatusTypeDef HAL_IRDA_Receive_DMA(IRDA_HandleTypeDef *hirda, uint8_t *pData, uint16_t Size); HAL_StatusTypeDef HAL_IRDA_DMAPause(IRDA_HandleTypeDef *hirda); HAL_StatusTypeDef HAL_IRDA_DMAResume(IRDA_HandleTypeDef *hirda); HAL_StatusTypeDef HAL_IRDA_DMAStop(IRDA_HandleTypeDef *hirda); void HAL_IRDA_IRQHandler(IRDA_HandleTypeDef *hirda); void HAL_IRDA_TxCpltCallback(IRDA_HandleTypeDef *hirda); void HAL_IRDA_RxCpltCallback(IRDA_HandleTypeDef *hirda); void HAL_IRDA_TxHalfCpltCallback(IRDA_HandleTypeDef *hirda); void HAL_IRDA_RxHalfCpltCallback(IRDA_HandleTypeDef *hirda); void HAL_IRDA_ErrorCallback(IRDA_HandleTypeDef *hirda); /** * @} */ /** @addtogroup IRDA_Exported_Functions_Group3 * @{ */ /* Peripheral State functions **************************************************/ HAL_IRDA_StateTypeDef HAL_IRDA_GetState(IRDA_HandleTypeDef *hirda); uint32_t HAL_IRDA_GetError(IRDA_HandleTypeDef *hirda); /** * @} */ /** * @} */ /* Private types -------------------------------------------------------------*/ /* Private variables ---------------------------------------------------------*/ /* Private constants ---------------------------------------------------------*/ /** @defgroup IRDA_Private_Constants IRDA Private Constants * @{ */ /** @brief IRDA interruptions flag mask * */ #define IRDA_IT_MASK ((uint32_t) USART_CR1_PEIE | USART_CR1_TXEIE | USART_CR1_TCIE | USART_CR1_RXNEIE | \ USART_CR1_IDLEIE | USART_CR2_LBDIE | USART_CR3_CTSIE | USART_CR3_EIE ) #define IRDA_CR1_REG_INDEX 1 #define IRDA_CR2_REG_INDEX 2 #define IRDA_CR3_REG_INDEX 3 /** * @} */ /* Private macros --------------------------------------------------------*/ /** @defgroup IRDA_Private_Macros IRDA Private Macros * @{ */ #define IS_IRDA_WORD_LENGTH(LENGTH) (((LENGTH) == IRDA_WORDLENGTH_8B) || \ ((LENGTH) == IRDA_WORDLENGTH_9B)) #define IS_IRDA_PARITY(PARITY) (((PARITY) == IRDA_PARITY_NONE) || \ ((PARITY) == IRDA_PARITY_EVEN) || \ ((PARITY) == IRDA_PARITY_ODD)) #define IS_IRDA_MODE(MODE) ((((MODE) & (uint32_t)0x0000FFF3) == 0x00) && ((MODE) != (uint32_t)0x000000)) #define IS_IRDA_POWERMODE(MODE) (((MODE) == IRDA_POWERMODE_LOWPOWER) || \ ((MODE) == IRDA_POWERMODE_NORMAL)) #define IS_IRDA_BAUDRATE(BAUDRATE) ((BAUDRATE) < 115201) #define IRDA_DIV(_PCLK_, _BAUD_) (((_PCLK_)*25)/(4*(_BAUD_))) #define IRDA_DIVMANT(_PCLK_, _BAUD_) (IRDA_DIV((_PCLK_), (_BAUD_))/100) #define IRDA_DIVFRAQ(_PCLK_, _BAUD_) (((IRDA_DIV((_PCLK_), (_BAUD_)) - (IRDA_DIVMANT((_PCLK_), (_BAUD_)) * 100)) * 16 + 50) / 100) #define IRDA_BRR(_PCLK_, _BAUD_) ((IRDA_DIVMANT((_PCLK_), (_BAUD_)) << 4)|(IRDA_DIVFRAQ((_PCLK_), (_BAUD_)) & 0x0F)) /** * @} */ /* Private functions ---------------------------------------------------------*/ /** @defgroup IRDA_Private_Functions IRDA Private Functions * @{ */ /** * @} */ /** * @} */ /** * @} */ #ifdef __cplusplus } #endif #endif /* __STM32F4xx_HAL_IRDA_H */ /************************ (C) COPYRIGHT STMicroelectronics *****END OF FILE****/ ================================================ FILE: Zelig/mbed/TARGET_NUCLEO_F411RE/stm32f4xx_hal_iwdg.h ================================================ /** ****************************************************************************** * @file stm32f4xx_hal_iwdg.h * @author MCD Application Team * @version V1.4.1 * @date 09-October-2015 * @brief Header file of IWDG HAL module. ****************************************************************************** * @attention * *

© COPYRIGHT(c) 2015 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. * ****************************************************************************** */ /* Define to prevent recursive inclusion -------------------------------------*/ #ifndef __STM32F4xx_HAL_IWDG_H #define __STM32F4xx_HAL_IWDG_H #ifdef __cplusplus extern "C" { #endif /* Includes ------------------------------------------------------------------*/ #include "stm32f4xx_hal_def.h" /** @addtogroup STM32F4xx_HAL_Driver * @{ */ /** @addtogroup IWDG * @{ */ /* Exported types ------------------------------------------------------------*/ /** @defgroup IWDG_Exported_Types IWDG Exported Types * @{ */ /** * @brief IWDG HAL State Structure definition */ typedef enum { HAL_IWDG_STATE_RESET = 0x00, /*!< IWDG not yet initialized or disabled */ HAL_IWDG_STATE_READY = 0x01, /*!< IWDG initialized and ready for use */ HAL_IWDG_STATE_BUSY = 0x02, /*!< IWDG internal process is ongoing */ HAL_IWDG_STATE_TIMEOUT = 0x03, /*!< IWDG timeout state */ HAL_IWDG_STATE_ERROR = 0x04 /*!< IWDG error state */ }HAL_IWDG_StateTypeDef; /** * @brief IWDG Init structure definition */ typedef struct { uint32_t Prescaler; /*!< Select the prescaler of the IWDG. This parameter can be a value of @ref IWDG_Prescaler */ uint32_t Reload; /*!< Specifies the IWDG down-counter reload value. This parameter must be a number between Min_Data = 0 and Max_Data = 0x0FFF */ }IWDG_InitTypeDef; /** * @brief IWDG Handle Structure definition */ typedef struct { IWDG_TypeDef *Instance; /*!< Register base address */ IWDG_InitTypeDef Init; /*!< IWDG required parameters */ HAL_LockTypeDef Lock; /*!< IWDG Locking object */ __IO HAL_IWDG_StateTypeDef State; /*!< IWDG communication state */ }IWDG_HandleTypeDef; /** * @} */ /* Exported constants --------------------------------------------------------*/ /** @defgroup IWDG_Exported_Constants IWDG Exported Constants * @{ */ /** @defgroup IWDG_Registers_BitMask IWDG Registers BitMask * @brief IWDG registers bit mask * @{ */ /* --- KR Register ---*/ /* KR register bit mask */ #define IWDG_KEY_RELOAD ((uint32_t)0xAAAA) /*!< IWDG Reload Counter Enable */ #define IWDG_KEY_ENABLE ((uint32_t)0xCCCC) /*!< IWDG Peripheral Enable */ #define IWDG_KEY_WRITE_ACCESS_ENABLE ((uint32_t)0x5555) /*!< IWDG KR Write Access Enable */ #define IWDG_KEY_WRITE_ACCESS_DISABLE ((uint32_t)0x0000) /*!< IWDG KR Write Access Disable */ /** * @} */ /** @defgroup IWDG_Flag_definition IWDG Flag definition * @{ */ #define IWDG_FLAG_PVU ((uint32_t)IWDG_SR_PVU) /*!< Watchdog counter prescaler value update Flag */ #define IWDG_FLAG_RVU ((uint32_t)IWDG_SR_RVU) /*!< Watchdog counter reload value update Flag */ /** * @} */ /** @defgroup IWDG_Prescaler IWDG Prescaler * @{ */ #define IWDG_PRESCALER_4 ((uint8_t)0x00) /*!< IWDG prescaler set to 4 */ #define IWDG_PRESCALER_8 ((uint8_t)(IWDG_PR_PR_0)) /*!< IWDG prescaler set to 8 */ #define IWDG_PRESCALER_16 ((uint8_t)(IWDG_PR_PR_1)) /*!< IWDG prescaler set to 16 */ #define IWDG_PRESCALER_32 ((uint8_t)(IWDG_PR_PR_1 | IWDG_PR_PR_0)) /*!< IWDG prescaler set to 32 */ #define IWDG_PRESCALER_64 ((uint8_t)(IWDG_PR_PR_2)) /*!< IWDG prescaler set to 64 */ #define IWDG_PRESCALER_128 ((uint8_t)(IWDG_PR_PR_2 | IWDG_PR_PR_0)) /*!< IWDG prescaler set to 128 */ #define IWDG_PRESCALER_256 ((uint8_t)(IWDG_PR_PR_2 | IWDG_PR_PR_1)) /*!< IWDG prescaler set to 256 */ /** * @} */ /** * @} */ /* Exported macros -----------------------------------------------------------*/ /** @defgroup IWDG_Exported_Macros IWDG Exported Macros * @{ */ /** @brief Reset IWDG handle state * @param __HANDLE__: IWDG handle. * @retval None */ #define __HAL_IWDG_RESET_HANDLE_STATE(__HANDLE__) ((__HANDLE__)->State = HAL_IWDG_STATE_RESET) /** * @brief Enables the IWDG peripheral. * @param __HANDLE__: IWDG handle * @retval None */ #define __HAL_IWDG_START(__HANDLE__) WRITE_REG((__HANDLE__)->Instance->KR, IWDG_KEY_ENABLE) /** * @brief Reloads IWDG counter with value defined in the reload register * (write access to IWDG_PR and IWDG_RLR registers disabled). * @param __HANDLE__: IWDG handle * @retval None */ #define __HAL_IWDG_RELOAD_COUNTER(__HANDLE__) WRITE_REG((__HANDLE__)->Instance->KR, IWDG_KEY_RELOAD) /** * @brief Gets the selected IWDG's flag status. * @param __HANDLE__: IWDG handle * @param __FLAG__: specifies the flag to check. * This parameter can be one of the following values: * @arg IWDG_FLAG_PVU: Watchdog counter reload value update flag * @arg IWDG_FLAG_RVU: Watchdog counter prescaler value flag * @retval The new state of __FLAG__ (TRUE or FALSE). */ #define __HAL_IWDG_GET_FLAG(__HANDLE__, __FLAG__) (((__HANDLE__)->Instance->SR & (__FLAG__)) == (__FLAG__)) /** * @} */ /* Exported functions --------------------------------------------------------*/ /** @addtogroup IWDG_Exported_Functions * @{ */ /** @addtogroup IWDG_Exported_Functions_Group1 * @{ */ /* Initialization/de-initialization functions ********************************/ HAL_StatusTypeDef HAL_IWDG_Init(IWDG_HandleTypeDef *hiwdg); void HAL_IWDG_MspInit(IWDG_HandleTypeDef *hiwdg); /** * @} */ /** @addtogroup IWDG_Exported_Functions_Group2 * @{ */ /* I/O operation functions ****************************************************/ HAL_StatusTypeDef HAL_IWDG_Start(IWDG_HandleTypeDef *hiwdg); HAL_StatusTypeDef HAL_IWDG_Refresh(IWDG_HandleTypeDef *hiwdg); /** * @} */ /** @addtogroup IWDG_Exported_Functions_Group3 * @{ */ /* Peripheral State functions ************************************************/ HAL_IWDG_StateTypeDef HAL_IWDG_GetState(IWDG_HandleTypeDef *hiwdg); /** * @} */ /** * @} */ /* Private macro -------------------------------------------------------------*/ /** @defgroup IWDG_Private_Macros IWDG Private Macros * @{ */ /** * @brief Enables write access to IWDG_PR and IWDG_RLR registers. * @param __HANDLE__: IWDG handle * @retval None */ #define IWDG_ENABLE_WRITE_ACCESS(__HANDLE__) WRITE_REG((__HANDLE__)->Instance->KR, IWDG_KEY_WRITE_ACCESS_ENABLE) /** * @brief Disables write access to IWDG_PR and IWDG_RLR registers. * @param __HANDLE__: IWDG handle * @retval None */ #define IWDG_DISABLE_WRITE_ACCESS(__HANDLE__) WRITE_REG((__HANDLE__)->Instance->KR, IWDG_KEY_WRITE_ACCESS_DISABLE) #define IS_IWDG_PRESCALER(__PRESCALER__) (((__PRESCALER__) == IWDG_PRESCALER_4) || \ ((__PRESCALER__) == IWDG_PRESCALER_8) || \ ((__PRESCALER__) == IWDG_PRESCALER_16) || \ ((__PRESCALER__) == IWDG_PRESCALER_32) || \ ((__PRESCALER__) == IWDG_PRESCALER_64) || \ ((__PRESCALER__) == IWDG_PRESCALER_128)|| \ ((__PRESCALER__) == IWDG_PRESCALER_256)) #define IS_IWDG_RELOAD(__RELOAD__) ((__RELOAD__) <= 0xFFF) /** * @} */ /* Private define ------------------------------------------------------------*/ /** @defgroup IWDG_Private_Constants IWDG Private Constants * @{ */ /** * @} */ /** * @} */ /** * @} */ #ifdef __cplusplus } #endif #endif /* __STM32F4xx_HAL_IWDG_H */ /************************ (C) COPYRIGHT STMicroelectronics *****END OF FILE****/ ================================================ FILE: Zelig/mbed/TARGET_NUCLEO_F411RE/stm32f4xx_hal_lptim.h ================================================ /** ****************************************************************************** * @file stm32f4xx_hal_lptim.h * @author MCD Application Team * @version V1.4.1 * @date 09-October-2015 * @brief Header file of LPTIM HAL module. ****************************************************************************** * @attention * *

© COPYRIGHT(c) 2015 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. * ****************************************************************************** */ /* Define to prevent recursive inclusion -------------------------------------*/ #ifndef __STM32F4xx_HAL_LPTIM_H #define __STM32F4xx_HAL_LPTIM_H #ifdef __cplusplus extern "C" { #endif #if defined(STM32F410Tx) || defined(STM32F410Cx) || defined(STM32F410Rx) /* Includes ------------------------------------------------------------------*/ #include "stm32f4xx_hal_def.h" /** @addtogroup STM32F4xx_HAL_Driver * @{ */ /** @defgroup LPTIM LPTIM * @brief LPTIM HAL module driver * @{ */ /* Exported types ------------------------------------------------------------*/ /** @defgroup LPTIM_Exported_Types LPTIM Exported Types * @{ */ /** @defgroup LPTIM_WAKEUPTIMER_EXTILINE LPTIM WAKEUP Timer EXTI Line * @{ */ #define LPTIM_EXTI_LINE_WAKEUPTIMER_EVENT ((uint32_t)EXTI_IMR_MR23) /*!< External interrupt line 23 Connected to the LPTIM EXTI Line */ /** * @} */ /** * @brief LPTIM Clock configuration definition */ typedef struct { uint32_t Source; /*!< Selects the clock source. This parameter can be a value of @ref LPTIM_Clock_Source */ uint32_t Prescaler; /*!< Specifies the counter clock Prescaler. This parameter can be a value of @ref LPTIM_Clock_Prescaler */ }LPTIM_ClockConfigTypeDef; /** * @brief LPTIM Clock configuration definition */ typedef struct { uint32_t Polarity; /*!< Selects the polarity of the active edge for the counter unit if the ULPTIM input is selected. Note: This parameter is used only when Ultra low power clock source is used. Note: If the polarity is configured on 'both edges', an auxiliary clock (one of the Low power oscillator) must be active. This parameter can be a value of @ref LPTIM_Clock_Polarity */ uint32_t SampleTime; /*!< Selects the clock sampling time to configure the clock glitch filter. Note: This parameter is used only when Ultra low power clock source is used. This parameter can be a value of @ref LPTIM_Clock_Sample_Time */ }LPTIM_ULPClockConfigTypeDef; /** * @brief LPTIM Trigger configuration definition */ typedef struct { uint32_t Source; /*!< Selects the Trigger source. This parameter can be a value of @ref LPTIM_Trigger_Source */ uint32_t ActiveEdge; /*!< Selects the Trigger active edge. Note: This parameter is used only when an external trigger is used. This parameter can be a value of @ref LPTIM_External_Trigger_Polarity */ uint32_t SampleTime; /*!< Selects the trigger sampling time to configure the clock glitch filter. Note: This parameter is used only when an external trigger is used. This parameter can be a value of @ref LPTIM_Trigger_Sample_Time */ }LPTIM_TriggerConfigTypeDef; /** * @brief LPTIM Initialization Structure definition */ typedef struct { LPTIM_ClockConfigTypeDef Clock; /*!< Specifies the clock parameters */ LPTIM_ULPClockConfigTypeDef UltraLowPowerClock; /*!< Specifies the Ultra Low Power clock parameters */ LPTIM_TriggerConfigTypeDef Trigger; /*!< Specifies the Trigger parameters */ uint32_t OutputPolarity; /*!< Specifies the Output polarity. This parameter can be a value of @ref LPTIM_Output_Polarity */ uint32_t UpdateMode; /*!< Specifies whether the update of the autorelaod and the compare values is done immediately or after the end of current period. This parameter can be a value of @ref LPTIM_Updating_Mode */ uint32_t CounterSource; /*!< Specifies whether the counter is incremented each internal event or each external event. This parameter can be a value of @ref LPTIM_Counter_Source */ }LPTIM_InitTypeDef; /** * @brief HAL LPTIM State structure definition */ typedef enum __HAL_LPTIM_StateTypeDef { HAL_LPTIM_STATE_RESET = 0x00, /*!< Peripheral not yet initialized or disabled */ HAL_LPTIM_STATE_READY = 0x01, /*!< Peripheral Initialized and ready for use */ HAL_LPTIM_STATE_BUSY = 0x02, /*!< An internal process is ongoing */ HAL_LPTIM_STATE_TIMEOUT = 0x03, /*!< Timeout state */ HAL_LPTIM_STATE_ERROR = 0x04 /*!< Internal Process is ongoing */ }HAL_LPTIM_StateTypeDef; /** * @brief LPTIM handle Structure definition */ typedef struct { LPTIM_TypeDef *Instance; /*!< Register base address */ LPTIM_InitTypeDef Init; /*!< LPTIM required parameters */ HAL_StatusTypeDef Status; /*!< LPTIM peripheral status */ HAL_LockTypeDef Lock; /*!< LPTIM locking object */ __IO HAL_LPTIM_StateTypeDef State; /*!< LPTIM peripheral state */ }LPTIM_HandleTypeDef; /** * @} */ /* Exported constants --------------------------------------------------------*/ /** @defgroup LPTIM_Exported_Constants LPTIM Exported Constants * @{ */ /** @defgroup LPTIM_Clock_Source LPTIM Clock Source * @{ */ #define LPTIM_CLOCKSOURCE_APBCLOCK_LPOSC ((uint32_t)0x00) #define LPTIM_CLOCKSOURCE_ULPTIM LPTIM_CFGR_CKSEL /** * @} */ /** @defgroup LPTIM_Clock_Prescaler LPTIM Clock Prescaler * @{ */ #define LPTIM_PRESCALER_DIV1 ((uint32_t)0x000000) #define LPTIM_PRESCALER_DIV2 LPTIM_CFGR_PRESC_0 #define LPTIM_PRESCALER_DIV4 LPTIM_CFGR_PRESC_1 #define LPTIM_PRESCALER_DIV8 ((uint32_t)(LPTIM_CFGR_PRESC_0 | LPTIM_CFGR_PRESC_1)) #define LPTIM_PRESCALER_DIV16 LPTIM_CFGR_PRESC_2 #define LPTIM_PRESCALER_DIV32 ((uint32_t)(LPTIM_CFGR_PRESC_0 | LPTIM_CFGR_PRESC_2)) #define LPTIM_PRESCALER_DIV64 ((uint32_t)(LPTIM_CFGR_PRESC_1 | LPTIM_CFGR_PRESC_2)) #define LPTIM_PRESCALER_DIV128 ((uint32_t)LPTIM_CFGR_PRESC) /** * @} */ /** @defgroup LPTIM_Output_Polarity LPTIM Output Polarity * @{ */ #define LPTIM_OUTPUTPOLARITY_HIGH ((uint32_t)0x00000000) #define LPTIM_OUTPUTPOLARITY_LOW (LPTIM_CFGR_WAVPOL) /** * @} */ /** @defgroup LPTIM_Clock_Sample_Time LPTIM Clock Sample Time * @{ */ #define LPTIM_CLOCKSAMPLETIME_DIRECTTRANSITION ((uint32_t)0x00000000) #define LPTIM_CLOCKSAMPLETIME_2TRANSITIONS LPTIM_CFGR_CKFLT_0 #define LPTIM_CLOCKSAMPLETIME_4TRANSITIONS LPTIM_CFGR_CKFLT_1 #define LPTIM_CLOCKSAMPLETIME_8TRANSITIONS LPTIM_CFGR_CKFLT /** * @} */ /** @defgroup LPTIM_Clock_Polarity LPTIM Clock Polarity * @{ */ #define LPTIM_CLOCKPOLARITY_RISING ((uint32_t)0x00000000) #define LPTIM_CLOCKPOLARITY_FALLING LPTIM_CFGR_CKPOL_0 #define LPTIM_CLOCKPOLARITY_RISING_FALLING LPTIM_CFGR_CKPOL_1 /** * @} */ /** @defgroup LPTIM_Trigger_Source LPTIM Trigger Source * @{ */ #define LPTIM_TRIGSOURCE_SOFTWARE ((uint32_t)0x0000FFFF) #define LPTIM_TRIGSOURCE_0 ((uint32_t)0x00000000) #define LPTIM_TRIGSOURCE_1 ((uint32_t)LPTIM_CFGR_TRIGSEL_0) #define LPTIM_TRIGSOURCE_2 LPTIM_CFGR_TRIGSEL_1 #define LPTIM_TRIGSOURCE_3 ((uint32_t)LPTIM_CFGR_TRIGSEL_0 | LPTIM_CFGR_TRIGSEL_1) #define LPTIM_TRIGSOURCE_4 LPTIM_CFGR_TRIGSEL_2 #define LPTIM_TRIGSOURCE_5 ((uint32_t)LPTIM_CFGR_TRIGSEL_0 | LPTIM_CFGR_TRIGSEL_2) /** * @} */ /** @defgroup LPTIM_External_Trigger_Polarity LPTIM External Trigger Polarity * @{ */ #define LPTIM_ACTIVEEDGE_RISING LPTIM_CFGR_TRIGEN_0 #define LPTIM_ACTIVEEDGE_FALLING LPTIM_CFGR_TRIGEN_1 #define LPTIM_ACTIVEEDGE_RISING_FALLING LPTIM_CFGR_TRIGEN /** * @} */ /** @defgroup LPTIM_Trigger_Sample_Time LPTIM Trigger Sample Time * @{ */ #define LPTIM_TRIGSAMPLETIME_DIRECTTRANSITION ((uint32_t)0x00000000) #define LPTIM_TRIGSAMPLETIME_2TRANSITIONS LPTIM_CFGR_TRGFLT_0 #define LPTIM_TRIGSAMPLETIME_4TRANSITIONS LPTIM_CFGR_TRGFLT_1 #define LPTIM_TRIGSAMPLETIME_8TRANSITIONS LPTIM_CFGR_TRGFLT /** * @} */ /** @defgroup LPTIM_Updating_Mode LPTIM Updating Mode * @{ */ #define LPTIM_UPDATE_IMMEDIATE ((uint32_t)0x00000000) #define LPTIM_UPDATE_ENDOFPERIOD LPTIM_CFGR_PRELOAD /** * @} */ /** @defgroup LPTIM_Counter_Source LPTIM Counter Source * @{ */ #define LPTIM_COUNTERSOURCE_INTERNAL ((uint32_t)0x00000000) #define LPTIM_COUNTERSOURCE_EXTERNAL LPTIM_CFGR_COUNTMODE /** * @} */ /** @defgroup LPTIM_Flag_Definition LPTIM Flag Definition * @{ */ #define LPTIM_FLAG_DOWN LPTIM_ISR_DOWN #define LPTIM_FLAG_UP LPTIM_ISR_UP #define LPTIM_FLAG_ARROK LPTIM_ISR_ARROK #define LPTIM_FLAG_CMPOK LPTIM_ISR_CMPOK #define LPTIM_FLAG_EXTTRIG LPTIM_ISR_EXTTRIG #define LPTIM_FLAG_ARRM LPTIM_ISR_ARRM #define LPTIM_FLAG_CMPM LPTIM_ISR_CMPM /** * @} */ /** @defgroup LPTIM_Interrupts_Definition LPTIM Interrupts Definition * @{ */ #define LPTIM_IT_DOWN LPTIM_IER_DOWNIE #define LPTIM_IT_UP LPTIM_IER_UPIE #define LPTIM_IT_ARROK LPTIM_IER_ARROKIE #define LPTIM_IT_CMPOK LPTIM_IER_CMPOKIE #define LPTIM_IT_EXTTRIG LPTIM_IER_EXTTRIGIE #define LPTIM_IT_ARRM LPTIM_IER_ARRMIE #define LPTIM_IT_CMPM LPTIM_IER_CMPMIE /** * @} */ /** @defgroup LPTIM_Option Register Definition * @{ */ #define LPTIM_OP_PAD_AF ((uint32_t)0x00000000) #define LPTIM_OP_PAD_PA4 LPTIM_OR_OR_0 #define LPTIM_OP_PAD_PB9 LPTIM_OR_OR_1 #define LPTIM_OP_TIM_DAC LPTIM_OR_OR /** * @} */ /** * @} */ /* Exported macro ------------------------------------------------------------*/ /** @defgroup LPTIM_Exported_Macros LPTIM Exported Macros * @{ */ /** @brief Reset LPTIM handle state * @param __HANDLE__: LPTIM handle * @retval None */ #define __HAL_LPTIM_RESET_HANDLE_STATE(__HANDLE__) ((__HANDLE__)->State = HAL_LPTIM_STATE_RESET) /** * @brief Enable/Disable the LPTIM peripheral. * @param __HANDLE__: LPTIM handle * @retval None */ #define __HAL_LPTIM_ENABLE(__HANDLE__) ((__HANDLE__)->Instance->CR |= (LPTIM_CR_ENABLE)) #define __HAL_LPTIM_DISABLE(__HANDLE__) ((__HANDLE__)->Instance->CR &= ~(LPTIM_CR_ENABLE)) /** * @brief Starts the LPTIM peripheral in Continuous or in single mode. * @param __HANDLE__: DMA handle * @retval None */ #define __HAL_LPTIM_START_CONTINUOUS(__HANDLE__) ((__HANDLE__)->Instance->CR |= LPTIM_CR_CNTSTRT) #define __HAL_LPTIM_START_SINGLE(__HANDLE__) ((__HANDLE__)->Instance->CR |= LPTIM_CR_SNGSTRT) /** * @brief Writes the passed parameter in the Autoreload register. * @param __HANDLE__: LPTIM handle * @param __VALUE__ : Autoreload value * @retval None */ #define __HAL_LPTIM_AUTORELOAD_SET(__HANDLE__ , __VALUE__) ((__HANDLE__)->Instance->ARR = (__VALUE__)) /** * @brief Writes the passed parameter in the Compare register. * @param __HANDLE__: LPTIM handle * @param __VALUE__ : Compare value * @retval None */ #define __HAL_LPTIM_COMPARE_SET(__HANDLE__ , __VALUE__) ((__HANDLE__)->Instance->CMP = (__VALUE__)) /** * @brief Checks whether the specified LPTIM flag is set or not. * @param __HANDLE__: LPTIM handle * @param __FLAG__ : LPTIM flag to check * This parameter can be a value of: * @arg LPTIM_FLAG_DOWN : Counter direction change up Flag. * @arg LPTIM_FLAG_UP : Counter direction change down to up Flag. * @arg LPTIM_FLAG_ARROK : Autoreload register update OK Flag. * @arg LPTIM_FLAG_CMPOK : Compare register update OK Flag. * @arg LPTIM_FLAG_EXTTRIG : External trigger edge event Flag. * @arg LPTIM_FLAG_ARRM : Autoreload match Flag. * @arg LPTIM_FLAG_CMPM : Compare match Flag. * @retval The state of the specified flag (SET or RESET). */ #define __HAL_LPTIM_GET_FLAG(__HANDLE__, __FLAG__) (((__HANDLE__)->Instance->ISR &(__FLAG__)) == (__FLAG__)) /** * @brief Clears the specified LPTIM flag. * @param __HANDLE__: LPTIM handle. * @param __FLAG__ : LPTIM flag to clear. * This parameter can be a value of: * @arg LPTIM_FLAG_DOWN : Counter direction change up Flag. * @arg LPTIM_FLAG_UP : Counter direction change down to up Flag. * @arg LPTIM_FLAG_ARROK : Autoreload register update OK Flag. * @arg LPTIM_FLAG_CMPOK : Compare register update OK Flag. * @arg LPTIM_FLAG_EXTTRIG : External trigger edge event Flag. * @arg LPTIM_FLAG_ARRM : Autoreload match Flag. * @arg LPTIM_FLAG_CMPM : Compare match Flag. * @retval None. */ #define __HAL_LPTIM_CLEAR_FLAG(__HANDLE__, __FLAG__) ((__HANDLE__)->Instance->ICR = (__FLAG__)) /** * @brief Enable the specified LPTIM interrupt. * @param __HANDLE__ : LPTIM handle. * @param __INTERRUPT__ : LPTIM interrupt to set. * This parameter can be a value of: * @arg LPTIM_IT_DOWN : Counter direction change up Interrupt. * @arg LPTIM_IT_UP : Counter direction change down to up Interrupt. * @arg LPTIM_IT_ARROK : Autoreload register update OK Interrupt. * @arg LPTIM_IT_CMPOK : Compare register update OK Interrupt. * @arg LPTIM_IT_EXTTRIG : External trigger edge event Interrupt. * @arg LPTIM_IT_ARRM : Autoreload match Interrupt. * @arg LPTIM_IT_CMPM : Compare match Interrupt. * @retval None. */ #define __HAL_LPTIM_ENABLE_IT(__HANDLE__, __INTERRUPT__) ((__HANDLE__)->Instance->IER |= (__INTERRUPT__)) /** * @brief Disable the specified LPTIM interrupt. * @param __HANDLE__ : LPTIM handle. * @param __INTERRUPT__ : LPTIM interrupt to set. * This parameter can be a value of: * @arg LPTIM_IT_DOWN : Counter direction change up Interrupt. * @arg LPTIM_IT_UP : Counter direction change down to up Interrupt. * @arg LPTIM_IT_ARROK : Autoreload register update OK Interrupt. * @arg LPTIM_IT_CMPOK : Compare register update OK Interrupt. * @arg LPTIM_IT_EXTTRIG : External trigger edge event Interrupt. * @arg LPTIM_IT_ARRM : Autoreload match Interrupt. * @arg LPTIM_IT_CMPM : Compare match Interrupt. * @retval None. */ #define __HAL_LPTIM_DISABLE_IT(__HANDLE__, __INTERRUPT__) ((__HANDLE__)->Instance->IER &= (~(__INTERRUPT__))) /** * @brief Checks whether the specified LPTIM interrupt is set or not. * @param __HANDLE__ : LPTIM handle. * @param __INTERRUPT__ : LPTIM interrupt to check. * This parameter can be a value of: * @arg LPTIM_IT_DOWN : Counter direction change up Interrupt. * @arg LPTIM_IT_UP : Counter direction change down to up Interrupt. * @arg LPTIM_IT_ARROK : Autoreload register update OK Interrupt. * @arg LPTIM_IT_CMPOK : Compare register update OK Interrupt. * @arg LPTIM_IT_EXTTRIG : External trigger edge event Interrupt. * @arg LPTIM_IT_ARRM : Autoreload match Interrupt. * @arg LPTIM_IT_CMPM : Compare match Interrupt. * @retval Interrupt status. */ #define __HAL_LPTIM_GET_IT_SOURCE(__HANDLE__, __INTERRUPT__) ((((__HANDLE__)->Instance->IER & (__INTERRUPT__)) == (__INTERRUPT__)) ? SET : RESET) /** @brief LPTIM Option Register * @param __HANDLE__: LPTIM handle * @param __VALUE__: This parameter can be a value of : * @arg LPTIM_OP_PAD_AF * @arg LPTIM_OP_PAD_PA4 * @arg LPTIM_OP_PAD_PB9 * @arg LPTIM_OP_TIM_DAC * @retval None */ #define __HAL_LPTIM_OPTR_CONFIG(__HANDLE__ , __VALUE__) ((__HANDLE__)->Instance->OR = (__VALUE__)) /** * @brief Enable interrupt on the LPTIM Wake-up Timer associated Exti line. * @retval None */ #define __HAL_LPTIM_WAKEUPTIMER_EXTI_ENABLE_IT() (EXTI->IMR |= LPTIM_EXTI_LINE_WAKEUPTIMER_EVENT) /** * @brief Disable interrupt on the LPTIM Wake-up Timer associated Exti line. * @retval None */ #define __HAL_LPTIM_WAKEUPTIMER_EXTI_DISABLE_IT() (EXTI->IMR &= ~(LPTIM_EXTI_LINE_WAKEUPTIMER_EVENT)) /** * @brief Enable event on the LPTIM Wake-up Timer associated Exti line. * @retval None. */ #define __HAL_LPTIM_WAKEUPTIMER_EXTI_ENABLE_EVENT() (EXTI->EMR |= LPTIM_EXTI_LINE_WAKEUPTIMER_EVENT) /** * @brief Disable event on the LPTIM Wake-up Timer associated Exti line. * @retval None. */ #define __HAL_LPTIM_WAKEUPTIMER_EXTI_DISABLE_EVENT() (EXTI->EMR &= ~(LPTIM_EXTI_LINE_WAKEUPTIMER_EVENT)) /** * @brief Enable falling edge trigger on the LPTIM Wake-up Timer associated Exti line. * @retval None. */ #define __HAL_LPTIM_WAKEUPTIMER_EXTI_ENABLE_FALLING_EDGE() (EXTI->FTSR |= LPTIM_EXTI_LINE_WAKEUPTIMER_EVENT) /** * @brief Disable falling edge trigger on the LPTIM Wake-up Timer associated Exti line. * @retval None. */ #define __HAL_LPTIM_WAKEUPTIMER_EXTI_DISABLE_FALLING_EDGE() (EXTI->FTSR &= ~(LPTIM_EXTI_LINE_WAKEUPTIMER_EVENT)) /** * @brief Enable rising edge trigger on the LPTIM Wake-up Timer associated Exti line. * @retval None. */ #define __HAL_LPTIM_WAKEUPTIMER_EXTI_ENABLE_RISING_EDGE() (EXTI->RTSR |= LPTIM_EXTI_LINE_WAKEUPTIMER_EVENT) /** * @brief Disable rising edge trigger on the LPTIM Wake-up Timer associated Exti line. * @retval None. */ #define __HAL_LPTIM_WAKEUPTIMER_EXTI_DISABLE_RISING_EDGE() (EXTI->RTSR &= ~(LPTIM_EXTI_LINE_WAKEUPTIMER_EVENT)) /** * @brief Enable rising & falling edge trigger on the LPTIM Wake-up Timer associated Exti line. * @retval None. */ #define __HAL_LPTIM_WAKEUPTIMER_EXTI_ENABLE_RISING_FALLING_EDGE() __HAL_LPTIM_WAKEUPTIMER_EXTI_ENABLE_RISING_EDGE();__HAL_LPTIM_WAKEUPTIMER_EXTI_ENABLE_FALLING_EDGE(); /** * @brief Disable rising & falling edge trigger on the LPTIM Wake-up Timer associated Exti line. * This parameter can be: * @retval None. */ #define __HAL_LPTIM_WAKEUPTIMER_EXTI_DISABLE_RISING_FALLING_EDGE() __HAL_LPTIM_WAKEUPTIMER_EXTI_DISABLE_RISING_EDGE();__HAL_LPTIM_WAKEUPTIMER_EXTI_DISABLE_FALLING_EDGE(); /** * @brief Check whether the LPTIM Wake-up Timer associated Exti line interrupt flag is set or not. * @retval Line Status. */ #define __HAL_LPTIM_WAKEUPTIMER_EXTI_GET_FLAG() (EXTI->PR & LPTIM_EXTI_LINE_WAKEUPTIMER_EVENT) /** * @brief Clear the LPTIM Wake-up Timer associated Exti line flag. * @retval None. */ #define __HAL_LPTIM_WAKEUPTIMER_EXTI_CLEAR_FLAG() (EXTI->PR = LPTIM_EXTI_LINE_WAKEUPTIMER_EVENT) /** * @brief Generate a Software interrupt on the LPTIM Wake-up Timer associated Exti line. * @retval None. */ #define __HAL_LPTIM_WAKEUPTIMER_EXTI_GENERATE_SWIT() (EXTI->SWIER |= LPTIM_EXTI_LINE_WAKEUPTIMER_EVENT) /** * @} */ /* Exported functions --------------------------------------------------------*/ /** @defgroup LPTIM_Exported_Functions LPTIM Exported Functions * @{ */ /* Initialization/de-initialization functions ********************************/ HAL_StatusTypeDef HAL_LPTIM_Init(LPTIM_HandleTypeDef *hlptim); HAL_StatusTypeDef HAL_LPTIM_DeInit(LPTIM_HandleTypeDef *hlptim); /* MSP functions *************************************************************/ void HAL_LPTIM_MspInit(LPTIM_HandleTypeDef *hlptim); void HAL_LPTIM_MspDeInit(LPTIM_HandleTypeDef *hlptim); /* Start/Stop operation functions *********************************************/ /* ################################# PWM Mode ################################*/ /* Blocking mode: Polling */ HAL_StatusTypeDef HAL_LPTIM_PWM_Start(LPTIM_HandleTypeDef *hlptim, uint32_t Period, uint32_t Pulse); HAL_StatusTypeDef HAL_LPTIM_PWM_Stop(LPTIM_HandleTypeDef *hlptim); /* Non-Blocking mode: Interrupt */ HAL_StatusTypeDef HAL_LPTIM_PWM_Start_IT(LPTIM_HandleTypeDef *hlptim, uint32_t Period, uint32_t Pulse); HAL_StatusTypeDef HAL_LPTIM_PWM_Stop_IT(LPTIM_HandleTypeDef *hlptim); /* ############################# One Pulse Mode ##############################*/ /* Blocking mode: Polling */ HAL_StatusTypeDef HAL_LPTIM_OnePulse_Start(LPTIM_HandleTypeDef *hlptim, uint32_t Period, uint32_t Pulse); HAL_StatusTypeDef HAL_LPTIM_OnePulse_Stop(LPTIM_HandleTypeDef *hlptim); /* Non-Blocking mode: Interrupt */ HAL_StatusTypeDef HAL_LPTIM_OnePulse_Start_IT(LPTIM_HandleTypeDef *hlptim, uint32_t Period, uint32_t Pulse); HAL_StatusTypeDef HAL_LPTIM_OnePulse_Stop_IT(LPTIM_HandleTypeDef *hlptim); /* ############################## Set once Mode ##############################*/ /* Blocking mode: Polling */ HAL_StatusTypeDef HAL_LPTIM_SetOnce_Start(LPTIM_HandleTypeDef *hlptim, uint32_t Period, uint32_t Pulse); HAL_StatusTypeDef HAL_LPTIM_SetOnce_Stop(LPTIM_HandleTypeDef *hlptim); /* Non-Blocking mode: Interrupt */ HAL_StatusTypeDef HAL_LPTIM_SetOnce_Start_IT(LPTIM_HandleTypeDef *hlptim, uint32_t Period, uint32_t Pulse); HAL_StatusTypeDef HAL_LPTIM_SetOnce_Stop_IT(LPTIM_HandleTypeDef *hlptim); /* ############################### Encoder Mode ##############################*/ /* Blocking mode: Polling */ HAL_StatusTypeDef HAL_LPTIM_Encoder_Start(LPTIM_HandleTypeDef *hlptim, uint32_t Period); HAL_StatusTypeDef HAL_LPTIM_Encoder_Stop(LPTIM_HandleTypeDef *hlptim); /* Non-Blocking mode: Interrupt */ HAL_StatusTypeDef HAL_LPTIM_Encoder_Start_IT(LPTIM_HandleTypeDef *hlptim, uint32_t Period); HAL_StatusTypeDef HAL_LPTIM_Encoder_Stop_IT(LPTIM_HandleTypeDef *hlptim); /* ############################# Time out Mode ##############################*/ /* Blocking mode: Polling */ HAL_StatusTypeDef HAL_LPTIM_TimeOut_Start(LPTIM_HandleTypeDef *hlptim, uint32_t Period, uint32_t Timeout); HAL_StatusTypeDef HAL_LPTIM_TimeOut_Stop(LPTIM_HandleTypeDef *hlptim); /* Non-Blocking mode: Interrupt */ HAL_StatusTypeDef HAL_LPTIM_TimeOut_Start_IT(LPTIM_HandleTypeDef *hlptim, uint32_t Period, uint32_t Timeout); HAL_StatusTypeDef HAL_LPTIM_TimeOut_Stop_IT(LPTIM_HandleTypeDef *hlptim); /* ############################## Counter Mode ###############################*/ /* Blocking mode: Polling */ HAL_StatusTypeDef HAL_LPTIM_Counter_Start(LPTIM_HandleTypeDef *hlptim, uint32_t Period); HAL_StatusTypeDef HAL_LPTIM_Counter_Stop(LPTIM_HandleTypeDef *hlptim); /* Non-Blocking mode: Interrupt */ HAL_StatusTypeDef HAL_LPTIM_Counter_Start_IT(LPTIM_HandleTypeDef *hlptim, uint32_t Period); HAL_StatusTypeDef HAL_LPTIM_Counter_Stop_IT(LPTIM_HandleTypeDef *hlptim); /* Reading operation functions ************************************************/ uint32_t HAL_LPTIM_ReadCounter(LPTIM_HandleTypeDef *hlptim); uint32_t HAL_LPTIM_ReadAutoReload(LPTIM_HandleTypeDef *hlptim); uint32_t HAL_LPTIM_ReadCompare(LPTIM_HandleTypeDef *hlptim); /* LPTIM IRQ functions *******************************************************/ void HAL_LPTIM_IRQHandler(LPTIM_HandleTypeDef *hlptim); /* CallBack functions ********************************************************/ void HAL_LPTIM_CompareMatchCallback(LPTIM_HandleTypeDef *hlptim); void HAL_LPTIM_AutoReloadMatchCallback(LPTIM_HandleTypeDef *hlptim); void HAL_LPTIM_TriggerCallback(LPTIM_HandleTypeDef *hlptim); void HAL_LPTIM_CompareWriteCallback(LPTIM_HandleTypeDef *hlptim); void HAL_LPTIM_AutoReloadWriteCallback(LPTIM_HandleTypeDef *hlptim); void HAL_LPTIM_DirectionUpCallback(LPTIM_HandleTypeDef *hlptim); void HAL_LPTIM_DirectionDownCallback(LPTIM_HandleTypeDef *hlptim); /* Peripheral State functions ************************************************/ HAL_LPTIM_StateTypeDef HAL_LPTIM_GetState(LPTIM_HandleTypeDef *hlptim); /** * @} */ /* Private types -------------------------------------------------------------*/ /** @defgroup LPTIM_Private_Types LPTIM Private Types * @{ */ /** * @} */ /* Private variables ---------------------------------------------------------*/ /** @defgroup LPTIM_Private_Variables LPTIM Private Variables * @{ */ /** * @} */ /* Private constants ---------------------------------------------------------*/ /** @defgroup LPTIM_Private_Constants LPTIM Private Constants * @{ */ /** * @} */ /* Private macros ------------------------------------------------------------*/ /** @defgroup LPTIM_Private_Macros LPTIM Private Macros * @{ */ #define IS_LPTIM_CLOCK_SOURCE(__SOURCE__) (((__SOURCE__) == LPTIM_CLOCKSOURCE_ULPTIM) || \ ((__SOURCE__) == LPTIM_CLOCKSOURCE_APBCLOCK_LPOSC)) #define IS_LPTIM_CLOCK_PRESCALER(__PRESCALER__) (((__PRESCALER__) == LPTIM_PRESCALER_DIV1 ) || \ ((__PRESCALER__) == LPTIM_PRESCALER_DIV2 ) || \ ((__PRESCALER__) == LPTIM_PRESCALER_DIV4 ) || \ ((__PRESCALER__) == LPTIM_PRESCALER_DIV8 ) || \ ((__PRESCALER__) == LPTIM_PRESCALER_DIV16 ) || \ ((__PRESCALER__) == LPTIM_PRESCALER_DIV32 ) || \ ((__PRESCALER__) == LPTIM_PRESCALER_DIV64 ) || \ ((__PRESCALER__) == LPTIM_PRESCALER_DIV128)) #define IS_LPTIM_CLOCK_PRESCALERDIV1(__PRESCALER__) ((__PRESCALER__) == LPTIM_PRESCALER_DIV1) #define IS_LPTIM_OUTPUT_POLARITY(__POLARITY__) (((__POLARITY__) == LPTIM_OUTPUTPOLARITY_LOW ) || \ ((__POLARITY__) == LPTIM_OUTPUTPOLARITY_HIGH)) #define IS_LPTIM_CLOCK_SAMPLE_TIME(__SAMPLETIME__) (((__SAMPLETIME__) == LPTIM_CLOCKSAMPLETIME_DIRECTTRANSITION) || \ ((__SAMPLETIME__) == LPTIM_CLOCKSAMPLETIME_2TRANSITIONS) || \ ((__SAMPLETIME__) == LPTIM_CLOCKSAMPLETIME_4TRANSITIONS) || \ ((__SAMPLETIME__) == LPTIM_CLOCKSAMPLETIME_8TRANSITIONS)) #define IS_LPTIM_CLOCK_POLARITY(__POLARITY__) (((__POLARITY__) == LPTIM_CLOCKPOLARITY_RISING) || \ ((__POLARITY__) == LPTIM_CLOCKPOLARITY_FALLING) || \ ((__POLARITY__) == LPTIM_CLOCKPOLARITY_RISING_FALLING)) #define IS_LPTIM_TRG_SOURCE(__TRIG__) (((__TRIG__) == LPTIM_TRIGSOURCE_SOFTWARE) || \ ((__TRIG__) == LPTIM_TRIGSOURCE_0) || \ ((__TRIG__) == LPTIM_TRIGSOURCE_1) || \ ((__TRIG__) == LPTIM_TRIGSOURCE_2) || \ ((__TRIG__) == LPTIM_TRIGSOURCE_3) || \ ((__TRIG__) == LPTIM_TRIGSOURCE_4) || \ ((__TRIG__) == LPTIM_TRIGSOURCE_5)) #define IS_LPTIM_EXT_TRG_POLARITY(__POLAR__) (((__POLAR__) == LPTIM_ACTIVEEDGE_RISING ) || \ ((__POLAR__) == LPTIM_ACTIVEEDGE_FALLING ) || \ ((__POLAR__) == LPTIM_ACTIVEEDGE_RISING_FALLING )) #define IS_LPTIM_TRIG_SAMPLE_TIME(__SAMPLETIME__) (((__SAMPLETIME__) == LPTIM_TRIGSAMPLETIME_DIRECTTRANSITION) || \ ((__SAMPLETIME__) == LPTIM_TRIGSAMPLETIME_2TRANSITIONS ) || \ ((__SAMPLETIME__) == LPTIM_TRIGSAMPLETIME_4TRANSITIONS ) || \ ((__SAMPLETIME__) == LPTIM_TRIGSAMPLETIME_8TRANSITIONS )) #define IS_LPTIM_UPDATE_MODE(__MODE__) (((__MODE__) == LPTIM_UPDATE_IMMEDIATE) || \ ((__MODE__) == LPTIM_UPDATE_ENDOFPERIOD)) #define IS_LPTIM_COUNTER_SOURCE(__SOURCE__) (((__SOURCE__) == LPTIM_COUNTERSOURCE_INTERNAL) || \ ((__SOURCE__) == LPTIM_COUNTERSOURCE_EXTERNAL)) #define IS_LPTIM_AUTORELOAD(__AUTORELOAD__) ((__AUTORELOAD__) <= 0x0000FFFF) #define IS_LPTIM_COMPARE(__COMPARE__) ((__COMPARE__) <= 0x0000FFFF) #define IS_LPTIM_PERIOD(PERIOD) ((PERIOD) <= 0x0000FFFF) #define IS_LPTIM_PULSE(PULSE) ((PULSE) <= 0x0000FFFF) /** * @} */ /* Private functions ---------------------------------------------------------*/ /** @defgroup LPTIM_Private_Functions LPTIM Private Functions * @{ */ /** * @} */ /** * @} */ /** * @} */ #endif /* STM32F410Tx || STM32F410Cx || STM32F410Rx */ #ifdef __cplusplus } #endif #endif /* __STM32F4xx_HAL_LPTIM_H */ /************************ (C) COPYRIGHT STMicroelectronics *****END OF FILE****/ ================================================ FILE: Zelig/mbed/TARGET_NUCLEO_F411RE/stm32f4xx_hal_ltdc.h ================================================ /** ****************************************************************************** * @file stm32f4xx_hal_ltdc.h * @author MCD Application Team * @version V1.4.1 * @date 09-October-2015 * @brief Header file of LTDC HAL module. ****************************************************************************** * @attention * *

© COPYRIGHT(c) 2015 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. * ****************************************************************************** */ /* Define to prevent recursive inclusion -------------------------------------*/ #ifndef __STM32F4xx_HAL_LTDC_H #define __STM32F4xx_HAL_LTDC_H #ifdef __cplusplus extern "C" { #endif #if defined(STM32F429xx) || defined(STM32F439xx) || defined(STM32F469xx) || defined(STM32F479xx) /* Includes ------------------------------------------------------------------*/ #include "stm32f4xx_hal_def.h" /** @addtogroup STM32F4xx_HAL_Driver * @{ */ /** @defgroup LTDC LTDC * @brief LTDC HAL module driver * @{ */ /* Exported types ------------------------------------------------------------*/ /** @defgroup LTDC_Exported_Types LTDC Exported Types * @{ */ #define MAX_LAYER 2 /** * @brief LTDC color structure definition */ typedef struct { uint8_t Blue; /*!< Configures the blue value. This parameter must be a number between Min_Data = 0x00 and Max_Data = 0xFF. */ uint8_t Green; /*!< Configures the green value. This parameter must be a number between Min_Data = 0x00 and Max_Data = 0xFF. */ uint8_t Red; /*!< Configures the red value. This parameter must be a number between Min_Data = 0x00 and Max_Data = 0xFF. */ uint8_t Reserved; /*!< Reserved 0xFF */ } LTDC_ColorTypeDef; /** * @brief LTDC Init structure definition */ typedef struct { uint32_t HSPolarity; /*!< configures the horizontal synchronization polarity. This parameter can be one value of @ref LTDC_HS_POLARITY */ uint32_t VSPolarity; /*!< configures the vertical synchronization polarity. This parameter can be one value of @ref LTDC_VS_POLARITY */ uint32_t DEPolarity; /*!< configures the data enable polarity. This parameter can be one of value of @ref LTDC_DE_POLARITY */ uint32_t PCPolarity; /*!< configures the pixel clock polarity. This parameter can be one of value of @ref LTDC_PC_POLARITY */ uint32_t HorizontalSync; /*!< configures the number of Horizontal synchronization width. This parameter must be a number between Min_Data = 0x000 and Max_Data = 0xFFF. */ uint32_t VerticalSync; /*!< configures the number of Vertical synchronization height. This parameter must be a number between Min_Data = 0x000 and Max_Data = 0x7FF. */ uint32_t AccumulatedHBP; /*!< configures the accumulated horizontal back porch width. This parameter must be a number between Min_Data = LTDC_HorizontalSync and Max_Data = 0xFFF. */ uint32_t AccumulatedVBP; /*!< configures the accumulated vertical back porch height. This parameter must be a number between Min_Data = LTDC_VerticalSync and Max_Data = 0x7FF. */ uint32_t AccumulatedActiveW; /*!< configures the accumulated active width. This parameter must be a number between Min_Data = LTDC_AccumulatedHBP and Max_Data = 0xFFF. */ uint32_t AccumulatedActiveH; /*!< configures the accumulated active height. This parameter must be a number between Min_Data = LTDC_AccumulatedVBP and Max_Data = 0x7FF. */ uint32_t TotalWidth; /*!< configures the total width. This parameter must be a number between Min_Data = LTDC_AccumulatedActiveW and Max_Data = 0xFFF. */ uint32_t TotalHeigh; /*!< configures the total height. This parameter must be a number between Min_Data = LTDC_AccumulatedActiveH and Max_Data = 0x7FF. */ LTDC_ColorTypeDef Backcolor; /*!< Configures the background color. */ } LTDC_InitTypeDef; /** * @brief LTDC Layer structure definition */ typedef struct { uint32_t WindowX0; /*!< Configures the Window Horizontal Start Position. This parameter must be a number between Min_Data = 0x000 and Max_Data = 0xFFF. */ uint32_t WindowX1; /*!< Configures the Window Horizontal Stop Position. This parameter must be a number between Min_Data = 0x000 and Max_Data = 0xFFF. */ uint32_t WindowY0; /*!< Configures the Window vertical Start Position. This parameter must be a number between Min_Data = 0x000 and Max_Data = 0xFFF. */ uint32_t WindowY1; /*!< Configures the Window vertical Stop Position. This parameter must be a number between Min_Data = 0x0000 and Max_Data = 0xFFFF. */ uint32_t PixelFormat; /*!< Specifies the pixel format. This parameter can be one of value of @ref LTDC_Pixelformat */ uint32_t Alpha; /*!< Specifies the constant alpha used for blending. This parameter must be a number between Min_Data = 0x00 and Max_Data = 0xFF. */ uint32_t Alpha0; /*!< Configures the default alpha value. This parameter must be a number between Min_Data = 0x00 and Max_Data = 0xFF. */ uint32_t BlendingFactor1; /*!< Select the blending factor 1. This parameter can be one of value of @ref LTDC_BlendingFactor1 */ uint32_t BlendingFactor2; /*!< Select the blending factor 2. This parameter can be one of value of @ref LTDC_BlendingFactor2 */ uint32_t FBStartAdress; /*!< Configures the color frame buffer address */ uint32_t ImageWidth; /*!< Configures the color frame buffer line length. This parameter must be a number between Min_Data = 0x0000 and Max_Data = 0x1FFF. */ uint32_t ImageHeight; /*!< Specifies the number of line in frame buffer. This parameter must be a number between Min_Data = 0x000 and Max_Data = 0x7FF. */ LTDC_ColorTypeDef Backcolor; /*!< Configures the layer background color. */ } LTDC_LayerCfgTypeDef; /** * @brief HAL LTDC State structures definition */ typedef enum { HAL_LTDC_STATE_RESET = 0x00, /*!< LTDC not yet initialized or disabled */ HAL_LTDC_STATE_READY = 0x01, /*!< LTDC initialized and ready for use */ HAL_LTDC_STATE_BUSY = 0x02, /*!< LTDC internal process is ongoing */ HAL_LTDC_STATE_TIMEOUT = 0x03, /*!< LTDC Timeout state */ HAL_LTDC_STATE_ERROR = 0x04 /*!< LTDC state error */ }HAL_LTDC_StateTypeDef; /** * @brief LTDC handle Structure definition */ typedef struct { LTDC_TypeDef *Instance; /*!< LTDC Register base address */ LTDC_InitTypeDef Init; /*!< LTDC parameters */ LTDC_LayerCfgTypeDef LayerCfg[MAX_LAYER]; /*!< LTDC Layers parameters */ HAL_LockTypeDef Lock; /*!< LTDC Lock */ __IO HAL_LTDC_StateTypeDef State; /*!< LTDC state */ __IO uint32_t ErrorCode; /*!< LTDC Error code */ } LTDC_HandleTypeDef; /** * @} */ /* Exported constants --------------------------------------------------------*/ /** @defgroup LTDC_Exported_Constants LTDC Exported Constants * @{ */ /** @defgroup LTDC_Error_Code LTDC Error Code * @{ */ #define HAL_LTDC_ERROR_NONE ((uint32_t)0x00000000) /*!< LTDC No error */ #define HAL_LTDC_ERROR_TE ((uint32_t)0x00000001) /*!< LTDC Transfer error */ #define HAL_LTDC_ERROR_FU ((uint32_t)0x00000002) /*!< LTDC FIFO Underrun */ #define HAL_LTDC_ERROR_TIMEOUT ((uint32_t)0x00000020) /*!< LTDC Timeout error */ /** * @} */ /** @defgroup LTDC_HS_POLARITY LTDC HS POLARITY * @{ */ #define LTDC_HSPOLARITY_AL ((uint32_t)0x00000000) /*!< Horizontal Synchronization is active low. */ #define LTDC_HSPOLARITY_AH LTDC_GCR_HSPOL /*!< Horizontal Synchronization is active high. */ /** * @} */ /** @defgroup LTDC_VS_POLARITY LTDC VS POLARITY * @{ */ #define LTDC_VSPOLARITY_AL ((uint32_t)0x00000000) /*!< Vertical Synchronization is active low. */ #define LTDC_VSPOLARITY_AH LTDC_GCR_VSPOL /*!< Vertical Synchronization is active high. */ /** * @} */ /** @defgroup LTDC_DE_POLARITY LTDC DE POLARITY * @{ */ #define LTDC_DEPOLARITY_AL ((uint32_t)0x00000000) /*!< Data Enable, is active low. */ #define LTDC_DEPOLARITY_AH LTDC_GCR_DEPOL /*!< Data Enable, is active high. */ /** * @} */ /** @defgroup LTDC_PC_POLARITY LTDC PC POLARITY * @{ */ #define LTDC_PCPOLARITY_IPC ((uint32_t)0x00000000) /*!< input pixel clock. */ #define LTDC_PCPOLARITY_IIPC LTDC_GCR_PCPOL /*!< inverted input pixel clock. */ /** * @} */ /** @defgroup LTDC_SYNC LTDC SYNC * @{ */ #define LTDC_HORIZONTALSYNC (LTDC_SSCR_HSW >> 16) /*!< Horizontal synchronization width. */ #define LTDC_VERTICALSYNC LTDC_SSCR_VSH /*!< Vertical synchronization height. */ /** * @} */ /** @defgroup LTDC_BACK_COLOR LTDC BACK COLOR * @{ */ #define LTDC_COLOR ((uint32_t)0x000000FF) /*!< Color mask */ /** * @} */ /** @defgroup LTDC_BlendingFactor1 LTDC Blending Factor1 * @{ */ #define LTDC_BLENDING_FACTOR1_CA ((uint32_t)0x00000400) /*!< Blending factor : Cte Alpha */ #define LTDC_BLENDING_FACTOR1_PAxCA ((uint32_t)0x00000600) /*!< Blending factor : Cte Alpha x Pixel Alpha*/ /** * @} */ /** @defgroup LTDC_BlendingFactor2 LTDC Blending Factor2 * @{ */ #define LTDC_BLENDING_FACTOR2_CA ((uint32_t)0x00000005) /*!< Blending factor : Cte Alpha */ #define LTDC_BLENDING_FACTOR2_PAxCA ((uint32_t)0x00000007) /*!< Blending factor : Cte Alpha x Pixel Alpha*/ /** * @} */ /** @defgroup LTDC_Pixelformat LTDC Pixel format * @{ */ #define LTDC_PIXEL_FORMAT_ARGB8888 ((uint32_t)0x00000000) /*!< ARGB8888 LTDC pixel format */ #define LTDC_PIXEL_FORMAT_RGB888 ((uint32_t)0x00000001) /*!< RGB888 LTDC pixel format */ #define LTDC_PIXEL_FORMAT_RGB565 ((uint32_t)0x00000002) /*!< RGB565 LTDC pixel format */ #define LTDC_PIXEL_FORMAT_ARGB1555 ((uint32_t)0x00000003) /*!< ARGB1555 LTDC pixel format */ #define LTDC_PIXEL_FORMAT_ARGB4444 ((uint32_t)0x00000004) /*!< ARGB4444 LTDC pixel format */ #define LTDC_PIXEL_FORMAT_L8 ((uint32_t)0x00000005) /*!< L8 LTDC pixel format */ #define LTDC_PIXEL_FORMAT_AL44 ((uint32_t)0x00000006) /*!< AL44 LTDC pixel format */ #define LTDC_PIXEL_FORMAT_AL88 ((uint32_t)0x00000007) /*!< AL88 LTDC pixel format */ /** * @} */ /** @defgroup LTDC_Alpha LTDC Alpha * @{ */ #define LTDC_ALPHA LTDC_LxCACR_CONSTA /*!< LTDC Cte Alpha mask */ /** * @} */ /** @defgroup LTDC_LAYER_Config LTDC LAYER Config * @{ */ #define LTDC_STOPPOSITION (LTDC_LxWHPCR_WHSPPOS >> 16) /*!< LTDC Layer stop position */ #define LTDC_STARTPOSITION LTDC_LxWHPCR_WHSTPOS /*!< LTDC Layer start position */ #define LTDC_COLOR_FRAME_BUFFER LTDC_LxCFBLR_CFBLL /*!< LTDC Layer Line length */ #define LTDC_LINE_NUMBER LTDC_LxCFBLNR_CFBLNBR /*!< LTDC Layer Line number */ /** * @} */ /** @defgroup LTDC_Interrupts LTDC Interrupts * @{ */ #define LTDC_IT_LI LTDC_IER_LIE #define LTDC_IT_FU LTDC_IER_FUIE #define LTDC_IT_TE LTDC_IER_TERRIE #define LTDC_IT_RR LTDC_IER_RRIE /** * @} */ /** @defgroup LTDC_Flag LTDC Flag * @{ */ #define LTDC_FLAG_LI LTDC_ISR_LIF #define LTDC_FLAG_FU LTDC_ISR_FUIF #define LTDC_FLAG_TE LTDC_ISR_TERRIF #define LTDC_FLAG_RR LTDC_ISR_RRIF /** * @} */ /** * @} */ /* Exported macro ------------------------------------------------------------*/ /** @defgroup LTDC_Exported_Macros LTDC Exported Macros * @{ */ /** @brief Reset LTDC handle state * @param __HANDLE__: specifies the LTDC handle. * @retval None */ #define __HAL_LTDC_RESET_HANDLE_STATE(__HANDLE__) ((__HANDLE__)->State = HAL_LTDC_STATE_RESET) /** * @brief Enable the LTDC. * @param __HANDLE__: LTDC handle * @retval None. */ #define __HAL_LTDC_ENABLE(__HANDLE__) ((__HANDLE__)->Instance->GCR |= LTDC_GCR_LTDCEN) /** * @brief Disable the LTDC. * @param __HANDLE__: LTDC handle * @retval None. */ #define __HAL_LTDC_DISABLE(__HANDLE__) ((__HANDLE__)->Instance->GCR &= ~(LTDC_GCR_LTDCEN)) /** * @brief Enable the LTDC Layer. * @param __HANDLE__: LTDC handle * @param __LAYER__: Specify the layer to be enabled * This parameter can be 0 or 1 * @retval None. */ #define __HAL_LTDC_LAYER_ENABLE(__HANDLE__, __LAYER__) ((LTDC_LAYER((__HANDLE__), (__LAYER__)))->CR |= (uint32_t)LTDC_LxCR_LEN) /** * @brief Disable the LTDC Layer. * @param __HANDLE__: LTDC handle * @param __LAYER__: Specify the layer to be disabled * This parameter can be 0 or 1 * @retval None. */ #define __HAL_LTDC_LAYER_DISABLE(__HANDLE__, __LAYER__) ((LTDC_LAYER((__HANDLE__), (__LAYER__)))->CR &= ~(uint32_t)LTDC_LxCR_LEN) /** * @brief Reload Layer Configuration. * @param __HANDLE__: LTDC handle * @retval None. */ #define __HAL_LTDC_RELOAD_CONFIG(__HANDLE__) ((__HANDLE__)->Instance->SRCR |= LTDC_SRCR_IMR) /* Interrupt & Flag management */ /** * @brief Get the LTDC pending flags. * @param __HANDLE__: LTDC handle * @param __FLAG__: Get the specified flag. * This parameter can be any combination of the following values: * @arg LTDC_FLAG_LI: Line Interrupt flag * @arg LTDC_FLAG_FU: FIFO Underrun Interrupt flag * @arg LTDC_FLAG_TE: Transfer Error interrupt flag * @arg LTDC_FLAG_RR: Register Reload Interrupt Flag * @retval The state of FLAG (SET or RESET). */ #define __HAL_LTDC_GET_FLAG(__HANDLE__, __FLAG__) ((__HANDLE__)->Instance->ISR & (__FLAG__)) /** * @brief Clears the LTDC pending flags. * @param __HANDLE__: LTDC handle * @param __FLAG__: specifies the flag to clear. * This parameter can be any combination of the following values: * @arg LTDC_FLAG_LI: Line Interrupt flag * @arg LTDC_FLAG_FU: FIFO Underrun Interrupt flag * @arg LTDC_FLAG_TE: Transfer Error interrupt flag * @arg LTDC_FLAG_RR: Register Reload Interrupt Flag * @retval None */ #define __HAL_LTDC_CLEAR_FLAG(__HANDLE__, __FLAG__) ((__HANDLE__)->Instance->ICR = (__FLAG__)) /** * @brief Enables the specified LTDC interrupts. * @param __HANDLE__: LTDC handle * @param __INTERRUPT__: specifies the LTDC interrupt sources to be enabled. * This parameter can be any combination of the following values: * @arg LTDC_IT_LI: Line Interrupt flag * @arg LTDC_IT_FU: FIFO Underrun Interrupt flag * @arg LTDC_IT_TE: Transfer Error interrupt flag * @arg LTDC_IT_RR: Register Reload Interrupt Flag * @retval None */ #define __HAL_LTDC_ENABLE_IT(__HANDLE__, __INTERRUPT__) ((__HANDLE__)->Instance->IER |= (__INTERRUPT__)) /** * @brief Disables the specified LTDC interrupts. * @param __HANDLE__: LTDC handle * @param __INTERRUPT__: specifies the LTDC interrupt sources to be disabled. * This parameter can be any combination of the following values: * @arg LTDC_IT_LI: Line Interrupt flag * @arg LTDC_IT_FU: FIFO Underrun Interrupt flag * @arg LTDC_IT_TE: Transfer Error interrupt flag * @arg LTDC_IT_RR: Register Reload Interrupt Flag * @retval None */ #define __HAL_LTDC_DISABLE_IT(__HANDLE__, __INTERRUPT__) ((__HANDLE__)->Instance->IER &= ~(__INTERRUPT__)) /** * @brief Checks whether the specified LTDC interrupt has occurred or not. * @param __HANDLE__: LTDC handle * @param __INTERRUPT__: specifies the LTDC interrupt source to check. * This parameter can be one of the following values: * @arg LTDC_IT_LI: Line Interrupt flag * @arg LTDC_IT_FU: FIFO Underrun Interrupt flag * @arg LTDC_IT_TE: Transfer Error interrupt flag * @arg LTDC_IT_RR: Register Reload Interrupt Flag * @retval The state of INTERRUPT (SET or RESET). */ #define __HAL_LTDC_GET_IT_SOURCE(__HANDLE__, __INTERRUPT__) ((__HANDLE__)->Instance->ISR & (__INTERRUPT__)) /** * @} */ /* Include LTDC HAL Extension module */ #include "stm32f4xx_hal_ltdc_ex.h" /* Exported functions --------------------------------------------------------*/ /** @addtogroup LTDC_Exported_Functions * @{ */ /** @addtogroup LTDC_Exported_Functions_Group1 * @{ */ /* Initialization and de-initialization functions *****************************/ HAL_StatusTypeDef HAL_LTDC_Init(LTDC_HandleTypeDef *hltdc); HAL_StatusTypeDef HAL_LTDC_DeInit(LTDC_HandleTypeDef *hltdc); void HAL_LTDC_MspInit(LTDC_HandleTypeDef* hltdc); void HAL_LTDC_MspDeInit(LTDC_HandleTypeDef* hltdc); void HAL_LTDC_ErrorCallback(LTDC_HandleTypeDef *hltdc); void HAL_LTDC_LineEventCallback(LTDC_HandleTypeDef *hltdc); /** * @} */ /** @addtogroup LTDC_Exported_Functions_Group2 * @{ */ /* IO operation functions *****************************************************/ void HAL_LTDC_IRQHandler(LTDC_HandleTypeDef *hltdc); /** * @} */ /** @addtogroup LTDC_Exported_Functions_Group3 * @{ */ /* Peripheral Control functions ***********************************************/ HAL_StatusTypeDef HAL_LTDC_ConfigLayer(LTDC_HandleTypeDef *hltdc, LTDC_LayerCfgTypeDef *pLayerCfg, uint32_t LayerIdx); HAL_StatusTypeDef HAL_LTDC_SetWindowSize(LTDC_HandleTypeDef *hltdc, uint32_t XSize, uint32_t YSize, uint32_t LayerIdx); HAL_StatusTypeDef HAL_LTDC_SetWindowPosition(LTDC_HandleTypeDef *hltdc, uint32_t X0, uint32_t Y0, uint32_t LayerIdx); HAL_StatusTypeDef HAL_LTDC_SetPixelFormat(LTDC_HandleTypeDef *hltdc, uint32_t Pixelformat, uint32_t LayerIdx); HAL_StatusTypeDef HAL_LTDC_SetAlpha(LTDC_HandleTypeDef *hltdc, uint32_t Alpha, uint32_t LayerIdx); HAL_StatusTypeDef HAL_LTDC_SetAddress(LTDC_HandleTypeDef *hltdc, uint32_t Address, uint32_t LayerIdx); HAL_StatusTypeDef HAL_LTDC_SetPitch(LTDC_HandleTypeDef *hltdc, uint32_t LinePitchInPixels, uint32_t LayerIdx); HAL_StatusTypeDef HAL_LTDC_ConfigColorKeying(LTDC_HandleTypeDef *hltdc, uint32_t RGBValue, uint32_t LayerIdx); HAL_StatusTypeDef HAL_LTDC_ConfigCLUT(LTDC_HandleTypeDef *hltdc, uint32_t *pCLUT, uint32_t CLUTSize, uint32_t LayerIdx); HAL_StatusTypeDef HAL_LTDC_EnableColorKeying(LTDC_HandleTypeDef *hltdc, uint32_t LayerIdx); HAL_StatusTypeDef HAL_LTDC_DisableColorKeying(LTDC_HandleTypeDef *hltdc, uint32_t LayerIdx); HAL_StatusTypeDef HAL_LTDC_EnableCLUT(LTDC_HandleTypeDef *hltdc, uint32_t LayerIdx); HAL_StatusTypeDef HAL_LTDC_DisableCLUT(LTDC_HandleTypeDef *hltdc, uint32_t LayerIdx); HAL_StatusTypeDef HAL_LTDC_ProgramLineEvent(LTDC_HandleTypeDef *hltdc, uint32_t Line); HAL_StatusTypeDef HAL_LTDC_EnableDither(LTDC_HandleTypeDef *hltdc); HAL_StatusTypeDef HAL_LTDC_DisableDither(LTDC_HandleTypeDef *hltdc); /** * @} */ /** @addtogroup LTDC_Exported_Functions_Group4 * @{ */ /* Peripheral State functions *************************************************/ HAL_LTDC_StateTypeDef HAL_LTDC_GetState(LTDC_HandleTypeDef *hltdc); uint32_t HAL_LTDC_GetError(LTDC_HandleTypeDef *hltdc); /** * @} */ /** * @} */ /* Private types -------------------------------------------------------------*/ /** @defgroup LTDC_Private_Types LTDC Private Types * @{ */ /** * @} */ /* Private variables ---------------------------------------------------------*/ /** @defgroup LTDC_Private_Variables LTDC Private Variables * @{ */ /** * @} */ /* Private constants ---------------------------------------------------------*/ /** @defgroup LTDC_Private_Constants LTDC Private Constants * @{ */ /** * @} */ /* Private macros ------------------------------------------------------------*/ /** @defgroup LTDC_Private_Macros LTDC Private Macros * @{ */ #define LTDC_LAYER(__HANDLE__, __LAYER__) ((LTDC_Layer_TypeDef *)((uint32_t)(((uint32_t)((__HANDLE__)->Instance)) + 0x84 + (0x80*(__LAYER__))))) #define IS_LTDC_LAYER(LAYER) ((LAYER) <= MAX_LAYER) #define IS_LTDC_HSPOL(HSPOL) (((HSPOL) == LTDC_HSPOLARITY_AL) || \ ((HSPOL) == LTDC_HSPOLARITY_AH)) #define IS_LTDC_VSPOL(VSPOL) (((VSPOL) == LTDC_VSPOLARITY_AL) || \ ((VSPOL) == LTDC_VSPOLARITY_AH)) #define IS_LTDC_DEPOL(DEPOL) (((DEPOL) == LTDC_DEPOLARITY_AL) || \ ((DEPOL) == LTDC_DEPOLARITY_AH)) #define IS_LTDC_PCPOL(PCPOL) (((PCPOL) == LTDC_PCPOLARITY_IPC) || \ ((PCPOL) == LTDC_PCPOLARITY_IIPC)) #define IS_LTDC_HSYNC(HSYNC) ((HSYNC) <= LTDC_HORIZONTALSYNC) #define IS_LTDC_VSYNC(VSYNC) ((VSYNC) <= LTDC_VERTICALSYNC) #define IS_LTDC_AHBP(AHBP) ((AHBP) <= LTDC_HORIZONTALSYNC) #define IS_LTDC_AVBP(AVBP) ((AVBP) <= LTDC_VERTICALSYNC) #define IS_LTDC_AAW(AAW) ((AAW) <= LTDC_HORIZONTALSYNC) #define IS_LTDC_AAH(AAH) ((AAH) <= LTDC_VERTICALSYNC) #define IS_LTDC_TOTALW(TOTALW) ((TOTALW) <= LTDC_HORIZONTALSYNC) #define IS_LTDC_TOTALH(TOTALH) ((TOTALH) <= LTDC_VERTICALSYNC) #define IS_LTDC_BLUEVALUE(BBLUE) ((BBLUE) <= LTDC_COLOR) #define IS_LTDC_GREENVALUE(BGREEN) ((BGREEN) <= LTDC_COLOR) #define IS_LTDC_REDVALUE(BRED) ((BRED) <= LTDC_COLOR) #define IS_LTDC_BLENDING_FACTOR1(BlendingFactor1) (((BlendingFactor1) == LTDC_BLENDING_FACTOR1_CA) || \ ((BlendingFactor1) == LTDC_BLENDING_FACTOR1_PAxCA)) #define IS_LTDC_BLENDING_FACTOR2(BlendingFactor2) (((BlendingFactor2) == LTDC_BLENDING_FACTOR2_CA) || \ ((BlendingFactor2) == LTDC_BLENDING_FACTOR2_PAxCA)) #define IS_LTDC_PIXEL_FORMAT(Pixelformat) (((Pixelformat) == LTDC_PIXEL_FORMAT_ARGB8888) || ((Pixelformat) == LTDC_PIXEL_FORMAT_RGB888) || \ ((Pixelformat) == LTDC_PIXEL_FORMAT_RGB565) || ((Pixelformat) == LTDC_PIXEL_FORMAT_ARGB1555) || \ ((Pixelformat) == LTDC_PIXEL_FORMAT_ARGB4444) || ((Pixelformat) == LTDC_PIXEL_FORMAT_L8) || \ ((Pixelformat) == LTDC_PIXEL_FORMAT_AL44) || ((Pixelformat) == LTDC_PIXEL_FORMAT_AL88)) #define IS_LTDC_ALPHA(ALPHA) ((ALPHA) <= LTDC_ALPHA) #define IS_LTDC_HCONFIGST(HCONFIGST) ((HCONFIGST) <= LTDC_STARTPOSITION) #define IS_LTDC_HCONFIGSP(HCONFIGSP) ((HCONFIGSP) <= LTDC_STOPPOSITION) #define IS_LTDC_VCONFIGST(VCONFIGST) ((VCONFIGST) <= LTDC_STARTPOSITION) #define IS_LTDC_VCONFIGSP(VCONFIGSP) ((VCONFIGSP) <= LTDC_STOPPOSITION) #define IS_LTDC_CFBP(CFBP) ((CFBP) <= LTDC_COLOR_FRAME_BUFFER) #define IS_LTDC_CFBLL(CFBLL) ((CFBLL) <= LTDC_COLOR_FRAME_BUFFER) #define IS_LTDC_CFBLNBR(CFBLNBR) ((CFBLNBR) <= LTDC_LINE_NUMBER) #define IS_LTDC_LIPOS(LIPOS) ((LIPOS) <= 0x7FF) /** * @} */ /* Private functions ---------------------------------------------------------*/ /** @defgroup LTDC_Private_Functions LTDC Private Functions * @{ */ /** * @} */ /** * @} */ /** * @} */ #endif /* STM32F429xx || STM32F439xx || STM32F469xx || STM32F479xx */ #ifdef __cplusplus } #endif #endif /* __STM32F4xx_HAL_LTDC_H */ /************************ (C) COPYRIGHT STMicroelectronics *****END OF FILE****/ ================================================ FILE: Zelig/mbed/TARGET_NUCLEO_F411RE/stm32f4xx_hal_ltdc_ex.h ================================================ /** ****************************************************************************** * @file stm32f4xx_hal_ltdc_ex.h * @author MCD Application Team * @version V1.4.1 * @date 09-October-2015 * @brief Header file of LTDC HAL Extension module. ****************************************************************************** * @attention * *

© COPYRIGHT(c) 2015 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. * ****************************************************************************** */ /* Define to prevent recursive inclusion -------------------------------------*/ #ifndef __STM32F4xx_HAL_LTDC_EX_H #define __STM32F4xx_HAL_LTDC_EX_H #ifdef __cplusplus extern "C" { #endif #if defined(STM32F469xx) || defined(STM32F479xx) /* Includes ------------------------------------------------------------------*/ #include "stm32f4xx_hal_def.h" #include "stm32f4xx_hal_dsi.h" /** @addtogroup STM32F4xx_HAL_Driver * @{ */ /** @addtogroup LTDCEx * @{ */ /* Exported types ------------------------------------------------------------*/ /* Exported constants --------------------------------------------------------*/ /** @defgroup LTDCEx_Exported_Constants LTDCEx Exported Constants * @{ */ /** * @} */ /* Exported macro ------------------------------------------------------------*/ /** @defgroup LTDCEx_Exported_Macros LTDC Exported Macros * @{ */ /** * @} */ /* Exported functions --------------------------------------------------------*/ /** @defgroup LTDCEx_Exported_Functions LTDC Extended Exported Functions * @{ */ HAL_StatusTypeDef HAL_LTDC_StructInitFromVideoConfig(LTDC_HandleTypeDef* hltdc, DSI_VidCfgTypeDef *VidCfg); HAL_StatusTypeDef HAL_LTDC_StructInitFromAdaptedCommandConfig(LTDC_HandleTypeDef* hltdc, DSI_CmdCfgTypeDef *CmdCfg); /** * @} */ /* Private types -------------------------------------------------------------*/ /** @defgroup LTDCEx_Private_Types LTDCEx Private Types * @{ */ /** * @} */ /* Private variables ---------------------------------------------------------*/ /** @defgroup LTDCEx_Private_Variables LTDCEx Private Variables * @{ */ /** * @} */ /* Private constants ---------------------------------------------------------*/ /** @defgroup LTDCEx_Private_Constants LTDCEx Private Constants * @{ */ /** * @} */ /* Private macros ------------------------------------------------------------*/ /** @defgroup LTDCEx_Private_Macros LTDCEx Private Macros * @{ */ /** * @} */ /* Private functions ---------------------------------------------------------*/ /** @defgroup LTDCEx_Private_Functions LTDCEx Private Functions * @{ */ /** * @} */ /** * @} */ /** * @} */ #endif /* STM32F469xx || STM32F479xx */ #ifdef __cplusplus } #endif #endif /* __STM32F4xx_HAL_LTDC_EX_H */ /************************ (C) COPYRIGHT STMicroelectronics *****END OF FILE****/ ================================================ FILE: Zelig/mbed/TARGET_NUCLEO_F411RE/stm32f4xx_hal_nand.h ================================================ /** ****************************************************************************** * @file stm32f4xx_hal_nand.h * @author MCD Application Team * @version V1.4.1 * @date 09-October-2015 * @brief Header file of NAND HAL module. ****************************************************************************** * @attention * *

© COPYRIGHT(c) 2015 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. * ****************************************************************************** */ /* Define to prevent recursive inclusion -------------------------------------*/ #ifndef __STM32F4xx_HAL_NAND_H #define __STM32F4xx_HAL_NAND_H #ifdef __cplusplus extern "C" { #endif /* Includes ------------------------------------------------------------------*/ #if defined(STM32F405xx) || defined(STM32F415xx) || defined(STM32F407xx) || defined(STM32F417xx) #include "stm32f4xx_ll_fsmc.h" #endif /* STM32F405xx || STM32F415xx || STM32F407xx || STM32F417xx */ #if defined(STM32F427xx) || defined(STM32F437xx) || defined(STM32F429xx) || defined(STM32F439xx) ||\ defined(STM32F446xx) || defined(STM32F469xx) || defined(STM32F479xx) #include "stm32f4xx_ll_fmc.h" #endif /* STM32F427xx || STM32F437xx || STM32F429xx || STM32F439xx || STM32F446xx || STM32F469xx ||\ STM32F479xx */ /** @addtogroup STM32F4xx_HAL_Driver * @{ */ /** @addtogroup NAND * @{ */ #if defined(STM32F405xx) || defined(STM32F415xx) || defined(STM32F407xx) || defined(STM32F417xx) || \ defined(STM32F427xx) || defined(STM32F437xx) || defined(STM32F429xx) || defined(STM32F439xx) || \ defined(STM32F446xx) || defined(STM32F469xx) || defined(STM32F479xx) /* Exported typedef ----------------------------------------------------------*/ /* Exported types ------------------------------------------------------------*/ /** @defgroup NAND_Exported_Types NAND Exported Types * @{ */ /** * @brief HAL NAND State structures definition */ typedef enum { HAL_NAND_STATE_RESET = 0x00, /*!< NAND not yet initialized or disabled */ HAL_NAND_STATE_READY = 0x01, /*!< NAND initialized and ready for use */ HAL_NAND_STATE_BUSY = 0x02, /*!< NAND internal process is ongoing */ HAL_NAND_STATE_ERROR = 0x03 /*!< NAND error state */ }HAL_NAND_StateTypeDef; /** * @brief NAND Memory electronic signature Structure definition */ typedef struct { /*State = HAL_NAND_STATE_RESET) /** * @} */ /* Exported functions --------------------------------------------------------*/ /** @addtogroup NAND_Exported_Functions NAND Exported Functions * @{ */ /** @addtogroup NAND_Exported_Functions_Group1 Initialization and de-initialization functions * @{ */ /* Initialization/de-initialization functions ********************************/ HAL_StatusTypeDef HAL_NAND_Init(NAND_HandleTypeDef *hnand, FMC_NAND_PCC_TimingTypeDef *ComSpace_Timing, FMC_NAND_PCC_TimingTypeDef *AttSpace_Timing); HAL_StatusTypeDef HAL_NAND_DeInit(NAND_HandleTypeDef *hnand); void HAL_NAND_MspInit(NAND_HandleTypeDef *hnand); void HAL_NAND_MspDeInit(NAND_HandleTypeDef *hnand); void HAL_NAND_IRQHandler(NAND_HandleTypeDef *hnand); void HAL_NAND_ITCallback(NAND_HandleTypeDef *hnand); /** * @} */ /** @addtogroup NAND_Exported_Functions_Group2 Input and Output functions * @{ */ /* IO operation functions ****************************************************/ HAL_StatusTypeDef HAL_NAND_Read_ID(NAND_HandleTypeDef *hnand, NAND_IDTypeDef *pNAND_ID); HAL_StatusTypeDef HAL_NAND_Reset(NAND_HandleTypeDef *hnand); HAL_StatusTypeDef HAL_NAND_Read_Page(NAND_HandleTypeDef *hnand, NAND_AddressTypeDef *pAddress, uint8_t *pBuffer, uint32_t NumPageToRead); HAL_StatusTypeDef HAL_NAND_Write_Page(NAND_HandleTypeDef *hnand, NAND_AddressTypeDef *pAddress, uint8_t *pBuffer, uint32_t NumPageToWrite); HAL_StatusTypeDef HAL_NAND_Read_SpareArea(NAND_HandleTypeDef *hnand, NAND_AddressTypeDef *pAddress, uint8_t *pBuffer, uint32_t NumSpareAreaToRead); HAL_StatusTypeDef HAL_NAND_Write_SpareArea(NAND_HandleTypeDef *hnand, NAND_AddressTypeDef *pAddress, uint8_t *pBuffer, uint32_t NumSpareAreaTowrite); HAL_StatusTypeDef HAL_NAND_Erase_Block(NAND_HandleTypeDef *hnand, NAND_AddressTypeDef *pAddress); uint32_t HAL_NAND_Read_Status(NAND_HandleTypeDef *hnand); uint32_t HAL_NAND_Address_Inc(NAND_HandleTypeDef *hnand, NAND_AddressTypeDef *pAddress); /** * @} */ /** @addtogroup NAND_Exported_Functions_Group3 Peripheral Control functions * @{ */ /* NAND Control functions ****************************************************/ HAL_StatusTypeDef HAL_NAND_ECC_Enable(NAND_HandleTypeDef *hnand); HAL_StatusTypeDef HAL_NAND_ECC_Disable(NAND_HandleTypeDef *hnand); HAL_StatusTypeDef HAL_NAND_GetECC(NAND_HandleTypeDef *hnand, uint32_t *ECCval, uint32_t Timeout); /** * @} */ /** @addtogroup NAND_Exported_Functions_Group4 Peripheral State functions * @{ */ /* NAND State functions *******************************************************/ HAL_NAND_StateTypeDef HAL_NAND_GetState(NAND_HandleTypeDef *hnand); uint32_t HAL_NAND_Read_Status(NAND_HandleTypeDef *hnand); /** * @} */ /** * @} */ /* Private types -------------------------------------------------------------*/ /* Private variables ---------------------------------------------------------*/ /* Private constants ---------------------------------------------------------*/ /** @defgroup NAND_Private_Constants NAND Private Constants * @{ */ #define NAND_DEVICE1 ((uint32_t)0x70000000) #define NAND_DEVICE2 ((uint32_t)0x80000000) #define NAND_WRITE_TIMEOUT ((uint32_t)0x01000000) #define CMD_AREA ((uint32_t)(1<<16)) /* A16 = CLE high */ #define ADDR_AREA ((uint32_t)(1<<17)) /* A17 = ALE high */ #define NAND_CMD_AREA_A ((uint8_t)0x00) #define NAND_CMD_AREA_B ((uint8_t)0x01) #define NAND_CMD_AREA_C ((uint8_t)0x50) #define NAND_CMD_AREA_TRUE1 ((uint8_t)0x30) #define NAND_CMD_WRITE0 ((uint8_t)0x80) #define NAND_CMD_WRITE_TRUE1 ((uint8_t)0x10) #define NAND_CMD_ERASE0 ((uint8_t)0x60) #define NAND_CMD_ERASE1 ((uint8_t)0xD0) #define NAND_CMD_READID ((uint8_t)0x90) #define NAND_CMD_STATUS ((uint8_t)0x70) #define NAND_CMD_LOCK_STATUS ((uint8_t)0x7A) #define NAND_CMD_RESET ((uint8_t)0xFF) /* NAND memory status */ #define NAND_VALID_ADDRESS ((uint32_t)0x00000100) #define NAND_INVALID_ADDRESS ((uint32_t)0x00000200) #define NAND_TIMEOUT_ERROR ((uint32_t)0x00000400) #define NAND_BUSY ((uint32_t)0x00000000) #define NAND_ERROR ((uint32_t)0x00000001) #define NAND_READY ((uint32_t)0x00000040) /** * @} */ /* Private macros ------------------------------------------------------------*/ /** @defgroup NAND_Private_Macros NAND Private Macros * @{ */ /** * @brief NAND memory address computation. * @param __ADDRESS__: NAND memory address. * @param __HANDLE__: NAND handle. * @retval NAND Raw address value */ #define ARRAY_ADDRESS(__ADDRESS__ , __HANDLE__) ((__ADDRESS__)->Page + \ (((__ADDRESS__)->Block + (((__ADDRESS__)->Zone) * ((__HANDLE__)->Info.ZoneSize)))* ((__HANDLE__)->Info.BlockSize))) /** * @brief NAND memory address cycling. * @param __ADDRESS__: NAND memory address. * @retval NAND address cycling value. */ #define ADDR_1ST_CYCLE(__ADDRESS__) (uint8_t)(__ADDRESS__) /* 1st addressing cycle */ #define ADDR_2ND_CYCLE(__ADDRESS__) (uint8_t)((__ADDRESS__) >> 8) /* 2nd addressing cycle */ #define ADDR_3RD_CYCLE(__ADDRESS__) (uint8_t)((__ADDRESS__) >> 16) /* 3rd addressing cycle */ #define ADDR_4TH_CYCLE(__ADDRESS__) (uint8_t)((__ADDRESS__) >> 24) /* 4th addressing cycle */ /** * @} */ #endif /* STM32F405xx || STM32F415xx || STM32F407xx || STM32F417xx ||\ STM32F427xx || STM32F437xx || STM32F429xx || STM32F439xx ||\ STM32F446xx || STM32F469xx || STM32F479xx */ /** * @} */ /** * @} */ /** * @} */ #ifdef __cplusplus } #endif #endif /* __STM32F4xx_HAL_NAND_H */ /************************ (C) COPYRIGHT STMicroelectronics *****END OF FILE****/ ================================================ FILE: Zelig/mbed/TARGET_NUCLEO_F411RE/stm32f4xx_hal_nor.h ================================================ /** ****************************************************************************** * @file stm32f4xx_hal_nor.h * @author MCD Application Team * @version V1.4.1 * @date 09-October-2015 * @brief Header file of NOR HAL module. ****************************************************************************** * @attention * *

© COPYRIGHT(c) 2015 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. * ****************************************************************************** */ /* Define to prevent recursive inclusion -------------------------------------*/ #ifndef __STM32F4xx_HAL_NOR_H #define __STM32F4xx_HAL_NOR_H #ifdef __cplusplus extern "C" { #endif /* Includes ------------------------------------------------------------------*/ #if defined(STM32F405xx) || defined(STM32F415xx) || defined(STM32F407xx) || defined(STM32F417xx) #include "stm32f4xx_ll_fsmc.h" #endif /* STM32F405xx || STM32F415xx || STM32F407xx || STM32F417xx */ #if defined(STM32F427xx) || defined(STM32F437xx) || defined(STM32F429xx) || defined(STM32F439xx) ||\ defined(STM32F446xx) || defined(STM32F469xx) || defined(STM32F479xx) #include "stm32f4xx_ll_fmc.h" #endif /* STM32F427xx || STM32F437xx || STM32F429xx || STM32F439xx || STM32F446xx || STM32F469xx || STM32F479xx */ /** @addtogroup STM32F4xx_HAL_Driver * @{ */ /** @addtogroup NOR * @{ */ #if defined(STM32F405xx) || defined(STM32F415xx) || defined(STM32F407xx) || defined(STM32F417xx) ||\ defined(STM32F427xx) || defined(STM32F437xx) || defined(STM32F429xx) || defined(STM32F439xx) ||\ defined(STM32F446xx) || defined(STM32F469xx) || defined(STM32F479xx) /* Exported typedef ----------------------------------------------------------*/ /** @defgroup NOR_Exported_Types NOR Exported Types * @{ */ /** * @brief HAL SRAM State structures definition */ typedef enum { HAL_NOR_STATE_RESET = 0x00, /*!< NOR not yet initialized or disabled */ HAL_NOR_STATE_READY = 0x01, /*!< NOR initialized and ready for use */ HAL_NOR_STATE_BUSY = 0x02, /*!< NOR internal processing is ongoing */ HAL_NOR_STATE_ERROR = 0x03, /*!< NOR error state */ HAL_NOR_STATE_PROTECTED = 0x04 /*!< NOR NORSRAM device write protected */ }HAL_NOR_StateTypeDef; /** * @brief FMC NOR Status typedef */ typedef enum { HAL_NOR_STATUS_SUCCESS = 0, HAL_NOR_STATUS_ONGOING, HAL_NOR_STATUS_ERROR, HAL_NOR_STATUS_TIMEOUT }HAL_NOR_StatusTypeDef; /** * @brief FMC NOR ID typedef */ typedef struct { uint16_t Manufacturer_Code; /*!< Defines the device's manufacturer code used to identify the memory */ uint16_t Device_Code1; uint16_t Device_Code2; uint16_t Device_Code3; /*!< Defines the device's codes used to identify the memory. These codes can be accessed by performing read operations with specific control signals and addresses set.They can also be accessed by issuing an Auto Select command */ }NOR_IDTypeDef; /** * @brief FMC NOR CFI typedef */ typedef struct { /*!< Defines the information stored in the memory's Common flash interface which contains a description of various electrical and timing parameters, density information and functions supported by the memory */ uint16_t CFI_1; uint16_t CFI_2; uint16_t CFI_3; uint16_t CFI_4; }NOR_CFITypeDef; /** * @brief NOR handle Structure definition */ typedef struct { FMC_NORSRAM_TypeDef *Instance; /*!< Register base address */ FMC_NORSRAM_EXTENDED_TypeDef *Extended; /*!< Extended mode register base address */ FMC_NORSRAM_InitTypeDef Init; /*!< NOR device control configuration parameters */ HAL_LockTypeDef Lock; /*!< NOR locking object */ __IO HAL_NOR_StateTypeDef State; /*!< NOR device access state */ }NOR_HandleTypeDef; /** * @} */ /* Exported constants --------------------------------------------------------*/ /* Exported macros ------------------------------------------------------------*/ /** @defgroup NOR_Exported_Macros NOR Exported Macros * @{ */ /** @brief Reset NOR handle state * @param __HANDLE__: specifies the NOR handle. * @retval None */ #define __HAL_NOR_RESET_HANDLE_STATE(__HANDLE__) ((__HANDLE__)->State = HAL_NOR_STATE_RESET) /** * @} */ /* Exported functions --------------------------------------------------------*/ /** @addtogroup NOR_Exported_Functions * @{ */ /** @addtogroup NOR_Exported_Functions_Group1 * @{ */ /* Initialization/de-initialization functions ********************************/ HAL_StatusTypeDef HAL_NOR_Init(NOR_HandleTypeDef *hnor, FMC_NORSRAM_TimingTypeDef *Timing, FMC_NORSRAM_TimingTypeDef *ExtTiming); HAL_StatusTypeDef HAL_NOR_DeInit(NOR_HandleTypeDef *hnor); void HAL_NOR_MspInit(NOR_HandleTypeDef *hnor); void HAL_NOR_MspDeInit(NOR_HandleTypeDef *hnor); void HAL_NOR_MspWait(NOR_HandleTypeDef *hnor, uint32_t Timeout); /** * @} */ /** @addtogroup NOR_Exported_Functions_Group2 * @{ */ /* I/O operation functions ***************************************************/ HAL_StatusTypeDef HAL_NOR_Read_ID(NOR_HandleTypeDef *hnor, NOR_IDTypeDef *pNOR_ID); HAL_StatusTypeDef HAL_NOR_ReturnToReadMode(NOR_HandleTypeDef *hnor); HAL_StatusTypeDef HAL_NOR_Read(NOR_HandleTypeDef *hnor, uint32_t *pAddress, uint16_t *pData); HAL_StatusTypeDef HAL_NOR_Program(NOR_HandleTypeDef *hnor, uint32_t *pAddress, uint16_t *pData); HAL_StatusTypeDef HAL_NOR_ReadBuffer(NOR_HandleTypeDef *hnor, uint32_t uwAddress, uint16_t *pData, uint32_t uwBufferSize); HAL_StatusTypeDef HAL_NOR_ProgramBuffer(NOR_HandleTypeDef *hnor, uint32_t uwAddress, uint16_t *pData, uint32_t uwBufferSize); HAL_StatusTypeDef HAL_NOR_Erase_Block(NOR_HandleTypeDef *hnor, uint32_t BlockAddress, uint32_t Address); HAL_StatusTypeDef HAL_NOR_Erase_Chip(NOR_HandleTypeDef *hnor, uint32_t Address); HAL_StatusTypeDef HAL_NOR_Read_CFI(NOR_HandleTypeDef *hnor, NOR_CFITypeDef *pNOR_CFI); /** * @} */ /** @addtogroup NOR_Exported_Functions_Group3 * @{ */ /* NOR Control functions *****************************************************/ HAL_StatusTypeDef HAL_NOR_WriteOperation_Enable(NOR_HandleTypeDef *hnor); HAL_StatusTypeDef HAL_NOR_WriteOperation_Disable(NOR_HandleTypeDef *hnor); /** * @} */ /** @addtogroup NOR_Exported_Functions_Group4 * @{ */ /* NOR State functions ********************************************************/ HAL_NOR_StateTypeDef HAL_NOR_GetState(NOR_HandleTypeDef *hnor); HAL_NOR_StatusTypeDef HAL_NOR_GetStatus(NOR_HandleTypeDef *hnor, uint32_t Address, uint32_t Timeout); /** * @} */ /** * @} */ /* Private types -------------------------------------------------------------*/ /* Private variables ---------------------------------------------------------*/ /* Private constants ---------------------------------------------------------*/ /** @defgroup NOR_Private_Constants NOR Private Constants * @{ */ /* NOR device IDs addresses */ #define MC_ADDRESS ((uint16_t)0x0000) #define DEVICE_CODE1_ADDR ((uint16_t)0x0001) #define DEVICE_CODE2_ADDR ((uint16_t)0x000E) #define DEVICE_CODE3_ADDR ((uint16_t)0x000F) /* NOR CFI IDs addresses */ #define CFI1_ADDRESS ((uint16_t)0x61) #define CFI2_ADDRESS ((uint16_t)0x62) #define CFI3_ADDRESS ((uint16_t)0x63) #define CFI4_ADDRESS ((uint16_t)0x64) /* NOR operation wait timeout */ #define NOR_TMEOUT ((uint16_t)0xFFFF) /* NOR memory data width */ #define NOR_MEMORY_8B ((uint8_t)0x0) #define NOR_MEMORY_16B ((uint8_t)0x1) /* NOR memory device read/write start address */ #define NOR_MEMORY_ADRESS1 ((uint32_t)0x60000000) #define NOR_MEMORY_ADRESS2 ((uint32_t)0x64000000) #define NOR_MEMORY_ADRESS3 ((uint32_t)0x68000000) #define NOR_MEMORY_ADRESS4 ((uint32_t)0x6C000000) /** * @} */ /* Private macros ------------------------------------------------------------*/ /** @defgroup NOR_Private_Macros NOR Private Macros * @{ */ /** * @brief NOR memory address shifting. * @param __NOR_ADDRESS__: NOR base address * @param NOR_MEMORY_WIDTH: NOR memory width * @param ADDRESS: NOR memory address * @retval NOR shifted address value */ #define NOR_ADDR_SHIFT(__NOR_ADDRESS__, NOR_MEMORY_WIDTH, ADDRESS) (uint32_t)(((NOR_MEMORY_WIDTH) == NOR_MEMORY_8B)? ((uint32_t)((__NOR_ADDRESS__) + (2 * (ADDRESS)))):\ ((uint32_t)((__NOR_ADDRESS__) + (ADDRESS)))) /** * @brief NOR memory write data to specified address. * @param ADDRESS: NOR memory address * @param DATA: Data to write * @retval None */ #define NOR_WRITE(ADDRESS, DATA) (*(__IO uint16_t *)((uint32_t)(ADDRESS)) = (DATA)) /** * @} */ #endif /* STM32F405xx || STM32F415xx || STM32F407xx || STM32F417xx ||\ STM32F427xx || STM32F437xx || STM32F429xx || STM32F439xx ||\ STM32F446xx || STM32F469xx || STM32F479xx */ /** * @} */ /** * @} */ #ifdef __cplusplus } #endif #endif /* __STM32F4xx_HAL_NOR_H */ /************************ (C) COPYRIGHT STMicroelectronics *****END OF FILE****/ ================================================ FILE: Zelig/mbed/TARGET_NUCLEO_F411RE/stm32f4xx_hal_pccard.h ================================================ /** ****************************************************************************** * @file stm32f4xx_hal_pccard.h * @author MCD Application Team * @version V1.4.1 * @date 09-October-2015 * @brief Header file of PCCARD HAL module. ****************************************************************************** * @attention * *

© COPYRIGHT(c) 2015 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. * ****************************************************************************** */ /* Define to prevent recursive inclusion -------------------------------------*/ #ifndef __STM32F4xx_HAL_PCCARD_H #define __STM32F4xx_HAL_PCCARD_H #ifdef __cplusplus extern "C" { #endif /* Includes ------------------------------------------------------------------*/ #if defined(STM32F405xx) || defined(STM32F415xx) || defined(STM32F407xx) || defined(STM32F417xx) #include "stm32f4xx_ll_fsmc.h" #endif /* STM32F405xx || STM32F415xx || STM32F407xx || STM32F417xx */ #if defined(STM32F427xx) || defined(STM32F437xx) || defined(STM32F429xx) || defined(STM32F439xx) #include "stm32f4xx_ll_fmc.h" #endif /* STM32F427xx || STM32F437xx || STM32F429xx || STM32F439xx */ /** @addtogroup STM32F4xx_HAL_Driver * @{ */ #if defined(STM32F405xx) || defined(STM32F415xx) || defined(STM32F407xx) || defined(STM32F417xx) ||\ defined(STM32F427xx) || defined(STM32F437xx) || defined(STM32F429xx) || defined(STM32F439xx) /** @addtogroup PCCARD * @{ */ /* Exported typedef ----------------------------------------------------------*/ /** @defgroup PCCARD_Exported_Types PCCARD Exported Types * @{ */ /** * @brief HAL PCCARD State structures definition */ typedef enum { HAL_PCCARD_STATE_RESET = 0x00, /*!< PCCARD peripheral not yet initialized or disabled */ HAL_PCCARD_STATE_READY = 0x01, /*!< PCCARD peripheral ready */ HAL_PCCARD_STATE_BUSY = 0x02, /*!< PCCARD peripheral busy */ HAL_PCCARD_STATE_ERROR = 0x04 /*!< PCCARD peripheral error */ }HAL_PCCARD_StateTypeDef; typedef enum { HAL_PCCARD_STATUS_SUCCESS = 0, HAL_PCCARD_STATUS_ONGOING, HAL_PCCARD_STATUS_ERROR, HAL_PCCARD_STATUS_TIMEOUT }HAL_PCCARD_StatusTypeDef; /** * @brief FMC_PCCARD handle Structure definition */ typedef struct { FMC_PCCARD_TypeDef *Instance; /*!< Register base address for PCCARD device */ FMC_PCCARD_InitTypeDef Init; /*!< PCCARD device control configuration parameters */ __IO HAL_PCCARD_StateTypeDef State; /*!< PCCARD device access state */ HAL_LockTypeDef Lock; /*!< PCCARD Lock */ }PCCARD_HandleTypeDef; /** * @} */ /* Exported constants --------------------------------------------------------*/ /* Exported macro ------------------------------------------------------------*/ /** @defgroup PCCARD_Exported_Macros PCCARD Exported Macros * @{ */ /** @brief Reset PCCARD handle state * @param __HANDLE__: specifies the PCCARD handle. * @retval None */ #define __HAL_PCCARD_RESET_HANDLE_STATE(__HANDLE__) ((__HANDLE__)->State = HAL_PCCARD_STATE_RESET) /** * @} */ /* Exported functions --------------------------------------------------------*/ /** @addtogroup PCCARD_Exported_Functions * @{ */ /** @addtogroup PCCARD_Exported_Functions_Group1 * @{ */ /* Initialization/de-initialization functions **********************************/ HAL_StatusTypeDef HAL_PCCARD_Init(PCCARD_HandleTypeDef *hpccard, FMC_NAND_PCC_TimingTypeDef *ComSpaceTiming, FMC_NAND_PCC_TimingTypeDef *AttSpaceTiming, FMC_NAND_PCC_TimingTypeDef *IOSpaceTiming); HAL_StatusTypeDef HAL_PCCARD_DeInit(PCCARD_HandleTypeDef *hpccard); void HAL_PCCARD_MspInit(PCCARD_HandleTypeDef *hpccard); void HAL_PCCARD_MspDeInit(PCCARD_HandleTypeDef *hpccard); /** * @} */ /** @addtogroup PCCARD_Exported_Functions_Group2 * @{ */ /* IO operation functions *****************************************************/ HAL_StatusTypeDef HAL_PCCARD_Read_ID(PCCARD_HandleTypeDef *hpccard, uint8_t CompactFlash_ID[], uint8_t *pStatus); HAL_StatusTypeDef HAL_PCCARD_Write_Sector(PCCARD_HandleTypeDef *hpccard, uint16_t *pBuffer, uint16_t SectorAddress, uint8_t *pStatus); HAL_StatusTypeDef HAL_PCCARD_Read_Sector(PCCARD_HandleTypeDef *hpccard, uint16_t *pBuffer, uint16_t SectorAddress, uint8_t *pStatus); HAL_StatusTypeDef HAL_PCCARD_Erase_Sector(PCCARD_HandleTypeDef *hpccard, uint16_t SectorAddress, uint8_t *pStatus); HAL_StatusTypeDef HAL_PCCARD_Reset(PCCARD_HandleTypeDef *hpccard); void HAL_PCCARD_IRQHandler(PCCARD_HandleTypeDef *hpccard); void HAL_PCCARD_ITCallback(PCCARD_HandleTypeDef *hpccard); /** * @} */ /** @addtogroup PCCARD_Exported_Functions_Group3 * @{ */ /* PCCARD State functions *******************************************************/ HAL_PCCARD_StateTypeDef HAL_PCCARD_GetState(PCCARD_HandleTypeDef *hpccard); HAL_PCCARD_StatusTypeDef HAL_PCCARD_GetStatus(PCCARD_HandleTypeDef *hpccard); HAL_PCCARD_StatusTypeDef HAL_PCCARD_ReadStatus(PCCARD_HandleTypeDef *hpccard); /** * @} */ /** * @} */ /* Private types -------------------------------------------------------------*/ /* Private variables ---------------------------------------------------------*/ /* Private constants ---------------------------------------------------------*/ /** @defgroup PCCARD_Private_Constants PCCARD Private Constants * @{ */ #define PCCARD_DEVICE_ADDRESS ((uint32_t)0x90000000) #define PCCARD_ATTRIBUTE_SPACE_ADDRESS ((uint32_t)0x98000000) /* Attribute space size to @0x9BFF FFFF */ #define PCCARD_COMMON_SPACE_ADDRESS PCCARD_DEVICE_ADDRESS /* Common space size to @0x93FF FFFF */ #define PCCARD_IO_SPACE_ADDRESS ((uint32_t)0x9C000000) /* IO space size to @0x9FFF FFFF */ #define PCCARD_IO_SPACE_PRIMARY_ADDR ((uint32_t)0x9C0001F0) /* IO space size to @0x9FFF FFFF */ /* Flash-ATA registers description */ #define ATA_DATA ((uint8_t)0x00) /* Data register */ #define ATA_SECTOR_COUNT ((uint8_t)0x02) /* Sector Count register */ #define ATA_SECTOR_NUMBER ((uint8_t)0x03) /* Sector Number register */ #define ATA_CYLINDER_LOW ((uint8_t)0x04) /* Cylinder low register */ #define ATA_CYLINDER_HIGH ((uint8_t)0x05) /* Cylinder high register */ #define ATA_CARD_HEAD ((uint8_t)0x06) /* Card/Head register */ #define ATA_STATUS_CMD ((uint8_t)0x07) /* Status(read)/Command(write) register */ #define ATA_STATUS_CMD_ALTERNATE ((uint8_t)0x0E) /* Alternate Status(read)/Command(write) register */ #define ATA_COMMON_DATA_AREA ((uint16_t)0x0400) /* Start of data area (for Common access only!) */ #define ATA_CARD_CONFIGURATION ((uint16_t)0x0202) /* Card Configuration and Status Register */ /* Flash-ATA commands */ #define ATA_READ_SECTOR_CMD ((uint8_t)0x20) #define ATA_WRITE_SECTOR_CMD ((uint8_t)0x30) #define ATA_ERASE_SECTOR_CMD ((uint8_t)0xC0) #define ATA_IDENTIFY_CMD ((uint8_t)0xEC) /* PC Card/Compact Flash status */ #define PCCARD_TIMEOUT_ERROR ((uint8_t)0x60) #define PCCARD_BUSY ((uint8_t)0x80) #define PCCARD_PROGR ((uint8_t)0x01) #define PCCARD_READY ((uint8_t)0x40) #define PCCARD_SECTOR_SIZE ((uint32_t)255) /* In half words */ /** * @} */ /* Compact Flash redefinition */ #define HAL_CF_Init HAL_PCCARD_Init #define HAL_CF_DeInit HAL_PCCARD_DeInit #define HAL_CF_MspInit HAL_PCCARD_MspInit #define HAL_CF_MspDeInit HAL_PCCARD_MspDeInit #define HAL_CF_Read_ID HAL_PCCARD_Read_ID #define HAL_CF_Write_Sector HAL_PCCARD_Write_Sector #define HAL_CF_Read_Sector HAL_PCCARD_Read_Sector #define HAL_CF_Erase_Sector HAL_PCCARD_Erase_Sector #define HAL_CF_Reset HAL_PCCARD_Reset #define HAL_CF_IRQHandler HAL_PCCARD_IRQHandler #define HAL_CF_ITCallback HAL_PCCARD_ITCallback #define HAL_CF_GetState HAL_PCCARD_GetState #define HAL_CF_GetStatus HAL_PCCARD_GetStatus #define HAL_CF_ReadStatus HAL_PCCARD_ReadStatus #define HAL_CF_STATUS_SUCCESS HAL_PCCARD_STATUS_SUCCESS #define HAL_CF_STATUS_ONGOING HAL_PCCARD_STATUS_ONGOING #define HAL_CF_STATUS_ERROR HAL_PCCARD_STATUS_ERROR #define HAL_CF_STATUS_TIMEOUT HAL_PCCARD_STATUS_TIMEOUT #define HAL_CF_StatusTypeDef HAL_PCCARD_StatusTypeDef #define CF_DEVICE_ADDRESS PCCARD_DEVICE_ADDRESS #define CF_ATTRIBUTE_SPACE_ADDRESS PCCARD_ATTRIBUTE_SPACE_ADDRESS #define CF_COMMON_SPACE_ADDRESS PCCARD_COMMON_SPACE_ADDRESS #define CF_IO_SPACE_ADDRESS PCCARD_IO_SPACE_ADDRESS #define CF_IO_SPACE_PRIMARY_ADDR PCCARD_IO_SPACE_PRIMARY_ADDR #define CF_TIMEOUT_ERROR PCCARD_TIMEOUT_ERROR #define CF_BUSY PCCARD_BUSY #define CF_PROGR PCCARD_PROGR #define CF_READY PCCARD_READY #define CF_SECTOR_SIZE PCCARD_SECTOR_SIZE /* Private macros ------------------------------------------------------------*/ /** * @} */ #endif /* STM32F405xx || STM32F415xx || STM32F407xx || STM32F417xx ||\ STM32F427xx || STM32F437xx || STM32F429xx || STM32F439xx */ /** * @} */ #ifdef __cplusplus } #endif #endif /* __STM32F4xx_HAL_PCCARD_H */ /************************ (C) COPYRIGHT STMicroelectronics *****END OF FILE****/ ================================================ FILE: Zelig/mbed/TARGET_NUCLEO_F411RE/stm32f4xx_hal_pcd.h ================================================ /** ****************************************************************************** * @file stm32f4xx_hal_pcd.h * @author MCD Application Team * @version V1.4.1 * @date 09-October-2015 * @brief Header file of PCD HAL module. ****************************************************************************** * @attention * *

© COPYRIGHT(c) 2015 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. * ****************************************************************************** */ /* Define to prevent recursive inclusion -------------------------------------*/ #ifndef __STM32F4xx_HAL_PCD_H #define __STM32F4xx_HAL_PCD_H #ifdef __cplusplus extern "C" { #endif #if defined(STM32F405xx) || defined(STM32F415xx) || defined(STM32F407xx) || defined(STM32F417xx) || \ defined(STM32F427xx) || defined(STM32F437xx) || defined(STM32F429xx) || defined(STM32F439xx) || \ defined(STM32F401xC) || defined(STM32F401xE) || defined(STM32F411xE) || defined(STM32F446xx) || \ defined(STM32F469xx) || defined(STM32F479xx) /* Includes ------------------------------------------------------------------*/ #include "stm32f4xx_ll_usb.h" /** @addtogroup STM32F4xx_HAL_Driver * @{ */ /** @addtogroup PCD * @{ */ /* Exported types ------------------------------------------------------------*/ /** @defgroup PCD_Exported_Types PCD Exported Types * @{ */ /** * @brief PCD State structure definition */ typedef enum { HAL_PCD_STATE_RESET = 0x00, HAL_PCD_STATE_READY = 0x01, HAL_PCD_STATE_ERROR = 0x02, HAL_PCD_STATE_BUSY = 0x03, HAL_PCD_STATE_TIMEOUT = 0x04 } PCD_StateTypeDef; #ifdef USB_OTG_GLPMCFG_LPMEN /* Device LPM suspend state */ typedef enum { LPM_L0 = 0x00, /* on */ LPM_L1 = 0x01, /* LPM L1 sleep */ LPM_L2 = 0x02, /* suspend */ LPM_L3 = 0x03, /* off */ }PCD_LPM_StateTypeDef; #endif /* USB_OTG_GLPMCFG_LPMEN */ typedef USB_OTG_GlobalTypeDef PCD_TypeDef; typedef USB_OTG_CfgTypeDef PCD_InitTypeDef; typedef USB_OTG_EPTypeDef PCD_EPTypeDef ; /** * @brief PCD Handle Structure definition */ typedef struct { PCD_TypeDef *Instance; /*!< Register base address */ PCD_InitTypeDef Init; /*!< PCD required parameters */ PCD_EPTypeDef IN_ep[15]; /*!< IN endpoint parameters */ PCD_EPTypeDef OUT_ep[15]; /*!< OUT endpoint parameters */ HAL_LockTypeDef Lock; /*!< PCD peripheral status */ __IO PCD_StateTypeDef State; /*!< PCD communication state */ uint32_t Setup[12]; /*!< Setup packet buffer */ #ifdef USB_OTG_GLPMCFG_LPMEN PCD_LPM_StateTypeDef LPM_State; /*!< LPM State */ uint32_t BESL; uint32_t lpm_active; /*!< Enable or disable the Link Power Management . This parameter can be set to ENABLE or DISABLE */ #endif /* USB_OTG_GLPMCFG_LPMEN */ #ifdef USB_OTG_GCCFG_BCDEN uint32_t battery_charging_active; /*!< Enable or disable Battery charging. This parameter can be set to ENABLE or DISABLE */ #endif /* USB_OTG_GCCFG_BCDEN */ void *pData; /*!< Pointer to upper stack Handler */ } PCD_HandleTypeDef; /** * @} */ /* Include PCD HAL Extension module */ #include "stm32f4xx_hal_pcd_ex.h" /* Exported constants --------------------------------------------------------*/ /** @defgroup PCD_Exported_Constants PCD Exported Constants * @{ */ /** @defgroup PCD_Speed PCD Speed * @{ */ #define PCD_SPEED_HIGH 0 #define PCD_SPEED_HIGH_IN_FULL 1 #define PCD_SPEED_FULL 2 /** * @} */ /** @defgroup PCD_PHY_Module PCD PHY Module * @{ */ #define PCD_PHY_ULPI 1 #define PCD_PHY_EMBEDDED 2 /** * @} */ /** @defgroup PCD_Turnaround_Timeout Turnaround Timeout Value * @{ */ #ifndef USBD_HS_TRDT_VALUE #define USBD_HS_TRDT_VALUE 9 #endif /* USBD_HS_TRDT_VALUE */ #ifndef USBD_FS_TRDT_VALUE #define USBD_FS_TRDT_VALUE 5 #endif /* USBD_FS_TRDT_VALUE */ /** * @} */ /** * @} */ /* Exported macros -----------------------------------------------------------*/ /** @defgroup PCD_Exported_Macros PCD Exported Macros * @brief macros to handle interrupts and specific clock configurations * @{ */ #define __HAL_PCD_ENABLE(__HANDLE__) USB_EnableGlobalInt ((__HANDLE__)->Instance) #define __HAL_PCD_DISABLE(__HANDLE__) USB_DisableGlobalInt ((__HANDLE__)->Instance) #define __HAL_PCD_GET_FLAG(__HANDLE__, __INTERRUPT__) ((USB_ReadInterrupts((__HANDLE__)->Instance) & (__INTERRUPT__)) == (__INTERRUPT__)) #define __HAL_PCD_CLEAR_FLAG(__HANDLE__, __INTERRUPT__) (((__HANDLE__)->Instance->GINTSTS) &= (__INTERRUPT__)) #define __HAL_PCD_IS_INVALID_INTERRUPT(__HANDLE__) (USB_ReadInterrupts((__HANDLE__)->Instance) == 0) #define __HAL_PCD_UNGATE_PHYCLOCK(__HANDLE__) *(__IO uint32_t *)((uint32_t)((__HANDLE__)->Instance) + USB_OTG_PCGCCTL_BASE) &= \ ~(USB_OTG_PCGCCTL_STOPCLK) #define __HAL_PCD_GATE_PHYCLOCK(__HANDLE__) *(__IO uint32_t *)((uint32_t)((__HANDLE__)->Instance) + USB_OTG_PCGCCTL_BASE) |= USB_OTG_PCGCCTL_STOPCLK #define __HAL_PCD_IS_PHY_SUSPENDED(__HANDLE__) ((*(__IO uint32_t *)((uint32_t)((__HANDLE__)->Instance) + USB_OTG_PCGCCTL_BASE))&0x10) #define USB_OTG_FS_WAKEUP_EXTI_RISING_EDGE ((uint32_t)0x08) #define USB_OTG_FS_WAKEUP_EXTI_FALLING_EDGE ((uint32_t)0x0C) #define USB_OTG_FS_WAKEUP_EXTI_RISING_FALLING_EDGE ((uint32_t)0x10) #define USB_OTG_HS_WAKEUP_EXTI_RISING_EDGE ((uint32_t)0x08) #define USB_OTG_HS_WAKEUP_EXTI_FALLING_EDGE ((uint32_t)0x0C) #define USB_OTG_HS_WAKEUP_EXTI_RISING_FALLING_EDGE ((uint32_t)0x10) #define USB_OTG_HS_WAKEUP_EXTI_LINE ((uint32_t)0x00100000) /*!< External interrupt line 20 Connected to the USB HS EXTI Line */ #define USB_OTG_FS_WAKEUP_EXTI_LINE ((uint32_t)0x00040000) /*!< External interrupt line 18 Connected to the USB FS EXTI Line */ #define __HAL_USB_OTG_HS_WAKEUP_EXTI_ENABLE_IT() EXTI->IMR |= (USB_OTG_HS_WAKEUP_EXTI_LINE) #define __HAL_USB_OTG_HS_WAKEUP_EXTI_DISABLE_IT() EXTI->IMR &= ~(USB_OTG_HS_WAKEUP_EXTI_LINE) #define __HAL_USB_OTG_HS_WAKEUP_EXTI_GET_FLAG() EXTI->PR & (USB_OTG_HS_WAKEUP_EXTI_LINE) #define __HAL_USB_OTG_HS_WAKEUP_EXTI_CLEAR_FLAG() EXTI->PR = (USB_OTG_HS_WAKEUP_EXTI_LINE) #define __HAL_USB_OTG_HS_WAKEUP_EXTI_ENABLE_RISING_EDGE() EXTI->FTSR &= ~(USB_OTG_HS_WAKEUP_EXTI_LINE);\ EXTI->RTSR |= USB_OTG_HS_WAKEUP_EXTI_LINE #define __HAL_USB_OTG_HS_WAKEUP_EXTI_ENABLE_FALLING_EDGE() EXTI->FTSR |= (USB_OTG_HS_WAKEUP_EXTI_LINE);\ EXTI->RTSR &= ~(USB_OTG_HS_WAKEUP_EXTI_LINE) #define __HAL_USB_OTG_HS_WAKEUP_EXTI_ENABLE_RISING_FALLING_EDGE() EXTI->RTSR &= ~(USB_OTG_HS_WAKEUP_EXTI_LINE);\ EXTI->FTSR &= ~(USB_OTG_HS_WAKEUP_EXTI_LINE;)\ EXTI->RTSR |= USB_OTG_HS_WAKEUP_EXTI_LINE;\ EXTI->FTSR |= USB_OTG_HS_WAKEUP_EXTI_LINE #define __HAL_USB_OTG_HS_WAKEUP_EXTI_GENERATE_SWIT() (EXTI->SWIER |= USB_OTG_FS_WAKEUP_EXTI_LINE) #define __HAL_USB_OTG_FS_WAKEUP_EXTI_ENABLE_IT() EXTI->IMR |= USB_OTG_FS_WAKEUP_EXTI_LINE #define __HAL_USB_OTG_FS_WAKEUP_EXTI_DISABLE_IT() EXTI->IMR &= ~(USB_OTG_FS_WAKEUP_EXTI_LINE) #define __HAL_USB_OTG_FS_WAKEUP_EXTI_GET_FLAG() EXTI->PR & (USB_OTG_FS_WAKEUP_EXTI_LINE) #define __HAL_USB_OTG_FS_WAKEUP_EXTI_CLEAR_FLAG() EXTI->PR = USB_OTG_FS_WAKEUP_EXTI_LINE #define __HAL_USB_OTG_FS_WAKEUP_EXTI_ENABLE_RISING_EDGE() EXTI->FTSR &= ~(USB_OTG_FS_WAKEUP_EXTI_LINE);\ EXTI->RTSR |= USB_OTG_FS_WAKEUP_EXTI_LINE #define __HAL_USB_OTG_FS_WAKEUP_EXTI_ENABLE_FALLING_EDGE() EXTI->FTSR |= (USB_OTG_FS_WAKEUP_EXTI_LINE);\ EXTI->RTSR &= ~(USB_OTG_FS_WAKEUP_EXTI_LINE) #define __HAL_USB_OTG_FS_WAKEUP_EXTI_ENABLE_RISING_FALLING_EDGE() EXTI->RTSR &= ~(USB_OTG_FS_WAKEUP_EXTI_LINE);\ EXTI->FTSR &= ~(USB_OTG_FS_WAKEUP_EXTI_LINE);\ EXTI->RTSR |= USB_OTG_FS_WAKEUP_EXTI_LINE;\ EXTI->FTSR |= USB_OTG_FS_WAKEUP_EXTI_LINE #define __HAL_USB_OTG_FS_WAKEUP_EXTI_GENERATE_SWIT() (EXTI->SWIER |= USB_OTG_FS_WAKEUP_EXTI_LINE) /** * @} */ /* Exported functions --------------------------------------------------------*/ /** @addtogroup PCD_Exported_Functions PCD Exported Functions * @{ */ /* Initialization/de-initialization functions ********************************/ /** @addtogroup PCD_Exported_Functions_Group1 Initialization and de-initialization functions * @{ */ HAL_StatusTypeDef HAL_PCD_Init(PCD_HandleTypeDef *hpcd); HAL_StatusTypeDef HAL_PCD_DeInit(PCD_HandleTypeDef *hpcd); void HAL_PCD_MspInit(PCD_HandleTypeDef *hpcd); void HAL_PCD_MspDeInit(PCD_HandleTypeDef *hpcd); /** * @} */ /* I/O operation functions ***************************************************/ /* Non-Blocking mode: Interrupt */ /** @addtogroup PCD_Exported_Functions_Group2 Input and Output operation functions * @{ */ /* Non-Blocking mode: Interrupt */ HAL_StatusTypeDef HAL_PCD_Start(PCD_HandleTypeDef *hpcd); HAL_StatusTypeDef HAL_PCD_Stop(PCD_HandleTypeDef *hpcd); void HAL_PCD_IRQHandler(PCD_HandleTypeDef *hpcd); void HAL_PCD_DataOutStageCallback(PCD_HandleTypeDef *hpcd, uint8_t epnum); void HAL_PCD_DataInStageCallback(PCD_HandleTypeDef *hpcd, uint8_t epnum); void HAL_PCD_SetupStageCallback(PCD_HandleTypeDef *hpcd); void HAL_PCD_SOFCallback(PCD_HandleTypeDef *hpcd); void HAL_PCD_ResetCallback(PCD_HandleTypeDef *hpcd); void HAL_PCD_SuspendCallback(PCD_HandleTypeDef *hpcd); void HAL_PCD_ResumeCallback(PCD_HandleTypeDef *hpcd); void HAL_PCD_ISOOUTIncompleteCallback(PCD_HandleTypeDef *hpcd, uint8_t epnum); void HAL_PCD_ISOINIncompleteCallback(PCD_HandleTypeDef *hpcd, uint8_t epnum); void HAL_PCD_ConnectCallback(PCD_HandleTypeDef *hpcd); void HAL_PCD_DisconnectCallback(PCD_HandleTypeDef *hpcd); /** * @} */ /* Peripheral Control functions **********************************************/ /** @addtogroup PCD_Exported_Functions_Group3 Peripheral Control functions * @{ */ HAL_StatusTypeDef HAL_PCD_DevConnect(PCD_HandleTypeDef *hpcd); HAL_StatusTypeDef HAL_PCD_DevDisconnect(PCD_HandleTypeDef *hpcd); HAL_StatusTypeDef HAL_PCD_SetAddress(PCD_HandleTypeDef *hpcd, uint8_t address); HAL_StatusTypeDef HAL_PCD_EP_Open(PCD_HandleTypeDef *hpcd, uint8_t ep_addr, uint16_t ep_mps, uint8_t ep_type); HAL_StatusTypeDef HAL_PCD_EP_Close(PCD_HandleTypeDef *hpcd, uint8_t ep_addr); HAL_StatusTypeDef HAL_PCD_EP_Receive(PCD_HandleTypeDef *hpcd, uint8_t ep_addr, uint8_t *pBuf, uint32_t len); HAL_StatusTypeDef HAL_PCD_EP_Transmit(PCD_HandleTypeDef *hpcd, uint8_t ep_addr, uint8_t *pBuf, uint32_t len); uint16_t HAL_PCD_EP_GetRxCount(PCD_HandleTypeDef *hpcd, uint8_t ep_addr); HAL_StatusTypeDef HAL_PCD_EP_SetStall(PCD_HandleTypeDef *hpcd, uint8_t ep_addr); HAL_StatusTypeDef HAL_PCD_EP_ClrStall(PCD_HandleTypeDef *hpcd, uint8_t ep_addr); HAL_StatusTypeDef HAL_PCD_EP_Flush(PCD_HandleTypeDef *hpcd, uint8_t ep_addr); HAL_StatusTypeDef HAL_PCD_ActivateRemoteWakeup(PCD_HandleTypeDef *hpcd); HAL_StatusTypeDef HAL_PCD_DeActivateRemoteWakeup(PCD_HandleTypeDef *hpcd); /** * @} */ /* Peripheral State functions ************************************************/ /** @addtogroup PCD_Exported_Functions_Group4 Peripheral State functions * @{ */ PCD_StateTypeDef HAL_PCD_GetState(PCD_HandleTypeDef *hpcd); /** * @} */ /** * @} */ /* Private macros ------------------------------------------------------------*/ /** @defgroup PCD_Private_Macros PCD Private Macros * @{ */ /** @defgroup PCD_Instance_definition PCD Instance definition * @{ */ #if defined(STM32F405xx) || defined(STM32F415xx) || defined(STM32F407xx) || defined(STM32F417xx) || defined(STM32F427xx) || defined(STM32F437xx) ||\ defined(STM32F429xx) || defined(STM32F439xx) || defined(STM32F446xx) || defined(STM32F469xx) || defined(STM32F479xx) #define IS_PCD_ALL_INSTANCE(INSTANCE) (((INSTANCE) == USB_OTG_FS) || \ ((INSTANCE) == USB_OTG_HS)) #elif defined(STM32F401xC) || defined(STM32F401xE) || defined(STM32F411xE) #define IS_PCD_ALL_INSTANCE(INSTANCE) (((INSTANCE) == USB_OTG_FS)) #endif /** * @} */ /** * @} */ /** * @} */ /** * @} */ #endif /* STM32F405xx || STM32F415xx || STM32F407xx || STM32F417xx || STM32F427xx || STM32F437xx || STM32F429xx || STM32F439xx || STM32F401xC || STM32F401xE || STM32F411xE || STM32F446xx || STM32F469xx || STM32F479xx */ #ifdef __cplusplus } #endif #endif /* __STM32F4xx_HAL_PCD_H */ /************************ (C) COPYRIGHT STMicroelectronics *****END OF FILE****/ ================================================ FILE: Zelig/mbed/TARGET_NUCLEO_F411RE/stm32f4xx_hal_pcd_ex.h ================================================ /** ****************************************************************************** * @file stm32f4xx_hal_pcd_ex.h * @author MCD Application Team * @version V1.4.1 * @date 09-October-2015 * @brief Header file of PCD HAL module. ****************************************************************************** * @attention * *

© COPYRIGHT(c) 2015 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. * ****************************************************************************** */ /* Define to prevent recursive inclusion -------------------------------------*/ #ifndef __STM32F4xx_HAL_PCD_EX_H #define __STM32F4xx_HAL_PCD_EX_H #ifdef __cplusplus extern "C" { #endif #if defined(STM32F405xx) || defined(STM32F415xx) || defined(STM32F407xx) || defined(STM32F417xx) || \ defined(STM32F427xx) || defined(STM32F437xx) || defined(STM32F429xx) || defined(STM32F439xx) || \ defined(STM32F401xC) || defined(STM32F401xE) || defined(STM32F411xE) || defined(STM32F446xx) || \ defined(STM32F469xx) || defined(STM32F479xx) /* Includes ------------------------------------------------------------------*/ #include "stm32f4xx_hal_def.h" /** @addtogroup STM32F4xx_HAL_Driver * @{ */ /** @addtogroup PCDEx * @{ */ /* Exported types ------------------------------------------------------------*/ #if defined(STM32F446xx) || defined(STM32F469xx) || defined(STM32F479xx) typedef enum { PCD_LPM_L0_ACTIVE = 0x00, /* on */ PCD_LPM_L1_ACTIVE = 0x01, /* LPM L1 sleep */ }PCD_LPM_MsgTypeDef; #endif /* STM32F446xx || STM32F469xx || STM32F479xx */ /* Exported constants --------------------------------------------------------*/ /* Exported macros -----------------------------------------------------------*/ /* Exported functions --------------------------------------------------------*/ /** @addtogroup PCDEx_Exported_Functions PCD Extended Exported Functions * @{ */ /** @addtogroup PCDEx_Exported_Functions_Group1 Peripheral Control functions * @{ */ HAL_StatusTypeDef HAL_PCDEx_SetTxFiFo(PCD_HandleTypeDef *hpcd, uint8_t fifo, uint16_t size); HAL_StatusTypeDef HAL_PCDEx_SetRxFiFo(PCD_HandleTypeDef *hpcd, uint16_t size); #if defined(STM32F446xx) || defined(STM32F469xx) || defined(STM32F479xx) HAL_StatusTypeDef HAL_PCDEx_ActivateLPM(PCD_HandleTypeDef *hpcd); HAL_StatusTypeDef HAL_PCDEx_DeActivateLPM(PCD_HandleTypeDef *hpcd); void HAL_PCDEx_LPM_Callback(PCD_HandleTypeDef *hpcd, PCD_LPM_MsgTypeDef msg); #endif /* STM32F446xx || STM32F469xx || STM32F479xx */ /** * @} */ /** * @} */ /** * @} */ /** * @} */ #endif /* STM32F405xx || STM32F415xx || STM32F407xx || STM32F417xx || STM32F427xx || STM32F437xx || STM32F429xx || STM32F439xx || STM32F401xC || STM32F401xE || STM32F411xE || STM32F446xx || STM32F469xx || STM32F479xx */ #ifdef __cplusplus } #endif #endif /* __STM32F4xx_HAL_PCD_EX_H */ /************************ (C) COPYRIGHT STMicroelectronics *****END OF FILE****/ ================================================ FILE: Zelig/mbed/TARGET_NUCLEO_F411RE/stm32f4xx_hal_pwr.h ================================================ /** ****************************************************************************** * @file stm32f4xx_hal_pwr.h * @author MCD Application Team * @version V1.4.1 * @date 09-October-2015 * @brief Header file of PWR HAL module. ****************************************************************************** * @attention * *

© COPYRIGHT(c) 2015 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. * ****************************************************************************** */ /* Define to prevent recursive inclusion -------------------------------------*/ #ifndef __STM32F4xx_HAL_PWR_H #define __STM32F4xx_HAL_PWR_H #ifdef __cplusplus extern "C" { #endif /* Includes ------------------------------------------------------------------*/ #include "stm32f4xx_hal_def.h" /** @addtogroup STM32F4xx_HAL_Driver * @{ */ /** @addtogroup PWR * @{ */ /* Exported types ------------------------------------------------------------*/ /** @defgroup PWR_Exported_Types PWR Exported Types * @{ */ /** * @brief PWR PVD configuration structure definition */ typedef struct { uint32_t PVDLevel; /*!< PVDLevel: Specifies the PVD detection level. This parameter can be a value of @ref PWR_PVD_detection_level */ uint32_t Mode; /*!< Mode: Specifies the operating mode for the selected pins. This parameter can be a value of @ref PWR_PVD_Mode */ }PWR_PVDTypeDef; /** * @} */ /* Exported constants --------------------------------------------------------*/ /** @defgroup PWR_Exported_Constants PWR Exported Constants * @{ */ /** @defgroup PWR_WakeUp_Pins PWR WakeUp Pins * @{ */ #define PWR_WAKEUP_PIN1 ((uint32_t)0x00000100) /** * @} */ /** @defgroup PWR_PVD_detection_level PWR PVD detection level * @{ */ #define PWR_PVDLEVEL_0 PWR_CR_PLS_LEV0 #define PWR_PVDLEVEL_1 PWR_CR_PLS_LEV1 #define PWR_PVDLEVEL_2 PWR_CR_PLS_LEV2 #define PWR_PVDLEVEL_3 PWR_CR_PLS_LEV3 #define PWR_PVDLEVEL_4 PWR_CR_PLS_LEV4 #define PWR_PVDLEVEL_5 PWR_CR_PLS_LEV5 #define PWR_PVDLEVEL_6 PWR_CR_PLS_LEV6 #define PWR_PVDLEVEL_7 PWR_CR_PLS_LEV7/* External input analog voltage (Compare internally to VREFINT) */ /** * @} */ /** @defgroup PWR_PVD_Mode PWR PVD Mode * @{ */ #define PWR_PVD_MODE_NORMAL ((uint32_t)0x00000000) /*!< basic mode is used */ #define PWR_PVD_MODE_IT_RISING ((uint32_t)0x00010001) /*!< External Interrupt Mode with Rising edge trigger detection */ #define PWR_PVD_MODE_IT_FALLING ((uint32_t)0x00010002) /*!< External Interrupt Mode with Falling edge trigger detection */ #define PWR_PVD_MODE_IT_RISING_FALLING ((uint32_t)0x00010003) /*!< External Interrupt Mode with Rising/Falling edge trigger detection */ #define PWR_PVD_MODE_EVENT_RISING ((uint32_t)0x00020001) /*!< Event Mode with Rising edge trigger detection */ #define PWR_PVD_MODE_EVENT_FALLING ((uint32_t)0x00020002) /*!< Event Mode with Falling edge trigger detection */ #define PWR_PVD_MODE_EVENT_RISING_FALLING ((uint32_t)0x00020003) /*!< Event Mode with Rising/Falling edge trigger detection */ /** * @} */ /** @defgroup PWR_Regulator_state_in_STOP_mode PWR Regulator state in SLEEP/STOP mode * @{ */ #define PWR_MAINREGULATOR_ON ((uint32_t)0x00000000) #define PWR_LOWPOWERREGULATOR_ON PWR_CR_LPDS /** * @} */ /** @defgroup PWR_SLEEP_mode_entry PWR SLEEP mode entry * @{ */ #define PWR_SLEEPENTRY_WFI ((uint8_t)0x01) #define PWR_SLEEPENTRY_WFE ((uint8_t)0x02) /** * @} */ /** @defgroup PWR_STOP_mode_entry PWR STOP mode entry * @{ */ #define PWR_STOPENTRY_WFI ((uint8_t)0x01) #define PWR_STOPENTRY_WFE ((uint8_t)0x02) /** * @} */ /** @defgroup PWR_Flag PWR Flag * @{ */ #define PWR_FLAG_WU PWR_CSR_WUF #define PWR_FLAG_SB PWR_CSR_SBF #define PWR_FLAG_PVDO PWR_CSR_PVDO #define PWR_FLAG_BRR PWR_CSR_BRR #define PWR_FLAG_VOSRDY PWR_CSR_VOSRDY /** * @} */ /** * @} */ /* Exported macro ------------------------------------------------------------*/ /** @defgroup PWR_Exported_Macro PWR Exported Macro * @{ */ /** @brief Check PWR flag is set or not. * @param __FLAG__: specifies the flag to check. * This parameter can be one of the following values: * @arg PWR_FLAG_WU: Wake Up flag. This flag indicates that a wakeup event * was received from the WKUP pin or from the RTC alarm (Alarm A * or Alarm B), RTC Tamper event, RTC TimeStamp event or RTC Wakeup. * An additional wakeup event is detected if the WKUP pin is enabled * (by setting the EWUP bit) when the WKUP pin level is already high. * @arg PWR_FLAG_SB: StandBy flag. This flag indicates that the system was * resumed from StandBy mode. * @arg PWR_FLAG_PVDO: PVD Output. This flag is valid only if PVD is enabled * by the HAL_PWR_EnablePVD() function. The PVD is stopped by Standby mode * For this reason, this bit is equal to 0 after Standby or reset * until the PVDE bit is set. * @arg PWR_FLAG_BRR: Backup regulator ready flag. This bit is not reset * when the device wakes up from Standby mode or by a system reset * or power reset. * @arg PWR_FLAG_VOSRDY: This flag indicates that the Regulator voltage * scaling output selection is ready. * @retval The new state of __FLAG__ (TRUE or FALSE). */ #define __HAL_PWR_GET_FLAG(__FLAG__) ((PWR->CSR & (__FLAG__)) == (__FLAG__)) /** @brief Clear the PWR's pending flags. * @param __FLAG__: specifies the flag to clear. * This parameter can be one of the following values: * @arg PWR_FLAG_WU: Wake Up flag * @arg PWR_FLAG_SB: StandBy flag */ #define __HAL_PWR_CLEAR_FLAG(__FLAG__) (PWR->CR |= (__FLAG__) << 2) /** * @brief Enable the PVD Exti Line 16. * @retval None. */ #define __HAL_PWR_PVD_EXTI_ENABLE_IT() (EXTI->IMR |= (PWR_EXTI_LINE_PVD)) /** * @brief Disable the PVD EXTI Line 16. * @retval None. */ #define __HAL_PWR_PVD_EXTI_DISABLE_IT() (EXTI->IMR &= ~(PWR_EXTI_LINE_PVD)) /** * @brief Enable event on PVD Exti Line 16. * @retval None. */ #define __HAL_PWR_PVD_EXTI_ENABLE_EVENT() (EXTI->EMR |= (PWR_EXTI_LINE_PVD)) /** * @brief Disable event on PVD Exti Line 16. * @retval None. */ #define __HAL_PWR_PVD_EXTI_DISABLE_EVENT() (EXTI->EMR &= ~(PWR_EXTI_LINE_PVD)) /** * @brief Enable the PVD Extended Interrupt Rising Trigger. * @retval None. */ #define __HAL_PWR_PVD_EXTI_ENABLE_RISING_EDGE() SET_BIT(EXTI->RTSR, PWR_EXTI_LINE_PVD) /** * @brief Disable the PVD Extended Interrupt Rising Trigger. * @retval None. */ #define __HAL_PWR_PVD_EXTI_DISABLE_RISING_EDGE() CLEAR_BIT(EXTI->RTSR, PWR_EXTI_LINE_PVD) /** * @brief Enable the PVD Extended Interrupt Falling Trigger. * @retval None. */ #define __HAL_PWR_PVD_EXTI_ENABLE_FALLING_EDGE() SET_BIT(EXTI->FTSR, PWR_EXTI_LINE_PVD) /** * @brief Disable the PVD Extended Interrupt Falling Trigger. * @retval None. */ #define __HAL_PWR_PVD_EXTI_DISABLE_FALLING_EDGE() CLEAR_BIT(EXTI->FTSR, PWR_EXTI_LINE_PVD) /** * @brief PVD EXTI line configuration: set rising & falling edge trigger. * @retval None. */ #define __HAL_PWR_PVD_EXTI_ENABLE_RISING_FALLING_EDGE() __HAL_PWR_PVD_EXTI_ENABLE_RISING_EDGE();__HAL_PWR_PVD_EXTI_ENABLE_FALLING_EDGE(); /** * @brief Disable the PVD Extended Interrupt Rising & Falling Trigger. * This parameter can be: * @retval None. */ #define __HAL_PWR_PVD_EXTI_DISABLE_RISING_FALLING_EDGE() __HAL_PWR_PVD_EXTI_DISABLE_RISING_EDGE();__HAL_PWR_PVD_EXTI_DISABLE_FALLING_EDGE(); /** * @brief checks whether the specified PVD Exti interrupt flag is set or not. * @retval EXTI PVD Line Status. */ #define __HAL_PWR_PVD_EXTI_GET_FLAG() (EXTI->PR & (PWR_EXTI_LINE_PVD)) /** * @brief Clear the PVD Exti flag. * @retval None. */ #define __HAL_PWR_PVD_EXTI_CLEAR_FLAG() (EXTI->PR = (PWR_EXTI_LINE_PVD)) /** * @brief Generates a Software interrupt on PVD EXTI line. * @retval None */ #define __HAL_PWR_PVD_EXTI_GENERATE_SWIT() (EXTI->SWIER |= (PWR_EXTI_LINE_PVD)) /** * @} */ /* Include PWR HAL Extension module */ #include "stm32f4xx_hal_pwr_ex.h" /* Exported functions --------------------------------------------------------*/ /** @addtogroup PWR_Exported_Functions PWR Exported Functions * @{ */ /** @addtogroup PWR_Exported_Functions_Group1 Initialization and de-initialization functions * @{ */ /* Initialization and de-initialization functions *****************************/ void HAL_PWR_DeInit(void); void HAL_PWR_EnableBkUpAccess(void); void HAL_PWR_DisableBkUpAccess(void); /** * @} */ /** @addtogroup PWR_Exported_Functions_Group2 Peripheral Control functions * @{ */ /* Peripheral Control functions **********************************************/ /* PVD configuration */ void HAL_PWR_ConfigPVD(PWR_PVDTypeDef *sConfigPVD); void HAL_PWR_EnablePVD(void); void HAL_PWR_DisablePVD(void); /* WakeUp pins configuration */ void HAL_PWR_EnableWakeUpPin(uint32_t WakeUpPinx); void HAL_PWR_DisableWakeUpPin(uint32_t WakeUpPinx); /* Low Power modes entry */ void HAL_PWR_EnterSTOPMode(uint32_t Regulator, uint8_t STOPEntry); void HAL_PWR_EnterSLEEPMode(uint32_t Regulator, uint8_t SLEEPEntry); void HAL_PWR_EnterSTANDBYMode(void); /* Power PVD IRQ Handler */ void HAL_PWR_PVD_IRQHandler(void); void HAL_PWR_PVDCallback(void); /* Cortex System Control functions *******************************************/ void HAL_PWR_EnableSleepOnExit(void); void HAL_PWR_DisableSleepOnExit(void); void HAL_PWR_EnableSEVOnPend(void); void HAL_PWR_DisableSEVOnPend(void); /** * @} */ /** * @} */ /* Private types -------------------------------------------------------------*/ /* Private variables ---------------------------------------------------------*/ /* Private constants ---------------------------------------------------------*/ /** @defgroup PWR_Private_Constants PWR Private Constants * @{ */ /** @defgroup PWR_PVD_EXTI_Line PWR PVD EXTI Line * @{ */ #define PWR_EXTI_LINE_PVD ((uint32_t)EXTI_IMR_MR16) /*!< External interrupt line 16 Connected to the PVD EXTI Line */ /** * @} */ /** @defgroup PWR_register_alias_address PWR Register alias address * @{ */ /* ------------- PWR registers bit address in the alias region ---------------*/ #define PWR_OFFSET (PWR_BASE - PERIPH_BASE) #define PWR_CR_OFFSET 0x00 #define PWR_CSR_OFFSET 0x04 #define PWR_CR_OFFSET_BB (PWR_OFFSET + PWR_CR_OFFSET) #define PWR_CSR_OFFSET_BB (PWR_OFFSET + PWR_CSR_OFFSET) /** * @} */ /** @defgroup PWR_CR_register_alias PWR CR Register alias address * @{ */ /* --- CR Register ---*/ /* Alias word address of DBP bit */ #define DBP_BIT_NUMBER POSITION_VAL(PWR_CR_DBP) #define CR_DBP_BB (uint32_t)(PERIPH_BB_BASE + (PWR_CR_OFFSET_BB * 32) + (DBP_BIT_NUMBER * 4)) /* Alias word address of PVDE bit */ #define PVDE_BIT_NUMBER POSITION_VAL(PWR_CR_PVDE) #define CR_PVDE_BB (uint32_t)(PERIPH_BB_BASE + (PWR_CR_OFFSET_BB * 32) + (PVDE_BIT_NUMBER * 4)) /* Alias word address of PMODE bit */ #define PMODE_BIT_NUMBER POSITION_VAL(PWR_CR_PMODE) #define CR_PMODE_BB (uint32_t)(PERIPH_BB_BASE + (PWR_CR_OFFSET_BB * 32) + (PMODE_BIT_NUMBER * 4)) /** * @} */ /** @defgroup PWR_CSR_register_alias PWR CSR Register alias address * @{ */ /* --- CSR Register ---*/ /* Alias word address of EWUP bit */ #define EWUP_BIT_NUMBER POSITION_VAL(PWR_CSR_EWUP) #define CSR_EWUP_BB (PERIPH_BB_BASE + (PWR_CSR_OFFSET_BB * 32) + (EWUP_BIT_NUMBER * 4)) /** * @} */ /** * @} */ /* Private macros ------------------------------------------------------------*/ /** @defgroup PWR_Private_Macros PWR Private Macros * @{ */ /** @defgroup PWR_IS_PWR_Definitions PWR Private macros to check input parameters * @{ */ #define IS_PWR_PVD_LEVEL(LEVEL) (((LEVEL) == PWR_PVDLEVEL_0) || ((LEVEL) == PWR_PVDLEVEL_1)|| \ ((LEVEL) == PWR_PVDLEVEL_2) || ((LEVEL) == PWR_PVDLEVEL_3)|| \ ((LEVEL) == PWR_PVDLEVEL_4) || ((LEVEL) == PWR_PVDLEVEL_5)|| \ ((LEVEL) == PWR_PVDLEVEL_6) || ((LEVEL) == PWR_PVDLEVEL_7)) #define IS_PWR_PVD_MODE(MODE) (((MODE) == PWR_PVD_MODE_IT_RISING)|| ((MODE) == PWR_PVD_MODE_IT_FALLING) || \ ((MODE) == PWR_PVD_MODE_IT_RISING_FALLING) || ((MODE) == PWR_PVD_MODE_EVENT_RISING) || \ ((MODE) == PWR_PVD_MODE_EVENT_FALLING) || ((MODE) == PWR_PVD_MODE_EVENT_RISING_FALLING) || \ ((MODE) == PWR_PVD_MODE_NORMAL)) #define IS_PWR_REGULATOR(REGULATOR) (((REGULATOR) == PWR_MAINREGULATOR_ON) || \ ((REGULATOR) == PWR_LOWPOWERREGULATOR_ON)) #define IS_PWR_SLEEP_ENTRY(ENTRY) (((ENTRY) == PWR_SLEEPENTRY_WFI) || ((ENTRY) == PWR_SLEEPENTRY_WFE)) #define IS_PWR_STOP_ENTRY(ENTRY) (((ENTRY) == PWR_STOPENTRY_WFI) || ((ENTRY) == PWR_STOPENTRY_WFE)) /** * @} */ /** * @} */ /** * @} */ /** * @} */ #ifdef __cplusplus } #endif #endif /* __STM32F4xx_HAL_PWR_H */ /************************ (C) COPYRIGHT STMicroelectronics *****END OF FILE****/ ================================================ FILE: Zelig/mbed/TARGET_NUCLEO_F411RE/stm32f4xx_hal_pwr_ex.h ================================================ /** ****************************************************************************** * @file stm32f4xx_hal_pwr_ex.h * @author MCD Application Team * @version V1.4.1 * @date 09-October-2015 * @brief Header file of PWR HAL Extension module. ****************************************************************************** * @attention * *

© COPYRIGHT(c) 2015 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. * ****************************************************************************** */ /* Define to prevent recursive inclusion -------------------------------------*/ #ifndef __STM32F4xx_HAL_PWR_EX_H #define __STM32F4xx_HAL_PWR_EX_H #ifdef __cplusplus extern "C" { #endif /* Includes ------------------------------------------------------------------*/ #include "stm32f4xx_hal_def.h" /** @addtogroup STM32F4xx_HAL_Driver * @{ */ /** @addtogroup PWREx * @{ */ /* Exported types ------------------------------------------------------------*/ /* Exported constants --------------------------------------------------------*/ /** @defgroup PWREx_Exported_Constants PWREx Exported Constants * @{ */ #if defined(STM32F427xx) || defined(STM32F437xx) || defined(STM32F429xx) || defined(STM32F439xx) ||\ defined(STM32F446xx) || defined(STM32F469xx) || defined(STM32F479xx) /** @defgroup PWREx_Regulator_state_in_UnderDrive_mode PWREx Regulator state in UnderDrive mode * @{ */ #define PWR_MAINREGULATOR_UNDERDRIVE_ON PWR_CR_MRUDS #define PWR_LOWPOWERREGULATOR_UNDERDRIVE_ON ((uint32_t)(PWR_CR_LPDS | PWR_CR_LPUDS)) /** * @} */ /** @defgroup PWREx_Over_Under_Drive_Flag PWREx Over Under Drive Flag * @{ */ #define PWR_FLAG_ODRDY PWR_CSR_ODRDY #define PWR_FLAG_ODSWRDY PWR_CSR_ODSWRDY #define PWR_FLAG_UDRDY PWR_CSR_UDSWRDY /** * @} */ #endif /* STM32F427xx || STM32F437xx || STM32F429xx || STM32F439xx || STM32F446xx || STM32F469xx || STM32F479xx */ /** @defgroup PWREx_Regulator_Voltage_Scale PWREx Regulator Voltage Scale * @{ */ #if defined(STM32F405xx) || defined(STM32F407xx) || defined(STM32F415xx) || defined(STM32F417xx) #define PWR_REGULATOR_VOLTAGE_SCALE1 PWR_CR_VOS /* Scale 1 mode(default value at reset): the maximum value of fHCLK = 168 MHz. */ #define PWR_REGULATOR_VOLTAGE_SCALE2 ((uint32_t)0x00000000) /* Scale 2 mode: the maximum value of fHCLK = 144 MHz. */ #else #define PWR_REGULATOR_VOLTAGE_SCALE1 PWR_CR_VOS /* Scale 1 mode(default value at reset): the maximum value of fHCLK is 168 MHz. It can be extended to 180 MHz by activating the over-drive mode. */ #define PWR_REGULATOR_VOLTAGE_SCALE2 PWR_CR_VOS_1 /* Scale 2 mode: the maximum value of fHCLK is 144 MHz. It can be extended to 168 MHz by activating the over-drive mode. */ #define PWR_REGULATOR_VOLTAGE_SCALE3 PWR_CR_VOS_0 /* Scale 3 mode: the maximum value of fHCLK is 120 MHz. */ #endif /* STM32F405xx || STM32F407xx || STM32F415xx || STM32F417xx */ /** * @} */ #if defined(STM32F410Tx) || defined(STM32F410Cx) || defined(STM32F410Rx) || defined(STM32F446xx) /** @defgroup PWREx_WakeUp_Pins PWREx WakeUp Pins * @{ */ #define PWR_WAKEUP_PIN2 ((uint32_t)0x00000080) #if defined(STM32F410Tx) || defined(STM32F410Cx) || defined(STM32F410Rx) #define PWR_WAKEUP_PIN3 ((uint32_t)0x00000040) #endif /* STM32F410xx */ /** * @} */ #endif /* STM32F410xx || STM32F446xx */ /** * @} */ /* Exported macro ------------------------------------------------------------*/ /** @defgroup PWREx_Exported_Constants PWREx Exported Constants * @{ */ #if defined(STM32F405xx) || defined(STM32F407xx) || defined(STM32F415xx) || defined(STM32F417xx) /** @brief macros configure the main internal regulator output voltage. * @param __REGULATOR__: specifies the regulator output voltage to achieve * a tradeoff between performance and power consumption when the device does * not operate at the maximum frequency (refer to the datasheets for more details). * This parameter can be one of the following values: * @arg PWR_REGULATOR_VOLTAGE_SCALE1: Regulator voltage output Scale 1 mode * @arg PWR_REGULATOR_VOLTAGE_SCALE2: Regulator voltage output Scale 2 mode * @retval None */ #define __HAL_PWR_VOLTAGESCALING_CONFIG(__REGULATOR__) do { \ __IO uint32_t tmpreg; \ MODIFY_REG(PWR->CR, PWR_CR_VOS, (__REGULATOR__)); \ /* Delay after an RCC peripheral clock enabling */ \ tmpreg = READ_BIT(PWR->CR, PWR_CR_VOS); \ UNUSED(tmpreg); \ } while(0) #else /** @brief macros configure the main internal regulator output voltage. * @param __REGULATOR__: specifies the regulator output voltage to achieve * a tradeoff between performance and power consumption when the device does * not operate at the maximum frequency (refer to the datasheets for more details). * This parameter can be one of the following values: * @arg PWR_REGULATOR_VOLTAGE_SCALE1: Regulator voltage output Scale 1 mode * @arg PWR_REGULATOR_VOLTAGE_SCALE2: Regulator voltage output Scale 2 mode * @arg PWR_REGULATOR_VOLTAGE_SCALE3: Regulator voltage output Scale 3 mode * @retval None */ #define __HAL_PWR_VOLTAGESCALING_CONFIG(__REGULATOR__) do { \ __IO uint32_t tmpreg; \ MODIFY_REG(PWR->CR, PWR_CR_VOS, (__REGULATOR__)); \ /* Delay after an RCC peripheral clock enabling */ \ tmpreg = READ_BIT(PWR->CR, PWR_CR_VOS); \ UNUSED(tmpreg); \ } while(0) #endif /* STM32F405xx || STM32F407xx || STM32F415xx || STM32F417xx */ #if defined(STM32F427xx) || defined(STM32F437xx) || defined(STM32F429xx) || defined(STM32F439xx) ||\ defined(STM32F446xx) || defined(STM32F469xx) || defined(STM32F479xx) /** @brief Macros to enable or disable the Over drive mode. * @note These macros can be used only for STM32F42xx/STM3243xx devices. */ #define __HAL_PWR_OVERDRIVE_ENABLE() (*(__IO uint32_t *) CR_ODEN_BB = ENABLE) #define __HAL_PWR_OVERDRIVE_DISABLE() (*(__IO uint32_t *) CR_ODEN_BB = DISABLE) /** @brief Macros to enable or disable the Over drive switching. * @note These macros can be used only for STM32F42xx/STM3243xx devices. */ #define __HAL_PWR_OVERDRIVESWITCHING_ENABLE() (*(__IO uint32_t *) CR_ODSWEN_BB = ENABLE) #define __HAL_PWR_OVERDRIVESWITCHING_DISABLE() (*(__IO uint32_t *) CR_ODSWEN_BB = DISABLE) /** @brief Macros to enable or disable the Under drive mode. * @note This mode is enabled only with STOP low power mode. * In this mode, the 1.2V domain is preserved in reduced leakage mode. This * mode is only available when the main regulator or the low power regulator * is in low voltage mode. * @note If the Under-drive mode was enabled, it is automatically disabled after * exiting Stop mode. * When the voltage regulator operates in Under-drive mode, an additional * startup delay is induced when waking up from Stop mode. */ #define __HAL_PWR_UNDERDRIVE_ENABLE() (PWR->CR |= (uint32_t)PWR_CR_UDEN) #define __HAL_PWR_UNDERDRIVE_DISABLE() (PWR->CR &= (uint32_t)(~PWR_CR_UDEN)) /** @brief Check PWR flag is set or not. * @note These macros can be used only for STM32F42xx/STM3243xx devices. * @param __FLAG__: specifies the flag to check. * This parameter can be one of the following values: * @arg PWR_FLAG_ODRDY: This flag indicates that the Over-drive mode * is ready * @arg PWR_FLAG_ODSWRDY: This flag indicates that the Over-drive mode * switching is ready * @arg PWR_FLAG_UDRDY: This flag indicates that the Under-drive mode * is enabled in Stop mode * @retval The new state of __FLAG__ (TRUE or FALSE). */ #define __HAL_PWR_GET_ODRUDR_FLAG(__FLAG__) ((PWR->CSR & (__FLAG__)) == (__FLAG__)) /** @brief Clear the Under-Drive Ready flag. * @note These macros can be used only for STM32F42xx/STM3243xx devices. */ #define __HAL_PWR_CLEAR_ODRUDR_FLAG() (PWR->CSR |= PWR_FLAG_UDRDY) #endif /* STM32F427xx || STM32F437xx || STM32F429xx || STM32F439xx || STM32F446xx || STM32F469xx || STM32F479xx */ /** * @} */ /* Exported functions --------------------------------------------------------*/ /** @addtogroup PWREx_Exported_Functions PWREx Exported Functions * @{ */ /** @addtogroup PWREx_Exported_Functions_Group1 * @{ */ void HAL_PWREx_EnableFlashPowerDown(void); void HAL_PWREx_DisableFlashPowerDown(void); HAL_StatusTypeDef HAL_PWREx_EnableBkUpReg(void); HAL_StatusTypeDef HAL_PWREx_DisableBkUpReg(void); uint32_t HAL_PWREx_GetVoltageRange(void); HAL_StatusTypeDef HAL_PWREx_ControlVoltageScaling(uint32_t VoltageScaling); #if defined(STM32F469xx) || defined(STM32F479xx) void HAL_PWREx_EnableWakeUpPinPolarityRisingEdge(void); void HAL_PWREx_EnableWakeUpPinPolarityFallingEdge(void); #endif /* STM32F469xx || STM32F479xx */ #if defined(STM32F410Tx) || defined(STM32F410Cx) || defined(STM32F410Rx) || defined(STM32F401xC) ||\ defined(STM32F401xE) || defined(STM32F411xE) void HAL_PWREx_EnableMainRegulatorLowVoltage(void); void HAL_PWREx_DisableMainRegulatorLowVoltage(void); void HAL_PWREx_EnableLowRegulatorLowVoltage(void); void HAL_PWREx_DisableLowRegulatorLowVoltage(void); #endif /* STM32F410xx || STM32F401xC || STM32F401xE || STM32F411xE */ #if defined(STM32F427xx) || defined(STM32F437xx) || defined(STM32F429xx) || defined(STM32F439xx) || defined(STM32F446xx) ||\ defined(STM32F469xx) || defined(STM32F479xx) HAL_StatusTypeDef HAL_PWREx_EnableOverDrive(void); HAL_StatusTypeDef HAL_PWREx_DisableOverDrive(void); HAL_StatusTypeDef HAL_PWREx_EnterUnderDriveSTOPMode(uint32_t Regulator, uint8_t STOPEntry); #endif /* STM32F427xx || STM32F437xx || STM32F429xx || STM32F439xx || STM32F446xx || STM32F469xx || STM32F479xx */ /** * @} */ /** * @} */ /* Private types -------------------------------------------------------------*/ /* Private variables ---------------------------------------------------------*/ /* Private constants ---------------------------------------------------------*/ /** @defgroup PWREx_Private_Constants PWREx Private Constants * @{ */ /** @defgroup PWREx_register_alias_address PWREx Register alias address * @{ */ /* ------------- PWR registers bit address in the alias region ---------------*/ /* --- CR Register ---*/ /* Alias word address of FPDS bit */ #define FPDS_BIT_NUMBER POSITION_VAL(PWR_CR_FPDS) #define CR_FPDS_BB (uint32_t)(PERIPH_BB_BASE + (PWR_CR_OFFSET_BB * 32) + (FPDS_BIT_NUMBER * 4)) /* Alias word address of ODEN bit */ #define ODEN_BIT_NUMBER POSITION_VAL(PWR_CR_ODEN) #define CR_ODEN_BB (uint32_t)(PERIPH_BB_BASE + (PWR_CR_OFFSET_BB * 32) + (ODEN_BIT_NUMBER * 4)) /* Alias word address of ODSWEN bit */ #define ODSWEN_BIT_NUMBER POSITION_VAL(PWR_CR_ODSWEN) #define CR_ODSWEN_BB (uint32_t)(PERIPH_BB_BASE + (PWR_CR_OFFSET_BB * 32) + (ODSWEN_BIT_NUMBER * 4)) /* Alias word address of MRLVDS bit */ #define MRLVDS_BIT_NUMBER POSITION_VAL(PWR_CR_MRLVDS) #define CR_MRLVDS_BB (uint32_t)(PERIPH_BB_BASE + (PWR_CR_OFFSET_BB * 32) + (MRLVDS_BIT_NUMBER * 4)) /* Alias word address of LPLVDS bit */ #define LPLVDS_BIT_NUMBER POSITION_VAL(PWR_CR_LPLVDS) #define CR_LPLVDS_BB (uint32_t)(PERIPH_BB_BASE + (PWR_CR_OFFSET_BB * 32) + (LPLVDS_BIT_NUMBER * 4)) /** * @} */ /** @defgroup PWREx_CSR_register_alias PWRx CSR Register alias address * @{ */ /* --- CSR Register ---*/ /* Alias word address of BRE bit */ #define BRE_BIT_NUMBER POSITION_VAL(PWR_CSR_BRE) #define CSR_BRE_BB (uint32_t)(PERIPH_BB_BASE + (PWR_CSR_OFFSET_BB * 32) + (BRE_BIT_NUMBER * 4)) #if defined(STM32F469xx) || defined(STM32F479xx) /* Alias word address of WUPP bit */ #define WUPP_BIT_NUMBER POSITION_VAL(PWR_CSR_WUPP) #define CSR_WUPP_BB (PERIPH_BB_BASE + (PWR_CSR_OFFSET_BB * 32) + (WUPP_BIT_NUMBER * 4)) #endif /* STM32F469xx || STM32F479xx */ /** * @} */ /** * @} */ /* Private macros ------------------------------------------------------------*/ /** @defgroup PWREx_Private_Macros PWREx Private Macros * @{ */ /** @defgroup PWREx_IS_PWR_Definitions PWREx Private macros to check input parameters * @{ */ #if defined(STM32F427xx) || defined(STM32F437xx) || defined(STM32F429xx) || defined(STM32F439xx) ||\ defined(STM32F446xx) || defined(STM32F469xx) || defined(STM32F479xx) #define IS_PWR_REGULATOR_UNDERDRIVE(REGULATOR) (((REGULATOR) == PWR_MAINREGULATOR_UNDERDRIVE_ON) || \ ((REGULATOR) == PWR_LOWPOWERREGULATOR_UNDERDRIVE_ON)) #endif /* STM32F427xx || STM32F437xx || STM32F429xx || STM32F439xx || STM32F446xx || STM32F469xx || STM32F479xx */ #if defined(STM32F405xx) || defined(STM32F407xx) || defined(STM32F415xx) || defined(STM32F417xx) #define IS_PWR_VOLTAGE_SCALING_RANGE(VOLTAGE) (((VOLTAGE) == PWR_REGULATOR_VOLTAGE_SCALE1) || \ ((VOLTAGE) == PWR_REGULATOR_VOLTAGE_SCALE2)) #else #define IS_PWR_VOLTAGE_SCALING_RANGE(VOLTAGE) (((VOLTAGE) == PWR_REGULATOR_VOLTAGE_SCALE1) || \ ((VOLTAGE) == PWR_REGULATOR_VOLTAGE_SCALE2) || \ ((VOLTAGE) == PWR_REGULATOR_VOLTAGE_SCALE3)) #endif /* STM32F405xx || STM32F407xx || STM32F415xx || STM32F417xx */ #if defined(STM32F446xx) #define IS_PWR_WAKEUP_PIN(PIN) (((PIN) == PWR_WAKEUP_PIN1) || ((PIN) == PWR_WAKEUP_PIN2)) #elif defined(STM32F410Tx) || defined(STM32F410Cx) || defined(STM32F410Rx) #define IS_PWR_WAKEUP_PIN(PIN) (((PIN) == PWR_WAKEUP_PIN1) || ((PIN) == PWR_WAKEUP_PIN2) || \ ((PIN) == PWR_WAKEUP_PIN3)) #else #define IS_PWR_WAKEUP_PIN(PIN) ((PIN) == PWR_WAKEUP_PIN1) #endif /* STM32F446xx */ /** * @} */ /** * @} */ /** * @} */ /** * @} */ #ifdef __cplusplus } #endif #endif /* __STM32F4xx_HAL_PWR_EX_H */ /************************ (C) COPYRIGHT STMicroelectronics *****END OF FILE****/ ================================================ FILE: Zelig/mbed/TARGET_NUCLEO_F411RE/stm32f4xx_hal_qspi.h ================================================ /** ****************************************************************************** * @file stm32f4xx_hal_qspi.h * @author MCD Application Team * @version V1.4.1 * @date 09-October-2015 * @brief Header file of QSPI HAL module. ****************************************************************************** * @attention * *

© COPYRIGHT(c) 2015 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. * ****************************************************************************** */ /* Define to prevent recursive inclusion -------------------------------------*/ #ifndef __STM32F4xx_HAL_QSPI_H #define __STM32F4xx_HAL_QSPI_H #ifdef __cplusplus extern "C" { #endif #if defined(STM32F446xx) || defined(STM32F469xx) || defined(STM32F479xx) /* Includes ------------------------------------------------------------------*/ #include "stm32f4xx_hal_def.h" /** @addtogroup STM32F4xx_HAL_Driver * @{ */ /** @addtogroup QSPI * @{ */ /* Exported types ------------------------------------------------------------*/ /** @defgroup QSPI_Exported_Types QSPI Exported Types * @{ */ /** * @brief QSPI Init structure definition */ typedef struct { uint32_t ClockPrescaler; /* Specifies the prescaler factor for generating clock based on the AHB clock. This parameter can be a number between 0 and 255 */ uint32_t FifoThreshold; /* Specifies the threshold number of bytes in the FIFO (used only in indirect mode) This parameter can be a value between 1 and 32 */ uint32_t SampleShifting; /* Specifies the Sample Shift. The data is sampled 1/2 clock cycle delay later to take in account external signal delays. (It should be QSPI_SAMPLE_SHIFTING_NONE in DDR mode) This parameter can be a value of @ref QSPI_SampleShifting */ uint32_t FlashSize; /* Specifies the Flash Size. FlashSize+1 is effectively the number of address bits required to address the flash memory. The flash capacity can be up to 4GB (addressed using 32 bits) in indirect mode, but the addressable space in memory-mapped mode is limited to 256MB This parameter can be a number between 0 and 31 */ uint32_t ChipSelectHighTime; /* Specifies the Chip Select High Time. ChipSelectHighTime+1 defines the minimum number of clock cycles which the chip select must remain high between commands. This parameter can be a value of @ref QSPI_ChipSelectHighTime */ uint32_t ClockMode; /* Specifies the Clock Mode. It indicates the level that clock takes between commands. This parameter can be a value of @ref QSPI_ClockMode */ uint32_t FlashID; /* Specifies the Flash which will be used, This parameter can be a value of @ref QSPI_Flash_Select */ uint32_t DualFlash; /* Specifies the Dual Flash Mode State This parameter can be a value of @ref QSPI_DualFlash_Mode */ }QSPI_InitTypeDef; /** * @brief HAL QSPI State structures definition */ typedef enum { HAL_QSPI_STATE_RESET = 0x00, /*!< Peripheral not initialized */ HAL_QSPI_STATE_READY = 0x01, /*!< Peripheral initialized and ready for use */ HAL_QSPI_STATE_BUSY = 0x02, /*!< Peripheral in indirect mode and busy */ HAL_QSPI_STATE_BUSY_INDIRECT_TX = 0x12, /*!< Peripheral in indirect mode with transmission ongoing */ HAL_QSPI_STATE_BUSY_INDIRECT_RX = 0x22, /*!< Peripheral in indirect mode with reception ongoing */ HAL_QSPI_STATE_BUSY_AUTO_POLLING = 0x42, /*!< Peripheral in auto polling mode ongoing */ HAL_QSPI_STATE_BUSY_MEM_MAPPED = 0x82, /*!< Peripheral in memory mapped mode ongoing */ HAL_QSPI_STATE_ERROR = 0x04 /*!< Peripheral in error */ }HAL_QSPI_StateTypeDef; /** * @brief QSPI Handle Structure definition */ typedef struct { QUADSPI_TypeDef *Instance; /* QSPI registers base address */ QSPI_InitTypeDef Init; /* QSPI communication parameters */ uint8_t *pTxBuffPtr; /* Pointer to QSPI Tx transfer Buffer */ __IO uint16_t TxXferSize; /* QSPI Tx Transfer size */ __IO uint16_t TxXferCount; /* QSPI Tx Transfer Counter */ uint8_t *pRxBuffPtr; /* Pointer to QSPI Rx transfer Buffer */ __IO uint16_t RxXferSize; /* QSPI Rx Transfer size */ __IO uint16_t RxXferCount; /* QSPI Rx Transfer Counter */ DMA_HandleTypeDef *hdma; /* QSPI Rx/Tx DMA Handle parameters */ __IO HAL_LockTypeDef Lock; /* Locking object */ __IO HAL_QSPI_StateTypeDef State; /* QSPI communication state */ __IO uint32_t ErrorCode; /* QSPI Error code */ uint32_t Timeout; /* Timeout for the QSPI memory access */ }QSPI_HandleTypeDef; /** * @brief QSPI Command structure definition */ typedef struct { uint32_t Instruction; /* Specifies the Instruction to be sent This parameter can be a value (8-bit) between 0x00 and 0xFF */ uint32_t Address; /* Specifies the Address to be sent (Size from 1 to 4 bytes according AddressSize) This parameter can be a value (32-bits) between 0x0 and 0xFFFFFFFF */ uint32_t AlternateBytes; /* Specifies the Alternate Bytes to be sent (Size from 1 to 4 bytes according AlternateBytesSize) This parameter can be a value (32-bits) between 0x0 and 0xFFFFFFFF */ uint32_t AddressSize; /* Specifies the Address Size This parameter can be a value of @ref QSPI_AddressSize */ uint32_t AlternateBytesSize; /* Specifies the Alternate Bytes Size This parameter can be a value of @ref QSPI_AlternateBytesSize */ uint32_t DummyCycles; /* Specifies the Number of Dummy Cycles. This parameter can be a number between 0 and 31 */ uint32_t InstructionMode; /* Specifies the Instruction Mode This parameter can be a value of @ref QSPI_InstructionMode */ uint32_t AddressMode; /* Specifies the Address Mode This parameter can be a value of @ref QSPI_AddressMode */ uint32_t AlternateByteMode; /* Specifies the Alternate Bytes Mode This parameter can be a value of @ref QSPI_AlternateBytesMode */ uint32_t DataMode; /* Specifies the Data Mode (used for dummy cycles and data phases) This parameter can be a value of @ref QSPI_DataMode */ uint32_t NbData; /* Specifies the number of data to transfer. This parameter can be any value between 0 and 0xFFFFFFFF (0 means undefined length until end of memory)*/ uint32_t DdrMode; /* Specifies the double data rate mode for address, alternate byte and data phase This parameter can be a value of @ref QSPI_DdrMode */ uint32_t DdrHoldHalfCycle; /* Specifies the DDR hold half cycle. It delays the data output by one half of system clock in DDR mode. This parameter can be a value of @ref QSPI_DdrHoldHalfCycle */ uint32_t SIOOMode; /* Specifies the send instruction only once mode This parameter can be a value of @ref QSPI_SIOOMode */ }QSPI_CommandTypeDef; /** * @brief QSPI Auto Polling mode configuration structure definition */ typedef struct { uint32_t Match; /* Specifies the value to be compared with the masked status register to get a match. This parameter can be any value between 0 and 0xFFFFFFFF */ uint32_t Mask; /* Specifies the mask to be applied to the status bytes received. This parameter can be any value between 0 and 0xFFFFFFFF */ uint32_t Interval; /* Specifies the number of clock cycles between two read during automatic polling phases. This parameter can be any value between 0 and 0xFFFF */ uint32_t StatusBytesSize; /* Specifies the size of the status bytes received. This parameter can be any value between 1 and 4 */ uint32_t MatchMode; /* Specifies the method used for determining a match. This parameter can be a value of @ref QSPI_MatchMode */ uint32_t AutomaticStop; /* Specifies if automatic polling is stopped after a match. This parameter can be a value of @ref QSPI_AutomaticStop */ }QSPI_AutoPollingTypeDef; /** * @brief QSPI Memory Mapped mode configuration structure definition */ typedef struct { uint32_t TimeOutPeriod; /* Specifies the number of clock to wait when the FIFO is full before to release the chip select. This parameter can be any value between 0 and 0xFFFF */ uint32_t TimeOutActivation; /* Specifies if the time out counter is enabled to release the chip select. This parameter can be a value of @ref QSPI_TimeOutActivation */ }QSPI_MemoryMappedTypeDef; /** * @} */ /* Exported constants --------------------------------------------------------*/ /** @defgroup QSPI_Exported_Constants QSPI Exported Constants * @{ */ /** @defgroup QSPI_ErrorCode QSPI Error Code * @{ */ #define HAL_QSPI_ERROR_NONE ((uint32_t)0x00000000) /*!< No error */ #define HAL_QSPI_ERROR_TIMEOUT ((uint32_t)0x00000001) /*!< Timeout error */ #define HAL_QSPI_ERROR_TRANSFER ((uint32_t)0x00000002) /*!< Transfer error */ #define HAL_QSPI_ERROR_DMA ((uint32_t)0x00000004) /*!< DMA transfer error */ /** * @} */ /** @defgroup QSPI_SampleShifting QSPI Sample Shifting * @{ */ #define QSPI_SAMPLE_SHIFTING_NONE ((uint32_t)0x00000000) /*!State = HAL_QSPI_STATE_RESET) /** @brief Enable QSPI * @param __HANDLE__: specifies the QSPI Handle. * @retval None */ #define __HAL_QSPI_ENABLE(__HANDLE__) SET_BIT((__HANDLE__)->Instance->CR, QUADSPI_CR_EN) /** @brief Disable QSPI * @param __HANDLE__: specifies the QSPI Handle. * @retval None */ #define __HAL_QSPI_DISABLE(__HANDLE__) CLEAR_BIT((__HANDLE__)->Instance->CR, QUADSPI_CR_EN) /** @brief Enables the specified QSPI interrupt. * @param __HANDLE__: specifies the QSPI Handle. * @param __INTERRUPT__: specifies the QSPI interrupt source to enable. * This parameter can be one of the following values: * @arg QSPI_IT_TO: QSPI Time out interrupt * @arg QSPI_IT_SM: QSPI Status match interrupt * @arg QSPI_IT_FT: QSPI FIFO threshold interrupt * @arg QSPI_IT_TC: QSPI Transfer complete interrupt * @arg QSPI_IT_TE: QSPI Transfer error interrupt * @retval None */ #define __HAL_QSPI_ENABLE_IT(__HANDLE__, __INTERRUPT__) SET_BIT((__HANDLE__)->Instance->CR, (__INTERRUPT__)) /** @brief Disables the specified QSPI interrupt. * @param __HANDLE__: specifies the QSPI Handle. * @param __INTERRUPT__: specifies the QSPI interrupt source to disable. * This parameter can be one of the following values: * @arg QSPI_IT_TO: QSPI Timeout interrupt * @arg QSPI_IT_SM: QSPI Status match interrupt * @arg QSPI_IT_FT: QSPI FIFO threshold interrupt * @arg QSPI_IT_TC: QSPI Transfer complete interrupt * @arg QSPI_IT_TE: QSPI Transfer error interrupt * @retval None */ #define __HAL_QSPI_DISABLE_IT(__HANDLE__, __INTERRUPT__) CLEAR_BIT((__HANDLE__)->Instance->CR, (__INTERRUPT__)) /** @brief Checks whether the specified QSPI interrupt source is enabled. * @param __HANDLE__: specifies the QSPI Handle. * @param __INTERRUPT__: specifies the QSPI interrupt source to check. * This parameter can be one of the following values: * @arg QSPI_IT_TO: QSPI Time out interrupt * @arg QSPI_IT_SM: QSPI Status match interrupt * @arg QSPI_IT_FT: QSPI FIFO threshold interrupt * @arg QSPI_IT_TC: QSPI Transfer complete interrupt * @arg QSPI_IT_TE: QSPI Transfer error interrupt * @retval The new state of __INTERRUPT__ (TRUE or FALSE). */ #define __HAL_QSPI_GET_IT_SOURCE(__HANDLE__, __INTERRUPT__) (READ_BIT((__HANDLE__)->Instance->CR, (__INTERRUPT__)) == (__INTERRUPT__)) /** * @brief Get the selected QSPI's flag status. * @param __HANDLE__: specifies the QSPI Handle. * @param __FLAG__: specifies the QSPI flag to check. * This parameter can be one of the following values: * @arg QSPI_FLAG_BUSY: QSPI Busy flag * @arg QSPI_FLAG_TO: QSPI Time out flag * @arg QSPI_FLAG_SM: QSPI Status match flag * @arg QSPI_FLAG_FT: QSPI FIFO threshold flag * @arg QSPI_FLAG_TC: QSPI Transfer complete flag * @arg QSPI_FLAG_TE: QSPI Transfer error flag * @retval None */ #define __HAL_QSPI_GET_FLAG(__HANDLE__, __FLAG__) (READ_BIT((__HANDLE__)->Instance->SR, (__FLAG__)) != 0) /** @brief Clears the specified QSPI's flag status. * @param __HANDLE__: specifies the QSPI Handle. * @param __FLAG__: specifies the QSPI clear register flag that needs to be set * This parameter can be one of the following values: * @arg QSPI_FLAG_TO: QSPI Time out flag * @arg QSPI_FLAG_SM: QSPI Status match flag * @arg QSPI_FLAG_TC: QSPI Transfer complete flag * @arg QSPI_FLAG_TE: QSPI Transfer error flag * @retval None */ #define __HAL_QSPI_CLEAR_FLAG(__HANDLE__, __FLAG__) WRITE_REG((__HANDLE__)->Instance->FCR, (__FLAG__)) /** * @} */ /* Exported functions --------------------------------------------------------*/ /** @addtogroup QSPI_Exported_Functions * @{ */ /** @addtogroup QSPI_Exported_Functions_Group1 * @{ */ /* Initialization/de-initialization functions ********************************/ HAL_StatusTypeDef HAL_QSPI_Init (QSPI_HandleTypeDef *hqspi); HAL_StatusTypeDef HAL_QSPI_DeInit (QSPI_HandleTypeDef *hqspi); void HAL_QSPI_MspInit (QSPI_HandleTypeDef *hqspi); void HAL_QSPI_MspDeInit(QSPI_HandleTypeDef *hqspi); /** * @} */ /** @addtogroup QSPI_Exported_Functions_Group2 * @{ */ /* IO operation functions *****************************************************/ /* QSPI IRQ handler method */ void HAL_QSPI_IRQHandler(QSPI_HandleTypeDef *hqspi); /* QSPI indirect mode */ HAL_StatusTypeDef HAL_QSPI_Command (QSPI_HandleTypeDef *hqspi, QSPI_CommandTypeDef *cmd, uint32_t Timeout); HAL_StatusTypeDef HAL_QSPI_Transmit (QSPI_HandleTypeDef *hqspi, uint8_t *pData, uint32_t Timeout); HAL_StatusTypeDef HAL_QSPI_Receive (QSPI_HandleTypeDef *hqspi, uint8_t *pData, uint32_t Timeout); HAL_StatusTypeDef HAL_QSPI_Command_IT (QSPI_HandleTypeDef *hqspi, QSPI_CommandTypeDef *cmd); HAL_StatusTypeDef HAL_QSPI_Transmit_IT (QSPI_HandleTypeDef *hqspi, uint8_t *pData); HAL_StatusTypeDef HAL_QSPI_Receive_IT (QSPI_HandleTypeDef *hqspi, uint8_t *pData); HAL_StatusTypeDef HAL_QSPI_Transmit_DMA (QSPI_HandleTypeDef *hqspi, uint8_t *pData); HAL_StatusTypeDef HAL_QSPI_Receive_DMA (QSPI_HandleTypeDef *hqspi, uint8_t *pData); /* QSPI status flag polling mode */ HAL_StatusTypeDef HAL_QSPI_AutoPolling (QSPI_HandleTypeDef *hqspi, QSPI_CommandTypeDef *cmd, QSPI_AutoPollingTypeDef *cfg, uint32_t Timeout); HAL_StatusTypeDef HAL_QSPI_AutoPolling_IT(QSPI_HandleTypeDef *hqspi, QSPI_CommandTypeDef *cmd, QSPI_AutoPollingTypeDef *cfg); /* QSPI memory-mapped mode */ HAL_StatusTypeDef HAL_QSPI_MemoryMapped(QSPI_HandleTypeDef *hqspi, QSPI_CommandTypeDef *cmd, QSPI_MemoryMappedTypeDef *cfg); /** * @} */ /** @addtogroup QSPI_Exported_Functions_Group3 * @{ */ /* Callback functions in non-blocking modes ***********************************/ void HAL_QSPI_ErrorCallback (QSPI_HandleTypeDef *hqspi); void HAL_QSPI_FifoThresholdCallback(QSPI_HandleTypeDef *hqspi); /* QSPI indirect mode */ void HAL_QSPI_CmdCpltCallback (QSPI_HandleTypeDef *hqspi); void HAL_QSPI_RxCpltCallback (QSPI_HandleTypeDef *hqspi); void HAL_QSPI_TxCpltCallback (QSPI_HandleTypeDef *hqspi); void HAL_QSPI_RxHalfCpltCallback (QSPI_HandleTypeDef *hqspi); void HAL_QSPI_TxHalfCpltCallback (QSPI_HandleTypeDef *hqspi); /* QSPI status flag polling mode */ void HAL_QSPI_StatusMatchCallback (QSPI_HandleTypeDef *hqspi); /* QSPI memory-mapped mode */ void HAL_QSPI_TimeOutCallback (QSPI_HandleTypeDef *hqspi); /** * @} */ /** @addtogroup QSPI_Exported_Functions_Group4 * @{ */ /* Peripheral Control and State functions ************************************/ HAL_QSPI_StateTypeDef HAL_QSPI_GetState(QSPI_HandleTypeDef *hqspi); uint32_t HAL_QSPI_GetError(QSPI_HandleTypeDef *hqspi); HAL_StatusTypeDef HAL_QSPI_Abort (QSPI_HandleTypeDef *hqspi); void HAL_QSPI_SetTimeout(QSPI_HandleTypeDef *hqspi, uint32_t Timeout); /** * @} */ /** * @} */ /* Private types -------------------------------------------------------------*/ /* Private variables ---------------------------------------------------------*/ /* Private constants ---------------------------------------------------------*/ /** @defgroup QSPI_Private_Constants QSPI Private Constants * @{ */ /** * @} */ /* Private macros ------------------------------------------------------------*/ /** @defgroup QSPI_Private_Macros QSPI Private Macros * @{ */ /** @defgroup QSPI_ClockPrescaler QSPI Clock Prescaler * @{ */ #define IS_QSPI_CLOCK_PRESCALER(PRESCALER) ((PRESCALER) <= 0xFF) /** * @} */ /** @defgroup QSPI_FifoThreshold QSPI Fifo Threshold * @{ */ #define IS_QSPI_FIFO_THRESHOLD(THR) (((THR) > 0) && ((THR) <= 32)) /** * @} */ #define IS_QSPI_SSHIFT(SSHIFT) (((SSHIFT) == QSPI_SAMPLE_SHIFTING_NONE) || \ ((SSHIFT) == QSPI_SAMPLE_SHIFTING_HALFCYCLE)) /** @defgroup QSPI_FlashSize QSPI Flash Size * @{ */ #define IS_QSPI_FLASH_SIZE(FSIZE) (((FSIZE) <= 31)) /** * @} */ #define IS_QSPI_CS_HIGH_TIME(CSHTIME) (((CSHTIME) == QSPI_CS_HIGH_TIME_1_CYCLE) || \ ((CSHTIME) == QSPI_CS_HIGH_TIME_2_CYCLE) || \ ((CSHTIME) == QSPI_CS_HIGH_TIME_3_CYCLE) || \ ((CSHTIME) == QSPI_CS_HIGH_TIME_4_CYCLE) || \ ((CSHTIME) == QSPI_CS_HIGH_TIME_5_CYCLE) || \ ((CSHTIME) == QSPI_CS_HIGH_TIME_6_CYCLE) || \ ((CSHTIME) == QSPI_CS_HIGH_TIME_7_CYCLE) || \ ((CSHTIME) == QSPI_CS_HIGH_TIME_8_CYCLE)) #define IS_QSPI_CLOCK_MODE(CLKMODE) (((CLKMODE) == QSPI_CLOCK_MODE_0) || \ ((CLKMODE) == QSPI_CLOCK_MODE_3)) #define IS_QSPI_FLASH_ID(FLA) (((FLA) == QSPI_FLASH_ID_1) || \ ((FLA) == QSPI_FLASH_ID_2)) #define IS_QSPI_DUAL_FLASH_MODE(MODE) (((MODE) == QSPI_DUALFLASH_ENABLE) || \ ((MODE) == QSPI_DUALFLASH_DISABLE)) /** @defgroup QSPI_Instruction QSPI Instruction * @{ */ #define IS_QSPI_INSTRUCTION(INSTRUCTION) ((INSTRUCTION) <= 0xFF) /** * @} */ #define IS_QSPI_ADDRESS_SIZE(ADDR_SIZE) (((ADDR_SIZE) == QSPI_ADDRESS_8_BITS) || \ ((ADDR_SIZE) == QSPI_ADDRESS_16_BITS) || \ ((ADDR_SIZE) == QSPI_ADDRESS_24_BITS) || \ ((ADDR_SIZE) == QSPI_ADDRESS_32_BITS)) #define IS_QSPI_ALTERNATE_BYTES_SIZE(SIZE) (((SIZE) == QSPI_ALTERNATE_BYTES_8_BITS) || \ ((SIZE) == QSPI_ALTERNATE_BYTES_16_BITS) || \ ((SIZE) == QSPI_ALTERNATE_BYTES_24_BITS) || \ ((SIZE) == QSPI_ALTERNATE_BYTES_32_BITS)) /** @defgroup QSPI_DummyCycles QSPI Dummy Cycles * @{ */ #define IS_QSPI_DUMMY_CYCLES(DCY) ((DCY) <= 31) /** * @} */ #define IS_QSPI_INSTRUCTION_MODE(MODE) (((MODE) == QSPI_INSTRUCTION_NONE) || \ ((MODE) == QSPI_INSTRUCTION_1_LINE) || \ ((MODE) == QSPI_INSTRUCTION_2_LINES) || \ ((MODE) == QSPI_INSTRUCTION_4_LINES)) #define IS_QSPI_ADDRESS_MODE(MODE) (((MODE) == QSPI_ADDRESS_NONE) || \ ((MODE) == QSPI_ADDRESS_1_LINE) || \ ((MODE) == QSPI_ADDRESS_2_LINES) || \ ((MODE) == QSPI_ADDRESS_4_LINES)) #define IS_QSPI_ALTERNATE_BYTES_MODE(MODE) (((MODE) == QSPI_ALTERNATE_BYTES_NONE) || \ ((MODE) == QSPI_ALTERNATE_BYTES_1_LINE) || \ ((MODE) == QSPI_ALTERNATE_BYTES_2_LINES) || \ ((MODE) == QSPI_ALTERNATE_BYTES_4_LINES)) #define IS_QSPI_DATA_MODE(MODE) (((MODE) == QSPI_DATA_NONE) || \ ((MODE) == QSPI_DATA_1_LINE) || \ ((MODE) == QSPI_DATA_2_LINES) || \ ((MODE) == QSPI_DATA_4_LINES)) #define IS_QSPI_DDR_MODE(DDR_MODE) (((DDR_MODE) == QSPI_DDR_MODE_DISABLE) || \ ((DDR_MODE) == QSPI_DDR_MODE_ENABLE)) #define IS_QSPI_DDR_HHC(DDR_HHC) (((DDR_HHC) == QSPI_DDR_HHC_ANALOG_DELAY) || \ ((DDR_HHC) == QSPI_DDR_HHC_HALF_CLK_DELAY)) #define IS_QSPI_SIOO_MODE(SIOO_MODE) (((SIOO_MODE) == QSPI_SIOO_INST_EVERY_CMD) || \ ((SIOO_MODE) == QSPI_SIOO_INST_ONLY_FIRST_CMD)) /** @defgroup QSPI_Interval QSPI Interval * @{ */ #define IS_QSPI_INTERVAL(INTERVAL) ((INTERVAL) <= QUADSPI_PIR_INTERVAL) /** * @} */ /** @defgroup QSPI_StatusBytesSize QSPI Status Bytes Size * @{ */ #define IS_QSPI_STATUS_BYTES_SIZE(SIZE) (((SIZE) >= 1) && ((SIZE) <= 4)) /** * @} */ #define IS_QSPI_MATCH_MODE(MODE) (((MODE) == QSPI_MATCH_MODE_AND) || \ ((MODE) == QSPI_MATCH_MODE_OR)) #define IS_QSPI_AUTOMATIC_STOP(APMS) (((APMS) == QSPI_AUTOMATIC_STOP_DISABLE) || \ ((APMS) == QSPI_AUTOMATIC_STOP_ENABLE)) #define IS_QSPI_TIMEOUT_ACTIVATION(TCEN) (((TCEN) == QSPI_TIMEOUT_COUNTER_DISABLE) || \ ((TCEN) == QSPI_TIMEOUT_COUNTER_ENABLE)) /** @defgroup QSPI_TimeOutPeriod QSPI TimeOut Period * @{ */ #define IS_QSPI_TIMEOUT_PERIOD(PERIOD) ((PERIOD) <= 0xFFFF) /** * @} */ #define IS_QSPI_GET_FLAG(FLAG) (((FLAG) == QSPI_FLAG_BUSY) || \ ((FLAG) == QSPI_FLAG_TO) || \ ((FLAG) == QSPI_FLAG_SM) || \ ((FLAG) == QSPI_FLAG_FT) || \ ((FLAG) == QSPI_FLAG_TC) || \ ((FLAG) == QSPI_FLAG_TE)) #define IS_QSPI_IT(IT) ((((IT) & (uint32_t)0xFFE0FFFF) == 0x00000000) && ((IT) != 0x00000000)) /** * @} */ /* Private functions ---------------------------------------------------------*/ /** @defgroup QSPI_Private_Functions QSPI Private Functions * @{ */ /** * @} */ /** * @} */ /** * @} */ #endif /* STM32F446xx || STM32F469xx || STM32F479xx */ #ifdef __cplusplus } #endif #endif /* __STM32F4xx_HAL_QSPI_H */ /************************ (C) COPYRIGHT STMicroelectronics *****END OF FILE****/ ================================================ FILE: Zelig/mbed/TARGET_NUCLEO_F411RE/stm32f4xx_hal_rcc.h ================================================ /** ****************************************************************************** * @file stm32f4xx_hal_rcc.h * @author MCD Application Team * @version V1.4.1 * @date 09-October-2015 * @brief Header file of RCC HAL module. ****************************************************************************** * @attention * *

© COPYRIGHT(c) 2015 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. * ****************************************************************************** */ /* Define to prevent recursive inclusion -------------------------------------*/ #ifndef __STM32F4xx_HAL_RCC_H #define __STM32F4xx_HAL_RCC_H #ifdef __cplusplus extern "C" { #endif /* Includes ------------------------------------------------------------------*/ #include "stm32f4xx_hal_def.h" /* Include RCC HAL Extended module */ /* (include on top of file since RCC structures are defined in extended file) */ #include "stm32f4xx_hal_rcc_ex.h" /** @addtogroup STM32F4xx_HAL_Driver * @{ */ /** @addtogroup RCC * @{ */ /* Exported types ------------------------------------------------------------*/ /** @defgroup RCC_Exported_Types RCC Exported Types * @{ */ /** * @brief RCC Internal/External Oscillator (HSE, HSI, LSE and LSI) configuration structure definition */ typedef struct { uint32_t OscillatorType; /*!< The oscillators to be configured. This parameter can be a value of @ref RCC_Oscillator_Type */ uint32_t HSEState; /*!< The new state of the HSE. This parameter can be a value of @ref RCC_HSE_Config */ uint32_t LSEState; /*!< The new state of the LSE. This parameter can be a value of @ref RCC_LSE_Config */ uint32_t HSIState; /*!< The new state of the HSI. This parameter can be a value of @ref RCC_HSI_Config */ uint32_t HSICalibrationValue; /*!< The calibration trimming value. This parameter must be a number between Min_Data = 0x00 and Max_Data = 0x1F */ uint32_t LSIState; /*!< The new state of the LSI. This parameter can be a value of @ref RCC_LSI_Config */ RCC_PLLInitTypeDef PLL; /*!< PLL structure parameters */ }RCC_OscInitTypeDef; /** * @brief RCC System, AHB and APB busses clock configuration structure definition */ typedef struct { uint32_t ClockType; /*!< The clock to be configured. This parameter can be a value of @ref RCC_System_Clock_Type */ uint32_t SYSCLKSource; /*!< The clock source (SYSCLKS) used as system clock. This parameter can be a value of @ref RCC_System_Clock_Source */ uint32_t AHBCLKDivider; /*!< The AHB clock (HCLK) divider. This clock is derived from the system clock (SYSCLK). This parameter can be a value of @ref RCC_AHB_Clock_Source */ uint32_t APB1CLKDivider; /*!< The APB1 clock (PCLK1) divider. This clock is derived from the AHB clock (HCLK). This parameter can be a value of @ref RCC_APB1_APB2_Clock_Source */ uint32_t APB2CLKDivider; /*!< The APB2 clock (PCLK2) divider. This clock is derived from the AHB clock (HCLK). This parameter can be a value of @ref RCC_APB1_APB2_Clock_Source */ }RCC_ClkInitTypeDef; /** * @} */ /* Exported constants --------------------------------------------------------*/ /** @defgroup RCC_Exported_Constants RCC Exported Constants * @{ */ /** @defgroup RCC_Oscillator_Type Oscillator Type * @{ */ #define RCC_OSCILLATORTYPE_NONE ((uint32_t)0x00000000) #define RCC_OSCILLATORTYPE_HSE ((uint32_t)0x00000001) #define RCC_OSCILLATORTYPE_HSI ((uint32_t)0x00000002) #define RCC_OSCILLATORTYPE_LSE ((uint32_t)0x00000004) #define RCC_OSCILLATORTYPE_LSI ((uint32_t)0x00000008) /** * @} */ /** @defgroup RCC_HSE_Config HSE Config * @{ */ #define RCC_HSE_OFF ((uint8_t)0x00) #define RCC_HSE_ON ((uint8_t)0x01) #define RCC_HSE_BYPASS ((uint8_t)0x05) /** * @} */ /** @defgroup RCC_LSE_Config LSE Config * @{ */ #define RCC_LSE_OFF ((uint8_t)0x00) #define RCC_LSE_ON ((uint8_t)0x01) #define RCC_LSE_BYPASS ((uint8_t)0x05) /** * @} */ /** @defgroup RCC_HSI_Config HSI Config * @{ */ #define RCC_HSI_OFF ((uint8_t)0x00) #define RCC_HSI_ON ((uint8_t)0x01) /** * @} */ /** @defgroup RCC_LSI_Config LSI Config * @{ */ #define RCC_LSI_OFF ((uint8_t)0x00) #define RCC_LSI_ON ((uint8_t)0x01) /** * @} */ /** @defgroup RCC_PLL_Config PLL Config * @{ */ #define RCC_PLL_NONE ((uint8_t)0x00) #define RCC_PLL_OFF ((uint8_t)0x01) #define RCC_PLL_ON ((uint8_t)0x02) /** * @} */ /** @defgroup RCC_PLLP_Clock_Divider PLLP Clock Divider * @{ */ #define RCC_PLLP_DIV2 ((uint32_t)0x00000002) #define RCC_PLLP_DIV4 ((uint32_t)0x00000004) #define RCC_PLLP_DIV6 ((uint32_t)0x00000006) #define RCC_PLLP_DIV8 ((uint32_t)0x00000008) /** * @} */ /** @defgroup RCC_PLL_Clock_Source PLL Clock Source * @{ */ #define RCC_PLLSOURCE_HSI RCC_PLLCFGR_PLLSRC_HSI #define RCC_PLLSOURCE_HSE RCC_PLLCFGR_PLLSRC_HSE /** * @} */ /** @defgroup RCC_System_Clock_Type System Clock Type * @{ */ #define RCC_CLOCKTYPE_SYSCLK ((uint32_t)0x00000001) #define RCC_CLOCKTYPE_HCLK ((uint32_t)0x00000002) #define RCC_CLOCKTYPE_PCLK1 ((uint32_t)0x00000004) #define RCC_CLOCKTYPE_PCLK2 ((uint32_t)0x00000008) /** * @} */ /** @defgroup RCC_System_Clock_Source System Clock Source * @{ */ #define RCC_SYSCLKSOURCE_HSI RCC_CFGR_SW_HSI #define RCC_SYSCLKSOURCE_HSE RCC_CFGR_SW_HSE #define RCC_SYSCLKSOURCE_PLLCLK RCC_CFGR_SW_PLL #define RCC_SYSCLKSOURCE_PLLRCLK ((uint32_t)(RCC_CFGR_SW_0 | RCC_CFGR_SW_1)) /** * @} */ /** @defgroup RCC_System_Clock_Source_Status System Clock Source Status * @{ */ #define RCC_SYSCLKSOURCE_STATUS_HSI RCC_CFGR_SWS_HSI /*!< HSI used as system clock */ #define RCC_SYSCLKSOURCE_STATUS_HSE RCC_CFGR_SWS_HSE /*!< HSE used as system clock */ #define RCC_SYSCLKSOURCE_STATUS_PLLCLK RCC_CFGR_SWS_PLL /*!< PLL used as system clock */ #define RCC_SYSCLKSOURCE_STATUS_PLLRCLK ((uint32_t)(RCC_CFGR_SW_0 | RCC_CFGR_SW_1)) /*!< PLLR used as system clock */ /** * @} */ /** @defgroup RCC_AHB_Clock_Source AHB Clock Source * @{ */ #define RCC_SYSCLK_DIV1 RCC_CFGR_HPRE_DIV1 #define RCC_SYSCLK_DIV2 RCC_CFGR_HPRE_DIV2 #define RCC_SYSCLK_DIV4 RCC_CFGR_HPRE_DIV4 #define RCC_SYSCLK_DIV8 RCC_CFGR_HPRE_DIV8 #define RCC_SYSCLK_DIV16 RCC_CFGR_HPRE_DIV16 #define RCC_SYSCLK_DIV64 RCC_CFGR_HPRE_DIV64 #define RCC_SYSCLK_DIV128 RCC_CFGR_HPRE_DIV128 #define RCC_SYSCLK_DIV256 RCC_CFGR_HPRE_DIV256 #define RCC_SYSCLK_DIV512 RCC_CFGR_HPRE_DIV512 /** * @} */ /** @defgroup RCC_APB1_APB2_Clock_Source APB1/APB2 Clock Source * @{ */ #define RCC_HCLK_DIV1 RCC_CFGR_PPRE1_DIV1 #define RCC_HCLK_DIV2 RCC_CFGR_PPRE1_DIV2 #define RCC_HCLK_DIV4 RCC_CFGR_PPRE1_DIV4 #define RCC_HCLK_DIV8 RCC_CFGR_PPRE1_DIV8 #define RCC_HCLK_DIV16 RCC_CFGR_PPRE1_DIV16 /** * @} */ /** @defgroup RCC_RTC_Clock_Source RTC Clock Source * @{ */ #define RCC_RTCCLKSOURCE_LSE ((uint32_t)0x00000100) #define RCC_RTCCLKSOURCE_LSI ((uint32_t)0x00000200) #define RCC_RTCCLKSOURCE_HSE_DIV2 ((uint32_t)0x00020300) #define RCC_RTCCLKSOURCE_HSE_DIV3 ((uint32_t)0x00030300) #define RCC_RTCCLKSOURCE_HSE_DIV4 ((uint32_t)0x00040300) #define RCC_RTCCLKSOURCE_HSE_DIV5 ((uint32_t)0x00050300) #define RCC_RTCCLKSOURCE_HSE_DIV6 ((uint32_t)0x00060300) #define RCC_RTCCLKSOURCE_HSE_DIV7 ((uint32_t)0x00070300) #define RCC_RTCCLKSOURCE_HSE_DIV8 ((uint32_t)0x00080300) #define RCC_RTCCLKSOURCE_HSE_DIV9 ((uint32_t)0x00090300) #define RCC_RTCCLKSOURCE_HSE_DIV10 ((uint32_t)0x000A0300) #define RCC_RTCCLKSOURCE_HSE_DIV11 ((uint32_t)0x000B0300) #define RCC_RTCCLKSOURCE_HSE_DIV12 ((uint32_t)0x000C0300) #define RCC_RTCCLKSOURCE_HSE_DIV13 ((uint32_t)0x000D0300) #define RCC_RTCCLKSOURCE_HSE_DIV14 ((uint32_t)0x000E0300) #define RCC_RTCCLKSOURCE_HSE_DIV15 ((uint32_t)0x000F0300) #define RCC_RTCCLKSOURCE_HSE_DIV16 ((uint32_t)0x00100300) #define RCC_RTCCLKSOURCE_HSE_DIV17 ((uint32_t)0x00110300) #define RCC_RTCCLKSOURCE_HSE_DIV18 ((uint32_t)0x00120300) #define RCC_RTCCLKSOURCE_HSE_DIV19 ((uint32_t)0x00130300) #define RCC_RTCCLKSOURCE_HSE_DIV20 ((uint32_t)0x00140300) #define RCC_RTCCLKSOURCE_HSE_DIV21 ((uint32_t)0x00150300) #define RCC_RTCCLKSOURCE_HSE_DIV22 ((uint32_t)0x00160300) #define RCC_RTCCLKSOURCE_HSE_DIV23 ((uint32_t)0x00170300) #define RCC_RTCCLKSOURCE_HSE_DIV24 ((uint32_t)0x00180300) #define RCC_RTCCLKSOURCE_HSE_DIV25 ((uint32_t)0x00190300) #define RCC_RTCCLKSOURCE_HSE_DIV26 ((uint32_t)0x001A0300) #define RCC_RTCCLKSOURCE_HSE_DIV27 ((uint32_t)0x001B0300) #define RCC_RTCCLKSOURCE_HSE_DIV28 ((uint32_t)0x001C0300) #define RCC_RTCCLKSOURCE_HSE_DIV29 ((uint32_t)0x001D0300) #define RCC_RTCCLKSOURCE_HSE_DIV30 ((uint32_t)0x001E0300) #define RCC_RTCCLKSOURCE_HSE_DIV31 ((uint32_t)0x001F0300) /** * @} */ /** @defgroup RCC_MCO_Index MCO Index * @{ */ #define RCC_MCO1 ((uint32_t)0x00000000) #define RCC_MCO2 ((uint32_t)0x00000001) /** * @} */ /** @defgroup RCC_MCO1_Clock_Source MCO1 Clock Source * @{ */ #define RCC_MCO1SOURCE_HSI ((uint32_t)0x00000000) #define RCC_MCO1SOURCE_LSE RCC_CFGR_MCO1_0 #define RCC_MCO1SOURCE_HSE RCC_CFGR_MCO1_1 #define RCC_MCO1SOURCE_PLLCLK RCC_CFGR_MCO1 /** * @} */ /** @defgroup RCC_MCOx_Clock_Prescaler MCOx Clock Prescaler * @{ */ #define RCC_MCODIV_1 ((uint32_t)0x00000000) #define RCC_MCODIV_2 RCC_CFGR_MCO1PRE_2 #define RCC_MCODIV_3 ((uint32_t)RCC_CFGR_MCO1PRE_0 | RCC_CFGR_MCO1PRE_2) #define RCC_MCODIV_4 ((uint32_t)RCC_CFGR_MCO1PRE_1 | RCC_CFGR_MCO1PRE_2) #define RCC_MCODIV_5 RCC_CFGR_MCO1PRE /** * @} */ /** @defgroup RCC_Interrupt Interrupts * @{ */ #define RCC_IT_LSIRDY ((uint8_t)0x01) #define RCC_IT_LSERDY ((uint8_t)0x02) #define RCC_IT_HSIRDY ((uint8_t)0x04) #define RCC_IT_HSERDY ((uint8_t)0x08) #define RCC_IT_PLLRDY ((uint8_t)0x10) #define RCC_IT_PLLI2SRDY ((uint8_t)0x20) #define RCC_IT_CSS ((uint8_t)0x80) /** * @} */ /** @defgroup RCC_Flag Flags * Elements values convention: 0XXYYYYYb * - YYYYY : Flag position in the register * - 0XX : Register index * - 01: CR register * - 10: BDCR register * - 11: CSR register * @{ */ /* Flags in the CR register */ #define RCC_FLAG_HSIRDY ((uint8_t)0x21) #define RCC_FLAG_HSERDY ((uint8_t)0x31) #define RCC_FLAG_PLLRDY ((uint8_t)0x39) #define RCC_FLAG_PLLI2SRDY ((uint8_t)0x3B) /* Flags in the BDCR register */ #define RCC_FLAG_LSERDY ((uint8_t)0x41) /* Flags in the CSR register */ #define RCC_FLAG_LSIRDY ((uint8_t)0x61) #define RCC_FLAG_BORRST ((uint8_t)0x79) #define RCC_FLAG_PINRST ((uint8_t)0x7A) #define RCC_FLAG_PORRST ((uint8_t)0x7B) #define RCC_FLAG_SFTRST ((uint8_t)0x7C) #define RCC_FLAG_IWDGRST ((uint8_t)0x7D) #define RCC_FLAG_WWDGRST ((uint8_t)0x7E) #define RCC_FLAG_LPWRRST ((uint8_t)0x7F) /** * @} */ /** * @} */ /* Exported macro ------------------------------------------------------------*/ /** @defgroup RCC_Exported_Macros RCC Exported Macros * @{ */ /** @defgroup RCC_AHB1_Clock_Enable_Disable AHB1 Peripheral Clock Enable Disable * @brief Enable or disable the AHB1 peripheral clock. * @note After reset, the peripheral clock (used for registers read/write access) * is disabled and the application software has to enable this clock before * using it. * @{ */ #define __HAL_RCC_GPIOA_CLK_ENABLE() do { \ __IO uint32_t tmpreg; \ SET_BIT(RCC->AHB1ENR, RCC_AHB1ENR_GPIOAEN);\ /* Delay after an RCC peripheral clock enabling */ \ tmpreg = READ_BIT(RCC->AHB1ENR, RCC_AHB1ENR_GPIOAEN);\ UNUSED(tmpreg); \ } while(0) #define __HAL_RCC_GPIOB_CLK_ENABLE() do { \ __IO uint32_t tmpreg; \ SET_BIT(RCC->AHB1ENR, RCC_AHB1ENR_GPIOBEN);\ /* Delay after an RCC peripheral clock enabling */ \ tmpreg = READ_BIT(RCC->AHB1ENR, RCC_AHB1ENR_GPIOBEN);\ UNUSED(tmpreg); \ } while(0) #define __HAL_RCC_GPIOC_CLK_ENABLE() do { \ __IO uint32_t tmpreg; \ SET_BIT(RCC->AHB1ENR, RCC_AHB1ENR_GPIOCEN);\ /* Delay after an RCC peripheral clock enabling */ \ tmpreg = READ_BIT(RCC->AHB1ENR, RCC_AHB1ENR_GPIOCEN);\ UNUSED(tmpreg); \ } while(0) #define __HAL_RCC_GPIOH_CLK_ENABLE() do { \ __IO uint32_t tmpreg; \ SET_BIT(RCC->AHB1ENR, RCC_AHB1ENR_GPIOHEN);\ /* Delay after an RCC peripheral clock enabling */ \ tmpreg = READ_BIT(RCC->AHB1ENR, RCC_AHB1ENR_GPIOHEN);\ UNUSED(tmpreg); \ } while(0) #define __HAL_RCC_DMA1_CLK_ENABLE() do { \ __IO uint32_t tmpreg; \ SET_BIT(RCC->AHB1ENR, RCC_AHB1ENR_DMA1EN);\ /* Delay after an RCC peripheral clock enabling */ \ tmpreg = READ_BIT(RCC->AHB1ENR, RCC_AHB1ENR_DMA1EN);\ UNUSED(tmpreg); \ } while(0) #define __HAL_RCC_DMA2_CLK_ENABLE() do { \ __IO uint32_t tmpreg; \ SET_BIT(RCC->AHB1ENR, RCC_AHB1ENR_DMA2EN);\ /* Delay after an RCC peripheral clock enabling */ \ tmpreg = READ_BIT(RCC->AHB1ENR, RCC_AHB1ENR_DMA2EN);\ UNUSED(tmpreg); \ } while(0) #define __HAL_RCC_GPIOA_CLK_DISABLE() (RCC->AHB1ENR &= ~(RCC_AHB1ENR_GPIOAEN)) #define __HAL_RCC_GPIOB_CLK_DISABLE() (RCC->AHB1ENR &= ~(RCC_AHB1ENR_GPIOBEN)) #define __HAL_RCC_GPIOC_CLK_DISABLE() (RCC->AHB1ENR &= ~(RCC_AHB1ENR_GPIOCEN)) #define __HAL_RCC_GPIOH_CLK_DISABLE() (RCC->AHB1ENR &= ~(RCC_AHB1ENR_GPIOHEN)) #define __HAL_RCC_DMA1_CLK_DISABLE() (RCC->AHB1ENR &= ~(RCC_AHB1ENR_DMA1EN)) #define __HAL_RCC_DMA2_CLK_DISABLE() (RCC->AHB1ENR &= ~(RCC_AHB1ENR_DMA2EN)) /** * @} */ /** @defgroup RCC_APB1_Clock_Enable_Disable APB1 Peripheral Clock Enable Disable * @brief Enable or disable the Low Speed APB (APB1) peripheral clock. * @note After reset, the peripheral clock (used for registers read/write access) * is disabled and the application software has to enable this clock before * using it. * @{ */ #define __HAL_RCC_TIM5_CLK_ENABLE() do { \ __IO uint32_t tmpreg; \ SET_BIT(RCC->APB1ENR, RCC_APB1ENR_TIM5EN);\ /* Delay after an RCC peripheral clock enabling */ \ tmpreg = READ_BIT(RCC->APB1ENR, RCC_APB1ENR_TIM5EN);\ UNUSED(tmpreg); \ } while(0) #define __HAL_RCC_WWDG_CLK_ENABLE() do { \ __IO uint32_t tmpreg; \ SET_BIT(RCC->APB1ENR, RCC_APB1ENR_WWDGEN);\ /* Delay after an RCC peripheral clock enabling */ \ tmpreg = READ_BIT(RCC->APB1ENR, RCC_APB1ENR_WWDGEN);\ UNUSED(tmpreg); \ } while(0) #define __HAL_RCC_SPI2_CLK_ENABLE() do { \ __IO uint32_t tmpreg; \ SET_BIT(RCC->APB1ENR, RCC_APB1ENR_SPI2EN);\ /* Delay after an RCC peripheral clock enabling */ \ tmpreg = READ_BIT(RCC->APB1ENR, RCC_APB1ENR_SPI2EN);\ UNUSED(tmpreg); \ } while(0) #define __HAL_RCC_USART2_CLK_ENABLE() do { \ __IO uint32_t tmpreg; \ SET_BIT(RCC->APB1ENR, RCC_APB1ENR_USART2EN);\ /* Delay after an RCC peripheral clock enabling */ \ tmpreg = READ_BIT(RCC->APB1ENR, RCC_APB1ENR_USART2EN);\ UNUSED(tmpreg); \ } while(0) #define __HAL_RCC_I2C1_CLK_ENABLE() do { \ __IO uint32_t tmpreg; \ SET_BIT(RCC->APB1ENR, RCC_APB1ENR_I2C1EN);\ /* Delay after an RCC peripheral clock enabling */ \ tmpreg = READ_BIT(RCC->APB1ENR, RCC_APB1ENR_I2C1EN);\ UNUSED(tmpreg); \ } while(0) #define __HAL_RCC_I2C2_CLK_ENABLE() do { \ __IO uint32_t tmpreg; \ SET_BIT(RCC->APB1ENR, RCC_APB1ENR_I2C2EN);\ /* Delay after an RCC peripheral clock enabling */ \ tmpreg = READ_BIT(RCC->APB1ENR, RCC_APB1ENR_I2C2EN);\ UNUSED(tmpreg); \ } while(0) #define __HAL_RCC_PWR_CLK_ENABLE() do { \ __IO uint32_t tmpreg; \ SET_BIT(RCC->APB1ENR, RCC_APB1ENR_PWREN);\ /* Delay after an RCC peripheral clock enabling */ \ tmpreg = READ_BIT(RCC->APB1ENR, RCC_APB1ENR_PWREN);\ UNUSED(tmpreg); \ } while(0) #define __HAL_RCC_TIM5_CLK_DISABLE() (RCC->APB1ENR &= ~(RCC_APB1ENR_TIM5EN)) #define __HAL_RCC_WWDG_CLK_DISABLE() (RCC->APB1ENR &= ~(RCC_APB1ENR_WWDGEN)) #define __HAL_RCC_SPI2_CLK_DISABLE() (RCC->APB1ENR &= ~(RCC_APB1ENR_SPI2EN)) #define __HAL_RCC_USART2_CLK_DISABLE() (RCC->APB1ENR &= ~(RCC_APB1ENR_USART2EN)) #define __HAL_RCC_I2C1_CLK_DISABLE() (RCC->APB1ENR &= ~(RCC_APB1ENR_I2C1EN)) #define __HAL_RCC_I2C2_CLK_DISABLE() (RCC->APB1ENR &= ~(RCC_APB1ENR_I2C2EN)) #define __HAL_RCC_PWR_CLK_DISABLE() (RCC->APB1ENR &= ~(RCC_APB1ENR_PWREN)) /** * @} */ /** @defgroup RCC_APB2_Clock_Enable_Disable APB2 Peripheral Clock Enable Disable * @brief Enable or disable the High Speed APB (APB2) peripheral clock. * @note After reset, the peripheral clock (used for registers read/write access) * is disabled and the application software has to enable this clock before * using it. * @{ */ #define __HAL_RCC_TIM1_CLK_ENABLE() do { \ __IO uint32_t tmpreg; \ SET_BIT(RCC->APB2ENR, RCC_APB2ENR_TIM1EN);\ /* Delay after an RCC peripheral clock enabling */ \ tmpreg = READ_BIT(RCC->APB2ENR, RCC_APB2ENR_TIM1EN);\ UNUSED(tmpreg); \ } while(0) #define __HAL_RCC_USART1_CLK_ENABLE() do { \ __IO uint32_t tmpreg; \ SET_BIT(RCC->APB2ENR, RCC_APB2ENR_USART1EN);\ /* Delay after an RCC peripheral clock enabling */ \ tmpreg = READ_BIT(RCC->APB2ENR, RCC_APB2ENR_USART1EN);\ UNUSED(tmpreg); \ } while(0) #define __HAL_RCC_USART6_CLK_ENABLE() do { \ __IO uint32_t tmpreg; \ SET_BIT(RCC->APB2ENR, RCC_APB2ENR_USART6EN);\ /* Delay after an RCC peripheral clock enabling */ \ tmpreg = READ_BIT(RCC->APB2ENR, RCC_APB2ENR_USART6EN);\ UNUSED(tmpreg); \ } while(0) #define __HAL_RCC_ADC1_CLK_ENABLE() do { \ __IO uint32_t tmpreg; \ SET_BIT(RCC->APB2ENR, RCC_APB2ENR_ADC1EN);\ /* Delay after an RCC peripheral clock enabling */ \ tmpreg = READ_BIT(RCC->APB2ENR, RCC_APB2ENR_ADC1EN);\ UNUSED(tmpreg); \ } while(0) #define __HAL_RCC_SPI1_CLK_ENABLE() do { \ __IO uint32_t tmpreg; \ SET_BIT(RCC->APB2ENR, RCC_APB2ENR_SPI1EN);\ /* Delay after an RCC peripheral clock enabling */ \ tmpreg = READ_BIT(RCC->APB2ENR, RCC_APB2ENR_SPI1EN);\ UNUSED(tmpreg); \ } while(0) #define __HAL_RCC_SYSCFG_CLK_ENABLE() do { \ __IO uint32_t tmpreg; \ SET_BIT(RCC->APB2ENR, RCC_APB2ENR_SYSCFGEN);\ /* Delay after an RCC peripheral clock enabling */ \ tmpreg = READ_BIT(RCC->APB2ENR, RCC_APB2ENR_SYSCFGEN);\ UNUSED(tmpreg); \ } while(0) #define __HAL_RCC_TIM9_CLK_ENABLE() do { \ __IO uint32_t tmpreg; \ SET_BIT(RCC->APB2ENR, RCC_APB2ENR_TIM9EN);\ /* Delay after an RCC peripheral clock enabling */ \ tmpreg = READ_BIT(RCC->APB2ENR, RCC_APB2ENR_TIM9EN);\ UNUSED(tmpreg); \ } while(0) #define __HAL_RCC_TIM11_CLK_ENABLE() do { \ __IO uint32_t tmpreg; \ SET_BIT(RCC->APB2ENR, RCC_APB2ENR_TIM11EN);\ /* Delay after an RCC peripheral clock enabling */ \ tmpreg = READ_BIT(RCC->APB2ENR, RCC_APB2ENR_TIM11EN);\ UNUSED(tmpreg); \ } while(0) #define __HAL_RCC_TIM1_CLK_DISABLE() (RCC->APB2ENR &= ~(RCC_APB2ENR_TIM1EN)) #define __HAL_RCC_USART1_CLK_DISABLE() (RCC->APB2ENR &= ~(RCC_APB2ENR_USART1EN)) #define __HAL_RCC_USART6_CLK_DISABLE() (RCC->APB2ENR &= ~(RCC_APB2ENR_USART6EN)) #define __HAL_RCC_ADC1_CLK_DISABLE() (RCC->APB2ENR &= ~(RCC_APB2ENR_ADC1EN)) #define __HAL_RCC_SPI1_CLK_DISABLE() (RCC->APB2ENR &= ~(RCC_APB2ENR_SPI1EN)) #define __HAL_RCC_SYSCFG_CLK_DISABLE() (RCC->APB2ENR &= ~(RCC_APB2ENR_SYSCFGEN)) #define __HAL_RCC_TIM9_CLK_DISABLE() (RCC->APB2ENR &= ~(RCC_APB2ENR_TIM9EN)) #define __HAL_RCC_TIM11_CLK_DISABLE() (RCC->APB2ENR &= ~(RCC_APB2ENR_TIM11EN)) /** * @} */ /** @defgroup RCC_AHB1_Force_Release_Reset AHB1 Force Release Reset * @brief Force or release AHB1 peripheral reset. * @{ */ #define __HAL_RCC_AHB1_FORCE_RESET() (RCC->AHB1RSTR = 0xFFFFFFFF) #define __HAL_RCC_GPIOA_FORCE_RESET() (RCC->AHB1RSTR |= (RCC_AHB1RSTR_GPIOARST)) #define __HAL_RCC_GPIOB_FORCE_RESET() (RCC->AHB1RSTR |= (RCC_AHB1RSTR_GPIOBRST)) #define __HAL_RCC_GPIOC_FORCE_RESET() (RCC->AHB1RSTR |= (RCC_AHB1RSTR_GPIOCRST)) #define __HAL_RCC_GPIOH_FORCE_RESET() (RCC->AHB1RSTR |= (RCC_AHB1RSTR_GPIOHRST)) #define __HAL_RCC_DMA1_FORCE_RESET() (RCC->AHB1RSTR |= (RCC_AHB1RSTR_DMA1RST)) #define __HAL_RCC_DMA2_FORCE_RESET() (RCC->AHB1RSTR |= (RCC_AHB1RSTR_DMA2RST)) #define __HAL_RCC_AHB1_RELEASE_RESET() (RCC->AHB1RSTR = 0x00) #define __HAL_RCC_GPIOA_RELEASE_RESET() (RCC->AHB1RSTR &= ~(RCC_AHB1RSTR_GPIOARST)) #define __HAL_RCC_GPIOB_RELEASE_RESET() (RCC->AHB1RSTR &= ~(RCC_AHB1RSTR_GPIOBRST)) #define __HAL_RCC_GPIOC_RELEASE_RESET() (RCC->AHB1RSTR &= ~(RCC_AHB1RSTR_GPIOCRST)) #define __HAL_RCC_GPIOH_RELEASE_RESET() (RCC->AHB1RSTR &= ~(RCC_AHB1RSTR_GPIOHRST)) #define __HAL_RCC_DMA1_RELEASE_RESET() (RCC->AHB1RSTR &= ~(RCC_AHB1RSTR_DMA1RST)) #define __HAL_RCC_DMA2_RELEASE_RESET() (RCC->AHB1RSTR &= ~(RCC_AHB1RSTR_DMA2RST)) /** * @} */ /** @defgroup RCC_APB1_Force_Release_Reset APB1 Force Release Reset * @brief Force or release APB1 peripheral reset. * @{ */ #define __HAL_RCC_APB1_FORCE_RESET() (RCC->APB1RSTR = 0xFFFFFFFF) #define __HAL_RCC_TIM5_FORCE_RESET() (RCC->APB1RSTR |= (RCC_APB1RSTR_TIM5RST)) #define __HAL_RCC_WWDG_FORCE_RESET() (RCC->APB1RSTR |= (RCC_APB1RSTR_WWDGRST)) #define __HAL_RCC_SPI2_FORCE_RESET() (RCC->APB1RSTR |= (RCC_APB1RSTR_SPI2RST)) #define __HAL_RCC_USART2_FORCE_RESET() (RCC->APB1RSTR |= (RCC_APB1RSTR_USART2RST)) #define __HAL_RCC_I2C1_FORCE_RESET() (RCC->APB1RSTR |= (RCC_APB1RSTR_I2C1RST)) #define __HAL_RCC_I2C2_FORCE_RESET() (RCC->APB1RSTR |= (RCC_APB1RSTR_I2C2RST)) #define __HAL_RCC_PWR_FORCE_RESET() (RCC->APB1RSTR |= (RCC_APB1RSTR_PWRRST)) #define __HAL_RCC_APB1_RELEASE_RESET() (RCC->APB1RSTR = 0x00) #define __HAL_RCC_TIM5_RELEASE_RESET() (RCC->APB1RSTR &= ~(RCC_APB1RSTR_TIM5RST)) #define __HAL_RCC_WWDG_RELEASE_RESET() (RCC->APB1RSTR &= ~(RCC_APB1RSTR_WWDGRST)) #define __HAL_RCC_SPI2_RELEASE_RESET() (RCC->APB1RSTR &= ~(RCC_APB1RSTR_SPI2RST)) #define __HAL_RCC_USART2_RELEASE_RESET() (RCC->APB1RSTR &= ~(RCC_APB1RSTR_USART2RST)) #define __HAL_RCC_I2C1_RELEASE_RESET() (RCC->APB1RSTR &= ~(RCC_APB1RSTR_I2C1RST)) #define __HAL_RCC_I2C2_RELEASE_RESET() (RCC->APB1RSTR &= ~(RCC_APB1RSTR_I2C2RST)) #define __HAL_RCC_PWR_RELEASE_RESET() (RCC->APB1RSTR &= ~(RCC_APB1RSTR_PWRRST)) /** * @} */ /** @defgroup RCC_APB2_Force_Release_Reset APB2 Force Release Reset * @brief Force or release APB2 peripheral reset. * @{ */ #define __HAL_RCC_APB2_FORCE_RESET() (RCC->APB2RSTR = 0xFFFFFFFF) #define __HAL_RCC_TIM1_FORCE_RESET() (RCC->APB2RSTR |= (RCC_APB2RSTR_TIM1RST)) #define __HAL_RCC_USART1_FORCE_RESET() (RCC->APB2RSTR |= (RCC_APB2RSTR_USART1RST)) #define __HAL_RCC_USART6_FORCE_RESET() (RCC->APB2RSTR |= (RCC_APB2RSTR_USART6RST)) #define __HAL_RCC_ADC_FORCE_RESET() (RCC->APB2RSTR |= (RCC_APB2RSTR_ADCRST)) #define __HAL_RCC_SPI1_FORCE_RESET() (RCC->APB2RSTR |= (RCC_APB2RSTR_SPI1RST)) #define __HAL_RCC_SYSCFG_FORCE_RESET() (RCC->APB2RSTR |= (RCC_APB2RSTR_SYSCFGRST)) #define __HAL_RCC_TIM9_FORCE_RESET() (RCC->APB2RSTR |= (RCC_APB2RSTR_TIM9RST)) #define __HAL_RCC_TIM11_FORCE_RESET() (RCC->APB2RSTR |= (RCC_APB2RSTR_TIM11RST)) #define __HAL_RCC_APB2_RELEASE_RESET() (RCC->APB2RSTR = 0x00) #define __HAL_RCC_TIM1_RELEASE_RESET() (RCC->APB2RSTR &= ~(RCC_APB2RSTR_TIM1RST)) #define __HAL_RCC_USART1_RELEASE_RESET() (RCC->APB2RSTR &= ~(RCC_APB2RSTR_USART1RST)) #define __HAL_RCC_USART6_RELEASE_RESET() (RCC->APB2RSTR &= ~(RCC_APB2RSTR_USART6RST)) #define __HAL_RCC_ADC_RELEASE_RESET() (RCC->APB2RSTR &= ~(RCC_APB2RSTR_ADCRST)) #define __HAL_RCC_SPI1_RELEASE_RESET() (RCC->APB2RSTR &= ~(RCC_APB2RSTR_SPI1RST)) #define __HAL_RCC_SYSCFG_RELEASE_RESET() (RCC->APB2RSTR &= ~(RCC_APB2RSTR_SYSCFGRST)) #define __HAL_RCC_TIM9_RELEASE_RESET() (RCC->APB2RSTR &= ~(RCC_APB2RSTR_TIM9RST)) #define __HAL_RCC_TIM11_RELEASE_RESET() (RCC->APB2RSTR &= ~(RCC_APB2RSTR_TIM11RST)) /** * @} */ /** @defgroup RCC_AHB1_LowPower_Enable_Disable AHB1 Peripheral Low Power Enable Disable * @brief Enable or disable the AHB1 peripheral clock during Low Power (Sleep) mode. * @note Peripheral clock gating in SLEEP mode can be used to further reduce * power consumption. * @note After wake-up from SLEEP mode, the peripheral clock is enabled again. * @note By default, all peripheral clocks are enabled during SLEEP mode. * @{ */ #define __HAL_RCC_GPIOA_CLK_SLEEP_ENABLE() (RCC->AHB1LPENR |= (RCC_AHB1LPENR_GPIOALPEN)) #define __HAL_RCC_GPIOB_CLK_SLEEP_ENABLE() (RCC->AHB1LPENR |= (RCC_AHB1LPENR_GPIOBLPEN)) #define __HAL_RCC_GPIOC_CLK_SLEEP_ENABLE() (RCC->AHB1LPENR |= (RCC_AHB1LPENR_GPIOCLPEN)) #define __HAL_RCC_GPIOH_CLK_SLEEP_ENABLE() (RCC->AHB1LPENR |= (RCC_AHB1LPENR_GPIOHLPEN)) #define __HAL_RCC_DMA1_CLK_SLEEP_ENABLE() (RCC->AHB1LPENR |= (RCC_AHB1LPENR_DMA1LPEN)) #define __HAL_RCC_DMA2_CLK_SLEEP_ENABLE() (RCC->AHB1LPENR |= (RCC_AHB1LPENR_DMA2LPEN)) #define __HAL_RCC_GPIOA_CLK_SLEEP_DISABLE() (RCC->AHB1LPENR &= ~(RCC_AHB1LPENR_GPIOALPEN)) #define __HAL_RCC_GPIOB_CLK_SLEEP_DISABLE() (RCC->AHB1LPENR &= ~(RCC_AHB1LPENR_GPIOBLPEN)) #define __HAL_RCC_GPIOC_CLK_SLEEP_DISABLE() (RCC->AHB1LPENR &= ~(RCC_AHB1LPENR_GPIOCLPEN)) #define __HAL_RCC_GPIOH_CLK_SLEEP_DISABLE() (RCC->AHB1LPENR &= ~(RCC_AHB1LPENR_GPIOHLPEN)) #define __HAL_RCC_DMA1_CLK_SLEEP_DISABLE() (RCC->AHB1LPENR &= ~(RCC_AHB1LPENR_DMA1LPEN)) #define __HAL_RCC_DMA2_CLK_SLEEP_DISABLE() (RCC->AHB1LPENR &= ~(RCC_AHB1LPENR_DMA2LPEN)) /** * @} */ /** @defgroup RCC_APB1_LowPower_Enable_Disable APB1 Peripheral Low Power Enable Disable * @brief Enable or disable the APB1 peripheral clock during Low Power (Sleep) mode. * @note Peripheral clock gating in SLEEP mode can be used to further reduce * power consumption. * @note After wake-up from SLEEP mode, the peripheral clock is enabled again. * @note By default, all peripheral clocks are enabled during SLEEP mode. * @{ */ #define __HAL_RCC_TIM5_CLK_SLEEP_ENABLE() (RCC->APB1LPENR |= (RCC_APB1LPENR_TIM5LPEN)) #define __HAL_RCC_WWDG_CLK_SLEEP_ENABLE() (RCC->APB1LPENR |= (RCC_APB1LPENR_WWDGLPEN)) #define __HAL_RCC_SPI2_CLK_SLEEP_ENABLE() (RCC->APB1LPENR |= (RCC_APB1LPENR_SPI2LPEN)) #define __HAL_RCC_USART2_CLK_SLEEP_ENABLE() (RCC->APB1LPENR |= (RCC_APB1LPENR_USART2LPEN)) #define __HAL_RCC_I2C1_CLK_SLEEP_ENABLE() (RCC->APB1LPENR |= (RCC_APB1LPENR_I2C1LPEN)) #define __HAL_RCC_I2C2_CLK_SLEEP_ENABLE() (RCC->APB1LPENR |= (RCC_APB1LPENR_I2C2LPEN)) #define __HAL_RCC_PWR_CLK_SLEEP_ENABLE() (RCC->APB1LPENR |= (RCC_APB1LPENR_PWRLPEN)) #define __HAL_RCC_TIM5_CLK_SLEEP_DISABLE() (RCC->APB1LPENR &= ~(RCC_APB1LPENR_TIM5LPEN)) #define __HAL_RCC_WWDG_CLK_SLEEP_DISABLE() (RCC->APB1LPENR &= ~(RCC_APB1LPENR_WWDGLPEN)) #define __HAL_RCC_SPI2_CLK_SLEEP_DISABLE() (RCC->APB1LPENR &= ~(RCC_APB1LPENR_SPI2LPEN)) #define __HAL_RCC_USART2_CLK_SLEEP_DISABLE() (RCC->APB1LPENR &= ~(RCC_APB1LPENR_USART2LPEN)) #define __HAL_RCC_I2C1_CLK_SLEEP_DISABLE() (RCC->APB1LPENR &= ~(RCC_APB1LPENR_I2C1LPEN)) #define __HAL_RCC_I2C2_CLK_SLEEP_DISABLE() (RCC->APB1LPENR &= ~(RCC_APB1LPENR_I2C2LPEN)) #define __HAL_RCC_PWR_CLK_SLEEP_DISABLE() (RCC->APB1LPENR &= ~(RCC_APB1LPENR_PWRLPEN)) /** * @} */ /** @defgroup RCC_APB2_LowPower_Enable_Disable APB2 Peripheral Low Power Enable Disable * @brief Enable or disable the APB2 peripheral clock during Low Power (Sleep) mode. * @note Peripheral clock gating in SLEEP mode can be used to further reduce * power consumption. * @note After wake-up from SLEEP mode, the peripheral clock is enabled again. * @note By default, all peripheral clocks are enabled during SLEEP mode. * @{ */ #define __HAL_RCC_TIM1_CLK_SLEEP_ENABLE() (RCC->APB2LPENR |= (RCC_APB2LPENR_TIM1LPEN)) #define __HAL_RCC_USART1_CLK_SLEEP_ENABLE() (RCC->APB2LPENR |= (RCC_APB2LPENR_USART1LPEN)) #define __HAL_RCC_USART6_CLK_SLEEP_ENABLE() (RCC->APB2LPENR |= (RCC_APB2LPENR_USART6LPEN)) #define __HAL_RCC_ADC1_CLK_SLEEP_ENABLE() (RCC->APB2LPENR |= (RCC_APB2LPENR_ADC1LPEN)) #define __HAL_RCC_SPI1_CLK_SLEEP_ENABLE() (RCC->APB2LPENR |= (RCC_APB2LPENR_SPI1LPEN)) #define __HAL_RCC_SYSCFG_CLK_SLEEP_ENABLE() (RCC->APB2LPENR |= (RCC_APB2LPENR_SYSCFGLPEN)) #define __HAL_RCC_TIM9_CLK_SLEEP_ENABLE() (RCC->APB2LPENR |= (RCC_APB2LPENR_TIM9LPEN)) #define __HAL_RCC_TIM11_CLK_SLEEP_ENABLE() (RCC->APB2LPENR |= (RCC_APB2LPENR_TIM11LPEN)) #define __HAL_RCC_TIM1_CLK_SLEEP_DISABLE() (RCC->APB2LPENR &= ~(RCC_APB2LPENR_TIM1LPEN)) #define __HAL_RCC_USART1_CLK_SLEEP_DISABLE() (RCC->APB2LPENR &= ~(RCC_APB2LPENR_USART1LPEN)) #define __HAL_RCC_USART6_CLK_SLEEP_DISABLE() (RCC->APB2LPENR &= ~(RCC_APB2LPENR_USART6LPEN)) #define __HAL_RCC_ADC1_CLK_SLEEP_DISABLE() (RCC->APB2LPENR &= ~(RCC_APB2LPENR_ADC1LPEN)) #define __HAL_RCC_SPI1_CLK_SLEEP_DISABLE() (RCC->APB2LPENR &= ~(RCC_APB2LPENR_SPI1LPEN)) #define __HAL_RCC_SYSCFG_CLK_SLEEP_DISABLE() (RCC->APB2LPENR &= ~(RCC_APB2LPENR_SYSCFGLPEN)) #define __HAL_RCC_TIM9_CLK_SLEEP_DISABLE() (RCC->APB2LPENR &= ~(RCC_APB2LPENR_TIM9LPEN)) #define __HAL_RCC_TIM11_CLK_SLEEP_DISABLE() (RCC->APB2LPENR &= ~(RCC_APB2LPENR_TIM11LPEN)) /** * @} */ /** @defgroup RCC_HSI_Configuration HSI Configuration * @{ */ /** @brief Macros to enable or disable the Internal High Speed oscillator (HSI). * @note The HSI is stopped by hardware when entering STOP and STANDBY modes. * It is used (enabled by hardware) as system clock source after startup * from Reset, wake-up from STOP and STANDBY mode, or in case of failure * of the HSE used directly or indirectly as system clock (if the Clock * Security System CSS is enabled). * @note HSI can not be stopped if it is used as system clock source. In this case, * you have to select another source of the system clock then stop the HSI. * @note After enabling the HSI, the application software should wait on HSIRDY * flag to be set indicating that HSI clock is stable and can be used as * system clock source. * This parameter can be: ENABLE or DISABLE. * @note When the HSI is stopped, HSIRDY flag goes low after 6 HSI oscillator * clock cycles. */ #define __HAL_RCC_HSI_ENABLE() (*(__IO uint32_t *) RCC_CR_HSION_BB = ENABLE) #define __HAL_RCC_HSI_DISABLE() (*(__IO uint32_t *) RCC_CR_HSION_BB = DISABLE) /** @brief Macro to adjust the Internal High Speed oscillator (HSI) calibration value. * @note The calibration is used to compensate for the variations in voltage * and temperature that influence the frequency of the internal HSI RC. * @param __HSICalibrationValue__: specifies the calibration trimming value. * This parameter must be a number between 0 and 0x1F. */ #define __HAL_RCC_HSI_CALIBRATIONVALUE_ADJUST(__HSICalibrationValue__) (MODIFY_REG(RCC->CR,\ RCC_CR_HSITRIM, (uint32_t)(__HSICalibrationValue__) << POSITION_VAL(RCC_CR_HSITRIM))) /** * @} */ /** @defgroup RCC_LSI_Configuration LSI Configuration * @{ */ /** @brief Macros to enable or disable the Internal Low Speed oscillator (LSI). * @note After enabling the LSI, the application software should wait on * LSIRDY flag to be set indicating that LSI clock is stable and can * be used to clock the IWDG and/or the RTC. * @note LSI can not be disabled if the IWDG is running. * @note When the LSI is stopped, LSIRDY flag goes low after 6 LSI oscillator * clock cycles. */ #define __HAL_RCC_LSI_ENABLE() (*(__IO uint32_t *) RCC_CSR_LSION_BB = ENABLE) #define __HAL_RCC_LSI_DISABLE() (*(__IO uint32_t *) RCC_CSR_LSION_BB = DISABLE) /** * @} */ /** @defgroup RCC_HSE_Configuration HSE Configuration * @{ */ /** * @brief Macro to configure the External High Speed oscillator (HSE). * @note Transition HSE Bypass to HSE On and HSE On to HSE Bypass are not supported by this macro. * User should request a transition to HSE Off first and then HSE On or HSE Bypass. * @note After enabling the HSE (RCC_HSE_ON or RCC_HSE_Bypass), the application * software should wait on HSERDY flag to be set indicating that HSE clock * is stable and can be used to clock the PLL and/or system clock. * @note HSE state can not be changed if it is used directly or through the * PLL as system clock. In this case, you have to select another source * of the system clock then change the HSE state (ex. disable it). * @note The HSE is stopped by hardware when entering STOP and STANDBY modes. * @note This function reset the CSSON bit, so if the clock security system(CSS) * was previously enabled you have to enable it again after calling this * function. * @param __STATE__: specifies the new state of the HSE. * This parameter can be one of the following values: * @arg RCC_HSE_OFF: turn OFF the HSE oscillator, HSERDY flag goes low after * 6 HSE oscillator clock cycles. * @arg RCC_HSE_ON: turn ON the HSE oscillator. * @arg RCC_HSE_BYPASS: HSE oscillator bypassed with external clock. */ #define __HAL_RCC_HSE_CONFIG(__STATE__) (*(__IO uint8_t *) RCC_CR_BYTE2_ADDRESS = (__STATE__)) /** * @} */ /** @defgroup RCC_LSE_Configuration LSE Configuration * @{ */ /** * @brief Macro to configure the External Low Speed oscillator (LSE). * @note Transition LSE Bypass to LSE On and LSE On to LSE Bypass are not supported by this macro. * User should request a transition to LSE Off first and then LSE On or LSE Bypass. * @note As the LSE is in the Backup domain and write access is denied to * this domain after reset, you have to enable write access using * HAL_PWR_EnableBkUpAccess() function before to configure the LSE * (to be done once after reset). * @note After enabling the LSE (RCC_LSE_ON or RCC_LSE_BYPASS), the application * software should wait on LSERDY flag to be set indicating that LSE clock * is stable and can be used to clock the RTC. * @param __STATE__: specifies the new state of the LSE. * This parameter can be one of the following values: * @arg RCC_LSE_OFF: turn OFF the LSE oscillator, LSERDY flag goes low after * 6 LSE oscillator clock cycles. * @arg RCC_LSE_ON: turn ON the LSE oscillator. * @arg RCC_LSE_BYPASS: LSE oscillator bypassed with external clock. */ #define __HAL_RCC_LSE_CONFIG(__STATE__) (*(__IO uint8_t *) RCC_BDCR_BYTE0_ADDRESS = (__STATE__)) /** * @} */ /** @defgroup RCC_Internal_RTC_Clock_Configuration RTC Clock Configuration * @{ */ /** @brief Macros to enable or disable the RTC clock. * @note These macros must be used only after the RTC clock source was selected. */ #define __HAL_RCC_RTC_ENABLE() (*(__IO uint32_t *) RCC_BDCR_RTCEN_BB = ENABLE) #define __HAL_RCC_RTC_DISABLE() (*(__IO uint32_t *) RCC_BDCR_RTCEN_BB = DISABLE) /** @brief Macros to configure the RTC clock (RTCCLK). * @note As the RTC clock configuration bits are in the Backup domain and write * access is denied to this domain after reset, you have to enable write * access using the Power Backup Access macro before to configure * the RTC clock source (to be done once after reset). * @note Once the RTC clock is configured it can't be changed unless the * Backup domain is reset using __HAL_RCC_BackupReset_RELEASE() macro, or by * a Power On Reset (POR). * @param __RTCCLKSource__: specifies the RTC clock source. * This parameter can be one of the following values: * @arg RCC_RTCCLKSOURCE_LSE: LSE selected as RTC clock. * @arg RCC_RTCCLKSOURCE_LSI: LSI selected as RTC clock. * @arg RCC_RTCCLKSOURCE_HSE_DIVx: HSE clock divided by x selected * as RTC clock, where x:[2,31] * @note If the LSE or LSI is used as RTC clock source, the RTC continues to * work in STOP and STANDBY modes, and can be used as wake-up source. * However, when the HSE clock is used as RTC clock source, the RTC * cannot be used in STOP and STANDBY modes. * @note The maximum input clock frequency for RTC is 1MHz (when using HSE as * RTC clock source). */ #define __HAL_RCC_RTC_CLKPRESCALER(__RTCCLKSource__) (((__RTCCLKSource__) & RCC_BDCR_RTCSEL) == RCC_BDCR_RTCSEL) ? \ MODIFY_REG(RCC->CFGR, RCC_CFGR_RTCPRE, ((__RTCCLKSource__) & 0xFFFFCFF)) : CLEAR_BIT(RCC->CFGR, RCC_CFGR_RTCPRE) #define __HAL_RCC_RTC_CONFIG(__RTCCLKSource__) do { __HAL_RCC_RTC_CLKPRESCALER(__RTCCLKSource__); \ RCC->BDCR |= ((__RTCCLKSource__) & 0x00000FFF); \ } while (0) /** @brief Macros to force or release the Backup domain reset. * @note This function resets the RTC peripheral (including the backup registers) * and the RTC clock source selection in RCC_CSR register. * @note The BKPSRAM is not affected by this reset. */ #define __HAL_RCC_BACKUPRESET_FORCE() (*(__IO uint32_t *) RCC_BDCR_BDRST_BB = ENABLE) #define __HAL_RCC_BACKUPRESET_RELEASE() (*(__IO uint32_t *) RCC_BDCR_BDRST_BB = DISABLE) /** * @} */ /** @defgroup RCC_PLL_Configuration PLL Configuration * @{ */ /** @brief Macros to enable or disable the main PLL. * @note After enabling the main PLL, the application software should wait on * PLLRDY flag to be set indicating that PLL clock is stable and can * be used as system clock source. * @note The main PLL can not be disabled if it is used as system clock source * @note The main PLL is disabled by hardware when entering STOP and STANDBY modes. */ #define __HAL_RCC_PLL_ENABLE() (*(__IO uint32_t *) RCC_CR_PLLON_BB = ENABLE) #define __HAL_RCC_PLL_DISABLE() (*(__IO uint32_t *) RCC_CR_PLLON_BB = DISABLE) /** @brief Macro to configure the PLL clock source. * @note This function must be used only when the main PLL is disabled. * @param __PLLSOURCE__: specifies the PLL entry clock source. * This parameter can be one of the following values: * @arg RCC_PLLSOURCE_HSI: HSI oscillator clock selected as PLL clock entry * @arg RCC_PLLSOURCE_HSE: HSE oscillator clock selected as PLL clock entry * */ #define __HAL_RCC_PLL_PLLSOURCE_CONFIG(__PLLSOURCE__) MODIFY_REG(RCC->PLLCFGR, RCC_PLLCFGR_PLLSRC, (__PLLSOURCE__)) /** @brief Macro to configure the PLL multiplication factor. * @note This function must be used only when the main PLL is disabled. * @param __PLLM__: specifies the division factor for PLL VCO input clock * This parameter must be a number between Min_Data = 2 and Max_Data = 63. * @note You have to set the PLLM parameter correctly to ensure that the VCO input * frequency ranges from 1 to 2 MHz. It is recommended to select a frequency * of 2 MHz to limit PLL jitter. * */ #define __HAL_RCC_PLL_PLLM_CONFIG(__PLLM__) MODIFY_REG(RCC->PLLCFGR, RCC_PLLCFGR_PLLM, (__PLLM__)) /** * @} */ /** @defgroup RCC_Get_Clock_source Get Clock source * @{ */ /** * @brief Macro to configure the system clock source. * @param __RCC_SYSCLKSOURCE__: specifies the system clock source. * This parameter can be one of the following values: * - RCC_SYSCLKSOURCE_HSI: HSI oscillator is used as system clock source. * - RCC_SYSCLKSOURCE_HSE: HSE oscillator is used as system clock source. * - RCC_SYSCLKSOURCE_PLLCLK: PLL output is used as system clock source. * - RCC_SYSCLKSOURCE_PLLRCLK: PLLR output is used as system clock source. */ #define __HAL_RCC_SYSCLK_CONFIG(__RCC_SYSCLKSOURCE__) MODIFY_REG(RCC->CFGR, RCC_CFGR_SW, (__RCC_SYSCLKSOURCE__)) /** @brief Macro to get the clock source used as system clock. * @retval The clock source used as system clock. The returned value can be one * of the following: * - RCC_SYSCLKSOURCE_STATUS_HSI: HSI used as system clock. * - RCC_SYSCLKSOURCE_STATUS_HSE: HSE used as system clock. * - RCC_SYSCLKSOURCE_STATUS_PLLCLK: PLL used as system clock. * - RCC_SYSCLKSOURCE_STATUS_PLLRCLK: PLLR used as system clock. */ #define __HAL_RCC_GET_SYSCLK_SOURCE() ((uint32_t)(RCC->CFGR & RCC_CFGR_SWS)) /** @brief Macro to get the oscillator used as PLL clock source. * @retval The oscillator used as PLL clock source. The returned value can be one * of the following: * - RCC_PLLSOURCE_HSI: HSI oscillator is used as PLL clock source. * - RCC_PLLSOURCE_HSE: HSE oscillator is used as PLL clock source. */ #define __HAL_RCC_GET_PLL_OSCSOURCE() ((uint32_t)(RCC->PLLCFGR & RCC_PLLCFGR_PLLSRC)) /** * @} */ /** @defgroup RCCEx_MCOx_Clock_Config RCC Extended MCOx Clock Config * @{ */ /** @brief Macro to configure the MCO1 clock. * @param __MCOCLKSOURCE__ specifies the MCO clock source. * This parameter can be one of the following values: * @arg RCC_MCO1SOURCE_HSI: HSI clock selected as MCO1 source * @arg RCC_MCO1SOURCE_LSE: LSE clock selected as MCO1 source * @arg RCC_MCO1SOURCE_HSE: HSE clock selected as MCO1 source * @arg RCC_MCO1SOURCE_PLLCLK: main PLL clock selected as MCO1 source * @param __MCODIV__ specifies the MCO clock prescaler. * This parameter can be one of the following values: * @arg RCC_MCODIV_1: no division applied to MCOx clock * @arg RCC_MCODIV_2: division by 2 applied to MCOx clock * @arg RCC_MCODIV_3: division by 3 applied to MCOx clock * @arg RCC_MCODIV_4: division by 4 applied to MCOx clock * @arg RCC_MCODIV_5: division by 5 applied to MCOx clock */ #define __HAL_RCC_MCO1_CONFIG(__MCOCLKSOURCE__, __MCODIV__) \ MODIFY_REG(RCC->CFGR, (RCC_CFGR_MCO1 | RCC_CFGR_MCO1PRE), ((__MCOCLKSOURCE__) | (__MCODIV__))) /** @brief Macro to configure the MCO2 clock. * @param __MCOCLKSOURCE__ specifies the MCO clock source. * This parameter can be one of the following values: * @arg RCC_MCO2SOURCE_SYSCLK: System clock (SYSCLK) selected as MCO2 source * @arg RCC_MCO2SOURCE_PLLI2SCLK: PLLI2S clock selected as MCO2 source, available for all STM32F4 devices except STM32F410xx * @arg RCC_MCO2SOURCE_I2SCLK: I2SCLK clock selected as MCO2 source, available only for STM32F410Rx devices * @arg RCC_MCO2SOURCE_HSE: HSE clock selected as MCO2 source * @arg RCC_MCO2SOURCE_PLLCLK: main PLL clock selected as MCO2 source * @param __MCODIV__ specifies the MCO clock prescaler. * This parameter can be one of the following values: * @arg RCC_MCODIV_1: no division applied to MCOx clock * @arg RCC_MCODIV_2: division by 2 applied to MCOx clock * @arg RCC_MCODIV_3: division by 3 applied to MCOx clock * @arg RCC_MCODIV_4: division by 4 applied to MCOx clock * @arg RCC_MCODIV_5: division by 5 applied to MCOx clock * @note For STM32F410Rx devices to output I2SCLK clock on MCO2 you should have * at last one of the SPI clocks enabled (SPI1, SPI2 or SPI5). */ #define __HAL_RCC_MCO2_CONFIG(__MCOCLKSOURCE__, __MCODIV__) \ MODIFY_REG(RCC->CFGR, (RCC_CFGR_MCO2 | RCC_CFGR_MCO2PRE), (__MCOCLKSOURCE__ | (__MCODIV__ << 3))); /** * @} */ /** @defgroup RCC_Flags_Interrupts_Management Flags Interrupts Management * @brief macros to manage the specified RCC Flags and interrupts. * @{ */ /** @brief Enable RCC interrupt (Perform Byte access to RCC_CIR[14:8] bits to enable * the selected interrupts). * @param __INTERRUPT__: specifies the RCC interrupt sources to be enabled. * This parameter can be any combination of the following values: * @arg RCC_IT_LSIRDY: LSI ready interrupt. * @arg RCC_IT_LSERDY: LSE ready interrupt. * @arg RCC_IT_HSIRDY: HSI ready interrupt. * @arg RCC_IT_HSERDY: HSE ready interrupt. * @arg RCC_IT_PLLRDY: Main PLL ready interrupt. * @arg RCC_IT_PLLI2SRDY: PLLI2S ready interrupt. */ #define __HAL_RCC_ENABLE_IT(__INTERRUPT__) (*(__IO uint8_t *) RCC_CIR_BYTE1_ADDRESS |= (__INTERRUPT__)) /** @brief Disable RCC interrupt (Perform Byte access to RCC_CIR[14:8] bits to disable * the selected interrupts). * @param __INTERRUPT__: specifies the RCC interrupt sources to be disabled. * This parameter can be any combination of the following values: * @arg RCC_IT_LSIRDY: LSI ready interrupt. * @arg RCC_IT_LSERDY: LSE ready interrupt. * @arg RCC_IT_HSIRDY: HSI ready interrupt. * @arg RCC_IT_HSERDY: HSE ready interrupt. * @arg RCC_IT_PLLRDY: Main PLL ready interrupt. * @arg RCC_IT_PLLI2SRDY: PLLI2S ready interrupt. */ #define __HAL_RCC_DISABLE_IT(__INTERRUPT__) (*(__IO uint8_t *) RCC_CIR_BYTE1_ADDRESS &= ~(__INTERRUPT__)) /** @brief Clear the RCC's interrupt pending bits (Perform Byte access to RCC_CIR[23:16] * bits to clear the selected interrupt pending bits. * @param __INTERRUPT__: specifies the interrupt pending bit to clear. * This parameter can be any combination of the following values: * @arg RCC_IT_LSIRDY: LSI ready interrupt. * @arg RCC_IT_LSERDY: LSE ready interrupt. * @arg RCC_IT_HSIRDY: HSI ready interrupt. * @arg RCC_IT_HSERDY: HSE ready interrupt. * @arg RCC_IT_PLLRDY: Main PLL ready interrupt. * @arg RCC_IT_PLLI2SRDY: PLLI2S ready interrupt. * @arg RCC_IT_CSS: Clock Security System interrupt */ #define __HAL_RCC_CLEAR_IT(__INTERRUPT__) (*(__IO uint8_t *) RCC_CIR_BYTE2_ADDRESS = (__INTERRUPT__)) /** @brief Check the RCC's interrupt has occurred or not. * @param __INTERRUPT__: specifies the RCC interrupt source to check. * This parameter can be one of the following values: * @arg RCC_IT_LSIRDY: LSI ready interrupt. * @arg RCC_IT_LSERDY: LSE ready interrupt. * @arg RCC_IT_HSIRDY: HSI ready interrupt. * @arg RCC_IT_HSERDY: HSE ready interrupt. * @arg RCC_IT_PLLRDY: Main PLL ready interrupt. * @arg RCC_IT_PLLI2SRDY: PLLI2S ready interrupt. * @arg RCC_IT_CSS: Clock Security System interrupt * @retval The new state of __INTERRUPT__ (TRUE or FALSE). */ #define __HAL_RCC_GET_IT(__INTERRUPT__) ((RCC->CIR & (__INTERRUPT__)) == (__INTERRUPT__)) /** @brief Set RMVF bit to clear the reset flags: RCC_FLAG_PINRST, RCC_FLAG_PORRST, * RCC_FLAG_SFTRST, RCC_FLAG_IWDGRST, RCC_FLAG_WWDGRST and RCC_FLAG_LPWRRST. */ #define __HAL_RCC_CLEAR_RESET_FLAGS() (RCC->CSR |= RCC_CSR_RMVF) /** @brief Check RCC flag is set or not. * @param __FLAG__: specifies the flag to check. * This parameter can be one of the following values: * @arg RCC_FLAG_HSIRDY: HSI oscillator clock ready. * @arg RCC_FLAG_HSERDY: HSE oscillator clock ready. * @arg RCC_FLAG_PLLRDY: Main PLL clock ready. * @arg RCC_FLAG_PLLI2SRDY: PLLI2S clock ready. * @arg RCC_FLAG_LSERDY: LSE oscillator clock ready. * @arg RCC_FLAG_LSIRDY: LSI oscillator clock ready. * @arg RCC_FLAG_BORRST: POR/PDR or BOR reset. * @arg RCC_FLAG_PINRST: Pin reset. * @arg RCC_FLAG_PORRST: POR/PDR reset. * @arg RCC_FLAG_SFTRST: Software reset. * @arg RCC_FLAG_IWDGRST: Independent Watchdog reset. * @arg RCC_FLAG_WWDGRST: Window Watchdog reset. * @arg RCC_FLAG_LPWRRST: Low Power reset. * @retval The new state of __FLAG__ (TRUE or FALSE). */ #define RCC_FLAG_MASK ((uint8_t)0x1F) #define __HAL_RCC_GET_FLAG(__FLAG__) (((((((__FLAG__) >> 5) == 1)? RCC->CR :((((__FLAG__) >> 5) == 2) ? RCC->BDCR :((((__FLAG__) >> 5) == 3)? RCC->CSR :RCC->CIR))) & ((uint32_t)1 << ((__FLAG__) & RCC_FLAG_MASK)))!= 0)? 1 : 0) /** * @} */ /** * @} */ /* Exported functions --------------------------------------------------------*/ /** @addtogroup RCC_Exported_Functions * @{ */ /** @addtogroup RCC_Exported_Functions_Group1 * @{ */ /* Initialization and de-initialization functions ******************************/ void HAL_RCC_DeInit(void); HAL_StatusTypeDef HAL_RCC_OscConfig(RCC_OscInitTypeDef *RCC_OscInitStruct); HAL_StatusTypeDef HAL_RCC_ClockConfig(RCC_ClkInitTypeDef *RCC_ClkInitStruct, uint32_t FLatency); /** * @} */ /** @addtogroup RCC_Exported_Functions_Group2 * @{ */ /* Peripheral Control functions ************************************************/ void HAL_RCC_MCOConfig(uint32_t RCC_MCOx, uint32_t RCC_MCOSource, uint32_t RCC_MCODiv); void HAL_RCC_EnableCSS(void); void HAL_RCC_DisableCSS(void); uint32_t HAL_RCC_GetSysClockFreq(void); uint32_t HAL_RCC_GetHCLKFreq(void); uint32_t HAL_RCC_GetPCLK1Freq(void); uint32_t HAL_RCC_GetPCLK2Freq(void); void HAL_RCC_GetOscConfig(RCC_OscInitTypeDef *RCC_OscInitStruct); void HAL_RCC_GetClockConfig(RCC_ClkInitTypeDef *RCC_ClkInitStruct, uint32_t *pFLatency); /* CSS NMI IRQ handler */ void HAL_RCC_NMI_IRQHandler(void); /* User Callbacks in non blocking mode (IT mode) */ void HAL_RCC_CSSCallback(void); /** * @} */ /** * @} */ /* Private types -------------------------------------------------------------*/ /* Private variables ---------------------------------------------------------*/ /* Private constants ---------------------------------------------------------*/ /** @defgroup RCC_Private_Constants RCC Private Constants * @{ */ /** @defgroup RCC_BitAddress_AliasRegion RCC BitAddress AliasRegion * @brief RCC registers bit address in the alias region * @{ */ #define RCC_OFFSET (RCC_BASE - PERIPH_BASE) /* --- CR Register ---*/ /* Alias word address of HSION bit */ #define RCC_CR_OFFSET (RCC_OFFSET + 0x00) #define RCC_HSION_BIT_NUMBER 0x00 #define RCC_CR_HSION_BB (PERIPH_BB_BASE + (RCC_CR_OFFSET * 32) + (RCC_HSION_BIT_NUMBER * 4)) /* Alias word address of CSSON bit */ #define RCC_CSSON_BIT_NUMBER 0x13 #define RCC_CR_CSSON_BB (PERIPH_BB_BASE + (RCC_CR_OFFSET * 32) + (RCC_CSSON_BIT_NUMBER * 4)) /* Alias word address of PLLON bit */ #define RCC_PLLON_BIT_NUMBER 0x18 #define RCC_CR_PLLON_BB (PERIPH_BB_BASE + (RCC_CR_OFFSET * 32) + (RCC_PLLON_BIT_NUMBER * 4)) /* --- BDCR Register ---*/ /* Alias word address of RTCEN bit */ #define RCC_BDCR_OFFSET (RCC_OFFSET + 0x70) #define RCC_RTCEN_BIT_NUMBER 0x0F #define RCC_BDCR_RTCEN_BB (PERIPH_BB_BASE + (RCC_BDCR_OFFSET * 32) + (RCC_RTCEN_BIT_NUMBER * 4)) /* Alias word address of BDRST bit */ #define RCC_BDRST_BIT_NUMBER 0x10 #define RCC_BDCR_BDRST_BB (PERIPH_BB_BASE + (RCC_BDCR_OFFSET * 32) + (RCC_BDRST_BIT_NUMBER * 4)) /* --- CSR Register ---*/ /* Alias word address of LSION bit */ #define RCC_CSR_OFFSET (RCC_OFFSET + 0x74) #define RCC_LSION_BIT_NUMBER 0x00 #define RCC_CSR_LSION_BB (PERIPH_BB_BASE + (RCC_CSR_OFFSET * 32) + (RCC_LSION_BIT_NUMBER * 4)) /* CR register byte 3 (Bits[23:16]) base address */ #define RCC_CR_BYTE2_ADDRESS ((uint32_t)0x40023802) /* CIR register byte 2 (Bits[15:8]) base address */ #define RCC_CIR_BYTE1_ADDRESS ((uint32_t)(RCC_BASE + 0x0C + 0x01)) /* CIR register byte 3 (Bits[23:16]) base address */ #define RCC_CIR_BYTE2_ADDRESS ((uint32_t)(RCC_BASE + 0x0C + 0x02)) /* BDCR register base address */ #define RCC_BDCR_BYTE0_ADDRESS (PERIPH_BASE + RCC_BDCR_OFFSET) #define RCC_DBP_TIMEOUT_VALUE ((uint32_t)100) #define RCC_LSE_TIMEOUT_VALUE ((uint32_t)100) /* 100 ms */ #define HSE_TIMEOUT_VALUE HSE_STARTUP_TIMEOUT #define HSI_TIMEOUT_VALUE ((uint32_t)100) /* 100 ms */ #define LSI_TIMEOUT_VALUE ((uint32_t)100) /* 100 ms */ /** * @} */ /** * @} */ /* Private macros ------------------------------------------------------------*/ /** @addtogroup RCC_Private_Macros RCC Private Macros * @{ */ /** @defgroup RCC_IS_RCC_Definitions RCC Private macros to check input parameters * @{ */ #define IS_RCC_OSCILLATORTYPE(OSCILLATOR) ((OSCILLATOR) <= 15) #define IS_RCC_HSE(HSE) (((HSE) == RCC_HSE_OFF) || ((HSE) == RCC_HSE_ON) || \ ((HSE) == RCC_HSE_BYPASS)) #define IS_RCC_LSE(LSE) (((LSE) == RCC_LSE_OFF) || ((LSE) == RCC_LSE_ON) || \ ((LSE) == RCC_LSE_BYPASS)) #define IS_RCC_HSI(HSI) (((HSI) == RCC_HSI_OFF) || ((HSI) == RCC_HSI_ON)) #define IS_RCC_LSI(LSI) (((LSI) == RCC_LSI_OFF) || ((LSI) == RCC_LSI_ON)) #define IS_RCC_PLL(PLL) (((PLL) == RCC_PLL_NONE) ||((PLL) == RCC_PLL_OFF) || ((PLL) == RCC_PLL_ON)) #define IS_RCC_PLLSOURCE(SOURCE) (((SOURCE) == RCC_PLLSOURCE_HSI) || \ ((SOURCE) == RCC_PLLSOURCE_HSE)) #define IS_RCC_SYSCLKSOURCE(SOURCE) (((SOURCE) == RCC_SYSCLKSOURCE_HSI) || \ ((SOURCE) == RCC_SYSCLKSOURCE_HSE) || \ ((SOURCE) == RCC_SYSCLKSOURCE_PLLCLK) || \ ((SOURCE) == RCC_SYSCLKSOURCE_PLLRCLK)) #define IS_RCC_PLLM_VALUE(VALUE) ((VALUE) <= 63) #define IS_RCC_PLLN_VALUE(VALUE) ((192 <= (VALUE)) && ((VALUE) <= 432)) #define IS_RCC_PLLP_VALUE(VALUE) (((VALUE) == 2) || ((VALUE) == 4) || ((VALUE) == 6) || ((VALUE) == 8)) #define IS_RCC_PLLQ_VALUE(VALUE) ((4 <= (VALUE)) && ((VALUE) <= 15)) #define IS_RCC_HCLK(HCLK) (((HCLK) == RCC_SYSCLK_DIV1) || ((HCLK) == RCC_SYSCLK_DIV2) || \ ((HCLK) == RCC_SYSCLK_DIV4) || ((HCLK) == RCC_SYSCLK_DIV8) || \ ((HCLK) == RCC_SYSCLK_DIV16) || ((HCLK) == RCC_SYSCLK_DIV64) || \ ((HCLK) == RCC_SYSCLK_DIV128) || ((HCLK) == RCC_SYSCLK_DIV256) || \ ((HCLK) == RCC_SYSCLK_DIV512)) #define IS_RCC_CLOCKTYPE(CLK) ((1 <= (CLK)) && ((CLK) <= 15)) #define IS_RCC_PCLK(PCLK) (((PCLK) == RCC_HCLK_DIV1) || ((PCLK) == RCC_HCLK_DIV2) || \ ((PCLK) == RCC_HCLK_DIV4) || ((PCLK) == RCC_HCLK_DIV8) || \ ((PCLK) == RCC_HCLK_DIV16)) #define IS_RCC_MCO(MCOx) (((MCOx) == RCC_MCO1) || ((MCOx) == RCC_MCO2)) #define IS_RCC_MCO1SOURCE(SOURCE) (((SOURCE) == RCC_MCO1SOURCE_HSI) || ((SOURCE) == RCC_MCO1SOURCE_LSE) || \ ((SOURCE) == RCC_MCO1SOURCE_HSE) || ((SOURCE) == RCC_MCO1SOURCE_PLLCLK)) #define IS_RCC_MCODIV(DIV) (((DIV) == RCC_MCODIV_1) || ((DIV) == RCC_MCODIV_2) || \ ((DIV) == RCC_MCODIV_3) || ((DIV) == RCC_MCODIV_4) || \ ((DIV) == RCC_MCODIV_5)) #define IS_RCC_CALIBRATION_VALUE(VALUE) ((VALUE) <= 0x1F) /** * @} */ /** * @} */ /** * @} */ /** * @} */ #ifdef __cplusplus } #endif #endif /* __STM32F4xx_HAL_RCC_H */ /************************ (C) COPYRIGHT STMicroelectronics *****END OF FILE****/ ================================================ FILE: Zelig/mbed/TARGET_NUCLEO_F411RE/stm32f4xx_hal_rcc_ex.h ================================================ /** ****************************************************************************** * @file stm32f4xx_hal_rcc_ex.h * @author MCD Application Team * @version V1.4.1 * @date 09-October-2015 * @brief Header file of RCC HAL Extension module. ****************************************************************************** * @attention * *

© COPYRIGHT(c) 2015 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. * ****************************************************************************** */ /* Define to prevent recursive inclusion -------------------------------------*/ #ifndef __STM32F4xx_HAL_RCC_EX_H #define __STM32F4xx_HAL_RCC_EX_H #ifdef __cplusplus extern "C" { #endif /* Includes ------------------------------------------------------------------*/ #include "stm32f4xx_hal_def.h" /** @addtogroup STM32F4xx_HAL_Driver * @{ */ /** @addtogroup RCCEx * @{ */ /* Exported types ------------------------------------------------------------*/ /** @defgroup RCCEx_Exported_Types RCCEx Exported Types * @{ */ /** * @brief RCC PLL configuration structure definition */ typedef struct { uint32_t PLLState; /*!< The new state of the PLL. This parameter can be a value of @ref RCC_PLL_Config */ uint32_t PLLSource; /*!< RCC_PLLSource: PLL entry clock source. This parameter must be a value of @ref RCC_PLL_Clock_Source */ uint32_t PLLM; /*!< PLLM: Division factor for PLL VCO input clock. This parameter must be a number between Min_Data = 0 and Max_Data = 63 */ uint32_t PLLN; /*!< PLLN: Multiplication factor for PLL VCO output clock. This parameter must be a number between Min_Data = 192 and Max_Data = 432 */ uint32_t PLLP; /*!< PLLP: Division factor for main system clock (SYSCLK). This parameter must be a value of @ref RCC_PLLP_Clock_Divider */ uint32_t PLLQ; /*!< PLLQ: Division factor for OTG FS, SDIO and RNG clocks. This parameter must be a number between Min_Data = 4 and Max_Data = 15 */ #if defined(STM32F410Tx) || defined(STM32F410Cx) || defined(STM32F410Rx) || defined(STM32F446xx) || defined(STM32F469xx) ||\ defined(STM32F479xx) uint32_t PLLR; /*!< PLLR: PLL division factor for I2S, SAI, SYSTEM, SPDIFRX clocks. This parameter is only available in STM32F410xx/STM32F446xx/STM32F469xx and STM32F479xx devices. This parameter must be a number between Min_Data = 2 and Max_Data = 7 */ #endif /* STM32F410xx || STM32F446xx || STM32F469xx || STM32F479xx */ }RCC_PLLInitTypeDef; #if defined(STM32F446xx) /** * @brief PLLI2S Clock structure definition */ typedef struct { uint32_t PLLI2SM; /*!< Specifies division factor for PLL VCO input clock. This parameter must be a number between Min_Data = 2 and Max_Data = 63 */ uint32_t PLLI2SN; /*!< Specifies the multiplication factor for PLLI2S VCO output clock. This parameter must be a number between Min_Data = 192 and Max_Data = 432 */ uint32_t PLLI2SP; /*!< Specifies division factor for SPDIFRX Clock. This parameter must be a value of @ref RCCEx_PLLI2SP_Clock_Divider */ uint32_t PLLI2SQ; /*!< Specifies the division factor for SAI clock. This parameter must be a number between Min_Data = 2 and Max_Data = 15. This parameter will be used only when PLLI2S is selected as Clock Source SAI */ uint32_t PLLI2SR; /*!< Specifies the division factor for I2S clock. This parameter must be a number between Min_Data = 2 and Max_Data = 7. This parameter will be used only when PLLI2S is selected as Clock Source I2S */ }RCC_PLLI2SInitTypeDef; /** * @brief PLLSAI Clock structure definition */ typedef struct { uint32_t PLLSAIM; /*!< Spcifies division factor for PLL VCO input clock. This parameter must be a number between Min_Data = 2 and Max_Data = 63 */ uint32_t PLLSAIN; /*!< Specifies the multiplication factor for PLLI2S VCO output clock. This parameter must be a number between Min_Data = 192 and Max_Data = 432 */ uint32_t PLLSAIP; /*!< Specifies division factor for OTG FS, SDIO and RNG clocks. This parameter must be a value of @ref RCCEx_PLLSAIP_Clock_Divider */ uint32_t PLLSAIQ; /*!< Specifies the division factor for SAI clock. This parameter must be a number between Min_Data = 2 and Max_Data = 15. This parameter will be used only when PLLSAI is selected as Clock Source SAI */ }RCC_PLLSAIInitTypeDef; /** * @brief RCC extended clocks structure definition */ typedef struct { uint32_t PeriphClockSelection; /*!< The Extended Clock to be configured. This parameter can be a value of @ref RCCEx_Periph_Clock_Selection */ RCC_PLLI2SInitTypeDef PLLI2S; /*!< PLL I2S structure parameters. This parameter will be used only when PLLI2S is selected as Clock Source I2S or SAI */ RCC_PLLSAIInitTypeDef PLLSAI; /*!< PLL SAI structure parameters. This parameter will be used only when PLLI2S is selected as Clock Source SAI or LTDC */ uint32_t PLLI2SDivQ; /*!< Specifies the PLLI2S division factor for SAI1 clock. This parameter must be a number between Min_Data = 1 and Max_Data = 32 This parameter will be used only when PLLI2S is selected as Clock Source SAI */ uint32_t PLLSAIDivQ; /*!< Specifies the PLLI2S division factor for SAI1 clock. This parameter must be a number between Min_Data = 1 and Max_Data = 32 This parameter will be used only when PLLSAI is selected as Clock Source SAI */ uint32_t Sai1ClockSelection; /*!< Specifies SAI1 Clock Source Selection. This parameter can be a value of @ref RCCEx_SAI1_Clock_Source */ uint32_t Sai2ClockSelection; /*!< Specifies SAI2 Clock Source Selection. This parameter can be a value of @ref RCCEx_SAI2_Clock_Source */ uint32_t I2sApb1ClockSelection; /*!< Specifies I2S APB1 Clock Source Selection. This parameter can be a value of @ref RCCEx_I2SAPB1_Clock_Source */ uint32_t I2sApb2ClockSelection; /*!< Specifies I2S APB2 Clock Source Selection. This parameter can be a value of @ref RCCEx_I2SAPB2_Clock_Source */ uint32_t RTCClockSelection; /*!< Specifies RTC Clock Source Selection. This parameter can be a value of @ref RCC_RTC_Clock_Source */ uint32_t SdioClockSelection; /*!< Specifies SDIO Clock Source Selection. This parameter can be a value of @ref RCCEx_SDIO_Clock_Source */ uint32_t CecClockSelection; /*!< Specifies CEC Clock Source Selection. This parameter can be a value of @ref RCCEx_CEC_Clock_Source */ uint32_t Fmpi2c1ClockSelection; /*!< Specifies FMPI2C1 Clock Source Selection. This parameter can be a value of @ref RCCEx_FMPI2C1_Clock_Source */ uint32_t SpdifClockSelection; /*!< Specifies SPDIFRX Clock Source Selection. This parameter can be a value of @ref RCCEx_SPDIFRX_Clock_Source */ uint32_t Clk48ClockSelection; /*!< Specifies CK48 Clock Selection this clock used OTG FS, SDIO and RNG clocks. This parameter can be a value of @ref RCCEx_CK48_Clock_Source */ uint8_t TIMPresSelection; /*!< Specifies TIM Clock Source Selection. This parameter can be a value of @ref RCCEx_TIM_PRescaler_Selection */ }RCC_PeriphCLKInitTypeDef; #endif /* STM32F446xx */ #if defined(STM32F410Tx) || defined(STM32F410Cx) || defined(STM32F410Rx) /** * @brief RCC extended clocks structure definition */ typedef struct { uint32_t PeriphClockSelection; /*!< The Extended Clock to be configured. This parameter can be a value of @ref RCCEx_Periph_Clock_Selection */ uint32_t I2SClockSelection; /*!< Specifies RTC Clock Source Selection. This parameter can be a value of @ref RCCEx_I2S_APB_Clock_Source */ uint32_t RTCClockSelection; /*!< Specifies RTC Clock Source Selection. This parameter can be a value of @ref RCC_RTC_Clock_Source */ uint32_t Lptim1ClockSelection; /*!< Specifies LPTIM1 Clock Source Selection. This parameter can be a value of @ref RCCEx_LPTIM1_Clock_Source */ uint32_t Fmpi2c1ClockSelection; /*!< Specifies FMPI2C1 Clock Source Selection. This parameter can be a value of @ref RCCEx_FMPI2C1_Clock_Source */ uint8_t TIMPresSelection; /*!< Specifies TIM Clock Source Selection. This parameter can be a value of @ref RCCEx_TIM_PRescaler_Selection */ }RCC_PeriphCLKInitTypeDef; #endif /* STM32F410Tx || STM32F410Cx || STM32F410Rx */ #if defined(STM32F427xx) || defined(STM32F437xx) || defined(STM32F429xx) || defined(STM32F439xx) || defined(STM32F469xx) || defined(STM32F479xx) /** * @brief PLLI2S Clock structure definition */ typedef struct { uint32_t PLLI2SN; /*!< Specifies the multiplication factor for PLLI2S VCO output clock. This parameter must be a number between Min_Data = 192 and Max_Data = 432. This parameter will be used only when PLLI2S is selected as Clock Source I2S or SAI */ uint32_t PLLI2SR; /*!< Specifies the division factor for I2S clock. This parameter must be a number between Min_Data = 2 and Max_Data = 7. This parameter will be used only when PLLI2S is selected as Clock Source I2S or SAI */ uint32_t PLLI2SQ; /*!< Specifies the division factor for SAI1 clock. This parameter must be a number between Min_Data = 2 and Max_Data = 15. This parameter will be used only when PLLI2S is selected as Clock Source SAI */ }RCC_PLLI2SInitTypeDef; /** * @brief PLLSAI Clock structure definition */ typedef struct { uint32_t PLLSAIN; /*!< Specifies the multiplication factor for PLLI2S VCO output clock. This parameter must be a number between Min_Data = 192 and Max_Data = 432. This parameter will be used only when PLLSAI is selected as Clock Source SAI or LTDC */ #if defined(STM32F469xx) || defined(STM32F479xx) uint32_t PLLSAIP; /*!< Specifies division factor for OTG FS and SDIO clocks. This parameter is only available in STM32F469xx/STM32F479xx devices. This parameter must be a value of @ref RCCEx_PLLSAIP_Clock_Divider */ #endif /* STM32F469xx || STM32F479xx */ uint32_t PLLSAIQ; /*!< Specifies the division factor for SAI1 clock. This parameter must be a number between Min_Data = 2 and Max_Data = 15. This parameter will be used only when PLLSAI is selected as Clock Source SAI or LTDC */ uint32_t PLLSAIR; /*!< specifies the division factor for LTDC clock This parameter must be a number between Min_Data = 2 and Max_Data = 7. This parameter will be used only when PLLSAI is selected as Clock Source LTDC */ }RCC_PLLSAIInitTypeDef; /** * @brief RCC extended clocks structure definition */ typedef struct { uint32_t PeriphClockSelection; /*!< The Extended Clock to be configured. This parameter can be a value of @ref RCCEx_Periph_Clock_Selection */ RCC_PLLI2SInitTypeDef PLLI2S; /*!< PLL I2S structure parameters. This parameter will be used only when PLLI2S is selected as Clock Source I2S or SAI */ RCC_PLLSAIInitTypeDef PLLSAI; /*!< PLL SAI structure parameters. This parameter will be used only when PLLI2S is selected as Clock Source SAI or LTDC */ uint32_t PLLI2SDivQ; /*!< Specifies the PLLI2S division factor for SAI1 clock. This parameter must be a number between Min_Data = 1 and Max_Data = 32 This parameter will be used only when PLLI2S is selected as Clock Source SAI */ uint32_t PLLSAIDivQ; /*!< Specifies the PLLI2S division factor for SAI1 clock. This parameter must be a number between Min_Data = 1 and Max_Data = 32 This parameter will be used only when PLLSAI is selected as Clock Source SAI */ uint32_t PLLSAIDivR; /*!< Specifies the PLLSAI division factor for LTDC clock. This parameter must be one value of @ref RCCEx_PLLSAI_DIVR */ uint32_t RTCClockSelection; /*!< Specifies RTC Clock Prescalers Selection. This parameter can be a value of @ref RCC_RTC_Clock_Source */ uint8_t TIMPresSelection; /*!< Specifies TIM Clock Prescalers Selection. This parameter can be a value of @ref RCCEx_TIM_PRescaler_Selection */ #if defined(STM32F469xx) || defined(STM32F479xx) uint32_t Clk48ClockSelection; /*!< Specifies CK48 Clock Selection this clock used OTG FS, SDIO and RNG clocks. This parameter can be a value of @ref RCCEx_CK48_Clock_Source */ uint32_t SdioClockSelection; /*!< Specifies SDIO Clock Source Selection. This parameter can be a value of @ref RCCEx_SDIO_Clock_Source */ #endif /* STM32F469xx || STM32F479xx */ }RCC_PeriphCLKInitTypeDef; #endif /* STM32F427xx || STM32F437xx || STM32F429xx || STM32F439xx || STM32F469xx || STM32F479xx */ #if defined(STM32F405xx) || defined(STM32F415xx) || defined(STM32F407xx) || defined(STM32F417xx) ||\ defined(STM32F401xC) || defined(STM32F401xE) || defined(STM32F411xE) /** * @brief PLLI2S Clock structure definition */ typedef struct { #if defined(STM32F411xE) uint32_t PLLI2SM; /*!< PLLM: Division factor for PLLI2S VCO input clock. This parameter must be a number between Min_Data = 2 and Max_Data = 62 */ #endif /* STM32F411xE */ uint32_t PLLI2SN; /*!< Specifies the multiplication factor for PLLI2S VCO output clock. This parameter must be a number between Min_Data = 192 and Max_Data = 432 This parameter will be used only when PLLI2S is selected as Clock Source I2S or SAI */ uint32_t PLLI2SR; /*!< Specifies the division factor for I2S clock. This parameter must be a number between Min_Data = 2 and Max_Data = 7. This parameter will be used only when PLLI2S is selected as Clock Source I2S or SAI */ }RCC_PLLI2SInitTypeDef; /** * @brief RCC extended clocks structure definition */ typedef struct { uint32_t PeriphClockSelection; /*!< The Extended Clock to be configured. This parameter can be a value of @ref RCCEx_Periph_Clock_Selection */ RCC_PLLI2SInitTypeDef PLLI2S; /*!< PLL I2S structure parameters. This parameter will be used only when PLLI2S is selected as Clock Source I2S or SAI */ uint32_t RTCClockSelection; /*!< Specifies RTC Clock Prescalers Selection. This parameter can be a value of @ref RCC_RTC_Clock_Source */ }RCC_PeriphCLKInitTypeDef; #endif /* STM32F405xx || STM32F415xx || STM32F407xx || STM32F417xx || STM32F401xC || STM32F401xE || STM32F411xE */ /** * @} */ /* Exported constants --------------------------------------------------------*/ /** @defgroup RCCEx_Exported_Constants RCCEx Exported Constants * @{ */ /** @defgroup RCCEx_Periph_Clock_Selection RCC Periph Clock Selection * @{ */ /*------------------- Peripheral Clock source for STM32F410xx ----------------*/ #if defined(STM32F410Tx) || defined(STM32F410Cx) || defined(STM32F410Rx) #define RCC_PERIPHCLK_I2S ((uint32_t)0x00000001) #define RCC_PERIPHCLK_TIM ((uint32_t)0x00000002) #define RCC_PERIPHCLK_RTC ((uint32_t)0x00000004) #define RCC_PERIPHCLK_FMPI2C1 ((uint32_t)0x00000008) #define RCC_PERIPHCLK_LPTIM1 ((uint32_t)0x00000010) #endif /* STM32F410Tx || STM32F410Cx || STM32F410Rx */ /*----------------------------------------------------------------------------*/ /*------------------- Peripheral Clock source for STM32F446xx ----------------*/ #if defined(STM32F446xx) #define RCC_PERIPHCLK_I2S_APB1 ((uint32_t)0x00000001) #define RCC_PERIPHCLK_I2S_APB2 ((uint32_t)0x00000002) #define RCC_PERIPHCLK_SAI1 ((uint32_t)0x00000004) #define RCC_PERIPHCLK_SAI2 ((uint32_t)0x00000008) #define RCC_PERIPHCLK_TIM ((uint32_t)0x00000010) #define RCC_PERIPHCLK_RTC ((uint32_t)0x00000020) #define RCC_PERIPHCLK_CEC ((uint32_t)0x00000040) #define RCC_PERIPHCLK_FMPI2C1 ((uint32_t)0x00000080) #define RCC_PERIPHCLK_CK48 ((uint32_t)0x00000100) #define RCC_PERIPHCLK_SDIO ((uint32_t)0x00000200) #define RCC_PERIPHCLK_SPDIFRX ((uint32_t)0x00000400) #define RCC_PERIPHCLK_PLLI2S ((uint32_t)0x00000800) #endif /* STM32F446xx */ /*-----------------------------------------------------------------------------*/ /*----------- Peripheral Clock source for STM32F469xx/STM32F479xx -------------*/ #if defined(STM32F469xx) || defined(STM32F479xx) #define RCC_PERIPHCLK_I2S ((uint32_t)0x00000001) #define RCC_PERIPHCLK_SAI_PLLI2S ((uint32_t)0x00000002) #define RCC_PERIPHCLK_SAI_PLLSAI ((uint32_t)0x00000004) #define RCC_PERIPHCLK_LTDC ((uint32_t)0x00000008) #define RCC_PERIPHCLK_TIM ((uint32_t)0x00000010) #define RCC_PERIPHCLK_RTC ((uint32_t)0x00000020) #define RCC_PERIPHCLK_PLLI2S ((uint32_t)0x00000040) #define RCC_PERIPHCLK_CK48 ((uint32_t)0x00000080) #define RCC_PERIPHCLK_SDIO ((uint32_t)0x00000100) #endif /* STM32F469xx || STM32F479xx */ /*----------------------------------------------------------------------------*/ /*-------- Peripheral Clock source for STM32F42xxx/STM32F43xxx ---------------*/ #if defined(STM32F427xx) || defined(STM32F437xx) || defined(STM32F429xx) || defined(STM32F439xx) #define RCC_PERIPHCLK_I2S ((uint32_t)0x00000001) #define RCC_PERIPHCLK_SAI_PLLI2S ((uint32_t)0x00000002) #define RCC_PERIPHCLK_SAI_PLLSAI ((uint32_t)0x00000004) #define RCC_PERIPHCLK_LTDC ((uint32_t)0x00000008) #define RCC_PERIPHCLK_TIM ((uint32_t)0x00000010) #define RCC_PERIPHCLK_RTC ((uint32_t)0x00000020) #define RCC_PERIPHCLK_PLLI2S ((uint32_t)0x00000040) #endif /* STM32F427xx || STM32F437xx || STM32F429xx || STM32F439xx */ /*----------------------------------------------------------------------------*/ /*-------- Peripheral Clock source for STM32F40xxx/STM32F41xxx ---------------*/ #if defined(STM32F405xx) || defined(STM32F415xx) || defined(STM32F407xx)|| defined(STM32F417xx) ||\ defined(STM32F401xC) || defined(STM32F401xE) || defined(STM32F411xE) #define RCC_PERIPHCLK_I2S ((uint32_t)0x00000001) #define RCC_PERIPHCLK_RTC ((uint32_t)0x00000002) #define RCC_PERIPHCLK_PLLI2S ((uint32_t)0x00000004) #endif /* STM32F405xx || STM32F415xx || STM32F407xx || STM32F417xx || STM32F401xC || STM32F401xE || STM32F411xE */ /*----------------------------------------------------------------------------*/ /** * @} */ #if defined(STM32F405xx) || defined(STM32F415xx) || defined(STM32F407xx) || defined(STM32F417xx) || \ defined(STM32F427xx) || defined(STM32F437xx) || defined(STM32F429xx) || defined(STM32F439xx) || \ defined(STM32F401xC) || defined(STM32F401xE) || defined(STM32F411xE) || defined(STM32F446xx) || \ defined(STM32F469xx) || defined(STM32F479xx) /** @defgroup RCCEx_I2S_Clock_Source I2S Clock Source * @{ */ #define RCC_I2SCLKSOURCE_PLLI2S ((uint32_t)0x00000000) #define RCC_I2SCLKSOURCE_EXT ((uint32_t)0x00000001) /** * @} */ #endif /* STM32F405xx || STM32F415xx || STM32F407xx || STM32F417xx || STM32F427xx || STM32F437xx || STM32F429xx || STM32F439xx || STM32F401xC || STM32F401xE || STM32F411xE || STM32F446xx || STM32F469xx || STM32F479xx */ /** @defgroup RCCEx_PLLSAI_DIVR RCC PLLSAI DIVR * @{ */ #if defined(STM32F427xx) || defined(STM32F437xx) || defined(STM32F429xx) || defined(STM32F439xx) || defined(STM32F446xx) ||\ defined(STM32F469xx) || defined(STM32F479xx) #define RCC_PLLSAIDIVR_2 ((uint32_t)0x00000000) #define RCC_PLLSAIDIVR_4 ((uint32_t)0x00010000) #define RCC_PLLSAIDIVR_8 ((uint32_t)0x00020000) #define RCC_PLLSAIDIVR_16 ((uint32_t)0x00030000) #endif /* STM32F427xx || STM32F437xx || STM32F429xx || STM32F439xx || STM32F446xx || STM32F469xx || STM32F479xx */ /** * @} */ /** @defgroup RCCEx_PLLI2SP_Clock_Divider RCC PLLI2SP Clock Divider * @{ */ #if defined(STM32F446xx) #define RCC_PLLI2SP_DIV2 ((uint32_t)0x00000002) #define RCC_PLLI2SP_DIV4 ((uint32_t)0x00000004) #define RCC_PLLI2SP_DIV6 ((uint32_t)0x00000006) #define RCC_PLLI2SP_DIV8 ((uint32_t)0x00000008) #endif /* STM32F446xx */ /** * @} */ /** @defgroup RCCEx_PLLSAIP_Clock_Divider RCC PLLSAIP Clock Divider * @{ */ #if defined(STM32F446xx) || defined(STM32F469xx) || defined(STM32F479xx) #define RCC_PLLSAIP_DIV2 ((uint32_t)0x00000002) #define RCC_PLLSAIP_DIV4 ((uint32_t)0x00000004) #define RCC_PLLSAIP_DIV6 ((uint32_t)0x00000006) #define RCC_PLLSAIP_DIV8 ((uint32_t)0x00000008) #endif /* STM32F446xx || STM32F469xx || STM32F479xx */ /** * @} */ #if defined(STM32F427xx) || defined(STM32F437xx) || defined(STM32F429xx) || defined(STM32F439xx) || defined(STM32F469xx) || defined(STM32F479xx) /** @defgroup RCCEx_SAI_BlockA_Clock_Source RCC SAI BlockA Clock Source * @{ */ #define RCC_SAIACLKSOURCE_PLLSAI ((uint32_t)0x00000000) #define RCC_SAIACLKSOURCE_PLLI2S ((uint32_t)0x00100000) #define RCC_SAIACLKSOURCE_EXT ((uint32_t)0x00200000) /** * @} */ /** @defgroup RCCEx_SAI_BlockB_Clock_Source RCC SAI BlockB Clock Source * @{ */ #define RCC_SAIBCLKSOURCE_PLLSAI ((uint32_t)0x00000000) #define RCC_SAIBCLKSOURCE_PLLI2S ((uint32_t)0x00400000) #define RCC_SAIBCLKSOURCE_EXT ((uint32_t)0x00800000) /** * @} */ #endif /* STM32F427xx || STM32F437xx || STM32F429xx || STM32F439xx || STM32F469xx || STM32F479xx */ #if defined(STM32F469xx) || defined(STM32F479xx) /** @defgroup RCCEx_CK48_Clock_Source RCC CK48 Clock Source * @{ */ #define RCC_CK48CLKSOURCE_PLLQ ((uint32_t)0x00000000) #define RCC_CK48CLKSOURCE_PLLSAIP ((uint32_t)RCC_DCKCFGR_CK48MSEL) /** * @} */ /** @defgroup RCCEx_SDIO_Clock_Source RCC SDIO Clock Source * @{ */ #define RCC_SDIOCLKSOURCE_CK48 ((uint32_t)0x00000000) #define RCC_SDIOCLKSOURCE_SYSCLK ((uint32_t)RCC_DCKCFGR_SDIOSEL) /** * @} */ /** @defgroup RCCEx_DSI_Clock_Source RCC DSI Clock Source * @{ */ #define RCC_DSICLKSOURCE_DSIPHY ((uint32_t)0x00000000) #define RCC_DSICLKSOURCE_PLLR ((uint32_t)RCC_DCKCFGR_DSISEL) /** * @} */ #endif /* STM32F469xx || STM32F479xx */ #if defined(STM32F446xx) /** @defgroup RCCEx_SAI1_Clock_Source RCC SAI1 Clock Source * @{ */ #define RCC_SAI1CLKSOURCE_PLLSAI ((uint32_t)0x00000000) #define RCC_SAI1CLKSOURCE_PLLI2S ((uint32_t)RCC_DCKCFGR_SAI1SRC_0) #define RCC_SAI1CLKSOURCE_PLLR ((uint32_t)RCC_DCKCFGR_SAI1SRC_1) #define RCC_SAI1CLKSOURCE_EXT ((uint32_t)RCC_DCKCFGR_SAI1SRC) /** * @} */ /** @defgroup RCCEx_SAI2_Clock_Source RCC SAI2 Clock Source * @{ */ #define RCC_SAI2CLKSOURCE_PLLSAI ((uint32_t)0x00000000) #define RCC_SAI2CLKSOURCE_PLLI2S ((uint32_t)RCC_DCKCFGR_SAI2SRC_0) #define RCC_SAI2CLKSOURCE_PLLR ((uint32_t)RCC_DCKCFGR_SAI2SRC_1) #define RCC_SAI2CLKSOURCE_PLLSRC ((uint32_t)RCC_DCKCFGR_SAI2SRC) /** * @} */ /** @defgroup RCCEx_I2SAPB1_Clock_Source RCC I2S APB1 Clock Source * @{ */ #define RCC_I2SAPB1CLKSOURCE_PLLI2S ((uint32_t)0x00000000) #define RCC_I2SAPB1CLKSOURCE_EXT ((uint32_t)RCC_DCKCFGR_I2S1SRC_0) #define RCC_I2SAPB1CLKSOURCE_PLLR ((uint32_t)RCC_DCKCFGR_I2S1SRC_1) #define RCC_I2SAPB1CLKSOURCE_PLLSRC ((uint32_t)RCC_DCKCFGR_I2S1SRC) /** * @} */ /** @defgroup RCCEx_I2SAPB2_Clock_Source RCC I2S APB2 Clock Source * @{ */ #define RCC_I2SAPB2CLKSOURCE_PLLI2S ((uint32_t)0x00000000) #define RCC_I2SAPB2CLKSOURCE_EXT ((uint32_t)RCC_DCKCFGR_I2S2SRC_0) #define RCC_I2SAPB2CLKSOURCE_PLLR ((uint32_t)RCC_DCKCFGR_I2S2SRC_1) #define RCC_I2SAPB2CLKSOURCE_PLLSRC ((uint32_t)RCC_DCKCFGR_I2S2SRC) /** * @} */ /** @defgroup RCCEx_FMPI2C1_Clock_Source RCC FMPI2C1 Clock Source * @{ */ #define RCC_FMPI2C1CLKSOURCE_APB ((uint32_t)0x00000000) #define RCC_FMPI2C1CLKSOURCE_SYSCLK ((uint32_t)RCC_DCKCFGR2_FMPI2C1SEL_0) #define RCC_FMPI2C1CLKSOURCE_HSI ((uint32_t)RCC_DCKCFGR2_FMPI2C1SEL_1) /** * @} */ /** @defgroup RCCEx_CEC_Clock_Source RCC CEC Clock Source * @{ */ #define RCC_CECCLKSOURCE_HSI ((uint32_t)0x00000000) #define RCC_CECCLKSOURCE_LSE ((uint32_t)RCC_DCKCFGR2_CECSEL) /** * @} */ /** @defgroup RCCEx_CK48_Clock_Source RCC CK48 Clock Source * @{ */ #define RCC_CK48CLKSOURCE_PLLQ ((uint32_t)0x00000000) #define RCC_CK48CLKSOURCE_PLLSAIP ((uint32_t)RCC_DCKCFGR2_CK48MSEL) /** * @} */ /** @defgroup RCCEx_SDIO_Clock_Source RCC SDIO Clock Source * @{ */ #define RCC_SDIOCLKSOURCE_CK48 ((uint32_t)0x00000000) #define RCC_SDIOCLKSOURCE_SYSCLK ((uint32_t)RCC_DCKCFGR2_SDIOSEL) /** * @} */ /** @defgroup RCCEx_SPDIFRX_Clock_Source RCC SPDIFRX Clock Source * @{ */ #define RCC_SPDIFRXCLKSOURCE_PLLR ((uint32_t)0x00000000) #define RCC_SPDIFRXCLKSOURCE_PLLI2SP ((uint32_t)RCC_DCKCFGR2_SPDIFRXSEL) /** * @} */ #endif /* STM32F446xx */ #if defined(STM32F410Tx) || defined(STM32F410Cx) || defined(STM32F410Rx) /** @defgroup RCCEx_I2S_APB_Clock_Source RCC I2S APB Clock Source * @{ */ #define RCC_I2SAPBCLKSOURCE_PLLR ((uint32_t)0x00000000) #define RCC_I2SAPBCLKSOURCE_EXT ((uint32_t)RCC_DCKCFGR_I2SSRC_0) #define RCC_I2SAPBCLKSOURCE_PLLSRC ((uint32_t)RCC_DCKCFGR_I2SSRC_1) /** * @} */ /** @defgroup RCCEx_FMPI2C1_Clock_Source RCC FMPI2C1 Clock Source * @{ */ #define RCC_FMPI2C1CLKSOURCE_APB ((uint32_t)0x00000000) #define RCC_FMPI2C1CLKSOURCE_SYSCLK ((uint32_t)RCC_DCKCFGR2_FMPI2C1SEL_0) #define RCC_FMPI2C1CLKSOURCE_HSI ((uint32_t)RCC_DCKCFGR2_FMPI2C1SEL_1) /** * @} */ /** @defgroup RCCEx_LPTIM1_Clock_Source RCC LPTIM1 Clock Source * @{ */ #define RCC_LPTIM1CLKSOURCE_PCLK ((uint32_t)0x00000000) #define RCC_LPTIM1CLKSOURCE_HSI ((uint32_t)RCC_DCKCFGR2_LPTIM1SEL_0) #define RCC_LPTIM1CLKSOURCE_LSI ((uint32_t)RCC_DCKCFGR2_LPTIM1SEL_1) #define RCC_LPTIM1CLKSOURCE_LSE ((uint32_t)RCC_DCKCFGR2_LPTIM1SEL_0 | RCC_DCKCFGR2_LPTIM1SEL_1) /** * @} */ /** @defgroup RCCEx_TIM_PRescaler_Selection RCC TIM PRescaler Selection * @{ */ #define RCC_TIMPRES_DESACTIVATED ((uint8_t)0x00) #define RCC_TIMPRES_ACTIVATED ((uint8_t)0x01) /** * @} */ #endif /* STM32F410Tx || STM32F410Cx || STM32F410Rx */ #if defined(STM32F427xx) || defined(STM32F437xx) || defined(STM32F429xx) || defined(STM32F439xx) ||\ defined(STM32F401xC) || defined(STM32F401xE) || defined(STM32F411xE) || defined(STM32F446xx) ||\ defined(STM32F469xx) || defined(STM32F479xx) /** @defgroup RCCEx_TIM_PRescaler_Selection RCC TIM PRescaler Selection * @{ */ #define RCC_TIMPRES_DESACTIVATED ((uint8_t)0x00) #define RCC_TIMPRES_ACTIVATED ((uint8_t)0x01) /** * @} */ #endif /* STM32F427xx || STM32F437xx || STM32F429xx || STM32F439xx || STM32F401xC || STM32F401xE ||\ STM32F410xx || STM32F411xE || STM32F446xx || STM32F469xx || STM32F479xx */ #if defined(STM32F410Tx) || defined(STM32F410Cx) || defined(STM32F410Rx) || defined(STM32F411xE) ||\ defined(STM32F446xx) || defined(STM32F469xx) || defined(STM32F479xx) /** @defgroup RCCEx_LSE_Dual_Mode_Selection RCC LSE Dual Mode Selection * @{ */ #define RCC_LSE_LOWPOWER_MODE ((uint8_t)0x00) #define RCC_LSE_HIGHDRIVE_MODE ((uint8_t)0x01) /** * @} */ #endif /* STM32F410xx || STM32F411xE || STM32F446xx || STM32F469xx || STM32F479xx */ #if defined(STM32F405xx) || defined(STM32F415xx) || defined(STM32F407xx) || defined(STM32F417xx) || \ defined(STM32F427xx) || defined(STM32F437xx) || defined(STM32F429xx) || defined(STM32F439xx) || \ defined(STM32F401xC) || defined(STM32F401xE) || defined(STM32F411xE) || defined(STM32F446xx) || \ defined(STM32F469xx) || defined(STM32F479xx) /** @defgroup RCC_MCO2_Clock_Source MCO2 Clock Source * @{ */ #define RCC_MCO2SOURCE_SYSCLK ((uint32_t)0x00000000) #define RCC_MCO2SOURCE_PLLI2SCLK RCC_CFGR_MCO2_0 #define RCC_MCO2SOURCE_HSE RCC_CFGR_MCO2_1 #define RCC_MCO2SOURCE_PLLCLK RCC_CFGR_MCO2 /** * @} */ #endif /* STM32F405xx || STM32F415xx || STM32F407xx || STM32F417xx || STM32F427xx || STM32F437xx || STM32F429xx || STM32F439xx || STM32F401xC || STM32F401xE || STM32F411xE || STM32F446xx || STM32F469xx || STM32F479xx */ #if defined(STM32F410Tx) || defined(STM32F410Cx) || defined(STM32F410Rx) /** @defgroup RCC_MCO2_Clock_Source MCO2 Clock Source * @{ */ #define RCC_MCO2SOURCE_SYSCLK ((uint32_t)0x00000000) #define RCC_MCO2SOURCE_I2SCLK RCC_CFGR_MCO2_0 #define RCC_MCO2SOURCE_HSE RCC_CFGR_MCO2_1 #define RCC_MCO2SOURCE_PLLCLK RCC_CFGR_MCO2 /** * @} */ #endif /* STM32F410Tx || STM32F410Cx || STM32F410Rx */ /** * @} */ /* Exported macro ------------------------------------------------------------*/ /** @defgroup RCCEx_Exported_Macros RCCEx Exported Macros * @{ */ /*------------------- STM32F42xxx/STM32F43xxx/STM32F469xx/STM32F479xx --------*/ #if defined(STM32F427xx) || defined(STM32F437xx) || defined(STM32F429xx)|| defined(STM32F439xx) || defined(STM32F469xx) || defined(STM32F479xx) /** @defgroup RCCEx_AHB1_Clock_Enable_Disable AHB1 Peripheral Clock Enable Disable * @brief Enables or disables the AHB1 peripheral clock. * @note After reset, the peripheral clock (used for registers read/write access) * is disabled and the application software has to enable this clock before * using it. */ #define __HAL_RCC_BKPSRAM_CLK_ENABLE() do { \ __IO uint32_t tmpreg; \ SET_BIT(RCC->AHB1ENR, RCC_AHB1ENR_BKPSRAMEN);\ /* Delay after an RCC peripheral clock enabling */ \ tmpreg = READ_BIT(RCC->AHB1ENR, RCC_AHB1ENR_BKPSRAMEN);\ UNUSED(tmpreg); \ } while(0) #define __HAL_RCC_CCMDATARAMEN_CLK_ENABLE() do { \ __IO uint32_t tmpreg; \ SET_BIT(RCC->AHB1ENR, RCC_AHB1ENR_CCMDATARAMEN);\ /* Delay after an RCC peripheral clock enabling */ \ tmpreg = READ_BIT(RCC->AHB1ENR, RCC_AHB1ENR_CCMDATARAMEN);\ UNUSED(tmpreg); \ } while(0) #define __HAL_RCC_CRC_CLK_ENABLE() do { \ __IO uint32_t tmpreg; \ SET_BIT(RCC->AHB1ENR, RCC_AHB1ENR_CRCEN);\ /* Delay after an RCC peripheral clock enabling */ \ tmpreg = READ_BIT(RCC->AHB1ENR, RCC_AHB1ENR_CRCEN);\ UNUSED(tmpreg); \ } while(0) #define __HAL_RCC_GPIOD_CLK_ENABLE() do { \ __IO uint32_t tmpreg; \ SET_BIT(RCC->AHB1ENR, RCC_AHB1ENR_GPIODEN);\ /* Delay after an RCC peripheral clock enabling */ \ tmpreg = READ_BIT(RCC->AHB1ENR, RCC_AHB1ENR_GPIODEN);\ UNUSED(tmpreg); \ } while(0) #define __HAL_RCC_GPIOE_CLK_ENABLE() do { \ __IO uint32_t tmpreg; \ SET_BIT(RCC->AHB1ENR, RCC_AHB1ENR_GPIOEEN);\ /* Delay after an RCC peripheral clock enabling */ \ tmpreg = READ_BIT(RCC->AHB1ENR, RCC_AHB1ENR_GPIOEEN);\ UNUSED(tmpreg); \ } while(0) #define __HAL_RCC_GPIOI_CLK_ENABLE() do { \ __IO uint32_t tmpreg; \ SET_BIT(RCC->AHB1ENR, RCC_AHB1ENR_GPIOIEN);\ /* Delay after an RCC peripheral clock enabling */ \ tmpreg = READ_BIT(RCC->AHB1ENR, RCC_AHB1ENR_GPIOIEN);\ UNUSED(tmpreg); \ } while(0) #define __HAL_RCC_GPIOF_CLK_ENABLE() do { \ __IO uint32_t tmpreg; \ SET_BIT(RCC->AHB1ENR, RCC_AHB1ENR_GPIOFEN);\ /* Delay after an RCC peripheral clock enabling */ \ tmpreg = READ_BIT(RCC->AHB1ENR, RCC_AHB1ENR_GPIOFEN);\ UNUSED(tmpreg); \ } while(0) #define __HAL_RCC_GPIOG_CLK_ENABLE() do { \ __IO uint32_t tmpreg; \ SET_BIT(RCC->AHB1ENR, RCC_AHB1ENR_GPIOGEN);\ /* Delay after an RCC peripheral clock enabling */ \ tmpreg = READ_BIT(RCC->AHB1ENR, RCC_AHB1ENR_GPIOGEN);\ UNUSED(tmpreg); \ } while(0) #define __HAL_RCC_GPIOJ_CLK_ENABLE() do { \ __IO uint32_t tmpreg; \ SET_BIT(RCC->AHB1ENR, RCC_AHB1ENR_GPIOJEN);\ /* Delay after an RCC peripheral clock enabling */ \ tmpreg = READ_BIT(RCC->AHB1ENR, RCC_AHB1ENR_GPIOJEN);\ UNUSED(tmpreg); \ } while(0) #define __HAL_RCC_GPIOK_CLK_ENABLE() do { \ __IO uint32_t tmpreg; \ SET_BIT(RCC->AHB1ENR, RCC_AHB1ENR_GPIOKEN);\ /* Delay after an RCC peripheral clock enabling */ \ tmpreg = READ_BIT(RCC->AHB1ENR, RCC_AHB1ENR_GPIOKEN);\ UNUSED(tmpreg); \ } while(0) #define __HAL_RCC_DMA2D_CLK_ENABLE() do { \ __IO uint32_t tmpreg; \ SET_BIT(RCC->AHB1ENR, RCC_AHB1ENR_DMA2DEN);\ /* Delay after an RCC peripheral clock enabling */ \ tmpreg = READ_BIT(RCC->AHB1ENR, RCC_AHB1ENR_DMA2DEN);\ UNUSED(tmpreg); \ } while(0) #define __HAL_RCC_ETHMAC_CLK_ENABLE() do { \ __IO uint32_t tmpreg; \ SET_BIT(RCC->AHB1ENR, RCC_AHB1ENR_ETHMACEN);\ /* Delay after an RCC peripheral clock enabling */ \ tmpreg = READ_BIT(RCC->AHB1ENR, RCC_AHB1ENR_ETHMACEN);\ UNUSED(tmpreg); \ } while(0) #define __HAL_RCC_ETHMACTX_CLK_ENABLE() do { \ __IO uint32_t tmpreg; \ SET_BIT(RCC->AHB1ENR, RCC_AHB1ENR_ETHMACTXEN);\ /* Delay after an RCC peripheral clock enabling */ \ tmpreg = READ_BIT(RCC->AHB1ENR, RCC_AHB1ENR_ETHMACTXEN);\ UNUSED(tmpreg); \ } while(0) #define __HAL_RCC_ETHMACRX_CLK_ENABLE() do { \ __IO uint32_t tmpreg; \ SET_BIT(RCC->AHB1ENR, RCC_AHB1ENR_ETHMACRXEN);\ /* Delay after an RCC peripheral clock enabling */ \ tmpreg = READ_BIT(RCC->AHB1ENR, RCC_AHB1ENR_ETHMACRXEN);\ UNUSED(tmpreg); \ } while(0) #define __HAL_RCC_ETHMACPTP_CLK_ENABLE() do { \ __IO uint32_t tmpreg; \ SET_BIT(RCC->AHB1ENR, RCC_AHB1ENR_ETHMACPTPEN);\ /* Delay after an RCC peripheral clock enabling */ \ tmpreg = READ_BIT(RCC->AHB1ENR, RCC_AHB1ENR_ETHMACPTPEN);\ UNUSED(tmpreg); \ } while(0) #define __HAL_RCC_USB_OTG_HS_CLK_ENABLE() do { \ __IO uint32_t tmpreg; \ SET_BIT(RCC->AHB1ENR, RCC_AHB1ENR_OTGHSEN);\ /* Delay after an RCC peripheral clock enabling */ \ tmpreg = READ_BIT(RCC->AHB1ENR, RCC_AHB1ENR_OTGHSEN);\ UNUSED(tmpreg); \ } while(0) #define __HAL_RCC_USB_OTG_HS_ULPI_CLK_ENABLE() do { \ __IO uint32_t tmpreg; \ SET_BIT(RCC->AHB1ENR, RCC_AHB1ENR_OTGHSULPIEN);\ /* Delay after an RCC peripheral clock enabling */ \ tmpreg = READ_BIT(RCC->AHB1ENR, RCC_AHB1ENR_OTGHSULPIEN);\ UNUSED(tmpreg); \ } while(0) #define __HAL_RCC_GPIOD_CLK_DISABLE() (RCC->AHB1ENR &= ~(RCC_AHB1ENR_GPIODEN)) #define __HAL_RCC_GPIOE_CLK_DISABLE() (RCC->AHB1ENR &= ~(RCC_AHB1ENR_GPIOEEN)) #define __HAL_RCC_GPIOF_CLK_DISABLE() (RCC->AHB1ENR &= ~(RCC_AHB1ENR_GPIOFEN)) #define __HAL_RCC_GPIOG_CLK_DISABLE() (RCC->AHB1ENR &= ~(RCC_AHB1ENR_GPIOGEN)) #define __HAL_RCC_GPIOI_CLK_DISABLE() (RCC->AHB1ENR &= ~(RCC_AHB1ENR_GPIOIEN)) #define __HAL_RCC_GPIOJ_CLK_DISABLE() (RCC->AHB1ENR &= ~(RCC_AHB1ENR_GPIOJEN)) #define __HAL_RCC_GPIOK_CLK_DISABLE() (RCC->AHB1ENR &= ~(RCC_AHB1ENR_GPIOKEN)) #define __HAL_RCC_DMA2D_CLK_DISABLE() (RCC->AHB1ENR &= ~(RCC_AHB1ENR_DMA2DEN)) #define __HAL_RCC_ETHMAC_CLK_DISABLE() (RCC->AHB1ENR &= ~(RCC_AHB1ENR_ETHMACEN)) #define __HAL_RCC_ETHMACTX_CLK_DISABLE() (RCC->AHB1ENR &= ~(RCC_AHB1ENR_ETHMACTXEN)) #define __HAL_RCC_ETHMACRX_CLK_DISABLE() (RCC->AHB1ENR &= ~(RCC_AHB1ENR_ETHMACRXEN)) #define __HAL_RCC_ETHMACPTP_CLK_DISABLE() (RCC->AHB1ENR &= ~(RCC_AHB1ENR_ETHMACPTPEN)) #define __HAL_RCC_USB_OTG_HS_CLK_DISABLE() (RCC->AHB1ENR &= ~(RCC_AHB1ENR_OTGHSEN)) #define __HAL_RCC_USB_OTG_HS_ULPI_CLK_DISABLE() (RCC->AHB1ENR &= ~(RCC_AHB1ENR_OTGHSULPIEN)) #define __HAL_RCC_BKPSRAM_CLK_DISABLE() (RCC->AHB1ENR &= ~(RCC_AHB1ENR_BKPSRAMEN)) #define __HAL_RCC_CCMDATARAMEN_CLK_DISABLE() (RCC->AHB1ENR &= ~(RCC_AHB1ENR_CCMDATARAMEN)) #define __HAL_RCC_CRC_CLK_DISABLE() (RCC->AHB1ENR &= ~(RCC_AHB1ENR_CRCEN)) /** * @brief Enable ETHERNET clock. */ #define __HAL_RCC_ETH_CLK_ENABLE() do { \ __HAL_RCC_ETHMAC_CLK_ENABLE(); \ __HAL_RCC_ETHMACTX_CLK_ENABLE(); \ __HAL_RCC_ETHMACRX_CLK_ENABLE(); \ } while(0) /** * @brief Disable ETHERNET clock. */ #define __HAL_RCC_ETH_CLK_DISABLE() do { \ __HAL_RCC_ETHMACTX_CLK_DISABLE(); \ __HAL_RCC_ETHMACRX_CLK_DISABLE(); \ __HAL_RCC_ETHMAC_CLK_DISABLE(); \ } while(0) /** * @} */ /** @defgroup RCCEx_AHB2_Clock_Enable_Disable AHB2 Peripheral Clock Enable Disable * @brief Enable or disable the AHB2 peripheral clock. * @note After reset, the peripheral clock (used for registers read/write access) * is disabled and the application software has to enable this clock before * using it. */ #define __HAL_RCC_DCMI_CLK_ENABLE() do { \ __IO uint32_t tmpreg; \ SET_BIT(RCC->AHB2ENR, RCC_AHB2ENR_DCMIEN);\ /* Delay after an RCC peripheral clock enabling */ \ tmpreg = READ_BIT(RCC->AHB2ENR, RCC_AHB2ENR_DCMIEN);\ UNUSED(tmpreg); \ } while(0) #define __HAL_RCC_DCMI_CLK_DISABLE() (RCC->AHB2ENR &= ~(RCC_AHB2ENR_DCMIEN)) #if defined(STM32F437xx)|| defined(STM32F439xx) || defined(STM32F479xx) #define __HAL_RCC_CRYP_CLK_ENABLE() do { \ __IO uint32_t tmpreg; \ SET_BIT(RCC->AHB2ENR, RCC_AHB2ENR_CRYPEN);\ /* Delay after an RCC peripheral clock enabling */ \ tmpreg = READ_BIT(RCC->AHB2ENR, RCC_AHB2ENR_CRYPEN);\ UNUSED(tmpreg); \ } while(0) #define __HAL_RCC_HASH_CLK_ENABLE() do { \ __IO uint32_t tmpreg; \ SET_BIT(RCC->AHB2ENR, RCC_AHB2ENR_HASHEN);\ /* Delay after an RCC peripheral clock enabling */ \ tmpreg = READ_BIT(RCC->AHB2ENR, RCC_AHB2ENR_HASHEN);\ UNUSED(tmpreg); \ } while(0) #define __HAL_RCC_CRYP_CLK_DISABLE() (RCC->AHB2ENR &= ~(RCC_AHB2ENR_CRYPEN)) #define __HAL_RCC_HASH_CLK_DISABLE() (RCC->AHB2ENR &= ~(RCC_AHB2ENR_HASHEN)) #endif /* STM32F437xx || STM32F439xx || STM32F479xx */ /** * @} */ /** @defgroup RCCEX_AHB2_Clock_Enable_Disable AHB2 Peripheral Clock Enable Disable * @brief Enable or disable the AHB2 peripheral clock. * @note After reset, the peripheral clock (used for registers read/write access) * is disabled and the application software has to enable this clock before * using it. * @{ */ #define __HAL_RCC_USB_OTG_FS_CLK_ENABLE() do {(RCC->AHB2ENR |= (RCC_AHB2ENR_OTGFSEN));\ __HAL_RCC_SYSCFG_CLK_ENABLE();\ }while(0) #define __HAL_RCC_USB_OTG_FS_CLK_DISABLE() do { (RCC->AHB2ENR &= ~(RCC_AHB2ENR_OTGFSEN));\ __HAL_RCC_SYSCFG_CLK_DISABLE();\ }while(0) #define __HAL_RCC_RNG_CLK_ENABLE() do { \ __IO uint32_t tmpreg; \ SET_BIT(RCC->AHB2ENR, RCC_AHB2ENR_RNGEN);\ /* Delay after an RCC peripheral clock enabling */ \ tmpreg = READ_BIT(RCC->AHB2ENR, RCC_AHB2ENR_RNGEN);\ UNUSED(tmpreg); \ } while(0) #define __HAL_RCC_RNG_CLK_DISABLE() (RCC->AHB2ENR &= ~(RCC_AHB2ENR_RNGEN)) /** * @} */ /** @defgroup RCCEx_AHB3_Clock_Enable_Disable AHB3 Peripheral Clock Enable Disable * @brief Enables or disables the AHB3 peripheral clock. * @note After reset, the peripheral clock (used for registers read/write access) * is disabled and the application software has to enable this clock before * using it. */ #define __HAL_RCC_FMC_CLK_ENABLE() do { \ __IO uint32_t tmpreg; \ SET_BIT(RCC->AHB3ENR, RCC_AHB3ENR_FMCEN);\ /* Delay after an RCC peripheral clock enabling */ \ tmpreg = READ_BIT(RCC->AHB3ENR, RCC_AHB3ENR_FMCEN);\ UNUSED(tmpreg); \ } while(0) #define __HAL_RCC_FMC_CLK_DISABLE() (RCC->AHB3ENR &= ~(RCC_AHB3ENR_FMCEN)) #if defined(STM32F469xx) || defined(STM32F479xx) #define __HAL_RCC_QSPI_CLK_ENABLE() do { \ __IO uint32_t tmpreg; \ SET_BIT(RCC->AHB3ENR, RCC_AHB3ENR_QSPIEN);\ /* Delay after an RCC peripheral clock enabling */ \ tmpreg = READ_BIT(RCC->AHB3ENR, RCC_AHB3ENR_QSPIEN);\ UNUSED(tmpreg); \ } while(0) #define __HAL_RCC_QSPI_CLK_DISABLE() (RCC->AHB3ENR &= ~(RCC_AHB3ENR_QSPIEN)) #endif /* STM32F469xx || STM32F479xx */ /** * @} */ /** @defgroup RCCEx_APB1_Clock_Enable_Disable APB1 Peripheral Clock Enable Disable * @brief Enable or disable the Low Speed APB (APB1) peripheral clock. * @note After reset, the peripheral clock (used for registers read/write access) * is disabled and the application software has to enable this clock before * using it. */ #define __HAL_RCC_TIM6_CLK_ENABLE() do { \ __IO uint32_t tmpreg; \ SET_BIT(RCC->APB1ENR, RCC_APB1ENR_TIM6EN);\ /* Delay after an RCC peripheral clock enabling */ \ tmpreg = READ_BIT(RCC->APB1ENR, RCC_APB1ENR_TIM6EN);\ UNUSED(tmpreg); \ } while(0) #define __HAL_RCC_TIM7_CLK_ENABLE() do { \ __IO uint32_t tmpreg; \ SET_BIT(RCC->APB1ENR, RCC_APB1ENR_TIM7EN);\ /* Delay after an RCC peripheral clock enabling */ \ tmpreg = READ_BIT(RCC->APB1ENR, RCC_APB1ENR_TIM7EN);\ UNUSED(tmpreg); \ } while(0) #define __HAL_RCC_TIM12_CLK_ENABLE() do { \ __IO uint32_t tmpreg; \ SET_BIT(RCC->APB1ENR, RCC_APB1ENR_TIM12EN);\ /* Delay after an RCC peripheral clock enabling */ \ tmpreg = READ_BIT(RCC->APB1ENR, RCC_APB1ENR_TIM12EN);\ UNUSED(tmpreg); \ } while(0) #define __HAL_RCC_TIM13_CLK_ENABLE() do { \ __IO uint32_t tmpreg; \ SET_BIT(RCC->APB1ENR, RCC_APB1ENR_TIM13EN);\ /* Delay after an RCC peripheral clock enabling */ \ tmpreg = READ_BIT(RCC->APB1ENR, RCC_APB1ENR_TIM13EN);\ UNUSED(tmpreg); \ } while(0) #define __HAL_RCC_TIM14_CLK_ENABLE() do { \ __IO uint32_t tmpreg; \ SET_BIT(RCC->APB1ENR, RCC_APB1ENR_TIM14EN);\ /* Delay after an RCC peripheral clock enabling */ \ tmpreg = READ_BIT(RCC->APB1ENR, RCC_APB1ENR_TIM14EN);\ UNUSED(tmpreg); \ } while(0) #define __HAL_RCC_TIM14_CLK_ENABLE() do { \ __IO uint32_t tmpreg; \ SET_BIT(RCC->APB1ENR, RCC_APB1ENR_TIM14EN);\ /* Delay after an RCC peripheral clock enabling */ \ tmpreg = READ_BIT(RCC->APB1ENR, RCC_APB1ENR_TIM14EN);\ UNUSED(tmpreg); \ } while(0) #define __HAL_RCC_USART3_CLK_ENABLE() do { \ __IO uint32_t tmpreg; \ SET_BIT(RCC->APB1ENR, RCC_APB1ENR_USART3EN);\ /* Delay after an RCC peripheral clock enabling */ \ tmpreg = READ_BIT(RCC->APB1ENR, RCC_APB1ENR_USART3EN);\ UNUSED(tmpreg); \ } while(0) #define __HAL_RCC_UART4_CLK_ENABLE() do { \ __IO uint32_t tmpreg; \ SET_BIT(RCC->APB1ENR, RCC_APB1ENR_UART4EN);\ /* Delay after an RCC peripheral clock enabling */ \ tmpreg = READ_BIT(RCC->APB1ENR, RCC_APB1ENR_UART4EN);\ UNUSED(tmpreg); \ } while(0) #define __HAL_RCC_UART5_CLK_ENABLE() do { \ __IO uint32_t tmpreg; \ SET_BIT(RCC->APB1ENR, RCC_APB1ENR_UART5EN);\ /* Delay after an RCC peripheral clock enabling */ \ tmpreg = READ_BIT(RCC->APB1ENR, RCC_APB1ENR_UART5EN);\ UNUSED(tmpreg); \ } while(0) #define __HAL_RCC_CAN1_CLK_ENABLE() do { \ __IO uint32_t tmpreg; \ SET_BIT(RCC->APB1ENR, RCC_APB1ENR_CAN1EN);\ /* Delay after an RCC peripheral clock enabling */ \ tmpreg = READ_BIT(RCC->APB1ENR, RCC_APB1ENR_CAN1EN);\ UNUSED(tmpreg); \ } while(0) #define __HAL_RCC_CAN2_CLK_ENABLE() do { \ __IO uint32_t tmpreg; \ SET_BIT(RCC->APB1ENR, RCC_APB1ENR_CAN2EN);\ /* Delay after an RCC peripheral clock enabling */ \ tmpreg = READ_BIT(RCC->APB1ENR, RCC_APB1ENR_CAN2EN);\ UNUSED(tmpreg); \ } while(0) #define __HAL_RCC_DAC_CLK_ENABLE() do { \ __IO uint32_t tmpreg; \ SET_BIT(RCC->APB1ENR, RCC_APB1ENR_DACEN);\ /* Delay after an RCC peripheral clock enabling */ \ tmpreg = READ_BIT(RCC->APB1ENR, RCC_APB1ENR_DACEN);\ UNUSED(tmpreg); \ } while(0) #define __HAL_RCC_UART7_CLK_ENABLE() do { \ __IO uint32_t tmpreg; \ SET_BIT(RCC->APB1ENR, RCC_APB1ENR_UART7EN);\ /* Delay after an RCC peripheral clock enabling */ \ tmpreg = READ_BIT(RCC->APB1ENR, RCC_APB1ENR_UART7EN);\ UNUSED(tmpreg); \ } while(0) #define __HAL_RCC_UART8_CLK_ENABLE() do { \ __IO uint32_t tmpreg; \ SET_BIT(RCC->APB1ENR, RCC_APB1ENR_UART8EN);\ /* Delay after an RCC peripheral clock enabling */ \ tmpreg = READ_BIT(RCC->APB1ENR, RCC_APB1ENR_UART8EN);\ UNUSED(tmpreg); \ } while(0) #define __HAL_RCC_TIM2_CLK_ENABLE() do { \ __IO uint32_t tmpreg; \ SET_BIT(RCC->APB1ENR, RCC_APB1ENR_TIM2EN);\ /* Delay after an RCC peripheral clock enabling */ \ tmpreg = READ_BIT(RCC->APB1ENR, RCC_APB1ENR_TIM2EN);\ UNUSED(tmpreg); \ } while(0) #define __HAL_RCC_TIM3_CLK_ENABLE() do { \ __IO uint32_t tmpreg; \ SET_BIT(RCC->APB1ENR, RCC_APB1ENR_TIM3EN);\ /* Delay after an RCC peripheral clock enabling */ \ tmpreg = READ_BIT(RCC->APB1ENR, RCC_APB1ENR_TIM3EN);\ UNUSED(tmpreg); \ } while(0) #define __HAL_RCC_TIM4_CLK_ENABLE() do { \ __IO uint32_t tmpreg; \ SET_BIT(RCC->APB1ENR, RCC_APB1ENR_TIM4EN);\ /* Delay after an RCC peripheral clock enabling */ \ tmpreg = READ_BIT(RCC->APB1ENR, RCC_APB1ENR_TIM4EN);\ UNUSED(tmpreg); \ } while(0) #define __HAL_RCC_SPI3_CLK_ENABLE() do { \ __IO uint32_t tmpreg; \ SET_BIT(RCC->APB1ENR, RCC_APB1ENR_SPI3EN);\ /* Delay after an RCC peripheral clock enabling */ \ tmpreg = READ_BIT(RCC->APB1ENR, RCC_APB1ENR_SPI3EN);\ UNUSED(tmpreg); \ } while(0) #define __HAL_RCC_I2C3_CLK_ENABLE() do { \ __IO uint32_t tmpreg; \ SET_BIT(RCC->APB1ENR, RCC_APB1ENR_I2C3EN);\ /* Delay after an RCC peripheral clock enabling */ \ tmpreg = READ_BIT(RCC->APB1ENR, RCC_APB1ENR_I2C3EN);\ UNUSED(tmpreg); \ } while(0) #define __HAL_RCC_TIM2_CLK_DISABLE() (RCC->APB1ENR &= ~(RCC_APB1ENR_TIM2EN)) #define __HAL_RCC_TIM3_CLK_DISABLE() (RCC->APB1ENR &= ~(RCC_APB1ENR_TIM3EN)) #define __HAL_RCC_TIM4_CLK_DISABLE() (RCC->APB1ENR &= ~(RCC_APB1ENR_TIM4EN)) #define __HAL_RCC_SPI3_CLK_DISABLE() (RCC->APB1ENR &= ~(RCC_APB1ENR_SPI3EN)) #define __HAL_RCC_I2C3_CLK_DISABLE() (RCC->APB1ENR &= ~(RCC_APB1ENR_I2C3EN)) #define __HAL_RCC_TIM6_CLK_DISABLE() (RCC->APB1ENR &= ~(RCC_APB1ENR_TIM6EN)) #define __HAL_RCC_TIM7_CLK_DISABLE() (RCC->APB1ENR &= ~(RCC_APB1ENR_TIM7EN)) #define __HAL_RCC_TIM12_CLK_DISABLE() (RCC->APB1ENR &= ~(RCC_APB1ENR_TIM12EN)) #define __HAL_RCC_TIM13_CLK_DISABLE() (RCC->APB1ENR &= ~(RCC_APB1ENR_TIM13EN)) #define __HAL_RCC_TIM14_CLK_DISABLE() (RCC->APB1ENR &= ~(RCC_APB1ENR_TIM14EN)) #define __HAL_RCC_USART3_CLK_DISABLE() (RCC->APB1ENR &= ~(RCC_APB1ENR_USART3EN)) #define __HAL_RCC_UART4_CLK_DISABLE() (RCC->APB1ENR &= ~(RCC_APB1ENR_UART4EN)) #define __HAL_RCC_UART5_CLK_DISABLE() (RCC->APB1ENR &= ~(RCC_APB1ENR_UART5EN)) #define __HAL_RCC_CAN1_CLK_DISABLE() (RCC->APB1ENR &= ~(RCC_APB1ENR_CAN1EN)) #define __HAL_RCC_CAN2_CLK_DISABLE() (RCC->APB1ENR &= ~(RCC_APB1ENR_CAN2EN)) #define __HAL_RCC_DAC_CLK_DISABLE() (RCC->APB1ENR &= ~(RCC_APB1ENR_DACEN)) #define __HAL_RCC_UART7_CLK_DISABLE() (RCC->APB1ENR &= ~(RCC_APB1ENR_UART7EN)) #define __HAL_RCC_UART8_CLK_DISABLE() (RCC->APB1ENR &= ~(RCC_APB1ENR_UART8EN)) /** * @} */ /** @defgroup RCCEx_APB2_Clock_Enable_Disable APB2 Peripheral Clock Enable Disable * @brief Enable or disable the High Speed APB (APB2) peripheral clock. * @note After reset, the peripheral clock (used for registers read/write access) * is disabled and the application software has to enable this clock before * using it. */ #define __HAL_RCC_TIM8_CLK_ENABLE() do { \ __IO uint32_t tmpreg; \ SET_BIT(RCC->APB2ENR, RCC_APB2ENR_TIM8EN);\ /* Delay after an RCC peripheral clock enabling */ \ tmpreg = READ_BIT(RCC->APB2ENR, RCC_APB2ENR_TIM8EN);\ UNUSED(tmpreg); \ } while(0) #define __HAL_RCC_ADC2_CLK_ENABLE() do { \ __IO uint32_t tmpreg; \ SET_BIT(RCC->APB2ENR, RCC_APB2ENR_ADC2EN);\ /* Delay after an RCC peripheral clock enabling */ \ tmpreg = READ_BIT(RCC->APB2ENR, RCC_APB2ENR_ADC2EN);\ UNUSED(tmpreg); \ } while(0) #define __HAL_RCC_ADC3_CLK_ENABLE() do { \ __IO uint32_t tmpreg; \ SET_BIT(RCC->APB2ENR, RCC_APB2ENR_ADC3EN);\ /* Delay after an RCC peripheral clock enabling */ \ tmpreg = READ_BIT(RCC->APB2ENR, RCC_APB2ENR_ADC3EN);\ UNUSED(tmpreg); \ } while(0) #define __HAL_RCC_SPI5_CLK_ENABLE() do { \ __IO uint32_t tmpreg; \ SET_BIT(RCC->APB2ENR, RCC_APB2ENR_SPI5EN);\ /* Delay after an RCC peripheral clock enabling */ \ tmpreg = READ_BIT(RCC->APB2ENR, RCC_APB2ENR_SPI5EN);\ UNUSED(tmpreg); \ } while(0) #define __HAL_RCC_SPI6_CLK_ENABLE() do { \ __IO uint32_t tmpreg; \ SET_BIT(RCC->APB2ENR, RCC_APB2ENR_SPI6EN);\ /* Delay after an RCC peripheral clock enabling */ \ tmpreg = READ_BIT(RCC->APB2ENR, RCC_APB2ENR_SPI6EN);\ UNUSED(tmpreg); \ } while(0) #define __HAL_RCC_SAI1_CLK_ENABLE() do { \ __IO uint32_t tmpreg; \ SET_BIT(RCC->APB2ENR, RCC_APB2ENR_SAI1EN);\ /* Delay after an RCC peripheral clock enabling */ \ tmpreg = READ_BIT(RCC->APB2ENR, RCC_APB2ENR_SAI1EN);\ UNUSED(tmpreg); \ } while(0) #define __HAL_RCC_SDIO_CLK_ENABLE() do { \ __IO uint32_t tmpreg; \ SET_BIT(RCC->APB2ENR, RCC_APB2ENR_SDIOEN);\ /* Delay after an RCC peripheral clock enabling */ \ tmpreg = READ_BIT(RCC->APB2ENR, RCC_APB2ENR_SDIOEN);\ UNUSED(tmpreg); \ } while(0) #define __HAL_RCC_SPI4_CLK_ENABLE() do { \ __IO uint32_t tmpreg; \ SET_BIT(RCC->APB2ENR, RCC_APB2ENR_SPI4EN);\ /* Delay after an RCC peripheral clock enabling */ \ tmpreg = READ_BIT(RCC->APB2ENR, RCC_APB2ENR_SPI4EN);\ UNUSED(tmpreg); \ } while(0) #define __HAL_RCC_TIM10_CLK_ENABLE() do { \ __IO uint32_t tmpreg; \ SET_BIT(RCC->APB2ENR, RCC_APB2ENR_TIM10EN);\ /* Delay after an RCC peripheral clock enabling */ \ tmpreg = READ_BIT(RCC->APB2ENR, RCC_APB2ENR_TIM10EN);\ UNUSED(tmpreg); \ } while(0) #define __HAL_RCC_SDIO_CLK_DISABLE() (RCC->APB2ENR &= ~(RCC_APB2ENR_SDIOEN)) #define __HAL_RCC_SPI4_CLK_DISABLE() (RCC->APB2ENR &= ~(RCC_APB2ENR_SPI4EN)) #define __HAL_RCC_TIM10_CLK_DISABLE() (RCC->APB2ENR &= ~(RCC_APB2ENR_TIM10EN)) #define __HAL_RCC_TIM8_CLK_DISABLE() (RCC->APB2ENR &= ~(RCC_APB2ENR_TIM8EN)) #define __HAL_RCC_ADC2_CLK_DISABLE() (RCC->APB2ENR &= ~(RCC_APB2ENR_ADC2EN)) #define __HAL_RCC_ADC3_CLK_DISABLE() (RCC->APB2ENR &= ~(RCC_APB2ENR_ADC3EN)) #define __HAL_RCC_SPI5_CLK_DISABLE() (RCC->APB2ENR &= ~(RCC_APB2ENR_SPI5EN)) #define __HAL_RCC_SPI6_CLK_DISABLE() (RCC->APB2ENR &= ~(RCC_APB2ENR_SPI6EN)) #define __HAL_RCC_SAI1_CLK_DISABLE() (RCC->APB2ENR &= ~(RCC_APB2ENR_SAI1EN)) #if defined(STM32F429xx)|| defined(STM32F439xx) || defined(STM32F469xx) || defined(STM32F479xx) #define __HAL_RCC_LTDC_CLK_ENABLE() do { \ __IO uint32_t tmpreg; \ SET_BIT(RCC->APB2ENR, RCC_APB2ENR_LTDCEN);\ /* Delay after an RCC peripheral clock enabling */ \ tmpreg = READ_BIT(RCC->APB2ENR, RCC_APB2ENR_LTDCEN);\ UNUSED(tmpreg); \ } while(0) #define __HAL_RCC_LTDC_CLK_DISABLE() (RCC->APB2ENR &= ~(RCC_APB2ENR_LTDCEN)) #endif /* STM32F429xx || STM32F439xx || STM32F469xx || STM32F479xx */ #if defined(STM32F469xx) || defined(STM32F479xx) #define __HAL_RCC_DSI_CLK_ENABLE() do { \ __IO uint32_t tmpreg; \ SET_BIT(RCC->APB2ENR, RCC_APB2ENR_DSIEN);\ /* Delay after an RCC peripheral clock enabling */ \ tmpreg = READ_BIT(RCC->APB2ENR, RCC_APB2ENR_DSIEN);\ UNUSED(tmpreg); \ } while(0) #define __HAL_RCC_DSI_CLK_DISABLE() (RCC->APB2ENR &= ~(RCC_APB2ENR_DSIEN)) #endif /* STM32F469xx || STM32F479xx */ /** * @} */ /** @defgroup RCCEx_AHB1_Force_Release_Reset AHB1 Force Release Reset * @brief Force or release AHB1 peripheral reset. */ #define __HAL_RCC_GPIOD_FORCE_RESET() (RCC->AHB1RSTR |= (RCC_AHB1RSTR_GPIODRST)) #define __HAL_RCC_GPIOE_FORCE_RESET() (RCC->AHB1RSTR |= (RCC_AHB1RSTR_GPIOERST)) #define __HAL_RCC_GPIOF_FORCE_RESET() (RCC->AHB1RSTR |= (RCC_AHB1RSTR_GPIOFRST)) #define __HAL_RCC_GPIOG_FORCE_RESET() (RCC->AHB1RSTR |= (RCC_AHB1RSTR_GPIOGRST)) #define __HAL_RCC_GPIOI_FORCE_RESET() (RCC->AHB1RSTR |= (RCC_AHB1RSTR_GPIOIRST)) #define __HAL_RCC_ETHMAC_FORCE_RESET() (RCC->AHB1RSTR |= (RCC_AHB1RSTR_ETHMACRST)) #define __HAL_RCC_USB_OTG_HS_FORCE_RESET() (RCC->AHB1RSTR |= (RCC_AHB1RSTR_OTGHRST)) #define __HAL_RCC_GPIOJ_FORCE_RESET() (RCC->AHB1RSTR |= (RCC_AHB1RSTR_GPIOJRST)) #define __HAL_RCC_GPIOK_FORCE_RESET() (RCC->AHB1RSTR |= (RCC_AHB1RSTR_GPIOKRST)) #define __HAL_RCC_DMA2D_FORCE_RESET() (RCC->AHB1RSTR |= (RCC_AHB1RSTR_DMA2DRST)) #define __HAL_RCC_CRC_FORCE_RESET() (RCC->AHB1RSTR |= (RCC_AHB1RSTR_CRCRST)) #define __HAL_RCC_GPIOD_RELEASE_RESET() (RCC->AHB1RSTR &= ~(RCC_AHB1RSTR_GPIODRST)) #define __HAL_RCC_GPIOE_RELEASE_RESET() (RCC->AHB1RSTR &= ~(RCC_AHB1RSTR_GPIOERST)) #define __HAL_RCC_GPIOF_RELEASE_RESET() (RCC->AHB1RSTR &= ~(RCC_AHB1RSTR_GPIOFRST)) #define __HAL_RCC_GPIOG_RELEASE_RESET() (RCC->AHB1RSTR &= ~(RCC_AHB1RSTR_GPIOGRST)) #define __HAL_RCC_GPIOI_RELEASE_RESET() (RCC->AHB1RSTR &= ~(RCC_AHB1RSTR_GPIOIRST)) #define __HAL_RCC_ETHMAC_RELEASE_RESET() (RCC->AHB1RSTR &= ~(RCC_AHB1RSTR_ETHMACRST)) #define __HAL_RCC_USB_OTG_HS_RELEASE_RESET() (RCC->AHB1RSTR &= ~(RCC_AHB1RSTR_OTGHRST)) #define __HAL_RCC_GPIOJ_RELEASE_RESET() (RCC->AHB1RSTR &= ~(RCC_AHB1RSTR_GPIOJRST)) #define __HAL_RCC_GPIOK_RELEASE_RESET() (RCC->AHB1RSTR &= ~(RCC_AHB1RSTR_GPIOKRST)) #define __HAL_RCC_DMA2D_RELEASE_RESET() (RCC->AHB1RSTR &= ~(RCC_AHB1RSTR_DMA2DRST)) #define __HAL_RCC_CRC_RELEASE_RESET() (RCC->AHB1RSTR &= ~(RCC_AHB1RSTR_CRCRST)) /** * @} */ /** @defgroup RCCEx_AHB2_Force_Release_Reset AHB2 Force Release Reset * @brief Force or release AHB2 peripheral reset. * @{ */ #define __HAL_RCC_AHB2_FORCE_RESET() (RCC->AHB2RSTR = 0xFFFFFFFF) #define __HAL_RCC_USB_OTG_FS_FORCE_RESET() (RCC->AHB2RSTR |= (RCC_AHB2RSTR_OTGFSRST)) #define __HAL_RCC_RNG_FORCE_RESET() (RCC->AHB2RSTR |= (RCC_AHB2RSTR_RNGRST)) #define __HAL_RCC_DCMI_FORCE_RESET() (RCC->AHB2RSTR |= (RCC_AHB2RSTR_DCMIRST)) #define __HAL_RCC_AHB2_RELEASE_RESET() (RCC->AHB2RSTR = 0x00) #define __HAL_RCC_USB_OTG_FS_RELEASE_RESET() (RCC->AHB2RSTR &= ~(RCC_AHB2RSTR_OTGFSRST)) #define __HAL_RCC_RNG_RELEASE_RESET() (RCC->AHB2RSTR &= ~(RCC_AHB2RSTR_RNGRST)) #define __HAL_RCC_DCMI_RELEASE_RESET() (RCC->AHB2RSTR &= ~(RCC_AHB2RSTR_DCMIRST)) #if defined(STM32F437xx)|| defined(STM32F439xx) || defined(STM32F479xx) #define __HAL_RCC_CRYP_FORCE_RESET() (RCC->AHB2RSTR |= (RCC_AHB2RSTR_CRYPRST)) #define __HAL_RCC_HASH_FORCE_RESET() (RCC->AHB2RSTR |= (RCC_AHB2RSTR_HASHRST)) #define __HAL_RCC_CRYP_RELEASE_RESET() (RCC->AHB2RSTR &= ~(RCC_AHB2RSTR_CRYPRST)) #define __HAL_RCC_HASH_RELEASE_RESET() (RCC->AHB2RSTR &= ~(RCC_AHB2RSTR_HASHRST)) #endif /* STM32F437xx || STM32F439xx || STM32F479xx */ /** * @} */ /** @defgroup RCCEx_AHB3_Force_Release_Reset AHB3 Force Release Reset * @brief Force or release AHB3 peripheral reset. * @{ */ #define __HAL_RCC_AHB3_FORCE_RESET() (RCC->AHB3RSTR = 0xFFFFFFFF) #define __HAL_RCC_AHB3_RELEASE_RESET() (RCC->AHB3RSTR = 0x00) #define __HAL_RCC_FMC_FORCE_RESET() (RCC->AHB3RSTR |= (RCC_AHB3RSTR_FMCRST)) #define __HAL_RCC_FMC_RELEASE_RESET() (RCC->AHB3RSTR &= ~(RCC_AHB3RSTR_FMCRST)) #if defined(STM32F469xx) || defined(STM32F479xx) #define __HAL_RCC_QSPI_FORCE_RESET() (RCC->AHB3RSTR |= (RCC_AHB3RSTR_QSPIRST)) #define __HAL_RCC_QSPI_RELEASE_RESET() (RCC->AHB3RSTR &= ~(RCC_AHB3RSTR_QSPIRST)) #endif /* STM32F469xx || STM32F479xx */ /** * @} */ /** @defgroup RCCEx_APB1_Force_Release_Reset APB1 Force Release Reset * @brief Force or release APB1 peripheral reset. */ #define __HAL_RCC_TIM6_FORCE_RESET() (RCC->APB1RSTR |= (RCC_APB1RSTR_TIM6RST)) #define __HAL_RCC_TIM7_FORCE_RESET() (RCC->APB1RSTR |= (RCC_APB1RSTR_TIM7RST)) #define __HAL_RCC_TIM12_FORCE_RESET() (RCC->APB1RSTR |= (RCC_APB1RSTR_TIM12RST)) #define __HAL_RCC_TIM13_FORCE_RESET() (RCC->APB1RSTR |= (RCC_APB1RSTR_TIM13RST)) #define __HAL_RCC_TIM14_FORCE_RESET() (RCC->APB1RSTR |= (RCC_APB1RSTR_TIM14RST)) #define __HAL_RCC_USART3_FORCE_RESET() (RCC->APB1RSTR |= (RCC_APB1RSTR_USART3RST)) #define __HAL_RCC_UART4_FORCE_RESET() (RCC->APB1RSTR |= (RCC_APB1RSTR_UART4RST)) #define __HAL_RCC_UART5_FORCE_RESET() (RCC->APB1RSTR |= (RCC_APB1RSTR_UART5RST)) #define __HAL_RCC_CAN1_FORCE_RESET() (RCC->APB1RSTR |= (RCC_APB1RSTR_CAN1RST)) #define __HAL_RCC_CAN2_FORCE_RESET() (RCC->APB1RSTR |= (RCC_APB1RSTR_CAN2RST)) #define __HAL_RCC_DAC_FORCE_RESET() (RCC->APB1RSTR |= (RCC_APB1RSTR_DACRST)) #define __HAL_RCC_UART7_FORCE_RESET() (RCC->APB1RSTR |= (RCC_APB1RSTR_UART7RST)) #define __HAL_RCC_UART8_FORCE_RESET() (RCC->APB1RSTR |= (RCC_APB1RSTR_UART8RST)) #define __HAL_RCC_TIM2_FORCE_RESET() (RCC->APB1RSTR |= (RCC_APB1RSTR_TIM2RST)) #define __HAL_RCC_TIM3_FORCE_RESET() (RCC->APB1RSTR |= (RCC_APB1RSTR_TIM3RST)) #define __HAL_RCC_TIM4_FORCE_RESET() (RCC->APB1RSTR |= (RCC_APB1RSTR_TIM4RST)) #define __HAL_RCC_SPI3_FORCE_RESET() (RCC->APB1RSTR |= (RCC_APB1RSTR_SPI3RST)) #define __HAL_RCC_I2C3_FORCE_RESET() (RCC->APB1RSTR |= (RCC_APB1RSTR_I2C3RST)) #define __HAL_RCC_TIM2_RELEASE_RESET() (RCC->APB1RSTR &= ~(RCC_APB1RSTR_TIM2RST)) #define __HAL_RCC_TIM3_RELEASE_RESET() (RCC->APB1RSTR &= ~(RCC_APB1RSTR_TIM3RST)) #define __HAL_RCC_TIM4_RELEASE_RESET() (RCC->APB1RSTR &= ~(RCC_APB1RSTR_TIM4RST)) #define __HAL_RCC_SPI3_RELEASE_RESET() (RCC->APB1RSTR &= ~(RCC_APB1RSTR_SPI3RST)) #define __HAL_RCC_I2C3_RELEASE_RESET() (RCC->APB1RSTR &= ~(RCC_APB1RSTR_I2C3RST)) #define __HAL_RCC_TIM6_RELEASE_RESET() (RCC->APB1RSTR &= ~(RCC_APB1RSTR_TIM6RST)) #define __HAL_RCC_TIM7_RELEASE_RESET() (RCC->APB1RSTR &= ~(RCC_APB1RSTR_TIM7RST)) #define __HAL_RCC_TIM12_RELEASE_RESET() (RCC->APB1RSTR &= ~(RCC_APB1RSTR_TIM12RST)) #define __HAL_RCC_TIM13_RELEASE_RESET() (RCC->APB1RSTR &= ~(RCC_APB1RSTR_TIM13RST)) #define __HAL_RCC_TIM14_RELEASE_RESET() (RCC->APB1RSTR &= ~(RCC_APB1RSTR_TIM14RST)) #define __HAL_RCC_USART3_RELEASE_RESET() (RCC->APB1RSTR &= ~(RCC_APB1RSTR_USART3RST)) #define __HAL_RCC_UART4_RELEASE_RESET() (RCC->APB1RSTR &= ~(RCC_APB1RSTR_UART4RST)) #define __HAL_RCC_UART5_RELEASE_RESET() (RCC->APB1RSTR &= ~(RCC_APB1RSTR_UART5RST)) #define __HAL_RCC_CAN1_RELEASE_RESET() (RCC->APB1RSTR &= ~(RCC_APB1RSTR_CAN1RST)) #define __HAL_RCC_CAN2_RELEASE_RESET() (RCC->APB1RSTR &= ~(RCC_APB1RSTR_CAN2RST)) #define __HAL_RCC_DAC_RELEASE_RESET() (RCC->APB1RSTR &= ~(RCC_APB1RSTR_DACRST)) #define __HAL_RCC_UART7_RELEASE_RESET() (RCC->APB1RSTR &= ~(RCC_APB1RSTR_UART7RST)) #define __HAL_RCC_UART8_RELEASE_RESET() (RCC->APB1RSTR &= ~(RCC_APB1RSTR_UART8RST)) /** * @} */ /** @defgroup RCCEx_APB2_Force_Release_Reset APB2 Force Release Reset * @brief Force or release APB2 peripheral reset. */ #define __HAL_RCC_TIM8_FORCE_RESET() (RCC->APB2RSTR |= (RCC_APB2RSTR_TIM8RST)) #define __HAL_RCC_SPI5_FORCE_RESET() (RCC->APB2RSTR |= (RCC_APB2RSTR_SPI5RST)) #define __HAL_RCC_SPI6_FORCE_RESET() (RCC->APB2RSTR |= (RCC_APB2RSTR_SPI6RST)) #define __HAL_RCC_SAI1_FORCE_RESET() (RCC->APB2RSTR |= (RCC_APB2RSTR_SAI1RST)) #define __HAL_RCC_SDIO_FORCE_RESET() (RCC->APB2RSTR |= (RCC_APB2RSTR_SDIORST)) #define __HAL_RCC_SPI4_FORCE_RESET() (RCC->APB2RSTR |= (RCC_APB2RSTR_SPI4RST)) #define __HAL_RCC_TIM10_FORCE_RESET() (RCC->APB2RSTR |= (RCC_APB2RSTR_TIM10RST)) #define __HAL_RCC_SDIO_RELEASE_RESET() (RCC->APB2RSTR &= ~(RCC_APB2RSTR_SDIORST)) #define __HAL_RCC_SPI4_RELEASE_RESET() (RCC->APB2RSTR &= ~(RCC_APB2RSTR_SPI4RST)) #define __HAL_RCC_TIM10_RELEASE_RESET()(RCC->APB2RSTR &= ~(RCC_APB2RSTR_TIM10RST)) #define __HAL_RCC_TIM8_RELEASE_RESET() (RCC->APB2RSTR &= ~(RCC_APB2RSTR_TIM8RST)) #define __HAL_RCC_SPI5_RELEASE_RESET() (RCC->APB2RSTR &= ~(RCC_APB2RSTR_SPI5RST)) #define __HAL_RCC_SPI6_RELEASE_RESET() (RCC->APB2RSTR &= ~(RCC_APB2RSTR_SPI6RST)) #define __HAL_RCC_SAI1_RELEASE_RESET() (RCC->APB2RSTR &= ~(RCC_APB2RSTR_SAI1RST)) #if defined(STM32F429xx)|| defined(STM32F439xx) || defined(STM32F469xx) || defined(STM32F479xx) #define __HAL_RCC_LTDC_FORCE_RESET() (RCC->APB2RSTR |= (RCC_APB2RSTR_LTDCRST)) #define __HAL_RCC_LTDC_RELEASE_RESET() (RCC->APB2RSTR &= ~(RCC_APB2RSTR_LTDCRST)) #endif /* STM32F429xx|| STM32F439xx || STM32F469xx || STM32F479xx */ #if defined(STM32F469xx) || defined(STM32F479xx) #define __HAL_RCC_DSI_FORCE_RESET() (RCC->APB2RSTR |= (RCC_APB2RSTR_DSIRST)) #define __HAL_RCC_DSI_RELEASE_RESET() (RCC->APB2RSTR &= ~(RCC_APB2RSTR_DSIRST)) #endif /* STM32F469xx || STM32F479xx */ /** * @} */ /** @defgroup RCCEx_AHB1_LowPower_Enable_Disable AHB1 Peripheral Low Power Enable Disable * @brief Enable or disable the AHB1 peripheral clock during Low Power (Sleep) mode. * @note Peripheral clock gating in SLEEP mode can be used to further reduce * power consumption. * @note After wakeup from SLEEP mode, the peripheral clock is enabled again. * @note By default, all peripheral clocks are enabled during SLEEP mode. */ #define __HAL_RCC_GPIOD_CLK_SLEEP_ENABLE() (RCC->AHB1LPENR |= (RCC_AHB1LPENR_GPIODLPEN)) #define __HAL_RCC_GPIOE_CLK_SLEEP_ENABLE() (RCC->AHB1LPENR |= (RCC_AHB1LPENR_GPIOELPEN)) #define __HAL_RCC_GPIOF_CLK_SLEEP_ENABLE() (RCC->AHB1LPENR |= (RCC_AHB1LPENR_GPIOFLPEN)) #define __HAL_RCC_GPIOG_CLK_SLEEP_ENABLE() (RCC->AHB1LPENR |= (RCC_AHB1LPENR_GPIOGLPEN)) #define __HAL_RCC_GPIOI_CLK_SLEEP_ENABLE() (RCC->AHB1LPENR |= (RCC_AHB1LPENR_GPIOILPEN)) #define __HAL_RCC_SRAM2_CLK_SLEEP_ENABLE() (RCC->AHB1LPENR |= (RCC_AHB1LPENR_SRAM2LPEN)) #define __HAL_RCC_ETHMAC_CLK_SLEEP_ENABLE() (RCC->AHB1LPENR |= (RCC_AHB1LPENR_ETHMACLPEN)) #define __HAL_RCC_ETHMACTX_CLK_SLEEP_ENABLE() (RCC->AHB1LPENR |= (RCC_AHB1LPENR_ETHMACTXLPEN)) #define __HAL_RCC_ETHMACRX_CLK_SLEEP_ENABLE() (RCC->AHB1LPENR |= (RCC_AHB1LPENR_ETHMACRXLPEN)) #define __HAL_RCC_ETHMACPTP_CLK_SLEEP_ENABLE() (RCC->AHB1LPENR |= (RCC_AHB1LPENR_ETHMACPTPLPEN)) #define __HAL_RCC_USB_OTG_HS_CLK_SLEEP_ENABLE() (RCC->AHB1LPENR |= (RCC_AHB1LPENR_OTGHSLPEN)) #define __HAL_RCC_USB_OTG_HS_ULPI_CLK_SLEEP_ENABLE() (RCC->AHB1LPENR |= (RCC_AHB1LPENR_OTGHSULPILPEN)) #define __HAL_RCC_GPIOJ_CLK_SLEEP_ENABLE() (RCC->AHB1LPENR |= (RCC_AHB1LPENR_GPIOJLPEN)) #define __HAL_RCC_GPIOK_CLK_SLEEP_ENABLE() (RCC->AHB1LPENR |= (RCC_AHB1LPENR_GPIOKLPEN)) #define __HAL_RCC_SRAM3_CLK_SLEEP_ENABLE() (RCC->AHB1LPENR |= (RCC_AHB1LPENR_SRAM3LPEN)) #define __HAL_RCC_DMA2D_CLK_SLEEP_ENABLE() (RCC->AHB1LPENR |= (RCC_AHB1LPENR_DMA2DLPEN)) #define __HAL_RCC_CRC_CLK_SLEEP_ENABLE() (RCC->AHB1LPENR |= (RCC_AHB1LPENR_CRCLPEN)) #define __HAL_RCC_FLITF_CLK_SLEEP_ENABLE() (RCC->AHB1LPENR |= (RCC_AHB1LPENR_FLITFLPEN)) #define __HAL_RCC_SRAM1_CLK_SLEEP_ENABLE() (RCC->AHB1LPENR |= (RCC_AHB1LPENR_SRAM1LPEN)) #define __HAL_RCC_BKPSRAM_CLK_SLEEP_ENABLE() (RCC->AHB1LPENR |= (RCC_AHB1LPENR_BKPSRAMLPEN)) #define __HAL_RCC_GPIOD_CLK_SLEEP_DISABLE() (RCC->AHB1LPENR &= ~(RCC_AHB1LPENR_GPIODLPEN)) #define __HAL_RCC_GPIOE_CLK_SLEEP_DISABLE() (RCC->AHB1LPENR &= ~(RCC_AHB1LPENR_GPIOELPEN)) #define __HAL_RCC_GPIOF_CLK_SLEEP_DISABLE() (RCC->AHB1LPENR &= ~(RCC_AHB1LPENR_GPIOFLPEN)) #define __HAL_RCC_GPIOG_CLK_SLEEP_DISABLE() (RCC->AHB1LPENR &= ~(RCC_AHB1LPENR_GPIOGLPEN)) #define __HAL_RCC_GPIOI_CLK_SLEEP_DISABLE() (RCC->AHB1LPENR &= ~(RCC_AHB1LPENR_GPIOILPEN)) #define __HAL_RCC_SRAM2_CLK_SLEEP_DISABLE() (RCC->AHB1LPENR &= ~(RCC_AHB1LPENR_SRAM2LPEN)) #define __HAL_RCC_ETHMAC_CLK_SLEEP_DISABLE() (RCC->AHB1LPENR &= ~(RCC_AHB1LPENR_ETHMACLPEN)) #define __HAL_RCC_ETHMACTX_CLK_SLEEP_DISABLE() (RCC->AHB1LPENR &= ~(RCC_AHB1LPENR_ETHMACTXLPEN)) #define __HAL_RCC_ETHMACRX_CLK_SLEEP_DISABLE() (RCC->AHB1LPENR &= ~(RCC_AHB1LPENR_ETHMACRXLPEN)) #define __HAL_RCC_ETHMACPTP_CLK_SLEEP_DISABLE() (RCC->AHB1LPENR &= ~(RCC_AHB1LPENR_ETHMACPTPLPEN)) #define __HAL_RCC_USB_OTG_HS_CLK_SLEEP_DISABLE() (RCC->AHB1LPENR &= ~(RCC_AHB1LPENR_OTGHSLPEN)) #define __HAL_RCC_USB_OTG_HS_ULPI_CLK_SLEEP_DISABLE() (RCC->AHB1LPENR &= ~(RCC_AHB1LPENR_OTGHSULPILPEN)) #define __HAL_RCC_GPIOJ_CLK_SLEEP_DISABLE() (RCC->AHB1LPENR &= ~(RCC_AHB1LPENR_GPIOJLPEN)) #define __HAL_RCC_GPIOK_CLK_SLEEP_DISABLE() (RCC->AHB1LPENR &= ~(RCC_AHB1LPENR_GPIOKLPEN)) #define __HAL_RCC_DMA2D_CLK_SLEEP_DISABLE() (RCC->AHB1LPENR &= ~(RCC_AHB1LPENR_DMA2DLPEN)) #define __HAL_RCC_CRC_CLK_SLEEP_DISABLE() (RCC->AHB1LPENR &= ~(RCC_AHB1LPENR_CRCLPEN)) #define __HAL_RCC_FLITF_CLK_SLEEP_DISABLE() (RCC->AHB1LPENR &= ~(RCC_AHB1LPENR_FLITFLPEN)) #define __HAL_RCC_SRAM1_CLK_SLEEP_DISABLE() (RCC->AHB1LPENR &= ~(RCC_AHB1LPENR_SRAM1LPEN)) #define __HAL_RCC_BKPSRAM_CLK_SLEEP_DISABLE() (RCC->AHB1LPENR &= ~(RCC_AHB1LPENR_BKPSRAMLPEN)) /** * @} */ /** @defgroup RCCEx_AHB2_LowPower_Enable_Disable AHB2 Peripheral Low Power Enable Disable * @brief Enable or disable the AHB2 peripheral clock during Low Power (Sleep) mode. * @note Peripheral clock gating in SLEEP mode can be used to further reduce * power consumption. * @note After wake-up from SLEEP mode, the peripheral clock is enabled again. * @note By default, all peripheral clocks are enabled during SLEEP mode. * @{ */ #define __HAL_RCC_USB_OTG_FS_CLK_SLEEP_ENABLE() (RCC->AHB2LPENR |= (RCC_AHB2LPENR_OTGFSLPEN)) #define __HAL_RCC_USB_OTG_FS_CLK_SLEEP_DISABLE() (RCC->AHB2LPENR &= ~(RCC_AHB2LPENR_OTGFSLPEN)) #define __HAL_RCC_RNG_CLK_SLEEP_ENABLE() (RCC->AHB2LPENR |= (RCC_AHB2LPENR_RNGLPEN)) #define __HAL_RCC_RNG_CLK_SLEEP_DISABLE() (RCC->AHB2LPENR &= ~(RCC_AHB2LPENR_RNGLPEN)) #define __HAL_RCC_DCMI_CLK_SLEEP_ENABLE() (RCC->AHB2LPENR |= (RCC_AHB2LPENR_DCMILPEN)) #define __HAL_RCC_DCMI_CLK_SLEEP_DISABLE() (RCC->AHB2LPENR &= ~(RCC_AHB2LPENR_DCMILPEN)) #if defined(STM32F437xx)|| defined(STM32F439xx) || defined(STM32F479xx) #define __HAL_RCC_CRYP_CLK_SLEEP_ENABLE() (RCC->AHB2LPENR |= (RCC_AHB2LPENR_CRYPLPEN)) #define __HAL_RCC_HASH_CLK_SLEEP_ENABLE() (RCC->AHB2LPENR |= (RCC_AHB2LPENR_HASHLPEN)) #define __HAL_RCC_CRYP_CLK_SLEEP_DISABLE() (RCC->AHB2LPENR &= ~(RCC_AHB2LPENR_CRYPLPEN)) #define __HAL_RCC_HASH_CLK_SLEEP_DISABLE() (RCC->AHB2LPENR &= ~(RCC_AHB2LPENR_HASHLPEN)) #endif /* STM32F437xx || STM32F439xx || STM32F479xx */ /** * @} */ /** @defgroup RCCEx_AHB3_LowPower_Enable_Disable AHB3 Peripheral Low Power Enable Disable * @brief Enable or disable the AHB3 peripheral clock during Low Power (Sleep) mode. * @note Peripheral clock gating in SLEEP mode can be used to further reduce * power consumption. * @note After wakeup from SLEEP mode, the peripheral clock is enabled again. * @note By default, all peripheral clocks are enabled during SLEEP mode. */ #define __HAL_RCC_FMC_CLK_SLEEP_ENABLE() (RCC->AHB3LPENR |= (RCC_AHB3LPENR_FMCLPEN)) #define __HAL_RCC_FMC_CLK_SLEEP_DISABLE() (RCC->AHB3LPENR &= ~(RCC_AHB3LPENR_FMCLPEN)) #if defined(STM32F469xx) || defined(STM32F479xx) #define __HAL_RCC_QSPI_CLK_SLEEP_ENABLE() (RCC->AHB3LPENR |= (RCC_AHB3LPENR_QSPILPEN)) #define __HAL_RCC_QSPI_CLK_SLEEP_DISABLE() (RCC->AHB3LPENR &= ~(RCC_AHB3LPENR_QSPILPEN)) #endif /* STM32F469xx || STM32F479xx */ /** * @} */ /** @defgroup RCCEx_APB1_LowPower_Enable_Disable APB1 Peripheral Low Power Enable Disable * @brief Enable or disable the APB1 peripheral clock during Low Power (Sleep) mode. * @note Peripheral clock gating in SLEEP mode can be used to further reduce * power consumption. * @note After wakeup from SLEEP mode, the peripheral clock is enabled again. * @note By default, all peripheral clocks are enabled during SLEEP mode. */ #define __HAL_RCC_TIM6_CLK_SLEEP_ENABLE() (RCC->APB1LPENR |= (RCC_APB1LPENR_TIM6LPEN)) #define __HAL_RCC_TIM7_CLK_SLEEP_ENABLE() (RCC->APB1LPENR |= (RCC_APB1LPENR_TIM7LPEN)) #define __HAL_RCC_TIM12_CLK_SLEEP_ENABLE() (RCC->APB1LPENR |= (RCC_APB1LPENR_TIM12LPEN)) #define __HAL_RCC_TIM13_CLK_SLEEP_ENABLE() (RCC->APB1LPENR |= (RCC_APB1LPENR_TIM13LPEN)) #define __HAL_RCC_TIM14_CLK_SLEEP_ENABLE() (RCC->APB1LPENR |= (RCC_APB1LPENR_TIM14LPEN)) #define __HAL_RCC_USART3_CLK_SLEEP_ENABLE() (RCC->APB1LPENR |= (RCC_APB1LPENR_USART3LPEN)) #define __HAL_RCC_UART4_CLK_SLEEP_ENABLE() (RCC->APB1LPENR |= (RCC_APB1LPENR_UART4LPEN)) #define __HAL_RCC_UART5_CLK_SLEEP_ENABLE() (RCC->APB1LPENR |= (RCC_APB1LPENR_UART5LPEN)) #define __HAL_RCC_CAN1_CLK_SLEEP_ENABLE() (RCC->APB1LPENR |= (RCC_APB1LPENR_CAN1LPEN)) #define __HAL_RCC_CAN2_CLK_SLEEP_ENABLE() (RCC->APB1LPENR |= (RCC_APB1LPENR_CAN2LPEN)) #define __HAL_RCC_DAC_CLK_SLEEP_ENABLE() (RCC->APB1LPENR |= (RCC_APB1LPENR_DACLPEN)) #define __HAL_RCC_UART7_CLK_SLEEP_ENABLE() (RCC->APB1LPENR |= (RCC_APB1LPENR_UART7LPEN)) #define __HAL_RCC_UART8_CLK_SLEEP_ENABLE() (RCC->APB1LPENR |= (RCC_APB1LPENR_UART8LPEN)) #define __HAL_RCC_TIM2_CLK_SLEEP_ENABLE() (RCC->APB1LPENR |= (RCC_APB1LPENR_TIM2LPEN)) #define __HAL_RCC_TIM3_CLK_SLEEP_ENABLE() (RCC->APB1LPENR |= (RCC_APB1LPENR_TIM3LPEN)) #define __HAL_RCC_TIM4_CLK_SLEEP_ENABLE() (RCC->APB1LPENR |= (RCC_APB1LPENR_TIM4LPEN)) #define __HAL_RCC_SPI3_CLK_SLEEP_ENABLE() (RCC->APB1LPENR |= (RCC_APB1LPENR_SPI3LPEN)) #define __HAL_RCC_I2C3_CLK_SLEEP_ENABLE() (RCC->APB1LPENR |= (RCC_APB1LPENR_I2C3LPEN)) #define __HAL_RCC_TIM2_CLK_SLEEP_DISABLE() (RCC->APB1LPENR &= ~(RCC_APB1LPENR_TIM2LPEN)) #define __HAL_RCC_TIM3_CLK_SLEEP_DISABLE() (RCC->APB1LPENR &= ~(RCC_APB1LPENR_TIM3LPEN)) #define __HAL_RCC_TIM4_CLK_SLEEP_DISABLE() (RCC->APB1LPENR &= ~(RCC_APB1LPENR_TIM4LPEN)) #define __HAL_RCC_SPI3_CLK_SLEEP_DISABLE() (RCC->APB1LPENR &= ~(RCC_APB1LPENR_SPI3LPEN)) #define __HAL_RCC_I2C3_CLK_SLEEP_DISABLE() (RCC->APB1LPENR &= ~(RCC_APB1LPENR_I2C3LPEN)) #define __HAL_RCC_TIM6_CLK_SLEEP_DISABLE() (RCC->APB1LPENR &= ~(RCC_APB1LPENR_TIM6LPEN)) #define __HAL_RCC_TIM7_CLK_SLEEP_DISABLE() (RCC->APB1LPENR &= ~(RCC_APB1LPENR_TIM7LPEN)) #define __HAL_RCC_TIM12_CLK_SLEEP_DISABLE() (RCC->APB1LPENR &= ~(RCC_APB1LPENR_TIM12LPEN)) #define __HAL_RCC_TIM13_CLK_SLEEP_DISABLE() (RCC->APB1LPENR &= ~(RCC_APB1LPENR_TIM13LPEN)) #define __HAL_RCC_TIM14_CLK_SLEEP_DISABLE() (RCC->APB1LPENR &= ~(RCC_APB1LPENR_TIM14LPEN)) #define __HAL_RCC_USART3_CLK_SLEEP_DISABLE() (RCC->APB1LPENR &= ~(RCC_APB1LPENR_USART3LPEN)) #define __HAL_RCC_UART4_CLK_SLEEP_DISABLE() (RCC->APB1LPENR &= ~(RCC_APB1LPENR_UART4LPEN)) #define __HAL_RCC_UART5_CLK_SLEEP_DISABLE() (RCC->APB1LPENR &= ~(RCC_APB1LPENR_UART5LPEN)) #define __HAL_RCC_CAN1_CLK_SLEEP_DISABLE() (RCC->APB1LPENR &= ~(RCC_APB1LPENR_CAN1LPEN)) #define __HAL_RCC_CAN2_CLK_SLEEP_DISABLE() (RCC->APB1LPENR &= ~(RCC_APB1LPENR_CAN2LPEN)) #define __HAL_RCC_DAC_CLK_SLEEP_DISABLE() (RCC->APB1LPENR &= ~(RCC_APB1LPENR_DACLPEN)) #define __HAL_RCC_UART7_CLK_SLEEP_DISABLE() (RCC->APB1LPENR &= ~(RCC_APB1LPENR_UART7LPEN)) #define __HAL_RCC_UART8_CLK_SLEEP_DISABLE() (RCC->APB1LPENR &= ~(RCC_APB1LPENR_UART8LPEN)) /** * @} */ /** @defgroup RCCEx_APB2_LowPower_Enable_Disable APB2 Peripheral Low Power Enable Disable * @brief Enable or disable the APB2 peripheral clock during Low Power (Sleep) mode. * @note Peripheral clock gating in SLEEP mode can be used to further reduce * power consumption. * @note After wakeup from SLEEP mode, the peripheral clock is enabled again. * @note By default, all peripheral clocks are enabled during SLEEP mode. */ #define __HAL_RCC_TIM8_CLK_SLEEP_ENABLE() (RCC->APB2LPENR |= (RCC_APB2LPENR_TIM8LPEN)) #define __HAL_RCC_ADC2_CLK_SLEEP_ENABLE() (RCC->APB2LPENR |= (RCC_APB2LPENR_ADC2LPEN)) #define __HAL_RCC_ADC3_CLK_SLEEP_ENABLE() (RCC->APB2LPENR |= (RCC_APB2LPENR_ADC3LPEN)) #define __HAL_RCC_SPI5_CLK_SLEEP_ENABLE() (RCC->APB2LPENR |= (RCC_APB2LPENR_SPI5LPEN)) #define __HAL_RCC_SPI6_CLK_SLEEP_ENABLE() (RCC->APB2LPENR |= (RCC_APB2LPENR_SPI6LPEN)) #define __HAL_RCC_SAI1_CLK_SLEEP_ENABLE() (RCC->APB2LPENR |= (RCC_APB2LPENR_SAI1LPEN)) #define __HAL_RCC_SDIO_CLK_SLEEP_ENABLE() (RCC->APB2LPENR |= (RCC_APB2LPENR_SDIOLPEN)) #define __HAL_RCC_SPI4_CLK_SLEEP_ENABLE() (RCC->APB2LPENR |= (RCC_APB2LPENR_SPI4LPEN)) #define __HAL_RCC_TIM10_CLK_SLEEP_ENABLE()(RCC->APB2LPENR |= (RCC_APB2LPENR_TIM10LPEN)) #define __HAL_RCC_SDIO_CLK_SLEEP_DISABLE() (RCC->APB2LPENR &= ~(RCC_APB2LPENR_SDIOLPEN)) #define __HAL_RCC_SPI4_CLK_SLEEP_DISABLE() (RCC->APB2LPENR &= ~(RCC_APB2LPENR_SPI4LPEN)) #define __HAL_RCC_TIM10_CLK_SLEEP_DISABLE()(RCC->APB2LPENR &= ~(RCC_APB2LPENR_TIM10LPEN)) #define __HAL_RCC_TIM8_CLK_SLEEP_DISABLE() (RCC->APB2LPENR &= ~(RCC_APB2LPENR_TIM8LPEN)) #define __HAL_RCC_ADC2_CLK_SLEEP_DISABLE() (RCC->APB2LPENR &= ~(RCC_APB2LPENR_ADC2LPEN)) #define __HAL_RCC_ADC3_CLK_SLEEP_DISABLE() (RCC->APB2LPENR &= ~(RCC_APB2LPENR_ADC3LPEN)) #define __HAL_RCC_SPI5_CLK_SLEEP_DISABLE() (RCC->APB2LPENR &= ~(RCC_APB2LPENR_SPI5LPEN)) #define __HAL_RCC_SPI6_CLK_SLEEP_DISABLE() (RCC->APB2LPENR &= ~(RCC_APB2LPENR_SPI6LPEN)) #define __HAL_RCC_SAI1_CLK_SLEEP_DISABLE() (RCC->APB2LPENR &= ~(RCC_APB2LPENR_SAI1LPEN)) #if defined(STM32F429xx)|| defined(STM32F439xx) || defined(STM32F469xx) || defined(STM32F479xx) #define __HAL_RCC_LTDC_CLK_SLEEP_ENABLE() (RCC->APB2LPENR |= (RCC_APB2LPENR_LTDCLPEN)) #define __HAL_RCC_LTDC_CLK_SLEEP_DISABLE() (RCC->APB2LPENR &= ~(RCC_APB2LPENR_LTDCLPEN)) #endif /* STM32F429xx || STM32F439xx || STM32F469xx || STM32F479xx */ #if defined(STM32F469xx) || defined(STM32F479xx) #define __HAL_RCC_DSI_CLK_SLEEP_ENABLE() (RCC->APB2LPENR |= (RCC_APB2LPENR_DSILPEN)) #define __HAL_RCC_DSI_CLK_SLEEP_DISABLE() (RCC->APB2LPENR &= ~(RCC_APB2LPENR_DSILPEN)) #endif /* STM32F469xx || STM32F479xx */ /** * @} */ #endif /* STM32F427xx || STM32F437xx || STM32F429xx|| STM32F439xx || STM32F469xx || STM32F479xx */ /*----------------------------------------------------------------------------*/ /*----------------------------------- STM32F40xxx/STM32F41xxx-----------------*/ #if defined(STM32F405xx) || defined(STM32F415xx) || defined(STM32F407xx)|| defined(STM32F417xx) /** @defgroup RCCEx_AHB1_Clock_Enable_Disable AHB1 Peripheral Clock Enable Disable * @brief Enables or disables the AHB1 peripheral clock. * @note After reset, the peripheral clock (used for registers read/write access) * is disabled and the application software has to enable this clock before * using it. */ #define __HAL_RCC_BKPSRAM_CLK_ENABLE() do { \ __IO uint32_t tmpreg; \ SET_BIT(RCC->AHB1ENR, RCC_AHB1ENR_BKPSRAMEN);\ /* Delay after an RCC peripheral clock enabling */ \ tmpreg = READ_BIT(RCC->AHB1ENR, RCC_AHB1ENR_BKPSRAMEN);\ UNUSED(tmpreg); \ } while(0) #define __HAL_RCC_CCMDATARAMEN_CLK_ENABLE() do { \ __IO uint32_t tmpreg; \ SET_BIT(RCC->AHB1ENR, RCC_AHB1ENR_CCMDATARAMEN);\ /* Delay after an RCC peripheral clock enabling */ \ tmpreg = READ_BIT(RCC->AHB1ENR, RCC_AHB1ENR_CCMDATARAMEN);\ UNUSED(tmpreg); \ } while(0) #define __HAL_RCC_CRC_CLK_ENABLE() do { \ __IO uint32_t tmpreg; \ SET_BIT(RCC->AHB1ENR, RCC_AHB1ENR_CRCEN);\ /* Delay after an RCC peripheral clock enabling */ \ tmpreg = READ_BIT(RCC->AHB1ENR, RCC_AHB1ENR_CRCEN);\ UNUSED(tmpreg); \ } while(0) #define __HAL_RCC_GPIOD_CLK_ENABLE() do { \ __IO uint32_t tmpreg; \ SET_BIT(RCC->AHB1ENR, RCC_AHB1ENR_GPIODEN);\ /* Delay after an RCC peripheral clock enabling */ \ tmpreg = READ_BIT(RCC->AHB1ENR, RCC_AHB1ENR_GPIODEN);\ UNUSED(tmpreg); \ } while(0) #define __HAL_RCC_GPIOE_CLK_ENABLE() do { \ __IO uint32_t tmpreg; \ SET_BIT(RCC->AHB1ENR, RCC_AHB1ENR_GPIOEEN);\ /* Delay after an RCC peripheral clock enabling */ \ tmpreg = READ_BIT(RCC->AHB1ENR, RCC_AHB1ENR_GPIOEEN);\ UNUSED(tmpreg); \ } while(0) #define __HAL_RCC_GPIOI_CLK_ENABLE() do { \ __IO uint32_t tmpreg; \ SET_BIT(RCC->AHB1ENR, RCC_AHB1ENR_GPIOIEN);\ /* Delay after an RCC peripheral clock enabling */ \ tmpreg = READ_BIT(RCC->AHB1ENR, RCC_AHB1ENR_GPIOIEN);\ UNUSED(tmpreg); \ } while(0) #define __HAL_RCC_GPIOF_CLK_ENABLE() do { \ __IO uint32_t tmpreg; \ SET_BIT(RCC->AHB1ENR, RCC_AHB1ENR_GPIOFEN);\ /* Delay after an RCC peripheral clock enabling */ \ tmpreg = READ_BIT(RCC->AHB1ENR, RCC_AHB1ENR_GPIOFEN);\ UNUSED(tmpreg); \ } while(0) #define __HAL_RCC_GPIOG_CLK_ENABLE() do { \ __IO uint32_t tmpreg; \ SET_BIT(RCC->AHB1ENR, RCC_AHB1ENR_GPIOGEN);\ /* Delay after an RCC peripheral clock enabling */ \ tmpreg = READ_BIT(RCC->AHB1ENR, RCC_AHB1ENR_GPIOGEN);\ UNUSED(tmpreg); \ } while(0) #define __HAL_RCC_USB_OTG_HS_CLK_ENABLE() do { \ __IO uint32_t tmpreg; \ SET_BIT(RCC->AHB1ENR, RCC_AHB1ENR_OTGHSEN);\ /* Delay after an RCC peripheral clock enabling */ \ tmpreg = READ_BIT(RCC->AHB1ENR, RCC_AHB1ENR_OTGHSEN);\ UNUSED(tmpreg); \ } while(0) #define __HAL_RCC_USB_OTG_HS_ULPI_CLK_ENABLE() do { \ __IO uint32_t tmpreg; \ SET_BIT(RCC->AHB1ENR, RCC_AHB1ENR_OTGHSULPIEN);\ /* Delay after an RCC peripheral clock enabling */ \ tmpreg = READ_BIT(RCC->AHB1ENR, RCC_AHB1ENR_OTGHSULPIEN);\ UNUSED(tmpreg); \ } while(0) #define __HAL_RCC_GPIOD_CLK_DISABLE() (RCC->AHB1ENR &= ~(RCC_AHB1ENR_GPIODEN)) #define __HAL_RCC_GPIOE_CLK_DISABLE() (RCC->AHB1ENR &= ~(RCC_AHB1ENR_GPIOEEN)) #define __HAL_RCC_GPIOF_CLK_DISABLE() (RCC->AHB1ENR &= ~(RCC_AHB1ENR_GPIOFEN)) #define __HAL_RCC_GPIOG_CLK_DISABLE() (RCC->AHB1ENR &= ~(RCC_AHB1ENR_GPIOGEN)) #define __HAL_RCC_GPIOI_CLK_DISABLE() (RCC->AHB1ENR &= ~(RCC_AHB1ENR_GPIOIEN)) #define __HAL_RCC_USB_OTG_HS_CLK_DISABLE() (RCC->AHB1ENR &= ~(RCC_AHB1ENR_OTGHSEN)) #define __HAL_RCC_USB_OTG_HS_ULPI_CLK_DISABLE() (RCC->AHB1ENR &= ~(RCC_AHB1ENR_OTGHSULPIEN)) #define __HAL_RCC_BKPSRAM_CLK_DISABLE() (RCC->AHB1ENR &= ~(RCC_AHB1ENR_BKPSRAMEN)) #define __HAL_RCC_CCMDATARAMEN_CLK_DISABLE() (RCC->AHB1ENR &= ~(RCC_AHB1ENR_CCMDATARAMEN)) #define __HAL_RCC_CRC_CLK_DISABLE() (RCC->AHB1ENR &= ~(RCC_AHB1ENR_CRCEN)) #if defined(STM32F407xx)|| defined(STM32F417xx) /** * @brief Enable ETHERNET clock. */ #define __HAL_RCC_ETHMAC_CLK_ENABLE() do { \ __IO uint32_t tmpreg; \ SET_BIT(RCC->AHB1ENR, RCC_AHB1ENR_ETHMACEN);\ /* Delay after an RCC peripheral clock enabling */ \ tmpreg = READ_BIT(RCC->AHB1ENR, RCC_AHB1ENR_ETHMACEN);\ UNUSED(tmpreg); \ } while(0) #define __HAL_RCC_ETHMACTX_CLK_ENABLE() do { \ __IO uint32_t tmpreg; \ SET_BIT(RCC->AHB1ENR, RCC_AHB1ENR_ETHMACTXEN);\ /* Delay after an RCC peripheral clock enabling */ \ tmpreg = READ_BIT(RCC->AHB1ENR, RCC_AHB1ENR_ETHMACTXEN);\ UNUSED(tmpreg); \ } while(0) #define __HAL_RCC_ETHMACRX_CLK_ENABLE() do { \ __IO uint32_t tmpreg; \ SET_BIT(RCC->AHB1ENR, RCC_AHB1ENR_ETHMACRXEN);\ /* Delay after an RCC peripheral clock enabling */ \ tmpreg = READ_BIT(RCC->AHB1ENR, RCC_AHB1ENR_ETHMACRXEN);\ UNUSED(tmpreg); \ } while(0) #define __HAL_RCC_ETHMACPTP_CLK_ENABLE() do { \ __IO uint32_t tmpreg; \ SET_BIT(RCC->AHB1ENR, RCC_AHB1ENR_ETHMACPTPEN);\ /* Delay after an RCC peripheral clock enabling */ \ tmpreg = READ_BIT(RCC->AHB1ENR, RCC_AHB1ENR_ETHMACPTPEN);\ UNUSED(tmpreg); \ } while(0) #define __HAL_RCC_ETH_CLK_ENABLE() do { \ __HAL_RCC_ETHMAC_CLK_ENABLE(); \ __HAL_RCC_ETHMACTX_CLK_ENABLE(); \ __HAL_RCC_ETHMACRX_CLK_ENABLE(); \ } while(0) /** * @brief Disable ETHERNET clock. */ #define __HAL_RCC_ETHMAC_CLK_DISABLE() (RCC->AHB1ENR &= ~(RCC_AHB1ENR_ETHMACEN)) #define __HAL_RCC_ETHMACTX_CLK_DISABLE() (RCC->AHB1ENR &= ~(RCC_AHB1ENR_ETHMACTXEN)) #define __HAL_RCC_ETHMACRX_CLK_DISABLE() (RCC->AHB1ENR &= ~(RCC_AHB1ENR_ETHMACRXEN)) #define __HAL_RCC_ETHMACPTP_CLK_DISABLE() (RCC->AHB1ENR &= ~(RCC_AHB1ENR_ETHMACPTPEN)) #define __HAL_RCC_ETH_CLK_DISABLE() do { \ __HAL_RCC_ETHMACTX_CLK_DISABLE(); \ __HAL_RCC_ETHMACRX_CLK_DISABLE(); \ __HAL_RCC_ETHMAC_CLK_DISABLE(); \ } while(0) #endif /* STM32F407xx || STM32F417xx */ /** * @} */ /** @defgroup RCCEx_AHB2_Clock_Enable_Disable AHB2 Peripheral Clock Enable Disable * @brief Enable or disable the AHB2 peripheral clock. * @note After reset, the peripheral clock (used for registers read/write access) * is disabled and the application software has to enable this clock before * using it. */ #define __HAL_RCC_USB_OTG_FS_CLK_ENABLE() do {(RCC->AHB2ENR |= (RCC_AHB2ENR_OTGFSEN));\ __HAL_RCC_SYSCFG_CLK_ENABLE();\ }while(0) #define __HAL_RCC_USB_OTG_FS_CLK_DISABLE() do { (RCC->AHB2ENR &= ~(RCC_AHB2ENR_OTGFSEN));\ __HAL_RCC_SYSCFG_CLK_DISABLE();\ }while(0) #define __HAL_RCC_RNG_CLK_ENABLE() do { \ __IO uint32_t tmpreg; \ SET_BIT(RCC->AHB2ENR, RCC_AHB2ENR_RNGEN);\ /* Delay after an RCC peripheral clock enabling */ \ tmpreg = READ_BIT(RCC->AHB2ENR, RCC_AHB2ENR_RNGEN);\ UNUSED(tmpreg); \ } while(0) #define __HAL_RCC_RNG_CLK_DISABLE() (RCC->AHB2ENR &= ~(RCC_AHB2ENR_RNGEN)) #if defined(STM32F407xx)|| defined(STM32F417xx) #define __HAL_RCC_DCMI_CLK_ENABLE() do { \ __IO uint32_t tmpreg; \ SET_BIT(RCC->AHB2ENR, RCC_AHB2ENR_DCMIEN);\ /* Delay after an RCC peripheral clock enabling */ \ tmpreg = READ_BIT(RCC->AHB2ENR, RCC_AHB2ENR_DCMIEN);\ UNUSED(tmpreg); \ } while(0) #define __HAL_RCC_DCMI_CLK_DISABLE() (RCC->AHB2ENR &= ~(RCC_AHB2ENR_DCMIEN)) #endif /* STM32F407xx || STM32F417xx */ #if defined(STM32F415xx) || defined(STM32F417xx) #define __HAL_RCC_CRYP_CLK_ENABLE() do { \ __IO uint32_t tmpreg; \ SET_BIT(RCC->AHB2ENR, RCC_AHB2ENR_CRYPEN);\ /* Delay after an RCC peripheral clock enabling */ \ tmpreg = READ_BIT(RCC->AHB2ENR, RCC_AHB2ENR_CRYPEN);\ UNUSED(tmpreg); \ } while(0) #define __HAL_RCC_HASH_CLK_ENABLE() do { \ __IO uint32_t tmpreg; \ SET_BIT(RCC->AHB2ENR, RCC_AHB2ENR_HASHEN);\ /* Delay after an RCC peripheral clock enabling */ \ tmpreg = READ_BIT(RCC->AHB2ENR, RCC_AHB2ENR_HASHEN);\ UNUSED(tmpreg); \ } while(0) #define __HAL_RCC_CRYP_CLK_DISABLE() (RCC->AHB2ENR &= ~(RCC_AHB2ENR_CRYPEN)) #define __HAL_RCC_HASH_CLK_DISABLE() (RCC->AHB2ENR &= ~(RCC_AHB2ENR_HASHEN)) #endif /* STM32F415xx || STM32F417xx */ /** * @} */ /** @defgroup RCCEx_AHB3_Clock_Enable_Disable AHB3 Peripheral Clock Enable Disable * @brief Enables or disables the AHB3 peripheral clock. * @note After reset, the peripheral clock (used for registers read/write access) * is disabled and the application software has to enable this clock before * using it. */ #define __HAL_RCC_FSMC_CLK_ENABLE() do { \ __IO uint32_t tmpreg; \ SET_BIT(RCC->AHB3ENR, RCC_AHB3ENR_FSMCEN);\ /* Delay after an RCC peripheral clock enabling */ \ tmpreg = READ_BIT(RCC->AHB3ENR, RCC_AHB3ENR_FSMCEN);\ UNUSED(tmpreg); \ } while(0) #define __HAL_RCC_FSMC_CLK_DISABLE() (RCC->AHB3ENR &= ~(RCC_AHB3ENR_FSMCEN)) /** * @} */ /** @defgroup RCCEx_APB1_Clock_Enable_Disable APB1 Peripheral Clock Enable Disable * @brief Enable or disable the Low Speed APB (APB1) peripheral clock. * @note After reset, the peripheral clock (used for registers read/write access) * is disabled and the application software has to enable this clock before * using it. */ #define __HAL_RCC_TIM6_CLK_ENABLE() do { \ __IO uint32_t tmpreg; \ SET_BIT(RCC->APB1ENR, RCC_APB1ENR_TIM6EN);\ /* Delay after an RCC peripheral clock enabling */ \ tmpreg = READ_BIT(RCC->APB1ENR, RCC_APB1ENR_TIM6EN);\ UNUSED(tmpreg); \ } while(0) #define __HAL_RCC_TIM7_CLK_ENABLE() do { \ __IO uint32_t tmpreg; \ SET_BIT(RCC->APB1ENR, RCC_APB1ENR_TIM7EN);\ /* Delay after an RCC peripheral clock enabling */ \ tmpreg = READ_BIT(RCC->APB1ENR, RCC_APB1ENR_TIM7EN);\ UNUSED(tmpreg); \ } while(0) #define __HAL_RCC_TIM12_CLK_ENABLE() do { \ __IO uint32_t tmpreg; \ SET_BIT(RCC->APB1ENR, RCC_APB1ENR_TIM12EN);\ /* Delay after an RCC peripheral clock enabling */ \ tmpreg = READ_BIT(RCC->APB1ENR, RCC_APB1ENR_TIM12EN);\ UNUSED(tmpreg); \ } while(0) #define __HAL_RCC_TIM13_CLK_ENABLE() do { \ __IO uint32_t tmpreg; \ SET_BIT(RCC->APB1ENR, RCC_APB1ENR_TIM13EN);\ /* Delay after an RCC peripheral clock enabling */ \ tmpreg = READ_BIT(RCC->APB1ENR, RCC_APB1ENR_TIM13EN);\ UNUSED(tmpreg); \ } while(0) #define __HAL_RCC_TIM14_CLK_ENABLE() do { \ __IO uint32_t tmpreg; \ SET_BIT(RCC->APB1ENR, RCC_APB1ENR_TIM14EN);\ /* Delay after an RCC peripheral clock enabling */ \ tmpreg = READ_BIT(RCC->APB1ENR, RCC_APB1ENR_TIM14EN);\ UNUSED(tmpreg); \ } while(0) #define __HAL_RCC_USART3_CLK_ENABLE() do { \ __IO uint32_t tmpreg; \ SET_BIT(RCC->APB1ENR, RCC_APB1ENR_USART3EN);\ /* Delay after an RCC peripheral clock enabling */ \ tmpreg = READ_BIT(RCC->APB1ENR, RCC_APB1ENR_USART3EN);\ UNUSED(tmpreg); \ } while(0) #define __HAL_RCC_UART4_CLK_ENABLE() do { \ __IO uint32_t tmpreg; \ SET_BIT(RCC->APB1ENR, RCC_APB1ENR_UART4EN);\ /* Delay after an RCC peripheral clock enabling */ \ tmpreg = READ_BIT(RCC->APB1ENR, RCC_APB1ENR_UART4EN);\ UNUSED(tmpreg); \ } while(0) #define __HAL_RCC_UART5_CLK_ENABLE() do { \ __IO uint32_t tmpreg; \ SET_BIT(RCC->APB1ENR, RCC_APB1ENR_UART5EN);\ /* Delay after an RCC peripheral clock enabling */ \ tmpreg = READ_BIT(RCC->APB1ENR, RCC_APB1ENR_UART5EN);\ UNUSED(tmpreg); \ } while(0) #define __HAL_RCC_CAN1_CLK_ENABLE() do { \ __IO uint32_t tmpreg; \ SET_BIT(RCC->APB1ENR, RCC_APB1ENR_CAN1EN);\ /* Delay after an RCC peripheral clock enabling */ \ tmpreg = READ_BIT(RCC->APB1ENR, RCC_APB1ENR_CAN1EN);\ UNUSED(tmpreg); \ } while(0) #define __HAL_RCC_CAN2_CLK_ENABLE() do { \ __IO uint32_t tmpreg; \ SET_BIT(RCC->APB1ENR, RCC_APB1ENR_CAN2EN);\ /* Delay after an RCC peripheral clock enabling */ \ tmpreg = READ_BIT(RCC->APB1ENR, RCC_APB1ENR_CAN2EN);\ UNUSED(tmpreg); \ } while(0) #define __HAL_RCC_DAC_CLK_ENABLE() do { \ __IO uint32_t tmpreg; \ SET_BIT(RCC->APB1ENR, RCC_APB1ENR_DACEN);\ /* Delay after an RCC peripheral clock enabling */ \ tmpreg = READ_BIT(RCC->APB1ENR, RCC_APB1ENR_DACEN);\ UNUSED(tmpreg); \ } while(0) #define __HAL_RCC_TIM2_CLK_ENABLE() do { \ __IO uint32_t tmpreg; \ SET_BIT(RCC->APB1ENR, RCC_APB1ENR_TIM2EN);\ /* Delay after an RCC peripheral clock enabling */ \ tmpreg = READ_BIT(RCC->APB1ENR, RCC_APB1ENR_TIM2EN);\ UNUSED(tmpreg); \ } while(0) #define __HAL_RCC_TIM3_CLK_ENABLE() do { \ __IO uint32_t tmpreg; \ SET_BIT(RCC->APB1ENR, RCC_APB1ENR_TIM3EN);\ /* Delay after an RCC peripheral clock enabling */ \ tmpreg = READ_BIT(RCC->APB1ENR, RCC_APB1ENR_TIM3EN);\ UNUSED(tmpreg); \ } while(0) #define __HAL_RCC_TIM4_CLK_ENABLE() do { \ __IO uint32_t tmpreg; \ SET_BIT(RCC->APB1ENR, RCC_APB1ENR_TIM4EN);\ /* Delay after an RCC peripheral clock enabling */ \ tmpreg = READ_BIT(RCC->APB1ENR, RCC_APB1ENR_TIM4EN);\ UNUSED(tmpreg); \ } while(0) #define __HAL_RCC_SPI3_CLK_ENABLE() do { \ __IO uint32_t tmpreg; \ SET_BIT(RCC->APB1ENR, RCC_APB1ENR_SPI3EN);\ /* Delay after an RCC peripheral clock enabling */ \ tmpreg = READ_BIT(RCC->APB1ENR, RCC_APB1ENR_SPI3EN);\ UNUSED(tmpreg); \ } while(0) #define __HAL_RCC_I2C3_CLK_ENABLE() do { \ __IO uint32_t tmpreg; \ SET_BIT(RCC->APB1ENR, RCC_APB1ENR_I2C3EN);\ /* Delay after an RCC peripheral clock enabling */ \ tmpreg = READ_BIT(RCC->APB1ENR, RCC_APB1ENR_I2C3EN);\ UNUSED(tmpreg); \ } while(0) #define __HAL_RCC_TIM2_CLK_DISABLE() (RCC->APB1ENR &= ~(RCC_APB1ENR_TIM2EN)) #define __HAL_RCC_TIM3_CLK_DISABLE() (RCC->APB1ENR &= ~(RCC_APB1ENR_TIM3EN)) #define __HAL_RCC_TIM4_CLK_DISABLE() (RCC->APB1ENR &= ~(RCC_APB1ENR_TIM4EN)) #define __HAL_RCC_SPI3_CLK_DISABLE() (RCC->APB1ENR &= ~(RCC_APB1ENR_SPI3EN)) #define __HAL_RCC_I2C3_CLK_DISABLE() (RCC->APB1ENR &= ~(RCC_APB1ENR_I2C3EN)) #define __HAL_RCC_TIM6_CLK_DISABLE() (RCC->APB1ENR &= ~(RCC_APB1ENR_TIM6EN)) #define __HAL_RCC_TIM7_CLK_DISABLE() (RCC->APB1ENR &= ~(RCC_APB1ENR_TIM7EN)) #define __HAL_RCC_TIM12_CLK_DISABLE() (RCC->APB1ENR &= ~(RCC_APB1ENR_TIM12EN)) #define __HAL_RCC_TIM13_CLK_DISABLE() (RCC->APB1ENR &= ~(RCC_APB1ENR_TIM13EN)) #define __HAL_RCC_TIM14_CLK_DISABLE() (RCC->APB1ENR &= ~(RCC_APB1ENR_TIM14EN)) #define __HAL_RCC_USART3_CLK_DISABLE() (RCC->APB1ENR &= ~(RCC_APB1ENR_USART3EN)) #define __HAL_RCC_UART4_CLK_DISABLE() (RCC->APB1ENR &= ~(RCC_APB1ENR_UART4EN)) #define __HAL_RCC_UART5_CLK_DISABLE() (RCC->APB1ENR &= ~(RCC_APB1ENR_UART5EN)) #define __HAL_RCC_CAN1_CLK_DISABLE() (RCC->APB1ENR &= ~(RCC_APB1ENR_CAN1EN)) #define __HAL_RCC_CAN2_CLK_DISABLE() (RCC->APB1ENR &= ~(RCC_APB1ENR_CAN2EN)) #define __HAL_RCC_DAC_CLK_DISABLE() (RCC->APB1ENR &= ~(RCC_APB1ENR_DACEN)) /** * @} */ /** @defgroup RCCEx_APB2_Clock_Enable_Disable APB2 Peripheral Clock Enable Disable * @brief Enable or disable the High Speed APB (APB2) peripheral clock. * @note After reset, the peripheral clock (used for registers read/write access) * is disabled and the application software has to enable this clock before * using it. */ #define __HAL_RCC_TIM8_CLK_ENABLE() do { \ __IO uint32_t tmpreg; \ SET_BIT(RCC->APB2ENR, RCC_APB2ENR_TIM8EN);\ /* Delay after an RCC peripheral clock enabling */ \ tmpreg = READ_BIT(RCC->APB2ENR, RCC_APB2ENR_TIM8EN);\ UNUSED(tmpreg); \ } while(0) #define __HAL_RCC_ADC2_CLK_ENABLE() do { \ __IO uint32_t tmpreg; \ SET_BIT(RCC->APB2ENR, RCC_APB2ENR_ADC2EN);\ /* Delay after an RCC peripheral clock enabling */ \ tmpreg = READ_BIT(RCC->APB2ENR, RCC_APB2ENR_ADC2EN);\ UNUSED(tmpreg); \ } while(0) #define __HAL_RCC_ADC3_CLK_ENABLE() do { \ __IO uint32_t tmpreg; \ SET_BIT(RCC->APB2ENR, RCC_APB2ENR_ADC3EN);\ /* Delay after an RCC peripheral clock enabling */ \ tmpreg = READ_BIT(RCC->APB2ENR, RCC_APB2ENR_ADC3EN);\ UNUSED(tmpreg); \ } while(0) #define __HAL_RCC_SDIO_CLK_ENABLE() do { \ __IO uint32_t tmpreg; \ SET_BIT(RCC->APB2ENR, RCC_APB2ENR_SDIOEN);\ /* Delay after an RCC peripheral clock enabling */ \ tmpreg = READ_BIT(RCC->APB2ENR, RCC_APB2ENR_SDIOEN);\ UNUSED(tmpreg); \ } while(0) #define __HAL_RCC_SPI4_CLK_ENABLE() do { \ __IO uint32_t tmpreg; \ SET_BIT(RCC->APB2ENR, RCC_APB2ENR_SPI4EN);\ /* Delay after an RCC peripheral clock enabling */ \ tmpreg = READ_BIT(RCC->APB2ENR, RCC_APB2ENR_SPI4EN);\ UNUSED(tmpreg); \ } while(0) #define __HAL_RCC_TIM10_CLK_ENABLE() do { \ __IO uint32_t tmpreg; \ SET_BIT(RCC->APB2ENR, RCC_APB2ENR_TIM10EN);\ /* Delay after an RCC peripheral clock enabling */ \ tmpreg = READ_BIT(RCC->APB2ENR, RCC_APB2ENR_TIM10EN);\ UNUSED(tmpreg); \ } while(0) #define __HAL_RCC_SDIO_CLK_DISABLE() (RCC->APB2ENR &= ~(RCC_APB2ENR_SDIOEN)) #define __HAL_RCC_SPI4_CLK_DISABLE() (RCC->APB2ENR &= ~(RCC_APB2ENR_SPI4EN)) #define __HAL_RCC_TIM10_CLK_DISABLE() (RCC->APB2ENR &= ~(RCC_APB2ENR_TIM10EN)) #define __HAL_RCC_TIM8_CLK_DISABLE() (RCC->APB2ENR &= ~(RCC_APB2ENR_TIM8EN)) #define __HAL_RCC_ADC2_CLK_DISABLE() (RCC->APB2ENR &= ~(RCC_APB2ENR_ADC2EN)) #define __HAL_RCC_ADC3_CLK_DISABLE() (RCC->APB2ENR &= ~(RCC_APB2ENR_ADC3EN)) /** * @} */ /** @defgroup RCCEx_AHB1_Force_Release_Reset AHB1 Force Release Reset * @brief Force or release AHB1 peripheral reset. */ #define __HAL_RCC_GPIOD_FORCE_RESET() (RCC->AHB1RSTR |= (RCC_AHB1RSTR_GPIODRST)) #define __HAL_RCC_GPIOE_FORCE_RESET() (RCC->AHB1RSTR |= (RCC_AHB1RSTR_GPIOERST)) #define __HAL_RCC_GPIOF_FORCE_RESET() (RCC->AHB1RSTR |= (RCC_AHB1RSTR_GPIOFRST)) #define __HAL_RCC_GPIOG_FORCE_RESET() (RCC->AHB1RSTR |= (RCC_AHB1RSTR_GPIOGRST)) #define __HAL_RCC_GPIOI_FORCE_RESET() (RCC->AHB1RSTR |= (RCC_AHB1RSTR_GPIOIRST)) #define __HAL_RCC_ETHMAC_FORCE_RESET() (RCC->AHB1RSTR |= (RCC_AHB1RSTR_ETHMACRST)) #define __HAL_RCC_USB_OTG_HS_FORCE_RESET() (RCC->AHB1RSTR |= (RCC_AHB1RSTR_OTGHRST)) #define __HAL_RCC_CRC_FORCE_RESET() (RCC->AHB1RSTR |= (RCC_AHB1RSTR_CRCRST)) #define __HAL_RCC_GPIOD_RELEASE_RESET() (RCC->AHB1RSTR &= ~(RCC_AHB1RSTR_GPIODRST)) #define __HAL_RCC_GPIOE_RELEASE_RESET() (RCC->AHB1RSTR &= ~(RCC_AHB1RSTR_GPIOERST)) #define __HAL_RCC_GPIOF_RELEASE_RESET() (RCC->AHB1RSTR &= ~(RCC_AHB1RSTR_GPIOFRST)) #define __HAL_RCC_GPIOG_RELEASE_RESET() (RCC->AHB1RSTR &= ~(RCC_AHB1RSTR_GPIOGRST)) #define __HAL_RCC_GPIOI_RELEASE_RESET() (RCC->AHB1RSTR &= ~(RCC_AHB1RSTR_GPIOIRST)) #define __HAL_RCC_ETHMAC_RELEASE_RESET() (RCC->AHB1RSTR &= ~(RCC_AHB1RSTR_ETHMACRST)) #define __HAL_RCC_USB_OTG_HS_RELEASE_RESET() (RCC->AHB1RSTR &= ~(RCC_AHB1RSTR_OTGHRST)) #define __HAL_RCC_CRC_RELEASE_RESET() (RCC->AHB1RSTR &= ~(RCC_AHB1RSTR_CRCRST)) /** * @} */ /** @defgroup RCCEx_AHB2_Force_Release_Reset AHB2 Force Release Reset * @brief Force or release AHB2 peripheral reset. */ #define __HAL_RCC_AHB2_FORCE_RESET() (RCC->AHB2RSTR = 0xFFFFFFFF) #define __HAL_RCC_AHB2_RELEASE_RESET() (RCC->AHB2RSTR = 0x00) #if defined(STM32F407xx)|| defined(STM32F417xx) #define __HAL_RCC_DCMI_FORCE_RESET() (RCC->AHB2RSTR |= (RCC_AHB2RSTR_DCMIRST)) #define __HAL_RCC_DCMI_RELEASE_RESET() (RCC->AHB2RSTR &= ~(RCC_AHB2RSTR_DCMIRST)) #endif /* STM32F407xx || STM32F417xx */ #if defined(STM32F415xx) || defined(STM32F417xx) #define __HAL_RCC_CRYP_FORCE_RESET() (RCC->AHB2RSTR |= (RCC_AHB2RSTR_CRYPRST)) #define __HAL_RCC_HASH_FORCE_RESET() (RCC->AHB2RSTR |= (RCC_AHB2RSTR_HASHRST)) #define __HAL_RCC_CRYP_RELEASE_RESET() (RCC->AHB2RSTR &= ~(RCC_AHB2RSTR_CRYPRST)) #define __HAL_RCC_HASH_RELEASE_RESET() (RCC->AHB2RSTR &= ~(RCC_AHB2RSTR_HASHRST)) #endif /* STM32F415xx || STM32F417xx */ #define __HAL_RCC_USB_OTG_FS_FORCE_RESET() (RCC->AHB2RSTR |= (RCC_AHB2RSTR_OTGFSRST)) #define __HAL_RCC_USB_OTG_FS_RELEASE_RESET() (RCC->AHB2RSTR &= ~(RCC_AHB2RSTR_OTGFSRST)) #define __HAL_RCC_RNG_FORCE_RESET() (RCC->AHB2RSTR |= (RCC_AHB2RSTR_RNGRST)) #define __HAL_RCC_RNG_RELEASE_RESET() (RCC->AHB2RSTR &= ~(RCC_AHB2RSTR_RNGRST)) /** * @} */ /** @defgroup RCCEx_AHB3_Force_Release_Reset AHB3 Force Release Reset * @brief Force or release AHB3 peripheral reset. * @{ */ #define __HAL_RCC_AHB3_FORCE_RESET() (RCC->AHB3RSTR = 0xFFFFFFFF) #define __HAL_RCC_AHB3_RELEASE_RESET() (RCC->AHB3RSTR = 0x00) #define __HAL_RCC_FSMC_FORCE_RESET() (RCC->AHB3RSTR |= (RCC_AHB3RSTR_FSMCRST)) #define __HAL_RCC_FSMC_RELEASE_RESET() (RCC->AHB3RSTR &= ~(RCC_AHB3RSTR_FSMCRST)) /** * @} */ /** @defgroup RCCEx_APB1_Force_Release_Reset APB1 Force Release Reset * @brief Force or release APB1 peripheral reset. */ #define __HAL_RCC_TIM6_FORCE_RESET() (RCC->APB1RSTR |= (RCC_APB1RSTR_TIM6RST)) #define __HAL_RCC_TIM7_FORCE_RESET() (RCC->APB1RSTR |= (RCC_APB1RSTR_TIM7RST)) #define __HAL_RCC_TIM12_FORCE_RESET() (RCC->APB1RSTR |= (RCC_APB1RSTR_TIM12RST)) #define __HAL_RCC_TIM13_FORCE_RESET() (RCC->APB1RSTR |= (RCC_APB1RSTR_TIM13RST)) #define __HAL_RCC_TIM14_FORCE_RESET() (RCC->APB1RSTR |= (RCC_APB1RSTR_TIM14RST)) #define __HAL_RCC_USART3_FORCE_RESET() (RCC->APB1RSTR |= (RCC_APB1RSTR_USART3RST)) #define __HAL_RCC_UART4_FORCE_RESET() (RCC->APB1RSTR |= (RCC_APB1RSTR_UART4RST)) #define __HAL_RCC_UART5_FORCE_RESET() (RCC->APB1RSTR |= (RCC_APB1RSTR_UART5RST)) #define __HAL_RCC_CAN1_FORCE_RESET() (RCC->APB1RSTR |= (RCC_APB1RSTR_CAN1RST)) #define __HAL_RCC_CAN2_FORCE_RESET() (RCC->APB1RSTR |= (RCC_APB1RSTR_CAN2RST)) #define __HAL_RCC_DAC_FORCE_RESET() (RCC->APB1RSTR |= (RCC_APB1RSTR_DACRST)) #define __HAL_RCC_TIM2_FORCE_RESET() (RCC->APB1RSTR |= (RCC_APB1RSTR_TIM2RST)) #define __HAL_RCC_TIM3_FORCE_RESET() (RCC->APB1RSTR |= (RCC_APB1RSTR_TIM3RST)) #define __HAL_RCC_TIM4_FORCE_RESET() (RCC->APB1RSTR |= (RCC_APB1RSTR_TIM4RST)) #define __HAL_RCC_SPI3_FORCE_RESET() (RCC->APB1RSTR |= (RCC_APB1RSTR_SPI3RST)) #define __HAL_RCC_I2C3_FORCE_RESET() (RCC->APB1RSTR |= (RCC_APB1RSTR_I2C3RST)) #define __HAL_RCC_TIM2_RELEASE_RESET() (RCC->APB1RSTR &= ~(RCC_APB1RSTR_TIM2RST)) #define __HAL_RCC_TIM3_RELEASE_RESET() (RCC->APB1RSTR &= ~(RCC_APB1RSTR_TIM3RST)) #define __HAL_RCC_TIM4_RELEASE_RESET() (RCC->APB1RSTR &= ~(RCC_APB1RSTR_TIM4RST)) #define __HAL_RCC_SPI3_RELEASE_RESET() (RCC->APB1RSTR &= ~(RCC_APB1RSTR_SPI3RST)) #define __HAL_RCC_I2C3_RELEASE_RESET() (RCC->APB1RSTR &= ~(RCC_APB1RSTR_I2C3RST)) #define __HAL_RCC_TIM6_RELEASE_RESET() (RCC->APB1RSTR &= ~(RCC_APB1RSTR_TIM6RST)) #define __HAL_RCC_TIM7_RELEASE_RESET() (RCC->APB1RSTR &= ~(RCC_APB1RSTR_TIM7RST)) #define __HAL_RCC_TIM12_RELEASE_RESET() (RCC->APB1RSTR &= ~(RCC_APB1RSTR_TIM12RST)) #define __HAL_RCC_TIM13_RELEASE_RESET() (RCC->APB1RSTR &= ~(RCC_APB1RSTR_TIM13RST)) #define __HAL_RCC_TIM14_RELEASE_RESET() (RCC->APB1RSTR &= ~(RCC_APB1RSTR_TIM14RST)) #define __HAL_RCC_USART3_RELEASE_RESET() (RCC->APB1RSTR &= ~(RCC_APB1RSTR_USART3RST)) #define __HAL_RCC_UART4_RELEASE_RESET() (RCC->APB1RSTR &= ~(RCC_APB1RSTR_UART4RST)) #define __HAL_RCC_UART5_RELEASE_RESET() (RCC->APB1RSTR &= ~(RCC_APB1RSTR_UART5RST)) #define __HAL_RCC_CAN1_RELEASE_RESET() (RCC->APB1RSTR &= ~(RCC_APB1RSTR_CAN1RST)) #define __HAL_RCC_CAN2_RELEASE_RESET() (RCC->APB1RSTR &= ~(RCC_APB1RSTR_CAN2RST)) #define __HAL_RCC_DAC_RELEASE_RESET() (RCC->APB1RSTR &= ~(RCC_APB1RSTR_DACRST)) /** * @} */ /** @defgroup RCCEx_APB2_Force_Release_Reset APB2 Force Release Reset * @brief Force or release APB2 peripheral reset. */ #define __HAL_RCC_TIM8_FORCE_RESET() (RCC->APB2RSTR |= (RCC_APB2RSTR_TIM8RST)) #define __HAL_RCC_SDIO_FORCE_RESET() (RCC->APB2RSTR |= (RCC_APB2RSTR_SDIORST)) #define __HAL_RCC_SPI4_FORCE_RESET() (RCC->APB2RSTR |= (RCC_APB2RSTR_SPI4RST)) #define __HAL_RCC_TIM10_FORCE_RESET() (RCC->APB2RSTR |= (RCC_APB2RSTR_TIM10RST)) #define __HAL_RCC_SDIO_RELEASE_RESET() (RCC->APB2RSTR &= ~(RCC_APB2RSTR_SDIORST)) #define __HAL_RCC_SPI4_RELEASE_RESET() (RCC->APB2RSTR &= ~(RCC_APB2RSTR_SPI4RST)) #define __HAL_RCC_TIM10_RELEASE_RESET()(RCC->APB2RSTR &= ~(RCC_APB2RSTR_TIM10RST)) #define __HAL_RCC_TIM8_RELEASE_RESET() (RCC->APB2RSTR &= ~(RCC_APB2RSTR_TIM8RST)) /** * @} */ /** @defgroup RCCEx_AHB1_LowPower_Enable_Disable AHB1 Peripheral Low Power Enable Disable * @brief Enable or disable the AHB1 peripheral clock during Low Power (Sleep) mode. * @note Peripheral clock gating in SLEEP mode can be used to further reduce * power consumption. * @note After wakeup from SLEEP mode, the peripheral clock is enabled again. * @note By default, all peripheral clocks are enabled during SLEEP mode. */ #define __HAL_RCC_GPIOD_CLK_SLEEP_ENABLE() (RCC->AHB1LPENR |= (RCC_AHB1LPENR_GPIODLPEN)) #define __HAL_RCC_GPIOE_CLK_SLEEP_ENABLE() (RCC->AHB1LPENR |= (RCC_AHB1LPENR_GPIOELPEN)) #define __HAL_RCC_GPIOF_CLK_SLEEP_ENABLE() (RCC->AHB1LPENR |= (RCC_AHB1LPENR_GPIOFLPEN)) #define __HAL_RCC_GPIOG_CLK_SLEEP_ENABLE() (RCC->AHB1LPENR |= (RCC_AHB1LPENR_GPIOGLPEN)) #define __HAL_RCC_GPIOI_CLK_SLEEP_ENABLE() (RCC->AHB1LPENR |= (RCC_AHB1LPENR_GPIOILPEN)) #define __HAL_RCC_SRAM2_CLK_SLEEP_ENABLE() (RCC->AHB1LPENR |= (RCC_AHB1LPENR_SRAM2LPEN)) #define __HAL_RCC_ETHMAC_CLK_SLEEP_ENABLE() (RCC->AHB1LPENR |= (RCC_AHB1LPENR_ETHMACLPEN)) #define __HAL_RCC_ETHMACTX_CLK_SLEEP_ENABLE() (RCC->AHB1LPENR |= (RCC_AHB1LPENR_ETHMACTXLPEN)) #define __HAL_RCC_ETHMACRX_CLK_SLEEP_ENABLE() (RCC->AHB1LPENR |= (RCC_AHB1LPENR_ETHMACRXLPEN)) #define __HAL_RCC_ETHMACPTP_CLK_SLEEP_ENABLE() (RCC->AHB1LPENR |= (RCC_AHB1LPENR_ETHMACPTPLPEN)) #define __HAL_RCC_USB_OTG_HS_CLK_SLEEP_ENABLE() (RCC->AHB1LPENR |= (RCC_AHB1LPENR_OTGHSLPEN)) #define __HAL_RCC_USB_OTG_HS_ULPI_CLK_SLEEP_ENABLE() (RCC->AHB1LPENR |= (RCC_AHB1LPENR_OTGHSULPILPEN)) #define __HAL_RCC_CRC_CLK_SLEEP_ENABLE() (RCC->AHB1LPENR |= (RCC_AHB1LPENR_CRCLPEN)) #define __HAL_RCC_FLITF_CLK_SLEEP_ENABLE() (RCC->AHB1LPENR |= (RCC_AHB1LPENR_FLITFLPEN)) #define __HAL_RCC_SRAM1_CLK_SLEEP_ENABLE() (RCC->AHB1LPENR |= (RCC_AHB1LPENR_SRAM1LPEN)) #define __HAL_RCC_BKPSRAM_CLK_SLEEP_ENABLE() (RCC->AHB1LPENR |= (RCC_AHB1LPENR_BKPSRAMLPEN)) #define __HAL_RCC_GPIOD_CLK_SLEEP_DISABLE() (RCC->AHB1LPENR &= ~(RCC_AHB1LPENR_GPIODLPEN)) #define __HAL_RCC_GPIOE_CLK_SLEEP_DISABLE() (RCC->AHB1LPENR &= ~(RCC_AHB1LPENR_GPIOELPEN)) #define __HAL_RCC_GPIOF_CLK_SLEEP_DISABLE() (RCC->AHB1LPENR &= ~(RCC_AHB1LPENR_GPIOFLPEN)) #define __HAL_RCC_GPIOG_CLK_SLEEP_DISABLE() (RCC->AHB1LPENR &= ~(RCC_AHB1LPENR_GPIOGLPEN)) #define __HAL_RCC_GPIOI_CLK_SLEEP_DISABLE() (RCC->AHB1LPENR &= ~(RCC_AHB1LPENR_GPIOILPEN)) #define __HAL_RCC_SRAM2_CLK_SLEEP_DISABLE() (RCC->AHB1LPENR &= ~(RCC_AHB1LPENR_SRAM2LPEN)) #define __HAL_RCC_ETHMAC_CLK_SLEEP_DISABLE() (RCC->AHB1LPENR &= ~(RCC_AHB1LPENR_ETHMACLPEN)) #define __HAL_RCC_ETHMACTX_CLK_SLEEP_DISABLE() (RCC->AHB1LPENR &= ~(RCC_AHB1LPENR_ETHMACTXLPEN)) #define __HAL_RCC_ETHMACRX_CLK_SLEEP_DISABLE() (RCC->AHB1LPENR &= ~(RCC_AHB1LPENR_ETHMACRXLPEN)) #define __HAL_RCC_ETHMACPTP_CLK_SLEEP_DISABLE() (RCC->AHB1LPENR &= ~(RCC_AHB1LPENR_ETHMACPTPLPEN)) #define __HAL_RCC_USB_OTG_HS_CLK_SLEEP_DISABLE() (RCC->AHB1LPENR &= ~(RCC_AHB1LPENR_OTGHSLPEN)) #define __HAL_RCC_USB_OTG_HS_ULPI_CLK_SLEEP_DISABLE() (RCC->AHB1LPENR &= ~(RCC_AHB1LPENR_OTGHSULPILPEN)) #define __HAL_RCC_CRC_CLK_SLEEP_DISABLE() (RCC->AHB1LPENR &= ~(RCC_AHB1LPENR_CRCLPEN)) #define __HAL_RCC_FLITF_CLK_SLEEP_DISABLE() (RCC->AHB1LPENR &= ~(RCC_AHB1LPENR_FLITFLPEN)) #define __HAL_RCC_SRAM1_CLK_SLEEP_DISABLE() (RCC->AHB1LPENR &= ~(RCC_AHB1LPENR_SRAM1LPEN)) #define __HAL_RCC_BKPSRAM_CLK_SLEEP_DISABLE() (RCC->AHB1LPENR &= ~(RCC_AHB1LPENR_BKPSRAMLPEN)) /** * @} */ /** @defgroup RCCEx_AHB2_LowPower_Enable_Disable AHB2 Peripheral Low Power Enable Disable * @brief Enable or disable the AHB2 peripheral clock during Low Power (Sleep) mode. * @note Peripheral clock gating in SLEEP mode can be used to further reduce * power consumption. * @note After wake-up from SLEEP mode, the peripheral clock is enabled again. * @note By default, all peripheral clocks are enabled during SLEEP mode. * @{ */ #define __HAL_RCC_USB_OTG_FS_CLK_SLEEP_ENABLE() (RCC->AHB2LPENR |= (RCC_AHB2LPENR_OTGFSLPEN)) #define __HAL_RCC_USB_OTG_FS_CLK_SLEEP_DISABLE() (RCC->AHB2LPENR &= ~(RCC_AHB2LPENR_OTGFSLPEN)) #define __HAL_RCC_RNG_CLK_SLEEP_ENABLE() (RCC->AHB2LPENR |= (RCC_AHB2LPENR_RNGLPEN)) #define __HAL_RCC_RNG_CLK_SLEEP_DISABLE() (RCC->AHB2LPENR &= ~(RCC_AHB2LPENR_RNGLPEN)) #if defined(STM32F407xx)|| defined(STM32F417xx) #define __HAL_RCC_DCMI_CLK_SLEEP_ENABLE() (RCC->AHB2LPENR |= (RCC_AHB2LPENR_DCMILPEN)) #define __HAL_RCC_DCMI_CLK_SLEEP_DISABLE() (RCC->AHB2LPENR &= ~(RCC_AHB2LPENR_DCMILPEN)) #endif /* STM32F407xx || STM32F417xx */ #if defined(STM32F415xx) || defined(STM32F417xx) #define __HAL_RCC_CRYP_CLK_SLEEP_ENABLE() (RCC->AHB2LPENR |= (RCC_AHB2LPENR_CRYPLPEN)) #define __HAL_RCC_HASH_CLK_SLEEP_ENABLE() (RCC->AHB2LPENR |= (RCC_AHB2LPENR_HASHLPEN)) #define __HAL_RCC_CRYP_CLK_SLEEP_DISABLE() (RCC->AHB2LPENR &= ~(RCC_AHB2LPENR_CRYPLPEN)) #define __HAL_RCC_HASH_CLK_SLEEP_DISABLE() (RCC->AHB2LPENR &= ~(RCC_AHB2LPENR_HASHLPEN)) #endif /* STM32F415xx || STM32F417xx */ /** * @} */ /** @defgroup RCCEx_AHB3_LowPower_Enable_Disable AHB3 Peripheral Low Power Enable Disable * @brief Enable or disable the AHB3 peripheral clock during Low Power (Sleep) mode. * @note Peripheral clock gating in SLEEP mode can be used to further reduce * power consumption. * @note After wakeup from SLEEP mode, the peripheral clock is enabled again. * @note By default, all peripheral clocks are enabled during SLEEP mode. */ #define __HAL_RCC_FSMC_CLK_SLEEP_ENABLE() (RCC->AHB3LPENR |= (RCC_AHB3LPENR_FSMCLPEN)) #define __HAL_RCC_FSMC_CLK_SLEEP_DISABLE() (RCC->AHB3LPENR &= ~(RCC_AHB3LPENR_FSMCLPEN)) /** * @} */ /** @defgroup RCCEx_APB1_LowPower_Enable_Disable APB1 Peripheral Low Power Enable Disable * @brief Enable or disable the APB1 peripheral clock during Low Power (Sleep) mode. * @note Peripheral clock gating in SLEEP mode can be used to further reduce * power consumption. * @note After wakeup from SLEEP mode, the peripheral clock is enabled again. * @note By default, all peripheral clocks are enabled during SLEEP mode. */ #define __HAL_RCC_TIM6_CLK_SLEEP_ENABLE() (RCC->APB1LPENR |= (RCC_APB1LPENR_TIM6LPEN)) #define __HAL_RCC_TIM7_CLK_SLEEP_ENABLE() (RCC->APB1LPENR |= (RCC_APB1LPENR_TIM7LPEN)) #define __HAL_RCC_TIM12_CLK_SLEEP_ENABLE() (RCC->APB1LPENR |= (RCC_APB1LPENR_TIM12LPEN)) #define __HAL_RCC_TIM13_CLK_SLEEP_ENABLE() (RCC->APB1LPENR |= (RCC_APB1LPENR_TIM13LPEN)) #define __HAL_RCC_TIM14_CLK_SLEEP_ENABLE() (RCC->APB1LPENR |= (RCC_APB1LPENR_TIM14LPEN)) #define __HAL_RCC_USART3_CLK_SLEEP_ENABLE() (RCC->APB1LPENR |= (RCC_APB1LPENR_USART3LPEN)) #define __HAL_RCC_UART4_CLK_SLEEP_ENABLE() (RCC->APB1LPENR |= (RCC_APB1LPENR_UART4LPEN)) #define __HAL_RCC_UART5_CLK_SLEEP_ENABLE() (RCC->APB1LPENR |= (RCC_APB1LPENR_UART5LPEN)) #define __HAL_RCC_CAN1_CLK_SLEEP_ENABLE() (RCC->APB1LPENR |= (RCC_APB1LPENR_CAN1LPEN)) #define __HAL_RCC_CAN2_CLK_SLEEP_ENABLE() (RCC->APB1LPENR |= (RCC_APB1LPENR_CAN2LPEN)) #define __HAL_RCC_DAC_CLK_SLEEP_ENABLE() (RCC->APB1LPENR |= (RCC_APB1LPENR_DACLPEN)) #define __HAL_RCC_TIM2_CLK_SLEEP_ENABLE() (RCC->APB1LPENR |= (RCC_APB1LPENR_TIM2LPEN)) #define __HAL_RCC_TIM3_CLK_SLEEP_ENABLE() (RCC->APB1LPENR |= (RCC_APB1LPENR_TIM3LPEN)) #define __HAL_RCC_TIM4_CLK_SLEEP_ENABLE() (RCC->APB1LPENR |= (RCC_APB1LPENR_TIM4LPEN)) #define __HAL_RCC_SPI3_CLK_SLEEP_ENABLE() (RCC->APB1LPENR |= (RCC_APB1LPENR_SPI3LPEN)) #define __HAL_RCC_I2C3_CLK_SLEEP_ENABLE() (RCC->APB1LPENR |= (RCC_APB1LPENR_I2C3LPEN)) #define __HAL_RCC_TIM2_CLK_SLEEP_DISABLE() (RCC->APB1LPENR &= ~(RCC_APB1LPENR_TIM2LPEN)) #define __HAL_RCC_TIM3_CLK_SLEEP_DISABLE() (RCC->APB1LPENR &= ~(RCC_APB1LPENR_TIM3LPEN)) #define __HAL_RCC_TIM4_CLK_SLEEP_DISABLE() (RCC->APB1LPENR &= ~(RCC_APB1LPENR_TIM4LPEN)) #define __HAL_RCC_SPI3_CLK_SLEEP_DISABLE() (RCC->APB1LPENR &= ~(RCC_APB1LPENR_SPI3LPEN)) #define __HAL_RCC_I2C3_CLK_SLEEP_DISABLE() (RCC->APB1LPENR &= ~(RCC_APB1LPENR_I2C3LPEN)) #define __HAL_RCC_TIM6_CLK_SLEEP_DISABLE() (RCC->APB1LPENR &= ~(RCC_APB1LPENR_TIM6LPEN)) #define __HAL_RCC_TIM7_CLK_SLEEP_DISABLE() (RCC->APB1LPENR &= ~(RCC_APB1LPENR_TIM7LPEN)) #define __HAL_RCC_TIM12_CLK_SLEEP_DISABLE() (RCC->APB1LPENR &= ~(RCC_APB1LPENR_TIM12LPEN)) #define __HAL_RCC_TIM13_CLK_SLEEP_DISABLE() (RCC->APB1LPENR &= ~(RCC_APB1LPENR_TIM13LPEN)) #define __HAL_RCC_TIM14_CLK_SLEEP_DISABLE() (RCC->APB1LPENR &= ~(RCC_APB1LPENR_TIM14LPEN)) #define __HAL_RCC_USART3_CLK_SLEEP_DISABLE() (RCC->APB1LPENR &= ~(RCC_APB1LPENR_USART3LPEN)) #define __HAL_RCC_UART4_CLK_SLEEP_DISABLE() (RCC->APB1LPENR &= ~(RCC_APB1LPENR_UART4LPEN)) #define __HAL_RCC_UART5_CLK_SLEEP_DISABLE() (RCC->APB1LPENR &= ~(RCC_APB1LPENR_UART5LPEN)) #define __HAL_RCC_CAN1_CLK_SLEEP_DISABLE() (RCC->APB1LPENR &= ~(RCC_APB1LPENR_CAN1LPEN)) #define __HAL_RCC_CAN2_CLK_SLEEP_DISABLE() (RCC->APB1LPENR &= ~(RCC_APB1LPENR_CAN2LPEN)) #define __HAL_RCC_DAC_CLK_SLEEP_DISABLE() (RCC->APB1LPENR &= ~(RCC_APB1LPENR_DACLPEN)) /** * @} */ /** @defgroup RCCEx_APB2_LowPower_Enable_Disable APB2 Peripheral Low Power Enable Disable * @brief Enable or disable the APB2 peripheral clock during Low Power (Sleep) mode. * @note Peripheral clock gating in SLEEP mode can be used to further reduce * power consumption. * @note After wakeup from SLEEP mode, the peripheral clock is enabled again. * @note By default, all peripheral clocks are enabled during SLEEP mode. */ #define __HAL_RCC_TIM8_CLK_SLEEP_ENABLE() (RCC->APB2LPENR |= (RCC_APB2LPENR_TIM8LPEN)) #define __HAL_RCC_ADC2_CLK_SLEEP_ENABLE() (RCC->APB2LPENR |= (RCC_APB2LPENR_ADC2LPEN)) #define __HAL_RCC_ADC3_CLK_SLEEP_ENABLE() (RCC->APB2LPENR |= (RCC_APB2LPENR_ADC3LPEN)) #define __HAL_RCC_SDIO_CLK_SLEEP_ENABLE() (RCC->APB2LPENR |= (RCC_APB2LPENR_SDIOLPEN)) #define __HAL_RCC_SPI4_CLK_SLEEP_ENABLE() (RCC->APB2LPENR |= (RCC_APB2LPENR_SPI4LPEN)) #define __HAL_RCC_TIM10_CLK_SLEEP_ENABLE()(RCC->APB2LPENR |= (RCC_APB2LPENR_TIM10LPEN)) #define __HAL_RCC_SDIO_CLK_SLEEP_DISABLE() (RCC->APB2LPENR &= ~(RCC_APB2LPENR_SDIOLPEN)) #define __HAL_RCC_SPI4_CLK_SLEEP_DISABLE() (RCC->APB2LPENR &= ~(RCC_APB2LPENR_SPI4LPEN)) #define __HAL_RCC_TIM10_CLK_SLEEP_DISABLE()(RCC->APB2LPENR &= ~(RCC_APB2LPENR_TIM10LPEN)) #define __HAL_RCC_TIM8_CLK_SLEEP_DISABLE() (RCC->APB2LPENR &= ~(RCC_APB2LPENR_TIM8LPEN)) #define __HAL_RCC_ADC2_CLK_SLEEP_DISABLE() (RCC->APB2LPENR &= ~(RCC_APB2LPENR_ADC2LPEN)) #define __HAL_RCC_ADC3_CLK_SLEEP_DISABLE() (RCC->APB2LPENR &= ~(RCC_APB2LPENR_ADC3LPEN)) /** * @} */ #endif /* STM32F405xx || STM32F415xx || STM32F407xx || STM32F417xx */ /*----------------------------------------------------------------------------*/ /*------------------------- STM32F401xE/STM32F401xC --------------------------*/ #if defined(STM32F401xC) || defined(STM32F401xE) /** @defgroup RCCEx_AHB1_Clock_Enable_Disable AHB1 Peripheral Clock Enable Disable * @brief Enable or disable the AHB1 peripheral clock. * @note After reset, the peripheral clock (used for registers read/write access) * is disabled and the application software has to enable this clock before * using it. * @{ */ #define __HAL_RCC_GPIOD_CLK_ENABLE() do { \ __IO uint32_t tmpreg; \ SET_BIT(RCC->AHB1ENR, RCC_AHB1ENR_GPIODEN);\ /* Delay after an RCC peripheral clock enabling */ \ tmpreg = READ_BIT(RCC->AHB1ENR, RCC_AHB1ENR_GPIODEN);\ UNUSED(tmpreg); \ } while(0) #define __HAL_RCC_GPIOE_CLK_ENABLE() do { \ __IO uint32_t tmpreg; \ SET_BIT(RCC->AHB1ENR, RCC_AHB1ENR_GPIOEEN);\ /* Delay after an RCC peripheral clock enabling */ \ tmpreg = READ_BIT(RCC->AHB1ENR, RCC_AHB1ENR_GPIOEEN);\ UNUSED(tmpreg); \ } while(0) #define __HAL_RCC_CRC_CLK_ENABLE() do { \ __IO uint32_t tmpreg; \ SET_BIT(RCC->AHB1ENR, RCC_AHB1ENR_CRCEN);\ /* Delay after an RCC peripheral clock enabling */ \ tmpreg = READ_BIT(RCC->AHB1ENR, RCC_AHB1ENR_CRCEN);\ UNUSED(tmpreg); \ } while(0) #define __HAL_RCC_BKPSRAM_CLK_ENABLE() do { \ __IO uint32_t tmpreg; \ SET_BIT(RCC->AHB1ENR, RCC_AHB1ENR_BKPSRAMEN);\ /* Delay after an RCC peripheral clock enabling */ \ tmpreg = READ_BIT(RCC->AHB1ENR, RCC_AHB1ENR_BKPSRAMEN);\ UNUSED(tmpreg); \ } while(0) #define __HAL_RCC_CCMDATARAMEN_CLK_ENABLE() do { \ __IO uint32_t tmpreg; \ SET_BIT(RCC->AHB1ENR, RCC_AHB1ENR_CCMDATARAMEN);\ /* Delay after an RCC peripheral clock enabling */ \ tmpreg = READ_BIT(RCC->AHB1ENR, RCC_AHB1ENR_CCMDATARAMEN);\ UNUSED(tmpreg); \ } while(0) #define __HAL_RCC_GPIOD_CLK_DISABLE() (RCC->AHB1ENR &= ~(RCC_AHB1ENR_GPIODEN)) #define __HAL_RCC_GPIOE_CLK_DISABLE() (RCC->AHB1ENR &= ~(RCC_AHB1ENR_GPIOEEN)) #define __HAL_RCC_CRC_CLK_DISABLE() (RCC->AHB1ENR &= ~(RCC_AHB1ENR_CRCEN)) #define __HAL_RCC_BKPSRAM_CLK_DISABLE() (RCC->AHB1ENR &= ~(RCC_AHB1ENR_BKPSRAMEN)) #define __HAL_RCC_CCMDATARAMEN_CLK_DISABLE() (RCC->AHB1ENR &= ~(RCC_AHB1ENR_CCMDATARAMEN)) /** * @} */ /** @defgroup RCCEx_AHB2_Clock_Enable_Disable AHB2 Peripheral Clock Enable Disable * @brief Enable or disable the AHB2 peripheral clock. * @note After reset, the peripheral clock (used for registers read/write access) * is disabled and the application software has to enable this clock before * using it. * @{ */ #define __HAL_RCC_USB_OTG_FS_CLK_ENABLE() do {(RCC->AHB2ENR |= (RCC_AHB2ENR_OTGFSEN));\ __HAL_RCC_SYSCFG_CLK_ENABLE();\ }while(0) #define __HAL_RCC_USB_OTG_FS_CLK_DISABLE() do { (RCC->AHB2ENR &= ~(RCC_AHB2ENR_OTGFSEN));\ __HAL_RCC_SYSCFG_CLK_DISABLE();\ }while(0) /** * @} */ /** @defgroup RCC_APB1_Clock_Enable_Disable APB1 Peripheral Clock Enable Disable * @brief Enable or disable the Low Speed APB (APB1) peripheral clock. * @note After reset, the peripheral clock (used for registers read/write access) * is disabled and the application software has to enable this clock before * using it. * @{ */ #define __HAL_RCC_TIM2_CLK_ENABLE() do { \ __IO uint32_t tmpreg; \ SET_BIT(RCC->APB1ENR, RCC_APB1ENR_TIM2EN);\ /* Delay after an RCC peripheral clock enabling */ \ tmpreg = READ_BIT(RCC->APB1ENR, RCC_APB1ENR_TIM2EN);\ UNUSED(tmpreg); \ } while(0) #define __HAL_RCC_TIM3_CLK_ENABLE() do { \ __IO uint32_t tmpreg; \ SET_BIT(RCC->APB1ENR, RCC_APB1ENR_TIM3EN);\ /* Delay after an RCC peripheral clock enabling */ \ tmpreg = READ_BIT(RCC->APB1ENR, RCC_APB1ENR_TIM3EN);\ UNUSED(tmpreg); \ } while(0) #define __HAL_RCC_TIM4_CLK_ENABLE() do { \ __IO uint32_t tmpreg; \ SET_BIT(RCC->APB1ENR, RCC_APB1ENR_TIM4EN);\ /* Delay after an RCC peripheral clock enabling */ \ tmpreg = READ_BIT(RCC->APB1ENR, RCC_APB1ENR_TIM4EN);\ UNUSED(tmpreg); \ } while(0) #define __HAL_RCC_SPI3_CLK_ENABLE() do { \ __IO uint32_t tmpreg; \ SET_BIT(RCC->APB1ENR, RCC_APB1ENR_SPI3EN);\ /* Delay after an RCC peripheral clock enabling */ \ tmpreg = READ_BIT(RCC->APB1ENR, RCC_APB1ENR_SPI3EN);\ UNUSED(tmpreg); \ } while(0) #define __HAL_RCC_I2C3_CLK_ENABLE() do { \ __IO uint32_t tmpreg; \ SET_BIT(RCC->APB1ENR, RCC_APB1ENR_I2C3EN);\ /* Delay after an RCC peripheral clock enabling */ \ tmpreg = READ_BIT(RCC->APB1ENR, RCC_APB1ENR_I2C3EN);\ UNUSED(tmpreg); \ } while(0) #define __HAL_RCC_TIM2_CLK_DISABLE() (RCC->APB1ENR &= ~(RCC_APB1ENR_TIM2EN)) #define __HAL_RCC_TIM3_CLK_DISABLE() (RCC->APB1ENR &= ~(RCC_APB1ENR_TIM3EN)) #define __HAL_RCC_TIM4_CLK_DISABLE() (RCC->APB1ENR &= ~(RCC_APB1ENR_TIM4EN)) #define __HAL_RCC_SPI3_CLK_DISABLE() (RCC->APB1ENR &= ~(RCC_APB1ENR_SPI3EN)) #define __HAL_RCC_I2C3_CLK_DISABLE() (RCC->APB1ENR &= ~(RCC_APB1ENR_I2C3EN)) /** * @} */ /** @defgroup RCCEx_APB2_Clock_Enable_Disable APB2 Peripheral Clock Enable Disable * @brief Enable or disable the High Speed APB (APB2) peripheral clock. * @note After reset, the peripheral clock (used for registers read/write access) * is disabled and the application software has to enable this clock before * using it. * @{ */ #define __HAL_RCC_SDIO_CLK_ENABLE() do { \ __IO uint32_t tmpreg; \ SET_BIT(RCC->APB2ENR, RCC_APB2ENR_SDIOEN);\ /* Delay after an RCC peripheral clock enabling */ \ tmpreg = READ_BIT(RCC->APB2ENR, RCC_APB2ENR_SDIOEN);\ UNUSED(tmpreg); \ } while(0) #define __HAL_RCC_SPI4_CLK_ENABLE() do { \ __IO uint32_t tmpreg; \ SET_BIT(RCC->APB2ENR, RCC_APB2ENR_SPI4EN);\ /* Delay after an RCC peripheral clock enabling */ \ tmpreg = READ_BIT(RCC->APB2ENR, RCC_APB2ENR_SPI4EN);\ UNUSED(tmpreg); \ } while(0) #define __HAL_RCC_TIM10_CLK_ENABLE() do { \ __IO uint32_t tmpreg; \ SET_BIT(RCC->APB2ENR, RCC_APB2ENR_TIM10EN);\ /* Delay after an RCC peripheral clock enabling */ \ tmpreg = READ_BIT(RCC->APB2ENR, RCC_APB2ENR_TIM10EN);\ UNUSED(tmpreg); \ } while(0) #define __HAL_RCC_SDIO_CLK_DISABLE() (RCC->APB2ENR &= ~(RCC_APB2ENR_SDIOEN)) #define __HAL_RCC_SPI4_CLK_DISABLE() (RCC->APB2ENR &= ~(RCC_APB2ENR_SPI4EN)) #define __HAL_RCC_TIM10_CLK_DISABLE() (RCC->APB2ENR &= ~(RCC_APB2ENR_TIM10EN)) /** * @} */ /** @defgroup RCCEx_AHB1_Force_Release_Reset AHB1 Force Release Reset * @brief Force or release AHB1 peripheral reset. * @{ */ #define __HAL_RCC_AHB1_FORCE_RESET() (RCC->AHB1RSTR = 0xFFFFFFFF) #define __HAL_RCC_GPIOD_FORCE_RESET() (RCC->AHB1RSTR |= (RCC_AHB1RSTR_GPIODRST)) #define __HAL_RCC_GPIOE_FORCE_RESET() (RCC->AHB1RSTR |= (RCC_AHB1RSTR_GPIOERST)) #define __HAL_RCC_CRC_FORCE_RESET() (RCC->AHB1RSTR |= (RCC_AHB1RSTR_CRCRST)) #define __HAL_RCC_AHB1_RELEASE_RESET() (RCC->AHB1RSTR = 0x00) #define __HAL_RCC_GPIOD_RELEASE_RESET() (RCC->AHB1RSTR &= ~(RCC_AHB1RSTR_GPIODRST)) #define __HAL_RCC_GPIOE_RELEASE_RESET() (RCC->AHB1RSTR &= ~(RCC_AHB1RSTR_GPIOERST)) #define __HAL_RCC_CRC_RELEASE_RESET() (RCC->AHB1RSTR &= ~(RCC_AHB1RSTR_CRCRST)) /** * @} */ /** @defgroup RCCEx_AHB2_Force_Release_Reset AHB2 Force Release Reset * @brief Force or release AHB2 peripheral reset. * @{ */ #define __HAL_RCC_AHB2_FORCE_RESET() (RCC->AHB2RSTR = 0xFFFFFFFF) #define __HAL_RCC_USB_OTG_FS_FORCE_RESET() (RCC->AHB2RSTR |= (RCC_AHB2RSTR_OTGFSRST)) #define __HAL_RCC_AHB2_RELEASE_RESET() (RCC->AHB2RSTR = 0x00) #define __HAL_RCC_USB_OTG_FS_RELEASE_RESET() (RCC->AHB2RSTR &= ~(RCC_AHB2RSTR_OTGFSRST)) /** * @} */ /** @defgroup RCCEx_APB1_Force_Release_Reset APB1 Force Release Reset * @brief Force or release APB1 peripheral reset. * @{ */ #define __HAL_RCC_APB1_FORCE_RESET() (RCC->APB1RSTR = 0xFFFFFFFF) #define __HAL_RCC_TIM2_FORCE_RESET() (RCC->APB1RSTR |= (RCC_APB1RSTR_TIM2RST)) #define __HAL_RCC_TIM3_FORCE_RESET() (RCC->APB1RSTR |= (RCC_APB1RSTR_TIM3RST)) #define __HAL_RCC_TIM4_FORCE_RESET() (RCC->APB1RSTR |= (RCC_APB1RSTR_TIM4RST)) #define __HAL_RCC_SPI3_FORCE_RESET() (RCC->APB1RSTR |= (RCC_APB1RSTR_SPI3RST)) #define __HAL_RCC_I2C3_FORCE_RESET() (RCC->APB1RSTR |= (RCC_APB1RSTR_I2C3RST)) #define __HAL_RCC_APB1_RELEASE_RESET() (RCC->APB1RSTR = 0x00) #define __HAL_RCC_TIM2_RELEASE_RESET() (RCC->APB1RSTR &= ~(RCC_APB1RSTR_TIM2RST)) #define __HAL_RCC_TIM3_RELEASE_RESET() (RCC->APB1RSTR &= ~(RCC_APB1RSTR_TIM3RST)) #define __HAL_RCC_TIM4_RELEASE_RESET() (RCC->APB1RSTR &= ~(RCC_APB1RSTR_TIM4RST)) #define __HAL_RCC_SPI3_RELEASE_RESET() (RCC->APB1RSTR &= ~(RCC_APB1RSTR_SPI3RST)) #define __HAL_RCC_I2C3_RELEASE_RESET() (RCC->APB1RSTR &= ~(RCC_APB1RSTR_I2C3RST)) /** * @} */ /** @defgroup RCCEx_APB2_Force_Release_Reset APB2 Force Release Reset * @brief Force or release APB2 peripheral reset. * @{ */ #define __HAL_RCC_APB2_FORCE_RESET() (RCC->APB2RSTR = 0xFFFFFFFF) #define __HAL_RCC_SDIO_FORCE_RESET() (RCC->APB2RSTR |= (RCC_APB2RSTR_SDIORST)) #define __HAL_RCC_SPI4_FORCE_RESET() (RCC->APB2RSTR |= (RCC_APB2RSTR_SPI4RST)) #define __HAL_RCC_TIM10_FORCE_RESET() (RCC->APB2RSTR |= (RCC_APB2RSTR_TIM10RST)) #define __HAL_RCC_APB2_RELEASE_RESET() (RCC->APB2RSTR = 0x00) #define __HAL_RCC_SDIO_RELEASE_RESET() (RCC->APB2RSTR &= ~(RCC_APB2RSTR_SDIORST)) #define __HAL_RCC_SPI4_RELEASE_RESET() (RCC->APB2RSTR &= ~(RCC_APB2RSTR_SPI4RST)) #define __HAL_RCC_TIM10_RELEASE_RESET() (RCC->APB2RSTR &= ~(RCC_APB2RSTR_TIM10RST)) /** * @} */ /** @defgroup RCCEx_AHB3_Force_Release_Reset AHB3 Force Release Reset * @brief Force or release AHB3 peripheral reset. * @{ */ #define __HAL_RCC_AHB3_FORCE_RESET() (RCC->AHB3RSTR = 0xFFFFFFFF) #define __HAL_RCC_AHB3_RELEASE_RESET() (RCC->AHB3RSTR = 0x00) /** * @} */ /** @defgroup RCCEx_AHB1_LowPower_Enable_Disable AHB1 Peripheral Low Power Enable Disable * @brief Enable or disable the AHB1 peripheral clock during Low Power (Sleep) mode. * @note Peripheral clock gating in SLEEP mode can be used to further reduce * power consumption. * @note After wake-up from SLEEP mode, the peripheral clock is enabled again. * @note By default, all peripheral clocks are enabled during SLEEP mode. * @{ */ #define __HAL_RCC_GPIOD_CLK_SLEEP_ENABLE() (RCC->AHB1LPENR |= (RCC_AHB1LPENR_GPIODLPEN)) #define __HAL_RCC_GPIOE_CLK_SLEEP_ENABLE() (RCC->AHB1LPENR |= (RCC_AHB1LPENR_GPIOELPEN)) #define __HAL_RCC_CRC_CLK_SLEEP_ENABLE() (RCC->AHB1LPENR |= (RCC_AHB1LPENR_CRCLPEN)) #define __HAL_RCC_FLITF_CLK_SLEEP_ENABLE() (RCC->AHB1LPENR |= (RCC_AHB1LPENR_FLITFLPEN)) #define __HAL_RCC_SRAM1_CLK_SLEEP_ENABLE() (RCC->AHB1LPENR |= (RCC_AHB1LPENR_SRAM1LPEN)) #define __HAL_RCC_BKPSRAM_CLK_SLEEP_ENABLE() (RCC->AHB1LPENR |= (RCC_AHB1LPENR_BKPSRAMLPEN)) #define __HAL_RCC_GPIOD_CLK_SLEEP_DISABLE() (RCC->AHB1LPENR &= ~(RCC_AHB1LPENR_GPIODLPEN)) #define __HAL_RCC_GPIOE_CLK_SLEEP_DISABLE() (RCC->AHB1LPENR &= ~(RCC_AHB1LPENR_GPIOELPEN)) #define __HAL_RCC_CRC_CLK_SLEEP_DISABLE() (RCC->AHB1LPENR &= ~(RCC_AHB1LPENR_CRCLPEN)) #define __HAL_RCC_FLITF_CLK_SLEEP_DISABLE() (RCC->AHB1LPENR &= ~(RCC_AHB1LPENR_FLITFLPEN)) #define __HAL_RCC_SRAM1_CLK_SLEEP_DISABLE() (RCC->AHB1LPENR &= ~(RCC_AHB1LPENR_SRAM1LPEN)) #define __HAL_RCC_BKPSRAM_CLK_SLEEP_DISABLE() (RCC->AHB1LPENR &= ~(RCC_AHB1LPENR_BKPSRAMLPEN)) /** * @} */ /** @defgroup RCCEx_AHB2_LowPower_Enable_Disable AHB2 Peripheral Low Power Enable Disable * @brief Enable or disable the AHB2 peripheral clock during Low Power (Sleep) mode. * @note Peripheral clock gating in SLEEP mode can be used to further reduce * power consumption. * @note After wake-up from SLEEP mode, the peripheral clock is enabled again. * @note By default, all peripheral clocks are enabled during SLEEP mode. * @{ */ #define __HAL_RCC_USB_OTG_FS_CLK_SLEEP_ENABLE() (RCC->AHB2LPENR |= (RCC_AHB2LPENR_OTGFSLPEN)) #define __HAL_RCC_USB_OTG_FS_CLK_SLEEP_DISABLE() (RCC->AHB2LPENR &= ~(RCC_AHB2LPENR_OTGFSLPEN)) /** * @} */ /** @defgroup RCCEx_APB1_LowPower_Enable_Disable APB1 Peripheral Low Power Enable Disable * @brief Enable or disable the APB1 peripheral clock during Low Power (Sleep) mode. * @note Peripheral clock gating in SLEEP mode can be used to further reduce * power consumption. * @note After wake-up from SLEEP mode, the peripheral clock is enabled again. * @note By default, all peripheral clocks are enabled during SLEEP mode. * @{ */ #define __HAL_RCC_TIM2_CLK_SLEEP_ENABLE() (RCC->APB1LPENR |= (RCC_APB1LPENR_TIM2LPEN)) #define __HAL_RCC_TIM3_CLK_SLEEP_ENABLE() (RCC->APB1LPENR |= (RCC_APB1LPENR_TIM3LPEN)) #define __HAL_RCC_TIM4_CLK_SLEEP_ENABLE() (RCC->APB1LPENR |= (RCC_APB1LPENR_TIM4LPEN)) #define __HAL_RCC_SPI3_CLK_SLEEP_ENABLE() (RCC->APB1LPENR |= (RCC_APB1LPENR_SPI3LPEN)) #define __HAL_RCC_I2C3_CLK_SLEEP_ENABLE() (RCC->APB1LPENR |= (RCC_APB1LPENR_I2C3LPEN)) #define __HAL_RCC_TIM2_CLK_SLEEP_DISABLE() (RCC->APB1LPENR &= ~(RCC_APB1LPENR_TIM2LPEN)) #define __HAL_RCC_TIM3_CLK_SLEEP_DISABLE() (RCC->APB1LPENR &= ~(RCC_APB1LPENR_TIM3LPEN)) #define __HAL_RCC_TIM4_CLK_SLEEP_DISABLE() (RCC->APB1LPENR &= ~(RCC_APB1LPENR_TIM4LPEN)) #define __HAL_RCC_SPI3_CLK_SLEEP_DISABLE() (RCC->APB1LPENR &= ~(RCC_APB1LPENR_SPI3LPEN)) #define __HAL_RCC_I2C3_CLK_SLEEP_DISABLE() (RCC->APB1LPENR &= ~(RCC_APB1LPENR_I2C3LPEN)) /** * @} */ /** @defgroup RCCEx_APB2_LowPower_Enable_Disable APB2 Peripheral Low Power Enable Disable * @brief Enable or disable the APB2 peripheral clock during Low Power (Sleep) mode. * @note Peripheral clock gating in SLEEP mode can be used to further reduce * power consumption. * @note After wake-up from SLEEP mode, the peripheral clock is enabled again. * @note By default, all peripheral clocks are enabled during SLEEP mode. * @{ */ #define __HAL_RCC_SDIO_CLK_SLEEP_ENABLE() (RCC->APB2LPENR |= (RCC_APB2LPENR_SDIOLPEN)) #define __HAL_RCC_SPI4_CLK_SLEEP_ENABLE() (RCC->APB2LPENR |= (RCC_APB2LPENR_SPI4LPEN)) #define __HAL_RCC_TIM10_CLK_SLEEP_ENABLE() (RCC->APB2LPENR |= (RCC_APB2LPENR_TIM10LPEN)) #define __HAL_RCC_SDIO_CLK_SLEEP_DISABLE() (RCC->APB2LPENR &= ~(RCC_APB2LPENR_SDIOLPEN)) #define __HAL_RCC_SPI4_CLK_SLEEP_DISABLE() (RCC->APB2LPENR &= ~(RCC_APB2LPENR_SPI4LPEN)) #define __HAL_RCC_TIM10_CLK_SLEEP_DISABLE() (RCC->APB2LPENR &= ~(RCC_APB2LPENR_TIM10LPEN)) /** * @} */ #endif /* STM32F401xC || STM32F401xE*/ /*----------------------------------------------------------------------------*/ /*-------------------------------- STM32F410xx -------------------------------*/ #if defined(STM32F410Tx) || defined(STM32F410Cx) || defined(STM32F410Rx) /** @defgroup RCCEx_AHB1_Clock_Enable_Disable AHB1 Peripheral Clock Enable Disable * @brief Enables or disables the AHB1 peripheral clock. * @note After reset, the peripheral clock (used for registers read/write access) * is disabled and the application software has to enable this clock before * using it. */ #define __HAL_RCC_CRC_CLK_ENABLE() do { \ __IO uint32_t tmpreg; \ SET_BIT(RCC->AHB1ENR, RCC_AHB1ENR_CRCEN);\ /* Delay after an RCC peripheral clock enabling */ \ tmpreg = READ_BIT(RCC->AHB1ENR, RCC_AHB1ENR_CRCEN);\ UNUSED(tmpreg); \ } while(0) #define __HAL_RCC_RNG_CLK_ENABLE() do { \ __IO uint32_t tmpreg; \ SET_BIT(RCC->AHB1ENR, RCC_AHB1ENR_RNGEN);\ /* Delay after an RCC peripheral clock enabling */ \ tmpreg = READ_BIT(RCC->AHB1ENR, RCC_AHB1ENR_RNGEN);\ UNUSED(tmpreg); \ } while(0) #define __HAL_RCC_CRC_CLK_DISABLE() (RCC->AHB1ENR &= ~(RCC_AHB1ENR_CRCEN)) #define __HAL_RCC_RNG_CLK_DISABLE() (RCC->AHB1ENR &= ~(RCC_AHB1ENR_RNGEN)) /** * @} */ /** @defgroup RCCEx_APB1_Clock_Enable_Disable APB1 Peripheral Clock Enable Disable * @brief Enable or disable the High Speed APB (APB1) peripheral clock. */ #define __HAL_RCC_TIM6_CLK_ENABLE() do { \ __IO uint32_t tmpreg; \ SET_BIT(RCC->APB1ENR, RCC_APB1ENR_TIM6EN);\ /* Delay after an RCC peripheral clock enabling */ \ tmpreg = READ_BIT(RCC->APB1ENR, RCC_APB1ENR_TIM6EN);\ UNUSED(tmpreg); \ } while(0) #define __HAL_RCC_LPTIM1_CLK_ENABLE() do { \ __IO uint32_t tmpreg; \ SET_BIT(RCC->APB1ENR, RCC_APB1ENR_LPTIM1EN);\ /* Delay after an RCC peripheral clock enabling */ \ tmpreg = READ_BIT(RCC->APB1ENR, RCC_APB1ENR_LPTIM1EN);\ UNUSED(tmpreg); \ } while(0) #define __HAL_RCC_RTCAPB_CLK_ENABLE() do { \ __IO uint32_t tmpreg; \ SET_BIT(RCC->APB1ENR, RCC_APB1ENR_RTCAPBEN);\ /* Delay after an RCC peripheral clock enabling */ \ tmpreg = READ_BIT(RCC->APB1ENR, RCC_APB1ENR_RTCAPBEN);\ UNUSED(tmpreg); \ } while(0) #define __HAL_RCC_FMPI2C1_CLK_ENABLE() do { \ __IO uint32_t tmpreg; \ SET_BIT(RCC->APB1ENR, RCC_APB1ENR_FMPI2C1EN);\ /* Delay after an RCC peripheral clock enabling */ \ tmpreg = READ_BIT(RCC->APB1ENR, RCC_APB1ENR_FMPI2C1EN);\ UNUSED(tmpreg); \ } while(0) #define __HAL_RCC_DAC_CLK_ENABLE() do { \ __IO uint32_t tmpreg; \ SET_BIT(RCC->APB1ENR, RCC_APB1ENR_DACEN);\ /* Delay after an RCC peripheral clock enabling */ \ tmpreg = READ_BIT(RCC->APB1ENR, RCC_APB1ENR_DACEN);\ UNUSED(tmpreg); \ } while(0) #define __HAL_RCC_TIM6_CLK_DISABLE() (RCC->APB1ENR &= ~(RCC_APB1ENR_TIM6EN)) #define __HAL_RCC_RTCAPB_CLK_DISABLE() (RCC->APB1ENR &= ~(RCC_APB1ENR_RTCAPBEN)) #define __HAL_RCC_LPTIM1_CLK_DISABLE() (RCC->APB1ENR &= ~(RCC_APB1ENR_LPTIM1EN)) #define __HAL_RCC_FMPI2C1_CLK_DISABLE() (RCC->APB1ENR &= ~(RCC_APB1ENR_FMPI2C1EN)) #define __HAL_RCC_DAC_CLK_DISABLE() (RCC->APB1ENR &= ~(RCC_APB1ENR_DACEN)) /** * @} */ /** @defgroup RCCEx_APB2_Clock_Enable_Disable APB2 Peripheral Clock Enable Disable * @brief Enable or disable the High Speed APB (APB2) peripheral clock. */ #define __HAL_RCC_SPI5_CLK_ENABLE() do { \ __IO uint32_t tmpreg; \ SET_BIT(RCC->APB2ENR, RCC_APB2ENR_SPI5EN);\ /* Delay after an RCC peripheral clock enabling */ \ tmpreg = READ_BIT(RCC->APB2ENR, RCC_APB2ENR_SPI5EN);\ UNUSED(tmpreg); \ } while(0) #define __HAL_RCC_EXTIT_CLK_ENABLE() do { \ __IO uint32_t tmpreg; \ SET_BIT(RCC->APB2ENR, RCC_APB2ENR_EXTITEN);\ /* Delay after an RCC peripheral clock enabling */ \ tmpreg = READ_BIT(RCC->APB2ENR, RCC_APB2ENR_EXTITEN);\ UNUSED(tmpreg); \ } while(0) #define __HAL_RCC_SPI5_CLK_DISABLE() (RCC->APB2ENR &= ~(RCC_APB2ENR_SPI5EN)) #define __HAL_RCC_EXTIT_CLK_DISABLE() (RCC->APB2ENR &= ~(RCC_APB2ENR_EXTITEN)) /** * @} */ /** @defgroup RCCEx_AHB1_Force_Release_Reset AHB1 Force Release Reset * @brief Force or release AHB1 peripheral reset. */ #define __HAL_RCC_CRC_FORCE_RESET() (RCC->AHB1RSTR |= (RCC_AHB1RSTR_CRCRST)) #define __HAL_RCC_RNG_FORCE_RESET() (RCC->AHB1RSTR |= (RCC_AHB1RSTR_RNGRST)) #define __HAL_RCC_CRC_RELEASE_RESET() (RCC->AHB1RSTR &= ~(RCC_AHB1RSTR_CRCRST)) #define __HAL_RCC_RNG_RELEASE_RESET() (RCC->AHB1RSTR &= ~(RCC_AHB1RSTR_RNGRST)) /** * @} */ /** @defgroup RCCEx_AHB2_Force_Release_Reset AHB2 Force Release Reset * @brief Force or release AHB2 peripheral reset. * @{ */ #define __HAL_RCC_AHB2_FORCE_RESET() #define __HAL_RCC_AHB2_RELEASE_RESET() /** * @} */ /** @defgroup RCCEx_AHB3_Force_Release_Reset AHB3 Force Release Reset * @brief Force or release AHB3 peripheral reset. * @{ */ #define __HAL_RCC_AHB3_FORCE_RESET() #define __HAL_RCC_AHB3_RELEASE_RESET() /** * @} */ /** @defgroup RCCEx_APB1_Force_Release_Reset APB1 Force Release Reset * @brief Force or release APB1 peripheral reset. */ #define __HAL_RCC_TIM6_FORCE_RESET() (RCC->APB1RSTR |= (RCC_APB1RSTR_TIM6RST)) #define __HAL_RCC_LPTIM1_FORCE_RESET() (RCC->APB1RSTR |= (RCC_APB1RSTR_LPTIM1RST)) #define __HAL_RCC_FMPI2C1_FORCE_RESET() (RCC->APB1RSTR |= (RCC_APB1RSTR_FMPI2C1RST)) #define __HAL_RCC_DAC_FORCE_RESET() (RCC->APB1RSTR |= (RCC_APB1RSTR_DACRST)) #define __HAL_RCC_TIM6_RELEASE_RESET() (RCC->APB1RSTR &= ~(RCC_APB1RSTR_TIM6RST)) #define __HAL_RCC_LPTIM1_RELEASE_RESET() (RCC->APB1RSTR &= ~(RCC_APB1RSTR_LPTIM1RST)) #define __HAL_RCC_FMPI2C1_RELEASE_RESET() (RCC->APB1RSTR &= ~(RCC_APB1RSTR_FMPI2C1RST)) #define __HAL_RCC_DAC_RELEASE_RESET() (RCC->APB1RSTR &= ~(RCC_APB1RSTR_DACRST)) /** * @} */ /** @defgroup RCCEx_APB2_Force_Release_Reset APB2 Force Release Reset * @brief Force or release APB2 peripheral reset. */ #define __HAL_RCC_SPI5_FORCE_RESET() (RCC->APB2RSTR |= (RCC_APB2RSTR_SPI5RST)) #define __HAL_RCC_SPI5_RELEASE_RESET() (RCC->APB2RSTR &= ~(RCC_APB2RSTR_SPI5RST)) /** * @} */ /** @defgroup RCCEx_AHB1_LowPower_Enable_Disable AHB1 Peripheral Low Power Enable Disable * @brief Enable or disable the AHB1 peripheral clock during Low Power (Sleep) mode. * @note Peripheral clock gating in SLEEP mode can be used to further reduce * power consumption. * @note After wakeup from SLEEP mode, the peripheral clock is enabled again. * @note By default, all peripheral clocks are enabled during SLEEP mode. */ #define __HAL_RCC_RNG_CLK_SLEEP_ENABLE() (RCC->AHB1LPENR |= (RCC_AHB1LPENR_RNGLPEN)) #define __HAL_RCC_CRC_CLK_SLEEP_ENABLE() (RCC->AHB1LPENR |= (RCC_AHB1LPENR_CRCLPEN)) #define __HAL_RCC_FLITF_CLK_SLEEP_ENABLE() (RCC->AHB1LPENR |= (RCC_AHB1LPENR_FLITFLPEN)) #define __HAL_RCC_SRAM1_CLK_SLEEP_ENABLE() (RCC->AHB1LPENR |= (RCC_AHB1LPENR_SRAM1LPEN)) #define __HAL_RCC_RNG_CLK_SLEEP_DISABLE() (RCC->AHB1LPENR &= ~(RCC_AHB1LPENR_RNGLPEN)) #define __HAL_RCC_CRC_CLK_SLEEP_DISABLE() (RCC->AHB1LPENR &= ~(RCC_AHB1LPENR_CRCLPEN)) #define __HAL_RCC_FLITF_CLK_SLEEP_DISABLE() (RCC->AHB1LPENR &= ~(RCC_AHB1LPENR_FLITFLPEN)) #define __HAL_RCC_SRAM1_CLK_SLEEP_DISABLE() (RCC->AHB1LPENR &= ~(RCC_AHB1LPENR_SRAM1LPEN)) /** * @} */ /** @defgroup RCCEx_APB1_LowPower_Enable_Disable APB1 Peripheral Low Power Enable Disable * @brief Enable or disable the APB1 peripheral clock during Low Power (Sleep) mode. */ #define __HAL_RCC_TIM6_CLK_SLEEP_ENABLE() (RCC->APB1LPENR |= (RCC_APB1LPENR_TIM6LPEN)) #define __HAL_RCC_LPTIM1_CLK_SLEEP_ENABLE() (RCC->APB1LPENR |= (RCC_APB1LPENR_LPTIM1LPEN)) #define __HAL_RCC_RTCAPB_CLK_SLEEP_ENABLE() (RCC->APB1LPENR |= (RCC_APB1LPENR_RTCAPBLPEN)) #define __HAL_RCC_FMPI2C1_CLK_SLEEP_ENABLE() (RCC->APB1LPENR |= (RCC_APB1LPENR_FMPI2C1LPEN)) #define __HAL_RCC_DAC_CLK_SLEEP_ENABLE() (RCC->APB1LPENR |= (RCC_APB1LPENR_DACLPEN)) #define __HAL_RCC_TIM6_CLK_SLEEP_DISABLE() (RCC->APB1LPENR &= ~(RCC_APB1LPENR_TIM6LPEN)) #define __HAL_RCC_LPTIM1_CLK_SLEEP_DISABLE() (RCC->APB1LPENR &= ~(RCC_APB1LPENR_LPTIM1LPEN)) #define __HAL_RCC_RTCAPB_CLK_SLEEP_DISABLE() (RCC->APB1LPENR &= ~(RCC_APB1LPENR_RTCAPBLPEN)) #define __HAL_RCC_FMPI2C1_CLK_SLEEP_DISABLE() (RCC->APB1LPENR &= ~(RCC_APB1LPENR_FMPI2C1LPEN)) #define __HAL_RCC_DAC_CLK_SLEEP_DISABLE() (RCC->APB1LPENR &= ~(RCC_APB1LPENR_DACLPEN)) /** * @} */ /** @defgroup RCCEx_APB2_LowPower_Enable_Disable APB2 Peripheral Low Power Enable Disable * @brief Enable or disable the APB2 peripheral clock during Low Power (Sleep) mode. */ #define __HAL_RCC_SPI5_CLK_SLEEP_ENABLE() (RCC->APB2LPENR |= (RCC_APB2LPENR_SPI5LPEN)) #define __HAL_RCC_EXTIT_CLK_SLEEP_ENABLE() (RCC->APB2LPENR |= (RCC_APB2LPENR_EXTITLPEN)) #define __HAL_RCC_SPI5_CLK_SLEEP_DISABLE() (RCC->APB2LPENR &= ~(RCC_APB2LPENR_SPI5LPEN)) #define __HAL_RCC_EXTIT_CLK_SLEEP_DISABLE() (RCC->APB2LPENR &= ~(RCC_APB2LPENR_EXTITLPEN)) /** * @} */ #endif /* STM32F410Tx || STM32F410Cx || STM32F410Rx */ /*----------------------------------------------------------------------------*/ /*-------------------------------- STM32F411xx -------------------------------*/ #if defined(STM32F411xE) /** @defgroup RCCEx_AHB1_Clock_Enable_Disable AHB1 Peripheral Clock Enable Disable * @brief Enables or disables the AHB1 peripheral clock. * @note After reset, the peripheral clock (used for registers read/write access) * is disabled and the application software has to enable this clock before * using it. */ #define __HAL_RCC_BKPSRAM_CLK_ENABLE() do { \ __IO uint32_t tmpreg; \ SET_BIT(RCC->AHB1ENR, RCC_AHB1ENR_BKPSRAMEN);\ /* Delay after an RCC peripheral clock enabling */ \ tmpreg = READ_BIT(RCC->AHB1ENR, RCC_AHB1ENR_BKPSRAMEN);\ UNUSED(tmpreg); \ } while(0) #define __HAL_RCC_CCMDATARAMEN_CLK_ENABLE() do { \ __IO uint32_t tmpreg; \ SET_BIT(RCC->AHB1ENR, RCC_AHB1ENR_CCMDATARAMEN);\ /* Delay after an RCC peripheral clock enabling */ \ tmpreg = READ_BIT(RCC->AHB1ENR, RCC_AHB1ENR_CCMDATARAMEN);\ UNUSED(tmpreg); \ } while(0) #define __HAL_RCC_GPIOD_CLK_ENABLE() do { \ __IO uint32_t tmpreg; \ SET_BIT(RCC->AHB1ENR, RCC_AHB1ENR_GPIODEN);\ /* Delay after an RCC peripheral clock enabling */ \ tmpreg = READ_BIT(RCC->AHB1ENR, RCC_AHB1ENR_GPIODEN);\ UNUSED(tmpreg); \ } while(0) #define __HAL_RCC_GPIOE_CLK_ENABLE() do { \ __IO uint32_t tmpreg; \ SET_BIT(RCC->AHB1ENR, RCC_AHB1ENR_GPIOEEN);\ /* Delay after an RCC peripheral clock enabling */ \ tmpreg = READ_BIT(RCC->AHB1ENR, RCC_AHB1ENR_GPIOEEN);\ UNUSED(tmpreg); \ } while(0) #define __HAL_RCC_CRC_CLK_ENABLE() do { \ __IO uint32_t tmpreg; \ SET_BIT(RCC->AHB1ENR, RCC_AHB1ENR_CRCEN);\ /* Delay after an RCC peripheral clock enabling */ \ tmpreg = READ_BIT(RCC->AHB1ENR, RCC_AHB1ENR_CRCEN);\ UNUSED(tmpreg); \ } while(0) #define __HAL_RCC_GPIOD_CLK_DISABLE() (RCC->AHB1ENR &= ~(RCC_AHB1ENR_GPIODEN)) #define __HAL_RCC_GPIOE_CLK_DISABLE() (RCC->AHB1ENR &= ~(RCC_AHB1ENR_GPIOEEN)) #define __HAL_RCC_BKPSRAM_CLK_DISABLE() (RCC->AHB1ENR &= ~(RCC_AHB1ENR_BKPSRAMEN)) #define __HAL_RCC_CCMDATARAMEN_CLK_DISABLE() (RCC->AHB1ENR &= ~(RCC_AHB1ENR_CCMDATARAMEN)) #define __HAL_RCC_CRC_CLK_DISABLE() (RCC->AHB1ENR &= ~(RCC_AHB1ENR_CRCEN)) /** * @} */ /** @defgroup RCCEX_AHB2_Clock_Enable_Disable AHB2 Peripheral Clock Enable Disable * @brief Enable or disable the AHB2 peripheral clock. * @note After reset, the peripheral clock (used for registers read/write access) * is disabled and the application software has to enable this clock before * using it. * @{ */ #define __HAL_RCC_USB_OTG_FS_CLK_ENABLE() do {(RCC->AHB2ENR |= (RCC_AHB2ENR_OTGFSEN));\ __HAL_RCC_SYSCFG_CLK_ENABLE();\ }while(0) #define __HAL_RCC_USB_OTG_FS_CLK_DISABLE() do { (RCC->AHB2ENR &= ~(RCC_AHB2ENR_OTGFSEN));\ __HAL_RCC_SYSCFG_CLK_DISABLE();\ }while(0) /** * @} */ /** @defgroup RCCEx_APB1_Clock_Enable_Disable APB1 Peripheral Clock Enable Disable * @brief Enable or disable the Low Speed APB (APB1) peripheral clock. * @note After reset, the peripheral clock (used for registers read/write access) * is disabled and the application software has to enable this clock before * using it. */ #define __HAL_RCC_TIM2_CLK_ENABLE() do { \ __IO uint32_t tmpreg; \ SET_BIT(RCC->APB1ENR, RCC_APB1ENR_TIM2EN);\ /* Delay after an RCC peripheral clock enabling */ \ tmpreg = READ_BIT(RCC->APB1ENR, RCC_APB1ENR_TIM2EN);\ UNUSED(tmpreg); \ } while(0) #define __HAL_RCC_TIM3_CLK_ENABLE() do { \ __IO uint32_t tmpreg; \ SET_BIT(RCC->APB1ENR, RCC_APB1ENR_TIM3EN);\ /* Delay after an RCC peripheral clock enabling */ \ tmpreg = READ_BIT(RCC->APB1ENR, RCC_APB1ENR_TIM3EN);\ UNUSED(tmpreg); \ } while(0) #define __HAL_RCC_TIM4_CLK_ENABLE() do { \ __IO uint32_t tmpreg; \ SET_BIT(RCC->APB1ENR, RCC_APB1ENR_TIM4EN);\ /* Delay after an RCC peripheral clock enabling */ \ tmpreg = READ_BIT(RCC->APB1ENR, RCC_APB1ENR_TIM4EN);\ UNUSED(tmpreg); \ } while(0) #define __HAL_RCC_SPI3_CLK_ENABLE() do { \ __IO uint32_t tmpreg; \ SET_BIT(RCC->APB1ENR, RCC_APB1ENR_SPI3EN);\ /* Delay after an RCC peripheral clock enabling */ \ tmpreg = READ_BIT(RCC->APB1ENR, RCC_APB1ENR_SPI3EN);\ UNUSED(tmpreg); \ } while(0) #define __HAL_RCC_I2C3_CLK_ENABLE() do { \ __IO uint32_t tmpreg; \ SET_BIT(RCC->APB1ENR, RCC_APB1ENR_I2C3EN);\ /* Delay after an RCC peripheral clock enabling */ \ tmpreg = READ_BIT(RCC->APB1ENR, RCC_APB1ENR_I2C3EN);\ UNUSED(tmpreg); \ } while(0) #define __HAL_RCC_TIM2_CLK_DISABLE() (RCC->APB1ENR &= ~(RCC_APB1ENR_TIM2EN)) #define __HAL_RCC_TIM3_CLK_DISABLE() (RCC->APB1ENR &= ~(RCC_APB1ENR_TIM3EN)) #define __HAL_RCC_TIM4_CLK_DISABLE() (RCC->APB1ENR &= ~(RCC_APB1ENR_TIM4EN)) #define __HAL_RCC_SPI3_CLK_DISABLE() (RCC->APB1ENR &= ~(RCC_APB1ENR_SPI3EN)) #define __HAL_RCC_I2C3_CLK_DISABLE() (RCC->APB1ENR &= ~(RCC_APB1ENR_I2C3EN)) /** * @} */ /** @defgroup RCCEx_APB2_Clock_Enable_Disable APB2 Peripheral Clock Enable Disable * @brief Enable or disable the High Speed APB (APB2) peripheral clock. */ #define __HAL_RCC_SPI5_CLK_ENABLE() do { \ __IO uint32_t tmpreg; \ SET_BIT(RCC->APB2ENR, RCC_APB2ENR_SPI5EN);\ /* Delay after an RCC peripheral clock enabling */ \ tmpreg = READ_BIT(RCC->APB2ENR, RCC_APB2ENR_SPI5EN);\ UNUSED(tmpreg); \ } while(0) #define __HAL_RCC_SDIO_CLK_ENABLE() do { \ __IO uint32_t tmpreg; \ SET_BIT(RCC->APB2ENR, RCC_APB2ENR_SDIOEN);\ /* Delay after an RCC peripheral clock enabling */ \ tmpreg = READ_BIT(RCC->APB2ENR, RCC_APB2ENR_SDIOEN);\ UNUSED(tmpreg); \ } while(0) #define __HAL_RCC_SPI4_CLK_ENABLE() do { \ __IO uint32_t tmpreg; \ SET_BIT(RCC->APB2ENR, RCC_APB2ENR_SPI4EN);\ /* Delay after an RCC peripheral clock enabling */ \ tmpreg = READ_BIT(RCC->APB2ENR, RCC_APB2ENR_SPI4EN);\ UNUSED(tmpreg); \ } while(0) #define __HAL_RCC_TIM10_CLK_ENABLE() do { \ __IO uint32_t tmpreg; \ SET_BIT(RCC->APB2ENR, RCC_APB2ENR_TIM10EN);\ /* Delay after an RCC peripheral clock enabling */ \ tmpreg = READ_BIT(RCC->APB2ENR, RCC_APB2ENR_TIM10EN);\ UNUSED(tmpreg); \ } while(0) #define __HAL_RCC_SDIO_CLK_DISABLE() (RCC->APB2ENR &= ~(RCC_APB2ENR_SDIOEN)) #define __HAL_RCC_SPI4_CLK_DISABLE() (RCC->APB2ENR &= ~(RCC_APB2ENR_SPI4EN)) #define __HAL_RCC_TIM10_CLK_DISABLE() (RCC->APB2ENR &= ~(RCC_APB2ENR_TIM10EN)) #define __HAL_RCC_SPI5_CLK_DISABLE() (RCC->APB2ENR &= ~(RCC_APB2ENR_SPI5EN)) /** * @} */ /** @defgroup RCCEx_AHB1_Force_Release_Reset AHB1 Force Release Reset * @brief Force or release AHB1 peripheral reset. */ #define __HAL_RCC_GPIOD_FORCE_RESET() (RCC->AHB1RSTR |= (RCC_AHB1RSTR_GPIODRST)) #define __HAL_RCC_GPIOE_FORCE_RESET() (RCC->AHB1RSTR |= (RCC_AHB1RSTR_GPIOERST)) #define __HAL_RCC_CRC_FORCE_RESET() (RCC->AHB1RSTR |= (RCC_AHB1RSTR_CRCRST)) #define __HAL_RCC_GPIOD_RELEASE_RESET() (RCC->AHB1RSTR &= ~(RCC_AHB1RSTR_GPIODRST)) #define __HAL_RCC_GPIOE_RELEASE_RESET() (RCC->AHB1RSTR &= ~(RCC_AHB1RSTR_GPIOERST)) #define __HAL_RCC_CRC_RELEASE_RESET() (RCC->AHB1RSTR &= ~(RCC_AHB1RSTR_CRCRST)) /** * @} */ /** @defgroup RCCEx_AHB2_Force_Release_Reset AHB2 Force Release Reset * @brief Force or release AHB2 peripheral reset. * @{ */ #define __HAL_RCC_AHB2_FORCE_RESET() (RCC->AHB2RSTR = 0xFFFFFFFF) #define __HAL_RCC_USB_OTG_FS_FORCE_RESET() (RCC->AHB2RSTR |= (RCC_AHB2RSTR_OTGFSRST)) #define __HAL_RCC_AHB2_RELEASE_RESET() (RCC->AHB2RSTR = 0x00) #define __HAL_RCC_USB_OTG_FS_RELEASE_RESET() (RCC->AHB2RSTR &= ~(RCC_AHB2RSTR_OTGFSRST)) /** * @} */ /** @defgroup RCCEx_AHB3_Force_Release_Reset AHB3 Force Release Reset * @brief Force or release AHB3 peripheral reset. * @{ */ #define __HAL_RCC_AHB3_FORCE_RESET() (RCC->AHB3RSTR = 0xFFFFFFFF) #define __HAL_RCC_AHB3_RELEASE_RESET() (RCC->AHB3RSTR = 0x00) /** * @} */ /** @defgroup RCCEx_APB1_Force_Release_Reset APB1 Force Release Reset * @brief Force or release APB1 peripheral reset. */ #define __HAL_RCC_TIM2_FORCE_RESET() (RCC->APB1RSTR |= (RCC_APB1RSTR_TIM2RST)) #define __HAL_RCC_TIM3_FORCE_RESET() (RCC->APB1RSTR |= (RCC_APB1RSTR_TIM3RST)) #define __HAL_RCC_TIM4_FORCE_RESET() (RCC->APB1RSTR |= (RCC_APB1RSTR_TIM4RST)) #define __HAL_RCC_SPI3_FORCE_RESET() (RCC->APB1RSTR |= (RCC_APB1RSTR_SPI3RST)) #define __HAL_RCC_I2C3_FORCE_RESET() (RCC->APB1RSTR |= (RCC_APB1RSTR_I2C3RST)) #define __HAL_RCC_TIM2_RELEASE_RESET() (RCC->APB1RSTR &= ~(RCC_APB1RSTR_TIM2RST)) #define __HAL_RCC_TIM3_RELEASE_RESET() (RCC->APB1RSTR &= ~(RCC_APB1RSTR_TIM3RST)) #define __HAL_RCC_TIM4_RELEASE_RESET() (RCC->APB1RSTR &= ~(RCC_APB1RSTR_TIM4RST)) #define __HAL_RCC_SPI3_RELEASE_RESET() (RCC->APB1RSTR &= ~(RCC_APB1RSTR_SPI3RST)) #define __HAL_RCC_I2C3_RELEASE_RESET() (RCC->APB1RSTR &= ~(RCC_APB1RSTR_I2C3RST)) /** * @} */ /** @defgroup RCCEx_APB2_Force_Release_Reset APB2 Force Release Reset * @brief Force or release APB2 peripheral reset. */ #define __HAL_RCC_SPI5_FORCE_RESET() (RCC->APB2RSTR |= (RCC_APB2RSTR_SPI5RST)) #define __HAL_RCC_SDIO_FORCE_RESET() (RCC->APB2RSTR |= (RCC_APB2RSTR_SDIORST)) #define __HAL_RCC_SPI4_FORCE_RESET() (RCC->APB2RSTR |= (RCC_APB2RSTR_SPI4RST)) #define __HAL_RCC_TIM10_FORCE_RESET() (RCC->APB2RSTR |= (RCC_APB2RSTR_TIM10RST)) #define __HAL_RCC_SDIO_RELEASE_RESET() (RCC->APB2RSTR &= ~(RCC_APB2RSTR_SDIORST)) #define __HAL_RCC_SPI4_RELEASE_RESET() (RCC->APB2RSTR &= ~(RCC_APB2RSTR_SPI4RST)) #define __HAL_RCC_TIM10_RELEASE_RESET() (RCC->APB2RSTR &= ~(RCC_APB2RSTR_TIM10RST)) #define __HAL_RCC_SPI5_RELEASE_RESET() (RCC->APB2RSTR &= ~(RCC_APB2RSTR_SPI5RST)) /** * @} */ /** @defgroup RCCEx_AHB1_LowPower_Enable_Disable AHB1 Peripheral Low Power Enable Disable * @brief Enable or disable the AHB1 peripheral clock during Low Power (Sleep) mode. * @note Peripheral clock gating in SLEEP mode can be used to further reduce * power consumption. * @note After wakeup from SLEEP mode, the peripheral clock is enabled again. * @note By default, all peripheral clocks are enabled during SLEEP mode. */ #define __HAL_RCC_GPIOD_CLK_SLEEP_ENABLE() (RCC->AHB1LPENR |= (RCC_AHB1LPENR_GPIODLPEN)) #define __HAL_RCC_GPIOE_CLK_SLEEP_ENABLE() (RCC->AHB1LPENR |= (RCC_AHB1LPENR_GPIOELPEN)) #define __HAL_RCC_CRC_CLK_SLEEP_ENABLE() (RCC->AHB1LPENR |= (RCC_AHB1LPENR_CRCLPEN)) #define __HAL_RCC_FLITF_CLK_SLEEP_ENABLE() (RCC->AHB1LPENR |= (RCC_AHB1LPENR_FLITFLPEN)) #define __HAL_RCC_SRAM1_CLK_SLEEP_ENABLE() (RCC->AHB1LPENR |= (RCC_AHB1LPENR_SRAM1LPEN)) #define __HAL_RCC_GPIOD_CLK_SLEEP_DISABLE() (RCC->AHB1LPENR &= ~(RCC_AHB1LPENR_GPIODLPEN)) #define __HAL_RCC_GPIOE_CLK_SLEEP_DISABLE() (RCC->AHB1LPENR &= ~(RCC_AHB1LPENR_GPIOELPEN)) #define __HAL_RCC_CRC_CLK_SLEEP_DISABLE() (RCC->AHB1LPENR &= ~(RCC_AHB1LPENR_CRCLPEN)) #define __HAL_RCC_FLITF_CLK_SLEEP_DISABLE() (RCC->AHB1LPENR &= ~(RCC_AHB1LPENR_FLITFLPEN)) #define __HAL_RCC_SRAM1_CLK_SLEEP_DISABLE() (RCC->AHB1LPENR &= ~(RCC_AHB1LPENR_SRAM1LPEN)) /** * @} */ /** @defgroup RCCEx_AHB2_LowPower_Enable_Disable AHB2 Peripheral Low Power Enable Disable * @brief Enable or disable the AHB2 peripheral clock during Low Power (Sleep) mode. * @note Peripheral clock gating in SLEEP mode can be used to further reduce * power consumption. * @note After wake-up from SLEEP mode, the peripheral clock is enabled again. * @note By default, all peripheral clocks are enabled during SLEEP mode. * @{ */ #define __HAL_RCC_USB_OTG_FS_CLK_SLEEP_ENABLE() (RCC->AHB2LPENR |= (RCC_AHB2LPENR_OTGFSLPEN)) #define __HAL_RCC_USB_OTG_FS_CLK_SLEEP_DISABLE() (RCC->AHB2LPENR &= ~(RCC_AHB2LPENR_OTGFSLPEN)) /** * @} */ /** @defgroup RCCEx_APB1_LowPower_Enable_Disable APB1 Peripheral Low Power Enable Disable * @brief Enable or disable the APB1 peripheral clock during Low Power (Sleep) mode. */ #define __HAL_RCC_TIM2_CLK_SLEEP_ENABLE() (RCC->APB1LPENR |= (RCC_APB1LPENR_TIM2LPEN)) #define __HAL_RCC_TIM3_CLK_SLEEP_ENABLE() (RCC->APB1LPENR |= (RCC_APB1LPENR_TIM3LPEN)) #define __HAL_RCC_TIM4_CLK_SLEEP_ENABLE() (RCC->APB1LPENR |= (RCC_APB1LPENR_TIM4LPEN)) #define __HAL_RCC_SPI3_CLK_SLEEP_ENABLE() (RCC->APB1LPENR |= (RCC_APB1LPENR_SPI3LPEN)) #define __HAL_RCC_I2C3_CLK_SLEEP_ENABLE() (RCC->APB1LPENR |= (RCC_APB1LPENR_I2C3LPEN)) #define __HAL_RCC_TIM2_CLK_SLEEP_DISABLE() (RCC->APB1LPENR &= ~(RCC_APB1LPENR_TIM2LPEN)) #define __HAL_RCC_TIM3_CLK_SLEEP_DISABLE() (RCC->APB1LPENR &= ~(RCC_APB1LPENR_TIM3LPEN)) #define __HAL_RCC_TIM4_CLK_SLEEP_DISABLE() (RCC->APB1LPENR &= ~(RCC_APB1LPENR_TIM4LPEN)) #define __HAL_RCC_SPI3_CLK_SLEEP_DISABLE() (RCC->APB1LPENR &= ~(RCC_APB1LPENR_SPI3LPEN)) #define __HAL_RCC_I2C3_CLK_SLEEP_DISABLE() (RCC->APB1LPENR &= ~(RCC_APB1LPENR_I2C3LPEN)) /** * @} */ /** @defgroup RCCEx_APB2_LowPower_Enable_Disable APB2 Peripheral Low Power Enable Disable * @brief Enable or disable the APB2 peripheral clock during Low Power (Sleep) mode. */ #define __HAL_RCC_SPI5_CLK_SLEEP_ENABLE() (RCC->APB2LPENR |= (RCC_APB2LPENR_SPI5LPEN)) #define __HAL_RCC_SDIO_CLK_SLEEP_ENABLE() (RCC->APB2LPENR |= (RCC_APB2LPENR_SDIOLPEN)) #define __HAL_RCC_SPI4_CLK_SLEEP_ENABLE() (RCC->APB2LPENR |= (RCC_APB2LPENR_SPI4LPEN)) #define __HAL_RCC_TIM10_CLK_SLEEP_ENABLE() (RCC->APB2LPENR |= (RCC_APB2LPENR_TIM10LPEN)) #define __HAL_RCC_SDIO_CLK_SLEEP_DISABLE() (RCC->APB2LPENR &= ~(RCC_APB2LPENR_SDIOLPEN)) #define __HAL_RCC_SPI4_CLK_SLEEP_DISABLE() (RCC->APB2LPENR &= ~(RCC_APB2LPENR_SPI4LPEN)) #define __HAL_RCC_TIM10_CLK_SLEEP_DISABLE() (RCC->APB2LPENR &= ~(RCC_APB2LPENR_TIM10LPEN)) #define __HAL_RCC_SPI5_CLK_SLEEP_DISABLE() (RCC->APB2LPENR &= ~(RCC_APB2LPENR_SPI5LPEN)) /** * @} */ #endif /* STM32F411xE */ /*----------------------------------------------------------------------------*/ /*---------------------------------- STM32F446xx -----------------------------*/ #if defined(STM32F446xx) /** @defgroup RCCEx_AHB1_Clock_Enable_Disable AHB1 Peripheral Clock Enable Disable * @brief Enables or disables the AHB1 peripheral clock. * @note After reset, the peripheral clock (used for registers read/write access) * is disabled and the application software has to enable this clock before * using it. */ #define __HAL_RCC_BKPSRAM_CLK_ENABLE() do { \ __IO uint32_t tmpreg; \ SET_BIT(RCC->AHB1ENR, RCC_AHB1ENR_BKPSRAMEN);\ /* Delay after an RCC peripheral clock enabling */ \ tmpreg = READ_BIT(RCC->AHB1ENR, RCC_AHB1ENR_BKPSRAMEN);\ UNUSED(tmpreg); \ } while(0) #define __HAL_RCC_CCMDATARAMEN_CLK_ENABLE() do { \ __IO uint32_t tmpreg; \ SET_BIT(RCC->AHB1ENR, RCC_AHB1ENR_CCMDATARAMEN);\ /* Delay after an RCC peripheral clock enabling */ \ tmpreg = READ_BIT(RCC->AHB1ENR, RCC_AHB1ENR_CCMDATARAMEN);\ UNUSED(tmpreg); \ } while(0) #define __HAL_RCC_CRC_CLK_ENABLE() do { \ __IO uint32_t tmpreg; \ SET_BIT(RCC->AHB1ENR, RCC_AHB1ENR_CRCEN);\ /* Delay after an RCC peripheral clock enabling */ \ tmpreg = READ_BIT(RCC->AHB1ENR, RCC_AHB1ENR_CRCEN);\ UNUSED(tmpreg); \ } while(0) #define __HAL_RCC_GPIOD_CLK_ENABLE() do { \ __IO uint32_t tmpreg; \ SET_BIT(RCC->AHB1ENR, RCC_AHB1ENR_GPIODEN);\ /* Delay after an RCC peripheral clock enabling */ \ tmpreg = READ_BIT(RCC->AHB1ENR, RCC_AHB1ENR_GPIODEN);\ UNUSED(tmpreg); \ } while(0) #define __HAL_RCC_GPIOE_CLK_ENABLE() do { \ __IO uint32_t tmpreg; \ SET_BIT(RCC->AHB1ENR, RCC_AHB1ENR_GPIOEEN);\ /* Delay after an RCC peripheral clock enabling */ \ tmpreg = READ_BIT(RCC->AHB1ENR, RCC_AHB1ENR_GPIOEEN);\ UNUSED(tmpreg); \ } while(0) #define __HAL_RCC_GPIOF_CLK_ENABLE() do { \ __IO uint32_t tmpreg; \ SET_BIT(RCC->AHB1ENR, RCC_AHB1ENR_GPIOFEN);\ /* Delay after an RCC peripheral clock enabling */ \ tmpreg = READ_BIT(RCC->AHB1ENR, RCC_AHB1ENR_GPIOFEN);\ UNUSED(tmpreg); \ } while(0) #define __HAL_RCC_GPIOG_CLK_ENABLE() do { \ __IO uint32_t tmpreg; \ SET_BIT(RCC->AHB1ENR, RCC_AHB1ENR_GPIOGEN);\ /* Delay after an RCC peripheral clock enabling */ \ tmpreg = READ_BIT(RCC->AHB1ENR, RCC_AHB1ENR_GPIOGEN);\ UNUSED(tmpreg); \ } while(0) #define __HAL_RCC_USB_OTG_HS_CLK_ENABLE() do { \ __IO uint32_t tmpreg; \ SET_BIT(RCC->AHB1ENR, RCC_AHB1ENR_OTGHSEN);\ /* Delay after an RCC peripheral clock enabling */ \ tmpreg = READ_BIT(RCC->AHB1ENR, RCC_AHB1ENR_OTGHSEN);\ UNUSED(tmpreg); \ } while(0) #define __HAL_RCC_USB_OTG_HS_ULPI_CLK_ENABLE() do { \ __IO uint32_t tmpreg; \ SET_BIT(RCC->AHB1ENR, RCC_AHB1ENR_OTGHSULPIEN);\ /* Delay after an RCC peripheral clock enabling */ \ tmpreg = READ_BIT(RCC->AHB1ENR, RCC_AHB1ENR_OTGHSULPIEN);\ UNUSED(tmpreg); \ } while(0) #define __HAL_RCC_GPIOD_CLK_DISABLE() (RCC->AHB1ENR &= ~(RCC_AHB1ENR_GPIODEN)) #define __HAL_RCC_GPIOE_CLK_DISABLE() (RCC->AHB1ENR &= ~(RCC_AHB1ENR_GPIOEEN)) #define __HAL_RCC_GPIOF_CLK_DISABLE() (RCC->AHB1ENR &= ~(RCC_AHB1ENR_GPIOFEN)) #define __HAL_RCC_GPIOG_CLK_DISABLE() (RCC->AHB1ENR &= ~(RCC_AHB1ENR_GPIOGEN)) #define __HAL_RCC_USB_OTG_HS_CLK_DISABLE() (RCC->AHB1ENR &= ~(RCC_AHB1ENR_OTGHSEN)) #define __HAL_RCC_USB_OTG_HS_ULPI_CLK_DISABLE() (RCC->AHB1ENR &= ~(RCC_AHB1ENR_OTGHSULPIEN)) #define __HAL_RCC_BKPSRAM_CLK_DISABLE() (RCC->AHB1ENR &= ~(RCC_AHB1ENR_BKPSRAMEN)) #define __HAL_RCC_CCMDATARAMEN_CLK_DISABLE() (RCC->AHB1ENR &= ~(RCC_AHB1ENR_CCMDATARAMEN)) #define __HAL_RCC_CRC_CLK_DISABLE() (RCC->AHB1ENR &= ~(RCC_AHB1ENR_CRCEN)) /** * @} */ /** @defgroup RCCEx_AHB2_Clock_Enable_Disable AHB2 Peripheral Clock Enable Disable * @brief Enable or disable the AHB2 peripheral clock. * @note After reset, the peripheral clock (used for registers read/write access) * is disabled and the application software has to enable this clock before * using it. */ #define __HAL_RCC_DCMI_CLK_ENABLE() do { \ __IO uint32_t tmpreg; \ SET_BIT(RCC->AHB2ENR, RCC_AHB2ENR_DCMIEN);\ /* Delay after an RCC peripheral clock enabling */ \ tmpreg = READ_BIT(RCC->AHB2ENR, RCC_AHB2ENR_DCMIEN);\ UNUSED(tmpreg); \ } while(0) #define __HAL_RCC_DCMI_CLK_DISABLE() (RCC->AHB2ENR &= ~(RCC_AHB2ENR_DCMIEN)) #define __HAL_RCC_USB_OTG_FS_CLK_ENABLE() do {(RCC->AHB2ENR |= (RCC_AHB2ENR_OTGFSEN));\ __HAL_RCC_SYSCFG_CLK_ENABLE();\ }while(0) #define __HAL_RCC_USB_OTG_FS_CLK_DISABLE() do { (RCC->AHB2ENR &= ~(RCC_AHB2ENR_OTGFSEN));\ __HAL_RCC_SYSCFG_CLK_DISABLE();\ }while(0) #define __HAL_RCC_RNG_CLK_ENABLE() do { \ __IO uint32_t tmpreg; \ SET_BIT(RCC->AHB2ENR, RCC_AHB2ENR_RNGEN);\ /* Delay after an RCC peripheral clock enabling */ \ tmpreg = READ_BIT(RCC->AHB2ENR, RCC_AHB2ENR_RNGEN);\ UNUSED(tmpreg); \ } while(0) #define __HAL_RCC_RNG_CLK_DISABLE() (RCC->AHB2ENR &= ~(RCC_AHB2ENR_RNGEN)) /** * @} */ /** @defgroup RCCEx_AHB3_Clock_Enable_Disable AHB3 Peripheral Clock Enable Disable * @brief Enables or disables the AHB3 peripheral clock. * @note After reset, the peripheral clock (used for registers read/write access) * is disabled and the application software has to enable this clock before * using it. */ #define __HAL_RCC_FMC_CLK_ENABLE() do { \ __IO uint32_t tmpreg; \ SET_BIT(RCC->AHB3ENR, RCC_AHB3ENR_FMCEN);\ /* Delay after an RCC peripheral clock enabling */ \ tmpreg = READ_BIT(RCC->AHB3ENR, RCC_AHB3ENR_FMCEN);\ UNUSED(tmpreg); \ } while(0) #define __HAL_RCC_QSPI_CLK_ENABLE() do { \ __IO uint32_t tmpreg; \ SET_BIT(RCC->AHB3ENR, RCC_AHB3ENR_QSPIEN);\ /* Delay after an RCC peripheral clock enabling */ \ tmpreg = READ_BIT(RCC->AHB3ENR, RCC_AHB3ENR_QSPIEN);\ UNUSED(tmpreg); \ } while(0) #define __HAL_RCC_FMC_CLK_DISABLE() (RCC->AHB3ENR &= ~(RCC_AHB3ENR_FMCEN)) #define __HAL_RCC_QSPI_CLK_DISABLE() (RCC->AHB3ENR &= ~(RCC_AHB3ENR_QSPIEN)) /** * @} */ /** @defgroup RCCEx_APB1_Clock_Enable_Disable APB1 Peripheral Clock Enable Disable * @brief Enable or disable the Low Speed APB (APB1) peripheral clock. * @note After reset, the peripheral clock (used for registers read/write access) * is disabled and the application software has to enable this clock before * using it. */ #define __HAL_RCC_TIM6_CLK_ENABLE() do { \ __IO uint32_t tmpreg; \ SET_BIT(RCC->APB1ENR, RCC_APB1ENR_TIM6EN);\ /* Delay after an RCC peripheral clock enabling */ \ tmpreg = READ_BIT(RCC->APB1ENR, RCC_APB1ENR_TIM6EN);\ UNUSED(tmpreg); \ } while(0) #define __HAL_RCC_TIM7_CLK_ENABLE() do { \ __IO uint32_t tmpreg; \ SET_BIT(RCC->APB1ENR, RCC_APB1ENR_TIM7EN);\ /* Delay after an RCC peripheral clock enabling */ \ tmpreg = READ_BIT(RCC->APB1ENR, RCC_APB1ENR_TIM7EN);\ UNUSED(tmpreg); \ } while(0) #define __HAL_RCC_TIM12_CLK_ENABLE() do { \ __IO uint32_t tmpreg; \ SET_BIT(RCC->APB1ENR, RCC_APB1ENR_TIM12EN);\ /* Delay after an RCC peripheral clock enabling */ \ tmpreg = READ_BIT(RCC->APB1ENR, RCC_APB1ENR_TIM12EN);\ UNUSED(tmpreg); \ } while(0) #define __HAL_RCC_TIM13_CLK_ENABLE() do { \ __IO uint32_t tmpreg; \ SET_BIT(RCC->APB1ENR, RCC_APB1ENR_TIM13EN);\ /* Delay after an RCC peripheral clock enabling */ \ tmpreg = READ_BIT(RCC->APB1ENR, RCC_APB1ENR_TIM13EN);\ UNUSED(tmpreg); \ } while(0) #define __HAL_RCC_TIM14_CLK_ENABLE() do { \ __IO uint32_t tmpreg; \ SET_BIT(RCC->APB1ENR, RCC_APB1ENR_TIM14EN);\ /* Delay after an RCC peripheral clock enabling */ \ tmpreg = READ_BIT(RCC->APB1ENR, RCC_APB1ENR_TIM14EN);\ UNUSED(tmpreg); \ } while(0) #define __HAL_RCC_SPDIFRX_CLK_ENABLE() do { \ __IO uint32_t tmpreg; \ SET_BIT(RCC->APB1ENR, RCC_APB1ENR_SPDIFRXEN);\ /* Delay after an RCC peripheral clock enabling */ \ tmpreg = READ_BIT(RCC->APB1ENR, RCC_APB1ENR_SPDIFRXEN);\ UNUSED(tmpreg); \ } while(0) #define __HAL_RCC_USART3_CLK_ENABLE() do { \ __IO uint32_t tmpreg; \ SET_BIT(RCC->APB1ENR, RCC_APB1ENR_USART3EN);\ /* Delay after an RCC peripheral clock enabling */ \ tmpreg = READ_BIT(RCC->APB1ENR, RCC_APB1ENR_USART3EN);\ UNUSED(tmpreg); \ } while(0) #define __HAL_RCC_UART4_CLK_ENABLE() do { \ __IO uint32_t tmpreg; \ SET_BIT(RCC->APB1ENR, RCC_APB1ENR_UART4EN);\ /* Delay after an RCC peripheral clock enabling */ \ tmpreg = READ_BIT(RCC->APB1ENR, RCC_APB1ENR_UART4EN);\ UNUSED(tmpreg); \ } while(0) #define __HAL_RCC_UART5_CLK_ENABLE() do { \ __IO uint32_t tmpreg; \ SET_BIT(RCC->APB1ENR, RCC_APB1ENR_UART5EN);\ /* Delay after an RCC peripheral clock enabling */ \ tmpreg = READ_BIT(RCC->APB1ENR, RCC_APB1ENR_UART5EN);\ UNUSED(tmpreg); \ } while(0) #define __HAL_RCC_FMPI2C1_CLK_ENABLE() do { \ __IO uint32_t tmpreg; \ SET_BIT(RCC->APB1ENR, RCC_APB1ENR_FMPI2C1EN);\ /* Delay after an RCC peripheral clock enabling */ \ tmpreg = READ_BIT(RCC->APB1ENR, RCC_APB1ENR_FMPI2C1EN);\ UNUSED(tmpreg); \ } while(0) #define __HAL_RCC_CAN1_CLK_ENABLE() do { \ __IO uint32_t tmpreg; \ SET_BIT(RCC->APB1ENR, RCC_APB1ENR_CAN1EN);\ /* Delay after an RCC peripheral clock enabling */ \ tmpreg = READ_BIT(RCC->APB1ENR, RCC_APB1ENR_CAN1EN);\ UNUSED(tmpreg); \ } while(0) #define __HAL_RCC_CAN2_CLK_ENABLE() do { \ __IO uint32_t tmpreg; \ SET_BIT(RCC->APB1ENR, RCC_APB1ENR_CAN2EN);\ /* Delay after an RCC peripheral clock enabling */ \ tmpreg = READ_BIT(RCC->APB1ENR, RCC_APB1ENR_CAN2EN);\ UNUSED(tmpreg); \ } while(0) #define __HAL_RCC_CEC_CLK_ENABLE() do { \ __IO uint32_t tmpreg; \ SET_BIT(RCC->APB1ENR, RCC_APB1ENR_CECEN);\ /* Delay after an RCC peripheral clock enabling */ \ tmpreg = READ_BIT(RCC->APB1ENR, RCC_APB1ENR_CECEN);\ UNUSED(tmpreg); \ } while(0) #define __HAL_RCC_DAC_CLK_ENABLE() do { \ __IO uint32_t tmpreg; \ SET_BIT(RCC->APB1ENR, RCC_APB1ENR_DACEN);\ /* Delay after an RCC peripheral clock enabling */ \ tmpreg = READ_BIT(RCC->APB1ENR, RCC_APB1ENR_DACEN);\ UNUSED(tmpreg); \ } while(0) #define __HAL_RCC_TIM2_CLK_ENABLE() do { \ __IO uint32_t tmpreg; \ SET_BIT(RCC->APB1ENR, RCC_APB1ENR_TIM2EN);\ /* Delay after an RCC peripheral clock enabling */ \ tmpreg = READ_BIT(RCC->APB1ENR, RCC_APB1ENR_TIM2EN);\ UNUSED(tmpreg); \ } while(0) #define __HAL_RCC_TIM3_CLK_ENABLE() do { \ __IO uint32_t tmpreg; \ SET_BIT(RCC->APB1ENR, RCC_APB1ENR_TIM3EN);\ /* Delay after an RCC peripheral clock enabling */ \ tmpreg = READ_BIT(RCC->APB1ENR, RCC_APB1ENR_TIM3EN);\ UNUSED(tmpreg); \ } while(0) #define __HAL_RCC_TIM4_CLK_ENABLE() do { \ __IO uint32_t tmpreg; \ SET_BIT(RCC->APB1ENR, RCC_APB1ENR_TIM4EN);\ /* Delay after an RCC peripheral clock enabling */ \ tmpreg = READ_BIT(RCC->APB1ENR, RCC_APB1ENR_TIM4EN);\ UNUSED(tmpreg); \ } while(0) #define __HAL_RCC_SPI3_CLK_ENABLE() do { \ __IO uint32_t tmpreg; \ SET_BIT(RCC->APB1ENR, RCC_APB1ENR_SPI3EN);\ /* Delay after an RCC peripheral clock enabling */ \ tmpreg = READ_BIT(RCC->APB1ENR, RCC_APB1ENR_SPI3EN);\ UNUSED(tmpreg); \ } while(0) #define __HAL_RCC_I2C3_CLK_ENABLE() do { \ __IO uint32_t tmpreg; \ SET_BIT(RCC->APB1ENR, RCC_APB1ENR_I2C3EN);\ /* Delay after an RCC peripheral clock enabling */ \ tmpreg = READ_BIT(RCC->APB1ENR, RCC_APB1ENR_I2C3EN);\ UNUSED(tmpreg); \ } while(0) #define __HAL_RCC_TIM2_CLK_DISABLE() (RCC->APB1ENR &= ~(RCC_APB1ENR_TIM2EN)) #define __HAL_RCC_TIM3_CLK_DISABLE() (RCC->APB1ENR &= ~(RCC_APB1ENR_TIM3EN)) #define __HAL_RCC_TIM4_CLK_DISABLE() (RCC->APB1ENR &= ~(RCC_APB1ENR_TIM4EN)) #define __HAL_RCC_SPI3_CLK_DISABLE() (RCC->APB1ENR &= ~(RCC_APB1ENR_SPI3EN)) #define __HAL_RCC_I2C3_CLK_DISABLE() (RCC->APB1ENR &= ~(RCC_APB1ENR_I2C3EN)) #define __HAL_RCC_TIM6_CLK_DISABLE() (RCC->APB1ENR &= ~(RCC_APB1ENR_TIM6EN)) #define __HAL_RCC_TIM7_CLK_DISABLE() (RCC->APB1ENR &= ~(RCC_APB1ENR_TIM7EN)) #define __HAL_RCC_TIM12_CLK_DISABLE() (RCC->APB1ENR &= ~(RCC_APB1ENR_TIM12EN)) #define __HAL_RCC_TIM13_CLK_DISABLE() (RCC->APB1ENR &= ~(RCC_APB1ENR_TIM13EN)) #define __HAL_RCC_TIM14_CLK_DISABLE() (RCC->APB1ENR &= ~(RCC_APB1ENR_TIM14EN)) #define __HAL_RCC_SPDIFRX_CLK_DISABLE() (RCC->APB1ENR &= ~(RCC_APB1ENR_SPDIFRXEN)) #define __HAL_RCC_USART3_CLK_DISABLE() (RCC->APB1ENR &= ~(RCC_APB1ENR_USART3EN)) #define __HAL_RCC_UART4_CLK_DISABLE() (RCC->APB1ENR &= ~(RCC_APB1ENR_UART4EN)) #define __HAL_RCC_UART5_CLK_DISABLE() (RCC->APB1ENR &= ~(RCC_APB1ENR_UART5EN)) #define __HAL_RCC_FMPI2C1_CLK_DISABLE() (RCC->APB1ENR &= ~(RCC_APB1ENR_FMPI2C1EN)) #define __HAL_RCC_CAN1_CLK_DISABLE() (RCC->APB1ENR &= ~(RCC_APB1ENR_CAN1EN)) #define __HAL_RCC_CAN2_CLK_DISABLE() (RCC->APB1ENR &= ~(RCC_APB1ENR_CAN2EN)) #define __HAL_RCC_CEC_CLK_DISABLE() (RCC->APB1ENR &= ~(RCC_APB1ENR_CECEN)) #define __HAL_RCC_DAC_CLK_DISABLE() (RCC->APB1ENR &= ~(RCC_APB1ENR_DACEN)) /** * @} */ /** @defgroup RCCEx_APB2_Clock_Enable_Disable APB2 Peripheral Clock Enable Disable * @brief Enable or disable the High Speed APB (APB2) peripheral clock. * @note After reset, the peripheral clock (used for registers read/write access) * is disabled and the application software has to enable this clock before * using it. */ #define __HAL_RCC_TIM8_CLK_ENABLE() do { \ __IO uint32_t tmpreg; \ SET_BIT(RCC->APB2ENR, RCC_APB2ENR_TIM8EN);\ /* Delay after an RCC peripheral clock enabling */ \ tmpreg = READ_BIT(RCC->APB2ENR, RCC_APB2ENR_TIM8EN);\ UNUSED(tmpreg); \ } while(0) #define __HAL_RCC_ADC2_CLK_ENABLE() do { \ __IO uint32_t tmpreg; \ SET_BIT(RCC->APB2ENR, RCC_APB2ENR_ADC2EN);\ /* Delay after an RCC peripheral clock enabling */ \ tmpreg = READ_BIT(RCC->APB2ENR, RCC_APB2ENR_ADC2EN);\ UNUSED(tmpreg); \ } while(0) #define __HAL_RCC_ADC3_CLK_ENABLE() do { \ __IO uint32_t tmpreg; \ SET_BIT(RCC->APB2ENR, RCC_APB2ENR_ADC3EN);\ /* Delay after an RCC peripheral clock enabling */ \ tmpreg = READ_BIT(RCC->APB2ENR, RCC_APB2ENR_ADC3EN);\ UNUSED(tmpreg); \ } while(0) #define __HAL_RCC_SAI1_CLK_ENABLE() do { \ __IO uint32_t tmpreg; \ SET_BIT(RCC->APB2ENR, RCC_APB2ENR_SAI1EN);\ /* Delay after an RCC peripheral clock enabling */ \ tmpreg = READ_BIT(RCC->APB2ENR, RCC_APB2ENR_SAI1EN);\ UNUSED(tmpreg); \ } while(0) #define __HAL_RCC_SAI2_CLK_ENABLE() do { \ __IO uint32_t tmpreg; \ SET_BIT(RCC->APB2ENR, RCC_APB2ENR_SAI2EN);\ /* Delay after an RCC peripheral clock enabling */ \ tmpreg = READ_BIT(RCC->APB2ENR, RCC_APB2ENR_SAI2EN);\ UNUSED(tmpreg); \ } while(0) #define __HAL_RCC_SDIO_CLK_ENABLE() do { \ __IO uint32_t tmpreg; \ SET_BIT(RCC->APB2ENR, RCC_APB2ENR_SDIOEN);\ /* Delay after an RCC peripheral clock enabling */ \ tmpreg = READ_BIT(RCC->APB2ENR, RCC_APB2ENR_SDIOEN);\ UNUSED(tmpreg); \ } while(0) #define __HAL_RCC_SPI4_CLK_ENABLE() do { \ __IO uint32_t tmpreg; \ SET_BIT(RCC->APB2ENR, RCC_APB2ENR_SPI4EN);\ /* Delay after an RCC peripheral clock enabling */ \ tmpreg = READ_BIT(RCC->APB2ENR, RCC_APB2ENR_SPI4EN);\ UNUSED(tmpreg); \ } while(0) #define __HAL_RCC_TIM10_CLK_ENABLE() do { \ __IO uint32_t tmpreg; \ SET_BIT(RCC->APB2ENR, RCC_APB2ENR_TIM10EN);\ /* Delay after an RCC peripheral clock enabling */ \ tmpreg = READ_BIT(RCC->APB2ENR, RCC_APB2ENR_TIM10EN);\ UNUSED(tmpreg); \ } while(0) #define __HAL_RCC_SDIO_CLK_DISABLE() (RCC->APB2ENR &= ~(RCC_APB2ENR_SDIOEN)) #define __HAL_RCC_SPI4_CLK_DISABLE() (RCC->APB2ENR &= ~(RCC_APB2ENR_SPI4EN)) #define __HAL_RCC_TIM10_CLK_DISABLE() (RCC->APB2ENR &= ~(RCC_APB2ENR_TIM10EN)) #define __HAL_RCC_TIM8_CLK_DISABLE() (RCC->APB2ENR &= ~(RCC_APB2ENR_TIM8EN)) #define __HAL_RCC_ADC2_CLK_DISABLE() (RCC->APB2ENR &= ~(RCC_APB2ENR_ADC2EN)) #define __HAL_RCC_ADC3_CLK_DISABLE() (RCC->APB2ENR &= ~(RCC_APB2ENR_ADC3EN)) #define __HAL_RCC_SAI1_CLK_DISABLE() (RCC->APB2ENR &= ~(RCC_APB2ENR_SAI1EN)) #define __HAL_RCC_SAI2_CLK_DISABLE() (RCC->APB2ENR &= ~(RCC_APB2ENR_SAI2EN)) /** * @} */ /** @defgroup RCCEx_AHB1_Force_Release_Reset AHB1 Force Release Reset * @brief Force or release AHB1 peripheral reset. */ #define __HAL_RCC_GPIOD_FORCE_RESET() (RCC->AHB1RSTR |= (RCC_AHB1RSTR_GPIODRST)) #define __HAL_RCC_GPIOE_FORCE_RESET() (RCC->AHB1RSTR |= (RCC_AHB1RSTR_GPIOERST)) #define __HAL_RCC_GPIOF_FORCE_RESET() (RCC->AHB1RSTR |= (RCC_AHB1RSTR_GPIOFRST)) #define __HAL_RCC_GPIOG_FORCE_RESET() (RCC->AHB1RSTR |= (RCC_AHB1RSTR_GPIOGRST)) #define __HAL_RCC_USB_OTG_HS_FORCE_RESET() (RCC->AHB1RSTR |= (RCC_AHB1RSTR_OTGHRST)) #define __HAL_RCC_CRC_FORCE_RESET() (RCC->AHB1RSTR |= (RCC_AHB1RSTR_CRCRST)) #define __HAL_RCC_GPIOD_RELEASE_RESET() (RCC->AHB1RSTR &= ~(RCC_AHB1RSTR_GPIODRST)) #define __HAL_RCC_GPIOE_RELEASE_RESET() (RCC->AHB1RSTR &= ~(RCC_AHB1RSTR_GPIOERST)) #define __HAL_RCC_GPIOF_RELEASE_RESET() (RCC->AHB1RSTR &= ~(RCC_AHB1RSTR_GPIOFRST)) #define __HAL_RCC_GPIOG_RELEASE_RESET() (RCC->AHB1RSTR &= ~(RCC_AHB1RSTR_GPIOGRST)) #define __HAL_RCC_USB_OTG_HS_RELEASE_RESET() (RCC->AHB1RSTR &= ~(RCC_AHB1RSTR_OTGHRST)) #define __HAL_RCC_CRC_RELEASE_RESET() (RCC->AHB1RSTR &= ~(RCC_AHB1RSTR_CRCRST)) /** * @} */ /** @defgroup RCCEx_AHB2_Force_Release_Reset AHB2 Force Release Reset * @brief Force or release AHB2 peripheral reset. * @{ */ #define __HAL_RCC_AHB2_FORCE_RESET() (RCC->AHB2RSTR = 0xFFFFFFFF) #define __HAL_RCC_USB_OTG_FS_FORCE_RESET() (RCC->AHB2RSTR |= (RCC_AHB2RSTR_OTGFSRST)) #define __HAL_RCC_RNG_FORCE_RESET() (RCC->AHB2RSTR |= (RCC_AHB2RSTR_RNGRST)) #define __HAL_RCC_DCMI_FORCE_RESET() (RCC->AHB2RSTR |= (RCC_AHB2RSTR_DCMIRST)) #define __HAL_RCC_AHB2_RELEASE_RESET() (RCC->AHB2RSTR = 0x00) #define __HAL_RCC_USB_OTG_FS_RELEASE_RESET() (RCC->AHB2RSTR &= ~(RCC_AHB2RSTR_OTGFSRST)) #define __HAL_RCC_RNG_RELEASE_RESET() (RCC->AHB2RSTR &= ~(RCC_AHB2RSTR_RNGRST)) #define __HAL_RCC_DCMI_RELEASE_RESET() (RCC->AHB2RSTR &= ~(RCC_AHB2RSTR_DCMIRST)) /** * @} */ /** @defgroup RCCEx_AHB3_Force_Release_Reset AHB3 Force Release Reset * @brief Force or release AHB3 peripheral reset. * @{ */ #define __HAL_RCC_AHB3_FORCE_RESET() (RCC->AHB3RSTR = 0xFFFFFFFF) #define __HAL_RCC_AHB3_RELEASE_RESET() (RCC->AHB3RSTR = 0x00) #define __HAL_RCC_FMC_FORCE_RESET() (RCC->AHB3RSTR |= (RCC_AHB3RSTR_FMCRST)) #define __HAL_RCC_QSPI_FORCE_RESET() (RCC->AHB3RSTR |= (RCC_AHB3RSTR_QSPIRST)) #define __HAL_RCC_FMC_RELEASE_RESET() (RCC->AHB3RSTR &= ~(RCC_AHB3RSTR_FMCRST)) #define __HAL_RCC_QSPI_RELEASE_RESET() (RCC->AHB3RSTR &= ~(RCC_AHB3RSTR_QSPIRST)) /** * @} */ /** @defgroup RCCEx_APB1_Force_Release_Reset APB1 Force Release Reset * @brief Force or release APB1 peripheral reset. */ #define __HAL_RCC_TIM6_FORCE_RESET() (RCC->APB1RSTR |= (RCC_APB1RSTR_TIM6RST)) #define __HAL_RCC_TIM7_FORCE_RESET() (RCC->APB1RSTR |= (RCC_APB1RSTR_TIM7RST)) #define __HAL_RCC_TIM12_FORCE_RESET() (RCC->APB1RSTR |= (RCC_APB1RSTR_TIM12RST)) #define __HAL_RCC_TIM13_FORCE_RESET() (RCC->APB1RSTR |= (RCC_APB1RSTR_TIM13RST)) #define __HAL_RCC_TIM14_FORCE_RESET() (RCC->APB1RSTR |= (RCC_APB1RSTR_TIM14RST)) #define __HAL_RCC_SPDIFRX_FORCE_RESET() (RCC->APB1RSTR |= (RCC_APB1RSTR_SPDIFRXRST)) #define __HAL_RCC_USART3_FORCE_RESET() (RCC->APB1RSTR |= (RCC_APB1RSTR_USART3RST)) #define __HAL_RCC_UART4_FORCE_RESET() (RCC->APB1RSTR |= (RCC_APB1RSTR_UART4RST)) #define __HAL_RCC_UART5_FORCE_RESET() (RCC->APB1RSTR |= (RCC_APB1RSTR_UART5RST)) #define __HAL_RCC_FMPI2C1_FORCE_RESET() (RCC->APB1RSTR |= (RCC_APB1RSTR_FMPI2C1RST)) #define __HAL_RCC_CAN1_FORCE_RESET() (RCC->APB1RSTR |= (RCC_APB1RSTR_CAN1RST)) #define __HAL_RCC_CAN2_FORCE_RESET() (RCC->APB1RSTR |= (RCC_APB1RSTR_CAN2RST)) #define __HAL_RCC_CEC_FORCE_RESET() (RCC->APB1RSTR |= (RCC_APB1RSTR_CECRST)) #define __HAL_RCC_DAC_FORCE_RESET() (RCC->APB1RSTR |= (RCC_APB1RSTR_DACRST)) #define __HAL_RCC_TIM2_FORCE_RESET() (RCC->APB1RSTR |= (RCC_APB1RSTR_TIM2RST)) #define __HAL_RCC_TIM3_FORCE_RESET() (RCC->APB1RSTR |= (RCC_APB1RSTR_TIM3RST)) #define __HAL_RCC_TIM4_FORCE_RESET() (RCC->APB1RSTR |= (RCC_APB1RSTR_TIM4RST)) #define __HAL_RCC_SPI3_FORCE_RESET() (RCC->APB1RSTR |= (RCC_APB1RSTR_SPI3RST)) #define __HAL_RCC_I2C3_FORCE_RESET() (RCC->APB1RSTR |= (RCC_APB1RSTR_I2C3RST)) #define __HAL_RCC_TIM2_RELEASE_RESET() (RCC->APB1RSTR &= ~(RCC_APB1RSTR_TIM2RST)) #define __HAL_RCC_TIM3_RELEASE_RESET() (RCC->APB1RSTR &= ~(RCC_APB1RSTR_TIM3RST)) #define __HAL_RCC_TIM4_RELEASE_RESET() (RCC->APB1RSTR &= ~(RCC_APB1RSTR_TIM4RST)) #define __HAL_RCC_SPI3_RELEASE_RESET() (RCC->APB1RSTR &= ~(RCC_APB1RSTR_SPI3RST)) #define __HAL_RCC_I2C3_RELEASE_RESET() (RCC->APB1RSTR &= ~(RCC_APB1RSTR_I2C3RST)) #define __HAL_RCC_TIM6_RELEASE_RESET() (RCC->APB1RSTR &= ~(RCC_APB1RSTR_TIM6RST)) #define __HAL_RCC_TIM7_RELEASE_RESET() (RCC->APB1RSTR &= ~(RCC_APB1RSTR_TIM7RST)) #define __HAL_RCC_TIM12_RELEASE_RESET() (RCC->APB1RSTR &= ~(RCC_APB1RSTR_TIM12RST)) #define __HAL_RCC_TIM13_RELEASE_RESET() (RCC->APB1RSTR &= ~(RCC_APB1RSTR_TIM13RST)) #define __HAL_RCC_TIM14_RELEASE_RESET() (RCC->APB1RSTR &= ~(RCC_APB1RSTR_TIM14RST)) #define __HAL_RCC_SPDIFRX_RELEASE_RESET() (RCC->APB1RSTR &= ~(RCC_APB1RSTR_SPDIFRXRST)) #define __HAL_RCC_USART3_RELEASE_RESET() (RCC->APB1RSTR &= ~(RCC_APB1RSTR_USART3RST)) #define __HAL_RCC_UART4_RELEASE_RESET() (RCC->APB1RSTR &= ~(RCC_APB1RSTR_UART4RST)) #define __HAL_RCC_UART5_RELEASE_RESET() (RCC->APB1RSTR &= ~(RCC_APB1RSTR_UART5RST)) #define __HAL_RCC_FMPI2C1_RELEASE_RESET() (RCC->APB1RSTR &= ~(RCC_APB1RSTR_FMPI2C1RST)) #define __HAL_RCC_CAN1_RELEASE_RESET() (RCC->APB1RSTR &= ~(RCC_APB1RSTR_CAN1RST)) #define __HAL_RCC_CAN2_RELEASE_RESET() (RCC->APB1RSTR &= ~(RCC_APB1RSTR_CAN2RST)) #define __HAL_RCC_CEC_RELEASE_RESET() (RCC->APB1RSTR &= ~(RCC_APB1RSTR_CECRST)) #define __HAL_RCC_DAC_RELEASE_RESET() (RCC->APB1RSTR &= ~(RCC_APB1RSTR_DACRST)) /** * @} */ /** @defgroup RCCEx_APB2_Force_Release_Reset APB2 Force Release Reset * @brief Force or release APB2 peripheral reset. */ #define __HAL_RCC_TIM8_FORCE_RESET() (RCC->APB2RSTR |= (RCC_APB2RSTR_TIM8RST)) #define __HAL_RCC_SAI1_FORCE_RESET() (RCC->APB2RSTR |= (RCC_APB2RSTR_SAI1RST)) #define __HAL_RCC_SAI2_FORCE_RESET() (RCC->APB2RSTR |= (RCC_APB2RSTR_SAI2RST)) #define __HAL_RCC_SDIO_FORCE_RESET() (RCC->APB2RSTR |= (RCC_APB2RSTR_SDIORST)) #define __HAL_RCC_SPI4_FORCE_RESET() (RCC->APB2RSTR |= (RCC_APB2RSTR_SPI4RST)) #define __HAL_RCC_TIM10_FORCE_RESET() (RCC->APB2RSTR |= (RCC_APB2RSTR_TIM10RST)) #define __HAL_RCC_SDIO_RELEASE_RESET() (RCC->APB2RSTR &= ~(RCC_APB2RSTR_SDIORST)) #define __HAL_RCC_SPI4_RELEASE_RESET() (RCC->APB2RSTR &= ~(RCC_APB2RSTR_SPI4RST)) #define __HAL_RCC_TIM10_RELEASE_RESET() (RCC->APB2RSTR &= ~(RCC_APB2RSTR_TIM10RST)) #define __HAL_RCC_TIM8_RELEASE_RESET() (RCC->APB2RSTR &= ~(RCC_APB2RSTR_TIM8RST)) #define __HAL_RCC_SAI1_RELEASE_RESET() (RCC->APB2RSTR &= ~(RCC_APB2RSTR_SAI1RST)) #define __HAL_RCC_SAI2_RELEASE_RESET() (RCC->APB2RSTR &= ~(RCC_APB2RSTR_SAI2RST)) /** * @} */ /** @defgroup RCCEx_AHB1_LowPower_Enable_Disable AHB1 Peripheral Low Power Enable Disable * @brief Enable or disable the AHB1 peripheral clock during Low Power (Sleep) mode. * @note Peripheral clock gating in SLEEP mode can be used to further reduce * power consumption. * @note After wakeup from SLEEP mode, the peripheral clock is enabled again. * @note By default, all peripheral clocks are enabled during SLEEP mode. */ #define __HAL_RCC_GPIOD_CLK_SLEEP_ENABLE() (RCC->AHB1LPENR |= (RCC_AHB1LPENR_GPIODLPEN)) #define __HAL_RCC_GPIOE_CLK_SLEEP_ENABLE() (RCC->AHB1LPENR |= (RCC_AHB1LPENR_GPIOELPEN)) #define __HAL_RCC_GPIOF_CLK_SLEEP_ENABLE() (RCC->AHB1LPENR |= (RCC_AHB1LPENR_GPIOFLPEN)) #define __HAL_RCC_GPIOG_CLK_SLEEP_ENABLE() (RCC->AHB1LPENR |= (RCC_AHB1LPENR_GPIOGLPEN)) #define __HAL_RCC_SRAM2_CLK_SLEEP_ENABLE() (RCC->AHB1LPENR |= (RCC_AHB1LPENR_SRAM2LPEN)) #define __HAL_RCC_USB_OTG_HS_CLK_SLEEP_ENABLE() (RCC->AHB1LPENR |= (RCC_AHB1LPENR_OTGHSLPEN)) #define __HAL_RCC_USB_OTG_HS_ULPI_CLK_SLEEP_ENABLE() (RCC->AHB1LPENR |= (RCC_AHB1LPENR_OTGHSULPILPEN)) #define __HAL_RCC_CRC_CLK_SLEEP_ENABLE() (RCC->AHB1LPENR |= (RCC_AHB1LPENR_CRCLPEN)) #define __HAL_RCC_FLITF_CLK_SLEEP_ENABLE() (RCC->AHB1LPENR |= (RCC_AHB1LPENR_FLITFLPEN)) #define __HAL_RCC_SRAM1_CLK_SLEEP_ENABLE() (RCC->AHB1LPENR |= (RCC_AHB1LPENR_SRAM1LPEN)) #define __HAL_RCC_BKPSRAM_CLK_SLEEP_ENABLE() (RCC->AHB1LPENR |= (RCC_AHB1LPENR_BKPSRAMLPEN)) #define __HAL_RCC_GPIOD_CLK_SLEEP_DISABLE() (RCC->AHB1LPENR &= ~(RCC_AHB1LPENR_GPIODLPEN)) #define __HAL_RCC_GPIOE_CLK_SLEEP_DISABLE() (RCC->AHB1LPENR &= ~(RCC_AHB1LPENR_GPIOELPEN)) #define __HAL_RCC_GPIOF_CLK_SLEEP_DISABLE() (RCC->AHB1LPENR &= ~(RCC_AHB1LPENR_GPIOFLPEN)) #define __HAL_RCC_GPIOG_CLK_SLEEP_DISABLE() (RCC->AHB1LPENR &= ~(RCC_AHB1LPENR_GPIOGLPEN)) #define __HAL_RCC_SRAM2_CLK_SLEEP_DISABLE() (RCC->AHB1LPENR &= ~(RCC_AHB1LPENR_SRAM2LPEN)) #define __HAL_RCC_USB_OTG_HS_CLK_SLEEP_DISABLE() (RCC->AHB1LPENR &= ~(RCC_AHB1LPENR_OTGHSLPEN)) #define __HAL_RCC_USB_OTG_HS_ULPI_CLK_SLEEP_DISABLE() (RCC->AHB1LPENR &= ~(RCC_AHB1LPENR_OTGHSULPILPEN)) #define __HAL_RCC_CRC_CLK_SLEEP_DISABLE() (RCC->AHB1LPENR &= ~(RCC_AHB1LPENR_CRCLPEN)) #define __HAL_RCC_FLITF_CLK_SLEEP_DISABLE() (RCC->AHB1LPENR &= ~(RCC_AHB1LPENR_FLITFLPEN)) #define __HAL_RCC_SRAM1_CLK_SLEEP_DISABLE() (RCC->AHB1LPENR &= ~(RCC_AHB1LPENR_SRAM1LPEN)) #define __HAL_RCC_BKPSRAM_CLK_SLEEP_DISABLE() (RCC->AHB1LPENR &= ~(RCC_AHB1LPENR_BKPSRAMLPEN)) /** * @} */ /** @defgroup RCCEx_AHB2_LowPower_Enable_Disable AHB2 Peripheral Low Power Enable Disable * @brief Enable or disable the AHB2 peripheral clock during Low Power (Sleep) mode. * @note Peripheral clock gating in SLEEP mode can be used to further reduce * power consumption. * @note After wake-up from SLEEP mode, the peripheral clock is enabled again. * @note By default, all peripheral clocks are enabled during SLEEP mode. * @{ */ #define __HAL_RCC_USB_OTG_FS_CLK_SLEEP_ENABLE() (RCC->AHB2LPENR |= (RCC_AHB2LPENR_OTGFSLPEN)) #define __HAL_RCC_USB_OTG_FS_CLK_SLEEP_DISABLE() (RCC->AHB2LPENR &= ~(RCC_AHB2LPENR_OTGFSLPEN)) #define __HAL_RCC_RNG_CLK_SLEEP_ENABLE() (RCC->AHB2LPENR |= (RCC_AHB2LPENR_RNGLPEN)) #define __HAL_RCC_RNG_CLK_SLEEP_DISABLE() (RCC->AHB2LPENR &= ~(RCC_AHB2LPENR_RNGLPEN)) #define __HAL_RCC_DCMI_CLK_SLEEP_ENABLE() (RCC->AHB2LPENR |= (RCC_AHB2LPENR_DCMILPEN)) #define __HAL_RCC_DCMI_CLK_SLEEP_DISABLE() (RCC->AHB2LPENR &= ~(RCC_AHB2LPENR_DCMILPEN)) /** * @} */ /** @defgroup RCCEx_AHB3_LowPower_Enable_Disable AHB3 Peripheral Low Power Enable Disable * @brief Enable or disable the AHB3 peripheral clock during Low Power (Sleep) mode. * @note Peripheral clock gating in SLEEP mode can be used to further reduce * power consumption. * @note After wakeup from SLEEP mode, the peripheral clock is enabled again. * @note By default, all peripheral clocks are enabled during SLEEP mode. */ #define __HAL_RCC_FMC_CLK_SLEEP_ENABLE() (RCC->AHB3LPENR |= (RCC_AHB3LPENR_FMCLPEN)) #define __HAL_RCC_QSPI_CLK_SLEEP_ENABLE() (RCC->AHB3LPENR |= (RCC_AHB3LPENR_QSPILPEN)) #define __HAL_RCC_FMC_CLK_SLEEP_DISABLE() (RCC->AHB3LPENR &= ~(RCC_AHB3LPENR_FMCLPEN)) #define __HAL_RCC_QSPI_CLK_SLEEP_DISABLE() (RCC->AHB3LPENR &= ~(RCC_AHB3LPENR_QSPILPEN)) /** * @} */ /** @defgroup RCCEx_APB1_LowPower_Enable_Disable APB1 Peripheral Low Power Enable Disable * @brief Enable or disable the APB1 peripheral clock during Low Power (Sleep) mode. * @note Peripheral clock gating in SLEEP mode can be used to further reduce * power consumption. * @note After wakeup from SLEEP mode, the peripheral clock is enabled again. * @note By default, all peripheral clocks are enabled during SLEEP mode. */ #define __HAL_RCC_TIM6_CLK_SLEEP_ENABLE() (RCC->APB1LPENR |= (RCC_APB1LPENR_TIM6LPEN)) #define __HAL_RCC_TIM7_CLK_SLEEP_ENABLE() (RCC->APB1LPENR |= (RCC_APB1LPENR_TIM7LPEN)) #define __HAL_RCC_TIM12_CLK_SLEEP_ENABLE() (RCC->APB1LPENR |= (RCC_APB1LPENR_TIM12LPEN)) #define __HAL_RCC_TIM13_CLK_SLEEP_ENABLE() (RCC->APB1LPENR |= (RCC_APB1LPENR_TIM13LPEN)) #define __HAL_RCC_TIM14_CLK_SLEEP_ENABLE() (RCC->APB1LPENR |= (RCC_APB1LPENR_TIM14LPEN)) #define __HAL_RCC_SPDIFRX_CLK_SLEEP_ENABLE() (RCC->APB1LPENR |= (RCC_APB1LPENR_SPDIFRXLPEN)) #define __HAL_RCC_USART3_CLK_SLEEP_ENABLE() (RCC->APB1LPENR |= (RCC_APB1LPENR_USART3LPEN)) #define __HAL_RCC_UART4_CLK_SLEEP_ENABLE() (RCC->APB1LPENR |= (RCC_APB1LPENR_UART4LPEN)) #define __HAL_RCC_UART5_CLK_SLEEP_ENABLE() (RCC->APB1LPENR |= (RCC_APB1LPENR_UART5LPEN)) #define __HAL_RCC_FMPI2C1_CLK_SLEEP_ENABLE() (RCC->APB1LPENR |= (RCC_APB1LPENR_FMPI2C1LPEN)) #define __HAL_RCC_CAN1_CLK_SLEEP_ENABLE() (RCC->APB1LPENR |= (RCC_APB1LPENR_CAN1LPEN)) #define __HAL_RCC_CAN2_CLK_SLEEP_ENABLE() (RCC->APB1LPENR |= (RCC_APB1LPENR_CAN2LPEN)) #define __HAL_RCC_CEC_CLK_SLEEP_ENABLE() (RCC->APB1LPENR |= (RCC_APB1LPENR_CECLPEN)) #define __HAL_RCC_DAC_CLK_SLEEP_ENABLE() (RCC->APB1LPENR |= (RCC_APB1LPENR_DACLPEN)) #define __HAL_RCC_TIM2_CLK_SLEEP_ENABLE() (RCC->APB1LPENR |= (RCC_APB1LPENR_TIM2LPEN)) #define __HAL_RCC_TIM3_CLK_SLEEP_ENABLE() (RCC->APB1LPENR |= (RCC_APB1LPENR_TIM3LPEN)) #define __HAL_RCC_TIM4_CLK_SLEEP_ENABLE() (RCC->APB1LPENR |= (RCC_APB1LPENR_TIM4LPEN)) #define __HAL_RCC_SPI3_CLK_SLEEP_ENABLE() (RCC->APB1LPENR |= (RCC_APB1LPENR_SPI3LPEN)) #define __HAL_RCC_I2C3_CLK_SLEEP_ENABLE() (RCC->APB1LPENR |= (RCC_APB1LPENR_I2C3LPEN)) #define __HAL_RCC_TIM2_CLK_SLEEP_DISABLE() (RCC->APB1LPENR &= ~(RCC_APB1LPENR_TIM2LPEN)) #define __HAL_RCC_TIM3_CLK_SLEEP_DISABLE() (RCC->APB1LPENR &= ~(RCC_APB1LPENR_TIM3LPEN)) #define __HAL_RCC_TIM4_CLK_SLEEP_DISABLE() (RCC->APB1LPENR &= ~(RCC_APB1LPENR_TIM4LPEN)) #define __HAL_RCC_SPI3_CLK_SLEEP_DISABLE() (RCC->APB1LPENR &= ~(RCC_APB1LPENR_SPI3LPEN)) #define __HAL_RCC_I2C3_CLK_SLEEP_DISABLE() (RCC->APB1LPENR &= ~(RCC_APB1LPENR_I2C3LPEN)) #define __HAL_RCC_TIM6_CLK_SLEEP_DISABLE() (RCC->APB1LPENR &= ~(RCC_APB1LPENR_TIM6LPEN)) #define __HAL_RCC_TIM7_CLK_SLEEP_DISABLE() (RCC->APB1LPENR &= ~(RCC_APB1LPENR_TIM7LPEN)) #define __HAL_RCC_TIM12_CLK_SLEEP_DISABLE() (RCC->APB1LPENR &= ~(RCC_APB1LPENR_TIM12LPEN)) #define __HAL_RCC_TIM13_CLK_SLEEP_DISABLE() (RCC->APB1LPENR &= ~(RCC_APB1LPENR_TIM13LPEN)) #define __HAL_RCC_TIM14_CLK_SLEEP_DISABLE() (RCC->APB1LPENR &= ~(RCC_APB1LPENR_TIM14LPEN)) #define __HAL_RCC_SPDIFRX_CLK_SLEEP_DISABLE()(RCC->APB1LPENR &= ~(RCC_APB1LPENR_SPDIFRXLPEN)) #define __HAL_RCC_USART3_CLK_SLEEP_DISABLE() (RCC->APB1LPENR &= ~(RCC_APB1LPENR_USART3LPEN)) #define __HAL_RCC_UART4_CLK_SLEEP_DISABLE() (RCC->APB1LPENR &= ~(RCC_APB1LPENR_UART4LPEN)) #define __HAL_RCC_UART5_CLK_SLEEP_DISABLE() (RCC->APB1LPENR &= ~(RCC_APB1LPENR_UART5LPEN)) #define __HAL_RCC_FMPI2C1_CLK_SLEEP_DISABLE()(RCC->APB1LPENR &= ~(RCC_APB1LPENR_FMPI2C1LPEN)) #define __HAL_RCC_CAN1_CLK_SLEEP_DISABLE() (RCC->APB1LPENR &= ~(RCC_APB1LPENR_CAN1LPEN)) #define __HAL_RCC_CAN2_CLK_SLEEP_DISABLE() (RCC->APB1LPENR &= ~(RCC_APB1LPENR_CAN2LPEN)) #define __HAL_RCC_CEC_CLK_SLEEP_DISABLE() (RCC->APB1LPENR &= ~(RCC_APB1LPENR_CECLPEN)) #define __HAL_RCC_DAC_CLK_SLEEP_DISABLE() (RCC->APB1LPENR &= ~(RCC_APB1LPENR_DACLPEN)) /** * @} */ /** @defgroup RCCEx_APB2_LowPower_Enable_Disable APB2 Peripheral Low Power Enable Disable * @brief Enable or disable the APB2 peripheral clock during Low Power (Sleep) mode. * @note Peripheral clock gating in SLEEP mode can be used to further reduce * power consumption. * @note After wakeup from SLEEP mode, the peripheral clock is enabled again. * @note By default, all peripheral clocks are enabled during SLEEP mode. */ #define __HAL_RCC_TIM8_CLK_SLEEP_ENABLE() (RCC->APB2LPENR |= (RCC_APB2LPENR_TIM8LPEN)) #define __HAL_RCC_ADC2_CLK_SLEEP_ENABLE() (RCC->APB2LPENR |= (RCC_APB2LPENR_ADC2LPEN)) #define __HAL_RCC_ADC3_CLK_SLEEP_ENABLE() (RCC->APB2LPENR |= (RCC_APB2LPENR_ADC3LPEN)) #define __HAL_RCC_SAI1_CLK_SLEEP_ENABLE() (RCC->APB2LPENR |= (RCC_APB2LPENR_SAI1LPEN)) #define __HAL_RCC_SAI2_CLK_SLEEP_ENABLE() (RCC->APB2LPENR |= (RCC_APB2LPENR_SAI2LPEN)) #define __HAL_RCC_SDIO_CLK_SLEEP_ENABLE() (RCC->APB2LPENR |= (RCC_APB2LPENR_SDIOLPEN)) #define __HAL_RCC_SPI4_CLK_SLEEP_ENABLE() (RCC->APB2LPENR |= (RCC_APB2LPENR_SPI4LPEN)) #define __HAL_RCC_TIM10_CLK_SLEEP_ENABLE()(RCC->APB2LPENR |= (RCC_APB2LPENR_TIM10LPEN)) #define __HAL_RCC_SDIO_CLK_SLEEP_DISABLE() (RCC->APB2LPENR &= ~(RCC_APB2LPENR_SDIOLPEN)) #define __HAL_RCC_SPI4_CLK_SLEEP_DISABLE() (RCC->APB2LPENR &= ~(RCC_APB2LPENR_SPI4LPEN)) #define __HAL_RCC_TIM10_CLK_SLEEP_DISABLE()(RCC->APB2LPENR &= ~(RCC_APB2LPENR_TIM10LPEN)) #define __HAL_RCC_TIM8_CLK_SLEEP_DISABLE() (RCC->APB2LPENR &= ~(RCC_APB2LPENR_TIM8LPEN)) #define __HAL_RCC_ADC2_CLK_SLEEP_DISABLE() (RCC->APB2LPENR &= ~(RCC_APB2LPENR_ADC2LPEN)) #define __HAL_RCC_ADC3_CLK_SLEEP_DISABLE() (RCC->APB2LPENR &= ~(RCC_APB2LPENR_ADC3LPEN)) #define __HAL_RCC_SAI1_CLK_SLEEP_DISABLE() (RCC->APB2LPENR &= ~(RCC_APB2LPENR_SAI1LPEN)) #define __HAL_RCC_SAI2_CLK_SLEEP_DISABLE() (RCC->APB2LPENR &= ~(RCC_APB2LPENR_SAI2LPEN)) /** * @} */ #endif /* STM32F446xx */ /*----------------------------------------------------------------------------*/ /*------------------------------- PLL Configuration --------------------------*/ #if defined(STM32F410Tx) || defined(STM32F410Cx) || defined(STM32F410Rx) || defined(STM32F446xx) ||\ defined(STM32F469xx) || defined(STM32F479xx) /** @brief Macro to configure the main PLL clock source, multiplication and division factors. * @note This function must be used only when the main PLL is disabled. * @param __RCC_PLLSource__: specifies the PLL entry clock source. * This parameter can be one of the following values: * @arg RCC_PLLSOURCE_HSI: HSI oscillator clock selected as PLL clock entry * @arg RCC_PLLSOURCE_HSE: HSE oscillator clock selected as PLL clock entry * @note This clock source (RCC_PLLSource) is common for the main PLL and PLLI2S. * @param __PLLM__: specifies the division factor for PLL VCO input clock * This parameter must be a number between Min_Data = 2 and Max_Data = 63. * @note You have to set the PLLM parameter correctly to ensure that the VCO input * frequency ranges from 1 to 2 MHz. It is recommended to select a frequency * of 2 MHz to limit PLL jitter. * @param __PLLN__: specifies the multiplication factor for PLL VCO output clock * This parameter must be a number between Min_Data = 192 and Max_Data = 432. * @note You have to set the PLLN parameter correctly to ensure that the VCO * output frequency is between 192 and 432 MHz. * * @param __PLLP__: specifies the division factor for main system clock (SYSCLK) * This parameter must be a number in the range {2, 4, 6, or 8}. * * @param __PLLQ__: specifies the division factor for OTG FS, SDIO and RNG clocks * This parameter must be a number between Min_Data = 2 and Max_Data = 15. * @note If the USB OTG FS is used in your application, you have to set the * PLLQ parameter correctly to have 48 MHz clock for the USB. However, * the SDIO and RNG need a frequency lower than or equal to 48 MHz to work * correctly. * * @param __PLLR__: PLL division factor for I2S, SAI, SYSTEM, SPDIFRX clocks. * This parameter must be a number between Min_Data = 2 and Max_Data = 7. * @note This parameter is only available in STM32F446xx/STM32F469xx/STM32F479xx devices. * */ #define __HAL_RCC_PLL_CONFIG(__RCC_PLLSource__, __PLLM__, __PLLN__, __PLLP__, __PLLQ__,__PLLR__) \ (RCC->PLLCFGR = ((__RCC_PLLSource__) | (__PLLM__) | \ ((__PLLN__) << POSITION_VAL(RCC_PLLCFGR_PLLN)) | \ ((((__PLLP__) >> 1) -1) << POSITION_VAL(RCC_PLLCFGR_PLLP)) | \ ((__PLLQ__) << POSITION_VAL(RCC_PLLCFGR_PLLQ)) | \ ((__PLLR__) << POSITION_VAL(RCC_PLLCFGR_PLLR)))) #else /** @brief Macro to configure the main PLL clock source, multiplication and division factors. * @note This function must be used only when the main PLL is disabled. * @param __RCC_PLLSource__: specifies the PLL entry clock source. * This parameter can be one of the following values: * @arg RCC_PLLSOURCE_HSI: HSI oscillator clock selected as PLL clock entry * @arg RCC_PLLSOURCE_HSE: HSE oscillator clock selected as PLL clock entry * @note This clock source (RCC_PLLSource) is common for the main PLL and PLLI2S. * @param __PLLM__: specifies the division factor for PLL VCO input clock * This parameter must be a number between Min_Data = 2 and Max_Data = 63. * @note You have to set the PLLM parameter correctly to ensure that the VCO input * frequency ranges from 1 to 2 MHz. It is recommended to select a frequency * of 2 MHz to limit PLL jitter. * @param __PLLN__: specifies the multiplication factor for PLL VCO output clock * This parameter must be a number between Min_Data = 192 and Max_Data = 432. * @note You have to set the PLLN parameter correctly to ensure that the VCO * output frequency is between 192 and 432 MHz. * * @param __PLLP__: specifies the division factor for main system clock (SYSCLK) * This parameter must be a number in the range {2, 4, 6, or 8}. * * @param __PLLQ__: specifies the division factor for OTG FS, SDIO and RNG clocks * This parameter must be a number between Min_Data = 2 and Max_Data = 15. * @note If the USB OTG FS is used in your application, you have to set the * PLLQ parameter correctly to have 48 MHz clock for the USB. However, * the SDIO and RNG need a frequency lower than or equal to 48 MHz to work * correctly. * */ #define __HAL_RCC_PLL_CONFIG(__RCC_PLLSource__, __PLLM__, __PLLN__, __PLLP__, __PLLQ__) \ (RCC->PLLCFGR = (0x20000000 | (__RCC_PLLSource__) | (__PLLM__)| \ ((__PLLN__) << POSITION_VAL(RCC_PLLCFGR_PLLN)) | \ ((((__PLLP__) >> 1) -1) << POSITION_VAL(RCC_PLLCFGR_PLLP)) | \ ((__PLLQ__) << POSITION_VAL(RCC_PLLCFGR_PLLQ)))) #endif /* STM32F410xx || STM32F446xx || STM32F469xx || STM32F479xx */ /*----------------------------------------------------------------------------*/ /*----------------------------PLLI2S Configuration ---------------------------*/ #if defined(STM32F405xx) || defined(STM32F415xx) || defined(STM32F407xx) || defined(STM32F417xx) || \ defined(STM32F427xx) || defined(STM32F437xx) || defined(STM32F429xx) || defined(STM32F439xx) || \ defined(STM32F401xC) || defined(STM32F401xE) || defined(STM32F411xE) || defined(STM32F446xx) || \ defined(STM32F469xx) || defined(STM32F479xx) /** @brief Macros to enable or disable the PLLI2S. * @note The PLLI2S is disabled by hardware when entering STOP and STANDBY modes. */ #define __HAL_RCC_PLLI2S_ENABLE() (*(__IO uint32_t *) RCC_CR_PLLI2SON_BB = ENABLE) #define __HAL_RCC_PLLI2S_DISABLE() (*(__IO uint32_t *) RCC_CR_PLLI2SON_BB = DISABLE) #endif /* STM32F405xx || STM32F415xx || STM32F407xx || STM32F417xx || STM32F427xx || STM32F437xx || STM32F429xx || STM32F439xx || STM32F401xC || STM32F401xE || STM32F411xE || STM32F446xx || STM32F469xx || STM32F479xx */ #if defined(STM32F446xx) /** @brief Macro to configure the PLLI2S clock multiplication and division factors . * @note This macro must be used only when the PLLI2S is disabled. * @note PLLI2S clock source is common with the main PLL (configured in * HAL_RCC_ClockConfig() API). * @param __PLLI2SM__: specifies the division factor for PLLI2S VCO input clock * This parameter must be a number between Min_Data = 2 and Max_Data = 63. * @note You have to set the PLLI2SM parameter correctly to ensure that the VCO input * frequency ranges from 1 to 2 MHz. It is recommended to select a frequency * of 1 MHz to limit PLLI2S jitter. * * @param __PLLI2SN__: specifies the multiplication factor for PLLI2S VCO output clock * This parameter must be a number between Min_Data = 192 and Max_Data = 432. * @note You have to set the PLLI2SN parameter correctly to ensure that the VCO * output frequency is between Min_Data = 192 and Max_Data = 432 MHz. * * @param __PLLI2SP__: specifies division factor for SPDIFRX Clock. * This parameter must be a number in the range {2, 4, 6, or 8}. * @note the PLLI2SP parameter is only available with STM32F446xx Devices * * @param __PLLI2SR__: specifies the division factor for I2S clock * This parameter must be a number between Min_Data = 2 and Max_Data = 7. * @note You have to set the PLLI2SR parameter correctly to not exceed 192 MHz * on the I2S clock frequency. * * @param __PLLI2SQ__: specifies the division factor for SAI clock * This parameter must be a number between Min_Data = 2 and Max_Data = 15. */ #define __HAL_RCC_PLLI2S_CONFIG(__PLLI2SM__, __PLLI2SN__, __PLLI2SP__, __PLLI2SQ__, __PLLI2SR__) \ (RCC->PLLI2SCFGR = ((__PLLI2SM__) |\ ((__PLLI2SN__) << POSITION_VAL(RCC_PLLI2SCFGR_PLLI2SN)) |\ ((((__PLLI2SP__) >> 1) -1) << POSITION_VAL(RCC_PLLI2SCFGR_PLLI2SP)) |\ ((__PLLI2SQ__) << POSITION_VAL(RCC_PLLI2SCFGR_PLLI2SQ)) |\ ((__PLLI2SR__) << POSITION_VAL(RCC_PLLI2SCFGR_PLLI2SR)))) #else /** @brief Macro to configure the PLLI2S clock multiplication and division factors . * @note This macro must be used only when the PLLI2S is disabled. * @note PLLI2S clock source is common with the main PLL (configured in * HAL_RCC_ClockConfig() API). * @param __PLLI2SN__: specifies the multiplication factor for PLLI2S VCO output clock * This parameter must be a number between Min_Data = 192 and Max_Data = 432. * @note You have to set the PLLI2SN parameter correctly to ensure that the VCO * output frequency is between Min_Data = 192 and Max_Data = 432 MHz. * * @param __PLLI2SR__: specifies the division factor for I2S clock * This parameter must be a number between Min_Data = 2 and Max_Data = 7. * @note You have to set the PLLI2SR parameter correctly to not exceed 192 MHz * on the I2S clock frequency. * */ #define __HAL_RCC_PLLI2S_CONFIG(__PLLI2SN__, __PLLI2SR__) \ (RCC->PLLI2SCFGR = (((__PLLI2SN__) << POSITION_VAL(RCC_PLLI2SCFGR_PLLI2SN)) |\ ((__PLLI2SR__) << POSITION_VAL(RCC_PLLI2SCFGR_PLLI2SR)))) #endif /* STM32F446xx */ #if defined(STM32F411xE) /** @brief Macro to configure the PLLI2S clock multiplication and division factors . * @note This macro must be used only when the PLLI2S is disabled. * @note This macro must be used only when the PLLI2S is disabled. * @note PLLI2S clock source is common with the main PLL (configured in * HAL_RCC_ClockConfig() API). * @param __PLLI2SM__: specifies the division factor for PLLI2S VCO input clock * This parameter must be a number between Min_Data = 2 and Max_Data = 63. * @note The PLLI2SM parameter is only used with STM32F411xE/STM32F410xx Devices * @note You have to set the PLLI2SM parameter correctly to ensure that the VCO input * frequency ranges from 1 to 2 MHz. It is recommended to select a frequency * of 2 MHz to limit PLLI2S jitter. * @param __PLLI2SN__: specifies the multiplication factor for PLLI2S VCO output clock * This parameter must be a number between Min_Data = 192 and Max_Data = 432. * @note You have to set the PLLI2SN parameter correctly to ensure that the VCO * output frequency is between Min_Data = 192 and Max_Data = 432 MHz. * @param __PLLI2SR__: specifies the division factor for I2S clock * This parameter must be a number between Min_Data = 2 and Max_Data = 7. * @note You have to set the PLLI2SR parameter correctly to not exceed 192 MHz * on the I2S clock frequency. */ #define __HAL_RCC_PLLI2S_I2SCLK_CONFIG(__PLLI2SM__, __PLLI2SN__, __PLLI2SR__) (RCC->PLLI2SCFGR = ((__PLLI2SM__) |\ ((__PLLI2SN__) << POSITION_VAL(RCC_PLLI2SCFGR_PLLI2SN)) |\ ((__PLLI2SR__) << POSITION_VAL(RCC_PLLI2SCFGR_PLLI2SR)))) #endif /* STM32F411xE */ #if defined(STM32F427xx) || defined(STM32F437xx) || defined(STM32F429xx) || defined(STM32F439xx) || defined(STM32F469xx) || defined(STM32F479xx) /** @brief Macro used by the SAI HAL driver to configure the PLLI2S clock multiplication and division factors. * @note This macro must be used only when the PLLI2S is disabled. * @note PLLI2S clock source is common with the main PLL (configured in * HAL_RCC_ClockConfig() API) * @param __PLLI2SN__: specifies the multiplication factor for PLLI2S VCO output clock. * This parameter must be a number between Min_Data = 192 and Max_Data = 432. * @note You have to set the PLLI2SN parameter correctly to ensure that the VCO * output frequency is between Min_Data = 192 and Max_Data = 432 MHz. * @param __PLLI2SQ__: specifies the division factor for SAI1 clock. * This parameter must be a number between Min_Data = 2 and Max_Data = 15. * @note the PLLI2SQ parameter is only available with STM32F427xx/437xx/429xx/439xx/469xx/479xx * Devices and can be configured using the __HAL_RCC_PLLI2S_PLLSAICLK_CONFIG() macro * @param __PLLI2SR__: specifies the division factor for I2S clock * This parameter must be a number between Min_Data = 2 and Max_Data = 7. * @note You have to set the PLLI2SR parameter correctly to not exceed 192 MHz * on the I2S clock frequency. */ #define __HAL_RCC_PLLI2S_SAICLK_CONFIG(__PLLI2SN__, __PLLI2SQ__, __PLLI2SR__) (RCC->PLLI2SCFGR = ((__PLLI2SN__) << 6) |\ ((__PLLI2SQ__) << 24) |\ ((__PLLI2SR__) << 28)) #endif /* STM32F427xx || STM32F437xx || STM32F429xx || STM32F439xx || STM32F469xx || STM32F479xx */ /*----------------------------------------------------------------------------*/ /*------------------------------ PLLSAI Configuration ------------------------*/ #if defined(STM32F427xx) || defined(STM32F437xx) || defined(STM32F429xx) || defined(STM32F439xx) || defined(STM32F446xx) || defined(STM32F469xx) || defined(STM32F479xx) /** @brief Macros to Enable or Disable the PLLISAI. * @note The PLLSAI is only available with STM32F429x/439x Devices. * @note The PLLSAI is disabled by hardware when entering STOP and STANDBY modes. */ #define __HAL_RCC_PLLSAI_ENABLE() (*(__IO uint32_t *) RCC_CR_PLLSAION_BB = ENABLE) #define __HAL_RCC_PLLSAI_DISABLE() (*(__IO uint32_t *) RCC_CR_PLLSAION_BB = DISABLE) #if defined(STM32F446xx) /** @brief Macro to configure the PLLSAI clock multiplication and division factors. * * @param __PLLSAIM__: specifies the division factor for PLLSAI VCO input clock * This parameter must be a number between Min_Data = 2 and Max_Data = 63. * @note You have to set the PLLSAIM parameter correctly to ensure that the VCO input * frequency ranges from 1 to 2 MHz. It is recommended to select a frequency * of 1 MHz to limit PLLI2S jitter. * @note The PLLSAIM parameter is only used with STM32F446xx Devices * * @param __PLLSAIN__: specifies the multiplication factor for PLLSAI VCO output clock. * This parameter must be a number between Min_Data = 192 and Max_Data = 432. * @note You have to set the PLLSAIN parameter correctly to ensure that the VCO * output frequency is between Min_Data = 192 and Max_Data = 432 MHz. * * @param __PLLSAIP__: specifies division factor for OTG FS, SDIO and RNG clocks. * This parameter must be a number in the range {2, 4, 6, or 8}. * @note the PLLSAIP parameter is only available with STM32F446xx Devices * * @param __PLLSAIQ__: specifies the division factor for SAI clock * This parameter must be a number between Min_Data = 2 and Max_Data = 15. * * @param __PLLSAIR__: specifies the division factor for LTDC clock * This parameter must be a number between Min_Data = 2 and Max_Data = 7. * @note the PLLI2SR parameter is only available with STM32F427/437/429/439xx Devices */ #define __HAL_RCC_PLLSAI_CONFIG(__PLLSAIM__, __PLLSAIN__, __PLLSAIP__, __PLLSAIQ__, __PLLSAIR__) \ (RCC->PLLSAICFGR = ((__PLLSAIM__) | \ ((__PLLSAIN__) << POSITION_VAL(RCC_PLLSAICFGR_PLLSAIN)) | \ ((((__PLLSAIP__) >> 1) -1) << POSITION_VAL(RCC_PLLSAICFGR_PLLSAIP)) | \ ((__PLLSAIQ__) << POSITION_VAL(RCC_PLLSAICFGR_PLLSAIQ)))) #endif /* STM32F446xx */ #if defined(STM32F469xx) || defined(STM32F479xx) /** @brief Macro to configure the PLLSAI clock multiplication and division factors. * * @param __PLLSAIN__: specifies the multiplication factor for PLLSAI VCO output clock. * This parameter must be a number between Min_Data = 192 and Max_Data = 432. * @note You have to set the PLLSAIN parameter correctly to ensure that the VCO * output frequency is between Min_Data = 192 and Max_Data = 432 MHz. * * @param __PLLSAIP__: specifies division factor for SDIO and CLK48 clocks. * This parameter must be a number in the range {2, 4, 6, or 8}. * * @param __PLLSAIQ__: specifies the division factor for SAI clock * This parameter must be a number between Min_Data = 2 and Max_Data = 15. * * @param __PLLSAIR__: specifies the division factor for LTDC clock * This parameter must be a number between Min_Data = 2 and Max_Data = 7. */ #define __HAL_RCC_PLLSAI_CONFIG(__PLLSAIN__, __PLLSAIP__, __PLLSAIQ__, __PLLSAIR__) \ (RCC->PLLSAICFGR = (((__PLLSAIN__) << POSITION_VAL(RCC_PLLSAICFGR_PLLSAIN)) |\ ((((__PLLSAIP__) >> 1) -1) << POSITION_VAL(RCC_PLLSAICFGR_PLLSAIP)) |\ ((__PLLSAIQ__) << POSITION_VAL(RCC_PLLSAICFGR_PLLSAIQ)) |\ ((__PLLSAIR__) << POSITION_VAL(RCC_PLLSAICFGR_PLLSAIR)))) #endif /* STM32F469xx || STM32F479xx */ #if defined(STM32F427xx) || defined(STM32F437xx) || defined(STM32F429xx) || defined(STM32F439xx) /** @brief Macro to configure the PLLSAI clock multiplication and division factors. * * @param __PLLSAIN__: specifies the multiplication factor for PLLSAI VCO output clock. * This parameter must be a number between Min_Data = 192 and Max_Data = 432. * @note You have to set the PLLSAIN parameter correctly to ensure that the VCO * output frequency is between Min_Data = 192 and Max_Data = 432 MHz. * * @param __PLLSAIQ__: specifies the division factor for SAI clock * This parameter must be a number between Min_Data = 2 and Max_Data = 15. * * @param __PLLSAIR__: specifies the division factor for LTDC clock * This parameter must be a number between Min_Data = 2 and Max_Data = 7. * @note the PLLI2SR parameter is only available with STM32F427/437/429/439xx Devices */ #define __HAL_RCC_PLLSAI_CONFIG(__PLLSAIN__, __PLLSAIQ__, __PLLSAIR__) \ (RCC->PLLSAICFGR = (((__PLLSAIN__) << POSITION_VAL(RCC_PLLSAICFGR_PLLSAIN)) | \ ((__PLLSAIQ__) << POSITION_VAL(RCC_PLLSAICFGR_PLLSAIQ)) | \ ((__PLLSAIR__) << POSITION_VAL(RCC_PLLSAICFGR_PLLSAIR)))) #endif /* STM32F427xx || STM32F437xx || STM32F429xx || STM32F439xx */ #endif /* STM32F427xx || STM32F437xx || STM32F429xx || STM32F439xx || STM32F446xx || STM32F469xx || STM32F479xx */ /*----------------------------------------------------------------------------*/ /*------------------- PLLSAI/PLLI2S Dividers Configuration -------------------*/ #if defined(STM32F427xx) || defined(STM32F437xx) || defined(STM32F429xx) || defined(STM32F439xx) || defined(STM32F446xx) ||\ defined(STM32F469xx) || defined(STM32F479xx) /** @brief Macro to configure the SAI clock Divider coming from PLLI2S. * @note This function must be called before enabling the PLLI2S. * @param __PLLI2SDivQ__: specifies the PLLI2S division factor for SAI1 clock. * This parameter must be a number between 1 and 32. * SAI1 clock frequency = f(PLLI2SQ) / __PLLI2SDivQ__ */ #define __HAL_RCC_PLLI2S_PLLSAICLKDIVQ_CONFIG(__PLLI2SDivQ__) (MODIFY_REG(RCC->DCKCFGR, RCC_DCKCFGR_PLLI2SDIVQ, (__PLLI2SDivQ__)-1)) /** @brief Macro to configure the SAI clock Divider coming from PLLSAI. * @note This function must be called before enabling the PLLSAI. * @param __PLLSAIDivQ__: specifies the PLLSAI division factor for SAI1 clock . * This parameter must be a number between Min_Data = 1 and Max_Data = 32. * SAI1 clock frequency = f(PLLSAIQ) / __PLLSAIDivQ__ */ #define __HAL_RCC_PLLSAI_PLLSAICLKDIVQ_CONFIG(__PLLSAIDivQ__) (MODIFY_REG(RCC->DCKCFGR, RCC_DCKCFGR_PLLSAIDIVQ, ((__PLLSAIDivQ__)-1)<<8)) #endif /* STM32F427xx || STM32F437xx || STM32F429xx || STM32F439xx || STM32F446xx || STM32F469xx || STM32F479xx */ #if defined(STM32F427xx) || defined(STM32F437xx) || defined(STM32F429xx) || defined(STM32F439xx) || defined(STM32F469xx) || defined(STM32F479xx) /** @brief Macro to configure the LTDC clock Divider coming from PLLSAI. * * @note The LTDC peripheral is only available with STM32F427/437/429/439/469/479xx Devices. * @note This function must be called before enabling the PLLSAI. * @param __PLLSAIDivR__: specifies the PLLSAI division factor for LTDC clock . * This parameter must be a number between Min_Data = 2 and Max_Data = 16. * LTDC clock frequency = f(PLLSAIR) / __PLLSAIDivR__ */ #define __HAL_RCC_PLLSAI_PLLSAICLKDIVR_CONFIG(__PLLSAIDivR__) (MODIFY_REG(RCC->DCKCFGR, RCC_DCKCFGR_PLLSAIDIVR, (__PLLSAIDivR__))) #endif /* STM32F427xx || STM32F437xx || STM32F429xx || STM32F439xx || STM32F469xx || STM32F479xx */ /*----------------------------------------------------------------------------*/ /*------------------------- Peripheral Clock selection -----------------------*/ #if defined(STM32F405xx) || defined(STM32F415xx) || defined(STM32F407xx) || defined(STM32F417xx) ||\ defined(STM32F427xx) || defined(STM32F437xx) || defined(STM32F429xx) || defined(STM32F439xx) ||\ defined(STM32F401xC) || defined(STM32F401xE) || defined(STM32F411xE) || defined(STM32F469xx) ||\ defined(STM32F479xx) /** @brief Macro to configure the I2S clock source (I2SCLK). * @note This function must be called before enabling the I2S APB clock. * @param __SOURCE__: specifies the I2S clock source. * This parameter can be one of the following values: * @arg RCC_I2SCLKSOURCE_PLLI2S: PLLI2S clock used as I2S clock source. * @arg RCC_I2SCLKSOURCE_EXT: External clock mapped on the I2S_CKIN pin * used as I2S clock source. */ #define __HAL_RCC_I2S_CONFIG(__SOURCE__) (*(__IO uint32_t *) RCC_CFGR_I2SSRC_BB = (__SOURCE__)) #endif /* STM32F40xxx || STM32F41xxx || STM32F42xxx || STM32F43xxx || STM32F469xx || STM32F479xx */ #if defined(STM32F427xx) || defined(STM32F437xx) || defined(STM32F429xx) || defined(STM32F439xx) || defined(STM32F469xx) || defined(STM32F479xx) /** @brief Macro to configure SAI1BlockA clock source selection. * @note The SAI peripheral is only available with STM32F427/437/429/439/469/479xx Devices. * @note This function must be called before enabling PLLSAI, PLLI2S and * the SAI clock. * @param __SOURCE__: specifies the SAI Block A clock source. * This parameter can be one of the following values: * @arg RCC_SAIACLKSOURCE_PLLI2S: PLLI2S_Q clock divided by PLLI2SDIVQ used * as SAI1 Block A clock. * @arg RCC_SAIACLKSOURCE_PLLSAI: PLLISAI_Q clock divided by PLLSAIDIVQ used * as SAI1 Block A clock. * @arg RCC_SAIACLKSOURCE_Ext: External clock mapped on the I2S_CKIN pin * used as SAI1 Block A clock. */ #define __HAL_RCC_SAI_BLOCKACLKSOURCE_CONFIG(__SOURCE__) (MODIFY_REG(RCC->DCKCFGR, RCC_DCKCFGR_SAI1ASRC, (__SOURCE__))) /** @brief Macro to configure SAI1BlockB clock source selection. * @note The SAI peripheral is only available with STM32F427/437/429/439/469/479xx Devices. * @note This function must be called before enabling PLLSAI, PLLI2S and * the SAI clock. * @param __SOURCE__: specifies the SAI Block B clock source. * This parameter can be one of the following values: * @arg RCC_SAIBCLKSOURCE_PLLI2S: PLLI2S_Q clock divided by PLLI2SDIVQ used * as SAI1 Block B clock. * @arg RCC_SAIBCLKSOURCE_PLLSAI: PLLISAI_Q clock divided by PLLSAIDIVQ used * as SAI1 Block B clock. * @arg RCC_SAIBCLKSOURCE_Ext: External clock mapped on the I2S_CKIN pin * used as SAI1 Block B clock. */ #define __HAL_RCC_SAI_BLOCKBCLKSOURCE_CONFIG(__SOURCE__) (MODIFY_REG(RCC->DCKCFGR, RCC_DCKCFGR_SAI1BSRC, (__SOURCE__))) #endif /* STM32F427xx || STM32F437xx || STM32F429xx || STM32F439xx || STM32F469xx || STM32F479xx */ #if defined(STM32F446xx) /** @brief Macro to configure SAI1 clock source selection. * @note This configuration is only available with STM32F446xx Devices. * @note This function must be called before enabling PLL, PLLSAI, PLLI2S and * the SAI clock. * @param __SOURCE__: specifies the SAI1 clock source. * This parameter can be one of the following values: * @arg RCC_SAI1CLKSOURCE_PLLI2S: PLLI2S_Q clock divided by PLLI2SDIVQ used as SAI1 clock. * @arg RCC_SAI1CLKSOURCE_PLLSAI: PLLISAI_Q clock divided by PLLSAIDIVQ used as SAI1 clock. * @arg RCC_SAI1CLKSOURCE_PLLR: PLL VCO Output divided by PLLR used as SAI1 clock. * @arg RCC_SAI1CLKSOURCE_EXT: External clock mapped on the I2S_CKIN pin used as SAI1 clock. */ #define __HAL_RCC_SAI1_CONFIG(__SOURCE__) (MODIFY_REG(RCC->DCKCFGR, RCC_DCKCFGR_SAI1SRC, (__SOURCE__))) /** @brief Macro to Get SAI1 clock source selection. * @note This configuration is only available with STM32F446xx Devices. * @retval The clock source can be one of the following values: * @arg RCC_SAI1CLKSOURCE_PLLI2S: PLLI2S_Q clock divided by PLLI2SDIVQ used as SAI1 clock. * @arg RCC_SAI1CLKSOURCE_PLLSAI: PLLISAI_Q clock divided by PLLSAIDIVQ used as SAI1 clock. * @arg RCC_SAI1CLKSOURCE_PLLR: PLL VCO Output divided by PLLR used as SAI1 clock. * @arg RCC_SAI1CLKSOURCE_EXT: External clock mapped on the I2S_CKIN pin used as SAI1 clock. */ #define __HAL_RCC_GET_SAI1_SOURCE() (READ_BIT(RCC->DCKCFGR, RCC_DCKCFGR_SAI1SRC)) /** @brief Macro to configure SAI2 clock source selection. * @note This configuration is only available with STM32F446xx Devices. * @note This function must be called before enabling PLL, PLLSAI, PLLI2S and * the SAI clock. * @param __SOURCE__: specifies the SAI2 clock source. * This parameter can be one of the following values: * @arg RCC_SAI2CLKSOURCE_PLLI2S: PLLI2S_Q clock divided by PLLI2SDIVQ used as SAI2 clock. * @arg RCC_SAI2CLKSOURCE_PLLSAI: PLLISAI_Q clock divided by PLLSAIDIVQ used as SAI2 clock. * @arg RCC_SAI2CLKSOURCE_PLLR: PLL VCO Output divided by PLLR used as SAI2 clock. * @arg RCC_SAI2CLKSOURCE_PLLSRC: HSI or HSE depending from PLL Source clock used as SAI2 clock. */ #define __HAL_RCC_SAI2_CONFIG(__SOURCE__) (MODIFY_REG(RCC->DCKCFGR, RCC_DCKCFGR_SAI2SRC, (__SOURCE__))) /** @brief Macro to Get SAI2 clock source selection. * @note This configuration is only available with STM32F446xx Devices. * @retval The clock source can be one of the following values: * @arg RCC_SAI2CLKSOURCE_PLLI2S: PLLI2S_Q clock divided by PLLI2SDIVQ used as SAI2 clock. * @arg RCC_SAI2CLKSOURCE_PLLSAI: PLLISAI_Q clock divided by PLLSAIDIVQ used as SAI2 clock. * @arg RCC_SAI2CLKSOURCE_PLLR: PLL VCO Output divided by PLLR used as SAI2 clock. * @arg RCC_SAI2CLKSOURCE_PLLSRC: HSI or HSE depending from PLL Source clock used as SAI2 clock. */ #define __HAL_RCC_GET_SAI2_SOURCE() (READ_BIT(RCC->DCKCFGR, RCC_DCKCFGR_SAI2SRC)) /** @brief Macro to configure I2S APB1 clock source selection. * @note This function must be called before enabling PLL, PLLI2S and the I2S clock. * @param __SOURCE__: specifies the I2S APB1 clock source. * This parameter can be one of the following values: * @arg RCC_I2SAPB1CLKSOURCE_PLLI2S: PLLI2S VCO output clock divided by PLLI2SR used as I2S clock. * @arg RCC_I2SAPB1CLKSOURCE_EXT: External clock mapped on the I2S_CKIN pin used as SAI1 clock. * @arg RCC_I2SAPB1CLKSOURCE_PLLR: PLL VCO Output divided by PLLR used as SAI1 clock. * @arg RCC_I2SAPB1CLKSOURCE_PLLSRC: HSI or HSE depending from PLL source Clock. */ #define __HAL_RCC_I2S_APB1_CONFIG(__SOURCE__) (MODIFY_REG(RCC->DCKCFGR, RCC_DCKCFGR_I2S1SRC, (__SOURCE__))) /** @brief Macro to Get I2S APB1 clock source selection. * @retval The clock source can be one of the following values: * @arg RCC_I2SAPB1CLKSOURCE_PLLI2S: PLLI2S VCO output clock divided by PLLI2SR used as I2S clock. * @arg RCC_I2SAPB1CLKSOURCE_EXT: External clock mapped on the I2S_CKIN pin used as SAI1 clock. * @arg RCC_I2SAPB1CLKSOURCE_PLLR: PLL VCO Output divided by PLLR used as SAI1 clock. * @arg RCC_I2SAPB1CLKSOURCE_PLLSRC: HSI or HSE depending from PLL source Clock. */ #define __HAL_RCC_GET_I2S_APB1_SOURCE() (READ_BIT(RCC->DCKCFGR, RCC_DCKCFGR_I2S1SRC)) /** @brief Macro to configure I2S APB2 clock source selection. * @note This function must be called before enabling PLL, PLLI2S and the I2S clock. * @param __SOURCE__: specifies the SAI Block A clock source. * This parameter can be one of the following values: * @arg RCC_I2SAPB2CLKSOURCE_PLLI2S: PLLI2S VCO output clock divided by PLLI2SR used as I2S clock. * @arg RCC_I2SAPB2CLKSOURCE_EXT: External clock mapped on the I2S_CKIN pin used as SAI1 clock. * @arg RCC_I2SAPB2CLKSOURCE_PLLR: PLL VCO Output divided by PLLR used as SAI1 clock. * @arg RCC_I2SAPB2CLKSOURCE_PLLSRC: HSI or HSE depending from PLL source Clock. */ #define __HAL_RCC_I2S_APB2_CONFIG(__SOURCE__) (MODIFY_REG(RCC->DCKCFGR, RCC_DCKCFGR_I2S2SRC, (__SOURCE__))) /** @brief Macro to Get I2S APB2 clock source selection. * @retval The clock source can be one of the following values: * @arg RCC_I2SAPB2CLKSOURCE_PLLI2S: PLLI2S VCO output clock divided by PLLI2SR used as I2S clock. * @arg RCC_I2SAPB2CLKSOURCE_EXT: External clock mapped on the I2S_CKIN pin used as SAI1 clock. * @arg RCC_I2SAPB2CLKSOURCE_PLLR: PLL VCO Output divided by PLLR used as SAI1 clock. * @arg RCC_I2SAPB2CLKSOURCE_PLLSRC: HSI or HSE depending from PLL source Clock. */ #define __HAL_RCC_GET_I2S_APB2_SOURCE() (READ_BIT(RCC->DCKCFGR, RCC_DCKCFGR_I2S2SRC)) /** @brief Macro to configure the CEC clock. * @param __SOURCE__: specifies the CEC clock source. * This parameter can be one of the following values: * @arg RCC_CECCLKSOURCE_HSI: HSI selected as CEC clock * @arg RCC_CECCLKSOURCE_LSE: LSE selected as CEC clock */ #define __HAL_RCC_CEC_CONFIG(__SOURCE__) (MODIFY_REG(RCC->DCKCFGR2, RCC_DCKCFGR2_CECSEL, (uint32_t)(__SOURCE__))) /** @brief Macro to Get the CEC clock. * @retval The clock source can be one of the following values: * @arg RCC_CECCLKSOURCE_HSI488: HSI selected as CEC clock * @arg RCC_CECCLKSOURCE_LSE: LSE selected as CEC clock */ #define __HAL_RCC_GET_CEC_SOURCE() (READ_BIT(RCC->DCKCFGR2, RCC_DCKCFGR2_CECSEL)) /** @brief Macro to configure the FMPI2C1 clock. * @param __SOURCE__: specifies the FMPI2C1 clock source. * This parameter can be one of the following values: * @arg RCC_FMPI2C1CLKSOURCE_APB: APB selected as FMPI2C1 clock * @arg RCC_FMPI2C1CLKSOURCE_SYSCLK: SYS clock selected as FMPI2C1 clock * @arg RCC_FMPI2C1CLKSOURCE_HSI: HSI selected as FMPI2C1 clock */ #define __HAL_RCC_FMPI2C1_CONFIG(__SOURCE__) (MODIFY_REG(RCC->DCKCFGR2, RCC_DCKCFGR2_FMPI2C1SEL, (uint32_t)(__SOURCE__))) /** @brief Macro to Get the FMPI2C1 clock. * @retval The clock source can be one of the following values: * @arg RCC_FMPI2C1CLKSOURCE_APB: APB selected as FMPI2C1 clock * @arg RCC_FMPI2C1CLKSOURCE_SYSCLK: SYS clock selected as FMPI2C1 clock * @arg RCC_FMPI2C1CLKSOURCE_HSI: HSI selected as FMPI2C1 clock */ #define __HAL_RCC_GET_FMPI2C1_SOURCE() (READ_BIT(RCC->DCKCFGR2, RCC_DCKCFGR2_FMPI2C1SEL)) /** @brief Macro to configure the CLK48 clock. * @param __SOURCE__: specifies the CK48 clock source. * This parameter can be one of the following values: * @arg RCC_CK48CLKSOURCE_PLLQ: PLL VCO Output divided by PLLQ used as CK48 clock. * @arg RCC_CK48CLKSOURCE_PLLSAIP: PLLSAI VCO Output divided by PLLSAIP used as CK48 clock. */ #define __HAL_RCC_CLK48_CONFIG(__SOURCE__) (MODIFY_REG(RCC->DCKCFGR2, RCC_DCKCFGR2_CK48MSEL, (uint32_t)(__SOURCE__))) /** @brief Macro to Get the CLK48 clock. * @retval The clock source can be one of the following values: * @arg RCC_CK48CLKSOURCE_PLLQ: PLL VCO Output divided by PLLQ used as CK48 clock. * @arg RCC_CK48CLKSOURCE_PLLSAIP: PLLSAI VCO Output divided by PLLSAIP used as CK48 clock. */ #define __HAL_RCC_GET_CLK48_SOURCE() (READ_BIT(RCC->DCKCFGR2, RCC_DCKCFGR2_CK48MSEL)) /** @brief Macro to configure the SDIO clock. * @param __SOURCE__: specifies the SDIO clock source. * This parameter can be one of the following values: * @arg RCC_SDIOCLKSOURCE_CK48: CK48 output used as SDIO clock. * @arg RCC_SDIOCLKSOURCE_SYSCLK: System clock output used as SDIO clock. */ #define __HAL_RCC_SDIO_CONFIG(__SOURCE__) (MODIFY_REG(RCC->DCKCFGR2, RCC_DCKCFGR2_SDIOSEL, (uint32_t)(__SOURCE__))) /** @brief Macro to Get the SDIO clock. * @retval The clock source can be one of the following values: * @arg RCC_SDIOCLKSOURCE_CK48: CK48 output used as SDIO clock. * @arg RCC_SDIOCLKSOURCE_SYSCLK: System clock output used as SDIO clock. */ #define __HAL_RCC_GET_SDIO_SOURCE() (READ_BIT(RCC->DCKCFGR2, RCC_DCKCFGR2_SDIOSEL)) /** @brief Macro to configure the SPDIFRX clock. * @param __SOURCE__: specifies the SPDIFRX clock source. * This parameter can be one of the following values: * @arg RCC_SPDIFRXCLKSOURCE_PLLR: PLL VCO Output divided by PLLR used as SPDIFRX clock. * @arg RCC_SPDIFRXCLKSOURCE_PLLI2SP: PLLI2S VCO Output divided by PLLI2SP used as SPDIFRX clock. */ #define __HAL_RCC_SPDIFRX_CONFIG(__SOURCE__) (MODIFY_REG(RCC->DCKCFGR2, RCC_DCKCFGR2_SPDIFRXSEL, (uint32_t)(__SOURCE__))) /** @brief Macro to Get the SPDIFRX clock. * @retval The clock source can be one of the following values: * @arg RCC_SPDIFRXCLKSOURCE_PLLR: PLL VCO Output divided by PLLR used as SPDIFRX clock. * @arg RCC_SPDIFRXCLKSOURCE_PLLI2SP: PLLI2S VCO Output divided by PLLI2SP used as SPDIFRX clock. */ #define __HAL_RCC_GET_SPDIFRX_SOURCE() (READ_BIT(RCC->DCKCFGR2, RCC_DCKCFGR2_SPDIFRXSEL)) #endif /* STM32F446xx */ #if defined(STM32F469xx) || defined(STM32F479xx) /** @brief Macro to configure the CLK48 clock. * @param __SOURCE__: specifies the CK48 clock source. * This parameter can be one of the following values: * @arg RCC_CK48CLKSOURCE_PLLQ: PLL VCO Output divided by PLLQ used as CK48 clock. * @arg RCC_CK48CLKSOURCE_PLLSAIP: PLLSAI VCO Output divided by PLLSAIP used as CK48 clock. */ #define __HAL_RCC_CLK48_CONFIG(__SOURCE__) (MODIFY_REG(RCC->DCKCFGR, RCC_DCKCFGR_CK48MSEL, (uint32_t)(__SOURCE__))) /** @brief Macro to Get the CLK48 clock. * @retval The clock source can be one of the following values: * @arg RCC_CK48CLKSOURCE_PLLQ: PLL VCO Output divided by PLLQ used as CK48 clock. * @arg RCC_CK48CLKSOURCE_PLLSAIP: PLLSAI VCO Output divided by PLLSAIP used as CK48 clock. */ #define __HAL_RCC_GET_CLK48_SOURCE() (READ_BIT(RCC->DCKCFGR, RCC_DCKCFGR_CK48MSEL)) /** @brief Macro to configure the SDIO clock. * @param __SOURCE__: specifies the SDIO clock source. * This parameter can be one of the following values: * @arg RCC_SDIOCLKSOURCE_CK48: CK48 output used as SDIO clock. * @arg RCC_SDIOCLKSOURCE_SYSCLK: System clock output used as SDIO clock. */ #define __HAL_RCC_SDIO_CONFIG(__SOURCE__) (MODIFY_REG(RCC->DCKCFGR, RCC_DCKCFGR_SDIOSEL, (uint32_t)(__SOURCE__))) /** @brief Macro to Get the SDIO clock. * @retval The clock source can be one of the following values: * @arg RCC_SDIOCLKSOURCE_CK48: CK48 output used as SDIO clock. * @arg RCC_SDIOCLKSOURCE_SYSCLK: System clock output used as SDIO clock. */ #define __HAL_RCC_GET_SDIO_SOURCE() (READ_BIT(RCC->DCKCFGR, RCC_DCKCFGR_SDIOSEL)) /** @brief Macro to configure the DSI clock. * @param __SOURCE__: specifies the DSI clock source. * This parameter can be one of the following values: * @arg RCC_DSICLKSOURCE_PLLR: PLLR output used as DSI clock. * @arg RCC_DSICLKSOURCE_DSIPHY: DSI-PHY output used as DSI clock. */ #define __HAL_RCC_DSI_CONFIG(__SOURCE__) (MODIFY_REG(RCC->DCKCFGR, RCC_DCKCFGR_DSISEL, (uint32_t)(__SOURCE__))) /** @brief Macro to Get the DSI clock. * @retval The clock source can be one of the following values: * @arg RCC_DSICLKSOURCE_PLLR: PLLR output used as DSI clock. * @arg RCC_DSICLKSOURCE_DSIPHY: DSI-PHY output used as DSI clock. */ #define __HAL_RCC_GET_DSI_SOURCE() (READ_BIT(RCC->DCKCFGR, RCC_DCKCFGR_DSISEL)) #endif /* STM32F469xx || STM32F479xx */ #if defined(STM32F410Tx) || defined(STM32F410Cx) || defined(STM32F410Rx) /** @brief Macro to configure I2S clock source selection. * @param __SOURCE__: specifies the I2S clock source. * This parameter can be one of the following values: * @arg RCC_I2SAPBCLKSOURCE_PLLR: PLL VCO output clock divided by PLLR. * @arg RCC_I2SAPBCLKSOURCE_EXT: External clock mapped on the I2S_CKIN pin. * @arg RCC_I2SAPBCLKSOURCE_PLLSRC: HSI/HSE depends on PLLSRC. */ #define __HAL_RCC_I2S_CONFIG(__SOURCE__) (MODIFY_REG(RCC->DCKCFGR, RCC_DCKCFGR_I2SSRC, (__SOURCE__))) /** @brief Macro to Get I2S clock source selection. * @retval The clock source can be one of the following values: * @arg RCC_I2SAPBCLKSOURCE_PLLR: PLL VCO output clock divided by PLLR. * @arg RCC_I2SAPBCLKSOURCE_EXT: External clock mapped on the I2S_CKIN pin. * @arg RCC_I2SAPBCLKSOURCE_PLLSRC: HSI/HSE depends on PLLSRC. */ #define __HAL_RCC_GET_I2S_SOURCE() (READ_BIT(RCC->DCKCFGR, RCC_DCKCFGR_I2SSRC)) /** @brief Macro to configure the FMPI2C1 clock. * @param __SOURCE__: specifies the FMPI2C1 clock source. * This parameter can be one of the following values: * @arg RCC_FMPI2C1CLKSOURCE_APB: APB selected as FMPI2C1 clock * @arg RCC_FMPI2C1CLKSOURCE_SYSCLK: SYS clock selected as FMPI2C1 clock * @arg RCC_FMPI2C1CLKSOURCE_HSI: HSI selected as FMPI2C1 clock */ #define __HAL_RCC_FMPI2C1_CONFIG(__SOURCE__) (MODIFY_REG(RCC->DCKCFGR2, RCC_DCKCFGR2_FMPI2C1SEL, (uint32_t)(__SOURCE__))) /** @brief Macro to Get the FMPI2C1 clock. * @retval The clock source can be one of the following values: * @arg RCC_FMPI2C1CLKSOURCE_APB: APB selected as FMPI2C1 clock * @arg RCC_FMPI2C1CLKSOURCE_SYSCLK: SYS clock selected as FMPI2C1 clock * @arg RCC_FMPI2C1CLKSOURCE_HSI: HSI selected as FMPI2C1 clock */ #define __HAL_RCC_GET_FMPI2C1_SOURCE() (READ_BIT(RCC->DCKCFGR2, RCC_DCKCFGR2_FMPI2C1SEL)) /** @brief Macro to configure the LPTIM1 clock. * @param __SOURCE__: specifies the LPTIM1 clock source. * This parameter can be one of the following values: * @arg RCC_LPTIM1CLKSOURCE_PCLK: APB selected as LPTIM1 clock * @arg RCC_LPTIM1CLKSOURCE_HSI: HSI clock selected as LPTIM1 clock * @arg RCC_LPTIM1CLKSOURCE_LSI: LSI selected as LPTIM1 clock * @arg RCC_LPTIM1CLKSOURCE_LSE: LSE selected as LPTIM1 clock */ #define __HAL_RCC_LPTIM1_CONFIG(__SOURCE__) (MODIFY_REG(RCC->DCKCFGR2, RCC_DCKCFGR2_LPTIM1SEL, (uint32_t)(__SOURCE__))) /** @brief Macro to Get the LPTIM1 clock. * @retval The clock source can be one of the following values: * @arg RCC_LPTIM1CLKSOURCE_PCLK: APB selected as LPTIM1 clock * @arg RCC_LPTIM1CLKSOURCE_HSI: HSI clock selected as LPTIM1 clock * @arg RCC_LPTIM1CLKSOURCE_LSI: LSI selected as LPTIM1 clock * @arg RCC_LPTIM1CLKSOURCE_LSE: LSE selected as LPTIM1 clock */ #define __HAL_RCC_GET_LPTIM1_SOURCE() (READ_BIT(RCC->DCKCFGR2, RCC_DCKCFGR2_LPTIM1SEL)) #endif /* STM32F410Tx || STM32F410Cx || STM32F410Rx */ #if defined(STM32F427xx) || defined(STM32F437xx) || defined(STM32F429xx) || defined(STM32F439xx) ||\ defined(STM32F401xC) || defined(STM32F401xE) || defined(STM32F410Tx) || defined(STM32F410Cx) ||\ defined(STM32F410Rx) || defined(STM32F411xE) || defined(STM32F446xx) || defined(STM32F469xx) ||\ defined(STM32F479xx) /** @brief Macro to configure the Timers clocks prescalers * @note This feature is only available with STM32F429x/439x Devices. * @param __PRESC__ : specifies the Timers clocks prescalers selection * This parameter can be one of the following values: * @arg RCC_TIMPRES_DESACTIVATED: The Timers kernels clocks prescaler is * equal to HPRE if PPREx is corresponding to division by 1 or 2, * else it is equal to [(HPRE * PPREx) / 2] if PPREx is corresponding to * division by 4 or more. * @arg RCC_TIMPRES_ACTIVATED: The Timers kernels clocks prescaler is * equal to HPRE if PPREx is corresponding to division by 1, 2 or 4, * else it is equal to [(HPRE * PPREx) / 4] if PPREx is corresponding * to division by 8 or more. */ #define __HAL_RCC_TIMCLKPRESCALER(__PRESC__) (*(__IO uint32_t *) RCC_DCKCFGR_TIMPRE_BB = (__PRESC__)) #endif /* STM32F427xx || STM32F437xx || STM32F429xx || STM32F439xx) || STM32F401xC || STM32F401xE || STM32F410xx || STM32F411xE ||\ STM32F446xx || STM32F469xx || STM32F479xx */ /*----------------------------------------------------------------------------*/ #if defined(STM32F427xx) || defined(STM32F437xx) || defined(STM32F429xx) || defined(STM32F439xx) || defined(STM32F446xx) || defined(STM32F469xx) || defined(STM32F479xx) /** @brief Enable PLLSAI_RDY interrupt. */ #define __HAL_RCC_PLLSAI_ENABLE_IT() (RCC->CIR |= (RCC_CIR_PLLSAIRDYIE)) /** @brief Disable PLLSAI_RDY interrupt. */ #define __HAL_RCC_PLLSAI_DISABLE_IT() (RCC->CIR &= ~(RCC_CIR_PLLSAIRDYIE)) /** @brief Clear the PLLSAI RDY interrupt pending bits. */ #define __HAL_RCC_PLLSAI_CLEAR_IT() (RCC->CIR |= (RCC_CIR_PLLSAIRDYF)) /** @brief Check the PLLSAI RDY interrupt has occurred or not. * @retval The new state (TRUE or FALSE). */ #define __HAL_RCC_PLLSAI_GET_IT() ((RCC->CIR & (RCC_CIR_PLLSAIRDYIE)) == (RCC_CIR_PLLSAIRDYIE)) /** @brief Check PLLSAI RDY flag is set or not. * @retval The new state (TRUE or FALSE). */ #define __HAL_RCC_PLLSAI_GET_FLAG() ((RCC->CR & (RCC_CR_PLLSAIRDY)) == (RCC_CR_PLLSAIRDY)) #endif /* STM32F427xx || STM32F437xx || STM32F429xx || STM32F439xx || STM32F446xx || STM32F469xx || STM32F479xx */ #if defined(STM32F410Tx) || defined(STM32F410Cx) || defined(STM32F410Rx) /** @defgroup RCCEx_MCO1_Enable MCO1 Enable * @brief Macros to enable or disable the RCC MCO1 feature. */ #define __HAL_RCC_MCO1_ENABLE() (*(__IO uint32_t *) RCC_CFGR_MCO1EN_BB = ENABLE) #define __HAL_RCC_MCO1_DISABLE() (*(__IO uint32_t *) RCC_CFGR_MCO1EN_BB = DISABLE) /** * @} */ /** @defgroup RCCEx_MCO2_Enable MCO2 Enable * @brief Macros to enable or disable the RCC MCO2 feature. */ #define __HAL_RCC_MCO2_ENABLE() (*(__IO uint32_t *) RCC_CFGR_MCO2EN_BB = ENABLE) #define __HAL_RCC_MCO2_DISABLE() (*(__IO uint32_t *) RCC_CFGR_MCO2EN_BB = DISABLE) /** * @} */ #endif /* STM32F410Tx || STM32F410Cx || STM32F410Rx */ /** * @} */ /* Exported functions --------------------------------------------------------*/ /** @addtogroup RCCEx_Exported_Functions * @{ */ /** @addtogroup RCCEx_Exported_Functions_Group1 * @{ */ HAL_StatusTypeDef HAL_RCCEx_PeriphCLKConfig(RCC_PeriphCLKInitTypeDef *PeriphClkInit); void HAL_RCCEx_GetPeriphCLKConfig(RCC_PeriphCLKInitTypeDef *PeriphClkInit); #if defined(STM32F446xx) uint32_t HAL_RCCEx_GetPeriphCLKFreq(uint32_t PeriphClk); #endif /* STM32F446xx */ #if defined(STM32F410Tx) || defined(STM32F410Cx) || defined(STM32F410Rx) || defined(STM32F411xE) ||\ defined(STM32F446xx) || defined(STM32F469xx) || defined(STM32F479xx) void HAL_RCCEx_SelectLSEMode(uint8_t Mode); #endif /* STM32F410xx || STM32F411xE || STM32F446xx || STM32F469xx || STM32F479xx */ /** * @} */ /** * @} */ /* Private types -------------------------------------------------------------*/ /* Private variables ---------------------------------------------------------*/ /* Private constants ---------------------------------------------------------*/ /** @defgroup RCCEx_Private_Constants RCCEx Private Constants * @{ */ /** @defgroup RCCEx_BitAddress_AliasRegion RCC BitAddress AliasRegion * @brief RCC registers bit address in the alias region * @{ */ /* --- CR Register ---*/ #if defined(STM32F427xx) || defined(STM32F437xx) || defined(STM32F429xx) || defined(STM32F439xx) ||\ defined(STM32F446xx) || defined(STM32F469xx) || defined(STM32F479xx) /* Alias word address of PLLSAION bit */ #define RCC_PLLSAION_BIT_NUMBER 0x1C #define RCC_CR_PLLSAION_BB (PERIPH_BB_BASE + (RCC_CR_OFFSET * 32) + (RCC_PLLSAION_BIT_NUMBER * 4)) #define PLLSAI_TIMEOUT_VALUE ((uint32_t)100) /* Timeout value fixed to 100 ms */ #endif /* STM32F427xx || STM32F437xx || STM32F429xx || STM32F439xx || STM32F446xx || STM32F469xx || STM32F479xx */ #if defined(STM32F405xx) || defined(STM32F415xx) || defined(STM32F407xx) || defined(STM32F417xx) || \ defined(STM32F427xx) || defined(STM32F437xx) || defined(STM32F429xx) || defined(STM32F439xx) || \ defined(STM32F401xC) || defined(STM32F401xE) || defined(STM32F411xE) || defined(STM32F446xx) || \ defined(STM32F469xx) || defined(STM32F479xx) /* Alias word address of PLLI2SON bit */ #define RCC_PLLI2SON_BIT_NUMBER 0x1A #define RCC_CR_PLLI2SON_BB (PERIPH_BB_BASE + (RCC_CR_OFFSET * 32) + (RCC_PLLI2SON_BIT_NUMBER * 4)) #endif /* STM32F405xx || STM32F415xx || STM32F407xx || STM32F417xx || STM32F427xx || STM32F437xx || STM32F429xx || STM32F439xx || STM32F401xC || STM32F401xE || STM32F411xE || STM32F446xx || STM32F469xx || STM32F479xx */ /* --- DCKCFGR Register ---*/ #if defined(STM32F427xx) || defined(STM32F437xx) || defined(STM32F429xx) || defined(STM32F439xx) ||\ defined(STM32F410Tx) || defined(STM32F410Cx) || defined(STM32F410Rx) || defined(STM32F446xx) ||\ defined(STM32F469xx) || defined(STM32F479xx) /* Alias word address of TIMPRE bit */ #define RCC_DCKCFGR_OFFSET (RCC_OFFSET + 0x8C) #define RCC_TIMPRE_BIT_NUMBER 0x18 #define RCC_DCKCFGR_TIMPRE_BB (PERIPH_BB_BASE + (RCC_DCKCFGR_OFFSET * 32) + (RCC_TIMPRE_BIT_NUMBER * 4)) #endif /* STM32F427xx || STM32F437xx || STM32F429xx || STM32F439xx || STM32F410xx || STM32F446xx || STM32F469xx || STM32F479xx */ /* --- CFGR Register ---*/ #define RCC_CFGR_OFFSET (RCC_OFFSET + 0x08) #if defined(STM32F405xx) || defined(STM32F415xx) || defined(STM32F407xx) || defined(STM32F417xx) || \ defined(STM32F427xx) || defined(STM32F437xx) || defined(STM32F429xx) || defined(STM32F439xx) || \ defined(STM32F401xC) || defined(STM32F401xE) || defined(STM32F411xE) || defined(STM32F446xx) || \ defined(STM32F469xx) || defined(STM32F479xx) /* Alias word address of I2SSRC bit */ #define RCC_I2SSRC_BIT_NUMBER 0x17 #define RCC_CFGR_I2SSRC_BB (PERIPH_BB_BASE + (RCC_CFGR_OFFSET * 32) + (RCC_I2SSRC_BIT_NUMBER * 4)) #define PLLI2S_TIMEOUT_VALUE ((uint32_t)100) /* Timeout value fixed to 100 ms */ #endif /* STM32F405xx || STM32F415xx || STM32F407xx || STM32F417xx || STM32F427xx || STM32F437xx || STM32F429xx || STM32F439xx || STM32F401xC || STM32F401xE || STM32F411xE || STM32F446xx || STM32F469xx || STM32F479xx */ #if defined(STM32F410Tx) || defined(STM32F410Cx) || defined(STM32F410Rx) /* Alias word address of MCO1EN bit */ #define RCC_MCO1EN_BIT_NUMBER 0x8 #define RCC_CFGR_MCO1EN_BB (PERIPH_BB_BASE + (RCC_CFGR_OFFSET * 32) + (RCC_MCO1EN_BIT_NUMBER * 4)) /* Alias word address of MCO2EN bit */ #define RCC_MCO2EN_BIT_NUMBER 0x9 #define RCC_CFGR_MCO2EN_BB (PERIPH_BB_BASE + (RCC_CFGR_OFFSET * 32) + (RCC_MCO2EN_BIT_NUMBER * 4)) #endif /* STM32F410Tx || STM32F410Cx || STM32F410Rx */ #define PLL_TIMEOUT_VALUE ((uint32_t)100) /* 100 ms */ /** * @} */ /** * @} */ /* Private macros ------------------------------------------------------------*/ /** @addtogroup RCCEx_Private_Macros RCCEx Private Macros * @{ */ /** @defgroup RCCEx_IS_RCC_Definitions RCC Private macros to check input parameters * @{ */ #if defined(STM32F427xx) || defined(STM32F437xx) || defined(STM32F429xx)|| defined(STM32F439xx) #define IS_RCC_PERIPHCLOCK(SELECTION) ((1 <= (SELECTION)) && ((SELECTION) <= 0x0000007F)) #endif /* STM32F427xx || STM32F437xx || STM32F429xx || STM32F439xx */ #if defined(STM32F405xx) || defined(STM32F415xx) || defined(STM32F407xx)|| defined(STM32F417xx) ||\ defined(STM32F401xC) || defined(STM32F401xE) || defined(STM32F411xE) #define IS_RCC_PERIPHCLOCK(SELECTION) ((1 <= (SELECTION)) && ((SELECTION) <= 0x00000007)) #endif /* STM32F405xx || STM32F415xx || STM32F407xx || STM32F417xx || STM32F401xC || STM32F401xE || STM32F411xE */ #if defined(STM32F410Tx) || defined(STM32F410Cx) || defined(STM32F410Rx) #define IS_RCC_PERIPHCLOCK(SELECTION) ((1 <= (SELECTION)) && ((SELECTION) <= 0x0000001F)) #endif /* STM32F410Tx || STM32F410Cx || STM32F410Rx */ #if defined(STM32F446xx) #define IS_RCC_PERIPHCLOCK(SELECTION) ((1 <= (SELECTION)) && ((SELECTION) <= 0x00000FFF)) #endif /* STM32F446xx */ #if defined(STM32F469xx) || defined(STM32F479xx) #define IS_RCC_PERIPHCLOCK(SELECTION) ((1 <= (SELECTION)) && ((SELECTION) <= 0x000001FF)) #endif /* STM32F469xx || STM32F479xx */ #define IS_RCC_PLLI2SN_VALUE(VALUE) ((192 <= (VALUE)) && ((VALUE) <= 432)) #define IS_RCC_PLLI2SR_VALUE(VALUE) ((2 <= (VALUE)) && ((VALUE) <= 7)) #if defined(STM32F427xx) || defined(STM32F437xx) || defined(STM32F429xx)|| defined(STM32F439xx) ||\ defined(STM32F446xx) || defined(STM32F469xx) || defined(STM32F479xx) #define IS_RCC_PLLI2SQ_VALUE(VALUE) ((2 <= (VALUE)) && ((VALUE) <= 15)) #define IS_RCC_PLLSAIN_VALUE(VALUE) ((49 <= (VALUE)) && ((VALUE) <= 432)) #define IS_RCC_PLLSAIQ_VALUE(VALUE) ((2 <= (VALUE)) && ((VALUE) <= 15)) #define IS_RCC_PLLSAIR_VALUE(VALUE) ((2 <= (VALUE)) && ((VALUE) <= 7)) #define IS_RCC_PLLSAI_DIVQ_VALUE(VALUE) ((1 <= (VALUE)) && ((VALUE) <= 32)) #define IS_RCC_PLLI2S_DIVQ_VALUE(VALUE) ((1 <= (VALUE)) && ((VALUE) <= 32)) #define IS_RCC_PLLSAI_DIVR_VALUE(VALUE) (((VALUE) == RCC_PLLSAIDIVR_2) ||\ ((VALUE) == RCC_PLLSAIDIVR_4) ||\ ((VALUE) == RCC_PLLSAIDIVR_8) ||\ ((VALUE) == RCC_PLLSAIDIVR_16)) #endif /* STM32F427xx || STM32F437xx || STM32F429xx || STM32F439xx || STM32F446xx || STM32F469xx || STM32F479xx */ #if defined(STM32F411xE) || defined(STM32F446xx) #define IS_RCC_PLLI2SM_VALUE(VALUE) ((VALUE) <= 63) #define IS_RCC_LSE_MODE(MODE) (((MODE) == RCC_LSE_LOWPOWER_MODE) ||\ ((MODE) == RCC_LSE_HIGHDRIVE_MODE)) #endif /* STM32F411xE || STM32F446xx */ #if defined(STM32F410Tx) || defined(STM32F410Cx) || defined(STM32F410Rx) #define IS_RCC_PLLR_VALUE(VALUE) ((2 <= (VALUE)) && ((VALUE) <= 7)) #define IS_RCC_LSE_MODE(MODE) (((MODE) == RCC_LSE_LOWPOWER_MODE) ||\ ((MODE) == RCC_LSE_HIGHDRIVE_MODE)) #define IS_RCC_FMPI2C1CLKSOURCE(SOURCE) (((SOURCE) == RCC_FMPI2C1CLKSOURCE_APB) ||\ ((SOURCE) == RCC_FMPI2C1CLKSOURCE_SYSCLK) ||\ ((SOURCE) == RCC_FMPI2C1CLKSOURCE_HSI)) #define IS_RCC_LPTIM1CLKSOURCE(SOURCE) (((SOURCE) == RCC_LPTIM1CLKSOURCE_PCLK) ||\ ((SOURCE) == RCC_LPTIM1CLKSOURCE_HSI) ||\ ((SOURCE) == RCC_LPTIM1CLKSOURCE_LSI) ||\ ((SOURCE) == RCC_LPTIM1CLKSOURCE_LSE)) #define IS_RCC_I2SAPBCLKSOURCE(SOURCE) (((SOURCE) == RCC_I2SAPBCLKSOURCE_PLLR) ||\ ((SOURCE) == RCC_I2SAPBCLKSOURCE_EXT) ||\ ((SOURCE) == RCC_I2SAPBCLKSOURCE_PLLSRC)) #endif /* STM32F410Tx || STM32F410Cx || STM32F410Rx */ #if defined(STM32F446xx) #define IS_RCC_PLLR_VALUE(VALUE) ((2 <= (VALUE)) && ((VALUE) <= 7)) #define IS_RCC_PLLI2SP_VALUE(VALUE) (((VALUE) == RCC_PLLI2SP_DIV2) ||\ ((VALUE) == RCC_PLLI2SP_DIV4) ||\ ((VALUE) == RCC_PLLI2SP_DIV6) ||\ ((VALUE) == RCC_PLLI2SP_DIV8)) #define IS_RCC_PLLSAIM_VALUE(VALUE) ((VALUE) <= 63) #define IS_RCC_PLLSAIP_VALUE(VALUE) (((VALUE) == RCC_PLLSAIP_DIV2) ||\ ((VALUE) == RCC_PLLSAIP_DIV4) ||\ ((VALUE) == RCC_PLLSAIP_DIV6) ||\ ((VALUE) == RCC_PLLSAIP_DIV8)) #define IS_RCC_SAI1CLKSOURCE(SOURCE) (((SOURCE) == RCC_SAI1CLKSOURCE_PLLSAI) ||\ ((SOURCE) == RCC_SAI1CLKSOURCE_PLLI2S) ||\ ((SOURCE) == RCC_SAI1CLKSOURCE_PLLR) ||\ ((SOURCE) == RCC_SAI1CLKSOURCE_EXT)) #define IS_RCC_SAI2CLKSOURCE(SOURCE) (((SOURCE) == RCC_SAI2CLKSOURCE_PLLSAI) ||\ ((SOURCE) == RCC_SAI2CLKSOURCE_PLLI2S) ||\ ((SOURCE) == RCC_SAI2CLKSOURCE_PLLR) ||\ ((SOURCE) == RCC_SAI2CLKSOURCE_PLLSRC)) #define IS_RCC_I2SAPB1CLKSOURCE(SOURCE) (((SOURCE) == RCC_I2SAPB1CLKSOURCE_PLLI2S) ||\ ((SOURCE) == RCC_I2SAPB1CLKSOURCE_EXT) ||\ ((SOURCE) == RCC_I2SAPB1CLKSOURCE_PLLR) ||\ ((SOURCE) == RCC_I2SAPB1CLKSOURCE_PLLSRC)) #define IS_RCC_I2SAPB2CLKSOURCE(SOURCE) (((SOURCE) == RCC_I2SAPB2CLKSOURCE_PLLI2S) ||\ ((SOURCE) == RCC_I2SAPB2CLKSOURCE_EXT) ||\ ((SOURCE) == RCC_I2SAPB2CLKSOURCE_PLLR) ||\ ((SOURCE) == RCC_I2SAPB2CLKSOURCE_PLLSRC)) #define IS_RCC_FMPI2C1CLKSOURCE(SOURCE) (((SOURCE) == RCC_FMPI2C1CLKSOURCE_APB) ||\ ((SOURCE) == RCC_FMPI2C1CLKSOURCE_SYSCLK) ||\ ((SOURCE) == RCC_FMPI2C1CLKSOURCE_HSI)) #define IS_RCC_CECCLKSOURCE(SOURCE) (((SOURCE) == RCC_CECCLKSOURCE_HSI) ||\ ((SOURCE) == RCC_CECCLKSOURCE_LSE)) #define IS_RCC_CK48CLKSOURCE(SOURCE) (((SOURCE) == RCC_CK48CLKSOURCE_PLLQ) ||\ ((SOURCE) == RCC_CK48CLKSOURCE_PLLSAIP)) #define IS_RCC_SDIOCLKSOURCE(SOURCE) (((SOURCE) == RCC_SDIOCLKSOURCE_CK48) ||\ ((SOURCE) == RCC_SDIOCLKSOURCE_SYSCLK)) #define IS_RCC_SPDIFRXCLKSOURCE(SOURCE) (((SOURCE) == RCC_SPDIFRXCLKSOURCE_PLLR) ||\ ((SOURCE) == RCC_SPDIFRXCLKSOURCE_PLLI2SP)) #endif /* STM32F446xx */ #if defined(STM32F469xx) || defined(STM32F479xx) #define IS_RCC_PLLR_VALUE(VALUE) ((2 <= (VALUE)) && ((VALUE) <= 7)) #define IS_RCC_PLLSAIP_VALUE(VALUE) (((VALUE) == RCC_PLLSAIP_DIV2) ||\ ((VALUE) == RCC_PLLSAIP_DIV4) ||\ ((VALUE) == RCC_PLLSAIP_DIV6) ||\ ((VALUE) == RCC_PLLSAIP_DIV8)) #define IS_RCC_CK48CLKSOURCE(SOURCE) (((SOURCE) == RCC_CK48CLKSOURCE_PLLQ) ||\ ((SOURCE) == RCC_CK48CLKSOURCE_PLLSAIP)) #define IS_RCC_SDIOCLKSOURCE(SOURCE) (((SOURCE) == RCC_SDIOCLKSOURCE_CK48) ||\ ((SOURCE) == RCC_SDIOCLKSOURCE_SYSCLK)) #define IS_RCC_DSIBYTELANECLKSOURCE(SOURCE) (((SOURCE) == RCC_DSICLKSOURCE_PLLR) ||\ ((SOURCE) == RCC_DSICLKSOURCE_DSIPHY)) #define IS_RCC_LSE_MODE(MODE) (((MODE) == RCC_LSE_LOWPOWER_MODE) ||\ ((MODE) == RCC_LSE_HIGHDRIVE_MODE)) #endif /* STM32F469xx || STM32F479xx */ #if defined(STM32F405xx) || defined(STM32F415xx) || defined(STM32F407xx) || defined(STM32F417xx) || \ defined(STM32F427xx) || defined(STM32F437xx) || defined(STM32F429xx) || defined(STM32F439xx) || \ defined(STM32F401xC) || defined(STM32F401xE) || defined(STM32F411xE) || defined(STM32F446xx) || \ defined(STM32F469xx) || defined(STM32F479xx) #define IS_RCC_MCO2SOURCE(SOURCE) (((SOURCE) == RCC_MCO2SOURCE_SYSCLK) || ((SOURCE) == RCC_MCO2SOURCE_PLLI2SCLK)|| \ ((SOURCE) == RCC_MCO2SOURCE_HSE) || ((SOURCE) == RCC_MCO2SOURCE_PLLCLK)) #endif /* STM32F405xx || STM32F415xx || STM32F407xx || STM32F417xx || STM32F427xx || STM32F437xx || STM32F429xx || STM32F439xx || STM32F401xC || STM32F401xE || STM32F411xE || STM32F446xx || STM32F469xx || STM32F479xx */ #if defined(STM32F410Tx) || defined(STM32F410Cx) || defined(STM32F410Rx) #define IS_RCC_MCO2SOURCE(SOURCE) (((SOURCE) == RCC_MCO2SOURCE_SYSCLK) || ((SOURCE) == RCC_MCO2SOURCE_I2SCLK)|| \ ((SOURCE) == RCC_MCO2SOURCE_HSE) || ((SOURCE) == RCC_MCO2SOURCE_PLLCLK)) #endif /* STM32F410Tx || STM32F410Cx || STM32F410Rx */ /** * @} */ /** * @} */ /** * @} */ /** * @} */ #ifdef __cplusplus } #endif #endif /* __STM32F4xx_HAL_RCC_EX_H */ /************************ (C) COPYRIGHT STMicroelectronics *****END OF FILE****/ ================================================ FILE: Zelig/mbed/TARGET_NUCLEO_F411RE/stm32f4xx_hal_rng.h ================================================ /** ****************************************************************************** * @file stm32f4xx_hal_rng.h * @author MCD Application Team * @version V1.4.1 * @date 09-October-2015 * @brief Header file of RNG HAL module. ****************************************************************************** * @attention * *

© COPYRIGHT(c) 2015 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. * ****************************************************************************** */ /* Define to prevent recursive inclusion -------------------------------------*/ #ifndef __STM32F4xx_HAL_RNG_H #define __STM32F4xx_HAL_RNG_H #ifdef __cplusplus extern "C" { #endif #if defined(STM32F405xx) || defined(STM32F415xx) || defined(STM32F407xx) || defined(STM32F417xx) ||\ defined(STM32F427xx) || defined(STM32F437xx) || defined(STM32F429xx) || defined(STM32F439xx) ||\ defined(STM32F410Tx) || defined(STM32F410Cx) || defined(STM32F410Rx) || defined(STM32F469xx) ||\ defined(STM32F479xx) /* Includes ------------------------------------------------------------------*/ #include "stm32f4xx_hal_def.h" /** @addtogroup STM32F4xx_HAL_Driver * @{ */ /** @defgroup RNG RNG * @brief RNG HAL module driver * @{ */ /* Exported types ------------------------------------------------------------*/ /** @defgroup RNG_Exported_Types RNG Exported Types * @{ */ /** @defgroup RNG_Exported_Types_Group1 RNG State Structure definition * @{ */ typedef enum { HAL_RNG_STATE_RESET = 0x00, /*!< RNG not yet initialized or disabled */ HAL_RNG_STATE_READY = 0x01, /*!< RNG initialized and ready for use */ HAL_RNG_STATE_BUSY = 0x02, /*!< RNG internal process is ongoing */ HAL_RNG_STATE_TIMEOUT = 0x03, /*!< RNG timeout state */ HAL_RNG_STATE_ERROR = 0x04 /*!< RNG error state */ }HAL_RNG_StateTypeDef; /** * @} */ /** @defgroup RNG_Exported_Types_Group2 RNG Handle Structure definition * @{ */ typedef struct { RNG_TypeDef *Instance; /*!< Register base address */ HAL_LockTypeDef Lock; /*!< RNG locking object */ __IO HAL_RNG_StateTypeDef State; /*!< RNG communication state */ uint32_t RandomNumber; /*!< Last Generated RNG Data */ }RNG_HandleTypeDef; /** * @} */ /** * @} */ /* Exported constants --------------------------------------------------------*/ /** @defgroup RNG_Exported_Constants RNG Exported Constants * @{ */ /** @defgroup RNG_Exported_Constants_Group1 RNG Interrupt definition * @{ */ #define RNG_IT_DRDY RNG_SR_DRDY /*!< Data Ready interrupt */ #define RNG_IT_CEI RNG_SR_CEIS /*!< Clock error interrupt */ #define RNG_IT_SEI RNG_SR_SEIS /*!< Seed error interrupt */ /** * @} */ /** @defgroup RNG_Exported_Constants_Group2 RNG Flag definition * @{ */ #define RNG_FLAG_DRDY RNG_SR_DRDY /*!< Data ready */ #define RNG_FLAG_CECS RNG_SR_CECS /*!< Clock error current status */ #define RNG_FLAG_SECS RNG_SR_SECS /*!< Seed error current status */ /** * @} */ /** * @} */ /* Exported macros -----------------------------------------------------------*/ /** @defgroup RNG_Exported_Macros RNG Exported Macros * @{ */ /** @brief Reset RNG handle state * @param __HANDLE__: RNG Handle * @retval None */ #define __HAL_RNG_RESET_HANDLE_STATE(__HANDLE__) ((__HANDLE__)->State = HAL_RNG_STATE_RESET) /** * @brief Enables the RNG peripheral. * @param __HANDLE__: RNG Handle * @retval None */ #define __HAL_RNG_ENABLE(__HANDLE__) ((__HANDLE__)->Instance->CR |= RNG_CR_RNGEN) /** * @brief Disables the RNG peripheral. * @param __HANDLE__: RNG Handle * @retval None */ #define __HAL_RNG_DISABLE(__HANDLE__) ((__HANDLE__)->Instance->CR &= ~RNG_CR_RNGEN) /** * @brief Check the selected RNG flag status. * @param __HANDLE__: RNG Handle * @param __FLAG__: RNG flag * This parameter can be one of the following values: * @arg RNG_FLAG_DRDY: Data ready * @arg RNG_FLAG_CECS: Clock error current status * @arg RNG_FLAG_SECS: Seed error current status * @retval The new state of __FLAG__ (SET or RESET). */ #define __HAL_RNG_GET_FLAG(__HANDLE__, __FLAG__) (((__HANDLE__)->Instance->SR & (__FLAG__)) == (__FLAG__)) /** * @brief Clears the selected RNG flag status. * @param __HANDLE__: RNG handle * @param __FLAG__: RNG flag to clear * @note WARNING: This is a dummy macro for HAL code alignment, * flags RNG_FLAG_DRDY, RNG_FLAG_CECS and RNG_FLAG_SECS are read-only. * @retval None */ #define __HAL_RNG_CLEAR_FLAG(__HANDLE__, __FLAG__) /* dummy macro */ /** * @brief Enables the RNG interrupts. * @param __HANDLE__: RNG Handle * @retval None */ #define __HAL_RNG_ENABLE_IT(__HANDLE__) ((__HANDLE__)->Instance->CR |= RNG_CR_IE) /** * @brief Disables the RNG interrupts. * @param __HANDLE__: RNG Handle * @retval None */ #define __HAL_RNG_DISABLE_IT(__HANDLE__) ((__HANDLE__)->Instance->CR &= ~RNG_CR_IE) /** * @brief Checks whether the specified RNG interrupt has occurred or not. * @param __HANDLE__: RNG Handle * @param __INTERRUPT__: specifies the RNG interrupt status flag to check. * This parameter can be one of the following values: * @arg RNG_IT_DRDY: Data ready interrupt * @arg RNG_IT_CEI: Clock error interrupt * @arg RNG_IT_SEI: Seed error interrupt * @retval The new state of __INTERRUPT__ (SET or RESET). */ #define __HAL_RNG_GET_IT(__HANDLE__, __INTERRUPT__) (((__HANDLE__)->Instance->SR & (__INTERRUPT__)) == (__INTERRUPT__)) /** * @brief Clear the RNG interrupt status flags. * @param __HANDLE__: RNG Handle * @param __INTERRUPT__: specifies the RNG interrupt status flag to clear. * This parameter can be one of the following values: * @arg RNG_IT_CEI: Clock error interrupt * @arg RNG_IT_SEI: Seed error interrupt * @note RNG_IT_DRDY flag is read-only, reading RNG_DR register automatically clears RNG_IT_DRDY. * @retval None */ #define __HAL_RNG_CLEAR_IT(__HANDLE__, __INTERRUPT__) (((__HANDLE__)->Instance->SR) = ~(__INTERRUPT__)) /** * @} */ /* Exported functions --------------------------------------------------------*/ /** @defgroup RNG_Exported_Functions RNG Exported Functions * @{ */ /** @defgroup RNG_Exported_Functions_Group1 Initialization and de-initialization functions * @{ */ HAL_StatusTypeDef HAL_RNG_Init(RNG_HandleTypeDef *hrng); HAL_StatusTypeDef HAL_RNG_DeInit (RNG_HandleTypeDef *hrng); void HAL_RNG_MspInit(RNG_HandleTypeDef *hrng); void HAL_RNG_MspDeInit(RNG_HandleTypeDef *hrng); /** * @} */ /** @defgroup RNG_Exported_Functions_Group2 Peripheral Control functions * @{ */ uint32_t HAL_RNG_GetRandomNumber(RNG_HandleTypeDef *hrng); /* Obsolete, use HAL_RNG_GenerateRandomNumber() instead */ uint32_t HAL_RNG_GetRandomNumber_IT(RNG_HandleTypeDef *hrng); /* Obsolete, use HAL_RNG_GenerateRandomNumber_IT() instead */ HAL_StatusTypeDef HAL_RNG_GenerateRandomNumber(RNG_HandleTypeDef *hrng, uint32_t *random32bit); HAL_StatusTypeDef HAL_RNG_GenerateRandomNumber_IT(RNG_HandleTypeDef *hrng); uint32_t HAL_RNG_ReadLastRandomNumber(RNG_HandleTypeDef *hrng); void HAL_RNG_IRQHandler(RNG_HandleTypeDef *hrng); void HAL_RNG_ErrorCallback(RNG_HandleTypeDef *hrng); void HAL_RNG_ReadyDataCallback(RNG_HandleTypeDef* hrng, uint32_t random32bit); /** * @} */ /** @defgroup RNG_Exported_Functions_Group3 Peripheral State functions * @{ */ HAL_RNG_StateTypeDef HAL_RNG_GetState(RNG_HandleTypeDef *hrng); /** * @} */ /** * @} */ /* Private types -------------------------------------------------------------*/ /** @defgroup RNG_Private_Types RNG Private Types * @{ */ /** * @} */ /* Private defines -----------------------------------------------------------*/ /** @defgroup RNG_Private_Defines RNG Private Defines * @{ */ /** * @} */ /* Private variables ---------------------------------------------------------*/ /** @defgroup RNG_Private_Variables RNG Private Variables * @{ */ /** * @} */ /* Private constants ---------------------------------------------------------*/ /** @defgroup RNG_Private_Constants RNG Private Constants * @{ */ /** * @} */ /* Private macros ------------------------------------------------------------*/ /** @defgroup RNG_Private_Macros RNG Private Macros * @{ */ #define IS_RNG_IT(IT) (((IT) == RNG_IT_CEI) || \ ((IT) == RNG_IT_SEI)) #define IS_RNG_FLAG(FLAG) (((FLAG) == RNG_FLAG_DRDY) || \ ((FLAG) == RNG_FLAG_CECS) || \ ((FLAG) == RNG_FLAG_SECS)) /** * @} */ /* Private functions prototypes ----------------------------------------------*/ /** @defgroup RNG_Private_Functions_Prototypes RNG Private Functions Prototypes * @{ */ /** * @} */ /* Private functions ---------------------------------------------------------*/ /** @defgroup RNG_Private_Functions RNG Private Functions * @{ */ /** * @} */ /** * @} */ /** * @} */ #endif /* STM32F405xx || STM32F415xx || STM32F407xx || STM32F417xx || STM32F427xx || STM32F437xx ||\ STM32F429xx || STM32F439xx || STM32F410xx || STM32F469xx || STM32F479xx */ #ifdef __cplusplus } #endif #endif /* __STM32F4xx_HAL_RNG_H */ /************************ (C) COPYRIGHT STMicroelectronics *****END OF FILE****/ ================================================ FILE: Zelig/mbed/TARGET_NUCLEO_F411RE/stm32f4xx_hal_rtc.h ================================================ /** ****************************************************************************** * @file stm32f4xx_hal_rtc.h * @author MCD Application Team * @version V1.4.1 * @date 09-October-2015 * @brief Header file of RTC HAL module. ****************************************************************************** * @attention * *

© COPYRIGHT(c) 2015 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. * ****************************************************************************** */ /* Define to prevent recursive inclusion -------------------------------------*/ #ifndef __STM32F4xx_HAL_RTC_H #define __STM32F4xx_HAL_RTC_H #ifdef __cplusplus extern "C" { #endif /* Includes ------------------------------------------------------------------*/ #include "stm32f4xx_hal_def.h" /** @addtogroup STM32F4xx_HAL_Driver * @{ */ /** @addtogroup RTC * @{ */ /* Exported types ------------------------------------------------------------*/ /** @defgroup RTC_Exported_Types RTC Exported Types * @{ */ /** * @brief HAL State structures definition */ typedef enum { HAL_RTC_STATE_RESET = 0x00, /*!< RTC not yet initialized or disabled */ HAL_RTC_STATE_READY = 0x01, /*!< RTC initialized and ready for use */ HAL_RTC_STATE_BUSY = 0x02, /*!< RTC process is ongoing */ HAL_RTC_STATE_TIMEOUT = 0x03, /*!< RTC timeout state */ HAL_RTC_STATE_ERROR = 0x04 /*!< RTC error state */ }HAL_RTCStateTypeDef; /** * @brief RTC Configuration Structure definition */ typedef struct { uint32_t HourFormat; /*!< Specifies the RTC Hour Format. This parameter can be a value of @ref RTC_Hour_Formats */ uint32_t AsynchPrediv; /*!< Specifies the RTC Asynchronous Predivider value. This parameter must be a number between Min_Data = 0x00 and Max_Data = 0x7F */ uint32_t SynchPrediv; /*!< Specifies the RTC Synchronous Predivider value. This parameter must be a number between Min_Data = 0x00 and Max_Data = 0x7FFF */ uint32_t OutPut; /*!< Specifies which signal will be routed to the RTC output. This parameter can be a value of @ref RTC_Output_selection_Definitions */ uint32_t OutPutPolarity; /*!< Specifies the polarity of the output signal. This parameter can be a value of @ref RTC_Output_Polarity_Definitions */ uint32_t OutPutType; /*!< Specifies the RTC Output Pin mode. This parameter can be a value of @ref RTC_Output_Type_ALARM_OUT */ }RTC_InitTypeDef; /** * @brief RTC Time structure definition */ typedef struct { uint8_t Hours; /*!< Specifies the RTC Time Hour. This parameter must be a number between Min_Data = 0 and Max_Data = 12 if the RTC_HourFormat_12 is selected. This parameter must be a number between Min_Data = 0 and Max_Data = 23 if the RTC_HourFormat_24 is selected */ uint8_t Minutes; /*!< Specifies the RTC Time Minutes. This parameter must be a number between Min_Data = 0 and Max_Data = 59 */ uint8_t Seconds; /*!< Specifies the RTC Time Seconds. This parameter must be a number between Min_Data = 0 and Max_Data = 59 */ uint8_t TimeFormat; /*!< Specifies the RTC AM/PM Time. This parameter can be a value of @ref RTC_AM_PM_Definitions */ uint32_t SubSeconds; /*!< Specifies the RTC_SSR RTC Sub Second register content. This parameter corresponds to a time unit range between [0-1] Second with [1 Sec / SecondFraction +1] granularity */ uint32_t SecondFraction; /*!< Specifies the range or granularity of Sub Second register content corresponding to Synchronous pre-scaler factor value (PREDIV_S) This parameter corresponds to a time unit range between [0-1] Second with [1 Sec / SecondFraction +1] granularity. This field will be used only by HAL_RTC_GetTime function */ uint32_t DayLightSaving; /*!< Specifies DayLight Save Operation. This parameter can be a value of @ref RTC_DayLightSaving_Definitions */ uint32_t StoreOperation; /*!< Specifies RTC_StoreOperation value to be written in the BCK bit in CR register to store the operation. This parameter can be a value of @ref RTC_StoreOperation_Definitions */ }RTC_TimeTypeDef; /** * @brief RTC Date structure definition */ typedef struct { uint8_t WeekDay; /*!< Specifies the RTC Date WeekDay. This parameter can be a value of @ref RTC_WeekDay_Definitions */ uint8_t Month; /*!< Specifies the RTC Date Month (in BCD format). This parameter can be a value of @ref RTC_Month_Date_Definitions */ uint8_t Date; /*!< Specifies the RTC Date. This parameter must be a number between Min_Data = 1 and Max_Data = 31 */ uint8_t Year; /*!< Specifies the RTC Date Year. This parameter must be a number between Min_Data = 0 and Max_Data = 99 */ }RTC_DateTypeDef; /** * @brief RTC Alarm structure definition */ typedef struct { RTC_TimeTypeDef AlarmTime; /*!< Specifies the RTC Alarm Time members */ uint32_t AlarmMask; /*!< Specifies the RTC Alarm Masks. This parameter can be a value of @ref RTC_AlarmMask_Definitions */ uint32_t AlarmSubSecondMask; /*!< Specifies the RTC Alarm SubSeconds Masks. This parameter can be a value of @ref RTC_Alarm_Sub_Seconds_Masks_Definitions */ uint32_t AlarmDateWeekDaySel; /*!< Specifies the RTC Alarm is on Date or WeekDay. This parameter can be a value of @ref RTC_AlarmDateWeekDay_Definitions */ uint8_t AlarmDateWeekDay; /*!< Specifies the RTC Alarm Date/WeekDay. If the Alarm Date is selected, this parameter must be set to a value in the 1-31 range. If the Alarm WeekDay is selected, this parameter can be a value of @ref RTC_WeekDay_Definitions */ uint32_t Alarm; /*!< Specifies the alarm . This parameter can be a value of @ref RTC_Alarms_Definitions */ }RTC_AlarmTypeDef; /** * @brief RTC Handle Structure definition */ typedef struct { RTC_TypeDef *Instance; /*!< Register base address */ RTC_InitTypeDef Init; /*!< RTC required parameters */ HAL_LockTypeDef Lock; /*!< RTC locking object */ __IO HAL_RTCStateTypeDef State; /*!< Time communication state */ }RTC_HandleTypeDef; /** * @} */ /* Exported constants --------------------------------------------------------*/ /** @defgroup RTC_Exported_Constants RTC Exported Constants * @{ */ /** @defgroup RTC_Hour_Formats RTC Hour Formats * @{ */ #define RTC_HOURFORMAT_24 ((uint32_t)0x00000000) #define RTC_HOURFORMAT_12 ((uint32_t)0x00000040) /** * @} */ /** @defgroup RTC_Output_selection_Definitions RTC Output Selection Definitions * @{ */ #define RTC_OUTPUT_DISABLE ((uint32_t)0x00000000) #define RTC_OUTPUT_ALARMA ((uint32_t)0x00200000) #define RTC_OUTPUT_ALARMB ((uint32_t)0x00400000) #define RTC_OUTPUT_WAKEUP ((uint32_t)0x00600000) /** * @} */ /** @defgroup RTC_Output_Polarity_Definitions RTC Output Polarity Definitions * @{ */ #define RTC_OUTPUT_POLARITY_HIGH ((uint32_t)0x00000000) #define RTC_OUTPUT_POLARITY_LOW ((uint32_t)0x00100000) /** * @} */ /** @defgroup RTC_Output_Type_ALARM_OUT RTC Output Type ALARM OUT * @{ */ #define RTC_OUTPUT_TYPE_OPENDRAIN ((uint32_t)0x00000000) #define RTC_OUTPUT_TYPE_PUSHPULL ((uint32_t)0x00040000) /** * @} */ /** @defgroup RTC_AM_PM_Definitions RTC AM PM Definitions * @{ */ #define RTC_HOURFORMAT12_AM ((uint8_t)0x00) #define RTC_HOURFORMAT12_PM ((uint8_t)0x40) /** * @} */ /** @defgroup RTC_DayLightSaving_Definitions RTC DayLight Saving Definitions * @{ */ #define RTC_DAYLIGHTSAVING_SUB1H ((uint32_t)0x00020000) #define RTC_DAYLIGHTSAVING_ADD1H ((uint32_t)0x00010000) #define RTC_DAYLIGHTSAVING_NONE ((uint32_t)0x00000000) /** * @} */ /** @defgroup RTC_StoreOperation_Definitions RTC Store Operation Definitions * @{ */ #define RTC_STOREOPERATION_RESET ((uint32_t)0x00000000) #define RTC_STOREOPERATION_SET ((uint32_t)0x00040000) /** * @} */ /** @defgroup RTC_Input_parameter_format_definitions RTC Input Parameter Format Definitions * @{ */ #define RTC_FORMAT_BIN ((uint32_t)0x000000000) #define RTC_FORMAT_BCD ((uint32_t)0x000000001) /** * @} */ /** @defgroup RTC_Month_Date_Definitions RTC Month Date Definitions * @{ */ /* Coded in BCD format */ #define RTC_MONTH_JANUARY ((uint8_t)0x01) #define RTC_MONTH_FEBRUARY ((uint8_t)0x02) #define RTC_MONTH_MARCH ((uint8_t)0x03) #define RTC_MONTH_APRIL ((uint8_t)0x04) #define RTC_MONTH_MAY ((uint8_t)0x05) #define RTC_MONTH_JUNE ((uint8_t)0x06) #define RTC_MONTH_JULY ((uint8_t)0x07) #define RTC_MONTH_AUGUST ((uint8_t)0x08) #define RTC_MONTH_SEPTEMBER ((uint8_t)0x09) #define RTC_MONTH_OCTOBER ((uint8_t)0x10) #define RTC_MONTH_NOVEMBER ((uint8_t)0x11) #define RTC_MONTH_DECEMBER ((uint8_t)0x12) /** * @} */ /** @defgroup RTC_WeekDay_Definitions RTC WeekDay Definitions * @{ */ #define RTC_WEEKDAY_MONDAY ((uint8_t)0x01) #define RTC_WEEKDAY_TUESDAY ((uint8_t)0x02) #define RTC_WEEKDAY_WEDNESDAY ((uint8_t)0x03) #define RTC_WEEKDAY_THURSDAY ((uint8_t)0x04) #define RTC_WEEKDAY_FRIDAY ((uint8_t)0x05) #define RTC_WEEKDAY_SATURDAY ((uint8_t)0x06) #define RTC_WEEKDAY_SUNDAY ((uint8_t)0x07) /** * @} */ /** @defgroup RTC_AlarmDateWeekDay_Definitions RTC Alarm Date WeekDay Definitions * @{ */ #define RTC_ALARMDATEWEEKDAYSEL_DATE ((uint32_t)0x00000000) #define RTC_ALARMDATEWEEKDAYSEL_WEEKDAY ((uint32_t)0x40000000) /** * @} */ /** @defgroup RTC_AlarmMask_Definitions RTC Alarm Mask Definitions * @{ */ #define RTC_ALARMMASK_NONE ((uint32_t)0x00000000) #define RTC_ALARMMASK_DATEWEEKDAY RTC_ALRMAR_MSK4 #define RTC_ALARMMASK_HOURS RTC_ALRMAR_MSK3 #define RTC_ALARMMASK_MINUTES RTC_ALRMAR_MSK2 #define RTC_ALARMMASK_SECONDS RTC_ALRMAR_MSK1 #define RTC_ALARMMASK_ALL ((uint32_t)0x80808080) /** * @} */ /** @defgroup RTC_Alarms_Definitions RTC Alarms Definitions * @{ */ #define RTC_ALARM_A RTC_CR_ALRAE #define RTC_ALARM_B RTC_CR_ALRBE /** * @} */ /** @defgroup RTC_Alarm_Sub_Seconds_Masks_Definitions RTC Alarm Sub Seconds Masks Definitions * @{ */ #define RTC_ALARMSUBSECONDMASK_ALL ((uint32_t)0x00000000) /*!< All Alarm SS fields are masked. There is no comparison on sub seconds for Alarm */ #define RTC_ALARMSUBSECONDMASK_SS14_1 ((uint32_t)0x01000000) /*!< SS[14:1] are don't care in Alarm comparison. Only SS[0] is compared. */ #define RTC_ALARMSUBSECONDMASK_SS14_2 ((uint32_t)0x02000000) /*!< SS[14:2] are don't care in Alarm comparison. Only SS[1:0] are compared */ #define RTC_ALARMSUBSECONDMASK_SS14_3 ((uint32_t)0x03000000) /*!< SS[14:3] are don't care in Alarm comparison. Only SS[2:0] are compared */ #define RTC_ALARMSUBSECONDMASK_SS14_4 ((uint32_t)0x04000000) /*!< SS[14:4] are don't care in Alarm comparison. Only SS[3:0] are compared */ #define RTC_ALARMSUBSECONDMASK_SS14_5 ((uint32_t)0x05000000) /*!< SS[14:5] are don't care in Alarm comparison. Only SS[4:0] are compared */ #define RTC_ALARMSUBSECONDMASK_SS14_6 ((uint32_t)0x06000000) /*!< SS[14:6] are don't care in Alarm comparison. Only SS[5:0] are compared */ #define RTC_ALARMSUBSECONDMASK_SS14_7 ((uint32_t)0x07000000) /*!< SS[14:7] are don't care in Alarm comparison. Only SS[6:0] are compared */ #define RTC_ALARMSUBSECONDMASK_SS14_8 ((uint32_t)0x08000000) /*!< SS[14:8] are don't care in Alarm comparison. Only SS[7:0] are compared */ #define RTC_ALARMSUBSECONDMASK_SS14_9 ((uint32_t)0x09000000) /*!< SS[14:9] are don't care in Alarm comparison. Only SS[8:0] are compared */ #define RTC_ALARMSUBSECONDMASK_SS14_10 ((uint32_t)0x0A000000) /*!< SS[14:10] are don't care in Alarm comparison. Only SS[9:0] are compared */ #define RTC_ALARMSUBSECONDMASK_SS14_11 ((uint32_t)0x0B000000) /*!< SS[14:11] are don't care in Alarm comparison. Only SS[10:0] are compared */ #define RTC_ALARMSUBSECONDMASK_SS14_12 ((uint32_t)0x0C000000) /*!< SS[14:12] are don't care in Alarm comparison.Only SS[11:0] are compared */ #define RTC_ALARMSUBSECONDMASK_SS14_13 ((uint32_t)0x0D000000) /*!< SS[14:13] are don't care in Alarm comparison. Only SS[12:0] are compared */ #define RTC_ALARMSUBSECONDMASK_SS14 ((uint32_t)0x0E000000) /*!< SS[14] is don't care in Alarm comparison.Only SS[13:0] are compared */ #define RTC_ALARMSUBSECONDMASK_NONE ((uint32_t)0x0F000000) /*!< SS[14:0] are compared and must match to activate alarm. */ /** * @} */ /** @defgroup RTC_Interrupts_Definitions RTC Interrupts Definitions * @{ */ #define RTC_IT_TS ((uint32_t)0x00008000) #define RTC_IT_WUT ((uint32_t)0x00004000) #define RTC_IT_ALRB ((uint32_t)0x00002000) #define RTC_IT_ALRA ((uint32_t)0x00001000) #define RTC_IT_TAMP ((uint32_t)0x00000004) /* Used only to Enable the Tamper Interrupt */ #define RTC_IT_TAMP1 ((uint32_t)0x00020000) #define RTC_IT_TAMP2 ((uint32_t)0x00040000) /** * @} */ /** @defgroup RTC_Flags_Definitions RTC Flags Definitions * @{ */ #define RTC_FLAG_RECALPF ((uint32_t)0x00010000) #define RTC_FLAG_TAMP2F ((uint32_t)0x00004000) #define RTC_FLAG_TAMP1F ((uint32_t)0x00002000) #define RTC_FLAG_TSOVF ((uint32_t)0x00001000) #define RTC_FLAG_TSF ((uint32_t)0x00000800) #define RTC_FLAG_WUTF ((uint32_t)0x00000400) #define RTC_FLAG_ALRBF ((uint32_t)0x00000200) #define RTC_FLAG_ALRAF ((uint32_t)0x00000100) #define RTC_FLAG_INITF ((uint32_t)0x00000040) #define RTC_FLAG_RSF ((uint32_t)0x00000020) #define RTC_FLAG_INITS ((uint32_t)0x00000010) #define RTC_FLAG_SHPF ((uint32_t)0x00000008) #define RTC_FLAG_WUTWF ((uint32_t)0x00000004) #define RTC_FLAG_ALRBWF ((uint32_t)0x00000002) #define RTC_FLAG_ALRAWF ((uint32_t)0x00000001) /** * @} */ /** * @} */ /* Exported macro ------------------------------------------------------------*/ /** @defgroup RTC_Exported_Macros RTC Exported Macros * @{ */ /** @brief Reset RTC handle state * @param __HANDLE__: specifies the RTC handle. * @retval None */ #define __HAL_RTC_RESET_HANDLE_STATE(__HANDLE__) ((__HANDLE__)->State = HAL_RTC_STATE_RESET) /** * @brief Disable the write protection for RTC registers. * @param __HANDLE__: specifies the RTC handle. * @retval None */ #define __HAL_RTC_WRITEPROTECTION_DISABLE(__HANDLE__) \ do{ \ (__HANDLE__)->Instance->WPR = 0xCA; \ (__HANDLE__)->Instance->WPR = 0x53; \ } while(0) /** * @brief Enable the write protection for RTC registers. * @param __HANDLE__: specifies the RTC handle. * @retval None */ #define __HAL_RTC_WRITEPROTECTION_ENABLE(__HANDLE__) \ do{ \ (__HANDLE__)->Instance->WPR = 0xFF; \ } while(0) /** * @brief Enable the RTC ALARMA peripheral. * @param __HANDLE__: specifies the RTC handle. * @retval None */ #define __HAL_RTC_ALARMA_ENABLE(__HANDLE__) ((__HANDLE__)->Instance->CR |= (RTC_CR_ALRAE)) /** * @brief Disable the RTC ALARMA peripheral. * @param __HANDLE__: specifies the RTC handle. * @retval None */ #define __HAL_RTC_ALARMA_DISABLE(__HANDLE__) ((__HANDLE__)->Instance->CR &= ~(RTC_CR_ALRAE)) /** * @brief Enable the RTC ALARMB peripheral. * @param __HANDLE__: specifies the RTC handle. * @retval None */ #define __HAL_RTC_ALARMB_ENABLE(__HANDLE__) ((__HANDLE__)->Instance->CR |= (RTC_CR_ALRBE)) /** * @brief Disable the RTC ALARMB peripheral. * @param __HANDLE__: specifies the RTC handle. * @retval None */ #define __HAL_RTC_ALARMB_DISABLE(__HANDLE__) ((__HANDLE__)->Instance->CR &= ~(RTC_CR_ALRBE)) /** * @brief Enable the RTC Alarm interrupt. * @param __HANDLE__: specifies the RTC handle. * @param __INTERRUPT__: specifies the RTC Alarm interrupt sources to be enabled or disabled. * This parameter can be any combination of the following values: * @arg RTC_IT_ALRA: Alarm A interrupt * @arg RTC_IT_ALRB: Alarm B interrupt * @retval None */ #define __HAL_RTC_ALARM_ENABLE_IT(__HANDLE__, __INTERRUPT__) ((__HANDLE__)->Instance->CR |= (__INTERRUPT__)) /** * @brief Disable the RTC Alarm interrupt. * @param __HANDLE__: specifies the RTC handle. * @param __INTERRUPT__: specifies the RTC Alarm interrupt sources to be enabled or disabled. * This parameter can be any combination of the following values: * @arg RTC_IT_ALRA: Alarm A interrupt * @arg RTC_IT_ALRB: Alarm B interrupt * @retval None */ #define __HAL_RTC_ALARM_DISABLE_IT(__HANDLE__, __INTERRUPT__) ((__HANDLE__)->Instance->CR &= ~(__INTERRUPT__)) /** * @brief Check whether the specified RTC Alarm interrupt has occurred or not. * @param __HANDLE__: specifies the RTC handle. * @param __INTERRUPT__: specifies the RTC Alarm interrupt to check. * This parameter can be: * @arg RTC_IT_ALRA: Alarm A interrupt * @arg RTC_IT_ALRB: Alarm B interrupt * @retval None */ #define __HAL_RTC_ALARM_GET_IT(__HANDLE__, __INTERRUPT__) (((((__HANDLE__)->Instance->ISR)& ((__INTERRUPT__)>> 4)) != RESET)? SET : RESET) /** * @brief Get the selected RTC Alarm's flag status. * @param __HANDLE__: specifies the RTC handle. * @param __FLAG__: specifies the RTC Alarm Flag to check. * This parameter can be: * @arg RTC_FLAG_ALRAF * @arg RTC_FLAG_ALRBF * @arg RTC_FLAG_ALRAWF * @arg RTC_FLAG_ALRBWF * @retval None */ #define __HAL_RTC_ALARM_GET_FLAG(__HANDLE__, __FLAG__) (((((__HANDLE__)->Instance->ISR) & (__FLAG__)) != RESET)? SET : RESET) /** * @brief Clear the RTC Alarm's pending flags. * @param __HANDLE__: specifies the RTC handle. * @param __FLAG__: specifies the RTC Alarm Flag sources to be enabled or disabled. * This parameter can be: * @arg RTC_FLAG_ALRAF * @arg RTC_FLAG_ALRBF * @retval None */ #define __HAL_RTC_ALARM_CLEAR_FLAG(__HANDLE__, __FLAG__) ((__HANDLE__)->Instance->ISR) = (~((__FLAG__) | RTC_ISR_INIT)|((__HANDLE__)->Instance->ISR & RTC_ISR_INIT)) /** * @brief Check whether the specified RTC Alarm interrupt has been enabled or not. * @param __HANDLE__: specifies the RTC handle. * @param __INTERRUPT__: specifies the RTC Alarm interrupt sources to check. * This parameter can be: * @arg RTC_IT_ALRA: Alarm A interrupt * @arg RTC_IT_ALRB: Alarm B interrupt * @retval None */ #define __HAL_RTC_ALARM_GET_IT_SOURCE(__HANDLE__, __INTERRUPT__) (((((__HANDLE__)->Instance->CR) & (__INTERRUPT__)) != RESET) ? SET : RESET) /** * @brief Enable interrupt on the RTC Alarm associated Exti line. * @retval None */ #define __HAL_RTC_ALARM_EXTI_ENABLE_IT() (EXTI->IMR |= RTC_EXTI_LINE_ALARM_EVENT) /** * @brief Disable interrupt on the RTC Alarm associated Exti line. * @retval None */ #define __HAL_RTC_ALARM_EXTI_DISABLE_IT() (EXTI->IMR &= ~(RTC_EXTI_LINE_ALARM_EVENT)) /** * @brief Enable event on the RTC Alarm associated Exti line. * @retval None. */ #define __HAL_RTC_ALARM_EXTI_ENABLE_EVENT() (EXTI->EMR |= RTC_EXTI_LINE_ALARM_EVENT) /** * @brief Disable event on the RTC Alarm associated Exti line. * @retval None. */ #define __HAL_RTC_ALARM_EXTI_DISABLE_EVENT() (EXTI->EMR &= ~(RTC_EXTI_LINE_ALARM_EVENT)) /** * @brief Enable falling edge trigger on the RTC Alarm associated Exti line. * @retval None. */ #define __HAL_RTC_ALARM_EXTI_ENABLE_FALLING_EDGE() (EXTI->FTSR |= RTC_EXTI_LINE_ALARM_EVENT) /** * @brief Disable falling edge trigger on the RTC Alarm associated Exti line. * @retval None. */ #define __HAL_RTC_ALARM_EXTI_DISABLE_FALLING_EDGE() (EXTI->FTSR &= ~(RTC_EXTI_LINE_ALARM_EVENT)) /** * @brief Enable rising edge trigger on the RTC Alarm associated Exti line. * @retval None. */ #define __HAL_RTC_ALARM_EXTI_ENABLE_RISING_EDGE() (EXTI->RTSR |= RTC_EXTI_LINE_ALARM_EVENT) /** * @brief Disable rising edge trigger on the RTC Alarm associated Exti line. * @retval None. */ #define __HAL_RTC_ALARM_EXTI_DISABLE_RISING_EDGE() (EXTI->RTSR &= ~(RTC_EXTI_LINE_ALARM_EVENT)) /** * @brief Enable rising & falling edge trigger on the RTC Alarm associated Exti line. * @retval None. */ #define __HAL_RTC_ALARM_EXTI_ENABLE_RISING_FALLING_EDGE() __HAL_RTC_ALARM_EXTI_ENABLE_RISING_EDGE();__HAL_RTC_ALARM_EXTI_ENABLE_FALLING_EDGE(); /** * @brief Disable rising & falling edge trigger on the RTC Alarm associated Exti line. * @retval None. */ #define __HAL_RTC_ALARM_EXTI_DISABLE_RISING_FALLING_EDGE() __HAL_RTC_ALARM_EXTI_DISABLE_RISING_EDGE();__HAL_RTC_ALARM_EXTI_DISABLE_FALLING_EDGE(); /** * @brief Check whether the RTC Alarm associated Exti line interrupt flag is set or not. * @retval Line Status. */ #define __HAL_RTC_ALARM_EXTI_GET_FLAG() (EXTI->PR & RTC_EXTI_LINE_ALARM_EVENT) /** * @brief Clear the RTC Alarm associated Exti line flag. * @retval None. */ #define __HAL_RTC_ALARM_EXTI_CLEAR_FLAG() (EXTI->PR = RTC_EXTI_LINE_ALARM_EVENT) /** * @brief Generate a Software interrupt on RTC Alarm associated Exti line. * @retval None. */ #define __HAL_RTC_ALARM_EXTI_GENERATE_SWIT() (EXTI->SWIER |= RTC_EXTI_LINE_ALARM_EVENT) /** * @} */ /* Include RTC HAL Extension module */ #include "stm32f4xx_hal_rtc_ex.h" /* Exported functions --------------------------------------------------------*/ /** @addtogroup RTC_Exported_Functions * @{ */ /** @addtogroup RTC_Exported_Functions_Group1 * @{ */ /* Initialization and de-initialization functions ****************************/ HAL_StatusTypeDef HAL_RTC_Init(RTC_HandleTypeDef *hrtc); HAL_StatusTypeDef HAL_RTC_DeInit(RTC_HandleTypeDef *hrtc); void HAL_RTC_MspInit(RTC_HandleTypeDef *hrtc); void HAL_RTC_MspDeInit(RTC_HandleTypeDef *hrtc); /** * @} */ /** @addtogroup RTC_Exported_Functions_Group2 * @{ */ /* RTC Time and Date functions ************************************************/ HAL_StatusTypeDef HAL_RTC_SetTime(RTC_HandleTypeDef *hrtc, RTC_TimeTypeDef *sTime, uint32_t Format); HAL_StatusTypeDef HAL_RTC_GetTime(RTC_HandleTypeDef *hrtc, RTC_TimeTypeDef *sTime, uint32_t Format); HAL_StatusTypeDef HAL_RTC_SetDate(RTC_HandleTypeDef *hrtc, RTC_DateTypeDef *sDate, uint32_t Format); HAL_StatusTypeDef HAL_RTC_GetDate(RTC_HandleTypeDef *hrtc, RTC_DateTypeDef *sDate, uint32_t Format); /** * @} */ /** @addtogroup RTC_Exported_Functions_Group3 * @{ */ /* RTC Alarm functions ********************************************************/ HAL_StatusTypeDef HAL_RTC_SetAlarm(RTC_HandleTypeDef *hrtc, RTC_AlarmTypeDef *sAlarm, uint32_t Format); HAL_StatusTypeDef HAL_RTC_SetAlarm_IT(RTC_HandleTypeDef *hrtc, RTC_AlarmTypeDef *sAlarm, uint32_t Format); HAL_StatusTypeDef HAL_RTC_DeactivateAlarm(RTC_HandleTypeDef *hrtc, uint32_t Alarm); HAL_StatusTypeDef HAL_RTC_GetAlarm(RTC_HandleTypeDef *hrtc, RTC_AlarmTypeDef *sAlarm, uint32_t Alarm, uint32_t Format); void HAL_RTC_AlarmIRQHandler(RTC_HandleTypeDef *hrtc); HAL_StatusTypeDef HAL_RTC_PollForAlarmAEvent(RTC_HandleTypeDef *hrtc, uint32_t Timeout); void HAL_RTC_AlarmAEventCallback(RTC_HandleTypeDef *hrtc); /** * @} */ /** @addtogroup RTC_Exported_Functions_Group4 * @{ */ /* Peripheral Control functions ***********************************************/ HAL_StatusTypeDef HAL_RTC_WaitForSynchro(RTC_HandleTypeDef* hrtc); /** * @} */ /** @addtogroup RTC_Exported_Functions_Group5 * @{ */ /* Peripheral State functions *************************************************/ HAL_RTCStateTypeDef HAL_RTC_GetState(RTC_HandleTypeDef *hrtc); /** * @} */ /** * @} */ /* Private types -------------------------------------------------------------*/ /* Private variables ---------------------------------------------------------*/ /* Private constants ---------------------------------------------------------*/ /** @defgroup RTC_Private_Constants RTC Private Constants * @{ */ /* Masks Definition */ #define RTC_TR_RESERVED_MASK ((uint32_t)0x007F7F7F) #define RTC_DR_RESERVED_MASK ((uint32_t)0x00FFFF3F) #define RTC_INIT_MASK ((uint32_t)0xFFFFFFFF) #define RTC_RSF_MASK ((uint32_t)0xFFFFFF5F) #define RTC_FLAGS_MASK ((uint32_t)(RTC_FLAG_TSOVF | RTC_FLAG_TSF | RTC_FLAG_WUTF | \ RTC_FLAG_ALRBF | RTC_FLAG_ALRAF | RTC_FLAG_INITF | \ RTC_FLAG_RSF | RTC_FLAG_INITS | RTC_FLAG_WUTWF | \ RTC_FLAG_ALRBWF | RTC_FLAG_ALRAWF | RTC_FLAG_TAMP1F | \ RTC_FLAG_RECALPF | RTC_FLAG_SHPF)) #define RTC_TIMEOUT_VALUE 1000 #define RTC_EXTI_LINE_ALARM_EVENT ((uint32_t)EXTI_IMR_MR17) /*!< External interrupt line 17 Connected to the RTC Alarm event */ /** * @} */ /* Private macros ------------------------------------------------------------*/ /** @defgroup RTC_Private_Macros RTC Private Macros * @{ */ /** @defgroup RTC_IS_RTC_Definitions RTC Private macros to check input parameters * @{ */ #define IS_RTC_HOUR_FORMAT(FORMAT) (((FORMAT) == RTC_HOURFORMAT_12) || \ ((FORMAT) == RTC_HOURFORMAT_24)) #define IS_RTC_OUTPUT(OUTPUT) (((OUTPUT) == RTC_OUTPUT_DISABLE) || \ ((OUTPUT) == RTC_OUTPUT_ALARMA) || \ ((OUTPUT) == RTC_OUTPUT_ALARMB) || \ ((OUTPUT) == RTC_OUTPUT_WAKEUP)) #define IS_RTC_OUTPUT_POL(POL) (((POL) == RTC_OUTPUT_POLARITY_HIGH) || \ ((POL) == RTC_OUTPUT_POLARITY_LOW)) #define IS_RTC_OUTPUT_TYPE(TYPE) (((TYPE) == RTC_OUTPUT_TYPE_OPENDRAIN) || \ ((TYPE) == RTC_OUTPUT_TYPE_PUSHPULL)) #define IS_RTC_HOUR12(HOUR) (((HOUR) > (uint32_t)0) && ((HOUR) <= (uint32_t)12)) #define IS_RTC_HOUR24(HOUR) ((HOUR) <= (uint32_t)23) #define IS_RTC_ASYNCH_PREDIV(PREDIV) ((PREDIV) <= (uint32_t)0x7F) #define IS_RTC_SYNCH_PREDIV(PREDIV) ((PREDIV) <= (uint32_t)0x7FFF) #define IS_RTC_MINUTES(MINUTES) ((MINUTES) <= (uint32_t)59) #define IS_RTC_SECONDS(SECONDS) ((SECONDS) <= (uint32_t)59) #define IS_RTC_HOURFORMAT12(PM) (((PM) == RTC_HOURFORMAT12_AM) || ((PM) == RTC_HOURFORMAT12_PM)) #define IS_RTC_DAYLIGHT_SAVING(SAVE) (((SAVE) == RTC_DAYLIGHTSAVING_SUB1H) || \ ((SAVE) == RTC_DAYLIGHTSAVING_ADD1H) || \ ((SAVE) == RTC_DAYLIGHTSAVING_NONE)) #define IS_RTC_STORE_OPERATION(OPERATION) (((OPERATION) == RTC_STOREOPERATION_RESET) || \ ((OPERATION) == RTC_STOREOPERATION_SET)) #define IS_RTC_FORMAT(FORMAT) (((FORMAT) == RTC_FORMAT_BIN) || ((FORMAT) == RTC_FORMAT_BCD)) #define IS_RTC_YEAR(YEAR) ((YEAR) <= (uint32_t)99) #define IS_RTC_MONTH(MONTH) (((MONTH) >= (uint32_t)1) && ((MONTH) <= (uint32_t)12)) #define IS_RTC_DATE(DATE) (((DATE) >= (uint32_t)1) && ((DATE) <= (uint32_t)31)) #define IS_RTC_WEEKDAY(WEEKDAY) (((WEEKDAY) == RTC_WEEKDAY_MONDAY) || \ ((WEEKDAY) == RTC_WEEKDAY_TUESDAY) || \ ((WEEKDAY) == RTC_WEEKDAY_WEDNESDAY) || \ ((WEEKDAY) == RTC_WEEKDAY_THURSDAY) || \ ((WEEKDAY) == RTC_WEEKDAY_FRIDAY) || \ ((WEEKDAY) == RTC_WEEKDAY_SATURDAY) || \ ((WEEKDAY) == RTC_WEEKDAY_SUNDAY)) #define IS_RTC_ALARM_DATE_WEEKDAY_DATE(DATE) (((DATE) >(uint32_t) 0) && ((DATE) <= (uint32_t)31)) #define IS_RTC_ALARM_DATE_WEEKDAY_WEEKDAY(WEEKDAY) (((WEEKDAY) == RTC_WEEKDAY_MONDAY) || \ ((WEEKDAY) == RTC_WEEKDAY_TUESDAY) || \ ((WEEKDAY) == RTC_WEEKDAY_WEDNESDAY) || \ ((WEEKDAY) == RTC_WEEKDAY_THURSDAY) || \ ((WEEKDAY) == RTC_WEEKDAY_FRIDAY) || \ ((WEEKDAY) == RTC_WEEKDAY_SATURDAY) || \ ((WEEKDAY) == RTC_WEEKDAY_SUNDAY)) #define IS_RTC_ALARM_DATE_WEEKDAY_SEL(SEL) (((SEL) == RTC_ALARMDATEWEEKDAYSEL_DATE) || \ ((SEL) == RTC_ALARMDATEWEEKDAYSEL_WEEKDAY)) #define IS_RTC_ALARM_MASK(MASK) (((MASK) & 0x7F7F7F7F) == (uint32_t)RESET) #define IS_RTC_ALARM(ALARM) (((ALARM) == RTC_ALARM_A) || ((ALARM) == RTC_ALARM_B)) #define IS_RTC_ALARM_SUB_SECOND_VALUE(VALUE) ((VALUE) <= (uint32_t)0x00007FFF) #define IS_RTC_ALARM_SUB_SECOND_MASK(MASK) (((MASK) == RTC_ALARMSUBSECONDMASK_ALL) || \ ((MASK) == RTC_ALARMSUBSECONDMASK_SS14_1) || \ ((MASK) == RTC_ALARMSUBSECONDMASK_SS14_2) || \ ((MASK) == RTC_ALARMSUBSECONDMASK_SS14_3) || \ ((MASK) == RTC_ALARMSUBSECONDMASK_SS14_4) || \ ((MASK) == RTC_ALARMSUBSECONDMASK_SS14_5) || \ ((MASK) == RTC_ALARMSUBSECONDMASK_SS14_6) || \ ((MASK) == RTC_ALARMSUBSECONDMASK_SS14_7) || \ ((MASK) == RTC_ALARMSUBSECONDMASK_SS14_8) || \ ((MASK) == RTC_ALARMSUBSECONDMASK_SS14_9) || \ ((MASK) == RTC_ALARMSUBSECONDMASK_SS14_10) || \ ((MASK) == RTC_ALARMSUBSECONDMASK_SS14_11) || \ ((MASK) == RTC_ALARMSUBSECONDMASK_SS14_12) || \ ((MASK) == RTC_ALARMSUBSECONDMASK_SS14_13) || \ ((MASK) == RTC_ALARMSUBSECONDMASK_SS14) || \ ((MASK) == RTC_ALARMSUBSECONDMASK_NONE)) /** * @} */ /** * @} */ /* Private functions ---------------------------------------------------------*/ /** @defgroup RTC_Private_Functions RTC Private Functions * @{ */ HAL_StatusTypeDef RTC_EnterInitMode(RTC_HandleTypeDef* hrtc); uint8_t RTC_ByteToBcd2(uint8_t Value); uint8_t RTC_Bcd2ToByte(uint8_t Value); /** * @} */ /** * @} */ /** * @} */ #ifdef __cplusplus } #endif #endif /* __STM32F4xx_HAL_RTC_H */ /************************ (C) COPYRIGHT STMicroelectronics *****END OF FILE****/ ================================================ FILE: Zelig/mbed/TARGET_NUCLEO_F411RE/stm32f4xx_hal_rtc_ex.h ================================================ /** ****************************************************************************** * @file stm32f4xx_hal_rtc_ex.h * @author MCD Application Team * @version V1.4.1 * @date 09-October-2015 * @brief Header file of RTC HAL Extension module. ****************************************************************************** * @attention * *

© COPYRIGHT(c) 2015 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. * ****************************************************************************** */ /* Define to prevent recursive inclusion -------------------------------------*/ #ifndef __STM32F4xx_HAL_RTC_EX_H #define __STM32F4xx_HAL_RTC_EX_H #ifdef __cplusplus extern "C" { #endif /* Includes ------------------------------------------------------------------*/ #include "stm32f4xx_hal_def.h" /** @addtogroup STM32F4xx_HAL_Driver * @{ */ /** @addtogroup RTCEx * @{ */ /* Exported types ------------------------------------------------------------*/ /** @defgroup RTCEx_Exported_Types RTCEx Exported Types * @{ */ /** * @brief RTC Tamper structure definition */ typedef struct { uint32_t Tamper; /*!< Specifies the Tamper Pin. This parameter can be a value of @ref RTCEx_Tamper_Pins_Definitions */ uint32_t PinSelection; /*!< Specifies the Tamper Pin. This parameter can be a value of @ref RTCEx_Tamper_Pins_Selection */ uint32_t Trigger; /*!< Specifies the Tamper Trigger. This parameter can be a value of @ref RTCEx_Tamper_Trigger_Definitions */ uint32_t Filter; /*!< Specifies the RTC Filter Tamper. This parameter can be a value of @ref RTCEx_Tamper_Filter_Definitions */ uint32_t SamplingFrequency; /*!< Specifies the sampling frequency. This parameter can be a value of @ref RTCEx_Tamper_Sampling_Frequencies_Definitions */ uint32_t PrechargeDuration; /*!< Specifies the Precharge Duration . This parameter can be a value of @ref RTCEx_Tamper_Pin_Precharge_Duration_Definitions */ uint32_t TamperPullUp; /*!< Specifies the Tamper PullUp . This parameter can be a value of @ref RTCEx_Tamper_Pull_UP_Definitions */ uint32_t TimeStampOnTamperDetection; /*!< Specifies the TimeStampOnTamperDetection. This parameter can be a value of @ref RTCEx_Tamper_TimeStampOnTamperDetection_Definitions */ }RTC_TamperTypeDef; /** * @} */ /* Exported constants --------------------------------------------------------*/ /** @defgroup RTCEx_Exported_Constants RTCEx Exported Constants * @{ */ /** @defgroup RTCEx_Backup_Registers_Definitions RTC Backup Registers Definitions * @{ */ #define RTC_BKP_DR0 ((uint32_t)0x00000000) #define RTC_BKP_DR1 ((uint32_t)0x00000001) #define RTC_BKP_DR2 ((uint32_t)0x00000002) #define RTC_BKP_DR3 ((uint32_t)0x00000003) #define RTC_BKP_DR4 ((uint32_t)0x00000004) #define RTC_BKP_DR5 ((uint32_t)0x00000005) #define RTC_BKP_DR6 ((uint32_t)0x00000006) #define RTC_BKP_DR7 ((uint32_t)0x00000007) #define RTC_BKP_DR8 ((uint32_t)0x00000008) #define RTC_BKP_DR9 ((uint32_t)0x00000009) #define RTC_BKP_DR10 ((uint32_t)0x0000000A) #define RTC_BKP_DR11 ((uint32_t)0x0000000B) #define RTC_BKP_DR12 ((uint32_t)0x0000000C) #define RTC_BKP_DR13 ((uint32_t)0x0000000D) #define RTC_BKP_DR14 ((uint32_t)0x0000000E) #define RTC_BKP_DR15 ((uint32_t)0x0000000F) #define RTC_BKP_DR16 ((uint32_t)0x00000010) #define RTC_BKP_DR17 ((uint32_t)0x00000011) #define RTC_BKP_DR18 ((uint32_t)0x00000012) #define RTC_BKP_DR19 ((uint32_t)0x00000013) /** * @} */ /** @defgroup RTCEx_Time_Stamp_Edges_definitions RTC TimeStamp Edges Definitions * @{ */ #define RTC_TIMESTAMPEDGE_RISING ((uint32_t)0x00000000) #define RTC_TIMESTAMPEDGE_FALLING ((uint32_t)0x00000008) /** * @} */ /** @defgroup RTCEx_Tamper_Pins_Definitions RTC Tamper Pins Definitions * @{ */ #define RTC_TAMPER_1 RTC_TAFCR_TAMP1E #define RTC_TAMPER_2 RTC_TAFCR_TAMP2E /** * @} */ /** @defgroup RTCEx_Tamper_Pins_Selection RTC tamper Pins Selection * @{ */ #define RTC_TAMPERPIN_DEFAULT ((uint32_t)0x00000000) #define RTC_TAMPERPIN_POS1 ((uint32_t)0x00010000) /** * @} */ /** @defgroup RTCEx_TimeStamp_Pin_Selection RTC TimeStamp Pins Selection * @{ */ #define RTC_TIMESTAMPPIN_DEFAULT ((uint32_t)0x00000000) #define RTC_TIMESTAMPPIN_POS1 ((uint32_t)0x00020000) /** * @} */ /** @defgroup RTCEx_Tamper_Trigger_Definitions RTC Tamper Triggers Definitions * @{ */ #define RTC_TAMPERTRIGGER_RISINGEDGE ((uint32_t)0x00000000) #define RTC_TAMPERTRIGGER_FALLINGEDGE ((uint32_t)0x00000002) #define RTC_TAMPERTRIGGER_LOWLEVEL RTC_TAMPERTRIGGER_RISINGEDGE #define RTC_TAMPERTRIGGER_HIGHLEVEL RTC_TAMPERTRIGGER_FALLINGEDGE /** * @} */ /** @defgroup RTCEx_Tamper_Filter_Definitions RTC Tamper Filter Definitions * @{ */ #define RTC_TAMPERFILTER_DISABLE ((uint32_t)0x00000000) /*!< Tamper filter is disabled */ #define RTC_TAMPERFILTER_2SAMPLE ((uint32_t)0x00000800) /*!< Tamper is activated after 2 consecutive samples at the active level */ #define RTC_TAMPERFILTER_4SAMPLE ((uint32_t)0x00001000) /*!< Tamper is activated after 4 consecutive samples at the active level */ #define RTC_TAMPERFILTER_8SAMPLE ((uint32_t)0x00001800) /*!< Tamper is activated after 8 consecutive samples at the active level. */ /** * @} */ /** @defgroup RTCEx_Tamper_Sampling_Frequencies_Definitions RTC Tamper Sampling Frequencies Definitions * @{ */ #define RTC_TAMPERSAMPLINGFREQ_RTCCLK_DIV32768 ((uint32_t)0x00000000) /*!< Each of the tamper inputs are sampled with a frequency = RTCCLK / 32768 */ #define RTC_TAMPERSAMPLINGFREQ_RTCCLK_DIV16384 ((uint32_t)0x00000100) /*!< Each of the tamper inputs are sampled with a frequency = RTCCLK / 16384 */ #define RTC_TAMPERSAMPLINGFREQ_RTCCLK_DIV8192 ((uint32_t)0x00000200) /*!< Each of the tamper inputs are sampled with a frequency = RTCCLK / 8192 */ #define RTC_TAMPERSAMPLINGFREQ_RTCCLK_DIV4096 ((uint32_t)0x00000300) /*!< Each of the tamper inputs are sampled with a frequency = RTCCLK / 4096 */ #define RTC_TAMPERSAMPLINGFREQ_RTCCLK_DIV2048 ((uint32_t)0x00000400) /*!< Each of the tamper inputs are sampled with a frequency = RTCCLK / 2048 */ #define RTC_TAMPERSAMPLINGFREQ_RTCCLK_DIV1024 ((uint32_t)0x00000500) /*!< Each of the tamper inputs are sampled with a frequency = RTCCLK / 1024 */ #define RTC_TAMPERSAMPLINGFREQ_RTCCLK_DIV512 ((uint32_t)0x00000600) /*!< Each of the tamper inputs are sampled with a frequency = RTCCLK / 512 */ #define RTC_TAMPERSAMPLINGFREQ_RTCCLK_DIV256 ((uint32_t)0x00000700) /*!< Each of the tamper inputs are sampled with a frequency = RTCCLK / 256 */ /** * @} */ /** @defgroup RTCEx_Tamper_Pin_Precharge_Duration_Definitions RTC Tamper Pin Precharge Duration Definitions * @{ */ #define RTC_TAMPERPRECHARGEDURATION_1RTCCLK ((uint32_t)0x00000000) /*!< Tamper pins are pre-charged before sampling during 1 RTCCLK cycle */ #define RTC_TAMPERPRECHARGEDURATION_2RTCCLK ((uint32_t)0x00002000) /*!< Tamper pins are pre-charged before sampling during 2 RTCCLK cycles */ #define RTC_TAMPERPRECHARGEDURATION_4RTCCLK ((uint32_t)0x00004000) /*!< Tamper pins are pre-charged before sampling during 4 RTCCLK cycles */ #define RTC_TAMPERPRECHARGEDURATION_8RTCCLK ((uint32_t)0x00006000) /*!< Tamper pins are pre-charged before sampling during 8 RTCCLK cycles */ /** * @} */ /** @defgroup RTCEx_Tamper_TimeStampOnTamperDetection_Definitions RTC Tamper TimeStamp On Tamper Detection Definitions * @{ */ #define RTC_TIMESTAMPONTAMPERDETECTION_ENABLE ((uint32_t)RTC_TAFCR_TAMPTS) /*!< TimeStamp on Tamper Detection event saved */ #define RTC_TIMESTAMPONTAMPERDETECTION_DISABLE ((uint32_t)0x00000000) /*!< TimeStamp on Tamper Detection event is not saved */ /** * @} */ /** @defgroup RTCEx_Tamper_Pull_UP_Definitions RTC Tamper Pull Up Definitions * @{ */ #define RTC_TAMPER_PULLUP_ENABLE ((uint32_t)0x00000000) /*!< TimeStamp on Tamper Detection event saved */ #define RTC_TAMPER_PULLUP_DISABLE ((uint32_t)RTC_TAFCR_TAMPPUDIS) /*!< TimeStamp on Tamper Detection event is not saved */ /** * @} */ /** @defgroup RTCEx_Wakeup_Timer_Definitions RTC Wake-up Timer Definitions * @{ */ #define RTC_WAKEUPCLOCK_RTCCLK_DIV16 ((uint32_t)0x00000000) #define RTC_WAKEUPCLOCK_RTCCLK_DIV8 ((uint32_t)0x00000001) #define RTC_WAKEUPCLOCK_RTCCLK_DIV4 ((uint32_t)0x00000002) #define RTC_WAKEUPCLOCK_RTCCLK_DIV2 ((uint32_t)0x00000003) #define RTC_WAKEUPCLOCK_CK_SPRE_16BITS ((uint32_t)0x00000004) #define RTC_WAKEUPCLOCK_CK_SPRE_17BITS ((uint32_t)0x00000006) /** * @} */ /** @defgroup RTCEx_Digital_Calibration_Definitions RTC Digital Calib Definitions * @{ */ #define RTC_CALIBSIGN_POSITIVE ((uint32_t)0x00000000) #define RTC_CALIBSIGN_NEGATIVE ((uint32_t)0x00000080) /** * @} */ /** @defgroup RTCEx_Smooth_calib_period_Definitions RTC Smooth Calib Period Definitions * @{ */ #define RTC_SMOOTHCALIB_PERIOD_32SEC ((uint32_t)0x00000000) /*!< If RTCCLK = 32768 Hz, Smooth calibration period is 32s, else 2exp20 RTCCLK seconds */ #define RTC_SMOOTHCALIB_PERIOD_16SEC ((uint32_t)0x00002000) /*!< If RTCCLK = 32768 Hz, Smooth calibration period is 16s, else 2exp19 RTCCLK seconds */ #define RTC_SMOOTHCALIB_PERIOD_8SEC ((uint32_t)0x00004000) /*!< If RTCCLK = 32768 Hz, Smooth calibration period is 8s, else 2exp18 RTCCLK seconds */ /** * @} */ /** @defgroup RTCEx_Smooth_calib_Plus_pulses_Definitions RTC Smooth Calib Plus Pulses Definitions * @{ */ #define RTC_SMOOTHCALIB_PLUSPULSES_SET ((uint32_t)0x00008000) /*!< The number of RTCCLK pulses added during a X -second window = Y - CALM[8:0] with Y = 512, 256, 128 when X = 32, 16, 8 */ #define RTC_SMOOTHCALIB_PLUSPULSES_RESET ((uint32_t)0x00000000) /*!< The number of RTCCLK pulses subbstited during a 32-second window = CALM[8:0] */ /** * @} */ /** @defgroup RTCEx_Add_1_Second_Parameter_Definitions RTC Add 1 Second Parameter Definitions * @{ */ #define RTC_SHIFTADD1S_RESET ((uint32_t)0x00000000) #define RTC_SHIFTADD1S_SET ((uint32_t)0x80000000) /** * @} */ /** @defgroup RTCEx_Calib_Output_selection_Definitions RTC Calib Output Selection Definitions * @{ */ #define RTC_CALIBOUTPUT_512HZ ((uint32_t)0x00000000) #define RTC_CALIBOUTPUT_1HZ ((uint32_t)0x00080000) /** * @} */ /** * @} */ /* Exported macro ------------------------------------------------------------*/ /** @defgroup RTCEx_Exported_Macros RTCEx Exported Macros * @{ */ /* ---------------------------------WAKEUPTIMER---------------------------------*/ /** @defgroup RTCEx_WakeUp_Timer RTC WakeUp Timer * @{ */ /** * @brief Enable the RTC WakeUp Timer peripheral. * @param __HANDLE__: specifies the RTC handle. * @retval None */ #define __HAL_RTC_WAKEUPTIMER_ENABLE(__HANDLE__) ((__HANDLE__)->Instance->CR |= (RTC_CR_WUTE)) /** * @brief Disable the RTC Wake-up Timer peripheral. * @param __HANDLE__: specifies the RTC handle. * @retval None */ #define __HAL_RTC_WAKEUPTIMER_DISABLE(__HANDLE__) ((__HANDLE__)->Instance->CR &= ~(RTC_CR_WUTE)) /** * @brief Enable the RTC WakeUpTimer interrupt. * @param __HANDLE__: specifies the RTC handle. * @param __INTERRUPT__: specifies the RTC WakeUpTimer interrupt sources to be enabled or disabled. * This parameter can be: * @arg RTC_IT_WUT: WakeUpTimer A interrupt * @retval None */ #define __HAL_RTC_WAKEUPTIMER_ENABLE_IT(__HANDLE__, __INTERRUPT__) ((__HANDLE__)->Instance->CR |= (__INTERRUPT__)) /** * @brief Disable the RTC WakeUpTimer interrupt. * @param __HANDLE__: specifies the RTC handle. * @param __INTERRUPT__: specifies the RTC WakeUpTimer interrupt sources to be enabled or disabled. * This parameter can be: * @arg RTC_IT_WUT: WakeUpTimer A interrupt * @retval None */ #define __HAL_RTC_WAKEUPTIMER_DISABLE_IT(__HANDLE__, __INTERRUPT__) ((__HANDLE__)->Instance->CR &= ~(__INTERRUPT__)) /** * @brief Check whether the specified RTC WakeUpTimer interrupt has occurred or not. * @param __HANDLE__: specifies the RTC handle. * @param __INTERRUPT__: specifies the RTC WakeUpTimer interrupt to check. * This parameter can be: * @arg RTC_IT_WUT: WakeUpTimer A interrupt * @retval None */ #define __HAL_RTC_WAKEUPTIMER_GET_IT(__HANDLE__, __INTERRUPT__) (((((__HANDLE__)->Instance->ISR) & ((__INTERRUPT__)>> 4)) != RESET)? SET : RESET) /** * @brief Check whether the specified RTC Wake Up timer interrupt has been enabled or not. * @param __HANDLE__: specifies the RTC handle. * @param __INTERRUPT__: specifies the RTC Wake Up timer interrupt sources to check. * This parameter can be: * @arg RTC_IT_WUT: WakeUpTimer interrupt * @retval None */ #define __HAL_RTC_WAKEUPTIMER_GET_IT_SOURCE(__HANDLE__, __INTERRUPT__) (((((__HANDLE__)->Instance->CR) & (__INTERRUPT__)) != RESET) ? SET : RESET) /** * @brief Get the selected RTC WakeUpTimer's flag status. * @param __HANDLE__: specifies the RTC handle. * @param __FLAG__: specifies the RTC WakeUpTimer Flag to check. * This parameter can be: * @arg RTC_FLAG_WUTF * @arg RTC_FLAG_WUTWF * @retval None */ #define __HAL_RTC_WAKEUPTIMER_GET_FLAG(__HANDLE__, __FLAG__) (((((__HANDLE__)->Instance->ISR) & (__FLAG__)) != RESET)? SET : RESET) /** * @brief Clear the RTC Wake Up timer's pending flags. * @param __HANDLE__: specifies the RTC handle. * @param __FLAG__: specifies the RTC Tamper Flag sources to be enabled or disabled. * This parameter can be: * @arg RTC_FLAG_WUTF * @retval None */ #define __HAL_RTC_WAKEUPTIMER_CLEAR_FLAG(__HANDLE__, __FLAG__) ((__HANDLE__)->Instance->ISR) = (~((__FLAG__) | RTC_ISR_INIT)|((__HANDLE__)->Instance->ISR & RTC_ISR_INIT)) /** * @brief Enable interrupt on the RTC Wake-up Timer associated Exti line. * @retval None */ #define __HAL_RTC_WAKEUPTIMER_EXTI_ENABLE_IT() (EXTI->IMR |= RTC_EXTI_LINE_WAKEUPTIMER_EVENT) /** * @brief Disable interrupt on the RTC Wake-up Timer associated Exti line. * @retval None */ #define __HAL_RTC_WAKEUPTIMER_EXTI_DISABLE_IT() (EXTI->IMR &= ~(RTC_EXTI_LINE_WAKEUPTIMER_EVENT)) /** * @brief Enable event on the RTC Wake-up Timer associated Exti line. * @retval None. */ #define __HAL_RTC_WAKEUPTIMER_EXTI_ENABLE_EVENT() (EXTI->EMR |= RTC_EXTI_LINE_WAKEUPTIMER_EVENT) /** * @brief Disable event on the RTC Wake-up Timer associated Exti line. * @retval None. */ #define __HAL_RTC_WAKEUPTIMER_EXTI_DISABLE_EVENT() (EXTI->EMR &= ~(RTC_EXTI_LINE_WAKEUPTIMER_EVENT)) /** * @brief Enable falling edge trigger on the RTC Wake-up Timer associated Exti line. * @retval None. */ #define __HAL_RTC_WAKEUPTIMER_EXTI_ENABLE_FALLING_EDGE() (EXTI->FTSR |= RTC_EXTI_LINE_WAKEUPTIMER_EVENT) /** * @brief Disable falling edge trigger on the RTC Wake-up Timer associated Exti line. * @retval None. */ #define __HAL_RTC_WAKEUPTIMER_EXTI_DISABLE_FALLING_EDGE() (EXTI->FTSR &= ~(RTC_EXTI_LINE_WAKEUPTIMER_EVENT)) /** * @brief Enable rising edge trigger on the RTC Wake-up Timer associated Exti line. * @retval None. */ #define __HAL_RTC_WAKEUPTIMER_EXTI_ENABLE_RISING_EDGE() (EXTI->RTSR |= RTC_EXTI_LINE_WAKEUPTIMER_EVENT) /** * @brief Disable rising edge trigger on the RTC Wake-up Timer associated Exti line. * @retval None. */ #define __HAL_RTC_WAKEUPTIMER_EXTI_DISABLE_RISING_EDGE() (EXTI->RTSR &= ~(RTC_EXTI_LINE_WAKEUPTIMER_EVENT)) /** * @brief Enable rising & falling edge trigger on the RTC Wake-up Timer associated Exti line. * @retval None. */ #define __HAL_RTC_WAKEUPTIMER_EXTI_ENABLE_RISING_FALLING_EDGE() __HAL_RTC_WAKEUPTIMER_EXTI_ENABLE_RISING_EDGE();__HAL_RTC_WAKEUPTIMER_EXTI_ENABLE_FALLING_EDGE(); /** * @brief Disable rising & falling edge trigger on the RTC Wake-up Timer associated Exti line. * This parameter can be: * @retval None. */ #define __HAL_RTC_WAKEUPTIMER_EXTI_DISABLE_RISING_FALLING_EDGE() __HAL_RTC_WAKEUPTIMER_EXTI_DISABLE_RISING_EDGE();__HAL_RTC_WAKEUPTIMER_EXTI_DISABLE_FALLING_EDGE(); /** * @brief Check whether the RTC Wake-up Timer associated Exti line interrupt flag is set or not. * @retval Line Status. */ #define __HAL_RTC_WAKEUPTIMER_EXTI_GET_FLAG() (EXTI->PR & RTC_EXTI_LINE_WAKEUPTIMER_EVENT) /** * @brief Clear the RTC Wake-up Timer associated Exti line flag. * @retval None. */ #define __HAL_RTC_WAKEUPTIMER_EXTI_CLEAR_FLAG() (EXTI->PR = RTC_EXTI_LINE_WAKEUPTIMER_EVENT) /** * @brief Generate a Software interrupt on the RTC Wake-up Timer associated Exti line. * @retval None. */ #define __HAL_RTC_WAKEUPTIMER_EXTI_GENERATE_SWIT() (EXTI->SWIER |= RTC_EXTI_LINE_WAKEUPTIMER_EVENT) /** * @} */ /* ---------------------------------TIMESTAMP---------------------------------*/ /** @defgroup RTCEx_Timestamp RTC Timestamp * @{ */ /** * @brief Enable the RTC TimeStamp peripheral. * @param __HANDLE__: specifies the RTC handle. * @retval None */ #define __HAL_RTC_TIMESTAMP_ENABLE(__HANDLE__) ((__HANDLE__)->Instance->CR |= (RTC_CR_TSE)) /** * @brief Disable the RTC TimeStamp peripheral. * @param __HANDLE__: specifies the RTC handle. * @retval None */ #define __HAL_RTC_TIMESTAMP_DISABLE(__HANDLE__) ((__HANDLE__)->Instance->CR &= ~(RTC_CR_TSE)) /** * @brief Enable the RTC TimeStamp interrupt. * @param __HANDLE__: specifies the RTC handle. * @param __INTERRUPT__: specifies the RTC TimeStamp interrupt sources to be enabled or disabled. * This parameter can be: * @arg RTC_IT_TS: TimeStamp interrupt * @retval None */ #define __HAL_RTC_TIMESTAMP_ENABLE_IT(__HANDLE__, __INTERRUPT__) ((__HANDLE__)->Instance->CR |= (__INTERRUPT__)) /** * @brief Disable the RTC TimeStamp interrupt. * @param __HANDLE__: specifies the RTC handle. * @param __INTERRUPT__: specifies the RTC TimeStamp interrupt sources to be enabled or disabled. * This parameter can be: * @arg RTC_IT_TS: TimeStamp interrupt * @retval None */ #define __HAL_RTC_TIMESTAMP_DISABLE_IT(__HANDLE__, __INTERRUPT__) ((__HANDLE__)->Instance->CR &= ~(__INTERRUPT__)) /** * @brief Check whether the specified RTC TimeStamp interrupt has occurred or not. * @param __HANDLE__: specifies the RTC handle. * @param __INTERRUPT__: specifies the RTC TimeStamp interrupt to check. * This parameter can be: * @arg RTC_IT_TS: TimeStamp interrupt * @retval None */ #define __HAL_RTC_TIMESTAMP_GET_IT(__HANDLE__, __INTERRUPT__) (((((__HANDLE__)->Instance->ISR) & ((__INTERRUPT__)>> 4)) != RESET)? SET : RESET) /** * @brief Check whether the specified RTC Time Stamp interrupt has been enabled or not. * @param __HANDLE__: specifies the RTC handle. * @param __INTERRUPT__: specifies the RTC Time Stamp interrupt source to check. * This parameter can be: * @arg RTC_IT_TS: TimeStamp interrupt * @retval None */ #define __HAL_RTC_TIMESTAMP_GET_IT_SOURCE(__HANDLE__, __INTERRUPT__) (((((__HANDLE__)->Instance->CR) & (__INTERRUPT__)) != RESET) ? SET : RESET) /** * @brief Get the selected RTC TimeStamp's flag status. * @param __HANDLE__: specifies the RTC handle. * @param __FLAG__: specifies the RTC TimeStamp flag to check. * This parameter can be: * @arg RTC_FLAG_TSF * @arg RTC_FLAG_TSOVF * @retval None */ #define __HAL_RTC_TIMESTAMP_GET_FLAG(__HANDLE__, __FLAG__) (((((__HANDLE__)->Instance->ISR) & (__FLAG__)) != RESET)? SET : RESET) /** * @brief Clear the RTC Time Stamp's pending flags. * @param __HANDLE__: specifies the RTC handle. * @param __FLAG__: specifies the RTC Alarm Flag sources to be enabled or disabled. * This parameter can be: * @arg RTC_FLAG_TSF * @retval None */ #define __HAL_RTC_TIMESTAMP_CLEAR_FLAG(__HANDLE__, __FLAG__) ((__HANDLE__)->Instance->ISR) = (~((__FLAG__) | RTC_ISR_INIT)|((__HANDLE__)->Instance->ISR & RTC_ISR_INIT)) /** * @} */ /* ---------------------------------TAMPER------------------------------------*/ /** @defgroup RTCEx_Tamper RTC Tamper * @{ */ /** * @brief Enable the RTC Tamper1 input detection. * @param __HANDLE__: specifies the RTC handle. * @retval None */ #define __HAL_RTC_TAMPER1_ENABLE(__HANDLE__) ((__HANDLE__)->Instance->TAFCR |= (RTC_TAFCR_TAMP1E)) /** * @brief Disable the RTC Tamper1 input detection. * @param __HANDLE__: specifies the RTC handle. * @retval None */ #define __HAL_RTC_TAMPER1_DISABLE(__HANDLE__) ((__HANDLE__)->Instance->TAFCR &= ~(RTC_TAFCR_TAMP1E)) /** * @brief Enable the RTC Tamper2 input detection. * @param __HANDLE__: specifies the RTC handle. * @retval None */ #define __HAL_RTC_TAMPER2_ENABLE(__HANDLE__) ((__HANDLE__)->Instance->TAFCR |= (RTC_TAFCR_TAMP2E)) /** * @brief Disable the RTC Tamper2 input detection. * @param __HANDLE__: specifies the RTC handle. * @retval None */ #define __HAL_RTC_TAMPER2_DISABLE(__HANDLE__) ((__HANDLE__)->Instance->TAFCR &= ~(RTC_TAFCR_TAMP2E)) /** * @brief Check whether the specified RTC Tamper interrupt has occurred or not. * @param __HANDLE__: specifies the RTC handle. * @param __INTERRUPT__: specifies the RTC Tamper interrupt to check. * This parameter can be: * @arg RTC_IT_TAMP1 * @arg RTC_IT_TAMP2 * @retval None */ #define __HAL_RTC_TAMPER_GET_IT(__HANDLE__, __INTERRUPT__) (((((__HANDLE__)->Instance->ISR) & ((__INTERRUPT__)>> 4)) != RESET)? SET : RESET) /** * @brief Check whether the specified RTC Tamper interrupt has been enabled or not. * @param __HANDLE__: specifies the RTC handle. * @param __INTERRUPT__: specifies the RTC Tamper interrupt source to check. * This parameter can be: * @arg RTC_IT_TAMP: Tamper interrupt * @retval None */ #define __HAL_RTC_TAMPER_GET_IT_SOURCE(__HANDLE__, __INTERRUPT__) (((((__HANDLE__)->Instance->TAFCR) & (__INTERRUPT__)) != RESET) ? SET : RESET) /** * @brief Get the selected RTC Tamper's flag status. * @param __HANDLE__: specifies the RTC handle. * @param __FLAG__: specifies the RTC Tamper Flag sources to be enabled or disabled. * This parameter can be: * @arg RTC_FLAG_TAMP1F * @arg RTC_FLAG_TAMP2F * @retval None */ #define __HAL_RTC_TAMPER_GET_FLAG(__HANDLE__, __FLAG__) (((((__HANDLE__)->Instance->ISR) & (__FLAG__)) != RESET)? SET : RESET) /** * @brief Clear the RTC Tamper's pending flags. * @param __HANDLE__: specifies the RTC handle. * @param __FLAG__: specifies the RTC Tamper Flag to clear. * This parameter can be: * @arg RTC_FLAG_TAMP1F * @arg RTC_FLAG_TAMP2F * @retval None */ #define __HAL_RTC_TAMPER_CLEAR_FLAG(__HANDLE__, __FLAG__) ((__HANDLE__)->Instance->ISR) = (~((__FLAG__) | RTC_ISR_INIT)|((__HANDLE__)->Instance->ISR & RTC_ISR_INIT)) /** * @} */ /* --------------------------TAMPER/TIMESTAMP---------------------------------*/ /** @defgroup RTCEx_Tamper_Timestamp EXTI RTC Tamper Timestamp EXTI * @{ */ /** * @brief Enable interrupt on the RTC Tamper and Timestamp associated Exti line. * @retval None */ #define __HAL_RTC_TAMPER_TIMESTAMP_EXTI_ENABLE_IT() (EXTI->IMR |= RTC_EXTI_LINE_TAMPER_TIMESTAMP_EVENT) /** * @brief Disable interrupt on the RTC Tamper and Timestamp associated Exti line. * @retval None */ #define __HAL_RTC_TAMPER_TIMESTAMP_EXTI_DISABLE_IT() (EXTI->IMR &= ~(RTC_EXTI_LINE_TAMPER_TIMESTAMP_EVENT)) /** * @brief Enable event on the RTC Tamper and Timestamp associated Exti line. * @retval None. */ #define __HAL_RTC_TAMPER_TIMESTAMP_EXTI_ENABLE_EVENT() (EXTI->EMR |= RTC_EXTI_LINE_TAMPER_TIMESTAMP_EVENT) /** * @brief Disable event on the RTC Tamper and Timestamp associated Exti line. * @retval None. */ #define __HAL_RTC_TAMPER_TIMESTAMP_EXTI_DISABLE_EVENT() (EXTI->EMR &= ~(RTC_EXTI_LINE_TAMPER_TIMESTAMP_EVENT)) /** * @brief Enable falling edge trigger on the RTC Tamper and Timestamp associated Exti line. * @retval None. */ #define __HAL_RTC_TAMPER_TIMESTAMP_EXTI_ENABLE_FALLING_EDGE() (EXTI->FTSR |= RTC_EXTI_LINE_TAMPER_TIMESTAMP_EVENT) /** * @brief Disable falling edge trigger on the RTC Tamper and Timestamp associated Exti line. * @retval None. */ #define __HAL_RTC_TAMPER_TIMESTAMP_EXTI_DISABLE_FALLING_EDGE() (EXTI->FTSR &= ~(RTC_EXTI_LINE_TAMPER_TIMESTAMP_EVENT)) /** * @brief Enable rising edge trigger on the RTC Tamper and Timestamp associated Exti line. * @retval None. */ #define __HAL_RTC_TAMPER_TIMESTAMP_EXTI_ENABLE_RISING_EDGE() (EXTI->RTSR |= RTC_EXTI_LINE_TAMPER_TIMESTAMP_EVENT) /** * @brief Disable rising edge trigger on the RTC Tamper and Timestamp associated Exti line. * @retval None. */ #define __HAL_RTC_TAMPER_TIMESTAMP_EXTI_DISABLE_RISING_EDGE() (EXTI->RTSR &= ~(RTC_EXTI_LINE_TAMPER_TIMESTAMP_EVENT)) /** * @brief Enable rising & falling edge trigger on the RTC Tamper and Timestamp associated Exti line. * @retval None. */ #define __HAL_RTC_TAMPER_TIMESTAMP_EXTI_ENABLE_RISING_FALLING_EDGE() __HAL_RTC_TAMPER_TIMESTAMP_EXTI_ENABLE_RISING_EDGE();__HAL_RTC_TAMPER_TIMESTAMP_EXTI_ENABLE_FALLING_EDGE(); /** * @brief Disable rising & falling edge trigger on the RTC Tamper and Timestamp associated Exti line. * This parameter can be: * @retval None. */ #define __HAL_RTC_TAMPER_TIMESTAMP_EXTI_DISABLE_RISING_FALLING_EDGE() __HAL_RTC_TAMPER_TIMESTAMP_EXTI_DISABLE_RISING_EDGE();__HAL_RTC_TAMPER_TIMESTAMP_EXTI_DISABLE_FALLING_EDGE(); /** * @brief Check whether the RTC Tamper and Timestamp associated Exti line interrupt flag is set or not. * @retval Line Status. */ #define __HAL_RTC_TAMPER_TIMESTAMP_EXTI_GET_FLAG() (EXTI->PR & RTC_EXTI_LINE_TAMPER_TIMESTAMP_EVENT) /** * @brief Clear the RTC Tamper and Timestamp associated Exti line flag. * @retval None. */ #define __HAL_RTC_TAMPER_TIMESTAMP_EXTI_CLEAR_FLAG() (EXTI->PR = RTC_EXTI_LINE_TAMPER_TIMESTAMP_EVENT) /** * @brief Generate a Software interrupt on the RTC Tamper and Timestamp associated Exti line * @retval None. */ #define __HAL_RTC_TAMPER_TIMESTAMP_EXTI_GENERATE_SWIT() (EXTI->SWIER |= RTC_EXTI_LINE_TAMPER_TIMESTAMP_EVENT) /** * @} */ /* ------------------------------Calibration----------------------------------*/ /** @defgroup RTCEx_Calibration RTC Calibration * @{ */ /** * @brief Enable the Coarse calibration process. * @param __HANDLE__: specifies the RTC handle. * @retval None */ #define __HAL_RTC_COARSE_CALIB_ENABLE(__HANDLE__) ((__HANDLE__)->Instance->CR |= (RTC_CR_DCE)) /** * @brief Disable the Coarse calibration process. * @param __HANDLE__: specifies the RTC handle. * @retval None */ #define __HAL_RTC_COARSE_CALIB_DISABLE(__HANDLE__) ((__HANDLE__)->Instance->CR &= ~(RTC_CR_DCE)) /** * @brief Enable the RTC calibration output. * @param __HANDLE__: specifies the RTC handle. * @retval None */ #define __HAL_RTC_CALIBRATION_OUTPUT_ENABLE(__HANDLE__) ((__HANDLE__)->Instance->CR |= (RTC_CR_COE)) /** * @brief Disable the calibration output. * @param __HANDLE__: specifies the RTC handle. * @retval None */ #define __HAL_RTC_CALIBRATION_OUTPUT_DISABLE(__HANDLE__) ((__HANDLE__)->Instance->CR &= ~(RTC_CR_COE)) /** * @brief Enable the clock reference detection. * @param __HANDLE__: specifies the RTC handle. * @retval None */ #define __HAL_RTC_CLOCKREF_DETECTION_ENABLE(__HANDLE__) ((__HANDLE__)->Instance->CR |= (RTC_CR_REFCKON)) /** * @brief Disable the clock reference detection. * @param __HANDLE__: specifies the RTC handle. * @retval None */ #define __HAL_RTC_CLOCKREF_DETECTION_DISABLE(__HANDLE__) ((__HANDLE__)->Instance->CR &= ~(RTC_CR_REFCKON)) /** * @brief Get the selected RTC shift operation's flag status. * @param __HANDLE__: specifies the RTC handle. * @param __FLAG__: specifies the RTC shift operation Flag is pending or not. * This parameter can be: * @arg RTC_FLAG_SHPF * @retval None */ #define __HAL_RTC_SHIFT_GET_FLAG(__HANDLE__, __FLAG__) (((((__HANDLE__)->Instance->ISR) & (__FLAG__)) != RESET)? SET : RESET) /** * @} */ /** * @} */ /* Exported functions --------------------------------------------------------*/ /** @defgroup RTCEx_Exported_Functions RTCEx Exported Functions * @{ */ /** @addtogroup RTCEx_Exported_Functions_Group1 * @{ */ /* RTC TimeStamp and Tamper functions *****************************************/ HAL_StatusTypeDef HAL_RTCEx_SetTimeStamp(RTC_HandleTypeDef *hrtc, uint32_t TimeStampEdge, uint32_t RTC_TimeStampPin); HAL_StatusTypeDef HAL_RTCEx_SetTimeStamp_IT(RTC_HandleTypeDef *hrtc, uint32_t TimeStampEdge, uint32_t RTC_TimeStampPin); HAL_StatusTypeDef HAL_RTCEx_DeactivateTimeStamp(RTC_HandleTypeDef *hrtc); HAL_StatusTypeDef HAL_RTCEx_GetTimeStamp(RTC_HandleTypeDef *hrtc, RTC_TimeTypeDef *sTimeStamp, RTC_DateTypeDef *sTimeStampDate, uint32_t Format); HAL_StatusTypeDef HAL_RTCEx_SetTamper(RTC_HandleTypeDef *hrtc, RTC_TamperTypeDef* sTamper); HAL_StatusTypeDef HAL_RTCEx_SetTamper_IT(RTC_HandleTypeDef *hrtc, RTC_TamperTypeDef* sTamper); HAL_StatusTypeDef HAL_RTCEx_DeactivateTamper(RTC_HandleTypeDef *hrtc, uint32_t Tamper); void HAL_RTCEx_TamperTimeStampIRQHandler(RTC_HandleTypeDef *hrtc); void HAL_RTCEx_Tamper1EventCallback(RTC_HandleTypeDef *hrtc); void HAL_RTCEx_Tamper2EventCallback(RTC_HandleTypeDef *hrtc); void HAL_RTCEx_TimeStampEventCallback(RTC_HandleTypeDef *hrtc); HAL_StatusTypeDef HAL_RTCEx_PollForTimeStampEvent(RTC_HandleTypeDef *hrtc, uint32_t Timeout); HAL_StatusTypeDef HAL_RTCEx_PollForTamper1Event(RTC_HandleTypeDef *hrtc, uint32_t Timeout); HAL_StatusTypeDef HAL_RTCEx_PollForTamper2Event(RTC_HandleTypeDef *hrtc, uint32_t Timeout); /** * @} */ /** @addtogroup RTCEx_Exported_Functions_Group2 * @{ */ /* RTC Wake-up functions ******************************************************/ HAL_StatusTypeDef HAL_RTCEx_SetWakeUpTimer(RTC_HandleTypeDef *hrtc, uint32_t WakeUpCounter, uint32_t WakeUpClock); HAL_StatusTypeDef HAL_RTCEx_SetWakeUpTimer_IT(RTC_HandleTypeDef *hrtc, uint32_t WakeUpCounter, uint32_t WakeUpClock); uint32_t HAL_RTCEx_DeactivateWakeUpTimer(RTC_HandleTypeDef *hrtc); uint32_t HAL_RTCEx_GetWakeUpTimer(RTC_HandleTypeDef *hrtc); void HAL_RTCEx_WakeUpTimerIRQHandler(RTC_HandleTypeDef *hrtc); void HAL_RTCEx_WakeUpTimerEventCallback(RTC_HandleTypeDef *hrtc); HAL_StatusTypeDef HAL_RTCEx_PollForWakeUpTimerEvent(RTC_HandleTypeDef *hrtc, uint32_t Timeout); /** * @} */ /** @addtogroup RTCEx_Exported_Functions_Group3 * @{ */ /* Extension Control functions ************************************************/ void HAL_RTCEx_BKUPWrite(RTC_HandleTypeDef *hrtc, uint32_t BackupRegister, uint32_t Data); uint32_t HAL_RTCEx_BKUPRead(RTC_HandleTypeDef *hrtc, uint32_t BackupRegister); HAL_StatusTypeDef HAL_RTCEx_SetCoarseCalib(RTC_HandleTypeDef *hrtc, uint32_t CalibSign, uint32_t Value); HAL_StatusTypeDef HAL_RTCEx_DeactivateCoarseCalib(RTC_HandleTypeDef *hrtc); HAL_StatusTypeDef HAL_RTCEx_SetSmoothCalib(RTC_HandleTypeDef *hrtc, uint32_t SmoothCalibPeriod, uint32_t SmoothCalibPlusPulses, uint32_t SmouthCalibMinusPulsesValue); HAL_StatusTypeDef HAL_RTCEx_SetSynchroShift(RTC_HandleTypeDef *hrtc, uint32_t ShiftAdd1S, uint32_t ShiftSubFS); HAL_StatusTypeDef HAL_RTCEx_SetCalibrationOutPut(RTC_HandleTypeDef *hrtc, uint32_t CalibOutput); HAL_StatusTypeDef HAL_RTCEx_DeactivateCalibrationOutPut(RTC_HandleTypeDef *hrtc); HAL_StatusTypeDef HAL_RTCEx_SetRefClock(RTC_HandleTypeDef *hrtc); HAL_StatusTypeDef HAL_RTCEx_DeactivateRefClock(RTC_HandleTypeDef *hrtc); HAL_StatusTypeDef HAL_RTCEx_EnableBypassShadow(RTC_HandleTypeDef *hrtc); HAL_StatusTypeDef HAL_RTCEx_DisableBypassShadow(RTC_HandleTypeDef *hrtc); /** * @} */ /** @addtogroup RTCEx_Exported_Functions_Group4 * @{ */ /* Extension RTC features functions *******************************************/ void HAL_RTCEx_AlarmBEventCallback(RTC_HandleTypeDef *hrtc); HAL_StatusTypeDef HAL_RTCEx_PollForAlarmBEvent(RTC_HandleTypeDef *hrtc, uint32_t Timeout); /** * @} */ /** * @} */ /* Private types -------------------------------------------------------------*/ /* Private variables ---------------------------------------------------------*/ /* Private constants ---------------------------------------------------------*/ /** @defgroup RTCEx_Private_Constants RTCEx Private Constants * @{ */ #define RTC_EXTI_LINE_TAMPER_TIMESTAMP_EVENT ((uint32_t)EXTI_IMR_MR21) /*!< External interrupt line 21 Connected to the RTC Tamper and Time Stamp events */ #define RTC_EXTI_LINE_WAKEUPTIMER_EVENT ((uint32_t)EXTI_IMR_MR22) /*!< External interrupt line 22 Connected to the RTC Wake-up event */ /** * @} */ /* Private macros ------------------------------------------------------------*/ /** @defgroup RTCEx_Private_Macros RTCEx Private Macros * @{ */ /** @defgroup RTCEx_IS_RTC_Definitions Private macros to check input parameters * @{ */ #define IS_RTC_BKP(BKP) (((BKP) == RTC_BKP_DR0) || \ ((BKP) == RTC_BKP_DR1) || \ ((BKP) == RTC_BKP_DR2) || \ ((BKP) == RTC_BKP_DR3) || \ ((BKP) == RTC_BKP_DR4) || \ ((BKP) == RTC_BKP_DR5) || \ ((BKP) == RTC_BKP_DR6) || \ ((BKP) == RTC_BKP_DR7) || \ ((BKP) == RTC_BKP_DR8) || \ ((BKP) == RTC_BKP_DR9) || \ ((BKP) == RTC_BKP_DR10) || \ ((BKP) == RTC_BKP_DR11) || \ ((BKP) == RTC_BKP_DR12) || \ ((BKP) == RTC_BKP_DR13) || \ ((BKP) == RTC_BKP_DR14) || \ ((BKP) == RTC_BKP_DR15) || \ ((BKP) == RTC_BKP_DR16) || \ ((BKP) == RTC_BKP_DR17) || \ ((BKP) == RTC_BKP_DR18) || \ ((BKP) == RTC_BKP_DR19)) #define IS_TIMESTAMP_EDGE(EDGE) (((EDGE) == RTC_TIMESTAMPEDGE_RISING) || \ ((EDGE) == RTC_TIMESTAMPEDGE_FALLING)) #define IS_RTC_TAMPER(TAMPER) ((((TAMPER) & ((uint32_t)!(RTC_TAFCR_TAMP1E | RTC_TAFCR_TAMP2E))) == 0x00) && ((TAMPER) != (uint32_t)RESET)) #define IS_RTC_TAMPER_PIN(PIN) (((PIN) == RTC_TAMPERPIN_DEFAULT) || \ ((PIN) == RTC_TAMPERPIN_POS1)) #define IS_RTC_TIMESTAMP_PIN(PIN) (((PIN) == RTC_TIMESTAMPPIN_DEFAULT) || \ ((PIN) == RTC_TIMESTAMPPIN_POS1)) #define IS_RTC_TAMPER_TRIGGER(TRIGGER) (((TRIGGER) == RTC_TAMPERTRIGGER_RISINGEDGE) || \ ((TRIGGER) == RTC_TAMPERTRIGGER_FALLINGEDGE) || \ ((TRIGGER) == RTC_TAMPERTRIGGER_LOWLEVEL) || \ ((TRIGGER) == RTC_TAMPERTRIGGER_HIGHLEVEL)) #define IS_RTC_TAMPER_FILTER(FILTER) (((FILTER) == RTC_TAMPERFILTER_DISABLE) || \ ((FILTER) == RTC_TAMPERFILTER_2SAMPLE) || \ ((FILTER) == RTC_TAMPERFILTER_4SAMPLE) || \ ((FILTER) == RTC_TAMPERFILTER_8SAMPLE)) #define IS_RTC_TAMPER_SAMPLING_FREQ(FREQ) (((FREQ) == RTC_TAMPERSAMPLINGFREQ_RTCCLK_DIV32768)|| \ ((FREQ) == RTC_TAMPERSAMPLINGFREQ_RTCCLK_DIV16384)|| \ ((FREQ) == RTC_TAMPERSAMPLINGFREQ_RTCCLK_DIV8192) || \ ((FREQ) == RTC_TAMPERSAMPLINGFREQ_RTCCLK_DIV4096) || \ ((FREQ) == RTC_TAMPERSAMPLINGFREQ_RTCCLK_DIV2048) || \ ((FREQ) == RTC_TAMPERSAMPLINGFREQ_RTCCLK_DIV1024) || \ ((FREQ) == RTC_TAMPERSAMPLINGFREQ_RTCCLK_DIV512) || \ ((FREQ) == RTC_TAMPERSAMPLINGFREQ_RTCCLK_DIV256)) #define IS_RTC_TAMPER_PRECHARGE_DURATION(DURATION) (((DURATION) == RTC_TAMPERPRECHARGEDURATION_1RTCCLK) || \ ((DURATION) == RTC_TAMPERPRECHARGEDURATION_2RTCCLK) || \ ((DURATION) == RTC_TAMPERPRECHARGEDURATION_4RTCCLK) || \ ((DURATION) == RTC_TAMPERPRECHARGEDURATION_8RTCCLK)) #define IS_RTC_TAMPER_TIMESTAMPONTAMPER_DETECTION(DETECTION) (((DETECTION) == RTC_TIMESTAMPONTAMPERDETECTION_ENABLE) || \ ((DETECTION) == RTC_TIMESTAMPONTAMPERDETECTION_DISABLE)) #define IS_RTC_TAMPER_PULLUP_STATE(STATE) (((STATE) == RTC_TAMPER_PULLUP_ENABLE) || \ ((STATE) == RTC_TAMPER_PULLUP_DISABLE)) #define IS_RTC_WAKEUP_CLOCK(CLOCK) (((CLOCK) == RTC_WAKEUPCLOCK_RTCCLK_DIV16) || \ ((CLOCK) == RTC_WAKEUPCLOCK_RTCCLK_DIV8) || \ ((CLOCK) == RTC_WAKEUPCLOCK_RTCCLK_DIV4) || \ ((CLOCK) == RTC_WAKEUPCLOCK_RTCCLK_DIV2) || \ ((CLOCK) == RTC_WAKEUPCLOCK_CK_SPRE_16BITS) || \ ((CLOCK) == RTC_WAKEUPCLOCK_CK_SPRE_17BITS)) #define IS_RTC_WAKEUP_COUNTER(COUNTER) ((COUNTER) <= 0xFFFF) #define IS_RTC_CALIB_SIGN(SIGN) (((SIGN) == RTC_CALIBSIGN_POSITIVE) || \ ((SIGN) == RTC_CALIBSIGN_NEGATIVE)) #define IS_RTC_CALIB_VALUE(VALUE) ((VALUE) < 0x20) #define IS_RTC_SMOOTH_CALIB_PERIOD(PERIOD) (((PERIOD) == RTC_SMOOTHCALIB_PERIOD_32SEC) || \ ((PERIOD) == RTC_SMOOTHCALIB_PERIOD_16SEC) || \ ((PERIOD) == RTC_SMOOTHCALIB_PERIOD_8SEC)) #define IS_RTC_SMOOTH_CALIB_PLUS(PLUS) (((PLUS) == RTC_SMOOTHCALIB_PLUSPULSES_SET) || \ ((PLUS) == RTC_SMOOTHCALIB_PLUSPULSES_RESET)) #define IS_RTC_SMOOTH_CALIB_MINUS(VALUE) ((VALUE) <= 0x000001FF) #define IS_RTC_SHIFT_ADD1S(SEL) (((SEL) == RTC_SHIFTADD1S_RESET) || \ ((SEL) == RTC_SHIFTADD1S_SET)) #define IS_RTC_SHIFT_SUBFS(FS) ((FS) <= 0x00007FFF) #define IS_RTC_CALIB_OUTPUT(OUTPUT) (((OUTPUT) == RTC_CALIBOUTPUT_512HZ) || \ ((OUTPUT) == RTC_CALIBOUTPUT_1HZ)) /** * @} */ /** * @} */ /** * @} */ /** * @} */ #ifdef __cplusplus } #endif #endif /* __STM32F4xx_HAL_RTC_EX_H */ /************************ (C) COPYRIGHT STMicroelectronics *****END OF FILE****/ ================================================ FILE: Zelig/mbed/TARGET_NUCLEO_F411RE/stm32f4xx_hal_sai.h ================================================ /** ****************************************************************************** * @file stm32f4xx_hal_sai.h * @author MCD Application Team * @version V1.4.1 * @date 09-October-2015 * @brief Header file of SAI HAL module. ****************************************************************************** * @attention * *

© COPYRIGHT(c) 2015 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. * ****************************************************************************** */ /* Define to prevent recursive inclusion -------------------------------------*/ #ifndef __STM32F4xx_HAL_SAI_H #define __STM32F4xx_HAL_SAI_H #ifdef __cplusplus extern "C" { #endif /* Includes ------------------------------------------------------------------*/ #include "stm32f4xx_hal_def.h" /** @addtogroup STM32F4xx_HAL_Driver * @{ */ #if defined(STM32F427xx) || defined(STM32F437xx) || defined(STM32F429xx) || defined(STM32F439xx) ||\ defined(STM32F446xx) || defined(STM32F469xx) || defined(STM32F479xx) /** @addtogroup SAI * @{ */ /* Exported types ------------------------------------------------------------*/ /** @defgroup SAI_Exported_Types SAI Exported Types * @{ */ /** * @brief HAL State structures definition */ typedef enum { HAL_SAI_STATE_RESET = 0x00, /*!< SAI not yet initialized or disabled */ HAL_SAI_STATE_READY = 0x01, /*!< SAI initialized and ready for use */ HAL_SAI_STATE_BUSY = 0x02, /*!< SAI internal process is ongoing */ HAL_SAI_STATE_BUSY_TX = 0x12, /*!< Data transmission process is ongoing */ HAL_SAI_STATE_BUSY_RX = 0x22, /*!< Data reception process is ongoing */ HAL_SAI_STATE_TIMEOUT = 0x03, /*!< SAI timeout state */ HAL_SAI_STATE_ERROR = 0x04 /*!< SAI error state */ }HAL_SAI_StateTypeDef; /** * @brief SAI Callback prototype */ typedef void (*SAIcallback)(void); /** * @brief SAI Init Structure definition */ typedef struct { uint32_t AudioMode; /*!< Specifies the SAI Block audio Mode. This parameter can be a value of @ref SAI_Block_Mode */ uint32_t Synchro; /*!< Specifies SAI Block synchronization This parameter can be a value of @ref SAI_Block_Synchronization */ uint32_t SynchroExt; /*!< Specifies SAI Block synchronization, this setup is common for BLOCKA and BLOCKB This parameter can be a value of @ref SAI_Block_SyncExt */ uint32_t OutputDrive; /*!< Specifies when SAI Block outputs are driven. This parameter can be a value of @ref SAI_Block_Output_Drive @note this value has to be set before enabling the audio block but after the audio block configuration. */ uint32_t NoDivider; /*!< Specifies whether master clock will be divided or not. This parameter can be a value of @ref SAI_Block_NoDivider @note: If bit NODIV in the SAI_xCR1 register is cleared, the frame length should be aligned to a number equal to a power of 2, from 8 to 256. If bit NODIV in the SAI_xCR1 register is set, the frame length can take any of the values without constraint since the input clock of the audio block should be equal to the bit clock. There is no MCLK_x clock which can be output. */ uint32_t FIFOThreshold; /*!< Specifies SAI Block FIFO threshold. This parameter can be a value of @ref SAI_Block_Fifo_Threshold */ uint32_t ClockSource; /*!< Specifies the SAI Block x Clock source. This parameter is not used for STM32F446xx devices. */ uint32_t AudioFrequency; /*!< Specifies the audio frequency sampling. This parameter can be a value of @ref SAI_Audio_Frequency */ uint32_t Mckdiv; /*!< Specifies the master clock divider, the parameter will be used if for AudioFrequency the user choice This parameter must be a number between Min_Data = 0 and Max_Data = 15 */ uint32_t MonoStereoMode; /*!< Specifies if the mono or stereo mode is selected. This parameter can be a value of @ref SAI_Mono_Stereo_Mode */ uint32_t CompandingMode; /*!< Specifies the companding mode type. This parameter can be a value of @ref SAI_Block_Companding_Mode */ uint32_t TriState; /*!< Specifies the companding mode type. This parameter can be a value of @ref SAI_TRIState_Management */ /* This part of the structure is automatically filled if your are using the high level intialisation function HAL_SAI_InitProtocol */ uint32_t Protocol; /*!< Specifies the SAI Block protocol. This parameter can be a value of @ref SAI_Block_Protocol */ uint32_t DataSize; /*!< Specifies the SAI Block data size. This parameter can be a value of @ref SAI_Block_Data_Size */ uint32_t FirstBit; /*!< Specifies whether data transfers start from MSB or LSB bit. This parameter can be a value of @ref SAI_Block_MSB_LSB_transmission */ uint32_t ClockStrobing; /*!< Specifies the SAI Block clock strobing edge sensitivity. This parameter can be a value of @ref SAI_Block_Clock_Strobing */ }SAI_InitTypeDef; /** * @brief SAI Block Frame Init structure definition */ typedef struct { uint32_t FrameLength; /*!< Specifies the Frame length, the number of SCK clocks for each audio frame. This parameter must be a number between Min_Data = 8 and Max_Data = 256. @note: If master clock MCLK_x pin is declared as an output, the frame length should be aligned to a number equal to power of 2 in order to keep in an audio frame, an integer number of MCLK pulses by bit Clock. */ uint32_t ActiveFrameLength; /*!< Specifies the Frame synchronization active level length. This Parameter specifies the length in number of bit clock (SCK + 1) of the active level of FS signal in audio frame. This parameter must be a number between Min_Data = 1 and Max_Data = 128 */ uint32_t FSDefinition; /*!< Specifies the Frame synchronization definition. This parameter can be a value of @ref SAI_Block_FS_Definition */ uint32_t FSPolarity; /*!< Specifies the Frame synchronization Polarity. This parameter can be a value of @ref SAI_Block_FS_Polarity */ uint32_t FSOffset; /*!< Specifies the Frame synchronization Offset. This parameter can be a value of @ref SAI_Block_FS_Offset */ }SAI_FrameInitTypeDef; /** * @brief SAI Block Slot Init Structure definition */ typedef struct { uint32_t FirstBitOffset; /*!< Specifies the position of first data transfer bit in the slot. This parameter must be a number between Min_Data = 0 and Max_Data = 24 */ uint32_t SlotSize; /*!< Specifies the Slot Size. This parameter can be a value of @ref SAI_Block_Slot_Size */ uint32_t SlotNumber; /*!< Specifies the number of slot in the audio frame. This parameter must be a number between Min_Data = 1 and Max_Data = 16 */ uint32_t SlotActive; /*!< Specifies the slots in audio frame that will be activated. This parameter can be a value of @ref SAI_Block_Slot_Active */ }SAI_SlotInitTypeDef; /** * @brief SAI handle Structure definition */ typedef struct __SAI_HandleTypeDef { SAI_Block_TypeDef *Instance; /*!< SAI Blockx registers base address */ SAI_InitTypeDef Init; /*!< SAI communication parameters */ SAI_FrameInitTypeDef FrameInit; /*!< SAI Frame configuration parameters */ SAI_SlotInitTypeDef SlotInit; /*!< SAI Slot configuration parameters */ uint8_t *pBuffPtr; /*!< Pointer to SAI transfer Buffer */ uint16_t XferSize; /*!< SAI transfer size */ uint16_t XferCount; /*!< SAI transfer counter */ DMA_HandleTypeDef *hdmatx; /*!< SAI Tx DMA handle parameters */ DMA_HandleTypeDef *hdmarx; /*!< SAI Rx DMA handle parameters */ SAIcallback mutecallback;/*!< SAI mute callback */ void (*InterruptServiceRoutine)(struct __SAI_HandleTypeDef *hsai); /* function pointer for IRQ handler */ HAL_LockTypeDef Lock; /*!< SAI locking object */ __IO HAL_SAI_StateTypeDef State; /*!< SAI communication state */ __IO uint32_t ErrorCode; /*!< SAI Error code */ }SAI_HandleTypeDef; /** * @} */ /* Exported constants --------------------------------------------------------*/ /** @defgroup SAI_Exported_Constants SAI Exported Constants * @{ */ /** @defgroup SAI_Error_Code SAI Error Code * @{ */ #define HAL_SAI_ERROR_NONE ((uint32_t)0x00000000) /*!< No error */ #define HAL_SAI_ERROR_OVR ((uint32_t)0x00000001) /*!< Overrun Error */ #define HAL_SAI_ERROR_UDR ((uint32_t)0x00000002) /*!< Underrun error */ #define HAL_SAI_ERROR_AFSDET ((uint32_t)0x00000004) /*!< Anticipated Frame synchronisation detection */ #define HAL_SAI_ERROR_LFSDET ((uint32_t)0x00000008) /*!< Late Frame synchronisation detection */ #define HAL_SAI_ERROR_CNREADY ((uint32_t)0x00000010) /*!< codec not ready */ #define HAL_SAI_ERROR_WCKCFG ((uint32_t)0x00000020) /*!< Wrong clock configuration */ #define HAL_SAI_ERROR_TIMEOUT ((uint32_t)0x00000040) /*!< Timeout error */ /** * @} */ /** @defgroup SAI_Block_SyncExt SAI External synchronisation * @{ */ #define SAI_SYNCEXT_DISABLE ((uint32_t)0x00000000) #define SAI_SYNCEXT_IN_ENABLE ((uint32_t)0x00000001) #define SAI_SYNCEXT_OUTBLOCKA_ENABLE ((uint32_t)0x00000002) #define SAI_SYNCEXT_OUTBLOCKB_ENABLE ((uint32_t)0x00000004) /** * @} */ /** @defgroup SAI_Protocol SAI Supported protocol * @{ */ #define SAI_I2S_STANDARD ((uint32_t)0x00000000) #define SAI_I2S_MSBJUSTIFIED ((uint32_t)0x00000001) #define SAI_I2S_LSBJUSTIFIED ((uint32_t)0x00000002) #define SAI_PCM_LONG ((uint32_t)0x00000004) #define SAI_PCM_SHORT ((uint32_t)0x00000008) /** * @} */ /** @defgroup SAI_Protocol_DataSize SAI protocol data size * @{ */ #define SAI_PROTOCOL_DATASIZE_16BIT ((uint32_t)0x00000000) #define SAI_PROTOCOL_DATASIZE_16BITEXTENDED ((uint32_t)0x00000001) #define SAI_PROTOCOL_DATASIZE_24BIT ((uint32_t)0x00000002) #define SAI_PROTOCOL_DATASIZE_32BIT ((uint32_t)0x00000004) /** * @} */ /** @defgroup SAI_Clock_Source SAI Clock Source * @{ */ #define SAI_CLKSOURCE_PLLSAI ((uint32_t)0x00000000) #define SAI_CLKSOURCE_PLLI2S ((uint32_t)0x00100000) #define SAI_CLKSOURCE_EXT ((uint32_t)0x00200000) #define SAI_CLKSOURCE_NA ((uint32_t)0x00400000) /*!< No applicable for STM32F446xx */ /** * @} */ /** @defgroup SAI_Audio_Frequency SAI Audio Frequency * @{ */ #define SAI_AUDIO_FREQUENCY_192K ((uint32_t)192000) #define SAI_AUDIO_FREQUENCY_96K ((uint32_t)96000) #define SAI_AUDIO_FREQUENCY_48K ((uint32_t)48000) #define SAI_AUDIO_FREQUENCY_44K ((uint32_t)44100) #define SAI_AUDIO_FREQUENCY_32K ((uint32_t)32000) #define SAI_AUDIO_FREQUENCY_22K ((uint32_t)22050) #define SAI_AUDIO_FREQUENCY_16K ((uint32_t)16000) #define SAI_AUDIO_FREQUENCY_11K ((uint32_t)11025) #define SAI_AUDIO_FREQUENCY_8K ((uint32_t)8000) #define SAI_AUDIO_FREQUENCY_MCKDIV ((uint32_t)0) /** * @} */ /** @defgroup SAI_Block_Mode SAI Block Mode * @{ */ #define SAI_MODEMASTER_TX ((uint32_t)0x00000000) #define SAI_MODEMASTER_RX ((uint32_t)SAI_xCR1_MODE_0) #define SAI_MODESLAVE_TX ((uint32_t)SAI_xCR1_MODE_1) #define SAI_MODESLAVE_RX ((uint32_t)(SAI_xCR1_MODE_1 | SAI_xCR1_MODE_0)) /** * @} */ /** @defgroup SAI_Block_Protocol SAI Block Protocol * @{ */ #define SAI_FREE_PROTOCOL ((uint32_t)0x00000000) #define SAI_SPDIF_PROTOCOL ((uint32_t)SAI_xCR1_PRTCFG_0) #define SAI_AC97_PROTOCOL ((uint32_t)SAI_xCR1_PRTCFG_1) /** * @} */ /** @defgroup SAI_Block_Data_Size SAI Block Data Size * @{ */ #define SAI_DATASIZE_8 ((uint32_t)SAI_xCR1_DS_1) #define SAI_DATASIZE_10 ((uint32_t)(SAI_xCR1_DS_1 | SAI_xCR1_DS_0)) #define SAI_DATASIZE_16 ((uint32_t)SAI_xCR1_DS_2) #define SAI_DATASIZE_20 ((uint32_t)(SAI_xCR1_DS_2 | SAI_xCR1_DS_0)) #define SAI_DATASIZE_24 ((uint32_t)(SAI_xCR1_DS_2 | SAI_xCR1_DS_1)) #define SAI_DATASIZE_32 ((uint32_t)(SAI_xCR1_DS_2 | SAI_xCR1_DS_1 | SAI_xCR1_DS_0)) /** * @} */ /** @defgroup SAI_Block_MSB_LSB_transmission SAI Block MSB LSB transmission * @{ */ #define SAI_FIRSTBIT_MSB ((uint32_t)0x00000000) #define SAI_FIRSTBIT_LSB ((uint32_t)SAI_xCR1_LSBFIRST) /** * @} */ /** @defgroup SAI_Block_Clock_Strobing SAI Block Clock Strobing * @{ */ #define SAI_CLOCKSTROBING_FALLINGEDGE ((uint32_t)0x00000000) #define SAI_CLOCKSTROBING_RISINGEDGE ((uint32_t)SAI_xCR1_CKSTR) /** * @} */ /** @defgroup SAI_Block_Synchronization SAI Block Synchronization * @{ */ #define SAI_ASYNCHRONOUS ((uint32_t)0x00000000) #define SAI_SYNCHRONOUS ((uint32_t)SAI_xCR1_SYNCEN_0) #define SAI_SYNCHRONOUS_EXT ((uint32_t)SAI_xCR1_SYNCEN_1) /** * @} */ /** @defgroup SAI_Block_Output_Drive SAI Block Output Drive * @{ */ #define SAI_OUTPUTDRIVE_DISABLE ((uint32_t)0x00000000) #define SAI_OUTPUTDRIVE_ENABLE ((uint32_t)SAI_xCR1_OUTDRIV) /** * @} */ /** @defgroup SAI_Block_NoDivider SAI Block NoDivider * @{ */ #define SAI_MASTERDIVIDER_ENABLE ((uint32_t)0x00000000) #define SAI_MASTERDIVIDER_DISABLE ((uint32_t)SAI_xCR1_NODIV) /** * @} */ /** @defgroup SAI_Block_FS_Definition SAI Block FS Definition * @{ */ #define SAI_FS_STARTFRAME ((uint32_t)0x00000000) #define SAI_FS_CHANNEL_IDENTIFICATION ((uint32_t)SAI_xFRCR_FSDEF) /** * @} */ /** @defgroup SAI_Block_FS_Polarity SAI Block FS Polarity * @{ */ #define SAI_FS_ACTIVE_LOW ((uint32_t)0x00000000) #define SAI_FS_ACTIVE_HIGH ((uint32_t)SAI_xFRCR_FSPO) /** * @} */ /** @defgroup SAI_Block_FS_Offset SAI Block FS Offset * @{ */ #define SAI_FS_FIRSTBIT ((uint32_t)0x00000000) #define SAI_FS_BEFOREFIRSTBIT ((uint32_t)SAI_xFRCR_FSOFF) /** * @} */ /** @defgroup SAI_Block_Slot_Size SAI Block Slot Size * @{ */ #define SAI_SLOTSIZE_DATASIZE ((uint32_t)0x00000000) #define SAI_SLOTSIZE_16B ((uint32_t)SAI_xSLOTR_SLOTSZ_0) #define SAI_SLOTSIZE_32B ((uint32_t)SAI_xSLOTR_SLOTSZ_1) /** * @} */ /** @defgroup SAI_Block_Slot_Active SAI Block Slot Active * @{ */ #define SAI_SLOT_NOTACTIVE ((uint32_t)0x00000000) #define SAI_SLOTACTIVE_0 ((uint32_t)0x00010000) #define SAI_SLOTACTIVE_1 ((uint32_t)0x00020000) #define SAI_SLOTACTIVE_2 ((uint32_t)0x00040000) #define SAI_SLOTACTIVE_3 ((uint32_t)0x00080000) #define SAI_SLOTACTIVE_4 ((uint32_t)0x00100000) #define SAI_SLOTACTIVE_5 ((uint32_t)0x00200000) #define SAI_SLOTACTIVE_6 ((uint32_t)0x00400000) #define SAI_SLOTACTIVE_7 ((uint32_t)0x00800000) #define SAI_SLOTACTIVE_8 ((uint32_t)0x01000000) #define SAI_SLOTACTIVE_9 ((uint32_t)0x02000000) #define SAI_SLOTACTIVE_10 ((uint32_t)0x04000000) #define SAI_SLOTACTIVE_11 ((uint32_t)0x08000000) #define SAI_SLOTACTIVE_12 ((uint32_t)0x10000000) #define SAI_SLOTACTIVE_13 ((uint32_t)0x20000000) #define SAI_SLOTACTIVE_14 ((uint32_t)0x40000000) #define SAI_SLOTACTIVE_15 ((uint32_t)0x80000000) #define SAI_SLOTACTIVE_ALL ((uint32_t)0xFFFF0000) /** * @} */ /** @defgroup SAI_Mono_Stereo_Mode SAI Mono Stereo Mode * @{ */ #define SAI_STEREOMODE ((uint32_t)0x00000000) #define SAI_MONOMODE ((uint32_t)SAI_xCR1_MONO) /** * @} */ /** @defgroup SAI_TRIState_Management SAI TRIState Management * @{ */ #define SAI_OUTPUT_NOTRELEASED ((uint32_t)0x00000000) #define SAI_OUTPUT_RELEASED ((uint32_t)SAI_xCR2_TRIS) /** * @} */ /** @defgroup SAI_Block_Fifo_Threshold SAI Block Fifo Threshold * @{ */ #define SAI_FIFOTHRESHOLD_EMPTY ((uint32_t)0x00000000) #define SAI_FIFOTHRESHOLD_1QF ((uint32_t)SAI_xCR2_FTH_0) #define SAI_FIFOTHRESHOLD_HF ((uint32_t)SAI_xCR2_FTH_1) #define SAI_FIFOTHRESHOLD_3QF ((uint32_t)(SAI_xCR2_FTH_1 | SAI_xCR2_FTH_0)) #define SAI_FIFOTHRESHOLD_FULL ((uint32_t)SAI_xCR2_FTH_2) /** * @} */ /** @defgroup SAI_Block_Companding_Mode SAI Block Companding Mode * @{ */ #define SAI_NOCOMPANDING ((uint32_t)0x00000000) #define SAI_ULAW_1CPL_COMPANDING ((uint32_t)SAI_xCR2_COMP_1) #define SAI_ALAW_1CPL_COMPANDING ((uint32_t)(SAI_xCR2_COMP_1 | SAI_xCR2_COMP_0)) #define SAI_ULAW_2CPL_COMPANDING ((uint32_t)(SAI_xCR2_COMP_1 | SAI_xCR2_CPL)) #define SAI_ALAW_2CPL_COMPANDING ((uint32_t)(SAI_xCR2_COMP_1 | SAI_xCR2_COMP_0 | SAI_xCR2_CPL)) /** * @} */ /** @defgroup SAI_Block_Mute_Value SAI Block Mute Value * @{ */ #define SAI_ZERO_VALUE ((uint32_t)0x00000000) #define SAI_LAST_SENT_VALUE ((uint32_t)SAI_xCR2_MUTEVAL) /** * @} */ /** @defgroup SAI_Block_Interrupts_Definition SAI Block Interrupts Definition * @{ */ #define SAI_IT_OVRUDR ((uint32_t)SAI_xIMR_OVRUDRIE) #define SAI_IT_MUTEDET ((uint32_t)SAI_xIMR_MUTEDETIE) #define SAI_IT_WCKCFG ((uint32_t)SAI_xIMR_WCKCFGIE) #define SAI_IT_FREQ ((uint32_t)SAI_xIMR_FREQIE) #define SAI_IT_CNRDY ((uint32_t)SAI_xIMR_CNRDYIE) #define SAI_IT_AFSDET ((uint32_t)SAI_xIMR_AFSDETIE) #define SAI_IT_LFSDET ((uint32_t)SAI_xIMR_LFSDETIE) /** * @} */ /** @defgroup SAI_Block_Flags_Definition SAI Block Flags Definition * @{ */ #define SAI_FLAG_OVRUDR ((uint32_t)SAI_xSR_OVRUDR) #define SAI_FLAG_MUTEDET ((uint32_t)SAI_xSR_MUTEDET) #define SAI_FLAG_WCKCFG ((uint32_t)SAI_xSR_WCKCFG) #define SAI_FLAG_FREQ ((uint32_t)SAI_xSR_FREQ) #define SAI_FLAG_CNRDY ((uint32_t)SAI_xSR_CNRDY) #define SAI_FLAG_AFSDET ((uint32_t)SAI_xSR_AFSDET) #define SAI_FLAG_LFSDET ((uint32_t)SAI_xSR_LFSDET) /** * @} */ /** @defgroup SAI_Block_Fifo_Status_Level SAI Block Fifo Status Level * @{ */ #define SAI_FIFOSTATUS_EMPTY ((uint32_t)0x00000000) #define SAI_FIFOSTATUS_LESS1QUARTERFULL ((uint32_t)0x00010000) #define SAI_FIFOSTATUS_1QUARTERFULL ((uint32_t)0x00020000) #define SAI_FIFOSTATUS_HALFFULL ((uint32_t)0x00030000) #define SAI_FIFOSTATUS_3QUARTERFULL ((uint32_t)0x00040000) #define SAI_FIFOSTATUS_FULL ((uint32_t)0x00050000) /** * @} */ /** * @} */ /* Exported macro ------------------------------------------------------------*/ /** @defgroup SAI_Exported_Macros SAI Exported Macros * @brief macros to handle interrupts and specific configurations * @{ */ /** @brief Reset SAI handle state * @param __HANDLE__: specifies the SAI Handle. * @retval None */ #define __HAL_SAI_RESET_HANDLE_STATE(__HANDLE__) ((__HANDLE__)->State = HAL_SAI_STATE_RESET) /** @brief Enable or disable the specified SAI interrupts. * @param __HANDLE__: specifies the SAI Handle. * @param __INTERRUPT__: specifies the interrupt source to enable or disable. * This parameter can be one of the following values: * @arg SAI_IT_OVRUDR: Overrun underrun interrupt enable * @arg SAI_IT_MUTEDET: Mute detection interrupt enable * @arg SAI_IT_WCKCFG: Wrong Clock Configuration interrupt enable * @arg SAI_IT_FREQ: FIFO request interrupt enable * @arg SAI_IT_CNRDY: Codec not ready interrupt enable * @arg SAI_IT_AFSDET: Anticipated frame synchronization detection interrupt enable * @arg SAI_IT_LFSDET: Late frame synchronization detection interrupt enabl * @retval None */ #define __HAL_SAI_ENABLE_IT(__HANDLE__, __INTERRUPT__) ((__HANDLE__)->Instance->IMR |= (__INTERRUPT__)) #define __HAL_SAI_DISABLE_IT(__HANDLE__, __INTERRUPT__) ((__HANDLE__)->Instance->IMR &= (~(__INTERRUPT__))) /** @brief Check if the specified SAI interrupt source is enabled or disabled. * @param __HANDLE__: specifies the SAI Handle. * This parameter can be SAI where x: 1, 2, or 3 to select the SAI peripheral. * @param __INTERRUPT__: specifies the SAI interrupt source to check. * This parameter can be one of the following values: * @arg SAI_IT_TXE: Tx buffer empty interrupt enable. * @arg SAI_IT_RXNE: Rx buffer not empty interrupt enable. * @arg SAI_IT_ERR: Error interrupt enable. * @retval The new state of __INTERRUPT__ (TRUE or FALSE). */ #define __HAL_SAI_GET_IT_SOURCE(__HANDLE__, __INTERRUPT__) ((((__HANDLE__)->Instance->IMR & (__INTERRUPT__)) == (__INTERRUPT__)) ? SET : RESET) /** @brief Check whether the specified SAI flag is set or not. * @param __HANDLE__: specifies the SAI Handle. * @param __FLAG__: specifies the flag to check. * This parameter can be one of the following values: * @arg SAI_FLAG_OVRUDR: Overrun underrun flag. * @arg SAI_FLAG_MUTEDET: Mute detection flag. * @arg SAI_FLAG_WCKCFG: Wrong Clock Configuration flag. * @arg SAI_FLAG_FREQ: FIFO request flag. * @arg SAI_FLAG_CNRDY: Codec not ready flag. * @arg SAI_FLAG_AFSDET: Anticipated frame synchronization detection flag. * @arg SAI_FLAG_LFSDET: Late frame synchronization detection flag. * @retval The new state of __FLAG__ (TRUE or FALSE). */ #define __HAL_SAI_GET_FLAG(__HANDLE__, __FLAG__) ((((__HANDLE__)->Instance->SR) & (__FLAG__)) == (__FLAG__)) /** @brief Clears the specified SAI pending flag. * @param __HANDLE__: specifies the SAI Handle. * @param __FLAG__: specifies the flag to check. * This parameter can be any combination of the following values: * @arg SAI_FLAG_OVRUDR: Clear Overrun underrun * @arg SAI_FLAG_MUTEDET: Clear Mute detection * @arg SAI_FLAG_WCKCFG: Clear Wrong Clock Configuration * @arg SAI_FLAG_FREQ: Clear FIFO request * @arg SAI_FLAG_CNRDY: Clear Codec not ready * @arg SAI_FLAG_AFSDET: Clear Anticipated frame synchronization detection * @arg SAI_FLAG_LFSDET: Clear Late frame synchronization detection * * @retval None */ #define __HAL_SAI_CLEAR_FLAG(__HANDLE__, __FLAG__) ((__HANDLE__)->Instance->CLRFR = (__FLAG__)) #define __HAL_SAI_ENABLE(__HANDLE__) ((__HANDLE__)->Instance->CR1 |= SAI_xCR1_SAIEN) #define __HAL_SAI_DISABLE(__HANDLE__) ((__HANDLE__)->Instance->CR1 &= ~SAI_xCR1_SAIEN) /** * @} */ /* Include RCC SAI Extension module */ #include "stm32f4xx_hal_sai_ex.h" /* Exported functions --------------------------------------------------------*/ /** @addtogroup SAI_Exported_Functions * @{ */ /* Initialization/de-initialization functions **********************************/ /** @addtogroup SAI_Exported_Functions_Group1 * @{ */ HAL_StatusTypeDef HAL_SAI_InitProtocol(SAI_HandleTypeDef *hsai, uint32_t protocol, uint32_t datasize, uint32_t nbslot); HAL_StatusTypeDef HAL_SAI_Init(SAI_HandleTypeDef *hsai); HAL_StatusTypeDef HAL_SAI_DeInit (SAI_HandleTypeDef *hsai); void HAL_SAI_MspInit(SAI_HandleTypeDef *hsai); void HAL_SAI_MspDeInit(SAI_HandleTypeDef *hsai); /** * @} */ /* I/O operation functions *****************************************************/ /** @addtogroup SAI_Exported_Functions_Group2 * @{ */ /* Blocking mode: Polling */ HAL_StatusTypeDef HAL_SAI_Transmit(SAI_HandleTypeDef *hsai, uint8_t *pData, uint16_t Size, uint32_t Timeout); HAL_StatusTypeDef HAL_SAI_Receive(SAI_HandleTypeDef *hsai, uint8_t *pData, uint16_t Size, uint32_t Timeout); /* Non-Blocking mode: Interrupt */ HAL_StatusTypeDef HAL_SAI_Transmit_IT(SAI_HandleTypeDef *hsai, uint8_t *pData, uint16_t Size); HAL_StatusTypeDef HAL_SAI_Receive_IT(SAI_HandleTypeDef *hsai, uint8_t *pData, uint16_t Size); /* Non-Blocking mode: DMA */ HAL_StatusTypeDef HAL_SAI_Transmit_DMA(SAI_HandleTypeDef *hsai, uint8_t *pData, uint16_t Size); HAL_StatusTypeDef HAL_SAI_Receive_DMA(SAI_HandleTypeDef *hsai, uint8_t *pData, uint16_t Size); HAL_StatusTypeDef HAL_SAI_DMAPause(SAI_HandleTypeDef *hsai); HAL_StatusTypeDef HAL_SAI_DMAResume(SAI_HandleTypeDef *hsai); HAL_StatusTypeDef HAL_SAI_DMAStop(SAI_HandleTypeDef *hsai); /* Abort function */ HAL_StatusTypeDef HAL_SAI_Abort(SAI_HandleTypeDef *hsai); /* Mute management */ HAL_StatusTypeDef HAL_SAI_EnableTxMuteMode(SAI_HandleTypeDef *hsai, uint16_t val); HAL_StatusTypeDef HAL_SAI_DisableTxMuteMode(SAI_HandleTypeDef *hsai); HAL_StatusTypeDef HAL_SAI_EnableRxMuteMode(SAI_HandleTypeDef *hsai, SAIcallback callback, uint16_t counter); HAL_StatusTypeDef HAL_SAI_DisableRxMuteMode(SAI_HandleTypeDef *hsai); /* SAI IRQHandler and Callbacks used in non blocking modes (Interrupt and DMA) */ void HAL_SAI_IRQHandler(SAI_HandleTypeDef *hsai); void HAL_SAI_TxHalfCpltCallback(SAI_HandleTypeDef *hsai); void HAL_SAI_TxCpltCallback(SAI_HandleTypeDef *hsai); void HAL_SAI_RxHalfCpltCallback(SAI_HandleTypeDef *hsai); void HAL_SAI_RxCpltCallback(SAI_HandleTypeDef *hsai); void HAL_SAI_ErrorCallback(SAI_HandleTypeDef *hsai); /** * @} */ /** @addtogroup SAI_Exported_Functions_Group3 * @{ */ /* Peripheral State functions **************************************************/ HAL_SAI_StateTypeDef HAL_SAI_GetState(SAI_HandleTypeDef *hsai); uint32_t HAL_SAI_GetError(SAI_HandleTypeDef *hsai); /** * @} */ /** * @} */ /* Private types -------------------------------------------------------------*/ /** @defgroup SAI_Private_Types SAI Private Types * @{ */ /** * @} */ /* Private variables ---------------------------------------------------------*/ /** @defgroup SAI_Private_Variables SAI Private Variables * @{ */ /** * @} */ /* Private constants ---------------------------------------------------------*/ /** @defgroup SAI_Private_Constants SAI Private Constants * @{ */ /** * @} */ /* Private macros ------------------------------------------------------------*/ /** @addtogroup SAI_Private_Macros * @{ */ #define IS_SAI_BLOCK_SYNCEXT(STATE) (((STATE) == SAI_SYNCEXT_DISABLE) ||\ ((STATE) == SAI_SYNCEXT_IN_ENABLE) ||\ ((STATE) == SAI_SYNCEXT_OUTBLOCKA_ENABLE) ||\ ((STATE) == SAI_SYNCEXT_OUTBLOCKB_ENABLE)) #define IS_SAI_SUPPORTED_PROTOCOL(PROTOCOL) (((PROTOCOL) == SAI_I2S_STANDARD) ||\ ((PROTOCOL) == SAI_I2S_MSBJUSTIFIED) ||\ ((PROTOCOL) == SAI_I2S_LSBJUSTIFIED) ||\ ((PROTOCOL) == SAI_PCM_LONG) ||\ ((PROTOCOL) == SAI_PCM_SHORT)) #define IS_SAI_PROTOCOL_DATASIZE(DATASIZE) (((DATASIZE) == SAI_PROTOCOL_DATASIZE_16BIT) ||\ ((DATASIZE) == SAI_PROTOCOL_DATASIZE_16BITEXTENDED) ||\ ((DATASIZE) == SAI_PROTOCOL_DATASIZE_24BIT) ||\ ((DATASIZE) == SAI_PROTOCOL_DATASIZE_32BIT)) #define IS_SAI_CLK_SOURCE(SOURCE) (((SOURCE) == SAI_CLKSOURCE_PLLSAI) ||\ ((SOURCE) == SAI_CLKSOURCE_PLLI2S) ||\ ((SOURCE) == SAI_CLKSOURCE_EXT)) #define IS_SAI_AUDIO_FREQUENCY(AUDIO) (((AUDIO) == SAI_AUDIO_FREQUENCY_192K) || ((AUDIO) == SAI_AUDIO_FREQUENCY_96K) || \ ((AUDIO) == SAI_AUDIO_FREQUENCY_48K) || ((AUDIO) == SAI_AUDIO_FREQUENCY_44K) || \ ((AUDIO) == SAI_AUDIO_FREQUENCY_32K) || ((AUDIO) == SAI_AUDIO_FREQUENCY_22K) || \ ((AUDIO) == SAI_AUDIO_FREQUENCY_16K) || ((AUDIO) == SAI_AUDIO_FREQUENCY_11K) || \ ((AUDIO) == SAI_AUDIO_FREQUENCY_8K) || ((AUDIO) == SAI_AUDIO_FREQUENCY_MCKDIV)) #define IS_SAI_BLOCK_MODE(MODE) (((MODE) == SAI_MODEMASTER_TX) || \ ((MODE) == SAI_MODEMASTER_RX) || \ ((MODE) == SAI_MODESLAVE_TX) || \ ((MODE) == SAI_MODESLAVE_RX)) #define IS_SAI_BLOCK_PROTOCOL(PROTOCOL) (((PROTOCOL) == SAI_FREE_PROTOCOL) || \ ((PROTOCOL) == SAI_AC97_PROTOCOL) || \ ((PROTOCOL) == SAI_SPDIF_PROTOCOL)) #define IS_SAI_BLOCK_DATASIZE(DATASIZE) (((DATASIZE) == SAI_DATASIZE_8) || \ ((DATASIZE) == SAI_DATASIZE_10) || \ ((DATASIZE) == SAI_DATASIZE_16) || \ ((DATASIZE) == SAI_DATASIZE_20) || \ ((DATASIZE) == SAI_DATASIZE_24) || \ ((DATASIZE) == SAI_DATASIZE_32)) #define IS_SAI_BLOCK_FIRST_BIT(BIT) (((BIT) == SAI_FIRSTBIT_MSB) || \ ((BIT) == SAI_FIRSTBIT_LSB)) #define IS_SAI_BLOCK_CLOCK_STROBING(CLOCK) (((CLOCK) == SAI_CLOCKSTROBING_FALLINGEDGE) || \ ((CLOCK) == SAI_CLOCKSTROBING_RISINGEDGE)) #define IS_SAI_BLOCK_SYNCHRO(SYNCHRO) (((SYNCHRO) == SAI_ASYNCHRONOUS) || \ ((SYNCHRO) == SAI_SYNCHRONOUS) || \ ((SYNCHRO) == SAI_SYNCHRONOUS_EXT)) #define IS_SAI_BLOCK_OUTPUT_DRIVE(DRIVE) (((DRIVE) == SAI_OUTPUTDRIVE_DISABLE) || \ ((DRIVE) == SAI_OUTPUTDRIVE_ENABLE)) #define IS_SAI_BLOCK_NODIVIDER(NODIVIDER) (((NODIVIDER) == SAI_MASTERDIVIDER_ENABLE) || \ ((NODIVIDER) == SAI_MASTERDIVIDER_DISABLE)) #define IS_SAI_BLOCK_FIFO_STATUS(STATUS) (((STATUS) == SAI_FIFOSTATUS_LESS1QUARTERFULL ) || \ ((STATUS) == SAI_FIFOSTATUS_HALFFULL) || \ ((STATUS) == SAI_FIFOSTATUS_1QUARTERFULL) || \ ((STATUS) == SAI_FIFOSTATUS_3QUARTERFULL) || \ ((STATUS) == SAI_FIFOSTATUS_FULL) || \ ((STATUS) == SAI_FIFOSTATUS_EMPTY)) #define IS_SAI_BLOCK_MUTE_COUNTER(COUNTER) ((COUNTER) <= 63) #define IS_SAI_BLOCK_MUTE_VALUE(VALUE) (((VALUE) == SAI_ZERO_VALUE) || \ ((VALUE) == SAI_LAST_SENT_VALUE)) #define IS_SAI_BLOCK_COMPANDING_MODE(MODE) (((MODE) == SAI_NOCOMPANDING) || \ ((MODE) == SAI_ULAW_1CPL_COMPANDING) || \ ((MODE) == SAI_ALAW_1CPL_COMPANDING) || \ ((MODE) == SAI_ULAW_2CPL_COMPANDING) || \ ((MODE) == SAI_ALAW_2CPL_COMPANDING)) #define IS_SAI_BLOCK_FIFO_THRESHOLD(THRESHOLD) (((THRESHOLD) == SAI_FIFOTHRESHOLD_EMPTY) || \ ((THRESHOLD) == SAI_FIFOTHRESHOLD_1QF) || \ ((THRESHOLD) == SAI_FIFOTHRESHOLD_HF) || \ ((THRESHOLD) == SAI_FIFOTHRESHOLD_3QF) || \ ((THRESHOLD) == SAI_FIFOTHRESHOLD_FULL)) #define IS_SAI_BLOCK_TRISTATE_MANAGEMENT(STATE) (((STATE) == SAI_OUTPUT_NOTRELEASED) ||\ ((STATE) == SAI_OUTPUT_RELEASED)) #define IS_SAI_MONO_STEREO_MODE(MODE) (((MODE) == SAI_MONOMODE) ||\ ((MODE) == SAI_STEREOMODE)) #define IS_SAI_SLOT_ACTIVE(ACTIVE) ((((ACTIVE) >> 16 ) > 0) && (((ACTIVE) >> 16 ) <= (SAI_SLOTACTIVE_ALL >> 16))) #define IS_SAI_BLOCK_SLOT_NUMBER(NUMBER) ((1 <= (NUMBER)) && ((NUMBER) <= 16)) #define IS_SAI_BLOCK_SLOT_SIZE(SIZE) (((SIZE) == SAI_SLOTSIZE_DATASIZE) || \ ((SIZE) == SAI_SLOTSIZE_16B) || \ ((SIZE) == SAI_SLOTSIZE_32B)) #define IS_SAI_BLOCK_FIRSTBIT_OFFSET(OFFSET) ((OFFSET) <= 24) #define IS_SAI_BLOCK_FS_OFFSET(OFFSET) (((OFFSET) == SAI_FS_FIRSTBIT) || \ ((OFFSET) == SAI_FS_BEFOREFIRSTBIT)) #define IS_SAI_BLOCK_FS_POLARITY(POLARITY) (((POLARITY) == SAI_FS_ACTIVE_LOW) || \ ((POLARITY) == SAI_FS_ACTIVE_HIGH)) #define IS_SAI_BLOCK_FS_DEFINITION(DEFINITION) (((DEFINITION) == SAI_FS_STARTFRAME) || \ ((DEFINITION) == SAI_FS_CHANNEL_IDENTIFICATION)) #define IS_SAI_BLOCK_MASTER_DIVIDER(DIVIDER) ((DIVIDER) <= 15) #define IS_SAI_BLOCK_FRAME_LENGTH(LENGTH) ((8 <= (LENGTH)) && ((LENGTH) <= 256)) #define IS_SAI_BLOCK_ACTIVE_FRAME(LENGTH) ((1 <= (LENGTH)) && ((LENGTH) <= 128)) /** * @} */ /* Private functions ---------------------------------------------------------*/ /** @defgroup SAI_Private_Functions SAI Private Functions * @{ */ /** * @} */ #endif /* STM32F427xx || STM32F437xx || STM32F429xx || STM32F439xx || STM32F446xx || STM32F469xx || STM32F479xx */ /** * @} */ /** * @} */ #ifdef __cplusplus } #endif #endif /* __STM32F4xx_HAL_SAI_H */ /************************ (C) COPYRIGHT STMicroelectronics *****END OF FILE****/ ================================================ FILE: Zelig/mbed/TARGET_NUCLEO_F411RE/stm32f4xx_hal_sai_ex.h ================================================ /** ****************************************************************************** * @file stm32f4xx_hal_sai_ex.h * @author MCD Application Team * @version V1.4.1 * @date 09-October-2015 * @brief Header file of SAI Extension HAL module. ****************************************************************************** * @attention * *

© COPYRIGHT(c) 2015 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. * ****************************************************************************** */ /* Define to prevent recursive inclusion -------------------------------------*/ #ifndef __STM32F4xx_HAL_SAI_EX_H #define __STM32F4xx_HAL_SAI_EX_H #ifdef __cplusplus extern "C" { #endif /* Includes ------------------------------------------------------------------*/ #include "stm32f4xx_hal_def.h" /** @addtogroup STM32F4xx_HAL_Driver * @{ */ /** @addtogroup SAIEx * @{ */ #if defined(STM32F427xx) || defined(STM32F437xx) || defined(STM32F429xx) || defined(STM32F439xx) ||\ defined(STM32F446xx) || defined(STM32F469xx) || defined(STM32F479xx) /* Exported types ------------------------------------------------------------*/ /* Exported constants --------------------------------------------------------*/ /* Exported functions --------------------------------------------------------*/ /** @addtogroup SAIEx_Exported_Functions * @{ */ /** @addtogroup SAIEx_Exported_Functions_Group1 * @{ */ /* Extended features functions ************************************************/ void SAI_BlockSynchroConfig(SAI_HandleTypeDef *hsai); uint32_t SAI_GetInputClock(SAI_HandleTypeDef *hsai); /** * @} */ /** * @} */ /* Private types -------------------------------------------------------------*/ /* Private variables ---------------------------------------------------------*/ /* Private constants ---------------------------------------------------------*/ /* Private macros ------------------------------------------------------------*/ /* Private functions ---------------------------------------------------------*/ #endif /* STM32F427xx || STM32F437xx || STM32F429xx || STM32F439xx || STM32F446xx || STM32F469xx || STM32F479xx */ /** * @} */ /** * @} */ #ifdef __cplusplus } #endif #endif /* __STM32F4xx_HAL_SAI_EX_H */ /************************ (C) COPYRIGHT STMicroelectronics *****END OF FILE****/ ================================================ FILE: Zelig/mbed/TARGET_NUCLEO_F411RE/stm32f4xx_hal_sd.h ================================================ /** ****************************************************************************** * @file stm32f4xx_hal_sd.h * @author MCD Application Team * @version V1.4.1 * @date 09-October-2015 * @brief Header file of SD HAL module. ****************************************************************************** * @attention * *

© COPYRIGHT(c) 2015 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. * ****************************************************************************** */ /* Define to prevent recursive inclusion -------------------------------------*/ #ifndef __STM32F4xx_HAL_SD_H #define __STM32F4xx_HAL_SD_H #ifdef __cplusplus extern "C" { #endif #if defined(STM32F405xx) || defined(STM32F415xx) || defined(STM32F407xx) || defined(STM32F417xx) || \ defined(STM32F427xx) || defined(STM32F437xx) || defined(STM32F429xx) || defined(STM32F439xx) || \ defined(STM32F401xC) || defined(STM32F401xE) || defined(STM32F411xE) || defined(STM32F446xx) || \ defined(STM32F469xx) || defined(STM32F479xx) /* Includes ------------------------------------------------------------------*/ #include "stm32f4xx_ll_sdmmc.h" /** @addtogroup STM32F4xx_HAL_Driver * @{ */ /** @defgroup SD SD * @brief SD HAL module driver * @{ */ /* Exported types ------------------------------------------------------------*/ /** @defgroup SD_Exported_Types SD Exported Types * @{ */ /** @defgroup SD_Exported_Types_Group1 SD Handle Structure definition * @{ */ #define SD_InitTypeDef SDIO_InitTypeDef #define SD_TypeDef SDIO_TypeDef typedef struct { SD_TypeDef *Instance; /*!< SDIO register base address */ SD_InitTypeDef Init; /*!< SD required parameters */ HAL_LockTypeDef Lock; /*!< SD locking object */ uint32_t CardType; /*!< SD card type */ uint32_t RCA; /*!< SD relative card address */ uint32_t CSD[4]; /*!< SD card specific data table */ uint32_t CID[4]; /*!< SD card identification number table */ __IO uint32_t SdTransferCplt; /*!< SD transfer complete flag in non blocking mode */ __IO uint32_t SdTransferErr; /*!< SD transfer error flag in non blocking mode */ __IO uint32_t DmaTransferCplt; /*!< SD DMA transfer complete flag */ __IO uint32_t SdOperation; /*!< SD transfer operation (read/write) */ DMA_HandleTypeDef *hdmarx; /*!< SD Rx DMA handle parameters */ DMA_HandleTypeDef *hdmatx; /*!< SD Tx DMA handle parameters */ }SD_HandleTypeDef; /** * @} */ /** @defgroup SD_Exported_Types_Group2 Card Specific Data: CSD Register * @{ */ typedef struct { __IO uint8_t CSDStruct; /*!< CSD structure */ __IO uint8_t SysSpecVersion; /*!< System specification version */ __IO uint8_t Reserved1; /*!< Reserved */ __IO uint8_t TAAC; /*!< Data read access time 1 */ __IO uint8_t NSAC; /*!< Data read access time 2 in CLK cycles */ __IO uint8_t MaxBusClkFrec; /*!< Max. bus clock frequency */ __IO uint16_t CardComdClasses; /*!< Card command classes */ __IO uint8_t RdBlockLen; /*!< Max. read data block length */ __IO uint8_t PartBlockRead; /*!< Partial blocks for read allowed */ __IO uint8_t WrBlockMisalign; /*!< Write block misalignment */ __IO uint8_t RdBlockMisalign; /*!< Read block misalignment */ __IO uint8_t DSRImpl; /*!< DSR implemented */ __IO uint8_t Reserved2; /*!< Reserved */ __IO uint32_t DeviceSize; /*!< Device Size */ __IO uint8_t MaxRdCurrentVDDMin; /*!< Max. read current @ VDD min */ __IO uint8_t MaxRdCurrentVDDMax; /*!< Max. read current @ VDD max */ __IO uint8_t MaxWrCurrentVDDMin; /*!< Max. write current @ VDD min */ __IO uint8_t MaxWrCurrentVDDMax; /*!< Max. write current @ VDD max */ __IO uint8_t DeviceSizeMul; /*!< Device size multiplier */ __IO uint8_t EraseGrSize; /*!< Erase group size */ __IO uint8_t EraseGrMul; /*!< Erase group size multiplier */ __IO uint8_t WrProtectGrSize; /*!< Write protect group size */ __IO uint8_t WrProtectGrEnable; /*!< Write protect group enable */ __IO uint8_t ManDeflECC; /*!< Manufacturer default ECC */ __IO uint8_t WrSpeedFact; /*!< Write speed factor */ __IO uint8_t MaxWrBlockLen; /*!< Max. write data block length */ __IO uint8_t WriteBlockPaPartial; /*!< Partial blocks for write allowed */ __IO uint8_t Reserved3; /*!< Reserved */ __IO uint8_t ContentProtectAppli; /*!< Content protection application */ __IO uint8_t FileFormatGrouop; /*!< File format group */ __IO uint8_t CopyFlag; /*!< Copy flag (OTP) */ __IO uint8_t PermWrProtect; /*!< Permanent write protection */ __IO uint8_t TempWrProtect; /*!< Temporary write protection */ __IO uint8_t FileFormat; /*!< File format */ __IO uint8_t ECC; /*!< ECC code */ __IO uint8_t CSD_CRC; /*!< CSD CRC */ __IO uint8_t Reserved4; /*!< Always 1 */ }HAL_SD_CSDTypedef; /** * @} */ /** @defgroup SD_Exported_Types_Group3 Card Identification Data: CID Register * @{ */ typedef struct { __IO uint8_t ManufacturerID; /*!< Manufacturer ID */ __IO uint16_t OEM_AppliID; /*!< OEM/Application ID */ __IO uint32_t ProdName1; /*!< Product Name part1 */ __IO uint8_t ProdName2; /*!< Product Name part2 */ __IO uint8_t ProdRev; /*!< Product Revision */ __IO uint32_t ProdSN; /*!< Product Serial Number */ __IO uint8_t Reserved1; /*!< Reserved1 */ __IO uint16_t ManufactDate; /*!< Manufacturing Date */ __IO uint8_t CID_CRC; /*!< CID CRC */ __IO uint8_t Reserved2; /*!< Always 1 */ }HAL_SD_CIDTypedef; /** * @} */ /** @defgroup SD_Exported_Types_Group4 SD Card Status returned by ACMD13 * @{ */ typedef struct { __IO uint8_t DAT_BUS_WIDTH; /*!< Shows the currently defined data bus width */ __IO uint8_t SECURED_MODE; /*!< Card is in secured mode of operation */ __IO uint16_t SD_CARD_TYPE; /*!< Carries information about card type */ __IO uint32_t SIZE_OF_PROTECTED_AREA; /*!< Carries information about the capacity of protected area */ __IO uint8_t SPEED_CLASS; /*!< Carries information about the speed class of the card */ __IO uint8_t PERFORMANCE_MOVE; /*!< Carries information about the card's performance move */ __IO uint8_t AU_SIZE; /*!< Carries information about the card's allocation unit size */ __IO uint16_t ERASE_SIZE; /*!< Determines the number of AUs to be erased in one operation */ __IO uint8_t ERASE_TIMEOUT; /*!< Determines the timeout for any number of AU erase */ __IO uint8_t ERASE_OFFSET; /*!< Carries information about the erase offset */ }HAL_SD_CardStatusTypedef; /** * @} */ /** @defgroup SD_Exported_Types_Group5 SD Card information structure * @{ */ typedef struct { HAL_SD_CSDTypedef SD_csd; /*!< SD card specific data register */ HAL_SD_CIDTypedef SD_cid; /*!< SD card identification number register */ uint64_t CardCapacity; /*!< Card capacity */ uint32_t CardBlockSize; /*!< Card block size */ uint16_t RCA; /*!< SD relative card address */ uint8_t CardType; /*!< SD card type */ }HAL_SD_CardInfoTypedef; /** * @} */ /** @defgroup SD_Exported_Types_Group6 SD Error status enumeration Structure definition * @{ */ typedef enum { /** * @brief SD specific error defines */ SD_CMD_CRC_FAIL = (1), /*!< Command response received (but CRC check failed) */ SD_DATA_CRC_FAIL = (2), /*!< Data block sent/received (CRC check failed) */ SD_CMD_RSP_TIMEOUT = (3), /*!< Command response timeout */ SD_DATA_TIMEOUT = (4), /*!< Data timeout */ SD_TX_UNDERRUN = (5), /*!< Transmit FIFO underrun */ SD_RX_OVERRUN = (6), /*!< Receive FIFO overrun */ SD_START_BIT_ERR = (7), /*!< Start bit not detected on all data signals in wide bus mode */ SD_CMD_OUT_OF_RANGE = (8), /*!< Command's argument was out of range. */ SD_ADDR_MISALIGNED = (9), /*!< Misaligned address */ SD_BLOCK_LEN_ERR = (10), /*!< Transferred block length is not allowed for the card or the number of transferred bytes does not match the block length */ SD_ERASE_SEQ_ERR = (11), /*!< An error in the sequence of erase command occurs. */ SD_BAD_ERASE_PARAM = (12), /*!< An invalid selection for erase groups */ SD_WRITE_PROT_VIOLATION = (13), /*!< Attempt to program a write protect block */ SD_LOCK_UNLOCK_FAILED = (14), /*!< Sequence or password error has been detected in unlock command or if there was an attempt to access a locked card */ SD_COM_CRC_FAILED = (15), /*!< CRC check of the previous command failed */ SD_ILLEGAL_CMD = (16), /*!< Command is not legal for the card state */ SD_CARD_ECC_FAILED = (17), /*!< Card internal ECC was applied but failed to correct the data */ SD_CC_ERROR = (18), /*!< Internal card controller error */ SD_GENERAL_UNKNOWN_ERROR = (19), /*!< General or unknown error */ SD_STREAM_READ_UNDERRUN = (20), /*!< The card could not sustain data transfer in stream read operation. */ SD_STREAM_WRITE_OVERRUN = (21), /*!< The card could not sustain data programming in stream mode */ SD_CID_CSD_OVERWRITE = (22), /*!< CID/CSD overwrite error */ SD_WP_ERASE_SKIP = (23), /*!< Only partial address space was erased */ SD_CARD_ECC_DISABLED = (24), /*!< Command has been executed without using internal ECC */ SD_ERASE_RESET = (25), /*!< Erase sequence was cleared before executing because an out of erase sequence command was received */ SD_AKE_SEQ_ERROR = (26), /*!< Error in sequence of authentication. */ SD_INVALID_VOLTRANGE = (27), SD_ADDR_OUT_OF_RANGE = (28), SD_SWITCH_ERROR = (29), SD_SDIO_DISABLED = (30), SD_SDIO_FUNCTION_BUSY = (31), SD_SDIO_FUNCTION_FAILED = (32), SD_SDIO_UNKNOWN_FUNCTION = (33), /** * @brief Standard error defines */ SD_INTERNAL_ERROR = (34), SD_NOT_CONFIGURED = (35), SD_REQUEST_PENDING = (36), SD_REQUEST_NOT_APPLICABLE = (37), SD_INVALID_PARAMETER = (38), SD_UNSUPPORTED_FEATURE = (39), SD_UNSUPPORTED_HW = (40), SD_ERROR = (41), SD_OK = (0) }HAL_SD_ErrorTypedef; /** * @} */ /** @defgroup SD_Exported_Types_Group7 SD Transfer state enumeration structure * @{ */ typedef enum { SD_TRANSFER_OK = 0, /*!< Transfer success */ SD_TRANSFER_BUSY = 1, /*!< Transfer is occurring */ SD_TRANSFER_ERROR = 2 /*!< Transfer failed */ }HAL_SD_TransferStateTypedef; /** * @} */ /** @defgroup SD_Exported_Types_Group8 SD Card State enumeration structure * @{ */ typedef enum { SD_CARD_READY = ((uint32_t)0x00000001), /*!< Card state is ready */ SD_CARD_IDENTIFICATION = ((uint32_t)0x00000002), /*!< Card is in identification state */ SD_CARD_STANDBY = ((uint32_t)0x00000003), /*!< Card is in standby state */ SD_CARD_TRANSFER = ((uint32_t)0x00000004), /*!< Card is in transfer state */ SD_CARD_SENDING = ((uint32_t)0x00000005), /*!< Card is sending an operation */ SD_CARD_RECEIVING = ((uint32_t)0x00000006), /*!< Card is receiving operation information */ SD_CARD_PROGRAMMING = ((uint32_t)0x00000007), /*!< Card is in programming state */ SD_CARD_DISCONNECTED = ((uint32_t)0x00000008), /*!< Card is disconnected */ SD_CARD_ERROR = ((uint32_t)0x000000FF) /*!< Card is in error state */ }HAL_SD_CardStateTypedef; /** * @} */ /** @defgroup SD_Exported_Types_Group9 SD Operation enumeration structure * @{ */ typedef enum { SD_READ_SINGLE_BLOCK = 0, /*!< Read single block operation */ SD_READ_MULTIPLE_BLOCK = 1, /*!< Read multiple blocks operation */ SD_WRITE_SINGLE_BLOCK = 2, /*!< Write single block operation */ SD_WRITE_MULTIPLE_BLOCK = 3 /*!< Write multiple blocks operation */ }HAL_SD_OperationTypedef; /** * @} */ /** * @} */ /* Exported constants --------------------------------------------------------*/ /** @defgroup SD_Exported_Constants SD Exported Constants * @{ */ /** * @brief SD Commands Index */ #define SD_CMD_GO_IDLE_STATE ((uint8_t)0) /*!< Resets the SD memory card. */ #define SD_CMD_SEND_OP_COND ((uint8_t)1) /*!< Sends host capacity support information and activates the card's initialization process. */ #define SD_CMD_ALL_SEND_CID ((uint8_t)2) /*!< Asks any card connected to the host to send the CID numbers on the CMD line. */ #define SD_CMD_SET_REL_ADDR ((uint8_t)3) /*!< Asks the card to publish a new relative address (RCA). */ #define SD_CMD_SET_DSR ((uint8_t)4) /*!< Programs the DSR of all cards. */ #define SD_CMD_SDIO_SEN_OP_COND ((uint8_t)5) /*!< Sends host capacity support information (HCS) and asks the accessed card to send its operating condition register (OCR) content in the response on the CMD line. */ #define SD_CMD_HS_SWITCH ((uint8_t)6) /*!< Checks switchable function (mode 0) and switch card function (mode 1). */ #define SD_CMD_SEL_DESEL_CARD ((uint8_t)7) /*!< Selects the card by its own relative address and gets deselected by any other address */ #define SD_CMD_HS_SEND_EXT_CSD ((uint8_t)8) /*!< Sends SD Memory Card interface condition, which includes host supply voltage information and asks the card whether card supports voltage. */ #define SD_CMD_SEND_CSD ((uint8_t)9) /*!< Addressed card sends its card specific data (CSD) on the CMD line. */ #define SD_CMD_SEND_CID ((uint8_t)10) /*!< Addressed card sends its card identification (CID) on the CMD line. */ #define SD_CMD_READ_DAT_UNTIL_STOP ((uint8_t)11) /*!< SD card doesn't support it. */ #define SD_CMD_STOP_TRANSMISSION ((uint8_t)12) /*!< Forces the card to stop transmission. */ #define SD_CMD_SEND_STATUS ((uint8_t)13) /*!< Addressed card sends its status register. */ #define SD_CMD_HS_BUSTEST_READ ((uint8_t)14) #define SD_CMD_GO_INACTIVE_STATE ((uint8_t)15) /*!< Sends an addressed card into the inactive state. */ #define SD_CMD_SET_BLOCKLEN ((uint8_t)16) /*!< Sets the block length (in bytes for SDSC) for all following block commands (read, write, lock). Default block length is fixed to 512 Bytes. Not effective for SDHS and SDXC. */ #define SD_CMD_READ_SINGLE_BLOCK ((uint8_t)17) /*!< Reads single block of size selected by SET_BLOCKLEN in case of SDSC, and a block of fixed 512 bytes in case of SDHC and SDXC. */ #define SD_CMD_READ_MULT_BLOCK ((uint8_t)18) /*!< Continuously transfers data blocks from card to host until interrupted by STOP_TRANSMISSION command. */ #define SD_CMD_HS_BUSTEST_WRITE ((uint8_t)19) /*!< 64 bytes tuning pattern is sent for SDR50 and SDR104. */ #define SD_CMD_WRITE_DAT_UNTIL_STOP ((uint8_t)20) /*!< Speed class control command. */ #define SD_CMD_SET_BLOCK_COUNT ((uint8_t)23) /*!< Specify block count for CMD18 and CMD25. */ #define SD_CMD_WRITE_SINGLE_BLOCK ((uint8_t)24) /*!< Writes single block of size selected by SET_BLOCKLEN in case of SDSC, and a block of fixed 512 bytes in case of SDHC and SDXC. */ #define SD_CMD_WRITE_MULT_BLOCK ((uint8_t)25) /*!< Continuously writes blocks of data until a STOP_TRANSMISSION follows. */ #define SD_CMD_PROG_CID ((uint8_t)26) /*!< Reserved for manufacturers. */ #define SD_CMD_PROG_CSD ((uint8_t)27) /*!< Programming of the programmable bits of the CSD. */ #define SD_CMD_SET_WRITE_PROT ((uint8_t)28) /*!< Sets the write protection bit of the addressed group. */ #define SD_CMD_CLR_WRITE_PROT ((uint8_t)29) /*!< Clears the write protection bit of the addressed group. */ #define SD_CMD_SEND_WRITE_PROT ((uint8_t)30) /*!< Asks the card to send the status of the write protection bits. */ #define SD_CMD_SD_ERASE_GRP_START ((uint8_t)32) /*!< Sets the address of the first write block to be erased. (For SD card only). */ #define SD_CMD_SD_ERASE_GRP_END ((uint8_t)33) /*!< Sets the address of the last write block of the continuous range to be erased. */ #define SD_CMD_ERASE_GRP_START ((uint8_t)35) /*!< Sets the address of the first write block to be erased. Reserved for each command system set by switch function command (CMD6). */ #define SD_CMD_ERASE_GRP_END ((uint8_t)36) /*!< Sets the address of the last write block of the continuous range to be erased. Reserved for each command system set by switch function command (CMD6). */ #define SD_CMD_ERASE ((uint8_t)38) /*!< Reserved for SD security applications. */ #define SD_CMD_FAST_IO ((uint8_t)39) /*!< SD card doesn't support it (Reserved). */ #define SD_CMD_GO_IRQ_STATE ((uint8_t)40) /*!< SD card doesn't support it (Reserved). */ #define SD_CMD_LOCK_UNLOCK ((uint8_t)42) /*!< Sets/resets the password or lock/unlock the card. The size of the data block is set by the SET_BLOCK_LEN command. */ #define SD_CMD_APP_CMD ((uint8_t)55) /*!< Indicates to the card that the next command is an application specific command rather than a standard command. */ #define SD_CMD_GEN_CMD ((uint8_t)56) /*!< Used either to transfer a data block to the card or to get a data block from the card for general purpose/application specific commands. */ #define SD_CMD_NO_CMD ((uint8_t)64) /** * @brief Following commands are SD Card Specific commands. * SDIO_APP_CMD should be sent before sending these commands. */ #define SD_CMD_APP_SD_SET_BUSWIDTH ((uint8_t)6) /*!< (ACMD6) Defines the data bus width to be used for data transfer. The allowed data bus widths are given in SCR register. */ #define SD_CMD_SD_APP_STATUS ((uint8_t)13) /*!< (ACMD13) Sends the SD status. */ #define SD_CMD_SD_APP_SEND_NUM_WRITE_BLOCKS ((uint8_t)22) /*!< (ACMD22) Sends the number of the written (without errors) write blocks. Responds with 32bit+CRC data block. */ #define SD_CMD_SD_APP_OP_COND ((uint8_t)41) /*!< (ACMD41) Sends host capacity support information (HCS) and asks the accessed card to send its operating condition register (OCR) content in the response on the CMD line. */ #define SD_CMD_SD_APP_SET_CLR_CARD_DETECT ((uint8_t)42) /*!< (ACMD42) Connects/Disconnects the 50 KOhm pull-up resistor on CD/DAT3 (pin 1) of the card. */ #define SD_CMD_SD_APP_SEND_SCR ((uint8_t)51) /*!< Reads the SD Configuration Register (SCR). */ #define SD_CMD_SDIO_RW_DIRECT ((uint8_t)52) /*!< For SD I/O card only, reserved for security specification. */ #define SD_CMD_SDIO_RW_EXTENDED ((uint8_t)53) /*!< For SD I/O card only, reserved for security specification. */ /** * @brief Following commands are SD Card Specific security commands. * SD_CMD_APP_CMD should be sent before sending these commands. */ #define SD_CMD_SD_APP_GET_MKB ((uint8_t)43) /*!< For SD card only */ #define SD_CMD_SD_APP_GET_MID ((uint8_t)44) /*!< For SD card only */ #define SD_CMD_SD_APP_SET_CER_RN1 ((uint8_t)45) /*!< For SD card only */ #define SD_CMD_SD_APP_GET_CER_RN2 ((uint8_t)46) /*!< For SD card only */ #define SD_CMD_SD_APP_SET_CER_RES2 ((uint8_t)47) /*!< For SD card only */ #define SD_CMD_SD_APP_GET_CER_RES1 ((uint8_t)48) /*!< For SD card only */ #define SD_CMD_SD_APP_SECURE_READ_MULTIPLE_BLOCK ((uint8_t)18) /*!< For SD card only */ #define SD_CMD_SD_APP_SECURE_WRITE_MULTIPLE_BLOCK ((uint8_t)25) /*!< For SD card only */ #define SD_CMD_SD_APP_SECURE_ERASE ((uint8_t)38) /*!< For SD card only */ #define SD_CMD_SD_APP_CHANGE_SECURE_AREA ((uint8_t)49) /*!< For SD card only */ #define SD_CMD_SD_APP_SECURE_WRITE_MKB ((uint8_t)48) /*!< For SD card only */ /** * @brief Supported SD Memory Cards */ #define STD_CAPACITY_SD_CARD_V1_1 ((uint32_t)0x00000000) #define STD_CAPACITY_SD_CARD_V2_0 ((uint32_t)0x00000001) #define HIGH_CAPACITY_SD_CARD ((uint32_t)0x00000002) #define MULTIMEDIA_CARD ((uint32_t)0x00000003) #define SECURE_DIGITAL_IO_CARD ((uint32_t)0x00000004) #define HIGH_SPEED_MULTIMEDIA_CARD ((uint32_t)0x00000005) #define SECURE_DIGITAL_IO_COMBO_CARD ((uint32_t)0x00000006) #define HIGH_CAPACITY_MMC_CARD ((uint32_t)0x00000007) /** * @} */ /* Exported macro ------------------------------------------------------------*/ /** @defgroup SD_Exported_macros SD Exported Macros * @brief macros to handle interrupts and specific clock configurations * @{ */ /** * @brief Enable the SD device. * @retval None */ #define __HAL_SD_SDIO_ENABLE() __SDIO_ENABLE() /** * @brief Disable the SD device. * @retval None */ #define __HAL_SD_SDIO_DISABLE() __SDIO_DISABLE() /** * @brief Enable the SDIO DMA transfer. * @retval None */ #define __HAL_SD_SDIO_DMA_ENABLE() __SDIO_DMA_ENABLE() /** * @brief Disable the SDIO DMA transfer. * @retval None */ #define __HAL_SD_SDIO_DMA_DISABLE() __SDIO_DMA_DISABLE() /** * @brief Enable the SD device interrupt. * @param __HANDLE__: SD Handle * @param __INTERRUPT__: specifies the SDIO interrupt sources to be enabled. * This parameter can be one or a combination of the following values: * @arg SDIO_IT_CCRCFAIL: Command response received (CRC check failed) interrupt * @arg SDIO_IT_DCRCFAIL: Data block sent/received (CRC check failed) interrupt * @arg SDIO_IT_CTIMEOUT: Command response timeout interrupt * @arg SDIO_IT_DTIMEOUT: Data timeout interrupt * @arg SDIO_IT_TXUNDERR: Transmit FIFO underrun error interrupt * @arg SDIO_IT_RXOVERR: Received FIFO overrun error interrupt * @arg SDIO_IT_CMDREND: Command response received (CRC check passed) interrupt * @arg SDIO_IT_CMDSENT: Command sent (no response required) interrupt * @arg SDIO_IT_DATAEND: Data end (data counter, SDIDCOUNT, is zero) interrupt * @arg SDIO_IT_STBITERR: Start bit not detected on all data signals in wide * bus mode interrupt * @arg SDIO_IT_DBCKEND: Data block sent/received (CRC check passed) interrupt * @arg SDIO_IT_CMDACT: Command transfer in progress interrupt * @arg SDIO_IT_TXACT: Data transmit in progress interrupt * @arg SDIO_IT_RXACT: Data receive in progress interrupt * @arg SDIO_IT_TXFIFOHE: Transmit FIFO Half Empty interrupt * @arg SDIO_IT_RXFIFOHF: Receive FIFO Half Full interrupt * @arg SDIO_IT_TXFIFOF: Transmit FIFO full interrupt * @arg SDIO_IT_RXFIFOF: Receive FIFO full interrupt * @arg SDIO_IT_TXFIFOE: Transmit FIFO empty interrupt * @arg SDIO_IT_RXFIFOE: Receive FIFO empty interrupt * @arg SDIO_IT_TXDAVL: Data available in transmit FIFO interrupt * @arg SDIO_IT_RXDAVL: Data available in receive FIFO interrupt * @arg SDIO_IT_SDIOIT: SD I/O interrupt received interrupt * @arg SDIO_IT_CEATAEND: CE-ATA command completion signal received for CMD61 interrupt * @retval None */ #define __HAL_SD_SDIO_ENABLE_IT(__HANDLE__, __INTERRUPT__) __SDIO_ENABLE_IT((__HANDLE__)->Instance, (__INTERRUPT__)) /** * @brief Disable the SD device interrupt. * @param __HANDLE__: SD Handle * @param __INTERRUPT__: specifies the SDIO interrupt sources to be disabled. * This parameter can be one or a combination of the following values: * @arg SDIO_IT_CCRCFAIL: Command response received (CRC check failed) interrupt * @arg SDIO_IT_DCRCFAIL: Data block sent/received (CRC check failed) interrupt * @arg SDIO_IT_CTIMEOUT: Command response timeout interrupt * @arg SDIO_IT_DTIMEOUT: Data timeout interrupt * @arg SDIO_IT_TXUNDERR: Transmit FIFO underrun error interrupt * @arg SDIO_IT_RXOVERR: Received FIFO overrun error interrupt * @arg SDIO_IT_CMDREND: Command response received (CRC check passed) interrupt * @arg SDIO_IT_CMDSENT: Command sent (no response required) interrupt * @arg SDIO_IT_DATAEND: Data end (data counter, SDIDCOUNT, is zero) interrupt * @arg SDIO_IT_STBITERR: Start bit not detected on all data signals in wide * bus mode interrupt * @arg SDIO_IT_DBCKEND: Data block sent/received (CRC check passed) interrupt * @arg SDIO_IT_CMDACT: Command transfer in progress interrupt * @arg SDIO_IT_TXACT: Data transmit in progress interrupt * @arg SDIO_IT_RXACT: Data receive in progress interrupt * @arg SDIO_IT_TXFIFOHE: Transmit FIFO Half Empty interrupt * @arg SDIO_IT_RXFIFOHF: Receive FIFO Half Full interrupt * @arg SDIO_IT_TXFIFOF: Transmit FIFO full interrupt * @arg SDIO_IT_RXFIFOF: Receive FIFO full interrupt * @arg SDIO_IT_TXFIFOE: Transmit FIFO empty interrupt * @arg SDIO_IT_RXFIFOE: Receive FIFO empty interrupt * @arg SDIO_IT_TXDAVL: Data available in transmit FIFO interrupt * @arg SDIO_IT_RXDAVL: Data available in receive FIFO interrupt * @arg SDIO_IT_SDIOIT: SD I/O interrupt received interrupt * @arg SDIO_IT_CEATAEND: CE-ATA command completion signal received for CMD61 interrupt * @retval None */ #define __HAL_SD_SDIO_DISABLE_IT(__HANDLE__, __INTERRUPT__) __SDIO_DISABLE_IT((__HANDLE__)->Instance, (__INTERRUPT__)) /** * @brief Check whether the specified SD flag is set or not. * @param __HANDLE__: SD Handle * @param __FLAG__: specifies the flag to check. * This parameter can be one of the following values: * @arg SDIO_FLAG_CCRCFAIL: Command response received (CRC check failed) * @arg SDIO_FLAG_DCRCFAIL: Data block sent/received (CRC check failed) * @arg SDIO_FLAG_CTIMEOUT: Command response timeout * @arg SDIO_FLAG_DTIMEOUT: Data timeout * @arg SDIO_FLAG_TXUNDERR: Transmit FIFO underrun error * @arg SDIO_FLAG_RXOVERR: Received FIFO overrun error * @arg SDIO_FLAG_CMDREND: Command response received (CRC check passed) * @arg SDIO_FLAG_CMDSENT: Command sent (no response required) * @arg SDIO_FLAG_DATAEND: Data end (data counter, SDIDCOUNT, is zero) * @arg SDIO_FLAG_STBITERR: Start bit not detected on all data signals in wide bus mode. * @arg SDIO_FLAG_DBCKEND: Data block sent/received (CRC check passed) * @arg SDIO_FLAG_CMDACT: Command transfer in progress * @arg SDIO_FLAG_TXACT: Data transmit in progress * @arg SDIO_FLAG_RXACT: Data receive in progress * @arg SDIO_FLAG_TXFIFOHE: Transmit FIFO Half Empty * @arg SDIO_FLAG_RXFIFOHF: Receive FIFO Half Full * @arg SDIO_FLAG_TXFIFOF: Transmit FIFO full * @arg SDIO_FLAG_RXFIFOF: Receive FIFO full * @arg SDIO_FLAG_TXFIFOE: Transmit FIFO empty * @arg SDIO_FLAG_RXFIFOE: Receive FIFO empty * @arg SDIO_FLAG_TXDAVL: Data available in transmit FIFO * @arg SDIO_FLAG_RXDAVL: Data available in receive FIFO * @arg SDIO_FLAG_SDIOIT: SD I/O interrupt received * @arg SDIO_FLAG_CEATAEND: CE-ATA command completion signal received for CMD61 * @retval The new state of SD FLAG (SET or RESET). */ #define __HAL_SD_SDIO_GET_FLAG(__HANDLE__, __FLAG__) __SDIO_GET_FLAG((__HANDLE__)->Instance, (__FLAG__)) /** * @brief Clear the SD's pending flags. * @param __HANDLE__: SD Handle * @param __FLAG__: specifies the flag to clear. * This parameter can be one or a combination of the following values: * @arg SDIO_FLAG_CCRCFAIL: Command response received (CRC check failed) * @arg SDIO_FLAG_DCRCFAIL: Data block sent/received (CRC check failed) * @arg SDIO_FLAG_CTIMEOUT: Command response timeout * @arg SDIO_FLAG_DTIMEOUT: Data timeout * @arg SDIO_FLAG_TXUNDERR: Transmit FIFO underrun error * @arg SDIO_FLAG_RXOVERR: Received FIFO overrun error * @arg SDIO_FLAG_CMDREND: Command response received (CRC check passed) * @arg SDIO_FLAG_CMDSENT: Command sent (no response required) * @arg SDIO_FLAG_DATAEND: Data end (data counter, SDIDCOUNT, is zero) * @arg SDIO_FLAG_STBITERR: Start bit not detected on all data signals in wide bus mode * @arg SDIO_FLAG_DBCKEND: Data block sent/received (CRC check passed) * @arg SDIO_FLAG_SDIOIT: SD I/O interrupt received * @arg SDIO_FLAG_CEATAEND: CE-ATA command completion signal received for CMD61 * @retval None */ #define __HAL_SD_SDIO_CLEAR_FLAG(__HANDLE__, __FLAG__) __SDIO_CLEAR_FLAG((__HANDLE__)->Instance, (__FLAG__)) /** * @brief Check whether the specified SD interrupt has occurred or not. * @param __HANDLE__: SD Handle * @param __INTERRUPT__: specifies the SDIO interrupt source to check. * This parameter can be one of the following values: * @arg SDIO_IT_CCRCFAIL: Command response received (CRC check failed) interrupt * @arg SDIO_IT_DCRCFAIL: Data block sent/received (CRC check failed) interrupt * @arg SDIO_IT_CTIMEOUT: Command response timeout interrupt * @arg SDIO_IT_DTIMEOUT: Data timeout interrupt * @arg SDIO_IT_TXUNDERR: Transmit FIFO underrun error interrupt * @arg SDIO_IT_RXOVERR: Received FIFO overrun error interrupt * @arg SDIO_IT_CMDREND: Command response received (CRC check passed) interrupt * @arg SDIO_IT_CMDSENT: Command sent (no response required) interrupt * @arg SDIO_IT_DATAEND: Data end (data counter, SDIDCOUNT, is zero) interrupt * @arg SDIO_IT_STBITERR: Start bit not detected on all data signals in wide * bus mode interrupt * @arg SDIO_IT_DBCKEND: Data block sent/received (CRC check passed) interrupt * @arg SDIO_IT_CMDACT: Command transfer in progress interrupt * @arg SDIO_IT_TXACT: Data transmit in progress interrupt * @arg SDIO_IT_RXACT: Data receive in progress interrupt * @arg SDIO_IT_TXFIFOHE: Transmit FIFO Half Empty interrupt * @arg SDIO_IT_RXFIFOHF: Receive FIFO Half Full interrupt * @arg SDIO_IT_TXFIFOF: Transmit FIFO full interrupt * @arg SDIO_IT_RXFIFOF: Receive FIFO full interrupt * @arg SDIO_IT_TXFIFOE: Transmit FIFO empty interrupt * @arg SDIO_IT_RXFIFOE: Receive FIFO empty interrupt * @arg SDIO_IT_TXDAVL: Data available in transmit FIFO interrupt * @arg SDIO_IT_RXDAVL: Data available in receive FIFO interrupt * @arg SDIO_IT_SDIOIT: SD I/O interrupt received interrupt * @arg SDIO_IT_CEATAEND: CE-ATA command completion signal received for CMD61 interrupt * @retval The new state of SD IT (SET or RESET). */ #define __HAL_SD_SDIO_GET_IT (__HANDLE__, __INTERRUPT__) __SDIO_GET_IT ((__HANDLE__)->Instance, __INTERRUPT__) /** * @brief Clear the SD's interrupt pending bits. * @param __HANDLE__ : SD Handle * @param __INTERRUPT__: specifies the interrupt pending bit to clear. * This parameter can be one or a combination of the following values: * @arg SDIO_IT_CCRCFAIL: Command response received (CRC check failed) interrupt * @arg SDIO_IT_DCRCFAIL: Data block sent/received (CRC check failed) interrupt * @arg SDIO_IT_CTIMEOUT: Command response timeout interrupt * @arg SDIO_IT_DTIMEOUT: Data timeout interrupt * @arg SDIO_IT_TXUNDERR: Transmit FIFO underrun error interrupt * @arg SDIO_IT_RXOVERR: Received FIFO overrun error interrupt * @arg SDIO_IT_CMDREND: Command response received (CRC check passed) interrupt * @arg SDIO_IT_CMDSENT: Command sent (no response required) interrupt * @arg SDIO_IT_DATAEND: Data end (data counter, SDIO_DCOUNT, is zero) interrupt * @arg SDIO_IT_STBITERR: Start bit not detected on all data signals in wide * bus mode interrupt * @arg SDIO_IT_SDIOIT: SD I/O interrupt received interrupt * @arg SDIO_IT_CEATAEND: CE-ATA command completion signal received for CMD61 * @retval None */ #define __HAL_SD_SDIO_CLEAR_IT(__HANDLE__, __INTERRUPT__) __SDIO_CLEAR_IT((__HANDLE__)->Instance, (__INTERRUPT__)) /** * @} */ /* Exported functions --------------------------------------------------------*/ /** @defgroup SD_Exported_Functions SD Exported Functions * @{ */ /** @defgroup SD_Exported_Functions_Group1 Initialization and de-initialization functions * @{ */ HAL_SD_ErrorTypedef HAL_SD_Init(SD_HandleTypeDef *hsd, HAL_SD_CardInfoTypedef *SDCardInfo); HAL_StatusTypeDef HAL_SD_DeInit (SD_HandleTypeDef *hsd); void HAL_SD_MspInit(SD_HandleTypeDef *hsd); void HAL_SD_MspDeInit(SD_HandleTypeDef *hsd); /** * @} */ /** @defgroup SD_Exported_Functions_Group2 I/O operation functions * @{ */ /* Blocking mode: Polling */ HAL_SD_ErrorTypedef HAL_SD_ReadBlocks(SD_HandleTypeDef *hsd, uint32_t *pReadBuffer, uint64_t ReadAddr, uint32_t BlockSize, uint32_t NumberOfBlocks); HAL_SD_ErrorTypedef HAL_SD_WriteBlocks(SD_HandleTypeDef *hsd, uint32_t *pWriteBuffer, uint64_t WriteAddr, uint32_t BlockSize, uint32_t NumberOfBlocks); HAL_SD_ErrorTypedef HAL_SD_Erase(SD_HandleTypeDef *hsd, uint64_t startaddr, uint64_t endaddr); /* Non-Blocking mode: Interrupt */ void HAL_SD_IRQHandler(SD_HandleTypeDef *hsd); /* Callback in non blocking modes (DMA) */ void HAL_SD_DMA_RxCpltCallback(DMA_HandleTypeDef *hdma); void HAL_SD_DMA_RxErrorCallback(DMA_HandleTypeDef *hdma); void HAL_SD_DMA_TxCpltCallback(DMA_HandleTypeDef *hdma); void HAL_SD_DMA_TxErrorCallback(DMA_HandleTypeDef *hdma); void HAL_SD_XferCpltCallback(SD_HandleTypeDef *hsd); void HAL_SD_XferErrorCallback(SD_HandleTypeDef *hsd); /* Non-Blocking mode: DMA */ HAL_SD_ErrorTypedef HAL_SD_ReadBlocks_DMA(SD_HandleTypeDef *hsd, uint32_t *pReadBuffer, uint64_t ReadAddr, uint32_t BlockSize, uint32_t NumberOfBlocks); HAL_SD_ErrorTypedef HAL_SD_WriteBlocks_DMA(SD_HandleTypeDef *hsd, uint32_t *pWriteBuffer, uint64_t WriteAddr, uint32_t BlockSize, uint32_t NumberOfBlocks); HAL_SD_ErrorTypedef HAL_SD_CheckWriteOperation(SD_HandleTypeDef *hsd, uint32_t Timeout); HAL_SD_ErrorTypedef HAL_SD_CheckReadOperation(SD_HandleTypeDef *hsd, uint32_t Timeout); /** * @} */ /** @defgroup SD_Exported_Functions_Group3 Peripheral Control functions * @{ */ HAL_SD_ErrorTypedef HAL_SD_Get_CardInfo(SD_HandleTypeDef *hsd, HAL_SD_CardInfoTypedef *pCardInfo); HAL_SD_ErrorTypedef HAL_SD_WideBusOperation_Config(SD_HandleTypeDef *hsd, uint32_t WideMode); HAL_SD_ErrorTypedef HAL_SD_StopTransfer(SD_HandleTypeDef *hsd); HAL_SD_ErrorTypedef HAL_SD_HighSpeed (SD_HandleTypeDef *hsd); /** * @} */ /* Peripheral State functions ************************************************/ /** @defgroup SD_Exported_Functions_Group4 Peripheral State functions * @{ */ HAL_SD_ErrorTypedef HAL_SD_SendSDStatus(SD_HandleTypeDef *hsd, uint32_t *pSDstatus); HAL_SD_ErrorTypedef HAL_SD_GetCardStatus(SD_HandleTypeDef *hsd, HAL_SD_CardStatusTypedef *pCardStatus); HAL_SD_TransferStateTypedef HAL_SD_GetStatus(SD_HandleTypeDef *hsd); /** * @} */ /** * @} */ /* Private types -------------------------------------------------------------*/ /** @defgroup SD_Private_Types SD Private Types * @{ */ /** * @} */ /* Private defines -----------------------------------------------------------*/ /** @defgroup SD_Private_Defines SD Private Defines * @{ */ /** * @} */ /* Private variables ---------------------------------------------------------*/ /** @defgroup SD_Private_Variables SD Private Variables * @{ */ /** * @} */ /* Private constants ---------------------------------------------------------*/ /** @defgroup SD_Private_Constants SD Private Constants * @{ */ /** * @} */ /* Private macros ------------------------------------------------------------*/ /** @defgroup SD_Private_Macros SD Private Macros * @{ */ /** * @} */ /* Private functions prototypes ----------------------------------------------*/ /** @defgroup SD_Private_Functions_Prototypes SD Private Functions Prototypes * @{ */ /** * @} */ /* Private functions ---------------------------------------------------------*/ /** @defgroup SD_Private_Functions SD Private Functions * @{ */ /** * @} */ /** * @} */ /** * @} */ #endif /* STM32F405xx || STM32F415xx || STM32F407xx || STM32F417xx || STM32F427xx || STM32F437xx || STM32F429xx || STM32F439xx || STM32F401xC || STM32F401xE || STM32F411xE || STM32F446xx || STM32F469xx || STM32F479xx */ #ifdef __cplusplus } #endif #endif /* __STM32F4xx_HAL_SD_H */ /************************ (C) COPYRIGHT STMicroelectronics *****END OF FILE****/ ================================================ FILE: Zelig/mbed/TARGET_NUCLEO_F411RE/stm32f4xx_hal_sdram.h ================================================ /** ****************************************************************************** * @file stm32f4xx_hal_sdram.h * @author MCD Application Team * @version V1.4.1 * @date 09-October-2015 * @brief Header file of SDRAM HAL module. ****************************************************************************** * @attention * *

© COPYRIGHT(c) 2015 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. * ****************************************************************************** */ /* Define to prevent recursive inclusion -------------------------------------*/ #ifndef __STM32F4xx_HAL_SDRAM_H #define __STM32F4xx_HAL_SDRAM_H #ifdef __cplusplus extern "C" { #endif #if defined(STM32F427xx) || defined(STM32F437xx) || defined(STM32F429xx) || defined(STM32F439xx) ||\ defined(STM32F446xx) || defined(STM32F469xx) || defined(STM32F479xx) /* Includes ------------------------------------------------------------------*/ #include "stm32f4xx_ll_fmc.h" /** @addtogroup STM32F4xx_HAL_Driver * @{ */ /** @addtogroup SDRAM * @{ */ /* Exported typedef ----------------------------------------------------------*/ /** @defgroup SDRAM_Exported_Types SDRAM Exported Types * @{ */ /** * @brief HAL SDRAM State structure definition */ typedef enum { HAL_SDRAM_STATE_RESET = 0x00, /*!< SDRAM not yet initialized or disabled */ HAL_SDRAM_STATE_READY = 0x01, /*!< SDRAM initialized and ready for use */ HAL_SDRAM_STATE_BUSY = 0x02, /*!< SDRAM internal process is ongoing */ HAL_SDRAM_STATE_ERROR = 0x03, /*!< SDRAM error state */ HAL_SDRAM_STATE_WRITE_PROTECTED = 0x04, /*!< SDRAM device write protected */ HAL_SDRAM_STATE_PRECHARGED = 0x05 /*!< SDRAM device precharged */ }HAL_SDRAM_StateTypeDef; /** * @brief SDRAM handle Structure definition */ typedef struct { FMC_SDRAM_TypeDef *Instance; /*!< Register base address */ FMC_SDRAM_InitTypeDef Init; /*!< SDRAM device configuration parameters */ __IO HAL_SDRAM_StateTypeDef State; /*!< SDRAM access state */ HAL_LockTypeDef Lock; /*!< SDRAM locking object */ DMA_HandleTypeDef *hdma; /*!< Pointer DMA handler */ }SDRAM_HandleTypeDef; /** * @} */ /* Exported constants --------------------------------------------------------*/ /* Exported macro ------------------------------------------------------------*/ /** @defgroup SDRAM_Exported_Macros SDRAM Exported Macros * @{ */ /** @brief Reset SDRAM handle state * @param __HANDLE__: specifies the SDRAM handle. * @retval None */ #define __HAL_SDRAM_RESET_HANDLE_STATE(__HANDLE__) ((__HANDLE__)->State = HAL_SDRAM_STATE_RESET) /** * @} */ /* Exported functions --------------------------------------------------------*/ /** @addtogroup SDRAM_Exported_Functions SDRAM Exported Functions * @{ */ /** @addtogroup SDRAM_Exported_Functions_Group1 * @{ */ /* Initialization/de-initialization functions *********************************/ HAL_StatusTypeDef HAL_SDRAM_Init(SDRAM_HandleTypeDef *hsdram, FMC_SDRAM_TimingTypeDef *Timing); HAL_StatusTypeDef HAL_SDRAM_DeInit(SDRAM_HandleTypeDef *hsdram); void HAL_SDRAM_MspInit(SDRAM_HandleTypeDef *hsdram); void HAL_SDRAM_MspDeInit(SDRAM_HandleTypeDef *hsdram); void HAL_SDRAM_IRQHandler(SDRAM_HandleTypeDef *hsdram); void HAL_SDRAM_RefreshErrorCallback(SDRAM_HandleTypeDef *hsdram); void HAL_SDRAM_DMA_XferCpltCallback(DMA_HandleTypeDef *hdma); void HAL_SDRAM_DMA_XferErrorCallback(DMA_HandleTypeDef *hdma); /** * @} */ /** @addtogroup SDRAM_Exported_Functions_Group2 * @{ */ /* I/O operation functions ****************************************************/ HAL_StatusTypeDef HAL_SDRAM_Read_8b(SDRAM_HandleTypeDef *hsdram, uint32_t *pAddress, uint8_t *pDstBuffer, uint32_t BufferSize); HAL_StatusTypeDef HAL_SDRAM_Write_8b(SDRAM_HandleTypeDef *hsdram, uint32_t *pAddress, uint8_t *pSrcBuffer, uint32_t BufferSize); HAL_StatusTypeDef HAL_SDRAM_Read_16b(SDRAM_HandleTypeDef *hsdram, uint32_t *pAddress, uint16_t *pDstBuffer, uint32_t BufferSize); HAL_StatusTypeDef HAL_SDRAM_Write_16b(SDRAM_HandleTypeDef *hsdram, uint32_t *pAddress, uint16_t *pSrcBuffer, uint32_t BufferSize); HAL_StatusTypeDef HAL_SDRAM_Read_32b(SDRAM_HandleTypeDef *hsdram, uint32_t *pAddress, uint32_t *pDstBuffer, uint32_t BufferSize); HAL_StatusTypeDef HAL_SDRAM_Write_32b(SDRAM_HandleTypeDef *hsdram, uint32_t *pAddress, uint32_t *pSrcBuffer, uint32_t BufferSize); HAL_StatusTypeDef HAL_SDRAM_Read_DMA(SDRAM_HandleTypeDef *hsdram, uint32_t * pAddress, uint32_t *pDstBuffer, uint32_t BufferSize); HAL_StatusTypeDef HAL_SDRAM_Write_DMA(SDRAM_HandleTypeDef *hsdram, uint32_t *pAddress, uint32_t *pSrcBuffer, uint32_t BufferSize); /** * @} */ /** @addtogroup SDRAM_Exported_Functions_Group3 * @{ */ /* SDRAM Control functions *****************************************************/ HAL_StatusTypeDef HAL_SDRAM_WriteProtection_Enable(SDRAM_HandleTypeDef *hsdram); HAL_StatusTypeDef HAL_SDRAM_WriteProtection_Disable(SDRAM_HandleTypeDef *hsdram); HAL_StatusTypeDef HAL_SDRAM_SendCommand(SDRAM_HandleTypeDef *hsdram, FMC_SDRAM_CommandTypeDef *Command, uint32_t Timeout); HAL_StatusTypeDef HAL_SDRAM_ProgramRefreshRate(SDRAM_HandleTypeDef *hsdram, uint32_t RefreshRate); HAL_StatusTypeDef HAL_SDRAM_SetAutoRefreshNumber(SDRAM_HandleTypeDef *hsdram, uint32_t AutoRefreshNumber); uint32_t HAL_SDRAM_GetModeStatus(SDRAM_HandleTypeDef *hsdram); /** * @} */ /** @addtogroup SDRAM_Exported_Functions_Group4 * @{ */ /* SDRAM State functions ********************************************************/ HAL_SDRAM_StateTypeDef HAL_SDRAM_GetState(SDRAM_HandleTypeDef *hsdram); /** * @} */ /** * @} */ /** * @} */ #endif /* STM32F427xx || STM32F437xx || STM32F429xx || STM32F439xx || STM32F446xx || STM32F469xx || STM32F479xx */ /** * @} */ #ifdef __cplusplus } #endif #endif /* __STM32F4xx_HAL_SDRAM_H */ /************************ (C) COPYRIGHT STMicroelectronics *****END OF FILE****/ ================================================ FILE: Zelig/mbed/TARGET_NUCLEO_F411RE/stm32f4xx_hal_smartcard.h ================================================ /** ****************************************************************************** * @file stm32f4xx_hal_smartcard.h * @author MCD Application Team * @version V1.4.1 * @date 09-October-2015 * @brief Header file of SMARTCARD HAL module. ****************************************************************************** * @attention * *

© COPYRIGHT(c) 2015 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. * ****************************************************************************** */ /* Define to prevent recursive inclusion -------------------------------------*/ #ifndef __STM32F4xx_HAL_SMARTCARD_H #define __STM32F4xx_HAL_SMARTCARD_H #ifdef __cplusplus extern "C" { #endif /* Includes ------------------------------------------------------------------*/ #include "stm32f4xx_hal_def.h" /** @addtogroup STM32F4xx_HAL_Driver * @{ */ /** @addtogroup SMARTCARD * @{ */ /* Exported types ------------------------------------------------------------*/ /** @defgroup SMARTCARD_Exported_Types SMARTCARD Exported Types * @{ */ /** * @brief SMARTCARD Init Structure definition */ typedef struct { uint32_t BaudRate; /*!< This member configures the SmartCard communication baud rate. The baud rate is computed using the following formula: - IntegerDivider = ((PCLKx) / (8 * (hirda->Init.BaudRate))) - FractionalDivider = ((IntegerDivider - ((uint32_t) IntegerDivider)) * 8) + 0.5 */ uint32_t WordLength; /*!< Specifies the number of data bits transmitted or received in a frame. This parameter can be a value of @ref SMARTCARD_Word_Length */ uint32_t StopBits; /*!< Specifies the number of stop bits transmitted. This parameter can be a value of @ref SMARTCARD_Stop_Bits */ uint32_t Parity; /*!< Specifies the parity mode. This parameter can be a value of @ref SMARTCARD_Parity @note When parity is enabled, the computed parity is inserted at the MSB position of the transmitted data (9th bit when the word length is set to 9 data bits; 8th bit when the word length is set to 8 data bits).*/ uint32_t Mode; /*!< Specifies whether the Receive or Transmit mode is enabled or disabled. This parameter can be a value of @ref SMARTCARD_Mode */ uint32_t CLKPolarity; /*!< Specifies the steady state of the serial clock. This parameter can be a value of @ref SMARTCARD_Clock_Polarity */ uint32_t CLKPhase; /*!< Specifies the clock transition on which the bit capture is made. This parameter can be a value of @ref SMARTCARD_Clock_Phase */ uint32_t CLKLastBit; /*!< Specifies whether the clock pulse corresponding to the last transmitted data bit (MSB) has to be output on the SCLK pin in synchronous mode. This parameter can be a value of @ref SMARTCARD_Last_Bit */ uint32_t Prescaler; /*!< Specifies the SmartCard Prescaler value used for dividing the system clock to provide the smartcard clock This parameter can be a value of @ref SMARTCARD_Prescaler */ uint32_t GuardTime; /*!< Specifies the SmartCard Guard Time value in terms of number of baud clocks The value given in the register (5 significant bits) is multiplied by 2 to give the division factor of the source clock frequency */ uint32_t NACKState; /*!< Specifies the SmartCard NACK Transmission state. This parameter can be a value of @ref SmartCard_NACK_State */ }SMARTCARD_InitTypeDef; /** * @brief HAL State structures definition */ typedef enum { HAL_SMARTCARD_STATE_RESET = 0x00, /*!< Peripheral is not yet Initialized */ HAL_SMARTCARD_STATE_READY = 0x01, /*!< Peripheral Initialized and ready for use */ HAL_SMARTCARD_STATE_BUSY = 0x02, /*!< an internal process is ongoing */ HAL_SMARTCARD_STATE_BUSY_TX = 0x12, /*!< Data Transmission process is ongoing */ HAL_SMARTCARD_STATE_BUSY_RX = 0x22, /*!< Data Reception process is ongoing */ HAL_SMARTCARD_STATE_BUSY_TX_RX = 0x32, /*!< Data Transmission and Reception process is ongoing */ HAL_SMARTCARD_STATE_TIMEOUT = 0x03, /*!< Timeout state */ HAL_SMARTCARD_STATE_ERROR = 0x04 /*!< Error */ }HAL_SMARTCARD_StateTypeDef; /** * @brief SMARTCARD handle Structure definition */ typedef struct { USART_TypeDef *Instance; /* USART registers base address */ SMARTCARD_InitTypeDef Init; /* SmartCard communication parameters */ uint8_t *pTxBuffPtr; /* Pointer to SmartCard Tx transfer Buffer */ uint16_t TxXferSize; /* SmartCard Tx Transfer size */ uint16_t TxXferCount; /* SmartCard Tx Transfer Counter */ uint8_t *pRxBuffPtr; /* Pointer to SmartCard Rx transfer Buffer */ uint16_t RxXferSize; /* SmartCard Rx Transfer size */ uint16_t RxXferCount; /* SmartCard Rx Transfer Counter */ DMA_HandleTypeDef *hdmatx; /* SmartCard Tx DMA Handle parameters */ DMA_HandleTypeDef *hdmarx; /* SmartCard Rx DMA Handle parameters */ HAL_LockTypeDef Lock; /* Locking object */ __IO HAL_SMARTCARD_StateTypeDef State; /* SmartCard communication state */ __IO uint32_t ErrorCode; /* SmartCard Error code */ }SMARTCARD_HandleTypeDef; /** * @} */ /* Exported constants --------------------------------------------------------*/ /** @defgroup SMARTCARD_Exported_Constants SMARTCARD Exported constants * @{ */ /** @defgroup SMARTCARD_Error_Code SMARTCARD Error Code * @brief SMARTCARD Error Code * @{ */ #define HAL_SMARTCARD_ERROR_NONE ((uint32_t)0x00000000) /*!< No error */ #define HAL_SMARTCARD_ERROR_PE ((uint32_t)0x00000001) /*!< Parity error */ #define HAL_SMARTCARD_ERROR_NE ((uint32_t)0x00000002) /*!< Noise error */ #define HAL_SMARTCARD_ERROR_FE ((uint32_t)0x00000004) /*!< Frame error */ #define HAL_SMARTCARD_ERROR_ORE ((uint32_t)0x00000008) /*!< Overrun error */ #define HAL_SMARTCARD_ERROR_DMA ((uint32_t)0x00000010) /*!< DMA transfer error */ /** * @} */ /** @defgroup SMARTCARD_Word_Length SMARTCARD Word Length * @{ */ #define SMARTCARD_WORDLENGTH_9B ((uint32_t)USART_CR1_M) /** * @} */ /** @defgroup SMARTCARD_Stop_Bits SMARTCARD Number of Stop Bits * @{ */ #define SMARTCARD_STOPBITS_0_5 ((uint32_t)USART_CR2_STOP_0) #define SMARTCARD_STOPBITS_1_5 ((uint32_t)(USART_CR2_STOP_0 | USART_CR2_STOP_1)) /** * @} */ /** @defgroup SMARTCARD_Parity SMARTCARD Parity * @{ */ #define SMARTCARD_PARITY_EVEN ((uint32_t)USART_CR1_PCE) #define SMARTCARD_PARITY_ODD ((uint32_t)(USART_CR1_PCE | USART_CR1_PS)) /** * @} */ /** @defgroup SMARTCARD_Mode SMARTCARD Mode * @{ */ #define SMARTCARD_MODE_RX ((uint32_t)USART_CR1_RE) #define SMARTCARD_MODE_TX ((uint32_t)USART_CR1_TE) #define SMARTCARD_MODE_TX_RX ((uint32_t)(USART_CR1_TE |USART_CR1_RE)) /** * @} */ /** @defgroup SMARTCARD_Clock_Polarity SMARTCARD Clock Polarity * @{ */ #define SMARTCARD_POLARITY_LOW ((uint32_t)0x00000000) #define SMARTCARD_POLARITY_HIGH ((uint32_t)USART_CR2_CPOL) /** * @} */ /** @defgroup SMARTCARD_Clock_Phase SMARTCARD Clock Phase * @{ */ #define SMARTCARD_PHASE_1EDGE ((uint32_t)0x00000000) #define SMARTCARD_PHASE_2EDGE ((uint32_t)USART_CR2_CPHA) /** * @} */ /** @defgroup SMARTCARD_Last_Bit SMARTCARD Last Bit * @{ */ #define SMARTCARD_LASTBIT_DISABLE ((uint32_t)0x00000000) #define SMARTCARD_LASTBIT_ENABLE ((uint32_t)USART_CR2_LBCL) /** * @} */ /** @defgroup SmartCard_NACK_State SMARTCARD NACK State * @{ */ #define SMARTCARD_NACK_ENABLE ((uint32_t)USART_CR3_NACK) #define SMARTCARD_NACK_DISABLE ((uint32_t)0x00000000) /** * @} */ /** @defgroup SmartCard_DMA_Requests SMARTCARD DMA requests * @{ */ #define SMARTCARD_DMAREQ_TX ((uint32_t)USART_CR3_DMAT) #define SMARTCARD_DMAREQ_RX ((uint32_t)USART_CR3_DMAR) /** * @} */ /** @defgroup SMARTCARD_Prescaler SMARTCARD Prescaler * @{ */ #define SMARTCARD_PRESCALER_SYSCLK_DIV2 ((uint32_t)0x00000001) /*!< SYSCLK divided by 2 */ #define SMARTCARD_PRESCALER_SYSCLK_DIV4 ((uint32_t)0x00000002) /*!< SYSCLK divided by 4 */ #define SMARTCARD_PRESCALER_SYSCLK_DIV6 ((uint32_t)0x00000003) /*!< SYSCLK divided by 6 */ #define SMARTCARD_PRESCALER_SYSCLK_DIV8 ((uint32_t)0x00000004) /*!< SYSCLK divided by 8 */ #define SMARTCARD_PRESCALER_SYSCLK_DIV10 ((uint32_t)0x00000005) /*!< SYSCLK divided by 10 */ #define SMARTCARD_PRESCALER_SYSCLK_DIV12 ((uint32_t)0x00000006) /*!< SYSCLK divided by 12 */ #define SMARTCARD_PRESCALER_SYSCLK_DIV14 ((uint32_t)0x00000007) /*!< SYSCLK divided by 14 */ #define SMARTCARD_PRESCALER_SYSCLK_DIV16 ((uint32_t)0x00000008) /*!< SYSCLK divided by 16 */ #define SMARTCARD_PRESCALER_SYSCLK_DIV18 ((uint32_t)0x00000009) /*!< SYSCLK divided by 18 */ #define SMARTCARD_PRESCALER_SYSCLK_DIV20 ((uint32_t)0x0000000A) /*!< SYSCLK divided by 20 */ #define SMARTCARD_PRESCALER_SYSCLK_DIV22 ((uint32_t)0x0000000B) /*!< SYSCLK divided by 22 */ #define SMARTCARD_PRESCALER_SYSCLK_DIV24 ((uint32_t)0x0000000C) /*!< SYSCLK divided by 24 */ #define SMARTCARD_PRESCALER_SYSCLK_DIV26 ((uint32_t)0x0000000D) /*!< SYSCLK divided by 26 */ #define SMARTCARD_PRESCALER_SYSCLK_DIV28 ((uint32_t)0x0000000E) /*!< SYSCLK divided by 28 */ #define SMARTCARD_PRESCALER_SYSCLK_DIV30 ((uint32_t)0x0000000F) /*!< SYSCLK divided by 30 */ #define SMARTCARD_PRESCALER_SYSCLK_DIV32 ((uint32_t)0x00000010) /*!< SYSCLK divided by 32 */ #define SMARTCARD_PRESCALER_SYSCLK_DIV34 ((uint32_t)0x00000011) /*!< SYSCLK divided by 34 */ #define SMARTCARD_PRESCALER_SYSCLK_DIV36 ((uint32_t)0x00000012) /*!< SYSCLK divided by 36 */ #define SMARTCARD_PRESCALER_SYSCLK_DIV38 ((uint32_t)0x00000013) /*!< SYSCLK divided by 38 */ #define SMARTCARD_PRESCALER_SYSCLK_DIV40 ((uint32_t)0x00000014) /*!< SYSCLK divided by 40 */ #define SMARTCARD_PRESCALER_SYSCLK_DIV42 ((uint32_t)0x00000015) /*!< SYSCLK divided by 42 */ #define SMARTCARD_PRESCALER_SYSCLK_DIV44 ((uint32_t)0x00000016) /*!< SYSCLK divided by 44 */ #define SMARTCARD_PRESCALER_SYSCLK_DIV46 ((uint32_t)0x00000017) /*!< SYSCLK divided by 46 */ #define SMARTCARD_PRESCALER_SYSCLK_DIV48 ((uint32_t)0x00000018) /*!< SYSCLK divided by 48 */ #define SMARTCARD_PRESCALER_SYSCLK_DIV50 ((uint32_t)0x00000019) /*!< SYSCLK divided by 50 */ #define SMARTCARD_PRESCALER_SYSCLK_DIV52 ((uint32_t)0x0000001A) /*!< SYSCLK divided by 52 */ #define SMARTCARD_PRESCALER_SYSCLK_DIV54 ((uint32_t)0x0000001B) /*!< SYSCLK divided by 54 */ #define SMARTCARD_PRESCALER_SYSCLK_DIV56 ((uint32_t)0x0000001C) /*!< SYSCLK divided by 56 */ #define SMARTCARD_PRESCALER_SYSCLK_DIV58 ((uint32_t)0x0000001D) /*!< SYSCLK divided by 58 */ #define SMARTCARD_PRESCALER_SYSCLK_DIV60 ((uint32_t)0x0000001E) /*!< SYSCLK divided by 60 */ #define SMARTCARD_PRESCALER_SYSCLK_DIV62 ((uint32_t)0x0000001F) /*!< SYSCLK divided by 62 */ /** * @} */ /** @defgroup SmartCard_Flags SMARTCARD Flags * Elements values convention: 0xXXXX * - 0xXXXX : Flag mask in the SR register * @{ */ #define SMARTCARD_FLAG_TXE ((uint32_t)0x00000080) #define SMARTCARD_FLAG_TC ((uint32_t)0x00000040) #define SMARTCARD_FLAG_RXNE ((uint32_t)0x00000020) #define SMARTCARD_FLAG_IDLE ((uint32_t)0x00000010) #define SMARTCARD_FLAG_ORE ((uint32_t)0x00000008) #define SMARTCARD_FLAG_NE ((uint32_t)0x00000004) #define SMARTCARD_FLAG_FE ((uint32_t)0x00000002) #define SMARTCARD_FLAG_PE ((uint32_t)0x00000001) /** * @} */ /** @defgroup SmartCard_Interrupt_definition SMARTCARD Interrupts Definition * Elements values convention: 0xY000XXXX * - XXXX : Interrupt mask in the XX register * - Y : Interrupt source register (2bits) * - 01: CR1 register * - 10: CR3 register * @{ */ #define SMARTCARD_IT_PE ((uint32_t)(SMARTCARD_CR1_REG_INDEX << 28 | USART_CR1_PEIE)) #define SMARTCARD_IT_TXE ((uint32_t)(SMARTCARD_CR1_REG_INDEX << 28 | USART_CR1_TXEIE)) #define SMARTCARD_IT_TC ((uint32_t)(SMARTCARD_CR1_REG_INDEX << 28 | USART_CR1_TCIE)) #define SMARTCARD_IT_RXNE ((uint32_t)(SMARTCARD_CR1_REG_INDEX << 28 | USART_CR1_RXNEIE)) #define SMARTCARD_IT_IDLE ((uint32_t)(SMARTCARD_CR1_REG_INDEX << 28 | USART_CR1_IDLEIE)) #define SMARTCARD_IT_ERR ((uint32_t)(SMARTCARD_CR3_REG_INDEX << 28 | USART_CR3_EIE)) /** * @} */ /** * @} */ /* Exported macro ------------------------------------------------------------*/ /** @defgroup SMARTCARD_Exported_Macros SMARTCARD Exported Macros * @{ */ /** @brief Reset SMARTCARD handle state * @param __HANDLE__: specifies the SMARTCARD Handle. * @retval None */ #define __HAL_SMARTCARD_RESET_HANDLE_STATE(__HANDLE__) ((__HANDLE__)->State = HAL_SMARTCARD_STATE_RESET) /** @brief Flushs the Smartcard DR register * @param __HANDLE__: specifies the SMARTCARD Handle. */ #define __HAL_SMARTCARD_FLUSH_DRREGISTER(__HANDLE__) ((__HANDLE__)->Instance->DR) /** @brief Checks whether the specified Smartcard flag is set or not. * @param __HANDLE__: specifies the SMARTCARD Handle. * @param __FLAG__: specifies the flag to check. * This parameter can be one of the following values: * @arg SMARTCARD_FLAG_TXE: Transmit data register empty flag * @arg SMARTCARD_FLAG_TC: Transmission Complete flag * @arg SMARTCARD_FLAG_RXNE: Receive data register not empty flag * @arg SMARTCARD_FLAG_IDLE: Idle Line detection flag * @arg SMARTCARD_FLAG_ORE: Overrun Error flag * @arg SMARTCARD_FLAG_NE: Noise Error flag * @arg SMARTCARD_FLAG_FE: Framing Error flag * @arg SMARTCARD_FLAG_PE: Parity Error flag * @retval The new state of __FLAG__ (TRUE or FALSE). */ #define __HAL_SMARTCARD_GET_FLAG(__HANDLE__, __FLAG__) (((__HANDLE__)->Instance->SR & (__FLAG__)) == (__FLAG__)) /** @brief Clears the specified Smartcard pending flags. * @param __HANDLE__: specifies the SMARTCARD Handle. * @param __FLAG__: specifies the flag to check. * This parameter can be any combination of the following values: * @arg SMARTCARD_FLAG_TC: Transmission Complete flag. * @arg SMARTCARD_FLAG_RXNE: Receive data register not empty flag. * * @note PE (Parity error), FE (Framing error), NE (Noise error) and ORE (Overrun * error) flags are cleared by software sequence: a read operation to * USART_SR register followed by a read operation to USART_DR register. * @note RXNE flag can be also cleared by a read to the USART_DR register. * @note TC flag can be also cleared by software sequence: a read operation to * USART_SR register followed by a write operation to USART_DR register. * @note TXE flag is cleared only by a write to the USART_DR register. */ #define __HAL_SMARTCARD_CLEAR_FLAG(__HANDLE__, __FLAG__) ((__HANDLE__)->Instance->SR = ~(__FLAG__)) /** @brief Clear the SMARTCARD PE pending flag. * @param __HANDLE__: specifies the USART Handle. * This parameter can be USARTx where x: 1, 2, 3, 4, 5, 6, 7 or 8 to select the USART or * UART peripheral. * @retval None */ #define __HAL_SMARTCARD_CLEAR_PEFLAG(__HANDLE__) \ do{ \ __IO uint32_t tmpreg; \ tmpreg = (__HANDLE__)->Instance->SR; \ tmpreg = (__HANDLE__)->Instance->DR; \ UNUSED(tmpreg); \ } while(0) /** @brief Clear the SMARTCARD FE pending flag. * @param __HANDLE__: specifies the USART Handle. * This parameter can be USARTx where x: 1, 2, 3, 4, 5, 6, 7 or 8 to select the USART or * UART peripheral. * @retval None */ #define __HAL_SMARTCARD_CLEAR_FEFLAG(__HANDLE__) __HAL_SMARTCARD_CLEAR_PEFLAG(__HANDLE__) /** @brief Clear the SMARTCARD NE pending flag. * @param __HANDLE__: specifies the USART Handle. * This parameter can be USARTx where x: 1, 2, 3, 4, 5, 6, 7 or 8 to select the USART or * UART peripheral. * @retval None */ #define __HAL_SMARTCARD_CLEAR_NEFLAG(__HANDLE__) __HAL_SMARTCARD_CLEAR_PEFLAG(__HANDLE__) /** @brief Clear the SMARTCARD ORE pending flag. * @param __HANDLE__: specifies the USART Handle. * This parameter can be USARTx where x: 1, 2, 3, 4, 5, 6, 7 or 8 to select the USART or * UART peripheral. * @retval None */ #define __HAL_SMARTCARD_CLEAR_OREFLAG(__HANDLE__) __HAL_SMARTCARD_CLEAR_PEFLAG(__HANDLE__) /** @brief Clear the SMARTCARD IDLE pending flag. * @param __HANDLE__: specifies the USART Handle. * This parameter can be USARTx where x: 1, 2, 3, 4, 5, 6, 7 or 8 to select the USART or * UART peripheral. * @retval None */ #define __HAL_SMARTCARD_CLEAR_IDLEFLAG(__HANDLE__) __HAL_SMARTCARD_CLEAR_PEFLAG(__HANDLE__) /** @brief Enables or disables the specified SmartCard interrupts. * @param __HANDLE__: specifies the SMARTCARD Handle. * @param __INTERRUPT__: specifies the SMARTCARD interrupt source to check. * This parameter can be one of the following values: * @arg SMARTCARD_IT_TXE: Transmit Data Register empty interrupt * @arg SMARTCARD_IT_TC: Transmission complete interrupt * @arg SMARTCARD_IT_RXNE: Receive Data register not empty interrupt * @arg SMARTCARD_IT_IDLE: Idle line detection interrupt * @arg SMARTCARD_IT_PE: Parity Error interrupt * @arg SMARTCARD_IT_ERR: Error interrupt(Frame error, noise error, overrun error) */ #define __HAL_SMARTCARD_ENABLE_IT(__HANDLE__, __INTERRUPT__) ((((__INTERRUPT__) >> 28) == 1)? ((__HANDLE__)->Instance->CR1 |= ((__INTERRUPT__) & SMARTCARD_IT_MASK)): \ ((__HANDLE__)->Instance->CR3 |= ((__INTERRUPT__) & SMARTCARD_IT_MASK))) #define __HAL_SMARTCARD_DISABLE_IT(__HANDLE__, __INTERRUPT__) ((((__INTERRUPT__) >> 28) == 1)? ((__HANDLE__)->Instance->CR1 &= ~((__INTERRUPT__) & SMARTCARD_IT_MASK)): \ ((__HANDLE__)->Instance->CR3 &= ~ ((__INTERRUPT__) & SMARTCARD_IT_MASK))) /** @brief Checks whether the specified SmartCard interrupt has occurred or not. * @param __HANDLE__: specifies the SmartCard Handle. * @param __IT__: specifies the SMARTCARD interrupt source to check. * This parameter can be one of the following values: * @arg SMARTCARD_IT_TXE: Transmit Data Register empty interrupt * @arg SMARTCARD_IT_TC: Transmission complete interrupt * @arg SMARTCARD_IT_RXNE: Receive Data register not empty interrupt * @arg SMARTCARD_IT_IDLE: Idle line detection interrupt * @arg SMARTCARD_IT_ERR: Error interrupt * @arg SMARTCARD_IT_PE: Parity Error interrupt * @retval The new state of __IT__ (TRUE or FALSE). */ #define __HAL_SMARTCARD_GET_IT_SOURCE(__HANDLE__, __IT__) (((((__IT__) >> 28) == 1)? (__HANDLE__)->Instance->CR1: (__HANDLE__)->Instance->CR3) & (((uint32_t)(__IT__)) & SMARTCARD_IT_MASK)) /** @brief Macro to enable the SMARTCARD's one bit sample method * @param __HANDLE__: specifies the SMARTCARD Handle. * @retval None */ #define __HAL_SMARTCARD_ONE_BIT_SAMPLE_ENABLE(__HANDLE__) ((__HANDLE__)->Instance->CR3|= USART_CR3_ONEBIT) /** @brief Macro to disable the SMARTCARD's one bit sample method * @param __HANDLE__: specifies the SMARTCARD Handle. * @retval None */ #define __HAL_SMARTCARD_ONE_BIT_SAMPLE_DISABLE(__HANDLE__) ((__HANDLE__)->Instance->CR3 &= (uint16_t)~((uint16_t)USART_CR3_ONEBIT)) /** @brief Enable the USART associated to the SMARTCARD Handle * @param __HANDLE__: specifies the SMARTCARD Handle. * SMARTCARD Handle selects the USARTx peripheral (USART availability and x value depending on device). * @retval None */ #define __HAL_SMARTCARD_ENABLE(__HANDLE__) ((__HANDLE__)->Instance->CR1 |= USART_CR1_UE) /** @brief Disable the USART associated to the SMARTCARD Handle * @param __HANDLE__: specifies the SMARTCARD Handle. * SMARTCARD Handle selects the USARTx peripheral (USART availability and x value depending on device). * @retval None */ #define __HAL_SMARTCARD_DISABLE(__HANDLE__) ((__HANDLE__)->Instance->CR1 &= ~USART_CR1_UE) /** @brief Macros to enable or disable the SmartCard DMA request. * @param __HANDLE__: specifies the SmartCard Handle. * @param __REQUEST__: specifies the SmartCard DMA request. * This parameter can be one of the following values: * @arg SMARTCARD_DMAREQ_TX: SmartCard DMA transmit request * @arg SMARTCARD_DMAREQ_RX: SmartCard DMA receive request */ #define __HAL_SMARTCARD_DMA_REQUEST_ENABLE(__HANDLE__, __REQUEST__) ((__HANDLE__)->Instance->CR3 |= (__REQUEST__)) #define __HAL_SMARTCARD_DMA_REQUEST_DISABLE(__HANDLE__, __REQUEST__) ((__HANDLE__)->Instance->CR3 &= ~(__REQUEST__)) /** * @} */ /* Exported functions --------------------------------------------------------*/ /** @addtogroup SMARTCARD_Exported_Functions * @{ */ /** @addtogroup SMARTCARD_Exported_Functions_Group1 * @{ */ /* Initialization/de-initialization functions **********************************/ HAL_StatusTypeDef HAL_SMARTCARD_Init(SMARTCARD_HandleTypeDef *hsc); HAL_StatusTypeDef HAL_SMARTCARD_ReInit(SMARTCARD_HandleTypeDef *hsc); HAL_StatusTypeDef HAL_SMARTCARD_DeInit(SMARTCARD_HandleTypeDef *hsc); void HAL_SMARTCARD_MspInit(SMARTCARD_HandleTypeDef *hsc); void HAL_SMARTCARD_MspDeInit(SMARTCARD_HandleTypeDef *hsc); /** * @} */ /** @addtogroup SMARTCARD_Exported_Functions_Group2 * @{ */ /* IO operation functions *******************************************************/ HAL_StatusTypeDef HAL_SMARTCARD_Transmit(SMARTCARD_HandleTypeDef *hsc, uint8_t *pData, uint16_t Size, uint32_t Timeout); HAL_StatusTypeDef HAL_SMARTCARD_Receive(SMARTCARD_HandleTypeDef *hsc, uint8_t *pData, uint16_t Size, uint32_t Timeout); HAL_StatusTypeDef HAL_SMARTCARD_Transmit_IT(SMARTCARD_HandleTypeDef *hsc, uint8_t *pData, uint16_t Size); HAL_StatusTypeDef HAL_SMARTCARD_Receive_IT(SMARTCARD_HandleTypeDef *hsc, uint8_t *pData, uint16_t Size); HAL_StatusTypeDef HAL_SMARTCARD_Transmit_DMA(SMARTCARD_HandleTypeDef *hsc, uint8_t *pData, uint16_t Size); HAL_StatusTypeDef HAL_SMARTCARD_Receive_DMA(SMARTCARD_HandleTypeDef *hsc, uint8_t *pData, uint16_t Size); void HAL_SMARTCARD_IRQHandler(SMARTCARD_HandleTypeDef *hsc); void HAL_SMARTCARD_TxCpltCallback(SMARTCARD_HandleTypeDef *hsc); void HAL_SMARTCARD_RxCpltCallback(SMARTCARD_HandleTypeDef *hsc); void HAL_SMARTCARD_ErrorCallback(SMARTCARD_HandleTypeDef *hsc); /** * @} */ /** @addtogroup SMARTCARD_Exported_Functions_Group3 * @{ */ /* Peripheral State functions **************************************************/ HAL_SMARTCARD_StateTypeDef HAL_SMARTCARD_GetState(SMARTCARD_HandleTypeDef *hsc); uint32_t HAL_SMARTCARD_GetError(SMARTCARD_HandleTypeDef *hsc); /** * @} */ /** * @} */ /* Private types -------------------------------------------------------------*/ /* Private variables ---------------------------------------------------------*/ /* Private constants ---------------------------------------------------------*/ /** @defgroup SMARTCARD_Private_Constants SMARTCARD Private Constants * @{ */ /** @brief SMARTCARD interruptions flag mask * */ #define SMARTCARD_IT_MASK ((uint32_t) USART_CR1_PEIE | USART_CR1_TXEIE | USART_CR1_TCIE | USART_CR1_RXNEIE | \ USART_CR1_IDLEIE | USART_CR3_EIE ) #define SMARTCARD_DIV(_PCLK_, _BAUD_) (((_PCLK_)*25)/(4*(_BAUD_))) #define SMARTCARD_DIVMANT(_PCLK_, _BAUD_) (SMARTCARD_DIV((_PCLK_), (_BAUD_))/100) #define SMARTCARD_DIVFRAQ(_PCLK_, _BAUD_) (((SMARTCARD_DIV((_PCLK_), (_BAUD_)) - (SMARTCARD_DIVMANT((_PCLK_), (_BAUD_)) * 100)) * 16 + 50) / 100) #define SMARTCARD_BRR(_PCLK_, _BAUD_) ((SMARTCARD_DIVMANT((_PCLK_), (_BAUD_)) << 4)|(SMARTCARD_DIVFRAQ((_PCLK_), (_BAUD_)) & 0x0F)) #define SMARTCARD_CR1_REG_INDEX 1 #define SMARTCARD_CR3_REG_INDEX 3 /** * @} */ /* Private macros --------------------------------------------------------*/ /** @defgroup SMARTCARD_Private_Macros SMARTCARD Private Macros * @{ */ #define IS_SMARTCARD_WORD_LENGTH(LENGTH) ((LENGTH) == SMARTCARD_WORDLENGTH_9B) #define IS_SMARTCARD_STOPBITS(STOPBITS) (((STOPBITS) == SMARTCARD_STOPBITS_0_5) || \ ((STOPBITS) == SMARTCARD_STOPBITS_1_5)) #define IS_SMARTCARD_PARITY(PARITY) (((PARITY) == SMARTCARD_PARITY_EVEN) || \ ((PARITY) == SMARTCARD_PARITY_ODD)) #define IS_SMARTCARD_MODE(MODE) ((((MODE) & (uint32_t)0x0000FFF3) == 0x00) && ((MODE) != (uint32_t)0x000000)) #define IS_SMARTCARD_POLARITY(CPOL) (((CPOL) == SMARTCARD_POLARITY_LOW) || ((CPOL) == SMARTCARD_POLARITY_HIGH)) #define IS_SMARTCARD_PHASE(CPHA) (((CPHA) == SMARTCARD_PHASE_1EDGE) || ((CPHA) == SMARTCARD_PHASE_2EDGE)) #define IS_SMARTCARD_LASTBIT(LASTBIT) (((LASTBIT) == SMARTCARD_LASTBIT_DISABLE) || \ ((LASTBIT) == SMARTCARD_LASTBIT_ENABLE)) #define IS_SMARTCARD_NACK_STATE(NACK) (((NACK) == SMARTCARD_NACK_ENABLE) || \ ((NACK) == SMARTCARD_NACK_DISABLE)) #define IS_SMARTCARD_BAUDRATE(BAUDRATE) ((BAUDRATE) < 10500001) /** * @} */ /* Private functions ---------------------------------------------------------*/ /** @defgroup SMARTCARD_Private_Functions SMARTCARD Private Functions * @{ */ /** * @} */ /** * @} */ /** * @} */ #ifdef __cplusplus } #endif #endif /* __STM32F4xx_HAL_SMARTCARD_H */ /************************ (C) COPYRIGHT STMicroelectronics *****END OF FILE****/ ================================================ FILE: Zelig/mbed/TARGET_NUCLEO_F411RE/stm32f4xx_hal_spdifrx.h ================================================ /** ****************************************************************************** * @file stm32f4xx_hal_spdifrx.h * @author MCD Application Team * @version V1.4.1 * @date 09-October-2015 * @brief Header file of SPDIFRX HAL module. ****************************************************************************** * @attention * *

© COPYRIGHT(c) 2015 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. * ****************************************************************************** */ /* Define to prevent recursive inclusion -------------------------------------*/ #ifndef __STM32F4xx_HAL_SPDIFRX_H #define __STM32F4xx_HAL_SPDIFRX_H #ifdef __cplusplus extern "C" { #endif #if defined(STM32F446xx) /* Includes ------------------------------------------------------------------*/ #include "stm32f4xx_hal_def.h" /** @addtogroup STM32F4xx_HAL_Driver * @{ */ /** @addtogroup SPDIFRX * @{ */ /* Exported types ------------------------------------------------------------*/ /** @defgroup SPDIFRX_Exported_Types SPDIFRX Exported Types * @{ */ /** * @brief SPDIFRX Init structure definition */ typedef struct { uint32_t InputSelection; /*!< Specifies the SPDIF input selection. This parameter can be a value of @ref SPDIFRX_Input_Selection */ uint32_t Retries; /*!< Specifies the Maximum allowed re-tries during synchronization phase. This parameter can be a value of @ref SPDIFRX_Max_Retries */ uint32_t WaitForActivity; /*!< Specifies the wait for activity on SPDIF selected input. This parameter can be a value of @ref SPDIFRX_Wait_For_Activity. */ uint32_t ChannelSelection; /*!< Specifies whether the control flow will take the channel status from channel A or B. This parameter can be a value of @ref SPDIFRX_Channel_Selection */ uint32_t DataFormat; /*!< Specifies the Data samples format (LSB, MSB, ...). This parameter can be a value of @ref SPDIFRX_Data_Format */ uint32_t StereoMode; /*!< Specifies whether the peripheral is in stereo or mono mode. This parameter can be a value of @ref SPDIFRX_Stereo_Mode */ uint32_t PreambleTypeMask; /*!< Specifies whether The preamble type bits are copied or not into the received frame. This parameter can be a value of @ref SPDIFRX_PT_Mask */ uint32_t ChannelStatusMask; /*!< Specifies whether the channel status and user bits are copied or not into the received frame. This parameter can be a value of @ref SPDIFRX_ChannelStatus_Mask */ uint32_t ValidityBitMask; /*!< Specifies whether the validity bit is copied or not into the received frame. This parameter can be a value of @ref SPDIFRX_V_Mask */ uint32_t ParityErrorMask; /*!< Specifies whether the parity error bit is copied or not into the received frame. This parameter can be a value of @ref SPDIFRX_PE_Mask */ }SPDIFRX_InitTypeDef; /** * @brief SPDIFRX SetDataFormat structure definition */ typedef struct { uint32_t DataFormat; /*!< Specifies the Data samples format (LSB, MSB, ...). This parameter can be a value of @ref SPDIFRX_Data_Format */ uint32_t StereoMode; /*!< Specifies whether the peripheral is in stereo or mono mode. This parameter can be a value of @ref SPDIFRX_Stereo_Mode */ uint32_t PreambleTypeMask; /*!< Specifies whether The preamble type bits are copied or not into the received frame. This parameter can be a value of @ref SPDIFRX_PT_Mask */ uint32_t ChannelStatusMask; /*!< Specifies whether the channel status and user bits are copied or not into the received frame. This parameter can be a value of @ref SPDIFRX_ChannelStatus_Mask */ uint32_t ValidityBitMask; /*!< Specifies whether the validity bit is copied or not into the received frame. This parameter can be a value of @ref SPDIFRX_V_Mask */ uint32_t ParityErrorMask; /*!< Specifies whether the parity error bit is copied or not into the received frame. This parameter can be a value of @ref SPDIFRX_PE_Mask */ }SPDIFRX_SetDataFormatTypeDef; /** * @brief HAL State structures definition */ typedef enum { HAL_SPDIFRX_STATE_RESET = 0x00, /*!< SPDIFRX not yet initialized or disabled */ HAL_SPDIFRX_STATE_READY = 0x01, /*!< SPDIFRX initialized and ready for use */ HAL_SPDIFRX_STATE_BUSY = 0x02, /*!< SPDIFRX internal process is ongoing */ HAL_SPDIFRX_STATE_BUSY_RX = 0x03, /*!< SPDIFRX internal Data Flow RX process is ongoing */ HAL_SPDIFRX_STATE_BUSY_CX = 0x04, /*!< SPDIFRX internal Control Flow RX process is ongoing */ HAL_SPDIFRX_STATE_ERROR = 0x07 /*!< SPDIFRX error state */ }HAL_SPDIFRX_StateTypeDef; /** * @brief SPDIFRX handle Structure definition */ typedef struct { SPDIFRX_TypeDef *Instance; /* SPDIFRX registers base address */ SPDIFRX_InitTypeDef Init; /* SPDIFRX communication parameters */ uint32_t *pRxBuffPtr; /* Pointer to SPDIFRX Rx transfer buffer */ uint32_t *pCsBuffPtr; /* Pointer to SPDIFRX Cx transfer buffer */ __IO uint16_t RxXferSize; /* SPDIFRX Rx transfer size */ __IO uint16_t RxXferCount; /* SPDIFRX Rx transfer counter (This field is initialized at the same value as transfer size at the beginning of the transfer and decremented when a sample is received. NbSamplesReceived = RxBufferSize-RxBufferCount) */ __IO uint16_t CsXferSize; /* SPDIFRX Rx transfer size */ __IO uint16_t CsXferCount; /* SPDIFRX Rx transfer counter (This field is initialized at the same value as transfer size at the beginning of the transfer and decremented when a sample is received. NbSamplesReceived = RxBufferSize-RxBufferCount) */ DMA_HandleTypeDef *hdmaCsRx; /* SPDIFRX EC60958_channel_status and user_information DMA handle parameters */ DMA_HandleTypeDef *hdmaDrRx; /* SPDIFRX Rx DMA handle parameters */ __IO HAL_LockTypeDef Lock; /* SPDIFRX locking object */ __IO HAL_SPDIFRX_StateTypeDef State; /* SPDIFRX communication state */ __IO uint32_t ErrorCode; /* SPDIFRX Error code */ }SPDIFRX_HandleTypeDef; /** * @} */ /* Exported constants --------------------------------------------------------*/ /** @defgroup SPDIFRX_Exported_Constants SPDIFRX Exported Constants * @{ */ /** @defgroup SPDIFRX_ErrorCode SPDIFRX Error Code * @{ */ #define HAL_SPDIFRX_ERROR_NONE ((uint32_t)0x00000000) /*!< No error */ #define HAL_SPDIFRX_ERROR_TIMEOUT ((uint32_t)0x00000001) /*!< Timeout error */ #define HAL_SPDIFRX_ERROR_OVR ((uint32_t)0x00000002) /*!< OVR error */ #define HAL_SPDIFRX_ERROR_PE ((uint32_t)0x00000004) /*!< Parity error */ #define HAL_SPDIFRX_ERROR_DMA ((uint32_t)0x00000008) /*!< DMA transfer error */ #define HAL_SPDIFRX_ERROR_UNKNOWN ((uint32_t)0x00000010) /*!< Unknown Error error */ /** * @} */ /** @defgroup SPDIFRX_Input_Selection SPDIFRX Input Selection * @{ */ #define SPDIFRX_INPUT_IN0 ((uint32_t)0x00000000) #define SPDIFRX_INPUT_IN1 ((uint32_t)0x00010000) #define SPDIFRX_INPUT_IN2 ((uint32_t)0x00020000) #define SPDIFRX_INPUT_IN3 ((uint32_t)0x00030000) /** * @} */ /** @defgroup SPDIFRX_Max_Retries SPDIFRX Maximum Retries * @{ */ #define SPDIFRX_MAXRETRIES_NONE ((uint32_t)0x00000000) #define SPDIFRX_MAXRETRIES_3 ((uint32_t)0x00001000) #define SPDIFRX_MAXRETRIES_15 ((uint32_t)0x00002000) #define SPDIFRX_MAXRETRIES_63 ((uint32_t)0x00003000) /** * @} */ /** @defgroup SPDIFRX_Wait_For_Activity SPDIFRX Wait For Activity * @{ */ #define SPDIFRX_WAITFORACTIVITY_OFF ((uint32_t)0x00000000) #define SPDIFRX_WAITFORACTIVITY_ON ((uint32_t)SPDIFRX_CR_WFA) /** * @} */ /** @defgroup SPDIFRX_PT_Mask SPDIFRX Preamble Type Mask * @{ */ #define SPDIFRX_PREAMBLETYPEMASK_OFF ((uint32_t)0x00000000) #define SPDIFRX_PREAMBLETYPEMASK_ON ((uint32_t)SPDIFRX_CR_PTMSK) /** * @} */ /** @defgroup SPDIFRX_ChannelStatus_Mask SPDIFRX Channel Status Mask * @{ */ #define SPDIFRX_CHANNELSTATUS_OFF ((uint32_t)0x00000000) /* The channel status and user bits are copied into the SPDIF_DR */ #define SPDIFRX_CHANNELSTATUS_ON ((uint32_t)SPDIFRX_CR_CUMSK) /* The channel status and user bits are not copied into the SPDIF_DR, zeros are written instead*/ /** * @} */ /** @defgroup SPDIFRX_V_Mask SPDIFRX Validity Mask * @{ */ #define SPDIFRX_VALIDITYMASK_OFF ((uint32_t)0x00000000) #define SPDIFRX_VALIDITYMASK_ON ((uint32_t)SPDIFRX_CR_VMSK) /** * @} */ /** @defgroup SPDIFRX_PE_Mask SPDIFRX Parity Error Mask * @{ */ #define SPDIFRX_PARITYERRORMASK_OFF ((uint32_t)0x00000000) #define SPDIFRX_PARITYERRORMASK_ON ((uint32_t)SPDIFRX_CR_PMSK) /** * @} */ /** @defgroup SPDIFRX_Channel_Selection SPDIFRX Channel Selection * @{ */ #define SPDIFRX_CHANNEL_A ((uint32_t)0x00000000) #define SPDIFRX_CHANNEL_B ((uint32_t)SPDIFRX_CR_CHSEL) /** * @} */ /** @defgroup SPDIFRX_Data_Format SPDIFRX Data Format * @{ */ #define SPDIFRX_DATAFORMAT_LSB ((uint32_t)0x00000000) #define SPDIFRX_DATAFORMAT_MSB ((uint32_t)0x00000010) #define SPDIFRX_DATAFORMAT_32BITS ((uint32_t)0x00000020) /** * @} */ /** @defgroup SPDIFRX_Stereo_Mode SPDIFRX Stereo Mode * @{ */ #define SPDIFRX_STEREOMODE_DISABLE ((uint32_t)0x00000000) #define SPDIFRX_STEREOMODE_ENABLE ((uint32_t)SPDIFRX_CR_RXSTEO) /** * @} */ /** @defgroup SPDIFRX_State SPDIFRX State * @{ */ #define SPDIFRX_STATE_IDLE ((uint32_t)0xFFFFFFFC) #define SPDIFRX_STATE_SYNC ((uint32_t)0x00000001) #define SPDIFRX_STATE_RCV ((uint32_t)SPDIFRX_CR_SPDIFEN) /** * @} */ /** @defgroup SPDIFRX_Interrupts_Definition SPDIFRX Interrupts Definition * @{ */ #define SPDIFRX_IT_RXNE ((uint32_t)SPDIFRX_IMR_RXNEIE) #define SPDIFRX_IT_CSRNE ((uint32_t)SPDIFRX_IMR_CSRNEIE) #define SPDIFRX_IT_PERRIE ((uint32_t)SPDIFRX_IMR_PERRIE) #define SPDIFRX_IT_OVRIE ((uint32_t)SPDIFRX_IMR_OVRIE) #define SPDIFRX_IT_SBLKIE ((uint32_t)SPDIFRX_IMR_SBLKIE) #define SPDIFRX_IT_SYNCDIE ((uint32_t)SPDIFRX_IMR_SYNCDIE) #define SPDIFRX_IT_IFEIE ((uint32_t)SPDIFRX_IMR_IFEIE ) /** * @} */ /** @defgroup SPDIFRX_Flags_Definition SPDIFRX Flags Definition * @{ */ #define SPDIFRX_FLAG_RXNE ((uint32_t)SPDIFRX_SR_RXNE) #define SPDIFRX_FLAG_CSRNE ((uint32_t)SPDIFRX_SR_CSRNE) #define SPDIFRX_FLAG_PERR ((uint32_t)SPDIFRX_SR_PERR) #define SPDIFRX_FLAG_OVR ((uint32_t)SPDIFRX_SR_OVR) #define SPDIFRX_FLAG_SBD ((uint32_t)SPDIFRX_SR_SBD) #define SPDIFRX_FLAG_SYNCD ((uint32_t)SPDIFRX_SR_SYNCD) #define SPDIFRX_FLAG_FERR ((uint32_t)SPDIFRX_SR_FERR) #define SPDIFRX_FLAG_SERR ((uint32_t)SPDIFRX_SR_SERR) #define SPDIFRX_FLAG_TERR ((uint32_t)SPDIFRX_SR_TERR) /** * @} */ /** * @} */ /* Exported macros -----------------------------------------------------------*/ /** @defgroup SPDIFRX_Exported_macros SPDIFRX Exported Macros * @{ */ /** @brief Reset SPDIFRX handle state * @param __HANDLE__: SPDIFRX handle. * @retval None */ #define __HAL_SPDIFRX_RESET_HANDLE_STATE(__HANDLE__) ((__HANDLE__)->State = (uint16_t)SPDIFRX_CR_SPDIFEN) /** @brief Disable the specified SPDIFRX peripheral (IDLE State). * @param __HANDLE__: specifies the SPDIFRX Handle. * @retval None */ #define __HAL_SPDIFRX_IDLE(__HANDLE__) ((__HANDLE__)->Instance->CR &= SPDIFRX_STATE_IDLE) /** @brief Enable the specified SPDIFRX peripheral (SYNC State). * @param __HANDLE__: specifies the SPDIFRX Handle. * @retval None */ #define __HAL_SPDIFRX_SYNC(__HANDLE__) ((__HANDLE__)->Instance->CR |= SPDIFRX_STATE_SYNC) /** @brief Enable the specified SPDIFRX peripheral (RCV State). * @param __HANDLE__: specifies the SPDIFRX Handle. * @retval None */ #define __HAL_SPDIFRX_RCV(__HANDLE__) ((__HANDLE__)->Instance->CR |= SPDIFRX_STATE_RCV) /** @brief Enable or disable the specified SPDIFRX interrupts. * @param __HANDLE__: specifies the SPDIFRX Handle. * @param __INTERRUPT__: specifies the interrupt source to enable or disable. * This parameter can be one of the following values: * @arg SPDIFRX_IT_RXNE * @arg SPDIFRX_IT_CSRNE * @arg SPDIFRX_IT_PERRIE * @arg SPDIFRX_IT_OVRIE * @arg SPDIFRX_IT_SBLKIE * @arg SPDIFRX_IT_SYNCDIE * @arg SPDIFRX_IT_IFEIE * @retval None */ #define __HAL_SPDIFRX_ENABLE_IT(__HANDLE__, __INTERRUPT__) ((__HANDLE__)->Instance->IMR |= (__INTERRUPT__)) #define __HAL_SPDIFRX_DISABLE_IT(__HANDLE__, __INTERRUPT__) ((__HANDLE__)->Instance->IMR &= (uint16_t)(~(__INTERRUPT__))) /** @brief Checks if the specified SPDIFRX interrupt source is enabled or disabled. * @param __HANDLE__: specifies the SPDIFRX Handle. * @param __INTERRUPT__: specifies the SPDIFRX interrupt source to check. * This parameter can be one of the following values: * @arg SPDIFRX_IT_RXNE * @arg SPDIFRX_IT_CSRNE * @arg SPDIFRX_IT_PERRIE * @arg SPDIFRX_IT_OVRIE * @arg SPDIFRX_IT_SBLKIE * @arg SPDIFRX_IT_SYNCDIE * @arg SPDIFRX_IT_IFEIE * @retval The new state of __IT__ (TRUE or FALSE). */ #define __HAL_SPDIFRX_GET_IT_SOURCE(__HANDLE__, __INTERRUPT__) ((((__HANDLE__)->Instance->IMR & (__INTERRUPT__)) == (__INTERRUPT__)) ? SET : RESET) /** @brief Checks whether the specified SPDIFRX flag is set or not. * @param __HANDLE__: specifies the SPDIFRX Handle. * @param __FLAG__: specifies the flag to check. * This parameter can be one of the following values: * @arg SPDIFRX_FLAG_RXNE * @arg SPDIFRX_FLAG_CSRNE * @arg SPDIFRX_FLAG_PERR * @arg SPDIFRX_FLAG_OVR * @arg SPDIFRX_FLAG_SBD * @arg SPDIFRX_FLAG_SYNCD * @arg SPDIFRX_FLAG_FERR * @arg SPDIFRX_FLAG_SERR * @arg SPDIFRX_FLAG_TERR * @retval The new state of __FLAG__ (TRUE or FALSE). */ #define __HAL_SPDIFRX_GET_FLAG(__HANDLE__, __FLAG__) ((((__HANDLE__)->Instance->SR) & (__FLAG__)) == (__FLAG__)) /** @brief Clears the specified SPDIFRX SR flag, in setting the proper IFCR register bit. * @param __HANDLE__: specifies the USART Handle. * @param __IT_CLEAR__: specifies the interrupt clear register flag that needs to be set * to clear the corresponding interrupt * This parameter can be one of the following values: * @arg SPDIFRX_FLAG_PERR * @arg SPDIFRX_FLAG_OVR * @arg SPDIFRX_SR_SBD * @arg SPDIFRX_SR_SYNCD * @retval None */ #define __HAL_SPDIFRX_CLEAR_IT(__HANDLE__, __IT_CLEAR__) ((__HANDLE__)->Instance->IFCR = (uint32_t)(__IT_CLEAR__)) /** * @} */ /* Exported functions --------------------------------------------------------*/ /** @addtogroup SPDIFRX_Exported_Functions * @{ */ /** @addtogroup SPDIFRX_Exported_Functions_Group1 * @{ */ /* Initialization/de-initialization functions **********************************/ HAL_StatusTypeDef HAL_SPDIFRX_Init(SPDIFRX_HandleTypeDef *hspdif); HAL_StatusTypeDef HAL_SPDIFRX_DeInit (SPDIFRX_HandleTypeDef *hspdif); void HAL_SPDIFRX_MspInit(SPDIFRX_HandleTypeDef *hspdif); void HAL_SPDIFRX_MspDeInit(SPDIFRX_HandleTypeDef *hspdif); HAL_StatusTypeDef HAL_SPDIFRX_SetDataFormat(SPDIFRX_HandleTypeDef *hspdif, SPDIFRX_SetDataFormatTypeDef sDataFormat); /** * @} */ /** @addtogroup SPDIFRX_Exported_Functions_Group2 * @{ */ /* I/O operation functions ***************************************************/ /* Blocking mode: Polling */ HAL_StatusTypeDef HAL_SPDIFRX_ReceiveDataFlow(SPDIFRX_HandleTypeDef *hspdif, uint32_t *pData, uint16_t Size, uint32_t Timeout); HAL_StatusTypeDef HAL_SPDIFRX_ReceiveControlFlow(SPDIFRX_HandleTypeDef *hspdif, uint32_t *pData, uint16_t Size, uint32_t Timeout); /* Non-Blocking mode: Interrupt */ HAL_StatusTypeDef HAL_SPDIFRX_ReceiveControlFlow_IT(SPDIFRX_HandleTypeDef *hspdif, uint32_t *pData, uint16_t Size); HAL_StatusTypeDef HAL_SPDIFRX_ReceiveDataFlow_IT(SPDIFRX_HandleTypeDef *hspdif, uint32_t *pData, uint16_t Size); void HAL_SPDIFRX_IRQHandler(SPDIFRX_HandleTypeDef *hspdif); /* Non-Blocking mode: DMA */ HAL_StatusTypeDef HAL_SPDIFRX_ReceiveControlFlow_DMA(SPDIFRX_HandleTypeDef *hspdif, uint32_t *pData, uint16_t Size); HAL_StatusTypeDef HAL_SPDIFRX_ReceiveDataFlow_DMA(SPDIFRX_HandleTypeDef *hspdif, uint32_t *pData, uint16_t Size); HAL_StatusTypeDef HAL_SPDIFRX_DMAStop(SPDIFRX_HandleTypeDef *hspdif); /* Callbacks used in non blocking modes (Interrupt and DMA) *******************/ void HAL_SPDIFRX_RxHalfCpltCallback(SPDIFRX_HandleTypeDef *hspdif); void HAL_SPDIFRX_RxCpltCallback(SPDIFRX_HandleTypeDef *hspdif); void HAL_SPDIFRX_ErrorCallback(SPDIFRX_HandleTypeDef *hspdif); void HAL_SPDIFRX_CxHalfCpltCallback(SPDIFRX_HandleTypeDef *hspdif); void HAL_SPDIFRX_CxCpltCallback(SPDIFRX_HandleTypeDef *hspdif); /** * @} */ /** @addtogroup SPDIFRX_Exported_Functions_Group3 * @{ */ /* Peripheral Control and State functions ************************************/ HAL_SPDIFRX_StateTypeDef HAL_SPDIFRX_GetState(SPDIFRX_HandleTypeDef *hspdif); uint32_t HAL_SPDIFRX_GetError(SPDIFRX_HandleTypeDef *hspdif); /** * @} */ /** * @} */ /* Private types -------------------------------------------------------------*/ /* Private variables ---------------------------------------------------------*/ /* Private constants ---------------------------------------------------------*/ /* Private macros ------------------------------------------------------------*/ /** @defgroup SPDIFRX_Private_Macros SPDIFRX Private Macros * @{ */ #define IS_SPDIFRX_INPUT_SELECT(INPUT) (((INPUT) == SPDIFRX_INPUT_IN1) || \ ((INPUT) == SPDIFRX_INPUT_IN2) || \ ((INPUT) == SPDIFRX_INPUT_IN3) || \ ((INPUT) == SPDIFRX_INPUT_IN0)) #define IS_SPDIFRX_MAX_RETRIES(RET) (((RET) == SPDIFRX_MAXRETRIES_NONE) || \ ((RET) == SPDIFRX_MAXRETRIES_3) || \ ((RET) == SPDIFRX_MAXRETRIES_15) || \ ((RET) == SPDIFRX_MAXRETRIES_63)) #define IS_SPDIFRX_WAIT_FOR_ACTIVITY(VAL) (((VAL) == SPDIFRX_WAITFORACTIVITY_ON) || \ ((VAL) == SPDIFRX_WAITFORACTIVITY_OFF)) #define IS_PREAMBLE_TYPE_MASK(VAL) (((VAL) == SPDIFRX_PREAMBLETYPEMASK_ON) || \ ((VAL) == SPDIFRX_PREAMBLETYPEMASK_OFF)) #define IS_VALIDITY_MASK(VAL) (((VAL) == SPDIFRX_VALIDITYMASK_OFF) || \ ((VAL) == SPDIFRX_VALIDITYMASK_ON)) #define IS_PARITY_ERROR_MASK(VAL) (((VAL) == SPDIFRX_PARITYERRORMASK_OFF) || \ ((VAL) == SPDIFRX_PARITYERRORMASK_ON)) #define IS_SPDIFRX_CHANNEL(CHANNEL) (((CHANNEL) == SPDIFRX_CHANNEL_A) || \ ((CHANNEL) == SPDIFRX_CHANNEL_B)) #define IS_SPDIFRX_DATA_FORMAT(FORMAT) (((FORMAT) == SPDIFRX_DATAFORMAT_LSB) || \ ((FORMAT) == SPDIFRX_DATAFORMAT_MSB) || \ ((FORMAT) == SPDIFRX_DATAFORMAT_32BITS)) #define IS_STEREO_MODE(MODE) (((MODE) == SPDIFRX_STEREOMODE_DISABLE) || \ ((MODE) == SPDIFRX_STEREOMODE_ENABLE)) #define IS_CHANNEL_STATUS_MASK(VAL) (((VAL) == SPDIFRX_CHANNELSTATUS_ON) || \ ((VAL) == SPDIFRX_CHANNELSTATUS_OFF)) /** * @} */ /* Private functions ---------------------------------------------------------*/ /** @defgroup SPDIFRX_Private_Functions SPDIFRX Private Functions * @{ */ /** * @} */ /** * @} */ /** * @} */ #endif /* STM32F446xx */ #ifdef __cplusplus } #endif #endif /* __STM32F4xx_HAL_SPDIFRX_H */ /************************ (C) COPYRIGHT STMicroelectronics *****END OF FILE****/ ================================================ FILE: Zelig/mbed/TARGET_NUCLEO_F411RE/stm32f4xx_hal_spi.h ================================================ /** ****************************************************************************** * @file stm32f4xx_hal_spi.h * @author MCD Application Team * @version V1.4.1 * @date 09-October-2015 * @brief Header file of SPI HAL module. ****************************************************************************** * @attention * *

© COPYRIGHT(c) 2015 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. * ****************************************************************************** */ /* Define to prevent recursive inclusion -------------------------------------*/ #ifndef __STM32F4xx_HAL_SPI_H #define __STM32F4xx_HAL_SPI_H #ifdef __cplusplus extern "C" { #endif /* Includes ------------------------------------------------------------------*/ #include "stm32f4xx_hal_def.h" /** @addtogroup STM32F4xx_HAL_Driver * @{ */ /** @addtogroup SPI * @{ */ /* Exported types ------------------------------------------------------------*/ /** @defgroup SPI_Exported_Types SPI Exported Types * @{ */ /** * @brief SPI Configuration Structure definition */ typedef struct { uint32_t Mode; /*!< Specifies the SPI operating mode. This parameter can be a value of @ref SPI_mode */ uint32_t Direction; /*!< Specifies the SPI Directional mode state. This parameter can be a value of @ref SPI_Direction_mode */ uint32_t DataSize; /*!< Specifies the SPI data size. This parameter can be a value of @ref SPI_data_size */ uint32_t CLKPolarity; /*!< Specifies the serial clock steady state. This parameter can be a value of @ref SPI_Clock_Polarity */ uint32_t CLKPhase; /*!< Specifies the clock active edge for the bit capture. This parameter can be a value of @ref SPI_Clock_Phase */ uint32_t NSS; /*!< Specifies whether the NSS signal is managed by hardware (NSS pin) or by software using the SSI bit. This parameter can be a value of @ref SPI_Slave_Select_management */ uint32_t BaudRatePrescaler; /*!< Specifies the Baud Rate prescaler value which will be used to configure the transmit and receive SCK clock. This parameter can be a value of @ref SPI_BaudRate_Prescaler @note The communication clock is derived from the master clock. The slave clock does not need to be set */ uint32_t FirstBit; /*!< Specifies whether data transfers start from MSB or LSB bit. This parameter can be a value of @ref SPI_MSB_LSB_transmission */ uint32_t TIMode; /*!< Specifies if the TI mode is enabled or not. This parameter can be a value of @ref SPI_TI_mode */ uint32_t CRCCalculation; /*!< Specifies if the CRC calculation is enabled or not. This parameter can be a value of @ref SPI_CRC_Calculation */ uint32_t CRCPolynomial; /*!< Specifies the polynomial used for the CRC calculation. This parameter must be a number between Min_Data = 0 and Max_Data = 65535 */ }SPI_InitTypeDef; /** * @brief HAL SPI State structure definition */ typedef enum { HAL_SPI_STATE_RESET = 0x00, /*!< SPI not yet initialized or disabled */ HAL_SPI_STATE_READY = 0x01, /*!< SPI initialized and ready for use */ HAL_SPI_STATE_BUSY = 0x02, /*!< SPI process is ongoing */ HAL_SPI_STATE_BUSY_TX = 0x12, /*!< Data Transmission process is ongoing */ HAL_SPI_STATE_BUSY_RX = 0x22, /*!< Data Reception process is ongoing */ HAL_SPI_STATE_BUSY_TX_RX = 0x32, /*!< Data Transmission and Reception process is ongoing */ HAL_SPI_STATE_ERROR = 0x03 /*!< SPI error state */ }HAL_SPI_StateTypeDef; /** * @brief SPI handle Structure definition */ typedef struct __SPI_HandleTypeDef { SPI_TypeDef *Instance; /* SPI registers base address */ SPI_InitTypeDef Init; /* SPI communication parameters */ uint8_t *pTxBuffPtr; /* Pointer to SPI Tx transfer Buffer */ uint16_t TxXferSize; /* SPI Tx transfer size */ uint16_t TxXferCount; /* SPI Tx Transfer Counter */ uint8_t *pRxBuffPtr; /* Pointer to SPI Rx transfer Buffer */ uint16_t RxXferSize; /* SPI Rx transfer size */ uint16_t RxXferCount; /* SPI Rx Transfer Counter */ DMA_HandleTypeDef *hdmatx; /* SPI Tx DMA handle parameters */ DMA_HandleTypeDef *hdmarx; /* SPI Rx DMA handle parameters */ void (*RxISR)(struct __SPI_HandleTypeDef * hspi); /* function pointer on Rx ISR */ void (*TxISR)(struct __SPI_HandleTypeDef * hspi); /* function pointer on Tx ISR */ HAL_LockTypeDef Lock; /* SPI locking object */ __IO HAL_SPI_StateTypeDef State; /* SPI communication state */ __IO uint32_t ErrorCode; /* SPI Error code */ }SPI_HandleTypeDef; /** * @} */ /* Exported constants --------------------------------------------------------*/ /** @defgroup SPI_Exported_Constants SPI Exported Constants * @{ */ /** @defgroup SPI_Error_Code SPI Error Code * @brief SPI Error Code * @{ */ #define HAL_SPI_ERROR_NONE ((uint32_t)0x00000000) /*!< No error */ #define HAL_SPI_ERROR_MODF ((uint32_t)0x00000001) /*!< MODF error */ #define HAL_SPI_ERROR_CRC ((uint32_t)0x00000002) /*!< CRC error */ #define HAL_SPI_ERROR_OVR ((uint32_t)0x00000004) /*!< OVR error */ #define HAL_SPI_ERROR_FRE ((uint32_t)0x00000008) /*!< FRE error */ #define HAL_SPI_ERROR_DMA ((uint32_t)0x00000010) /*!< DMA transfer error */ #define HAL_SPI_ERROR_FLAG ((uint32_t)0x00000020) /*!< Flag: RXNE,TXE, BSY */ /** * @} */ /** @defgroup SPI_mode SPI Mode * @{ */ #define SPI_MODE_SLAVE ((uint32_t)0x00000000) #define SPI_MODE_MASTER (SPI_CR1_MSTR | SPI_CR1_SSI) /** * @} */ /** @defgroup SPI_Direction_mode SPI Direction Mode * @{ */ #define SPI_DIRECTION_2LINES ((uint32_t)0x00000000) #define SPI_DIRECTION_2LINES_RXONLY SPI_CR1_RXONLY #define SPI_DIRECTION_1LINE SPI_CR1_BIDIMODE /** * @} */ /** @defgroup SPI_data_size SPI Data Size * @{ */ #define SPI_DATASIZE_8BIT ((uint32_t)0x00000000) #define SPI_DATASIZE_16BIT SPI_CR1_DFF /** * @} */ /** @defgroup SPI_Clock_Polarity SPI Clock Polarity * @{ */ #define SPI_POLARITY_LOW ((uint32_t)0x00000000) #define SPI_POLARITY_HIGH SPI_CR1_CPOL /** * @} */ /** @defgroup SPI_Clock_Phase SPI Clock Phase * @{ */ #define SPI_PHASE_1EDGE ((uint32_t)0x00000000) #define SPI_PHASE_2EDGE SPI_CR1_CPHA /** * @} */ /** @defgroup SPI_Slave_Select_management SPI Slave Select Management * @{ */ #define SPI_NSS_SOFT SPI_CR1_SSM #define SPI_NSS_HARD_INPUT ((uint32_t)0x00000000) #define SPI_NSS_HARD_OUTPUT ((uint32_t)0x00040000) /** * @} */ /** @defgroup SPI_BaudRate_Prescaler SPI BaudRate Prescaler * @{ */ #define SPI_BAUDRATEPRESCALER_2 ((uint32_t)0x00000000) #define SPI_BAUDRATEPRESCALER_4 ((uint32_t)0x00000008) #define SPI_BAUDRATEPRESCALER_8 ((uint32_t)0x00000010) #define SPI_BAUDRATEPRESCALER_16 ((uint32_t)0x00000018) #define SPI_BAUDRATEPRESCALER_32 ((uint32_t)0x00000020) #define SPI_BAUDRATEPRESCALER_64 ((uint32_t)0x00000028) #define SPI_BAUDRATEPRESCALER_128 ((uint32_t)0x00000030) #define SPI_BAUDRATEPRESCALER_256 ((uint32_t)0x00000038) /** * @} */ /** @defgroup SPI_MSB_LSB_transmission SPI MSB LSB Transsmission * @{ */ #define SPI_FIRSTBIT_MSB ((uint32_t)0x00000000) #define SPI_FIRSTBIT_LSB SPI_CR1_LSBFIRST /** * @} */ /** @defgroup SPI_TI_mode SPI TI Mode * @{ */ #define SPI_TIMODE_DISABLE ((uint32_t)0x00000000) #define SPI_TIMODE_ENABLE SPI_CR2_FRF /** * @} */ /** @defgroup SPI_CRC_Calculation SPI CRC Calculation * @{ */ #define SPI_CRCCALCULATION_DISABLE ((uint32_t)0x00000000) #define SPI_CRCCALCULATION_ENABLE SPI_CR1_CRCEN /** * @} */ /** @defgroup SPI_Interrupt_definition SPI Interrupt Definition * @{ */ #define SPI_IT_TXE SPI_CR2_TXEIE #define SPI_IT_RXNE SPI_CR2_RXNEIE #define SPI_IT_ERR SPI_CR2_ERRIE /** * @} */ /** @defgroup SPI_Flags_definition SPI Flags Definition * @{ */ #define SPI_FLAG_RXNE SPI_SR_RXNE #define SPI_FLAG_TXE SPI_SR_TXE #define SPI_FLAG_CRCERR SPI_SR_CRCERR #define SPI_FLAG_MODF SPI_SR_MODF #define SPI_FLAG_OVR SPI_SR_OVR #define SPI_FLAG_BSY SPI_SR_BSY #define SPI_FLAG_FRE SPI_SR_FRE /** * @} */ /** * @} */ /* Exported macro ------------------------------------------------------------*/ /** @defgroup SPI_Exported_Macros SPI Exported Macros * @{ */ /** @brief Reset SPI handle state * @param __HANDLE__: specifies the SPI handle. * This parameter can be SPI where x: 1, 2, or 3 to select the SPI peripheral. * @retval None */ #define __HAL_SPI_RESET_HANDLE_STATE(__HANDLE__) ((__HANDLE__)->State = HAL_SPI_STATE_RESET) /** @brief Enable or disable the specified SPI interrupts. * @param __HANDLE__: specifies the SPI handle. * This parameter can be SPI where x: 1, 2, or 3 to select the SPI peripheral. * @param __INTERRUPT__: specifies the interrupt source to enable or disable. * This parameter can be one of the following values: * @arg SPI_IT_TXE: Tx buffer empty interrupt enable * @arg SPI_IT_RXNE: RX buffer not empty interrupt enable * @arg SPI_IT_ERR: Error interrupt enable * @retval None */ #define __HAL_SPI_ENABLE_IT(__HANDLE__, __INTERRUPT__) ((__HANDLE__)->Instance->CR2 |= (__INTERRUPT__)) #define __HAL_SPI_DISABLE_IT(__HANDLE__, __INTERRUPT__) ((__HANDLE__)->Instance->CR2 &= (~(__INTERRUPT__))) /** @brief Check if the specified SPI interrupt source is enabled or disabled. * @param __HANDLE__: specifies the SPI handle. * This parameter can be SPI where x: 1, 2, or 3 to select the SPI peripheral. * @param __INTERRUPT__: specifies the SPI interrupt source to check. * This parameter can be one of the following values: * @arg SPI_IT_TXE: Tx buffer empty interrupt enable * @arg SPI_IT_RXNE: RX buffer not empty interrupt enable * @arg SPI_IT_ERR: Error interrupt enable * @retval The new state of __IT__ (TRUE or FALSE). */ #define __HAL_SPI_GET_IT_SOURCE(__HANDLE__, __INTERRUPT__) ((((__HANDLE__)->Instance->CR2 & (__INTERRUPT__)) == (__INTERRUPT__)) ? SET : RESET) /** @brief Check whether the specified SPI flag is set or not. * @param __HANDLE__: specifies the SPI handle. * This parameter can be SPI where x: 1, 2, or 3 to select the SPI peripheral. * @param __FLAG__: specifies the flag to check. * This parameter can be one of the following values: * @arg SPI_FLAG_RXNE: Receive buffer not empty flag * @arg SPI_FLAG_TXE: Transmit buffer empty flag * @arg SPI_FLAG_CRCERR: CRC error flag * @arg SPI_FLAG_MODF: Mode fault flag * @arg SPI_FLAG_OVR: Overrun flag * @arg SPI_FLAG_BSY: Busy flag * @arg SPI_FLAG_FRE: Frame format error flag * @retval The new state of __FLAG__ (TRUE or FALSE). */ #define __HAL_SPI_GET_FLAG(__HANDLE__, __FLAG__) ((((__HANDLE__)->Instance->SR) & (__FLAG__)) == (__FLAG__)) /** @brief Clear the SPI CRCERR pending flag. * @param __HANDLE__: specifies the SPI handle. * This parameter can be SPI where x: 1, 2, or 3 to select the SPI peripheral. * @retval None */ #define __HAL_SPI_CLEAR_CRCERRFLAG(__HANDLE__) ((__HANDLE__)->Instance->SR = ~(SPI_FLAG_CRCERR)) /** @brief Clear the SPI MODF pending flag. * @param __HANDLE__: specifies the SPI handle. * This parameter can be SPI where x: 1, 2, or 3 to select the SPI peripheral. * @retval None */ #define __HAL_SPI_CLEAR_MODFFLAG(__HANDLE__) \ do{ \ __IO uint32_t tmpreg; \ tmpreg = (__HANDLE__)->Instance->SR; \ (__HANDLE__)->Instance->CR1 &= (~SPI_CR1_SPE); \ UNUSED(tmpreg); \ } while(0) /** @brief Clear the SPI OVR pending flag. * @param __HANDLE__: specifies the SPI handle. * This parameter can be SPI where x: 1, 2, or 3 to select the SPI peripheral. * @retval None */ #define __HAL_SPI_CLEAR_OVRFLAG(__HANDLE__) \ do{ \ __IO uint32_t tmpreg; \ tmpreg = (__HANDLE__)->Instance->DR; \ tmpreg = (__HANDLE__)->Instance->SR; \ UNUSED(tmpreg); \ } while(0) /** @brief Clear the SPI FRE pending flag. * @param __HANDLE__: specifies the SPI handle. * This parameter can be SPI where x: 1, 2, or 3 to select the SPI peripheral. * @retval None */ #define __HAL_SPI_CLEAR_FREFLAG(__HANDLE__) \ do{ \ __IO uint32_t tmpreg; \ tmpreg = (__HANDLE__)->Instance->SR; \ UNUSED(tmpreg); \ }while(0) /** @brief Enable SPI * @param __HANDLE__: specifies the SPI Handle. * @retval None */ #define __HAL_SPI_ENABLE(__HANDLE__) ((__HANDLE__)->Instance->CR1 |= SPI_CR1_SPE) /** @brief Disable SPI * @param __HANDLE__: specifies the SPI Handle. * @retval None */ #define __HAL_SPI_DISABLE(__HANDLE__) ((__HANDLE__)->Instance->CR1 &= ~SPI_CR1_SPE) /** * @} */ /* Exported functions --------------------------------------------------------*/ /** @addtogroup SPI_Exported_Functions * @{ */ /** @addtogroup SPI_Exported_Functions_Group1 * @{ */ /* Initialization/de-initialization functions **********************************/ HAL_StatusTypeDef HAL_SPI_Init(SPI_HandleTypeDef *hspi); HAL_StatusTypeDef HAL_SPI_DeInit (SPI_HandleTypeDef *hspi); void HAL_SPI_MspInit(SPI_HandleTypeDef *hspi); void HAL_SPI_MspDeInit(SPI_HandleTypeDef *hspi); /** * @} */ /** @addtogroup SPI_Exported_Functions_Group2 * @{ */ /* I/O operation functions *****************************************************/ HAL_StatusTypeDef HAL_SPI_Transmit(SPI_HandleTypeDef *hspi, uint8_t *pData, uint16_t Size, uint32_t Timeout); HAL_StatusTypeDef HAL_SPI_Receive(SPI_HandleTypeDef *hspi, uint8_t *pData, uint16_t Size, uint32_t Timeout); HAL_StatusTypeDef HAL_SPI_TransmitReceive(SPI_HandleTypeDef *hspi, uint8_t *pTxData, uint8_t *pRxData, uint16_t Size, uint32_t Timeout); HAL_StatusTypeDef HAL_SPI_Transmit_IT(SPI_HandleTypeDef *hspi, uint8_t *pData, uint16_t Size); HAL_StatusTypeDef HAL_SPI_Receive_IT(SPI_HandleTypeDef *hspi, uint8_t *pData, uint16_t Size); HAL_StatusTypeDef HAL_SPI_TransmitReceive_IT(SPI_HandleTypeDef *hspi, uint8_t *pTxData, uint8_t *pRxData, uint16_t Size); HAL_StatusTypeDef HAL_SPI_Transmit_DMA(SPI_HandleTypeDef *hspi, uint8_t *pData, uint16_t Size); HAL_StatusTypeDef HAL_SPI_Receive_DMA(SPI_HandleTypeDef *hspi, uint8_t *pData, uint16_t Size); HAL_StatusTypeDef HAL_SPI_TransmitReceive_DMA(SPI_HandleTypeDef *hspi, uint8_t *pTxData, uint8_t *pRxData, uint16_t Size); HAL_StatusTypeDef HAL_SPI_DMAPause(SPI_HandleTypeDef *hspi); HAL_StatusTypeDef HAL_SPI_DMAResume(SPI_HandleTypeDef *hspi); HAL_StatusTypeDef HAL_SPI_DMAStop(SPI_HandleTypeDef *hspi); void HAL_SPI_IRQHandler(SPI_HandleTypeDef *hspi); void HAL_SPI_TxCpltCallback(SPI_HandleTypeDef *hspi); void HAL_SPI_RxCpltCallback(SPI_HandleTypeDef *hspi); void HAL_SPI_TxRxCpltCallback(SPI_HandleTypeDef *hspi); void HAL_SPI_ErrorCallback(SPI_HandleTypeDef *hspi); void HAL_SPI_TxHalfCpltCallback(SPI_HandleTypeDef *hspi); void HAL_SPI_RxHalfCpltCallback(SPI_HandleTypeDef *hspi); void HAL_SPI_TxRxHalfCpltCallback(SPI_HandleTypeDef *hspi); /** * @} */ /** @addtogroup SPI_Exported_Functions_Group3 * @{ */ /* Peripheral State and Control functions **************************************/ HAL_SPI_StateTypeDef HAL_SPI_GetState(SPI_HandleTypeDef *hspi); uint32_t HAL_SPI_GetError(SPI_HandleTypeDef *hspi); /** * @} */ /** * @} */ /* Private types -------------------------------------------------------------*/ /* Private variables ---------------------------------------------------------*/ /* Private constants ---------------------------------------------------------*/ /** @defgroup SPI_Private_Constants SPI Private Constants * @{ */ /** * @} */ /* Private macros ------------------------------------------------------------*/ /** @defgroup SPI_Private_Macros SPI Private Macros * @{ */ #define IS_SPI_MODE(MODE) (((MODE) == SPI_MODE_SLAVE) || \ ((MODE) == SPI_MODE_MASTER)) #define IS_SPI_DIRECTION_MODE(MODE) (((MODE) == SPI_DIRECTION_2LINES) || \ ((MODE) == SPI_DIRECTION_2LINES_RXONLY) || \ ((MODE) == SPI_DIRECTION_1LINE)) #define IS_SPI_DIRECTION_2LINES_OR_1LINE(MODE) (((MODE) == SPI_DIRECTION_2LINES) || \ ((MODE) == SPI_DIRECTION_1LINE)) #define IS_SPI_DIRECTION_2LINES(MODE) ((MODE) == SPI_DIRECTION_2LINES) #define IS_SPI_DATASIZE(DATASIZE) (((DATASIZE) == SPI_DATASIZE_16BIT) || \ ((DATASIZE) == SPI_DATASIZE_8BIT)) #define IS_SPI_CPOL(CPOL) (((CPOL) == SPI_POLARITY_LOW) || \ ((CPOL) == SPI_POLARITY_HIGH)) #define IS_SPI_CPHA(CPHA) (((CPHA) == SPI_PHASE_1EDGE) || \ ((CPHA) == SPI_PHASE_2EDGE)) #define IS_SPI_NSS(NSS) (((NSS) == SPI_NSS_SOFT) || \ ((NSS) == SPI_NSS_HARD_INPUT) || \ ((NSS) == SPI_NSS_HARD_OUTPUT)) #define IS_SPI_BAUDRATE_PRESCALER(PRESCALER) (((PRESCALER) == SPI_BAUDRATEPRESCALER_2) || \ ((PRESCALER) == SPI_BAUDRATEPRESCALER_4) || \ ((PRESCALER) == SPI_BAUDRATEPRESCALER_8) || \ ((PRESCALER) == SPI_BAUDRATEPRESCALER_16) || \ ((PRESCALER) == SPI_BAUDRATEPRESCALER_32) || \ ((PRESCALER) == SPI_BAUDRATEPRESCALER_64) || \ ((PRESCALER) == SPI_BAUDRATEPRESCALER_128) || \ ((PRESCALER) == SPI_BAUDRATEPRESCALER_256)) #define IS_SPI_FIRST_BIT(BIT) (((BIT) == SPI_FIRSTBIT_MSB) || \ ((BIT) == SPI_FIRSTBIT_LSB)) #define IS_SPI_TIMODE(MODE) (((MODE) == SPI_TIMODE_DISABLE) || \ ((MODE) == SPI_TIMODE_ENABLE)) #define IS_SPI_CRC_CALCULATION(CALCULATION) (((CALCULATION) == SPI_CRCCALCULATION_DISABLE) || \ ((CALCULATION) == SPI_CRCCALCULATION_ENABLE)) #define IS_SPI_CRC_POLYNOMIAL(POLYNOMIAL) (((POLYNOMIAL) >= 0x1) && ((POLYNOMIAL) <= 0xFFFF)) #define SPI_1LINE_TX(__HANDLE__) ((__HANDLE__)->Instance->CR1 |= SPI_CR1_BIDIOE) #define SPI_1LINE_RX(__HANDLE__) ((__HANDLE__)->Instance->CR1 &= ~SPI_CR1_BIDIOE) #define SPI_RESET_CRC(__HANDLE__) do{(__HANDLE__)->Instance->CR1 &= (~SPI_CR1_CRCEN);\ (__HANDLE__)->Instance->CR1 |= SPI_CR1_CRCEN;}while(0) /** * @} */ /* Private functions ---------------------------------------------------------*/ /** @defgroup SPI_Private_Functions SPI Private Functions * @{ */ /** * @} */ /** * @} */ /** * @} */ #ifdef __cplusplus } #endif #endif /* __STM32F4xx_HAL_SPI_H */ /************************ (C) COPYRIGHT STMicroelectronics *****END OF FILE****/ ================================================ FILE: Zelig/mbed/TARGET_NUCLEO_F411RE/stm32f4xx_hal_sram.h ================================================ /** ****************************************************************************** * @file stm32f4xx_hal_sram.h * @author MCD Application Team * @version V1.4.1 * @date 09-October-2015 * @brief Header file of SRAM HAL module. ****************************************************************************** * @attention * *

© COPYRIGHT(c) 2015 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. * ****************************************************************************** */ /* Define to prevent recursive inclusion -------------------------------------*/ #ifndef __STM32F4xx_HAL_SRAM_H #define __STM32F4xx_HAL_SRAM_H #ifdef __cplusplus extern "C" { #endif /* Includes ------------------------------------------------------------------*/ #if defined(STM32F405xx) || defined(STM32F415xx) || defined(STM32F407xx)|| defined(STM32F417xx) #include "stm32f4xx_ll_fsmc.h" #endif /* STM32F405xx || STM32F415xx || STM32F407xx || STM32F417xx */ #if defined(STM32F427xx) || defined(STM32F437xx) || defined(STM32F429xx)|| defined(STM32F439xx) ||\ defined(STM32F446xx) || defined(STM32F469xx) || defined(STM32F479xx) #include "stm32f4xx_ll_fmc.h" #endif /* STM32F427xx || STM32F437xx || STM32F429xx || STM32F439xx || STM32F446xx || STM32F469xx || STM32F479xx */ /** @addtogroup STM32F4xx_HAL_Driver * @{ */ #if defined(STM32F405xx) || defined(STM32F415xx) || defined(STM32F407xx) || defined(STM32F417xx) ||\ defined(STM32F427xx) || defined(STM32F437xx) || defined(STM32F429xx) || defined(STM32F439xx) ||\ defined(STM32F446xx) || defined(STM32F469xx) || defined(STM32F479xx) /** @addtogroup SRAM * @{ */ /* Exported typedef ----------------------------------------------------------*/ /** @defgroup SRAM_Exported_Types SRAM Exported Types * @{ */ /** * @brief HAL SRAM State structures definition */ typedef enum { HAL_SRAM_STATE_RESET = 0x00, /*!< SRAM not yet initialized or disabled */ HAL_SRAM_STATE_READY = 0x01, /*!< SRAM initialized and ready for use */ HAL_SRAM_STATE_BUSY = 0x02, /*!< SRAM internal process is ongoing */ HAL_SRAM_STATE_ERROR = 0x03, /*!< SRAM error state */ HAL_SRAM_STATE_PROTECTED = 0x04 /*!< SRAM peripheral NORSRAM device write protected */ }HAL_SRAM_StateTypeDef; /** * @brief SRAM handle Structure definition */ typedef struct { FMC_NORSRAM_TypeDef *Instance; /*!< Register base address */ FMC_NORSRAM_EXTENDED_TypeDef *Extended; /*!< Extended mode register base address */ FMC_NORSRAM_InitTypeDef Init; /*!< SRAM device control configuration parameters */ HAL_LockTypeDef Lock; /*!< SRAM locking object */ __IO HAL_SRAM_StateTypeDef State; /*!< SRAM device access state */ DMA_HandleTypeDef *hdma; /*!< Pointer DMA handler */ }SRAM_HandleTypeDef; /** * @} */ /* Exported constants --------------------------------------------------------*/ /* Exported macro ------------------------------------------------------------*/ /** @defgroup SRAM_Exported_Macros SRAM Exported Macros * @{ */ /** @brief Reset SRAM handle state * @param __HANDLE__: SRAM handle * @retval None */ #define __HAL_SRAM_RESET_HANDLE_STATE(__HANDLE__) ((__HANDLE__)->State = HAL_SRAM_STATE_RESET) /** * @} */ /* Exported functions --------------------------------------------------------*/ /** @addtogroup SRAM_Exported_Functions * @{ */ /** @addtogroup SRAM_Exported_Functions_Group1 * @{ */ /* Initialization/de-initialization functions **********************************/ HAL_StatusTypeDef HAL_SRAM_Init(SRAM_HandleTypeDef *hsram, FMC_NORSRAM_TimingTypeDef *Timing, FMC_NORSRAM_TimingTypeDef *ExtTiming); HAL_StatusTypeDef HAL_SRAM_DeInit(SRAM_HandleTypeDef *hsram); void HAL_SRAM_MspInit(SRAM_HandleTypeDef *hsram); void HAL_SRAM_MspDeInit(SRAM_HandleTypeDef *hsram); void HAL_SRAM_DMA_XferCpltCallback(DMA_HandleTypeDef *hdma); void HAL_SRAM_DMA_XferErrorCallback(DMA_HandleTypeDef *hdma); /** * @} */ /** @addtogroup SRAM_Exported_Functions_Group2 * @{ */ /* I/O operation functions *****************************************************/ HAL_StatusTypeDef HAL_SRAM_Read_8b(SRAM_HandleTypeDef *hsram, uint32_t *pAddress, uint8_t *pDstBuffer, uint32_t BufferSize); HAL_StatusTypeDef HAL_SRAM_Write_8b(SRAM_HandleTypeDef *hsram, uint32_t *pAddress, uint8_t *pSrcBuffer, uint32_t BufferSize); HAL_StatusTypeDef HAL_SRAM_Read_16b(SRAM_HandleTypeDef *hsram, uint32_t *pAddress, uint16_t *pDstBuffer, uint32_t BufferSize); HAL_StatusTypeDef HAL_SRAM_Write_16b(SRAM_HandleTypeDef *hsram, uint32_t *pAddress, uint16_t *pSrcBuffer, uint32_t BufferSize); HAL_StatusTypeDef HAL_SRAM_Read_32b(SRAM_HandleTypeDef *hsram, uint32_t *pAddress, uint32_t *pDstBuffer, uint32_t BufferSize); HAL_StatusTypeDef HAL_SRAM_Write_32b(SRAM_HandleTypeDef *hsram, uint32_t *pAddress, uint32_t *pSrcBuffer, uint32_t BufferSize); HAL_StatusTypeDef HAL_SRAM_Read_DMA(SRAM_HandleTypeDef *hsram, uint32_t *pAddress, uint32_t *pDstBuffer, uint32_t BufferSize); HAL_StatusTypeDef HAL_SRAM_Write_DMA(SRAM_HandleTypeDef *hsram, uint32_t *pAddress, uint32_t *pSrcBuffer, uint32_t BufferSize); /** * @} */ /** @addtogroup SRAM_Exported_Functions_Group3 * @{ */ /* SRAM Control functions ******************************************************/ HAL_StatusTypeDef HAL_SRAM_WriteOperation_Enable(SRAM_HandleTypeDef *hsram); HAL_StatusTypeDef HAL_SRAM_WriteOperation_Disable(SRAM_HandleTypeDef *hsram); /** * @} */ /** @addtogroup SRAM_Exported_Functions_Group4 * @{ */ /* SRAM State functions *********************************************************/ HAL_SRAM_StateTypeDef HAL_SRAM_GetState(SRAM_HandleTypeDef *hsram); /** * @} */ /** * @} */ /* Private types -------------------------------------------------------------*/ /* Private variables ---------------------------------------------------------*/ /* Private constants ---------------------------------------------------------*/ /* Private macros ------------------------------------------------------------*/ /* Private functions ---------------------------------------------------------*/ /** * @} */ #endif /* STM32F405xx || STM32F415xx || STM32F407xx || STM32F417xx || STM32F427xx || STM32F437xx ||\ STM32F429xx || STM32F439xx || STM32F446xx || STM32F469xx || STM32F479xx */ /** * @} */ #ifdef __cplusplus } #endif #endif /* __STM32F4xx_HAL_SRAM_H */ /************************ (C) COPYRIGHT STMicroelectronics *****END OF FILE****/ ================================================ FILE: Zelig/mbed/TARGET_NUCLEO_F411RE/stm32f4xx_hal_tim.h ================================================ /** ****************************************************************************** * @file stm32f4xx_hal_tim.h * @author MCD Application Team * @version V1.4.1 * @date 09-October-2015 * @brief Header file of TIM HAL module. ****************************************************************************** * @attention * *

© COPYRIGHT(c) 2015 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. * ****************************************************************************** */ /* Define to prevent recursive inclusion -------------------------------------*/ #ifndef __STM32F4xx_HAL_TIM_H #define __STM32F4xx_HAL_TIM_H #ifdef __cplusplus extern "C" { #endif /* Includes ------------------------------------------------------------------*/ #include "stm32f4xx_hal_def.h" /** @addtogroup STM32F4xx_HAL_Driver * @{ */ /** @addtogroup TIM * @{ */ /* Exported types ------------------------------------------------------------*/ /** @defgroup TIM_Exported_Types TIM Exported Types * @{ */ /** * @brief TIM Time base Configuration Structure definition */ typedef struct { uint32_t Prescaler; /*!< Specifies the prescaler value used to divide the TIM clock. This parameter can be a number between Min_Data = 0x0000 and Max_Data = 0xFFFF */ uint32_t CounterMode; /*!< Specifies the counter mode. This parameter can be a value of @ref TIM_Counter_Mode */ uint32_t Period; /*!< Specifies the period value to be loaded into the active Auto-Reload Register at the next update event. This parameter can be a number between Min_Data = 0x0000 and Max_Data = 0xFFFF. */ uint32_t ClockDivision; /*!< Specifies the clock division. This parameter can be a value of @ref TIM_ClockDivision */ uint32_t RepetitionCounter; /*!< Specifies the repetition counter value. Each time the RCR downcounter reaches zero, an update event is generated and counting restarts from the RCR value (N). This means in PWM mode that (N+1) corresponds to: - the number of PWM periods in edge-aligned mode - the number of half PWM period in center-aligned mode This parameter must be a number between Min_Data = 0x00 and Max_Data = 0xFF. @note This parameter is valid only for TIM1 and TIM8. */ } TIM_Base_InitTypeDef; /** * @brief TIM Output Compare Configuration Structure definition */ typedef struct { uint32_t OCMode; /*!< Specifies the TIM mode. This parameter can be a value of @ref TIM_Output_Compare_and_PWM_modes */ uint32_t Pulse; /*!< Specifies the pulse value to be loaded into the Capture Compare Register. This parameter can be a number between Min_Data = 0x0000 and Max_Data = 0xFFFF */ uint32_t OCPolarity; /*!< Specifies the output polarity. This parameter can be a value of @ref TIM_Output_Compare_Polarity */ uint32_t OCNPolarity; /*!< Specifies the complementary output polarity. This parameter can be a value of @ref TIM_Output_Compare_N_Polarity @note This parameter is valid only for TIM1 and TIM8. */ uint32_t OCFastMode; /*!< Specifies the Fast mode state. This parameter can be a value of @ref TIM_Output_Fast_State @note This parameter is valid only in PWM1 and PWM2 mode. */ uint32_t OCIdleState; /*!< Specifies the TIM Output Compare pin state during Idle state. This parameter can be a value of @ref TIM_Output_Compare_Idle_State @note This parameter is valid only for TIM1 and TIM8. */ uint32_t OCNIdleState; /*!< Specifies the TIM Output Compare pin state during Idle state. This parameter can be a value of @ref TIM_Output_Compare_N_Idle_State @note This parameter is valid only for TIM1 and TIM8. */ } TIM_OC_InitTypeDef; /** * @brief TIM One Pulse Mode Configuration Structure definition */ typedef struct { uint32_t OCMode; /*!< Specifies the TIM mode. This parameter can be a value of @ref TIM_Output_Compare_and_PWM_modes */ uint32_t Pulse; /*!< Specifies the pulse value to be loaded into the Capture Compare Register. This parameter can be a number between Min_Data = 0x0000 and Max_Data = 0xFFFF */ uint32_t OCPolarity; /*!< Specifies the output polarity. This parameter can be a value of @ref TIM_Output_Compare_Polarity */ uint32_t OCNPolarity; /*!< Specifies the complementary output polarity. This parameter can be a value of @ref TIM_Output_Compare_N_Polarity @note This parameter is valid only for TIM1 and TIM8. */ uint32_t OCIdleState; /*!< Specifies the TIM Output Compare pin state during Idle state. This parameter can be a value of @ref TIM_Output_Compare_Idle_State @note This parameter is valid only for TIM1 and TIM8. */ uint32_t OCNIdleState; /*!< Specifies the TIM Output Compare pin state during Idle state. This parameter can be a value of @ref TIM_Output_Compare_N_Idle_State @note This parameter is valid only for TIM1 and TIM8. */ uint32_t ICPolarity; /*!< Specifies the active edge of the input signal. This parameter can be a value of @ref TIM_Input_Capture_Polarity */ uint32_t ICSelection; /*!< Specifies the input. This parameter can be a value of @ref TIM_Input_Capture_Selection */ uint32_t ICFilter; /*!< Specifies the input capture filter. This parameter can be a number between Min_Data = 0x0 and Max_Data = 0xF */ } TIM_OnePulse_InitTypeDef; /** * @brief TIM Input Capture Configuration Structure definition */ typedef struct { uint32_t ICPolarity; /*!< Specifies the active edge of the input signal. This parameter can be a value of @ref TIM_Input_Capture_Polarity */ uint32_t ICSelection; /*!< Specifies the input. This parameter can be a value of @ref TIM_Input_Capture_Selection */ uint32_t ICPrescaler; /*!< Specifies the Input Capture Prescaler. This parameter can be a value of @ref TIM_Input_Capture_Prescaler */ uint32_t ICFilter; /*!< Specifies the input capture filter. This parameter can be a number between Min_Data = 0x0 and Max_Data = 0xF */ } TIM_IC_InitTypeDef; /** * @brief TIM Encoder Configuration Structure definition */ typedef struct { uint32_t EncoderMode; /*!< Specifies the active edge of the input signal. This parameter can be a value of @ref TIM_Encoder_Mode */ uint32_t IC1Polarity; /*!< Specifies the active edge of the input signal. This parameter can be a value of @ref TIM_Input_Capture_Polarity */ uint32_t IC1Selection; /*!< Specifies the input. This parameter can be a value of @ref TIM_Input_Capture_Selection */ uint32_t IC1Prescaler; /*!< Specifies the Input Capture Prescaler. This parameter can be a value of @ref TIM_Input_Capture_Prescaler */ uint32_t IC1Filter; /*!< Specifies the input capture filter. This parameter can be a number between Min_Data = 0x0 and Max_Data = 0xF */ uint32_t IC2Polarity; /*!< Specifies the active edge of the input signal. This parameter can be a value of @ref TIM_Input_Capture_Polarity */ uint32_t IC2Selection; /*!< Specifies the input. This parameter can be a value of @ref TIM_Input_Capture_Selection */ uint32_t IC2Prescaler; /*!< Specifies the Input Capture Prescaler. This parameter can be a value of @ref TIM_Input_Capture_Prescaler */ uint32_t IC2Filter; /*!< Specifies the input capture filter. This parameter can be a number between Min_Data = 0x0 and Max_Data = 0xF */ } TIM_Encoder_InitTypeDef; /** * @brief Clock Configuration Handle Structure definition */ typedef struct { uint32_t ClockSource; /*!< TIM clock sources. This parameter can be a value of @ref TIM_Clock_Source */ uint32_t ClockPolarity; /*!< TIM clock polarity. This parameter can be a value of @ref TIM_Clock_Polarity */ uint32_t ClockPrescaler; /*!< TIM clock prescaler. This parameter can be a value of @ref TIM_Clock_Prescaler */ uint32_t ClockFilter; /*!< TIM clock filter. This parameter can be a number between Min_Data = 0x0 and Max_Data = 0xF */ }TIM_ClockConfigTypeDef; /** * @brief Clear Input Configuration Handle Structure definition */ typedef struct { uint32_t ClearInputState; /*!< TIM clear Input state. This parameter can be ENABLE or DISABLE */ uint32_t ClearInputSource; /*!< TIM clear Input sources. This parameter can be a value of @ref TIM_ClearInput_Source */ uint32_t ClearInputPolarity; /*!< TIM Clear Input polarity. This parameter can be a value of @ref TIM_ClearInput_Polarity */ uint32_t ClearInputPrescaler; /*!< TIM Clear Input prescaler. This parameter can be a value of @ref TIM_ClearInput_Prescaler */ uint32_t ClearInputFilter; /*!< TIM Clear Input filter. This parameter can be a number between Min_Data = 0x0 and Max_Data = 0xF */ }TIM_ClearInputConfigTypeDef; /** * @brief TIM Slave configuration Structure definition */ typedef struct { uint32_t SlaveMode; /*!< Slave mode selection This parameter can be a value of @ref TIM_Slave_Mode */ uint32_t InputTrigger; /*!< Input Trigger source This parameter can be a value of @ref TIM_Trigger_Selection */ uint32_t TriggerPolarity; /*!< Input Trigger polarity This parameter can be a value of @ref TIM_Trigger_Polarity */ uint32_t TriggerPrescaler; /*!< Input trigger prescaler This parameter can be a value of @ref TIM_Trigger_Prescaler */ uint32_t TriggerFilter; /*!< Input trigger filter This parameter can be a number between Min_Data = 0x0 and Max_Data = 0xF */ }TIM_SlaveConfigTypeDef; /** * @brief HAL State structures definition */ typedef enum { HAL_TIM_STATE_RESET = 0x00, /*!< Peripheral not yet initialized or disabled */ HAL_TIM_STATE_READY = 0x01, /*!< Peripheral Initialized and ready for use */ HAL_TIM_STATE_BUSY = 0x02, /*!< An internal process is ongoing */ HAL_TIM_STATE_TIMEOUT = 0x03, /*!< Timeout state */ HAL_TIM_STATE_ERROR = 0x04 /*!< Reception process is ongoing */ }HAL_TIM_StateTypeDef; /** * @brief HAL Active channel structures definition */ typedef enum { HAL_TIM_ACTIVE_CHANNEL_1 = 0x01, /*!< The active channel is 1 */ HAL_TIM_ACTIVE_CHANNEL_2 = 0x02, /*!< The active channel is 2 */ HAL_TIM_ACTIVE_CHANNEL_3 = 0x04, /*!< The active channel is 3 */ HAL_TIM_ACTIVE_CHANNEL_4 = 0x08, /*!< The active channel is 4 */ HAL_TIM_ACTIVE_CHANNEL_CLEARED = 0x00 /*!< All active channels cleared */ }HAL_TIM_ActiveChannel; /** * @brief TIM Time Base Handle Structure definition */ typedef struct { TIM_TypeDef *Instance; /*!< Register base address */ TIM_Base_InitTypeDef Init; /*!< TIM Time Base required parameters */ HAL_TIM_ActiveChannel Channel; /*!< Active channel */ DMA_HandleTypeDef *hdma[7]; /*!< DMA Handlers array This array is accessed by a @ref DMA_Handle_index */ HAL_LockTypeDef Lock; /*!< Locking object */ __IO HAL_TIM_StateTypeDef State; /*!< TIM operation state */ }TIM_HandleTypeDef; /** * @} */ /* Exported constants --------------------------------------------------------*/ /** @defgroup TIM_Exported_Constants TIM Exported Constants * @{ */ /** @defgroup TIM_Input_Channel_Polarity TIM Input Channel Polarity * @{ */ #define TIM_INPUTCHANNELPOLARITY_RISING ((uint32_t)0x00000000) /*!< Polarity for TIx source */ #define TIM_INPUTCHANNELPOLARITY_FALLING (TIM_CCER_CC1P) /*!< Polarity for TIx source */ #define TIM_INPUTCHANNELPOLARITY_BOTHEDGE (TIM_CCER_CC1P | TIM_CCER_CC1NP) /*!< Polarity for TIx source */ /** * @} */ /** @defgroup TIM_ETR_Polarity TIM ETR Polarity * @{ */ #define TIM_ETRPOLARITY_INVERTED (TIM_SMCR_ETP) /*!< Polarity for ETR source */ #define TIM_ETRPOLARITY_NONINVERTED ((uint32_t)0x0000) /*!< Polarity for ETR source */ /** * @} */ /** @defgroup TIM_ETR_Prescaler TIM ETR Prescaler * @{ */ #define TIM_ETRPRESCALER_DIV1 ((uint32_t)0x0000) /*!< No prescaler is used */ #define TIM_ETRPRESCALER_DIV2 (TIM_SMCR_ETPS_0) /*!< ETR input source is divided by 2 */ #define TIM_ETRPRESCALER_DIV4 (TIM_SMCR_ETPS_1) /*!< ETR input source is divided by 4 */ #define TIM_ETRPRESCALER_DIV8 (TIM_SMCR_ETPS) /*!< ETR input source is divided by 8 */ /** * @} */ /** @defgroup TIM_Counter_Mode TIM Counter Mode * @{ */ #define TIM_COUNTERMODE_UP ((uint32_t)0x0000) #define TIM_COUNTERMODE_DOWN TIM_CR1_DIR #define TIM_COUNTERMODE_CENTERALIGNED1 TIM_CR1_CMS_0 #define TIM_COUNTERMODE_CENTERALIGNED2 TIM_CR1_CMS_1 #define TIM_COUNTERMODE_CENTERALIGNED3 TIM_CR1_CMS /** * @} */ /** @defgroup TIM_ClockDivision TIM Clock Division * @{ */ #define TIM_CLOCKDIVISION_DIV1 ((uint32_t)0x0000) #define TIM_CLOCKDIVISION_DIV2 (TIM_CR1_CKD_0) #define TIM_CLOCKDIVISION_DIV4 (TIM_CR1_CKD_1) /** * @} */ /** @defgroup TIM_Output_Compare_and_PWM_modes TIM Output Compare and PWM modes * @{ */ #define TIM_OCMODE_TIMING ((uint32_t)0x0000) #define TIM_OCMODE_ACTIVE (TIM_CCMR1_OC1M_0) #define TIM_OCMODE_INACTIVE (TIM_CCMR1_OC1M_1) #define TIM_OCMODE_TOGGLE (TIM_CCMR1_OC1M_0 | TIM_CCMR1_OC1M_1) #define TIM_OCMODE_PWM1 (TIM_CCMR1_OC1M_1 | TIM_CCMR1_OC1M_2) #define TIM_OCMODE_PWM2 (TIM_CCMR1_OC1M) #define TIM_OCMODE_FORCED_ACTIVE (TIM_CCMR1_OC1M_0 | TIM_CCMR1_OC1M_2) #define TIM_OCMODE_FORCED_INACTIVE (TIM_CCMR1_OC1M_2) /** * @} */ /** @defgroup TIM_Output_Fast_State TIM Output Fast State * @{ */ #define TIM_OCFAST_DISABLE ((uint32_t)0x0000) #define TIM_OCFAST_ENABLE (TIM_CCMR1_OC1FE) /** * @} */ /** @defgroup TIM_Output_Compare_Polarity TIM Output Compare Polarity * @{ */ #define TIM_OCPOLARITY_HIGH ((uint32_t)0x0000) #define TIM_OCPOLARITY_LOW (TIM_CCER_CC1P) /** * @} */ /** @defgroup TIM_Output_Compare_N_Polarity TIM Output CompareN Polarity * @{ */ #define TIM_OCNPOLARITY_HIGH ((uint32_t)0x0000) #define TIM_OCNPOLARITY_LOW (TIM_CCER_CC1NP) /** * @} */ /** @defgroup TIM_Output_Compare_Idle_State TIM Output Compare Idle State * @{ */ #define TIM_OCIDLESTATE_SET (TIM_CR2_OIS1) #define TIM_OCIDLESTATE_RESET ((uint32_t)0x0000) /** * @} */ /** @defgroup TIM_Output_Compare_N_Idle_State TIM Output Compare N Idle State * @{ */ #define TIM_OCNIDLESTATE_SET (TIM_CR2_OIS1N) #define TIM_OCNIDLESTATE_RESET ((uint32_t)0x0000) /** * @} */ /** @defgroup TIM_Channel TIM Channel * @{ */ #define TIM_CHANNEL_1 ((uint32_t)0x0000) #define TIM_CHANNEL_2 ((uint32_t)0x0004) #define TIM_CHANNEL_3 ((uint32_t)0x0008) #define TIM_CHANNEL_4 ((uint32_t)0x000C) #define TIM_CHANNEL_ALL ((uint32_t)0x0018) /** * @} */ /** @defgroup TIM_Input_Capture_Polarity TIM Input Capture Polarity * @{ */ #define TIM_ICPOLARITY_RISING TIM_INPUTCHANNELPOLARITY_RISING #define TIM_ICPOLARITY_FALLING TIM_INPUTCHANNELPOLARITY_FALLING #define TIM_ICPOLARITY_BOTHEDGE TIM_INPUTCHANNELPOLARITY_BOTHEDGE /** * @} */ /** @defgroup TIM_Input_Capture_Selection TIM Input Capture Selection * @{ */ #define TIM_ICSELECTION_DIRECTTI (TIM_CCMR1_CC1S_0) /*!< TIM Input 1, 2, 3 or 4 is selected to be connected to IC1, IC2, IC3 or IC4, respectively */ #define TIM_ICSELECTION_INDIRECTTI (TIM_CCMR1_CC1S_1) /*!< TIM Input 1, 2, 3 or 4 is selected to be connected to IC2, IC1, IC4 or IC3, respectively */ #define TIM_ICSELECTION_TRC (TIM_CCMR1_CC1S) /*!< TIM Input 1, 2, 3 or 4 is selected to be connected to TRC */ /** * @} */ /** @defgroup TIM_Input_Capture_Prescaler TIM Input Capture Prescaler * @{ */ #define TIM_ICPSC_DIV1 ((uint32_t)0x0000) /*!< Capture performed each time an edge is detected on the capture input */ #define TIM_ICPSC_DIV2 (TIM_CCMR1_IC1PSC_0) /*!< Capture performed once every 2 events */ #define TIM_ICPSC_DIV4 (TIM_CCMR1_IC1PSC_1) /*!< Capture performed once every 4 events */ #define TIM_ICPSC_DIV8 (TIM_CCMR1_IC1PSC) /*!< Capture performed once every 8 events */ /** * @} */ /** @defgroup TIM_One_Pulse_Mode TIM One Pulse Mode * @{ */ #define TIM_OPMODE_SINGLE (TIM_CR1_OPM) #define TIM_OPMODE_REPETITIVE ((uint32_t)0x0000) /** * @} */ /** @defgroup TIM_Encoder_Mode TIM Encoder Mode * @{ */ #define TIM_ENCODERMODE_TI1 (TIM_SMCR_SMS_0) #define TIM_ENCODERMODE_TI2 (TIM_SMCR_SMS_1) #define TIM_ENCODERMODE_TI12 (TIM_SMCR_SMS_1 | TIM_SMCR_SMS_0) /** * @} */ /** @defgroup TIM_Interrupt_definition TIM Interrupt definition * @{ */ #define TIM_IT_UPDATE (TIM_DIER_UIE) #define TIM_IT_CC1 (TIM_DIER_CC1IE) #define TIM_IT_CC2 (TIM_DIER_CC2IE) #define TIM_IT_CC3 (TIM_DIER_CC3IE) #define TIM_IT_CC4 (TIM_DIER_CC4IE) #define TIM_IT_COM (TIM_DIER_COMIE) #define TIM_IT_TRIGGER (TIM_DIER_TIE) #define TIM_IT_BREAK (TIM_DIER_BIE) /** * @} */ /** @defgroup TIM_Commutation_Source TIM Commutation Source * @{ */ #define TIM_COMMUTATION_TRGI (TIM_CR2_CCUS) #define TIM_COMMUTATION_SOFTWARE ((uint32_t)0x0000) /** * @} */ /** @defgroup TIM_DMA_sources TIM DMA sources * @{ */ #define TIM_DMA_UPDATE (TIM_DIER_UDE) #define TIM_DMA_CC1 (TIM_DIER_CC1DE) #define TIM_DMA_CC2 (TIM_DIER_CC2DE) #define TIM_DMA_CC3 (TIM_DIER_CC3DE) #define TIM_DMA_CC4 (TIM_DIER_CC4DE) #define TIM_DMA_COM (TIM_DIER_COMDE) #define TIM_DMA_TRIGGER (TIM_DIER_TDE) /** * @} */ /** @defgroup TIM_Event_Source TIM Event Source * @{ */ #define TIM_EVENTSOURCE_UPDATE TIM_EGR_UG #define TIM_EVENTSOURCE_CC1 TIM_EGR_CC1G #define TIM_EVENTSOURCE_CC2 TIM_EGR_CC2G #define TIM_EVENTSOURCE_CC3 TIM_EGR_CC3G #define TIM_EVENTSOURCE_CC4 TIM_EGR_CC4G #define TIM_EVENTSOURCE_COM TIM_EGR_COMG #define TIM_EVENTSOURCE_TRIGGER TIM_EGR_TG #define TIM_EVENTSOURCE_BREAK TIM_EGR_BG /** * @} */ /** @defgroup TIM_Flag_definition TIM Flag definition * @{ */ #define TIM_FLAG_UPDATE (TIM_SR_UIF) #define TIM_FLAG_CC1 (TIM_SR_CC1IF) #define TIM_FLAG_CC2 (TIM_SR_CC2IF) #define TIM_FLAG_CC3 (TIM_SR_CC3IF) #define TIM_FLAG_CC4 (TIM_SR_CC4IF) #define TIM_FLAG_COM (TIM_SR_COMIF) #define TIM_FLAG_TRIGGER (TIM_SR_TIF) #define TIM_FLAG_BREAK (TIM_SR_BIF) #define TIM_FLAG_CC1OF (TIM_SR_CC1OF) #define TIM_FLAG_CC2OF (TIM_SR_CC2OF) #define TIM_FLAG_CC3OF (TIM_SR_CC3OF) #define TIM_FLAG_CC4OF (TIM_SR_CC4OF) /** * @} */ /** @defgroup TIM_Clock_Source TIM Clock Source * @{ */ #define TIM_CLOCKSOURCE_ETRMODE2 (TIM_SMCR_ETPS_1) #define TIM_CLOCKSOURCE_INTERNAL (TIM_SMCR_ETPS_0) #define TIM_CLOCKSOURCE_ITR0 ((uint32_t)0x0000) #define TIM_CLOCKSOURCE_ITR1 (TIM_SMCR_TS_0) #define TIM_CLOCKSOURCE_ITR2 (TIM_SMCR_TS_1) #define TIM_CLOCKSOURCE_ITR3 (TIM_SMCR_TS_0 | TIM_SMCR_TS_1) #define TIM_CLOCKSOURCE_TI1ED (TIM_SMCR_TS_2) #define TIM_CLOCKSOURCE_TI1 (TIM_SMCR_TS_0 | TIM_SMCR_TS_2) #define TIM_CLOCKSOURCE_TI2 (TIM_SMCR_TS_1 | TIM_SMCR_TS_2) #define TIM_CLOCKSOURCE_ETRMODE1 (TIM_SMCR_TS) /** * @} */ /** @defgroup TIM_Clock_Polarity TIM Clock Polarity * @{ */ #define TIM_CLOCKPOLARITY_INVERTED TIM_ETRPOLARITY_INVERTED /*!< Polarity for ETRx clock sources */ #define TIM_CLOCKPOLARITY_NONINVERTED TIM_ETRPOLARITY_NONINVERTED /*!< Polarity for ETRx clock sources */ #define TIM_CLOCKPOLARITY_RISING TIM_INPUTCHANNELPOLARITY_RISING /*!< Polarity for TIx clock sources */ #define TIM_CLOCKPOLARITY_FALLING TIM_INPUTCHANNELPOLARITY_FALLING /*!< Polarity for TIx clock sources */ #define TIM_CLOCKPOLARITY_BOTHEDGE TIM_INPUTCHANNELPOLARITY_BOTHEDGE /*!< Polarity for TIx clock sources */ /** * @} */ /** @defgroup TIM_Clock_Prescaler TIM Clock Prescaler * @{ */ #define TIM_CLOCKPRESCALER_DIV1 TIM_ETRPRESCALER_DIV1 /*!< No prescaler is used */ #define TIM_CLOCKPRESCALER_DIV2 TIM_ETRPRESCALER_DIV2 /*!< Prescaler for External ETR Clock: Capture performed once every 2 events. */ #define TIM_CLOCKPRESCALER_DIV4 TIM_ETRPRESCALER_DIV4 /*!< Prescaler for External ETR Clock: Capture performed once every 4 events. */ #define TIM_CLOCKPRESCALER_DIV8 TIM_ETRPRESCALER_DIV8 /*!< Prescaler for External ETR Clock: Capture performed once every 8 events. */ /** * @} */ /** @defgroup TIM_ClearInput_Source TIM Clear Input Source * @{ */ #define TIM_CLEARINPUTSOURCE_ETR ((uint32_t)0x0001) #define TIM_CLEARINPUTSOURCE_NONE ((uint32_t)0x0000) /** * @} */ /** @defgroup TIM_ClearInput_Polarity TIM Clear Input Polarity * @{ */ #define TIM_CLEARINPUTPOLARITY_INVERTED TIM_ETRPOLARITY_INVERTED /*!< Polarity for ETRx pin */ #define TIM_CLEARINPUTPOLARITY_NONINVERTED TIM_ETRPOLARITY_NONINVERTED /*!< Polarity for ETRx pin */ /** * @} */ /** @defgroup TIM_ClearInput_Prescaler TIM Clear Input Prescaler * @{ */ #define TIM_CLEARINPUTPRESCALER_DIV1 TIM_ETRPRESCALER_DIV1 /*!< No prescaler is used */ #define TIM_CLEARINPUTPRESCALER_DIV2 TIM_ETRPRESCALER_DIV2 /*!< Prescaler for External ETR pin: Capture performed once every 2 events. */ #define TIM_CLEARINPUTPRESCALER_DIV4 TIM_ETRPRESCALER_DIV4 /*!< Prescaler for External ETR pin: Capture performed once every 4 events. */ #define TIM_CLEARINPUTPRESCALER_DIV8 TIM_ETRPRESCALER_DIV8 /*!< Prescaler for External ETR pin: Capture performed once every 8 events. */ /** * @} */ /** @defgroup TIM_OSSR_Off_State_Selection_for_Run_mode_state TIM OSSR OffState Selection for Run mode state * @{ */ #define TIM_OSSR_ENABLE (TIM_BDTR_OSSR) #define TIM_OSSR_DISABLE ((uint32_t)0x0000) /** * @} */ /** @defgroup TIM_OSSI_Off_State_Selection_for_Idle_mode_state TIM OSSI OffState Selection for Idle mode state * @{ */ #define TIM_OSSI_ENABLE (TIM_BDTR_OSSI) #define TIM_OSSI_DISABLE ((uint32_t)0x0000) /** * @} */ /** @defgroup TIM_Lock_level TIM Lock level * @{ */ #define TIM_LOCKLEVEL_OFF ((uint32_t)0x0000) #define TIM_LOCKLEVEL_1 (TIM_BDTR_LOCK_0) #define TIM_LOCKLEVEL_2 (TIM_BDTR_LOCK_1) #define TIM_LOCKLEVEL_3 (TIM_BDTR_LOCK) /** * @} */ /** @defgroup TIM_Break_Input_enable_disable TIM Break Input State * @{ */ #define TIM_BREAK_ENABLE (TIM_BDTR_BKE) #define TIM_BREAK_DISABLE ((uint32_t)0x0000) /** * @} */ /** @defgroup TIM_Break_Polarity TIM Break Polarity * @{ */ #define TIM_BREAKPOLARITY_LOW ((uint32_t)0x0000) #define TIM_BREAKPOLARITY_HIGH (TIM_BDTR_BKP) /** * @} */ /** @defgroup TIM_AOE_Bit_Set_Reset TIM AOE Bit State * @{ */ #define TIM_AUTOMATICOUTPUT_ENABLE (TIM_BDTR_AOE) #define TIM_AUTOMATICOUTPUT_DISABLE ((uint32_t)0x0000) /** * @} */ /** @defgroup TIM_Master_Mode_Selection TIM Master Mode Selection * @{ */ #define TIM_TRGO_RESET ((uint32_t)0x0000) #define TIM_TRGO_ENABLE (TIM_CR2_MMS_0) #define TIM_TRGO_UPDATE (TIM_CR2_MMS_1) #define TIM_TRGO_OC1 ((TIM_CR2_MMS_1 | TIM_CR2_MMS_0)) #define TIM_TRGO_OC1REF (TIM_CR2_MMS_2) #define TIM_TRGO_OC2REF ((TIM_CR2_MMS_2 | TIM_CR2_MMS_0)) #define TIM_TRGO_OC3REF ((TIM_CR2_MMS_2 | TIM_CR2_MMS_1)) #define TIM_TRGO_OC4REF ((TIM_CR2_MMS_2 | TIM_CR2_MMS_1 | TIM_CR2_MMS_0)) /** * @} */ /** @defgroup TIM_Slave_Mode TIM Slave Mode * @{ */ #define TIM_SLAVEMODE_DISABLE ((uint32_t)0x0000) #define TIM_SLAVEMODE_RESET ((uint32_t)0x0004) #define TIM_SLAVEMODE_GATED ((uint32_t)0x0005) #define TIM_SLAVEMODE_TRIGGER ((uint32_t)0x0006) #define TIM_SLAVEMODE_EXTERNAL1 ((uint32_t)0x0007) /** * @} */ /** @defgroup TIM_Master_Slave_Mode TIM Master Slave Mode * @{ */ #define TIM_MASTERSLAVEMODE_ENABLE ((uint32_t)0x0080) #define TIM_MASTERSLAVEMODE_DISABLE ((uint32_t)0x0000) /** * @} */ /** @defgroup TIM_Trigger_Selection TIM Trigger Selection * @{ */ #define TIM_TS_ITR0 ((uint32_t)0x0000) #define TIM_TS_ITR1 ((uint32_t)0x0010) #define TIM_TS_ITR2 ((uint32_t)0x0020) #define TIM_TS_ITR3 ((uint32_t)0x0030) #define TIM_TS_TI1F_ED ((uint32_t)0x0040) #define TIM_TS_TI1FP1 ((uint32_t)0x0050) #define TIM_TS_TI2FP2 ((uint32_t)0x0060) #define TIM_TS_ETRF ((uint32_t)0x0070) #define TIM_TS_NONE ((uint32_t)0xFFFF) /** * @} */ /** @defgroup TIM_Trigger_Polarity TIM Trigger Polarity * @{ */ #define TIM_TRIGGERPOLARITY_INVERTED TIM_ETRPOLARITY_INVERTED /*!< Polarity for ETRx trigger sources */ #define TIM_TRIGGERPOLARITY_NONINVERTED TIM_ETRPOLARITY_NONINVERTED /*!< Polarity for ETRx trigger sources */ #define TIM_TRIGGERPOLARITY_RISING TIM_INPUTCHANNELPOLARITY_RISING /*!< Polarity for TIxFPx or TI1_ED trigger sources */ #define TIM_TRIGGERPOLARITY_FALLING TIM_INPUTCHANNELPOLARITY_FALLING /*!< Polarity for TIxFPx or TI1_ED trigger sources */ #define TIM_TRIGGERPOLARITY_BOTHEDGE TIM_INPUTCHANNELPOLARITY_BOTHEDGE /*!< Polarity for TIxFPx or TI1_ED trigger sources */ /** * @} */ /** @defgroup TIM_Trigger_Prescaler TIM Trigger Prescaler * @{ */ #define TIM_TRIGGERPRESCALER_DIV1 TIM_ETRPRESCALER_DIV1 /*!< No prescaler is used */ #define TIM_TRIGGERPRESCALER_DIV2 TIM_ETRPRESCALER_DIV2 /*!< Prescaler for External ETR Trigger: Capture performed once every 2 events. */ #define TIM_TRIGGERPRESCALER_DIV4 TIM_ETRPRESCALER_DIV4 /*!< Prescaler for External ETR Trigger: Capture performed once every 4 events. */ #define TIM_TRIGGERPRESCALER_DIV8 TIM_ETRPRESCALER_DIV8 /*!< Prescaler for External ETR Trigger: Capture performed once every 8 events. */ /** * @} */ /** @defgroup TIM_TI1_Selection TIM TI1 Selection * @{ */ #define TIM_TI1SELECTION_CH1 ((uint32_t)0x0000) #define TIM_TI1SELECTION_XORCOMBINATION (TIM_CR2_TI1S) /** * @} */ /** @defgroup TIM_DMA_Base_address TIM DMA Base address * @{ */ #define TIM_DMABASE_CR1 (0x00000000) #define TIM_DMABASE_CR2 (0x00000001) #define TIM_DMABASE_SMCR (0x00000002) #define TIM_DMABASE_DIER (0x00000003) #define TIM_DMABASE_SR (0x00000004) #define TIM_DMABASE_EGR (0x00000005) #define TIM_DMABASE_CCMR1 (0x00000006) #define TIM_DMABASE_CCMR2 (0x00000007) #define TIM_DMABASE_CCER (0x00000008) #define TIM_DMABASE_CNT (0x00000009) #define TIM_DMABASE_PSC (0x0000000A) #define TIM_DMABASE_ARR (0x0000000B) #define TIM_DMABASE_RCR (0x0000000C) #define TIM_DMABASE_CCR1 (0x0000000D) #define TIM_DMABASE_CCR2 (0x0000000E) #define TIM_DMABASE_CCR3 (0x0000000F) #define TIM_DMABASE_CCR4 (0x00000010) #define TIM_DMABASE_BDTR (0x00000011) #define TIM_DMABASE_DCR (0x00000012) #define TIM_DMABASE_OR (0x00000013) /** * @} */ /** @defgroup TIM_DMA_Burst_Length TIM DMA Burst Length * @{ */ #define TIM_DMABURSTLENGTH_1TRANSFER (0x00000000) #define TIM_DMABURSTLENGTH_2TRANSFERS (0x00000100) #define TIM_DMABURSTLENGTH_3TRANSFERS (0x00000200) #define TIM_DMABURSTLENGTH_4TRANSFERS (0x00000300) #define TIM_DMABURSTLENGTH_5TRANSFERS (0x00000400) #define TIM_DMABURSTLENGTH_6TRANSFERS (0x00000500) #define TIM_DMABURSTLENGTH_7TRANSFERS (0x00000600) #define TIM_DMABURSTLENGTH_8TRANSFERS (0x00000700) #define TIM_DMABURSTLENGTH_9TRANSFERS (0x00000800) #define TIM_DMABURSTLENGTH_10TRANSFERS (0x00000900) #define TIM_DMABURSTLENGTH_11TRANSFERS (0x00000A00) #define TIM_DMABURSTLENGTH_12TRANSFERS (0x00000B00) #define TIM_DMABURSTLENGTH_13TRANSFERS (0x00000C00) #define TIM_DMABURSTLENGTH_14TRANSFERS (0x00000D00) #define TIM_DMABURSTLENGTH_15TRANSFERS (0x00000E00) #define TIM_DMABURSTLENGTH_16TRANSFERS (0x00000F00) #define TIM_DMABURSTLENGTH_17TRANSFERS (0x00001000) #define TIM_DMABURSTLENGTH_18TRANSFERS (0x00001100) /** * @} */ /** @defgroup DMA_Handle_index DMA Handle index * @{ */ #define TIM_DMA_ID_UPDATE ((uint16_t) 0x0) /*!< Index of the DMA handle used for Update DMA requests */ #define TIM_DMA_ID_CC1 ((uint16_t) 0x1) /*!< Index of the DMA handle used for Capture/Compare 1 DMA requests */ #define TIM_DMA_ID_CC2 ((uint16_t) 0x2) /*!< Index of the DMA handle used for Capture/Compare 2 DMA requests */ #define TIM_DMA_ID_CC3 ((uint16_t) 0x3) /*!< Index of the DMA handle used for Capture/Compare 3 DMA requests */ #define TIM_DMA_ID_CC4 ((uint16_t) 0x4) /*!< Index of the DMA handle used for Capture/Compare 4 DMA requests */ #define TIM_DMA_ID_COMMUTATION ((uint16_t) 0x5) /*!< Index of the DMA handle used for Commutation DMA requests */ #define TIM_DMA_ID_TRIGGER ((uint16_t) 0x6) /*!< Index of the DMA handle used for Trigger DMA requests */ /** * @} */ /** @defgroup Channel_CC_State Channel CC State * @{ */ #define TIM_CCx_ENABLE ((uint32_t)0x0001) #define TIM_CCx_DISABLE ((uint32_t)0x0000) #define TIM_CCxN_ENABLE ((uint32_t)0x0004) #define TIM_CCxN_DISABLE ((uint32_t)0x0000) /** * @} */ /** * @} */ /* Exported macro ------------------------------------------------------------*/ /** @defgroup TIM_Exported_Macros TIM Exported Macros * @{ */ /** @brief Reset TIM handle state * @param __HANDLE__: TIM handle * @retval None */ #define __HAL_TIM_RESET_HANDLE_STATE(__HANDLE__) ((__HANDLE__)->State = HAL_TIM_STATE_RESET) /** * @brief Enable the TIM peripheral. * @param __HANDLE__: TIM handle * @retval None */ #define __HAL_TIM_ENABLE(__HANDLE__) ((__HANDLE__)->Instance->CR1|=(TIM_CR1_CEN)) /** * @brief Enable the TIM main Output. * @param __HANDLE__: TIM handle * @retval None */ #define __HAL_TIM_MOE_ENABLE(__HANDLE__) ((__HANDLE__)->Instance->BDTR|=(TIM_BDTR_MOE)) /** * @brief Disable the TIM peripheral. * @param __HANDLE__: TIM handle * @retval None */ #define __HAL_TIM_DISABLE(__HANDLE__) \ do { \ if (((__HANDLE__)->Instance->CCER & TIM_CCER_CCxE_MASK) == 0) \ { \ if(((__HANDLE__)->Instance->CCER & TIM_CCER_CCxNE_MASK) == 0) \ { \ (__HANDLE__)->Instance->CR1 &= ~(TIM_CR1_CEN); \ } \ } \ } while(0) /* The Main Output of a timer instance is disabled only if all the CCx and CCxN channels have been disabled */ /** * @brief Disable the TIM main Output. * @param __HANDLE__: TIM handle * @retval None */ #define __HAL_TIM_MOE_DISABLE(__HANDLE__) \ do { \ if (((__HANDLE__)->Instance->CCER & TIM_CCER_CCxE_MASK) == 0) \ { \ if(((__HANDLE__)->Instance->CCER & TIM_CCER_CCxNE_MASK) == 0) \ { \ (__HANDLE__)->Instance->BDTR &= ~(TIM_BDTR_MOE); \ } \ } \ } while(0) #define __HAL_TIM_ENABLE_IT(__HANDLE__, __INTERRUPT__) ((__HANDLE__)->Instance->DIER |= (__INTERRUPT__)) #define __HAL_TIM_ENABLE_DMA(__HANDLE__, __DMA__) ((__HANDLE__)->Instance->DIER |= (__DMA__)) #define __HAL_TIM_DISABLE_IT(__HANDLE__, __INTERRUPT__) ((__HANDLE__)->Instance->DIER &= ~(__INTERRUPT__)) #define __HAL_TIM_DISABLE_DMA(__HANDLE__, __DMA__) ((__HANDLE__)->Instance->DIER &= ~(__DMA__)) #define __HAL_TIM_GET_FLAG(__HANDLE__, __FLAG__) (((__HANDLE__)->Instance->SR &(__FLAG__)) == (__FLAG__)) #define __HAL_TIM_CLEAR_FLAG(__HANDLE__, __FLAG__) ((__HANDLE__)->Instance->SR = ~(__FLAG__)) #define __HAL_TIM_GET_IT_SOURCE(__HANDLE__, __INTERRUPT__) ((((__HANDLE__)->Instance->DIER & (__INTERRUPT__)) == (__INTERRUPT__)) ? SET : RESET) #define __HAL_TIM_CLEAR_IT(__HANDLE__, __INTERRUPT__) ((__HANDLE__)->Instance->SR = ~(__INTERRUPT__)) #define __HAL_TIM_IS_TIM_COUNTING_DOWN(__HANDLE__) (((__HANDLE__)->Instance->CR1 &(TIM_CR1_DIR)) == (TIM_CR1_DIR)) #define __HAL_TIM_SET_PRESCALER(__HANDLE__, __PRESC__) ((__HANDLE__)->Instance->PSC = (__PRESC__)) #define TIM_SET_ICPRESCALERVALUE(__HANDLE__, __CHANNEL__, __ICPSC__) \ (((__CHANNEL__) == TIM_CHANNEL_1) ? ((__HANDLE__)->Instance->CCMR1 |= (__ICPSC__)) :\ ((__CHANNEL__) == TIM_CHANNEL_2) ? ((__HANDLE__)->Instance->CCMR1 |= ((__ICPSC__) << 8)) :\ ((__CHANNEL__) == TIM_CHANNEL_3) ? ((__HANDLE__)->Instance->CCMR2 |= (__ICPSC__)) :\ ((__HANDLE__)->Instance->CCMR2 |= ((__ICPSC__) << 8))) #define TIM_RESET_ICPRESCALERVALUE(__HANDLE__, __CHANNEL__) \ (((__CHANNEL__) == TIM_CHANNEL_1) ? ((__HANDLE__)->Instance->CCMR1 &= (uint16_t)~TIM_CCMR1_IC1PSC) :\ ((__CHANNEL__) == TIM_CHANNEL_2) ? ((__HANDLE__)->Instance->CCMR1 &= (uint16_t)~TIM_CCMR1_IC2PSC) :\ ((__CHANNEL__) == TIM_CHANNEL_3) ? ((__HANDLE__)->Instance->CCMR2 &= (uint16_t)~TIM_CCMR2_IC3PSC) :\ ((__HANDLE__)->Instance->CCMR2 &= (uint16_t)~TIM_CCMR2_IC4PSC)) #define TIM_SET_CAPTUREPOLARITY(__HANDLE__, __CHANNEL__, __POLARITY__) \ (((__CHANNEL__) == TIM_CHANNEL_1) ? ((__HANDLE__)->Instance->CCER |= (__POLARITY__)) :\ ((__CHANNEL__) == TIM_CHANNEL_2) ? ((__HANDLE__)->Instance->CCER |= ((__POLARITY__) << 4)) :\ ((__CHANNEL__) == TIM_CHANNEL_3) ? ((__HANDLE__)->Instance->CCER |= ((__POLARITY__) << 8)) :\ ((__HANDLE__)->Instance->CCER |= (((__POLARITY__) << 12) & TIM_CCER_CC4P))) #define TIM_RESET_CAPTUREPOLARITY(__HANDLE__, __CHANNEL__) \ (((__CHANNEL__) == TIM_CHANNEL_1) ? ((__HANDLE__)->Instance->CCER &= (uint16_t)~(TIM_CCER_CC1P | TIM_CCER_CC1NP)) :\ ((__CHANNEL__) == TIM_CHANNEL_2) ? ((__HANDLE__)->Instance->CCER &= (uint16_t)~(TIM_CCER_CC2P | TIM_CCER_CC2NP)) :\ ((__CHANNEL__) == TIM_CHANNEL_3) ? ((__HANDLE__)->Instance->CCER &= (uint16_t)~(TIM_CCER_CC3P | TIM_CCER_CC3NP)) :\ ((__HANDLE__)->Instance->CCER &= (uint16_t)~TIM_CCER_CC4P)) /** * @brief Sets the TIM Capture Compare Register value on runtime without * calling another time ConfigChannel function. * @param __HANDLE__: TIM handle. * @param __CHANNEL__ : TIM Channels to be configured. * This parameter can be one of the following values: * @arg TIM_CHANNEL_1: TIM Channel 1 selected * @arg TIM_CHANNEL_2: TIM Channel 2 selected * @arg TIM_CHANNEL_3: TIM Channel 3 selected * @arg TIM_CHANNEL_4: TIM Channel 4 selected * @param __COMPARE__: specifies the Capture Compare register new value. * @retval None */ #define __HAL_TIM_SET_COMPARE(__HANDLE__, __CHANNEL__, __COMPARE__) \ (*(__IO uint32_t *)(&((__HANDLE__)->Instance->CCR1) + ((__CHANNEL__) >> 2)) = (__COMPARE__)) /** * @brief Gets the TIM Capture Compare Register value on runtime * @param __HANDLE__: TIM handle. * @param __CHANNEL__ : TIM Channel associated with the capture compare register * This parameter can be one of the following values: * @arg TIM_CHANNEL_1: get capture/compare 1 register value * @arg TIM_CHANNEL_2: get capture/compare 2 register value * @arg TIM_CHANNEL_3: get capture/compare 3 register value * @arg TIM_CHANNEL_4: get capture/compare 4 register value * @retval None */ #define __HAL_TIM_GET_COMPARE(__HANDLE__, __CHANNEL__) \ (*(__IO uint32_t *)(&((__HANDLE__)->Instance->CCR1) + ((__CHANNEL__) >> 2))) /** * @brief Sets the TIM Counter Register value on runtime. * @param __HANDLE__: TIM handle. * @param __COUNTER__: specifies the Counter register new value. * @retval None */ #define __HAL_TIM_SET_COUNTER(__HANDLE__, __COUNTER__) ((__HANDLE__)->Instance->CNT = (__COUNTER__)) /** * @brief Gets the TIM Counter Register value on runtime. * @param __HANDLE__: TIM handle. * @retval None */ #define __HAL_TIM_GET_COUNTER(__HANDLE__) ((__HANDLE__)->Instance->CNT) /** * @brief Sets the TIM Autoreload Register value on runtime without calling * another time any Init function. * @param __HANDLE__: TIM handle. * @param __AUTORELOAD__: specifies the Counter register new value. * @retval None */ #define __HAL_TIM_SET_AUTORELOAD(__HANDLE__, __AUTORELOAD__) \ do{ \ (__HANDLE__)->Instance->ARR = (__AUTORELOAD__); \ (__HANDLE__)->Init.Period = (__AUTORELOAD__); \ } while(0) /** * @brief Gets the TIM Autoreload Register value on runtime * @param __HANDLE__: TIM handle. * @retval None */ #define __HAL_TIM_GET_AUTORELOAD(__HANDLE__) ((__HANDLE__)->Instance->ARR) /** * @brief Sets the TIM Clock Division value on runtime without calling * another time any Init function. * @param __HANDLE__: TIM handle. * @param __CKD__: specifies the clock division value. * This parameter can be one of the following value: * @arg TIM_CLOCKDIVISION_DIV1 * @arg TIM_CLOCKDIVISION_DIV2 * @arg TIM_CLOCKDIVISION_DIV4 * @retval None */ #define __HAL_TIM_SET_CLOCKDIVISION(__HANDLE__, __CKD__) \ do{ \ (__HANDLE__)->Instance->CR1 &= (uint16_t)(~TIM_CR1_CKD); \ (__HANDLE__)->Instance->CR1 |= (__CKD__); \ (__HANDLE__)->Init.ClockDivision = (__CKD__); \ } while(0) /** * @brief Gets the TIM Clock Division value on runtime * @param __HANDLE__: TIM handle. * @retval None */ #define __HAL_TIM_GET_CLOCKDIVISION(__HANDLE__) ((__HANDLE__)->Instance->CR1 & TIM_CR1_CKD) /** * @brief Sets the TIM Input Capture prescaler on runtime without calling * another time HAL_TIM_IC_ConfigChannel() function. * @param __HANDLE__: TIM handle. * @param __CHANNEL__ : TIM Channels to be configured. * This parameter can be one of the following values: * @arg TIM_CHANNEL_1: TIM Channel 1 selected * @arg TIM_CHANNEL_2: TIM Channel 2 selected * @arg TIM_CHANNEL_3: TIM Channel 3 selected * @arg TIM_CHANNEL_4: TIM Channel 4 selected * @param __ICPSC__: specifies the Input Capture4 prescaler new value. * This parameter can be one of the following values: * @arg TIM_ICPSC_DIV1: no prescaler * @arg TIM_ICPSC_DIV2: capture is done once every 2 events * @arg TIM_ICPSC_DIV4: capture is done once every 4 events * @arg TIM_ICPSC_DIV8: capture is done once every 8 events * @retval None */ #define __HAL_TIM_SET_ICPRESCALER(__HANDLE__, __CHANNEL__, __ICPSC__) \ do{ \ TIM_RESET_ICPRESCALERVALUE((__HANDLE__), (__CHANNEL__)); \ TIM_SET_ICPRESCALERVALUE((__HANDLE__), (__CHANNEL__), (__ICPSC__)); \ } while(0) /** * @brief Gets the TIM Input Capture prescaler on runtime * @param __HANDLE__: TIM handle. * @param __CHANNEL__ : TIM Channels to be configured. * This parameter can be one of the following values: * @arg TIM_CHANNEL_1: get input capture 1 prescaler value * @arg TIM_CHANNEL_2: get input capture 2 prescaler value * @arg TIM_CHANNEL_3: get input capture 3 prescaler value * @arg TIM_CHANNEL_4: get input capture 4 prescaler value * @retval None */ #define __HAL_TIM_GET_ICPRESCALER(__HANDLE__, __CHANNEL__) \ (((__CHANNEL__) == TIM_CHANNEL_1) ? ((__HANDLE__)->Instance->CCMR1 & TIM_CCMR1_IC1PSC) :\ ((__CHANNEL__) == TIM_CHANNEL_2) ? (((__HANDLE__)->Instance->CCMR1 & TIM_CCMR1_IC2PSC) >> 8) :\ ((__CHANNEL__) == TIM_CHANNEL_3) ? ((__HANDLE__)->Instance->CCMR2 & TIM_CCMR2_IC3PSC) :\ (((__HANDLE__)->Instance->CCMR2 & TIM_CCMR2_IC4PSC)) >> 8) /** * @brief Set the Update Request Source (URS) bit of the TIMx_CR1 register * @param __HANDLE__: TIM handle. * @note When the USR bit of the TIMx_CR1 register is set, only counter * overflow/underflow generates an update interrupt or DMA request (if * enabled) * @retval None */ #define __HAL_TIM_URS_ENABLE(__HANDLE__) \ ((__HANDLE__)->Instance->CR1|= (TIM_CR1_URS)) /** * @brief Reset the Update Request Source (URS) bit of the TIMx_CR1 register * @param __HANDLE__: TIM handle. * @note When the USR bit of the TIMx_CR1 register is reset, any of the * following events generate an update interrupt or DMA request (if * enabled): * Counter overflow/underflow * Setting the UG bit * Update generation through the slave mode controller * @retval None */ #define __HAL_TIM_URS_DISABLE(__HANDLE__) \ ((__HANDLE__)->Instance->CR1&=~(TIM_CR1_URS)) /** * @brief Sets the TIM Capture x input polarity on runtime. * @param __HANDLE__: TIM handle. * @param __CHANNEL__: TIM Channels to be configured. * This parameter can be one of the following values: * @arg TIM_CHANNEL_1: TIM Channel 1 selected * @arg TIM_CHANNEL_2: TIM Channel 2 selected * @arg TIM_CHANNEL_3: TIM Channel 3 selected * @arg TIM_CHANNEL_4: TIM Channel 4 selected * @param __POLARITY__: Polarity for TIx source * @arg TIM_INPUTCHANNELPOLARITY_RISING: Rising Edge * @arg TIM_INPUTCHANNELPOLARITY_FALLING: Falling Edge * @arg TIM_INPUTCHANNELPOLARITY_BOTHEDGE: Rising and Falling Edge * @note The polarity TIM_INPUTCHANNELPOLARITY_BOTHEDGE is not authorized for TIM Channel 4. * @retval None */ #define __HAL_TIM_SET_CAPTUREPOLARITY(__HANDLE__, __CHANNEL__, __POLARITY__) \ do{ \ TIM_RESET_CAPTUREPOLARITY((__HANDLE__), (__CHANNEL__)); \ TIM_SET_CAPTUREPOLARITY((__HANDLE__), (__CHANNEL__), (__POLARITY__)); \ }while(0) /** * @} */ /* Include TIM HAL Extension module */ #include "stm32f4xx_hal_tim_ex.h" /* Exported functions --------------------------------------------------------*/ /** @addtogroup TIM_Exported_Functions * @{ */ /** @addtogroup TIM_Exported_Functions_Group1 * @{ */ /* Time Base functions ********************************************************/ HAL_StatusTypeDef HAL_TIM_Base_Init(TIM_HandleTypeDef *htim); HAL_StatusTypeDef HAL_TIM_Base_DeInit(TIM_HandleTypeDef *htim); void HAL_TIM_Base_MspInit(TIM_HandleTypeDef *htim); void HAL_TIM_Base_MspDeInit(TIM_HandleTypeDef *htim); /* Blocking mode: Polling */ HAL_StatusTypeDef HAL_TIM_Base_Start(TIM_HandleTypeDef *htim); HAL_StatusTypeDef HAL_TIM_Base_Stop(TIM_HandleTypeDef *htim); /* Non-Blocking mode: Interrupt */ HAL_StatusTypeDef HAL_TIM_Base_Start_IT(TIM_HandleTypeDef *htim); HAL_StatusTypeDef HAL_TIM_Base_Stop_IT(TIM_HandleTypeDef *htim); /* Non-Blocking mode: DMA */ HAL_StatusTypeDef HAL_TIM_Base_Start_DMA(TIM_HandleTypeDef *htim, uint32_t *pData, uint16_t Length); HAL_StatusTypeDef HAL_TIM_Base_Stop_DMA(TIM_HandleTypeDef *htim); /** * @} */ /** @addtogroup TIM_Exported_Functions_Group2 * @{ */ /* Timer Output Compare functions **********************************************/ HAL_StatusTypeDef HAL_TIM_OC_Init(TIM_HandleTypeDef *htim); HAL_StatusTypeDef HAL_TIM_OC_DeInit(TIM_HandleTypeDef *htim); void HAL_TIM_OC_MspInit(TIM_HandleTypeDef *htim); void HAL_TIM_OC_MspDeInit(TIM_HandleTypeDef *htim); /* Blocking mode: Polling */ HAL_StatusTypeDef HAL_TIM_OC_Start(TIM_HandleTypeDef *htim, uint32_t Channel); HAL_StatusTypeDef HAL_TIM_OC_Stop(TIM_HandleTypeDef *htim, uint32_t Channel); /* Non-Blocking mode: Interrupt */ HAL_StatusTypeDef HAL_TIM_OC_Start_IT(TIM_HandleTypeDef *htim, uint32_t Channel); HAL_StatusTypeDef HAL_TIM_OC_Stop_IT(TIM_HandleTypeDef *htim, uint32_t Channel); /* Non-Blocking mode: DMA */ HAL_StatusTypeDef HAL_TIM_OC_Start_DMA(TIM_HandleTypeDef *htim, uint32_t Channel, uint32_t *pData, uint16_t Length); HAL_StatusTypeDef HAL_TIM_OC_Stop_DMA(TIM_HandleTypeDef *htim, uint32_t Channel); /** * @} */ /** @addtogroup TIM_Exported_Functions_Group3 * @{ */ /* Timer PWM functions *********************************************************/ HAL_StatusTypeDef HAL_TIM_PWM_Init(TIM_HandleTypeDef *htim); HAL_StatusTypeDef HAL_TIM_PWM_DeInit(TIM_HandleTypeDef *htim); void HAL_TIM_PWM_MspInit(TIM_HandleTypeDef *htim); void HAL_TIM_PWM_MspDeInit(TIM_HandleTypeDef *htim); /* Blocking mode: Polling */ HAL_StatusTypeDef HAL_TIM_PWM_Start(TIM_HandleTypeDef *htim, uint32_t Channel); HAL_StatusTypeDef HAL_TIM_PWM_Stop(TIM_HandleTypeDef *htim, uint32_t Channel); /* Non-Blocking mode: Interrupt */ HAL_StatusTypeDef HAL_TIM_PWM_Start_IT(TIM_HandleTypeDef *htim, uint32_t Channel); HAL_StatusTypeDef HAL_TIM_PWM_Stop_IT(TIM_HandleTypeDef *htim, uint32_t Channel); /* Non-Blocking mode: DMA */ HAL_StatusTypeDef HAL_TIM_PWM_Start_DMA(TIM_HandleTypeDef *htim, uint32_t Channel, uint32_t *pData, uint16_t Length); HAL_StatusTypeDef HAL_TIM_PWM_Stop_DMA(TIM_HandleTypeDef *htim, uint32_t Channel); /** * @} */ /** @addtogroup TIM_Exported_Functions_Group4 * @{ */ /* Timer Input Capture functions ***********************************************/ HAL_StatusTypeDef HAL_TIM_IC_Init(TIM_HandleTypeDef *htim); HAL_StatusTypeDef HAL_TIM_IC_DeInit(TIM_HandleTypeDef *htim); void HAL_TIM_IC_MspInit(TIM_HandleTypeDef *htim); void HAL_TIM_IC_MspDeInit(TIM_HandleTypeDef *htim); /* Blocking mode: Polling */ HAL_StatusTypeDef HAL_TIM_IC_Start(TIM_HandleTypeDef *htim, uint32_t Channel); HAL_StatusTypeDef HAL_TIM_IC_Stop(TIM_HandleTypeDef *htim, uint32_t Channel); /* Non-Blocking mode: Interrupt */ HAL_StatusTypeDef HAL_TIM_IC_Start_IT(TIM_HandleTypeDef *htim, uint32_t Channel); HAL_StatusTypeDef HAL_TIM_IC_Stop_IT(TIM_HandleTypeDef *htim, uint32_t Channel); /* Non-Blocking mode: DMA */ HAL_StatusTypeDef HAL_TIM_IC_Start_DMA(TIM_HandleTypeDef *htim, uint32_t Channel, uint32_t *pData, uint16_t Length); HAL_StatusTypeDef HAL_TIM_IC_Stop_DMA(TIM_HandleTypeDef *htim, uint32_t Channel); /** * @} */ /** @addtogroup TIM_Exported_Functions_Group5 * @{ */ /* Timer One Pulse functions ***************************************************/ HAL_StatusTypeDef HAL_TIM_OnePulse_Init(TIM_HandleTypeDef *htim, uint32_t OnePulseMode); HAL_StatusTypeDef HAL_TIM_OnePulse_DeInit(TIM_HandleTypeDef *htim); void HAL_TIM_OnePulse_MspInit(TIM_HandleTypeDef *htim); void HAL_TIM_OnePulse_MspDeInit(TIM_HandleTypeDef *htim); /* Blocking mode: Polling */ HAL_StatusTypeDef HAL_TIM_OnePulse_Start(TIM_HandleTypeDef *htim, uint32_t OutputChannel); HAL_StatusTypeDef HAL_TIM_OnePulse_Stop(TIM_HandleTypeDef *htim, uint32_t OutputChannel); /* Non-Blocking mode: Interrupt */ HAL_StatusTypeDef HAL_TIM_OnePulse_Start_IT(TIM_HandleTypeDef *htim, uint32_t OutputChannel); HAL_StatusTypeDef HAL_TIM_OnePulse_Stop_IT(TIM_HandleTypeDef *htim, uint32_t OutputChannel); /** * @} */ /** @addtogroup TIM_Exported_Functions_Group6 * @{ */ /* Timer Encoder functions *****************************************************/ HAL_StatusTypeDef HAL_TIM_Encoder_Init(TIM_HandleTypeDef *htim, TIM_Encoder_InitTypeDef* sConfig); HAL_StatusTypeDef HAL_TIM_Encoder_DeInit(TIM_HandleTypeDef *htim); void HAL_TIM_Encoder_MspInit(TIM_HandleTypeDef *htim); void HAL_TIM_Encoder_MspDeInit(TIM_HandleTypeDef *htim); /* Blocking mode: Polling */ HAL_StatusTypeDef HAL_TIM_Encoder_Start(TIM_HandleTypeDef *htim, uint32_t Channel); HAL_StatusTypeDef HAL_TIM_Encoder_Stop(TIM_HandleTypeDef *htim, uint32_t Channel); /* Non-Blocking mode: Interrupt */ HAL_StatusTypeDef HAL_TIM_Encoder_Start_IT(TIM_HandleTypeDef *htim, uint32_t Channel); HAL_StatusTypeDef HAL_TIM_Encoder_Stop_IT(TIM_HandleTypeDef *htim, uint32_t Channel); /* Non-Blocking mode: DMA */ HAL_StatusTypeDef HAL_TIM_Encoder_Start_DMA(TIM_HandleTypeDef *htim, uint32_t Channel, uint32_t *pData1, uint32_t *pData2, uint16_t Length); HAL_StatusTypeDef HAL_TIM_Encoder_Stop_DMA(TIM_HandleTypeDef *htim, uint32_t Channel); /** * @} */ /** @addtogroup TIM_Exported_Functions_Group7 * @{ */ /* Interrupt Handler functions **********************************************/ void HAL_TIM_IRQHandler(TIM_HandleTypeDef *htim); /** * @} */ /** @addtogroup TIM_Exported_Functions_Group8 * @{ */ /* Control functions *********************************************************/ HAL_StatusTypeDef HAL_TIM_OC_ConfigChannel(TIM_HandleTypeDef *htim, TIM_OC_InitTypeDef* sConfig, uint32_t Channel); HAL_StatusTypeDef HAL_TIM_PWM_ConfigChannel(TIM_HandleTypeDef *htim, TIM_OC_InitTypeDef* sConfig, uint32_t Channel); HAL_StatusTypeDef HAL_TIM_IC_ConfigChannel(TIM_HandleTypeDef *htim, TIM_IC_InitTypeDef* sConfig, uint32_t Channel); HAL_StatusTypeDef HAL_TIM_OnePulse_ConfigChannel(TIM_HandleTypeDef *htim, TIM_OnePulse_InitTypeDef* sConfig, uint32_t OutputChannel, uint32_t InputChannel); HAL_StatusTypeDef HAL_TIM_ConfigOCrefClear(TIM_HandleTypeDef *htim, TIM_ClearInputConfigTypeDef * sClearInputConfig, uint32_t Channel); HAL_StatusTypeDef HAL_TIM_ConfigClockSource(TIM_HandleTypeDef *htim, TIM_ClockConfigTypeDef * sClockSourceConfig); HAL_StatusTypeDef HAL_TIM_ConfigTI1Input(TIM_HandleTypeDef *htim, uint32_t TI1_Selection); HAL_StatusTypeDef HAL_TIM_SlaveConfigSynchronization(TIM_HandleTypeDef *htim, TIM_SlaveConfigTypeDef * sSlaveConfig); HAL_StatusTypeDef HAL_TIM_SlaveConfigSynchronization_IT(TIM_HandleTypeDef *htim, TIM_SlaveConfigTypeDef * sSlaveConfig); HAL_StatusTypeDef HAL_TIM_DMABurst_WriteStart(TIM_HandleTypeDef *htim, uint32_t BurstBaseAddress, uint32_t BurstRequestSrc, \ uint32_t *BurstBuffer, uint32_t BurstLength); HAL_StatusTypeDef HAL_TIM_DMABurst_WriteStop(TIM_HandleTypeDef *htim, uint32_t BurstRequestSrc); HAL_StatusTypeDef HAL_TIM_DMABurst_ReadStart(TIM_HandleTypeDef *htim, uint32_t BurstBaseAddress, uint32_t BurstRequestSrc, \ uint32_t *BurstBuffer, uint32_t BurstLength); HAL_StatusTypeDef HAL_TIM_DMABurst_ReadStop(TIM_HandleTypeDef *htim, uint32_t BurstRequestSrc); HAL_StatusTypeDef HAL_TIM_GenerateEvent(TIM_HandleTypeDef *htim, uint32_t EventSource); uint32_t HAL_TIM_ReadCapturedValue(TIM_HandleTypeDef *htim, uint32_t Channel); /** * @} */ /** @addtogroup TIM_Exported_Functions_Group9 * @{ */ /* Callback in non blocking modes (Interrupt and DMA) *************************/ void HAL_TIM_PeriodElapsedCallback(TIM_HandleTypeDef *htim); void HAL_TIM_OC_DelayElapsedCallback(TIM_HandleTypeDef *htim); void HAL_TIM_IC_CaptureCallback(TIM_HandleTypeDef *htim); void HAL_TIM_PWM_PulseFinishedCallback(TIM_HandleTypeDef *htim); void HAL_TIM_TriggerCallback(TIM_HandleTypeDef *htim); void HAL_TIM_ErrorCallback(TIM_HandleTypeDef *htim); /** * @} */ /** @addtogroup TIM_Exported_Functions_Group10 * @{ */ /* Peripheral State functions **************************************************/ HAL_TIM_StateTypeDef HAL_TIM_Base_GetState(TIM_HandleTypeDef *htim); HAL_TIM_StateTypeDef HAL_TIM_OC_GetState(TIM_HandleTypeDef *htim); HAL_TIM_StateTypeDef HAL_TIM_PWM_GetState(TIM_HandleTypeDef *htim); HAL_TIM_StateTypeDef HAL_TIM_IC_GetState(TIM_HandleTypeDef *htim); HAL_TIM_StateTypeDef HAL_TIM_OnePulse_GetState(TIM_HandleTypeDef *htim); HAL_TIM_StateTypeDef HAL_TIM_Encoder_GetState(TIM_HandleTypeDef *htim); /** * @} */ /** * @} */ /* Private macros ------------------------------------------------------------*/ /** @defgroup TIM_Private_Macros TIM Private Macros * @{ */ /** @defgroup TIM_IS_TIM_Definitions TIM Private macros to check input parameters * @{ */ #define IS_TIM_COUNTER_MODE(MODE) (((MODE) == TIM_COUNTERMODE_UP) || \ ((MODE) == TIM_COUNTERMODE_DOWN) || \ ((MODE) == TIM_COUNTERMODE_CENTERALIGNED1) || \ ((MODE) == TIM_COUNTERMODE_CENTERALIGNED2) || \ ((MODE) == TIM_COUNTERMODE_CENTERALIGNED3)) #define IS_TIM_CLOCKDIVISION_DIV(DIV) (((DIV) == TIM_CLOCKDIVISION_DIV1) || \ ((DIV) == TIM_CLOCKDIVISION_DIV2) || \ ((DIV) == TIM_CLOCKDIVISION_DIV4)) #define IS_TIM_PWM_MODE(MODE) (((MODE) == TIM_OCMODE_PWM1) || \ ((MODE) == TIM_OCMODE_PWM2)) #define IS_TIM_OC_MODE(MODE) (((MODE) == TIM_OCMODE_TIMING) || \ ((MODE) == TIM_OCMODE_ACTIVE) || \ ((MODE) == TIM_OCMODE_INACTIVE) || \ ((MODE) == TIM_OCMODE_TOGGLE) || \ ((MODE) == TIM_OCMODE_FORCED_ACTIVE) || \ ((MODE) == TIM_OCMODE_FORCED_INACTIVE)) #define IS_TIM_FAST_STATE(STATE) (((STATE) == TIM_OCFAST_DISABLE) || \ ((STATE) == TIM_OCFAST_ENABLE)) #define IS_TIM_OC_POLARITY(POLARITY) (((POLARITY) == TIM_OCPOLARITY_HIGH) || \ ((POLARITY) == TIM_OCPOLARITY_LOW)) #define IS_TIM_OCN_POLARITY(POLARITY) (((POLARITY) == TIM_OCNPOLARITY_HIGH) || \ ((POLARITY) == TIM_OCNPOLARITY_LOW)) #define IS_TIM_OCIDLE_STATE(STATE) (((STATE) == TIM_OCIDLESTATE_SET) || \ ((STATE) == TIM_OCIDLESTATE_RESET)) #define IS_TIM_OCNIDLE_STATE(STATE) (((STATE) == TIM_OCNIDLESTATE_SET) || \ ((STATE) == TIM_OCNIDLESTATE_RESET)) #define IS_TIM_CHANNELS(CHANNEL) (((CHANNEL) == TIM_CHANNEL_1) || \ ((CHANNEL) == TIM_CHANNEL_2) || \ ((CHANNEL) == TIM_CHANNEL_3) || \ ((CHANNEL) == TIM_CHANNEL_4) || \ ((CHANNEL) == TIM_CHANNEL_ALL)) #define IS_TIM_OPM_CHANNELS(CHANNEL) (((CHANNEL) == TIM_CHANNEL_1) || \ ((CHANNEL) == TIM_CHANNEL_2)) #define IS_TIM_COMPLEMENTARY_CHANNELS(CHANNEL) (((CHANNEL) == TIM_CHANNEL_1) || \ ((CHANNEL) == TIM_CHANNEL_2) || \ ((CHANNEL) == TIM_CHANNEL_3)) #define IS_TIM_IC_POLARITY(POLARITY) (((POLARITY) == TIM_ICPOLARITY_RISING) || \ ((POLARITY) == TIM_ICPOLARITY_FALLING) || \ ((POLARITY) == TIM_ICPOLARITY_BOTHEDGE)) #define IS_TIM_IC_SELECTION(SELECTION) (((SELECTION) == TIM_ICSELECTION_DIRECTTI) || \ ((SELECTION) == TIM_ICSELECTION_INDIRECTTI) || \ ((SELECTION) == TIM_ICSELECTION_TRC)) #define IS_TIM_IC_PRESCALER(PRESCALER) (((PRESCALER) == TIM_ICPSC_DIV1) || \ ((PRESCALER) == TIM_ICPSC_DIV2) || \ ((PRESCALER) == TIM_ICPSC_DIV4) || \ ((PRESCALER) == TIM_ICPSC_DIV8)) #define IS_TIM_OPM_MODE(MODE) (((MODE) == TIM_OPMODE_SINGLE) || \ ((MODE) == TIM_OPMODE_REPETITIVE)) #define IS_TIM_DMA_SOURCE(SOURCE) ((((SOURCE) & 0xFFFF80FF) == 0x00000000) && ((SOURCE) != 0x00000000)) #define IS_TIM_ENCODER_MODE(MODE) (((MODE) == TIM_ENCODERMODE_TI1) || \ ((MODE) == TIM_ENCODERMODE_TI2) || \ ((MODE) == TIM_ENCODERMODE_TI12)) #define IS_TIM_EVENT_SOURCE(SOURCE) ((((SOURCE) & 0xFFFFFF00) == 0x00000000) && ((SOURCE) != 0x00000000)) #define IS_TIM_CLOCKSOURCE(CLOCK) (((CLOCK) == TIM_CLOCKSOURCE_INTERNAL) || \ ((CLOCK) == TIM_CLOCKSOURCE_ETRMODE2) || \ ((CLOCK) == TIM_CLOCKSOURCE_ITR0) || \ ((CLOCK) == TIM_CLOCKSOURCE_ITR1) || \ ((CLOCK) == TIM_CLOCKSOURCE_ITR2) || \ ((CLOCK) == TIM_CLOCKSOURCE_ITR3) || \ ((CLOCK) == TIM_CLOCKSOURCE_TI1ED) || \ ((CLOCK) == TIM_CLOCKSOURCE_TI1) || \ ((CLOCK) == TIM_CLOCKSOURCE_TI2) || \ ((CLOCK) == TIM_CLOCKSOURCE_ETRMODE1)) #define IS_TIM_CLOCKPOLARITY(POLARITY) (((POLARITY) == TIM_CLOCKPOLARITY_INVERTED) || \ ((POLARITY) == TIM_CLOCKPOLARITY_NONINVERTED) || \ ((POLARITY) == TIM_CLOCKPOLARITY_RISING) || \ ((POLARITY) == TIM_CLOCKPOLARITY_FALLING) || \ ((POLARITY) == TIM_CLOCKPOLARITY_BOTHEDGE)) #define IS_TIM_CLOCKPRESCALER(PRESCALER) (((PRESCALER) == TIM_CLOCKPRESCALER_DIV1) || \ ((PRESCALER) == TIM_CLOCKPRESCALER_DIV2) || \ ((PRESCALER) == TIM_CLOCKPRESCALER_DIV4) || \ ((PRESCALER) == TIM_CLOCKPRESCALER_DIV8)) #define IS_TIM_CLOCKFILTER(ICFILTER) ((ICFILTER) <= 0xF) #define IS_TIM_CLEARINPUT_SOURCE(SOURCE) (((SOURCE) == TIM_CLEARINPUTSOURCE_NONE) || \ ((SOURCE) == TIM_CLEARINPUTSOURCE_ETR)) #define IS_TIM_CLEARINPUT_POLARITY(POLARITY) (((POLARITY) == TIM_CLEARINPUTPOLARITY_INVERTED) || \ ((POLARITY) == TIM_CLEARINPUTPOLARITY_NONINVERTED)) #define IS_TIM_CLEARINPUT_PRESCALER(PRESCALER) (((PRESCALER) == TIM_CLEARINPUTPRESCALER_DIV1) || \ ((PRESCALER) == TIM_CLEARINPUTPRESCALER_DIV2) || \ ((PRESCALER) == TIM_CLEARINPUTPRESCALER_DIV4) || \ ((PRESCALER) == TIM_CLEARINPUTPRESCALER_DIV8)) #define IS_TIM_CLEARINPUT_FILTER(ICFILTER) ((ICFILTER) <= 0xF) #define IS_TIM_OSSR_STATE(STATE) (((STATE) == TIM_OSSR_ENABLE) || \ ((STATE) == TIM_OSSR_DISABLE)) #define IS_TIM_OSSI_STATE(STATE) (((STATE) == TIM_OSSI_ENABLE) || \ ((STATE) == TIM_OSSI_DISABLE)) #define IS_TIM_LOCK_LEVEL(LEVEL) (((LEVEL) == TIM_LOCKLEVEL_OFF) || \ ((LEVEL) == TIM_LOCKLEVEL_1) || \ ((LEVEL) == TIM_LOCKLEVEL_2) || \ ((LEVEL) == TIM_LOCKLEVEL_3)) #define IS_TIM_BREAK_STATE(STATE) (((STATE) == TIM_BREAK_ENABLE) || \ ((STATE) == TIM_BREAK_DISABLE)) #define IS_TIM_BREAK_POLARITY(POLARITY) (((POLARITY) == TIM_BREAKPOLARITY_LOW) || \ ((POLARITY) == TIM_BREAKPOLARITY_HIGH)) #define IS_TIM_AUTOMATIC_OUTPUT_STATE(STATE) (((STATE) == TIM_AUTOMATICOUTPUT_ENABLE) || \ ((STATE) == TIM_AUTOMATICOUTPUT_DISABLE)) #define IS_TIM_TRGO_SOURCE(SOURCE) (((SOURCE) == TIM_TRGO_RESET) || \ ((SOURCE) == TIM_TRGO_ENABLE) || \ ((SOURCE) == TIM_TRGO_UPDATE) || \ ((SOURCE) == TIM_TRGO_OC1) || \ ((SOURCE) == TIM_TRGO_OC1REF) || \ ((SOURCE) == TIM_TRGO_OC2REF) || \ ((SOURCE) == TIM_TRGO_OC3REF) || \ ((SOURCE) == TIM_TRGO_OC4REF)) #define IS_TIM_SLAVE_MODE(MODE) (((MODE) == TIM_SLAVEMODE_DISABLE) || \ ((MODE) == TIM_SLAVEMODE_GATED) || \ ((MODE) == TIM_SLAVEMODE_RESET) || \ ((MODE) == TIM_SLAVEMODE_TRIGGER) || \ ((MODE) == TIM_SLAVEMODE_EXTERNAL1)) #define IS_TIM_MSM_STATE(STATE) (((STATE) == TIM_MASTERSLAVEMODE_ENABLE) || \ ((STATE) == TIM_MASTERSLAVEMODE_DISABLE)) #define IS_TIM_TRIGGER_SELECTION(SELECTION) (((SELECTION) == TIM_TS_ITR0) || \ ((SELECTION) == TIM_TS_ITR1) || \ ((SELECTION) == TIM_TS_ITR2) || \ ((SELECTION) == TIM_TS_ITR3) || \ ((SELECTION) == TIM_TS_TI1F_ED) || \ ((SELECTION) == TIM_TS_TI1FP1) || \ ((SELECTION) == TIM_TS_TI2FP2) || \ ((SELECTION) == TIM_TS_ETRF)) #define IS_TIM_INTERNAL_TRIGGEREVENT_SELECTION(SELECTION) (((SELECTION) == TIM_TS_ITR0) || \ ((SELECTION) == TIM_TS_ITR1) || \ ((SELECTION) == TIM_TS_ITR2) || \ ((SELECTION) == TIM_TS_ITR3) || \ ((SELECTION) == TIM_TS_NONE)) #define IS_TIM_TRIGGERPOLARITY(POLARITY) (((POLARITY) == TIM_TRIGGERPOLARITY_INVERTED ) || \ ((POLARITY) == TIM_TRIGGERPOLARITY_NONINVERTED) || \ ((POLARITY) == TIM_TRIGGERPOLARITY_RISING ) || \ ((POLARITY) == TIM_TRIGGERPOLARITY_FALLING ) || \ ((POLARITY) == TIM_TRIGGERPOLARITY_BOTHEDGE )) #define IS_TIM_TRIGGERPRESCALER(PRESCALER) (((PRESCALER) == TIM_TRIGGERPRESCALER_DIV1) || \ ((PRESCALER) == TIM_TRIGGERPRESCALER_DIV2) || \ ((PRESCALER) == TIM_TRIGGERPRESCALER_DIV4) || \ ((PRESCALER) == TIM_TRIGGERPRESCALER_DIV8)) #define IS_TIM_TRIGGERFILTER(ICFILTER) ((ICFILTER) <= 0xF) #define IS_TIM_TI1SELECTION(TI1SELECTION) (((TI1SELECTION) == TIM_TI1SELECTION_CH1) || \ ((TI1SELECTION) == TIM_TI1SELECTION_XORCOMBINATION)) #define IS_TIM_DMA_BASE(BASE) (((BASE) == TIM_DMABASE_CR1) || \ ((BASE) == TIM_DMABASE_CR2) || \ ((BASE) == TIM_DMABASE_SMCR) || \ ((BASE) == TIM_DMABASE_DIER) || \ ((BASE) == TIM_DMABASE_SR) || \ ((BASE) == TIM_DMABASE_EGR) || \ ((BASE) == TIM_DMABASE_CCMR1) || \ ((BASE) == TIM_DMABASE_CCMR2) || \ ((BASE) == TIM_DMABASE_CCER) || \ ((BASE) == TIM_DMABASE_CNT) || \ ((BASE) == TIM_DMABASE_PSC) || \ ((BASE) == TIM_DMABASE_ARR) || \ ((BASE) == TIM_DMABASE_RCR) || \ ((BASE) == TIM_DMABASE_CCR1) || \ ((BASE) == TIM_DMABASE_CCR2) || \ ((BASE) == TIM_DMABASE_CCR3) || \ ((BASE) == TIM_DMABASE_CCR4) || \ ((BASE) == TIM_DMABASE_BDTR) || \ ((BASE) == TIM_DMABASE_DCR) || \ ((BASE) == TIM_DMABASE_OR)) #define IS_TIM_DMA_LENGTH(LENGTH) (((LENGTH) == TIM_DMABURSTLENGTH_1TRANSFER) || \ ((LENGTH) == TIM_DMABURSTLENGTH_2TRANSFERS) || \ ((LENGTH) == TIM_DMABURSTLENGTH_3TRANSFERS) || \ ((LENGTH) == TIM_DMABURSTLENGTH_4TRANSFERS) || \ ((LENGTH) == TIM_DMABURSTLENGTH_5TRANSFERS) || \ ((LENGTH) == TIM_DMABURSTLENGTH_6TRANSFERS) || \ ((LENGTH) == TIM_DMABURSTLENGTH_7TRANSFERS) || \ ((LENGTH) == TIM_DMABURSTLENGTH_8TRANSFERS) || \ ((LENGTH) == TIM_DMABURSTLENGTH_9TRANSFERS) || \ ((LENGTH) == TIM_DMABURSTLENGTH_10TRANSFERS) || \ ((LENGTH) == TIM_DMABURSTLENGTH_11TRANSFERS) || \ ((LENGTH) == TIM_DMABURSTLENGTH_12TRANSFERS) || \ ((LENGTH) == TIM_DMABURSTLENGTH_13TRANSFERS) || \ ((LENGTH) == TIM_DMABURSTLENGTH_14TRANSFERS) || \ ((LENGTH) == TIM_DMABURSTLENGTH_15TRANSFERS) || \ ((LENGTH) == TIM_DMABURSTLENGTH_16TRANSFERS) || \ ((LENGTH) == TIM_DMABURSTLENGTH_17TRANSFERS) || \ ((LENGTH) == TIM_DMABURSTLENGTH_18TRANSFERS)) #define IS_TIM_IC_FILTER(ICFILTER) ((ICFILTER) <= 0xF) /** * @} */ /** @defgroup TIM_Mask_Definitions TIM Mask Definition * @{ */ /* The counter of a timer instance is disabled only if all the CCx and CCxN channels have been disabled */ #define TIM_CCER_CCxE_MASK ((uint32_t)(TIM_CCER_CC1E | TIM_CCER_CC2E | TIM_CCER_CC3E | TIM_CCER_CC4E)) #define TIM_CCER_CCxNE_MASK ((uint32_t)(TIM_CCER_CC1NE | TIM_CCER_CC2NE | TIM_CCER_CC3NE)) /** * @} */ /** * @} */ /* Private functions ---------------------------------------------------------*/ /** @defgroup TIM_Private_Functions TIM Private Functions * @{ */ void TIM_Base_SetConfig(TIM_TypeDef *TIMx, TIM_Base_InitTypeDef *Structure); void TIM_TI1_SetConfig(TIM_TypeDef *TIMx, uint32_t TIM_ICPolarity, uint32_t TIM_ICSelection, uint32_t TIM_ICFilter); void TIM_OC2_SetConfig(TIM_TypeDef *TIMx, TIM_OC_InitTypeDef *OC_Config); void TIM_DMADelayPulseCplt(DMA_HandleTypeDef *hdma); void TIM_DMAError(DMA_HandleTypeDef *hdma); void TIM_DMACaptureCplt(DMA_HandleTypeDef *hdma); void TIM_CCxChannelCmd(TIM_TypeDef* TIMx, uint32_t Channel, uint32_t ChannelState); /** * @} */ /** * @} */ /** * @} */ #ifdef __cplusplus } #endif #endif /* __STM32F4xx_HAL_TIM_H */ /************************ (C) COPYRIGHT STMicroelectronics *****END OF FILE****/ ================================================ FILE: Zelig/mbed/TARGET_NUCLEO_F411RE/stm32f4xx_hal_tim_ex.h ================================================ /** ****************************************************************************** * @file stm32f4xx_hal_tim_ex.h * @author MCD Application Team * @version V1.4.1 * @date 09-October-2015 * @brief Header file of TIM HAL Extension module. ****************************************************************************** * @attention * *

© COPYRIGHT(c) 2015 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. * ****************************************************************************** */ /* Define to prevent recursive inclusion -------------------------------------*/ #ifndef __STM32F4xx_HAL_TIM_EX_H #define __STM32F4xx_HAL_TIM_EX_H #ifdef __cplusplus extern "C" { #endif /* Includes ------------------------------------------------------------------*/ #include "stm32f4xx_hal_def.h" /** @addtogroup STM32F4xx_HAL_Driver * @{ */ /** @addtogroup TIMEx * @{ */ /* Exported types ------------------------------------------------------------*/ /** @defgroup TIMEx_Exported_Types TIM Exported Types * @{ */ /** * @brief TIM Hall sensor Configuration Structure definition */ typedef struct { uint32_t IC1Polarity; /*!< Specifies the active edge of the input signal. This parameter can be a value of @ref TIM_Input_Capture_Polarity */ uint32_t IC1Prescaler; /*!< Specifies the Input Capture Prescaler. This parameter can be a value of @ref TIM_Input_Capture_Prescaler */ uint32_t IC1Filter; /*!< Specifies the input capture filter. This parameter can be a number between Min_Data = 0x0 and Max_Data = 0xF */ uint32_t Commutation_Delay; /*!< Specifies the pulse value to be loaded into the Capture Compare Register. This parameter can be a number between Min_Data = 0x0000 and Max_Data = 0xFFFF */ } TIM_HallSensor_InitTypeDef; /** * @brief TIM Master configuration Structure definition */ typedef struct { uint32_t MasterOutputTrigger; /*!< Trigger output (TRGO) selection. This parameter can be a value of @ref TIM_Master_Mode_Selection */ uint32_t MasterSlaveMode; /*!< Master/slave mode selection. This parameter can be a value of @ref TIM_Master_Slave_Mode */ }TIM_MasterConfigTypeDef; /** * @brief TIM Break and Dead time configuration Structure definition */ typedef struct { uint32_t OffStateRunMode; /*!< TIM off state in run mode. This parameter can be a value of @ref TIM_OSSR_Off_State_Selection_for_Run_mode_state */ uint32_t OffStateIDLEMode; /*!< TIM off state in IDLE mode. This parameter can be a value of @ref TIM_OSSI_Off_State_Selection_for_Idle_mode_state */ uint32_t LockLevel; /*!< TIM Lock level. This parameter can be a value of @ref TIM_Lock_level */ uint32_t DeadTime; /*!< TIM dead Time. This parameter can be a number between Min_Data = 0x00 and Max_Data = 0xFF */ uint32_t BreakState; /*!< TIM Break State. This parameter can be a value of @ref TIM_Break_Input_enable_disable */ uint32_t BreakPolarity; /*!< TIM Break input polarity. This parameter can be a value of @ref TIM_Break_Polarity */ uint32_t AutomaticOutput; /*!< TIM Automatic Output Enable state. This parameter can be a value of @ref TIM_AOE_Bit_Set_Reset */ }TIM_BreakDeadTimeConfigTypeDef; /** * @} */ /* Exported constants --------------------------------------------------------*/ /** @defgroup TIMEx_Exported_Constants TIM Exported Constants * @{ */ /** @defgroup TIMEx_Remap TIM Remap * @{ */ #define TIM_TIM2_TIM8_TRGO (0x00000000) #define TIM_TIM2_ETH_PTP (0x00000400) #define TIM_TIM2_USBFS_SOF (0x00000800) #define TIM_TIM2_USBHS_SOF (0x00000C00) #define TIM_TIM5_GPIO (0x00000000) #define TIM_TIM5_LSI (0x00000040) #define TIM_TIM5_LSE (0x00000080) #define TIM_TIM5_RTC (0x000000C0) #define TIM_TIM11_GPIO (0x00000000) #define TIM_TIM11_HSE (0x00000002) #if defined (STM32F446xx) #define TIM_TIM11_SPDIFRX (0x00000001) #endif /* STM32F446xx */ /** * @} */ #if defined(STM32F410Tx) || defined(STM32F410Cx) || defined(STM32F410Rx) /** @defgroup TIMEx_SystemBreakInput TIM System Break Input * @{ */ #define TIM_SYSTEMBREAKINPUT_HARDFAULT ((uint32_t)0x00000001) /* Core Lockup lock output(Hardfault) is connected to Break Input of TIM1 and TIM8 */ #define TIM_SYSTEMBREAKINPUT_PVD ((uint32_t)0x00000004) /* PVD Interrupt is connected to Break Input of TIM1 and TIM8 */ #define TIM_SYSTEMBREAKINPUT_HARDFAULT_PVD ((uint32_t)0x00000005) /* Core Lockup lock output(Hardfault) and PVD Interrupt are connected to Break Input of TIM1 and TIM8 */ /** * @} */ #endif /* STM32F410Tx || STM32F410Cx || STM32F410Rx */ /** * @} */ /* Exported macro ------------------------------------------------------------*/ /* Exported functions --------------------------------------------------------*/ /** @addtogroup TIMEx_Exported_Functions * @{ */ /** @addtogroup TIMEx_Exported_Functions_Group1 * @{ */ /* Timer Hall Sensor functions **********************************************/ HAL_StatusTypeDef HAL_TIMEx_HallSensor_Init(TIM_HandleTypeDef* htim, TIM_HallSensor_InitTypeDef* sConfig); HAL_StatusTypeDef HAL_TIMEx_HallSensor_DeInit(TIM_HandleTypeDef* htim); void HAL_TIMEx_HallSensor_MspInit(TIM_HandleTypeDef* htim); void HAL_TIMEx_HallSensor_MspDeInit(TIM_HandleTypeDef* htim); /* Blocking mode: Polling */ HAL_StatusTypeDef HAL_TIMEx_HallSensor_Start(TIM_HandleTypeDef* htim); HAL_StatusTypeDef HAL_TIMEx_HallSensor_Stop(TIM_HandleTypeDef* htim); /* Non-Blocking mode: Interrupt */ HAL_StatusTypeDef HAL_TIMEx_HallSensor_Start_IT(TIM_HandleTypeDef* htim); HAL_StatusTypeDef HAL_TIMEx_HallSensor_Stop_IT(TIM_HandleTypeDef* htim); /* Non-Blocking mode: DMA */ HAL_StatusTypeDef HAL_TIMEx_HallSensor_Start_DMA(TIM_HandleTypeDef* htim, uint32_t *pData, uint16_t Length); HAL_StatusTypeDef HAL_TIMEx_HallSensor_Stop_DMA(TIM_HandleTypeDef* htim); /** * @} */ /** @addtogroup TIMEx_Exported_Functions_Group2 * @{ */ /* Timer Complementary Output Compare functions *****************************/ /* Blocking mode: Polling */ HAL_StatusTypeDef HAL_TIMEx_OCN_Start(TIM_HandleTypeDef* htim, uint32_t Channel); HAL_StatusTypeDef HAL_TIMEx_OCN_Stop(TIM_HandleTypeDef* htim, uint32_t Channel); /* Non-Blocking mode: Interrupt */ HAL_StatusTypeDef HAL_TIMEx_OCN_Start_IT(TIM_HandleTypeDef* htim, uint32_t Channel); HAL_StatusTypeDef HAL_TIMEx_OCN_Stop_IT(TIM_HandleTypeDef* htim, uint32_t Channel); /* Non-Blocking mode: DMA */ HAL_StatusTypeDef HAL_TIMEx_OCN_Start_DMA(TIM_HandleTypeDef* htim, uint32_t Channel, uint32_t *pData, uint16_t Length); HAL_StatusTypeDef HAL_TIMEx_OCN_Stop_DMA(TIM_HandleTypeDef* htim, uint32_t Channel); /** * @} */ /** @addtogroup TIMEx_Exported_Functions_Group3 * @{ */ /* Timer Complementary PWM functions ****************************************/ /* Blocking mode: Polling */ HAL_StatusTypeDef HAL_TIMEx_PWMN_Start(TIM_HandleTypeDef* htim, uint32_t Channel); HAL_StatusTypeDef HAL_TIMEx_PWMN_Stop(TIM_HandleTypeDef* htim, uint32_t Channel); /* Non-Blocking mode: Interrupt */ HAL_StatusTypeDef HAL_TIMEx_PWMN_Start_IT(TIM_HandleTypeDef* htim, uint32_t Channel); HAL_StatusTypeDef HAL_TIMEx_PWMN_Stop_IT(TIM_HandleTypeDef* htim, uint32_t Channel); /* Non-Blocking mode: DMA */ HAL_StatusTypeDef HAL_TIMEx_PWMN_Start_DMA(TIM_HandleTypeDef* htim, uint32_t Channel, uint32_t *pData, uint16_t Length); HAL_StatusTypeDef HAL_TIMEx_PWMN_Stop_DMA(TIM_HandleTypeDef* htim, uint32_t Channel); /** * @} */ /** @addtogroup TIMEx_Exported_Functions_Group4 * @{ */ /* Timer Complementary One Pulse functions **********************************/ /* Blocking mode: Polling */ HAL_StatusTypeDef HAL_TIMEx_OnePulseN_Start(TIM_HandleTypeDef* htim, uint32_t OutputChannel); HAL_StatusTypeDef HAL_TIMEx_OnePulseN_Stop(TIM_HandleTypeDef* htim, uint32_t OutputChannel); /* Non-Blocking mode: Interrupt */ HAL_StatusTypeDef HAL_TIMEx_OnePulseN_Start_IT(TIM_HandleTypeDef* htim, uint32_t OutputChannel); HAL_StatusTypeDef HAL_TIMEx_OnePulseN_Stop_IT(TIM_HandleTypeDef* htim, uint32_t OutputChannel); /** * @} */ /** @addtogroup TIMEx_Exported_Functions_Group5 * @{ */ /* Extension Control functions ************************************************/ HAL_StatusTypeDef HAL_TIMEx_ConfigCommutationEvent(TIM_HandleTypeDef* htim, uint32_t InputTrigger, uint32_t CommutationSource); HAL_StatusTypeDef HAL_TIMEx_ConfigCommutationEvent_IT(TIM_HandleTypeDef* htim, uint32_t InputTrigger, uint32_t CommutationSource); HAL_StatusTypeDef HAL_TIMEx_ConfigCommutationEvent_DMA(TIM_HandleTypeDef* htim, uint32_t InputTrigger, uint32_t CommutationSource); HAL_StatusTypeDef HAL_TIMEx_MasterConfigSynchronization(TIM_HandleTypeDef* htim, TIM_MasterConfigTypeDef * sMasterConfig); HAL_StatusTypeDef HAL_TIMEx_ConfigBreakDeadTime(TIM_HandleTypeDef* htim, TIM_BreakDeadTimeConfigTypeDef *sBreakDeadTimeConfig); HAL_StatusTypeDef HAL_TIMEx_RemapConfig(TIM_HandleTypeDef* htim, uint32_t Remap); /** * @} */ /** @addtogroup TIMEx_Exported_Functions_Group6 * @{ */ /* Extension Callback *********************************************************/ void HAL_TIMEx_CommutationCallback(TIM_HandleTypeDef* htim); void HAL_TIMEx_BreakCallback(TIM_HandleTypeDef* htim); void TIMEx_DMACommutationCplt(DMA_HandleTypeDef *hdma); /** * @} */ /** @addtogroup TIMEx_Exported_Functions_Group7 * @{ */ /* Extension Peripheral State functions **************************************/ HAL_TIM_StateTypeDef HAL_TIMEx_HallSensor_GetState(TIM_HandleTypeDef* htim); /** * @} */ /** * @} */ /* Private types -------------------------------------------------------------*/ /* Private variables ---------------------------------------------------------*/ /* Private constants ---------------------------------------------------------*/ /* Private macros ------------------------------------------------------------*/ /** @defgroup TIMEx_Private_Macros TIM Private Macros * @{ */ #if defined (STM32F446xx) #define IS_TIM_REMAP(TIM_REMAP) (((TIM_REMAP) == TIM_TIM2_TIM8_TRGO)||\ ((TIM_REMAP) == TIM_TIM2_ETH_PTP)||\ ((TIM_REMAP) == TIM_TIM2_USBFS_SOF)||\ ((TIM_REMAP) == TIM_TIM2_USBHS_SOF)||\ ((TIM_REMAP) == TIM_TIM5_GPIO)||\ ((TIM_REMAP) == TIM_TIM5_LSI)||\ ((TIM_REMAP) == TIM_TIM5_LSE)||\ ((TIM_REMAP) == TIM_TIM5_RTC)||\ ((TIM_REMAP) == TIM_TIM11_GPIO)||\ ((TIM_REMAP) == TIM_TIM11_SPDIFRX)||\ ((TIM_REMAP) == TIM_TIM11_HSE)) #else #define IS_TIM_REMAP(TIM_REMAP) (((TIM_REMAP) == TIM_TIM2_TIM8_TRGO)||\ ((TIM_REMAP) == TIM_TIM2_ETH_PTP)||\ ((TIM_REMAP) == TIM_TIM2_USBFS_SOF)||\ ((TIM_REMAP) == TIM_TIM2_USBHS_SOF)||\ ((TIM_REMAP) == TIM_TIM5_GPIO)||\ ((TIM_REMAP) == TIM_TIM5_LSI)||\ ((TIM_REMAP) == TIM_TIM5_LSE)||\ ((TIM_REMAP) == TIM_TIM5_RTC)||\ ((TIM_REMAP) == TIM_TIM11_GPIO)||\ ((TIM_REMAP) == TIM_TIM11_HSE)) #endif /* STM32F446xx */ #if defined(STM32F410Tx) || defined(STM32F410Cx) || defined(STM32F410Rx) #define IS_TIM_SYSTEMBREAKINPUT(BREAKINPUT) (((BREAKINPUT) == TIM_SYSTEMBREAKINPUT_HARDFAULT)||\ ((BREAKINPUT) == TIM_SYSTEMBREAKINPUT_PVD)||\ ((BREAKINPUT) == TIM_SYSTEMBREAKINPUT_HARDFAULT_PVD)) #endif /* STM32F410Tx || STM32F410Cx || STM32F410Rx */ #define IS_TIM_DEADTIME(DEADTIME) ((DEADTIME) <= 0xFF) /** * @} */ /* Private functions ---------------------------------------------------------*/ /** @defgroup TIMEx_Private_Functions TIM Private Functions * @{ */ /** * @} */ /** * @} */ /** * @} */ #ifdef __cplusplus } #endif #endif /* __STM32F4xx_HAL_TIM_EX_H */ /************************ (C) COPYRIGHT STMicroelectronics *****END OF FILE****/ ================================================ FILE: Zelig/mbed/TARGET_NUCLEO_F411RE/stm32f4xx_hal_uart.h ================================================ /** ****************************************************************************** * @file stm32f4xx_hal_uart.h * @author MCD Application Team * @version V1.4.1 * @date 09-October-2015 * @brief Header file of UART HAL module. ****************************************************************************** * @attention * *

© COPYRIGHT(c) 2015 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. * ****************************************************************************** */ /* Define to prevent recursive inclusion -------------------------------------*/ #ifndef __STM32F4xx_HAL_UART_H #define __STM32F4xx_HAL_UART_H #ifdef __cplusplus extern "C" { #endif /* Includes ------------------------------------------------------------------*/ #include "stm32f4xx_hal_def.h" /** @addtogroup STM32F4xx_HAL_Driver * @{ */ /** @addtogroup UART * @{ */ /* Exported types ------------------------------------------------------------*/ /** @defgroup UART_Exported_Types UART Exported Types * @{ */ /** * @brief UART Init Structure definition */ typedef struct { uint32_t BaudRate; /*!< This member configures the UART communication baud rate. The baud rate is computed using the following formula: - IntegerDivider = ((PCLKx) / (8 * (OVR8+1) * (huart->Init.BaudRate))) - FractionalDivider = ((IntegerDivider - ((uint32_t) IntegerDivider)) * 8 * (OVR8+1)) + 0.5 Where OVR8 is the "oversampling by 8 mode" configuration bit in the CR1 register. */ uint32_t WordLength; /*!< Specifies the number of data bits transmitted or received in a frame. This parameter can be a value of @ref UART_Word_Length */ uint32_t StopBits; /*!< Specifies the number of stop bits transmitted. This parameter can be a value of @ref UART_Stop_Bits */ uint32_t Parity; /*!< Specifies the parity mode. This parameter can be a value of @ref UART_Parity @note When parity is enabled, the computed parity is inserted at the MSB position of the transmitted data (9th bit when the word length is set to 9 data bits; 8th bit when the word length is set to 8 data bits). */ uint32_t Mode; /*!< Specifies whether the Receive or Transmit mode is enabled or disabled. This parameter can be a value of @ref UART_Mode */ uint32_t HwFlowCtl; /*!< Specifies whether the hardware flow control mode is enabled or disabled. This parameter can be a value of @ref UART_Hardware_Flow_Control */ uint32_t OverSampling; /*!< Specifies whether the Over sampling 8 is enabled or disabled, to achieve higher speed (up to fPCLK/8). This parameter can be a value of @ref UART_Over_Sampling */ }UART_InitTypeDef; /** * @brief HAL UART State structures definition */ typedef enum { HAL_UART_STATE_RESET = 0x00, /*!< Peripheral is not yet Initialized */ HAL_UART_STATE_READY = 0x01, /*!< Peripheral Initialized and ready for use */ HAL_UART_STATE_BUSY = 0x02, /*!< an internal process is ongoing */ HAL_UART_STATE_BUSY_TX = 0x12, /*!< Data Transmission process is ongoing */ HAL_UART_STATE_BUSY_RX = 0x22, /*!< Data Reception process is ongoing */ HAL_UART_STATE_BUSY_TX_RX = 0x32, /*!< Data Transmission and Reception process is ongoing */ HAL_UART_STATE_TIMEOUT = 0x03, /*!< Timeout state */ HAL_UART_STATE_ERROR = 0x04 /*!< Error */ }HAL_UART_StateTypeDef; /** * @brief UART handle Structure definition */ typedef struct { USART_TypeDef *Instance; /*!< UART registers base address */ UART_InitTypeDef Init; /*!< UART communication parameters */ uint8_t *pTxBuffPtr; /*!< Pointer to UART Tx transfer Buffer */ uint16_t TxXferSize; /*!< UART Tx Transfer size */ uint16_t TxXferCount; /*!< UART Tx Transfer Counter */ uint8_t *pRxBuffPtr; /*!< Pointer to UART Rx transfer Buffer */ uint16_t RxXferSize; /*!< UART Rx Transfer size */ uint16_t RxXferCount; /*!< UART Rx Transfer Counter */ DMA_HandleTypeDef *hdmatx; /*!< UART Tx DMA Handle parameters */ DMA_HandleTypeDef *hdmarx; /*!< UART Rx DMA Handle parameters */ HAL_LockTypeDef Lock; /*!< Locking object */ __IO HAL_UART_StateTypeDef State; /*!< UART communication state */ __IO uint32_t ErrorCode; /*!< UART Error code */ }UART_HandleTypeDef; /** * @} */ /* Exported constants --------------------------------------------------------*/ /** @defgroup UART_Exported_Constants UART Exported constants * @{ */ /** @defgroup UART_Error_Code UART Error Code * @brief UART Error Code * @{ */ #define HAL_UART_ERROR_NONE ((uint32_t)0x00000000) /*!< No error */ #define HAL_UART_ERROR_PE ((uint32_t)0x00000001) /*!< Parity error */ #define HAL_UART_ERROR_NE ((uint32_t)0x00000002) /*!< Noise error */ #define HAL_UART_ERROR_FE ((uint32_t)0x00000004) /*!< Frame error */ #define HAL_UART_ERROR_ORE ((uint32_t)0x00000008) /*!< Overrun error */ #define HAL_UART_ERROR_DMA ((uint32_t)0x00000010) /*!< DMA transfer error */ /** * @} */ /** @defgroup UART_Word_Length UART Word Length * @{ */ #define UART_WORDLENGTH_8B ((uint32_t)0x00000000) #define UART_WORDLENGTH_9B ((uint32_t)USART_CR1_M) /** * @} */ /** @defgroup UART_Stop_Bits UART Number of Stop Bits * @{ */ #define UART_STOPBITS_1 ((uint32_t)0x00000000) #define UART_STOPBITS_2 ((uint32_t)USART_CR2_STOP_1) /** * @} */ /** @defgroup UART_Parity UART Parity * @{ */ #define UART_PARITY_NONE ((uint32_t)0x00000000) #define UART_PARITY_EVEN ((uint32_t)USART_CR1_PCE) #define UART_PARITY_ODD ((uint32_t)(USART_CR1_PCE | USART_CR1_PS)) /** * @} */ /** @defgroup UART_Hardware_Flow_Control UART Hardware Flow Control * @{ */ #define UART_HWCONTROL_NONE ((uint32_t)0x00000000) #define UART_HWCONTROL_RTS ((uint32_t)USART_CR3_RTSE) #define UART_HWCONTROL_CTS ((uint32_t)USART_CR3_CTSE) #define UART_HWCONTROL_RTS_CTS ((uint32_t)(USART_CR3_RTSE | USART_CR3_CTSE)) /** * @} */ /** @defgroup UART_Mode UART Transfer Mode * @{ */ #define UART_MODE_RX ((uint32_t)USART_CR1_RE) #define UART_MODE_TX ((uint32_t)USART_CR1_TE) #define UART_MODE_TX_RX ((uint32_t)(USART_CR1_TE |USART_CR1_RE)) /** * @} */ /** @defgroup UART_State UART State * @{ */ #define UART_STATE_DISABLE ((uint32_t)0x00000000) #define UART_STATE_ENABLE ((uint32_t)USART_CR1_UE) /** * @} */ /** @defgroup UART_Over_Sampling UART Over Sampling * @{ */ #define UART_OVERSAMPLING_16 ((uint32_t)0x00000000) #define UART_OVERSAMPLING_8 ((uint32_t)USART_CR1_OVER8) /** * @} */ /** @defgroup UART_LIN_Break_Detection_Length UART LIN Break Detection Length * @{ */ #define UART_LINBREAKDETECTLENGTH_10B ((uint32_t)0x00000000) #define UART_LINBREAKDETECTLENGTH_11B ((uint32_t)0x00000020) /** * @} */ /** @defgroup UART_WakeUp_functions UART Wakeup Functions * @{ */ #define UART_WAKEUPMETHOD_IDLELINE ((uint32_t)0x00000000) #define UART_WAKEUPMETHOD_ADDRESSMARK ((uint32_t)0x00000800) /** * @} */ /** @defgroup UART_Flags UART FLags * Elements values convention: 0xXXXX * - 0xXXXX : Flag mask in the SR register * @{ */ #define UART_FLAG_CTS ((uint32_t)USART_SR_CTS) #define UART_FLAG_LBD ((uint32_t)USART_SR_LBD) #define UART_FLAG_TXE ((uint32_t)USART_SR_TXE) #define UART_FLAG_TC ((uint32_t)USART_SR_TC) #define UART_FLAG_RXNE ((uint32_t)USART_SR_RXNE) #define UART_FLAG_IDLE ((uint32_t)USART_SR_IDLE) #define UART_FLAG_ORE ((uint32_t)USART_SR_ORE) #define UART_FLAG_NE ((uint32_t)USART_SR_NE) #define UART_FLAG_FE ((uint32_t)USART_SR_FE) #define UART_FLAG_PE ((uint32_t)USART_SR_PE) /** * @} */ /** @defgroup UART_Interrupt_definition UART Interrupt Definitions * Elements values convention: 0xY000XXXX * - XXXX : Interrupt mask (16 bits) in the Y register * - Y : Interrupt source register (2bits) * - 0001: CR1 register * - 0010: CR2 register * - 0011: CR3 register * * @{ */ #define UART_IT_PE ((uint32_t)(UART_CR1_REG_INDEX << 28 | USART_CR1_PEIE)) #define UART_IT_TXE ((uint32_t)(UART_CR1_REG_INDEX << 28 | USART_CR1_TXEIE)) #define UART_IT_TC ((uint32_t)(UART_CR1_REG_INDEX << 28 | USART_CR1_TCIE)) #define UART_IT_RXNE ((uint32_t)(UART_CR1_REG_INDEX << 28 | USART_CR1_RXNEIE)) #define UART_IT_IDLE ((uint32_t)(UART_CR1_REG_INDEX << 28 | USART_CR1_IDLEIE)) #define UART_IT_LBD ((uint32_t)(UART_CR2_REG_INDEX << 28 | USART_CR2_LBDIE)) #define UART_IT_CTS ((uint32_t)(UART_CR3_REG_INDEX << 28 | USART_CR3_CTSIE)) #define UART_IT_ERR ((uint32_t)(UART_CR3_REG_INDEX << 28 | USART_CR3_EIE)) /** * @} */ /** * @} */ /* Exported macro ------------------------------------------------------------*/ /** @defgroup UART_Exported_Macros UART Exported Macros * @{ */ /** @brief Reset UART handle state * @param __HANDLE__: specifies the UART Handle. * This parameter can be UARTx where x: 1, 2, 3, 4, 5, 6, 7 or 8 to select the USART or * UART peripheral. * @retval None */ #define __HAL_UART_RESET_HANDLE_STATE(__HANDLE__) ((__HANDLE__)->State = HAL_UART_STATE_RESET) /** @brief Flushes the UART DR register * @param __HANDLE__: specifies the UART Handle. */ #define __HAL_UART_FLUSH_DRREGISTER(__HANDLE__) ((__HANDLE__)->Instance->DR) /** @brief Checks whether the specified UART flag is set or not. * @param __HANDLE__: specifies the UART Handle. * This parameter can be UARTx where x: 1, 2, 3, 4, 5, 6, 7 or 8 to select the USART or * UART peripheral. * @param __FLAG__: specifies the flag to check. * This parameter can be one of the following values: * @arg UART_FLAG_CTS: CTS Change flag (not available for UART4 and UART5) * @arg UART_FLAG_LBD: LIN Break detection flag * @arg UART_FLAG_TXE: Transmit data register empty flag * @arg UART_FLAG_TC: Transmission Complete flag * @arg UART_FLAG_RXNE: Receive data register not empty flag * @arg UART_FLAG_IDLE: Idle Line detection flag * @arg UART_FLAG_ORE: Overrun Error flag * @arg UART_FLAG_NE: Noise Error flag * @arg UART_FLAG_FE: Framing Error flag * @arg UART_FLAG_PE: Parity Error flag * @retval The new state of __FLAG__ (TRUE or FALSE). */ #define __HAL_UART_GET_FLAG(__HANDLE__, __FLAG__) (((__HANDLE__)->Instance->SR & (__FLAG__)) == (__FLAG__)) /** @brief Clears the specified UART pending flag. * @param __HANDLE__: specifies the UART Handle. * This parameter can be UARTx where x: 1, 2, 3, 4, 5, 6, 7 or 8 to select the USART or * UART peripheral. * @param __FLAG__: specifies the flag to check. * This parameter can be any combination of the following values: * @arg UART_FLAG_CTS: CTS Change flag (not available for UART4 and UART5). * @arg UART_FLAG_LBD: LIN Break detection flag. * @arg UART_FLAG_TC: Transmission Complete flag. * @arg UART_FLAG_RXNE: Receive data register not empty flag. * * @note PE (Parity error), FE (Framing error), NE (Noise error), ORE (Overrun * error) and IDLE (Idle line detected) flags are cleared by software * sequence: a read operation to USART_SR register followed by a read * operation to USART_DR register. * @note RXNE flag can be also cleared by a read to the USART_DR register. * @note TC flag can be also cleared by software sequence: a read operation to * USART_SR register followed by a write operation to USART_DR register. * @note TXE flag is cleared only by a write to the USART_DR register. * * @retval None */ #define __HAL_UART_CLEAR_FLAG(__HANDLE__, __FLAG__) ((__HANDLE__)->Instance->SR = ~(__FLAG__)) /** @brief Clear the UART PE pending flag. * @param __HANDLE__: specifies the UART Handle. * This parameter can be UARTx where x: 1, 2, 3, 4, 5, 6, 7 or 8 to select the USART or * UART peripheral. * @retval None */ #define __HAL_UART_CLEAR_PEFLAG(__HANDLE__) \ do{ \ __IO uint32_t tmpreg; \ tmpreg = (__HANDLE__)->Instance->SR; \ tmpreg = (__HANDLE__)->Instance->DR; \ UNUSED(tmpreg); \ } while(0) /** @brief Clear the UART FE pending flag. * @param __HANDLE__: specifies the UART Handle. * This parameter can be UARTx where x: 1, 2, 3, 4, 5, 6, 7 or 8 to select the USART or * UART peripheral. * @retval None */ #define __HAL_UART_CLEAR_FEFLAG(__HANDLE__) __HAL_UART_CLEAR_PEFLAG(__HANDLE__) /** @brief Clear the UART NE pending flag. * @param __HANDLE__: specifies the UART Handle. * This parameter can be UARTx where x: 1, 2, 3, 4, 5, 6, 7 or 8 to select the USART or * UART peripheral. * @retval None */ #define __HAL_UART_CLEAR_NEFLAG(__HANDLE__) __HAL_UART_CLEAR_PEFLAG(__HANDLE__) /** @brief Clear the UART ORE pending flag. * @param __HANDLE__: specifies the UART Handle. * This parameter can be UARTx where x: 1, 2, 3, 4, 5, 6, 7 or 8 to select the USART or * UART peripheral. * @retval None */ #define __HAL_UART_CLEAR_OREFLAG(__HANDLE__) __HAL_UART_CLEAR_PEFLAG(__HANDLE__) /** @brief Clear the UART IDLE pending flag. * @param __HANDLE__: specifies the UART Handle. * This parameter can be UARTx where x: 1, 2, 3, 4, 5, 6, 7 or 8 to select the USART or * UART peripheral. * @retval None */ #define __HAL_UART_CLEAR_IDLEFLAG(__HANDLE__) __HAL_UART_CLEAR_PEFLAG(__HANDLE__) /** @brief Enable the specified UART interrupt. * @param __HANDLE__: specifies the UART Handle. * This parameter can be UARTx where x: 1, 2, 3, 4, 5, 6, 7 or 8 to select the USART or * UART peripheral. * @param __INTERRUPT__: specifies the UART interrupt source to enable. * This parameter can be one of the following values: * @arg UART_IT_CTS: CTS change interrupt * @arg UART_IT_LBD: LIN Break detection interrupt * @arg UART_IT_TXE: Transmit Data Register empty interrupt * @arg UART_IT_TC: Transmission complete interrupt * @arg UART_IT_RXNE: Receive Data register not empty interrupt * @arg UART_IT_IDLE: Idle line detection interrupt * @arg UART_IT_PE: Parity Error interrupt * @arg UART_IT_ERR: Error interrupt(Frame error, noise error, overrun error) * @retval None */ #define UART_IT_MASK ((uint32_t)0x0000FFFF) #define __HAL_UART_ENABLE_IT(__HANDLE__, __INTERRUPT__) ((((__INTERRUPT__) >> 28) == 1)? ((__HANDLE__)->Instance->CR1 |= ((__INTERRUPT__) & UART_IT_MASK)): \ (((__INTERRUPT__) >> 28) == 2)? ((__HANDLE__)->Instance->CR2 |= ((__INTERRUPT__) & UART_IT_MASK)): \ ((__HANDLE__)->Instance->CR3 |= ((__INTERRUPT__) & UART_IT_MASK))) /** @brief Disable the specified UART interrupt. * @param __HANDLE__: specifies the UART Handle. * This parameter can be UARTx where x: 1, 2, 3, 4, 5, 6, 7 or 8 to select the USART or * UART peripheral. * @param __INTERRUPT__: specifies the UART interrupt source to disable. * This parameter can be one of the following values: * @arg UART_IT_CTS: CTS change interrupt * @arg UART_IT_LBD: LIN Break detection interrupt * @arg UART_IT_TXE: Transmit Data Register empty interrupt * @arg UART_IT_TC: Transmission complete interrupt * @arg UART_IT_RXNE: Receive Data register not empty interrupt * @arg UART_IT_IDLE: Idle line detection interrupt * @arg UART_IT_PE: Parity Error interrupt * @arg UART_IT_ERR: Error interrupt(Frame error, noise error, overrun error) * @retval None */ #define __HAL_UART_DISABLE_IT(__HANDLE__, __INTERRUPT__) ((((__INTERRUPT__) >> 28) == 1)? ((__HANDLE__)->Instance->CR1 &= ~((__INTERRUPT__) & UART_IT_MASK)): \ (((__INTERRUPT__) >> 28) == 2)? ((__HANDLE__)->Instance->CR2 &= ~((__INTERRUPT__) & UART_IT_MASK)): \ ((__HANDLE__)->Instance->CR3 &= ~ ((__INTERRUPT__) & UART_IT_MASK))) /** @brief Checks whether the specified UART interrupt has occurred or not. * @param __HANDLE__: specifies the UART Handle. * This parameter can be UARTx where x: 1, 2, 3, 4, 5, 6, 7 or 8 to select the USART or * UART peripheral. * @param __IT__: specifies the UART interrupt source to check. * This parameter can be one of the following values: * @arg UART_IT_CTS: CTS change interrupt (not available for UART4 and UART5) * @arg UART_IT_LBD: LIN Break detection interrupt * @arg UART_IT_TXE: Transmit Data Register empty interrupt * @arg UART_IT_TC: Transmission complete interrupt * @arg UART_IT_RXNE: Receive Data register not empty interrupt * @arg UART_IT_IDLE: Idle line detection interrupt * @arg USART_IT_ERR: Error interrupt * @retval The new state of __IT__ (TRUE or FALSE). */ #define __HAL_UART_GET_IT_SOURCE(__HANDLE__, __IT__) (((((__IT__) >> 28) == 1)? (__HANDLE__)->Instance->CR1:(((((uint32_t)(__IT__)) >> 28) == 2)? \ (__HANDLE__)->Instance->CR2 : (__HANDLE__)->Instance->CR3)) & (((uint32_t)(__IT__)) & UART_IT_MASK)) /** @brief Enable CTS flow control * This macro allows to enable CTS hardware flow control for a given UART instance, * without need to call HAL_UART_Init() function. * As involving direct access to UART registers, usage of this macro should be fully endorsed by user. * @note As macro is expected to be used for modifying CTS Hw flow control feature activation, without need * for USART instance Deinit/Init, following conditions for macro call should be fulfilled : * - UART instance should have already been initialised (through call of HAL_UART_Init() ) * - macro could only be called when corresponding UART instance is disabled (i.e __HAL_UART_DISABLE(__HANDLE__)) * and should be followed by an Enable macro (i.e __HAL_UART_ENABLE(__HANDLE__)). * @param __HANDLE__: specifies the UART Handle. * The Handle Instance can be USART1, USART2 or LPUART. * @retval None */ #define __HAL_UART_HWCONTROL_CTS_ENABLE(__HANDLE__) \ do{ \ SET_BIT((__HANDLE__)->Instance->CR3, USART_CR3_CTSE); \ (__HANDLE__)->Init.HwFlowCtl |= USART_CR3_CTSE; \ } while(0) /** @brief Disable CTS flow control * This macro allows to disable CTS hardware flow control for a given UART instance, * without need to call HAL_UART_Init() function. * As involving direct access to UART registers, usage of this macro should be fully endorsed by user. * @note As macro is expected to be used for modifying CTS Hw flow control feature activation, without need * for USART instance Deinit/Init, following conditions for macro call should be fulfilled : * - UART instance should have already been initialised (through call of HAL_UART_Init() ) * - macro could only be called when corresponding UART instance is disabled (i.e __HAL_UART_DISABLE(__HANDLE__)) * and should be followed by an Enable macro (i.e __HAL_UART_ENABLE(__HANDLE__)). * @param __HANDLE__: specifies the UART Handle. * The Handle Instance can be USART1, USART2 or LPUART. * @retval None */ #define __HAL_UART_HWCONTROL_CTS_DISABLE(__HANDLE__) \ do{ \ CLEAR_BIT((__HANDLE__)->Instance->CR3, USART_CR3_CTSE); \ (__HANDLE__)->Init.HwFlowCtl &= ~(USART_CR3_CTSE); \ } while(0) /** @brief Enable RTS flow control * This macro allows to enable RTS hardware flow control for a given UART instance, * without need to call HAL_UART_Init() function. * As involving direct access to UART registers, usage of this macro should be fully endorsed by user. * @note As macro is expected to be used for modifying RTS Hw flow control feature activation, without need * for USART instance Deinit/Init, following conditions for macro call should be fulfilled : * - UART instance should have already been initialised (through call of HAL_UART_Init() ) * - macro could only be called when corresponding UART instance is disabled (i.e __HAL_UART_DISABLE(__HANDLE__)) * and should be followed by an Enable macro (i.e __HAL_UART_ENABLE(__HANDLE__)). * @param __HANDLE__: specifies the UART Handle. * The Handle Instance can be USART1, USART2 or LPUART. * @retval None */ #define __HAL_UART_HWCONTROL_RTS_ENABLE(__HANDLE__) \ do{ \ SET_BIT((__HANDLE__)->Instance->CR3, USART_CR3_RTSE); \ (__HANDLE__)->Init.HwFlowCtl |= USART_CR3_RTSE; \ } while(0) /** @brief Disable RTS flow control * This macro allows to disable RTS hardware flow control for a given UART instance, * without need to call HAL_UART_Init() function. * As involving direct access to UART registers, usage of this macro should be fully endorsed by user. * @note As macro is expected to be used for modifying RTS Hw flow control feature activation, without need * for USART instance Deinit/Init, following conditions for macro call should be fulfilled : * - UART instance should have already been initialised (through call of HAL_UART_Init() ) * - macro could only be called when corresponding UART instance is disabled (i.e __HAL_UART_DISABLE(__HANDLE__)) * and should be followed by an Enable macro (i.e __HAL_UART_ENABLE(__HANDLE__)). * @param __HANDLE__: specifies the UART Handle. * The Handle Instance can be USART1, USART2 or LPUART. * @retval None */ #define __HAL_UART_HWCONTROL_RTS_DISABLE(__HANDLE__) \ do{ \ CLEAR_BIT((__HANDLE__)->Instance->CR3, USART_CR3_RTSE);\ (__HANDLE__)->Init.HwFlowCtl &= ~(USART_CR3_RTSE); \ } while(0) /** @brief macros to enables the UART's one bit sample method * @param __HANDLE__: specifies the UART Handle. * @retval None */ #define __HAL_UART_ONE_BIT_SAMPLE_ENABLE(__HANDLE__) ((__HANDLE__)->Instance->CR3|= USART_CR3_ONEBIT) /** @brief macros to disables the UART's one bit sample method * @param __HANDLE__: specifies the UART Handle. * @retval None */ #define __HAL_UART_ONE_BIT_SAMPLE_DISABLE(__HANDLE__) ((__HANDLE__)->Instance->CR3 &= (uint16_t)~((uint16_t)USART_CR3_ONEBIT)) /** @brief Enable UART * @param __HANDLE__: specifies the UART Handle. * @retval None */ #define __HAL_UART_ENABLE(__HANDLE__) ((__HANDLE__)->Instance->CR1 |= USART_CR1_UE) /** @brief Disable UART * @param __HANDLE__: specifies the UART Handle. * @retval None */ #define __HAL_UART_DISABLE(__HANDLE__) ((__HANDLE__)->Instance->CR1 &= ~USART_CR1_UE) /** * @} */ /* Exported functions --------------------------------------------------------*/ /** @addtogroup UART_Exported_Functions * @{ */ /** @addtogroup UART_Exported_Functions_Group1 * @{ */ /* Initialization/de-initialization functions **********************************/ HAL_StatusTypeDef HAL_UART_Init(UART_HandleTypeDef *huart); HAL_StatusTypeDef HAL_HalfDuplex_Init(UART_HandleTypeDef *huart); HAL_StatusTypeDef HAL_LIN_Init(UART_HandleTypeDef *huart, uint32_t BreakDetectLength); HAL_StatusTypeDef HAL_MultiProcessor_Init(UART_HandleTypeDef *huart, uint8_t Address, uint32_t WakeUpMethod); HAL_StatusTypeDef HAL_UART_DeInit (UART_HandleTypeDef *huart); void HAL_UART_MspInit(UART_HandleTypeDef *huart); void HAL_UART_MspDeInit(UART_HandleTypeDef *huart); /** * @} */ /** @addtogroup UART_Exported_Functions_Group2 * @{ */ /* IO operation functions *******************************************************/ HAL_StatusTypeDef HAL_UART_Transmit(UART_HandleTypeDef *huart, uint8_t *pData, uint16_t Size, uint32_t Timeout); HAL_StatusTypeDef HAL_UART_Receive(UART_HandleTypeDef *huart, uint8_t *pData, uint16_t Size, uint32_t Timeout); HAL_StatusTypeDef HAL_UART_Transmit_IT(UART_HandleTypeDef *huart, uint8_t *pData, uint16_t Size); HAL_StatusTypeDef HAL_UART_Receive_IT(UART_HandleTypeDef *huart, uint8_t *pData, uint16_t Size); HAL_StatusTypeDef HAL_UART_Transmit_DMA(UART_HandleTypeDef *huart, uint8_t *pData, uint16_t Size); HAL_StatusTypeDef HAL_UART_Receive_DMA(UART_HandleTypeDef *huart, uint8_t *pData, uint16_t Size); HAL_StatusTypeDef HAL_UART_DMAPause(UART_HandleTypeDef *huart); HAL_StatusTypeDef HAL_UART_DMAResume(UART_HandleTypeDef *huart); HAL_StatusTypeDef HAL_UART_DMAStop(UART_HandleTypeDef *huart); void HAL_UART_IRQHandler(UART_HandleTypeDef *huart); void HAL_UART_TxCpltCallback(UART_HandleTypeDef *huart); void HAL_UART_TxHalfCpltCallback(UART_HandleTypeDef *huart); void HAL_UART_RxCpltCallback(UART_HandleTypeDef *huart); void HAL_UART_RxHalfCpltCallback(UART_HandleTypeDef *huart); void HAL_UART_ErrorCallback(UART_HandleTypeDef *huart); /** * @} */ /** @addtogroup UART_Exported_Functions_Group3 * @{ */ /* Peripheral Control functions ************************************************/ HAL_StatusTypeDef HAL_LIN_SendBreak(UART_HandleTypeDef *huart); HAL_StatusTypeDef HAL_MultiProcessor_EnterMuteMode(UART_HandleTypeDef *huart); HAL_StatusTypeDef HAL_MultiProcessor_ExitMuteMode(UART_HandleTypeDef *huart); HAL_StatusTypeDef HAL_HalfDuplex_EnableTransmitter(UART_HandleTypeDef *huart); HAL_StatusTypeDef HAL_HalfDuplex_EnableReceiver(UART_HandleTypeDef *huart); /** * @} */ /** @addtogroup UART_Exported_Functions_Group4 * @{ */ /* Peripheral State functions **************************************************/ HAL_UART_StateTypeDef HAL_UART_GetState(UART_HandleTypeDef *huart); uint32_t HAL_UART_GetError(UART_HandleTypeDef *huart); /** * @} */ /** * @} */ /* Private types -------------------------------------------------------------*/ /* Private variables ---------------------------------------------------------*/ /* Private constants ---------------------------------------------------------*/ /** @defgroup UART_Private_Constants UART Private Constants * @{ */ /** @brief UART interruptions flag mask * */ #define UART_CR1_REG_INDEX 1 #define UART_CR2_REG_INDEX 2 #define UART_CR3_REG_INDEX 3 /** * @} */ /* Private macros ------------------------------------------------------------*/ /** @defgroup UART_Private_Macros UART Private Macros * @{ */ #define IS_UART_WORD_LENGTH(LENGTH) (((LENGTH) == UART_WORDLENGTH_8B) || \ ((LENGTH) == UART_WORDLENGTH_9B)) #define IS_UART_LIN_WORD_LENGTH(LENGTH) (((LENGTH) == UART_WORDLENGTH_8B)) #define IS_UART_STOPBITS(STOPBITS) (((STOPBITS) == UART_STOPBITS_1) || \ ((STOPBITS) == UART_STOPBITS_2)) #define IS_UART_PARITY(PARITY) (((PARITY) == UART_PARITY_NONE) || \ ((PARITY) == UART_PARITY_EVEN) || \ ((PARITY) == UART_PARITY_ODD)) #define IS_UART_HARDWARE_FLOW_CONTROL(CONTROL)\ (((CONTROL) == UART_HWCONTROL_NONE) || \ ((CONTROL) == UART_HWCONTROL_RTS) || \ ((CONTROL) == UART_HWCONTROL_CTS) || \ ((CONTROL) == UART_HWCONTROL_RTS_CTS)) #define IS_UART_MODE(MODE) ((((MODE) & (uint32_t)0x0000FFF3) == 0x00) && ((MODE) != (uint32_t)0x000000)) #define IS_UART_STATE(STATE) (((STATE) == UART_STATE_DISABLE) || \ ((STATE) == UART_STATE_ENABLE)) #define IS_UART_OVERSAMPLING(SAMPLING) (((SAMPLING) == UART_OVERSAMPLING_16) || \ ((SAMPLING) == UART_OVERSAMPLING_8)) #define IS_UART_LIN_OVERSAMPLING(SAMPLING) (((SAMPLING) == UART_OVERSAMPLING_16)) #define IS_UART_LIN_BREAK_DETECT_LENGTH(LENGTH) (((LENGTH) == UART_LINBREAKDETECTLENGTH_10B) || \ ((LENGTH) == UART_LINBREAKDETECTLENGTH_11B)) #define IS_UART_WAKEUPMETHOD(WAKEUP) (((WAKEUP) == UART_WAKEUPMETHOD_IDLELINE) || \ ((WAKEUP) == UART_WAKEUPMETHOD_ADDRESSMARK)) #define IS_UART_BAUDRATE(BAUDRATE) ((BAUDRATE) < 10500001) #define IS_UART_ADDRESS(ADDRESS) ((ADDRESS) <= 0xF) #define UART_DIV_SAMPLING16(_PCLK_, _BAUD_) (((_PCLK_)*25)/(4*(_BAUD_))) #define UART_DIVMANT_SAMPLING16(_PCLK_, _BAUD_) (UART_DIV_SAMPLING16((_PCLK_), (_BAUD_))/100) #define UART_DIVFRAQ_SAMPLING16(_PCLK_, _BAUD_) (((UART_DIV_SAMPLING16((_PCLK_), (_BAUD_)) - (UART_DIVMANT_SAMPLING16((_PCLK_), (_BAUD_)) * 100)) * 16 + 50) / 100) #define UART_BRR_SAMPLING16(_PCLK_, _BAUD_) ((UART_DIVMANT_SAMPLING16((_PCLK_), (_BAUD_)) << 4)|(UART_DIVFRAQ_SAMPLING16((_PCLK_), (_BAUD_)) & 0x0F)) #define UART_DIV_SAMPLING8(_PCLK_, _BAUD_) (((_PCLK_)*25)/(2*(_BAUD_))) #define UART_DIVMANT_SAMPLING8(_PCLK_, _BAUD_) (UART_DIV_SAMPLING8((_PCLK_), (_BAUD_))/100) #define UART_DIVFRAQ_SAMPLING8(_PCLK_, _BAUD_) (((UART_DIV_SAMPLING8((_PCLK_), (_BAUD_)) - (UART_DIVMANT_SAMPLING8((_PCLK_), (_BAUD_)) * 100)) * 16 + 50) / 100) #define UART_BRR_SAMPLING8(_PCLK_, _BAUD_) ((UART_DIVMANT_SAMPLING8((_PCLK_), (_BAUD_)) << 4)|(UART_DIVFRAQ_SAMPLING8((_PCLK_), (_BAUD_)) & 0x0F)) /** * @} */ /* Private functions ---------------------------------------------------------*/ /** @defgroup UART_Private_Functions UART Private Functions * @{ */ /** * @} */ /** * @} */ /** * @} */ #ifdef __cplusplus } #endif #endif /* __STM32F4xx_HAL_UART_H */ /************************ (C) COPYRIGHT STMicroelectronics *****END OF FILE****/ ================================================ FILE: Zelig/mbed/TARGET_NUCLEO_F411RE/stm32f4xx_hal_usart.h ================================================ /** ****************************************************************************** * @file stm32f4xx_hal_usart.h * @author MCD Application Team * @version V1.4.1 * @date 09-October-2015 * @brief Header file of USART HAL module. ****************************************************************************** * @attention * *

© COPYRIGHT(c) 2015 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. * ****************************************************************************** */ /* Define to prevent recursive inclusion -------------------------------------*/ #ifndef __STM32F4xx_HAL_USART_H #define __STM32F4xx_HAL_USART_H #ifdef __cplusplus extern "C" { #endif /* Includes ------------------------------------------------------------------*/ #include "stm32f4xx_hal_def.h" /** @addtogroup STM32F4xx_HAL_Driver * @{ */ /** @addtogroup USART * @{ */ /* Exported types ------------------------------------------------------------*/ /** @defgroup USART_Exported_Types USART Exported Types * @{ */ /** * @brief USART Init Structure definition */ typedef struct { uint32_t BaudRate; /*!< This member configures the Usart communication baud rate. The baud rate is computed using the following formula: - IntegerDivider = ((PCLKx) / (8 * (husart->Init.BaudRate))) - FractionalDivider = ((IntegerDivider - ((uint32_t) IntegerDivider)) * 8) + 0.5 */ uint32_t WordLength; /*!< Specifies the number of data bits transmitted or received in a frame. This parameter can be a value of @ref USART_Word_Length */ uint32_t StopBits; /*!< Specifies the number of stop bits transmitted. This parameter can be a value of @ref USART_Stop_Bits */ uint32_t Parity; /*!< Specifies the parity mode. This parameter can be a value of @ref USART_Parity @note When parity is enabled, the computed parity is inserted at the MSB position of the transmitted data (9th bit when the word length is set to 9 data bits; 8th bit when the word length is set to 8 data bits). */ uint32_t Mode; /*!< Specifies whether the Receive or Transmit mode is enabled or disabled. This parameter can be a value of @ref USART_Mode */ uint32_t CLKPolarity; /*!< Specifies the steady state of the serial clock. This parameter can be a value of @ref USART_Clock_Polarity */ uint32_t CLKPhase; /*!< Specifies the clock transition on which the bit capture is made. This parameter can be a value of @ref USART_Clock_Phase */ uint32_t CLKLastBit; /*!< Specifies whether the clock pulse corresponding to the last transmitted data bit (MSB) has to be output on the SCLK pin in synchronous mode. This parameter can be a value of @ref USART_Last_Bit */ }USART_InitTypeDef; /** * @brief HAL State structures definition */ typedef enum { HAL_USART_STATE_RESET = 0x00, /*!< Peripheral is not yet Initialized */ HAL_USART_STATE_READY = 0x01, /*!< Peripheral Initialized and ready for use */ HAL_USART_STATE_BUSY = 0x02, /*!< an internal process is ongoing */ HAL_USART_STATE_BUSY_TX = 0x12, /*!< Data Transmission process is ongoing */ HAL_USART_STATE_BUSY_RX = 0x22, /*!< Data Reception process is ongoing */ HAL_USART_STATE_BUSY_TX_RX = 0x32, /*!< Data Transmission Reception process is ongoing */ HAL_USART_STATE_TIMEOUT = 0x03, /*!< Timeout state */ HAL_USART_STATE_ERROR = 0x04 /*!< Error */ }HAL_USART_StateTypeDef; /** * @brief USART handle Structure definition */ typedef struct { USART_TypeDef *Instance; /* USART registers base address */ USART_InitTypeDef Init; /* Usart communication parameters */ uint8_t *pTxBuffPtr; /* Pointer to Usart Tx transfer Buffer */ uint16_t TxXferSize; /* Usart Tx Transfer size */ __IO uint16_t TxXferCount; /* Usart Tx Transfer Counter */ uint8_t *pRxBuffPtr; /* Pointer to Usart Rx transfer Buffer */ uint16_t RxXferSize; /* Usart Rx Transfer size */ __IO uint16_t RxXferCount; /* Usart Rx Transfer Counter */ DMA_HandleTypeDef *hdmatx; /* Usart Tx DMA Handle parameters */ DMA_HandleTypeDef *hdmarx; /* Usart Rx DMA Handle parameters */ HAL_LockTypeDef Lock; /* Locking object */ __IO HAL_USART_StateTypeDef State; /* Usart communication state */ __IO uint32_t ErrorCode; /* USART Error code */ }USART_HandleTypeDef; /** * @} */ /* Exported constants --------------------------------------------------------*/ /** @defgroup USART_Exported_Constants USART Exported Constants * @{ */ /** @defgroup USART_Error_Code USART Error Code * @brief USART Error Code * @{ */ #define HAL_USART_ERROR_NONE ((uint32_t)0x00000000) /*!< No error */ #define HAL_USART_ERROR_PE ((uint32_t)0x00000001) /*!< Parity error */ #define HAL_USART_ERROR_NE ((uint32_t)0x00000002) /*!< Noise error */ #define HAL_USART_ERROR_FE ((uint32_t)0x00000004) /*!< Frame error */ #define HAL_USART_ERROR_ORE ((uint32_t)0x00000008) /*!< Overrun error */ #define HAL_USART_ERROR_DMA ((uint32_t)0x00000010) /*!< DMA transfer error */ /** * @} */ /** @defgroup USART_Word_Length USART Word Length * @{ */ #define USART_WORDLENGTH_8B ((uint32_t)0x00000000) #define USART_WORDLENGTH_9B ((uint32_t)USART_CR1_M) /** * @} */ /** @defgroup USART_Stop_Bits USART Number of Stop Bits * @{ */ #define USART_STOPBITS_1 ((uint32_t)0x00000000) #define USART_STOPBITS_0_5 ((uint32_t)USART_CR2_STOP_0) #define USART_STOPBITS_2 ((uint32_t)USART_CR2_STOP_1) #define USART_STOPBITS_1_5 ((uint32_t)(USART_CR2_STOP_0 | USART_CR2_STOP_1)) /** * @} */ /** @defgroup USART_Parity USART Parity * @{ */ #define USART_PARITY_NONE ((uint32_t)0x00000000) #define USART_PARITY_EVEN ((uint32_t)USART_CR1_PCE) #define USART_PARITY_ODD ((uint32_t)(USART_CR1_PCE | USART_CR1_PS)) /** * @} */ /** @defgroup USART_Mode USART Mode * @{ */ #define USART_MODE_RX ((uint32_t)USART_CR1_RE) #define USART_MODE_TX ((uint32_t)USART_CR1_TE) #define USART_MODE_TX_RX ((uint32_t)(USART_CR1_TE |USART_CR1_RE)) /** * @} */ /** @defgroup USART_Clock USART Clock * @{ */ #define USART_CLOCK_DISABLE ((uint32_t)0x00000000) #define USART_CLOCK_ENABLE ((uint32_t)USART_CR2_CLKEN) /** * @} */ /** @defgroup USART_Clock_Polarity USART Clock Polarity * @{ */ #define USART_POLARITY_LOW ((uint32_t)0x00000000) #define USART_POLARITY_HIGH ((uint32_t)USART_CR2_CPOL) /** * @} */ /** @defgroup USART_Clock_Phase USART Clock Phase * @{ */ #define USART_PHASE_1EDGE ((uint32_t)0x00000000) #define USART_PHASE_2EDGE ((uint32_t)USART_CR2_CPHA) /** * @} */ /** @defgroup USART_Last_Bit USART Last Bit * @{ */ #define USART_LASTBIT_DISABLE ((uint32_t)0x00000000) #define USART_LASTBIT_ENABLE ((uint32_t)USART_CR2_LBCL) /** * @} */ /** @defgroup USART_NACK_State USART NACK State * @{ */ #define USART_NACK_ENABLE ((uint32_t)USART_CR3_NACK) #define USART_NACK_DISABLE ((uint32_t)0x00000000) /** * @} */ /** @defgroup USART_Flags USART Flags * Elements values convention: 0xXXXX * - 0xXXXX : Flag mask in the SR register * @{ */ #define USART_FLAG_TXE ((uint32_t)0x00000080) #define USART_FLAG_TC ((uint32_t)0x00000040) #define USART_FLAG_RXNE ((uint32_t)0x00000020) #define USART_FLAG_IDLE ((uint32_t)0x00000010) #define USART_FLAG_ORE ((uint32_t)0x00000008) #define USART_FLAG_NE ((uint32_t)0x00000004) #define USART_FLAG_FE ((uint32_t)0x00000002) #define USART_FLAG_PE ((uint32_t)0x00000001) /** * @} */ /** @defgroup USART_Interrupt_definition USART Interrupts Definition * Elements values convention: 0xY000XXXX * - XXXX : Interrupt mask in the XX register * - Y : Interrupt source register (2bits) * - 01: CR1 register * - 10: CR2 register * - 11: CR3 register * * @{ */ #define USART_IT_PE ((uint32_t)(USART_CR1_REG_INDEX << 28 | USART_CR1_PEIE)) #define USART_IT_TXE ((uint32_t)(USART_CR1_REG_INDEX << 28 | USART_CR1_TXEIE)) #define USART_IT_TC ((uint32_t)(USART_CR1_REG_INDEX << 28 | USART_CR1_TCIE)) #define USART_IT_RXNE ((uint32_t)(USART_CR1_REG_INDEX << 28 | USART_CR1_RXNEIE)) #define USART_IT_IDLE ((uint32_t)(USART_CR1_REG_INDEX << 28 | USART_CR1_IDLEIE)) #define USART_IT_LBD ((uint32_t)(USART_CR2_REG_INDEX << 28 | USART_CR2_LBDIE)) #define USART_IT_CTS ((uint32_t)(USART_CR3_REG_INDEX << 28 | USART_CR3_CTSIE)) #define USART_IT_ERR ((uint32_t)(USART_CR3_REG_INDEX << 28 | USART_CR3_EIE)) /** * @} */ /** * @} */ /* Exported macro ------------------------------------------------------------*/ /** @defgroup USART_Exported_Macros USART Exported Macros * @{ */ /** @brief Reset USART handle state * @param __HANDLE__: specifies the USART Handle. * This parameter can be USARTx where x: 1, 2, 3 or 6 to select the USART peripheral. * @retval None */ #define __HAL_USART_RESET_HANDLE_STATE(__HANDLE__) ((__HANDLE__)->State = HAL_USART_STATE_RESET) /** @brief Checks whether the specified Smartcard flag is set or not. * @param __HANDLE__: specifies the USART Handle. * This parameter can be USARTx where x: 1, 2, 3 or 6 to select the USART peripheral. * @param __FLAG__: specifies the flag to check. * This parameter can be one of the following values: * @arg USART_FLAG_TXE: Transmit data register empty flag * @arg USART_FLAG_TC: Transmission Complete flag * @arg USART_FLAG_RXNE: Receive data register not empty flag * @arg USART_FLAG_IDLE: Idle Line detection flag * @arg USART_FLAG_ORE: Overrun Error flag * @arg USART_FLAG_NE: Noise Error flag * @arg USART_FLAG_FE: Framing Error flag * @arg USART_FLAG_PE: Parity Error flag * @retval The new state of __FLAG__ (TRUE or FALSE). */ #define __HAL_USART_GET_FLAG(__HANDLE__, __FLAG__) (((__HANDLE__)->Instance->SR & (__FLAG__)) == (__FLAG__)) /** @brief Clears the specified Smartcard pending flags. * @param __HANDLE__: specifies the USART Handle. * This parameter can be USARTx where x: 1, 2, 3 or 6 to select the USART peripheral. * @param __FLAG__: specifies the flag to check. * This parameter can be any combination of the following values: * @arg USART_FLAG_TC: Transmission Complete flag. * @arg USART_FLAG_RXNE: Receive data register not empty flag. * * @note PE (Parity error), FE (Framing error), NE (Noise error), ORE (Overrun * error) and IDLE (Idle line detected) flags are cleared by software * sequence: a read operation to USART_SR register followed by a read * operation to USART_DR register. * @note RXNE flag can be also cleared by a read to the USART_DR register. * @note TC flag can be also cleared by software sequence: a read operation to * USART_SR register followed by a write operation to USART_DR register. * @note TXE flag is cleared only by a write to the USART_DR register. * * @retval None */ #define __HAL_USART_CLEAR_FLAG(__HANDLE__, __FLAG__) ((__HANDLE__)->Instance->SR = ~(__FLAG__)) /** @brief Clear the USART PE pending flag. * @param __HANDLE__: specifies the USART Handle. * This parameter can be USARTx where x: 1, 2, 3 or 6 to select the USART peripheral. * @retval None */ #define __HAL_USART_CLEAR_PEFLAG(__HANDLE__) \ do{ \ __IO uint32_t tmpreg; \ tmpreg = (__HANDLE__)->Instance->SR; \ tmpreg = (__HANDLE__)->Instance->DR; \ UNUSED(tmpreg); \ } while(0) /** @brief Clear the USART FE pending flag. * @param __HANDLE__: specifies the USART Handle. * This parameter can be USARTx where x: 1, 2, 3 or 6 to select the USART peripheral. * @retval None */ #define __HAL_USART_CLEAR_FEFLAG(__HANDLE__) __HAL_USART_CLEAR_PEFLAG(__HANDLE__) /** @brief Clear the USART NE pending flag. * @param __HANDLE__: specifies the USART Handle. * This parameter can be USARTx where x: 1, 2, 3 or 6 to select the USART peripheral. * @retval None */ #define __HAL_USART_CLEAR_NEFLAG(__HANDLE__) __HAL_USART_CLEAR_PEFLAG(__HANDLE__) /** @brief Clear the UART ORE pending flag. * @param __HANDLE__: specifies the USART Handle. * This parameter can be USARTx where x: 1, 2, 3 or 6 to select the USART peripheral. * @retval None */ #define __HAL_USART_CLEAR_OREFLAG(__HANDLE__) __HAL_USART_CLEAR_PEFLAG(__HANDLE__) /** @brief Clear the USART IDLE pending flag. * @param __HANDLE__: specifies the USART Handle. * This parameter can be USARTx where x: 1, 2, 3 or 6 to select the USART peripheral. * @retval None */ #define __HAL_USART_CLEAR_IDLEFLAG(__HANDLE__) __HAL_USART_CLEAR_PEFLAG(__HANDLE__) /** @brief Enables or disables the specified USART interrupts. * @param __HANDLE__: specifies the USART Handle. * This parameter can be USARTx where x: 1, 2, 3 or 6 to select the USART peripheral. * @param __INTERRUPT__: specifies the USART interrupt source to check. * This parameter can be one of the following values: * @arg USART_IT_TXE: Transmit Data Register empty interrupt * @arg USART_IT_TC: Transmission complete interrupt * @arg USART_IT_RXNE: Receive Data register not empty interrupt * @arg USART_IT_IDLE: Idle line detection interrupt * @arg USART_IT_PE: Parity Error interrupt * @arg USART_IT_ERR: Error interrupt(Frame error, noise error, overrun error) * This parameter can be: ENABLE or DISABLE. * @retval None */ #define __HAL_USART_ENABLE_IT(__HANDLE__, __INTERRUPT__) ((((__INTERRUPT__) >> 28) == 1)? ((__HANDLE__)->Instance->CR1 |= ((__INTERRUPT__) & USART_IT_MASK)): \ (((__INTERRUPT__) >> 28) == 2)? ((__HANDLE__)->Instance->CR2 |= ((__INTERRUPT__) & USART_IT_MASK)): \ ((__HANDLE__)->Instance->CR3 |= ((__INTERRUPT__) & USART_IT_MASK))) #define __HAL_USART_DISABLE_IT(__HANDLE__, __INTERRUPT__) ((((__INTERRUPT__) >> 28) == 1)? ((__HANDLE__)->Instance->CR1 &= ~((__INTERRUPT__) & USART_IT_MASK)): \ (((__INTERRUPT__) >> 28) == 2)? ((__HANDLE__)->Instance->CR2 &= ~((__INTERRUPT__) & USART_IT_MASK)): \ ((__HANDLE__)->Instance->CR3 &= ~ ((__INTERRUPT__) & USART_IT_MASK))) /** @brief Checks whether the specified USART interrupt has occurred or not. * @param __HANDLE__: specifies the USART Handle. * This parameter can be USARTx where x: 1, 2, 3 or 6 to select the USART peripheral. * @param __IT__: specifies the USART interrupt source to check. * This parameter can be one of the following values: * @arg USART_IT_TXE: Transmit Data Register empty interrupt * @arg USART_IT_TC: Transmission complete interrupt * @arg USART_IT_RXNE: Receive Data register not empty interrupt * @arg USART_IT_IDLE: Idle line detection interrupt * @arg USART_IT_ERR: Error interrupt * @arg USART_IT_PE: Parity Error interrupt * @retval The new state of __IT__ (TRUE or FALSE). */ #define __HAL_USART_GET_IT_SOURCE(__HANDLE__, __IT__) (((((__IT__) >> 28) == 1)? (__HANDLE__)->Instance->CR1:(((((uint32_t)(__IT__)) >> 28) == 2)? \ (__HANDLE__)->Instance->CR2 : (__HANDLE__)->Instance->CR3)) & (((uint32_t)(__IT__)) & USART_IT_MASK)) /** @brief Macro to enable the USART's one bit sample method * @param __HANDLE__: specifies the USART Handle. * @retval None */ #define __HAL_USART_ONE_BIT_SAMPLE_ENABLE(__HANDLE__) ((__HANDLE__)->Instance->CR3|= USART_CR3_ONEBIT) /** @brief Macro to disable the USART's one bit sample method * @param __HANDLE__: specifies the USART Handle. * @retval None */ #define __HAL_USART_ONE_BIT_SAMPLE_DISABLE(__HANDLE__) ((__HANDLE__)->Instance->CR3 &= (uint16_t)~((uint16_t)USART_CR3_ONEBIT)) /** @brief Enable USART * @param __HANDLE__: specifies the USART Handle. * USART Handle selects the USARTx peripheral (USART availability and x value depending on device). * @retval None */ #define __HAL_USART_ENABLE(__HANDLE__) ( (__HANDLE__)->Instance->CR1 |= USART_CR1_UE) /** @brief Disable USART * @param __HANDLE__: specifies the USART Handle. * USART Handle selects the USARTx peripheral (USART availability and x value depending on device). * @retval None */ #define __HAL_USART_DISABLE(__HANDLE__) ( (__HANDLE__)->Instance->CR1 &= ~USART_CR1_UE) /** * @} */ /* Exported functions --------------------------------------------------------*/ /** @addtogroup USART_Exported_Functions * @{ */ /** @addtogroup USART_Exported_Functions_Group1 * @{ */ /* Initialization/de-initialization functions **********************************/ HAL_StatusTypeDef HAL_USART_Init(USART_HandleTypeDef *husart); HAL_StatusTypeDef HAL_USART_DeInit(USART_HandleTypeDef *husart); void HAL_USART_MspInit(USART_HandleTypeDef *husart); void HAL_USART_MspDeInit(USART_HandleTypeDef *husart); /** * @} */ /** @addtogroup USART_Exported_Functions_Group2 * @{ */ /* IO operation functions *******************************************************/ HAL_StatusTypeDef HAL_USART_Transmit(USART_HandleTypeDef *husart, uint8_t *pTxData, uint16_t Size, uint32_t Timeout); HAL_StatusTypeDef HAL_USART_Receive(USART_HandleTypeDef *husart, uint8_t *pRxData, uint16_t Size, uint32_t Timeout); HAL_StatusTypeDef HAL_USART_TransmitReceive(USART_HandleTypeDef *husart, uint8_t *pTxData, uint8_t *pRxData, uint16_t Size, uint32_t Timeout); HAL_StatusTypeDef HAL_USART_Transmit_IT(USART_HandleTypeDef *husart, uint8_t *pTxData, uint16_t Size); HAL_StatusTypeDef HAL_USART_Receive_IT(USART_HandleTypeDef *husart, uint8_t *pRxData, uint16_t Size); HAL_StatusTypeDef HAL_USART_TransmitReceive_IT(USART_HandleTypeDef *husart, uint8_t *pTxData, uint8_t *pRxData, uint16_t Size); HAL_StatusTypeDef HAL_USART_Transmit_DMA(USART_HandleTypeDef *husart, uint8_t *pTxData, uint16_t Size); HAL_StatusTypeDef HAL_USART_Receive_DMA(USART_HandleTypeDef *husart, uint8_t *pRxData, uint16_t Size); HAL_StatusTypeDef HAL_USART_TransmitReceive_DMA(USART_HandleTypeDef *husart, uint8_t *pTxData, uint8_t *pRxData, uint16_t Size); HAL_StatusTypeDef HAL_USART_DMAPause(USART_HandleTypeDef *husart); HAL_StatusTypeDef HAL_USART_DMAResume(USART_HandleTypeDef *husart); HAL_StatusTypeDef HAL_USART_DMAStop(USART_HandleTypeDef *husart); void HAL_USART_IRQHandler(USART_HandleTypeDef *husart); void HAL_USART_TxCpltCallback(USART_HandleTypeDef *husart); void HAL_USART_TxHalfCpltCallback(USART_HandleTypeDef *husart); void HAL_USART_RxCpltCallback(USART_HandleTypeDef *husart); void HAL_USART_RxHalfCpltCallback(USART_HandleTypeDef *husart); void HAL_USART_TxRxCpltCallback(USART_HandleTypeDef *husart); void HAL_USART_ErrorCallback(USART_HandleTypeDef *husart); /** * @} */ /** @addtogroup USART_Exported_Functions_Group3 * @{ */ /* Peripheral State functions ************************************************/ HAL_USART_StateTypeDef HAL_USART_GetState(USART_HandleTypeDef *husart); uint32_t HAL_USART_GetError(USART_HandleTypeDef *husart); /** * @} */ /** * @} */ /* Private types -------------------------------------------------------------*/ /* Private variables ---------------------------------------------------------*/ /* Private constants ---------------------------------------------------------*/ /** @defgroup USART_Private_Constants USART Private Constants * @{ */ /** @brief USART interruptions flag mask * */ #define USART_IT_MASK ((uint32_t) USART_CR1_PEIE | USART_CR1_TXEIE | USART_CR1_TCIE | USART_CR1_RXNEIE | \ USART_CR1_IDLEIE | USART_CR2_LBDIE | USART_CR3_CTSIE | USART_CR3_EIE ) #define USART_CR1_REG_INDEX 1 #define USART_CR2_REG_INDEX 2 #define USART_CR3_REG_INDEX 3 /** * @} */ /* Private macros ------------------------------------------------------------*/ /** @defgroup USART_Private_Macros USART Private Macros * @{ */ #define IS_USART_NACK_STATE(NACK) (((NACK) == USART_NACK_ENABLE) || \ ((NACK) == USART_NACK_DISABLE)) #define IS_USART_LASTBIT(LASTBIT) (((LASTBIT) == USART_LASTBIT_DISABLE) || \ ((LASTBIT) == USART_LASTBIT_ENABLE)) #define IS_USART_PHASE(CPHA) (((CPHA) == USART_PHASE_1EDGE) || ((CPHA) == USART_PHASE_2EDGE)) #define IS_USART_POLARITY(CPOL) (((CPOL) == USART_POLARITY_LOW) || ((CPOL) == USART_POLARITY_HIGH)) #define IS_USART_CLOCK(CLOCK) (((CLOCK) == USART_CLOCK_DISABLE) || \ ((CLOCK) == USART_CLOCK_ENABLE)) #define IS_USART_WORD_LENGTH(LENGTH) (((LENGTH) == USART_WORDLENGTH_8B) || \ ((LENGTH) == USART_WORDLENGTH_9B)) #define IS_USART_STOPBITS(STOPBITS) (((STOPBITS) == USART_STOPBITS_1) || \ ((STOPBITS) == USART_STOPBITS_0_5) || \ ((STOPBITS) == USART_STOPBITS_1_5) || \ ((STOPBITS) == USART_STOPBITS_2)) #define IS_USART_PARITY(PARITY) (((PARITY) == USART_PARITY_NONE) || \ ((PARITY) == USART_PARITY_EVEN) || \ ((PARITY) == USART_PARITY_ODD)) #define IS_USART_MODE(MODE) ((((MODE) & (uint32_t)0xFFF3) == 0x00) && ((MODE) != (uint32_t)0x00)) #define IS_USART_BAUDRATE(BAUDRATE) ((BAUDRATE) < 10500001) #define USART_DIV(_PCLK_, _BAUD_) (((_PCLK_)*25)/(2*(_BAUD_))) #define USART_DIVMANT(_PCLK_, _BAUD_) (USART_DIV((_PCLK_), (_BAUD_))/100) #define USART_DIVFRAQ(_PCLK_, _BAUD_) (((USART_DIV((_PCLK_), (_BAUD_)) - (USART_DIVMANT((_PCLK_), (_BAUD_)) * 100)) * 16 + 50) / 100) #define USART_BRR(_PCLK_, _BAUD_) ((USART_DIVMANT((_PCLK_), (_BAUD_)) << 4)|(USART_DIVFRAQ((_PCLK_), (_BAUD_)) & 0x0F)) /** * @} */ /* Private functions ---------------------------------------------------------*/ /** @defgroup USART_Private_Functions USART Private Functions * @{ */ /** * @} */ /** * @} */ /** * @} */ #ifdef __cplusplus } #endif #endif /* __STM32F4xx_HAL_USART_H */ /************************ (C) COPYRIGHT STMicroelectronics *****END OF FILE****/ ================================================ FILE: Zelig/mbed/TARGET_NUCLEO_F411RE/stm32f4xx_hal_wwdg.h ================================================ /** ****************************************************************************** * @file stm32f4xx_hal_wwdg.h * @author MCD Application Team * @version V1.4.1 * @date 09-October-2015 * @brief Header file of WWDG HAL module. ****************************************************************************** * @attention * *

© COPYRIGHT(c) 2015 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. * ****************************************************************************** */ /* Define to prevent recursive inclusion -------------------------------------*/ #ifndef __STM32F4xx_HAL_WWDG_H #define __STM32F4xx_HAL_WWDG_H #ifdef __cplusplus extern "C" { #endif /* Includes ------------------------------------------------------------------*/ #include "stm32f4xx_hal_def.h" /** @addtogroup STM32F4xx_HAL_Driver * @{ */ /** @addtogroup WWDG * @{ */ /* Exported types ------------------------------------------------------------*/ /** @defgroup WWDG_Exported_Types WWDG Exported Types * @{ */ /** * @brief WWDG HAL State Structure definition */ typedef enum { HAL_WWDG_STATE_RESET = 0x00, /*!< WWDG not yet initialized or disabled */ HAL_WWDG_STATE_READY = 0x01, /*!< WWDG initialized and ready for use */ HAL_WWDG_STATE_BUSY = 0x02, /*!< WWDG internal process is ongoing */ HAL_WWDG_STATE_TIMEOUT = 0x03, /*!< WWDG timeout state */ HAL_WWDG_STATE_ERROR = 0x04 /*!< WWDG error state */ }HAL_WWDG_StateTypeDef; /** * @brief WWDG Init structure definition */ typedef struct { uint32_t Prescaler; /*!< Specifies the prescaler value of the WWDG. This parameter can be a value of @ref WWDG_Prescaler */ uint32_t Window; /*!< Specifies the WWDG window value to be compared to the downcounter. This parameter must be a number lower than Max_Data = 0x80 */ uint32_t Counter; /*!< Specifies the WWDG free-running downcounter value. This parameter must be a number between Min_Data = 0x40 and Max_Data = 0x7F */ }WWDG_InitTypeDef; /** * @brief WWDG handle Structure definition */ typedef struct { WWDG_TypeDef *Instance; /*!< Register base address */ WWDG_InitTypeDef Init; /*!< WWDG required parameters */ HAL_LockTypeDef Lock; /*!< WWDG locking object */ __IO HAL_WWDG_StateTypeDef State; /*!< WWDG communication state */ }WWDG_HandleTypeDef; /** * @} */ /* Exported constants --------------------------------------------------------*/ /** @defgroup WWDG_Exported_Constants WWDG Exported Constants * @{ */ /** @defgroup WWDG_Interrupt_definition WWDG Interrupt definition * @{ */ #define WWDG_IT_EWI WWDG_CFR_EWI /*!< Early wakeup interrupt */ /** * @} */ /** @defgroup WWDG_Flag_definition WWDG Flag definition * @brief WWDG Flag definition * @{ */ #define WWDG_FLAG_EWIF WWDG_SR_EWIF /*!< Early wakeup interrupt flag */ /** * @} */ /** @defgroup WWDG_Prescaler WWDG Prescaler * @{ */ #define WWDG_PRESCALER_1 ((uint32_t)0x00000000) /*!< WWDG counter clock = (PCLK1/4096)/1 */ #define WWDG_PRESCALER_2 WWDG_CFR_WDGTB0 /*!< WWDG counter clock = (PCLK1/4096)/2 */ #define WWDG_PRESCALER_4 WWDG_CFR_WDGTB1 /*!< WWDG counter clock = (PCLK1/4096)/4 */ #define WWDG_PRESCALER_8 WWDG_CFR_WDGTB /*!< WWDG counter clock = (PCLK1/4096)/8 */ /** * @} */ /** * @} */ /* Exported macro ------------------------------------------------------------*/ /** @defgroup WWDG_Exported_Macros WWDG Exported Macros * @{ */ /** @brief Reset WWDG handle state * @param __HANDLE__: WWDG handle * @retval None */ #define __HAL_WWDG_RESET_HANDLE_STATE(__HANDLE__) ((__HANDLE__)->State = HAL_WWDG_STATE_RESET) /** * @brief Enables the WWDG peripheral. * @param __HANDLE__: WWDG handle * @retval None */ #define __HAL_WWDG_ENABLE(__HANDLE__) SET_BIT((__HANDLE__)->Instance->CR, WWDG_CR_WDGA) /** * @brief Disables the WWDG peripheral. * @param __HANDLE__: WWDG handle * @note WARNING: This is a dummy macro for HAL code alignment. * Once enable, WWDG Peripheral cannot be disabled except by a system reset. * @retval None */ #define __HAL_WWDG_DISABLE(__HANDLE__) /* dummy macro */ /** * @brief Gets the selected WWDG's it status. * @param __HANDLE__: WWDG handle * @param __INTERRUPT__: specifies the it to check. * This parameter can be one of the following values: * @arg WWDG_FLAG_EWIF: Early wakeup interrupt IT * @retval The new state of WWDG_FLAG (SET or RESET). */ #define __HAL_WWDG_GET_IT(__HANDLE__, __INTERRUPT__) __HAL_WWDG_GET_FLAG((__HANDLE__),(__INTERRUPT__)) /** @brief Clear the WWDG's interrupt pending bits * bits to clear the selected interrupt pending bits. * @param __HANDLE__: WWDG handle * @param __INTERRUPT__: specifies the interrupt pending bit to clear. * This parameter can be one of the following values: * @arg WWDG_FLAG_EWIF: Early wakeup interrupt flag */ #define __HAL_WWDG_CLEAR_IT(__HANDLE__, __INTERRUPT__) __HAL_WWDG_CLEAR_FLAG((__HANDLE__), (__INTERRUPT__)) /** * @brief Enables the WWDG early wakeup interrupt. * @param __HANDLE__: WWDG handle * @param __INTERRUPT__: specifies the interrupt to enable. * This parameter can be one of the following values: * @arg WWDG_IT_EWI: Early wakeup interrupt * @note Once enabled this interrupt cannot be disabled except by a system reset. * @retval None */ #define __HAL_WWDG_ENABLE_IT(__HANDLE__, __INTERRUPT__) SET_BIT((__HANDLE__)->Instance->CFR, (__INTERRUPT__)) /** * @brief Disables the WWDG early wakeup interrupt. * @param __HANDLE__: WWDG handle * @param __INTERRUPT__: specifies the interrupt to disable. * This parameter can be one of the following values: * @arg WWDG_IT_EWI: Early wakeup interrupt * @note WARNING: This is a dummy macro for HAL code alignment. * Once enabled this interrupt cannot be disabled except by a system reset. * @retval None */ #define __HAL_WWDG_DISABLE_IT(__HANDLE__, __INTERRUPT__) /* dummy macro */ /** * @brief Gets the selected WWDG's flag status. * @param __HANDLE__: WWDG handle * @param __FLAG__: specifies the flag to check. * This parameter can be one of the following values: * @arg WWDG_FLAG_EWIF: Early wakeup interrupt flag * @retval The new state of WWDG_FLAG (SET or RESET). */ #define __HAL_WWDG_GET_FLAG(__HANDLE__, __FLAG__) (((__HANDLE__)->Instance->SR & (__FLAG__)) == (__FLAG__)) /** * @brief Clears the WWDG's pending flags. * @param __HANDLE__: WWDG handle * @param __FLAG__: specifies the flag to clear. * This parameter can be one of the following values: * @arg WWDG_FLAG_EWIF: Early wakeup interrupt flag * @retval None */ #define __HAL_WWDG_CLEAR_FLAG(__HANDLE__, __FLAG__) (((__HANDLE__)->Instance->SR) = ~(__FLAG__)) /** @brief Checks if the specified WWDG interrupt source is enabled or disabled. * @param __HANDLE__: WWDG Handle. * @param __INTERRUPT__: specifies the WWDG interrupt source to check. * This parameter can be one of the following values: * @arg WWDG_IT_EWI: Early Wakeup Interrupt * @retval state of __INTERRUPT__ (TRUE or FALSE). */ #define __HAL_WWDG_GET_IT_SOURCE(__HANDLE__, __INTERRUPT__) (((__HANDLE__)->Instance->CFR & (__INTERRUPT__)) == (__INTERRUPT__)) /** * @} */ /* Exported functions --------------------------------------------------------*/ /** @addtogroup WWDG_Exported_Functions * @{ */ /** @addtogroup WWDG_Exported_Functions_Group1 * @{ */ /* Initialization/de-initialization functions **********************************/ HAL_StatusTypeDef HAL_WWDG_Init(WWDG_HandleTypeDef *hwwdg); HAL_StatusTypeDef HAL_WWDG_DeInit(WWDG_HandleTypeDef *hwwdg); void HAL_WWDG_MspInit(WWDG_HandleTypeDef *hwwdg); void HAL_WWDG_MspDeInit(WWDG_HandleTypeDef *hwwdg); void HAL_WWDG_WakeupCallback(WWDG_HandleTypeDef* hwwdg); /** * @} */ /** @addtogroup WWDG_Exported_Functions_Group2 * @{ */ /* I/O operation functions ******************************************************/ HAL_StatusTypeDef HAL_WWDG_Start(WWDG_HandleTypeDef *hwwdg); HAL_StatusTypeDef HAL_WWDG_Start_IT(WWDG_HandleTypeDef *hwwdg); HAL_StatusTypeDef HAL_WWDG_Refresh(WWDG_HandleTypeDef *hwwdg, uint32_t Counter); void HAL_WWDG_IRQHandler(WWDG_HandleTypeDef *hwwdg); /** * @} */ /** @addtogroup WWDG_Exported_Functions_Group3 * @{ */ /* Peripheral State functions **************************************************/ HAL_WWDG_StateTypeDef HAL_WWDG_GetState(WWDG_HandleTypeDef *hwwdg); /** * @} */ /** * @} */ /* Private types -------------------------------------------------------------*/ /* Private variables ---------------------------------------------------------*/ /* Private constants ---------------------------------------------------------*/ /** @defgroup WWDG_Private_Constants WWDG Private Constants * @{ */ /** @defgroup WWDG_BitAddress_AliasRegion WWDG BitAddress * @brief WWDG registers bit address in the alias region * @{ */ /* --- CFR Register ---*/ /* Alias word address of EWI bit */ #define WWDG_CFR_BASE (uint32_t)(WWDG_BASE + 0x04) /** * @} */ /** * @} */ /* Private macros ------------------------------------------------------------*/ /** @defgroup WWDG_Private_Macros WWDG Private Macros * @{ */ #define IS_WWDG_PRESCALER(__PRESCALER__) (((__PRESCALER__) == WWDG_PRESCALER_1) || \ ((__PRESCALER__) == WWDG_PRESCALER_2) || \ ((__PRESCALER__) == WWDG_PRESCALER_4) || \ ((__PRESCALER__) == WWDG_PRESCALER_8)) #define IS_WWDG_WINDOW(__WINDOW__) ((__WINDOW__) <= 0x7F) #define IS_WWDG_COUNTER(__COUNTER__) (((__COUNTER__) >= 0x40) && ((__COUNTER__) <= 0x7F)) /** * @} */ /* Private functions ---------------------------------------------------------*/ /** @defgroup WWDG_Private_Functions WWDG Private Functions * @{ */ /** * @} */ /** * @} */ /** * @} */ #ifdef __cplusplus } #endif #endif /* __STM32F4xx_HAL_WWDG_H */ /************************ (C) COPYRIGHT STMicroelectronics *****END OF FILE****/ ================================================ FILE: Zelig/mbed/TARGET_NUCLEO_F411RE/stm32f4xx_ll_fmc.h ================================================ /** ****************************************************************************** * @file stm32f4xx_ll_fmc.h * @author MCD Application Team * @version V1.4.1 * @date 09-October-2015 * @brief Header file of FMC HAL module. ****************************************************************************** * @attention * *

© COPYRIGHT(c) 2015 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. * ****************************************************************************** */ /* Define to prevent recursive inclusion -------------------------------------*/ #ifndef __STM32F4xx_LL_FMC_H #define __STM32F4xx_LL_FMC_H #ifdef __cplusplus extern "C" { #endif /* Includes ------------------------------------------------------------------*/ #include "stm32f4xx_hal_def.h" /** @addtogroup STM32F4xx_HAL_Driver * @{ */ /** @addtogroup FMC_LL * @{ */ #if defined(STM32F427xx) || defined(STM32F437xx) || defined(STM32F429xx) || defined(STM32F439xx) ||\ defined(STM32F446xx) || defined(STM32F469xx) || defined(STM32F479xx) /* Private types -------------------------------------------------------------*/ /** @defgroup FMC_LL_Private_Types FMC Private Types * @{ */ /** * @brief FMC NORSRAM Configuration Structure definition */ typedef struct { uint32_t NSBank; /*!< Specifies the NORSRAM memory device that will be used. This parameter can be a value of @ref FMC_NORSRAM_Bank */ uint32_t DataAddressMux; /*!< Specifies whether the address and data values are multiplexed on the data bus or not. This parameter can be a value of @ref FMC_Data_Address_Bus_Multiplexing */ uint32_t MemoryType; /*!< Specifies the type of external memory attached to the corresponding memory device. This parameter can be a value of @ref FMC_Memory_Type */ uint32_t MemoryDataWidth; /*!< Specifies the external memory device width. This parameter can be a value of @ref FMC_NORSRAM_Data_Width */ uint32_t BurstAccessMode; /*!< Enables or disables the burst access mode for Flash memory, valid only with synchronous burst Flash memories. This parameter can be a value of @ref FMC_Burst_Access_Mode */ uint32_t WaitSignalPolarity; /*!< Specifies the wait signal polarity, valid only when accessing the Flash memory in burst mode. This parameter can be a value of @ref FMC_Wait_Signal_Polarity */ uint32_t WrapMode; /*!< Enables or disables the Wrapped burst access mode for Flash memory, valid only when accessing Flash memories in burst mode. This parameter can be a value of @ref FMC_Wrap_Mode This mode is not available for the STM32F446/467/479xx devices */ uint32_t WaitSignalActive; /*!< Specifies if the wait signal is asserted by the memory one clock cycle before the wait state or during the wait state, valid only when accessing memories in burst mode. This parameter can be a value of @ref FMC_Wait_Timing */ uint32_t WriteOperation; /*!< Enables or disables the write operation in the selected device by the FMC. This parameter can be a value of @ref FMC_Write_Operation */ uint32_t WaitSignal; /*!< Enables or disables the wait state insertion via wait signal, valid for Flash memory access in burst mode. This parameter can be a value of @ref FMC_Wait_Signal */ uint32_t ExtendedMode; /*!< Enables or disables the extended mode. This parameter can be a value of @ref FMC_Extended_Mode */ uint32_t AsynchronousWait; /*!< Enables or disables wait signal during asynchronous transfers, valid only with asynchronous Flash memories. This parameter can be a value of @ref FMC_AsynchronousWait */ uint32_t WriteBurst; /*!< Enables or disables the write burst operation. This parameter can be a value of @ref FMC_Write_Burst */ uint32_t ContinuousClock; /*!< Enables or disables the FMC clock output to external memory devices. This parameter is only enabled through the FMC_BCR1 register, and don't care through FMC_BCR2..4 registers. This parameter can be a value of @ref FMC_Continous_Clock */ uint32_t WriteFifo; /*!< Enables or disables the write FIFO used by the FMC controller. This parameter is only enabled through the FMC_BCR1 register, and don't care through FMC_BCR2..4 registers. This parameter can be a value of @ref FMC_Write_FIFO This mode is available only for the STM32F446/469/479xx devices */ uint32_t PageSize; /*!< Specifies the memory page size. This parameter can be a value of @ref FMC_Page_Size This mode is available only for the STM32F446xx devices */ }FMC_NORSRAM_InitTypeDef; /** * @brief FMC NORSRAM Timing parameters structure definition */ typedef struct { uint32_t AddressSetupTime; /*!< Defines the number of HCLK cycles to configure the duration of the address setup time. This parameter can be a value between Min_Data = 0 and Max_Data = 15. @note This parameter is not used with synchronous NOR Flash memories. */ uint32_t AddressHoldTime; /*!< Defines the number of HCLK cycles to configure the duration of the address hold time. This parameter can be a value between Min_Data = 1 and Max_Data = 15. @note This parameter is not used with synchronous NOR Flash memories. */ uint32_t DataSetupTime; /*!< Defines the number of HCLK cycles to configure the duration of the data setup time. This parameter can be a value between Min_Data = 1 and Max_Data = 255. @note This parameter is used for SRAMs, ROMs and asynchronous multiplexed NOR Flash memories. */ uint32_t BusTurnAroundDuration; /*!< Defines the number of HCLK cycles to configure the duration of the bus turnaround. This parameter can be a value between Min_Data = 0 and Max_Data = 15. @note This parameter is only used for multiplexed NOR Flash memories. */ uint32_t CLKDivision; /*!< Defines the period of CLK clock output signal, expressed in number of HCLK cycles. This parameter can be a value between Min_Data = 2 and Max_Data = 16. @note This parameter is not used for asynchronous NOR Flash, SRAM or ROM accesses. */ uint32_t DataLatency; /*!< Defines the number of memory clock cycles to issue to the memory before getting the first data. The parameter value depends on the memory type as shown below: - It must be set to 0 in case of a CRAM - It is don't care in asynchronous NOR, SRAM or ROM accesses - It may assume a value between Min_Data = 2 and Max_Data = 17 in NOR Flash memories with synchronous burst mode enable */ uint32_t AccessMode; /*!< Specifies the asynchronous access mode. This parameter can be a value of @ref FMC_Access_Mode */ }FMC_NORSRAM_TimingTypeDef; /** * @brief FMC NAND Configuration Structure definition */ typedef struct { uint32_t NandBank; /*!< Specifies the NAND memory device that will be used. This parameter can be a value of @ref FMC_NAND_Bank */ uint32_t Waitfeature; /*!< Enables or disables the Wait feature for the NAND Memory device. This parameter can be any value of @ref FMC_Wait_feature */ uint32_t MemoryDataWidth; /*!< Specifies the external memory device width. This parameter can be any value of @ref FMC_NAND_Data_Width */ uint32_t EccComputation; /*!< Enables or disables the ECC computation. This parameter can be any value of @ref FMC_ECC */ uint32_t ECCPageSize; /*!< Defines the page size for the extended ECC. This parameter can be any value of @ref FMC_ECC_Page_Size */ uint32_t TCLRSetupTime; /*!< Defines the number of HCLK cycles to configure the delay between CLE low and RE low. This parameter can be a value between Min_Data = 0 and Max_Data = 255 */ uint32_t TARSetupTime; /*!< Defines the number of HCLK cycles to configure the delay between ALE low and RE low. This parameter can be a number between Min_Data = 0 and Max_Data = 255 */ }FMC_NAND_InitTypeDef; /** * @brief FMC NAND/PCCARD Timing parameters structure definition */ typedef struct { uint32_t SetupTime; /*!< Defines the number of HCLK cycles to setup address before the command assertion for NAND-Flash read or write access to common/Attribute or I/O memory space (depending on the memory space timing to be configured). This parameter can be a value between Min_Data = 0 and Max_Data = 255 */ uint32_t WaitSetupTime; /*!< Defines the minimum number of HCLK cycles to assert the command for NAND-Flash read or write access to common/Attribute or I/O memory space (depending on the memory space timing to be configured). This parameter can be a number between Min_Data = 0 and Max_Data = 255 */ uint32_t HoldSetupTime; /*!< Defines the number of HCLK clock cycles to hold address (and data for write access) after the command de-assertion for NAND-Flash read or write access to common/Attribute or I/O memory space (depending on the memory space timing to be configured). This parameter can be a number between Min_Data = 0 and Max_Data = 255 */ uint32_t HiZSetupTime; /*!< Defines the number of HCLK clock cycles during which the data bus is kept in HiZ after the start of a NAND-Flash write access to common/Attribute or I/O memory space (depending on the memory space timing to be configured). This parameter can be a number between Min_Data = 0 and Max_Data = 255 */ }FMC_NAND_PCC_TimingTypeDef; /** * @brief FMC NAND Configuration Structure definition */ typedef struct { uint32_t Waitfeature; /*!< Enables or disables the Wait feature for the PCCARD Memory device. This parameter can be any value of @ref FMC_Wait_feature */ uint32_t TCLRSetupTime; /*!< Defines the number of HCLK cycles to configure the delay between CLE low and RE low. This parameter can be a value between Min_Data = 0 and Max_Data = 255 */ uint32_t TARSetupTime; /*!< Defines the number of HCLK cycles to configure the delay between ALE low and RE low. This parameter can be a number between Min_Data = 0 and Max_Data = 255 */ }FMC_PCCARD_InitTypeDef; /** * @brief FMC SDRAM Configuration Structure definition */ typedef struct { uint32_t SDBank; /*!< Specifies the SDRAM memory device that will be used. This parameter can be a value of @ref FMC_SDRAM_Bank */ uint32_t ColumnBitsNumber; /*!< Defines the number of bits of column address. This parameter can be a value of @ref FMC_SDRAM_Column_Bits_number. */ uint32_t RowBitsNumber; /*!< Defines the number of bits of column address. This parameter can be a value of @ref FMC_SDRAM_Row_Bits_number. */ uint32_t MemoryDataWidth; /*!< Defines the memory device width. This parameter can be a value of @ref FMC_SDRAM_Memory_Bus_Width. */ uint32_t InternalBankNumber; /*!< Defines the number of the device's internal banks. This parameter can be of @ref FMC_SDRAM_Internal_Banks_Number. */ uint32_t CASLatency; /*!< Defines the SDRAM CAS latency in number of memory clock cycles. This parameter can be a value of @ref FMC_SDRAM_CAS_Latency. */ uint32_t WriteProtection; /*!< Enables the SDRAM device to be accessed in write mode. This parameter can be a value of @ref FMC_SDRAM_Write_Protection. */ uint32_t SDClockPeriod; /*!< Define the SDRAM Clock Period for both SDRAM devices and they allow to disable the clock before changing frequency. This parameter can be a value of @ref FMC_SDRAM_Clock_Period. */ uint32_t ReadBurst; /*!< This bit enable the SDRAM controller to anticipate the next read commands during the CAS latency and stores data in the Read FIFO. This parameter can be a value of @ref FMC_SDRAM_Read_Burst. */ uint32_t ReadPipeDelay; /*!< Define the delay in system clock cycles on read data path. This parameter can be a value of @ref FMC_SDRAM_Read_Pipe_Delay. */ }FMC_SDRAM_InitTypeDef; /** * @brief FMC SDRAM Timing parameters structure definition */ typedef struct { uint32_t LoadToActiveDelay; /*!< Defines the delay between a Load Mode Register command and an active or Refresh command in number of memory clock cycles. This parameter can be a value between Min_Data = 1 and Max_Data = 16 */ uint32_t ExitSelfRefreshDelay; /*!< Defines the delay from releasing the self refresh command to issuing the Activate command in number of memory clock cycles. This parameter can be a value between Min_Data = 1 and Max_Data = 16 */ uint32_t SelfRefreshTime; /*!< Defines the minimum Self Refresh period in number of memory clock cycles. This parameter can be a value between Min_Data = 1 and Max_Data = 16 */ uint32_t RowCycleDelay; /*!< Defines the delay between the Refresh command and the Activate command and the delay between two consecutive Refresh commands in number of memory clock cycles. This parameter can be a value between Min_Data = 1 and Max_Data = 16 */ uint32_t WriteRecoveryTime; /*!< Defines the Write recovery Time in number of memory clock cycles. This parameter can be a value between Min_Data = 1 and Max_Data = 16 */ uint32_t RPDelay; /*!< Defines the delay between a Precharge Command and an other command in number of memory clock cycles. This parameter can be a value between Min_Data = 1 and Max_Data = 16 */ uint32_t RCDDelay; /*!< Defines the delay between the Activate Command and a Read/Write command in number of memory clock cycles. This parameter can be a value between Min_Data = 1 and Max_Data = 16 */ }FMC_SDRAM_TimingTypeDef; /** * @brief SDRAM command parameters structure definition */ typedef struct { uint32_t CommandMode; /*!< Defines the command issued to the SDRAM device. This parameter can be a value of @ref FMC_SDRAM_Command_Mode. */ uint32_t CommandTarget; /*!< Defines which device (1 or 2) the command will be issued to. This parameter can be a value of @ref FMC_SDRAM_Command_Target. */ uint32_t AutoRefreshNumber; /*!< Defines the number of consecutive auto refresh command issued in auto refresh mode. This parameter can be a value between Min_Data = 1 and Max_Data = 16 */ uint32_t ModeRegisterDefinition; /*!< Defines the SDRAM Mode register content */ }FMC_SDRAM_CommandTypeDef; /** * @} */ /* Private constants ---------------------------------------------------------*/ /** @defgroup FMC_LL_Private_Constants FMC Private Constants * @{ */ /** @defgroup FMC_LL_NOR_SRAM_Controller FMC NOR/SRAM Controller * @{ */ /** @defgroup FMC_NORSRAM_Bank FMC NOR/SRAM Bank * @{ */ #define FMC_NORSRAM_BANK1 ((uint32_t)0x00000000) #define FMC_NORSRAM_BANK2 ((uint32_t)0x00000002) #define FMC_NORSRAM_BANK3 ((uint32_t)0x00000004) #define FMC_NORSRAM_BANK4 ((uint32_t)0x00000006) /** * @} */ /** @defgroup FMC_Data_Address_Bus_Multiplexing FMC Data Address Bus Multiplexing * @{ */ #define FMC_DATA_ADDRESS_MUX_DISABLE ((uint32_t)0x00000000) #define FMC_DATA_ADDRESS_MUX_ENABLE ((uint32_t)0x00000002) /** * @} */ /** @defgroup FMC_Memory_Type FMC Memory Type * @{ */ #define FMC_MEMORY_TYPE_SRAM ((uint32_t)0x00000000) #define FMC_MEMORY_TYPE_PSRAM ((uint32_t)0x00000004) #define FMC_MEMORY_TYPE_NOR ((uint32_t)0x00000008) /** * @} */ /** @defgroup FMC_NORSRAM_Data_Width FMC NORSRAM Data Width * @{ */ #define FMC_NORSRAM_MEM_BUS_WIDTH_8 ((uint32_t)0x00000000) #define FMC_NORSRAM_MEM_BUS_WIDTH_16 ((uint32_t)0x00000010) #define FMC_NORSRAM_MEM_BUS_WIDTH_32 ((uint32_t)0x00000020) /** * @} */ /** @defgroup FMC_NORSRAM_Flash_Access FMC NOR/SRAM Flash Access * @{ */ #define FMC_NORSRAM_FLASH_ACCESS_ENABLE ((uint32_t)0x00000040) #define FMC_NORSRAM_FLASH_ACCESS_DISABLE ((uint32_t)0x00000000) /** * @} */ /** @defgroup FMC_Burst_Access_Mode FMC Burst Access Mode * @{ */ #define FMC_BURST_ACCESS_MODE_DISABLE ((uint32_t)0x00000000) #define FMC_BURST_ACCESS_MODE_ENABLE ((uint32_t)0x00000100) /** * @} */ /** @defgroup FMC_Wait_Signal_Polarity FMC Wait Signal Polarity * @{ */ #define FMC_WAIT_SIGNAL_POLARITY_LOW ((uint32_t)0x00000000) #define FMC_WAIT_SIGNAL_POLARITY_HIGH ((uint32_t)0x00000200) /** * @} */ /** @defgroup FMC_Wrap_Mode FMC Wrap Mode * @{ */ /** @note This mode is not available for the STM32F446/469/479xx devices */ #define FMC_WRAP_MODE_DISABLE ((uint32_t)0x00000000) #define FMC_WRAP_MODE_ENABLE ((uint32_t)0x00000400) /** * @} */ /** @defgroup FMC_Wait_Timing FMC Wait Timing * @{ */ #define FMC_WAIT_TIMING_BEFORE_WS ((uint32_t)0x00000000) #define FMC_WAIT_TIMING_DURING_WS ((uint32_t)0x00000800) /** * @} */ /** @defgroup FMC_Write_Operation FMC Write Operation * @{ */ #define FMC_WRITE_OPERATION_DISABLE ((uint32_t)0x00000000) #define FMC_WRITE_OPERATION_ENABLE ((uint32_t)0x00001000) /** * @} */ /** @defgroup FMC_Wait_Signal FMC Wait Signal * @{ */ #define FMC_WAIT_SIGNAL_DISABLE ((uint32_t)0x00000000) #define FMC_WAIT_SIGNAL_ENABLE ((uint32_t)0x00002000) /** * @} */ /** @defgroup FMC_Extended_Mode FMC Extended Mode * @{ */ #define FMC_EXTENDED_MODE_DISABLE ((uint32_t)0x00000000) #define FMC_EXTENDED_MODE_ENABLE ((uint32_t)0x00004000) /** * @} */ /** @defgroup FMC_AsynchronousWait FMC Asynchronous Wait * @{ */ #define FMC_ASYNCHRONOUS_WAIT_DISABLE ((uint32_t)0x00000000) #define FMC_ASYNCHRONOUS_WAIT_ENABLE ((uint32_t)0x00008000) /** * @} */ /** @defgroup FMC_Page_Size FMC Page Size * @note These values are available only for the STM32F446/469/479xx devices. * @{ */ #define FMC_PAGE_SIZE_NONE ((uint32_t)0x00000000) #define FMC_PAGE_SIZE_128 ((uint32_t)FMC_BCR1_CPSIZE_0) #define FMC_PAGE_SIZE_256 ((uint32_t)FMC_BCR1_CPSIZE_1) #define FMC_PAGE_SIZE_1024 ((uint32_t)FMC_BCR1_CPSIZE_2) /** * @} */ /** @defgroup FMC_Write_FIFO FMC Write FIFO * @note These values are available only for the STM32F446/469/479xx devices. * @{ */ #define FMC_WRITE_FIFO_DISABLE ((uint32_t)0x00000000) #define FMC_WRITE_FIFO_ENABLE ((uint32_t)FMC_BCR1_WFDIS) /** * @} */ /** @defgroup FMC_Write_Burst FMC Write Burst * @{ */ #define FMC_WRITE_BURST_DISABLE ((uint32_t)0x00000000) #define FMC_WRITE_BURST_ENABLE ((uint32_t)0x00080000) /** * @} */ /** @defgroup FMC_Continous_Clock FMC Continuous Clock * @{ */ #define FMC_CONTINUOUS_CLOCK_SYNC_ONLY ((uint32_t)0x00000000) #define FMC_CONTINUOUS_CLOCK_SYNC_ASYNC ((uint32_t)0x00100000) /** * @} */ /** @defgroup FMC_Access_Mode FMC Access Mode * @{ */ #define FMC_ACCESS_MODE_A ((uint32_t)0x00000000) #define FMC_ACCESS_MODE_B ((uint32_t)0x10000000) #define FMC_ACCESS_MODE_C ((uint32_t)0x20000000) #define FMC_ACCESS_MODE_D ((uint32_t)0x30000000) /** * @} */ /** * @} */ /** @defgroup FMC_LL_NAND_Controller FMC NAND Controller * @{ */ /** @defgroup FMC_NAND_Bank FMC NAND Bank * @{ */ #define FMC_NAND_BANK2 ((uint32_t)0x00000010) #define FMC_NAND_BANK3 ((uint32_t)0x00000100) /** * @} */ /** @defgroup FMC_Wait_feature FMC Wait feature * @{ */ #define FMC_NAND_PCC_WAIT_FEATURE_DISABLE ((uint32_t)0x00000000) #define FMC_NAND_PCC_WAIT_FEATURE_ENABLE ((uint32_t)0x00000002) /** * @} */ /** @defgroup FMC_PCR_Memory_Type FMC PCR Memory Type * @{ */ #define FMC_PCR_MEMORY_TYPE_PCCARD ((uint32_t)0x00000000) #define FMC_PCR_MEMORY_TYPE_NAND ((uint32_t)0x00000008) /** * @} */ /** @defgroup FMC_NAND_Data_Width FMC NAND Data Width * @{ */ #define FMC_NAND_PCC_MEM_BUS_WIDTH_8 ((uint32_t)0x00000000) #define FMC_NAND_PCC_MEM_BUS_WIDTH_16 ((uint32_t)0x00000010) /** * @} */ /** @defgroup FMC_ECC FMC ECC * @{ */ #define FMC_NAND_ECC_DISABLE ((uint32_t)0x00000000) #define FMC_NAND_ECC_ENABLE ((uint32_t)0x00000040) /** * @} */ /** @defgroup FMC_ECC_Page_Size FMC ECC Page Size * @{ */ #define FMC_NAND_ECC_PAGE_SIZE_256BYTE ((uint32_t)0x00000000) #define FMC_NAND_ECC_PAGE_SIZE_512BYTE ((uint32_t)0x00020000) #define FMC_NAND_ECC_PAGE_SIZE_1024BYTE ((uint32_t)0x00040000) #define FMC_NAND_ECC_PAGE_SIZE_2048BYTE ((uint32_t)0x00060000) #define FMC_NAND_ECC_PAGE_SIZE_4096BYTE ((uint32_t)0x00080000) #define FMC_NAND_ECC_PAGE_SIZE_8192BYTE ((uint32_t)0x000A0000) /** * @} */ /** * @} */ /** @defgroup FMC_LL_SDRAM_Controller FMC SDRAM Controller * @{ */ /** @defgroup FMC_SDRAM_Bank FMC SDRAM Bank * @{ */ #define FMC_SDRAM_BANK1 ((uint32_t)0x00000000) #define FMC_SDRAM_BANK2 ((uint32_t)0x00000001) /** * @} */ /** @defgroup FMC_SDRAM_Column_Bits_number FMC SDRAM Column Bits number * @{ */ #define FMC_SDRAM_COLUMN_BITS_NUM_8 ((uint32_t)0x00000000) #define FMC_SDRAM_COLUMN_BITS_NUM_9 ((uint32_t)0x00000001) #define FMC_SDRAM_COLUMN_BITS_NUM_10 ((uint32_t)0x00000002) #define FMC_SDRAM_COLUMN_BITS_NUM_11 ((uint32_t)0x00000003) /** * @} */ /** @defgroup FMC_SDRAM_Row_Bits_number FMC SDRAM Row Bits number * @{ */ #define FMC_SDRAM_ROW_BITS_NUM_11 ((uint32_t)0x00000000) #define FMC_SDRAM_ROW_BITS_NUM_12 ((uint32_t)0x00000004) #define FMC_SDRAM_ROW_BITS_NUM_13 ((uint32_t)0x00000008) /** * @} */ /** @defgroup FMC_SDRAM_Memory_Bus_Width FMC SDRAM Memory Bus Width * @{ */ #define FMC_SDRAM_MEM_BUS_WIDTH_8 ((uint32_t)0x00000000) #define FMC_SDRAM_MEM_BUS_WIDTH_16 ((uint32_t)0x00000010) #define FMC_SDRAM_MEM_BUS_WIDTH_32 ((uint32_t)0x00000020) /** * @} */ /** @defgroup FMC_SDRAM_Internal_Banks_Number FMC SDRAM Internal Banks Number * @{ */ #define FMC_SDRAM_INTERN_BANKS_NUM_2 ((uint32_t)0x00000000) #define FMC_SDRAM_INTERN_BANKS_NUM_4 ((uint32_t)0x00000040) /** * @} */ /** @defgroup FMC_SDRAM_CAS_Latency FMC SDRAM CAS Latency * @{ */ #define FMC_SDRAM_CAS_LATENCY_1 ((uint32_t)0x00000080) #define FMC_SDRAM_CAS_LATENCY_2 ((uint32_t)0x00000100) #define FMC_SDRAM_CAS_LATENCY_3 ((uint32_t)0x00000180) /** * @} */ /** @defgroup FMC_SDRAM_Write_Protection FMC SDRAM Write Protection * @{ */ #define FMC_SDRAM_WRITE_PROTECTION_DISABLE ((uint32_t)0x00000000) #define FMC_SDRAM_WRITE_PROTECTION_ENABLE ((uint32_t)0x00000200) /** * @} */ /** @defgroup FMC_SDRAM_Clock_Period FMC SDRAM Clock Period * @{ */ #define FMC_SDRAM_CLOCK_DISABLE ((uint32_t)0x00000000) #define FMC_SDRAM_CLOCK_PERIOD_2 ((uint32_t)0x00000800) #define FMC_SDRAM_CLOCK_PERIOD_3 ((uint32_t)0x00000C00) /** * @} */ /** @defgroup FMC_SDRAM_Read_Burst FMC SDRAM Read Burst * @{ */ #define FMC_SDRAM_RBURST_DISABLE ((uint32_t)0x00000000) #define FMC_SDRAM_RBURST_ENABLE ((uint32_t)0x00001000) /** * @} */ /** @defgroup FMC_SDRAM_Read_Pipe_Delay FMC SDRAM Read Pipe Delay * @{ */ #define FMC_SDRAM_RPIPE_DELAY_0 ((uint32_t)0x00000000) #define FMC_SDRAM_RPIPE_DELAY_1 ((uint32_t)0x00002000) #define FMC_SDRAM_RPIPE_DELAY_2 ((uint32_t)0x00004000) /** * @} */ /** @defgroup FMC_SDRAM_Command_Mode FMC SDRAM Command Mode * @{ */ #define FMC_SDRAM_CMD_NORMAL_MODE ((uint32_t)0x00000000) #define FMC_SDRAM_CMD_CLK_ENABLE ((uint32_t)0x00000001) #define FMC_SDRAM_CMD_PALL ((uint32_t)0x00000002) #define FMC_SDRAM_CMD_AUTOREFRESH_MODE ((uint32_t)0x00000003) #define FMC_SDRAM_CMD_LOAD_MODE ((uint32_t)0x00000004) #define FMC_SDRAM_CMD_SELFREFRESH_MODE ((uint32_t)0x00000005) #define FMC_SDRAM_CMD_POWERDOWN_MODE ((uint32_t)0x00000006) /** * @} */ /** @defgroup FMC_SDRAM_Command_Target FMC SDRAM Command Target * @{ */ #define FMC_SDRAM_CMD_TARGET_BANK2 FMC_SDCMR_CTB2 #define FMC_SDRAM_CMD_TARGET_BANK1 FMC_SDCMR_CTB1 #define FMC_SDRAM_CMD_TARGET_BANK1_2 ((uint32_t)0x00000018) /** * @} */ /** @defgroup FMC_SDRAM_Mode_Status FMC SDRAM Mode Status * @{ */ #define FMC_SDRAM_NORMAL_MODE ((uint32_t)0x00000000) #define FMC_SDRAM_SELF_REFRESH_MODE FMC_SDSR_MODES1_0 #define FMC_SDRAM_POWER_DOWN_MODE FMC_SDSR_MODES1_1 /** * @} */ /** * @} */ /** @defgroup FMC_LL_Interrupt_definition FMC Interrupt definition * @{ */ #define FMC_IT_RISING_EDGE ((uint32_t)0x00000008) #define FMC_IT_LEVEL ((uint32_t)0x00000010) #define FMC_IT_FALLING_EDGE ((uint32_t)0x00000020) #define FMC_IT_REFRESH_ERROR ((uint32_t)0x00004000) /** * @} */ /** @defgroup FMC_LL_Flag_definition FMC Flag definition * @{ */ #define FMC_FLAG_RISING_EDGE ((uint32_t)0x00000001) #define FMC_FLAG_LEVEL ((uint32_t)0x00000002) #define FMC_FLAG_FALLING_EDGE ((uint32_t)0x00000004) #define FMC_FLAG_FEMPT ((uint32_t)0x00000040) #define FMC_SDRAM_FLAG_REFRESH_IT FMC_SDSR_RE #define FMC_SDRAM_FLAG_BUSY FMC_SDSR_BUSY #define FMC_SDRAM_FLAG_REFRESH_ERROR FMC_SDRTR_CRE /** * @} */ /** @defgroup FMC_LL_Alias_definition FMC Alias definition * @{ */ #if defined(STM32F446xx) || defined(STM32F469xx) || defined(STM32F479xx) #define FMC_NAND_TypeDef FMC_Bank3_TypeDef #else #define FMC_NAND_TypeDef FMC_Bank2_3_TypeDef #define FMC_PCCARD_TypeDef FMC_Bank4_TypeDef #endif /* STM32F446xx || STM32F469xx || STM32F479xx */ #define FMC_NORSRAM_TypeDef FMC_Bank1_TypeDef #define FMC_NORSRAM_EXTENDED_TypeDef FMC_Bank1E_TypeDef #define FMC_SDRAM_TypeDef FMC_Bank5_6_TypeDef #if defined(STM32F446xx) || defined(STM32F469xx) || defined(STM32F479xx) #define FMC_NAND_DEVICE FMC_Bank3 #else #define FMC_NAND_DEVICE FMC_Bank2_3 #define FMC_PCCARD_DEVICE FMC_Bank4 #endif /* STM32F446xx || STM32F469xx || STM32F479xx */ #define FMC_NORSRAM_DEVICE FMC_Bank1 #define FMC_NORSRAM_EXTENDED_DEVICE FMC_Bank1E #define FMC_SDRAM_DEVICE FMC_Bank5_6 /** * @} */ /** * @} */ /* Private macro -------------------------------------------------------------*/ /** @defgroup FMC_LL_Private_Macros FMC Private Macros * @{ */ /** @defgroup FMC_LL_NOR_Macros FMC NOR/SRAM Macros * @brief macros to handle NOR device enable/disable and read/write operations * @{ */ /** * @brief Enable the NORSRAM device access. * @param __INSTANCE__: FMC_NORSRAM Instance * @param __BANK__: FMC_NORSRAM Bank * @retval None */ #define __FMC_NORSRAM_ENABLE(__INSTANCE__, __BANK__) ((__INSTANCE__)->BTCR[(__BANK__)] |= FMC_BCR1_MBKEN) /** * @brief Disable the NORSRAM device access. * @param __INSTANCE__: FMC_NORSRAM Instance * @param __BANK__: FMC_NORSRAM Bank * @retval None */ #define __FMC_NORSRAM_DISABLE(__INSTANCE__, __BANK__) ((__INSTANCE__)->BTCR[(__BANK__)] &= ~FMC_BCR1_MBKEN) /** * @} */ /** @defgroup FMC_LL_NAND_Macros FMC NAND Macros * @brief macros to handle NAND device enable/disable * @{ */ #if defined(STM32F446xx) || defined(STM32F469xx) || defined(STM32F479xx) /** * @brief Enable the NAND device access. * @param __INSTANCE__: FMC_NAND Instance * @param __BANK__: FMC_NAND Bank * @retval None */ #define __FMC_NAND_ENABLE(__INSTANCE__, __BANK__) ((__INSTANCE__)->PCR |= FMC_PCR_PBKEN) /** * @brief Disable the NAND device access. * @param __INSTANCE__: FMC_NAND Instance * @param __BANK__: FMC_NAND Bank * @retval None */ #define __FMC_NAND_DISABLE(__INSTANCE__, __BANK__) ((__INSTANCE__)->PCR &= ~FMC_PCR_PBKEN) #else /* defined(STM32F427xx) || defined(STM32F437xx) || defined(STM32F429xx) || defined(STM32F439xx) */ /** * @brief Enable the NAND device access. * @param __INSTANCE__: FMC_NAND Instance * @param __BANK__: FMC_NAND Bank * @retval None */ #define __FMC_NAND_ENABLE(__INSTANCE__, __BANK__) (((__BANK__) == FMC_NAND_BANK2)? ((__INSTANCE__)->PCR2 |= FMC_PCR2_PBKEN): \ ((__INSTANCE__)->PCR3 |= FMC_PCR3_PBKEN)) /** * @brief Disable the NAND device access. * @param __INSTANCE__: FMC_NAND Instance * @param __BANK__: FMC_NAND Bank * @retval None */ #define __FMC_NAND_DISABLE(__INSTANCE__, __BANK__) (((__BANK__) == FMC_NAND_BANK2)? ((__INSTANCE__)->PCR2 &= ~FMC_PCR2_PBKEN): \ ((__INSTANCE__)->PCR3 &= ~FMC_PCR3_PBKEN)) #endif /* defined(STM32F446xx) || defined(STM32F469xx) || defined(STM32F479xx) */ /** * @} */ #if defined(STM32F427xx) || defined(STM32F437xx) || defined(STM32F429xx) || defined(STM32F439xx) /** @defgroup FMC_LL_PCCARD_Macros FMC PCCARD Macros * @brief macros to handle SRAM read/write operations * @{ */ /** * @brief Enable the PCCARD device access. * @param __INSTANCE__: FMC_PCCARD Instance * @retval None */ #define __FMC_PCCARD_ENABLE(__INSTANCE__) ((__INSTANCE__)->PCR4 |= FMC_PCR4_PBKEN) /** * @brief Disable the PCCARD device access. * @param __INSTANCE__: FMC_PCCARD Instance * @retval None */ #define __FMC_PCCARD_DISABLE(__INSTANCE__) ((__INSTANCE__)->PCR4 &= ~FMC_PCR4_PBKEN) /** * @} */ #endif /* defined(STM32F427xx) || defined(STM32F437xx) || defined(STM32F429xx) || defined(STM32F439xx) */ /** @defgroup FMC_LL_Flag_Interrupt_Macros FMC Flag&Interrupt Macros * @brief macros to handle FMC flags and interrupts * @{ */ #if defined(STM32F446xx) || defined(STM32F469xx) || defined(STM32F479xx) /** * @brief Enable the NAND device interrupt. * @param __INSTANCE__: FMC_NAND instance * @param __BANK__: FMC_NAND Bank * @param __INTERRUPT__: FMC_NAND interrupt * This parameter can be any combination of the following values: * @arg FMC_IT_RISING_EDGE: Interrupt rising edge. * @arg FMC_IT_LEVEL: Interrupt level. * @arg FMC_IT_FALLING_EDGE: Interrupt falling edge. * @retval None */ #define __FMC_NAND_ENABLE_IT(__INSTANCE__, __BANK__, __INTERRUPT__) ((__INSTANCE__)->SR |= (__INTERRUPT__)) /** * @brief Disable the NAND device interrupt. * @param __INSTANCE__: FMC_NAND Instance * @param __BANK__: FMC_NAND Bank * @param __INTERRUPT__: FMC_NAND interrupt * This parameter can be any combination of the following values: * @arg FMC_IT_RISING_EDGE: Interrupt rising edge. * @arg FMC_IT_LEVEL: Interrupt level. * @arg FMC_IT_FALLING_EDGE: Interrupt falling edge. * @retval None */ #define __FMC_NAND_DISABLE_IT(__INSTANCE__, __BANK__, __INTERRUPT__) ((__INSTANCE__)->SR &= ~(__INTERRUPT__)) /** * @brief Get flag status of the NAND device. * @param __INSTANCE__: FMC_NAND Instance * @param __BANK__: FMC_NAND Bank * @param __FLAG__: FMC_NAND flag * This parameter can be any combination of the following values: * @arg FMC_FLAG_RISING_EDGE: Interrupt rising edge flag. * @arg FMC_FLAG_LEVEL: Interrupt level edge flag. * @arg FMC_FLAG_FALLING_EDGE: Interrupt falling edge flag. * @arg FMC_FLAG_FEMPT: FIFO empty flag. * @retval The state of FLAG (SET or RESET). */ #define __FMC_NAND_GET_FLAG(__INSTANCE__, __BANK__, __FLAG__) (((__INSTANCE__)->SR &(__FLAG__)) == (__FLAG__)) /** * @brief Clear flag status of the NAND device. * @param __INSTANCE__: FMC_NAND Instance * @param __BANK__: FMC_NAND Bank * @param __FLAG__: FMC_NAND flag * This parameter can be any combination of the following values: * @arg FMC_FLAG_RISING_EDGE: Interrupt rising edge flag. * @arg FMC_FLAG_LEVEL: Interrupt level edge flag. * @arg FMC_FLAG_FALLING_EDGE: Interrupt falling edge flag. * @arg FMC_FLAG_FEMPT: FIFO empty flag. * @retval None */ #define __FMC_NAND_CLEAR_FLAG(__INSTANCE__, __BANK__, __FLAG__) ((__INSTANCE__)->SR &= ~(__FLAG__)) #else /* defined(STM32F427xx) || defined(STM32F437xx) || defined(STM32F429xx) || defined(STM32F439xx) */ /** * @brief Enable the NAND device interrupt. * @param __INSTANCE__: FMC_NAND instance * @param __BANK__: FMC_NAND Bank * @param __INTERRUPT__: FMC_NAND interrupt * This parameter can be any combination of the following values: * @arg FMC_IT_RISING_EDGE: Interrupt rising edge. * @arg FMC_IT_LEVEL: Interrupt level. * @arg FMC_IT_FALLING_EDGE: Interrupt falling edge. * @retval None */ #define __FMC_NAND_ENABLE_IT(__INSTANCE__, __BANK__, __INTERRUPT__) (((__BANK__) == FMC_NAND_BANK2)? ((__INSTANCE__)->SR2 |= (__INTERRUPT__)): \ ((__INSTANCE__)->SR3 |= (__INTERRUPT__))) /** * @brief Disable the NAND device interrupt. * @param __INSTANCE__: FMC_NAND Instance * @param __BANK__: FMC_NAND Bank * @param __INTERRUPT__: FMC_NAND interrupt * This parameter can be any combination of the following values: * @arg FMC_IT_RISING_EDGE: Interrupt rising edge. * @arg FMC_IT_LEVEL: Interrupt level. * @arg FMC_IT_FALLING_EDGE: Interrupt falling edge. * @retval None */ #define __FMC_NAND_DISABLE_IT(__INSTANCE__, __BANK__, __INTERRUPT__) (((__BANK__) == FMC_NAND_BANK2)? ((__INSTANCE__)->SR2 &= ~(__INTERRUPT__)): \ ((__INSTANCE__)->SR3 &= ~(__INTERRUPT__))) /** * @brief Get flag status of the NAND device. * @param __INSTANCE__: FMC_NAND Instance * @param __BANK__: FMC_NAND Bank * @param __FLAG__: FMC_NAND flag * This parameter can be any combination of the following values: * @arg FMC_FLAG_RISING_EDGE: Interrupt rising edge flag. * @arg FMC_FLAG_LEVEL: Interrupt level edge flag. * @arg FMC_FLAG_FALLING_EDGE: Interrupt falling edge flag. * @arg FMC_FLAG_FEMPT: FIFO empty flag. * @retval The state of FLAG (SET or RESET). */ #define __FMC_NAND_GET_FLAG(__INSTANCE__, __BANK__, __FLAG__) (((__BANK__) == FMC_NAND_BANK2)? (((__INSTANCE__)->SR2 &(__FLAG__)) == (__FLAG__)): \ (((__INSTANCE__)->SR3 &(__FLAG__)) == (__FLAG__))) /** * @brief Clear flag status of the NAND device. * @param __INSTANCE__: FMC_NAND Instance * @param __BANK__: FMC_NAND Bank * @param __FLAG__: FMC_NAND flag * This parameter can be any combination of the following values: * @arg FMC_FLAG_RISING_EDGE: Interrupt rising edge flag. * @arg FMC_FLAG_LEVEL: Interrupt level edge flag. * @arg FMC_FLAG_FALLING_EDGE: Interrupt falling edge flag. * @arg FMC_FLAG_FEMPT: FIFO empty flag. * @retval None */ #define __FMC_NAND_CLEAR_FLAG(__INSTANCE__, __BANK__, __FLAG__) (((__BANK__) == FMC_NAND_BANK2)? ((__INSTANCE__)->SR2 &= ~(__FLAG__)): \ ((__INSTANCE__)->SR3 &= ~(__FLAG__))) #endif /* defined(STM32F446xx) || defined(STM32F469xx) || defined(STM32F479xx) */ #if defined(STM32F427xx) || defined(STM32F437xx) || defined(STM32F429xx) || defined(STM32F439xx) /** * @brief Enable the PCCARD device interrupt. * @param __INSTANCE__: FMC_PCCARD instance * @param __INTERRUPT__: FMC_PCCARD interrupt * This parameter can be any combination of the following values: * @arg FMC_IT_RISING_EDGE: Interrupt rising edge. * @arg FMC_IT_LEVEL: Interrupt level. * @arg FMC_IT_FALLING_EDGE: Interrupt falling edge. * @retval None */ #define __FMC_PCCARD_ENABLE_IT(__INSTANCE__, __INTERRUPT__) ((__INSTANCE__)->SR4 |= (__INTERRUPT__)) /** * @brief Disable the PCCARD device interrupt. * @param __INSTANCE__: FMC_PCCARD instance * @param __INTERRUPT__: FMC_PCCARD interrupt * This parameter can be any combination of the following values: * @arg FMC_IT_RISING_EDGE: Interrupt rising edge. * @arg FMC_IT_LEVEL: Interrupt level. * @arg FMC_IT_FALLING_EDGE: Interrupt falling edge. * @retval None */ #define __FMC_PCCARD_DISABLE_IT(__INSTANCE__, __INTERRUPT__) ((__INSTANCE__)->SR4 &= ~(__INTERRUPT__)) /** * @brief Get flag status of the PCCARD device. * @param __INSTANCE__: FMC_PCCARD instance * @param __FLAG__: FMC_PCCARD flag * This parameter can be any combination of the following values: * @arg FMC_FLAG_RISING_EDGE: Interrupt rising edge flag. * @arg FMC_FLAG_LEVEL: Interrupt level edge flag. * @arg FMC_FLAG_FALLING_EDGE: Interrupt falling edge flag. * @arg FMC_FLAG_FEMPT: FIFO empty flag. * @retval The state of FLAG (SET or RESET). */ #define __FMC_PCCARD_GET_FLAG(__INSTANCE__, __FLAG__) (((__INSTANCE__)->SR4 &(__FLAG__)) == (__FLAG__)) /** * @brief Clear flag status of the PCCARD device. * @param __INSTANCE__: FMC_PCCARD instance * @param __FLAG__: FMC_PCCARD flag * This parameter can be any combination of the following values: * @arg FMC_FLAG_RISING_EDGE: Interrupt rising edge flag. * @arg FMC_FLAG_LEVEL: Interrupt level edge flag. * @arg FMC_FLAG_FALLING_EDGE: Interrupt falling edge flag. * @arg FMC_FLAG_FEMPT: FIFO empty flag. * @retval None */ #define __FMC_PCCARD_CLEAR_FLAG(__INSTANCE__, __FLAG__) ((__INSTANCE__)->SR4 &= ~(__FLAG__)) #endif /* defined(STM32F427xx) || defined(STM32F437xx) || defined(STM32F429xx) || defined(STM32F439xx) */ /** * @brief Enable the SDRAM device interrupt. * @param __INSTANCE__: FMC_SDRAM instance * @param __INTERRUPT__: FMC_SDRAM interrupt * This parameter can be any combination of the following values: * @arg FMC_IT_REFRESH_ERROR: Interrupt refresh error * @retval None */ #define __FMC_SDRAM_ENABLE_IT(__INSTANCE__, __INTERRUPT__) ((__INSTANCE__)->SDRTR |= (__INTERRUPT__)) /** * @brief Disable the SDRAM device interrupt. * @param __INSTANCE__: FMC_SDRAM instance * @param __INTERRUPT__: FMC_SDRAM interrupt * This parameter can be any combination of the following values: * @arg FMC_IT_REFRESH_ERROR: Interrupt refresh error * @retval None */ #define __FMC_SDRAM_DISABLE_IT(__INSTANCE__, __INTERRUPT__) ((__INSTANCE__)->SDRTR &= ~(__INTERRUPT__)) /** * @brief Get flag status of the SDRAM device. * @param __INSTANCE__: FMC_SDRAM instance * @param __FLAG__: FMC_SDRAM flag * This parameter can be any combination of the following values: * @arg FMC_SDRAM_FLAG_REFRESH_IT: Interrupt refresh error. * @arg FMC_SDRAM_FLAG_BUSY: SDRAM busy flag. * @arg FMC_SDRAM_FLAG_REFRESH_ERROR: Refresh error flag. * @retval The state of FLAG (SET or RESET). */ #define __FMC_SDRAM_GET_FLAG(__INSTANCE__, __FLAG__) (((__INSTANCE__)->SDSR &(__FLAG__)) == (__FLAG__)) /** * @brief Clear flag status of the SDRAM device. * @param __INSTANCE__: FMC_SDRAM instance * @param __FLAG__: FMC_SDRAM flag * This parameter can be any combination of the following values: * @arg FMC_SDRAM_FLAG_REFRESH_ERROR * @retval None */ #define __FMC_SDRAM_CLEAR_FLAG(__INSTANCE__, __FLAG__) ((__INSTANCE__)->SDRTR |= (__FLAG__)) /** * @} */ /** @defgroup FSMC_LL_Assert_Macros FSMC Assert Macros * @{ */ #define IS_FMC_NORSRAM_BANK(BANK) (((BANK) == FMC_NORSRAM_BANK1) || \ ((BANK) == FMC_NORSRAM_BANK2) || \ ((BANK) == FMC_NORSRAM_BANK3) || \ ((BANK) == FMC_NORSRAM_BANK4)) #define IS_FMC_MUX(__MUX__) (((__MUX__) == FMC_DATA_ADDRESS_MUX_DISABLE) || \ ((__MUX__) == FMC_DATA_ADDRESS_MUX_ENABLE)) #define IS_FMC_MEMORY(__MEMORY__) (((__MEMORY__) == FMC_MEMORY_TYPE_SRAM) || \ ((__MEMORY__) == FMC_MEMORY_TYPE_PSRAM)|| \ ((__MEMORY__) == FMC_MEMORY_TYPE_NOR)) #define IS_FMC_NORSRAM_MEMORY_WIDTH(__WIDTH__) (((__WIDTH__) == FMC_NORSRAM_MEM_BUS_WIDTH_8) || \ ((__WIDTH__) == FMC_NORSRAM_MEM_BUS_WIDTH_16) || \ ((__WIDTH__) == FMC_NORSRAM_MEM_BUS_WIDTH_32)) #define IS_FMC_ACCESS_MODE(__MODE__) (((__MODE__) == FMC_ACCESS_MODE_A) || \ ((__MODE__) == FMC_ACCESS_MODE_B) || \ ((__MODE__) == FMC_ACCESS_MODE_C) || \ ((__MODE__) == FMC_ACCESS_MODE_D)) #define IS_FMC_NAND_BANK(BANK) (((BANK) == FMC_NAND_BANK2) || \ ((BANK) == FMC_NAND_BANK3)) #define IS_FMC_WAIT_FEATURE(FEATURE) (((FEATURE) == FMC_NAND_PCC_WAIT_FEATURE_DISABLE) || \ ((FEATURE) == FMC_NAND_PCC_WAIT_FEATURE_ENABLE)) #define IS_FMC_NAND_MEMORY_WIDTH(WIDTH) (((WIDTH) == FMC_NAND_PCC_MEM_BUS_WIDTH_8) || \ ((WIDTH) == FMC_NAND_PCC_MEM_BUS_WIDTH_16)) #define IS_FMC_ECC_STATE(STATE) (((STATE) == FMC_NAND_ECC_DISABLE) || \ ((STATE) == FMC_NAND_ECC_ENABLE)) #define IS_FMC_ECCPAGE_SIZE(SIZE) (((SIZE) == FMC_NAND_ECC_PAGE_SIZE_256BYTE) || \ ((SIZE) == FMC_NAND_ECC_PAGE_SIZE_512BYTE) || \ ((SIZE) == FMC_NAND_ECC_PAGE_SIZE_1024BYTE) || \ ((SIZE) == FMC_NAND_ECC_PAGE_SIZE_2048BYTE) || \ ((SIZE) == FMC_NAND_ECC_PAGE_SIZE_4096BYTE) || \ ((SIZE) == FMC_NAND_ECC_PAGE_SIZE_8192BYTE)) #define IS_FMC_TCLR_TIME(TIME) ((TIME) <= 255) #define IS_FMC_TAR_TIME(TIME) ((TIME) <= 255) #define IS_FMC_SETUP_TIME(TIME) ((TIME) <= 255) #define IS_FMC_WAIT_TIME(TIME) ((TIME) <= 255) #define IS_FMC_HOLD_TIME(TIME) ((TIME) <= 255) #define IS_FMC_HIZ_TIME(TIME) ((TIME) <= 255) #define IS_FMC_NORSRAM_DEVICE(__INSTANCE__) ((__INSTANCE__) == FMC_NORSRAM_DEVICE) #define IS_FMC_NORSRAM_EXTENDED_DEVICE(__INSTANCE__) ((__INSTANCE__) == FMC_NORSRAM_EXTENDED_DEVICE) #define IS_FMC_NAND_DEVICE(__INSTANCE__) ((__INSTANCE__) == FMC_NAND_DEVICE) #define IS_FMC_PCCARD_DEVICE(__INSTANCE__) ((__INSTANCE__) == FMC_PCCARD_DEVICE) #define IS_FMC_BURSTMODE(__STATE__) (((__STATE__) == FMC_BURST_ACCESS_MODE_DISABLE) || \ ((__STATE__) == FMC_BURST_ACCESS_MODE_ENABLE)) #define IS_FMC_WAIT_POLARITY(__POLARITY__) (((__POLARITY__) == FMC_WAIT_SIGNAL_POLARITY_LOW) || \ ((__POLARITY__) == FMC_WAIT_SIGNAL_POLARITY_HIGH)) #if defined(STM32F427xx) || defined(STM32F437xx) || defined(STM32F429xx) || defined(STM32F439xx) #define IS_FMC_WRAP_MODE(__MODE__) (((__MODE__) == FMC_WRAP_MODE_DISABLE) || \ ((__MODE__) == FMC_WRAP_MODE_ENABLE)) #endif /* STM32F427xx || STM32F437xx || STM32F429xx || STM32F439xx */ #define IS_FMC_WAIT_SIGNAL_ACTIVE(__ACTIVE__) (((__ACTIVE__) == FMC_WAIT_TIMING_BEFORE_WS) || \ ((__ACTIVE__) == FMC_WAIT_TIMING_DURING_WS)) #define IS_FMC_WRITE_OPERATION(__OPERATION__) (((__OPERATION__) == FMC_WRITE_OPERATION_DISABLE) || \ ((__OPERATION__) == FMC_WRITE_OPERATION_ENABLE)) #define IS_FMC_WAITE_SIGNAL(__SIGNAL__) (((__SIGNAL__) == FMC_WAIT_SIGNAL_DISABLE) || \ ((__SIGNAL__) == FMC_WAIT_SIGNAL_ENABLE)) #define IS_FMC_EXTENDED_MODE(__MODE__) (((__MODE__) == FMC_EXTENDED_MODE_DISABLE) || \ ((__MODE__) == FMC_EXTENDED_MODE_ENABLE)) #define IS_FMC_ASYNWAIT(__STATE__) (((__STATE__) == FMC_ASYNCHRONOUS_WAIT_DISABLE) || \ ((__STATE__) == FMC_ASYNCHRONOUS_WAIT_ENABLE)) #define IS_FMC_WRITE_BURST(__BURST__) (((__BURST__) == FMC_WRITE_BURST_DISABLE) || \ ((__BURST__) == FMC_WRITE_BURST_ENABLE)) #define IS_FMC_CONTINOUS_CLOCK(CCLOCK) (((CCLOCK) == FMC_CONTINUOUS_CLOCK_SYNC_ONLY) || \ ((CCLOCK) == FMC_CONTINUOUS_CLOCK_SYNC_ASYNC)) #define IS_FMC_ADDRESS_SETUP_TIME(__TIME__) ((__TIME__) <= 15) #define IS_FMC_ADDRESS_HOLD_TIME(__TIME__) (((__TIME__) > 0) && ((__TIME__) <= 15)) #define IS_FMC_DATASETUP_TIME(__TIME__) (((__TIME__) > 0) && ((__TIME__) <= 255)) #define IS_FMC_TURNAROUND_TIME(__TIME__) ((__TIME__) <= 15) #define IS_FMC_DATA_LATENCY(__LATENCY__) (((__LATENCY__) > 1) && ((__LATENCY__) <= 17)) #define IS_FMC_CLK_DIV(DIV) (((DIV) > 1) && ((DIV) <= 16)) #define IS_FMC_SDRAM_BANK(BANK) (((BANK) == FMC_SDRAM_BANK1) || \ ((BANK) == FMC_SDRAM_BANK2)) #define IS_FMC_COLUMNBITS_NUMBER(COLUMN) (((COLUMN) == FMC_SDRAM_COLUMN_BITS_NUM_8) || \ ((COLUMN) == FMC_SDRAM_COLUMN_BITS_NUM_9) || \ ((COLUMN) == FMC_SDRAM_COLUMN_BITS_NUM_10) || \ ((COLUMN) == FMC_SDRAM_COLUMN_BITS_NUM_11)) #define IS_FMC_ROWBITS_NUMBER(ROW) (((ROW) == FMC_SDRAM_ROW_BITS_NUM_11) || \ ((ROW) == FMC_SDRAM_ROW_BITS_NUM_12) || \ ((ROW) == FMC_SDRAM_ROW_BITS_NUM_13)) #define IS_FMC_SDMEMORY_WIDTH(WIDTH) (((WIDTH) == FMC_SDRAM_MEM_BUS_WIDTH_8) || \ ((WIDTH) == FMC_SDRAM_MEM_BUS_WIDTH_16) || \ ((WIDTH) == FMC_SDRAM_MEM_BUS_WIDTH_32)) #define IS_FMC_INTERNALBANK_NUMBER(NUMBER) (((NUMBER) == FMC_SDRAM_INTERN_BANKS_NUM_2) || \ ((NUMBER) == FMC_SDRAM_INTERN_BANKS_NUM_4)) #define IS_FMC_CAS_LATENCY(LATENCY) (((LATENCY) == FMC_SDRAM_CAS_LATENCY_1) || \ ((LATENCY) == FMC_SDRAM_CAS_LATENCY_2) || \ ((LATENCY) == FMC_SDRAM_CAS_LATENCY_3)) #define IS_FMC_SDCLOCK_PERIOD(PERIOD) (((PERIOD) == FMC_SDRAM_CLOCK_DISABLE) || \ ((PERIOD) == FMC_SDRAM_CLOCK_PERIOD_2) || \ ((PERIOD) == FMC_SDRAM_CLOCK_PERIOD_3)) #define IS_FMC_READ_BURST(RBURST) (((RBURST) == FMC_SDRAM_RBURST_DISABLE) || \ ((RBURST) == FMC_SDRAM_RBURST_ENABLE)) #define IS_FMC_READPIPE_DELAY(DELAY) (((DELAY) == FMC_SDRAM_RPIPE_DELAY_0) || \ ((DELAY) == FMC_SDRAM_RPIPE_DELAY_1) || \ ((DELAY) == FMC_SDRAM_RPIPE_DELAY_2)) #define IS_FMC_LOADTOACTIVE_DELAY(DELAY) (((DELAY) > 0) && ((DELAY) <= 16)) #define IS_FMC_EXITSELFREFRESH_DELAY(DELAY) (((DELAY) > 0) && ((DELAY) <= 16)) #define IS_FMC_SELFREFRESH_TIME(TIME) (((TIME) > 0) && ((TIME) <= 16)) #define IS_FMC_ROWCYCLE_DELAY(DELAY) (((DELAY) > 0) && ((DELAY) <= 16)) #define IS_FMC_WRITE_RECOVERY_TIME(TIME) (((TIME) > 0) && ((TIME) <= 16)) #define IS_FMC_RP_DELAY(DELAY) (((DELAY) > 0) && ((DELAY) <= 16)) #define IS_FMC_RCD_DELAY(DELAY) (((DELAY) > 0) && ((DELAY) <= 16)) #define IS_FMC_COMMAND_MODE(COMMAND) (((COMMAND) == FMC_SDRAM_CMD_NORMAL_MODE) || \ ((COMMAND) == FMC_SDRAM_CMD_CLK_ENABLE) || \ ((COMMAND) == FMC_SDRAM_CMD_PALL) || \ ((COMMAND) == FMC_SDRAM_CMD_AUTOREFRESH_MODE) || \ ((COMMAND) == FMC_SDRAM_CMD_LOAD_MODE) || \ ((COMMAND) == FMC_SDRAM_CMD_SELFREFRESH_MODE) || \ ((COMMAND) == FMC_SDRAM_CMD_POWERDOWN_MODE)) #define IS_FMC_COMMAND_TARGET(TARGET) (((TARGET) == FMC_SDRAM_CMD_TARGET_BANK1) || \ ((TARGET) == FMC_SDRAM_CMD_TARGET_BANK2) || \ ((TARGET) == FMC_SDRAM_CMD_TARGET_BANK1_2)) #define IS_FMC_AUTOREFRESH_NUMBER(NUMBER) (((NUMBER) > 0) && ((NUMBER) <= 16)) #define IS_FMC_MODE_REGISTER(CONTENT) ((CONTENT) <= 8191) #define IS_FMC_REFRESH_RATE(RATE) ((RATE) <= 8191) #define IS_FMC_SDRAM_DEVICE(INSTANCE) ((INSTANCE) == FMC_SDRAM_DEVICE) #define IS_FMC_WRITE_PROTECTION(WRITE) (((WRITE) == FMC_SDRAM_WRITE_PROTECTION_DISABLE) || \ ((WRITE) == FMC_SDRAM_WRITE_PROTECTION_ENABLE)) #if defined (STM32F446xx) || defined(STM32F469xx) || defined(STM32F479xx) #define IS_FMC_PAGESIZE(SIZE) (((SIZE) == FMC_PAGE_SIZE_NONE) || \ ((SIZE) == FMC_PAGE_SIZE_128) || \ ((SIZE) == FMC_PAGE_SIZE_256) || \ ((SIZE) == FMC_PAGE_SIZE_1024)) #define IS_FMC_WRITE_FIFO(FIFO) (((FIFO) == FMC_WRITE_FIFO_DISABLE) || \ ((FIFO) == FMC_WRITE_FIFO_ENABLE)) #endif /* STM32F446xx || STM32F469xx || STM32F479xx */ /** * @} */ /** * @} */ /* Private functions ---------------------------------------------------------*/ /** @defgroup FMC_LL_Private_Functions FMC LL Private Functions * @{ */ /** @defgroup FMC_LL_NORSRAM NOR SRAM * @{ */ /** @defgroup FMC_LL_NORSRAM_Private_Functions_Group1 NOR SRAM Initialization/de-initialization functions * @{ */ HAL_StatusTypeDef FMC_NORSRAM_Init(FMC_NORSRAM_TypeDef *Device, FMC_NORSRAM_InitTypeDef *Init); HAL_StatusTypeDef FMC_NORSRAM_Timing_Init(FMC_NORSRAM_TypeDef *Device, FMC_NORSRAM_TimingTypeDef *Timing, uint32_t Bank); HAL_StatusTypeDef FMC_NORSRAM_Extended_Timing_Init(FMC_NORSRAM_EXTENDED_TypeDef *Device, FMC_NORSRAM_TimingTypeDef *Timing, uint32_t Bank, uint32_t ExtendedMode); HAL_StatusTypeDef FMC_NORSRAM_DeInit(FMC_NORSRAM_TypeDef *Device, FMC_NORSRAM_EXTENDED_TypeDef *ExDevice, uint32_t Bank); /** * @} */ /** @defgroup FMC_LL_NORSRAM_Private_Functions_Group2 NOR SRAM Control functions * @{ */ HAL_StatusTypeDef FMC_NORSRAM_WriteOperation_Enable(FMC_NORSRAM_TypeDef *Device, uint32_t Bank); HAL_StatusTypeDef FMC_NORSRAM_WriteOperation_Disable(FMC_NORSRAM_TypeDef *Device, uint32_t Bank); /** * @} */ /** * @} */ /** @defgroup FMC_LL_NAND NAND * @{ */ /** @defgroup FMC_LL_NAND_Private_Functions_Group1 NAND Initialization/de-initialization functions * @{ */ HAL_StatusTypeDef FMC_NAND_Init(FMC_NAND_TypeDef *Device, FMC_NAND_InitTypeDef *Init); HAL_StatusTypeDef FMC_NAND_CommonSpace_Timing_Init(FMC_NAND_TypeDef *Device, FMC_NAND_PCC_TimingTypeDef *Timing, uint32_t Bank); HAL_StatusTypeDef FMC_NAND_AttributeSpace_Timing_Init(FMC_NAND_TypeDef *Device, FMC_NAND_PCC_TimingTypeDef *Timing, uint32_t Bank); HAL_StatusTypeDef FMC_NAND_DeInit(FMC_NAND_TypeDef *Device, uint32_t Bank); /** * @} */ /** @defgroup FMC_LL_NAND_Private_Functions_Group2 NAND Control functions * @{ */ HAL_StatusTypeDef FMC_NAND_ECC_Enable(FMC_NAND_TypeDef *Device, uint32_t Bank); HAL_StatusTypeDef FMC_NAND_ECC_Disable(FMC_NAND_TypeDef *Device, uint32_t Bank); HAL_StatusTypeDef FMC_NAND_GetECC(FMC_NAND_TypeDef *Device, uint32_t *ECCval, uint32_t Bank, uint32_t Timeout); /** * @} */ /** * @} */ #if defined(STM32F427xx) || defined(STM32F437xx) || defined(STM32F429xx) || defined(STM32F439xx) /** @defgroup FMC_LL_PCCARD PCCARD * @{ */ /** @defgroup FMC_LL_PCCARD_Private_Functions_Group1 PCCARD Initialization/de-initialization functions * @{ */ HAL_StatusTypeDef FMC_PCCARD_Init(FMC_PCCARD_TypeDef *Device, FMC_PCCARD_InitTypeDef *Init); HAL_StatusTypeDef FMC_PCCARD_CommonSpace_Timing_Init(FMC_PCCARD_TypeDef *Device, FMC_NAND_PCC_TimingTypeDef *Timing); HAL_StatusTypeDef FMC_PCCARD_AttributeSpace_Timing_Init(FMC_PCCARD_TypeDef *Device, FMC_NAND_PCC_TimingTypeDef *Timing); HAL_StatusTypeDef FMC_PCCARD_IOSpace_Timing_Init(FMC_PCCARD_TypeDef *Device, FMC_NAND_PCC_TimingTypeDef *Timing); HAL_StatusTypeDef FMC_PCCARD_DeInit(FMC_PCCARD_TypeDef *Device); /** * @} */ /** * @} */ #endif /* STM32F427xx || STM32F437xx || STM32F429xx || STM32F439xx */ /** @defgroup FMC_LL_SDRAM SDRAM * @{ */ /** @defgroup FMC_LL_SDRAM_Private_Functions_Group1 SDRAM Initialization/de-initialization functions * @{ */ HAL_StatusTypeDef FMC_SDRAM_Init(FMC_SDRAM_TypeDef *Device, FMC_SDRAM_InitTypeDef *Init); HAL_StatusTypeDef FMC_SDRAM_Timing_Init(FMC_SDRAM_TypeDef *Device, FMC_SDRAM_TimingTypeDef *Timing, uint32_t Bank); HAL_StatusTypeDef FMC_SDRAM_DeInit(FMC_SDRAM_TypeDef *Device, uint32_t Bank); /** * @} */ /** @defgroup FMC_LL_SDRAM_Private_Functions_Group2 SDRAM Control functions * @{ */ HAL_StatusTypeDef FMC_SDRAM_WriteProtection_Enable(FMC_SDRAM_TypeDef *Device, uint32_t Bank); HAL_StatusTypeDef FMC_SDRAM_WriteProtection_Disable(FMC_SDRAM_TypeDef *Device, uint32_t Bank); HAL_StatusTypeDef FMC_SDRAM_SendCommand(FMC_SDRAM_TypeDef *Device, FMC_SDRAM_CommandTypeDef *Command, uint32_t Timeout); HAL_StatusTypeDef FMC_SDRAM_ProgramRefreshRate(FMC_SDRAM_TypeDef *Device, uint32_t RefreshRate); HAL_StatusTypeDef FMC_SDRAM_SetAutoRefreshNumber(FMC_SDRAM_TypeDef *Device, uint32_t AutoRefreshNumber); uint32_t FMC_SDRAM_GetModeStatus(FMC_SDRAM_TypeDef *Device, uint32_t Bank); /** * @} */ /** * @} */ /** * @} */ #endif /* STM32F427xx || STM32F437xx || STM32F429xx || STM32F439xx || STM32F446xx || STM32F469xx || STM32F479xx */ /** * @} */ /** * @} */ #ifdef __cplusplus } #endif #endif /* __STM32F4xx_LL_FMC_H */ /************************ (C) COPYRIGHT STMicroelectronics *****END OF FILE****/ ================================================ FILE: Zelig/mbed/TARGET_NUCLEO_F411RE/stm32f4xx_ll_fsmc.h ================================================ /** ****************************************************************************** * @file stm32f4xx_ll_fsmc.h * @author MCD Application Team * @version V1.4.1 * @date 09-October-2015 * @brief Header file of FSMC HAL module. ****************************************************************************** * @attention * *

© COPYRIGHT(c) 2015 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. * ****************************************************************************** */ /* Define to prevent recursive inclusion -------------------------------------*/ #ifndef __STM32F4xx_LL_FSMC_H #define __STM32F4xx_LL_FSMC_H #ifdef __cplusplus extern "C" { #endif /* Includes ------------------------------------------------------------------*/ #include "stm32f4xx_hal_def.h" /** @addtogroup STM32F4xx_HAL_Driver * @{ */ /** @addtogroup FSMC_LL * @{ */ #if defined(STM32F405xx) || defined(STM32F415xx) || defined(STM32F407xx) || defined(STM32F417xx) /* Private types -------------------------------------------------------------*/ /** @defgroup FSMC_LL_Private_Types FSMC Private Types * @{ */ /** * @brief FSMC NORSRAM Configuration Structure definition */ typedef struct { uint32_t NSBank; /*!< Specifies the NORSRAM memory device that will be used. This parameter can be a value of @ref FSMC_NORSRAM_Bank */ uint32_t DataAddressMux; /*!< Specifies whether the address and data values are multiplexed on the data bus or not. This parameter can be a value of @ref FSMC_Data_Address_Bus_Multiplexing */ uint32_t MemoryType; /*!< Specifies the type of external memory attached to the corresponding memory device. This parameter can be a value of @ref FSMC_Memory_Type */ uint32_t MemoryDataWidth; /*!< Specifies the external memory device width. This parameter can be a value of @ref FSMC_NORSRAM_Data_Width */ uint32_t BurstAccessMode; /*!< Enables or disables the burst access mode for Flash memory, valid only with synchronous burst Flash memories. This parameter can be a value of @ref FSMC_Burst_Access_Mode */ uint32_t WaitSignalPolarity; /*!< Specifies the wait signal polarity, valid only when accessing the Flash memory in burst mode. This parameter can be a value of @ref FSMC_Wait_Signal_Polarity */ uint32_t WrapMode; /*!< Enables or disables the Wrapped burst access mode for Flash memory, valid only when accessing Flash memories in burst mode. This parameter can be a value of @ref FSMC_Wrap_Mode */ uint32_t WaitSignalActive; /*!< Specifies if the wait signal is asserted by the memory one clock cycle before the wait state or during the wait state, valid only when accessing memories in burst mode. This parameter can be a value of @ref FSMC_Wait_Timing */ uint32_t WriteOperation; /*!< Enables or disables the write operation in the selected device by the FSMC. This parameter can be a value of @ref FSMC_Write_Operation */ uint32_t WaitSignal; /*!< Enables or disables the wait state insertion via wait signal, valid for Flash memory access in burst mode. This parameter can be a value of @ref FSMC_Wait_Signal */ uint32_t ExtendedMode; /*!< Enables or disables the extended mode. This parameter can be a value of @ref FSMC_Extended_Mode */ uint32_t AsynchronousWait; /*!< Enables or disables wait signal during asynchronous transfers, valid only with asynchronous Flash memories. This parameter can be a value of @ref FSMC_AsynchronousWait */ uint32_t WriteBurst; /*!< Enables or disables the write burst operation. This parameter can be a value of @ref FSMC_Write_Burst */ }FSMC_NORSRAM_InitTypeDef; /** * @brief FSMC NORSRAM Timing parameters structure definition */ typedef struct { uint32_t AddressSetupTime; /*!< Defines the number of HCLK cycles to configure the duration of the address setup time. This parameter can be a value between Min_Data = 0 and Max_Data = 15. @note This parameter is not used with synchronous NOR Flash memories. */ uint32_t AddressHoldTime; /*!< Defines the number of HCLK cycles to configure the duration of the address hold time. This parameter can be a value between Min_Data = 1 and Max_Data = 15. @note This parameter is not used with synchronous NOR Flash memories. */ uint32_t DataSetupTime; /*!< Defines the number of HCLK cycles to configure the duration of the data setup time. This parameter can be a value between Min_Data = 1 and Max_Data = 255. @note This parameter is used for SRAMs, ROMs and asynchronous multiplexed NOR Flash memories. */ uint32_t BusTurnAroundDuration; /*!< Defines the number of HCLK cycles to configure the duration of the bus turnaround. This parameter can be a value between Min_Data = 0 and Max_Data = 15. @note This parameter is only used for multiplexed NOR Flash memories. */ uint32_t CLKDivision; /*!< Defines the period of CLK clock output signal, expressed in number of HCLK cycles. This parameter can be a value between Min_Data = 2 and Max_Data = 16. @note This parameter is not used for asynchronous NOR Flash, SRAM or ROM accesses. */ uint32_t DataLatency; /*!< Defines the number of memory clock cycles to issue to the memory before getting the first data. The parameter value depends on the memory type as shown below: - It must be set to 0 in case of a CRAM - It is don't care in asynchronous NOR, SRAM or ROM accesses - It may assume a value between Min_Data = 2 and Max_Data = 17 in NOR Flash memories with synchronous burst mode enable */ uint32_t AccessMode; /*!< Specifies the asynchronous access mode. This parameter can be a value of @ref FSMC_Access_Mode */ }FSMC_NORSRAM_TimingTypeDef; #if defined(STM32F405xx) || defined(STM32F415xx) || defined(STM32F407xx) || defined(STM32F417xx) /** * @brief FSMC NAND Configuration Structure definition */ typedef struct { uint32_t NandBank; /*!< Specifies the NAND memory device that will be used. This parameter can be a value of @ref FSMC_NAND_Bank */ uint32_t Waitfeature; /*!< Enables or disables the Wait feature for the NAND Memory device. This parameter can be any value of @ref FSMC_Wait_feature */ uint32_t MemoryDataWidth; /*!< Specifies the external memory device width. This parameter can be any value of @ref FSMC_NAND_Data_Width */ uint32_t EccComputation; /*!< Enables or disables the ECC computation. This parameter can be any value of @ref FSMC_ECC */ uint32_t ECCPageSize; /*!< Defines the page size for the extended ECC. This parameter can be any value of @ref FSMC_ECC_Page_Size */ uint32_t TCLRSetupTime; /*!< Defines the number of HCLK cycles to configure the delay between CLE low and RE low. This parameter can be a value between Min_Data = 0 and Max_Data = 255 */ uint32_t TARSetupTime; /*!< Defines the number of HCLK cycles to configure the delay between ALE low and RE low. This parameter can be a number between Min_Data = 0 and Max_Data = 255 */ }FSMC_NAND_InitTypeDef; /** * @brief FSMC NAND/PCCARD Timing parameters structure definition */ typedef struct { uint32_t SetupTime; /*!< Defines the number of HCLK cycles to setup address before the command assertion for NAND-Flash read or write access to common/Attribute or I/O memory space (depending on the memory space timing to be configured). This parameter can be a value between Min_Data = 0 and Max_Data = 255 */ uint32_t WaitSetupTime; /*!< Defines the minimum number of HCLK cycles to assert the command for NAND-Flash read or write access to common/Attribute or I/O memory space (depending on the memory space timing to be configured). This parameter can be a number between Min_Data = 0 and Max_Data = 255 */ uint32_t HoldSetupTime; /*!< Defines the number of HCLK clock cycles to hold address (and data for write access) after the command de-assertion for NAND-Flash read or write access to common/Attribute or I/O memory space (depending on the memory space timing to be configured). This parameter can be a number between Min_Data = 0 and Max_Data = 255 */ uint32_t HiZSetupTime; /*!< Defines the number of HCLK clock cycles during which the data bus is kept in HiZ after the start of a NAND-Flash write access to common/Attribute or I/O memory space (depending on the memory space timing to be configured). This parameter can be a number between Min_Data = 0 and Max_Data = 255 */ }FSMC_NAND_PCC_TimingTypeDef; /** * @brief FSMC NAND Configuration Structure definition */ typedef struct { uint32_t Waitfeature; /*!< Enables or disables the Wait feature for the PCCARD Memory device. This parameter can be any value of @ref FSMC_Wait_feature */ uint32_t TCLRSetupTime; /*!< Defines the number of HCLK cycles to configure the delay between CLE low and RE low. This parameter can be a value between Min_Data = 0 and Max_Data = 255 */ uint32_t TARSetupTime; /*!< Defines the number of HCLK cycles to configure the delay between ALE low and RE low. This parameter can be a number between Min_Data = 0 and Max_Data = 255 */ }FSMC_PCCARD_InitTypeDef; /** * @} */ #endif /* STM32F405xx || STM32F415xx || STM32F407xx || STM32F417xx */ /* Private constants ---------------------------------------------------------*/ /** @defgroup FSMC_LL_Private_Constants FSMC Private Constants * @{ */ /** @defgroup FSMC_LL_NOR_SRAM_Controller FSMC NOR/SRAM Controller * @{ */ /** @defgroup FSMC_NORSRAM_Bank FSMC NOR/SRAM Bank * @{ */ #define FSMC_NORSRAM_BANK1 ((uint32_t)0x00000000) #define FSMC_NORSRAM_BANK2 ((uint32_t)0x00000002) #define FSMC_NORSRAM_BANK3 ((uint32_t)0x00000004) #define FSMC_NORSRAM_BANK4 ((uint32_t)0x00000006) /** * @} */ /** @defgroup FSMC_Data_Address_Bus_Multiplexing FSMC Data Address Bus Multiplexing * @{ */ #define FSMC_DATA_ADDRESS_MUX_DISABLE ((uint32_t)0x00000000) #define FSMC_DATA_ADDRESS_MUX_ENABLE ((uint32_t)0x00000002) /** * @} */ /** @defgroup FSMC_Memory_Type FSMC Memory Type * @{ */ #define FSMC_MEMORY_TYPE_SRAM ((uint32_t)0x00000000) #define FSMC_MEMORY_TYPE_PSRAM ((uint32_t)0x00000004) #define FSMC_MEMORY_TYPE_NOR ((uint32_t)0x00000008) /** * @} */ /** @defgroup FSMC_NORSRAM_Data_Width FSMC NOR/SRAM Data Width * @{ */ #define FSMC_NORSRAM_MEM_BUS_WIDTH_8 ((uint32_t)0x00000000) #define FSMC_NORSRAM_MEM_BUS_WIDTH_16 ((uint32_t)0x00000010) #define FSMC_NORSRAM_MEM_BUS_WIDTH_32 ((uint32_t)0x00000020) /** * @} */ /** @defgroup FSMC_NORSRAM_Flash_Access FSMC NOR/SRAM Flash Access * @{ */ #define FSMC_NORSRAM_FLASH_ACCESS_ENABLE ((uint32_t)0x00000040) #define FSMC_NORSRAM_FLASH_ACCESS_DISABLE ((uint32_t)0x00000000) /** * @} */ /** @defgroup FSMC_Burst_Access_Mode FSMC Burst Access Mode * @{ */ #define FSMC_BURST_ACCESS_MODE_DISABLE ((uint32_t)0x00000000) #define FSMC_BURST_ACCESS_MODE_ENABLE ((uint32_t)0x00000100) /** * @} */ /** @defgroup FSMC_Wait_Signal_Polarity FSMC Wait Signal Polarity * @{ */ #define FSMC_WAIT_SIGNAL_POLARITY_LOW ((uint32_t)0x00000000) #define FSMC_WAIT_SIGNAL_POLARITY_HIGH ((uint32_t)0x00000200) /** * @} */ /** @defgroup FSMC_Wrap_Mode FSMC Wrap Mode * @{ */ #define FSMC_WRAP_MODE_DISABLE ((uint32_t)0x00000000) #define FSMC_WRAP_MODE_ENABLE ((uint32_t)0x00000400) /** * @} */ /** @defgroup FSMC_Wait_Timing FSMC Wait Timing * @{ */ #define FSMC_WAIT_TIMING_BEFORE_WS ((uint32_t)0x00000000) #define FSMC_WAIT_TIMING_DURING_WS ((uint32_t)0x00000800) /** * @} */ /** @defgroup FSMC_Write_Operation FSMC Write Operation * @{ */ #define FSMC_WRITE_OPERATION_DISABLE ((uint32_t)0x00000000) #define FSMC_WRITE_OPERATION_ENABLE ((uint32_t)0x00001000) /** * @} */ /** @defgroup FSMC_Wait_Signal FSMC Wait Signal * @{ */ #define FSMC_WAIT_SIGNAL_DISABLE ((uint32_t)0x00000000) #define FSMC_WAIT_SIGNAL_ENABLE ((uint32_t)0x00002000) /** * @} */ /** @defgroup FSMC_Extended_Mode FSMC Extended Mode * @{ */ #define FSMC_EXTENDED_MODE_DISABLE ((uint32_t)0x00000000) #define FSMC_EXTENDED_MODE_ENABLE ((uint32_t)0x00004000) /** * @} */ /** @defgroup FSMC_AsynchronousWait FSMC Asynchronous Wait * @{ */ #define FSMC_ASYNCHRONOUS_WAIT_DISABLE ((uint32_t)0x00000000) #define FSMC_ASYNCHRONOUS_WAIT_ENABLE ((uint32_t)0x00008000) /** * @} */ /** @defgroup FSMC_Write_Burst FSMC Write Burst * @{ */ #define FSMC_WRITE_BURST_DISABLE ((uint32_t)0x00000000) #define FSMC_WRITE_BURST_ENABLE ((uint32_t)0x00080000) /** * @} */ /** @defgroup FSMC_Continous_Clock FSMC Continous Clock * @{ */ #define FSMC_CONTINUOUS_CLOCK_SYNC_ONLY ((uint32_t)0x00000000) #define FSMC_CONTINUOUS_CLOCK_SYNC_ASYNC ((uint32_t)0x00100000) /** * @} */ /** @defgroup FSMC_Access_Mode FSMC Access Mode * @{ */ #define FSMC_ACCESS_MODE_A ((uint32_t)0x00000000) #define FSMC_ACCESS_MODE_B ((uint32_t)0x10000000) #define FSMC_ACCESS_MODE_C ((uint32_t)0x20000000) #define FSMC_ACCESS_MODE_D ((uint32_t)0x30000000) /** * @} */ /** * @} */ #if defined(STM32F405xx) || defined(STM32F415xx) || defined(STM32F407xx) || defined(STM32F417xx) /** @defgroup FSMC_LL_NAND_Controller FSMC NAND and PCCARD Controller * @{ */ /** @defgroup FSMC_NAND_Bank FSMC NAND Bank * @{ */ #define FSMC_NAND_BANK2 ((uint32_t)0x00000010) #define FSMC_NAND_BANK3 ((uint32_t)0x00000100) /** * @} */ /** @defgroup FSMC_Wait_feature FSMC Wait feature * @{ */ #define FSMC_NAND_PCC_WAIT_FEATURE_DISABLE ((uint32_t)0x00000000) #define FSMC_NAND_PCC_WAIT_FEATURE_ENABLE ((uint32_t)0x00000002) /** * @} */ /** @defgroup FSMC_PCR_Memory_Type FSMC PCR Memory Type * @{ */ #define FSMC_PCR_MEMORY_TYPE_PCCARD ((uint32_t)0x00000000) #define FSMC_PCR_MEMORY_TYPE_NAND ((uint32_t)0x00000008) /** * @} */ /** @defgroup FSMC_NAND_Data_Width FSMC NAND Data Width * @{ */ #define FSMC_NAND_PCC_MEM_BUS_WIDTH_8 ((uint32_t)0x00000000) #define FSMC_NAND_PCC_MEM_BUS_WIDTH_16 ((uint32_t)0x00000010) /** * @} */ /** @defgroup FSMC_ECC FSMC ECC * @{ */ #define FSMC_NAND_ECC_DISABLE ((uint32_t)0x00000000) #define FSMC_NAND_ECC_ENABLE ((uint32_t)0x00000040) /** * @} */ /** @defgroup FSMC_ECC_Page_Size FSMC ECC Page Size * @{ */ #define FSMC_NAND_ECC_PAGE_SIZE_256BYTE ((uint32_t)0x00000000) #define FSMC_NAND_ECC_PAGE_SIZE_512BYTE ((uint32_t)0x00020000) #define FSMC_NAND_ECC_PAGE_SIZE_1024BYTE ((uint32_t)0x00040000) #define FSMC_NAND_ECC_PAGE_SIZE_2048BYTE ((uint32_t)0x00060000) #define FSMC_NAND_ECC_PAGE_SIZE_4096BYTE ((uint32_t)0x00080000) #define FSMC_NAND_ECC_PAGE_SIZE_8192BYTE ((uint32_t)0x000A0000) /** * @} */ /** * @} */ #endif /* STM32F405xx || STM32F415xx || STM32F407xx || STM32F417xx */ /** @defgroup FSMC_LL_Interrupt_definition FSMC Interrupt definition * @{ */ #define FSMC_IT_RISING_EDGE ((uint32_t)0x00000008) #define FSMC_IT_LEVEL ((uint32_t)0x00000010) #define FSMC_IT_FALLING_EDGE ((uint32_t)0x00000020) #define FSMC_IT_REFRESH_ERROR ((uint32_t)0x00004000) /** * @} */ /** @defgroup FSMC_LL_Flag_definition FSMC Flag definition * @{ */ #define FSMC_FLAG_RISING_EDGE ((uint32_t)0x00000001) #define FSMC_FLAG_LEVEL ((uint32_t)0x00000002) #define FSMC_FLAG_FALLING_EDGE ((uint32_t)0x00000004) #define FSMC_FLAG_FEMPT ((uint32_t)0x00000040) /** * @} */ /** @defgroup FSMC_LL_Alias_definition FSMC Alias definition * @{ */ #define FSMC_NORSRAM_TypeDef FSMC_Bank1_TypeDef #define FSMC_NORSRAM_EXTENDED_TypeDef FSMC_Bank1E_TypeDef #if defined(STM32F405xx) || defined(STM32F415xx) || defined(STM32F407xx) || defined(STM32F417xx) #define FSMC_NAND_TypeDef FSMC_Bank2_3_TypeDef #define FSMC_PCCARD_TypeDef FSMC_Bank4_TypeDef #endif /* STM32F405xx || STM32F415xx || STM32F407xx || STM32F417xx */ #define FSMC_NORSRAM_DEVICE FSMC_Bank1 #define FSMC_NORSRAM_EXTENDED_DEVICE FSMC_Bank1E #if defined(STM32F405xx) || defined(STM32F415xx) || defined(STM32F407xx) || defined(STM32F417xx) #define FSMC_NAND_DEVICE FSMC_Bank2_3 #define FSMC_PCCARD_DEVICE FSMC_Bank4 #endif /* STM32F405xx || STM32F415xx || STM32F407xx || STM32F417xx */ #define FMC_NORSRAM_TypeDef FSMC_NORSRAM_TypeDef #define FMC_NORSRAM_EXTENDED_TypeDef FSMC_NORSRAM_EXTENDED_TypeDef #define FMC_NORSRAM_InitTypeDef FSMC_NORSRAM_InitTypeDef #define FMC_NORSRAM_TimingTypeDef FSMC_NORSRAM_TimingTypeDef #define FMC_NORSRAM_Init FSMC_NORSRAM_Init #define FMC_NORSRAM_Timing_Init FSMC_NORSRAM_Timing_Init #define FMC_NORSRAM_Extended_Timing_Init FSMC_NORSRAM_Extended_Timing_Init #define FMC_NORSRAM_DeInit FSMC_NORSRAM_DeInit #define FMC_NORSRAM_WriteOperation_Enable FSMC_NORSRAM_WriteOperation_Enable #define FMC_NORSRAM_WriteOperation_Disable FSMC_NORSRAM_WriteOperation_Disable #define __FMC_NORSRAM_ENABLE __FSMC_NORSRAM_ENABLE #define __FMC_NORSRAM_DISABLE __FSMC_NORSRAM_DISABLE #if defined(STM32F405xx) || defined(STM32F415xx) || defined(STM32F407xx) || defined(STM32F417xx) #define FMC_NAND_InitTypeDef FSMC_NAND_InitTypeDef #define FMC_PCCARD_InitTypeDef FSMC_PCCARD_InitTypeDef #define FMC_NAND_PCC_TimingTypeDef FSMC_NAND_PCC_TimingTypeDef #define FMC_NAND_Init FSMC_NAND_Init #define FMC_NAND_CommonSpace_Timing_Init FSMC_NAND_CommonSpace_Timing_Init #define FMC_NAND_AttributeSpace_Timing_Init FSMC_NAND_AttributeSpace_Timing_Init #define FMC_NAND_DeInit FSMC_NAND_DeInit #define FMC_NAND_ECC_Enable FSMC_NAND_ECC_Enable #define FMC_NAND_ECC_Disable FSMC_NAND_ECC_Disable #define FMC_NAND_GetECC FSMC_NAND_GetECC #define FMC_PCCARD_Init FSMC_PCCARD_Init #define FMC_PCCARD_CommonSpace_Timing_Init FSMC_PCCARD_CommonSpace_Timing_Init #define FMC_PCCARD_AttributeSpace_Timing_Init FSMC_PCCARD_AttributeSpace_Timing_Init #define FMC_PCCARD_IOSpace_Timing_Init FSMC_PCCARD_IOSpace_Timing_Init #define FMC_PCCARD_DeInit FSMC_PCCARD_DeInit #define __FMC_NAND_ENABLE __FSMC_NAND_ENABLE #define __FMC_NAND_DISABLE __FSMC_NAND_DISABLE #define __FMC_PCCARD_ENABLE __FSMC_PCCARD_ENABLE #define __FMC_PCCARD_DISABLE __FSMC_PCCARD_DISABLE #define __FMC_NAND_ENABLE_IT __FSMC_NAND_ENABLE_IT #define __FMC_NAND_DISABLE_IT __FSMC_NAND_DISABLE_IT #define __FMC_NAND_GET_FLAG __FSMC_NAND_GET_FLAG #define __FMC_NAND_CLEAR_FLAG __FSMC_NAND_CLEAR_FLAG #define __FMC_PCCARD_ENABLE_IT __FSMC_PCCARD_ENABLE_IT #define __FMC_PCCARD_DISABLE_IT __FSMC_PCCARD_DISABLE_IT #define __FMC_PCCARD_GET_FLAG __FSMC_PCCARD_GET_FLAG #define __FMC_PCCARD_CLEAR_FLAG __FSMC_PCCARD_CLEAR_FLAG #endif /* STM32F405xx || STM32F415xx || STM32F407xx || STM32F417xx */ #define FMC_NORSRAM_TypeDef FSMC_NORSRAM_TypeDef #define FMC_NORSRAM_EXTENDED_TypeDef FSMC_NORSRAM_EXTENDED_TypeDef #if defined(STM32F405xx) || defined(STM32F415xx) || defined(STM32F407xx) || defined(STM32F417xx) #define FMC_NAND_TypeDef FSMC_NAND_TypeDef #define FMC_PCCARD_TypeDef FSMC_PCCARD_TypeDef #endif /* STM32F405xx || STM32F415xx || STM32F407xx || STM32F417xx */ #define FMC_NORSRAM_DEVICE FSMC_NORSRAM_DEVICE #define FMC_NORSRAM_EXTENDED_DEVICE FSMC_NORSRAM_EXTENDED_DEVICE #if defined(STM32F405xx) || defined(STM32F415xx) || defined(STM32F407xx) || defined(STM32F417xx) #define FMC_NAND_DEVICE FSMC_NAND_DEVICE #define FMC_PCCARD_DEVICE FSMC_PCCARD_DEVICE #define FMC_NAND_BANK2 FSMC_NAND_BANK2 #endif /* STM32F405xx || STM32F415xx || STM32F407xx || STM32F417xx */ #define FMC_NORSRAM_BANK1 FSMC_NORSRAM_BANK1 #define FMC_NORSRAM_BANK2 FSMC_NORSRAM_BANK2 #define FMC_NORSRAM_BANK3 FSMC_NORSRAM_BANK3 #define FMC_IT_RISING_EDGE FSMC_IT_RISING_EDGE #define FMC_IT_LEVEL FSMC_IT_LEVEL #define FMC_IT_FALLING_EDGE FSMC_IT_FALLING_EDGE #define FMC_IT_REFRESH_ERROR FSMC_IT_REFRESH_ERROR #define FMC_FLAG_RISING_EDGE FSMC_FLAG_RISING_EDGE #define FMC_FLAG_LEVEL FSMC_FLAG_LEVEL #define FMC_FLAG_FALLING_EDGE FSMC_FLAG_FALLING_EDGE #define FMC_FLAG_FEMPT FSMC_FLAG_FEMPT /** * @} */ /** * @} */ /* Private macro -------------------------------------------------------------*/ /** @defgroup FSMC_LL_Private_Macros FSMC Private Macros * @{ */ /** @defgroup FSMC_LL_NOR_Macros FSMC NOR/SRAM Exported Macros * @brief macros to handle NOR device enable/disable and read/write operations * @{ */ /** * @brief Enable the NORSRAM device access. * @param __INSTANCE__: FSMC_NORSRAM Instance * @param __BANK__: FSMC_NORSRAM Bank * @retval none */ #define __FSMC_NORSRAM_ENABLE(__INSTANCE__, __BANK__) ((__INSTANCE__)->BTCR[(__BANK__)] |= FSMC_BCR1_MBKEN) /** * @brief Disable the NORSRAM device access. * @param __INSTANCE__: FSMC_NORSRAM Instance * @param __BANK__: FSMC_NORSRAM Bank * @retval none */ #define __FSMC_NORSRAM_DISABLE(__INSTANCE__, __BANK__) ((__INSTANCE__)->BTCR[(__BANK__)] &= ~FSMC_BCR1_MBKEN) /** * @} */ /** @defgroup FSMC_LL_NAND_Macros FSMC NAND Macros * @brief macros to handle NAND device enable/disable * @{ */ #if defined(STM32F405xx) || defined(STM32F415xx) || defined(STM32F407xx) || defined(STM32F417xx) /** * @brief Enable the NAND device access. * @param __INSTANCE__: FSMC_NAND Instance * @param __BANK__: FSMC_NAND Bank * @retval none */ #define __FSMC_NAND_ENABLE(__INSTANCE__, __BANK__) (((__BANK__) == FSMC_NAND_BANK2)? ((__INSTANCE__)->PCR2 |= FSMC_PCR2_PBKEN): \ ((__INSTANCE__)->PCR3 |= FSMC_PCR3_PBKEN)) /** * @brief Disable the NAND device access. * @param __INSTANCE__: FSMC_NAND Instance * @param __BANK__: FSMC_NAND Bank * @retval none */ #define __FSMC_NAND_DISABLE(__INSTANCE__, __BANK__) (((__BANK__) == FSMC_NAND_BANK2)? ((__INSTANCE__)->PCR2 &= ~FSMC_PCR2_PBKEN): \ ((__INSTANCE__)->PCR3 &= ~FSMC_PCR3_PBKEN)) /** * @} */ /** @defgroup FSMC_LL_PCCARD_Macros FSMC PCCARD Macros * @brief macros to handle SRAM read/write operations * @{ */ /** * @brief Enable the PCCARD device access. * @param __INSTANCE__: FSMC_PCCARD Instance * @retval none */ #define __FSMC_PCCARD_ENABLE(__INSTANCE__) ((__INSTANCE__)->PCR4 |= FSMC_PCR4_PBKEN) /** * @brief Disable the PCCARD device access. * @param __INSTANCE__: FSMC_PCCARD Instance * @retval none */ #define __FSMC_PCCARD_DISABLE(__INSTANCE__) ((__INSTANCE__)->PCR4 &= ~FSMC_PCR4_PBKEN) /** * @} */ /** @defgroup FSMC_LL_Flag_Interrupt_Macros FSMC Flag&Interrupt Macros * @brief macros to handle FSMC flags and interrupts * @{ */ /** * @brief Enable the NAND device interrupt. * @param __INSTANCE__: FSMC_NAND Instance * @param __BANK__: FSMC_NAND Bank * @param __INTERRUPT__: FSMC_NAND interrupt * This parameter can be any combination of the following values: * @arg FSMC_IT_RISING_EDGE: Interrupt rising edge. * @arg FSMC_IT_LEVEL: Interrupt level. * @arg FSMC_IT_FALLING_EDGE: Interrupt falling edge. * @retval None */ #define __FSMC_NAND_ENABLE_IT(__INSTANCE__, __BANK__, __INTERRUPT__) (((__BANK__) == FSMC_NAND_BANK2)? ((__INSTANCE__)->SR2 |= (__INTERRUPT__)): \ ((__INSTANCE__)->SR3 |= (__INTERRUPT__))) /** * @brief Disable the NAND device interrupt. * @param __INSTANCE__: FSMC_NAND Instance * @param __BANK__: FSMC_NAND Bank * @param __INTERRUPT__: FSMC_NAND interrupt * This parameter can be any combination of the following values: * @arg FSMC_IT_RISING_EDGE: Interrupt rising edge. * @arg FSMC_IT_LEVEL: Interrupt level. * @arg FSMC_IT_FALLING_EDGE: Interrupt falling edge. * @retval None */ #define __FSMC_NAND_DISABLE_IT(__INSTANCE__, __BANK__, __INTERRUPT__) (((__BANK__) == FSMC_NAND_BANK2)? ((__INSTANCE__)->SR2 &= ~(__INTERRUPT__)): \ ((__INSTANCE__)->SR3 &= ~(__INTERRUPT__))) /** * @brief Get flag status of the NAND device. * @param __INSTANCE__: FSMC_NAND Instance * @param __BANK__ : FSMC_NAND Bank * @param __FLAG__ : FSMC_NAND flag * This parameter can be any combination of the following values: * @arg FSMC_FLAG_RISING_EDGE: Interrupt rising edge flag. * @arg FSMC_FLAG_LEVEL: Interrupt level edge flag. * @arg FSMC_FLAG_FALLING_EDGE: Interrupt falling edge flag. * @arg FSMC_FLAG_FEMPT: FIFO empty flag. * @retval The state of FLAG (SET or RESET). */ #define __FSMC_NAND_GET_FLAG(__INSTANCE__, __BANK__, __FLAG__) (((__BANK__) == FSMC_NAND_BANK2)? (((__INSTANCE__)->SR2 &(__FLAG__)) == (__FLAG__)): \ (((__INSTANCE__)->SR3 &(__FLAG__)) == (__FLAG__))) /** * @brief Clear flag status of the NAND device. * @param __INSTANCE__: FSMC_NAND Instance * @param __BANK__: FSMC_NAND Bank * @param __FLAG__: FSMC_NAND flag * This parameter can be any combination of the following values: * @arg FSMC_FLAG_RISING_EDGE: Interrupt rising edge flag. * @arg FSMC_FLAG_LEVEL: Interrupt level edge flag. * @arg FSMC_FLAG_FALLING_EDGE: Interrupt falling edge flag. * @arg FSMC_FLAG_FEMPT: FIFO empty flag. * @retval None */ #define __FSMC_NAND_CLEAR_FLAG(__INSTANCE__, __BANK__, __FLAG__) (((__BANK__) == FSMC_NAND_BANK2)? ((__INSTANCE__)->SR2 &= ~(__FLAG__)): \ ((__INSTANCE__)->SR3 &= ~(__FLAG__))) /** * @brief Enable the PCCARD device interrupt. * @param __INSTANCE__: FSMC_PCCARD Instance * @param __INTERRUPT__: FSMC_PCCARD interrupt * This parameter can be any combination of the following values: * @arg FSMC_IT_RISING_EDGE: Interrupt rising edge. * @arg FSMC_IT_LEVEL: Interrupt level. * @arg FSMC_IT_FALLING_EDGE: Interrupt falling edge. * @retval None */ #define __FSMC_PCCARD_ENABLE_IT(__INSTANCE__, __INTERRUPT__) ((__INSTANCE__)->SR4 |= (__INTERRUPT__)) /** * @brief Disable the PCCARD device interrupt. * @param __INSTANCE__: FSMC_PCCARD Instance * @param __INTERRUPT__: FSMC_PCCARD interrupt * This parameter can be any combination of the following values: * @arg FSMC_IT_RISING_EDGE: Interrupt rising edge. * @arg FSMC_IT_LEVEL: Interrupt level. * @arg FSMC_IT_FALLING_EDGE: Interrupt falling edge. * @retval None */ #define __FSMC_PCCARD_DISABLE_IT(__INSTANCE__, __INTERRUPT__) ((__INSTANCE__)->SR4 &= ~(__INTERRUPT__)) /** * @brief Get flag status of the PCCARD device. * @param __INSTANCE__: FSMC_PCCARD Instance * @param __FLAG__: FSMC_PCCARD flag * This parameter can be any combination of the following values: * @arg FSMC_FLAG_RISING_EDGE: Interrupt rising edge flag. * @arg FSMC_FLAG_LEVEL: Interrupt level edge flag. * @arg FSMC_FLAG_FALLING_EDGE: Interrupt falling edge flag. * @arg FSMC_FLAG_FEMPT: FIFO empty flag. * @retval The state of FLAG (SET or RESET). */ #define __FSMC_PCCARD_GET_FLAG(__INSTANCE__, __FLAG__) (((__INSTANCE__)->SR4 &(__FLAG__)) == (__FLAG__)) /** * @brief Clear flag status of the PCCARD device. * @param __INSTANCE__: FSMC_PCCARD Instance * @param __FLAG__: FSMC_PCCARD flag * This parameter can be any combination of the following values: * @arg FSMC_FLAG_RISING_EDGE: Interrupt rising edge flag. * @arg FSMC_FLAG_LEVEL: Interrupt level edge flag. * @arg FSMC_FLAG_FALLING_EDGE: Interrupt falling edge flag. * @arg FSMC_FLAG_FEMPT: FIFO empty flag. * @retval None */ #define __FSMC_PCCARD_CLEAR_FLAG(__INSTANCE__, __FLAG__) ((__INSTANCE__)->SR4 &= ~(__FLAG__)) /** * @} */ #endif /* STM32F405xx || STM32F415xx || STM32F407xx || STM32F417xx */ /** @defgroup FSMC_LL_Assert_Macros FSMC Assert Macros * @{ */ #define IS_FSMC_NORSRAM_BANK(__BANK__) (((__BANK__) == FSMC_NORSRAM_BANK1) || \ ((__BANK__) == FSMC_NORSRAM_BANK2) || \ ((__BANK__) == FSMC_NORSRAM_BANK3) || \ ((__BANK__) == FSMC_NORSRAM_BANK4)) #define IS_FSMC_MUX(__MUX__) (((__MUX__) == FSMC_DATA_ADDRESS_MUX_DISABLE) || \ ((__MUX__) == FSMC_DATA_ADDRESS_MUX_ENABLE)) #define IS_FSMC_MEMORY(__MEMORY__) (((__MEMORY__) == FSMC_MEMORY_TYPE_SRAM) || \ ((__MEMORY__) == FSMC_MEMORY_TYPE_PSRAM)|| \ ((__MEMORY__) == FSMC_MEMORY_TYPE_NOR)) #define IS_FSMC_NORSRAM_MEMORY_WIDTH(__WIDTH__) (((__WIDTH__) == FSMC_NORSRAM_MEM_BUS_WIDTH_8) || \ ((__WIDTH__) == FSMC_NORSRAM_MEM_BUS_WIDTH_16) || \ ((__WIDTH__) == FSMC_NORSRAM_MEM_BUS_WIDTH_32)) #define IS_FSMC_ACCESS_MODE(__MODE__) (((__MODE__) == FSMC_ACCESS_MODE_A) || \ ((__MODE__) == FSMC_ACCESS_MODE_B) || \ ((__MODE__) == FSMC_ACCESS_MODE_C) || \ ((__MODE__) == FSMC_ACCESS_MODE_D)) #define IS_FSMC_NAND_BANK(BANK) (((BANK) == FSMC_NAND_BANK2) || \ ((BANK) == FSMC_NAND_BANK3)) #define IS_FSMC_WAIT_FEATURE(FEATURE) (((FEATURE) == FSMC_NAND_PCC_WAIT_FEATURE_DISABLE) || \ ((FEATURE) == FSMC_NAND_PCC_WAIT_FEATURE_ENABLE)) #define IS_FSMC_NAND_MEMORY_WIDTH(WIDTH) (((WIDTH) == FSMC_NAND_PCC_MEM_BUS_WIDTH_8) || \ ((WIDTH) == FSMC_NAND_PCC_MEM_BUS_WIDTH_16)) #define IS_FSMC_ECC_STATE(STATE) (((STATE) == FSMC_NAND_ECC_DISABLE) || \ ((STATE) == FSMC_NAND_ECC_ENABLE)) #define IS_FSMC_ECCPAGE_SIZE(SIZE) (((SIZE) == FSMC_NAND_ECC_PAGE_SIZE_256BYTE) || \ ((SIZE) == FSMC_NAND_ECC_PAGE_SIZE_512BYTE) || \ ((SIZE) == FSMC_NAND_ECC_PAGE_SIZE_1024BYTE) || \ ((SIZE) == FSMC_NAND_ECC_PAGE_SIZE_2048BYTE) || \ ((SIZE) == FSMC_NAND_ECC_PAGE_SIZE_4096BYTE) || \ ((SIZE) == FSMC_NAND_ECC_PAGE_SIZE_8192BYTE)) #define IS_FSMC_TCLR_TIME(TIME) ((TIME) <= 255) #define IS_FSMC_TAR_TIME(TIME) ((TIME) <= 255) #define IS_FSMC_SETUP_TIME(TIME) ((TIME) <= 255) #define IS_FSMC_WAIT_TIME(TIME) ((TIME) <= 255) #define IS_FSMC_HOLD_TIME(TIME) ((TIME) <= 255) #define IS_FSMC_HIZ_TIME(TIME) ((TIME) <= 255) #define IS_FSMC_NORSRAM_DEVICE(__INSTANCE__) ((__INSTANCE__) == FSMC_NORSRAM_DEVICE) #define IS_FSMC_NORSRAM_EXTENDED_DEVICE(__INSTANCE__) ((__INSTANCE__) == FSMC_NORSRAM_EXTENDED_DEVICE) #define IS_FSMC_NAND_DEVICE(INSTANCE) ((INSTANCE) == FSMC_NAND_DEVICE) #define IS_FSMC_PCCARD_DEVICE(INSTANCE) ((INSTANCE) == FSMC_PCCARD_DEVICE) #define IS_FSMC_BURSTMODE(__STATE__) (((__STATE__) == FSMC_BURST_ACCESS_MODE_DISABLE) || \ ((__STATE__) == FSMC_BURST_ACCESS_MODE_ENABLE)) #define IS_FSMC_WAIT_POLARITY(__POLARITY__) (((__POLARITY__) == FSMC_WAIT_SIGNAL_POLARITY_LOW) || \ ((__POLARITY__) == FSMC_WAIT_SIGNAL_POLARITY_HIGH)) #define IS_FSMC_WRAP_MODE(__MODE__) (((__MODE__) == FSMC_WRAP_MODE_DISABLE) || \ ((__MODE__) == FSMC_WRAP_MODE_ENABLE)) #define IS_FSMC_WAIT_SIGNAL_ACTIVE(__ACTIVE__) (((__ACTIVE__) == FSMC_WAIT_TIMING_BEFORE_WS) || \ ((__ACTIVE__) == FSMC_WAIT_TIMING_DURING_WS)) #define IS_FSMC_WRITE_OPERATION(__OPERATION__) (((__OPERATION__) == FSMC_WRITE_OPERATION_DISABLE) || \ ((__OPERATION__) == FSMC_WRITE_OPERATION_ENABLE)) #define IS_FSMC_WAITE_SIGNAL(__SIGNAL__) (((__SIGNAL__) == FSMC_WAIT_SIGNAL_DISABLE) || \ ((__SIGNAL__) == FSMC_WAIT_SIGNAL_ENABLE)) #define IS_FSMC_EXTENDED_MODE(__MODE__) (((__MODE__) == FSMC_EXTENDED_MODE_DISABLE) || \ ((__MODE__) == FSMC_EXTENDED_MODE_ENABLE)) #define IS_FSMC_ASYNWAIT(__STATE__) (((__STATE__) == FSMC_ASYNCHRONOUS_WAIT_DISABLE) || \ ((__STATE__) == FSMC_ASYNCHRONOUS_WAIT_ENABLE)) #define IS_FSMC_DATA_LATENCY(__LATENCY__) (((__LATENCY__) > 1) && ((__LATENCY__) <= 17)) #define IS_FSMC_WRITE_BURST(__BURST__) (((__BURST__) == FSMC_WRITE_BURST_DISABLE) || \ ((__BURST__) == FSMC_WRITE_BURST_ENABLE)) #define IS_FSMC_ADDRESS_SETUP_TIME(__TIME__) ((__TIME__) <= 15) #define IS_FSMC_ADDRESS_HOLD_TIME(__TIME__) (((__TIME__) > 0) && ((__TIME__) <= 15)) #define IS_FSMC_DATASETUP_TIME(__TIME__) (((__TIME__) > 0) && ((__TIME__) <= 255)) #define IS_FSMC_TURNAROUND_TIME(__TIME__) ((__TIME__) <= 15) #define IS_FSMC_CONTINOUS_CLOCK(CCLOCK) (((CCLOCK) == FSMC_CONTINUOUS_CLOCK_SYNC_ONLY) || \ ((CCLOCK) == FSMC_CONTINUOUS_CLOCK_SYNC_ASYNC)) #define IS_FSMC_CLK_DIV(DIV) (((DIV) > 1) && ((DIV) <= 16)) /** * @} */ /** * @} */ /* Private functions ---------------------------------------------------------*/ /** @defgroup FSMC_LL_Private_Functions FSMC LL Private Functions * @{ */ /** @defgroup FSMC_LL_NORSRAM NOR SRAM * @{ */ /** @defgroup FSMC_LL_NORSRAM_Private_Functions_Group1 NOR SRAM Initialization/de-initialization functions * @{ */ HAL_StatusTypeDef FSMC_NORSRAM_Init(FSMC_NORSRAM_TypeDef *Device, FSMC_NORSRAM_InitTypeDef *Init); HAL_StatusTypeDef FSMC_NORSRAM_Timing_Init(FSMC_NORSRAM_TypeDef *Device, FSMC_NORSRAM_TimingTypeDef *Timing, uint32_t Bank); HAL_StatusTypeDef FSMC_NORSRAM_Extended_Timing_Init(FSMC_NORSRAM_EXTENDED_TypeDef *Device, FSMC_NORSRAM_TimingTypeDef *Timing, uint32_t Bank, uint32_t ExtendedMode); HAL_StatusTypeDef FSMC_NORSRAM_DeInit(FSMC_NORSRAM_TypeDef *Device, FSMC_NORSRAM_EXTENDED_TypeDef *ExDevice, uint32_t Bank); /** * @} */ /** @defgroup FSMC_LL_NORSRAM_Private_Functions_Group2 NOR SRAM Control functions * @{ */ HAL_StatusTypeDef FSMC_NORSRAM_WriteOperation_Enable(FSMC_NORSRAM_TypeDef *Device, uint32_t Bank); HAL_StatusTypeDef FSMC_NORSRAM_WriteOperation_Disable(FSMC_NORSRAM_TypeDef *Device, uint32_t Bank); /** * @} */ /** * @} */ #if defined(STM32F405xx) || defined(STM32F415xx) || defined(STM32F407xx) || defined(STM32F417xx) /** @defgroup FSMC_LL_NAND NAND * @{ */ /** @defgroup FSMC_LL_NAND_Private_Functions_Group1 NAND Initialization/de-initialization functions * @{ */ HAL_StatusTypeDef FSMC_NAND_Init(FSMC_NAND_TypeDef *Device, FSMC_NAND_InitTypeDef *Init); HAL_StatusTypeDef FSMC_NAND_CommonSpace_Timing_Init(FSMC_NAND_TypeDef *Device, FSMC_NAND_PCC_TimingTypeDef *Timing, uint32_t Bank); HAL_StatusTypeDef FSMC_NAND_AttributeSpace_Timing_Init(FSMC_NAND_TypeDef *Device, FSMC_NAND_PCC_TimingTypeDef *Timing, uint32_t Bank); HAL_StatusTypeDef FSMC_NAND_DeInit(FSMC_NAND_TypeDef *Device, uint32_t Bank); /** * @} */ /** @defgroup FSMC_LL_NAND_Private_Functions_Group2 NAND Control functions * @{ */ HAL_StatusTypeDef FSMC_NAND_ECC_Enable(FSMC_NAND_TypeDef *Device, uint32_t Bank); HAL_StatusTypeDef FSMC_NAND_ECC_Disable(FSMC_NAND_TypeDef *Device, uint32_t Bank); HAL_StatusTypeDef FSMC_NAND_GetECC(FSMC_NAND_TypeDef *Device, uint32_t *ECCval, uint32_t Bank, uint32_t Timeout); /** * @} */ /** * @} */ /** @defgroup FSMC_LL_PCCARD PCCARD * @{ */ /** @defgroup FSMC_LL_PCCARD_Private_Functions_Group1 PCCARD Initialization/de-initialization functions * @{ */ HAL_StatusTypeDef FSMC_PCCARD_Init(FSMC_PCCARD_TypeDef *Device, FSMC_PCCARD_InitTypeDef *Init); HAL_StatusTypeDef FSMC_PCCARD_CommonSpace_Timing_Init(FSMC_PCCARD_TypeDef *Device, FSMC_NAND_PCC_TimingTypeDef *Timing); HAL_StatusTypeDef FSMC_PCCARD_AttributeSpace_Timing_Init(FSMC_PCCARD_TypeDef *Device, FSMC_NAND_PCC_TimingTypeDef *Timing); HAL_StatusTypeDef FSMC_PCCARD_IOSpace_Timing_Init(FSMC_PCCARD_TypeDef *Device, FSMC_NAND_PCC_TimingTypeDef *Timing); HAL_StatusTypeDef FSMC_PCCARD_DeInit(FSMC_PCCARD_TypeDef *Device); /** * @} */ /** * @} */ #endif /* STM32F405xx || STM32F415xx || STM32F407xx || STM32F417xx */ /** * @} */ #endif /* STM32F405xx || STM32F415xx || STM32F407xx || STM32F417xx */ /** * @} */ /** * @} */ #ifdef __cplusplus } #endif #endif /* __STM32F4xx_LL_FSMC_H */ /************************ (C) COPYRIGHT STMicroelectronics *****END OF FILE****/ ================================================ FILE: Zelig/mbed/TARGET_NUCLEO_F411RE/stm32f4xx_ll_sdmmc.h ================================================ /** ****************************************************************************** * @file stm32f4xx_ll_sdmmc.h * @author MCD Application Team * @version V1.4.1 * @date 09-October-2015 * @brief Header file of SDMMC HAL module. ****************************************************************************** * @attention * *

© COPYRIGHT(c) 2015 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. * ****************************************************************************** */ /* Define to prevent recursive inclusion -------------------------------------*/ #ifndef __STM32F4xx_LL_SDMMC_H #define __STM32F4xx_LL_SDMMC_H #ifdef __cplusplus extern "C" { #endif #if defined(STM32F405xx) || defined(STM32F415xx) || defined(STM32F407xx) || defined(STM32F417xx) || \ defined(STM32F427xx) || defined(STM32F437xx) || defined(STM32F429xx) || defined(STM32F439xx) || \ defined(STM32F401xC) || defined(STM32F401xE) || defined(STM32F411xE) || defined(STM32F446xx) || \ defined(STM32F469xx) || defined(STM32F479xx) /* Includes ------------------------------------------------------------------*/ #include "stm32f4xx_hal_def.h" /** @addtogroup STM32F4xx_Driver * @{ */ /** @addtogroup SDMMC_LL * @{ */ /* Exported types ------------------------------------------------------------*/ /** @defgroup SDMMC_LL_Exported_Types SDMMC_LL Exported Types * @{ */ /** * @brief SDMMC Configuration Structure definition */ typedef struct { uint32_t ClockEdge; /*!< Specifies the clock transition on which the bit capture is made. This parameter can be a value of @ref SDIO_Clock_Edge */ uint32_t ClockBypass; /*!< Specifies whether the SDIO Clock divider bypass is enabled or disabled. This parameter can be a value of @ref SDIO_Clock_Bypass */ uint32_t ClockPowerSave; /*!< Specifies whether SDIO Clock output is enabled or disabled when the bus is idle. This parameter can be a value of @ref SDIO_Clock_Power_Save */ uint32_t BusWide; /*!< Specifies the SDIO bus width. This parameter can be a value of @ref SDIO_Bus_Wide */ uint32_t HardwareFlowControl; /*!< Specifies whether the SDIO hardware flow control is enabled or disabled. This parameter can be a value of @ref SDIO_Hardware_Flow_Control */ uint32_t ClockDiv; /*!< Specifies the clock frequency of the SDIO controller. This parameter can be a value between Min_Data = 0 and Max_Data = 255 */ }SDIO_InitTypeDef; /** * @brief SDIO Command Control structure */ typedef struct { uint32_t Argument; /*!< Specifies the SDIO command argument which is sent to a card as part of a command message. If a command contains an argument, it must be loaded into this register before writing the command to the command register. */ uint32_t CmdIndex; /*!< Specifies the SDIO command index. It must be Min_Data = 0 and Max_Data = 64 */ uint32_t Response; /*!< Specifies the SDIO response type. This parameter can be a value of @ref SDIO_Response_Type */ uint32_t WaitForInterrupt; /*!< Specifies whether SDIO wait for interrupt request is enabled or disabled. This parameter can be a value of @ref SDIO_Wait_Interrupt_State */ uint32_t CPSM; /*!< Specifies whether SDIO Command path state machine (CPSM) is enabled or disabled. This parameter can be a value of @ref SDIO_CPSM_State */ }SDIO_CmdInitTypeDef; /** * @brief SDIO Data Control structure */ typedef struct { uint32_t DataTimeOut; /*!< Specifies the data timeout period in card bus clock periods. */ uint32_t DataLength; /*!< Specifies the number of data bytes to be transferred. */ uint32_t DataBlockSize; /*!< Specifies the data block size for block transfer. This parameter can be a value of @ref SDIO_Data_Block_Size */ uint32_t TransferDir; /*!< Specifies the data transfer direction, whether the transfer is a read or write. This parameter can be a value of @ref SDIO_Transfer_Direction */ uint32_t TransferMode; /*!< Specifies whether data transfer is in stream or block mode. This parameter can be a value of @ref SDIO_Transfer_Type */ uint32_t DPSM; /*!< Specifies whether SDIO Data path state machine (DPSM) is enabled or disabled. This parameter can be a value of @ref SDIO_DPSM_State */ }SDIO_DataInitTypeDef; /** * @} */ /* Exported constants --------------------------------------------------------*/ /** @defgroup SDMMC_LL_Exported_Constants SDMMC_LL Exported Constants * @{ */ /** @defgroup SDIO_Clock_Edge Clock Edge * @{ */ #define SDIO_CLOCK_EDGE_RISING ((uint32_t)0x00000000) #define SDIO_CLOCK_EDGE_FALLING SDIO_CLKCR_NEGEDGE #define IS_SDIO_CLOCK_EDGE(EDGE) (((EDGE) == SDIO_CLOCK_EDGE_RISING) || \ ((EDGE) == SDIO_CLOCK_EDGE_FALLING)) /** * @} */ /** @defgroup SDIO_Clock_Bypass Clock Bypass * @{ */ #define SDIO_CLOCK_BYPASS_DISABLE ((uint32_t)0x00000000) #define SDIO_CLOCK_BYPASS_ENABLE SDIO_CLKCR_BYPASS #define IS_SDIO_CLOCK_BYPASS(BYPASS) (((BYPASS) == SDIO_CLOCK_BYPASS_DISABLE) || \ ((BYPASS) == SDIO_CLOCK_BYPASS_ENABLE)) /** * @} */ /** @defgroup SDIO_Clock_Power_Save Clock Power Saving * @{ */ #define SDIO_CLOCK_POWER_SAVE_DISABLE ((uint32_t)0x00000000) #define SDIO_CLOCK_POWER_SAVE_ENABLE SDIO_CLKCR_PWRSAV #define IS_SDIO_CLOCK_POWER_SAVE(SAVE) (((SAVE) == SDIO_CLOCK_POWER_SAVE_DISABLE) || \ ((SAVE) == SDIO_CLOCK_POWER_SAVE_ENABLE)) /** * @} */ /** @defgroup SDIO_Bus_Wide Bus Width * @{ */ #define SDIO_BUS_WIDE_1B ((uint32_t)0x00000000) #define SDIO_BUS_WIDE_4B SDIO_CLKCR_WIDBUS_0 #define SDIO_BUS_WIDE_8B SDIO_CLKCR_WIDBUS_1 #define IS_SDIO_BUS_WIDE(WIDE) (((WIDE) == SDIO_BUS_WIDE_1B) || \ ((WIDE) == SDIO_BUS_WIDE_4B) || \ ((WIDE) == SDIO_BUS_WIDE_8B)) /** * @} */ /** @defgroup SDIO_Hardware_Flow_Control Hardware Flow Control * @{ */ #define SDIO_HARDWARE_FLOW_CONTROL_DISABLE ((uint32_t)0x00000000) #define SDIO_HARDWARE_FLOW_CONTROL_ENABLE SDIO_CLKCR_HWFC_EN #define IS_SDIO_HARDWARE_FLOW_CONTROL(CONTROL) (((CONTROL) == SDIO_HARDWARE_FLOW_CONTROL_DISABLE) || \ ((CONTROL) == SDIO_HARDWARE_FLOW_CONTROL_ENABLE)) /** * @} */ /** @defgroup SDIO_Clock_Division Clock Division * @{ */ #define IS_SDIO_CLKDIV(DIV) ((DIV) <= 0xFF) /** * @} */ /** @defgroup SDIO_Command_Index Command Index * @{ */ #define IS_SDIO_CMD_INDEX(INDEX) ((INDEX) < 0x40) /** * @} */ /** @defgroup SDIO_Response_Type Response Type * @{ */ #define SDIO_RESPONSE_NO ((uint32_t)0x00000000) #define SDIO_RESPONSE_SHORT SDIO_CMD_WAITRESP_0 #define SDIO_RESPONSE_LONG SDIO_CMD_WAITRESP #define IS_SDIO_RESPONSE(RESPONSE) (((RESPONSE) == SDIO_RESPONSE_NO) || \ ((RESPONSE) == SDIO_RESPONSE_SHORT) || \ ((RESPONSE) == SDIO_RESPONSE_LONG)) /** * @} */ /** @defgroup SDIO_Wait_Interrupt_State Wait Interrupt * @{ */ #define SDIO_WAIT_NO ((uint32_t)0x00000000) #define SDIO_WAIT_IT SDIO_CMD_WAITINT #define SDIO_WAIT_PEND SDIO_CMD_WAITPEND #define IS_SDIO_WAIT(WAIT) (((WAIT) == SDIO_WAIT_NO) || \ ((WAIT) == SDIO_WAIT_IT) || \ ((WAIT) == SDIO_WAIT_PEND)) /** * @} */ /** @defgroup SDIO_CPSM_State CPSM State * @{ */ #define SDIO_CPSM_DISABLE ((uint32_t)0x00000000) #define SDIO_CPSM_ENABLE SDIO_CMD_CPSMEN #define IS_SDIO_CPSM(CPSM) (((CPSM) == SDIO_CPSM_DISABLE) || \ ((CPSM) == SDIO_CPSM_ENABLE)) /** * @} */ /** @defgroup SDIO_Response_Registers Response Register * @{ */ #define SDIO_RESP1 ((uint32_t)0x00000000) #define SDIO_RESP2 ((uint32_t)0x00000004) #define SDIO_RESP3 ((uint32_t)0x00000008) #define SDIO_RESP4 ((uint32_t)0x0000000C) #define IS_SDIO_RESP(RESP) (((RESP) == SDIO_RESP1) || \ ((RESP) == SDIO_RESP2) || \ ((RESP) == SDIO_RESP3) || \ ((RESP) == SDIO_RESP4)) /** * @} */ /** @defgroup SDIO_Data_Length Data Lenght * @{ */ #define IS_SDIO_DATA_LENGTH(LENGTH) ((LENGTH) <= 0x01FFFFFF) /** * @} */ /** @defgroup SDIO_Data_Block_Size Data Block Size * @{ */ #define SDIO_DATABLOCK_SIZE_1B ((uint32_t)0x00000000) #define SDIO_DATABLOCK_SIZE_2B SDIO_DCTRL_DBLOCKSIZE_0 #define SDIO_DATABLOCK_SIZE_4B SDIO_DCTRL_DBLOCKSIZE_1 #define SDIO_DATABLOCK_SIZE_8B ((uint32_t)0x00000030) #define SDIO_DATABLOCK_SIZE_16B SDIO_DCTRL_DBLOCKSIZE_2 #define SDIO_DATABLOCK_SIZE_32B ((uint32_t)0x00000050) #define SDIO_DATABLOCK_SIZE_64B ((uint32_t)0x00000060) #define SDIO_DATABLOCK_SIZE_128B ((uint32_t)0x00000070) #define SDIO_DATABLOCK_SIZE_256B SDIO_DCTRL_DBLOCKSIZE_3 #define SDIO_DATABLOCK_SIZE_512B ((uint32_t)0x00000090) #define SDIO_DATABLOCK_SIZE_1024B ((uint32_t)0x000000A0) #define SDIO_DATABLOCK_SIZE_2048B ((uint32_t)0x000000B0) #define SDIO_DATABLOCK_SIZE_4096B ((uint32_t)0x000000C0) #define SDIO_DATABLOCK_SIZE_8192B ((uint32_t)0x000000D0) #define SDIO_DATABLOCK_SIZE_16384B ((uint32_t)0x000000E0) #define IS_SDIO_BLOCK_SIZE(SIZE) (((SIZE) == SDIO_DATABLOCK_SIZE_1B) || \ ((SIZE) == SDIO_DATABLOCK_SIZE_2B) || \ ((SIZE) == SDIO_DATABLOCK_SIZE_4B) || \ ((SIZE) == SDIO_DATABLOCK_SIZE_8B) || \ ((SIZE) == SDIO_DATABLOCK_SIZE_16B) || \ ((SIZE) == SDIO_DATABLOCK_SIZE_32B) || \ ((SIZE) == SDIO_DATABLOCK_SIZE_64B) || \ ((SIZE) == SDIO_DATABLOCK_SIZE_128B) || \ ((SIZE) == SDIO_DATABLOCK_SIZE_256B) || \ ((SIZE) == SDIO_DATABLOCK_SIZE_512B) || \ ((SIZE) == SDIO_DATABLOCK_SIZE_1024B) || \ ((SIZE) == SDIO_DATABLOCK_SIZE_2048B) || \ ((SIZE) == SDIO_DATABLOCK_SIZE_4096B) || \ ((SIZE) == SDIO_DATABLOCK_SIZE_8192B) || \ ((SIZE) == SDIO_DATABLOCK_SIZE_16384B)) /** * @} */ /** @defgroup SDIO_Transfer_Direction Transfer Direction * @{ */ #define SDIO_TRANSFER_DIR_TO_CARD ((uint32_t)0x00000000) #define SDIO_TRANSFER_DIR_TO_SDIO SDIO_DCTRL_DTDIR #define IS_SDIO_TRANSFER_DIR(DIR) (((DIR) == SDIO_TRANSFER_DIR_TO_CARD) || \ ((DIR) == SDIO_TRANSFER_DIR_TO_SDIO)) /** * @} */ /** @defgroup SDIO_Transfer_Type Transfer Type * @{ */ #define SDIO_TRANSFER_MODE_BLOCK ((uint32_t)0x00000000) #define SDIO_TRANSFER_MODE_STREAM SDIO_DCTRL_DTMODE #define IS_SDIO_TRANSFER_MODE(MODE) (((MODE) == SDIO_TRANSFER_MODE_BLOCK) || \ ((MODE) == SDIO_TRANSFER_MODE_STREAM)) /** * @} */ /** @defgroup SDIO_DPSM_State DPSM State * @{ */ #define SDIO_DPSM_DISABLE ((uint32_t)0x00000000) #define SDIO_DPSM_ENABLE SDIO_DCTRL_DTEN #define IS_SDIO_DPSM(DPSM) (((DPSM) == SDIO_DPSM_DISABLE) ||\ ((DPSM) == SDIO_DPSM_ENABLE)) /** * @} */ /** @defgroup SDIO_Read_Wait_Mode Read Wait Mode * @{ */ #define SDIO_READ_WAIT_MODE_DATA2 ((uint32_t)0x00000000) #define SDIO_READ_WAIT_MODE_CLK ((uint32_t)0x00000001) #define IS_SDIO_READWAIT_MODE(MODE) (((MODE) == SDIO_READ_WAIT_MODE_CLK) || \ ((MODE) == SDIO_READ_WAIT_MODE_DATA2)) /** * @} */ /** @defgroup SDIO_Interrupt_sources Interrupt Sources * @{ */ #define SDIO_IT_CCRCFAIL SDIO_STA_CCRCFAIL #define SDIO_IT_DCRCFAIL SDIO_STA_DCRCFAIL #define SDIO_IT_CTIMEOUT SDIO_STA_CTIMEOUT #define SDIO_IT_DTIMEOUT SDIO_STA_DTIMEOUT #define SDIO_IT_TXUNDERR SDIO_STA_TXUNDERR #define SDIO_IT_RXOVERR SDIO_STA_RXOVERR #define SDIO_IT_CMDREND SDIO_STA_CMDREND #define SDIO_IT_CMDSENT SDIO_STA_CMDSENT #define SDIO_IT_DATAEND SDIO_STA_DATAEND #define SDIO_IT_STBITERR SDIO_STA_STBITERR #define SDIO_IT_DBCKEND SDIO_STA_DBCKEND #define SDIO_IT_CMDACT SDIO_STA_CMDACT #define SDIO_IT_TXACT SDIO_STA_TXACT #define SDIO_IT_RXACT SDIO_STA_RXACT #define SDIO_IT_TXFIFOHE SDIO_STA_TXFIFOHE #define SDIO_IT_RXFIFOHF SDIO_STA_RXFIFOHF #define SDIO_IT_TXFIFOF SDIO_STA_TXFIFOF #define SDIO_IT_RXFIFOF SDIO_STA_RXFIFOF #define SDIO_IT_TXFIFOE SDIO_STA_TXFIFOE #define SDIO_IT_RXFIFOE SDIO_STA_RXFIFOE #define SDIO_IT_TXDAVL SDIO_STA_TXDAVL #define SDIO_IT_RXDAVL SDIO_STA_RXDAVL #define SDIO_IT_SDIOIT SDIO_STA_SDIOIT #define SDIO_IT_CEATAEND SDIO_STA_CEATAEND /** * @} */ /** @defgroup SDIO_Flags Flags * @{ */ #define SDIO_FLAG_CCRCFAIL SDIO_STA_CCRCFAIL #define SDIO_FLAG_DCRCFAIL SDIO_STA_DCRCFAIL #define SDIO_FLAG_CTIMEOUT SDIO_STA_CTIMEOUT #define SDIO_FLAG_DTIMEOUT SDIO_STA_DTIMEOUT #define SDIO_FLAG_TXUNDERR SDIO_STA_TXUNDERR #define SDIO_FLAG_RXOVERR SDIO_STA_RXOVERR #define SDIO_FLAG_CMDREND SDIO_STA_CMDREND #define SDIO_FLAG_CMDSENT SDIO_STA_CMDSENT #define SDIO_FLAG_DATAEND SDIO_STA_DATAEND #define SDIO_FLAG_STBITERR SDIO_STA_STBITERR #define SDIO_FLAG_DBCKEND SDIO_STA_DBCKEND #define SDIO_FLAG_CMDACT SDIO_STA_CMDACT #define SDIO_FLAG_TXACT SDIO_STA_TXACT #define SDIO_FLAG_RXACT SDIO_STA_RXACT #define SDIO_FLAG_TXFIFOHE SDIO_STA_TXFIFOHE #define SDIO_FLAG_RXFIFOHF SDIO_STA_RXFIFOHF #define SDIO_FLAG_TXFIFOF SDIO_STA_TXFIFOF #define SDIO_FLAG_RXFIFOF SDIO_STA_RXFIFOF #define SDIO_FLAG_TXFIFOE SDIO_STA_TXFIFOE #define SDIO_FLAG_RXFIFOE SDIO_STA_RXFIFOE #define SDIO_FLAG_TXDAVL SDIO_STA_TXDAVL #define SDIO_FLAG_RXDAVL SDIO_STA_RXDAVL #define SDIO_FLAG_SDIOIT SDIO_STA_SDIOIT #define SDIO_FLAG_CEATAEND SDIO_STA_CEATAEND /** * @} */ /** * @} */ /* Exported macro ------------------------------------------------------------*/ /** @defgroup SDMMC_LL_Exported_macros SDMMC_LL Exported Macros * @{ */ /** @defgroup SDMMC_LL_Alias_Region Bit Address in the alias region * @{ */ /* ------------ SDIO registers bit address in the alias region -------------- */ #define SDIO_OFFSET (SDIO_BASE - PERIPH_BASE) /* --- CLKCR Register ---*/ /* Alias word address of CLKEN bit */ #define CLKCR_OFFSET (SDIO_OFFSET + 0x04) #define CLKEN_BITNUMBER 0x08 #define CLKCR_CLKEN_BB (PERIPH_BB_BASE + (CLKCR_OFFSET * 32) + (CLKEN_BITNUMBER * 4)) /* --- CMD Register ---*/ /* Alias word address of SDIOSUSPEND bit */ #define CMD_OFFSET (SDIO_OFFSET + 0x0C) #define SDIOSUSPEND_BITNUMBER 0x0B #define CMD_SDIOSUSPEND_BB (PERIPH_BB_BASE + (CMD_OFFSET * 32) + (SDIOSUSPEND_BITNUMBER * 4)) /* Alias word address of ENCMDCOMPL bit */ #define ENCMDCOMPL_BITNUMBER 0x0C #define CMD_ENCMDCOMPL_BB (PERIPH_BB_BASE + (CMD_OFFSET * 32) + (ENCMDCOMPL_BITNUMBER * 4)) /* Alias word address of NIEN bit */ #define NIEN_BITNUMBER 0x0D #define CMD_NIEN_BB (PERIPH_BB_BASE + (CMD_OFFSET * 32) + (NIEN_BITNUMBER * 4)) /* Alias word address of ATACMD bit */ #define ATACMD_BITNUMBER 0x0E #define CMD_ATACMD_BB (PERIPH_BB_BASE + (CMD_OFFSET * 32) + (ATACMD_BITNUMBER * 4)) /* --- DCTRL Register ---*/ /* Alias word address of DMAEN bit */ #define DCTRL_OFFSET (SDIO_OFFSET + 0x2C) #define DMAEN_BITNUMBER 0x03 #define DCTRL_DMAEN_BB (PERIPH_BB_BASE + (DCTRL_OFFSET * 32) + (DMAEN_BITNUMBER * 4)) /* Alias word address of RWSTART bit */ #define RWSTART_BITNUMBER 0x08 #define DCTRL_RWSTART_BB (PERIPH_BB_BASE + (DCTRL_OFFSET * 32) + (RWSTART_BITNUMBER * 4)) /* Alias word address of RWSTOP bit */ #define RWSTOP_BITNUMBER 0x09 #define DCTRL_RWSTOP_BB (PERIPH_BB_BASE + (DCTRL_OFFSET * 32) + (RWSTOP_BITNUMBER * 4)) /* Alias word address of RWMOD bit */ #define RWMOD_BITNUMBER 0x0A #define DCTRL_RWMOD_BB (PERIPH_BB_BASE + (DCTRL_OFFSET * 32) + (RWMOD_BITNUMBER * 4)) /* Alias word address of SDIOEN bit */ #define SDIOEN_BITNUMBER 0x0B #define DCTRL_SDIOEN_BB (PERIPH_BB_BASE + (DCTRL_OFFSET * 32) + (SDIOEN_BITNUMBER * 4)) /** * @} */ /** @defgroup SDMMC_LL_Register Bits And Addresses Definitions * @brief SDMMC_LL registers bit address in the alias region * @{ */ /* ---------------------- SDIO registers bit mask --------------------------- */ /* --- CLKCR Register ---*/ /* CLKCR register clear mask */ #define CLKCR_CLEAR_MASK ((uint32_t)(SDIO_CLKCR_CLKDIV | SDIO_CLKCR_PWRSAV |\ SDIO_CLKCR_BYPASS | SDIO_CLKCR_WIDBUS |\ SDIO_CLKCR_NEGEDGE | SDIO_CLKCR_HWFC_EN)) /* --- PWRCTRL Register ---*/ /* --- DCTRL Register ---*/ /* SDIO DCTRL Clear Mask */ #define DCTRL_CLEAR_MASK ((uint32_t)(SDIO_DCTRL_DTEN | SDIO_DCTRL_DTDIR |\ SDIO_DCTRL_DTMODE | SDIO_DCTRL_DBLOCKSIZE)) /* --- CMD Register ---*/ /* CMD Register clear mask */ #define CMD_CLEAR_MASK ((uint32_t)(SDIO_CMD_CMDINDEX | SDIO_CMD_WAITRESP |\ SDIO_CMD_WAITINT | SDIO_CMD_WAITPEND |\ SDIO_CMD_CPSMEN | SDIO_CMD_SDIOSUSPEND)) /* SDIO RESP Registers Address */ #define SDIO_RESP_ADDR ((uint32_t)(SDIO_BASE + 0x14)) /* SDIO Initialization Frequency (400KHz max) */ #define SDIO_INIT_CLK_DIV ((uint8_t)0x76) /* SDIO Data Transfer Frequency (25MHz max) */ #define SDIO_TRANSFER_CLK_DIV ((uint8_t)0x0) /** * @} */ /** @defgroup SDMMC_LL_Interrupt_Clock Interrupt And Clock Configuration * @brief macros to handle interrupts and specific clock configurations * @{ */ /** * @brief Enable the SDIO device. * @retval None */ #define __SDIO_ENABLE() (*(__IO uint32_t *)CLKCR_CLKEN_BB = ENABLE) /** * @brief Disable the SDIO device. * @retval None */ #define __SDIO_DISABLE() (*(__IO uint32_t *)CLKCR_CLKEN_BB = DISABLE) /** * @brief Enable the SDIO DMA transfer. * @retval None */ #define __SDIO_DMA_ENABLE() (*(__IO uint32_t *)DCTRL_DMAEN_BB = ENABLE) /** * @brief Disable the SDIO DMA transfer. * @retval None */ #define __SDIO_DMA_DISABLE() (*(__IO uint32_t *)DCTRL_DMAEN_BB = DISABLE) /** * @brief Enable the SDIO device interrupt. * @param __INSTANCE__ : Pointer to SDIO register base * @param __INTERRUPT__ : specifies the SDIO interrupt sources to be enabled. * This parameter can be one or a combination of the following values: * @arg SDIO_IT_CCRCFAIL: Command response received (CRC check failed) interrupt * @arg SDIO_IT_DCRCFAIL: Data block sent/received (CRC check failed) interrupt * @arg SDIO_IT_CTIMEOUT: Command response timeout interrupt * @arg SDIO_IT_DTIMEOUT: Data timeout interrupt * @arg SDIO_IT_TXUNDERR: Transmit FIFO underrun error interrupt * @arg SDIO_IT_RXOVERR: Received FIFO overrun error interrupt * @arg SDIO_IT_CMDREND: Command response received (CRC check passed) interrupt * @arg SDIO_IT_CMDSENT: Command sent (no response required) interrupt * @arg SDIO_IT_DATAEND: Data end (data counter, SDIDCOUNT, is zero) interrupt * @arg SDIO_IT_STBITERR: Start bit not detected on all data signals in wide * bus mode interrupt * @arg SDIO_IT_DBCKEND: Data block sent/received (CRC check passed) interrupt * @arg SDIO_IT_CMDACT: Command transfer in progress interrupt * @arg SDIO_IT_TXACT: Data transmit in progress interrupt * @arg SDIO_IT_RXACT: Data receive in progress interrupt * @arg SDIO_IT_TXFIFOHE: Transmit FIFO Half Empty interrupt * @arg SDIO_IT_RXFIFOHF: Receive FIFO Half Full interrupt * @arg SDIO_IT_TXFIFOF: Transmit FIFO full interrupt * @arg SDIO_IT_RXFIFOF: Receive FIFO full interrupt * @arg SDIO_IT_TXFIFOE: Transmit FIFO empty interrupt * @arg SDIO_IT_RXFIFOE: Receive FIFO empty interrupt * @arg SDIO_IT_TXDAVL: Data available in transmit FIFO interrupt * @arg SDIO_IT_RXDAVL: Data available in receive FIFO interrupt * @arg SDIO_IT_SDIOIT: SD I/O interrupt received interrupt * @arg SDIO_IT_CEATAEND: CE-ATA command completion signal received for CMD61 interrupt * @retval None */ #define __SDIO_ENABLE_IT(__INSTANCE__, __INTERRUPT__) ((__INSTANCE__)->MASK |= (__INTERRUPT__)) /** * @brief Disable the SDIO device interrupt. * @param __INSTANCE__ : Pointer to SDIO register base * @param __INTERRUPT__ : specifies the SDIO interrupt sources to be disabled. * This parameter can be one or a combination of the following values: * @arg SDIO_IT_CCRCFAIL: Command response received (CRC check failed) interrupt * @arg SDIO_IT_DCRCFAIL: Data block sent/received (CRC check failed) interrupt * @arg SDIO_IT_CTIMEOUT: Command response timeout interrupt * @arg SDIO_IT_DTIMEOUT: Data timeout interrupt * @arg SDIO_IT_TXUNDERR: Transmit FIFO underrun error interrupt * @arg SDIO_IT_RXOVERR: Received FIFO overrun error interrupt * @arg SDIO_IT_CMDREND: Command response received (CRC check passed) interrupt * @arg SDIO_IT_CMDSENT: Command sent (no response required) interrupt * @arg SDIO_IT_DATAEND: Data end (data counter, SDIDCOUNT, is zero) interrupt * @arg SDIO_IT_STBITERR: Start bit not detected on all data signals in wide * bus mode interrupt * @arg SDIO_IT_DBCKEND: Data block sent/received (CRC check passed) interrupt * @arg SDIO_IT_CMDACT: Command transfer in progress interrupt * @arg SDIO_IT_TXACT: Data transmit in progress interrupt * @arg SDIO_IT_RXACT: Data receive in progress interrupt * @arg SDIO_IT_TXFIFOHE: Transmit FIFO Half Empty interrupt * @arg SDIO_IT_RXFIFOHF: Receive FIFO Half Full interrupt * @arg SDIO_IT_TXFIFOF: Transmit FIFO full interrupt * @arg SDIO_IT_RXFIFOF: Receive FIFO full interrupt * @arg SDIO_IT_TXFIFOE: Transmit FIFO empty interrupt * @arg SDIO_IT_RXFIFOE: Receive FIFO empty interrupt * @arg SDIO_IT_TXDAVL: Data available in transmit FIFO interrupt * @arg SDIO_IT_RXDAVL: Data available in receive FIFO interrupt * @arg SDIO_IT_SDIOIT: SD I/O interrupt received interrupt * @arg SDIO_IT_CEATAEND: CE-ATA command completion signal received for CMD61 interrupt * @retval None */ #define __SDIO_DISABLE_IT(__INSTANCE__, __INTERRUPT__) ((__INSTANCE__)->MASK &= ~(__INTERRUPT__)) /** * @brief Checks whether the specified SDIO flag is set or not. * @param __INSTANCE__ : Pointer to SDIO register base * @param __FLAG__: specifies the flag to check. * This parameter can be one of the following values: * @arg SDIO_FLAG_CCRCFAIL: Command response received (CRC check failed) * @arg SDIO_FLAG_DCRCFAIL: Data block sent/received (CRC check failed) * @arg SDIO_FLAG_CTIMEOUT: Command response timeout * @arg SDIO_FLAG_DTIMEOUT: Data timeout * @arg SDIO_FLAG_TXUNDERR: Transmit FIFO underrun error * @arg SDIO_FLAG_RXOVERR: Received FIFO overrun error * @arg SDIO_FLAG_CMDREND: Command response received (CRC check passed) * @arg SDIO_FLAG_CMDSENT: Command sent (no response required) * @arg SDIO_FLAG_DATAEND: Data end (data counter, SDIDCOUNT, is zero) * @arg SDIO_FLAG_STBITERR: Start bit not detected on all data signals in wide bus mode. * @arg SDIO_FLAG_DBCKEND: Data block sent/received (CRC check passed) * @arg SDIO_FLAG_CMDACT: Command transfer in progress * @arg SDIO_FLAG_TXACT: Data transmit in progress * @arg SDIO_FLAG_RXACT: Data receive in progress * @arg SDIO_FLAG_TXFIFOHE: Transmit FIFO Half Empty * @arg SDIO_FLAG_RXFIFOHF: Receive FIFO Half Full * @arg SDIO_FLAG_TXFIFOF: Transmit FIFO full * @arg SDIO_FLAG_RXFIFOF: Receive FIFO full * @arg SDIO_FLAG_TXFIFOE: Transmit FIFO empty * @arg SDIO_FLAG_RXFIFOE: Receive FIFO empty * @arg SDIO_FLAG_TXDAVL: Data available in transmit FIFO * @arg SDIO_FLAG_RXDAVL: Data available in receive FIFO * @arg SDIO_FLAG_SDIOIT: SD I/O interrupt received * @arg SDIO_FLAG_CEATAEND: CE-ATA command completion signal received for CMD61 * @retval The new state of SDIO_FLAG (SET or RESET). */ #define __SDIO_GET_FLAG(__INSTANCE__, __FLAG__) (((__INSTANCE__)->STA &(__FLAG__)) != RESET) /** * @brief Clears the SDIO pending flags. * @param __INSTANCE__ : Pointer to SDIO register base * @param __FLAG__: specifies the flag to clear. * This parameter can be one or a combination of the following values: * @arg SDIO_FLAG_CCRCFAIL: Command response received (CRC check failed) * @arg SDIO_FLAG_DCRCFAIL: Data block sent/received (CRC check failed) * @arg SDIO_FLAG_CTIMEOUT: Command response timeout * @arg SDIO_FLAG_DTIMEOUT: Data timeout * @arg SDIO_FLAG_TXUNDERR: Transmit FIFO underrun error * @arg SDIO_FLAG_RXOVERR: Received FIFO overrun error * @arg SDIO_FLAG_CMDREND: Command response received (CRC check passed) * @arg SDIO_FLAG_CMDSENT: Command sent (no response required) * @arg SDIO_FLAG_DATAEND: Data end (data counter, SDIDCOUNT, is zero) * @arg SDIO_FLAG_STBITERR: Start bit not detected on all data signals in wide bus mode * @arg SDIO_FLAG_DBCKEND: Data block sent/received (CRC check passed) * @arg SDIO_FLAG_SDIOIT: SD I/O interrupt received * @arg SDIO_FLAG_CEATAEND: CE-ATA command completion signal received for CMD61 * @retval None */ #define __SDIO_CLEAR_FLAG(__INSTANCE__, __FLAG__) ((__INSTANCE__)->ICR = (__FLAG__)) /** * @brief Checks whether the specified SDIO interrupt has occurred or not. * @param __INSTANCE__ : Pointer to SDIO register base * @param __INTERRUPT__: specifies the SDIO interrupt source to check. * This parameter can be one of the following values: * @arg SDIO_IT_CCRCFAIL: Command response received (CRC check failed) interrupt * @arg SDIO_IT_DCRCFAIL: Data block sent/received (CRC check failed) interrupt * @arg SDIO_IT_CTIMEOUT: Command response timeout interrupt * @arg SDIO_IT_DTIMEOUT: Data timeout interrupt * @arg SDIO_IT_TXUNDERR: Transmit FIFO underrun error interrupt * @arg SDIO_IT_RXOVERR: Received FIFO overrun error interrupt * @arg SDIO_IT_CMDREND: Command response received (CRC check passed) interrupt * @arg SDIO_IT_CMDSENT: Command sent (no response required) interrupt * @arg SDIO_IT_DATAEND: Data end (data counter, SDIDCOUNT, is zero) interrupt * @arg SDIO_IT_STBITERR: Start bit not detected on all data signals in wide * bus mode interrupt * @arg SDIO_IT_DBCKEND: Data block sent/received (CRC check passed) interrupt * @arg SDIO_IT_CMDACT: Command transfer in progress interrupt * @arg SDIO_IT_TXACT: Data transmit in progress interrupt * @arg SDIO_IT_RXACT: Data receive in progress interrupt * @arg SDIO_IT_TXFIFOHE: Transmit FIFO Half Empty interrupt * @arg SDIO_IT_RXFIFOHF: Receive FIFO Half Full interrupt * @arg SDIO_IT_TXFIFOF: Transmit FIFO full interrupt * @arg SDIO_IT_RXFIFOF: Receive FIFO full interrupt * @arg SDIO_IT_TXFIFOE: Transmit FIFO empty interrupt * @arg SDIO_IT_RXFIFOE: Receive FIFO empty interrupt * @arg SDIO_IT_TXDAVL: Data available in transmit FIFO interrupt * @arg SDIO_IT_RXDAVL: Data available in receive FIFO interrupt * @arg SDIO_IT_SDIOIT: SD I/O interrupt received interrupt * @arg SDIO_IT_CEATAEND: CE-ATA command completion signal received for CMD61 interrupt * @retval The new state of SDIO_IT (SET or RESET). */ #define __SDIO_GET_IT (__INSTANCE__, __INTERRUPT__) (((__INSTANCE__)->STA &(__INTERRUPT__)) == (__INTERRUPT__)) /** * @brief Clears the SDIO's interrupt pending bits. * @param __INSTANCE__ : Pointer to SDIO register base * @param __INTERRUPT__: specifies the interrupt pending bit to clear. * This parameter can be one or a combination of the following values: * @arg SDIO_IT_CCRCFAIL: Command response received (CRC check failed) interrupt * @arg SDIO_IT_DCRCFAIL: Data block sent/received (CRC check failed) interrupt * @arg SDIO_IT_CTIMEOUT: Command response timeout interrupt * @arg SDIO_IT_DTIMEOUT: Data timeout interrupt * @arg SDIO_IT_TXUNDERR: Transmit FIFO underrun error interrupt * @arg SDIO_IT_RXOVERR: Received FIFO overrun error interrupt * @arg SDIO_IT_CMDREND: Command response received (CRC check passed) interrupt * @arg SDIO_IT_CMDSENT: Command sent (no response required) interrupt * @arg SDIO_IT_DATAEND: Data end (data counter, SDIO_DCOUNT, is zero) interrupt * @arg SDIO_IT_STBITERR: Start bit not detected on all data signals in wide * bus mode interrupt * @arg SDIO_IT_SDIOIT: SD I/O interrupt received interrupt * @arg SDIO_IT_CEATAEND: CE-ATA command completion signal received for CMD61 * @retval None */ #define __SDIO_CLEAR_IT(__INSTANCE__, __INTERRUPT__) ((__INSTANCE__)->ICR = (__INTERRUPT__)) /** * @brief Enable Start the SD I/O Read Wait operation. * @retval None */ #define __SDIO_START_READWAIT_ENABLE() (*(__IO uint32_t *) DCTRL_RWSTART_BB = ENABLE) /** * @brief Disable Start the SD I/O Read Wait operations. * @retval None */ #define __SDIO_START_READWAIT_DISABLE() (*(__IO uint32_t *) DCTRL_RWSTART_BB = DISABLE) /** * @brief Enable Start the SD I/O Read Wait operation. * @retval None */ #define __SDIO_STOP_READWAIT_ENABLE() (*(__IO uint32_t *) DCTRL_RWSTOP_BB = ENABLE) /** * @brief Disable Stop the SD I/O Read Wait operations. * @retval None */ #define __SDIO_STOP_READWAIT_DISABLE() (*(__IO uint32_t *) DCTRL_RWSTOP_BB = DISABLE) /** * @brief Enable the SD I/O Mode Operation. * @retval None */ #define __SDIO_OPERATION_ENABLE() (*(__IO uint32_t *) DCTRL_SDIOEN_BB = ENABLE) /** * @brief Disable the SD I/O Mode Operation. * @retval None */ #define __SDIO_OPERATION_DISABLE() (*(__IO uint32_t *) DCTRL_SDIOEN_BB = DISABLE) /** * @brief Enable the SD I/O Suspend command sending. * @retval None */ #define __SDIO_SUSPEND_CMD_ENABLE() (*(__IO uint32_t *) CMD_SDIOSUSPEND_BB = ENABLE) /** * @brief Disable the SD I/O Suspend command sending. * @retval None */ #define __SDIO_SUSPEND_CMD_DISABLE() (*(__IO uint32_t *) CMD_SDIOSUSPEND_BB = DISABLE) #if defined(STM32F405xx) || defined(STM32F415xx) || defined(STM32F407xx) || defined(STM32F417xx) ||\ defined(STM32F427xx) || defined(STM32F437xx) || defined(STM32F429xx) || defined(STM32F439xx) ||\ defined(STM32F401xC) || defined(STM32F401xE) || defined(STM32F411xE) /** * @brief Enable the command completion signal. * @retval None */ #define __SDIO_CEATA_CMD_COMPLETION_ENABLE() (*(__IO uint32_t *) CMD_ENCMDCOMPL_BB = ENABLE) /** * @brief Disable the command completion signal. * @retval None */ #define __SDIO_CEATA_CMD_COMPLETION_DISABLE() (*(__IO uint32_t *) CMD_ENCMDCOMPL_BB = DISABLE) /** * @brief Enable the CE-ATA interrupt. * @retval None */ #define __SDIO_CEATA_ENABLE_IT() (*(__IO uint32_t *) CMD_NIEN_BB = (uint32_t)0) /** * @brief Disable the CE-ATA interrupt. * @retval None */ #define __SDIO_CEATA_DISABLE_IT() (*(__IO uint32_t *) CMD_NIEN_BB = (uint32_t)1) /** * @brief Enable send CE-ATA command (CMD61). * @retval None */ #define __SDIO_CEATA_SENDCMD_ENABLE() (*(__IO uint32_t *) CMD_ATACMD_BB = ENABLE) /** * @brief Disable send CE-ATA command (CMD61). * @retval None */ #define __SDIO_CEATA_SENDCMD_DISABLE() (*(__IO uint32_t *) CMD_ATACMD_BB = DISABLE) #endif /* STM32F405xx || STM32F415xx || STM32F407xx || STM32F417xx || STM32F401xC || STM32F401xE || STM32F411xE ||\ STM32F427xx || STM32F437xx || STM32F429xx || STM32F439xx */ /** * @} */ /** * @} */ /* Exported functions --------------------------------------------------------*/ /** @addtogroup SDMMC_LL_Exported_Functions * @{ */ /* Initialization/de-initialization functions **********************************/ /** @addtogroup HAL_SDMMC_LL_Group1 * @{ */ HAL_StatusTypeDef SDIO_Init(SDIO_TypeDef *SDIOx, SDIO_InitTypeDef Init); /** * @} */ /* I/O operation functions *****************************************************/ /** @addtogroup HAL_SDMMC_LL_Group2 * @{ */ /* Blocking mode: Polling */ uint32_t SDIO_ReadFIFO(SDIO_TypeDef *SDIOx); HAL_StatusTypeDef SDIO_WriteFIFO(SDIO_TypeDef *SDIOx, uint32_t *pWriteData); /** * @} */ /* Peripheral Control functions ************************************************/ /** @addtogroup HAL_SDMMC_LL_Group3 * @{ */ HAL_StatusTypeDef SDIO_PowerState_ON(SDIO_TypeDef *SDIOx); HAL_StatusTypeDef SDIO_PowerState_OFF(SDIO_TypeDef *SDIOx); uint32_t SDIO_GetPowerState(SDIO_TypeDef *SDIOx); /* Command path state machine (CPSM) management functions */ HAL_StatusTypeDef SDIO_SendCommand(SDIO_TypeDef *SDIOx, SDIO_CmdInitTypeDef *SDIO_CmdInitStruct); uint8_t SDIO_GetCommandResponse(SDIO_TypeDef *SDIOx); uint32_t SDIO_GetResponse(uint32_t SDIO_RESP); /* Data path state machine (DPSM) management functions */ HAL_StatusTypeDef SDIO_DataConfig(SDIO_TypeDef *SDIOx, SDIO_DataInitTypeDef* SDIO_DataInitStruct); uint32_t SDIO_GetDataCounter(SDIO_TypeDef *SDIOx); uint32_t SDIO_GetFIFOCount(SDIO_TypeDef *SDIOx); /* SDIO IO Cards mode management functions */ HAL_StatusTypeDef SDIO_SetSDIOReadWaitMode(uint32_t SDIO_ReadWaitMode); /** * @} */ /** * @} */ /** * @} */ /** * @} */ #endif /* STM32F405xx || STM32F415xx || STM32F407xx || STM32F417xx || STM32F427xx || STM32F437xx || STM32F429xx || STM32F439xx || STM32F401xC || STM32F401xE || STM32F411xE || STM32F446xx || STM32F469xx || STM32F479xx */ #ifdef __cplusplus } #endif #endif /* __STM32F4xx_LL_SDMMC_H */ /************************ (C) COPYRIGHT STMicroelectronics *****END OF FILE****/ ================================================ FILE: Zelig/mbed/TARGET_NUCLEO_F411RE/stm32f4xx_ll_usb.h ================================================ /** ****************************************************************************** * @file stm32f4xx_ll_usb.h * @author MCD Application Team * @version V1.4.1 * @date 09-October-2015 * @brief Header file of USB Core HAL module. ****************************************************************************** * @attention * *

© COPYRIGHT(c) 2015 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. * ****************************************************************************** */ /* Define to prevent recursive inclusion -------------------------------------*/ #ifndef __STM32F4xx_LL_USB_H #define __STM32F4xx_LL_USB_H #ifdef __cplusplus extern "C" { #endif #if defined(STM32F405xx) || defined(STM32F415xx) || defined(STM32F407xx) || defined(STM32F417xx) || \ defined(STM32F427xx) || defined(STM32F437xx) || defined(STM32F429xx) || defined(STM32F439xx) || \ defined(STM32F401xC) || defined(STM32F401xE) || defined(STM32F411xE) || defined(STM32F446xx) || \ defined(STM32F469xx) || defined(STM32F479xx) /* Includes ------------------------------------------------------------------*/ #include "stm32f4xx_hal_def.h" /** @addtogroup STM32F4xx_HAL * @{ */ /** @addtogroup USB_Core * @{ */ /* Exported types ------------------------------------------------------------*/ /** * @brief USB Mode definition */ typedef enum { USB_OTG_DEVICE_MODE = 0, USB_OTG_HOST_MODE = 1, USB_OTG_DRD_MODE = 2 }USB_OTG_ModeTypeDef; /** * @brief URB States definition */ typedef enum { URB_IDLE = 0, URB_DONE, URB_NOTREADY, URB_NYET, URB_ERROR, URB_STALL }USB_OTG_URBStateTypeDef; /** * @brief Host channel States definition */ typedef enum { HC_IDLE = 0, HC_XFRC, HC_HALTED, HC_NAK, HC_NYET, HC_STALL, HC_XACTERR, HC_BBLERR, HC_DATATGLERR }USB_OTG_HCStateTypeDef; /** * @brief PCD Initialization Structure definition */ typedef struct { uint32_t dev_endpoints; /*!< Device Endpoints number. This parameter depends on the used USB core. This parameter must be a number between Min_Data = 1 and Max_Data = 15 */ uint32_t Host_channels; /*!< Host Channels number. This parameter Depends on the used USB core. This parameter must be a number between Min_Data = 1 and Max_Data = 15 */ uint32_t speed; /*!< USB Core speed. This parameter can be any value of @ref USB_Core_Speed_ */ uint32_t dma_enable; /*!< Enable or disable of the USB embedded DMA. */ uint32_t ep0_mps; /*!< Set the Endpoint 0 Max Packet size. This parameter can be any value of @ref USB_EP0_MPS_ */ uint32_t phy_itface; /*!< Select the used PHY interface. This parameter can be any value of @ref USB_Core_PHY_ */ uint32_t Sof_enable; /*!< Enable or disable the output of the SOF signal. */ uint32_t low_power_enable; /*!< Enable or disable the low power mode. */ uint32_t lpm_enable; /*!< Enable or disable Link Power Management. */ uint32_t battery_charging_enable; /*!< Enable or disable Battery charging. */ uint32_t vbus_sensing_enable; /*!< Enable or disable the VBUS Sensing feature. */ uint32_t use_dedicated_ep1; /*!< Enable or disable the use of the dedicated EP1 interrupt. */ uint32_t use_external_vbus; /*!< Enable or disable the use of the external VBUS. */ }USB_OTG_CfgTypeDef; typedef struct { uint8_t num; /*!< Endpoint number This parameter must be a number between Min_Data = 1 and Max_Data = 15 */ uint8_t is_in; /*!< Endpoint direction This parameter must be a number between Min_Data = 0 and Max_Data = 1 */ uint8_t is_stall; /*!< Endpoint stall condition This parameter must be a number between Min_Data = 0 and Max_Data = 1 */ uint8_t type; /*!< Endpoint type This parameter can be any value of @ref USB_EP_Type_ */ uint8_t data_pid_start; /*!< Initial data PID This parameter must be a number between Min_Data = 0 and Max_Data = 1 */ uint8_t even_odd_frame; /*!< IFrame parity This parameter must be a number between Min_Data = 0 and Max_Data = 1 */ uint16_t tx_fifo_num; /*!< Transmission FIFO number This parameter must be a number between Min_Data = 1 and Max_Data = 15 */ uint32_t maxpacket; /*!< Endpoint Max packet size This parameter must be a number between Min_Data = 0 and Max_Data = 64KB */ uint8_t *xfer_buff; /*!< Pointer to transfer buffer */ uint32_t dma_addr; /*!< 32 bits aligned transfer buffer address */ uint32_t xfer_len; /*!< Current transfer length */ uint32_t xfer_count; /*!< Partial transfer length in case of multi packet transfer */ }USB_OTG_EPTypeDef; typedef struct { uint8_t dev_addr ; /*!< USB device address. This parameter must be a number between Min_Data = 1 and Max_Data = 255 */ uint8_t ch_num; /*!< Host channel number. This parameter must be a number between Min_Data = 1 and Max_Data = 15 */ uint8_t ep_num; /*!< Endpoint number. This parameter must be a number between Min_Data = 1 and Max_Data = 15 */ uint8_t ep_is_in; /*!< Endpoint direction This parameter must be a number between Min_Data = 0 and Max_Data = 1 */ uint8_t speed; /*!< USB Host speed. This parameter can be any value of @ref USB_Core_Speed_ */ uint8_t do_ping; /*!< Enable or disable the use of the PING protocol for HS mode. */ uint8_t process_ping; /*!< Execute the PING protocol for HS mode. */ uint8_t ep_type; /*!< Endpoint Type. This parameter can be any value of @ref USB_EP_Type_ */ uint16_t max_packet; /*!< Endpoint Max packet size. This parameter must be a number between Min_Data = 0 and Max_Data = 64KB */ uint8_t data_pid; /*!< Initial data PID. This parameter must be a number between Min_Data = 0 and Max_Data = 1 */ uint8_t *xfer_buff; /*!< Pointer to transfer buffer. */ uint32_t xfer_len; /*!< Current transfer length. */ uint32_t xfer_count; /*!< Partial transfer length in case of multi packet transfer. */ uint8_t toggle_in; /*!< IN transfer current toggle flag. This parameter must be a number between Min_Data = 0 and Max_Data = 1 */ uint8_t toggle_out; /*!< OUT transfer current toggle flag This parameter must be a number between Min_Data = 0 and Max_Data = 1 */ uint32_t dma_addr; /*!< 32 bits aligned transfer buffer address. */ uint32_t ErrCnt; /*!< Host channel error count.*/ USB_OTG_URBStateTypeDef urb_state; /*!< URB state. This parameter can be any value of @ref USB_OTG_URBStateTypeDef */ USB_OTG_HCStateTypeDef state; /*!< Host Channel state. This parameter can be any value of @ref USB_OTG_HCStateTypeDef */ }USB_OTG_HCTypeDef; /* Exported constants --------------------------------------------------------*/ /** @defgroup PCD_Exported_Constants PCD Exported Constants * @{ */ /** @defgroup USB_Core_Mode_ USB Core Mode * @{ */ #define USB_OTG_MODE_DEVICE 0 #define USB_OTG_MODE_HOST 1 #define USB_OTG_MODE_DRD 2 /** * @} */ /** @defgroup USB_Core_Speed_ USB Core Speed * @{ */ #define USB_OTG_SPEED_HIGH 0 #define USB_OTG_SPEED_HIGH_IN_FULL 1 #define USB_OTG_SPEED_LOW 2 #define USB_OTG_SPEED_FULL 3 /** * @} */ /** @defgroup USB_Core_PHY_ USB Core PHY * @{ */ #define USB_OTG_ULPI_PHY 1 #define USB_OTG_EMBEDDED_PHY 2 /** * @} */ /** @defgroup USB_Core_MPS_ USB Core MPS * @{ */ #define USB_OTG_HS_MAX_PACKET_SIZE 512 #define USB_OTG_FS_MAX_PACKET_SIZE 64 #define USB_OTG_MAX_EP0_SIZE 64 /** * @} */ /** @defgroup USB_Core_Phy_Frequency_ USB Core Phy Frequency * @{ */ #define DSTS_ENUMSPD_HS_PHY_30MHZ_OR_60MHZ (0 << 1) #define DSTS_ENUMSPD_FS_PHY_30MHZ_OR_60MHZ (1 << 1) #define DSTS_ENUMSPD_LS_PHY_6MHZ (2 << 1) #define DSTS_ENUMSPD_FS_PHY_48MHZ (3 << 1) /** * @} */ /** @defgroup USB_CORE_Frame_Interval_ USB CORE Frame Interval * @{ */ #define DCFG_FRAME_INTERVAL_80 0 #define DCFG_FRAME_INTERVAL_85 1 #define DCFG_FRAME_INTERVAL_90 2 #define DCFG_FRAME_INTERVAL_95 3 /** * @} */ /** @defgroup USB_EP0_MPS_ USB EP0 MPS * @{ */ #define DEP0CTL_MPS_64 0 #define DEP0CTL_MPS_32 1 #define DEP0CTL_MPS_16 2 #define DEP0CTL_MPS_8 3 /** * @} */ /** @defgroup USB_EP_Speed_ USB EP Speed * @{ */ #define EP_SPEED_LOW 0 #define EP_SPEED_FULL 1 #define EP_SPEED_HIGH 2 /** * @} */ /** @defgroup USB_EP_Type_ USB EP Type * @{ */ #define EP_TYPE_CTRL 0 #define EP_TYPE_ISOC 1 #define EP_TYPE_BULK 2 #define EP_TYPE_INTR 3 #define EP_TYPE_MSK 3 /** * @} */ /** @defgroup USB_STS_Defines_ USB STS Defines * @{ */ #define STS_GOUT_NAK 1 #define STS_DATA_UPDT 2 #define STS_XFER_COMP 3 #define STS_SETUP_COMP 4 #define STS_SETUP_UPDT 6 /** * @} */ /** @defgroup HCFG_SPEED_Defines_ HCFG SPEED Defines * @{ */ #define HCFG_30_60_MHZ 0 #define HCFG_48_MHZ 1 #define HCFG_6_MHZ 2 /** * @} */ /** @defgroup HPRT0_PRTSPD_SPEED_Defines_ HPRT0 PRTSPD SPEED Defines * @{ */ #define HPRT0_PRTSPD_HIGH_SPEED 0 #define HPRT0_PRTSPD_FULL_SPEED 1 #define HPRT0_PRTSPD_LOW_SPEED 2 /** * @} */ #define HCCHAR_CTRL 0 #define HCCHAR_ISOC 1 #define HCCHAR_BULK 2 #define HCCHAR_INTR 3 #define HC_PID_DATA0 0 #define HC_PID_DATA2 1 #define HC_PID_DATA1 2 #define HC_PID_SETUP 3 #define GRXSTS_PKTSTS_IN 2 #define GRXSTS_PKTSTS_IN_XFER_COMP 3 #define GRXSTS_PKTSTS_DATA_TOGGLE_ERR 5 #define GRXSTS_PKTSTS_CH_HALTED 7 #define USBx_PCGCCTL *(__IO uint32_t *)((uint32_t)USBx + USB_OTG_PCGCCTL_BASE) #define USBx_HPRT0 *(__IO uint32_t *)((uint32_t)USBx + USB_OTG_HOST_PORT_BASE) #define USBx_DEVICE ((USB_OTG_DeviceTypeDef *)((uint32_t )USBx + USB_OTG_DEVICE_BASE)) #define USBx_INEP(i) ((USB_OTG_INEndpointTypeDef *)((uint32_t)USBx + USB_OTG_IN_ENDPOINT_BASE + (i)*USB_OTG_EP_REG_SIZE)) #define USBx_OUTEP(i) ((USB_OTG_OUTEndpointTypeDef *)((uint32_t)USBx + USB_OTG_OUT_ENDPOINT_BASE + (i)*USB_OTG_EP_REG_SIZE)) #define USBx_DFIFO(i) *(__IO uint32_t *)((uint32_t)USBx + USB_OTG_FIFO_BASE + (i) * USB_OTG_FIFO_SIZE) #define USBx_HOST ((USB_OTG_HostTypeDef *)((uint32_t )USBx + USB_OTG_HOST_BASE)) #define USBx_HC(i) ((USB_OTG_HostChannelTypeDef *)((uint32_t)USBx + USB_OTG_HOST_CHANNEL_BASE + (i)*USB_OTG_HOST_CHANNEL_SIZE)) /** * @} */ /* Exported macro ------------------------------------------------------------*/ #define USB_MASK_INTERRUPT(__INSTANCE__, __INTERRUPT__) ((__INSTANCE__)->GINTMSK &= ~(__INTERRUPT__)) #define USB_UNMASK_INTERRUPT(__INSTANCE__, __INTERRUPT__) ((__INSTANCE__)->GINTMSK |= (__INTERRUPT__)) #define CLEAR_IN_EP_INTR(__EPNUM__, __INTERRUPT__) (USBx_INEP(__EPNUM__)->DIEPINT = (__INTERRUPT__)) #define CLEAR_OUT_EP_INTR(__EPNUM__, __INTERRUPT__) (USBx_OUTEP(__EPNUM__)->DOEPINT = (__INTERRUPT__)) /* Exported functions --------------------------------------------------------*/ HAL_StatusTypeDef USB_CoreInit(USB_OTG_GlobalTypeDef *USBx, USB_OTG_CfgTypeDef Init); HAL_StatusTypeDef USB_DevInit(USB_OTG_GlobalTypeDef *USBx, USB_OTG_CfgTypeDef Init); HAL_StatusTypeDef USB_EnableGlobalInt(USB_OTG_GlobalTypeDef *USBx); HAL_StatusTypeDef USB_DisableGlobalInt(USB_OTG_GlobalTypeDef *USBx); HAL_StatusTypeDef USB_SetCurrentMode(USB_OTG_GlobalTypeDef *USBx , USB_OTG_ModeTypeDef mode); HAL_StatusTypeDef USB_SetDevSpeed(USB_OTG_GlobalTypeDef *USBx , uint8_t speed); HAL_StatusTypeDef USB_FlushRxFifo (USB_OTG_GlobalTypeDef *USBx); HAL_StatusTypeDef USB_FlushTxFifo (USB_OTG_GlobalTypeDef *USBx, uint32_t num ); HAL_StatusTypeDef USB_ActivateEndpoint(USB_OTG_GlobalTypeDef *USBx, USB_OTG_EPTypeDef *ep); HAL_StatusTypeDef USB_DeactivateEndpoint(USB_OTG_GlobalTypeDef *USBx, USB_OTG_EPTypeDef *ep); HAL_StatusTypeDef USB_ActivateDedicatedEndpoint(USB_OTG_GlobalTypeDef *USBx, USB_OTG_EPTypeDef *ep); HAL_StatusTypeDef USB_DeactivateDedicatedEndpoint(USB_OTG_GlobalTypeDef *USBx, USB_OTG_EPTypeDef *ep); HAL_StatusTypeDef USB_EPStartXfer(USB_OTG_GlobalTypeDef *USBx , USB_OTG_EPTypeDef *ep, uint8_t dma); HAL_StatusTypeDef USB_EP0StartXfer(USB_OTG_GlobalTypeDef *USBx , USB_OTG_EPTypeDef *ep, uint8_t dma); HAL_StatusTypeDef USB_WritePacket(USB_OTG_GlobalTypeDef *USBx, uint8_t *src, uint8_t ch_ep_num, uint16_t len, uint8_t dma); void * USB_ReadPacket(USB_OTG_GlobalTypeDef *USBx, uint8_t *dest, uint16_t len); HAL_StatusTypeDef USB_EPSetStall(USB_OTG_GlobalTypeDef *USBx , USB_OTG_EPTypeDef *ep); HAL_StatusTypeDef USB_EPClearStall(USB_OTG_GlobalTypeDef *USBx , USB_OTG_EPTypeDef *ep); HAL_StatusTypeDef USB_SetDevAddress (USB_OTG_GlobalTypeDef *USBx, uint8_t address); HAL_StatusTypeDef USB_DevConnect (USB_OTG_GlobalTypeDef *USBx); HAL_StatusTypeDef USB_DevDisconnect (USB_OTG_GlobalTypeDef *USBx); HAL_StatusTypeDef USB_StopDevice(USB_OTG_GlobalTypeDef *USBx); HAL_StatusTypeDef USB_ActivateSetup (USB_OTG_GlobalTypeDef *USBx); HAL_StatusTypeDef USB_EP0_OutStart(USB_OTG_GlobalTypeDef *USBx, uint8_t dma, uint8_t *psetup); uint8_t USB_GetDevSpeed(USB_OTG_GlobalTypeDef *USBx); uint32_t USB_GetMode(USB_OTG_GlobalTypeDef *USBx); uint32_t USB_ReadInterrupts (USB_OTG_GlobalTypeDef *USBx); uint32_t USB_ReadDevAllOutEpInterrupt (USB_OTG_GlobalTypeDef *USBx); uint32_t USB_ReadDevOutEPInterrupt (USB_OTG_GlobalTypeDef *USBx , uint8_t epnum); uint32_t USB_ReadDevAllInEpInterrupt (USB_OTG_GlobalTypeDef *USBx); uint32_t USB_ReadDevInEPInterrupt (USB_OTG_GlobalTypeDef *USBx , uint8_t epnum); void USB_ClearInterrupts (USB_OTG_GlobalTypeDef *USBx, uint32_t interrupt); HAL_StatusTypeDef USB_HostInit (USB_OTG_GlobalTypeDef *USBx, USB_OTG_CfgTypeDef cfg); HAL_StatusTypeDef USB_InitFSLSPClkSel(USB_OTG_GlobalTypeDef *USBx , uint8_t freq); HAL_StatusTypeDef USB_ResetPort(USB_OTG_GlobalTypeDef *USBx); HAL_StatusTypeDef USB_DriveVbus (USB_OTG_GlobalTypeDef *USBx, uint8_t state); uint32_t USB_GetHostSpeed (USB_OTG_GlobalTypeDef *USBx); uint32_t USB_GetCurrentFrame (USB_OTG_GlobalTypeDef *USBx); HAL_StatusTypeDef USB_HC_Init(USB_OTG_GlobalTypeDef *USBx, uint8_t ch_num, uint8_t epnum, uint8_t dev_address, uint8_t speed, uint8_t ep_type, uint16_t mps); HAL_StatusTypeDef USB_HC_StartXfer(USB_OTG_GlobalTypeDef *USBx, USB_OTG_HCTypeDef *hc, uint8_t dma); uint32_t USB_HC_ReadInterrupt (USB_OTG_GlobalTypeDef *USBx); HAL_StatusTypeDef USB_HC_Halt(USB_OTG_GlobalTypeDef *USBx , uint8_t hc_num); HAL_StatusTypeDef USB_DoPing(USB_OTG_GlobalTypeDef *USBx , uint8_t ch_num); HAL_StatusTypeDef USB_StopHost(USB_OTG_GlobalTypeDef *USBx); /** * @} */ /** * @} */ #endif /* STM32F405xx || STM32F415xx || STM32F407xx || STM32F417xx || STM32F427xx || STM32F437xx || STM32F429xx || STM32F439xx || STM32F401xC || STM32F401xE || STM32F411xE || STM32F446xx || STM32F469xx || STM32F479xx */ #ifdef __cplusplus } #endif #endif /* __STM32F4xx_LL_USB_H */ /************************ (C) COPYRIGHT STMicroelectronics *****END OF FILE****/ ================================================ FILE: Zelig/mbed/TARGET_NUCLEO_F411RE/system_stm32f4xx.h ================================================ /** ****************************************************************************** * @file system_stm32f4xx.h * @author MCD Application Team * @version V2.3.2 * @date 26-June-2015 * @brief CMSIS Cortex-M4 Device System Source File for STM32F4xx devices. ****************************************************************************** * @attention * *

© COPYRIGHT(c) 2015 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. * ****************************************************************************** */ /** @addtogroup CMSIS * @{ */ /** @addtogroup stm32f4xx_system * @{ */ /** * @brief Define to prevent recursive inclusion */ #ifndef __SYSTEM_STM32F4XX_H #define __SYSTEM_STM32F4XX_H #ifdef __cplusplus extern "C" { #endif /** @addtogroup STM32F4xx_System_Includes * @{ */ /** * @} */ /** @addtogroup STM32F4xx_System_Exported_types * @{ */ /* This variable is updated in three ways: 1) by calling CMSIS function SystemCoreClockUpdate() 2) by calling HAL API function HAL_RCC_GetSysClockFreq() 3) each time HAL_RCC_ClockConfig() is called to configure the system clock frequency Note: If you use this function to configure the system clock; then there is no need to call the 2 first functions listed above, since SystemCoreClock variable is updated automatically. */ extern uint32_t SystemCoreClock; /*!< System Clock Frequency (Core Clock) */ /** * @} */ /** @addtogroup STM32F4xx_System_Exported_Constants * @{ */ /** * @} */ /** @addtogroup STM32F4xx_System_Exported_Macros * @{ */ /** * @} */ /** @addtogroup STM32F4xx_System_Exported_Functions * @{ */ extern void SystemInit(void); extern void SystemCoreClockUpdate(void); extern void SetSysClock(void); /** * @} */ #ifdef __cplusplus } #endif #endif /*__SYSTEM_STM32F4XX_H */ /** * @} */ /** * @} */ /************************ (C) COPYRIGHT STMicroelectronics *****END OF FILE****/ ================================================ FILE: Zelig/mbed/TARGET_NUCLEO_L152RE/TARGET_STM/TARGET_STM32L1/PeripheralPins.h ================================================ /* mbed Microcontroller Library ******************************************************************************* * Copyright (c) 2014, STMicroelectronics * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * 1. Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * 3. Neither the name of 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. ******************************************************************************* */ #ifndef MBED_PERIPHERALPINS_H #define MBED_PERIPHERALPINS_H #include "pinmap.h" #include "PeripheralNames.h" //*** ADC *** extern const PinMap PinMap_ADC[]; //*** DAC *** extern const PinMap PinMap_DAC[]; //*** I2C *** extern const PinMap PinMap_I2C_SDA[]; extern const PinMap PinMap_I2C_SCL[]; //*** PWM *** extern const PinMap PinMap_PWM[]; //*** SERIAL *** extern const PinMap PinMap_UART_TX[]; extern const PinMap PinMap_UART_RX[]; //*** SPI *** extern const PinMap PinMap_SPI_MOSI[]; extern const PinMap PinMap_SPI_MISO[]; extern const PinMap PinMap_SPI_SCLK[]; extern const PinMap PinMap_SPI_SSEL[]; #endif ================================================ FILE: Zelig/mbed/TARGET_NUCLEO_L152RE/TARGET_STM/TARGET_STM32L1/TARGET_NUCLEO_L152RE/PeripheralNames.h ================================================ /* mbed Microcontroller Library ******************************************************************************* * Copyright (c) 2014, STMicroelectronics * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * 1. Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * 3. Neither the name of 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. ******************************************************************************* */ #ifndef MBED_PERIPHERALNAMES_H #define MBED_PERIPHERALNAMES_H #include "cmsis.h" #ifdef __cplusplus extern "C" { #endif typedef enum { ADC_1 = (int)ADC1_BASE } ADCName; typedef enum { DAC_1 = (int)DAC_BASE } DACName; typedef enum { UART_1 = (int)USART1_BASE, UART_2 = (int)USART2_BASE, UART_3 = (int)USART3_BASE, UART_4 = (int)UART4_BASE, UART_5 = (int)UART5_BASE } UARTName; #define STDIO_UART_TX PA_2 #define STDIO_UART_RX PA_3 #define STDIO_UART UART_2 typedef enum { SPI_1 = (int)SPI1_BASE, SPI_2 = (int)SPI2_BASE, SPI_3 = (int)SPI3_BASE } SPIName; typedef enum { I2C_1 = (int)I2C1_BASE, I2C_2 = (int)I2C2_BASE } I2CName; typedef enum { PWM_2 = (int)TIM2_BASE, PWM_3 = (int)TIM3_BASE, PWM_4 = (int)TIM4_BASE, PWM_5 = (int)TIM5_BASE, PWM_9 = (int)TIM9_BASE, PWM_10 = (int)TIM10_BASE, PWM_11 = (int)TIM11_BASE } PWMName; #ifdef __cplusplus } #endif #endif ================================================ FILE: Zelig/mbed/TARGET_NUCLEO_L152RE/TARGET_STM/TARGET_STM32L1/TARGET_NUCLEO_L152RE/PinNames.h ================================================ /* mbed Microcontroller Library ******************************************************************************* * Copyright (c) 2014, STMicroelectronics * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * 1. Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * 3. Neither the name of 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. ******************************************************************************* */ #ifndef MBED_PINNAMES_H #define MBED_PINNAMES_H #include "cmsis.h" #ifdef __cplusplus extern "C" { #endif // See stm32l0xx_hal_gpio.h and stm32l0xx_hal_gpio_ex.h for values of MODE, PUPD and AFNUM #define STM_PIN_DATA(MODE, PUPD, AFNUM) ((int)(((AFNUM) << 7) | ((PUPD) << 4) | ((MODE) << 0))) #define STM_PIN_MODE(X) (((X) >> 0) & 0x0F) #define STM_PIN_PUPD(X) (((X) >> 4) & 0x07) #define STM_PIN_AFNUM(X) (((X) >> 7) & 0x0F) #define STM_MODE_INPUT (0) #define STM_MODE_OUTPUT_PP (1) #define STM_MODE_OUTPUT_OD (2) #define STM_MODE_AF_PP (3) #define STM_MODE_AF_OD (4) #define STM_MODE_ANALOG (5) #define STM_MODE_IT_RISING (6) #define STM_MODE_IT_FALLING (7) #define STM_MODE_IT_RISING_FALLING (8) #define STM_MODE_EVT_RISING (9) #define STM_MODE_EVT_FALLING (10) #define STM_MODE_EVT_RISING_FALLING (11) #define STM_MODE_IT_EVT_RESET (12) // High nibble = port number (0=A, 1=B, 2=C, 3=D, 4=E, 5=F, 6=G, 7=H) // Low nibble = pin number #define STM_PORT(X) (((uint32_t)(X) >> 4) & 0xF) #define STM_PIN(X) ((uint32_t)(X) & 0xF) typedef enum { PIN_INPUT, PIN_OUTPUT } PinDirection; typedef enum { PA_0 = 0x00, PA_1 = 0x01, PA_2 = 0x02, PA_3 = 0x03, PA_4 = 0x04, PA_5 = 0x05, PA_6 = 0x06, PA_7 = 0x07, PA_8 = 0x08, PA_9 = 0x09, PA_10 = 0x0A, PA_11 = 0x0B, PA_12 = 0x0C, PA_13 = 0x0D, PA_14 = 0x0E, PA_15 = 0x0F, PB_0 = 0x10, PB_1 = 0x11, PB_2 = 0x12, PB_3 = 0x13, PB_4 = 0x14, PB_5 = 0x15, PB_6 = 0x16, PB_7 = 0x17, PB_8 = 0x18, PB_9 = 0x19, PB_10 = 0x1A, PB_11 = 0x1B, PB_12 = 0x1C, PB_13 = 0x1D, PB_14 = 0x1E, PB_15 = 0x1F, PC_0 = 0x20, PC_1 = 0x21, PC_2 = 0x22, PC_3 = 0x23, PC_4 = 0x24, PC_5 = 0x25, PC_6 = 0x26, PC_7 = 0x27, PC_8 = 0x28, PC_9 = 0x29, PC_10 = 0x2A, PC_11 = 0x2B, PC_12 = 0x2C, PC_13 = 0x2D, PC_14 = 0x2E, PC_15 = 0x2F, PD_2 = 0x32, PH_0 = 0x70, PH_1 = 0x71, // Arduino connector namings A0 = PA_0, A1 = PA_1, A2 = PA_4, A3 = PB_0, A4 = PC_1, A5 = PC_0, D0 = PA_3, D1 = PA_2, D2 = PA_10, D3 = PB_3, D4 = PB_5, D5 = PB_4, D6 = PB_10, D7 = PA_8, D8 = PA_9, D9 = PC_7, D10 = PB_6, D11 = PA_7, D12 = PA_6, D13 = PA_5, D14 = PB_9, D15 = PB_8, // Generic signals namings LED1 = PA_5, LED2 = PA_5, LED3 = PA_5, LED4 = PA_5, USER_BUTTON = PC_13, SERIAL_TX = PA_2, SERIAL_RX = PA_3, USBTX = PA_2, USBRX = PA_3, I2C_SCL = PB_8, I2C_SDA = PB_9, SPI_MOSI = PA_7, SPI_MISO = PA_6, SPI_SCK = PA_5, SPI_CS = PB_6, PWM_OUT = PB_3, // Not connected NC = (int)0xFFFFFFFF } PinName; typedef enum { PullNone = 0, PullUp = 1, PullDown = 2, OpenDrain = 3, PullDefault = PullNone } PinMode; #ifdef __cplusplus } #endif #endif ================================================ FILE: Zelig/mbed/TARGET_NUCLEO_L152RE/TARGET_STM/TARGET_STM32L1/TARGET_NUCLEO_L152RE/PortNames.h ================================================ /* mbed Microcontroller Library ******************************************************************************* * Copyright (c) 2014, STMicroelectronics * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * 1. Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * 3. Neither the name of 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. ******************************************************************************* */ #ifndef MBED_PORTNAMES_H #define MBED_PORTNAMES_H #ifdef __cplusplus extern "C" { #endif typedef enum { PortA = 0, PortB = 1, PortC = 2, PortD = 3, PortH = 7 } PortName; #ifdef __cplusplus } #endif #endif ================================================ FILE: Zelig/mbed/TARGET_NUCLEO_L152RE/TARGET_STM/TARGET_STM32L1/TARGET_NUCLEO_L152RE/device.h ================================================ /* mbed Microcontroller Library ******************************************************************************* * Copyright (c) 2014, STMicroelectronics * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * 1. Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * 3. Neither the name of 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. ******************************************************************************* */ #ifndef MBED_DEVICE_H #define MBED_DEVICE_H #define DEVICE_PORTIN 1 #define DEVICE_PORTOUT 1 #define DEVICE_PORTINOUT 1 #define DEVICE_INTERRUPTIN 1 #define DEVICE_ANALOGIN 1 #define DEVICE_ANALOGOUT 1 #define DEVICE_SERIAL 1 #define DEVICE_I2C 1 #define DEVICE_I2CSLAVE 1 #define DEVICE_SPI 1 #define DEVICE_SPISLAVE 1 #define DEVICE_RTC 1 #define DEVICE_PWMOUT 1 #define DEVICE_SLEEP 1 //======================================= #define DEVICE_SEMIHOST 0 #define DEVICE_LOCALFILESYSTEM 0 #define DEVICE_ID_LENGTH 24 #define DEVICE_DEBUG_AWARENESS 0 #define DEVICE_STDIO_MESSAGES 1 #define DEVICE_ERROR_RED 0 #include "objects.h" #endif ================================================ FILE: Zelig/mbed/TARGET_NUCLEO_L152RE/TARGET_STM/TARGET_STM32L1/TARGET_NUCLEO_L152RE/objects.h ================================================ /* mbed Microcontroller Library ******************************************************************************* * Copyright (c) 2014, STMicroelectronics * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * 1. Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * 3. Neither the name of 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. ******************************************************************************* */ #ifndef MBED_OBJECTS_H #define MBED_OBJECTS_H #include "cmsis.h" #include "PortNames.h" #include "PeripheralNames.h" #include "PinNames.h" #ifdef __cplusplus extern "C" { #endif struct gpio_irq_s { IRQn_Type irq_n; uint32_t irq_index; uint32_t event; PinName pin; }; struct port_s { PortName port; uint32_t mask; PinDirection direction; __IO uint32_t *reg_in; __IO uint32_t *reg_out; }; struct analogin_s { ADCName adc; PinName pin; }; struct dac_s { DACName dac; PinName pin; }; struct serial_s { UARTName uart; int index; // Used by irq uint32_t baudrate; uint32_t databits; uint32_t stopbits; uint32_t parity; PinName pin_tx; PinName pin_rx; }; struct spi_s { SPIName spi; uint32_t bits; uint32_t cpol; uint32_t cpha; uint32_t mode; uint32_t nss; uint32_t br_presc; PinName pin_miso; PinName pin_mosi; PinName pin_sclk; PinName pin_ssel; }; struct i2c_s { I2CName i2c; uint32_t slave; }; struct pwmout_s { PWMName pwm; PinName pin; uint32_t period; uint32_t pulse; }; #include "gpio_object.h" #ifdef __cplusplus } #endif #endif ================================================ FILE: Zelig/mbed/TARGET_NUCLEO_L152RE/TARGET_STM/TARGET_STM32L1/gpio_object.h ================================================ /* mbed Microcontroller Library ******************************************************************************* * Copyright (c) 2014, STMicroelectronics * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * 1. Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * 3. Neither the name of 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. ******************************************************************************* */ #ifndef MBED_GPIO_OBJECT_H #define MBED_GPIO_OBJECT_H #include "mbed_assert.h" #include "cmsis.h" #include "PortNames.h" #include "PeripheralNames.h" #include "PinNames.h" #ifdef __cplusplus extern "C" { #endif typedef struct { PinName pin; uint32_t mask; __IO uint32_t *reg_in; __IO uint32_t *reg_set; __IO uint32_t *reg_clr; } gpio_t; static inline void gpio_write(gpio_t *obj, int value) { MBED_ASSERT(obj->pin != (PinName)NC); if (value) { *obj->reg_set = obj->mask; } else { #if defined(TARGET_STM32L152RC) || defined(TARGET_STM32L151RC) *obj->reg_set = obj->mask << 16; #else *obj->reg_clr = obj->mask; #endif } } static inline int gpio_read(gpio_t *obj) { MBED_ASSERT(obj->pin != (PinName)NC); return ((*obj->reg_in & obj->mask) ? 1 : 0); } static inline int gpio_is_connected(const gpio_t *obj) { return obj->pin != (PinName)NC; } #ifdef __cplusplus } #endif #endif ================================================ FILE: Zelig/mbed/TARGET_NUCLEO_L152RE/TOOLCHAIN_GCC_ARM/STM32L152XE.ld ================================================ /* Linker script to configure memory regions. */ MEMORY { /* 512KB FLASH, 80KB RAM, Reserve up till 0x13C. There are 0x73 vectors = 292 * bytes (0x124) in RAM. But all GCC scripts seem to require BootRAM @0x138 */ FLASH (rx) : ORIGIN = 0x08000000, LENGTH = 512k RAM (rwx) : ORIGIN = 0x2000013C, LENGTH = 0x14000-0x13C } /* Linker script to place sections and symbol values. Should be used together * with other linker script that defines memory regions FLASH and RAM. * It references following symbols, which must be defined in code: * Reset_Handler : Entry of reset handler * * It defines following symbols, which code can use without definition: * __exidx_start * __exidx_end * __etext * __data_start__ * __preinit_array_start * __preinit_array_end * __init_array_start * __init_array_end * __fini_array_start * __fini_array_end * __data_end__ * __bss_start__ * __bss_end__ * __end__ * end * __HeapLimit * __StackLimit * __StackTop * __stack * _estack */ ENTRY(Reset_Handler) SECTIONS { .text : { KEEP(*(.isr_vector)) *(.text*) KEEP(*(.init)) KEEP(*(.fini)) /* .ctors */ *crtbegin.o(.ctors) *crtbegin?.o(.ctors) *(EXCLUDE_FILE(*crtend?.o *crtend.o) .ctors) *(SORT(.ctors.*)) *(.ctors) /* .dtors */ *crtbegin.o(.dtors) *crtbegin?.o(.dtors) *(EXCLUDE_FILE(*crtend?.o *crtend.o) .dtors) *(SORT(.dtors.*)) *(.dtors) *(.rodata*) KEEP(*(.eh_frame*)) } > FLASH .ARM.extab : { *(.ARM.extab* .gnu.linkonce.armextab.*) } > FLASH __exidx_start = .; .ARM.exidx : { *(.ARM.exidx* .gnu.linkonce.armexidx.*) } > FLASH __exidx_end = .; __etext = .; _sidata = .; .data : AT (__etext) { __data_start__ = .; _sdata = .; *(vtable) *(.data*) . = ALIGN(4); /* preinit data */ PROVIDE_HIDDEN (__preinit_array_start = .); KEEP(*(.preinit_array)) PROVIDE_HIDDEN (__preinit_array_end = .); . = ALIGN(4); /* init data */ PROVIDE_HIDDEN (__init_array_start = .); KEEP(*(SORT(.init_array.*))) KEEP(*(.init_array)) PROVIDE_HIDDEN (__init_array_end = .); . = ALIGN(4); /* finit data */ PROVIDE_HIDDEN (__fini_array_start = .); KEEP(*(SORT(.fini_array.*))) KEEP(*(.fini_array)) PROVIDE_HIDDEN (__fini_array_end = .); KEEP(*(.jcr*)) . = ALIGN(4); /* All data end */ __data_end__ = .; _edata = .; } > RAM .bss : { . = ALIGN(4); __bss_start__ = .; _sbss = .; *(.bss*) *(COMMON) . = ALIGN(4); __bss_end__ = .; _ebss = .; } > RAM .heap (COPY): { __end__ = .; end = __end__; *(.heap*) __HeapLimit = .; } > RAM /* .stack_dummy section doesn't contains any symbols. It is only * used for linker to calculate size of stack sections, and assign * values to stack symbols later */ .stack_dummy (COPY): { *(.stack*) } > RAM /* * The section '.managed_exception_thread' is a LLILUM Specific addition to pad * the stack space at the bottom with enough space to build a managed array. * Assuming that the stack bottom (_StackLimit) is 8 bytes aligned, we add * 16 bytes that will contain the array ObjectHeader and the length member (see * ArrayImpl.cs). This way we do preserve stack alignment. */ .stack_dummy_managed_exception_thread : { *(.managed_exception_thread) } > RAM /* Set stack top to end of RAM, and stack limit move down by * size of stack_dummy section */ __StackTop = ORIGIN(RAM) + LENGTH(RAM); _estack = __StackTop; __StackLimit = __StackTop - SIZEOF(.stack_dummy) + SIZEOF(.stack_dummy_managed_exception_thread); PROVIDE(__stack = __StackTop); /* Check if data + heap + stack exceeds RAM limit */ ASSERT(__StackLimit >= __HeapLimit, "region RAM overflowed with stack") } ================================================ FILE: Zelig/mbed/TARGET_NUCLEO_L152RE/cmsis.h ================================================ /* mbed Microcontroller Library * A generic CMSIS include header ******************************************************************************* * Copyright (c) 2014, STMicroelectronics * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * 1. Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * 3. Neither the name of 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. ******************************************************************************* */ #ifndef MBED_CMSIS_H #define MBED_CMSIS_H #include "stm32l1xx.h" #include "cmsis_nvic.h" #endif ================================================ FILE: Zelig/mbed/TARGET_NUCLEO_L152RE/cmsis_nvic.h ================================================ /* mbed Microcontroller Library * CMSIS-style functionality to support dynamic vectors ******************************************************************************* * Copyright (c) 2014, STMicroelectronics * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * 1. Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * 3. Neither the name of 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. ******************************************************************************* */ #ifndef MBED_CMSIS_NVIC_H #define MBED_CMSIS_NVIC_H // STM32L152RE // CORE: 16 vectors = 64 bytes from 0x00 to 0x3F // MCU Peripherals: 57 vectors = 228 bytes from 0x40 to 0x123 // Total: 73 vectors = 292 bytes (0x124) to be reserved in RAM #define NVIC_NUM_VECTORS 73 #define NVIC_USER_IRQ_OFFSET 16 #include "cmsis.h" #ifdef __cplusplus extern "C" { #endif void NVIC_SetVector(IRQn_Type IRQn, uint32_t vector); uint32_t NVIC_GetVector(IRQn_Type IRQn); #ifdef __cplusplus } #endif #endif ================================================ FILE: Zelig/mbed/TARGET_NUCLEO_L152RE/core_ca9.h ================================================ /**************************************************************************//** * @file core_ca9.h * @brief CMSIS Cortex-A9 Core Peripheral Access Layer Header File * @version * @date 25 March 2013 * * @note * ******************************************************************************/ /* Copyright (c) 2009 - 2012 ARM LIMITED All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: - Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. - Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. - Neither the name of ARM 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 COPYRIGHT HOLDERS AND 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. ---------------------------------------------------------------------------*/ #if defined ( __ICCARM__ ) #pragma system_include /* treat file as system include file for MISRA check */ #endif #ifdef __cplusplus extern "C" { #endif #ifndef __CORE_CA9_H_GENERIC #define __CORE_CA9_H_GENERIC /** \page CMSIS_MISRA_Exceptions MISRA-C:2004 Compliance Exceptions CMSIS violates the following MISRA-C:2004 rules: \li Required Rule 8.5, object/function definition in header file.
Function definitions in header files are used to allow 'inlining'. \li Required Rule 18.4, declaration of union type or object of union type: '{...}'.
Unions are used for effective representation of core registers. \li Advisory Rule 19.7, Function-like macro defined.
Function-like macros are used to allow more efficient code. */ /******************************************************************************* * CMSIS definitions ******************************************************************************/ /** \ingroup Cortex_A9 @{ */ /* CMSIS CA9 definitions */ #define __CA9_CMSIS_VERSION_MAIN (0x03) /*!< [31:16] CMSIS HAL main version */ #define __CA9_CMSIS_VERSION_SUB (0x10) /*!< [15:0] CMSIS HAL sub version */ #define __CA9_CMSIS_VERSION ((__CA9_CMSIS_VERSION_MAIN << 16) | \ __CA9_CMSIS_VERSION_SUB ) /*!< CMSIS HAL version number */ #define __CORTEX_A (0x09) /*!< Cortex-A Core */ #if defined ( __CC_ARM ) #define __ASM __asm /*!< asm keyword for ARM Compiler */ #define __INLINE __inline /*!< inline keyword for ARM Compiler */ #define __STATIC_INLINE static __inline #define __STATIC_ASM static __asm #elif defined ( __ICCARM__ ) #define __ASM __asm /*!< asm keyword for IAR Compiler */ #define __INLINE inline /*!< inline keyword for IAR Compiler. Only available in High optimization mode! */ #define __STATIC_INLINE static inline #define __STATIC_ASM static __asm #elif defined ( __TMS470__ ) #define __ASM __asm /*!< asm keyword for TI CCS Compiler */ #define __STATIC_INLINE static inline #define __STATIC_ASM static __asm #elif defined ( __GNUC__ ) #define __ASM __asm /*!< asm keyword for GNU Compiler */ #define __INLINE inline /*!< inline keyword for GNU Compiler */ #define __STATIC_INLINE static inline #define __STATIC_ASM static __asm #elif defined ( __TASKING__ ) #define __ASM __asm /*!< asm keyword for TASKING Compiler */ #define __INLINE inline /*!< inline keyword for TASKING Compiler */ #define __STATIC_INLINE static inline #define __STATIC_ASM static __asm #endif /** __FPU_USED indicates whether an FPU is used or not. For this, __FPU_PRESENT has to be checked prior to making use of FPU specific registers and functions. */ #if defined ( __CC_ARM ) #if defined __TARGET_FPU_VFP #if (__FPU_PRESENT == 1) #define __FPU_USED 1 #else #warning "Compiler generates FPU instructions for a device without an FPU (check __FPU_PRESENT)" #define __FPU_USED 0 #endif #else #define __FPU_USED 0 #endif #elif defined ( __ICCARM__ ) #if defined __ARMVFP__ #if (__FPU_PRESENT == 1) #define __FPU_USED 1 #else #warning "Compiler generates FPU instructions for a device without an FPU (check __FPU_PRESENT)" #define __FPU_USED 0 #endif #else #define __FPU_USED 0 #endif #elif defined ( __TMS470__ ) #if defined __TI_VFP_SUPPORT__ #if (__FPU_PRESENT == 1) #define __FPU_USED 1 #else #warning "Compiler generates FPU instructions for a device without an FPU (check __FPU_PRESENT)" #define __FPU_USED 0 #endif #else #define __FPU_USED 0 #endif #elif defined ( __GNUC__ ) #if defined (__VFP_FP__) && !defined(__SOFTFP__) #if (__FPU_PRESENT == 1) #define __FPU_USED 1 #else #warning "Compiler generates FPU instructions for a device without an FPU (check __FPU_PRESENT)" #define __FPU_USED 0 #endif #else #define __FPU_USED 0 #endif #elif defined ( __TASKING__ ) #if defined __FPU_VFP__ #if (__FPU_PRESENT == 1) #define __FPU_USED 1 #else #error "Compiler generates FPU instructions for a device without an FPU (check __FPU_PRESENT)" #define __FPU_USED 0 #endif #else #define __FPU_USED 0 #endif #endif #include /*!< standard types definitions */ #include "core_caInstr.h" /*!< Core Instruction Access */ #include "core_caFunc.h" /*!< Core Function Access */ #include "core_cm4_simd.h" /*!< Compiler specific SIMD Intrinsics */ #endif /* __CORE_CA9_H_GENERIC */ #ifndef __CMSIS_GENERIC #ifndef __CORE_CA9_H_DEPENDANT #define __CORE_CA9_H_DEPENDANT /* check device defines and use defaults */ #if defined __CHECK_DEVICE_DEFINES #ifndef __CA9_REV #define __CA9_REV 0x0000 #warning "__CA9_REV not defined in device header file; using default!" #endif #ifndef __FPU_PRESENT #define __FPU_PRESENT 1 #warning "__FPU_PRESENT not defined in device header file; using default!" #endif #ifndef __Vendor_SysTickConfig #define __Vendor_SysTickConfig 1 #endif #if __Vendor_SysTickConfig == 0 #error "__Vendor_SysTickConfig set to 0, but vendor systick timer must be supplied for Cortex-A9" #endif #endif /* IO definitions (access restrictions to peripheral registers) */ /** \defgroup CMSIS_glob_defs CMSIS Global Defines IO Type Qualifiers are used \li to specify the access to peripheral variables. \li for automatic generation of peripheral register debug information. */ #ifdef __cplusplus #define __I volatile /*!< Defines 'read only' permissions */ #else #define __I volatile const /*!< Defines 'read only' permissions */ #endif #define __O volatile /*!< Defines 'write only' permissions */ #define __IO volatile /*!< Defines 'read / write' permissions */ /*@} end of group Cortex_A9 */ /******************************************************************************* * Register Abstraction ******************************************************************************/ /** \defgroup CMSIS_core_register Defines and Type Definitions \brief Type definitions and defines for Cortex-A processor based devices. */ /** \ingroup CMSIS_core_register \defgroup CMSIS_CORE Status and Control Registers \brief Core Register type definitions. @{ */ /** \brief Union type to access the Application Program Status Register (APSR). */ typedef union { struct { uint32_t _reserved0:16; /*!< bit: 0..15 Reserved */ uint32_t GE:4; /*!< bit: 16..19 Greater than or Equal flags */ uint32_t reserved1:7; /*!< bit: 20..23 Reserved */ uint32_t Q:1; /*!< bit: 27 Saturation condition flag */ uint32_t V:1; /*!< bit: 28 Overflow condition code flag */ uint32_t C:1; /*!< bit: 29 Carry condition code flag */ uint32_t Z:1; /*!< bit: 30 Zero condition code flag */ uint32_t N:1; /*!< bit: 31 Negative condition code flag */ } b; /*!< Structure used for bit access */ uint32_t w; /*!< Type used for word access */ } APSR_Type; /*@} end of group CMSIS_CORE */ /*@} end of CMSIS_Core_FPUFunctions */ #endif /* __CORE_CA9_H_GENERIC */ #endif /* __CMSIS_GENERIC */ #ifdef __cplusplus } #endif ================================================ FILE: Zelig/mbed/TARGET_NUCLEO_L152RE/core_caFunc.h ================================================ /**************************************************************************//** * @file core_caFunc.h * @brief CMSIS Cortex-A Core Function Access Header File * @version V3.10 * @date 30 Oct 2013 * * @note * ******************************************************************************/ /* Copyright (c) 2009 - 2013 ARM LIMITED All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: - Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. - Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. - Neither the name of ARM 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 COPYRIGHT HOLDERS AND 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. ---------------------------------------------------------------------------*/ #ifndef __CORE_CAFUNC_H__ #define __CORE_CAFUNC_H__ /* ########################### Core Function Access ########################### */ /** \ingroup CMSIS_Core_FunctionInterface \defgroup CMSIS_Core_RegAccFunctions CMSIS Core Register Access Functions @{ */ #if defined ( __CC_ARM ) /*------------------RealView Compiler -----------------*/ /* ARM armcc specific functions */ #if (__ARMCC_VERSION < 400677) #error "Please use ARM Compiler Toolchain V4.0.677 or later!" #endif #define MODE_USR 0x10 #define MODE_FIQ 0x11 #define MODE_IRQ 0x12 #define MODE_SVC 0x13 #define MODE_MON 0x16 #define MODE_ABT 0x17 #define MODE_HYP 0x1A #define MODE_UND 0x1B #define MODE_SYS 0x1F /** \brief Get APSR Register This function returns the content of the APSR Register. \return APSR Register value */ __STATIC_INLINE uint32_t __get_APSR(void) { register uint32_t __regAPSR __ASM("apsr"); return(__regAPSR); } /** \brief Get CPSR Register This function returns the content of the CPSR Register. \return CPSR Register value */ __STATIC_INLINE uint32_t __get_CPSR(void) { register uint32_t __regCPSR __ASM("cpsr"); return(__regCPSR); } /** \brief Set Stack Pointer This function assigns the given value to the current stack pointer. \param [in] topOfStack Stack Pointer value to set */ register uint32_t __regSP __ASM("sp"); __STATIC_INLINE void __set_SP(uint32_t topOfStack) { __regSP = topOfStack; } /** \brief Get link register This function returns the value of the link register \return Value of link register */ register uint32_t __reglr __ASM("lr"); __STATIC_INLINE uint32_t __get_LR(void) { return(__reglr); } /** \brief Set link register This function sets the value of the link register \param [in] lr LR value to set */ __STATIC_INLINE void __set_LR(uint32_t lr) { __reglr = lr; } /** \brief Set Process Stack Pointer This function assigns the given value to the USR/SYS Stack Pointer (PSP). \param [in] topOfProcStack USR/SYS Stack Pointer value to set */ __STATIC_ASM void __set_PSP(uint32_t topOfProcStack) { ARM PRESERVE8 BIC R0, R0, #7 ;ensure stack is 8-byte aligned MRS R1, CPSR CPS #MODE_SYS ;no effect in USR mode MOV SP, R0 MSR CPSR_c, R1 ;no effect in USR mode ISB BX LR } /** \brief Set User Mode This function changes the processor state to User Mode */ __STATIC_ASM void __set_CPS_USR(void) { ARM CPS #MODE_USR BX LR } /** \brief Enable FIQ This function enables FIQ interrupts by clearing the F-bit in the CPSR. Can only be executed in Privileged modes. */ #define __enable_fault_irq __enable_fiq /** \brief Disable FIQ This function disables FIQ interrupts by setting the F-bit in the CPSR. Can only be executed in Privileged modes. */ #define __disable_fault_irq __disable_fiq /** \brief Get FPSCR This function returns the current value of the Floating Point Status/Control register. \return Floating Point Status/Control register value */ __STATIC_INLINE uint32_t __get_FPSCR(void) { #if (__FPU_PRESENT == 1) && (__FPU_USED == 1) register uint32_t __regfpscr __ASM("fpscr"); return(__regfpscr); #else return(0); #endif } /** \brief Set FPSCR This function assigns the given value to the Floating Point Status/Control register. \param [in] fpscr Floating Point Status/Control value to set */ __STATIC_INLINE void __set_FPSCR(uint32_t fpscr) { #if (__FPU_PRESENT == 1) && (__FPU_USED == 1) register uint32_t __regfpscr __ASM("fpscr"); __regfpscr = (fpscr); #endif } /** \brief Get FPEXC This function returns the current value of the Floating Point Exception Control register. \return Floating Point Exception Control register value */ __STATIC_INLINE uint32_t __get_FPEXC(void) { #if (__FPU_PRESENT == 1) register uint32_t __regfpexc __ASM("fpexc"); return(__regfpexc); #else return(0); #endif } /** \brief Set FPEXC This function assigns the given value to the Floating Point Exception Control register. \param [in] fpscr Floating Point Exception Control value to set */ __STATIC_INLINE void __set_FPEXC(uint32_t fpexc) { #if (__FPU_PRESENT == 1) register uint32_t __regfpexc __ASM("fpexc"); __regfpexc = (fpexc); #endif } /** \brief Get CPACR This function returns the current value of the Coprocessor Access Control register. \return Coprocessor Access Control register value */ __STATIC_INLINE uint32_t __get_CPACR(void) { register uint32_t __regCPACR __ASM("cp15:0:c1:c0:2"); return __regCPACR; } /** \brief Set CPACR This function assigns the given value to the Coprocessor Access Control register. \param [in] cpacr Coprocessor Acccess Control value to set */ __STATIC_INLINE void __set_CPACR(uint32_t cpacr) { register uint32_t __regCPACR __ASM("cp15:0:c1:c0:2"); __regCPACR = cpacr; __ISB(); } /** \brief Get CBAR This function returns the value of the Configuration Base Address register. \return Configuration Base Address register value */ __STATIC_INLINE uint32_t __get_CBAR() { register uint32_t __regCBAR __ASM("cp15:4:c15:c0:0"); return(__regCBAR); } /** \brief Get TTBR0 This function returns the value of the Translation Table Base Register 0. \return Translation Table Base Register 0 value */ __STATIC_INLINE uint32_t __get_TTBR0() { register uint32_t __regTTBR0 __ASM("cp15:0:c2:c0:0"); return(__regTTBR0); } /** \brief Set TTBR0 This function assigns the given value to the Translation Table Base Register 0. \param [in] ttbr0 Translation Table Base Register 0 value to set */ __STATIC_INLINE void __set_TTBR0(uint32_t ttbr0) { register uint32_t __regTTBR0 __ASM("cp15:0:c2:c0:0"); __regTTBR0 = ttbr0; __ISB(); } /** \brief Get DACR This function returns the value of the Domain Access Control Register. \return Domain Access Control Register value */ __STATIC_INLINE uint32_t __get_DACR() { register uint32_t __regDACR __ASM("cp15:0:c3:c0:0"); return(__regDACR); } /** \brief Set DACR This function assigns the given value to the Domain Access Control Register. \param [in] dacr Domain Access Control Register value to set */ __STATIC_INLINE void __set_DACR(uint32_t dacr) { register uint32_t __regDACR __ASM("cp15:0:c3:c0:0"); __regDACR = dacr; __ISB(); } /******************************** Cache and BTAC enable ****************************************************/ /** \brief Set SCTLR This function assigns the given value to the System Control Register. \param [in] sctlr System Control Register value to set */ __STATIC_INLINE void __set_SCTLR(uint32_t sctlr) { register uint32_t __regSCTLR __ASM("cp15:0:c1:c0:0"); __regSCTLR = sctlr; } /** \brief Get SCTLR This function returns the value of the System Control Register. \return System Control Register value */ __STATIC_INLINE uint32_t __get_SCTLR() { register uint32_t __regSCTLR __ASM("cp15:0:c1:c0:0"); return(__regSCTLR); } /** \brief Enable Caches Enable Caches */ __STATIC_INLINE void __enable_caches(void) { // Set I bit 12 to enable I Cache // Set C bit 2 to enable D Cache __set_SCTLR( __get_SCTLR() | (1 << 12) | (1 << 2)); } /** \brief Disable Caches Disable Caches */ __STATIC_INLINE void __disable_caches(void) { // Clear I bit 12 to disable I Cache // Clear C bit 2 to disable D Cache __set_SCTLR( __get_SCTLR() & ~(1 << 12) & ~(1 << 2)); __ISB(); } /** \brief Enable BTAC Enable BTAC */ __STATIC_INLINE void __enable_btac(void) { // Set Z bit 11 to enable branch prediction __set_SCTLR( __get_SCTLR() | (1 << 11)); __ISB(); } /** \brief Disable BTAC Disable BTAC */ __STATIC_INLINE void __disable_btac(void) { // Clear Z bit 11 to disable branch prediction __set_SCTLR( __get_SCTLR() & ~(1 << 11)); } /** \brief Enable MMU Enable MMU */ __STATIC_INLINE void __enable_mmu(void) { // Set M bit 0 to enable the MMU // Set AFE bit to enable simplified access permissions model // Clear TRE bit to disable TEX remap and A bit to disable strict alignment fault checking __set_SCTLR( (__get_SCTLR() & ~(1 << 28) & ~(1 << 1)) | 1 | (1 << 29)); __ISB(); } /** \brief Disable MMU Disable MMU */ __STATIC_INLINE void __disable_mmu(void) { // Clear M bit 0 to disable the MMU __set_SCTLR( __get_SCTLR() & ~1); __ISB(); } /******************************** TLB maintenance operations ************************************************/ /** \brief Invalidate the whole tlb TLBIALL. Invalidate the whole tlb */ __STATIC_INLINE void __ca9u_inv_tlb_all(void) { register uint32_t __TLBIALL __ASM("cp15:0:c8:c7:0"); __TLBIALL = 0; __DSB(); __ISB(); } /******************************** BTB maintenance operations ************************************************/ /** \brief Invalidate entire branch predictor array BPIALL. Branch Predictor Invalidate All. */ __STATIC_INLINE void __v7_inv_btac(void) { register uint32_t __BPIALL __ASM("cp15:0:c7:c5:6"); __BPIALL = 0; __DSB(); //ensure completion of the invalidation __ISB(); //ensure instruction fetch path sees new state } /******************************** L1 cache operations ******************************************************/ /** \brief Invalidate the whole I$ ICIALLU. Instruction Cache Invalidate All to PoU */ __STATIC_INLINE void __v7_inv_icache_all(void) { register uint32_t __ICIALLU __ASM("cp15:0:c7:c5:0"); __ICIALLU = 0; __DSB(); //ensure completion of the invalidation __ISB(); //ensure instruction fetch path sees new I cache state } /** \brief Clean D$ by MVA DCCMVAC. Data cache clean by MVA to PoC */ __STATIC_INLINE void __v7_clean_dcache_mva(void *va) { register uint32_t __DCCMVAC __ASM("cp15:0:c7:c10:1"); __DCCMVAC = (uint32_t)va; __DMB(); //ensure the ordering of data cache maintenance operations and their effects } /** \brief Invalidate D$ by MVA DCIMVAC. Data cache invalidate by MVA to PoC */ __STATIC_INLINE void __v7_inv_dcache_mva(void *va) { register uint32_t __DCIMVAC __ASM("cp15:0:c7:c6:1"); __DCIMVAC = (uint32_t)va; __DMB(); //ensure the ordering of data cache maintenance operations and their effects } /** \brief Clean and Invalidate D$ by MVA DCCIMVAC. Data cache clean and invalidate by MVA to PoC */ __STATIC_INLINE void __v7_clean_inv_dcache_mva(void *va) { register uint32_t __DCCIMVAC __ASM("cp15:0:c7:c14:1"); __DCCIMVAC = (uint32_t)va; __DMB(); //ensure the ordering of data cache maintenance operations and their effects } /** \brief Clean and Invalidate the entire data or unified cache Generic mechanism for cleaning/invalidating the entire data or unified cache to the point of coherency. */ #pragma push #pragma arm __STATIC_ASM void __v7_all_cache(uint32_t op) { ARM PUSH {R4-R11} MRC p15, 1, R6, c0, c0, 1 // Read CLIDR ANDS R3, R6, #0x07000000 // Extract coherency level MOV R3, R3, LSR #23 // Total cache levels << 1 BEQ Finished // If 0, no need to clean MOV R10, #0 // R10 holds current cache level << 1 Loop1 ADD R2, R10, R10, LSR #1 // R2 holds cache "Set" position MOV R1, R6, LSR R2 // Bottom 3 bits are the Cache-type for this level AND R1, R1, #7 // Isolate those lower 3 bits CMP R1, #2 BLT Skip // No cache or only instruction cache at this level MCR p15, 2, R10, c0, c0, 0 // Write the Cache Size selection register ISB // ISB to sync the change to the CacheSizeID reg MRC p15, 1, R1, c0, c0, 0 // Reads current Cache Size ID register AND R2, R1, #7 // Extract the line length field ADD R2, R2, #4 // Add 4 for the line length offset (log2 16 bytes) LDR R4, =0x3FF ANDS R4, R4, R1, LSR #3 // R4 is the max number on the way size (right aligned) CLZ R5, R4 // R5 is the bit position of the way size increment LDR R7, =0x7FFF ANDS R7, R7, R1, LSR #13 // R7 is the max number of the index size (right aligned) Loop2 MOV R9, R4 // R9 working copy of the max way size (right aligned) Loop3 ORR R11, R10, R9, LSL R5 // Factor in the Way number and cache number into R11 ORR R11, R11, R7, LSL R2 // Factor in the Set number CMP R0, #0 BNE Dccsw MCR p15, 0, R11, c7, c6, 2 // DCISW. Invalidate by Set/Way B cont Dccsw CMP R0, #1 BNE Dccisw MCR p15, 0, R11, c7, c10, 2 // DCCSW. Clean by Set/Way B cont Dccisw MCR p15, 0, R11, c7, c14, 2 // DCCISW. Clean and Invalidate by Set/Way cont SUBS R9, R9, #1 // Decrement the Way number BGE Loop3 SUBS R7, R7, #1 // Decrement the Set number BGE Loop2 Skip ADD R10, R10, #2 // Increment the cache number CMP R3, R10 BGT Loop1 Finished DSB POP {R4-R11} BX lr } #pragma pop /** \brief Invalidate the whole D$ DCISW. Invalidate by Set/Way */ __STATIC_INLINE void __v7_inv_dcache_all(void) { __v7_all_cache(0); } /** \brief Clean the whole D$ DCCSW. Clean by Set/Way */ __STATIC_INLINE void __v7_clean_dcache_all(void) { __v7_all_cache(1); } /** \brief Clean and invalidate the whole D$ DCCISW. Clean and Invalidate by Set/Way */ __STATIC_INLINE void __v7_clean_inv_dcache_all(void) { __v7_all_cache(2); } #include "core_ca_mmu.h" #elif (defined (__ICCARM__)) /*---------------- ICC Compiler ---------------------*/ #error IAR Compiler support not implemented for Cortex-A #elif (defined (__GNUC__)) /*------------------ GNU Compiler ---------------------*/ /* GNU gcc specific functions */ #define MODE_USR 0x10 #define MODE_FIQ 0x11 #define MODE_IRQ 0x12 #define MODE_SVC 0x13 #define MODE_MON 0x16 #define MODE_ABT 0x17 #define MODE_HYP 0x1A #define MODE_UND 0x1B #define MODE_SYS 0x1F __attribute__( ( always_inline ) ) __STATIC_INLINE void __enable_irq(void) { __ASM volatile ("cpsie i"); } /** \brief Disable IRQ Interrupts This function disables IRQ interrupts by setting the I-bit in the CPSR. Can only be executed in Privileged modes. */ __attribute__( ( always_inline ) ) __STATIC_INLINE uint32_t __disable_irq(void) { uint32_t result; __ASM volatile ("mrs %0, cpsr" : "=r" (result)); __ASM volatile ("cpsid i"); return(result & 0x80); } /** \brief Get APSR Register This function returns the content of the APSR Register. \return APSR Register value */ __attribute__( ( always_inline ) ) __STATIC_INLINE uint32_t __get_APSR(void) { #if 1 register uint32_t __regAPSR; __ASM volatile ("mrs %0, apsr" : "=r" (__regAPSR) ); #else register uint32_t __regAPSR __ASM("apsr"); #endif return(__regAPSR); } /** \brief Get CPSR Register This function returns the content of the CPSR Register. \return CPSR Register value */ __attribute__( ( always_inline ) ) __STATIC_INLINE uint32_t __get_CPSR(void) { #if 1 register uint32_t __regCPSR; __ASM volatile ("mrs %0, cpsr" : "=r" (__regCPSR)); #else register uint32_t __regCPSR __ASM("cpsr"); #endif return(__regCPSR); } #if 0 /** \brief Set Stack Pointer This function assigns the given value to the current stack pointer. \param [in] topOfStack Stack Pointer value to set */ __attribute__( ( always_inline ) ) __STATIC_INLINE void __set_SP(uint32_t topOfStack) { register uint32_t __regSP __ASM("sp"); __regSP = topOfStack; } #endif /** \brief Get link register This function returns the value of the link register \return Value of link register */ __attribute__( ( always_inline ) ) __STATIC_INLINE uint32_t __get_LR(void) { register uint32_t __reglr __ASM("lr"); return(__reglr); } #if 0 /** \brief Set link register This function sets the value of the link register \param [in] lr LR value to set */ __attribute__( ( always_inline ) ) __STATIC_INLINE void __set_LR(uint32_t lr) { register uint32_t __reglr __ASM("lr"); __reglr = lr; } #endif /** \brief Set Process Stack Pointer This function assigns the given value to the USR/SYS Stack Pointer (PSP). \param [in] topOfProcStack USR/SYS Stack Pointer value to set */ __attribute__( ( always_inline ) ) __STATIC_INLINE void __set_PSP(uint32_t topOfProcStack) { __asm__ volatile ( ".ARM;" ".eabi_attribute Tag_ABI_align8_preserved,1;" "BIC R0, R0, #7;" /* ;ensure stack is 8-byte aligned */ "MRS R1, CPSR;" "CPS %0;" /* ;no effect in USR mode */ "MOV SP, R0;" "MSR CPSR_c, R1;" /* ;no effect in USR mode */ "ISB;" //"BX LR;" : : "i"(MODE_SYS) : "r0", "r1"); return; } /** \brief Set User Mode This function changes the processor state to User Mode */ __attribute__( ( always_inline ) ) __STATIC_INLINE void __set_CPS_USR(void) { __asm__ volatile ( ".ARM;" "CPS %0;" //"BX LR;" : : "i"(MODE_USR) : ); return; } /** \brief Enable FIQ This function enables FIQ interrupts by clearing the F-bit in the CPSR. Can only be executed in Privileged modes. */ #define __enable_fault_irq() __asm__ volatile ("cpsie f") /** \brief Disable FIQ This function disables FIQ interrupts by setting the F-bit in the CPSR. Can only be executed in Privileged modes. */ #define __disable_fault_irq() __asm__ volatile ("cpsid f") /** \brief Get FPSCR This function returns the current value of the Floating Point Status/Control register. \return Floating Point Status/Control register value */ __attribute__( ( always_inline ) ) __STATIC_INLINE uint32_t __get_FPSCR(void) { #if (__FPU_PRESENT == 1) && (__FPU_USED == 1) #if 1 uint32_t result; __ASM volatile ("vmrs %0, fpscr" : "=r" (result) ); return (result); #else register uint32_t __regfpscr __ASM("fpscr"); return(__regfpscr); #endif #else return(0); #endif } /** \brief Set FPSCR This function assigns the given value to the Floating Point Status/Control register. \param [in] fpscr Floating Point Status/Control value to set */ __attribute__( ( always_inline ) ) __STATIC_INLINE void __set_FPSCR(uint32_t fpscr) { #if (__FPU_PRESENT == 1) && (__FPU_USED == 1) #if 1 __ASM volatile ("vmsr fpscr, %0" : : "r" (fpscr) ); #else register uint32_t __regfpscr __ASM("fpscr"); __regfpscr = (fpscr); #endif #endif } /** \brief Get FPEXC This function returns the current value of the Floating Point Exception Control register. \return Floating Point Exception Control register value */ __attribute__( ( always_inline ) ) __STATIC_INLINE uint32_t __get_FPEXC(void) { #if (__FPU_PRESENT == 1) #if 1 uint32_t result; __ASM volatile ("vmrs %0, fpexc" : "=r" (result)); return (result); #else register uint32_t __regfpexc __ASM("fpexc"); return(__regfpexc); #endif #else return(0); #endif } /** \brief Set FPEXC This function assigns the given value to the Floating Point Exception Control register. \param [in] fpscr Floating Point Exception Control value to set */ __attribute__( ( always_inline ) ) __STATIC_INLINE void __set_FPEXC(uint32_t fpexc) { #if (__FPU_PRESENT == 1) #if 1 __ASM volatile ("vmsr fpexc, %0" : : "r" (fpexc)); #else register uint32_t __regfpexc __ASM("fpexc"); __regfpexc = (fpexc); #endif #endif } /** \brief Get CPACR This function returns the current value of the Coprocessor Access Control register. \return Coprocessor Access Control register value */ __attribute__( ( always_inline ) ) __STATIC_INLINE uint32_t __get_CPACR(void) { #if 1 register uint32_t __regCPACR; __ASM volatile ("mrc p15, 0, %0, c1, c0, 2" : "=r" (__regCPACR)); #else register uint32_t __regCPACR __ASM("cp15:0:c1:c0:2"); #endif return __regCPACR; } /** \brief Set CPACR This function assigns the given value to the Coprocessor Access Control register. \param [in] cpacr Coprocessor Acccess Control value to set */ __attribute__( ( always_inline ) ) __STATIC_INLINE void __set_CPACR(uint32_t cpacr) { #if 1 __ASM volatile ("mcr p15, 0, %0, c1, c0, 2" : : "r" (cpacr)); #else register uint32_t __regCPACR __ASM("cp15:0:c1:c0:2"); __regCPACR = cpacr; #endif __ISB(); } /** \brief Get CBAR This function returns the value of the Configuration Base Address register. \return Configuration Base Address register value */ __attribute__( ( always_inline ) ) __STATIC_INLINE uint32_t __get_CBAR() { #if 1 register uint32_t __regCBAR; __ASM volatile ("mrc p15, 4, %0, c15, c0, 0" : "=r" (__regCBAR)); #else register uint32_t __regCBAR __ASM("cp15:4:c15:c0:0"); #endif return(__regCBAR); } /** \brief Get TTBR0 This function returns the value of the Translation Table Base Register 0. \return Translation Table Base Register 0 value */ __attribute__( ( always_inline ) ) __STATIC_INLINE uint32_t __get_TTBR0() { #if 1 register uint32_t __regTTBR0; __ASM volatile ("mrc p15, 0, %0, c2, c0, 0" : "=r" (__regTTBR0)); #else register uint32_t __regTTBR0 __ASM("cp15:0:c2:c0:0"); #endif return(__regTTBR0); } /** \brief Set TTBR0 This function assigns the given value to the Translation Table Base Register 0. \param [in] ttbr0 Translation Table Base Register 0 value to set */ __attribute__( ( always_inline ) ) __STATIC_INLINE void __set_TTBR0(uint32_t ttbr0) { #if 1 __ASM volatile ("mcr p15, 0, %0, c2, c0, 0" : : "r" (ttbr0)); #else register uint32_t __regTTBR0 __ASM("cp15:0:c2:c0:0"); __regTTBR0 = ttbr0; #endif __ISB(); } /** \brief Get DACR This function returns the value of the Domain Access Control Register. \return Domain Access Control Register value */ __attribute__( ( always_inline ) ) __STATIC_INLINE uint32_t __get_DACR() { #if 1 register uint32_t __regDACR; __ASM volatile ("mrc p15, 0, %0, c3, c0, 0" : "=r" (__regDACR)); #else register uint32_t __regDACR __ASM("cp15:0:c3:c0:0"); #endif return(__regDACR); } /** \brief Set DACR This function assigns the given value to the Domain Access Control Register. \param [in] dacr Domain Access Control Register value to set */ __attribute__( ( always_inline ) ) __STATIC_INLINE void __set_DACR(uint32_t dacr) { #if 1 __ASM volatile ("mcr p15, 0, %0, c3, c0, 0" : : "r" (dacr)); #else register uint32_t __regDACR __ASM("cp15:0:c3:c0:0"); __regDACR = dacr; #endif __ISB(); } /******************************** Cache and BTAC enable ****************************************************/ /** \brief Set SCTLR This function assigns the given value to the System Control Register. \param [in] sctlr System Control Register value to set */ __attribute__( ( always_inline ) ) __STATIC_INLINE void __set_SCTLR(uint32_t sctlr) { #if 1 __ASM volatile ("mcr p15, 0, %0, c1, c0, 0" : : "r" (sctlr)); #else register uint32_t __regSCTLR __ASM("cp15:0:c1:c0:0"); __regSCTLR = sctlr; #endif } /** \brief Get SCTLR This function returns the value of the System Control Register. \return System Control Register value */ __attribute__( ( always_inline ) ) __STATIC_INLINE uint32_t __get_SCTLR() { #if 1 register uint32_t __regSCTLR; __ASM volatile ("mrc p15, 0, %0, c1, c0, 0" : "=r" (__regSCTLR)); #else register uint32_t __regSCTLR __ASM("cp15:0:c1:c0:0"); #endif return(__regSCTLR); } /** \brief Enable Caches Enable Caches */ __attribute__( ( always_inline ) ) __STATIC_INLINE void __enable_caches(void) { // Set I bit 12 to enable I Cache // Set C bit 2 to enable D Cache __set_SCTLR( __get_SCTLR() | (1 << 12) | (1 << 2)); } /** \brief Disable Caches Disable Caches */ __attribute__( ( always_inline ) ) __STATIC_INLINE void __disable_caches(void) { // Clear I bit 12 to disable I Cache // Clear C bit 2 to disable D Cache __set_SCTLR( __get_SCTLR() & ~(1 << 12) & ~(1 << 2)); __ISB(); } /** \brief Enable BTAC Enable BTAC */ __attribute__( ( always_inline ) ) __STATIC_INLINE void __enable_btac(void) { // Set Z bit 11 to enable branch prediction __set_SCTLR( __get_SCTLR() | (1 << 11)); __ISB(); } /** \brief Disable BTAC Disable BTAC */ __attribute__( ( always_inline ) ) __STATIC_INLINE void __disable_btac(void) { // Clear Z bit 11 to disable branch prediction __set_SCTLR( __get_SCTLR() & ~(1 << 11)); } /** \brief Enable MMU Enable MMU */ __attribute__( ( always_inline ) ) __STATIC_INLINE void __enable_mmu(void) { // Set M bit 0 to enable the MMU // Set AFE bit to enable simplified access permissions model // Clear TRE bit to disable TEX remap and A bit to disable strict alignment fault checking __set_SCTLR( (__get_SCTLR() & ~(1 << 28) & ~(1 << 1)) | 1 | (1 << 29)); __ISB(); } /** \brief Disable MMU Disable MMU */ __attribute__( ( always_inline ) ) __STATIC_INLINE void __disable_mmu(void) { // Clear M bit 0 to disable the MMU __set_SCTLR( __get_SCTLR() & ~1); __ISB(); } /******************************** TLB maintenance operations ************************************************/ /** \brief Invalidate the whole tlb TLBIALL. Invalidate the whole tlb */ __attribute__( ( always_inline ) ) __STATIC_INLINE void __ca9u_inv_tlb_all(void) { #if 1 __ASM volatile ("mcr p15, 0, %0, c8, c7, 0" : : "r" (0)); #else register uint32_t __TLBIALL __ASM("cp15:0:c8:c7:0"); __TLBIALL = 0; #endif __DSB(); __ISB(); } /******************************** BTB maintenance operations ************************************************/ /** \brief Invalidate entire branch predictor array BPIALL. Branch Predictor Invalidate All. */ __attribute__( ( always_inline ) ) __STATIC_INLINE void __v7_inv_btac(void) { #if 1 __ASM volatile ("mcr p15, 0, %0, c7, c5, 6" : : "r" (0)); #else register uint32_t __BPIALL __ASM("cp15:0:c7:c5:6"); __BPIALL = 0; #endif __DSB(); //ensure completion of the invalidation __ISB(); //ensure instruction fetch path sees new state } /******************************** L1 cache operations ******************************************************/ /** \brief Invalidate the whole I$ ICIALLU. Instruction Cache Invalidate All to PoU */ __attribute__( ( always_inline ) ) __STATIC_INLINE void __v7_inv_icache_all(void) { #if 1 __ASM volatile ("mcr p15, 0, %0, c7, c5, 0" : : "r" (0)); #else register uint32_t __ICIALLU __ASM("cp15:0:c7:c5:0"); __ICIALLU = 0; #endif __DSB(); //ensure completion of the invalidation __ISB(); //ensure instruction fetch path sees new I cache state } /** \brief Clean D$ by MVA DCCMVAC. Data cache clean by MVA to PoC */ __attribute__( ( always_inline ) ) __STATIC_INLINE void __v7_clean_dcache_mva(void *va) { #if 1 __ASM volatile ("mcr p15, 0, %0, c7, c10, 1" : : "r" ((uint32_t)va)); #else register uint32_t __DCCMVAC __ASM("cp15:0:c7:c10:1"); __DCCMVAC = (uint32_t)va; #endif __DMB(); //ensure the ordering of data cache maintenance operations and their effects } /** \brief Invalidate D$ by MVA DCIMVAC. Data cache invalidate by MVA to PoC */ __attribute__( ( always_inline ) ) __STATIC_INLINE void __v7_inv_dcache_mva(void *va) { #if 1 __ASM volatile ("mcr p15, 0, %0, c7, c6, 1" : : "r" ((uint32_t)va)); #else register uint32_t __DCIMVAC __ASM("cp15:0:c7:c6:1"); __DCIMVAC = (uint32_t)va; #endif __DMB(); //ensure the ordering of data cache maintenance operations and their effects } /** \brief Clean and Invalidate D$ by MVA DCCIMVAC. Data cache clean and invalidate by MVA to PoC */ __attribute__( ( always_inline ) ) __STATIC_INLINE void __v7_clean_inv_dcache_mva(void *va) { #if 1 __ASM volatile ("mcr p15, 0, %0, c7, c14, 1" : : "r" ((uint32_t)va)); #else register uint32_t __DCCIMVAC __ASM("cp15:0:c7:c14:1"); __DCCIMVAC = (uint32_t)va; #endif __DMB(); //ensure the ordering of data cache maintenance operations and their effects } /** \brief Clean and Invalidate the entire data or unified cache Generic mechanism for cleaning/invalidating the entire data or unified cache to the point of coherency. */ extern void __v7_all_cache(uint32_t op); /** \brief Invalidate the whole D$ DCISW. Invalidate by Set/Way */ __attribute__( ( always_inline ) ) __STATIC_INLINE void __v7_inv_dcache_all(void) { __v7_all_cache(0); } /** \brief Clean the whole D$ DCCSW. Clean by Set/Way */ __attribute__( ( always_inline ) ) __STATIC_INLINE void __v7_clean_dcache_all(void) { __v7_all_cache(1); } /** \brief Clean and invalidate the whole D$ DCCISW. Clean and Invalidate by Set/Way */ __attribute__( ( always_inline ) ) __STATIC_INLINE void __v7_clean_inv_dcache_all(void) { __v7_all_cache(2); } #include "core_ca_mmu.h" #elif (defined (__TASKING__)) /*--------------- TASKING Compiler -----------------*/ #error TASKING Compiler support not implemented for Cortex-A #endif /*@} end of CMSIS_Core_RegAccFunctions */ #endif /* __CORE_CAFUNC_H__ */ ================================================ FILE: Zelig/mbed/TARGET_NUCLEO_L152RE/core_caInstr.h ================================================ /**************************************************************************//** * @file core_caInstr.h * @brief CMSIS Cortex-A9 Core Peripheral Access Layer Header File * @version * @date 04. December 2012 * * @note * ******************************************************************************/ /* Copyright (c) 2009 - 2012 ARM LIMITED All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: - Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. - Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. - Neither the name of ARM 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 COPYRIGHT HOLDERS AND 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. ---------------------------------------------------------------------------*/ #ifndef __CORE_CAINSTR_H__ #define __CORE_CAINSTR_H__ #define __CORTEX_M 0x3 #include "core_cmInstr.h" #undef __CORTEX_M #endif ================================================ FILE: Zelig/mbed/TARGET_NUCLEO_L152RE/core_ca_mmu.h ================================================ ;/**************************************************************************//** ; * @file core_ca_mmu.h ; * @brief MMU Startup File for A9_MP Device Series ; * @version V1.01 ; * @date 10 Sept 2014 ; * ; * @note ; * ; ******************************************************************************/ ;/* Copyright (c) 2012-2014 ARM LIMITED ; ; All rights reserved. ; Redistribution and use in source and binary forms, with or without ; modification, are permitted provided that the following conditions are met: ; - Redistributions of source code must retain the above copyright ; notice, this list of conditions and the following disclaimer. ; - Redistributions in binary form must reproduce the above copyright ; notice, this list of conditions and the following disclaimer in the ; documentation and/or other materials provided with the distribution. ; - Neither the name of ARM 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 COPYRIGHT HOLDERS AND CONTRIBUTORS BE ; LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR ; CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF ; SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS ; INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN ; CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ; ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE ; POSSIBILITY OF SUCH DAMAGE. ; ---------------------------------------------------------------------------*/ #ifdef __cplusplus extern "C" { #endif #ifndef _MMU_FUNC_H #define _MMU_FUNC_H #define SECTION_DESCRIPTOR (0x2) #define SECTION_MASK (0xFFFFFFFC) #define SECTION_TEXCB_MASK (0xFFFF8FF3) #define SECTION_B_SHIFT (2) #define SECTION_C_SHIFT (3) #define SECTION_TEX0_SHIFT (12) #define SECTION_TEX1_SHIFT (13) #define SECTION_TEX2_SHIFT (14) #define SECTION_XN_MASK (0xFFFFFFEF) #define SECTION_XN_SHIFT (4) #define SECTION_DOMAIN_MASK (0xFFFFFE1F) #define SECTION_DOMAIN_SHIFT (5) #define SECTION_P_MASK (0xFFFFFDFF) #define SECTION_P_SHIFT (9) #define SECTION_AP_MASK (0xFFFF73FF) #define SECTION_AP_SHIFT (10) #define SECTION_AP2_SHIFT (15) #define SECTION_S_MASK (0xFFFEFFFF) #define SECTION_S_SHIFT (16) #define SECTION_NG_MASK (0xFFFDFFFF) #define SECTION_NG_SHIFT (17) #define SECTION_NS_MASK (0xFFF7FFFF) #define SECTION_NS_SHIFT (19) #define PAGE_L1_DESCRIPTOR (0x1) #define PAGE_L1_MASK (0xFFFFFFFC) #define PAGE_L2_4K_DESC (0x2) #define PAGE_L2_4K_MASK (0xFFFFFFFD) #define PAGE_L2_64K_DESC (0x1) #define PAGE_L2_64K_MASK (0xFFFFFFFC) #define PAGE_4K_TEXCB_MASK (0xFFFFFE33) #define PAGE_4K_B_SHIFT (2) #define PAGE_4K_C_SHIFT (3) #define PAGE_4K_TEX0_SHIFT (6) #define PAGE_4K_TEX1_SHIFT (7) #define PAGE_4K_TEX2_SHIFT (8) #define PAGE_64K_TEXCB_MASK (0xFFFF8FF3) #define PAGE_64K_B_SHIFT (2) #define PAGE_64K_C_SHIFT (3) #define PAGE_64K_TEX0_SHIFT (12) #define PAGE_64K_TEX1_SHIFT (13) #define PAGE_64K_TEX2_SHIFT (14) #define PAGE_TEXCB_MASK (0xFFFF8FF3) #define PAGE_B_SHIFT (2) #define PAGE_C_SHIFT (3) #define PAGE_TEX_SHIFT (12) #define PAGE_XN_4K_MASK (0xFFFFFFFE) #define PAGE_XN_4K_SHIFT (0) #define PAGE_XN_64K_MASK (0xFFFF7FFF) #define PAGE_XN_64K_SHIFT (15) #define PAGE_DOMAIN_MASK (0xFFFFFE1F) #define PAGE_DOMAIN_SHIFT (5) #define PAGE_P_MASK (0xFFFFFDFF) #define PAGE_P_SHIFT (9) #define PAGE_AP_MASK (0xFFFFFDCF) #define PAGE_AP_SHIFT (4) #define PAGE_AP2_SHIFT (9) #define PAGE_S_MASK (0xFFFFFBFF) #define PAGE_S_SHIFT (10) #define PAGE_NG_MASK (0xFFFFF7FF) #define PAGE_NG_SHIFT (11) #define PAGE_NS_MASK (0xFFFFFFF7) #define PAGE_NS_SHIFT (3) #define OFFSET_1M (0x00100000) #define OFFSET_64K (0x00010000) #define OFFSET_4K (0x00001000) #define DESCRIPTOR_FAULT (0x00000000) /* ########################### MMU Function Access ########################### */ /** \ingroup MMU_FunctionInterface \defgroup MMU_Functions MMU Functions Interface @{ */ /* Attributes enumerations */ /* Region size attributes */ typedef enum { SECTION, PAGE_4k, PAGE_64k, } mmu_region_size_Type; /* Region type attributes */ typedef enum { NORMAL, DEVICE, SHARED_DEVICE, NON_SHARED_DEVICE, STRONGLY_ORDERED } mmu_memory_Type; /* Region cacheability attributes */ typedef enum { NON_CACHEABLE, WB_WA, WT, WB_NO_WA, } mmu_cacheability_Type; /* Region parity check attributes */ typedef enum { ECC_DISABLED, ECC_ENABLED, } mmu_ecc_check_Type; /* Region execution attributes */ typedef enum { EXECUTE, NON_EXECUTE, } mmu_execute_Type; /* Region global attributes */ typedef enum { GLOBAL, NON_GLOBAL, } mmu_global_Type; /* Region shareability attributes */ typedef enum { NON_SHARED, SHARED, } mmu_shared_Type; /* Region security attributes */ typedef enum { SECURE, NON_SECURE, } mmu_secure_Type; /* Region access attributes */ typedef enum { NO_ACCESS, RW, READ, } mmu_access_Type; /* Memory Region definition */ typedef struct RegionStruct { mmu_region_size_Type rg_t; mmu_memory_Type mem_t; uint8_t domain; mmu_cacheability_Type inner_norm_t; mmu_cacheability_Type outer_norm_t; mmu_ecc_check_Type e_t; mmu_execute_Type xn_t; mmu_global_Type g_t; mmu_secure_Type sec_t; mmu_access_Type priv_t; mmu_access_Type user_t; mmu_shared_Type sh_t; } mmu_region_attributes_Type; /** \brief Set section execution-never attribute The function sets section execution-never attribute \param [out] descriptor_l1 L1 descriptor. \param [in] xn Section execution-never attribute : EXECUTE , NON_EXECUTE. \return 0 */ __STATIC_INLINE int __xn_section(uint32_t *descriptor_l1, mmu_execute_Type xn) { *descriptor_l1 &= SECTION_XN_MASK; *descriptor_l1 |= ((xn & 0x1) << SECTION_XN_SHIFT); return 0; } /** \brief Set section domain The function sets section domain \param [out] descriptor_l1 L1 descriptor. \param [in] domain Section domain \return 0 */ __STATIC_INLINE int __domain_section(uint32_t *descriptor_l1, uint8_t domain) { *descriptor_l1 &= SECTION_DOMAIN_MASK; *descriptor_l1 |= ((domain & 0xF) << SECTION_DOMAIN_SHIFT); return 0; } /** \brief Set section parity check The function sets section parity check \param [out] descriptor_l1 L1 descriptor. \param [in] p_bit Parity check: ECC_DISABLED, ECC_ENABLED \return 0 */ __STATIC_INLINE int __p_section(uint32_t *descriptor_l1, mmu_ecc_check_Type p_bit) { *descriptor_l1 &= SECTION_P_MASK; *descriptor_l1 |= ((p_bit & 0x1) << SECTION_P_SHIFT); return 0; } /** \brief Set section access privileges The function sets section access privileges \param [out] descriptor_l1 L1 descriptor. \param [in] user User Level Access: NO_ACCESS, RW, READ \param [in] priv Privilege Level Access: NO_ACCESS, RW, READ \param [in] afe Access flag enable \return 0 */ __STATIC_INLINE int __ap_section(uint32_t *descriptor_l1, mmu_access_Type user, mmu_access_Type priv, uint32_t afe) { uint32_t ap = 0; if (afe == 0) { //full access if ((priv == NO_ACCESS) && (user == NO_ACCESS)) { ap = 0x0; } else if ((priv == RW) && (user == NO_ACCESS)) { ap = 0x1; } else if ((priv == RW) && (user == READ)) { ap = 0x2; } else if ((priv == RW) && (user == RW)) { ap = 0x3; } else if ((priv == READ) && (user == NO_ACCESS)) { ap = 0x5; } else if ((priv == READ) && (user == READ)) { ap = 0x7; } } else { //Simplified access if ((priv == RW) && (user == NO_ACCESS)) { ap = 0x1; } else if ((priv == RW) && (user == RW)) { ap = 0x3; } else if ((priv == READ) && (user == NO_ACCESS)) { ap = 0x5; } else if ((priv == READ) && (user == READ)) { ap = 0x7; } } *descriptor_l1 &= SECTION_AP_MASK; *descriptor_l1 |= (ap & 0x3) << SECTION_AP_SHIFT; *descriptor_l1 |= ((ap & 0x4)>>2) << SECTION_AP2_SHIFT; return 0; } /** \brief Set section shareability The function sets section shareability \param [out] descriptor_l1 L1 descriptor. \param [in] s_bit Section shareability: NON_SHARED, SHARED \return 0 */ __STATIC_INLINE int __shared_section(uint32_t *descriptor_l1, mmu_shared_Type s_bit) { *descriptor_l1 &= SECTION_S_MASK; *descriptor_l1 |= ((s_bit & 0x1) << SECTION_S_SHIFT); return 0; } /** \brief Set section Global attribute The function sets section Global attribute \param [out] descriptor_l1 L1 descriptor. \param [in] g_bit Section attribute: GLOBAL, NON_GLOBAL \return 0 */ __STATIC_INLINE int __global_section(uint32_t *descriptor_l1, mmu_global_Type g_bit) { *descriptor_l1 &= SECTION_NG_MASK; *descriptor_l1 |= ((g_bit & 0x1) << SECTION_NG_SHIFT); return 0; } /** \brief Set section Security attribute The function sets section Global attribute \param [out] descriptor_l1 L1 descriptor. \param [in] s_bit Section Security attribute: SECURE, NON_SECURE \return 0 */ __STATIC_INLINE int __secure_section(uint32_t *descriptor_l1, mmu_secure_Type s_bit) { *descriptor_l1 &= SECTION_NS_MASK; *descriptor_l1 |= ((s_bit & 0x1) << SECTION_NS_SHIFT); return 0; } /* Page 4k or 64k */ /** \brief Set 4k/64k page execution-never attribute The function sets 4k/64k page execution-never attribute \param [out] descriptor_l2 L2 descriptor. \param [in] xn Page execution-never attribute : EXECUTE , NON_EXECUTE. \param [in] page Page size: PAGE_4k, PAGE_64k, \return 0 */ __STATIC_INLINE int __xn_page(uint32_t *descriptor_l2, mmu_execute_Type xn, mmu_region_size_Type page) { if (page == PAGE_4k) { *descriptor_l2 &= PAGE_XN_4K_MASK; *descriptor_l2 |= ((xn & 0x1) << PAGE_XN_4K_SHIFT); } else { *descriptor_l2 &= PAGE_XN_64K_MASK; *descriptor_l2 |= ((xn & 0x1) << PAGE_XN_64K_SHIFT); } return 0; } /** \brief Set 4k/64k page domain The function sets 4k/64k page domain \param [out] descriptor_l1 L1 descriptor. \param [in] domain Page domain \return 0 */ __STATIC_INLINE int __domain_page(uint32_t *descriptor_l1, uint8_t domain) { *descriptor_l1 &= PAGE_DOMAIN_MASK; *descriptor_l1 |= ((domain & 0xf) << PAGE_DOMAIN_SHIFT); return 0; } /** \brief Set 4k/64k page parity check The function sets 4k/64k page parity check \param [out] descriptor_l1 L1 descriptor. \param [in] p_bit Parity check: ECC_DISABLED, ECC_ENABLED \return 0 */ __STATIC_INLINE int __p_page(uint32_t *descriptor_l1, mmu_ecc_check_Type p_bit) { *descriptor_l1 &= SECTION_P_MASK; *descriptor_l1 |= ((p_bit & 0x1) << SECTION_P_SHIFT); return 0; } /** \brief Set 4k/64k page access privileges The function sets 4k/64k page access privileges \param [out] descriptor_l2 L2 descriptor. \param [in] user User Level Access: NO_ACCESS, RW, READ \param [in] priv Privilege Level Access: NO_ACCESS, RW, READ \param [in] afe Access flag enable \return 0 */ __STATIC_INLINE int __ap_page(uint32_t *descriptor_l2, mmu_access_Type user, mmu_access_Type priv, uint32_t afe) { uint32_t ap = 0; if (afe == 0) { //full access if ((priv == NO_ACCESS) && (user == NO_ACCESS)) { ap = 0x0; } else if ((priv == RW) && (user == NO_ACCESS)) { ap = 0x1; } else if ((priv == RW) && (user == READ)) { ap = 0x2; } else if ((priv == RW) && (user == RW)) { ap = 0x3; } else if ((priv == READ) && (user == NO_ACCESS)) { ap = 0x5; } else if ((priv == READ) && (user == READ)) { ap = 0x6; } } else { //Simplified access if ((priv == RW) && (user == NO_ACCESS)) { ap = 0x1; } else if ((priv == RW) && (user == RW)) { ap = 0x3; } else if ((priv == READ) && (user == NO_ACCESS)) { ap = 0x5; } else if ((priv == READ) && (user == READ)) { ap = 0x7; } } *descriptor_l2 &= PAGE_AP_MASK; *descriptor_l2 |= (ap & 0x3) << PAGE_AP_SHIFT; *descriptor_l2 |= ((ap & 0x4)>>2) << PAGE_AP2_SHIFT; return 0; } /** \brief Set 4k/64k page shareability The function sets 4k/64k page shareability \param [out] descriptor_l2 L2 descriptor. \param [in] s_bit 4k/64k page shareability: NON_SHARED, SHARED \return 0 */ __STATIC_INLINE int __shared_page(uint32_t *descriptor_l2, mmu_shared_Type s_bit) { *descriptor_l2 &= PAGE_S_MASK; *descriptor_l2 |= ((s_bit & 0x1) << PAGE_S_SHIFT); return 0; } /** \brief Set 4k/64k page Global attribute The function sets 4k/64k page Global attribute \param [out] descriptor_l2 L2 descriptor. \param [in] g_bit 4k/64k page attribute: GLOBAL, NON_GLOBAL \return 0 */ __STATIC_INLINE int __global_page(uint32_t *descriptor_l2, mmu_global_Type g_bit) { *descriptor_l2 &= PAGE_NG_MASK; *descriptor_l2 |= ((g_bit & 0x1) << PAGE_NG_SHIFT); return 0; } /** \brief Set 4k/64k page Security attribute The function sets 4k/64k page Global attribute \param [out] descriptor_l1 L1 descriptor. \param [in] s_bit 4k/64k page Security attribute: SECURE, NON_SECURE \return 0 */ __STATIC_INLINE int __secure_page(uint32_t *descriptor_l1, mmu_secure_Type s_bit) { *descriptor_l1 &= PAGE_NS_MASK; *descriptor_l1 |= ((s_bit & 0x1) << PAGE_NS_SHIFT); return 0; } /** \brief Set Section memory attributes The function sets section memory attributes \param [out] descriptor_l1 L1 descriptor. \param [in] mem Section memory type: NORMAL, DEVICE, SHARED_DEVICE, NON_SHARED_DEVICE, STRONGLY_ORDERED \param [in] outer Outer cacheability: NON_CACHEABLE, WB_WA, WT, WB_NO_WA, \param [in] inner Inner cacheability: NON_CACHEABLE, WB_WA, WT, WB_NO_WA, \return 0 */ __STATIC_INLINE int __memory_section(uint32_t *descriptor_l1, mmu_memory_Type mem, mmu_cacheability_Type outer, mmu_cacheability_Type inner) { *descriptor_l1 &= SECTION_TEXCB_MASK; if (STRONGLY_ORDERED == mem) { return 0; } else if (SHARED_DEVICE == mem) { *descriptor_l1 |= (1 << SECTION_B_SHIFT); } else if (NON_SHARED_DEVICE == mem) { *descriptor_l1 |= (1 << SECTION_TEX1_SHIFT); } else if (NORMAL == mem) { *descriptor_l1 |= 1 << SECTION_TEX2_SHIFT; switch(inner) { case NON_CACHEABLE: break; case WB_WA: *descriptor_l1 |= (1 << SECTION_B_SHIFT); break; case WT: *descriptor_l1 |= 1 << SECTION_C_SHIFT; break; case WB_NO_WA: *descriptor_l1 |= (1 << SECTION_B_SHIFT) | (1 << SECTION_C_SHIFT); break; } switch(outer) { case NON_CACHEABLE: break; case WB_WA: *descriptor_l1 |= (1 << SECTION_TEX0_SHIFT); break; case WT: *descriptor_l1 |= 1 << SECTION_TEX1_SHIFT; break; case WB_NO_WA: *descriptor_l1 |= (1 << SECTION_TEX0_SHIFT) | (1 << SECTION_TEX0_SHIFT); break; } } return 0; } /** \brief Set 4k/64k page memory attributes The function sets 4k/64k page memory attributes \param [out] descriptor_l2 L2 descriptor. \param [in] mem 4k/64k page memory type: NORMAL, DEVICE, SHARED_DEVICE, NON_SHARED_DEVICE, STRONGLY_ORDERED \param [in] outer Outer cacheability: NON_CACHEABLE, WB_WA, WT, WB_NO_WA, \param [in] inner Inner cacheability: NON_CACHEABLE, WB_WA, WT, WB_NO_WA, \return 0 */ __STATIC_INLINE int __memory_page(uint32_t *descriptor_l2, mmu_memory_Type mem, mmu_cacheability_Type outer, mmu_cacheability_Type inner, mmu_region_size_Type page) { *descriptor_l2 &= PAGE_4K_TEXCB_MASK; if (page == PAGE_64k) { //same as section __memory_section(descriptor_l2, mem, outer, inner); } else { if (STRONGLY_ORDERED == mem) { return 0; } else if (SHARED_DEVICE == mem) { *descriptor_l2 |= (1 << PAGE_4K_B_SHIFT); } else if (NON_SHARED_DEVICE == mem) { *descriptor_l2 |= (1 << PAGE_4K_TEX1_SHIFT); } else if (NORMAL == mem) { *descriptor_l2 |= 1 << PAGE_4K_TEX2_SHIFT; switch(inner) { case NON_CACHEABLE: break; case WB_WA: *descriptor_l2 |= (1 << PAGE_4K_B_SHIFT); break; case WT: *descriptor_l2 |= 1 << PAGE_4K_C_SHIFT; break; case WB_NO_WA: *descriptor_l2 |= (1 << PAGE_4K_B_SHIFT) | (1 << PAGE_4K_C_SHIFT); break; } switch(outer) { case NON_CACHEABLE: break; case WB_WA: *descriptor_l2 |= (1 << PAGE_4K_TEX0_SHIFT); break; case WT: *descriptor_l2 |= 1 << PAGE_4K_TEX1_SHIFT; break; case WB_NO_WA: *descriptor_l2 |= (1 << PAGE_4K_TEX0_SHIFT) | (1 << PAGE_4K_TEX0_SHIFT); break; } } } return 0; } /** \brief Create a L1 section descriptor The function creates a section descriptor. Assumptions: - 16MB super sections not supported - TEX remap disabled, so memory type and attributes are described directly by bits in the descriptor - Functions always return 0 \param [out] descriptor L1 descriptor \param [out] descriptor2 L2 descriptor \param [in] reg Section attributes \return 0 */ __STATIC_INLINE int __get_section_descriptor(uint32_t *descriptor, mmu_region_attributes_Type reg) { *descriptor = 0; __memory_section(descriptor, reg.mem_t, reg.outer_norm_t, reg.inner_norm_t); __xn_section(descriptor,reg.xn_t); __domain_section(descriptor, reg.domain); __p_section(descriptor, reg.e_t); __ap_section(descriptor, reg.priv_t, reg.user_t, 1); __shared_section(descriptor,reg.sh_t); __global_section(descriptor,reg.g_t); __secure_section(descriptor,reg.sec_t); *descriptor &= SECTION_MASK; *descriptor |= SECTION_DESCRIPTOR; return 0; } /** \brief Create a L1 and L2 4k/64k page descriptor The function creates a 4k/64k page descriptor. Assumptions: - TEX remap disabled, so memory type and attributes are described directly by bits in the descriptor - Functions always return 0 \param [out] descriptor L1 descriptor \param [out] descriptor2 L2 descriptor \param [in] reg 4k/64k page attributes \return 0 */ __STATIC_INLINE int __get_page_descriptor(uint32_t *descriptor, uint32_t *descriptor2, mmu_region_attributes_Type reg) { *descriptor = 0; *descriptor2 = 0; switch (reg.rg_t) { case PAGE_4k: __memory_page(descriptor2, reg.mem_t, reg.outer_norm_t, reg.inner_norm_t, PAGE_4k); __xn_page(descriptor2, reg.xn_t, PAGE_4k); __domain_page(descriptor, reg.domain); __p_page(descriptor, reg.e_t); __ap_page(descriptor2, reg.priv_t, reg.user_t, 1); __shared_page(descriptor2,reg.sh_t); __global_page(descriptor2,reg.g_t); __secure_page(descriptor,reg.sec_t); *descriptor &= PAGE_L1_MASK; *descriptor |= PAGE_L1_DESCRIPTOR; *descriptor2 &= PAGE_L2_4K_MASK; *descriptor2 |= PAGE_L2_4K_DESC; break; case PAGE_64k: __memory_page(descriptor2, reg.mem_t, reg.outer_norm_t, reg.inner_norm_t, PAGE_64k); __xn_page(descriptor2, reg.xn_t, PAGE_64k); __domain_page(descriptor, reg.domain); __p_page(descriptor, reg.e_t); __ap_page(descriptor2, reg.priv_t, reg.user_t, 1); __shared_page(descriptor2,reg.sh_t); __global_page(descriptor2,reg.g_t); __secure_page(descriptor,reg.sec_t); *descriptor &= PAGE_L1_MASK; *descriptor |= PAGE_L1_DESCRIPTOR; *descriptor2 &= PAGE_L2_64K_MASK; *descriptor2 |= PAGE_L2_64K_DESC; break; case SECTION: //error break; } return 0; } /** \brief Create a 1MB Section \param [in] ttb Translation table base address \param [in] base_address Section base address \param [in] count Number of sections to create \param [in] descriptor_l1 L1 descriptor (region attributes) */ __STATIC_INLINE void __TTSection(uint32_t *ttb, uint32_t base_address, uint32_t count, uint32_t descriptor_l1) { uint32_t offset; uint32_t entry; uint32_t i; offset = base_address >> 20; entry = (base_address & 0xFFF00000) | descriptor_l1; //4 bytes aligned ttb = ttb + offset; for (i = 0; i < count; i++ ) { //4 bytes aligned *ttb++ = entry; entry += OFFSET_1M; } } /** \brief Create a 4k page entry \param [in] ttb L1 table base address \param [in] base_address 4k base address \param [in] count Number of 4k pages to create \param [in] descriptor_l1 L1 descriptor (region attributes) \param [in] ttb_l2 L2 table base address \param [in] descriptor_l2 L2 descriptor (region attributes) */ __STATIC_INLINE void __TTPage_4k(uint32_t *ttb, uint32_t base_address, uint32_t count, uint32_t descriptor_l1, uint32_t *ttb_l2, uint32_t descriptor_l2 ) { uint32_t offset, offset2; uint32_t entry, entry2; uint32_t i; offset = base_address >> 20; entry = ((int)ttb_l2 & 0xFFFFFC00) | descriptor_l1; //4 bytes aligned ttb += offset; //create l1_entry *ttb = entry; offset2 = (base_address & 0xff000) >> 12; ttb_l2 += offset2; entry2 = (base_address & 0xFFFFF000) | descriptor_l2; for (i = 0; i < count; i++ ) { //4 bytes aligned *ttb_l2++ = entry2; entry2 += OFFSET_4K; } } /** \brief Create a 64k page entry \param [in] ttb L1 table base address \param [in] base_address 64k base address \param [in] count Number of 64k pages to create \param [in] descriptor_l1 L1 descriptor (region attributes) \param [in] ttb_l2 L2 table base address \param [in] descriptor_l2 L2 descriptor (region attributes) */ __STATIC_INLINE void __TTPage_64k(uint32_t *ttb, uint32_t base_address, uint32_t count, uint32_t descriptor_l1, uint32_t *ttb_l2, uint32_t descriptor_l2 ) { uint32_t offset, offset2; uint32_t entry, entry2; uint32_t i,j; offset = base_address >> 20; entry = ((int)ttb_l2 & 0xFFFFFC00) | descriptor_l1; //4 bytes aligned ttb += offset; //create l1_entry *ttb = entry; offset2 = (base_address & 0xff000) >> 12; ttb_l2 += offset2; entry2 = (base_address & 0xFFFF0000) | descriptor_l2; for (i = 0; i < count; i++ ) { //create 16 entries for (j = 0; j < 16; j++) //4 bytes aligned *ttb_l2++ = entry2; entry2 += OFFSET_64K; } } /*@} end of MMU_Functions */ #endif #ifdef __cplusplus } #endif ================================================ FILE: Zelig/mbed/TARGET_NUCLEO_L152RE/core_cm0.h ================================================ /**************************************************************************//** * @file core_cm0.h * @brief CMSIS Cortex-M0 Core Peripheral Access Layer Header File * @version V3.20 * @date 25. February 2013 * * @note * ******************************************************************************/ /* Copyright (c) 2009 - 2013 ARM LIMITED All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: - Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. - Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. - Neither the name of ARM 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 COPYRIGHT HOLDERS AND 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. ---------------------------------------------------------------------------*/ #if defined ( __ICCARM__ ) #pragma system_include /* treat file as system include file for MISRA check */ #endif #ifdef __cplusplus extern "C" { #endif #ifndef __CORE_CM0_H_GENERIC #define __CORE_CM0_H_GENERIC /** \page CMSIS_MISRA_Exceptions MISRA-C:2004 Compliance Exceptions CMSIS violates the following MISRA-C:2004 rules: \li Required Rule 8.5, object/function definition in header file.
Function definitions in header files are used to allow 'inlining'. \li Required Rule 18.4, declaration of union type or object of union type: '{...}'.
Unions are used for effective representation of core registers. \li Advisory Rule 19.7, Function-like macro defined.
Function-like macros are used to allow more efficient code. */ /******************************************************************************* * CMSIS definitions ******************************************************************************/ /** \ingroup Cortex_M0 @{ */ /* CMSIS CM0 definitions */ #define __CM0_CMSIS_VERSION_MAIN (0x03) /*!< [31:16] CMSIS HAL main version */ #define __CM0_CMSIS_VERSION_SUB (0x20) /*!< [15:0] CMSIS HAL sub version */ #define __CM0_CMSIS_VERSION ((__CM0_CMSIS_VERSION_MAIN << 16) | \ __CM0_CMSIS_VERSION_SUB ) /*!< CMSIS HAL version number */ #define __CORTEX_M (0x00) /*!< Cortex-M Core */ #if defined ( __CC_ARM ) #define __ASM __asm /*!< asm keyword for ARM Compiler */ #define __INLINE __inline /*!< inline keyword for ARM Compiler */ #define __STATIC_INLINE static __inline #elif defined ( __ICCARM__ ) #define __ASM __asm /*!< asm keyword for IAR Compiler */ #define __INLINE inline /*!< inline keyword for IAR Compiler. Only available in High optimization mode! */ #define __STATIC_INLINE static inline #elif defined ( __GNUC__ ) #define __ASM __asm /*!< asm keyword for GNU Compiler */ #define __INLINE inline /*!< inline keyword for GNU Compiler */ #define __STATIC_INLINE static inline #elif defined ( __TASKING__ ) #define __ASM __asm /*!< asm keyword for TASKING Compiler */ #define __INLINE inline /*!< inline keyword for TASKING Compiler */ #define __STATIC_INLINE static inline #endif /** __FPU_USED indicates whether an FPU is used or not. This core does not support an FPU at all */ #define __FPU_USED 0 #if defined ( __CC_ARM ) #if defined __TARGET_FPU_VFP #warning "Compiler generates FPU instructions for a device without an FPU (check __FPU_PRESENT)" #endif #elif defined ( __ICCARM__ ) #if defined __ARMVFP__ #warning "Compiler generates FPU instructions for a device without an FPU (check __FPU_PRESENT)" #endif #elif defined ( __GNUC__ ) #if defined (__VFP_FP__) && !defined(__SOFTFP__) #warning "Compiler generates FPU instructions for a device without an FPU (check __FPU_PRESENT)" #endif #elif defined ( __TASKING__ ) #if defined __FPU_VFP__ #error "Compiler generates FPU instructions for a device without an FPU (check __FPU_PRESENT)" #endif #endif #include /* standard types definitions */ #include /* Core Instruction Access */ #include /* Core Function Access */ #endif /* __CORE_CM0_H_GENERIC */ #ifndef __CMSIS_GENERIC #ifndef __CORE_CM0_H_DEPENDANT #define __CORE_CM0_H_DEPENDANT /* check device defines and use defaults */ #if defined __CHECK_DEVICE_DEFINES #ifndef __CM0_REV #define __CM0_REV 0x0000 #warning "__CM0_REV not defined in device header file; using default!" #endif #ifndef __NVIC_PRIO_BITS #define __NVIC_PRIO_BITS 2 #warning "__NVIC_PRIO_BITS not defined in device header file; using default!" #endif #ifndef __Vendor_SysTickConfig #define __Vendor_SysTickConfig 0 #warning "__Vendor_SysTickConfig not defined in device header file; using default!" #endif #endif /* IO definitions (access restrictions to peripheral registers) */ /** \defgroup CMSIS_glob_defs CMSIS Global Defines IO Type Qualifiers are used \li to specify the access to peripheral variables. \li for automatic generation of peripheral register debug information. */ #ifdef __cplusplus #define __I volatile /*!< Defines 'read only' permissions */ #else #define __I volatile const /*!< Defines 'read only' permissions */ #endif #define __O volatile /*!< Defines 'write only' permissions */ #define __IO volatile /*!< Defines 'read / write' permissions */ /*@} end of group Cortex_M0 */ /******************************************************************************* * Register Abstraction Core Register contain: - Core Register - Core NVIC Register - Core SCB Register - Core SysTick Register ******************************************************************************/ /** \defgroup CMSIS_core_register Defines and Type Definitions \brief Type definitions and defines for Cortex-M processor based devices. */ /** \ingroup CMSIS_core_register \defgroup CMSIS_CORE Status and Control Registers \brief Core Register type definitions. @{ */ /** \brief Union type to access the Application Program Status Register (APSR). */ typedef union { struct { #if (__CORTEX_M != 0x04) uint32_t _reserved0:27; /*!< bit: 0..26 Reserved */ #else uint32_t _reserved0:16; /*!< bit: 0..15 Reserved */ uint32_t GE:4; /*!< bit: 16..19 Greater than or Equal flags */ uint32_t _reserved1:7; /*!< bit: 20..26 Reserved */ #endif uint32_t Q:1; /*!< bit: 27 Saturation condition flag */ uint32_t V:1; /*!< bit: 28 Overflow condition code flag */ uint32_t C:1; /*!< bit: 29 Carry condition code flag */ uint32_t Z:1; /*!< bit: 30 Zero condition code flag */ uint32_t N:1; /*!< bit: 31 Negative condition code flag */ } b; /*!< Structure used for bit access */ uint32_t w; /*!< Type used for word access */ } APSR_Type; /** \brief Union type to access the Interrupt Program Status Register (IPSR). */ typedef union { struct { uint32_t ISR:9; /*!< bit: 0.. 8 Exception number */ uint32_t _reserved0:23; /*!< bit: 9..31 Reserved */ } b; /*!< Structure used for bit access */ uint32_t w; /*!< Type used for word access */ } IPSR_Type; /** \brief Union type to access the Special-Purpose Program Status Registers (xPSR). */ typedef union { struct { uint32_t ISR:9; /*!< bit: 0.. 8 Exception number */ #if (__CORTEX_M != 0x04) uint32_t _reserved0:15; /*!< bit: 9..23 Reserved */ #else uint32_t _reserved0:7; /*!< bit: 9..15 Reserved */ uint32_t GE:4; /*!< bit: 16..19 Greater than or Equal flags */ uint32_t _reserved1:4; /*!< bit: 20..23 Reserved */ #endif uint32_t T:1; /*!< bit: 24 Thumb bit (read 0) */ uint32_t IT:2; /*!< bit: 25..26 saved IT state (read 0) */ uint32_t Q:1; /*!< bit: 27 Saturation condition flag */ uint32_t V:1; /*!< bit: 28 Overflow condition code flag */ uint32_t C:1; /*!< bit: 29 Carry condition code flag */ uint32_t Z:1; /*!< bit: 30 Zero condition code flag */ uint32_t N:1; /*!< bit: 31 Negative condition code flag */ } b; /*!< Structure used for bit access */ uint32_t w; /*!< Type used for word access */ } xPSR_Type; /** \brief Union type to access the Control Registers (CONTROL). */ typedef union { struct { uint32_t nPRIV:1; /*!< bit: 0 Execution privilege in Thread mode */ uint32_t SPSEL:1; /*!< bit: 1 Stack to be used */ uint32_t FPCA:1; /*!< bit: 2 FP extension active flag */ uint32_t _reserved0:29; /*!< bit: 3..31 Reserved */ } b; /*!< Structure used for bit access */ uint32_t w; /*!< Type used for word access */ } CONTROL_Type; /*@} end of group CMSIS_CORE */ /** \ingroup CMSIS_core_register \defgroup CMSIS_NVIC Nested Vectored Interrupt Controller (NVIC) \brief Type definitions for the NVIC Registers @{ */ /** \brief Structure type to access the Nested Vectored Interrupt Controller (NVIC). */ typedef struct { __IO uint32_t ISER[1]; /*!< Offset: 0x000 (R/W) Interrupt Set Enable Register */ uint32_t RESERVED0[31]; __IO uint32_t ICER[1]; /*!< Offset: 0x080 (R/W) Interrupt Clear Enable Register */ uint32_t RSERVED1[31]; __IO uint32_t ISPR[1]; /*!< Offset: 0x100 (R/W) Interrupt Set Pending Register */ uint32_t RESERVED2[31]; __IO uint32_t ICPR[1]; /*!< Offset: 0x180 (R/W) Interrupt Clear Pending Register */ uint32_t RESERVED3[31]; uint32_t RESERVED4[64]; __IO uint32_t IP[8]; /*!< Offset: 0x300 (R/W) Interrupt Priority Register */ } NVIC_Type; /*@} end of group CMSIS_NVIC */ /** \ingroup CMSIS_core_register \defgroup CMSIS_SCB System Control Block (SCB) \brief Type definitions for the System Control Block Registers @{ */ /** \brief Structure type to access the System Control Block (SCB). */ typedef struct { __I uint32_t CPUID; /*!< Offset: 0x000 (R/ ) CPUID Base Register */ __IO uint32_t ICSR; /*!< Offset: 0x004 (R/W) Interrupt Control and State Register */ uint32_t RESERVED0; __IO uint32_t AIRCR; /*!< Offset: 0x00C (R/W) Application Interrupt and Reset Control Register */ __IO uint32_t SCR; /*!< Offset: 0x010 (R/W) System Control Register */ __IO uint32_t CCR; /*!< Offset: 0x014 (R/W) Configuration Control Register */ uint32_t RESERVED1; __IO uint32_t SHP[2]; /*!< Offset: 0x01C (R/W) System Handlers Priority Registers. [0] is RESERVED */ __IO uint32_t SHCSR; /*!< Offset: 0x024 (R/W) System Handler Control and State Register */ } SCB_Type; /* SCB CPUID Register Definitions */ #define SCB_CPUID_IMPLEMENTER_Pos 24 /*!< SCB CPUID: IMPLEMENTER Position */ #define SCB_CPUID_IMPLEMENTER_Msk (0xFFUL << SCB_CPUID_IMPLEMENTER_Pos) /*!< SCB CPUID: IMPLEMENTER Mask */ #define SCB_CPUID_VARIANT_Pos 20 /*!< SCB CPUID: VARIANT Position */ #define SCB_CPUID_VARIANT_Msk (0xFUL << SCB_CPUID_VARIANT_Pos) /*!< SCB CPUID: VARIANT Mask */ #define SCB_CPUID_ARCHITECTURE_Pos 16 /*!< SCB CPUID: ARCHITECTURE Position */ #define SCB_CPUID_ARCHITECTURE_Msk (0xFUL << SCB_CPUID_ARCHITECTURE_Pos) /*!< SCB CPUID: ARCHITECTURE Mask */ #define SCB_CPUID_PARTNO_Pos 4 /*!< SCB CPUID: PARTNO Position */ #define SCB_CPUID_PARTNO_Msk (0xFFFUL << SCB_CPUID_PARTNO_Pos) /*!< SCB CPUID: PARTNO Mask */ #define SCB_CPUID_REVISION_Pos 0 /*!< SCB CPUID: REVISION Position */ #define SCB_CPUID_REVISION_Msk (0xFUL << SCB_CPUID_REVISION_Pos) /*!< SCB CPUID: REVISION Mask */ /* SCB Interrupt Control State Register Definitions */ #define SCB_ICSR_NMIPENDSET_Pos 31 /*!< SCB ICSR: NMIPENDSET Position */ #define SCB_ICSR_NMIPENDSET_Msk (1UL << SCB_ICSR_NMIPENDSET_Pos) /*!< SCB ICSR: NMIPENDSET Mask */ #define SCB_ICSR_PENDSVSET_Pos 28 /*!< SCB ICSR: PENDSVSET Position */ #define SCB_ICSR_PENDSVSET_Msk (1UL << SCB_ICSR_PENDSVSET_Pos) /*!< SCB ICSR: PENDSVSET Mask */ #define SCB_ICSR_PENDSVCLR_Pos 27 /*!< SCB ICSR: PENDSVCLR Position */ #define SCB_ICSR_PENDSVCLR_Msk (1UL << SCB_ICSR_PENDSVCLR_Pos) /*!< SCB ICSR: PENDSVCLR Mask */ #define SCB_ICSR_PENDSTSET_Pos 26 /*!< SCB ICSR: PENDSTSET Position */ #define SCB_ICSR_PENDSTSET_Msk (1UL << SCB_ICSR_PENDSTSET_Pos) /*!< SCB ICSR: PENDSTSET Mask */ #define SCB_ICSR_PENDSTCLR_Pos 25 /*!< SCB ICSR: PENDSTCLR Position */ #define SCB_ICSR_PENDSTCLR_Msk (1UL << SCB_ICSR_PENDSTCLR_Pos) /*!< SCB ICSR: PENDSTCLR Mask */ #define SCB_ICSR_ISRPREEMPT_Pos 23 /*!< SCB ICSR: ISRPREEMPT Position */ #define SCB_ICSR_ISRPREEMPT_Msk (1UL << SCB_ICSR_ISRPREEMPT_Pos) /*!< SCB ICSR: ISRPREEMPT Mask */ #define SCB_ICSR_ISRPENDING_Pos 22 /*!< SCB ICSR: ISRPENDING Position */ #define SCB_ICSR_ISRPENDING_Msk (1UL << SCB_ICSR_ISRPENDING_Pos) /*!< SCB ICSR: ISRPENDING Mask */ #define SCB_ICSR_VECTPENDING_Pos 12 /*!< SCB ICSR: VECTPENDING Position */ #define SCB_ICSR_VECTPENDING_Msk (0x1FFUL << SCB_ICSR_VECTPENDING_Pos) /*!< SCB ICSR: VECTPENDING Mask */ #define SCB_ICSR_VECTACTIVE_Pos 0 /*!< SCB ICSR: VECTACTIVE Position */ #define SCB_ICSR_VECTACTIVE_Msk (0x1FFUL << SCB_ICSR_VECTACTIVE_Pos) /*!< SCB ICSR: VECTACTIVE Mask */ /* SCB Application Interrupt and Reset Control Register Definitions */ #define SCB_AIRCR_VECTKEY_Pos 16 /*!< SCB AIRCR: VECTKEY Position */ #define SCB_AIRCR_VECTKEY_Msk (0xFFFFUL << SCB_AIRCR_VECTKEY_Pos) /*!< SCB AIRCR: VECTKEY Mask */ #define SCB_AIRCR_VECTKEYSTAT_Pos 16 /*!< SCB AIRCR: VECTKEYSTAT Position */ #define SCB_AIRCR_VECTKEYSTAT_Msk (0xFFFFUL << SCB_AIRCR_VECTKEYSTAT_Pos) /*!< SCB AIRCR: VECTKEYSTAT Mask */ #define SCB_AIRCR_ENDIANESS_Pos 15 /*!< SCB AIRCR: ENDIANESS Position */ #define SCB_AIRCR_ENDIANESS_Msk (1UL << SCB_AIRCR_ENDIANESS_Pos) /*!< SCB AIRCR: ENDIANESS Mask */ #define SCB_AIRCR_SYSRESETREQ_Pos 2 /*!< SCB AIRCR: SYSRESETREQ Position */ #define SCB_AIRCR_SYSRESETREQ_Msk (1UL << SCB_AIRCR_SYSRESETREQ_Pos) /*!< SCB AIRCR: SYSRESETREQ Mask */ #define SCB_AIRCR_VECTCLRACTIVE_Pos 1 /*!< SCB AIRCR: VECTCLRACTIVE Position */ #define SCB_AIRCR_VECTCLRACTIVE_Msk (1UL << SCB_AIRCR_VECTCLRACTIVE_Pos) /*!< SCB AIRCR: VECTCLRACTIVE Mask */ /* SCB System Control Register Definitions */ #define SCB_SCR_SEVONPEND_Pos 4 /*!< SCB SCR: SEVONPEND Position */ #define SCB_SCR_SEVONPEND_Msk (1UL << SCB_SCR_SEVONPEND_Pos) /*!< SCB SCR: SEVONPEND Mask */ #define SCB_SCR_SLEEPDEEP_Pos 2 /*!< SCB SCR: SLEEPDEEP Position */ #define SCB_SCR_SLEEPDEEP_Msk (1UL << SCB_SCR_SLEEPDEEP_Pos) /*!< SCB SCR: SLEEPDEEP Mask */ #define SCB_SCR_SLEEPONEXIT_Pos 1 /*!< SCB SCR: SLEEPONEXIT Position */ #define SCB_SCR_SLEEPONEXIT_Msk (1UL << SCB_SCR_SLEEPONEXIT_Pos) /*!< SCB SCR: SLEEPONEXIT Mask */ /* SCB Configuration Control Register Definitions */ #define SCB_CCR_STKALIGN_Pos 9 /*!< SCB CCR: STKALIGN Position */ #define SCB_CCR_STKALIGN_Msk (1UL << SCB_CCR_STKALIGN_Pos) /*!< SCB CCR: STKALIGN Mask */ #define SCB_CCR_UNALIGN_TRP_Pos 3 /*!< SCB CCR: UNALIGN_TRP Position */ #define SCB_CCR_UNALIGN_TRP_Msk (1UL << SCB_CCR_UNALIGN_TRP_Pos) /*!< SCB CCR: UNALIGN_TRP Mask */ /* SCB System Handler Control and State Register Definitions */ #define SCB_SHCSR_SVCALLPENDED_Pos 15 /*!< SCB SHCSR: SVCALLPENDED Position */ #define SCB_SHCSR_SVCALLPENDED_Msk (1UL << SCB_SHCSR_SVCALLPENDED_Pos) /*!< SCB SHCSR: SVCALLPENDED Mask */ /*@} end of group CMSIS_SCB */ /** \ingroup CMSIS_core_register \defgroup CMSIS_SysTick System Tick Timer (SysTick) \brief Type definitions for the System Timer Registers. @{ */ /** \brief Structure type to access the System Timer (SysTick). */ typedef struct { __IO uint32_t CTRL; /*!< Offset: 0x000 (R/W) SysTick Control and Status Register */ __IO uint32_t LOAD; /*!< Offset: 0x004 (R/W) SysTick Reload Value Register */ __IO uint32_t VAL; /*!< Offset: 0x008 (R/W) SysTick Current Value Register */ __I uint32_t CALIB; /*!< Offset: 0x00C (R/ ) SysTick Calibration Register */ } SysTick_Type; /* SysTick Control / Status Register Definitions */ #define SysTick_CTRL_COUNTFLAG_Pos 16 /*!< SysTick CTRL: COUNTFLAG Position */ #define SysTick_CTRL_COUNTFLAG_Msk (1UL << SysTick_CTRL_COUNTFLAG_Pos) /*!< SysTick CTRL: COUNTFLAG Mask */ #define SysTick_CTRL_CLKSOURCE_Pos 2 /*!< SysTick CTRL: CLKSOURCE Position */ #define SysTick_CTRL_CLKSOURCE_Msk (1UL << SysTick_CTRL_CLKSOURCE_Pos) /*!< SysTick CTRL: CLKSOURCE Mask */ #define SysTick_CTRL_TICKINT_Pos 1 /*!< SysTick CTRL: TICKINT Position */ #define SysTick_CTRL_TICKINT_Msk (1UL << SysTick_CTRL_TICKINT_Pos) /*!< SysTick CTRL: TICKINT Mask */ #define SysTick_CTRL_ENABLE_Pos 0 /*!< SysTick CTRL: ENABLE Position */ #define SysTick_CTRL_ENABLE_Msk (1UL << SysTick_CTRL_ENABLE_Pos) /*!< SysTick CTRL: ENABLE Mask */ /* SysTick Reload Register Definitions */ #define SysTick_LOAD_RELOAD_Pos 0 /*!< SysTick LOAD: RELOAD Position */ #define SysTick_LOAD_RELOAD_Msk (0xFFFFFFUL << SysTick_LOAD_RELOAD_Pos) /*!< SysTick LOAD: RELOAD Mask */ /* SysTick Current Register Definitions */ #define SysTick_VAL_CURRENT_Pos 0 /*!< SysTick VAL: CURRENT Position */ #define SysTick_VAL_CURRENT_Msk (0xFFFFFFUL << SysTick_VAL_CURRENT_Pos) /*!< SysTick VAL: CURRENT Mask */ /* SysTick Calibration Register Definitions */ #define SysTick_CALIB_NOREF_Pos 31 /*!< SysTick CALIB: NOREF Position */ #define SysTick_CALIB_NOREF_Msk (1UL << SysTick_CALIB_NOREF_Pos) /*!< SysTick CALIB: NOREF Mask */ #define SysTick_CALIB_SKEW_Pos 30 /*!< SysTick CALIB: SKEW Position */ #define SysTick_CALIB_SKEW_Msk (1UL << SysTick_CALIB_SKEW_Pos) /*!< SysTick CALIB: SKEW Mask */ #define SysTick_CALIB_TENMS_Pos 0 /*!< SysTick CALIB: TENMS Position */ #define SysTick_CALIB_TENMS_Msk (0xFFFFFFUL << SysTick_VAL_CURRENT_Pos) /*!< SysTick CALIB: TENMS Mask */ /*@} end of group CMSIS_SysTick */ /** \ingroup CMSIS_core_register \defgroup CMSIS_CoreDebug Core Debug Registers (CoreDebug) \brief Cortex-M0 Core Debug Registers (DCB registers, SHCSR, and DFSR) are only accessible over DAP and not via processor. Therefore they are not covered by the Cortex-M0 header file. @{ */ /*@} end of group CMSIS_CoreDebug */ /** \ingroup CMSIS_core_register \defgroup CMSIS_core_base Core Definitions \brief Definitions for base addresses, unions, and structures. @{ */ /* Memory mapping of Cortex-M0 Hardware */ #define SCS_BASE (0xE000E000UL) /*!< System Control Space Base Address */ #define SysTick_BASE (SCS_BASE + 0x0010UL) /*!< SysTick Base Address */ #define NVIC_BASE (SCS_BASE + 0x0100UL) /*!< NVIC Base Address */ #define SCB_BASE (SCS_BASE + 0x0D00UL) /*!< System Control Block Base Address */ #define SCB ((SCB_Type *) SCB_BASE ) /*!< SCB configuration struct */ #define SysTick ((SysTick_Type *) SysTick_BASE ) /*!< SysTick configuration struct */ #define NVIC ((NVIC_Type *) NVIC_BASE ) /*!< NVIC configuration struct */ /*@} */ /******************************************************************************* * Hardware Abstraction Layer Core Function Interface contains: - Core NVIC Functions - Core SysTick Functions - Core Register Access Functions ******************************************************************************/ /** \defgroup CMSIS_Core_FunctionInterface Functions and Instructions Reference */ /* ########################## NVIC functions #################################### */ /** \ingroup CMSIS_Core_FunctionInterface \defgroup CMSIS_Core_NVICFunctions NVIC Functions \brief Functions that manage interrupts and exceptions via the NVIC. @{ */ /* Interrupt Priorities are WORD accessible only under ARMv6M */ /* The following MACROS handle generation of the register offset and byte masks */ #define _BIT_SHIFT(IRQn) ( (((uint32_t)(IRQn) ) & 0x03) * 8 ) #define _SHP_IDX(IRQn) ( ((((uint32_t)(IRQn) & 0x0F)-8) >> 2) ) #define _IP_IDX(IRQn) ( ((uint32_t)(IRQn) >> 2) ) /** \brief Enable External Interrupt The function enables a device-specific interrupt in the NVIC interrupt controller. \param [in] IRQn External interrupt number. Value cannot be negative. */ __STATIC_INLINE void NVIC_EnableIRQ(IRQn_Type IRQn) { NVIC->ISER[0] = (1 << ((uint32_t)(IRQn) & 0x1F)); } /** \brief Disable External Interrupt The function disables a device-specific interrupt in the NVIC interrupt controller. \param [in] IRQn External interrupt number. Value cannot be negative. */ __STATIC_INLINE void NVIC_DisableIRQ(IRQn_Type IRQn) { NVIC->ICER[0] = (1 << ((uint32_t)(IRQn) & 0x1F)); } /** \brief Get Pending Interrupt The function reads the pending register in the NVIC and returns the pending bit for the specified interrupt. \param [in] IRQn Interrupt number. \return 0 Interrupt status is not pending. \return 1 Interrupt status is pending. */ __STATIC_INLINE uint32_t NVIC_GetPendingIRQ(IRQn_Type IRQn) { return((uint32_t) ((NVIC->ISPR[0] & (1 << ((uint32_t)(IRQn) & 0x1F)))?1:0)); } /** \brief Set Pending Interrupt The function sets the pending bit of an external interrupt. \param [in] IRQn Interrupt number. Value cannot be negative. */ __STATIC_INLINE void NVIC_SetPendingIRQ(IRQn_Type IRQn) { NVIC->ISPR[0] = (1 << ((uint32_t)(IRQn) & 0x1F)); } /** \brief Clear Pending Interrupt The function clears the pending bit of an external interrupt. \param [in] IRQn External interrupt number. Value cannot be negative. */ __STATIC_INLINE void NVIC_ClearPendingIRQ(IRQn_Type IRQn) { NVIC->ICPR[0] = (1 << ((uint32_t)(IRQn) & 0x1F)); /* Clear pending interrupt */ } /** \brief Set Interrupt Priority The function sets the priority of an interrupt. \note The priority cannot be set for every core interrupt. \param [in] IRQn Interrupt number. \param [in] priority Priority to set. */ __STATIC_INLINE void NVIC_SetPriority(IRQn_Type IRQn, uint32_t priority) { if(IRQn < 0) { SCB->SHP[_SHP_IDX(IRQn)] = (SCB->SHP[_SHP_IDX(IRQn)] & ~(0xFF << _BIT_SHIFT(IRQn))) | (((priority << (8 - __NVIC_PRIO_BITS)) & 0xFF) << _BIT_SHIFT(IRQn)); } else { NVIC->IP[_IP_IDX(IRQn)] = (NVIC->IP[_IP_IDX(IRQn)] & ~(0xFF << _BIT_SHIFT(IRQn))) | (((priority << (8 - __NVIC_PRIO_BITS)) & 0xFF) << _BIT_SHIFT(IRQn)); } } /** \brief Get Interrupt Priority The function reads the priority of an interrupt. The interrupt number can be positive to specify an external (device specific) interrupt, or negative to specify an internal (core) interrupt. \param [in] IRQn Interrupt number. \return Interrupt Priority. Value is aligned automatically to the implemented priority bits of the microcontroller. */ __STATIC_INLINE uint32_t NVIC_GetPriority(IRQn_Type IRQn) { if(IRQn < 0) { return((uint32_t)(((SCB->SHP[_SHP_IDX(IRQn)] >> _BIT_SHIFT(IRQn) ) & 0xFF) >> (8 - __NVIC_PRIO_BITS))); } /* get priority for Cortex-M0 system interrupts */ else { return((uint32_t)(((NVIC->IP[ _IP_IDX(IRQn)] >> _BIT_SHIFT(IRQn) ) & 0xFF) >> (8 - __NVIC_PRIO_BITS))); } /* get priority for device specific interrupts */ } /** \brief System Reset The function initiates a system reset request to reset the MCU. */ __STATIC_INLINE void NVIC_SystemReset(void) { __DSB(); /* Ensure all outstanding memory accesses included buffered write are completed before reset */ SCB->AIRCR = ((0x5FA << SCB_AIRCR_VECTKEY_Pos) | SCB_AIRCR_SYSRESETREQ_Msk); __DSB(); /* Ensure completion of memory access */ while(1); /* wait until reset */ } /*@} end of CMSIS_Core_NVICFunctions */ /* ################################## SysTick function ############################################ */ /** \ingroup CMSIS_Core_FunctionInterface \defgroup CMSIS_Core_SysTickFunctions SysTick Functions \brief Functions that configure the System. @{ */ #if (__Vendor_SysTickConfig == 0) /** \brief System Tick Configuration The function initializes the System Timer and its interrupt, and starts the System Tick Timer. Counter is in free running mode to generate periodic interrupts. \param [in] ticks Number of ticks between two interrupts. \return 0 Function succeeded. \return 1 Function failed. \note When the variable __Vendor_SysTickConfig is set to 1, then the function SysTick_Config is not included. In this case, the file device.h must contain a vendor-specific implementation of this function. */ __STATIC_INLINE uint32_t SysTick_Config(uint32_t ticks) { if ((ticks - 1) > SysTick_LOAD_RELOAD_Msk) return (1); /* Reload value impossible */ SysTick->LOAD = ticks - 1; /* set reload register */ NVIC_SetPriority (SysTick_IRQn, (1<<__NVIC_PRIO_BITS) - 1); /* set Priority for Systick Interrupt */ SysTick->VAL = 0; /* Load the SysTick Counter Value */ SysTick->CTRL = SysTick_CTRL_CLKSOURCE_Msk | SysTick_CTRL_TICKINT_Msk | SysTick_CTRL_ENABLE_Msk; /* Enable SysTick IRQ and SysTick Timer */ return (0); /* Function successful */ } #endif /*@} end of CMSIS_Core_SysTickFunctions */ #endif /* __CORE_CM0_H_DEPENDANT */ #endif /* __CMSIS_GENERIC */ #ifdef __cplusplus } #endif ================================================ FILE: Zelig/mbed/TARGET_NUCLEO_L152RE/core_cm0plus.h ================================================ /**************************************************************************//** * @file core_cm0plus.h * @brief CMSIS Cortex-M0+ Core Peripheral Access Layer Header File * @version V3.20 * @date 25. February 2013 * * @note * ******************************************************************************/ /* Copyright (c) 2009 - 2013 ARM LIMITED All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: - Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. - Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. - Neither the name of ARM 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 COPYRIGHT HOLDERS AND 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. ---------------------------------------------------------------------------*/ #if defined ( __ICCARM__ ) #pragma system_include /* treat file as system include file for MISRA check */ #endif #ifdef __cplusplus extern "C" { #endif #ifndef __CORE_CM0PLUS_H_GENERIC #define __CORE_CM0PLUS_H_GENERIC /** \page CMSIS_MISRA_Exceptions MISRA-C:2004 Compliance Exceptions CMSIS violates the following MISRA-C:2004 rules: \li Required Rule 8.5, object/function definition in header file.
Function definitions in header files are used to allow 'inlining'. \li Required Rule 18.4, declaration of union type or object of union type: '{...}'.
Unions are used for effective representation of core registers. \li Advisory Rule 19.7, Function-like macro defined.
Function-like macros are used to allow more efficient code. */ /******************************************************************************* * CMSIS definitions ******************************************************************************/ /** \ingroup Cortex-M0+ @{ */ /* CMSIS CM0P definitions */ #define __CM0PLUS_CMSIS_VERSION_MAIN (0x03) /*!< [31:16] CMSIS HAL main version */ #define __CM0PLUS_CMSIS_VERSION_SUB (0x20) /*!< [15:0] CMSIS HAL sub version */ #define __CM0PLUS_CMSIS_VERSION ((__CM0PLUS_CMSIS_VERSION_MAIN << 16) | \ __CM0PLUS_CMSIS_VERSION_SUB) /*!< CMSIS HAL version number */ #define __CORTEX_M (0x00) /*!< Cortex-M Core */ #if defined ( __CC_ARM ) #define __ASM __asm /*!< asm keyword for ARM Compiler */ #define __INLINE __inline /*!< inline keyword for ARM Compiler */ #define __STATIC_INLINE static __inline #elif defined ( __ICCARM__ ) #define __ASM __asm /*!< asm keyword for IAR Compiler */ #define __INLINE inline /*!< inline keyword for IAR Compiler. Only available in High optimization mode! */ #define __STATIC_INLINE static inline #elif defined ( __GNUC__ ) #define __ASM __asm /*!< asm keyword for GNU Compiler */ #define __INLINE inline /*!< inline keyword for GNU Compiler */ #define __STATIC_INLINE static inline #elif defined ( __TASKING__ ) #define __ASM __asm /*!< asm keyword for TASKING Compiler */ #define __INLINE inline /*!< inline keyword for TASKING Compiler */ #define __STATIC_INLINE static inline #endif /** __FPU_USED indicates whether an FPU is used or not. This core does not support an FPU at all */ #define __FPU_USED 0 #if defined ( __CC_ARM ) #if defined __TARGET_FPU_VFP #warning "Compiler generates FPU instructions for a device without an FPU (check __FPU_PRESENT)" #endif #elif defined ( __ICCARM__ ) #if defined __ARMVFP__ #warning "Compiler generates FPU instructions for a device without an FPU (check __FPU_PRESENT)" #endif #elif defined ( __GNUC__ ) #if defined (__VFP_FP__) && !defined(__SOFTFP__) #warning "Compiler generates FPU instructions for a device without an FPU (check __FPU_PRESENT)" #endif #elif defined ( __TASKING__ ) #if defined __FPU_VFP__ #error "Compiler generates FPU instructions for a device without an FPU (check __FPU_PRESENT)" #endif #endif #include /* standard types definitions */ #include /* Core Instruction Access */ #include /* Core Function Access */ #endif /* __CORE_CM0PLUS_H_GENERIC */ #ifndef __CMSIS_GENERIC #ifndef __CORE_CM0PLUS_H_DEPENDANT #define __CORE_CM0PLUS_H_DEPENDANT /* check device defines and use defaults */ #if defined __CHECK_DEVICE_DEFINES #ifndef __CM0PLUS_REV #define __CM0PLUS_REV 0x0000 #warning "__CM0PLUS_REV not defined in device header file; using default!" #endif #ifndef __MPU_PRESENT #define __MPU_PRESENT 0 #warning "__MPU_PRESENT not defined in device header file; using default!" #endif #ifndef __VTOR_PRESENT #define __VTOR_PRESENT 0 #warning "__VTOR_PRESENT not defined in device header file; using default!" #endif #ifndef __NVIC_PRIO_BITS #define __NVIC_PRIO_BITS 2 #warning "__NVIC_PRIO_BITS not defined in device header file; using default!" #endif #ifndef __Vendor_SysTickConfig #define __Vendor_SysTickConfig 0 #warning "__Vendor_SysTickConfig not defined in device header file; using default!" #endif #endif /* IO definitions (access restrictions to peripheral registers) */ /** \defgroup CMSIS_glob_defs CMSIS Global Defines IO Type Qualifiers are used \li to specify the access to peripheral variables. \li for automatic generation of peripheral register debug information. */ #ifdef __cplusplus #define __I volatile /*!< Defines 'read only' permissions */ #else #define __I volatile const /*!< Defines 'read only' permissions */ #endif #define __O volatile /*!< Defines 'write only' permissions */ #define __IO volatile /*!< Defines 'read / write' permissions */ /*@} end of group Cortex-M0+ */ /******************************************************************************* * Register Abstraction Core Register contain: - Core Register - Core NVIC Register - Core SCB Register - Core SysTick Register - Core MPU Register ******************************************************************************/ /** \defgroup CMSIS_core_register Defines and Type Definitions \brief Type definitions and defines for Cortex-M processor based devices. */ /** \ingroup CMSIS_core_register \defgroup CMSIS_CORE Status and Control Registers \brief Core Register type definitions. @{ */ /** \brief Union type to access the Application Program Status Register (APSR). */ typedef union { struct { #if (__CORTEX_M != 0x04) uint32_t _reserved0:27; /*!< bit: 0..26 Reserved */ #else uint32_t _reserved0:16; /*!< bit: 0..15 Reserved */ uint32_t GE:4; /*!< bit: 16..19 Greater than or Equal flags */ uint32_t _reserved1:7; /*!< bit: 20..26 Reserved */ #endif uint32_t Q:1; /*!< bit: 27 Saturation condition flag */ uint32_t V:1; /*!< bit: 28 Overflow condition code flag */ uint32_t C:1; /*!< bit: 29 Carry condition code flag */ uint32_t Z:1; /*!< bit: 30 Zero condition code flag */ uint32_t N:1; /*!< bit: 31 Negative condition code flag */ } b; /*!< Structure used for bit access */ uint32_t w; /*!< Type used for word access */ } APSR_Type; /** \brief Union type to access the Interrupt Program Status Register (IPSR). */ typedef union { struct { uint32_t ISR:9; /*!< bit: 0.. 8 Exception number */ uint32_t _reserved0:23; /*!< bit: 9..31 Reserved */ } b; /*!< Structure used for bit access */ uint32_t w; /*!< Type used for word access */ } IPSR_Type; /** \brief Union type to access the Special-Purpose Program Status Registers (xPSR). */ typedef union { struct { uint32_t ISR:9; /*!< bit: 0.. 8 Exception number */ #if (__CORTEX_M != 0x04) uint32_t _reserved0:15; /*!< bit: 9..23 Reserved */ #else uint32_t _reserved0:7; /*!< bit: 9..15 Reserved */ uint32_t GE:4; /*!< bit: 16..19 Greater than or Equal flags */ uint32_t _reserved1:4; /*!< bit: 20..23 Reserved */ #endif uint32_t T:1; /*!< bit: 24 Thumb bit (read 0) */ uint32_t IT:2; /*!< bit: 25..26 saved IT state (read 0) */ uint32_t Q:1; /*!< bit: 27 Saturation condition flag */ uint32_t V:1; /*!< bit: 28 Overflow condition code flag */ uint32_t C:1; /*!< bit: 29 Carry condition code flag */ uint32_t Z:1; /*!< bit: 30 Zero condition code flag */ uint32_t N:1; /*!< bit: 31 Negative condition code flag */ } b; /*!< Structure used for bit access */ uint32_t w; /*!< Type used for word access */ } xPSR_Type; /** \brief Union type to access the Control Registers (CONTROL). */ typedef union { struct { uint32_t nPRIV:1; /*!< bit: 0 Execution privilege in Thread mode */ uint32_t SPSEL:1; /*!< bit: 1 Stack to be used */ uint32_t FPCA:1; /*!< bit: 2 FP extension active flag */ uint32_t _reserved0:29; /*!< bit: 3..31 Reserved */ } b; /*!< Structure used for bit access */ uint32_t w; /*!< Type used for word access */ } CONTROL_Type; /*@} end of group CMSIS_CORE */ /** \ingroup CMSIS_core_register \defgroup CMSIS_NVIC Nested Vectored Interrupt Controller (NVIC) \brief Type definitions for the NVIC Registers @{ */ /** \brief Structure type to access the Nested Vectored Interrupt Controller (NVIC). */ typedef struct { __IO uint32_t ISER[1]; /*!< Offset: 0x000 (R/W) Interrupt Set Enable Register */ uint32_t RESERVED0[31]; __IO uint32_t ICER[1]; /*!< Offset: 0x080 (R/W) Interrupt Clear Enable Register */ uint32_t RSERVED1[31]; __IO uint32_t ISPR[1]; /*!< Offset: 0x100 (R/W) Interrupt Set Pending Register */ uint32_t RESERVED2[31]; __IO uint32_t ICPR[1]; /*!< Offset: 0x180 (R/W) Interrupt Clear Pending Register */ uint32_t RESERVED3[31]; uint32_t RESERVED4[64]; __IO uint32_t IP[8]; /*!< Offset: 0x300 (R/W) Interrupt Priority Register */ } NVIC_Type; /*@} end of group CMSIS_NVIC */ /** \ingroup CMSIS_core_register \defgroup CMSIS_SCB System Control Block (SCB) \brief Type definitions for the System Control Block Registers @{ */ /** \brief Structure type to access the System Control Block (SCB). */ typedef struct { __I uint32_t CPUID; /*!< Offset: 0x000 (R/ ) CPUID Base Register */ __IO uint32_t ICSR; /*!< Offset: 0x004 (R/W) Interrupt Control and State Register */ #if (__VTOR_PRESENT == 1) __IO uint32_t VTOR; /*!< Offset: 0x008 (R/W) Vector Table Offset Register */ #else uint32_t RESERVED0; #endif __IO uint32_t AIRCR; /*!< Offset: 0x00C (R/W) Application Interrupt and Reset Control Register */ __IO uint32_t SCR; /*!< Offset: 0x010 (R/W) System Control Register */ __IO uint32_t CCR; /*!< Offset: 0x014 (R/W) Configuration Control Register */ uint32_t RESERVED1; __IO uint32_t SHP[2]; /*!< Offset: 0x01C (R/W) System Handlers Priority Registers. [0] is RESERVED */ __IO uint32_t SHCSR; /*!< Offset: 0x024 (R/W) System Handler Control and State Register */ } SCB_Type; /* SCB CPUID Register Definitions */ #define SCB_CPUID_IMPLEMENTER_Pos 24 /*!< SCB CPUID: IMPLEMENTER Position */ #define SCB_CPUID_IMPLEMENTER_Msk (0xFFUL << SCB_CPUID_IMPLEMENTER_Pos) /*!< SCB CPUID: IMPLEMENTER Mask */ #define SCB_CPUID_VARIANT_Pos 20 /*!< SCB CPUID: VARIANT Position */ #define SCB_CPUID_VARIANT_Msk (0xFUL << SCB_CPUID_VARIANT_Pos) /*!< SCB CPUID: VARIANT Mask */ #define SCB_CPUID_ARCHITECTURE_Pos 16 /*!< SCB CPUID: ARCHITECTURE Position */ #define SCB_CPUID_ARCHITECTURE_Msk (0xFUL << SCB_CPUID_ARCHITECTURE_Pos) /*!< SCB CPUID: ARCHITECTURE Mask */ #define SCB_CPUID_PARTNO_Pos 4 /*!< SCB CPUID: PARTNO Position */ #define SCB_CPUID_PARTNO_Msk (0xFFFUL << SCB_CPUID_PARTNO_Pos) /*!< SCB CPUID: PARTNO Mask */ #define SCB_CPUID_REVISION_Pos 0 /*!< SCB CPUID: REVISION Position */ #define SCB_CPUID_REVISION_Msk (0xFUL << SCB_CPUID_REVISION_Pos) /*!< SCB CPUID: REVISION Mask */ /* SCB Interrupt Control State Register Definitions */ #define SCB_ICSR_NMIPENDSET_Pos 31 /*!< SCB ICSR: NMIPENDSET Position */ #define SCB_ICSR_NMIPENDSET_Msk (1UL << SCB_ICSR_NMIPENDSET_Pos) /*!< SCB ICSR: NMIPENDSET Mask */ #define SCB_ICSR_PENDSVSET_Pos 28 /*!< SCB ICSR: PENDSVSET Position */ #define SCB_ICSR_PENDSVSET_Msk (1UL << SCB_ICSR_PENDSVSET_Pos) /*!< SCB ICSR: PENDSVSET Mask */ #define SCB_ICSR_PENDSVCLR_Pos 27 /*!< SCB ICSR: PENDSVCLR Position */ #define SCB_ICSR_PENDSVCLR_Msk (1UL << SCB_ICSR_PENDSVCLR_Pos) /*!< SCB ICSR: PENDSVCLR Mask */ #define SCB_ICSR_PENDSTSET_Pos 26 /*!< SCB ICSR: PENDSTSET Position */ #define SCB_ICSR_PENDSTSET_Msk (1UL << SCB_ICSR_PENDSTSET_Pos) /*!< SCB ICSR: PENDSTSET Mask */ #define SCB_ICSR_PENDSTCLR_Pos 25 /*!< SCB ICSR: PENDSTCLR Position */ #define SCB_ICSR_PENDSTCLR_Msk (1UL << SCB_ICSR_PENDSTCLR_Pos) /*!< SCB ICSR: PENDSTCLR Mask */ #define SCB_ICSR_ISRPREEMPT_Pos 23 /*!< SCB ICSR: ISRPREEMPT Position */ #define SCB_ICSR_ISRPREEMPT_Msk (1UL << SCB_ICSR_ISRPREEMPT_Pos) /*!< SCB ICSR: ISRPREEMPT Mask */ #define SCB_ICSR_ISRPENDING_Pos 22 /*!< SCB ICSR: ISRPENDING Position */ #define SCB_ICSR_ISRPENDING_Msk (1UL << SCB_ICSR_ISRPENDING_Pos) /*!< SCB ICSR: ISRPENDING Mask */ #define SCB_ICSR_VECTPENDING_Pos 12 /*!< SCB ICSR: VECTPENDING Position */ #define SCB_ICSR_VECTPENDING_Msk (0x1FFUL << SCB_ICSR_VECTPENDING_Pos) /*!< SCB ICSR: VECTPENDING Mask */ #define SCB_ICSR_VECTACTIVE_Pos 0 /*!< SCB ICSR: VECTACTIVE Position */ #define SCB_ICSR_VECTACTIVE_Msk (0x1FFUL << SCB_ICSR_VECTACTIVE_Pos) /*!< SCB ICSR: VECTACTIVE Mask */ #if (__VTOR_PRESENT == 1) /* SCB Interrupt Control State Register Definitions */ #define SCB_VTOR_TBLOFF_Pos 8 /*!< SCB VTOR: TBLOFF Position */ #define SCB_VTOR_TBLOFF_Msk (0xFFFFFFUL << SCB_VTOR_TBLOFF_Pos) /*!< SCB VTOR: TBLOFF Mask */ #endif /* SCB Application Interrupt and Reset Control Register Definitions */ #define SCB_AIRCR_VECTKEY_Pos 16 /*!< SCB AIRCR: VECTKEY Position */ #define SCB_AIRCR_VECTKEY_Msk (0xFFFFUL << SCB_AIRCR_VECTKEY_Pos) /*!< SCB AIRCR: VECTKEY Mask */ #define SCB_AIRCR_VECTKEYSTAT_Pos 16 /*!< SCB AIRCR: VECTKEYSTAT Position */ #define SCB_AIRCR_VECTKEYSTAT_Msk (0xFFFFUL << SCB_AIRCR_VECTKEYSTAT_Pos) /*!< SCB AIRCR: VECTKEYSTAT Mask */ #define SCB_AIRCR_ENDIANESS_Pos 15 /*!< SCB AIRCR: ENDIANESS Position */ #define SCB_AIRCR_ENDIANESS_Msk (1UL << SCB_AIRCR_ENDIANESS_Pos) /*!< SCB AIRCR: ENDIANESS Mask */ #define SCB_AIRCR_SYSRESETREQ_Pos 2 /*!< SCB AIRCR: SYSRESETREQ Position */ #define SCB_AIRCR_SYSRESETREQ_Msk (1UL << SCB_AIRCR_SYSRESETREQ_Pos) /*!< SCB AIRCR: SYSRESETREQ Mask */ #define SCB_AIRCR_VECTCLRACTIVE_Pos 1 /*!< SCB AIRCR: VECTCLRACTIVE Position */ #define SCB_AIRCR_VECTCLRACTIVE_Msk (1UL << SCB_AIRCR_VECTCLRACTIVE_Pos) /*!< SCB AIRCR: VECTCLRACTIVE Mask */ /* SCB System Control Register Definitions */ #define SCB_SCR_SEVONPEND_Pos 4 /*!< SCB SCR: SEVONPEND Position */ #define SCB_SCR_SEVONPEND_Msk (1UL << SCB_SCR_SEVONPEND_Pos) /*!< SCB SCR: SEVONPEND Mask */ #define SCB_SCR_SLEEPDEEP_Pos 2 /*!< SCB SCR: SLEEPDEEP Position */ #define SCB_SCR_SLEEPDEEP_Msk (1UL << SCB_SCR_SLEEPDEEP_Pos) /*!< SCB SCR: SLEEPDEEP Mask */ #define SCB_SCR_SLEEPONEXIT_Pos 1 /*!< SCB SCR: SLEEPONEXIT Position */ #define SCB_SCR_SLEEPONEXIT_Msk (1UL << SCB_SCR_SLEEPONEXIT_Pos) /*!< SCB SCR: SLEEPONEXIT Mask */ /* SCB Configuration Control Register Definitions */ #define SCB_CCR_STKALIGN_Pos 9 /*!< SCB CCR: STKALIGN Position */ #define SCB_CCR_STKALIGN_Msk (1UL << SCB_CCR_STKALIGN_Pos) /*!< SCB CCR: STKALIGN Mask */ #define SCB_CCR_UNALIGN_TRP_Pos 3 /*!< SCB CCR: UNALIGN_TRP Position */ #define SCB_CCR_UNALIGN_TRP_Msk (1UL << SCB_CCR_UNALIGN_TRP_Pos) /*!< SCB CCR: UNALIGN_TRP Mask */ /* SCB System Handler Control and State Register Definitions */ #define SCB_SHCSR_SVCALLPENDED_Pos 15 /*!< SCB SHCSR: SVCALLPENDED Position */ #define SCB_SHCSR_SVCALLPENDED_Msk (1UL << SCB_SHCSR_SVCALLPENDED_Pos) /*!< SCB SHCSR: SVCALLPENDED Mask */ /*@} end of group CMSIS_SCB */ /** \ingroup CMSIS_core_register \defgroup CMSIS_SysTick System Tick Timer (SysTick) \brief Type definitions for the System Timer Registers. @{ */ /** \brief Structure type to access the System Timer (SysTick). */ typedef struct { __IO uint32_t CTRL; /*!< Offset: 0x000 (R/W) SysTick Control and Status Register */ __IO uint32_t LOAD; /*!< Offset: 0x004 (R/W) SysTick Reload Value Register */ __IO uint32_t VAL; /*!< Offset: 0x008 (R/W) SysTick Current Value Register */ __I uint32_t CALIB; /*!< Offset: 0x00C (R/ ) SysTick Calibration Register */ } SysTick_Type; /* SysTick Control / Status Register Definitions */ #define SysTick_CTRL_COUNTFLAG_Pos 16 /*!< SysTick CTRL: COUNTFLAG Position */ #define SysTick_CTRL_COUNTFLAG_Msk (1UL << SysTick_CTRL_COUNTFLAG_Pos) /*!< SysTick CTRL: COUNTFLAG Mask */ #define SysTick_CTRL_CLKSOURCE_Pos 2 /*!< SysTick CTRL: CLKSOURCE Position */ #define SysTick_CTRL_CLKSOURCE_Msk (1UL << SysTick_CTRL_CLKSOURCE_Pos) /*!< SysTick CTRL: CLKSOURCE Mask */ #define SysTick_CTRL_TICKINT_Pos 1 /*!< SysTick CTRL: TICKINT Position */ #define SysTick_CTRL_TICKINT_Msk (1UL << SysTick_CTRL_TICKINT_Pos) /*!< SysTick CTRL: TICKINT Mask */ #define SysTick_CTRL_ENABLE_Pos 0 /*!< SysTick CTRL: ENABLE Position */ #define SysTick_CTRL_ENABLE_Msk (1UL << SysTick_CTRL_ENABLE_Pos) /*!< SysTick CTRL: ENABLE Mask */ /* SysTick Reload Register Definitions */ #define SysTick_LOAD_RELOAD_Pos 0 /*!< SysTick LOAD: RELOAD Position */ #define SysTick_LOAD_RELOAD_Msk (0xFFFFFFUL << SysTick_LOAD_RELOAD_Pos) /*!< SysTick LOAD: RELOAD Mask */ /* SysTick Current Register Definitions */ #define SysTick_VAL_CURRENT_Pos 0 /*!< SysTick VAL: CURRENT Position */ #define SysTick_VAL_CURRENT_Msk (0xFFFFFFUL << SysTick_VAL_CURRENT_Pos) /*!< SysTick VAL: CURRENT Mask */ /* SysTick Calibration Register Definitions */ #define SysTick_CALIB_NOREF_Pos 31 /*!< SysTick CALIB: NOREF Position */ #define SysTick_CALIB_NOREF_Msk (1UL << SysTick_CALIB_NOREF_Pos) /*!< SysTick CALIB: NOREF Mask */ #define SysTick_CALIB_SKEW_Pos 30 /*!< SysTick CALIB: SKEW Position */ #define SysTick_CALIB_SKEW_Msk (1UL << SysTick_CALIB_SKEW_Pos) /*!< SysTick CALIB: SKEW Mask */ #define SysTick_CALIB_TENMS_Pos 0 /*!< SysTick CALIB: TENMS Position */ #define SysTick_CALIB_TENMS_Msk (0xFFFFFFUL << SysTick_VAL_CURRENT_Pos) /*!< SysTick CALIB: TENMS Mask */ /*@} end of group CMSIS_SysTick */ #if (__MPU_PRESENT == 1) /** \ingroup CMSIS_core_register \defgroup CMSIS_MPU Memory Protection Unit (MPU) \brief Type definitions for the Memory Protection Unit (MPU) @{ */ /** \brief Structure type to access the Memory Protection Unit (MPU). */ typedef struct { __I uint32_t TYPE; /*!< Offset: 0x000 (R/ ) MPU Type Register */ __IO uint32_t CTRL; /*!< Offset: 0x004 (R/W) MPU Control Register */ __IO uint32_t RNR; /*!< Offset: 0x008 (R/W) MPU Region RNRber Register */ __IO uint32_t RBAR; /*!< Offset: 0x00C (R/W) MPU Region Base Address Register */ __IO uint32_t RASR; /*!< Offset: 0x010 (R/W) MPU Region Attribute and Size Register */ } MPU_Type; /* MPU Type Register */ #define MPU_TYPE_IREGION_Pos 16 /*!< MPU TYPE: IREGION Position */ #define MPU_TYPE_IREGION_Msk (0xFFUL << MPU_TYPE_IREGION_Pos) /*!< MPU TYPE: IREGION Mask */ #define MPU_TYPE_DREGION_Pos 8 /*!< MPU TYPE: DREGION Position */ #define MPU_TYPE_DREGION_Msk (0xFFUL << MPU_TYPE_DREGION_Pos) /*!< MPU TYPE: DREGION Mask */ #define MPU_TYPE_SEPARATE_Pos 0 /*!< MPU TYPE: SEPARATE Position */ #define MPU_TYPE_SEPARATE_Msk (1UL << MPU_TYPE_SEPARATE_Pos) /*!< MPU TYPE: SEPARATE Mask */ /* MPU Control Register */ #define MPU_CTRL_PRIVDEFENA_Pos 2 /*!< MPU CTRL: PRIVDEFENA Position */ #define MPU_CTRL_PRIVDEFENA_Msk (1UL << MPU_CTRL_PRIVDEFENA_Pos) /*!< MPU CTRL: PRIVDEFENA Mask */ #define MPU_CTRL_HFNMIENA_Pos 1 /*!< MPU CTRL: HFNMIENA Position */ #define MPU_CTRL_HFNMIENA_Msk (1UL << MPU_CTRL_HFNMIENA_Pos) /*!< MPU CTRL: HFNMIENA Mask */ #define MPU_CTRL_ENABLE_Pos 0 /*!< MPU CTRL: ENABLE Position */ #define MPU_CTRL_ENABLE_Msk (1UL << MPU_CTRL_ENABLE_Pos) /*!< MPU CTRL: ENABLE Mask */ /* MPU Region Number Register */ #define MPU_RNR_REGION_Pos 0 /*!< MPU RNR: REGION Position */ #define MPU_RNR_REGION_Msk (0xFFUL << MPU_RNR_REGION_Pos) /*!< MPU RNR: REGION Mask */ /* MPU Region Base Address Register */ #define MPU_RBAR_ADDR_Pos 8 /*!< MPU RBAR: ADDR Position */ #define MPU_RBAR_ADDR_Msk (0xFFFFFFUL << MPU_RBAR_ADDR_Pos) /*!< MPU RBAR: ADDR Mask */ #define MPU_RBAR_VALID_Pos 4 /*!< MPU RBAR: VALID Position */ #define MPU_RBAR_VALID_Msk (1UL << MPU_RBAR_VALID_Pos) /*!< MPU RBAR: VALID Mask */ #define MPU_RBAR_REGION_Pos 0 /*!< MPU RBAR: REGION Position */ #define MPU_RBAR_REGION_Msk (0xFUL << MPU_RBAR_REGION_Pos) /*!< MPU RBAR: REGION Mask */ /* MPU Region Attribute and Size Register */ #define MPU_RASR_ATTRS_Pos 16 /*!< MPU RASR: MPU Region Attribute field Position */ #define MPU_RASR_ATTRS_Msk (0xFFFFUL << MPU_RASR_ATTRS_Pos) /*!< MPU RASR: MPU Region Attribute field Mask */ #define MPU_RASR_XN_Pos 28 /*!< MPU RASR: ATTRS.XN Position */ #define MPU_RASR_XN_Msk (1UL << MPU_RASR_XN_Pos) /*!< MPU RASR: ATTRS.XN Mask */ #define MPU_RASR_AP_Pos 24 /*!< MPU RASR: ATTRS.AP Position */ #define MPU_RASR_AP_Msk (0x7UL << MPU_RASR_AP_Pos) /*!< MPU RASR: ATTRS.AP Mask */ #define MPU_RASR_TEX_Pos 19 /*!< MPU RASR: ATTRS.TEX Position */ #define MPU_RASR_TEX_Msk (0x7UL << MPU_RASR_TEX_Pos) /*!< MPU RASR: ATTRS.TEX Mask */ #define MPU_RASR_S_Pos 18 /*!< MPU RASR: ATTRS.S Position */ #define MPU_RASR_S_Msk (1UL << MPU_RASR_S_Pos) /*!< MPU RASR: ATTRS.S Mask */ #define MPU_RASR_C_Pos 17 /*!< MPU RASR: ATTRS.C Position */ #define MPU_RASR_C_Msk (1UL << MPU_RASR_C_Pos) /*!< MPU RASR: ATTRS.C Mask */ #define MPU_RASR_B_Pos 16 /*!< MPU RASR: ATTRS.B Position */ #define MPU_RASR_B_Msk (1UL << MPU_RASR_B_Pos) /*!< MPU RASR: ATTRS.B Mask */ #define MPU_RASR_SRD_Pos 8 /*!< MPU RASR: Sub-Region Disable Position */ #define MPU_RASR_SRD_Msk (0xFFUL << MPU_RASR_SRD_Pos) /*!< MPU RASR: Sub-Region Disable Mask */ #define MPU_RASR_SIZE_Pos 1 /*!< MPU RASR: Region Size Field Position */ #define MPU_RASR_SIZE_Msk (0x1FUL << MPU_RASR_SIZE_Pos) /*!< MPU RASR: Region Size Field Mask */ #define MPU_RASR_ENABLE_Pos 0 /*!< MPU RASR: Region enable bit Position */ #define MPU_RASR_ENABLE_Msk (1UL << MPU_RASR_ENABLE_Pos) /*!< MPU RASR: Region enable bit Disable Mask */ /*@} end of group CMSIS_MPU */ #endif /** \ingroup CMSIS_core_register \defgroup CMSIS_CoreDebug Core Debug Registers (CoreDebug) \brief Cortex-M0+ Core Debug Registers (DCB registers, SHCSR, and DFSR) are only accessible over DAP and not via processor. Therefore they are not covered by the Cortex-M0 header file. @{ */ /*@} end of group CMSIS_CoreDebug */ /** \ingroup CMSIS_core_register \defgroup CMSIS_core_base Core Definitions \brief Definitions for base addresses, unions, and structures. @{ */ /* Memory mapping of Cortex-M0+ Hardware */ #define SCS_BASE (0xE000E000UL) /*!< System Control Space Base Address */ #define SysTick_BASE (SCS_BASE + 0x0010UL) /*!< SysTick Base Address */ #define NVIC_BASE (SCS_BASE + 0x0100UL) /*!< NVIC Base Address */ #define SCB_BASE (SCS_BASE + 0x0D00UL) /*!< System Control Block Base Address */ #define SCB ((SCB_Type *) SCB_BASE ) /*!< SCB configuration struct */ #define SysTick ((SysTick_Type *) SysTick_BASE ) /*!< SysTick configuration struct */ #define NVIC ((NVIC_Type *) NVIC_BASE ) /*!< NVIC configuration struct */ #if (__MPU_PRESENT == 1) #define MPU_BASE (SCS_BASE + 0x0D90UL) /*!< Memory Protection Unit */ #define MPU ((MPU_Type *) MPU_BASE ) /*!< Memory Protection Unit */ #endif /*@} */ /******************************************************************************* * Hardware Abstraction Layer Core Function Interface contains: - Core NVIC Functions - Core SysTick Functions - Core Register Access Functions ******************************************************************************/ /** \defgroup CMSIS_Core_FunctionInterface Functions and Instructions Reference */ /* ########################## NVIC functions #################################### */ /** \ingroup CMSIS_Core_FunctionInterface \defgroup CMSIS_Core_NVICFunctions NVIC Functions \brief Functions that manage interrupts and exceptions via the NVIC. @{ */ /* Interrupt Priorities are WORD accessible only under ARMv6M */ /* The following MACROS handle generation of the register offset and byte masks */ #define _BIT_SHIFT(IRQn) ( (((uint32_t)(IRQn) ) & 0x03) * 8 ) #define _SHP_IDX(IRQn) ( ((((uint32_t)(IRQn) & 0x0F)-8) >> 2) ) #define _IP_IDX(IRQn) ( ((uint32_t)(IRQn) >> 2) ) /** \brief Enable External Interrupt The function enables a device-specific interrupt in the NVIC interrupt controller. \param [in] IRQn External interrupt number. Value cannot be negative. */ __STATIC_INLINE void NVIC_EnableIRQ(IRQn_Type IRQn) { NVIC->ISER[0] = (1 << ((uint32_t)(IRQn) & 0x1F)); } /** \brief Disable External Interrupt The function disables a device-specific interrupt in the NVIC interrupt controller. \param [in] IRQn External interrupt number. Value cannot be negative. */ __STATIC_INLINE void NVIC_DisableIRQ(IRQn_Type IRQn) { NVIC->ICER[0] = (1 << ((uint32_t)(IRQn) & 0x1F)); } /** \brief Get Pending Interrupt The function reads the pending register in the NVIC and returns the pending bit for the specified interrupt. \param [in] IRQn Interrupt number. \return 0 Interrupt status is not pending. \return 1 Interrupt status is pending. */ __STATIC_INLINE uint32_t NVIC_GetPendingIRQ(IRQn_Type IRQn) { return((uint32_t) ((NVIC->ISPR[0] & (1 << ((uint32_t)(IRQn) & 0x1F)))?1:0)); } /** \brief Set Pending Interrupt The function sets the pending bit of an external interrupt. \param [in] IRQn Interrupt number. Value cannot be negative. */ __STATIC_INLINE void NVIC_SetPendingIRQ(IRQn_Type IRQn) { NVIC->ISPR[0] = (1 << ((uint32_t)(IRQn) & 0x1F)); } /** \brief Clear Pending Interrupt The function clears the pending bit of an external interrupt. \param [in] IRQn External interrupt number. Value cannot be negative. */ __STATIC_INLINE void NVIC_ClearPendingIRQ(IRQn_Type IRQn) { NVIC->ICPR[0] = (1 << ((uint32_t)(IRQn) & 0x1F)); /* Clear pending interrupt */ } /** \brief Set Interrupt Priority The function sets the priority of an interrupt. \note The priority cannot be set for every core interrupt. \param [in] IRQn Interrupt number. \param [in] priority Priority to set. */ __STATIC_INLINE void NVIC_SetPriority(IRQn_Type IRQn, uint32_t priority) { if(IRQn < 0) { SCB->SHP[_SHP_IDX(IRQn)] = (SCB->SHP[_SHP_IDX(IRQn)] & ~(0xFF << _BIT_SHIFT(IRQn))) | (((priority << (8 - __NVIC_PRIO_BITS)) & 0xFF) << _BIT_SHIFT(IRQn)); } else { NVIC->IP[_IP_IDX(IRQn)] = (NVIC->IP[_IP_IDX(IRQn)] & ~(0xFF << _BIT_SHIFT(IRQn))) | (((priority << (8 - __NVIC_PRIO_BITS)) & 0xFF) << _BIT_SHIFT(IRQn)); } } /** \brief Get Interrupt Priority The function reads the priority of an interrupt. The interrupt number can be positive to specify an external (device specific) interrupt, or negative to specify an internal (core) interrupt. \param [in] IRQn Interrupt number. \return Interrupt Priority. Value is aligned automatically to the implemented priority bits of the microcontroller. */ __STATIC_INLINE uint32_t NVIC_GetPriority(IRQn_Type IRQn) { if(IRQn < 0) { return((uint32_t)(((SCB->SHP[_SHP_IDX(IRQn)] >> _BIT_SHIFT(IRQn) ) & 0xFF) >> (8 - __NVIC_PRIO_BITS))); } /* get priority for Cortex-M0 system interrupts */ else { return((uint32_t)(((NVIC->IP[ _IP_IDX(IRQn)] >> _BIT_SHIFT(IRQn) ) & 0xFF) >> (8 - __NVIC_PRIO_BITS))); } /* get priority for device specific interrupts */ } /** \brief System Reset The function initiates a system reset request to reset the MCU. */ __STATIC_INLINE void NVIC_SystemReset(void) { __DSB(); /* Ensure all outstanding memory accesses included buffered write are completed before reset */ SCB->AIRCR = ((0x5FA << SCB_AIRCR_VECTKEY_Pos) | SCB_AIRCR_SYSRESETREQ_Msk); __DSB(); /* Ensure completion of memory access */ while(1); /* wait until reset */ } /*@} end of CMSIS_Core_NVICFunctions */ /* ################################## SysTick function ############################################ */ /** \ingroup CMSIS_Core_FunctionInterface \defgroup CMSIS_Core_SysTickFunctions SysTick Functions \brief Functions that configure the System. @{ */ #if (__Vendor_SysTickConfig == 0) /** \brief System Tick Configuration The function initializes the System Timer and its interrupt, and starts the System Tick Timer. Counter is in free running mode to generate periodic interrupts. \param [in] ticks Number of ticks between two interrupts. \return 0 Function succeeded. \return 1 Function failed. \note When the variable __Vendor_SysTickConfig is set to 1, then the function SysTick_Config is not included. In this case, the file device.h must contain a vendor-specific implementation of this function. */ __STATIC_INLINE uint32_t SysTick_Config(uint32_t ticks) { if ((ticks - 1) > SysTick_LOAD_RELOAD_Msk) return (1); /* Reload value impossible */ SysTick->LOAD = ticks - 1; /* set reload register */ NVIC_SetPriority (SysTick_IRQn, (1<<__NVIC_PRIO_BITS) - 1); /* set Priority for Systick Interrupt */ SysTick->VAL = 0; /* Load the SysTick Counter Value */ SysTick->CTRL = SysTick_CTRL_CLKSOURCE_Msk | SysTick_CTRL_TICKINT_Msk | SysTick_CTRL_ENABLE_Msk; /* Enable SysTick IRQ and SysTick Timer */ return (0); /* Function successful */ } #endif /*@} end of CMSIS_Core_SysTickFunctions */ #endif /* __CORE_CM0PLUS_H_DEPENDANT */ #endif /* __CMSIS_GENERIC */ #ifdef __cplusplus } #endif ================================================ FILE: Zelig/mbed/TARGET_NUCLEO_L152RE/core_cm3.h ================================================ /**************************************************************************//** * @file core_cm3.h * @brief CMSIS Cortex-M3 Core Peripheral Access Layer Header File * @version V3.20 * @date 25. February 2013 * * @note * ******************************************************************************/ /* Copyright (c) 2009 - 2013 ARM LIMITED All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: - Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. - Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. - Neither the name of ARM 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 COPYRIGHT HOLDERS AND 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. ---------------------------------------------------------------------------*/ #if defined ( __ICCARM__ ) #pragma system_include /* treat file as system include file for MISRA check */ #endif #ifdef __cplusplus extern "C" { #endif #ifndef __CORE_CM3_H_GENERIC #define __CORE_CM3_H_GENERIC /** \page CMSIS_MISRA_Exceptions MISRA-C:2004 Compliance Exceptions CMSIS violates the following MISRA-C:2004 rules: \li Required Rule 8.5, object/function definition in header file.
Function definitions in header files are used to allow 'inlining'. \li Required Rule 18.4, declaration of union type or object of union type: '{...}'.
Unions are used for effective representation of core registers. \li Advisory Rule 19.7, Function-like macro defined.
Function-like macros are used to allow more efficient code. */ /******************************************************************************* * CMSIS definitions ******************************************************************************/ /** \ingroup Cortex_M3 @{ */ /* CMSIS CM3 definitions */ #define __CM3_CMSIS_VERSION_MAIN (0x03) /*!< [31:16] CMSIS HAL main version */ #define __CM3_CMSIS_VERSION_SUB (0x20) /*!< [15:0] CMSIS HAL sub version */ #define __CM3_CMSIS_VERSION ((__CM3_CMSIS_VERSION_MAIN << 16) | \ __CM3_CMSIS_VERSION_SUB ) /*!< CMSIS HAL version number */ #define __CORTEX_M (0x03) /*!< Cortex-M Core */ #if defined ( __CC_ARM ) #define __ASM __asm /*!< asm keyword for ARM Compiler */ #define __INLINE __inline /*!< inline keyword for ARM Compiler */ #define __STATIC_INLINE static __inline #elif defined ( __ICCARM__ ) #define __ASM __asm /*!< asm keyword for IAR Compiler */ #define __INLINE inline /*!< inline keyword for IAR Compiler. Only available in High optimization mode! */ #define __STATIC_INLINE static inline #elif defined ( __TMS470__ ) #define __ASM __asm /*!< asm keyword for TI CCS Compiler */ #define __STATIC_INLINE static inline #elif defined ( __GNUC__ ) #define __ASM __asm /*!< asm keyword for GNU Compiler */ #define __INLINE inline /*!< inline keyword for GNU Compiler */ #define __STATIC_INLINE static inline #elif defined ( __TASKING__ ) #define __ASM __asm /*!< asm keyword for TASKING Compiler */ #define __INLINE inline /*!< inline keyword for TASKING Compiler */ #define __STATIC_INLINE static inline #endif /** __FPU_USED indicates whether an FPU is used or not. This core does not support an FPU at all */ #define __FPU_USED 0 #if defined ( __CC_ARM ) #if defined __TARGET_FPU_VFP #warning "Compiler generates FPU instructions for a device without an FPU (check __FPU_PRESENT)" #endif #elif defined ( __ICCARM__ ) #if defined __ARMVFP__ #warning "Compiler generates FPU instructions for a device without an FPU (check __FPU_PRESENT)" #endif #elif defined ( __TMS470__ ) #if defined __TI__VFP_SUPPORT____ #warning "Compiler generates FPU instructions for a device without an FPU (check __FPU_PRESENT)" #endif #elif defined ( __GNUC__ ) #if defined (__VFP_FP__) && !defined(__SOFTFP__) #warning "Compiler generates FPU instructions for a device without an FPU (check __FPU_PRESENT)" #endif #elif defined ( __TASKING__ ) #if defined __FPU_VFP__ #error "Compiler generates FPU instructions for a device without an FPU (check __FPU_PRESENT)" #endif #endif #include /* standard types definitions */ #include /* Core Instruction Access */ #include /* Core Function Access */ #endif /* __CORE_CM3_H_GENERIC */ #ifndef __CMSIS_GENERIC #ifndef __CORE_CM3_H_DEPENDANT #define __CORE_CM3_H_DEPENDANT /* check device defines and use defaults */ #if defined __CHECK_DEVICE_DEFINES #ifndef __CM3_REV #define __CM3_REV 0x0200 #warning "__CM3_REV not defined in device header file; using default!" #endif #ifndef __MPU_PRESENT #define __MPU_PRESENT 0 #warning "__MPU_PRESENT not defined in device header file; using default!" #endif #ifndef __NVIC_PRIO_BITS #define __NVIC_PRIO_BITS 4 #warning "__NVIC_PRIO_BITS not defined in device header file; using default!" #endif #ifndef __Vendor_SysTickConfig #define __Vendor_SysTickConfig 0 #warning "__Vendor_SysTickConfig not defined in device header file; using default!" #endif #endif /* IO definitions (access restrictions to peripheral registers) */ /** \defgroup CMSIS_glob_defs CMSIS Global Defines IO Type Qualifiers are used \li to specify the access to peripheral variables. \li for automatic generation of peripheral register debug information. */ #ifdef __cplusplus #define __I volatile /*!< Defines 'read only' permissions */ #else #define __I volatile const /*!< Defines 'read only' permissions */ #endif #define __O volatile /*!< Defines 'write only' permissions */ #define __IO volatile /*!< Defines 'read / write' permissions */ /*@} end of group Cortex_M3 */ /******************************************************************************* * Register Abstraction Core Register contain: - Core Register - Core NVIC Register - Core SCB Register - Core SysTick Register - Core Debug Register - Core MPU Register ******************************************************************************/ /** \defgroup CMSIS_core_register Defines and Type Definitions \brief Type definitions and defines for Cortex-M processor based devices. */ /** \ingroup CMSIS_core_register \defgroup CMSIS_CORE Status and Control Registers \brief Core Register type definitions. @{ */ /** \brief Union type to access the Application Program Status Register (APSR). */ typedef union { struct { #if (__CORTEX_M != 0x04) uint32_t _reserved0:27; /*!< bit: 0..26 Reserved */ #else uint32_t _reserved0:16; /*!< bit: 0..15 Reserved */ uint32_t GE:4; /*!< bit: 16..19 Greater than or Equal flags */ uint32_t _reserved1:7; /*!< bit: 20..26 Reserved */ #endif uint32_t Q:1; /*!< bit: 27 Saturation condition flag */ uint32_t V:1; /*!< bit: 28 Overflow condition code flag */ uint32_t C:1; /*!< bit: 29 Carry condition code flag */ uint32_t Z:1; /*!< bit: 30 Zero condition code flag */ uint32_t N:1; /*!< bit: 31 Negative condition code flag */ } b; /*!< Structure used for bit access */ uint32_t w; /*!< Type used for word access */ } APSR_Type; /** \brief Union type to access the Interrupt Program Status Register (IPSR). */ typedef union { struct { uint32_t ISR:9; /*!< bit: 0.. 8 Exception number */ uint32_t _reserved0:23; /*!< bit: 9..31 Reserved */ } b; /*!< Structure used for bit access */ uint32_t w; /*!< Type used for word access */ } IPSR_Type; /** \brief Union type to access the Special-Purpose Program Status Registers (xPSR). */ typedef union { struct { uint32_t ISR:9; /*!< bit: 0.. 8 Exception number */ #if (__CORTEX_M != 0x04) uint32_t _reserved0:15; /*!< bit: 9..23 Reserved */ #else uint32_t _reserved0:7; /*!< bit: 9..15 Reserved */ uint32_t GE:4; /*!< bit: 16..19 Greater than or Equal flags */ uint32_t _reserved1:4; /*!< bit: 20..23 Reserved */ #endif uint32_t T:1; /*!< bit: 24 Thumb bit (read 0) */ uint32_t IT:2; /*!< bit: 25..26 saved IT state (read 0) */ uint32_t Q:1; /*!< bit: 27 Saturation condition flag */ uint32_t V:1; /*!< bit: 28 Overflow condition code flag */ uint32_t C:1; /*!< bit: 29 Carry condition code flag */ uint32_t Z:1; /*!< bit: 30 Zero condition code flag */ uint32_t N:1; /*!< bit: 31 Negative condition code flag */ } b; /*!< Structure used for bit access */ uint32_t w; /*!< Type used for word access */ } xPSR_Type; /** \brief Union type to access the Control Registers (CONTROL). */ typedef union { struct { uint32_t nPRIV:1; /*!< bit: 0 Execution privilege in Thread mode */ uint32_t SPSEL:1; /*!< bit: 1 Stack to be used */ uint32_t FPCA:1; /*!< bit: 2 FP extension active flag */ uint32_t _reserved0:29; /*!< bit: 3..31 Reserved */ } b; /*!< Structure used for bit access */ uint32_t w; /*!< Type used for word access */ } CONTROL_Type; /*@} end of group CMSIS_CORE */ /** \ingroup CMSIS_core_register \defgroup CMSIS_NVIC Nested Vectored Interrupt Controller (NVIC) \brief Type definitions for the NVIC Registers @{ */ /** \brief Structure type to access the Nested Vectored Interrupt Controller (NVIC). */ typedef struct { __IO uint32_t ISER[8]; /*!< Offset: 0x000 (R/W) Interrupt Set Enable Register */ uint32_t RESERVED0[24]; __IO uint32_t ICER[8]; /*!< Offset: 0x080 (R/W) Interrupt Clear Enable Register */ uint32_t RSERVED1[24]; __IO uint32_t ISPR[8]; /*!< Offset: 0x100 (R/W) Interrupt Set Pending Register */ uint32_t RESERVED2[24]; __IO uint32_t ICPR[8]; /*!< Offset: 0x180 (R/W) Interrupt Clear Pending Register */ uint32_t RESERVED3[24]; __IO uint32_t IABR[8]; /*!< Offset: 0x200 (R/W) Interrupt Active bit Register */ uint32_t RESERVED4[56]; __IO uint8_t IP[240]; /*!< Offset: 0x300 (R/W) Interrupt Priority Register (8Bit wide) */ uint32_t RESERVED5[644]; __O uint32_t STIR; /*!< Offset: 0xE00 ( /W) Software Trigger Interrupt Register */ } NVIC_Type; /* Software Triggered Interrupt Register Definitions */ #define NVIC_STIR_INTID_Pos 0 /*!< STIR: INTLINESNUM Position */ #define NVIC_STIR_INTID_Msk (0x1FFUL << NVIC_STIR_INTID_Pos) /*!< STIR: INTLINESNUM Mask */ /*@} end of group CMSIS_NVIC */ /** \ingroup CMSIS_core_register \defgroup CMSIS_SCB System Control Block (SCB) \brief Type definitions for the System Control Block Registers @{ */ /** \brief Structure type to access the System Control Block (SCB). */ typedef struct { __I uint32_t CPUID; /*!< Offset: 0x000 (R/ ) CPUID Base Register */ __IO uint32_t ICSR; /*!< Offset: 0x004 (R/W) Interrupt Control and State Register */ __IO uint32_t VTOR; /*!< Offset: 0x008 (R/W) Vector Table Offset Register */ __IO uint32_t AIRCR; /*!< Offset: 0x00C (R/W) Application Interrupt and Reset Control Register */ __IO uint32_t SCR; /*!< Offset: 0x010 (R/W) System Control Register */ __IO uint32_t CCR; /*!< Offset: 0x014 (R/W) Configuration Control Register */ __IO uint8_t SHP[12]; /*!< Offset: 0x018 (R/W) System Handlers Priority Registers (4-7, 8-11, 12-15) */ __IO uint32_t SHCSR; /*!< Offset: 0x024 (R/W) System Handler Control and State Register */ __IO uint32_t CFSR; /*!< Offset: 0x028 (R/W) Configurable Fault Status Register */ __IO uint32_t HFSR; /*!< Offset: 0x02C (R/W) HardFault Status Register */ __IO uint32_t DFSR; /*!< Offset: 0x030 (R/W) Debug Fault Status Register */ __IO uint32_t MMFAR; /*!< Offset: 0x034 (R/W) MemManage Fault Address Register */ __IO uint32_t BFAR; /*!< Offset: 0x038 (R/W) BusFault Address Register */ __IO uint32_t AFSR; /*!< Offset: 0x03C (R/W) Auxiliary Fault Status Register */ __I uint32_t PFR[2]; /*!< Offset: 0x040 (R/ ) Processor Feature Register */ __I uint32_t DFR; /*!< Offset: 0x048 (R/ ) Debug Feature Register */ __I uint32_t ADR; /*!< Offset: 0x04C (R/ ) Auxiliary Feature Register */ __I uint32_t MMFR[4]; /*!< Offset: 0x050 (R/ ) Memory Model Feature Register */ __I uint32_t ISAR[5]; /*!< Offset: 0x060 (R/ ) Instruction Set Attributes Register */ uint32_t RESERVED0[5]; __IO uint32_t CPACR; /*!< Offset: 0x088 (R/W) Coprocessor Access Control Register */ } SCB_Type; /* SCB CPUID Register Definitions */ #define SCB_CPUID_IMPLEMENTER_Pos 24 /*!< SCB CPUID: IMPLEMENTER Position */ #define SCB_CPUID_IMPLEMENTER_Msk (0xFFUL << SCB_CPUID_IMPLEMENTER_Pos) /*!< SCB CPUID: IMPLEMENTER Mask */ #define SCB_CPUID_VARIANT_Pos 20 /*!< SCB CPUID: VARIANT Position */ #define SCB_CPUID_VARIANT_Msk (0xFUL << SCB_CPUID_VARIANT_Pos) /*!< SCB CPUID: VARIANT Mask */ #define SCB_CPUID_ARCHITECTURE_Pos 16 /*!< SCB CPUID: ARCHITECTURE Position */ #define SCB_CPUID_ARCHITECTURE_Msk (0xFUL << SCB_CPUID_ARCHITECTURE_Pos) /*!< SCB CPUID: ARCHITECTURE Mask */ #define SCB_CPUID_PARTNO_Pos 4 /*!< SCB CPUID: PARTNO Position */ #define SCB_CPUID_PARTNO_Msk (0xFFFUL << SCB_CPUID_PARTNO_Pos) /*!< SCB CPUID: PARTNO Mask */ #define SCB_CPUID_REVISION_Pos 0 /*!< SCB CPUID: REVISION Position */ #define SCB_CPUID_REVISION_Msk (0xFUL << SCB_CPUID_REVISION_Pos) /*!< SCB CPUID: REVISION Mask */ /* SCB Interrupt Control State Register Definitions */ #define SCB_ICSR_NMIPENDSET_Pos 31 /*!< SCB ICSR: NMIPENDSET Position */ #define SCB_ICSR_NMIPENDSET_Msk (1UL << SCB_ICSR_NMIPENDSET_Pos) /*!< SCB ICSR: NMIPENDSET Mask */ #define SCB_ICSR_PENDSVSET_Pos 28 /*!< SCB ICSR: PENDSVSET Position */ #define SCB_ICSR_PENDSVSET_Msk (1UL << SCB_ICSR_PENDSVSET_Pos) /*!< SCB ICSR: PENDSVSET Mask */ #define SCB_ICSR_PENDSVCLR_Pos 27 /*!< SCB ICSR: PENDSVCLR Position */ #define SCB_ICSR_PENDSVCLR_Msk (1UL << SCB_ICSR_PENDSVCLR_Pos) /*!< SCB ICSR: PENDSVCLR Mask */ #define SCB_ICSR_PENDSTSET_Pos 26 /*!< SCB ICSR: PENDSTSET Position */ #define SCB_ICSR_PENDSTSET_Msk (1UL << SCB_ICSR_PENDSTSET_Pos) /*!< SCB ICSR: PENDSTSET Mask */ #define SCB_ICSR_PENDSTCLR_Pos 25 /*!< SCB ICSR: PENDSTCLR Position */ #define SCB_ICSR_PENDSTCLR_Msk (1UL << SCB_ICSR_PENDSTCLR_Pos) /*!< SCB ICSR: PENDSTCLR Mask */ #define SCB_ICSR_ISRPREEMPT_Pos 23 /*!< SCB ICSR: ISRPREEMPT Position */ #define SCB_ICSR_ISRPREEMPT_Msk (1UL << SCB_ICSR_ISRPREEMPT_Pos) /*!< SCB ICSR: ISRPREEMPT Mask */ #define SCB_ICSR_ISRPENDING_Pos 22 /*!< SCB ICSR: ISRPENDING Position */ #define SCB_ICSR_ISRPENDING_Msk (1UL << SCB_ICSR_ISRPENDING_Pos) /*!< SCB ICSR: ISRPENDING Mask */ #define SCB_ICSR_VECTPENDING_Pos 12 /*!< SCB ICSR: VECTPENDING Position */ #define SCB_ICSR_VECTPENDING_Msk (0x1FFUL << SCB_ICSR_VECTPENDING_Pos) /*!< SCB ICSR: VECTPENDING Mask */ #define SCB_ICSR_RETTOBASE_Pos 11 /*!< SCB ICSR: RETTOBASE Position */ #define SCB_ICSR_RETTOBASE_Msk (1UL << SCB_ICSR_RETTOBASE_Pos) /*!< SCB ICSR: RETTOBASE Mask */ #define SCB_ICSR_VECTACTIVE_Pos 0 /*!< SCB ICSR: VECTACTIVE Position */ #define SCB_ICSR_VECTACTIVE_Msk (0x1FFUL << SCB_ICSR_VECTACTIVE_Pos) /*!< SCB ICSR: VECTACTIVE Mask */ /* SCB Vector Table Offset Register Definitions */ #if (__CM3_REV < 0x0201) /* core r2p1 */ #define SCB_VTOR_TBLBASE_Pos 29 /*!< SCB VTOR: TBLBASE Position */ #define SCB_VTOR_TBLBASE_Msk (1UL << SCB_VTOR_TBLBASE_Pos) /*!< SCB VTOR: TBLBASE Mask */ #define SCB_VTOR_TBLOFF_Pos 7 /*!< SCB VTOR: TBLOFF Position */ #define SCB_VTOR_TBLOFF_Msk (0x3FFFFFUL << SCB_VTOR_TBLOFF_Pos) /*!< SCB VTOR: TBLOFF Mask */ #else #define SCB_VTOR_TBLOFF_Pos 7 /*!< SCB VTOR: TBLOFF Position */ #define SCB_VTOR_TBLOFF_Msk (0x1FFFFFFUL << SCB_VTOR_TBLOFF_Pos) /*!< SCB VTOR: TBLOFF Mask */ #endif /* SCB Application Interrupt and Reset Control Register Definitions */ #define SCB_AIRCR_VECTKEY_Pos 16 /*!< SCB AIRCR: VECTKEY Position */ #define SCB_AIRCR_VECTKEY_Msk (0xFFFFUL << SCB_AIRCR_VECTKEY_Pos) /*!< SCB AIRCR: VECTKEY Mask */ #define SCB_AIRCR_VECTKEYSTAT_Pos 16 /*!< SCB AIRCR: VECTKEYSTAT Position */ #define SCB_AIRCR_VECTKEYSTAT_Msk (0xFFFFUL << SCB_AIRCR_VECTKEYSTAT_Pos) /*!< SCB AIRCR: VECTKEYSTAT Mask */ #define SCB_AIRCR_ENDIANESS_Pos 15 /*!< SCB AIRCR: ENDIANESS Position */ #define SCB_AIRCR_ENDIANESS_Msk (1UL << SCB_AIRCR_ENDIANESS_Pos) /*!< SCB AIRCR: ENDIANESS Mask */ #define SCB_AIRCR_PRIGROUP_Pos 8 /*!< SCB AIRCR: PRIGROUP Position */ #define SCB_AIRCR_PRIGROUP_Msk (7UL << SCB_AIRCR_PRIGROUP_Pos) /*!< SCB AIRCR: PRIGROUP Mask */ #define SCB_AIRCR_SYSRESETREQ_Pos 2 /*!< SCB AIRCR: SYSRESETREQ Position */ #define SCB_AIRCR_SYSRESETREQ_Msk (1UL << SCB_AIRCR_SYSRESETREQ_Pos) /*!< SCB AIRCR: SYSRESETREQ Mask */ #define SCB_AIRCR_VECTCLRACTIVE_Pos 1 /*!< SCB AIRCR: VECTCLRACTIVE Position */ #define SCB_AIRCR_VECTCLRACTIVE_Msk (1UL << SCB_AIRCR_VECTCLRACTIVE_Pos) /*!< SCB AIRCR: VECTCLRACTIVE Mask */ #define SCB_AIRCR_VECTRESET_Pos 0 /*!< SCB AIRCR: VECTRESET Position */ #define SCB_AIRCR_VECTRESET_Msk (1UL << SCB_AIRCR_VECTRESET_Pos) /*!< SCB AIRCR: VECTRESET Mask */ /* SCB System Control Register Definitions */ #define SCB_SCR_SEVONPEND_Pos 4 /*!< SCB SCR: SEVONPEND Position */ #define SCB_SCR_SEVONPEND_Msk (1UL << SCB_SCR_SEVONPEND_Pos) /*!< SCB SCR: SEVONPEND Mask */ #define SCB_SCR_SLEEPDEEP_Pos 2 /*!< SCB SCR: SLEEPDEEP Position */ #define SCB_SCR_SLEEPDEEP_Msk (1UL << SCB_SCR_SLEEPDEEP_Pos) /*!< SCB SCR: SLEEPDEEP Mask */ #define SCB_SCR_SLEEPONEXIT_Pos 1 /*!< SCB SCR: SLEEPONEXIT Position */ #define SCB_SCR_SLEEPONEXIT_Msk (1UL << SCB_SCR_SLEEPONEXIT_Pos) /*!< SCB SCR: SLEEPONEXIT Mask */ /* SCB Configuration Control Register Definitions */ #define SCB_CCR_STKALIGN_Pos 9 /*!< SCB CCR: STKALIGN Position */ #define SCB_CCR_STKALIGN_Msk (1UL << SCB_CCR_STKALIGN_Pos) /*!< SCB CCR: STKALIGN Mask */ #define SCB_CCR_BFHFNMIGN_Pos 8 /*!< SCB CCR: BFHFNMIGN Position */ #define SCB_CCR_BFHFNMIGN_Msk (1UL << SCB_CCR_BFHFNMIGN_Pos) /*!< SCB CCR: BFHFNMIGN Mask */ #define SCB_CCR_DIV_0_TRP_Pos 4 /*!< SCB CCR: DIV_0_TRP Position */ #define SCB_CCR_DIV_0_TRP_Msk (1UL << SCB_CCR_DIV_0_TRP_Pos) /*!< SCB CCR: DIV_0_TRP Mask */ #define SCB_CCR_UNALIGN_TRP_Pos 3 /*!< SCB CCR: UNALIGN_TRP Position */ #define SCB_CCR_UNALIGN_TRP_Msk (1UL << SCB_CCR_UNALIGN_TRP_Pos) /*!< SCB CCR: UNALIGN_TRP Mask */ #define SCB_CCR_USERSETMPEND_Pos 1 /*!< SCB CCR: USERSETMPEND Position */ #define SCB_CCR_USERSETMPEND_Msk (1UL << SCB_CCR_USERSETMPEND_Pos) /*!< SCB CCR: USERSETMPEND Mask */ #define SCB_CCR_NONBASETHRDENA_Pos 0 /*!< SCB CCR: NONBASETHRDENA Position */ #define SCB_CCR_NONBASETHRDENA_Msk (1UL << SCB_CCR_NONBASETHRDENA_Pos) /*!< SCB CCR: NONBASETHRDENA Mask */ /* SCB System Handler Control and State Register Definitions */ #define SCB_SHCSR_USGFAULTENA_Pos 18 /*!< SCB SHCSR: USGFAULTENA Position */ #define SCB_SHCSR_USGFAULTENA_Msk (1UL << SCB_SHCSR_USGFAULTENA_Pos) /*!< SCB SHCSR: USGFAULTENA Mask */ #define SCB_SHCSR_BUSFAULTENA_Pos 17 /*!< SCB SHCSR: BUSFAULTENA Position */ #define SCB_SHCSR_BUSFAULTENA_Msk (1UL << SCB_SHCSR_BUSFAULTENA_Pos) /*!< SCB SHCSR: BUSFAULTENA Mask */ #define SCB_SHCSR_MEMFAULTENA_Pos 16 /*!< SCB SHCSR: MEMFAULTENA Position */ #define SCB_SHCSR_MEMFAULTENA_Msk (1UL << SCB_SHCSR_MEMFAULTENA_Pos) /*!< SCB SHCSR: MEMFAULTENA Mask */ #define SCB_SHCSR_SVCALLPENDED_Pos 15 /*!< SCB SHCSR: SVCALLPENDED Position */ #define SCB_SHCSR_SVCALLPENDED_Msk (1UL << SCB_SHCSR_SVCALLPENDED_Pos) /*!< SCB SHCSR: SVCALLPENDED Mask */ #define SCB_SHCSR_BUSFAULTPENDED_Pos 14 /*!< SCB SHCSR: BUSFAULTPENDED Position */ #define SCB_SHCSR_BUSFAULTPENDED_Msk (1UL << SCB_SHCSR_BUSFAULTPENDED_Pos) /*!< SCB SHCSR: BUSFAULTPENDED Mask */ #define SCB_SHCSR_MEMFAULTPENDED_Pos 13 /*!< SCB SHCSR: MEMFAULTPENDED Position */ #define SCB_SHCSR_MEMFAULTPENDED_Msk (1UL << SCB_SHCSR_MEMFAULTPENDED_Pos) /*!< SCB SHCSR: MEMFAULTPENDED Mask */ #define SCB_SHCSR_USGFAULTPENDED_Pos 12 /*!< SCB SHCSR: USGFAULTPENDED Position */ #define SCB_SHCSR_USGFAULTPENDED_Msk (1UL << SCB_SHCSR_USGFAULTPENDED_Pos) /*!< SCB SHCSR: USGFAULTPENDED Mask */ #define SCB_SHCSR_SYSTICKACT_Pos 11 /*!< SCB SHCSR: SYSTICKACT Position */ #define SCB_SHCSR_SYSTICKACT_Msk (1UL << SCB_SHCSR_SYSTICKACT_Pos) /*!< SCB SHCSR: SYSTICKACT Mask */ #define SCB_SHCSR_PENDSVACT_Pos 10 /*!< SCB SHCSR: PENDSVACT Position */ #define SCB_SHCSR_PENDSVACT_Msk (1UL << SCB_SHCSR_PENDSVACT_Pos) /*!< SCB SHCSR: PENDSVACT Mask */ #define SCB_SHCSR_MONITORACT_Pos 8 /*!< SCB SHCSR: MONITORACT Position */ #define SCB_SHCSR_MONITORACT_Msk (1UL << SCB_SHCSR_MONITORACT_Pos) /*!< SCB SHCSR: MONITORACT Mask */ #define SCB_SHCSR_SVCALLACT_Pos 7 /*!< SCB SHCSR: SVCALLACT Position */ #define SCB_SHCSR_SVCALLACT_Msk (1UL << SCB_SHCSR_SVCALLACT_Pos) /*!< SCB SHCSR: SVCALLACT Mask */ #define SCB_SHCSR_USGFAULTACT_Pos 3 /*!< SCB SHCSR: USGFAULTACT Position */ #define SCB_SHCSR_USGFAULTACT_Msk (1UL << SCB_SHCSR_USGFAULTACT_Pos) /*!< SCB SHCSR: USGFAULTACT Mask */ #define SCB_SHCSR_BUSFAULTACT_Pos 1 /*!< SCB SHCSR: BUSFAULTACT Position */ #define SCB_SHCSR_BUSFAULTACT_Msk (1UL << SCB_SHCSR_BUSFAULTACT_Pos) /*!< SCB SHCSR: BUSFAULTACT Mask */ #define SCB_SHCSR_MEMFAULTACT_Pos 0 /*!< SCB SHCSR: MEMFAULTACT Position */ #define SCB_SHCSR_MEMFAULTACT_Msk (1UL << SCB_SHCSR_MEMFAULTACT_Pos) /*!< SCB SHCSR: MEMFAULTACT Mask */ /* SCB Configurable Fault Status Registers Definitions */ #define SCB_CFSR_USGFAULTSR_Pos 16 /*!< SCB CFSR: Usage Fault Status Register Position */ #define SCB_CFSR_USGFAULTSR_Msk (0xFFFFUL << SCB_CFSR_USGFAULTSR_Pos) /*!< SCB CFSR: Usage Fault Status Register Mask */ #define SCB_CFSR_BUSFAULTSR_Pos 8 /*!< SCB CFSR: Bus Fault Status Register Position */ #define SCB_CFSR_BUSFAULTSR_Msk (0xFFUL << SCB_CFSR_BUSFAULTSR_Pos) /*!< SCB CFSR: Bus Fault Status Register Mask */ #define SCB_CFSR_MEMFAULTSR_Pos 0 /*!< SCB CFSR: Memory Manage Fault Status Register Position */ #define SCB_CFSR_MEMFAULTSR_Msk (0xFFUL << SCB_CFSR_MEMFAULTSR_Pos) /*!< SCB CFSR: Memory Manage Fault Status Register Mask */ /* SCB Hard Fault Status Registers Definitions */ #define SCB_HFSR_DEBUGEVT_Pos 31 /*!< SCB HFSR: DEBUGEVT Position */ #define SCB_HFSR_DEBUGEVT_Msk (1UL << SCB_HFSR_DEBUGEVT_Pos) /*!< SCB HFSR: DEBUGEVT Mask */ #define SCB_HFSR_FORCED_Pos 30 /*!< SCB HFSR: FORCED Position */ #define SCB_HFSR_FORCED_Msk (1UL << SCB_HFSR_FORCED_Pos) /*!< SCB HFSR: FORCED Mask */ #define SCB_HFSR_VECTTBL_Pos 1 /*!< SCB HFSR: VECTTBL Position */ #define SCB_HFSR_VECTTBL_Msk (1UL << SCB_HFSR_VECTTBL_Pos) /*!< SCB HFSR: VECTTBL Mask */ /* SCB Debug Fault Status Register Definitions */ #define SCB_DFSR_EXTERNAL_Pos 4 /*!< SCB DFSR: EXTERNAL Position */ #define SCB_DFSR_EXTERNAL_Msk (1UL << SCB_DFSR_EXTERNAL_Pos) /*!< SCB DFSR: EXTERNAL Mask */ #define SCB_DFSR_VCATCH_Pos 3 /*!< SCB DFSR: VCATCH Position */ #define SCB_DFSR_VCATCH_Msk (1UL << SCB_DFSR_VCATCH_Pos) /*!< SCB DFSR: VCATCH Mask */ #define SCB_DFSR_DWTTRAP_Pos 2 /*!< SCB DFSR: DWTTRAP Position */ #define SCB_DFSR_DWTTRAP_Msk (1UL << SCB_DFSR_DWTTRAP_Pos) /*!< SCB DFSR: DWTTRAP Mask */ #define SCB_DFSR_BKPT_Pos 1 /*!< SCB DFSR: BKPT Position */ #define SCB_DFSR_BKPT_Msk (1UL << SCB_DFSR_BKPT_Pos) /*!< SCB DFSR: BKPT Mask */ #define SCB_DFSR_HALTED_Pos 0 /*!< SCB DFSR: HALTED Position */ #define SCB_DFSR_HALTED_Msk (1UL << SCB_DFSR_HALTED_Pos) /*!< SCB DFSR: HALTED Mask */ /*@} end of group CMSIS_SCB */ /** \ingroup CMSIS_core_register \defgroup CMSIS_SCnSCB System Controls not in SCB (SCnSCB) \brief Type definitions for the System Control and ID Register not in the SCB @{ */ /** \brief Structure type to access the System Control and ID Register not in the SCB. */ typedef struct { uint32_t RESERVED0[1]; __I uint32_t ICTR; /*!< Offset: 0x004 (R/ ) Interrupt Controller Type Register */ #if ((defined __CM3_REV) && (__CM3_REV >= 0x200)) __IO uint32_t ACTLR; /*!< Offset: 0x008 (R/W) Auxiliary Control Register */ #else uint32_t RESERVED1[1]; #endif } SCnSCB_Type; /* Interrupt Controller Type Register Definitions */ #define SCnSCB_ICTR_INTLINESNUM_Pos 0 /*!< ICTR: INTLINESNUM Position */ #define SCnSCB_ICTR_INTLINESNUM_Msk (0xFUL << SCnSCB_ICTR_INTLINESNUM_Pos) /*!< ICTR: INTLINESNUM Mask */ /* Auxiliary Control Register Definitions */ #define SCnSCB_ACTLR_DISFOLD_Pos 2 /*!< ACTLR: DISFOLD Position */ #define SCnSCB_ACTLR_DISFOLD_Msk (1UL << SCnSCB_ACTLR_DISFOLD_Pos) /*!< ACTLR: DISFOLD Mask */ #define SCnSCB_ACTLR_DISDEFWBUF_Pos 1 /*!< ACTLR: DISDEFWBUF Position */ #define SCnSCB_ACTLR_DISDEFWBUF_Msk (1UL << SCnSCB_ACTLR_DISDEFWBUF_Pos) /*!< ACTLR: DISDEFWBUF Mask */ #define SCnSCB_ACTLR_DISMCYCINT_Pos 0 /*!< ACTLR: DISMCYCINT Position */ #define SCnSCB_ACTLR_DISMCYCINT_Msk (1UL << SCnSCB_ACTLR_DISMCYCINT_Pos) /*!< ACTLR: DISMCYCINT Mask */ /*@} end of group CMSIS_SCnotSCB */ /** \ingroup CMSIS_core_register \defgroup CMSIS_SysTick System Tick Timer (SysTick) \brief Type definitions for the System Timer Registers. @{ */ /** \brief Structure type to access the System Timer (SysTick). */ typedef struct { __IO uint32_t CTRL; /*!< Offset: 0x000 (R/W) SysTick Control and Status Register */ __IO uint32_t LOAD; /*!< Offset: 0x004 (R/W) SysTick Reload Value Register */ __IO uint32_t VAL; /*!< Offset: 0x008 (R/W) SysTick Current Value Register */ __I uint32_t CALIB; /*!< Offset: 0x00C (R/ ) SysTick Calibration Register */ } SysTick_Type; /* SysTick Control / Status Register Definitions */ #define SysTick_CTRL_COUNTFLAG_Pos 16 /*!< SysTick CTRL: COUNTFLAG Position */ #define SysTick_CTRL_COUNTFLAG_Msk (1UL << SysTick_CTRL_COUNTFLAG_Pos) /*!< SysTick CTRL: COUNTFLAG Mask */ #define SysTick_CTRL_CLKSOURCE_Pos 2 /*!< SysTick CTRL: CLKSOURCE Position */ #define SysTick_CTRL_CLKSOURCE_Msk (1UL << SysTick_CTRL_CLKSOURCE_Pos) /*!< SysTick CTRL: CLKSOURCE Mask */ #define SysTick_CTRL_TICKINT_Pos 1 /*!< SysTick CTRL: TICKINT Position */ #define SysTick_CTRL_TICKINT_Msk (1UL << SysTick_CTRL_TICKINT_Pos) /*!< SysTick CTRL: TICKINT Mask */ #define SysTick_CTRL_ENABLE_Pos 0 /*!< SysTick CTRL: ENABLE Position */ #define SysTick_CTRL_ENABLE_Msk (1UL << SysTick_CTRL_ENABLE_Pos) /*!< SysTick CTRL: ENABLE Mask */ /* SysTick Reload Register Definitions */ #define SysTick_LOAD_RELOAD_Pos 0 /*!< SysTick LOAD: RELOAD Position */ #define SysTick_LOAD_RELOAD_Msk (0xFFFFFFUL << SysTick_LOAD_RELOAD_Pos) /*!< SysTick LOAD: RELOAD Mask */ /* SysTick Current Register Definitions */ #define SysTick_VAL_CURRENT_Pos 0 /*!< SysTick VAL: CURRENT Position */ #define SysTick_VAL_CURRENT_Msk (0xFFFFFFUL << SysTick_VAL_CURRENT_Pos) /*!< SysTick VAL: CURRENT Mask */ /* SysTick Calibration Register Definitions */ #define SysTick_CALIB_NOREF_Pos 31 /*!< SysTick CALIB: NOREF Position */ #define SysTick_CALIB_NOREF_Msk (1UL << SysTick_CALIB_NOREF_Pos) /*!< SysTick CALIB: NOREF Mask */ #define SysTick_CALIB_SKEW_Pos 30 /*!< SysTick CALIB: SKEW Position */ #define SysTick_CALIB_SKEW_Msk (1UL << SysTick_CALIB_SKEW_Pos) /*!< SysTick CALIB: SKEW Mask */ #define SysTick_CALIB_TENMS_Pos 0 /*!< SysTick CALIB: TENMS Position */ #define SysTick_CALIB_TENMS_Msk (0xFFFFFFUL << SysTick_VAL_CURRENT_Pos) /*!< SysTick CALIB: TENMS Mask */ /*@} end of group CMSIS_SysTick */ /** \ingroup CMSIS_core_register \defgroup CMSIS_ITM Instrumentation Trace Macrocell (ITM) \brief Type definitions for the Instrumentation Trace Macrocell (ITM) @{ */ /** \brief Structure type to access the Instrumentation Trace Macrocell Register (ITM). */ typedef struct { __O union { __O uint8_t u8; /*!< Offset: 0x000 ( /W) ITM Stimulus Port 8-bit */ __O uint16_t u16; /*!< Offset: 0x000 ( /W) ITM Stimulus Port 16-bit */ __O uint32_t u32; /*!< Offset: 0x000 ( /W) ITM Stimulus Port 32-bit */ } PORT [32]; /*!< Offset: 0x000 ( /W) ITM Stimulus Port Registers */ uint32_t RESERVED0[864]; __IO uint32_t TER; /*!< Offset: 0xE00 (R/W) ITM Trace Enable Register */ uint32_t RESERVED1[15]; __IO uint32_t TPR; /*!< Offset: 0xE40 (R/W) ITM Trace Privilege Register */ uint32_t RESERVED2[15]; __IO uint32_t TCR; /*!< Offset: 0xE80 (R/W) ITM Trace Control Register */ uint32_t RESERVED3[29]; __O uint32_t IWR; /*!< Offset: 0xEF8 ( /W) ITM Integration Write Register */ __I uint32_t IRR; /*!< Offset: 0xEFC (R/ ) ITM Integration Read Register */ __IO uint32_t IMCR; /*!< Offset: 0xF00 (R/W) ITM Integration Mode Control Register */ uint32_t RESERVED4[43]; __O uint32_t LAR; /*!< Offset: 0xFB0 ( /W) ITM Lock Access Register */ __I uint32_t LSR; /*!< Offset: 0xFB4 (R/ ) ITM Lock Status Register */ uint32_t RESERVED5[6]; __I uint32_t PID4; /*!< Offset: 0xFD0 (R/ ) ITM Peripheral Identification Register #4 */ __I uint32_t PID5; /*!< Offset: 0xFD4 (R/ ) ITM Peripheral Identification Register #5 */ __I uint32_t PID6; /*!< Offset: 0xFD8 (R/ ) ITM Peripheral Identification Register #6 */ __I uint32_t PID7; /*!< Offset: 0xFDC (R/ ) ITM Peripheral Identification Register #7 */ __I uint32_t PID0; /*!< Offset: 0xFE0 (R/ ) ITM Peripheral Identification Register #0 */ __I uint32_t PID1; /*!< Offset: 0xFE4 (R/ ) ITM Peripheral Identification Register #1 */ __I uint32_t PID2; /*!< Offset: 0xFE8 (R/ ) ITM Peripheral Identification Register #2 */ __I uint32_t PID3; /*!< Offset: 0xFEC (R/ ) ITM Peripheral Identification Register #3 */ __I uint32_t CID0; /*!< Offset: 0xFF0 (R/ ) ITM Component Identification Register #0 */ __I uint32_t CID1; /*!< Offset: 0xFF4 (R/ ) ITM Component Identification Register #1 */ __I uint32_t CID2; /*!< Offset: 0xFF8 (R/ ) ITM Component Identification Register #2 */ __I uint32_t CID3; /*!< Offset: 0xFFC (R/ ) ITM Component Identification Register #3 */ } ITM_Type; /* ITM Trace Privilege Register Definitions */ #define ITM_TPR_PRIVMASK_Pos 0 /*!< ITM TPR: PRIVMASK Position */ #define ITM_TPR_PRIVMASK_Msk (0xFUL << ITM_TPR_PRIVMASK_Pos) /*!< ITM TPR: PRIVMASK Mask */ /* ITM Trace Control Register Definitions */ #define ITM_TCR_BUSY_Pos 23 /*!< ITM TCR: BUSY Position */ #define ITM_TCR_BUSY_Msk (1UL << ITM_TCR_BUSY_Pos) /*!< ITM TCR: BUSY Mask */ #define ITM_TCR_TraceBusID_Pos 16 /*!< ITM TCR: ATBID Position */ #define ITM_TCR_TraceBusID_Msk (0x7FUL << ITM_TCR_TraceBusID_Pos) /*!< ITM TCR: ATBID Mask */ #define ITM_TCR_GTSFREQ_Pos 10 /*!< ITM TCR: Global timestamp frequency Position */ #define ITM_TCR_GTSFREQ_Msk (3UL << ITM_TCR_GTSFREQ_Pos) /*!< ITM TCR: Global timestamp frequency Mask */ #define ITM_TCR_TSPrescale_Pos 8 /*!< ITM TCR: TSPrescale Position */ #define ITM_TCR_TSPrescale_Msk (3UL << ITM_TCR_TSPrescale_Pos) /*!< ITM TCR: TSPrescale Mask */ #define ITM_TCR_SWOENA_Pos 4 /*!< ITM TCR: SWOENA Position */ #define ITM_TCR_SWOENA_Msk (1UL << ITM_TCR_SWOENA_Pos) /*!< ITM TCR: SWOENA Mask */ #define ITM_TCR_DWTENA_Pos 3 /*!< ITM TCR: DWTENA Position */ #define ITM_TCR_DWTENA_Msk (1UL << ITM_TCR_DWTENA_Pos) /*!< ITM TCR: DWTENA Mask */ #define ITM_TCR_SYNCENA_Pos 2 /*!< ITM TCR: SYNCENA Position */ #define ITM_TCR_SYNCENA_Msk (1UL << ITM_TCR_SYNCENA_Pos) /*!< ITM TCR: SYNCENA Mask */ #define ITM_TCR_TSENA_Pos 1 /*!< ITM TCR: TSENA Position */ #define ITM_TCR_TSENA_Msk (1UL << ITM_TCR_TSENA_Pos) /*!< ITM TCR: TSENA Mask */ #define ITM_TCR_ITMENA_Pos 0 /*!< ITM TCR: ITM Enable bit Position */ #define ITM_TCR_ITMENA_Msk (1UL << ITM_TCR_ITMENA_Pos) /*!< ITM TCR: ITM Enable bit Mask */ /* ITM Integration Write Register Definitions */ #define ITM_IWR_ATVALIDM_Pos 0 /*!< ITM IWR: ATVALIDM Position */ #define ITM_IWR_ATVALIDM_Msk (1UL << ITM_IWR_ATVALIDM_Pos) /*!< ITM IWR: ATVALIDM Mask */ /* ITM Integration Read Register Definitions */ #define ITM_IRR_ATREADYM_Pos 0 /*!< ITM IRR: ATREADYM Position */ #define ITM_IRR_ATREADYM_Msk (1UL << ITM_IRR_ATREADYM_Pos) /*!< ITM IRR: ATREADYM Mask */ /* ITM Integration Mode Control Register Definitions */ #define ITM_IMCR_INTEGRATION_Pos 0 /*!< ITM IMCR: INTEGRATION Position */ #define ITM_IMCR_INTEGRATION_Msk (1UL << ITM_IMCR_INTEGRATION_Pos) /*!< ITM IMCR: INTEGRATION Mask */ /* ITM Lock Status Register Definitions */ #define ITM_LSR_ByteAcc_Pos 2 /*!< ITM LSR: ByteAcc Position */ #define ITM_LSR_ByteAcc_Msk (1UL << ITM_LSR_ByteAcc_Pos) /*!< ITM LSR: ByteAcc Mask */ #define ITM_LSR_Access_Pos 1 /*!< ITM LSR: Access Position */ #define ITM_LSR_Access_Msk (1UL << ITM_LSR_Access_Pos) /*!< ITM LSR: Access Mask */ #define ITM_LSR_Present_Pos 0 /*!< ITM LSR: Present Position */ #define ITM_LSR_Present_Msk (1UL << ITM_LSR_Present_Pos) /*!< ITM LSR: Present Mask */ /*@}*/ /* end of group CMSIS_ITM */ /** \ingroup CMSIS_core_register \defgroup CMSIS_DWT Data Watchpoint and Trace (DWT) \brief Type definitions for the Data Watchpoint and Trace (DWT) @{ */ /** \brief Structure type to access the Data Watchpoint and Trace Register (DWT). */ typedef struct { __IO uint32_t CTRL; /*!< Offset: 0x000 (R/W) Control Register */ __IO uint32_t CYCCNT; /*!< Offset: 0x004 (R/W) Cycle Count Register */ __IO uint32_t CPICNT; /*!< Offset: 0x008 (R/W) CPI Count Register */ __IO uint32_t EXCCNT; /*!< Offset: 0x00C (R/W) Exception Overhead Count Register */ __IO uint32_t SLEEPCNT; /*!< Offset: 0x010 (R/W) Sleep Count Register */ __IO uint32_t LSUCNT; /*!< Offset: 0x014 (R/W) LSU Count Register */ __IO uint32_t FOLDCNT; /*!< Offset: 0x018 (R/W) Folded-instruction Count Register */ __I uint32_t PCSR; /*!< Offset: 0x01C (R/ ) Program Counter Sample Register */ __IO uint32_t COMP0; /*!< Offset: 0x020 (R/W) Comparator Register 0 */ __IO uint32_t MASK0; /*!< Offset: 0x024 (R/W) Mask Register 0 */ __IO uint32_t FUNCTION0; /*!< Offset: 0x028 (R/W) Function Register 0 */ uint32_t RESERVED0[1]; __IO uint32_t COMP1; /*!< Offset: 0x030 (R/W) Comparator Register 1 */ __IO uint32_t MASK1; /*!< Offset: 0x034 (R/W) Mask Register 1 */ __IO uint32_t FUNCTION1; /*!< Offset: 0x038 (R/W) Function Register 1 */ uint32_t RESERVED1[1]; __IO uint32_t COMP2; /*!< Offset: 0x040 (R/W) Comparator Register 2 */ __IO uint32_t MASK2; /*!< Offset: 0x044 (R/W) Mask Register 2 */ __IO uint32_t FUNCTION2; /*!< Offset: 0x048 (R/W) Function Register 2 */ uint32_t RESERVED2[1]; __IO uint32_t COMP3; /*!< Offset: 0x050 (R/W) Comparator Register 3 */ __IO uint32_t MASK3; /*!< Offset: 0x054 (R/W) Mask Register 3 */ __IO uint32_t FUNCTION3; /*!< Offset: 0x058 (R/W) Function Register 3 */ } DWT_Type; /* DWT Control Register Definitions */ #define DWT_CTRL_NUMCOMP_Pos 28 /*!< DWT CTRL: NUMCOMP Position */ #define DWT_CTRL_NUMCOMP_Msk (0xFUL << DWT_CTRL_NUMCOMP_Pos) /*!< DWT CTRL: NUMCOMP Mask */ #define DWT_CTRL_NOTRCPKT_Pos 27 /*!< DWT CTRL: NOTRCPKT Position */ #define DWT_CTRL_NOTRCPKT_Msk (0x1UL << DWT_CTRL_NOTRCPKT_Pos) /*!< DWT CTRL: NOTRCPKT Mask */ #define DWT_CTRL_NOEXTTRIG_Pos 26 /*!< DWT CTRL: NOEXTTRIG Position */ #define DWT_CTRL_NOEXTTRIG_Msk (0x1UL << DWT_CTRL_NOEXTTRIG_Pos) /*!< DWT CTRL: NOEXTTRIG Mask */ #define DWT_CTRL_NOCYCCNT_Pos 25 /*!< DWT CTRL: NOCYCCNT Position */ #define DWT_CTRL_NOCYCCNT_Msk (0x1UL << DWT_CTRL_NOCYCCNT_Pos) /*!< DWT CTRL: NOCYCCNT Mask */ #define DWT_CTRL_NOPRFCNT_Pos 24 /*!< DWT CTRL: NOPRFCNT Position */ #define DWT_CTRL_NOPRFCNT_Msk (0x1UL << DWT_CTRL_NOPRFCNT_Pos) /*!< DWT CTRL: NOPRFCNT Mask */ #define DWT_CTRL_CYCEVTENA_Pos 22 /*!< DWT CTRL: CYCEVTENA Position */ #define DWT_CTRL_CYCEVTENA_Msk (0x1UL << DWT_CTRL_CYCEVTENA_Pos) /*!< DWT CTRL: CYCEVTENA Mask */ #define DWT_CTRL_FOLDEVTENA_Pos 21 /*!< DWT CTRL: FOLDEVTENA Position */ #define DWT_CTRL_FOLDEVTENA_Msk (0x1UL << DWT_CTRL_FOLDEVTENA_Pos) /*!< DWT CTRL: FOLDEVTENA Mask */ #define DWT_CTRL_LSUEVTENA_Pos 20 /*!< DWT CTRL: LSUEVTENA Position */ #define DWT_CTRL_LSUEVTENA_Msk (0x1UL << DWT_CTRL_LSUEVTENA_Pos) /*!< DWT CTRL: LSUEVTENA Mask */ #define DWT_CTRL_SLEEPEVTENA_Pos 19 /*!< DWT CTRL: SLEEPEVTENA Position */ #define DWT_CTRL_SLEEPEVTENA_Msk (0x1UL << DWT_CTRL_SLEEPEVTENA_Pos) /*!< DWT CTRL: SLEEPEVTENA Mask */ #define DWT_CTRL_EXCEVTENA_Pos 18 /*!< DWT CTRL: EXCEVTENA Position */ #define DWT_CTRL_EXCEVTENA_Msk (0x1UL << DWT_CTRL_EXCEVTENA_Pos) /*!< DWT CTRL: EXCEVTENA Mask */ #define DWT_CTRL_CPIEVTENA_Pos 17 /*!< DWT CTRL: CPIEVTENA Position */ #define DWT_CTRL_CPIEVTENA_Msk (0x1UL << DWT_CTRL_CPIEVTENA_Pos) /*!< DWT CTRL: CPIEVTENA Mask */ #define DWT_CTRL_EXCTRCENA_Pos 16 /*!< DWT CTRL: EXCTRCENA Position */ #define DWT_CTRL_EXCTRCENA_Msk (0x1UL << DWT_CTRL_EXCTRCENA_Pos) /*!< DWT CTRL: EXCTRCENA Mask */ #define DWT_CTRL_PCSAMPLENA_Pos 12 /*!< DWT CTRL: PCSAMPLENA Position */ #define DWT_CTRL_PCSAMPLENA_Msk (0x1UL << DWT_CTRL_PCSAMPLENA_Pos) /*!< DWT CTRL: PCSAMPLENA Mask */ #define DWT_CTRL_SYNCTAP_Pos 10 /*!< DWT CTRL: SYNCTAP Position */ #define DWT_CTRL_SYNCTAP_Msk (0x3UL << DWT_CTRL_SYNCTAP_Pos) /*!< DWT CTRL: SYNCTAP Mask */ #define DWT_CTRL_CYCTAP_Pos 9 /*!< DWT CTRL: CYCTAP Position */ #define DWT_CTRL_CYCTAP_Msk (0x1UL << DWT_CTRL_CYCTAP_Pos) /*!< DWT CTRL: CYCTAP Mask */ #define DWT_CTRL_POSTINIT_Pos 5 /*!< DWT CTRL: POSTINIT Position */ #define DWT_CTRL_POSTINIT_Msk (0xFUL << DWT_CTRL_POSTINIT_Pos) /*!< DWT CTRL: POSTINIT Mask */ #define DWT_CTRL_POSTPRESET_Pos 1 /*!< DWT CTRL: POSTPRESET Position */ #define DWT_CTRL_POSTPRESET_Msk (0xFUL << DWT_CTRL_POSTPRESET_Pos) /*!< DWT CTRL: POSTPRESET Mask */ #define DWT_CTRL_CYCCNTENA_Pos 0 /*!< DWT CTRL: CYCCNTENA Position */ #define DWT_CTRL_CYCCNTENA_Msk (0x1UL << DWT_CTRL_CYCCNTENA_Pos) /*!< DWT CTRL: CYCCNTENA Mask */ /* DWT CPI Count Register Definitions */ #define DWT_CPICNT_CPICNT_Pos 0 /*!< DWT CPICNT: CPICNT Position */ #define DWT_CPICNT_CPICNT_Msk (0xFFUL << DWT_CPICNT_CPICNT_Pos) /*!< DWT CPICNT: CPICNT Mask */ /* DWT Exception Overhead Count Register Definitions */ #define DWT_EXCCNT_EXCCNT_Pos 0 /*!< DWT EXCCNT: EXCCNT Position */ #define DWT_EXCCNT_EXCCNT_Msk (0xFFUL << DWT_EXCCNT_EXCCNT_Pos) /*!< DWT EXCCNT: EXCCNT Mask */ /* DWT Sleep Count Register Definitions */ #define DWT_SLEEPCNT_SLEEPCNT_Pos 0 /*!< DWT SLEEPCNT: SLEEPCNT Position */ #define DWT_SLEEPCNT_SLEEPCNT_Msk (0xFFUL << DWT_SLEEPCNT_SLEEPCNT_Pos) /*!< DWT SLEEPCNT: SLEEPCNT Mask */ /* DWT LSU Count Register Definitions */ #define DWT_LSUCNT_LSUCNT_Pos 0 /*!< DWT LSUCNT: LSUCNT Position */ #define DWT_LSUCNT_LSUCNT_Msk (0xFFUL << DWT_LSUCNT_LSUCNT_Pos) /*!< DWT LSUCNT: LSUCNT Mask */ /* DWT Folded-instruction Count Register Definitions */ #define DWT_FOLDCNT_FOLDCNT_Pos 0 /*!< DWT FOLDCNT: FOLDCNT Position */ #define DWT_FOLDCNT_FOLDCNT_Msk (0xFFUL << DWT_FOLDCNT_FOLDCNT_Pos) /*!< DWT FOLDCNT: FOLDCNT Mask */ /* DWT Comparator Mask Register Definitions */ #define DWT_MASK_MASK_Pos 0 /*!< DWT MASK: MASK Position */ #define DWT_MASK_MASK_Msk (0x1FUL << DWT_MASK_MASK_Pos) /*!< DWT MASK: MASK Mask */ /* DWT Comparator Function Register Definitions */ #define DWT_FUNCTION_MATCHED_Pos 24 /*!< DWT FUNCTION: MATCHED Position */ #define DWT_FUNCTION_MATCHED_Msk (0x1UL << DWT_FUNCTION_MATCHED_Pos) /*!< DWT FUNCTION: MATCHED Mask */ #define DWT_FUNCTION_DATAVADDR1_Pos 16 /*!< DWT FUNCTION: DATAVADDR1 Position */ #define DWT_FUNCTION_DATAVADDR1_Msk (0xFUL << DWT_FUNCTION_DATAVADDR1_Pos) /*!< DWT FUNCTION: DATAVADDR1 Mask */ #define DWT_FUNCTION_DATAVADDR0_Pos 12 /*!< DWT FUNCTION: DATAVADDR0 Position */ #define DWT_FUNCTION_DATAVADDR0_Msk (0xFUL << DWT_FUNCTION_DATAVADDR0_Pos) /*!< DWT FUNCTION: DATAVADDR0 Mask */ #define DWT_FUNCTION_DATAVSIZE_Pos 10 /*!< DWT FUNCTION: DATAVSIZE Position */ #define DWT_FUNCTION_DATAVSIZE_Msk (0x3UL << DWT_FUNCTION_DATAVSIZE_Pos) /*!< DWT FUNCTION: DATAVSIZE Mask */ #define DWT_FUNCTION_LNK1ENA_Pos 9 /*!< DWT FUNCTION: LNK1ENA Position */ #define DWT_FUNCTION_LNK1ENA_Msk (0x1UL << DWT_FUNCTION_LNK1ENA_Pos) /*!< DWT FUNCTION: LNK1ENA Mask */ #define DWT_FUNCTION_DATAVMATCH_Pos 8 /*!< DWT FUNCTION: DATAVMATCH Position */ #define DWT_FUNCTION_DATAVMATCH_Msk (0x1UL << DWT_FUNCTION_DATAVMATCH_Pos) /*!< DWT FUNCTION: DATAVMATCH Mask */ #define DWT_FUNCTION_CYCMATCH_Pos 7 /*!< DWT FUNCTION: CYCMATCH Position */ #define DWT_FUNCTION_CYCMATCH_Msk (0x1UL << DWT_FUNCTION_CYCMATCH_Pos) /*!< DWT FUNCTION: CYCMATCH Mask */ #define DWT_FUNCTION_EMITRANGE_Pos 5 /*!< DWT FUNCTION: EMITRANGE Position */ #define DWT_FUNCTION_EMITRANGE_Msk (0x1UL << DWT_FUNCTION_EMITRANGE_Pos) /*!< DWT FUNCTION: EMITRANGE Mask */ #define DWT_FUNCTION_FUNCTION_Pos 0 /*!< DWT FUNCTION: FUNCTION Position */ #define DWT_FUNCTION_FUNCTION_Msk (0xFUL << DWT_FUNCTION_FUNCTION_Pos) /*!< DWT FUNCTION: FUNCTION Mask */ /*@}*/ /* end of group CMSIS_DWT */ /** \ingroup CMSIS_core_register \defgroup CMSIS_TPI Trace Port Interface (TPI) \brief Type definitions for the Trace Port Interface (TPI) @{ */ /** \brief Structure type to access the Trace Port Interface Register (TPI). */ typedef struct { __IO uint32_t SSPSR; /*!< Offset: 0x000 (R/ ) Supported Parallel Port Size Register */ __IO uint32_t CSPSR; /*!< Offset: 0x004 (R/W) Current Parallel Port Size Register */ uint32_t RESERVED0[2]; __IO uint32_t ACPR; /*!< Offset: 0x010 (R/W) Asynchronous Clock Prescaler Register */ uint32_t RESERVED1[55]; __IO uint32_t SPPR; /*!< Offset: 0x0F0 (R/W) Selected Pin Protocol Register */ uint32_t RESERVED2[131]; __I uint32_t FFSR; /*!< Offset: 0x300 (R/ ) Formatter and Flush Status Register */ __IO uint32_t FFCR; /*!< Offset: 0x304 (R/W) Formatter and Flush Control Register */ __I uint32_t FSCR; /*!< Offset: 0x308 (R/ ) Formatter Synchronization Counter Register */ uint32_t RESERVED3[759]; __I uint32_t TRIGGER; /*!< Offset: 0xEE8 (R/ ) TRIGGER */ __I uint32_t FIFO0; /*!< Offset: 0xEEC (R/ ) Integration ETM Data */ __I uint32_t ITATBCTR2; /*!< Offset: 0xEF0 (R/ ) ITATBCTR2 */ uint32_t RESERVED4[1]; __I uint32_t ITATBCTR0; /*!< Offset: 0xEF8 (R/ ) ITATBCTR0 */ __I uint32_t FIFO1; /*!< Offset: 0xEFC (R/ ) Integration ITM Data */ __IO uint32_t ITCTRL; /*!< Offset: 0xF00 (R/W) Integration Mode Control */ uint32_t RESERVED5[39]; __IO uint32_t CLAIMSET; /*!< Offset: 0xFA0 (R/W) Claim tag set */ __IO uint32_t CLAIMCLR; /*!< Offset: 0xFA4 (R/W) Claim tag clear */ uint32_t RESERVED7[8]; __I uint32_t DEVID; /*!< Offset: 0xFC8 (R/ ) TPIU_DEVID */ __I uint32_t DEVTYPE; /*!< Offset: 0xFCC (R/ ) TPIU_DEVTYPE */ } TPI_Type; /* TPI Asynchronous Clock Prescaler Register Definitions */ #define TPI_ACPR_PRESCALER_Pos 0 /*!< TPI ACPR: PRESCALER Position */ #define TPI_ACPR_PRESCALER_Msk (0x1FFFUL << TPI_ACPR_PRESCALER_Pos) /*!< TPI ACPR: PRESCALER Mask */ /* TPI Selected Pin Protocol Register Definitions */ #define TPI_SPPR_TXMODE_Pos 0 /*!< TPI SPPR: TXMODE Position */ #define TPI_SPPR_TXMODE_Msk (0x3UL << TPI_SPPR_TXMODE_Pos) /*!< TPI SPPR: TXMODE Mask */ /* TPI Formatter and Flush Status Register Definitions */ #define TPI_FFSR_FtNonStop_Pos 3 /*!< TPI FFSR: FtNonStop Position */ #define TPI_FFSR_FtNonStop_Msk (0x1UL << TPI_FFSR_FtNonStop_Pos) /*!< TPI FFSR: FtNonStop Mask */ #define TPI_FFSR_TCPresent_Pos 2 /*!< TPI FFSR: TCPresent Position */ #define TPI_FFSR_TCPresent_Msk (0x1UL << TPI_FFSR_TCPresent_Pos) /*!< TPI FFSR: TCPresent Mask */ #define TPI_FFSR_FtStopped_Pos 1 /*!< TPI FFSR: FtStopped Position */ #define TPI_FFSR_FtStopped_Msk (0x1UL << TPI_FFSR_FtStopped_Pos) /*!< TPI FFSR: FtStopped Mask */ #define TPI_FFSR_FlInProg_Pos 0 /*!< TPI FFSR: FlInProg Position */ #define TPI_FFSR_FlInProg_Msk (0x1UL << TPI_FFSR_FlInProg_Pos) /*!< TPI FFSR: FlInProg Mask */ /* TPI Formatter and Flush Control Register Definitions */ #define TPI_FFCR_TrigIn_Pos 8 /*!< TPI FFCR: TrigIn Position */ #define TPI_FFCR_TrigIn_Msk (0x1UL << TPI_FFCR_TrigIn_Pos) /*!< TPI FFCR: TrigIn Mask */ #define TPI_FFCR_EnFCont_Pos 1 /*!< TPI FFCR: EnFCont Position */ #define TPI_FFCR_EnFCont_Msk (0x1UL << TPI_FFCR_EnFCont_Pos) /*!< TPI FFCR: EnFCont Mask */ /* TPI TRIGGER Register Definitions */ #define TPI_TRIGGER_TRIGGER_Pos 0 /*!< TPI TRIGGER: TRIGGER Position */ #define TPI_TRIGGER_TRIGGER_Msk (0x1UL << TPI_TRIGGER_TRIGGER_Pos) /*!< TPI TRIGGER: TRIGGER Mask */ /* TPI Integration ETM Data Register Definitions (FIFO0) */ #define TPI_FIFO0_ITM_ATVALID_Pos 29 /*!< TPI FIFO0: ITM_ATVALID Position */ #define TPI_FIFO0_ITM_ATVALID_Msk (0x3UL << TPI_FIFO0_ITM_ATVALID_Pos) /*!< TPI FIFO0: ITM_ATVALID Mask */ #define TPI_FIFO0_ITM_bytecount_Pos 27 /*!< TPI FIFO0: ITM_bytecount Position */ #define TPI_FIFO0_ITM_bytecount_Msk (0x3UL << TPI_FIFO0_ITM_bytecount_Pos) /*!< TPI FIFO0: ITM_bytecount Mask */ #define TPI_FIFO0_ETM_ATVALID_Pos 26 /*!< TPI FIFO0: ETM_ATVALID Position */ #define TPI_FIFO0_ETM_ATVALID_Msk (0x3UL << TPI_FIFO0_ETM_ATVALID_Pos) /*!< TPI FIFO0: ETM_ATVALID Mask */ #define TPI_FIFO0_ETM_bytecount_Pos 24 /*!< TPI FIFO0: ETM_bytecount Position */ #define TPI_FIFO0_ETM_bytecount_Msk (0x3UL << TPI_FIFO0_ETM_bytecount_Pos) /*!< TPI FIFO0: ETM_bytecount Mask */ #define TPI_FIFO0_ETM2_Pos 16 /*!< TPI FIFO0: ETM2 Position */ #define TPI_FIFO0_ETM2_Msk (0xFFUL << TPI_FIFO0_ETM2_Pos) /*!< TPI FIFO0: ETM2 Mask */ #define TPI_FIFO0_ETM1_Pos 8 /*!< TPI FIFO0: ETM1 Position */ #define TPI_FIFO0_ETM1_Msk (0xFFUL << TPI_FIFO0_ETM1_Pos) /*!< TPI FIFO0: ETM1 Mask */ #define TPI_FIFO0_ETM0_Pos 0 /*!< TPI FIFO0: ETM0 Position */ #define TPI_FIFO0_ETM0_Msk (0xFFUL << TPI_FIFO0_ETM0_Pos) /*!< TPI FIFO0: ETM0 Mask */ /* TPI ITATBCTR2 Register Definitions */ #define TPI_ITATBCTR2_ATREADY_Pos 0 /*!< TPI ITATBCTR2: ATREADY Position */ #define TPI_ITATBCTR2_ATREADY_Msk (0x1UL << TPI_ITATBCTR2_ATREADY_Pos) /*!< TPI ITATBCTR2: ATREADY Mask */ /* TPI Integration ITM Data Register Definitions (FIFO1) */ #define TPI_FIFO1_ITM_ATVALID_Pos 29 /*!< TPI FIFO1: ITM_ATVALID Position */ #define TPI_FIFO1_ITM_ATVALID_Msk (0x3UL << TPI_FIFO1_ITM_ATVALID_Pos) /*!< TPI FIFO1: ITM_ATVALID Mask */ #define TPI_FIFO1_ITM_bytecount_Pos 27 /*!< TPI FIFO1: ITM_bytecount Position */ #define TPI_FIFO1_ITM_bytecount_Msk (0x3UL << TPI_FIFO1_ITM_bytecount_Pos) /*!< TPI FIFO1: ITM_bytecount Mask */ #define TPI_FIFO1_ETM_ATVALID_Pos 26 /*!< TPI FIFO1: ETM_ATVALID Position */ #define TPI_FIFO1_ETM_ATVALID_Msk (0x3UL << TPI_FIFO1_ETM_ATVALID_Pos) /*!< TPI FIFO1: ETM_ATVALID Mask */ #define TPI_FIFO1_ETM_bytecount_Pos 24 /*!< TPI FIFO1: ETM_bytecount Position */ #define TPI_FIFO1_ETM_bytecount_Msk (0x3UL << TPI_FIFO1_ETM_bytecount_Pos) /*!< TPI FIFO1: ETM_bytecount Mask */ #define TPI_FIFO1_ITM2_Pos 16 /*!< TPI FIFO1: ITM2 Position */ #define TPI_FIFO1_ITM2_Msk (0xFFUL << TPI_FIFO1_ITM2_Pos) /*!< TPI FIFO1: ITM2 Mask */ #define TPI_FIFO1_ITM1_Pos 8 /*!< TPI FIFO1: ITM1 Position */ #define TPI_FIFO1_ITM1_Msk (0xFFUL << TPI_FIFO1_ITM1_Pos) /*!< TPI FIFO1: ITM1 Mask */ #define TPI_FIFO1_ITM0_Pos 0 /*!< TPI FIFO1: ITM0 Position */ #define TPI_FIFO1_ITM0_Msk (0xFFUL << TPI_FIFO1_ITM0_Pos) /*!< TPI FIFO1: ITM0 Mask */ /* TPI ITATBCTR0 Register Definitions */ #define TPI_ITATBCTR0_ATREADY_Pos 0 /*!< TPI ITATBCTR0: ATREADY Position */ #define TPI_ITATBCTR0_ATREADY_Msk (0x1UL << TPI_ITATBCTR0_ATREADY_Pos) /*!< TPI ITATBCTR0: ATREADY Mask */ /* TPI Integration Mode Control Register Definitions */ #define TPI_ITCTRL_Mode_Pos 0 /*!< TPI ITCTRL: Mode Position */ #define TPI_ITCTRL_Mode_Msk (0x1UL << TPI_ITCTRL_Mode_Pos) /*!< TPI ITCTRL: Mode Mask */ /* TPI DEVID Register Definitions */ #define TPI_DEVID_NRZVALID_Pos 11 /*!< TPI DEVID: NRZVALID Position */ #define TPI_DEVID_NRZVALID_Msk (0x1UL << TPI_DEVID_NRZVALID_Pos) /*!< TPI DEVID: NRZVALID Mask */ #define TPI_DEVID_MANCVALID_Pos 10 /*!< TPI DEVID: MANCVALID Position */ #define TPI_DEVID_MANCVALID_Msk (0x1UL << TPI_DEVID_MANCVALID_Pos) /*!< TPI DEVID: MANCVALID Mask */ #define TPI_DEVID_PTINVALID_Pos 9 /*!< TPI DEVID: PTINVALID Position */ #define TPI_DEVID_PTINVALID_Msk (0x1UL << TPI_DEVID_PTINVALID_Pos) /*!< TPI DEVID: PTINVALID Mask */ #define TPI_DEVID_MinBufSz_Pos 6 /*!< TPI DEVID: MinBufSz Position */ #define TPI_DEVID_MinBufSz_Msk (0x7UL << TPI_DEVID_MinBufSz_Pos) /*!< TPI DEVID: MinBufSz Mask */ #define TPI_DEVID_AsynClkIn_Pos 5 /*!< TPI DEVID: AsynClkIn Position */ #define TPI_DEVID_AsynClkIn_Msk (0x1UL << TPI_DEVID_AsynClkIn_Pos) /*!< TPI DEVID: AsynClkIn Mask */ #define TPI_DEVID_NrTraceInput_Pos 0 /*!< TPI DEVID: NrTraceInput Position */ #define TPI_DEVID_NrTraceInput_Msk (0x1FUL << TPI_DEVID_NrTraceInput_Pos) /*!< TPI DEVID: NrTraceInput Mask */ /* TPI DEVTYPE Register Definitions */ #define TPI_DEVTYPE_SubType_Pos 0 /*!< TPI DEVTYPE: SubType Position */ #define TPI_DEVTYPE_SubType_Msk (0xFUL << TPI_DEVTYPE_SubType_Pos) /*!< TPI DEVTYPE: SubType Mask */ #define TPI_DEVTYPE_MajorType_Pos 4 /*!< TPI DEVTYPE: MajorType Position */ #define TPI_DEVTYPE_MajorType_Msk (0xFUL << TPI_DEVTYPE_MajorType_Pos) /*!< TPI DEVTYPE: MajorType Mask */ /*@}*/ /* end of group CMSIS_TPI */ #if (__MPU_PRESENT == 1) /** \ingroup CMSIS_core_register \defgroup CMSIS_MPU Memory Protection Unit (MPU) \brief Type definitions for the Memory Protection Unit (MPU) @{ */ /** \brief Structure type to access the Memory Protection Unit (MPU). */ typedef struct { __I uint32_t TYPE; /*!< Offset: 0x000 (R/ ) MPU Type Register */ __IO uint32_t CTRL; /*!< Offset: 0x004 (R/W) MPU Control Register */ __IO uint32_t RNR; /*!< Offset: 0x008 (R/W) MPU Region RNRber Register */ __IO uint32_t RBAR; /*!< Offset: 0x00C (R/W) MPU Region Base Address Register */ __IO uint32_t RASR; /*!< Offset: 0x010 (R/W) MPU Region Attribute and Size Register */ __IO uint32_t RBAR_A1; /*!< Offset: 0x014 (R/W) MPU Alias 1 Region Base Address Register */ __IO uint32_t RASR_A1; /*!< Offset: 0x018 (R/W) MPU Alias 1 Region Attribute and Size Register */ __IO uint32_t RBAR_A2; /*!< Offset: 0x01C (R/W) MPU Alias 2 Region Base Address Register */ __IO uint32_t RASR_A2; /*!< Offset: 0x020 (R/W) MPU Alias 2 Region Attribute and Size Register */ __IO uint32_t RBAR_A3; /*!< Offset: 0x024 (R/W) MPU Alias 3 Region Base Address Register */ __IO uint32_t RASR_A3; /*!< Offset: 0x028 (R/W) MPU Alias 3 Region Attribute and Size Register */ } MPU_Type; /* MPU Type Register */ #define MPU_TYPE_IREGION_Pos 16 /*!< MPU TYPE: IREGION Position */ #define MPU_TYPE_IREGION_Msk (0xFFUL << MPU_TYPE_IREGION_Pos) /*!< MPU TYPE: IREGION Mask */ #define MPU_TYPE_DREGION_Pos 8 /*!< MPU TYPE: DREGION Position */ #define MPU_TYPE_DREGION_Msk (0xFFUL << MPU_TYPE_DREGION_Pos) /*!< MPU TYPE: DREGION Mask */ #define MPU_TYPE_SEPARATE_Pos 0 /*!< MPU TYPE: SEPARATE Position */ #define MPU_TYPE_SEPARATE_Msk (1UL << MPU_TYPE_SEPARATE_Pos) /*!< MPU TYPE: SEPARATE Mask */ /* MPU Control Register */ #define MPU_CTRL_PRIVDEFENA_Pos 2 /*!< MPU CTRL: PRIVDEFENA Position */ #define MPU_CTRL_PRIVDEFENA_Msk (1UL << MPU_CTRL_PRIVDEFENA_Pos) /*!< MPU CTRL: PRIVDEFENA Mask */ #define MPU_CTRL_HFNMIENA_Pos 1 /*!< MPU CTRL: HFNMIENA Position */ #define MPU_CTRL_HFNMIENA_Msk (1UL << MPU_CTRL_HFNMIENA_Pos) /*!< MPU CTRL: HFNMIENA Mask */ #define MPU_CTRL_ENABLE_Pos 0 /*!< MPU CTRL: ENABLE Position */ #define MPU_CTRL_ENABLE_Msk (1UL << MPU_CTRL_ENABLE_Pos) /*!< MPU CTRL: ENABLE Mask */ /* MPU Region Number Register */ #define MPU_RNR_REGION_Pos 0 /*!< MPU RNR: REGION Position */ #define MPU_RNR_REGION_Msk (0xFFUL << MPU_RNR_REGION_Pos) /*!< MPU RNR: REGION Mask */ /* MPU Region Base Address Register */ #define MPU_RBAR_ADDR_Pos 5 /*!< MPU RBAR: ADDR Position */ #define MPU_RBAR_ADDR_Msk (0x7FFFFFFUL << MPU_RBAR_ADDR_Pos) /*!< MPU RBAR: ADDR Mask */ #define MPU_RBAR_VALID_Pos 4 /*!< MPU RBAR: VALID Position */ #define MPU_RBAR_VALID_Msk (1UL << MPU_RBAR_VALID_Pos) /*!< MPU RBAR: VALID Mask */ #define MPU_RBAR_REGION_Pos 0 /*!< MPU RBAR: REGION Position */ #define MPU_RBAR_REGION_Msk (0xFUL << MPU_RBAR_REGION_Pos) /*!< MPU RBAR: REGION Mask */ /* MPU Region Attribute and Size Register */ #define MPU_RASR_ATTRS_Pos 16 /*!< MPU RASR: MPU Region Attribute field Position */ #define MPU_RASR_ATTRS_Msk (0xFFFFUL << MPU_RASR_ATTRS_Pos) /*!< MPU RASR: MPU Region Attribute field Mask */ #define MPU_RASR_XN_Pos 28 /*!< MPU RASR: ATTRS.XN Position */ #define MPU_RASR_XN_Msk (1UL << MPU_RASR_XN_Pos) /*!< MPU RASR: ATTRS.XN Mask */ #define MPU_RASR_AP_Pos 24 /*!< MPU RASR: ATTRS.AP Position */ #define MPU_RASR_AP_Msk (0x7UL << MPU_RASR_AP_Pos) /*!< MPU RASR: ATTRS.AP Mask */ #define MPU_RASR_TEX_Pos 19 /*!< MPU RASR: ATTRS.TEX Position */ #define MPU_RASR_TEX_Msk (0x7UL << MPU_RASR_TEX_Pos) /*!< MPU RASR: ATTRS.TEX Mask */ #define MPU_RASR_S_Pos 18 /*!< MPU RASR: ATTRS.S Position */ #define MPU_RASR_S_Msk (1UL << MPU_RASR_S_Pos) /*!< MPU RASR: ATTRS.S Mask */ #define MPU_RASR_C_Pos 17 /*!< MPU RASR: ATTRS.C Position */ #define MPU_RASR_C_Msk (1UL << MPU_RASR_C_Pos) /*!< MPU RASR: ATTRS.C Mask */ #define MPU_RASR_B_Pos 16 /*!< MPU RASR: ATTRS.B Position */ #define MPU_RASR_B_Msk (1UL << MPU_RASR_B_Pos) /*!< MPU RASR: ATTRS.B Mask */ #define MPU_RASR_SRD_Pos 8 /*!< MPU RASR: Sub-Region Disable Position */ #define MPU_RASR_SRD_Msk (0xFFUL << MPU_RASR_SRD_Pos) /*!< MPU RASR: Sub-Region Disable Mask */ #define MPU_RASR_SIZE_Pos 1 /*!< MPU RASR: Region Size Field Position */ #define MPU_RASR_SIZE_Msk (0x1FUL << MPU_RASR_SIZE_Pos) /*!< MPU RASR: Region Size Field Mask */ #define MPU_RASR_ENABLE_Pos 0 /*!< MPU RASR: Region enable bit Position */ #define MPU_RASR_ENABLE_Msk (1UL << MPU_RASR_ENABLE_Pos) /*!< MPU RASR: Region enable bit Disable Mask */ /*@} end of group CMSIS_MPU */ #endif /** \ingroup CMSIS_core_register \defgroup CMSIS_CoreDebug Core Debug Registers (CoreDebug) \brief Type definitions for the Core Debug Registers @{ */ /** \brief Structure type to access the Core Debug Register (CoreDebug). */ typedef struct { __IO uint32_t DHCSR; /*!< Offset: 0x000 (R/W) Debug Halting Control and Status Register */ __O uint32_t DCRSR; /*!< Offset: 0x004 ( /W) Debug Core Register Selector Register */ __IO uint32_t DCRDR; /*!< Offset: 0x008 (R/W) Debug Core Register Data Register */ __IO uint32_t DEMCR; /*!< Offset: 0x00C (R/W) Debug Exception and Monitor Control Register */ } CoreDebug_Type; /* Debug Halting Control and Status Register */ #define CoreDebug_DHCSR_DBGKEY_Pos 16 /*!< CoreDebug DHCSR: DBGKEY Position */ #define CoreDebug_DHCSR_DBGKEY_Msk (0xFFFFUL << CoreDebug_DHCSR_DBGKEY_Pos) /*!< CoreDebug DHCSR: DBGKEY Mask */ #define CoreDebug_DHCSR_S_RESET_ST_Pos 25 /*!< CoreDebug DHCSR: S_RESET_ST Position */ #define CoreDebug_DHCSR_S_RESET_ST_Msk (1UL << CoreDebug_DHCSR_S_RESET_ST_Pos) /*!< CoreDebug DHCSR: S_RESET_ST Mask */ #define CoreDebug_DHCSR_S_RETIRE_ST_Pos 24 /*!< CoreDebug DHCSR: S_RETIRE_ST Position */ #define CoreDebug_DHCSR_S_RETIRE_ST_Msk (1UL << CoreDebug_DHCSR_S_RETIRE_ST_Pos) /*!< CoreDebug DHCSR: S_RETIRE_ST Mask */ #define CoreDebug_DHCSR_S_LOCKUP_Pos 19 /*!< CoreDebug DHCSR: S_LOCKUP Position */ #define CoreDebug_DHCSR_S_LOCKUP_Msk (1UL << CoreDebug_DHCSR_S_LOCKUP_Pos) /*!< CoreDebug DHCSR: S_LOCKUP Mask */ #define CoreDebug_DHCSR_S_SLEEP_Pos 18 /*!< CoreDebug DHCSR: S_SLEEP Position */ #define CoreDebug_DHCSR_S_SLEEP_Msk (1UL << CoreDebug_DHCSR_S_SLEEP_Pos) /*!< CoreDebug DHCSR: S_SLEEP Mask */ #define CoreDebug_DHCSR_S_HALT_Pos 17 /*!< CoreDebug DHCSR: S_HALT Position */ #define CoreDebug_DHCSR_S_HALT_Msk (1UL << CoreDebug_DHCSR_S_HALT_Pos) /*!< CoreDebug DHCSR: S_HALT Mask */ #define CoreDebug_DHCSR_S_REGRDY_Pos 16 /*!< CoreDebug DHCSR: S_REGRDY Position */ #define CoreDebug_DHCSR_S_REGRDY_Msk (1UL << CoreDebug_DHCSR_S_REGRDY_Pos) /*!< CoreDebug DHCSR: S_REGRDY Mask */ #define CoreDebug_DHCSR_C_SNAPSTALL_Pos 5 /*!< CoreDebug DHCSR: C_SNAPSTALL Position */ #define CoreDebug_DHCSR_C_SNAPSTALL_Msk (1UL << CoreDebug_DHCSR_C_SNAPSTALL_Pos) /*!< CoreDebug DHCSR: C_SNAPSTALL Mask */ #define CoreDebug_DHCSR_C_MASKINTS_Pos 3 /*!< CoreDebug DHCSR: C_MASKINTS Position */ #define CoreDebug_DHCSR_C_MASKINTS_Msk (1UL << CoreDebug_DHCSR_C_MASKINTS_Pos) /*!< CoreDebug DHCSR: C_MASKINTS Mask */ #define CoreDebug_DHCSR_C_STEP_Pos 2 /*!< CoreDebug DHCSR: C_STEP Position */ #define CoreDebug_DHCSR_C_STEP_Msk (1UL << CoreDebug_DHCSR_C_STEP_Pos) /*!< CoreDebug DHCSR: C_STEP Mask */ #define CoreDebug_DHCSR_C_HALT_Pos 1 /*!< CoreDebug DHCSR: C_HALT Position */ #define CoreDebug_DHCSR_C_HALT_Msk (1UL << CoreDebug_DHCSR_C_HALT_Pos) /*!< CoreDebug DHCSR: C_HALT Mask */ #define CoreDebug_DHCSR_C_DEBUGEN_Pos 0 /*!< CoreDebug DHCSR: C_DEBUGEN Position */ #define CoreDebug_DHCSR_C_DEBUGEN_Msk (1UL << CoreDebug_DHCSR_C_DEBUGEN_Pos) /*!< CoreDebug DHCSR: C_DEBUGEN Mask */ /* Debug Core Register Selector Register */ #define CoreDebug_DCRSR_REGWnR_Pos 16 /*!< CoreDebug DCRSR: REGWnR Position */ #define CoreDebug_DCRSR_REGWnR_Msk (1UL << CoreDebug_DCRSR_REGWnR_Pos) /*!< CoreDebug DCRSR: REGWnR Mask */ #define CoreDebug_DCRSR_REGSEL_Pos 0 /*!< CoreDebug DCRSR: REGSEL Position */ #define CoreDebug_DCRSR_REGSEL_Msk (0x1FUL << CoreDebug_DCRSR_REGSEL_Pos) /*!< CoreDebug DCRSR: REGSEL Mask */ /* Debug Exception and Monitor Control Register */ #define CoreDebug_DEMCR_TRCENA_Pos 24 /*!< CoreDebug DEMCR: TRCENA Position */ #define CoreDebug_DEMCR_TRCENA_Msk (1UL << CoreDebug_DEMCR_TRCENA_Pos) /*!< CoreDebug DEMCR: TRCENA Mask */ #define CoreDebug_DEMCR_MON_REQ_Pos 19 /*!< CoreDebug DEMCR: MON_REQ Position */ #define CoreDebug_DEMCR_MON_REQ_Msk (1UL << CoreDebug_DEMCR_MON_REQ_Pos) /*!< CoreDebug DEMCR: MON_REQ Mask */ #define CoreDebug_DEMCR_MON_STEP_Pos 18 /*!< CoreDebug DEMCR: MON_STEP Position */ #define CoreDebug_DEMCR_MON_STEP_Msk (1UL << CoreDebug_DEMCR_MON_STEP_Pos) /*!< CoreDebug DEMCR: MON_STEP Mask */ #define CoreDebug_DEMCR_MON_PEND_Pos 17 /*!< CoreDebug DEMCR: MON_PEND Position */ #define CoreDebug_DEMCR_MON_PEND_Msk (1UL << CoreDebug_DEMCR_MON_PEND_Pos) /*!< CoreDebug DEMCR: MON_PEND Mask */ #define CoreDebug_DEMCR_MON_EN_Pos 16 /*!< CoreDebug DEMCR: MON_EN Position */ #define CoreDebug_DEMCR_MON_EN_Msk (1UL << CoreDebug_DEMCR_MON_EN_Pos) /*!< CoreDebug DEMCR: MON_EN Mask */ #define CoreDebug_DEMCR_VC_HARDERR_Pos 10 /*!< CoreDebug DEMCR: VC_HARDERR Position */ #define CoreDebug_DEMCR_VC_HARDERR_Msk (1UL << CoreDebug_DEMCR_VC_HARDERR_Pos) /*!< CoreDebug DEMCR: VC_HARDERR Mask */ #define CoreDebug_DEMCR_VC_INTERR_Pos 9 /*!< CoreDebug DEMCR: VC_INTERR Position */ #define CoreDebug_DEMCR_VC_INTERR_Msk (1UL << CoreDebug_DEMCR_VC_INTERR_Pos) /*!< CoreDebug DEMCR: VC_INTERR Mask */ #define CoreDebug_DEMCR_VC_BUSERR_Pos 8 /*!< CoreDebug DEMCR: VC_BUSERR Position */ #define CoreDebug_DEMCR_VC_BUSERR_Msk (1UL << CoreDebug_DEMCR_VC_BUSERR_Pos) /*!< CoreDebug DEMCR: VC_BUSERR Mask */ #define CoreDebug_DEMCR_VC_STATERR_Pos 7 /*!< CoreDebug DEMCR: VC_STATERR Position */ #define CoreDebug_DEMCR_VC_STATERR_Msk (1UL << CoreDebug_DEMCR_VC_STATERR_Pos) /*!< CoreDebug DEMCR: VC_STATERR Mask */ #define CoreDebug_DEMCR_VC_CHKERR_Pos 6 /*!< CoreDebug DEMCR: VC_CHKERR Position */ #define CoreDebug_DEMCR_VC_CHKERR_Msk (1UL << CoreDebug_DEMCR_VC_CHKERR_Pos) /*!< CoreDebug DEMCR: VC_CHKERR Mask */ #define CoreDebug_DEMCR_VC_NOCPERR_Pos 5 /*!< CoreDebug DEMCR: VC_NOCPERR Position */ #define CoreDebug_DEMCR_VC_NOCPERR_Msk (1UL << CoreDebug_DEMCR_VC_NOCPERR_Pos) /*!< CoreDebug DEMCR: VC_NOCPERR Mask */ #define CoreDebug_DEMCR_VC_MMERR_Pos 4 /*!< CoreDebug DEMCR: VC_MMERR Position */ #define CoreDebug_DEMCR_VC_MMERR_Msk (1UL << CoreDebug_DEMCR_VC_MMERR_Pos) /*!< CoreDebug DEMCR: VC_MMERR Mask */ #define CoreDebug_DEMCR_VC_CORERESET_Pos 0 /*!< CoreDebug DEMCR: VC_CORERESET Position */ #define CoreDebug_DEMCR_VC_CORERESET_Msk (1UL << CoreDebug_DEMCR_VC_CORERESET_Pos) /*!< CoreDebug DEMCR: VC_CORERESET Mask */ /*@} end of group CMSIS_CoreDebug */ /** \ingroup CMSIS_core_register \defgroup CMSIS_core_base Core Definitions \brief Definitions for base addresses, unions, and structures. @{ */ /* Memory mapping of Cortex-M3 Hardware */ #define SCS_BASE (0xE000E000UL) /*!< System Control Space Base Address */ #define ITM_BASE (0xE0000000UL) /*!< ITM Base Address */ #define DWT_BASE (0xE0001000UL) /*!< DWT Base Address */ #define TPI_BASE (0xE0040000UL) /*!< TPI Base Address */ #define CoreDebug_BASE (0xE000EDF0UL) /*!< Core Debug Base Address */ #define SysTick_BASE (SCS_BASE + 0x0010UL) /*!< SysTick Base Address */ #define NVIC_BASE (SCS_BASE + 0x0100UL) /*!< NVIC Base Address */ #define SCB_BASE (SCS_BASE + 0x0D00UL) /*!< System Control Block Base Address */ #define SCnSCB ((SCnSCB_Type *) SCS_BASE ) /*!< System control Register not in SCB */ #define SCB ((SCB_Type *) SCB_BASE ) /*!< SCB configuration struct */ #define SysTick ((SysTick_Type *) SysTick_BASE ) /*!< SysTick configuration struct */ #define NVIC ((NVIC_Type *) NVIC_BASE ) /*!< NVIC configuration struct */ #define ITM ((ITM_Type *) ITM_BASE ) /*!< ITM configuration struct */ #define DWT ((DWT_Type *) DWT_BASE ) /*!< DWT configuration struct */ #define TPI ((TPI_Type *) TPI_BASE ) /*!< TPI configuration struct */ #define CoreDebug ((CoreDebug_Type *) CoreDebug_BASE) /*!< Core Debug configuration struct */ #if (__MPU_PRESENT == 1) #define MPU_BASE (SCS_BASE + 0x0D90UL) /*!< Memory Protection Unit */ #define MPU ((MPU_Type *) MPU_BASE ) /*!< Memory Protection Unit */ #endif /*@} */ /******************************************************************************* * Hardware Abstraction Layer Core Function Interface contains: - Core NVIC Functions - Core SysTick Functions - Core Debug Functions - Core Register Access Functions ******************************************************************************/ /** \defgroup CMSIS_Core_FunctionInterface Functions and Instructions Reference */ /* ########################## NVIC functions #################################### */ /** \ingroup CMSIS_Core_FunctionInterface \defgroup CMSIS_Core_NVICFunctions NVIC Functions \brief Functions that manage interrupts and exceptions via the NVIC. @{ */ /** \brief Set Priority Grouping The function sets the priority grouping field using the required unlock sequence. The parameter PriorityGroup is assigned to the field SCB->AIRCR [10:8] PRIGROUP field. Only values from 0..7 are used. In case of a conflict between priority grouping and available priority bits (__NVIC_PRIO_BITS), the smallest possible priority group is set. \param [in] PriorityGroup Priority grouping field. */ __STATIC_INLINE void NVIC_SetPriorityGrouping(uint32_t PriorityGroup) { uint32_t reg_value; uint32_t PriorityGroupTmp = (PriorityGroup & (uint32_t)0x07); /* only values 0..7 are used */ reg_value = SCB->AIRCR; /* read old register configuration */ reg_value &= ~(SCB_AIRCR_VECTKEY_Msk | SCB_AIRCR_PRIGROUP_Msk); /* clear bits to change */ reg_value = (reg_value | ((uint32_t)0x5FA << SCB_AIRCR_VECTKEY_Pos) | (PriorityGroupTmp << 8)); /* Insert write key and priorty group */ SCB->AIRCR = reg_value; } /** \brief Get Priority Grouping The function reads the priority grouping field from the NVIC Interrupt Controller. \return Priority grouping field (SCB->AIRCR [10:8] PRIGROUP field). */ __STATIC_INLINE uint32_t NVIC_GetPriorityGrouping(void) { return ((SCB->AIRCR & SCB_AIRCR_PRIGROUP_Msk) >> SCB_AIRCR_PRIGROUP_Pos); /* read priority grouping field */ } /** \brief Enable External Interrupt The function enables a device-specific interrupt in the NVIC interrupt controller. \param [in] IRQn External interrupt number. Value cannot be negative. */ __STATIC_INLINE void NVIC_EnableIRQ(IRQn_Type IRQn) { NVIC->ISER[((uint32_t)(IRQn) >> 5)] = (1 << ((uint32_t)(IRQn) & 0x1F)); /* enable interrupt */ } /** \brief Disable External Interrupt The function disables a device-specific interrupt in the NVIC interrupt controller. \param [in] IRQn External interrupt number. Value cannot be negative. */ __STATIC_INLINE void NVIC_DisableIRQ(IRQn_Type IRQn) { NVIC->ICER[((uint32_t)(IRQn) >> 5)] = (1 << ((uint32_t)(IRQn) & 0x1F)); /* disable interrupt */ } /** \brief Get Pending Interrupt The function reads the pending register in the NVIC and returns the pending bit for the specified interrupt. \param [in] IRQn Interrupt number. \return 0 Interrupt status is not pending. \return 1 Interrupt status is pending. */ __STATIC_INLINE uint32_t NVIC_GetPendingIRQ(IRQn_Type IRQn) { return((uint32_t) ((NVIC->ISPR[(uint32_t)(IRQn) >> 5] & (1 << ((uint32_t)(IRQn) & 0x1F)))?1:0)); /* Return 1 if pending else 0 */ } /** \brief Set Pending Interrupt The function sets the pending bit of an external interrupt. \param [in] IRQn Interrupt number. Value cannot be negative. */ __STATIC_INLINE void NVIC_SetPendingIRQ(IRQn_Type IRQn) { NVIC->ISPR[((uint32_t)(IRQn) >> 5)] = (1 << ((uint32_t)(IRQn) & 0x1F)); /* set interrupt pending */ } /** \brief Clear Pending Interrupt The function clears the pending bit of an external interrupt. \param [in] IRQn External interrupt number. Value cannot be negative. */ __STATIC_INLINE void NVIC_ClearPendingIRQ(IRQn_Type IRQn) { NVIC->ICPR[((uint32_t)(IRQn) >> 5)] = (1 << ((uint32_t)(IRQn) & 0x1F)); /* Clear pending interrupt */ } /** \brief Get Active Interrupt The function reads the active register in NVIC and returns the active bit. \param [in] IRQn Interrupt number. \return 0 Interrupt status is not active. \return 1 Interrupt status is active. */ __STATIC_INLINE uint32_t NVIC_GetActive(IRQn_Type IRQn) { return((uint32_t)((NVIC->IABR[(uint32_t)(IRQn) >> 5] & (1 << ((uint32_t)(IRQn) & 0x1F)))?1:0)); /* Return 1 if active else 0 */ } /** \brief Set Interrupt Priority The function sets the priority of an interrupt. \note The priority cannot be set for every core interrupt. \param [in] IRQn Interrupt number. \param [in] priority Priority to set. */ __STATIC_INLINE void NVIC_SetPriority(IRQn_Type IRQn, uint32_t priority) { if(IRQn < 0) { SCB->SHP[((uint32_t)(IRQn) & 0xF)-4] = ((priority << (8 - __NVIC_PRIO_BITS)) & 0xff); } /* set Priority for Cortex-M System Interrupts */ else { NVIC->IP[(uint32_t)(IRQn)] = ((priority << (8 - __NVIC_PRIO_BITS)) & 0xff); } /* set Priority for device specific Interrupts */ } /** \brief Get Interrupt Priority The function reads the priority of an interrupt. The interrupt number can be positive to specify an external (device specific) interrupt, or negative to specify an internal (core) interrupt. \param [in] IRQn Interrupt number. \return Interrupt Priority. Value is aligned automatically to the implemented priority bits of the microcontroller. */ __STATIC_INLINE uint32_t NVIC_GetPriority(IRQn_Type IRQn) { if(IRQn < 0) { return((uint32_t)(SCB->SHP[((uint32_t)(IRQn) & 0xF)-4] >> (8 - __NVIC_PRIO_BITS))); } /* get priority for Cortex-M system interrupts */ else { return((uint32_t)(NVIC->IP[(uint32_t)(IRQn)] >> (8 - __NVIC_PRIO_BITS))); } /* get priority for device specific interrupts */ } /** \brief Encode Priority The function encodes the priority for an interrupt with the given priority group, preemptive priority value, and subpriority value. In case of a conflict between priority grouping and available priority bits (__NVIC_PRIO_BITS), the samllest possible priority group is set. \param [in] PriorityGroup Used priority group. \param [in] PreemptPriority Preemptive priority value (starting from 0). \param [in] SubPriority Subpriority value (starting from 0). \return Encoded priority. Value can be used in the function \ref NVIC_SetPriority(). */ __STATIC_INLINE uint32_t NVIC_EncodePriority (uint32_t PriorityGroup, uint32_t PreemptPriority, uint32_t SubPriority) { uint32_t PriorityGroupTmp = (PriorityGroup & 0x07); /* only values 0..7 are used */ uint32_t PreemptPriorityBits; uint32_t SubPriorityBits; PreemptPriorityBits = ((7 - PriorityGroupTmp) > __NVIC_PRIO_BITS) ? __NVIC_PRIO_BITS : 7 - PriorityGroupTmp; SubPriorityBits = ((PriorityGroupTmp + __NVIC_PRIO_BITS) < 7) ? 0 : PriorityGroupTmp - 7 + __NVIC_PRIO_BITS; return ( ((PreemptPriority & ((1 << (PreemptPriorityBits)) - 1)) << SubPriorityBits) | ((SubPriority & ((1 << (SubPriorityBits )) - 1))) ); } /** \brief Decode Priority The function decodes an interrupt priority value with a given priority group to preemptive priority value and subpriority value. In case of a conflict between priority grouping and available priority bits (__NVIC_PRIO_BITS) the samllest possible priority group is set. \param [in] Priority Priority value, which can be retrieved with the function \ref NVIC_GetPriority(). \param [in] PriorityGroup Used priority group. \param [out] pPreemptPriority Preemptive priority value (starting from 0). \param [out] pSubPriority Subpriority value (starting from 0). */ __STATIC_INLINE void NVIC_DecodePriority (uint32_t Priority, uint32_t PriorityGroup, uint32_t* pPreemptPriority, uint32_t* pSubPriority) { uint32_t PriorityGroupTmp = (PriorityGroup & 0x07); /* only values 0..7 are used */ uint32_t PreemptPriorityBits; uint32_t SubPriorityBits; PreemptPriorityBits = ((7 - PriorityGroupTmp) > __NVIC_PRIO_BITS) ? __NVIC_PRIO_BITS : 7 - PriorityGroupTmp; SubPriorityBits = ((PriorityGroupTmp + __NVIC_PRIO_BITS) < 7) ? 0 : PriorityGroupTmp - 7 + __NVIC_PRIO_BITS; *pPreemptPriority = (Priority >> SubPriorityBits) & ((1 << (PreemptPriorityBits)) - 1); *pSubPriority = (Priority ) & ((1 << (SubPriorityBits )) - 1); } /** \brief System Reset The function initiates a system reset request to reset the MCU. */ __STATIC_INLINE void NVIC_SystemReset(void) { __DSB(); /* Ensure all outstanding memory accesses included buffered write are completed before reset */ SCB->AIRCR = ((0x5FA << SCB_AIRCR_VECTKEY_Pos) | (SCB->AIRCR & SCB_AIRCR_PRIGROUP_Msk) | SCB_AIRCR_SYSRESETREQ_Msk); /* Keep priority group unchanged */ __DSB(); /* Ensure completion of memory access */ while(1); /* wait until reset */ } /*@} end of CMSIS_Core_NVICFunctions */ /* ################################## SysTick function ############################################ */ /** \ingroup CMSIS_Core_FunctionInterface \defgroup CMSIS_Core_SysTickFunctions SysTick Functions \brief Functions that configure the System. @{ */ #if (__Vendor_SysTickConfig == 0) /** \brief System Tick Configuration The function initializes the System Timer and its interrupt, and starts the System Tick Timer. Counter is in free running mode to generate periodic interrupts. \param [in] ticks Number of ticks between two interrupts. \return 0 Function succeeded. \return 1 Function failed. \note When the variable __Vendor_SysTickConfig is set to 1, then the function SysTick_Config is not included. In this case, the file device.h must contain a vendor-specific implementation of this function. */ __STATIC_INLINE uint32_t SysTick_Config(uint32_t ticks) { if ((ticks - 1) > SysTick_LOAD_RELOAD_Msk) return (1); /* Reload value impossible */ SysTick->LOAD = ticks - 1; /* set reload register */ NVIC_SetPriority (SysTick_IRQn, (1<<__NVIC_PRIO_BITS) - 1); /* set Priority for Systick Interrupt */ SysTick->VAL = 0; /* Load the SysTick Counter Value */ SysTick->CTRL = SysTick_CTRL_CLKSOURCE_Msk | SysTick_CTRL_TICKINT_Msk | SysTick_CTRL_ENABLE_Msk; /* Enable SysTick IRQ and SysTick Timer */ return (0); /* Function successful */ } #endif /*@} end of CMSIS_Core_SysTickFunctions */ /* ##################################### Debug In/Output function ########################################### */ /** \ingroup CMSIS_Core_FunctionInterface \defgroup CMSIS_core_DebugFunctions ITM Functions \brief Functions that access the ITM debug interface. @{ */ extern volatile int32_t ITM_RxBuffer; /*!< External variable to receive characters. */ #define ITM_RXBUFFER_EMPTY 0x5AA55AA5 /*!< Value identifying \ref ITM_RxBuffer is ready for next character. */ /** \brief ITM Send Character The function transmits a character via the ITM channel 0, and \li Just returns when no debugger is connected that has booked the output. \li Is blocking when a debugger is connected, but the previous character sent has not been transmitted. \param [in] ch Character to transmit. \returns Character to transmit. */ __STATIC_INLINE uint32_t ITM_SendChar (uint32_t ch) { if ((ITM->TCR & ITM_TCR_ITMENA_Msk) && /* ITM enabled */ (ITM->TER & (1UL << 0) ) ) /* ITM Port #0 enabled */ { while (ITM->PORT[0].u32 == 0); ITM->PORT[0].u8 = (uint8_t) ch; } return (ch); } /** \brief ITM Receive Character The function inputs a character via the external variable \ref ITM_RxBuffer. \return Received character. \return -1 No character pending. */ __STATIC_INLINE int32_t ITM_ReceiveChar (void) { int32_t ch = -1; /* no character available */ if (ITM_RxBuffer != ITM_RXBUFFER_EMPTY) { ch = ITM_RxBuffer; ITM_RxBuffer = ITM_RXBUFFER_EMPTY; /* ready for next character */ } return (ch); } /** \brief ITM Check Character The function checks whether a character is pending for reading in the variable \ref ITM_RxBuffer. \return 0 No character available. \return 1 Character available. */ __STATIC_INLINE int32_t ITM_CheckChar (void) { if (ITM_RxBuffer == ITM_RXBUFFER_EMPTY) { return (0); /* no character available */ } else { return (1); /* character available */ } } /*@} end of CMSIS_core_DebugFunctions */ #endif /* __CORE_CM3_H_DEPENDANT */ #endif /* __CMSIS_GENERIC */ #ifdef __cplusplus } #endif ================================================ FILE: Zelig/mbed/TARGET_NUCLEO_L152RE/core_cm4.h ================================================ /**************************************************************************//** * @file core_cm4.h * @brief CMSIS Cortex-M4 Core Peripheral Access Layer Header File * @version V3.20 * @date 25. February 2013 * * @note * ******************************************************************************/ /* Copyright (c) 2009 - 2013 ARM LIMITED All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: - Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. - Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. - Neither the name of ARM 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 COPYRIGHT HOLDERS AND 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. ---------------------------------------------------------------------------*/ #if defined ( __ICCARM__ ) #pragma system_include /* treat file as system include file for MISRA check */ #endif #ifdef __cplusplus extern "C" { #endif #ifndef __CORE_CM4_H_GENERIC #define __CORE_CM4_H_GENERIC /** \page CMSIS_MISRA_Exceptions MISRA-C:2004 Compliance Exceptions CMSIS violates the following MISRA-C:2004 rules: \li Required Rule 8.5, object/function definition in header file.
Function definitions in header files are used to allow 'inlining'. \li Required Rule 18.4, declaration of union type or object of union type: '{...}'.
Unions are used for effective representation of core registers. \li Advisory Rule 19.7, Function-like macro defined.
Function-like macros are used to allow more efficient code. */ /******************************************************************************* * CMSIS definitions ******************************************************************************/ /** \ingroup Cortex_M4 @{ */ /* CMSIS CM4 definitions */ #define __CM4_CMSIS_VERSION_MAIN (0x03) /*!< [31:16] CMSIS HAL main version */ #define __CM4_CMSIS_VERSION_SUB (0x20) /*!< [15:0] CMSIS HAL sub version */ #define __CM4_CMSIS_VERSION ((__CM4_CMSIS_VERSION_MAIN << 16) | \ __CM4_CMSIS_VERSION_SUB ) /*!< CMSIS HAL version number */ #define __CORTEX_M (0x04) /*!< Cortex-M Core */ #if defined ( __CC_ARM ) #define __ASM __asm /*!< asm keyword for ARM Compiler */ #define __INLINE __inline /*!< inline keyword for ARM Compiler */ #define __STATIC_INLINE static __inline #elif defined ( __ICCARM__ ) #define __ASM __asm /*!< asm keyword for IAR Compiler */ #define __INLINE inline /*!< inline keyword for IAR Compiler. Only available in High optimization mode! */ #define __STATIC_INLINE static inline #elif defined ( __TMS470__ ) #define __ASM __asm /*!< asm keyword for TI CCS Compiler */ #define __STATIC_INLINE static inline #elif defined ( __GNUC__ ) #define __ASM __asm /*!< asm keyword for GNU Compiler */ #define __INLINE inline /*!< inline keyword for GNU Compiler */ #define __STATIC_INLINE static inline #elif defined ( __TASKING__ ) #define __ASM __asm /*!< asm keyword for TASKING Compiler */ #define __INLINE inline /*!< inline keyword for TASKING Compiler */ #define __STATIC_INLINE static inline #endif /** __FPU_USED indicates whether an FPU is used or not. For this, __FPU_PRESENT has to be checked prior to making use of FPU specific registers and functions. */ #if defined ( __CC_ARM ) #if defined __TARGET_FPU_VFP #if (__FPU_PRESENT == 1) #define __FPU_USED 1 #else #warning "Compiler generates FPU instructions for a device without an FPU (check __FPU_PRESENT)" #define __FPU_USED 0 #endif #else #define __FPU_USED 0 #endif #elif defined ( __ICCARM__ ) #if defined __ARMVFP__ #if (__FPU_PRESENT == 1) #define __FPU_USED 1 #else #warning "Compiler generates FPU instructions for a device without an FPU (check __FPU_PRESENT)" #define __FPU_USED 0 #endif #else #define __FPU_USED 0 #endif #elif defined ( __TMS470__ ) #if defined __TI_VFP_SUPPORT__ #if (__FPU_PRESENT == 1) #define __FPU_USED 1 #else #warning "Compiler generates FPU instructions for a device without an FPU (check __FPU_PRESENT)" #define __FPU_USED 0 #endif #else #define __FPU_USED 0 #endif #elif defined ( __GNUC__ ) #if defined (__VFP_FP__) && !defined(__SOFTFP__) #if (__FPU_PRESENT == 1) #define __FPU_USED 1 #else #warning "Compiler generates FPU instructions for a device without an FPU (check __FPU_PRESENT)" #define __FPU_USED 0 #endif #else #define __FPU_USED 0 #endif #elif defined ( __TASKING__ ) #if defined __FPU_VFP__ #if (__FPU_PRESENT == 1) #define __FPU_USED 1 #else #error "Compiler generates FPU instructions for a device without an FPU (check __FPU_PRESENT)" #define __FPU_USED 0 #endif #else #define __FPU_USED 0 #endif #endif #include /* standard types definitions */ #include /* Core Instruction Access */ #include /* Core Function Access */ #include /* Compiler specific SIMD Intrinsics */ #endif /* __CORE_CM4_H_GENERIC */ #ifndef __CMSIS_GENERIC #ifndef __CORE_CM4_H_DEPENDANT #define __CORE_CM4_H_DEPENDANT /* check device defines and use defaults */ #if defined __CHECK_DEVICE_DEFINES #ifndef __CM4_REV #define __CM4_REV 0x0000 #warning "__CM4_REV not defined in device header file; using default!" #endif #ifndef __FPU_PRESENT #define __FPU_PRESENT 0 #warning "__FPU_PRESENT not defined in device header file; using default!" #endif #ifndef __MPU_PRESENT #define __MPU_PRESENT 0 #warning "__MPU_PRESENT not defined in device header file; using default!" #endif #ifndef __NVIC_PRIO_BITS #define __NVIC_PRIO_BITS 4 #warning "__NVIC_PRIO_BITS not defined in device header file; using default!" #endif #ifndef __Vendor_SysTickConfig #define __Vendor_SysTickConfig 0 #warning "__Vendor_SysTickConfig not defined in device header file; using default!" #endif #endif /* IO definitions (access restrictions to peripheral registers) */ /** \defgroup CMSIS_glob_defs CMSIS Global Defines IO Type Qualifiers are used \li to specify the access to peripheral variables. \li for automatic generation of peripheral register debug information. */ #ifdef __cplusplus #define __I volatile /*!< Defines 'read only' permissions */ #else #define __I volatile const /*!< Defines 'read only' permissions */ #endif #define __O volatile /*!< Defines 'write only' permissions */ #define __IO volatile /*!< Defines 'read / write' permissions */ /*@} end of group Cortex_M4 */ /******************************************************************************* * Register Abstraction Core Register contain: - Core Register - Core NVIC Register - Core SCB Register - Core SysTick Register - Core Debug Register - Core MPU Register - Core FPU Register ******************************************************************************/ /** \defgroup CMSIS_core_register Defines and Type Definitions \brief Type definitions and defines for Cortex-M processor based devices. */ /** \ingroup CMSIS_core_register \defgroup CMSIS_CORE Status and Control Registers \brief Core Register type definitions. @{ */ /** \brief Union type to access the Application Program Status Register (APSR). */ typedef union { struct { #if (__CORTEX_M != 0x04) uint32_t _reserved0:27; /*!< bit: 0..26 Reserved */ #else uint32_t _reserved0:16; /*!< bit: 0..15 Reserved */ uint32_t GE:4; /*!< bit: 16..19 Greater than or Equal flags */ uint32_t _reserved1:7; /*!< bit: 20..26 Reserved */ #endif uint32_t Q:1; /*!< bit: 27 Saturation condition flag */ uint32_t V:1; /*!< bit: 28 Overflow condition code flag */ uint32_t C:1; /*!< bit: 29 Carry condition code flag */ uint32_t Z:1; /*!< bit: 30 Zero condition code flag */ uint32_t N:1; /*!< bit: 31 Negative condition code flag */ } b; /*!< Structure used for bit access */ uint32_t w; /*!< Type used for word access */ } APSR_Type; /** \brief Union type to access the Interrupt Program Status Register (IPSR). */ typedef union { struct { uint32_t ISR:9; /*!< bit: 0.. 8 Exception number */ uint32_t _reserved0:23; /*!< bit: 9..31 Reserved */ } b; /*!< Structure used for bit access */ uint32_t w; /*!< Type used for word access */ } IPSR_Type; /** \brief Union type to access the Special-Purpose Program Status Registers (xPSR). */ typedef union { struct { uint32_t ISR:9; /*!< bit: 0.. 8 Exception number */ #if (__CORTEX_M != 0x04) uint32_t _reserved0:15; /*!< bit: 9..23 Reserved */ #else uint32_t _reserved0:7; /*!< bit: 9..15 Reserved */ uint32_t GE:4; /*!< bit: 16..19 Greater than or Equal flags */ uint32_t _reserved1:4; /*!< bit: 20..23 Reserved */ #endif uint32_t T:1; /*!< bit: 24 Thumb bit (read 0) */ uint32_t IT:2; /*!< bit: 25..26 saved IT state (read 0) */ uint32_t Q:1; /*!< bit: 27 Saturation condition flag */ uint32_t V:1; /*!< bit: 28 Overflow condition code flag */ uint32_t C:1; /*!< bit: 29 Carry condition code flag */ uint32_t Z:1; /*!< bit: 30 Zero condition code flag */ uint32_t N:1; /*!< bit: 31 Negative condition code flag */ } b; /*!< Structure used for bit access */ uint32_t w; /*!< Type used for word access */ } xPSR_Type; /** \brief Union type to access the Control Registers (CONTROL). */ typedef union { struct { uint32_t nPRIV:1; /*!< bit: 0 Execution privilege in Thread mode */ uint32_t SPSEL:1; /*!< bit: 1 Stack to be used */ uint32_t FPCA:1; /*!< bit: 2 FP extension active flag */ uint32_t _reserved0:29; /*!< bit: 3..31 Reserved */ } b; /*!< Structure used for bit access */ uint32_t w; /*!< Type used for word access */ } CONTROL_Type; /*@} end of group CMSIS_CORE */ /** \ingroup CMSIS_core_register \defgroup CMSIS_NVIC Nested Vectored Interrupt Controller (NVIC) \brief Type definitions for the NVIC Registers @{ */ /** \brief Structure type to access the Nested Vectored Interrupt Controller (NVIC). */ typedef struct { __IO uint32_t ISER[8]; /*!< Offset: 0x000 (R/W) Interrupt Set Enable Register */ uint32_t RESERVED0[24]; __IO uint32_t ICER[8]; /*!< Offset: 0x080 (R/W) Interrupt Clear Enable Register */ uint32_t RSERVED1[24]; __IO uint32_t ISPR[8]; /*!< Offset: 0x100 (R/W) Interrupt Set Pending Register */ uint32_t RESERVED2[24]; __IO uint32_t ICPR[8]; /*!< Offset: 0x180 (R/W) Interrupt Clear Pending Register */ uint32_t RESERVED3[24]; __IO uint32_t IABR[8]; /*!< Offset: 0x200 (R/W) Interrupt Active bit Register */ uint32_t RESERVED4[56]; __IO uint8_t IP[240]; /*!< Offset: 0x300 (R/W) Interrupt Priority Register (8Bit wide) */ uint32_t RESERVED5[644]; __O uint32_t STIR; /*!< Offset: 0xE00 ( /W) Software Trigger Interrupt Register */ } NVIC_Type; /* Software Triggered Interrupt Register Definitions */ #define NVIC_STIR_INTID_Pos 0 /*!< STIR: INTLINESNUM Position */ #define NVIC_STIR_INTID_Msk (0x1FFUL << NVIC_STIR_INTID_Pos) /*!< STIR: INTLINESNUM Mask */ /*@} end of group CMSIS_NVIC */ /** \ingroup CMSIS_core_register \defgroup CMSIS_SCB System Control Block (SCB) \brief Type definitions for the System Control Block Registers @{ */ /** \brief Structure type to access the System Control Block (SCB). */ typedef struct { __I uint32_t CPUID; /*!< Offset: 0x000 (R/ ) CPUID Base Register */ __IO uint32_t ICSR; /*!< Offset: 0x004 (R/W) Interrupt Control and State Register */ __IO uint32_t VTOR; /*!< Offset: 0x008 (R/W) Vector Table Offset Register */ __IO uint32_t AIRCR; /*!< Offset: 0x00C (R/W) Application Interrupt and Reset Control Register */ __IO uint32_t SCR; /*!< Offset: 0x010 (R/W) System Control Register */ __IO uint32_t CCR; /*!< Offset: 0x014 (R/W) Configuration Control Register */ __IO uint8_t SHP[12]; /*!< Offset: 0x018 (R/W) System Handlers Priority Registers (4-7, 8-11, 12-15) */ __IO uint32_t SHCSR; /*!< Offset: 0x024 (R/W) System Handler Control and State Register */ __IO uint32_t CFSR; /*!< Offset: 0x028 (R/W) Configurable Fault Status Register */ __IO uint32_t HFSR; /*!< Offset: 0x02C (R/W) HardFault Status Register */ __IO uint32_t DFSR; /*!< Offset: 0x030 (R/W) Debug Fault Status Register */ __IO uint32_t MMFAR; /*!< Offset: 0x034 (R/W) MemManage Fault Address Register */ __IO uint32_t BFAR; /*!< Offset: 0x038 (R/W) BusFault Address Register */ __IO uint32_t AFSR; /*!< Offset: 0x03C (R/W) Auxiliary Fault Status Register */ __I uint32_t PFR[2]; /*!< Offset: 0x040 (R/ ) Processor Feature Register */ __I uint32_t DFR; /*!< Offset: 0x048 (R/ ) Debug Feature Register */ __I uint32_t ADR; /*!< Offset: 0x04C (R/ ) Auxiliary Feature Register */ __I uint32_t MMFR[4]; /*!< Offset: 0x050 (R/ ) Memory Model Feature Register */ __I uint32_t ISAR[5]; /*!< Offset: 0x060 (R/ ) Instruction Set Attributes Register */ uint32_t RESERVED0[5]; __IO uint32_t CPACR; /*!< Offset: 0x088 (R/W) Coprocessor Access Control Register */ } SCB_Type; /* SCB CPUID Register Definitions */ #define SCB_CPUID_IMPLEMENTER_Pos 24 /*!< SCB CPUID: IMPLEMENTER Position */ #define SCB_CPUID_IMPLEMENTER_Msk (0xFFUL << SCB_CPUID_IMPLEMENTER_Pos) /*!< SCB CPUID: IMPLEMENTER Mask */ #define SCB_CPUID_VARIANT_Pos 20 /*!< SCB CPUID: VARIANT Position */ #define SCB_CPUID_VARIANT_Msk (0xFUL << SCB_CPUID_VARIANT_Pos) /*!< SCB CPUID: VARIANT Mask */ #define SCB_CPUID_ARCHITECTURE_Pos 16 /*!< SCB CPUID: ARCHITECTURE Position */ #define SCB_CPUID_ARCHITECTURE_Msk (0xFUL << SCB_CPUID_ARCHITECTURE_Pos) /*!< SCB CPUID: ARCHITECTURE Mask */ #define SCB_CPUID_PARTNO_Pos 4 /*!< SCB CPUID: PARTNO Position */ #define SCB_CPUID_PARTNO_Msk (0xFFFUL << SCB_CPUID_PARTNO_Pos) /*!< SCB CPUID: PARTNO Mask */ #define SCB_CPUID_REVISION_Pos 0 /*!< SCB CPUID: REVISION Position */ #define SCB_CPUID_REVISION_Msk (0xFUL << SCB_CPUID_REVISION_Pos) /*!< SCB CPUID: REVISION Mask */ /* SCB Interrupt Control State Register Definitions */ #define SCB_ICSR_NMIPENDSET_Pos 31 /*!< SCB ICSR: NMIPENDSET Position */ #define SCB_ICSR_NMIPENDSET_Msk (1UL << SCB_ICSR_NMIPENDSET_Pos) /*!< SCB ICSR: NMIPENDSET Mask */ #define SCB_ICSR_PENDSVSET_Pos 28 /*!< SCB ICSR: PENDSVSET Position */ #define SCB_ICSR_PENDSVSET_Msk (1UL << SCB_ICSR_PENDSVSET_Pos) /*!< SCB ICSR: PENDSVSET Mask */ #define SCB_ICSR_PENDSVCLR_Pos 27 /*!< SCB ICSR: PENDSVCLR Position */ #define SCB_ICSR_PENDSVCLR_Msk (1UL << SCB_ICSR_PENDSVCLR_Pos) /*!< SCB ICSR: PENDSVCLR Mask */ #define SCB_ICSR_PENDSTSET_Pos 26 /*!< SCB ICSR: PENDSTSET Position */ #define SCB_ICSR_PENDSTSET_Msk (1UL << SCB_ICSR_PENDSTSET_Pos) /*!< SCB ICSR: PENDSTSET Mask */ #define SCB_ICSR_PENDSTCLR_Pos 25 /*!< SCB ICSR: PENDSTCLR Position */ #define SCB_ICSR_PENDSTCLR_Msk (1UL << SCB_ICSR_PENDSTCLR_Pos) /*!< SCB ICSR: PENDSTCLR Mask */ #define SCB_ICSR_ISRPREEMPT_Pos 23 /*!< SCB ICSR: ISRPREEMPT Position */ #define SCB_ICSR_ISRPREEMPT_Msk (1UL << SCB_ICSR_ISRPREEMPT_Pos) /*!< SCB ICSR: ISRPREEMPT Mask */ #define SCB_ICSR_ISRPENDING_Pos 22 /*!< SCB ICSR: ISRPENDING Position */ #define SCB_ICSR_ISRPENDING_Msk (1UL << SCB_ICSR_ISRPENDING_Pos) /*!< SCB ICSR: ISRPENDING Mask */ #define SCB_ICSR_VECTPENDING_Pos 12 /*!< SCB ICSR: VECTPENDING Position */ #define SCB_ICSR_VECTPENDING_Msk (0x1FFUL << SCB_ICSR_VECTPENDING_Pos) /*!< SCB ICSR: VECTPENDING Mask */ #define SCB_ICSR_RETTOBASE_Pos 11 /*!< SCB ICSR: RETTOBASE Position */ #define SCB_ICSR_RETTOBASE_Msk (1UL << SCB_ICSR_RETTOBASE_Pos) /*!< SCB ICSR: RETTOBASE Mask */ #define SCB_ICSR_VECTACTIVE_Pos 0 /*!< SCB ICSR: VECTACTIVE Position */ #define SCB_ICSR_VECTACTIVE_Msk (0x1FFUL << SCB_ICSR_VECTACTIVE_Pos) /*!< SCB ICSR: VECTACTIVE Mask */ /* SCB Vector Table Offset Register Definitions */ #define SCB_VTOR_TBLOFF_Pos 7 /*!< SCB VTOR: TBLOFF Position */ #define SCB_VTOR_TBLOFF_Msk (0x1FFFFFFUL << SCB_VTOR_TBLOFF_Pos) /*!< SCB VTOR: TBLOFF Mask */ /* SCB Application Interrupt and Reset Control Register Definitions */ #define SCB_AIRCR_VECTKEY_Pos 16 /*!< SCB AIRCR: VECTKEY Position */ #define SCB_AIRCR_VECTKEY_Msk (0xFFFFUL << SCB_AIRCR_VECTKEY_Pos) /*!< SCB AIRCR: VECTKEY Mask */ #define SCB_AIRCR_VECTKEYSTAT_Pos 16 /*!< SCB AIRCR: VECTKEYSTAT Position */ #define SCB_AIRCR_VECTKEYSTAT_Msk (0xFFFFUL << SCB_AIRCR_VECTKEYSTAT_Pos) /*!< SCB AIRCR: VECTKEYSTAT Mask */ #define SCB_AIRCR_ENDIANESS_Pos 15 /*!< SCB AIRCR: ENDIANESS Position */ #define SCB_AIRCR_ENDIANESS_Msk (1UL << SCB_AIRCR_ENDIANESS_Pos) /*!< SCB AIRCR: ENDIANESS Mask */ #define SCB_AIRCR_PRIGROUP_Pos 8 /*!< SCB AIRCR: PRIGROUP Position */ #define SCB_AIRCR_PRIGROUP_Msk (7UL << SCB_AIRCR_PRIGROUP_Pos) /*!< SCB AIRCR: PRIGROUP Mask */ #define SCB_AIRCR_SYSRESETREQ_Pos 2 /*!< SCB AIRCR: SYSRESETREQ Position */ #define SCB_AIRCR_SYSRESETREQ_Msk (1UL << SCB_AIRCR_SYSRESETREQ_Pos) /*!< SCB AIRCR: SYSRESETREQ Mask */ #define SCB_AIRCR_VECTCLRACTIVE_Pos 1 /*!< SCB AIRCR: VECTCLRACTIVE Position */ #define SCB_AIRCR_VECTCLRACTIVE_Msk (1UL << SCB_AIRCR_VECTCLRACTIVE_Pos) /*!< SCB AIRCR: VECTCLRACTIVE Mask */ #define SCB_AIRCR_VECTRESET_Pos 0 /*!< SCB AIRCR: VECTRESET Position */ #define SCB_AIRCR_VECTRESET_Msk (1UL << SCB_AIRCR_VECTRESET_Pos) /*!< SCB AIRCR: VECTRESET Mask */ /* SCB System Control Register Definitions */ #define SCB_SCR_SEVONPEND_Pos 4 /*!< SCB SCR: SEVONPEND Position */ #define SCB_SCR_SEVONPEND_Msk (1UL << SCB_SCR_SEVONPEND_Pos) /*!< SCB SCR: SEVONPEND Mask */ #define SCB_SCR_SLEEPDEEP_Pos 2 /*!< SCB SCR: SLEEPDEEP Position */ #define SCB_SCR_SLEEPDEEP_Msk (1UL << SCB_SCR_SLEEPDEEP_Pos) /*!< SCB SCR: SLEEPDEEP Mask */ #define SCB_SCR_SLEEPONEXIT_Pos 1 /*!< SCB SCR: SLEEPONEXIT Position */ #define SCB_SCR_SLEEPONEXIT_Msk (1UL << SCB_SCR_SLEEPONEXIT_Pos) /*!< SCB SCR: SLEEPONEXIT Mask */ /* SCB Configuration Control Register Definitions */ #define SCB_CCR_STKALIGN_Pos 9 /*!< SCB CCR: STKALIGN Position */ #define SCB_CCR_STKALIGN_Msk (1UL << SCB_CCR_STKALIGN_Pos) /*!< SCB CCR: STKALIGN Mask */ #define SCB_CCR_BFHFNMIGN_Pos 8 /*!< SCB CCR: BFHFNMIGN Position */ #define SCB_CCR_BFHFNMIGN_Msk (1UL << SCB_CCR_BFHFNMIGN_Pos) /*!< SCB CCR: BFHFNMIGN Mask */ #define SCB_CCR_DIV_0_TRP_Pos 4 /*!< SCB CCR: DIV_0_TRP Position */ #define SCB_CCR_DIV_0_TRP_Msk (1UL << SCB_CCR_DIV_0_TRP_Pos) /*!< SCB CCR: DIV_0_TRP Mask */ #define SCB_CCR_UNALIGN_TRP_Pos 3 /*!< SCB CCR: UNALIGN_TRP Position */ #define SCB_CCR_UNALIGN_TRP_Msk (1UL << SCB_CCR_UNALIGN_TRP_Pos) /*!< SCB CCR: UNALIGN_TRP Mask */ #define SCB_CCR_USERSETMPEND_Pos 1 /*!< SCB CCR: USERSETMPEND Position */ #define SCB_CCR_USERSETMPEND_Msk (1UL << SCB_CCR_USERSETMPEND_Pos) /*!< SCB CCR: USERSETMPEND Mask */ #define SCB_CCR_NONBASETHRDENA_Pos 0 /*!< SCB CCR: NONBASETHRDENA Position */ #define SCB_CCR_NONBASETHRDENA_Msk (1UL << SCB_CCR_NONBASETHRDENA_Pos) /*!< SCB CCR: NONBASETHRDENA Mask */ /* SCB System Handler Control and State Register Definitions */ #define SCB_SHCSR_USGFAULTENA_Pos 18 /*!< SCB SHCSR: USGFAULTENA Position */ #define SCB_SHCSR_USGFAULTENA_Msk (1UL << SCB_SHCSR_USGFAULTENA_Pos) /*!< SCB SHCSR: USGFAULTENA Mask */ #define SCB_SHCSR_BUSFAULTENA_Pos 17 /*!< SCB SHCSR: BUSFAULTENA Position */ #define SCB_SHCSR_BUSFAULTENA_Msk (1UL << SCB_SHCSR_BUSFAULTENA_Pos) /*!< SCB SHCSR: BUSFAULTENA Mask */ #define SCB_SHCSR_MEMFAULTENA_Pos 16 /*!< SCB SHCSR: MEMFAULTENA Position */ #define SCB_SHCSR_MEMFAULTENA_Msk (1UL << SCB_SHCSR_MEMFAULTENA_Pos) /*!< SCB SHCSR: MEMFAULTENA Mask */ #define SCB_SHCSR_SVCALLPENDED_Pos 15 /*!< SCB SHCSR: SVCALLPENDED Position */ #define SCB_SHCSR_SVCALLPENDED_Msk (1UL << SCB_SHCSR_SVCALLPENDED_Pos) /*!< SCB SHCSR: SVCALLPENDED Mask */ #define SCB_SHCSR_BUSFAULTPENDED_Pos 14 /*!< SCB SHCSR: BUSFAULTPENDED Position */ #define SCB_SHCSR_BUSFAULTPENDED_Msk (1UL << SCB_SHCSR_BUSFAULTPENDED_Pos) /*!< SCB SHCSR: BUSFAULTPENDED Mask */ #define SCB_SHCSR_MEMFAULTPENDED_Pos 13 /*!< SCB SHCSR: MEMFAULTPENDED Position */ #define SCB_SHCSR_MEMFAULTPENDED_Msk (1UL << SCB_SHCSR_MEMFAULTPENDED_Pos) /*!< SCB SHCSR: MEMFAULTPENDED Mask */ #define SCB_SHCSR_USGFAULTPENDED_Pos 12 /*!< SCB SHCSR: USGFAULTPENDED Position */ #define SCB_SHCSR_USGFAULTPENDED_Msk (1UL << SCB_SHCSR_USGFAULTPENDED_Pos) /*!< SCB SHCSR: USGFAULTPENDED Mask */ #define SCB_SHCSR_SYSTICKACT_Pos 11 /*!< SCB SHCSR: SYSTICKACT Position */ #define SCB_SHCSR_SYSTICKACT_Msk (1UL << SCB_SHCSR_SYSTICKACT_Pos) /*!< SCB SHCSR: SYSTICKACT Mask */ #define SCB_SHCSR_PENDSVACT_Pos 10 /*!< SCB SHCSR: PENDSVACT Position */ #define SCB_SHCSR_PENDSVACT_Msk (1UL << SCB_SHCSR_PENDSVACT_Pos) /*!< SCB SHCSR: PENDSVACT Mask */ #define SCB_SHCSR_MONITORACT_Pos 8 /*!< SCB SHCSR: MONITORACT Position */ #define SCB_SHCSR_MONITORACT_Msk (1UL << SCB_SHCSR_MONITORACT_Pos) /*!< SCB SHCSR: MONITORACT Mask */ #define SCB_SHCSR_SVCALLACT_Pos 7 /*!< SCB SHCSR: SVCALLACT Position */ #define SCB_SHCSR_SVCALLACT_Msk (1UL << SCB_SHCSR_SVCALLACT_Pos) /*!< SCB SHCSR: SVCALLACT Mask */ #define SCB_SHCSR_USGFAULTACT_Pos 3 /*!< SCB SHCSR: USGFAULTACT Position */ #define SCB_SHCSR_USGFAULTACT_Msk (1UL << SCB_SHCSR_USGFAULTACT_Pos) /*!< SCB SHCSR: USGFAULTACT Mask */ #define SCB_SHCSR_BUSFAULTACT_Pos 1 /*!< SCB SHCSR: BUSFAULTACT Position */ #define SCB_SHCSR_BUSFAULTACT_Msk (1UL << SCB_SHCSR_BUSFAULTACT_Pos) /*!< SCB SHCSR: BUSFAULTACT Mask */ #define SCB_SHCSR_MEMFAULTACT_Pos 0 /*!< SCB SHCSR: MEMFAULTACT Position */ #define SCB_SHCSR_MEMFAULTACT_Msk (1UL << SCB_SHCSR_MEMFAULTACT_Pos) /*!< SCB SHCSR: MEMFAULTACT Mask */ /* SCB Configurable Fault Status Registers Definitions */ #define SCB_CFSR_USGFAULTSR_Pos 16 /*!< SCB CFSR: Usage Fault Status Register Position */ #define SCB_CFSR_USGFAULTSR_Msk (0xFFFFUL << SCB_CFSR_USGFAULTSR_Pos) /*!< SCB CFSR: Usage Fault Status Register Mask */ #define SCB_CFSR_BUSFAULTSR_Pos 8 /*!< SCB CFSR: Bus Fault Status Register Position */ #define SCB_CFSR_BUSFAULTSR_Msk (0xFFUL << SCB_CFSR_BUSFAULTSR_Pos) /*!< SCB CFSR: Bus Fault Status Register Mask */ #define SCB_CFSR_MEMFAULTSR_Pos 0 /*!< SCB CFSR: Memory Manage Fault Status Register Position */ #define SCB_CFSR_MEMFAULTSR_Msk (0xFFUL << SCB_CFSR_MEMFAULTSR_Pos) /*!< SCB CFSR: Memory Manage Fault Status Register Mask */ /* SCB Hard Fault Status Registers Definitions */ #define SCB_HFSR_DEBUGEVT_Pos 31 /*!< SCB HFSR: DEBUGEVT Position */ #define SCB_HFSR_DEBUGEVT_Msk (1UL << SCB_HFSR_DEBUGEVT_Pos) /*!< SCB HFSR: DEBUGEVT Mask */ #define SCB_HFSR_FORCED_Pos 30 /*!< SCB HFSR: FORCED Position */ #define SCB_HFSR_FORCED_Msk (1UL << SCB_HFSR_FORCED_Pos) /*!< SCB HFSR: FORCED Mask */ #define SCB_HFSR_VECTTBL_Pos 1 /*!< SCB HFSR: VECTTBL Position */ #define SCB_HFSR_VECTTBL_Msk (1UL << SCB_HFSR_VECTTBL_Pos) /*!< SCB HFSR: VECTTBL Mask */ /* SCB Debug Fault Status Register Definitions */ #define SCB_DFSR_EXTERNAL_Pos 4 /*!< SCB DFSR: EXTERNAL Position */ #define SCB_DFSR_EXTERNAL_Msk (1UL << SCB_DFSR_EXTERNAL_Pos) /*!< SCB DFSR: EXTERNAL Mask */ #define SCB_DFSR_VCATCH_Pos 3 /*!< SCB DFSR: VCATCH Position */ #define SCB_DFSR_VCATCH_Msk (1UL << SCB_DFSR_VCATCH_Pos) /*!< SCB DFSR: VCATCH Mask */ #define SCB_DFSR_DWTTRAP_Pos 2 /*!< SCB DFSR: DWTTRAP Position */ #define SCB_DFSR_DWTTRAP_Msk (1UL << SCB_DFSR_DWTTRAP_Pos) /*!< SCB DFSR: DWTTRAP Mask */ #define SCB_DFSR_BKPT_Pos 1 /*!< SCB DFSR: BKPT Position */ #define SCB_DFSR_BKPT_Msk (1UL << SCB_DFSR_BKPT_Pos) /*!< SCB DFSR: BKPT Mask */ #define SCB_DFSR_HALTED_Pos 0 /*!< SCB DFSR: HALTED Position */ #define SCB_DFSR_HALTED_Msk (1UL << SCB_DFSR_HALTED_Pos) /*!< SCB DFSR: HALTED Mask */ /*@} end of group CMSIS_SCB */ /** \ingroup CMSIS_core_register \defgroup CMSIS_SCnSCB System Controls not in SCB (SCnSCB) \brief Type definitions for the System Control and ID Register not in the SCB @{ */ /** \brief Structure type to access the System Control and ID Register not in the SCB. */ typedef struct { uint32_t RESERVED0[1]; __I uint32_t ICTR; /*!< Offset: 0x004 (R/ ) Interrupt Controller Type Register */ __IO uint32_t ACTLR; /*!< Offset: 0x008 (R/W) Auxiliary Control Register */ } SCnSCB_Type; /* Interrupt Controller Type Register Definitions */ #define SCnSCB_ICTR_INTLINESNUM_Pos 0 /*!< ICTR: INTLINESNUM Position */ #define SCnSCB_ICTR_INTLINESNUM_Msk (0xFUL << SCnSCB_ICTR_INTLINESNUM_Pos) /*!< ICTR: INTLINESNUM Mask */ /* Auxiliary Control Register Definitions */ #define SCnSCB_ACTLR_DISOOFP_Pos 9 /*!< ACTLR: DISOOFP Position */ #define SCnSCB_ACTLR_DISOOFP_Msk (1UL << SCnSCB_ACTLR_DISOOFP_Pos) /*!< ACTLR: DISOOFP Mask */ #define SCnSCB_ACTLR_DISFPCA_Pos 8 /*!< ACTLR: DISFPCA Position */ #define SCnSCB_ACTLR_DISFPCA_Msk (1UL << SCnSCB_ACTLR_DISFPCA_Pos) /*!< ACTLR: DISFPCA Mask */ #define SCnSCB_ACTLR_DISFOLD_Pos 2 /*!< ACTLR: DISFOLD Position */ #define SCnSCB_ACTLR_DISFOLD_Msk (1UL << SCnSCB_ACTLR_DISFOLD_Pos) /*!< ACTLR: DISFOLD Mask */ #define SCnSCB_ACTLR_DISDEFWBUF_Pos 1 /*!< ACTLR: DISDEFWBUF Position */ #define SCnSCB_ACTLR_DISDEFWBUF_Msk (1UL << SCnSCB_ACTLR_DISDEFWBUF_Pos) /*!< ACTLR: DISDEFWBUF Mask */ #define SCnSCB_ACTLR_DISMCYCINT_Pos 0 /*!< ACTLR: DISMCYCINT Position */ #define SCnSCB_ACTLR_DISMCYCINT_Msk (1UL << SCnSCB_ACTLR_DISMCYCINT_Pos) /*!< ACTLR: DISMCYCINT Mask */ /*@} end of group CMSIS_SCnotSCB */ /** \ingroup CMSIS_core_register \defgroup CMSIS_SysTick System Tick Timer (SysTick) \brief Type definitions for the System Timer Registers. @{ */ /** \brief Structure type to access the System Timer (SysTick). */ typedef struct { __IO uint32_t CTRL; /*!< Offset: 0x000 (R/W) SysTick Control and Status Register */ __IO uint32_t LOAD; /*!< Offset: 0x004 (R/W) SysTick Reload Value Register */ __IO uint32_t VAL; /*!< Offset: 0x008 (R/W) SysTick Current Value Register */ __I uint32_t CALIB; /*!< Offset: 0x00C (R/ ) SysTick Calibration Register */ } SysTick_Type; /* SysTick Control / Status Register Definitions */ #define SysTick_CTRL_COUNTFLAG_Pos 16 /*!< SysTick CTRL: COUNTFLAG Position */ #define SysTick_CTRL_COUNTFLAG_Msk (1UL << SysTick_CTRL_COUNTFLAG_Pos) /*!< SysTick CTRL: COUNTFLAG Mask */ #define SysTick_CTRL_CLKSOURCE_Pos 2 /*!< SysTick CTRL: CLKSOURCE Position */ #define SysTick_CTRL_CLKSOURCE_Msk (1UL << SysTick_CTRL_CLKSOURCE_Pos) /*!< SysTick CTRL: CLKSOURCE Mask */ #define SysTick_CTRL_TICKINT_Pos 1 /*!< SysTick CTRL: TICKINT Position */ #define SysTick_CTRL_TICKINT_Msk (1UL << SysTick_CTRL_TICKINT_Pos) /*!< SysTick CTRL: TICKINT Mask */ #define SysTick_CTRL_ENABLE_Pos 0 /*!< SysTick CTRL: ENABLE Position */ #define SysTick_CTRL_ENABLE_Msk (1UL << SysTick_CTRL_ENABLE_Pos) /*!< SysTick CTRL: ENABLE Mask */ /* SysTick Reload Register Definitions */ #define SysTick_LOAD_RELOAD_Pos 0 /*!< SysTick LOAD: RELOAD Position */ #define SysTick_LOAD_RELOAD_Msk (0xFFFFFFUL << SysTick_LOAD_RELOAD_Pos) /*!< SysTick LOAD: RELOAD Mask */ /* SysTick Current Register Definitions */ #define SysTick_VAL_CURRENT_Pos 0 /*!< SysTick VAL: CURRENT Position */ #define SysTick_VAL_CURRENT_Msk (0xFFFFFFUL << SysTick_VAL_CURRENT_Pos) /*!< SysTick VAL: CURRENT Mask */ /* SysTick Calibration Register Definitions */ #define SysTick_CALIB_NOREF_Pos 31 /*!< SysTick CALIB: NOREF Position */ #define SysTick_CALIB_NOREF_Msk (1UL << SysTick_CALIB_NOREF_Pos) /*!< SysTick CALIB: NOREF Mask */ #define SysTick_CALIB_SKEW_Pos 30 /*!< SysTick CALIB: SKEW Position */ #define SysTick_CALIB_SKEW_Msk (1UL << SysTick_CALIB_SKEW_Pos) /*!< SysTick CALIB: SKEW Mask */ #define SysTick_CALIB_TENMS_Pos 0 /*!< SysTick CALIB: TENMS Position */ #define SysTick_CALIB_TENMS_Msk (0xFFFFFFUL << SysTick_VAL_CURRENT_Pos) /*!< SysTick CALIB: TENMS Mask */ /*@} end of group CMSIS_SysTick */ /** \ingroup CMSIS_core_register \defgroup CMSIS_ITM Instrumentation Trace Macrocell (ITM) \brief Type definitions for the Instrumentation Trace Macrocell (ITM) @{ */ /** \brief Structure type to access the Instrumentation Trace Macrocell Register (ITM). */ typedef struct { __O union { __O uint8_t u8; /*!< Offset: 0x000 ( /W) ITM Stimulus Port 8-bit */ __O uint16_t u16; /*!< Offset: 0x000 ( /W) ITM Stimulus Port 16-bit */ __O uint32_t u32; /*!< Offset: 0x000 ( /W) ITM Stimulus Port 32-bit */ } PORT [32]; /*!< Offset: 0x000 ( /W) ITM Stimulus Port Registers */ uint32_t RESERVED0[864]; __IO uint32_t TER; /*!< Offset: 0xE00 (R/W) ITM Trace Enable Register */ uint32_t RESERVED1[15]; __IO uint32_t TPR; /*!< Offset: 0xE40 (R/W) ITM Trace Privilege Register */ uint32_t RESERVED2[15]; __IO uint32_t TCR; /*!< Offset: 0xE80 (R/W) ITM Trace Control Register */ uint32_t RESERVED3[29]; __O uint32_t IWR; /*!< Offset: 0xEF8 ( /W) ITM Integration Write Register */ __I uint32_t IRR; /*!< Offset: 0xEFC (R/ ) ITM Integration Read Register */ __IO uint32_t IMCR; /*!< Offset: 0xF00 (R/W) ITM Integration Mode Control Register */ uint32_t RESERVED4[43]; __O uint32_t LAR; /*!< Offset: 0xFB0 ( /W) ITM Lock Access Register */ __I uint32_t LSR; /*!< Offset: 0xFB4 (R/ ) ITM Lock Status Register */ uint32_t RESERVED5[6]; __I uint32_t PID4; /*!< Offset: 0xFD0 (R/ ) ITM Peripheral Identification Register #4 */ __I uint32_t PID5; /*!< Offset: 0xFD4 (R/ ) ITM Peripheral Identification Register #5 */ __I uint32_t PID6; /*!< Offset: 0xFD8 (R/ ) ITM Peripheral Identification Register #6 */ __I uint32_t PID7; /*!< Offset: 0xFDC (R/ ) ITM Peripheral Identification Register #7 */ __I uint32_t PID0; /*!< Offset: 0xFE0 (R/ ) ITM Peripheral Identification Register #0 */ __I uint32_t PID1; /*!< Offset: 0xFE4 (R/ ) ITM Peripheral Identification Register #1 */ __I uint32_t PID2; /*!< Offset: 0xFE8 (R/ ) ITM Peripheral Identification Register #2 */ __I uint32_t PID3; /*!< Offset: 0xFEC (R/ ) ITM Peripheral Identification Register #3 */ __I uint32_t CID0; /*!< Offset: 0xFF0 (R/ ) ITM Component Identification Register #0 */ __I uint32_t CID1; /*!< Offset: 0xFF4 (R/ ) ITM Component Identification Register #1 */ __I uint32_t CID2; /*!< Offset: 0xFF8 (R/ ) ITM Component Identification Register #2 */ __I uint32_t CID3; /*!< Offset: 0xFFC (R/ ) ITM Component Identification Register #3 */ } ITM_Type; /* ITM Trace Privilege Register Definitions */ #define ITM_TPR_PRIVMASK_Pos 0 /*!< ITM TPR: PRIVMASK Position */ #define ITM_TPR_PRIVMASK_Msk (0xFUL << ITM_TPR_PRIVMASK_Pos) /*!< ITM TPR: PRIVMASK Mask */ /* ITM Trace Control Register Definitions */ #define ITM_TCR_BUSY_Pos 23 /*!< ITM TCR: BUSY Position */ #define ITM_TCR_BUSY_Msk (1UL << ITM_TCR_BUSY_Pos) /*!< ITM TCR: BUSY Mask */ #define ITM_TCR_TraceBusID_Pos 16 /*!< ITM TCR: ATBID Position */ #define ITM_TCR_TraceBusID_Msk (0x7FUL << ITM_TCR_TraceBusID_Pos) /*!< ITM TCR: ATBID Mask */ #define ITM_TCR_GTSFREQ_Pos 10 /*!< ITM TCR: Global timestamp frequency Position */ #define ITM_TCR_GTSFREQ_Msk (3UL << ITM_TCR_GTSFREQ_Pos) /*!< ITM TCR: Global timestamp frequency Mask */ #define ITM_TCR_TSPrescale_Pos 8 /*!< ITM TCR: TSPrescale Position */ #define ITM_TCR_TSPrescale_Msk (3UL << ITM_TCR_TSPrescale_Pos) /*!< ITM TCR: TSPrescale Mask */ #define ITM_TCR_SWOENA_Pos 4 /*!< ITM TCR: SWOENA Position */ #define ITM_TCR_SWOENA_Msk (1UL << ITM_TCR_SWOENA_Pos) /*!< ITM TCR: SWOENA Mask */ #define ITM_TCR_DWTENA_Pos 3 /*!< ITM TCR: DWTENA Position */ #define ITM_TCR_DWTENA_Msk (1UL << ITM_TCR_DWTENA_Pos) /*!< ITM TCR: DWTENA Mask */ #define ITM_TCR_SYNCENA_Pos 2 /*!< ITM TCR: SYNCENA Position */ #define ITM_TCR_SYNCENA_Msk (1UL << ITM_TCR_SYNCENA_Pos) /*!< ITM TCR: SYNCENA Mask */ #define ITM_TCR_TSENA_Pos 1 /*!< ITM TCR: TSENA Position */ #define ITM_TCR_TSENA_Msk (1UL << ITM_TCR_TSENA_Pos) /*!< ITM TCR: TSENA Mask */ #define ITM_TCR_ITMENA_Pos 0 /*!< ITM TCR: ITM Enable bit Position */ #define ITM_TCR_ITMENA_Msk (1UL << ITM_TCR_ITMENA_Pos) /*!< ITM TCR: ITM Enable bit Mask */ /* ITM Integration Write Register Definitions */ #define ITM_IWR_ATVALIDM_Pos 0 /*!< ITM IWR: ATVALIDM Position */ #define ITM_IWR_ATVALIDM_Msk (1UL << ITM_IWR_ATVALIDM_Pos) /*!< ITM IWR: ATVALIDM Mask */ /* ITM Integration Read Register Definitions */ #define ITM_IRR_ATREADYM_Pos 0 /*!< ITM IRR: ATREADYM Position */ #define ITM_IRR_ATREADYM_Msk (1UL << ITM_IRR_ATREADYM_Pos) /*!< ITM IRR: ATREADYM Mask */ /* ITM Integration Mode Control Register Definitions */ #define ITM_IMCR_INTEGRATION_Pos 0 /*!< ITM IMCR: INTEGRATION Position */ #define ITM_IMCR_INTEGRATION_Msk (1UL << ITM_IMCR_INTEGRATION_Pos) /*!< ITM IMCR: INTEGRATION Mask */ /* ITM Lock Status Register Definitions */ #define ITM_LSR_ByteAcc_Pos 2 /*!< ITM LSR: ByteAcc Position */ #define ITM_LSR_ByteAcc_Msk (1UL << ITM_LSR_ByteAcc_Pos) /*!< ITM LSR: ByteAcc Mask */ #define ITM_LSR_Access_Pos 1 /*!< ITM LSR: Access Position */ #define ITM_LSR_Access_Msk (1UL << ITM_LSR_Access_Pos) /*!< ITM LSR: Access Mask */ #define ITM_LSR_Present_Pos 0 /*!< ITM LSR: Present Position */ #define ITM_LSR_Present_Msk (1UL << ITM_LSR_Present_Pos) /*!< ITM LSR: Present Mask */ /*@}*/ /* end of group CMSIS_ITM */ /** \ingroup CMSIS_core_register \defgroup CMSIS_DWT Data Watchpoint and Trace (DWT) \brief Type definitions for the Data Watchpoint and Trace (DWT) @{ */ /** \brief Structure type to access the Data Watchpoint and Trace Register (DWT). */ typedef struct { __IO uint32_t CTRL; /*!< Offset: 0x000 (R/W) Control Register */ __IO uint32_t CYCCNT; /*!< Offset: 0x004 (R/W) Cycle Count Register */ __IO uint32_t CPICNT; /*!< Offset: 0x008 (R/W) CPI Count Register */ __IO uint32_t EXCCNT; /*!< Offset: 0x00C (R/W) Exception Overhead Count Register */ __IO uint32_t SLEEPCNT; /*!< Offset: 0x010 (R/W) Sleep Count Register */ __IO uint32_t LSUCNT; /*!< Offset: 0x014 (R/W) LSU Count Register */ __IO uint32_t FOLDCNT; /*!< Offset: 0x018 (R/W) Folded-instruction Count Register */ __I uint32_t PCSR; /*!< Offset: 0x01C (R/ ) Program Counter Sample Register */ __IO uint32_t COMP0; /*!< Offset: 0x020 (R/W) Comparator Register 0 */ __IO uint32_t MASK0; /*!< Offset: 0x024 (R/W) Mask Register 0 */ __IO uint32_t FUNCTION0; /*!< Offset: 0x028 (R/W) Function Register 0 */ uint32_t RESERVED0[1]; __IO uint32_t COMP1; /*!< Offset: 0x030 (R/W) Comparator Register 1 */ __IO uint32_t MASK1; /*!< Offset: 0x034 (R/W) Mask Register 1 */ __IO uint32_t FUNCTION1; /*!< Offset: 0x038 (R/W) Function Register 1 */ uint32_t RESERVED1[1]; __IO uint32_t COMP2; /*!< Offset: 0x040 (R/W) Comparator Register 2 */ __IO uint32_t MASK2; /*!< Offset: 0x044 (R/W) Mask Register 2 */ __IO uint32_t FUNCTION2; /*!< Offset: 0x048 (R/W) Function Register 2 */ uint32_t RESERVED2[1]; __IO uint32_t COMP3; /*!< Offset: 0x050 (R/W) Comparator Register 3 */ __IO uint32_t MASK3; /*!< Offset: 0x054 (R/W) Mask Register 3 */ __IO uint32_t FUNCTION3; /*!< Offset: 0x058 (R/W) Function Register 3 */ } DWT_Type; /* DWT Control Register Definitions */ #define DWT_CTRL_NUMCOMP_Pos 28 /*!< DWT CTRL: NUMCOMP Position */ #define DWT_CTRL_NUMCOMP_Msk (0xFUL << DWT_CTRL_NUMCOMP_Pos) /*!< DWT CTRL: NUMCOMP Mask */ #define DWT_CTRL_NOTRCPKT_Pos 27 /*!< DWT CTRL: NOTRCPKT Position */ #define DWT_CTRL_NOTRCPKT_Msk (0x1UL << DWT_CTRL_NOTRCPKT_Pos) /*!< DWT CTRL: NOTRCPKT Mask */ #define DWT_CTRL_NOEXTTRIG_Pos 26 /*!< DWT CTRL: NOEXTTRIG Position */ #define DWT_CTRL_NOEXTTRIG_Msk (0x1UL << DWT_CTRL_NOEXTTRIG_Pos) /*!< DWT CTRL: NOEXTTRIG Mask */ #define DWT_CTRL_NOCYCCNT_Pos 25 /*!< DWT CTRL: NOCYCCNT Position */ #define DWT_CTRL_NOCYCCNT_Msk (0x1UL << DWT_CTRL_NOCYCCNT_Pos) /*!< DWT CTRL: NOCYCCNT Mask */ #define DWT_CTRL_NOPRFCNT_Pos 24 /*!< DWT CTRL: NOPRFCNT Position */ #define DWT_CTRL_NOPRFCNT_Msk (0x1UL << DWT_CTRL_NOPRFCNT_Pos) /*!< DWT CTRL: NOPRFCNT Mask */ #define DWT_CTRL_CYCEVTENA_Pos 22 /*!< DWT CTRL: CYCEVTENA Position */ #define DWT_CTRL_CYCEVTENA_Msk (0x1UL << DWT_CTRL_CYCEVTENA_Pos) /*!< DWT CTRL: CYCEVTENA Mask */ #define DWT_CTRL_FOLDEVTENA_Pos 21 /*!< DWT CTRL: FOLDEVTENA Position */ #define DWT_CTRL_FOLDEVTENA_Msk (0x1UL << DWT_CTRL_FOLDEVTENA_Pos) /*!< DWT CTRL: FOLDEVTENA Mask */ #define DWT_CTRL_LSUEVTENA_Pos 20 /*!< DWT CTRL: LSUEVTENA Position */ #define DWT_CTRL_LSUEVTENA_Msk (0x1UL << DWT_CTRL_LSUEVTENA_Pos) /*!< DWT CTRL: LSUEVTENA Mask */ #define DWT_CTRL_SLEEPEVTENA_Pos 19 /*!< DWT CTRL: SLEEPEVTENA Position */ #define DWT_CTRL_SLEEPEVTENA_Msk (0x1UL << DWT_CTRL_SLEEPEVTENA_Pos) /*!< DWT CTRL: SLEEPEVTENA Mask */ #define DWT_CTRL_EXCEVTENA_Pos 18 /*!< DWT CTRL: EXCEVTENA Position */ #define DWT_CTRL_EXCEVTENA_Msk (0x1UL << DWT_CTRL_EXCEVTENA_Pos) /*!< DWT CTRL: EXCEVTENA Mask */ #define DWT_CTRL_CPIEVTENA_Pos 17 /*!< DWT CTRL: CPIEVTENA Position */ #define DWT_CTRL_CPIEVTENA_Msk (0x1UL << DWT_CTRL_CPIEVTENA_Pos) /*!< DWT CTRL: CPIEVTENA Mask */ #define DWT_CTRL_EXCTRCENA_Pos 16 /*!< DWT CTRL: EXCTRCENA Position */ #define DWT_CTRL_EXCTRCENA_Msk (0x1UL << DWT_CTRL_EXCTRCENA_Pos) /*!< DWT CTRL: EXCTRCENA Mask */ #define DWT_CTRL_PCSAMPLENA_Pos 12 /*!< DWT CTRL: PCSAMPLENA Position */ #define DWT_CTRL_PCSAMPLENA_Msk (0x1UL << DWT_CTRL_PCSAMPLENA_Pos) /*!< DWT CTRL: PCSAMPLENA Mask */ #define DWT_CTRL_SYNCTAP_Pos 10 /*!< DWT CTRL: SYNCTAP Position */ #define DWT_CTRL_SYNCTAP_Msk (0x3UL << DWT_CTRL_SYNCTAP_Pos) /*!< DWT CTRL: SYNCTAP Mask */ #define DWT_CTRL_CYCTAP_Pos 9 /*!< DWT CTRL: CYCTAP Position */ #define DWT_CTRL_CYCTAP_Msk (0x1UL << DWT_CTRL_CYCTAP_Pos) /*!< DWT CTRL: CYCTAP Mask */ #define DWT_CTRL_POSTINIT_Pos 5 /*!< DWT CTRL: POSTINIT Position */ #define DWT_CTRL_POSTINIT_Msk (0xFUL << DWT_CTRL_POSTINIT_Pos) /*!< DWT CTRL: POSTINIT Mask */ #define DWT_CTRL_POSTPRESET_Pos 1 /*!< DWT CTRL: POSTPRESET Position */ #define DWT_CTRL_POSTPRESET_Msk (0xFUL << DWT_CTRL_POSTPRESET_Pos) /*!< DWT CTRL: POSTPRESET Mask */ #define DWT_CTRL_CYCCNTENA_Pos 0 /*!< DWT CTRL: CYCCNTENA Position */ #define DWT_CTRL_CYCCNTENA_Msk (0x1UL << DWT_CTRL_CYCCNTENA_Pos) /*!< DWT CTRL: CYCCNTENA Mask */ /* DWT CPI Count Register Definitions */ #define DWT_CPICNT_CPICNT_Pos 0 /*!< DWT CPICNT: CPICNT Position */ #define DWT_CPICNT_CPICNT_Msk (0xFFUL << DWT_CPICNT_CPICNT_Pos) /*!< DWT CPICNT: CPICNT Mask */ /* DWT Exception Overhead Count Register Definitions */ #define DWT_EXCCNT_EXCCNT_Pos 0 /*!< DWT EXCCNT: EXCCNT Position */ #define DWT_EXCCNT_EXCCNT_Msk (0xFFUL << DWT_EXCCNT_EXCCNT_Pos) /*!< DWT EXCCNT: EXCCNT Mask */ /* DWT Sleep Count Register Definitions */ #define DWT_SLEEPCNT_SLEEPCNT_Pos 0 /*!< DWT SLEEPCNT: SLEEPCNT Position */ #define DWT_SLEEPCNT_SLEEPCNT_Msk (0xFFUL << DWT_SLEEPCNT_SLEEPCNT_Pos) /*!< DWT SLEEPCNT: SLEEPCNT Mask */ /* DWT LSU Count Register Definitions */ #define DWT_LSUCNT_LSUCNT_Pos 0 /*!< DWT LSUCNT: LSUCNT Position */ #define DWT_LSUCNT_LSUCNT_Msk (0xFFUL << DWT_LSUCNT_LSUCNT_Pos) /*!< DWT LSUCNT: LSUCNT Mask */ /* DWT Folded-instruction Count Register Definitions */ #define DWT_FOLDCNT_FOLDCNT_Pos 0 /*!< DWT FOLDCNT: FOLDCNT Position */ #define DWT_FOLDCNT_FOLDCNT_Msk (0xFFUL << DWT_FOLDCNT_FOLDCNT_Pos) /*!< DWT FOLDCNT: FOLDCNT Mask */ /* DWT Comparator Mask Register Definitions */ #define DWT_MASK_MASK_Pos 0 /*!< DWT MASK: MASK Position */ #define DWT_MASK_MASK_Msk (0x1FUL << DWT_MASK_MASK_Pos) /*!< DWT MASK: MASK Mask */ /* DWT Comparator Function Register Definitions */ #define DWT_FUNCTION_MATCHED_Pos 24 /*!< DWT FUNCTION: MATCHED Position */ #define DWT_FUNCTION_MATCHED_Msk (0x1UL << DWT_FUNCTION_MATCHED_Pos) /*!< DWT FUNCTION: MATCHED Mask */ #define DWT_FUNCTION_DATAVADDR1_Pos 16 /*!< DWT FUNCTION: DATAVADDR1 Position */ #define DWT_FUNCTION_DATAVADDR1_Msk (0xFUL << DWT_FUNCTION_DATAVADDR1_Pos) /*!< DWT FUNCTION: DATAVADDR1 Mask */ #define DWT_FUNCTION_DATAVADDR0_Pos 12 /*!< DWT FUNCTION: DATAVADDR0 Position */ #define DWT_FUNCTION_DATAVADDR0_Msk (0xFUL << DWT_FUNCTION_DATAVADDR0_Pos) /*!< DWT FUNCTION: DATAVADDR0 Mask */ #define DWT_FUNCTION_DATAVSIZE_Pos 10 /*!< DWT FUNCTION: DATAVSIZE Position */ #define DWT_FUNCTION_DATAVSIZE_Msk (0x3UL << DWT_FUNCTION_DATAVSIZE_Pos) /*!< DWT FUNCTION: DATAVSIZE Mask */ #define DWT_FUNCTION_LNK1ENA_Pos 9 /*!< DWT FUNCTION: LNK1ENA Position */ #define DWT_FUNCTION_LNK1ENA_Msk (0x1UL << DWT_FUNCTION_LNK1ENA_Pos) /*!< DWT FUNCTION: LNK1ENA Mask */ #define DWT_FUNCTION_DATAVMATCH_Pos 8 /*!< DWT FUNCTION: DATAVMATCH Position */ #define DWT_FUNCTION_DATAVMATCH_Msk (0x1UL << DWT_FUNCTION_DATAVMATCH_Pos) /*!< DWT FUNCTION: DATAVMATCH Mask */ #define DWT_FUNCTION_CYCMATCH_Pos 7 /*!< DWT FUNCTION: CYCMATCH Position */ #define DWT_FUNCTION_CYCMATCH_Msk (0x1UL << DWT_FUNCTION_CYCMATCH_Pos) /*!< DWT FUNCTION: CYCMATCH Mask */ #define DWT_FUNCTION_EMITRANGE_Pos 5 /*!< DWT FUNCTION: EMITRANGE Position */ #define DWT_FUNCTION_EMITRANGE_Msk (0x1UL << DWT_FUNCTION_EMITRANGE_Pos) /*!< DWT FUNCTION: EMITRANGE Mask */ #define DWT_FUNCTION_FUNCTION_Pos 0 /*!< DWT FUNCTION: FUNCTION Position */ #define DWT_FUNCTION_FUNCTION_Msk (0xFUL << DWT_FUNCTION_FUNCTION_Pos) /*!< DWT FUNCTION: FUNCTION Mask */ /*@}*/ /* end of group CMSIS_DWT */ /** \ingroup CMSIS_core_register \defgroup CMSIS_TPI Trace Port Interface (TPI) \brief Type definitions for the Trace Port Interface (TPI) @{ */ /** \brief Structure type to access the Trace Port Interface Register (TPI). */ typedef struct { __IO uint32_t SSPSR; /*!< Offset: 0x000 (R/ ) Supported Parallel Port Size Register */ __IO uint32_t CSPSR; /*!< Offset: 0x004 (R/W) Current Parallel Port Size Register */ uint32_t RESERVED0[2]; __IO uint32_t ACPR; /*!< Offset: 0x010 (R/W) Asynchronous Clock Prescaler Register */ uint32_t RESERVED1[55]; __IO uint32_t SPPR; /*!< Offset: 0x0F0 (R/W) Selected Pin Protocol Register */ uint32_t RESERVED2[131]; __I uint32_t FFSR; /*!< Offset: 0x300 (R/ ) Formatter and Flush Status Register */ __IO uint32_t FFCR; /*!< Offset: 0x304 (R/W) Formatter and Flush Control Register */ __I uint32_t FSCR; /*!< Offset: 0x308 (R/ ) Formatter Synchronization Counter Register */ uint32_t RESERVED3[759]; __I uint32_t TRIGGER; /*!< Offset: 0xEE8 (R/ ) TRIGGER */ __I uint32_t FIFO0; /*!< Offset: 0xEEC (R/ ) Integration ETM Data */ __I uint32_t ITATBCTR2; /*!< Offset: 0xEF0 (R/ ) ITATBCTR2 */ uint32_t RESERVED4[1]; __I uint32_t ITATBCTR0; /*!< Offset: 0xEF8 (R/ ) ITATBCTR0 */ __I uint32_t FIFO1; /*!< Offset: 0xEFC (R/ ) Integration ITM Data */ __IO uint32_t ITCTRL; /*!< Offset: 0xF00 (R/W) Integration Mode Control */ uint32_t RESERVED5[39]; __IO uint32_t CLAIMSET; /*!< Offset: 0xFA0 (R/W) Claim tag set */ __IO uint32_t CLAIMCLR; /*!< Offset: 0xFA4 (R/W) Claim tag clear */ uint32_t RESERVED7[8]; __I uint32_t DEVID; /*!< Offset: 0xFC8 (R/ ) TPIU_DEVID */ __I uint32_t DEVTYPE; /*!< Offset: 0xFCC (R/ ) TPIU_DEVTYPE */ } TPI_Type; /* TPI Asynchronous Clock Prescaler Register Definitions */ #define TPI_ACPR_PRESCALER_Pos 0 /*!< TPI ACPR: PRESCALER Position */ #define TPI_ACPR_PRESCALER_Msk (0x1FFFUL << TPI_ACPR_PRESCALER_Pos) /*!< TPI ACPR: PRESCALER Mask */ /* TPI Selected Pin Protocol Register Definitions */ #define TPI_SPPR_TXMODE_Pos 0 /*!< TPI SPPR: TXMODE Position */ #define TPI_SPPR_TXMODE_Msk (0x3UL << TPI_SPPR_TXMODE_Pos) /*!< TPI SPPR: TXMODE Mask */ /* TPI Formatter and Flush Status Register Definitions */ #define TPI_FFSR_FtNonStop_Pos 3 /*!< TPI FFSR: FtNonStop Position */ #define TPI_FFSR_FtNonStop_Msk (0x1UL << TPI_FFSR_FtNonStop_Pos) /*!< TPI FFSR: FtNonStop Mask */ #define TPI_FFSR_TCPresent_Pos 2 /*!< TPI FFSR: TCPresent Position */ #define TPI_FFSR_TCPresent_Msk (0x1UL << TPI_FFSR_TCPresent_Pos) /*!< TPI FFSR: TCPresent Mask */ #define TPI_FFSR_FtStopped_Pos 1 /*!< TPI FFSR: FtStopped Position */ #define TPI_FFSR_FtStopped_Msk (0x1UL << TPI_FFSR_FtStopped_Pos) /*!< TPI FFSR: FtStopped Mask */ #define TPI_FFSR_FlInProg_Pos 0 /*!< TPI FFSR: FlInProg Position */ #define TPI_FFSR_FlInProg_Msk (0x1UL << TPI_FFSR_FlInProg_Pos) /*!< TPI FFSR: FlInProg Mask */ /* TPI Formatter and Flush Control Register Definitions */ #define TPI_FFCR_TrigIn_Pos 8 /*!< TPI FFCR: TrigIn Position */ #define TPI_FFCR_TrigIn_Msk (0x1UL << TPI_FFCR_TrigIn_Pos) /*!< TPI FFCR: TrigIn Mask */ #define TPI_FFCR_EnFCont_Pos 1 /*!< TPI FFCR: EnFCont Position */ #define TPI_FFCR_EnFCont_Msk (0x1UL << TPI_FFCR_EnFCont_Pos) /*!< TPI FFCR: EnFCont Mask */ /* TPI TRIGGER Register Definitions */ #define TPI_TRIGGER_TRIGGER_Pos 0 /*!< TPI TRIGGER: TRIGGER Position */ #define TPI_TRIGGER_TRIGGER_Msk (0x1UL << TPI_TRIGGER_TRIGGER_Pos) /*!< TPI TRIGGER: TRIGGER Mask */ /* TPI Integration ETM Data Register Definitions (FIFO0) */ #define TPI_FIFO0_ITM_ATVALID_Pos 29 /*!< TPI FIFO0: ITM_ATVALID Position */ #define TPI_FIFO0_ITM_ATVALID_Msk (0x3UL << TPI_FIFO0_ITM_ATVALID_Pos) /*!< TPI FIFO0: ITM_ATVALID Mask */ #define TPI_FIFO0_ITM_bytecount_Pos 27 /*!< TPI FIFO0: ITM_bytecount Position */ #define TPI_FIFO0_ITM_bytecount_Msk (0x3UL << TPI_FIFO0_ITM_bytecount_Pos) /*!< TPI FIFO0: ITM_bytecount Mask */ #define TPI_FIFO0_ETM_ATVALID_Pos 26 /*!< TPI FIFO0: ETM_ATVALID Position */ #define TPI_FIFO0_ETM_ATVALID_Msk (0x3UL << TPI_FIFO0_ETM_ATVALID_Pos) /*!< TPI FIFO0: ETM_ATVALID Mask */ #define TPI_FIFO0_ETM_bytecount_Pos 24 /*!< TPI FIFO0: ETM_bytecount Position */ #define TPI_FIFO0_ETM_bytecount_Msk (0x3UL << TPI_FIFO0_ETM_bytecount_Pos) /*!< TPI FIFO0: ETM_bytecount Mask */ #define TPI_FIFO0_ETM2_Pos 16 /*!< TPI FIFO0: ETM2 Position */ #define TPI_FIFO0_ETM2_Msk (0xFFUL << TPI_FIFO0_ETM2_Pos) /*!< TPI FIFO0: ETM2 Mask */ #define TPI_FIFO0_ETM1_Pos 8 /*!< TPI FIFO0: ETM1 Position */ #define TPI_FIFO0_ETM1_Msk (0xFFUL << TPI_FIFO0_ETM1_Pos) /*!< TPI FIFO0: ETM1 Mask */ #define TPI_FIFO0_ETM0_Pos 0 /*!< TPI FIFO0: ETM0 Position */ #define TPI_FIFO0_ETM0_Msk (0xFFUL << TPI_FIFO0_ETM0_Pos) /*!< TPI FIFO0: ETM0 Mask */ /* TPI ITATBCTR2 Register Definitions */ #define TPI_ITATBCTR2_ATREADY_Pos 0 /*!< TPI ITATBCTR2: ATREADY Position */ #define TPI_ITATBCTR2_ATREADY_Msk (0x1UL << TPI_ITATBCTR2_ATREADY_Pos) /*!< TPI ITATBCTR2: ATREADY Mask */ /* TPI Integration ITM Data Register Definitions (FIFO1) */ #define TPI_FIFO1_ITM_ATVALID_Pos 29 /*!< TPI FIFO1: ITM_ATVALID Position */ #define TPI_FIFO1_ITM_ATVALID_Msk (0x3UL << TPI_FIFO1_ITM_ATVALID_Pos) /*!< TPI FIFO1: ITM_ATVALID Mask */ #define TPI_FIFO1_ITM_bytecount_Pos 27 /*!< TPI FIFO1: ITM_bytecount Position */ #define TPI_FIFO1_ITM_bytecount_Msk (0x3UL << TPI_FIFO1_ITM_bytecount_Pos) /*!< TPI FIFO1: ITM_bytecount Mask */ #define TPI_FIFO1_ETM_ATVALID_Pos 26 /*!< TPI FIFO1: ETM_ATVALID Position */ #define TPI_FIFO1_ETM_ATVALID_Msk (0x3UL << TPI_FIFO1_ETM_ATVALID_Pos) /*!< TPI FIFO1: ETM_ATVALID Mask */ #define TPI_FIFO1_ETM_bytecount_Pos 24 /*!< TPI FIFO1: ETM_bytecount Position */ #define TPI_FIFO1_ETM_bytecount_Msk (0x3UL << TPI_FIFO1_ETM_bytecount_Pos) /*!< TPI FIFO1: ETM_bytecount Mask */ #define TPI_FIFO1_ITM2_Pos 16 /*!< TPI FIFO1: ITM2 Position */ #define TPI_FIFO1_ITM2_Msk (0xFFUL << TPI_FIFO1_ITM2_Pos) /*!< TPI FIFO1: ITM2 Mask */ #define TPI_FIFO1_ITM1_Pos 8 /*!< TPI FIFO1: ITM1 Position */ #define TPI_FIFO1_ITM1_Msk (0xFFUL << TPI_FIFO1_ITM1_Pos) /*!< TPI FIFO1: ITM1 Mask */ #define TPI_FIFO1_ITM0_Pos 0 /*!< TPI FIFO1: ITM0 Position */ #define TPI_FIFO1_ITM0_Msk (0xFFUL << TPI_FIFO1_ITM0_Pos) /*!< TPI FIFO1: ITM0 Mask */ /* TPI ITATBCTR0 Register Definitions */ #define TPI_ITATBCTR0_ATREADY_Pos 0 /*!< TPI ITATBCTR0: ATREADY Position */ #define TPI_ITATBCTR0_ATREADY_Msk (0x1UL << TPI_ITATBCTR0_ATREADY_Pos) /*!< TPI ITATBCTR0: ATREADY Mask */ /* TPI Integration Mode Control Register Definitions */ #define TPI_ITCTRL_Mode_Pos 0 /*!< TPI ITCTRL: Mode Position */ #define TPI_ITCTRL_Mode_Msk (0x1UL << TPI_ITCTRL_Mode_Pos) /*!< TPI ITCTRL: Mode Mask */ /* TPI DEVID Register Definitions */ #define TPI_DEVID_NRZVALID_Pos 11 /*!< TPI DEVID: NRZVALID Position */ #define TPI_DEVID_NRZVALID_Msk (0x1UL << TPI_DEVID_NRZVALID_Pos) /*!< TPI DEVID: NRZVALID Mask */ #define TPI_DEVID_MANCVALID_Pos 10 /*!< TPI DEVID: MANCVALID Position */ #define TPI_DEVID_MANCVALID_Msk (0x1UL << TPI_DEVID_MANCVALID_Pos) /*!< TPI DEVID: MANCVALID Mask */ #define TPI_DEVID_PTINVALID_Pos 9 /*!< TPI DEVID: PTINVALID Position */ #define TPI_DEVID_PTINVALID_Msk (0x1UL << TPI_DEVID_PTINVALID_Pos) /*!< TPI DEVID: PTINVALID Mask */ #define TPI_DEVID_MinBufSz_Pos 6 /*!< TPI DEVID: MinBufSz Position */ #define TPI_DEVID_MinBufSz_Msk (0x7UL << TPI_DEVID_MinBufSz_Pos) /*!< TPI DEVID: MinBufSz Mask */ #define TPI_DEVID_AsynClkIn_Pos 5 /*!< TPI DEVID: AsynClkIn Position */ #define TPI_DEVID_AsynClkIn_Msk (0x1UL << TPI_DEVID_AsynClkIn_Pos) /*!< TPI DEVID: AsynClkIn Mask */ #define TPI_DEVID_NrTraceInput_Pos 0 /*!< TPI DEVID: NrTraceInput Position */ #define TPI_DEVID_NrTraceInput_Msk (0x1FUL << TPI_DEVID_NrTraceInput_Pos) /*!< TPI DEVID: NrTraceInput Mask */ /* TPI DEVTYPE Register Definitions */ #define TPI_DEVTYPE_SubType_Pos 0 /*!< TPI DEVTYPE: SubType Position */ #define TPI_DEVTYPE_SubType_Msk (0xFUL << TPI_DEVTYPE_SubType_Pos) /*!< TPI DEVTYPE: SubType Mask */ #define TPI_DEVTYPE_MajorType_Pos 4 /*!< TPI DEVTYPE: MajorType Position */ #define TPI_DEVTYPE_MajorType_Msk (0xFUL << TPI_DEVTYPE_MajorType_Pos) /*!< TPI DEVTYPE: MajorType Mask */ /*@}*/ /* end of group CMSIS_TPI */ #if (__MPU_PRESENT == 1) /** \ingroup CMSIS_core_register \defgroup CMSIS_MPU Memory Protection Unit (MPU) \brief Type definitions for the Memory Protection Unit (MPU) @{ */ /** \brief Structure type to access the Memory Protection Unit (MPU). */ typedef struct { __I uint32_t TYPE; /*!< Offset: 0x000 (R/ ) MPU Type Register */ __IO uint32_t CTRL; /*!< Offset: 0x004 (R/W) MPU Control Register */ __IO uint32_t RNR; /*!< Offset: 0x008 (R/W) MPU Region RNRber Register */ __IO uint32_t RBAR; /*!< Offset: 0x00C (R/W) MPU Region Base Address Register */ __IO uint32_t RASR; /*!< Offset: 0x010 (R/W) MPU Region Attribute and Size Register */ __IO uint32_t RBAR_A1; /*!< Offset: 0x014 (R/W) MPU Alias 1 Region Base Address Register */ __IO uint32_t RASR_A1; /*!< Offset: 0x018 (R/W) MPU Alias 1 Region Attribute and Size Register */ __IO uint32_t RBAR_A2; /*!< Offset: 0x01C (R/W) MPU Alias 2 Region Base Address Register */ __IO uint32_t RASR_A2; /*!< Offset: 0x020 (R/W) MPU Alias 2 Region Attribute and Size Register */ __IO uint32_t RBAR_A3; /*!< Offset: 0x024 (R/W) MPU Alias 3 Region Base Address Register */ __IO uint32_t RASR_A3; /*!< Offset: 0x028 (R/W) MPU Alias 3 Region Attribute and Size Register */ } MPU_Type; /* MPU Type Register */ #define MPU_TYPE_IREGION_Pos 16 /*!< MPU TYPE: IREGION Position */ #define MPU_TYPE_IREGION_Msk (0xFFUL << MPU_TYPE_IREGION_Pos) /*!< MPU TYPE: IREGION Mask */ #define MPU_TYPE_DREGION_Pos 8 /*!< MPU TYPE: DREGION Position */ #define MPU_TYPE_DREGION_Msk (0xFFUL << MPU_TYPE_DREGION_Pos) /*!< MPU TYPE: DREGION Mask */ #define MPU_TYPE_SEPARATE_Pos 0 /*!< MPU TYPE: SEPARATE Position */ #define MPU_TYPE_SEPARATE_Msk (1UL << MPU_TYPE_SEPARATE_Pos) /*!< MPU TYPE: SEPARATE Mask */ /* MPU Control Register */ #define MPU_CTRL_PRIVDEFENA_Pos 2 /*!< MPU CTRL: PRIVDEFENA Position */ #define MPU_CTRL_PRIVDEFENA_Msk (1UL << MPU_CTRL_PRIVDEFENA_Pos) /*!< MPU CTRL: PRIVDEFENA Mask */ #define MPU_CTRL_HFNMIENA_Pos 1 /*!< MPU CTRL: HFNMIENA Position */ #define MPU_CTRL_HFNMIENA_Msk (1UL << MPU_CTRL_HFNMIENA_Pos) /*!< MPU CTRL: HFNMIENA Mask */ #define MPU_CTRL_ENABLE_Pos 0 /*!< MPU CTRL: ENABLE Position */ #define MPU_CTRL_ENABLE_Msk (1UL << MPU_CTRL_ENABLE_Pos) /*!< MPU CTRL: ENABLE Mask */ /* MPU Region Number Register */ #define MPU_RNR_REGION_Pos 0 /*!< MPU RNR: REGION Position */ #define MPU_RNR_REGION_Msk (0xFFUL << MPU_RNR_REGION_Pos) /*!< MPU RNR: REGION Mask */ /* MPU Region Base Address Register */ #define MPU_RBAR_ADDR_Pos 5 /*!< MPU RBAR: ADDR Position */ #define MPU_RBAR_ADDR_Msk (0x7FFFFFFUL << MPU_RBAR_ADDR_Pos) /*!< MPU RBAR: ADDR Mask */ #define MPU_RBAR_VALID_Pos 4 /*!< MPU RBAR: VALID Position */ #define MPU_RBAR_VALID_Msk (1UL << MPU_RBAR_VALID_Pos) /*!< MPU RBAR: VALID Mask */ #define MPU_RBAR_REGION_Pos 0 /*!< MPU RBAR: REGION Position */ #define MPU_RBAR_REGION_Msk (0xFUL << MPU_RBAR_REGION_Pos) /*!< MPU RBAR: REGION Mask */ /* MPU Region Attribute and Size Register */ #define MPU_RASR_ATTRS_Pos 16 /*!< MPU RASR: MPU Region Attribute field Position */ #define MPU_RASR_ATTRS_Msk (0xFFFFUL << MPU_RASR_ATTRS_Pos) /*!< MPU RASR: MPU Region Attribute field Mask */ #define MPU_RASR_XN_Pos 28 /*!< MPU RASR: ATTRS.XN Position */ #define MPU_RASR_XN_Msk (1UL << MPU_RASR_XN_Pos) /*!< MPU RASR: ATTRS.XN Mask */ #define MPU_RASR_AP_Pos 24 /*!< MPU RASR: ATTRS.AP Position */ #define MPU_RASR_AP_Msk (0x7UL << MPU_RASR_AP_Pos) /*!< MPU RASR: ATTRS.AP Mask */ #define MPU_RASR_TEX_Pos 19 /*!< MPU RASR: ATTRS.TEX Position */ #define MPU_RASR_TEX_Msk (0x7UL << MPU_RASR_TEX_Pos) /*!< MPU RASR: ATTRS.TEX Mask */ #define MPU_RASR_S_Pos 18 /*!< MPU RASR: ATTRS.S Position */ #define MPU_RASR_S_Msk (1UL << MPU_RASR_S_Pos) /*!< MPU RASR: ATTRS.S Mask */ #define MPU_RASR_C_Pos 17 /*!< MPU RASR: ATTRS.C Position */ #define MPU_RASR_C_Msk (1UL << MPU_RASR_C_Pos) /*!< MPU RASR: ATTRS.C Mask */ #define MPU_RASR_B_Pos 16 /*!< MPU RASR: ATTRS.B Position */ #define MPU_RASR_B_Msk (1UL << MPU_RASR_B_Pos) /*!< MPU RASR: ATTRS.B Mask */ #define MPU_RASR_SRD_Pos 8 /*!< MPU RASR: Sub-Region Disable Position */ #define MPU_RASR_SRD_Msk (0xFFUL << MPU_RASR_SRD_Pos) /*!< MPU RASR: Sub-Region Disable Mask */ #define MPU_RASR_SIZE_Pos 1 /*!< MPU RASR: Region Size Field Position */ #define MPU_RASR_SIZE_Msk (0x1FUL << MPU_RASR_SIZE_Pos) /*!< MPU RASR: Region Size Field Mask */ #define MPU_RASR_ENABLE_Pos 0 /*!< MPU RASR: Region enable bit Position */ #define MPU_RASR_ENABLE_Msk (1UL << MPU_RASR_ENABLE_Pos) /*!< MPU RASR: Region enable bit Disable Mask */ /*@} end of group CMSIS_MPU */ #endif #if (__FPU_PRESENT == 1) /** \ingroup CMSIS_core_register \defgroup CMSIS_FPU Floating Point Unit (FPU) \brief Type definitions for the Floating Point Unit (FPU) @{ */ /** \brief Structure type to access the Floating Point Unit (FPU). */ typedef struct { uint32_t RESERVED0[1]; __IO uint32_t FPCCR; /*!< Offset: 0x004 (R/W) Floating-Point Context Control Register */ __IO uint32_t FPCAR; /*!< Offset: 0x008 (R/W) Floating-Point Context Address Register */ __IO uint32_t FPDSCR; /*!< Offset: 0x00C (R/W) Floating-Point Default Status Control Register */ __I uint32_t MVFR0; /*!< Offset: 0x010 (R/ ) Media and FP Feature Register 0 */ __I uint32_t MVFR1; /*!< Offset: 0x014 (R/ ) Media and FP Feature Register 1 */ } FPU_Type; /* Floating-Point Context Control Register */ #define FPU_FPCCR_ASPEN_Pos 31 /*!< FPCCR: ASPEN bit Position */ #define FPU_FPCCR_ASPEN_Msk (1UL << FPU_FPCCR_ASPEN_Pos) /*!< FPCCR: ASPEN bit Mask */ #define FPU_FPCCR_LSPEN_Pos 30 /*!< FPCCR: LSPEN Position */ #define FPU_FPCCR_LSPEN_Msk (1UL << FPU_FPCCR_LSPEN_Pos) /*!< FPCCR: LSPEN bit Mask */ #define FPU_FPCCR_MONRDY_Pos 8 /*!< FPCCR: MONRDY Position */ #define FPU_FPCCR_MONRDY_Msk (1UL << FPU_FPCCR_MONRDY_Pos) /*!< FPCCR: MONRDY bit Mask */ #define FPU_FPCCR_BFRDY_Pos 6 /*!< FPCCR: BFRDY Position */ #define FPU_FPCCR_BFRDY_Msk (1UL << FPU_FPCCR_BFRDY_Pos) /*!< FPCCR: BFRDY bit Mask */ #define FPU_FPCCR_MMRDY_Pos 5 /*!< FPCCR: MMRDY Position */ #define FPU_FPCCR_MMRDY_Msk (1UL << FPU_FPCCR_MMRDY_Pos) /*!< FPCCR: MMRDY bit Mask */ #define FPU_FPCCR_HFRDY_Pos 4 /*!< FPCCR: HFRDY Position */ #define FPU_FPCCR_HFRDY_Msk (1UL << FPU_FPCCR_HFRDY_Pos) /*!< FPCCR: HFRDY bit Mask */ #define FPU_FPCCR_THREAD_Pos 3 /*!< FPCCR: processor mode bit Position */ #define FPU_FPCCR_THREAD_Msk (1UL << FPU_FPCCR_THREAD_Pos) /*!< FPCCR: processor mode active bit Mask */ #define FPU_FPCCR_USER_Pos 1 /*!< FPCCR: privilege level bit Position */ #define FPU_FPCCR_USER_Msk (1UL << FPU_FPCCR_USER_Pos) /*!< FPCCR: privilege level bit Mask */ #define FPU_FPCCR_LSPACT_Pos 0 /*!< FPCCR: Lazy state preservation active bit Position */ #define FPU_FPCCR_LSPACT_Msk (1UL << FPU_FPCCR_LSPACT_Pos) /*!< FPCCR: Lazy state preservation active bit Mask */ /* Floating-Point Context Address Register */ #define FPU_FPCAR_ADDRESS_Pos 3 /*!< FPCAR: ADDRESS bit Position */ #define FPU_FPCAR_ADDRESS_Msk (0x1FFFFFFFUL << FPU_FPCAR_ADDRESS_Pos) /*!< FPCAR: ADDRESS bit Mask */ /* Floating-Point Default Status Control Register */ #define FPU_FPDSCR_AHP_Pos 26 /*!< FPDSCR: AHP bit Position */ #define FPU_FPDSCR_AHP_Msk (1UL << FPU_FPDSCR_AHP_Pos) /*!< FPDSCR: AHP bit Mask */ #define FPU_FPDSCR_DN_Pos 25 /*!< FPDSCR: DN bit Position */ #define FPU_FPDSCR_DN_Msk (1UL << FPU_FPDSCR_DN_Pos) /*!< FPDSCR: DN bit Mask */ #define FPU_FPDSCR_FZ_Pos 24 /*!< FPDSCR: FZ bit Position */ #define FPU_FPDSCR_FZ_Msk (1UL << FPU_FPDSCR_FZ_Pos) /*!< FPDSCR: FZ bit Mask */ #define FPU_FPDSCR_RMode_Pos 22 /*!< FPDSCR: RMode bit Position */ #define FPU_FPDSCR_RMode_Msk (3UL << FPU_FPDSCR_RMode_Pos) /*!< FPDSCR: RMode bit Mask */ /* Media and FP Feature Register 0 */ #define FPU_MVFR0_FP_rounding_modes_Pos 28 /*!< MVFR0: FP rounding modes bits Position */ #define FPU_MVFR0_FP_rounding_modes_Msk (0xFUL << FPU_MVFR0_FP_rounding_modes_Pos) /*!< MVFR0: FP rounding modes bits Mask */ #define FPU_MVFR0_Short_vectors_Pos 24 /*!< MVFR0: Short vectors bits Position */ #define FPU_MVFR0_Short_vectors_Msk (0xFUL << FPU_MVFR0_Short_vectors_Pos) /*!< MVFR0: Short vectors bits Mask */ #define FPU_MVFR0_Square_root_Pos 20 /*!< MVFR0: Square root bits Position */ #define FPU_MVFR0_Square_root_Msk (0xFUL << FPU_MVFR0_Square_root_Pos) /*!< MVFR0: Square root bits Mask */ #define FPU_MVFR0_Divide_Pos 16 /*!< MVFR0: Divide bits Position */ #define FPU_MVFR0_Divide_Msk (0xFUL << FPU_MVFR0_Divide_Pos) /*!< MVFR0: Divide bits Mask */ #define FPU_MVFR0_FP_excep_trapping_Pos 12 /*!< MVFR0: FP exception trapping bits Position */ #define FPU_MVFR0_FP_excep_trapping_Msk (0xFUL << FPU_MVFR0_FP_excep_trapping_Pos) /*!< MVFR0: FP exception trapping bits Mask */ #define FPU_MVFR0_Double_precision_Pos 8 /*!< MVFR0: Double-precision bits Position */ #define FPU_MVFR0_Double_precision_Msk (0xFUL << FPU_MVFR0_Double_precision_Pos) /*!< MVFR0: Double-precision bits Mask */ #define FPU_MVFR0_Single_precision_Pos 4 /*!< MVFR0: Single-precision bits Position */ #define FPU_MVFR0_Single_precision_Msk (0xFUL << FPU_MVFR0_Single_precision_Pos) /*!< MVFR0: Single-precision bits Mask */ #define FPU_MVFR0_A_SIMD_registers_Pos 0 /*!< MVFR0: A_SIMD registers bits Position */ #define FPU_MVFR0_A_SIMD_registers_Msk (0xFUL << FPU_MVFR0_A_SIMD_registers_Pos) /*!< MVFR0: A_SIMD registers bits Mask */ /* Media and FP Feature Register 1 */ #define FPU_MVFR1_FP_fused_MAC_Pos 28 /*!< MVFR1: FP fused MAC bits Position */ #define FPU_MVFR1_FP_fused_MAC_Msk (0xFUL << FPU_MVFR1_FP_fused_MAC_Pos) /*!< MVFR1: FP fused MAC bits Mask */ #define FPU_MVFR1_FP_HPFP_Pos 24 /*!< MVFR1: FP HPFP bits Position */ #define FPU_MVFR1_FP_HPFP_Msk (0xFUL << FPU_MVFR1_FP_HPFP_Pos) /*!< MVFR1: FP HPFP bits Mask */ #define FPU_MVFR1_D_NaN_mode_Pos 4 /*!< MVFR1: D_NaN mode bits Position */ #define FPU_MVFR1_D_NaN_mode_Msk (0xFUL << FPU_MVFR1_D_NaN_mode_Pos) /*!< MVFR1: D_NaN mode bits Mask */ #define FPU_MVFR1_FtZ_mode_Pos 0 /*!< MVFR1: FtZ mode bits Position */ #define FPU_MVFR1_FtZ_mode_Msk (0xFUL << FPU_MVFR1_FtZ_mode_Pos) /*!< MVFR1: FtZ mode bits Mask */ /*@} end of group CMSIS_FPU */ #endif /** \ingroup CMSIS_core_register \defgroup CMSIS_CoreDebug Core Debug Registers (CoreDebug) \brief Type definitions for the Core Debug Registers @{ */ /** \brief Structure type to access the Core Debug Register (CoreDebug). */ typedef struct { __IO uint32_t DHCSR; /*!< Offset: 0x000 (R/W) Debug Halting Control and Status Register */ __O uint32_t DCRSR; /*!< Offset: 0x004 ( /W) Debug Core Register Selector Register */ __IO uint32_t DCRDR; /*!< Offset: 0x008 (R/W) Debug Core Register Data Register */ __IO uint32_t DEMCR; /*!< Offset: 0x00C (R/W) Debug Exception and Monitor Control Register */ } CoreDebug_Type; /* Debug Halting Control and Status Register */ #define CoreDebug_DHCSR_DBGKEY_Pos 16 /*!< CoreDebug DHCSR: DBGKEY Position */ #define CoreDebug_DHCSR_DBGKEY_Msk (0xFFFFUL << CoreDebug_DHCSR_DBGKEY_Pos) /*!< CoreDebug DHCSR: DBGKEY Mask */ #define CoreDebug_DHCSR_S_RESET_ST_Pos 25 /*!< CoreDebug DHCSR: S_RESET_ST Position */ #define CoreDebug_DHCSR_S_RESET_ST_Msk (1UL << CoreDebug_DHCSR_S_RESET_ST_Pos) /*!< CoreDebug DHCSR: S_RESET_ST Mask */ #define CoreDebug_DHCSR_S_RETIRE_ST_Pos 24 /*!< CoreDebug DHCSR: S_RETIRE_ST Position */ #define CoreDebug_DHCSR_S_RETIRE_ST_Msk (1UL << CoreDebug_DHCSR_S_RETIRE_ST_Pos) /*!< CoreDebug DHCSR: S_RETIRE_ST Mask */ #define CoreDebug_DHCSR_S_LOCKUP_Pos 19 /*!< CoreDebug DHCSR: S_LOCKUP Position */ #define CoreDebug_DHCSR_S_LOCKUP_Msk (1UL << CoreDebug_DHCSR_S_LOCKUP_Pos) /*!< CoreDebug DHCSR: S_LOCKUP Mask */ #define CoreDebug_DHCSR_S_SLEEP_Pos 18 /*!< CoreDebug DHCSR: S_SLEEP Position */ #define CoreDebug_DHCSR_S_SLEEP_Msk (1UL << CoreDebug_DHCSR_S_SLEEP_Pos) /*!< CoreDebug DHCSR: S_SLEEP Mask */ #define CoreDebug_DHCSR_S_HALT_Pos 17 /*!< CoreDebug DHCSR: S_HALT Position */ #define CoreDebug_DHCSR_S_HALT_Msk (1UL << CoreDebug_DHCSR_S_HALT_Pos) /*!< CoreDebug DHCSR: S_HALT Mask */ #define CoreDebug_DHCSR_S_REGRDY_Pos 16 /*!< CoreDebug DHCSR: S_REGRDY Position */ #define CoreDebug_DHCSR_S_REGRDY_Msk (1UL << CoreDebug_DHCSR_S_REGRDY_Pos) /*!< CoreDebug DHCSR: S_REGRDY Mask */ #define CoreDebug_DHCSR_C_SNAPSTALL_Pos 5 /*!< CoreDebug DHCSR: C_SNAPSTALL Position */ #define CoreDebug_DHCSR_C_SNAPSTALL_Msk (1UL << CoreDebug_DHCSR_C_SNAPSTALL_Pos) /*!< CoreDebug DHCSR: C_SNAPSTALL Mask */ #define CoreDebug_DHCSR_C_MASKINTS_Pos 3 /*!< CoreDebug DHCSR: C_MASKINTS Position */ #define CoreDebug_DHCSR_C_MASKINTS_Msk (1UL << CoreDebug_DHCSR_C_MASKINTS_Pos) /*!< CoreDebug DHCSR: C_MASKINTS Mask */ #define CoreDebug_DHCSR_C_STEP_Pos 2 /*!< CoreDebug DHCSR: C_STEP Position */ #define CoreDebug_DHCSR_C_STEP_Msk (1UL << CoreDebug_DHCSR_C_STEP_Pos) /*!< CoreDebug DHCSR: C_STEP Mask */ #define CoreDebug_DHCSR_C_HALT_Pos 1 /*!< CoreDebug DHCSR: C_HALT Position */ #define CoreDebug_DHCSR_C_HALT_Msk (1UL << CoreDebug_DHCSR_C_HALT_Pos) /*!< CoreDebug DHCSR: C_HALT Mask */ #define CoreDebug_DHCSR_C_DEBUGEN_Pos 0 /*!< CoreDebug DHCSR: C_DEBUGEN Position */ #define CoreDebug_DHCSR_C_DEBUGEN_Msk (1UL << CoreDebug_DHCSR_C_DEBUGEN_Pos) /*!< CoreDebug DHCSR: C_DEBUGEN Mask */ /* Debug Core Register Selector Register */ #define CoreDebug_DCRSR_REGWnR_Pos 16 /*!< CoreDebug DCRSR: REGWnR Position */ #define CoreDebug_DCRSR_REGWnR_Msk (1UL << CoreDebug_DCRSR_REGWnR_Pos) /*!< CoreDebug DCRSR: REGWnR Mask */ #define CoreDebug_DCRSR_REGSEL_Pos 0 /*!< CoreDebug DCRSR: REGSEL Position */ #define CoreDebug_DCRSR_REGSEL_Msk (0x1FUL << CoreDebug_DCRSR_REGSEL_Pos) /*!< CoreDebug DCRSR: REGSEL Mask */ /* Debug Exception and Monitor Control Register */ #define CoreDebug_DEMCR_TRCENA_Pos 24 /*!< CoreDebug DEMCR: TRCENA Position */ #define CoreDebug_DEMCR_TRCENA_Msk (1UL << CoreDebug_DEMCR_TRCENA_Pos) /*!< CoreDebug DEMCR: TRCENA Mask */ #define CoreDebug_DEMCR_MON_REQ_Pos 19 /*!< CoreDebug DEMCR: MON_REQ Position */ #define CoreDebug_DEMCR_MON_REQ_Msk (1UL << CoreDebug_DEMCR_MON_REQ_Pos) /*!< CoreDebug DEMCR: MON_REQ Mask */ #define CoreDebug_DEMCR_MON_STEP_Pos 18 /*!< CoreDebug DEMCR: MON_STEP Position */ #define CoreDebug_DEMCR_MON_STEP_Msk (1UL << CoreDebug_DEMCR_MON_STEP_Pos) /*!< CoreDebug DEMCR: MON_STEP Mask */ #define CoreDebug_DEMCR_MON_PEND_Pos 17 /*!< CoreDebug DEMCR: MON_PEND Position */ #define CoreDebug_DEMCR_MON_PEND_Msk (1UL << CoreDebug_DEMCR_MON_PEND_Pos) /*!< CoreDebug DEMCR: MON_PEND Mask */ #define CoreDebug_DEMCR_MON_EN_Pos 16 /*!< CoreDebug DEMCR: MON_EN Position */ #define CoreDebug_DEMCR_MON_EN_Msk (1UL << CoreDebug_DEMCR_MON_EN_Pos) /*!< CoreDebug DEMCR: MON_EN Mask */ #define CoreDebug_DEMCR_VC_HARDERR_Pos 10 /*!< CoreDebug DEMCR: VC_HARDERR Position */ #define CoreDebug_DEMCR_VC_HARDERR_Msk (1UL << CoreDebug_DEMCR_VC_HARDERR_Pos) /*!< CoreDebug DEMCR: VC_HARDERR Mask */ #define CoreDebug_DEMCR_VC_INTERR_Pos 9 /*!< CoreDebug DEMCR: VC_INTERR Position */ #define CoreDebug_DEMCR_VC_INTERR_Msk (1UL << CoreDebug_DEMCR_VC_INTERR_Pos) /*!< CoreDebug DEMCR: VC_INTERR Mask */ #define CoreDebug_DEMCR_VC_BUSERR_Pos 8 /*!< CoreDebug DEMCR: VC_BUSERR Position */ #define CoreDebug_DEMCR_VC_BUSERR_Msk (1UL << CoreDebug_DEMCR_VC_BUSERR_Pos) /*!< CoreDebug DEMCR: VC_BUSERR Mask */ #define CoreDebug_DEMCR_VC_STATERR_Pos 7 /*!< CoreDebug DEMCR: VC_STATERR Position */ #define CoreDebug_DEMCR_VC_STATERR_Msk (1UL << CoreDebug_DEMCR_VC_STATERR_Pos) /*!< CoreDebug DEMCR: VC_STATERR Mask */ #define CoreDebug_DEMCR_VC_CHKERR_Pos 6 /*!< CoreDebug DEMCR: VC_CHKERR Position */ #define CoreDebug_DEMCR_VC_CHKERR_Msk (1UL << CoreDebug_DEMCR_VC_CHKERR_Pos) /*!< CoreDebug DEMCR: VC_CHKERR Mask */ #define CoreDebug_DEMCR_VC_NOCPERR_Pos 5 /*!< CoreDebug DEMCR: VC_NOCPERR Position */ #define CoreDebug_DEMCR_VC_NOCPERR_Msk (1UL << CoreDebug_DEMCR_VC_NOCPERR_Pos) /*!< CoreDebug DEMCR: VC_NOCPERR Mask */ #define CoreDebug_DEMCR_VC_MMERR_Pos 4 /*!< CoreDebug DEMCR: VC_MMERR Position */ #define CoreDebug_DEMCR_VC_MMERR_Msk (1UL << CoreDebug_DEMCR_VC_MMERR_Pos) /*!< CoreDebug DEMCR: VC_MMERR Mask */ #define CoreDebug_DEMCR_VC_CORERESET_Pos 0 /*!< CoreDebug DEMCR: VC_CORERESET Position */ #define CoreDebug_DEMCR_VC_CORERESET_Msk (1UL << CoreDebug_DEMCR_VC_CORERESET_Pos) /*!< CoreDebug DEMCR: VC_CORERESET Mask */ /*@} end of group CMSIS_CoreDebug */ /** \ingroup CMSIS_core_register \defgroup CMSIS_core_base Core Definitions \brief Definitions for base addresses, unions, and structures. @{ */ /* Memory mapping of Cortex-M4 Hardware */ #define SCS_BASE (0xE000E000UL) /*!< System Control Space Base Address */ #define ITM_BASE (0xE0000000UL) /*!< ITM Base Address */ #define DWT_BASE (0xE0001000UL) /*!< DWT Base Address */ #define TPI_BASE (0xE0040000UL) /*!< TPI Base Address */ #define CoreDebug_BASE (0xE000EDF0UL) /*!< Core Debug Base Address */ #define SysTick_BASE (SCS_BASE + 0x0010UL) /*!< SysTick Base Address */ #define NVIC_BASE (SCS_BASE + 0x0100UL) /*!< NVIC Base Address */ #define SCB_BASE (SCS_BASE + 0x0D00UL) /*!< System Control Block Base Address */ #define SCnSCB ((SCnSCB_Type *) SCS_BASE ) /*!< System control Register not in SCB */ #define SCB ((SCB_Type *) SCB_BASE ) /*!< SCB configuration struct */ #define SysTick ((SysTick_Type *) SysTick_BASE ) /*!< SysTick configuration struct */ #define NVIC ((NVIC_Type *) NVIC_BASE ) /*!< NVIC configuration struct */ #define ITM ((ITM_Type *) ITM_BASE ) /*!< ITM configuration struct */ #define DWT ((DWT_Type *) DWT_BASE ) /*!< DWT configuration struct */ #define TPI ((TPI_Type *) TPI_BASE ) /*!< TPI configuration struct */ #define CoreDebug ((CoreDebug_Type *) CoreDebug_BASE) /*!< Core Debug configuration struct */ #if (__MPU_PRESENT == 1) #define MPU_BASE (SCS_BASE + 0x0D90UL) /*!< Memory Protection Unit */ #define MPU ((MPU_Type *) MPU_BASE ) /*!< Memory Protection Unit */ #endif #if (__FPU_PRESENT == 1) #define FPU_BASE (SCS_BASE + 0x0F30UL) /*!< Floating Point Unit */ #define FPU ((FPU_Type *) FPU_BASE ) /*!< Floating Point Unit */ #endif /*@} */ /******************************************************************************* * Hardware Abstraction Layer Core Function Interface contains: - Core NVIC Functions - Core SysTick Functions - Core Debug Functions - Core Register Access Functions ******************************************************************************/ /** \defgroup CMSIS_Core_FunctionInterface Functions and Instructions Reference */ /* ########################## NVIC functions #################################### */ /** \ingroup CMSIS_Core_FunctionInterface \defgroup CMSIS_Core_NVICFunctions NVIC Functions \brief Functions that manage interrupts and exceptions via the NVIC. @{ */ /** \brief Set Priority Grouping The function sets the priority grouping field using the required unlock sequence. The parameter PriorityGroup is assigned to the field SCB->AIRCR [10:8] PRIGROUP field. Only values from 0..7 are used. In case of a conflict between priority grouping and available priority bits (__NVIC_PRIO_BITS), the smallest possible priority group is set. \param [in] PriorityGroup Priority grouping field. */ __STATIC_INLINE void NVIC_SetPriorityGrouping(uint32_t PriorityGroup) { uint32_t reg_value; uint32_t PriorityGroupTmp = (PriorityGroup & (uint32_t)0x07); /* only values 0..7 are used */ reg_value = SCB->AIRCR; /* read old register configuration */ reg_value &= ~(SCB_AIRCR_VECTKEY_Msk | SCB_AIRCR_PRIGROUP_Msk); /* clear bits to change */ reg_value = (reg_value | ((uint32_t)0x5FA << SCB_AIRCR_VECTKEY_Pos) | (PriorityGroupTmp << 8)); /* Insert write key and priorty group */ SCB->AIRCR = reg_value; } /** \brief Get Priority Grouping The function reads the priority grouping field from the NVIC Interrupt Controller. \return Priority grouping field (SCB->AIRCR [10:8] PRIGROUP field). */ __STATIC_INLINE uint32_t NVIC_GetPriorityGrouping(void) { return ((SCB->AIRCR & SCB_AIRCR_PRIGROUP_Msk) >> SCB_AIRCR_PRIGROUP_Pos); /* read priority grouping field */ } /** \brief Enable External Interrupt The function enables a device-specific interrupt in the NVIC interrupt controller. \param [in] IRQn External interrupt number. Value cannot be negative. */ __STATIC_INLINE void NVIC_EnableIRQ(IRQn_Type IRQn) { /* NVIC->ISER[((uint32_t)(IRQn) >> 5)] = (1 << ((uint32_t)(IRQn) & 0x1F)); enable interrupt */ NVIC->ISER[(uint32_t)((int32_t)IRQn) >> 5] = (uint32_t)(1 << ((uint32_t)((int32_t)IRQn) & (uint32_t)0x1F)); /* enable interrupt */ } /** \brief Disable External Interrupt The function disables a device-specific interrupt in the NVIC interrupt controller. \param [in] IRQn External interrupt number. Value cannot be negative. */ __STATIC_INLINE void NVIC_DisableIRQ(IRQn_Type IRQn) { NVIC->ICER[((uint32_t)(IRQn) >> 5)] = (1 << ((uint32_t)(IRQn) & 0x1F)); /* disable interrupt */ } /** \brief Get Pending Interrupt The function reads the pending register in the NVIC and returns the pending bit for the specified interrupt. \param [in] IRQn Interrupt number. \return 0 Interrupt status is not pending. \return 1 Interrupt status is pending. */ __STATIC_INLINE uint32_t NVIC_GetPendingIRQ(IRQn_Type IRQn) { return((uint32_t) ((NVIC->ISPR[(uint32_t)(IRQn) >> 5] & (1 << ((uint32_t)(IRQn) & 0x1F)))?1:0)); /* Return 1 if pending else 0 */ } /** \brief Set Pending Interrupt The function sets the pending bit of an external interrupt. \param [in] IRQn Interrupt number. Value cannot be negative. */ __STATIC_INLINE void NVIC_SetPendingIRQ(IRQn_Type IRQn) { NVIC->ISPR[((uint32_t)(IRQn) >> 5)] = (1 << ((uint32_t)(IRQn) & 0x1F)); /* set interrupt pending */ } /** \brief Clear Pending Interrupt The function clears the pending bit of an external interrupt. \param [in] IRQn External interrupt number. Value cannot be negative. */ __STATIC_INLINE void NVIC_ClearPendingIRQ(IRQn_Type IRQn) { NVIC->ICPR[((uint32_t)(IRQn) >> 5)] = (1 << ((uint32_t)(IRQn) & 0x1F)); /* Clear pending interrupt */ } /** \brief Get Active Interrupt The function reads the active register in NVIC and returns the active bit. \param [in] IRQn Interrupt number. \return 0 Interrupt status is not active. \return 1 Interrupt status is active. */ __STATIC_INLINE uint32_t NVIC_GetActive(IRQn_Type IRQn) { return((uint32_t)((NVIC->IABR[(uint32_t)(IRQn) >> 5] & (1 << ((uint32_t)(IRQn) & 0x1F)))?1:0)); /* Return 1 if active else 0 */ } /** \brief Set Interrupt Priority The function sets the priority of an interrupt. \note The priority cannot be set for every core interrupt. \param [in] IRQn Interrupt number. \param [in] priority Priority to set. */ __STATIC_INLINE void NVIC_SetPriority(IRQn_Type IRQn, uint32_t priority) { if(IRQn < 0) { SCB->SHP[((uint32_t)(IRQn) & 0xF)-4] = ((priority << (8 - __NVIC_PRIO_BITS)) & 0xff); } /* set Priority for Cortex-M System Interrupts */ else { NVIC->IP[(uint32_t)(IRQn)] = ((priority << (8 - __NVIC_PRIO_BITS)) & 0xff); } /* set Priority for device specific Interrupts */ } /** \brief Get Interrupt Priority The function reads the priority of an interrupt. The interrupt number can be positive to specify an external (device specific) interrupt, or negative to specify an internal (core) interrupt. \param [in] IRQn Interrupt number. \return Interrupt Priority. Value is aligned automatically to the implemented priority bits of the microcontroller. */ __STATIC_INLINE uint32_t NVIC_GetPriority(IRQn_Type IRQn) { if(IRQn < 0) { return((uint32_t)(SCB->SHP[((uint32_t)(IRQn) & 0xF)-4] >> (8 - __NVIC_PRIO_BITS))); } /* get priority for Cortex-M system interrupts */ else { return((uint32_t)(NVIC->IP[(uint32_t)(IRQn)] >> (8 - __NVIC_PRIO_BITS))); } /* get priority for device specific interrupts */ } /** \brief Encode Priority The function encodes the priority for an interrupt with the given priority group, preemptive priority value, and subpriority value. In case of a conflict between priority grouping and available priority bits (__NVIC_PRIO_BITS), the samllest possible priority group is set. \param [in] PriorityGroup Used priority group. \param [in] PreemptPriority Preemptive priority value (starting from 0). \param [in] SubPriority Subpriority value (starting from 0). \return Encoded priority. Value can be used in the function \ref NVIC_SetPriority(). */ __STATIC_INLINE uint32_t NVIC_EncodePriority (uint32_t PriorityGroup, uint32_t PreemptPriority, uint32_t SubPriority) { uint32_t PriorityGroupTmp = (PriorityGroup & 0x07); /* only values 0..7 are used */ uint32_t PreemptPriorityBits; uint32_t SubPriorityBits; PreemptPriorityBits = ((7 - PriorityGroupTmp) > __NVIC_PRIO_BITS) ? __NVIC_PRIO_BITS : 7 - PriorityGroupTmp; SubPriorityBits = ((PriorityGroupTmp + __NVIC_PRIO_BITS) < 7) ? 0 : PriorityGroupTmp - 7 + __NVIC_PRIO_BITS; return ( ((PreemptPriority & ((1 << (PreemptPriorityBits)) - 1)) << SubPriorityBits) | ((SubPriority & ((1 << (SubPriorityBits )) - 1))) ); } /** \brief Decode Priority The function decodes an interrupt priority value with a given priority group to preemptive priority value and subpriority value. In case of a conflict between priority grouping and available priority bits (__NVIC_PRIO_BITS) the samllest possible priority group is set. \param [in] Priority Priority value, which can be retrieved with the function \ref NVIC_GetPriority(). \param [in] PriorityGroup Used priority group. \param [out] pPreemptPriority Preemptive priority value (starting from 0). \param [out] pSubPriority Subpriority value (starting from 0). */ __STATIC_INLINE void NVIC_DecodePriority (uint32_t Priority, uint32_t PriorityGroup, uint32_t* pPreemptPriority, uint32_t* pSubPriority) { uint32_t PriorityGroupTmp = (PriorityGroup & 0x07); /* only values 0..7 are used */ uint32_t PreemptPriorityBits; uint32_t SubPriorityBits; PreemptPriorityBits = ((7 - PriorityGroupTmp) > __NVIC_PRIO_BITS) ? __NVIC_PRIO_BITS : 7 - PriorityGroupTmp; SubPriorityBits = ((PriorityGroupTmp + __NVIC_PRIO_BITS) < 7) ? 0 : PriorityGroupTmp - 7 + __NVIC_PRIO_BITS; *pPreemptPriority = (Priority >> SubPriorityBits) & ((1 << (PreemptPriorityBits)) - 1); *pSubPriority = (Priority ) & ((1 << (SubPriorityBits )) - 1); } /** \brief System Reset The function initiates a system reset request to reset the MCU. */ __STATIC_INLINE void NVIC_SystemReset(void) { __DSB(); /* Ensure all outstanding memory accesses included buffered write are completed before reset */ SCB->AIRCR = ((0x5FA << SCB_AIRCR_VECTKEY_Pos) | (SCB->AIRCR & SCB_AIRCR_PRIGROUP_Msk) | SCB_AIRCR_SYSRESETREQ_Msk); /* Keep priority group unchanged */ __DSB(); /* Ensure completion of memory access */ while(1); /* wait until reset */ } /*@} end of CMSIS_Core_NVICFunctions */ /* ################################## SysTick function ############################################ */ /** \ingroup CMSIS_Core_FunctionInterface \defgroup CMSIS_Core_SysTickFunctions SysTick Functions \brief Functions that configure the System. @{ */ #if (__Vendor_SysTickConfig == 0) /** \brief System Tick Configuration The function initializes the System Timer and its interrupt, and starts the System Tick Timer. Counter is in free running mode to generate periodic interrupts. \param [in] ticks Number of ticks between two interrupts. \return 0 Function succeeded. \return 1 Function failed. \note When the variable __Vendor_SysTickConfig is set to 1, then the function SysTick_Config is not included. In this case, the file device.h must contain a vendor-specific implementation of this function. */ __STATIC_INLINE uint32_t SysTick_Config(uint32_t ticks) { if ((ticks - 1) > SysTick_LOAD_RELOAD_Msk) return (1); /* Reload value impossible */ SysTick->LOAD = ticks - 1; /* set reload register */ NVIC_SetPriority (SysTick_IRQn, (1<<__NVIC_PRIO_BITS) - 1); /* set Priority for Systick Interrupt */ SysTick->VAL = 0; /* Load the SysTick Counter Value */ SysTick->CTRL = SysTick_CTRL_CLKSOURCE_Msk | SysTick_CTRL_TICKINT_Msk | SysTick_CTRL_ENABLE_Msk; /* Enable SysTick IRQ and SysTick Timer */ return (0); /* Function successful */ } #endif /*@} end of CMSIS_Core_SysTickFunctions */ /* ##################################### Debug In/Output function ########################################### */ /** \ingroup CMSIS_Core_FunctionInterface \defgroup CMSIS_core_DebugFunctions ITM Functions \brief Functions that access the ITM debug interface. @{ */ extern volatile int32_t ITM_RxBuffer; /*!< External variable to receive characters. */ #define ITM_RXBUFFER_EMPTY 0x5AA55AA5 /*!< Value identifying \ref ITM_RxBuffer is ready for next character. */ /** \brief ITM Send Character The function transmits a character via the ITM channel 0, and \li Just returns when no debugger is connected that has booked the output. \li Is blocking when a debugger is connected, but the previous character sent has not been transmitted. \param [in] ch Character to transmit. \returns Character to transmit. */ __STATIC_INLINE uint32_t ITM_SendChar (uint32_t ch) { if ((ITM->TCR & ITM_TCR_ITMENA_Msk) && /* ITM enabled */ (ITM->TER & (1UL << 0) ) ) /* ITM Port #0 enabled */ { while (ITM->PORT[0].u32 == 0); ITM->PORT[0].u8 = (uint8_t) ch; } return (ch); } /** \brief ITM Receive Character The function inputs a character via the external variable \ref ITM_RxBuffer. \return Received character. \return -1 No character pending. */ __STATIC_INLINE int32_t ITM_ReceiveChar (void) { int32_t ch = -1; /* no character available */ if (ITM_RxBuffer != ITM_RXBUFFER_EMPTY) { ch = ITM_RxBuffer; ITM_RxBuffer = ITM_RXBUFFER_EMPTY; /* ready for next character */ } return (ch); } /** \brief ITM Check Character The function checks whether a character is pending for reading in the variable \ref ITM_RxBuffer. \return 0 No character available. \return 1 Character available. */ __STATIC_INLINE int32_t ITM_CheckChar (void) { if (ITM_RxBuffer == ITM_RXBUFFER_EMPTY) { return (0); /* no character available */ } else { return (1); /* character available */ } } /*@} end of CMSIS_core_DebugFunctions */ #endif /* __CORE_CM4_H_DEPENDANT */ #endif /* __CMSIS_GENERIC */ #ifdef __cplusplus } #endif ================================================ FILE: Zelig/mbed/TARGET_NUCLEO_L152RE/core_cm4_simd.h ================================================ /**************************************************************************//** * @file core_cm4_simd.h * @brief CMSIS Cortex-M4 SIMD Header File * @version V3.20 * @date 25. February 2013 * * @note * ******************************************************************************/ /* Copyright (c) 2009 - 2013 ARM LIMITED All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: - Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. - Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. - Neither the name of ARM 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 COPYRIGHT HOLDERS AND CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. ---------------------------------------------------------------------------*/ #ifdef __cplusplus extern "C" { #endif #ifndef __CORE_CM4_SIMD_H #define __CORE_CM4_SIMD_H /******************************************************************************* * Hardware Abstraction Layer ******************************************************************************/ /* ################### Compiler specific Intrinsics ########################### */ /** \defgroup CMSIS_SIMD_intrinsics CMSIS SIMD Intrinsics Access to dedicated SIMD instructions @{ */ #if defined ( __CC_ARM ) /*------------------RealView Compiler -----------------*/ /* ARM armcc specific functions */ /*------ CM4 SIMD Intrinsics -----------------------------------------------------*/ #define __SADD8 __sadd8 #define __QADD8 __qadd8 #define __SHADD8 __shadd8 #define __UADD8 __uadd8 #define __UQADD8 __uqadd8 #define __UHADD8 __uhadd8 #define __SSUB8 __ssub8 #define __QSUB8 __qsub8 #define __SHSUB8 __shsub8 #define __USUB8 __usub8 #define __UQSUB8 __uqsub8 #define __UHSUB8 __uhsub8 #define __SADD16 __sadd16 #define __QADD16 __qadd16 #define __SHADD16 __shadd16 #define __UADD16 __uadd16 #define __UQADD16 __uqadd16 #define __UHADD16 __uhadd16 #define __SSUB16 __ssub16 #define __QSUB16 __qsub16 #define __SHSUB16 __shsub16 #define __USUB16 __usub16 #define __UQSUB16 __uqsub16 #define __UHSUB16 __uhsub16 #define __SASX __sasx #define __QASX __qasx #define __SHASX __shasx #define __UASX __uasx #define __UQASX __uqasx #define __UHASX __uhasx #define __SSAX __ssax #define __QSAX __qsax #define __SHSAX __shsax #define __USAX __usax #define __UQSAX __uqsax #define __UHSAX __uhsax #define __USAD8 __usad8 #define __USADA8 __usada8 #define __SSAT16 __ssat16 #define __USAT16 __usat16 #define __UXTB16 __uxtb16 #define __UXTAB16 __uxtab16 #define __SXTB16 __sxtb16 #define __SXTAB16 __sxtab16 #define __SMUAD __smuad #define __SMUADX __smuadx #define __SMLAD __smlad #define __SMLADX __smladx #define __SMLALD __smlald #define __SMLALDX __smlaldx #define __SMUSD __smusd #define __SMUSDX __smusdx #define __SMLSD __smlsd #define __SMLSDX __smlsdx #define __SMLSLD __smlsld #define __SMLSLDX __smlsldx #define __SEL __sel #define __QADD __qadd #define __QSUB __qsub #define __PKHBT(ARG1,ARG2,ARG3) ( ((((uint32_t)(ARG1)) ) & 0x0000FFFFUL) | \ ((((uint32_t)(ARG2)) << (ARG3)) & 0xFFFF0000UL) ) #define __PKHTB(ARG1,ARG2,ARG3) ( ((((uint32_t)(ARG1)) ) & 0xFFFF0000UL) | \ ((((uint32_t)(ARG2)) >> (ARG3)) & 0x0000FFFFUL) ) #define __SMMLA(ARG1,ARG2,ARG3) ( (int32_t)((((int64_t)(ARG1) * (ARG2)) + \ ((int64_t)(ARG3) << 32) ) >> 32)) /*-- End CM4 SIMD Intrinsics -----------------------------------------------------*/ #elif defined ( __ICCARM__ ) /*------------------ ICC Compiler -------------------*/ /* IAR iccarm specific functions */ /*------ CM4 SIMD Intrinsics -----------------------------------------------------*/ #include /*-- End CM4 SIMD Intrinsics -----------------------------------------------------*/ #elif defined ( __TMS470__ ) /*---------------- TI CCS Compiler ------------------*/ /* TI CCS specific functions */ /*------ CM4 SIMD Intrinsics -----------------------------------------------------*/ #include /*-- End CM4 SIMD Intrinsics -----------------------------------------------------*/ #elif defined ( __GNUC__ ) /*------------------ GNU Compiler ---------------------*/ /* GNU gcc specific functions */ /*------ CM4 SIMD Intrinsics -----------------------------------------------------*/ __attribute__( ( always_inline ) ) __STATIC_INLINE uint32_t __SADD8(uint32_t op1, uint32_t op2) { uint32_t result; __ASM volatile ("sadd8 %0, %1, %2" : "=r" (result) : "r" (op1), "r" (op2) ); return(result); } __attribute__( ( always_inline ) ) __STATIC_INLINE uint32_t __QADD8(uint32_t op1, uint32_t op2) { uint32_t result; __ASM volatile ("qadd8 %0, %1, %2" : "=r" (result) : "r" (op1), "r" (op2) ); return(result); } __attribute__( ( always_inline ) ) __STATIC_INLINE uint32_t __SHADD8(uint32_t op1, uint32_t op2) { uint32_t result; __ASM volatile ("shadd8 %0, %1, %2" : "=r" (result) : "r" (op1), "r" (op2) ); return(result); } __attribute__( ( always_inline ) ) __STATIC_INLINE uint32_t __UADD8(uint32_t op1, uint32_t op2) { uint32_t result; __ASM volatile ("uadd8 %0, %1, %2" : "=r" (result) : "r" (op1), "r" (op2) ); return(result); } __attribute__( ( always_inline ) ) __STATIC_INLINE uint32_t __UQADD8(uint32_t op1, uint32_t op2) { uint32_t result; __ASM volatile ("uqadd8 %0, %1, %2" : "=r" (result) : "r" (op1), "r" (op2) ); return(result); } __attribute__( ( always_inline ) ) __STATIC_INLINE uint32_t __UHADD8(uint32_t op1, uint32_t op2) { uint32_t result; __ASM volatile ("uhadd8 %0, %1, %2" : "=r" (result) : "r" (op1), "r" (op2) ); return(result); } __attribute__( ( always_inline ) ) __STATIC_INLINE uint32_t __SSUB8(uint32_t op1, uint32_t op2) { uint32_t result; __ASM volatile ("ssub8 %0, %1, %2" : "=r" (result) : "r" (op1), "r" (op2) ); return(result); } __attribute__( ( always_inline ) ) __STATIC_INLINE uint32_t __QSUB8(uint32_t op1, uint32_t op2) { uint32_t result; __ASM volatile ("qsub8 %0, %1, %2" : "=r" (result) : "r" (op1), "r" (op2) ); return(result); } __attribute__( ( always_inline ) ) __STATIC_INLINE uint32_t __SHSUB8(uint32_t op1, uint32_t op2) { uint32_t result; __ASM volatile ("shsub8 %0, %1, %2" : "=r" (result) : "r" (op1), "r" (op2) ); return(result); } __attribute__( ( always_inline ) ) __STATIC_INLINE uint32_t __USUB8(uint32_t op1, uint32_t op2) { uint32_t result; __ASM volatile ("usub8 %0, %1, %2" : "=r" (result) : "r" (op1), "r" (op2) ); return(result); } __attribute__( ( always_inline ) ) __STATIC_INLINE uint32_t __UQSUB8(uint32_t op1, uint32_t op2) { uint32_t result; __ASM volatile ("uqsub8 %0, %1, %2" : "=r" (result) : "r" (op1), "r" (op2) ); return(result); } __attribute__( ( always_inline ) ) __STATIC_INLINE uint32_t __UHSUB8(uint32_t op1, uint32_t op2) { uint32_t result; __ASM volatile ("uhsub8 %0, %1, %2" : "=r" (result) : "r" (op1), "r" (op2) ); return(result); } __attribute__( ( always_inline ) ) __STATIC_INLINE uint32_t __SADD16(uint32_t op1, uint32_t op2) { uint32_t result; __ASM volatile ("sadd16 %0, %1, %2" : "=r" (result) : "r" (op1), "r" (op2) ); return(result); } __attribute__( ( always_inline ) ) __STATIC_INLINE uint32_t __QADD16(uint32_t op1, uint32_t op2) { uint32_t result; __ASM volatile ("qadd16 %0, %1, %2" : "=r" (result) : "r" (op1), "r" (op2) ); return(result); } __attribute__( ( always_inline ) ) __STATIC_INLINE uint32_t __SHADD16(uint32_t op1, uint32_t op2) { uint32_t result; __ASM volatile ("shadd16 %0, %1, %2" : "=r" (result) : "r" (op1), "r" (op2) ); return(result); } __attribute__( ( always_inline ) ) __STATIC_INLINE uint32_t __UADD16(uint32_t op1, uint32_t op2) { uint32_t result; __ASM volatile ("uadd16 %0, %1, %2" : "=r" (result) : "r" (op1), "r" (op2) ); return(result); } __attribute__( ( always_inline ) ) __STATIC_INLINE uint32_t __UQADD16(uint32_t op1, uint32_t op2) { uint32_t result; __ASM volatile ("uqadd16 %0, %1, %2" : "=r" (result) : "r" (op1), "r" (op2) ); return(result); } __attribute__( ( always_inline ) ) __STATIC_INLINE uint32_t __UHADD16(uint32_t op1, uint32_t op2) { uint32_t result; __ASM volatile ("uhadd16 %0, %1, %2" : "=r" (result) : "r" (op1), "r" (op2) ); return(result); } __attribute__( ( always_inline ) ) __STATIC_INLINE uint32_t __SSUB16(uint32_t op1, uint32_t op2) { uint32_t result; __ASM volatile ("ssub16 %0, %1, %2" : "=r" (result) : "r" (op1), "r" (op2) ); return(result); } __attribute__( ( always_inline ) ) __STATIC_INLINE uint32_t __QSUB16(uint32_t op1, uint32_t op2) { uint32_t result; __ASM volatile ("qsub16 %0, %1, %2" : "=r" (result) : "r" (op1), "r" (op2) ); return(result); } __attribute__( ( always_inline ) ) __STATIC_INLINE uint32_t __SHSUB16(uint32_t op1, uint32_t op2) { uint32_t result; __ASM volatile ("shsub16 %0, %1, %2" : "=r" (result) : "r" (op1), "r" (op2) ); return(result); } __attribute__( ( always_inline ) ) __STATIC_INLINE uint32_t __USUB16(uint32_t op1, uint32_t op2) { uint32_t result; __ASM volatile ("usub16 %0, %1, %2" : "=r" (result) : "r" (op1), "r" (op2) ); return(result); } __attribute__( ( always_inline ) ) __STATIC_INLINE uint32_t __UQSUB16(uint32_t op1, uint32_t op2) { uint32_t result; __ASM volatile ("uqsub16 %0, %1, %2" : "=r" (result) : "r" (op1), "r" (op2) ); return(result); } __attribute__( ( always_inline ) ) __STATIC_INLINE uint32_t __UHSUB16(uint32_t op1, uint32_t op2) { uint32_t result; __ASM volatile ("uhsub16 %0, %1, %2" : "=r" (result) : "r" (op1), "r" (op2) ); return(result); } __attribute__( ( always_inline ) ) __STATIC_INLINE uint32_t __SASX(uint32_t op1, uint32_t op2) { uint32_t result; __ASM volatile ("sasx %0, %1, %2" : "=r" (result) : "r" (op1), "r" (op2) ); return(result); } __attribute__( ( always_inline ) ) __STATIC_INLINE uint32_t __QASX(uint32_t op1, uint32_t op2) { uint32_t result; __ASM volatile ("qasx %0, %1, %2" : "=r" (result) : "r" (op1), "r" (op2) ); return(result); } __attribute__( ( always_inline ) ) __STATIC_INLINE uint32_t __SHASX(uint32_t op1, uint32_t op2) { uint32_t result; __ASM volatile ("shasx %0, %1, %2" : "=r" (result) : "r" (op1), "r" (op2) ); return(result); } __attribute__( ( always_inline ) ) __STATIC_INLINE uint32_t __UASX(uint32_t op1, uint32_t op2) { uint32_t result; __ASM volatile ("uasx %0, %1, %2" : "=r" (result) : "r" (op1), "r" (op2) ); return(result); } __attribute__( ( always_inline ) ) __STATIC_INLINE uint32_t __UQASX(uint32_t op1, uint32_t op2) { uint32_t result; __ASM volatile ("uqasx %0, %1, %2" : "=r" (result) : "r" (op1), "r" (op2) ); return(result); } __attribute__( ( always_inline ) ) __STATIC_INLINE uint32_t __UHASX(uint32_t op1, uint32_t op2) { uint32_t result; __ASM volatile ("uhasx %0, %1, %2" : "=r" (result) : "r" (op1), "r" (op2) ); return(result); } __attribute__( ( always_inline ) ) __STATIC_INLINE uint32_t __SSAX(uint32_t op1, uint32_t op2) { uint32_t result; __ASM volatile ("ssax %0, %1, %2" : "=r" (result) : "r" (op1), "r" (op2) ); return(result); } __attribute__( ( always_inline ) ) __STATIC_INLINE uint32_t __QSAX(uint32_t op1, uint32_t op2) { uint32_t result; __ASM volatile ("qsax %0, %1, %2" : "=r" (result) : "r" (op1), "r" (op2) ); return(result); } __attribute__( ( always_inline ) ) __STATIC_INLINE uint32_t __SHSAX(uint32_t op1, uint32_t op2) { uint32_t result; __ASM volatile ("shsax %0, %1, %2" : "=r" (result) : "r" (op1), "r" (op2) ); return(result); } __attribute__( ( always_inline ) ) __STATIC_INLINE uint32_t __USAX(uint32_t op1, uint32_t op2) { uint32_t result; __ASM volatile ("usax %0, %1, %2" : "=r" (result) : "r" (op1), "r" (op2) ); return(result); } __attribute__( ( always_inline ) ) __STATIC_INLINE uint32_t __UQSAX(uint32_t op1, uint32_t op2) { uint32_t result; __ASM volatile ("uqsax %0, %1, %2" : "=r" (result) : "r" (op1), "r" (op2) ); return(result); } __attribute__( ( always_inline ) ) __STATIC_INLINE uint32_t __UHSAX(uint32_t op1, uint32_t op2) { uint32_t result; __ASM volatile ("uhsax %0, %1, %2" : "=r" (result) : "r" (op1), "r" (op2) ); return(result); } __attribute__( ( always_inline ) ) __STATIC_INLINE uint32_t __USAD8(uint32_t op1, uint32_t op2) { uint32_t result; __ASM volatile ("usad8 %0, %1, %2" : "=r" (result) : "r" (op1), "r" (op2) ); return(result); } __attribute__( ( always_inline ) ) __STATIC_INLINE uint32_t __USADA8(uint32_t op1, uint32_t op2, uint32_t op3) { uint32_t result; __ASM volatile ("usada8 %0, %1, %2, %3" : "=r" (result) : "r" (op1), "r" (op2), "r" (op3) ); return(result); } #define __SSAT16(ARG1,ARG2) \ ({ \ uint32_t __RES, __ARG1 = (ARG1); \ __ASM ("ssat16 %0, %1, %2" : "=r" (__RES) : "I" (ARG2), "r" (__ARG1) ); \ __RES; \ }) #define __USAT16(ARG1,ARG2) \ ({ \ uint32_t __RES, __ARG1 = (ARG1); \ __ASM ("usat16 %0, %1, %2" : "=r" (__RES) : "I" (ARG2), "r" (__ARG1) ); \ __RES; \ }) __attribute__( ( always_inline ) ) __STATIC_INLINE uint32_t __UXTB16(uint32_t op1) { uint32_t result; __ASM volatile ("uxtb16 %0, %1" : "=r" (result) : "r" (op1)); return(result); } __attribute__( ( always_inline ) ) __STATIC_INLINE uint32_t __UXTAB16(uint32_t op1, uint32_t op2) { uint32_t result; __ASM volatile ("uxtab16 %0, %1, %2" : "=r" (result) : "r" (op1), "r" (op2) ); return(result); } __attribute__( ( always_inline ) ) __STATIC_INLINE uint32_t __SXTB16(uint32_t op1) { uint32_t result; __ASM volatile ("sxtb16 %0, %1" : "=r" (result) : "r" (op1)); return(result); } __attribute__( ( always_inline ) ) __STATIC_INLINE uint32_t __SXTAB16(uint32_t op1, uint32_t op2) { uint32_t result; __ASM volatile ("sxtab16 %0, %1, %2" : "=r" (result) : "r" (op1), "r" (op2) ); return(result); } __attribute__( ( always_inline ) ) __STATIC_INLINE uint32_t __SMUAD (uint32_t op1, uint32_t op2) { uint32_t result; __ASM volatile ("smuad %0, %1, %2" : "=r" (result) : "r" (op1), "r" (op2) ); return(result); } __attribute__( ( always_inline ) ) __STATIC_INLINE uint32_t __SMUADX (uint32_t op1, uint32_t op2) { uint32_t result; __ASM volatile ("smuadx %0, %1, %2" : "=r" (result) : "r" (op1), "r" (op2) ); return(result); } __attribute__( ( always_inline ) ) __STATIC_INLINE uint32_t __SMLAD (uint32_t op1, uint32_t op2, uint32_t op3) { uint32_t result; __ASM volatile ("smlad %0, %1, %2, %3" : "=r" (result) : "r" (op1), "r" (op2), "r" (op3) ); return(result); } __attribute__( ( always_inline ) ) __STATIC_INLINE uint32_t __SMLADX (uint32_t op1, uint32_t op2, uint32_t op3) { uint32_t result; __ASM volatile ("smladx %0, %1, %2, %3" : "=r" (result) : "r" (op1), "r" (op2), "r" (op3) ); return(result); } #define __SMLALD(ARG1,ARG2,ARG3) \ ({ \ uint32_t __ARG1 = (ARG1), __ARG2 = (ARG2), __ARG3_H = (uint32_t)((uint64_t)(ARG3) >> 32), __ARG3_L = (uint32_t)((uint64_t)(ARG3) & 0xFFFFFFFFUL); \ __ASM volatile ("smlald %0, %1, %2, %3" : "=r" (__ARG3_L), "=r" (__ARG3_H) : "r" (__ARG1), "r" (__ARG2), "0" (__ARG3_L), "1" (__ARG3_H) ); \ (uint64_t)(((uint64_t)__ARG3_H << 32) | __ARG3_L); \ }) #define __SMLALDX(ARG1,ARG2,ARG3) \ ({ \ uint32_t __ARG1 = (ARG1), __ARG2 = (ARG2), __ARG3_H = (uint32_t)((uint64_t)(ARG3) >> 32), __ARG3_L = (uint32_t)((uint64_t)(ARG3) & 0xFFFFFFFFUL); \ __ASM volatile ("smlaldx %0, %1, %2, %3" : "=r" (__ARG3_L), "=r" (__ARG3_H) : "r" (__ARG1), "r" (__ARG2), "0" (__ARG3_L), "1" (__ARG3_H) ); \ (uint64_t)(((uint64_t)__ARG3_H << 32) | __ARG3_L); \ }) __attribute__( ( always_inline ) ) __STATIC_INLINE uint32_t __SMUSD (uint32_t op1, uint32_t op2) { uint32_t result; __ASM volatile ("smusd %0, %1, %2" : "=r" (result) : "r" (op1), "r" (op2) ); return(result); } __attribute__( ( always_inline ) ) __STATIC_INLINE uint32_t __SMUSDX (uint32_t op1, uint32_t op2) { uint32_t result; __ASM volatile ("smusdx %0, %1, %2" : "=r" (result) : "r" (op1), "r" (op2) ); return(result); } __attribute__( ( always_inline ) ) __STATIC_INLINE uint32_t __SMLSD (uint32_t op1, uint32_t op2, uint32_t op3) { uint32_t result; __ASM volatile ("smlsd %0, %1, %2, %3" : "=r" (result) : "r" (op1), "r" (op2), "r" (op3) ); return(result); } __attribute__( ( always_inline ) ) __STATIC_INLINE uint32_t __SMLSDX (uint32_t op1, uint32_t op2, uint32_t op3) { uint32_t result; __ASM volatile ("smlsdx %0, %1, %2, %3" : "=r" (result) : "r" (op1), "r" (op2), "r" (op3) ); return(result); } #define __SMLSLD(ARG1,ARG2,ARG3) \ ({ \ uint32_t __ARG1 = (ARG1), __ARG2 = (ARG2), __ARG3_H = (uint32_t)((ARG3) >> 32), __ARG3_L = (uint32_t)((ARG3) & 0xFFFFFFFFUL); \ __ASM volatile ("smlsld %0, %1, %2, %3" : "=r" (__ARG3_L), "=r" (__ARG3_H) : "r" (__ARG1), "r" (__ARG2), "0" (__ARG3_L), "1" (__ARG3_H) ); \ (uint64_t)(((uint64_t)__ARG3_H << 32) | __ARG3_L); \ }) #define __SMLSLDX(ARG1,ARG2,ARG3) \ ({ \ uint32_t __ARG1 = (ARG1), __ARG2 = (ARG2), __ARG3_H = (uint32_t)((ARG3) >> 32), __ARG3_L = (uint32_t)((ARG3) & 0xFFFFFFFFUL); \ __ASM volatile ("smlsldx %0, %1, %2, %3" : "=r" (__ARG3_L), "=r" (__ARG3_H) : "r" (__ARG1), "r" (__ARG2), "0" (__ARG3_L), "1" (__ARG3_H) ); \ (uint64_t)(((uint64_t)__ARG3_H << 32) | __ARG3_L); \ }) __attribute__( ( always_inline ) ) __STATIC_INLINE uint32_t __SEL (uint32_t op1, uint32_t op2) { uint32_t result; __ASM volatile ("sel %0, %1, %2" : "=r" (result) : "r" (op1), "r" (op2) ); return(result); } __attribute__( ( always_inline ) ) __STATIC_INLINE uint32_t __QADD(uint32_t op1, uint32_t op2) { uint32_t result; __ASM volatile ("qadd %0, %1, %2" : "=r" (result) : "r" (op1), "r" (op2) ); return(result); } __attribute__( ( always_inline ) ) __STATIC_INLINE uint32_t __QSUB(uint32_t op1, uint32_t op2) { uint32_t result; __ASM volatile ("qsub %0, %1, %2" : "=r" (result) : "r" (op1), "r" (op2) ); return(result); } #define __PKHBT(ARG1,ARG2,ARG3) \ ({ \ uint32_t __RES, __ARG1 = (ARG1), __ARG2 = (ARG2); \ __ASM ("pkhbt %0, %1, %2, lsl %3" : "=r" (__RES) : "r" (__ARG1), "r" (__ARG2), "I" (ARG3) ); \ __RES; \ }) #define __PKHTB(ARG1,ARG2,ARG3) \ ({ \ uint32_t __RES, __ARG1 = (ARG1), __ARG2 = (ARG2); \ if (ARG3 == 0) \ __ASM ("pkhtb %0, %1, %2" : "=r" (__RES) : "r" (__ARG1), "r" (__ARG2) ); \ else \ __ASM ("pkhtb %0, %1, %2, asr %3" : "=r" (__RES) : "r" (__ARG1), "r" (__ARG2), "I" (ARG3) ); \ __RES; \ }) __attribute__( ( always_inline ) ) __STATIC_INLINE uint32_t __SMMLA (int32_t op1, int32_t op2, int32_t op3) { int32_t result; __ASM volatile ("smmla %0, %1, %2, %3" : "=r" (result): "r" (op1), "r" (op2), "r" (op3) ); return(result); } /*-- End CM4 SIMD Intrinsics -----------------------------------------------------*/ #elif defined ( __TASKING__ ) /*------------------ TASKING Compiler --------------*/ /* TASKING carm specific functions */ /*------ CM4 SIMD Intrinsics -----------------------------------------------------*/ /* not yet supported */ /*-- End CM4 SIMD Intrinsics -----------------------------------------------------*/ #endif /*@} end of group CMSIS_SIMD_intrinsics */ #endif /* __CORE_CM4_SIMD_H */ #ifdef __cplusplus } #endif ================================================ FILE: Zelig/mbed/TARGET_NUCLEO_L152RE/core_cm7.h ================================================ /**************************************************************************//** * @file core_cm7.h * @brief CMSIS Cortex-M7 Core Peripheral Access Layer Header File * @version V4.10 * @date 18. March 2015 * * @note * ******************************************************************************/ /* Copyright (c) 2009 - 2015 ARM LIMITED All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: - Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. - Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. - Neither the name of ARM 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 COPYRIGHT HOLDERS AND 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. ---------------------------------------------------------------------------*/ #if defined ( __ICCARM__ ) #pragma system_include /* treat file as system include file for MISRA check */ #endif #ifndef __CORE_CM7_H_GENERIC #define __CORE_CM7_H_GENERIC #ifdef __cplusplus extern "C" { #endif /** \page CMSIS_MISRA_Exceptions MISRA-C:2004 Compliance Exceptions CMSIS violates the following MISRA-C:2004 rules: \li Required Rule 8.5, object/function definition in header file.
Function definitions in header files are used to allow 'inlining'. \li Required Rule 18.4, declaration of union type or object of union type: '{...}'.
Unions are used for effective representation of core registers. \li Advisory Rule 19.7, Function-like macro defined.
Function-like macros are used to allow more efficient code. */ /******************************************************************************* * CMSIS definitions ******************************************************************************/ /** \ingroup Cortex_M7 @{ */ /* CMSIS CM7 definitions */ #define __CM7_CMSIS_VERSION_MAIN (0x04) /*!< [31:16] CMSIS HAL main version */ #define __CM7_CMSIS_VERSION_SUB (0x00) /*!< [15:0] CMSIS HAL sub version */ #define __CM7_CMSIS_VERSION ((__CM7_CMSIS_VERSION_MAIN << 16) | \ __CM7_CMSIS_VERSION_SUB ) /*!< CMSIS HAL version number */ #define __CORTEX_M (0x07) /*!< Cortex-M Core */ #if defined ( __CC_ARM ) #define __ASM __asm /*!< asm keyword for ARM Compiler */ #define __INLINE __inline /*!< inline keyword for ARM Compiler */ #define __STATIC_INLINE static __inline #elif defined ( __GNUC__ ) #define __ASM __asm /*!< asm keyword for GNU Compiler */ #define __INLINE inline /*!< inline keyword for GNU Compiler */ #define __STATIC_INLINE static inline #elif defined ( __ICCARM__ ) #define __ASM __asm /*!< asm keyword for IAR Compiler */ #define __INLINE inline /*!< inline keyword for IAR Compiler. Only available in High optimization mode! */ #define __STATIC_INLINE static inline #elif defined ( __TMS470__ ) #define __ASM __asm /*!< asm keyword for TI CCS Compiler */ #define __STATIC_INLINE static inline #elif defined ( __TASKING__ ) #define __ASM __asm /*!< asm keyword for TASKING Compiler */ #define __INLINE inline /*!< inline keyword for TASKING Compiler */ #define __STATIC_INLINE static inline #elif defined ( __CSMC__ ) #define __packed #define __ASM _asm /*!< asm keyword for COSMIC Compiler */ #define __INLINE inline /*use -pc99 on compile line !< inline keyword for COSMIC Compiler */ #define __STATIC_INLINE static inline #endif /** __FPU_USED indicates whether an FPU is used or not. For this, __FPU_PRESENT has to be checked prior to making use of FPU specific registers and functions. */ #if defined ( __CC_ARM ) #if defined __TARGET_FPU_VFP #if (__FPU_PRESENT == 1) #define __FPU_USED 1 #else #warning "Compiler generates FPU instructions for a device without an FPU (check __FPU_PRESENT)" #define __FPU_USED 0 #endif #else #define __FPU_USED 0 #endif #elif defined ( __GNUC__ ) #if defined (__VFP_FP__) && !defined(__SOFTFP__) #if (__FPU_PRESENT == 1) #define __FPU_USED 1 #else #warning "Compiler generates FPU instructions for a device without an FPU (check __FPU_PRESENT)" #define __FPU_USED 0 #endif #else #define __FPU_USED 0 #endif #elif defined ( __ICCARM__ ) #if defined __ARMVFP__ #if (__FPU_PRESENT == 1) #define __FPU_USED 1 #else #warning "Compiler generates FPU instructions for a device without an FPU (check __FPU_PRESENT)" #define __FPU_USED 0 #endif #else #define __FPU_USED 0 #endif #elif defined ( __TMS470__ ) #if defined __TI_VFP_SUPPORT__ #if (__FPU_PRESENT == 1) #define __FPU_USED 1 #else #warning "Compiler generates FPU instructions for a device without an FPU (check __FPU_PRESENT)" #define __FPU_USED 0 #endif #else #define __FPU_USED 0 #endif #elif defined ( __TASKING__ ) #if defined __FPU_VFP__ #if (__FPU_PRESENT == 1) #define __FPU_USED 1 #else #error "Compiler generates FPU instructions for a device without an FPU (check __FPU_PRESENT)" #define __FPU_USED 0 #endif #else #define __FPU_USED 0 #endif #elif defined ( __CSMC__ ) /* Cosmic */ #if ( __CSMC__ & 0x400) // FPU present for parser #if (__FPU_PRESENT == 1) #define __FPU_USED 1 #else #error "Compiler generates FPU instructions for a device without an FPU (check __FPU_PRESENT)" #define __FPU_USED 0 #endif #else #define __FPU_USED 0 #endif #endif #include /* standard types definitions */ #include /* Core Instruction Access */ #include /* Core Function Access */ #include /* Compiler specific SIMD Intrinsics */ #ifdef __cplusplus } #endif #endif /* __CORE_CM7_H_GENERIC */ #ifndef __CMSIS_GENERIC #ifndef __CORE_CM7_H_DEPENDANT #define __CORE_CM7_H_DEPENDANT #ifdef __cplusplus extern "C" { #endif /* check device defines and use defaults */ #if defined __CHECK_DEVICE_DEFINES #ifndef __CM7_REV #define __CM7_REV 0x0000 #warning "__CM7_REV not defined in device header file; using default!" #endif #ifndef __FPU_PRESENT #define __FPU_PRESENT 0 #warning "__FPU_PRESENT not defined in device header file; using default!" #endif #ifndef __MPU_PRESENT #define __MPU_PRESENT 0 #warning "__MPU_PRESENT not defined in device header file; using default!" #endif #ifndef __ICACHE_PRESENT #define __ICACHE_PRESENT 0 #warning "__ICACHE_PRESENT not defined in device header file; using default!" #endif #ifndef __DCACHE_PRESENT #define __DCACHE_PRESENT 0 #warning "__DCACHE_PRESENT not defined in device header file; using default!" #endif #ifndef __DTCM_PRESENT #define __DTCM_PRESENT 0 #warning "__DTCM_PRESENT not defined in device header file; using default!" #endif #ifndef __NVIC_PRIO_BITS #define __NVIC_PRIO_BITS 3 #warning "__NVIC_PRIO_BITS not defined in device header file; using default!" #endif #ifndef __Vendor_SysTickConfig #define __Vendor_SysTickConfig 0 #warning "__Vendor_SysTickConfig not defined in device header file; using default!" #endif #endif /* IO definitions (access restrictions to peripheral registers) */ /** \defgroup CMSIS_glob_defs CMSIS Global Defines IO Type Qualifiers are used \li to specify the access to peripheral variables. \li for automatic generation of peripheral register debug information. */ #ifdef __cplusplus #define __I volatile /*!< Defines 'read only' permissions */ #else #define __I volatile const /*!< Defines 'read only' permissions */ #endif #define __O volatile /*!< Defines 'write only' permissions */ #define __IO volatile /*!< Defines 'read / write' permissions */ /*@} end of group Cortex_M7 */ /******************************************************************************* * Register Abstraction Core Register contain: - Core Register - Core NVIC Register - Core SCB Register - Core SysTick Register - Core Debug Register - Core MPU Register - Core FPU Register ******************************************************************************/ /** \defgroup CMSIS_core_register Defines and Type Definitions \brief Type definitions and defines for Cortex-M processor based devices. */ /** \ingroup CMSIS_core_register \defgroup CMSIS_CORE Status and Control Registers \brief Core Register type definitions. @{ */ /** \brief Union type to access the Application Program Status Register (APSR). */ typedef union { struct { uint32_t _reserved0:16; /*!< bit: 0..15 Reserved */ uint32_t GE:4; /*!< bit: 16..19 Greater than or Equal flags */ uint32_t _reserved1:7; /*!< bit: 20..26 Reserved */ uint32_t Q:1; /*!< bit: 27 Saturation condition flag */ uint32_t V:1; /*!< bit: 28 Overflow condition code flag */ uint32_t C:1; /*!< bit: 29 Carry condition code flag */ uint32_t Z:1; /*!< bit: 30 Zero condition code flag */ uint32_t N:1; /*!< bit: 31 Negative condition code flag */ } b; /*!< Structure used for bit access */ uint32_t w; /*!< Type used for word access */ } APSR_Type; /* APSR Register Definitions */ #define APSR_N_Pos 31 /*!< APSR: N Position */ #define APSR_N_Msk (1UL << APSR_N_Pos) /*!< APSR: N Mask */ #define APSR_Z_Pos 30 /*!< APSR: Z Position */ #define APSR_Z_Msk (1UL << APSR_Z_Pos) /*!< APSR: Z Mask */ #define APSR_C_Pos 29 /*!< APSR: C Position */ #define APSR_C_Msk (1UL << APSR_C_Pos) /*!< APSR: C Mask */ #define APSR_V_Pos 28 /*!< APSR: V Position */ #define APSR_V_Msk (1UL << APSR_V_Pos) /*!< APSR: V Mask */ #define APSR_Q_Pos 27 /*!< APSR: Q Position */ #define APSR_Q_Msk (1UL << APSR_Q_Pos) /*!< APSR: Q Mask */ #define APSR_GE_Pos 16 /*!< APSR: GE Position */ #define APSR_GE_Msk (0xFUL << APSR_GE_Pos) /*!< APSR: GE Mask */ /** \brief Union type to access the Interrupt Program Status Register (IPSR). */ typedef union { struct { uint32_t ISR:9; /*!< bit: 0.. 8 Exception number */ uint32_t _reserved0:23; /*!< bit: 9..31 Reserved */ } b; /*!< Structure used for bit access */ uint32_t w; /*!< Type used for word access */ } IPSR_Type; /* IPSR Register Definitions */ #define IPSR_ISR_Pos 0 /*!< IPSR: ISR Position */ #define IPSR_ISR_Msk (0x1FFUL /*<< IPSR_ISR_Pos*/) /*!< IPSR: ISR Mask */ /** \brief Union type to access the Special-Purpose Program Status Registers (xPSR). */ typedef union { struct { uint32_t ISR:9; /*!< bit: 0.. 8 Exception number */ uint32_t _reserved0:7; /*!< bit: 9..15 Reserved */ uint32_t GE:4; /*!< bit: 16..19 Greater than or Equal flags */ uint32_t _reserved1:4; /*!< bit: 20..23 Reserved */ uint32_t T:1; /*!< bit: 24 Thumb bit (read 0) */ uint32_t IT:2; /*!< bit: 25..26 saved IT state (read 0) */ uint32_t Q:1; /*!< bit: 27 Saturation condition flag */ uint32_t V:1; /*!< bit: 28 Overflow condition code flag */ uint32_t C:1; /*!< bit: 29 Carry condition code flag */ uint32_t Z:1; /*!< bit: 30 Zero condition code flag */ uint32_t N:1; /*!< bit: 31 Negative condition code flag */ } b; /*!< Structure used for bit access */ uint32_t w; /*!< Type used for word access */ } xPSR_Type; /* xPSR Register Definitions */ #define xPSR_N_Pos 31 /*!< xPSR: N Position */ #define xPSR_N_Msk (1UL << xPSR_N_Pos) /*!< xPSR: N Mask */ #define xPSR_Z_Pos 30 /*!< xPSR: Z Position */ #define xPSR_Z_Msk (1UL << xPSR_Z_Pos) /*!< xPSR: Z Mask */ #define xPSR_C_Pos 29 /*!< xPSR: C Position */ #define xPSR_C_Msk (1UL << xPSR_C_Pos) /*!< xPSR: C Mask */ #define xPSR_V_Pos 28 /*!< xPSR: V Position */ #define xPSR_V_Msk (1UL << xPSR_V_Pos) /*!< xPSR: V Mask */ #define xPSR_Q_Pos 27 /*!< xPSR: Q Position */ #define xPSR_Q_Msk (1UL << xPSR_Q_Pos) /*!< xPSR: Q Mask */ #define xPSR_IT_Pos 25 /*!< xPSR: IT Position */ #define xPSR_IT_Msk (3UL << xPSR_IT_Pos) /*!< xPSR: IT Mask */ #define xPSR_T_Pos 24 /*!< xPSR: T Position */ #define xPSR_T_Msk (1UL << xPSR_T_Pos) /*!< xPSR: T Mask */ #define xPSR_GE_Pos 16 /*!< xPSR: GE Position */ #define xPSR_GE_Msk (0xFUL << xPSR_GE_Pos) /*!< xPSR: GE Mask */ #define xPSR_ISR_Pos 0 /*!< xPSR: ISR Position */ #define xPSR_ISR_Msk (0x1FFUL /*<< xPSR_ISR_Pos*/) /*!< xPSR: ISR Mask */ /** \brief Union type to access the Control Registers (CONTROL). */ typedef union { struct { uint32_t nPRIV:1; /*!< bit: 0 Execution privilege in Thread mode */ uint32_t SPSEL:1; /*!< bit: 1 Stack to be used */ uint32_t FPCA:1; /*!< bit: 2 FP extension active flag */ uint32_t _reserved0:29; /*!< bit: 3..31 Reserved */ } b; /*!< Structure used for bit access */ uint32_t w; /*!< Type used for word access */ } CONTROL_Type; /* CONTROL Register Definitions */ #define CONTROL_FPCA_Pos 2 /*!< CONTROL: FPCA Position */ #define CONTROL_FPCA_Msk (1UL << CONTROL_FPCA_Pos) /*!< CONTROL: FPCA Mask */ #define CONTROL_SPSEL_Pos 1 /*!< CONTROL: SPSEL Position */ #define CONTROL_SPSEL_Msk (1UL << CONTROL_SPSEL_Pos) /*!< CONTROL: SPSEL Mask */ #define CONTROL_nPRIV_Pos 0 /*!< CONTROL: nPRIV Position */ #define CONTROL_nPRIV_Msk (1UL /*<< CONTROL_nPRIV_Pos*/) /*!< CONTROL: nPRIV Mask */ /*@} end of group CMSIS_CORE */ /** \ingroup CMSIS_core_register \defgroup CMSIS_NVIC Nested Vectored Interrupt Controller (NVIC) \brief Type definitions for the NVIC Registers @{ */ /** \brief Structure type to access the Nested Vectored Interrupt Controller (NVIC). */ typedef struct { __IO uint32_t ISER[8]; /*!< Offset: 0x000 (R/W) Interrupt Set Enable Register */ uint32_t RESERVED0[24]; __IO uint32_t ICER[8]; /*!< Offset: 0x080 (R/W) Interrupt Clear Enable Register */ uint32_t RSERVED1[24]; __IO uint32_t ISPR[8]; /*!< Offset: 0x100 (R/W) Interrupt Set Pending Register */ uint32_t RESERVED2[24]; __IO uint32_t ICPR[8]; /*!< Offset: 0x180 (R/W) Interrupt Clear Pending Register */ uint32_t RESERVED3[24]; __IO uint32_t IABR[8]; /*!< Offset: 0x200 (R/W) Interrupt Active bit Register */ uint32_t RESERVED4[56]; __IO uint8_t IP[240]; /*!< Offset: 0x300 (R/W) Interrupt Priority Register (8Bit wide) */ uint32_t RESERVED5[644]; __O uint32_t STIR; /*!< Offset: 0xE00 ( /W) Software Trigger Interrupt Register */ } NVIC_Type; /* Software Triggered Interrupt Register Definitions */ #define NVIC_STIR_INTID_Pos 0 /*!< STIR: INTLINESNUM Position */ #define NVIC_STIR_INTID_Msk (0x1FFUL /*<< NVIC_STIR_INTID_Pos*/) /*!< STIR: INTLINESNUM Mask */ /*@} end of group CMSIS_NVIC */ /** \ingroup CMSIS_core_register \defgroup CMSIS_SCB System Control Block (SCB) \brief Type definitions for the System Control Block Registers @{ */ /** \brief Structure type to access the System Control Block (SCB). */ typedef struct { __I uint32_t CPUID; /*!< Offset: 0x000 (R/ ) CPUID Base Register */ __IO uint32_t ICSR; /*!< Offset: 0x004 (R/W) Interrupt Control and State Register */ __IO uint32_t VTOR; /*!< Offset: 0x008 (R/W) Vector Table Offset Register */ __IO uint32_t AIRCR; /*!< Offset: 0x00C (R/W) Application Interrupt and Reset Control Register */ __IO uint32_t SCR; /*!< Offset: 0x010 (R/W) System Control Register */ __IO uint32_t CCR; /*!< Offset: 0x014 (R/W) Configuration Control Register */ __IO uint8_t SHPR[12]; /*!< Offset: 0x018 (R/W) System Handlers Priority Registers (4-7, 8-11, 12-15) */ __IO uint32_t SHCSR; /*!< Offset: 0x024 (R/W) System Handler Control and State Register */ __IO uint32_t CFSR; /*!< Offset: 0x028 (R/W) Configurable Fault Status Register */ __IO uint32_t HFSR; /*!< Offset: 0x02C (R/W) HardFault Status Register */ __IO uint32_t DFSR; /*!< Offset: 0x030 (R/W) Debug Fault Status Register */ __IO uint32_t MMFAR; /*!< Offset: 0x034 (R/W) MemManage Fault Address Register */ __IO uint32_t BFAR; /*!< Offset: 0x038 (R/W) BusFault Address Register */ __IO uint32_t AFSR; /*!< Offset: 0x03C (R/W) Auxiliary Fault Status Register */ __I uint32_t ID_PFR[2]; /*!< Offset: 0x040 (R/ ) Processor Feature Register */ __I uint32_t ID_DFR; /*!< Offset: 0x048 (R/ ) Debug Feature Register */ __I uint32_t ID_AFR; /*!< Offset: 0x04C (R/ ) Auxiliary Feature Register */ __I uint32_t ID_MFR[4]; /*!< Offset: 0x050 (R/ ) Memory Model Feature Register */ __I uint32_t ID_ISAR[5]; /*!< Offset: 0x060 (R/ ) Instruction Set Attributes Register */ uint32_t RESERVED0[1]; __I uint32_t CLIDR; /*!< Offset: 0x078 (R/ ) Cache Level ID register */ __I uint32_t CTR; /*!< Offset: 0x07C (R/ ) Cache Type register */ __I uint32_t CCSIDR; /*!< Offset: 0x080 (R/ ) Cache Size ID Register */ __IO uint32_t CSSELR; /*!< Offset: 0x084 (R/W) Cache Size Selection Register */ __IO uint32_t CPACR; /*!< Offset: 0x088 (R/W) Coprocessor Access Control Register */ uint32_t RESERVED3[93]; __O uint32_t STIR; /*!< Offset: 0x200 ( /W) Software Triggered Interrupt Register */ uint32_t RESERVED4[15]; __I uint32_t MVFR0; /*!< Offset: 0x240 (R/ ) Media and VFP Feature Register 0 */ __I uint32_t MVFR1; /*!< Offset: 0x244 (R/ ) Media and VFP Feature Register 1 */ __I uint32_t MVFR2; /*!< Offset: 0x248 (R/ ) Media and VFP Feature Register 1 */ uint32_t RESERVED5[1]; __O uint32_t ICIALLU; /*!< Offset: 0x250 ( /W) I-Cache Invalidate All to PoU */ uint32_t RESERVED6[1]; __O uint32_t ICIMVAU; /*!< Offset: 0x258 ( /W) I-Cache Invalidate by MVA to PoU */ __O uint32_t DCIMVAC; /*!< Offset: 0x25C ( /W) D-Cache Invalidate by MVA to PoC */ __O uint32_t DCISW; /*!< Offset: 0x260 ( /W) D-Cache Invalidate by Set-way */ __O uint32_t DCCMVAU; /*!< Offset: 0x264 ( /W) D-Cache Clean by MVA to PoU */ __O uint32_t DCCMVAC; /*!< Offset: 0x268 ( /W) D-Cache Clean by MVA to PoC */ __O uint32_t DCCSW; /*!< Offset: 0x26C ( /W) D-Cache Clean by Set-way */ __O uint32_t DCCIMVAC; /*!< Offset: 0x270 ( /W) D-Cache Clean and Invalidate by MVA to PoC */ __O uint32_t DCCISW; /*!< Offset: 0x274 ( /W) D-Cache Clean and Invalidate by Set-way */ uint32_t RESERVED7[6]; __IO uint32_t ITCMCR; /*!< Offset: 0x290 (R/W) Instruction Tightly-Coupled Memory Control Register */ __IO uint32_t DTCMCR; /*!< Offset: 0x294 (R/W) Data Tightly-Coupled Memory Control Registers */ __IO uint32_t AHBPCR; /*!< Offset: 0x298 (R/W) AHBP Control Register */ __IO uint32_t CACR; /*!< Offset: 0x29C (R/W) L1 Cache Control Register */ __IO uint32_t AHBSCR; /*!< Offset: 0x2A0 (R/W) AHB Slave Control Register */ uint32_t RESERVED8[1]; __IO uint32_t ABFSR; /*!< Offset: 0x2A8 (R/W) Auxiliary Bus Fault Status Register */ } SCB_Type; /* SCB CPUID Register Definitions */ #define SCB_CPUID_IMPLEMENTER_Pos 24 /*!< SCB CPUID: IMPLEMENTER Position */ #define SCB_CPUID_IMPLEMENTER_Msk (0xFFUL << SCB_CPUID_IMPLEMENTER_Pos) /*!< SCB CPUID: IMPLEMENTER Mask */ #define SCB_CPUID_VARIANT_Pos 20 /*!< SCB CPUID: VARIANT Position */ #define SCB_CPUID_VARIANT_Msk (0xFUL << SCB_CPUID_VARIANT_Pos) /*!< SCB CPUID: VARIANT Mask */ #define SCB_CPUID_ARCHITECTURE_Pos 16 /*!< SCB CPUID: ARCHITECTURE Position */ #define SCB_CPUID_ARCHITECTURE_Msk (0xFUL << SCB_CPUID_ARCHITECTURE_Pos) /*!< SCB CPUID: ARCHITECTURE Mask */ #define SCB_CPUID_PARTNO_Pos 4 /*!< SCB CPUID: PARTNO Position */ #define SCB_CPUID_PARTNO_Msk (0xFFFUL << SCB_CPUID_PARTNO_Pos) /*!< SCB CPUID: PARTNO Mask */ #define SCB_CPUID_REVISION_Pos 0 /*!< SCB CPUID: REVISION Position */ #define SCB_CPUID_REVISION_Msk (0xFUL /*<< SCB_CPUID_REVISION_Pos*/) /*!< SCB CPUID: REVISION Mask */ /* SCB Interrupt Control State Register Definitions */ #define SCB_ICSR_NMIPENDSET_Pos 31 /*!< SCB ICSR: NMIPENDSET Position */ #define SCB_ICSR_NMIPENDSET_Msk (1UL << SCB_ICSR_NMIPENDSET_Pos) /*!< SCB ICSR: NMIPENDSET Mask */ #define SCB_ICSR_PENDSVSET_Pos 28 /*!< SCB ICSR: PENDSVSET Position */ #define SCB_ICSR_PENDSVSET_Msk (1UL << SCB_ICSR_PENDSVSET_Pos) /*!< SCB ICSR: PENDSVSET Mask */ #define SCB_ICSR_PENDSVCLR_Pos 27 /*!< SCB ICSR: PENDSVCLR Position */ #define SCB_ICSR_PENDSVCLR_Msk (1UL << SCB_ICSR_PENDSVCLR_Pos) /*!< SCB ICSR: PENDSVCLR Mask */ #define SCB_ICSR_PENDSTSET_Pos 26 /*!< SCB ICSR: PENDSTSET Position */ #define SCB_ICSR_PENDSTSET_Msk (1UL << SCB_ICSR_PENDSTSET_Pos) /*!< SCB ICSR: PENDSTSET Mask */ #define SCB_ICSR_PENDSTCLR_Pos 25 /*!< SCB ICSR: PENDSTCLR Position */ #define SCB_ICSR_PENDSTCLR_Msk (1UL << SCB_ICSR_PENDSTCLR_Pos) /*!< SCB ICSR: PENDSTCLR Mask */ #define SCB_ICSR_ISRPREEMPT_Pos 23 /*!< SCB ICSR: ISRPREEMPT Position */ #define SCB_ICSR_ISRPREEMPT_Msk (1UL << SCB_ICSR_ISRPREEMPT_Pos) /*!< SCB ICSR: ISRPREEMPT Mask */ #define SCB_ICSR_ISRPENDING_Pos 22 /*!< SCB ICSR: ISRPENDING Position */ #define SCB_ICSR_ISRPENDING_Msk (1UL << SCB_ICSR_ISRPENDING_Pos) /*!< SCB ICSR: ISRPENDING Mask */ #define SCB_ICSR_VECTPENDING_Pos 12 /*!< SCB ICSR: VECTPENDING Position */ #define SCB_ICSR_VECTPENDING_Msk (0x1FFUL << SCB_ICSR_VECTPENDING_Pos) /*!< SCB ICSR: VECTPENDING Mask */ #define SCB_ICSR_RETTOBASE_Pos 11 /*!< SCB ICSR: RETTOBASE Position */ #define SCB_ICSR_RETTOBASE_Msk (1UL << SCB_ICSR_RETTOBASE_Pos) /*!< SCB ICSR: RETTOBASE Mask */ #define SCB_ICSR_VECTACTIVE_Pos 0 /*!< SCB ICSR: VECTACTIVE Position */ #define SCB_ICSR_VECTACTIVE_Msk (0x1FFUL /*<< SCB_ICSR_VECTACTIVE_Pos*/) /*!< SCB ICSR: VECTACTIVE Mask */ /* SCB Vector Table Offset Register Definitions */ #define SCB_VTOR_TBLOFF_Pos 7 /*!< SCB VTOR: TBLOFF Position */ #define SCB_VTOR_TBLOFF_Msk (0x1FFFFFFUL << SCB_VTOR_TBLOFF_Pos) /*!< SCB VTOR: TBLOFF Mask */ /* SCB Application Interrupt and Reset Control Register Definitions */ #define SCB_AIRCR_VECTKEY_Pos 16 /*!< SCB AIRCR: VECTKEY Position */ #define SCB_AIRCR_VECTKEY_Msk (0xFFFFUL << SCB_AIRCR_VECTKEY_Pos) /*!< SCB AIRCR: VECTKEY Mask */ #define SCB_AIRCR_VECTKEYSTAT_Pos 16 /*!< SCB AIRCR: VECTKEYSTAT Position */ #define SCB_AIRCR_VECTKEYSTAT_Msk (0xFFFFUL << SCB_AIRCR_VECTKEYSTAT_Pos) /*!< SCB AIRCR: VECTKEYSTAT Mask */ #define SCB_AIRCR_ENDIANESS_Pos 15 /*!< SCB AIRCR: ENDIANESS Position */ #define SCB_AIRCR_ENDIANESS_Msk (1UL << SCB_AIRCR_ENDIANESS_Pos) /*!< SCB AIRCR: ENDIANESS Mask */ #define SCB_AIRCR_PRIGROUP_Pos 8 /*!< SCB AIRCR: PRIGROUP Position */ #define SCB_AIRCR_PRIGROUP_Msk (7UL << SCB_AIRCR_PRIGROUP_Pos) /*!< SCB AIRCR: PRIGROUP Mask */ #define SCB_AIRCR_SYSRESETREQ_Pos 2 /*!< SCB AIRCR: SYSRESETREQ Position */ #define SCB_AIRCR_SYSRESETREQ_Msk (1UL << SCB_AIRCR_SYSRESETREQ_Pos) /*!< SCB AIRCR: SYSRESETREQ Mask */ #define SCB_AIRCR_VECTCLRACTIVE_Pos 1 /*!< SCB AIRCR: VECTCLRACTIVE Position */ #define SCB_AIRCR_VECTCLRACTIVE_Msk (1UL << SCB_AIRCR_VECTCLRACTIVE_Pos) /*!< SCB AIRCR: VECTCLRACTIVE Mask */ #define SCB_AIRCR_VECTRESET_Pos 0 /*!< SCB AIRCR: VECTRESET Position */ #define SCB_AIRCR_VECTRESET_Msk (1UL /*<< SCB_AIRCR_VECTRESET_Pos*/) /*!< SCB AIRCR: VECTRESET Mask */ /* SCB System Control Register Definitions */ #define SCB_SCR_SEVONPEND_Pos 4 /*!< SCB SCR: SEVONPEND Position */ #define SCB_SCR_SEVONPEND_Msk (1UL << SCB_SCR_SEVONPEND_Pos) /*!< SCB SCR: SEVONPEND Mask */ #define SCB_SCR_SLEEPDEEP_Pos 2 /*!< SCB SCR: SLEEPDEEP Position */ #define SCB_SCR_SLEEPDEEP_Msk (1UL << SCB_SCR_SLEEPDEEP_Pos) /*!< SCB SCR: SLEEPDEEP Mask */ #define SCB_SCR_SLEEPONEXIT_Pos 1 /*!< SCB SCR: SLEEPONEXIT Position */ #define SCB_SCR_SLEEPONEXIT_Msk (1UL << SCB_SCR_SLEEPONEXIT_Pos) /*!< SCB SCR: SLEEPONEXIT Mask */ /* SCB Configuration Control Register Definitions */ #define SCB_CCR_BP_Pos 18 /*!< SCB CCR: Branch prediction enable bit Position */ #define SCB_CCR_BP_Msk (1UL << SCB_CCR_BP_Pos) /*!< SCB CCR: Branch prediction enable bit Mask */ #define SCB_CCR_IC_Pos 17 /*!< SCB CCR: Instruction cache enable bit Position */ #define SCB_CCR_IC_Msk (1UL << SCB_CCR_IC_Pos) /*!< SCB CCR: Instruction cache enable bit Mask */ #define SCB_CCR_DC_Pos 16 /*!< SCB CCR: Cache enable bit Position */ #define SCB_CCR_DC_Msk (1UL << SCB_CCR_DC_Pos) /*!< SCB CCR: Cache enable bit Mask */ #define SCB_CCR_STKALIGN_Pos 9 /*!< SCB CCR: STKALIGN Position */ #define SCB_CCR_STKALIGN_Msk (1UL << SCB_CCR_STKALIGN_Pos) /*!< SCB CCR: STKALIGN Mask */ #define SCB_CCR_BFHFNMIGN_Pos 8 /*!< SCB CCR: BFHFNMIGN Position */ #define SCB_CCR_BFHFNMIGN_Msk (1UL << SCB_CCR_BFHFNMIGN_Pos) /*!< SCB CCR: BFHFNMIGN Mask */ #define SCB_CCR_DIV_0_TRP_Pos 4 /*!< SCB CCR: DIV_0_TRP Position */ #define SCB_CCR_DIV_0_TRP_Msk (1UL << SCB_CCR_DIV_0_TRP_Pos) /*!< SCB CCR: DIV_0_TRP Mask */ #define SCB_CCR_UNALIGN_TRP_Pos 3 /*!< SCB CCR: UNALIGN_TRP Position */ #define SCB_CCR_UNALIGN_TRP_Msk (1UL << SCB_CCR_UNALIGN_TRP_Pos) /*!< SCB CCR: UNALIGN_TRP Mask */ #define SCB_CCR_USERSETMPEND_Pos 1 /*!< SCB CCR: USERSETMPEND Position */ #define SCB_CCR_USERSETMPEND_Msk (1UL << SCB_CCR_USERSETMPEND_Pos) /*!< SCB CCR: USERSETMPEND Mask */ #define SCB_CCR_NONBASETHRDENA_Pos 0 /*!< SCB CCR: NONBASETHRDENA Position */ #define SCB_CCR_NONBASETHRDENA_Msk (1UL /*<< SCB_CCR_NONBASETHRDENA_Pos*/) /*!< SCB CCR: NONBASETHRDENA Mask */ /* SCB System Handler Control and State Register Definitions */ #define SCB_SHCSR_USGFAULTENA_Pos 18 /*!< SCB SHCSR: USGFAULTENA Position */ #define SCB_SHCSR_USGFAULTENA_Msk (1UL << SCB_SHCSR_USGFAULTENA_Pos) /*!< SCB SHCSR: USGFAULTENA Mask */ #define SCB_SHCSR_BUSFAULTENA_Pos 17 /*!< SCB SHCSR: BUSFAULTENA Position */ #define SCB_SHCSR_BUSFAULTENA_Msk (1UL << SCB_SHCSR_BUSFAULTENA_Pos) /*!< SCB SHCSR: BUSFAULTENA Mask */ #define SCB_SHCSR_MEMFAULTENA_Pos 16 /*!< SCB SHCSR: MEMFAULTENA Position */ #define SCB_SHCSR_MEMFAULTENA_Msk (1UL << SCB_SHCSR_MEMFAULTENA_Pos) /*!< SCB SHCSR: MEMFAULTENA Mask */ #define SCB_SHCSR_SVCALLPENDED_Pos 15 /*!< SCB SHCSR: SVCALLPENDED Position */ #define SCB_SHCSR_SVCALLPENDED_Msk (1UL << SCB_SHCSR_SVCALLPENDED_Pos) /*!< SCB SHCSR: SVCALLPENDED Mask */ #define SCB_SHCSR_BUSFAULTPENDED_Pos 14 /*!< SCB SHCSR: BUSFAULTPENDED Position */ #define SCB_SHCSR_BUSFAULTPENDED_Msk (1UL << SCB_SHCSR_BUSFAULTPENDED_Pos) /*!< SCB SHCSR: BUSFAULTPENDED Mask */ #define SCB_SHCSR_MEMFAULTPENDED_Pos 13 /*!< SCB SHCSR: MEMFAULTPENDED Position */ #define SCB_SHCSR_MEMFAULTPENDED_Msk (1UL << SCB_SHCSR_MEMFAULTPENDED_Pos) /*!< SCB SHCSR: MEMFAULTPENDED Mask */ #define SCB_SHCSR_USGFAULTPENDED_Pos 12 /*!< SCB SHCSR: USGFAULTPENDED Position */ #define SCB_SHCSR_USGFAULTPENDED_Msk (1UL << SCB_SHCSR_USGFAULTPENDED_Pos) /*!< SCB SHCSR: USGFAULTPENDED Mask */ #define SCB_SHCSR_SYSTICKACT_Pos 11 /*!< SCB SHCSR: SYSTICKACT Position */ #define SCB_SHCSR_SYSTICKACT_Msk (1UL << SCB_SHCSR_SYSTICKACT_Pos) /*!< SCB SHCSR: SYSTICKACT Mask */ #define SCB_SHCSR_PENDSVACT_Pos 10 /*!< SCB SHCSR: PENDSVACT Position */ #define SCB_SHCSR_PENDSVACT_Msk (1UL << SCB_SHCSR_PENDSVACT_Pos) /*!< SCB SHCSR: PENDSVACT Mask */ #define SCB_SHCSR_MONITORACT_Pos 8 /*!< SCB SHCSR: MONITORACT Position */ #define SCB_SHCSR_MONITORACT_Msk (1UL << SCB_SHCSR_MONITORACT_Pos) /*!< SCB SHCSR: MONITORACT Mask */ #define SCB_SHCSR_SVCALLACT_Pos 7 /*!< SCB SHCSR: SVCALLACT Position */ #define SCB_SHCSR_SVCALLACT_Msk (1UL << SCB_SHCSR_SVCALLACT_Pos) /*!< SCB SHCSR: SVCALLACT Mask */ #define SCB_SHCSR_USGFAULTACT_Pos 3 /*!< SCB SHCSR: USGFAULTACT Position */ #define SCB_SHCSR_USGFAULTACT_Msk (1UL << SCB_SHCSR_USGFAULTACT_Pos) /*!< SCB SHCSR: USGFAULTACT Mask */ #define SCB_SHCSR_BUSFAULTACT_Pos 1 /*!< SCB SHCSR: BUSFAULTACT Position */ #define SCB_SHCSR_BUSFAULTACT_Msk (1UL << SCB_SHCSR_BUSFAULTACT_Pos) /*!< SCB SHCSR: BUSFAULTACT Mask */ #define SCB_SHCSR_MEMFAULTACT_Pos 0 /*!< SCB SHCSR: MEMFAULTACT Position */ #define SCB_SHCSR_MEMFAULTACT_Msk (1UL /*<< SCB_SHCSR_MEMFAULTACT_Pos*/) /*!< SCB SHCSR: MEMFAULTACT Mask */ /* SCB Configurable Fault Status Registers Definitions */ #define SCB_CFSR_USGFAULTSR_Pos 16 /*!< SCB CFSR: Usage Fault Status Register Position */ #define SCB_CFSR_USGFAULTSR_Msk (0xFFFFUL << SCB_CFSR_USGFAULTSR_Pos) /*!< SCB CFSR: Usage Fault Status Register Mask */ #define SCB_CFSR_BUSFAULTSR_Pos 8 /*!< SCB CFSR: Bus Fault Status Register Position */ #define SCB_CFSR_BUSFAULTSR_Msk (0xFFUL << SCB_CFSR_BUSFAULTSR_Pos) /*!< SCB CFSR: Bus Fault Status Register Mask */ #define SCB_CFSR_MEMFAULTSR_Pos 0 /*!< SCB CFSR: Memory Manage Fault Status Register Position */ #define SCB_CFSR_MEMFAULTSR_Msk (0xFFUL /*<< SCB_CFSR_MEMFAULTSR_Pos*/) /*!< SCB CFSR: Memory Manage Fault Status Register Mask */ /* SCB Hard Fault Status Registers Definitions */ #define SCB_HFSR_DEBUGEVT_Pos 31 /*!< SCB HFSR: DEBUGEVT Position */ #define SCB_HFSR_DEBUGEVT_Msk (1UL << SCB_HFSR_DEBUGEVT_Pos) /*!< SCB HFSR: DEBUGEVT Mask */ #define SCB_HFSR_FORCED_Pos 30 /*!< SCB HFSR: FORCED Position */ #define SCB_HFSR_FORCED_Msk (1UL << SCB_HFSR_FORCED_Pos) /*!< SCB HFSR: FORCED Mask */ #define SCB_HFSR_VECTTBL_Pos 1 /*!< SCB HFSR: VECTTBL Position */ #define SCB_HFSR_VECTTBL_Msk (1UL << SCB_HFSR_VECTTBL_Pos) /*!< SCB HFSR: VECTTBL Mask */ /* SCB Debug Fault Status Register Definitions */ #define SCB_DFSR_EXTERNAL_Pos 4 /*!< SCB DFSR: EXTERNAL Position */ #define SCB_DFSR_EXTERNAL_Msk (1UL << SCB_DFSR_EXTERNAL_Pos) /*!< SCB DFSR: EXTERNAL Mask */ #define SCB_DFSR_VCATCH_Pos 3 /*!< SCB DFSR: VCATCH Position */ #define SCB_DFSR_VCATCH_Msk (1UL << SCB_DFSR_VCATCH_Pos) /*!< SCB DFSR: VCATCH Mask */ #define SCB_DFSR_DWTTRAP_Pos 2 /*!< SCB DFSR: DWTTRAP Position */ #define SCB_DFSR_DWTTRAP_Msk (1UL << SCB_DFSR_DWTTRAP_Pos) /*!< SCB DFSR: DWTTRAP Mask */ #define SCB_DFSR_BKPT_Pos 1 /*!< SCB DFSR: BKPT Position */ #define SCB_DFSR_BKPT_Msk (1UL << SCB_DFSR_BKPT_Pos) /*!< SCB DFSR: BKPT Mask */ #define SCB_DFSR_HALTED_Pos 0 /*!< SCB DFSR: HALTED Position */ #define SCB_DFSR_HALTED_Msk (1UL /*<< SCB_DFSR_HALTED_Pos*/) /*!< SCB DFSR: HALTED Mask */ /* Cache Level ID register */ #define SCB_CLIDR_LOUU_Pos 27 /*!< SCB CLIDR: LoUU Position */ #define SCB_CLIDR_LOUU_Msk (7UL << SCB_CLIDR_LOUU_Pos) /*!< SCB CLIDR: LoUU Mask */ #define SCB_CLIDR_LOC_Pos 24 /*!< SCB CLIDR: LoC Position */ #define SCB_CLIDR_LOC_Msk (7UL << SCB_CLIDR_FORMAT_Pos) /*!< SCB CLIDR: LoC Mask */ /* Cache Type register */ #define SCB_CTR_FORMAT_Pos 29 /*!< SCB CTR: Format Position */ #define SCB_CTR_FORMAT_Msk (7UL << SCB_CTR_FORMAT_Pos) /*!< SCB CTR: Format Mask */ #define SCB_CTR_CWG_Pos 24 /*!< SCB CTR: CWG Position */ #define SCB_CTR_CWG_Msk (0xFUL << SCB_CTR_CWG_Pos) /*!< SCB CTR: CWG Mask */ #define SCB_CTR_ERG_Pos 20 /*!< SCB CTR: ERG Position */ #define SCB_CTR_ERG_Msk (0xFUL << SCB_CTR_ERG_Pos) /*!< SCB CTR: ERG Mask */ #define SCB_CTR_DMINLINE_Pos 16 /*!< SCB CTR: DminLine Position */ #define SCB_CTR_DMINLINE_Msk (0xFUL << SCB_CTR_DMINLINE_Pos) /*!< SCB CTR: DminLine Mask */ #define SCB_CTR_IMINLINE_Pos 0 /*!< SCB CTR: ImInLine Position */ #define SCB_CTR_IMINLINE_Msk (0xFUL /*<< SCB_CTR_IMINLINE_Pos*/) /*!< SCB CTR: ImInLine Mask */ /* Cache Size ID Register */ #define SCB_CCSIDR_WT_Pos 31 /*!< SCB CCSIDR: WT Position */ #define SCB_CCSIDR_WT_Msk (7UL << SCB_CCSIDR_WT_Pos) /*!< SCB CCSIDR: WT Mask */ #define SCB_CCSIDR_WB_Pos 30 /*!< SCB CCSIDR: WB Position */ #define SCB_CCSIDR_WB_Msk (7UL << SCB_CCSIDR_WB_Pos) /*!< SCB CCSIDR: WB Mask */ #define SCB_CCSIDR_RA_Pos 29 /*!< SCB CCSIDR: RA Position */ #define SCB_CCSIDR_RA_Msk (7UL << SCB_CCSIDR_RA_Pos) /*!< SCB CCSIDR: RA Mask */ #define SCB_CCSIDR_WA_Pos 28 /*!< SCB CCSIDR: WA Position */ #define SCB_CCSIDR_WA_Msk (7UL << SCB_CCSIDR_WA_Pos) /*!< SCB CCSIDR: WA Mask */ #define SCB_CCSIDR_NUMSETS_Pos 13 /*!< SCB CCSIDR: NumSets Position */ #define SCB_CCSIDR_NUMSETS_Msk (0x7FFFUL << SCB_CCSIDR_NUMSETS_Pos) /*!< SCB CCSIDR: NumSets Mask */ #define SCB_CCSIDR_ASSOCIATIVITY_Pos 3 /*!< SCB CCSIDR: Associativity Position */ #define SCB_CCSIDR_ASSOCIATIVITY_Msk (0x3FFUL << SCB_CCSIDR_ASSOCIATIVITY_Pos) /*!< SCB CCSIDR: Associativity Mask */ #define SCB_CCSIDR_LINESIZE_Pos 0 /*!< SCB CCSIDR: LineSize Position */ #define SCB_CCSIDR_LINESIZE_Msk (7UL /*<< SCB_CCSIDR_LINESIZE_Pos*/) /*!< SCB CCSIDR: LineSize Mask */ /* Cache Size Selection Register */ #define SCB_CSSELR_LEVEL_Pos 1 /*!< SCB CSSELR: Level Position */ #define SCB_CSSELR_LEVEL_Msk (7UL << SCB_CSSELR_LEVEL_Pos) /*!< SCB CSSELR: Level Mask */ #define SCB_CSSELR_IND_Pos 0 /*!< SCB CSSELR: InD Position */ #define SCB_CSSELR_IND_Msk (1UL /*<< SCB_CSSELR_IND_Pos*/) /*!< SCB CSSELR: InD Mask */ /* SCB Software Triggered Interrupt Register */ #define SCB_STIR_INTID_Pos 0 /*!< SCB STIR: INTID Position */ #define SCB_STIR_INTID_Msk (0x1FFUL /*<< SCB_STIR_INTID_Pos*/) /*!< SCB STIR: INTID Mask */ /* Instruction Tightly-Coupled Memory Control Register*/ #define SCB_ITCMCR_SZ_Pos 3 /*!< SCB ITCMCR: SZ Position */ #define SCB_ITCMCR_SZ_Msk (0xFUL << SCB_ITCMCR_SZ_Pos) /*!< SCB ITCMCR: SZ Mask */ #define SCB_ITCMCR_RETEN_Pos 2 /*!< SCB ITCMCR: RETEN Position */ #define SCB_ITCMCR_RETEN_Msk (1UL << SCB_ITCMCR_RETEN_Pos) /*!< SCB ITCMCR: RETEN Mask */ #define SCB_ITCMCR_RMW_Pos 1 /*!< SCB ITCMCR: RMW Position */ #define SCB_ITCMCR_RMW_Msk (1UL << SCB_ITCMCR_RMW_Pos) /*!< SCB ITCMCR: RMW Mask */ #define SCB_ITCMCR_EN_Pos 0 /*!< SCB ITCMCR: EN Position */ #define SCB_ITCMCR_EN_Msk (1UL /*<< SCB_ITCMCR_EN_Pos*/) /*!< SCB ITCMCR: EN Mask */ /* Data Tightly-Coupled Memory Control Registers */ #define SCB_DTCMCR_SZ_Pos 3 /*!< SCB DTCMCR: SZ Position */ #define SCB_DTCMCR_SZ_Msk (0xFUL << SCB_DTCMCR_SZ_Pos) /*!< SCB DTCMCR: SZ Mask */ #define SCB_DTCMCR_RETEN_Pos 2 /*!< SCB DTCMCR: RETEN Position */ #define SCB_DTCMCR_RETEN_Msk (1UL << SCB_DTCMCR_RETEN_Pos) /*!< SCB DTCMCR: RETEN Mask */ #define SCB_DTCMCR_RMW_Pos 1 /*!< SCB DTCMCR: RMW Position */ #define SCB_DTCMCR_RMW_Msk (1UL << SCB_DTCMCR_RMW_Pos) /*!< SCB DTCMCR: RMW Mask */ #define SCB_DTCMCR_EN_Pos 0 /*!< SCB DTCMCR: EN Position */ #define SCB_DTCMCR_EN_Msk (1UL /*<< SCB_DTCMCR_EN_Pos*/) /*!< SCB DTCMCR: EN Mask */ /* AHBP Control Register */ #define SCB_AHBPCR_SZ_Pos 1 /*!< SCB AHBPCR: SZ Position */ #define SCB_AHBPCR_SZ_Msk (7UL << SCB_AHBPCR_SZ_Pos) /*!< SCB AHBPCR: SZ Mask */ #define SCB_AHBPCR_EN_Pos 0 /*!< SCB AHBPCR: EN Position */ #define SCB_AHBPCR_EN_Msk (1UL /*<< SCB_AHBPCR_EN_Pos*/) /*!< SCB AHBPCR: EN Mask */ /* L1 Cache Control Register */ #define SCB_CACR_FORCEWT_Pos 2 /*!< SCB CACR: FORCEWT Position */ #define SCB_CACR_FORCEWT_Msk (1UL << SCB_CACR_FORCEWT_Pos) /*!< SCB CACR: FORCEWT Mask */ #define SCB_CACR_ECCEN_Pos 1 /*!< SCB CACR: ECCEN Position */ #define SCB_CACR_ECCEN_Msk (1UL << SCB_CACR_ECCEN_Pos) /*!< SCB CACR: ECCEN Mask */ #define SCB_CACR_SIWT_Pos 0 /*!< SCB CACR: SIWT Position */ #define SCB_CACR_SIWT_Msk (1UL /*<< SCB_CACR_SIWT_Pos*/) /*!< SCB CACR: SIWT Mask */ /* AHBS control register */ #define SCB_AHBSCR_INITCOUNT_Pos 11 /*!< SCB AHBSCR: INITCOUNT Position */ #define SCB_AHBSCR_INITCOUNT_Msk (0x1FUL << SCB_AHBPCR_INITCOUNT_Pos) /*!< SCB AHBSCR: INITCOUNT Mask */ #define SCB_AHBSCR_TPRI_Pos 2 /*!< SCB AHBSCR: TPRI Position */ #define SCB_AHBSCR_TPRI_Msk (0x1FFUL << SCB_AHBPCR_TPRI_Pos) /*!< SCB AHBSCR: TPRI Mask */ #define SCB_AHBSCR_CTL_Pos 0 /*!< SCB AHBSCR: CTL Position*/ #define SCB_AHBSCR_CTL_Msk (3UL /*<< SCB_AHBPCR_CTL_Pos*/) /*!< SCB AHBSCR: CTL Mask */ /* Auxiliary Bus Fault Status Register */ #define SCB_ABFSR_AXIMTYPE_Pos 8 /*!< SCB ABFSR: AXIMTYPE Position*/ #define SCB_ABFSR_AXIMTYPE_Msk (3UL << SCB_ABFSR_AXIMTYPE_Pos) /*!< SCB ABFSR: AXIMTYPE Mask */ #define SCB_ABFSR_EPPB_Pos 4 /*!< SCB ABFSR: EPPB Position*/ #define SCB_ABFSR_EPPB_Msk (1UL << SCB_ABFSR_EPPB_Pos) /*!< SCB ABFSR: EPPB Mask */ #define SCB_ABFSR_AXIM_Pos 3 /*!< SCB ABFSR: AXIM Position*/ #define SCB_ABFSR_AXIM_Msk (1UL << SCB_ABFSR_AXIM_Pos) /*!< SCB ABFSR: AXIM Mask */ #define SCB_ABFSR_AHBP_Pos 2 /*!< SCB ABFSR: AHBP Position*/ #define SCB_ABFSR_AHBP_Msk (1UL << SCB_ABFSR_AHBP_Pos) /*!< SCB ABFSR: AHBP Mask */ #define SCB_ABFSR_DTCM_Pos 1 /*!< SCB ABFSR: DTCM Position*/ #define SCB_ABFSR_DTCM_Msk (1UL << SCB_ABFSR_DTCM_Pos) /*!< SCB ABFSR: DTCM Mask */ #define SCB_ABFSR_ITCM_Pos 0 /*!< SCB ABFSR: ITCM Position*/ #define SCB_ABFSR_ITCM_Msk (1UL /*<< SCB_ABFSR_ITCM_Pos*/) /*!< SCB ABFSR: ITCM Mask */ /*@} end of group CMSIS_SCB */ /** \ingroup CMSIS_core_register \defgroup CMSIS_SCnSCB System Controls not in SCB (SCnSCB) \brief Type definitions for the System Control and ID Register not in the SCB @{ */ /** \brief Structure type to access the System Control and ID Register not in the SCB. */ typedef struct { uint32_t RESERVED0[1]; __I uint32_t ICTR; /*!< Offset: 0x004 (R/ ) Interrupt Controller Type Register */ __IO uint32_t ACTLR; /*!< Offset: 0x008 (R/W) Auxiliary Control Register */ } SCnSCB_Type; /* Interrupt Controller Type Register Definitions */ #define SCnSCB_ICTR_INTLINESNUM_Pos 0 /*!< ICTR: INTLINESNUM Position */ #define SCnSCB_ICTR_INTLINESNUM_Msk (0xFUL /*<< SCnSCB_ICTR_INTLINESNUM_Pos*/) /*!< ICTR: INTLINESNUM Mask */ /* Auxiliary Control Register Definitions */ #define SCnSCB_ACTLR_DISITMATBFLUSH_Pos 12 /*!< ACTLR: DISITMATBFLUSH Position */ #define SCnSCB_ACTLR_DISITMATBFLUSH_Msk (1UL << SCnSCB_ACTLR_DISITMATBFLUSH_Pos) /*!< ACTLR: DISITMATBFLUSH Mask */ #define SCnSCB_ACTLR_DISRAMODE_Pos 11 /*!< ACTLR: DISRAMODE Position */ #define SCnSCB_ACTLR_DISRAMODE_Msk (1UL << SCnSCB_ACTLR_DISRAMODE_Pos) /*!< ACTLR: DISRAMODE Mask */ #define SCnSCB_ACTLR_FPEXCODIS_Pos 10 /*!< ACTLR: FPEXCODIS Position */ #define SCnSCB_ACTLR_FPEXCODIS_Msk (1UL << SCnSCB_ACTLR_FPEXCODIS_Pos) /*!< ACTLR: FPEXCODIS Mask */ #define SCnSCB_ACTLR_DISFOLD_Pos 2 /*!< ACTLR: DISFOLD Position */ #define SCnSCB_ACTLR_DISFOLD_Msk (1UL << SCnSCB_ACTLR_DISFOLD_Pos) /*!< ACTLR: DISFOLD Mask */ #define SCnSCB_ACTLR_DISMCYCINT_Pos 0 /*!< ACTLR: DISMCYCINT Position */ #define SCnSCB_ACTLR_DISMCYCINT_Msk (1UL /*<< SCnSCB_ACTLR_DISMCYCINT_Pos*/) /*!< ACTLR: DISMCYCINT Mask */ /*@} end of group CMSIS_SCnotSCB */ /** \ingroup CMSIS_core_register \defgroup CMSIS_SysTick System Tick Timer (SysTick) \brief Type definitions for the System Timer Registers. @{ */ /** \brief Structure type to access the System Timer (SysTick). */ typedef struct { __IO uint32_t CTRL; /*!< Offset: 0x000 (R/W) SysTick Control and Status Register */ __IO uint32_t LOAD; /*!< Offset: 0x004 (R/W) SysTick Reload Value Register */ __IO uint32_t VAL; /*!< Offset: 0x008 (R/W) SysTick Current Value Register */ __I uint32_t CALIB; /*!< Offset: 0x00C (R/ ) SysTick Calibration Register */ } SysTick_Type; /* SysTick Control / Status Register Definitions */ #define SysTick_CTRL_COUNTFLAG_Pos 16 /*!< SysTick CTRL: COUNTFLAG Position */ #define SysTick_CTRL_COUNTFLAG_Msk (1UL << SysTick_CTRL_COUNTFLAG_Pos) /*!< SysTick CTRL: COUNTFLAG Mask */ #define SysTick_CTRL_CLKSOURCE_Pos 2 /*!< SysTick CTRL: CLKSOURCE Position */ #define SysTick_CTRL_CLKSOURCE_Msk (1UL << SysTick_CTRL_CLKSOURCE_Pos) /*!< SysTick CTRL: CLKSOURCE Mask */ #define SysTick_CTRL_TICKINT_Pos 1 /*!< SysTick CTRL: TICKINT Position */ #define SysTick_CTRL_TICKINT_Msk (1UL << SysTick_CTRL_TICKINT_Pos) /*!< SysTick CTRL: TICKINT Mask */ #define SysTick_CTRL_ENABLE_Pos 0 /*!< SysTick CTRL: ENABLE Position */ #define SysTick_CTRL_ENABLE_Msk (1UL /*<< SysTick_CTRL_ENABLE_Pos*/) /*!< SysTick CTRL: ENABLE Mask */ /* SysTick Reload Register Definitions */ #define SysTick_LOAD_RELOAD_Pos 0 /*!< SysTick LOAD: RELOAD Position */ #define SysTick_LOAD_RELOAD_Msk (0xFFFFFFUL /*<< SysTick_LOAD_RELOAD_Pos*/) /*!< SysTick LOAD: RELOAD Mask */ /* SysTick Current Register Definitions */ #define SysTick_VAL_CURRENT_Pos 0 /*!< SysTick VAL: CURRENT Position */ #define SysTick_VAL_CURRENT_Msk (0xFFFFFFUL /*<< SysTick_VAL_CURRENT_Pos*/) /*!< SysTick VAL: CURRENT Mask */ /* SysTick Calibration Register Definitions */ #define SysTick_CALIB_NOREF_Pos 31 /*!< SysTick CALIB: NOREF Position */ #define SysTick_CALIB_NOREF_Msk (1UL << SysTick_CALIB_NOREF_Pos) /*!< SysTick CALIB: NOREF Mask */ #define SysTick_CALIB_SKEW_Pos 30 /*!< SysTick CALIB: SKEW Position */ #define SysTick_CALIB_SKEW_Msk (1UL << SysTick_CALIB_SKEW_Pos) /*!< SysTick CALIB: SKEW Mask */ #define SysTick_CALIB_TENMS_Pos 0 /*!< SysTick CALIB: TENMS Position */ #define SysTick_CALIB_TENMS_Msk (0xFFFFFFUL /*<< SysTick_CALIB_TENMS_Pos*/) /*!< SysTick CALIB: TENMS Mask */ /*@} end of group CMSIS_SysTick */ /** \ingroup CMSIS_core_register \defgroup CMSIS_ITM Instrumentation Trace Macrocell (ITM) \brief Type definitions for the Instrumentation Trace Macrocell (ITM) @{ */ /** \brief Structure type to access the Instrumentation Trace Macrocell Register (ITM). */ typedef struct { __O union { __O uint8_t u8; /*!< Offset: 0x000 ( /W) ITM Stimulus Port 8-bit */ __O uint16_t u16; /*!< Offset: 0x000 ( /W) ITM Stimulus Port 16-bit */ __O uint32_t u32; /*!< Offset: 0x000 ( /W) ITM Stimulus Port 32-bit */ } PORT [32]; /*!< Offset: 0x000 ( /W) ITM Stimulus Port Registers */ uint32_t RESERVED0[864]; __IO uint32_t TER; /*!< Offset: 0xE00 (R/W) ITM Trace Enable Register */ uint32_t RESERVED1[15]; __IO uint32_t TPR; /*!< Offset: 0xE40 (R/W) ITM Trace Privilege Register */ uint32_t RESERVED2[15]; __IO uint32_t TCR; /*!< Offset: 0xE80 (R/W) ITM Trace Control Register */ uint32_t RESERVED3[29]; __O uint32_t IWR; /*!< Offset: 0xEF8 ( /W) ITM Integration Write Register */ __I uint32_t IRR; /*!< Offset: 0xEFC (R/ ) ITM Integration Read Register */ __IO uint32_t IMCR; /*!< Offset: 0xF00 (R/W) ITM Integration Mode Control Register */ uint32_t RESERVED4[43]; __O uint32_t LAR; /*!< Offset: 0xFB0 ( /W) ITM Lock Access Register */ __I uint32_t LSR; /*!< Offset: 0xFB4 (R/ ) ITM Lock Status Register */ uint32_t RESERVED5[6]; __I uint32_t PID4; /*!< Offset: 0xFD0 (R/ ) ITM Peripheral Identification Register #4 */ __I uint32_t PID5; /*!< Offset: 0xFD4 (R/ ) ITM Peripheral Identification Register #5 */ __I uint32_t PID6; /*!< Offset: 0xFD8 (R/ ) ITM Peripheral Identification Register #6 */ __I uint32_t PID7; /*!< Offset: 0xFDC (R/ ) ITM Peripheral Identification Register #7 */ __I uint32_t PID0; /*!< Offset: 0xFE0 (R/ ) ITM Peripheral Identification Register #0 */ __I uint32_t PID1; /*!< Offset: 0xFE4 (R/ ) ITM Peripheral Identification Register #1 */ __I uint32_t PID2; /*!< Offset: 0xFE8 (R/ ) ITM Peripheral Identification Register #2 */ __I uint32_t PID3; /*!< Offset: 0xFEC (R/ ) ITM Peripheral Identification Register #3 */ __I uint32_t CID0; /*!< Offset: 0xFF0 (R/ ) ITM Component Identification Register #0 */ __I uint32_t CID1; /*!< Offset: 0xFF4 (R/ ) ITM Component Identification Register #1 */ __I uint32_t CID2; /*!< Offset: 0xFF8 (R/ ) ITM Component Identification Register #2 */ __I uint32_t CID3; /*!< Offset: 0xFFC (R/ ) ITM Component Identification Register #3 */ } ITM_Type; /* ITM Trace Privilege Register Definitions */ #define ITM_TPR_PRIVMASK_Pos 0 /*!< ITM TPR: PRIVMASK Position */ #define ITM_TPR_PRIVMASK_Msk (0xFUL /*<< ITM_TPR_PRIVMASK_Pos*/) /*!< ITM TPR: PRIVMASK Mask */ /* ITM Trace Control Register Definitions */ #define ITM_TCR_BUSY_Pos 23 /*!< ITM TCR: BUSY Position */ #define ITM_TCR_BUSY_Msk (1UL << ITM_TCR_BUSY_Pos) /*!< ITM TCR: BUSY Mask */ #define ITM_TCR_TraceBusID_Pos 16 /*!< ITM TCR: ATBID Position */ #define ITM_TCR_TraceBusID_Msk (0x7FUL << ITM_TCR_TraceBusID_Pos) /*!< ITM TCR: ATBID Mask */ #define ITM_TCR_GTSFREQ_Pos 10 /*!< ITM TCR: Global timestamp frequency Position */ #define ITM_TCR_GTSFREQ_Msk (3UL << ITM_TCR_GTSFREQ_Pos) /*!< ITM TCR: Global timestamp frequency Mask */ #define ITM_TCR_TSPrescale_Pos 8 /*!< ITM TCR: TSPrescale Position */ #define ITM_TCR_TSPrescale_Msk (3UL << ITM_TCR_TSPrescale_Pos) /*!< ITM TCR: TSPrescale Mask */ #define ITM_TCR_SWOENA_Pos 4 /*!< ITM TCR: SWOENA Position */ #define ITM_TCR_SWOENA_Msk (1UL << ITM_TCR_SWOENA_Pos) /*!< ITM TCR: SWOENA Mask */ #define ITM_TCR_DWTENA_Pos 3 /*!< ITM TCR: DWTENA Position */ #define ITM_TCR_DWTENA_Msk (1UL << ITM_TCR_DWTENA_Pos) /*!< ITM TCR: DWTENA Mask */ #define ITM_TCR_SYNCENA_Pos 2 /*!< ITM TCR: SYNCENA Position */ #define ITM_TCR_SYNCENA_Msk (1UL << ITM_TCR_SYNCENA_Pos) /*!< ITM TCR: SYNCENA Mask */ #define ITM_TCR_TSENA_Pos 1 /*!< ITM TCR: TSENA Position */ #define ITM_TCR_TSENA_Msk (1UL << ITM_TCR_TSENA_Pos) /*!< ITM TCR: TSENA Mask */ #define ITM_TCR_ITMENA_Pos 0 /*!< ITM TCR: ITM Enable bit Position */ #define ITM_TCR_ITMENA_Msk (1UL /*<< ITM_TCR_ITMENA_Pos*/) /*!< ITM TCR: ITM Enable bit Mask */ /* ITM Integration Write Register Definitions */ #define ITM_IWR_ATVALIDM_Pos 0 /*!< ITM IWR: ATVALIDM Position */ #define ITM_IWR_ATVALIDM_Msk (1UL /*<< ITM_IWR_ATVALIDM_Pos*/) /*!< ITM IWR: ATVALIDM Mask */ /* ITM Integration Read Register Definitions */ #define ITM_IRR_ATREADYM_Pos 0 /*!< ITM IRR: ATREADYM Position */ #define ITM_IRR_ATREADYM_Msk (1UL /*<< ITM_IRR_ATREADYM_Pos*/) /*!< ITM IRR: ATREADYM Mask */ /* ITM Integration Mode Control Register Definitions */ #define ITM_IMCR_INTEGRATION_Pos 0 /*!< ITM IMCR: INTEGRATION Position */ #define ITM_IMCR_INTEGRATION_Msk (1UL /*<< ITM_IMCR_INTEGRATION_Pos*/) /*!< ITM IMCR: INTEGRATION Mask */ /* ITM Lock Status Register Definitions */ #define ITM_LSR_ByteAcc_Pos 2 /*!< ITM LSR: ByteAcc Position */ #define ITM_LSR_ByteAcc_Msk (1UL << ITM_LSR_ByteAcc_Pos) /*!< ITM LSR: ByteAcc Mask */ #define ITM_LSR_Access_Pos 1 /*!< ITM LSR: Access Position */ #define ITM_LSR_Access_Msk (1UL << ITM_LSR_Access_Pos) /*!< ITM LSR: Access Mask */ #define ITM_LSR_Present_Pos 0 /*!< ITM LSR: Present Position */ #define ITM_LSR_Present_Msk (1UL /*<< ITM_LSR_Present_Pos*/) /*!< ITM LSR: Present Mask */ /*@}*/ /* end of group CMSIS_ITM */ /** \ingroup CMSIS_core_register \defgroup CMSIS_DWT Data Watchpoint and Trace (DWT) \brief Type definitions for the Data Watchpoint and Trace (DWT) @{ */ /** \brief Structure type to access the Data Watchpoint and Trace Register (DWT). */ typedef struct { __IO uint32_t CTRL; /*!< Offset: 0x000 (R/W) Control Register */ __IO uint32_t CYCCNT; /*!< Offset: 0x004 (R/W) Cycle Count Register */ __IO uint32_t CPICNT; /*!< Offset: 0x008 (R/W) CPI Count Register */ __IO uint32_t EXCCNT; /*!< Offset: 0x00C (R/W) Exception Overhead Count Register */ __IO uint32_t SLEEPCNT; /*!< Offset: 0x010 (R/W) Sleep Count Register */ __IO uint32_t LSUCNT; /*!< Offset: 0x014 (R/W) LSU Count Register */ __IO uint32_t FOLDCNT; /*!< Offset: 0x018 (R/W) Folded-instruction Count Register */ __I uint32_t PCSR; /*!< Offset: 0x01C (R/ ) Program Counter Sample Register */ __IO uint32_t COMP0; /*!< Offset: 0x020 (R/W) Comparator Register 0 */ __IO uint32_t MASK0; /*!< Offset: 0x024 (R/W) Mask Register 0 */ __IO uint32_t FUNCTION0; /*!< Offset: 0x028 (R/W) Function Register 0 */ uint32_t RESERVED0[1]; __IO uint32_t COMP1; /*!< Offset: 0x030 (R/W) Comparator Register 1 */ __IO uint32_t MASK1; /*!< Offset: 0x034 (R/W) Mask Register 1 */ __IO uint32_t FUNCTION1; /*!< Offset: 0x038 (R/W) Function Register 1 */ uint32_t RESERVED1[1]; __IO uint32_t COMP2; /*!< Offset: 0x040 (R/W) Comparator Register 2 */ __IO uint32_t MASK2; /*!< Offset: 0x044 (R/W) Mask Register 2 */ __IO uint32_t FUNCTION2; /*!< Offset: 0x048 (R/W) Function Register 2 */ uint32_t RESERVED2[1]; __IO uint32_t COMP3; /*!< Offset: 0x050 (R/W) Comparator Register 3 */ __IO uint32_t MASK3; /*!< Offset: 0x054 (R/W) Mask Register 3 */ __IO uint32_t FUNCTION3; /*!< Offset: 0x058 (R/W) Function Register 3 */ uint32_t RESERVED3[981]; __O uint32_t LAR; /*!< Offset: 0xFB0 ( W) Lock Access Register */ __I uint32_t LSR; /*!< Offset: 0xFB4 (R ) Lock Status Register */ } DWT_Type; /* DWT Control Register Definitions */ #define DWT_CTRL_NUMCOMP_Pos 28 /*!< DWT CTRL: NUMCOMP Position */ #define DWT_CTRL_NUMCOMP_Msk (0xFUL << DWT_CTRL_NUMCOMP_Pos) /*!< DWT CTRL: NUMCOMP Mask */ #define DWT_CTRL_NOTRCPKT_Pos 27 /*!< DWT CTRL: NOTRCPKT Position */ #define DWT_CTRL_NOTRCPKT_Msk (0x1UL << DWT_CTRL_NOTRCPKT_Pos) /*!< DWT CTRL: NOTRCPKT Mask */ #define DWT_CTRL_NOEXTTRIG_Pos 26 /*!< DWT CTRL: NOEXTTRIG Position */ #define DWT_CTRL_NOEXTTRIG_Msk (0x1UL << DWT_CTRL_NOEXTTRIG_Pos) /*!< DWT CTRL: NOEXTTRIG Mask */ #define DWT_CTRL_NOCYCCNT_Pos 25 /*!< DWT CTRL: NOCYCCNT Position */ #define DWT_CTRL_NOCYCCNT_Msk (0x1UL << DWT_CTRL_NOCYCCNT_Pos) /*!< DWT CTRL: NOCYCCNT Mask */ #define DWT_CTRL_NOPRFCNT_Pos 24 /*!< DWT CTRL: NOPRFCNT Position */ #define DWT_CTRL_NOPRFCNT_Msk (0x1UL << DWT_CTRL_NOPRFCNT_Pos) /*!< DWT CTRL: NOPRFCNT Mask */ #define DWT_CTRL_CYCEVTENA_Pos 22 /*!< DWT CTRL: CYCEVTENA Position */ #define DWT_CTRL_CYCEVTENA_Msk (0x1UL << DWT_CTRL_CYCEVTENA_Pos) /*!< DWT CTRL: CYCEVTENA Mask */ #define DWT_CTRL_FOLDEVTENA_Pos 21 /*!< DWT CTRL: FOLDEVTENA Position */ #define DWT_CTRL_FOLDEVTENA_Msk (0x1UL << DWT_CTRL_FOLDEVTENA_Pos) /*!< DWT CTRL: FOLDEVTENA Mask */ #define DWT_CTRL_LSUEVTENA_Pos 20 /*!< DWT CTRL: LSUEVTENA Position */ #define DWT_CTRL_LSUEVTENA_Msk (0x1UL << DWT_CTRL_LSUEVTENA_Pos) /*!< DWT CTRL: LSUEVTENA Mask */ #define DWT_CTRL_SLEEPEVTENA_Pos 19 /*!< DWT CTRL: SLEEPEVTENA Position */ #define DWT_CTRL_SLEEPEVTENA_Msk (0x1UL << DWT_CTRL_SLEEPEVTENA_Pos) /*!< DWT CTRL: SLEEPEVTENA Mask */ #define DWT_CTRL_EXCEVTENA_Pos 18 /*!< DWT CTRL: EXCEVTENA Position */ #define DWT_CTRL_EXCEVTENA_Msk (0x1UL << DWT_CTRL_EXCEVTENA_Pos) /*!< DWT CTRL: EXCEVTENA Mask */ #define DWT_CTRL_CPIEVTENA_Pos 17 /*!< DWT CTRL: CPIEVTENA Position */ #define DWT_CTRL_CPIEVTENA_Msk (0x1UL << DWT_CTRL_CPIEVTENA_Pos) /*!< DWT CTRL: CPIEVTENA Mask */ #define DWT_CTRL_EXCTRCENA_Pos 16 /*!< DWT CTRL: EXCTRCENA Position */ #define DWT_CTRL_EXCTRCENA_Msk (0x1UL << DWT_CTRL_EXCTRCENA_Pos) /*!< DWT CTRL: EXCTRCENA Mask */ #define DWT_CTRL_PCSAMPLENA_Pos 12 /*!< DWT CTRL: PCSAMPLENA Position */ #define DWT_CTRL_PCSAMPLENA_Msk (0x1UL << DWT_CTRL_PCSAMPLENA_Pos) /*!< DWT CTRL: PCSAMPLENA Mask */ #define DWT_CTRL_SYNCTAP_Pos 10 /*!< DWT CTRL: SYNCTAP Position */ #define DWT_CTRL_SYNCTAP_Msk (0x3UL << DWT_CTRL_SYNCTAP_Pos) /*!< DWT CTRL: SYNCTAP Mask */ #define DWT_CTRL_CYCTAP_Pos 9 /*!< DWT CTRL: CYCTAP Position */ #define DWT_CTRL_CYCTAP_Msk (0x1UL << DWT_CTRL_CYCTAP_Pos) /*!< DWT CTRL: CYCTAP Mask */ #define DWT_CTRL_POSTINIT_Pos 5 /*!< DWT CTRL: POSTINIT Position */ #define DWT_CTRL_POSTINIT_Msk (0xFUL << DWT_CTRL_POSTINIT_Pos) /*!< DWT CTRL: POSTINIT Mask */ #define DWT_CTRL_POSTPRESET_Pos 1 /*!< DWT CTRL: POSTPRESET Position */ #define DWT_CTRL_POSTPRESET_Msk (0xFUL << DWT_CTRL_POSTPRESET_Pos) /*!< DWT CTRL: POSTPRESET Mask */ #define DWT_CTRL_CYCCNTENA_Pos 0 /*!< DWT CTRL: CYCCNTENA Position */ #define DWT_CTRL_CYCCNTENA_Msk (0x1UL /*<< DWT_CTRL_CYCCNTENA_Pos*/) /*!< DWT CTRL: CYCCNTENA Mask */ /* DWT CPI Count Register Definitions */ #define DWT_CPICNT_CPICNT_Pos 0 /*!< DWT CPICNT: CPICNT Position */ #define DWT_CPICNT_CPICNT_Msk (0xFFUL /*<< DWT_CPICNT_CPICNT_Pos*/) /*!< DWT CPICNT: CPICNT Mask */ /* DWT Exception Overhead Count Register Definitions */ #define DWT_EXCCNT_EXCCNT_Pos 0 /*!< DWT EXCCNT: EXCCNT Position */ #define DWT_EXCCNT_EXCCNT_Msk (0xFFUL /*<< DWT_EXCCNT_EXCCNT_Pos*/) /*!< DWT EXCCNT: EXCCNT Mask */ /* DWT Sleep Count Register Definitions */ #define DWT_SLEEPCNT_SLEEPCNT_Pos 0 /*!< DWT SLEEPCNT: SLEEPCNT Position */ #define DWT_SLEEPCNT_SLEEPCNT_Msk (0xFFUL /*<< DWT_SLEEPCNT_SLEEPCNT_Pos*/) /*!< DWT SLEEPCNT: SLEEPCNT Mask */ /* DWT LSU Count Register Definitions */ #define DWT_LSUCNT_LSUCNT_Pos 0 /*!< DWT LSUCNT: LSUCNT Position */ #define DWT_LSUCNT_LSUCNT_Msk (0xFFUL /*<< DWT_LSUCNT_LSUCNT_Pos*/) /*!< DWT LSUCNT: LSUCNT Mask */ /* DWT Folded-instruction Count Register Definitions */ #define DWT_FOLDCNT_FOLDCNT_Pos 0 /*!< DWT FOLDCNT: FOLDCNT Position */ #define DWT_FOLDCNT_FOLDCNT_Msk (0xFFUL /*<< DWT_FOLDCNT_FOLDCNT_Pos*/) /*!< DWT FOLDCNT: FOLDCNT Mask */ /* DWT Comparator Mask Register Definitions */ #define DWT_MASK_MASK_Pos 0 /*!< DWT MASK: MASK Position */ #define DWT_MASK_MASK_Msk (0x1FUL /*<< DWT_MASK_MASK_Pos*/) /*!< DWT MASK: MASK Mask */ /* DWT Comparator Function Register Definitions */ #define DWT_FUNCTION_MATCHED_Pos 24 /*!< DWT FUNCTION: MATCHED Position */ #define DWT_FUNCTION_MATCHED_Msk (0x1UL << DWT_FUNCTION_MATCHED_Pos) /*!< DWT FUNCTION: MATCHED Mask */ #define DWT_FUNCTION_DATAVADDR1_Pos 16 /*!< DWT FUNCTION: DATAVADDR1 Position */ #define DWT_FUNCTION_DATAVADDR1_Msk (0xFUL << DWT_FUNCTION_DATAVADDR1_Pos) /*!< DWT FUNCTION: DATAVADDR1 Mask */ #define DWT_FUNCTION_DATAVADDR0_Pos 12 /*!< DWT FUNCTION: DATAVADDR0 Position */ #define DWT_FUNCTION_DATAVADDR0_Msk (0xFUL << DWT_FUNCTION_DATAVADDR0_Pos) /*!< DWT FUNCTION: DATAVADDR0 Mask */ #define DWT_FUNCTION_DATAVSIZE_Pos 10 /*!< DWT FUNCTION: DATAVSIZE Position */ #define DWT_FUNCTION_DATAVSIZE_Msk (0x3UL << DWT_FUNCTION_DATAVSIZE_Pos) /*!< DWT FUNCTION: DATAVSIZE Mask */ #define DWT_FUNCTION_LNK1ENA_Pos 9 /*!< DWT FUNCTION: LNK1ENA Position */ #define DWT_FUNCTION_LNK1ENA_Msk (0x1UL << DWT_FUNCTION_LNK1ENA_Pos) /*!< DWT FUNCTION: LNK1ENA Mask */ #define DWT_FUNCTION_DATAVMATCH_Pos 8 /*!< DWT FUNCTION: DATAVMATCH Position */ #define DWT_FUNCTION_DATAVMATCH_Msk (0x1UL << DWT_FUNCTION_DATAVMATCH_Pos) /*!< DWT FUNCTION: DATAVMATCH Mask */ #define DWT_FUNCTION_CYCMATCH_Pos 7 /*!< DWT FUNCTION: CYCMATCH Position */ #define DWT_FUNCTION_CYCMATCH_Msk (0x1UL << DWT_FUNCTION_CYCMATCH_Pos) /*!< DWT FUNCTION: CYCMATCH Mask */ #define DWT_FUNCTION_EMITRANGE_Pos 5 /*!< DWT FUNCTION: EMITRANGE Position */ #define DWT_FUNCTION_EMITRANGE_Msk (0x1UL << DWT_FUNCTION_EMITRANGE_Pos) /*!< DWT FUNCTION: EMITRANGE Mask */ #define DWT_FUNCTION_FUNCTION_Pos 0 /*!< DWT FUNCTION: FUNCTION Position */ #define DWT_FUNCTION_FUNCTION_Msk (0xFUL /*<< DWT_FUNCTION_FUNCTION_Pos*/) /*!< DWT FUNCTION: FUNCTION Mask */ /*@}*/ /* end of group CMSIS_DWT */ /** \ingroup CMSIS_core_register \defgroup CMSIS_TPI Trace Port Interface (TPI) \brief Type definitions for the Trace Port Interface (TPI) @{ */ /** \brief Structure type to access the Trace Port Interface Register (TPI). */ typedef struct { __IO uint32_t SSPSR; /*!< Offset: 0x000 (R/ ) Supported Parallel Port Size Register */ __IO uint32_t CSPSR; /*!< Offset: 0x004 (R/W) Current Parallel Port Size Register */ uint32_t RESERVED0[2]; __IO uint32_t ACPR; /*!< Offset: 0x010 (R/W) Asynchronous Clock Prescaler Register */ uint32_t RESERVED1[55]; __IO uint32_t SPPR; /*!< Offset: 0x0F0 (R/W) Selected Pin Protocol Register */ uint32_t RESERVED2[131]; __I uint32_t FFSR; /*!< Offset: 0x300 (R/ ) Formatter and Flush Status Register */ __IO uint32_t FFCR; /*!< Offset: 0x304 (R/W) Formatter and Flush Control Register */ __I uint32_t FSCR; /*!< Offset: 0x308 (R/ ) Formatter Synchronization Counter Register */ uint32_t RESERVED3[759]; __I uint32_t TRIGGER; /*!< Offset: 0xEE8 (R/ ) TRIGGER */ __I uint32_t FIFO0; /*!< Offset: 0xEEC (R/ ) Integration ETM Data */ __I uint32_t ITATBCTR2; /*!< Offset: 0xEF0 (R/ ) ITATBCTR2 */ uint32_t RESERVED4[1]; __I uint32_t ITATBCTR0; /*!< Offset: 0xEF8 (R/ ) ITATBCTR0 */ __I uint32_t FIFO1; /*!< Offset: 0xEFC (R/ ) Integration ITM Data */ __IO uint32_t ITCTRL; /*!< Offset: 0xF00 (R/W) Integration Mode Control */ uint32_t RESERVED5[39]; __IO uint32_t CLAIMSET; /*!< Offset: 0xFA0 (R/W) Claim tag set */ __IO uint32_t CLAIMCLR; /*!< Offset: 0xFA4 (R/W) Claim tag clear */ uint32_t RESERVED7[8]; __I uint32_t DEVID; /*!< Offset: 0xFC8 (R/ ) TPIU_DEVID */ __I uint32_t DEVTYPE; /*!< Offset: 0xFCC (R/ ) TPIU_DEVTYPE */ } TPI_Type; /* TPI Asynchronous Clock Prescaler Register Definitions */ #define TPI_ACPR_PRESCALER_Pos 0 /*!< TPI ACPR: PRESCALER Position */ #define TPI_ACPR_PRESCALER_Msk (0x1FFFUL /*<< TPI_ACPR_PRESCALER_Pos*/) /*!< TPI ACPR: PRESCALER Mask */ /* TPI Selected Pin Protocol Register Definitions */ #define TPI_SPPR_TXMODE_Pos 0 /*!< TPI SPPR: TXMODE Position */ #define TPI_SPPR_TXMODE_Msk (0x3UL /*<< TPI_SPPR_TXMODE_Pos*/) /*!< TPI SPPR: TXMODE Mask */ /* TPI Formatter and Flush Status Register Definitions */ #define TPI_FFSR_FtNonStop_Pos 3 /*!< TPI FFSR: FtNonStop Position */ #define TPI_FFSR_FtNonStop_Msk (0x1UL << TPI_FFSR_FtNonStop_Pos) /*!< TPI FFSR: FtNonStop Mask */ #define TPI_FFSR_TCPresent_Pos 2 /*!< TPI FFSR: TCPresent Position */ #define TPI_FFSR_TCPresent_Msk (0x1UL << TPI_FFSR_TCPresent_Pos) /*!< TPI FFSR: TCPresent Mask */ #define TPI_FFSR_FtStopped_Pos 1 /*!< TPI FFSR: FtStopped Position */ #define TPI_FFSR_FtStopped_Msk (0x1UL << TPI_FFSR_FtStopped_Pos) /*!< TPI FFSR: FtStopped Mask */ #define TPI_FFSR_FlInProg_Pos 0 /*!< TPI FFSR: FlInProg Position */ #define TPI_FFSR_FlInProg_Msk (0x1UL /*<< TPI_FFSR_FlInProg_Pos*/) /*!< TPI FFSR: FlInProg Mask */ /* TPI Formatter and Flush Control Register Definitions */ #define TPI_FFCR_TrigIn_Pos 8 /*!< TPI FFCR: TrigIn Position */ #define TPI_FFCR_TrigIn_Msk (0x1UL << TPI_FFCR_TrigIn_Pos) /*!< TPI FFCR: TrigIn Mask */ #define TPI_FFCR_EnFCont_Pos 1 /*!< TPI FFCR: EnFCont Position */ #define TPI_FFCR_EnFCont_Msk (0x1UL << TPI_FFCR_EnFCont_Pos) /*!< TPI FFCR: EnFCont Mask */ /* TPI TRIGGER Register Definitions */ #define TPI_TRIGGER_TRIGGER_Pos 0 /*!< TPI TRIGGER: TRIGGER Position */ #define TPI_TRIGGER_TRIGGER_Msk (0x1UL /*<< TPI_TRIGGER_TRIGGER_Pos*/) /*!< TPI TRIGGER: TRIGGER Mask */ /* TPI Integration ETM Data Register Definitions (FIFO0) */ #define TPI_FIFO0_ITM_ATVALID_Pos 29 /*!< TPI FIFO0: ITM_ATVALID Position */ #define TPI_FIFO0_ITM_ATVALID_Msk (0x3UL << TPI_FIFO0_ITM_ATVALID_Pos) /*!< TPI FIFO0: ITM_ATVALID Mask */ #define TPI_FIFO0_ITM_bytecount_Pos 27 /*!< TPI FIFO0: ITM_bytecount Position */ #define TPI_FIFO0_ITM_bytecount_Msk (0x3UL << TPI_FIFO0_ITM_bytecount_Pos) /*!< TPI FIFO0: ITM_bytecount Mask */ #define TPI_FIFO0_ETM_ATVALID_Pos 26 /*!< TPI FIFO0: ETM_ATVALID Position */ #define TPI_FIFO0_ETM_ATVALID_Msk (0x3UL << TPI_FIFO0_ETM_ATVALID_Pos) /*!< TPI FIFO0: ETM_ATVALID Mask */ #define TPI_FIFO0_ETM_bytecount_Pos 24 /*!< TPI FIFO0: ETM_bytecount Position */ #define TPI_FIFO0_ETM_bytecount_Msk (0x3UL << TPI_FIFO0_ETM_bytecount_Pos) /*!< TPI FIFO0: ETM_bytecount Mask */ #define TPI_FIFO0_ETM2_Pos 16 /*!< TPI FIFO0: ETM2 Position */ #define TPI_FIFO0_ETM2_Msk (0xFFUL << TPI_FIFO0_ETM2_Pos) /*!< TPI FIFO0: ETM2 Mask */ #define TPI_FIFO0_ETM1_Pos 8 /*!< TPI FIFO0: ETM1 Position */ #define TPI_FIFO0_ETM1_Msk (0xFFUL << TPI_FIFO0_ETM1_Pos) /*!< TPI FIFO0: ETM1 Mask */ #define TPI_FIFO0_ETM0_Pos 0 /*!< TPI FIFO0: ETM0 Position */ #define TPI_FIFO0_ETM0_Msk (0xFFUL /*<< TPI_FIFO0_ETM0_Pos*/) /*!< TPI FIFO0: ETM0 Mask */ /* TPI ITATBCTR2 Register Definitions */ #define TPI_ITATBCTR2_ATREADY_Pos 0 /*!< TPI ITATBCTR2: ATREADY Position */ #define TPI_ITATBCTR2_ATREADY_Msk (0x1UL /*<< TPI_ITATBCTR2_ATREADY_Pos*/) /*!< TPI ITATBCTR2: ATREADY Mask */ /* TPI Integration ITM Data Register Definitions (FIFO1) */ #define TPI_FIFO1_ITM_ATVALID_Pos 29 /*!< TPI FIFO1: ITM_ATVALID Position */ #define TPI_FIFO1_ITM_ATVALID_Msk (0x3UL << TPI_FIFO1_ITM_ATVALID_Pos) /*!< TPI FIFO1: ITM_ATVALID Mask */ #define TPI_FIFO1_ITM_bytecount_Pos 27 /*!< TPI FIFO1: ITM_bytecount Position */ #define TPI_FIFO1_ITM_bytecount_Msk (0x3UL << TPI_FIFO1_ITM_bytecount_Pos) /*!< TPI FIFO1: ITM_bytecount Mask */ #define TPI_FIFO1_ETM_ATVALID_Pos 26 /*!< TPI FIFO1: ETM_ATVALID Position */ #define TPI_FIFO1_ETM_ATVALID_Msk (0x3UL << TPI_FIFO1_ETM_ATVALID_Pos) /*!< TPI FIFO1: ETM_ATVALID Mask */ #define TPI_FIFO1_ETM_bytecount_Pos 24 /*!< TPI FIFO1: ETM_bytecount Position */ #define TPI_FIFO1_ETM_bytecount_Msk (0x3UL << TPI_FIFO1_ETM_bytecount_Pos) /*!< TPI FIFO1: ETM_bytecount Mask */ #define TPI_FIFO1_ITM2_Pos 16 /*!< TPI FIFO1: ITM2 Position */ #define TPI_FIFO1_ITM2_Msk (0xFFUL << TPI_FIFO1_ITM2_Pos) /*!< TPI FIFO1: ITM2 Mask */ #define TPI_FIFO1_ITM1_Pos 8 /*!< TPI FIFO1: ITM1 Position */ #define TPI_FIFO1_ITM1_Msk (0xFFUL << TPI_FIFO1_ITM1_Pos) /*!< TPI FIFO1: ITM1 Mask */ #define TPI_FIFO1_ITM0_Pos 0 /*!< TPI FIFO1: ITM0 Position */ #define TPI_FIFO1_ITM0_Msk (0xFFUL /*<< TPI_FIFO1_ITM0_Pos*/) /*!< TPI FIFO1: ITM0 Mask */ /* TPI ITATBCTR0 Register Definitions */ #define TPI_ITATBCTR0_ATREADY_Pos 0 /*!< TPI ITATBCTR0: ATREADY Position */ #define TPI_ITATBCTR0_ATREADY_Msk (0x1UL /*<< TPI_ITATBCTR0_ATREADY_Pos*/) /*!< TPI ITATBCTR0: ATREADY Mask */ /* TPI Integration Mode Control Register Definitions */ #define TPI_ITCTRL_Mode_Pos 0 /*!< TPI ITCTRL: Mode Position */ #define TPI_ITCTRL_Mode_Msk (0x1UL /*<< TPI_ITCTRL_Mode_Pos*/) /*!< TPI ITCTRL: Mode Mask */ /* TPI DEVID Register Definitions */ #define TPI_DEVID_NRZVALID_Pos 11 /*!< TPI DEVID: NRZVALID Position */ #define TPI_DEVID_NRZVALID_Msk (0x1UL << TPI_DEVID_NRZVALID_Pos) /*!< TPI DEVID: NRZVALID Mask */ #define TPI_DEVID_MANCVALID_Pos 10 /*!< TPI DEVID: MANCVALID Position */ #define TPI_DEVID_MANCVALID_Msk (0x1UL << TPI_DEVID_MANCVALID_Pos) /*!< TPI DEVID: MANCVALID Mask */ #define TPI_DEVID_PTINVALID_Pos 9 /*!< TPI DEVID: PTINVALID Position */ #define TPI_DEVID_PTINVALID_Msk (0x1UL << TPI_DEVID_PTINVALID_Pos) /*!< TPI DEVID: PTINVALID Mask */ #define TPI_DEVID_MinBufSz_Pos 6 /*!< TPI DEVID: MinBufSz Position */ #define TPI_DEVID_MinBufSz_Msk (0x7UL << TPI_DEVID_MinBufSz_Pos) /*!< TPI DEVID: MinBufSz Mask */ #define TPI_DEVID_AsynClkIn_Pos 5 /*!< TPI DEVID: AsynClkIn Position */ #define TPI_DEVID_AsynClkIn_Msk (0x1UL << TPI_DEVID_AsynClkIn_Pos) /*!< TPI DEVID: AsynClkIn Mask */ #define TPI_DEVID_NrTraceInput_Pos 0 /*!< TPI DEVID: NrTraceInput Position */ #define TPI_DEVID_NrTraceInput_Msk (0x1FUL /*<< TPI_DEVID_NrTraceInput_Pos*/) /*!< TPI DEVID: NrTraceInput Mask */ /* TPI DEVTYPE Register Definitions */ #define TPI_DEVTYPE_MajorType_Pos 4 /*!< TPI DEVTYPE: MajorType Position */ #define TPI_DEVTYPE_MajorType_Msk (0xFUL << TPI_DEVTYPE_MajorType_Pos) /*!< TPI DEVTYPE: MajorType Mask */ #define TPI_DEVTYPE_SubType_Pos 0 /*!< TPI DEVTYPE: SubType Position */ #define TPI_DEVTYPE_SubType_Msk (0xFUL /*<< TPI_DEVTYPE_SubType_Pos*/) /*!< TPI DEVTYPE: SubType Mask */ /*@}*/ /* end of group CMSIS_TPI */ #if (__MPU_PRESENT == 1) /** \ingroup CMSIS_core_register \defgroup CMSIS_MPU Memory Protection Unit (MPU) \brief Type definitions for the Memory Protection Unit (MPU) @{ */ /** \brief Structure type to access the Memory Protection Unit (MPU). */ typedef struct { __I uint32_t TYPE; /*!< Offset: 0x000 (R/ ) MPU Type Register */ __IO uint32_t CTRL; /*!< Offset: 0x004 (R/W) MPU Control Register */ __IO uint32_t RNR; /*!< Offset: 0x008 (R/W) MPU Region RNRber Register */ __IO uint32_t RBAR; /*!< Offset: 0x00C (R/W) MPU Region Base Address Register */ __IO uint32_t RASR; /*!< Offset: 0x010 (R/W) MPU Region Attribute and Size Register */ __IO uint32_t RBAR_A1; /*!< Offset: 0x014 (R/W) MPU Alias 1 Region Base Address Register */ __IO uint32_t RASR_A1; /*!< Offset: 0x018 (R/W) MPU Alias 1 Region Attribute and Size Register */ __IO uint32_t RBAR_A2; /*!< Offset: 0x01C (R/W) MPU Alias 2 Region Base Address Register */ __IO uint32_t RASR_A2; /*!< Offset: 0x020 (R/W) MPU Alias 2 Region Attribute and Size Register */ __IO uint32_t RBAR_A3; /*!< Offset: 0x024 (R/W) MPU Alias 3 Region Base Address Register */ __IO uint32_t RASR_A3; /*!< Offset: 0x028 (R/W) MPU Alias 3 Region Attribute and Size Register */ } MPU_Type; /* MPU Type Register */ #define MPU_TYPE_IREGION_Pos 16 /*!< MPU TYPE: IREGION Position */ #define MPU_TYPE_IREGION_Msk (0xFFUL << MPU_TYPE_IREGION_Pos) /*!< MPU TYPE: IREGION Mask */ #define MPU_TYPE_DREGION_Pos 8 /*!< MPU TYPE: DREGION Position */ #define MPU_TYPE_DREGION_Msk (0xFFUL << MPU_TYPE_DREGION_Pos) /*!< MPU TYPE: DREGION Mask */ #define MPU_TYPE_SEPARATE_Pos 0 /*!< MPU TYPE: SEPARATE Position */ #define MPU_TYPE_SEPARATE_Msk (1UL /*<< MPU_TYPE_SEPARATE_Pos*/) /*!< MPU TYPE: SEPARATE Mask */ /* MPU Control Register */ #define MPU_CTRL_PRIVDEFENA_Pos 2 /*!< MPU CTRL: PRIVDEFENA Position */ #define MPU_CTRL_PRIVDEFENA_Msk (1UL << MPU_CTRL_PRIVDEFENA_Pos) /*!< MPU CTRL: PRIVDEFENA Mask */ #define MPU_CTRL_HFNMIENA_Pos 1 /*!< MPU CTRL: HFNMIENA Position */ #define MPU_CTRL_HFNMIENA_Msk (1UL << MPU_CTRL_HFNMIENA_Pos) /*!< MPU CTRL: HFNMIENA Mask */ #define MPU_CTRL_ENABLE_Pos 0 /*!< MPU CTRL: ENABLE Position */ #define MPU_CTRL_ENABLE_Msk (1UL /*<< MPU_CTRL_ENABLE_Pos*/) /*!< MPU CTRL: ENABLE Mask */ /* MPU Region Number Register */ #define MPU_RNR_REGION_Pos 0 /*!< MPU RNR: REGION Position */ #define MPU_RNR_REGION_Msk (0xFFUL /*<< MPU_RNR_REGION_Pos*/) /*!< MPU RNR: REGION Mask */ /* MPU Region Base Address Register */ #define MPU_RBAR_ADDR_Pos 5 /*!< MPU RBAR: ADDR Position */ #define MPU_RBAR_ADDR_Msk (0x7FFFFFFUL << MPU_RBAR_ADDR_Pos) /*!< MPU RBAR: ADDR Mask */ #define MPU_RBAR_VALID_Pos 4 /*!< MPU RBAR: VALID Position */ #define MPU_RBAR_VALID_Msk (1UL << MPU_RBAR_VALID_Pos) /*!< MPU RBAR: VALID Mask */ #define MPU_RBAR_REGION_Pos 0 /*!< MPU RBAR: REGION Position */ #define MPU_RBAR_REGION_Msk (0xFUL /*<< MPU_RBAR_REGION_Pos*/) /*!< MPU RBAR: REGION Mask */ /* MPU Region Attribute and Size Register */ #define MPU_RASR_ATTRS_Pos 16 /*!< MPU RASR: MPU Region Attribute field Position */ #define MPU_RASR_ATTRS_Msk (0xFFFFUL << MPU_RASR_ATTRS_Pos) /*!< MPU RASR: MPU Region Attribute field Mask */ #define MPU_RASR_XN_Pos 28 /*!< MPU RASR: ATTRS.XN Position */ #define MPU_RASR_XN_Msk (1UL << MPU_RASR_XN_Pos) /*!< MPU RASR: ATTRS.XN Mask */ #define MPU_RASR_AP_Pos 24 /*!< MPU RASR: ATTRS.AP Position */ #define MPU_RASR_AP_Msk (0x7UL << MPU_RASR_AP_Pos) /*!< MPU RASR: ATTRS.AP Mask */ #define MPU_RASR_TEX_Pos 19 /*!< MPU RASR: ATTRS.TEX Position */ #define MPU_RASR_TEX_Msk (0x7UL << MPU_RASR_TEX_Pos) /*!< MPU RASR: ATTRS.TEX Mask */ #define MPU_RASR_S_Pos 18 /*!< MPU RASR: ATTRS.S Position */ #define MPU_RASR_S_Msk (1UL << MPU_RASR_S_Pos) /*!< MPU RASR: ATTRS.S Mask */ #define MPU_RASR_C_Pos 17 /*!< MPU RASR: ATTRS.C Position */ #define MPU_RASR_C_Msk (1UL << MPU_RASR_C_Pos) /*!< MPU RASR: ATTRS.C Mask */ #define MPU_RASR_B_Pos 16 /*!< MPU RASR: ATTRS.B Position */ #define MPU_RASR_B_Msk (1UL << MPU_RASR_B_Pos) /*!< MPU RASR: ATTRS.B Mask */ #define MPU_RASR_SRD_Pos 8 /*!< MPU RASR: Sub-Region Disable Position */ #define MPU_RASR_SRD_Msk (0xFFUL << MPU_RASR_SRD_Pos) /*!< MPU RASR: Sub-Region Disable Mask */ #define MPU_RASR_SIZE_Pos 1 /*!< MPU RASR: Region Size Field Position */ #define MPU_RASR_SIZE_Msk (0x1FUL << MPU_RASR_SIZE_Pos) /*!< MPU RASR: Region Size Field Mask */ #define MPU_RASR_ENABLE_Pos 0 /*!< MPU RASR: Region enable bit Position */ #define MPU_RASR_ENABLE_Msk (1UL /*<< MPU_RASR_ENABLE_Pos*/) /*!< MPU RASR: Region enable bit Disable Mask */ /*@} end of group CMSIS_MPU */ #endif #if (__FPU_PRESENT == 1) /** \ingroup CMSIS_core_register \defgroup CMSIS_FPU Floating Point Unit (FPU) \brief Type definitions for the Floating Point Unit (FPU) @{ */ /** \brief Structure type to access the Floating Point Unit (FPU). */ typedef struct { uint32_t RESERVED0[1]; __IO uint32_t FPCCR; /*!< Offset: 0x004 (R/W) Floating-Point Context Control Register */ __IO uint32_t FPCAR; /*!< Offset: 0x008 (R/W) Floating-Point Context Address Register */ __IO uint32_t FPDSCR; /*!< Offset: 0x00C (R/W) Floating-Point Default Status Control Register */ __I uint32_t MVFR0; /*!< Offset: 0x010 (R/ ) Media and FP Feature Register 0 */ __I uint32_t MVFR1; /*!< Offset: 0x014 (R/ ) Media and FP Feature Register 1 */ __I uint32_t MVFR2; /*!< Offset: 0x018 (R/ ) Media and FP Feature Register 2 */ } FPU_Type; /* Floating-Point Context Control Register */ #define FPU_FPCCR_ASPEN_Pos 31 /*!< FPCCR: ASPEN bit Position */ #define FPU_FPCCR_ASPEN_Msk (1UL << FPU_FPCCR_ASPEN_Pos) /*!< FPCCR: ASPEN bit Mask */ #define FPU_FPCCR_LSPEN_Pos 30 /*!< FPCCR: LSPEN Position */ #define FPU_FPCCR_LSPEN_Msk (1UL << FPU_FPCCR_LSPEN_Pos) /*!< FPCCR: LSPEN bit Mask */ #define FPU_FPCCR_MONRDY_Pos 8 /*!< FPCCR: MONRDY Position */ #define FPU_FPCCR_MONRDY_Msk (1UL << FPU_FPCCR_MONRDY_Pos) /*!< FPCCR: MONRDY bit Mask */ #define FPU_FPCCR_BFRDY_Pos 6 /*!< FPCCR: BFRDY Position */ #define FPU_FPCCR_BFRDY_Msk (1UL << FPU_FPCCR_BFRDY_Pos) /*!< FPCCR: BFRDY bit Mask */ #define FPU_FPCCR_MMRDY_Pos 5 /*!< FPCCR: MMRDY Position */ #define FPU_FPCCR_MMRDY_Msk (1UL << FPU_FPCCR_MMRDY_Pos) /*!< FPCCR: MMRDY bit Mask */ #define FPU_FPCCR_HFRDY_Pos 4 /*!< FPCCR: HFRDY Position */ #define FPU_FPCCR_HFRDY_Msk (1UL << FPU_FPCCR_HFRDY_Pos) /*!< FPCCR: HFRDY bit Mask */ #define FPU_FPCCR_THREAD_Pos 3 /*!< FPCCR: processor mode bit Position */ #define FPU_FPCCR_THREAD_Msk (1UL << FPU_FPCCR_THREAD_Pos) /*!< FPCCR: processor mode active bit Mask */ #define FPU_FPCCR_USER_Pos 1 /*!< FPCCR: privilege level bit Position */ #define FPU_FPCCR_USER_Msk (1UL << FPU_FPCCR_USER_Pos) /*!< FPCCR: privilege level bit Mask */ #define FPU_FPCCR_LSPACT_Pos 0 /*!< FPCCR: Lazy state preservation active bit Position */ #define FPU_FPCCR_LSPACT_Msk (1UL /*<< FPU_FPCCR_LSPACT_Pos*/) /*!< FPCCR: Lazy state preservation active bit Mask */ /* Floating-Point Context Address Register */ #define FPU_FPCAR_ADDRESS_Pos 3 /*!< FPCAR: ADDRESS bit Position */ #define FPU_FPCAR_ADDRESS_Msk (0x1FFFFFFFUL << FPU_FPCAR_ADDRESS_Pos) /*!< FPCAR: ADDRESS bit Mask */ /* Floating-Point Default Status Control Register */ #define FPU_FPDSCR_AHP_Pos 26 /*!< FPDSCR: AHP bit Position */ #define FPU_FPDSCR_AHP_Msk (1UL << FPU_FPDSCR_AHP_Pos) /*!< FPDSCR: AHP bit Mask */ #define FPU_FPDSCR_DN_Pos 25 /*!< FPDSCR: DN bit Position */ #define FPU_FPDSCR_DN_Msk (1UL << FPU_FPDSCR_DN_Pos) /*!< FPDSCR: DN bit Mask */ #define FPU_FPDSCR_FZ_Pos 24 /*!< FPDSCR: FZ bit Position */ #define FPU_FPDSCR_FZ_Msk (1UL << FPU_FPDSCR_FZ_Pos) /*!< FPDSCR: FZ bit Mask */ #define FPU_FPDSCR_RMode_Pos 22 /*!< FPDSCR: RMode bit Position */ #define FPU_FPDSCR_RMode_Msk (3UL << FPU_FPDSCR_RMode_Pos) /*!< FPDSCR: RMode bit Mask */ /* Media and FP Feature Register 0 */ #define FPU_MVFR0_FP_rounding_modes_Pos 28 /*!< MVFR0: FP rounding modes bits Position */ #define FPU_MVFR0_FP_rounding_modes_Msk (0xFUL << FPU_MVFR0_FP_rounding_modes_Pos) /*!< MVFR0: FP rounding modes bits Mask */ #define FPU_MVFR0_Short_vectors_Pos 24 /*!< MVFR0: Short vectors bits Position */ #define FPU_MVFR0_Short_vectors_Msk (0xFUL << FPU_MVFR0_Short_vectors_Pos) /*!< MVFR0: Short vectors bits Mask */ #define FPU_MVFR0_Square_root_Pos 20 /*!< MVFR0: Square root bits Position */ #define FPU_MVFR0_Square_root_Msk (0xFUL << FPU_MVFR0_Square_root_Pos) /*!< MVFR0: Square root bits Mask */ #define FPU_MVFR0_Divide_Pos 16 /*!< MVFR0: Divide bits Position */ #define FPU_MVFR0_Divide_Msk (0xFUL << FPU_MVFR0_Divide_Pos) /*!< MVFR0: Divide bits Mask */ #define FPU_MVFR0_FP_excep_trapping_Pos 12 /*!< MVFR0: FP exception trapping bits Position */ #define FPU_MVFR0_FP_excep_trapping_Msk (0xFUL << FPU_MVFR0_FP_excep_trapping_Pos) /*!< MVFR0: FP exception trapping bits Mask */ #define FPU_MVFR0_Double_precision_Pos 8 /*!< MVFR0: Double-precision bits Position */ #define FPU_MVFR0_Double_precision_Msk (0xFUL << FPU_MVFR0_Double_precision_Pos) /*!< MVFR0: Double-precision bits Mask */ #define FPU_MVFR0_Single_precision_Pos 4 /*!< MVFR0: Single-precision bits Position */ #define FPU_MVFR0_Single_precision_Msk (0xFUL << FPU_MVFR0_Single_precision_Pos) /*!< MVFR0: Single-precision bits Mask */ #define FPU_MVFR0_A_SIMD_registers_Pos 0 /*!< MVFR0: A_SIMD registers bits Position */ #define FPU_MVFR0_A_SIMD_registers_Msk (0xFUL /*<< FPU_MVFR0_A_SIMD_registers_Pos*/) /*!< MVFR0: A_SIMD registers bits Mask */ /* Media and FP Feature Register 1 */ #define FPU_MVFR1_FP_fused_MAC_Pos 28 /*!< MVFR1: FP fused MAC bits Position */ #define FPU_MVFR1_FP_fused_MAC_Msk (0xFUL << FPU_MVFR1_FP_fused_MAC_Pos) /*!< MVFR1: FP fused MAC bits Mask */ #define FPU_MVFR1_FP_HPFP_Pos 24 /*!< MVFR1: FP HPFP bits Position */ #define FPU_MVFR1_FP_HPFP_Msk (0xFUL << FPU_MVFR1_FP_HPFP_Pos) /*!< MVFR1: FP HPFP bits Mask */ #define FPU_MVFR1_D_NaN_mode_Pos 4 /*!< MVFR1: D_NaN mode bits Position */ #define FPU_MVFR1_D_NaN_mode_Msk (0xFUL << FPU_MVFR1_D_NaN_mode_Pos) /*!< MVFR1: D_NaN mode bits Mask */ #define FPU_MVFR1_FtZ_mode_Pos 0 /*!< MVFR1: FtZ mode bits Position */ #define FPU_MVFR1_FtZ_mode_Msk (0xFUL /*<< FPU_MVFR1_FtZ_mode_Pos*/) /*!< MVFR1: FtZ mode bits Mask */ /* Media and FP Feature Register 2 */ /*@} end of group CMSIS_FPU */ #endif /** \ingroup CMSIS_core_register \defgroup CMSIS_CoreDebug Core Debug Registers (CoreDebug) \brief Type definitions for the Core Debug Registers @{ */ /** \brief Structure type to access the Core Debug Register (CoreDebug). */ typedef struct { __IO uint32_t DHCSR; /*!< Offset: 0x000 (R/W) Debug Halting Control and Status Register */ __O uint32_t DCRSR; /*!< Offset: 0x004 ( /W) Debug Core Register Selector Register */ __IO uint32_t DCRDR; /*!< Offset: 0x008 (R/W) Debug Core Register Data Register */ __IO uint32_t DEMCR; /*!< Offset: 0x00C (R/W) Debug Exception and Monitor Control Register */ } CoreDebug_Type; /* Debug Halting Control and Status Register */ #define CoreDebug_DHCSR_DBGKEY_Pos 16 /*!< CoreDebug DHCSR: DBGKEY Position */ #define CoreDebug_DHCSR_DBGKEY_Msk (0xFFFFUL << CoreDebug_DHCSR_DBGKEY_Pos) /*!< CoreDebug DHCSR: DBGKEY Mask */ #define CoreDebug_DHCSR_S_RESET_ST_Pos 25 /*!< CoreDebug DHCSR: S_RESET_ST Position */ #define CoreDebug_DHCSR_S_RESET_ST_Msk (1UL << CoreDebug_DHCSR_S_RESET_ST_Pos) /*!< CoreDebug DHCSR: S_RESET_ST Mask */ #define CoreDebug_DHCSR_S_RETIRE_ST_Pos 24 /*!< CoreDebug DHCSR: S_RETIRE_ST Position */ #define CoreDebug_DHCSR_S_RETIRE_ST_Msk (1UL << CoreDebug_DHCSR_S_RETIRE_ST_Pos) /*!< CoreDebug DHCSR: S_RETIRE_ST Mask */ #define CoreDebug_DHCSR_S_LOCKUP_Pos 19 /*!< CoreDebug DHCSR: S_LOCKUP Position */ #define CoreDebug_DHCSR_S_LOCKUP_Msk (1UL << CoreDebug_DHCSR_S_LOCKUP_Pos) /*!< CoreDebug DHCSR: S_LOCKUP Mask */ #define CoreDebug_DHCSR_S_SLEEP_Pos 18 /*!< CoreDebug DHCSR: S_SLEEP Position */ #define CoreDebug_DHCSR_S_SLEEP_Msk (1UL << CoreDebug_DHCSR_S_SLEEP_Pos) /*!< CoreDebug DHCSR: S_SLEEP Mask */ #define CoreDebug_DHCSR_S_HALT_Pos 17 /*!< CoreDebug DHCSR: S_HALT Position */ #define CoreDebug_DHCSR_S_HALT_Msk (1UL << CoreDebug_DHCSR_S_HALT_Pos) /*!< CoreDebug DHCSR: S_HALT Mask */ #define CoreDebug_DHCSR_S_REGRDY_Pos 16 /*!< CoreDebug DHCSR: S_REGRDY Position */ #define CoreDebug_DHCSR_S_REGRDY_Msk (1UL << CoreDebug_DHCSR_S_REGRDY_Pos) /*!< CoreDebug DHCSR: S_REGRDY Mask */ #define CoreDebug_DHCSR_C_SNAPSTALL_Pos 5 /*!< CoreDebug DHCSR: C_SNAPSTALL Position */ #define CoreDebug_DHCSR_C_SNAPSTALL_Msk (1UL << CoreDebug_DHCSR_C_SNAPSTALL_Pos) /*!< CoreDebug DHCSR: C_SNAPSTALL Mask */ #define CoreDebug_DHCSR_C_MASKINTS_Pos 3 /*!< CoreDebug DHCSR: C_MASKINTS Position */ #define CoreDebug_DHCSR_C_MASKINTS_Msk (1UL << CoreDebug_DHCSR_C_MASKINTS_Pos) /*!< CoreDebug DHCSR: C_MASKINTS Mask */ #define CoreDebug_DHCSR_C_STEP_Pos 2 /*!< CoreDebug DHCSR: C_STEP Position */ #define CoreDebug_DHCSR_C_STEP_Msk (1UL << CoreDebug_DHCSR_C_STEP_Pos) /*!< CoreDebug DHCSR: C_STEP Mask */ #define CoreDebug_DHCSR_C_HALT_Pos 1 /*!< CoreDebug DHCSR: C_HALT Position */ #define CoreDebug_DHCSR_C_HALT_Msk (1UL << CoreDebug_DHCSR_C_HALT_Pos) /*!< CoreDebug DHCSR: C_HALT Mask */ #define CoreDebug_DHCSR_C_DEBUGEN_Pos 0 /*!< CoreDebug DHCSR: C_DEBUGEN Position */ #define CoreDebug_DHCSR_C_DEBUGEN_Msk (1UL /*<< CoreDebug_DHCSR_C_DEBUGEN_Pos*/) /*!< CoreDebug DHCSR: C_DEBUGEN Mask */ /* Debug Core Register Selector Register */ #define CoreDebug_DCRSR_REGWnR_Pos 16 /*!< CoreDebug DCRSR: REGWnR Position */ #define CoreDebug_DCRSR_REGWnR_Msk (1UL << CoreDebug_DCRSR_REGWnR_Pos) /*!< CoreDebug DCRSR: REGWnR Mask */ #define CoreDebug_DCRSR_REGSEL_Pos 0 /*!< CoreDebug DCRSR: REGSEL Position */ #define CoreDebug_DCRSR_REGSEL_Msk (0x1FUL /*<< CoreDebug_DCRSR_REGSEL_Pos*/) /*!< CoreDebug DCRSR: REGSEL Mask */ /* Debug Exception and Monitor Control Register */ #define CoreDebug_DEMCR_TRCENA_Pos 24 /*!< CoreDebug DEMCR: TRCENA Position */ #define CoreDebug_DEMCR_TRCENA_Msk (1UL << CoreDebug_DEMCR_TRCENA_Pos) /*!< CoreDebug DEMCR: TRCENA Mask */ #define CoreDebug_DEMCR_MON_REQ_Pos 19 /*!< CoreDebug DEMCR: MON_REQ Position */ #define CoreDebug_DEMCR_MON_REQ_Msk (1UL << CoreDebug_DEMCR_MON_REQ_Pos) /*!< CoreDebug DEMCR: MON_REQ Mask */ #define CoreDebug_DEMCR_MON_STEP_Pos 18 /*!< CoreDebug DEMCR: MON_STEP Position */ #define CoreDebug_DEMCR_MON_STEP_Msk (1UL << CoreDebug_DEMCR_MON_STEP_Pos) /*!< CoreDebug DEMCR: MON_STEP Mask */ #define CoreDebug_DEMCR_MON_PEND_Pos 17 /*!< CoreDebug DEMCR: MON_PEND Position */ #define CoreDebug_DEMCR_MON_PEND_Msk (1UL << CoreDebug_DEMCR_MON_PEND_Pos) /*!< CoreDebug DEMCR: MON_PEND Mask */ #define CoreDebug_DEMCR_MON_EN_Pos 16 /*!< CoreDebug DEMCR: MON_EN Position */ #define CoreDebug_DEMCR_MON_EN_Msk (1UL << CoreDebug_DEMCR_MON_EN_Pos) /*!< CoreDebug DEMCR: MON_EN Mask */ #define CoreDebug_DEMCR_VC_HARDERR_Pos 10 /*!< CoreDebug DEMCR: VC_HARDERR Position */ #define CoreDebug_DEMCR_VC_HARDERR_Msk (1UL << CoreDebug_DEMCR_VC_HARDERR_Pos) /*!< CoreDebug DEMCR: VC_HARDERR Mask */ #define CoreDebug_DEMCR_VC_INTERR_Pos 9 /*!< CoreDebug DEMCR: VC_INTERR Position */ #define CoreDebug_DEMCR_VC_INTERR_Msk (1UL << CoreDebug_DEMCR_VC_INTERR_Pos) /*!< CoreDebug DEMCR: VC_INTERR Mask */ #define CoreDebug_DEMCR_VC_BUSERR_Pos 8 /*!< CoreDebug DEMCR: VC_BUSERR Position */ #define CoreDebug_DEMCR_VC_BUSERR_Msk (1UL << CoreDebug_DEMCR_VC_BUSERR_Pos) /*!< CoreDebug DEMCR: VC_BUSERR Mask */ #define CoreDebug_DEMCR_VC_STATERR_Pos 7 /*!< CoreDebug DEMCR: VC_STATERR Position */ #define CoreDebug_DEMCR_VC_STATERR_Msk (1UL << CoreDebug_DEMCR_VC_STATERR_Pos) /*!< CoreDebug DEMCR: VC_STATERR Mask */ #define CoreDebug_DEMCR_VC_CHKERR_Pos 6 /*!< CoreDebug DEMCR: VC_CHKERR Position */ #define CoreDebug_DEMCR_VC_CHKERR_Msk (1UL << CoreDebug_DEMCR_VC_CHKERR_Pos) /*!< CoreDebug DEMCR: VC_CHKERR Mask */ #define CoreDebug_DEMCR_VC_NOCPERR_Pos 5 /*!< CoreDebug DEMCR: VC_NOCPERR Position */ #define CoreDebug_DEMCR_VC_NOCPERR_Msk (1UL << CoreDebug_DEMCR_VC_NOCPERR_Pos) /*!< CoreDebug DEMCR: VC_NOCPERR Mask */ #define CoreDebug_DEMCR_VC_MMERR_Pos 4 /*!< CoreDebug DEMCR: VC_MMERR Position */ #define CoreDebug_DEMCR_VC_MMERR_Msk (1UL << CoreDebug_DEMCR_VC_MMERR_Pos) /*!< CoreDebug DEMCR: VC_MMERR Mask */ #define CoreDebug_DEMCR_VC_CORERESET_Pos 0 /*!< CoreDebug DEMCR: VC_CORERESET Position */ #define CoreDebug_DEMCR_VC_CORERESET_Msk (1UL /*<< CoreDebug_DEMCR_VC_CORERESET_Pos*/) /*!< CoreDebug DEMCR: VC_CORERESET Mask */ /*@} end of group CMSIS_CoreDebug */ /** \ingroup CMSIS_core_register \defgroup CMSIS_core_base Core Definitions \brief Definitions for base addresses, unions, and structures. @{ */ /* Memory mapping of Cortex-M4 Hardware */ #define SCS_BASE (0xE000E000UL) /*!< System Control Space Base Address */ #define ITM_BASE (0xE0000000UL) /*!< ITM Base Address */ #define DWT_BASE (0xE0001000UL) /*!< DWT Base Address */ #define TPI_BASE (0xE0040000UL) /*!< TPI Base Address */ #define CoreDebug_BASE (0xE000EDF0UL) /*!< Core Debug Base Address */ #define SysTick_BASE (SCS_BASE + 0x0010UL) /*!< SysTick Base Address */ #define NVIC_BASE (SCS_BASE + 0x0100UL) /*!< NVIC Base Address */ #define SCB_BASE (SCS_BASE + 0x0D00UL) /*!< System Control Block Base Address */ #define SCnSCB ((SCnSCB_Type *) SCS_BASE ) /*!< System control Register not in SCB */ #define SCB ((SCB_Type *) SCB_BASE ) /*!< SCB configuration struct */ #define SysTick ((SysTick_Type *) SysTick_BASE ) /*!< SysTick configuration struct */ #define NVIC ((NVIC_Type *) NVIC_BASE ) /*!< NVIC configuration struct */ #define ITM ((ITM_Type *) ITM_BASE ) /*!< ITM configuration struct */ #define DWT ((DWT_Type *) DWT_BASE ) /*!< DWT configuration struct */ #define TPI ((TPI_Type *) TPI_BASE ) /*!< TPI configuration struct */ #define CoreDebug ((CoreDebug_Type *) CoreDebug_BASE) /*!< Core Debug configuration struct */ #if (__MPU_PRESENT == 1) #define MPU_BASE (SCS_BASE + 0x0D90UL) /*!< Memory Protection Unit */ #define MPU ((MPU_Type *) MPU_BASE ) /*!< Memory Protection Unit */ #endif #if (__FPU_PRESENT == 1) #define FPU_BASE (SCS_BASE + 0x0F30UL) /*!< Floating Point Unit */ #define FPU ((FPU_Type *) FPU_BASE ) /*!< Floating Point Unit */ #endif /*@} */ /******************************************************************************* * Hardware Abstraction Layer Core Function Interface contains: - Core NVIC Functions - Core SysTick Functions - Core Debug Functions - Core Register Access Functions ******************************************************************************/ /** \defgroup CMSIS_Core_FunctionInterface Functions and Instructions Reference */ /* ########################## NVIC functions #################################### */ /** \ingroup CMSIS_Core_FunctionInterface \defgroup CMSIS_Core_NVICFunctions NVIC Functions \brief Functions that manage interrupts and exceptions via the NVIC. @{ */ /** \brief Set Priority Grouping The function sets the priority grouping field using the required unlock sequence. The parameter PriorityGroup is assigned to the field SCB->AIRCR [10:8] PRIGROUP field. Only values from 0..7 are used. In case of a conflict between priority grouping and available priority bits (__NVIC_PRIO_BITS), the smallest possible priority group is set. \param [in] PriorityGroup Priority grouping field. */ __STATIC_INLINE void NVIC_SetPriorityGrouping(uint32_t PriorityGroup) { uint32_t reg_value; uint32_t PriorityGroupTmp = (PriorityGroup & (uint32_t)0x07UL); /* only values 0..7 are used */ reg_value = SCB->AIRCR; /* read old register configuration */ reg_value &= ~((uint32_t)(SCB_AIRCR_VECTKEY_Msk | SCB_AIRCR_PRIGROUP_Msk)); /* clear bits to change */ reg_value = (reg_value | ((uint32_t)0x5FAUL << SCB_AIRCR_VECTKEY_Pos) | (PriorityGroupTmp << 8) ); /* Insert write key and priorty group */ SCB->AIRCR = reg_value; } /** \brief Get Priority Grouping The function reads the priority grouping field from the NVIC Interrupt Controller. \return Priority grouping field (SCB->AIRCR [10:8] PRIGROUP field). */ __STATIC_INLINE uint32_t NVIC_GetPriorityGrouping(void) { return ((uint32_t)((SCB->AIRCR & SCB_AIRCR_PRIGROUP_Msk) >> SCB_AIRCR_PRIGROUP_Pos)); } /** \brief Enable External Interrupt The function enables a device-specific interrupt in the NVIC interrupt controller. \param [in] IRQn External interrupt number. Value cannot be negative. */ __STATIC_INLINE void NVIC_EnableIRQ(IRQn_Type IRQn) { NVIC->ISER[(((uint32_t)(int32_t)IRQn) >> 5UL)] = (uint32_t)(1UL << (((uint32_t)(int32_t)IRQn) & 0x1FUL)); } /** \brief Disable External Interrupt The function disables a device-specific interrupt in the NVIC interrupt controller. \param [in] IRQn External interrupt number. Value cannot be negative. */ __STATIC_INLINE void NVIC_DisableIRQ(IRQn_Type IRQn) { NVIC->ICER[(((uint32_t)(int32_t)IRQn) >> 5UL)] = (uint32_t)(1UL << (((uint32_t)(int32_t)IRQn) & 0x1FUL)); } /** \brief Get Pending Interrupt The function reads the pending register in the NVIC and returns the pending bit for the specified interrupt. \param [in] IRQn Interrupt number. \return 0 Interrupt status is not pending. \return 1 Interrupt status is pending. */ __STATIC_INLINE uint32_t NVIC_GetPendingIRQ(IRQn_Type IRQn) { return((uint32_t)(((NVIC->ISPR[(((uint32_t)(int32_t)IRQn) >> 5UL)] & (1UL << (((uint32_t)(int32_t)IRQn) & 0x1FUL))) != 0UL) ? 1UL : 0UL)); } /** \brief Set Pending Interrupt The function sets the pending bit of an external interrupt. \param [in] IRQn Interrupt number. Value cannot be negative. */ __STATIC_INLINE void NVIC_SetPendingIRQ(IRQn_Type IRQn) { NVIC->ISPR[(((uint32_t)(int32_t)IRQn) >> 5UL)] = (uint32_t)(1UL << (((uint32_t)(int32_t)IRQn) & 0x1FUL)); } /** \brief Clear Pending Interrupt The function clears the pending bit of an external interrupt. \param [in] IRQn External interrupt number. Value cannot be negative. */ __STATIC_INLINE void NVIC_ClearPendingIRQ(IRQn_Type IRQn) { NVIC->ICPR[(((uint32_t)(int32_t)IRQn) >> 5UL)] = (uint32_t)(1UL << (((uint32_t)(int32_t)IRQn) & 0x1FUL)); } /** \brief Get Active Interrupt The function reads the active register in NVIC and returns the active bit. \param [in] IRQn Interrupt number. \return 0 Interrupt status is not active. \return 1 Interrupt status is active. */ __STATIC_INLINE uint32_t NVIC_GetActive(IRQn_Type IRQn) { return((uint32_t)(((NVIC->IABR[(((uint32_t)(int32_t)IRQn) >> 5UL)] & (1UL << (((uint32_t)(int32_t)IRQn) & 0x1FUL))) != 0UL) ? 1UL : 0UL)); } /** \brief Set Interrupt Priority The function sets the priority of an interrupt. \note The priority cannot be set for every core interrupt. \param [in] IRQn Interrupt number. \param [in] priority Priority to set. */ __STATIC_INLINE void NVIC_SetPriority(IRQn_Type IRQn, uint32_t priority) { if((int32_t)IRQn < 0) { SCB->SHPR[(((uint32_t)(int32_t)IRQn) & 0xFUL)-4UL] = (uint8_t)((priority << (8 - __NVIC_PRIO_BITS)) & (uint32_t)0xFFUL); } else { NVIC->IP[((uint32_t)(int32_t)IRQn)] = (uint8_t)((priority << (8 - __NVIC_PRIO_BITS)) & (uint32_t)0xFFUL); } } /** \brief Get Interrupt Priority The function reads the priority of an interrupt. The interrupt number can be positive to specify an external (device specific) interrupt, or negative to specify an internal (core) interrupt. \param [in] IRQn Interrupt number. \return Interrupt Priority. Value is aligned automatically to the implemented priority bits of the microcontroller. */ __STATIC_INLINE uint32_t NVIC_GetPriority(IRQn_Type IRQn) { if((int32_t)IRQn < 0) { return(((uint32_t)SCB->SHPR[(((uint32_t)(int32_t)IRQn) & 0xFUL)-4UL] >> (8 - __NVIC_PRIO_BITS))); } else { return(((uint32_t)NVIC->IP[((uint32_t)(int32_t)IRQn)] >> (8 - __NVIC_PRIO_BITS))); } } /** \brief Encode Priority The function encodes the priority for an interrupt with the given priority group, preemptive priority value, and subpriority value. In case of a conflict between priority grouping and available priority bits (__NVIC_PRIO_BITS), the smallest possible priority group is set. \param [in] PriorityGroup Used priority group. \param [in] PreemptPriority Preemptive priority value (starting from 0). \param [in] SubPriority Subpriority value (starting from 0). \return Encoded priority. Value can be used in the function \ref NVIC_SetPriority(). */ __STATIC_INLINE uint32_t NVIC_EncodePriority (uint32_t PriorityGroup, uint32_t PreemptPriority, uint32_t SubPriority) { uint32_t PriorityGroupTmp = (PriorityGroup & (uint32_t)0x07UL); /* only values 0..7 are used */ uint32_t PreemptPriorityBits; uint32_t SubPriorityBits; PreemptPriorityBits = ((7UL - PriorityGroupTmp) > (uint32_t)(__NVIC_PRIO_BITS)) ? (uint32_t)(__NVIC_PRIO_BITS) : (uint32_t)(7UL - PriorityGroupTmp); SubPriorityBits = ((PriorityGroupTmp + (uint32_t)(__NVIC_PRIO_BITS)) < (uint32_t)7UL) ? (uint32_t)0UL : (uint32_t)((PriorityGroupTmp - 7UL) + (uint32_t)(__NVIC_PRIO_BITS)); return ( ((PreemptPriority & (uint32_t)((1UL << (PreemptPriorityBits)) - 1UL)) << SubPriorityBits) | ((SubPriority & (uint32_t)((1UL << (SubPriorityBits )) - 1UL))) ); } /** \brief Decode Priority The function decodes an interrupt priority value with a given priority group to preemptive priority value and subpriority value. In case of a conflict between priority grouping and available priority bits (__NVIC_PRIO_BITS) the smallest possible priority group is set. \param [in] Priority Priority value, which can be retrieved with the function \ref NVIC_GetPriority(). \param [in] PriorityGroup Used priority group. \param [out] pPreemptPriority Preemptive priority value (starting from 0). \param [out] pSubPriority Subpriority value (starting from 0). */ __STATIC_INLINE void NVIC_DecodePriority (uint32_t Priority, uint32_t PriorityGroup, uint32_t* pPreemptPriority, uint32_t* pSubPriority) { uint32_t PriorityGroupTmp = (PriorityGroup & (uint32_t)0x07UL); /* only values 0..7 are used */ uint32_t PreemptPriorityBits; uint32_t SubPriorityBits; PreemptPriorityBits = ((7UL - PriorityGroupTmp) > (uint32_t)(__NVIC_PRIO_BITS)) ? (uint32_t)(__NVIC_PRIO_BITS) : (uint32_t)(7UL - PriorityGroupTmp); SubPriorityBits = ((PriorityGroupTmp + (uint32_t)(__NVIC_PRIO_BITS)) < (uint32_t)7UL) ? (uint32_t)0UL : (uint32_t)((PriorityGroupTmp - 7UL) + (uint32_t)(__NVIC_PRIO_BITS)); *pPreemptPriority = (Priority >> SubPriorityBits) & (uint32_t)((1UL << (PreemptPriorityBits)) - 1UL); *pSubPriority = (Priority ) & (uint32_t)((1UL << (SubPriorityBits )) - 1UL); } /** \brief System Reset The function initiates a system reset request to reset the MCU. */ __STATIC_INLINE void NVIC_SystemReset(void) { __DSB(); /* Ensure all outstanding memory accesses included buffered write are completed before reset */ SCB->AIRCR = (uint32_t)((0x5FAUL << SCB_AIRCR_VECTKEY_Pos) | (SCB->AIRCR & SCB_AIRCR_PRIGROUP_Msk) | SCB_AIRCR_SYSRESETREQ_Msk ); /* Keep priority group unchanged */ __DSB(); /* Ensure completion of memory access */ while(1) { __NOP(); } /* wait until reset */ } /*@} end of CMSIS_Core_NVICFunctions */ /* ########################## FPU functions #################################### */ /** \ingroup CMSIS_Core_FunctionInterface \defgroup CMSIS_Core_FpuFunctions FPU Functions \brief Function that provides FPU type. @{ */ /** \fn uint32_t SCB_GetFPUType(void) \brief get FPU type \returns - \b 0: No FPU - \b 1: Single precision FPU - \b 2: Double + Single precision FPU */ __STATIC_INLINE uint32_t SCB_GetFPUType(void) { uint32_t mvfr0; mvfr0 = SCB->MVFR0; if ((mvfr0 & 0x00000FF0UL) == 0x220UL) { return 2UL; // Double + Single precision FPU } else if ((mvfr0 & 0x00000FF0UL) == 0x020UL) { return 1UL; // Single precision FPU } else { return 0UL; // No FPU } } /*@} end of CMSIS_Core_FpuFunctions */ /* ########################## Cache functions #################################### */ /** \ingroup CMSIS_Core_FunctionInterface \defgroup CMSIS_Core_CacheFunctions Cache Functions \brief Functions that configure Instruction and Data cache. @{ */ /* Cache Size ID Register Macros */ #define CCSIDR_WAYS(x) (((x) & SCB_CCSIDR_ASSOCIATIVITY_Msk) >> SCB_CCSIDR_ASSOCIATIVITY_Pos) #define CCSIDR_SETS(x) (((x) & SCB_CCSIDR_NUMSETS_Msk ) >> SCB_CCSIDR_NUMSETS_Pos ) #define CCSIDR_LSSHIFT(x) (((x) & SCB_CCSIDR_LINESIZE_Msk ) /*>> SCB_CCSIDR_LINESIZE_Pos*/ ) /** \brief Enable I-Cache The function turns on I-Cache */ __STATIC_INLINE void SCB_EnableICache (void) { #if (__ICACHE_PRESENT == 1) __DSB(); __ISB(); SCB->ICIALLU = 0UL; // invalidate I-Cache SCB->CCR |= (uint32_t)SCB_CCR_IC_Msk; // enable I-Cache __DSB(); __ISB(); #endif } /** \brief Disable I-Cache The function turns off I-Cache */ __STATIC_INLINE void SCB_DisableICache (void) { #if (__ICACHE_PRESENT == 1) __DSB(); __ISB(); SCB->CCR &= ~(uint32_t)SCB_CCR_IC_Msk; // disable I-Cache SCB->ICIALLU = 0UL; // invalidate I-Cache __DSB(); __ISB(); #endif } /** \brief Invalidate I-Cache The function invalidates I-Cache */ __STATIC_INLINE void SCB_InvalidateICache (void) { #if (__ICACHE_PRESENT == 1) __DSB(); __ISB(); SCB->ICIALLU = 0UL; __DSB(); __ISB(); #endif } /** \brief Enable D-Cache The function turns on D-Cache */ __STATIC_INLINE void SCB_EnableDCache (void) { #if (__DCACHE_PRESENT == 1) uint32_t ccsidr, sshift, wshift, sw; uint32_t sets, ways; SCB->CSSELR = (0UL << 1) | 0UL; // Level 1 data cache ccsidr = SCB->CCSIDR; sets = (uint32_t)(CCSIDR_SETS(ccsidr)); sshift = (uint32_t)(CCSIDR_LSSHIFT(ccsidr) + 4UL); ways = (uint32_t)(CCSIDR_WAYS(ccsidr)); wshift = (uint32_t)((uint32_t)__CLZ(ways) & 0x1FUL); __DSB(); do { // invalidate D-Cache uint32_t tmpways = ways; do { sw = ((tmpways << wshift) | (sets << sshift)); SCB->DCISW = sw; } while(tmpways--); } while(sets--); __DSB(); SCB->CCR |= (uint32_t)SCB_CCR_DC_Msk; // enable D-Cache __DSB(); __ISB(); #endif } /** \brief Disable D-Cache The function turns off D-Cache */ __STATIC_INLINE void SCB_DisableDCache (void) { #if (__DCACHE_PRESENT == 1) uint32_t ccsidr, sshift, wshift, sw; uint32_t sets, ways; SCB->CSSELR = (0UL << 1) | 0UL; // Level 1 data cache ccsidr = SCB->CCSIDR; sets = (uint32_t)(CCSIDR_SETS(ccsidr)); sshift = (uint32_t)(CCSIDR_LSSHIFT(ccsidr) + 4UL); ways = (uint32_t)(CCSIDR_WAYS(ccsidr)); wshift = (uint32_t)((uint32_t)__CLZ(ways) & 0x1FUL); __DSB(); SCB->CCR &= ~(uint32_t)SCB_CCR_DC_Msk; // disable D-Cache do { // clean & invalidate D-Cache uint32_t tmpways = ways; do { sw = ((tmpways << wshift) | (sets << sshift)); SCB->DCCISW = sw; } while(tmpways--); } while(sets--); __DSB(); __ISB(); #endif } /** \brief Invalidate D-Cache The function invalidates D-Cache */ __STATIC_INLINE void SCB_InvalidateDCache (void) { #if (__DCACHE_PRESENT == 1) uint32_t ccsidr, sshift, wshift, sw; uint32_t sets, ways; SCB->CSSELR = (0UL << 1) | 0UL; // Level 1 data cache ccsidr = SCB->CCSIDR; sets = (uint32_t)(CCSIDR_SETS(ccsidr)); sshift = (uint32_t)(CCSIDR_LSSHIFT(ccsidr) + 4UL); ways = (uint32_t)(CCSIDR_WAYS(ccsidr)); wshift = (uint32_t)((uint32_t)__CLZ(ways) & 0x1FUL); __DSB(); do { // invalidate D-Cache uint32_t tmpways = ways; do { sw = ((tmpways << wshift) | (sets << sshift)); SCB->DCISW = sw; } while(tmpways--); } while(sets--); __DSB(); __ISB(); #endif } /** \brief Clean D-Cache The function cleans D-Cache */ __STATIC_INLINE void SCB_CleanDCache (void) { #if (__DCACHE_PRESENT == 1) uint32_t ccsidr, sshift, wshift, sw; uint32_t sets, ways; SCB->CSSELR = (0UL << 1) | 0UL; // Level 1 data cache ccsidr = SCB->CCSIDR; sets = (uint32_t)(CCSIDR_SETS(ccsidr)); sshift = (uint32_t)(CCSIDR_LSSHIFT(ccsidr) + 4UL); ways = (uint32_t)(CCSIDR_WAYS(ccsidr)); wshift = (uint32_t)((uint32_t)__CLZ(ways) & 0x1FUL); __DSB(); do { // clean D-Cache uint32_t tmpways = ways; do { sw = ((tmpways << wshift) | (sets << sshift)); SCB->DCCSW = sw; } while(tmpways--); } while(sets--); __DSB(); __ISB(); #endif } /** \brief Clean & Invalidate D-Cache The function cleans and Invalidates D-Cache */ __STATIC_INLINE void SCB_CleanInvalidateDCache (void) { #if (__DCACHE_PRESENT == 1) uint32_t ccsidr, sshift, wshift, sw; uint32_t sets, ways; SCB->CSSELR = (0UL << 1) | 0UL; // Level 1 data cache ccsidr = SCB->CCSIDR; sets = (uint32_t)(CCSIDR_SETS(ccsidr)); sshift = (uint32_t)(CCSIDR_LSSHIFT(ccsidr) + 4UL); ways = (uint32_t)(CCSIDR_WAYS(ccsidr)); wshift = (uint32_t)((uint32_t)__CLZ(ways) & 0x1FUL); __DSB(); do { // clean & invalidate D-Cache uint32_t tmpways = ways; do { sw = ((tmpways << wshift) | (sets << sshift)); SCB->DCCISW = sw; } while(tmpways--); } while(sets--); __DSB(); __ISB(); #endif } /** \fn void SCB_InvalidateDCache_by_Addr(volatile uint32_t *addr, int32_t dsize) \brief D-Cache Invalidate by address \param[in] addr address (aligned to 32-byte boundary) \param[in] dsize size of memory block (in number of bytes) */ __STATIC_INLINE void SCB_InvalidateDCache_by_Addr (uint32_t *addr, int32_t dsize) { #if (__DCACHE_PRESENT == 1) int32_t op_size = dsize; uint32_t op_addr = (uint32_t)addr; uint32_t linesize = 32UL; // in Cortex-M7 size of cache line is fixed to 8 words (32 bytes) __DSB(); while (op_size > 0) { SCB->DCIMVAC = op_addr; op_addr += linesize; op_size -= (int32_t)linesize; } __DSB(); __ISB(); #endif } /** \fn void SCB_CleanDCache_by_Addr(volatile uint32_t *addr, int32_t dsize) \brief D-Cache Clean by address \param[in] addr address (aligned to 32-byte boundary) \param[in] dsize size of memory block (in number of bytes) */ __STATIC_INLINE void SCB_CleanDCache_by_Addr (uint32_t *addr, int32_t dsize) { #if (__DCACHE_PRESENT == 1) int32_t op_size = dsize; uint32_t op_addr = (uint32_t) addr; uint32_t linesize = 32UL; // in Cortex-M7 size of cache line is fixed to 8 words (32 bytes) __DSB(); while (op_size > 0) { SCB->DCCMVAC = op_addr; op_addr += linesize; op_size -= (int32_t)linesize; } __DSB(); __ISB(); #endif } /** \fn void SCB_CleanInvalidateDCache_by_Addr(volatile uint32_t *addr, int32_t dsize) \brief D-Cache Clean and Invalidate by address \param[in] addr address (aligned to 32-byte boundary) \param[in] dsize size of memory block (in number of bytes) */ __STATIC_INLINE void SCB_CleanInvalidateDCache_by_Addr (uint32_t *addr, int32_t dsize) { #if (__DCACHE_PRESENT == 1) int32_t op_size = dsize; uint32_t op_addr = (uint32_t) addr; uint32_t linesize = 32UL; // in Cortex-M7 size of cache line is fixed to 8 words (32 bytes) __DSB(); while (op_size > 0) { SCB->DCCIMVAC = op_addr; op_addr += linesize; op_size -= (int32_t)linesize; } __DSB(); __ISB(); #endif } /*@} end of CMSIS_Core_CacheFunctions */ /* ################################## SysTick function ############################################ */ /** \ingroup CMSIS_Core_FunctionInterface \defgroup CMSIS_Core_SysTickFunctions SysTick Functions \brief Functions that configure the System. @{ */ #if (__Vendor_SysTickConfig == 0) /** \brief System Tick Configuration The function initializes the System Timer and its interrupt, and starts the System Tick Timer. Counter is in free running mode to generate periodic interrupts. \param [in] ticks Number of ticks between two interrupts. \return 0 Function succeeded. \return 1 Function failed. \note When the variable __Vendor_SysTickConfig is set to 1, then the function SysTick_Config is not included. In this case, the file device.h must contain a vendor-specific implementation of this function. */ __STATIC_INLINE uint32_t SysTick_Config(uint32_t ticks) { if ((ticks - 1UL) > SysTick_LOAD_RELOAD_Msk) { return (1UL); } /* Reload value impossible */ SysTick->LOAD = (uint32_t)(ticks - 1UL); /* set reload register */ NVIC_SetPriority (SysTick_IRQn, (1UL << __NVIC_PRIO_BITS) - 1UL); /* set Priority for Systick Interrupt */ SysTick->VAL = 0UL; /* Load the SysTick Counter Value */ SysTick->CTRL = SysTick_CTRL_CLKSOURCE_Msk | SysTick_CTRL_TICKINT_Msk | SysTick_CTRL_ENABLE_Msk; /* Enable SysTick IRQ and SysTick Timer */ return (0UL); /* Function successful */ } #endif /*@} end of CMSIS_Core_SysTickFunctions */ /* ##################################### Debug In/Output function ########################################### */ /** \ingroup CMSIS_Core_FunctionInterface \defgroup CMSIS_core_DebugFunctions ITM Functions \brief Functions that access the ITM debug interface. @{ */ extern volatile int32_t ITM_RxBuffer; /*!< External variable to receive characters. */ #define ITM_RXBUFFER_EMPTY 0x5AA55AA5 /*!< Value identifying \ref ITM_RxBuffer is ready for next character. */ /** \brief ITM Send Character The function transmits a character via the ITM channel 0, and \li Just returns when no debugger is connected that has booked the output. \li Is blocking when a debugger is connected, but the previous character sent has not been transmitted. \param [in] ch Character to transmit. \returns Character to transmit. */ __STATIC_INLINE uint32_t ITM_SendChar (uint32_t ch) { if (((ITM->TCR & ITM_TCR_ITMENA_Msk) != 0UL) && /* ITM enabled */ ((ITM->TER & 1UL ) != 0UL) ) /* ITM Port #0 enabled */ { while (ITM->PORT[0].u32 == 0UL) { __NOP(); } ITM->PORT[0].u8 = (uint8_t)ch; } return (ch); } /** \brief ITM Receive Character The function inputs a character via the external variable \ref ITM_RxBuffer. \return Received character. \return -1 No character pending. */ __STATIC_INLINE int32_t ITM_ReceiveChar (void) { int32_t ch = -1; /* no character available */ if (ITM_RxBuffer != ITM_RXBUFFER_EMPTY) { ch = ITM_RxBuffer; ITM_RxBuffer = ITM_RXBUFFER_EMPTY; /* ready for next character */ } return (ch); } /** \brief ITM Check Character The function checks whether a character is pending for reading in the variable \ref ITM_RxBuffer. \return 0 No character available. \return 1 Character available. */ __STATIC_INLINE int32_t ITM_CheckChar (void) { if (ITM_RxBuffer == ITM_RXBUFFER_EMPTY) { return (0); /* no character available */ } else { return (1); /* character available */ } } /*@} end of CMSIS_core_DebugFunctions */ #ifdef __cplusplus } #endif #endif /* __CORE_CM7_H_DEPENDANT */ #endif /* __CMSIS_GENERIC */ ================================================ FILE: Zelig/mbed/TARGET_NUCLEO_L152RE/core_cmFunc.h ================================================ /**************************************************************************//** * @file core_cmFunc.h * @brief CMSIS Cortex-M Core Function Access Header File * @version V3.20 * @date 25. February 2013 * * @note * ******************************************************************************/ /* Copyright (c) 2009 - 2013 ARM LIMITED All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: - Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. - Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. - Neither the name of ARM 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 COPYRIGHT HOLDERS AND 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. ---------------------------------------------------------------------------*/ #ifndef __CORE_CMFUNC_H #define __CORE_CMFUNC_H /* ########################### Core Function Access ########################### */ /** \ingroup CMSIS_Core_FunctionInterface \defgroup CMSIS_Core_RegAccFunctions CMSIS Core Register Access Functions @{ */ #if defined ( __CC_ARM ) /*------------------RealView Compiler -----------------*/ /* ARM armcc specific functions */ #if (__ARMCC_VERSION < 400677) #error "Please use ARM Compiler Toolchain V4.0.677 or later!" #endif /* intrinsic void __enable_irq(); */ /* intrinsic void __disable_irq(); */ /** \brief Get Control Register This function returns the content of the Control Register. \return Control Register value */ __STATIC_INLINE uint32_t __get_CONTROL(void) { register uint32_t __regControl __ASM("control"); return(__regControl); } /** \brief Set Control Register This function writes the given value to the Control Register. \param [in] control Control Register value to set */ __STATIC_INLINE void __set_CONTROL(uint32_t control) { register uint32_t __regControl __ASM("control"); __regControl = control; } /** \brief Get IPSR Register This function returns the content of the IPSR Register. \return IPSR Register value */ __STATIC_INLINE uint32_t __get_IPSR(void) { register uint32_t __regIPSR __ASM("ipsr"); return(__regIPSR); } /** \brief Get APSR Register This function returns the content of the APSR Register. \return APSR Register value */ __STATIC_INLINE uint32_t __get_APSR(void) { register uint32_t __regAPSR __ASM("apsr"); return(__regAPSR); } /** \brief Get xPSR Register This function returns the content of the xPSR Register. \return xPSR Register value */ __STATIC_INLINE uint32_t __get_xPSR(void) { register uint32_t __regXPSR __ASM("xpsr"); return(__regXPSR); } /** \brief Get Process Stack Pointer This function returns the current value of the Process Stack Pointer (PSP). \return PSP Register value */ __STATIC_INLINE uint32_t __get_PSP(void) { register uint32_t __regProcessStackPointer __ASM("psp"); return(__regProcessStackPointer); } /** \brief Set Process Stack Pointer This function assigns the given value to the Process Stack Pointer (PSP). \param [in] topOfProcStack Process Stack Pointer value to set */ __STATIC_INLINE void __set_PSP(uint32_t topOfProcStack) { register uint32_t __regProcessStackPointer __ASM("psp"); __regProcessStackPointer = topOfProcStack; } /** \brief Get Main Stack Pointer This function returns the current value of the Main Stack Pointer (MSP). \return MSP Register value */ __STATIC_INLINE uint32_t __get_MSP(void) { register uint32_t __regMainStackPointer __ASM("msp"); return(__regMainStackPointer); } /** \brief Set Main Stack Pointer This function assigns the given value to the Main Stack Pointer (MSP). \param [in] topOfMainStack Main Stack Pointer value to set */ __STATIC_INLINE void __set_MSP(uint32_t topOfMainStack) { register uint32_t __regMainStackPointer __ASM("msp"); __regMainStackPointer = topOfMainStack; } /** \brief Get Priority Mask This function returns the current state of the priority mask bit from the Priority Mask Register. \return Priority Mask value */ __STATIC_INLINE uint32_t __get_PRIMASK(void) { register uint32_t __regPriMask __ASM("primask"); return(__regPriMask); } /** \brief Set Priority Mask This function assigns the given value to the Priority Mask Register. \param [in] priMask Priority Mask */ __STATIC_INLINE void __set_PRIMASK(uint32_t priMask) { register uint32_t __regPriMask __ASM("primask"); __regPriMask = (priMask); } #if (__CORTEX_M >= 0x03) /** \brief Enable FIQ This function enables FIQ interrupts by clearing the F-bit in the CPSR. Can only be executed in Privileged modes. */ #define __enable_fault_irq __enable_fiq /** \brief Disable FIQ This function disables FIQ interrupts by setting the F-bit in the CPSR. Can only be executed in Privileged modes. */ #define __disable_fault_irq __disable_fiq /** \brief Get Base Priority This function returns the current value of the Base Priority register. \return Base Priority register value */ __STATIC_INLINE uint32_t __get_BASEPRI(void) { register uint32_t __regBasePri __ASM("basepri"); return(__regBasePri); } /** \brief Set Base Priority This function assigns the given value to the Base Priority register. \param [in] basePri Base Priority value to set */ __STATIC_INLINE void __set_BASEPRI(uint32_t basePri) { register uint32_t __regBasePri __ASM("basepri"); __regBasePri = (basePri & 0xff); } /** \brief Get Fault Mask This function returns the current value of the Fault Mask register. \return Fault Mask register value */ __STATIC_INLINE uint32_t __get_FAULTMASK(void) { register uint32_t __regFaultMask __ASM("faultmask"); return(__regFaultMask); } /** \brief Set Fault Mask This function assigns the given value to the Fault Mask register. \param [in] faultMask Fault Mask value to set */ __STATIC_INLINE void __set_FAULTMASK(uint32_t faultMask) { register uint32_t __regFaultMask __ASM("faultmask"); __regFaultMask = (faultMask & (uint32_t)1); } #endif /* (__CORTEX_M >= 0x03) */ #if (__CORTEX_M == 0x04) /** \brief Get FPSCR This function returns the current value of the Floating Point Status/Control register. \return Floating Point Status/Control register value */ __STATIC_INLINE uint32_t __get_FPSCR(void) { #if (__FPU_PRESENT == 1) && (__FPU_USED == 1) register uint32_t __regfpscr __ASM("fpscr"); return(__regfpscr); #else return(0); #endif } /** \brief Set FPSCR This function assigns the given value to the Floating Point Status/Control register. \param [in] fpscr Floating Point Status/Control value to set */ __STATIC_INLINE void __set_FPSCR(uint32_t fpscr) { #if (__FPU_PRESENT == 1) && (__FPU_USED == 1) register uint32_t __regfpscr __ASM("fpscr"); __regfpscr = (fpscr); #endif } #endif /* (__CORTEX_M == 0x04) */ #elif defined ( __ICCARM__ ) /*------------------ ICC Compiler -------------------*/ /* IAR iccarm specific functions */ #include #elif defined ( __TMS470__ ) /*---------------- TI CCS Compiler ------------------*/ /* TI CCS specific functions */ #include #elif defined ( __GNUC__ ) /*------------------ GNU Compiler ---------------------*/ /* GNU gcc specific functions */ /** \brief Enable IRQ Interrupts This function enables IRQ interrupts by clearing the I-bit in the CPSR. Can only be executed in Privileged modes. */ __attribute__( ( always_inline ) ) __STATIC_INLINE void __enable_irq(void) { __ASM volatile ("cpsie i" : : : "memory"); } /** \brief Disable IRQ Interrupts This function disables IRQ interrupts by setting the I-bit in the CPSR. Can only be executed in Privileged modes. */ __attribute__( ( always_inline ) ) __STATIC_INLINE void __disable_irq(void) { __ASM volatile ("cpsid i" : : : "memory"); } /** \brief Get Control Register This function returns the content of the Control Register. \return Control Register value */ __attribute__( ( always_inline ) ) __STATIC_INLINE uint32_t __get_CONTROL(void) { uint32_t result; __ASM volatile ("MRS %0, control" : "=r" (result) ); return(result); } /** \brief Set Control Register This function writes the given value to the Control Register. \param [in] control Control Register value to set */ __attribute__( ( always_inline ) ) __STATIC_INLINE void __set_CONTROL(uint32_t control) { __ASM volatile ("MSR control, %0" : : "r" (control) : "memory"); } /** \brief Get IPSR Register This function returns the content of the IPSR Register. \return IPSR Register value */ __attribute__( ( always_inline ) ) __STATIC_INLINE uint32_t __get_IPSR(void) { uint32_t result; __ASM volatile ("MRS %0, ipsr" : "=r" (result) ); return(result); } /** \brief Get APSR Register This function returns the content of the APSR Register. \return APSR Register value */ __attribute__( ( always_inline ) ) __STATIC_INLINE uint32_t __get_APSR(void) { uint32_t result; __ASM volatile ("MRS %0, apsr" : "=r" (result) ); return(result); } /** \brief Get xPSR Register This function returns the content of the xPSR Register. \return xPSR Register value */ __attribute__( ( always_inline ) ) __STATIC_INLINE uint32_t __get_xPSR(void) { uint32_t result; __ASM volatile ("MRS %0, xpsr" : "=r" (result) ); return(result); } /** \brief Get Process Stack Pointer This function returns the current value of the Process Stack Pointer (PSP). \return PSP Register value */ __attribute__( ( always_inline ) ) __STATIC_INLINE uint32_t __get_PSP(void) { register uint32_t result; __ASM volatile ("MRS %0, psp\n" : "=r" (result) ); return(result); } /** \brief Set Process Stack Pointer This function assigns the given value to the Process Stack Pointer (PSP). \param [in] topOfProcStack Process Stack Pointer value to set */ __attribute__( ( always_inline ) ) __STATIC_INLINE void __set_PSP(uint32_t topOfProcStack) { __ASM volatile ("MSR psp, %0\n" : : "r" (topOfProcStack) : "sp"); } /** \brief Get Main Stack Pointer This function returns the current value of the Main Stack Pointer (MSP). \return MSP Register value */ __attribute__( ( always_inline ) ) __STATIC_INLINE uint32_t __get_MSP(void) { register uint32_t result; __ASM volatile ("MRS %0, msp\n" : "=r" (result) ); return(result); } /** \brief Set Main Stack Pointer This function assigns the given value to the Main Stack Pointer (MSP). \param [in] topOfMainStack Main Stack Pointer value to set */ __attribute__( ( always_inline ) ) __STATIC_INLINE void __set_MSP(uint32_t topOfMainStack) { __ASM volatile ("MSR msp, %0\n" : : "r" (topOfMainStack) : "sp"); } /** \brief Get Priority Mask This function returns the current state of the priority mask bit from the Priority Mask Register. \return Priority Mask value */ __attribute__( ( always_inline ) ) __STATIC_INLINE uint32_t __get_PRIMASK(void) { uint32_t result; __ASM volatile ("MRS %0, primask" : "=r" (result) ); return(result); } /** \brief Set Priority Mask This function assigns the given value to the Priority Mask Register. \param [in] priMask Priority Mask */ __attribute__( ( always_inline ) ) __STATIC_INLINE void __set_PRIMASK(uint32_t priMask) { __ASM volatile ("MSR primask, %0" : : "r" (priMask) : "memory"); } #if (__CORTEX_M >= 0x03) /** \brief Enable FIQ This function enables FIQ interrupts by clearing the F-bit in the CPSR. Can only be executed in Privileged modes. */ __attribute__( ( always_inline ) ) __STATIC_INLINE void __enable_fault_irq(void) { __ASM volatile ("cpsie f" : : : "memory"); } /** \brief Disable FIQ This function disables FIQ interrupts by setting the F-bit in the CPSR. Can only be executed in Privileged modes. */ __attribute__( ( always_inline ) ) __STATIC_INLINE void __disable_fault_irq(void) { __ASM volatile ("cpsid f" : : : "memory"); } /** \brief Get Base Priority This function returns the current value of the Base Priority register. \return Base Priority register value */ __attribute__( ( always_inline ) ) __STATIC_INLINE uint32_t __get_BASEPRI(void) { uint32_t result; __ASM volatile ("MRS %0, basepri_max" : "=r" (result) ); return(result); } /** \brief Set Base Priority This function assigns the given value to the Base Priority register. \param [in] basePri Base Priority value to set */ __attribute__( ( always_inline ) ) __STATIC_INLINE void __set_BASEPRI(uint32_t value) { __ASM volatile ("MSR basepri, %0" : : "r" (value) : "memory"); } /** \brief Get Fault Mask This function returns the current value of the Fault Mask register. \return Fault Mask register value */ __attribute__( ( always_inline ) ) __STATIC_INLINE uint32_t __get_FAULTMASK(void) { uint32_t result; __ASM volatile ("MRS %0, faultmask" : "=r" (result) ); return(result); } /** \brief Set Fault Mask This function assigns the given value to the Fault Mask register. \param [in] faultMask Fault Mask value to set */ __attribute__( ( always_inline ) ) __STATIC_INLINE void __set_FAULTMASK(uint32_t faultMask) { __ASM volatile ("MSR faultmask, %0" : : "r" (faultMask) : "memory"); } #endif /* (__CORTEX_M >= 0x03) */ #if (__CORTEX_M == 0x04) /** \brief Get FPSCR This function returns the current value of the Floating Point Status/Control register. \return Floating Point Status/Control register value */ __attribute__( ( always_inline ) ) __STATIC_INLINE uint32_t __get_FPSCR(void) { #if (__FPU_PRESENT == 1) && (__FPU_USED == 1) uint32_t result; /* Empty asm statement works as a scheduling barrier */ __ASM volatile (""); __ASM volatile ("VMRS %0, fpscr" : "=r" (result) ); __ASM volatile (""); return(result); #else return(0); #endif } /** \brief Set FPSCR This function assigns the given value to the Floating Point Status/Control register. \param [in] fpscr Floating Point Status/Control value to set */ __attribute__( ( always_inline ) ) __STATIC_INLINE void __set_FPSCR(uint32_t fpscr) { #if (__FPU_PRESENT == 1) && (__FPU_USED == 1) /* Empty asm statement works as a scheduling barrier */ __ASM volatile (""); __ASM volatile ("VMSR fpscr, %0" : : "r" (fpscr) : "vfpcc"); __ASM volatile (""); #endif } #endif /* (__CORTEX_M == 0x04) */ #elif defined ( __TASKING__ ) /*------------------ TASKING Compiler --------------*/ /* TASKING carm specific functions */ /* * The CMSIS functions have been implemented as intrinsics in the compiler. * Please use "carm -?i" to get an up to date list of all instrinsics, * Including the CMSIS ones. */ #endif /*@} end of CMSIS_Core_RegAccFunctions */ #endif /* __CORE_CMFUNC_H */ ================================================ FILE: Zelig/mbed/TARGET_NUCLEO_L152RE/core_cmInstr.h ================================================ /**************************************************************************//** * @file core_cmInstr.h * @brief CMSIS Cortex-M Core Instruction Access Header File * @version V3.20 * @date 05. March 2013 * * @note * ******************************************************************************/ /* Copyright (c) 2009 - 2013 ARM LIMITED All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: - Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. - Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. - Neither the name of ARM 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 COPYRIGHT HOLDERS AND 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. ---------------------------------------------------------------------------*/ #ifndef __CORE_CMINSTR_H #define __CORE_CMINSTR_H /* ########################## Core Instruction Access ######################### */ /** \defgroup CMSIS_Core_InstructionInterface CMSIS Core Instruction Interface Access to dedicated instructions @{ */ #if defined ( __CC_ARM ) /*------------------RealView Compiler -----------------*/ /* ARM armcc specific functions */ #if (__ARMCC_VERSION < 400677) #error "Please use ARM Compiler Toolchain V4.0.677 or later!" #endif /** \brief No Operation No Operation does nothing. This instruction can be used for code alignment purposes. */ #define __NOP __nop /** \brief Wait For Interrupt Wait For Interrupt is a hint instruction that suspends execution until one of a number of events occurs. */ #define __WFI __wfi /** \brief Wait For Event Wait For Event is a hint instruction that permits the processor to enter a low-power state until one of a number of events occurs. */ #define __WFE __wfe /** \brief Send Event Send Event is a hint instruction. It causes an event to be signaled to the CPU. */ #define __SEV __sev /** \brief Instruction Synchronization Barrier Instruction Synchronization Barrier flushes the pipeline in the processor, so that all instructions following the ISB are fetched from cache or memory, after the instruction has been completed. */ #define __ISB() __isb(0xF) /** \brief Data Synchronization Barrier This function acts as a special kind of Data Memory Barrier. It completes when all explicit memory accesses before this instruction complete. */ #define __DSB() __dsb(0xF) /** \brief Data Memory Barrier This function ensures the apparent order of the explicit memory operations before and after the instruction, without ensuring their completion. */ #define __DMB() __dmb(0xF) /** \brief Reverse byte order (32 bit) This function reverses the byte order in integer value. \param [in] value Value to reverse \return Reversed value */ #define __REV __rev /** \brief Reverse byte order (16 bit) This function reverses the byte order in two unsigned short values. \param [in] value Value to reverse \return Reversed value */ #ifndef __NO_EMBEDDED_ASM __attribute__((section(".rev16_text"))) __STATIC_INLINE __ASM uint32_t __REV16(uint32_t value) { rev16 r0, r0 bx lr } #endif /** \brief Reverse byte order in signed short value This function reverses the byte order in a signed short value with sign extension to integer. \param [in] value Value to reverse \return Reversed value */ #ifndef __NO_EMBEDDED_ASM __attribute__((section(".revsh_text"))) __STATIC_INLINE __ASM int32_t __REVSH(int32_t value) { revsh r0, r0 bx lr } #endif /** \brief Rotate Right in unsigned value (32 bit) This function Rotate Right (immediate) provides the value of the contents of a register rotated by a variable number of bits. \param [in] value Value to rotate \param [in] value Number of Bits to rotate \return Rotated value */ #define __ROR __ror /** \brief Breakpoint This function causes the processor to enter Debug state. Debug tools can use this to investigate system state when the instruction at a particular address is reached. \param [in] value is ignored by the processor. If required, a debugger can use it to store additional information about the breakpoint. */ #define __BKPT(value) __breakpoint(value) #if (__CORTEX_M >= 0x03) /** \brief Reverse bit order of value This function reverses the bit order of the given value. \param [in] value Value to reverse \return Reversed value */ #define __RBIT __rbit /** \brief LDR Exclusive (8 bit) This function performs a exclusive LDR command for 8 bit value. \param [in] ptr Pointer to data \return value of type uint8_t at (*ptr) */ #define __LDREXB(ptr) ((uint8_t ) __ldrex(ptr)) /** \brief LDR Exclusive (16 bit) This function performs a exclusive LDR command for 16 bit values. \param [in] ptr Pointer to data \return value of type uint16_t at (*ptr) */ #define __LDREXH(ptr) ((uint16_t) __ldrex(ptr)) /** \brief LDR Exclusive (32 bit) This function performs a exclusive LDR command for 32 bit values. \param [in] ptr Pointer to data \return value of type uint32_t at (*ptr) */ #define __LDREXW(ptr) ((uint32_t ) __ldrex(ptr)) /** \brief STR Exclusive (8 bit) This function performs a exclusive STR command for 8 bit values. \param [in] value Value to store \param [in] ptr Pointer to location \return 0 Function succeeded \return 1 Function failed */ #define __STREXB(value, ptr) __strex(value, ptr) /** \brief STR Exclusive (16 bit) This function performs a exclusive STR command for 16 bit values. \param [in] value Value to store \param [in] ptr Pointer to location \return 0 Function succeeded \return 1 Function failed */ #define __STREXH(value, ptr) __strex(value, ptr) /** \brief STR Exclusive (32 bit) This function performs a exclusive STR command for 32 bit values. \param [in] value Value to store \param [in] ptr Pointer to location \return 0 Function succeeded \return 1 Function failed */ #define __STREXW(value, ptr) __strex(value, ptr) /** \brief Remove the exclusive lock This function removes the exclusive lock which is created by LDREX. */ #define __CLREX __clrex /** \brief Signed Saturate This function saturates a signed value. \param [in] value Value to be saturated \param [in] sat Bit position to saturate to (1..32) \return Saturated value */ #define __SSAT __ssat /** \brief Unsigned Saturate This function saturates an unsigned value. \param [in] value Value to be saturated \param [in] sat Bit position to saturate to (0..31) \return Saturated value */ #define __USAT __usat /** \brief Count leading zeros This function counts the number of leading zeros of a data value. \param [in] value Value to count the leading zeros \return number of leading zeros in value */ #define __CLZ __clz #endif /* (__CORTEX_M >= 0x03) */ #elif defined ( __ICCARM__ ) /*------------------ ICC Compiler -------------------*/ /* IAR iccarm specific functions */ #include #elif defined ( __TMS470__ ) /*---------------- TI CCS Compiler ------------------*/ /* TI CCS specific functions */ #include #elif defined ( __GNUC__ ) /*------------------ GNU Compiler ---------------------*/ /* GNU gcc specific functions */ /* Define macros for porting to both thumb1 and thumb2. * For thumb1, use low register (r0-r7), specified by constrant "l" * Otherwise, use general registers, specified by constrant "r" */ #if defined (__thumb__) && !defined (__thumb2__) #define __CMSIS_GCC_OUT_REG(r) "=l" (r) #define __CMSIS_GCC_USE_REG(r) "l" (r) #else #define __CMSIS_GCC_OUT_REG(r) "=r" (r) #define __CMSIS_GCC_USE_REG(r) "r" (r) #endif /** \brief No Operation No Operation does nothing. This instruction can be used for code alignment purposes. */ __attribute__( ( always_inline ) ) __STATIC_INLINE void __NOP(void) { __ASM volatile ("nop"); } /** \brief Wait For Interrupt Wait For Interrupt is a hint instruction that suspends execution until one of a number of events occurs. */ __attribute__( ( always_inline ) ) __STATIC_INLINE void __WFI(void) { __ASM volatile ("wfi"); } /** \brief Wait For Event Wait For Event is a hint instruction that permits the processor to enter a low-power state until one of a number of events occurs. */ __attribute__( ( always_inline ) ) __STATIC_INLINE void __WFE(void) { __ASM volatile ("wfe"); } /** \brief Send Event Send Event is a hint instruction. It causes an event to be signaled to the CPU. */ __attribute__( ( always_inline ) ) __STATIC_INLINE void __SEV(void) { __ASM volatile ("sev"); } /** \brief Instruction Synchronization Barrier Instruction Synchronization Barrier flushes the pipeline in the processor, so that all instructions following the ISB are fetched from cache or memory, after the instruction has been completed. */ __attribute__( ( always_inline ) ) __STATIC_INLINE void __ISB(void) { __ASM volatile ("isb"); } /** \brief Data Synchronization Barrier This function acts as a special kind of Data Memory Barrier. It completes when all explicit memory accesses before this instruction complete. */ __attribute__( ( always_inline ) ) __STATIC_INLINE void __DSB(void) { __ASM volatile ("dsb"); } /** \brief Data Memory Barrier This function ensures the apparent order of the explicit memory operations before and after the instruction, without ensuring their completion. */ __attribute__( ( always_inline ) ) __STATIC_INLINE void __DMB(void) { __ASM volatile ("dmb"); } /** \brief Reverse byte order (32 bit) This function reverses the byte order in integer value. \param [in] value Value to reverse \return Reversed value */ __attribute__( ( always_inline ) ) __STATIC_INLINE uint32_t __REV(uint32_t value) { #if (__GNUC__ > 4) || (__GNUC__ == 4 && __GNUC_MINOR__ >= 5) return __builtin_bswap32(value); #else uint32_t result; __ASM volatile ("rev %0, %1" : __CMSIS_GCC_OUT_REG (result) : __CMSIS_GCC_USE_REG (value) ); return(result); #endif } /** \brief Reverse byte order (16 bit) This function reverses the byte order in two unsigned short values. \param [in] value Value to reverse \return Reversed value */ __attribute__( ( always_inline ) ) __STATIC_INLINE uint32_t __REV16(uint32_t value) { uint32_t result; __ASM volatile ("rev16 %0, %1" : __CMSIS_GCC_OUT_REG (result) : __CMSIS_GCC_USE_REG (value) ); return(result); } /** \brief Reverse byte order in signed short value This function reverses the byte order in a signed short value with sign extension to integer. \param [in] value Value to reverse \return Reversed value */ __attribute__( ( always_inline ) ) __STATIC_INLINE int32_t __REVSH(int32_t value) { #if (__GNUC__ > 4) || (__GNUC__ == 4 && __GNUC_MINOR__ >= 8) return (short)__builtin_bswap16(value); #else uint32_t result; __ASM volatile ("revsh %0, %1" : __CMSIS_GCC_OUT_REG (result) : __CMSIS_GCC_USE_REG (value) ); return(result); #endif } /** \brief Rotate Right in unsigned value (32 bit) This function Rotate Right (immediate) provides the value of the contents of a register rotated by a variable number of bits. \param [in] value Value to rotate \param [in] value Number of Bits to rotate \return Rotated value */ __attribute__( ( always_inline ) ) __STATIC_INLINE uint32_t __ROR(uint32_t op1, uint32_t op2) { return (op1 >> op2) | (op1 << (32 - op2)); } /** \brief Breakpoint This function causes the processor to enter Debug state. Debug tools can use this to investigate system state when the instruction at a particular address is reached. \param [in] value is ignored by the processor. If required, a debugger can use it to store additional information about the breakpoint. */ #define __BKPT(value) __ASM volatile ("bkpt "#value) #if (__CORTEX_M >= 0x03) /** \brief Reverse bit order of value This function reverses the bit order of the given value. \param [in] value Value to reverse \return Reversed value */ __attribute__( ( always_inline ) ) __STATIC_INLINE uint32_t __RBIT(uint32_t value) { uint32_t result; __ASM volatile ("rbit %0, %1" : "=r" (result) : "r" (value) ); return(result); } /** \brief LDR Exclusive (8 bit) This function performs a exclusive LDR command for 8 bit value. \param [in] ptr Pointer to data \return value of type uint8_t at (*ptr) */ __attribute__( ( always_inline ) ) __STATIC_INLINE uint8_t __LDREXB(volatile uint8_t *addr) { uint32_t result; #if (__GNUC__ > 4) || (__GNUC__ == 4 && __GNUC_MINOR__ >= 8) __ASM volatile ("ldrexb %0, %1" : "=r" (result) : "Q" (*addr) ); #else /* Prior to GCC 4.8, "Q" will be expanded to [rx, #0] which is not accepted by assembler. So has to use following less efficient pattern. */ __ASM volatile ("ldrexb %0, [%1]" : "=r" (result) : "r" (addr) : "memory" ); #endif return(result); } /** \brief LDR Exclusive (16 bit) This function performs a exclusive LDR command for 16 bit values. \param [in] ptr Pointer to data \return value of type uint16_t at (*ptr) */ __attribute__( ( always_inline ) ) __STATIC_INLINE uint16_t __LDREXH(volatile uint16_t *addr) { uint32_t result; #if (__GNUC__ > 4) || (__GNUC__ == 4 && __GNUC_MINOR__ >= 8) __ASM volatile ("ldrexh %0, %1" : "=r" (result) : "Q" (*addr) ); #else /* Prior to GCC 4.8, "Q" will be expanded to [rx, #0] which is not accepted by assembler. So has to use following less efficient pattern. */ __ASM volatile ("ldrexh %0, [%1]" : "=r" (result) : "r" (addr) : "memory" ); #endif return(result); } /** \brief LDR Exclusive (32 bit) This function performs a exclusive LDR command for 32 bit values. \param [in] ptr Pointer to data \return value of type uint32_t at (*ptr) */ __attribute__( ( always_inline ) ) __STATIC_INLINE uint32_t __LDREXW(volatile uint32_t *addr) { uint32_t result; __ASM volatile ("ldrex %0, %1" : "=r" (result) : "Q" (*addr) ); return(result); } /** \brief STR Exclusive (8 bit) This function performs a exclusive STR command for 8 bit values. \param [in] value Value to store \param [in] ptr Pointer to location \return 0 Function succeeded \return 1 Function failed */ __attribute__( ( always_inline ) ) __STATIC_INLINE uint32_t __STREXB(uint8_t value, volatile uint8_t *addr) { uint32_t result; __ASM volatile ("strexb %0, %2, %1" : "=&r" (result), "=Q" (*addr) : "r" (value) ); return(result); } /** \brief STR Exclusive (16 bit) This function performs a exclusive STR command for 16 bit values. \param [in] value Value to store \param [in] ptr Pointer to location \return 0 Function succeeded \return 1 Function failed */ __attribute__( ( always_inline ) ) __STATIC_INLINE uint32_t __STREXH(uint16_t value, volatile uint16_t *addr) { uint32_t result; __ASM volatile ("strexh %0, %2, %1" : "=&r" (result), "=Q" (*addr) : "r" (value) ); return(result); } /** \brief STR Exclusive (32 bit) This function performs a exclusive STR command for 32 bit values. \param [in] value Value to store \param [in] ptr Pointer to location \return 0 Function succeeded \return 1 Function failed */ __attribute__( ( always_inline ) ) __STATIC_INLINE uint32_t __STREXW(uint32_t value, volatile uint32_t *addr) { uint32_t result; __ASM volatile ("strex %0, %2, %1" : "=&r" (result), "=Q" (*addr) : "r" (value) ); return(result); } /** \brief Remove the exclusive lock This function removes the exclusive lock which is created by LDREX. */ __attribute__( ( always_inline ) ) __STATIC_INLINE void __CLREX(void) { __ASM volatile ("clrex" ::: "memory"); } /** \brief Signed Saturate This function saturates a signed value. \param [in] value Value to be saturated \param [in] sat Bit position to saturate to (1..32) \return Saturated value */ #define __SSAT(ARG1,ARG2) \ ({ \ uint32_t __RES, __ARG1 = (ARG1); \ __ASM ("ssat %0, %1, %2" : "=r" (__RES) : "I" (ARG2), "r" (__ARG1) ); \ __RES; \ }) /** \brief Unsigned Saturate This function saturates an unsigned value. \param [in] value Value to be saturated \param [in] sat Bit position to saturate to (0..31) \return Saturated value */ #define __USAT(ARG1,ARG2) \ ({ \ uint32_t __RES, __ARG1 = (ARG1); \ __ASM ("usat %0, %1, %2" : "=r" (__RES) : "I" (ARG2), "r" (__ARG1) ); \ __RES; \ }) /** \brief Count leading zeros This function counts the number of leading zeros of a data value. \param [in] value Value to count the leading zeros \return number of leading zeros in value */ __attribute__( ( always_inline ) ) __STATIC_INLINE uint8_t __CLZ(uint32_t value) { uint32_t result; __ASM volatile ("clz %0, %1" : "=r" (result) : "r" (value) ); return(result); } #endif /* (__CORTEX_M >= 0x03) */ #elif defined ( __TASKING__ ) /*------------------ TASKING Compiler --------------*/ /* TASKING carm specific functions */ /* * The CMSIS functions have been implemented as intrinsics in the compiler. * Please use "carm -?i" to get an up to date list of all intrinsics, * Including the CMSIS ones. */ #endif /*@}*/ /* end of group CMSIS_Core_InstructionInterface */ #endif /* __CORE_CMINSTR_H */ ================================================ FILE: Zelig/mbed/TARGET_NUCLEO_L152RE/core_cmSimd.h ================================================ /**************************************************************************//** * @file core_cmSimd.h * @brief CMSIS Cortex-M SIMD Header File * @version V4.10 * @date 18. March 2015 * * @note * ******************************************************************************/ /* Copyright (c) 2009 - 2014 ARM LIMITED All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: - Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. - Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. - Neither the name of ARM 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 COPYRIGHT HOLDERS AND 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. ---------------------------------------------------------------------------*/ #if defined ( __ICCARM__ ) #pragma system_include /* treat file as system include file for MISRA check */ #endif #ifndef __CORE_CMSIMD_H #define __CORE_CMSIMD_H #ifdef __cplusplus extern "C" { #endif /******************************************************************************* * Hardware Abstraction Layer ******************************************************************************/ /* ################### Compiler specific Intrinsics ########################### */ /** \defgroup CMSIS_SIMD_intrinsics CMSIS SIMD Intrinsics Access to dedicated SIMD instructions @{ */ #if defined ( __CC_ARM ) /*------------------RealView Compiler -----------------*/ /* ARM armcc specific functions */ #define __SADD8 __sadd8 #define __QADD8 __qadd8 #define __SHADD8 __shadd8 #define __UADD8 __uadd8 #define __UQADD8 __uqadd8 #define __UHADD8 __uhadd8 #define __SSUB8 __ssub8 #define __QSUB8 __qsub8 #define __SHSUB8 __shsub8 #define __USUB8 __usub8 #define __UQSUB8 __uqsub8 #define __UHSUB8 __uhsub8 #define __SADD16 __sadd16 #define __QADD16 __qadd16 #define __SHADD16 __shadd16 #define __UADD16 __uadd16 #define __UQADD16 __uqadd16 #define __UHADD16 __uhadd16 #define __SSUB16 __ssub16 #define __QSUB16 __qsub16 #define __SHSUB16 __shsub16 #define __USUB16 __usub16 #define __UQSUB16 __uqsub16 #define __UHSUB16 __uhsub16 #define __SASX __sasx #define __QASX __qasx #define __SHASX __shasx #define __UASX __uasx #define __UQASX __uqasx #define __UHASX __uhasx #define __SSAX __ssax #define __QSAX __qsax #define __SHSAX __shsax #define __USAX __usax #define __UQSAX __uqsax #define __UHSAX __uhsax #define __USAD8 __usad8 #define __USADA8 __usada8 #define __SSAT16 __ssat16 #define __USAT16 __usat16 #define __UXTB16 __uxtb16 #define __UXTAB16 __uxtab16 #define __SXTB16 __sxtb16 #define __SXTAB16 __sxtab16 #define __SMUAD __smuad #define __SMUADX __smuadx #define __SMLAD __smlad #define __SMLADX __smladx #define __SMLALD __smlald #define __SMLALDX __smlaldx #define __SMUSD __smusd #define __SMUSDX __smusdx #define __SMLSD __smlsd #define __SMLSDX __smlsdx #define __SMLSLD __smlsld #define __SMLSLDX __smlsldx #define __SEL __sel #define __QADD __qadd #define __QSUB __qsub #define __PKHBT(ARG1,ARG2,ARG3) ( ((((uint32_t)(ARG1)) ) & 0x0000FFFFUL) | \ ((((uint32_t)(ARG2)) << (ARG3)) & 0xFFFF0000UL) ) #define __PKHTB(ARG1,ARG2,ARG3) ( ((((uint32_t)(ARG1)) ) & 0xFFFF0000UL) | \ ((((uint32_t)(ARG2)) >> (ARG3)) & 0x0000FFFFUL) ) #define __SMMLA(ARG1,ARG2,ARG3) ( (int32_t)((((int64_t)(ARG1) * (ARG2)) + \ ((int64_t)(ARG3) << 32) ) >> 32)) #elif defined ( __GNUC__ ) /*------------------ GNU Compiler ---------------------*/ /* GNU gcc specific functions */ __attribute__( ( always_inline ) ) __STATIC_INLINE uint32_t __SADD8(uint32_t op1, uint32_t op2) { uint32_t result; __ASM volatile ("sadd8 %0, %1, %2" : "=r" (result) : "r" (op1), "r" (op2) ); return(result); } __attribute__( ( always_inline ) ) __STATIC_INLINE uint32_t __QADD8(uint32_t op1, uint32_t op2) { uint32_t result; __ASM volatile ("qadd8 %0, %1, %2" : "=r" (result) : "r" (op1), "r" (op2) ); return(result); } __attribute__( ( always_inline ) ) __STATIC_INLINE uint32_t __SHADD8(uint32_t op1, uint32_t op2) { uint32_t result; __ASM volatile ("shadd8 %0, %1, %2" : "=r" (result) : "r" (op1), "r" (op2) ); return(result); } __attribute__( ( always_inline ) ) __STATIC_INLINE uint32_t __UADD8(uint32_t op1, uint32_t op2) { uint32_t result; __ASM volatile ("uadd8 %0, %1, %2" : "=r" (result) : "r" (op1), "r" (op2) ); return(result); } __attribute__( ( always_inline ) ) __STATIC_INLINE uint32_t __UQADD8(uint32_t op1, uint32_t op2) { uint32_t result; __ASM volatile ("uqadd8 %0, %1, %2" : "=r" (result) : "r" (op1), "r" (op2) ); return(result); } __attribute__( ( always_inline ) ) __STATIC_INLINE uint32_t __UHADD8(uint32_t op1, uint32_t op2) { uint32_t result; __ASM volatile ("uhadd8 %0, %1, %2" : "=r" (result) : "r" (op1), "r" (op2) ); return(result); } __attribute__( ( always_inline ) ) __STATIC_INLINE uint32_t __SSUB8(uint32_t op1, uint32_t op2) { uint32_t result; __ASM volatile ("ssub8 %0, %1, %2" : "=r" (result) : "r" (op1), "r" (op2) ); return(result); } __attribute__( ( always_inline ) ) __STATIC_INLINE uint32_t __QSUB8(uint32_t op1, uint32_t op2) { uint32_t result; __ASM volatile ("qsub8 %0, %1, %2" : "=r" (result) : "r" (op1), "r" (op2) ); return(result); } __attribute__( ( always_inline ) ) __STATIC_INLINE uint32_t __SHSUB8(uint32_t op1, uint32_t op2) { uint32_t result; __ASM volatile ("shsub8 %0, %1, %2" : "=r" (result) : "r" (op1), "r" (op2) ); return(result); } __attribute__( ( always_inline ) ) __STATIC_INLINE uint32_t __USUB8(uint32_t op1, uint32_t op2) { uint32_t result; __ASM volatile ("usub8 %0, %1, %2" : "=r" (result) : "r" (op1), "r" (op2) ); return(result); } __attribute__( ( always_inline ) ) __STATIC_INLINE uint32_t __UQSUB8(uint32_t op1, uint32_t op2) { uint32_t result; __ASM volatile ("uqsub8 %0, %1, %2" : "=r" (result) : "r" (op1), "r" (op2) ); return(result); } __attribute__( ( always_inline ) ) __STATIC_INLINE uint32_t __UHSUB8(uint32_t op1, uint32_t op2) { uint32_t result; __ASM volatile ("uhsub8 %0, %1, %2" : "=r" (result) : "r" (op1), "r" (op2) ); return(result); } __attribute__( ( always_inline ) ) __STATIC_INLINE uint32_t __SADD16(uint32_t op1, uint32_t op2) { uint32_t result; __ASM volatile ("sadd16 %0, %1, %2" : "=r" (result) : "r" (op1), "r" (op2) ); return(result); } __attribute__( ( always_inline ) ) __STATIC_INLINE uint32_t __QADD16(uint32_t op1, uint32_t op2) { uint32_t result; __ASM volatile ("qadd16 %0, %1, %2" : "=r" (result) : "r" (op1), "r" (op2) ); return(result); } __attribute__( ( always_inline ) ) __STATIC_INLINE uint32_t __SHADD16(uint32_t op1, uint32_t op2) { uint32_t result; __ASM volatile ("shadd16 %0, %1, %2" : "=r" (result) : "r" (op1), "r" (op2) ); return(result); } __attribute__( ( always_inline ) ) __STATIC_INLINE uint32_t __UADD16(uint32_t op1, uint32_t op2) { uint32_t result; __ASM volatile ("uadd16 %0, %1, %2" : "=r" (result) : "r" (op1), "r" (op2) ); return(result); } __attribute__( ( always_inline ) ) __STATIC_INLINE uint32_t __UQADD16(uint32_t op1, uint32_t op2) { uint32_t result; __ASM volatile ("uqadd16 %0, %1, %2" : "=r" (result) : "r" (op1), "r" (op2) ); return(result); } __attribute__( ( always_inline ) ) __STATIC_INLINE uint32_t __UHADD16(uint32_t op1, uint32_t op2) { uint32_t result; __ASM volatile ("uhadd16 %0, %1, %2" : "=r" (result) : "r" (op1), "r" (op2) ); return(result); } __attribute__( ( always_inline ) ) __STATIC_INLINE uint32_t __SSUB16(uint32_t op1, uint32_t op2) { uint32_t result; __ASM volatile ("ssub16 %0, %1, %2" : "=r" (result) : "r" (op1), "r" (op2) ); return(result); } __attribute__( ( always_inline ) ) __STATIC_INLINE uint32_t __QSUB16(uint32_t op1, uint32_t op2) { uint32_t result; __ASM volatile ("qsub16 %0, %1, %2" : "=r" (result) : "r" (op1), "r" (op2) ); return(result); } __attribute__( ( always_inline ) ) __STATIC_INLINE uint32_t __SHSUB16(uint32_t op1, uint32_t op2) { uint32_t result; __ASM volatile ("shsub16 %0, %1, %2" : "=r" (result) : "r" (op1), "r" (op2) ); return(result); } __attribute__( ( always_inline ) ) __STATIC_INLINE uint32_t __USUB16(uint32_t op1, uint32_t op2) { uint32_t result; __ASM volatile ("usub16 %0, %1, %2" : "=r" (result) : "r" (op1), "r" (op2) ); return(result); } __attribute__( ( always_inline ) ) __STATIC_INLINE uint32_t __UQSUB16(uint32_t op1, uint32_t op2) { uint32_t result; __ASM volatile ("uqsub16 %0, %1, %2" : "=r" (result) : "r" (op1), "r" (op2) ); return(result); } __attribute__( ( always_inline ) ) __STATIC_INLINE uint32_t __UHSUB16(uint32_t op1, uint32_t op2) { uint32_t result; __ASM volatile ("uhsub16 %0, %1, %2" : "=r" (result) : "r" (op1), "r" (op2) ); return(result); } __attribute__( ( always_inline ) ) __STATIC_INLINE uint32_t __SASX(uint32_t op1, uint32_t op2) { uint32_t result; __ASM volatile ("sasx %0, %1, %2" : "=r" (result) : "r" (op1), "r" (op2) ); return(result); } __attribute__( ( always_inline ) ) __STATIC_INLINE uint32_t __QASX(uint32_t op1, uint32_t op2) { uint32_t result; __ASM volatile ("qasx %0, %1, %2" : "=r" (result) : "r" (op1), "r" (op2) ); return(result); } __attribute__( ( always_inline ) ) __STATIC_INLINE uint32_t __SHASX(uint32_t op1, uint32_t op2) { uint32_t result; __ASM volatile ("shasx %0, %1, %2" : "=r" (result) : "r" (op1), "r" (op2) ); return(result); } __attribute__( ( always_inline ) ) __STATIC_INLINE uint32_t __UASX(uint32_t op1, uint32_t op2) { uint32_t result; __ASM volatile ("uasx %0, %1, %2" : "=r" (result) : "r" (op1), "r" (op2) ); return(result); } __attribute__( ( always_inline ) ) __STATIC_INLINE uint32_t __UQASX(uint32_t op1, uint32_t op2) { uint32_t result; __ASM volatile ("uqasx %0, %1, %2" : "=r" (result) : "r" (op1), "r" (op2) ); return(result); } __attribute__( ( always_inline ) ) __STATIC_INLINE uint32_t __UHASX(uint32_t op1, uint32_t op2) { uint32_t result; __ASM volatile ("uhasx %0, %1, %2" : "=r" (result) : "r" (op1), "r" (op2) ); return(result); } __attribute__( ( always_inline ) ) __STATIC_INLINE uint32_t __SSAX(uint32_t op1, uint32_t op2) { uint32_t result; __ASM volatile ("ssax %0, %1, %2" : "=r" (result) : "r" (op1), "r" (op2) ); return(result); } __attribute__( ( always_inline ) ) __STATIC_INLINE uint32_t __QSAX(uint32_t op1, uint32_t op2) { uint32_t result; __ASM volatile ("qsax %0, %1, %2" : "=r" (result) : "r" (op1), "r" (op2) ); return(result); } __attribute__( ( always_inline ) ) __STATIC_INLINE uint32_t __SHSAX(uint32_t op1, uint32_t op2) { uint32_t result; __ASM volatile ("shsax %0, %1, %2" : "=r" (result) : "r" (op1), "r" (op2) ); return(result); } __attribute__( ( always_inline ) ) __STATIC_INLINE uint32_t __USAX(uint32_t op1, uint32_t op2) { uint32_t result; __ASM volatile ("usax %0, %1, %2" : "=r" (result) : "r" (op1), "r" (op2) ); return(result); } __attribute__( ( always_inline ) ) __STATIC_INLINE uint32_t __UQSAX(uint32_t op1, uint32_t op2) { uint32_t result; __ASM volatile ("uqsax %0, %1, %2" : "=r" (result) : "r" (op1), "r" (op2) ); return(result); } __attribute__( ( always_inline ) ) __STATIC_INLINE uint32_t __UHSAX(uint32_t op1, uint32_t op2) { uint32_t result; __ASM volatile ("uhsax %0, %1, %2" : "=r" (result) : "r" (op1), "r" (op2) ); return(result); } __attribute__( ( always_inline ) ) __STATIC_INLINE uint32_t __USAD8(uint32_t op1, uint32_t op2) { uint32_t result; __ASM volatile ("usad8 %0, %1, %2" : "=r" (result) : "r" (op1), "r" (op2) ); return(result); } __attribute__( ( always_inline ) ) __STATIC_INLINE uint32_t __USADA8(uint32_t op1, uint32_t op2, uint32_t op3) { uint32_t result; __ASM volatile ("usada8 %0, %1, %2, %3" : "=r" (result) : "r" (op1), "r" (op2), "r" (op3) ); return(result); } #define __SSAT16(ARG1,ARG2) \ ({ \ uint32_t __RES, __ARG1 = (ARG1); \ __ASM ("ssat16 %0, %1, %2" : "=r" (__RES) : "I" (ARG2), "r" (__ARG1) ); \ __RES; \ }) #define __USAT16(ARG1,ARG2) \ ({ \ uint32_t __RES, __ARG1 = (ARG1); \ __ASM ("usat16 %0, %1, %2" : "=r" (__RES) : "I" (ARG2), "r" (__ARG1) ); \ __RES; \ }) __attribute__( ( always_inline ) ) __STATIC_INLINE uint32_t __UXTB16(uint32_t op1) { uint32_t result; __ASM volatile ("uxtb16 %0, %1" : "=r" (result) : "r" (op1)); return(result); } __attribute__( ( always_inline ) ) __STATIC_INLINE uint32_t __UXTAB16(uint32_t op1, uint32_t op2) { uint32_t result; __ASM volatile ("uxtab16 %0, %1, %2" : "=r" (result) : "r" (op1), "r" (op2) ); return(result); } __attribute__( ( always_inline ) ) __STATIC_INLINE uint32_t __SXTB16(uint32_t op1) { uint32_t result; __ASM volatile ("sxtb16 %0, %1" : "=r" (result) : "r" (op1)); return(result); } __attribute__( ( always_inline ) ) __STATIC_INLINE uint32_t __SXTAB16(uint32_t op1, uint32_t op2) { uint32_t result; __ASM volatile ("sxtab16 %0, %1, %2" : "=r" (result) : "r" (op1), "r" (op2) ); return(result); } __attribute__( ( always_inline ) ) __STATIC_INLINE uint32_t __SMUAD (uint32_t op1, uint32_t op2) { uint32_t result; __ASM volatile ("smuad %0, %1, %2" : "=r" (result) : "r" (op1), "r" (op2) ); return(result); } __attribute__( ( always_inline ) ) __STATIC_INLINE uint32_t __SMUADX (uint32_t op1, uint32_t op2) { uint32_t result; __ASM volatile ("smuadx %0, %1, %2" : "=r" (result) : "r" (op1), "r" (op2) ); return(result); } __attribute__( ( always_inline ) ) __STATIC_INLINE uint32_t __SMLAD (uint32_t op1, uint32_t op2, uint32_t op3) { uint32_t result; __ASM volatile ("smlad %0, %1, %2, %3" : "=r" (result) : "r" (op1), "r" (op2), "r" (op3) ); return(result); } __attribute__( ( always_inline ) ) __STATIC_INLINE uint32_t __SMLADX (uint32_t op1, uint32_t op2, uint32_t op3) { uint32_t result; __ASM volatile ("smladx %0, %1, %2, %3" : "=r" (result) : "r" (op1), "r" (op2), "r" (op3) ); return(result); } __attribute__( ( always_inline ) ) __STATIC_INLINE uint64_t __SMLALD (uint32_t op1, uint32_t op2, uint64_t acc) { union llreg_u{ uint32_t w32[2]; uint64_t w64; } llr; llr.w64 = acc; #ifndef __ARMEB__ // Little endian __ASM volatile ("smlald %0, %1, %2, %3" : "=r" (llr.w32[0]), "=r" (llr.w32[1]): "r" (op1), "r" (op2) , "0" (llr.w32[0]), "1" (llr.w32[1]) ); #else // Big endian __ASM volatile ("smlald %0, %1, %2, %3" : "=r" (llr.w32[1]), "=r" (llr.w32[0]): "r" (op1), "r" (op2) , "0" (llr.w32[1]), "1" (llr.w32[0]) ); #endif return(llr.w64); } __attribute__( ( always_inline ) ) __STATIC_INLINE uint64_t __SMLALDX (uint32_t op1, uint32_t op2, uint64_t acc) { union llreg_u{ uint32_t w32[2]; uint64_t w64; } llr; llr.w64 = acc; #ifndef __ARMEB__ // Little endian __ASM volatile ("smlaldx %0, %1, %2, %3" : "=r" (llr.w32[0]), "=r" (llr.w32[1]): "r" (op1), "r" (op2) , "0" (llr.w32[0]), "1" (llr.w32[1]) ); #else // Big endian __ASM volatile ("smlaldx %0, %1, %2, %3" : "=r" (llr.w32[1]), "=r" (llr.w32[0]): "r" (op1), "r" (op2) , "0" (llr.w32[1]), "1" (llr.w32[0]) ); #endif return(llr.w64); } __attribute__( ( always_inline ) ) __STATIC_INLINE uint32_t __SMUSD (uint32_t op1, uint32_t op2) { uint32_t result; __ASM volatile ("smusd %0, %1, %2" : "=r" (result) : "r" (op1), "r" (op2) ); return(result); } __attribute__( ( always_inline ) ) __STATIC_INLINE uint32_t __SMUSDX (uint32_t op1, uint32_t op2) { uint32_t result; __ASM volatile ("smusdx %0, %1, %2" : "=r" (result) : "r" (op1), "r" (op2) ); return(result); } __attribute__( ( always_inline ) ) __STATIC_INLINE uint32_t __SMLSD (uint32_t op1, uint32_t op2, uint32_t op3) { uint32_t result; __ASM volatile ("smlsd %0, %1, %2, %3" : "=r" (result) : "r" (op1), "r" (op2), "r" (op3) ); return(result); } __attribute__( ( always_inline ) ) __STATIC_INLINE uint32_t __SMLSDX (uint32_t op1, uint32_t op2, uint32_t op3) { uint32_t result; __ASM volatile ("smlsdx %0, %1, %2, %3" : "=r" (result) : "r" (op1), "r" (op2), "r" (op3) ); return(result); } __attribute__( ( always_inline ) ) __STATIC_INLINE uint64_t __SMLSLD (uint32_t op1, uint32_t op2, uint64_t acc) { union llreg_u{ uint32_t w32[2]; uint64_t w64; } llr; llr.w64 = acc; #ifndef __ARMEB__ // Little endian __ASM volatile ("smlsld %0, %1, %2, %3" : "=r" (llr.w32[0]), "=r" (llr.w32[1]): "r" (op1), "r" (op2) , "0" (llr.w32[0]), "1" (llr.w32[1]) ); #else // Big endian __ASM volatile ("smlsld %0, %1, %2, %3" : "=r" (llr.w32[1]), "=r" (llr.w32[0]): "r" (op1), "r" (op2) , "0" (llr.w32[1]), "1" (llr.w32[0]) ); #endif return(llr.w64); } __attribute__( ( always_inline ) ) __STATIC_INLINE uint64_t __SMLSLDX (uint32_t op1, uint32_t op2, uint64_t acc) { union llreg_u{ uint32_t w32[2]; uint64_t w64; } llr; llr.w64 = acc; #ifndef __ARMEB__ // Little endian __ASM volatile ("smlsldx %0, %1, %2, %3" : "=r" (llr.w32[0]), "=r" (llr.w32[1]): "r" (op1), "r" (op2) , "0" (llr.w32[0]), "1" (llr.w32[1]) ); #else // Big endian __ASM volatile ("smlsldx %0, %1, %2, %3" : "=r" (llr.w32[1]), "=r" (llr.w32[0]): "r" (op1), "r" (op2) , "0" (llr.w32[1]), "1" (llr.w32[0]) ); #endif return(llr.w64); } __attribute__( ( always_inline ) ) __STATIC_INLINE uint32_t __SEL (uint32_t op1, uint32_t op2) { uint32_t result; __ASM volatile ("sel %0, %1, %2" : "=r" (result) : "r" (op1), "r" (op2) ); return(result); } __attribute__( ( always_inline ) ) __STATIC_INLINE uint32_t __QADD(uint32_t op1, uint32_t op2) { uint32_t result; __ASM volatile ("qadd %0, %1, %2" : "=r" (result) : "r" (op1), "r" (op2) ); return(result); } __attribute__( ( always_inline ) ) __STATIC_INLINE uint32_t __QSUB(uint32_t op1, uint32_t op2) { uint32_t result; __ASM volatile ("qsub %0, %1, %2" : "=r" (result) : "r" (op1), "r" (op2) ); return(result); } #define __PKHBT(ARG1,ARG2,ARG3) \ ({ \ uint32_t __RES, __ARG1 = (ARG1), __ARG2 = (ARG2); \ __ASM ("pkhbt %0, %1, %2, lsl %3" : "=r" (__RES) : "r" (__ARG1), "r" (__ARG2), "I" (ARG3) ); \ __RES; \ }) #define __PKHTB(ARG1,ARG2,ARG3) \ ({ \ uint32_t __RES, __ARG1 = (ARG1), __ARG2 = (ARG2); \ if (ARG3 == 0) \ __ASM ("pkhtb %0, %1, %2" : "=r" (__RES) : "r" (__ARG1), "r" (__ARG2) ); \ else \ __ASM ("pkhtb %0, %1, %2, asr %3" : "=r" (__RES) : "r" (__ARG1), "r" (__ARG2), "I" (ARG3) ); \ __RES; \ }) __attribute__( ( always_inline ) ) __STATIC_INLINE uint32_t __SMMLA (int32_t op1, int32_t op2, int32_t op3) { int32_t result; __ASM volatile ("smmla %0, %1, %2, %3" : "=r" (result): "r" (op1), "r" (op2), "r" (op3) ); return(result); } #elif defined ( __ICCARM__ ) /*------------------ ICC Compiler -------------------*/ /* IAR iccarm specific functions */ #include #elif defined ( __TMS470__ ) /*---------------- TI CCS Compiler ------------------*/ /* TI CCS specific functions */ #include #elif defined ( __TASKING__ ) /*------------------ TASKING Compiler --------------*/ /* TASKING carm specific functions */ /* not yet supported */ #elif defined ( __CSMC__ ) /*------------------ COSMIC Compiler -------------------*/ /* Cosmic specific functions */ #include #endif /*@} end of group CMSIS_SIMD_intrinsics */ #ifdef __cplusplus } #endif #endif /* __CORE_CMSIMD_H */ ================================================ FILE: Zelig/mbed/TARGET_NUCLEO_L152RE/hal_tick.h ================================================ /** ****************************************************************************** * @file hal_tick.h * @author MCD Application Team * @brief Initialization of HAL tick ****************************************************************************** * @attention * *

© COPYRIGHT(c) 2014 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. * ****************************************************************************** */ #ifndef __HAL_TICK_H #define __HAL_TICK_H #ifdef __cplusplus extern "C" { #endif #include "stm32l1xx.h" #include "cmsis_nvic.h" #define TIM_MST TIM5 #define TIM_MST_IRQ TIM5_IRQn #define TIM_MST_RCC __TIM5_CLK_ENABLE() #define TIM_MST_RESET_ON __TIM5_FORCE_RESET() #define TIM_MST_RESET_OFF __TIM5_RELEASE_RESET() #define HAL_TICK_DELAY (1000) // 1 ms #ifdef __cplusplus } #endif #endif // __HAL_TICK_H /************************ (C) COPYRIGHT STMicroelectronics *****END OF FILE****/ ================================================ FILE: Zelig/mbed/TARGET_NUCLEO_L152RE/stm32l152xe.h ================================================ /** ****************************************************************************** * @file stm32l152xe.h * @author MCD Application Team * @version V2.0.0 * @date 5-September-2014 * @brief CMSIS Cortex-M3 Device Peripheral Access Layer Header File. * This file contains all the peripheral register's definitions, bits * definitions and memory mapping for STM32L1xx devices. * * This file contains: * - Data structures and the address mapping for all peripherals * - Peripheral's registers declarations and bits definition * - Macros to access peripherals registers hardware * ****************************************************************************** * @attention * *

© COPYRIGHT(c) 2014 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. * ****************************************************************************** */ /** @addtogroup CMSIS * @{ */ /** @addtogroup stm32l152xe * @{ */ #ifndef __STM32L152xE_H #define __STM32L152xE_H #ifdef __cplusplus extern "C" { #endif /** @addtogroup Configuration_section_for_CMSIS * @{ */ /** * @brief Configuration of the Cortex-M3 Processor and Core Peripherals */ #define __CM3_REV 0x200 /*!< Cortex-M3 Revision r2p0 */ #define __MPU_PRESENT 1 /*!< STM32L1xx provides MPU */ #define __NVIC_PRIO_BITS 4 /*!< STM32L1xx uses 4 Bits for the Priority Levels */ #define __Vendor_SysTickConfig 0 /*!< Set to 1 if different SysTick Config is used */ /** * @} */ /** @addtogroup Peripheral_interrupt_number_definition * @{ */ /** * @brief STM32L1xx Interrupt Number Definition, according to the selected device * in @ref Library_configuration_section */ /*!< Interrupt Number Definition */ typedef enum { /****** Cortex-M3 Processor Exceptions Numbers ******************************************************/ NonMaskableInt_IRQn = -14, /*!< 2 Non Maskable Interrupt */ MemoryManagement_IRQn = -12, /*!< 4 Cortex-M3 Memory Management Interrupt */ BusFault_IRQn = -11, /*!< 5 Cortex-M3 Bus Fault Interrupt */ UsageFault_IRQn = -10, /*!< 6 Cortex-M3 Usage Fault Interrupt */ SVC_IRQn = -5, /*!< 11 Cortex-M3 SV Call Interrupt */ DebugMonitor_IRQn = -4, /*!< 12 Cortex-M3 Debug Monitor Interrupt */ PendSV_IRQn = -2, /*!< 14 Cortex-M3 Pend SV Interrupt */ SysTick_IRQn = -1, /*!< 15 Cortex-M3 System Tick Interrupt */ /****** STM32L specific Interrupt Numbers ***********************************************************/ WWDG_IRQn = 0, /*!< Window WatchDog Interrupt */ PVD_IRQn = 1, /*!< PVD through EXTI Line detection Interrupt */ TAMPER_STAMP_IRQn = 2, /*!< Tamper and TimeStamp interrupts through the EXTI line */ RTC_WKUP_IRQn = 3, /*!< RTC Wakeup Timer through EXTI Line Interrupt */ FLASH_IRQn = 4, /*!< FLASH global Interrupt */ RCC_IRQn = 5, /*!< RCC global Interrupt */ EXTI0_IRQn = 6, /*!< EXTI Line0 Interrupt */ EXTI1_IRQn = 7, /*!< EXTI Line1 Interrupt */ EXTI2_IRQn = 8, /*!< EXTI Line2 Interrupt */ EXTI3_IRQn = 9, /*!< EXTI Line3 Interrupt */ EXTI4_IRQn = 10, /*!< EXTI Line4 Interrupt */ DMA1_Channel1_IRQn = 11, /*!< DMA1 Channel 1 global Interrupt */ DMA1_Channel2_IRQn = 12, /*!< DMA1 Channel 2 global Interrupt */ DMA1_Channel3_IRQn = 13, /*!< DMA1 Channel 3 global Interrupt */ DMA1_Channel4_IRQn = 14, /*!< DMA1 Channel 4 global Interrupt */ DMA1_Channel5_IRQn = 15, /*!< DMA1 Channel 5 global Interrupt */ DMA1_Channel6_IRQn = 16, /*!< DMA1 Channel 6 global Interrupt */ DMA1_Channel7_IRQn = 17, /*!< DMA1 Channel 7 global Interrupt */ ADC1_IRQn = 18, /*!< ADC1 global Interrupt */ USB_HP_IRQn = 19, /*!< USB High Priority Interrupt */ USB_LP_IRQn = 20, /*!< USB Low Priority Interrupt */ DAC_IRQn = 21, /*!< DAC Interrupt */ COMP_IRQn = 22, /*!< Comparator through EXTI Line Interrupt */ EXTI9_5_IRQn = 23, /*!< External Line[9:5] Interrupts */ LCD_IRQn = 24, /*!< LCD Interrupt */ TIM9_IRQn = 25, /*!< TIM9 global Interrupt */ TIM10_IRQn = 26, /*!< TIM10 global Interrupt */ TIM11_IRQn = 27, /*!< TIM11 global Interrupt */ TIM2_IRQn = 28, /*!< TIM2 global Interrupt */ TIM3_IRQn = 29, /*!< TIM3 global Interrupt */ TIM4_IRQn = 30, /*!< TIM4 global Interrupt */ I2C1_EV_IRQn = 31, /*!< I2C1 Event Interrupt */ I2C1_ER_IRQn = 32, /*!< I2C1 Error Interrupt */ I2C2_EV_IRQn = 33, /*!< I2C2 Event Interrupt */ I2C2_ER_IRQn = 34, /*!< I2C2 Error Interrupt */ SPI1_IRQn = 35, /*!< SPI1 global Interrupt */ SPI2_IRQn = 36, /*!< SPI2 global Interrupt */ USART1_IRQn = 37, /*!< USART1 global Interrupt */ USART2_IRQn = 38, /*!< USART2 global Interrupt */ USART3_IRQn = 39, /*!< USART3 global Interrupt */ EXTI15_10_IRQn = 40, /*!< External Line[15:10] Interrupts */ RTC_Alarm_IRQn = 41, /*!< RTC Alarm through EXTI Line Interrupt */ USB_FS_WKUP_IRQn = 42, /*!< USB FS WakeUp from suspend through EXTI Line Interrupt */ TIM6_IRQn = 43, /*!< TIM6 global Interrupt */ TIM7_IRQn = 44, /*!< TIM7 global Interrupt */ TIM5_IRQn = 46, /*!< TIM5 global Interrupt */ SPI3_IRQn = 47, /*!< SPI3 global Interrupt */ UART4_IRQn = 48, /*!< UART4 global Interrupt */ UART5_IRQn = 49, /*!< UART5 global Interrupt */ DMA2_Channel1_IRQn = 50, /*!< DMA2 Channel 1 global Interrupt */ DMA2_Channel2_IRQn = 51, /*!< DMA2 Channel 2 global Interrupt */ DMA2_Channel3_IRQn = 52, /*!< DMA2 Channel 3 global Interrupt */ DMA2_Channel4_IRQn = 53, /*!< DMA2 Channel 4 global Interrupt */ DMA2_Channel5_IRQn = 54, /*!< DMA2 Channel 5 global Interrupt */ COMP_ACQ_IRQn = 56 /*!< Comparator Channel Acquisition global Interrupt */ } IRQn_Type; /** * @} */ #include "core_cm3.h" #include "system_stm32l1xx.h" #include /** @addtogroup Peripheral_registers_structures * @{ */ /** * @brief Analog to Digital Converter */ typedef struct { __IO uint32_t SR; /*!< ADC status register, Address offset: 0x00 */ __IO uint32_t CR1; /*!< ADC control register 1, Address offset: 0x04 */ __IO uint32_t CR2; /*!< ADC control register 2, Address offset: 0x08 */ __IO uint32_t SMPR1; /*!< ADC sample time register 1, Address offset: 0x0C */ __IO uint32_t SMPR2; /*!< ADC sample time register 2, Address offset: 0x10 */ __IO uint32_t SMPR3; /*!< ADC sample time register 3, Address offset: 0x14 */ __IO uint32_t JOFR1; /*!< ADC injected channel data offset register 1, Address offset: 0x18 */ __IO uint32_t JOFR2; /*!< ADC injected channel data offset register 2, Address offset: 0x1C */ __IO uint32_t JOFR3; /*!< ADC injected channel data offset register 3, Address offset: 0x20 */ __IO uint32_t JOFR4; /*!< ADC injected channel data offset register 4, Address offset: 0x24 */ __IO uint32_t HTR; /*!< ADC watchdog higher threshold register, Address offset: 0x28 */ __IO uint32_t LTR; /*!< ADC watchdog lower threshold register, Address offset: 0x2C */ __IO uint32_t SQR1; /*!< ADC regular sequence register 1, Address offset: 0x30 */ __IO uint32_t SQR2; /*!< ADC regular sequence register 2, Address offset: 0x34 */ __IO uint32_t SQR3; /*!< ADC regular sequence register 3, Address offset: 0x38 */ __IO uint32_t SQR4; /*!< ADC regular sequence register 4, Address offset: 0x3C */ __IO uint32_t SQR5; /*!< ADC regular sequence register 5, Address offset: 0x40 */ __IO uint32_t JSQR; /*!< ADC injected sequence register, Address offset: 0x44 */ __IO uint32_t JDR1; /*!< ADC injected data register 1, Address offset: 0x48 */ __IO uint32_t JDR2; /*!< ADC injected data register 2, Address offset: 0x4C */ __IO uint32_t JDR3; /*!< ADC injected data register 3, Address offset: 0x50 */ __IO uint32_t JDR4; /*!< ADC injected data register 4, Address offset: 0x54 */ __IO uint32_t DR; /*!< ADC regular data register, Address offset: 0x58 */ __IO uint32_t SMPR0; /*!< ADC sample time register 0, Address offset: 0x5C */ } ADC_TypeDef; typedef struct { __IO uint32_t CSR; /*!< ADC common status register, Address offset: ADC1 base address + 0x300 */ __IO uint32_t CCR; /*!< ADC common control register, Address offset: ADC1 base address + 0x304 */ } ADC_Common_TypeDef; /** * @brief Comparator */ typedef struct { __IO uint32_t CSR; /*!< COMP comparator control and status register, Address offset: 0x00 */ } COMP_TypeDef; /** * @brief CRC calculation unit */ typedef struct { __IO uint32_t DR; /*!< CRC Data register, Address offset: 0x00 */ __IO uint32_t IDR; /*!< CRC Independent data register, Address offset: 0x04 */ __IO uint32_t CR; /*!< CRC Control register, Address offset: 0x08 */ } CRC_TypeDef; /** * @brief Digital to Analog Converter */ typedef struct { __IO uint32_t CR; /*!< DAC control register, Address offset: 0x00 */ __IO uint32_t SWTRIGR; /*!< DAC software trigger register, Address offset: 0x04 */ __IO uint32_t DHR12R1; /*!< DAC channel1 12-bit right-aligned data holding register, Address offset: 0x08 */ __IO uint32_t DHR12L1; /*!< DAC channel1 12-bit left aligned data holding register, Address offset: 0x0C */ __IO uint32_t DHR8R1; /*!< DAC channel1 8-bit right aligned data holding register, Address offset: 0x10 */ __IO uint32_t DHR12R2; /*!< DAC channel2 12-bit right aligned data holding register, Address offset: 0x14 */ __IO uint32_t DHR12L2; /*!< DAC channel2 12-bit left aligned data holding register, Address offset: 0x18 */ __IO uint32_t DHR8R2; /*!< DAC channel2 8-bit right-aligned data holding register, Address offset: 0x1C */ __IO uint32_t DHR12RD; /*!< Dual DAC 12-bit right-aligned data holding register, Address offset: 0x20 */ __IO uint32_t DHR12LD; /*!< DUAL DAC 12-bit left aligned data holding register, Address offset: 0x24 */ __IO uint32_t DHR8RD; /*!< DUAL DAC 8-bit right aligned data holding register, Address offset: 0x28 */ __IO uint32_t DOR1; /*!< DAC channel1 data output register, Address offset: 0x2C */ __IO uint32_t DOR2; /*!< DAC channel2 data output register, Address offset: 0x30 */ __IO uint32_t SR; /*!< DAC status register, Address offset: 0x34 */ } DAC_TypeDef; /** * @brief Debug MCU */ typedef struct { __IO uint32_t IDCODE; /*!< MCU device ID code, Address offset: 0x00 */ __IO uint32_t CR; /*!< Debug MCU configuration register, Address offset: 0x04 */ __IO uint32_t APB1FZ; /*!< Debug MCU APB1 freeze register, Address offset: 0x08 */ __IO uint32_t APB2FZ; /*!< Debug MCU APB2 freeze register, Address offset: 0x0C */ }DBGMCU_TypeDef; /** * @brief DMA Controller */ typedef struct { __IO uint32_t CCR; /*!< DMA channel x configuration register */ __IO uint32_t CNDTR; /*!< DMA channel x number of data register */ __IO uint32_t CPAR; /*!< DMA channel x peripheral address register */ __IO uint32_t CMAR; /*!< DMA channel x memory address register */ } DMA_Channel_TypeDef; typedef struct { __IO uint32_t ISR; /*!< DMA interrupt status register, Address offset: 0x00 */ __IO uint32_t IFCR; /*!< DMA interrupt flag clear register, Address offset: 0x04 */ } DMA_TypeDef; /** * @brief External Interrupt/Event Controller */ typedef struct { __IO uint32_t IMR; /*! 0x7C */ __IO uint32_t WRP1213; /*!< write protection register 12 13, Address offset: 0x80 */ __IO uint32_t WRP1415; /*!< write protection register 14 15, Address offset: 0x84 */ } OB_TypeDef; /** * @brief Operational Amplifier (OPAMP) */ typedef struct { __IO uint32_t CSR; /*!< OPAMP control/status register, Address offset: 0x00 */ __IO uint32_t OTR; /*!< OPAMP offset trimming register for normal mode, Address offset: 0x04 */ __IO uint32_t LPOTR; /*!< OPAMP offset trimming register for low power mode, Address offset: 0x08 */ } OPAMP_TypeDef; /** * @brief General Purpose IO */ typedef struct { __IO uint32_t MODER; /*!< GPIO port mode register, Address offset: 0x00 */ __IO uint32_t OTYPER; /*!< GPIO port output type register, Address offset: 0x04 */ __IO uint32_t OSPEEDR; /*!< GPIO port output speed register, Address offset: 0x08 */ __IO uint32_t PUPDR; /*!< GPIO port pull-up/pull-down register, Address offset: 0x0C */ __IO uint32_t IDR; /*!< GPIO port input data register, Address offset: 0x10 */ __IO uint32_t ODR; /*!< GPIO port output data register, Address offset: 0x14 */ __IO uint32_t BSRR; /*!< GPIO port bit set/reset registerBSRR, Address offset: 0x18 */ __IO uint32_t LCKR; /*!< GPIO port configuration lock register, Address offset: 0x1C */ __IO uint32_t AFR[2]; /*!< GPIO alternate function register, Address offset: 0x20-0x24 */ __IO uint32_t BRR; /*!< GPIO bit reset register, Address offset: 0x28 */ } GPIO_TypeDef; /** * @brief SysTem Configuration */ typedef struct { __IO uint32_t MEMRMP; /*!< SYSCFG memory remap register, Address offset: 0x00 */ __IO uint32_t PMC; /*!< SYSCFG peripheral mode configuration register, Address offset: 0x04 */ __IO uint32_t EXTICR[4]; /*!< SYSCFG external interrupt configuration registers, Address offset: 0x08-0x14 */ } SYSCFG_TypeDef; /** * @brief Inter-integrated Circuit Interface */ typedef struct { __IO uint32_t CR1; /*!< I2C Control register 1, Address offset: 0x00 */ __IO uint32_t CR2; /*!< I2C Control register 2, Address offset: 0x04 */ __IO uint32_t OAR1; /*!< I2C Own address register 1, Address offset: 0x08 */ __IO uint32_t OAR2; /*!< I2C Own address register 2, Address offset: 0x0C */ __IO uint32_t DR; /*!< I2C Data register, Address offset: 0x10 */ __IO uint32_t SR1; /*!< I2C Status register 1, Address offset: 0x14 */ __IO uint32_t SR2; /*!< I2C Status register 2, Address offset: 0x18 */ __IO uint32_t CCR; /*!< I2C Clock control register, Address offset: 0x1C */ __IO uint32_t TRISE; /*!< I2C TRISE register, Address offset: 0x20 */ } I2C_TypeDef; /** * @brief Independent WATCHDOG */ typedef struct { __IO uint32_t KR; /*!< Key register, Address offset: 0x00 */ __IO uint32_t PR; /*!< Prescaler register, Address offset: 0x04 */ __IO uint32_t RLR; /*!< Reload register, Address offset: 0x08 */ __IO uint32_t SR; /*!< Status register, Address offset: 0x0C */ } IWDG_TypeDef; /** * @brief LCD */ typedef struct { __IO uint32_t CR; /*!< LCD control register, Address offset: 0x00 */ __IO uint32_t FCR; /*!< LCD frame control register, Address offset: 0x04 */ __IO uint32_t SR; /*!< LCD status register, Address offset: 0x08 */ __IO uint32_t CLR; /*!< LCD clear register, Address offset: 0x0C */ uint32_t RESERVED; /*!< Reserved, Address offset: 0x10 */ __IO uint32_t RAM[16]; /*!< LCD display memory, Address offset: 0x14-0x50 */ } LCD_TypeDef; /** * @brief Power Control */ typedef struct { __IO uint32_t CR; /*!< PWR power control register, Address offset: 0x00 */ __IO uint32_t CSR; /*!< PWR power control/status register, Address offset: 0x04 */ } PWR_TypeDef; /** * @brief Reset and Clock Control */ typedef struct { __IO uint32_t CR; /*!< RCC clock control register, Address offset: 0x00 */ __IO uint32_t ICSCR; /*!< RCC Internal clock sources calibration register, Address offset: 0x04 */ __IO uint32_t CFGR; /*!< RCC Clock configuration register, Address offset: 0x08 */ __IO uint32_t CIR; /*!< RCC Clock interrupt register, Address offset: 0x0C */ __IO uint32_t AHBRSTR; /*!< RCC AHB peripheral reset register, Address offset: 0x10 */ __IO uint32_t APB2RSTR; /*!< RCC APB2 peripheral reset register, Address offset: 0x14 */ __IO uint32_t APB1RSTR; /*!< RCC APB1 peripheral reset register, Address offset: 0x18 */ __IO uint32_t AHBENR; /*!< RCC AHB peripheral clock enable register, Address offset: 0x1C */ __IO uint32_t APB2ENR; /*!< RCC APB2 peripheral clock enable register, Address offset: 0x20 */ __IO uint32_t APB1ENR; /*!< RCC APB1 peripheral clock enable register, Address offset: 0x24 */ __IO uint32_t AHBLPENR; /*!< RCC AHB peripheral clock enable in low power mode register, Address offset: 0x28 */ __IO uint32_t APB2LPENR; /*!< RCC APB2 peripheral clock enable in low power mode register, Address offset: 0x2C */ __IO uint32_t APB1LPENR; /*!< RCC APB1 peripheral clock enable in low power mode register, Address offset: 0x30 */ __IO uint32_t CSR; /*!< RCC Control/status register, Address offset: 0x34 */ } RCC_TypeDef; /** * @brief Routing Interface */ typedef struct { __IO uint32_t ICR; /*!< RI input capture register, Address offset: 0x00 */ __IO uint32_t ASCR1; /*!< RI analog switches control register, Address offset: 0x04 */ __IO uint32_t ASCR2; /*!< RI analog switch control register 2, Address offset: 0x08 */ __IO uint32_t HYSCR1; /*!< RI hysteresis control register, Address offset: 0x0C */ __IO uint32_t HYSCR2; /*!< RI Hysteresis control register, Address offset: 0x10 */ __IO uint32_t HYSCR3; /*!< RI Hysteresis control register, Address offset: 0x14 */ __IO uint32_t HYSCR4; /*!< RI Hysteresis control register, Address offset: 0x18 */ __IO uint32_t ASMR1; /*!< RI Analog switch mode register 1, Address offset: 0x1C */ __IO uint32_t CMR1; /*!< RI Channel mask register 1, Address offset: 0x20 */ __IO uint32_t CICR1; /*!< RI Channel Iden for capture register 1, Address offset: 0x24 */ __IO uint32_t ASMR2; /*!< RI Analog switch mode register 2, Address offset: 0x28 */ __IO uint32_t CMR2; /*!< RI Channel mask register 2, Address offset: 0x2C */ __IO uint32_t CICR2; /*!< RI Channel Iden for capture register 2, Address offset: 0x30 */ __IO uint32_t ASMR3; /*!< RI Analog switch mode register 3, Address offset: 0x34 */ __IO uint32_t CMR3; /*!< RI Channel mask register 3, Address offset: 0x38 */ __IO uint32_t CICR3; /*!< RI Channel Iden for capture register 3, Address offset: 0x3C */ __IO uint32_t ASMR4; /*!< RI Analog switch mode register 4, Address offset: 0x40 */ __IO uint32_t CMR4; /*!< RI Channel mask register 4, Address offset: 0x44 */ __IO uint32_t CICR4; /*!< RI Channel Iden for capture register 4, Address offset: 0x48 */ __IO uint32_t ASMR5; /*!< RI Analog switch mode register 5, Address offset: 0x4C */ __IO uint32_t CMR5; /*!< RI Channel mask register 5, Address offset: 0x50 */ __IO uint32_t CICR5; /*!< RI Channel Iden for capture register 5, Address offset: 0x54 */ } RI_TypeDef; /** * @brief Real-Time Clock */ typedef struct { __IO uint32_t TR; /*!< RTC time register, Address offset: 0x00 */ __IO uint32_t DR; /*!< RTC date register, Address offset: 0x04 */ __IO uint32_t CR; /*!< RTC control register, Address offset: 0x08 */ __IO uint32_t ISR; /*!< RTC initialization and status register, Address offset: 0x0C */ __IO uint32_t PRER; /*!< RTC prescaler register, Address offset: 0x10 */ __IO uint32_t WUTR; /*!< RTC wakeup timer register, Address offset: 0x14 */ __IO uint32_t CALIBR; /*!< RTC calibration register, Address offset: 0x18 */ __IO uint32_t ALRMAR; /*!< RTC alarm A register, Address offset: 0x1C */ __IO uint32_t ALRMBR; /*!< RTC alarm B register, Address offset: 0x20 */ __IO uint32_t WPR; /*!< RTC write protection register, Address offset: 0x24 */ __IO uint32_t SSR; /*!< RTC sub second register, Address offset: 0x28 */ __IO uint32_t SHIFTR; /*!< RTC shift control register, Address offset: 0x2C */ __IO uint32_t TSTR; /*!< RTC time stamp time register, Address offset: 0x30 */ __IO uint32_t TSDR; /*!< RTC time stamp date register, Address offset: 0x34 */ __IO uint32_t TSSSR; /*!< RTC time-stamp sub second register, Address offset: 0x38 */ __IO uint32_t CALR; /*!< RRTC calibration register, Address offset: 0x3C */ __IO uint32_t TAFCR; /*!< RTC tamper and alternate function configuration register, Address offset: 0x40 */ __IO uint32_t ALRMASSR; /*!< RTC alarm A sub second register, Address offset: 0x44 */ __IO uint32_t ALRMBSSR; /*!< RTC alarm B sub second register, Address offset: 0x48 */ uint32_t RESERVED7; /*!< Reserved, 0x4C */ __IO uint32_t BKP0R; /*!< RTC backup register 0, Address offset: 0x50 */ __IO uint32_t BKP1R; /*!< RTC backup register 1, Address offset: 0x54 */ __IO uint32_t BKP2R; /*!< RTC backup register 2, Address offset: 0x58 */ __IO uint32_t BKP3R; /*!< RTC backup register 3, Address offset: 0x5C */ __IO uint32_t BKP4R; /*!< RTC backup register 4, Address offset: 0x60 */ __IO uint32_t BKP5R; /*!< RTC backup register 5, Address offset: 0x64 */ __IO uint32_t BKP6R; /*!< RTC backup register 6, Address offset: 0x68 */ __IO uint32_t BKP7R; /*!< RTC backup register 7, Address offset: 0x6C */ __IO uint32_t BKP8R; /*!< RTC backup register 8, Address offset: 0x70 */ __IO uint32_t BKP9R; /*!< RTC backup register 9, Address offset: 0x74 */ __IO uint32_t BKP10R; /*!< RTC backup register 10, Address offset: 0x78 */ __IO uint32_t BKP11R; /*!< RTC backup register 11, Address offset: 0x7C */ __IO uint32_t BKP12R; /*!< RTC backup register 12, Address offset: 0x80 */ __IO uint32_t BKP13R; /*!< RTC backup register 13, Address offset: 0x84 */ __IO uint32_t BKP14R; /*!< RTC backup register 14, Address offset: 0x88 */ __IO uint32_t BKP15R; /*!< RTC backup register 15, Address offset: 0x8C */ __IO uint32_t BKP16R; /*!< RTC backup register 16, Address offset: 0x90 */ __IO uint32_t BKP17R; /*!< RTC backup register 17, Address offset: 0x94 */ __IO uint32_t BKP18R; /*!< RTC backup register 18, Address offset: 0x98 */ __IO uint32_t BKP19R; /*!< RTC backup register 19, Address offset: 0x9C */ __IO uint32_t BKP20R; /*!< RTC backup register 20, Address offset: 0xA0 */ __IO uint32_t BKP21R; /*!< RTC backup register 21, Address offset: 0xA4 */ __IO uint32_t BKP22R; /*!< RTC backup register 22, Address offset: 0xA8 */ __IO uint32_t BKP23R; /*!< RTC backup register 23, Address offset: 0xAC */ __IO uint32_t BKP24R; /*!< RTC backup register 24, Address offset: 0xB0 */ __IO uint32_t BKP25R; /*!< RTC backup register 25, Address offset: 0xB4 */ __IO uint32_t BKP26R; /*!< RTC backup register 26, Address offset: 0xB8 */ __IO uint32_t BKP27R; /*!< RTC backup register 27, Address offset: 0xBC */ __IO uint32_t BKP28R; /*!< RTC backup register 28, Address offset: 0xC0 */ __IO uint32_t BKP29R; /*!< RTC backup register 29, Address offset: 0xC4 */ __IO uint32_t BKP30R; /*!< RTC backup register 30, Address offset: 0xC8 */ __IO uint32_t BKP31R; /*!< RTC backup register 31, Address offset: 0xCC */ } RTC_TypeDef; /** * @brief Serial Peripheral Interface */ typedef struct { __IO uint32_t CR1; /*!< SPI Control register 1 (not used in I2S mode), Address offset: 0x00 */ __IO uint32_t CR2; /*!< SPI Control register 2, Address offset: 0x04 */ __IO uint32_t SR; /*!< SPI Status register, Address offset: 0x08 */ __IO uint32_t DR; /*!< SPI data register, Address offset: 0x0C */ __IO uint32_t CRCPR; /*!< SPI CRC polynomial register (not used in I2S mode), Address offset: 0x10 */ __IO uint32_t RXCRCR; /*!< SPI Rx CRC register (not used in I2S mode), Address offset: 0x14 */ __IO uint32_t TXCRCR; /*!< SPI Tx CRC register (not used in I2S mode), Address offset: 0x18 */ __IO uint32_t I2SCFGR; /*!< SPI_I2S configuration register, Address offset: 0x1C */ __IO uint32_t I2SPR; /*!< SPI_I2S prescaler register, Address offset: 0x20 */ } SPI_TypeDef; /** * @brief TIM */ typedef struct { __IO uint32_t CR1; /*!< TIM control register 1, Address offset: 0x00 */ __IO uint32_t CR2; /*!< TIM control register 2, Address offset: 0x04 */ __IO uint32_t SMCR; /*!< TIM slave Mode Control register, Address offset: 0x08 */ __IO uint32_t DIER; /*!< TIM DMA/interrupt enable register, Address offset: 0x0C */ __IO uint32_t SR; /*!< TIM status register, Address offset: 0x10 */ __IO uint32_t EGR; /*!< TIM event generation register, Address offset: 0x14 */ __IO uint32_t CCMR1; /*!< TIM capture/compare mode register 1, Address offset: 0x18 */ __IO uint32_t CCMR2; /*!< TIM capture/compare mode register 2, Address offset: 0x1C */ __IO uint32_t CCER; /*!< TIM capture/compare enable register, Address offset: 0x20 */ __IO uint32_t CNT; /*!< TIM counter register, Address offset: 0x24 */ __IO uint32_t PSC; /*!< TIM prescaler register, Address offset: 0x28 */ __IO uint32_t ARR; /*!< TIM auto-reload register, Address offset: 0x2C */ uint32_t RESERVED12; /*!< Reserved, 0x30 */ __IO uint32_t CCR1; /*!< TIM capture/compare register 1, Address offset: 0x34 */ __IO uint32_t CCR2; /*!< TIM capture/compare register 2, Address offset: 0x38 */ __IO uint32_t CCR3; /*!< TIM capture/compare register 3, Address offset: 0x3C */ __IO uint32_t CCR4; /*!< TIM capture/compare register 4, Address offset: 0x40 */ uint32_t RESERVED17; /*!< Reserved, 0x44 */ __IO uint32_t DCR; /*!< TIM DMA control register, Address offset: 0x48 */ __IO uint32_t DMAR; /*!< TIM DMA address for full transfer, Address offset: 0x4C */ __IO uint32_t OR; /*!< TIM option register, Address offset: 0x50 */ } TIM_TypeDef; /** * @brief Universal Synchronous Asynchronous Receiver Transmitter */ typedef struct { __IO uint32_t SR; /*!< USART Status register, Address offset: 0x00 */ __IO uint32_t DR; /*!< USART Data register, Address offset: 0x04 */ __IO uint32_t BRR; /*!< USART Baud rate register, Address offset: 0x08 */ __IO uint32_t CR1; /*!< USART Control register 1, Address offset: 0x0C */ __IO uint32_t CR2; /*!< USART Control register 2, Address offset: 0x10 */ __IO uint32_t CR3; /*!< USART Control register 3, Address offset: 0x14 */ __IO uint32_t GTPR; /*!< USART Guard time and prescaler register, Address offset: 0x18 */ } USART_TypeDef; /** * @brief Universal Serial Bus Full Speed Device */ typedef struct { __IO uint16_t EP0R; /*!< USB Endpoint 0 register, Address offset: 0x00 */ __IO uint16_t RESERVED0; /*!< Reserved */ __IO uint16_t EP1R; /*!< USB Endpoint 1 register, Address offset: 0x04 */ __IO uint16_t RESERVED1; /*!< Reserved */ __IO uint16_t EP2R; /*!< USB Endpoint 2 register, Address offset: 0x08 */ __IO uint16_t RESERVED2; /*!< Reserved */ __IO uint16_t EP3R; /*!< USB Endpoint 3 register, Address offset: 0x0C */ __IO uint16_t RESERVED3; /*!< Reserved */ __IO uint16_t EP4R; /*!< USB Endpoint 4 register, Address offset: 0x10 */ __IO uint16_t RESERVED4; /*!< Reserved */ __IO uint16_t EP5R; /*!< USB Endpoint 5 register, Address offset: 0x14 */ __IO uint16_t RESERVED5; /*!< Reserved */ __IO uint16_t EP6R; /*!< USB Endpoint 6 register, Address offset: 0x18 */ __IO uint16_t RESERVED6; /*!< Reserved */ __IO uint16_t EP7R; /*!< USB Endpoint 7 register, Address offset: 0x1C */ __IO uint16_t RESERVED7[17]; /*!< Reserved */ __IO uint16_t CNTR; /*!< Control register, Address offset: 0x40 */ __IO uint16_t RESERVED8; /*!< Reserved */ __IO uint16_t ISTR; /*!< Interrupt status register, Address offset: 0x44 */ __IO uint16_t RESERVED9; /*!< Reserved */ __IO uint16_t FNR; /*!< Frame number register, Address offset: 0x48 */ __IO uint16_t RESERVEDA; /*!< Reserved */ __IO uint16_t DADDR; /*!< Device address register, Address offset: 0x4C */ __IO uint16_t RESERVEDB; /*!< Reserved */ __IO uint16_t BTABLE; /*!< Buffer Table address register, Address offset: 0x50 */ __IO uint16_t RESERVEDC; /*!< Reserved */ } USB_TypeDef; /** * @brief Window WATCHDOG */ typedef struct { __IO uint32_t CR; /*!< WWDG Control register, Address offset: 0x00 */ __IO uint32_t CFR; /*!< WWDG Configuration register, Address offset: 0x04 */ __IO uint32_t SR; /*!< WWDG Status register, Address offset: 0x08 */ } WWDG_TypeDef; /** * @brief Universal Serial Bus Full Speed Device */ /** * @} */ /** @addtogroup Peripheral_memory_map * @{ */ #define FLASH_BASE ((uint32_t)0x08000000) /*!< FLASH base address in the alias region */ #define FLASH_EEPROM_BASE ((uint32_t)(FLASH_BASE + 0x80000)) /*!< FLASH EEPROM base address in the alias region */ #define SRAM_BASE ((uint32_t)0x20000000) /*!< SRAM base address in the alias region */ #define PERIPH_BASE ((uint32_t)0x40000000) /*!< Peripheral base address in the alias region */ #define SRAM_BB_BASE ((uint32_t)0x22000000) /*!< SRAM base address in the bit-band region */ #define PERIPH_BB_BASE ((uint32_t)0x42000000) /*!< Peripheral base address in the bit-band region */ #define FLASH_BANK2_BASE ((uint32_t)0x08040000) /*!< FLASH BANK2 base address in the alias region */ #define FLASH_BANK1_END ((uint32_t)0x0803FFFF) /*!< Program end FLASH BANK1 address */ #define FLASH_BANK2_END ((uint32_t)0x0807FFFF) /*!< Program end FLASH BANK2 address */ #define FLASH_EEPROM_END ((uint32_t)0x08083FFF) /*!< FLASH EEPROM end address (16KB) */ /*!< Peripheral memory map */ #define APB1PERIPH_BASE PERIPH_BASE #define APB2PERIPH_BASE (PERIPH_BASE + 0x00010000) #define AHBPERIPH_BASE (PERIPH_BASE + 0x00020000) /*!< APB1 peripherals */ #define TIM2_BASE (APB1PERIPH_BASE + 0x00000000) #define TIM3_BASE (APB1PERIPH_BASE + 0x00000400) #define TIM4_BASE (APB1PERIPH_BASE + 0x00000800) #define TIM5_BASE (APB1PERIPH_BASE + 0x00000C00) #define TIM6_BASE (APB1PERIPH_BASE + 0x00001000) #define TIM7_BASE (APB1PERIPH_BASE + 0x00001400) #define LCD_BASE (APB1PERIPH_BASE + 0x00002400) #define RTC_BASE (APB1PERIPH_BASE + 0x00002800) #define WWDG_BASE (APB1PERIPH_BASE + 0x00002C00) #define IWDG_BASE (APB1PERIPH_BASE + 0x00003000) #define SPI2_BASE (APB1PERIPH_BASE + 0x00003800) #define SPI3_BASE (APB1PERIPH_BASE + 0x00003C00) #define USART2_BASE (APB1PERIPH_BASE + 0x00004400) #define USART3_BASE (APB1PERIPH_BASE + 0x00004800) #define UART4_BASE (APB1PERIPH_BASE + 0x00004C00) #define UART5_BASE (APB1PERIPH_BASE + 0x00005000) #define I2C1_BASE (APB1PERIPH_BASE + 0x00005400) #define I2C2_BASE (APB1PERIPH_BASE + 0x00005800) /* USB device FS */ #define USB_BASE (APB1PERIPH_BASE + 0x00005C00) /*!< USB_IP Peripheral Registers base address */ #define USB_PMAADDR (APB1PERIPH_BASE + 0x00006000) /*!< USB_IP Packet Memory Area base address */ /* USB device FS SRAM */ #define PWR_BASE (APB1PERIPH_BASE + 0x00007000) #define DAC_BASE (APB1PERIPH_BASE + 0x00007400) #define COMP_BASE (APB1PERIPH_BASE + 0x00007C00) #define RI_BASE (APB1PERIPH_BASE + 0x00007C04) #define OPAMP_BASE (APB1PERIPH_BASE + 0x00007C5C) /*!< APB2 peripherals */ #define SYSCFG_BASE (APB2PERIPH_BASE + 0x00000000) #define EXTI_BASE (APB2PERIPH_BASE + 0x00000400) #define TIM9_BASE (APB2PERIPH_BASE + 0x00000800) #define TIM10_BASE (APB2PERIPH_BASE + 0x00000C00) #define TIM11_BASE (APB2PERIPH_BASE + 0x00001000) #define ADC1_BASE (APB2PERIPH_BASE + 0x00002400) #define ADC_BASE (APB2PERIPH_BASE + 0x00002700) #define SPI1_BASE (APB2PERIPH_BASE + 0x00003000) #define USART1_BASE (APB2PERIPH_BASE + 0x00003800) /*!< AHB peripherals */ #define GPIOA_BASE (AHBPERIPH_BASE + 0x00000000) #define GPIOB_BASE (AHBPERIPH_BASE + 0x00000400) #define GPIOC_BASE (AHBPERIPH_BASE + 0x00000800) #define GPIOD_BASE (AHBPERIPH_BASE + 0x00000C00) #define GPIOE_BASE (AHBPERIPH_BASE + 0x00001000) #define GPIOH_BASE (AHBPERIPH_BASE + 0x00001400) #define GPIOF_BASE (AHBPERIPH_BASE + 0x00001800) #define GPIOG_BASE (AHBPERIPH_BASE + 0x00001C00) #define CRC_BASE (AHBPERIPH_BASE + 0x00003000) #define RCC_BASE (AHBPERIPH_BASE + 0x00003800) #define FLASH_R_BASE (AHBPERIPH_BASE + 0x00003C00) /*!< FLASH registers base address */ #define OB_BASE ((uint32_t)0x1FF80000) /*!< FLASH Option Bytes base address */ #define DMA1_BASE (AHBPERIPH_BASE + 0x00006000) #define DMA1_Channel1_BASE (DMA1_BASE + 0x00000008) #define DMA1_Channel2_BASE (DMA1_BASE + 0x0000001C) #define DMA1_Channel3_BASE (DMA1_BASE + 0x00000030) #define DMA1_Channel4_BASE (DMA1_BASE + 0x00000044) #define DMA1_Channel5_BASE (DMA1_BASE + 0x00000058) #define DMA1_Channel6_BASE (DMA1_BASE + 0x0000006C) #define DMA1_Channel7_BASE (DMA1_BASE + 0x00000080) #define DMA2_BASE (AHBPERIPH_BASE + 0x00006400) #define DMA2_Channel1_BASE (DMA2_BASE + 0x00000008) #define DMA2_Channel2_BASE (DMA2_BASE + 0x0000001C) #define DMA2_Channel3_BASE (DMA2_BASE + 0x00000030) #define DMA2_Channel4_BASE (DMA2_BASE + 0x00000044) #define DMA2_Channel5_BASE (DMA2_BASE + 0x00000058) #define DBGMCU_BASE ((uint32_t)0xE0042000) /*!< Debug MCU registers base address */ /** * @} */ /** @addtogroup Peripheral_declaration * @{ */ #define TIM2 ((TIM_TypeDef *) TIM2_BASE) #define TIM3 ((TIM_TypeDef *) TIM3_BASE) #define TIM4 ((TIM_TypeDef *) TIM4_BASE) #define TIM5 ((TIM_TypeDef *) TIM5_BASE) #define TIM6 ((TIM_TypeDef *) TIM6_BASE) #define TIM7 ((TIM_TypeDef *) TIM7_BASE) #define LCD ((LCD_TypeDef *) LCD_BASE) #define RTC ((RTC_TypeDef *) RTC_BASE) #define WWDG ((WWDG_TypeDef *) WWDG_BASE) #define IWDG ((IWDG_TypeDef *) IWDG_BASE) #define SPI2 ((SPI_TypeDef *) SPI2_BASE) #define SPI3 ((SPI_TypeDef *) SPI3_BASE) #define USART2 ((USART_TypeDef *) USART2_BASE) #define USART3 ((USART_TypeDef *) USART3_BASE) #define UART4 ((USART_TypeDef *) UART4_BASE) #define UART5 ((USART_TypeDef *) UART5_BASE) #define I2C1 ((I2C_TypeDef *) I2C1_BASE) #define I2C2 ((I2C_TypeDef *) I2C2_BASE) /* USB device FS */ #define USB ((USB_TypeDef *) USB_BASE) /* USB device FS SRAM */ #define PWR ((PWR_TypeDef *) PWR_BASE) #define DAC ((DAC_TypeDef *) DAC_BASE) #define COMP ((COMP_TypeDef *) COMP_BASE) #define COMP1 ((COMP_TypeDef *) COMP_BASE) #define COMP2 ((COMP_TypeDef *) (COMP_BASE + 0x00000001)) #define RI ((RI_TypeDef *) RI_BASE) #define OPAMP ((OPAMP_TypeDef *) OPAMP_BASE) #define OPAMP1 ((OPAMP_TypeDef *) OPAMP_BASE) #define OPAMP2 ((OPAMP_TypeDef *) (OPAMP_BASE + 0x00000001)) #define SYSCFG ((SYSCFG_TypeDef *) SYSCFG_BASE) #define EXTI ((EXTI_TypeDef *) EXTI_BASE) #define TIM9 ((TIM_TypeDef *) TIM9_BASE) #define TIM10 ((TIM_TypeDef *) TIM10_BASE) #define TIM11 ((TIM_TypeDef *) TIM11_BASE) #define ADC1 ((ADC_TypeDef *) ADC1_BASE) #define ADC ((ADC_Common_TypeDef *) ADC_BASE) #define SPI1 ((SPI_TypeDef *) SPI1_BASE) #define USART1 ((USART_TypeDef *) USART1_BASE) #define GPIOA ((GPIO_TypeDef *) GPIOA_BASE) #define GPIOB ((GPIO_TypeDef *) GPIOB_BASE) #define GPIOC ((GPIO_TypeDef *) GPIOC_BASE) #define GPIOD ((GPIO_TypeDef *) GPIOD_BASE) #define GPIOE ((GPIO_TypeDef *) GPIOE_BASE) #define GPIOH ((GPIO_TypeDef *) GPIOH_BASE) #define GPIOF ((GPIO_TypeDef *) GPIOF_BASE) #define GPIOG ((GPIO_TypeDef *) GPIOG_BASE) #define CRC ((CRC_TypeDef *) CRC_BASE) #define RCC ((RCC_TypeDef *) RCC_BASE) #define FLASH ((FLASH_TypeDef *) FLASH_R_BASE) #define OB ((OB_TypeDef *) OB_BASE) #define DMA1 ((DMA_TypeDef *) DMA1_BASE) #define DMA1_Channel1 ((DMA_Channel_TypeDef *) DMA1_Channel1_BASE) #define DMA1_Channel2 ((DMA_Channel_TypeDef *) DMA1_Channel2_BASE) #define DMA1_Channel3 ((DMA_Channel_TypeDef *) DMA1_Channel3_BASE) #define DMA1_Channel4 ((DMA_Channel_TypeDef *) DMA1_Channel4_BASE) #define DMA1_Channel5 ((DMA_Channel_TypeDef *) DMA1_Channel5_BASE) #define DMA1_Channel6 ((DMA_Channel_TypeDef *) DMA1_Channel6_BASE) #define DMA1_Channel7 ((DMA_Channel_TypeDef *) DMA1_Channel7_BASE) #define DMA2 ((DMA_TypeDef *) DMA2_BASE) #define DMA2_Channel1 ((DMA_Channel_TypeDef *) DMA2_Channel1_BASE) #define DMA2_Channel2 ((DMA_Channel_TypeDef *) DMA2_Channel2_BASE) #define DMA2_Channel3 ((DMA_Channel_TypeDef *) DMA2_Channel3_BASE) #define DMA2_Channel4 ((DMA_Channel_TypeDef *) DMA2_Channel4_BASE) #define DMA2_Channel5 ((DMA_Channel_TypeDef *) DMA2_Channel5_BASE) #define DBGMCU ((DBGMCU_TypeDef *) DBGMCU_BASE) /** * @} */ /** @addtogroup Exported_constants * @{ */ /** @addtogroup Peripheral_Registers_Bits_Definition * @{ */ /******************************************************************************/ /* Peripheral Registers Bits Definition */ /******************************************************************************/ /******************************************************************************/ /* */ /* Analog to Digital Converter (ADC) */ /* */ /******************************************************************************/ /******************** Bit definition for ADC_SR register ********************/ #define ADC_SR_AWD ((uint32_t)0x00000001) /*!< Analog watchdog flag */ #define ADC_SR_EOC ((uint32_t)0x00000002) /*!< End of conversion */ #define ADC_SR_JEOC ((uint32_t)0x00000004) /*!< Injected channel end of conversion */ #define ADC_SR_JSTRT ((uint32_t)0x00000008) /*!< Injected channel Start flag */ #define ADC_SR_STRT ((uint32_t)0x00000010) /*!< Regular channel Start flag */ #define ADC_SR_OVR ((uint32_t)0x00000020) /*!< Overrun flag */ #define ADC_SR_ADONS ((uint32_t)0x00000040) /*!< ADC ON status */ #define ADC_SR_RCNR ((uint32_t)0x00000100) /*!< Regular channel not ready flag */ #define ADC_SR_JCNR ((uint32_t)0x00000200) /*!< Injected channel not ready flag */ /******************* Bit definition for ADC_CR1 register ********************/ #define ADC_CR1_AWDCH ((uint32_t)0x0000001F) /*!< AWDCH[4:0] bits (Analog watchdog channel select bits) */ #define ADC_CR1_AWDCH_0 ((uint32_t)0x00000001) /*!< Bit 0 */ #define ADC_CR1_AWDCH_1 ((uint32_t)0x00000002) /*!< Bit 1 */ #define ADC_CR1_AWDCH_2 ((uint32_t)0x00000004) /*!< Bit 2 */ #define ADC_CR1_AWDCH_3 ((uint32_t)0x00000008) /*!< Bit 3 */ #define ADC_CR1_AWDCH_4 ((uint32_t)0x00000010) /*!< Bit 4 */ #define ADC_CR1_EOCIE ((uint32_t)0x00000020) /*!< Interrupt enable for EOC */ #define ADC_CR1_AWDIE ((uint32_t)0x00000040) /*!< Analog Watchdog interrupt enable */ #define ADC_CR1_JEOCIE ((uint32_t)0x00000080) /*!< Interrupt enable for injected channels */ #define ADC_CR1_SCAN ((uint32_t)0x00000100) /*!< Scan mode */ #define ADC_CR1_AWDSGL ((uint32_t)0x00000200) /*!< Enable the watchdog on a single channel in scan mode */ #define ADC_CR1_JAUTO ((uint32_t)0x00000400) /*!< Automatic injected group conversion */ #define ADC_CR1_DISCEN ((uint32_t)0x00000800) /*!< Discontinuous mode on regular channels */ #define ADC_CR1_JDISCEN ((uint32_t)0x00001000) /*!< Discontinuous mode on injected channels */ #define ADC_CR1_DISCNUM ((uint32_t)0x0000E000) /*!< DISCNUM[2:0] bits (Discontinuous mode channel count) */ #define ADC_CR1_DISCNUM_0 ((uint32_t)0x00002000) /*!< Bit 0 */ #define ADC_CR1_DISCNUM_1 ((uint32_t)0x00004000) /*!< Bit 1 */ #define ADC_CR1_DISCNUM_2 ((uint32_t)0x00008000) /*!< Bit 2 */ #define ADC_CR1_PDD ((uint32_t)0x00010000) /*!< Power Down during Delay phase */ #define ADC_CR1_PDI ((uint32_t)0x00020000) /*!< Power Down during Idle phase */ #define ADC_CR1_JAWDEN ((uint32_t)0x00400000) /*!< Analog watchdog enable on injected channels */ #define ADC_CR1_AWDEN ((uint32_t)0x00800000) /*!< Analog watchdog enable on regular channels */ #define ADC_CR1_RES ((uint32_t)0x03000000) /*!< RES[1:0] bits (Resolution) */ #define ADC_CR1_RES_0 ((uint32_t)0x01000000) /*!< Bit 0 */ #define ADC_CR1_RES_1 ((uint32_t)0x02000000) /*!< Bit 1 */ #define ADC_CR1_OVRIE ((uint32_t)0x04000000) /*!< Overrun interrupt enable */ /******************* Bit definition for ADC_CR2 register ********************/ #define ADC_CR2_ADON ((uint32_t)0x00000001) /*!< A/D Converter ON / OFF */ #define ADC_CR2_CONT ((uint32_t)0x00000002) /*!< Continuous Conversion */ #define ADC_CR2_CFG ((uint32_t)0x00000004) /*!< ADC Configuration */ #define ADC_CR2_DELS ((uint32_t)0x00000070) /*!< DELS[2:0] bits (Delay selection) */ #define ADC_CR2_DELS_0 ((uint32_t)0x00000010) /*!< Bit 0 */ #define ADC_CR2_DELS_1 ((uint32_t)0x00000020) /*!< Bit 1 */ #define ADC_CR2_DELS_2 ((uint32_t)0x00000040) /*!< Bit 2 */ #define ADC_CR2_DMA ((uint32_t)0x00000100) /*!< Direct Memory access mode */ #define ADC_CR2_DDS ((uint32_t)0x00000200) /*!< DMA disable selection (Single ADC) */ #define ADC_CR2_EOCS ((uint32_t)0x00000400) /*!< End of conversion selection */ #define ADC_CR2_ALIGN ((uint32_t)0x00000800) /*!< Data Alignment */ #define ADC_CR2_JEXTSEL ((uint32_t)0x000F0000) /*!< JEXTSEL[3:0] bits (External event select for injected group) */ #define ADC_CR2_JEXTSEL_0 ((uint32_t)0x00010000) /*!< Bit 0 */ #define ADC_CR2_JEXTSEL_1 ((uint32_t)0x00020000) /*!< Bit 1 */ #define ADC_CR2_JEXTSEL_2 ((uint32_t)0x00040000) /*!< Bit 2 */ #define ADC_CR2_JEXTSEL_3 ((uint32_t)0x00080000) /*!< Bit 3 */ #define ADC_CR2_JEXTEN ((uint32_t)0x00300000) /*!< JEXTEN[1:0] bits (External Trigger Conversion mode for injected channels) */ #define ADC_CR2_JEXTEN_0 ((uint32_t)0x00100000) /*!< Bit 0 */ #define ADC_CR2_JEXTEN_1 ((uint32_t)0x00200000) /*!< Bit 1 */ #define ADC_CR2_JSWSTART ((uint32_t)0x00400000) /*!< Start Conversion of injected channels */ #define ADC_CR2_EXTSEL ((uint32_t)0x0F000000) /*!< EXTSEL[3:0] bits (External Event Select for regular group) */ #define ADC_CR2_EXTSEL_0 ((uint32_t)0x01000000) /*!< Bit 0 */ #define ADC_CR2_EXTSEL_1 ((uint32_t)0x02000000) /*!< Bit 1 */ #define ADC_CR2_EXTSEL_2 ((uint32_t)0x04000000) /*!< Bit 2 */ #define ADC_CR2_EXTSEL_3 ((uint32_t)0x08000000) /*!< Bit 3 */ #define ADC_CR2_EXTEN ((uint32_t)0x30000000) /*!< EXTEN[1:0] bits (External Trigger Conversion mode for regular channels) */ #define ADC_CR2_EXTEN_0 ((uint32_t)0x10000000) /*!< Bit 0 */ #define ADC_CR2_EXTEN_1 ((uint32_t)0x20000000) /*!< Bit 1 */ #define ADC_CR2_SWSTART ((uint32_t)0x40000000) /*!< Start Conversion of regular channels */ /****************** Bit definition for ADC_SMPR1 register *******************/ #define ADC_SMPR1_SMP20 ((uint32_t)0x00000007) /*!< SMP20[2:0] bits (Channel 20 Sample time selection) */ #define ADC_SMPR1_SMP20_0 ((uint32_t)0x00000001) /*!< Bit 0 */ #define ADC_SMPR1_SMP20_1 ((uint32_t)0x00000002) /*!< Bit 1 */ #define ADC_SMPR1_SMP20_2 ((uint32_t)0x00000004) /*!< Bit 2 */ #define ADC_SMPR1_SMP21 ((uint32_t)0x00000038) /*!< SMP21[2:0] bits (Channel 21 Sample time selection) */ #define ADC_SMPR1_SMP21_0 ((uint32_t)0x00000008) /*!< Bit 0 */ #define ADC_SMPR1_SMP21_1 ((uint32_t)0x00000010) /*!< Bit 1 */ #define ADC_SMPR1_SMP21_2 ((uint32_t)0x00000020) /*!< Bit 2 */ #define ADC_SMPR1_SMP22 ((uint32_t)0x000001C0) /*!< SMP22[2:0] bits (Channel 22 Sample time selection) */ #define ADC_SMPR1_SMP22_0 ((uint32_t)0x00000040) /*!< Bit 0 */ #define ADC_SMPR1_SMP22_1 ((uint32_t)0x00000080) /*!< Bit 1 */ #define ADC_SMPR1_SMP22_2 ((uint32_t)0x00000100) /*!< Bit 2 */ #define ADC_SMPR1_SMP23 ((uint32_t)0x00000E00) /*!< SMP23[2:0] bits (Channel 23 Sample time selection) */ #define ADC_SMPR1_SMP23_0 ((uint32_t)0x00000200) /*!< Bit 0 */ #define ADC_SMPR1_SMP23_1 ((uint32_t)0x00000400) /*!< Bit 1 */ #define ADC_SMPR1_SMP23_2 ((uint32_t)0x00000800) /*!< Bit 2 */ #define ADC_SMPR1_SMP24 ((uint32_t)0x00007000) /*!< SMP24[2:0] bits (Channel 24 Sample time selection) */ #define ADC_SMPR1_SMP24_0 ((uint32_t)0x00001000) /*!< Bit 0 */ #define ADC_SMPR1_SMP24_1 ((uint32_t)0x00002000) /*!< Bit 1 */ #define ADC_SMPR1_SMP24_2 ((uint32_t)0x00004000) /*!< Bit 2 */ #define ADC_SMPR1_SMP25 ((uint32_t)0x00038000) /*!< SMP25[2:0] bits (Channel 25 Sample time selection) */ #define ADC_SMPR1_SMP25_0 ((uint32_t)0x00008000) /*!< Bit 0 */ #define ADC_SMPR1_SMP25_1 ((uint32_t)0x00010000) /*!< Bit 1 */ #define ADC_SMPR1_SMP25_2 ((uint32_t)0x00020000) /*!< Bit 2 */ #define ADC_SMPR1_SMP26 ((uint32_t)0x001C0000) /*!< SMP26[2:0] bits (Channel 26 Sample time selection) */ #define ADC_SMPR1_SMP26_0 ((uint32_t)0x00040000) /*!< Bit 0 */ #define ADC_SMPR1_SMP26_1 ((uint32_t)0x00080000) /*!< Bit 1 */ #define ADC_SMPR1_SMP26_2 ((uint32_t)0x00100000) /*!< Bit 2 */ #define ADC_SMPR1_SMP27 ((uint32_t)0x00E00000) /*!< SMP27[2:0] bits (Channel 27 Sample time selection) */ #define ADC_SMPR1_SMP27_0 ((uint32_t)0x00200000) /*!< Bit 0 */ #define ADC_SMPR1_SMP27_1 ((uint32_t)0x00400000) /*!< Bit 1 */ #define ADC_SMPR1_SMP27_2 ((uint32_t)0x00800000) /*!< Bit 2 */ #define ADC_SMPR1_SMP28 ((uint32_t)0x07000000) /*!< SMP28[2:0] bits (Channel 28 Sample time selection) */ #define ADC_SMPR1_SMP28_0 ((uint32_t)0x01000000) /*!< Bit 0 */ #define ADC_SMPR1_SMP28_1 ((uint32_t)0x02000000) /*!< Bit 1 */ #define ADC_SMPR1_SMP28_2 ((uint32_t)0x04000000) /*!< Bit 2 */ #define ADC_SMPR1_SMP29 ((uint32_t)0x38000000) /*!< SMP29[2:0] bits (Channel 29 Sample time selection) */ #define ADC_SMPR1_SMP29_0 ((uint32_t)0x08000000) /*!< Bit 0 */ #define ADC_SMPR1_SMP29_1 ((uint32_t)0x10000000) /*!< Bit 1 */ #define ADC_SMPR1_SMP29_2 ((uint32_t)0x20000000) /*!< Bit 2 */ /****************** Bit definition for ADC_SMPR2 register *******************/ #define ADC_SMPR2_SMP10 ((uint32_t)0x00000007) /*!< SMP10[2:0] bits (Channel 10 Sample time selection) */ #define ADC_SMPR2_SMP10_0 ((uint32_t)0x00000001) /*!< Bit 0 */ #define ADC_SMPR2_SMP10_1 ((uint32_t)0x00000002) /*!< Bit 1 */ #define ADC_SMPR2_SMP10_2 ((uint32_t)0x00000004) /*!< Bit 2 */ #define ADC_SMPR2_SMP11 ((uint32_t)0x00000038) /*!< SMP11[2:0] bits (Channel 11 Sample time selection) */ #define ADC_SMPR2_SMP11_0 ((uint32_t)0x00000008) /*!< Bit 0 */ #define ADC_SMPR2_SMP11_1 ((uint32_t)0x00000010) /*!< Bit 1 */ #define ADC_SMPR2_SMP11_2 ((uint32_t)0x00000020) /*!< Bit 2 */ #define ADC_SMPR2_SMP12 ((uint32_t)0x000001C0) /*!< SMP12[2:0] bits (Channel 12 Sample time selection) */ #define ADC_SMPR2_SMP12_0 ((uint32_t)0x00000040) /*!< Bit 0 */ #define ADC_SMPR2_SMP12_1 ((uint32_t)0x00000080) /*!< Bit 1 */ #define ADC_SMPR2_SMP12_2 ((uint32_t)0x00000100) /*!< Bit 2 */ #define ADC_SMPR2_SMP13 ((uint32_t)0x00000E00) /*!< SMP13[2:0] bits (Channel 13 Sample time selection) */ #define ADC_SMPR2_SMP13_0 ((uint32_t)0x00000200) /*!< Bit 0 */ #define ADC_SMPR2_SMP13_1 ((uint32_t)0x00000400) /*!< Bit 1 */ #define ADC_SMPR2_SMP13_2 ((uint32_t)0x00000800) /*!< Bit 2 */ #define ADC_SMPR2_SMP14 ((uint32_t)0x00007000) /*!< SMP14[2:0] bits (Channel 14 Sample time selection) */ #define ADC_SMPR2_SMP14_0 ((uint32_t)0x00001000) /*!< Bit 0 */ #define ADC_SMPR2_SMP14_1 ((uint32_t)0x00002000) /*!< Bit 1 */ #define ADC_SMPR2_SMP14_2 ((uint32_t)0x00004000) /*!< Bit 2 */ #define ADC_SMPR2_SMP15 ((uint32_t)0x00038000) /*!< SMP15[2:0] bits (Channel 5 Sample time selection) */ #define ADC_SMPR2_SMP15_0 ((uint32_t)0x00008000) /*!< Bit 0 */ #define ADC_SMPR2_SMP15_1 ((uint32_t)0x00010000) /*!< Bit 1 */ #define ADC_SMPR2_SMP15_2 ((uint32_t)0x00020000) /*!< Bit 2 */ #define ADC_SMPR2_SMP16 ((uint32_t)0x001C0000) /*!< SMP16[2:0] bits (Channel 16 Sample time selection) */ #define ADC_SMPR2_SMP16_0 ((uint32_t)0x00040000) /*!< Bit 0 */ #define ADC_SMPR2_SMP16_1 ((uint32_t)0x00080000) /*!< Bit 1 */ #define ADC_SMPR2_SMP16_2 ((uint32_t)0x00100000) /*!< Bit 2 */ #define ADC_SMPR2_SMP17 ((uint32_t)0x00E00000) /*!< SMP17[2:0] bits (Channel 17 Sample time selection) */ #define ADC_SMPR2_SMP17_0 ((uint32_t)0x00200000) /*!< Bit 0 */ #define ADC_SMPR2_SMP17_1 ((uint32_t)0x00400000) /*!< Bit 1 */ #define ADC_SMPR2_SMP17_2 ((uint32_t)0x00800000) /*!< Bit 2 */ #define ADC_SMPR2_SMP18 ((uint32_t)0x07000000) /*!< SMP18[2:0] bits (Channel 18 Sample time selection) */ #define ADC_SMPR2_SMP18_0 ((uint32_t)0x01000000) /*!< Bit 0 */ #define ADC_SMPR2_SMP18_1 ((uint32_t)0x02000000) /*!< Bit 1 */ #define ADC_SMPR2_SMP18_2 ((uint32_t)0x04000000) /*!< Bit 2 */ #define ADC_SMPR2_SMP19 ((uint32_t)0x38000000) /*!< SMP19[2:0] bits (Channel 19 Sample time selection) */ #define ADC_SMPR2_SMP19_0 ((uint32_t)0x08000000) /*!< Bit 0 */ #define ADC_SMPR2_SMP19_1 ((uint32_t)0x10000000) /*!< Bit 1 */ #define ADC_SMPR2_SMP19_2 ((uint32_t)0x20000000) /*!< Bit 2 */ /****************** Bit definition for ADC_SMPR3 register *******************/ #define ADC_SMPR3_SMP0 ((uint32_t)0x00000007) /*!< SMP0[2:0] bits (Channel 0 Sample time selection) */ #define ADC_SMPR3_SMP0_0 ((uint32_t)0x00000001) /*!< Bit 0 */ #define ADC_SMPR3_SMP0_1 ((uint32_t)0x00000002) /*!< Bit 1 */ #define ADC_SMPR3_SMP0_2 ((uint32_t)0x00000004) /*!< Bit 2 */ #define ADC_SMPR3_SMP1 ((uint32_t)0x00000038) /*!< SMP1[2:0] bits (Channel 1 Sample time selection) */ #define ADC_SMPR3_SMP1_0 ((uint32_t)0x00000008) /*!< Bit 0 */ #define ADC_SMPR3_SMP1_1 ((uint32_t)0x00000010) /*!< Bit 1 */ #define ADC_SMPR3_SMP1_2 ((uint32_t)0x00000020) /*!< Bit 2 */ #define ADC_SMPR3_SMP2 ((uint32_t)0x000001C0) /*!< SMP2[2:0] bits (Channel 2 Sample time selection) */ #define ADC_SMPR3_SMP2_0 ((uint32_t)0x00000040) /*!< Bit 0 */ #define ADC_SMPR3_SMP2_1 ((uint32_t)0x00000080) /*!< Bit 1 */ #define ADC_SMPR3_SMP2_2 ((uint32_t)0x00000100) /*!< Bit 2 */ #define ADC_SMPR3_SMP3 ((uint32_t)0x00000E00) /*!< SMP3[2:0] bits (Channel 3 Sample time selection) */ #define ADC_SMPR3_SMP3_0 ((uint32_t)0x00000200) /*!< Bit 0 */ #define ADC_SMPR3_SMP3_1 ((uint32_t)0x00000400) /*!< Bit 1 */ #define ADC_SMPR3_SMP3_2 ((uint32_t)0x00000800) /*!< Bit 2 */ #define ADC_SMPR3_SMP4 ((uint32_t)0x00007000) /*!< SMP4[2:0] bits (Channel 4 Sample time selection) */ #define ADC_SMPR3_SMP4_0 ((uint32_t)0x00001000) /*!< Bit 0 */ #define ADC_SMPR3_SMP4_1 ((uint32_t)0x00002000) /*!< Bit 1 */ #define ADC_SMPR3_SMP4_2 ((uint32_t)0x00004000) /*!< Bit 2 */ #define ADC_SMPR3_SMP5 ((uint32_t)0x00038000) /*!< SMP5[2:0] bits (Channel 5 Sample time selection) */ #define ADC_SMPR3_SMP5_0 ((uint32_t)0x00008000) /*!< Bit 0 */ #define ADC_SMPR3_SMP5_1 ((uint32_t)0x00010000) /*!< Bit 1 */ #define ADC_SMPR3_SMP5_2 ((uint32_t)0x00020000) /*!< Bit 2 */ #define ADC_SMPR3_SMP6 ((uint32_t)0x001C0000) /*!< SMP6[2:0] bits (Channel 6 Sample time selection) */ #define ADC_SMPR3_SMP6_0 ((uint32_t)0x00040000) /*!< Bit 0 */ #define ADC_SMPR3_SMP6_1 ((uint32_t)0x00080000) /*!< Bit 1 */ #define ADC_SMPR3_SMP6_2 ((uint32_t)0x00100000) /*!< Bit 2 */ #define ADC_SMPR3_SMP7 ((uint32_t)0x00E00000) /*!< SMP7[2:0] bits (Channel 7 Sample time selection) */ #define ADC_SMPR3_SMP7_0 ((uint32_t)0x00200000) /*!< Bit 0 */ #define ADC_SMPR3_SMP7_1 ((uint32_t)0x00400000) /*!< Bit 1 */ #define ADC_SMPR3_SMP7_2 ((uint32_t)0x00800000) /*!< Bit 2 */ #define ADC_SMPR3_SMP8 ((uint32_t)0x07000000) /*!< SMP8[2:0] bits (Channel 8 Sample time selection) */ #define ADC_SMPR3_SMP8_0 ((uint32_t)0x01000000) /*!< Bit 0 */ #define ADC_SMPR3_SMP8_1 ((uint32_t)0x02000000) /*!< Bit 1 */ #define ADC_SMPR3_SMP8_2 ((uint32_t)0x04000000) /*!< Bit 2 */ #define ADC_SMPR3_SMP9 ((uint32_t)0x38000000) /*!< SMP9[2:0] bits (Channel 9 Sample time selection) */ #define ADC_SMPR3_SMP9_0 ((uint32_t)0x08000000) /*!< Bit 0 */ #define ADC_SMPR3_SMP9_1 ((uint32_t)0x10000000) /*!< Bit 1 */ #define ADC_SMPR3_SMP9_2 ((uint32_t)0x20000000) /*!< Bit 2 */ /****************** Bit definition for ADC_JOFR1 register *******************/ #define ADC_JOFR1_JOFFSET1 ((uint32_t)0x00000FFF) /*!< Data offset for injected channel 1 */ /****************** Bit definition for ADC_JOFR2 register *******************/ #define ADC_JOFR2_JOFFSET2 ((uint32_t)0x00000FFF) /*!< Data offset for injected channel 2 */ /****************** Bit definition for ADC_JOFR3 register *******************/ #define ADC_JOFR3_JOFFSET3 ((uint32_t)0x00000FFF) /*!< Data offset for injected channel 3 */ /****************** Bit definition for ADC_JOFR4 register *******************/ #define ADC_JOFR4_JOFFSET4 ((uint32_t)0x00000FFF) /*!< Data offset for injected channel 4 */ /******************* Bit definition for ADC_HTR register ********************/ #define ADC_HTR_HT ((uint32_t)0x00000FFF) /*!< Analog watchdog high threshold */ /******************* Bit definition for ADC_LTR register ********************/ #define ADC_LTR_LT ((uint32_t)0x00000FFF) /*!< Analog watchdog low threshold */ /******************* Bit definition for ADC_SQR1 register *******************/ #define ADC_SQR1_L ((uint32_t)0x01F00000) /*!< L[4:0] bits (Regular channel sequence length) */ #define ADC_SQR1_L_0 ((uint32_t)0x00100000) /*!< Bit 0 */ #define ADC_SQR1_L_1 ((uint32_t)0x00200000) /*!< Bit 1 */ #define ADC_SQR1_L_2 ((uint32_t)0x00400000) /*!< Bit 2 */ #define ADC_SQR1_L_3 ((uint32_t)0x00800000) /*!< Bit 3 */ #define ADC_SQR1_L_4 ((uint32_t)0x01000000) /*!< Bit 4 */ #define ADC_SQR1_SQ28 ((uint32_t)0x000F8000) /*!< SQ28[4:0] bits (25th conversion in regular sequence) */ #define ADC_SQR1_SQ28_0 ((uint32_t)0x00008000) /*!< Bit 0 */ #define ADC_SQR1_SQ28_1 ((uint32_t)0x00010000) /*!< Bit 1 */ #define ADC_SQR1_SQ28_2 ((uint32_t)0x00020000) /*!< Bit 2 */ #define ADC_SQR1_SQ28_3 ((uint32_t)0x00040000) /*!< Bit 3 */ #define ADC_SQR1_SQ28_4 ((uint32_t)0x00080000) /*!< Bit 4 */ #define ADC_SQR1_SQ27 ((uint32_t)0x00007C00) /*!< SQ27[4:0] bits (27th conversion in regular sequence) */ #define ADC_SQR1_SQ27_0 ((uint32_t)0x00000400) /*!< Bit 0 */ #define ADC_SQR1_SQ27_1 ((uint32_t)0x00000800) /*!< Bit 1 */ #define ADC_SQR1_SQ27_2 ((uint32_t)0x00001000) /*!< Bit 2 */ #define ADC_SQR1_SQ27_3 ((uint32_t)0x00002000) /*!< Bit 3 */ #define ADC_SQR1_SQ27_4 ((uint32_t)0x00004000) /*!< Bit 4 */ #define ADC_SQR1_SQ26 ((uint32_t)0x000003E0) /*!< SQ26[4:0] bits (26th conversion in regular sequence) */ #define ADC_SQR1_SQ26_0 ((uint32_t)0x00000020) /*!< Bit 0 */ #define ADC_SQR1_SQ26_1 ((uint32_t)0x00000040) /*!< Bit 1 */ #define ADC_SQR1_SQ26_2 ((uint32_t)0x00000080) /*!< Bit 2 */ #define ADC_SQR1_SQ26_3 ((uint32_t)0x00000100) /*!< Bit 3 */ #define ADC_SQR1_SQ26_4 ((uint32_t)0x00000200) /*!< Bit 4 */ #define ADC_SQR1_SQ25 ((uint32_t)0x0000001F) /*!< SQ25[4:0] bits (25th conversion in regular sequence) */ #define ADC_SQR1_SQ25_0 ((uint32_t)0x00000001) /*!< Bit 0 */ #define ADC_SQR1_SQ25_1 ((uint32_t)0x00000002) /*!< Bit 1 */ #define ADC_SQR1_SQ25_2 ((uint32_t)0x00000004) /*!< Bit 2 */ #define ADC_SQR1_SQ25_3 ((uint32_t)0x00000008) /*!< Bit 3 */ #define ADC_SQR1_SQ25_4 ((uint32_t)0x00000010) /*!< Bit 4 */ /******************* Bit definition for ADC_SQR2 register *******************/ #define ADC_SQR2_SQ19 ((uint32_t)0x0000001F) /*!< SQ19[4:0] bits (19th conversion in regular sequence) */ #define ADC_SQR2_SQ19_0 ((uint32_t)0x00000001) /*!< Bit 0 */ #define ADC_SQR2_SQ19_1 ((uint32_t)0x00000002) /*!< Bit 1 */ #define ADC_SQR2_SQ19_2 ((uint32_t)0x00000004) /*!< Bit 2 */ #define ADC_SQR2_SQ19_3 ((uint32_t)0x00000008) /*!< Bit 3 */ #define ADC_SQR2_SQ19_4 ((uint32_t)0x00000010) /*!< Bit 4 */ #define ADC_SQR2_SQ20 ((uint32_t)0x000003E0) /*!< SQ20[4:0] bits (20th conversion in regular sequence) */ #define ADC_SQR2_SQ20_0 ((uint32_t)0x00000020) /*!< Bit 0 */ #define ADC_SQR2_SQ20_1 ((uint32_t)0x00000040) /*!< Bit 1 */ #define ADC_SQR2_SQ20_2 ((uint32_t)0x00000080) /*!< Bit 2 */ #define ADC_SQR2_SQ20_3 ((uint32_t)0x00000100) /*!< Bit 3 */ #define ADC_SQR2_SQ20_4 ((uint32_t)0x00000200) /*!< Bit 4 */ #define ADC_SQR2_SQ21 ((uint32_t)0x00007C00) /*!< SQ21[4:0] bits (21th conversion in regular sequence) */ #define ADC_SQR2_SQ21_0 ((uint32_t)0x00000400) /*!< Bit 0 */ #define ADC_SQR2_SQ21_1 ((uint32_t)0x00000800) /*!< Bit 1 */ #define ADC_SQR2_SQ21_2 ((uint32_t)0x00001000) /*!< Bit 2 */ #define ADC_SQR2_SQ21_3 ((uint32_t)0x00002000) /*!< Bit 3 */ #define ADC_SQR2_SQ21_4 ((uint32_t)0x00004000) /*!< Bit 4 */ #define ADC_SQR2_SQ22 ((uint32_t)0x000F8000) /*!< SQ22[4:0] bits (22th conversion in regular sequence) */ #define ADC_SQR2_SQ22_0 ((uint32_t)0x00008000) /*!< Bit 0 */ #define ADC_SQR2_SQ22_1 ((uint32_t)0x00010000) /*!< Bit 1 */ #define ADC_SQR2_SQ22_2 ((uint32_t)0x00020000) /*!< Bit 2 */ #define ADC_SQR2_SQ22_3 ((uint32_t)0x00040000) /*!< Bit 3 */ #define ADC_SQR2_SQ22_4 ((uint32_t)0x00080000) /*!< Bit 4 */ #define ADC_SQR2_SQ23 ((uint32_t)0x01F00000) /*!< SQ23[4:0] bits (23th conversion in regular sequence) */ #define ADC_SQR2_SQ23_0 ((uint32_t)0x00100000) /*!< Bit 0 */ #define ADC_SQR2_SQ23_1 ((uint32_t)0x00200000) /*!< Bit 1 */ #define ADC_SQR2_SQ23_2 ((uint32_t)0x00400000) /*!< Bit 2 */ #define ADC_SQR2_SQ23_3 ((uint32_t)0x00800000) /*!< Bit 3 */ #define ADC_SQR2_SQ23_4 ((uint32_t)0x01000000) /*!< Bit 4 */ #define ADC_SQR2_SQ24 ((uint32_t)0x3E000000) /*!< SQ24[4:0] bits (24th conversion in regular sequence) */ #define ADC_SQR2_SQ24_0 ((uint32_t)0x02000000) /*!< Bit 0 */ #define ADC_SQR2_SQ24_1 ((uint32_t)0x04000000) /*!< Bit 1 */ #define ADC_SQR2_SQ24_2 ((uint32_t)0x08000000) /*!< Bit 2 */ #define ADC_SQR2_SQ24_3 ((uint32_t)0x10000000) /*!< Bit 3 */ #define ADC_SQR2_SQ24_4 ((uint32_t)0x20000000) /*!< Bit 4 */ /******************* Bit definition for ADC_SQR3 register *******************/ #define ADC_SQR3_SQ13 ((uint32_t)0x0000001F) /*!< SQ13[4:0] bits (13th conversion in regular sequence) */ #define ADC_SQR3_SQ13_0 ((uint32_t)0x00000001) /*!< Bit 0 */ #define ADC_SQR3_SQ13_1 ((uint32_t)0x00000002) /*!< Bit 1 */ #define ADC_SQR3_SQ13_2 ((uint32_t)0x00000004) /*!< Bit 2 */ #define ADC_SQR3_SQ13_3 ((uint32_t)0x00000008) /*!< Bit 3 */ #define ADC_SQR3_SQ13_4 ((uint32_t)0x00000010) /*!< Bit 4 */ #define ADC_SQR3_SQ14 ((uint32_t)0x000003E0) /*!< SQ14[4:0] bits (14th conversion in regular sequence) */ #define ADC_SQR3_SQ14_0 ((uint32_t)0x00000020) /*!< Bit 0 */ #define ADC_SQR3_SQ14_1 ((uint32_t)0x00000040) /*!< Bit 1 */ #define ADC_SQR3_SQ14_2 ((uint32_t)0x00000080) /*!< Bit 2 */ #define ADC_SQR3_SQ14_3 ((uint32_t)0x00000100) /*!< Bit 3 */ #define ADC_SQR3_SQ14_4 ((uint32_t)0x00000200) /*!< Bit 4 */ #define ADC_SQR3_SQ15 ((uint32_t)0x00007C00) /*!< SQ15[4:0] bits (15th conversion in regular sequence) */ #define ADC_SQR3_SQ15_0 ((uint32_t)0x00000400) /*!< Bit 0 */ #define ADC_SQR3_SQ15_1 ((uint32_t)0x00000800) /*!< Bit 1 */ #define ADC_SQR3_SQ15_2 ((uint32_t)0x00001000) /*!< Bit 2 */ #define ADC_SQR3_SQ15_3 ((uint32_t)0x00002000) /*!< Bit 3 */ #define ADC_SQR3_SQ15_4 ((uint32_t)0x00004000) /*!< Bit 4 */ #define ADC_SQR3_SQ16 ((uint32_t)0x000F8000) /*!< SQ16[4:0] bits (16th conversion in regular sequence) */ #define ADC_SQR3_SQ16_0 ((uint32_t)0x00008000) /*!< Bit 0 */ #define ADC_SQR3_SQ16_1 ((uint32_t)0x00010000) /*!< Bit 1 */ #define ADC_SQR3_SQ16_2 ((uint32_t)0x00020000) /*!< Bit 2 */ #define ADC_SQR3_SQ16_3 ((uint32_t)0x00040000) /*!< Bit 3 */ #define ADC_SQR3_SQ16_4 ((uint32_t)0x00080000) /*!< Bit 4 */ #define ADC_SQR3_SQ17 ((uint32_t)0x01F00000) /*!< SQ17[4:0] bits (17th conversion in regular sequence) */ #define ADC_SQR3_SQ17_0 ((uint32_t)0x00100000) /*!< Bit 0 */ #define ADC_SQR3_SQ17_1 ((uint32_t)0x00200000) /*!< Bit 1 */ #define ADC_SQR3_SQ17_2 ((uint32_t)0x00400000) /*!< Bit 2 */ #define ADC_SQR3_SQ17_3 ((uint32_t)0x00800000) /*!< Bit 3 */ #define ADC_SQR3_SQ17_4 ((uint32_t)0x01000000) /*!< Bit 4 */ #define ADC_SQR3_SQ18 ((uint32_t)0x3E000000) /*!< SQ18[4:0] bits (18th conversion in regular sequence) */ #define ADC_SQR3_SQ18_0 ((uint32_t)0x02000000) /*!< Bit 0 */ #define ADC_SQR3_SQ18_1 ((uint32_t)0x04000000) /*!< Bit 1 */ #define ADC_SQR3_SQ18_2 ((uint32_t)0x08000000) /*!< Bit 2 */ #define ADC_SQR3_SQ18_3 ((uint32_t)0x10000000) /*!< Bit 3 */ #define ADC_SQR3_SQ18_4 ((uint32_t)0x20000000) /*!< Bit 4 */ /******************* Bit definition for ADC_SQR4 register *******************/ #define ADC_SQR4_SQ7 ((uint32_t)0x0000001F) /*!< SQ7[4:0] bits (7th conversion in regular sequence) */ #define ADC_SQR4_SQ7_0 ((uint32_t)0x00000001) /*!< Bit 0 */ #define ADC_SQR4_SQ7_1 ((uint32_t)0x00000002) /*!< Bit 1 */ #define ADC_SQR4_SQ7_2 ((uint32_t)0x00000004) /*!< Bit 2 */ #define ADC_SQR4_SQ7_3 ((uint32_t)0x00000008) /*!< Bit 3 */ #define ADC_SQR4_SQ7_4 ((uint32_t)0x00000010) /*!< Bit 4 */ #define ADC_SQR4_SQ8 ((uint32_t)0x000003E0) /*!< SQ8[4:0] bits (8th conversion in regular sequence) */ #define ADC_SQR4_SQ8_0 ((uint32_t)0x00000020) /*!< Bit 0 */ #define ADC_SQR4_SQ8_1 ((uint32_t)0x00000040) /*!< Bit 1 */ #define ADC_SQR4_SQ8_2 ((uint32_t)0x00000080) /*!< Bit 2 */ #define ADC_SQR4_SQ8_3 ((uint32_t)0x00000100) /*!< Bit 3 */ #define ADC_SQR4_SQ8_4 ((uint32_t)0x00000200) /*!< Bit 4 */ #define ADC_SQR4_SQ9 ((uint32_t)0x00007C00) /*!< SQ9[4:0] bits (9th conversion in regular sequence) */ #define ADC_SQR4_SQ9_0 ((uint32_t)0x00000400) /*!< Bit 0 */ #define ADC_SQR4_SQ9_1 ((uint32_t)0x00000800) /*!< Bit 1 */ #define ADC_SQR4_SQ9_2 ((uint32_t)0x00001000) /*!< Bit 2 */ #define ADC_SQR4_SQ9_3 ((uint32_t)0x00002000) /*!< Bit 3 */ #define ADC_SQR4_SQ9_4 ((uint32_t)0x00004000) /*!< Bit 4 */ #define ADC_SQR4_SQ10 ((uint32_t)0x000F8000) /*!< SQ10[4:0] bits (10th conversion in regular sequence) */ #define ADC_SQR4_SQ10_0 ((uint32_t)0x00008000) /*!< Bit 0 */ #define ADC_SQR4_SQ10_1 ((uint32_t)0x00010000) /*!< Bit 1 */ #define ADC_SQR4_SQ10_2 ((uint32_t)0x00020000) /*!< Bit 2 */ #define ADC_SQR4_SQ10_3 ((uint32_t)0x00040000) /*!< Bit 3 */ #define ADC_SQR4_SQ10_4 ((uint32_t)0x00080000) /*!< Bit 4 */ #define ADC_SQR4_SQ11 ((uint32_t)0x01F00000) /*!< SQ11[4:0] bits (11th conversion in regular sequence) */ #define ADC_SQR4_SQ11_0 ((uint32_t)0x00100000) /*!< Bit 0 */ #define ADC_SQR4_SQ11_1 ((uint32_t)0x00200000) /*!< Bit 1 */ #define ADC_SQR4_SQ11_2 ((uint32_t)0x00400000) /*!< Bit 2 */ #define ADC_SQR4_SQ11_3 ((uint32_t)0x00800000) /*!< Bit 3 */ #define ADC_SQR4_SQ11_4 ((uint32_t)0x01000000) /*!< Bit 4 */ #define ADC_SQR4_SQ12 ((uint32_t)0x3E000000) /*!< SQ12[4:0] bits (12th conversion in regular sequence) */ #define ADC_SQR4_SQ12_0 ((uint32_t)0x02000000) /*!< Bit 0 */ #define ADC_SQR4_SQ12_1 ((uint32_t)0x04000000) /*!< Bit 1 */ #define ADC_SQR4_SQ12_2 ((uint32_t)0x08000000) /*!< Bit 2 */ #define ADC_SQR4_SQ12_3 ((uint32_t)0x10000000) /*!< Bit 3 */ #define ADC_SQR4_SQ12_4 ((uint32_t)0x20000000) /*!< Bit 4 */ /******************* Bit definition for ADC_SQR5 register *******************/ #define ADC_SQR5_SQ1 ((uint32_t)0x0000001F) /*!< SQ1[4:0] bits (1st conversion in regular sequence) */ #define ADC_SQR5_SQ1_0 ((uint32_t)0x00000001) /*!< Bit 0 */ #define ADC_SQR5_SQ1_1 ((uint32_t)0x00000002) /*!< Bit 1 */ #define ADC_SQR5_SQ1_2 ((uint32_t)0x00000004) /*!< Bit 2 */ #define ADC_SQR5_SQ1_3 ((uint32_t)0x00000008) /*!< Bit 3 */ #define ADC_SQR5_SQ1_4 ((uint32_t)0x00000010) /*!< Bit 4 */ #define ADC_SQR5_SQ2 ((uint32_t)0x000003E0) /*!< SQ2[4:0] bits (2nd conversion in regular sequence) */ #define ADC_SQR5_SQ2_0 ((uint32_t)0x00000020) /*!< Bit 0 */ #define ADC_SQR5_SQ2_1 ((uint32_t)0x00000040) /*!< Bit 1 */ #define ADC_SQR5_SQ2_2 ((uint32_t)0x00000080) /*!< Bit 2 */ #define ADC_SQR5_SQ2_3 ((uint32_t)0x00000100) /*!< Bit 3 */ #define ADC_SQR5_SQ2_4 ((uint32_t)0x00000200) /*!< Bit 4 */ #define ADC_SQR5_SQ3 ((uint32_t)0x00007C00) /*!< SQ3[4:0] bits (3rd conversion in regular sequence) */ #define ADC_SQR5_SQ3_0 ((uint32_t)0x00000400) /*!< Bit 0 */ #define ADC_SQR5_SQ3_1 ((uint32_t)0x00000800) /*!< Bit 1 */ #define ADC_SQR5_SQ3_2 ((uint32_t)0x00001000) /*!< Bit 2 */ #define ADC_SQR5_SQ3_3 ((uint32_t)0x00002000) /*!< Bit 3 */ #define ADC_SQR5_SQ3_4 ((uint32_t)0x00004000) /*!< Bit 4 */ #define ADC_SQR5_SQ4 ((uint32_t)0x000F8000) /*!< SQ4[4:0] bits (4th conversion in regular sequence) */ #define ADC_SQR5_SQ4_0 ((uint32_t)0x00008000) /*!< Bit 0 */ #define ADC_SQR5_SQ4_1 ((uint32_t)0x00010000) /*!< Bit 1 */ #define ADC_SQR5_SQ4_2 ((uint32_t)0x00020000) /*!< Bit 2 */ #define ADC_SQR5_SQ4_3 ((uint32_t)0x00040000) /*!< Bit 3 */ #define ADC_SQR5_SQ4_4 ((uint32_t)0x00080000) /*!< Bit 4 */ #define ADC_SQR5_SQ5 ((uint32_t)0x01F00000) /*!< SQ5[4:0] bits (5th conversion in regular sequence) */ #define ADC_SQR5_SQ5_0 ((uint32_t)0x00100000) /*!< Bit 0 */ #define ADC_SQR5_SQ5_1 ((uint32_t)0x00200000) /*!< Bit 1 */ #define ADC_SQR5_SQ5_2 ((uint32_t)0x00400000) /*!< Bit 2 */ #define ADC_SQR5_SQ5_3 ((uint32_t)0x00800000) /*!< Bit 3 */ #define ADC_SQR5_SQ5_4 ((uint32_t)0x01000000) /*!< Bit 4 */ #define ADC_SQR5_SQ6 ((uint32_t)0x3E000000) /*!< SQ6[4:0] bits (6th conversion in regular sequence) */ #define ADC_SQR5_SQ6_0 ((uint32_t)0x02000000) /*!< Bit 0 */ #define ADC_SQR5_SQ6_1 ((uint32_t)0x04000000) /*!< Bit 1 */ #define ADC_SQR5_SQ6_2 ((uint32_t)0x08000000) /*!< Bit 2 */ #define ADC_SQR5_SQ6_3 ((uint32_t)0x10000000) /*!< Bit 3 */ #define ADC_SQR5_SQ6_4 ((uint32_t)0x20000000) /*!< Bit 4 */ /******************* Bit definition for ADC_JSQR register *******************/ #define ADC_JSQR_JSQ1 ((uint32_t)0x0000001F) /*!< JSQ1[4:0] bits (1st conversion in injected sequence) */ #define ADC_JSQR_JSQ1_0 ((uint32_t)0x00000001) /*!< Bit 0 */ #define ADC_JSQR_JSQ1_1 ((uint32_t)0x00000002) /*!< Bit 1 */ #define ADC_JSQR_JSQ1_2 ((uint32_t)0x00000004) /*!< Bit 2 */ #define ADC_JSQR_JSQ1_3 ((uint32_t)0x00000008) /*!< Bit 3 */ #define ADC_JSQR_JSQ1_4 ((uint32_t)0x00000010) /*!< Bit 4 */ #define ADC_JSQR_JSQ2 ((uint32_t)0x000003E0) /*!< JSQ2[4:0] bits (2nd conversion in injected sequence) */ #define ADC_JSQR_JSQ2_0 ((uint32_t)0x00000020) /*!< Bit 0 */ #define ADC_JSQR_JSQ2_1 ((uint32_t)0x00000040) /*!< Bit 1 */ #define ADC_JSQR_JSQ2_2 ((uint32_t)0x00000080) /*!< Bit 2 */ #define ADC_JSQR_JSQ2_3 ((uint32_t)0x00000100) /*!< Bit 3 */ #define ADC_JSQR_JSQ2_4 ((uint32_t)0x00000200) /*!< Bit 4 */ #define ADC_JSQR_JSQ3 ((uint32_t)0x00007C00) /*!< JSQ3[4:0] bits (3rd conversion in injected sequence) */ #define ADC_JSQR_JSQ3_0 ((uint32_t)0x00000400) /*!< Bit 0 */ #define ADC_JSQR_JSQ3_1 ((uint32_t)0x00000800) /*!< Bit 1 */ #define ADC_JSQR_JSQ3_2 ((uint32_t)0x00001000) /*!< Bit 2 */ #define ADC_JSQR_JSQ3_3 ((uint32_t)0x00002000) /*!< Bit 3 */ #define ADC_JSQR_JSQ3_4 ((uint32_t)0x00004000) /*!< Bit 4 */ #define ADC_JSQR_JSQ4 ((uint32_t)0x000F8000) /*!< JSQ4[4:0] bits (4th conversion in injected sequence) */ #define ADC_JSQR_JSQ4_0 ((uint32_t)0x00008000) /*!< Bit 0 */ #define ADC_JSQR_JSQ4_1 ((uint32_t)0x00010000) /*!< Bit 1 */ #define ADC_JSQR_JSQ4_2 ((uint32_t)0x00020000) /*!< Bit 2 */ #define ADC_JSQR_JSQ4_3 ((uint32_t)0x00040000) /*!< Bit 3 */ #define ADC_JSQR_JSQ4_4 ((uint32_t)0x00080000) /*!< Bit 4 */ #define ADC_JSQR_JL ((uint32_t)0x00300000) /*!< JL[1:0] bits (Injected Sequence length) */ #define ADC_JSQR_JL_0 ((uint32_t)0x00100000) /*!< Bit 0 */ #define ADC_JSQR_JL_1 ((uint32_t)0x00200000) /*!< Bit 1 */ /******************* Bit definition for ADC_JDR1 register *******************/ #define ADC_JDR1_JDATA ((uint32_t)0x0000FFFF) /*!< Injected data */ /******************* Bit definition for ADC_JDR2 register *******************/ #define ADC_JDR2_JDATA ((uint32_t)0x0000FFFF) /*!< Injected data */ /******************* Bit definition for ADC_JDR3 register *******************/ #define ADC_JDR3_JDATA ((uint32_t)0x0000FFFF) /*!< Injected data */ /******************* Bit definition for ADC_JDR4 register *******************/ #define ADC_JDR4_JDATA ((uint32_t)0x0000FFFF) /*!< Injected data */ /******************** Bit definition for ADC_DR register ********************/ #define ADC_DR_DATA ((uint32_t)0x0000FFFF) /*!< Regular data */ /****************** Bit definition for ADC_SMPR0 register *******************/ #define ADC_SMPR0_SMP30 ((uint32_t)0x00000007) /*!< SMP30[2:0] bits (Channel 30 Sample time selection) */ #define ADC_SMPR0_SMP30_0 ((uint32_t)0x00000001) /*!< Bit 0 */ #define ADC_SMPR0_SMP30_1 ((uint32_t)0x00000002) /*!< Bit 1 */ #define ADC_SMPR0_SMP30_2 ((uint32_t)0x00000004) /*!< Bit 2 */ #define ADC_SMPR0_SMP31 ((uint32_t)0x00000038) /*!< SMP31[2:0] bits (Channel 31 Sample time selection) */ #define ADC_SMPR0_SMP31_0 ((uint32_t)0x00000008) /*!< Bit 0 */ #define ADC_SMPR0_SMP31_1 ((uint32_t)0x00000010) /*!< Bit 1 */ #define ADC_SMPR0_SMP31_2 ((uint32_t)0x00000020) /*!< Bit 2 */ /******************* Bit definition for ADC_CSR register ********************/ #define ADC_CSR_AWD1 ((uint32_t)0x00000001) /*!< ADC1 Analog watchdog flag */ #define ADC_CSR_EOC1 ((uint32_t)0x00000002) /*!< ADC1 End of conversion */ #define ADC_CSR_JEOC1 ((uint32_t)0x00000004) /*!< ADC1 Injected channel end of conversion */ #define ADC_CSR_JSTRT1 ((uint32_t)0x00000008) /*!< ADC1 Injected channel Start flag */ #define ADC_CSR_STRT1 ((uint32_t)0x00000010) /*!< ADC1 Regular channel Start flag */ #define ADC_CSR_OVR1 ((uint32_t)0x00000020) /*!< ADC1 overrun flag */ #define ADC_CSR_ADONS1 ((uint32_t)0x00000040) /*!< ADON status of ADC1 */ /******************* Bit definition for ADC_CCR register ********************/ #define ADC_CCR_ADCPRE ((uint32_t)0x00030000) /*!< ADC prescaler*/ #define ADC_CCR_ADCPRE_0 ((uint32_t)0x00010000) /*!< Bit 0 */ #define ADC_CCR_ADCPRE_1 ((uint32_t)0x00020000) /*!< Bit 1 */ #define ADC_CCR_TSVREFE ((uint32_t)0x00800000) /*!< Temperature Sensor and VREFINT Enable */ /******************************************************************************/ /* */ /* Analog Comparators (COMP) */ /* */ /******************************************************************************/ /****************** Bit definition for COMP_CSR register ********************/ #define COMP_CSR_10KPU ((uint32_t)0x00000001) /*!< 10K pull-up resistor */ #define COMP_CSR_400KPU ((uint32_t)0x00000002) /*!< 400K pull-up resistor */ #define COMP_CSR_10KPD ((uint32_t)0x00000004) /*!< 10K pull-down resistor */ #define COMP_CSR_400KPD ((uint32_t)0x00000008) /*!< 400K pull-down resistor */ #define COMP_CSR_CMP1EN ((uint32_t)0x00000010) /*!< Comparator 1 enable */ #define COMP_CSR_SW1 ((uint32_t)0x00000020) /*!< SW1 analog switch enable */ #define COMP_CSR_CMP1OUT ((uint32_t)0x00000080) /*!< Comparator 1 output */ #define COMP_CSR_SPEED ((uint32_t)0x00001000) /*!< Comparator 2 speed */ #define COMP_CSR_CMP2OUT ((uint32_t)0x00002000) /*!< Comparator 2 ouput */ #define COMP_CSR_VREFOUTEN ((uint32_t)0x00010000) /*!< Comparator Vref Enable */ #define COMP_CSR_WNDWE ((uint32_t)0x00020000) /*!< Window mode enable */ #define COMP_CSR_INSEL ((uint32_t)0x001C0000) /*!< INSEL[2:0] Inversion input Selection */ #define COMP_CSR_INSEL_0 ((uint32_t)0x00040000) /*!< Bit 0 */ #define COMP_CSR_INSEL_1 ((uint32_t)0x00080000) /*!< Bit 1 */ #define COMP_CSR_INSEL_2 ((uint32_t)0x00100000) /*!< Bit 2 */ #define COMP_CSR_OUTSEL ((uint32_t)0x00E00000) /*!< OUTSEL[2:0] comparator 2 output redirection */ #define COMP_CSR_OUTSEL_0 ((uint32_t)0x00200000) /*!< Bit 0 */ #define COMP_CSR_OUTSEL_1 ((uint32_t)0x00400000) /*!< Bit 1 */ #define COMP_CSR_OUTSEL_2 ((uint32_t)0x00800000) /*!< Bit 2 */ #define COMP_CSR_FCH3 ((uint32_t)0x04000000) /*!< Bit 26 */ #define COMP_CSR_FCH8 ((uint32_t)0x08000000) /*!< Bit 27 */ #define COMP_CSR_RCH13 ((uint32_t)0x10000000) /*!< Bit 28 */ #define COMP_CSR_CAIE ((uint32_t)0x20000000) /*!< Bit 29 */ #define COMP_CSR_CAIF ((uint32_t)0x40000000) /*!< Bit 30 */ #define COMP_CSR_TSUSP ((uint32_t)0x80000000) /*!< Bit 31 */ /******************************************************************************/ /* */ /* Operational Amplifier (OPAMP) */ /* */ /******************************************************************************/ /******************* Bit definition for OPAMP_CSR register ******************/ #define OPAMP_CSR_OPA1PD ((uint32_t)0x00000001) /*!< OPAMP1 disable */ #define OPAMP_CSR_S3SEL1 ((uint32_t)0x00000002) /*!< Switch 3 for OPAMP1 Enable */ #define OPAMP_CSR_S4SEL1 ((uint32_t)0x00000004) /*!< Switch 4 for OPAMP1 Enable */ #define OPAMP_CSR_S5SEL1 ((uint32_t)0x00000008) /*!< Switch 5 for OPAMP1 Enable */ #define OPAMP_CSR_S6SEL1 ((uint32_t)0x00000010) /*!< Switch 6 for OPAMP1 Enable */ #define OPAMP_CSR_OPA1CAL_L ((uint32_t)0x00000020) /*!< OPAMP1 Offset calibration for P differential pair */ #define OPAMP_CSR_OPA1CAL_H ((uint32_t)0x00000040) /*!< OPAMP1 Offset calibration for N differential pair */ #define OPAMP_CSR_OPA1LPM ((uint32_t)0x00000080) /*!< OPAMP1 Low power enable */ #define OPAMP_CSR_OPA2PD ((uint32_t)0x00000100) /*!< OPAMP2 disable */ #define OPAMP_CSR_S3SEL2 ((uint32_t)0x00000200) /*!< Switch 3 for OPAMP2 Enable */ #define OPAMP_CSR_S4SEL2 ((uint32_t)0x00000400) /*!< Switch 4 for OPAMP2 Enable */ #define OPAMP_CSR_S5SEL2 ((uint32_t)0x00000800) /*!< Switch 5 for OPAMP2 Enable */ #define OPAMP_CSR_S6SEL2 ((uint32_t)0x00001000) /*!< Switch 6 for OPAMP2 Enable */ #define OPAMP_CSR_OPA2CAL_L ((uint32_t)0x00002000) /*!< OPAMP2 Offset calibration for P differential pair */ #define OPAMP_CSR_OPA2CAL_H ((uint32_t)0x00004000) /*!< OPAMP2 Offset calibration for N differential pair */ #define OPAMP_CSR_OPA2LPM ((uint32_t)0x00008000) /*!< OPAMP2 Low power enable */ #define OPAMP_CSR_ANAWSEL1 ((uint32_t)0x01000000) /*!< Switch ANA Enable for OPAMP1 */ #define OPAMP_CSR_ANAWSEL2 ((uint32_t)0x02000000) /*!< Switch ANA Enable for OPAMP2 */ #define OPAMP_CSR_S7SEL2 ((uint32_t)0x08000000) /*!< Switch 7 for OPAMP2 Enable */ #define OPAMP_CSR_AOP_RANGE ((uint32_t)0x10000000) /*!< Power range selection */ #define OPAMP_CSR_OPA1CALOUT ((uint32_t)0x20000000) /*!< OPAMP1 calibration output */ #define OPAMP_CSR_OPA2CALOUT ((uint32_t)0x40000000) /*!< OPAMP2 calibration output */ /******************* Bit definition for OPAMP_OTR register ******************/ #define OPAMP_OTR_AO1_OPT_OFFSET_TRIM_LOW ((uint32_t)0x0000001F) /*!< Offset trim for transistors differential pair PMOS of OPAMP1 */ #define OPAMP_OTR_AO1_OPT_OFFSET_TRIM_HIGH ((uint32_t)0x000003E0) /*!< Offset trim for transistors differential pair NMOS of OPAMP1 */ #define OPAMP_OTR_AO2_OPT_OFFSET_TRIM_LOW ((uint32_t)0x00007C00) /*!< Offset trim for transistors differential pair PMOS of OPAMP2 */ #define OPAMP_OTR_AO2_OPT_OFFSET_TRIM_HIGH ((uint32_t)0x000F8000) /*!< Offset trim for transistors differential pair NMOS of OPAMP2 */ #define OPAMP_OTR_OT_USER ((uint32_t)0x80000000) /*!< Switch to OPAMP offset user trimmed values */ /******************* Bit definition for OPAMP_LPOTR register ****************/ #define OPAMP_OTR_AO1_OPT_OFFSET_TRIM_LP_LOW ((uint32_t)0x0000001F) /*!< Offset trim for transistors differential pair PMOS of OPAMP1 */ #define OPAMP_OTR_AO1_OPT_OFFSET_TRIM_LP_HIGH ((uint32_t)0x000003E0) /*!< Offset trim for transistors differential pair NMOS of OPAMP1 */ #define OPAMP_OTR_AO2_OPT_OFFSET_TRIM_LP_LOW ((uint32_t)0x00007C00) /*!< Offset trim for transistors differential pair PMOS of OPAMP2 */ #define OPAMP_OTR_AO2_OPT_OFFSET_TRIM_LP_HIGH ((uint32_t)0x000F8000) /*!< Offset trim for transistors differential pair NMOS of OPAMP2 */ /******************************************************************************/ /* */ /* CRC calculation unit (CRC) */ /* */ /******************************************************************************/ /******************* Bit definition for CRC_DR register *********************/ #define CRC_DR_DR ((uint32_t)0xFFFFFFFF) /*!< Data register bits */ /******************* Bit definition for CRC_IDR register ********************/ #define CRC_IDR_IDR ((uint32_t)0x000000FF) /*!< General-purpose 8-bit data register bits */ /******************** Bit definition for CRC_CR register ********************/ #define CRC_CR_RESET ((uint32_t)0x00000001) /*!< RESET bit */ /******************************************************************************/ /* */ /* Digital to Analog Converter (DAC) */ /* */ /******************************************************************************/ /******************** Bit definition for DAC_CR register ********************/ #define DAC_CR_EN1 ((uint32_t)0x00000001) /*!
© COPYRIGHT(c) 2014 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. * ****************************************************************************** */ /** @addtogroup CMSIS * @{ */ /** @addtogroup stm32l1xx * @{ */ #ifndef __STM32L1XX_H #define __STM32L1XX_H #ifdef __cplusplus extern "C" { #endif /* __cplusplus */ /** @addtogroup Library_configuration_section * @{ */ /* Uncomment the line below according to the target STM32L device used in your application */ #if !defined (STM32L100xB) && !defined (STM32L100xBA) && !defined (STM32L100xC) && \ !defined (STM32L151xB) && !defined (STM32L151xBA) && !defined (STM32L151xC) && !defined (STM32L151xCA) && !defined (STM32L151xD) && !defined (STM32L151xE) && \ !defined (STM32L152xB) && !defined (STM32L152xBA) && !defined (STM32L152xC) && !defined (STM32L152xCA) && !defined (STM32L152xD) && !defined (STM32L152xE) && \ !defined (STM32L162xC) && !defined (STM32L162xCA) && !defined (STM32L162xD) && !defined (STM32L162xE) /* #define STM32L100xB */ /*!< STM32L100C6, STM32L100R and STM32L100RB Devices */ /* #define STM32L100xBA */ /*!< STM32L100C6-A, STM32L100R8-A and STM32L100RB-A Devices */ /* #define STM32L100xC */ /*!< STM32L100RC Devices */ /* #define STM32L151xB */ /*!< STM32L151C6, STM32L151R6, STM32L151C8, STM32L151R8, STM32L151V8, STM32L151CB, STM32L151RB and STM32L151VB */ /* #define STM32L151xBA */ /*!< STM32L151C6-A, STM32L151R6-A, STM32L151C8-A, STM32L151R8-A, STM32L151V8-A, STM32L151CB-A, STM32L151RB-A and STM32L151VB-A */ /* #define STM32L151xC */ /*!< STM32L151CC, STM32L151UC, STM32L151RC and STM32L151VC */ /* #define STM32L151xCA */ /*!< STM32L151RC-A, STM32L151VC-A, STM32L151QC and STM32L151ZC */ /* #define STM32L151xD */ /*!< STM32L151QD, STM32L151RD, STM32L151VD & STM32L151ZD */ /* #define STM32L151xE */ /*!< STM32L151QE, STM32L151RE, STM32L151VE and STM32L151ZE */ /* #define STM32L152xB */ /*!< STM32L152C6, STM32L152R6, STM32L152C8, STM32L152R8, STM32L152V8, STM32L152CB, STM32L152RB and STM32L152VB */ /* #define STM32L152xBA */ /*!< STM32L152C6-A, STM32L152R6-A, STM32L152C8-A, STM32L152R8-A, STM32L152V8-A, STM32L152CB-A, STM32L152RB-A and STM32L152VB-A */ /* #define STM32L152xC */ /*!< STM32L152CC, STM32L152UC, STM32L152RC and STM32L152VC */ /* #define STM32L152xCA */ /*!< STM32L152RC-A, STM32L152VC-A, STM32L152QC and STM32L152ZC */ /* #define STM32L152xD */ /*!< STM32L152QD, STM32L152RD, STM32L152VD and STM32L152ZD */ #define STM32L152xE /*!< STM32L152QE, STM32L152RE, STM32L152VE and STM32L152ZE */ /* #define STM32L162xC */ /*!< STM32L162RC and STM32L162VC */ /* #define STM32L162xCA */ /*!< STM32L162RC-A, STM32L162VC-A, STM32L162QC and STM32L162ZC */ /* #define STM32L162xD */ /*!< STM32L162QD, STM32L162RD, STM32L162VD and STM32L162ZD */ /* #define STM32L162xE */ /*!< STM32L162RE, STM32L162VE and STM32L162ZE */ #endif /* Tip: To avoid modifying this file each time you need to switch between these devices, you can define the device in your toolchain compiler preprocessor. */ #if !defined (USE_HAL_DRIVER) /** * @brief Comment the line below if you will not use the peripherals drivers. In this case, these drivers will not be included and the application code will be based on direct access to peripherals registers */ #define USE_HAL_DRIVER #endif /* USE_HAL_DRIVER */ /** * @brief CMSIS Device version number V2.0.0 */ #define __STM32L1xx_CMSIS_DEVICE_VERSION_MAIN (0x02) /*!< [31:24] main version */ #define __STM32L1xx_CMSIS_DEVICE_VERSION_SUB1 (0x00) /*!< [23:16] sub1 version */ #define __STM32L1xx_CMSIS_DEVICE_VERSION_SUB2 (0x00) /*!< [15:8] sub2 version */ #define __STM32L1xx_CMSIS_DEVICE_VERSION_RC (0x00) /*!< [7:0] release candidate */ #define __STM32L1xx_CMSIS_DEVICE_VERSION ((__CMSIS_DEVICE_VERSION_MAIN << 24)\ |(__CMSIS_DEVICE_HAL_VERSION_SUB1 << 16)\ |(__CMSIS_DEVICE_HAL_VERSION_SUB2 << 8 )\ |(__CMSIS_DEVICE_HAL_VERSION_RC)) /** * @} */ /** @addtogroup Device_Included * @{ */ #if defined(STM32L100xB) #include "stm32l100xb.h" #elif defined(STM32L100xBA) #include "stm32l100xba.h" #elif defined(STM32L100xC) #include "stm32l100xc.h" #elif defined(STM32L151xB) #include "stm32l151xb.h" #elif defined(STM32L151xBA) #include "stm32l151xba.h" #elif defined(STM32L151xC) #include "stm32l151xc.h" #elif defined(STM32L151xCA) #include "stm32l151xca.h" #elif defined(STM32L151xD) #include "stm32l151xd.h" #elif defined(STM32L151xE) #include "stm32l151xe.h" #elif defined(STM32L152xB) #include "stm32l152xb.h" #elif defined(STM32L152xBA) #include "stm32l152xba.h" #elif defined(STM32L152xC) #include "stm32l152xc.h" #elif defined(STM32L152xCA) #include "stm32l152xca.h" #elif defined(STM32L152xD) #include "stm32l152xd.h" #elif defined(STM32L152xE) #include "stm32l152xe.h" #elif defined(STM32L162xC) #include "stm32l162xc.h" #elif defined(STM32L162xCA) #include "stm32l162xca.h" #elif defined(STM32L162xD) #include "stm32l162xd.h" #elif defined(STM32L162xE) #include "stm32l162xe.h" #else #error "Please select first the target STM32L1xx device used in your application (in stm32l1xx.h file)" #endif /** * @} */ /** @addtogroup Exported_types * @{ */ typedef enum { RESET = 0, SET = !RESET } FlagStatus, ITStatus; typedef enum { DISABLE = 0, ENABLE = !DISABLE } FunctionalState; #define IS_FUNCTIONAL_STATE(STATE) (((STATE) == DISABLE) || ((STATE) == ENABLE)) typedef enum { ERROR = 0, SUCCESS = !ERROR } ErrorStatus; /** * @} */ /** @addtogroup Exported_macros * @{ */ #define SET_BIT(REG, BIT) ((REG) |= (BIT)) #define CLEAR_BIT(REG, BIT) ((REG) &= ~(BIT)) #define READ_BIT(REG, BIT) ((REG) & (BIT)) #define CLEAR_REG(REG) ((REG) = (0x0)) #define WRITE_REG(REG, VAL) ((REG) = (VAL)) #define READ_REG(REG) ((REG)) #define MODIFY_REG(REG, CLEARMASK, SETMASK) WRITE_REG((REG), (((READ_REG(REG)) & (~(CLEARMASK))) | (SETMASK))) #define POSITION_VAL(VAL) (__CLZ(__RBIT(VAL))) /** * @} */ #if defined (USE_HAL_DRIVER) #include "stm32l1xx_hal.h" #endif /* USE_HAL_DRIVER */ #ifdef __cplusplus } #endif /* __cplusplus */ #endif /* __STM32L1xx_H */ /** * @} */ /** * @} */ /************************ (C) COPYRIGHT STMicroelectronics *****END OF FILE****/ ================================================ FILE: Zelig/mbed/TARGET_NUCLEO_L152RE/stm32l1xx_hal.h ================================================ /** ****************************************************************************** * @file stm32l1xx_hal.h * @author MCD Application Team * @version V1.0.0 * @date 5-September-2014 * @brief This file contains all the functions prototypes for the HAL * module driver. ****************************************************************************** * @attention * *

© COPYRIGHT(c) 2014 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. * ****************************************************************************** */ /* Define to prevent recursive inclusion -------------------------------------*/ #ifndef __STM32L1xx_HAL_H #define __STM32L1xx_HAL_H #ifdef __cplusplus extern "C" { #endif /* Includes ------------------------------------------------------------------*/ #include "stm32l1xx_hal_conf.h" /** @addtogroup STM32L1xx_HAL_Driver * @{ */ /** @addtogroup HAL * @{ */ /* Exported types ------------------------------------------------------------*/ /* Exported constants --------------------------------------------------------*/ /** @defgroup HAL_Exported_Constants HAL Exported Constants * @{ */ /** @defgroup SYSCFG_Constants SYSCFG: SYStem ConFiG * @{ */ /** @defgroup SYSCFG_BootMode Boot Mode * @{ */ #define SYSCFG_BOOT_MAINFLASH ((uint32_t)0x00000000) #define SYSCFG_BOOT_SYSTEMFLASH ((uint32_t)SYSCFG_MEMRMP_BOOT_MODE_0) #if defined(FSMC_R_BASE) #define SYSCFG_BOOT_FSMC ((uint32_t)SYSCFG_MEMRMP_BOOT_MODE_1) #endif /* FSMC_R_BASE */ #define SYSCFG_BOOT_SRAM ((uint32_t)SYSCFG_MEMRMP_BOOT_MODE) /** * @} */ /** * @} */ /** @defgroup RI_Constants RI: Routing Interface * @{ */ /** @defgroup RI_InputCapture Input Capture * @{ */ #define RI_INPUTCAPTURE_IC1 RI_ICR_IC1 /*!< Input Capture 1 */ #define RI_INPUTCAPTURE_IC2 RI_ICR_IC2 /*!< Input Capture 2 */ #define RI_INPUTCAPTURE_IC3 RI_ICR_IC3 /*!< Input Capture 3 */ #define RI_INPUTCAPTURE_IC4 RI_ICR_IC4 /*!< Input Capture 4 */ /** * @} */ /** @defgroup TIM_Select TIM Select * @{ */ #define TIM_SELECT_NONE ((uint32_t)0x00000000) /*!< None selected */ #define TIM_SELECT_TIM2 ((uint32_t)RI_ICR_TIM_0) /*!< Timer 2 selected */ #define TIM_SELECT_TIM3 ((uint32_t)RI_ICR_TIM_1) /*!< Timer 3 selected */ #define TIM_SELECT_TIM4 ((uint32_t)RI_ICR_TIM) /*!< Timer 4 selected */ #define IS_RI_TIM(__TIM__) (((__TIM__) == TIM_SELECT_NONE) || \ ((__TIM__) == TIM_SELECT_TIM2) || \ ((__TIM__) == TIM_SELECT_TIM3) || \ ((__TIM__) == TIM_SELECT_TIM4)) /** * @} */ /** @defgroup RI_InputCaptureRouting Input Capture Routing * @{ */ /* TIMx_IC1 TIMx_IC2 TIMx_IC3 TIMx_IC4 */ #define RI_INPUTCAPTUREROUTING_0 ((uint32_t)0x00000000) /* PA0 PA1 PA2 PA3 */ #define RI_INPUTCAPTUREROUTING_1 ((uint32_t)0x00000001) /* PA4 PA5 PA6 PA7 */ #define RI_INPUTCAPTUREROUTING_2 ((uint32_t)0x00000002) /* PA8 PA9 PA10 PA11 */ #define RI_INPUTCAPTUREROUTING_3 ((uint32_t)0x00000003) /* PA12 PA13 PA14 PA15 */ #define RI_INPUTCAPTUREROUTING_4 ((uint32_t)0x00000004) /* PC0 PC1 PC2 PC3 */ #define RI_INPUTCAPTUREROUTING_5 ((uint32_t)0x00000005) /* PC4 PC5 PC6 PC7 */ #define RI_INPUTCAPTUREROUTING_6 ((uint32_t)0x00000006) /* PC8 PC9 PC10 PC11 */ #define RI_INPUTCAPTUREROUTING_7 ((uint32_t)0x00000007) /* PC12 PC13 PC14 PC15 */ #define RI_INPUTCAPTUREROUTING_8 ((uint32_t)0x00000008) /* PD0 PD1 PD2 PD3 */ #define RI_INPUTCAPTUREROUTING_9 ((uint32_t)0x00000009) /* PD4 PD5 PD6 PD7 */ #define RI_INPUTCAPTUREROUTING_10 ((uint32_t)0x0000000A) /* PD8 PD9 PD10 PD11 */ #define RI_INPUTCAPTUREROUTING_11 ((uint32_t)0x0000000B) /* PD12 PD13 PD14 PD15 */ #define RI_INPUTCAPTUREROUTING_12 ((uint32_t)0x0000000C) /* PE0 PE1 PE2 PE3 */ #define RI_INPUTCAPTUREROUTING_13 ((uint32_t)0x0000000D) /* PE4 PE5 PE6 PE7 */ #define RI_INPUTCAPTUREROUTING_14 ((uint32_t)0x0000000E) /* PE8 PE9 PE10 PE11 */ #define RI_INPUTCAPTUREROUTING_15 ((uint32_t)0x0000000F) /* PE12 PE13 PE14 PE15 */ #define IS_RI_INPUTCAPTURE_ROUTING(__ROUTING__) (((__ROUTING__) == RI_INPUTCAPTUREROUTING_0) || \ ((__ROUTING__) == RI_INPUTCAPTUREROUTING_1) || \ ((__ROUTING__) == RI_INPUTCAPTUREROUTING_2) || \ ((__ROUTING__) == RI_INPUTCAPTUREROUTING_3) || \ ((__ROUTING__) == RI_INPUTCAPTUREROUTING_4) || \ ((__ROUTING__) == RI_INPUTCAPTUREROUTING_5) || \ ((__ROUTING__) == RI_INPUTCAPTUREROUTING_6) || \ ((__ROUTING__) == RI_INPUTCAPTUREROUTING_7) || \ ((__ROUTING__) == RI_INPUTCAPTUREROUTING_8) || \ ((__ROUTING__) == RI_INPUTCAPTUREROUTING_9) || \ ((__ROUTING__) == RI_INPUTCAPTUREROUTING_10) || \ ((__ROUTING__) == RI_INPUTCAPTUREROUTING_11) || \ ((__ROUTING__) == RI_INPUTCAPTUREROUTING_12) || \ ((__ROUTING__) == RI_INPUTCAPTUREROUTING_13) || \ ((__ROUTING__) == RI_INPUTCAPTUREROUTING_14) || \ ((__ROUTING__) == RI_INPUTCAPTUREROUTING_15)) /** * @} */ /** @defgroup RI_IOSwitch IO Switch * @{ */ #define RI_ASCR1_REGISTER ((uint32_t)0x80000000) /* ASCR1 I/O switch: bit 31 is set to '1' to indicate that the mask is in ASCR1 register */ #define RI_IOSWITCH_CH0 ((uint32_t)RI_ASCR1_REGISTER | RI_ASCR1_CH_0) #define RI_IOSWITCH_CH1 ((uint32_t)RI_ASCR1_REGISTER | RI_ASCR1_CH_1) #define RI_IOSWITCH_CH2 ((uint32_t)RI_ASCR1_REGISTER | RI_ASCR1_CH_2) #define RI_IOSWITCH_CH3 ((uint32_t)RI_ASCR1_REGISTER | RI_ASCR1_CH_3) #define RI_IOSWITCH_CH4 ((uint32_t)RI_ASCR1_REGISTER | RI_ASCR1_CH_4) #define RI_IOSWITCH_CH5 ((uint32_t)RI_ASCR1_REGISTER | RI_ASCR1_CH_5) #define RI_IOSWITCH_CH6 ((uint32_t)RI_ASCR1_REGISTER | RI_ASCR1_CH_6) #define RI_IOSWITCH_CH7 ((uint32_t)RI_ASCR1_REGISTER | RI_ASCR1_CH_7) #define RI_IOSWITCH_CH8 ((uint32_t)RI_ASCR1_REGISTER | RI_ASCR1_CH_8) #define RI_IOSWITCH_CH9 ((uint32_t)RI_ASCR1_REGISTER | RI_ASCR1_CH_9) #define RI_IOSWITCH_CH10 ((uint32_t)RI_ASCR1_REGISTER | RI_ASCR1_CH_10) #define RI_IOSWITCH_CH11 ((uint32_t)RI_ASCR1_REGISTER | RI_ASCR1_CH_11) #define RI_IOSWITCH_CH12 ((uint32_t)RI_ASCR1_REGISTER | RI_ASCR1_CH_12) #define RI_IOSWITCH_CH13 ((uint32_t)RI_ASCR1_REGISTER | RI_ASCR1_CH_13) #define RI_IOSWITCH_CH14 ((uint32_t)RI_ASCR1_REGISTER | RI_ASCR1_CH_14) #define RI_IOSWITCH_CH15 ((uint32_t)RI_ASCR1_REGISTER | RI_ASCR1_CH_15) #define RI_IOSWITCH_CH18 ((uint32_t)RI_ASCR1_REGISTER | RI_ASCR1_CH_18) #define RI_IOSWITCH_CH19 ((uint32_t)RI_ASCR1_REGISTER | RI_ASCR1_CH_19) #define RI_IOSWITCH_CH20 ((uint32_t)RI_ASCR1_REGISTER | RI_ASCR1_CH_20) #define RI_IOSWITCH_CH21 ((uint32_t)RI_ASCR1_REGISTER | RI_ASCR1_CH_21) #define RI_IOSWITCH_CH22 ((uint32_t)RI_ASCR1_REGISTER | RI_ASCR1_CH_22) #define RI_IOSWITCH_CH23 ((uint32_t)RI_ASCR1_REGISTER | RI_ASCR1_CH_23) #define RI_IOSWITCH_CH24 ((uint32_t)RI_ASCR1_REGISTER | RI_ASCR1_CH_24) #define RI_IOSWITCH_CH25 ((uint32_t)RI_ASCR1_REGISTER | RI_ASCR1_CH_25) #define RI_IOSWITCH_VCOMP ((uint32_t)RI_ASCR1_REGISTER | RI_ASCR1_VCOMP) /* VCOMP (ADC channel 26) is an internal switch used to connect selected channel to COMP1 non inverting input */ #if defined (RI_ASCR2_CH1b) /* STM32L1 devices category Cat.4 and Cat.5 */ #define RI_IOSWITCH_CH27 ((uint32_t)RI_ASCR1_REGISTER | RI_ASCR1_CH_27) #define RI_IOSWITCH_CH28 ((uint32_t)RI_ASCR1_REGISTER | RI_ASCR1_CH_28) #define RI_IOSWITCH_CH29 ((uint32_t)RI_ASCR1_REGISTER | RI_ASCR1_CH_29) #define RI_IOSWITCH_CH30 ((uint32_t)RI_ASCR1_REGISTER | RI_ASCR1_CH_30) #define RI_IOSWITCH_CH31 ((uint32_t)RI_ASCR1_REGISTER | RI_ASCR1_CH_31) #endif /* RI_ASCR2_CH1b */ /* ASCR2 IO switch: bit 31 is set to '0' to indicate that the mask is in ASCR2 register */ #define RI_IOSWITCH_GR10_1 ((uint32_t)RI_ASCR2_GR10_1) #define RI_IOSWITCH_GR10_2 ((uint32_t)RI_ASCR2_GR10_2) #define RI_IOSWITCH_GR10_3 ((uint32_t)RI_ASCR2_GR10_3) #define RI_IOSWITCH_GR10_4 ((uint32_t)RI_ASCR2_GR10_4) #define RI_IOSWITCH_GR6_1 ((uint32_t)RI_ASCR2_GR6_1) #define RI_IOSWITCH_GR6_2 ((uint32_t)RI_ASCR2_GR6_2) #define RI_IOSWITCH_GR5_1 ((uint32_t)RI_ASCR2_GR5_1) #define RI_IOSWITCH_GR5_2 ((uint32_t)RI_ASCR2_GR5_2) #define RI_IOSWITCH_GR5_3 ((uint32_t)RI_ASCR2_GR5_3) #define RI_IOSWITCH_GR4_1 ((uint32_t)RI_ASCR2_GR4_1) #define RI_IOSWITCH_GR4_2 ((uint32_t)RI_ASCR2_GR4_2) #define RI_IOSWITCH_GR4_3 ((uint32_t)RI_ASCR2_GR4_3) #if defined (RI_ASCR2_CH0b) /* STM32L1 devices category Cat.3, Cat.4 and Cat.5 */ #define RI_IOSWITCH_CH0b ((uint32_t)RI_ASCR2_CH0b) #if defined (RI_ASCR2_CH1b) /* STM32L1 devices category Cat.4 and Cat.5 */ #define RI_IOSWITCH_CH1b ((uint32_t)RI_ASCR2_CH1b) #define RI_IOSWITCH_CH2b ((uint32_t)RI_ASCR2_CH2b) #define RI_IOSWITCH_CH3b ((uint32_t)RI_ASCR2_CH3b) #define RI_IOSWITCH_CH6b ((uint32_t)RI_ASCR2_CH6b) #define RI_IOSWITCH_CH7b ((uint32_t)RI_ASCR2_CH7b) #define RI_IOSWITCH_CH8b ((uint32_t)RI_ASCR2_CH8b) #define RI_IOSWITCH_CH9b ((uint32_t)RI_ASCR2_CH9b) #define RI_IOSWITCH_CH10b ((uint32_t)RI_ASCR2_CH10b) #define RI_IOSWITCH_CH11b ((uint32_t)RI_ASCR2_CH11b) #define RI_IOSWITCH_CH12b ((uint32_t)RI_ASCR2_CH12b) #endif /* RI_ASCR2_CH1b */ #define RI_IOSWITCH_GR6_3 ((uint32_t)RI_ASCR2_GR6_3) #define RI_IOSWITCH_GR6_4 ((uint32_t)RI_ASCR2_GR6_4) #endif /* RI_ASCR2_CH0b */ #if defined (RI_ASCR2_CH1b) /* STM32L1 devices category Cat.4 and Cat.5 */ #define IS_RI_IOSWITCH(__IOSWITCH__) (((__IOSWITCH__) == RI_IOSWITCH_CH0) || ((__IOSWITCH__) == RI_IOSWITCH_CH1) || \ ((__IOSWITCH__) == RI_IOSWITCH_CH2) || ((__IOSWITCH__) == RI_IOSWITCH_CH3) || \ ((__IOSWITCH__) == RI_IOSWITCH_CH4) || ((__IOSWITCH__) == RI_IOSWITCH_CH5) || \ ((__IOSWITCH__) == RI_IOSWITCH_CH6) || ((__IOSWITCH__) == RI_IOSWITCH_CH7) || \ ((__IOSWITCH__) == RI_IOSWITCH_CH8) || ((__IOSWITCH__) == RI_IOSWITCH_CH9) || \ ((__IOSWITCH__) == RI_IOSWITCH_CH10) || ((__IOSWITCH__) == RI_IOSWITCH_CH11) || \ ((__IOSWITCH__) == RI_IOSWITCH_CH12) || ((__IOSWITCH__) == RI_IOSWITCH_CH13) || \ ((__IOSWITCH__) == RI_IOSWITCH_CH14) || ((__IOSWITCH__) == RI_IOSWITCH_CH15) || \ ((__IOSWITCH__) == RI_IOSWITCH_CH18) || ((__IOSWITCH__) == RI_IOSWITCH_CH19) || \ ((__IOSWITCH__) == RI_IOSWITCH_CH20) || ((__IOSWITCH__) == RI_IOSWITCH_CH21) || \ ((__IOSWITCH__) == RI_IOSWITCH_CH22) || ((__IOSWITCH__) == RI_IOSWITCH_CH23) || \ ((__IOSWITCH__) == RI_IOSWITCH_CH24) || ((__IOSWITCH__) == RI_IOSWITCH_CH25) || \ ((__IOSWITCH__) == RI_IOSWITCH_VCOMP) || ((__IOSWITCH__) == RI_IOSWITCH_CH27) || \ ((__IOSWITCH__) == RI_IOSWITCH_CH28) || ((__IOSWITCH__) == RI_IOSWITCH_CH29) || \ ((__IOSWITCH__) == RI_IOSWITCH_CH30) || ((__IOSWITCH__) == RI_IOSWITCH_CH31) || \ ((__IOSWITCH__) == RI_IOSWITCH_GR10_1) || ((__IOSWITCH__) == RI_IOSWITCH_GR10_2) || \ ((__IOSWITCH__) == RI_IOSWITCH_GR10_3) || ((__IOSWITCH__) == RI_IOSWITCH_GR10_4) || \ ((__IOSWITCH__) == RI_IOSWITCH_GR6_1) || ((__IOSWITCH__) == RI_IOSWITCH_GR6_2) || \ ((__IOSWITCH__) == RI_IOSWITCH_GR6_3) || ((__IOSWITCH__) == RI_IOSWITCH_GR6_4) || \ ((__IOSWITCH__) == RI_IOSWITCH_GR5_1) || ((__IOSWITCH__) == RI_IOSWITCH_GR5_2) || \ ((__IOSWITCH__) == RI_IOSWITCH_GR5_3) || ((__IOSWITCH__) == RI_IOSWITCH_GR4_1) || \ ((__IOSWITCH__) == RI_IOSWITCH_GR4_2) || ((__IOSWITCH__) == RI_IOSWITCH_GR4_3) || \ ((__IOSWITCH__) == RI_IOSWITCH_CH0b) || ((__IOSWITCH__) == RI_IOSWITCH_CH1b) || \ ((__IOSWITCH__) == RI_IOSWITCH_CH2b) || ((__IOSWITCH__) == RI_IOSWITCH_CH3b) || \ ((__IOSWITCH__) == RI_IOSWITCH_CH6b) || ((__IOSWITCH__) == RI_IOSWITCH_CH7b) || \ ((__IOSWITCH__) == RI_IOSWITCH_CH8b) || ((__IOSWITCH__) == RI_IOSWITCH_CH9b) || \ ((__IOSWITCH__) == RI_IOSWITCH_CH10b) || ((__IOSWITCH__) == RI_IOSWITCH_CH11b) || \ ((__IOSWITCH__) == RI_IOSWITCH_CH12b)) #else /* !RI_ASCR2_CH1b */ #if defined (RI_ASCR2_CH0b) /* STM32L1 devices category Cat.3 */ #define IS_RI_IOSWITCH(__IOSWITCH__) (((__IOSWITCH__) == RI_IOSWITCH_CH0) || ((__IOSWITCH__) == RI_IOSWITCH_CH1) || \ ((__IOSWITCH__) == RI_IOSWITCH_CH2) || ((__IOSWITCH__) == RI_IOSWITCH_CH3) || \ ((__IOSWITCH__) == RI_IOSWITCH_CH4) || ((__IOSWITCH__) == RI_IOSWITCH_CH5) || \ ((__IOSWITCH__) == RI_IOSWITCH_CH6) || ((__IOSWITCH__) == RI_IOSWITCH_CH7) || \ ((__IOSWITCH__) == RI_IOSWITCH_CH8) || ((__IOSWITCH__) == RI_IOSWITCH_CH9) || \ ((__IOSWITCH__) == RI_IOSWITCH_CH10) || ((__IOSWITCH__) == RI_IOSWITCH_CH11) || \ ((__IOSWITCH__) == RI_IOSWITCH_CH12) || ((__IOSWITCH__) == RI_IOSWITCH_CH13) || \ ((__IOSWITCH__) == RI_IOSWITCH_CH14) || ((__IOSWITCH__) == RI_IOSWITCH_CH15) || \ ((__IOSWITCH__) == RI_IOSWITCH_CH18) || ((__IOSWITCH__) == RI_IOSWITCH_CH19) || \ ((__IOSWITCH__) == RI_IOSWITCH_CH20) || ((__IOSWITCH__) == RI_IOSWITCH_CH21) || \ ((__IOSWITCH__) == RI_IOSWITCH_CH22) || ((__IOSWITCH__) == RI_IOSWITCH_CH23) || \ ((__IOSWITCH__) == RI_IOSWITCH_CH24) || ((__IOSWITCH__) == RI_IOSWITCH_CH25) || \ ((__IOSWITCH__) == RI_IOSWITCH_VCOMP) || ((__IOSWITCH__) == RI_IOSWITCH_GR10_1) || \ ((__IOSWITCH__) == RI_IOSWITCH_GR10_2) || ((__IOSWITCH__) == RI_IOSWITCH_GR10_3) || \ ((__IOSWITCH__) == RI_IOSWITCH_GR10_4) || ((__IOSWITCH__) == RI_IOSWITCH_GR6_1) || \ ((__IOSWITCH__) == RI_IOSWITCH_GR6_2) || ((__IOSWITCH__) == RI_IOSWITCH_GR5_1) || \ ((__IOSWITCH__) == RI_IOSWITCH_GR5_2) || ((__IOSWITCH__) == RI_IOSWITCH_GR5_3) || \ ((__IOSWITCH__) == RI_IOSWITCH_GR4_1) || ((__IOSWITCH__) == RI_IOSWITCH_GR4_2) || \ ((__IOSWITCH__) == RI_IOSWITCH_GR4_3) || ((__IOSWITCH__) == RI_IOSWITCH_CH0b)) #else /* !RI_ASCR2_CH0b */ /* STM32L1 devices category Cat.1 and Cat.2 */ #define IS_RI_IOSWITCH(__IOSWITCH__) (((__IOSWITCH__) == RI_IOSWITCH_CH0) || ((__IOSWITCH__) == RI_IOSWITCH_CH1) || \ ((__IOSWITCH__) == RI_IOSWITCH_CH2) || ((__IOSWITCH__) == RI_IOSWITCH_CH3) || \ ((__IOSWITCH__) == RI_IOSWITCH_CH4) || ((__IOSWITCH__) == RI_IOSWITCH_CH5) || \ ((__IOSWITCH__) == RI_IOSWITCH_CH6) || ((__IOSWITCH__) == RI_IOSWITCH_CH7) || \ ((__IOSWITCH__) == RI_IOSWITCH_CH8) || ((__IOSWITCH__) == RI_IOSWITCH_CH9) || \ ((__IOSWITCH__) == RI_IOSWITCH_CH10) || ((__IOSWITCH__) == RI_IOSWITCH_CH11) || \ ((__IOSWITCH__) == RI_IOSWITCH_CH12) || ((__IOSWITCH__) == RI_IOSWITCH_CH13) || \ ((__IOSWITCH__) == RI_IOSWITCH_CH14) || ((__IOSWITCH__) == RI_IOSWITCH_CH15) || \ ((__IOSWITCH__) == RI_IOSWITCH_CH18) || ((__IOSWITCH__) == RI_IOSWITCH_CH19) || \ ((__IOSWITCH__) == RI_IOSWITCH_CH20) || ((__IOSWITCH__) == RI_IOSWITCH_CH21) || \ ((__IOSWITCH__) == RI_IOSWITCH_CH22) || ((__IOSWITCH__) == RI_IOSWITCH_CH23) || \ ((__IOSWITCH__) == RI_IOSWITCH_CH24) || ((__IOSWITCH__) == RI_IOSWITCH_CH25) || \ ((__IOSWITCH__) == RI_IOSWITCH_VCOMP) || ((__IOSWITCH__) == RI_IOSWITCH_GR10_1) || \ ((__IOSWITCH__) == RI_IOSWITCH_GR10_2) || ((__IOSWITCH__) == RI_IOSWITCH_GR10_3) || \ ((__IOSWITCH__) == RI_IOSWITCH_GR10_4) || ((__IOSWITCH__) == RI_IOSWITCH_GR6_1) || \ ((__IOSWITCH__) == RI_IOSWITCH_GR6_2) || ((__IOSWITCH__) == RI_IOSWITCH_GR5_1) || \ ((__IOSWITCH__) == RI_IOSWITCH_GR5_2) || ((__IOSWITCH__) == RI_IOSWITCH_GR5_3) || \ ((__IOSWITCH__) == RI_IOSWITCH_GR4_1) || ((__IOSWITCH__) == RI_IOSWITCH_GR4_2) || \ ((__IOSWITCH__) == RI_IOSWITCH_GR4_3)) #endif /* RI_ASCR2_CH0b */ #endif /* RI_ASCR2_CH1b */ /** * @} */ /** @defgroup RI_Pin PIN define * @{ */ #define RI_PIN_0 ((uint16_t)0x0001) /*!< Pin 0 selected */ #define RI_PIN_1 ((uint16_t)0x0002) /*!< Pin 1 selected */ #define RI_PIN_2 ((uint16_t)0x0004) /*!< Pin 2 selected */ #define RI_PIN_3 ((uint16_t)0x0008) /*!< Pin 3 selected */ #define RI_PIN_4 ((uint16_t)0x0010) /*!< Pin 4 selected */ #define RI_PIN_5 ((uint16_t)0x0020) /*!< Pin 5 selected */ #define RI_PIN_6 ((uint16_t)0x0040) /*!< Pin 6 selected */ #define RI_PIN_7 ((uint16_t)0x0080) /*!< Pin 7 selected */ #define RI_PIN_8 ((uint16_t)0x0100) /*!< Pin 8 selected */ #define RI_PIN_9 ((uint16_t)0x0200) /*!< Pin 9 selected */ #define RI_PIN_10 ((uint16_t)0x0400) /*!< Pin 10 selected */ #define RI_PIN_11 ((uint16_t)0x0800) /*!< Pin 11 selected */ #define RI_PIN_12 ((uint16_t)0x1000) /*!< Pin 12 selected */ #define RI_PIN_13 ((uint16_t)0x2000) /*!< Pin 13 selected */ #define RI_PIN_14 ((uint16_t)0x4000) /*!< Pin 14 selected */ #define RI_PIN_15 ((uint16_t)0x8000) /*!< Pin 15 selected */ #define RI_PIN_ALL ((uint16_t)0xFFFF) /*!< All pins selected */ #define IS_RI_PIN(__PIN__) ((__PIN__) != (uint16_t)0x00) /** * @} */ /** * @} */ /** * @} */ /* Exported macro ------------------------------------------------------------*/ /** @defgroup HAL_Exported_Macros HAL Exported Macros * @{ */ /** @defgroup DBGMCU_Macros DBGMCU: Debug MCU * @{ */ /** @defgroup DBGMCU_Freeze_Unfreeze Freeze Unfreeze Peripherals in Debug mode * @brief Freeze/Unfreeze Peripherals in Debug mode * @{ */ /** * @brief TIM2 Peripherals Debug mode */ #if defined (DBGMCU_APB1_FZ_DBG_TIM2_STOP) #define __HAL_FREEZE_TIM2_DBGMCU() SET_BIT(DBGMCU->APB1FZ, DBGMCU_APB1_FZ_DBG_TIM2_STOP) #define __HAL_UNFREEZE_TIM2_DBGMCU() CLEAR_BIT(DBGMCU->APB1FZ, DBGMCU_APB1_FZ_DBG_TIM2_STOP) #endif /** * @brief TIM3 Peripherals Debug mode */ #if defined (DBGMCU_APB1_FZ_DBG_TIM3_STOP) #define __HAL_FREEZE_TIM3_DBGMCU() SET_BIT(DBGMCU->APB1FZ, DBGMCU_APB1_FZ_DBG_TIM3_STOP) #define __HAL_UNFREEZE_TIM3_DBGMCU() CLEAR_BIT(DBGMCU->APB1FZ, DBGMCU_APB1_FZ_DBG_TIM3_STOP) #endif /** * @brief TIM4 Peripherals Debug mode */ #if defined (DBGMCU_APB1_FZ_DBG_TIM4_STOP) #define __HAL_FREEZE_TIM4_DBGMCU() SET_BIT(DBGMCU->APB1FZ, DBGMCU_APB1_FZ_DBG_TIM4_STOP) #define __HAL_UNFREEZE_TIM4_DBGMCU() CLEAR_BIT(DBGMCU->APB1FZ, DBGMCU_APB1_FZ_DBG_TIM4_STOP) #endif /** * @brief TIM5 Peripherals Debug mode */ #if defined (DBGMCU_APB1_FZ_DBG_TIM5_STOP) #define __HAL_FREEZE_TIM5_DBGMCU() SET_BIT(DBGMCU->APB1FZ, DBGMCU_APB1_FZ_DBG_TIM5_STOP) #define __HAL_UNFREEZE_TIM5_DBGMCU() CLEAR_BIT(DBGMCU->APB1FZ, DBGMCU_APB1_FZ_DBG_TIM5_STOP) #endif /** * @brief TIM6 Peripherals Debug mode */ #if defined (DBGMCU_APB1_FZ_DBG_TIM6_STOP) #define __HAL_FREEZE_TIM6_DBGMCU() SET_BIT(DBGMCU->APB1FZ, DBGMCU_APB1_FZ_DBG_TIM6_STOP) #define __HAL_UNFREEZE_TIM6_DBGMCU() CLEAR_BIT(DBGMCU->APB1FZ, DBGMCU_APB1_FZ_DBG_TIM6_STOP) #endif /** * @brief TIM7 Peripherals Debug mode */ #if defined (DBGMCU_APB1_FZ_DBG_TIM7_STOP) #define __HAL_FREEZE_TIM7_DBGMCU() SET_BIT(DBGMCU->APB1FZ, DBGMCU_APB1_FZ_DBG_TIM7_STOP) #define __HAL_UNFREEZE_TIM7_DBGMCU() CLEAR_BIT(DBGMCU->APB1FZ, DBGMCU_APB1_FZ_DBG_TIM7_STOP) #endif /** * @brief RTC Peripherals Debug mode */ #if defined (DBGMCU_APB1_FZ_DBG_RTC_STOP) #define __HAL_FREEZE_RTC_DBGMCU() SET_BIT(DBGMCU->APB1FZ, DBGMCU_APB1_FZ_DBG_RTC_STOP) #define __HAL_UNFREEZE_RTC_DBGMCU() CLEAR_BIT(DBGMCU->APB1FZ, DBGMCU_APB1_FZ_DBG_RTC_STOP) #endif /** * @brief WWDG Peripherals Debug mode */ #if defined (DBGMCU_APB1_FZ_DBG_WWDG_STOP) #define __HAL_FREEZE_WWDG_DBGMCU() SET_BIT(DBGMCU->APB1FZ, DBGMCU_APB1_FZ_DBG_WWDG_STOP) #define __HAL_UNFREEZE_WWDG_DBGMCU() CLEAR_BIT(DBGMCU->APB1FZ, DBGMCU_APB1_FZ_DBG_WWDG_STOP) #endif /** * @brief IWDG Peripherals Debug mode */ #if defined (DBGMCU_APB1_FZ_DBG_IWDG_STOP) #define __HAL_FREEZE_IWDG_DBGMCU() SET_BIT(DBGMCU->APB1FZ, DBGMCU_APB1_FZ_DBG_IWDG_STOP) #define __HAL_UNFREEZE_IWDG_DBGMCU() CLEAR_BIT(DBGMCU->APB1FZ, DBGMCU_APB1_FZ_DBG_IWDG_STOP) #endif /** * @brief I2C1 Peripherals Debug mode */ #if defined (DBGMCU_APB1_FZ_DBG_I2C1_SMBUS_TIMEOUT) #define __HAL_FREEZE_I2C1_TIMEOUT_DBGMCU() SET_BIT(DBGMCU->APB1FZ, DBGMCU_APB1_FZ_DBG_I2C1_SMBUS_TIMEOUT) #define __HAL_UNFREEZE_I2C1_TIMEOUT_DBGMCU() CLEAR_BIT(DBGMCU->APB1FZ, DBGMCU_APB1_FZ_DBG_I2C1_SMBUS_TIMEOUT) #endif /** * @brief I2C2 Peripherals Debug mode */ #if defined (DBGMCU_APB1_FZ_DBG_I2C2_SMBUS_TIMEOUT) #define __HAL_FREEZE_I2C2_TIMEOUT_DBGMCU() SET_BIT(DBGMCU->APB1FZ, DBGMCU_APB1_FZ_DBG_I2C2_SMBUS_TIMEOUT) #define __HAL_UNFREEZE_I2C2_TIMEOUT_DBGMCU() CLEAR_BIT(DBGMCU->APB1FZ, DBGMCU_APB1_FZ_DBG_I2C2_SMBUS_TIMEOUT) #endif /** * @brief TIM9 Peripherals Debug mode */ #if defined (DBGMCU_APB2_FZ_DBG_TIM9_STOP) #define __HAL_FREEZE_TIM9_DBGMCU() SET_BIT(DBGMCU->APB2FZ, DBGMCU_APB2_FZ_DBG_TIM9_STOP) #define __HAL_UNFREEZE_TIM9_DBGMCU() CLEAR_BIT(DBGMCU->APB2FZ, DBGMCU_APB2_FZ_DBG_TIM9_STOP) #endif /** * @brief TIM10 Peripherals Debug mode */ #if defined (DBGMCU_APB2_FZ_DBG_TIM10_STOP) #define __HAL_FREEZE_TIM10_DBGMCU() SET_BIT(DBGMCU->APB2FZ, DBGMCU_APB2_FZ_DBG_TIM10_STOP) #define __HAL_UNFREEZE_TIM10_DBGMCU() CLEAR_BIT(DBGMCU->APB2FZ, DBGMCU_APB2_FZ_DBG_TIM10_STOP) #endif /** * @brief TIM11 Peripherals Debug mode */ #if defined (DBGMCU_APB2_FZ_DBG_TIM11_STOP) #define __HAL_FREEZE_TIM11_DBGMCU() SET_BIT(DBGMCU->APB2FZ, DBGMCU_APB2_FZ_DBG_TIM11_STOP) #define __HAL_UNFREEZE_TIM11_DBGMCU() CLEAR_BIT(DBGMCU->APB2FZ, DBGMCU_APB2_FZ_DBG_TIM11_STOP) #endif /** * @brief Enables or disables the output of internal reference voltage * (VREFINT) on I/O pin. * The VREFINT output can be routed to any I/O in group 3: * - For Cat.1 and Cat.2 devices: CH8 (PB0) or CH9 (PB1). * - For Cat.3 devices: CH8 (PB0), CH9 (PB1) or CH0b (PB2). * - For Cat.4 and Cat.5 devices: CH8 (PB0), CH9 (PB1), CH0b (PB2), * CH1b (PF11) or CH2b (PF12). * Note: Comparator peripheral clock must be preliminarility enabled, * either in COMP user function "HAL_COMP_MspInit()" (should be * done if comparators are used) or by direct clock enable: * Refer to macro "__COMP_CLK_ENABLE()". * Note: In addition with this macro, Vrefint output buffer must be * connected to the selected I/O pin. Refer to macro * "__HAL_RI_IOSWITCH_CLOSE()". * @note ENABLE: Internal reference voltage connected to I/O group 3 * @note DISABLE: Internal reference voltage disconnected from I/O group 3 * @retval None */ #define __HAL_VREFINT_OUT_ENABLE() SET_BIT(COMP->CSR, COMP_CSR_VREFOUTEN) #define __HAL_VREFINT_OUT_DISABLE() CLEAR_BIT(COMP->CSR, COMP_CSR_VREFOUTEN) /** * @} */ /** * @} */ /** @defgroup SYSCFG_Macros SYSCFG: SYStem ConFiG * @{ */ /** @defgroup SYSCFG_BootModeConfig Boot Mode Configuration * @{ */ /** * @brief Main Flash memory mapped at 0x00000000 */ #define __HAL_REMAPMEMORY_FLASH() CLEAR_BIT(SYSCFG->MEMRMP, SYSCFG_MEMRMP_MEM_MODE) /** @brief System Flash memory mapped at 0x00000000 */ #define __HAL_REMAPMEMORY_SYSTEMFLASH() MODIFY_REG(SYSCFG->MEMRMP, SYSCFG_MEMRMP_MEM_MODE, SYSCFG_MEMRMP_MEM_MODE_0) /** @brief Embedded SRAM mapped at 0x00000000 */ #define __HAL_REMAPMEMORY_SRAM() MODIFY_REG(SYSCFG->MEMRMP, SYSCFG_MEMRMP_MEM_MODE, SYSCFG_MEMRMP_MEM_MODE_0 | SYSCFG_MEMRMP_MEM_MODE_1) #if defined(FSMC_R_BASE) /** @brief FSMC Bank1 (NOR/PSRAM 1 and 2) mapped at 0x00000000 */ #define __HAL_REMAPMEMORY_FSMC() MODIFY_REG(SYSCFG->MEMRMP, SYSCFG_MEMRMP_MEM_MODE, SYSCFG_MEMRMP_MEM_MODE_1) #endif /* FSMC_R_BASE */ /** * @brief Returns the boot mode as configured by user. * @retval The boot mode as configured by user. The returned value can be one * of the following values: * @arg SYSCFG_BOOT_MAINFLASH * @arg SYSCFG_BOOT_SYSTEMFLASH * @arg SYSCFG_BOOT_FSMC (available only for STM32L151xD, STM32L152xD & STM32L162xD) * @arg SYSCFG_BOOT_SRAM */ #define __HAL_SYSCFG_GET_BOOT_MODE() READ_BIT(SYSCFG->MEMRMP, SYSCFG_MEMRMP_BOOT_MODE) /** * @} */ /** @defgroup SYSCFG_USBConfig USB DP line Configuration * @{ */ /** * @brief Control the internal pull-up on USB DP line. */ #define __HAL_SYSCFG_USBPULLUP_ENABLE() SET_BIT(SYSCFG->PMC, SYSCFG_PMC_USB_PU) #define __HAL_SYSCFG_USBPULLUP_DISABLE() CLEAR_BIT(SYSCFG->PMC, SYSCFG_PMC_USB_PU) /** * @} */ /** * @} */ /** @defgroup RI_Macris RI: Routing Interface * @{ */ /** @defgroup RI_InputCaputureConfig Input Capture configuration * @{ */ /** * @brief Configures the routing interface to map Input Capture 1 of TIMx to a selected I/O pin. * @param __TIMSELECT__: Timer select. * This parameter can be one of the following values: * @arg TIM_SELECT_NONE: No timer selected and default Timer mapping is enabled. * @arg TIM_SELECT_TIM2: Timer 2 Input Captures to be routed. * @arg TIM_SELECT_TIM3: Timer 3 Input Captures to be routed. * @arg TIM_SELECT_TIM4: Timer 4 Input Captures to be routed. * @param __INPUT__: selects which pin to be routed to Input Capture. * This parameter must be a value of @ref RI_InputCaptureRouting * e.g. * __HAL_RI_REMAP_INPUTCAPTURE1(TIM_SELECT_TIM2, RI_INPUTCAPTUREROUTING_1) * allows routing of Input capture IC1 of TIM2 to PA4. * For details about correspondence between RI_INPUTCAPTUREROUTING_x * and I/O pins refer to the parameters' description in the header file * or refer to the product reference manual. * @note Input capture selection bits are not reset by this function. * To reset input capture selection bits, use SYSCFG_RIDeInit() function. * @note The I/O should be configured in alternate function mode (AF14) using * GPIO_PinAFConfig() function. * @retval None. */ #define __HAL_RI_REMAP_INPUTCAPTURE1(__TIMSELECT__, __INPUT__) \ do {assert_param(IS_RI_TIM(__TIMSELECT__)); \ assert_param(IS_RI_INPUTCAPTURE_ROUTING(__INPUT__)); \ MODIFY_REG(RI->ICR, RI_ICR_TIM, (__TIMSELECT__)); \ SET_BIT(RI->ICR, RI_INPUTCAPTURE_IC1); \ MODIFY_REG(RI->ICR, RI_ICR_IC1OS, (__INPUT__) << POSITION_VAL(RI_ICR_IC1OS)); \ }while(0) /** * @brief Configures the routing interface to map Input Capture 2 of TIMx to a selected I/O pin. * @param __TIMSELECT__: Timer select. * This parameter can be one of the following values: * @arg TIM_SELECT_NONE: No timer selected and default Timer mapping is enabled. * @arg TIM_SELECT_TIM2: Timer 2 Input Captures to be routed. * @arg TIM_SELECT_TIM3: Timer 3 Input Captures to be routed. * @arg TIM_SELECT_TIM4: Timer 4 Input Captures to be routed. * @param __INPUT__: selects which pin to be routed to Input Capture. * This parameter must be a value of @ref RI_InputCaptureRouting * @retval None. */ #define __HAL_RI_REMAP_INPUTCAPTURE2(__TIMSELECT__, __INPUT__) \ do {assert_param(IS_RI_TIM(__TIMSELECT__)); \ assert_param(IS_RI_INPUTCAPTURE_ROUTING(__INPUT__)); \ MODIFY_REG(RI->ICR, RI_ICR_TIM, (__TIMSELECT__)); \ SET_BIT(RI->ICR, RI_INPUTCAPTURE_IC2); \ MODIFY_REG(RI->ICR, RI_ICR_IC2OS, (__INPUT__) << POSITION_VAL(RI_ICR_IC2OS)); \ }while(0) /** * @brief Configures the routing interface to map Input Capture 3 of TIMx to a selected I/O pin. * @param __TIMSELECT__: Timer select. * This parameter can be one of the following values: * @arg TIM_SELECT_NONE: No timer selected and default Timer mapping is enabled. * @arg TIM_SELECT_TIM2: Timer 2 Input Captures to be routed. * @arg TIM_SELECT_TIM3: Timer 3 Input Captures to be routed. * @arg TIM_SELECT_TIM4: Timer 4 Input Captures to be routed. * @param __INPUT__: selects which pin to be routed to Input Capture. * This parameter must be a value of @ref RI_InputCaptureRouting * @retval None. */ #define __HAL_RI_REMAP_INPUTCAPTURE3(__TIMSELECT__, __INPUT__) \ do {assert_param(IS_RI_TIM(__TIMSELECT__)); \ assert_param(IS_RI_INPUTCAPTURE_ROUTING(__INPUT__)); \ MODIFY_REG(RI->ICR, RI_ICR_TIM, (__TIMSELECT__)); \ SET_BIT(RI->ICR, RI_INPUTCAPTURE_IC3); \ MODIFY_REG(RI->ICR, RI_ICR_IC3OS, (__INPUT__) << POSITION_VAL(RI_ICR_IC3OS)); \ }while(0) /** * @brief Configures the routing interface to map Input Capture 4 of TIMx to a selected I/O pin. * @param __TIMSELECT__: Timer select. * This parameter can be one of the following values: * @arg TIM_SELECT_NONE: No timer selected and default Timer mapping is enabled. * @arg TIM_SELECT_TIM2: Timer 2 Input Captures to be routed. * @arg TIM_SELECT_TIM3: Timer 3 Input Captures to be routed. * @arg TIM_SELECT_TIM4: Timer 4 Input Captures to be routed. * @param __INPUT__: selects which pin to be routed to Input Capture. * This parameter must be a value of @ref RI_InputCaptureRouting * @retval None. */ #define __HAL_RI_REMAP_INPUTCAPTURE4(__TIMSELECT__, __INPUT__) \ do {assert_param(IS_RI_TIM(__TIMSELECT__)); \ assert_param(IS_RI_INPUTCAPTURE_ROUTING(__INPUT__)); \ MODIFY_REG(RI->ICR, RI_ICR_TIM, (__TIMSELECT__)); \ SET_BIT(RI->ICR, RI_INPUTCAPTURE_IC4); \ MODIFY_REG(RI->ICR, RI_ICR_IC4OS, (__INPUT__) << POSITION_VAL(RI_ICR_IC4OS)); \ }while(0) /** * @} */ /** @defgroup RI_SwitchControlConfig Switch Control configuration * @{ */ /** * @brief Enable or disable the switch control mode. * @note ENABLE: ADC analog switches closed if the corresponding * I/O switch is also closed. * When using COMP1, switch control mode must be enabled. * @note DISABLE: ADC analog switches open or controlled by the ADC interface. * When using the ADC for acquisition, switch control mode * must be disabled. * @note COMP1 comparator and ADC cannot be used at the same time since * they share the ADC switch matrix. * @retval None */ #define __HAL_RI_SWITCHCONTROLMODE_ENABLE() SET_BIT(RI->ASCR1, RI_ASCR1_SCM) #define __HAL_RI_SWITCHCONTROLMODE_DISABLE() CLEAR_BIT(RI->ASCR1, RI_ASCR1_SCM) /* * @brief Close or Open the routing interface Input Output switches. * @param __IOSWITCH__: selects the I/O analog switch number. * This parameter must be a value of @ref RI_IOSwitch * @retval None */ #define __HAL_RI_IOSWITCH_CLOSE(__IOSWITCH__) do { assert_param(IS_RI_IOSWITCH(__IOSWITCH__)); \ if ((__IOSWITCH__) >> 31 != 0 ) \ { \ SET_BIT(RI->ASCR1, (__IOSWITCH__) & 0x7FFFFFFF); \ } \ else \ { \ SET_BIT(RI->ASCR2, (__IOSWITCH__)); \ } \ }while(0) #define __HAL_RI_IOSWITCH_OPEN(__IOSWITCH__) do { assert_param(IS_RI_IOSWITCH(__IOSWITCH__)); \ if ((__IOSWITCH__) >> 31 != 0 ) \ { \ CLEAR_BIT(RI->ASCR1, (__IOSWITCH__) & 0x7FFFFFFF); \ } \ else \ { \ CLEAR_BIT(RI->ASCR2, (__IOSWITCH__)); \ } \ }while(0) #if defined (COMP_CSR_SW1) /** * @brief Close or open the internal switch COMP1_SW1. * This switch connects I/O pin PC3 (can be used as ADC channel 13) * and OPAMP3 ouput to ADC switch matrix (ADC channel VCOMP, channel * 26) and COMP1 non-inverting input. * Pin PC3 connection depends on another switch setting, refer to * macro "__HAL_ADC_CHANNEL_SPEED_FAST()". * @retval None. */ #define __HAL_RI_SWITCH_COMP1_SW1_CLOSE() SET_BIT(COMP->CSR, COMP_CSR_SW1) #define __HAL_RI_SWITCH_COMP1_SW1_OPEN() CLEAR_BIT(COMP->CSR, COMP_CSR_SW1) #endif /* COMP_CSR_SW1 */ /** * @} */ /** @defgroup RI_HystConfig Hysteresis Activation and Deactivation * @{ */ /** * @brief Enable or disable Hysteresis of the input schmitt triger of Ports A * When the I/Os are programmed in input mode by standard I/O port * registers, the Schmitt trigger and the hysteresis are enabled by default. * When hysteresis is disabled, it is possible to read the * corresponding port with a trigger level of VDDIO/2. * @param __IOPIN__ : Selects the pin(s) on which to enable or disable hysteresis. * This parameter must be a value of @ref RI_Pin * @retval None */ #define __HAL_RI_HYSTERIS_PORTA_ON(__IOPIN__) do {assert_param(IS_RI_PIN(__IOPIN__)); \ CLEAR_BIT(RI->HYSCR1, (__IOPIN__)); \ } while(0) #define __HAL_RI_HYSTERIS_PORTA_OFF(__IOPIN__) do {assert_param(IS_RI_PIN(__IOPIN__)); \ SET_BIT(RI->HYSCR1, (__IOPIN__)); \ } while(0) /** * @brief Enable or disable Hysteresis of the input schmitt triger of Ports B * When the I/Os are programmed in input mode by standard I/O port * registers, the Schmitt trigger and the hysteresis are enabled by default. * When hysteresis is disabled, it is possible to read the * corresponding port with a trigger level of VDDIO/2. * @param __IOPIN__ : Selects the pin(s) on which to enable or disable hysteresis. * This parameter must be a value of @ref RI_Pin * @retval None */ #define __HAL_RI_HYSTERIS_PORTB_ON(__IOPIN__) do {assert_param(IS_RI_PIN(__IOPIN__)); \ CLEAR_BIT(RI->HYSCR1, (__IOPIN__) << 16 ); \ } while(0) #define __HAL_RI_HYSTERIS_PORTB_OFF(__IOPIN__) do {assert_param(IS_RI_PIN(__IOPIN__)); \ SET_BIT(RI->HYSCR1, (__IOPIN__) << 16 ); \ } while(0) /** * @brief Enable or disable Hysteresis of the input schmitt triger of Ports C * When the I/Os are programmed in input mode by standard I/O port * registers, the Schmitt trigger and the hysteresis are enabled by default. * When hysteresis is disabled, it is possible to read the * corresponding port with a trigger level of VDDIO/2. * @param __IOPIN__ : Selects the pin(s) on which to enable or disable hysteresis. * This parameter must be a value of @ref RI_Pin * @retval None */ #define __HAL_RI_HYSTERIS_PORTC_ON(__IOPIN__) do {assert_param(IS_RI_PIN(__IOPIN__)); \ CLEAR_BIT(RI->HYSCR2, (__IOPIN__)); \ } while(0) #define __HAL_RI_HYSTERIS_PORTC_OFF(__IOPIN__) do {assert_param(IS_RI_PIN(__IOPIN__)); \ SET_BIT(RI->HYSCR2, (__IOPIN__)); \ } while(0) /** * @brief Enable or disable Hysteresis of the input schmitt triger of Ports D * When the I/Os are programmed in input mode by standard I/O port * registers, the Schmitt trigger and the hysteresis are enabled by default. * When hysteresis is disabled, it is possible to read the * corresponding port with a trigger level of VDDIO/2. * @param __IOPIN__ : Selects the pin(s) on which to enable or disable hysteresis. * This parameter must be a value of @ref RI_Pin * @retval None */ #define __HAL_RI_HYSTERIS_PORTD_ON(__IOPIN__) do {assert_param(IS_RI_PIN(__IOPIN__)); \ CLEAR_BIT(RI->HYSCR2, (__IOPIN__) << 16 ); \ } while(0) #define __HAL_RI_HYSTERIS_PORTD_OFF(__IOPIN__) do {assert_param(IS_RI_PIN(__IOPIN__)); \ SET_BIT(RI->HYSCR2, (__IOPIN__) << 16 ); \ } while(0) #if defined (GPIOE_BASE) /** * @brief Enable or disable Hysteresis of the input schmitt triger of Ports E * When the I/Os are programmed in input mode by standard I/O port * registers, the Schmitt trigger and the hysteresis are enabled by default. * When hysteresis is disabled, it is possible to read the * corresponding port with a trigger level of VDDIO/2. * @param __IOPIN__ : Selects the pin(s) on which to enable or disable hysteresis. * This parameter must be a value of @ref RI_Pin * @retval None */ #define __HAL_RI_HYSTERIS_PORTE_ON(__IOPIN__) do {assert_param(IS_RI_PIN(__IOPIN__)); \ CLEAR_BIT(RI->HYSCR3, (__IOPIN__)); \ } while(0) #define __HAL_RI_HYSTERIS_PORTE_OFF(__IOPIN__) do {assert_param(IS_RI_PIN(__IOPIN__)); \ SET_BIT(RI->HYSCR3, (__IOPIN__)); \ } while(0) #endif /* GPIOE_BASE */ #if defined(GPIOF_BASE) || defined(GPIOG_BASE) /** * @brief Enable or disable Hysteresis of the input schmitt triger of Ports F * When the I/Os are programmed in input mode by standard I/O port * registers, the Schmitt trigger and the hysteresis are enabled by default. * When hysteresis is disabled, it is possible to read the * corresponding port with a trigger level of VDDIO/2. * @param __IOPIN__ : Selects the pin(s) on which to enable or disable hysteresis. * This parameter must be a value of @ref RI_Pin * @retval None */ #define __HAL_RI_HYSTERIS_PORTF_ON(__IOPIN__) do {assert_param(IS_RI_PIN(__IOPIN__)); \ CLEAR_BIT(RI->HYSCR3, (__IOPIN__) << 16 ); \ } while(0) #define __HAL_RI_HYSTERIS_PORTF_OFF(__IOPIN__) do {assert_param(IS_RI_PIN(__IOPIN__)); \ SET_BIT(RI->HYSCR3, (__IOPIN__) << 16 ); \ } while(0) /** * @brief Enable or disable Hysteresis of the input schmitt triger of Ports G * When the I/Os are programmed in input mode by standard I/O port * registers, the Schmitt trigger and the hysteresis are enabled by default. * When hysteresis is disabled, it is possible to read the * corresponding port with a trigger level of VDDIO/2. * @param __IOPIN__ : Selects the pin(s) on which to enable or disable hysteresis. * This parameter must be a value of @ref RI_Pin * @retval None */ #define __HAL_RI_HYSTERIS_PORTG_ON(__IOPIN__) do {assert_param(IS_RI_PIN(__IOPIN__)); \ CLEAR_BIT(RI->HYSCR4, (__IOPIN__)); \ } while(0) #define __HAL_RI_HYSTERIS_PORTG_OFF(__IOPIN__) do {assert_param(IS_RI_PIN(__IOPIN__)); \ SET_BIT(RI->HYSCR4, (__IOPIN__)); \ } while(0) #endif /* GPIOF_BASE || GPIOG_BASE */ /** * @} */ /** * @} */ /** * @} */ /* Exported functions --------------------------------------------------------*/ /** @addtogroup HAL_Exported_Functions * @{ */ /** @addtogroup HAL_Exported_Functions_Group1 * @{ */ /* Initialization and de-initialization functions ******************************/ HAL_StatusTypeDef HAL_Init(void); HAL_StatusTypeDef HAL_DeInit(void); void HAL_MspInit(void); void HAL_MspDeInit(void); HAL_StatusTypeDef HAL_InitTick (uint32_t TickPriority); /** * @} */ /** @addtogroup HAL_Exported_Functions_Group2 * @{ */ /* Peripheral Control functions ************************************************/ void HAL_IncTick(void); void HAL_Delay(__IO uint32_t Delay); uint32_t HAL_GetTick(void); void HAL_SuspendTick(void); void HAL_ResumeTick(void); uint32_t HAL_GetHalVersion(void); uint32_t HAL_GetREVID(void); uint32_t HAL_GetDEVID(void); void HAL_EnableDBGSleepMode(void); void HAL_DisableDBGSleepMode(void); void HAL_EnableDBGStopMode(void); void HAL_DisableDBGStopMode(void); void HAL_EnableDBGStandbyMode(void); void HAL_DisableDBGStandbyMode(void); /** * @} */ /** * @} */ /** * @} */ /** * @} */ #ifdef __cplusplus } #endif #endif /* __STM32L1xx_HAL_H */ /************************ (C) COPYRIGHT STMicroelectronics *****END OF FILE****/ ================================================ FILE: Zelig/mbed/TARGET_NUCLEO_L152RE/stm32l1xx_hal_adc.h ================================================ /** ****************************************************************************** * @file stm32l1xx_hal_adc.h * @author MCD Application Team * @version V1.0.0 * @date 5-September-2014 * @brief Header file containing functions prototypes of ADC HAL library. ****************************************************************************** * @attention * *

© COPYRIGHT(c) 2014 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. * ****************************************************************************** */ /* Define to prevent recursive inclusion -------------------------------------*/ #ifndef __STM32L1xx_HAL_ADC_H #define __STM32L1xx_HAL_ADC_H #ifdef __cplusplus extern "C" { #endif /* Includes ------------------------------------------------------------------*/ #include "stm32l1xx_hal_def.h" /** @addtogroup STM32L1xx_HAL_Driver * @{ */ /** @addtogroup ADC * @{ */ /* Exported types ------------------------------------------------------------*/ /** @defgroup ADC_Exported_Types ADC Exported Types * @{ */ /** * @brief Structure definition of ADC and regular group initialization * @note Parameters of this structure are shared within 2 scopes: * - Scope entire ADC (affects regular and injected groups): ClockPrescaler, Resolution, ScanConvMode, DataAlign, ScanConvMode, EOCSelection, LowPowerAutoWait, LowPowerAutoPowerOff, ChannelsBank. * - Scope regular group: ContinuousConvMode, NbrOfConversion, DiscontinuousConvMode, NbrOfDiscConversion, ExternalTrigConvEdge, ExternalTrigConv. * @note The setting of these parameters with function HAL_ADC_Init() is conditioned to ADC state. * ADC state can be either: * - For all parameters: ADC disabled * - For all parameters except 'Resolution', 'ScanConvMode', 'LowPowerAutoWait', 'LowPowerAutoPowerOff', 'DiscontinuousConvMode', 'NbrOfDiscConversion' : ADC enabled without conversion on going on regular group. * - For parameters 'ExternalTrigConv' and 'ExternalTrigConvEdge': ADC enabled, even with conversion on going. * If ADC is not in the appropriate state to modify some parameters, these parameters setting is bypassed * without error reporting without error reporting (as it can be the expected behaviour in case of intended action to update another parameter (which fullfills the ADC state condition) on the fly). */ typedef struct { uint32_t ClockPrescaler; /*!< Select ADC clock source (asynchronous clock derived from HSI RC oscillator) and clock prescaler. This parameter can be a value of @ref ADC_ClockPrescaler Note: In case of usage of channels on injected group, ADC frequency should be low than AHB clock frequency /4 for resolution 12 or 10 bits, AHB clock frequency /3 for resolution 8 bits, AHB clock frequency /2 for resolution 6 bits. Note: HSI RC oscillator must be preliminarily enabled at RCC top level. */ uint32_t Resolution; /*!< Configures the ADC resolution. This parameter can be a value of @ref ADC_Resolution */ uint32_t DataAlign; /*!< Specifies ADC data alignment to right (MSB on register bit 11 and LSB on register bit 0) (default setting) or to left (if regular group: MSB on register bit 15 and LSB on register bit 4, if injected group (MSB kept as signed value due to potential negative value after offset application): MSB on register bit 14 and LSB on register bit 3). This parameter can be a value of @ref ADC_Data_align */ uint32_t ScanConvMode; /*!< Configures the sequencer of regular and injected groups. This parameter can be associated to parameter 'DiscontinuousConvMode' to have main sequence subdivided in successive parts. If disabled: Conversion is performed in single mode (one channel converted, the one defined in rank 1). Parameters 'NbrOfConversion' and 'InjectedNbrOfConversion' are discarded (equivalent to set to 1). If enabled: Conversions are performed in sequence mode (multiple ranks defined by 'NbrOfConversion'/'InjectedNbrOfConversion' and each channel rank). Scan direction is upward: from rank1 to rank 'n'. This parameter can be a value of @ref ADC_Scan_mode */ uint32_t EOCSelection; /*!< Specifies what EOC (End Of Conversion) flag is used for conversion by polling and interruption: end of conversion of each rank or complete sequence. This parameter can be a value of @ref ADC_EOCSelection. Note: For injected group, end of conversion (flag&IT) is raised only at the end of the sequence. Therefore, if end of conversion is set to end of each conversion, injected group should not be used with interruption (HAL_ADCEx_InjectedStart_IT) or polling (HAL_ADCEx_InjectedStart and HAL_ADCEx_InjectedPollForConversion). By the way, polling is still possible since driver will use an estimated timing for end of injected conversion. Note: If overrun feature is intending to be used in ADC mode 'interruption' (function HAL_ADC_Start_IT() ), parameter EOCSelection must be set to each conversion (this is not needed for ADC mode 'transfer by DMA', with function HAL_ADC_Start_DMA()) */ uint32_t LowPowerAutoWait; /*!< Selects the dynamic low power Auto Delay: new conversion start only when the previous conversion (for regular group) or previous sequence (for injected group) has been treated by user software. This feature automatically adapts the speed of ADC to the speed of the system that reads the data. Moreover, this avoids risk of overrun for low frequency applications. This parameter can be a value of @ref ADC_LowPowerAutoWait. Note: Do not use with interruption or DMA (HAL_ADC_Start_IT(), HAL_ADC_Start_DMA()) since they have to clear immediately the EOC flag to free the IRQ vector sequencer. Do use with polling: 1. Start conversion with HAL_ADC_Start(), 2. Later on, when conversion data is needed: use HAL_ADC_PollForConversion() to ensure that conversion is completed and use HAL_ADC_GetValue() to retrieve conversion result and trig another conversion. Note: ADC clock latency and some timing constraints depending on clock prescaler have to be taken into account: refer to reference manual (register ADC_CR2 bit DELS description). */ uint32_t LowPowerAutoPowerOff; /*!< Selects the auto-off mode: the ADC automatically powers-off after a conversion and automatically wakes-up when a new conversion is triggered (with startup time between trigger and start of sampling). This feature can be combined with automatic wait mode (parameter 'LowPowerAutoWait'). This parameter can be a value of @ref ADC_LowPowerAutoPowerOff. */ uint32_t ChannelsBank; /*!< Selects the ADC channels bank. This parameter can be a value of @ref ADC_ChannelsBank. Note: Banks availability depends on devices categories. Note: To change bank selection on the fly, without going through execution of 'HAL_ADC_Init()', macro '__HAL_ADC_CHANNELS_BANK()' can be used directly. */ uint32_t ContinuousConvMode; /*!< Specifies whether the conversion is performed in single mode (one conversion) or continuous mode for regular group, after the selected trigger occurred (software start or external trigger). This parameter can be set to ENABLE or DISABLE. */ #if defined(STM32L100xC) || defined (STM32L151xC) || defined (STM32L152xC) || defined (STM32L162xC) || defined(STM32L151xCA) || defined (STM32L151xD) || defined (STM32L152xCA) || defined (STM32L152xD) || defined (STM32L162xCA) || defined (STM32L162xD) || defined(STM32L151xE) || defined (STM32L152xE) || defined (STM32L162xE) uint32_t NbrOfConversion; /*!< Specifies the number of ranks that will be converted within the regular group sequencer. To use regular group sequencer and convert several ranks, parameter 'ScanConvMode' must be enabled. This parameter must be a number between Min_Data = 1 and Max_Data = 28. */ #else uint32_t NbrOfConversion; /*!< Specifies the number of ranks that will be converted within the regular group sequencer. To use regular group sequencer and convert several ranks, parameter 'ScanConvMode' must be enabled. This parameter must be a number between Min_Data = 1 and Max_Data = 27. */ #endif /* STM32L100xC || STM32L151xC || STM32L152xC || STM32L162xC || STM32L151xCA || STM32L151xD || STM32L152xCA || STM32L152xD || STM32L162xCA || STM32L162xD || STM32L151xE || STM32L152xE || STM32L162xE */ uint32_t DiscontinuousConvMode; /*!< Specifies whether the conversions sequence of regular group is performed in Complete-sequence/Discontinuous-sequence (main sequence subdivided in successive parts). Discontinuous mode is used only if sequencer is enabled (parameter 'ScanConvMode'). If sequencer is disabled, this parameter is discarded. Discontinuous mode can be enabled only if continuous mode is disabled. If continuous mode is enabled, this parameter setting is discarded. This parameter can be set to ENABLE or DISABLE. */ uint32_t NbrOfDiscConversion; /*!< Specifies the number of discontinuous conversions in which the main sequence of regular group (parameter NbrOfConversion) will be subdivided. If parameter 'DiscontinuousConvMode' is disabled, this parameter is discarded. This parameter must be a number between Min_Data = 1 and Max_Data = 8. */ uint32_t ExternalTrigConv; /*!< Selects the external event used to trigger the conversion start of regular group. If set to ADC_SOFTWARE_START, external triggers are disabled. If set to external trigger source, triggering is on event rising edge. This parameter can be a value of @ref ADC_External_trigger_source_Regular */ uint32_t ExternalTrigConvEdge; /*!< Selects the external trigger edge of regular group. If trigger is set to ADC_SOFTWARE_START, this parameter is discarded. This parameter can be a value of @ref ADC_External_trigger_edge_Regular */ uint32_t DMAContinuousRequests; /*!< Specifies whether the DMA requests are performed in one shot mode (DMA transfer stop when number of conversions is reached) or in Continuous mode (DMA transfer unlimited, whatever number of conversions). Note: In continuous mode, DMA must be configured in circular mode. Otherwise an overrun will be triggered when DMA buffer maximum pointer is reached. This parameter can be set to ENABLE or DISABLE. Note: This parameter must be modified when no conversion is on going on both regular and injected groups (ADC disabled, or ADC enabled without continuous mode or external trigger that could lauch a conversion). */ }ADC_InitTypeDef; /** * @brief Structure definition of ADC channel for regular group * @note The setting of these parameters with function HAL_ADC_ConfigChannel() is conditioned to ADC state. * ADC can be either disabled or enabled without conversion on going on regular group. */ typedef struct { uint32_t Channel; /*!< Specifies the channel to configure into ADC regular group. This parameter can be a value of @ref ADC_channels Note: Depending on devices, some channels may not be available on package pins. Refer to device datasheet for channels availability. Maximum number of channels by device category (without taking in account each device package constraints): STM32L1 category 1, 2: 24 channels on external pins + 3 channels on internal measurement paths (VrefInt, Temp sensor, Vcomp): Channel 0 to channel 26. STM32L1 category 3: 25 channels on external pins + 3 channels on internal measurement paths (VrefInt, Temp sensor, Vcomp): Channel 0 to channel 26, 1 additional channel in bank B. Note: OPAMP1 and OPAMP2 are connected internally but not increasing internal channels number: they are sharing ADC input with external channels ADC_IN3 and ADC_IN8. STM32L1 category 4, 5: 40 channels on external pins + 3 channels on internal measurement paths (VrefInt, Temp sensor, Vcomp): Channel 0 to channel 31, 11 additional channels in bank B. Note: OPAMP1 and OPAMP2 are connected internally but not increasing internal channels number: they are sharing ADC input with external channels ADC_IN3 and ADC_IN8. Note: In case of peripherals OPAMPx not used: 3 channels (3, 8, 13) can be configured as direct channels (fast channels). Refer to macro ' __HAL_ADC_CHANNEL_SPEED_FAST() '. Note: In case of peripheral OPAMP3 and ADC channel OPAMP3 used (OPAMP3 available on STM32L1 devices Cat.4 only): the analog switch COMP1_SW1 must be closed. Refer to macro: ' __HAL_OPAMP_OPAMP3OUT_CONNECT_ADC_COMP1() '. */ uint32_t Rank; /*!< Specifies the rank in the regular group sequencer This parameter can be a value of @ref ADC_regular_rank Note: In case of need to disable a channel or change order of conversion sequencer, rank containing a previous channel setting can be overwritten by the new channel setting (or parameter number of conversions can be adjusted) */ uint32_t SamplingTime; /*!< Sampling time value to be set for the selected channel. Unit: ADC clock cycles Conversion time is the addition of sampling time and processing time (12 ADC clock cycles at ADC resolution 12 bits, 11 cycles at 10 bits, 9 cycles at 8 bits, 7 cycles at 6 bits). This parameter can be a value of @ref ADC_sampling_times Caution: This parameter updates the parameter property of the channel, that can be used into regular and/or injected groups. If this same channel has been previously configured in the other group (regular/injected), it will be updated to last setting. Note: In case of usage of internal measurement channels (VrefInt/Vbat/TempSensor), sampling time constraints must be respected (sampling time can be adjusted in function of ADC clock frequency and sampling time setting) Refer to device datasheet for timings values, parameters TS_vrefint, TS_temp (values rough order: 4us min). */ }ADC_ChannelConfTypeDef; /** * @brief ADC Configuration analog watchdog definition * @note The setting of these parameters with function is conditioned to ADC state. * ADC state can be either disabled or enabled without conversion on going on regular and injected groups. */ typedef struct { uint32_t WatchdogMode; /*!< Configures the ADC analog watchdog mode: single/all channels, regular/injected group. This parameter can be a value of @ref ADC_analog_watchdog_mode. */ uint32_t Channel; /*!< Selects which ADC channel to monitor by analog watchdog. This parameter has an effect only if watchdog mode is configured on single channel (parameter WatchdogMode) This parameter can be a value of @ref ADC_channels. */ uint32_t ITMode; /*!< Specifies whether the analog watchdog is configured in interrupt or polling mode. This parameter can be set to ENABLE or DISABLE */ uint32_t HighThreshold; /*!< Configures the ADC analog watchdog High threshold value. This parameter must be a number between Min_Data = 0x000 and Max_Data = 0xFFF. */ uint32_t LowThreshold; /*!< Configures the ADC analog watchdog High threshold value. This parameter must be a number between Min_Data = 0x000 and Max_Data = 0xFFF. */ uint32_t WatchdogNumber; /*!< Reserved for future use, can be set to 0 */ }ADC_AnalogWDGConfTypeDef; /** * @brief HAL ADC state machine: ADC States structure definition */ typedef enum { HAL_ADC_STATE_RESET = 0x00, /*!< ADC not yet initialized or disabled */ HAL_ADC_STATE_READY = 0x01, /*!< ADC peripheral ready for use */ HAL_ADC_STATE_BUSY = 0x02, /*!< An internal process is ongoing */ HAL_ADC_STATE_BUSY_REG = 0x12, /*!< Regular conversion is ongoing */ HAL_ADC_STATE_BUSY_INJ = 0x22, /*!< Injected conversion is ongoing */ HAL_ADC_STATE_BUSY_INJ_REG = 0x32, /*!< Injected and regular conversion are ongoing */ HAL_ADC_STATE_TIMEOUT = 0x03, /*!< Timeout state */ HAL_ADC_STATE_ERROR = 0x04, /*!< ADC state error */ HAL_ADC_STATE_EOC = 0x05, /*!< Conversion is completed */ HAL_ADC_STATE_EOC_REG = 0x15, /*!< Regular conversion is completed */ HAL_ADC_STATE_EOC_INJ = 0x25, /*!< Injected conversion is completed */ HAL_ADC_STATE_EOC_INJ_REG = 0x35, /*!< Injected and regular conversion are completed */ HAL_ADC_STATE_AWD = 0x06, /*!< ADC state analog watchdog */ HAL_ADC_STATE_AWD2 = 0x07, /*!< Not used on STM32L1xx devices (kept for compatibility with other devices featuring several AWD) */ HAL_ADC_STATE_AWD3 = 0x08, /*!< Not used on STM32l1xx devices (kept for compatibility with other devices featuring several AWD) */ }HAL_ADC_StateTypeDef; /** * @brief ADC handle Structure definition */ typedef struct { ADC_TypeDef *Instance; /*!< Register base address */ ADC_InitTypeDef Init; /*!< ADC required parameters */ __IO uint32_t NbrOfConversionRank ; /*!< ADC conversion rank counter */ DMA_HandleTypeDef *DMA_Handle; /*!< Pointer DMA Handler */ HAL_LockTypeDef Lock; /*!< ADC locking object */ __IO HAL_ADC_StateTypeDef State; /*!< ADC communication state */ __IO uint32_t ErrorCode; /*!< ADC Error code */ }ADC_HandleTypeDef; /** * @} */ /* Exported constants --------------------------------------------------------*/ /** @defgroup ADC_Exported_Constants ADC Exported Constants * @{ */ /** @defgroup ADC_Error_Code ADC Error Code * @{ */ #define HAL_ADC_ERROR_NONE ((uint32_t)0x00) /*!< No error */ #define HAL_ADC_ERROR_INTERNAL ((uint32_t)0x01) /*!< ADC IP internal error: if problem of clocking, enable/disable, erroneous state */ #define HAL_ADC_ERROR_OVR ((uint32_t)0x02) /*!< Overrun error */ #define HAL_ADC_ERROR_DMA ((uint32_t)0x04) /*!< DMA transfer error */ /** * @} */ /** @defgroup ADC_ClockPrescaler ADC ClockPrescaler * @{ */ #define ADC_CLOCK_ASYNC_DIV1 ((uint32_t)0x00000000) /*!< ADC asynchronous clock derived from ADC dedicated HSI without prescaler */ #define ADC_CLOCK_ASYNC_DIV2 ((uint32_t)ADC_CCR_ADCPRE_0) /*!< ADC asynchronous clock derived from ADC dedicated HSI divided by a prescaler of 2 */ #define ADC_CLOCK_ASYNC_DIV4 ((uint32_t)ADC_CCR_ADCPRE_1) /*!< ADC asynchronous clock derived from ADC dedicated HSI divided by a prescaler of 4 */ #define IS_ADC_CLOCKPRESCALER(ADC_CLOCK) (((ADC_CLOCK) == ADC_CLOCK_ASYNC_DIV1) || \ ((ADC_CLOCK) == ADC_CLOCK_ASYNC_DIV2) || \ ((ADC_CLOCK) == ADC_CLOCK_ASYNC_DIV4) ) /** * @} */ /** @defgroup ADC_Resolution ADC Resolution * @{ */ #define ADC_RESOLUTION12b ((uint32_t)0x00000000) /*!< ADC 12-bit resolution */ #define ADC_RESOLUTION10b ((uint32_t)ADC_CR1_RES_0) /*!< ADC 10-bit resolution */ #define ADC_RESOLUTION8b ((uint32_t)ADC_CR1_RES_1) /*!< ADC 8-bit resolution */ #define ADC_RESOLUTION6b ((uint32_t)ADC_CR1_RES) /*!< ADC 6-bit resolution */ #define IS_ADC_RESOLUTION(RESOLUTION) (((RESOLUTION) == ADC_RESOLUTION12b) || \ ((RESOLUTION) == ADC_RESOLUTION10b) || \ ((RESOLUTION) == ADC_RESOLUTION8b) || \ ((RESOLUTION) == ADC_RESOLUTION6b) ) #define IS_ADC_RESOLUTION_8_6_BITS(RESOLUTION) (((RESOLUTION) == ADC_RESOLUTION8b) || \ ((RESOLUTION) == ADC_RESOLUTION6b) ) /** * @} */ /** @defgroup ADC_Data_align ADC Data_align * @{ */ #define ADC_DATAALIGN_RIGHT ((uint32_t)0x00000000) #define ADC_DATAALIGN_LEFT ((uint32_t)ADC_CR2_ALIGN) #define IS_ADC_DATA_ALIGN(ALIGN) (((ALIGN) == ADC_DATAALIGN_RIGHT) || \ ((ALIGN) == ADC_DATAALIGN_LEFT) ) /** * @} */ /** @defgroup ADC_Scan_mode ADC Scan mode * @{ */ #define ADC_SCAN_DISABLE ((uint32_t)0x00000000) #define ADC_SCAN_ENABLE ((uint32_t)0x00000001) #define IS_ADC_SCAN_MODE(SCAN_MODE) (((SCAN_MODE) == ADC_SCAN_DISABLE) || \ ((SCAN_MODE) == ADC_SCAN_ENABLE) ) /** * @} */ /** @defgroup ADC_External_trigger_edge_Regular ADC External trigger edge Regular * @{ */ #define ADC_EXTERNALTRIGCONVEDGE_NONE ((uint32_t)0x00000000) #define ADC_EXTERNALTRIGCONVEDGE_RISING ((uint32_t)ADC_CR2_EXTEN_0) #define ADC_EXTERNALTRIGCONVEDGE_FALLING ((uint32_t)ADC_CR2_EXTEN_1) #define ADC_EXTERNALTRIGCONVEDGE_RISINGFALLING ((uint32_t)ADC_CR2_EXTEN) #define IS_ADC_EXTTRIG_EDGE(EDGE) (((EDGE) == ADC_EXTERNALTRIGCONVEDGE_NONE) || \ ((EDGE) == ADC_EXTERNALTRIGCONVEDGE_RISING) || \ ((EDGE) == ADC_EXTERNALTRIGCONVEDGE_FALLING) || \ ((EDGE) == ADC_EXTERNALTRIGCONVEDGE_RISINGFALLING) ) /** * @} */ /** @defgroup ADC_External_trigger_source_Regular ADC External trigger source Regular * @{ */ /* List of external triggers with generic trigger name, sorted by trigger */ /* name: */ /* External triggers of regular group for ADC1 */ #define ADC_EXTERNALTRIGCONV_T2_CC3 ADC_EXTERNALTRIG_T2_CC3 #define ADC_EXTERNALTRIGCONV_T2_CC2 ADC_EXTERNALTRIG_T2_CC2 #define ADC_EXTERNALTRIGCONV_T2_TRGO ADC_EXTERNALTRIG_T2_TRGO #define ADC_EXTERNALTRIGCONV_T3_CC1 ADC_EXTERNALTRIG_T3_CC1 #define ADC_EXTERNALTRIGCONV_T3_CC3 ADC_EXTERNALTRIG_T3_CC3 #define ADC_EXTERNALTRIGCONV_T3_TRGO ADC_EXTERNALTRIG_T3_TRGO #define ADC_EXTERNALTRIGCONV_T4_CC4 ADC_EXTERNALTRIG_T4_CC4 #define ADC_EXTERNALTRIGCONV_T4_TRGO ADC_EXTERNALTRIG_T4_TRGO #define ADC_EXTERNALTRIGCONV_T6_TRGO ADC_EXTERNALTRIG_T6_TRGO #define ADC_EXTERNALTRIGCONV_T9_CC2 ADC_EXTERNALTRIG_T9_CC2 #define ADC_EXTERNALTRIGCONV_T9_TRGO ADC_EXTERNALTRIG_T9_TRGO #define ADC_EXTERNALTRIGCONV_EXT_IT11 ADC_EXTERNALTRIG_EXT_IT11 #define ADC_SOFTWARE_START ((uint32_t)0x00000010) #define IS_ADC_EXTTRIG(REGTRIG) (((REGTRIG) == ADC_EXTERNALTRIGCONV_T2_CC3) || \ ((REGTRIG) == ADC_EXTERNALTRIGCONV_T2_CC2) || \ ((REGTRIG) == ADC_EXTERNALTRIGCONV_T2_TRGO) || \ ((REGTRIG) == ADC_EXTERNALTRIGCONV_T3_CC1) || \ ((REGTRIG) == ADC_EXTERNALTRIGCONV_T3_CC3) || \ ((REGTRIG) == ADC_EXTERNALTRIGCONV_T3_TRGO) || \ ((REGTRIG) == ADC_EXTERNALTRIGCONV_T4_CC4) || \ ((REGTRIG) == ADC_EXTERNALTRIGCONV_T4_TRGO) || \ ((REGTRIG) == ADC_EXTERNALTRIGCONV_T6_TRGO) || \ ((REGTRIG) == ADC_EXTERNALTRIGCONV_T9_CC2) || \ ((REGTRIG) == ADC_EXTERNALTRIGCONV_T9_TRGO) || \ ((REGTRIG) == ADC_EXTERNALTRIGCONV_EXT_IT11) || \ ((REGTRIG) == ADC_SOFTWARE_START) ) /** * @} */ /** @defgroup ADC_Internal_HAL_driver_Ext_trig_src_Regular ADC Internal HAL driver Ext trig src Regular * @{ */ /* List of external triggers of regular group for ADC1: */ /* (used internally by HAL driver. To not use into HAL structure parameters) */ /* External triggers of regular group for ADC1 */ #define ADC_EXTERNALTRIG_T9_CC2 ((uint32_t) 0x00000000) #define ADC_EXTERNALTRIG_T9_TRGO ((uint32_t)( ADC_CR2_EXTSEL_0)) #define ADC_EXTERNALTRIG_T2_CC3 ((uint32_t)( ADC_CR2_EXTSEL_1 )) #define ADC_EXTERNALTRIG_T2_CC2 ((uint32_t)( ADC_CR2_EXTSEL_1 | ADC_CR2_EXTSEL_0)) #define ADC_EXTERNALTRIG_T3_TRGO ((uint32_t)( ADC_CR2_EXTSEL_2 )) #define ADC_EXTERNALTRIG_T4_CC4 ((uint32_t)( ADC_CR2_EXTSEL_2 | ADC_CR2_EXTSEL_0)) #define ADC_EXTERNALTRIG_T2_TRGO ((uint32_t)( ADC_CR2_EXTSEL_2 | ADC_CR2_EXTSEL_1 )) #define ADC_EXTERNALTRIG_T3_CC1 ((uint32_t)( ADC_CR2_EXTSEL_2 | ADC_CR2_EXTSEL_1 | ADC_CR2_EXTSEL_0)) #define ADC_EXTERNALTRIG_T3_CC3 ((uint32_t)(ADC_CR2_EXTSEL_3 )) #define ADC_EXTERNALTRIG_T4_TRGO ((uint32_t)(ADC_CR2_EXTSEL_3 | ADC_CR2_EXTSEL_0)) #define ADC_EXTERNALTRIG_T6_TRGO ((uint32_t)(ADC_CR2_EXTSEL_3 | ADC_CR2_EXTSEL_1 )) #define ADC_EXTERNALTRIG_EXT_IT11 ((uint32_t)(ADC_CR2_EXTSEL_3 | ADC_CR2_EXTSEL_2 | ADC_CR2_EXTSEL_1 | ADC_CR2_EXTSEL_0)) /** * @} */ /** @defgroup ADC_EOCSelection ADC EOCSelection * @{ */ #define EOC_SEQ_CONV ((uint32_t)0x00000000) #define EOC_SINGLE_CONV ((uint32_t)ADC_CR2_EOCS) #define IS_ADC_EOC_SELECTION(EOC_SELECTION) (((EOC_SELECTION) == EOC_SINGLE_CONV) || \ ((EOC_SELECTION) == EOC_SEQ_CONV) ) /** * @} */ /** @defgroup ADC_LowPowerAutoWait ADC LowPowerAutoWait * @{ */ /*!< Note : For compatibility with other STM32 devices with ADC autowait */ /* feature limited to enable or disable settings: */ /* Setting "ADC_AUTOWAIT_UNTIL_DATA_READ" is equivalent to "ENABLE". */ #define ADC_AUTOWAIT_DISABLE ((uint32_t)0x00000000) #define ADC_AUTOWAIT_UNTIL_DATA_READ ((uint32_t)( ADC_CR2_DELS_0)) /*!< Insert a delay between ADC conversions: infinite delay, until the result of previous conversion is read */ #define ADC_AUTOWAIT_7_APBCLOCKCYCLES ((uint32_t)( ADC_CR2_DELS_1 )) /*!< Insert a delay between ADC conversions: 7 APB clock cycles */ #define ADC_AUTOWAIT_15_APBCLOCKCYCLES ((uint32_t)( ADC_CR2_DELS_1 | ADC_CR2_DELS_0)) /*!< Insert a delay between ADC conversions: 15 APB clock cycles */ #define ADC_AUTOWAIT_31_APBCLOCKCYCLES ((uint32_t)(ADC_CR2_DELS_2 )) /*!< Insert a delay between ADC conversions: 31 APB clock cycles */ #define ADC_AUTOWAIT_63_APBCLOCKCYCLES ((uint32_t)(ADC_CR2_DELS_2 | ADC_CR2_DELS_0)) /*!< Insert a delay between ADC conversions: 63 APB clock cycles */ #define ADC_AUTOWAIT_127_APBCLOCKCYCLES ((uint32_t)(ADC_CR2_DELS_2 | ADC_CR2_DELS_1 )) /*!< Insert a delay between ADC conversions: 127 APB clock cycles */ #define ADC_AUTOWAIT_255_APBCLOCKCYCLES ((uint32_t)(ADC_CR2_DELS_2 | ADC_CR2_DELS_1 | ADC_CR2_DELS_0)) /*!< Insert a delay between ADC conversions: 255 APB clock cycles */ #define IS_ADC_AUTOWAIT(AUTOWAIT) (((AUTOWAIT) == ADC_AUTOWAIT_DISABLE) || \ ((AUTOWAIT) == ADC_AUTOWAIT_UNTIL_DATA_READ) || \ ((AUTOWAIT) == ADC_AUTOWAIT_7_APBCLOCKCYCLES) || \ ((AUTOWAIT) == ADC_AUTOWAIT_15_APBCLOCKCYCLES) || \ ((AUTOWAIT) == ADC_AUTOWAIT_31_APBCLOCKCYCLES) || \ ((AUTOWAIT) == ADC_AUTOWAIT_63_APBCLOCKCYCLES) || \ ((AUTOWAIT) == ADC_AUTOWAIT_127_APBCLOCKCYCLES) || \ ((AUTOWAIT) == ADC_AUTOWAIT_255_APBCLOCKCYCLES) ) /** * @} */ /** @defgroup ADC_LowPowerAutoPowerOff ADC LowPowerAutoPowerOff * @{ */ #define ADC_AUTOPOWEROFF_DISABLE ((uint32_t)0x00000000) #define ADC_AUTOPOWEROFF_IDLE_PHASE ((uint32_t)ADC_CR1_PDI) /*!< ADC power off when ADC is not converting (idle phase) */ #define ADC_AUTOPOWEROFF_DELAY_PHASE ((uint32_t)ADC_CR1_PDD) /*!< ADC power off when a delay is inserted between conversions (see parameter ADC_LowPowerAutoWait) */ #define ADC_AUTOPOWEROFF_IDLE_DELAY_PHASES ((uint32_t)(ADC_CR1_PDI | ADC_CR1_PDD)) /*!< ADC power off when ADC is not converting (idle phase) and when a delay is inserted between conversions */ #define IS_ADC_AUTOPOWEROFF(AUTOPOWEROFF) (((AUTOPOWEROFF) == ADC_AUTOPOWEROFF_DISABLE) || \ ((AUTOPOWEROFF) == ADC_AUTOPOWEROFF_IDLE_PHASE) || \ ((AUTOPOWEROFF) == ADC_AUTOPOWEROFF_DELAY_PHASE) || \ ((AUTOPOWEROFF) == ADC_AUTOPOWEROFF_IDLE_DELAY_PHASES) ) /** * @} */ /** @defgroup ADC_ChannelsBank ADC ChannelsBank * @{ */ #if defined(STM32L100xC) || defined (STM32L151xC) || defined (STM32L152xC) || defined (STM32L162xC) || defined(STM32L151xCA) || defined (STM32L151xD) || defined (STM32L152xCA) || defined (STM32L152xD) || defined (STM32L162xCA) || defined (STM32L162xD) || defined(STM32L151xE) || defined (STM32L152xE) || defined (STM32L162xE) #define ADC_CHANNELS_BANK_A ((uint32_t)0x00000000) #define ADC_CHANNELS_BANK_B ((uint32_t)ADC_CR2_CFG) #define IS_ADC_CHANNELSBANK(BANK) (((BANK) == ADC_CHANNELS_BANK_A) || \ ((BANK) == ADC_CHANNELS_BANK_B) ) #else #define ADC_CHANNELS_BANK_A ((uint32_t)0x00000000) #define IS_ADC_CHANNELSBANK(BANK) (((BANK) == ADC_CHANNELS_BANK_A)) #endif /* STM32L100xC || STM32L151xC || STM32L152xC || STM32L162xC || STM32L151xCA || STM32L151xD || STM32L152xCA || STM32L152xD || STM32L162xCA || STM32L162xD || STM32L151xE || STM32L152xE || STM32L162xE */ /** * @} */ /** @defgroup ADC_channels ADC channels * @{ */ /* Note: Depending on devices, some channels may not be available on package */ /* pins. Refer to device datasheet for channels availability. */ #define ADC_CHANNEL_0 ((uint32_t)0x00000000) /* Channel different in bank A and bank B */ #define ADC_CHANNEL_1 ((uint32_t)( ADC_SQR5_SQ1_0)) /* Channel different in bank A and bank B */ #define ADC_CHANNEL_2 ((uint32_t)( ADC_SQR5_SQ1_1 )) /* Channel different in bank A and bank B */ #define ADC_CHANNEL_3 ((uint32_t)( ADC_SQR5_SQ1_1 | ADC_SQR5_SQ1_0)) /* Channel different in bank A and bank B */ #define ADC_CHANNEL_4 ((uint32_t)( ADC_SQR5_SQ1_2 )) /* Direct (fast) channel */ #define ADC_CHANNEL_5 ((uint32_t)( ADC_SQR5_SQ1_2 | ADC_SQR5_SQ1_0)) /* Direct (fast) channel */ #define ADC_CHANNEL_6 ((uint32_t)( ADC_SQR5_SQ1_2 | ADC_SQR5_SQ1_1 )) /* Channel different in bank A and bank B */ #define ADC_CHANNEL_7 ((uint32_t)( ADC_SQR5_SQ1_2 | ADC_SQR5_SQ1_1 | ADC_SQR5_SQ1_0)) /* Channel different in bank A and bank B */ #define ADC_CHANNEL_8 ((uint32_t)( ADC_SQR5_SQ1_3 )) /* Channel different in bank A and bank B */ #define ADC_CHANNEL_9 ((uint32_t)( ADC_SQR5_SQ1_3 | ADC_SQR5_SQ1_0)) /* Channel different in bank A and bank B */ #define ADC_CHANNEL_10 ((uint32_t)( ADC_SQR5_SQ1_3 | ADC_SQR5_SQ1_1 )) /* Channel different in bank A and bank B */ #define ADC_CHANNEL_11 ((uint32_t)( ADC_SQR5_SQ1_3 | ADC_SQR5_SQ1_1 | ADC_SQR5_SQ1_0)) /* Channel different in bank A and bank B */ #define ADC_CHANNEL_12 ((uint32_t)( ADC_SQR5_SQ1_3 | ADC_SQR5_SQ1_2 )) /* Channel different in bank A and bank B */ #define ADC_CHANNEL_13 ((uint32_t)( ADC_SQR5_SQ1_3 | ADC_SQR5_SQ1_2 | ADC_SQR5_SQ1_0)) /* Channel common to both bank A and bank B */ #define ADC_CHANNEL_14 ((uint32_t)( ADC_SQR5_SQ1_3 | ADC_SQR5_SQ1_2 | ADC_SQR5_SQ1_1 )) /* Channel common to both bank A and bank B */ #define ADC_CHANNEL_15 ((uint32_t)( ADC_SQR5_SQ1_3 | ADC_SQR5_SQ1_2 | ADC_SQR5_SQ1_1 | ADC_SQR5_SQ1_0)) /* Channel common to both bank A and bank B */ #define ADC_CHANNEL_16 ((uint32_t)(ADC_SQR5_SQ1_4 )) /* Channel common to both bank A and bank B */ #define ADC_CHANNEL_17 ((uint32_t)(ADC_SQR5_SQ1_4 | ADC_SQR5_SQ1_0)) /* Channel common to both bank A and bank B */ #define ADC_CHANNEL_18 ((uint32_t)(ADC_SQR5_SQ1_4 | ADC_SQR5_SQ1_1 )) /* Channel common to both bank A and bank B */ #define ADC_CHANNEL_19 ((uint32_t)(ADC_SQR5_SQ1_4 | ADC_SQR5_SQ1_1 | ADC_SQR5_SQ1_0)) /* Channel common to both bank A and bank B */ #define ADC_CHANNEL_20 ((uint32_t)(ADC_SQR5_SQ1_4 | ADC_SQR5_SQ1_2 )) /* Channel common to both bank A and bank B */ #define ADC_CHANNEL_21 ((uint32_t)(ADC_SQR5_SQ1_4 | ADC_SQR5_SQ1_2 | ADC_SQR5_SQ1_0)) /* Channel common to both bank A and bank B */ #define ADC_CHANNEL_22 ((uint32_t)(ADC_SQR5_SQ1_4 | ADC_SQR5_SQ1_2 | ADC_SQR5_SQ1_1 )) /* Direct (fast) channel */ #define ADC_CHANNEL_23 ((uint32_t)(ADC_SQR5_SQ1_4 | ADC_SQR5_SQ1_2 | ADC_SQR5_SQ1_1 | ADC_SQR5_SQ1_0)) /* Direct (fast) channel */ #define ADC_CHANNEL_24 ((uint32_t)(ADC_SQR5_SQ1_4 | ADC_SQR5_SQ1_3 )) /* Direct (fast) channel */ #define ADC_CHANNEL_25 ((uint32_t)(ADC_SQR5_SQ1_4 | ADC_SQR5_SQ1_3 | ADC_SQR5_SQ1_0)) /* Direct (fast) channel */ #define ADC_CHANNEL_26 ((uint32_t)(ADC_SQR5_SQ1_4 | ADC_SQR5_SQ1_3 | ADC_SQR5_SQ1_1 )) /* Channel common to both bank A and bank B */ #if defined(STM32L151xCA) || defined (STM32L151xD) || defined (STM32L152xCA) || defined (STM32L152xD) || defined (STM32L162xCA) || defined (STM32L162xD) || defined(STM32L151xE) || defined (STM32L152xE) || defined (STM32L162xE) #define ADC_CHANNEL_27 ((uint32_t)(ADC_SQR5_SQ1_4 | ADC_SQR5_SQ1_3 | ADC_SQR5_SQ1_1 | ADC_SQR5_SQ1_0)) /* Channel common to both bank A and bank B */ #define ADC_CHANNEL_28 ((uint32_t)(ADC_SQR5_SQ1_4 | ADC_SQR5_SQ1_3 | ADC_SQR5_SQ1_2 )) /* Channel common to both bank A and bank B */ #define ADC_CHANNEL_29 ((uint32_t)(ADC_SQR5_SQ1_4 | ADC_SQR5_SQ1_3 | ADC_SQR5_SQ1_2 | ADC_SQR5_SQ1_0)) /* Channel common to both bank A and bank B */ #define ADC_CHANNEL_30 ((uint32_t)(ADC_SQR5_SQ1_4 | ADC_SQR5_SQ1_3 | ADC_SQR5_SQ1_2 | ADC_SQR5_SQ1_1 )) /* Channel common to both bank A and bank B */ #define ADC_CHANNEL_31 ((uint32_t)(ADC_SQR5_SQ1_4 | ADC_SQR5_SQ1_3 | ADC_SQR5_SQ1_2 | ADC_SQR5_SQ1_1 | ADC_SQR5_SQ1_0)) /* Channel common to both bank A and bank B */ #endif /* STM32L151xCA || STM32L151xD || STM32L152xCA || STM32L152xD || STM32L162xCA || STM32L162xD || STM32L151xE || STM32L152xE || STM32L162xE */ #define ADC_CHANNEL_TEMPSENSOR ADC_CHANNEL_16 /* ADC internal channel (no connection on device pin). Channel common to both bank A and bank B. */ #define ADC_CHANNEL_VREFINT ADC_CHANNEL_17 /* ADC internal channel (no connection on device pin). Channel common to both bank A and bank B. */ #define ADC_CHANNEL_VCOMP ADC_CHANNEL_26 /* ADC internal channel (no connection on device pin). Channel common to both bank A and bank B. */ #if defined(STM32L100xC) || defined (STM32L151xC) || defined (STM32L152xC) || defined (STM32L162xC) || defined(STM32L151xCA) || defined (STM32L151xD) || defined (STM32L152xCA) || defined (STM32L152xD) || defined (STM32L162xCA) || defined (STM32L162xD) || defined(STM32L151xE) || defined (STM32L152xE) || defined (STM32L162xE) #define ADC_CHANNEL_VOPAMP1 ADC_CHANNEL_3 /* Internal connection from OPAMP1 output to ADC switch matrix */ #define ADC_CHANNEL_VOPAMP2 ADC_CHANNEL_8 /* Internal connection from OPAMP2 output to ADC switch matrix */ #if defined(STM32L151xCA) || defined (STM32L151xD) || defined (STM32L152xCA) || defined (STM32L152xD) || defined (STM32L162xCA) || defined (STM32L162xD) #define ADC_CHANNEL_VOPAMP3 ADC_CHANNEL_13 /* Internal connection from OPAMP3 output to ADC switch matrix */ #endif /* STM32L151xCA || STM32L151xD || STM32L152xCA || STM32L152xD || STM32L162xCA || STM32L162xD */ #endif /* STM32L100xC || STM32L151xC || STM32L152xC || STM32L162xC || STM32L151xCA || STM32L151xD || STM32L152xCA || STM32L152xD || STM32L162xCA || STM32L162xD || STM32L151xE || STM32L152xE || STM32L162xE */ #if defined(STM32L100xB) || defined (STM32L151xB) || defined (STM32L152xB) || defined(STM32L100xBA) || defined (STM32L151xBA) || defined (STM32L152xBA) || defined(STM32L100xC) || defined (STM32L151xC) || defined (STM32L152xC) || defined (STM32L162xC) #define IS_ADC_CHANNEL(CHANNEL) (((CHANNEL) == ADC_CHANNEL_0) || \ ((CHANNEL) == ADC_CHANNEL_1) || \ ((CHANNEL) == ADC_CHANNEL_2) || \ ((CHANNEL) == ADC_CHANNEL_3) || \ ((CHANNEL) == ADC_CHANNEL_4) || \ ((CHANNEL) == ADC_CHANNEL_5) || \ ((CHANNEL) == ADC_CHANNEL_6) || \ ((CHANNEL) == ADC_CHANNEL_7) || \ ((CHANNEL) == ADC_CHANNEL_8) || \ ((CHANNEL) == ADC_CHANNEL_9) || \ ((CHANNEL) == ADC_CHANNEL_10) || \ ((CHANNEL) == ADC_CHANNEL_11) || \ ((CHANNEL) == ADC_CHANNEL_12) || \ ((CHANNEL) == ADC_CHANNEL_13) || \ ((CHANNEL) == ADC_CHANNEL_14) || \ ((CHANNEL) == ADC_CHANNEL_15) || \ ((CHANNEL) == ADC_CHANNEL_16) || \ ((CHANNEL) == ADC_CHANNEL_17) || \ ((CHANNEL) == ADC_CHANNEL_18) || \ ((CHANNEL) == ADC_CHANNEL_19) || \ ((CHANNEL) == ADC_CHANNEL_20) || \ ((CHANNEL) == ADC_CHANNEL_21) || \ ((CHANNEL) == ADC_CHANNEL_22) || \ ((CHANNEL) == ADC_CHANNEL_23) || \ ((CHANNEL) == ADC_CHANNEL_24) || \ ((CHANNEL) == ADC_CHANNEL_25) || \ ((CHANNEL) == ADC_CHANNEL_26) ) #endif /* STM32L100xB || STM32L151xB || STM32L152xB || STM32L100xBA || STM32L151xBA || STM32L152xBA || STM32L100xC || STM32L151xC || STM32L152xC || STM32L162xC */ #if defined(STM32L151xCA) || defined (STM32L151xD) || defined (STM32L152xCA) || defined (STM32L152xD) || defined (STM32L162xCA) || defined (STM32L162xD) || defined(STM32L151xE) || defined (STM32L152xE) || defined (STM32L162xE) #define IS_ADC_CHANNEL(CHANNEL) (((CHANNEL) == ADC_CHANNEL_0) || \ ((CHANNEL) == ADC_CHANNEL_1) || \ ((CHANNEL) == ADC_CHANNEL_2) || \ ((CHANNEL) == ADC_CHANNEL_3) || \ ((CHANNEL) == ADC_CHANNEL_4) || \ ((CHANNEL) == ADC_CHANNEL_5) || \ ((CHANNEL) == ADC_CHANNEL_6) || \ ((CHANNEL) == ADC_CHANNEL_7) || \ ((CHANNEL) == ADC_CHANNEL_8) || \ ((CHANNEL) == ADC_CHANNEL_9) || \ ((CHANNEL) == ADC_CHANNEL_10) || \ ((CHANNEL) == ADC_CHANNEL_11) || \ ((CHANNEL) == ADC_CHANNEL_12) || \ ((CHANNEL) == ADC_CHANNEL_13) || \ ((CHANNEL) == ADC_CHANNEL_14) || \ ((CHANNEL) == ADC_CHANNEL_15) || \ ((CHANNEL) == ADC_CHANNEL_16) || \ ((CHANNEL) == ADC_CHANNEL_17) || \ ((CHANNEL) == ADC_CHANNEL_18) || \ ((CHANNEL) == ADC_CHANNEL_19) || \ ((CHANNEL) == ADC_CHANNEL_20) || \ ((CHANNEL) == ADC_CHANNEL_21) || \ ((CHANNEL) == ADC_CHANNEL_22) || \ ((CHANNEL) == ADC_CHANNEL_23) || \ ((CHANNEL) == ADC_CHANNEL_24) || \ ((CHANNEL) == ADC_CHANNEL_25) || \ ((CHANNEL) == ADC_CHANNEL_26) || \ ((CHANNEL) == ADC_CHANNEL_27) || \ ((CHANNEL) == ADC_CHANNEL_28) || \ ((CHANNEL) == ADC_CHANNEL_29) || \ ((CHANNEL) == ADC_CHANNEL_30) || \ ((CHANNEL) == ADC_CHANNEL_31) ) #endif /* STM32L151xCA || STM32L151xD || STM32L152xCA || STM32L152xD || STM32L162xCA || STM32L162xD || STM32L151xE || STM32L152xE || STM32L162xE */ /** * @} */ /** @defgroup ADC_sampling_times ADC sampling times * @{ */ #define ADC_SAMPLETIME_4CYCLES ((uint32_t)0x00000000) /*!< Sampling time 4 ADC clock cycles */ #define ADC_SAMPLETIME_9CYCLES ((uint32_t) ADC_SMPR3_SMP0_0) /*!< Sampling time 9 ADC clock cycles */ #define ADC_SAMPLETIME_16CYCLES ((uint32_t) ADC_SMPR3_SMP0_1) /*!< Sampling time 16 ADC clock cycles */ #define ADC_SAMPLETIME_24CYCLES ((uint32_t)(ADC_SMPR3_SMP0_1 | ADC_SMPR3_SMP0_0)) /*!< Sampling time 24 ADC clock cycles */ #define ADC_SAMPLETIME_48CYCLES ((uint32_t) ADC_SMPR3_SMP0_2) /*!< Sampling time 48 ADC clock cycles */ #define ADC_SAMPLETIME_96CYCLES ((uint32_t)(ADC_SMPR3_SMP0_2 | ADC_SMPR3_SMP0_0)) /*!< Sampling time 96 ADC clock cycles */ #define ADC_SAMPLETIME_192CYCLES ((uint32_t)(ADC_SMPR3_SMP0_2 | ADC_SMPR3_SMP0_1)) /*!< Sampling time 192 ADC clock cycles */ #define ADC_SAMPLETIME_384CYCLES ((uint32_t) ADC_SMPR3_SMP0) /*!< Sampling time 384 ADC clock cycles */ #define IS_ADC_SAMPLE_TIME(TIME) (((TIME) == ADC_SAMPLETIME_4CYCLES) || \ ((TIME) == ADC_SAMPLETIME_9CYCLES) || \ ((TIME) == ADC_SAMPLETIME_16CYCLES) || \ ((TIME) == ADC_SAMPLETIME_24CYCLES) || \ ((TIME) == ADC_SAMPLETIME_48CYCLES) || \ ((TIME) == ADC_SAMPLETIME_96CYCLES) || \ ((TIME) == ADC_SAMPLETIME_192CYCLES) || \ ((TIME) == ADC_SAMPLETIME_384CYCLES) ) /** * @} */ /** @defgroup ADC_sampling_times_all_channels ADC sampling times all channels * @{ */ #define ADC_SAMPLETIME_ALLCHANNELS_SMPR3BIT2 \ (ADC_SMPR3_SMP9_2 | ADC_SMPR3_SMP8_2 | ADC_SMPR3_SMP7_2 | ADC_SMPR3_SMP6_2 | \ ADC_SMPR3_SMP5_2 | ADC_SMPR3_SMP4_2 | ADC_SMPR3_SMP3_2 | ADC_SMPR3_SMP2_2 | \ ADC_SMPR3_SMP1_2 | ADC_SMPR3_SMP0_2) #define ADC_SAMPLETIME_ALLCHANNELS_SMPR2BIT2 \ (ADC_SMPR2_SMP19_2 | ADC_SMPR2_SMP18_2 | ADC_SMPR2_SMP17_2 | ADC_SMPR2_SMP16_2 | \ ADC_SMPR2_SMP15_2 | ADC_SMPR2_SMP14_2 | ADC_SMPR2_SMP13_2 | ADC_SMPR2_SMP12_2 | \ ADC_SMPR2_SMP11_2 | ADC_SMPR2_SMP10_2) #if defined(STM32L100xB) || defined (STM32L151xB) || defined (STM32L152xB) || defined(STM32L100xBA) || defined (STM32L151xBA) || defined (STM32L152xBA) || defined(STM32L100xC) || defined (STM32L151xC) || defined (STM32L152xC) || defined (STM32L162xC) #define ADC_SAMPLETIME_ALLCHANNELS_SMPR1BIT2 \ (ADC_SMPR1_SMP26_2 | ADC_SMPR1_SMP25_2 | ADC_SMPR1_SMP24_2 | ADC_SMPR1_SMP23_2 | \ ADC_SMPR1_SMP22_2 | ADC_SMPR1_SMP21_2 | ADC_SMPR1_SMP20_2) #endif /* STM32L100xB || STM32L151xB || STM32L152xB || STM32L100xBA || STM32L151xBA || STM32L152xBA || STM32L100xC || STM32L151xC || STM32L152xC || STM32L162xC */ #if defined(STM32L151xCA) || defined (STM32L151xD) || defined (STM32L152xCA) || defined (STM32L152xD) || defined (STM32L162xCA) || defined (STM32L162xD) || defined(STM32L151xE) || defined (STM32L152xE) || defined (STM32L162xE) #define ADC_SAMPLETIME_ALLCHANNELS_SMPR1BIT2 \ (ADC_SMPR1_SMP29_2 | ADC_SMPR1_SMP28_2 | ADC_SMPR1_SMP27_2 | ADC_SMPR1_SMP26_2 | \ ADC_SMPR1_SMP25_2 | ADC_SMPR1_SMP24_2 | ADC_SMPR1_SMP23_2 | ADC_SMPR1_SMP22_2 | \ ADC_SMPR1_SMP21_2 | ADC_SMPR1_SMP20_2) #define ADC_SAMPLETIME_ALLCHANNELS_SMPR0BIT2 \ (ADC_SMPR0_SMP31_2 | ADC_SMPR0_SMP30_2 ) #endif /* STM32L151xCA || STM32L151xD || STM32L152xCA || STM32L152xD || STM32L162xCA || STM32L162xD || STM32L151xE || STM32L152xE || STM32L162xE */ #define ADC_SAMPLETIME_ALLCHANNELS_SMPR3BIT1 \ (ADC_SMPR3_SMP9_1 | ADC_SMPR3_SMP8_1 | ADC_SMPR3_SMP7_1 | ADC_SMPR3_SMP6_1 | \ ADC_SMPR3_SMP5_1 | ADC_SMPR3_SMP4_1 | ADC_SMPR3_SMP3_1 | ADC_SMPR3_SMP2_1 | \ ADC_SMPR3_SMP1_1 | ADC_SMPR3_SMP0_1) #define ADC_SAMPLETIME_ALLCHANNELS_SMPR2BIT1 \ (ADC_SMPR2_SMP19_1 | ADC_SMPR2_SMP18_1 | ADC_SMPR2_SMP17_1 | ADC_SMPR2_SMP16_1 | \ ADC_SMPR2_SMP15_1 | ADC_SMPR2_SMP14_1 | ADC_SMPR2_SMP13_1 | ADC_SMPR2_SMP12_1 | \ ADC_SMPR2_SMP11_1 | ADC_SMPR2_SMP10_1) #if defined(STM32L100xB) || defined (STM32L151xB) || defined (STM32L152xB) || defined(STM32L100xBA) || defined (STM32L151xBA) || defined (STM32L152xBA) || defined(STM32L100xC) || defined (STM32L151xC) || defined (STM32L152xC) || defined (STM32L162xC) #define ADC_SAMPLETIME_ALLCHANNELS_SMPR1BIT1 \ (ADC_SMPR1_SMP26_1 | ADC_SMPR1_SMP25_1 | ADC_SMPR1_SMP24_1 | ADC_SMPR1_SMP23_1 | \ ADC_SMPR1_SMP22_1 | ADC_SMPR1_SMP21_1 | ADC_SMPR1_SMP20_1) #endif /* STM32L100xB || STM32L151xB || STM32L152xB || STM32L100xBA || STM32L151xBA || STM32L152xBA || STM32L100xC || STM32L151xC || STM32L152xC || STM32L162xC */ #if defined(STM32L151xCA) || defined (STM32L151xD) || defined (STM32L152xCA) || defined (STM32L152xD) || defined (STM32L162xCA) || defined (STM32L162xD) || defined(STM32L151xE) || defined (STM32L152xE) || defined (STM32L162xE) #define ADC_SAMPLETIME_ALLCHANNELS_SMPR1BIT1 \ (ADC_SMPR1_SMP29_1 | ADC_SMPR1_SMP28_1 | ADC_SMPR1_SMP27_1 | ADC_SMPR1_SMP26_1 | \ ADC_SMPR1_SMP25_1 | ADC_SMPR1_SMP24_1 | ADC_SMPR1_SMP23_1 | ADC_SMPR1_SMP22_1 | \ ADC_SMPR1_SMP21_1 | ADC_SMPR1_SMP20_1) #define ADC_SAMPLETIME_ALLCHANNELS_SMPR0BIT1 \ (ADC_SMPR0_SMP31_1 | ADC_SMPR0_SMP30_1 ) #endif /* STM32L151xCA || STM32L151xD || STM32L152xCA || STM32L152xD || STM32L162xCA || STM32L162xD || STM32L151xE || STM32L152xE || STM32L162xE */ #define ADC_SAMPLETIME_ALLCHANNELS_SMPR3BIT0 \ (ADC_SMPR3_SMP9_0 | ADC_SMPR3_SMP8_0 | ADC_SMPR3_SMP7_0 | ADC_SMPR3_SMP6_0 | \ ADC_SMPR3_SMP5_0 | ADC_SMPR3_SMP4_0 | ADC_SMPR3_SMP3_0 | ADC_SMPR3_SMP2_0 | \ ADC_SMPR3_SMP1_0 | ADC_SMPR3_SMP0_0) #define ADC_SAMPLETIME_ALLCHANNELS_SMPR2BIT0 \ (ADC_SMPR2_SMP19_0 | ADC_SMPR2_SMP18_0 | ADC_SMPR2_SMP17_0 | ADC_SMPR2_SMP16_0 | \ ADC_SMPR2_SMP15_0 | ADC_SMPR2_SMP14_0 | ADC_SMPR2_SMP13_0 | ADC_SMPR2_SMP12_0 | \ ADC_SMPR2_SMP11_0 | ADC_SMPR2_SMP10_0) #if defined(STM32L100xB) || defined (STM32L151xB) || defined (STM32L152xB) || defined(STM32L100xBA) || defined (STM32L151xBA) || defined (STM32L152xBA) || defined(STM32L100xC) || defined (STM32L151xC) || defined (STM32L152xC) || defined (STM32L162xC) #define ADC_SAMPLETIME_ALLCHANNELS_SMPR1BIT0 \ (ADC_SMPR1_SMP26_0 | ADC_SMPR1_SMP25_0 | ADC_SMPR1_SMP24_0 | ADC_SMPR1_SMP23_0 | \ ADC_SMPR1_SMP22_0 | ADC_SMPR1_SMP21_0 | ADC_SMPR1_SMP20_0) #endif /* STM32L100xB || STM32L151xB || STM32L152xB || STM32L100xBA || STM32L151xBA || STM32L152xBA || STM32L100xC || STM32L151xC || STM32L152xC || STM32L162xC */ #if defined(STM32L151xCA) || defined (STM32L151xD) || defined (STM32L152xCA) || defined (STM32L152xD) || defined (STM32L162xCA) || defined (STM32L162xD) || defined(STM32L151xE) || defined (STM32L152xE) || defined (STM32L162xE) #define ADC_SAMPLETIME_ALLCHANNELS_SMPR1BIT0 \ (ADC_SMPR1_SMP29_0 | ADC_SMPR1_SMP28_0 | ADC_SMPR1_SMP27_0 | ADC_SMPR1_SMP26_0 | \ ADC_SMPR1_SMP25_0 | ADC_SMPR1_SMP24_0 | ADC_SMPR1_SMP23_0 | ADC_SMPR1_SMP22_0 | \ ADC_SMPR1_SMP21_0 | ADC_SMPR1_SMP20_0) #define ADC_SAMPLETIME_ALLCHANNELS_SMPR0BIT0 \ (ADC_SMPR0_SMP31_0 | ADC_SMPR0_SMP30_0 ) #endif /* STM32L151xCA || STM32L151xD || STM32L152xCA || STM32L152xD || STM32L162xCA || STM32L162xD || STM32L151xE || STM32L152xE || STM32L162xE */ /** * @} */ /** @defgroup ADC_regular_rank ADC regular rank * @{ */ #define ADC_REGULAR_RANK_1 ((uint32_t)0x00000001) #define ADC_REGULAR_RANK_2 ((uint32_t)0x00000002) #define ADC_REGULAR_RANK_3 ((uint32_t)0x00000003) #define ADC_REGULAR_RANK_4 ((uint32_t)0x00000004) #define ADC_REGULAR_RANK_5 ((uint32_t)0x00000005) #define ADC_REGULAR_RANK_6 ((uint32_t)0x00000006) #define ADC_REGULAR_RANK_7 ((uint32_t)0x00000007) #define ADC_REGULAR_RANK_8 ((uint32_t)0x00000008) #define ADC_REGULAR_RANK_9 ((uint32_t)0x00000009) #define ADC_REGULAR_RANK_10 ((uint32_t)0x0000000A) #define ADC_REGULAR_RANK_11 ((uint32_t)0x0000000B) #define ADC_REGULAR_RANK_12 ((uint32_t)0x0000000C) #define ADC_REGULAR_RANK_13 ((uint32_t)0x0000000D) #define ADC_REGULAR_RANK_14 ((uint32_t)0x0000000E) #define ADC_REGULAR_RANK_15 ((uint32_t)0x0000000F) #define ADC_REGULAR_RANK_16 ((uint32_t)0x00000010) #define ADC_REGULAR_RANK_17 ((uint32_t)0x00000011) #define ADC_REGULAR_RANK_18 ((uint32_t)0x00000012) #define ADC_REGULAR_RANK_19 ((uint32_t)0x00000013) #define ADC_REGULAR_RANK_20 ((uint32_t)0x00000014) #define ADC_REGULAR_RANK_21 ((uint32_t)0x00000015) #define ADC_REGULAR_RANK_22 ((uint32_t)0x00000016) #define ADC_REGULAR_RANK_23 ((uint32_t)0x00000017) #define ADC_REGULAR_RANK_24 ((uint32_t)0x00000018) #define ADC_REGULAR_RANK_25 ((uint32_t)0x00000019) #define ADC_REGULAR_RANK_26 ((uint32_t)0x0000001A) #define ADC_REGULAR_RANK_27 ((uint32_t)0x0000001B) #if defined(STM32L100xC) || defined (STM32L151xC) || defined (STM32L152xC) || defined (STM32L162xC) || defined(STM32L151xCA) || defined (STM32L151xD) || defined (STM32L152xCA) || defined (STM32L152xD) || defined (STM32L162xCA) || defined (STM32L162xD) || defined(STM32L151xE) || defined (STM32L152xE) || defined (STM32L162xE) #define ADC_REGULAR_RANK_28 ((uint32_t)0x0000001C) #define IS_ADC_REGULAR_RANK(CHANNEL) (((CHANNEL) == ADC_REGULAR_RANK_1 ) || \ ((CHANNEL) == ADC_REGULAR_RANK_2 ) || \ ((CHANNEL) == ADC_REGULAR_RANK_3 ) || \ ((CHANNEL) == ADC_REGULAR_RANK_4 ) || \ ((CHANNEL) == ADC_REGULAR_RANK_5 ) || \ ((CHANNEL) == ADC_REGULAR_RANK_6 ) || \ ((CHANNEL) == ADC_REGULAR_RANK_7 ) || \ ((CHANNEL) == ADC_REGULAR_RANK_8 ) || \ ((CHANNEL) == ADC_REGULAR_RANK_9 ) || \ ((CHANNEL) == ADC_REGULAR_RANK_10) || \ ((CHANNEL) == ADC_REGULAR_RANK_11) || \ ((CHANNEL) == ADC_REGULAR_RANK_12) || \ ((CHANNEL) == ADC_REGULAR_RANK_13) || \ ((CHANNEL) == ADC_REGULAR_RANK_14) || \ ((CHANNEL) == ADC_REGULAR_RANK_15) || \ ((CHANNEL) == ADC_REGULAR_RANK_16) || \ ((CHANNEL) == ADC_REGULAR_RANK_17) || \ ((CHANNEL) == ADC_REGULAR_RANK_18) || \ ((CHANNEL) == ADC_REGULAR_RANK_19) || \ ((CHANNEL) == ADC_REGULAR_RANK_20) || \ ((CHANNEL) == ADC_REGULAR_RANK_21) || \ ((CHANNEL) == ADC_REGULAR_RANK_22) || \ ((CHANNEL) == ADC_REGULAR_RANK_23) || \ ((CHANNEL) == ADC_REGULAR_RANK_24) || \ ((CHANNEL) == ADC_REGULAR_RANK_25) || \ ((CHANNEL) == ADC_REGULAR_RANK_26) || \ ((CHANNEL) == ADC_REGULAR_RANK_27) || \ ((CHANNEL) == ADC_REGULAR_RANK_28) ) #else #define IS_ADC_REGULAR_RANK(CHANNEL) (((CHANNEL) == ADC_REGULAR_RANK_1 ) || \ ((CHANNEL) == ADC_REGULAR_RANK_2 ) || \ ((CHANNEL) == ADC_REGULAR_RANK_3 ) || \ ((CHANNEL) == ADC_REGULAR_RANK_4 ) || \ ((CHANNEL) == ADC_REGULAR_RANK_5 ) || \ ((CHANNEL) == ADC_REGULAR_RANK_6 ) || \ ((CHANNEL) == ADC_REGULAR_RANK_7 ) || \ ((CHANNEL) == ADC_REGULAR_RANK_8 ) || \ ((CHANNEL) == ADC_REGULAR_RANK_9 ) || \ ((CHANNEL) == ADC_REGULAR_RANK_10) || \ ((CHANNEL) == ADC_REGULAR_RANK_11) || \ ((CHANNEL) == ADC_REGULAR_RANK_12) || \ ((CHANNEL) == ADC_REGULAR_RANK_13) || \ ((CHANNEL) == ADC_REGULAR_RANK_14) || \ ((CHANNEL) == ADC_REGULAR_RANK_15) || \ ((CHANNEL) == ADC_REGULAR_RANK_16) || \ ((CHANNEL) == ADC_REGULAR_RANK_17) || \ ((CHANNEL) == ADC_REGULAR_RANK_18) || \ ((CHANNEL) == ADC_REGULAR_RANK_19) || \ ((CHANNEL) == ADC_REGULAR_RANK_20) || \ ((CHANNEL) == ADC_REGULAR_RANK_21) || \ ((CHANNEL) == ADC_REGULAR_RANK_22) || \ ((CHANNEL) == ADC_REGULAR_RANK_23) || \ ((CHANNEL) == ADC_REGULAR_RANK_24) || \ ((CHANNEL) == ADC_REGULAR_RANK_25) || \ ((CHANNEL) == ADC_REGULAR_RANK_26) || \ ((CHANNEL) == ADC_REGULAR_RANK_27) ) #endif /* STM32L100xC || STM32L151xC || STM32L152xC || STM32L162xC || STM32L151xCA || STM32L151xD || STM32L152xCA || STM32L152xD || STM32L162xCA || STM32L162xD || STM32L151xE || STM32L152xE || STM32L162xE */ /** * @} */ /** @defgroup ADC_analog_watchdog_mode ADC analog watchdog mode * @{ */ #define ADC_ANALOGWATCHDOG_NONE ((uint32_t)0x00000000) #define ADC_ANALOGWATCHDOG_SINGLE_REG ((uint32_t)(ADC_CR1_AWDSGL | ADC_CR1_AWDEN)) #define ADC_ANALOGWATCHDOG_SINGLE_INJEC ((uint32_t)(ADC_CR1_AWDSGL | ADC_CR1_JAWDEN)) #define ADC_ANALOGWATCHDOG_SINGLE_REGINJEC ((uint32_t)(ADC_CR1_AWDSGL | ADC_CR1_AWDEN | ADC_CR1_JAWDEN)) #define ADC_ANALOGWATCHDOG_ALL_REG ((uint32_t) ADC_CR1_AWDEN) #define ADC_ANALOGWATCHDOG_ALL_INJEC ((uint32_t) ADC_CR1_JAWDEN) #define ADC_ANALOGWATCHDOG_ALL_REGINJEC ((uint32_t)(ADC_CR1_AWDEN | ADC_CR1_JAWDEN)) #define IS_ADC_ANALOG_WATCHDOG_MODE(WATCHDOG) (((WATCHDOG) == ADC_ANALOGWATCHDOG_NONE) || \ ((WATCHDOG) == ADC_ANALOGWATCHDOG_SINGLE_REG) || \ ((WATCHDOG) == ADC_ANALOGWATCHDOG_SINGLE_INJEC) || \ ((WATCHDOG) == ADC_ANALOGWATCHDOG_SINGLE_REGINJEC) || \ ((WATCHDOG) == ADC_ANALOGWATCHDOG_ALL_REG) || \ ((WATCHDOG) == ADC_ANALOGWATCHDOG_ALL_INJEC) || \ ((WATCHDOG) == ADC_ANALOGWATCHDOG_ALL_REGINJEC) ) /** * @} */ /** @defgroup ADC_conversion_group ADC conversion group * @{ */ #define REGULAR_GROUP ((uint32_t)(ADC_FLAG_EOC)) #define INJECTED_GROUP ((uint32_t)(ADC_FLAG_JEOC)) #define REGULAR_INJECTED_GROUP ((uint32_t)(ADC_FLAG_EOC | ADC_FLAG_JEOC)) #define IS_ADC_CONVERSION_GROUP(CONVERSION) (((CONVERSION) == REGULAR_GROUP) || \ ((CONVERSION) == INJECTED_GROUP) || \ ((CONVERSION) == REGULAR_INJECTED_GROUP) ) /** * @} */ /** @defgroup ADC_Event_type ADC Event type * @{ */ #define AWD_EVENT ((uint32_t)ADC_FLAG_AWD) /*!< ADC Analog watchdog event */ #define OVR_EVENT ((uint32_t)ADC_FLAG_OVR) /*!< ADC overrun event */ #define IS_ADC_EVENT_TYPE(EVENT) (((EVENT) == AWD_EVENT) || \ ((EVENT) == ADC_FLAG_OVR) ) /** * @} */ /** @defgroup ADC_interrupts_definition ADC interrupts definition * @{ */ #define ADC_IT_EOC ADC_CR1_EOCIE /*!< ADC End of Regular Conversion interrupt source */ #define ADC_IT_JEOC ADC_CR1_JEOCIE /*!< ADC End of Injected Conversion interrupt source */ #define ADC_IT_AWD ADC_CR1_AWDIE /*!< ADC Analog watchdog interrupt source */ #define ADC_IT_OVR ADC_CR1_OVRIE /*!< ADC overrun interrupt source */ /** * @} */ /** @defgroup ADC_flags_definition ADC flags definition * @{ */ #define ADC_FLAG_AWD ADC_SR_AWD /*!< ADC Analog watchdog flag */ #define ADC_FLAG_EOC ADC_SR_EOC /*!< ADC End of Regular conversion flag */ #define ADC_FLAG_JEOC ADC_SR_JEOC /*!< ADC End of Injected conversion flag */ #define ADC_FLAG_JSTRT ADC_SR_JSTRT /*!< ADC Injected group start flag */ #define ADC_FLAG_STRT ADC_SR_STRT /*!< ADC Regular group start flag */ #define ADC_FLAG_OVR ADC_SR_OVR /*!< ADC overrun flag */ #define ADC_FLAG_ADONS ADC_SR_ADONS /*!< ADC ready status flag */ #define ADC_FLAG_RCNR ADC_SR_RCNR /*!< ADC Regular group ready status flag */ #define ADC_FLAG_JCNR ADC_SR_JCNR /*!< ADC Regular group ready status flag */ /* Combination of all post-conversion flags bits: EOC/EOS, JEOC/JEOS, OVR, AWDx */ #define ADC_FLAG_POSTCONV_ALL (ADC_FLAG_EOC | ADC_FLAG_JEOC | ADC_FLAG_AWD | \ ADC_FLAG_OVR) /** * @} */ /** @defgroup ADC_range_verification ADC range verification * For a unique ADC resolution: 12 bits * @{ */ #define IS_ADC_RANGE(ADC_VALUE) ((ADC_VALUE) <= ((uint32_t)0x0FFF)) /** * @} */ /** @defgroup ADC_regular_nb_conv_verification ADC regular nb conv verification * @{ */ #if defined(STM32L100xC) || defined (STM32L151xC) || defined (STM32L152xC) || defined (STM32L162xC) || defined(STM32L151xCA) || defined (STM32L151xD) || defined (STM32L152xCA) || defined (STM32L152xD) || defined (STM32L162xCA) || defined (STM32L162xD) || defined(STM32L151xE) || defined (STM32L152xE) || defined (STM32L162xE) #define IS_ADC_REGULAR_NB_CONV(LENGTH) (((LENGTH) >= ((uint32_t)1)) && ((LENGTH) <= ((uint32_t)28))) #else #define IS_ADC_REGULAR_NB_CONV(LENGTH) (((LENGTH) >= ((uint32_t)1)) && ((LENGTH) <= ((uint32_t)27))) #endif /** * @} */ /** @defgroup ADC_regular_discontinuous_mode_number_verification ADC regular discontinuous mode number verification * @{ */ #define IS_ADC_REGULAR_DISCONT_NUMBER(NUMBER) (((NUMBER) >= ((uint32_t)1)) && ((NUMBER) <= ((uint32_t)8))) /** * @} */ /** * @} */ /* Exported macro ------------------------------------------------------------*/ /** @defgroup ADC_Exported_Macros ADC Exported Macros * @{ */ /* Macro for internal HAL driver usage, and possibly can be used into code of */ /* final user. */ /** * @brief Verification of ADC state: enabled or disabled * @param __HANDLE__: ADC handle * @retval SET (ADC enabled) or RESET (ADC disabled) */ #define __HAL_ADC_IS_ENABLED(__HANDLE__) \ ((( ((__HANDLE__)->Instance->SR & ADC_SR_ADONS) == ADC_SR_ADONS ) \ ) ? SET : RESET) /** * @brief Test if conversion trigger of regular group is software start * or external trigger. * @param __HANDLE__: ADC handle * @retval SET (software start) or RESET (external trigger) */ #define __HAL_ADC_IS_SOFTWARE_START_REGULAR(__HANDLE__) \ (((__HANDLE__)->Instance->CR2 & ADC_CR2_EXTEN) == RESET) /** * @brief Test if conversion trigger of injected group is software start * or external trigger. * @param __HANDLE__: ADC handle * @retval SET (software start) or RESET (external trigger) */ #define __HAL_ADC_IS_SOFTWARE_START_INJECTED(__HANDLE__) \ (((__HANDLE__)->Instance->CR2 & ADC_CR2_JEXTEN) == RESET) /** @brief Checks if the specified ADC interrupt source is enabled or disabled. * @param __HANDLE__: ADC handle * @param __INTERRUPT__: ADC interrupt source to check * @retval State of interruption (SET or RESET) */ #define __HAL_ADC_GET_IT_SOURCE(__HANDLE__, __INTERRUPT__) \ (( ((__HANDLE__)->Instance->CR1 & (__INTERRUPT__)) == (__INTERRUPT__) \ )? SET : RESET \ ) /** * @brief Enable the ADC end of conversion interrupt. * @param __HANDLE__: ADC handle * @param __INTERRUPT__: ADC Interrupt * @retval None */ #define __HAL_ADC_ENABLE_IT(__HANDLE__, __INTERRUPT__) \ (SET_BIT((__HANDLE__)->Instance->CR1, (__INTERRUPT__))) /** * @brief Disable the ADC end of conversion interrupt. * @param __HANDLE__: ADC handle * @param __INTERRUPT__: ADC Interrupt * @retval None */ #define __HAL_ADC_DISABLE_IT(__HANDLE__, __INTERRUPT__) \ (CLEAR_BIT((__HANDLE__)->Instance->CR1, (__INTERRUPT__))) /** * @brief Get the selected ADC's flag status. * @param __HANDLE__: ADC handle * @param __FLAG__: ADC flag * @retval None */ #define __HAL_ADC_GET_FLAG(__HANDLE__, __FLAG__) \ ((((__HANDLE__)->Instance->SR) & (__FLAG__)) == (__FLAG__)) /** * @brief Clear the ADC's pending flags * @param __HANDLE__: ADC handle * @param __FLAG__: ADC flag * @retval None */ #define __HAL_ADC_CLEAR_FLAG(__HANDLE__, __FLAG__) (((__HANDLE__)->Instance->SR) = ~(__FLAG__)) /** * @brief Clear ADC error code (set it to error code: "no error") * @param __HANDLE__: ADC handle * @retval None */ #define __HAL_ADC_CLEAR_ERRORCODE(__HANDLE__) \ ((__HANDLE__)->ErrorCode = HAL_ADC_ERROR_NONE) /** @brief Reset ADC handle state * @param __HANDLE__: ADC handle * @retval None */ #define __HAL_ADC_RESET_HANDLE_STATE(__HANDLE__) ((__HANDLE__)->State = HAL_ADC_STATE_RESET) /** * @} */ /* Include ADC HAL Extension module */ #include "stm32l1xx_hal_adc_ex.h" /* Exported functions --------------------------------------------------------*/ /** @addtogroup ADC_Exported_Functions * @{ */ /** @addtogroup ADC_Exported_Functions_Group1 * @{ */ /* Initialization and de-initialization functions **********************************/ HAL_StatusTypeDef HAL_ADC_Init(ADC_HandleTypeDef* hadc); HAL_StatusTypeDef HAL_ADC_DeInit(ADC_HandleTypeDef *hadc); void HAL_ADC_MspInit(ADC_HandleTypeDef* hadc); void HAL_ADC_MspDeInit(ADC_HandleTypeDef* hadc); /** * @} */ /* IO operation functions *****************************************************/ /** @addtogroup ADC_Exported_Functions_Group2 * @{ */ /* Blocking mode: Polling */ HAL_StatusTypeDef HAL_ADC_Start(ADC_HandleTypeDef* hadc); HAL_StatusTypeDef HAL_ADC_Stop(ADC_HandleTypeDef* hadc); HAL_StatusTypeDef HAL_ADC_PollForConversion(ADC_HandleTypeDef* hadc, uint32_t Timeout); HAL_StatusTypeDef HAL_ADC_PollForEvent(ADC_HandleTypeDef* hadc, uint32_t EventType, uint32_t Timeout); /* Non-blocking mode: Interruption */ HAL_StatusTypeDef HAL_ADC_Start_IT(ADC_HandleTypeDef* hadc); HAL_StatusTypeDef HAL_ADC_Stop_IT(ADC_HandleTypeDef* hadc); /* Non-blocking mode: DMA */ HAL_StatusTypeDef HAL_ADC_Start_DMA(ADC_HandleTypeDef* hadc, uint32_t* pData, uint32_t Length); HAL_StatusTypeDef HAL_ADC_Stop_DMA(ADC_HandleTypeDef* hadc); /* ADC retrieve conversion value intended to be used with polling or interruption */ uint32_t HAL_ADC_GetValue(ADC_HandleTypeDef* hadc); /* ADC IRQHandler and Callbacks used in non-blocking modes (Interruption and DMA) */ void HAL_ADC_IRQHandler(ADC_HandleTypeDef* hadc); void HAL_ADC_ConvCpltCallback(ADC_HandleTypeDef* hadc); void HAL_ADC_ConvHalfCpltCallback(ADC_HandleTypeDef* hadc); void HAL_ADC_LevelOutOfWindowCallback(ADC_HandleTypeDef* hadc); void HAL_ADC_ErrorCallback(ADC_HandleTypeDef *hadc); /** * @} */ /* Peripheral Control functions ***********************************************/ /** @addtogroup ADC_Exported_Functions_Group3 * @{ */ HAL_StatusTypeDef HAL_ADC_ConfigChannel(ADC_HandleTypeDef* hadc, ADC_ChannelConfTypeDef* sConfig); HAL_StatusTypeDef HAL_ADC_AnalogWDGConfig(ADC_HandleTypeDef* hadc, ADC_AnalogWDGConfTypeDef* AnalogWDGConfig); /** * @} */ /* Peripheral State functions *************************************************/ /** @addtogroup ADC_Exported_Functions_Group4 * @{ */ HAL_ADC_StateTypeDef HAL_ADC_GetState(ADC_HandleTypeDef* hadc); uint32_t HAL_ADC_GetError(ADC_HandleTypeDef *hadc); /** * @} */ /** * @} */ /* Internal HAL driver functions **********************************************/ /** @addtogroup ADC_Private_Functions * @{ */ HAL_StatusTypeDef ADC_Enable(ADC_HandleTypeDef* hadc); HAL_StatusTypeDef ADC_ConversionStop_Disable(ADC_HandleTypeDef* hadc); /** * @} */ /** * @} */ /** * @} */ #ifdef __cplusplus } #endif #endif /* __STM32L1xx_HAL_ADC_H */ /************************ (C) COPYRIGHT STMicroelectronics *****END OF FILE****/ ================================================ FILE: Zelig/mbed/TARGET_NUCLEO_L152RE/stm32l1xx_hal_adc_ex.h ================================================ /** ****************************************************************************** * @file stm32l1xx_hal_adc_ex.h * @author MCD Application Team * @version V1.0.0 * @date 5-September-2014 * @brief Header file of ADC HAL Extension module. ****************************************************************************** * @attention * *

© COPYRIGHT(c) 2014 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. * ****************************************************************************** */ /* Define to prevent recursive inclusion -------------------------------------*/ #ifndef __STM32L1xx_HAL_ADC_EX_H #define __STM32L1xx_HAL_ADC_EX_H #ifdef __cplusplus extern "C" { #endif /* Includes ------------------------------------------------------------------*/ #include "stm32l1xx_hal_def.h" /** @addtogroup STM32L1xx_HAL_Driver * @{ */ /** @addtogroup ADCEx * @{ */ /* Exported types ------------------------------------------------------------*/ /** @defgroup ADCEx_Exported_Types ADCEx Exported Types * @{ */ /** * @brief ADC Configuration injected Channel structure definition * @note Parameters of this structure are shared within 2 scopes: * - Scope channel: InjectedChannel, InjectedRank, InjectedSamplingTime, InjectedOffset * - Scope injected group (affects all channels of injected group): InjectedNbrOfConversion, InjectedDiscontinuousConvMode, * AutoInjectedConv, ExternalTrigInjecConvEdge, ExternalTrigInjecConv. * @note The setting of these parameters with function HAL_ADCEx_InjectedConfigChannel() is conditioned to ADC state. * ADC state can be either: * - For all parameters: ADC disabled * - For all except parameters 'InjectedDiscontinuousConvMode' and 'AutoInjectedConv': ADC enabled without conversion on going on injected group. * - For parameters 'ExternalTrigInjecConv' and 'ExternalTrigInjecConvEdge': ADC enabled, even with conversion on going on injected group. */ typedef struct { uint32_t InjectedChannel; /*!< Selection of ADC channel to configure This parameter can be a value of @ref ADC_channels Note: Depending on devices, some channels may not be available on package pins. Refer to device datasheet for channels availability. */ uint32_t InjectedRank; /*!< Rank in the injected group sequencer This parameter must be a value of @ref ADCEx_injected_rank Note: In case of need to disable a channel or change order of conversion sequencer, rank containing a previous channel setting can be overwritten by the new channel setting (or parameter number of conversions can be adjusted) */ uint32_t InjectedSamplingTime; /*!< Sampling time value to be set for the selected channel. Unit: ADC clock cycles Conversion time is the addition of sampling time and processing time (12 ADC clock cycles at ADC resolution 12 bits, 11 cycles at 10 bits, 9 cycles at 8 bits, 7 cycles at 6 bits). This parameter can be a value of @ref ADC_sampling_times Caution: This parameter updates the parameter property of the channel, that can be used into regular and/or injected groups. If this same channel has been previously configured in the other group (regular/injected), it will be updated to last setting. Note: In case of usage of internal measurement channels (VrefInt/Vbat/TempSensor), sampling time constraints must be respected (sampling time can be adjusted in function of ADC clock frequency and sampling time setting) Refer to device datasheet for timings values, parameters TS_vrefint, TS_temp (values rough order: 4us min). */ uint32_t InjectedOffset; /*!< Defines the offset to be subtracted from the raw converted data (for channels set on injected group only). Offset value must be a positive number. Depending of ADC resolution selected (12, 10, 8 or 6 bits), this parameter must be a number between Min_Data = 0x000 and Max_Data = 0xFFF, 0x3FF, 0xFF or 0x3F respectively. */ uint32_t InjectedNbrOfConversion; /*!< Specifies the number of ranks that will be converted within the injected group sequencer. To use the injected group sequencer and convert several ranks, parameter 'ScanConvMode' must be enabled. This parameter must be a number between Min_Data = 1 and Max_Data = 4. Caution: this setting impacts the entire injected group. Therefore, call of HAL_ADCEx_InjectedConfigChannel() to configure a channel on injected group can impact the configuration of other channels previously set. */ uint32_t InjectedDiscontinuousConvMode; /*!< Specifies whether the conversions sequence of injected group is performed in Complete-sequence/Discontinuous-sequence (main sequence subdivided in successive parts). Discontinuous mode is used only if sequencer is enabled (parameter 'ScanConvMode'). If sequencer is disabled, this parameter is discarded. Discontinuous mode can be enabled only if continuous mode is disabled. If continuous mode is enabled, this parameter setting is discarded. This parameter can be set to ENABLE or DISABLE. Note: For injected group, number of discontinuous ranks increment is fixed to one-by-one. Caution: this setting impacts the entire injected group. Therefore, call of HAL_ADCEx_InjectedConfigChannel() to configure a channel on injected group can impact the configuration of other channels previously set. */ uint32_t AutoInjectedConv; /*!< Enables or disables the selected ADC automatic injected group conversion after regular one This parameter can be set to ENABLE or DISABLE. Note: To use Automatic injected conversion, discontinuous mode must be disabled ('DiscontinuousConvMode' and 'InjectedDiscontinuousConvMode' set to DISABLE) Note: To use Automatic injected conversion, injected group external triggers must be disabled ('ExternalTrigInjecConv' set to ADC_SOFTWARE_START) Note: In case of DMA used with regular group: if DMA configured in normal mode (single shot) JAUTO will be stopped upon DMA transfer complete. To maintain JAUTO always enabled, DMA must be configured in circular mode. Caution: this setting impacts the entire injected group. Therefore, call of HAL_ADCEx_InjectedConfigChannel() to configure a channel on injected group can impact the configuration of other channels previously set. */ uint32_t ExternalTrigInjecConv; /*!< Selects the external event used to trigger the conversion start of injected group. If set to ADC_INJECTED_SOFTWARE_START, external triggers are disabled. If set to external trigger source, triggering is on event rising edge. This parameter can be a value of @ref ADCEx_External_trigger_source_Injected Note: This parameter must be modified when ADC is disabled (before ADC start conversion or after ADC stop conversion). If ADC is enabled, this parameter setting is bypassed without error reporting (as it can be the expected behaviour in case of another parameter update on the fly) Caution: this setting impacts the entire injected group. Therefore, call of HAL_ADCEx_InjectedConfigChannel() to configure a channel on injected group can impact the configuration of other channels previously set. */ uint32_t ExternalTrigInjecConvEdge; /*!< Selects the external trigger edge of injected group. This parameter can be a value of @ref ADCEx_External_trigger_edge_Injected. If trigger is set to ADC_INJECTED_SOFTWARE_START, this parameter is discarded. Caution: this setting impacts the entire injected group. Therefore, call of HAL_ADCEx_InjectedConfigChannel() to configure a channel on injected group can impact the configuration of other channels previously set. */ }ADC_InjectionConfTypeDef; /** * @} */ /* Exported constants --------------------------------------------------------*/ /** @defgroup ADCEx_Exported_Constants ADCEx Exported Constants * @{ */ /** @defgroup ADCEx_injected_rank ADCEx injected rank * @{ */ #define ADC_INJECTED_RANK_1 ((uint32_t)0x00000001) #define ADC_INJECTED_RANK_2 ((uint32_t)0x00000002) #define ADC_INJECTED_RANK_3 ((uint32_t)0x00000003) #define ADC_INJECTED_RANK_4 ((uint32_t)0x00000004) #define IS_ADC_INJECTED_RANK(CHANNEL) (((CHANNEL) == ADC_INJECTED_RANK_1) || \ ((CHANNEL) == ADC_INJECTED_RANK_2) || \ ((CHANNEL) == ADC_INJECTED_RANK_3) || \ ((CHANNEL) == ADC_INJECTED_RANK_4) ) /** * @} */ /** @defgroup ADCEx_External_trigger_edge_Injected ADCEx External trigger edge Injected * @{ */ #define ADC_EXTERNALTRIGINJECCONV_EDGE_NONE ((uint32_t)0x00000000) #define ADC_EXTERNALTRIGINJECCONV_EDGE_RISING ((uint32_t)ADC_CR2_JEXTEN_0) #define ADC_EXTERNALTRIGINJECCONV_EDGE_FALLING ((uint32_t)ADC_CR2_JEXTEN_1) #define ADC_EXTERNALTRIGINJECCONV_EDGE_RISINGFALLING ((uint32_t)ADC_CR2_JEXTEN) #define IS_ADC_EXTTRIGINJEC_EDGE(EDGE) (((EDGE) == ADC_EXTERNALTRIGINJECCONV_EDGE_NONE) || \ ((EDGE) == ADC_EXTERNALTRIGINJECCONV_EDGE_RISING) || \ ((EDGE) == ADC_EXTERNALTRIGINJECCONV_EDGE_FALLING) || \ ((EDGE) == ADC_EXTERNALTRIGINJECCONV_EDGE_RISINGFALLING) ) /** * @} */ /** @defgroup ADCEx_External_trigger_source_Injected ADCEx External trigger source Injected * @{ */ /* External triggers for injected groups of ADC1 */ #define ADC_EXTERNALTRIGINJECCONV_T2_CC1 ADC_EXTERNALTRIGINJEC_T2_CC1 #define ADC_EXTERNALTRIGINJECCONV_T2_TRGO ADC_EXTERNALTRIGINJEC_T2_TRGO #define ADC_EXTERNALTRIGINJECCONV_T3_CC4 ADC_EXTERNALTRIGINJEC_T3_CC4 #define ADC_EXTERNALTRIGINJECCONV_T4_TRGO ADC_EXTERNALTRIGINJEC_T4_TRGO #define ADC_EXTERNALTRIGINJECCONV_T4_CC1 ADC_EXTERNALTRIGINJEC_T4_CC1 #define ADC_EXTERNALTRIGINJECCONV_T4_CC2 ADC_EXTERNALTRIGINJEC_T4_CC2 #define ADC_EXTERNALTRIGINJECCONV_T4_CC3 ADC_EXTERNALTRIGINJEC_T4_CC3 #define ADC_EXTERNALTRIGINJECCONV_T7_TRGO ADC_EXTERNALTRIGINJEC_T7_TRGO #define ADC_EXTERNALTRIGINJECCONV_T9_CC1 ADC_EXTERNALTRIGINJEC_T9_CC1 #define ADC_EXTERNALTRIGINJECCONV_T9_TRGO ADC_EXTERNALTRIGINJEC_T9_TRGO #define ADC_EXTERNALTRIGINJECCONV_T10_CC1 ADC_EXTERNALTRIGINJEC_T10_CC1 #define ADC_EXTERNALTRIGINJECCONV_EXT_IT15 ADC_EXTERNALTRIGINJEC_EXT_IT15 #define ADC_INJECTED_SOFTWARE_START ((uint32_t)0x00000010) #define IS_ADC_EXTTRIGINJEC(REGTRIG) (((REGTRIG) == ADC_EXTERNALTRIGINJECCONV_T2_CC1) || \ ((REGTRIG) == ADC_EXTERNALTRIGINJECCONV_T2_TRGO) || \ ((REGTRIG) == ADC_EXTERNALTRIGINJECCONV_T3_CC4) || \ ((REGTRIG) == ADC_EXTERNALTRIGINJECCONV_T4_TRGO) || \ ((REGTRIG) == ADC_EXTERNALTRIGINJECCONV_T4_CC1) || \ ((REGTRIG) == ADC_EXTERNALTRIGINJECCONV_T4_CC2) || \ ((REGTRIG) == ADC_EXTERNALTRIGINJECCONV_T4_CC3) || \ ((REGTRIG) == ADC_EXTERNALTRIGINJECCONV_T7_TRGO) || \ ((REGTRIG) == ADC_EXTERNALTRIGINJECCONV_T9_CC1) || \ ((REGTRIG) == ADC_EXTERNALTRIGINJECCONV_T9_TRGO) || \ ((REGTRIG) == ADC_EXTERNALTRIGINJECCONV_T10_CC1) || \ ((REGTRIG) == ADC_EXTERNALTRIGINJECCONV_EXT_IT15) || \ ((REGTRIG) == ADC_SOFTWARE_START) ) /** * @} */ /** @defgroup ADCEx_Internal_HAL_driver_Ext_trig_src_Injected ADCEx Internal HAL driver Ext trig src Injected * @{ */ /* List of external triggers of injected group for ADC1: */ /* (used internally by HAL driver. To not use into HAL structure parameters) */ #define ADC_EXTERNALTRIGINJEC_T9_CC1 ((uint32_t) 0x00000000) #define ADC_EXTERNALTRIGINJEC_T9_TRGO ((uint32_t)( ADC_CR2_JEXTSEL_0)) #define ADC_EXTERNALTRIGINJEC_T2_TRGO ((uint32_t)( ADC_CR2_JEXTSEL_1 )) #define ADC_EXTERNALTRIGINJEC_T2_CC1 ((uint32_t)( ADC_CR2_JEXTSEL_1 | ADC_CR2_JEXTSEL_0)) #define ADC_EXTERNALTRIGINJEC_T3_CC4 ((uint32_t)( ADC_CR2_JEXTSEL_2 )) #define ADC_EXTERNALTRIGINJEC_T4_TRGO ((uint32_t)( ADC_CR2_JEXTSEL_2 | ADC_CR2_JEXTSEL_0)) #define ADC_EXTERNALTRIGINJEC_T4_CC1 ((uint32_t)( ADC_CR2_JEXTSEL_2 | ADC_CR2_JEXTSEL_1 )) #define ADC_EXTERNALTRIGINJEC_T4_CC2 ((uint32_t)( ADC_CR2_JEXTSEL_2 | ADC_CR2_JEXTSEL_1 | ADC_CR2_JEXTSEL_0)) #define ADC_EXTERNALTRIGINJEC_T4_CC3 ((uint32_t)(ADC_CR2_JEXTSEL_3 )) #define ADC_EXTERNALTRIGINJEC_T10_CC1 ((uint32_t)(ADC_CR2_JEXTSEL_3 | ADC_CR2_JEXTSEL_0)) #define ADC_EXTERNALTRIGINJEC_T7_TRGO ((uint32_t)(ADC_CR2_JEXTSEL_3 | ADC_CR2_JEXTSEL_1 )) #define ADC_EXTERNALTRIGINJEC_EXT_IT15 ((uint32_t)(ADC_CR2_JEXTSEL_3 | ADC_CR2_JEXTSEL_2 | ADC_CR2_JEXTSEL_1 | ADC_CR2_JEXTSEL_0)) /** * @} */ /** @defgroup ADCEx_injected_nb_conv_verification ADCEx injected nb conv verification * @{ */ #define IS_ADC_INJECTED_NB_CONV(LENGTH) (((LENGTH) >= ((uint32_t)1)) && ((LENGTH) <= ((uint32_t)4))) /** * @} */ /** * @} */ /* Exported macro ------------------------------------------------------------*/ /** @defgroup ADCEx_Exported_Macros ADCEx Exported Macros * @{ */ /* Macro for internal HAL driver usage, and possibly can be used into code of */ /* final user. */ /** * @brief Selection of channels bank. * Note: Banks availability depends on devices categories. * This macro is intended to change bank selection quickly on the fly, * without going through ADC init structure update and execution of function * 'HAL_ADC_Init()'. * @param __HANDLE__: ADC handle * @param __BANK__: Bank selection. This parameter can be a value of @ref ADC_ChannelsBank. * @retval None */ #define __HAL_ADC_CHANNELS_BANK(__HANDLE__, __BANK__) \ MODIFY_REG((__HANDLE__)->Instance->CR2, ADC_CR2_CFG, (__BANK__)) #if defined(STM32L100xC) || defined (STM32L151xC) || defined (STM32L152xC) || defined (STM32L162xC) || defined(STM32L151xCA) || defined (STM32L151xD) || defined (STM32L152xCA) || defined (STM32L152xD) || defined (STM32L162xCA) || defined (STM32L162xD) || defined(STM32L151xE) || defined (STM32L152xE) || defined (STM32L162xE) /** * @brief Configures the ADC channels speed. * Limited to channels 3, 8, 13 and to devices category Cat.3, Cat.4, Cat.5. * - For ADC_CHANNEL_3: Used as ADC direct channel (fast channel) if OPAMP1 is * in power down mode. * - For ADC_CHANNEL_8: Used as ADC direct channel (fast channel) if OPAMP2 is * in power down mode. * - For ADC_CHANNEL_13: Used as ADC re-routed channel if OPAMP3 is in * power down mode. Otherwise, channel 13 is connected to OPAMP3 output and * routed through switches COMP1_SW1 and VCOMP to ADC switch matrix. * (Note: OPAMP3 is available on STM32L1 Cat.4 only). * @param __CHANNEL__: ADC channel * This parameter can be one of the following values: * @arg ADC_CHANNEL_3: Channel 3 is selected. * @arg ADC_CHANNEL_8: Channel 8 is selected. * @arg ADC_CHANNEL_13: Channel 13 is selected. * @retval None */ #define __HAL_ADC_CHANNEL_SPEED_FAST(__CHANNEL__) \ ( ( ((__CHANNEL__) == ADC_CHANNEL_3) \ )? \ (SET_BIT(COMP->CSR, COMP_CSR_FCH3)) \ : \ ( ( ((__CHANNEL__) == ADC_CHANNEL_8) \ )? \ (SET_BIT(COMP->CSR, COMP_CSR_FCH8)) \ : \ ( ( ((__CHANNEL__) == ADC_CHANNEL_13) \ )? \ (SET_BIT(COMP->CSR, COMP_CSR_RCH13)) \ : \ (SET_BIT(COMP->CSR, 0x00000000)) \ ) \ ) \ ) #define __HAL_ADC_CHANNEL_SPEED_SLOW(__CHANNEL__) \ ( ( ((__CHANNEL__) == ADC_CHANNEL_3) \ )? \ (CLEAR_BIT(COMP->CSR, COMP_CSR_FCH3)) \ : \ ( ( ((__CHANNEL__) == ADC_CHANNEL_8) \ )? \ (CLEAR_BIT(COMP->CSR, COMP_CSR_FCH8)) \ : \ ( ( ((__CHANNEL__) == ADC_CHANNEL_13) \ )? \ (CLEAR_BIT(COMP->CSR, COMP_CSR_RCH13)) \ : \ (SET_BIT(COMP->CSR, 0x00000000)) \ ) \ ) \ ) #endif /* STM32L100xC || STM32L151xC || STM32L152xC || STM32L162xC || STM32L151xCA || STM32L151xD || STM32L152xCA || STM32L152xD || STM32L162xCA || STM32L162xD || STM32L151xE || STM32L152xE || STM32L162xE */ /** * @} */ /* Private macro ------------------------------------------------------------*/ /** @defgroup ADCEx_Private_Macro ADCEx Private Macro * @{ */ /* Macro reserved for internal HAL driver usage, not intended to be used in */ /* code of final user. */ /** * @brief Set ADC number of ranks into regular channel sequence length. * @param _NbrOfConversion_: Regular channel sequence length * @retval None */ #define __ADC_SQR1_L(_NbrOfConversion_) (((_NbrOfConversion_) - (uint8_t)1) << POSITION_VAL(ADC_SQR1_L)) /** * @brief Set ADC ranks available in register SQR1. * Register SQR1 bits availability depends on device category. * @param _NbrOfConversion_: Regular channel sequence length * @retval None */ #if defined(STM32L100xC) || defined (STM32L151xC) || defined (STM32L152xC) || defined (STM32L162xC) || defined(STM32L151xCA) || defined (STM32L151xD) || defined (STM32L152xCA) || defined (STM32L152xD) || defined (STM32L162xCA) || defined (STM32L162xD) || defined(STM32L151xE) || defined (STM32L152xE) || defined (STM32L162xE) #define __ADC_SQR1_SQXX ADC_SQR1_SQ28 | ADC_SQR1_SQ27 | ADC_SQR1_SQ26 | ADC_SQR1_SQ25 #else #define __ADC_SQR1_SQXX ADC_SQR1_SQ27 | ADC_SQR1_SQ26 | ADC_SQR1_SQ25 #endif /* STM32L100xC || STM32L151xC || STM32L152xC || STM32L162xC || STM32L151xCA || STM32L151xD || STM32L152xCA || STM32L152xD || STM32L162xCA || STM32L162xD || STM32L151xE || STM32L152xE || STM32L162xE */ /** * @brief Set the ADC's sample time for channel numbers between 30 and 31. * Register SMPR0 availability depends on device category. If register is not * available on the current device, this macro does nothing. * @retval None * @param _SAMPLETIME_: Sample time parameter. * @param _CHANNELNB_: Channel number. * @retval None */ #if defined(STM32L151xCA) || defined (STM32L151xD) || defined (STM32L152xCA) || defined (STM32L152xD) || defined (STM32L162xCA) || defined (STM32L162xD) || defined(STM32L151xE) || defined (STM32L152xE) || defined (STM32L162xE) #define __ADC_SMPR0(_SAMPLETIME_, _CHANNELNB_) ((_SAMPLETIME_) << (3 * ((_CHANNELNB_) - 30))) #else #define __ADC_SMPR0(_SAMPLETIME_, _CHANNELNB_) ((uint32_t)0x00000000) #endif /* STM32L151xCA || STM32L151xD || STM32L152xCA || STM32L152xD || STM32L162xCA || STM32L162xD || STM32L151xE || STM32L152xE || STM32L162xE */ #if defined(STM32L151xCA) || defined (STM32L151xD) || defined (STM32L152xCA) || defined (STM32L152xD) || defined (STM32L162xCA) || defined (STM32L162xD) || defined(STM32L151xE) || defined (STM32L152xE) || defined (STM32L162xE) /** * @brief Set the ADC's sample time for channel numbers between 20 and 29. * @param _SAMPLETIME_: Sample time parameter. * @param _CHANNELNB_: Channel number. * @retval None */ #define __ADC_SMPR1(_SAMPLETIME_, _CHANNELNB_) ((_SAMPLETIME_) << (3 * ((_CHANNELNB_) - 20))) #else /** * @brief Set the ADC's sample time for channel numbers between 20 and 26. * @param _SAMPLETIME_: Sample time parameter. * @param _CHANNELNB_: Channel number. * @retval None */ #define __ADC_SMPR1(_SAMPLETIME_, _CHANNELNB_) ((_SAMPLETIME_) << (3 * ((_CHANNELNB_) - 20))) #endif /* STM32L151xCA || STM32L151xD || STM32L152xCA || STM32L152xD || STM32L162xCA || STM32L162xD || STM32L151xE || STM32L152xE || STM32L162xE */ /** * @brief Defines the highest channel available in register SMPR1. Channels * availability depends on device category: * Highest channel in register SMPR1 is channel 26 for devices Cat.1, Cat.2, Cat.3 * Highest channel in register SMPR1 is channel 29 for devices Cat.4, Cat.5 * @param None * @retval None */ #if defined(STM32L151xCA) || defined (STM32L151xD) || defined (STM32L152xCA) || defined (STM32L152xD) || defined (STM32L162xCA) || defined (STM32L162xD) || defined(STM32L151xE) || defined (STM32L152xE) || defined (STM32L162xE) #define ADC_SMPR1_CHANNEL_MAX ADC_CHANNEL_29 #else #define ADC_SMPR1_CHANNEL_MAX ADC_CHANNEL_26 #endif /* STM32L151xCA || STM32L151xD || STM32L152xCA || STM32L152xD || STM32L162xCA || STM32L162xD || STM32L151xE || STM32L152xE || STM32L162xE */ /** * @brief Set the ADC's sample time for channel numbers between 10 and 18. * @param _SAMPLETIME_: Sample time parameter. * @param _CHANNELNB_: Channel number. * @retval None */ #define __ADC_SMPR2(_SAMPLETIME_, _CHANNELNB_) ((_SAMPLETIME_) << (3 * ((_CHANNELNB_) - 10))) /** * @brief Set the ADC's sample time for channel numbers between 0 and 9. * @param _SAMPLETIME_: Sample time parameter. * @param _CHANNELNB_: Channel number. * @retval None */ #define __ADC_SMPR3(_SAMPLETIME_, _CHANNELNB_) ((_SAMPLETIME_) << (3 * (_CHANNELNB_))) /** * @brief Set the selected regular channel rank for rank between 1 and 6. * @param _CHANNELNB_: Channel number. * @param _RANKNB_: Rank number. * @retval None */ #define __ADC_SQR5_RK(_CHANNELNB_, _RANKNB_) ((_CHANNELNB_) << (5 * ((_RANKNB_) - 1))) /** * @brief Set the selected regular channel rank for rank between 7 and 12. * @param _CHANNELNB_: Channel number. * @param _RANKNB_: Rank number. * @retval None */ #define __ADC_SQR4_RK(_CHANNELNB_, _RANKNB_) ((_CHANNELNB_) << (5 * ((_RANKNB_) - 7))) /** * @brief Set the selected regular channel rank for rank between 13 and 18. * @param _CHANNELNB_: Channel number. * @param _RANKNB_: Rank number. * @retval None */ #define __ADC_SQR3_RK(_CHANNELNB_, _RANKNB_) ((_CHANNELNB_) << (5 * ((_RANKNB_) - 13))) /** * @brief Set the selected regular channel rank for rank between 19 and 24. * @param _CHANNELNB_: Channel number. * @param _RANKNB_: Rank number. * @retval None */ #define __ADC_SQR2_RK(_CHANNELNB_, _RANKNB_) ((_CHANNELNB_) << (5 * ((_RANKNB_) - 19))) /** * @brief Set the selected regular channel rank for rank between 25 and 28. * @param _CHANNELNB_: Channel number. * @param _RANKNB_: Rank number. * @retval None */ #define __ADC_SQR1_RK(_CHANNELNB_, _RANKNB_) ((_CHANNELNB_) << (5 * ((_RANKNB_) - 25))) /** * @brief Set the injected sequence length. * @param _JSQR_JL_: Sequence length. * @retval None */ #define __ADC_JSQR_JL(_JSQR_JL_) (((_JSQR_JL_) -1) << 20) /** * @brief Set the selected injected Channel rank (channels sequence starting from 4-JL) * @param _CHANNELNB_: Channel number. * @param _RANKNB_: Rank number. * @param _JSQR_JL_: Sequence length. * @retval None */ #define __ADC_JSQR_RK(_CHANNELNB_, _RANKNB_, _JSQR_JL_) \ ((_CHANNELNB_) << (5 * ((4 - ((_JSQR_JL_) - (_RANKNB_))) - 1))) /** * @brief Enable the ADC DMA continuous request. * @param _DMACONTREQ_MODE_: DMA continuous request mode. * @retval None */ #define __ADC_CR2_DMACONTREQ(_DMACONTREQ_MODE_) ((_DMACONTREQ_MODE_) << POSITION_VAL(ADC_CR2_DDS)) /** * @brief Enable ADC continuous conversion mode. * @param _CONTINUOUS_MODE_: Continuous mode. * @retval None */ #define __ADC_CR2_CONTINUOUS(_CONTINUOUS_MODE_) ((_CONTINUOUS_MODE_) << POSITION_VAL(ADC_CR2_CONT)) /** * @brief Define mask of configuration bits of ADC and regular group in * register CR2 (bits of ADC enable, conversion start and injected group are * excluded of this mask). * @retval None */ #if defined (STM32L100xC) || defined (STM32L151xC) || defined (STM32L152xC) || defined (STM32L162xC) || defined (STM32L151xCA) || defined (STM32L151xD) || defined (STM32L152xCA) || defined (STM32L152xD) || defined (STM32L162xCA) || defined (STM32L162xD) || defined (STM32L151xE) || defined (STM32L152xE) || defined (STM32L162xE) #define __ADC_CR2_MASK_ADCINIT() \ (ADC_CR2_EXTEN | ADC_CR2_EXTSEL | ADC_CR2_ALIGN | ADC_CR2_EOCS | ADC_CR2_DDS | ADC_CR2_DELS | ADC_CR2_CFG | ADC_CR2_CONT) #else #define __ADC_CR2_MASK_ADCINIT() \ (ADC_CR2_EXTEN | ADC_CR2_EXTSEL | ADC_CR2_ALIGN | ADC_CR2_EOCS | ADC_CR2_DDS | ADC_CR2_DELS | ADC_CR2_CONT) #endif /** * @brief Configures the number of discontinuous conversions for the regular group channels. * @param _NBR_DISCONTINUOUS_CONV_: Number of discontinuous conversions. * @retval None */ #define __ADC_CR1_DISCONTINUOUS_NUM(_NBR_DISCONTINUOUS_CONV_) (((_NBR_DISCONTINUOUS_CONV_) - 1) << POSITION_VAL(ADC_CR1_DISCNUM)) /** * @brief Enable ADC scan mode to convert multiple ranks with sequencer. * @param _SCAN_MODE_: Scan conversion mode. * @retval None */ #define __ADC_CR1_SCAN(_SCAN_MODE_) \ ( ( (_SCAN_MODE_) == (ADC_SCAN_ENABLE) \ )? (ADC_CR1_SCAN) : (0x00000000) \ ) /** * @brief Get the maximum ADC conversion cycles on all channels. * Returns the selected sampling time + conversion time (12.5 ADC clock cycles) * Approximation of sampling time within 2 ranges, returns the higher value: * below 24 cycles {4 cycles; 9 cycles; 16 cycles; 24 cycles} * between 48 cycles and 384 cycles {48 cycles; 96 cycles; 192 cycles; 384 cycles} * Unit: ADC clock cycles * @param __HANDLE__: ADC handle * @retval ADC conversion cycles on all channels */ #if defined(STM32L151xCA) || defined (STM32L151xD) || defined (STM32L152xCA) || defined (STM32L152xD) || defined (STM32L162xCA) || defined (STM32L162xD) || defined(STM32L151xE) || defined (STM32L152xE) || defined (STM32L162xE) #define __ADC_CONVCYCLES_MAX_RANGE(__HANDLE__) \ (( (((__HANDLE__)->Instance->SMPR3 & ADC_SAMPLETIME_ALLCHANNELS_SMPR3BIT2) == RESET) && \ (((__HANDLE__)->Instance->SMPR2 & ADC_SAMPLETIME_ALLCHANNELS_SMPR2BIT2) == RESET) && \ (((__HANDLE__)->Instance->SMPR1 & ADC_SAMPLETIME_ALLCHANNELS_SMPR1BIT2) == RESET) && \ (((__HANDLE__)->Instance->SMPR0 & ADC_SAMPLETIME_ALLCHANNELS_SMPR0BIT2) == RESET) ) ? \ \ ADC_CONVERSIONCLOCKCYCLES_SAMPLETIME_24CYCLES : ADC_CONVERSIONCLOCKCYCLES_SAMPLETIME_384CYCLES \ ) #else #define __ADC_CONVCYCLES_MAX_RANGE(__HANDLE__) \ (( (((__HANDLE__)->Instance->SMPR3 & ADC_SAMPLETIME_ALLCHANNELS_SMPR3BIT2) == RESET) && \ (((__HANDLE__)->Instance->SMPR2 & ADC_SAMPLETIME_ALLCHANNELS_SMPR2BIT2) == RESET) && \ (((__HANDLE__)->Instance->SMPR1 & ADC_SAMPLETIME_ALLCHANNELS_SMPR1BIT2) == RESET) ) ? \ \ ADC_CONVERSIONCLOCKCYCLES_SAMPLETIME_24CYCLES : ADC_CONVERSIONCLOCKCYCLES_SAMPLETIME_384CYCLES \ ) #endif /* STM32L151xCA || STM32L151xD || STM32L152xCA || STM32L152xD || STM32L162xCA || STM32L162xD || STM32L151xE || STM32L152xE || STM32L162xE */ /** * @brief Get the ADC clock prescaler from ADC common control register * and convert it to its decimal number setting (refer to reference manual) * @retval None */ #define __ADC_GET_CLOCK_PRESCALER_DECIMAL(__HANDLE__) \ ((0x01) << ((ADC->CCR & ADC_CCR_ADCPRE) >> POSITION_VAL(ADC_CCR_ADCPRE))) /** * @brief Clear register SMPR0. * Register SMPR0 availability depends on device category. If register is not * available on the current device, this macro performs no action. * @param __HANDLE__: ADC handle * @retval None */ #if defined(STM32L151xCA) || defined (STM32L151xD) || defined (STM32L152xCA) || defined (STM32L152xD) || defined (STM32L162xCA) || defined (STM32L162xD) || defined(STM32L151xE) || defined (STM32L152xE) || defined (STM32L162xE) #define __ADC_SMPR0_CLEAR(__HANDLE__) \ (CLEAR_BIT((__HANDLE__)->Instance->SMPR0, (ADC_SMPR0_SMP31 | ADC_SMPR0_SMP30))) #else #define __ADC_SMPR0_CLEAR(__HANDLE__) __NOP() #endif /* STM32L151xCA || STM32L151xD || STM32L152xCA || STM32L152xD || STM32L162xCA || STM32L162xD || STM32L151xE || STM32L152xE || STM32L162xE */ /** * @brief Clear register CR2. * @param __HANDLE__: ADC handle * @retval None */ #if defined(STM32L151xCA) || defined (STM32L151xD) || defined (STM32L152xCA) || defined (STM32L152xD) || defined (STM32L162xCA) || defined (STM32L162xD) || defined(STM32L151xE) || defined (STM32L152xE) || defined (STM32L162xE) #define __ADC_CR2_CLEAR(__HANDLE__) \ (CLEAR_BIT((__HANDLE__)->Instance->CR2, (ADC_CR2_SWSTART | ADC_CR2_EXTEN | ADC_CR2_EXTSEL | \ ADC_CR2_JSWSTART | ADC_CR2_JEXTEN | ADC_CR2_JEXTSEL | \ ADC_CR2_ALIGN | ADC_CR2_EOCS | ADC_CR2_DDS | \ ADC_CR2_DMA | ADC_CR2_DELS | ADC_CR2_CFG | \ ADC_CR2_CONT | ADC_CR2_ADON )) \ ) #else #define __ADC_CR2_CLEAR(__HANDLE__) \ (CLEAR_BIT((__HANDLE__)->Instance->CR2, (ADC_CR2_SWSTART | ADC_CR2_EXTEN | ADC_CR2_EXTSEL | \ ADC_CR2_JSWSTART | ADC_CR2_JEXTEN | ADC_CR2_JEXTSEL | \ ADC_CR2_ALIGN | ADC_CR2_EOCS | ADC_CR2_DDS | \ ADC_CR2_DMA | ADC_CR2_DELS | \ ADC_CR2_CONT | ADC_CR2_ADON )) \ ) #endif /* STM32L151xCA || STM32L151xD || STM32L152xCA || STM32L152xD || STM32L162xCA || STM32L162xD || STM32L151xE || STM32L152xE || STM32L162xE */ /** * @brief Set the sampling time of selected channel on register SMPR0 * Register SMPR0 availability depends on device category. If register is not * available on the current device, this macro performs no action. * @param __HANDLE__: ADC handle * @param _SAMPLETIME_: Sample time parameter. * @param __CHANNEL__: Channel number. * @retval None */ #if defined(STM32L151xCA) || defined (STM32L151xD) || defined (STM32L152xCA) || defined (STM32L152xD) || defined (STM32L162xCA) || defined (STM32L162xD) || defined(STM32L151xE) || defined (STM32L152xE) || defined (STM32L162xE) #define __ADC_SMPR0_CHANNEL_SET(__HANDLE__, _SAMPLETIME_, __CHANNEL__) \ MODIFY_REG((__HANDLE__)->Instance->SMPR0, \ __ADC_SMPR0(ADC_SMPR0_SMP30, (__CHANNEL__)), \ __ADC_SMPR0((_SAMPLETIME_), (__CHANNEL__)) ) #else #define __ADC_SMPR0_CHANNEL_SET(__HANDLE__, _SAMPLETIME_, __CHANNEL__) __NOP() #endif /* STM32L151xCA || STM32L151xD || STM32L152xCA || STM32L152xD || STM32L162xCA || STM32L162xD || STM32L151xE || STM32L152xE || STM32L162xE */ /** * @brief Enable the ADC peripheral * @param __HANDLE__: ADC handle * @retval None */ #define __ADC_ENABLE(__HANDLE__) \ (__HANDLE__)->Instance->CR2 |= ADC_CR2_ADON /** * @brief Disable the ADC peripheral * @param __HANDLE__: ADC handle * @retval None */ #define __ADC_DISABLE(__HANDLE__) \ (__HANDLE__)->Instance->CR2 &= ~ADC_CR2_ADON /** * @} */ /* Exported functions --------------------------------------------------------*/ /** @addtogroup ADCEx_Exported_Functions * @{ */ /* IO operation functions *****************************************************/ /** @addtogroup ADCEx_Exported_Functions_Group1 * @{ */ /* Blocking mode: Polling */ HAL_StatusTypeDef HAL_ADCEx_InjectedStart(ADC_HandleTypeDef* hadc); HAL_StatusTypeDef HAL_ADCEx_InjectedStop(ADC_HandleTypeDef* hadc); HAL_StatusTypeDef HAL_ADCEx_InjectedPollForConversion(ADC_HandleTypeDef* hadc, uint32_t Timeout); /* Non-blocking mode: Interruption */ HAL_StatusTypeDef HAL_ADCEx_InjectedStart_IT(ADC_HandleTypeDef* hadc); HAL_StatusTypeDef HAL_ADCEx_InjectedStop_IT(ADC_HandleTypeDef* hadc); /* ADC retrieve conversion value intended to be used with polling or interruption */ uint32_t HAL_ADCEx_InjectedGetValue(ADC_HandleTypeDef* hadc, uint32_t InjectedRank); /* ADC IRQHandler and Callbacks used in non-blocking modes (Interruption) */ void HAL_ADCEx_InjectedConvCpltCallback(ADC_HandleTypeDef* hadc); /** * @} */ /* Peripheral Control functions ***********************************************/ /** @addtogroup ADCEx_Exported_Functions_Group2 * @{ */ HAL_StatusTypeDef HAL_ADCEx_InjectedConfigChannel(ADC_HandleTypeDef* hadc,ADC_InjectionConfTypeDef* sConfigInjected); /** * @} */ /** * @} */ /** * @} */ /** * @} */ #ifdef __cplusplus } #endif #endif /* __STM32L1xx_HAL_ADC_EX_H */ /************************ (C) COPYRIGHT STMicroelectronics *****END OF FILE****/ ================================================ FILE: Zelig/mbed/TARGET_NUCLEO_L152RE/stm32l1xx_hal_comp.h ================================================ /** ****************************************************************************** * @file stm32l1xx_hal_comp.h * @author MCD Application Team * @version V1.0.0 * @date 5-September-2014 * @brief Header file of COMP HAL module. ****************************************************************************** * @attention * *

© COPYRIGHT(c) 2014 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. * ****************************************************************************** */ /* Define to prevent recursive inclusion -------------------------------------*/ #ifndef __STM32L1xx_HAL_COMP_H #define __STM32L1xx_HAL_COMP_H #ifdef __cplusplus extern "C" { #endif /* Includes ------------------------------------------------------------------*/ #include "stm32l1xx_hal_def.h" /** @addtogroup STM32L1xx_HAL_Driver * @{ */ /** @addtogroup COMP * @{ */ /* Exported types ------------------------------------------------------------*/ /** @defgroup COMP_Exported_Types COMP Exported Types * @{ */ /** * @brief COMP Init structure definition */ typedef struct { uint32_t InvertingInput; /*!< Selects the inverting input of the comparator. This parameter can be a value of @ref COMP_InvertingInput Note: Inverting input can be changed on the fly, while comparator is running. Note: This feature is available on COMP2 only. If COMP1 is selected, this parameter is discarded (On COMP1, inverting input is fixed to Vrefint). */ uint32_t NonInvertingInput; /*!< Selects the non inverting input of the comparator. This parameter can be a value of @ref COMPEx_NonInvertingInput */ uint32_t Output; /*!< Selects the output redirection of the comparator. This parameter can be a value of @ref COMP_Output Note: This feature is available on COMP2 only. If COMP1 is selected, this parameter is discarded. */ uint32_t Mode; /*!< Selects the operating consumption mode of the comparator to adjust the speed/consumption. This parameter can be a value of @ref COMP_Mode Note: This feature is available on COMP2 only. If COMP1 is selected, this parameter is discarded. */ uint32_t WindowMode; /*!< Selects the window mode of the 2 comparators. If enabled, non-inverting inputs of the 2 comparators are connected together and are using inputs of COMP2 only (COMP1 non-inverting input is no more accessible, even from ADC channel VCOMP). This parameter can be a value of @ref COMP_WindowMode Note: This feature must be enabled from COMP2 instance. If COMP1 is selected, this parameter is discarded. */ uint32_t TriggerMode; /*!< Selects the trigger mode of the comparator when using interruption on EXTI line (interrupt mode). This parameter can be a value of @ref COMP_TriggerMode Note: This feature is used with function "HAL_COMP_Start_IT()". In all other functions, this parameter is discarded. */ uint32_t NonInvertingInputPull; /*!< Selects the internal pulling resistor connected on non inverting input. This parameter can be a value of @ref COMP_NonInvertingInputPull Note: To avoid extra power consumption, only one resistor should be enabled at a time. Note: This feature is available on COMP1 only. If COMP2 is selected, this parameter is discarded. */ }COMP_InitTypeDef; /** * @brief HAL State structures definition */ typedef enum { HAL_COMP_STATE_RESET = 0x00, /*!< COMP not yet initialized or disabled */ HAL_COMP_STATE_READY = 0x01, /*!< COMP initialized and ready for use */ HAL_COMP_STATE_READY_LOCKED = 0x11, /*!< COMP initialized but the configuration is locked */ HAL_COMP_STATE_BUSY = 0x02, /*!< COMP is running */ HAL_COMP_STATE_BUSY_LOCKED = 0x12 /*!< COMP is running and the configuration is locked */ }HAL_COMP_StateTypeDef; /** * @brief COMP Handle Structure definition */ typedef struct { COMP_TypeDef *Instance; /*!< Register base address */ COMP_InitTypeDef Init; /*!< COMP required parameters */ HAL_LockTypeDef Lock; /*!< Locking object */ __IO HAL_COMP_StateTypeDef State; /*!< COMP communication state */ } COMP_HandleTypeDef; /** * @} */ /* Exported constants --------------------------------------------------------*/ /** @defgroup COMP_Exported_Constants COMP Exported Constants * @{ */ /** @defgroup COMP_Output COMP Output * @{ */ #define COMP_OUTPUT_TIM2IC4 ((uint32_t)0x00000000) /*!< COMP2 output connected to TIM2 Input Capture 4 */ #define COMP_OUTPUT_TIM2OCREFCLR ( COMP_CSR_OUTSEL_0) /*!< COMP2 output connected to TIM2 OCREF Clear */ #define COMP_OUTPUT_TIM3IC4 ( COMP_CSR_OUTSEL_1 ) /*!< COMP2 output connected to TIM3 Input Capture 4 */ #define COMP_OUTPUT_TIM3OCREFCLR ( COMP_CSR_OUTSEL_1 | COMP_CSR_OUTSEL_0) /*!< COMP2 output connected to TIM3 OCREF Clear */ #define COMP_OUTPUT_TIM4IC4 (COMP_CSR_OUTSEL_2 ) /*!< COMP2 output connected to TIM4 Input Capture 4 */ #define COMP_OUTPUT_TIM4OCREFCLR (COMP_CSR_OUTSEL_2 | COMP_CSR_OUTSEL_0) /*!< COMP2 output connected to TIM4 OCREF Clear */ #define COMP_OUTPUT_TIM10IC1 (COMP_CSR_OUTSEL_2 | COMP_CSR_OUTSEL_1 ) /*!< COMP2 output connected to TIM10 Input Capture 1 */ #define COMP_OUTPUT_NONE (COMP_CSR_OUTSEL_2 | COMP_CSR_OUTSEL_1 | COMP_CSR_OUTSEL_0) /*!< COMP2 output is not connected to other peripherals */ #define IS_COMP_OUTPUT(OUTPUT) (((OUTPUT) == COMP_OUTPUT_TIM2IC4) || \ ((OUTPUT) == COMP_OUTPUT_TIM2OCREFCLR) || \ ((OUTPUT) == COMP_OUTPUT_TIM3IC4) || \ ((OUTPUT) == COMP_OUTPUT_TIM3OCREFCLR) || \ ((OUTPUT) == COMP_OUTPUT_TIM4IC4) || \ ((OUTPUT) == COMP_OUTPUT_TIM4OCREFCLR) || \ ((OUTPUT) == COMP_OUTPUT_TIM10IC1) || \ ((OUTPUT) == COMP_OUTPUT_NONE) ) /** * @} */ /** @defgroup COMP_InvertingInput COMP InvertingInput * @{ */ /* Inverting Input specific to COMP2 */ #define COMP_INVERTINGINPUT_IO ( COMP_CSR_INSEL_0) /*!< External I/O (COMP2_INM connected to pin PB3) connected to comparator 2 inverting input */ #define COMP_INVERTINGINPUT_VREFINT ( COMP_CSR_INSEL_1 ) /*!< VREFINT connected to comparator 2 inverting input */ #define COMP_INVERTINGINPUT_3_4VREFINT ( COMP_CSR_INSEL_1 | COMP_CSR_INSEL_0) /*!< 3/4 VREFINT connected to comparator 2 inverting input */ #define COMP_INVERTINGINPUT_1_2VREFINT (COMP_CSR_INSEL_2 ) /*!< 1/2 VREFINT connected to comparator 2 inverting input */ #define COMP_INVERTINGINPUT_1_4VREFINT (COMP_CSR_INSEL_2 | COMP_CSR_INSEL_0) /*!< 1/4 VREFINT connected to comparator 2 inverting input */ #define COMP_INVERTINGINPUT_DAC1 (COMP_CSR_INSEL_2 | COMP_CSR_INSEL_1 ) /*!< DAC_OUT1 (PA4) connected to comparator 2 inverting input */ #define COMP_INVERTINGINPUT_DAC2 (COMP_CSR_INSEL_2 | COMP_CSR_INSEL_1 | COMP_CSR_INSEL_0) /*!< DAC2_OUT (PA5) connected to comparator 2 inverting input */ #define IS_COMP_INVERTINGINPUT(INPUT) (((INPUT) == COMP_INVERTINGINPUT_IO) || \ ((INPUT) == COMP_INVERTINGINPUT_VREFINT) || \ ((INPUT) == COMP_INVERTINGINPUT_3_4VREFINT) || \ ((INPUT) == COMP_INVERTINGINPUT_1_2VREFINT) || \ ((INPUT) == COMP_INVERTINGINPUT_1_4VREFINT) || \ ((INPUT) == COMP_INVERTINGINPUT_DAC1) || \ ((INPUT) == COMP_INVERTINGINPUT_DAC2) ) /** * @} */ /** @defgroup COMP_Mode COMP Mode * @{ */ /* Please refer to the electrical characteristics in the device datasheet for the power consumption values */ #define COMP_MODE_LOWSPEED ((uint32_t)0x00000000) /*!< Low Speed */ #define COMP_MODE_HIGHSPEED COMP_CSR_SPEED /*!< High Speed */ #define IS_COMP_MODE(SPEED) (((SPEED) == COMP_MODE_LOWSPEED) || \ ((SPEED) == COMP_MODE_HIGHSPEED)) /** * @} */ /** @defgroup COMP_WindowMode COMP WindowMode * @{ */ #define COMP_WINDOWMODE_DISABLED ((uint32_t)0x00000000) /*!< Window mode disabled: COMP1 non-inverting input is independant */ #define COMP_WINDOWMODE_ENABLED COMP_CSR_WNDWE /*!< Window mode enabled: COMP1 non-inverting input is no more accessible, even from ADC channel VCOMP) (connected to COMP2 non-inverting input) */ #define IS_COMP_WINDOWMODE(WINDOWMODE) (((WINDOWMODE) == COMP_WINDOWMODE_DISABLED) || \ ((WINDOWMODE) == COMP_WINDOWMODE_ENABLED)) /** * @} */ /** @defgroup COMP_OutputLevel COMP OutputLevel * @{ */ /* Comparator output is low when the non-inverting input is at a lower */ /* voltage than the inverting input. */ #define COMP_OUTPUTLEVEL_LOW ((uint32_t)0x00000000) /* Comparator output is high when the non-inverting input is at a higher */ /* voltage than the inverting input. */ #define COMP_OUTPUTLEVEL_HIGH ((uint32_t)0x00000001) /** * @} */ /** @defgroup COMP_TriggerMode COMP TriggerMode * @{ */ #define COMP_TRIGGERMODE_NONE ((uint32_t)0x00000000) /*!< No External Interrupt trigger detection */ #define COMP_TRIGGERMODE_IT_RISING ((uint32_t)0x00000001) /*!< External Interrupt Mode with Rising edge trigger detection */ #define COMP_TRIGGERMODE_IT_FALLING ((uint32_t)0x00000002) /*!< External Interrupt Mode with Falling edge trigger detection */ #define COMP_TRIGGERMODE_IT_RISING_FALLING ((uint32_t)0x00000003) /*!< External Interrupt Mode with Rising/Falling edge trigger detection */ #define IS_COMP_TRIGGERMODE(MODE) (((MODE) == COMP_TRIGGERMODE_NONE) || \ ((MODE) == COMP_TRIGGERMODE_IT_RISING) || \ ((MODE) == COMP_TRIGGERMODE_IT_FALLING) || \ ((MODE) == COMP_TRIGGERMODE_IT_RISING_FALLING) ) /** * @} */ /** @defgroup COMP_ExtiLineEvent COMP ExtiLineEvent * @{ */ #define COMP_EXTI_LINE_COMP1_EVENT EXTI_RTSR_TR21 /*!< External interrupt line 21 Connected to COMP1 */ #define COMP_EXTI_LINE_COMP2_EVENT EXTI_RTSR_TR22 /*!< External interrupt line 22 Connected to COMP2 */ /** * @} */ /** @defgroup COMP_NonInvertingInputPull COMP NonInvertingInputPull * @{ */ #define COMP_NONINVERTINGINPUT_NOPULL ((uint32_t)0x00000000) /*!< No internal pull-up or pull-down resistor connected to comparator non inverting input */ #define COMP_NONINVERTINGINPUT_10KPU COMP_CSR_10KPU /*!< Internal 10kOhm pull-up resistor connected to comparator non inverting input */ #define COMP_NONINVERTINGINPUT_10KPD COMP_CSR_10KPD /*!< Internal 10kOhm pull-down resistor connected to comparator non inverting input */ #define COMP_NONINVERTINGINPUT_400KPU COMP_CSR_400KPU /*!< Internal 400kOhm pull-up resistor connected to comparator non inverting input */ #define COMP_NONINVERTINGINPUT_400KPD COMP_CSR_400KPD /*!< Internal 400kOhm pull-down resistor connected to comparator non inverting input */ #define IS_COMP_NONINVERTINGINPUTPULL(INPUT) (((INPUT) == COMP_NONINVERTINGINPUT_NOPULL) || \ ((INPUT) == COMP_NONINVERTINGINPUT_10KPU) || \ ((INPUT) == COMP_NONINVERTINGINPUT_10KPD) || \ ((INPUT) == COMP_NONINVERTINGINPUT_400KPU) || \ ((INPUT) == COMP_NONINVERTINGINPUT_400KPD) ) /** * @} */ /** * @} */ /* Exported macro ------------------------------------------------------------*/ /** @defgroup COMP_Exported_Macro COMP Exported Macro * @{ */ /** @brief Reset COMP handle state * @param __HANDLE__: COMP handle. * @retval None */ #define __HAL_COMP_RESET_HANDLE_STATE(__HANDLE__) ((__HANDLE__)->State = HAL_COMP_STATE_RESET) /** * @brief Enables the specified comparator * @param __HANDLE__: COMP handle. * @retval None. */ #define __HAL_COMP_ENABLE(__HANDLE__) \ ( ( ((__HANDLE__)->Instance == COMP1) \ )? \ SET_BIT(COMP->CSR, COMP_CSR_CMP1EN) \ : \ MODIFY_REG(COMP->CSR, COMP_CSR_INSEL, (__HANDLE__)->Init.InvertingInput ) \ ) /** * @brief Disables the specified comparator * @param __HANDLE__: COMP handle. * @retval None. */ #define __HAL_COMP_DISABLE(__HANDLE__) \ ( ( ((__HANDLE__)->Instance == COMP1) \ )? \ CLEAR_BIT(COMP->CSR, COMP_CSR_CMP1EN) \ : \ CLEAR_BIT(COMP->CSR, COMP_CSR_INSEL) \ ) /** @brief Checks whether the specified COMP flag is set or not. * @param __HANDLE__: specifies the COMP Handle. * @param __FLAG__: specifies the flag to check. * This parameter can be one of the following values: * @arg COMP_FLAG_LOCK: lock flag * @retval The new state of __FLAG__ (TRUE or FALSE). */ #define __HAL_COMP_GET_FLAG(__HANDLE__, __FLAG__) (READ_BIT((__HANDLE__)->Instance->CSR, (__FLAG__)) == (__FLAG__)) /** * @brief Enable the Exti Line rising edge trigger. * @param __EXTILINE__: specifies the COMP Exti sources to be enabled. * This parameter can be a value of @ref COMP_ExtiLineEvent * @retval None. */ #define __HAL_COMP_EXTI_RISING_IT_ENABLE(__EXTILINE__) (SET_BIT(EXTI->RTSR, (__EXTILINE__))) /** * @brief Disable the Exti Line rising edge trigger. * @param __EXTILINE__: specifies the COMP Exti sources to be disabled. * This parameter can be a value of @ref COMP_ExtiLineEvent * @retval None. */ #define __HAL_COMP_EXTI_RISING_IT_DISABLE(__EXTILINE__) (CLEAR_BIT(EXTI->RTSR, (__EXTILINE__))) /** * @brief Enable the Exti Line falling edge trigger. * @param __EXTILINE__: specifies the COMP Exti sources to be enabled. * This parameter can be a value of @ref COMP_ExtiLineEvent * @retval None. */ #define __HAL_COMP_EXTI_FALLING_IT_ENABLE(__EXTILINE__) (SET_BIT(EXTI->FTSR, (__EXTILINE__))) /** * @brief Disable the Exti Line falling edge trigger. * @param __EXTILINE__: specifies the COMP Exti sources to be disabled. * This parameter can be a value of @ref COMP_ExtiLineEvent * @retval None. */ #define __HAL_COMP_EXTI_FALLING_IT_DISABLE(__EXTILINE__) (CLEAR_BIT(EXTI->FTSR, (__EXTILINE__))) /** * @brief Get the specified EXTI line for a comparator instance * @param __INSTANCE__: specifies the COMP instance. * @retval value of @ref COMP_ExtiLineEvent */ #define __HAL_COMP_GET_EXTI_LINE(__INSTANCE__) \ ( ( ((__INSTANCE__) == COMP1) \ )? \ (COMP_EXTI_LINE_COMP1_EVENT) \ : \ (COMP_EXTI_LINE_COMP2_EVENT) \ ) /** * @brief Enable the COMP Exti Line. * @param __EXTILINE__: specifies the COMP Exti sources to be enabled. * This parameter can be a value of @ref COMP_ExtiLineEvent * @retval None. */ #define __HAL_COMP_EXTI_ENABLE_IT(__EXTILINE__) (SET_BIT(EXTI->IMR, (__EXTILINE__))) /** * @brief Disable the COMP Exti Line. * @param __EXTILINE__: specifies the COMP Exti sources to be disabled. * This parameter can be a value of @ref COMP_ExtiLineEvent * @retval None. */ #define __HAL_COMP_EXTI_DISABLE_IT(__EXTILINE__) (CLEAR_BIT(EXTI->IMR, (__EXTILINE__))) /** * @brief Checks whether the specified EXTI line flag is set or not. * @param __FLAG__: specifies the COMP Exti sources to be checked. * This parameter can be a value of @ref COMP_ExtiLineEvent * @retval The state of __FLAG__ (SET or RESET). */ #define __HAL_COMP_EXTI_GET_FLAG(__FLAG__) (READ_BIT(EXTI->PR, (__FLAG__))) /** * @brief Clear the COMP Exti flags. * @param __FLAG__: specifies the COMP Exti sources to be cleared. * This parameter can be a value of @ref COMP_ExtiLineEvent * @retval None. */ #define __HAL_COMP_EXTI_CLEAR_FLAG(__FLAG__) (EXTI->PR = (__FLAG__)) /** * @brief Generates a Software interrupt on selected EXTI line. * @param __EXTILINE__: specifies the COMP Exti sources to trig. * This parameter can be a value of @ref COMP_ExtiLineEvent * @retval None */ #define __HAL_COMP_EXTI_GENERATE_SWIT(__EXTILINE__) (SET_BIT(EXTI->SWIER, (__EXTILINE__))) /** * @} */ /* Private macro -------------------------------------------------------------*/ /** @defgroup COMP_Private_Macro COMP Private Macro * @{ */ /** * @brief Select the COMP register CSR bit CMPxOUT corresponding to the * selected COMP instance. * @param __HANDLE__: COMP handle * @retval Comparator register CSR bit COMP_CSR_CMP1OUT or COMP_CSR_CMP2OUT */ #define __COMP_CSR_CMPXOUT(__HANDLE__) \ ( ( ((__HANDLE__)->Instance == COMP1) \ )? \ (COMP_CSR_CMP1OUT) \ : \ (COMP_CSR_CMP2OUT) \ ) /** * @brief Verification of COMP state: enabled or disabled * @param __HANDLE__: COMP handle * @retval SET (COMP enabled) or RESET (COMP disabled) */ #define __COMP_IS_ENABLED(__HANDLE__) \ ( ( ((__HANDLE__)->Instance == COMP1) \ )? \ (((READ_BIT(COMP->CSR , COMP_CSR_CMP1EN) == COMP_CSR_CMP1EN) \ ) ? SET : RESET) \ : \ (((READ_BIT(COMP->CSR , COMP_CSR_INSEL) != RESET) \ ) ? SET : RESET) \ ) /** * @} */ /* Include COMP HAL Extension module */ #include "stm32l1xx_hal_comp_ex.h" /* Exported functions --------------------------------------------------------*/ /** @addtogroup COMP_Exported_Functions * @{ */ /* Initialization and de-initialization functions ******************************/ /** @addtogroup COMP_Exported_Functions_Group1 * @{ */ HAL_StatusTypeDef HAL_COMP_Init(COMP_HandleTypeDef *hcomp); HAL_StatusTypeDef HAL_COMP_DeInit (COMP_HandleTypeDef *hcomp); void HAL_COMP_MspInit(COMP_HandleTypeDef *hcomp); void HAL_COMP_MspDeInit(COMP_HandleTypeDef *hcomp); /** * @} */ /* I/O operation functions *****************************************************/ /** @addtogroup COMP_Exported_Functions_Group2 * @{ */ HAL_StatusTypeDef HAL_COMP_Start(COMP_HandleTypeDef *hcomp); HAL_StatusTypeDef HAL_COMP_Stop(COMP_HandleTypeDef *hcomp); HAL_StatusTypeDef HAL_COMP_Start_IT(COMP_HandleTypeDef *hcomp); HAL_StatusTypeDef HAL_COMP_Stop_IT(COMP_HandleTypeDef *hcomp); void HAL_COMP_IRQHandler(COMP_HandleTypeDef *hcomp); /** * @} */ /* Peripheral Control functions ************************************************/ /** @addtogroup COMP_Exported_Functions_Group3 * @{ */ HAL_StatusTypeDef HAL_COMP_Lock(COMP_HandleTypeDef *hcomp); uint32_t HAL_COMP_GetOutputLevel(COMP_HandleTypeDef *hcomp); /* Callback in Interrupt mode */ void HAL_COMP_TriggerCallback(COMP_HandleTypeDef *hcomp); /** * @} */ /* Peripheral State functions **************************************************/ /** @addtogroup COMP_Exported_Functions_Group4 * @{ */ HAL_COMP_StateTypeDef HAL_COMP_GetState(COMP_HandleTypeDef *hcomp); /** * @} */ /** * @} */ /** * @} */ /** * @} */ #ifdef __cplusplus } #endif #endif /* __STM32L1xx_HAL_COMP_H */ /************************ (C) COPYRIGHT STMicroelectronics *****END OF FILE****/ ================================================ FILE: Zelig/mbed/TARGET_NUCLEO_L152RE/stm32l1xx_hal_comp_ex.h ================================================ /** ****************************************************************************** * @file stm32l1xx_hal_comp_ex.h * @author MCD Application Team * @version V1.0.0 * @date 5-September-2014 * @brief Header file of COMP HAL Extension module. ****************************************************************************** * @attention * *

© COPYRIGHT(c) 2014 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. * ****************************************************************************** */ /* Define to prevent recursive inclusion -------------------------------------*/ #ifndef __STM32L1xx_HAL_COMP_EX_H #define __STM32L1xx_HAL_COMP_EX_H #ifdef __cplusplus extern "C" { #endif /* Includes ------------------------------------------------------------------*/ #include "stm32l1xx_hal_def.h" /** @addtogroup STM32L1xx_HAL_Driver * @{ */ /** @defgroup COMPEx COMPEx * @{ */ /* Exported types ------------------------------------------------------------*/ /* Exported constants --------------------------------------------------------*/ /** @defgroup COMPEx_Exported_Constants COMPEx Exported Constants * @{ */ /** @defgroup COMPEx_NonInvertingInput COMPEx NonInvertingInput * @{ */ #if defined(STM32L151xCA) || defined (STM32L151xD) || defined (STM32L152xCA) || defined (STM32L152xD) || defined (STM32L162xCA) || defined (STM32L162xD) || defined(STM32L151xE) || defined (STM32L152xE) || defined (STM32L162xE) /* Non-inverting inputs specific to COMP2 */ #define COMP_NONINVERTINGINPUT_PB4 RI_IOSWITCH_GR6_1 /*!< I/O pin PB4 connection to COMP2 non-inverting input */ #define COMP_NONINVERTINGINPUT_PB5 RI_IOSWITCH_GR6_2 /*!< I/O pin PB5 connection to COMP2 non-inverting input */ #define COMP_NONINVERTINGINPUT_PB6 RI_IOSWITCH_GR6_3 /*!< I/O pin PB6 connection to COMP2 non-inverting input */ #define COMP_NONINVERTINGINPUT_PB7 RI_IOSWITCH_GR6_4 /*!< I/O pin PB7 connection to COMP2 non-inverting input */ /* Non-inverting inputs specific to COMP1 */ #define COMP_NONINVERTINGINPUT_NONE ((uint32_t)0x00000000) /*!< In case of window mode: No I/O pin connection to COMP1 non-inverting input. Instead, connection to COMP2 non-inverting input. */ #define COMP_NONINVERTINGINPUT_PA0 RI_IOSWITCH_CH0 /*!< I/O pin PA0 connection to COMP1 non-inverting input */ #define COMP_NONINVERTINGINPUT_PA1 RI_IOSWITCH_CH1 /*!< I/O pin PA1 connection to COMP1 non-inverting input */ #define COMP_NONINVERTINGINPUT_PA2 RI_IOSWITCH_CH2 /*!< I/O pin PA2 connection to COMP1 non-inverting input */ #define COMP_NONINVERTINGINPUT_PA3 RI_IOSWITCH_CH3 /*!< I/O pin PA3 connection to COMP1 non-inverting input */ #define COMP_NONINVERTINGINPUT_PA4 RI_IOSWITCH_CH4 /*!< I/O pin PA4 connection to COMP1 non-inverting input */ #define COMP_NONINVERTINGINPUT_PA5 RI_IOSWITCH_CH5 /*!< I/O pin PA5 connection to COMP1 non-inverting input */ #define COMP_NONINVERTINGINPUT_PA6 RI_IOSWITCH_CH5 /*!< I/O pin PA5 connection to COMP1 non-inverting input */ #define COMP_NONINVERTINGINPUT_PA7 RI_IOSWITCH_CH7 /*!< I/O pin PA7 connection to COMP1 non-inverting input */ #define COMP_NONINVERTINGINPUT_PB0 RI_IOSWITCH_CH8 /*!< I/O pin PB0 connection to COMP1 non-inverting input */ #define COMP_NONINVERTINGINPUT_PB1 RI_IOSWITCH_CH9 /*!< I/O pin PB1 connection to COMP1 non-inverting input */ #define COMP_NONINVERTINGINPUT_PC0 RI_IOSWITCH_CH10 /*!< I/O pin PC0 connection to COMP1 non-inverting input */ #define COMP_NONINVERTINGINPUT_PC1 RI_IOSWITCH_CH11 /*!< I/O pin PC1 connection to COMP1 non-inverting input */ #define COMP_NONINVERTINGINPUT_PC2 RI_IOSWITCH_CH12 /*!< I/O pin PC2 connection to COMP1 non-inverting input */ #define COMP_NONINVERTINGINPUT_PC3 RI_IOSWITCH_CH13 /*!< I/O pin PC3 connection to COMP1 non-inverting input */ #define COMP_NONINVERTINGINPUT_PC4 RI_IOSWITCH_CH14 /*!< I/O pin PC4 connection to COMP1 non-inverting input */ #define COMP_NONINVERTINGINPUT_PC5 RI_IOSWITCH_CH15 /*!< I/O pin PC5 connection to COMP1 non-inverting input */ #define COMP_NONINVERTINGINPUT_PB12 RI_IOSWITCH_CH18 /*!< I/O pin PB12 connection to COMP1 non-inverting input */ #define COMP_NONINVERTINGINPUT_PB13 RI_IOSWITCH_CH19 /*!< I/O pin PB13 connection to COMP1 non-inverting input */ #define COMP_NONINVERTINGINPUT_PB14 RI_IOSWITCH_CH20 /*!< I/O pin PB14 connection to COMP1 non-inverting input */ #define COMP_NONINVERTINGINPUT_PB15 RI_IOSWITCH_CH21 /*!< I/O pin PB15 connection to COMP1 non-inverting input */ #define COMP_NONINVERTINGINPUT_PE7 RI_IOSWITCH_CH22 /*!< I/O pin PE7 connection to COMP1 non-inverting input */ #define COMP_NONINVERTINGINPUT_PE8 RI_IOSWITCH_CH23 /*!< I/O pin PE8 connection to COMP1 non-inverting input */ #define COMP_NONINVERTINGINPUT_PE9 RI_IOSWITCH_CH24 /*!< I/O pin PE9 connection to COMP1 non-inverting input */ #define COMP_NONINVERTINGINPUT_PE10 RI_IOSWITCH_CH25 /*!< I/O pin PE10 connection to COMP1 non-inverting input */ #define COMP_NONINVERTINGINPUT_PF6 RI_IOSWITCH_CH27 /*!< I/O pin PF6 connection to COMP1 non-inverting input */ #define COMP_NONINVERTINGINPUT_PF7 RI_IOSWITCH_CH28 /*!< I/O pin PF7 connection to COMP1 non-inverting input */ #define COMP_NONINVERTINGINPUT_PF8 RI_IOSWITCH_CH29 /*!< I/O pin PF8 connection to COMP1 non-inverting input */ #define COMP_NONINVERTINGINPUT_PF9 RI_IOSWITCH_CH30 /*!< I/O pin PF9 connection to COMP1 non-inverting input */ #define COMP_NONINVERTINGINPUT_PF10 RI_IOSWITCH_CH31 /*!< I/O pin PF10 connection to COMP1 non-inverting input */ #define COMP_NONINVERTINGINPUT_OPAMP1 COMP_NONINVERTINGINPUT_PA3 /*!< OPAMP1 output connection to COMP1 non-inverting input */ #define COMP_NONINVERTINGINPUT_OPAMP2 COMP_NONINVERTINGINPUT_PB0 /*!< OPAMP2 output connection to COMP1 non-inverting input */ #if defined(STM32L151xCA) || defined (STM32L151xD) || defined (STM32L152xCA) || defined (STM32L152xD) || defined (STM32L162xCA) || defined (STM32L162xD) #define COMP_NONINVERTINGINPUT_OPAMP3 COMP_NONINVERTINGINPUT_PC3 /*!< OPAMP3 output connection to COMP1 non-inverting input */ #endif /* STM32L151xCA || STM32L151xD || STM32L152xCA || STM32L152xD || STM32L162xCA || STM32L162xD */ #endif /* STM32L151xCA || STM32L151xD || STM32L152xCA || STM32L152xD || STM32L162xCA || STM32L162xD || STM32L151xE || STM32L152xE || STM32L162xE */ #if defined(STM32L100xC) || defined (STM32L151xC) || defined (STM32L152xC) || defined (STM32L162xC) /* Non-inverting inputs specific to COMP2 */ #define COMP_NONINVERTINGINPUT_PB4 RI_IOSWITCH_GR6_1 /*!< I/O pin PB4 connection to COMP2 non-inverting input */ #define COMP_NONINVERTINGINPUT_PB5 RI_IOSWITCH_GR6_2 /*!< I/O pin PB5 connection to COMP2 non-inverting input */ #define COMP_NONINVERTINGINPUT_PB6 RI_IOSWITCH_GR6_3 /*!< I/O pin PB6 connection to COMP2 non-inverting input */ #define COMP_NONINVERTINGINPUT_PB7 RI_IOSWITCH_GR6_4 /*!< I/O pin PB7 connection to COMP2 non-inverting input */ /* Non-inverting inputs specific to COMP1 */ #define COMP_NONINVERTINGINPUT_NONE ((uint32_t)0x00000000) /*!< In case of window mode: No I/O pin connection to COMP1 non-inverting input. Instead, connection to COMP2 non-inverting input. */ #define COMP_NONINVERTINGINPUT_PA0 RI_IOSWITCH_CH0 /*!< I/O pin PA0 connection to COMP1 non-inverting input */ #define COMP_NONINVERTINGINPUT_PA1 RI_IOSWITCH_CH1 /*!< I/O pin PA1 connection to COMP1 non-inverting input */ #define COMP_NONINVERTINGINPUT_PA2 RI_IOSWITCH_CH2 /*!< I/O pin PA2 connection to COMP1 non-inverting input */ #define COMP_NONINVERTINGINPUT_PA3 RI_IOSWITCH_CH3 /*!< I/O pin PA3 connection to COMP1 non-inverting input */ #define COMP_NONINVERTINGINPUT_PA4 RI_IOSWITCH_CH4 /*!< I/O pin PA4 connection to COMP1 non-inverting input */ #define COMP_NONINVERTINGINPUT_PA5 RI_IOSWITCH_CH5 /*!< I/O pin PA5 connection to COMP1 non-inverting input */ #define COMP_NONINVERTINGINPUT_PA6 RI_IOSWITCH_CH5 /*!< I/O pin PA5 connection to COMP1 non-inverting input */ #define COMP_NONINVERTINGINPUT_PA7 RI_IOSWITCH_CH7 /*!< I/O pin PA7 connection to COMP1 non-inverting input */ #define COMP_NONINVERTINGINPUT_PB0 RI_IOSWITCH_CH8 /*!< I/O pin PB0 connection to COMP1 non-inverting input */ #define COMP_NONINVERTINGINPUT_PB1 RI_IOSWITCH_CH9 /*!< I/O pin PB1 connection to COMP1 non-inverting input */ #define COMP_NONINVERTINGINPUT_PC0 RI_IOSWITCH_CH10 /*!< I/O pin PC0 connection to COMP1 non-inverting input */ #define COMP_NONINVERTINGINPUT_PC1 RI_IOSWITCH_CH11 /*!< I/O pin PC1 connection to COMP1 non-inverting input */ #define COMP_NONINVERTINGINPUT_PC2 RI_IOSWITCH_CH12 /*!< I/O pin PC2 connection to COMP1 non-inverting input */ #define COMP_NONINVERTINGINPUT_PC3 RI_IOSWITCH_CH13 /*!< I/O pin PC3 connection to COMP1 non-inverting input */ #define COMP_NONINVERTINGINPUT_PC4 RI_IOSWITCH_CH14 /*!< I/O pin PC4 connection to COMP1 non-inverting input */ #define COMP_NONINVERTINGINPUT_PC5 RI_IOSWITCH_CH15 /*!< I/O pin PC5 connection to COMP1 non-inverting input */ #define COMP_NONINVERTINGINPUT_PB12 RI_IOSWITCH_CH18 /*!< I/O pin PB12 connection to COMP1 non-inverting input */ #define COMP_NONINVERTINGINPUT_PB13 RI_IOSWITCH_CH19 /*!< I/O pin PB13 connection to COMP1 non-inverting input */ #define COMP_NONINVERTINGINPUT_PB14 RI_IOSWITCH_CH20 /*!< I/O pin PB14 connection to COMP1 non-inverting input */ #define COMP_NONINVERTINGINPUT_PB15 RI_IOSWITCH_CH21 /*!< I/O pin PB15 connection to COMP1 non-inverting input */ #define COMP_NONINVERTINGINPUT_PE7 RI_IOSWITCH_CH22 /*!< I/O pin PE7 connection to COMP1 non-inverting input */ #define COMP_NONINVERTINGINPUT_PE8 RI_IOSWITCH_CH23 /*!< I/O pin PE8 connection to COMP1 non-inverting input */ #define COMP_NONINVERTINGINPUT_PE9 RI_IOSWITCH_CH24 /*!< I/O pin PE9 connection to COMP1 non-inverting input */ #define COMP_NONINVERTINGINPUT_PE10 RI_IOSWITCH_CH25 /*!< I/O pin PE10 connection to COMP1 non-inverting input */ #define COMP_NONINVERTINGINPUT_OPAMP1 COMP_NONINVERTINGINPUT_PA3 /*!< OPAMP1 output connection to COMP1 non-inverting input */ #define COMP_NONINVERTINGINPUT_OPAMP2 COMP_NONINVERTINGINPUT_PB0 /*!< OPAMP2 output connection to COMP1 non-inverting input */ #endif /* STM32L100xC || STM32L151xC || STM32L152xC || STM32L162xC */ #if defined(STM32L100xB) || defined (STM32L151xB) || defined (STM32L152xB) || defined(STM32L100xBA) || defined (STM32L151xBA) || defined (STM32L152xBA) /* Non-inverting inputs specific to COMP2 */ #define COMP_NONINVERTINGINPUT_PB4 RI_IOSWITCH_GR6_1 /*!< I/O pin PB4 connection to COMP2 non-inverting input */ #define COMP_NONINVERTINGINPUT_PB5 RI_IOSWITCH_GR6_2 /*!< I/O pin PB5 connection to COMP2 non-inverting input */ /* Non-inverting inputs specific to COMP1 */ #define COMP_NONINVERTINGINPUT_NONE ((uint32_t)0x00000000) /*!< In case of window mode: No I/O pin connection to COMP1 non-inverting input. Instead, connection to COMP2 non-inverting input. */ #define COMP_NONINVERTINGINPUT_PA0 RI_IOSWITCH_CH0 /*!< I/O pin PA0 connection to COMP1 non-inverting input */ #define COMP_NONINVERTINGINPUT_PA1 RI_IOSWITCH_CH1 /*!< I/O pin PA1 connection to COMP1 non-inverting input */ #define COMP_NONINVERTINGINPUT_PA2 RI_IOSWITCH_CH2 /*!< I/O pin PA2 connection to COMP1 non-inverting input */ #define COMP_NONINVERTINGINPUT_PA3 RI_IOSWITCH_CH3 /*!< I/O pin PA3 connection to COMP1 non-inverting input */ #define COMP_NONINVERTINGINPUT_PA4 RI_IOSWITCH_CH4 /*!< I/O pin PA4 connection to COMP1 non-inverting input */ #define COMP_NONINVERTINGINPUT_PA5 RI_IOSWITCH_CH5 /*!< I/O pin PA5 connection to COMP1 non-inverting input */ #define COMP_NONINVERTINGINPUT_PA6 RI_IOSWITCH_CH5 /*!< I/O pin PA5 connection to COMP1 non-inverting input */ #define COMP_NONINVERTINGINPUT_PA7 RI_IOSWITCH_CH7 /*!< I/O pin PA7 connection to COMP1 non-inverting input */ #define COMP_NONINVERTINGINPUT_PB0 RI_IOSWITCH_CH8 /*!< I/O pin PB0 connection to COMP1 non-inverting input */ #define COMP_NONINVERTINGINPUT_PB1 RI_IOSWITCH_CH9 /*!< I/O pin PB1 connection to COMP1 non-inverting input */ #define COMP_NONINVERTINGINPUT_PC0 RI_IOSWITCH_CH10 /*!< I/O pin PC0 connection to COMP1 non-inverting input */ #define COMP_NONINVERTINGINPUT_PC1 RI_IOSWITCH_CH11 /*!< I/O pin PC1 connection to COMP1 non-inverting input */ #define COMP_NONINVERTINGINPUT_PC2 RI_IOSWITCH_CH12 /*!< I/O pin PC2 connection to COMP1 non-inverting input */ #define COMP_NONINVERTINGINPUT_PC3 RI_IOSWITCH_CH13 /*!< I/O pin PC3 connection to COMP1 non-inverting input */ #define COMP_NONINVERTINGINPUT_PC4 RI_IOSWITCH_CH14 /*!< I/O pin PC4 connection to COMP1 non-inverting input */ #define COMP_NONINVERTINGINPUT_PC5 RI_IOSWITCH_CH15 /*!< I/O pin PC5 connection to COMP1 non-inverting input */ #define COMP_NONINVERTINGINPUT_PB12 RI_IOSWITCH_CH18 /*!< I/O pin PB12 connection to COMP1 non-inverting input */ #define COMP_NONINVERTINGINPUT_PB13 RI_IOSWITCH_CH19 /*!< I/O pin PB13 connection to COMP1 non-inverting input */ #define COMP_NONINVERTINGINPUT_PB14 RI_IOSWITCH_CH20 /*!< I/O pin PB14 connection to COMP1 non-inverting input */ #define COMP_NONINVERTINGINPUT_PB15 RI_IOSWITCH_CH21 /*!< I/O pin PB15 connection to COMP1 non-inverting input */ #define COMP_NONINVERTINGINPUT_PE7 RI_IOSWITCH_CH22 /*!< I/O pin PE7 connection to COMP1 non-inverting input */ #define COMP_NONINVERTINGINPUT_PE8 RI_IOSWITCH_CH23 /*!< I/O pin PE8 connection to COMP1 non-inverting input */ #define COMP_NONINVERTINGINPUT_PE9 RI_IOSWITCH_CH24 /*!< I/O pin PE9 connection to COMP1 non-inverting input */ #define COMP_NONINVERTINGINPUT_PE10 RI_IOSWITCH_CH25 /*!< I/O pin PE10 connection to COMP1 non-inverting input */ #endif /* STM32L100xB || STM32L151xB || STM32L152xB || STM32L100xBA || STM32L151xBA || STM32L152xBA */ #if defined(STM32L151xCA) || defined (STM32L151xD) || defined (STM32L152xCA) || defined (STM32L152xD) || defined (STM32L162xCA) || defined (STM32L162xD) || defined(STM32L151xE) || defined (STM32L152xE) || defined (STM32L162xE) #define IS_COMP_NONINVERTINGINPUT(INPUT) (((INPUT) == COMP_NONINVERTINGINPUT_PB4) || \ ((INPUT) == COMP_NONINVERTINGINPUT_PB5) || \ ((INPUT) == COMP_NONINVERTINGINPUT_PB6) || \ ((INPUT) == COMP_NONINVERTINGINPUT_PB7) || \ ((INPUT) == COMP_NONINVERTINGINPUT_NONE) || \ ((INPUT) == COMP_NONINVERTINGINPUT_PA0) || \ ((INPUT) == COMP_NONINVERTINGINPUT_PA1) || \ ((INPUT) == COMP_NONINVERTINGINPUT_PA2) || \ ((INPUT) == COMP_NONINVERTINGINPUT_PA3) || \ ((INPUT) == COMP_NONINVERTINGINPUT_PA4) || \ ((INPUT) == COMP_NONINVERTINGINPUT_PA5) || \ ((INPUT) == COMP_NONINVERTINGINPUT_PA6) || \ ((INPUT) == COMP_NONINVERTINGINPUT_PA7) || \ ((INPUT) == COMP_NONINVERTINGINPUT_PB0) || \ ((INPUT) == COMP_NONINVERTINGINPUT_PB1) || \ ((INPUT) == COMP_NONINVERTINGINPUT_PC0) || \ ((INPUT) == COMP_NONINVERTINGINPUT_PC1) || \ ((INPUT) == COMP_NONINVERTINGINPUT_PC2) || \ ((INPUT) == COMP_NONINVERTINGINPUT_PC3) || \ ((INPUT) == COMP_NONINVERTINGINPUT_PC4) || \ ((INPUT) == COMP_NONINVERTINGINPUT_PC5) || \ ((INPUT) == COMP_NONINVERTINGINPUT_PB12) || \ ((INPUT) == COMP_NONINVERTINGINPUT_PB13) || \ ((INPUT) == COMP_NONINVERTINGINPUT_PB14) || \ ((INPUT) == COMP_NONINVERTINGINPUT_PB15) || \ ((INPUT) == COMP_NONINVERTINGINPUT_PE7) || \ ((INPUT) == COMP_NONINVERTINGINPUT_PE8) || \ ((INPUT) == COMP_NONINVERTINGINPUT_PE9) || \ ((INPUT) == COMP_NONINVERTINGINPUT_PE10) || \ ((INPUT) == COMP_NONINVERTINGINPUT_PF6) || \ ((INPUT) == COMP_NONINVERTINGINPUT_PF7) || \ ((INPUT) == COMP_NONINVERTINGINPUT_PF8) || \ ((INPUT) == COMP_NONINVERTINGINPUT_PF9) || \ ((INPUT) == COMP_NONINVERTINGINPUT_PF10) ) #endif /* STM32L151xCA || STM32L151xD || STM32L152xCA || STM32L152xD || STM32L162xCA || STM32L162xD || STM32L151xE || STM32L152xE || STM32L162xE */ #if defined(STM32L100xC) || defined (STM32L151xC) || defined (STM32L152xC) || defined (STM32L162xC) #define IS_COMP_NONINVERTINGINPUT(INPUT) (((INPUT) == COMP_NONINVERTINGINPUT_PB4) || \ ((INPUT) == COMP_NONINVERTINGINPUT_PB5) || \ ((INPUT) == COMP_NONINVERTINGINPUT_PB6) || \ ((INPUT) == COMP_NONINVERTINGINPUT_PB7) || \ ((INPUT) == COMP_NONINVERTINGINPUT_NONE) || \ ((INPUT) == COMP_NONINVERTINGINPUT_PA0) || \ ((INPUT) == COMP_NONINVERTINGINPUT_PA1) || \ ((INPUT) == COMP_NONINVERTINGINPUT_PA2) || \ ((INPUT) == COMP_NONINVERTINGINPUT_PA3) || \ ((INPUT) == COMP_NONINVERTINGINPUT_PA4) || \ ((INPUT) == COMP_NONINVERTINGINPUT_PA5) || \ ((INPUT) == COMP_NONINVERTINGINPUT_PA6) || \ ((INPUT) == COMP_NONINVERTINGINPUT_PA7) || \ ((INPUT) == COMP_NONINVERTINGINPUT_PB0) || \ ((INPUT) == COMP_NONINVERTINGINPUT_PB1) || \ ((INPUT) == COMP_NONINVERTINGINPUT_PC0) || \ ((INPUT) == COMP_NONINVERTINGINPUT_PC1) || \ ((INPUT) == COMP_NONINVERTINGINPUT_PC2) || \ ((INPUT) == COMP_NONINVERTINGINPUT_PC3) || \ ((INPUT) == COMP_NONINVERTINGINPUT_PC4) || \ ((INPUT) == COMP_NONINVERTINGINPUT_PC5) || \ ((INPUT) == COMP_NONINVERTINGINPUT_PB12) || \ ((INPUT) == COMP_NONINVERTINGINPUT_PB13) || \ ((INPUT) == COMP_NONINVERTINGINPUT_PB14) || \ ((INPUT) == COMP_NONINVERTINGINPUT_PB15) || \ ((INPUT) == COMP_NONINVERTINGINPUT_PE7) || \ ((INPUT) == COMP_NONINVERTINGINPUT_PE8) || \ ((INPUT) == COMP_NONINVERTINGINPUT_PE9) || \ ((INPUT) == COMP_NONINVERTINGINPUT_PE10) ) #endif /* STM32L100xC || STM32L151xC || STM32L152xC || STM32L162xC */ #if defined(STM32L100xB) || defined (STM32L151xB) || defined (STM32L152xB) || defined(STM32L100xBA) || defined (STM32L151xBA) || defined (STM32L152xBA) #define IS_COMP_NONINVERTINGINPUT(INPUT) (((INPUT) == COMP_NONINVERTINGINPUT_PB4) || \ ((INPUT) == COMP_NONINVERTINGINPUT_PB5) || \ ((INPUT) == COMP_NONINVERTINGINPUT_NONE) || \ ((INPUT) == COMP_NONINVERTINGINPUT_PA0) || \ ((INPUT) == COMP_NONINVERTINGINPUT_PA1) || \ ((INPUT) == COMP_NONINVERTINGINPUT_PA2) || \ ((INPUT) == COMP_NONINVERTINGINPUT_PA3) || \ ((INPUT) == COMP_NONINVERTINGINPUT_PA4) || \ ((INPUT) == COMP_NONINVERTINGINPUT_PA5) || \ ((INPUT) == COMP_NONINVERTINGINPUT_PA6) || \ ((INPUT) == COMP_NONINVERTINGINPUT_PA7) || \ ((INPUT) == COMP_NONINVERTINGINPUT_PB0) || \ ((INPUT) == COMP_NONINVERTINGINPUT_PB1) || \ ((INPUT) == COMP_NONINVERTINGINPUT_PC0) || \ ((INPUT) == COMP_NONINVERTINGINPUT_PC1) || \ ((INPUT) == COMP_NONINVERTINGINPUT_PC2) || \ ((INPUT) == COMP_NONINVERTINGINPUT_PC3) || \ ((INPUT) == COMP_NONINVERTINGINPUT_PC4) || \ ((INPUT) == COMP_NONINVERTINGINPUT_PC5) || \ ((INPUT) == COMP_NONINVERTINGINPUT_PB12) || \ ((INPUT) == COMP_NONINVERTINGINPUT_PB13) || \ ((INPUT) == COMP_NONINVERTINGINPUT_PB14) || \ ((INPUT) == COMP_NONINVERTINGINPUT_PB15) || \ ((INPUT) == COMP_NONINVERTINGINPUT_PE7) || \ ((INPUT) == COMP_NONINVERTINGINPUT_PE8) || \ ((INPUT) == COMP_NONINVERTINGINPUT_PE9) || \ ((INPUT) == COMP_NONINVERTINGINPUT_PE10) ) #endif /* STM32L100xB || STM32L151xB || STM32L152xB || STM32L100xBA || STM32L151xBA || STM32L152xBA */ /** * @} */ /** * @} */ /* Exported macro ------------------------------------------------------------*/ /** @defgroup COMPEx_Private_Macro COMP Private Macro * @{ */ /** * @brief Specifies whether Routing Interface (RI) needs to be configured for * switches of comparator non-inverting input. * @param __HANDLE__: COMP handle. * @retval None. */ #if defined(STM32L151xCA) || defined (STM32L151xD) || defined (STM32L152xCA) || defined (STM32L152xD) || defined (STM32L162xCA) || defined (STM32L162xD) || defined(STM32L151xE) || defined (STM32L152xE) || defined (STM32L162xE) #define __COMP_ROUTING_INTERFACE_TOBECONFIGURED(__HANDLE__) \ (((__HANDLE__)->Init.NonInvertingInput != COMP_NONINVERTINGINPUT_NONE) && \ (READ_BIT(COMP->CSR, COMP_CSR_SW1) == RESET) ) #else #define __COMP_ROUTING_INTERFACE_TOBECONFIGURED(__HANDLE__) \ ((__HANDLE__)->Init.NonInvertingInput != COMP_NONINVERTINGINPUT_NONE) #endif /* STM32L151xCA || STM32L151xD || STM32L152xCA || STM32L152xD || STM32L162xCA || STM32L162xD || STM32L151xE || STM32L152xE || STM32L162xE */ /** * @} */ /* Exported functions --------------------------------------------------------*/ /** * @} */ /** * @} */ #ifdef __cplusplus } #endif #endif /* __STM32L1xx_HAL_COMP_EX_H */ /************************ (C) COPYRIGHT STMicroelectronics *****END OF FILE****/ ================================================ FILE: Zelig/mbed/TARGET_NUCLEO_L152RE/stm32l1xx_hal_conf.h ================================================ /** ****************************************************************************** * @file stm32l1xx_hal_conf_template.h * @author MCD Application Team * @version V1.0.0 * @date 5-September-2014 * @brief HAL configuration template file. * This file should be copied to the application folder and renamed * to stm32l1xx_hal_conf.h. ****************************************************************************** * @attention * *

© COPYRIGHT(c) 2014 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. * ****************************************************************************** */ /* Define to prevent recursive inclusion -------------------------------------*/ #ifndef __STM32L1xx_HAL_CONF_H #define __STM32L1xx_HAL_CONF_H #ifdef __cplusplus extern "C" { #endif /* Exported types ------------------------------------------------------------*/ /* Exported constants --------------------------------------------------------*/ /* ########################## Module Selection ############################## */ /** * @brief This is the list of modules to be used in the HAL driver */ #define HAL_MODULE_ENABLED #define HAL_ADC_MODULE_ENABLED #define HAL_COMP_MODULE_ENABLED #define HAL_CORTEX_MODULE_ENABLED #define HAL_CRC_MODULE_ENABLED #define HAL_CRYP_MODULE_ENABLED #define HAL_DAC_MODULE_ENABLED #define HAL_DMA_MODULE_ENABLED #define HAL_FLASH_MODULE_ENABLED #define HAL_GPIO_MODULE_ENABLED #define HAL_I2C_MODULE_ENABLED #define HAL_I2S_MODULE_ENABLED #define HAL_IRDA_MODULE_ENABLED #define HAL_IWDG_MODULE_ENABLED #define HAL_LCD_MODULE_ENABLED #define HAL_NOR_MODULE_ENABLED #define HAL_OPAMP_MODULE_ENABLED #define HAL_PCD_MODULE_ENABLED #define HAL_PWR_MODULE_ENABLED #define HAL_RCC_MODULE_ENABLED #define HAL_RTC_MODULE_ENABLED #define HAL_SD_MODULE_ENABLED #define HAL_SMARTCARD_MODULE_ENABLED #define HAL_SPI_MODULE_ENABLED #define HAL_SRAM_MODULE_ENABLED #define HAL_TIM_MODULE_ENABLED #define HAL_UART_MODULE_ENABLED #define HAL_USART_MODULE_ENABLED #define HAL_WWDG_MODULE_ENABLED /* ########################## Oscillator Values adaptation ####################*/ /** * @brief Adjust the value of External High Speed oscillator (HSE) used in your application. * This value is used by the RCC HAL module to compute the system frequency * (when HSE is used as system clock source, directly or through the PLL). */ #if !defined (HSE_VALUE) #define HSE_VALUE ((uint32_t)8000000) /*!< Value of the External oscillator in Hz */ #endif /* HSE_VALUE */ #if !defined (HSE_STARTUP_TIMEOUT) #define HSE_STARTUP_TIMEOUT ((uint32_t)500) /*!< Time out for HSE start up, in ms */ #endif /* HSE_STARTUP_TIMEOUT */ /** * @brief Internal Multiple Speed oscillator (MSI) default value. * This value is the default MSI range value after Reset. */ #if !defined (MSI_VALUE) #define MSI_VALUE ((uint32_t)2097000) /*!< Value of the Internal oscillator in Hz*/ #endif /* MSI_VALUE */ /** * @brief Internal High Speed oscillator (HSI) value. * This value is used by the RCC HAL module to compute the system frequency * (when HSI is used as system clock source, directly or through the PLL). */ #if !defined (HSI_VALUE) #define HSI_VALUE ((uint32_t)16000000) /*!< Value of the Internal oscillator in Hz*/ #endif /* HSI_VALUE */ /** * @brief External Low Speed oscillator (LSE) value. * This value is used by the UART, RTC HAL module to compute the system frequency */ #if !defined (LSE_VALUE) #define LSE_VALUE ((uint32_t)32768) /*!< Value of the External oscillator in Hz*/ #endif /* LSE_VALUE */ #if !defined (LSE_STARTUP_TIMEOUT) #define LSE_STARTUP_TIMEOUT ((uint32_t)5000) /*!< Time out for LSE start up, in ms */ #endif /* HSE_STARTUP_TIMEOUT */ /* Tip: To avoid modifying this file each time you need to use different HSE, === you can define the HSE value in your toolchain compiler preprocessor. */ /* ########################### System Configuration ######################### */ /** * @brief This is the HAL system configuration section */ #define VDD_VALUE ((uint32_t)3300) /*!< Value of VDD in mv */ #define TICK_INT_PRIORITY ((uint32_t)0x000F) /*!< tick interrupt priority */ #define USE_RTOS 0 #define PREFETCH_ENABLE 1 #define INSTRUCTION_CACHE_ENABLE 0 #define DATA_CACHE_ENABLE 0 /* ########################## Assert Selection ############################## */ /** * @brief Uncomment the line below to expanse the "assert_param" macro in the * HAL drivers code */ /*#define USE_FULL_ASSERT 1*/ /* Includes ------------------------------------------------------------------*/ /** * @brief Include module's header file */ #ifdef HAL_RCC_MODULE_ENABLED #include "stm32l1xx_hal_rcc.h" #endif /* HAL_RCC_MODULE_ENABLED */ #ifdef HAL_GPIO_MODULE_ENABLED #include "stm32l1xx_hal_gpio.h" #endif /* HAL_GPIO_MODULE_ENABLED */ #ifdef HAL_DMA_MODULE_ENABLED #include "stm32l1xx_hal_dma.h" #endif /* HAL_DMA_MODULE_ENABLED */ #ifdef HAL_CORTEX_MODULE_ENABLED #include "stm32l1xx_hal_cortex.h" #endif /* HAL_CORTEX_MODULE_ENABLED */ #ifdef HAL_ADC_MODULE_ENABLED #include "stm32l1xx_hal_adc.h" #endif /* HAL_ADC_MODULE_ENABLED */ #ifdef HAL_COMP_MODULE_ENABLED #include "stm32l1xx_hal_comp.h" #endif /* HAL_COMP_MODULE_ENABLED */ #ifdef HAL_CRC_MODULE_ENABLED #include "stm32l1xx_hal_crc.h" #endif /* HAL_CRC_MODULE_ENABLED */ #ifdef HAL_CRYP_MODULE_ENABLED #include "stm32l1xx_hal_cryp.h" #endif /* HAL_CRYP_MODULE_ENABLED */ #ifdef HAL_DAC_MODULE_ENABLED #include "stm32l1xx_hal_dac.h" #endif /* HAL_DAC_MODULE_ENABLED */ #ifdef HAL_FLASH_MODULE_ENABLED #include "stm32l1xx_hal_flash.h" #endif /* HAL_FLASH_MODULE_ENABLED */ #ifdef HAL_SRAM_MODULE_ENABLED #include "stm32l1xx_hal_sram.h" #endif /* HAL_SRAM_MODULE_ENABLED */ #ifdef HAL_NOR_MODULE_ENABLED #include "stm32l1xx_hal_nor.h" #endif /* HAL_NOR_MODULE_ENABLED */ #ifdef HAL_I2C_MODULE_ENABLED #include "stm32l1xx_hal_i2c.h" #endif /* HAL_I2C_MODULE_ENABLED */ #ifdef HAL_I2S_MODULE_ENABLED #include "stm32l1xx_hal_i2s.h" #endif /* HAL_I2S_MODULE_ENABLED */ #ifdef HAL_IWDG_MODULE_ENABLED #include "stm32l1xx_hal_iwdg.h" #endif /* HAL_IWDG_MODULE_ENABLED */ #ifdef HAL_LCD_MODULE_ENABLED #include "stm32l1xx_hal_lcd.h" #endif /* HAL_LCD_MODULE_ENABLED */ #ifdef HAL_OPAMP_MODULE_ENABLED #include "stm32l1xx_hal_opamp.h" #endif /* HAL_OPAMP_MODULE_ENABLED */ #ifdef HAL_PWR_MODULE_ENABLED #include "stm32l1xx_hal_pwr.h" #endif /* HAL_PWR_MODULE_ENABLED */ #ifdef HAL_RTC_MODULE_ENABLED #include "stm32l1xx_hal_rtc.h" #endif /* HAL_RTC_MODULE_ENABLED */ #ifdef HAL_SD_MODULE_ENABLED #include "stm32l1xx_hal_sd.h" #endif /* HAL_SD_MODULE_ENABLED */ #ifdef HAL_SPI_MODULE_ENABLED #include "stm32l1xx_hal_spi.h" #endif /* HAL_SPI_MODULE_ENABLED */ #ifdef HAL_TIM_MODULE_ENABLED #include "stm32l1xx_hal_tim.h" #endif /* HAL_TIM_MODULE_ENABLED */ #ifdef HAL_UART_MODULE_ENABLED #include "stm32l1xx_hal_uart.h" #endif /* HAL_UART_MODULE_ENABLED */ #ifdef HAL_USART_MODULE_ENABLED #include "stm32l1xx_hal_usart.h" #endif /* HAL_USART_MODULE_ENABLED */ #ifdef HAL_IRDA_MODULE_ENABLED #include "stm32l1xx_hal_irda.h" #endif /* HAL_IRDA_MODULE_ENABLED */ #ifdef HAL_SMARTCARD_MODULE_ENABLED #include "stm32l1xx_hal_smartcard.h" #endif /* HAL_SMARTCARD_MODULE_ENABLED */ #ifdef HAL_WWDG_MODULE_ENABLED #include "stm32l1xx_hal_wwdg.h" #endif /* HAL_WWDG_MODULE_ENABLED */ #ifdef HAL_PCD_MODULE_ENABLED #include "stm32l1xx_hal_pcd.h" #endif /* HAL_PCD_MODULE_ENABLED */ /* Exported macro ------------------------------------------------------------*/ #ifdef USE_FULL_ASSERT /** * @brief The assert_param macro is used for function's parameters check. * @param expr: If expr is false, it calls assert_failed function * which reports the name of the source file and the source * line number of the call that failed. * If expr is true, it returns no value. * @retval None */ #define assert_param(expr) ((expr) ? (void)0 : assert_failed((uint8_t *)__FILE__, __LINE__)) /* Exported functions ------------------------------------------------------- */ void assert_failed(uint8_t* file, uint32_t line); #else #define assert_param(expr) ((void)0) #endif /* USE_FULL_ASSERT */ #ifdef __cplusplus } #endif #endif /* __STM32L1xx_HAL_CONF_H */ /************************ (C) COPYRIGHT STMicroelectronics *****END OF FILE****/ ================================================ FILE: Zelig/mbed/TARGET_NUCLEO_L152RE/stm32l1xx_hal_cortex.h ================================================ /** ****************************************************************************** * @file stm32l1xx_hal_cortex.h * @author MCD Application Team * @version V1.0.0 * @date 5-September-2014 * @brief Header file of CORTEX HAL module. ****************************************************************************** * @attention * *

© COPYRIGHT(c) 2014 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. * ****************************************************************************** */ /* Define to prevent recursive inclusion -------------------------------------*/ #ifndef __STM32L1xx_HAL_CORTEX_H #define __STM32L1xx_HAL_CORTEX_H #ifdef __cplusplus extern "C" { #endif /* Includes ------------------------------------------------------------------*/ #include "stm32l1xx_hal_def.h" /** @addtogroup STM32L1xx_HAL_Driver * @{ */ /** @addtogroup CORTEX * @{ */ /* Exported types ------------------------------------------------------------*/ /* Exported constants --------------------------------------------------------*/ /** @defgroup CORTEX_Exported_Constants CORTEX Exported Constants * @{ */ /** @defgroup CORTEX_Preemption_Priority_Group CORTEX Preemption Priority Group * @{ */ #define NVIC_PRIORITYGROUP_0 ((uint32_t)0x00000007) /*!< 0 bits for pre-emption priority 4 bits for subpriority */ #define NVIC_PRIORITYGROUP_1 ((uint32_t)0x00000006) /*!< 1 bits for pre-emption priority 3 bits for subpriority */ #define NVIC_PRIORITYGROUP_2 ((uint32_t)0x00000005) /*!< 2 bits for pre-emption priority 2 bits for subpriority */ #define NVIC_PRIORITYGROUP_3 ((uint32_t)0x00000004) /*!< 3 bits for pre-emption priority 1 bits for subpriority */ #define NVIC_PRIORITYGROUP_4 ((uint32_t)0x00000003) /*!< 4 bits for pre-emption priority 0 bits for subpriority */ /** * @} */ /** @defgroup CORTEX_SysTick_clock_source CORTEX SysTick clock source * @{ */ #define SYSTICK_CLKSOURCE_HCLK_DIV8 ((uint32_t)0x00000000) #define SYSTICK_CLKSOURCE_HCLK ((uint32_t)0x00000004) /** * @} */ /** * @} */ /* Exported Macros -----------------------------------------------------------*/ /** @defgroup CORTEX_Exported_Macros CORTEX Exported Macros * @{ */ /** @defgroup CORTEX_Preemption_Priority_Group_Macro CORTEX Preemption Priority Group * @{ */ #define IS_NVIC_PRIORITY_GROUP(GROUP) (((GROUP) == NVIC_PRIORITYGROUP_0) || \ ((GROUP) == NVIC_PRIORITYGROUP_1) || \ ((GROUP) == NVIC_PRIORITYGROUP_2) || \ ((GROUP) == NVIC_PRIORITYGROUP_3) || \ ((GROUP) == NVIC_PRIORITYGROUP_4)) #define IS_NVIC_PREEMPTION_PRIORITY(PRIORITY) ((PRIORITY) < 0x10) #define IS_NVIC_SUB_PRIORITY(PRIORITY) ((PRIORITY) < 0x10) /** * @} */ /** @defgroup CORTEX_SysTick_clock_source_Macro_Exported CORTEX SysTick clock source * @{ */ /** @brief Configures the SysTick clock source. * @param __CLKSRC__: specifies the SysTick clock source. * This parameter can be one of the following values: * @arg SYSTICK_CLKSOURCE_HCLK_DIV8: AHB clock divided by 8 selected as SysTick clock source. * @arg SYSTICK_CLKSOURCE_HCLK: AHB clock selected as SysTick clock source. * @retval None */ #define __HAL_CORTEX_SYSTICKCLK_CONFIG(__CLKSRC__) \ do { \ if ((__CLKSRC__) == SYSTICK_CLKSOURCE_HCLK) \ { \ SysTick->CTRL |= SYSTICK_CLKSOURCE_HCLK; \ } \ else \ SysTick->CTRL &= ~SYSTICK_CLKSOURCE_HCLK; \ } while(0) /** * @} */ /** * @} */ /* Private macro -------------------------------------------------------------*/ /** @defgroup CORTEX_Private_Macros CORTEX Private Macros * @{ */ /** @defgroup CORTEX_SysTick_clock_source_Macro_Private CORTEX SysTick clock source * @{ */ #define IS_SYSTICK_CLK_SOURCE(SOURCE) (((SOURCE) == SYSTICK_CLKSOURCE_HCLK) || \ ((SOURCE) == SYSTICK_CLKSOURCE_HCLK_DIV8)) /** * @} */ /** * @} */ /* Exported functions --------------------------------------------------------*/ /** @addtogroup CORTEX_Exported_Functions * @{ */ /** @addtogroup CORTEX_Exported_Functions_Group1 * @{ */ /* Initialization and de-initialization functions *****************************/ void HAL_NVIC_SetPriorityGrouping(uint32_t PriorityGroup); void HAL_NVIC_SetPriority(IRQn_Type IRQn, uint32_t PreemptPriority, uint32_t SubPriority); void HAL_NVIC_EnableIRQ(IRQn_Type IRQn); void HAL_NVIC_DisableIRQ(IRQn_Type IRQn); void HAL_NVIC_SystemReset(void); uint32_t HAL_SYSTICK_Config(uint32_t TicksNumb); /** * @} */ /** @addtogroup CORTEX_Exported_Functions_Group2 * @{ */ /* Peripheral Control functions ***********************************************/ uint32_t HAL_NVIC_GetPriorityGrouping(void); void HAL_NVIC_GetPriority(IRQn_Type IRQn, uint32_t PriorityGroup, uint32_t* pPreemptPriority, uint32_t* pSubPriority); uint32_t HAL_NVIC_GetPendingIRQ(IRQn_Type IRQn); void HAL_NVIC_SetPendingIRQ(IRQn_Type IRQn); void HAL_NVIC_ClearPendingIRQ(IRQn_Type IRQn); uint32_t HAL_NVIC_GetActive(IRQn_Type IRQn); void HAL_SYSTICK_CLKSourceConfig(uint32_t CLKSource); void HAL_SYSTICK_IRQHandler(void); void HAL_SYSTICK_Callback(void); /** * @} */ /** * @} */ /** * @} */ /** * @} */ #ifdef __cplusplus } #endif #endif /* __STM32L1xx_HAL_CORTEX_H */ /************************ (C) COPYRIGHT STMicroelectronics *****END OF FILE****/ ================================================ FILE: Zelig/mbed/TARGET_NUCLEO_L152RE/stm32l1xx_hal_crc.h ================================================ /** ****************************************************************************** * @file stm32l1xx_hal_crc.h * @author MCD Application Team * @version V1.0.0 * @date 5-September-2014 * @brief Header file of CRC HAL module. ****************************************************************************** * @attention * *

© COPYRIGHT(c) 2014 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. * ****************************************************************************** */ /* Define to prevent recursive inclusion -------------------------------------*/ #ifndef __STM32L1xx_HAL_CRC_H #define __STM32L1xx_HAL_CRC_H #ifdef __cplusplus extern "C" { #endif /* Includes ------------------------------------------------------------------*/ #include "stm32l1xx_hal_def.h" /** @addtogroup STM32L1xx_HAL_Driver * @{ */ /** @addtogroup CRC * @{ */ /* Exported types ------------------------------------------------------------*/ /** @defgroup CRC_Exported_Types CRC Exported Types * @{ */ /** * @brief CRC HAL State Structure definition */ typedef enum { HAL_CRC_STATE_RESET = 0x00, /*!< CRC not yet initialized or disabled */ HAL_CRC_STATE_READY = 0x01, /*!< CRC initialized and ready for use */ HAL_CRC_STATE_BUSY = 0x02, /*!< CRC internal process is ongoing */ HAL_CRC_STATE_TIMEOUT = 0x03, /*!< CRC timeout state */ HAL_CRC_STATE_ERROR = 0x04 /*!< CRC error state */ }HAL_CRC_StateTypeDef; /** * @brief CRC handle Structure definition */ typedef struct { CRC_TypeDef *Instance; /*!< Register base address */ HAL_LockTypeDef Lock; /*!< CRC locking object */ __IO HAL_CRC_StateTypeDef State; /*!< CRC communication state */ }CRC_HandleTypeDef; /** * @} */ /* Exported constants --------------------------------------------------------*/ /* Exported macro ------------------------------------------------------------*/ /** @defgroup CRC_Exported_Macros CRC Exported Macros * @{ */ /** @brief Reset CRC handle state * @param __HANDLE__: CRC handle * @retval None */ #define __HAL_CRC_RESET_HANDLE_STATE(__HANDLE__) ((__HANDLE__)->State = HAL_CRC_STATE_RESET) /** * @brief Resets CRC Data Register. * @param __HANDLE__: CRC handle * @retval None */ #define __HAL_CRC_DR_RESET(__HANDLE__) (SET_BIT((__HANDLE__)->Instance->CR,CRC_CR_RESET)) /** * @brief Stores a 8-bit data in the Independent Data(ID) register. * @param __HANDLE__: CRC handle * @param __VALUE__: 8-bit value to be stored in the ID register * @retval None */ #define __HAL_CRC_SET_IDR(__HANDLE__, __VALUE__) (MODIFY_REG((__HANDLE__)->Instance->IDR, CRC_IDR_IDR, (__VALUE__)) /** * @brief Returns the 8-bit data stored in the Independent Data(ID) register. * @param __HANDLE__: CRC handle * @retval 8-bit value of the ID register */ #define __HAL_CRC_GET_IDR(__HANDLE__) (((__HANDLE__)->Instance->IDR) & CRC_IDR_IDR) /** * @} */ /* Exported functions --------------------------------------------------------*/ /** @addtogroup CRC_Exported_Functions * @{ */ /** @addtogroup CRC_Exported_Functions_Group1 * @{ */ /* Initialization/de-initialization functions **********************************/ HAL_StatusTypeDef HAL_CRC_Init(CRC_HandleTypeDef *hcrc); HAL_StatusTypeDef HAL_CRC_DeInit (CRC_HandleTypeDef *hcrc); void HAL_CRC_MspInit(CRC_HandleTypeDef *hcrc); void HAL_CRC_MspDeInit(CRC_HandleTypeDef *hcrc); /** * @} */ /** @addtogroup CRC_Exported_Functions_Group2 * @{ */ /** @addtogroup CRC_Exported_Functions_Group3 ** @{ */ /* Peripheral Control functions ************************************************/ uint32_t HAL_CRC_Accumulate(CRC_HandleTypeDef *hcrc, uint32_t pBuffer[], uint32_t BufferLength); uint32_t HAL_CRC_Calculate(CRC_HandleTypeDef *hcrc, uint32_t pBuffer[], uint32_t BufferLength); /* Peripheral State functions **************************************************/ HAL_CRC_StateTypeDef HAL_CRC_GetState(CRC_HandleTypeDef *hcrc); /** * @} */ /** * @} */ /** * @} */ /** * @} */ /** * @} */ #ifdef __cplusplus } #endif #endif /* __STM32L1xx_HAL_CRC_H */ /************************ (C) COPYRIGHT STMicroelectronics *****END OF FILE****/ ================================================ FILE: Zelig/mbed/TARGET_NUCLEO_L152RE/stm32l1xx_hal_cryp.h ================================================ /** ****************************************************************************** * @file stm32l1xx_hal_cryp.h * @author MCD Application Team * @version V1.0.0 * @date 5-September-2014 * @brief Header file of CRYP HAL module. ****************************************************************************** * @attention * *

© COPYRIGHT(c) 2014 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. * ****************************************************************************** */ /* Define to prevent recursive inclusion -------------------------------------*/ #ifndef __STM32L1xx_HAL_CRYP_H #define __STM32L1xx_HAL_CRYP_H #ifdef __cplusplus extern "C" { #endif #if defined(STM32L162xC) || defined(STM32L162xCA) || defined(STM32L162xD) || defined(STM32L162xE) /* Includes ------------------------------------------------------------------*/ #include "stm32l1xx_hal_def.h" /** @addtogroup STM32L1xx_HAL_Driver * @{ */ /** @addtogroup CRYP * @{ */ /* Exported types ------------------------------------------------------------*/ /** @defgroup CRYP_Exported_Types CRYP Exported Types * @{ */ /** * @brief CRYP Configuration Structure definition */ typedef struct { uint32_t DataType; /*!< 32-bit data, 16-bit data, 8-bit data or 1-bit string. This parameter can be a value of @ref CRYP_Data_Type */ uint8_t* pKey; /*!< The key used for encryption/decryption */ uint8_t* pInitVect; /*!< The initialization vector used also as initialization counter in CTR mode */ }CRYP_InitTypeDef; /** * @brief HAL CRYP State structures definition */ typedef enum { HAL_CRYP_STATE_RESET = 0x00, /*!< CRYP not yet initialized or disabled */ HAL_CRYP_STATE_READY = 0x01, /*!< CRYP initialized and ready for use */ HAL_CRYP_STATE_BUSY = 0x02, /*!< CRYP internal processing is ongoing */ HAL_CRYP_STATE_TIMEOUT = 0x03, /*!< CRYP timeout state */ HAL_CRYP_STATE_ERROR = 0x04 /*!< CRYP error state */ }HAL_CRYP_STATETypeDef; /** * @brief HAL CRYP phase structures definition */ typedef enum { HAL_CRYP_PHASE_READY = 0x01, /*!< CRYP peripheral is ready for initialization. */ HAL_CRYP_PHASE_PROCESS = 0x02, /*!< CRYP peripheral is in processing phase */ }HAL_PhaseTypeDef; /** * @brief CRYP handle Structure definition */ typedef struct { CRYP_InitTypeDef Init; /*!< CRYP required parameters */ uint8_t *pCrypInBuffPtr; /*!< Pointer to CRYP processing (encryption, decryption,...) buffer */ uint8_t *pCrypOutBuffPtr; /*!< Pointer to CRYP processing (encryption, decryption,...) buffer */ __IO uint16_t CrypInCount; /*!< Counter of inputed data */ __IO uint16_t CrypOutCount; /*!< Counter of outputed data */ HAL_StatusTypeDef Status; /*!< CRYP peripheral status */ HAL_PhaseTypeDef Phase; /*!< CRYP peripheral phase */ DMA_HandleTypeDef *hdmain; /*!< CRYP In DMA handle parameters */ DMA_HandleTypeDef *hdmaout; /*!< CRYP Out DMA handle parameters */ HAL_LockTypeDef Lock; /*!< CRYP locking object */ __IO HAL_CRYP_STATETypeDef State; /*!< CRYP peripheral state */ }CRYP_HandleTypeDef; /** * @} */ /* Exported constants --------------------------------------------------------*/ /** @defgroup CRYP_Exported_Constants CRYP Exported Constants * @{ */ /** @defgroup CRYP_Data_Type CRYP Data Type * @{ */ #define CRYP_DATATYPE_32B ((uint32_t)0x00000000) #define CRYP_DATATYPE_16B AES_CR_DATATYPE_0 #define CRYP_DATATYPE_8B AES_CR_DATATYPE_1 #define CRYP_DATATYPE_1B AES_CR_DATATYPE #define IS_CRYP_DATATYPE(DATATYPE) (((DATATYPE) == CRYP_DATATYPE_32B) || \ ((DATATYPE) == CRYP_DATATYPE_16B) || \ ((DATATYPE) == CRYP_DATATYPE_8B) || \ ((DATATYPE) == CRYP_DATATYPE_1B)) /** * @} */ /** @defgroup CRYP_AlgoModeDirection CRYP Algo Mode Direction * @{ */ #define CRYP_CR_ALGOMODE_DIRECTION (uint32_t)(AES_CR_MODE|AES_CR_CHMOD) #define CRYP_CR_ALGOMODE_AES_ECB_ENCRYPT ((uint32_t)0x00000000) #define CRYP_CR_ALGOMODE_AES_ECB_KEYDERDECRYPT (AES_CR_MODE) #define CRYP_CR_ALGOMODE_AES_CBC_ENCRYPT (AES_CR_CHMOD_0) #define CRYP_CR_ALGOMODE_AES_CBC_KEYDERDECRYPT ((uint32_t)(AES_CR_CHMOD_0|AES_CR_MODE)) #define CRYP_CR_ALGOMODE_AES_CTR_ENCRYPT (AES_CR_CHMOD_1) #define CRYP_CR_ALGOMODE_AES_CTR_DECRYPT ((uint32_t)(AES_CR_CHMOD_1 | AES_CR_MODE_1)) /** * @} */ /** @defgroup CRYP_AES_Interrupts AES Interrupts * @{ */ #define AES_IT_CC AES_CR_CCIE /*!< Computation Complete interrupt */ #define AES_IT_ERR AES_CR_ERRIE /*!< Error interrupt */ /** * @} */ /** @defgroup CRYP_AES_Flags AES Flags * @{ */ #define AES_FLAG_CCF AES_SR_CCF /*!< Computation Complete Flag */ #define AES_FLAG_RDERR AES_SR_RDERR /*!< Read Error Flag */ #define AES_FLAG_WRERR AES_SR_WRERR /*!< Write Error Flag */ /** * @} */ /** @defgroup CRYP_AES_Clear_Flags AES Clear Flags * @{ */ #define AES_CLEARFLAG_CCF AES_CR_CCFC /*!< Computation Complete Flag Clear */ #define AES_CLEARFLAG_RDERR AES_CR_ERRC /*!< Read Error Clear */ #define AES_CLEARFLAG_WRERR AES_CR_ERRC /*!< Write Error Clear */ /** * @} */ /** * @} */ /* Exported macro ------------------------------------------------------------*/ /** @defgroup CRYP_Exported_Macros CRYP Exported Macros * @{ */ /** @brief Reset CRYP handle state * @param __HANDLE__: specifies the CRYP Handle. * @retval None */ #define __HAL_CRYP_RESET_HANDLE_STATE(__HANDLE__) ((__HANDLE__)->State = HAL_CRYP_STATE_RESET) /** * @brief Enable/Disable the CRYP peripheral. * @retval None */ #define __HAL_CRYP_ENABLE() SET_BIT(AES->CR, AES_CR_EN) #define __HAL_CRYP_DISABLE() CLEAR_BIT(AES->CR, AES_CR_EN) /** * @brief Set the algorithm mode: AES-ECB, AES-CBC, AES-CTR, DES-ECB, DES-CBC,... * @param __MODE__: The algorithm mode. * @retval None */ #define __HAL_CRYP_SET_MODE(__MODE__) SET_BIT(AES->CR, (__MODE__)) /** @brief Check whether the specified CRYP flag is set or not. * @param __FLAG__: specifies the flag to check. * This parameter can be one of the following values: * @arg AES_FLAG_CCF : Computation Complete Flag * @arg AES_FLAG_RDERR : Read Error Flag * @arg AES_FLAG_WRERR : Write Error Flag * @retval The new state of __FLAG__ (TRUE or FALSE). */ #define __HAL_CRYP_GET_FLAG(__FLAG__) ((AES->SR & (__FLAG__)) == (__FLAG__)) /** @brief Clear the CRYP pending flag. * @param __HANDLE__: specifies the CRYP handle. * @param __FLAG__: specifies the flag to clear. * This parameter can be one of the following values: * @arg AES_CLEARFLAG_CCF : Computation Complete Clear Flag * @arg AES_CLEARFLAG_RDERR : Read Error Clear * @arg AES_CLEARFLAG_WRERR : Write Error Clear * @retval None */ #define __HAL_CRYP_CLEAR_FLAG(__HANDLE__, __FLAG__) SET_BIT(AES->CR, (__FLAG__)) /** * @brief Enable the CRYP interrupt. * @param __INTERRUPT__: CRYP Interrupt. * @retval None */ #define __HAL_CRYP_ENABLE_IT(__INTERRUPT__) SET_BIT(AES->CR, (__INTERRUPT__)) /** * @brief Disable the CRYP interrupt. * @param __INTERRUPT__: CRYP interrupt. * @retval None */ #define __HAL_CRYP_DISABLE_IT(__INTERRUPT__) CLEAR_BIT(AES->CR, (__INTERRUPT__)) /** @brief Checks if the specified CRYP interrupt source is enabled or disabled. * @param __HANDLE__: CRYP handle * @param __INTERRUPT__: CRYP interrupt source to check * This parameter can be one of the following values: * @arg AES_IT_CC : Computation Complete interrupt * @arg AES_IT_ERR : Error interrupt (used for RDERR and WRERR) * @retval State of interruption (SET or RESET) */ #define __HAL_CRYP_GET_IT_SOURCE(__HANDLE__, __INTERRUPT__) \ (( (AES->CR & (__INTERRUPT__)) == (__INTERRUPT__) \ )? SET : RESET \ ) /** @brief Clear the CRYP pending IT. * @param __HANDLE__: specifies the CRYP handle. * @param __IT__: specifies the IT to clear. * This parameter can be one of the following values: * @arg AES_CLEARFLAG_CCF : Computation Complete Clear Flag * @arg AES_CLEARFLAG_RDERR : Read Error Clear * @arg AES_CLEARFLAG_WRERR : Write Error Clear * @retval None */ #define __HAL_CRYP_CLEAR_IT(__HANDLE__, __IT__) SET_BIT(AES->CR, (__IT__)) /** * @} */ /* Include CRYP HAL Extension module */ #include "stm32l1xx_hal_cryp_ex.h" /* Exported functions --------------------------------------------------------*/ /** @addtogroup CRYP_Exported_Functions * @{ */ /** @addtogroup CRYP_Exported_Functions_Group1 * @{ */ /* Initialization/de-initialization functions *********************************/ HAL_StatusTypeDef HAL_CRYP_Init(CRYP_HandleTypeDef *hcryp); HAL_StatusTypeDef HAL_CRYP_DeInit(CRYP_HandleTypeDef *hcryp); /* MSP functions *************************************************************/ void HAL_CRYP_MspInit(CRYP_HandleTypeDef *hcryp); void HAL_CRYP_MspDeInit(CRYP_HandleTypeDef *hcryp); /** * @} */ /** @addtogroup CRYP_Exported_Functions_Group2 * @{ */ /* AES encryption/decryption using polling ***********************************/ HAL_StatusTypeDef HAL_CRYP_AESECB_Encrypt(CRYP_HandleTypeDef *hcryp, uint8_t *pPlainData, uint16_t Size, uint8_t *pCypherData, uint32_t Timeout); HAL_StatusTypeDef HAL_CRYP_AESECB_Decrypt(CRYP_HandleTypeDef *hcryp, uint8_t *pCypherData, uint16_t Size, uint8_t *pPlainData, uint32_t Timeout); HAL_StatusTypeDef HAL_CRYP_AESCBC_Encrypt(CRYP_HandleTypeDef *hcryp, uint8_t *pPlainData, uint16_t Size, uint8_t *pCypherData, uint32_t Timeout); HAL_StatusTypeDef HAL_CRYP_AESCBC_Decrypt(CRYP_HandleTypeDef *hcryp, uint8_t *pCypherData, uint16_t Size, uint8_t *pPlainData, uint32_t Timeout); HAL_StatusTypeDef HAL_CRYP_AESCTR_Encrypt(CRYP_HandleTypeDef *hcryp, uint8_t *pPlainData, uint16_t Size, uint8_t *pCypherData, uint32_t Timeout); HAL_StatusTypeDef HAL_CRYP_AESCTR_Decrypt(CRYP_HandleTypeDef *hcryp, uint8_t *pCypherData, uint16_t Size, uint8_t *pPlainData, uint32_t Timeout); /* AES encryption/decryption using interrupt *********************************/ HAL_StatusTypeDef HAL_CRYP_AESECB_Encrypt_IT(CRYP_HandleTypeDef *hcryp, uint8_t *pPlainData, uint16_t Size, uint8_t *pCypherData); HAL_StatusTypeDef HAL_CRYP_AESCBC_Encrypt_IT(CRYP_HandleTypeDef *hcryp, uint8_t *pPlainData, uint16_t Size, uint8_t *pCypherData); HAL_StatusTypeDef HAL_CRYP_AESCTR_Encrypt_IT(CRYP_HandleTypeDef *hcryp, uint8_t *pPlainData, uint16_t Size, uint8_t *pCypherData); HAL_StatusTypeDef HAL_CRYP_AESECB_Decrypt_IT(CRYP_HandleTypeDef *hcryp, uint8_t *pCypherData, uint16_t Size, uint8_t *pPlainData); HAL_StatusTypeDef HAL_CRYP_AESCTR_Decrypt_IT(CRYP_HandleTypeDef *hcryp, uint8_t *pCypherData, uint16_t Size, uint8_t *pPlainData); HAL_StatusTypeDef HAL_CRYP_AESCBC_Decrypt_IT(CRYP_HandleTypeDef *hcryp, uint8_t *pCypherData, uint16_t Size, uint8_t *pPlainData); /* AES encryption/decryption using DMA ***************************************/ HAL_StatusTypeDef HAL_CRYP_AESECB_Encrypt_DMA(CRYP_HandleTypeDef *hcryp, uint8_t *pPlainData, uint16_t Size, uint8_t *pCypherData); HAL_StatusTypeDef HAL_CRYP_AESECB_Decrypt_DMA(CRYP_HandleTypeDef *hcryp, uint8_t *pCypherData, uint16_t Size, uint8_t *pPlainData); HAL_StatusTypeDef HAL_CRYP_AESCBC_Encrypt_DMA(CRYP_HandleTypeDef *hcryp, uint8_t *pPlainData, uint16_t Size, uint8_t *pCypherData); HAL_StatusTypeDef HAL_CRYP_AESCBC_Decrypt_DMA(CRYP_HandleTypeDef *hcryp, uint8_t *pCypherData, uint16_t Size, uint8_t *pPlainData); HAL_StatusTypeDef HAL_CRYP_AESCTR_Encrypt_DMA(CRYP_HandleTypeDef *hcryp, uint8_t *pPlainData, uint16_t Size, uint8_t *pCypherData); HAL_StatusTypeDef HAL_CRYP_AESCTR_Decrypt_DMA(CRYP_HandleTypeDef *hcryp, uint8_t *pCypherData, uint16_t Size, uint8_t *pPlainData); /** * @} */ /** @addtogroup CRYP_Exported_Functions_Group3 * @{ */ /* CallBack functions ********************************************************/ void HAL_CRYP_InCpltCallback(CRYP_HandleTypeDef *hcryp); void HAL_CRYP_OutCpltCallback(CRYP_HandleTypeDef *hcryp); void HAL_CRYP_ErrorCallback(CRYP_HandleTypeDef *hcryp); /** * @} */ /** @addtogroup CRYP_Exported_Functions_Group4 * @{ */ /* Processing functions ********************************************************/ void HAL_CRYP_IRQHandler(CRYP_HandleTypeDef *hcryp); /** * @} */ /** @addtogroup CRYP_Exported_Functions_Group5 * @{ */ /* Peripheral State functions **************************************************/ HAL_CRYP_STATETypeDef HAL_CRYP_GetState(CRYP_HandleTypeDef *hcryp); /** * @} */ /** * @} */ /** * @} */ /** * @} */ #endif /* STM32L162xC || STM32L162xCA || STM32L162xD || STM32L162xE*/ #ifdef __cplusplus } #endif #endif /* __STM32L1xx_HAL_CRYP_H */ /************************ (C) COPYRIGHT STMicroelectronics *****END OF FILE****/ ================================================ FILE: Zelig/mbed/TARGET_NUCLEO_L152RE/stm32l1xx_hal_cryp_ex.h ================================================ /** ****************************************************************************** * @file stm32l1xx_hal_cryp_ex.h * @author MCD Application Team * @version V1.0.0 * @date 5-September-2014 * @brief Header file of CRYPEx HAL module. ****************************************************************************** * @attention * *

© COPYRIGHT(c) 2014 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. * ****************************************************************************** */ /* Define to prevent recursive inclusion -------------------------------------*/ #ifndef __STM32L1xx_HAL_CRYP_EX_H #define __STM32L1xx_HAL_CRYP_EX_H #ifdef __cplusplus extern "C" { #endif #if defined(STM32L162xC) || defined(STM32L162xCA) || defined(STM32L162xD) || defined(STM32L162xE) /* Includes ------------------------------------------------------------------*/ #include "stm32l1xx_hal_def.h" /** @addtogroup STM32L1xx_HAL_Driver * @{ */ /** @addtogroup CRYPEx * @{ */ /* Exported types ------------------------------------------------------------*/ /* Exported constants --------------------------------------------------------*/ /* Exported functions --------------------------------------------------------*/ /** @addtogroup CRYPEx_Exported_Functions * @{ */ /** @addtogroup CRYPEx_Exported_Functions_Group1 * @{ */ /* CallBack functions ********************************************************/ void HAL_CRYPEx_ComputationCpltCallback(CRYP_HandleTypeDef *hcryp); /** * @} */ /** * @} */ #endif /* STM32L162xC || STM32L162xCA || STM32L162xD || STM32L162xE*/ /** * @} */ /** * @} */ #ifdef __cplusplus } #endif #endif /* __STM32L1xx_HAL_CRYP_EX_H */ /************************ (C) COPYRIGHT STMicroelectronics *****END OF FILE****/ ================================================ FILE: Zelig/mbed/TARGET_NUCLEO_L152RE/stm32l1xx_hal_dac.h ================================================ /** ****************************************************************************** * @file stm32l1xx_hal_dac.h * @author MCD Application Team * @version V1.0.0 * @date 5-September-2014 * @brief Header file of DAC HAL module. ****************************************************************************** * @attention * *

© COPYRIGHT(c) 2014 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. * ****************************************************************************** */ /* Define to prevent recursive inclusion -------------------------------------*/ #ifndef __STM32L1xx_HAL_DAC_H #define __STM32L1xx_HAL_DAC_H #ifdef __cplusplus extern "C" { #endif /* Includes ------------------------------------------------------------------*/ #include "stm32l1xx_hal_def.h" /** @addtogroup STM32L1xx_HAL_Driver * @{ */ /** @addtogroup DAC * @{ */ /* Exported types ------------------------------------------------------------*/ /** @defgroup DAC_Exported_Types DAC Exported Types * @{ */ /** * @brief HAL State structures definition */ typedef enum { HAL_DAC_STATE_RESET = 0x00, /*!< DAC not yet initialized or disabled */ HAL_DAC_STATE_READY = 0x01, /*!< DAC initialized and ready for use */ HAL_DAC_STATE_BUSY = 0x02, /*!< DAC internal processing is ongoing */ HAL_DAC_STATE_TIMEOUT = 0x03, /*!< DAC timeout state */ HAL_DAC_STATE_ERROR = 0x04 /*!< DAC error state */ }HAL_DAC_StateTypeDef; /** * @brief DAC handle Structure definition */ typedef struct { DAC_TypeDef *Instance; /*!< Register base address */ __IO HAL_DAC_StateTypeDef State; /*!< DAC communication state */ HAL_LockTypeDef Lock; /*!< DAC locking object */ DMA_HandleTypeDef *DMA_Handle1; /*!< Pointer DMA handler for channel 1 */ DMA_HandleTypeDef *DMA_Handle2; /*!< Pointer DMA handler for channel 2 */ __IO uint32_t ErrorCode; /*!< DAC Error code */ }DAC_HandleTypeDef; /** * @brief DAC Configuration regular Channel structure definition */ typedef struct { uint32_t DAC_Trigger; /*!< Specifies the external trigger for the selected DAC channel. This parameter can be a value of @ref DAC_trigger_selection */ uint32_t DAC_OutputBuffer; /*!< Specifies whether the DAC channel output buffer is enabled or disabled. This parameter can be a value of @ref DAC_output_buffer */ }DAC_ChannelConfTypeDef; /** * @} */ /* Exported constants --------------------------------------------------------*/ /** @defgroup DAC_Exported_Constants DAC Exported Constants * @{ */ /** @defgroup DAC_Error_Code DAC Error Code * @{ */ #define HAL_DAC_ERROR_NONE 0x00 /*!< No error */ #define HAL_DAC_ERROR_DMAUNDERRUNCH1 0x01 /*!< DAC channel1 DAM underrun error */ #define HAL_DAC_ERROR_DMAUNDERRUNCH2 0x02 /*!< DAC channel2 DAM underrun error */ #define HAL_DAC_ERROR_DMA 0x04 /*!< DMA error */ /** * @} */ /** @defgroup DAC_trigger_selection DAC trigger selection * @{ */ #define DAC_TRIGGER_NONE ((uint32_t)0x00000000) /*!< Conversion is automatic once the DAC1_DHRxxxx register has been loaded, and not by external trigger */ #define DAC_TRIGGER_T6_TRGO ((uint32_t) DAC_CR_TEN1) /*!< TIM6 TRGO selected as external conversion trigger for DAC channel */ #define DAC_TRIGGER_T7_TRGO ((uint32_t)( DAC_CR_TSEL1_1 | DAC_CR_TEN1)) /*!< TIM7 TRGO selected as external conversion trigger for DAC channel */ #define DAC_TRIGGER_T9_TRGO ((uint32_t)( DAC_CR_TSEL1_1 | DAC_CR_TSEL1_0 | DAC_CR_TEN1)) /*!< TIM9 TRGO selected as external conversion trigger for DAC channel */ #define DAC_TRIGGER_T2_TRGO ((uint32_t)(DAC_CR_TSEL1_2 | DAC_CR_TEN1)) /*!< TIM2 TRGO selected as external conversion trigger for DAC channel */ #define DAC_TRIGGER_T4_TRGO ((uint32_t)(DAC_CR_TSEL1_2 | DAC_CR_TSEL1_0 | DAC_CR_TEN1)) /*!< TIM4 TRGO selected as external conversion trigger for DAC channel */ #define DAC_TRIGGER_EXT_IT9 ((uint32_t)(DAC_CR_TSEL1_2 | DAC_CR_TSEL1_1 | DAC_CR_TEN1)) /*!< EXTI Line9 event selected as external conversion trigger for DAC channel */ #define DAC_TRIGGER_SOFTWARE ((uint32_t)(DAC_CR_TSEL1 | DAC_CR_TEN1)) /*!< Conversion started by software trigger for DAC channel */ #define IS_DAC_TRIGGER(TRIGGER) (((TRIGGER) == DAC_TRIGGER_NONE) || \ ((TRIGGER) == DAC_TRIGGER_T6_TRGO) || \ ((TRIGGER) == DAC_TRIGGER_T7_TRGO) || \ ((TRIGGER) == DAC_TRIGGER_T9_TRGO) || \ ((TRIGGER) == DAC_TRIGGER_T2_TRGO) || \ ((TRIGGER) == DAC_TRIGGER_T4_TRGO) || \ ((TRIGGER) == DAC_TRIGGER_EXT_IT9) || \ ((TRIGGER) == DAC_TRIGGER_SOFTWARE)) /** * @} */ /** @defgroup DAC_output_buffer DAC output buffer * @{ */ #define DAC_OUTPUTBUFFER_ENABLE ((uint32_t)0x00000000) #define DAC_OUTPUTBUFFER_DISABLE ((uint32_t)DAC_CR_BOFF1) #define IS_DAC_OUTPUT_BUFFER_STATE(STATE) (((STATE) == DAC_OUTPUTBUFFER_ENABLE) || \ ((STATE) == DAC_OUTPUTBUFFER_DISABLE)) /** * @} */ /** @defgroup DAC_Channel_selection DAC Channel selection * @{ */ #define DAC_CHANNEL_1 ((uint32_t)0x00000000) #define DAC_CHANNEL_2 ((uint32_t)0x00000010) #define IS_DAC_CHANNEL(CHANNEL) (((CHANNEL) == DAC_CHANNEL_1) || \ ((CHANNEL) == DAC_CHANNEL_2)) /** * @} */ /** @defgroup DAC_data_alignement DAC data alignement * @{ */ #define DAC_ALIGN_12B_R ((uint32_t)0x00000000) #define DAC_ALIGN_12B_L ((uint32_t)0x00000004) #define DAC_ALIGN_8B_R ((uint32_t)0x00000008) #define IS_DAC_ALIGN(ALIGN) (((ALIGN) == DAC_ALIGN_12B_R) || \ ((ALIGN) == DAC_ALIGN_12B_L) || \ ((ALIGN) == DAC_ALIGN_8B_R)) /** * @} */ /** @defgroup DAC_data DAC data * @{ */ #define IS_DAC_DATA(DATA) ((DATA) <= 0xFFF0) /** * @} */ /** @defgroup DAC_flags_definition DAC flags definition * @{ */ #define DAC_FLAG_DMAUDR1 ((uint32_t)DAC_SR_DMAUDR1) #define DAC_FLAG_DMAUDR2 ((uint32_t)DAC_SR_DMAUDR2) /** * @} */ /** @defgroup DAC_IT_definition DAC IT definition * @{ */ #define DAC_IT_DMAUDR1 ((uint32_t)DAC_SR_DMAUDR1) #define DAC_IT_DMAUDR2 ((uint32_t)DAC_SR_DMAUDR2) /** * @} */ /** * @} */ /* Exported macro ------------------------------------------------------------*/ /** @defgroup DAC_Exported_Macros DAC Exported Macros * @{ */ /** @brief Reset DAC handle state * @param __HANDLE__: specifies the DAC handle. * @retval None */ #define __HAL_DAC_RESET_HANDLE_STATE(__HANDLE__) ((__HANDLE__)->State = HAL_DAC_STATE_RESET) /** @brief Enable the DAC channel * @param __HANDLE__: specifies the DAC handle. * @param __DAC_Channel__: specifies the DAC channel * @retval None */ #define __HAL_DAC_ENABLE(__HANDLE__, __DAC_Channel__) \ ((__HANDLE__)->Instance->CR |= (DAC_CR_EN1 << (__DAC_Channel__))) /** @brief Disable the DAC channel * @param __HANDLE__: specifies the DAC handle * @param __DAC_Channel__: specifies the DAC channel. * @retval None */ #define __HAL_DAC_DISABLE(__HANDLE__, __DAC_Channel__) \ ((__HANDLE__)->Instance->CR &= ~(DAC_CR_EN1 << (__DAC_Channel__))) /** @brief Set DHR12R1 alignment * @param __ALIGNEMENT__: specifies the DAC alignement * @retval None */ #define __HAL_DHR12R1_ALIGNEMENT(__ALIGNEMENT__) (((uint32_t)0x00000008) + (__ALIGNEMENT__)) /** @brief Set DHR12R2 alignment * @param __ALIGNEMENT__: specifies the DAC alignement * @retval None */ #define __HAL_DHR12R2_ALIGNEMENT(__ALIGNEMENT__) (((uint32_t)0x00000014) + (__ALIGNEMENT__)) /** @brief Set DHR12RD alignment * @param __ALIGNEMENT__: specifies the DAC alignement * @retval None */ #define __HAL_DHR12RD_ALIGNEMENT(__ALIGNEMENT__) (((uint32_t)0x00000020) + (__ALIGNEMENT__)) /** @brief Enable the DAC interrupt * @param __HANDLE__: specifies the DAC handle * @param __INTERRUPT__: specifies the DAC interrupt. * @retval None */ #define __HAL_DAC_ENABLE_IT(__HANDLE__, __INTERRUPT__) (((__HANDLE__)->Instance->CR) |= (__INTERRUPT__)) /** @brief Disable the DAC interrupt * @param __HANDLE__: specifies the DAC handle * @param __INTERRUPT__: specifies the DAC interrupt. * @retval None */ #define __HAL_DAC_DISABLE_IT(__HANDLE__, __INTERRUPT__) (((__HANDLE__)->Instance->CR) &= ~(__INTERRUPT__)) /** @brief Get the selected DAC's flag status. * @param __HANDLE__: specifies the DAC handle. * @param __FLAG__: specifies the FLAG. * @retval None */ #define __HAL_DAC_GET_FLAG(__HANDLE__, __FLAG__) ((((__HANDLE__)->Instance->SR) & (__FLAG__)) == (__FLAG__)) /** @brief Clear the DAC's flag. * @param __HANDLE__: specifies the DAC handle. * @param __FLAG__: specifies the FLAG. * @retval None */ #define __HAL_DAC_CLEAR_FLAG(__HANDLE__, __FLAG__) (((__HANDLE__)->Instance->SR) = (__FLAG__)) /** * @} */ /* Include DAC HAL Extension module */ #include "stm32l1xx_hal_dac_ex.h" /* Exported functions --------------------------------------------------------*/ /** @addtogroup DAC_Exported_Functions * @{ */ /** @addtogroup DAC_Exported_Functions_Group1 * @{ */ /* Initialization and de-initialization functions *****************************/ HAL_StatusTypeDef HAL_DAC_Init(DAC_HandleTypeDef* hdac); HAL_StatusTypeDef HAL_DAC_DeInit(DAC_HandleTypeDef* hdac); void HAL_DAC_MspInit(DAC_HandleTypeDef* hdac); void HAL_DAC_MspDeInit(DAC_HandleTypeDef* hdac); /** * @} */ /** @addtogroup DAC_Exported_Functions_Group2 * @{ */ /* IO operation functions *****************************************************/ HAL_StatusTypeDef HAL_DAC_Start(DAC_HandleTypeDef* hdac, uint32_t Channel); HAL_StatusTypeDef HAL_DAC_Stop(DAC_HandleTypeDef* hdac, uint32_t Channel); HAL_StatusTypeDef HAL_DAC_Start_DMA(DAC_HandleTypeDef* hdac, uint32_t Channel, uint32_t* pData, uint32_t Length, uint32_t Alignment); HAL_StatusTypeDef HAL_DAC_Stop_DMA(DAC_HandleTypeDef* hdac, uint32_t Channel); HAL_StatusTypeDef HAL_DAC_SetValue(DAC_HandleTypeDef* hdac, uint32_t Channel, uint32_t Alignment, uint32_t Data); uint32_t HAL_DAC_GetValue(DAC_HandleTypeDef* hdac, uint32_t Channel); /** * @} */ /** @addtogroup DAC_Exported_Functions_Group2 * @{ */ /* Peripheral Control functions ***********************************************/ HAL_StatusTypeDef HAL_DAC_ConfigChannel(DAC_HandleTypeDef* hdac, DAC_ChannelConfTypeDef* sConfig, uint32_t Channel); /** * @} */ /** @addtogroup DAC_Exported_Functions_Group2 * @{ */ /* Peripheral State functions ***************************************************/ HAL_DAC_StateTypeDef HAL_DAC_GetState(DAC_HandleTypeDef* hdac); void HAL_DAC_IRQHandler(DAC_HandleTypeDef* hdac); uint32_t HAL_DAC_GetError(DAC_HandleTypeDef *hdac); void HAL_DAC_ConvCpltCallbackCh1(DAC_HandleTypeDef* hdac); void HAL_DAC_ConvHalfCpltCallbackCh1(DAC_HandleTypeDef* hdac); void HAL_DAC_ErrorCallbackCh1(DAC_HandleTypeDef *hdac); void HAL_DAC_DMAUnderrunCallbackCh1(DAC_HandleTypeDef *hdac); /** * @} */ /** * @} */ /** * @} */ /** * @} */ #ifdef __cplusplus } #endif #endif /*__STM32L1xx_HAL_DAC_H */ /************************ (C) COPYRIGHT STMicroelectronics *****END OF FILE****/ ================================================ FILE: Zelig/mbed/TARGET_NUCLEO_L152RE/stm32l1xx_hal_dac_ex.h ================================================ /** ****************************************************************************** * @file stm32l1xx_hal_dac_ex.h * @author MCD Application Team * @version V1.0.0 * @date 5-September-2014 * @brief Header file of DAC HAL Extension module. ****************************************************************************** * @attention * *

© COPYRIGHT(c) 2014 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. * ****************************************************************************** */ /* Define to prevent recursive inclusion -------------------------------------*/ #ifndef __STM32L1xx_HAL_DAC_EX_H #define __STM32L1xx_HAL_DAC_EX_H #ifdef __cplusplus extern "C" { #endif /* Includes ------------------------------------------------------------------*/ #include "stm32l1xx_hal_def.h" /** @addtogroup STM32L1xx_HAL_Driver * @{ */ /** @addtogroup DACEx * @{ */ /* Exported types ------------------------------------------------------------*/ /* Exported constants --------------------------------------------------------*/ /** @defgroup DACEx_Exported_Constants DACEx Exported Constants * @{ */ /** @defgroup DACEx_wave_generation DACEx wave generation * @{ */ #define DAC_WAVEGENERATION_NONE ((uint32_t)0x00000000) #define DAC_WAVEGENERATION_NOISE ((uint32_t)DAC_CR_WAVE1_0) #define DAC_WAVEGENERATION_TRIANGLE ((uint32_t)DAC_CR_WAVE1_1) #define IS_DAC_GENERATE_WAVE(WAVE) (((WAVE) == DAC_WAVEGENERATION_NONE) || \ ((WAVE) == DAC_WAVEGENERATION_NOISE) || \ ((WAVE) == DAC_WAVEGENERATION_TRIANGLE)) /** * @} */ /** @defgroup DACEx_lfsrunmask_triangleamplitude DACEx lfsrunmask triangleamplitude * @{ */ #define DAC_LFSRUNMASK_BIT0 ((uint32_t)0x00000000) /*!< Unmask DAC channel LFSR bit0 for noise wave generation */ #define DAC_LFSRUNMASK_BITS1_0 ((uint32_t)DAC_CR_MAMP1_0) /*!< Unmask DAC channel LFSR bit[1:0] for noise wave generation */ #define DAC_LFSRUNMASK_BITS2_0 ((uint32_t)DAC_CR_MAMP1_1) /*!< Unmask DAC channel LFSR bit[2:0] for noise wave generation */ #define DAC_LFSRUNMASK_BITS3_0 ((uint32_t)DAC_CR_MAMP1_1 | DAC_CR_MAMP1_0)/*!< Unmask DAC channel LFSR bit[3:0] for noise wave generation */ #define DAC_LFSRUNMASK_BITS4_0 ((uint32_t)DAC_CR_MAMP1_2) /*!< Unmask DAC channel LFSR bit[4:0] for noise wave generation */ #define DAC_LFSRUNMASK_BITS5_0 ((uint32_t)DAC_CR_MAMP1_2 | DAC_CR_MAMP1_0) /*!< Unmask DAC channel LFSR bit[5:0] for noise wave generation */ #define DAC_LFSRUNMASK_BITS6_0 ((uint32_t)DAC_CR_MAMP1_2 | DAC_CR_MAMP1_1) /*!< Unmask DAC channel LFSR bit[6:0] for noise wave generation */ #define DAC_LFSRUNMASK_BITS7_0 ((uint32_t)DAC_CR_MAMP1_2 | DAC_CR_MAMP1_1 | DAC_CR_MAMP1_0) /*!< Unmask DAC channel LFSR bit[7:0] for noise wave generation */ #define DAC_LFSRUNMASK_BITS8_0 ((uint32_t)DAC_CR_MAMP1_3) /*!< Unmask DAC channel LFSR bit[8:0] for noise wave generation */ #define DAC_LFSRUNMASK_BITS9_0 ((uint32_t)DAC_CR_MAMP1_3 | DAC_CR_MAMP1_0) /*!< Unmask DAC channel LFSR bit[9:0] for noise wave generation */ #define DAC_LFSRUNMASK_BITS10_0 ((uint32_t)DAC_CR_MAMP1_3 | DAC_CR_MAMP1_1) /*!< Unmask DAC channel LFSR bit[10:0] for noise wave generation */ #define DAC_LFSRUNMASK_BITS11_0 ((uint32_t)DAC_CR_MAMP1_3 | DAC_CR_MAMP1_1 | DAC_CR_MAMP1_0) /*!< Unmask DAC channel LFSR bit[11:0] for noise wave generation */ #define DAC_TRIANGLEAMPLITUDE_1 ((uint32_t)0x00000000) /*!< Select max triangle amplitude of 1 */ #define DAC_TRIANGLEAMPLITUDE_3 ((uint32_t)DAC_CR_MAMP1_0) /*!< Select max triangle amplitude of 3 */ #define DAC_TRIANGLEAMPLITUDE_7 ((uint32_t)DAC_CR_MAMP1_1) /*!< Select max triangle amplitude of 7 */ #define DAC_TRIANGLEAMPLITUDE_15 ((uint32_t)DAC_CR_MAMP1_1 | DAC_CR_MAMP1_0) /*!< Select max triangle amplitude of 15 */ #define DAC_TRIANGLEAMPLITUDE_31 ((uint32_t)DAC_CR_MAMP1_2) /*!< Select max triangle amplitude of 31 */ #define DAC_TRIANGLEAMPLITUDE_63 ((uint32_t)DAC_CR_MAMP1_2 | DAC_CR_MAMP1_0) /*!< Select max triangle amplitude of 63 */ #define DAC_TRIANGLEAMPLITUDE_127 ((uint32_t)DAC_CR_MAMP1_2 | DAC_CR_MAMP1_1) /*!< Select max triangle amplitude of 127 */ #define DAC_TRIANGLEAMPLITUDE_255 ((uint32_t)DAC_CR_MAMP1_2 | DAC_CR_MAMP1_1 | DAC_CR_MAMP1_0) /*!< Select max triangle amplitude of 255 */ #define DAC_TRIANGLEAMPLITUDE_511 ((uint32_t)DAC_CR_MAMP1_3) /*!< Select max triangle amplitude of 511 */ #define DAC_TRIANGLEAMPLITUDE_1023 ((uint32_t)DAC_CR_MAMP1_3 | DAC_CR_MAMP1_0) /*!< Select max triangle amplitude of 1023 */ #define DAC_TRIANGLEAMPLITUDE_2047 ((uint32_t)DAC_CR_MAMP1_3 | DAC_CR_MAMP1_1) /*!< Select max triangle amplitude of 2047 */ #define DAC_TRIANGLEAMPLITUDE_4095 ((uint32_t)DAC_CR_MAMP1_3 | DAC_CR_MAMP1_1 | DAC_CR_MAMP1_0) /*!< Select max triangle amplitude of 4095 */ #define IS_DAC_LFSR_UNMASK_TRIANGLE_AMPLITUDE(VALUE) (((VALUE) == DAC_LFSRUNMASK_BIT0) || \ ((VALUE) == DAC_LFSRUNMASK_BITS1_0) || \ ((VALUE) == DAC_LFSRUNMASK_BITS2_0) || \ ((VALUE) == DAC_LFSRUNMASK_BITS3_0) || \ ((VALUE) == DAC_LFSRUNMASK_BITS4_0) || \ ((VALUE) == DAC_LFSRUNMASK_BITS5_0) || \ ((VALUE) == DAC_LFSRUNMASK_BITS6_0) || \ ((VALUE) == DAC_LFSRUNMASK_BITS7_0) || \ ((VALUE) == DAC_LFSRUNMASK_BITS8_0) || \ ((VALUE) == DAC_LFSRUNMASK_BITS9_0) || \ ((VALUE) == DAC_LFSRUNMASK_BITS10_0) || \ ((VALUE) == DAC_LFSRUNMASK_BITS11_0) || \ ((VALUE) == DAC_TRIANGLEAMPLITUDE_1) || \ ((VALUE) == DAC_TRIANGLEAMPLITUDE_3) || \ ((VALUE) == DAC_TRIANGLEAMPLITUDE_7) || \ ((VALUE) == DAC_TRIANGLEAMPLITUDE_15) || \ ((VALUE) == DAC_TRIANGLEAMPLITUDE_31) || \ ((VALUE) == DAC_TRIANGLEAMPLITUDE_63) || \ ((VALUE) == DAC_TRIANGLEAMPLITUDE_127) || \ ((VALUE) == DAC_TRIANGLEAMPLITUDE_255) || \ ((VALUE) == DAC_TRIANGLEAMPLITUDE_511) || \ ((VALUE) == DAC_TRIANGLEAMPLITUDE_1023) || \ ((VALUE) == DAC_TRIANGLEAMPLITUDE_2047) || \ ((VALUE) == DAC_TRIANGLEAMPLITUDE_4095)) /** * @} */ /** @defgroup DACEx_wave_generation DACEx wave generation * @{ */ #define DAC_WAVE_NOISE ((uint32_t)DAC_CR_WAVE1_0) #define DAC_WAVE_TRIANGLE ((uint32_t)DAC_CR_WAVE1_1) #define IS_DAC_WAVE(WAVE) (((WAVE) == DAC_WAVE_NOISE) || \ ((WAVE) == DAC_WAVE_TRIANGLE)) /** * @} */ /** * @} */ /* Exported macro ------------------------------------------------------------*/ /* Exported functions --------------------------------------------------------*/ /** @addtogroup DACEx_Exported_Functions * @{ */ /** @addtogroup DACEx_Exported_Functions_Group1 * @{ */ /* Extension features functions ***********************************************/ uint32_t HAL_DACEx_DualGetValue(DAC_HandleTypeDef* hdac); HAL_StatusTypeDef HAL_DACEx_TriangleWaveGenerate(DAC_HandleTypeDef* hdac, uint32_t Channel, uint32_t Amplitude); HAL_StatusTypeDef HAL_DACEx_NoiseWaveGenerate(DAC_HandleTypeDef* hdac, uint32_t Channel, uint32_t Amplitude); HAL_StatusTypeDef HAL_DACEx_DualSetValue(DAC_HandleTypeDef* hdac, uint32_t Alignment, uint32_t Data1, uint32_t Data2); void HAL_DACEx_ConvCpltCallbackCh2(DAC_HandleTypeDef* hdac); void HAL_DACEx_ConvHalfCpltCallbackCh2(DAC_HandleTypeDef* hdac); void HAL_DACEx_ErrorCallbackCh2(DAC_HandleTypeDef* hdac); void HAL_DACEx_DMAUnderrunCallbackCh2(DAC_HandleTypeDef* hdac); /** * @} */ /** * @} */ /** @addtogroup DACEx_Private_Functions * @{ */ void DAC_DMAConvCpltCh2(DMA_HandleTypeDef *hdma); void DAC_DMAErrorCh2(DMA_HandleTypeDef *hdma); void DAC_DMAHalfConvCpltCh2(DMA_HandleTypeDef *hdma); /** * @} */ /** * @} */ /** * @} */ #ifdef __cplusplus } #endif #endif /*__STM32L1xx_HAL_DAC_EX_H */ /************************ (C) COPYRIGHT STMicroelectronics *****END OF FILE****/ ================================================ FILE: Zelig/mbed/TARGET_NUCLEO_L152RE/stm32l1xx_hal_def.h ================================================ /** ****************************************************************************** * @file stm32l1xx_hal_def.h * @author MCD Application Team * @version V1.0.0 * @date 5-September-2014 * @brief This file contains HAL common defines, enumeration, macros and * structures definitions. ****************************************************************************** * @attention * *

© COPYRIGHT(c) 2014 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. * ****************************************************************************** */ /* Define to prevent recursive inclusion -------------------------------------*/ #ifndef __STM32L1xx_HAL_DEF #define __STM32L1xx_HAL_DEF #ifdef __cplusplus extern "C" { #endif /* Includes ------------------------------------------------------------------*/ #include "stm32l1xx.h" /* Exported types ------------------------------------------------------------*/ /** * @brief HAL Status structures definition */ typedef enum { HAL_OK = 0x00, HAL_ERROR = 0x01, HAL_BUSY = 0x02, HAL_TIMEOUT = 0x03 } HAL_StatusTypeDef; /** * @brief HAL Lock structures definition */ typedef enum { HAL_UNLOCKED = 0x00, HAL_LOCKED = 0x01 } HAL_LockTypeDef; /* Exported macro ------------------------------------------------------------*/ #ifndef HAL_NULL #define HAL_NULL (void *) 0 #endif #define HAL_MAX_DELAY 0xFFFFFFFF #define HAL_IS_BIT_SET(REG, BIT) (((REG) & (BIT)) != RESET) #define HAL_IS_BIT_CLR(REG, BIT) (((REG) & (BIT)) == RESET) #define __HAL_LINKDMA(__HANDLE__, __PPP_DMA_FIELD_, __DMA_HANDLE_) \ do{ \ (__HANDLE__)->__PPP_DMA_FIELD_ = &(__DMA_HANDLE_); \ (__DMA_HANDLE_).Parent = (__HANDLE__); \ } while(0) /** @brief Reset the Handle's State field. * @param __HANDLE__: specifies the Peripheral Handle. * @note This macro can be used for the following purpose: * - When the Handle is declared as local variable; before passing it as parameter * to HAL_PPP_Init() for the first time, it is mandatory to use this macro * to set to 0 the Handle's "State" field. * Otherwise, "State" field may have any random value and the first time the function * HAL_PPP_Init() is called, the low level hardware initialization will be missed * (i.e. HAL_PPP_MspInit() will not be executed). * - When there is a need to reconfigure the low level hardware: instead of calling * HAL_PPP_DeInit() then HAL_PPP_Init(), user can make a call to this macro then HAL_PPP_Init(). * In this later function, when the Handle's "State" field is set to 0, it will execute the function * HAL_PPP_MspInit() which will reconfigure the low level hardware. * @retval None */ #define __HAL_RESET_HANDLE_STATE(__HANDLE__) ((__HANDLE__)->State = 0) #if (USE_RTOS == 1) #error " USE_RTOS should be 0 in the current HAL release " #else #define __HAL_LOCK(__HANDLE__) \ do{ \ if((__HANDLE__)->Lock == HAL_LOCKED) \ { \ return HAL_BUSY; \ } \ else \ { \ (__HANDLE__)->Lock = HAL_LOCKED; \ } \ }while (0) #define __HAL_UNLOCK(__HANDLE__) \ do{ \ (__HANDLE__)->Lock = HAL_UNLOCKED; \ }while (0) #endif /* USE_RTOS */ #if defined ( __GNUC__ ) #ifndef __weak #define __weak __attribute__((weak)) #endif /* __weak */ #ifndef __packed #define __packed __attribute__((__packed__)) #endif /* __packed */ #endif /* __GNUC__ */ /* Macro to get variable aligned on 4-bytes, for __ICCARM__ the directive "#pragma data_alignment=4" must be used instead */ #if defined (__GNUC__) /* GNU Compiler */ #ifndef __ALIGN_END #define __ALIGN_END __attribute__ ((aligned (4))) #endif /* __ALIGN_END */ #ifndef __ALIGN_BEGIN #define __ALIGN_BEGIN #endif /* __ALIGN_BEGIN */ #else #ifndef __ALIGN_END #define __ALIGN_END #endif /* __ALIGN_END */ #ifndef __ALIGN_BEGIN #if defined (__CC_ARM) /* ARM Compiler */ #define __ALIGN_BEGIN __align(4) #elif defined (__ICCARM__) /* IAR Compiler */ #define __ALIGN_BEGIN #endif /* __CC_ARM */ #endif /* __ALIGN_BEGIN */ #endif /* __GNUC__ */ /** * @brief __RAM_FUNC definition */ #if defined ( __CC_ARM ) /* ARM Compiler ------------ RAM functions are defined using the toolchain options. Functions that are executed in RAM should reside in a separate source module. Using the 'Options for File' dialog you can simply change the 'Code / Const' area of a module to a memory space in physical RAM. Available memory areas are declared in the 'Target' tab of the 'Options for Target' dialog. */ #define __RAM_FUNC HAL_StatusTypeDef #elif defined ( __ICCARM__ ) /* ICCARM Compiler --------------- RAM functions are defined using a specific toolchain keyword "__ramfunc". */ #define __RAM_FUNC __ramfunc HAL_StatusTypeDef #elif defined ( __GNUC__ ) /* GNU Compiler ------------ RAM functions are defined using a specific toolchain attribute "__attribute__((section(".RamFunc")))". */ #define __RAM_FUNC HAL_StatusTypeDef __attribute__((section(".RamFunc"))) #endif #ifdef __cplusplus } #endif #endif /* ___STM32L1xx_HAL_DEF */ /************************ (C) COPYRIGHT STMicroelectronics *****END OF FILE****/ ================================================ FILE: Zelig/mbed/TARGET_NUCLEO_L152RE/stm32l1xx_hal_dma.h ================================================ /** ****************************************************************************** * @file stm32l1xx_hal_dma.h * @author MCD Application Team * @version V1.0.0 * @date 5-September-2014 * @brief Header file of DMA HAL module. ****************************************************************************** * @attention * *

© COPYRIGHT(c) 2014 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. * ****************************************************************************** */ /* Define to prevent recursive inclusion -------------------------------------*/ #ifndef __STM32L1xx_HAL_DMA_H #define __STM32L1xx_HAL_DMA_H #ifdef __cplusplus extern "C" { #endif /* Includes ------------------------------------------------------------------*/ #include "stm32l1xx_hal_def.h" /** @addtogroup STM32L1xx_HAL_Driver * @{ */ /** @addtogroup DMA * @{ */ /* Exported types ------------------------------------------------------------*/ /** @defgroup DMA_Exported_Types DMA Exported Types * @{ */ /** * @brief DMA Configuration Structure definition */ typedef struct { uint32_t Direction; /*!< Specifies if the data will be transferred from memory to peripheral, from memory to memory or from peripheral to memory. This parameter can be a value of @ref DMA_Data_transfer_direction */ uint32_t PeriphInc; /*!< Specifies whether the Peripheral address register should be incremented or not. This parameter can be a value of @ref DMA_Peripheral_incremented_mode */ uint32_t MemInc; /*!< Specifies whether the memory address register should be incremented or not. This parameter can be a value of @ref DMA_Memory_incremented_mode */ uint32_t PeriphDataAlignment; /*!< Specifies the Peripheral data width. This parameter can be a value of @ref DMA_Peripheral_data_size */ uint32_t MemDataAlignment; /*!< Specifies the Memory data width. This parameter can be a value of @ref DMA_Memory_data_size */ uint32_t Mode; /*!< Specifies the operation mode of the DMAy Channelx. This parameter can be a value of @ref DMA_mode @note The circular buffer mode cannot be used if the memory-to-memory data transfer is configured on the selected Channel */ uint32_t Priority; /*!< Specifies the software priority for the DMAy Channelx. This parameter can be a value of @ref DMA_Priority_level */ } DMA_InitTypeDef; /** * @brief DMA Configuration enumeration values definition */ typedef enum { DMA_MODE = 0, /*!< Control related DMA mode Parameter in DMA_InitTypeDef */ DMA_PRIORITY = 1, /*!< Control related priority level Parameter in DMA_InitTypeDef */ } DMA_ControlTypeDef; /** * @brief HAL DMA State structures definition */ typedef enum { HAL_DMA_STATE_RESET = 0x00, /*!< DMA not yet initialized or disabled */ HAL_DMA_STATE_READY = 0x01, /*!< DMA process success and ready for use */ HAL_DMA_STATE_READY_HALF = 0x11, /*!< DMA Half process success */ HAL_DMA_STATE_BUSY = 0x02, /*!< DMA process is ongoing */ HAL_DMA_STATE_TIMEOUT = 0x03, /*!< DMA timeout state */ HAL_DMA_STATE_ERROR = 0x04, /*!< DMA error state */ }HAL_DMA_StateTypeDef; /** * @brief HAL DMA Error Code structure definition */ typedef enum { HAL_DMA_FULL_TRANSFER = 0x00, /*!< Full transfer */ HAL_DMA_HALF_TRANSFER = 0x01, /*!< Half Transfer */ }HAL_DMA_LevelCompleteTypeDef; /** * @brief DMA handle Structure definition */ typedef struct __DMA_HandleTypeDef { DMA_Channel_TypeDef *Instance; /*!< Register base address */ DMA_InitTypeDef Init; /*!< DMA communication parameters */ HAL_LockTypeDef Lock; /*!< DMA locking object */ HAL_DMA_StateTypeDef State; /*!< DMA transfer state */ void *Parent; /*!< Parent object state */ void (* XferCpltCallback)( struct __DMA_HandleTypeDef * hdma); /*!< DMA transfer complete callback */ void (* XferHalfCpltCallback)( struct __DMA_HandleTypeDef * hdma); /*!< DMA Half transfer complete callback */ void (* XferErrorCallback)( struct __DMA_HandleTypeDef * hdma); /*!< DMA transfer error callback */ __IO uint32_t ErrorCode; /*!< DMA Error code */ } DMA_HandleTypeDef; /** * @} */ /* Exported constants --------------------------------------------------------*/ /** @defgroup DMA_Exported_Constants DMA Exported Constants * @{ */ /** @defgroup DMA_Error_Code DMA_Error_Code * @{ */ #define HAL_DMA_ERROR_NONE ((uint32_t)0x00000000) /*!< No error */ #define HAL_DMA_ERROR_TE ((uint32_t)0x00000001) /*!< Transfer error */ #define HAL_DMA_ERROR_TIMEOUT ((uint32_t)0x00000020) /*!< Timeout error */ /** * @} */ /** @defgroup DMA_Data_transfer_direction DMA_Data_transfer_direction * @{ */ #define DMA_PERIPH_TO_MEMORY ((uint32_t)0x00000000) /*!< Peripheral to memory direction */ #define DMA_MEMORY_TO_PERIPH ((uint32_t)DMA_CCR_DIR) /*!< Memory to peripheral direction */ #define DMA_MEMORY_TO_MEMORY ((uint32_t)(DMA_CCR_MEM2MEM)) /*!< Memory to memory direction */ #define IS_DMA_DIRECTION(DIRECTION) (((DIRECTION) == DMA_PERIPH_TO_MEMORY ) || \ ((DIRECTION) == DMA_MEMORY_TO_PERIPH) || \ ((DIRECTION) == DMA_MEMORY_TO_MEMORY)) /** * @} */ /** @defgroup DMA_Data_buffer_size DMA_Data_buffer_size * @{ */ #define IS_DMA_BUFFER_SIZE(SIZE) (((SIZE) >= 0x1) && ((SIZE) < 0x10000)) /** * @} */ /** @defgroup DMA_Peripheral_incremented_mode DMA_Peripheral_incremented_mode * @{ */ #define DMA_PINC_ENABLE ((uint32_t)DMA_CCR_PINC) /*!< Peripheral increment mode Enable */ #define DMA_PINC_DISABLE ((uint32_t)0x00000000) /*!< Peripheral increment mode Disable */ #define IS_DMA_PERIPHERAL_INC_STATE(STATE) (((STATE) == DMA_PINC_ENABLE) || \ ((STATE) == DMA_PINC_DISABLE)) /** * @} */ /** @defgroup DMA_Memory_incremented_mode DMA_Memory_incremented_mode * @{ */ #define DMA_MINC_ENABLE ((uint32_t)DMA_CCR_MINC) /*!< Memory increment mode Enable */ #define DMA_MINC_DISABLE ((uint32_t)0x00000000) /*!< Memory increment mode Disable */ #define IS_DMA_MEMORY_INC_STATE(STATE) (((STATE) == DMA_MINC_ENABLE) || \ ((STATE) == DMA_MINC_DISABLE)) /** * @} */ /** @defgroup DMA_Peripheral_data_size DMA_Peripheral_data_size * @{ */ #define DMA_PDATAALIGN_BYTE ((uint32_t)0x00000000) /*!< Peripheral data alignment : Byte */ #define DMA_PDATAALIGN_HALFWORD ((uint32_t)DMA_CCR_PSIZE_0) /*!< Peripheral data alignment : HalfWord */ #define DMA_PDATAALIGN_WORD ((uint32_t)DMA_CCR_PSIZE_1) /*!< Peripheral data alignment : Word */ #define IS_DMA_PERIPHERAL_DATA_SIZE(SIZE) (((SIZE) == DMA_PDATAALIGN_BYTE) || \ ((SIZE) == DMA_PDATAALIGN_HALFWORD) || \ ((SIZE) == DMA_PDATAALIGN_WORD)) /** * @} */ /** @defgroup DMA_Memory_data_size DMA_Memory_data_size * @{ */ #define DMA_MDATAALIGN_BYTE ((uint32_t)0x00000000) /*!< Memory data alignment : Byte */ #define DMA_MDATAALIGN_HALFWORD ((uint32_t)DMA_CCR_MSIZE_0) /*!< Memory data alignment : HalfWord */ #define DMA_MDATAALIGN_WORD ((uint32_t)DMA_CCR_MSIZE_1) /*!< Memory data alignment : Word */ #define IS_DMA_MEMORY_DATA_SIZE(SIZE) (((SIZE) == DMA_MDATAALIGN_BYTE) || \ ((SIZE) == DMA_MDATAALIGN_HALFWORD) || \ ((SIZE) == DMA_MDATAALIGN_WORD )) /** * @} */ /** @defgroup DMA_mode DMA_mode * @{ */ #define DMA_NORMAL ((uint32_t)0x00000000) /*!< Normal Mode */ #define DMA_CIRCULAR ((uint32_t)DMA_CCR_CIRC) /*!< Circular Mode */ #define IS_DMA_MODE(MODE) (((MODE) == DMA_NORMAL ) || \ ((MODE) == DMA_CIRCULAR)) /** * @} */ /** @defgroup DMA_Priority_level DMA_Priority_level * @{ */ #define DMA_PRIORITY_LOW ((uint32_t)0x00000000) /*!< Priority level : Low */ #define DMA_PRIORITY_MEDIUM ((uint32_t)DMA_CCR_PL_0) /*!< Priority level : Medium */ #define DMA_PRIORITY_HIGH ((uint32_t)DMA_CCR_PL_1) /*!< Priority level : High */ #define DMA_PRIORITY_VERY_HIGH ((uint32_t)DMA_CCR_PL) /*!< Priority level : Very_High */ #define IS_DMA_PRIORITY(PRIORITY) (((PRIORITY) == DMA_PRIORITY_LOW ) || \ ((PRIORITY) == DMA_PRIORITY_MEDIUM) || \ ((PRIORITY) == DMA_PRIORITY_HIGH) || \ ((PRIORITY) == DMA_PRIORITY_VERY_HIGH)) /** * @} */ /** @defgroup DMA_interrupt_enable_definitions DMA_interrupt_enable_definitions * @{ */ #define DMA_IT_TC ((uint32_t)DMA_CCR_TCIE) #define DMA_IT_HT ((uint32_t)DMA_CCR_HTIE) #define DMA_IT_TE ((uint32_t)DMA_CCR_TEIE) /** * @} */ /** @defgroup DMA_flag_definitions DMA_flag_definitions * @{ */ #define DMA_FLAG_GL1 ((uint32_t)0x00000001) #define DMA_FLAG_TC1 ((uint32_t)0x00000002) #define DMA_FLAG_HT1 ((uint32_t)0x00000004) #define DMA_FLAG_TE1 ((uint32_t)0x00000008) #define DMA_FLAG_GL2 ((uint32_t)0x00000010) #define DMA_FLAG_TC2 ((uint32_t)0x00000020) #define DMA_FLAG_HT2 ((uint32_t)0x00000040) #define DMA_FLAG_TE2 ((uint32_t)0x00000080) #define DMA_FLAG_GL3 ((uint32_t)0x00000100) #define DMA_FLAG_TC3 ((uint32_t)0x00000200) #define DMA_FLAG_HT3 ((uint32_t)0x00000400) #define DMA_FLAG_TE3 ((uint32_t)0x00000800) #define DMA_FLAG_GL4 ((uint32_t)0x00001000) #define DMA_FLAG_TC4 ((uint32_t)0x00002000) #define DMA_FLAG_HT4 ((uint32_t)0x00004000) #define DMA_FLAG_TE4 ((uint32_t)0x00008000) #define DMA_FLAG_GL5 ((uint32_t)0x00010000) #define DMA_FLAG_TC5 ((uint32_t)0x00020000) #define DMA_FLAG_HT5 ((uint32_t)0x00040000) #define DMA_FLAG_TE5 ((uint32_t)0x00080000) #define DMA_FLAG_GL6 ((uint32_t)0x00100000) #define DMA_FLAG_TC6 ((uint32_t)0x00200000) #define DMA_FLAG_HT6 ((uint32_t)0x00400000) #define DMA_FLAG_TE6 ((uint32_t)0x00800000) #define DMA_FLAG_GL7 ((uint32_t)0x01000000) #define DMA_FLAG_TC7 ((uint32_t)0x02000000) #define DMA_FLAG_HT7 ((uint32_t)0x04000000) #define DMA_FLAG_TE7 ((uint32_t)0x08000000) /** * @} */ /** * @} */ /* Exported macros -----------------------------------------------------------*/ /** @defgroup DMA_Exported_macros DMA Exported Macros * @{ */ /** @brief Reset DMA handle state * @param __HANDLE__: DMA handle. * @retval None */ #define __HAL_DMA_RESET_HANDLE_STATE(__HANDLE__) ((__HANDLE__)->State = HAL_DMA_STATE_RESET) /** * @brief Enable the specified DMA Channel. * @param __HANDLE__: DMA handle * @retval None. */ #define __HAL_DMA_ENABLE(__HANDLE__) (SET_BIT((__HANDLE__)->Instance->CCR, DMA_CCR_EN)) /** * @brief Disable the specified DMA Channel. * @param __HANDLE__: DMA handle * @retval None. */ #define __HAL_DMA_DISABLE(__HANDLE__) (CLEAR_BIT((__HANDLE__)->Instance->CCR, DMA_CCR_EN)) /* Interrupt & Flag management */ /** * @brief Enables the specified DMA Channel interrupts. * @param __HANDLE__: DMA handle * @param __INTERRUPT__: specifies the DMA interrupt sources to be enabled or disabled. * This parameter can be any combination of the following values: * @arg DMA_IT_TC: Transfer complete interrupt mask * @arg DMA_IT_HT: Half transfer complete interrupt mask * @arg DMA_IT_TE: Transfer error interrupt mask * @retval None */ #define __HAL_DMA_ENABLE_IT(__HANDLE__, __INTERRUPT__) (SET_BIT((__HANDLE__)->Instance->CCR, (__INTERRUPT__))) /** * @brief Disables the specified DMA Channel interrupts. * @param __HANDLE__: DMA handle * @param __INTERRUPT__: specifies the DMA interrupt sources to be enabled or disabled. * This parameter can be any combination of the following values: * @arg DMA_IT_TC: Transfer complete interrupt mask * @arg DMA_IT_HT: Half transfer complete interrupt mask * @arg DMA_IT_TE: Transfer error interrupt mask * @retval None */ #define __HAL_DMA_DISABLE_IT(__HANDLE__, __INTERRUPT__) (CLEAR_BIT((__HANDLE__)->Instance->CCR , (__INTERRUPT__))) /** * @brief Checks whether the specified DMA Channel interrupt has occurred or not. * @param __HANDLE__: DMA handle * @param __INTERRUPT__: specifies the DMA interrupt source to check. * This parameter can be one of the following values: * @arg DMA_IT_TC: Transfer complete interrupt mask * @arg DMA_IT_HT: Half transfer complete interrupt mask * @arg DMA_IT_TE: Transfer error interrupt mask * @retval The state of DMA_IT (SET or RESET). */ #define __HAL_DMA_GET_IT_SOURCE(__HANDLE__, __INTERRUPT__) ((((__HANDLE__)->Instance->CCR & (__INTERRUPT__)) == (__INTERRUPT__)) ? SET : RESET) /** * @} */ /* Include DMA HAL Extension module */ #include "stm32l1xx_hal_dma_ex.h" /* Exported functions --------------------------------------------------------*/ /** @addtogroup DMA_Exported_Functions * @{ */ /* Initialization and de-initialization functions *****************************/ HAL_StatusTypeDef HAL_DMA_Init(DMA_HandleTypeDef *hdma); HAL_StatusTypeDef HAL_DMA_DeInit (DMA_HandleTypeDef *hdma); /* IO operation functions *****************************************************/ HAL_StatusTypeDef HAL_DMA_Start (DMA_HandleTypeDef *hdma, uint32_t SrcAddress, uint32_t DstAddress, uint32_t DataLength); HAL_StatusTypeDef HAL_DMA_Start_IT(DMA_HandleTypeDef *hdma, uint32_t SrcAddress, uint32_t DstAddress, uint32_t DataLength); HAL_StatusTypeDef HAL_DMA_Abort(DMA_HandleTypeDef *hdma); HAL_StatusTypeDef HAL_DMA_PollForTransfer(DMA_HandleTypeDef *hdma, uint32_t CompleteLevel, uint32_t Timeout); void HAL_DMA_IRQHandler(DMA_HandleTypeDef *hdma); /* Peripheral State and Error functions ***************************************/ HAL_DMA_StateTypeDef HAL_DMA_GetState(DMA_HandleTypeDef *hdma); uint32_t HAL_DMA_GetError(DMA_HandleTypeDef *hdma); /** * @} */ /** * @} */ /** * @} */ #ifdef __cplusplus } #endif #endif /* __STM32L1xx_HAL_DMA_H */ /************************ (C) COPYRIGHT STMicroelectronics *****END OF FILE****/ ================================================ FILE: Zelig/mbed/TARGET_NUCLEO_L152RE/stm32l1xx_hal_dma_ex.h ================================================ /** ****************************************************************************** * @file stm32l1xx_hal_dma_ex.h * @author MCD Application Team * @version V1.0.0 * @date 5-September-2014 * @brief Header file of DMA HAL extension module. ****************************************************************************** * @attention * *

© COPYRIGHT(c) 2014 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. * ****************************************************************************** */ /* Define to prevent recursive inclusion -------------------------------------*/ #ifndef __STM32L1xx_HAL_DMA_EX_H #define __STM32L1xx_HAL_DMA_EX_H #ifdef __cplusplus extern "C" { #endif /* Includes ------------------------------------------------------------------*/ #include "stm32l1xx_hal_def.h" /** @addtogroup STM32L1xx_HAL_Driver * @{ */ /** @addtogroup DMAEx * @{ */ /* Exported types ------------------------------------------------------------*/ /* Exported constants --------------------------------------------------------*/ /* Exported macro ------------------------------------------------------------*/ /** @defgroup DMAEx_Exported_Macros DMAEx Exported Macros * @{ */ /* Interrupt & Flag management */ #if defined(STM32L100xC) || defined (STM32L151xC) || defined (STM32L152xC) || defined (STM32L162xC) || \ defined(STM32L151xCA) || defined (STM32L151xD) || defined (STM32L152xCA) || defined (STM32L152xD) || defined (STM32L162xCA) || defined (STM32L162xD) || \ defined(STM32L151xE) || defined (STM32L152xE) || defined (STM32L162xE) /** * @brief Returns the current DMA Channel transfer complete flag. * @param __HANDLE__: DMA handle * @retval The specified transfer complete flag index. */ #define __HAL_DMA_GET_TC_FLAG_INDEX(__HANDLE__) \ (((uint32_t)((__HANDLE__)->Instance) == ((uint32_t)DMA1_Channel1))? DMA_FLAG_TC1 :\ ((uint32_t)((__HANDLE__)->Instance) == ((uint32_t)DMA1_Channel2))? DMA_FLAG_TC2 :\ ((uint32_t)((__HANDLE__)->Instance) == ((uint32_t)DMA1_Channel3))? DMA_FLAG_TC3 :\ ((uint32_t)((__HANDLE__)->Instance) == ((uint32_t)DMA1_Channel4))? DMA_FLAG_TC4 :\ ((uint32_t)((__HANDLE__)->Instance) == ((uint32_t)DMA1_Channel5))? DMA_FLAG_TC5 :\ ((uint32_t)((__HANDLE__)->Instance) == ((uint32_t)DMA1_Channel6))? DMA_FLAG_TC6 :\ ((uint32_t)((__HANDLE__)->Instance) == ((uint32_t)DMA1_Channel7))? DMA_FLAG_TC7 :\ ((uint32_t)((__HANDLE__)->Instance) == ((uint32_t)DMA2_Channel1))? DMA_FLAG_TC1 :\ ((uint32_t)((__HANDLE__)->Instance) == ((uint32_t)DMA2_Channel2))? DMA_FLAG_TC2 :\ ((uint32_t)((__HANDLE__)->Instance) == ((uint32_t)DMA2_Channel3))? DMA_FLAG_TC3 :\ ((uint32_t)((__HANDLE__)->Instance) == ((uint32_t)DMA2_Channel4))? DMA_FLAG_TC4 :\ DMA_FLAG_TC5) /** * @brief Returns the current DMA Channel half transfer complete flag. * @param __HANDLE__: DMA handle * @retval The specified half transfer complete flag index. */ #define __HAL_DMA_GET_HT_FLAG_INDEX(__HANDLE__)\ (((uint32_t)((__HANDLE__)->Instance) == ((uint32_t)DMA1_Channel1))? DMA_FLAG_HT1 :\ ((uint32_t)((__HANDLE__)->Instance) == ((uint32_t)DMA1_Channel2))? DMA_FLAG_HT2 :\ ((uint32_t)((__HANDLE__)->Instance) == ((uint32_t)DMA1_Channel3))? DMA_FLAG_HT3 :\ ((uint32_t)((__HANDLE__)->Instance) == ((uint32_t)DMA1_Channel4))? DMA_FLAG_HT4 :\ ((uint32_t)((__HANDLE__)->Instance) == ((uint32_t)DMA1_Channel5))? DMA_FLAG_HT5 :\ ((uint32_t)((__HANDLE__)->Instance) == ((uint32_t)DMA1_Channel6))? DMA_FLAG_HT6 :\ ((uint32_t)((__HANDLE__)->Instance) == ((uint32_t)DMA1_Channel7))? DMA_FLAG_HT7 :\ ((uint32_t)((__HANDLE__)->Instance) == ((uint32_t)DMA2_Channel1))? DMA_FLAG_HT1 :\ ((uint32_t)((__HANDLE__)->Instance) == ((uint32_t)DMA2_Channel2))? DMA_FLAG_HT2 :\ ((uint32_t)((__HANDLE__)->Instance) == ((uint32_t)DMA2_Channel3))? DMA_FLAG_HT3 :\ ((uint32_t)((__HANDLE__)->Instance) == ((uint32_t)DMA2_Channel4))? DMA_FLAG_HT4 :\ DMA_FLAG_HT5) /** * @brief Returns the current DMA Channel transfer error flag. * @param __HANDLE__: DMA handle * @retval The specified transfer error flag index. */ #define __HAL_DMA_GET_TE_FLAG_INDEX(__HANDLE__)\ (((uint32_t)((__HANDLE__)->Instance) == ((uint32_t)DMA1_Channel1))? DMA_FLAG_TE1 :\ ((uint32_t)((__HANDLE__)->Instance) == ((uint32_t)DMA1_Channel2))? DMA_FLAG_TE2 :\ ((uint32_t)((__HANDLE__)->Instance) == ((uint32_t)DMA1_Channel3))? DMA_FLAG_TE3 :\ ((uint32_t)((__HANDLE__)->Instance) == ((uint32_t)DMA1_Channel4))? DMA_FLAG_TE4 :\ ((uint32_t)((__HANDLE__)->Instance) == ((uint32_t)DMA1_Channel5))? DMA_FLAG_TE5 :\ ((uint32_t)((__HANDLE__)->Instance) == ((uint32_t)DMA1_Channel6))? DMA_FLAG_TE6 :\ ((uint32_t)((__HANDLE__)->Instance) == ((uint32_t)DMA1_Channel7))? DMA_FLAG_TE7 :\ ((uint32_t)((__HANDLE__)->Instance) == ((uint32_t)DMA2_Channel1))? DMA_FLAG_TE1 :\ ((uint32_t)((__HANDLE__)->Instance) == ((uint32_t)DMA2_Channel2))? DMA_FLAG_TE2 :\ ((uint32_t)((__HANDLE__)->Instance) == ((uint32_t)DMA2_Channel3))? DMA_FLAG_TE3 :\ ((uint32_t)((__HANDLE__)->Instance) == ((uint32_t)DMA2_Channel4))? DMA_FLAG_TE4 :\ DMA_FLAG_TE5) /** * @brief Get the DMA Channel pending flags. * @param __HANDLE__: DMA handle * @param __FLAG__: Get the specified flag. * This parameter can be any combination of the following values: * @arg DMA_FLAG_TCx: Transfer complete flag * @arg DMA_FLAG_HTx: Half transfer complete flag * @arg DMA_FLAG_TEx: Transfer error flag * Where x can be 1_7 or 1_5 to select the DMA Channel flag. * @retval The state of FLAG (SET or RESET). */ #define __HAL_DMA_GET_FLAG(__HANDLE__, __FLAG__)\ (((uint32_t)((__HANDLE__)->Instance) > (uint32_t)DMA1_Channel7)? (DMA2->ISR & (__FLAG__)) :\ (DMA1->ISR & (__FLAG__))) /** * @brief Clears the DMA Channel pending flags. * @param __HANDLE__: DMA handle * @param __FLAG__: specifies the flag to clear. * This parameter can be any combination of the following values: * @arg DMA_FLAG_TCx: Transfer complete flag * @arg DMA_FLAG_HTx: Half transfer complete flag * @arg DMA_FLAG_TEx: Transfer error flag * Where x can be 1_7 or 1_5 to select the DMA Channel flag. * @retval None */ #define __HAL_DMA_CLEAR_FLAG(__HANDLE__, __FLAG__) \ (((uint32_t)((__HANDLE__)->Instance) > (uint32_t)DMA1_Channel7)? (DMA2->IFCR = (__FLAG__)) :\ (DMA1->IFCR = (__FLAG__))) #else /** * @brief Returns the current DMA Channel transfer complete flag. * @param __HANDLE__: DMA handle * @retval The specified transfer complete flag index. */ #define __HAL_DMA_GET_TC_FLAG_INDEX(__HANDLE__) \ (((uint32_t)((__HANDLE__)->Instance) == ((uint32_t)DMA1_Channel1))? DMA_FLAG_TC1 :\ ((uint32_t)((__HANDLE__)->Instance) == ((uint32_t)DMA1_Channel2))? DMA_FLAG_TC2 :\ ((uint32_t)((__HANDLE__)->Instance) == ((uint32_t)DMA1_Channel3))? DMA_FLAG_TC3 :\ ((uint32_t)((__HANDLE__)->Instance) == ((uint32_t)DMA1_Channel4))? DMA_FLAG_TC4 :\ ((uint32_t)((__HANDLE__)->Instance) == ((uint32_t)DMA1_Channel5))? DMA_FLAG_TC5 :\ ((uint32_t)((__HANDLE__)->Instance) == ((uint32_t)DMA1_Channel6))? DMA_FLAG_TC6 :\ DMA_FLAG_TC7) /** * @brief Returns the current DMA Channel half transfer complete flag. * @param __HANDLE__: DMA handle * @retval The specified half transfer complete flag index. */ #define __HAL_DMA_GET_HT_FLAG_INDEX(__HANDLE__)\ (((uint32_t)((__HANDLE__)->Instance) == ((uint32_t)DMA1_Channel1))? DMA_FLAG_HT1 :\ ((uint32_t)((__HANDLE__)->Instance) == ((uint32_t)DMA1_Channel2))? DMA_FLAG_HT2 :\ ((uint32_t)((__HANDLE__)->Instance) == ((uint32_t)DMA1_Channel3))? DMA_FLAG_HT3 :\ ((uint32_t)((__HANDLE__)->Instance) == ((uint32_t)DMA1_Channel4))? DMA_FLAG_HT4 :\ ((uint32_t)((__HANDLE__)->Instance) == ((uint32_t)DMA1_Channel5))? DMA_FLAG_HT5 :\ ((uint32_t)((__HANDLE__)->Instance) == ((uint32_t)DMA1_Channel6))? DMA_FLAG_HT6 :\ DMA_FLAG_HT7) /** * @brief Returns the current DMA Channel transfer error flag. * @param __HANDLE__: DMA handle * @retval The specified transfer error flag index. */ #define __HAL_DMA_GET_TE_FLAG_INDEX(__HANDLE__)\ (((uint32_t)((__HANDLE__)->Instance) == ((uint32_t)DMA1_Channel1))? DMA_FLAG_TE1 :\ ((uint32_t)((__HANDLE__)->Instance) == ((uint32_t)DMA1_Channel2))? DMA_FLAG_TE2 :\ ((uint32_t)((__HANDLE__)->Instance) == ((uint32_t)DMA1_Channel3))? DMA_FLAG_TE3 :\ ((uint32_t)((__HANDLE__)->Instance) == ((uint32_t)DMA1_Channel4))? DMA_FLAG_TE4 :\ ((uint32_t)((__HANDLE__)->Instance) == ((uint32_t)DMA1_Channel5))? DMA_FLAG_TE5 :\ ((uint32_t)((__HANDLE__)->Instance) == ((uint32_t)DMA1_Channel6))? DMA_FLAG_TE6 :\ DMA_FLAG_TE7) /** * @brief Get the DMA Channel pending flags. * @param __HANDLE__: DMA handle * @param __FLAG__: Get the specified flag. * This parameter can be any combination of the following values: * @arg DMA_FLAG_TCx: Transfer complete flag * @arg DMA_FLAG_HTx: Half transfer complete flag * @arg DMA_FLAG_TEx: Transfer error flag * Where x can be 1_7 to select the DMA Channel flag. * @retval The state of FLAG (SET or RESET). */ #define __HAL_DMA_GET_FLAG(__HANDLE__, __FLAG__) (DMA1->ISR & (__FLAG__)) /** * @brief Clears the DMA Channel pending flags. * @param __HANDLE__: DMA handle * @param __FLAG__: specifies the flag to clear. * This parameter can be any combination of the following values: * @arg DMA_FLAG_TCx: Transfer complete flag * @arg DMA_FLAG_HTx: Half transfer complete flag * @arg DMA_FLAG_TEx: Transfer error flag * Where x can be 1_7 to select the DMA Channel flag. * @retval None */ #define __HAL_DMA_CLEAR_FLAG(__HANDLE__, __FLAG__) (DMA1->IFCR = (__FLAG__)) #endif /* STM32L100xC || STM32L151xC || STM32L152xC || STM32L162xC || STM32L151xCA) || defined (STM32L151xD) || defined (STM32L152xCA) || defined (STM32L152xD) || defined (STM32L162xCA) || defined (STM32L162xD) || STM32L151xE || STM32L152xE || STM32L162xE */ /** * @} */ /** * @} */ /** * @} */ #ifdef __cplusplus } #endif #endif /* __STM32L1xx_HAL_DMA_EX_H */ /************************ (C) COPYRIGHT STMicroelectronics *****END OF FILE****/ ================================================ FILE: Zelig/mbed/TARGET_NUCLEO_L152RE/stm32l1xx_hal_flash.h ================================================ /** ****************************************************************************** * @file stm32l1xx_hal_flash.h * @author MCD Application Team * @version V1.0.0 * @date 5-September-2014 * @brief Header file of Flash HAL module. ****************************************************************************** * @attention * *

© COPYRIGHT(c) 2014 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. * ****************************************************************************** */ /* Define to prevent recursive inclusion -------------------------------------*/ #ifndef __STM32L1xx_HAL_FLASH_H #define __STM32L1xx_HAL_FLASH_H #ifdef __cplusplus extern "C" { #endif /* Includes ------------------------------------------------------------------*/ #include "stm32l1xx_hal_def.h" /** @addtogroup STM32L1xx_HAL_Driver * @{ */ /** @addtogroup FLASH * @{ */ /* Exported types ------------------------------------------------------------*/ /** @defgroup FLASH_Exported_Types FLASH Exported Types * @{ */ /** * @brief FLASH Error structure definition */ typedef enum { FLASH_ERROR_SIZE = 0x01, FLASH_ERROR_OPTV = 0x02, FLASH_ERROR_OPTVUSR = 0x04, FLASH_ERROR_PGA = 0x08, FLASH_ERROR_WRP = 0x10, FLASH_ERROR_RD = 0x20, FLASH_ERROR_OPERATION = 0x40 }FLASH_ErrorTypeDef; /** * @brief FLASH Procedure structure definition */ typedef enum { FLASH_PROC_NONE = 0, FLASH_PROC_PAGEERASE, FLASH_PROC_PROGRAM } FLASH_ProcedureTypeDef; /** * @brief FLASH handle Structure definition */ typedef struct { __IO FLASH_ProcedureTypeDef ProcedureOnGoing; /*Internal variable to indicate which procedure is ongoing or not in IT context*/ __IO uint32_t NbPagesToErase; /*Internal variable to save the remaining sectors to erase in IT context*/ __IO uint32_t Page; /*Internal variable to define the current sector which is erasing*/ __IO uint32_t Address; /*Internal variable to save address selected for program*/ HAL_LockTypeDef Lock; /* FLASH locking object */ __IO FLASH_ErrorTypeDef ErrorCode; /* FLASH error code */ }FLASH_ProcessTypeDef; /** * @} */ /** @addtogroup FLASH_Internal_Variables * @{ */ /** * @brief Variable used for Program/Erase sectors under interruption. * Put as extern as used also in flash_ex.c. */ extern FLASH_ProcessTypeDef ProcFlash; /** * @} */ /* Exported constants --------------------------------------------------------*/ /** @defgroup FLASH_Exported_Constants FLASH Exported Constants * @{ */ #define HAL_FLASH_TIMEOUT_VALUE ((uint32_t)50000) /* 50 s */ #define FLASH_PAGE_SIZE ((uint32_t)256) /** @defgroup FLASH_Type_Program FLASH Type Program * @{ */ #define TYPEPROGRAM_WORD ((uint32_t)0x02) /*!< Program a word (32-bit) at a specified address */ #define IS_TYPEPROGRAMFLASH(_VALUE_) (((_VALUE_) == TYPEPROGRAM_WORD)) /** * @} */ /** @defgroup FLASH_Latency FLASH Latency * @{ */ #define FLASH_LATENCY_0 ((uint8_t)0x00) /*!< FLASH Zero Latency cycle */ #define FLASH_LATENCY_1 ((uint8_t)0x01) /*!< FLASH One Latency cycle */ #define IS_FLASH_LATENCY(__LATENCY__) (((__LATENCY__) == FLASH_LATENCY_0) || \ ((__LATENCY__) == FLASH_LATENCY_1)) /** * @} */ /** @defgroup FLASH_Interrupts FLASH Interrupts * @{ */ #define FLASH_IT_EOP FLASH_PECR_EOPIE /*!< End of programming interrupt source */ #define FLASH_IT_ERR FLASH_PECR_ERRIE /*!< Error interrupt source */ /** * @} */ /** @defgroup FLASH_Flags FLASH Flags * @{ */ #define FLASH_FLAG_BSY FLASH_SR_BSY /*!< FLASH Busy flag */ #define FLASH_FLAG_EOP FLASH_SR_EOP /*!< FLASH End of Programming flag */ #define FLASH_FLAG_ENDHV FLASH_SR_ENDHV /*!< FLASH End of High Voltage flag */ #define FLASH_FLAG_READY FLASH_SR_READY /*!< FLASH Ready flag after low power mode */ #define FLASH_FLAG_WRPERR FLASH_SR_WRPERR /*!< FLASH Write protected error flag */ #define FLASH_FLAG_PGAERR FLASH_SR_PGAERR /*!< FLASH Programming Alignment error flag */ #define FLASH_FLAG_SIZERR FLASH_SR_SIZERR /*!< FLASH Size error flag */ #define FLASH_FLAG_OPTVERR FLASH_SR_OPTVERR /*!< FLASH Option Validity error flag */ /** * @} */ /** @defgroup FLASH_Keys FLASH Keys * @{ */ #define FLASH_PDKEY1 ((uint32_t)0x04152637) /*!< Flash power down key1 */ #define FLASH_PDKEY2 ((uint32_t)0xFAFBFCFD) /*!< Flash power down key2: used with FLASH_PDKEY1 to unlock the RUN_PD bit in FLASH_ACR */ #define FLASH_PEKEY1 ((uint32_t)0x89ABCDEF) /*!< Flash program erase key1 */ #define FLASH_PEKEY2 ((uint32_t)0x02030405) /*!< Flash program erase key: used with FLASH_PEKEY2 to unlock the write access to the FLASH_PECR register and data EEPROM */ #define FLASH_PRGKEY1 ((uint32_t)0x8C9DAEBF) /*!< Flash program memory key1 */ #define FLASH_PRGKEY2 ((uint32_t)0x13141516) /*!< Flash program memory key2: used with FLASH_PRGKEY2 to unlock the program memory */ #define FLASH_OPTKEY1 ((uint32_t)0xFBEAD9C8) /*!< Flash option key1 */ #define FLASH_OPTKEY2 ((uint32_t)0x24252627) /*!< Flash option key2: used with FLASH_OPTKEY1 to unlock the write access to the option byte block */ /** * @} */ #if defined ( __ICCARM__ ) #define InterruptType_ACTLR_DISMCYCINT_Msk IntType_ACTLR_DISMCYCINT_Msk #endif /** * @} */ /* Exported macro ------------------------------------------------------------*/ /** @defgroup FLASH_Exported_Macros FLASH Exported Macros * @{ */ /** @defgroup FLASH_Interrupt FLASH Interrupts * @brief macros to handle FLASH interrupts * @{ */ /** * @brief Enable the specified FLASH interrupt. * @param __INTERRUPT__ : FLASH interrupt * This parameter can be any combination of the following values: * @arg FLASH_IT_EOP: End of FLASH Operation Interrupt * @arg FLASH_IT_ERR: Error Interrupt * @retval none */ #define __HAL_FLASH_ENABLE_IT(__INTERRUPT__) ((FLASH->PECR) |= (__INTERRUPT__)) /** * @brief Disable the specified FLASH interrupt. * @param __INTERRUPT__ : FLASH interrupt * This parameter can be any combination of the following values: * @arg FLASH_IT_EOP: End of FLASH Operation Interrupt * @arg FLASH_IT_ERR: Error Interrupt * @retval none */ #define __HAL_FLASH_DISABLE_IT(__INTERRUPT__) ((FLASH->PECR) &= ~(uint32_t)(__INTERRUPT__)) /** * @brief Get the specified FLASH flag status. * @param __FLAG__: specifies the FLASH flag to check. * This parameter can be one of the following values: * @arg FLASH_FLAG_BSY : FLASH Busy flag * @arg FLASH_FLAG_EOP : FLASH End of Operation flag * @arg FLASH_FLAG_ENDHV : FLASH End of High Voltage flag * @arg FLASH_FLAG_READY: FLASH Ready flag after low power mode * @arg FLASH_FLAG_WRPERR: FLASH Write protected error flag * @arg FLASH_FLAG_PGAERR: FLASH Programming Alignment error flag * @arg FLASH_FLAG_SIZERR: FLASH Size error flag * @arg FLASH_FLAG_OPTVERR: FLASH Option validity error error flag * @arg FLASH_FLAG_OPTVERRUSR : FLASH Option UserValidity (available only Cat.3, Cat.4 and Cat.5 devices) * @arg FLASH_FLAG_RDERR : FLASH Read Protection error flag (PCROP) (available only Cat.2 and Cat.3 devices) * @retval The new state of __FLAG__ (SET or RESET). */ #define __HAL_FLASH_GET_FLAG(__FLAG__) (((FLASH->SR) & (__FLAG__)) == (__FLAG__)) /** * @brief Clear the specified FLASH flag. * @param __FLAG__: specifies the FLASH flags to clear. * This parameter can be any combination of the following values: * @arg FLASH_FLAG_BSY : FLASH Busy flag * @arg FLASH_FLAG_EOP : FLASH End of Operation flag * @arg FLASH_FLAG_ENDHV : FLASH End of High Voltage flag * @arg FLASH_FLAG_READY: FLASH Ready flag after low power mode * @arg FLASH_FLAG_WRPERR: FLASH Write protected error flag * @arg FLASH_FLAG_PGAERR: FLASH Programming Alignment error flag * @arg FLASH_FLAG_SIZERR: FLASH Size error flag * @arg FLASH_FLAG_OPTVERR: FLASH Option validity error error flag * @arg FLASH_FLAG_OPTVERRUSR : FLASH Option UserValidity (available only Cat.3, Cat.4 and Cat.5 devices) * @arg FLASH_FLAG_RDERR : FLASH Read Protection error flag (PCROP) (available only Cat.2 and Cat.3 devices) * @retval none */ #define __HAL_FLASH_CLEAR_FLAG(__FLAG__) ((FLASH->SR) = (__FLAG__)) /** * @} */ /** * @} */ /* Include FLASH HAL Extension module */ #include "stm32l1xx_hal_flash_ex.h" #include "stm32l1xx_hal_flash_ramfunc.h" /* Exported functions ------------------------------------------------------- */ /** @addtogroup FLASH_Exported_Functions * @{ */ /** @addtogroup FLASH_Exported_Functions_Group1 * @{ */ /** * @brief FLASH memory functions that can be executed from FLASH. */ /* Program operation functions ***********************************************/ HAL_StatusTypeDef HAL_FLASH_Program(uint32_t TypeProgram, uint32_t Address, uint64_t Data); HAL_StatusTypeDef HAL_FLASH_Program_IT(uint32_t TypeProgram, uint32_t Address, uint64_t Data); /* FLASH IRQ handler function */ void HAL_FLASH_IRQHandler(void); /* Callbacks in non blocking modes */ void HAL_FLASH_EndOfOperationCallback(uint32_t ReturnValue); void HAL_FLASH_OperationErrorCallback(uint32_t ReturnValue); /** * @} */ /** @addtogroup FLASH_Exported_Functions_Group2 * @{ */ /* FLASH Memory Programming functions *****************************************/ HAL_StatusTypeDef HAL_FLASH_Unlock(void); HAL_StatusTypeDef HAL_FLASH_Lock(void); /* Option Bytes Programming functions *****************************************/ HAL_StatusTypeDef HAL_FLASH_OB_Unlock(void); HAL_StatusTypeDef HAL_FLASH_OB_Lock(void); HAL_StatusTypeDef HAL_FLASH_OB_Launch(void); /** * @} */ /** @addtogroup FLASH_Exported_Functions_Group3 * @{ */ /* Peripheral State methods **************************************************/ FLASH_ErrorTypeDef HAL_FLASH_GetError(void); /** * @} */ /** * @} */ /** @addtogroup FLASH_Internal_Functions * @{ */ /** * @brief Function used internally by HAL FLASH driver. */ HAL_StatusTypeDef FLASH_WaitForLastOperation(uint32_t Timeout); /** * @} */ /** * @} */ /** * @} */ #ifdef __cplusplus } #endif #endif /* __STM32L1xx_HAL_FLASH_H */ /************************ (C) COPYRIGHT STMicroelectronics *****END OF FILE****/ ================================================ FILE: Zelig/mbed/TARGET_NUCLEO_L152RE/stm32l1xx_hal_flash_ex.h ================================================ /** ****************************************************************************** * @file stm32l1xx_hal_flash.h * @author MCD Application Team * @version V1.0.0 * @date 5-September-2014 * @brief Header file of Flash HAL module. ****************************************************************************** * @attention * *

© COPYRIGHT(c) 2014 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. * ****************************************************************************** */ /* Define to prevent recursive inclusion -------------------------------------*/ #ifndef __STM32L1xx_HAL_FLASH_EX_H #define __STM32L1xx_HAL_FLASH_EX_H #ifdef __cplusplus extern "C" { #endif /* Includes ------------------------------------------------------------------*/ #include "stm32l1xx_hal_def.h" /** @addtogroup STM32L1xx_HAL_Driver * @{ */ /** @addtogroup FLASHEx * @{ */ /* Exported types ------------------------------------------------------------*/ /** @defgroup FLASHEx_Exported_Types FLASHEx Exported Types * @{ */ /** * @brief FLASH Erase structure definition */ typedef struct { uint32_t TypeErase; /*!< TypeErase: Page Erase only. This parameter can be a value of @ref FLASHEx_Type_Erase */ uint32_t PageAddress; /*!< PageAddress: Initial FLASH address to be erased This parameter must be a value belonging to FLASH Programm address (depending on the devices) */ uint32_t NbPages; /*!< NbPages: Number of pages to be erased. This parameter must be a value between 1 and (max number of pages - value of Initial page)*/ } FLASH_EraseInitTypeDef; /** * @brief FLASH Option Bytes PROGRAM structure definition */ typedef struct { uint32_t OptionType; /*!< OptionType: Option byte to be configured. This parameter can be a value of @ref FLASHEx_Option_Type */ uint32_t WRPState; /*!< WRPState: Write protection activation or deactivation. This parameter can be a value of @ref FLASHEx_WRP_State */ uint32_t WRPSector0To31; /*!< WRPSector0To31: specifies the sector(s) which are write protected between Sector 0 to 31 This parameter can be a combination of @ref FLASHEx_Option_Bytes_Write_Protection1 */ #if defined(STM32L100xC) || defined (STM32L151xC) || defined (STM32L152xC) || defined (STM32L162xC) || \ defined(STM32L151xCA) || defined (STM32L151xD) || defined (STM32L152xCA) || defined (STM32L152xD) || defined (STM32L162xCA) || defined (STM32L162xD) || \ defined(STM32L151xE) || defined (STM32L152xE) || defined (STM32L162xE) uint32_t WRPSector32To63; /*!< WRPSector32To63: specifies the sector(s) which are write protected between Sector 32 to 63 This parameter can be a combination of @ref FLASHEx_Option_Bytes_Write_Protection2 */ #endif /* STM32L100xC || STM32L151xC || STM32L152xC || STM32L162xC || STM32L151xCA || STM32L151xD || STM32L152xCA || STM32L152xD || STM32L162xCA || STM32L162xD || STM32L151xE || STM32L152xE || STM32L162xE */ #if defined (STM32L151xD) || defined (STM32L152xD) || defined (STM32L162xD) || \ defined(STM32L151xE) || defined (STM32L152xE) || defined (STM32L162xE) uint32_t WRPSector64To95; /*!< WRPSector64to95: specifies the sector(s) which are write protected between Sector 64 to 95 This parameter can be a combination of @ref FLASHEx_Option_Bytes_Write_Protection3 */ #endif /* STM32L151xD || STM32L152xD || STM32L162xD || STM32L151xE || STM32L152xE || STM32L162xE */ #if defined(STM32L151xE) || defined (STM32L152xE) || defined (STM32L162xE) uint32_t WRPSector96To127; /*!< WRPSector96To127: specifies the sector(s) which are write protected between Sector 96 to 127 This parameter can be a combination of @ref FLASHEx_Option_Bytes_Write_Protection4 */ #endif /* STM32L151xE || STM32L152xE || STM32L162xE */ uint8_t RDPLevel; /*!< RDPLevel: Set the read protection level.. This parameter can be a value of @ref FLASHEx_Option_Bytes_Read_Protection */ uint8_t BORLevel; /*!< BORLevel: Set the BOR Level. This parameter can be a value of @ref FLASHEx_Option_Bytes_BOR_Level */ uint8_t USERConfig; /*!< USERConfig: Program the FLASH User Option Byte: IWDG_SW / RST_STOP / RST_STDBY. This parameter can be a combination of @ref FLASHEx_Option_Bytes_IWatchdog, @ref FLASHEx_Option_Bytes_nRST_STOP and @ref FLASHEx_Option_Bytes_nRST_STDBY*/ } FLASH_OBProgramInitTypeDef; /** * @brief FLASH Advanced Option Bytes Program structure definition */ typedef struct { uint32_t OptionType; /*!< OptionType: Option byte to be configured for extension . This parameter can be a value of @ref FLASHEx_OptionAdv_Type */ #if defined (STM32L151xBA) || defined (STM32L152xBA) || \ defined (STM32L151xC) || defined (STM32L152xC) || defined (STM32L162xC) uint32_t PCROPState; /*!< PCROPState: PCROP activation or deactivation. This parameter can be a value of @ref FLASHEx_PCROP_State */ uint32_t PCROPSector0To31; /*!< PCROPSector0To31: specifies the sector(s) set for PCROP This parameter can be a value of @ref FLASHEx_Option_Bytes_PC_ReadWrite_Protection1 */ #if defined (STM32L151xC) || defined (STM32L152xC) || defined (STM32L162xC) uint32_t PCROPSector32To63; /*!< PCROPSector32To63: specifies the sector(s) set for PCROP This parameter can be a value of @ref FLASHEx_Option_Bytes_PC_ReadWrite_Protection2 */ #endif /* STM32L151xC || STM32L152xC || STM32L162xC */ #endif /* STM32L151xBA || STM32L152xBA || STM32L151xC || STM32L152xC || STM32L162xC */ #if defined(STM32L151xCA) || defined (STM32L151xD) || defined (STM32L152xCA) || defined (STM32L152xD) || defined (STM32L162xCA) || defined (STM32L162xD) || \ defined(STM32L151xE) || defined (STM32L152xE) || defined (STM32L162xE) uint16_t BootConfig; /*!< BootConfig: specifies Option bytes for boot config This parameter can be a value of @ref FLASHEx_Option_Bytes_BOOT */ #endif /* STM32L151xCA || STM32L151xD || STM32L152xCA || STM32L152xD || STM32L162xCA || STM32L162xD || STM32L151xE || STM32L152xE || STM32L162xE*/ } FLASH_AdvOBProgramInitTypeDef; /** * @} */ /* Exported constants --------------------------------------------------------*/ /** @defgroup FLASHEx_Exported_Constants FLASHEx Exported Constants * @{ */ /** @defgroup FLASHEx_Type_Erase FLASHEx_Type_Erase * @{ */ #define TYPEERASE_PAGES ((uint32_t)0x00) /*!= 256KB*/ #define OB_WRP3_PAGES1024TO1039 ((uint32_t)0x00000001) /* Write protection of Sector64 */ #define OB_WRP3_PAGES1040TO1055 ((uint32_t)0x00000002) /* Write protection of Sector65 */ #define OB_WRP3_PAGES1056TO1071 ((uint32_t)0x00000004) /* Write protection of Sector66 */ #define OB_WRP3_PAGES1072TO1087 ((uint32_t)0x00000008) /* Write protection of Sector67 */ #define OB_WRP3_PAGES1088TO1103 ((uint32_t)0x00000010) /* Write protection of Sector68 */ #define OB_WRP3_PAGES1104TO1119 ((uint32_t)0x00000020) /* Write protection of Sector69 */ #define OB_WRP3_PAGES1120TO1135 ((uint32_t)0x00000040) /* Write protection of Sector70 */ #define OB_WRP3_PAGES1136TO1151 ((uint32_t)0x00000080) /* Write protection of Sector71 */ #define OB_WRP3_PAGES1152TO1167 ((uint32_t)0x00000100) /* Write protection of Sector72 */ #define OB_WRP3_PAGES1168TO1183 ((uint32_t)0x00000200) /* Write protection of Sector73 */ #define OB_WRP3_PAGES1184TO1199 ((uint32_t)0x00000400) /* Write protection of Sector74 */ #define OB_WRP3_PAGES1200TO1215 ((uint32_t)0x00000800) /* Write protection of Sector75 */ #define OB_WRP3_PAGES1216TO1231 ((uint32_t)0x00001000) /* Write protection of Sector76 */ #define OB_WRP3_PAGES1232TO1247 ((uint32_t)0x00002000) /* Write protection of Sector77 */ #define OB_WRP3_PAGES1248TO1263 ((uint32_t)0x00004000) /* Write protection of Sector78 */ #define OB_WRP3_PAGES1264TO1279 ((uint32_t)0x00008000) /* Write protection of Sector79 */ #define OB_WRP3_PAGES1280TO1295 ((uint32_t)0x00010000) /* Write protection of Sector80 */ #define OB_WRP3_PAGES1296TO1311 ((uint32_t)0x00020000) /* Write protection of Sector81 */ #define OB_WRP3_PAGES1312TO1327 ((uint32_t)0x00040000) /* Write protection of Sector82 */ #define OB_WRP3_PAGES1328TO1343 ((uint32_t)0x00080000) /* Write protection of Sector83 */ #define OB_WRP3_PAGES1344TO1359 ((uint32_t)0x00100000) /* Write protection of Sector84 */ #define OB_WRP3_PAGES1360TO1375 ((uint32_t)0x00200000) /* Write protection of Sector85 */ #define OB_WRP3_PAGES1376TO1391 ((uint32_t)0x00400000) /* Write protection of Sector86 */ #define OB_WRP3_PAGES1392TO1407 ((uint32_t)0x00800000) /* Write protection of Sector87 */ #define OB_WRP3_PAGES1408TO1423 ((uint32_t)0x01000000) /* Write protection of Sector88 */ #define OB_WRP3_PAGES1424TO1439 ((uint32_t)0x02000000) /* Write protection of Sector89 */ #define OB_WRP3_PAGES1440TO1455 ((uint32_t)0x04000000) /* Write protection of Sector90 */ #define OB_WRP3_PAGES1456TO1471 ((uint32_t)0x08000000) /* Write protection of Sector91 */ #define OB_WRP3_PAGES1472TO1487 ((uint32_t)0x10000000) /* Write protection of Sector92 */ #define OB_WRP3_PAGES1488TO1503 ((uint32_t)0x20000000) /* Write protection of Sector93 */ #define OB_WRP3_PAGES1504TO1519 ((uint32_t)0x40000000) /* Write protection of Sector94 */ #define OB_WRP3_PAGES1520TO1535 ((uint32_t)0x80000000) /* Write protection of Sector95 */ #define OB_WRP3_ALLPAGES ((uint32_t)0xFFFFFFFF) /*!< Write protection of all Sectors */ /** * @} */ #endif /* STM32L151xD || STM32L152xD || STM32L162xD || STM32L151xE || STM32L152xE || STM32L162xE*/ #if defined(STM32L151xE) || defined (STM32L152xE) || defined (STM32L162xE) /** @defgroup FLASHEx_Option_Bytes_Write_Protection4 FLASHEx Option Bytes Write Protection4 * @{ */ /* Pages for Cat5 devices*/ #define OB_WRP4_PAGES1536TO1551 ((uint32_t)0x00000001)/* Write protection of Sector96*/ #define OB_WRP4_PAGES1552TO1567 ((uint32_t)0x00000002)/* Write protection of Sector97*/ #define OB_WRP4_PAGES1568TO1583 ((uint32_t)0x00000004)/* Write protection of Sector98*/ #define OB_WRP4_PAGES1584TO1599 ((uint32_t)0x00000008)/* Write protection of Sector99*/ #define OB_WRP4_PAGES1600TO1615 ((uint32_t)0x00000010) /* Write protection of Sector100*/ #define OB_WRP4_PAGES1616TO1631 ((uint32_t)0x00000020) /* Write protection of Sector101*/ #define OB_WRP4_PAGES1632TO1647 ((uint32_t)0x00000040) /* Write protection of Sector102*/ #define OB_WRP4_PAGES1648TO1663 ((uint32_t)0x00000080) /* Write protection of Sector103*/ #define OB_WRP4_PAGES1664TO1679 ((uint32_t)0x00000100) /* Write protection of Sector104*/ #define OB_WRP4_PAGES1680TO1695 ((uint32_t)0x00000200) /* Write protection of Sector105*/ #define OB_WRP4_PAGES1696TO1711 ((uint32_t)0x00000400) /* Write protection of Sector106*/ #define OB_WRP4_PAGES1712TO1727 ((uint32_t)0x00000800) /* Write protection of Sector107*/ #define OB_WRP4_PAGES1728TO1743 ((uint32_t)0x00001000) /* Write protection of Sector108*/ #define OB_WRP4_PAGES1744TO1759 ((uint32_t)0x00002000) /* Write protection of Sector109*/ #define OB_WRP4_PAGES1760TO1775 ((uint32_t)0x00004000) /* Write protection of Sector110*/ #define OB_WRP4_PAGES1776TO1791 ((uint32_t)0x00008000) /* Write protection of Sector111*/ #define OB_WRP4_PAGES1792TO1807 ((uint32_t)0x00010000) /* Write protection of Sector112*/ #define OB_WRP4_PAGES1808TO1823 ((uint32_t)0x00020000) /* Write protection of Sector113*/ #define OB_WRP4_PAGES1824TO1839 ((uint32_t)0x00040000) /* Write protection of Sector114*/ #define OB_WRP4_PAGES1840TO1855 ((uint32_t)0x00080000) /* Write protection of Sector115*/ #define OB_WRP4_PAGES1856TO1871 ((uint32_t)0x00100000) /* Write protection of Sector116*/ #define OB_WRP4_PAGES1872TO1887 ((uint32_t)0x00200000) /* Write protection of Sector117*/ #define OB_WRP4_PAGES1888TO1903 ((uint32_t)0x00400000) /* Write protection of Sector118*/ #define OB_WRP4_PAGES1904TO1919 ((uint32_t)0x00800000) /* Write protection of Sector119*/ #define OB_WRP4_PAGES1920TO1935 ((uint32_t)0x01000000) /* Write protection of Sector120*/ #define OB_WRP4_PAGES1936TO1951 ((uint32_t)0x02000000) /* Write protection of Sector121*/ #define OB_WRP4_PAGES1952TO1967 ((uint32_t)0x04000000) /* Write protection of Sector122*/ #define OB_WRP4_PAGES1968TO1983 ((uint32_t)0x08000000) /* Write protection of Sector123*/ #define OB_WRP4_PAGES1984TO1999 ((uint32_t)0x10000000) /* Write protection of Sector124*/ #define OB_WRP4_PAGES2000TO2015 ((uint32_t)0x20000000) /* Write protection of Sector125*/ #define OB_WRP4_PAGES2016TO2031 ((uint32_t)0x40000000) /* Write protection of Sector126*/ #define OB_WRP4_PAGES2032TO2047 ((uint32_t)0x80000000) /* Write protection of Sector127*/ #define OB_WRP4_ALLPAGES ((uint32_t)0xFFFFFFFF) /*!< Write protection of all Sectors */ /** * @} */ #endif /* STM32L151xE || STM32L152xE || STM32L162xE */ /** @defgroup FLASHEx_Option_Bytes_Read_Protection FLASHEx Option Bytes Read Protection * @{ */ #define OB_RDP_LEVEL0 ((uint8_t)0xAA) #define OB_RDP_LEVEL1 ((uint8_t)0xBB) /*#define OB_RDP_LEVEL2 ((uint8_t)0xCC)*/ /* Warning: When enabling read protection level 2 it's no more possible to go back to level 1 or 0 */ #define IS_OB_RDP(__LEVEL__) (((__LEVEL__) == OB_RDP_LEVEL0)||\ ((__LEVEL__) == OB_RDP_LEVEL1))/*||\ ((__LEVEL__) == OB_RDP_LEVEL2))*/ /** * @} */ /** @defgroup FLASHEx_Option_Bytes_BOR_Level FLASHEx Option Bytes BOR Level * @{ */ #define OB_BOR_OFF ((uint8_t)0x00) /*!< BOR is disabled at power down, the reset is asserted when the VDD power supply reaches the PDR(Power Down Reset) threshold (1.5V) */ #define OB_BOR_LEVEL1 ((uint8_t)0x08) /*!< BOR Reset threshold levels for 1.7V - 1.8V VDD power supply */ #define OB_BOR_LEVEL2 ((uint8_t)0x09) /*!< BOR Reset threshold levels for 1.9V - 2.0V VDD power supply */ #define OB_BOR_LEVEL3 ((uint8_t)0x0A) /*!< BOR Reset threshold levels for 2.3V - 2.4V VDD power supply */ #define OB_BOR_LEVEL4 ((uint8_t)0x0B) /*!< BOR Reset threshold levels for 2.55V - 2.65V VDD power supply */ #define OB_BOR_LEVEL5 ((uint8_t)0x0C) /*!< BOR Reset threshold levels for 2.8V - 2.9V VDD power supply */ #define IS_OB_BOR_LEVEL(__LEVEL__) ( ((__LEVEL__) == OB_BOR_OFF) || \ ((__LEVEL__) == OB_BOR_LEVEL1) || \ ((__LEVEL__) == OB_BOR_LEVEL2) || \ ((__LEVEL__) == OB_BOR_LEVEL3) || \ ((__LEVEL__) == OB_BOR_LEVEL4) || \ ((__LEVEL__) == OB_BOR_LEVEL5)) /** * @} */ /** @defgroup FLASHEx_Option_Bytes_IWatchdog FLASHEx Option Bytes IWatchdog * @{ */ #define OB_IWDG_SW ((uint8_t)0x10) /*!< Software WDG selected */ #define OB_IWDG_HW ((uint8_t)0x00) /*!< Hardware WDG selected */ #define IS_OB_IWDG_SOURCE(__SOURCE__) (((__SOURCE__) == OB_IWDG_SW) || ((__SOURCE__) == OB_IWDG_HW)) /** * @} */ /** @defgroup FLASHEx_Option_Bytes_nRST_STOP FLASHEx Option Bytes nRST_STOP * @{ */ #define OB_STOP_NORST ((uint8_t)0x20) /*!< No reset generated when entering in STOP */ #define OB_STOP_RST ((uint8_t)0x00) /*!< Reset generated when entering in STOP */ #define IS_OB_STOP_SOURCE(__SOURCE__) (((__SOURCE__) == OB_STOP_NORST) || ((__SOURCE__) == OB_STOP_RST)) /** * @} */ /** @defgroup FLASHEx_Option_Bytes_nRST_STDBY FLASHEx Option Bytes nRST_STDBY * @{ */ #define OB_STDBY_NORST ((uint8_t)0x40) /*!< No reset generated when entering in STANDBY */ #define OB_STDBY_RST ((uint8_t)0x00) /*!< Reset generated when entering in STANDBY */ #define IS_OB_STDBY_SOURCE(__SOURCE__) (((__SOURCE__) == OB_STDBY_NORST) || ((__SOURCE__) == OB_STDBY_RST)) /** * @} */ #if defined (STM32L151xBA) || defined (STM32L152xBA) || \ defined (STM32L151xC) || defined (STM32L152xC) || defined (STM32L162xC) /** @defgroup FLASHEx_OptionAdv_Type FLASHEx Option Advanced Type * @{ */ #define OBEX_PCROP ((uint32_t)0x01) /*!= FLASH_EEPROM_BASE) && ((__ADDRESS__) <= FLASH_EEPROM_END)) #if defined(STM32L100xB) || defined (STM32L151xB) || defined (STM32L152xB) || \ defined(STM32L100xBA) || defined (STM32L151xBA) || defined (STM32L152xBA) || \ defined(STM32L100xC) || defined (STM32L151xC) || defined (STM32L152xC) || defined (STM32L162xC) || \ defined (STM32L151xCA) || defined (STM32L152xCA) || defined (STM32L162xCA) #define IS_FLASH_PROGRAM_ADDRESS(__ADDRESS__) (((__ADDRESS__) >= FLASH_BASE) && ((__ADDRESS__) <= FLASH_END)) #else /*STM32L151xD || STM32L152xD || STM32L162xD || STM32L151xE || STM32L152xE || STM32L162xE */ #define IS_FLASH_PROGRAM_ADDRESS(__ADDRESS__) (((__ADDRESS__) >= FLASH_BASE) && ((__ADDRESS__) <= FLASH_BANK2_END)) #define IS_FLASH_PROGRAM_BANK1_ADDRESS(__ADDRESS__) (((__ADDRESS__) >= FLASH_BASE) && ((__ADDRESS__) <= FLASH_BANK1_END)) #define IS_FLASH_PROGRAM_BANK2_ADDRESS(__ADDRESS__) (((__ADDRESS__) >= FLASH_BANK2_BASE) && ((__ADDRESS__) <= FLASH_BANK2_END)) #endif /* STM32L100xB || STM32L151xB || STM32L152xB || STM32L100xBA || STM32L151xBA || STM32L152xBA || STM32L100xC || STM32L151xC || STM32L152xC || STM32L162xC || STM32L151xCA || STM32L152xCA || STM32L162xCA */ #define IS_NBPAGES(_PAGES_) (((_PAGES_) >= 1) && ((_PAGES_) <= FLASH_NBPAGES_MAX)) /** * @} */ /** @defgroup FLASHEx_Flags FLASHEx Flags * @{ */ /* Cat2 & Cat3*/ #if defined (STM32L151xBA) || defined (STM32L152xBA) || \ defined (STM32L151xC) || defined (STM32L152xC) || defined (STM32L162xC) #define FLASH_FLAG_RDERR FLASH_SR_RDERR /*!< Read protected error flag */ #endif /* STM32L151xBA || STM32L152xBA || STM32L151xC || STM32L152xC || STM32L162xC */ /* Cat3, Cat4 & Cat5*/ #if defined(STM32L100xC) || defined (STM32L151xC) || defined (STM32L152xC) || defined (STM32L162xC) || \ defined(STM32L151xCA) || defined (STM32L151xD) || defined (STM32L152xCA) || defined (STM32L152xD) || defined (STM32L162xCA) || defined (STM32L162xD) || \ defined(STM32L151xE) || defined (STM32L152xE) || defined (STM32L162xE) #define FLASH_FLAG_OPTVERRUSR FLASH_SR_OPTVERRUSR /*!< FLASH Option User Validity error flag */ #endif /* STM32L100xC || STM32L151xC || STM32L152xC || STM32L162xC || STM32L151xCA || STM32L151xD || STM32L152xCA || STM32L152xD || STM32L162xCA || STM32L162xD || STM32L151xE || STM32L152xE || STM32L162xE */ /* Cat1*/ #if defined(STM32L100xB) || defined (STM32L151xB) || defined (STM32L152xB) || defined (STM32L100xBA) #define FLASH_FLAG_MASK ( FLASH_FLAG_EOP | FLASH_FLAG_ENDHV | FLASH_FLAG_WRPERR | \ FLASH_FLAG_OPTVERR | FLASH_FLAG_PGAERR | FLASH_FLAG_SIZERR) #endif /* STM32L100xB || STM32L151xB || STM32L152xB || STM32L100xBA */ /* RDERR only for STM32L151xBA & STM32L152xBA (Cat2)*/ #if defined (STM32L151xBA) || defined (STM32L152xBA) #define FLASH_FLAG_MASK ( FLASH_FLAG_EOP | FLASH_FLAG_ENDHV | FLASH_FLAG_WRPERR | \ FLASH_FLAG_OPTVERR | FLASH_FLAG_PGAERR | FLASH_FLAG_SIZERR | \ FLASH_FLAG_RDERR) #endif /* STM32L151xBA || STM32L152xBA */ /* FLASH_FLAG_OPTVERRUSR & RDERR only for STM32L151xC, STM32L152xC & STM32L152xBA (Cat3) */ #if defined (STM32L151xC) || defined (STM32L152xC) || defined (STM32L162xC) #define FLASH_FLAG_MASK ( FLASH_FLAG_EOP | FLASH_FLAG_ENDHV | FLASH_FLAG_WRPERR | \ FLASH_FLAG_OPTVERR | FLASH_FLAG_PGAERR | FLASH_FLAG_SIZERR | \ FLASH_FLAG_OPTVERRUSR | FLASH_FLAG_RDERR) #endif /* STM32L151xC || STM32L152xC || STM32L162xC */ /* FLASH_FLAG_OPTVERRUSR only for STM32L100xC (Cat3) */ #if defined (STM32L100xC) #define FLASH_FLAG_MASK ( FLASH_FLAG_EOP | FLASH_FLAG_ENDHV | FLASH_FLAG_WRPERR | \ FLASH_FLAG_OPTVERR | FLASH_FLAG_PGAERR | FLASH_FLAG_SIZERR | \ FLASH_FLAG_OPTVERRUSR) #endif /* STM32L100xC */ /* Cat4 & Cat5 */ #if defined(STM32L151xCA) || defined (STM32L151xD) || defined (STM32L152xCA) || defined (STM32L152xD) || defined (STM32L162xCA) || defined (STM32L162xD) || \ defined(STM32L151xE) || defined (STM32L152xE) || defined (STM32L162xE) #define FLASH_FLAG_MASK ( FLASH_FLAG_EOP | FLASH_FLAG_ENDHV | FLASH_FLAG_WRPERR | \ FLASH_FLAG_OPTVERR | FLASH_FLAG_PGAERR | FLASH_FLAG_SIZERR | \ FLASH_FLAG_OPTVERRUSR) #endif /* STM32L151xCA || STM32L151xD || STM32L152xCA || STM32L152xD || STM32L162xCA || STM32L162xD || STM32L151xE || STM32L152xE || STM32L162xE */ /** * @} */ #if defined (STM32L151xD) || defined (STM32L152xD) || defined (STM32L162xD) || \ defined(STM32L151xE) || defined (STM32L152xE) || defined (STM32L162xE) /** @defgroup FLASHEx_Option_Bytes_BOOT FLASHEx Option Bytes BOOT * @{ */ #define OB_BOOT_BANK2 ((uint8_t)0x00) /*!< At startup, if boot pins are set in boot from user Flash position and this parameter is selected the device will boot from Bank 2 or Bank 1, depending on the activation of the bank */ #define OB_BOOT_BANK1 ((uint8_t)(FLASH_OBR_nRST_BFB2 >> 16)) /*!< At startup, if boot pins are set in boot from user Flash position and this parameter is selected the device will boot from Bank1(Default) */ #define IS_OB_BOOT_BANK(__BANK__) (((__BANK__) == OB_BOOT_BANK2) || ((__BANK__) == OB_BOOT_BANK1)) /** * @} */ #endif /* STM32L151xD || STM32L152xD || STM32L162xD || STM32L151xE || STM32L152xE || STM32L162xE */ /** * @} */ /* Exported macro ------------------------------------------------------------*/ /** @defgroup FLASHEx_Exported_Macros FLASHEx Exported Macros * @{ */ /** * @brief Set the FLASH Latency. * @param __LATENCY__: FLASH Latency * This parameter can be one of the following values: * @arg FLASH_LATENCY_0: FLASH Zero Latency cycle * @arg FLASH_LATENCY_1: FLASH One Latency cycle * @retval none */ #define __HAL_FLASH_SET_LATENCY(__LATENCY__) do { \ if ((__LATENCY__) == FLASH_LATENCY_1) {__HAL_FLASH_ACC64_ENABLE();} \ MODIFY_REG((FLASH->ACR), FLASH_ACR_LATENCY, (__LATENCY__)); \ } while(0) /** * @brief Get the FLASH Latency. * @retval FLASH Latency * This parameter can be one of the following values: * @arg FLASH_LATENCY_0: FLASH Zero Latency cycle * @arg FLASH_LATENCY_1: FLASH One Latency cycle */ #define __HAL_FLASH_GET_LATENCY() (READ_BIT((FLASH->ACR), FLASH_ACR_LATENCY)) /** * @brief Enable the FLASH 64-bit access. * @note Read access 64 bit is used. * @note This bit cannot be written at the same time as the LATENCY and * PRFTEN bits. * @retval none */ #define __HAL_FLASH_ACC64_ENABLE() (SET_BIT((FLASH->ACR), FLASH_ACR_ACC64)) /** * @brief Disable the FLASH 64-bit access. * @note Read access 32 bit is used * @note To reset this bit, the LATENCY should be zero wait state and the * prefetch off. * @retval none */ #define __HAL_FLASH_ACC64_DISABLE() (CLEAR_BIT((FLASH->ACR), FLASH_ACR_ACC64)) /** * @brief Enable the FLASH prefetch buffer. * @retval none */ #define __HAL_FLASH_PREFETCH_BUFFER_ENABLE() do { __HAL_FLASH_ACC64_ENABLE(); \ SET_BIT((FLASH->ACR), FLASH_ACR_PRFTEN); \ } while(0) /** * @brief Disable the FLASH prefetch buffer. * @retval none */ #define __HAL_FLASH_PREFETCH_BUFFER_DISABLE() CLEAR_BIT((FLASH->ACR), FLASH_ACR_PRFTEN) /** * @brief Enable the FLASH power down during Sleep mode * @retval none */ #define __HAL_FLASH_SLEEP_POWERDOWN_ENABLE() SET_BIT(FLASH->ACR, FLASH_ACR_SLEEP_PD) /** * @brief Disable the FLASH power down during Sleep mode * @retval none */ #define __HAL_FLASH_SLEEP_POWERDOWN_DISABLE() CLEAR_BIT(FLASH->ACR, FLASH_ACR_SLEEP_PD) /** * @brief Macro to enable or disable the Flash Run power down mode. * @note Writing this bit to 0 this bit, automatically the keys are * loss and a new unlock sequence is necessary to re-write it to 1. */ #define __HAL_FLASH_POWER_DOWN_ENABLE() do { FLASH->PDKEYR = FLASH_PDKEY1; \ FLASH->PDKEYR = FLASH_PDKEY2; \ SET_BIT((FLASH->ACR), FLASH_ACR_RUN_PD); \ } while (0) #define __HAL_FLASH_POWER_DOWN_DISABLE() do { FLASH->PDKEYR = FLASH_PDKEY1; \ FLASH->PDKEYR = FLASH_PDKEY2; \ CLEAR_BIT((FLASH->ACR), FLASH_ACR_RUN_PD); \ } while (0) /** * @} */ /* Exported functions --------------------------------------------------------*/ /** @addtogroup FLASHEx_Exported_Functions * @{ */ /** @addtogroup FLASHEx_Exported_Functions_Group1 * @{ */ HAL_StatusTypeDef HAL_FLASHEx_Erase(FLASH_EraseInitTypeDef *pEraseInit, uint32_t *PageError); HAL_StatusTypeDef HAL_FLASHEx_Erase_IT(FLASH_EraseInitTypeDef *pEraseInit); /** * @} */ /** @addtogroup FLASHEx_Exported_Functions_Group2 * @{ */ HAL_StatusTypeDef HAL_FLASHEx_OBProgram(FLASH_OBProgramInitTypeDef *pOBInit); void HAL_FLASHEx_OBGetConfig(FLASH_OBProgramInitTypeDef *pOBInit); #if defined (STM32L151xBA) || defined (STM32L152xBA) || \ defined (STM32L151xC) || defined (STM32L152xC) || defined (STM32L162xC) || \ defined (STM32L151xD) || defined (STM32L152xD) || defined (STM32L162xD) || \ defined(STM32L151xE) || defined (STM32L152xE) || defined (STM32L162xE) HAL_StatusTypeDef HAL_FLASHEx_AdvOBProgram (FLASH_AdvOBProgramInitTypeDef *pAdvOBInit); void HAL_FLASHEx_AdvOBGetConfig(FLASH_AdvOBProgramInitTypeDef *pAdvOBInit); #endif /* STM32L151xBA || STM32L152xBA || STM32L151xC || STM32L152xC || STM32L162xC || STM32L151xD || STM32L152xD || STM32L162xD || STM32L151xE || STM32L152xE || STM32L162xE */ #if defined (STM32L151xBA) || defined (STM32L152xBA) || \ defined (STM32L151xC) || defined (STM32L152xC) || defined (STM32L162xC) HAL_StatusTypeDef HAL_FLASHEx_OB_SelectPCROP(void); HAL_StatusTypeDef HAL_FLASHEx_OB_DeSelectPCROP(void); #endif /* STM32L151xBA || STM32L152xBA || STM32L151xC || STM32L152xC || STM32L162xC */ /** * @} */ /** @addtogroup FLASHEx_Exported_Functions_Group3 * @{ */ HAL_StatusTypeDef HAL_FLASHEx_DATAEEPROM_Unlock(void); HAL_StatusTypeDef HAL_FLASHEx_DATAEEPROM_Lock(void); HAL_StatusTypeDef HAL_FLASHEx_DATAEEPROM_Erase(uint32_t TypeErase, uint32_t Address); HAL_StatusTypeDef HAL_FLASHEx_DATAEEPROM_Program(uint32_t TypeProgram, uint32_t Address, uint32_t Data); void HAL_FLASHEx_DATAEEPROM_EnableFixedTimeProgram(void); void HAL_FLASHEx_DATAEEPROM_DisableFixedTimeProgram(void); /** * @} */ /** * @} */ /** * @} */ /** * @} */ #ifdef __cplusplus } #endif #endif /* __STM32L1xx_HAL_FLASH_EX_H */ /************************ (C) COPYRIGHT STMicroelectronics *****END OF FILE****/ ================================================ FILE: Zelig/mbed/TARGET_NUCLEO_L152RE/stm32l1xx_hal_flash_ramfunc.h ================================================ /** ****************************************************************************** * @file stm32l1xx_hal_flash_ramfunc.h * @author MCD Application Team * @version V1.0.0 * @date 5-September-2014 * @brief Header file of FLASH RAMFUNC driver. ****************************************************************************** * @attention * *

© COPYRIGHT(c) 2014 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. * ****************************************************************************** */ /* Define to prevent recursive inclusion -------------------------------------*/ #ifndef __STM32L1xx_FLASH_RAMFUNC_H #define __STM32L1xx_FLASH_RAMFUNC_H #ifdef __cplusplus extern "C" { #endif /* Includes ------------------------------------------------------------------*/ #include "stm32l1xx_hal_def.h" /** @addtogroup STM32L1xx_HAL_Driver * @{ */ /** @addtogroup FLASHRamfunc * @{ */ /* Exported types ------------------------------------------------------------*/ /* Exported functions --------------------------------------------------------*/ /** @addtogroup FLASHRamfunc_Exported_Functions * @{ */ /* * @brief FLASH memory functions that should be executed from internal SRAM. * These functions are defined inside the "stm32l1xx_hal_flash_ramfunc.c" * file. */ /** @addtogroup FLASHRamfunc_Exported_Functions_Group1 * @{ */ __RAM_FUNC HAL_FLASHEx_EnableRunPowerDown(void); __RAM_FUNC HAL_FLASHEx_DisableRunPowerDown(void); /** * @} */ /** @addtogroup FLASHRamfunc_Exported_Functions_Group2 * @{ */ #if defined (STM32L151xD) || defined (STM32L152xD) || defined (STM32L162xD) || \ defined(STM32L151xE) || defined (STM32L152xE) || defined (STM32L162xE) __RAM_FUNC HAL_FLASHEx_EraseParallelPage(uint32_t Page_Address1, uint32_t Page_Address2); __RAM_FUNC HAL_FLASHEx_ProgramParallelHalfPage(uint32_t Address1, uint32_t* pBuffer1, uint32_t Address2, uint32_t* pBuffer2); #endif /* STM32L151xD || STM32L152xD || STM32L162xD || STM32L151xE || STM32L152xE || STM32L162xE */ __RAM_FUNC HAL_FLASHEx_HalfPageProgram(uint32_t Address, uint32_t* pBuffer); /** * @} */ /** @addtogroup FLASHRamfunc_Exported_Functions_Group3 * @{ */ __RAM_FUNC HAL_FLASHEx_DATAEEPROM_EraseDoubleWord(uint32_t Address); __RAM_FUNC HAL_FLASHEx_DATAEEPROM_ProgramDoubleWord(uint32_t Address, uint64_t Data); /** * @} */ /** * @} */ /** * @} */ /** * @} */ #ifdef __cplusplus } #endif #endif /* __STM32L1xx_FLASH_RAMFUNC_H */ /************************ (C) COPYRIGHT STMicroelectronics *****END OF FILE****/ ================================================ FILE: Zelig/mbed/TARGET_NUCLEO_L152RE/stm32l1xx_hal_gpio.h ================================================ /** ****************************************************************************** * @file stm32l1xx_hal_gpio.h * @author MCD Application Team * @version V1.0.0 * @date 5-September-2014 * @brief Header file of GPIO HAL module. ****************************************************************************** * @attention * *

© COPYRIGHT(c) 2014 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. * ****************************************************************************** */ /* Define to prevent recursive inclusion -------------------------------------*/ #ifndef __STM32L1xx_HAL_GPIO_H #define __STM32L1xx_HAL_GPIO_H #ifdef __cplusplus extern "C" { #endif /* Includes ------------------------------------------------------------------*/ #include "stm32l1xx_hal_def.h" /** @addtogroup STM32L1xx_HAL_Driver * @{ */ /** @addtogroup GPIO * @{ */ /* Exported types ------------------------------------------------------------*/ /** @defgroup GPIO_Exported_Types GPIO Exported Types * @{ */ /** * @brief GPIO Init structure definition */ typedef struct { uint32_t Pin; /*!< Specifies the GPIO pins to be configured. This parameter can be any value of @ref GPIO_pins_define */ uint32_t Mode; /*!< Specifies the operating mode for the selected pins. This parameter can be a value of @ref GPIO_mode_define */ uint32_t Pull; /*!< Specifies the Pull-up or Pull-Down activation for the selected pins. This parameter can be a value of @ref GPIO_pull_define */ uint32_t Speed; /*!< Specifies the speed for the selected pins. This parameter can be a value of @ref GPIO_speed_define */ uint32_t Alternate; /*!< Peripheral to be connected to the selected pins This parameter can be a value of @ref GPIOEx_Alternate_function_selection */ }GPIO_InitTypeDef; /** * @brief GPIO Bit SET and Bit RESET enumeration */ typedef enum { GPIO_PIN_RESET = 0, GPIO_PIN_SET }GPIO_PinState; /** * @} */ /* Exported constants --------------------------------------------------------*/ /** @defgroup GPIO_Exported_Constants GPIO Exported Constants * @{ */ /** @defgroup GPIO_pins_define GPIO pins define * @{ */ #define GPIO_PIN_0 ((uint16_t)0x0001) /* Pin 0 selected */ #define GPIO_PIN_1 ((uint16_t)0x0002) /* Pin 1 selected */ #define GPIO_PIN_2 ((uint16_t)0x0004) /* Pin 2 selected */ #define GPIO_PIN_3 ((uint16_t)0x0008) /* Pin 3 selected */ #define GPIO_PIN_4 ((uint16_t)0x0010) /* Pin 4 selected */ #define GPIO_PIN_5 ((uint16_t)0x0020) /* Pin 5 selected */ #define GPIO_PIN_6 ((uint16_t)0x0040) /* Pin 6 selected */ #define GPIO_PIN_7 ((uint16_t)0x0080) /* Pin 7 selected */ #define GPIO_PIN_8 ((uint16_t)0x0100) /* Pin 8 selected */ #define GPIO_PIN_9 ((uint16_t)0x0200) /* Pin 9 selected */ #define GPIO_PIN_10 ((uint16_t)0x0400) /* Pin 10 selected */ #define GPIO_PIN_11 ((uint16_t)0x0800) /* Pin 11 selected */ #define GPIO_PIN_12 ((uint16_t)0x1000) /* Pin 12 selected */ #define GPIO_PIN_13 ((uint16_t)0x2000) /* Pin 13 selected */ #define GPIO_PIN_14 ((uint16_t)0x4000) /* Pin 14 selected */ #define GPIO_PIN_15 ((uint16_t)0x8000) /* Pin 15 selected */ #define GPIO_PIN_All ((uint16_t)0xFFFF) /* All pins selected */ #define GPIO_PIN_MASK ((uint32_t)0x0000FFFF) /* PIN mask for assert test */ /** * @} */ /** @defgroup GPIO_mode_define GPIO mode define * @brief GPIO Configuration Mode * Elements values convention: 0xX0yz00YZ * - X : GPIO mode or EXTI Mode * - y : External IT or Event trigger detection * - z : IO configuration on External IT or Event * - Y : Output type (Push Pull or Open Drain) * - Z : IO Direction mode (Input, Output, Alternate or Analog) * @{ */ #define GPIO_MODE_INPUT ((uint32_t)0x00000000) /*!< Input Floating Mode */ #define GPIO_MODE_OUTPUT_PP ((uint32_t)0x00000001) /*!< Output Push Pull Mode */ #define GPIO_MODE_OUTPUT_OD ((uint32_t)0x00000011) /*!< Output Open Drain Mode */ #define GPIO_MODE_AF_PP ((uint32_t)0x00000002) /*!< Alternate Function Push Pull Mode */ #define GPIO_MODE_AF_OD ((uint32_t)0x00000012) /*!< Alternate Function Open Drain Mode */ #define GPIO_MODE_ANALOG ((uint32_t)0x00000003) /*!< Analog Mode */ #define GPIO_MODE_IT_RISING ((uint32_t)0x10110000) /*!< External Interrupt Mode with Rising edge trigger detection */ #define GPIO_MODE_IT_FALLING ((uint32_t)0x10210000) /*!< External Interrupt Mode with Falling edge trigger detection */ #define GPIO_MODE_IT_RISING_FALLING ((uint32_t)0x10310000) /*!< External Interrupt Mode with Rising/Falling edge trigger detection */ #define GPIO_MODE_EVT_RISING ((uint32_t)0x10120000) /*!< External Event Mode with Rising edge trigger detection */ #define GPIO_MODE_EVT_FALLING ((uint32_t)0x10220000) /*!< External Event Mode with Falling edge trigger detection */ #define GPIO_MODE_EVT_RISING_FALLING ((uint32_t)0x10320000) /*!< External Event Mode with Rising/Falling edge trigger detection */ /** * @} */ /** @defgroup GPIO_speed_define GPIO speed define * @brief GPIO Output Maximum frequency * @{ */ #define GPIO_SPEED_VERY_LOW ((uint32_t)0x00000000) /*!< Very Low speed */ #define GPIO_SPEED_LOW ((uint32_t)0x00000001) /*!< Low speed */ #define GPIO_SPEED_MEDIUM ((uint32_t)0x00000002) /*!< Medium speed */ #define GPIO_SPEED_HIGH ((uint32_t)0x00000003) /*!< High speed */ /** * @} */ /** @defgroup GPIO_pull_define GPIO pull define * @brief GPIO Pull-Up or Pull-Down Activation * @{ */ #define GPIO_NOPULL ((uint32_t)0x00000000) /*!< No Pull-up or Pull-down activation */ #define GPIO_PULLUP ((uint32_t)0x00000001) /*!< Pull-up activation */ #define GPIO_PULLDOWN ((uint32_t)0x00000002) /*!< Pull-down activation */ /** * @} */ /** * @} */ /* Private macros --------------------------------------------------------*/ /** @addtogroup GPIO_Private_Macros * @{ */ #define IS_GPIO_PIN_ACTION(ACTION) (((ACTION) == GPIO_PIN_RESET) || ((ACTION) == GPIO_PIN_SET)) #define IS_GPIO_PIN(PIN) (((PIN) & GPIO_PIN_MASK ) != (uint32_t)0x00) #define IS_GPIO_PULL(PULL) (((PULL) == GPIO_NOPULL) || ((PULL) == GPIO_PULLUP) || \ ((PULL) == GPIO_PULLDOWN)) #define IS_GPIO_SPEED(SPEED) (((SPEED) == GPIO_SPEED_VERY_LOW) || ((SPEED) == GPIO_SPEED_LOW) || \ ((SPEED) == GPIO_SPEED_MEDIUM) || ((SPEED) == GPIO_SPEED_HIGH)) #define IS_GPIO_MODE(MODE) (((MODE) == GPIO_MODE_INPUT) ||\ ((MODE) == GPIO_MODE_OUTPUT_PP) ||\ ((MODE) == GPIO_MODE_OUTPUT_OD) ||\ ((MODE) == GPIO_MODE_AF_PP) ||\ ((MODE) == GPIO_MODE_AF_OD) ||\ ((MODE) == GPIO_MODE_IT_RISING) ||\ ((MODE) == GPIO_MODE_IT_FALLING) ||\ ((MODE) == GPIO_MODE_IT_RISING_FALLING) ||\ ((MODE) == GPIO_MODE_EVT_RISING) ||\ ((MODE) == GPIO_MODE_EVT_FALLING) ||\ ((MODE) == GPIO_MODE_EVT_RISING_FALLING) ||\ ((MODE) == GPIO_MODE_ANALOG)) /** * @} */ /* Exported macro ------------------------------------------------------------*/ /** @defgroup GPIO_Exported_Macros GPIO Exported Macros * @{ */ /** * @brief Checks whether the specified EXTI line flag is set or not. * @param __EXTI_LINE__: specifies the EXTI line flag to check. * This parameter can be GPIO_PIN_x where x can be(0..15) * @retval The new state of __EXTI_LINE__ (SET or RESET). */ #define __HAL_GPIO_EXTI_GET_FLAG(__EXTI_LINE__) (EXTI->PR & (__EXTI_LINE__)) /** * @brief Clears the EXTI's line pending flags. * @param __EXTI_LINE__: specifies the EXTI lines flags to clear. * This parameter can be any combination of GPIO_PIN_x where x can be (0..15) * @retval None */ #define __HAL_GPIO_EXTI_CLEAR_FLAG(__EXTI_LINE__) (EXTI->PR = (__EXTI_LINE__)) /** * @brief Checks whether the specified EXTI line is asserted or not. * @param __EXTI_LINE__: specifies the EXTI line to check. * This parameter can be GPIO_PIN_x where x can be(0..15) * @retval The new state of __EXTI_LINE__ (SET or RESET). */ #define __HAL_GPIO_EXTI_GET_IT(__EXTI_LINE__) (EXTI->PR & (__EXTI_LINE__)) /** * @brief Clears the EXTI's line pending bits. * @param __EXTI_LINE__: specifies the EXTI lines to clear. * This parameter can be any combination of GPIO_PIN_x where x can be (0..15) * @retval None */ #define __HAL_GPIO_EXTI_CLEAR_IT(__EXTI_LINE__) (EXTI->PR = (__EXTI_LINE__)) /** * @brief Generates a Software interrupt on selected EXTI line. * @param __EXTI_LINE__: specifies the EXTI line to check. * This parameter can be GPIO_PIN_x where x can be(0..15) * @retval None */ #define __HAL_GPIO_EXTI_GENERATE_SWIT(__EXTI_LINE__) (EXTI->SWIER |= (__EXTI_LINE__)) /* Include GPIO HAL Extension module */ #include "stm32l1xx_hal_gpio_ex.h" /** * @} */ /* Exported functions --------------------------------------------------------*/ /* Initialization and de-initialization functions *******************************/ /** @addtogroup GPIO_Exported_Functions * @{ */ /** @addtogroup GPIO_Exported_Functions_Group1 * @brief Initialization and Configuration functions * * @{ */ void HAL_GPIO_Init(GPIO_TypeDef *GPIOx, GPIO_InitTypeDef *GPIO_Init); void HAL_GPIO_DeInit(GPIO_TypeDef *GPIOx, uint32_t GPIO_Pin); /** * @} */ /* IO operation functions *******************************************************/ /** @addtogroup GPIO_Exported_Functions_Group2 * @brief Initialization and Configuration functions * * @{ */ GPIO_PinState HAL_GPIO_ReadPin(GPIO_TypeDef* GPIOx, uint16_t GPIO_Pin); void HAL_GPIO_WritePin(GPIO_TypeDef* GPIOx, uint16_t GPIO_Pin, GPIO_PinState PinState); void HAL_GPIO_TogglePin(GPIO_TypeDef* GPIOx, uint16_t GPIO_Pin); HAL_StatusTypeDef HAL_GPIO_LockPin(GPIO_TypeDef* GPIOx, uint16_t GPIO_Pin); void HAL_GPIO_EXTI_IRQHandler(uint16_t GPIO_Pin); void HAL_GPIO_EXTI_Callback(uint16_t GPIO_Pin); /** * @} */ /** * @} */ /** * @} */ /** * @} */ #ifdef __cplusplus } #endif #endif /* __STM32L1xx_HAL_GPIO_H */ /************************ (C) COPYRIGHT STMicroelectronics *****END OF FILE****/ ================================================ FILE: Zelig/mbed/TARGET_NUCLEO_L152RE/stm32l1xx_hal_gpio_ex.h ================================================ /** ****************************************************************************** * @file stm32l1xx_hal_gpio_ex.h * @author MCD Application Team * @version V1.0.0 * @date 5-September-2014 * @brief Header file of GPIO HAL Extension module. ****************************************************************************** * @attention * *

© COPYRIGHT(c) 2014 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. * ****************************************************************************** */ /* Define to prevent recursive inclusion -------------------------------------*/ #ifndef __STM32L1xx_HAL_GPIO_EX_H #define __STM32L1xx_HAL_GPIO_EX_H #ifdef __cplusplus extern "C" { #endif /* Includes ------------------------------------------------------------------*/ #include "stm32l1xx_hal_def.h" /** @addtogroup STM32L1xx_HAL_Driver * @{ */ /** @defgroup GPIOEx GPIOEx * @{ */ /* Exported types ------------------------------------------------------------*/ /* Exported constants --------------------------------------------------------*/ /** @defgroup GPIOEx_Exported_Constants GPIOEx Exported Constants * @{ */ /** @defgroup GPIOEx_Alternate_function_selection GPIOEx Alternate function selection * @{ */ /** * @brief AF 0 selection */ #define GPIO_AF0_MCO ((uint8_t)0x00) /* MCO Alternate Function mapping */ #define GPIO_AF0_TAMPER ((uint8_t)0x00) /* TAMPER Alternate Function mapping */ #define GPIO_AF0_SWJ ((uint8_t)0x00) /* SWJ (SWD and JTAG) Alternate Function mapping */ #define GPIO_AF0_TRACE ((uint8_t)0x00) /* TRACE Alternate Function mapping */ #define GPIO_AF0_RTC_50Hz ((uint8_t)0x00) /* RTC_OUT Alternate Function mapping */ /** * @brief AF 1 selection */ #define GPIO_AF1_TIM2 ((uint8_t)0x01) /* TIM2 Alternate Function mapping */ /** * @brief AF 2 selection */ #define GPIO_AF2_TIM3 ((uint8_t)0x02) /* TIM3 Alternate Function mapping */ #define GPIO_AF2_TIM4 ((uint8_t)0x02) /* TIM4 Alternate Function mapping */ #if defined (STM32L151xCA) || defined (STM32L151xD) || defined (STM32L152xCA) || defined (STM32L152xD) || defined (STM32L162xCA) || defined (STM32L162xD) || defined (STM32L151xE) || defined (STM32L152xE) || defined (STM32L162xE) || defined (STM32L162xC) || defined (STM32L152xC) || defined (STM32L151xC) #define GPIO_AF2_TIM5 ((uint8_t)0x02) /* TIM5 Alternate Function mapping */ #endif /* STM32L151xCA || STM32L151xD || STM32L152xCA || STM32L152xD || STM32L162xCA || STM32L162xD ...STM32L151xC */ /** * @brief AF 3 selection */ #define GPIO_AF3_TIM9 ((uint8_t)0x03) /* TIM9 Alternate Function mapping */ #define GPIO_AF3_TIM10 ((uint8_t)0x03) /* TIM10 Alternate Function mapping */ #define GPIO_AF3_TIM11 ((uint8_t)0x03) /* TIM11 Alternate Function mapping */ /** * @brief AF 4 selection */ #define GPIO_AF4_I2C1 ((uint8_t)0x04) /* I2C1 Alternate Function mapping */ #define GPIO_AF4_I2C2 ((uint8_t)0x04) /* I2C2 Alternate Function mapping */ /** * @brief AF 5 selection */ #define GPIO_AF5_SPI1 ((uint8_t)0x05) /* SPI1/I2S1 Alternate Function mapping */ #define GPIO_AF5_SPI2 ((uint8_t)0x05) /* SPI2/I2S2 Alternate Function mapping */ /** * @brief AF 6 selection */ #if defined (STM32L100xC) || defined (STM32L151xC) || defined (STM32L151xCA) || defined (STM32L151xD) || defined (STM32L151xE) ||\ defined (STM32L152xC) || defined (STM32L152xCA) || defined (STM32L152xD) || defined (STM32L152xE) ||\ defined (STM32L162xC) || defined (STM32L162xCA) || defined (STM32L162xD) || defined (STM32L162xE) #define GPIO_AF6_SPI3 ((uint8_t)0x06) /* SPI3/I2S3 Alternate Function mapping */ #endif /* STM32L100xC || STM32L151xC || (...) || STM32L162xD || STM32L162xE */ /** * @brief AF 7 selection */ #define GPIO_AF7_USART1 ((uint8_t)0x07) /* USART1 Alternate Function mapping */ #define GPIO_AF7_USART2 ((uint8_t)0x07) /* USART2 Alternate Function mapping */ #define GPIO_AF7_USART3 ((uint8_t)0x07) /* USART3 Alternate Function mapping */ /** * @brief AF 8 selection */ #if defined (STM32L151xD) || defined (STM32L151xE) ||\ defined (STM32L152xD) || defined (STM32L152xE) ||\ defined (STM32L162xD) || defined (STM32L162xE) #define GPIO_AF8_UART4 ((uint8_t)0x08) /* UART4 Alternate Function mapping */ #define GPIO_AF8_UART5 ((uint8_t)0x08) /* UART5 Alternate Function mapping */ #endif /* STM32L151xD || STM32L151xE || STM32L152xD || STM32L 152xE || STM32L162xD || STM32L162xE */ /** * @brief AF 9 selection */ /** * @brief AF 10 selection */ /** * @brief AF 11 selection */ #if defined (STM32L100xB) || defined (STM32L100xBA) || defined (STM32L100xC) ||\ defined (STM32L152xB) || defined (STM32L152xBA) || defined (STM32L152xC) || defined (STM32L152xCA) || defined (STM32L152xD) || defined (STM32L152xE) ||\ defined (STM32L162xC) || defined (STM32L162xCA) || defined (STM32L162xD) || defined (STM32L162xE) #define GPIO_AF11_LCD ((uint8_t)0x0B) /* LCD Alternate Function mapping */ #endif /* STM32L100xB || STM32L100xBA || STM32L100xC || (...) || STM32L162xCA || STM32L162xD || STM32L162xE */ /** * @brief AF 12 selection */ #if defined (STM32L151xD) || defined (STM32L152xD) || defined (STM32L162xD) #define GPIO_AF12_FSMC ((uint8_t)0x0C) /* FSMC Alternate Function mapping */ #define GPIO_AF12_SDIO ((uint8_t)0x0C) /* SDIO Alternate Function mapping */ #endif /* STM32L151xD || STM32L152xD || STM32L162xD */ /** * @brief AF 13 selection */ /** * @brief AF 14 selection */ #define GPIO_AF14_TIM_IC1 ((uint8_t)0x0E) /* TIMER INPUT CAPTURE Alternate Function mapping */ #define GPIO_AF14_TIM_IC2 ((uint8_t)0x0E) /* TIMER INPUT CAPTURE Alternate Function mapping */ #define GPIO_AF14_TIM_IC3 ((uint8_t)0x0E) /* TIMER INPUT CAPTURE Alternate Function mapping */ #define GPIO_AF14_TIM_IC4 ((uint8_t)0x0E) /* TIMER INPUT CAPTURE Alternate Function mapping */ /** * @brief AF 15 selection */ #define GPIO_AF15_EVENTOUT ((uint8_t)0x0F) /* EVENTOUT Alternate Function mapping */ /** * @} */ /** * @} */ /** @defgroup GPIOEx_Private_Macros GPIOEx Private Macros * @{ */ #define IS_GPIO_AF(AF) ((AF) <= (uint8_t)0x0F) #if defined (STM32L151xCA) || defined (STM32L151xD) || defined (STM32L152xCA) || defined (STM32L152xD) || defined (STM32L162xCA) || defined (STM32L162xD) || defined (STM32L151xE) || defined (STM32L152xE) || defined (STM32L162xE) #define GET_GPIO_INDEX(__GPIOx__) (((__GPIOx__) == (GPIOA))? 0U :\ ((__GPIOx__) == (GPIOB))? 1U :\ ((__GPIOx__) == (GPIOC))? 2U :\ ((__GPIOx__) == (GPIOD))? 3U :\ ((__GPIOx__) == (GPIOE))? 4U :\ ((__GPIOx__) == (GPIOF))? 5U :\ ((__GPIOx__) == (GPIOG))? 6U :\ ((__GPIOx__) == (GPIOH))? 7U : 8U) #endif #if defined (STM32L151xB) || defined (STM32L151xBA) || defined (STM32L151xC) || defined (STM32L152xB) || defined (STM32L152xBA) || defined (STM32L152xC) || defined (STM32L162xC) #define GET_GPIO_INDEX(__GPIOx__) (((__GPIOx__) == (GPIOA))? 0U :\ ((__GPIOx__) == (GPIOB))? 1U :\ ((__GPIOx__) == (GPIOC))? 2U :\ ((__GPIOx__) == (GPIOD))? 3U :\ ((__GPIOx__) == (GPIOE))? 4U :\ ((__GPIOx__) == (GPIOH))? 7U : 8U) #endif #if defined (STM32L100xB) || defined (STM32L100xBA) || defined (STM32L100xC) #define GET_GPIO_INDEX(__GPIOx__) (((__GPIOx__) == (GPIOA))? 0U :\ ((__GPIOx__) == (GPIOB))? 1U :\ ((__GPIOx__) == (GPIOC))? 2U :\ ((__GPIOx__) == (GPIOD))? 3U :\ ((__GPIOx__) == (GPIOH))? 7U : 8U) #endif /** * @} */ /* Exported macro ------------------------------------------------------------*/ /* Exported functions --------------------------------------------------------*/ /** * @} */ /** * @} */ #ifdef __cplusplus } #endif #endif /* __STM32L1xx_HAL_GPIO_EX_H */ /************************ (C) COPYRIGHT STMicroelectronics *****END OF FILE****/ ================================================ FILE: Zelig/mbed/TARGET_NUCLEO_L152RE/stm32l1xx_hal_i2c.h ================================================ /** ****************************************************************************** * @file stm32l1xx_hal_i2c.h * @author MCD Application Team * @version V1.0.0 * @date 5-September-2014 * @brief Header file of I2C HAL module. ****************************************************************************** * @attention * *

© COPYRIGHT(c) 2014 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. * ****************************************************************************** */ /* Define to prevent recursive inclusion -------------------------------------*/ #ifndef __STM32L1xx_HAL_I2C_H #define __STM32L1xx_HAL_I2C_H #ifdef __cplusplus extern "C" { #endif /* Includes ------------------------------------------------------------------*/ #include "stm32l1xx_hal_def.h" /** @addtogroup STM32L1xx_HAL_Driver * @{ */ /** @addtogroup I2C * @{ */ /* Exported types ------------------------------------------------------------*/ /** @defgroup I2C_Exported_Types I2C Exported Types * @{ */ /** * @brief I2C Configuration Structure definition */ typedef struct { uint32_t ClockSpeed; /*!< Specifies the clock frequency. This parameter must be set to a value lower than 400kHz */ uint32_t DutyCycle; /*!< Specifies the I2C fast mode duty cycle. This parameter can be a value of @ref I2C_duty_cycle_in_fast_mode */ uint32_t OwnAddress1; /*!< Specifies the first device own address. This parameter can be a 7-bit or 10-bit address. */ uint32_t AddressingMode; /*!< Specifies if 7-bit or 10-bit addressing mode is selected. This parameter can be a value of @ref I2C_addressing_mode */ uint32_t DualAddressMode; /*!< Specifies if dual addressing mode is selected. This parameter can be a value of @ref I2C_dual_addressing_mode */ uint32_t OwnAddress2; /*!< Specifies the second device own address if dual addressing mode is selected This parameter can be a 7-bit address. */ uint32_t GeneralCallMode; /*!< Specifies if general call mode is selected. This parameter can be a value of @ref I2C_general_call_addressing_mode */ uint32_t NoStretchMode; /*!< Specifies if nostretch mode is selected. This parameter can be a value of @ref I2C_nostretch_mode */ }I2C_InitTypeDef; /** * @brief HAL State structures definition */ typedef enum { HAL_I2C_STATE_RESET = 0x00, /*!< I2C not yet initialized or disabled */ HAL_I2C_STATE_READY = 0x01, /*!< I2C initialized and ready for use */ HAL_I2C_STATE_BUSY = 0x02, /*!< I2C internal process is ongoing */ HAL_I2C_STATE_BUSY_TX = 0x12, /*!< Data Transmission process is ongoing */ HAL_I2C_STATE_BUSY_RX = 0x22, /*!< Data Reception process is ongoing */ HAL_I2C_STATE_MEM_BUSY_TX = 0x32, /*!< Memory Data Transmission process is ongoing */ HAL_I2C_STATE_MEM_BUSY_RX = 0x42, /*!< Memory Data Reception process is ongoing */ HAL_I2C_STATE_TIMEOUT = 0x03, /*!< I2C timeout state */ HAL_I2C_STATE_ERROR = 0x04 /*!< I2C error state */ }HAL_I2C_StateTypeDef; /** * @brief HAL I2C Error Code structure definition */ typedef enum { HAL_I2C_ERROR_NONE = 0x00, /*!< No error */ HAL_I2C_ERROR_BERR = 0x01, /*!< BERR error */ HAL_I2C_ERROR_ARLO = 0x02, /*!< ARLO error */ HAL_I2C_ERROR_AF = 0x04, /*!< AF error */ HAL_I2C_ERROR_OVR = 0x08, /*!< OVR error */ HAL_I2C_ERROR_DMA = 0x10, /*!< DMA transfer error */ HAL_I2C_ERROR_TIMEOUT = 0x20 /*!< Timeout error */ }HAL_I2C_ErrorTypeDef; /** * @brief I2C handle Structure definition */ typedef struct { I2C_TypeDef *Instance; /*!< I2C registers base address */ I2C_InitTypeDef Init; /*!< I2C communication parameters */ uint8_t *pBuffPtr; /*!< Pointer to I2C transfer buffer */ uint16_t XferSize; /*!< I2C transfer size */ __IO uint16_t XferCount; /*!< I2C transfer counter */ DMA_HandleTypeDef *hdmatx; /*!< I2C Tx DMA handle parameters */ DMA_HandleTypeDef *hdmarx; /*!< I2C Rx DMA handle parameters */ HAL_LockTypeDef Lock; /*!< I2C locking object */ __IO HAL_I2C_StateTypeDef State; /*!< I2C communication state */ __IO HAL_I2C_ErrorTypeDef ErrorCode; /* I2C Error code */ }I2C_HandleTypeDef; /** * @} */ /* Exported constants --------------------------------------------------------*/ /** @defgroup I2C_Exported_Constants I2C Exported Constants * @{ */ /** @defgroup I2C_duty_cycle_in_fast_mode I2C_duty_cycle_in_fast_mode * @{ */ #define I2C_DUTYCYCLE_2 ((uint32_t)0x00000000) #define I2C_DUTYCYCLE_16_9 I2C_CCR_DUTY #define IS_I2C_DUTY_CYCLE(CYCLE) (((CYCLE) == I2C_DUTYCYCLE_2) || \ ((CYCLE) == I2C_DUTYCYCLE_16_9)) /** * @} */ /** @defgroup I2C_addressing_mode I2C_addressing_mode * @{ */ #define I2C_ADDRESSINGMODE_7BIT ((uint32_t)0x00004000) #define I2C_ADDRESSINGMODE_10BIT (I2C_OAR1_ADDMODE | ((uint32_t)0x00004000)) #define IS_I2C_ADDRESSING_MODE(ADDRESS) (((ADDRESS) == I2C_ADDRESSINGMODE_7BIT) || \ ((ADDRESS) == I2C_ADDRESSINGMODE_10BIT)) /** * @} */ /** @defgroup I2C_dual_addressing_mode I2C_dual_addressing_mode * @{ */ #define I2C_DUALADDRESS_DISABLED ((uint32_t)0x00000000) #define I2C_DUALADDRESS_ENABLED I2C_OAR2_ENDUAL #define IS_I2C_DUAL_ADDRESS(ADDRESS) (((ADDRESS) == I2C_DUALADDRESS_DISABLED) || \ ((ADDRESS) == I2C_DUALADDRESS_ENABLED)) /** * @} */ /** @defgroup I2C_general_call_addressing_mode I2C_general_call_addressing_mode * @{ */ #define I2C_GENERALCALL_DISABLED ((uint32_t)0x00000000) #define I2C_GENERALCALL_ENABLED I2C_CR1_ENGC #define IS_I2C_GENERAL_CALL(CALL) (((CALL) == I2C_GENERALCALL_DISABLED) || \ ((CALL) == I2C_GENERALCALL_ENABLED)) /** * @} */ /** @defgroup I2C_nostretch_mode I2C_nostretch_mode * @{ */ #define I2C_NOSTRETCH_DISABLED ((uint32_t)0x00000000) #define I2C_NOSTRETCH_ENABLED I2C_CR1_NOSTRETCH #define IS_I2C_NO_STRETCH(STRETCH) (((STRETCH) == I2C_NOSTRETCH_DISABLED) || \ ((STRETCH) == I2C_NOSTRETCH_ENABLED)) /** * @} */ /** @defgroup I2C_Memory_Address_Size I2C_Memory_Address_Size * @{ */ #define I2C_MEMADD_SIZE_8BIT ((uint32_t)0x00000001) #define I2C_MEMADD_SIZE_16BIT ((uint32_t)0x00000010) #define IS_I2C_MEMADD_SIZE(SIZE) (((SIZE) == I2C_MEMADD_SIZE_8BIT) || \ ((SIZE) == I2C_MEMADD_SIZE_16BIT)) /** * @} */ /** @defgroup I2C_Interrupt_configuration_definition I2C_Interrupt_configuration_definition * @{ */ #define I2C_IT_BUF I2C_CR2_ITBUFEN #define I2C_IT_EVT I2C_CR2_ITEVTEN #define I2C_IT_ERR I2C_CR2_ITERREN /** * @} */ /** @defgroup I2C_Flag_definition I2C_Flag_definition * @{ */ #define I2C_FLAG_OVR ((uint32_t)(1 << 16 | I2C_SR1_OVR)) #define I2C_FLAG_AF ((uint32_t)(1 << 16 | I2C_SR1_AF)) #define I2C_FLAG_ARLO ((uint32_t)(1 << 16 | I2C_SR1_ARLO)) #define I2C_FLAG_BERR ((uint32_t)(1 << 16 | I2C_SR1_BERR)) #define I2C_FLAG_TXE ((uint32_t)(1 << 16 | I2C_SR1_TXE)) #define I2C_FLAG_RXNE ((uint32_t)(1 << 16 | I2C_SR1_RXNE)) #define I2C_FLAG_STOPF ((uint32_t)(1 << 16 | I2C_SR1_STOPF)) #define I2C_FLAG_ADD10 ((uint32_t)(1 << 16 | I2C_SR1_ADD10)) #define I2C_FLAG_BTF ((uint32_t)(1 << 16 | I2C_SR1_BTF)) #define I2C_FLAG_ADDR ((uint32_t)(1 << 16 | I2C_SR1_ADDR)) #define I2C_FLAG_SB ((uint32_t)(1 << 16 | I2C_SR1_SB)) #define I2C_FLAG_DUALF ((uint32_t)(2 << 16 | I2C_SR2_DUALF)) #define I2C_FLAG_GENCALL ((uint32_t)(2 << 16 | I2C_SR2_GENCALL)) #define I2C_FLAG_TRA ((uint32_t)(2 << 16 | I2C_SR2_TRA)) #define I2C_FLAG_BUSY ((uint32_t)(2 << 16 | I2C_SR2_BUSY)) #define I2C_FLAG_MSL ((uint32_t)(2 << 16 | I2C_SR2_MSL)) #define I2C_FLAG_MASK ((uint32_t)0x0000FFFF) /** * @} */ /** @defgroup I2C_Clock_Speed_definition I2C_Clock_Speed_definition * @{ */ #define IS_I2C_CLOCK_SPEED(SPEED) (((SPEED) > 0) && ((SPEED) <= 400000)) /** * @} */ /** @defgroup I2C_Own_Address1_definition I2C_Own_Address1_definition * @{ */ #define IS_I2C_OWN_ADDRESS1(ADDRESS1) (((ADDRESS1) & (uint32_t)(0xFFFFFC00)) == 0) /** * @} */ /** @defgroup I2C_Own_Address2_definition I2C_Own_Address2_definition * @{ */ #define IS_I2C_OWN_ADDRESS2(ADDRESS2) (((ADDRESS2) & (uint32_t)(0xFFFFFF01)) == 0) /** * @} */ /** * @} */ /* Exported macro ------------------------------------------------------------*/ /** @defgroup I2C_Exported_Macros I2C Exported Macros * @{ */ /** @brief Reset I2C handle state * @param __HANDLE__: specifies the I2C Handle. * This parameter can be I2C where x: 1, 2, or 3 to select the I2C peripheral. * @retval None */ #define __HAL_I2C_RESET_HANDLE_STATE(__HANDLE__) ((__HANDLE__)->State = HAL_I2C_STATE_RESET) /** @brief Enable or disable the specified I2C interrupts. * @param __HANDLE__: specifies the I2C Handle. * This parameter can be I2Cx where x: 1 or 2 to select the I2C peripheral. * @param __INTERRUPT__: specifies the interrupt source to enable or disable. * This parameter can be one of the following values: * @arg I2C_IT_BUF: Buffer interrupt enable * @arg I2C_IT_EVT: Event interrupt enable * @arg I2C_IT_ERR: Error interrupt enable * @retval None */ #define __HAL_I2C_ENABLE_IT(__HANDLE__, __INTERRUPT__) SET_BIT((__HANDLE__)->Instance->CR2,(__INTERRUPT__)) #define __HAL_I2C_DISABLE_IT(__HANDLE__, __INTERRUPT__) CLEAR_BIT((__HANDLE__)->Instance->CR2, (__INTERRUPT__)) /** @brief Checks if the specified I2C interrupt source is enabled or disabled. * @param __HANDLE__: specifies the I2C Handle. * This parameter can be I2Cx where x: 1 or 2 to select the I2C peripheral. * @param __INTERRUPT__: specifies the I2C interrupt source to check. * This parameter can be one of the following values: * @arg I2C_IT_BUF: Buffer interrupt enable * @arg I2C_IT_EVT: Event interrupt enable * @arg I2C_IT_ERR: Error interrupt enable * @retval The new state of __INTERRUPT__ (TRUE or FALSE). */ #define __HAL_I2C_GET_IT_SOURCE(__HANDLE__, __INTERRUPT__) ((((__HANDLE__)->Instance->CR2 & (__INTERRUPT__)) == (__INTERRUPT__)) ? SET : RESET) /** @brief Checks whether the specified I2C flag is set or not. * @param __HANDLE__: specifies the I2C Handle. * This parameter can be I2Cx where x: 1 or 2 to select the I2C peripheral. * @param __FLAG__: specifies the flag to check. * This parameter can be one of the following values: * @arg I2C_FLAG_OVR: Overrun/Underrun flag * @arg I2C_FLAG_AF: Acknowledge failure flag * @arg I2C_FLAG_ARLO: Arbitration lost flag * @arg I2C_FLAG_BERR: Bus error flag * @arg I2C_FLAG_TXE: Data register empty flag * @arg I2C_FLAG_RXNE: Data register not empty flag * @arg I2C_FLAG_STOPF: Stop detection flag * @arg I2C_FLAG_ADD10: 10-bit header sent flag * @arg I2C_FLAG_BTF: Byte transfer finished flag * @arg I2C_FLAG_ADDR: Address sent flag * Address matched flag * @arg I2C_FLAG_SB: Start bit flag * @arg I2C_FLAG_DUALF: Dual flag * @arg I2C_FLAG_GENCALL: General call header flag * @arg I2C_FLAG_TRA: Transmitter/Receiver flag * @arg I2C_FLAG_BUSY: Bus busy flag * @arg I2C_FLAG_MSL: Master/Slave flag * @retval The new state of __FLAG__ (TRUE or FALSE). */ #define __HAL_I2C_GET_FLAG(__HANDLE__, __FLAG__) ((((uint8_t)((__FLAG__) >> 16)) == 0x01)?((((__HANDLE__)->Instance->SR1) & ((__FLAG__) & I2C_FLAG_MASK)) == ((__FLAG__) & I2C_FLAG_MASK)): \ ((((__HANDLE__)->Instance->SR2) & ((__FLAG__) & I2C_FLAG_MASK)) == ((__FLAG__) & I2C_FLAG_MASK))) /** @brief Clears the I2C pending flags which are cleared by writing 0 in a specific bit. * @param __HANDLE__: specifies the I2C Handle. * This parameter can be I2Cx where x: 1 or 2 to select the I2C peripheral. * @param __FLAG__: specifies the flag to clear. * This parameter can be any combination of the following values: * @arg I2C_FLAG_OVR: Overrun/Underrun flag (Slave mode) * @arg I2C_FLAG_AF: Acknowledge failure flag * @arg I2C_FLAG_ARLO: Arbitration lost flag (Master mode) * @arg I2C_FLAG_BERR: Bus error flag * @retval None */ #define __HAL_I2C_CLEAR_FLAG(__HANDLE__, __FLAG__) ((__HANDLE__)->Instance->SR1 = ~((__FLAG__) & I2C_FLAG_MASK)) /** @brief Clears the I2C ADDR pending flag. * @param __HANDLE__: specifies the I2C Handle. * This parameter can be I2Cx where x: 1 or 2 to select the I2C peripheral. * @retval None */ #define __HAL_I2C_CLEAR_ADDRFLAG(__HANDLE__) do{(__HANDLE__)->Instance->SR1;\ (__HANDLE__)->Instance->SR2;}while(0) /** @brief Clears the I2C STOPF pending flag. * @param __HANDLE__: specifies the I2C Handle. * This parameter can be I2Cx where x: 1 or 2 to select the I2C peripheral. * @retval None */ #define __HAL_I2C_CLEAR_STOPFLAG(__HANDLE__) do{(__HANDLE__)->Instance->SR1;\ SET_BIT((__HANDLE__)->Instance->CR1, I2C_CR1_PE);}while(0) /** @brief Enable the I2C peripheral. * @param __HANDLE__: specifies the I2C Handle. * This parameter can be I2Cx where x: 1 or 2 to select the I2C peripheral. * @retval None */ #define __HAL_I2C_ENABLE(__HANDLE__) SET_BIT((__HANDLE__)->Instance->CR1, I2C_CR1_PE) /** @brief Disable the I2C peripheral. * @param __HANDLE__: specifies the I2C Handle. * This parameter can be I2Cx where x: 1 or 2 to select the I2C peripheral. * @retval None */ #define __HAL_I2C_DISABLE(__HANDLE__) CLEAR_BIT((__HANDLE__)->Instance->CR1, I2C_CR1_PE) /** * @} */ /** @defgroup I2C_Private_Macros I2C Private Macros * @{ */ #define I2C_FREQRANGE(__PCLK__) ((__PCLK__)/1000000) #define I2C_RISE_TIME(__FREQRANGE__, __SPEED__) (((__SPEED__) <= 100000) ? ((__FREQRANGE__) + 1) : ((((__FREQRANGE__) * 300) / 1000) + 1)) #define I2C_SPEED_STANDARD(__PCLK__, __SPEED__) (((((__PCLK__)/((__SPEED__) << 1)) & I2C_CCR_CCR) < 4)? 4:((__PCLK__) / ((__SPEED__) << 1))) #define I2C_SPEED_FAST(__PCLK__, __SPEED__, __DUTYCYCLE__) (((__DUTYCYCLE__) == I2C_DUTYCYCLE_2)? ((__PCLK__) / ((__SPEED__) * 3)) : (((__PCLK__) / ((__SPEED__) * 25)) | I2C_DUTYCYCLE_16_9)) #define I2C_SPEED(__PCLK__, __SPEED__, __DUTYCYCLE__) (((__SPEED__) <= 100000)? (I2C_SPEED_STANDARD((__PCLK__), (__SPEED__))) : \ ((I2C_SPEED_FAST((__PCLK__), (__SPEED__), (__DUTYCYCLE__)) & I2C_CCR_CCR) == 0)? 1 : \ ((I2C_SPEED_FAST((__PCLK__), (__SPEED__), (__DUTYCYCLE__))) | I2C_CCR_FS)) #define I2C_7BIT_ADD_WRITE(__ADDRESS__) ((uint8_t)((__ADDRESS__) & (~I2C_OAR1_ADD0))) #define I2C_7BIT_ADD_READ(__ADDRESS__) ((uint8_t)((__ADDRESS__) | I2C_OAR1_ADD0)) #define I2C_10BIT_ADDRESS(__ADDRESS__) ((uint8_t)((uint16_t)((__ADDRESS__) & (uint16_t)(0x00FF)))) #define I2C_10BIT_HEADER_WRITE(__ADDRESS__) ((uint8_t)((uint16_t)((uint16_t)(((uint16_t)((__ADDRESS__) & (uint16_t)(0x0300))) >> 7) | (uint16_t)(0xF0)))) #define I2C_10BIT_HEADER_READ(__ADDRESS__) ((uint8_t)((uint16_t)((uint16_t)(((uint16_t)((__ADDRESS__) & (uint16_t)(0x0300))) >> 7) | (uint16_t)(0xF1)))) #define I2C_MEM_ADD_MSB(__ADDRESS__) ((uint8_t)((uint16_t)(((uint16_t)((__ADDRESS__) & (uint16_t)(0xFF00))) >> 8))) #define I2C_MEM_ADD_LSB(__ADDRESS__) ((uint8_t)((uint16_t)((__ADDRESS__) & (uint16_t)(0x00FF)))) /** * @} */ /* Exported functions --------------------------------------------------------*/ /** @addtogroup I2C_Exported_Functions * @{ */ /* Initialization/de-initialization functions **********************************/ /** @addtogroup I2C_Exported_Functions_Group1 * @{ */ HAL_StatusTypeDef HAL_I2C_Init(I2C_HandleTypeDef *hi2c); HAL_StatusTypeDef HAL_I2C_DeInit (I2C_HandleTypeDef *hi2c); void HAL_I2C_MspInit(I2C_HandleTypeDef *hi2c); void HAL_I2C_MspDeInit(I2C_HandleTypeDef *hi2c); /** * @} */ /* I/O operation functions *****************************************************/ /** @addtogroup I2C_Exported_Functions_Group2 * @{ */ /******* Blocking mode: Polling */ HAL_StatusTypeDef HAL_I2C_Master_Transmit(I2C_HandleTypeDef *hi2c, uint16_t DevAddress, uint8_t *pData, uint16_t Size, uint32_t Timeout); HAL_StatusTypeDef HAL_I2C_Master_Receive(I2C_HandleTypeDef *hi2c, uint16_t DevAddress, uint8_t *pData, uint16_t Size, uint32_t Timeout); HAL_StatusTypeDef HAL_I2C_Slave_Transmit(I2C_HandleTypeDef *hi2c, uint8_t *pData, uint16_t Size, uint32_t Timeout); HAL_StatusTypeDef HAL_I2C_Slave_Receive(I2C_HandleTypeDef *hi2c, uint8_t *pData, uint16_t Size, uint32_t Timeout); HAL_StatusTypeDef HAL_I2C_Mem_Write(I2C_HandleTypeDef *hi2c, uint16_t DevAddress, uint16_t MemAddress, uint16_t MemAddSize, uint8_t *pData, uint16_t Size, uint32_t Timeout); HAL_StatusTypeDef HAL_I2C_Mem_Read(I2C_HandleTypeDef *hi2c, uint16_t DevAddress, uint16_t MemAddress, uint16_t MemAddSize, uint8_t *pData, uint16_t Size, uint32_t Timeout); HAL_StatusTypeDef HAL_I2C_IsDeviceReady(I2C_HandleTypeDef *hi2c, uint16_t DevAddress, uint32_t Trials, uint32_t Timeout); /******* Non-Blocking mode: Interrupt */ HAL_StatusTypeDef HAL_I2C_Master_Transmit_IT(I2C_HandleTypeDef *hi2c, uint16_t DevAddress, uint8_t *pData, uint16_t Size); HAL_StatusTypeDef HAL_I2C_Master_Receive_IT(I2C_HandleTypeDef *hi2c, uint16_t DevAddress, uint8_t *pData, uint16_t Size); HAL_StatusTypeDef HAL_I2C_Slave_Transmit_IT(I2C_HandleTypeDef *hi2c, uint8_t *pData, uint16_t Size); HAL_StatusTypeDef HAL_I2C_Slave_Receive_IT(I2C_HandleTypeDef *hi2c, uint8_t *pData, uint16_t Size); HAL_StatusTypeDef HAL_I2C_Mem_Write_IT(I2C_HandleTypeDef *hi2c, uint16_t DevAddress, uint16_t MemAddress, uint16_t MemAddSize, uint8_t *pData, uint16_t Size); HAL_StatusTypeDef HAL_I2C_Mem_Read_IT(I2C_HandleTypeDef *hi2c, uint16_t DevAddress, uint16_t MemAddress, uint16_t MemAddSize, uint8_t *pData, uint16_t Size); /******* Non-Blocking mode: DMA */ HAL_StatusTypeDef HAL_I2C_Master_Transmit_DMA(I2C_HandleTypeDef *hi2c, uint16_t DevAddress, uint8_t *pData, uint16_t Size); HAL_StatusTypeDef HAL_I2C_Master_Receive_DMA(I2C_HandleTypeDef *hi2c, uint16_t DevAddress, uint8_t *pData, uint16_t Size); HAL_StatusTypeDef HAL_I2C_Slave_Transmit_DMA(I2C_HandleTypeDef *hi2c, uint8_t *pData, uint16_t Size); HAL_StatusTypeDef HAL_I2C_Slave_Receive_DMA(I2C_HandleTypeDef *hi2c, uint8_t *pData, uint16_t Size); HAL_StatusTypeDef HAL_I2C_Mem_Write_DMA(I2C_HandleTypeDef *hi2c, uint16_t DevAddress, uint16_t MemAddress, uint16_t MemAddSize, uint8_t *pData, uint16_t Size); HAL_StatusTypeDef HAL_I2C_Mem_Read_DMA(I2C_HandleTypeDef *hi2c, uint16_t DevAddress, uint16_t MemAddress, uint16_t MemAddSize, uint8_t *pData, uint16_t Size); /******* I2C IRQHandler and Callbacks used in non blocking modes (Interrupt and DMA) */ void HAL_I2C_EV_IRQHandler(I2C_HandleTypeDef *hi2c); void HAL_I2C_ER_IRQHandler(I2C_HandleTypeDef *hi2c); void HAL_I2C_MasterTxCpltCallback(I2C_HandleTypeDef *hi2c); void HAL_I2C_MasterRxCpltCallback(I2C_HandleTypeDef *hi2c); void HAL_I2C_SlaveTxCpltCallback(I2C_HandleTypeDef *hi2c); void HAL_I2C_SlaveRxCpltCallback(I2C_HandleTypeDef *hi2c); void HAL_I2C_MemTxCpltCallback(I2C_HandleTypeDef *hi2c); void HAL_I2C_MemRxCpltCallback(I2C_HandleTypeDef *hi2c); void HAL_I2C_ErrorCallback(I2C_HandleTypeDef *hi2c); /** * @} */ /* Peripheral Control and State functions **************************************/ /** @addtogroup I2C_Exported_Functions_Group3 * @{ */ HAL_I2C_StateTypeDef HAL_I2C_GetState(I2C_HandleTypeDef *hi2c); uint32_t HAL_I2C_GetError(I2C_HandleTypeDef *hi2c); /** * @} */ /** * @} */ /** * @} */ /** * @} */ #ifdef __cplusplus } #endif #endif /* __STM32L1xx_HAL_I2C_H */ /************************ (C) COPYRIGHT STMicroelectronics *****END OF FILE****/ ================================================ FILE: Zelig/mbed/TARGET_NUCLEO_L152RE/stm32l1xx_hal_i2s.h ================================================ /** ****************************************************************************** * @file stm32l1xx_hal_i2s.h * @author MCD Application Team * @version V1.0.0 * @date 5-September-2014 * @brief Header file of I2S HAL module. ****************************************************************************** * @attention * *

© COPYRIGHT(c) 2014 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. * ****************************************************************************** */ /* Define to prevent recursive inclusion -------------------------------------*/ #ifndef __STM32L1xx_HAL_I2S_H #define __STM32L1xx_HAL_I2S_H #ifdef __cplusplus extern "C" { #endif #if defined(STM32L100xC) || \ defined(STM32L151xC) || defined(STM32L151xCA) || defined(STM32L151xD) || defined(STM32L151xE) || \ defined(STM32L152xC) || defined(STM32L152xCA) || defined(STM32L152xD) || defined(STM32L152xE) || defined(STM32L151xE) || \ defined(STM32L162xC) || defined(STM32L162xCA) || defined(STM32L162xD) || defined(STM32L162xE) /* Includes ------------------------------------------------------------------*/ #include "stm32l1xx_hal_def.h" /** @addtogroup STM32L1xx_HAL_Driver * @{ */ /** @addtogroup I2S * @{ */ /* Exported types ------------------------------------------------------------*/ /** @defgroup I2S_Exported_Types I2S Exported Types * @{ */ /** * @brief I2S Init structure definition */ typedef struct { uint32_t Mode; /*!< Specifies the I2S operating mode. This parameter can be a value of @ref I2S_Mode */ uint32_t Standard; /*!< Specifies the standard used for the I2S communication. This parameter can be a value of @ref I2S_Standard */ uint32_t DataFormat; /*!< Specifies the data format for the I2S communication. This parameter can be a value of @ref I2S_Data_Format */ uint32_t MCLKOutput; /*!< Specifies whether the I2S MCLK output is enabled or not. This parameter can be a value of @ref I2S_MCLK_Output */ uint32_t AudioFreq; /*!< Specifies the frequency selected for the I2S communication. This parameter can be a value of @ref I2S_Audio_Frequency */ uint32_t CPOL; /*!< Specifies the idle state of the I2S clock. This parameter can be a value of @ref I2S_Clock_Polarity */ }I2S_InitTypeDef; /** * @brief HAL State structures definition */ typedef enum { HAL_I2S_STATE_RESET = 0x00, /*!< I2S not yet initialized or disabled */ HAL_I2S_STATE_READY = 0x01, /*!< I2S initialized and ready for use */ HAL_I2S_STATE_BUSY = 0x02, /*!< I2S internal process is ongoing */ HAL_I2S_STATE_BUSY_TX = 0x12, /*!< Data Transmission process is ongoing */ HAL_I2S_STATE_BUSY_RX = 0x22, /*!< Data Reception process is ongoing */ HAL_I2S_STATE_TIMEOUT = 0x03, /*!< I2S pause state: used in case of DMA */ HAL_I2S_STATE_ERROR = 0x04 /*!< I2S error state */ }HAL_I2S_StateTypeDef; /** * @brief HAL I2S Error Code structure definition */ typedef enum { HAL_I2S_ERROR_NONE = 0x00, /*!< No error */ HAL_I2S_ERROR_UDR = 0x01, /*!< I2S Underrun error */ HAL_I2S_ERROR_OVR = 0x02, /*!< I2S Overrun error */ HAL_I2S_ERROR_FRE = 0x04, /*!< I2S Frame format error */ HAL_I2S_ERROR_DMA = 0x08 /*!< DMA transfer error */ }HAL_I2S_ErrorTypeDef; /** * @brief I2S handle Structure definition */ typedef struct { SPI_TypeDef *Instance; /* I2S registers base address */ I2S_InitTypeDef Init; /* I2S communication parameters */ uint16_t *pTxBuffPtr; /* Pointer to I2S Tx transfer buffer */ __IO uint16_t TxXferSize; /* I2S Tx transfer size */ __IO uint16_t TxXferCount; /* I2S Tx transfer Counter */ uint16_t *pRxBuffPtr; /* Pointer to I2S Rx transfer buffer */ __IO uint16_t RxXferSize; /* I2S Rx transfer size */ __IO uint16_t RxXferCount; /* I2S Rx transfer counter (This field is initialized at the same value as transfer size at the beginning of the transfer and decremented when a sample is received. NbSamplesReceived = RxBufferSize-RxBufferCount) */ DMA_HandleTypeDef *hdmatx; /* I2S Tx DMA handle parameters */ DMA_HandleTypeDef *hdmarx; /* I2S Rx DMA handle parameters */ __IO HAL_LockTypeDef Lock; /* I2S locking object */ __IO HAL_I2S_StateTypeDef State; /* I2S communication state */ __IO HAL_I2S_ErrorTypeDef ErrorCode; /* I2S Error code */ }I2S_HandleTypeDef; /** * @} */ /* Exported constants --------------------------------------------------------*/ /** @defgroup I2S_Exported_Constants I2S Exported Constants * @{ */ /** @defgroup I2S_Mode I2S Mode * @{ */ #define I2S_MODE_SLAVE_TX ((uint32_t)0x00000000) #define I2S_MODE_SLAVE_RX ((uint32_t)0x00000100) #define I2S_MODE_MASTER_TX ((uint32_t)0x00000200) #define I2S_MODE_MASTER_RX ((uint32_t)0x00000300) #define IS_I2S_MODE(MODE) (((MODE) == I2S_MODE_SLAVE_TX) || \ ((MODE) == I2S_MODE_SLAVE_RX) || \ ((MODE) == I2S_MODE_MASTER_TX) || \ ((MODE) == I2S_MODE_MASTER_RX)) /** * @} */ /** @defgroup I2S_Standard I2S Standard * @{ */ #define I2S_STANDARD_PHILIPS ((uint32_t)0x00000000) #define I2S_STANDARD_MSB ((uint32_t) SPI_I2SCFGR_I2SSTD_0) #define I2S_STANDARD_LSB ((uint32_t) SPI_I2SCFGR_I2SSTD_1) #define I2S_STANDARD_PCM_SHORT ((uint32_t)(SPI_I2SCFGR_I2SSTD_0 |\ SPI_I2SCFGR_I2SSTD_1)) #define I2S_STANDARD_PCM_LONG ((uint32_t)(SPI_I2SCFGR_I2SSTD_0 |\ SPI_I2SCFGR_I2SSTD_1 |\ SPI_I2SCFGR_PCMSYNC)) #define IS_I2S_STANDARD(STANDARD) (((STANDARD) == I2S_STANDARD_PHILIPS) || \ ((STANDARD) == I2S_STANDARD_MSB) || \ ((STANDARD) == I2S_STANDARD_LSB) || \ ((STANDARD) == I2S_STANDARD_PCM_SHORT) || \ ((STANDARD) == I2S_STANDARD_PCM_LONG)) /** @defgroup I2S_Legacy I2S Legacy * @{ */ #define I2S_STANDARD_PHILLIPS I2S_STANDARD_PHILIPS /** * @} */ /** * @} */ /** @defgroup I2S_Data_Format I2S Data Format * @{ */ #define I2S_DATAFORMAT_16B ((uint32_t)0x00000000) #define I2S_DATAFORMAT_16B_EXTENDED ((uint32_t) SPI_I2SCFGR_CHLEN) #define I2S_DATAFORMAT_24B ((uint32_t)(SPI_I2SCFGR_CHLEN | SPI_I2SCFGR_DATLEN_0)) #define I2S_DATAFORMAT_32B ((uint32_t)(SPI_I2SCFGR_CHLEN | SPI_I2SCFGR_DATLEN_1)) #define IS_I2S_DATA_FORMAT(FORMAT) (((FORMAT) == I2S_DATAFORMAT_16B) || \ ((FORMAT) == I2S_DATAFORMAT_16B_EXTENDED) || \ ((FORMAT) == I2S_DATAFORMAT_24B) || \ ((FORMAT) == I2S_DATAFORMAT_32B)) /** * @} */ /** @defgroup I2S_MCLK_Output I2S MCLK Output * @{ */ #define I2S_MCLKOUTPUT_ENABLE ((uint32_t)SPI_I2SPR_MCKOE) #define I2S_MCLKOUTPUT_DISABLE ((uint32_t)0x00000000) #define IS_I2S_MCLK_OUTPUT(OUTPUT) (((OUTPUT) == I2S_MCLKOUTPUT_ENABLE) || \ ((OUTPUT) == I2S_MCLKOUTPUT_DISABLE)) /** * @} */ /** @defgroup I2S_Audio_Frequency I2S Audio Frequency * @{ */ #define I2S_AUDIOFREQ_192K ((uint32_t)192000) #define I2S_AUDIOFREQ_96K ((uint32_t)96000) #define I2S_AUDIOFREQ_48K ((uint32_t)48000) #define I2S_AUDIOFREQ_44K ((uint32_t)44100) #define I2S_AUDIOFREQ_32K ((uint32_t)32000) #define I2S_AUDIOFREQ_22K ((uint32_t)22050) #define I2S_AUDIOFREQ_16K ((uint32_t)16000) #define I2S_AUDIOFREQ_11K ((uint32_t)11025) #define I2S_AUDIOFREQ_8K ((uint32_t)8000) #define I2S_AUDIOFREQ_DEFAULT ((uint32_t)2) #define IS_I2S_AUDIO_FREQ(FREQ) ((((FREQ) >= I2S_AUDIOFREQ_8K) && \ ((FREQ) <= I2S_AUDIOFREQ_192K)) || \ ((FREQ) == I2S_AUDIOFREQ_DEFAULT)) /** * @} */ /** @defgroup I2S_Clock_Polarity I2S Clock Polarity * @{ */ #define I2S_CPOL_LOW ((uint32_t)0x00000000) #define I2S_CPOL_HIGH ((uint32_t)SPI_I2SCFGR_CKPOL) #define IS_I2S_CPOL(CPOL) (((CPOL) == I2S_CPOL_LOW) || \ ((CPOL) == I2S_CPOL_HIGH)) /** * @} */ /** @defgroup I2S_Interrupt_configuration_definition I2S Interrupt configuration definition * @{ */ #define I2S_IT_TXE SPI_CR2_TXEIE #define I2S_IT_RXNE SPI_CR2_RXNEIE #define I2S_IT_ERR SPI_CR2_ERRIE /** * @} */ /** @defgroup I2S_Flag_definition I2S Flag definition * @{ */ #define I2S_FLAG_TXE SPI_SR_TXE #define I2S_FLAG_RXNE SPI_SR_RXNE #define I2S_FLAG_UDR SPI_SR_UDR #define I2S_FLAG_OVR SPI_SR_OVR #define I2S_FLAG_FRE SPI_SR_FRE #define I2S_FLAG_CHSIDE SPI_SR_CHSIDE #define I2S_FLAG_BSY SPI_SR_BSY /** * @} */ /** * @} */ /* Exported macro ------------------------------------------------------------*/ /** @defgroup I2S_Exported_macros I2S Exported Macros * @{ */ /** @brief Reset I2S handle state * @param __HANDLE__: specifies the I2S Handle. * @retval None */ #define __HAL_I2S_RESET_HANDLE_STATE(__HANDLE__) ((__HANDLE__)->State = HAL_I2S_STATE_RESET) /** @brief Enable or disable the specified SPI peripheral (in I2S mode). * @param __HANDLE__: specifies the I2S Handle. * @retval None */ #define __HAL_I2S_ENABLE(__HANDLE__) (SET_BIT((__HANDLE__)->Instance->I2SCFGR, SPI_I2SCFGR_I2SE)) #define __HAL_I2S_DISABLE(__HANDLE__) (CLEAR_BIT((__HANDLE__)->Instance->I2SCFGR, SPI_I2SCFGR_I2SE)) /** @brief Enable or disable the specified I2S interrupts. * @param __HANDLE__: specifies the I2S Handle. * @param __INTERRUPT__: specifies the interrupt source to enable or disable. * This parameter can be one of the following values: * @arg I2S_IT_TXE: Tx buffer empty interrupt enable * @arg I2S_IT_RXNE: RX buffer not empty interrupt enable * @arg I2S_IT_ERR: Error interrupt enable * @retval None */ #define __HAL_I2S_ENABLE_IT(__HANDLE__, __INTERRUPT__) (SET_BIT((__HANDLE__)->Instance->CR2,(__INTERRUPT__))) #define __HAL_I2S_DISABLE_IT(__HANDLE__, __INTERRUPT__) (CLEAR_BIT((__HANDLE__)->Instance->CR2,(__INTERRUPT__))) /** @brief Checks if the specified I2S interrupt source is enabled or disabled. * @param __HANDLE__: specifies the I2S Handle. * This parameter can be I2S where x: 1, 2, or 3 to select the I2S peripheral. * @param __INTERRUPT__: specifies the I2S interrupt source to check. * This parameter can be one of the following values: * @arg I2S_IT_TXE: Tx buffer empty interrupt enable * @arg I2S_IT_RXNE: RX buffer not empty interrupt enable * @arg I2S_IT_ERR: Error interrupt enable * @retval The new state of __IT__ (TRUE or FALSE). */ #define __HAL_I2S_GET_IT_SOURCE(__HANDLE__, __INTERRUPT__) ((((__HANDLE__)->Instance->CR2 & (__INTERRUPT__)) == (__INTERRUPT__)) ? SET : RESET) /** @brief Checks whether the specified I2S flag is set or not. * @param __HANDLE__: specifies the I2S Handle. * @param __FLAG__: specifies the flag to check. * This parameter can be one of the following values: * @arg I2S_FLAG_RXNE: Receive buffer not empty flag * @arg I2S_FLAG_TXE: Transmit buffer empty flag * @arg I2S_FLAG_UDR: Underrun flag * @arg I2S_FLAG_OVR: Overrun flag * @arg I2S_FLAG_FRE: Frame error flag * @arg I2S_FLAG_CHSIDE: Channel Side flag * @arg I2S_FLAG_BSY: Busy flag * @retval The new state of __FLAG__ (TRUE or FALSE). */ #define __HAL_I2S_GET_FLAG(__HANDLE__, __FLAG__) ((((__HANDLE__)->Instance->SR) & (__FLAG__)) == (__FLAG__)) /** @brief Clears the I2S OVR pending flag. * @param __HANDLE__: specifies the I2S Handle. * @retval None */ #define __HAL_I2S_CLEAR_OVRFLAG(__HANDLE__) do{__IO uint32_t tmpreg = (__HANDLE__)->Instance->DR;\ tmpreg = (__HANDLE__)->Instance->SR;\ }while(0) /** @brief Clears the I2S UDR pending flag. * @param __HANDLE__: specifies the I2S Handle. * @retval None */ #define __HAL_I2S_CLEAR_UDRFLAG(__HANDLE__)((__HANDLE__)->Instance->SR) /** * @} */ /* Exported functions --------------------------------------------------------*/ /** @addtogroup I2S_Exported_Functions * @{ */ /** @addtogroup I2S_Exported_Functions_Group1 * @{ */ /* Initialization/de-initialization functions ********************************/ HAL_StatusTypeDef HAL_I2S_Init(I2S_HandleTypeDef *hi2s); HAL_StatusTypeDef HAL_I2S_DeInit (I2S_HandleTypeDef *hi2s); void HAL_I2S_MspInit(I2S_HandleTypeDef *hi2s); void HAL_I2S_MspDeInit(I2S_HandleTypeDef *hi2s); /** * @} */ /** @addtogroup I2S_Exported_Functions_Group2 * @{ */ /* I/O operation functions ***************************************************/ /* Blocking mode: Polling */ HAL_StatusTypeDef HAL_I2S_Transmit(I2S_HandleTypeDef *hi2s, uint16_t *pData, uint16_t Size, uint32_t Timeout); HAL_StatusTypeDef HAL_I2S_Receive(I2S_HandleTypeDef *hi2s, uint16_t *pData, uint16_t Size, uint32_t Timeout); /* Non-Blocking mode: Interrupt */ HAL_StatusTypeDef HAL_I2S_Transmit_IT(I2S_HandleTypeDef *hi2s, uint16_t *pData, uint16_t Size); HAL_StatusTypeDef HAL_I2S_Receive_IT(I2S_HandleTypeDef *hi2s, uint16_t *pData, uint16_t Size); void HAL_I2S_IRQHandler(I2S_HandleTypeDef *hi2s); /* Non-Blocking mode: DMA */ HAL_StatusTypeDef HAL_I2S_Transmit_DMA(I2S_HandleTypeDef *hi2s, uint16_t *pData, uint16_t Size); HAL_StatusTypeDef HAL_I2S_Receive_DMA(I2S_HandleTypeDef *hi2s, uint16_t *pData, uint16_t Size); HAL_StatusTypeDef HAL_I2S_DMAPause(I2S_HandleTypeDef *hi2s); HAL_StatusTypeDef HAL_I2S_DMAResume(I2S_HandleTypeDef *hi2s); HAL_StatusTypeDef HAL_I2S_DMAStop(I2S_HandleTypeDef *hi2s); /* Callbacks used in non blocking modes (Interrupt and DMA) *******************/ void HAL_I2S_TxHalfCpltCallback(I2S_HandleTypeDef *hi2s); void HAL_I2S_TxCpltCallback(I2S_HandleTypeDef *hi2s); void HAL_I2S_RxHalfCpltCallback(I2S_HandleTypeDef *hi2s); void HAL_I2S_RxCpltCallback(I2S_HandleTypeDef *hi2s); void HAL_I2S_ErrorCallback(I2S_HandleTypeDef *hi2s); /** * @} */ /** @addtogroup I2S_Exported_Functions_Group3 * @{ */ /* Peripheral Control and State functions ************************************/ HAL_I2S_StateTypeDef HAL_I2S_GetState(I2S_HandleTypeDef *hi2s); HAL_I2S_ErrorTypeDef HAL_I2S_GetError(I2S_HandleTypeDef *hi2s); /** * @} */ /** * @} */ /** * @} */ /** * @} */ #endif /* STM32L100xC || STM32L151xC || STM32L151xCA || STM32L151xD || STM32L151xE ||\\ STM32L152xC || STM32L152xCA || STM32L152xD || STM32L152xE || STM32L151xE ||\\ STM32L162xC || STM32L162xCA || STM32L162xD || STM32L162xE */ #ifdef __cplusplus } #endif #endif /* __STM32L1xx_HAL_I2S_H */ /************************ (C) COPYRIGHT STMicroelectronics *****END OF FILE****/ ================================================ FILE: Zelig/mbed/TARGET_NUCLEO_L152RE/stm32l1xx_hal_irda.h ================================================ /** ****************************************************************************** * @file stm32l1xx_hal_irda.h * @author MCD Application Team * @version V1.0.0 * @date 5-September-2014 * @brief This file contains all the functions prototypes for the IRDA * firmware library. ****************************************************************************** * @attention * *

© COPYRIGHT(c) 2014 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. * ****************************************************************************** */ /* Define to prevent recursive inclusion -------------------------------------*/ #ifndef __STM32L1xx_HAL_IRDA_H #define __STM32L1xx_HAL_IRDA_H #ifdef __cplusplus extern "C" { #endif /* Includes ------------------------------------------------------------------*/ #include "stm32l1xx_hal_def.h" /** @addtogroup STM32L1xx_HAL_Driver * @{ */ /** @addtogroup IRDA * @{ */ /* Exported types ------------------------------------------------------------*/ /** @defgroup IRDA_Exported_Types IRDA Exported Types * @{ */ /** * @brief IRDA Init Structure definition */ typedef struct { uint32_t BaudRate; /*!< This member configures the IRDA communication baud rate. The baud rate is computed using the following formula: - IntegerDivider = ((PCLKx) / (8 * (hirda->Init.BaudRate))) - FractionalDivider = ((IntegerDivider - ((uint32_t) IntegerDivider)) * 8) + 0.5 */ uint32_t WordLength; /*!< Specifies the number of data bits transmitted or received in a frame. This parameter can be a value of @ref IRDA_Word_Length */ uint32_t Parity; /*!< Specifies the parity mode. This parameter can be a value of @ref IRDA_Parity @note When parity is enabled, the computed parity is inserted at the MSB position of the transmitted data (9th bit when the word length is set to 9 data bits; 8th bit when the word length is set to 8 data bits). */ uint32_t Mode; /*!< Specifies wether the Receive or Transmit mode is enabled or disabled. This parameter can be a value of @ref IRDA_Transfer_Mode */ uint8_t Prescaler; /*!< Specifies the Prescaler */ uint32_t IrDAMode; /*!< Specifies the IrDA mode This parameter can be a value of @ref IRDA_Low_Power */ }IRDA_InitTypeDef; /** * @brief HAL IRDA State structures definition */ typedef enum { HAL_IRDA_STATE_RESET = 0x00, /*!< Peripheral is not initialized */ HAL_IRDA_STATE_READY = 0x01, /*!< Peripheral Initialized and ready for use */ HAL_IRDA_STATE_BUSY = 0x02, /*!< an internal process is ongoing */ HAL_IRDA_STATE_BUSY_TX = 0x12, /*!< Data Transmission process is ongoing */ HAL_IRDA_STATE_BUSY_RX = 0x22, /*!< Data Reception process is ongoing */ HAL_IRDA_STATE_BUSY_TX_RX = 0x32, /*!< Data Transmission and Reception process is ongoing */ HAL_IRDA_STATE_TIMEOUT = 0x03, /*!< Timeout state */ HAL_IRDA_STATE_ERROR = 0x04 /*!< Error */ }HAL_IRDA_StateTypeDef; /** * @brief HAL IRDA Error Code structure definition */ typedef enum { HAL_IRDA_ERROR_NONE = 0x00, /*!< No error */ HAL_IRDA_ERROR_PE = 0x01, /*!< Parity error */ HAL_IRDA_ERROR_NE = 0x02, /*!< Noise error */ HAL_IRDA_ERROR_FE = 0x04, /*!< frame error */ HAL_IRDA_ERROR_ORE = 0x08, /*!< Overrun error */ HAL_IRDA_ERROR_DMA = 0x10 /*!< DMA transfer error */ }HAL_IRDA_ErrorTypeDef; /** * @brief IRDA handle Structure definition */ typedef struct { USART_TypeDef *Instance; /* USART registers base address */ IRDA_InitTypeDef Init; /* IRDA communication parameters */ uint8_t *pTxBuffPtr; /* Pointer to IRDA Tx transfer Buffer */ uint16_t TxXferSize; /* IRDA Tx Transfer size */ uint16_t TxXferCount; /* IRDA Tx Transfer Counter */ uint8_t *pRxBuffPtr; /* Pointer to IRDA Rx transfer Buffer */ uint16_t RxXferSize; /* IRDA Rx Transfer size */ uint16_t RxXferCount; /* IRDA Rx Transfer Counter */ DMA_HandleTypeDef *hdmatx; /* IRDA Tx DMA Handle parameters */ DMA_HandleTypeDef *hdmarx; /* IRDA Rx DMA Handle parameters */ HAL_LockTypeDef Lock; /* Locking object */ __IO HAL_IRDA_StateTypeDef State; /* IRDA communication state */ __IO HAL_IRDA_ErrorTypeDef ErrorCode; /* IRDA Error code */ }IRDA_HandleTypeDef; /** * @} */ /* Exported constants --------------------------------------------------------*/ /** @defgroup IRDA_Exported_Constants IRDA Exported constants * @{ */ /** @defgroup IRDA_Word_Length IRDA Word Length * @{ */ #define IRDA_WORDLENGTH_8B ((uint32_t)0x00000000) #define IRDA_WORDLENGTH_9B ((uint32_t)USART_CR1_M) #define IS_IRDA_WORD_LENGTH(LENGTH) (((LENGTH) == IRDA_WORDLENGTH_8B) || \ ((LENGTH) == IRDA_WORDLENGTH_9B)) /** * @} */ /** @defgroup IRDA_Parity IRDA Parity * @{ */ #define IRDA_PARITY_NONE ((uint32_t)0x00000000) #define IRDA_PARITY_EVEN ((uint32_t)USART_CR1_PCE) #define IRDA_PARITY_ODD ((uint32_t)(USART_CR1_PCE | USART_CR1_PS)) #define IS_IRDA_PARITY(PARITY) (((PARITY) == IRDA_PARITY_NONE) || \ ((PARITY) == IRDA_PARITY_EVEN) || \ ((PARITY) == IRDA_PARITY_ODD)) /** * @} */ /** @defgroup IRDA_Transfer_Mode IRDA Transfer Mode * @{ */ #define IRDA_MODE_RX ((uint32_t)USART_CR1_RE) #define IRDA_MODE_TX ((uint32_t)USART_CR1_TE) #define IRDA_MODE_TX_RX ((uint32_t)(USART_CR1_TE |USART_CR1_RE)) #define IS_IRDA_MODE(MODE) ((((MODE) & (uint32_t)0x0000FFF3) == 0x00) && ((MODE) != (uint32_t)0x000000)) /** * @} */ /** @defgroup IRDA_Low_Power IRDA Low Power * @{ */ #define IRDA_POWERMODE_LOWPOWER ((uint32_t)USART_CR3_IRLP) #define IRDA_POWERMODE_NORMAL ((uint32_t)0x00000000) #define IS_IRDA_POWERMODE(MODE) (((MODE) == IRDA_POWERMODE_LOWPOWER) || \ ((MODE) == IRDA_POWERMODE_NORMAL)) /** * @} */ /** @defgroup IRDA_Flags IRDA Flags * Elements values convention: 0xXXXX * - 0xXXXX : Flag mask in the SR register * @{ */ #define IRDA_FLAG_TXE ((uint32_t)USART_SR_TXE) #define IRDA_FLAG_TC ((uint32_t)USART_SR_TC) #define IRDA_FLAG_RXNE ((uint32_t)USART_SR_RXNE) #define IRDA_FLAG_IDLE ((uint32_t)USART_SR_IDLE) #define IRDA_FLAG_ORE ((uint32_t)USART_SR_ORE) #define IRDA_FLAG_NE ((uint32_t)USART_SR_NE) #define IRDA_FLAG_FE ((uint32_t)USART_SR_FE) #define IRDA_FLAG_PE ((uint32_t)USART_SR_PE) /** * @} */ /** @defgroup IRDA_Interrupt_definition IRDA Interrupt Definitions * Elements values convention: 0xY000XXXX * - XXXX : Interrupt mask in the XX register * - Y : Interrupt source register (4 bits) * - 01: CR1 register * - 10: CR2 register * - 11: CR3 register * * @{ */ #define IRDA_IT_PE ((uint32_t)0x10000100) #define IRDA_IT_TXE ((uint32_t)0x10000080) #define IRDA_IT_TC ((uint32_t)0x10000040) #define IRDA_IT_RXNE ((uint32_t)0x10000020) #define IRDA_IT_IDLE ((uint32_t)0x10000010) #define IRDA_IT_LBD ((uint32_t)0x20000040) #define IRDA_IT_CTS ((uint32_t)0x30000400) #define IRDA_IT_ERR ((uint32_t)0x30000001) /** * @} */ /** @defgroup IRDA_Interruption_Mask IRDA interruptions flag mask * @{ */ #define IRDA_IT_MASK ((uint32_t)0x0000FFFF) /** * @} */ /** * @} */ /* Exported macro ------------------------------------------------------------*/ /** @defgroup IRDA_Exported_Macros IRDA Exported Macros * @{ */ /** @brief Reset IRDA handle state * @param __HANDLE__: specifies the IRDA Handle. * This parameter can be USARTx with x: 1, 2 or 3, or UARTy with y:4 or 5 to select the USART or * UART peripheral (availability depending on device for UARTy). * @retval None */ #define __HAL_IRDA_RESET_HANDLE_STATE(__HANDLE__) ((__HANDLE__)->State = HAL_IRDA_STATE_RESET) /** @brief Flushs the IRDA DR register * @param __HANDLE__: specifies the USART Handle. * This parameter can be USARTx with x: 1, 2 or 3, or UARTy with y:4 or 5 to select the USART or * UART peripheral (availability depending on device for UARTy). */ #define __HAL_IRDA_FLUSH_DRREGISTER(__HANDLE__) ((__HANDLE__)->Instance->DR) /** @brief Checks whether the specified IRDA flag is set or not. * @param __HANDLE__: specifies the IRDA Handle. * This parameter can be USARTx with x: 1, 2 or 3, or UARTy with y:4 or 5 to select the USART or * UART peripheral (availability depending on device for UARTy). * @param __FLAG__: specifies the flag to check. * This parameter can be one of the following values: * @arg IRDA_FLAG_TXE: Transmit data register empty flag * @arg IRDA_FLAG_TC: Transmission Complete flag * @arg IRDA_FLAG_RXNE: Receive data register not empty flag * @arg IRDA_FLAG_IDLE: Idle Line detection flag * @arg IRDA_FLAG_ORE: OverRun Error flag * @arg IRDA_FLAG_NE: Noise Error flag * @arg IRDA_FLAG_FE: Framing Error flag * @arg IRDA_FLAG_PE: Parity Error flag * @retval The new state of __FLAG__ (TRUE or FALSE). */ #define __HAL_IRDA_GET_FLAG(__HANDLE__, __FLAG__) (((__HANDLE__)->Instance->SR & (__FLAG__)) == (__FLAG__)) /** @brief Clears the specified IRDA pending flag. * @param __HANDLE__: specifies the IRDA Handle. * This parameter can be USARTx with x: 1, 2 or 3, or UARTy with y:4 or 5 to select the USART or * UART peripheral (availability depending on device for UARTy). * @param __FLAG__: specifies the flag to check. * This parameter can be any combination of the following values: * @arg IRDA_FLAG_TC: Transmission Complete flag. * @arg IRDA_FLAG_RXNE: Receive data register not empty flag. * * @note PE (Parity error), FE (Framing error), NE (Noise error), ORE (OverRun * error) and IDLE (Idle line detected) flags are cleared by software * sequence: a read operation to USART_SR register followed by a read * operation to USART_DR register. * @note RXNE flag can be also cleared by a read to the USART_DR register. * @note TC flag can be also cleared by software sequence: a read operation to * USART_SR register followed by a write operation to USART_DR register. * @note TXE flag is cleared only by a write to the USART_DR register. * * @retval None */ #define __HAL_IRDA_CLEAR_FLAG(__HANDLE__, __FLAG__) ((__HANDLE__)->Instance->SR = ~(__FLAG__)) /** @brief Clear the IRDA PE pending flag. * @param __HANDLE__: specifies the IRDA Handle. * This parameter can be USARTx with x: 1, 2 or 3, or UARTy with y:4 or 5 to select the USART or * UART peripheral (availability depending on device for UARTy). * @retval None */ #define __HAL_IRDA_CLEAR_PEFLAG(__HANDLE__) do{(__HANDLE__)->Instance->SR;\ (__HANDLE__)->Instance->DR;}while(0) /** @brief Clear the IRDA FE pending flag. * @param __HANDLE__: specifies the IRDA Handle. * This parameter can be USARTx with x: 1, 2 or 3, or UARTy with y:4 or 5 to select the USART or * UART peripheral (availability depending on device for UARTy). * @retval None */ #define __HAL_IRDA_CLEAR_FEFLAG(__HANDLE__) __HAL_IRDA_CLEAR_PEFLAG(__HANDLE__) /** @brief Clear the IRDA NE pending flag. * @param __HANDLE__: specifies the IRDA Handle. * This parameter can be USARTx with x: 1, 2 or 3, or UARTy with y:4 or 5 to select the USART or * UART peripheral (availability depending on device for UARTy). * @retval None */ #define __HAL_IRDA_CLEAR_NEFLAG(__HANDLE__) __HAL_IRDA_CLEAR_PEFLAG(__HANDLE__) /** @brief Clear the IRDA ORE pending flag. * @param __HANDLE__: specifies the IRDA Handle. * This parameter can be USARTx with x: 1, 2 or 3, or UARTy with y:4 or 5 to select the USART or * UART peripheral (availability depending on device for UARTy). * @retval None */ #define __HAL_IRDA_CLEAR_OREFLAG(__HANDLE__) __HAL_IRDA_CLEAR_PEFLAG(__HANDLE__) /** @brief Clear the IRDA IDLE pending flag. * @param __HANDLE__: specifies the IRDA Handle. * This parameter can be USARTx with x: 1, 2 or 3, or UARTy with y:4 or 5 to select the USART or * UART peripheral (availability depending on device for UARTy). * @retval None */ #define __HAL_IRDA_CLEAR_IDLEFLAG(__HANDLE__) __HAL_IRDA_CLEAR_PEFLAG(__HANDLE__) /** @brief Enables the specified IRDA interrupt. * @param __HANDLE__: specifies the IRDA Handle. * This parameter can be USARTx with x: 1, 2 or 3, or UARTy with y:4 or 5 to select the USART or * UART peripheral (availability depending on device for UARTy). * @param __INTERRUPT__: specifies the IRDA interrupt source to enable. * This parameter can be one of the following values: * @arg IRDA_IT_TXE: Transmit Data Register empty interrupt * @arg IRDA_IT_TC: Transmission complete interrupt * @arg IRDA_IT_RXNE: Receive Data register not empty interrupt * @arg IRDA_IT_IDLE: Idle line detection interrupt * @arg IRDA_IT_PE: Parity Error interrupt * @arg IRDA_IT_ERR: Error interrupt(Frame error, noise error, overrun error) * @retval None */ #define __HAL_IRDA_ENABLE_IT(__HANDLE__, __INTERRUPT__) ((((__INTERRUPT__) >> 28) == 1)? ((__HANDLE__)->Instance->CR1 |= ((__INTERRUPT__) & IRDA_IT_MASK)): \ (((__INTERRUPT__) >> 28) == 2)? ((__HANDLE__)->Instance->CR2 |= ((__INTERRUPT__) & IRDA_IT_MASK)): \ ((__HANDLE__)->Instance->CR3 |= ((__INTERRUPT__) & IRDA_IT_MASK))) /** @brief Disables the specified IRDA interrupt. * @param __HANDLE__: specifies the IRDA Handle. * This parameter can be USARTx with x: 1, 2 or 3, or UARTy with y:4 or 5 to select the USART or * UART peripheral (availability depending on device for UARTy). * @param __INTERRUPT__: specifies the IRDA interrupt source to disable. * This parameter can be one of the following values: * @arg IRDA_IT_TXE: Transmit Data Register empty interrupt * @arg IRDA_IT_TC: Transmission complete interrupt * @arg IRDA_IT_RXNE: Receive Data register not empty interrupt * @arg IRDA_IT_IDLE: Idle line detection interrupt * @arg IRDA_IT_PE: Parity Error interrupt * @arg IRDA_IT_ERR: Error interrupt(Frame error, noise error, overrun error) * @retval None */ #define __HAL_IRDA_DISABLE_IT(__HANDLE__, __INTERRUPT__) ((((__INTERRUPT__) >> 28) == 1)? ((__HANDLE__)->Instance->CR1 &= ~((__INTERRUPT__) & IRDA_IT_MASK)): \ (((__INTERRUPT__) >> 28) == 2)? ((__HANDLE__)->Instance->CR2 &= ~((__INTERRUPT__) & IRDA_IT_MASK)): \ ((__HANDLE__)->Instance->CR3 &= ~ ((__INTERRUPT__) & IRDA_IT_MASK))) /** @brief Checks whether the specified IRDA interrupt has occurred or not. * @param __HANDLE__: specifies the IRDA Handle. * This parameter can be USARTx with x: 1, 2 or 3, or UARTy with y:4 or 5 to select the USART or * UART peripheral (availability depending on device for UARTy). * @param __IT__: specifies the IRDA interrupt source to check. * This parameter can be one of the following values: * @arg IRDA_IT_TXE: Transmit Data Register empty interrupt * @arg IRDA_IT_TC: Transmission complete interrupt * @arg IRDA_IT_RXNE: Receive Data register not empty interrupt * @arg IRDA_IT_IDLE: Idle line detection interrupt * @arg USART_IT_ERR: Error interrupt * @arg IRDA_IT_PE: Parity Error interrupt * @retval The new state of __IT__ (TRUE or FALSE). */ #define __HAL_IRDA_GET_IT_SOURCE(__HANDLE__, __IT__) (((((__IT__) >> 28) == 1)? (__HANDLE__)->Instance->CR1:(((((uint32_t)(__IT__)) >> 28) == 2)? \ (__HANDLE__)->Instance->CR2 : (__HANDLE__)->Instance->CR3)) & (((uint32_t)(__IT__)) & IRDA_IT_MASK)) /** @brief Enable UART/USART associated to IRDA Handle * @param __HANDLE__: specifies the IRDA Handle. * This parameter can be USARTx with x: 1, 2 or 3, or UARTy with y:4 or 5 to select the USART or * UART peripheral (availability depending on device for UARTy). * @retval None */ #define __HAL_IRDA_ENABLE(__HANDLE__) (SET_BIT((__HANDLE__)->Instance->CR1, USART_CR1_UE)) /** @brief Disable UART/USART associated to IRDA Handle * @param __HANDLE__: specifies the IRDA Handle. * This parameter can be USARTx with x: 1, 2 or 3, or UARTy with y:4 or 5 to select the USART or * UART peripheral (availability depending on device for UARTy). * @retval None */ #define __HAL_IRDA_DISABLE(__HANDLE__) (CLEAR_BIT((__HANDLE__)->Instance->CR1, USART_CR1_UE)) /** * @} */ /* Private macros --------------------------------------------------------*/ /** @defgroup IRDA_Private_Macros IRDA Private Macros * @{ */ #define IRDA_DIV(__PCLK__, __BAUD__) (((__PCLK__)*25)/(4*(__BAUD__))) #define IRDA_DIVMANT(__PCLK__, __BAUD__) (IRDA_DIV((__PCLK__), (__BAUD__))/100) #define IRDA_DIVFRAQ(__PCLK__, __BAUD__) (((IRDA_DIV((__PCLK__), (__BAUD__)) - (IRDA_DIVMANT((__PCLK__), (__BAUD__)) * 100)) * 16 + 50) / 100) #define IRDA_BRR(__PCLK__, __BAUD__) ((IRDA_DIVMANT((__PCLK__), (__BAUD__)) << 4)|(IRDA_DIVFRAQ((__PCLK__), (__BAUD__)) & 0x0F)) /** @brief Ensure that IRDA Baud rate is less or equal to maximum value * @param __BAUDRATE__: specifies the IRDA Baudrate set by the user. * @retval True or False */ #define IS_IRDA_BAUDRATE(__BAUDRATE__) ((__BAUDRATE__) < 115201) /** * @} */ /* Exported functions --------------------------------------------------------*/ /** @addtogroup IRDA_Exported_Functions IRDA Exported Functions * @{ */ /** @addtogroup IRDA_Exported_Functions_Group1 IrDA Initialization and de-initialization functions * @{ */ /* Initialization and de-initialization functions ****************************/ HAL_StatusTypeDef HAL_IRDA_Init(IRDA_HandleTypeDef *hirda); HAL_StatusTypeDef HAL_IRDA_DeInit(IRDA_HandleTypeDef *hirda); void HAL_IRDA_MspInit(IRDA_HandleTypeDef *hirda); void HAL_IRDA_MspDeInit(IRDA_HandleTypeDef *hirda); /** * @} */ /** @addtogroup IRDA_Exported_Functions_Group2 IO operation functions * @{ */ /* IO operation functions *****************************************************/ HAL_StatusTypeDef HAL_IRDA_Transmit(IRDA_HandleTypeDef *hirda, uint8_t *pData, uint16_t Size, uint32_t Timeout); HAL_StatusTypeDef HAL_IRDA_Receive(IRDA_HandleTypeDef *hirda, uint8_t *pData, uint16_t Size, uint32_t Timeout); HAL_StatusTypeDef HAL_IRDA_Transmit_IT(IRDA_HandleTypeDef *hirda, uint8_t *pData, uint16_t Size); HAL_StatusTypeDef HAL_IRDA_Receive_IT(IRDA_HandleTypeDef *hirda, uint8_t *pData, uint16_t Size); HAL_StatusTypeDef HAL_IRDA_Transmit_DMA(IRDA_HandleTypeDef *hirda, uint8_t *pData, uint16_t Size); HAL_StatusTypeDef HAL_IRDA_Receive_DMA(IRDA_HandleTypeDef *hirda, uint8_t *pData, uint16_t Size); HAL_StatusTypeDef HAL_IRDA_DMAPause(IRDA_HandleTypeDef *hirda); HAL_StatusTypeDef HAL_IRDA_DMAResume(IRDA_HandleTypeDef *hirda); HAL_StatusTypeDef HAL_IRDA_DMAStop(IRDA_HandleTypeDef *hirda); void HAL_IRDA_IRQHandler(IRDA_HandleTypeDef *hirda); void HAL_IRDA_TxCpltCallback(IRDA_HandleTypeDef *hirda); void HAL_IRDA_RxCpltCallback(IRDA_HandleTypeDef *hirda); void HAL_IRDA_TxHalfCpltCallback(IRDA_HandleTypeDef *hirda); void HAL_IRDA_RxHalfCpltCallback(IRDA_HandleTypeDef *hirda); void HAL_IRDA_ErrorCallback(IRDA_HandleTypeDef *hirda); /** * @} */ /** @addtogroup IRDA_Exported_Functions_Group3 Peripheral State and Errors functions * @{ */ /* Peripheral State and Error functions ***************************************/ HAL_IRDA_StateTypeDef HAL_IRDA_GetState(IRDA_HandleTypeDef *hirda); uint32_t HAL_IRDA_GetError(IRDA_HandleTypeDef *hirda); /** * @} */ /** * @} */ /** * @} */ /** * @} */ #ifdef __cplusplus } #endif #endif /* __STM32L1xx_HAL_IRDA_H */ /************************ (C) COPYRIGHT STMicroelectronics *****END OF FILE****/ ================================================ FILE: Zelig/mbed/TARGET_NUCLEO_L152RE/stm32l1xx_hal_iwdg.h ================================================ /** ****************************************************************************** * @file stm32l1xx_hal_iwdg.h * @author MCD Application Team * @version V1.0.0 * @date 5-September-2014 * @brief Header file of IWDG HAL module. ****************************************************************************** * @attention * *

© COPYRIGHT(c) 2014 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. * ****************************************************************************** */ /* Define to prevent recursive inclusion -------------------------------------*/ #ifndef __STM32L1xx_HAL_IWDG_H #define __STM32L1xx_HAL_IWDG_H #ifdef __cplusplus extern "C" { #endif /* Includes ------------------------------------------------------------------*/ #include "stm32l1xx_hal_def.h" /** @addtogroup STM32L1xx_HAL_Driver * @{ */ /** @addtogroup IWDG * @{ */ /* Exported types ------------------------------------------------------------*/ /** @defgroup IWDG_Exported_Types IWDG Exported Types * @{ */ /** * @brief IWDG HAL State Structure definition */ typedef enum { HAL_IWDG_STATE_RESET = 0x00, /*!< IWDG not yet initialized or disabled */ HAL_IWDG_STATE_READY = 0x01, /*!< IWDG initialized and ready for use */ HAL_IWDG_STATE_BUSY = 0x02, /*!< IWDG internal process is ongoing */ HAL_IWDG_STATE_TIMEOUT = 0x03, /*!< IWDG timeout state */ HAL_IWDG_STATE_ERROR = 0x04 /*!< IWDG error state */ }HAL_IWDG_StateTypeDef; /** * @brief IWDG Init structure definition */ typedef struct { uint32_t Prescaler; /*!< Select the prescaler of the IWDG. This parameter can be a value of @ref IWDG_Prescaler */ uint32_t Reload; /*!< Specifies the IWDG down-counter reload value. This parameter must be a number between Min_Data = 0 and Max_Data = 0x0FFF */ }IWDG_InitTypeDef; /** * @brief IWDG Handle Structure definition */ typedef struct { IWDG_TypeDef *Instance; /*!< Register base address */ IWDG_InitTypeDef Init; /*!< IWDG required parameters */ HAL_LockTypeDef Lock; /*!< IWDG Locking object */ __IO HAL_IWDG_StateTypeDef State; /*!< IWDG communication state */ }IWDG_HandleTypeDef; /** * @} */ /* Exported constants --------------------------------------------------------*/ /** @defgroup IWDG_Exported_Constants IWDG Exported Constants * @{ */ /** @defgroup IWDG_Registers_BitMask IWDG_Registers_BitMask * @brief IWDG registers bit mask * @{ */ /* --- KR Register ---*/ /* KR register bit mask */ #define KR_KEY_RELOAD ((uint32_t)0xAAAA) /*!< IWDG Reload Counter Enable */ #define KR_KEY_ENABLE ((uint32_t)0xCCCC) /*!< IWDG Peripheral Enable */ #define KR_KEY_EWA ((uint32_t)0x5555) /*!< IWDG KR Write Access Enable */ #define KR_KEY_DWA ((uint32_t)0x0000) /*!< IWDG KR Write Access Disable */ #define IS_IWDG_KR(__KR__) (((__KR__) == KR_KEY_RELOAD) || \ ((__KR__) == KR_KEY_ENABLE))|| \ ((__KR__) == KR_KEY_EWA)) || \ ((__KR__) == KR_KEY_DWA)) /** * @} */ /** @defgroup IWDG_Flag_definition IWDG_Flag_definition * @{ */ #define IWDG_FLAG_PVU ((uint32_t)IWDG_SR_PVU) /*!< Watchdog counter prescaler value update Flag */ #define IWDG_FLAG_RVU ((uint32_t)IWDG_SR_RVU) /*!< Watchdog counter reload value update Flag */ /** * @} */ /** @defgroup IWDG_Prescaler IWDG_Prescaler * @{ */ #define IWDG_PRESCALER_4 ((uint8_t)0x00) /*!< IWDG prescaler set to 4 */ #define IWDG_PRESCALER_8 ((uint8_t)(IWDG_PR_PR_0)) /*!< IWDG prescaler set to 8 */ #define IWDG_PRESCALER_16 ((uint8_t)(IWDG_PR_PR_1)) /*!< IWDG prescaler set to 16 */ #define IWDG_PRESCALER_32 ((uint8_t)(IWDG_PR_PR_1 | IWDG_PR_PR_0)) /*!< IWDG prescaler set to 32 */ #define IWDG_PRESCALER_64 ((uint8_t)(IWDG_PR_PR_2)) /*!< IWDG prescaler set to 64 */ #define IWDG_PRESCALER_128 ((uint8_t)(IWDG_PR_PR_2 | IWDG_PR_PR_0)) /*!< IWDG prescaler set to 128 */ #define IWDG_PRESCALER_256 ((uint8_t)(IWDG_PR_PR_2 | IWDG_PR_PR_1)) /*!< IWDG prescaler set to 256 */ #define IS_IWDG_PRESCALER(__PRESCALER__) (((__PRESCALER__) == IWDG_PRESCALER_4) || \ ((__PRESCALER__) == IWDG_PRESCALER_8) || \ ((__PRESCALER__) == IWDG_PRESCALER_16) || \ ((__PRESCALER__) == IWDG_PRESCALER_32) || \ ((__PRESCALER__) == IWDG_PRESCALER_64) || \ ((__PRESCALER__) == IWDG_PRESCALER_128)|| \ ((__PRESCALER__) == IWDG_PRESCALER_256)) /** * @} */ /** @defgroup IWDG_Reload_Value IWDG_Reload_Value * @{ */ #define IS_IWDG_RELOAD(__RELOAD__) ((__RELOAD__) <= 0xFFF) /** * @} */ /** * @} */ /* Exported macros -----------------------------------------------------------*/ /** @defgroup IWDG_Exported_Macros IWDG Exported Macros * @{ */ /** @brief Reset IWDG handle state * @param __HANDLE__: IWDG handle. * @retval None */ #define __HAL_IWDG_RESET_HANDLE_STATE(__HANDLE__) ((__HANDLE__)->State = HAL_IWDG_STATE_RESET) /** * @brief Enables the IWDG peripheral. * @param __HANDLE__: IWDG handle * @retval None */ #define __HAL_IWDG_START(__HANDLE__) WRITE_REG((__HANDLE__)->Instance->KR, KR_KEY_ENABLE) /** * @brief Reloads IWDG counter with value defined in the reload register * (write access to IWDG_PR and IWDG_RLR registers disabled). * @param __HANDLE__: IWDG handle * @retval None */ #define __HAL_IWDG_RELOAD_COUNTER(__HANDLE__) WRITE_REG((__HANDLE__)->Instance->KR, KR_KEY_RELOAD) /** * @brief Enables write access to IWDG_PR and IWDG_RLR registers. * @param __HANDLE__: IWDG handle * @retval None */ #define __HAL_IWDG_ENABLE_WRITE_ACCESS(__HANDLE__) WRITE_REG((__HANDLE__)->Instance->KR, KR_KEY_EWA) /** * @brief Disables write access to IWDG_PR and IWDG_RLR registers. * @param __HANDLE__: IWDG handle * @retval None */ #define __HAL_IWDG_DISABLE_WRITE_ACCESS(__HANDLE__) WRITE_REG((__HANDLE__)->Instance->KR, KR_KEY_DWA) /** * @brief Gets the selected IWDG's flag status. * @param __HANDLE__: IWDG handle * @param __FLAG__: specifies the flag to check. * This parameter can be one of the following values: * @arg IWDG_FLAG_PVU: Watchdog counter reload value update flag * @arg IWDG_FLAG_RVU: Watchdog counter prescaler value flag * @retval The new state of __FLAG__ (TRUE or FALSE). */ #define __HAL_IWDG_GET_FLAG(__HANDLE__, __FLAG__) (((__HANDLE__)->Instance->SR & (__FLAG__)) == (__FLAG__)) /** * @} */ /* Exported functions --------------------------------------------------------*/ /** @addtogroup IWDG_Exported_Functions * @{ */ /** @addtogroup IWDG_Exported_Functions_Group1 * @{ */ /* Initialization/de-initialization functions ********************************/ HAL_StatusTypeDef HAL_IWDG_Init(IWDG_HandleTypeDef *hiwdg); void HAL_IWDG_MspInit(IWDG_HandleTypeDef *hiwdg); /** * @} */ /** @addtogroup IWDG_Exported_Functions_Group2 * @{ */ /* I/O operation functions ****************************************************/ HAL_StatusTypeDef HAL_IWDG_Start(IWDG_HandleTypeDef *hiwdg); HAL_StatusTypeDef HAL_IWDG_Refresh(IWDG_HandleTypeDef *hiwdg); /** * @} */ /** @addtogroup IWDG_Exported_Functions_Group3 * @{ */ /* Peripheral State functions ************************************************/ HAL_IWDG_StateTypeDef HAL_IWDG_GetState(IWDG_HandleTypeDef *hiwdg); /** * @} */ /** * @} */ /** * @} */ /** * @} */ #ifdef __cplusplus } #endif #endif /* __STM32L1xx_HAL_IWDG_H */ /************************ (C) COPYRIGHT STMicroelectronics *****END OF FILE****/ ================================================ FILE: Zelig/mbed/TARGET_NUCLEO_L152RE/stm32l1xx_hal_lcd.h ================================================ /** ****************************************************************************** * @file stm32l1xx_hal_lcd.h * @author MCD Application Team * @version V1.0.0 * @date 5-September-2014 * @brief Header file of LCD Controller HAL module. ****************************************************************************** * @attention * *

© COPYRIGHT(c) 2014 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. * ****************************************************************************** */ /* Define to prevent recursive inclusion -------------------------------------*/ #ifndef __STM32L1xx_HAL_LCD_H #define __STM32L1xx_HAL_LCD_H #ifdef __cplusplus extern "C" { #endif /** @addtogroup STM32L1xx_HAL_Driver * @{ */ #if defined (STM32L100xB) || defined (STM32L100xBA) || defined (STM32L100xC) ||\ defined (STM32L152xB) || defined (STM32L152xBA) || defined (STM32L152xC) || defined (STM32L152xCA) || defined (STM32L152xD) || defined (STM32L152xE) ||\ defined (STM32L162xC) || defined (STM32L162xCA) || defined (STM32L162xD) || defined (STM32L162xE) /* Includes ------------------------------------------------------------------*/ #include "stm32l1xx_hal_def.h" /** @addtogroup LCD * @{ */ /* Exported types ------------------------------------------------------------*/ /** @defgroup LCD_Exported_Types LCD Exported Types * @{ */ /** * @brief LCD Init structure definition */ typedef struct { uint32_t Prescaler; /*!< Configures the LCD Prescaler. This parameter can be one value of @ref LCD_Prescaler */ uint32_t Divider; /*!< Configures the LCD Divider. This parameter can be one value of @ref LCD_Divider */ uint32_t Duty; /*!< Configures the LCD Duty. This parameter can be one value of @ref LCD_Duty */ uint32_t Bias; /*!< Configures the LCD Bias. This parameter can be one value of @ref LCD_Bias */ uint32_t VoltageSource; /*!< Selects the LCD Voltage source. This parameter can be one value of @ref LCD_Voltage_Source */ uint32_t Contrast; /*!< Configures the LCD Contrast. This parameter can be one value of @ref LCD_Contrast */ uint32_t DeadTime; /*!< Configures the LCD Dead Time. This parameter can be one value of @ref LCD_DeadTime */ uint32_t PulseOnDuration; /*!< Configures the LCD Pulse On Duration. This parameter can be one value of @ref LCD_PulseOnDuration */ uint32_t BlinkMode; /*!< Configures the LCD Blink Mode. This parameter can be one value of @ref LCD_BlinkMode */ uint32_t BlinkFrequency; /*!< Configures the LCD Blink frequency. This parameter can be one value of @ref LCD_BlinkFrequency */ uint32_t MuxSegment; /*!< Enable or disable mux segment. This parameter can be set to ENABLE or DISABLE. */ }LCD_InitTypeDef; /** * @brief HAL LCD State structures definition */ typedef enum { HAL_LCD_STATE_RESET = 0x00, /*!< Peripheral is not yet Initialized */ HAL_LCD_STATE_READY = 0x01, /*!< Peripheral Initialized and ready for use */ HAL_LCD_STATE_BUSY = 0x02, /*!< an internal process is ongoing */ HAL_LCD_STATE_TIMEOUT = 0x03, /*!< Timeout state */ HAL_LCD_STATE_ERROR = 0x04 /*!< Error */ }HAL_LCD_StateTypeDef; /** * @brief HAL LCD Error Code structure definition */ typedef enum { HAL_LCD_ERROR_NONE = 0x00, /*!< No error */ HAL_LCD_ERROR_FCRSF = 0x01, /*!< Synchro flag timeout error */ HAL_LCD_ERROR_UDR = 0x02, /*!< Update display request flag timeout error */ HAL_LCD_ERROR_UDD = 0x04, /*!< Update display done flag timeout error */ HAL_LCD_ERROR_ENS = 0x08, /*!< LCD enabled status flag timeout error */ HAL_LCD_ERROR_RDY = 0x10 /*!< LCD Booster ready timeout error */ }HAL_LCD_ErrorTypeDef; /** * @brief UART handle Structure definition */ typedef struct { LCD_TypeDef *Instance; /* LCD registers base address */ LCD_InitTypeDef Init; /* LCD communication parameters */ HAL_LockTypeDef Lock; /* Locking object */ __IO HAL_LCD_StateTypeDef State; /* LCD communication state */ __IO HAL_LCD_ErrorTypeDef ErrorCode; /* LCD Error code */ }LCD_HandleTypeDef; /** * @} */ /* Exported constants --------------------------------------------------------*/ /** @defgroup LCD_Exported_Constants LCD Exported Constants * @{ */ /** @defgroup LCD_Prescaler LCD Prescaler * @{ */ #define LCD_PRESCALER_1 ((uint32_t)0x00000000) /*!< CLKPS = LCDCLK */ #define LCD_PRESCALER_2 ((uint32_t)0x00400000) /*!< CLKPS = LCDCLK/2 */ #define LCD_PRESCALER_4 ((uint32_t)0x00800000) /*!< CLKPS = LCDCLK/4 */ #define LCD_PRESCALER_8 ((uint32_t)0x00C00000) /*!< CLKPS = LCDCLK/8 */ #define LCD_PRESCALER_16 ((uint32_t)0x01000000) /*!< CLKPS = LCDCLK/16 */ #define LCD_PRESCALER_32 ((uint32_t)0x01400000) /*!< CLKPS = LCDCLK/32 */ #define LCD_PRESCALER_64 ((uint32_t)0x01800000) /*!< CLKPS = LCDCLK/64 */ #define LCD_PRESCALER_128 ((uint32_t)0x01C00000) /*!< CLKPS = LCDCLK/128 */ #define LCD_PRESCALER_256 ((uint32_t)0x02000000) /*!< CLKPS = LCDCLK/256 */ #define LCD_PRESCALER_512 ((uint32_t)0x02400000) /*!< CLKPS = LCDCLK/512 */ #define LCD_PRESCALER_1024 ((uint32_t)0x02800000) /*!< CLKPS = LCDCLK/1024 */ #define LCD_PRESCALER_2048 ((uint32_t)0x02C00000) /*!< CLKPS = LCDCLK/2048 */ #define LCD_PRESCALER_4096 ((uint32_t)0x03000000) /*!< CLKPS = LCDCLK/4096 */ #define LCD_PRESCALER_8192 ((uint32_t)0x03400000) /*!< CLKPS = LCDCLK/8192 */ #define LCD_PRESCALER_16384 ((uint32_t)0x03800000) /*!< CLKPS = LCDCLK/16384 */ #define LCD_PRESCALER_32768 ((uint32_t)LCD_FCR_PS) /*!< CLKPS = LCDCLK/32768 */ #define IS_LCD_PRESCALER(__PRESCALER__) (((__PRESCALER__) == LCD_PRESCALER_1) || \ ((__PRESCALER__) == LCD_PRESCALER_2) || \ ((__PRESCALER__) == LCD_PRESCALER_4) || \ ((__PRESCALER__) == LCD_PRESCALER_8) || \ ((__PRESCALER__) == LCD_PRESCALER_16) || \ ((__PRESCALER__) == LCD_PRESCALER_32) || \ ((__PRESCALER__) == LCD_PRESCALER_64) || \ ((__PRESCALER__) == LCD_PRESCALER_128) || \ ((__PRESCALER__) == LCD_PRESCALER_256) || \ ((__PRESCALER__) == LCD_PRESCALER_512) || \ ((__PRESCALER__) == LCD_PRESCALER_1024) || \ ((__PRESCALER__) == LCD_PRESCALER_2048) || \ ((__PRESCALER__) == LCD_PRESCALER_4096) || \ ((__PRESCALER__) == LCD_PRESCALER_8192) || \ ((__PRESCALER__) == LCD_PRESCALER_16384) || \ ((__PRESCALER__) == LCD_PRESCALER_32768)) /** * @} */ /** @defgroup LCD_Divider LCD Divider * @{ */ #define LCD_DIVIDER_16 ((uint32_t)0x00000000) /*!< LCD frequency = CLKPS/16 */ #define LCD_DIVIDER_17 ((uint32_t)0x00040000) /*!< LCD frequency = CLKPS/17 */ #define LCD_DIVIDER_18 ((uint32_t)0x00080000) /*!< LCD frequency = CLKPS/18 */ #define LCD_DIVIDER_19 ((uint32_t)0x000C0000) /*!< LCD frequency = CLKPS/19 */ #define LCD_DIVIDER_20 ((uint32_t)0x00100000) /*!< LCD frequency = CLKPS/20 */ #define LCD_DIVIDER_21 ((uint32_t)0x00140000) /*!< LCD frequency = CLKPS/21 */ #define LCD_DIVIDER_22 ((uint32_t)0x00180000) /*!< LCD frequency = CLKPS/22 */ #define LCD_DIVIDER_23 ((uint32_t)0x001C0000) /*!< LCD frequency = CLKPS/23 */ #define LCD_DIVIDER_24 ((uint32_t)0x00200000) /*!< LCD frequency = CLKPS/24 */ #define LCD_DIVIDER_25 ((uint32_t)0x00240000) /*!< LCD frequency = CLKPS/25 */ #define LCD_DIVIDER_26 ((uint32_t)0x00280000) /*!< LCD frequency = CLKPS/26 */ #define LCD_DIVIDER_27 ((uint32_t)0x002C0000) /*!< LCD frequency = CLKPS/27 */ #define LCD_DIVIDER_28 ((uint32_t)0x00300000) /*!< LCD frequency = CLKPS/28 */ #define LCD_DIVIDER_29 ((uint32_t)0x00340000) /*!< LCD frequency = CLKPS/29 */ #define LCD_DIVIDER_30 ((uint32_t)0x00380000) /*!< LCD frequency = CLKPS/30 */ #define LCD_DIVIDER_31 ((uint32_t)LCD_FCR_DIV) /*!< LCD frequency = CLKPS/31 */ #define IS_LCD_DIVIDER(__DIVIDER__) (((__DIVIDER__) == LCD_DIVIDER_16) || \ ((__DIVIDER__) == LCD_DIVIDER_17) || \ ((__DIVIDER__) == LCD_DIVIDER_18) || \ ((__DIVIDER__) == LCD_DIVIDER_19) || \ ((__DIVIDER__) == LCD_DIVIDER_20) || \ ((__DIVIDER__) == LCD_DIVIDER_21) || \ ((__DIVIDER__) == LCD_DIVIDER_22) || \ ((__DIVIDER__) == LCD_DIVIDER_23) || \ ((__DIVIDER__) == LCD_DIVIDER_24) || \ ((__DIVIDER__) == LCD_DIVIDER_25) || \ ((__DIVIDER__) == LCD_DIVIDER_26) || \ ((__DIVIDER__) == LCD_DIVIDER_27) || \ ((__DIVIDER__) == LCD_DIVIDER_28) || \ ((__DIVIDER__) == LCD_DIVIDER_29) || \ ((__DIVIDER__) == LCD_DIVIDER_30) || \ ((__DIVIDER__) == LCD_DIVIDER_31)) /** * @} */ /** @defgroup LCD_Duty LCD Duty * @{ */ #define LCD_DUTY_STATIC ((uint32_t)0x00000000) /*!< Static duty */ #define LCD_DUTY_1_2 (LCD_CR_DUTY_0) /*!< 1/2 duty */ #define LCD_DUTY_1_3 (LCD_CR_DUTY_1) /*!< 1/3 duty */ #define LCD_DUTY_1_4 ((LCD_CR_DUTY_1 | LCD_CR_DUTY_0)) /*!< 1/4 duty */ #define LCD_DUTY_1_8 (LCD_CR_DUTY_2) /*!< 1/8 duty */ #define IS_LCD_DUTY(__DUTY__) (((__DUTY__) == LCD_DUTY_STATIC) || \ ((__DUTY__) == LCD_DUTY_1_2) || \ ((__DUTY__) == LCD_DUTY_1_3) || \ ((__DUTY__) == LCD_DUTY_1_4) || \ ((__DUTY__) == LCD_DUTY_1_8)) /** * @} */ /** @defgroup LCD_Bias LCD Bias * @{ */ #define LCD_BIAS_1_4 ((uint32_t)0x00000000) /*!< 1/4 Bias */ #define LCD_BIAS_1_2 LCD_CR_BIAS_0 /*!< 1/2 Bias */ #define LCD_BIAS_1_3 LCD_CR_BIAS_1 /*!< 1/3 Bias */ #define IS_LCD_BIAS(__BIAS__) (((__BIAS__) == LCD_BIAS_1_4) || \ ((__BIAS__) == LCD_BIAS_1_2) || \ ((__BIAS__) == LCD_BIAS_1_3)) /** * @} */ /** @defgroup LCD_Voltage_Source LCD Voltage Source * @{ */ #define LCD_VOLTAGESOURCE_INTERNAL ((uint32_t)0x00000000) /*!< Internal voltage source for the LCD */ #define LCD_VOLTAGESOURCE_EXTERNAL LCD_CR_VSEL /*!< External voltage source for the LCD */ #define IS_LCD_VOLTAGE_SOURCE(SOURCE) (((SOURCE) == LCD_VOLTAGESOURCE_INTERNAL) || \ ((SOURCE) == LCD_VOLTAGESOURCE_EXTERNAL)) /** * @} */ /** @defgroup LCD_Interrupts LCD Interrupts * @{ */ #define LCD_IT_SOF LCD_FCR_SOFIE #define LCD_IT_UDD LCD_FCR_UDDIE /** * @} */ /** @defgroup LCD_PulseOnDuration LCD Pulse On Duration * @{ */ #define LCD_PULSEONDURATION_0 ((uint32_t)0x00000000) /*!< Pulse ON duration = 0 pulse */ #define LCD_PULSEONDURATION_1 (LCD_FCR_PON_0) /*!< Pulse ON duration = 1/CK_PS */ #define LCD_PULSEONDURATION_2 (LCD_FCR_PON_1) /*!< Pulse ON duration = 2/CK_PS */ #define LCD_PULSEONDURATION_3 (LCD_FCR_PON_1 | LCD_FCR_PON_0) /*!< Pulse ON duration = 3/CK_PS */ #define LCD_PULSEONDURATION_4 (LCD_FCR_PON_2) /*!< Pulse ON duration = 4/CK_PS */ #define LCD_PULSEONDURATION_5 (LCD_FCR_PON_2 | LCD_FCR_PON_0) /*!< Pulse ON duration = 5/CK_PS */ #define LCD_PULSEONDURATION_6 (LCD_FCR_PON_2 | LCD_FCR_PON_1) /*!< Pulse ON duration = 6/CK_PS */ #define LCD_PULSEONDURATION_7 (LCD_FCR_PON) /*!< Pulse ON duration = 7/CK_PS */ #define IS_LCD_PULSE_ON_DURATION(__DURATION__) (((__DURATION__) == LCD_PULSEONDURATION_0) || \ ((__DURATION__) == LCD_PULSEONDURATION_1) || \ ((__DURATION__) == LCD_PULSEONDURATION_2) || \ ((__DURATION__) == LCD_PULSEONDURATION_3) || \ ((__DURATION__) == LCD_PULSEONDURATION_4) || \ ((__DURATION__) == LCD_PULSEONDURATION_5) || \ ((__DURATION__) == LCD_PULSEONDURATION_6) || \ ((__DURATION__) == LCD_PULSEONDURATION_7)) /** * @} */ /** @defgroup LCD_DeadTime LCD Dead Time * @{ */ #define LCD_DEADTIME_0 ((uint32_t)0x00000000) /*!< No dead Time */ #define LCD_DEADTIME_1 (LCD_FCR_DEAD_0) /*!< One Phase between different couple of Frame */ #define LCD_DEADTIME_2 (LCD_FCR_DEAD_1) /*!< Two Phase between different couple of Frame */ #define LCD_DEADTIME_3 (LCD_FCR_DEAD_1 | LCD_FCR_DEAD_0) /*!< Three Phase between different couple of Frame */ #define LCD_DEADTIME_4 (LCD_FCR_DEAD_2) /*!< Four Phase between different couple of Frame */ #define LCD_DEADTIME_5 (LCD_FCR_DEAD_2 | LCD_FCR_DEAD_0) /*!< Five Phase between different couple of Frame */ #define LCD_DEADTIME_6 (LCD_FCR_DEAD_2 | LCD_FCR_DEAD_1) /*!< Six Phase between different couple of Frame */ #define LCD_DEADTIME_7 (LCD_FCR_DEAD) /*!< Seven Phase between different couple of Frame */ #define IS_LCD_DEAD_TIME(__TIME__) (((__TIME__) == LCD_DEADTIME_0) || \ ((__TIME__) == LCD_DEADTIME_1) || \ ((__TIME__) == LCD_DEADTIME_2) || \ ((__TIME__) == LCD_DEADTIME_3) || \ ((__TIME__) == LCD_DEADTIME_4) || \ ((__TIME__) == LCD_DEADTIME_5) || \ ((__TIME__) == LCD_DEADTIME_6) || \ ((__TIME__) == LCD_DEADTIME_7)) /** * @} */ /** @defgroup LCD_BlinkMode LCD Blink Mode * @{ */ #define LCD_BLINKMODE_OFF ((uint32_t)0x00000000) /*!< Blink disabled */ #define LCD_BLINKMODE_SEG0_COM0 (LCD_FCR_BLINK_0) /*!< Blink enabled on SEG[0], COM[0] (1 pixel) */ #define LCD_BLINKMODE_SEG0_ALLCOM (LCD_FCR_BLINK_1) /*!< Blink enabled on SEG[0], all COM (up to 8 pixels according to the programmed duty) */ #define LCD_BLINKMODE_ALLSEG_ALLCOM (LCD_FCR_BLINK) /*!< Blink enabled on all SEG and all COM (all pixels) */ #define IS_LCD_BLINK_MODE(__MODE__) (((__MODE__) == LCD_BLINKMODE_OFF) || \ ((__MODE__) == LCD_BLINKMODE_SEG0_COM0) || \ ((__MODE__) == LCD_BLINKMODE_SEG0_ALLCOM) || \ ((__MODE__) == LCD_BLINKMODE_ALLSEG_ALLCOM)) /** * @} */ /** @defgroup LCD_BlinkFrequency LCD Blink Frequency * @{ */ #define LCD_BLINKFREQUENCY_DIV8 ((uint32_t)0x00000000) /*!< The Blink frequency = fLCD/8 */ #define LCD_BLINKFREQUENCY_DIV16 (LCD_FCR_BLINKF_0) /*!< The Blink frequency = fLCD/16 */ #define LCD_BLINKFREQUENCY_DIV32 (LCD_FCR_BLINKF_1) /*!< The Blink frequency = fLCD/32 */ #define LCD_BLINKFREQUENCY_DIV64 (LCD_FCR_BLINKF_1 | LCD_FCR_BLINKF_0) /*!< The Blink frequency = fLCD/64 */ #define LCD_BLINKFREQUENCY_DIV128 (LCD_FCR_BLINKF_2) /*!< The Blink frequency = fLCD/128 */ #define LCD_BLINKFREQUENCY_DIV256 (LCD_FCR_BLINKF_2 |LCD_FCR_BLINKF_0) /*!< The Blink frequency = fLCD/256 */ #define LCD_BLINKFREQUENCY_DIV512 (LCD_FCR_BLINKF_2 |LCD_FCR_BLINKF_1) /*!< The Blink frequency = fLCD/512 */ #define LCD_BLINKFREQUENCY_DIV1024 (LCD_FCR_BLINKF) /*!< The Blink frequency = fLCD/1024 */ #define IS_LCD_BLINK_FREQUENCY(__FREQUENCY__) (((__FREQUENCY__) == LCD_BLINKFREQUENCY_DIV8) || \ ((__FREQUENCY__) == LCD_BLINKFREQUENCY_DIV16) || \ ((__FREQUENCY__) == LCD_BLINKFREQUENCY_DIV32) || \ ((__FREQUENCY__) == LCD_BLINKFREQUENCY_DIV64) || \ ((__FREQUENCY__) == LCD_BLINKFREQUENCY_DIV128) || \ ((__FREQUENCY__) == LCD_BLINKFREQUENCY_DIV256) || \ ((__FREQUENCY__) == LCD_BLINKFREQUENCY_DIV512) || \ ((__FREQUENCY__) == LCD_BLINKFREQUENCY_DIV1024)) /** * @} */ /** @defgroup LCD_Contrast LCD Contrast * @{ */ #define LCD_CONTRASTLEVEL_0 ((uint32_t)0x00000000) /*!< Maximum Voltage = 2.60V */ #define LCD_CONTRASTLEVEL_1 (LCD_FCR_CC_0) /*!< Maximum Voltage = 2.73V */ #define LCD_CONTRASTLEVEL_2 (LCD_FCR_CC_1) /*!< Maximum Voltage = 2.86V */ #define LCD_CONTRASTLEVEL_3 (LCD_FCR_CC_1 | LCD_FCR_CC_0) /*!< Maximum Voltage = 2.99V */ #define LCD_CONTRASTLEVEL_4 (LCD_FCR_CC_2) /*!< Maximum Voltage = 3.12V */ #define LCD_CONTRASTLEVEL_5 (LCD_FCR_CC_2 | LCD_FCR_CC_0) /*!< Maximum Voltage = 3.25V */ #define LCD_CONTRASTLEVEL_6 (LCD_FCR_CC_2 | LCD_FCR_CC_1) /*!< Maximum Voltage = 3.38V */ #define LCD_CONTRASTLEVEL_7 (LCD_FCR_CC) /*!< Maximum Voltage = 3.51V */ #define IS_LCD_CONTRAST(__CONTRAST__) (((__CONTRAST__) == LCD_CONTRASTLEVEL_0) || \ ((__CONTRAST__) == LCD_CONTRASTLEVEL_1) || \ ((__CONTRAST__) == LCD_CONTRASTLEVEL_2) || \ ((__CONTRAST__) == LCD_CONTRASTLEVEL_3) || \ ((__CONTRAST__) == LCD_CONTRASTLEVEL_4) || \ ((__CONTRAST__) == LCD_CONTRASTLEVEL_5) || \ ((__CONTRAST__) == LCD_CONTRASTLEVEL_6) || \ ((__CONTRAST__) == LCD_CONTRASTLEVEL_7)) /** * @} */ /** @defgroup LCD_MuxSegment LCD Mux Segment * @{ */ #define LCD_MUXSEGMENT_DISABLE ((uint32_t)0x00000000) /*!< SEG pin multiplexing disabled */ #define LCD_MUXSEGMENT_ENABLE (LCD_CR_MUX_SEG) /*!< SEG[31:28] are multiplexed with SEG[43:40] */ #define IS_LCD_MUXSEGMENT(__VALUE__) (((__VALUE__) == LCD_MUXSEGMENT_ENABLE) || \ ((__VALUE__) == LCD_MUXSEGMENT_DISABLE)) /** * @} */ /** @defgroup LCD_Flag LCD Flag * @{ */ #define LCD_FLAG_ENS LCD_SR_ENS #define LCD_FLAG_SOF LCD_SR_SOF #define LCD_FLAG_UDR LCD_SR_UDR #define LCD_FLAG_UDD LCD_SR_UDD #define LCD_FLAG_RDY LCD_SR_RDY #define LCD_FLAG_FCRSF LCD_SR_FCRSR /** * @} */ /** @defgroup LCD_RAMRegister LCD RAMRegister * @{ */ #define LCD_RAM_REGISTER0 ((uint32_t)0x00000000) /*!< LCD RAM Register 0 */ #define LCD_RAM_REGISTER1 ((uint32_t)0x00000001) /*!< LCD RAM Register 1 */ #define LCD_RAM_REGISTER2 ((uint32_t)0x00000002) /*!< LCD RAM Register 2 */ #define LCD_RAM_REGISTER3 ((uint32_t)0x00000003) /*!< LCD RAM Register 3 */ #define LCD_RAM_REGISTER4 ((uint32_t)0x00000004) /*!< LCD RAM Register 4 */ #define LCD_RAM_REGISTER5 ((uint32_t)0x00000005) /*!< LCD RAM Register 5 */ #define LCD_RAM_REGISTER6 ((uint32_t)0x00000006) /*!< LCD RAM Register 6 */ #define LCD_RAM_REGISTER7 ((uint32_t)0x00000007) /*!< LCD RAM Register 7 */ #define LCD_RAM_REGISTER8 ((uint32_t)0x00000008) /*!< LCD RAM Register 8 */ #define LCD_RAM_REGISTER9 ((uint32_t)0x00000009) /*!< LCD RAM Register 9 */ #define LCD_RAM_REGISTER10 ((uint32_t)0x0000000A) /*!< LCD RAM Register 10 */ #define LCD_RAM_REGISTER11 ((uint32_t)0x0000000B) /*!< LCD RAM Register 11 */ #define LCD_RAM_REGISTER12 ((uint32_t)0x0000000C) /*!< LCD RAM Register 12 */ #define LCD_RAM_REGISTER13 ((uint32_t)0x0000000D) /*!< LCD RAM Register 13 */ #define LCD_RAM_REGISTER14 ((uint32_t)0x0000000E) /*!< LCD RAM Register 14 */ #define LCD_RAM_REGISTER15 ((uint32_t)0x0000000F) /*!< LCD RAM Register 15 */ #define IS_LCD_RAM_REGISTER(__REGISTER__) (((__REGISTER__) == LCD_RAM_REGISTER0) || \ ((__REGISTER__) == LCD_RAM_REGISTER1) || \ ((__REGISTER__) == LCD_RAM_REGISTER2) || \ ((__REGISTER__) == LCD_RAM_REGISTER3) || \ ((__REGISTER__) == LCD_RAM_REGISTER4) || \ ((__REGISTER__) == LCD_RAM_REGISTER5) || \ ((__REGISTER__) == LCD_RAM_REGISTER6) || \ ((__REGISTER__) == LCD_RAM_REGISTER7) || \ ((__REGISTER__) == LCD_RAM_REGISTER8) || \ ((__REGISTER__) == LCD_RAM_REGISTER9) || \ ((__REGISTER__) == LCD_RAM_REGISTER10) || \ ((__REGISTER__) == LCD_RAM_REGISTER11) || \ ((__REGISTER__) == LCD_RAM_REGISTER12) || \ ((__REGISTER__) == LCD_RAM_REGISTER13) || \ ((__REGISTER__) == LCD_RAM_REGISTER14) || \ ((__REGISTER__) == LCD_RAM_REGISTER15)) /** * @} */ /** * @} */ /* Exported macro ------------------------------------------------------------*/ /** @defgroup LCD_Exported_Macros LCD Exported Macros * @{ */ /** @brief Reset LCD handle state * @param __HANDLE__: specifies the LCD Handle. * @retval None */ #define __HAL_LCD_RESET_HANDLE_STATE(__HANDLE__) ((__HANDLE__)->State = HAL_LCD_STATE_RESET) /** @brief macros to enables or disables the LCD * @param __HANDLE__: specifies the LCD Handle. * @retval None */ #define __HAL_LCD_ENABLE(__HANDLE__) (SET_BIT((__HANDLE__)->Instance->CR, LCD_CR_LCDEN)) #define __HAL_LCD_DISABLE(__HANDLE__) (CLEAR_BIT((__HANDLE__)->Instance->CR, LCD_CR_LCDEN)) /** @brief Macros to enable or disable the low resistance divider. Displays with high * internal resistance may need a longer drive time to achieve * satisfactory contrast. This function is useful in this case if some * additional power consumption can be tolerated. * @param __HANDLE__: specifies the LCD Handle. * @note When this mode is enabled, the PulseOn Duration (PON) have to be * programmed to 1/CK_PS (LCD_PULSEONDURATION_1). * @retval None */ #define __HAL_LCD_HIGHDRIVER_ENABLE(__HANDLE__) \ do{ \ SET_BIT((__HANDLE__)->Instance->FCR, LCD_FCR_HD); \ LCD_WaitForSynchro(__HANDLE__); \ }while(0) #define __HAL_LCD_HIGHDRIVER_DISABLE(__HANDLE__) \ do{ \ CLEAR_BIT((__HANDLE__)->Instance->FCR, LCD_FCR_HD); \ LCD_WaitForSynchro(__HANDLE__); \ }while(0) /** * @brief Macro to configure the LCD pulses on duration. * @param __HANDLE__: specifies the LCD Handle. * @param __DURATION__: specifies the LCD pulse on duration in terms of * CK_PS (prescaled LCD clock period) pulses. * This parameter can be one of the following values: * @arg LCD_PULSEONDURATION_0: 0 pulse * @arg LCD_PULSEONDURATION_1: Pulse ON duration = 1/CK_PS * @arg LCD_PULSEONDURATION_2: Pulse ON duration = 2/CK_PS * @arg LCD_PULSEONDURATION_3: Pulse ON duration = 3/CK_PS * @arg LCD_PULSEONDURATION_4: Pulse ON duration = 4/CK_PS * @arg LCD_PULSEONDURATION_5: Pulse ON duration = 5/CK_PS * @arg LCD_PULSEONDURATION_6: Pulse ON duration = 6/CK_PS * @arg LCD_PULSEONDURATION_7: Pulse ON duration = 7/CK_PS * @retval None */ #define __HAL_LCD_PULSEONDURATION_CONFIG(__HANDLE__, __DURATION__) \ do{ \ MODIFY_REG((__HANDLE__)->Instance->FCR, LCD_FCR_PON, (__DURATION__)); \ LCD_WaitForSynchro(__HANDLE__); \ }while(0) /** * @brief Macro to configure the LCD dead time. * @param __HANDLE__: specifies the LCD Handle. * @param __DEADTIME__: specifies the LCD dead time. * This parameter can be one of the following values: * @arg LCD_DEADTIME_0: No dead Time * @arg LCD_DEADTIME_1: One Phase between different couple of Frame * @arg LCD_DEADTIME_2: Two Phase between different couple of Frame * @arg LCD_DEADTIME_3: Three Phase between different couple of Frame * @arg LCD_DEADTIME_4: Four Phase between different couple of Frame * @arg LCD_DEADTIME_5: Five Phase between different couple of Frame * @arg LCD_DEADTIME_6: Six Phase between different couple of Frame * @arg LCD_DEADTIME_7: Seven Phase between different couple of Frame * @retval None */ #define __HAL_LCD_DEADTIME_CONFIG(__HANDLE__, __DEADTIME__) \ do{ \ MODIFY_REG((__HANDLE__)->Instance->FCR, LCD_FCR_DEAD, (__DEADTIME__)); \ LCD_WaitForSynchro(__HANDLE__); \ }while(0) /** * @brief Macro to configure the LCD Contrast. * @param __HANDLE__: specifies the LCD Handle. * @param __CONTRAST__: specifies the LCD Contrast. * This parameter can be one of the following values: * @arg LCD_CONTRASTLEVEL_0: Maximum Voltage = 2.60V * @arg LCD_CONTRASTLEVEL_1: Maximum Voltage = 2.73V * @arg LCD_CONTRASTLEVEL_2: Maximum Voltage = 2.86V * @arg LCD_CONTRASTLEVEL_3: Maximum Voltage = 2.99V * @arg LCD_CONTRASTLEVEL_4: Maximum Voltage = 3.12V * @arg LCD_CONTRASTLEVEL_5: Maximum Voltage = 3.25V * @arg LCD_CONTRASTLEVEL_6: Maximum Voltage = 3.38V * @arg LCD_CONTRASTLEVEL_7: Maximum Voltage = 3.51V * @retval None */ #define __HAL_LCD_CONTRAST_CONFIG(__HANDLE__, __CONTRAST__) \ do{ \ MODIFY_REG((__HANDLE__)->Instance->FCR, LCD_FCR_CC, (__CONTRAST__)); \ LCD_WaitForSynchro(__HANDLE__); \ } while(0) /** * @brief Macro to configure the LCD Blink mode and Blink frequency. * @param __HANDLE__: specifies the LCD Handle. * @param __BLINKMODE__: specifies the LCD blink mode. * This parameter can be one of the following values: * @arg LCD_BLINKMODE_OFF: Blink disabled * @arg LCD_BLINKMODE_SEG0_COM0: Blink enabled on SEG[0], COM[0] (1 pixel) * @arg LCD_BLINKMODE_SEG0_ALLCOM: Blink enabled on SEG[0], all COM (up to 8 * pixels according to the programmed duty) * @arg LCD_BLINKMODE_ALLSEG_ALLCOM: Blink enabled on all SEG and all COM * (all pixels) * @param __BLINKFREQUENCY__: specifies the LCD blink frequency. * @arg LCD_BLINKFREQUENCY_DIV8: The Blink frequency = fLcd/8 * @arg LCD_BLINKFREQUENCY_DIV16: The Blink frequency = fLcd/16 * @arg LCD_BLINKFREQUENCY_DIV32: The Blink frequency = fLcd/32 * @arg LCD_BLINKFREQUENCY_DIV64: The Blink frequency = fLcd/64 * @arg LCD_BLINKFREQUENCY_DIV128: The Blink frequency = fLcd/128 * @arg LCD_BLINKFREQUENCY_DIV256: The Blink frequency = fLcd/256 * @arg LCD_BLINKFREQUENCY_DIV512: The Blink frequency = fLcd/512 * @arg LCD_BLINKFREQUENCY_DIV1024: The Blink frequency = fLcd/1024 * @retval None */ #define __HAL_LCD_BLINK_CONFIG(__HANDLE__, __BLINKMODE__, __BLINKFREQUENCY__) \ do{ \ MODIFY_REG((__HANDLE__)->Instance->FCR, (LCD_FCR_BLINKF | LCD_FCR_BLINK), ((__BLINKMODE__) | (__BLINKFREQUENCY__))); \ LCD_WaitForSynchro(__HANDLE__); \ }while(0) /** @brief Enables or disables the specified LCD interrupt. * @param __HANDLE__: specifies the LCD Handle. * @param __INTERRUPT__: specifies the LCD interrupt source to be enabled or disabled. * This parameter can be one of the following values: * @arg LCD_IT_SOF: Start of Frame Interrupt * @arg LCD_IT_UDD: Update Display Done Interrupt * @retval None */ #define __HAL_LCD_ENABLE_IT(__HANDLE__, __INTERRUPT__) \ do{ \ SET_BIT((__HANDLE__)->Instance->FCR, (__INTERRUPT__)); \ LCD_WaitForSynchro(__HANDLE__); \ }while(0) #define __HAL_LCD_DISABLE_IT(__HANDLE__, __INTERRUPT__) \ do{ \ CLEAR_BIT((__HANDLE__)->Instance->FCR, (__INTERRUPT__)); \ LCD_WaitForSynchro(__HANDLE__); \ }while(0) /** @brief Checks whether the specified LCD interrupt is enabled or not. * @param __HANDLE__: specifies the LCD Handle. * @param __IT__: specifies the LCD interrupt source to check. * This parameter can be one of the following values: * @arg LCD_IT_SOF: Start of Frame Interrupt * @arg LCD_IT_UDD: Update Display Done Interrupt. * @note If the device is in STOP mode (PCLK not provided) UDD will not * generate an interrupt even if UDDIE = 1. * If the display is not enabled the UDD interrupt will never occur. * @retval The state of __IT__ (TRUE or FALSE). */ #define __HAL_LCD_GET_IT_SOURCE(__HANDLE__, __IT__) (((__HANDLE__)->Instance->FCR) & (__IT__)) /** @brief Checks whether the specified LCD flag is set or not. * @param __HANDLE__: specifies the LCD Handle. * @param __FLAG__: specifies the flag to check. * This parameter can be one of the following values: * @arg LCD_FLAG_ENS: LCD Enabled flag. It indicates the LCD controller status. * @note The ENS bit is set immediately when the LCDEN bit in the LCD_CR * goes from 0 to 1. On deactivation it reflects the real status of * LCD so it becomes 0 at the end of the last displayed frame. * @arg LCD_FLAG_SOF: Start of Frame flag. This flag is set by hardware at * the beginning of a new frame, at the same time as the display data is * updated. * @arg LCD_FLAG_UDR: Update Display Request flag. * @arg LCD_FLAG_UDD: Update Display Done flag. * @arg LCD_FLAG_RDY: Step_up converter Ready flag. It indicates the status * of the step-up converter. * @arg LCD_FLAG_FCRSF: LCD Frame Control Register Synchronization Flag. * This flag is set by hardware each time the LCD_FCR register is updated * in the LCDCLK domain. * @retval The new state of __FLAG__ (TRUE or FALSE). */ #define __HAL_LCD_GET_FLAG(__HANDLE__, __FLAG__) (((__HANDLE__)->Instance->SR & (__FLAG__)) == (__FLAG__)) /** @brief Clears the specified LCD pending flag. * @param __HANDLE__: specifies the LCD Handle. * @param __FLAG__: specifies the flag to clear. * This parameter can be any combination of the following values: * @arg LCD_FLAG_SOF: Start of Frame Interrupt * @arg LCD_FLAG_UDD: Update Display Done Interrupt * @retval None */ #define __HAL_LCD_CLEAR_FLAG(__HANDLE__, __FLAG__) ((__HANDLE__)->Instance->CLR = (__FLAG__)) /** * @} */ /* Exported functions ------------------------------------------------------- */ /** @addtogroup LCD_Exported_Functions * @{ */ /** @addtogroup LCD_Exported_Functions_Group1 * @{ */ /* Initialization/de-initialization methods **********************************/ HAL_StatusTypeDef HAL_LCD_DeInit(LCD_HandleTypeDef *hlcd); HAL_StatusTypeDef HAL_LCD_Init(LCD_HandleTypeDef *hlcd); void HAL_LCD_MspInit(LCD_HandleTypeDef *hlcd); void HAL_LCD_MspDeInit(LCD_HandleTypeDef *hlcd); /** * @} */ /** @addtogroup LCD_Exported_Functions_Group2 * @{ */ /* IO operation methods *******************************************************/ HAL_StatusTypeDef HAL_LCD_Write(LCD_HandleTypeDef *hlcd, uint32_t RAMRegisterIndex, uint32_t RAMRegisterMask, uint32_t Data); HAL_StatusTypeDef HAL_LCD_Clear(LCD_HandleTypeDef *hlcd); HAL_StatusTypeDef HAL_LCD_UpdateDisplayRequest(LCD_HandleTypeDef *hlcd); /** * @} */ /** @addtogroup LCD_Exported_Functions_Group3 * @{ */ /* Peripheral State methods **************************************************/ HAL_LCD_StateTypeDef HAL_LCD_GetState(LCD_HandleTypeDef *hlcd); uint32_t HAL_LCD_GetError(LCD_HandleTypeDef *hlcd); /** * @} */ /** * @} */ /** @addtogroup LCD_Private_Functions * @{ */ /* Private functions ---------------------------------------------------------*/ HAL_StatusTypeDef LCD_WaitForSynchro(LCD_HandleTypeDef *hlcd); /** * @} */ /** * @} */ #endif /* STM32L100xB || STM32L100xBA || STM32L100xC ||... || STM32L162xD || STM32L162xE */ /** * @} */ #ifdef __cplusplus } #endif #endif /* __STM32L1xx_HAL_LCD_H */ /******************* (C) COPYRIGHT 2014 STMicroelectronics *****END OF FILE****/ ================================================ FILE: Zelig/mbed/TARGET_NUCLEO_L152RE/stm32l1xx_hal_nor.h ================================================ /** ****************************************************************************** * @file stm32l1xx_hal_nor.h * @author MCD Application Team * @version V1.0.0 * @date 5-September-2014 * @brief Header file of NOR HAL module. ****************************************************************************** * @attention * *

© COPYRIGHT(c) 2014 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. * ****************************************************************************** */ /* Define to prevent recursive inclusion -------------------------------------*/ #ifndef __STM32L1xx_HAL_NOR_H #define __STM32L1xx_HAL_NOR_H #ifdef __cplusplus extern "C" { #endif /* Includes ------------------------------------------------------------------*/ #include "stm32l1xx_ll_fsmc.h" /** @addtogroup STM32L1xx_HAL_Driver * @{ */ /** @addtogroup NOR * @{ */ #if defined (STM32L151xD) || defined (STM32L152xD) || defined (STM32L162xD) /* Exported typedef ----------------------------------------------------------*/ /** @defgroup NOR_Exported_typedef NOR Exported typedef * @{ */ /** * @brief HAL SRAM State structures definition */ typedef enum { HAL_NOR_STATE_RESET = 0x00, /*!< NOR not yet initialized or disabled */ HAL_NOR_STATE_READY = 0x01, /*!< NOR initialized and ready for use */ HAL_NOR_STATE_BUSY = 0x02, /*!< NOR internal processing is ongoing */ HAL_NOR_STATE_ERROR = 0x03, /*!< NOR error state */ HAL_NOR_STATE_PROTECTED = 0x04 /*!< NOR NORSRAM device write protected */ }HAL_NOR_StateTypeDef; /** * @brief FSMC NOR Status typedef */ typedef enum { NOR_SUCCESS = 0, NOR_ONGOING, NOR_ERROR, NOR_TIMEOUT }NOR_StatusTypedef; /** * @brief FSMC NOR ID typedef */ typedef struct { uint16_t ManufacturerCode; /*!< Defines the device's manufacturer code used to identify the memory */ uint16_t DeviceCode1; uint16_t DeviceCode2; uint16_t DeviceCode3; /*!< Defines the devices' codes used to identify the memory. These codes can be accessed by performing read operations with specific control signals and addresses set.They can also be accessed by issuing an Auto Select command */ }NOR_IDTypeDef; /** * @brief FSMC NOR CFI typedef */ typedef struct { /*!< Defines the information stored in the memory's Common flash interface which contains a description of various electrical and timing parameters, density information and functions supported by the memory */ uint16_t CFI1; uint16_t CFI2; uint16_t CFI3; uint16_t CFI4; }NOR_CFITypeDef; /** * @brief NOR handle Structure definition */ typedef struct { FSMC_NORSRAM_TYPEDEF *Instance; /*!< Register base address */ FSMC_NORSRAM_EXTENDED_TYPEDEF *Extended; /*!< Extended mode register base address */ FSMC_NORSRAM_InitTypeDef Init; /*!< NOR device control configuration parameters */ HAL_LockTypeDef Lock; /*!< NOR locking object */ __IO HAL_NOR_StateTypeDef State; /*!< NOR device access state */ }NOR_HandleTypeDef; /** * @} */ /* Exported constants --------------------------------------------------------*/ /** @defgroup NOR_Exported_Constants NOR Exported Constants * @{ */ /* NOR device IDs addresses */ #define MC_ADDRESS ((uint16_t)0x0000) #define DEVICE_CODE1_ADDR ((uint16_t)0x0001) #define DEVICE_CODE2_ADDR ((uint16_t)0x000E) #define DEVICE_CODE3_ADDR ((uint16_t)0x000F) /* NOR CFI IDs addresses */ #define CFI1_ADDRESS ((uint16_t)0x10) #define CFI2_ADDRESS ((uint16_t)0x11) #define CFI3_ADDRESS ((uint16_t)0x12) #define CFI4_ADDRESS ((uint16_t)0x13) /* NOR operation wait timeout */ #define NOR_TMEOUT ((uint16_t)0xFFFF) /* NOR memory data width */ #define NOR_MEMORY_8B ((uint8_t)0x0) #define NOR_MEMORY_16B ((uint8_t)0x1) /* NOR memory device read/write start address */ #define NOR_MEMORY_ADRESS1 ((uint32_t)0x60000000) #define NOR_MEMORY_ADRESS2 ((uint32_t)0x64000000) #define NOR_MEMORY_ADRESS3 ((uint32_t)0x68000000) #define NOR_MEMORY_ADRESS4 ((uint32_t)0x6C000000) /** * @} */ /* Exported macro ------------------------------------------------------------*/ /** @defgroup NOR_Exported_macro NOR Exported macro * @{ */ /** @brief Reset NOR handle state * @param __HANDLE__: NOR handle * @retval None */ #define __HAL_NOR_RESET_HANDLE_STATE(__HANDLE__) ((__HANDLE__)->State = HAL_NOR_STATE_RESET) /** * @brief NOR memory address shifting. * @param __NOR_ADDRESS: NOR base address * @param __NOR_MEMORY_WIDTH_: NOR memory width * @param __ADDRESS__: NOR memory address * @retval NOR shifted address value */ #define __NOR_ADDR_SHIFT(__NOR_ADDRESS, __NOR_MEMORY_WIDTH_, __ADDRESS__) \ ((uint32_t)(((__NOR_MEMORY_WIDTH_) == NOR_MEMORY_16B)? \ ((uint32_t)((__NOR_ADDRESS) + (2 * (__ADDRESS__)))): \ ((uint32_t)((__NOR_ADDRESS) + (__ADDRESS__))))) /** * @brief NOR memory write data to specified address. * @param __ADDRESS__: NOR memory address * @param __DATA__: Data to write * @retval None */ #define __NOR_WRITE(__ADDRESS__, __DATA__) (*(__IO uint16_t *)((uint32_t)(__ADDRESS__)) = (__DATA__)) /** * @} */ /* Exported functions --------------------------------------------------------*/ /** @addtogroup NOR_Exported_Functions * @{ */ /** @addtogroup NOR_Exported_Functions_Group1 * @{ */ /* Initialization/de-initialization functions **********************************/ HAL_StatusTypeDef HAL_NOR_Init(NOR_HandleTypeDef *hnor, FSMC_NORSRAM_TimingTypeDef *Timing, FSMC_NORSRAM_TimingTypeDef *ExtTiming); HAL_StatusTypeDef HAL_NOR_DeInit(NOR_HandleTypeDef *hnor); void HAL_NOR_MspInit(NOR_HandleTypeDef *hnor); void HAL_NOR_MspDeInit(NOR_HandleTypeDef *hnor); void HAL_NOR_MspWait(NOR_HandleTypeDef *hnor, uint32_t Timeout); /** * @} */ /** @addtogroup NOR_Exported_Functions_Group2 * @{ */ /* I/O operation functions *****************************************************/ HAL_StatusTypeDef HAL_NOR_Read_ID(NOR_HandleTypeDef *hnor, NOR_IDTypeDef *pNOR_ID); HAL_StatusTypeDef HAL_NOR_ReturnToReadMode(NOR_HandleTypeDef *hnor); HAL_StatusTypeDef HAL_NOR_Read(NOR_HandleTypeDef *hnor, uint32_t *pAddress, uint16_t *pData); HAL_StatusTypeDef HAL_NOR_Program(NOR_HandleTypeDef *hnor, uint32_t *pAddress, uint16_t *pData); HAL_StatusTypeDef HAL_NOR_ReadBuffer(NOR_HandleTypeDef *hnor, uint32_t uwAddress, uint16_t *pData, uint32_t uwBufferSize); HAL_StatusTypeDef HAL_NOR_ProgramBuffer(NOR_HandleTypeDef *hnor, uint32_t uwAddress, uint16_t *pData, uint32_t uwBufferSize); HAL_StatusTypeDef HAL_NOR_Erase_Block(NOR_HandleTypeDef *hnor, uint32_t BlockAddress, uint32_t Address); HAL_StatusTypeDef HAL_NOR_Erase_Chip(NOR_HandleTypeDef *hnor, uint32_t Address); HAL_StatusTypeDef HAL_NOR_Read_CFI(NOR_HandleTypeDef *hnor, NOR_CFITypeDef *pNOR_CFI); /** * @} */ /** @addtogroup NOR_Exported_Functions_Group3 * @{ */ /* NOR Control functions *******************************************************/ HAL_StatusTypeDef HAL_NOR_WriteOperation_Enable(NOR_HandleTypeDef *hnor); HAL_StatusTypeDef HAL_NOR_WriteOperation_Disable(NOR_HandleTypeDef *hnor); /** * @} */ /** @addtogroup NOR_Exported_Functions_Group4 * @{ */ /* NOR State functions **********************************************************/ HAL_NOR_StateTypeDef HAL_NOR_GetState(NOR_HandleTypeDef *hnor); NOR_StatusTypedef HAL_NOR_GetStatus(NOR_HandleTypeDef *hnor, uint32_t Address, uint32_t Timeout); /** * @} */ /** * @} */ #endif /* STM32L151xD || STM32L152xD || STM32L162xD */ /** * @} */ /** * @} */ #ifdef __cplusplus } #endif #endif /* __STM32L1xx_HAL_NOR_H */ /************************ (C) COPYRIGHT STMicroelectronics *****END OF FILE****/ ================================================ FILE: Zelig/mbed/TARGET_NUCLEO_L152RE/stm32l1xx_hal_opamp.h ================================================ /** ****************************************************************************** * @file stm32l1xx_hal_opamp.h * @author MCD Application Team * @version V1.0.0 * @date 5-September-2014 * @brief Header file of OPAMP HAL module. ****************************************************************************** * @attention * *

© COPYRIGHT(c) 2014 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. * ****************************************************************************** */ /* Define to prevent recursive inclusion -------------------------------------*/ #ifndef __STM32L1xx_HAL_OPAMP_H #define __STM32L1xx_HAL_OPAMP_H #ifdef __cplusplus extern "C" { #endif #if defined (STM32L151xCA) || defined (STM32L151xD) || defined (STM32L152xCA) || defined (STM32L152xD) || defined (STM32L162xCA) || defined (STM32L162xD) || defined (STM32L151xE) || defined (STM32L152xE) || defined (STM32L162xE) || defined (STM32L162xC) || defined (STM32L152xC) || defined (STM32L151xC) /* Includes ------------------------------------------------------------------*/ #include "stm32l1xx_hal_def.h" /** @addtogroup STM32L1xx_HAL_Driver * @{ */ /** @addtogroup OPAMP * @{ */ /* Exported types ------------------------------------------------------------*/ /** @defgroup OPAMP_Exported_Types OPAMP Exported Types * @{ */ /** * @brief OPAMP Init structure definition */ typedef struct { uint32_t PowerSupplyRange; /*!< Specifies the power supply range: above or under 2.4V. This parameter must be a value of @ref OPAMP_PowerSupplyRange Caution: This parameter is common to all OPAMP instances: a modification of this parameter for the selected OPAMP impacts the other OPAMP instances. */ uint32_t UserTrimming; /*!< Specifies the trimming mode This parameter must be a value of @ref OPAMP_UserTrimming UserTrimming is either factory or user trimming. Caution: This parameter is common to all OPAMP instances: a modification of this parameter for the selected OPAMP impacts the other OPAMP instances. */ uint32_t Mode; /*!< Specifies the OPAMP mode This parameter must be a value of @ref OPAMP_Mode mode is either Standalone or Follower */ uint32_t InvertingInput; /*!< Specifies the inverting input in Standalone mode - In Standalone mode: i.e when mode is OPAMP_STANDALONE_MODE This parameter must be a value of @ref OPAMP_InvertingInput InvertingInput is either VM0 or VM1 - In Follower mode: i.e when mode is OPAMP_FOLLOWER_MODE This parameter is Not Applicable */ uint32_t NonInvertingInput; /*!< Specifies the non inverting input of the opamp: This parameter must be a value of @ref OPAMP_NonInvertingInput NonInvertingInput is either VP0, VP1 or VP2 */ uint32_t PowerMode; /*!< Specifies the power mode Normal or Low-Power. This parameter must be a value of @ref OPAMP_PowerMode */ uint32_t TrimmingValueP; /*!< Specifies the offset trimming value (PMOS) i.e. when UserTrimming is OPAMP_TRIMMING_USER. This parameter must be a number between Min_Data = 0 and Max_Data = 30 (Trimming value 31 is forbidden) */ uint32_t TrimmingValueN; /*!< Specifies the offset trimming value (NMOS) i.e. when UserTrimming is OPAMP_TRIMMING_USER. This parameter must be a number between Min_Data = 0 and Max_Data = 30 (Trimming value 31 is forbidden) */ uint32_t TrimmingValuePLowPower; /*!< Specifies the offset trimming value (PMOS) i.e. when UserTrimming is OPAMP_TRIMMING_USER. This parameter must be a number between Min_Data = 0 and Max_Data = 30 (Trimming value 31 is forbidden) */ uint32_t TrimmingValueNLowPower; /*!< Specifies the offset trimming value (NMOS) i.e. when UserTrimming is OPAMP_TRIMMING_USER. This parameter must be a number between Min_Data = 0 and Max_Data = 30 (Trimming value 31 is forbidden) */ }OPAMP_InitTypeDef; /** * @brief HAL State structures definition */ typedef enum { HAL_OPAMP_STATE_RESET = 0x00000000, /*!< OPMAP is not yet Initialized */ HAL_OPAMP_STATE_READY = 0x00000001, /*!< OPAMP is initialized and ready for use */ HAL_OPAMP_STATE_CALIBBUSY = 0x00000002, /*!< OPAMP is enabled in auto calibration mode */ HAL_OPAMP_STATE_BUSY = 0x00000004, /*!< OPAMP is enabled and running in normal mode */ HAL_OPAMP_STATE_BUSYLOCKED = 0x00000005, /*!< OPAMP is locked only system reset allows reconfiguring the opamp. */ }HAL_OPAMP_StateTypeDef; /** * @brief OPAMP Handle Structure definition */ typedef struct { OPAMP_TypeDef *Instance; /*!< OPAMP instance's registers base address */ OPAMP_InitTypeDef Init; /*!< OPAMP required parameters */ HAL_StatusTypeDef Status; /*!< OPAMP peripheral status */ HAL_LockTypeDef Lock; /*!< Locking object */ __IO HAL_OPAMP_StateTypeDef State; /*!< OPAMP communication state */ } OPAMP_HandleTypeDef; /** * @brief OPAMP_TrimmingValueTypeDef @brief definition */ typedef uint32_t OPAMP_TrimmingValueTypeDef; /** * @} */ /* Exported constants --------------------------------------------------------*/ /** @defgroup OPAMP_Exported_Constants OPAMP Exported Constants * @{ */ /** * OTR register Mask */ #define OPAMP_TRIM_VALUE_MASK OPAMP_OTR_AO1_OPT_OFFSET_TRIM_LOW /** * CSR register Mask */ #define OPAMP_CSR_INSTANCE_OFFSET ((uint32_t) 8) /* Offset of each OPAMP instance into register CSR */ #define OPAMP_OTR_INSTANCE_OFFSET ((uint32_t) 10) /* Offset of each OPAMP instance into register OTR */ /** @defgroup OPAMP_Mode OPAMP Mode * @{ */ #define OPAMP_STANDALONE_MODE ((uint32_t)0x00000000) /*!< OPAMP standalone mode */ #define OPAMP_FOLLOWER_MODE ((uint32_t)0x00000001) /*!< OPAMP follower mode */ #define IS_OPAMP_FUNCTIONAL_NORMALMODE(INPUT) (((INPUT) == OPAMP_STANDALONE_MODE) || \ ((INPUT) == OPAMP_FOLLOWER_MODE)) /** * @} */ /** @defgroup OPAMP_NonInvertingInput OPAMP NonInvertingInput * @{ */ #define OPAMP_NONINVERTINGINPUT_VP0 ((uint32_t)0x00000000) /*!< Comparator non-inverting input connected to dedicated IO pin low-leakage */ #define OPAMP_NONINVERTINGINPUT_DAC_CH1 ((uint32_t)0x00000001) /*!< Comparator non-inverting input connected internally to DAC channel 1 */ #define OPAMP_NONINVERTINGINPUT_DAC_CH2 ((uint32_t)0x00000002) /*!< Comparator non-inverting input connected internally to DAC channel 2. Available on OPAMP2 only. */ #define IS_OPAMP_NONINVERTING_INPUT(INPUT) (((INPUT) == OPAMP_NONINVERTINGINPUT_VP0) || \ ((INPUT) == OPAMP_NONINVERTINGINPUT_DAC_CH1) || \ ((INPUT) == OPAMP_NONINVERTINGINPUT_DAC_CH2) ) /** * @} */ /** @defgroup OPAMP_InvertingInput OPAMP InvertingInput * @{ */ #define OPAMP_INVERTINGINPUT_VM0 ((uint32_t)0x00000000) /*!< Comparator inverting input connected to dedicated IO pin low-leakage */ #define OPAMP_INVERTINGINPUT_VM1 ((uint32_t)0x00000001) /*!< Comparator inverting input connected to alternative IO pin available on some device packages */ #define OPAMP_INVERTINGINPUT_VINM OPAMP_INVERTINGINPUT_VM1 /*!< Alternate name for comparator inverting input connected to alternative IO pin available on some device packages */ #define IOPAMP_INVERTINGINPUT_VM0 OPAMP_INVERTINGINPUT_VM0 /* For compatibility with other STM32 devices */ #define IOPAMP_INVERTINGINPUT_VM1 OPAMP_INVERTINGINPUT_VM1 /* For compatibility with other STM32 devices */ #define IS_OPAMP_INVERTING_INPUT(INPUT) (((INPUT) == OPAMP_INVERTINGINPUT_VM0) || \ ((INPUT) == OPAMP_INVERTINGINPUT_VM1) ) /** * @} */ /** @defgroup OPAMP_PowerMode OPAMP PowerMode * @{ */ #define OPAMP_POWERMODE_NORMAL ((uint32_t)0x00000000) #define OPAMP_POWERMODE_LOWPOWER ((uint32_t)0x00000001) #define IS_OPAMP_POWERMODE(TRIMMING) (((TRIMMING) == OPAMP_POWERMODE_NORMAL) || \ ((TRIMMING) == OPAMP_POWERMODE_LOWPOWER) ) /** * @} */ /** @defgroup OPAMP_PowerSupplyRange OPAMP PowerSupplyRange * @{ */ #define OPAMP_POWERSUPPLY_LOW ((uint32_t)0x00000000) /*!< Power supply range low (VDDA lower than 2.4V) */ #define OPAMP_POWERSUPPLY_HIGH OPAMP_CSR_AOP_RANGE /*!< Power supply range high (VDDA higher than 2.4V) */ #define IS_OPAMP_POWER_SUPPLY_RANGE(RANGE) (((RANGE) == OPAMP_POWERSUPPLY_LOW) || \ ((RANGE) == OPAMP_POWERSUPPLY_HIGH) ) /** * @} */ /** @defgroup OPAMP_UserTrimming OPAMP UserTrimming * @{ */ #define OPAMP_TRIMMING_FACTORY ((uint32_t)0x00000000) /*!< Factory trimming */ #define OPAMP_TRIMMING_USER OPAMP_OTR_OT_USER /*!< User trimming */ #define IS_OPAMP_TRIMMING(TRIMMING) (((TRIMMING) == OPAMP_TRIMMING_FACTORY) || \ ((TRIMMING) == OPAMP_TRIMMING_USER)) /** * @} */ /** @defgroup OPAMP_FactoryTrimming OPAMP FactoryTrimming * @{ */ #define OPAMP_FACTORYTRIMMING_DUMMY ((uint32_t)0xFFFFFFFF) /*!< Dummy value if trimming value could not be retrieved */ #define OPAMP_FACTORYTRIMMING_P ((uint32_t)0x00000000) /*!< Offset trimming P */ #define OPAMP_FACTORYTRIMMING_N POSITION_VAL(OPAMP_OTR_AO1_OPT_OFFSET_TRIM_HIGH) /*!< Offset trimming N */ #define IS_OPAMP_FACTORYTRIMMING(TRIMMING) (((TRIMMING) == OPAMP_FACTORYTRIMMING_N) || \ ((TRIMMING) == OPAMP_FACTORYTRIMMING_P) ) /** * @} */ /** * @} */ /* Private constants ---------------------------------------------------------*/ /** @defgroup OPAMP_Private_Constants OPAMP Private Constants * @{ */ /* Offset trimming time: during calibration, minimum time needed between two */ /* steps to have 1 mV accuracy. */ /* Refer to datasheet, electrical characteristics: parameter tOFFTRIM Typ=1ms.*/ /* Unit: ms. */ #define OPAMP_TRIMMING_DELAY ((uint32_t) 1) /** * @} */ /* Exported macros -----------------------------------------------------------*/ /** @defgroup OPAMP_Private_Macro OPAMP Private Macro * @{ */ /** @brief Reset OPAMP handle state * @param __HANDLE__: OPAMP handle. * @retval None */ #define __HAL_OPAMP_RESET_HANDLE_STATE(__HANDLE__) ((__HANDLE__)->State = HAL_OPAMP_STATE_RESET) /** * @} */ /* Private macro -------------------------------------------------------------*/ /** @defgroup OPAMP_Private_Macro OPAMP Private Macro * @{ */ /** * @brief Select the OPAMP bit OPAxPD (power-down) corresponding to the * selected OPAMP instance. * @param __HANDLE__: OPAMP handle * @retval None */ #define __OPAMP_CSR_OPAXPD(__HANDLE__) \ (OPAMP_CSR_OPA1PD << (__OPAMP_INSTANCE_DECIMAL__(__HANDLE__) * OPAMP_CSR_INSTANCE_OFFSET)) /** * @brief Select the OPAMP bit S3SELx (switch 3) corresponding to the * selected OPAMP instance. * @param __HANDLE__: OPAMP handle * @retval None */ #define __OPAMP_CSR_S3SELX(__HANDLE__) \ (OPAMP_CSR_S3SEL1 << (__OPAMP_INSTANCE_DECIMAL__(__HANDLE__) * OPAMP_CSR_INSTANCE_OFFSET)) /** * @brief Select the OPAMP bit S4SELx (switch 4) corresponding to the * selected OPAMP instance. * @param __HANDLE__: OPAMP handle * @retval None */ #define __OPAMP_CSR_S4SELX(__HANDLE__) \ (OPAMP_CSR_S4SEL1 << (__OPAMP_INSTANCE_DECIMAL__(__HANDLE__) * OPAMP_CSR_INSTANCE_OFFSET)) /** * @brief Select the OPAMP bit S5SELx (switch 5) corresponding to the * selected OPAMP instance. * @param __HANDLE__: OPAMP handle * @retval None */ #define __OPAMP_CSR_S5SELX(__HANDLE__) \ (OPAMP_CSR_S5SEL1 << (__OPAMP_INSTANCE_DECIMAL__(__HANDLE__) * OPAMP_CSR_INSTANCE_OFFSET)) /** * @brief Select the OPAMP bit S3SELx (switch 6) corresponding to the * selected OPAMP instance. * @param __HANDLE__: OPAMP handle * @retval None */ #define __OPAMP_CSR_S6SELX(__HANDLE__) \ (OPAMP_CSR_S6SEL1 << (__OPAMP_INSTANCE_DECIMAL__(__HANDLE__) * OPAMP_CSR_INSTANCE_OFFSET)) /** * @brief Select the OPAMP bit OPAxCAL_L (offset calibration for differential * pair P) corresponding to the selected OPAMP instance. * @param __HANDLE__: OPAMP handle * @retval None */ #define __OPAMP_CSR_OPAXCAL_L(__HANDLE__) \ (OPAMP_CSR_OPA1CAL_L << (__OPAMP_INSTANCE_DECIMAL__(__HANDLE__) * OPAMP_CSR_INSTANCE_OFFSET)) /** * @brief Select the OPAMP bit OPAxCAL_H (offset calibration for differential * pair N) corresponding to the selected OPAMP instance. * @param __HANDLE__: OPAMP handle * @retval None */ #define __OPAMP_CSR_OPAXCAL_H(__HANDLE__) \ (OPAMP_CSR_OPA1CAL_H << (__OPAMP_INSTANCE_DECIMAL__(__HANDLE__) * OPAMP_CSR_INSTANCE_OFFSET)) /** * @brief Select the OPAMP bit OPAxLPM (low power mode) corresponding to the * selected OPAMP instance. * @param __HANDLE__: OPAMP handle * @retval None */ #define __OPAMP_CSR_OPAXLPM(__HANDLE__) \ (OPAMP_CSR_OPA1LPM << (__OPAMP_INSTANCE_DECIMAL__(__HANDLE__) * OPAMP_CSR_INSTANCE_OFFSET)) /** * @brief Select the OPAMP bits of all switches corresponding to the * selected OPAMP instance. * @param __HANDLE__: OPAMP handle * @retval None */ #define __OPAMP_CSR_ALL_SWITCHES(__HANDLE__) \ ( ( ((__HANDLE__)->Instance != OPAMP2) \ )? \ ( \ ((OPAMP_CSR_S3SEL1 | OPAMP_CSR_S4SEL1 | OPAMP_CSR_S5SEL1 | OPAMP_CSR_S6SEL1) << (__OPAMP_INSTANCE_DECIMAL__(__HANDLE__) * OPAMP_CSR_INSTANCE_OFFSET)) \ | \ (OPAMP_CSR_ANAWSEL1 << (__OPAMP_INSTANCE_DECIMAL__(__HANDLE__))) \ ) \ : \ ( \ ((OPAMP_CSR_S3SEL1 | OPAMP_CSR_S4SEL1 | OPAMP_CSR_S5SEL1 | OPAMP_CSR_S6SEL1) << (__OPAMP_INSTANCE_DECIMAL__(__HANDLE__) * OPAMP_CSR_INSTANCE_OFFSET)) \ | \ (OPAMP_CSR_ANAWSEL1 << (__OPAMP_INSTANCE_DECIMAL__(__HANDLE__))) \ | \ (OPAMP_CSR_S7SEL2) \ ) \ ) /** * @brief Select the OPAMP bit ANAWSELx (switch SanA) corresponding to the * selected OPAMP instance. * @param __HANDLE__: OPAMP handle * @retval None */ #define __OPAMP_CSR_ANAWSELX(__HANDLE__) \ (OPAMP_CSR_ANAWSEL1 << (__OPAMP_INSTANCE_DECIMAL__(__HANDLE__))) /** * @brief Select the OPAMP bit OPAxCALOUT in function of the selected * OPAMP instance. * @param __HANDLE__: OPAMP handle * @retval None */ #define __OPAMP_CSR_OPAXCALOUT(__HANDLE__) \ (OPAMP_CSR_OPA1CALOUT << (__OPAMP_INSTANCE_DECIMAL__(__HANDLE__))) /** * @brief Select the OPAMP trimming bits position value (position of LSB) * in register OPAMP_OTR or register OPAMP_LPOTR in function of the selected * OPAMP instance and the transistors differential pair high (PMOS) or * low (NMOS). * @param __HANDLE__: OPAMP handle * @param __TRIM_HIGH_LOW__: transistors differential pair high or low. * Must be a value of @ref OPAMP_FactoryTrimming. * @retval None */ #define __OPAMP_OFFSET_TRIM_BITSPOSITION(__HANDLE__, __TRIM_HIGH_LOW__) \ ((__OPAMP_INSTANCE_DECIMAL__((__HANDLE__)) * OPAMP_OTR_INSTANCE_OFFSET) + (__TRIM_HIGH_LOW__)) /** * @brief Shift the OPAMP trimming bits to register OPAMP_OTR or register * OPAMP_LPOTR in function of the selected OPAMP instance and the transistors * differential pair high (PMOS) or low (NMOS). * @param __HANDLE__: OPAMP handle * @param __TRIM_HIGH_LOW__: transistors differential pair high or low. * Must be a value of @ref OPAMP_FactoryTrimming. * @param __TRIMMING_VALUE__: Trimming value * @retval None */ #define __OPAMP_OFFSET_TRIM_SET(__HANDLE__, __TRIM_HIGH_LOW__, __TRIMMING_VALUE__) \ ((__TRIMMING_VALUE__) << (__OPAMP_OFFSET_TRIM_BITSPOSITION((__HANDLE__), (__TRIM_HIGH_LOW__)))) /** * @brief Check that trimming value is within correct range * @param TRIMMINGVALUE: OPAMP trimming value * @retval None */ #define IS_OPAMP_TRIMMINGVALUE(TRIMMINGVALUE) ((TRIMMINGVALUE) <= 0x1E) /** * @} */ /* Include OPAMP HAL Extension module */ #include "stm32l1xx_hal_opamp_ex.h" /* Exported functions --------------------------------------------------------*/ /** @addtogroup OPAMP_Exported_Functions * @{ */ /** @addtogroup OPAMP_Exported_Functions_Group1 * @{ */ /* Initialization/de-initialization functions **********************************/ HAL_StatusTypeDef HAL_OPAMP_Init(OPAMP_HandleTypeDef *hopamp); HAL_StatusTypeDef HAL_OPAMP_DeInit (OPAMP_HandleTypeDef *hopamp); void HAL_OPAMP_MspInit(OPAMP_HandleTypeDef *hopamp); void HAL_OPAMP_MspDeInit(OPAMP_HandleTypeDef *hopamp); /** * @} */ /** @addtogroup OPAMP_Exported_Functions_Group2 * @{ */ /* I/O operation functions *****************************************************/ HAL_StatusTypeDef HAL_OPAMP_Start(OPAMP_HandleTypeDef *hopamp); HAL_StatusTypeDef HAL_OPAMP_Stop(OPAMP_HandleTypeDef *hopamp); HAL_StatusTypeDef HAL_OPAMP_SelfCalibrate(OPAMP_HandleTypeDef *hopamp); OPAMP_TrimmingValueTypeDef HAL_OPAMP_GetTrimOffset (OPAMP_HandleTypeDef *hopamp, uint32_t trimmingoffset); /** * @} */ /** @addtogroup OPAMP_Exported_Functions_Group3 * @{ */ /* Peripheral Control functions ************************************************/ HAL_StatusTypeDef HAL_OPAMP_Lock(OPAMP_HandleTypeDef *hopamp); /** * @} */ /** @addtogroup OPAMP_Exported_Functions_Group4 * @{ */ /* Peripheral State functions **************************************************/ HAL_OPAMP_StateTypeDef HAL_OPAMP_GetState(OPAMP_HandleTypeDef *hopamp); /** * @} */ /** * @} */ /** * @} */ /** * @} */ #endif /* STM32L151xCA || STM32L151xD || STM32L152xCA || STM32L152xD || STM32L162xCA || STM32L162xD || STM32L151xE || STM32L152xE || STM32L162xE || STM32L162xC || STM32L152xC || STM32L151xC */ #ifdef __cplusplus } #endif #endif /* __STM32L1xx_HAL_OPAMP_H */ /************************ (C) COPYRIGHT STMicroelectronics *****END OF FILE****/ ================================================ FILE: Zelig/mbed/TARGET_NUCLEO_L152RE/stm32l1xx_hal_opamp_ex.h ================================================ /** ****************************************************************************** * @file stm32l1xx_hal_opamp_ex.h * @author MCD Application Team * @version V1.0.0 * @date 5-September-2014 * @brief Header file of OPAMP HAL Extension module. ****************************************************************************** * @attention * *

© COPYRIGHT(c) 2014 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. * ****************************************************************************** */ /* Define to prevent recursive inclusion -------------------------------------*/ #ifndef __STM32L1xx_HAL_OPAMP_EX_H #define __STM32L1xx_HAL_OPAMP_EX_H #ifdef __cplusplus extern "C" { #endif #if defined (STM32L151xCA) || defined (STM32L151xD) || defined (STM32L152xCA) || defined (STM32L152xD) || defined (STM32L162xCA) || defined (STM32L162xD) || defined (STM32L151xE) || defined (STM32L152xE) || defined (STM32L162xE) || defined (STM32L162xC) || defined (STM32L152xC) || defined (STM32L151xC) /* Includes ------------------------------------------------------------------*/ #include "stm32l1xx_hal_def.h" /** @addtogroup STM32L1xx_HAL_Driver * @{ */ /** @addtogroup OPAMPEx * @{ */ /* Exported types ------------------------------------------------------------*/ /* Exported constants ---------------------------------------------------------*/ /** @defgroup OPAMPEx_Exported_Constants OPAMPEx Exported Constants * @{ */ #if defined (STM32L151xD) || defined (STM32L152xD) || defined (STM32L162xD) #define OPAMP_CSR_OPAXPD_ALL \ (OPAMP_CSR_OPA1PD | OPAMP_CSR_OPA2PD | OPAMP_CSR_OPA3PD) #define OPAMP_CSR_OPAXCAL_L_ALL \ (OPAMP_CSR_OPA1CAL_L | OPAMP_CSR_OPA2CAL_L | OPAMP_CSR_OPA3CAL_L) #define OPAMP_CSR_OPAXCAL_H_ALL \ (OPAMP_CSR_OPA1CAL_H | OPAMP_CSR_OPA2CAL_H | OPAMP_CSR_OPA3CAL_H) #define OPAMP_CSR_ALL_SWITCHES_ALL_OPAMPS \ (OPAMP_CSR_S3SEL1 | OPAMP_CSR_S4SEL1 | OPAMP_CSR_S5SEL1 | OPAMP_CSR_S6SEL1 | \ OPAMP_CSR_ANAWSEL1 | \ OPAMP_CSR_S3SEL2 | OPAMP_CSR_S4SEL2 | OPAMP_CSR_S5SEL2 | OPAMP_CSR_S6SEL2 | \ OPAMP_CSR_ANAWSEL2 | OPAMP_CSR_S7SEL2 | \ OPAMP_CSR_S3SEL3 | OPAMP_CSR_S4SEL3 | OPAMP_CSR_S5SEL3 | OPAMP_CSR_S6SEL3 | \ OPAMP_CSR_ANAWSEL3 ) #else #define OPAMP_CSR_OPAXPD_ALL \ (OPAMP_CSR_OPA1PD | OPAMP_CSR_OPA2PD) #define OPAMP_CSR_OPAXCAL_L_ALL \ (OPAMP_CSR_OPA1CAL_L | OPAMP_CSR_OPA2CAL_L) #define OPAMP_CSR_OPAXCAL_H_ALL \ (OPAMP_CSR_OPA1CAL_H | OPAMP_CSR_OPA2CAL_H) #define OPAMP_CSR_ALL_SWITCHES_ALL_OPAMPS \ (OPAMP_CSR_S3SEL1 | OPAMP_CSR_S4SEL1 | OPAMP_CSR_S5SEL1 | OPAMP_CSR_S6SEL1 | \ OPAMP_CSR_ANAWSEL1 | \ OPAMP_CSR_S3SEL2 | OPAMP_CSR_S4SEL2 | OPAMP_CSR_S5SEL2 | OPAMP_CSR_S6SEL2 | \ OPAMP_CSR_ANAWSEL2 | OPAMP_CSR_S7SEL2 ) #endif /* STM32L151xD || STM32L152xD || STM32L162xD */ /** * @} */ /* Exported macro ------------------------------------------------------------*/ /** @defgroup OPAMPEx_Exported_Macro OPAMPEx Exported Macro * @{ */ #if defined (STM32L151xD) || defined (STM32L152xD) || defined (STM32L162xD) /** * @brief Enable internal analog switch SW1 to connect OPAMP3 ouput to ADC * switch matrix (ADC channel VCOMP, channel 26) and COMP1 non-inverting input * (OPAMP3 available on STM32L1 devices Cat.4 only). * @retval None */ #define __HAL_OPAMP_OPAMP3OUT_CONNECT_ADC_COMP1() __HAL_RI_SWITCH_COMP1_SW1_CLOSE() /** * @brief Disable internal analog switch SW1 to disconnect OPAMP3 ouput from * ADC switch matrix (ADC channel VCOMP, channel 26) and COMP1 non-inverting * input. * @retval None */ #define __HAL_OPAMP_OPAMP3OUT_DISCONNECT_ADC_COMP1() __HAL_RI_SWITCH_COMP1_SW1_OPEN() #endif /* STM32L151xD || STM32L152xD || STM32L162xD */ /** * @} */ /* Private macro -------------------------------------------------------------*/ /** @defgroup OPAMPEx_Private_Macro OPAMPEx Private Macro * @{ */ #if defined (STM32L151xD) || defined (STM32L152xD) || defined (STM32L162xD) /** * @brief Get the OPAMP instance in decimal number for further * processing needs by HAL OPAMP driver functions. * @param __HANDLE__: OPAMP handle * @retval "0" for OPAMP1, "1" for OPAMP2, "2" for OPAMP3 */ #define __OPAMP_INSTANCE_DECIMAL__(__HANDLE__) \ ( ( ((__HANDLE__)->Instance == OPAMP1) \ )? \ ((uint32_t)0) \ : \ ( ( ((__HANDLE__)->Instance == OPAMP2) \ )? \ ((uint32_t)1) \ : \ ((uint32_t)2) \ ) \ ) #else /** * @brief Get the OPAMP instance in decimal number for further * processing needs by HAL OPAMP driver functions. * @param __HANDLE__: OPAMP handle * @retval "0" for OPAMP1, "1" for OPAMP2 */ #define __OPAMP_INSTANCE_DECIMAL__(__HANDLE__) \ ( ( ((__HANDLE__)->Instance == OPAMP1) \ )? \ ((uint32_t)0) \ : \ ((uint32_t)1) \ ) #endif /* STM32L151xD || STM32L152xD || STM32L162xD */ /** * @} */ /* Exported functions --------------------------------------------------------*/ /** @addtogroup OPAMPEx_Exported_Functions * @{ */ /* I/O operation functions *****************************************************/ /** @defgroup OPAMPEx_Exported_Functions_Group1 Extended IO operation functions * @{ */ #if defined (STM32L151xD) || defined (STM32L152xD) || defined (STM32L162xD) HAL_StatusTypeDef HAL_OPAMPEx_SelfCalibrateAll(OPAMP_HandleTypeDef *hopamp1, OPAMP_HandleTypeDef *hopamp2, OPAMP_HandleTypeDef *hopamp3); #else HAL_StatusTypeDef HAL_OPAMPEx_SelfCalibrateAll(OPAMP_HandleTypeDef *hopamp1, OPAMP_HandleTypeDef *hopamp2); #endif /* STM32L151xD || STM32L152xD || STM32L162xD */ /** * @} */ /* Peripheral Control functions ************************************************/ /** @addtogroup OPAMPEx_Exported_Functions_Group2 * @{ */ HAL_StatusTypeDef HAL_OPAMPEx_Unlock(OPAMP_HandleTypeDef *hopamp); /** * @} */ /** * @} */ /** * @} */ /** * @} */ #endif /* STM32L151xCA || STM32L151xD || STM32L152xCA || STM32L152xD || STM32L162xCA || STM32L162xD || STM32L151xE || STM32L152xE || STM32L162xE || STM32L162xC || STM32L152xC || STM32L151xC */ #ifdef __cplusplus } #endif #endif /* __STM32L1xx_HAL_OPAMP_EX_H */ /************************ (C) COPYRIGHT STMicroelectronics *****END OF FILE****/ ================================================ FILE: Zelig/mbed/TARGET_NUCLEO_L152RE/stm32l1xx_hal_pcd.h ================================================ /** ****************************************************************************** * @file stm32l1xx_hal_pcd.h * @author MCD Application Team * @version V1.0.0 * @date 5-September-2014 * @brief Header file of PCD HAL module. ****************************************************************************** * @attention * *

© COPYRIGHT(c) 2014 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. * ****************************************************************************** */ /* Define to prevent recursive inclusion -------------------------------------*/ #ifndef __STM32L1xx_HAL_PCD_H #define __STM32L1xx_HAL_PCD_H #ifdef __cplusplus extern "C" { #endif /* Includes ------------------------------------------------------------------*/ #include "stm32l1xx_hal_def.h" /** @addtogroup STM32L1xx_HAL_Driver * @{ */ /** @addtogroup PCD * @{ */ /* Exported types ------------------------------------------------------------*/ /** @defgroup PCD_Exported_Types PCD Exported Types * @{ */ /** * @brief PCD State structures definition */ typedef enum { PCD_READY = 0x00, PCD_ERROR = 0x01, PCD_BUSY = 0x02, PCD_TIMEOUT = 0x03 } PCD_StateTypeDef; typedef enum { /* double buffered endpoint direction */ PCD_EP_DBUF_OUT, PCD_EP_DBUF_IN, PCD_EP_DBUF_ERR, }PCD_EP_DBUF_DIR; /* endpoint buffer number */ typedef enum { PCD_EP_NOBUF, PCD_EP_BUF0, PCD_EP_BUF1 }PCD_EP_BUF_NUM; /** * @brief PCD Initialization Structure definition */ typedef struct { uint32_t dev_endpoints; /*!< Device Endpoints number. This parameter depends on the used USB core. This parameter must be a number between Min_Data = 1 and Max_Data = 15 */ uint32_t speed; /*!< USB Core speed. This parameter can be any value of @ref USB_Core_Speed */ uint32_t ep0_mps; /*!< Set the Endpoint 0 Max Packet size. This parameter can be any value of @ref USB_EP0_MPS */ uint32_t phy_itface; /*!< Select the used PHY interface. This parameter can be any value of @ref USB_Core_PHY */ uint32_t Sof_enable; /*!< Enable or disable the output of the SOF signal. */ uint32_t low_power_enable; /*!< Enable or disable Low Power mode */ uint32_t lpm_enable; /*!< Enable or disable Battery charging. */ uint32_t battery_charging_enable; /*!< Enable or disable Battery charging. */ }PCD_InitTypeDef; typedef struct { uint8_t num; /*!< Endpoint number This parameter must be a number between Min_Data = 1 and Max_Data = 15 */ uint8_t is_in; /*!< Endpoint direction This parameter must be a number between Min_Data = 0 and Max_Data = 1 */ uint8_t is_stall; /*!< Endpoint stall condition This parameter must be a number between Min_Data = 0 and Max_Data = 1 */ uint8_t type; /*!< Endpoint type This parameter can be any value of @ref USB_EP_Type */ uint16_t pmaadress; /*!< PMA Address This parameter can be any value between Min_addr = 0 and Max_addr = 1K */ uint16_t pmaaddr0; /*!< PMA Address0 This parameter can be any value between Min_addr = 0 and Max_addr = 1K */ uint16_t pmaaddr1; /*!< PMA Address1 This parameter can be any value between Min_addr = 0 and Max_addr = 1K */ uint8_t doublebuffer; /*!< Double buffer enable This parameter can be 0 or 1 */ uint32_t maxpacket; /*!< Endpoint Max packet size This parameter must be a number between Min_Data = 0 and Max_Data = 64KB */ uint8_t *xfer_buff; /*!< Pointer to transfer buffer */ uint32_t xfer_len; /*!< Current transfer length */ uint32_t xfer_count; /*!< Partial transfer length in case of multi packet transfer */ }PCD_EPTypeDef; typedef USB_TypeDef PCD_TypeDef; /** * @brief PCD Handle Structure definition */ typedef struct { PCD_TypeDef *Instance; /*!< Register base address */ PCD_InitTypeDef Init; /*!< PCD required parameters */ __IO uint8_t USB_Address; /*!< USB Address */ PCD_EPTypeDef IN_ep[8]; /*!< IN endpoint parameters */ PCD_EPTypeDef OUT_ep[8]; /*!< OUT endpoint parameters */ HAL_LockTypeDef Lock; /*!< PCD peripheral status */ __IO PCD_StateTypeDef State; /*!< PCD communication state */ uint32_t Setup[12]; /*!< Setup packet buffer */ void *pData; /*!< Pointer to upper stack Handler */ } PCD_HandleTypeDef; /** * @} */ #include "stm32l1xx_hal_pcd_ex.h" /* Exported constants --------------------------------------------------------*/ /** @defgroup PCD_Exported_Constants PCD Exported Constants * @{ */ /** @defgroup USB_Exti_Line_Wakeup USB_Exti_Line_Wakeup * @{ */ #define USB_EXTI_LINE_WAKEUP ((uint32_t)0x00040000) /*!< External interrupt line 18 Connected to the USB FS EXTI Line */ /** * @} */ /** @defgroup USB_Core_Speed USB Core Speed * @{ */ #define PCD_SPEED_HIGH 0 /* Not Supported */ #define PCD_SPEED_FULL 2 /** * @} */ /** @defgroup USB_Core_PHY USB Core PHY * @{ */ #define PCD_PHY_EMBEDDED 2 /** * @} */ /** @defgroup USB_EP0_MPS USB EP0 MPS * @{ */ #define DEP0CTL_MPS_64 0 #define DEP0CTL_MPS_32 1 #define DEP0CTL_MPS_16 2 #define DEP0CTL_MPS_8 3 #define PCD_EP0MPS_64 DEP0CTL_MPS_64 #define PCD_EP0MPS_32 DEP0CTL_MPS_32 #define PCD_EP0MPS_16 DEP0CTL_MPS_16 #define PCD_EP0MPS_08 DEP0CTL_MPS_8 /** * @} */ /** @defgroup USB_EP_Type USB EP Type * @{ */ #define PCD_EP_TYPE_CTRL 0 #define PCD_EP_TYPE_ISOC 1 #define PCD_EP_TYPE_BULK 2 #define PCD_EP_TYPE_INTR 3 /** * @} */ /** @defgroup USB_ENDP_Type USB_ENDP_Type * @{ */ #define PCD_ENDP0 ((uint8_t)0) #define PCD_ENDP1 ((uint8_t)1) #define PCD_ENDP2 ((uint8_t)2) #define PCD_ENDP3 ((uint8_t)3) #define PCD_ENDP4 ((uint8_t)4) #define PCD_ENDP5 ((uint8_t)5) #define PCD_ENDP6 ((uint8_t)6) #define PCD_ENDP7 ((uint8_t)7) /* Endpoint Kind */ #define PCD_SNG_BUF 0 #define PCD_DBL_BUF 1 #define IS_PCD_ALL_INSTANCE IS_USB_ALL_INSTANCE /** * @} */ /** * @} */ /* Exported macros -----------------------------------------------------------*/ /** @defgroup PCD_Exported_Macros PCD Exported Macros * @brief macros to handle interrupts and specific clock configurations * @{ */ #define __HAL_PCD_GET_FLAG(__HANDLE__, __INTERRUPT__) ((((__HANDLE__)->Instance->ISTR) & (__INTERRUPT__)) == (__INTERRUPT__)) #define __HAL_PCD_CLEAR_FLAG(__HANDLE__, __INTERRUPT__) (((__HANDLE__)->Instance->ISTR) &= ~(__INTERRUPT__)) #define __HAL_USB_EXTI_ENABLE_IT() EXTI->IMR |= USB_EXTI_LINE_WAKEUP #define __HAL_USB_EXTI_DISABLE_IT() EXTI->IMR &= ~(USB_EXTI_LINE_WAKEUP) #define __HAL_USB_EXTI_GET_FLAG() EXTI->PR & (USB_EXTI_LINE_WAKEUP) #define __HAL_USB_EXTI_CLEAR_FLAG() EXTI->PR = USB_EXTI_LINE_WAKEUP #define __HAL_USB_EXTI_SET_RISING_EDGE_TRIGGER() EXTI->FTSR &= ~(USB_EXTI_LINE_WAKEUP);\ EXTI->RTSR |= USB_EXTI_LINE_WAKEUP #define __HAL_USB_EXTI_SET_FALLING_EDGE_TRIGGER() EXTI->FTSR |= (USB_EXTI_LINE_WAKEUP);\ EXTI->RTSR &= ~(USB_EXTI_LINE_WAKEUP) #define __HAL_USB_EXTI_SET_FALLINGRISING_TRIGGER() EXTI->RTSR &= ~(USB_EXTI_LINE_WAKEUP);\ EXTI->FTSR &= ~(USB_EXTI_LINE_WAKEUP);\ EXTI->RTSR |= USB_EXTI_LINE_WAKEUP;\ EXTI->FTSR |= USB_EXTI_LINE_WAKEUP /** * @} */ /* Internal macros -----------------------------------------------------------*/ /** @defgroup PCD_Private_Macros PCD Private Macros * @brief macros to handle interrupts and specific clock configurations * @{ */ /* SetENDPOINT */ #define PCD_SET_ENDPOINT(USBx, bEpNum,wRegValue) (*(&(USBx)->EP0R + (bEpNum) * 2)= (uint16_t)(wRegValue)) /* GetENDPOINT */ #define PCD_GET_ENDPOINT(USBx, bEpNum) (*(&(USBx)->EP0R + (bEpNum) * 2)) /** * @brief sets the type in the endpoint register(bits EP_TYPE[1:0]) * @param USBx: USB peripheral instance register address. * @param bEpNum: Endpoint Number. * @param wType: Endpoint Type. * @retval None */ #define PCD_SET_EPTYPE(USBx, bEpNum,wType) (PCD_SET_ENDPOINT((USBx), (bEpNum),\ ((PCD_GET_ENDPOINT((USBx), (bEpNum)) & USB_EP_T_MASK) | (wType) ))) /** * @brief gets the type in the endpoint register(bits EP_TYPE[1:0]) * @param USBx: USB peripheral instance register address. * @param bEpNum: Endpoint Number. * @retval Endpoint Type */ #define PCD_GET_EPTYPE(USBx, bEpNum) (PCD_GET_ENDPOINT((USBx), (bEpNum)) & USB_EP_T_FIELD) /** * @brief free buffer used from the application realizing it to the line toggles bit SW_BUF in the double buffered endpoint register * @param USBx: USB peripheral instance register address. * @param bEpNum: Endpoint Number. * @param bDir: Direction * @retval None */ #define PCD_FreeUserBuffer(USBx, bEpNum, bDir)\ {\ if ((bDir) == PCD_EP_DBUF_OUT)\ { /* OUT double buffered endpoint */\ PCD_TX_DTOG((USBx), (bEpNum));\ }\ else if ((bDir) == PCD_EP_DBUF_IN)\ { /* IN double buffered endpoint */\ PCD_RX_DTOG((USBx), (bEpNum));\ }\ } /** * @brief gets direction of the double buffered endpoint * @param USBx: USB peripheral instance register address. * @param bEpNum: Endpoint Number. * @retval EP_DBUF_OUT, EP_DBUF_IN, * EP_DBUF_ERR if the endpoint counter not yet programmed. */ #define PCD_GET_DB_DIR(USBx, bEpNum)\ {\ if ((uint16_t)(*PCD_EP_RX_CNT((USBx), (bEpNum)) & 0xFC00) != 0)\ return(PCD_EP_DBUF_OUT);\ else if (((uint16_t)(*PCD_EP_TX_CNT((USBx), (bEpNum))) & 0x03FF) != 0)\ return(PCD_EP_DBUF_IN);\ else\ return(PCD_EP_DBUF_ERR);\ } /** * @brief sets the status for tx transfer (bits STAT_TX[1:0]). * @param USBx: USB peripheral instance register address. * @param bEpNum: Endpoint Number. * @param wState: new state * @retval None */ #define PCD_SET_EP_TX_STATUS(USBx, bEpNum, wState) { register uint16_t _wRegVal;\ \ _wRegVal = PCD_GET_ENDPOINT((USBx), (bEpNum)) & USB_EPTX_DTOGMASK;\ /* toggle first bit ? */ \ if((USB_EPTX_DTOG1 & (wState))!= 0) \ { \ _wRegVal ^= USB_EPTX_DTOG1; \ } \ /* toggle second bit ? */ \ if((USB_EPTX_DTOG2 & (wState))!= 0) \ { \ _wRegVal ^= USB_EPTX_DTOG2; \ } \ PCD_SET_ENDPOINT((USBx), (bEpNum), (_wRegVal | USB_EP_CTR_RX|USB_EP_CTR_TX)); \ } /* PCD_SET_EP_TX_STATUS */ /** * @brief sets the status for rx transfer (bits STAT_TX[1:0]) * @param USBx: USB peripheral instance register address. * @param bEpNum: Endpoint Number. * @param wState: new state * @retval None */ #define PCD_SET_EP_RX_STATUS(USBx, bEpNum,wState) {\ register uint16_t _wRegVal; \ \ _wRegVal = PCD_GET_ENDPOINT((USBx), (bEpNum)) & USB_EPRX_DTOGMASK;\ /* toggle first bit ? */ \ if((USB_EPRX_DTOG1 & (wState))!= 0) \ { \ _wRegVal ^= USB_EPRX_DTOG1; \ } \ /* toggle second bit ? */ \ if((USB_EPRX_DTOG2 & (wState))!= 0) \ { \ _wRegVal ^= USB_EPRX_DTOG2; \ } \ PCD_SET_ENDPOINT((USBx), (bEpNum), (_wRegVal | USB_EP_CTR_RX|USB_EP_CTR_TX)); \ } /* PCD_SET_EP_RX_STATUS */ /** * @brief sets the status for rx & tx (bits STAT_TX[1:0] & STAT_RX[1:0]) * @param USBx: USB peripheral instance register address. * @param bEpNum: Endpoint Number. * @param wStaterx: new state. * @param wStatetx: new state. * @retval None */ #define PCD_SET_EP_TXRX_STATUS(USBx,bEpNum,wStaterx,wStatetx) {\ register uint32_t _wRegVal; \ \ _wRegVal = PCD_GET_ENDPOINT((USBx), (bEpNum)) & (USB_EPRX_DTOGMASK |USB_EPTX_STAT) ;\ /* toggle first bit ? */ \ if((USB_EPRX_DTOG1 & ((wStaterx)))!= 0) \ { \ _wRegVal ^= USB_EPRX_DTOG1; \ } \ /* toggle second bit ? */ \ if((USB_EPRX_DTOG2 & (wStaterx))!= 0) \ { \ _wRegVal ^= USB_EPRX_DTOG2; \ } \ /* toggle first bit ? */ \ if((USB_EPTX_DTOG1 & (wStatetx))!= 0) \ { \ _wRegVal ^= USB_EPTX_DTOG1; \ } \ /* toggle second bit ? */ \ if((USB_EPTX_DTOG2 & (wStatetx))!= 0) \ { \ _wRegVal ^= USB_EPTX_DTOG2; \ } \ PCD_SET_ENDPOINT((USBx), (bEpNum), _wRegVal | USB_EP_CTR_RX|USB_EP_CTR_TX); \ } /* PCD_SET_EP_TXRX_STATUS */ /** * @brief gets the status for tx/rx transfer (bits STAT_TX[1:0] * /STAT_RX[1:0]) * @param USBx: USB peripheral instance register address. * @param bEpNum: Endpoint Number. * @retval status */ #define PCD_GET_EP_TX_STATUS(USBx, bEpNum) ((uint16_t)PCD_GET_ENDPOINT((USBx), (bEpNum)) & USB_EPTX_STAT) #define PCD_GET_EP_RX_STATUS(USBx, bEpNum) ((uint16_t)PCD_GET_ENDPOINT((USBx), (bEpNum)) & USB_EPRX_STAT) /** * @brief sets directly the VALID tx/rx-status into the endpoint register * @param USBx: USB peripheral instance register address. * @param bEpNum: Endpoint Number. * @retval None */ #define PCD_SET_EP_TX_VALID(USBx, bEpNum) (PCD_SET_EP_TX_STATUS((USBx), (bEpNum), USB_EP_TX_VALID)) #define PCD_SET_EP_RX_VALID(USBx, bEpNum) (PCD_SET_EP_RX_STATUS((USBx), (bEpNum), USB_EP_RX_VALID)) /** * @brief checks stall condition in an endpoint. * @param USBx: USB peripheral instance register address. * @param bEpNum: Endpoint Number. * @retval TRUE = endpoint in stall condition. */ #define PCD_GET_EP_TX_STALL_STATUS(USBx, bEpNum) (PCD_GET_EP_TX_STATUS((USBx), (bEpNum)) \ == USB_EP_TX_STALL) #define PCD_GET_EP_RX_STALL_STATUS(USBx, bEpNum) (PCD_GET_EP_RX_STATUS((USBx), (bEpNum)) \ == USB_EP_RX_STALL) /** * @brief set & clear EP_KIND bit. * @param USBx: USB peripheral instance register address. * @param bEpNum: Endpoint Number. * @retval None */ #define PCD_SET_EP_KIND(USBx, bEpNum) (PCD_SET_ENDPOINT((USBx), (bEpNum), \ (USB_EP_CTR_RX|USB_EP_CTR_TX|((PCD_GET_ENDPOINT((USBx), (bEpNum)) | USB_EP_KIND) & USB_EPREG_MASK)))) #define PCD_CLEAR_EP_KIND(USBx, bEpNum) (PCD_SET_ENDPOINT((USBx), (bEpNum), \ (USB_EP_CTR_RX|USB_EP_CTR_TX|(PCD_GET_ENDPOINT((USBx), (bEpNum)) & USB_EPKIND_MASK)))) /** * @brief Sets/clears directly STATUS_OUT bit in the endpoint register. * @param USBx: USB peripheral instance register address. * @param bEpNum: Endpoint Number. * @retval None */ #define PCD_SET_OUT_STATUS(USBx, bEpNum) PCD_SET_EP_KIND((USBx), (bEpNum)) #define PCD_CLEAR_OUT_STATUS(USBx, bEpNum) PCD_CLEAR_EP_KIND((USBx), (bEpNum)) /** * @brief Sets/clears directly EP_KIND bit in the endpoint register. * @param USBx: USB peripheral instance register address. * @param bEpNum: Endpoint Number. * @retval None */ #define PCD_SET_EP_DBUF(USBx, bEpNum) PCD_SET_EP_KIND((USBx), (bEpNum)) #define PCD_CLEAR_EP_DBUF(USBx, bEpNum) PCD_CLEAR_EP_KIND((USBx), (bEpNum)) /** * @brief Clears bit CTR_RX / CTR_TX in the endpoint register. * @param USBx: USB peripheral instance register address. * @param bEpNum: Endpoint Number. * @retval None */ #define PCD_CLEAR_RX_EP_CTR(USBx, bEpNum) (PCD_SET_ENDPOINT((USBx), (bEpNum),\ PCD_GET_ENDPOINT((USBx), (bEpNum)) & 0x7FFF & USB_EPREG_MASK)) #define PCD_CLEAR_TX_EP_CTR(USBx, bEpNum) (PCD_SET_ENDPOINT((USBx), (bEpNum),\ PCD_GET_ENDPOINT((USBx), (bEpNum)) & 0xFF7F & USB_EPREG_MASK)) /** * @brief Toggles DTOG_RX / DTOG_TX bit in the endpoint register. * @param USBx: USB peripheral instance register address. * @param bEpNum: Endpoint Number. * @retval None */ #define PCD_RX_DTOG(USBx, bEpNum) (PCD_SET_ENDPOINT((USBx), (bEpNum), \ USB_EP_CTR_RX|USB_EP_CTR_TX|USB_EP_DTOG_RX | (PCD_GET_ENDPOINT((USBx), (bEpNum)) & USB_EPREG_MASK))) #define PCD_TX_DTOG(USBx, bEpNum) (PCD_SET_ENDPOINT((USBx), (bEpNum), \ USB_EP_CTR_RX|USB_EP_CTR_TX|USB_EP_DTOG_TX | (PCD_GET_ENDPOINT((USBx), (bEpNum)) & USB_EPREG_MASK))) /** * @brief Clears DTOG_RX / DTOG_TX bit in the endpoint register. * @param USBx: USB peripheral instance register address. * @param bEpNum: Endpoint Number. * @retval None */ #define PCD_CLEAR_RX_DTOG(USBx, bEpNum) if((PCD_GET_ENDPOINT((USBx), (bEpNum)) & USB_EP_DTOG_RX) != 0)\ { \ PCD_RX_DTOG((USBx), (bEpNum)); \ } #define PCD_CLEAR_TX_DTOG(USBx, bEpNum) if((PCD_GET_ENDPOINT((USBx), (bEpNum)) & USB_EP_DTOG_TX) != 0)\ { \ PCD_TX_DTOG((USBx), (bEpNum)); \ } /** * @brief Sets address in an endpoint register. * @param USBx: USB peripheral instance register address. * @param bEpNum: Endpoint Number. * @param bAddr: Address. * @retval None */ #define PCD_SET_EP_ADDRESS(USBx, bEpNum,bAddr) PCD_SET_ENDPOINT((USBx), (bEpNum),\ USB_EP_CTR_RX|USB_EP_CTR_TX|(PCD_GET_ENDPOINT((USBx), (bEpNum)) & USB_EPREG_MASK) | (bAddr)) #define PCD_GET_EP_ADDRESS(USBx, bEpNum) ((uint8_t)(PCD_GET_ENDPOINT((USBx), (bEpNum)) & USB_EPADDR_FIELD)) #define PCD_EP_TX_ADDRESS(USBx, bEpNum) ((uint32_t *)(((USBx)->BTABLE+(bEpNum)*8)*2+ ((uint32_t)(USBx) + 0x400))) #define PCD_EP_TX_CNT(USBx, bEpNum) ((uint32_t *)(((USBx)->BTABLE+(bEpNum)*8+2)*2+ ((uint32_t)(USBx) + 0x400))) #define PCD_EP_RX_ADDRESS(USBx, bEpNum) ((uint32_t *)(((USBx)->BTABLE+(bEpNum)*8+4)*2+ ((uint32_t)(USBx) + 0x400))) #define PCD_EP_RX_CNT(USBx, bEpNum) ((uint32_t *)(((USBx)->BTABLE+(bEpNum)*8+6)*2+ ((uint32_t)(USBx) + 0x400))) #define PCD_SET_EP_RX_CNT(USBx, bEpNum,wCount) {\ uint32_t *pdwReg = PCD_EP_RX_CNT((USBx), (bEpNum)); \ PCD_SET_EP_CNT_RX_REG(pdwReg, (wCount));\ } /** * @brief sets address of the tx/rx buffer. * @param USBx: USB peripheral instance register address. * @param bEpNum: Endpoint Number. * @param wAddr: address to be set (must be word aligned). * @retval None */ #define PCD_SET_EP_TX_ADDRESS(USBx, bEpNum,wAddr) (*PCD_EP_TX_ADDRESS((USBx), (bEpNum)) = (((wAddr) >> 1) << 1)) #define PCD_SET_EP_RX_ADDRESS(USBx, bEpNum,wAddr) (*PCD_EP_RX_ADDRESS((USBx), (bEpNum)) = (((wAddr) >> 1) << 1)) /** * @brief Gets address of the tx/rx buffer. * @param USBx: USB peripheral instance register address. * @param bEpNum: Endpoint Number. * @retval address of the buffer. */ #define PCD_GET_EP_TX_ADDRESS(USBx, bEpNum) ((uint16_t)*PCD_EP_TX_ADDRESS((USBx), (bEpNum))) #define PCD_GET_EP_RX_ADDRESS(USBx, bEpNum) ((uint16_t)*PCD_EP_RX_ADDRESS((USBx), (bEpNum))) /** * @brief Sets counter of rx buffer with no. of blocks. * @param dwReg: Register * @param wCount: Counter. * @param wNBlocks: no. of Blocks. * @retval None */ #define PCD_CALC_BLK32(dwReg,wCount,wNBlocks) {\ (wNBlocks) = (wCount) >> 5;\ if(((wCount) & 0x1f) == 0)\ { \ (wNBlocks)--;\ } \ *pdwReg = (uint16_t)((uint16_t)((wNBlocks) << 10) | 0x8000); \ }/* PCD_CALC_BLK32 */ #define PCD_CALC_BLK2(dwReg,wCount,wNBlocks) {\ (wNBlocks) = (wCount) >> 1;\ if(((wCount) & 0x1) != 0)\ { \ (wNBlocks)++;\ } \ *pdwReg = (uint16_t)((wNBlocks) << 10);\ }/* PCD_CALC_BLK2 */ #define PCD_SET_EP_CNT_RX_REG(dwReg,wCount) {\ uint16_t wNBlocks;\ if((wCount) > 62) \ { \ PCD_CALC_BLK32((dwReg),(wCount),wNBlocks); \ } \ else \ { \ PCD_CALC_BLK2((dwReg),(wCount),wNBlocks); \ } \ }/* PCD_SET_EP_CNT_RX_REG */ #define PCD_SET_EP_RX_DBUF0_CNT(USBx, bEpNum,wCount) {\ uint16_t *pdwReg = PCD_EP_TX_CNT((USBx), (bEpNum)); \ PCD_SET_EP_CNT_RX_REG(pdwReg, (wCount));\ } /** * @brief sets counter for the tx/rx buffer. * @param USBx: USB peripheral instance register address. * @param bEpNum: Endpoint Number. * @param wCount: Counter value. * @retval None */ #define PCD_SET_EP_TX_CNT(USBx, bEpNum,wCount) (*PCD_EP_TX_CNT((USBx), (bEpNum)) = (wCount)) /** * @brief gets counter of the tx buffer. * @param USBx: USB peripheral instance register address. * @param bEpNum: Endpoint Number. * @retval Counter value */ #define PCD_GET_EP_TX_CNT(USBx, bEpNum)((uint16_t)(*PCD_EP_TX_CNT((USBx), (bEpNum))) & 0x3ff) #define PCD_GET_EP_RX_CNT(USBx, bEpNum)((uint16_t)(*PCD_EP_RX_CNT((USBx), (bEpNum))) & 0x3ff) /** * @brief Sets buffer 0/1 address in a double buffer endpoint. * @param USBx: USB peripheral instance register address. * @param bEpNum: Endpoint Number. * @param wBuf0Addr: buffer 0 address. * @retval Counter value */ #define PCD_SET_EP_DBUF0_ADDR(USBx, bEpNum,wBuf0Addr) {PCD_SET_EP_TX_ADDRESS((USBx), (bEpNum), (wBuf0Addr));} #define PCD_SET_EP_DBUF1_ADDR(USBx, bEpNum,wBuf1Addr) {PCD_SET_EP_RX_ADDRESS((USBx), (bEpNum), (wBuf1Addr));} /** * @brief Sets addresses in a double buffer endpoint. * @param USBx: USB peripheral instance register address. * @param bEpNum: Endpoint Number. * @param wBuf0Addr: buffer 0 address. * @param wBuf1Addr = buffer 1 address. * @retval None */ #define PCD_SET_EP_DBUF_ADDR(USBx, bEpNum,wBuf0Addr,wBuf1Addr) { \ PCD_SET_EP_DBUF0_ADDR((USBx), (bEpNum), (wBuf0Addr));\ PCD_SET_EP_DBUF1_ADDR((USBx), (bEpNum), (wBuf1Addr));\ } /* PCD_SET_EP_DBUF_ADDR */ /** * @brief Gets buffer 0/1 address of a double buffer endpoint. * @param USBx: USB peripheral instance register address. * @param bEpNum: Endpoint Number. * @retval None */ #define PCD_GET_EP_DBUF0_ADDR(USBx, bEpNum) (PCD_GET_EP_TX_ADDRESS((USBx), (bEpNum))) #define PCD_GET_EP_DBUF1_ADDR(USBx, bEpNum) (PCD_GET_EP_RX_ADDRESS((USBx), (bEpNum))) /** * @brief Gets buffer 0/1 address of a double buffer endpoint. * @param USBx: USB peripheral instance register address. * @param bEpNum: Endpoint Number. * @param bDir: endpoint dir EP_DBUF_OUT = OUT * EP_DBUF_IN = IN * @param wCount: Counter value * @retval None */ #define PCD_SET_EP_DBUF0_CNT(USBx, bEpNum, bDir, wCount) { \ if((bDir) == PCD_EP_DBUF_OUT)\ /* OUT endpoint */ \ {PCD_SET_EP_RX_DBUF0_CNT((USBx), (bEpNum),(wCount));} \ else if((bDir) == PCD_EP_DBUF_IN)\ /* IN endpoint */ \ *PCD_EP_TX_CNT((USBx), (bEpNum)) = (uint32_t)(wCount); \ } /* SetEPDblBuf0Count*/ #define PCD_SET_EP_DBUF1_CNT(USBx, bEpNum, bDir, wCount) { \ if((bDir) == PCD_EP_DBUF_OUT)\ {/* OUT endpoint */ \ PCD_SET_EP_RX_CNT((USBx), (bEpNum),(wCount)); \ } \ else if((bDir) == PCD_EP_DBUF_IN)\ {/* IN endpoint */ \ *PCD_EP_RX_CNT((USBx), (bEpNum)) = (uint32_t)(wCount); \ } \ } /* SetEPDblBuf1Count */ #define PCD_SET_EP_DBUF_CNT(USBx, bEpNum, bDir, wCount) {\ PCD_SET_EP_DBUF0_CNT((USBx), (bEpNum), (bDir), (wCount)); \ PCD_SET_EP_DBUF1_CNT((USBx), (bEpNum), (bDir), (wCount)); \ } /* PCD_SET_EP_DBUF_CNT */ /** * @brief Gets buffer 0/1 rx/tx counter for double buffering. * @param USBx: USB peripheral instance register address. * @param bEpNum: Endpoint Number. * @retval None */ #define PCD_GET_EP_DBUF0_CNT(USBx, bEpNum) (PCD_GET_EP_TX_CNT((USBx), (bEpNum))) #define PCD_GET_EP_DBUF1_CNT(USBx, bEpNum) (PCD_GET_EP_RX_CNT((USBx), (bEpNum))) /** * @} */ /* Exported functions --------------------------------------------------------*/ /** @addtogroup PCD_Exported_Functions * @{ */ /* Initialization/de-initialization functions **********************************/ /** @addtogroup PCD_Exported_Functions_Group1 * @{ */ HAL_StatusTypeDef HAL_PCD_Init(PCD_HandleTypeDef *hpcd); HAL_StatusTypeDef HAL_PCD_DeInit (PCD_HandleTypeDef *hpcd); void HAL_PCD_MspInit(PCD_HandleTypeDef *hpcd); void HAL_PCD_MspDeInit(PCD_HandleTypeDef *hpcd); /** * @} */ /* I/O operation functions *****************************************************/ /* Non-Blocking mode: Interrupt */ /** @addtogroup PCD_Exported_Functions_Group2 * @{ */ HAL_StatusTypeDef HAL_PCD_Start(PCD_HandleTypeDef *hpcd); HAL_StatusTypeDef HAL_PCD_Stop(PCD_HandleTypeDef *hpcd); void HAL_PCD_IRQHandler(PCD_HandleTypeDef *hpcd); void HAL_PCD_DataOutStageCallback(PCD_HandleTypeDef *hpcd, uint8_t epnum); void HAL_PCD_DataInStageCallback(PCD_HandleTypeDef *hpcd, uint8_t epnum); void HAL_PCD_SetupStageCallback(PCD_HandleTypeDef *hpcd); void HAL_PCD_SOFCallback(PCD_HandleTypeDef *hpcd); void HAL_PCD_ResetCallback(PCD_HandleTypeDef *hpcd); void HAL_PCD_SuspendCallback(PCD_HandleTypeDef *hpcd); void HAL_PCD_ResumeCallback(PCD_HandleTypeDef *hpcd); void HAL_PCD_ISOOUTIncompleteCallback(PCD_HandleTypeDef *hpcd, uint8_t epnum); void HAL_PCD_ISOINIncompleteCallback(PCD_HandleTypeDef *hpcd, uint8_t epnum); void HAL_PCD_ConnectCallback(PCD_HandleTypeDef *hpcd); void HAL_PCD_DisconnectCallback(PCD_HandleTypeDef *hpcd); /** * @} */ /* Peripheral Control functions ************************************************/ /** @addtogroup PCD_Exported_Functions_Group3 * @{ */ HAL_StatusTypeDef HAL_PCD_DevConnect(PCD_HandleTypeDef *hpcd); HAL_StatusTypeDef HAL_PCD_DevDisconnect(PCD_HandleTypeDef *hpcd); HAL_StatusTypeDef HAL_PCD_SetAddress(PCD_HandleTypeDef *hpcd, uint8_t address); HAL_StatusTypeDef HAL_PCD_EP_Open(PCD_HandleTypeDef *hpcd, uint8_t ep_addr, uint16_t ep_mps, uint8_t ep_type); HAL_StatusTypeDef HAL_PCD_EP_Close(PCD_HandleTypeDef *hpcd, uint8_t ep_addr); HAL_StatusTypeDef HAL_PCD_EP_Receive(PCD_HandleTypeDef *hpcd, uint8_t ep_addr, uint8_t *pBuf, uint32_t len); HAL_StatusTypeDef HAL_PCD_EP_Transmit(PCD_HandleTypeDef *hpcd, uint8_t ep_addr, uint8_t *pBuf, uint32_t len); uint16_t HAL_PCD_EP_GetRxCount(PCD_HandleTypeDef *hpcd, uint8_t ep_addr); HAL_StatusTypeDef HAL_PCD_EP_SetStall(PCD_HandleTypeDef *hpcd, uint8_t ep_addr); HAL_StatusTypeDef HAL_PCD_EP_ClrStall(PCD_HandleTypeDef *hpcd, uint8_t ep_addr); HAL_StatusTypeDef HAL_PCD_EP_Flush(PCD_HandleTypeDef *hpcd, uint8_t ep_addr); HAL_StatusTypeDef HAL_PCD_ActiveRemoteWakeup(PCD_HandleTypeDef *hpcd); HAL_StatusTypeDef HAL_PCD_DeActiveRemoteWakeup(PCD_HandleTypeDef *hpcd); /** * @} */ /* Peripheral State functions **************************************************/ /** @addtogroup PCD_Exported_Functions_Group4 * @{ */ PCD_StateTypeDef HAL_PCD_GetState(PCD_HandleTypeDef *hpcd); void HAL_PCDEx_SetConnectionState(PCD_HandleTypeDef *hpcd, uint8_t state); /** * @} */ /** * @} */ /** * @} */ /** * @} */ #ifdef __cplusplus } #endif #endif /* __STM32L1xx_HAL_PCD_H */ /************************ (C) COPYRIGHT STMicroelectronics *****END OF FILE****/ ================================================ FILE: Zelig/mbed/TARGET_NUCLEO_L152RE/stm32l1xx_hal_pcd_ex.h ================================================ /** ****************************************************************************** * @file stm32l1xx_hal_pcd.h * @author MCD Application Team * @version V1.0.0 * @date 5-September-2014 * @brief Header file of PCD HAL module. ****************************************************************************** * @attention * *

© COPYRIGHT(c) 2014 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. * ****************************************************************************** */ /* Define to prevent recursive inclusion -------------------------------------*/ #ifndef __STM32L1xx_HAL_PCD_EX_H #define __STM32L1xx_HAL_PCD_EX_H #ifdef __cplusplus extern "C" { #endif /* Includes ------------------------------------------------------------------*/ #include "stm32l1xx_hal_def.h" /** @addtogroup STM32L1xx_HAL_Driver * @{ */ /** @addtogroup PCDEx * @{ */ /* Exported types ------------------------------------------------------------*/ /* Exported constants --------------------------------------------------------*/ /* Exported macros -----------------------------------------------------------*/ /* Internal macros -----------------------------------------------------------*/ /* Exported functions --------------------------------------------------------*/ /** @addtogroup PCDEx_Exported_Functions * @{ */ HAL_StatusTypeDef HAL_PCDEx_PMAConfig(PCD_HandleTypeDef *hpcd, uint16_t ep_addr, uint16_t ep_kind, uint32_t pmaadress); /** * @} */ /** * @} */ /** * @} */ #ifdef __cplusplus } #endif #endif /* __STM32L1xx_HAL_PCD_EX_H */ /************************ (C) COPYRIGHT STMicroelectronics *****END OF FILE****/ ================================================ FILE: Zelig/mbed/TARGET_NUCLEO_L152RE/stm32l1xx_hal_pwr.h ================================================ /** ****************************************************************************** * @file stm32l1xx_hal_pwr.h * @author MCD Application Team * @version V1.0.0 * @date 5-September-2014 * @brief Header file of PWR HAL module. ****************************************************************************** * @attention * *

© COPYRIGHT(c) 2014 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. * ****************************************************************************** */ /* Define to prevent recursive inclusion -------------------------------------*/ #ifndef __STM32L1xx_HAL_PWR_H #define __STM32L1xx_HAL_PWR_H #ifdef __cplusplus extern "C" { #endif /* Includes ------------------------------------------------------------------*/ #include "stm32l1xx_hal_def.h" /** @addtogroup STM32L1xx_HAL_Driver * @{ */ /** @addtogroup PWR * @{ */ /* Exported types ------------------------------------------------------------*/ /** @defgroup PWR_Exported_Types PWR Exported Types * @{ */ /** * @brief PWR PVD configuration structure definition */ typedef struct { uint32_t PVDLevel; /*!< PVDLevel: Specifies the PVD detection level. This parameter can be a value of @ref PWR_PVD_detection_level */ uint32_t Mode; /*!< Mode: Specifies the operating mode for the selected pins. This parameter can be a value of @ref PWR_PVD_Mode */ }PWR_PVDTypeDef; /** * @} */ /* Exported constants --------------------------------------------------------*/ /** @defgroup PWR_Exported_Constants PWR Exported Constants * @{ */ /** @defgroup PWR_register_alias_address PWR Register alias address * @{ */ /* ------------- PWR registers bit address in the alias region ---------------*/ #define PWR_OFFSET (PWR_BASE - PERIPH_BASE) #define PWR_CR_OFFSET 0x00 #define PWR_CSR_OFFSET 0x04 #define PWR_CR_OFFSET_BB (PWR_OFFSET + PWR_CR_OFFSET) #define PWR_CSR_OFFSET_BB (PWR_OFFSET + PWR_CSR_OFFSET) /** * @} */ /** @defgroup PWR_CR_register_alias PWR CR Register alias address * @{ */ /* --- CR Register ---*/ /* Alias word address of LPSDSR bit */ #define LPSDSR_BIT_NUMBER POSITION_VAL(PWR_CR_LPSDSR) #define CR_LPSDSR_BB ((uint32_t)(PERIPH_BB_BASE + (PWR_CR_OFFSET_BB * 32) + (LPSDSR_BIT_NUMBER * 4))) /* Alias word address of DBP bit */ #define DBP_BIT_NUMBER POSITION_VAL(PWR_CR_DBP) #define CR_DBP_BB ((uint32_t)(PERIPH_BB_BASE + (PWR_CR_OFFSET_BB * 32) + (DBP_BIT_NUMBER * 4))) /* Alias word address of LPRUN bit */ #define LPRUN_BIT_NUMBER POSITION_VAL(PWR_CR_LPRUN) #define CR_LPRUN_BB ((uint32_t)(PERIPH_BB_BASE + (PWR_CR_OFFSET_BB * 32) + (LPRUN_BIT_NUMBER * 4))) /* Alias word address of PVDE bit */ #define PVDE_BIT_NUMBER POSITION_VAL(PWR_CR_PVDE) #define CR_PVDE_BB ((uint32_t)(PERIPH_BB_BASE + (PWR_CR_OFFSET_BB * 32) + (PVDE_BIT_NUMBER * 4))) /* Alias word address of FWU bit */ #define FWU_BIT_NUMBER POSITION_VAL(PWR_CR_FWU) #define CR_FWU_BB ((uint32_t)(PERIPH_BB_BASE + (PWR_CR_OFFSET_BB * 32) + (FWU_BIT_NUMBER * 4))) /* Alias word address of ULP bit */ #define ULP_BIT_NUMBER POSITION_VAL(PWR_CR_ULP) #define CR_ULP_BB ((uint32_t)(PERIPH_BB_BASE + (PWR_CR_OFFSET_BB * 32) + (ULP_BIT_NUMBER * 4))) /** * @} */ /** @defgroup PWR_CSR_register_alias PWR CSR Register alias address * @{ */ /* --- CSR Register ---*/ /* Alias word address of EWUP1, EWUP2 and EWUP3 bits */ #define CSR_EWUP_BB(VAL) ((uint32_t)(PERIPH_BB_BASE + (PWR_CSR_OFFSET_BB * 32) + (POSITION_VAL(VAL) * 4))) /** * @} */ /** @defgroup PWR_PVD_detection_level PWR PVD detection level * @{ */ #define PWR_PVDLEVEL_0 PWR_CR_PLS_LEV0 #define PWR_PVDLEVEL_1 PWR_CR_PLS_LEV1 #define PWR_PVDLEVEL_2 PWR_CR_PLS_LEV2 #define PWR_PVDLEVEL_3 PWR_CR_PLS_LEV3 #define PWR_PVDLEVEL_4 PWR_CR_PLS_LEV4 #define PWR_PVDLEVEL_5 PWR_CR_PLS_LEV5 #define PWR_PVDLEVEL_6 PWR_CR_PLS_LEV6 #define PWR_PVDLEVEL_7 PWR_CR_PLS_LEV7 /* External input analog voltage (Compare internally to VREFINT) */ #define IS_PWR_PVD_LEVEL(LEVEL) (((LEVEL) == PWR_PVDLEVEL_0) || ((LEVEL) == PWR_PVDLEVEL_1)|| \ ((LEVEL) == PWR_PVDLEVEL_2) || ((LEVEL) == PWR_PVDLEVEL_3)|| \ ((LEVEL) == PWR_PVDLEVEL_4) || ((LEVEL) == PWR_PVDLEVEL_5)|| \ ((LEVEL) == PWR_PVDLEVEL_6) || ((LEVEL) == PWR_PVDLEVEL_7)) /** * @} */ /** @defgroup PWR_PVD_Mode PWR PVD Mode * @{ */ #define PWR_PVD_MODE_NORMAL ((uint32_t)0x00000000) /*!< basic mode is used */ #define PWR_PVD_MODE_IT_RISING ((uint32_t)0x00010001) /*!< External Interrupt Mode with Rising edge trigger detection */ #define PWR_PVD_MODE_IT_FALLING ((uint32_t)0x00010002) /*!< External Interrupt Mode with Falling edge trigger detection */ #define PWR_PVD_MODE_IT_RISING_FALLING ((uint32_t)0x00010003) /*!< External Interrupt Mode with Rising/Falling edge trigger detection */ #define PWR_PVD_MODE_EVENT_RISING ((uint32_t)0x00020001) /*!< Event Mode with Rising edge trigger detection */ #define PWR_PVD_MODE_EVENT_FALLING ((uint32_t)0x00020002) /*!< Event Mode with Falling edge trigger detection */ #define PWR_PVD_MODE_EVENT_RISING_FALLING ((uint32_t)0x00020003) /*!< Event Mode with Rising/Falling edge trigger detection */ #define IS_PWR_PVD_MODE(MODE) (((MODE) == PWR_PVD_MODE_IT_RISING)|| ((MODE) == PWR_PVD_MODE_IT_FALLING) || \ ((MODE) == PWR_PVD_MODE_IT_RISING_FALLING) || ((MODE) == PWR_PVD_MODE_EVENT_RISING) || \ ((MODE) == PWR_PVD_MODE_EVENT_FALLING) || ((MODE) == PWR_PVD_MODE_EVENT_RISING_FALLING) || \ ((MODE) == PWR_PVD_MODE_NORMAL)) /** * @} */ /** @defgroup PWR_Regulator_state_in_SLEEP_STOP_mode PWR Regulator state in SLEEP/STOP mode * @{ */ #define PWR_MAINREGULATOR_ON ((uint32_t)0x00000000) #define PWR_LOWPOWERREGULATOR_ON PWR_CR_LPSDSR #define IS_PWR_REGULATOR(REGULATOR) (((REGULATOR) == PWR_MAINREGULATOR_ON) || \ ((REGULATOR) == PWR_LOWPOWERREGULATOR_ON)) /** * @} */ /** @defgroup PWR_SLEEP_mode_entry PWR SLEEP mode entry * @{ */ #define PWR_SLEEPENTRY_WFI ((uint8_t)0x01) #define PWR_SLEEPENTRY_WFE ((uint8_t)0x02) #define IS_PWR_SLEEP_ENTRY(ENTRY) (((ENTRY) == PWR_SLEEPENTRY_WFI) || ((ENTRY) == PWR_SLEEPENTRY_WFE)) /** * @} */ /** @defgroup PWR_STOP_mode_entry PWR STOP mode entry * @{ */ #define PWR_STOPENTRY_WFI ((uint8_t)0x01) #define PWR_STOPENTRY_WFE ((uint8_t)0x02) #define IS_PWR_STOP_ENTRY(ENTRY) (((ENTRY) == PWR_STOPENTRY_WFI) || ((ENTRY) == PWR_STOPENTRY_WFE) ) /** * @} */ /** @defgroup PWR_Regulator_Voltage_Scale PWR Regulator Voltage Scale * @{ */ #define PWR_REGULATOR_VOLTAGE_SCALE1 PWR_CR_VOS_0 #define PWR_REGULATOR_VOLTAGE_SCALE2 PWR_CR_VOS_1 #define PWR_REGULATOR_VOLTAGE_SCALE3 PWR_CR_VOS #define IS_PWR_VOLTAGE_SCALING_RANGE(RANGE) (((RANGE) == PWR_REGULATOR_VOLTAGE_SCALE1) || \ ((RANGE) == PWR_REGULATOR_VOLTAGE_SCALE2) || \ ((RANGE) == PWR_REGULATOR_VOLTAGE_SCALE3)) /** * @} */ /** @defgroup PWR_Flag PWR Flag * @{ */ #define PWR_FLAG_WU PWR_CSR_WUF #define PWR_FLAG_SB PWR_CSR_SBF #define PWR_FLAG_PVDO PWR_CSR_PVDO #define PWR_FLAG_VREFINTRDY PWR_CSR_VREFINTRDYF #define PWR_FLAG_VOS PWR_CSR_VOSF #define PWR_FLAG_REGLP PWR_CSR_REGLPF /** * @} */ /** * @} */ /* Exported macro ------------------------------------------------------------*/ /** @defgroup PWR_Exported_Macro PWR Exported Macro * @{ */ /** @brief macros configure the main internal regulator output voltage. * @param __REGULATOR__: specifies the regulator output voltage to achieve * a tradeoff between performance and power consumption when the device does * not operate at the maximum frequency (refer to the datasheets for more details). * This parameter can be one of the following values: * @arg PWR_REGULATOR_VOLTAGE_SCALE1: Regulator voltage output Scale 1 mode, * System frequency up to 32 MHz. * @arg PWR_REGULATOR_VOLTAGE_SCALE2: Regulator voltage output Scale 2 mode, * System frequency up to 16 MHz. * @arg PWR_REGULATOR_VOLTAGE_SCALE3: Regulator voltage output Scale 3 mode, * System frequency up to 4.2 MHz * @retval None */ #define __HAL_PWR_VOLTAGESCALING_CONFIG(__REGULATOR__) (MODIFY_REG(PWR->CR, PWR_CR_VOS, (__REGULATOR__))) /** @brief Check PWR flag is set or not. * @param __FLAG__: specifies the flag to check. * This parameter can be one of the following values: * @arg PWR_FLAG_WU: Wake Up flag. This flag indicates that a wakeup event * was received from the WKUP pin or from the RTC alarm (Alarm B), * RTC Tamper event, RTC TimeStamp event or RTC Wakeup. * An additional wakeup event is detected if the WKUP pin is enabled * (by setting the EWUP bit) when the WKUP pin level is already high. * @arg PWR_FLAG_SB: StandBy flag. This flag indicates that the system was * resumed from StandBy mode. * @arg PWR_FLAG_PVDO: PVD Output. This flag is valid only if PVD is enabled * by the HAL_PWR_EnablePVD() function. The PVD is stopped by Standby mode * For this reason, this bit is equal to 0 after Standby or reset * until the PVDE bit is set. * @arg PWR_FLAG_VREFINTRDY: Internal voltage reference (VREFINT) ready flag. * This bit indicates the state of the internal voltage reference, VREFINT. * @arg PWR_FLAG_VOS: Voltage Scaling select flag. A delay is required for * the internal regulator to be ready after the voltage range is changed. * The VOSF bit indicates that the regulator has reached the voltage level * defined with bits VOS of PWR_CR register. * @arg PWR_FLAG_REGLP: Regulator LP flag. When the MCU exits from Low power run * mode, this bit stays at 1 until the regulator is ready in main mode. * A polling on this bit is recommended to wait for the regulator main mode. * This bit is reset by hardware when the regulator is ready. * @retval The new state of __FLAG__ (TRUE or FALSE). */ #define __HAL_PWR_GET_FLAG(__FLAG__) ((PWR->CSR & (__FLAG__)) == (__FLAG__)) /** @brief Clear the PWR's pending flags. * @param __FLAG__: specifies the flag to clear. * This parameter can be one of the following values: * @arg PWR_FLAG_WU: Wake Up flag * @arg PWR_FLAG_SB: StandBy flag */ #define __HAL_PWR_CLEAR_FLAG(__FLAG__) (PWR->CR |= (__FLAG__) << 2) #define PWR_EXTI_LINE_PVD ((uint32_t)0x00010000) /*!< External interrupt line 16 Connected to the PVD EXTI Line */ /** * @brief Enable interrupt on PVD Exti Line 16. * @retval None. */ #define __HAL_PWR_PVD_EXTI_ENABLE_IT() (EXTI->IMR |= (PWR_EXTI_LINE_PVD)) /** * @brief Disable interrupt on PVD Exti Line 16. * @retval None. */ #define __HAL_PWR_PVD_EXTI_DISABLE_IT() (EXTI->IMR &= ~(PWR_EXTI_LINE_PVD)) /** * @brief Enable event on PVD Exti Line 16. * @retval None. */ #define __HAL_PWR_PVD_EXTI_ENABLE_EVENT() (EXTI->EMR |= (PWR_EXTI_LINE_PVD)) /** * @brief Disable event on PVD Exti Line 16. * @retval None. */ #define __HAL_PWR_PVD_EXTI_DISABLE_EVENT() (EXTI->EMR &= ~(PWR_EXTI_LINE_PVD)) /** * @brief PVD EXTI line configuration: clear falling edge trigger and set rising edge. * @retval None. */ #define __HAL_PWR_PVD_EXTI_CLEAR_EGDE_TRIGGER() EXTI->FTSR &= ~(PWR_EXTI_LINE_PVD); \ EXTI->RTSR &= ~(PWR_EXTI_LINE_PVD) /** * @brief PVD EXTI line configuration: set falling edge trigger. * @retval None. */ #define __HAL_PWR_PVD_EXTI_SET_FALLING_EGDE_TRIGGER() EXTI->FTSR |= (PWR_EXTI_LINE_PVD) /** * @brief PVD EXTI line configuration: set rising edge trigger. * @retval None. */ #define __HAL_PWR_PVD_EXTI_SET_RISING_EDGE_TRIGGER() EXTI->RTSR |= (PWR_EXTI_LINE_PVD) /** * @brief Check whether the specified PVD EXTI interrupt flag is set or not. * @retval EXTI PVD Line Status. */ #define __HAL_PWR_PVD_EXTI_GET_FLAG() (EXTI->PR & (PWR_EXTI_LINE_PVD)) /** * @brief Clear the PVD EXTI flag. * @retval None. */ #define __HAL_PWR_PVD_EXTI_CLEAR_FLAG() (EXTI->PR = (PWR_EXTI_LINE_PVD)) /** * @brief Generate a Software interrupt on selected EXTI line. * @retval None. */ #define __HAL_PWR_PVD_EXTI_GENERATE_SWIT() (EXTI->SWIER |= (PWR_EXTI_LINE_PVD)) /** * @} */ /* Include PWR HAL Extension module */ #include "stm32l1xx_hal_pwr_ex.h" /* Exported functions --------------------------------------------------------*/ /** @addtogroup PWR_Exported_Functions PWR Exported Functions * @{ */ /** @addtogroup PWR_Exported_Functions_Group1 Initialization and de-initialization functions * @{ */ /* Initialization and de-initialization functions *******************************/ void HAL_PWR_DeInit(void); void HAL_PWR_EnableBkUpAccess(void); void HAL_PWR_DisableBkUpAccess(void); /** * @} */ /** @addtogroup PWR_Exported_Functions_Group2 Peripheral Control functions * @{ */ /* Peripheral Control functions ************************************************/ void HAL_PWR_PVDConfig(PWR_PVDTypeDef *sConfigPVD); void HAL_PWR_EnablePVD(void); void HAL_PWR_DisablePVD(void); /* WakeUp pins configuration functions ****************************************/ void HAL_PWR_EnableWakeUpPin(uint32_t WakeUpPinx); void HAL_PWR_DisableWakeUpPin(uint32_t WakeUpPinx); /* Low Power modes configuration functions ************************************/ void HAL_PWR_EnterSTOPMode(uint32_t Regulator, uint8_t STOPEntry); void HAL_PWR_EnterSLEEPMode(uint32_t Regulator, uint8_t SLEEPEntry); void HAL_PWR_EnterSTANDBYMode(void); void HAL_PWR_PVD_IRQHandler(void); void HAL_PWR_PVDCallback(void); /** * @} */ /** * @} */ /** * @} */ /** * @} */ #ifdef __cplusplus } #endif #endif /* __STM32L1xx_HAL_PWR_H */ /************************ (C) COPYRIGHT STMicroelectronics *****END OF FILE****/ ================================================ FILE: Zelig/mbed/TARGET_NUCLEO_L152RE/stm32l1xx_hal_pwr_ex.h ================================================ /** ****************************************************************************** * @file stm32l1xx_hal_pwr_ex.h * @author MCD Application Team * @version V1.0.0 * @date 5-September-2014 * @brief Header file of PWR HAL Extension module. ****************************************************************************** * @attention * *

© COPYRIGHT(c) 2014 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. * ****************************************************************************** */ /* Define to prevent recursive inclusion -------------------------------------*/ #ifndef __STM32L1xx_HAL_PWR_EX_H #define __STM32L1xx_HAL_PWR_EX_H #ifdef __cplusplus extern "C" { #endif /* Includes ------------------------------------------------------------------*/ #include "stm32l1xx_hal_def.h" /** @addtogroup STM32L1xx_HAL_Driver * @{ */ /** @addtogroup PWREx * @{ */ /* Exported types ------------------------------------------------------------*/ /* Exported constants --------------------------------------------------------*/ /** @defgroup PWREx_Exported_Constants PWREx Exported Constants * @{ */ /** @defgroup PWR_WakeUp_Pins PWREx Wakeup Pins * @{ */ #if defined (STM32L151xCA) || defined (STM32L151xD) || defined (STM32L152xCA) || defined (STM32L152xD) || defined (STM32L162xCA) || defined (STM32L162xD) || defined (STM32L151xE) || defined (STM32L152xE) || defined (STM32L162xE) || defined (STM32L151xB) || defined (STM32L151xBA) || defined (STM32L151xC) || defined (STM32L152xB) || defined (STM32L152xBA) || defined (STM32L152xC) || defined (STM32L162xC) #define PWR_WAKEUP_PIN1 PWR_CSR_EWUP1 #define PWR_WAKEUP_PIN2 PWR_CSR_EWUP2 #define PWR_WAKEUP_PIN3 PWR_CSR_EWUP3 #define IS_PWR_WAKEUP_PIN(PIN) (((PIN) == PWR_WAKEUP_PIN1) || \ ((PIN) == PWR_WAKEUP_PIN2) || \ ((PIN) == PWR_WAKEUP_PIN3)) #else #define PWR_WAKEUP_PIN1 PWR_CSR_EWUP1 #define PWR_WAKEUP_PIN2 PWR_CSR_EWUP2 #define IS_PWR_WAKEUP_PIN(PIN) (((PIN) == PWR_WAKEUP_PIN1) || \ ((PIN) == PWR_WAKEUP_PIN2)) #endif /** * @} */ /** * @} */ /* Exported macro ------------------------------------------------------------*/ /* Exported functions --------------------------------------------------------*/ /** @defgroup PWREx_Exported_Functions PWREx Exported Functions * @{ */ /** @addtogroup PWREx_Exported_Functions_Group1 * @{ */ /* Peripheral Control methods ************************************************/ void HAL_PWREx_EnableFastWakeUp(void); void HAL_PWREx_DisableFastWakeUp(void); void HAL_PWREx_EnableUltraLowPower(void); void HAL_PWREx_DisableUltraLowPower(void); void HAL_PWREx_EnableLowPowerRunMode(void); void HAL_PWREx_DisableLowPowerRunMode(void); /** * @} */ /** * @} */ /** * @} */ /** * @} */ #ifdef __cplusplus } #endif #endif /* __STM32L1xx_HAL_PWR_EX_H */ /************************ (C) COPYRIGHT STMicroelectronics *****END OF FILE****/ ================================================ FILE: Zelig/mbed/TARGET_NUCLEO_L152RE/stm32l1xx_hal_rcc.h ================================================ /** ****************************************************************************** * @file stm32l1xx_hal_rcc.h * @author MCD Application Team * @version V1.0.0 * @date 5-September-2014 * @brief Header file of RCC HAL module. ****************************************************************************** * @attention * *

© COPYRIGHT(c) 2014 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. * ****************************************************************************** */ /* Define to prevent recursive inclusion -------------------------------------*/ #ifndef __STM32L1xx_HAL_RCC_H #define __STM32L1xx_HAL_RCC_H #ifdef __cplusplus extern "C" { #endif /* Includes ------------------------------------------------------------------*/ #include "stm32l1xx_hal_def.h" /** @addtogroup STM32L1xx_HAL_Driver * @{ */ /** @addtogroup RCC * @{ */ /* Exported types ------------------------------------------------------------*/ /** @defgroup RCC_Exported_Types RCC Exported Types * @{ */ /** * @brief RCC PLL configuration structure definition */ typedef struct { uint32_t PLLState; /*!< The new state of the PLL. This parameter can be a value of @ref RCC_PLL_Config */ uint32_t PLLSource; /*!< PLLSource: PLL entry clock source. This parameter must be a value of @ref RCC_PLL_Clock_Source */ uint32_t PLLMUL; /*!< PLLMUL: Multiplication factor for PLL VCO input clock This parameter must be a value of @ref RCC_PLL_Multiplication_Factor*/ uint32_t PLLDIV; /*!< PLLDIV: Division factor for PLL VCO input clock This parameter must be a value of @ref RCC_PLL_Division_Factor*/ } RCC_PLLInitTypeDef; /** * @brief RCC Internal/External Oscillator (HSE, HSI, LSE and LSI) configuration structure definition */ typedef struct { uint32_t OscillatorType; /*!< The oscillators to be configured. This parameter can be a value of @ref RCC_Oscillator_Type */ uint32_t HSEState; /*!< The new state of the HSE. This parameter can be a value of @ref RCC_HSE_Config */ uint32_t LSEState; /*!< The new state of the LSE. This parameter can be a value of @ref RCC_LSE_Config */ uint32_t HSIState; /*!< The new state of the HSI. This parameter can be a value of @ref RCC_HSI_Config */ uint32_t HSICalibrationValue; /*!< The HSI calibration trimming value (default is RCC_HSICALIBRATION_DEFAULT). This parameter must be a number between Min_Data = 0x00 and Max_Data = 0x1F */ uint32_t LSIState; /*!< The new state of the LSI. This parameter can be a value of @ref RCC_LSI_Config */ uint32_t MSIState; /*!< The new state of the MSI. This parameter can be a value of @ref RCC_MSI_Config */ uint32_t MSICalibrationValue; /*!< The MSI calibration trimming value. (default is RCC_MSICALIBRATION_DEFAULT). This parameter must be a number between Min_Data = 0x00 and Max_Data = 0xFF */ uint32_t MSIClockRange; /*!< The MSI frequency range. This parameter can be a value of @ref RCC_MSI_Clock_Range */ RCC_PLLInitTypeDef PLL; /*!< PLL structure parameters */ } RCC_OscInitTypeDef; /** * @brief RCC System, AHB and APB busses clock configuration structure definition */ typedef struct { uint32_t ClockType; /*!< The clock to be configured. This parameter can be a value of @ref RCC_System_Clock_Type */ uint32_t SYSCLKSource; /*!< The clock source (SYSCLKS) used as system clock. This parameter can be a value of @ref RCC_System_Clock_Source */ uint32_t AHBCLKDivider; /*!< The AHB clock (HCLK) divider. This clock is derived from the system clock (SYSCLK). This parameter can be a value of @ref RCC_AHB_Clock_Source */ uint32_t APB1CLKDivider; /*!< The APB1 clock (PCLK1) divider. This clock is derived from the AHB clock (HCLK). This parameter can be a value of @ref RCC_APB1_APB2_Clock_Source */ uint32_t APB2CLKDivider; /*!< The APB2 clock (PCLK2) divider. This clock is derived from the AHB clock (HCLK). This parameter can be a value of @ref RCC_APB1_APB2_Clock_Source */ } RCC_ClkInitTypeDef; /** * @} */ /* Exported constants --------------------------------------------------------*/ /** @defgroup RCC_Exported_Constants RCC Exported Constants * @{ */ #define DBP_TIMEOUT_VALUE ((uint32_t)100) #define LSE_TIMEOUT_VALUE LSE_STARTUP_TIMEOUT /** @defgroup RCC_BitAddress_AliasRegion RCC BitAddress AliasRegion * @brief RCC registers bit address in the alias region * @{ */ #define RCC_OFFSET (RCC_BASE - PERIPH_BASE) #define RCC_CR_OFFSET 0x00 #define RCC_CFGR_OFFSET 0x08 #define RCC_CIR_OFFSET 0x0C #define RCC_CSR_OFFSET 0x34 #define RCC_CR_OFFSET_BB (RCC_OFFSET + RCC_CR_OFFSET) #define RCC_CFGR_OFFSET_BB (RCC_OFFSET + RCC_CFGR_OFFSET) #define RCC_CIR_OFFSET_BB (RCC_OFFSET + RCC_CIR_OFFSET) #define RCC_CSR_OFFSET_BB (RCC_OFFSET + RCC_CSR_OFFSET) /* --- CR Register ---*/ /* Alias word address of HSION bit */ #define HSION_BITNUMBER POSITION_VAL(RCC_CR_HSION) #define CR_HSION_BB ((uint32_t)(PERIPH_BB_BASE + (RCC_CR_OFFSET_BB * 32) + (HSION_BITNUMBER * 4))) /* Alias word address of MSION bit */ #define MSION_BITNUMBER POSITION_VAL(RCC_CR_MSION) #define CR_MSION_BB ((uint32_t)(PERIPH_BB_BASE + (RCC_CR_OFFSET_BB * 32) + (MSION_BITNUMBER * 4))) /* Alias word address of HSEON bit */ #define HSEON_BITNUMBER POSITION_VAL(RCC_CR_HSEON) #define CR_HSEON_BB ((uint32_t)(PERIPH_BB_BASE + (RCC_CR_OFFSET_BB * 32) + (HSEON_BITNUMBER * 4))) /* Alias word address of CSSON bit */ #define CSSON_BITNUMBER POSITION_VAL(RCC_CR_CSSON) #define CR_CSSON_BB ((uint32_t)(PERIPH_BB_BASE + (RCC_CR_OFFSET_BB * 32) + (CSSON_BITNUMBER * 4))) /* Alias word address of PLLON bit */ #define PLLON_BITNUMBER POSITION_VAL(RCC_CR_PLLON) #define CR_PLLON_BB ((uint32_t)(PERIPH_BB_BASE + (RCC_CR_OFFSET_BB * 32) + (PLLON_BITNUMBER * 4))) /* --- CSR Register ---*/ /* Alias word address of LSION bit */ #define LSION_BITNUMBER POSITION_VAL(RCC_CSR_LSION) #define CSR_LSION_BB ((uint32_t)(PERIPH_BB_BASE + (RCC_CSR_OFFSET_BB * 32) + (LSION_BITNUMBER * 4))) /* Alias word address of LSEON bit */ #define LSEON_BITNUMBER POSITION_VAL(RCC_CSR_LSEON) #define CSR_LSEON_BB ((uint32_t)(PERIPH_BB_BASE + (RCC_CSR_OFFSET_BB * 32) + (LSEON_BITNUMBER * 4))) /* Alias word address of LSEON bit */ #define LSEBYP_BITNUMBER POSITION_VAL(RCC_CSR_LSEBYP) #define CSR_LSEBYP_BB ((uint32_t)(PERIPH_BB_BASE + (RCC_CSR_OFFSET_BB * 32) + (LSEBYP_BITNUMBER * 4))) /* Alias word address of RTCEN bit */ #define RTCEN_BITNUMBER POSITION_VAL(RCC_CSR_RTCEN) #define CSR_RTCEN_BB ((uint32_t)(PERIPH_BB_BASE + (RCC_CSR_OFFSET_BB * 32) + (RTCEN_BITNUMBER * 4))) /* Alias word address of RTCRST bit */ #define RTCRST_BITNUMBER POSITION_VAL(RCC_CSR_RTCRST) #define CSR_RTCRST_BB ((uint32_t)(PERIPH_BB_BASE + (RCC_CSR_OFFSET_BB * 32) + (RTCRST_BITNUMBER * 4))) /* CR register byte 2 (Bits[23:16]) base address */ #define CR_BYTE2_ADDRESS ((uint32_t)(RCC_BASE + RCC_CR_OFFSET + 0x02)) /* CIR register byte 1 (Bits[15:8]) base address */ #define CIR_BYTE1_ADDRESS ((uint32_t)(RCC_BASE + RCC_CIR_OFFSET + 0x01)) /* CIR register byte 2 (Bits[23:16]) base address */ #define CIR_BYTE2_ADDRESS ((uint32_t)(RCC_BASE + RCC_CIR_OFFSET + 0x02)) /** * @} */ /** @defgroup RCC_PLL_Clock_Source RCC PLL Clock Source * @{ */ #define RCC_PLLSOURCE_HSI RCC_CFGR_PLLSRC_HSI #define RCC_PLLSOURCE_HSE RCC_CFGR_PLLSRC_HSE #define IS_RCC_PLLSOURCE(__SOURCE__) (((__SOURCE__) == RCC_PLLSOURCE_HSI) || \ ((__SOURCE__) == RCC_PLLSOURCE_HSE)) /** * @} */ /** @defgroup RCC_Oscillator_Type RCC Oscillator Type * @{ */ #define RCC_OSCILLATORTYPE_NONE ((uint32_t)0x00000000) #define RCC_OSCILLATORTYPE_HSE ((uint32_t)0x00000001) #define RCC_OSCILLATORTYPE_HSI ((uint32_t)0x00000002) #define RCC_OSCILLATORTYPE_LSE ((uint32_t)0x00000004) #define RCC_OSCILLATORTYPE_LSI ((uint32_t)0x00000008) #define RCC_OSCILLATORTYPE_MSI ((uint32_t)0x00000010) #define IS_RCC_OSCILLATORTYPE(__OSCILLATOR__) (((__OSCILLATOR__) == RCC_OSCILLATORTYPE_NONE) || \ (((__OSCILLATOR__) & RCC_OSCILLATORTYPE_HSE) == RCC_OSCILLATORTYPE_HSE) || \ (((__OSCILLATOR__) & RCC_OSCILLATORTYPE_HSI) == RCC_OSCILLATORTYPE_HSI) || \ (((__OSCILLATOR__) & RCC_OSCILLATORTYPE_LSI) == RCC_OSCILLATORTYPE_LSI) || \ (((__OSCILLATOR__) & RCC_OSCILLATORTYPE_LSE) == RCC_OSCILLATORTYPE_LSE) || \ (((__OSCILLATOR__) & RCC_OSCILLATORTYPE_MSI) == RCC_OSCILLATORTYPE_MSI)) /** * @} */ /** @defgroup RCC_HSE_Config RCC HSE Config * @{ */ #define RCC_HSE_OFF ((uint32_t)0x00000000) #define RCC_HSE_ON ((uint32_t)0x00000001) #define RCC_HSE_BYPASS ((uint32_t)0x00000005) #define IS_RCC_HSE(__HSE__) (((__HSE__) == RCC_HSE_OFF) || ((__HSE__) == RCC_HSE_ON) || \ ((__HSE__) == RCC_HSE_BYPASS)) /** * @} */ /** @defgroup RCC_LSE_Config RCC LSE Config * @{ */ #define RCC_LSE_OFF ((uint32_t)0x00000000) #define RCC_LSE_ON ((uint32_t)0x00000001) #define RCC_LSE_BYPASS ((uint32_t)0x00000005) #define IS_RCC_LSE(__LSE__) (((__LSE__) == RCC_LSE_OFF) || ((__LSE__) == RCC_LSE_ON) || \ ((__LSE__) == RCC_LSE_BYPASS)) /** * @} */ /** @defgroup RCC_HSI_Config RCC HSI Config * @{ */ #define RCC_HSI_OFF ((uint32_t)0x00000000) #define RCC_HSI_ON ((uint32_t)0x00000001) #define IS_RCC_HSI(__HSI__) (((__HSI__) == RCC_HSI_OFF) || ((__HSI__) == RCC_HSI_ON)) #define RCC_HSICALIBRATION_DEFAULT ((uint32_t)0x10) /* Default HSI calibration trimming value */ #define IS_RCC_CALIBRATION_VALUE(__VALUE__) ((__VALUE__) <= 0x1F) /** * @} */ /** @defgroup RCC_MSI_Clock_Range RCC MSI Clock Range * @{ */ #define RCC_MSIRANGE_0 ((uint32_t)RCC_ICSCR_MSIRANGE_0) /*!< MSI = 65.536 KHz */ #define RCC_MSIRANGE_1 ((uint32_t)RCC_ICSCR_MSIRANGE_1) /*!< MSI = 131.072 KHz */ #define RCC_MSIRANGE_2 ((uint32_t)RCC_ICSCR_MSIRANGE_2) /*!< MSI = 262.144 KHz */ #define RCC_MSIRANGE_3 ((uint32_t)RCC_ICSCR_MSIRANGE_3) /*!< MSI = 524.288 KHz */ #define RCC_MSIRANGE_4 ((uint32_t)RCC_ICSCR_MSIRANGE_4) /*!< MSI = 1.048 MHz */ #define RCC_MSIRANGE_5 ((uint32_t)RCC_ICSCR_MSIRANGE_5) /*!< MSI = 2.097 MHz */ #define RCC_MSIRANGE_6 ((uint32_t)RCC_ICSCR_MSIRANGE_6) /*!< MSI = 4.194 MHz */ #define IS_RCC_MSIRANGE(__RANGE__) (((__RANGE__) == RCC_MSIRANGE_0) || \ ((__RANGE__) == RCC_MSIRANGE_1) || \ ((__RANGE__) == RCC_MSIRANGE_2) || \ ((__RANGE__) == RCC_MSIRANGE_3) || \ ((__RANGE__) == RCC_MSIRANGE_4) || \ ((__RANGE__) == RCC_MSIRANGE_5) || \ ((__RANGE__) == RCC_MSIRANGE_6)) /** * @} */ /** @defgroup RCC_LSI_Config RCC LSI Config * @{ */ #define RCC_LSI_OFF ((uint32_t)0x00000000) #define RCC_LSI_ON ((uint32_t)0x00000001) #define IS_RCC_LSI(__LSI__) (((__LSI__) == RCC_LSI_OFF) || ((__LSI__) == RCC_LSI_ON)) /** * @} */ /** @defgroup RCC_MSI_Config RCC MSI Config * @{ */ #define RCC_MSI_OFF ((uint32_t)0x00000000) #define RCC_MSI_ON ((uint32_t)0x00000001) #define IS_RCC_MSI(__MSI__) (((__MSI__) == RCC_MSI_OFF) || ((__MSI__) == RCC_MSI_ON)) #define RCC_MSICALIBRATION_DEFAULT ((uint32_t)0x00) /* Default MSI calibration trimming value */ /** * @} */ /** @defgroup RCC_PLL_Config RCC PLL Config * @{ */ #define RCC_PLL_NONE ((uint32_t)0x00000000) #define RCC_PLL_OFF ((uint32_t)0x00000001) #define RCC_PLL_ON ((uint32_t)0x00000002) #define IS_RCC_PLL(__PLL__) (((__PLL__) == RCC_PLL_NONE) || ((__PLL__) == RCC_PLL_OFF) || \ ((__PLL__) == RCC_PLL_ON)) /** * @} */ /** @defgroup RCC_PLL_Division_Factor RCC PLL Division Factor * @{ */ #define RCC_PLL_DIV2 RCC_CFGR_PLLDIV2 #define RCC_PLL_DIV3 RCC_CFGR_PLLDIV3 #define RCC_PLL_DIV4 RCC_CFGR_PLLDIV4 #define IS_RCC_PLL_DIV(__DIV__) (((__DIV__) == RCC_PLL_DIV2) || \ ((__DIV__) == RCC_PLL_DIV3) || ((__DIV__) == RCC_PLL_DIV4)) /** * @} */ /** @defgroup RCC_PLL_Multiplication_Factor RCC PLL Multiplication Factor * @{ */ #define RCC_PLL_MUL3 RCC_CFGR_PLLMUL3 #define RCC_PLL_MUL4 RCC_CFGR_PLLMUL4 #define RCC_PLL_MUL6 RCC_CFGR_PLLMUL6 #define RCC_PLL_MUL8 RCC_CFGR_PLLMUL8 #define RCC_PLL_MUL12 RCC_CFGR_PLLMUL12 #define RCC_PLL_MUL16 RCC_CFGR_PLLMUL16 #define RCC_PLL_MUL24 RCC_CFGR_PLLMUL24 #define RCC_PLL_MUL32 RCC_CFGR_PLLMUL32 #define RCC_PLL_MUL48 RCC_CFGR_PLLMUL48 #define IS_RCC_PLL_MUL(__MUL__) (((__MUL__) == RCC_PLL_MUL3) || ((__MUL__) == RCC_PLL_MUL4) || \ ((__MUL__) == RCC_PLL_MUL6) || ((__MUL__) == RCC_PLL_MUL8) || \ ((__MUL__) == RCC_PLL_MUL12) || ((__MUL__) == RCC_PLL_MUL16) || \ ((__MUL__) == RCC_PLL_MUL24) || ((__MUL__) == RCC_PLL_MUL32) || \ ((__MUL__) == RCC_PLL_MUL48)) /** * @} */ /** @defgroup RCC_System_Clock_Type RCC System Clock Type * @{ */ #define RCC_CLOCKTYPE_SYSCLK ((uint32_t)0x00000001) #define RCC_CLOCKTYPE_HCLK ((uint32_t)0x00000002) #define RCC_CLOCKTYPE_PCLK1 ((uint32_t)0x00000004) #define RCC_CLOCKTYPE_PCLK2 ((uint32_t)0x00000008) #define IS_RCC_CLOCKTYPE(__CLK__) ((1 <= (__CLK__)) && ((__CLK__) <= 15)) /** * @} */ /** @defgroup RCC_System_Clock_Source RCC System Clock Source * @{ */ #define RCC_SYSCLKSOURCE_MSI ((uint32_t)RCC_CFGR_SW_MSI) #define RCC_SYSCLKSOURCE_HSI ((uint32_t)RCC_CFGR_SW_HSI) #define RCC_SYSCLKSOURCE_HSE ((uint32_t)RCC_CFGR_SW_HSE) #define RCC_SYSCLKSOURCE_PLLCLK ((uint32_t)RCC_CFGR_SW_PLL) #define IS_RCC_SYSCLKSOURCE(__SOURCE__) (((__SOURCE__) == RCC_SYSCLKSOURCE_MSI) || \ ((__SOURCE__) == RCC_SYSCLKSOURCE_HSI) || \ ((__SOURCE__) == RCC_SYSCLKSOURCE_HSE) || \ ((__SOURCE__) == RCC_SYSCLKSOURCE_PLLCLK)) /** * @} */ /** @defgroup RCC_AHB_Clock_Source RCC AHB Clock Source * @{ */ #define RCC_SYSCLK_DIV1 ((uint32_t)RCC_CFGR_HPRE_DIV1) #define RCC_SYSCLK_DIV2 ((uint32_t)RCC_CFGR_HPRE_DIV2) #define RCC_SYSCLK_DIV4 ((uint32_t)RCC_CFGR_HPRE_DIV4) #define RCC_SYSCLK_DIV8 ((uint32_t)RCC_CFGR_HPRE_DIV8) #define RCC_SYSCLK_DIV16 ((uint32_t)RCC_CFGR_HPRE_DIV16) #define RCC_SYSCLK_DIV64 ((uint32_t)RCC_CFGR_HPRE_DIV64) #define RCC_SYSCLK_DIV128 ((uint32_t)RCC_CFGR_HPRE_DIV128) #define RCC_SYSCLK_DIV256 ((uint32_t)RCC_CFGR_HPRE_DIV256) #define RCC_SYSCLK_DIV512 ((uint32_t)RCC_CFGR_HPRE_DIV512) #define IS_RCC_HCLK(__HCLK__) (((__HCLK__) == RCC_SYSCLK_DIV1) || ((__HCLK__) == RCC_SYSCLK_DIV2) || \ ((__HCLK__) == RCC_SYSCLK_DIV4) || ((__HCLK__) == RCC_SYSCLK_DIV8) || \ ((__HCLK__) == RCC_SYSCLK_DIV16) || ((__HCLK__) == RCC_SYSCLK_DIV64) || \ ((__HCLK__) == RCC_SYSCLK_DIV128) || ((__HCLK__) == RCC_SYSCLK_DIV256) || \ ((__HCLK__) == RCC_SYSCLK_DIV512)) /** * @} */ /** @defgroup RCC_APB1_APB2_Clock_Source RCC APB1 APB2 Clock Source * @{ */ #define RCC_HCLK_DIV1 ((uint32_t)RCC_CFGR_PPRE1_DIV1) #define RCC_HCLK_DIV2 ((uint32_t)RCC_CFGR_PPRE1_DIV2) #define RCC_HCLK_DIV4 ((uint32_t)RCC_CFGR_PPRE1_DIV4) #define RCC_HCLK_DIV8 ((uint32_t)RCC_CFGR_PPRE1_DIV8) #define RCC_HCLK_DIV16 ((uint32_t)RCC_CFGR_PPRE1_DIV16) #define IS_RCC_PCLK(__PCLK__) (((__PCLK__) == RCC_HCLK_DIV1) || ((__PCLK__) == RCC_HCLK_DIV2) || \ ((__PCLK__) == RCC_HCLK_DIV4) || ((__PCLK__) == RCC_HCLK_DIV8) || \ ((__PCLK__) == RCC_HCLK_DIV16)) /** * @} */ /** @defgroup RCC_RTC_LCD_Clock_Source RCC RTC LCD Clock Source * @{ */ #define RCC_RTCCLKSOURCE_LSE ((uint32_t)RCC_CSR_RTCSEL_LSE) #define RCC_RTCCLKSOURCE_LSI ((uint32_t)RCC_CSR_RTCSEL_LSI) #define RCC_RTCCLKSOURCE_HSE_DIV2 ((uint32_t)RCC_CSR_RTCSEL_HSE) #define RCC_RTCCLKSOURCE_HSE_DIV4 ((uint32_t)(RCC_CR_RTCPRE_0 | RCC_CSR_RTCSEL_HSE)) #define RCC_RTCCLKSOURCE_HSE_DIV8 ((uint32_t)(RCC_CR_RTCPRE_1 | RCC_CSR_RTCSEL_HSE)) #define RCC_RTCCLKSOURCE_HSE_DIV16 ((uint32_t)(RCC_CR_RTCPRE | RCC_CSR_RTCSEL_HSE)) /** * @} */ /** @defgroup RCC_MCO_Index RCC MCO Index * @{ */ #define RCC_MCO1 ((uint32_t)0x00000000) #define RCC_MCO RCC_MCO1 #define IS_RCC_MCO(__MCO__) (((__MCO__) == RCC_MCO)) /** * @} */ /** @defgroup RCC_MCOx_Clock_Prescaler RCC MCO1 Clock Prescaler * @{ */ #define RCC_MCODIV_1 ((uint32_t)RCC_CFGR_MCO_DIV1) #define RCC_MCODIV_2 ((uint32_t)RCC_CFGR_MCO_DIV2) #define RCC_MCODIV_4 ((uint32_t)RCC_CFGR_MCO_DIV4) #define RCC_MCODIV_8 ((uint32_t)RCC_CFGR_MCO_DIV8) #define RCC_MCODIV_16 ((uint32_t)RCC_CFGR_MCO_DIV16) #define IS_RCC_MCODIV(__DIV__) (((__DIV__) == RCC_MCODIV_1) || ((__DIV__) == RCC_MCODIV_2) || \ ((__DIV__) == RCC_MCODIV_4) || ((__DIV__) == RCC_MCODIV_8) || \ ((__DIV__) == RCC_MCODIV_16)) /** * @} */ /** @defgroup RCC_MCO1_Clock_Source RCC MCO1 Clock Source * @{ */ #define RCC_MCO1SOURCE_NOCLOCK ((uint32_t)RCC_CFGR_MCO_NOCLOCK) #define RCC_MCO1SOURCE_SYSCLK ((uint32_t)RCC_CFGR_MCO_SYSCLK) #define RCC_MCO1SOURCE_MSI ((uint32_t)RCC_CFGR_MCO_MSI) #define RCC_MCO1SOURCE_HSI ((uint32_t)RCC_CFGR_MCO_HSI) #define RCC_MCO1SOURCE_LSE ((uint32_t)RCC_CFGR_MCO_LSE) #define RCC_MCO1SOURCE_LSI ((uint32_t)RCC_CFGR_MCO_LSI) #define RCC_MCO1SOURCE_HSE ((uint32_t)RCC_CFGR_MCO_HSE) #define RCC_MCO1SOURCE_PLLCLK ((uint32_t)RCC_CFGR_MCO_PLL) #define IS_RCC_MCO1SOURCE(__SOURCE__) (((__SOURCE__) == RCC_MCO1SOURCE_SYSCLK) || ((__SOURCE__) == RCC_MCO1SOURCE_MSI) \ || ((__SOURCE__) == RCC_MCO1SOURCE_HSI) || ((__SOURCE__) == RCC_MCO1SOURCE_LSE) \ || ((__SOURCE__) == RCC_MCO1SOURCE_LSI) || ((__SOURCE__) == RCC_MCO1SOURCE_HSE) \ || ((__SOURCE__) == RCC_MCO1SOURCE_PLLCLK) || ((__SOURCE__) == RCC_MCO1SOURCE_NOCLOCK)) /** * @} */ /** @defgroup RCC_Interrupt RCC Interrupt * @{ */ #define RCC_IT_LSIRDY ((uint8_t)RCC_CIR_LSIRDYF) #define RCC_IT_LSERDY ((uint8_t)RCC_CIR_LSERDYF) #define RCC_IT_HSIRDY ((uint8_t)RCC_CIR_HSIRDYF) #define RCC_IT_HSERDY ((uint8_t)RCC_CIR_HSERDYF) #define RCC_IT_PLLRDY ((uint8_t)RCC_CIR_PLLRDYF) #define RCC_IT_MSIRDY ((uint8_t)RCC_CIR_MSIRDYF) #define RCC_IT_LSECSS ((uint8_t)RCC_CIR_LSECSS) #define RCC_IT_CSS ((uint8_t)RCC_CIR_CSSF) /** * @} */ /** @defgroup RCC_Flag RCC Flag * Elements values convention: 0XXYYYYYb * - YYYYY : Flag position in the register * - XX : Register index * - 01: CR register * - 11: CSR register * @{ */ #define CR_REG_INDEX ((uint8_t)1) #define CSR_REG_INDEX ((uint8_t)3) /* Flags in the CR register */ #define RCC_FLAG_HSIRDY ((uint8_t)((CR_REG_INDEX << 5) | POSITION_VAL(RCC_CR_HSIRDY))) #define RCC_FLAG_MSIRDY ((uint8_t)((CR_REG_INDEX << 5) | POSITION_VAL(RCC_CR_MSIRDY))) #define RCC_FLAG_HSERDY ((uint8_t)((CR_REG_INDEX << 5) | POSITION_VAL(RCC_CR_HSERDY))) #define RCC_FLAG_PLLRDY ((uint8_t)((CR_REG_INDEX << 5) | POSITION_VAL(RCC_CR_PLLRDY))) /* Flags in the CSR register */ #define RCC_FLAG_LSIRDY ((uint8_t)((CSR_REG_INDEX << 5) | POSITION_VAL(RCC_CSR_LSIRDY))) #define RCC_FLAG_LSERDY ((uint8_t)((CSR_REG_INDEX << 5) | POSITION_VAL(RCC_CSR_LSERDY))) #define RCC_FLAG_LSECSS ((uint8_t)((CSR_REG_INDEX << 5) | POSITION_VAL(RCC_CSR_LSECSSD))) #define RCC_FLAG_RMV ((uint8_t)((CSR_REG_INDEX << 5) | POSITION_VAL(RCC_CSR_RMVF))) #define RCC_FLAG_OBLRST ((uint8_t)((CSR_REG_INDEX << 5) | POSITION_VAL(RCC_CSR_OBLRSTF))) #define RCC_FLAG_PINRST ((uint8_t)((CSR_REG_INDEX << 5) | POSITION_VAL(RCC_CSR_PINRSTF))) #define RCC_FLAG_PORRST ((uint8_t)((CSR_REG_INDEX << 5) | POSITION_VAL(RCC_CSR_PORRSTF))) #define RCC_FLAG_SFTRST ((uint8_t)((CSR_REG_INDEX << 5) | POSITION_VAL(RCC_CSR_SFTRSTF))) #define RCC_FLAG_IWDGRST ((uint8_t)((CSR_REG_INDEX << 5) | POSITION_VAL(RCC_CSR_IWDGRSTF))) #define RCC_FLAG_WWDGRST ((uint8_t)((CSR_REG_INDEX << 5) | POSITION_VAL(RCC_CSR_WWDGRSTF))) #define RCC_FLAG_LPWRRST ((uint8_t)((CSR_REG_INDEX << 5) | POSITION_VAL(RCC_CSR_LPWRRSTF))) #define RCC_FLAG_MASK ((uint8_t)0x1F) /** * @} */ /** * @} */ /* Exported macro ------------------------------------------------------------*/ /** @defgroup RCC_Exported_Macros RCC Exported Macros * @{ */ /** @defgroup RCC_Peripheral_Clock_Enable_Disable RCC Peripheral Clock Enable Disable * @brief Enable or disable the AHB1 peripheral clock. * @note After reset, the peripheral clock (used for registers read/write access) * is disabled and the application software has to enable this clock before * using it. * @{ */ #define __GPIOA_CLK_ENABLE() (RCC->AHBENR |= (RCC_AHBENR_GPIOAEN)) #define __GPIOB_CLK_ENABLE() (RCC->AHBENR |= (RCC_AHBENR_GPIOBEN)) #define __GPIOC_CLK_ENABLE() (RCC->AHBENR |= (RCC_AHBENR_GPIOCEN)) #define __GPIOD_CLK_ENABLE() (RCC->AHBENR |= (RCC_AHBENR_GPIODEN)) #define __GPIOH_CLK_ENABLE() (RCC->AHBENR |= (RCC_AHBENR_GPIOHEN)) #define __CRC_CLK_ENABLE() (RCC->AHBENR |= (RCC_AHBENR_CRCEN)) #define __FLITF_CLK_ENABLE() (RCC->AHBENR |= (RCC_AHBENR_FLITFEN)) #define __DMA1_CLK_ENABLE() (RCC->AHBENR |= (RCC_AHBENR_DMA1EN)) #define __GPIOA_CLK_DISABLE() (RCC->AHBENR &= ~(RCC_AHBENR_GPIOAEN)) #define __GPIOB_CLK_DISABLE() (RCC->AHBENR &= ~(RCC_AHBENR_GPIOBEN)) #define __GPIOC_CLK_DISABLE() (RCC->AHBENR &= ~(RCC_AHBENR_GPIOCEN)) #define __GPIOD_CLK_DISABLE() (RCC->AHBENR &= ~(RCC_AHBENR_GPIODEN)) #define __GPIOH_CLK_DISABLE() (RCC->AHBENR &= ~(RCC_AHBENR_GPIOHEN)) #define __CRC_CLK_DISABLE() (RCC->AHBENR &= ~(RCC_AHBENR_CRCEN)) #define __FLITF_CLK_DISABLE() (RCC->AHBENR &= ~(RCC_AHBENR_FLITFEN)) #define __DMA1_CLK_DISABLE() (RCC->AHBENR &= ~(RCC_AHBENR_DMA1EN)) /** @brief Enable or disable the Low Speed APB (APB1) peripheral clock. * @note After reset, the peripheral clock (used for registers read/write access) * is disabled and the application software has to enable this clock before * using it. */ #define __TIM2_CLK_ENABLE() (RCC->APB1ENR |= (RCC_APB1ENR_TIM2EN)) #define __TIM3_CLK_ENABLE() (RCC->APB1ENR |= (RCC_APB1ENR_TIM3EN)) #define __TIM4_CLK_ENABLE() (RCC->APB1ENR |= (RCC_APB1ENR_TIM4EN)) #define __TIM6_CLK_ENABLE() (RCC->APB1ENR |= (RCC_APB1ENR_TIM6EN)) #define __TIM7_CLK_ENABLE() (RCC->APB1ENR |= (RCC_APB1ENR_TIM7EN)) #define __WWDG_CLK_ENABLE() (RCC->APB1ENR |= (RCC_APB1ENR_WWDGEN)) #define __SPI2_CLK_ENABLE() (RCC->APB1ENR |= (RCC_APB1ENR_SPI2EN)) #define __USART2_CLK_ENABLE() (RCC->APB1ENR |= (RCC_APB1ENR_USART2EN)) #define __USART3_CLK_ENABLE() (RCC->APB1ENR |= (RCC_APB1ENR_USART3EN)) #define __I2C1_CLK_ENABLE() (RCC->APB1ENR |= (RCC_APB1ENR_I2C1EN)) #define __I2C2_CLK_ENABLE() (RCC->APB1ENR |= (RCC_APB1ENR_I2C2EN)) #define __USB_CLK_ENABLE() (RCC->APB1ENR |= (RCC_APB1ENR_USBEN)) #define __PWR_CLK_ENABLE() (RCC->APB1ENR |= (RCC_APB1ENR_PWREN)) #define __DAC_CLK_ENABLE() (RCC->APB1ENR |= (RCC_APB1ENR_DACEN)) #define __COMP_CLK_ENABLE() (RCC->APB1ENR |= (RCC_APB1ENR_COMPEN)) #define __TIM2_CLK_DISABLE() (RCC->APB1ENR &= ~(RCC_APB1ENR_TIM2EN)) #define __TIM3_CLK_DISABLE() (RCC->APB1ENR &= ~(RCC_APB1ENR_TIM3EN)) #define __TIM4_CLK_DISABLE() (RCC->APB1ENR &= ~(RCC_APB1ENR_TIM4EN)) #define __TIM6_CLK_DISABLE() (RCC->APB1ENR &= ~(RCC_APB1ENR_TIM6EN)) #define __TIM7_CLK_DISABLE() (RCC->APB1ENR &= ~(RCC_APB1ENR_TIM7EN)) #define __WWDG_CLK_DISABLE() (RCC->APB1ENR &= ~(RCC_APB1ENR_WWDGEN)) #define __SPI2_CLK_DISABLE() (RCC->APB1ENR &= ~(RCC_APB1ENR_SPI2EN)) #define __USART2_CLK_DISABLE() (RCC->APB1ENR &= ~(RCC_APB1ENR_USART2EN)) #define __USART3_CLK_DISABLE() (RCC->APB1ENR &= ~(RCC_APB1ENR_USART3EN)) #define __I2C1_CLK_DISABLE() (RCC->APB1ENR &= ~(RCC_APB1ENR_I2C1EN)) #define __I2C2_CLK_DISABLE() (RCC->APB1ENR &= ~(RCC_APB1ENR_I2C2EN)) #define __USB_CLK_DISABLE() (RCC->APB1ENR &= ~(RCC_APB1ENR_USBEN)) #define __PWR_CLK_DISABLE() (RCC->APB1ENR &= ~(RCC_APB1ENR_PWREN)) #define __DAC_CLK_DISABLE() (RCC->APB1ENR &= ~(RCC_APB1ENR_DACEN)) #define __COMP_CLK_DISABLE() (RCC->APB1ENR &= ~(RCC_APB1ENR_COMPEN)) /** @brief Enable or disable the High Speed APB (APB2) peripheral clock. * @note After reset, the peripheral clock (used for registers read/write access) * is disabled and the application software has to enable this clock before * using it. */ #define __SYSCFG_CLK_ENABLE() (RCC->APB2ENR |= (RCC_APB2ENR_SYSCFGEN)) #define __TIM9_CLK_ENABLE() (RCC->APB2ENR |= (RCC_APB2ENR_TIM9EN)) #define __TIM10_CLK_ENABLE() (RCC->APB2ENR |= (RCC_APB2ENR_TIM10EN)) #define __TIM11_CLK_ENABLE() (RCC->APB2ENR |= (RCC_APB2ENR_TIM11EN)) #define __ADC1_CLK_ENABLE() (RCC->APB2ENR |= (RCC_APB2ENR_ADC1EN)) #define __SPI1_CLK_ENABLE() (RCC->APB2ENR |= (RCC_APB2ENR_SPI1EN)) #define __USART1_CLK_ENABLE() (RCC->APB2ENR |= (RCC_APB2ENR_USART1EN)) #define __SYSCFG_CLK_DISABLE() (RCC->APB2ENR &= ~(RCC_APB2ENR_SYSCFGEN)) #define __TIM9_CLK_DISABLE() (RCC->APB2ENR &= ~(RCC_APB2ENR_TIM9EN)) #define __TIM10_CLK_DISABLE() (RCC->APB2ENR &= ~(RCC_APB2ENR_TIM10EN)) #define __TIM11_CLK_DISABLE() (RCC->APB2ENR &= ~(RCC_APB2ENR_TIM11EN)) #define __ADC1_CLK_DISABLE() (RCC->APB2ENR &= ~(RCC_APB2ENR_ADC1EN)) #define __SPI1_CLK_DISABLE() (RCC->APB2ENR &= ~(RCC_APB2ENR_SPI1EN)) #define __USART1_CLK_DISABLE() (RCC->APB2ENR &= ~(RCC_APB2ENR_USART1EN)) /** * @} */ /** @defgroup RCC_Peripheral_Clock_Force_Release RCC Peripheral Clock Force Release * @brief Force or release AHB peripheral reset. * @{ */ #define __AHB_FORCE_RESET() (RCC->AHBRSTR = 0xFFFFFFFF) #define __GPIOA_FORCE_RESET() (RCC->AHBRSTR |= (RCC_AHBRSTR_GPIOARST)) #define __GPIOB_FORCE_RESET() (RCC->AHBRSTR |= (RCC_AHBRSTR_GPIOBRST)) #define __GPIOC_FORCE_RESET() (RCC->AHBRSTR |= (RCC_AHBRSTR_GPIOCRST)) #define __GPIOD_FORCE_RESET() (RCC->AHBRSTR |= (RCC_AHBRSTR_GPIODRST)) #define __GPIOH_FORCE_RESET() (RCC->AHBRSTR |= (RCC_AHBRSTR_GPIOHRST)) #define __CRC_FORCE_RESET() (RCC->AHBRSTR |= (RCC_AHBRSTR_CRCRST)) #define __FLITF_FORCE_RESET() (RCC->AHBRSTR |= (RCC_AHBRSTR_FLITFRST)) #define __DMA1_FORCE_RESET() (RCC->AHBRSTR |= (RCC_AHBRSTR_DMA1RST)) #define __AHB_RELEASE_RESET() (RCC->AHBRSTR = 0x00) #define __GPIOA_RELEASE_RESET() (RCC->AHBRSTR &= ~(RCC_AHBRSTR_GPIOARST)) #define __GPIOB_RELEASE_RESET() (RCC->AHBRSTR &= ~(RCC_AHBRSTR_GPIOBRST)) #define __GPIOC_RELEASE_RESET() (RCC->AHBRSTR &= ~(RCC_AHBRSTR_GPIOCRST)) #define __GPIOD_RELEASE_RESET() (RCC->AHBRSTR &= ~(RCC_AHBRSTR_GPIODRST)) #define __GPIOH_RELEASE_RESET() (RCC->AHBRSTR &= ~(RCC_AHBRSTR_GPIOHRST)) #define __CRC_RELEASE_RESET() (RCC->AHBRSTR &= ~(RCC_AHBRSTR_CRCRST)) #define __FLITF_RELEASE_RESET() (RCC->AHBRSTR &= ~(RCC_AHBRSTR_FLITFRST)) #define __DMA1_RELEASE_RESET() (RCC->AHBRSTR &= ~(RCC_AHBRSTR_DMA1RST)) /** @brief Force or release APB1 peripheral reset. */ #define __APB1_FORCE_RESET() (RCC->APB1RSTR = 0xFFFFFFFF) #define __TIM2_FORCE_RESET() (RCC->APB1RSTR |= (RCC_APB1RSTR_TIM2RST)) #define __TIM3_FORCE_RESET() (RCC->APB1RSTR |= (RCC_APB1RSTR_TIM3RST)) #define __TIM4_FORCE_RESET() (RCC->APB1RSTR |= (RCC_APB1RSTR_TIM4RST)) #define __TIM6_FORCE_RESET() (RCC->APB1RSTR |= (RCC_APB1RSTR_TIM6RST)) #define __TIM7_FORCE_RESET() (RCC->APB1RSTR |= (RCC_APB1RSTR_TIM7RST)) #define __WWDG_FORCE_RESET() (RCC->APB1RSTR |= (RCC_APB1RSTR_WWDGRST)) #define __SPI2_FORCE_RESET() (RCC->APB1RSTR |= (RCC_APB1RSTR_SPI2RST)) #define __USART2_FORCE_RESET() (RCC->APB1RSTR |= (RCC_APB1RSTR_USART2RST)) #define __USART3_FORCE_RESET() (RCC->APB1RSTR |= (RCC_APB1RSTR_USART3RST)) #define __I2C1_FORCE_RESET() (RCC->APB1RSTR |= (RCC_APB1RSTR_I2C1RST)) #define __I2C2_FORCE_RESET() (RCC->APB1RSTR |= (RCC_APB1RSTR_I2C2RST)) #define __USB_FORCE_RESET() (RCC->APB1RSTR |= (RCC_APB1RSTR_USBRST)) #define __PWR_FORCE_RESET() (RCC->APB1RSTR |= (RCC_APB1RSTR_PWRRST)) #define __DAC_FORCE_RESET() (RCC->APB1RSTR |= (RCC_APB1RSTR_DACRST)) #define __COMP_FORCE_RESET() (RCC->APB1RSTR |= (RCC_APB1RSTR_COMPRST)) #define __APB1_RELEASE_RESET() (RCC->APB1RSTR = 0x00) #define __TIM2_RELEASE_RESET() (RCC->APB1RSTR &= ~(RCC_APB1RSTR_TIM2RST)) #define __TIM3_RELEASE_RESET() (RCC->APB1RSTR &= ~(RCC_APB1RSTR_TIM3RST)) #define __TIM4_RELEASE_RESET() (RCC->APB1RSTR &= ~(RCC_APB1RSTR_TIM4RST)) #define __TIM6_RELEASE_RESET() (RCC->APB1RSTR &= ~(RCC_APB1RSTR_TIM6RST)) #define __TIM7_RELEASE_RESET() (RCC->APB1RSTR &= ~(RCC_APB1RSTR_TIM7RST)) #define __WWDG_RELEASE_RESET() (RCC->APB1RSTR &= ~(RCC_APB1RSTR_WWDGRST)) #define __SPI2_RELEASE_RESET() (RCC->APB1RSTR &= ~(RCC_APB1RSTR_SPI2RST)) #define __USART2_RELEASE_RESET() (RCC->APB1RSTR &= ~(RCC_APB1RSTR_USART2RST)) #define __USART3_RELEASE_RESET() (RCC->APB1RSTR &= ~(RCC_APB1RSTR_USART3RST)) #define __I2C1_RELEASE_RESET() (RCC->APB1RSTR &= ~(RCC_APB1RSTR_I2C1RST)) #define __I2C2_RELEASE_RESET() (RCC->APB1RSTR &= ~(RCC_APB1RSTR_I2C2RST)) #define __USB_RELEASE_RESET() (RCC->APB1RSTR &= ~(RCC_APB1RSTR_USBRST)) #define __PWR_RELEASE_RESET() (RCC->APB1RSTR &= ~(RCC_APB1RSTR_PWRRST)) #define __DAC_RELEASE_RESET() (RCC->APB1RSTR &= ~(RCC_APB1RSTR_DACRST)) #define __COMP_RELEASE_RESET() (RCC->APB1RSTR &= ~(RCC_APB1RSTR_COMPRST)) /** @brief Force or release APB2 peripheral reset. */ #define __APB2_FORCE_RESET() (RCC->APB2RSTR = 0xFFFFFFFF) #define __SYSCFG_FORCE_RESET() (RCC->APB2RSTR |= (RCC_APB2RSTR_SYSCFGRST)) #define __TIM9_FORCE_RESET() (RCC->APB2RSTR |= (RCC_APB2RSTR_TIM9RST)) #define __TIM10_FORCE_RESET() (RCC->APB2RSTR |= (RCC_APB2RSTR_TIM10RST)) #define __TIM11_FORCE_RESET() (RCC->APB2RSTR |= (RCC_APB2RSTR_TIM11RST)) #define __ADC1_FORCE_RESET() (RCC->APB2RSTR |= (RCC_APB2RSTR_ADC1RST)) #define __SPI1_FORCE_RESET() (RCC->APB2RSTR |= (RCC_APB2RSTR_SPI1RST)) #define __USART1_FORCE_RESET() (RCC->APB2RSTR |= (RCC_APB2RSTR_USART1RST)) #define __APB2_RELEASE_RESET() (RCC->APB2RSTR = 0x00) #define __SYSCFG_RELEASE_RESET() (RCC->APB2RSTR &= ~(RCC_APB2RSTR_SYSCFGRST)) #define __TIM9_RELEASE_RESET() (RCC->APB2RSTR &= ~(RCC_APB2RSTR_TIM9RST)) #define __TIM10_RELEASE_RESET() (RCC->APB2RSTR &= ~(RCC_APB2RSTR_TIM10RST)) #define __TIM11_RELEASE_RESET() (RCC->APB2RSTR &= ~(RCC_APB2RSTR_TIM11RST)) #define __ADC1_RELEASE_RESET() (RCC->APB2RSTR &= ~(RCC_APB2RSTR_ADC1RST)) #define __SPI1_RELEASE_RESET() (RCC->APB2RSTR &= ~(RCC_APB2RSTR_SPI1RST)) #define __USART1_RELEASE_RESET() (RCC->APB2RSTR &= ~(RCC_APB2RSTR_USART1RST)) /** * @} */ /** @defgroup RCC_Peripheral_Clock_Sleep_Enable_Disable RCC Peripheral Clock Sleep Enable Disable * @note Peripheral clock gating in SLEEP mode can be used to further reduce * power consumption. * @note After wakeup from SLEEP mode, the peripheral clock is enabled again. * @note By default, all peripheral clocks are enabled during SLEEP mode. * @{ */ #define __GPIOA_CLK_SLEEP_ENABLE() (RCC->AHBLPENR |= (RCC_AHBLPENR_GPIOALPEN)) #define __GPIOB_CLK_SLEEP_ENABLE() (RCC->AHBLPENR |= (RCC_AHBLPENR_GPIOBLPEN)) #define __GPIOC_CLK_SLEEP_ENABLE() (RCC->AHBLPENR |= (RCC_AHBLPENR_GPIOCLPEN)) #define __GPIOD_CLK_SLEEP_ENABLE() (RCC->AHBLPENR |= (RCC_AHBLPENR_GPIODLPEN)) #define __GPIOH_CLK_SLEEP_ENABLE() (RCC->AHBLPENR |= (RCC_AHBLPENR_GPIOHLPEN)) #define __CRC_CLK_SLEEP_ENABLE() (RCC->AHBLPENR |= (RCC_AHBLPENR_CRCLPEN)) #define __FLITF_CLK_SLEEP_ENABLE() (RCC->AHBLPENR |= (RCC_AHBLPENR_FLITFLPEN)) #define __DMA1_CLK_SLEEP_ENABLE() (RCC->AHBLPENR |= (RCC_AHBLPENR_DMA1LPEN)) #define __GPIOA_CLK_SLEEP_DISABLE() (RCC->AHBLPENR &= ~(RCC_AHBLPENR_GPIOALPEN)) #define __GPIOB_CLK_SLEEP_DISABLE() (RCC->AHBLPENR &= ~(RCC_AHBLPENR_GPIOBLPEN)) #define __GPIOC_CLK_SLEEP_DISABLE() (RCC->AHBLPENR &= ~(RCC_AHBLPENR_GPIOCLPEN)) #define __GPIOD_CLK_SLEEP_DISABLE() (RCC->AHBLPENR &= ~(RCC_AHBLPENR_GPIODLPEN)) #define __GPIOH_CLK_SLEEP_DISABLE() (RCC->AHBLPENR &= ~(RCC_AHBLPENR_GPIOHLPEN)) #define __CRC_CLK_SLEEP_DISABLE() (RCC->AHBLPENR &= ~(RCC_AHBLPENR_CRCLPEN)) #define __FLITF_CLK_SLEEP_DISABLE() (RCC->AHBLPENR &= ~(RCC_AHBLPENR_FLITFLPEN)) #define __DMA1_CLK_SLEEP_DISABLE() (RCC->AHBLPENR &= ~(RCC_AHBLPENR_DMA1LPEN)) /** @brief Enable or disable the APB1 peripheral clock during Low Power (Sleep) mode. * @note Peripheral clock gating in SLEEP mode can be used to further reduce * power consumption. * @note After wakeup from SLEEP mode, the peripheral clock is enabled again. * @note By default, all peripheral clocks are enabled during SLEEP mode. */ #define __TIM2_CLK_SLEEP_ENABLE() (RCC->APB1LPENR |= (RCC_APB1LPENR_TIM2LPEN)) #define __TIM3_CLK_SLEEP_ENABLE() (RCC->APB1LPENR |= (RCC_APB1LPENR_TIM3LPEN)) #define __TIM4_CLK_SLEEP_ENABLE() (RCC->APB1LPENR |= (RCC_APB1LPENR_TIM4LPEN)) #define __TIM6_CLK_SLEEP_ENABLE() (RCC->APB1LPENR |= (RCC_APB1LPENR_TIM6LPEN)) #define __TIM7_CLK_SLEEP_ENABLE() (RCC->APB1LPENR |= (RCC_APB1LPENR_TIM7LPEN)) #define __WWDG_CLK_SLEEP_ENABLE() (RCC->APB1LPENR |= (RCC_APB1LPENR_WWDGLPEN)) #define __SPI2_CLK_SLEEP_ENABLE() (RCC->APB1LPENR |= (RCC_APB1LPENR_SPI2LPEN)) #define __USART2_CLK_SLEEP_ENABLE() (RCC->APB1LPENR |= (RCC_APB1LPENR_USART2LPEN)) #define __USART3_CLK_SLEEP_ENABLE() (RCC->APB1LPENR |= (RCC_APB1LPENR_USART3LPEN)) #define __I2C1_CLK_SLEEP_ENABLE() (RCC->APB1LPENR |= (RCC_APB1LPENR_I2C1LPEN)) #define __I2C2_CLK_SLEEP_ENABLE() (RCC->APB1LPENR |= (RCC_APB1LPENR_I2C2LPEN)) #define __USB_CLK_SLEEP_ENABLE() (RCC->APB1LPENR |= (RCC_APB1LPENR_USBLPEN)) #define __PWR_CLK_SLEEP_ENABLE() (RCC->APB1LPENR |= (RCC_APB1LPENR_PWRLPEN)) #define __DAC_CLK_SLEEP_ENABLE() (RCC->APB1LPENR |= (RCC_APB1LPENR_DACLPEN)) #define __COMP_CLK_SLEEP_ENABLE() (RCC->APB1LPENR |= (RCC_APB1LPENR_COMPLPEN)) #define __TIM2_CLK_SLEEP_DISABLE() (RCC->APB1LPENR &= ~(RCC_APB1LPENR_TIM2LPEN)) #define __TIM3_CLK_SLEEP_DISABLE() (RCC->APB1LPENR &= ~(RCC_APB1LPENR_TIM3LPEN)) #define __TIM4_CLK_SLEEP_DISABLE() (RCC->APB1LPENR &= ~(RCC_APB1LPENR_TIM4LPEN)) #define __TIM6_CLK_SLEEP_DISABLE() (RCC->APB1LPENR &= ~(RCC_APB1LPENR_TIM6LPEN)) #define __TIM7_CLK_SLEEP_DISABLE() (RCC->APB1LPENR &= ~(RCC_APB1LPENR_TIM7LPEN)) #define __WWDG_CLK_SLEEP_DISABLE() (RCC->APB1LPENR &= ~(RCC_APB1LPENR_WWDGLPEN)) #define __SPI2_CLK_SLEEP_DISABLE() (RCC->APB1LPENR &= ~(RCC_APB1LPENR_SPI2LPEN)) #define __USART2_CLK_SLEEP_DISABLE() (RCC->APB1LPENR &= ~(RCC_APB1LPENR_USART2LPEN)) #define __USART3_CLK_SLEEP_DISABLE() (RCC->APB1LPENR &= ~(RCC_APB1LPENR_USART3LPEN)) #define __I2C1_CLK_SLEEP_DISABLE() (RCC->APB1LPENR &= ~(RCC_APB1LPENR_I2C1LPEN)) #define __I2C2_CLK_SLEEP_DISABLE() (RCC->APB1LPENR &= ~(RCC_APB1LPENR_I2C2LPEN)) #define __USB_CLK_SLEEP_DISABLE() (RCC->APB1LPENR &= ~(RCC_APB1LPENR_USBLPEN)) #define __PWR_CLK_SLEEP_DISABLE() (RCC->APB1LPENR &= ~(RCC_APB1LPENR_PWRLPEN)) #define __DAC_CLK_SLEEP_DISABLE() (RCC->APB1LPENR &= ~(RCC_APB1LPENR_DACLPEN)) #define __COMP_CLK_SLEEP_DISABLE() (RCC->APB1LPENR &= ~(RCC_APB1LPENR_COMPLPEN)) /** @brief Enable or disable the APB2 peripheral clock during Low Power (Sleep) mode. * @note Peripheral clock gating in SLEEP mode can be used to further reduce * power consumption. * @note After wakeup from SLEEP mode, the peripheral clock is enabled again. * @note By default, all peripheral clocks are enabled during SLEEP mode. */ #define __SYSCFG_CLK_SLEEP_ENABLE() (RCC->APB2LPENR |= (RCC_APB2LPENR_SYSCFGLPEN)) #define __TIM9_CLK_SLEEP_ENABLE() (RCC->APB2LPENR |= (RCC_APB2LPENR_TIM9LPEN)) #define __TIM10_CLK_SLEEP_ENABLE() (RCC->APB2LPENR |= (RCC_APB2LPENR_TIM10LPEN)) #define __TIM11_CLK_SLEEP_ENABLE() (RCC->APB2LPENR |= (RCC_APB2LPENR_TIM11LPEN)) #define __ADC1_CLK_SLEEP_ENABLE() (RCC->APB2LPENR |= (RCC_APB2LPENR_ADC1LPEN)) #define __SPI1_CLK_SLEEP_ENABLE() (RCC->APB2LPENR |= (RCC_APB2LPENR_SPI1LPEN)) #define __USART1_CLK_SLEEP_ENABLE() (RCC->APB2LPENR |= (RCC_APB2LPENR_USART1LPEN)) #define __SYSCFG_CLK_SLEEP_DISABLE() (RCC->APB2LPENR &= ~(RCC_APB2LPENR_SYSCFGLPEN)) #define __TIM9_CLK_SLEEP_DISABLE() (RCC->APB2LPENR &= ~(RCC_APB2LPENR_TIM9LPEN)) #define __TIM10_CLK_SLEEP_DISABLE() (RCC->APB2LPENR &= ~(RCC_APB2LPENR_TIM10LPEN)) #define __TIM11_CLK_SLEEP_DISABLE() (RCC->APB2LPENR &= ~(RCC_APB2LPENR_TIM11LPEN)) #define __ADC1_CLK_SLEEP_DISABLE() (RCC->APB2LPENR &= ~(RCC_APB2LPENR_ADC1LPEN)) #define __SPI1_CLK_SLEEP_DISABLE() (RCC->APB2LPENR &= ~(RCC_APB2LPENR_SPI1LPEN)) #define __USART1_CLK_SLEEP_DISABLE() (RCC->APB2LPENR &= ~(RCC_APB2LPENR_USART1LPEN)) /** * @} */ /** @brief Macros to enable or disable the Internal High Speed oscillator (HSI). * @note The HSI is stopped by hardware when entering STOP and STANDBY modes. * @note HSI can not be stopped if it is used as system clock source. In this case, * you have to select another source of the system clock then stop the HSI. * @note After enabling the HSI, the application software should wait on HSIRDY * flag to be set indicating that HSI clock is stable and can be used as * system clock source. * @note When the HSI is stopped, HSIRDY flag goes low after 6 HSI oscillator * clock cycles. */ #define __HAL_RCC_HSI_ENABLE() (*(__IO uint32_t *) CR_HSION_BB = ENABLE) #define __HAL_RCC_HSI_DISABLE() (*(__IO uint32_t *) CR_HSION_BB = DISABLE) /** @brief Macros to enable or disable the External High Speed oscillator (HSE). * @param __HSE_STATE__: specifies the new state of the HSE. * This parameter can be one of the following values: * @arg RCC_HSE_OFF: turn OFF the HSE oscillator, HSERDY flag goes low after * 6 HSE oscillator clock cycles. * @arg RCC_HSE_ON: turn ON the HSE oscillator * @arg RCC_HSE_BYPASS: HSE oscillator bypassed with external clock */ #define __HAL_RCC_HSE_CONFIG(__HSE_STATE__) (*(__IO uint8_t *) CR_BYTE2_ADDRESS = (__HSE_STATE__)) /** @brief Macros to enable or disable the Internal Multi Speed oscillator (MSI). * @note The MSI is stopped by hardware when entering STOP and STANDBY modes. * It is used (enabled by hardware) as system clock source after startup * from Reset, wakeup from STOP and STANDBY mode, or in case of failure * of the HSE used directly or indirectly as system clock (if the Clock * Security System CSS is enabled). * @note MSI can not be stopped if it is used as system clock source. In this case, * you have to select another source of the system clock then stop the MSI. * @note After enabling the MSI, the application software should wait on MSIRDY * flag to be set indicating that MSI clock is stable and can be used as * system clock source. * @note When the MSI is stopped, MSIRDY flag goes low after 6 MSI oscillator * clock cycles. */ #define __HAL_RCC_MSI_ENABLE() (*(__IO uint32_t *) CR_MSION_BB = ENABLE) #define __HAL_RCC_MSI_DISABLE() (*(__IO uint32_t *) CR_MSION_BB = DISABLE) /** @brief macro to adjust the Internal High Speed oscillator (HSI) calibration value. * @note The calibration is used to compensate for the variations in voltage * and temperature that influence the frequency of the internal HSI RC. * @param _HSICALIBRATIONVALUE_: specifies the calibration trimming value. * (default is RCC_HSICALIBRATION_DEFAULT). * This parameter must be a number between 0 and 0x1F. */ #define __HAL_RCC_HSI_CALIBRATIONVALUE_ADJUST(_HSICALIBRATIONVALUE_) \ (MODIFY_REG(RCC->ICSCR, RCC_ICSCR_HSITRIM, (uint32_t)(_HSICALIBRATIONVALUE_) << POSITION_VAL(RCC_ICSCR_HSITRIM))) /** @brief macro to adjust the Internal Multi Speed oscillator (MSI) calibration value. * @note The calibration is used to compensate for the variations in voltage * and temperature that influence the frequency of the internal MSI RC. * @param _MSICALIBRATIONVALUE_: specifies the calibration trimming value. * (default is RCC_MSICALIBRATION_DEFAULT). * This parameter must be a number between 0 and 0x1F. */ #define __HAL_RCC_MSI_CALIBRATIONVALUE_ADJUST(_MSICALIBRATIONVALUE_) \ (MODIFY_REG(RCC->ICSCR, RCC_ICSCR_MSITRIM, (uint32_t)(_MSICALIBRATIONVALUE_) << POSITION_VAL(RCC_ICSCR_MSITRIM))) /* @brief Macro to configures the Internal Multi Speed oscillator (MSI) clock range. * @note After restart from Reset or wakeup from STANDBY, the MSI clock is * around 2.097 MHz. The MSI clock does not change after wake-up from * STOP mode. * @note The MSI clock range can be modified on the fly. * @param _MSIRANGEVALUE_: specifies the MSI Clock range. * This parameter must be one of the following values: * @arg RCC_MSIRANGE_0: MSI clock is around 65.536 KHz * @arg RCC_MSIRANGE_1: MSI clock is around 131.072 KHz * @arg RCC_MSIRANGE_2: MSI clock is around 262.144 KHz * @arg RCC_MSIRANGE_3: MSI clock is around 524.288 KHz * @arg RCC_MSIRANGE_4: MSI clock is around 1.048 MHz * @arg RCC_MSIRANGE_5: MSI clock is around 2.097 MHz (default after Reset or wake-up from STANDBY) * @arg RCC_MSIRANGE_6: MSI clock is around 4.194 MHz */ #define __HAL_RCC_MSI_RANGE_CONFIG(_MSIRANGEVALUE_) (MODIFY_REG(RCC->ICSCR, RCC_ICSCR_MSIRANGE, (uint32_t)(_MSIRANGEVALUE_))) /** @brief Macros to enable or disable the Internal Low Speed oscillator (LSI). * @note After enabling the LSI, the application software should wait on * LSIRDY flag to be set indicating that LSI clock is stable and can * be used to clock the IWDG and/or the RTC. * @note LSI can not be disabled if the IWDG is running. * @note When the LSI is stopped, LSIRDY flag goes low after 6 LSI oscillator * clock cycles. */ #define __HAL_RCC_LSI_ENABLE() (*(__IO uint32_t *) CSR_LSION_BB = ENABLE) #define __HAL_RCC_LSI_DISABLE() (*(__IO uint32_t *) CSR_LSION_BB = DISABLE) /** @brief Macros to enable or disable the Internal Low Speed oscillator (LSE). */ #define __HAL_RCC_LSE_CONFIG(__LSE_STATE__) \ do{ \ if ((__LSE_STATE__) == RCC_LSE_OFF) \ { \ *(__IO uint32_t *) CSR_LSEON_BB = DISABLE; \ *(__IO uint32_t *) CSR_LSEBYP_BB = DISABLE; \ } \ else if ((__LSE_STATE__) == RCC_LSE_ON) \ { \ *(__IO uint32_t *) CSR_LSEBYP_BB = DISABLE; \ *(__IO uint32_t *) CSR_LSEON_BB = ENABLE; \ } \ else \ { \ *(__IO uint32_t *) CSR_LSEON_BB = DISABLE; \ *(__IO uint32_t *) CSR_LSEBYP_BB = ENABLE; \ } \ }while(0) /** @brief Macros to enable or disable the the RTC clock. * @note These macros must be used only after the RTC clock source was selected. */ #define __HAL_RCC_RTC_ENABLE() (*(__IO uint32_t *) CSR_RTCEN_BB = ENABLE) #define __HAL_RCC_RTC_DISABLE() (*(__IO uint32_t *) CSR_RTCEN_BB = DISABLE) /** @brief Macros to force or release the Backup domain reset. * @note This function resets the RTC peripheral (including the backup registers) * and the RTC clock source selection in RCC_CSR register. * @note The BKPSRAM is not affected by this reset. */ #define __HAL_RCC_BACKUPRESET_FORCE() (*(__IO uint32_t *) CSR_RTCRST_BB = ENABLE) #define __HAL_RCC_BACKUPRESET_RELEASE() (*(__IO uint32_t *) CSR_RTCRST_BB = DISABLE) /** @brief Macro to configures the RTC clock (RTCCLK). * @note As the RTC clock configuration bits are in the Backup domain and write * access is denied to this domain after reset, you have to enable write * access using the Power Backup Access macro before to configure * the RTC clock source (to be done once after reset). * @note Once the RTC clock is configured it can't be changed unless the * Backup domain is reset using __HAL_RCC_BACKUPRESET_FORCE() macro, or by * a Power On Reset (POR). * @note RTC prescaler cannot be modified if HSE is enabled (HSEON = 1). * * @param __RTC_CLKSOURCE__: specifies the RTC clock source. * This parameter can be one of the following values: * @arg RCC_RTCCLKSOURCE_LSE: LSE selected as RTC clock * @arg RCC_RTCCLKSOURCE_LSI: LSI selected as RTC clock * @arg RCC_RTCCLKSOURCE_HSE_DIV2: HSE divided by 2 selected as RTC clock * @arg RCC_RTCCLKSOURCE_HSE_DIV4: HSE divided by 4 selected as RTC clock * @arg RCC_RTCCLKSOURCE_HSE_DIV8: HSE divided by 8 selected as RTC clock * @arg RCC_RTCCLKSOURCE_HSE_DIV16: HSE divided by 16 selected as RTC clock * @note If the LSE or LSI is used as RTC clock source, the RTC continues to * work in STOP and STANDBY modes, and can be used as wakeup source. * However, when the HSE clock is used as RTC clock source, the RTC * cannot be used in STOP and STANDBY modes. * @note The maximum input clock frequency for RTC is 1MHz (when using HSE as * RTC clock source). */ #define __HAL_RCC_RTC_CLKPRESCALER(__RTC_CLKSOURCE__) do { \ if(((__RTC_CLKSOURCE__) & RCC_CSR_RTCSEL_HSE) == RCC_CSR_RTCSEL_HSE) \ { \ MODIFY_REG(RCC->CR, RCC_CR_RTCPRE, ((__RTC_CLKSOURCE__) & RCC_CR_RTCPRE)); \ } \ } while (0) #define __HAL_RCC_RTC_CONFIG(__RTC_CLKSOURCE__) do { \ __HAL_RCC_RTC_CLKPRESCALER(__RTC_CLKSOURCE__); \ RCC->CSR |= ((__RTC_CLKSOURCE__) & RCC_CSR_RTCSEL); \ } while (0) /** @brief macros to get the RTC clock source. */ #define __HAL_RCC_GET_RTC_SOURCE() (READ_BIT(RCC->CSR, RCC_CSR_RTCSEL)) /** @brief Macros to enable or disable the main PLL. * @note After enabling the main PLL, the application software should wait on * PLLRDY flag to be set indicating that PLL clock is stable and can * be used as system clock source. * @note The main PLL can not be disabled if it is used as system clock source * @note The main PLL is disabled by hardware when entering STOP and STANDBY modes. */ #define __HAL_RCC_PLL_ENABLE() (*(__IO uint32_t *) CR_PLLON_BB = ENABLE) #define __HAL_RCC_PLL_DISABLE() (*(__IO uint32_t *) CR_PLLON_BB = DISABLE) /** @brief macros to configure the main PLL clock source, multiplication and division factors. * @note This function must be used only when the main PLL is disabled. * * @param __RCC_PLLSOURCE__: specifies the PLL entry clock source. * This parameter can be one of the following values: * @arg RCC_PLLSOURCE_HSI: HSI oscillator clock selected as PLL clock entry * @arg RCC_PLLSOURCE_HSE: HSE oscillator clock selected as PLL clock entry * @param __PLLMUL__: specifies the multiplication factor for PLL VCO output clock * This parameter can be one of the following values: * @arg RCC_PLL_MUL3: PLLVCO = PLL clock entry x 3 * @arg RCC_PLL_MUL4: PLLVCO = PLL clock entry x 4 * @arg RCC_PLL_MUL6: PLLVCO = PLL clock entry x 6 * @arg RCC_PLL_MUL8: PLLVCO = PLL clock entry x 8 * @arg RCC_PLL_MUL12: PLLVCO = PLL clock entry x 12 * @arg RCC_PLL_MUL16: PLLVCO = PLL clock entry x 16 * @arg RCC_PLL_MUL24: PLLVCO = PLL clock entry x 24 * @arg RCC_PLL_MUL32: PLLVCO = PLL clock entry x 32 * @arg RCC_PLL_MUL48: PLLVCO = PLL clock entry x 48 * @note The PLL VCO clock frequency must not exceed 96 MHz when the product is in * Range 1, 48 MHz when the product is in Range 2 and 24 MHz when the product is * in Range 3. * * @param __PLLDIV__: specifies the division factor for PLL VCO input clock * This parameter can be one of the following values: * @arg RCC_PLL_DIV2: PLL clock output = PLLVCO / 2 * @arg RCC_PLL_DIV3: PLL clock output = PLLVCO / 3 * @arg RCC_PLL_DIV4: PLL clock output = PLLVCO / 4 * */ #define __HAL_RCC_PLL_CONFIG(__RCC_PLLSOURCE__, __PLLMUL__, __PLLDIV__)\ MODIFY_REG(RCC->CFGR, (RCC_CFGR_PLLSRC|RCC_CFGR_PLLMUL|RCC_CFGR_PLLDIV),((__RCC_PLLSOURCE__) | (__PLLMUL__) | (__PLLDIV__))) /** @brief Macro to get the clock source used as system clock. * @retval The clock source used as system clock. The returned value can be one * of the following: * @arg RCC_CFGR_SWS_MSI: MSI used as system clock * @arg RCC_CFGR_SWS_HSI: HSI used as system clock * @arg RCC_CFGR_SWS_HSE: HSE used as system clock * @arg RCC_CFGR_SWS_PLL: PLL used as system clock */ #define __HAL_RCC_GET_SYSCLK_SOURCE() ((uint32_t)(READ_BIT(RCC->CFGR,RCC_CFGR_SWS))) /** @brief macros to manage the specified RCC Flags and interrupts. */ /** @brief Enable RCC interrupt (Perform Byte access to RCC_CIR[14:8] bits to enable * the selected interrupts.). * @param __INTERRUPT__: specifies the RCC interrupt sources to be enabled. * This parameter can be any combination of the following values: * @arg RCC_IT_LSIRDY: LSI ready interrupt * @arg RCC_IT_LSERDY: LSE ready interrupt * @arg RCC_IT_HSIRDY: HSI ready interrupt * @arg RCC_IT_HSERDY: HSE ready interrupt * @arg RCC_IT_PLLRDY: main PLL ready interrupt * @arg RCC_IT_MSIRDY: MSI ready interrupt * @arg RCC_IT_LSECSS: LSE CSS interrupt (not available for STM32L100xB || STM32L151xB || STM32L152xB device) */ #define __HAL_RCC_ENABLE_IT(__INTERRUPT__) (*(__IO uint8_t *) CIR_BYTE1_ADDRESS |= (__INTERRUPT__)) /** @brief Disable RCC interrupt (Perform Byte access to RCC_CIR[14:8] bits to disable * the selected interrupts). * @param __INTERRUPT__: specifies the RCC interrupt sources to be disabled. * This parameter can be any combination of the following values: * @arg RCC_IT_LSIRDY: LSI ready interrupt * @arg RCC_IT_LSERDY: LSE ready interrupt * @arg RCC_IT_HSIRDY: HSI ready interrupt * @arg RCC_IT_HSERDY: HSE ready interrupt * @arg RCC_IT_PLLRDY: main PLL ready interrupt * @arg RCC_IT_MSIRDY: MSI ready interrupt * @arg RCC_IT_LSECSS: LSE CSS interrupt (not available for STM32L100xB || STM32L151xB || STM32L152xB device) */ #define __HAL_RCC_DISABLE_IT(__INTERRUPT__) (*(__IO uint8_t *) CIR_BYTE1_ADDRESS &= ~(__INTERRUPT__)) /** @brief Clear the RCC's interrupt pending bits ( Perform Byte access to RCC_CIR[23:16] * bits to clear the selected interrupt pending bits. * @param __INTERRUPT__: specifies the interrupt pending bit to clear. * This parameter can be any combination of the following values: * @arg RCC_IT_LSIRDY: LSI ready interrupt. * @arg RCC_IT_LSERDY: LSE ready interrupt. * @arg RCC_IT_HSIRDY: HSI ready interrupt. * @arg RCC_IT_HSERDY: HSE ready interrupt. * @arg RCC_IT_PLLRDY: Main PLL ready interrupt. * @arg RCC_IT_MSIRDY: MSI ready interrupt. * @arg RCC_IT_LSECSS: LSE CSS interrupt (not available for STM32L100xB || STM32L151xB || STM32L152xB device) * @arg RCC_IT_CSS: Clock Security System interrupt */ #define __HAL_RCC_CLEAR_IT(__INTERRUPT__) (*(__IO uint8_t *) CIR_BYTE2_ADDRESS = (__INTERRUPT__)) /** @brief Check the RCC's interrupt has occurred or not. * @param __INTERRUPT__: specifies the RCC interrupt source to check. * This parameter can be one of the following values: * @arg RCC_IT_LSIRDY: LSI ready interrupt. * @arg RCC_IT_LSERDY: LSE ready interrupt. * @arg RCC_IT_HSIRDY: HSI ready interrupt. * @arg RCC_IT_HSERDY: HSE ready interrupt. * @arg RCC_IT_PLLRDY: Main PLL ready interrupt. * @arg RCC_IT_MSIRDY: MSI ready interrupt. * @arg RCC_IT_LSECSS: LSE CSS interrupt (not available for STM32L100xB || STM32L151xB || STM32L152xB device) * @arg RCC_IT_CSS: Clock Security System interrupt * @retval The new state of __INTERRUPT__ (TRUE or FALSE). */ #define __HAL_RCC_GET_IT(__INTERRUPT__) ((RCC->CIR & (__INTERRUPT__)) == (__INTERRUPT__)) /** @brief Set RMVF bit to clear the reset flags: RCC_FLAG_PINRST, RCC_FLAG_PORRST, RCC_FLAG_SFTRST, * RCC_FLAG_IWDGRST, RCC_FLAG_WWDGRST, RCC_FLAG_LPWRRST */ #define __HAL_RCC_CLEAR_RESET_FLAGS() (RCC->CSR |= RCC_CSR_RMVF) /** @brief Check RCC flag is set or not. * @param __FLAG__: specifies the flag to check. * This parameter can be one of the following values: * @arg RCC_FLAG_HSIRDY: HSI oscillator clock ready. * @arg RCC_FLAG_MSIRDY: MSI oscillator clock ready. * @arg RCC_FLAG_HSERDY: HSE oscillator clock ready. * @arg RCC_FLAG_PLLRDY: Main PLL clock ready. * @arg RCC_FLAG_LSERDY: LSE oscillator clock ready. * @arg RCC_FLAG_LSECSS: CSS on LSE failure Detection (*) * @arg RCC_FLAG_LSIRDY: LSI oscillator clock ready. * @arg RCC_FLAG_BORRST: POR/PDR or BOR reset. * @arg RCC_FLAG_PINRST: Pin reset. * @arg RCC_FLAG_PORRST: POR/PDR reset. * @arg RCC_FLAG_SFTRST: Software reset. * @arg RCC_FLAG_IWDGRST: Independent Watchdog reset. * @arg RCC_FLAG_WWDGRST: Window Watchdog reset. * @arg RCC_FLAG_LPWRRST: Low Power reset. * @note (*) This bit is available in high and medium+ density devices only. * @retval The new state of __FLAG__ (TRUE or FALSE). */ #define __HAL_RCC_GET_FLAG(__FLAG__) (((((__FLAG__) >> 5) == CR_REG_INDEX)? RCC->CR :RCC->CSR) & ((uint32_t)1 << ((__FLAG__) & RCC_FLAG_MASK))) /** @brief Get oscillator clock selected as PLL input clock * @retval The clock source used for PLL entry. The returned value can be one * of the following: * @arg RCC_PLLSOURCE_HSI: HSI oscillator clock selected as PLL input clock * @arg RCC_PLLSOURCE_HSE: HSE oscillator clock selected as PLL input clock */ #define __HAL_RCC_GET_PLL_OSCSOURCE() ((RCC->CFGR & RCC_CFGR_PLLSRC)) /** * @} */ /* Include RCC HAL Extension module */ #include "stm32l1xx_hal_rcc_ex.h" /* Exported functions --------------------------------------------------------*/ /** @addtogroup RCC_Private_Functions * @{ */ /** @addtogroup RCC_Exported_Functions_Group1 * @{ */ /* Initialization and de-initialization functions ******************************/ void HAL_RCC_DeInit(void); HAL_StatusTypeDef HAL_RCC_OscConfig(RCC_OscInitTypeDef *RCC_OscInitStruct); HAL_StatusTypeDef HAL_RCC_ClockConfig(RCC_ClkInitTypeDef *RCC_ClkInitStruct, uint32_t FLatency); /** * @} */ /** @addtogroup RCC_Exported_Functions_Group2 * @{ */ /* Peripheral Control functions ************************************************/ void HAL_RCC_MCOConfig(uint32_t RCC_MCOx, uint32_t RCC_MCOSource, uint32_t RCC_MCODiv); void HAL_RCC_EnableCSS(void); void HAL_RCC_DisableCSS(void); uint32_t HAL_RCC_GetSysClockFreq(void); uint32_t HAL_RCC_GetHCLKFreq(void); uint32_t HAL_RCC_GetPCLK1Freq(void); uint32_t HAL_RCC_GetPCLK2Freq(void); void HAL_RCC_GetOscConfig(RCC_OscInitTypeDef *RCC_OscInitStruct); void HAL_RCC_GetClockConfig(RCC_ClkInitTypeDef *RCC_ClkInitStruct, uint32_t *pFLatency); /* CSS NMI IRQ handler */ void HAL_RCC_NMI_IRQHandler(void); /* User Callbacks in non blocking mode (IT mode) */ void HAL_RCC_CCSCallback(void); /** * @} */ /** * @} */ /** * @} */ /** * @} */ #ifdef __cplusplus } #endif #endif /* __STM32L1xx_HAL_RCC_H */ /************************ (C) COPYRIGHT STMicroelectronics *****END OF FILE****/ ================================================ FILE: Zelig/mbed/TARGET_NUCLEO_L152RE/stm32l1xx_hal_rcc_ex.h ================================================ /** ****************************************************************************** * @file stm32l1xx_hal_rcc_ex.h * @author MCD Application Team * @version V1.0.0 * @date 5-September-2014 * @brief Header file of RCC HAL Extension module. ****************************************************************************** * @attention * *

© COPYRIGHT(c) 2014 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. * ****************************************************************************** */ /* Define to prevent recursive inclusion -------------------------------------*/ #ifndef __STM32L1xx_HAL_RCC_EX_H #define __STM32L1xx_HAL_RCC_EX_H #ifdef __cplusplus extern "C" { #endif /* Includes ------------------------------------------------------------------*/ #include "stm32l1xx_hal_def.h" /** @addtogroup STM32L1xx_HAL_Driver * @{ */ /** @addtogroup RCCEx * @{ */ /* Exported types ------------------------------------------------------------*/ /** @defgroup RCCEx_Exported_Types RCCEx Exported Types * @{ */ /** * @brief RCC extended clocks structure definition */ typedef struct { uint32_t PeriphClockSelection; /*!< The Extended Clock to be configured. This parameter can be a value of @ref RCCEx_Periph_Clock_Selection */ uint32_t RTCClockSelection; /*!< specifies the RTC clock source. This parameter can be a value of @ref RCC_RTC_LCD_Clock_Source */ #if defined (STM32L100xB) || defined (STM32L100xBA) || defined (STM32L100xC) ||\ defined(STM32L152xB) || defined(STM32L152xBA) || defined(STM32L152xC) || \ defined(STM32L162xC) || defined(STM32L152xCA) || defined(STM32L152xD) || \ defined(STM32L162xCA) || defined(STM32L162xD) || defined(STM32L152xE) || \ defined(STM32L162xE) uint32_t LCDClockSelection; /*!< specifies the LCD clock source. This parameter can be a value of @ref RCC_RTC_LCD_Clock_Source */ #endif /* STM32L100xB || STM32L152xBA || ... || STM32L152xE || STM32L162xE */ } RCC_PeriphCLKInitTypeDef; /** * @} */ /* Exported constants --------------------------------------------------------*/ /** @defgroup RCCEx_Exported_Constants RCCEx Exported Constants * @{ */ /** @defgroup RCCEx_Periph_Clock_Selection RCCEx Periph Clock Selection * @{ */ #define RCC_PERIPHCLK_RTC ((uint32_t)0x00000001) #if defined (STM32L100xB) || defined (STM32L100xBA) || defined (STM32L100xC) ||\ defined(STM32L152xB) || defined(STM32L152xBA) || defined(STM32L152xC) || \ defined(STM32L162xC) || defined(STM32L152xCA) || defined(STM32L152xD) || \ defined(STM32L162xCA) || defined(STM32L162xD) || defined(STM32L152xE) || \ defined(STM32L162xE) #define RCC_PERIPHCLK_LCD ((uint32_t)0x00000002) #endif /* STM32L100xB || STM32L152xBA || ... || STM32L152xE || STM32L162xE */ #if defined (STM32L100xB) || defined (STM32L100xBA) || defined (STM32L100xC) ||\ defined(STM32L152xB) || defined(STM32L152xBA) || defined(STM32L152xC) || \ defined(STM32L162xC) || defined(STM32L152xCA) || defined(STM32L152xD) || \ defined(STM32L162xCA) || defined(STM32L162xD) || defined(STM32L152xE) || \ defined(STM32L162xE) #define IS_RCC_PERIPHCLOCK(__CLK__) ((RCC_PERIPHCLK_RTC <= (__CLK__)) && ((__CLK__) <= RCC_PERIPHCLK_LCD)) #else /* Not LCD LINE */ #define IS_RCC_PERIPHCLOCK(__CLK__) ((__CLK__) == RCC_PERIPHCLK_RTC) #endif /* STM32L100xB || STM32L152xBA || ... || STM32L152xE || STM32L162xE */ /** * @} */ #if defined(STM32L100xBA) || defined (STM32L151xBA) || defined (STM32L152xBA) || \ defined(STM32L100xC) || defined (STM32L151xC) || defined (STM32L152xC) || defined (STM32L162xC) || \ defined(STM32L151xCA) || defined (STM32L151xD) || defined (STM32L152xCA) || defined (STM32L152xD) || defined (STM32L162xCA) || defined (STM32L162xD) || \ defined(STM32L151xE) || defined (STM32L152xE) || defined (STM32L162xE) /* Alias word address of LSECSSON bit */ #define LSECSSON_BITNUMBER POSITION_VAL(RCC_CSR_LSECSSON) #define CSR_LSECSSON_BB ((uint32_t)(PERIPH_BB_BASE + (RCC_CSR_OFFSET_BB * 32) + (LSECSSON_BITNUMBER * 4))) #endif /* STM32L100xBA || STM32L151xBA || STM32L152xBA || STM32L100xC || STM32L151xC || STM32L152xC || STM32L162xC || STM32L151xCA || STM32L151xD || STM32L152xCA || STM32L152xD || STM32L162xCA || STM32L162xD || STM32L151xE || STM32L152xE || STM32L162xE*/ /** * @} */ /* Exported macro ------------------------------------------------------------*/ /** @defgroup RCCEx_Exported_Macros RCCEx Exported Macros * @{ */ /** @defgroup RCCEx_Peripheral_Clock_Enable_Disable RCCEx_Peripheral_Clock_Enable_Disable * @brief Enables or disables the AHB1 peripheral clock. * @note After reset, the peripheral clock (used for registers read/write access) * is disabled and the application software has to enable this clock before * using it. * @{ */ #if defined (STM32L151xB) || defined (STM32L152xB) || \ defined (STM32L151xBA) || defined (STM32L152xBA) || \ defined (STM32L151xC) || defined (STM32L152xC) || defined (STM32L162xC) || \ defined(STM32L151xCA) || defined (STM32L151xD) || defined (STM32L152xCA) || defined (STM32L152xD) || defined (STM32L162xCA) || defined (STM32L162xD) || \ defined(STM32L151xE) || defined (STM32L152xE) || defined (STM32L162xE) #define __GPIOE_CLK_ENABLE() (RCC->AHBENR |= (RCC_AHBENR_GPIOEEN)) #define __GPIOE_CLK_DISABLE() (RCC->AHBENR &= ~(RCC_AHBENR_GPIOEEN)) #endif /* STM32L151xB || STM32L152xB || ... || STM32L151xCA || STM32L151xD || STM32L152xCA || STM32L152xD || STM32L162xCA || STM32L162xD || STM32L151xE || STM32L152xE || STM32L162xE */ #if defined(STM32L151xCA) || defined (STM32L151xD) || defined (STM32L152xCA) || defined (STM32L152xD) || defined (STM32L162xCA) || defined (STM32L162xD) || \ defined(STM32L151xE) || defined (STM32L152xE) || defined (STM32L162xE) #define __GPIOF_CLK_ENABLE() (RCC->AHBENR |= (RCC_AHBENR_GPIOFEN)) #define __GPIOG_CLK_ENABLE() (RCC->AHBENR |= (RCC_AHBENR_GPIOGEN)) #define __GPIOF_CLK_DISABLE() (RCC->AHBENR &= ~(RCC_AHBENR_GPIOFEN)) #define __GPIOG_CLK_DISABLE() (RCC->AHBENR &= ~(RCC_AHBENR_GPIOGEN)) #endif /* STM32L151xCA || STM32L151xD || STM32L152xCA || STM32L152xD || STM32L162xCA || STM32L162xD || STM32L151xE || STM32L152xE || STM32L162xE */ #if defined(STM32L100xC) || defined (STM32L151xC) || defined (STM32L152xC) || defined (STM32L162xC) || \ defined(STM32L151xCA) || defined (STM32L151xD) || defined (STM32L152xCA) || defined (STM32L152xD) || defined (STM32L162xCA) || defined (STM32L162xD) || \ defined(STM32L151xE) || defined (STM32L152xE) || defined (STM32L162xE) #define __DMA2_CLK_ENABLE() (RCC->AHBENR |= (RCC_AHBENR_DMA2EN)) #define __DMA2_CLK_DISABLE() (RCC->AHBENR &= ~(RCC_AHBENR_DMA2EN)) #endif /* STM32L100xC || STM32L151xC || STM32L152xC || STM32L162xC || STM32L151xCA || STM32L151xD || STM32L152xCA || STM32L152xD || STM32L162xCA || STM32L162xD || STM32L151xE || STM32L152xE || STM32L162xE */ #if defined(STM32L162xC) || defined(STM32L162xCA) || defined(STM32L162xD) || defined(STM32L162xE) #define __CRYP_CLK_ENABLE() (RCC->AHBENR |= (RCC_AHBENR_AESEN)) #define __CRYP_CLK_DISABLE() (RCC->AHBENR &= ~(RCC_AHBENR_AESEN)) #endif /* STM32L162xC || STM32L162xCA || STM32L162xD || STM32L162xE */ #if defined (STM32L151xD) || defined (STM32L152xD) || defined (STM32L162xD) #define __FSMC_CLK_ENABLE() (RCC->AHBENR |= (RCC_AHBENR_FSMCEN)) #define __FSMC_CLK_DISABLE() (RCC->AHBENR &= ~(RCC_AHBENR_FSMCEN)) #endif /* STM32L151xD || STM32L152xD || STM32L162xD */ #if defined (STM32L100xB) || defined (STM32L100xBA) || defined (STM32L100xC) ||\ defined(STM32L152xB) || defined(STM32L152xBA) || defined(STM32L152xC) || \ defined(STM32L162xC) || defined(STM32L152xCA) || defined(STM32L152xD) || \ defined(STM32L162xCA) || defined(STM32L162xD) || defined(STM32L152xE) || \ defined(STM32L162xE) #define __LCD_CLK_ENABLE() (RCC->APB1ENR |= (RCC_APB1ENR_LCDEN)) #define __LCD_CLK_DISABLE() (RCC->APB1ENR &= ~(RCC_APB1ENR_LCDEN)) #endif /* STM32L100xB || STM32L152xBA || ... || STM32L152xE || STM32L162xE */ /** @brief Enables or disables the Low Speed APB (APB1) peripheral clock. * @note After reset, the peripheral clock (used for registers read/write access) * is disabled and the application software has to enable this clock before * using it. */ #if defined (STM32L151xC) || defined (STM32L152xC) || defined (STM32L162xC) || \ defined(STM32L151xCA) || defined (STM32L151xD) || defined (STM32L152xCA) || defined (STM32L152xD) || defined (STM32L162xCA) || defined (STM32L162xD) || \ defined(STM32L151xE) || defined (STM32L152xE) || defined (STM32L162xE) #define __TIM5_CLK_ENABLE() (RCC->APB1ENR |= (RCC_APB1ENR_TIM5EN)) #define __TIM5_CLK_DISABLE() (RCC->APB1ENR &= ~(RCC_APB1ENR_TIM5EN)) #endif /* STM32L151xC || STM32L152xC || STM32L162xC || STM32L151xCA || STM32L151xD || STM32L152xCA || STM32L152xD || STM32L162xCA || STM32L162xD || STM32L151xE || STM32L152xE || STM32L162xE */ #if defined(STM32L100xC) || defined (STM32L151xC) || defined (STM32L152xC) || defined (STM32L162xC) || \ defined(STM32L151xCA) || defined (STM32L151xD) || defined (STM32L152xCA) || defined (STM32L152xD) || defined (STM32L162xCA) || defined (STM32L162xD) || \ defined(STM32L151xE) || defined (STM32L152xE) || defined (STM32L162xE) #define __SPI3_CLK_ENABLE() (RCC->APB1ENR |= (RCC_APB1ENR_SPI3EN)) #define __SPI3_CLK_DISABLE() (RCC->APB1ENR &= ~(RCC_APB1ENR_SPI3EN)) #endif /* STM32L100xC || STM32L151xC || STM32L152xC || STM32L162xC || STM32L151xCA || STM32L151xD || STM32L152xCA || STM32L152xD || STM32L162xCA || STM32L162xD || STM32L151xE || STM32L152xE || STM32L162xE */ #if defined (STM32L151xD) || defined (STM32L152xD) || defined (STM32L162xD) || \ defined(STM32L151xE) || defined (STM32L152xE) || defined (STM32L162xE) #define __UART4_CLK_ENABLE() (RCC->APB1ENR |= (RCC_APB1ENR_UART4EN)) #define __UART5_CLK_ENABLE() (RCC->APB1ENR |= (RCC_APB1ENR_UART5EN)) #define __UART4_CLK_DISABLE() (RCC->APB1ENR &= ~(RCC_APB1ENR_UART4EN)) #define __UART5_CLK_DISABLE() (RCC->APB1ENR &= ~(RCC_APB1ENR_UART5EN)) #endif /* STM32L151xD || STM32L152xD || STM32L162xD || STM32L151xE || STM32L152xE || STM32L162xE */ #if defined (STM32L151xCA) || defined (STM32L151xD) || defined (STM32L152xCA) || defined (STM32L152xD) || defined (STM32L162xCA) || defined (STM32L162xD) || defined (STM32L151xE) || defined (STM32L152xE) || defined (STM32L162xE) || defined (STM32L162xC) || defined (STM32L152xC) || defined (STM32L151xC) #define __OPAMP_CLK_ENABLE() __COMP_CLK_ENABLE() /* Peripherals COMP and OPAMP share the same clock domain */ #define __OPAMP_CLK_DISABLE() __COMP_CLK_DISABLE() /* Peripherals COMP and OPAMP share the same clock domain */ #endif /* STM32L151xCA || STM32L151xD || STM32L152xCA || STM32L152xD || STM32L162xCA || STM32L162xD || STM32L151xE || STM32L152xE || STM32L162xE || STM32L162xC || STM32L152xC || STM32L151xC */ /** @brief Enables or disables the High Speed APB (APB2) peripheral clock. * @note After reset, the peripheral clock (used for registers read/write access) * is disabled and the application software has to enable this clock before * using it. */ #if defined (STM32L151xD) || defined (STM32L152xD) || defined (STM32L162xD) #define __SDIO_CLK_ENABLE() (RCC->APB2ENR |= (RCC_APB2ENR_SDIOEN)) #define __SDIO_CLK_DISABLE() (RCC->APB2ENR &= ~(RCC_APB2ENR_SDIOEN)) #endif /* STM32L151xD || STM32L152xD || STM32L162xD */ /** * @} */ /** @defgroup RCCEx_Force_Release_Peripheral_Reset RCCEx Force Release Peripheral Reset * @brief Forces or releases AHB peripheral reset. * @{ */ #if defined (STM32L151xB) || defined (STM32L152xB) || \ defined (STM32L151xBA) || defined (STM32L152xBA) || \ defined (STM32L151xC) || defined (STM32L152xC) || defined (STM32L162xC) || \ defined(STM32L151xCA) || defined (STM32L151xD) || defined (STM32L152xCA) || defined (STM32L152xD) || defined (STM32L162xCA) || defined (STM32L162xD) || \ defined(STM32L151xE) || defined (STM32L152xE) || defined (STM32L162xE) #define __GPIOE_FORCE_RESET() (RCC->AHBRSTR |= (RCC_AHBRSTR_GPIOERST)) #define __GPIOE_RELEASE_RESET() (RCC->AHBRSTR &= ~(RCC_AHBRSTR_GPIOERST)) #endif /* STM32L151xB || STM32L152xB || ... || STM32L151xCA || STM32L151xD || STM32L152xCA || STM32L152xD || STM32L162xCA || STM32L162xD || STM32L151xE || STM32L152xE || STM32L162xE */ #if defined(STM32L151xCA) || defined (STM32L151xD) || defined (STM32L152xCA) || defined (STM32L152xD) || defined (STM32L162xCA) || defined (STM32L162xD) || \ defined(STM32L151xE) || defined (STM32L152xE) || defined (STM32L162xE) #define __GPIOF_FORCE_RESET() (RCC->AHBRSTR |= (RCC_AHBRSTR_GPIOFRST)) #define __GPIOG_FORCE_RESET() (RCC->AHBRSTR |= (RCC_AHBRSTR_GPIOGRST)) #define __GPIOF_RELEASE_RESET() (RCC->AHBRSTR &= ~(RCC_AHBRSTR_GPIOFRST)) #define __GPIOG_RELEASE_RESET() (RCC->AHBRSTR &= ~(RCC_AHBRSTR_GPIOGRST)) #endif /* STM32L151xCA || STM32L151xD || STM32L152xCA || STM32L152xD || STM32L162xCA || STM32L162xD || STM32L151xE || STM32L152xE || STM32L162xE */ #if defined(STM32L100xC) || defined (STM32L151xC) || defined (STM32L152xC) || defined (STM32L162xC) || \ defined(STM32L151xCA) || defined (STM32L151xD) || defined (STM32L152xCA) || defined (STM32L152xD) || defined (STM32L162xCA) || defined (STM32L162xD) || \ defined(STM32L151xE) || defined (STM32L152xE) || defined (STM32L162xE) #define __DMA2_FORCE_RESET() (RCC->AHBRSTR |= (RCC_AHBRSTR_DMA2RST)) #define __DMA2_RELEASE_RESET() (RCC->AHBRSTR &= ~(RCC_AHBRSTR_DMA2RST)) #endif /* STM32L100xC || STM32L151xC || STM32L152xC || STM32L162xC || STM32L151xCA || STM32L151xD || STM32L152xCA || STM32L152xD || STM32L162xCA || STM32L162xD || STM32L151xE || STM32L152xE || STM32L162xE */ #if defined(STM32L162xC) || defined(STM32L162xCA) || defined(STM32L162xD) || defined(STM32L162xE) #define __CRYP_FORCE_RESET() (RCC->AHBRSTR |= (RCC_AHBRSTR_AESRST)) #define __CRYP_RELEASE_RESET() (RCC->AHBRSTR &= ~(RCC_AHBRSTR_AESRST)) #endif /* STM32L162xC || STM32L162xCA || STM32L162xD || STM32L162xE */ #if defined (STM32L151xD) || defined (STM32L152xD) || defined (STM32L162xD) #define __FSMC_FORCE_RESET() (RCC->AHBRSTR |= (RCC_AHBRSTR_FSMCRST)) #define __FSMC_RELEASE_RESET() (RCC->AHBRSTR &= ~(RCC_AHBRSTR_FSMCRST)) #endif /* STM32L151xD || STM32L152xD || STM32L162xD */ #if defined (STM32L100xB) || defined (STM32L100xBA) || defined (STM32L100xC) ||\ defined(STM32L152xB) || defined(STM32L152xBA) || defined(STM32L152xC) || \ defined(STM32L162xC) || defined(STM32L152xCA) || defined(STM32L152xD) || \ defined(STM32L162xCA) || defined(STM32L162xD) || defined(STM32L152xE) || \ defined(STM32L162xE) #define __LCD_FORCE_RESET() (RCC->APB1RSTR |= (RCC_APB1RSTR_LCDRST)) #define __LCD_RELEASE_RESET() (RCC->APB1RSTR &= ~(RCC_APB1RSTR_LCDRST)) #endif /* STM32L100xB || STM32L152xBA || ... || STM32L152xE || STM32L162xE */ /** @brief Forces or releases APB1 peripheral reset. */ #if defined (STM32L151xC) || defined (STM32L152xC) || defined (STM32L162xC) || \ defined(STM32L151xCA) || defined (STM32L151xD) || defined (STM32L152xCA) || defined (STM32L152xD) || defined (STM32L162xCA) || defined (STM32L162xD) || \ defined(STM32L151xE) || defined (STM32L152xE) || defined (STM32L162xE) #define __TIM5_FORCE_RESET() (RCC->APB1RSTR |= (RCC_APB1RSTR_TIM5RST)) #define __TIM5_RELEASE_RESET() (RCC->APB1RSTR &= ~(RCC_APB1RSTR_TIM5RST)) #endif /* STM32L151xC || STM32L152xC || STM32L162xC || STM32L151xCA || STM32L151xD || STM32L152xCA || STM32L152xD || STM32L162xCA || STM32L162xD || STM32L151xE || STM32L152xE || STM32L162xE */ #if defined(STM32L100xC) || defined (STM32L151xC) || defined (STM32L152xC) || defined (STM32L162xC) || \ defined(STM32L151xCA) || defined (STM32L151xD) || defined (STM32L152xCA) || defined (STM32L152xD) || defined (STM32L162xCA) || defined (STM32L162xD) || \ defined(STM32L151xE) || defined (STM32L152xE) || defined (STM32L162xE) #define __SPI3_FORCE_RESET() (RCC->APB1RSTR |= (RCC_APB1RSTR_SPI3RST)) #define __SPI3_RELEASE_RESET() (RCC->APB1RSTR &= ~(RCC_APB1RSTR_SPI3RST)) #endif /* STM32L100xC || STM32L151xC || STM32L152xC || STM32L162xC || STM32L151xCA || STM32L151xD || STM32L152xCA || STM32L152xD || STM32L162xCA || STM32L162xD || STM32L151xE || STM32L152xE || STM32L162xE */ #if defined (STM32L151xD) || defined (STM32L152xD) || defined (STM32L162xD) || \ defined(STM32L151xE) || defined (STM32L152xE) || defined (STM32L162xE) #define __UART4_FORCE_RESET() (RCC->APB1RSTR |= (RCC_APB1RSTR_UART4RST)) #define __UART5_FORCE_RESET() (RCC->APB1RSTR |= (RCC_APB1RSTR_UART5RST)) #define __UART4_RELEASE_RESET() (RCC->APB1RSTR &= ~(RCC_APB1RSTR_UART4RST)) #define __UART5_RELEASE_RESET() (RCC->APB1RSTR &= ~(RCC_APB1RSTR_UART5RST)) #endif /* STM32L151xD || STM32L152xD || STM32L162xD || STM32L151xE || STM32L152xE || STM32L162xE */ #if defined (STM32L151xCA) || defined (STM32L151xD) || defined (STM32L152xCA) || defined (STM32L152xD) || defined (STM32L162xCA) || defined (STM32L162xD) || defined (STM32L151xE) || defined (STM32L152xE) || defined (STM32L162xE) || defined (STM32L162xC) || defined (STM32L152xC) || defined (STM32L151xC) #define __OPAMP_FORCE_RESET() __COMP_FORCE_RESET() /* Peripherals COMP and OPAMP share the same clock domain */ #define __OPAMP_RELEASE_RESET() __COMP_RELEASE_RESET() /* Peripherals COMP and OPAMP share the same clock domain */ #endif /* STM32L151xCA || STM32L151xD || STM32L152xCA || STM32L152xD || STM32L162xCA || STM32L162xD || STM32L151xE || STM32L152xE || STM32L162xE || STM32L162xC || STM32L152xC || STM32L151xC */ /** @brief Forces or releases APB2 peripheral reset. */ #if defined (STM32L151xD) || defined (STM32L152xD) || defined (STM32L162xD) #define __SDIO_FORCE_RESET() (RCC->APB2RSTR |= (RCC_APB2RSTR_SDIORST)) #define __SDIO_RELEASE_RESET() (RCC->APB2RSTR &= ~(RCC_APB2RSTR_SDIORST)) #endif /* STM32L151xD || STM32L152xD || STM32L162xD */ /** * @} */ /** @defgroup RCCEx_Peripheral_Clock_Sleep_Enable_Disable RCCEx Peripheral Clock Sleep Enable Disable * @brief Enables or disables the AHB1 peripheral clock during Low Power (Sleep) mode. * @note Peripheral clock gating in SLEEP mode can be used to further reduce * power consumption. * @note After wakeup from SLEEP mode, the peripheral clock is enabled again. * @note By default, all peripheral clocks are enabled during SLEEP mode. * @{ */ #if defined (STM32L151xB) || defined (STM32L152xB) || \ defined (STM32L151xBA) || defined (STM32L152xBA) || \ defined (STM32L151xC) || defined (STM32L152xC) || defined (STM32L162xC) || \ defined(STM32L151xCA) || defined (STM32L151xD) || defined (STM32L152xCA) || defined (STM32L152xD) || defined (STM32L162xCA) || defined (STM32L162xD) || \ defined(STM32L151xE) || defined (STM32L152xE) || defined (STM32L162xE) #define __GPIOE_CLK_SLEEP_ENABLE() (RCC->AHBLPENR |= (RCC_AHBLPENR_GPIOELPEN)) #define __GPIOE_CLK_SLEEP_DISABLE() (RCC->AHBLPENR &= ~(RCC_AHBLPENR_GPIOELPEN)) #endif /* STM32L151xB || STM32L152xB || ... || STM32L151xCA || STM32L151xD || STM32L152xCA || STM32L152xD || STM32L162xCA || STM32L162xD || STM32L151xE || STM32L152xE || STM32L162xE */ #if defined(STM32L151xCA) || defined (STM32L151xD) || defined (STM32L152xCA) || defined (STM32L152xD) || defined (STM32L162xCA) || defined (STM32L162xD) || \ defined(STM32L151xE) || defined (STM32L152xE) || defined (STM32L162xE) #define __GPIOF_CLK_SLEEP_ENABLE() (RCC->AHBLPENR |= (RCC_AHBLPENR_GPIOFLPEN)) #define __GPIOG_CLK_SLEEP_ENABLE() (RCC->AHBLPENR |= (RCC_AHBLPENR_GPIOGLPEN)) #define __GPIOF_CLK_SLEEP_DISABLE() (RCC->AHBLPENR &= ~(RCC_AHBLPENR_GPIOFLPEN)) #define __GPIOG_CLK_SLEEP_DISABLE() (RCC->AHBLPENR &= ~(RCC_AHBLPENR_GPIOGLPEN)) #endif /* STM32L151xCA || STM32L151xD || STM32L152xCA || STM32L152xD || STM32L162xCA || STM32L162xD || STM32L151xE || STM32L152xE || STM32L162xE */ #if defined(STM32L100xC) || defined (STM32L151xC) || defined (STM32L152xC) || defined (STM32L162xC) || \ defined(STM32L151xCA) || defined (STM32L151xD) || defined (STM32L152xCA) || defined (STM32L152xD) || defined (STM32L162xCA) || defined (STM32L162xD) || \ defined(STM32L151xE) || defined (STM32L152xE) || defined (STM32L162xE) #define __DMA2_CLK_SLEEP_ENABLE() (RCC->AHBLPENR |= (RCC_AHBLPENR_DMA2LPEN)) #define __DMA2_CLK_SLEEP_DISABLE() (RCC->AHBLPENR &= ~(RCC_AHBLPENR_DMA2LPEN)) #endif /* STM32L100xC || STM32L151xC || STM32L152xC || STM32L162xC || STM32L151xCA || STM32L151xD || STM32L152xCA || STM32L152xD || STM32L162xCA || STM32L162xD || STM32L151xE || STM32L152xE || STM32L162xE */ #if defined(STM32L162xC) || defined(STM32L162xCA) || defined(STM32L162xD) || defined(STM32L162xE) #define __CRYP_CLK_SLEEP_ENABLE() (RCC->AHBLPENR |= (RCC_AHBLPENR_AESLPEN)) #define __CRYP_CLK_SLEEP_DISABLE() (RCC->AHBLPENR &= ~(RCC_AHBLPENR_AESLPEN)) #endif /* STM32L162xC || STM32L162xCA || STM32L162xD || STM32L162xE */ #if defined (STM32L151xD) || defined (STM32L152xD) || defined (STM32L162xD) #define __FSMC_CLK_SLEEP_ENABLE() (RCC->AHBLPENR |= (RCC_AHBLPENR_FSMCLPEN)) #define __FSMC_CLK_SLEEP_DISABLE() (RCC->AHBLPENR &= ~(RCC_AHBLPENR_FSMCLPEN)) #endif /* STM32L151xD || STM32L152xD || STM32L162xD */ #if defined (STM32L100xB) || defined (STM32L100xBA) || defined (STM32L100xC) ||\ defined(STM32L152xB) || defined(STM32L152xBA) || defined(STM32L152xC) || \ defined(STM32L162xC) || defined(STM32L152xCA) || defined(STM32L152xD) || \ defined(STM32L162xCA) || defined(STM32L162xD) || defined(STM32L152xE) || \ defined(STM32L162xE) #define __LCD_CLK_SLEEP_ENABLE() (RCC->APB1LPENR |= (RCC_APB1LPENR_LCDLPEN)) #define __LCD_CLK_SLEEP_DISABLE() (RCC->APB1LPENR &= ~(RCC_APB1LPENR_LCDLPEN)) #endif /* STM32L100xB || STM32L152xBA || ... || STM32L152xE || STM32L162xE */ /** @brief Enables or disables the APB1 peripheral clock during Low Power (Sleep) mode. * @note Peripheral clock gating in SLEEP mode can be used to further reduce * power consumption. * @note After wakeup from SLEEP mode, the peripheral clock is enabled again. * @note By default, all peripheral clocks are enabled during SLEEP mode. */ #if defined (STM32L151xC) || defined (STM32L152xC) || defined (STM32L162xC) || \ defined(STM32L151xCA) || defined (STM32L151xD) || defined (STM32L152xCA) || defined (STM32L152xD) || defined (STM32L162xCA) || defined (STM32L162xD) || \ defined(STM32L151xE) || defined (STM32L152xE) || defined (STM32L162xE) #define __TIM5_CLK_SLEEP_ENABLE() (RCC->APB1LPENR |= (RCC_APB1LPENR_TIM5LPEN)) #define __TIM5_CLK_SLEEP_DISABLE() (RCC->APB1LPENR &= ~(RCC_APB1LPENR_TIM5LPEN)) #endif /* STM32L151xC || STM32L152xC || STM32L162xC || STM32L151xCA || STM32L151xD || STM32L152xCA || STM32L152xD || STM32L162xCA || STM32L162xD || STM32L151xE || STM32L152xE || STM32L162xE */ #if defined(STM32L100xC) || defined (STM32L151xC) || defined (STM32L152xC) || defined (STM32L162xC) || \ defined(STM32L151xCA) || defined (STM32L151xD) || defined (STM32L152xCA) || defined (STM32L152xD) || defined (STM32L162xCA) || defined (STM32L162xD) || \ defined(STM32L151xE) || defined (STM32L152xE) || defined (STM32L162xE) #define __SPI3_CLK_SLEEP_ENABLE() (RCC->APB1LPENR |= (RCC_APB1LPENR_SPI3LPEN)) #define __SPI3_CLK_SLEEP_DISABLE() (RCC->APB1LPENR &= ~(RCC_APB1LPENR_SPI3LPEN)) #endif /* STM32L100xC || STM32L151xC || STM32L152xC || STM32L162xC || STM32L151xCA || STM32L151xD || STM32L152xCA || STM32L152xD || STM32L162xCA || STM32L162xD || STM32L151xE || STM32L152xE || STM32L162xE */ #if defined (STM32L151xD) || defined (STM32L152xD) || defined (STM32L162xD) || \ defined(STM32L151xE) || defined (STM32L152xE) || defined (STM32L162xE) #define __UART4_CLK_SLEEP_ENABLE() (RCC->APB1LPENR |= (RCC_APB1LPENR_UART4LPEN)) #define __UART5_CLK_SLEEP_ENABLE() (RCC->APB1LPENR |= (RCC_APB1LPENR_UART5LPEN)) #define __UART4_CLK_SLEEP_DISABLE() (RCC->APB1LPENR &= ~(RCC_APB1LPENR_UART4LPEN)) #define __UART5_CLK_SLEEP_DISABLE() (RCC->APB1LPENR &= ~(RCC_APB1LPENR_UART5LPEN)) #endif /* STM32L151xD || STM32L152xD || STM32L162xD || STM32L151xE || STM32L152xE || STM32L162xE */ /** @brief Enables or disables the APB2 peripheral clock during Low Power (Sleep) mode. * @note Peripheral clock gating in SLEEP mode can be used to further reduce * power consumption. * @note After wakeup from SLEEP mode, the peripheral clock is enabled again. * @note By default, all peripheral clocks are enabled during SLEEP mode. */ #if defined (STM32L151xD) || defined (STM32L152xD) || defined (STM32L162xD) #define __SDIO_CLK_SLEEP_ENABLE() (RCC->APB2LPENR |= (RCC_APB2LPENR_SDIOLPEN)) #define __SDIO_CLK_SLEEP_DISABLE() (RCC->APB2LPENR &= ~(RCC_APB2LPENR_SDIOLPEN)) #endif /* STM32L151xD || STM32L152xD || STM32L162xD */ /** * @} */ #if defined (STM32L100xB) || defined (STM32L100xBA) || defined (STM32L100xC) ||\ defined(STM32L152xB) || defined(STM32L152xBA) || defined(STM32L152xC) || \ defined(STM32L162xC) || defined(STM32L152xCA) || defined(STM32L152xD) || \ defined(STM32L162xCA) || defined(STM32L162xD) || defined(STM32L152xE) || \ defined(STM32L162xE) /** @brief Macro to configures LCD clock (LCDCLK). * @note LCD and RTC use the same configuration * @note LCD can however be used in the Stop low power mode if the LSE or LSI is used as the * LCD clock source. * * @param __LCD_CLKSOURCE__: specifies the LCD clock source. * This parameter can be one of the following values: * @arg RCC_RTCCLKSOURCE_LSE: LSE selected as RTC clock * @arg RCC_RTCCLKSOURCE_LSI: LSI selected as RTC clock * @arg RCC_RTCCLKSOURCE_HSE_DIV2: HSE divided by 2 selected as RTC clock * @arg RCC_RTCCLKSOURCE_HSE_DIV4: HSE divided by 4 selected as RTC clock * @arg RCC_RTCCLKSOURCE_HSE_DIV8: HSE divided by 8 selected as RTC clock * @arg RCC_RTCCLKSOURCE_HSE_DIV16: HSE divided by 16 selected as RTC clock */ #define __HAL_RCC_LCD_CONFIG(__LCD_CLKSOURCE__) __HAL_RCC_RTC_CONFIG(__LCD_CLKSOURCE__) /** @brief macros to get the LCD clock source. */ #define __HAL_RCC_GET_LCD_SOURCE() __HAL_RCC_GET_RTC_SOURCE() #endif /* STM32L100xB || STM32L152xBA || ... || STM32L152xE || STM32L162xE */ /** * @} */ /* Exported functions --------------------------------------------------------*/ /** @addtogroup RCCEx_Private_Functions * @{ */ /** @addtogroup RCCEx_Exported_Functions_Group1 * @{ */ HAL_StatusTypeDef HAL_RCCEx_PeriphCLKConfig(RCC_PeriphCLKInitTypeDef *PeriphClkInit); void HAL_RCCEx_GetPeriphCLKConfig(RCC_PeriphCLKInitTypeDef *PeriphClkInit); #if defined(STM32L100xBA) || defined (STM32L151xBA) || defined (STM32L152xBA) || \ defined(STM32L100xC) || defined (STM32L151xC) || defined (STM32L152xC) || defined (STM32L162xC) || \ defined(STM32L151xCA) || defined (STM32L151xD) || defined (STM32L152xCA) || defined (STM32L152xD) || defined (STM32L162xCA) || defined (STM32L162xD) || \ defined(STM32L151xE) || defined (STM32L152xE) || defined (STM32L162xE) void HAL_RCCEx_EnableLSECSS(void); void HAL_RCCEx_DisableLSECSS(void); #endif /* STM32L100xBA || STM32L151xBA || STM32L152xBA || STM32L100xC || STM32L151xC || STM32L152xC || STM32L162xC || STM32L151xCA || STM32L151xD || STM32L152xCA || STM32L152xD || STM32L162xCA || STM32L162xD || STM32L151xE || STM32L152xE || STM32L162xE*/ /** * @} */ /** * @} */ /** * @} */ /** * @} */ #ifdef __cplusplus } #endif #endif /* __STM32L1xx_HAL_RCC_EX_H */ /************************ (C) COPYRIGHT STMicroelectronics *****END OF FILE****/ ================================================ FILE: Zelig/mbed/TARGET_NUCLEO_L152RE/stm32l1xx_hal_rtc.h ================================================ /** ****************************************************************************** * @file stm32l1xx_hal_rtc.h * @author MCD Application Team * @version V1.0.0 * @date 5-September-2014 * @brief Header file of RTC HAL module. ****************************************************************************** * @attention * *

© COPYRIGHT(c) 2014 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. * ****************************************************************************** */ /* Define to prevent recursive inclusion -------------------------------------*/ #ifndef __STM32L1xx_HAL_RTC_H #define __STM32L1xx_HAL_RTC_H #ifdef __cplusplus extern "C" { #endif /* Includes ------------------------------------------------------------------*/ #include "stm32l1xx_hal_def.h" /** @addtogroup STM32L1xx_HAL_Driver * @{ */ /** @addtogroup RTC * @{ */ /* Exported types ------------------------------------------------------------*/ /** @defgroup RTC_Exported_Types RTC Exported Types * @{ */ /** * @brief HAL State structures definition */ typedef enum { HAL_RTC_STATE_RESET = 0x00, /*!< RTC not yet initialized or disabled */ HAL_RTC_STATE_READY = 0x01, /*!< RTC initialized and ready for use */ HAL_RTC_STATE_BUSY = 0x02, /*!< RTC process is ongoing */ HAL_RTC_STATE_TIMEOUT = 0x03, /*!< RTC timeout state */ HAL_RTC_STATE_ERROR = 0x04 /*!< RTC error state */ }HAL_RTCStateTypeDef; /** * @brief RTC Configuration Structure definition */ typedef struct { uint32_t HourFormat; /*!< Specifies the RTC Hour Format. This parameter can be a value of @ref RTC_Hour_Formats */ uint32_t AsynchPrediv; /*!< Specifies the RTC Asynchronous Predivider value. This parameter must be a number between Min_Data = 0x00 and Max_Data = 0x7F */ uint32_t SynchPrediv; /*!< Specifies the RTC Synchronous Predivider value. This parameter must be a number between Min_Data = 0x00 and Max_Data = 0x7FFF */ uint32_t OutPut; /*!< Specifies which signal will be routed to the RTC output. This parameter can be a value of @ref RTCEx_Output_selection_Definitions */ uint32_t OutPutPolarity; /*!< Specifies the polarity of the output signal. This parameter can be a value of @ref RTC_Output_Polarity_Definitions */ uint32_t OutPutType; /*!< Specifies the RTC Output Pin mode. This parameter can be a value of @ref RTC_Output_Type_ALARM_OUT */ }RTC_InitTypeDef; /** * @brief RTC Date structure definition */ typedef struct { uint8_t WeekDay; /*!< Specifies the RTC Date WeekDay. This parameter can be a value of @ref RTC_WeekDay_Definitions */ uint8_t Month; /*!< Specifies the RTC Date Month (in BCD format). This parameter can be a value of @ref RTC_Month_Date_Definitions */ uint8_t Date; /*!< Specifies the RTC Date. This parameter must be a number between Min_Data = 1 and Max_Data = 31 */ uint8_t Year; /*!< Specifies the RTC Date Year. This parameter must be a number between Min_Data = 0 and Max_Data = 99 */ }RTC_DateTypeDef; /** * @brief Time Handle Structure definition */ typedef struct { RTC_TypeDef *Instance; /*!< Register base address */ RTC_InitTypeDef Init; /*!< RTC required parameters */ HAL_LockTypeDef Lock; /*!< RTC locking object */ __IO HAL_RTCStateTypeDef State; /*!< Time communication state */ }RTC_HandleTypeDef; /** * @} */ /* Exported constants --------------------------------------------------------*/ /** @defgroup RTC_Exported_Constants RTC Exported Constants * @{ */ /** @defgroup RTC_Timeout_Value Default Timeout Value * @{ */ #define RTC_TIMEOUT_VALUE 1000 /** * @} */ /** @defgroup RTC_Hour_Formats Hour Formats * @{ */ #define RTC_HOURFORMAT_24 ((uint32_t)0x00000000) #define RTC_HOURFORMAT_12 ((uint32_t)0x00000040) #define IS_RTC_HOUR_FORMAT(FORMAT) (((FORMAT) == RTC_HOURFORMAT_12) || \ ((FORMAT) == RTC_HOURFORMAT_24)) /** * @} */ /** @defgroup RTC_Output_Polarity_Definitions Outpout Polarity * @{ */ #define RTC_OUTPUT_POLARITY_HIGH ((uint32_t)0x00000000) #define RTC_OUTPUT_POLARITY_LOW ((uint32_t)0x00100000) #define IS_RTC_OUTPUT_POL(POL) (((POL) == RTC_OUTPUT_POLARITY_HIGH) || \ ((POL) == RTC_OUTPUT_POLARITY_LOW)) /** * @} */ /** @defgroup RTC_Output_Type_ALARM_OUT Alarm Output Type * @{ */ #define RTC_OUTPUT_TYPE_OPENDRAIN ((uint32_t)0x00000000) #define RTC_OUTPUT_TYPE_PUSHPULL ((uint32_t)0x00040000) #define IS_RTC_OUTPUT_TYPE(TYPE) (((TYPE) == RTC_OUTPUT_TYPE_OPENDRAIN) || \ ((TYPE) == RTC_OUTPUT_TYPE_PUSHPULL)) /** * @} */ /** @defgroup RTC_Asynchronous_Predivider Asynchronous Predivider * @{ */ #define IS_RTC_ASYNCH_PREDIV(PREDIV) ((PREDIV) <= (uint32_t)0x7F) /** * @} */ /** @defgroup RTC_Time_Definitions Time Definitions * @{ */ #define IS_RTC_HOUR12(HOUR) (((HOUR) > (uint32_t)0) && ((HOUR) <= (uint32_t)12)) #define IS_RTC_HOUR24(HOUR) ((HOUR) <= (uint32_t)23) #define IS_RTC_MINUTES(MINUTES) ((MINUTES) <= (uint32_t)59) #define IS_RTC_SECONDS(SECONDS) ((SECONDS) <= (uint32_t)59) /** * @} */ /** @defgroup RTC_AM_PM_Definitions AM PM Definitions * @{ */ #define RTC_HOURFORMAT12_AM ((uint8_t)0x00) #define RTC_HOURFORMAT12_PM ((uint8_t)0x40) #define IS_RTC_HOURFORMAT12(PM) (((PM) == RTC_HOURFORMAT12_AM) || ((PM) == RTC_HOURFORMAT12_PM)) /** * @} */ /** @defgroup RTC_DayLightSaving_Definitions DayLightSaving * @{ */ #define RTC_DAYLIGHTSAVING_SUB1H ((uint32_t)0x00020000) #define RTC_DAYLIGHTSAVING_ADD1H ((uint32_t)0x00010000) #define RTC_DAYLIGHTSAVING_NONE ((uint32_t)0x00000000) #define IS_RTC_DAYLIGHT_SAVING(SAVE) (((SAVE) == RTC_DAYLIGHTSAVING_SUB1H) || \ ((SAVE) == RTC_DAYLIGHTSAVING_ADD1H) || \ ((SAVE) == RTC_DAYLIGHTSAVING_NONE)) /** * @} */ /** @defgroup RTC_StoreOperation_Definitions StoreOperation * @{ */ #define RTC_STOREOPERATION_RESET ((uint32_t)0x00000000) #define RTC_STOREOPERATION_SET ((uint32_t)0x00040000) #define IS_RTC_STORE_OPERATION(OPERATION) (((OPERATION) == RTC_STOREOPERATION_RESET) || \ ((OPERATION) == RTC_STOREOPERATION_SET)) /** * @} */ /** @defgroup RTC_Input_parameter_format_definitions Input Parameter Format * @{ */ #define FORMAT_BIN ((uint32_t)0x000000000) #define FORMAT_BCD ((uint32_t)0x000000001) #define IS_RTC_FORMAT(FORMAT) (((FORMAT) == FORMAT_BIN) || ((FORMAT) == FORMAT_BCD)) /** * @} */ /** @defgroup RTC_Year_Date_Definitions Year Definitions * @{ */ #define IS_RTC_YEAR(YEAR) ((YEAR) <= (uint32_t)99) /** * @} */ /** @defgroup RTC_Month_Date_Definitions Month Definitions * @{ */ /* Coded in BCD format */ #define RTC_MONTH_JANUARY ((uint8_t)0x01) #define RTC_MONTH_FEBRUARY ((uint8_t)0x02) #define RTC_MONTH_MARCH ((uint8_t)0x03) #define RTC_MONTH_APRIL ((uint8_t)0x04) #define RTC_MONTH_MAY ((uint8_t)0x05) #define RTC_MONTH_JUNE ((uint8_t)0x06) #define RTC_MONTH_JULY ((uint8_t)0x07) #define RTC_MONTH_AUGUST ((uint8_t)0x08) #define RTC_MONTH_SEPTEMBER ((uint8_t)0x09) #define RTC_MONTH_OCTOBER ((uint8_t)0x10) #define RTC_MONTH_NOVEMBER ((uint8_t)0x11) #define RTC_MONTH_DECEMBER ((uint8_t)0x12) #define IS_RTC_MONTH(MONTH) (((MONTH) >= (uint32_t)1) && ((MONTH) <= (uint32_t)12)) #define IS_RTC_DATE(DATE) (((DATE) >= (uint32_t)1) && ((DATE) <= (uint32_t)31)) /** * @} */ /** @defgroup RTC_WeekDay_Definitions WeekDay Definitions * @{ */ #define RTC_WEEKDAY_MONDAY ((uint8_t)0x01) #define RTC_WEEKDAY_TUESDAY ((uint8_t)0x02) #define RTC_WEEKDAY_WEDNESDAY ((uint8_t)0x03) #define RTC_WEEKDAY_THURSDAY ((uint8_t)0x04) #define RTC_WEEKDAY_FRIDAY ((uint8_t)0x05) #define RTC_WEEKDAY_SATURDAY ((uint8_t)0x06) #define RTC_WEEKDAY_SUNDAY ((uint8_t)0x07) #define IS_RTC_WEEKDAY(WEEKDAY) (((WEEKDAY) == RTC_WEEKDAY_MONDAY) || \ ((WEEKDAY) == RTC_WEEKDAY_TUESDAY) || \ ((WEEKDAY) == RTC_WEEKDAY_WEDNESDAY) || \ ((WEEKDAY) == RTC_WEEKDAY_THURSDAY) || \ ((WEEKDAY) == RTC_WEEKDAY_FRIDAY) || \ ((WEEKDAY) == RTC_WEEKDAY_SATURDAY) || \ ((WEEKDAY) == RTC_WEEKDAY_SUNDAY)) /** * @} */ /** @defgroup RTC_Alarm_Definitions Alarm Definitions * @{ */ #define IS_RTC_ALARM_DATE_WEEKDAY_DATE(DATE) (((DATE) >(uint32_t) 0) && ((DATE) <= (uint32_t)31)) #define IS_RTC_ALARM_DATE_WEEKDAY_WEEKDAY(WEEKDAY) (((WEEKDAY) == RTC_WEEKDAY_MONDAY) || \ ((WEEKDAY) == RTC_WEEKDAY_TUESDAY) || \ ((WEEKDAY) == RTC_WEEKDAY_WEDNESDAY) || \ ((WEEKDAY) == RTC_WEEKDAY_THURSDAY) || \ ((WEEKDAY) == RTC_WEEKDAY_FRIDAY) || \ ((WEEKDAY) == RTC_WEEKDAY_SATURDAY) || \ ((WEEKDAY) == RTC_WEEKDAY_SUNDAY)) /** * @} */ /** @defgroup RTC_AlarmDateWeekDay_Definitions AlarmDateWeekDay Definitions * @{ */ #define RTC_ALARMDATEWEEKDAYSEL_DATE ((uint32_t)0x00000000) #define RTC_ALARMDATEWEEKDAYSEL_WEEKDAY ((uint32_t)0x40000000) #define IS_RTC_ALARM_DATE_WEEKDAY_SEL(SEL) (((SEL) == RTC_ALARMDATEWEEKDAYSEL_DATE) || \ ((SEL) == RTC_ALARMDATEWEEKDAYSEL_WEEKDAY)) /** * @} */ /** @defgroup RTC_AlarmMask_Definitions Alarm Mask Definitions * @{ */ #define RTC_ALARMMASK_NONE ((uint32_t)0x00000000) #define RTC_ALARMMASK_DATEWEEKDAY RTC_ALRMAR_MSK4 #define RTC_ALARMMASK_HOURS RTC_ALRMAR_MSK3 #define RTC_ALARMMASK_MINUTES RTC_ALRMAR_MSK2 #define RTC_ALARMMASK_SECONDS RTC_ALRMAR_MSK1 #define RTC_ALARMMASK_ALL ((uint32_t)0x80808080) #define IS_ALARM_MASK(MASK) (((MASK) & 0x7F7F7F7F) == (uint32_t)RESET) /** * @} */ /** @defgroup RTC_Alarms_Definitions Alarms Definitions * @{ */ #define RTC_ALARM_A RTC_CR_ALRAE #define RTC_ALARM_B RTC_CR_ALRBE #define IS_ALARM(ALARM) (((ALARM) == RTC_ALARM_A) || ((ALARM) == RTC_ALARM_B)) /** * @} */ /** * @} */ /* Exported macro ------------------------------------------------------------*/ /** @defgroup RTC_Exported_macros RTC Exported Macros * @{ */ /** @brief Reset RTC handle state * @param __HANDLE__: RTC handle. * @retval None */ #define __HAL_RTC_RESET_HANDLE_STATE(__HANDLE__) ((__HANDLE__)->State = HAL_RTC_STATE_RESET) /** * @brief Disable the write protection for RTC registers. * @param __HANDLE__: specifies the RTC handle. * @retval None */ #define __HAL_RTC_WRITEPROTECTION_DISABLE(__HANDLE__) \ do{ \ (__HANDLE__)->Instance->WPR = 0xCA; \ (__HANDLE__)->Instance->WPR = 0x53; \ } while(0) /** * @brief Enable the write protection for RTC registers. * @param __HANDLE__: specifies the RTC handle. * @retval None */ #define __HAL_RTC_WRITEPROTECTION_ENABLE(__HANDLE__) \ do{ \ (__HANDLE__)->Instance->WPR = 0xFF; \ } while(0) /** * @brief Enable the RTC ALARMA peripheral. * @param __HANDLE__: specifies the RTC handle. * @retval None */ #define __HAL_RTC_ALARMA_ENABLE(__HANDLE__) ((__HANDLE__)->Instance->CR |= (RTC_CR_ALRAE)) /** * @brief Disable the RTC ALARMA peripheral. * @param __HANDLE__: specifies the RTC handle. * @retval None */ #define __HAL_RTC_ALARMA_DISABLE(__HANDLE__) ((__HANDLE__)->Instance->CR &= ~(RTC_CR_ALRAE)) /** * @brief Enable the RTC ALARMB peripheral. * @param __HANDLE__: specifies the RTC handle. * @retval None */ #define __HAL_RTC_ALARMB_ENABLE(__HANDLE__) ((__HANDLE__)->Instance->CR |= (RTC_CR_ALRBE)) /** * @brief Disable the RTC ALARMB peripheral. * @param __HANDLE__: specifies the RTC handle. * @retval None */ #define __HAL_RTC_ALARMB_DISABLE(__HANDLE__) ((__HANDLE__)->Instance->CR &= ~(RTC_CR_ALRBE)) /** * @brief Enable the RTC Alarm interrupt. * @param __HANDLE__: specifies the RTC handle. * @param __INTERRUPT__: specifies the RTC Alarm interrupt sources to be enabled or disabled. * This parameter can be any combination of the following values: * @arg RTC_IT_ALRA: Alarm A interrupt * @arg RTC_IT_ALRB: Alarm B interrupt * @retval None */ #define __HAL_RTC_ALARM_ENABLE_IT(__HANDLE__, __INTERRUPT__) ((__HANDLE__)->Instance->CR |= (__INTERRUPT__)) /** * @brief Disable the RTC Alarm interrupt. * @param __HANDLE__: specifies the RTC handle. * @param __INTERRUPT__: specifies the RTC Alarm interrupt sources to be enabled or disabled. * This parameter can be any combination of the following values: * @arg RTC_IT_ALRA: Alarm A interrupt * @arg RTC_IT_ALRB: Alarm B interrupt * @retval None */ #define __HAL_RTC_ALARM_DISABLE_IT(__HANDLE__, __INTERRUPT__) ((__HANDLE__)->Instance->CR &= ~(__INTERRUPT__)) /** * @brief Check whether the specified RTC Alarm interrupt has occurred or not. * @param __HANDLE__: specifies the RTC handle. * @param __FLAG__: specifies the RTC Alarm interrupt sources to be enabled or disabled. * This parameter can be: * @arg RTC_IT_ALRA: Alarm A interrupt * @arg RTC_IT_ALRB: Alarm B interrupt * @retval None */ #define __HAL_RTC_ALARM_GET_IT(__HANDLE__, __FLAG__) ((((((__HANDLE__)->Instance->ISR)& ((__FLAG__)>> 4)) & 0x0000FFFF) != RESET)? SET : RESET) /** * @brief Get the selected RTC Alarm's flag status. * @param __HANDLE__: specifies the RTC handle. * @param __FLAG__: specifies the RTC Alarm Flag sources to be enabled or disabled. * This parameter can be: * @arg RTC_FLAG_ALRAF * @arg RTC_FLAG_ALRBF * @arg RTC_FLAG_ALRAWF * @arg RTC_FLAG_ALRBWF * @retval None */ #define __HAL_RTC_ALARM_GET_FLAG(__HANDLE__, __FLAG__) (((((__HANDLE__)->Instance->ISR) & (__FLAG__)) != RESET)? SET : RESET) /** * @brief Clear the RTC Alarm's pending flags. * @param __HANDLE__: specifies the RTC handle. * @param __FLAG__: specifies the RTC Alarm Flag sources to be enabled or disabled. * This parameter can be: * @arg RTC_FLAG_ALRAF * @arg RTC_FLAG_ALRBF * @retval None */ #define __HAL_RTC_ALARM_CLEAR_FLAG(__HANDLE__, __FLAG__) ((__HANDLE__)->Instance->ISR) = (~(((__FLAG__) | RTC_ISR_INIT)& 0x0000FFFF)|((__HANDLE__)->Instance->ISR & RTC_ISR_INIT)) #define RTC_EXTI_LINE_ALARM_EVENT ((uint32_t)0x00020000) /*!< External interrupt line 17 Connected to the RTC Alarm event */ #define RTC_EXTI_LINE_TAMPER_TIMESTAMP_EVENT ((uint32_t)0x00080000) /*!< External interrupt line 19 Connected to the RTC Tamper and Time Stamp events */ #define RTC_EXTI_LINE_WAKEUPTIMER_EVENT ((uint32_t)0x00100000) /*!< External interrupt line 20 Connected to the RTC Wakeup event */ /** * @brief Enable the RTC Exti line. * @param __EXTILINE__: specifies the RTC Exti sources to be enabled or disabled. * This parameter can be: * @arg RTC_EXTI_LINE_ALARM_EVENT * @arg RTC_EXTI_LINE_TAMPER_TIMESTAMP_EVENT * @arg RTC_EXTI_LINE_WAKEUPTIMER_EVENT * @retval None */ #define __HAL_RTC_EXTI_ENABLE_IT(__EXTILINE__) (EXTI->IMR |= (__EXTILINE__)) /* alias define maintained for legacy */ #define __HAL_RTC_ENABLE_IT __HAL_RTC_EXTI_ENABLE_IT /** * @brief Disable the RTC Exti line. * @param __EXTILINE__: specifies the RTC Exti sources to be enabled or disabled. * This parameter can be: * @arg RTC_EXTI_LINE_ALARM_EVENT * @arg RTC_EXTI_LINE_TAMPER_TIMESTAMP_EVENT * @arg RTC_EXTI_LINE_WAKEUPTIMER_EVENT * @retval None */ #define __HAL_RTC_EXTI_DISABLE_IT(__EXTILINE__) (EXTI->IMR &= ~(__EXTILINE__)) /* alias define maintained for legacy */ #define __HAL_RTC_DISABLE_IT __HAL_RTC_EXTI_DISABLE_IT /** * @brief Generates a Software interrupt on selected EXTI line. * @param __EXTILINE__: specifies the RTC Exti sources to be enabled or disabled. * This parameter can be: * @arg RTC_EXTI_LINE_ALARM_EVENT * @arg RTC_EXTI_LINE_TAMPER_TIMESTAMP_EVENT * @arg RTC_EXTI_LINE_WAKEUPTIMER_EVENT * @retval None */ #define __HAL_RTC_EXTI_GENERATE_SWIT(__EXTILINE__) (EXTI->SWIER |= (__EXTILINE__)) /** * @brief Clear the RTC Exti flags. * @param __FLAG__: specifies the RTC Exti sources to be enabled or disabled. * This parameter can be: * @arg RTC_EXTI_LINE_ALARM_EVENT * @arg RTC_EXTI_LINE_TAMPER_TIMESTAMP_EVENT * @arg RTC_EXTI_LINE_WAKEUPTIMER_EVENT * @retval None */ #define __HAL_RTC_EXTI_CLEAR_FLAG(__FLAG__) (EXTI->PR = (__FLAG__)) /* alias define maintained for legacy */ #define __HAL_RTC_CLEAR_FLAG __HAL_RTC_EXTI_CLEAR_FLAG /** * @} */ /* Include RTC HAL Extension module */ #include "stm32l1xx_hal_rtc_ex.h" /* Exported functions --------------------------------------------------------*/ /** @addtogroup RTC_Exported_Functions * @{ */ /* Initialization and de-initialization functions ****************************/ /** @addtogroup RTC_Exported_Functions_Group1 * @{ */ HAL_StatusTypeDef HAL_RTC_Init(RTC_HandleTypeDef *hrtc); HAL_StatusTypeDef HAL_RTC_DeInit(RTC_HandleTypeDef *hrtc); void HAL_RTC_MspInit(RTC_HandleTypeDef *hrtc); void HAL_RTC_MspDeInit(RTC_HandleTypeDef *hrtc); /** * @} */ /* RTC Time and Date functions ************************************************/ /** @addtogroup RTC_Exported_Functions_Group1 * @{ */ HAL_StatusTypeDef HAL_RTC_SetTime(RTC_HandleTypeDef *hrtc, RTC_TimeTypeDef *sTime, uint32_t Format); HAL_StatusTypeDef HAL_RTC_GetTime(RTC_HandleTypeDef *hrtc, RTC_TimeTypeDef *sTime, uint32_t Format); HAL_StatusTypeDef HAL_RTC_SetDate(RTC_HandleTypeDef *hrtc, RTC_DateTypeDef *sDate, uint32_t Format); HAL_StatusTypeDef HAL_RTC_GetDate(RTC_HandleTypeDef *hrtc, RTC_DateTypeDef *sDate, uint32_t Format); /** * @} */ /* RTC Alarm functions ********************************************************/ /** @addtogroup RTC_Exported_Functions_Group2 * @{ */ HAL_StatusTypeDef HAL_RTC_SetAlarm(RTC_HandleTypeDef *hrtc, RTC_AlarmTypeDef *sAlarm, uint32_t Format); HAL_StatusTypeDef HAL_RTC_SetAlarm_IT(RTC_HandleTypeDef *hrtc, RTC_AlarmTypeDef *sAlarm, uint32_t Format); HAL_StatusTypeDef HAL_RTC_DeactivateAlarm(RTC_HandleTypeDef *hrtc, uint32_t Alarm); HAL_StatusTypeDef HAL_RTC_GetAlarm(RTC_HandleTypeDef *hrtc, RTC_AlarmTypeDef *sAlarm, uint32_t Alarm, uint32_t Format); void HAL_RTC_AlarmIRQHandler(RTC_HandleTypeDef *hrtc); HAL_StatusTypeDef HAL_RTC_PollForAlarmAEvent(RTC_HandleTypeDef *hrtc, uint32_t Timeout); void HAL_RTC_AlarmAEventCallback(RTC_HandleTypeDef *hrtc); /** * @} */ /* Peripheral Control functions ***********************************************/ /** @addtogroup RTC_Exported_Functions_Group3 * @{ */ HAL_StatusTypeDef HAL_RTC_WaitForSynchro(RTC_HandleTypeDef* hrtc); /** * @} */ /* Peripheral State functions *************************************************/ /** @addtogroup RTC_Exported_Functions_Group5 * @{ */ HAL_RTCStateTypeDef HAL_RTC_GetState(RTC_HandleTypeDef *hrtc); /** * @} */ /** * @} */ /* Private functions **********************************************************/ /** @addtogroup RTC_Internal_Functions * @{ */ HAL_StatusTypeDef RTC_EnterInitMode(RTC_HandleTypeDef* hrtc); uint8_t RTC_ByteToBcd2(uint8_t Value); uint8_t RTC_Bcd2ToByte(uint8_t Value); /** * @} */ /** * @} */ /** * @} */ #ifdef __cplusplus } #endif #endif /* __STM32L1xx_HAL_RTC_H */ /************************ (C) COPYRIGHT STMicroelectronics *****END OF FILE****/ ================================================ FILE: Zelig/mbed/TARGET_NUCLEO_L152RE/stm32l1xx_hal_rtc_ex.h ================================================ /** ****************************************************************************** * @file stm32l1xx_hal_rtc_ex.h * @author MCD Application Team * @version V1.0.0 * @date 5-September-2014 * @brief Header file of RTC HAL Extension module. ****************************************************************************** * @attention * *

© COPYRIGHT(c) 2014 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. * ****************************************************************************** */ /* Define to prevent recursive inclusion -------------------------------------*/ #ifndef __STM32L1xx_HAL_RTC_EX_H #define __STM32L1xx_HAL_RTC_EX_H #ifdef __cplusplus extern "C" { #endif /* Includes ------------------------------------------------------------------*/ #include "stm32l1xx_hal_def.h" /** @addtogroup STM32L1xx_HAL_Driver * @{ */ /** @addtogroup RTCEx * @{ */ /* Exported types ------------------------------------------------------------*/ /** @defgroup RTCEx_Exported_Types RTCEx Exported Types * @{ */ /** * @brief RTC Tamper structure definition */ typedef struct { uint32_t Tamper; /*!< Specifies the Tamper Pin. This parameter can be a value of @ref RTCEx_Tamper_Pins_Definitions */ uint32_t Trigger; /*!< Specifies the Tamper Trigger. This parameter can be a value of @ref RTCEx_Tamper_Trigger_Definitions */ #if defined(STM32L100xBA) || defined (STM32L151xBA) || defined (STM32L152xBA) || defined(STM32L100xC) || defined (STM32L151xC) || defined (STM32L152xC) || defined (STM32L162xC) || defined(STM32L151xCA) || defined (STM32L151xD) || defined (STM32L152xCA) || defined (STM32L152xD) || defined (STM32L162xCA) || defined (STM32L162xD) || defined(STM32L151xE) || defined (STM32L152xE) || defined (STM32L162xE) uint32_t Filter; /*!< Specifies the RTC Filter Tamper. This parameter can be a value of @ref RTCEx_Tamper_Filter_Definitions */ uint32_t SamplingFrequency; /*!< Specifies the sampling frequency. This parameter can be a value of @ref RTCEx_Tamper_Sampling_Frequencies_Definitions */ uint32_t PrechargeDuration; /*!< Specifies the Precharge Duration . This parameter can be a value of @ref RTCEx_Tamper_Pin_Precharge_Duration_Definitions */ uint32_t TamperPullUp; /*!< Specifies the Tamper PullUp . This parameter can be a value of @ref RTCEx_Tamper_Pull_Up_Definitions */ uint32_t TimeStampOnTamperDetection; /*!< Specifies the TimeStampOnTamperDetection. This parameter can be a value of @ref RTCEx_Tamper_TimeStampOnTamperDetection_Definitions */ #endif /* STM32L100xBA || STM32L151xBA || STM32L152xBA || STM32L100xC || STM32L151xC || STM32L152xC || STM32L162xC || STM32L151xCA || STM32L151xD || STM32L152xCA || STM32L152xD || STM32L162xCA || STM32L162xD || STM32L151xE || STM32L152xE || STM32L162xE */ }RTC_TamperTypeDef; /** * @brief RTC Time structure definition */ typedef struct { uint8_t Hours; /*!< Specifies the RTC Time Hour. This parameter must be a number between Min_Data = 0 and Max_Data = 12 if the RTC_HourFormat_12 is selected This parameter must be a number between Min_Data = 0 and Max_Data = 23 if the RTC_HourFormat_24 is selected */ uint8_t Minutes; /*!< Specifies the RTC Time Minutes. This parameter must be a number between Min_Data = 0 and Max_Data = 59 */ uint8_t Seconds; /*!< Specifies the RTC Time Seconds. This parameter must be a number between Min_Data = 0 and Max_Data = 59 */ #if defined(STM32L100xBA) || defined (STM32L151xBA) || defined (STM32L152xBA) || defined(STM32L100xC) || defined (STM32L151xC) || defined (STM32L152xC) || defined (STM32L162xC) || defined(STM32L151xCA) || defined (STM32L151xD) || defined (STM32L152xCA) || defined (STM32L152xD) || defined (STM32L162xCA) || defined (STM32L162xD) || defined(STM32L151xE) || defined (STM32L152xE) || defined (STM32L162xE) uint32_t SubSeconds; /*!< Specifies the RTC Time SubSeconds. This parameter must be a number between Min_Data = 0 and Max_Data = 59 */ #endif /* STM32L100xBA || STM32L151xBA || STM32L152xBA || STM32L100xC || STM32L151xC || STM32L152xC || STM32L162xC || STM32L151xCA || STM32L151xD || STM32L152xCA || STM32L152xD || STM32L162xCA || STM32L162xD || STM32L151xE || STM32L152xE || STM32L162xE */ uint8_t TimeFormat; /*!< Specifies the RTC AM/PM Time. This parameter can be a value of @ref RTC_AM_PM_Definitions */ uint32_t DayLightSaving; /*!< Specifies RTC_DayLightSaveOperation: the value of hour adjustment. This parameter can be a value of @ref RTC_DayLightSaving_Definitions */ uint32_t StoreOperation; /*!< Specifies RTC_StoreOperation value to be written in the BCK bit in CR register to store the operation. This parameter can be a value of @ref RTC_StoreOperation_Definitions */ }RTC_TimeTypeDef; /** * @brief RTC Alarm structure definition */ typedef struct { RTC_TimeTypeDef AlarmTime; /*!< Specifies the RTC Alarm Time members */ uint32_t AlarmMask; /*!< Specifies the RTC Alarm Masks. This parameter can be a value of @ref RTC_AlarmMask_Definitions */ #if defined(STM32L100xBA) || defined (STM32L151xBA) || defined (STM32L152xBA) || defined(STM32L100xC) || defined (STM32L151xC) || defined (STM32L152xC) || defined (STM32L162xC) || defined(STM32L151xCA) || defined (STM32L151xD) || defined (STM32L152xCA) || defined (STM32L152xD) || defined (STM32L162xCA) || defined (STM32L162xD) || defined(STM32L151xE) || defined (STM32L152xE) || defined (STM32L162xE) uint32_t AlarmSubSecondMask; /*!< Specifies the RTC Alarm SubSeconds Masks. This parameter can be a value of @ref RTC_Alarm_Sub_Seconds_Masks_Definitions */ #endif /* STM32L100xBA || STM32L151xBA || STM32L152xBA || STM32L100xC || STM32L151xC || STM32L152xC || STM32L162xC || STM32L151xCA || STM32L151xD || STM32L152xCA || STM32L152xD || STM32L162xCA || STM32L162xD || STM32L151xE || STM32L152xE || STM32L162xE */ uint32_t AlarmDateWeekDaySel; /*!< Specifies the RTC Alarm is on Date or WeekDay. This parameter can be a value of @ref RTC_AlarmDateWeekDay_Definitions */ uint8_t AlarmDateWeekDay; /*!< Specifies the RTC Alarm Date/WeekDay. If the Alarm Date is selected, this parameter must be set to a value in the 1-31 range. If the Alarm WeekDay is selected, this parameter can be a value of @ref RTC_WeekDay_Definitions */ uint32_t Alarm; /*!< Specifies the alarm . This parameter can be a value of @ref RTC_Alarms_Definitions */ }RTC_AlarmTypeDef; /** * @} */ /* Exported constants --------------------------------------------------------*/ /** @defgroup RTCEx_Exported_Constants RTCEx Exported Constants * @{ */ /** @defgroup RTC_Masks_Definitions Masks Definitions * @{ */ #define RTC_TR_RESERVED_MASK ((uint32_t)0x007F7F7F) #define RTC_DR_RESERVED_MASK ((uint32_t)0x00FFFF3F) #define RTC_INIT_MASK ((uint32_t)0xFFFFFFFF) #define RTC_RSF_MASK ((uint32_t)0xFFFFFF5F) #if defined(STM32L100xBA) || defined (STM32L151xBA) || defined (STM32L152xBA) || defined(STM32L100xC) || defined (STM32L151xC) || defined (STM32L152xC) || defined (STM32L162xC) || defined(STM32L151xCA) || defined (STM32L151xD) || defined (STM32L152xCA) || defined (STM32L152xD) || defined (STM32L162xCA) || defined (STM32L162xD) || defined(STM32L151xE) || defined (STM32L152xE) || defined (STM32L162xE) #define RTC_FLAGS_MASK ((uint32_t)(RTC_FLAG_ALRAWF | RTC_FLAG_ALRBWF | RTC_FLAG_WUTWF | \ RTC_FLAG_SHPF | RTC_FLAG_INITS | RTC_FLAG_RSF | \ RTC_FLAG_INITF | RTC_FLAG_ALRAF | RTC_FLAG_ALRBF | \ RTC_FLAG_WUTF | RTC_FLAG_TSF | RTC_FLAG_TSOVF | \ RTC_FLAG_TAMP1F | RTC_FLAG_TAMP2F | RTC_FLAG_TAMP3F | \ RTC_FLAG_RECALPF)) #else #define RTC_FLAGS_MASK ((uint32_t)(RTC_FLAG_ALRAWF | RTC_FLAG_ALRBWF | RTC_FLAG_WUTWF | \ RTC_FLAG_SHPF | RTC_FLAG_INITS | RTC_FLAG_RSF | \ RTC_FLAG_INITF | RTC_FLAG_ALRAF | RTC_FLAG_ALRBF | \ RTC_FLAG_WUTF | RTC_FLAG_TSF | RTC_FLAG_TSOVF | \ RTC_FLAG_TAMP1F | \ RTC_FLAG_RECALPF)) #endif /* STM32L100xBA || STM32L151xBA || STM32L152xBA || STM32L100xC || STM32L151xC || STM32L152xC || STM32L162xC || STM32L151xCA || STM32L151xD || STM32L152xCA || STM32L152xD || STM32L162xCA || STM32L162xD || STM32L151xE || STM32L152xE || STM32L162xE */ /** * @} */ /** @defgroup RTC_Synchronous_Predivider Synchronous Predivider * @{ */ #if defined(STM32L100xBA) || defined (STM32L151xBA) || defined (STM32L152xBA) || defined(STM32L100xC) || defined (STM32L151xC) || defined (STM32L152xC) || defined (STM32L162xC) || defined(STM32L151xCA) || defined (STM32L151xD) || defined (STM32L152xCA) || defined (STM32L152xD) || defined (STM32L162xCA) || defined (STM32L162xD) || defined(STM32L151xE) || defined (STM32L152xE) || defined (STM32L162xE) #define IS_RTC_SYNCH_PREDIV(PREDIV) ((PREDIV) <= (uint32_t)0x7FFF) #elif defined(STM32L100xB) || defined (STM32L151xB) || defined (STM32L152xB) #define IS_RTC_SYNCH_PREDIV(PREDIV) ((PREDIV) <= (uint32_t)0x1FFF) #endif /* STM32L100xBA || STM32L151xBA || STM32L152xBA || STM32L100xC || STM32L151xC || STM32L152xC || STM32L162xC || STM32L151xCA || STM32L151xD || STM32L152xCA || STM32L152xD || STM32L162xCA || STM32L162xD || STM32L151xE || STM32L152xE || STM32L162xE */ /** * @} */ /** @defgroup RTC_Interrupts_Definitions Interrupts Definitions * @{ */ #define RTC_IT_TS ((uint32_t)0x00008000) #define RTC_IT_WUT ((uint32_t)0x00004000) #define RTC_IT_ALRB ((uint32_t)0x00002000) #define RTC_IT_ALRA ((uint32_t)0x00001000) #define RTC_IT_TAMP1 ((uint32_t)0x00020000) #if defined(STM32L100xBA) || defined (STM32L151xBA) || defined (STM32L152xBA) || defined(STM32L100xC) || defined (STM32L151xC) || defined (STM32L152xC) || defined (STM32L162xC) || defined(STM32L151xCA) || defined (STM32L151xD) || defined (STM32L152xCA) || defined (STM32L152xD) || defined (STM32L162xCA) || defined (STM32L162xD) || defined(STM32L151xE) || defined (STM32L152xE) || defined (STM32L162xE) #define RTC_IT_TAMP2 ((uint32_t)0x00040000) #define RTC_IT_TAMP3 ((uint32_t)0x00080000) #endif /* STM32L100xBA || STM32L151xBA || STM32L152xBA || STM32L100xC || STM32L151xC || STM32L152xC || STM32L162xC || STM32L151xCA || STM32L151xD || STM32L152xCA || STM32L152xD || STM32L162xCA || STM32L162xD || STM32L151xE || STM32L152xE || STM32L162xE */ /** * @} */ /** @defgroup RTC_Flags_Definitions Flags Definitions * @{ */ #define RTC_FLAG_RECALPF ((uint32_t)0x00010000) #if defined(STM32L100xBA) || defined (STM32L151xBA) || defined (STM32L152xBA) || defined(STM32L100xC) || defined (STM32L151xC) || defined (STM32L152xC) || defined (STM32L162xC) || defined(STM32L151xCA) || defined (STM32L151xD) || defined (STM32L152xCA) || defined (STM32L152xD) || defined (STM32L162xCA) || defined (STM32L162xD) || defined(STM32L151xE) || defined (STM32L152xE) || defined (STM32L162xE) #define RTC_FLAG_TAMP3F ((uint32_t)0x00008000) #define RTC_FLAG_TAMP2F ((uint32_t)0x00004000) #endif /* STM32L100xBA || STM32L151xBA || STM32L152xBA || STM32L100xC || STM32L151xC || STM32L152xC || STM32L162xC || STM32L151xCA || STM32L151xD || STM32L152xCA || STM32L152xD || STM32L162xCA || STM32L162xD || STM32L151xE || STM32L152xE || STM32L162xE */ #define RTC_FLAG_TAMP1F ((uint32_t)0x00002000) #define RTC_FLAG_TSOVF ((uint32_t)0x00001000) #define RTC_FLAG_TSF ((uint32_t)0x00000800) #define RTC_FLAG_WUTF ((uint32_t)0x00000400) #define RTC_FLAG_ALRBF ((uint32_t)0x00000200) #define RTC_FLAG_ALRAF ((uint32_t)0x00000100) #define RTC_FLAG_INITF ((uint32_t)0x00000040) #define RTC_FLAG_RSF ((uint32_t)0x00000020) #define RTC_FLAG_INITS ((uint32_t)0x00000010) #if defined(STM32L100xBA) || defined (STM32L151xBA) || defined (STM32L152xBA) || defined(STM32L100xC) || defined (STM32L151xC) || defined (STM32L152xC) || defined (STM32L162xC) || defined(STM32L151xCA) || defined (STM32L151xD) || defined (STM32L152xCA) || defined (STM32L152xD) || defined (STM32L162xCA) || defined (STM32L162xD) || defined(STM32L151xE) || defined (STM32L152xE) || defined (STM32L162xE) #define RTC_FLAG_SHPF ((uint32_t)0x00000008) #endif /* STM32L100xBA || STM32L151xBA || STM32L152xBA || STM32L100xC || STM32L151xC || STM32L152xC || STM32L162xC || STM32L151xCA || STM32L151xD || STM32L152xCA || STM32L152xD || STM32L162xCA || STM32L162xD || STM32L151xE || STM32L152xE || STM32L162xE */ #define RTC_FLAG_WUTWF ((uint32_t)0x00000004) #define RTC_FLAG_ALRBWF ((uint32_t)0x00000002) #define RTC_FLAG_ALRAWF ((uint32_t)0x00000001) /** * @} */ /** @defgroup RTCEx_Output_selection_Definitions Output selection Definitions * @{ */ #define RTC_OUTPUT_DISABLE ((uint32_t)0x00000000) #define RTC_OUTPUT_ALARMA ((uint32_t)0x00200000) #define RTC_OUTPUT_ALARMB ((uint32_t)0x00400000) #define RTC_OUTPUT_WAKEUP ((uint32_t)0x00600000) #define IS_RTC_OUTPUT(OUTPUT) (((OUTPUT) == RTC_OUTPUT_DISABLE) || \ ((OUTPUT) == RTC_OUTPUT_ALARMA) || \ ((OUTPUT) == RTC_OUTPUT_ALARMB) || \ ((OUTPUT) == RTC_OUTPUT_WAKEUP)) /** * @} */ /** @defgroup RTCEx_Backup_Registers_Definitions Backup Registers Definitions * @{ */ #if RTC_BKP_NUMBER > 0 #define RTC_BKP_DR0 ((uint32_t)0x00000000) #define RTC_BKP_DR1 ((uint32_t)0x00000001) #define RTC_BKP_DR2 ((uint32_t)0x00000002) #define RTC_BKP_DR3 ((uint32_t)0x00000003) #define RTC_BKP_DR4 ((uint32_t)0x00000004) #endif /* RTC_BKP_NUMBER > 0 */ #if RTC_BKP_NUMBER > 5 #define RTC_BKP_DR5 ((uint32_t)0x00000005) #define RTC_BKP_DR6 ((uint32_t)0x00000006) #define RTC_BKP_DR7 ((uint32_t)0x00000007) #define RTC_BKP_DR8 ((uint32_t)0x00000008) #define RTC_BKP_DR9 ((uint32_t)0x00000009) #define RTC_BKP_DR10 ((uint32_t)0x0000000A) #define RTC_BKP_DR11 ((uint32_t)0x0000000B) #define RTC_BKP_DR12 ((uint32_t)0x0000000C) #define RTC_BKP_DR13 ((uint32_t)0x0000000D) #define RTC_BKP_DR14 ((uint32_t)0x0000000E) #define RTC_BKP_DR15 ((uint32_t)0x0000000F) #define RTC_BKP_DR16 ((uint32_t)0x00000010) #define RTC_BKP_DR17 ((uint32_t)0x00000011) #define RTC_BKP_DR18 ((uint32_t)0x00000012) #define RTC_BKP_DR19 ((uint32_t)0x00000013) #endif /* RTC_BKP_NUMBER > 5 */ #if RTC_BKP_NUMBER > 20 #define RTC_BKP_DR20 ((uint32_t)0x00000014) #define RTC_BKP_DR21 ((uint32_t)0x00000015) #define RTC_BKP_DR22 ((uint32_t)0x00000016) #define RTC_BKP_DR23 ((uint32_t)0x00000017) #define RTC_BKP_DR24 ((uint32_t)0x00000018) #define RTC_BKP_DR25 ((uint32_t)0x00000019) #define RTC_BKP_DR26 ((uint32_t)0x0000001A) #define RTC_BKP_DR27 ((uint32_t)0x0000001B) #define RTC_BKP_DR28 ((uint32_t)0x0000001C) #define RTC_BKP_DR29 ((uint32_t)0x0000001D) #define RTC_BKP_DR30 ((uint32_t)0x0000001E) #define RTC_BKP_DR31 ((uint32_t)0x0000001F) #endif /* RTC_BKP_NUMBER > 20 */ #define IS_RTC_BKP(BKP) ((BKP) < (uint32_t) RTC_BKP_NUMBER) /** * @} */ /** @defgroup RTCEx_Time_Stamp_Edges_Definitions Time Stamp Edges Definitions * @{ */ #define RTC_TIMESTAMPEDGE_RISING ((uint32_t)0x00000000) #define RTC_TIMESTAMPEDGE_FALLING ((uint32_t)0x00000008) #define IS_TIMESTAMP_EDGE(EDGE) (((EDGE) == RTC_TIMESTAMPEDGE_RISING) || \ ((EDGE) == RTC_TIMESTAMPEDGE_FALLING)) /** * @} */ /** @defgroup RTCEx_Tamper_Pins_Definitions Tamper Pins Definitions * @{ */ #define RTC_TAMPER_1 RTC_TAFCR_TAMP1E #if defined(STM32L100xBA) || defined (STM32L151xBA) || defined (STM32L152xBA) || defined(STM32L100xC) || defined (STM32L151xC) || defined (STM32L152xC) || defined (STM32L162xC) || defined(STM32L151xCA) || defined (STM32L151xD) || defined (STM32L152xCA) || defined (STM32L152xD) || defined (STM32L162xCA) || defined (STM32L162xD) || defined(STM32L151xE) || defined (STM32L152xE) || defined (STM32L162xE) #define RTC_TAMPER_2 RTC_TAFCR_TAMP2E #define RTC_TAMPER_3 RTC_TAFCR_TAMP3E #endif /* STM32L100xBA || STM32L151xBA || STM32L152xBA || STM32L100xC || STM32L151xC || STM32L152xC || STM32L162xC || STM32L151xCA || STM32L151xD || STM32L152xCA || STM32L152xD || STM32L162xCA || STM32L162xD || STM32L151xE || STM32L152xE || STM32L162xE */ #if defined(STM32L100xBA) || defined (STM32L151xBA) || defined (STM32L152xBA) || defined(STM32L100xC) || defined (STM32L151xC) || defined (STM32L152xC) || defined (STM32L162xC) || defined(STM32L151xCA) || defined (STM32L151xD) || defined (STM32L152xCA) || defined (STM32L152xD) || defined (STM32L162xCA) || defined (STM32L162xD) || defined(STM32L151xE) || defined (STM32L152xE) || defined (STM32L162xE) #define IS_TAMPER(TAMPER) (((~(RTC_TAMPER_1|RTC_TAMPER_2|RTC_TAMPER_3) & (TAMPER)) == (uint32_t)RESET) && ((TAMPER) != (uint32_t)RESET)) #else #define IS_TAMPER(TAMPER) ((TAMPER) == RTC_TAMPER_1) #endif /* STM32L100xBA || STM32L151xBA || STM32L152xBA || STM32L100xC || STM32L151xC || STM32L152xC || STM32L162xC || STM32L151xCA || STM32L151xD || STM32L152xCA || STM32L152xD || STM32L162xCA || STM32L162xD || STM32L151xE || STM32L152xE || STM32L162xE */ /** * @} */ /** @defgroup RTCEx_Tamper_Trigger_Definitions Tamper Trigger Definitions * @{ */ #define RTC_TAMPERTRIGGER_RISINGEDGE ((uint32_t)0x00000000) #define RTC_TAMPERTRIGGER_FALLINGEDGE ((uint32_t)0x00000002) #if defined(STM32L100xBA) || defined (STM32L151xBA) || defined (STM32L152xBA) || defined(STM32L100xC) || defined (STM32L151xC) || defined (STM32L152xC) || defined (STM32L162xC) || defined(STM32L151xCA) || defined (STM32L151xD) || defined (STM32L152xCA) || defined (STM32L152xD) || defined (STM32L162xCA) || defined (STM32L162xD) || defined(STM32L151xE) || defined (STM32L152xE) || defined (STM32L162xE) #define RTC_TAMPERTRIGGER_LOWLEVEL RTC_TAMPERTRIGGER_RISINGEDGE #define RTC_TAMPERTRIGGER_HIGHLEVEL RTC_TAMPERTRIGGER_FALLINGEDGE #endif /* STM32L100xBA || STM32L151xBA || STM32L152xBA || STM32L100xC || STM32L151xC || STM32L152xC || STM32L162xC || STM32L151xCA || STM32L151xD || STM32L152xCA || STM32L152xD || STM32L162xCA || STM32L162xD || STM32L151xE || STM32L152xE || STM32L162xE */ #if defined(STM32L100xBA) || defined (STM32L151xBA) || defined (STM32L152xBA) || defined(STM32L100xC) || defined (STM32L151xC) || defined (STM32L152xC) || defined (STM32L162xC) || defined(STM32L151xCA) || defined (STM32L151xD) || defined (STM32L152xCA) || defined (STM32L152xD) || defined (STM32L162xCA) || defined (STM32L162xD) || defined(STM32L151xE) || defined (STM32L152xE) || defined (STM32L162xE) #define IS_TAMPER_TRIGGER(TRIGGER) (((TRIGGER) == RTC_TAMPERTRIGGER_RISINGEDGE) || \ ((TRIGGER) == RTC_TAMPERTRIGGER_FALLINGEDGE) || \ ((TRIGGER) == RTC_TAMPERTRIGGER_LOWLEVEL) || \ ((TRIGGER) == RTC_TAMPERTRIGGER_HIGHLEVEL)) #elif defined(STM32L100xB) || defined (STM32L151xB) || defined (STM32L152xB) #define IS_TAMPER_TRIGGER(TRIGGER) (((TRIGGER) == RTC_TAMPERTRIGGER_RISINGEDGE) || \ ((TRIGGER) == RTC_TAMPERTRIGGER_FALLINGEDGE)) #endif /* STM32L100xBA || STM32L151xBA || STM32L152xBA || STM32L100xC || STM32L151xC || STM32L152xC || STM32L162xC || STM32L151xCA || STM32L151xD || STM32L152xCA || STM32L152xD || STM32L162xCA || STM32L162xD || STM32L151xE || STM32L152xE || STM32L162xE */ /** * @} */ #if defined(STM32L100xBA) || defined (STM32L151xBA) || defined (STM32L152xBA) || defined(STM32L100xC) || defined (STM32L151xC) || defined (STM32L152xC) || defined (STM32L162xC) || defined(STM32L151xCA) || defined (STM32L151xD) || defined (STM32L152xCA) || defined (STM32L152xD) || defined (STM32L162xCA) || defined (STM32L162xD) || defined(STM32L151xE) || defined (STM32L152xE) || defined (STM32L162xE) /** @defgroup RTCEx_Tamper_Filter_Definitions Tamper Filter Definitions * @{ */ #define RTC_TAMPERFILTER_DISABLE ((uint32_t)0x00000000) /*!< Tamper filter is disabled */ #define RTC_TAMPERFILTER_2SAMPLE ((uint32_t)0x00000800) /*!< Tamper is activated after 2 consecutive samples at the active level */ #define RTC_TAMPERFILTER_4SAMPLE ((uint32_t)0x00001000) /*!< Tamper is activated after 4 consecutive samples at the active level */ #define RTC_TAMPERFILTER_8SAMPLE ((uint32_t)0x00001800) /*!< Tamper is activated after 8 consecutive samples at the active level. */ #define IS_TAMPER_FILTER(FILTER) (((FILTER) == RTC_TAMPERFILTER_DISABLE) || \ ((FILTER) == RTC_TAMPERFILTER_2SAMPLE) || \ ((FILTER) == RTC_TAMPERFILTER_4SAMPLE) || \ ((FILTER) == RTC_TAMPERFILTER_8SAMPLE)) /** * @} */ /** @defgroup RTCEx_Tamper_Sampling_Frequencies_Definitions Tamper Sampling Frequencies * @{ */ #define RTC_TAMPERSAMPLINGFREQ_RTCCLK_DIV32768 ((uint32_t)0x00000000) /*!< Each of the tamper inputs are sampled with a frequency = RTCCLK / 32768 */ #define RTC_TAMPERSAMPLINGFREQ_RTCCLK_DIV16384 ((uint32_t)0x00000100) /*!< Each of the tamper inputs are sampled with a frequency = RTCCLK / 16384 */ #define RTC_TAMPERSAMPLINGFREQ_RTCCLK_DIV8192 ((uint32_t)0x00000200) /*!< Each of the tamper inputs are sampled with a frequency = RTCCLK / 8192 */ #define RTC_TAMPERSAMPLINGFREQ_RTCCLK_DIV4096 ((uint32_t)0x00000300) /*!< Each of the tamper inputs are sampled with a frequency = RTCCLK / 4096 */ #define RTC_TAMPERSAMPLINGFREQ_RTCCLK_DIV2048 ((uint32_t)0x00000400) /*!< Each of the tamper inputs are sampled with a frequency = RTCCLK / 2048 */ #define RTC_TAMPERSAMPLINGFREQ_RTCCLK_DIV1024 ((uint32_t)0x00000500) /*!< Each of the tamper inputs are sampled with a frequency = RTCCLK / 1024 */ #define RTC_TAMPERSAMPLINGFREQ_RTCCLK_DIV512 ((uint32_t)0x00000600) /*!< Each of the tamper inputs are sampled with a frequency = RTCCLK / 512 */ #define RTC_TAMPERSAMPLINGFREQ_RTCCLK_DIV256 ((uint32_t)0x00000700) /*!< Each of the tamper inputs are sampled with a frequency = RTCCLK / 256 */ #define IS_TAMPER_SAMPLING_FREQ(FREQ) (((FREQ) == RTC_TAMPERSAMPLINGFREQ_RTCCLK_DIV32768)|| \ ((FREQ) == RTC_TAMPERSAMPLINGFREQ_RTCCLK_DIV16384)|| \ ((FREQ) == RTC_TAMPERSAMPLINGFREQ_RTCCLK_DIV8192) || \ ((FREQ) == RTC_TAMPERSAMPLINGFREQ_RTCCLK_DIV4096) || \ ((FREQ) == RTC_TAMPERSAMPLINGFREQ_RTCCLK_DIV2048) || \ ((FREQ) == RTC_TAMPERSAMPLINGFREQ_RTCCLK_DIV1024) || \ ((FREQ) == RTC_TAMPERSAMPLINGFREQ_RTCCLK_DIV512) || \ ((FREQ) == RTC_TAMPERSAMPLINGFREQ_RTCCLK_DIV256)) /** * @} */ /** @defgroup RTCEx_Tamper_Pin_Precharge_Duration_Definitions Tamper Pin Precharge Duration * @{ */ #define RTC_TAMPERPRECHARGEDURATION_1RTCCLK ((uint32_t)0x00000000) /*!< Tamper pins are pre-charged before sampling during 1 RTCCLK cycle */ #define RTC_TAMPERPRECHARGEDURATION_2RTCCLK ((uint32_t)0x00002000) /*!< Tamper pins are pre-charged before sampling during 2 RTCCLK cycles */ #define RTC_TAMPERPRECHARGEDURATION_4RTCCLK ((uint32_t)0x00004000) /*!< Tamper pins are pre-charged before sampling during 4 RTCCLK cycles */ #define RTC_TAMPERPRECHARGEDURATION_8RTCCLK ((uint32_t)0x00006000) /*!< Tamper pins are pre-charged before sampling during 8 RTCCLK cycles */ #define IS_TAMPER_PRECHARGE_DURATION(DURATION) (((DURATION) == RTC_TAMPERPRECHARGEDURATION_1RTCCLK) || \ ((DURATION) == RTC_TAMPERPRECHARGEDURATION_2RTCCLK) || \ ((DURATION) == RTC_TAMPERPRECHARGEDURATION_4RTCCLK) || \ ((DURATION) == RTC_TAMPERPRECHARGEDURATION_8RTCCLK)) /** * @} */ /** @defgroup RTCEx_Tamper_TimeStampOnTamperDetection_Definitions TimeStampOnTamperDetection Definitions * @{ */ #define RTC_TIMESTAMPONTAMPERDETECTION_ENABLE ((uint32_t)RTC_TAFCR_TAMPTS) /*!< TimeStamp on Tamper Detection event saved */ #define RTC_TIMESTAMPONTAMPERDETECTION_DISABLE ((uint32_t)0x00000000) /*!< TimeStamp on Tamper Detection event is not saved */ #define IS_TAMPER_TIMESTAMPONTAMPER_DETECTION(DETECTION) (((DETECTION) == RTC_TIMESTAMPONTAMPERDETECTION_ENABLE) || \ ((DETECTION) == RTC_TIMESTAMPONTAMPERDETECTION_DISABLE)) /** * @} */ /** @defgroup RTCEx_Tamper_Pull_Up_Definitions Tamper Pull-Up Definitions * @{ */ #define RTC_TAMPER_PULLUP_ENABLE ((uint32_t)0x00000000) /*!< TimeStamp on Tamper Detection event saved */ #define RTC_TAMPER_PULLUP_DISABLE ((uint32_t)RTC_TAFCR_TAMPPUDIS) /*!< TimeStamp on Tamper Detection event is not saved */ #define IS_TAMPER_PULLUP_STATE(STATE) (((STATE) == RTC_TAMPER_PULLUP_ENABLE) || \ ((STATE) == RTC_TAMPER_PULLUP_DISABLE)) /** * @} */ #endif /* STM32L100xBA || STM32L151xBA || STM32L152xBA || STM32L100xC || STM32L151xC || STM32L152xC || STM32L162xC || STM32L151xCA || STM32L151xD || STM32L152xCA || STM32L152xD || STM32L162xCA || STM32L162xD || STM32L151xE || STM32L152xE || STM32L162xE */ /** @defgroup RTCEx_Wakeup_Timer_Definitions Wakeup Timer Definitions * @{ */ #define RTC_WAKEUPCLOCK_RTCCLK_DIV16 ((uint32_t)0x00000000) #define RTC_WAKEUPCLOCK_RTCCLK_DIV8 ((uint32_t)0x00000001) #define RTC_WAKEUPCLOCK_RTCCLK_DIV4 ((uint32_t)0x00000002) #define RTC_WAKEUPCLOCK_RTCCLK_DIV2 ((uint32_t)0x00000003) #define RTC_WAKEUPCLOCK_CK_SPRE_16BITS ((uint32_t)0x00000004) #define RTC_WAKEUPCLOCK_CK_SPRE_17BITS ((uint32_t)0x00000006) #define IS_WAKEUP_CLOCK(CLOCK) (((CLOCK) == RTC_WAKEUPCLOCK_RTCCLK_DIV16) || \ ((CLOCK) == RTC_WAKEUPCLOCK_RTCCLK_DIV8) || \ ((CLOCK) == RTC_WAKEUPCLOCK_RTCCLK_DIV4) || \ ((CLOCK) == RTC_WAKEUPCLOCK_RTCCLK_DIV2) || \ ((CLOCK) == RTC_WAKEUPCLOCK_CK_SPRE_16BITS) || \ ((CLOCK) == RTC_WAKEUPCLOCK_CK_SPRE_17BITS)) #define IS_WAKEUP_COUNTER(COUNTER) ((COUNTER) <= 0xFFFF) /** * @} */ /** @defgroup RTCEx_Digital_Calibration_Definitions Digital Calibration Definitions * @{ */ #define RTC_CALIBSIGN_POSITIVE ((uint32_t)0x00000000) #define RTC_CALIBSIGN_NEGATIVE ((uint32_t)0x00000080) #define IS_RTC_CALIB_SIGN(SIGN) (((SIGN) == RTC_CALIBSIGN_POSITIVE) || \ ((SIGN) == RTC_CALIBSIGN_NEGATIVE)) #define IS_RTC_CALIB_VALUE(VALUE) ((VALUE) < 0x20) /** * @} */ /** @defgroup RTCEx_Smooth_Calib_Period_Definitions Smooth Calib Period Definitions * @{ */ #define RTC_SMOOTHCALIB_PERIOD_32SEC ((uint32_t)0x00000000) /*!< If RTCCLK = 32768 Hz, Smooth calibation period is 32s, else 2exp20 RTCCLK seconds */ #define RTC_SMOOTHCALIB_PERIOD_16SEC ((uint32_t)0x00002000) /*!< If RTCCLK = 32768 Hz, Smooth calibation period is 16s, else 2exp19 RTCCLK seconds */ #define RTC_SMOOTHCALIB_PERIOD_8SEC ((uint32_t)0x00004000) /*!< If RTCCLK = 32768 Hz, Smooth calibation period is 8s, else 2exp18 RTCCLK seconds */ #define IS_RTC_SMOOTH_CALIB_PERIOD(PERIOD) (((PERIOD) == RTC_SMOOTHCALIB_PERIOD_32SEC) || \ ((PERIOD) == RTC_SMOOTHCALIB_PERIOD_16SEC) || \ ((PERIOD) == RTC_SMOOTHCALIB_PERIOD_8SEC)) /** * @} */ /** @defgroup RTCEx_Smooth_Calib_Plus_Pulses_Definitions Smooth Calib Plus Pulses Definitions * @{ */ #define RTC_SMOOTHCALIB_PLUSPULSES_SET ((uint32_t)0x00008000) /*!< The number of RTCCLK pulses added during a X -second window = Y - CALM[8:0] with Y = 512, 256, 128 when X = 32, 16, 8 */ #define RTC_SMOOTHCALIB_PLUSPULSES_RESET ((uint32_t)0x00000000) /*!< The number of RTCCLK pulses subbstited during a 32-second window = CALM[8:0] */ #define IS_RTC_SMOOTH_CALIB_PLUS(PLUS) (((PLUS) == RTC_SMOOTHCALIB_PLUSPULSES_SET) || \ ((PLUS) == RTC_SMOOTHCALIB_PLUSPULSES_RESET)) /** * @} */ /** @defgroup RTCEx_Smooth_Calib_Minus_Pulses_Definitions Smooth Calib Minus Pulses Definitions * @{ */ #define IS_RTC_SMOOTH_CALIB_MINUS(VALUE) ((VALUE) <= 0x000001FF) /** * @} */ /** @defgroup RTCEx_Add_1_Second_Parameter_Definitions Add 1 Second Parameter Definitions * @{ */ #define RTC_SHIFTADD1S_RESET ((uint32_t)0x00000000) #define RTC_SHIFTADD1S_SET ((uint32_t)0x80000000) #define IS_RTC_SHIFT_ADD1S(SEL) (((SEL) == RTC_SHIFTADD1S_RESET) || \ ((SEL) == RTC_SHIFTADD1S_SET)) /** * @} */ /** @defgroup RTCEx_Substract_Fraction_Of_Second_Value Substract Fraction Of Second Value * @{ */ #define IS_RTC_SHIFT_SUBFS(FS) ((FS) <= 0x00007FFF) /** * @} */ /** @defgroup RTCEx_Calib_Output_Selection_Definitions Calib Output Selection Definitions * @{ */ #define RTC_CALIBOUTPUT_512HZ ((uint32_t)0x00000000) #define RTC_CALIBOUTPUT_1HZ ((uint32_t)0x00080000) #define IS_RTC_CALIB_OUTPUT(OUTPUT) (((OUTPUT) == RTC_CALIBOUTPUT_512HZ) || \ ((OUTPUT) == RTC_CALIBOUTPUT_1HZ)) /** * @} */ #if defined(STM32L100xBA) || defined (STM32L151xBA) || defined (STM32L152xBA) || defined(STM32L100xC) || defined (STM32L151xC) || defined (STM32L152xC) || defined (STM32L162xC) || defined(STM32L151xCA) || defined (STM32L151xD) || defined (STM32L152xCA) || defined (STM32L152xD) || defined (STM32L162xCA) || defined (STM32L162xD) || defined(STM32L151xE) || defined (STM32L152xE) || defined (STM32L162xE) /** @defgroup RTC_Alarm_Sub_Seconds_Value Alarm Sub Seconds Value * @{ */ #define IS_RTC_ALARM_SUB_SECOND_VALUE(VALUE) ((VALUE) <= (uint32_t)0x00007FFF) /** * @} */ /** @defgroup RTC_Alarm_Sub_Seconds_Masks_Definitions Alarm Sub Seconds Masks Definitions * @{ */ #define RTC_ALARMSUBSECONDMASK_ALL ((uint32_t)0x00000000) /*!< All Alarm SS fields are masked. There is no comparison on sub seconds for Alarm */ #define RTC_ALARMSUBSECONDMASK_SS14_1 ((uint32_t)0x01000000) /*!< SS[14:1] are don't care in Alarm comparison. Only SS[0] is compared. */ #define RTC_ALARMSUBSECONDMASK_SS14_2 ((uint32_t)0x02000000) /*!< SS[14:2] are don't care in Alarm comparison. Only SS[1:0] are compared */ #define RTC_ALARMSUBSECONDMASK_SS14_3 ((uint32_t)0x03000000) /*!< SS[14:3] are don't care in Alarm comparison. Only SS[2:0] are compared */ #define RTC_ALARMSUBSECONDMASK_SS14_4 ((uint32_t)0x04000000) /*!< SS[14:4] are don't care in Alarm comparison. Only SS[3:0] are compared */ #define RTC_ALARMSUBSECONDMASK_SS14_5 ((uint32_t)0x05000000) /*!< SS[14:5] are don't care in Alarm comparison. Only SS[4:0] are compared */ #define RTC_ALARMSUBSECONDMASK_SS14_6 ((uint32_t)0x06000000) /*!< SS[14:6] are don't care in Alarm comparison. Only SS[5:0] are compared */ #define RTC_ALARMSUBSECONDMASK_SS14_7 ((uint32_t)0x07000000) /*!< SS[14:7] are don't care in Alarm comparison. Only SS[6:0] are compared */ #define RTC_ALARMSUBSECONDMASK_SS14_8 ((uint32_t)0x08000000) /*!< SS[14:8] are don't care in Alarm comparison. Only SS[7:0] are compared */ #define RTC_ALARMSUBSECONDMASK_SS14_9 ((uint32_t)0x09000000) /*!< SS[14:9] are don't care in Alarm comparison. Only SS[8:0] are compared */ #define RTC_ALARMSUBSECONDMASK_SS14_10 ((uint32_t)0x0A000000) /*!< SS[14:10] are don't care in Alarm comparison. Only SS[9:0] are compared */ #define RTC_ALARMSUBSECONDMASK_SS14_11 ((uint32_t)0x0B000000) /*!< SS[14:11] are don't care in Alarm comparison. Only SS[10:0] are compared */ #define RTC_ALARMSUBSECONDMASK_SS14_12 ((uint32_t)0x0C000000) /*!< SS[14:12] are don't care in Alarm comparison.Only SS[11:0] are compared */ #define RTC_ALARMSUBSECONDMASK_SS14_13 ((uint32_t)0x0D000000) /*!< SS[14:13] are don't care in Alarm comparison. Only SS[12:0] are compared */ #define RTC_ALARMSUBSECONDMASK_SS14 ((uint32_t)0x0E000000) /*!< SS[14] is don't care in Alarm comparison.Only SS[13:0] are compared */ #define RTC_ALARMSUBSECONDMASK_NONE ((uint32_t)0x0F000000) /*!< SS[14:0] are compared and must match to activate alarm. */ #define IS_RTC_ALARM_SUB_SECOND_MASK(MASK) (((MASK) == RTC_ALARMSUBSECONDMASK_ALL) || \ ((MASK) == RTC_ALARMSUBSECONDMASK_SS14_1) || \ ((MASK) == RTC_ALARMSUBSECONDMASK_SS14_2) || \ ((MASK) == RTC_ALARMSUBSECONDMASK_SS14_3) || \ ((MASK) == RTC_ALARMSUBSECONDMASK_SS14_4) || \ ((MASK) == RTC_ALARMSUBSECONDMASK_SS14_5) || \ ((MASK) == RTC_ALARMSUBSECONDMASK_SS14_6) || \ ((MASK) == RTC_ALARMSUBSECONDMASK_SS14_7) || \ ((MASK) == RTC_ALARMSUBSECONDMASK_SS14_8) || \ ((MASK) == RTC_ALARMSUBSECONDMASK_SS14_9) || \ ((MASK) == RTC_ALARMSUBSECONDMASK_SS14_10) || \ ((MASK) == RTC_ALARMSUBSECONDMASK_SS14_11) || \ ((MASK) == RTC_ALARMSUBSECONDMASK_SS14_12) || \ ((MASK) == RTC_ALARMSUBSECONDMASK_SS14_13) || \ ((MASK) == RTC_ALARMSUBSECONDMASK_SS14) || \ ((MASK) == RTC_ALARMSUBSECONDMASK_NONE)) /** * @} */ #endif /* STM32L100xBA || STM32L151xBA || STM32L152xBA || STM32L100xC || STM32L151xC || STM32L152xC || STM32L162xC || STM32L151xCA || STM32L151xD || STM32L152xCA || STM32L152xD || STM32L162xCA || STM32L162xD || STM32L151xE || STM32L152xE || STM32L162xE */ /** * @} */ /* Exported macro ------------------------------------------------------------*/ /** @defgroup RTCEx_Exported_Macros RTCEx Exported Macros * @{ */ /** * @brief Enable the RTC WakeUp Timer peripheral. * @param __HANDLE__: specifies the RTC handle. * @retval None */ #define __HAL_RTC_WAKEUPTIMER_ENABLE(__HANDLE__) ((__HANDLE__)->Instance->CR |= (RTC_CR_WUTE)) /** * @brief Enable the RTC TimeStamp peripheral. * @param __HANDLE__: specifies the RTC handle. * @retval None */ #define __HAL_RTC_TIMESTAMP_ENABLE(__HANDLE__) ((__HANDLE__)->Instance->CR |= (RTC_CR_TSE)) /** * @brief Disable the RTC WakeUp Timer peripheral. * @param __HANDLE__: specifies the RTC handle. * @retval None */ #define __HAL_RTC_WAKEUPTIMER_DISABLE(__HANDLE__) ((__HANDLE__)->Instance->CR &= ~(RTC_CR_WUTE)) /** * @brief Disable the RTC TimeStamp peripheral. * @param __HANDLE__: specifies the RTC handle. * @retval None */ #define __HAL_RTC_TIMESTAMP_DISABLE(__HANDLE__) ((__HANDLE__)->Instance->CR &= ~(RTC_CR_TSE)) /** * @brief Enable the Coarse calibration process. * @param __HANDLE__: specifies the RTC handle. * @retval None */ #define __HAL_RTC_COARSE_CALIB_ENABLE(__HANDLE__) ((__HANDLE__)->Instance->CR |= (RTC_CR_DCE)) /** * @brief Disable the Coarse calibration process. * @param __HANDLE__: specifies the RTC handle. * @retval None */ #define __HAL_RTC_COARSE_CALIB_DISABLE(__HANDLE__) ((__HANDLE__)->Instance->CR &= ~(RTC_CR_DCE)) /** * @brief Enable the RTC calibration output. * @param __HANDLE__: specifies the RTC handle. * @retval None */ #define __HAL_RTC_CALIBRATION_OUTPUT_ENABLE(__HANDLE__) ((__HANDLE__)->Instance->CR |= (RTC_CR_COE)) /** * @brief Disable the calibration output. * @param __HANDLE__: specifies the RTC handle. * @retval None */ #define __HAL_RTC_CALIBRATION_OUTPUT_DISABLE(__HANDLE__) ((__HANDLE__)->Instance->CR &= ~(RTC_CR_COE)) /** * @brief Enable the clock reference detection. * @param __HANDLE__: specifies the RTC handle. * @retval None */ #define __HAL_RTC_CLOCKREF_DETECTION_ENABLE(__HANDLE__) ((__HANDLE__)->Instance->CR |= (RTC_CR_REFCKON)) /** * @brief Disable the clock reference detection. * @param __HANDLE__: specifies the RTC handle. * @retval None */ #define __HAL_RTC_CLOCKREF_DETECTION_DISABLE(__HANDLE__) ((__HANDLE__)->Instance->CR &= ~(RTC_CR_REFCKON)) /** * @brief Enable the RTC TimeStamp interrupt. * @param __HANDLE__: specifies the RTC handle. * @param __INTERRUPT__: specifies the RTC TimeStamp interrupt sources to be enabled or disabled. * This parameter can be: * @arg RTC_IT_TS: TimeStamp interrupt * @retval None */ #define __HAL_RTC_TIMESTAMP_ENABLE_IT(__HANDLE__, __INTERRUPT__) ((__HANDLE__)->Instance->CR |= (__INTERRUPT__)) /** * @brief Enable the RTC WakeUpTimer interrupt. * @param __HANDLE__: specifies the RTC handle. * @param __INTERRUPT__: specifies the RTC WakeUpTimer interrupt sources to be enabled or disabled. * This parameter can be: * @arg RTC_IT_WUT: WakeUpTimer A interrupt * @retval None */ #define __HAL_RTC_WAKEUPTIMER_ENABLE_IT(__HANDLE__, __INTERRUPT__) ((__HANDLE__)->Instance->CR |= (__INTERRUPT__)) /** * @brief Disable the RTC TimeStamp interrupt. * @param __HANDLE__: specifies the RTC handle. * @param __INTERRUPT__: specifies the RTC TimeStamp interrupt sources to be enabled or disabled. * This parameter can be: * @arg RTC_IT_TS: TimeStamp interrupt * @retval None */ #define __HAL_RTC_TIMESTAMP_DISABLE_IT(__HANDLE__, __INTERRUPT__) ((__HANDLE__)->Instance->CR &= ~(__INTERRUPT__)) /** * @brief Disable the RTC WakeUpTimer interrupt. * @param __HANDLE__: specifies the RTC handle. * @param __INTERRUPT__: specifies the RTC WakeUpTimer interrupt sources to be enabled or disabled. * This parameter can be: * @arg RTC_IT_WUT: WakeUpTimer A interrupt * @retval None */ #define __HAL_RTC_WAKEUPTIMER_DISABLE_IT(__HANDLE__, __INTERRUPT__) ((__HANDLE__)->Instance->CR &= ~(__INTERRUPT__)) #if defined(STM32L100xBA) || defined (STM32L151xBA) || defined (STM32L152xBA) || defined(STM32L100xC) || defined (STM32L151xC) || defined (STM32L152xC) || defined (STM32L162xC) || defined(STM32L151xCA) || defined (STM32L151xD) || defined (STM32L152xCA) || defined (STM32L152xD) || defined (STM32L162xCA) || defined (STM32L162xD) || defined(STM32L151xE) || defined (STM32L152xE) || defined (STM32L162xE) /** * @brief Check whether the specified RTC Tamper interrupt has occurred or not. * @param __HANDLE__: specifies the RTC handle. * @param __FLAG__: specifies the RTC Tamper interrupt sources to be enabled or disabled. * This parameter can be: * @arg RTC_IT_TAMP1 * @arg RTC_IT_TAMP2 * @arg RTC_IT_TAMP3 * @retval None */ #else /** * @brief Check whether the specified RTC Tamper interrupt has occurred or not. * @param __HANDLE__: specifies the RTC handle. * @param __FLAG__: specifies the RTC Tamper interrupt sources to be enabled or disabled. * This parameter can be: * @arg RTC_IT_TAMP1 * @retval None */ #endif #define __HAL_RTC_TAMPER_GET_IT(__HANDLE__, __FLAG__) (((((__HANDLE__)->Instance->ISR) & ((__FLAG__)>> 4)) != RESET)? SET : RESET) /** * @brief Check whether the specified RTC WakeUpTimer interrupt has occurred or not. * @param __HANDLE__: specifies the RTC handle. * @param __FLAG__: specifies the RTC WakeUpTimer interrupt sources to be enabled or disabled. * This parameter can be: * @arg RTC_IT_WUT: WakeUpTimer A interrupt * @retval None */ #define __HAL_RTC_WAKEUPTIMER_GET_IT(__HANDLE__, __FLAG__) (((((__HANDLE__)->Instance->ISR) & ((__FLAG__)>> 4)) != RESET)? SET : RESET) /** * @brief Check whether the specified RTC TimeStamp interrupt has occurred or not. * @param __HANDLE__: specifies the RTC handle. * @param __FLAG__: specifies the RTC TimeStamp interrupt sources to be enabled or disabled. * This parameter can be: * @arg RTC_IT_TS: TimeStamp interrupt * @retval None */ #define __HAL_RTC_TIMESTAMP_GET_IT(__HANDLE__, __FLAG__) (((((__HANDLE__)->Instance->ISR) & ((__FLAG__)>> 4)) != RESET)? SET : RESET) /** * @brief Get the selected RTC TimeStamp's flag status. * @param __HANDLE__: specifies the RTC handle. * @param __FLAG__: specifies the RTC TimeStamp Flag sources to be enabled or disabled. * This parameter can be: * @arg RTC_FLAG_TSF * @arg RTC_FLAG_TSOVF * @retval None */ #define __HAL_RTC_TIMESTAMP_GET_FLAG(__HANDLE__, __FLAG__) (((((__HANDLE__)->Instance->ISR) & (__FLAG__)) != RESET)? SET : RESET) /** * @brief Get the selected RTC WakeUpTimer's flag status. * @param __HANDLE__: specifies the RTC handle. * @param __FLAG__: specifies the RTC WakeUpTimer Flag sources to be enabled or disabled. * This parameter can be: * @arg RTC_FLAG_WUTF * @arg RTC_FLAG_WUTWF * @retval None */ #define __HAL_RTC_WAKEUPTIMER_GET_FLAG(__HANDLE__, __FLAG__) (((((__HANDLE__)->Instance->ISR) & (__FLAG__)) != RESET)? SET : RESET) /** * @brief Get the selected RTC Tamper's flag status. * @param __HANDLE__: specifies the RTC handle. * @param __FLAG__: specifies the RTC Tamper Flag sources to be enabled or disabled. * This parameter can be: * @arg RTC_FLAG_TAMP1F * @retval None */ #define __HAL_RTC_TAMPER_GET_FLAG(__HANDLE__, __FLAG__) (((((__HANDLE__)->Instance->ISR) & (__FLAG__)) != RESET)? SET : RESET) #if defined(STM32L100xBA) || defined (STM32L151xBA) || defined (STM32L152xBA) || defined(STM32L100xC) || defined (STM32L151xC) || defined (STM32L152xC) || defined (STM32L162xC) || defined(STM32L151xCA) || defined (STM32L151xD) || defined (STM32L152xCA) || defined (STM32L152xD) || defined (STM32L162xCA) || defined (STM32L162xD) || defined(STM32L151xE) || defined (STM32L152xE) || defined (STM32L162xE) /** * @brief Get the selected RTC shift operation's flag status. * @param __HANDLE__: specifies the RTC handle. * @param __FLAG__: specifies the RTC shift operation Flag is pending or not. * This parameter can be: * @arg RTC_FLAG_SHPF * @retval None */ #define __HAL_RTC_SHIFT_GET_FLAG(__HANDLE__, __FLAG__) (((((__HANDLE__)->Instance->ISR) & (__FLAG__)) != RESET)? SET : RESET) #endif /* STM32L100xBA || STM32L151xBA || STM32L152xBA || STM32L100xC || STM32L151xC || STM32L152xC || STM32L162xC || STM32L151xCA || STM32L151xD || STM32L152xCA || STM32L152xD || STM32L162xCA || STM32L162xD || STM32L151xE || STM32L152xE || STM32L162xE */ /** * @brief Clear the RTC Time Stamp's pending flags. * @param __HANDLE__: specifies the RTC handle. * @param __FLAG__: specifies the RTC Alarm Flag sources to be enabled or disabled. * This parameter can be: * @arg RTC_FLAG_TSF * @retval None */ #define __HAL_RTC_TIMESTAMP_CLEAR_FLAG(__HANDLE__, __FLAG__) ((__HANDLE__)->Instance->ISR) = (~(((__FLAG__) | RTC_ISR_INIT)& 0x0000FFFF)|((__HANDLE__)->Instance->ISR & RTC_ISR_INIT)) /** * @brief Clear the RTC Tamper's pending flags. * @param __HANDLE__: specifies the RTC handle. * @param __FLAG__: specifies the RTC Tamper Flag sources to be enabled or disabled. * This parameter can be: * @arg RTC_FLAG_TAMP1F * @retval None */ #define __HAL_RTC_TAMPER_CLEAR_FLAG(__HANDLE__, __FLAG__) ((__HANDLE__)->Instance->ISR) = (~(((__FLAG__) | RTC_ISR_INIT)& 0x0000FFFF)|((__HANDLE__)->Instance->ISR & RTC_ISR_INIT)) /** * @brief Clear the RTC Wake Up timer's pending flags. * @param __HANDLE__: specifies the RTC handle. * @param __FLAG__: specifies the RTC Tamper Flag sources to be enabled or disabled. * This parameter can be: * @arg RTC_FLAG_WUTF * @retval None */ #define __HAL_RTC_WAKEUPTIMER_CLEAR_FLAG(__HANDLE__, __FLAG__) ((__HANDLE__)->Instance->ISR) = (~(((__FLAG__) | RTC_ISR_INIT)& 0x0000FFFF)|((__HANDLE__)->Instance->ISR & RTC_ISR_INIT)) /** * @} */ /* Exported functions --------------------------------------------------------*/ /** @addtogroup RTCEx_Exported_Functions * @{ */ /* RTC TimeStamp and Tamper functions *****************************************/ /** @addtogroup RTCEx_Exported_Functions_Group4 * @{ */ HAL_StatusTypeDef HAL_RTCEx_SetTimeStamp(RTC_HandleTypeDef *hrtc, uint32_t TimeStampEdge); HAL_StatusTypeDef HAL_RTCEx_SetTimeStamp_IT(RTC_HandleTypeDef *hrtc, uint32_t TimeStampEdge); HAL_StatusTypeDef HAL_RTCEx_DeactivateTimeStamp(RTC_HandleTypeDef *hrtc); HAL_StatusTypeDef HAL_RTCEx_GetTimeStamp(RTC_HandleTypeDef *hrtc, RTC_TimeTypeDef *sTimeStamp, RTC_DateTypeDef *sTimeStampDate, uint32_t Format); HAL_StatusTypeDef HAL_RTCEx_SetTamper(RTC_HandleTypeDef *hrtc, RTC_TamperTypeDef* sTamper); HAL_StatusTypeDef HAL_RTCEx_SetTamper_IT(RTC_HandleTypeDef *hrtc, RTC_TamperTypeDef* sTamper); HAL_StatusTypeDef HAL_RTCEx_DeactivateTamper(RTC_HandleTypeDef *hrtc, uint32_t Tamper); void HAL_RTCEx_TamperTimeStampIRQHandler(RTC_HandleTypeDef *hrtc); void HAL_RTCEx_Tamper1EventCallback(RTC_HandleTypeDef *hrtc); #if defined(STM32L100xBA) || defined (STM32L151xBA) || defined (STM32L152xBA) || defined(STM32L100xC) || defined (STM32L151xC) || defined (STM32L152xC) || defined (STM32L162xC) || defined(STM32L151xCA) || defined (STM32L151xD) || defined (STM32L152xCA) || defined (STM32L152xD) || defined (STM32L162xCA) || defined (STM32L162xD) || defined(STM32L151xE) || defined (STM32L152xE) || defined (STM32L162xE) void HAL_RTCEx_Tamper2EventCallback(RTC_HandleTypeDef *hrtc); void HAL_RTCEx_Tamper3EventCallback(RTC_HandleTypeDef *hrtc); #endif /* STM32L100xBA || STM32L151xBA || STM32L152xBA || STM32L100xC || STM32L151xC || STM32L152xC || STM32L162xC || STM32L151xCA || STM32L151xD || STM32L152xCA || STM32L152xD || STM32L162xCA || STM32L162xD || STM32L151xE || STM32L152xE || STM32L162xE */ void HAL_RTCEx_TimeStampEventCallback(RTC_HandleTypeDef *hrtc); HAL_StatusTypeDef HAL_RTCEx_PollForTimeStampEvent(RTC_HandleTypeDef *hrtc, uint32_t Timeout); HAL_StatusTypeDef HAL_RTCEx_PollForTamper1Event(RTC_HandleTypeDef *hrtc, uint32_t Timeout); #if defined(STM32L100xBA) || defined (STM32L151xBA) || defined (STM32L152xBA) || defined(STM32L100xC) || defined (STM32L151xC) || defined (STM32L152xC) || defined (STM32L162xC) || defined(STM32L151xCA) || defined (STM32L151xD) || defined (STM32L152xCA) || defined (STM32L152xD) || defined (STM32L162xCA) || defined (STM32L162xD) || defined(STM32L151xE) || defined (STM32L152xE) || defined (STM32L162xE) HAL_StatusTypeDef HAL_RTCEx_PollForTamper2Event(RTC_HandleTypeDef *hrtc, uint32_t Timeout); HAL_StatusTypeDef HAL_RTCEx_PollForTamper3Event(RTC_HandleTypeDef *hrtc, uint32_t Timeout); #endif /* STM32L100xBA || STM32L151xBA || STM32L152xBA || STM32L100xC || STM32L151xC || STM32L152xC || STM32L162xC || STM32L151xCA || STM32L151xD || STM32L152xCA || STM32L152xD || STM32L162xCA || STM32L162xD || STM32L151xE || STM32L152xE || STM32L162xE */ /** * @} */ /* RTC Wake-up functions ******************************************************/ /** @addtogroup RTCEx_Exported_Functions_Group5 * @{ */ HAL_StatusTypeDef HAL_RTCEx_SetWakeUpTimer(RTC_HandleTypeDef *hrtc, uint32_t WakeUpCounter, uint32_t WakeUpClock); HAL_StatusTypeDef HAL_RTCEx_SetWakeUpTimer_IT(RTC_HandleTypeDef *hrtc, uint32_t WakeUpCounter, uint32_t WakeUpClock); uint32_t HAL_RTCEx_DeactivateWakeUpTimer(RTC_HandleTypeDef *hrtc); uint32_t HAL_RTCEx_GetWakeUpTimer(RTC_HandleTypeDef *hrtc); void HAL_RTCEx_WakeUpTimerIRQHandler(RTC_HandleTypeDef *hrtc); void HAL_RTCEx_WakeUpTimerEventCallback(RTC_HandleTypeDef *hrtc); HAL_StatusTypeDef HAL_RTCEx_PollForWakeUpTimerEvent(RTC_HandleTypeDef *hrtc, uint32_t Timeout); /** * @} */ /* Extension Control functions ************************************************/ /** @addtogroup RTCEx_Exported_Functions_Group7 * @{ */ void HAL_RTCEx_BKUPWrite(RTC_HandleTypeDef *hrtc, uint32_t BackupRegister, uint32_t Data); uint32_t HAL_RTCEx_BKUPRead(RTC_HandleTypeDef *hrtc, uint32_t BackupRegister); HAL_StatusTypeDef HAL_RTCEx_SetCoarseCalib(RTC_HandleTypeDef *hrtc, uint32_t CalibSign, uint32_t Value); HAL_StatusTypeDef HAL_RTCEx_DeactivateCoarseCalib(RTC_HandleTypeDef *hrtc); #if defined(STM32L100xBA) || defined (STM32L151xBA) || defined (STM32L152xBA) || defined(STM32L100xC) || defined (STM32L151xC) || defined (STM32L152xC) || defined (STM32L162xC) || defined(STM32L151xCA) || defined (STM32L151xD) || defined (STM32L152xCA) || defined (STM32L152xD) || defined (STM32L162xCA) || defined (STM32L162xD) || defined(STM32L151xE) || defined (STM32L152xE) || defined (STM32L162xE) HAL_StatusTypeDef HAL_RTCEx_SetSmoothCalib(RTC_HandleTypeDef *hrtc, uint32_t SmoothCalibPeriod, uint32_t SmoothCalibPlusPulses, uint32_t SmouthCalibMinusPulsesValue); HAL_StatusTypeDef HAL_RTCEx_SetSynchroShift(RTC_HandleTypeDef *hrtc, uint32_t ShiftAdd1S, uint32_t ShiftSubFS); HAL_StatusTypeDef HAL_RTCEx_SetCalibrationOutPut(RTC_HandleTypeDef *hrtc, uint32_t CalibOutput); #else HAL_StatusTypeDef HAL_RTCEx_SetCalibrationOutPut(RTC_HandleTypeDef *hrtc); #endif /* STM32L100xBA || STM32L151xBA || STM32L152xBA || STM32L100xC || STM32L151xC || STM32L152xC || STM32L162xC || STM32L151xCA || STM32L151xD || STM32L152xCA || STM32L152xD || STM32L162xCA || STM32L162xD || STM32L151xE || STM32L152xE || STM32L162xE */ HAL_StatusTypeDef HAL_RTCEx_DeactivateCalibrationOutPut(RTC_HandleTypeDef *hrtc); HAL_StatusTypeDef HAL_RTCEx_SetRefClock(RTC_HandleTypeDef *hrtc); HAL_StatusTypeDef HAL_RTCEx_DeactivateRefClock(RTC_HandleTypeDef *hrtc); HAL_StatusTypeDef HAL_RTCEx_EnableBypassShadow(RTC_HandleTypeDef *hrtc); HAL_StatusTypeDef HAL_RTCEx_DisableBypassShadow(RTC_HandleTypeDef *hrtc); /** * @} */ /* Extension RTC features functions *******************************************/ /** @addtogroup RTCEx_Exported_Functions_Group8 * @{ */ void HAL_RTCEx_AlarmBEventCallback(RTC_HandleTypeDef *hrtc); HAL_StatusTypeDef HAL_RTCEx_PollForAlarmBEvent(RTC_HandleTypeDef *hrtc, uint32_t Timeout); /** * @} */ /** * @} */ /** * @} */ /** * @} */ #ifdef __cplusplus } #endif #endif /* __STM32L1xx_HAL_RTC_EX_H */ /************************ (C) COPYRIGHT STMicroelectronics *****END OF FILE****/ ================================================ FILE: Zelig/mbed/TARGET_NUCLEO_L152RE/stm32l1xx_hal_sd.h ================================================ /** ****************************************************************************** * @file stm32l1xx_hal_sd.h * @author MCD Application Team * @version V1.0.0 * @date 5-September-2014 * @brief Header file of SD HAL module. ****************************************************************************** * @attention * *

© COPYRIGHT(c) 2014 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. * ****************************************************************************** */ /* Define to prevent recursive inclusion -------------------------------------*/ #ifndef __STM32L1xx_HAL_SD_H #define __STM32L1xx_HAL_SD_H #if defined(STM32L151xD) || defined(STM32L152xD) || defined(STM32L162xD) #ifdef __cplusplus extern "C" { #endif /* Includes ------------------------------------------------------------------*/ #include "stm32l1xx_ll_sdmmc.h" /** @addtogroup STM32L1xx_HAL_Driver * @{ */ /** @addtogroup SD * @{ */ /* Exported types ------------------------------------------------------------*/ /** @defgroup SD_Exported_Types SD Exported Types * @{ */ #define SD_InitTypeDef SDIO_InitTypeDef #define SD_TypeDef SDIO_TypeDef /** * @brief SDIO Handle Structure definition */ typedef struct { SD_TypeDef *Instance; /*!< SDIO register base address */ SD_InitTypeDef Init; /*!< SD required parameters */ HAL_LockTypeDef Lock; /*!< SD locking object */ uint32_t CardType; /*!< SD card type */ uint32_t RCA; /*!< SD relative card address */ uint32_t CSD[4]; /*!< SD card specific data table */ uint32_t CID[4]; /*!< SD card identification number table */ __IO uint32_t SdTransferCplt; /*!< SD transfer complete flag in non blocking mode */ __IO uint32_t SdTransferErr; /*!< SD transfer error flag in non blocking mode */ __IO uint32_t DmaTransferCplt; /*!< SD DMA transfer complete flag */ __IO uint32_t SdOperation; /*!< SD transfer operation (read/write) */ DMA_HandleTypeDef *hdmarx; /*!< SD Rx DMA handle parameters */ DMA_HandleTypeDef *hdmatx; /*!< SD Tx DMA handle parameters */ }SD_HandleTypeDef; /** * @brief Card Specific Data: CSD Register */ typedef struct { __IO uint8_t CSDStruct; /*!< CSD structure */ __IO uint8_t SysSpecVersion; /*!< System specification version */ __IO uint8_t Reserved1; /*!< Reserved */ __IO uint8_t TAAC; /*!< Data read access time 1 */ __IO uint8_t NSAC; /*!< Data read access time 2 in CLK cycles */ __IO uint8_t MaxBusClkFrec; /*!< Max. bus clock frequency */ __IO uint16_t CardComdClasses; /*!< Card command classes */ __IO uint8_t RdBlockLen; /*!< Max. read data block length */ __IO uint8_t PartBlockRead; /*!< Partial blocks for read allowed */ __IO uint8_t WrBlockMisalign; /*!< Write block misalignment */ __IO uint8_t RdBlockMisalign; /*!< Read block misalignment */ __IO uint8_t DSRImpl; /*!< DSR implemented */ __IO uint8_t Reserved2; /*!< Reserved */ __IO uint32_t DeviceSize; /*!< Device Size */ __IO uint8_t MaxRdCurrentVDDMin; /*!< Max. read current @ VDD min */ __IO uint8_t MaxRdCurrentVDDMax; /*!< Max. read current @ VDD max */ __IO uint8_t MaxWrCurrentVDDMin; /*!< Max. write current @ VDD min */ __IO uint8_t MaxWrCurrentVDDMax; /*!< Max. write current @ VDD max */ __IO uint8_t DeviceSizeMul; /*!< Device size multiplier */ __IO uint8_t EraseGrSize; /*!< Erase group size */ __IO uint8_t EraseGrMul; /*!< Erase group size multiplier */ __IO uint8_t WrProtectGrSize; /*!< Write protect group size */ __IO uint8_t WrProtectGrEnable; /*!< Write protect group enable */ __IO uint8_t ManDeflECC; /*!< Manufacturer default ECC */ __IO uint8_t WrSpeedFact; /*!< Write speed factor */ __IO uint8_t MaxWrBlockLen; /*!< Max. write data block length */ __IO uint8_t WriteBlockPaPartial; /*!< Partial blocks for write allowed */ __IO uint8_t Reserved3; /*!< Reserved */ __IO uint8_t ContentProtectAppli; /*!< Content protection application */ __IO uint8_t FileFormatGrouop; /*!< File format group */ __IO uint8_t CopyFlag; /*!< Copy flag (OTP) */ __IO uint8_t PermWrProtect; /*!< Permanent write protection */ __IO uint8_t TempWrProtect; /*!< Temporary write protection */ __IO uint8_t FileFormat; /*!< File format */ __IO uint8_t ECC; /*!< ECC code */ __IO uint8_t CSD_CRC; /*!< CSD CRC */ __IO uint8_t Reserved4; /*!< Always 1 */ }HAL_SD_CSDTypedef; /** * @brief Card Identification Data: CID Register */ typedef struct { __IO uint8_t ManufacturerID; /*!< Manufacturer ID */ __IO uint16_t OEM_AppliID; /*!< OEM/Application ID */ __IO uint32_t ProdName1; /*!< Product Name part1 */ __IO uint8_t ProdName2; /*!< Product Name part2 */ __IO uint8_t ProdRev; /*!< Product Revision */ __IO uint32_t ProdSN; /*!< Product Serial Number */ __IO uint8_t Reserved1; /*!< Reserved1 */ __IO uint16_t ManufactDate; /*!< Manufacturing Date */ __IO uint8_t CID_CRC; /*!< CID CRC */ __IO uint8_t Reserved2; /*!< Always 1 */ }HAL_SD_CIDTypedef; /** * @brief SD Card Status returned by ACMD13 */ typedef struct { __IO uint8_t DAT_BUS_WIDTH; /*!< Shows the currently defined data bus width */ __IO uint8_t SECURED_MODE; /*!< Card is in secured mode of operation */ __IO uint16_t SD_CARD_TYPE; /*!< Carries information about card type */ __IO uint32_t SIZE_OF_PROTECTED_AREA; /*!< Carries information about the capacity of protected area */ __IO uint8_t SPEED_CLASS; /*!< Carries information about the speed class of the card */ __IO uint8_t PERFORMANCE_MOVE; /*!< Carries information about the card's performance move */ __IO uint8_t AU_SIZE; /*!< Carries information about the card's allocation unit size */ __IO uint16_t ERASE_SIZE; /*!< Determines the number of AUs to be erased in one operation */ __IO uint8_t ERASE_TIMEOUT; /*!< Determines the timeout for any number of AU erase */ __IO uint8_t ERASE_OFFSET; /*!< Carries information about the erase offset */ }HAL_SD_CardStatusTypedef; /** * @brief SD Card information structure */ typedef struct { HAL_SD_CSDTypedef SD_csd; /*!< SD card specific data register */ HAL_SD_CIDTypedef SD_cid; /*!< SD card identification number register */ uint64_t CardCapacity; /*!< Card capacity */ uint32_t CardBlockSize; /*!< Card block size */ uint16_t RCA; /*!< SD relative card address */ uint8_t CardType; /*!< SD card type */ }HAL_SD_CardInfoTypedef; /** * @brief SD Error status enumeration Structure definition */ typedef enum { /** * @brief SD specific error defines */ SD_CMD_CRC_FAIL = (1), /*!< Command response received (but CRC check failed) */ SD_DATA_CRC_FAIL = (2), /*!< Data block sent/received (CRC check failed) */ SD_CMD_RSP_TIMEOUT = (3), /*!< Command response timeout */ SD_DATA_TIMEOUT = (4), /*!< Data timeout */ SD_TX_UNDERRUN = (5), /*!< Transmit FIFO underrun */ SD_RX_OVERRUN = (6), /*!< Receive FIFO overrun */ SD_START_BIT_ERR = (7), /*!< Start bit not detected on all data signals in wide bus mode */ SD_CMD_OUT_OF_RANGE = (8), /*!< Command's argument was out of range. */ SD_ADDR_MISALIGNED = (9), /*!< Misaligned address */ SD_BLOCK_LEN_ERR = (10), /*!< Transferred block length is not allowed for the card or the number of transferred bytes does not match the block length */ SD_ERASE_SEQ_ERR = (11), /*!< An error in the sequence of erase command occurs. */ SD_BAD_ERASE_PARAM = (12), /*!< An invalid selection for erase groups */ SD_WRITE_PROT_VIOLATION = (13), /*!< Attempt to program a write protect block */ SD_LOCK_UNLOCK_FAILED = (14), /*!< Sequence or password error has been detected in unlock command or if there was an attempt to access a locked card */ SD_COM_CRC_FAILED = (15), /*!< CRC check of the previous command failed */ SD_ILLEGAL_CMD = (16), /*!< Command is not legal for the card state */ SD_CARD_ECC_FAILED = (17), /*!< Card internal ECC was applied but failed to correct the data */ SD_CC_ERROR = (18), /*!< Internal card controller error */ SD_GENERAL_UNKNOWN_ERROR = (19), /*!< General or unknown error */ SD_STREAM_READ_UNDERRUN = (20), /*!< The card could not sustain data transfer in stream read operation. */ SD_STREAM_WRITE_OVERRUN = (21), /*!< The card could not sustain data programming in stream mode */ SD_CID_CSD_OVERWRITE = (22), /*!< CID/CSD overwrite error */ SD_WP_ERASE_SKIP = (23), /*!< Only partial address space was erased */ SD_CARD_ECC_DISABLED = (24), /*!< Command has been executed without using internal ECC */ SD_ERASE_RESET = (25), /*!< Erase sequence was cleared before executing because an out of erase sequence command was received */ SD_AKE_SEQ_ERROR = (26), /*!< Error in sequence of authentication. */ SD_INVALID_VOLTRANGE = (27), SD_ADDR_OUT_OF_RANGE = (28), SD_SWITCH_ERROR = (29), SD_SDIO_DISABLED = (30), SD_SDIO_FUNCTION_BUSY = (31), SD_SDIO_FUNCTION_FAILED = (32), SD_SDIO_UNKNOWN_FUNCTION = (33), /** * @brief Standard error defines */ SD_INTERNAL_ERROR = (34), SD_NOT_CONFIGURED = (35), SD_REQUEST_PENDING = (36), SD_REQUEST_NOT_APPLICABLE = (37), SD_INVALID_PARAMETER = (38), SD_UNSUPPORTED_FEATURE = (39), SD_UNSUPPORTED_HW = (40), SD_ERROR = (41), SD_OK = (0) }HAL_SD_ErrorTypedef; /** * @brief SD Transfer state enumeration structure */ typedef enum { SD_TRANSFER_OK = 0, /*!< Transfer success */ SD_TRANSFER_BUSY = 1, /*!< Transfer is occurring */ SD_TRANSFER_ERROR = 2 /*!< Transfer failed */ }HAL_SD_TransferStateTypedef; /** * @brief SD Card State enumeration structure */ typedef enum { SD_CARD_READY = ((uint32_t)0x00000001), /*!< Card state is ready */ SD_CARD_IDENTIFICATION = ((uint32_t)0x00000002), /*!< Card is in identification state */ SD_CARD_STANDBY = ((uint32_t)0x00000003), /*!< Card is in standby state */ SD_CARD_TRANSFER = ((uint32_t)0x00000004), /*!< Card is in transfer state */ SD_CARD_SENDING = ((uint32_t)0x00000005), /*!< Card is sending an operation */ SD_CARD_RECEIVING = ((uint32_t)0x00000006), /*!< Card is receiving operation information */ SD_CARD_PROGRAMMING = ((uint32_t)0x00000007), /*!< Card is in programming state */ SD_CARD_DISCONNECTED = ((uint32_t)0x00000008), /*!< Card is disconnected */ SD_CARD_ERROR = ((uint32_t)0x000000FF) /*!< Card is in error state */ }HAL_SD_CardStateTypedef; /** * @brief SD Operation enumeration structure */ typedef enum { SD_READ_SINGLE_BLOCK = 0, /*!< Read single block operation */ SD_READ_MULTIPLE_BLOCK = 1, /*!< Read multiple blocks operation */ SD_WRITE_SINGLE_BLOCK = 2, /*!< Write single block operation */ SD_WRITE_MULTIPLE_BLOCK = 3 /*!< Write multiple blocks operation */ }HAL_SD_OperationTypedef; /** * @} */ /* Exported constants --------------------------------------------------------*/ /** @defgroup SD_Exported_Constants SD Exported Constants * @{ */ /** * @brief SD Commands Index */ #define SD_CMD_GO_IDLE_STATE ((uint8_t)0) /*!< Resets the SD memory card. */ #define SD_CMD_SEND_OP_COND ((uint8_t)1) /*!< Sends host capacity support information and activates the card's initialization process. */ #define SD_CMD_ALL_SEND_CID ((uint8_t)2) /*!< Asks any card connected to the host to send the CID numbers on the CMD line. */ #define SD_CMD_SET_REL_ADDR ((uint8_t)3) /*!< Asks the card to publish a new relative address (RCA). */ #define SD_CMD_SET_DSR ((uint8_t)4) /*!< Programs the DSR of all cards. */ #define SD_CMD_SDIO_SEN_OP_COND ((uint8_t)5) /*!< Sends host capacity support information (HCS) and asks the accessed card to send its operating condition register (OCR) content in the response on the CMD line. */ #define SD_CMD_HS_SWITCH ((uint8_t)6) /*!< Checks switchable function (mode 0) and switch card function (mode 1). */ #define SD_CMD_SEL_DESEL_CARD ((uint8_t)7) /*!< Selects the card by its own relative address and gets deselected by any other address */ #define SD_CMD_HS_SEND_EXT_CSD ((uint8_t)8) /*!< Sends SD Memory Card interface condition, which includes host supply voltage information and asks the card whether card supports voltage. */ #define SD_CMD_SEND_CSD ((uint8_t)9) /*!< Addressed card sends its card specific data (CSD) on the CMD line. */ #define SD_CMD_SEND_CID ((uint8_t)10) /*!< Addressed card sends its card identification (CID) on the CMD line. */ #define SD_CMD_READ_DAT_UNTIL_STOP ((uint8_t)11) /*!< SD card doesn't support it. */ #define SD_CMD_STOP_TRANSMISSION ((uint8_t)12) /*!< Forces the card to stop transmission. */ #define SD_CMD_SEND_STATUS ((uint8_t)13) /*!< Addressed card sends its status register. */ #define SD_CMD_HS_BUSTEST_READ ((uint8_t)14) #define SD_CMD_GO_INACTIVE_STATE ((uint8_t)15) /*!< Sends an addressed card into the inactive state. */ #define SD_CMD_SET_BLOCKLEN ((uint8_t)16) /*!< Sets the block length (in bytes for SDSC) for all following block commands (read, write, lock). Default block length is fixed to 512 Bytes. Not effective for SDHS and SDXC. */ #define SD_CMD_READ_SINGLE_BLOCK ((uint8_t)17) /*!< Reads single block of size selected by SET_BLOCKLEN in case of SDSC, and a block of fixed 512 bytes in case of SDHC and SDXC. */ #define SD_CMD_READ_MULT_BLOCK ((uint8_t)18) /*!< Continuously transfers data blocks from card to host until interrupted by STOP_TRANSMISSION command. */ #define SD_CMD_HS_BUSTEST_WRITE ((uint8_t)19) /*!< 64 bytes tuning pattern is sent for SDR50 and SDR104. */ #define SD_CMD_WRITE_DAT_UNTIL_STOP ((uint8_t)20) /*!< Speed class control command. */ #define SD_CMD_SET_BLOCK_COUNT ((uint8_t)23) /*!< Specify block count for CMD18 and CMD25. */ #define SD_CMD_WRITE_SINGLE_BLOCK ((uint8_t)24) /*!< Writes single block of size selected by SET_BLOCKLEN in case of SDSC, and a block of fixed 512 bytes in case of SDHC and SDXC. */ #define SD_CMD_WRITE_MULT_BLOCK ((uint8_t)25) /*!< Continuously writes blocks of data until a STOP_TRANSMISSION follows. */ #define SD_CMD_PROG_CID ((uint8_t)26) /*!< Reserved for manufacturers. */ #define SD_CMD_PROG_CSD ((uint8_t)27) /*!< Programming of the programmable bits of the CSD. */ #define SD_CMD_SET_WRITE_PROT ((uint8_t)28) /*!< Sets the write protection bit of the addressed group. */ #define SD_CMD_CLR_WRITE_PROT ((uint8_t)29) /*!< Clears the write protection bit of the addressed group. */ #define SD_CMD_SEND_WRITE_PROT ((uint8_t)30) /*!< Asks the card to send the status of the write protection bits. */ #define SD_CMD_SD_ERASE_GRP_START ((uint8_t)32) /*!< Sets the address of the first write block to be erased. (For SD card only). */ #define SD_CMD_SD_ERASE_GRP_END ((uint8_t)33) /*!< Sets the address of the last write block of the continuous range to be erased. */ #define SD_CMD_ERASE_GRP_START ((uint8_t)35) /*!< Sets the address of the first write block to be erased. Reserved for each command system set by switch function command (CMD6). */ #define SD_CMD_ERASE_GRP_END ((uint8_t)36) /*!< Sets the address of the last write block of the continuous range to be erased. Reserved for each command system set by switch function command (CMD6). */ #define SD_CMD_ERASE ((uint8_t)38) /*!< Reserved for SD security applications. */ #define SD_CMD_FAST_IO ((uint8_t)39) /*!< SD card doesn't support it (Reserved). */ #define SD_CMD_GO_IRQ_STATE ((uint8_t)40) /*!< SD card doesn't support it (Reserved). */ #define SD_CMD_LOCK_UNLOCK ((uint8_t)42) /*!< Sets/resets the password or lock/unlock the card. The size of the data block is set by the SET_BLOCK_LEN command. */ #define SD_CMD_APP_CMD ((uint8_t)55) /*!< Indicates to the card that the next command is an application specific command rather than a standard command. */ #define SD_CMD_GEN_CMD ((uint8_t)56) /*!< Used either to transfer a data block to the card or to get a data block from the card for general purpose/application specific commands. */ #define SD_CMD_NO_CMD ((uint8_t)64) /** * @brief Following commands are SD Card Specific commands. * SDIO_APP_CMD should be sent before sending these commands. */ #define SD_CMD_APP_SD_SET_BUSWIDTH ((uint8_t)6) /*!< (ACMD6) Defines the data bus width to be used for data transfer. The allowed data bus widths are given in SCR register. */ #define SD_CMD_SD_APP_STAUS ((uint8_t)13) /*!< (ACMD13) Sends the SD status. */ #define SD_CMD_SD_APP_SEND_NUM_WRITE_BLOCKS ((uint8_t)22) /*!< (ACMD22) Sends the number of the written (without errors) write blocks. Responds with 32bit+CRC data block. */ #define SD_CMD_SD_APP_OP_COND ((uint8_t)41) /*!< (ACMD41) Sends host capacity support information (HCS) and asks the accessed card to send its operating condition register (OCR) content in the response on the CMD line. */ #define SD_CMD_SD_APP_SET_CLR_CARD_DETECT ((uint8_t)42) /*!< (ACMD42) Connects/Disconnects the 50 KOhm pull-up resistor on CD/DAT3 (pin 1) of the card. */ #define SD_CMD_SD_APP_SEND_SCR ((uint8_t)51) /*!< Reads the SD Configuration Register (SCR). */ #define SD_CMD_SDIO_RW_DIRECT ((uint8_t)52) /*!< For SD I/O card only, reserved for security specification. */ #define SD_CMD_SDIO_RW_EXTENDED ((uint8_t)53) /*!< For SD I/O card only, reserved for security specification. */ /** * @brief Following commands are SD Card Specific security commands. * SD_CMD_APP_CMD should be sent before sending these commands. */ #define SD_CMD_SD_APP_GET_MKB ((uint8_t)43) /*!< For SD card only */ #define SD_CMD_SD_APP_GET_MID ((uint8_t)44) /*!< For SD card only */ #define SD_CMD_SD_APP_SET_CER_RN1 ((uint8_t)45) /*!< For SD card only */ #define SD_CMD_SD_APP_GET_CER_RN2 ((uint8_t)46) /*!< For SD card only */ #define SD_CMD_SD_APP_SET_CER_RES2 ((uint8_t)47) /*!< For SD card only */ #define SD_CMD_SD_APP_GET_CER_RES1 ((uint8_t)48) /*!< For SD card only */ #define SD_CMD_SD_APP_SECURE_READ_MULTIPLE_BLOCK ((uint8_t)18) /*!< For SD card only */ #define SD_CMD_SD_APP_SECURE_WRITE_MULTIPLE_BLOCK ((uint8_t)25) /*!< For SD card only */ #define SD_CMD_SD_APP_SECURE_ERASE ((uint8_t)38) /*!< For SD card only */ #define SD_CMD_SD_APP_CHANGE_SECURE_AREA ((uint8_t)49) /*!< For SD card only */ #define SD_CMD_SD_APP_SECURE_WRITE_MKB ((uint8_t)48) /*!< For SD card only */ /** * @brief Supported SD Memory Cards */ #define STD_CAPACITY_SD_CARD_V1_1 ((uint32_t)0x00000000) #define STD_CAPACITY_SD_CARD_V2_0 ((uint32_t)0x00000001) #define HIGH_CAPACITY_SD_CARD ((uint32_t)0x00000002) #define MULTIMEDIA_CARD ((uint32_t)0x00000003) #define SECURE_DIGITAL_IO_CARD ((uint32_t)0x00000004) #define HIGH_SPEED_MULTIMEDIA_CARD ((uint32_t)0x00000005) #define SECURE_DIGITAL_IO_COMBO_CARD ((uint32_t)0x00000006) #define HIGH_CAPACITY_MMC_CARD ((uint32_t)0x00000007) /** * @} */ /* Exported macro ------------------------------------------------------------*/ /** @defgroup SD_Exported_macros SD Exported Macros * @brief macros to handle interrupts and specific clock configurations * @{ */ /** * @brief Enable the SD device. * @retval None */ #define __HAL_SD_SDIO_ENABLE() __SDIO_ENABLE() /** * @brief Disable the SD device. * @retval None */ #define __HAL_SD_SDIO_DISABLE() __SDIO_DISABLE() /** * @brief Enable the SDIO DMA transfer. * @retval None */ #define __HAL_SD_SDIO_DMA_ENABLE() __SDIO_DMA_ENABLE() /** * @brief Disable the SDIO DMA transfer. * @retval None */ #define __HAL_SD_SDIO_DMA_DISABLE() __SDIO_DMA_DISABLE() /** * @brief Enable the SD device interrupt. * @param __HANDLE__: SD Handle * @param __INTERRUPT__: specifies the SDIO interrupt sources to be enabled. * This parameter can be one or a combination of the following values: * @arg SDIO_IT_CCRCFAIL: Command response received (CRC check failed) interrupt * @arg SDIO_IT_DCRCFAIL: Data block sent/received (CRC check failed) interrupt * @arg SDIO_IT_CTIMEOUT: Command response timeout interrupt * @arg SDIO_IT_DTIMEOUT: Data timeout interrupt * @arg SDIO_IT_TXUNDERR: Transmit FIFO underrun error interrupt * @arg SDIO_IT_RXOVERR: Received FIFO overrun error interrupt * @arg SDIO_IT_CMDREND: Command response received (CRC check passed) interrupt * @arg SDIO_IT_CMDSENT: Command sent (no response required) interrupt * @arg SDIO_IT_DATAEND: Data end (data counter, SDIDCOUNT, is zero) interrupt * @arg SDIO_IT_STBITERR: Start bit not detected on all data signals in wide * bus mode interrupt * @arg SDIO_IT_DBCKEND: Data block sent/received (CRC check passed) interrupt * @arg SDIO_IT_CMDACT: Command transfer in progress interrupt * @arg SDIO_IT_TXACT: Data transmit in progress interrupt * @arg SDIO_IT_RXACT: Data receive in progress interrupt * @arg SDIO_IT_TXFIFOHE: Transmit FIFO Half Empty interrupt * @arg SDIO_IT_RXFIFOHF: Receive FIFO Half Full interrupt * @arg SDIO_IT_TXFIFOF: Transmit FIFO full interrupt * @arg SDIO_IT_RXFIFOF: Receive FIFO full interrupt * @arg SDIO_IT_TXFIFOE: Transmit FIFO empty interrupt * @arg SDIO_IT_RXFIFOE: Receive FIFO empty interrupt * @arg SDIO_IT_TXDAVL: Data available in transmit FIFO interrupt * @arg SDIO_IT_RXDAVL: Data available in receive FIFO interrupt * @arg SDIO_IT_SDIOIT: SD I/O interrupt received interrupt * @arg SDIO_IT_CEATAEND: CE-ATA command completion signal received for CMD61 interrupt * @retval None */ #define __HAL_SD_SDIO_ENABLE_IT(__HANDLE__, __INTERRUPT__) __SDIO_ENABLE_IT((__HANDLE__)->Instance, (__INTERRUPT__)) /** * @brief Disable the SD device interrupt. * @param __HANDLE__: SD Handle * @param __INTERRUPT__: specifies the SDIO interrupt sources to be disabled. * This parameter can be one or a combination of the following values: * @arg SDIO_IT_CCRCFAIL: Command response received (CRC check failed) interrupt * @arg SDIO_IT_DCRCFAIL: Data block sent/received (CRC check failed) interrupt * @arg SDIO_IT_CTIMEOUT: Command response timeout interrupt * @arg SDIO_IT_DTIMEOUT: Data timeout interrupt * @arg SDIO_IT_TXUNDERR: Transmit FIFO underrun error interrupt * @arg SDIO_IT_RXOVERR: Received FIFO overrun error interrupt * @arg SDIO_IT_CMDREND: Command response received (CRC check passed) interrupt * @arg SDIO_IT_CMDSENT: Command sent (no response required) interrupt * @arg SDIO_IT_DATAEND: Data end (data counter, SDIDCOUNT, is zero) interrupt * @arg SDIO_IT_STBITERR: Start bit not detected on all data signals in wide * bus mode interrupt * @arg SDIO_IT_DBCKEND: Data block sent/received (CRC check passed) interrupt * @arg SDIO_IT_CMDACT: Command transfer in progress interrupt * @arg SDIO_IT_TXACT: Data transmit in progress interrupt * @arg SDIO_IT_RXACT: Data receive in progress interrupt * @arg SDIO_IT_TXFIFOHE: Transmit FIFO Half Empty interrupt * @arg SDIO_IT_RXFIFOHF: Receive FIFO Half Full interrupt * @arg SDIO_IT_TXFIFOF: Transmit FIFO full interrupt * @arg SDIO_IT_RXFIFOF: Receive FIFO full interrupt * @arg SDIO_IT_TXFIFOE: Transmit FIFO empty interrupt * @arg SDIO_IT_RXFIFOE: Receive FIFO empty interrupt * @arg SDIO_IT_TXDAVL: Data available in transmit FIFO interrupt * @arg SDIO_IT_RXDAVL: Data available in receive FIFO interrupt * @arg SDIO_IT_SDIOIT: SD I/O interrupt received interrupt * @arg SDIO_IT_CEATAEND: CE-ATA command completion signal received for CMD61 interrupt * @retval None */ #define __HAL_SD_SDIO_DISABLE_IT(__HANDLE__, __INTERRUPT__) __SDIO_DISABLE_IT((__HANDLE__)->Instance, (__INTERRUPT__)) /** * @brief Check whether the specified SD flag is set or not. * @param __HANDLE__: SD Handle * @param __FLAG__: specifies the flag to check. * This parameter can be one of the following values: * @arg SDIO_FLAG_CCRCFAIL: Command response received (CRC check failed) * @arg SDIO_FLAG_DCRCFAIL: Data block sent/received (CRC check failed) * @arg SDIO_FLAG_CTIMEOUT: Command response timeout * @arg SDIO_FLAG_DTIMEOUT: Data timeout * @arg SDIO_FLAG_TXUNDERR: Transmit FIFO underrun error * @arg SDIO_FLAG_RXOVERR: Received FIFO overrun error * @arg SDIO_FLAG_CMDREND: Command response received (CRC check passed) * @arg SDIO_FLAG_CMDSENT: Command sent (no response required) * @arg SDIO_FLAG_DATAEND: Data end (data counter, SDIDCOUNT, is zero) * @arg SDIO_FLAG_STBITERR: Start bit not detected on all data signals in wide bus mode. * @arg SDIO_FLAG_DBCKEND: Data block sent/received (CRC check passed) * @arg SDIO_FLAG_CMDACT: Command transfer in progress * @arg SDIO_FLAG_TXACT: Data transmit in progress * @arg SDIO_FLAG_RXACT: Data receive in progress * @arg SDIO_FLAG_TXFIFOHE: Transmit FIFO Half Empty * @arg SDIO_FLAG_RXFIFOHF: Receive FIFO Half Full * @arg SDIO_FLAG_TXFIFOF: Transmit FIFO full * @arg SDIO_FLAG_RXFIFOF: Receive FIFO full * @arg SDIO_FLAG_TXFIFOE: Transmit FIFO empty * @arg SDIO_FLAG_RXFIFOE: Receive FIFO empty * @arg SDIO_FLAG_TXDAVL: Data available in transmit FIFO * @arg SDIO_FLAG_RXDAVL: Data available in receive FIFO * @arg SDIO_FLAG_SDIOIT: SD I/O interrupt received * @arg SDIO_FLAG_CEATAEND: CE-ATA command completion signal received for CMD61 * @retval The new state of SD FLAG (SET or RESET). */ #define __HAL_SD_SDIO_GET_FLAG(__HANDLE__, __FLAG__) __SDIO_GET_FLAG((__HANDLE__)->Instance, (__FLAG__)) /** * @brief Clear the SD's pending flags. * @param __HANDLE__: SD Handle * @param __FLAG__: specifies the flag to clear. * This parameter can be one or a combination of the following values: * @arg SDIO_FLAG_CCRCFAIL: Command response received (CRC check failed) * @arg SDIO_FLAG_DCRCFAIL: Data block sent/received (CRC check failed) * @arg SDIO_FLAG_CTIMEOUT: Command response timeout * @arg SDIO_FLAG_DTIMEOUT: Data timeout * @arg SDIO_FLAG_TXUNDERR: Transmit FIFO underrun error * @arg SDIO_FLAG_RXOVERR: Received FIFO overrun error * @arg SDIO_FLAG_CMDREND: Command response received (CRC check passed) * @arg SDIO_FLAG_CMDSENT: Command sent (no response required) * @arg SDIO_FLAG_DATAEND: Data end (data counter, SDIDCOUNT, is zero) * @arg SDIO_FLAG_STBITERR: Start bit not detected on all data signals in wide bus mode * @arg SDIO_FLAG_DBCKEND: Data block sent/received (CRC check passed) * @arg SDIO_FLAG_SDIOIT: SD I/O interrupt received * @arg SDIO_FLAG_CEATAEND: CE-ATA command completion signal received for CMD61 * @retval None */ #define __HAL_SD_SDIO_CLEAR_FLAG(__HANDLE__, __FLAG__) __SDIO_CLEAR_FLAG((__HANDLE__)->Instance, (__FLAG__)) /** * @brief Check whether the specified SD interrupt has occurred or not. * @param __HANDLE__: SD Handle * @param __INTERRUPT__: specifies the SDIO interrupt source to check. * This parameter can be one of the following values: * @arg SDIO_IT_CCRCFAIL: Command response received (CRC check failed) interrupt * @arg SDIO_IT_DCRCFAIL: Data block sent/received (CRC check failed) interrupt * @arg SDIO_IT_CTIMEOUT: Command response timeout interrupt * @arg SDIO_IT_DTIMEOUT: Data timeout interrupt * @arg SDIO_IT_TXUNDERR: Transmit FIFO underrun error interrupt * @arg SDIO_IT_RXOVERR: Received FIFO overrun error interrupt * @arg SDIO_IT_CMDREND: Command response received (CRC check passed) interrupt * @arg SDIO_IT_CMDSENT: Command sent (no response required) interrupt * @arg SDIO_IT_DATAEND: Data end (data counter, SDIDCOUNT, is zero) interrupt * @arg SDIO_IT_STBITERR: Start bit not detected on all data signals in wide * bus mode interrupt * @arg SDIO_IT_DBCKEND: Data block sent/received (CRC check passed) interrupt * @arg SDIO_IT_CMDACT: Command transfer in progress interrupt * @arg SDIO_IT_TXACT: Data transmit in progress interrupt * @arg SDIO_IT_RXACT: Data receive in progress interrupt * @arg SDIO_IT_TXFIFOHE: Transmit FIFO Half Empty interrupt * @arg SDIO_IT_RXFIFOHF: Receive FIFO Half Full interrupt * @arg SDIO_IT_TXFIFOF: Transmit FIFO full interrupt * @arg SDIO_IT_RXFIFOF: Receive FIFO full interrupt * @arg SDIO_IT_TXFIFOE: Transmit FIFO empty interrupt * @arg SDIO_IT_RXFIFOE: Receive FIFO empty interrupt * @arg SDIO_IT_TXDAVL: Data available in transmit FIFO interrupt * @arg SDIO_IT_RXDAVL: Data available in receive FIFO interrupt * @arg SDIO_IT_SDIOIT: SD I/O interrupt received interrupt * @arg SDIO_IT_CEATAEND: CE-ATA command completion signal received for CMD61 interrupt * @retval The new state of SD IT (SET or RESET). */ #define __HAL_SD_SDIO_GET_IT (__HANDLE__, __INTERRUPT__) __SDIO_GET_IT ((__HANDLE__)->Instance, __INTERRUPT__) /** * @brief Clear the SD's interrupt pending bits. * @param __HANDLE__ : SD Handle * @param __INTERRUPT__: specifies the interrupt pending bit to clear. * This parameter can be one or a combination of the following values: * @arg SDIO_IT_CCRCFAIL: Command response received (CRC check failed) interrupt * @arg SDIO_IT_DCRCFAIL: Data block sent/received (CRC check failed) interrupt * @arg SDIO_IT_CTIMEOUT: Command response timeout interrupt * @arg SDIO_IT_DTIMEOUT: Data timeout interrupt * @arg SDIO_IT_TXUNDERR: Transmit FIFO underrun error interrupt * @arg SDIO_IT_RXOVERR: Received FIFO overrun error interrupt * @arg SDIO_IT_CMDREND: Command response received (CRC check passed) interrupt * @arg SDIO_IT_CMDSENT: Command sent (no response required) interrupt * @arg SDIO_IT_DATAEND: Data end (data counter, SDIO_DCOUNT, is zero) interrupt * @arg SDIO_IT_STBITERR: Start bit not detected on all data signals in wide * bus mode interrupt * @arg SDIO_IT_SDIOIT: SD I/O interrupt received interrupt * @arg SDIO_IT_CEATAEND: CE-ATA command completion signal received for CMD61 * @retval None */ #define __HAL_SD_SDIO_CLEAR_IT(__HANDLE__, __INTERRUPT__) __SDIO_CLEAR_IT((__HANDLE__)->Instance, (__INTERRUPT__)) /** * @} */ /* Exported functions --------------------------------------------------------*/ /** @addtogroup SD_Exported_Functions * @{ */ /* Initialization and de-initialization functions **********************************/ /** @addtogroup SD_Exported_Functions_Group1 * @{ */ HAL_SD_ErrorTypedef HAL_SD_Init(SD_HandleTypeDef *hsd, HAL_SD_CardInfoTypedef *SDCardInfo); HAL_StatusTypeDef HAL_SD_DeInit (SD_HandleTypeDef *hsd); void HAL_SD_MspInit(SD_HandleTypeDef *hsd); void HAL_SD_MspDeInit(SD_HandleTypeDef *hsd); /** * @} */ /* I/O operation functions *****************************************************/ /** @addtogroup SD_Exported_Functions_Group2 * @{ */ /* Blocking mode: Polling */ HAL_SD_ErrorTypedef HAL_SD_ReadBlocks(SD_HandleTypeDef *hsd, uint32_t *pReadBuffer, uint64_t ReadAddr, uint32_t BlockSize, uint32_t NumberOfBlocks); HAL_SD_ErrorTypedef HAL_SD_WriteBlocks(SD_HandleTypeDef *hsd, uint32_t *pWriteBuffer, uint64_t WriteAddr, uint32_t BlockSize, uint32_t NumberOfBlocks); HAL_SD_ErrorTypedef HAL_SD_Erase(SD_HandleTypeDef *hsd, uint64_t startaddr, uint64_t endaddr); /* Non-Blocking mode: Interrupt */ void HAL_SD_IRQHandler(SD_HandleTypeDef *hsd); /* Callback in non blocking modes (DMA) */ void HAL_SD_DMA_RxCpltCallback(DMA_HandleTypeDef *hdma); void HAL_SD_DMA_RxErrorCallback(DMA_HandleTypeDef *hdma); void HAL_SD_DMA_TxCpltCallback(DMA_HandleTypeDef *hdma); void HAL_SD_DMA_TxErrorCallback(DMA_HandleTypeDef *hdma); void HAL_SD_XferCpltCallback(SD_HandleTypeDef *hsd); void HAL_SD_XferErrorCallback(SD_HandleTypeDef *hsd); /* Non-Blocking mode: DMA */ HAL_SD_ErrorTypedef HAL_SD_ReadBlocks_DMA(SD_HandleTypeDef *hsd, uint32_t *pReadBuffer, uint64_t ReadAddr, uint32_t BlockSize, uint32_t NumberOfBlocks); HAL_SD_ErrorTypedef HAL_SD_WriteBlocks_DMA(SD_HandleTypeDef *hsd, uint32_t *pWriteBuffer, uint64_t WriteAddr, uint32_t BlockSize, uint32_t NumberOfBlocks); HAL_SD_ErrorTypedef HAL_SD_CheckWriteOperation(SD_HandleTypeDef *hsd, uint32_t Timeout); HAL_SD_ErrorTypedef HAL_SD_CheckReadOperation(SD_HandleTypeDef *hsd, uint32_t Timeout); /** * @} */ /* Peripheral Control functions ************************************************/ /** @addtogroup SD_Exported_Functions_Group3 * @{ */ HAL_SD_ErrorTypedef HAL_SD_Get_CardInfo(SD_HandleTypeDef *hsd, HAL_SD_CardInfoTypedef *pCardInfo); HAL_SD_ErrorTypedef HAL_SD_WideBusOperation_Config(SD_HandleTypeDef *hsd, uint32_t WideMode); HAL_SD_ErrorTypedef HAL_SD_StopTransfer(SD_HandleTypeDef *hsd); HAL_SD_ErrorTypedef HAL_SD_HighSpeed (SD_HandleTypeDef *hsd); /** * @} */ /* Peripheral State functions **************************************************/ /** @addtogroup SD_Exported_Functions_Group4 * @{ */ HAL_SD_ErrorTypedef HAL_SD_SendSDStatus(SD_HandleTypeDef *hsd, uint32_t *pSDstatus); HAL_SD_ErrorTypedef HAL_SD_GetCardStatus(SD_HandleTypeDef *hsd, HAL_SD_CardStatusTypedef *pCardStatus); HAL_SD_TransferStateTypedef HAL_SD_GetStatus(SD_HandleTypeDef *hsd); /** * @} */ /** * @} */ /** * @} */ /** * @} */ #ifdef __cplusplus } #endif #endif /* STM32L151xD || STM32L152xD || STM32L162xD */ #endif /* __STM32L1xx_HAL_SD_H */ /************************ (C) COPYRIGHT STMicroelectronics *****END OF FILE****/ ================================================ FILE: Zelig/mbed/TARGET_NUCLEO_L152RE/stm32l1xx_hal_smartcard.h ================================================ /** ****************************************************************************** * @file stm32l1xx_hal_smartcard.h * @author MCD Application Team * @version V1.0.0 * @date 5-September-2014 * @brief This file contains all the functions prototypes for the SMARTCARD * firmware library. ****************************************************************************** * @attention * *

© COPYRIGHT(c) 2014 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. * ****************************************************************************** */ /* Define to prevent recursive inclusion -------------------------------------*/ #ifndef __STM32L1xx_HAL_SMARTCARD_H #define __STM32L1xx_HAL_SMARTCARD_H #ifdef __cplusplus extern "C" { #endif /* Includes ------------------------------------------------------------------*/ #include "stm32l1xx_hal_def.h" /** @addtogroup STM32L1xx_HAL_Driver * @{ */ /** @addtogroup SMARTCARD * @{ */ /* Exported types ------------------------------------------------------------*/ /** @defgroup SMARTCARD_Exported_Types SMARTCARD Exported Types * @{ */ /** * @brief SMARTCARD Init Structure definition */ typedef struct { uint32_t BaudRate; /*!< This member configures the SmartCard communication baud rate. The baud rate is computed using the following formula: - IntegerDivider = ((PCLKx) / (8 * (hsc->Init.BaudRate))) - FractionalDivider = ((IntegerDivider - ((uint32_t) IntegerDivider)) * 8) + 0.5 */ uint32_t WordLength; /*!< Specifies the number of data bits transmitted or received in a frame. This parameter can be a value of @ref SMARTCARD_Word_Length */ uint32_t StopBits; /*!< Specifies the number of stop bits transmitted. This parameter can be a value of @ref SMARTCARD_Stop_Bits */ uint32_t Parity; /*!< Specifies the parity mode. This parameter can be a value of @ref SMARTCARD_Parity @note When parity is enabled, the computed parity is inserted at the MSB position of the transmitted data (9th bit when the word length is set to 9 data bits; 8th bit when the word length is set to 8 data bits).*/ uint32_t Mode; /*!< Specifies wether the Receive or Transmit mode is enabled or disabled. This parameter can be a value of @ref SMARTCARD_Mode */ uint32_t CLKPolarity; /*!< Specifies the steady state of the serial clock. This parameter can be a value of @ref SMARTCARD_Clock_Polarity */ uint32_t CLKPhase; /*!< Specifies the clock transition on which the bit capture is made. This parameter can be a value of @ref SMARTCARD_Clock_Phase */ uint32_t CLKLastBit; /*!< Specifies whether the clock pulse corresponding to the last transmitted data bit (MSB) has to be output on the SCLK pin in synchronous mode. This parameter can be a value of @ref SMARTCARD_Last_Bit */ uint32_t Prescaler; /*!< Specifies the SmartCard Prescaler This parameter must be a number between Min_Data = 0 and Max_Data = 255 */ uint32_t GuardTime; /*!< Specifies the SmartCard Guard Time This parameter must be a number between Min_Data = 0 and Max_Data = 255 */ uint32_t NACKState; /*!< Specifies the SmartCard NACK Transmission state This parameter can be a value of @ref SMARTCARD_NACK_State */ }SMARTCARD_InitTypeDef; /** * @brief HAL State structures definition */ typedef enum { HAL_SMARTCARD_STATE_RESET = 0x00, /*!< Peripheral is not yet Initialized */ HAL_SMARTCARD_STATE_READY = 0x01, /*!< Peripheral Initialized and ready for use */ HAL_SMARTCARD_STATE_BUSY = 0x02, /*!< an internal process is ongoing */ HAL_SMARTCARD_STATE_BUSY_TX = 0x12, /*!< Data Transmission process is ongoing */ HAL_SMARTCARD_STATE_BUSY_RX = 0x22, /*!< Data Reception process is ongoing */ HAL_SMARTCARD_STATE_BUSY_TX_RX = 0x32, /*!< Data Transmission and Reception process is ongoing */ HAL_SMARTCARD_STATE_TIMEOUT = 0x03, /*!< Timeout state */ HAL_SMARTCARD_STATE_ERROR = 0x04 /*!< Error */ }HAL_SMARTCARD_StateTypeDef; /** * @brief HAL SMARTCARD Error Code structure definition */ typedef enum { HAL_SMARTCARD_ERROR_NONE = 0x00, /*!< No error */ HAL_SMARTCARD_ERROR_PE = 0x01, /*!< Parity error */ HAL_SMARTCARD_ERROR_NE = 0x02, /*!< Noise error */ HAL_SMARTCARD_ERROR_FE = 0x04, /*!< frame error */ HAL_SMARTCARD_ERROR_ORE = 0x08, /*!< Overrun error */ HAL_SMARTCARD_ERROR_DMA = 0x10 /*!< DMA transfer error */ }HAL_SMARTCARD_ErrorTypeDef; /** * @brief SMARTCARD handle Structure definition */ typedef struct { USART_TypeDef *Instance; /* USART registers base address */ SMARTCARD_InitTypeDef Init; /* SmartCard communication parameters */ uint8_t *pTxBuffPtr; /* Pointer to SmartCard Tx transfer Buffer */ uint16_t TxXferSize; /* SmartCard Tx Transfer size */ uint16_t TxXferCount; /* SmartCard Tx Transfer Counter */ uint8_t *pRxBuffPtr; /* Pointer to SmartCard Rx transfer Buffer */ uint16_t RxXferSize; /* SmartCard Rx Transfer size */ uint16_t RxXferCount; /* SmartCard Rx Transfer Counter */ DMA_HandleTypeDef *hdmatx; /* SmartCard Tx DMA Handle parameters */ DMA_HandleTypeDef *hdmarx; /* SmartCard Rx DMA Handle parameters */ HAL_LockTypeDef Lock; /* Locking object */ __IO HAL_SMARTCARD_StateTypeDef State; /* SmartCard communication state */ __IO HAL_SMARTCARD_ErrorTypeDef ErrorCode; /* SmartCard Error code */ }SMARTCARD_HandleTypeDef; /** * @} */ /* Exported constants --------------------------------------------------------*/ /** @defgroup SMARTCARD_Exported_Constants SMARTCARD Exported constants * @{ */ /** @defgroup SMARTCARD_Word_Length SMARTCARD Word Length * @{ */ #define SMARTCARD_WORDLENGTH_8B ((uint32_t)0x00000000) #define SMARTCARD_WORDLENGTH_9B ((uint32_t)USART_CR1_M) #define IS_SMARTCARD_WORD_LENGTH(LENGTH) ((LENGTH) == SMARTCARD_WORDLENGTH_9B) /** * @} */ /** @defgroup SMARTCARD_Stop_Bits SMARTCARD Number of Stop Bits * @{ */ #define SMARTCARD_STOPBITS_1 ((uint32_t)0x00000000) #define SMARTCARD_STOPBITS_0_5 ((uint32_t)USART_CR2_STOP_0) #define SMARTCARD_STOPBITS_2 ((uint32_t)USART_CR2_STOP_1) #define SMARTCARD_STOPBITS_1_5 ((uint32_t)(USART_CR2_STOP_0 | USART_CR2_STOP_1)) #define IS_SMARTCARD_STOPBITS(STOPBITS) (((STOPBITS) == SMARTCARD_STOPBITS_0_5) || \ ((STOPBITS) == SMARTCARD_STOPBITS_1_5)) /** * @} */ /** @defgroup SMARTCARD_Parity SMARTCARD Parity * @{ */ #define SMARTCARD_PARITY_NONE ((uint32_t)0x00000000) #define SMARTCARD_PARITY_EVEN ((uint32_t)USART_CR1_PCE) #define SMARTCARD_PARITY_ODD ((uint32_t)(USART_CR1_PCE | USART_CR1_PS)) #define IS_SMARTCARD_PARITY(PARITY) (((PARITY) == SMARTCARD_PARITY_EVEN) || \ ((PARITY) == SMARTCARD_PARITY_ODD)) /** * @} */ /** @defgroup SMARTCARD_Mode SMARTCARD Mode * @{ */ #define SMARTCARD_MODE_RX ((uint32_t)USART_CR1_RE) #define SMARTCARD_MODE_TX ((uint32_t)USART_CR1_TE) #define SMARTCARD_MODE_TX_RX ((uint32_t)(USART_CR1_TE |USART_CR1_RE)) #define IS_SMARTCARD_MODE(MODE) ((((MODE) & (uint32_t)0x0000FFF3) == 0x00) && ((MODE) != (uint32_t)0x00000000)) /** * @} */ /** @defgroup SMARTCARD_Clock_Polarity SMARTCARD Clock Polarity * @{ */ #define SMARTCARD_POLARITY_LOW ((uint32_t)0x00000000) #define SMARTCARD_POLARITY_HIGH ((uint32_t)USART_CR2_CPOL) #define IS_SMARTCARD_POLARITY(CPOL) (((CPOL) == SMARTCARD_POLARITY_LOW) || ((CPOL) == SMARTCARD_POLARITY_HIGH)) /** * @} */ /** @defgroup SMARTCARD_Clock_Phase SMARTCARD Clock Phase * @{ */ #define SMARTCARD_PHASE_1EDGE ((uint32_t)0x00000000) #define SMARTCARD_PHASE_2EDGE ((uint32_t)USART_CR2_CPHA) #define IS_SMARTCARD_PHASE(CPHA) (((CPHA) == SMARTCARD_PHASE_1EDGE) || ((CPHA) == SMARTCARD_PHASE_2EDGE)) /** * @} */ /** @defgroup SMARTCARD_Last_Bit SMARTCARD Last Bit * @{ */ #define SMARTCARD_LASTBIT_DISABLE ((uint32_t)0x00000000) #define SMARTCARD_LASTBIT_ENABLE ((uint32_t)USART_CR2_LBCL) #define IS_SMARTCARD_LASTBIT(LASTBIT) (((LASTBIT) == SMARTCARD_LASTBIT_DISABLE) || \ ((LASTBIT) == SMARTCARD_LASTBIT_ENABLE)) /** * @} */ /** @defgroup SMARTCARD_NACK_State SMARTCARD NACK State * @{ */ #define SMARTCARD_NACK_ENABLED ((uint32_t)USART_CR3_NACK) #define SMARTCARD_NACK_DISABLED ((uint32_t)0x00000000) #define IS_SMARTCARD_NACK_STATE(NACK) (((NACK) == SMARTCARD_NACK_ENABLED) || \ ((NACK) == SMARTCARD_NACK_DISABLED)) /** * @} */ /** @defgroup SMARTCARD_DMA_Requests SMARTCARD DMA requests * @{ */ #define SMARTCARD_DMAREQ_TX ((uint32_t)USART_CR3_DMAT) #define SMARTCARD_DMAREQ_RX ((uint32_t)USART_CR3_DMAR) /** * @} */ /** @defgroup SMARTCARD_Flags SMARTCARD Flags * Elements values convention: 0xXXXX * - 0xXXXX : Flag mask in the SR register * @{ */ #define SMARTCARD_FLAG_TXE ((uint32_t)USART_SR_TXE) #define SMARTCARD_FLAG_TC ((uint32_t)USART_SR_TC) #define SMARTCARD_FLAG_RXNE ((uint32_t)USART_SR_RXNE) #define SMARTCARD_FLAG_IDLE ((uint32_t)USART_SR_IDLE) #define SMARTCARD_FLAG_ORE ((uint32_t)USART_SR_ORE) #define SMARTCARD_FLAG_NE ((uint32_t)USART_SR_NE) #define SMARTCARD_FLAG_FE ((uint32_t)USART_SR_FE) #define SMARTCARD_FLAG_PE ((uint32_t)USART_SR_PE) /** * @} */ /** @defgroup SMARTCARD_Interrupt_definition SMARTCARD Interrupts Definition * Elements values convention: 0xY000XXXX * - XXXX : Interrupt mask in the XX register * - Y : Interrupt source register (4 bits) * - 01: CR1 register * - 10: CR3 register * * @{ */ #define SMARTCARD_IT_PE ((uint32_t)0x10000100) #define SMARTCARD_IT_TXE ((uint32_t)0x10000080) #define SMARTCARD_IT_TC ((uint32_t)0x10000040) #define SMARTCARD_IT_RXNE ((uint32_t)0x10000020) #define SMARTCARD_IT_IDLE ((uint32_t)0x10000010) #define SMARTCARD_IT_ERR ((uint32_t)0x20000001) /** * @} */ /** @defgroup SMARTCARD_Interruption_Mask SMARTCARD interruptions flag mask * @{ */ #define SMARTCARD_IT_MASK ((uint32_t)0x0000FFFF) /** * @} */ /** * @} */ /* Exported macro ------------------------------------------------------------*/ /** @defgroup SMARTCARD_Exported_Macros SMARTCARD Exported Macros * @{ */ /** @brief Reset SMARTCARD handle state * @param __HANDLE__: specifies the SMARTCARD Handle. * This parameter can be USARTx with x: 1, 2 or 3. * @retval None */ #define __HAL_SMARTCARD_RESET_HANDLE_STATE(__HANDLE__) ((__HANDLE__)->State = HAL_SMARTCARD_STATE_RESET) /** @brief Flushs the Smartcard DR register * @param __HANDLE__: specifies the SMARTCARD Handle. * This parameter can be USARTx with x: 1, 2 or 3. */ #define __HAL_SMARTCARD_FLUSH_DRREGISTER(__HANDLE__) ((__HANDLE__)->Instance->DR) /** @brief Checks whether the specified Smartcard flag is set or not. * @param __HANDLE__: specifies the SMARTCARD Handle. * This parameter can be USARTx with x: 1, 2 or 3. * @param __FLAG__: specifies the flag to check. * This parameter can be one of the following values: * @arg SMARTCARD_FLAG_TXE: Transmit data register empty flag * @arg SMARTCARD_FLAG_TC: Transmission Complete flag * @arg SMARTCARD_FLAG_RXNE: Receive data register not empty flag * @arg SMARTCARD_FLAG_IDLE: Idle Line detection flag * @arg SMARTCARD_FLAG_ORE: OverRun Error flag * @arg SMARTCARD_FLAG_NE: Noise Error flag * @arg SMARTCARD_FLAG_FE: Framing Error flag * @arg SMARTCARD_FLAG_PE: Parity Error flag * @retval The new state of __FLAG__ (TRUE or FALSE). */ #define __HAL_SMARTCARD_GET_FLAG(__HANDLE__, __FLAG__) (((__HANDLE__)->Instance->SR & (__FLAG__)) == (__FLAG__)) /** @brief Clears the specified Smartcard pending flags. * @param __HANDLE__: specifies the SMARTCARD Handle. * This parameter can be USARTx with x: 1, 2 or 3. * @param __FLAG__: specifies the flag to check. * This parameter can be any combination of the following values: * @arg SMARTCARD_FLAG_TC: Transmission Complete flag. * @arg SMARTCARD_FLAG_RXNE: Receive data register not empty flag. * * @note PE (Parity error), FE (Framing error), NE (Noise error) and ORE (OverRun * error) flags are cleared by software sequence: a read operation to * USART_SR register followed by a read operation to USART_DR register. * @note RXNE flag can be also cleared by a read to the USART_DR register. * @note TC flag can be also cleared by software sequence: a read operation to * USART_SR register followed by a write operation to USART_DR register. * @note TXE flag is cleared only by a write to the USART_DR register. * * @retval None */ #define __HAL_SMARTCARD_CLEAR_FLAG(__HANDLE__, __FLAG__) ((__HANDLE__)->Instance->SR = ~(__FLAG__)) /** @brief Clear the SMARTCARD PE pending flag. * @param __HANDLE__: specifies the USART Handle. * This parameter can be USARTx with x: 1, 2 or 3. * @retval None */ #define __HAL_SMARTCARD_CLEAR_PEFLAG(__HANDLE__) do{(__HANDLE__)->Instance->SR;\ (__HANDLE__)->Instance->DR;}while(0) /** @brief Clear the SMARTCARD FE pending flag. * @param __HANDLE__: specifies the USART Handle. * This parameter can be USARTx with x: 1, 2 or 3. * @retval None */ #define __HAL_SMARTCARD_CLEAR_FEFLAG(__HANDLE__) __HAL_SMARTCARD_CLEAR_PEFLAG(__HANDLE__) /** @brief Clear the SMARTCARD NE pending flag. * @param __HANDLE__: specifies the USART Handle. * This parameter can be USARTx with x: 1, 2 or 3. * @retval None */ #define __HAL_SMARTCARD_CLEAR_NEFLAG(__HANDLE__) __HAL_SMARTCARD_CLEAR_PEFLAG(__HANDLE__) /** @brief Clear the SMARTCARD ORE pending flag. * @param __HANDLE__: specifies the USART Handle. * This parameter can be USARTx with x: 1, 2 or 3. * @retval None */ #define __HAL_SMARTCARD_CLEAR_OREFLAG(__HANDLE__) __HAL_SMARTCARD_CLEAR_PEFLAG(__HANDLE__) /** @brief Clear the SMARTCARD IDLE pending flag. * @param __HANDLE__: specifies the USART Handle. * This parameter can be USARTx with x: 1, 2 or 3. * @retval None */ #define __HAL_SMARTCARD_CLEAR_IDLEFLAG(__HANDLE__) __HAL_SMARTCARD_CLEAR_PEFLAG(__HANDLE__) /** @brief Enables the specified SmartCard interrupt. * @param __HANDLE__: specifies the SMARTCARD Handle. * This parameter can be USARTx with x: 1, 2 or 3. * @param __INTERRUPT__: specifies the SMARTCARD interrupt to enable. * This parameter can be one of the following values: * @arg SMARTCARD_IT_TXE: Transmit Data Register empty interrupt * @arg SMARTCARD_IT_TC: Transmission complete interrupt * @arg SMARTCARD_IT_RXNE: Receive Data register not empty interrupt * @arg SMARTCARD_IT_IDLE: Idle line detection interrupt * @arg SMARTCARD_IT_PE: Parity Error interrupt * @arg SMARTCARD_IT_ERR: Error interrupt(Frame error, noise error, overrun error) */ #define __HAL_SMARTCARD_ENABLE_IT(__HANDLE__, __INTERRUPT__) ((((__INTERRUPT__) >> 28) == 1)? ((__HANDLE__)->Instance->CR1 |= ((__INTERRUPT__) & SMARTCARD_IT_MASK)): \ ((__HANDLE__)->Instance->CR3 |= ((__INTERRUPT__) & SMARTCARD_IT_MASK))) /** @brief Disables the specified SmartCard interrupts. * @param __HANDLE__: specifies the SMARTCARD Handle. * This parameter can be USARTx with x: 1, 2 or 3. * @param __INTERRUPT__: specifies the SMARTCARD interrupt to disable. * This parameter can be one of the following values: * @arg SMARTCARD_IT_TXE: Transmit Data Register empty interrupt * @arg SMARTCARD_IT_TC: Transmission complete interrupt * @arg SMARTCARD_IT_RXNE: Receive Data register not empty interrupt * @arg SMARTCARD_IT_IDLE: Idle line detection interrupt * @arg SMARTCARD_IT_PE: Parity Error interrupt * @arg SMARTCARD_IT_ERR: Error interrupt(Frame error, noise error, overrun error) */ #define __HAL_SMARTCARD_DISABLE_IT(__HANDLE__, __INTERRUPT__) ((((__INTERRUPT__) >> 28) == 1)? ((__HANDLE__)->Instance->CR1 &= ~((__INTERRUPT__) & SMARTCARD_IT_MASK)): \ ((__HANDLE__)->Instance->CR3 &= ~ ((__INTERRUPT__) & SMARTCARD_IT_MASK))) /** @brief Checks whether the specified SmartCard interrupt has occurred or not. * @param __HANDLE__: specifies the SMARTCARD Handle. * This parameter can be USARTx with x: 1, 2 or 3. * @param __IT__: specifies the SMARTCARD interrupt source to check. * This parameter can be one of the following values: * @arg SMARTCARD_IT_TXE: Transmit Data Register empty interrupt * @arg SMARTCARD_IT_TC: Transmission complete interrupt * @arg SMARTCARD_IT_RXNE: Receive Data register not empty interrupt * @arg SMARTCARD_IT_IDLE: Idle line detection interrupt * @arg SMARTCARD_IT_ERR: Error interrupt * @arg SMARTCARD_IT_PE: Parity Error interrupt * @retval The new state of __IT__ (TRUE or FALSE). */ #define __HAL_SMARTCARD_GET_IT_SOURCE(__HANDLE__, __IT__) (((((__IT__) >> 28) == 1)? (__HANDLE__)->Instance->CR1: (__HANDLE__)->Instance->CR3) & (((uint32_t)(__IT__)) & SMARTCARD_IT_MASK)) /** @brief Enable the USART associated to the SMARTCARD Handle * @param __HANDLE__: specifies the SMARTCARD Handle. * This parameter can be USARTx with x: 1, 2 or 3. * @retval None */ #define __HAL_SMARTCARD_ENABLE(__HANDLE__) (SET_BIT((__HANDLE__)->Instance->CR1, USART_CR1_UE)) /** @brief Disable the USART associated to the SMARTCARD Handle * @param __HANDLE__: specifies the SMARTCARD Handle. * This parameter can be USARTx with x: 1, 2 or 3. * @retval None */ #define __HAL_SMARTCARD_DISABLE(__HANDLE__) (CLEAR_BIT((__HANDLE__)->Instance->CR1, USART_CR1_UE)) /** * @} */ /* Private macros --------------------------------------------------------*/ /** @defgroup SMARTCARD_Private_Macros SMARTCARD Private Macros * @{ */ /** @brief Macros to enable or disable the SmartCard DMA request. * @param __HANDLE__: specifies the SmartCard Handle. * @param __REQUEST__: specifies the SmartCard DMA request. * This parameter can be one of the following values: * @arg SMARTCARD_DMAREQ_TX: SmartCard DMA transmit request * @arg SMARTCARD_DMAREQ_RX: SmartCard DMA receive request */ #define SMARTCARD_DMA_REQUEST_ENABLE(__HANDLE__, __REQUEST__) (SET_BIT((__HANDLE__)->Instance->CR3, (__REQUEST__))) #define SMARTCARD_DMA_REQUEST_DISABLE(__HANDLE__, __REQUEST__) (CLEAR_BIT((__HANDLE__)->Instance->CR3, (__REQUEST__))) #define SMARTCARD_DIV(__PCLK__, __BAUD__) (((__PCLK__)*25)/(4*(__BAUD__))) #define SMARTCARD_DIVMANT(__PCLK__, __BAUD__) (SMARTCARD_DIV((__PCLK__), (__BAUD__))/100) #define SMARTCARD_DIVFRAQ(__PCLK__, __BAUD__) (((SMARTCARD_DIV((__PCLK__), (__BAUD__)) - (SMARTCARD_DIVMANT((__PCLK__), (__BAUD__)) * 100)) * 16 + 50) / 100) #define SMARTCARD_BRR(__PCLK__, __BAUD__) ((SMARTCARD_DIVMANT((__PCLK__), (__BAUD__)) << 4)|(SMARTCARD_DIVFRAQ((__PCLK__), (__BAUD__)) & 0x0F)) /** @brief Check the Baud rate range. The maximum Baud Rate is derived from the * maximum clock on L1 (i.e. 32 MHz) divided by the oversampling used * on the SMARTCARD (i.e. 16). No overSampling by 16 on Smartcard. * @param __BAUDRATE__: Baud rate set by the configuration function. * @retval Test result (TRUE or FALSE) */ #define IS_SMARTCARD_BAUDRATE(__BAUDRATE__) ((__BAUDRATE__) < 2000001) /** * @} */ /* Exported functions --------------------------------------------------------*/ /** @addtogroup SMARTCARD_Exported_Functions SMARTCARD Exported Functions * @{ */ /** @addtogroup SMARTCARD_Exported_Functions_Group1 SmartCard Initialization and de-initialization functions * @{ */ /* Initialization/de-initialization functions **********************************/ HAL_StatusTypeDef HAL_SMARTCARD_Init(SMARTCARD_HandleTypeDef *hsc); HAL_StatusTypeDef HAL_SMARTCARD_ReInit(SMARTCARD_HandleTypeDef *hsc); HAL_StatusTypeDef HAL_SMARTCARD_DeInit(SMARTCARD_HandleTypeDef *hsc); void HAL_SMARTCARD_MspInit(SMARTCARD_HandleTypeDef *hsc); void HAL_SMARTCARD_MspDeInit(SMARTCARD_HandleTypeDef *hsc); /** * @} */ /** @addtogroup SMARTCARD_Exported_Functions_Group2 IO operation functions * @{ */ /* IO operation functions *******************************************************/ HAL_StatusTypeDef HAL_SMARTCARD_Transmit(SMARTCARD_HandleTypeDef *hsc, uint8_t *pData, uint16_t Size, uint32_t Timeout); HAL_StatusTypeDef HAL_SMARTCARD_Receive(SMARTCARD_HandleTypeDef *hsc, uint8_t *pData, uint16_t Size, uint32_t Timeout); HAL_StatusTypeDef HAL_SMARTCARD_Transmit_IT(SMARTCARD_HandleTypeDef *hsc, uint8_t *pData, uint16_t Size); HAL_StatusTypeDef HAL_SMARTCARD_Receive_IT(SMARTCARD_HandleTypeDef *hsc, uint8_t *pData, uint16_t Size); HAL_StatusTypeDef HAL_SMARTCARD_Transmit_DMA(SMARTCARD_HandleTypeDef *hsc, uint8_t *pData, uint16_t Size); HAL_StatusTypeDef HAL_SMARTCARD_Receive_DMA(SMARTCARD_HandleTypeDef *hsc, uint8_t *pData, uint16_t Size); void HAL_SMARTCARD_IRQHandler(SMARTCARD_HandleTypeDef *hsc); void HAL_SMARTCARD_TxCpltCallback(SMARTCARD_HandleTypeDef *hsc); void HAL_SMARTCARD_RxCpltCallback(SMARTCARD_HandleTypeDef *hsc); void HAL_SMARTCARD_ErrorCallback(SMARTCARD_HandleTypeDef *hsc); /** * @} */ /** @addtogroup SMARTCARD_Exported_Functions_Group3 Peripheral State and Errors functions * @{ */ /* Peripheral State and Errors functions functions *****************************/ HAL_SMARTCARD_StateTypeDef HAL_SMARTCARD_GetState(SMARTCARD_HandleTypeDef *hsc); uint32_t HAL_SMARTCARD_GetError(SMARTCARD_HandleTypeDef *hsc); /** * @} */ /** * @} */ /** * @} */ /** * @} */ #ifdef __cplusplus } #endif #endif /* __STM32L1xx_HAL_SMARTCARD_H */ /************************ (C) COPYRIGHT STMicroelectronics *****END OF FILE****/ ================================================ FILE: Zelig/mbed/TARGET_NUCLEO_L152RE/stm32l1xx_hal_spi.h ================================================ /** ****************************************************************************** * @file stm32l1xx_hal_spi.h * @author MCD Application Team * @version V1.0.0 * @date 5-September-2014 * @brief Header file of SPI HAL module. ****************************************************************************** * @attention * *

© COPYRIGHT(c) 2014 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. * ****************************************************************************** */ /* Define to prevent recursive inclusion -------------------------------------*/ #ifndef __STM32L1xx_HAL_SPI_H #define __STM32L1xx_HAL_SPI_H #ifdef __cplusplus extern "C" { #endif /* Includes ------------------------------------------------------------------*/ #include "stm32l1xx_hal_def.h" /** @addtogroup STM32L1xx_HAL_Driver * @{ */ /** @addtogroup SPI * @{ */ /* Exported types ------------------------------------------------------------*/ /** @defgroup SPI_Exported_Types SPI Exported Types * @{ */ /** * @brief SPI Configuration Structure definition */ typedef struct { uint32_t Mode; /*!< Specifies the SPI operating mode. This parameter can be a value of @ref SPI_mode */ uint32_t Direction; /*!< Specifies the SPI Directional mode state. This parameter can be a value of @ref SPI_Direction_mode */ uint32_t DataSize; /*!< Specifies the SPI data size. This parameter can be a value of @ref SPI_data_size */ uint32_t CLKPolarity; /*!< Specifies the serial clock steady state. This parameter can be a value of @ref SPI_Clock_Polarity */ uint32_t CLKPhase; /*!< Specifies the clock active edge for the bit capture. This parameter can be a value of @ref SPI_Clock_Phase */ uint32_t NSS; /*!< Specifies whether the NSS signal is managed by hardware (NSS pin) or by software using the SSI bit. This parameter can be a value of @ref SPI_Slave_Select_management */ uint32_t BaudRatePrescaler; /*!< Specifies the Baud Rate prescaler value which will be used to configure the transmit and receive SCK clock. This parameter can be a value of @ref SPI_BaudRate_Prescaler @note The communication clock is derived from the master clock. The slave clock does not need to be set */ uint32_t FirstBit; /*!< Specifies whether data transfers start from MSB or LSB bit. This parameter can be a value of @ref SPI_MSB_LSB_transmission */ uint32_t TIMode; /*!< Specifies if the TI mode is enabled or not. This parameter can be a value of @ref SPI_TI_mode */ uint32_t CRCCalculation; /*!< Specifies if the CRC calculation is enabled or not. This parameter can be a value of @ref SPI_CRC_Calculation */ uint32_t CRCPolynomial; /*!< Specifies the polynomial used for the CRC calculation. This parameter must be a number between Min_Data = 0 and Max_Data = 65535 */ }SPI_InitTypeDef; /** * @brief HAL SPI State structure definition */ typedef enum { HAL_SPI_STATE_RESET = 0x00, /*!< SPI not yet initialized or disabled */ HAL_SPI_STATE_READY = 0x01, /*!< SPI initialized and ready for use */ HAL_SPI_STATE_BUSY = 0x02, /*!< SPI process is ongoing */ HAL_SPI_STATE_BUSY_TX = 0x12, /*!< Data Transmission process is ongoing */ HAL_SPI_STATE_BUSY_RX = 0x22, /*!< Data Reception process is ongoing */ HAL_SPI_STATE_BUSY_TX_RX = 0x32, /*!< Data Transmission and Reception process is ongoing */ HAL_SPI_STATE_ERROR = 0x03 /*!< SPI error state */ }HAL_SPI_StateTypeDef; /** * @brief HAL SPI Error Code structure definition */ typedef enum { HAL_SPI_ERROR_NONE = 0x00, /*!< No error */ HAL_SPI_ERROR_MODF = 0x01, /*!< MODF error */ HAL_SPI_ERROR_CRC = 0x02, /*!< CRC error */ HAL_SPI_ERROR_OVR = 0x04, /*!< OVR error */ HAL_SPI_ERROR_FRE = 0x08, /*!< FRE error */ HAL_SPI_ERROR_DMA = 0x10, /*!< DMA transfer error */ HAL_SPI_ERROR_FLAG = 0x20 /*!< Flag: RXNE,TXE, BSY */ }HAL_SPI_ErrorTypeDef; /** * @brief SPI handle Structure definition */ typedef struct __SPI_HandleTypeDef { SPI_TypeDef *Instance; /* SPI registers base address */ SPI_InitTypeDef Init; /* SPI communication parameters */ uint8_t *pTxBuffPtr; /* Pointer to SPI Tx transfer Buffer */ uint16_t TxXferSize; /* SPI Tx transfer size */ uint16_t TxXferCount; /* SPI Tx Transfer Counter */ uint8_t *pRxBuffPtr; /* Pointer to SPI Rx transfer Buffer */ uint16_t RxXferSize; /* SPI Rx transfer size */ uint16_t RxXferCount; /* SPI Rx Transfer Counter */ DMA_HandleTypeDef *hdmatx; /* SPI Tx DMA handle parameters */ DMA_HandleTypeDef *hdmarx; /* SPI Rx DMA handle parameters */ void (*RxISR)(struct __SPI_HandleTypeDef * hspi); /* function pointer on Rx ISR */ void (*TxISR)(struct __SPI_HandleTypeDef * hspi); /* function pointer on Tx ISR */ HAL_LockTypeDef Lock; /* SPI locking object */ __IO HAL_SPI_StateTypeDef State; /* SPI communication state */ __IO HAL_SPI_ErrorTypeDef ErrorCode; /* SPI Error code */ }SPI_HandleTypeDef; /** * @} */ /* Exported constants --------------------------------------------------------*/ /** @defgroup SPI_Exported_Constants SPI Exported Constants * @{ */ /** @defgroup SPI_mode SPI mode * @{ */ #define SPI_MODE_SLAVE ((uint32_t)0x00000000) #define SPI_MODE_MASTER (SPI_CR1_MSTR | SPI_CR1_SSI) #define IS_SPI_MODE(MODE) (((MODE) == SPI_MODE_SLAVE) || \ ((MODE) == SPI_MODE_MASTER)) /** * @} */ /** @defgroup SPI_Direction_mode SPI Direction mode * @{ */ #define SPI_DIRECTION_2LINES ((uint32_t)0x00000000) #define SPI_DIRECTION_2LINES_RXONLY SPI_CR1_RXONLY #define SPI_DIRECTION_1LINE SPI_CR1_BIDIMODE #define IS_SPI_DIRECTION_MODE(MODE) (((MODE) == SPI_DIRECTION_2LINES) || \ ((MODE) == SPI_DIRECTION_2LINES_RXONLY) || \ ((MODE) == SPI_DIRECTION_1LINE)) #define IS_SPI_DIRECTION_2LINES_OR_1LINE(MODE) (((MODE) == SPI_DIRECTION_2LINES) || \ ((MODE) == SPI_DIRECTION_1LINE)) #define IS_SPI_DIRECTION_2LINES(MODE) ((MODE) == SPI_DIRECTION_2LINES) /** * @} */ /** @defgroup SPI_data_size SPI data size * @{ */ #define SPI_DATASIZE_8BIT ((uint32_t)0x00000000) #define SPI_DATASIZE_16BIT SPI_CR1_DFF #define IS_SPI_DATASIZE(DATASIZE) (((DATASIZE) == SPI_DATASIZE_16BIT) || \ ((DATASIZE) == SPI_DATASIZE_8BIT)) /** * @} */ /** @defgroup SPI_Clock_Polarity SPI Clock Polarity * @{ */ #define SPI_POLARITY_LOW ((uint32_t)0x00000000) #define SPI_POLARITY_HIGH SPI_CR1_CPOL #define IS_SPI_CPOL(CPOL) (((CPOL) == SPI_POLARITY_LOW) || \ ((CPOL) == SPI_POLARITY_HIGH)) /** * @} */ /** @defgroup SPI_Clock_Phase SPI Clock Phase * @{ */ #define SPI_PHASE_1EDGE ((uint32_t)0x00000000) #define SPI_PHASE_2EDGE SPI_CR1_CPHA #define IS_SPI_CPHA(CPHA) (((CPHA) == SPI_PHASE_1EDGE) || \ ((CPHA) == SPI_PHASE_2EDGE)) /** * @} */ /** @defgroup SPI_Slave_Select_management SPI Slave Select management * @{ */ #define SPI_NSS_SOFT SPI_CR1_SSM #define SPI_NSS_HARD_INPUT ((uint32_t)0x00000000) #define SPI_NSS_HARD_OUTPUT ((uint32_t)(SPI_CR2_SSOE << 16)) #define IS_SPI_NSS(NSS) (((NSS) == SPI_NSS_SOFT) || \ ((NSS) == SPI_NSS_HARD_INPUT) || \ ((NSS) == SPI_NSS_HARD_OUTPUT)) /** * @} */ /** @defgroup SPI_BaudRate_Prescaler SPI BaudRate Prescaler * @{ */ #define SPI_BAUDRATEPRESCALER_2 ((uint32_t)0x00000000) #define SPI_BAUDRATEPRESCALER_4 ((uint32_t)SPI_CR1_BR_0) #define SPI_BAUDRATEPRESCALER_8 ((uint32_t)SPI_CR1_BR_1) #define SPI_BAUDRATEPRESCALER_16 ((uint32_t)SPI_CR1_BR_1 | SPI_CR1_BR_0) #define SPI_BAUDRATEPRESCALER_32 ((uint32_t)SPI_CR1_BR_2) #define SPI_BAUDRATEPRESCALER_64 ((uint32_t)SPI_CR1_BR_2 | SPI_CR1_BR_0) #define SPI_BAUDRATEPRESCALER_128 ((uint32_t)SPI_CR1_BR_2 | SPI_CR1_BR_1) #define SPI_BAUDRATEPRESCALER_256 ((uint32_t)SPI_CR1_BR_2 | SPI_CR1_BR_1 | SPI_CR1_BR_0) #define IS_SPI_BAUDRATE_PRESCALER(PRESCALER) (((PRESCALER) == SPI_BAUDRATEPRESCALER_2) || \ ((PRESCALER) == SPI_BAUDRATEPRESCALER_4) || \ ((PRESCALER) == SPI_BAUDRATEPRESCALER_8) || \ ((PRESCALER) == SPI_BAUDRATEPRESCALER_16) || \ ((PRESCALER) == SPI_BAUDRATEPRESCALER_32) || \ ((PRESCALER) == SPI_BAUDRATEPRESCALER_64) || \ ((PRESCALER) == SPI_BAUDRATEPRESCALER_128) || \ ((PRESCALER) == SPI_BAUDRATEPRESCALER_256)) /** * @} */ /** @defgroup SPI_MSB_LSB_transmission SPI MSB LSB transmission * @{ */ #define SPI_FIRSTBIT_MSB ((uint32_t)0x00000000) #define SPI_FIRSTBIT_LSB SPI_CR1_LSBFIRST #define IS_SPI_FIRST_BIT(BIT) (((BIT) == SPI_FIRSTBIT_MSB) || \ ((BIT) == SPI_FIRSTBIT_LSB)) /** * @} */ /** @defgroup SPI_CRC_Calculation SPI CRC Calculation * @{ */ #define SPI_CRCCALCULATION_DISABLED ((uint32_t)0x00000000) #define SPI_CRCCALCULATION_ENABLED SPI_CR1_CRCEN #define IS_SPI_CRC_CALCULATION(CALCULATION) (((CALCULATION) == SPI_CRCCALCULATION_DISABLED) || \ ((CALCULATION) == SPI_CRCCALCULATION_ENABLED)) #define IS_SPI_CRC_POLYNOMIAL(POLYNOMIAL) (((POLYNOMIAL) >= 0x1) && ((POLYNOMIAL) <= 0xFFFF)) /** * @} */ /** @defgroup SPI_Interrupt_configuration_definition SPI Interrupt configuration definition * @{ */ #define SPI_IT_TXE SPI_CR2_TXEIE #define SPI_IT_RXNE SPI_CR2_RXNEIE #define SPI_IT_ERR SPI_CR2_ERRIE /** * @} */ /** @defgroup SPI_Flag_definition SPI Flag definition * @{ */ #define SPI_FLAG_RXNE SPI_SR_RXNE #define SPI_FLAG_TXE SPI_SR_TXE #define SPI_FLAG_CRCERR SPI_SR_CRCERR #define SPI_FLAG_MODF SPI_SR_MODF #define SPI_FLAG_OVR SPI_SR_OVR #define SPI_FLAG_BSY SPI_SR_BSY #define SPI_FLAG_FRE SPI_SR_FRE /** * @} */ /** * @} */ /* Exported macro ------------------------------------------------------------*/ /** @defgroup SPI_Exported_Macros SPI Exported Macros * @{ */ /** @brief Reset SPI handle state * @param __HANDLE__: specifies the SPI handle. * This parameter can be SPI where x: 1, 2, or 3 to select the SPI peripheral. * @retval None */ #define __HAL_SPI_RESET_HANDLE_STATE(__HANDLE__) ((__HANDLE__)->State = HAL_SPI_STATE_RESET) /** @brief Enable or disable the specified SPI interrupts. * @param __HANDLE__: specifies the SPI handle. * This parameter can be SPI where x: 1, 2, or 3 to select the SPI peripheral. * @param __INTERRUPT__: specifies the interrupt source to enable or disable. * This parameter can be one of the following values: * @arg SPI_IT_TXE: Tx buffer empty interrupt enable * @arg SPI_IT_RXNE: RX buffer not empty interrupt enable * @arg SPI_IT_ERR: Error interrupt enable * @retval None */ #define __HAL_SPI_ENABLE_IT(__HANDLE__, __INTERRUPT__) SET_BIT((__HANDLE__)->Instance->CR2, (__INTERRUPT__)) #define __HAL_SPI_DISABLE_IT(__HANDLE__, __INTERRUPT__) CLEAR_BIT((__HANDLE__)->Instance->CR2, (__INTERRUPT__)) /** @brief Check if the specified SPI interrupt source is enabled or disabled. * @param __HANDLE__: specifies the SPI handle. * This parameter can be SPI where x: 1, 2, or 3 to select the SPI peripheral. * @param __INTERRUPT__: specifies the SPI interrupt source to check. * This parameter can be one of the following values: * @arg SPI_IT_TXE: Tx buffer empty interrupt enable * @arg SPI_IT_RXNE: RX buffer not empty interrupt enable * @arg SPI_IT_ERR: Error interrupt enable * @retval The new state of __IT__ (TRUE or FALSE). */ #define __HAL_SPI_GET_IT_SOURCE(__HANDLE__, __INTERRUPT__) ((((__HANDLE__)->Instance->CR2 & (__INTERRUPT__)) == (__INTERRUPT__)) ? SET : RESET) /** @brief Check whether the specified SPI flag is set or not. * @param __HANDLE__: specifies the SPI handle. * This parameter can be SPI where x: 1, 2, or 3 to select the SPI peripheral. * @param __FLAG__: specifies the flag to check. * This parameter can be one of the following values: * @arg SPI_FLAG_RXNE: Receive buffer not empty flag * @arg SPI_FLAG_TXE: Transmit buffer empty flag * @arg SPI_FLAG_CRCERR: CRC error flag * @arg SPI_FLAG_MODF: Mode fault flag * @arg SPI_FLAG_OVR: Overrun flag * @arg SPI_FLAG_BSY: Busy flag * @arg SPI_FLAG_FRE: Frame format error flag * @retval The new state of __FLAG__ (TRUE or FALSE). */ #define __HAL_SPI_GET_FLAG(__HANDLE__, __FLAG__) ((((__HANDLE__)->Instance->SR) & (__FLAG__)) == (__FLAG__)) /** @brief Clear the SPI CRCERR pending flag. * @param __HANDLE__: specifies the SPI handle. * This parameter can be SPI where x: 1, 2, or 3 to select the SPI peripheral. * @retval None */ #define __HAL_SPI_CLEAR_CRCERRFLAG(__HANDLE__) ((__HANDLE__)->Instance->SR = ~(SPI_FLAG_CRCERR)) /** @brief Clear the SPI MODF pending flag. * @param __HANDLE__: specifies the SPI handle. * This parameter can be SPI where x: 1, 2, or 3 to select the SPI peripheral. * @retval None */ #define __HAL_SPI_CLEAR_MODFFLAG(__HANDLE__) do{(__HANDLE__)->Instance->SR;\ CLEAR_BIT((__HANDLE__)->Instance->CR1, SPI_CR1_SPE);}while(0) /** @brief Clear the SPI OVR pending flag. * @param __HANDLE__: specifies the SPI handle. * This parameter can be SPI where x: 1, 2, or 3 to select the SPI peripheral. * @retval None */ #define __HAL_SPI_CLEAR_OVRFLAG(__HANDLE__) do{(__HANDLE__)->Instance->DR;\ (__HANDLE__)->Instance->SR;}while(0) /** @brief Clear the SPI FRE pending flag. * @param __HANDLE__: specifies the SPI handle. * This parameter can be SPI where x: 1, 2, or 3 to select the SPI peripheral. * @retval None */ #define __HAL_SPI_CLEAR_FREFLAG(__HANDLE__) ((__HANDLE__)->Instance->SR) /** @brief Enables the SPI. * @param __HANDLE__: specifies the SPI Handle. * This parameter can be SPI where x: 1, 2, or 3 to select the SPI peripheral. * @retval None */ #define __HAL_SPI_ENABLE(__HANDLE__) SET_BIT((__HANDLE__)->Instance->CR1, SPI_CR1_SPE) /** @brief Disables the SPI. * @param __HANDLE__: specifies the SPI Handle. * This parameter can be SPI where x: 1, 2, or 3 to select the SPI peripheral. * @retval None */ #define __HAL_SPI_DISABLE(__HANDLE__) CLEAR_BIT((__HANDLE__)->Instance->CR1, SPI_CR1_SPE) /** * @} */ /* Private macro ------------------------------------------------------------*/ /** @defgroup SPI_Private_Macros SPI Private Macros * @{ */ /** @brief Sets the SPI transmit-only mode. * @param __HANDLE__: specifies the SPI Handle. * This parameter can be SPI where x: 1, 2, or 3 to select the SPI peripheral. * @retval None */ #define SPI_1LINE_TX(__HANDLE__) SET_BIT((__HANDLE__)->Instance->CR1, SPI_CR1_BIDIOE) /** @brief Sets the SPI receive-only mode. * @param __HANDLE__: specifies the SPI Handle. * This parameter can be SPI where x: 1, 2, or 3 to select the SPI peripheral. * @retval None */ #define SPI_1LINE_RX(__HANDLE__) CLEAR_BIT((__HANDLE__)->Instance->CR1, SPI_CR1_BIDIOE) /** @brief Resets the CRC calculation of the SPI. * @param __HANDLE__: specifies the SPI Handle. * This parameter can be SPI where x: 1, 2, or 3 to select the SPI peripheral. * @retval None */ #define SPI_RESET_CRC(__HANDLE__) do{CLEAR_BIT((__HANDLE__)->Instance->CR1, SPI_CR1_CRCEN);\ SET_BIT((__HANDLE__)->Instance->CR1, SPI_CR1_CRCEN);}while(0) /** * @} */ /* Include SPI HAL Extension module */ #include "stm32l1xx_hal_spi_ex.h" /* Exported functions --------------------------------------------------------*/ /** @addtogroup SPI_Exported_Functions * @{ */ /* Initialization/de-initialization functions **********************************/ /** @addtogroup SPI_Exported_Functions_Group1 * @{ */ HAL_StatusTypeDef HAL_SPI_Init(SPI_HandleTypeDef *hspi); HAL_StatusTypeDef HAL_SPI_DeInit (SPI_HandleTypeDef *hspi); void HAL_SPI_MspInit(SPI_HandleTypeDef *hspi); void HAL_SPI_MspDeInit(SPI_HandleTypeDef *hspi); /** * @} */ /* I/O operation functions *****************************************************/ /** @addtogroup SPI_Exported_Functions_Group2 * @{ */ HAL_StatusTypeDef HAL_SPI_Transmit(SPI_HandleTypeDef *hspi, uint8_t *pData, uint16_t Size, uint32_t Timeout); HAL_StatusTypeDef HAL_SPI_Receive(SPI_HandleTypeDef *hspi, uint8_t *pData, uint16_t Size, uint32_t Timeout); HAL_StatusTypeDef HAL_SPI_TransmitReceive(SPI_HandleTypeDef *hspi, uint8_t *pTxData, uint8_t *pRxData, uint16_t Size, uint32_t Timeout); HAL_StatusTypeDef HAL_SPI_Transmit_IT(SPI_HandleTypeDef *hspi, uint8_t *pData, uint16_t Size); HAL_StatusTypeDef HAL_SPI_Receive_IT(SPI_HandleTypeDef *hspi, uint8_t *pData, uint16_t Size); HAL_StatusTypeDef HAL_SPI_TransmitReceive_IT(SPI_HandleTypeDef *hspi, uint8_t *pTxData, uint8_t *pRxData, uint16_t Size); HAL_StatusTypeDef HAL_SPI_Transmit_DMA(SPI_HandleTypeDef *hspi, uint8_t *pData, uint16_t Size); HAL_StatusTypeDef HAL_SPI_Receive_DMA(SPI_HandleTypeDef *hspi, uint8_t *pData, uint16_t Size); HAL_StatusTypeDef HAL_SPI_TransmitReceive_DMA(SPI_HandleTypeDef *hspi, uint8_t *pTxData, uint8_t *pRxData, uint16_t Size); HAL_StatusTypeDef HAL_SPI_DMAPause(SPI_HandleTypeDef *hspi); HAL_StatusTypeDef HAL_SPI_DMAResume(SPI_HandleTypeDef *hspi); HAL_StatusTypeDef HAL_SPI_DMAStop(SPI_HandleTypeDef *hspi); void HAL_SPI_IRQHandler(SPI_HandleTypeDef *hspi); void HAL_SPI_TxCpltCallback(SPI_HandleTypeDef *hspi); void HAL_SPI_RxCpltCallback(SPI_HandleTypeDef *hspi); void HAL_SPI_TxRxCpltCallback(SPI_HandleTypeDef *hspi); void HAL_SPI_ErrorCallback(SPI_HandleTypeDef *hspi); void HAL_SPI_TxHalfCpltCallback(SPI_HandleTypeDef *hspi); void HAL_SPI_RxHalfCpltCallback(SPI_HandleTypeDef *hspi); void HAL_SPI_TxRxHalfCpltCallback(SPI_HandleTypeDef *hspi); /** * @} */ /* Peripheral State and Control functions **************************************/ /** @addtogroup SPI_Exported_Functions_Group3 * @{ */ HAL_SPI_StateTypeDef HAL_SPI_GetState(SPI_HandleTypeDef *hspi); HAL_SPI_ErrorTypeDef HAL_SPI_GetError(SPI_HandleTypeDef *hspi); /** * @} */ /** * @} */ /** * @} */ /** * @} */ #ifdef __cplusplus } #endif #endif /* __STM32L1xx_HAL_SPI_H */ /************************ (C) COPYRIGHT STMicroelectronics *****END OF FILE****/ ================================================ FILE: Zelig/mbed/TARGET_NUCLEO_L152RE/stm32l1xx_hal_spi_ex.h ================================================ /** ****************************************************************************** * @file stm32l1xx_hal_spi_ex.h * @author MCD Application Team * @version V1.0.0 * @date 5-September-2014 * @brief Header file of SPI HAL module. ****************************************************************************** * @attention * *

© COPYRIGHT(c) 2014 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. * ****************************************************************************** */ /* Define to prevent recursive inclusion -------------------------------------*/ #ifndef __STM32L1xx_HAL_SPI_EX_H #define __STM32L1xx_HAL_SPI_EX_H #ifdef __cplusplus extern "C" { #endif /* Includes ------------------------------------------------------------------*/ #include "stm32l1xx_hal_def.h" /** @addtogroup STM32L1xx_HAL_Driver * @{ */ /** @addtogroup SPI * @{ */ /* Exported types ------------------------------------------------------------*/ /* Exported constants --------------------------------------------------------*/ /** @defgroup SPI_Exported_Constants SPI Exported Constants * @{ */ #if defined (STM32L100xC) || defined (STM32L151xC) || defined (STM32L152xC) || defined (STM32L162xC) || defined (STM32L151xCA) || defined (STM32L151xD) || defined (STM32L152xCA) || defined (STM32L152xD) || defined (STM32L162xCA) || defined (STM32L162xD) || defined (STM32L151xE) || defined (STM32L152xE) || defined (STM32L162xE) /** @defgroup SPI_TI_mode SPI TI mode * @{ */ #define SPI_TIMODE_DISABLED ((uint32_t)0x00000000) #define SPI_TIMODE_ENABLED SPI_CR2_FRF #define IS_SPI_TIMODE(MODE) (((MODE) == SPI_TIMODE_DISABLED) || \ ((MODE) == SPI_TIMODE_ENABLED)) #else /** @defgroup SPI_TI_mode SPI TI mode disable * @brief SPI TI Mode not supported for Category 1 and 2 * @{ */ #define SPI_TIMODE_DISABLED ((uint32_t)0x00000000) #define IS_SPI_TIMODE(MODE) ((MODE) == SPI_TIMODE_DISABLED) #endif /** * @} */ /** * @} */ /** * @} */ /** * @} */ #ifdef __cplusplus } #endif #endif /* __STM32L1xx_HAL_SPI_H */ /************************ (C) COPYRIGHT STMicroelectronics *****END OF FILE****/ ================================================ FILE: Zelig/mbed/TARGET_NUCLEO_L152RE/stm32l1xx_hal_sram.h ================================================ /** ****************************************************************************** * @file stm32l1xx_hal_sram.h * @author MCD Application Team * @version V1.0.0 * @date 5-September-2014 * @brief Header file of SRAM HAL module. ****************************************************************************** * @attention * *

© COPYRIGHT(c) 2014 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. * ****************************************************************************** */ /* Define to prevent recursive inclusion -------------------------------------*/ #ifndef __STM32L1xx_HAL_SRAM_H #define __STM32L1xx_HAL_SRAM_H #ifdef __cplusplus extern "C" { #endif /* Includes ------------------------------------------------------------------*/ #include "stm32l1xx_ll_fsmc.h" /** @addtogroup STM32L1xx_HAL_Driver * @{ */ /** @addtogroup SRAM * @{ */ #if defined (STM32L151xD) || defined (STM32L152xD) || defined (STM32L162xD) /* Exported typedef ----------------------------------------------------------*/ /** @defgroup SRAM_Exported_typedef SRAM Exported typedef * @{ */ /** * @brief HAL SRAM State structures definition */ typedef enum { HAL_SRAM_STATE_RESET = 0x00, /*!< SRAM not yet initialized or disabled */ HAL_SRAM_STATE_READY = 0x01, /*!< SRAM initialized and ready for use */ HAL_SRAM_STATE_BUSY = 0x02, /*!< SRAM internal process is ongoing */ HAL_SRAM_STATE_ERROR = 0x03, /*!< SRAM error state */ HAL_SRAM_STATE_PROTECTED = 0x04 /*!< SRAM peripheral NORSRAM device write protected */ }HAL_SRAM_StateTypeDef; /** * @brief SRAM handle Structure definition */ typedef struct { FSMC_NORSRAM_TYPEDEF *Instance; /*!< Register base address */ FSMC_NORSRAM_EXTENDED_TYPEDEF *Extended; /*!< Extended mode register base address */ FSMC_NORSRAM_InitTypeDef Init; /*!< SRAM device control configuration parameters */ HAL_LockTypeDef Lock; /*!< SRAM locking object */ __IO HAL_SRAM_StateTypeDef State; /*!< SRAM device access state */ DMA_HandleTypeDef *hdma; /*!< Pointer DMA handler */ }SRAM_HandleTypeDef; /** * @} */ /* Exported constants --------------------------------------------------------*/ /* Exported macro ------------------------------------------------------------*/ /** @defgroup SRAM_Exported_macro SRAM Exported macro * @{ */ /** @brief Reset SRAM handle state * @param __HANDLE__: SRAM handle * @retval None */ #define __HAL_SRAM_RESET_HANDLE_STATE(__HANDLE__) ((__HANDLE__)->State = HAL_SRAM_STATE_RESET) /** * @} */ /* Exported functions --------------------------------------------------------*/ /** @addtogroup SRAM_Exported_Functions * @{ */ /** @addtogroup SRAM_Exported_Functions_Group1 * @{ */ /* Initialization/de-initialization functions **********************************/ HAL_StatusTypeDef HAL_SRAM_Init(SRAM_HandleTypeDef *hsram, FSMC_NORSRAM_TimingTypeDef *Timing, FSMC_NORSRAM_TimingTypeDef *ExtTiming); HAL_StatusTypeDef HAL_SRAM_DeInit(SRAM_HandleTypeDef *hsram); void HAL_SRAM_MspInit(SRAM_HandleTypeDef *hsram); void HAL_SRAM_MspDeInit(SRAM_HandleTypeDef *hsram); void HAL_SRAM_DMA_XferCpltCallback(DMA_HandleTypeDef *hdma); void HAL_SRAM_DMA_XferErrorCallback(DMA_HandleTypeDef *hdma); /** * @} */ /** @addtogroup SRAM_Exported_Functions_Group2 * @{ */ /* I/O operation functions *****************************************************/ HAL_StatusTypeDef HAL_SRAM_Read_8b(SRAM_HandleTypeDef *hsram, uint32_t *pAddress, uint8_t *pDstBuffer, uint32_t BufferSize); HAL_StatusTypeDef HAL_SRAM_Write_8b(SRAM_HandleTypeDef *hsram, uint32_t *pAddress, uint8_t *pSrcBuffer, uint32_t BufferSize); HAL_StatusTypeDef HAL_SRAM_Read_16b(SRAM_HandleTypeDef *hsram, uint32_t *pAddress, uint16_t *pDstBuffer, uint32_t BufferSize); HAL_StatusTypeDef HAL_SRAM_Write_16b(SRAM_HandleTypeDef *hsram, uint32_t *pAddress, uint16_t *pSrcBuffer, uint32_t BufferSize); HAL_StatusTypeDef HAL_SRAM_Read_32b(SRAM_HandleTypeDef *hsram, uint32_t *pAddress, uint32_t *pDstBuffer, uint32_t BufferSize); HAL_StatusTypeDef HAL_SRAM_Write_32b(SRAM_HandleTypeDef *hsram, uint32_t *pAddress, uint32_t *pSrcBuffer, uint32_t BufferSize); HAL_StatusTypeDef HAL_SRAM_Read_DMA(SRAM_HandleTypeDef *hsram, uint32_t *pAddress, uint32_t *pDstBuffer, uint32_t BufferSize); HAL_StatusTypeDef HAL_SRAM_Write_DMA(SRAM_HandleTypeDef *hsram, uint32_t *pAddress, uint32_t *pSrcBuffer, uint32_t BufferSize); /** * @} */ /** @addtogroup SRAM_Exported_Functions_Group3 * @{ */ /* SRAM Control functions ******************************************************/ HAL_StatusTypeDef HAL_SRAM_WriteOperation_Enable(SRAM_HandleTypeDef *hsram); HAL_StatusTypeDef HAL_SRAM_WriteOperation_Disable(SRAM_HandleTypeDef *hsram); /** * @} */ /** @addtogroup SRAM_Exported_Functions_Group4 * @{ */ /* SRAM State functions *********************************************************/ HAL_SRAM_StateTypeDef HAL_SRAM_GetState(SRAM_HandleTypeDef *hsram); /** * @} */ /** * @} */ #endif /* STM32L151xD || STM32L152xD || STM32L162xD */ /** * @} */ /** * @} */ #ifdef __cplusplus } #endif #endif /* __STM32L1xx_HAL_SRAM_H */ /************************ (C) COPYRIGHT STMicroelectronics *****END OF FILE****/ ================================================ FILE: Zelig/mbed/TARGET_NUCLEO_L152RE/stm32l1xx_hal_tim.h ================================================ /** ****************************************************************************** * @file stm32l1xx_hal_tim.h * @author MCD Application Team * @version V1.0.0 * @date 5-September-2014 * @brief Header file of TIM HAL module. ****************************************************************************** * @attention * *

© COPYRIGHT(c) 2014 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. * ****************************************************************************** */ /* Define to prevent recursive inclusion -------------------------------------*/ #ifndef __STM32L1xx_HAL_TIM_H #define __STM32L1xx_HAL_TIM_H #ifdef __cplusplus extern "C" { #endif /* Includes ------------------------------------------------------------------*/ #include "stm32l1xx_hal_def.h" /** @addtogroup STM32L1xx_HAL_Driver * @{ */ /** @addtogroup TIM * @{ */ /* Exported types ------------------------------------------------------------*/ /** @defgroup TIM_Exported_Types TIM Exported Types * @{ */ /** * @brief TIM Time base Configuration Structure definition */ typedef struct { uint32_t Prescaler; /*!< Specifies the prescaler value used to divide the TIM clock. This parameter can be a number between Min_Data = 0x0000 and Max_Data = 0xFFFF */ uint32_t CounterMode; /*!< Specifies the counter mode. This parameter can be a value of @ref TIM_Counter_Mode */ uint32_t Period; /*!< Specifies the period value to be loaded into the active Auto-Reload Register at the next update event. This parameter can be a number between Min_Data = 0x0000 and Max_Data = 0xFFFF. */ uint32_t ClockDivision; /*!< Specifies the clock division. This parameter can be a value of @ref TIM_ClockDivision */ } TIM_Base_InitTypeDef; /** * @brief TIM Output Compare Configuration Structure definition */ typedef struct { uint32_t OCMode; /*!< Specifies the TIM mode. This parameter can be a value of @ref TIM_Output_Compare_and_PWM_modes */ uint32_t Pulse; /*!< Specifies the pulse value to be loaded into the Capture Compare Register. This parameter can be a number between Min_Data = 0x0000 and Max_Data = 0xFFFF */ uint32_t OCPolarity; /*!< Specifies the output polarity. This parameter can be a value of @ref TIM_Output_Compare_Polarity */ uint32_t OCFastMode; /*!< Specifies the Fast mode state. This parameter can be a value of @ref TIM_Output_Fast_State @note This parameter is valid only in PWM1 and PWM2 mode. */ uint32_t OCIdleState; /*!< Specifies the TIM Output Compare pin state during Idle state. This parameter can be a value of @ref TIM_Output_Compare_Idle_State @note This parameter is valid only for TIM1 and TIM8. */ } TIM_OC_InitTypeDef; /** * @brief TIM One Pulse Mode Configuration Structure definition */ typedef struct { uint32_t OCMode; /*!< Specifies the TIM mode. This parameter can be a value of @ref TIM_Output_Compare_and_PWM_modes */ uint32_t Pulse; /*!< Specifies the pulse value to be loaded into the Capture Compare Register. This parameter can be a number between Min_Data = 0x0000 and Max_Data = 0xFFFF */ uint32_t OCPolarity; /*!< Specifies the output polarity. This parameter can be a value of @ref TIM_Output_Compare_Polarity */ uint32_t OCIdleState; /*!< Specifies the TIM Output Compare pin state during Idle state. This parameter can be a value of @ref TIM_Output_Compare_Idle_State @note This parameter is valid only for TIM1 and TIM8. */ uint32_t ICPolarity; /*!< Specifies the active edge of the input signal. This parameter can be a value of @ref TIM_Input_Capture_Polarity */ uint32_t ICSelection; /*!< Specifies the input. This parameter can be a value of @ref TIM_Input_Capture_Selection */ uint32_t ICFilter; /*!< Specifies the input capture filter. This parameter can be a number between Min_Data = 0x0 and Max_Data = 0xF */ } TIM_OnePulse_InitTypeDef; /** * @brief TIM Input Capture Configuration Structure definition */ typedef struct { uint32_t ICPolarity; /*!< Specifies the active edge of the input signal. This parameter can be a value of @ref TIM_Input_Capture_Polarity */ uint32_t ICSelection; /*!< Specifies the input. This parameter can be a value of @ref TIM_Input_Capture_Selection */ uint32_t ICPrescaler; /*!< Specifies the Input Capture Prescaler. This parameter can be a value of @ref TIM_Input_Capture_Prescaler */ uint32_t ICFilter; /*!< Specifies the input capture filter. This parameter can be a number between Min_Data = 0x0 and Max_Data = 0xF */ } TIM_IC_InitTypeDef; /** * @brief TIM Encoder Configuration Structure definition */ typedef struct { uint32_t EncoderMode; /*!< Specifies the active edge of the input signal. This parameter can be a value of @ref TIM_Encoder_Mode */ uint32_t IC1Polarity; /*!< Specifies the active edge of the input signal. This parameter can be a value of @ref TIM_Input_Capture_Polarity */ uint32_t IC1Selection; /*!< Specifies the input. This parameter can be a value of @ref TIM_Input_Capture_Selection */ uint32_t IC1Prescaler; /*!< Specifies the Input Capture Prescaler. This parameter can be a value of @ref TIM_Input_Capture_Prescaler */ uint32_t IC1Filter; /*!< Specifies the input capture filter. This parameter can be a number between Min_Data = 0x0 and Max_Data = 0xF */ uint32_t IC2Polarity; /*!< Specifies the active edge of the input signal. This parameter can be a value of @ref TIM_Input_Capture_Polarity */ uint32_t IC2Selection; /*!< Specifies the input. This parameter can be a value of @ref TIM_Input_Capture_Selection */ uint32_t IC2Prescaler; /*!< Specifies the Input Capture Prescaler. This parameter can be a value of @ref TIM_Input_Capture_Prescaler */ uint32_t IC2Filter; /*!< Specifies the input capture filter. This parameter can be a number between Min_Data = 0x0 and Max_Data = 0xF */ } TIM_Encoder_InitTypeDef; /** * @brief Clock Configuration Handle Structure definition */ typedef struct { uint32_t ClockSource; /*!< TIM clock sources This parameter can be a value of @ref TIM_Clock_Source */ uint32_t ClockPolarity; /*!< TIM clock polarity This parameter can be a value of @ref TIM_Clock_Polarity */ uint32_t ClockPrescaler; /*!< TIM clock prescaler This parameter can be a value of @ref TIM_Clock_Prescaler */ uint32_t ClockFilter; /*!< TIM clock filter This parameter can be a number between Min_Data = 0x0 and Max_Data = 0xF */ }TIM_ClockConfigTypeDef; /** * @brief Clear Input Configuration Handle Structure definition */ typedef struct { uint32_t ClearInputState; /*!< TIM clear Input state This parameter can be ENABLE or DISABLE */ uint32_t ClearInputSource; /*!< TIM clear Input sources This parameter can be a value of @ref TIM_ClearInput_Source */ uint32_t ClearInputPolarity; /*!< TIM Clear Input polarity This parameter can be a value of @ref TIM_ClearInput_Polarity */ uint32_t ClearInputPrescaler; /*!< TIM Clear Input prescaler This parameter can be a value of @ref TIM_ClearInput_Prescaler */ uint32_t ClearInputFilter; /*!< TIM Clear Input filter This parameter can be a number between Min_Data = 0x0 and Max_Data = 0xF */ }TIM_ClearInputConfigTypeDef; /** * @brief TIM Slave configuration Structure definition */ typedef struct { uint32_t SlaveMode; /*!< Slave mode selection This parameter can be a value of @ref TIM_Slave_Mode */ uint32_t InputTrigger; /*!< Input Trigger source This parameter can be a value of @ref TIM_Trigger_Selection */ uint32_t TriggerPolarity; /*!< Input Trigger polarity This parameter can be a value of @ref TIM_Trigger_Polarity */ uint32_t TriggerPrescaler; /*!< Input trigger prescaler This parameter can be a value of @ref TIM_Trigger_Prescaler */ uint32_t TriggerFilter; /*!< Input trigger filter This parameter can be a number between Min_Data = 0x0 and Max_Data = 0xF */ }TIM_SlaveConfigTypeDef; /** * @brief HAL State structures definition */ typedef enum { HAL_TIM_STATE_RESET = 0x00, /*!< Peripheral not yet initialized or disabled */ HAL_TIM_STATE_READY = 0x01, /*!< Peripheral Initialized and ready for use */ HAL_TIM_STATE_BUSY = 0x02, /*!< An internal process is ongoing */ HAL_TIM_STATE_TIMEOUT = 0x03, /*!< Timeout state */ HAL_TIM_STATE_ERROR = 0x04 /*!< Reception process is ongoing */ }HAL_TIM_StateTypeDef; /** * @brief HAL Active channel structures definition */ typedef enum { HAL_TIM_ACTIVE_CHANNEL_1 = 0x01, /*!< The active channel is 1 */ HAL_TIM_ACTIVE_CHANNEL_2 = 0x02, /*!< The active channel is 2 */ HAL_TIM_ACTIVE_CHANNEL_3 = 0x04, /*!< The active channel is 3 */ HAL_TIM_ACTIVE_CHANNEL_4 = 0x08, /*!< The active channel is 4 */ HAL_TIM_ACTIVE_CHANNEL_CLEARED = 0x00 /*!< All active channels cleared */ }HAL_TIM_ActiveChannel; /** * @brief TIM Time Base Handle Structure definition */ typedef struct { TIM_TypeDef *Instance; /*!< Register base address */ TIM_Base_InitTypeDef Init; /*!< TIM Time Base required parameters */ HAL_TIM_ActiveChannel Channel; /*!< Active channel */ DMA_HandleTypeDef *hdma[7]; /*!< DMA Handlers array This array is accessed by a @ref DMA_Handle_index */ HAL_LockTypeDef Lock; /*!< Locking object */ __IO HAL_TIM_StateTypeDef State; /*!< TIM operation state */ }TIM_HandleTypeDef; /** * @} */ /* Exported constants --------------------------------------------------------*/ /** @defgroup TIM_Exported_Constants TIM Exported Constants * @{ */ /** @defgroup TIM_Input_Channel_Polarity TIM_Input_Channel_Polarity * @{ */ #define TIM_INPUTCHANNELPOLARITY_RISING ((uint32_t)0x00000000) /*!< Polarity for TIx source */ #define TIM_INPUTCHANNELPOLARITY_FALLING (TIM_CCER_CC1P) /*!< Polarity for TIx source */ #define TIM_INPUTCHANNELPOLARITY_BOTHEDGE (TIM_CCER_CC1P | TIM_CCER_CC1NP) /*!< Polarity for TIx source */ /** * @} */ /** @defgroup TIM_ETR_Polarity TIM_ETR_Polarity * @{ */ #define TIM_ETRPOLARITY_INVERTED (TIM_SMCR_ETP) /*!< Polarity for ETR source */ #define TIM_ETRPOLARITY_NONINVERTED ((uint32_t)0x0000) /*!< Polarity for ETR source */ /** * @} */ /** @defgroup TIM_ETR_Prescaler TIM_ETR_Prescaler * @{ */ #define TIM_ETRPRESCALER_DIV1 ((uint32_t)0x0000) /*!< No prescaler is used */ #define TIM_ETRPRESCALER_DIV2 (TIM_SMCR_ETPS_0) /*!< ETR input source is divided by 2 */ #define TIM_ETRPRESCALER_DIV4 (TIM_SMCR_ETPS_1) /*!< ETR input source is divided by 4 */ #define TIM_ETRPRESCALER_DIV8 (TIM_SMCR_ETPS) /*!< ETR input source is divided by 8 */ /** * @} */ /** @defgroup TIM_Counter_Mode TIM_Counter_Mode * @{ */ #define TIM_COUNTERMODE_UP ((uint32_t)0x0000) #define TIM_COUNTERMODE_DOWN TIM_CR1_DIR #define TIM_COUNTERMODE_CENTERALIGNED1 TIM_CR1_CMS_0 #define TIM_COUNTERMODE_CENTERALIGNED2 TIM_CR1_CMS_1 #define TIM_COUNTERMODE_CENTERALIGNED3 TIM_CR1_CMS #define IS_TIM_COUNTER_MODE(MODE) (((MODE) == TIM_COUNTERMODE_UP) || \ ((MODE) == TIM_COUNTERMODE_DOWN) || \ ((MODE) == TIM_COUNTERMODE_CENTERALIGNED1) || \ ((MODE) == TIM_COUNTERMODE_CENTERALIGNED2) || \ ((MODE) == TIM_COUNTERMODE_CENTERALIGNED3)) /** * @} */ /** @defgroup TIM_ClockDivision TIM_ClockDivision * @{ */ #define TIM_CLOCKDIVISION_DIV1 ((uint32_t)0x0000) #define TIM_CLOCKDIVISION_DIV2 (TIM_CR1_CKD_0) #define TIM_CLOCKDIVISION_DIV4 (TIM_CR1_CKD_1) #define IS_TIM_CLOCKDIVISION_DIV(DIV) (((DIV) == TIM_CLOCKDIVISION_DIV1) || \ ((DIV) == TIM_CLOCKDIVISION_DIV2) || \ ((DIV) == TIM_CLOCKDIVISION_DIV4)) /** * @} */ /** @defgroup TIM_Output_Compare_and_PWM_modes TIM_Output_Compare_and_PWM_modes * @{ */ #define TIM_OCMODE_TIMING ((uint32_t)0x0000) #define TIM_OCMODE_ACTIVE (TIM_CCMR1_OC1M_0) #define TIM_OCMODE_INACTIVE (TIM_CCMR1_OC1M_1) #define TIM_OCMODE_TOGGLE (TIM_CCMR1_OC1M_0 | TIM_CCMR1_OC1M_1) #define TIM_OCMODE_PWM1 (TIM_CCMR1_OC1M_1 | TIM_CCMR1_OC1M_2) #define TIM_OCMODE_PWM2 (TIM_CCMR1_OC1M) #define TIM_OCMODE_FORCED_ACTIVE (TIM_CCMR1_OC1M_0 | TIM_CCMR1_OC1M_2) #define TIM_OCMODE_FORCED_INACTIVE (TIM_CCMR1_OC1M_2) #define IS_TIM_PWM_MODE(MODE) (((MODE) == TIM_OCMODE_PWM1) || \ ((MODE) == TIM_OCMODE_PWM2)) #define IS_TIM_OC_MODE(MODE) (((MODE) == TIM_OCMODE_TIMING) || \ ((MODE) == TIM_OCMODE_ACTIVE) || \ ((MODE) == TIM_OCMODE_INACTIVE) || \ ((MODE) == TIM_OCMODE_TOGGLE) || \ ((MODE) == TIM_OCMODE_FORCED_ACTIVE) || \ ((MODE) == TIM_OCMODE_FORCED_INACTIVE)) /** * @} */ /** @defgroup TIM_Output_Compare_State TIM_Output_Compare_State * @{ */ #define TIM_OUTPUTSTATE_DISABLE ((uint32_t)0x0000) #define TIM_OUTPUTSTATE_ENABLE (TIM_CCER_CC1E) #define IS_TIM_OUTPUT_STATE(STATE) (((STATE) == TIM_OUTPUTSTATE_DISABLE) || \ ((STATE) == TIM_OUTPUTSTATE_ENABLE)) /** * @} */ /** @defgroup TIM_Output_Fast_State TIM_Output_Fast_State * @{ */ #define TIM_OCFAST_DISABLE ((uint32_t)0x0000) #define TIM_OCFAST_ENABLE (TIM_CCMR1_OC1FE) #define IS_TIM_FAST_STATE(STATE) (((STATE) == TIM_OCFAST_DISABLE) || \ ((STATE) == TIM_OCFAST_ENABLE)) /** * @} */ /** @defgroup TIM_Output_Compare_Polarity TIM_Output_Compare_Polarity * @{ */ #define TIM_OCPOLARITY_HIGH ((uint32_t)0x0000) #define TIM_OCPOLARITY_LOW (TIM_CCER_CC1P) #define IS_TIM_OC_POLARITY(POLARITY) (((POLARITY) == TIM_OCPOLARITY_HIGH) || \ ((POLARITY) == TIM_OCPOLARITY_LOW)) /** * @} */ /** @defgroup TIM_Output_Compare_Idle_State TIM_Output_Compare_Idle_State * @{ */ #define TIM_OCIDLESTATE_SET (TIM_CR2_OIS1) #define TIM_OCIDLESTATE_RESET ((uint32_t)0x0000) #define IS_TIM_OCIDLE_STATE(STATE) (((STATE) == TIM_OCIDLESTATE_SET) || \ ((STATE) == TIM_OCIDLESTATE_RESET)) /** * @} */ /** @defgroup TIM_Channel TIM_Channel * @{ */ #define TIM_CHANNEL_1 ((uint32_t)0x0000) #define TIM_CHANNEL_2 ((uint32_t)0x0004) #define TIM_CHANNEL_3 ((uint32_t)0x0008) #define TIM_CHANNEL_4 ((uint32_t)0x000C) #define TIM_CHANNEL_ALL ((uint32_t)0x0018) #define IS_TIM_CHANNELS(CHANNEL) (((CHANNEL) == TIM_CHANNEL_1) || \ ((CHANNEL) == TIM_CHANNEL_2) || \ ((CHANNEL) == TIM_CHANNEL_3) || \ ((CHANNEL) == TIM_CHANNEL_4) || \ ((CHANNEL) == TIM_CHANNEL_ALL)) #define IS_TIM_PWMI_CHANNELS(CHANNEL) (((CHANNEL) == TIM_CHANNEL_1) || \ ((CHANNEL) == TIM_CHANNEL_2)) #define IS_TIM_OPM_CHANNELS(CHANNEL) (((CHANNEL) == TIM_CHANNEL_1) || \ ((CHANNEL) == TIM_CHANNEL_2)) /** * @} */ /** @defgroup TIM_Input_Capture_Polarity TIM_Input_Capture_Polarity * @{ */ #define TIM_ICPOLARITY_RISING TIM_INPUTCHANNELPOLARITY_RISING #define TIM_ICPOLARITY_FALLING TIM_INPUTCHANNELPOLARITY_FALLING #define TIM_ICPOLARITY_BOTHEDGE TIM_INPUTCHANNELPOLARITY_BOTHEDGE #define IS_TIM_IC_POLARITY(POLARITY) (((POLARITY) == TIM_ICPOLARITY_RISING) || \ ((POLARITY) == TIM_ICPOLARITY_FALLING) || \ ((POLARITY) == TIM_ICPOLARITY_BOTHEDGE)) /** * @} */ /** @defgroup TIM_Input_Capture_Selection TIM_Input_Capture_Selection * @{ */ #define TIM_ICSELECTION_DIRECTTI (TIM_CCMR1_CC1S_0) /*!< TIM Input 1, 2, 3 or 4 is selected to be connected to IC1, IC2, IC3 or IC4, respectively */ #define TIM_ICSELECTION_INDIRECTTI (TIM_CCMR1_CC1S_1) /*!< TIM Input 1, 2, 3 or 4 is selected to be connected to IC2, IC1, IC4 or IC3, respectively */ #define TIM_ICSELECTION_TRC (TIM_CCMR1_CC1S) /*!< TIM Input 1, 2, 3 or 4 is selected to be connected to TRC */ #define IS_TIM_IC_SELECTION(SELECTION) (((SELECTION) == TIM_ICSELECTION_DIRECTTI) || \ ((SELECTION) == TIM_ICSELECTION_INDIRECTTI) || \ ((SELECTION) == TIM_ICSELECTION_TRC)) /** * @} */ /** @defgroup TIM_Input_Capture_Prescaler TIM_Input_Capture_Prescaler * @{ */ #define TIM_ICPSC_DIV1 ((uint32_t)0x0000) /*!< Capture performed each time an edge is detected on the capture input */ #define TIM_ICPSC_DIV2 (TIM_CCMR1_IC1PSC_0) /*!< Capture performed once every 2 events */ #define TIM_ICPSC_DIV4 (TIM_CCMR1_IC1PSC_1) /*!< Capture performed once every 4 events */ #define TIM_ICPSC_DIV8 (TIM_CCMR1_IC1PSC) /*!< Capture performed once every 8 events */ #define IS_TIM_IC_PRESCALER(PRESCALER) (((PRESCALER) == TIM_ICPSC_DIV1) || \ ((PRESCALER) == TIM_ICPSC_DIV2) || \ ((PRESCALER) == TIM_ICPSC_DIV4) || \ ((PRESCALER) == TIM_ICPSC_DIV8)) /** * @} */ /** @defgroup TIM_One_Pulse_Mode TIM_One_Pulse_Mode * @{ */ #define TIM_OPMODE_SINGLE (TIM_CR1_OPM) #define TIM_OPMODE_REPETITIVE ((uint32_t)0x0000) #define IS_TIM_OPM_MODE(MODE) (((MODE) == TIM_OPMODE_SINGLE) || \ ((MODE) == TIM_OPMODE_REPETITIVE)) /** * @} */ /** @defgroup TIM_Encoder_Mode TIM_Encoder_Mode * @{ */ #define TIM_ENCODERMODE_TI1 (TIM_SMCR_SMS_0) #define TIM_ENCODERMODE_TI2 (TIM_SMCR_SMS_1) #define TIM_ENCODERMODE_TI12 (TIM_SMCR_SMS_1 | TIM_SMCR_SMS_0) #define IS_TIM_ENCODER_MODE(MODE) (((MODE) == TIM_ENCODERMODE_TI1) || \ ((MODE) == TIM_ENCODERMODE_TI2) || \ ((MODE) == TIM_ENCODERMODE_TI12)) /** * @} */ /** @defgroup TIM_Interrupt_definition TIM_Interrupt_definition * @{ */ #define TIM_IT_UPDATE (TIM_DIER_UIE) #define TIM_IT_CC1 (TIM_DIER_CC1IE) #define TIM_IT_CC2 (TIM_DIER_CC2IE) #define TIM_IT_CC3 (TIM_DIER_CC3IE) #define TIM_IT_CC4 (TIM_DIER_CC4IE) #define TIM_IT_TRIGGER (TIM_DIER_TIE) /** * @} */ /** @defgroup TIM_DMA_sources TIM_DMA_sources * @{ */ #define TIM_DMA_UPDATE (TIM_DIER_UDE) #define TIM_DMA_CC1 (TIM_DIER_CC1DE) #define TIM_DMA_CC2 (TIM_DIER_CC2DE) #define TIM_DMA_CC3 (TIM_DIER_CC3DE) #define TIM_DMA_CC4 (TIM_DIER_CC4DE) #define TIM_DMA_TRIGGER (TIM_DIER_TDE) #define IS_TIM_DMA_SOURCE(SOURCE) ((((SOURCE) & 0xFFFF80FF) == 0x00000000) && ((SOURCE) != 0x00000000)) /** * @} */ /** @defgroup TIM_Event_Source TIM_Event_Source * @{ */ #define TIM_EventSource_Update TIM_EGR_UG #define TIM_EventSource_CC1 TIM_EGR_CC1G #define TIM_EventSource_CC2 TIM_EGR_CC2G #define TIM_EventSource_CC3 TIM_EGR_CC3G #define TIM_EventSource_CC4 TIM_EGR_CC4G #define TIM_EventSource_Trigger TIM_EGR_TG #define IS_TIM_EVENT_SOURCE(SOURCE) ((((SOURCE) & 0xFFFFFF00) == 0x00000000) && ((SOURCE) != 0x00000000)) /** * @} */ /** @defgroup TIM_Flag_definition TIM_Flag_definition * @{ */ #define TIM_FLAG_UPDATE (TIM_SR_UIF) #define TIM_FLAG_CC1 (TIM_SR_CC1IF) #define TIM_FLAG_CC2 (TIM_SR_CC2IF) #define TIM_FLAG_CC3 (TIM_SR_CC3IF) #define TIM_FLAG_CC4 (TIM_SR_CC4IF) #define TIM_FLAG_TRIGGER (TIM_SR_TIF) #define TIM_FLAG_CC1OF (TIM_SR_CC1OF) #define TIM_FLAG_CC2OF (TIM_SR_CC2OF) #define TIM_FLAG_CC3OF (TIM_SR_CC3OF) #define TIM_FLAG_CC4OF (TIM_SR_CC4OF) /** * @} */ /** @defgroup TIM_Clock_Source TIM_Clock_Source * @{ */ #define TIM_CLOCKSOURCE_ETRMODE2 (TIM_SMCR_ETPS_1) #define TIM_CLOCKSOURCE_INTERNAL (TIM_SMCR_ETPS_0) #define TIM_CLOCKSOURCE_ITR0 ((uint32_t)0x0000) #define TIM_CLOCKSOURCE_ITR1 (TIM_SMCR_TS_0) #define TIM_CLOCKSOURCE_ITR2 (TIM_SMCR_TS_1) #define TIM_CLOCKSOURCE_ITR3 (TIM_SMCR_TS_0 | TIM_SMCR_TS_1) #define TIM_CLOCKSOURCE_TI1ED (TIM_SMCR_TS_2) #define TIM_CLOCKSOURCE_TI1 (TIM_SMCR_TS_0 | TIM_SMCR_TS_2) #define TIM_CLOCKSOURCE_TI2 (TIM_SMCR_TS_1 | TIM_SMCR_TS_2) #define TIM_CLOCKSOURCE_ETRMODE1 (TIM_SMCR_TS) #define IS_TIM_CLOCKSOURCE(CLOCK) (((CLOCK) == TIM_CLOCKSOURCE_INTERNAL) || \ ((CLOCK) == TIM_CLOCKSOURCE_ETRMODE2) || \ ((CLOCK) == TIM_CLOCKSOURCE_ITR0) || \ ((CLOCK) == TIM_CLOCKSOURCE_ITR1) || \ ((CLOCK) == TIM_CLOCKSOURCE_ITR2) || \ ((CLOCK) == TIM_CLOCKSOURCE_ITR3) || \ ((CLOCK) == TIM_CLOCKSOURCE_TI1ED) || \ ((CLOCK) == TIM_CLOCKSOURCE_TI1) || \ ((CLOCK) == TIM_CLOCKSOURCE_TI2) || \ ((CLOCK) == TIM_CLOCKSOURCE_ETRMODE1)) /** * @} */ /** @defgroup TIM_Clock_Polarity TIM_Clock_Polarity * @{ */ #define TIM_CLOCKPOLARITY_INVERTED TIM_ETRPOLARITY_INVERTED /*!< Polarity for ETRx clock sources */ #define TIM_CLOCKPOLARITY_NONINVERTED TIM_ETRPOLARITY_NONINVERTED /*!< Polarity for ETRx clock sources */ #define TIM_CLOCKPOLARITY_RISING TIM_INPUTCHANNELPOLARITY_RISING /*!< Polarity for TIx clock sources */ #define TIM_CLOCKPOLARITY_FALLING TIM_INPUTCHANNELPOLARITY_FALLING /*!< Polarity for TIx clock sources */ #define TIM_CLOCKPOLARITY_BOTHEDGE TIM_INPUTCHANNELPOLARITY_BOTHEDGE /*!< Polarity for TIx clock sources */ #define IS_TIM_CLOCKPOLARITY(POLARITY) (((POLARITY) == TIM_CLOCKPOLARITY_INVERTED) || \ ((POLARITY) == TIM_CLOCKPOLARITY_NONINVERTED) || \ ((POLARITY) == TIM_CLOCKPOLARITY_RISING) || \ ((POLARITY) == TIM_CLOCKPOLARITY_FALLING) || \ ((POLARITY) == TIM_CLOCKPOLARITY_BOTHEDGE)) /** * @} */ /** @defgroup TIM_Clock_Prescaler TIM_Clock_Prescaler * @{ */ #define TIM_CLOCKPRESCALER_DIV1 TIM_ETRPRESCALER_DIV1 /*!< No prescaler is used */ #define TIM_CLOCKPRESCALER_DIV2 TIM_ETRPRESCALER_DIV2 /*!< Prescaler for External ETR Clock: Capture performed once every 2 events. */ #define TIM_CLOCKPRESCALER_DIV4 TIM_ETRPRESCALER_DIV4 /*!< Prescaler for External ETR Clock: Capture performed once every 4 events. */ #define TIM_CLOCKPRESCALER_DIV8 TIM_ETRPRESCALER_DIV8 /*!< Prescaler for External ETR Clock: Capture performed once every 8 events. */ #define IS_TIM_CLOCKPRESCALER(PRESCALER) (((PRESCALER) == TIM_CLOCKPRESCALER_DIV1) || \ ((PRESCALER) == TIM_CLOCKPRESCALER_DIV2) || \ ((PRESCALER) == TIM_CLOCKPRESCALER_DIV4) || \ ((PRESCALER) == TIM_CLOCKPRESCALER_DIV8)) /** * @} */ /** @defgroup TIM_Clock_Filter TIM_Clock_Filter * @{ */ #define IS_TIM_CLOCKFILTER(ICFILTER) ((ICFILTER) <= 0xF) /** * @} */ /** @defgroup TIM_ClearInput_Source TIM_ClearInput_Source * @{ */ #define TIM_CLEARINPUTSOURCE_ETR ((uint32_t)0x0001) #define TIM_CLEARINPUTSOURCE_OCREFCLR ((uint32_t)0x0002) #define TIM_CLEARINPUTSOURCE_NONE ((uint32_t)0x0000) #define IS_TIM_CLEARINPUT_SOURCE(SOURCE) (((SOURCE) == TIM_CLEARINPUTSOURCE_ETR) || \ ((SOURCE) == TIM_CLEARINPUTSOURCE_OCREFCLR) || \ ((SOURCE) == TIM_CLEARINPUTSOURCE_NONE)) /** * @} */ /** @defgroup TIM_ClearInput_Polarity TIM_ClearInput_Polarity * @{ */ #define TIM_CLEARINPUTPOLARITY_INVERTED TIM_ETRPOLARITY_INVERTED /*!< Polarity for ETRx pin */ #define TIM_CLEARINPUTPOLARITY_NONINVERTED TIM_ETRPOLARITY_NONINVERTED /*!< Polarity for ETRx pin */ #define IS_TIM_CLEARINPUT_POLARITY(POLARITY) (((POLARITY) == TIM_CLEARINPUTPOLARITY_INVERTED) || \ ((POLARITY) == TIM_CLEARINPUTPOLARITY_NONINVERTED)) /** * @} */ /** @defgroup TIM_ClearInput_Prescaler TIM_ClearInput_Prescaler * @{ */ #define TIM_CLEARINPUTPRESCALER_DIV1 TIM_ETRPRESCALER_DIV1 /*!< No prescaler is used */ #define TIM_CLEARINPUTPRESCALER_DIV2 TIM_ETRPRESCALER_DIV2 /*!< Prescaler for External ETR pin: Capture performed once every 2 events. */ #define TIM_CLEARINPUTPRESCALER_DIV4 TIM_ETRPRESCALER_DIV4 /*!< Prescaler for External ETR pin: Capture performed once every 4 events. */ #define TIM_CLEARINPUTPRESCALER_DIV8 TIM_ETRPRESCALER_DIV8 /*!< Prescaler for External ETR pin: Capture performed once every 8 events. */ #define IS_TIM_CLEARINPUT_PRESCALER(PRESCALER) (((PRESCALER) == TIM_CLEARINPUTPRESCALER_DIV1) || \ ((PRESCALER) == TIM_CLEARINPUTPRESCALER_DIV2) || \ ((PRESCALER) == TIM_CLEARINPUTPRESCALER_DIV4) || \ ((PRESCALER) == TIM_CLEARINPUTPRESCALER_DIV8)) /** * @} */ /** @defgroup TIM_ClearInput_Filter TIM_ClearInput_Filter * @{ */ #define IS_TIM_CLEARINPUT_FILTER(ICFILTER) ((ICFILTER) <= 0xF) /** * @} */ /** @defgroup TIM_OSSR_Off_State_Selection_for_Run_mode_state TIM_OSSR_Off_State_Selection_for_Run_mode_state * @{ */ #define TIM_OSSR_ENABLE (TIM_BDTR_OSSR) #define TIM_OSSR_DISABLE ((uint32_t)0x0000) #define IS_TIM_OSSR_STATE(STATE) (((STATE) == TIM_OSSR_ENABLE) || \ ((STATE) == TIM_OSSR_DISABLE)) /** * @} */ /** @defgroup TIM_OSSI_Off_State_Selection_for_Idle_mode_state TIM_OSSI_Off_State_Selection_for_Idle_mode_state * @{ */ #define TIM_OSSI_ENABLE (TIM_BDTR_OSSI) #define TIM_OSSI_DISABLE ((uint32_t)0x0000) #define IS_TIM_OSSI_STATE(STATE) (((STATE) == TIM_OSSI_ENABLE) || \ ((STATE) == TIM_OSSI_DISABLE)) /** * @} */ /** @defgroup TIM_Lock_level TIM_Lock_level * @{ */ #define TIM_LOCKLEVEL_OFF ((uint32_t)0x0000) #define TIM_LOCKLEVEL_1 (TIM_BDTR_LOCK_0) #define TIM_LOCKLEVEL_2 (TIM_BDTR_LOCK_1) #define TIM_LOCKLEVEL_3 (TIM_BDTR_LOCK) #define IS_TIM_LOCK_LEVEL(LEVEL) (((LEVEL) == TIM_LOCKLEVEL_OFF) || \ ((LEVEL) == TIM_LOCKLEVEL_1) || \ ((LEVEL) == TIM_LOCKLEVEL_2) || \ ((LEVEL) == TIM_LOCKLEVEL_3)) /** * @} */ /** @defgroup TIM_AOE_Bit_Set_Reset TIM_AOE_Bit_Set_Reset * @{ */ #define TIM_AUTOMATICOUTPUT_ENABLE (TIM_BDTR_AOE) #define TIM_AUTOMATICOUTPUT_DISABLE ((uint32_t)0x0000) #define IS_TIM_AUTOMATIC_OUTPUT_STATE(STATE) (((STATE) == TIM_AUTOMATICOUTPUT_ENABLE) || \ ((STATE) == TIM_AUTOMATICOUTPUT_DISABLE)) /** * @} */ /** @defgroup TIM_Master_Mode_Selection TIM_Master_Mode_Selection * @{ */ #define TIM_TRGO_RESET ((uint32_t)0x0000) #define TIM_TRGO_ENABLE (TIM_CR2_MMS_0) #define TIM_TRGO_UPDATE (TIM_CR2_MMS_1) #define TIM_TRGO_OC1 ((TIM_CR2_MMS_1 | TIM_CR2_MMS_0)) #define TIM_TRGO_OC1REF (TIM_CR2_MMS_2) #define TIM_TRGO_OC2REF ((TIM_CR2_MMS_2 | TIM_CR2_MMS_0)) #define TIM_TRGO_OC3REF ((TIM_CR2_MMS_2 | TIM_CR2_MMS_1)) #define TIM_TRGO_OC4REF ((TIM_CR2_MMS_2 | TIM_CR2_MMS_1 | TIM_CR2_MMS_0)) #define IS_TIM_TRGO_SOURCE(SOURCE) (((SOURCE) == TIM_TRGO_RESET) || \ ((SOURCE) == TIM_TRGO_ENABLE) || \ ((SOURCE) == TIM_TRGO_UPDATE) || \ ((SOURCE) == TIM_TRGO_OC1) || \ ((SOURCE) == TIM_TRGO_OC1REF) || \ ((SOURCE) == TIM_TRGO_OC2REF) || \ ((SOURCE) == TIM_TRGO_OC3REF) || \ ((SOURCE) == TIM_TRGO_OC4REF)) /** * @} */ /** @defgroup TIM_Slave_Mode TIM_Slave_Mode * @{ */ #define TIM_SLAVEMODE_DISABLE ((uint32_t)0x0000) #define TIM_SLAVEMODE_RESET ((uint32_t)0x0004) #define TIM_SLAVEMODE_GATED ((uint32_t)0x0005) #define TIM_SLAVEMODE_TRIGGER ((uint32_t)0x0006) #define TIM_SLAVEMODE_EXTERNAL1 ((uint32_t)0x0007) #define IS_TIM_SLAVE_MODE(MODE) (((MODE) == TIM_SLAVEMODE_DISABLE) || \ ((MODE) == TIM_SLAVEMODE_GATED) || \ ((MODE) == TIM_SLAVEMODE_RESET) || \ ((MODE) == TIM_SLAVEMODE_TRIGGER) || \ ((MODE) == TIM_SLAVEMODE_EXTERNAL1)) /** * @} */ /** @defgroup TIM_Master_Slave_Mode TIM_Master_Slave_Mode * @{ */ #define TIM_MASTERSLAVEMODE_ENABLE ((uint32_t)0x0080) #define TIM_MASTERSLAVEMODE_DISABLE ((uint32_t)0x0000) #define IS_TIM_MSM_STATE(STATE) (((STATE) == TIM_MASTERSLAVEMODE_ENABLE) || \ ((STATE) == TIM_MASTERSLAVEMODE_DISABLE)) /** * @} */ /** @defgroup TIM_Trigger_Selection TIM_Trigger_Selection * @{ */ #define TIM_TS_ITR0 ((uint32_t)0x0000) #define TIM_TS_ITR1 ((uint32_t)0x0010) #define TIM_TS_ITR2 ((uint32_t)0x0020) #define TIM_TS_ITR3 ((uint32_t)0x0030) #define TIM_TS_TI1F_ED ((uint32_t)0x0040) #define TIM_TS_TI1FP1 ((uint32_t)0x0050) #define TIM_TS_TI2FP2 ((uint32_t)0x0060) #define TIM_TS_ETRF ((uint32_t)0x0070) #define TIM_TS_NONE ((uint32_t)0xFFFF) #define IS_TIM_TRIGGER_SELECTION(SELECTION) (((SELECTION) == TIM_TS_ITR0) || \ ((SELECTION) == TIM_TS_ITR1) || \ ((SELECTION) == TIM_TS_ITR2) || \ ((SELECTION) == TIM_TS_ITR3) || \ ((SELECTION) == TIM_TS_TI1F_ED) || \ ((SELECTION) == TIM_TS_TI1FP1) || \ ((SELECTION) == TIM_TS_TI2FP2) || \ ((SELECTION) == TIM_TS_ETRF)) #define IS_TIM_INTERNAL_TRIGGER_SELECTION(SELECTION) (((SELECTION) == TIM_TS_ITR0) || \ ((SELECTION) == TIM_TS_ITR1) || \ ((SELECTION) == TIM_TS_ITR2) || \ ((SELECTION) == TIM_TS_ITR3)) #define IS_TIM_INTERNAL_TRIGGEREVENT_SELECTION(SELECTION) (((SELECTION) == TIM_TS_ITR0) || \ ((SELECTION) == TIM_TS_ITR1) || \ ((SELECTION) == TIM_TS_ITR2) || \ ((SELECTION) == TIM_TS_ITR3) || \ ((SELECTION) == TIM_TS_NONE)) /** * @} */ /** @defgroup TIM_Trigger_Polarity TIM_Trigger_Polarity * @{ */ #define TIM_TRIGGERPOLARITY_INVERTED TIM_ETRPOLARITY_INVERTED /*!< Polarity for ETRx trigger sources */ #define TIM_TRIGGERPOLARITY_NONINVERTED TIM_ETRPOLARITY_NONINVERTED /*!< Polarity for ETRx trigger sources */ #define TIM_TRIGGERPOLARITY_RISING TIM_INPUTCHANNELPOLARITY_RISING /*!< Polarity for TIxFPx or TI1_ED trigger sources */ #define TIM_TRIGGERPOLARITY_FALLING TIM_INPUTCHANNELPOLARITY_FALLING /*!< Polarity for TIxFPx or TI1_ED trigger sources */ #define TIM_TRIGGERPOLARITY_BOTHEDGE TIM_INPUTCHANNELPOLARITY_BOTHEDGE /*!< Polarity for TIxFPx or TI1_ED trigger sources */ #define IS_TIM_TRIGGERPOLARITY(POLARITY) (((POLARITY) == TIM_TRIGGERPOLARITY_INVERTED ) || \ ((POLARITY) == TIM_TRIGGERPOLARITY_NONINVERTED) || \ ((POLARITY) == TIM_TRIGGERPOLARITY_RISING ) || \ ((POLARITY) == TIM_TRIGGERPOLARITY_FALLING ) || \ ((POLARITY) == TIM_TRIGGERPOLARITY_BOTHEDGE )) /** * @} */ /** @defgroup TIM_Trigger_Prescaler TIM_Trigger_Prescaler * @{ */ #define TIM_TRIGGERPRESCALER_DIV1 TIM_ETRPRESCALER_DIV1 /*!< No prescaler is used */ #define TIM_TRIGGERPRESCALER_DIV2 TIM_ETRPRESCALER_DIV2 /*!< Prescaler for External ETR Trigger: Capture performed once every 2 events. */ #define TIM_TRIGGERPRESCALER_DIV4 TIM_ETRPRESCALER_DIV4 /*!< Prescaler for External ETR Trigger: Capture performed once every 4 events. */ #define TIM_TRIGGERPRESCALER_DIV8 TIM_ETRPRESCALER_DIV8 /*!< Prescaler for External ETR Trigger: Capture performed once every 8 events. */ #define IS_TIM_TRIGGERPRESCALER(PRESCALER) (((PRESCALER) == TIM_TRIGGERPRESCALER_DIV1) || \ ((PRESCALER) == TIM_TRIGGERPRESCALER_DIV2) || \ ((PRESCALER) == TIM_TRIGGERPRESCALER_DIV4) || \ ((PRESCALER) == TIM_TRIGGERPRESCALER_DIV8)) /** * @} */ /** @defgroup TIM_Trigger_Filter TIM_Trigger_Filter * @{ */ #define IS_TIM_TRIGGERFILTER(ICFILTER) ((ICFILTER) <= 0xF) /** * @} */ /** @defgroup TIM_TI1_Selection TIM_TI1_Selection * @{ */ #define TIM_TI1SELECTION_CH1 ((uint32_t)0x0000) #define TIM_TI1SELECTION_XORCOMBINATION (TIM_CR2_TI1S) #define IS_TIM_TI1SELECTION(TI1SELECTION) (((TI1SELECTION) == TIM_TI1SELECTION_CH1) || \ ((TI1SELECTION) == TIM_TI1SELECTION_XORCOMBINATION)) /** * @} */ /** @defgroup TIM_DMA_Base_address TIM_DMA_Base_address * @{ */ #define TIM_DMABase_CR1 (0x00000000) #define TIM_DMABase_CR2 (0x00000001) #define TIM_DMABase_SMCR (0x00000002) #define TIM_DMABase_DIER (0x00000003) #define TIM_DMABase_SR (0x00000004) #define TIM_DMABase_EGR (0x00000005) #define TIM_DMABase_CCMR1 (0x00000006) #define TIM_DMABase_CCMR2 (0x00000007) #define TIM_DMABase_CCER (0x00000008) #define TIM_DMABase_CNT (0x00000009) #define TIM_DMABase_PSC (0x0000000A) #define TIM_DMABase_ARR (0x0000000B) #define TIM_DMABase_CCR1 (0x0000000D) #define TIM_DMABase_CCR2 (0x0000000E) #define TIM_DMABase_CCR3 (0x0000000F) #define TIM_DMABase_CCR4 (0x00000010) #define TIM_DMABase_DCR (0x00000012) #define TIM_DMABase_OR (0x00000013) #define IS_TIM_DMA_BASE(BASE) (((BASE) == TIM_DMABase_CR1) || \ ((BASE) == TIM_DMABase_CR2) || \ ((BASE) == TIM_DMABase_SMCR) || \ ((BASE) == TIM_DMABase_DIER) || \ ((BASE) == TIM_DMABase_SR) || \ ((BASE) == TIM_DMABase_EGR) || \ ((BASE) == TIM_DMABase_CCMR1) || \ ((BASE) == TIM_DMABase_CCMR2) || \ ((BASE) == TIM_DMABase_CCER) || \ ((BASE) == TIM_DMABase_CNT) || \ ((BASE) == TIM_DMABase_PSC) || \ ((BASE) == TIM_DMABase_ARR) || \ ((BASE) == TIM_DMABase_CCR1) || \ ((BASE) == TIM_DMABase_CCR2) || \ ((BASE) == TIM_DMABase_CCR3) || \ ((BASE) == TIM_DMABase_CCR4) || \ ((BASE) == TIM_DMABase_DCR) || \ ((BASE) == TIM_DMABase_OR)) /** * @} */ /** @defgroup TIM_DMA_Burst_Length TIM_DMA_Burst_Length * @{ */ #define TIM_DMABurstLength_1Transfer (0x00000000) #define TIM_DMABurstLength_2Transfers (0x00000100) #define TIM_DMABurstLength_3Transfers (0x00000200) #define TIM_DMABurstLength_4Transfers (0x00000300) #define TIM_DMABurstLength_5Transfers (0x00000400) #define TIM_DMABurstLength_6Transfers (0x00000500) #define TIM_DMABurstLength_7Transfers (0x00000600) #define TIM_DMABurstLength_8Transfers (0x00000700) #define TIM_DMABurstLength_9Transfers (0x00000800) #define TIM_DMABurstLength_10Transfers (0x00000900) #define TIM_DMABurstLength_11Transfers (0x00000A00) #define TIM_DMABurstLength_12Transfers (0x00000B00) #define TIM_DMABurstLength_13Transfers (0x00000C00) #define TIM_DMABurstLength_14Transfers (0x00000D00) #define TIM_DMABurstLength_15Transfers (0x00000E00) #define TIM_DMABurstLength_16Transfers (0x00000F00) #define TIM_DMABurstLength_17Transfers (0x00001000) #define TIM_DMABurstLength_18Transfers (0x00001100) #define IS_TIM_DMA_LENGTH(LENGTH) (((LENGTH) == TIM_DMABurstLength_1Transfer) || \ ((LENGTH) == TIM_DMABurstLength_2Transfers) || \ ((LENGTH) == TIM_DMABurstLength_3Transfers) || \ ((LENGTH) == TIM_DMABurstLength_4Transfers) || \ ((LENGTH) == TIM_DMABurstLength_5Transfers) || \ ((LENGTH) == TIM_DMABurstLength_6Transfers) || \ ((LENGTH) == TIM_DMABurstLength_7Transfers) || \ ((LENGTH) == TIM_DMABurstLength_8Transfers) || \ ((LENGTH) == TIM_DMABurstLength_9Transfers) || \ ((LENGTH) == TIM_DMABurstLength_10Transfers) || \ ((LENGTH) == TIM_DMABurstLength_11Transfers) || \ ((LENGTH) == TIM_DMABurstLength_12Transfers) || \ ((LENGTH) == TIM_DMABurstLength_13Transfers) || \ ((LENGTH) == TIM_DMABurstLength_14Transfers) || \ ((LENGTH) == TIM_DMABurstLength_15Transfers) || \ ((LENGTH) == TIM_DMABurstLength_16Transfers) || \ ((LENGTH) == TIM_DMABurstLength_17Transfers) || \ ((LENGTH) == TIM_DMABurstLength_18Transfers)) /** * @} */ /** @defgroup TIM_Input_Capture_Filer_Value TIM_Input_Capture_Filer_Value * @{ */ #define IS_TIM_IC_FILTER(ICFILTER) ((ICFILTER) <= 0xF) /** * @} */ /** @defgroup DMA_Handle_index DMA_Handle_index * @{ */ #define TIM_DMA_ID_UPDATE ((uint16_t) 0x0) /*!< Index of the DMA handle used for Update DMA requests */ #define TIM_DMA_ID_CC1 ((uint16_t) 0x1) /*!< Index of the DMA handle used for Capture/Compare 1 DMA requests */ #define TIM_DMA_ID_CC2 ((uint16_t) 0x2) /*!< Index of the DMA handle used for Capture/Compare 2 DMA requests */ #define TIM_DMA_ID_CC3 ((uint16_t) 0x3) /*!< Index of the DMA handle used for Capture/Compare 3 DMA requests */ #define TIM_DMA_ID_CC4 ((uint16_t) 0x4) /*!< Index of the DMA handle used for Capture/Compare 4 DMA requests */ #define TIM_DMA_ID_TRIGGER ((uint16_t) 0x6) /*!< Index of the DMA handle used for Trigger DMA requests */ /** * @} */ /** @defgroup Channel_CC_State Channel_CC_State * @{ */ #define TIM_CCx_ENABLE ((uint32_t)0x0001) #define TIM_CCx_DISABLE ((uint32_t)0x0000) /** * @} */ /** * @} */ /* Private Constants -----------------------------------------------------------*/ /** @defgroup TIM_Private_Constants TIM_Private_Constants * @{ */ /* The counter of a timer instance is disabled only if all the CCx channels have been disabled */ #define CCER_CCxE_MASK ((uint32_t)(TIM_CCER_CC1E | TIM_CCER_CC2E | TIM_CCER_CC3E | TIM_CCER_CC4E)) /** * @} */ /* Exported macros -----------------------------------------------------------*/ /** @defgroup TIM_Exported_Macros TIM Exported Macros * @{ */ /** @brief Reset TIM handle state * @param __HANDLE__: TIM handle. * @retval None */ #define __HAL_TIM_RESET_HANDLE_STATE(__HANDLE__) ((__HANDLE__)->State = HAL_TIM_STATE_RESET) /** * @brief Enable the TIM peripheral. * @param __HANDLE__: TIM handle * @retval None */ #define __HAL_TIM_ENABLE(__HANDLE__) ((__HANDLE__)->Instance->CR1|=(TIM_CR1_CEN)) /** * @brief Disable the TIM peripheral. * @param __HANDLE__: TIM handle * @retval None */ #define __HAL_TIM_DISABLE(__HANDLE__) \ do { \ if (((__HANDLE__)->Instance->CCER & CCER_CCxE_MASK) == 0) \ { \ (__HANDLE__)->Instance->CR1 &= ~(TIM_CR1_CEN); \ } \ } while(0) /** * @brief Enable the specified TIM interrupt. * @param __HANDLE__: TIM handle * @param __INTERRUPT__: specifies the TIM interrupt sources to be enabled or disabled. * @retval None */ #define __HAL_TIM_ENABLE_IT(__HANDLE__, __INTERRUPT__) ((__HANDLE__)->Instance->DIER |= (__INTERRUPT__)) /** * @brief Enable the specified DMA Channel. * @param __HANDLE__: TIM handle * @param __DMA__: specifies the DMA Channel to be enabled or disabled. * @retval None */ #define __HAL_TIM_ENABLE_DMA(__HANDLE__, __DMA__) ((__HANDLE__)->Instance->DIER |= (__DMA__)) /** * @brief Disable the specified TIM interrupt. * @param __HANDLE__: TIM handle * @param __INTERRUPT__: specifies the TIM interrupt sources to be enabled or disabled. * @retval None */ #define __HAL_TIM_DISABLE_IT(__HANDLE__, __INTERRUPT__) ((__HANDLE__)->Instance->DIER &= ~(__INTERRUPT__)) /** * @brief Disable the specified DMA Channel. * @param __HANDLE__: TIM handle * @param __DMA__: specifies the DMA Channel to be enabled or disabled. * @retval None */ #define __HAL_TIM_DISABLE_DMA(__HANDLE__, __DMA__) ((__HANDLE__)->Instance->DIER &= ~(__DMA__)) /** * @brief Get the TIM Channel pending flags. * @param __HANDLE__: TIM handle * @param __FLAG__: Get the specified flag. * @retval The state of FLAG (SET or RESET). */ #define __HAL_TIM_GET_FLAG(__HANDLE__, __FLAG__) (((__HANDLE__)->Instance->SR &(__FLAG__)) == (__FLAG__)) /** * @brief Clear the TIM Channel pending flags. * @param __HANDLE__: TIM handle * @param __FLAG__: specifies the flag to clear. * @retval None */ #define __HAL_TIM_CLEAR_FLAG(__HANDLE__, __FLAG__) ((__HANDLE__)->Instance->SR = ~(__FLAG__)) /** * @brief Checks whether the specified TIM interrupt has occurred or not. * @param __HANDLE__: TIM handle * @param __INTERRUPT__: specifies the TIM interrupt source to check. * @retval The state of TIM_IT (SET or RESET). */ #define __HAL_TIM_GET_ITSTATUS(__HANDLE__, __INTERRUPT__) ((((__HANDLE__)->Instance->DIER & (__INTERRUPT__)) == (__INTERRUPT__)) ? SET : RESET) /** @brief Clear the TIM interrupt pending bits * @param __HANDLE__: TIM handle * @param __INTERRUPT__: specifies the interrupt pending bit to clear. * @retval None */ #define __HAL_TIM_CLEAR_IT(__HANDLE__, __INTERRUPT__) ((__HANDLE__)->Instance->SR = ~(__INTERRUPT__)) /** @brief TIM counter direction * @param __HANDLE__: TIM handle */ #define __HAL_TIM_DIRECTION_STATUS(__HANDLE__) (((__HANDLE__)->Instance->CR1 & (TIM_CR1_DIR)) == (TIM_CR1_DIR)) /** @brief Set TIM prescaler * @param __HANDLE__: TIM handle * @param __PRESC__: specifies the prescaler value. * @retval None */ #define __HAL_TIM_PRESCALER(__HANDLE__, __PRESC__) ((__HANDLE__)->Instance->PSC = (__PRESC__)) /** @brief Set TIM IC prescaler * @param __HANDLE__: TIM handle * @param __CHANNEL__: specifies TIM Channel * @param __ICPSC__: specifies the prescaler value. * @retval None */ #define __HAL_TIM_SetICPrescalerValue(__HANDLE__, __CHANNEL__, __ICPSC__) \ (((__CHANNEL__) == TIM_CHANNEL_1) ? ((__HANDLE__)->Instance->CCMR1 |= (__ICPSC__)) :\ ((__CHANNEL__) == TIM_CHANNEL_2) ? ((__HANDLE__)->Instance->CCMR1 |= ((__ICPSC__) << 8)) :\ ((__CHANNEL__) == TIM_CHANNEL_3) ? ((__HANDLE__)->Instance->CCMR2 |= (__ICPSC__)) :\ ((__HANDLE__)->Instance->CCMR2 |= ((__ICPSC__) << 8))) /** @brief Reset TIM IC prescaler * @param __HANDLE__: TIM handle * @param __CHANNEL__: specifies TIM Channel * @retval None */ #define __HAL_TIM_ResetICPrescalerValue(__HANDLE__, __CHANNEL__) \ (((__CHANNEL__) == TIM_CHANNEL_1) ? ((__HANDLE__)->Instance->CCMR1 &= (uint16_t)~TIM_CCMR1_IC1PSC) :\ ((__CHANNEL__) == TIM_CHANNEL_2) ? ((__HANDLE__)->Instance->CCMR1 &= (uint16_t)~TIM_CCMR1_IC2PSC) :\ ((__CHANNEL__) == TIM_CHANNEL_3) ? ((__HANDLE__)->Instance->CCMR2 &= (uint16_t)~TIM_CCMR2_IC3PSC) :\ ((__HANDLE__)->Instance->CCMR2 &= (uint16_t)~TIM_CCMR2_IC4PSC)) /** * @brief Sets the TIM Capture Compare Register value on runtime without * calling another time ConfigChannel function. * @param __HANDLE__: TIM handle. * @param __CHANNEL__ : TIM Channels to be configured. * This parameter can be one of the following values: * @arg TIM_CHANNEL_1: TIM Channel 1 selected * @arg TIM_CHANNEL_2: TIM Channel 2 selected * @arg TIM_CHANNEL_3: TIM Channel 3 selected * @arg TIM_CHANNEL_4: TIM Channel 4 selected * @param __COMPARE__: specifies the Capture Compare register new value. * @retval None */ #define __HAL_TIM_SetCompare(__HANDLE__, __CHANNEL__, __COMPARE__) \ (*(__IO uint32_t *)(&((__HANDLE__)->Instance->CCR1) + ((__CHANNEL__) >> 2)) = (__COMPARE__)) /** * @brief Gets the TIM Capture Compare Register value on runtime * @param __HANDLE__: TIM handle. * @param __CHANNEL__ : TIM Channel associated with the capture compare register * This parameter can be one of the following values: * @arg TIM_CHANNEL_1: get capture/compare 1 register value * @arg TIM_CHANNEL_2: get capture/compare 2 register value * @arg TIM_CHANNEL_3: get capture/compare 3 register value * @arg TIM_CHANNEL_4: get capture/compare 4 register value * @retval None */ #define __HAL_TIM_GetCompare(__HANDLE__, __CHANNEL__) \ (*(__IO uint32_t *)(&((__HANDLE__)->Instance->CCR1) + ((__CHANNEL__) >> 2))) /** * @brief Sets the TIM Counter Register value on runtime. * @param __HANDLE__: TIM handle. * @param __COUNTER__: specifies the Counter register new value. * @retval None */ #define __HAL_TIM_SetCounter(__HANDLE__, __COUNTER__) ((__HANDLE__)->Instance->CNT = (__COUNTER__)) /** * @brief Gets the TIM Counter Register value on runtime. * @param __HANDLE__: TIM handle. * @retval None */ #define __HAL_TIM_GetCounter(__HANDLE__) \ ((__HANDLE__)->Instance->CNT) /** * @brief Sets the TIM Autoreload Register value on runtime without calling * another time any Init function. * @param __HANDLE__: TIM handle. * @param __AUTORELOAD__: specifies the Counter register new value. * @retval None */ #define __HAL_TIM_SetAutoreload(__HANDLE__, __AUTORELOAD__) \ do{ \ (__HANDLE__)->Instance->ARR = (__AUTORELOAD__); \ (__HANDLE__)->Init.Period = (__AUTORELOAD__); \ } while(0) /** * @brief Gets the TIM Autoreload Register value on runtime * @param __HANDLE__: TIM handle. * @retval None */ #define __HAL_TIM_GetAutoreload(__HANDLE__) \ ((__HANDLE__)->Instance->ARR) /** * @brief Sets the TIM Clock Division value on runtime without calling * another time any Init function. * @param __HANDLE__: TIM handle. * @param __CKD__: specifies the clock division value. * This parameter can be one of the following value: * @arg TIM_CLOCKDIVISION_DIV1 * @arg TIM_CLOCKDIVISION_DIV2 * @arg TIM_CLOCKDIVISION_DIV4 * @retval None */ #define __HAL_TIM_SetClockDivision(__HANDLE__, __CKD__) \ do{ \ (__HANDLE__)->Instance->CR1 &= (uint16_t)(~TIM_CR1_CKD); \ (__HANDLE__)->Instance->CR1 |= (__CKD__); \ (__HANDLE__)->Init.ClockDivision = (__CKD__); \ } while(0) /** * @brief Gets the TIM Clock Division value on runtime * @param __HANDLE__: TIM handle. * @retval None */ #define __HAL_TIM_GetClockDivision(__HANDLE__) \ ((__HANDLE__)->Instance->CR1 & TIM_CR1_CKD) /** * @brief Sets the TIM Input Capture prescaler on runtime without calling * another time HAL_TIM_IC_ConfigChannel() function. * @param __HANDLE__: TIM handle. * @param __CHANNEL__ : TIM Channels to be configured. * This parameter can be one of the following values: * @arg TIM_CHANNEL_1: TIM Channel 1 selected * @arg TIM_CHANNEL_2: TIM Channel 2 selected * @arg TIM_CHANNEL_3: TIM Channel 3 selected * @arg TIM_CHANNEL_4: TIM Channel 4 selected * @param __ICPSC__: specifies the Input Capture4 prescaler new value. * This parameter can be one of the following values: * @arg TIM_ICPSC_DIV1: no prescaler * @arg TIM_ICPSC_DIV2: capture is done once every 2 events * @arg TIM_ICPSC_DIV4: capture is done once every 4 events * @arg TIM_ICPSC_DIV8: capture is done once every 8 events * @retval None */ #define __HAL_TIM_SetICPrescaler(__HANDLE__, __CHANNEL__, __ICPSC__) \ do{ \ __HAL_TIM_ResetICPrescalerValue((__HANDLE__), (__CHANNEL__)); \ __HAL_TIM_SetICPrescalerValue((__HANDLE__), (__CHANNEL__), (__ICPSC__)); \ } while(0) /** * @brief Gets the TIM Input Capture prescaler on runtime * @param __HANDLE__: TIM handle. * @param __CHANNEL__ : TIM Channels to be configured. * This parameter can be one of the following values: * @arg TIM_CHANNEL_1: get input capture 1 prescaler value * @arg TIM_CHANNEL_2: get input capture 2 prescaler value * @arg TIM_CHANNEL_3: get input capture 3 prescaler value * @arg TIM_CHANNEL_4: get input capture 4 prescaler value * @retval None */ #define __HAL_TIM_GetICPrescaler(__HANDLE__, __CHANNEL__) \ (((__CHANNEL__) == TIM_CHANNEL_1) ? ((__HANDLE__)->Instance->CCMR1 & TIM_CCMR1_IC1PSC) :\ ((__CHANNEL__) == TIM_CHANNEL_2) ? (((__HANDLE__)->Instance->CCMR1 & TIM_CCMR1_IC2PSC) >> 8) :\ ((__CHANNEL__) == TIM_CHANNEL_3) ? ((__HANDLE__)->Instance->CCMR2 & TIM_CCMR2_IC3PSC) :\ (((__HANDLE__)->Instance->CCMR2 & TIM_CCMR2_IC4PSC)) >> 8) /** * @} */ /* Include TIM HAL Extension module */ #include "stm32l1xx_hal_tim_ex.h" /* Exported functions --------------------------------------------------------*/ /** @addtogroup TIM_Exported_Functions * @{ */ /** @addtogroup TIM_Exported_Functions_Group1 * @{ */ /* Time Base functions ********************************************************/ HAL_StatusTypeDef HAL_TIM_Base_Init(TIM_HandleTypeDef *htim); HAL_StatusTypeDef HAL_TIM_Base_DeInit(TIM_HandleTypeDef *htim); void HAL_TIM_Base_MspInit(TIM_HandleTypeDef *htim); void HAL_TIM_Base_MspDeInit(TIM_HandleTypeDef *htim); /* Blocking mode: Polling */ HAL_StatusTypeDef HAL_TIM_Base_Start(TIM_HandleTypeDef *htim); HAL_StatusTypeDef HAL_TIM_Base_Stop(TIM_HandleTypeDef *htim); /* Non-Blocking mode: Interrupt */ HAL_StatusTypeDef HAL_TIM_Base_Start_IT(TIM_HandleTypeDef *htim); HAL_StatusTypeDef HAL_TIM_Base_Stop_IT(TIM_HandleTypeDef *htim); /* Non-Blocking mode: DMA */ HAL_StatusTypeDef HAL_TIM_Base_Start_DMA(TIM_HandleTypeDef *htim, uint32_t *pData, uint16_t Length); HAL_StatusTypeDef HAL_TIM_Base_Stop_DMA(TIM_HandleTypeDef *htim); /** * @} */ /** @addtogroup TIM_Exported_Functions_Group2 * @{ */ /* Timer Output Compare functions **********************************************/ HAL_StatusTypeDef HAL_TIM_OC_Init(TIM_HandleTypeDef *htim); HAL_StatusTypeDef HAL_TIM_OC_DeInit(TIM_HandleTypeDef *htim); void HAL_TIM_OC_MspInit(TIM_HandleTypeDef *htim); void HAL_TIM_OC_MspDeInit(TIM_HandleTypeDef *htim); /* Blocking mode: Polling */ HAL_StatusTypeDef HAL_TIM_OC_Start(TIM_HandleTypeDef *htim, uint32_t Channel); HAL_StatusTypeDef HAL_TIM_OC_Stop(TIM_HandleTypeDef *htim, uint32_t Channel); /* Non-Blocking mode: Interrupt */ HAL_StatusTypeDef HAL_TIM_OC_Start_IT(TIM_HandleTypeDef *htim, uint32_t Channel); HAL_StatusTypeDef HAL_TIM_OC_Stop_IT(TIM_HandleTypeDef *htim, uint32_t Channel); /* Non-Blocking mode: DMA */ HAL_StatusTypeDef HAL_TIM_OC_Start_DMA(TIM_HandleTypeDef *htim, uint32_t Channel, uint32_t *pData, uint16_t Length); HAL_StatusTypeDef HAL_TIM_OC_Stop_DMA(TIM_HandleTypeDef *htim, uint32_t Channel); /** * @} */ /** @addtogroup TIM_Exported_Functions_Group3 * @{ */ /* Timer PWM functions *********************************************************/ HAL_StatusTypeDef HAL_TIM_PWM_Init(TIM_HandleTypeDef *htim); HAL_StatusTypeDef HAL_TIM_PWM_DeInit(TIM_HandleTypeDef *htim); void HAL_TIM_PWM_MspInit(TIM_HandleTypeDef *htim); void HAL_TIM_PWM_MspDeInit(TIM_HandleTypeDef *htim); /* Blocking mode: Polling */ HAL_StatusTypeDef HAL_TIM_PWM_Start(TIM_HandleTypeDef *htim, uint32_t Channel); HAL_StatusTypeDef HAL_TIM_PWM_Stop(TIM_HandleTypeDef *htim, uint32_t Channel); /* Non-Blocking mode: Interrupt */ HAL_StatusTypeDef HAL_TIM_PWM_Start_IT(TIM_HandleTypeDef *htim, uint32_t Channel); HAL_StatusTypeDef HAL_TIM_PWM_Stop_IT(TIM_HandleTypeDef *htim, uint32_t Channel); /* Non-Blocking mode: DMA */ HAL_StatusTypeDef HAL_TIM_PWM_Start_DMA(TIM_HandleTypeDef *htim, uint32_t Channel, uint32_t *pData, uint16_t Length); HAL_StatusTypeDef HAL_TIM_PWM_Stop_DMA(TIM_HandleTypeDef *htim, uint32_t Channel); /** * @} */ /** @addtogroup TIM_Exported_Functions_Group4 * @{ */ /* Timer Input Capture functions ***********************************************/ HAL_StatusTypeDef HAL_TIM_IC_Init(TIM_HandleTypeDef *htim); HAL_StatusTypeDef HAL_TIM_IC_DeInit(TIM_HandleTypeDef *htim); void HAL_TIM_IC_MspInit(TIM_HandleTypeDef *htim); void HAL_TIM_IC_MspDeInit(TIM_HandleTypeDef *htim); /* Blocking mode: Polling */ HAL_StatusTypeDef HAL_TIM_IC_Start(TIM_HandleTypeDef *htim, uint32_t Channel); HAL_StatusTypeDef HAL_TIM_IC_Stop(TIM_HandleTypeDef *htim, uint32_t Channel); /* Non-Blocking mode: Interrupt */ HAL_StatusTypeDef HAL_TIM_IC_Start_IT(TIM_HandleTypeDef *htim, uint32_t Channel); HAL_StatusTypeDef HAL_TIM_IC_Stop_IT(TIM_HandleTypeDef *htim, uint32_t Channel); /* Non-Blocking mode: DMA */ HAL_StatusTypeDef HAL_TIM_IC_Start_DMA(TIM_HandleTypeDef *htim, uint32_t Channel, uint32_t *pData, uint16_t Length); HAL_StatusTypeDef HAL_TIM_IC_Stop_DMA(TIM_HandleTypeDef *htim, uint32_t Channel); /** * @} */ /** @addtogroup TIM_Exported_Functions_Group5 * @{ */ /* Timer One Pulse functions ***************************************************/ HAL_StatusTypeDef HAL_TIM_OnePulse_Init(TIM_HandleTypeDef *htim, uint32_t OnePulseMode); HAL_StatusTypeDef HAL_TIM_OnePulse_DeInit(TIM_HandleTypeDef *htim); void HAL_TIM_OnePulse_MspInit(TIM_HandleTypeDef *htim); void HAL_TIM_OnePulse_MspDeInit(TIM_HandleTypeDef *htim); /* Blocking mode: Polling */ HAL_StatusTypeDef HAL_TIM_OnePulse_Start(TIM_HandleTypeDef *htim, uint32_t OutputChannel); HAL_StatusTypeDef HAL_TIM_OnePulse_Stop(TIM_HandleTypeDef *htim, uint32_t OutputChannel); /* Non-Blocking mode: Interrupt */ HAL_StatusTypeDef HAL_TIM_OnePulse_Start_IT(TIM_HandleTypeDef *htim, uint32_t OutputChannel); HAL_StatusTypeDef HAL_TIM_OnePulse_Stop_IT(TIM_HandleTypeDef *htim, uint32_t OutputChannel); /** * @} */ /** @addtogroup TIM_Exported_Functions_Group6 * @{ */ /* Timer Encoder functions *****************************************************/ HAL_StatusTypeDef HAL_TIM_Encoder_Init(TIM_HandleTypeDef *htim, TIM_Encoder_InitTypeDef* sConfig); HAL_StatusTypeDef HAL_TIM_Encoder_DeInit(TIM_HandleTypeDef *htim); void HAL_TIM_Encoder_MspInit(TIM_HandleTypeDef *htim); void HAL_TIM_Encoder_MspDeInit(TIM_HandleTypeDef *htim); /* Blocking mode: Polling */ HAL_StatusTypeDef HAL_TIM_Encoder_Start(TIM_HandleTypeDef *htim, uint32_t Channel); HAL_StatusTypeDef HAL_TIM_Encoder_Stop(TIM_HandleTypeDef *htim, uint32_t Channel); /* Non-Blocking mode: Interrupt */ HAL_StatusTypeDef HAL_TIM_Encoder_Start_IT(TIM_HandleTypeDef *htim, uint32_t Channel); HAL_StatusTypeDef HAL_TIM_Encoder_Stop_IT(TIM_HandleTypeDef *htim, uint32_t Channel); /* Non-Blocking mode: DMA */ HAL_StatusTypeDef HAL_TIM_Encoder_Start_DMA(TIM_HandleTypeDef *htim, uint32_t Channel, uint32_t *pData1, uint32_t *pData2, uint16_t Length); HAL_StatusTypeDef HAL_TIM_Encoder_Stop_DMA(TIM_HandleTypeDef *htim, uint32_t Channel); /** * @} */ /** @addtogroup TIM_Exported_Functions_Group7 * @{ */ /* Interrupt Handler functions **********************************************/ void HAL_TIM_IRQHandler(TIM_HandleTypeDef *htim); /** * @} */ /** @addtogroup TIM_Exported_Functions_Group8 * @{ */ /* Control functions *********************************************************/ HAL_StatusTypeDef HAL_TIM_OC_ConfigChannel(TIM_HandleTypeDef *htim, TIM_OC_InitTypeDef* sConfig, uint32_t Channel); HAL_StatusTypeDef HAL_TIM_PWM_ConfigChannel(TIM_HandleTypeDef *htim, TIM_OC_InitTypeDef* sConfig, uint32_t Channel); HAL_StatusTypeDef HAL_TIM_IC_ConfigChannel(TIM_HandleTypeDef *htim, TIM_IC_InitTypeDef* sConfig, uint32_t Channel); HAL_StatusTypeDef HAL_TIM_OnePulse_ConfigChannel(TIM_HandleTypeDef *htim, TIM_OnePulse_InitTypeDef* sConfig, uint32_t OutputChannel, uint32_t InputChannel); HAL_StatusTypeDef HAL_TIM_ConfigOCrefClear(TIM_HandleTypeDef *htim, TIM_ClearInputConfigTypeDef * sClearInputConfig, uint32_t Channel); HAL_StatusTypeDef HAL_TIM_ConfigClockSource(TIM_HandleTypeDef *htim, TIM_ClockConfigTypeDef * sClockSourceConfig); HAL_StatusTypeDef HAL_TIM_ConfigTI1Input(TIM_HandleTypeDef *htim, uint32_t TI1_Selection); HAL_StatusTypeDef HAL_TIM_SlaveConfigSynchronization(TIM_HandleTypeDef *htim, TIM_SlaveConfigTypeDef * sSlaveConfig); HAL_StatusTypeDef HAL_TIM_DMABurst_WriteStart(TIM_HandleTypeDef *htim, uint32_t BurstBaseAddress, uint32_t BurstRequestSrc, \ uint32_t *BurstBuffer, uint32_t BurstLength); HAL_StatusTypeDef HAL_TIM_DMABurst_WriteStop(TIM_HandleTypeDef *htim, uint32_t BurstRequestSrc); HAL_StatusTypeDef HAL_TIM_DMABurst_ReadStart(TIM_HandleTypeDef *htim, uint32_t BurstBaseAddress, uint32_t BurstRequestSrc, \ uint32_t *BurstBuffer, uint32_t BurstLength); HAL_StatusTypeDef HAL_TIM_DMABurst_ReadStop(TIM_HandleTypeDef *htim, uint32_t BurstRequestSrc); HAL_StatusTypeDef HAL_TIM_GenerateEvent(TIM_HandleTypeDef *htim, uint32_t EventSource); uint32_t HAL_TIM_ReadCapturedValue(TIM_HandleTypeDef *htim, uint32_t Channel); /** * @} */ /** @addtogroup TIM_Exported_Functions_Group9 * @{ */ /* Callback in non blocking modes (Interrupt and DMA) *************************/ void HAL_TIM_PeriodElapsedCallback(TIM_HandleTypeDef *htim); void HAL_TIM_OC_DelayElapsedCallback(TIM_HandleTypeDef *htim); void HAL_TIM_IC_CaptureCallback(TIM_HandleTypeDef *htim); void HAL_TIM_PWM_PulseFinishedCallback(TIM_HandleTypeDef *htim); void HAL_TIM_TriggerCallback(TIM_HandleTypeDef *htim); void HAL_TIM_ErrorCallback(TIM_HandleTypeDef *htim); /** * @} */ /** @addtogroup TIM_Exported_Functions_Group10 * @{ */ /* Peripheral State functions **************************************************/ HAL_TIM_StateTypeDef HAL_TIM_Base_GetState(TIM_HandleTypeDef *htim); HAL_TIM_StateTypeDef HAL_TIM_OC_GetState(TIM_HandleTypeDef *htim); HAL_TIM_StateTypeDef HAL_TIM_PWM_GetState(TIM_HandleTypeDef *htim); HAL_TIM_StateTypeDef HAL_TIM_IC_GetState(TIM_HandleTypeDef *htim); HAL_TIM_StateTypeDef HAL_TIM_OnePulse_GetState(TIM_HandleTypeDef *htim); HAL_TIM_StateTypeDef HAL_TIM_Encoder_GetState(TIM_HandleTypeDef *htim); /** * @} */ /** * @} */ /** * @} */ /** * @} */ #ifdef __cplusplus } #endif #endif /* __STM32L1xx_HAL_TIM_H */ /************************ (C) COPYRIGHT STMicroelectronics *****END OF FILE****/ ================================================ FILE: Zelig/mbed/TARGET_NUCLEO_L152RE/stm32l1xx_hal_tim_ex.h ================================================ /** ****************************************************************************** * @file stm32l1xx_hal_tim_ex.h * @author MCD Application Team * @version V1.0.0 * @date 5-September-2014 * @brief Header file of TIM HAL Extension module. ****************************************************************************** * @attention * *

© COPYRIGHT(c) 2014 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. * ****************************************************************************** */ /* Define to prevent recursive inclusion -------------------------------------*/ #ifndef __STM32L1xx_HAL_TIM_EX_H #define __STM32L1xx_HAL_TIM_EX_H #ifdef __cplusplus extern "C" { #endif /* Includes ------------------------------------------------------------------*/ #include "stm32l1xx_hal_def.h" /** @addtogroup STM32L1xx_HAL_Driver * @{ */ /** @addtogroup TIMEx * @{ */ /* Exported types ------------------------------------------------------------*/ /** @defgroup TIMEx_Exported_Types TIMEx Exported Types * @{ */ /** * @brief TIM Master configuration Structure definition */ typedef struct { uint32_t MasterOutputTrigger; /*!< Trigger output (TRGO) selection This parameter can be a value of @ref TIM_Master_Mode_Selection */ uint32_t MasterSlaveMode; /*!< Master/slave mode selection This parameter can be a value of @ref TIM_Master_Slave_Mode */ }TIM_MasterConfigTypeDef; /** * @} */ /* Exported constants --------------------------------------------------------*/ /** @defgroup TIMEx_Exported_Constants TIMEx_Exported_Constants * @{ */ /** @defgroup TIMEx_Remap TIMEx_Remap * @{ */ #if defined (STM32L100xC) || defined (STM32L151xC) || defined (STM32L152xC) || defined (STM32L162xC) || defined (STM32L151xCA) || defined (STM32L151xD) || defined (STM32L152xCA) || defined (STM32L152xD) || defined (STM32L162xCA) || defined (STM32L162xD) || defined (STM32L151xE) || defined (STM32L152xE) || defined (STM32L162xE) #define TIM_TIM2_ITR1_TIM10_OC (0x00000000) /* !< TIM2 ITR1 input is connected to TIM10 OC */ #define TIM_TIM2_ITR1_TIM5_TGO TIM2_OR_ITR1_RMP /* !< TIM2 ITR1 input is connected to TIM5 TGO */ #endif /* defined (STM32L100xC) || defined (STM32L151xC) || defined (STM32L152xC) || defined (STM32L162xC) || defined (STM32L151xCA) || defined (STM32L151xD) || defined (STM32L152xCA) || defined (STM32L152xD) || defined (STM32L162xCA) || defined (STM32L162xD) || defined (STM32L151xE) || defined (STM32L152xE) || defined (STM32L162xE) */ #if defined (STM32L100xC) || defined (STM32L151xC) || defined (STM32L152xC) || defined (STM32L162xC) || defined (STM32L151xCA) || defined (STM32L151xD) || defined (STM32L152xCA) || defined (STM32L152xD) || defined (STM32L162xCA) || defined (STM32L162xD) || defined (STM32L151xE) || defined (STM32L152xE) || defined (STM32L162xE) #define TIM_TIM3_ITR2_TIM11_OC (0x00000000) /* !< TIM3 ITR2 input is connected to TIM11 OC */ #define TIM_TIM3_ITR2_TIM5_TGO TIM2_OR_ITR1_RMP /* !< TIM3 ITR2 input is connected to TIM5 TGO */ #endif /* defined (STM32L100xC) || defined (STM32L151xC) || defined (STM32L152xC) || defined (STM32L162xC) || defined (STM32L151xCA) || defined (STM32L151xD) || defined (STM32L152xCA) || defined (STM32L152xD) || defined (STM32L162xCA) || defined (STM32L162xD) || defined (STM32L151xE) || defined (STM32L152xE) || defined (STM32L162xE) */ #if defined (STM32L100xC) || defined (STM32L151xC) || defined (STM32L152xC) || defined (STM32L162xC) || defined (STM32L151xCA) || defined (STM32L151xD) || defined (STM32L152xCA) || defined (STM32L152xD) || defined (STM32L162xCA) || defined (STM32L162xD) || defined (STM32L151xE) || defined (STM32L152xE) || defined (STM32L162xE) #define TIM_TIM9_ITR1_TIM3_TGO (0x00000000) /* !< TIM9 ITR1 input is connected to TIM3 TGO */ #define TIM_TIM9_ITR1_TS TIM9_OR_ITR1_RMP /* !< TIM9 ITR1 input is connected to touch sensing I/O */ #endif /* defined (STM32L100xC) || defined (STM32L151xC) || defined (STM32L152xC) || defined (STM32L162xC) || defined (STM32L151xCA) || defined (STM32L151xD) || defined (STM32L152xCA) || defined (STM32L152xD) || defined (STM32L162xCA) || defined (STM32L162xD) || defined (STM32L151xE) || defined (STM32L152xE) || defined (STM32L162xE) */ #define TIM_TIM9_GPIO (0x00000000) /* !< TIM9 Channel1 is connected to GPIO */ #define TIM_TIM9_LSE TIM_OR_TI1RMP_0 /* !< TIM9 Channel1 is connected to LSE internal clock */ #define TIM_TIM9_GPIO1 TIM_OR_TI1RMP_1 /* !< TIM9 Channel1 is connected to GPIO */ #define TIM_TIM9_GPIO2 TIM_OR_TI1RMP /* !< TIM9 Channel1 is connected to GPIO */ #if defined (STM32L100xC) || defined (STM32L151xC) || defined (STM32L152xC) || defined (STM32L162xC) || defined (STM32L151xCA) || defined (STM32L151xD) || defined (STM32L152xCA) || defined (STM32L152xD) || defined (STM32L162xCA) || defined (STM32L162xD) || defined (STM32L151xE) || defined (STM32L152xE) || defined (STM32L162xE) #define TIM_TIM10_TI1RMP (0x00000000) /* !< TIM10 Channel 1 depends on TI1_RMP */ #define TIM_TIM10_RI TIM_OR_TI1_RMP_RI /* !< TIM10 Channel 1 is connected to RI */ #define TIM_TIM10_ETR_LSE (0x00000000) /* !< TIM10 ETR input is connected to LSE clock */ #define TIM_TIM10_ETR_TIM9_TGO TIM_OR_ETR_RMP /* !< TIM10 ETR input is connected to TIM9 TGO */ #endif /* defined (STM32L100xC) || defined (STM32L151xC) || defined (STM32L152xC) || defined (STM32L162xC) || defined (STM32L151xCA) || defined (STM32L151xD) || defined (STM32L152xCA) || defined (STM32L152xD) || defined (STM32L162xCA) || defined (STM32L162xD) || defined (STM32L151xE) || defined (STM32L152xE) || defined (STM32L162xE) */ #define TIM_TIM10_GPIO (0x00000000) /* !< TIM10 Channel1 is connected to GPIO */ #define TIM_TIM10_LSI TIM_OR_TI1RMP_0 /* !< TIM10 Channel1 is connected to LSI internal clock */ #define TIM_TIM10_LSE TIM_OR_TI1RMP_1 /* !< TIM10 Channel1 is connected to LSE internal clock */ #define TIM_TIM10_RTC TIM_OR_TI1RMP /* !< TIM10 Channel1 is connected to RTC wakeup interrupt */ #if defined (STM32L100xC) || defined (STM32L151xC) || defined (STM32L152xC) || defined (STM32L162xC) || defined (STM32L151xCA) || defined (STM32L151xD) || defined (STM32L152xCA) || defined (STM32L152xD) || defined (STM32L162xCA) || defined (STM32L162xD) || defined (STM32L151xE) || defined (STM32L152xE) || defined (STM32L162xE) #define TIM_TIM11_TI1RMP (0x00000000) /* !< TIM11 Channel 1 depends on TI1_RMP */ #define TIM_TIM11_RI TIM_OR_TI1_RMP_RI /* !< TIM11 Channel 1 is connected to RI */ #define TIM_TIM11_ETR_LSE (0x00000000) /* !< TIM11 ETR input is connected to LSE clock */ #define TIM_TIM11_ETR_TIM9_TGO TIM_OR_ETR_RMP /* !< TIM11 ETR input is connected to TIM9 TGO */ #endif /* defined (STM32L100xC) || defined (STM32L151xC) || defined (STM32L152xC) || defined (STM32L162xC) || defined (STM32L151xCA) || defined (STM32L151xD) || defined (STM32L152xCA) || defined (STM32L152xD) || defined (STM32L162xCA) || defined (STM32L162xD) || defined (STM32L151xE) || defined (STM32L152xE) || defined (STM32L162xE) */ #define TIM_TIM11_GPIO (0x00000000) /* !< TIM11 Channel1 is connected to GPIO */ #define TIM_TIM11_MSI TIM_OR_TI1RMP_0 /* !< TIM11 Channel1 is connected to MSI internal clock */ #define TIM_TIM11_HSE_RTC TIM_OR_TI1RMP_1 /* !< TIM11 Channel1 is connected to HSE_RTC clock */ #define TIM_TIM11_GPIO1 TIM_OR_TI1RMP /* !< TIM11 Channel1 is connected to GPIO */ #if defined (STM32L100xC) || defined (STM32L151xC) || defined (STM32L152xC) || defined (STM32L162xC) || defined (STM32L151xCA) || defined (STM32L151xD) || defined (STM32L152xCA) || defined (STM32L152xD) || defined (STM32L162xCA) || defined (STM32L162xD) || defined (STM32L151xE) || defined (STM32L152xE) || defined (STM32L162xE) #define IS_TIM_REMAP(INSTANCE, TIM_REMAP) \ ( (((INSTANCE) == TIM2) && (((TIM_REMAP) == TIM_TIM2_ITR1_TIM10_OC) || ((TIM_REMAP) == TIM_TIM2_ITR1_TIM5_TGO))) || \ (((INSTANCE) == TIM3) && (((TIM_REMAP) == TIM_TIM3_ITR2_TIM11_OC) || ((TIM_REMAP) == TIM_TIM3_ITR2_TIM5_TGO))) || \ (((INSTANCE) == TIM9) && ((TIM_REMAP) <= (TIM_TIM9_ITR1_TS | TIM_TIM9_GPIO2))) || \ (((INSTANCE) == TIM10) && ((TIM_REMAP) <= (TIM_TIM10_RI | TIM_TIM10_ETR_TIM9_TGO | TIM_TIM10_RTC))) || \ (((INSTANCE) == TIM11) && ((TIM_REMAP) <= (TIM_TIM11_RI | TIM_TIM11_ETR_TIM9_TGO | TIM_TIM11_GPIO1))) \ ) #else /* defined (STM32L100xC) || defined (STM32L151xC) || defined (STM32L152xC) || defined (STM32L162xC) || defined (STM32L151xCA) || defined (STM32L151xD) || defined (STM32L152xCA) || defined (STM32L152xD) || defined (STM32L162xCA) || defined (STM32L162xD) || defined (STM32L151xE) || defined (STM32L152xE) || defined (STM32L162xE) */ #define IS_TIM_REMAP(INSTANCE, TIM_REMAP) \ ( (((INSTANCE) == TIM9) && (((TIM_REMAP) == TIM_TIM9_GPIO) || ((TIM_REMAP) == TIM_TIM9_LSE) || ((TIM_REMAP) == TIM_TIM9_GPIO1) || ((TIM_REMAP) == TIM_TIM9_GPIO2))) || \ (((INSTANCE) == TIM10) && (((TIM_REMAP) == TIM_TIM10_GPIO) || ((TIM_REMAP) == TIM_TIM10_LSI) || ((TIM_REMAP) == TIM_TIM10_LSE) || ((TIM_REMAP) == TIM_TIM10_RTC))) || \ (((INSTANCE) == TIM11) && (((TIM_REMAP) == TIM_TIM11_GPIO) || ((TIM_REMAP) == TIM_TIM11_MSI) || ((TIM_REMAP) == TIM_TIM11_HSE_RTC) || ((TIM_REMAP) == TIM_TIM11_GPIO1))) \ ) #endif /** * @} */ /** * @} */ /* Exported macro ------------------------------------------------------------*/ /* Exported functions --------------------------------------------------------*/ /** @addtogroup TIMEx_Exported_Functions * @{ */ /** @addtogroup TIMEx_Exported_Functions_Group1 * @{ */ /* Extension Control functions ************************************************/ HAL_StatusTypeDef HAL_TIMEx_MasterConfigSynchronization(TIM_HandleTypeDef *htim, TIM_MasterConfigTypeDef * sMasterConfig); HAL_StatusTypeDef HAL_TIMEx_RemapConfig(TIM_HandleTypeDef *htim, uint32_t Remap); /** * @} */ /** @addtogroup TIMEx_Exported_Functions_Group2 * @{ */ /** * @} */ /* Extension Callback *********************************************************/ /** @addtogroup TIMEx_Exported_Functions_Group3 * @{ */ /** * @} */ /* Extension Peripheral State functions **************************************/ /** * @} */ /** * @} */ /** * @} */ /** * @} */ #ifdef __cplusplus } #endif #endif /* __STM32L1xx_HAL_TIM_EX_H */ /************************ (C) COPYRIGHT STMicroelectronics *****END OF FILE****/ ================================================ FILE: Zelig/mbed/TARGET_NUCLEO_L152RE/stm32l1xx_hal_uart.h ================================================ /** ****************************************************************************** * @file stm32l1xx_hal_uart.h * @author MCD Application Team * @version V1.0.0 * @date 5-September-2014 * @brief This file contains all the functions prototypes for the UART * firmware library. ****************************************************************************** * @attention * *

© COPYRIGHT(c) 2014 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. * ****************************************************************************** */ /* Define to prevent recursive inclusion -------------------------------------*/ #ifndef __STM32L1xx_HAL_UART_H #define __STM32L1xx_HAL_UART_H #ifdef __cplusplus extern "C" { #endif /* Includes ------------------------------------------------------------------*/ #include "stm32l1xx_hal_def.h" /** @addtogroup STM32L1xx_HAL_Driver * @{ */ /** @addtogroup UART * @{ */ /* Exported types ------------------------------------------------------------*/ /** @defgroup UART_Exported_Types UART Exported Types * @{ */ /** * @brief UART Init Structure definition */ typedef struct { uint32_t BaudRate; /*!< This member configures the UART communication baud rate. The baud rate is computed using the following formula: - IntegerDivider = ((PCLKx) / (8 * (OVR8+1) * (huart->Init.BaudRate))) - FractionalDivider = ((IntegerDivider - ((uint32_t) IntegerDivider)) * 8 * (OVR8+1)) + 0.5 Where OVR8 is the "oversampling by 8 mode" configuration bit in the CR1 register. */ uint32_t WordLength; /*!< Specifies the number of data bits transmitted or received in a frame. This parameter can be a value of @ref UART_Word_Length */ uint32_t StopBits; /*!< Specifies the number of stop bits transmitted. This parameter can be a value of @ref UART_Stop_Bits */ uint32_t Parity; /*!< Specifies the parity mode. This parameter can be a value of @ref UART_Parity @note When parity is enabled, the computed parity is inserted at the MSB position of the transmitted data (9th bit when the word length is set to 9 data bits; 8th bit when the word length is set to 8 data bits). */ uint32_t Mode; /*!< Specifies wether the Receive or Transmit mode is enabled or disabled. This parameter can be a value of @ref UART_Mode */ uint32_t HwFlowCtl; /*!< Specifies wether the hardware flow control mode is enabled or disabled. This parameter can be a value of @ref UART_Hardware_Flow_Control */ uint32_t OverSampling; /*!< Specifies wether the Over sampling 8 is enabled or disabled, to achieve higher speed (up to fPCLK/8). This parameter can be a value of @ref UART_Over_Sampling */ }UART_InitTypeDef; /** * @brief HAL UART State structures definition */ typedef enum { HAL_UART_STATE_RESET = 0x00, /*!< Peripheral is not initialized */ HAL_UART_STATE_READY = 0x01, /*!< Peripheral Initialized and ready for use */ HAL_UART_STATE_BUSY = 0x02, /*!< an internal process is ongoing */ HAL_UART_STATE_BUSY_TX = 0x12, /*!< Data Transmission process is ongoing */ HAL_UART_STATE_BUSY_RX = 0x22, /*!< Data Reception process is ongoing */ HAL_UART_STATE_BUSY_TX_RX = 0x32, /*!< Data Transmission and Reception process is ongoing */ HAL_UART_STATE_TIMEOUT = 0x03, /*!< Timeout state */ HAL_UART_STATE_ERROR = 0x04 /*!< Error */ }HAL_UART_StateTypeDef; /** * @brief HAL UART Error Code structure definition */ typedef enum { HAL_UART_ERROR_NONE = 0x00, /*!< No error */ HAL_UART_ERROR_PE = 0x01, /*!< Parity error */ HAL_UART_ERROR_NE = 0x02, /*!< Noise error */ HAL_UART_ERROR_FE = 0x04, /*!< frame error */ HAL_UART_ERROR_ORE = 0x08, /*!< Overrun error */ HAL_UART_ERROR_DMA = 0x10 /*!< DMA transfer error */ }HAL_UART_ErrorTypeDef; /** * @brief UART handle Structure definition */ typedef struct { USART_TypeDef *Instance; /* UART registers base address */ UART_InitTypeDef Init; /* UART communication parameters */ uint8_t *pTxBuffPtr; /* Pointer to UART Tx transfer Buffer */ uint16_t TxXferSize; /* UART Tx Transfer size */ uint16_t TxXferCount; /* UART Tx Transfer Counter */ uint8_t *pRxBuffPtr; /* Pointer to UART Rx transfer Buffer */ uint16_t RxXferSize; /* UART Rx Transfer size */ uint16_t RxXferCount; /* UART Rx Transfer Counter */ DMA_HandleTypeDef *hdmatx; /* UART Tx DMA Handle parameters */ DMA_HandleTypeDef *hdmarx; /* UART Rx DMA Handle parameters */ HAL_LockTypeDef Lock; /* Locking object */ __IO HAL_UART_StateTypeDef State; /* UART communication state */ __IO HAL_UART_ErrorTypeDef ErrorCode; /* UART Error code */ }UART_HandleTypeDef; /** * @} */ /* Exported constants --------------------------------------------------------*/ /** @defgroup UART_Exported_Constants UART Exported constants * @{ */ /** @defgroup UART_Word_Length UART Word Length * @{ */ #define UART_WORDLENGTH_8B ((uint32_t)0x00000000) #define UART_WORDLENGTH_9B ((uint32_t)USART_CR1_M) #define IS_UART_WORD_LENGTH(LENGTH) (((LENGTH) == UART_WORDLENGTH_8B) || \ ((LENGTH) == UART_WORDLENGTH_9B)) /** * @} */ /** @defgroup UART_Stop_Bits UART Number of Stop Bits * @{ */ #define UART_STOPBITS_1 ((uint32_t)0x00000000) #define UART_STOPBITS_2 ((uint32_t)USART_CR2_STOP_1) #define IS_UART_STOPBITS(STOPBITS) (((STOPBITS) == UART_STOPBITS_1) || \ ((STOPBITS) == UART_STOPBITS_2)) /** * @} */ /** @defgroup UART_Parity UART Parity * @{ */ #define UART_PARITY_NONE ((uint32_t)0x00000000) #define UART_PARITY_EVEN ((uint32_t)USART_CR1_PCE) #define UART_PARITY_ODD ((uint32_t)(USART_CR1_PCE | USART_CR1_PS)) #define IS_UART_PARITY(PARITY) (((PARITY) == UART_PARITY_NONE) || \ ((PARITY) == UART_PARITY_EVEN) || \ ((PARITY) == UART_PARITY_ODD)) /** * @} */ /** @defgroup UART_Hardware_Flow_Control UART Hardware Flow Control * @{ */ #define UART_HWCONTROL_NONE ((uint32_t)0x00000000) #define UART_HWCONTROL_RTS ((uint32_t)USART_CR3_RTSE) #define UART_HWCONTROL_CTS ((uint32_t)USART_CR3_CTSE) #define UART_HWCONTROL_RTS_CTS ((uint32_t)(USART_CR3_RTSE | USART_CR3_CTSE)) #define IS_UART_HARDWARE_FLOW_CONTROL(CONTROL)\ (((CONTROL) == UART_HWCONTROL_NONE) || \ ((CONTROL) == UART_HWCONTROL_RTS) || \ ((CONTROL) == UART_HWCONTROL_CTS) || \ ((CONTROL) == UART_HWCONTROL_RTS_CTS)) /** * @} */ /** @defgroup UART_Mode UART Transfer Mode * @{ */ #define UART_MODE_RX ((uint32_t)USART_CR1_RE) #define UART_MODE_TX ((uint32_t)USART_CR1_TE) #define UART_MODE_TX_RX ((uint32_t)(USART_CR1_TE |USART_CR1_RE)) #define IS_UART_MODE(MODE) ((((MODE) & (uint32_t)0x0000FFF3) == 0x00) && ((MODE) != (uint32_t)0x00000000)) /** * @} */ /** @defgroup UART_State UART State * @{ */ #define UART_STATE_DISABLE ((uint32_t)0x00000000) #define UART_STATE_ENABLE ((uint32_t)USART_CR1_UE) #define IS_UART_STATE(STATE) (((STATE) == UART_STATE_DISABLE) || \ ((STATE) == UART_STATE_ENABLE)) /** * @} */ /** @defgroup UART_Over_Sampling UART Over Sampling * @{ */ #define UART_OVERSAMPLING_16 ((uint32_t)0x00000000) #define UART_OVERSAMPLING_8 ((uint32_t)USART_CR1_OVER8) #define IS_UART_OVERSAMPLING(SAMPLING) (((SAMPLING) == UART_OVERSAMPLING_16) || \ ((SAMPLING) == UART_OVERSAMPLING_8)) /** * @} */ /** @defgroup UART_LIN_Break_Detection_Length UART LIN Break Detection Length * @{ */ #define UART_LINBREAKDETECTLENGTH_10B ((uint32_t)0x00000000) #define UART_LINBREAKDETECTLENGTH_11B ((uint32_t)USART_CR2_LBDL) #define IS_UART_LIN_BREAK_DETECT_LENGTH(LENGTH) (((LENGTH) == UART_LINBREAKDETECTLENGTH_10B) || \ ((LENGTH) == UART_LINBREAKDETECTLENGTH_11B)) /** * @} */ /** @defgroup UART_WakeUp_functions UART Wakeup Functions * @{ */ #define UART_WAKEUPMETHOD_IDLELINE ((uint32_t)0x00000000) #define UART_WAKEUPMETHOD_ADDRESSMARK ((uint32_t)0x00000800) #define IS_UART_WAKEUPMETHOD(WAKEUP) (((WAKEUP) == UART_WAKEUPMETHOD_IDLELINE) || \ ((WAKEUP) == UART_WAKEUPMETHOD_ADDRESSMARK)) /** * @} */ /** @defgroup UART_Flags UART FLags * Elements values convention: 0xXXXX * - 0xXXXX : Flag mask in the SR register * @{ */ #define UART_FLAG_CTS ((uint32_t)USART_SR_CTS) #define UART_FLAG_LBD ((uint32_t)USART_SR_LBD) #define UART_FLAG_TXE ((uint32_t)USART_SR_TXE) #define UART_FLAG_TC ((uint32_t)USART_SR_TC) #define UART_FLAG_RXNE ((uint32_t)USART_SR_RXNE) #define UART_FLAG_IDLE ((uint32_t)USART_SR_IDLE) #define UART_FLAG_ORE ((uint32_t)USART_SR_ORE) #define UART_FLAG_NE ((uint32_t)USART_SR_NE) #define UART_FLAG_FE ((uint32_t)USART_SR_FE) #define UART_FLAG_PE ((uint32_t)USART_SR_PE) /** * @} */ /** @defgroup UART_Interrupt_definition UART Interrupt Definitions * Elements values convention: 0xY000XXXX * - XXXX : Interrupt mask in the XX register * - Y : Interrupt source register (2bits) * - 01: CR1 register * - 10: CR2 register * - 11: CR3 register * * @{ */ #define UART_IT_PE ((uint32_t)0x10000100) #define UART_IT_TXE ((uint32_t)0x10000080) #define UART_IT_TC ((uint32_t)0x10000040) #define UART_IT_RXNE ((uint32_t)0x10000020) #define UART_IT_IDLE ((uint32_t)0x10000010) #define UART_IT_LBD ((uint32_t)0x20000040) #define UART_IT_CTS ((uint32_t)0x30000400) #define UART_IT_ERR ((uint32_t)0x30000001) /** * @} */ /** @defgroup UART_Interruption_Mask UART interruptions flag mask * @{ */ #define UART_IT_MASK ((uint32_t)0x0000FFFF) /** * @} */ /** * @} */ /* Exported macro ------------------------------------------------------------*/ /** @defgroup UART_Exported_Macros UART Exported Macros * @{ */ /** @brief Reset UART handle state * @param __HANDLE__: specifies the UART Handle. * This parameter can be USARTx with x: 1, 2 or 3, or UARTy with y:4 or 5 to select the USART or * UART peripheral (availability depending on device for UARTy). * @retval None */ #define __HAL_UART_RESET_HANDLE_STATE(__HANDLE__) ((__HANDLE__)->State = HAL_UART_STATE_RESET) /** @brief Flushs the UART DR register * @param __HANDLE__: specifies the UART Handle. */ #define __HAL_UART_FLUSH_DRREGISTER(__HANDLE__) ((__HANDLE__)->Instance->DR) /** @brief Checks whether the specified UART flag is set or not. * @param __HANDLE__: specifies the UART Handle. * This parameter can be USARTx with x: 1, 2 or 3, or UARTy with y:4 or 5 to select the USART or * UART peripheral (availability depending on device for UARTy). * @param __FLAG__: specifies the flag to check. * This parameter can be one of the following values: * @arg UART_FLAG_CTS: CTS Change flag (not available for UART4 and UART5) * @arg UART_FLAG_LBD: LIN Break detection flag * @arg UART_FLAG_TXE: Transmit data register empty flag * @arg UART_FLAG_TC: Transmission Complete flag * @arg UART_FLAG_RXNE: Receive data register not empty flag * @arg UART_FLAG_IDLE: Idle Line detection flag * @arg UART_FLAG_ORE: OverRun Error flag * @arg UART_FLAG_NE: Noise Error flag * @arg UART_FLAG_FE: Framing Error flag * @arg UART_FLAG_PE: Parity Error flag * @retval The new state of __FLAG__ (TRUE or FALSE). */ #define __HAL_UART_GET_FLAG(__HANDLE__, __FLAG__) (((__HANDLE__)->Instance->SR & (__FLAG__)) == (__FLAG__)) /** @brief Clears the specified UART pending flag. * @param __HANDLE__: specifies the UART Handle. * This parameter can be USARTx with x: 1, 2 or 3, or UARTy with y:4 or 5 to select the USART or * UART peripheral (availability depending on device for UARTy). * @param __FLAG__: specifies the flag to check. * This parameter can be any combination of the following values: * @arg UART_FLAG_CTS: CTS Change flag (not available for UART4 and UART5). * @arg UART_FLAG_LBD: LIN Break detection flag. * @arg UART_FLAG_TC: Transmission Complete flag. * @arg UART_FLAG_RXNE: Receive data register not empty flag. * * @note PE (Parity error), FE (Framing error), NE (Noise error), ORE (OverRun * error) and IDLE (Idle line detected) flags are cleared by software * sequence: a read operation to USART_SR register followed by a read * operation to USART_DR register. * @note RXNE flag can be also cleared by a read to the USART_DR register. * @note TC flag can be also cleared by software sequence: a read operation to * USART_SR register followed by a write operation to USART_DR register. * @note TXE flag is cleared only by a write to the USART_DR register. * * @retval None */ #define __HAL_UART_CLEAR_FLAG(__HANDLE__, __FLAG__) ((__HANDLE__)->Instance->SR = ~(__FLAG__)) /** @brief Clear the UART PE pending flag. * @param __HANDLE__: specifies the UART Handle. * This parameter can be USARTx with x: 1, 2 or 3, or UARTy with y:4 or 5 to select the USART or * UART peripheral (availability depending on device for UARTy). * @retval None */ #define __HAL_UART_CLEAR_PEFLAG(__HANDLE__) do{(__HANDLE__)->Instance->SR;\ (__HANDLE__)->Instance->DR;}while(0) /** @brief Clear the UART FE pending flag. * @param __HANDLE__: specifies the UART Handle. * This parameter can be USARTx with x: 1, 2 or 3, or UARTy with y:4 or 5 to select the USART or * UART peripheral (availability depending on device for UARTy). * @retval None */ #define __HAL_UART_CLEAR_FEFLAG(__HANDLE__) __HAL_UART_CLEAR_PEFLAG(__HANDLE__) /** @brief Clear the UART NE pending flag. * @param __HANDLE__: specifies the UART Handle. * This parameter can be USARTx with x: 1, 2 or 3, or UARTy with y:4 or 5 to select the USART or * UART peripheral (availability depending on device for UARTy). * @retval None */ #define __HAL_UART_CLEAR_NEFLAG(__HANDLE__) __HAL_UART_CLEAR_PEFLAG(__HANDLE__) /** @brief Clear the UART ORE pending flag. * @param __HANDLE__: specifies the UART Handle. * This parameter can be USARTx with x: 1, 2 or 3, or UARTy with y:4 or 5 to select the USART or * UART peripheral (availability depending on device for UARTy). * @retval None */ #define __HAL_UART_CLEAR_OREFLAG(__HANDLE__) __HAL_UART_CLEAR_PEFLAG(__HANDLE__) /** @brief Clear the UART IDLE pending flag. * @param __HANDLE__: specifies the UART Handle. * This parameter can be USARTx with x: 1, 2 or 3, or UARTy with y:4 or 5 to select the USART or * UART peripheral (availability depending on device for UARTy). * @retval None */ #define __HAL_UART_CLEAR_IDLEFLAG(__HANDLE__) __HAL_UART_CLEAR_PEFLAG(__HANDLE__) /** @brief Enables or disables the specified UART interrupt. * @param __HANDLE__: specifies the UART Handle. * This parameter can be USARTx with x: 1, 2 or 3, or UARTy with y:4 or 5 to select the USART or * UART peripheral (availability depending on device for UARTy). * @param __INTERRUPT__: specifies the UART interrupt source to check. * This parameter can be one of the following values: * @arg UART_IT_CTS: CTS change interrupt * @arg UART_IT_LBD: LIN Break detection interrupt * @arg UART_IT_TXE: Transmit Data Register empty interrupt * @arg UART_IT_TC: Transmission complete interrupt * @arg UART_IT_RXNE: Receive Data register not empty interrupt * @arg UART_IT_IDLE: Idle line detection interrupt * @arg UART_IT_PE: Parity Error interrupt * @arg UART_IT_ERR: Error interrupt(Frame error, noise error, overrun error) * @retval None */ #define __HAL_UART_ENABLE_IT(__HANDLE__, __INTERRUPT__) ((((__INTERRUPT__) >> 28) == 1)? ((__HANDLE__)->Instance->CR1 |= ((__INTERRUPT__) & UART_IT_MASK)): \ (((__INTERRUPT__) >> 28) == 2)? ((__HANDLE__)->Instance->CR2 |= ((__INTERRUPT__) & UART_IT_MASK)): \ ((__HANDLE__)->Instance->CR3 |= ((__INTERRUPT__) & UART_IT_MASK))) #define __HAL_UART_DISABLE_IT(__HANDLE__, __INTERRUPT__) ((((__INTERRUPT__) >> 28) == 1)? ((__HANDLE__)->Instance->CR1 &= ~((__INTERRUPT__) & UART_IT_MASK)): \ (((__INTERRUPT__) >> 28) == 2)? ((__HANDLE__)->Instance->CR2 &= ~((__INTERRUPT__) & UART_IT_MASK)): \ ((__HANDLE__)->Instance->CR3 &= ~ ((__INTERRUPT__) & UART_IT_MASK))) /** @brief Checks whether the specified UART interrupt has occurred or not. * @param __HANDLE__: specifies the UART Handle. * This parameter can be USARTx with x: 1, 2 or 3, or UARTy with y:4 or 5 to select the USART or * UART peripheral (availability depending on device for UARTy). * @param __IT__: specifies the UART interrupt source to check. * This parameter can be one of the following values: * @arg UART_IT_CTS: CTS change interrupt (not available for UART4 and UART5) * @arg UART_IT_LBD: LIN Break detection interrupt * @arg UART_IT_TXE: Transmit Data Register empty interrupt * @arg UART_IT_TC: Transmission complete interrupt * @arg UART_IT_RXNE: Receive Data register not empty interrupt * @arg UART_IT_IDLE: Idle line detection interrupt * @arg USART_IT_ERR: Error interrupt * @retval The new state of __IT__ (TRUE or FALSE). */ #define __HAL_UART_GET_IT_SOURCE(__HANDLE__, __IT__) (((((__IT__) >> 28) == 1)? (__HANDLE__)->Instance->CR1:(((((uint32_t)(__IT__)) >> 28) == 2)? \ (__HANDLE__)->Instance->CR2 : (__HANDLE__)->Instance->CR3)) & (((uint32_t)(__IT__)) & UART_IT_MASK)) /** @brief macros to enables or disables the UART's one bit sampling method * @param __HANDLE__: specifies the UART Handle. * This parameter can be USARTx with x: 1, 2 or 3, or UARTy with y:4 or 5 to select the USART or * UART peripheral (availability depending on device for UARTy). * @retval None */ #define __HAL_UART_ONEBIT_ENABLE(__HANDLE__) ((__HANDLE__)->Instance->CR3|= USART_CR3_ONEBIT) #define __HAL_UART_ONEBIT_DISABLE(__HANDLE__) ((__HANDLE__)->Instance->CR3 &= (uint16_t)~((uint16_t)USART_CR3_ONEBIT)) /** @brief Enable UART * @param __HANDLE__: specifies the UART Handle. * The Handle Instance can be USARTx with x: 1, 2 or 3, or UARTy with y:4 or 5 to select the USART or * UART peripheral (availability depending on device for UARTy). * @retval None */ #define __HAL_UART_ENABLE(__HANDLE__) ((__HANDLE__)->Instance->CR1 |= USART_CR1_UE) /** @brief Disable UART * The Handle Instance can be USARTx with x: 1, 2 or 3, or UARTy with y:4 or 5 to select the USART or * UART peripheral (availability depending on device for UARTy). * @retval None */ #define __HAL_UART_DISABLE(__HANDLE__) ((__HANDLE__)->Instance->CR1 &= ~USART_CR1_UE) /** * @} */ /* Private macros --------------------------------------------------------*/ /** @defgroup UART_Private_Macros UART Private Macros * @{ */ #define UART_DIV_SAMPLING16(_PCLK_, _BAUD_) (((_PCLK_)*25)/(4*(_BAUD_))) #define UART_DIVMANT_SAMPLING16(_PCLK_, _BAUD_) (UART_DIV_SAMPLING16((_PCLK_), (_BAUD_))/100) #define UART_DIVFRAQ_SAMPLING16(_PCLK_, _BAUD_) (((UART_DIV_SAMPLING16((_PCLK_), (_BAUD_)) - (UART_DIVMANT_SAMPLING16((_PCLK_), (_BAUD_)) * 100)) * 16 + 50) / 100) #define UART_BRR_SAMPLING16(_PCLK_, _BAUD_) ((UART_DIVMANT_SAMPLING16((_PCLK_), (_BAUD_)) << 4)|(UART_DIVFRAQ_SAMPLING16((_PCLK_), (_BAUD_)) & 0x0F)) #define UART_DIV_SAMPLING8(_PCLK_, _BAUD_) (((_PCLK_)*25)/(2*(_BAUD_))) #define UART_DIVMANT_SAMPLING8(_PCLK_, _BAUD_) (UART_DIV_SAMPLING8((_PCLK_), (_BAUD_))/100) #define UART_DIVFRAQ_SAMPLING8(_PCLK_, _BAUD_) (((UART_DIV_SAMPLING8((_PCLK_), (_BAUD_)) - (UART_DIVMANT_SAMPLING8((_PCLK_), (_BAUD_)) * 100)) * 16 + 50) / 100) #define UART_BRR_SAMPLING8(_PCLK_, _BAUD_) ((UART_DIVMANT_SAMPLING8((_PCLK_), (_BAUD_)) << 4)|(UART_DIVFRAQ_SAMPLING8((_PCLK_), (_BAUD_)) & 0x0F)) /** @brief Check UART Baud rate * @param __BAUDRATE__: Baudrate specified by the user * The maximum Baud Rate is derived from the maximum clock on APB (i.e. 32 MHz) * divided by the smallest oversampling used on the USART (i.e. 8) * @retval Test result (TRUE or FALSE). */ #define IS_UART_BAUDRATE(__BAUDRATE__) ((__BAUDRATE__) < 4000001) #define IS_UART_ADDRESS(ADDRESS) ((ADDRESS) <= 0xF) /** * @} */ /* Exported functions --------------------------------------------------------*/ /** @addtogroup UART_Exported_Functions UART Exported Functions * @{ */ /** @addtogroup UART_Exported_Functions_Group1 Initialization and de-initialization functions * @{ */ /* Initialization and de-initialization functions ****************************/ HAL_StatusTypeDef HAL_UART_Init(UART_HandleTypeDef *huart); HAL_StatusTypeDef HAL_HalfDuplex_Init(UART_HandleTypeDef *huart); HAL_StatusTypeDef HAL_LIN_Init(UART_HandleTypeDef *huart, uint32_t BreakDetectLength); HAL_StatusTypeDef HAL_MultiProcessor_Init(UART_HandleTypeDef *huart, uint8_t Address, uint32_t WakeUpMethod); HAL_StatusTypeDef HAL_UART_DeInit (UART_HandleTypeDef *huart); void HAL_UART_MspInit(UART_HandleTypeDef *huart); void HAL_UART_MspDeInit(UART_HandleTypeDef *huart); /** * @} */ /** @addtogroup UART_Exported_Functions_Group2 IO operation functions * @{ */ /* IO operation functions *****************************************************/ HAL_StatusTypeDef HAL_UART_Transmit(UART_HandleTypeDef *huart, uint8_t *pData, uint16_t Size, uint32_t Timeout); HAL_StatusTypeDef HAL_UART_Receive(UART_HandleTypeDef *huart, uint8_t *pData, uint16_t Size, uint32_t Timeout); HAL_StatusTypeDef HAL_UART_Transmit_IT(UART_HandleTypeDef *huart, uint8_t *pData, uint16_t Size); HAL_StatusTypeDef HAL_UART_Receive_IT(UART_HandleTypeDef *huart, uint8_t *pData, uint16_t Size); HAL_StatusTypeDef HAL_UART_Transmit_DMA(UART_HandleTypeDef *huart, uint8_t *pData, uint16_t Size); HAL_StatusTypeDef HAL_UART_Receive_DMA(UART_HandleTypeDef *huart, uint8_t *pData, uint16_t Size); HAL_StatusTypeDef HAL_UART_DMAPause(UART_HandleTypeDef *huart); HAL_StatusTypeDef HAL_UART_DMAResume(UART_HandleTypeDef *huart); HAL_StatusTypeDef HAL_UART_DMAStop(UART_HandleTypeDef *huart); void HAL_UART_IRQHandler(UART_HandleTypeDef *huart); void HAL_UART_TxCpltCallback(UART_HandleTypeDef *huart); void HAL_UART_TxHalfCpltCallback(UART_HandleTypeDef *huart); void HAL_UART_RxCpltCallback(UART_HandleTypeDef *huart); void HAL_UART_RxHalfCpltCallback(UART_HandleTypeDef *huart); void HAL_UART_ErrorCallback(UART_HandleTypeDef *huart); /** * @} */ /** @addtogroup UART_Exported_Functions_Group3 Peripheral Control functions * @{ */ /* Peripheral Control functions ************************************************/ HAL_StatusTypeDef HAL_LIN_SendBreak(UART_HandleTypeDef *huart); HAL_StatusTypeDef HAL_MultiProcessor_EnterMuteMode(UART_HandleTypeDef *huart); HAL_StatusTypeDef HAL_MultiProcessor_ExitMuteMode(UART_HandleTypeDef *huart); HAL_StatusTypeDef HAL_HalfDuplex_EnableTransmitter(UART_HandleTypeDef *huart); HAL_StatusTypeDef HAL_HalfDuplex_EnableReceiver(UART_HandleTypeDef *huart); /** * @} */ /** @addtogroup UART_Exported_Functions_Group4 Peripheral State and Errors functions * @{ */ /* Peripheral State and Errors functions **************************************************/ HAL_UART_StateTypeDef HAL_UART_GetState(UART_HandleTypeDef *huart); uint32_t HAL_UART_GetError(UART_HandleTypeDef *huart); /** * @} */ /** * @} */ /** * @} */ /** * @} */ #ifdef __cplusplus } #endif #endif /* __STM32L1xx_HAL_UART_H */ /************************ (C) COPYRIGHT STMicroelectronics *****END OF FILE****/ ================================================ FILE: Zelig/mbed/TARGET_NUCLEO_L152RE/stm32l1xx_hal_usart.h ================================================ /** ****************************************************************************** * @file stm32l1xx_hal_usart.h * @author MCD Application Team * @version V1.0.0 * @date 5-September-2014 * @brief This file contains all the functions prototypes for the USART * firmware library. ****************************************************************************** * @attention * *

© COPYRIGHT(c) 2014 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. * ****************************************************************************** */ /* Define to prevent recursive inclusion -------------------------------------*/ #ifndef __STM32L1xx_HAL_USART_H #define __STM32L1xx_HAL_USART_H #ifdef __cplusplus extern "C" { #endif /* Includes ------------------------------------------------------------------*/ #include "stm32l1xx_hal_def.h" /** @addtogroup STM32L1xx_HAL_Driver * @{ */ /** @addtogroup USART * @{ */ /* Exported types ------------------------------------------------------------*/ /** @defgroup USART_Exported_Types USART Exported Types * @{ */ /** * @brief USART Init Structure definition */ typedef struct { uint32_t BaudRate; /*!< This member configures the Usart communication baud rate. The baud rate is computed using the following formula: - IntegerDivider = ((PCLKx) / (8 * (husart->Init.BaudRate))) - FractionalDivider = ((IntegerDivider - ((uint32_t) IntegerDivider)) * 8) + 0.5 */ uint32_t WordLength; /*!< Specifies the number of data bits transmitted or received in a frame. This parameter can be a value of @ref USART_Word_Length */ uint32_t StopBits; /*!< Specifies the number of stop bits transmitted. This parameter can be a value of @ref USART_Stop_Bits */ uint32_t Parity; /*!< Specifies the parity mode. This parameter can be a value of @ref USART_Parity @note When parity is enabled, the computed parity is inserted at the MSB position of the transmitted data (9th bit when the word length is set to 9 data bits; 8th bit when the word length is set to 8 data bits). */ uint32_t Mode; /*!< Specifies wether the Receive or Transmit mode is enabled or disabled. This parameter can be a value of @ref USART_Mode */ uint32_t CLKPolarity; /*!< Specifies the steady state of the serial clock. This parameter can be a value of @ref USART_Clock_Polarity */ uint32_t CLKPhase; /*!< Specifies the clock transition on which the bit capture is made. This parameter can be a value of @ref USART_Clock_Phase */ uint32_t CLKLastBit; /*!< Specifies whether the clock pulse corresponding to the last transmitted data bit (MSB) has to be output on the SCLK pin in synchronous mode. This parameter can be a value of @ref USART_Last_Bit */ }USART_InitTypeDef; /** * @brief HAL State structures definition */ typedef enum { HAL_USART_STATE_RESET = 0x00, /*!< Peripheral is not initialized */ HAL_USART_STATE_READY = 0x01, /*!< Peripheral Initialized and ready for use */ HAL_USART_STATE_BUSY = 0x02, /*!< an internal process is ongoing */ HAL_USART_STATE_BUSY_TX = 0x12, /*!< Data Transmission process is ongoing */ HAL_USART_STATE_BUSY_RX = 0x22, /*!< Data Reception process is ongoing */ HAL_USART_STATE_BUSY_TX_RX = 0x32, /*!< Data Transmission Reception process is ongoing */ HAL_USART_STATE_TIMEOUT = 0x03, /*!< Timeout state */ HAL_USART_STATE_ERROR = 0x04 /*!< Error */ }HAL_USART_StateTypeDef; /** * @brief HAL USART Error Code structure definition */ typedef enum { HAL_USART_ERROR_NONE = 0x00, /*!< No error */ HAL_USART_ERROR_PE = 0x01, /*!< Parity error */ HAL_USART_ERROR_NE = 0x02, /*!< Noise error */ HAL_USART_ERROR_FE = 0x04, /*!< frame error */ HAL_USART_ERROR_ORE = 0x08, /*!< Overrun error */ HAL_USART_ERROR_DMA = 0x10 /*!< DMA transfer error */ }HAL_USART_ErrorTypeDef; /** * @brief USART handle Structure definition */ typedef struct { USART_TypeDef *Instance; /* USART registers base address */ USART_InitTypeDef Init; /* Usart communication parameters */ uint8_t *pTxBuffPtr; /* Pointer to Usart Tx transfer Buffer */ uint16_t TxXferSize; /* Usart Tx Transfer size */ __IO uint16_t TxXferCount; /* Usart Tx Transfer Counter */ uint8_t *pRxBuffPtr; /* Pointer to Usart Rx transfer Buffer */ uint16_t RxXferSize; /* Usart Rx Transfer size */ __IO uint16_t RxXferCount; /* Usart Rx Transfer Counter */ DMA_HandleTypeDef *hdmatx; /* Usart Tx DMA Handle parameters */ DMA_HandleTypeDef *hdmarx; /* Usart Rx DMA Handle parameters */ HAL_LockTypeDef Lock; /* Locking object */ __IO HAL_USART_StateTypeDef State; /* Usart communication state */ __IO HAL_USART_ErrorTypeDef ErrorCode; /* USART Error code */ }USART_HandleTypeDef; /** * @} */ /* Exported constants --------------------------------------------------------*/ /** @defgroup USART_Exported_Constants USART Exported constants * @{ */ /** @defgroup USART_Word_Length USART Word Length * @{ */ #define USART_WORDLENGTH_8B ((uint32_t)0x00000000) #define USART_WORDLENGTH_9B ((uint32_t)USART_CR1_M) #define IS_USART_WORD_LENGTH(LENGTH) (((LENGTH) == USART_WORDLENGTH_8B) || \ ((LENGTH) == USART_WORDLENGTH_9B)) /** * @} */ /** @defgroup USART_Stop_Bits USART Number of Stop Bits * @{ */ #define USART_STOPBITS_1 ((uint32_t)0x00000000) #define USART_STOPBITS_0_5 ((uint32_t)USART_CR2_STOP_0) #define USART_STOPBITS_2 ((uint32_t)USART_CR2_STOP_1) #define USART_STOPBITS_1_5 ((uint32_t)(USART_CR2_STOP_0 | USART_CR2_STOP_1)) #define IS_USART_STOPBITS(STOPBITS) (((STOPBITS) == USART_STOPBITS_1) || \ ((STOPBITS) == USART_STOPBITS_0_5) || \ ((STOPBITS) == USART_STOPBITS_1_5) || \ ((STOPBITS) == USART_STOPBITS_2)) /** * @} */ /** @defgroup USART_Parity USART Parity * @{ */ #define USART_PARITY_NONE ((uint32_t)0x00000000) #define USART_PARITY_EVEN ((uint32_t)USART_CR1_PCE) #define USART_PARITY_ODD ((uint32_t)(USART_CR1_PCE | USART_CR1_PS)) #define IS_USART_PARITY(PARITY) (((PARITY) == USART_PARITY_NONE) || \ ((PARITY) == USART_PARITY_EVEN) || \ ((PARITY) == USART_PARITY_ODD)) /** * @} */ /** @defgroup USART_Mode USART Mode * @{ */ #define USART_MODE_RX ((uint32_t)USART_CR1_RE) #define USART_MODE_TX ((uint32_t)USART_CR1_TE) #define USART_MODE_TX_RX ((uint32_t)(USART_CR1_TE |USART_CR1_RE)) #define IS_USART_MODE(MODE) ((((MODE) & (uint32_t)0x0000FFF3) == 0x00) && ((MODE) != (uint32_t)0x00000000)) /** * @} */ /** @defgroup USART_Clock USART Clock * @{ */ #define USART_CLOCK_DISABLED ((uint32_t)0x00000000) #define USART_CLOCK_ENABLED ((uint32_t)USART_CR2_CLKEN) #define IS_USART_CLOCK(CLOCK) (((CLOCK) == USART_CLOCK_DISABLED) || \ ((CLOCK) == USART_CLOCK_ENABLED)) /** * @} */ /** @defgroup USART_Clock_Polarity USART Clock Polarity * @{ */ #define USART_POLARITY_LOW ((uint32_t)0x00000000) #define USART_POLARITY_HIGH ((uint32_t)USART_CR2_CPOL) #define IS_USART_POLARITY(CPOL) (((CPOL) == USART_POLARITY_LOW) || ((CPOL) == USART_POLARITY_HIGH)) /** * @} */ /** @defgroup USART_Clock_Phase USART Clock Phase * @{ */ #define USART_PHASE_1EDGE ((uint32_t)0x00000000) #define USART_PHASE_2EDGE ((uint32_t)USART_CR2_CPHA) #define IS_USART_PHASE(CPHA) (((CPHA) == USART_PHASE_1EDGE) || ((CPHA) == USART_PHASE_2EDGE)) /** * @} */ /** @defgroup USART_Last_Bit USART Last Bit * @{ */ #define USART_LASTBIT_DISABLE ((uint32_t)0x00000000) #define USART_LASTBIT_ENABLE ((uint32_t)USART_CR2_LBCL) #define IS_USART_LASTBIT(LASTBIT) (((LASTBIT) == USART_LASTBIT_DISABLE) || \ ((LASTBIT) == USART_LASTBIT_ENABLE)) /** * @} */ /** @defgroup USART_NACK_State USART NACK State * @{ */ #define USARTNACK_ENABLED ((uint32_t)USART_CR3_NACK) #define USARTNACK_DISABLED ((uint32_t)0x00000000) #define IS_USART_NACK_STATE(NACK) (((NACK) == USARTNACK_ENABLED) || \ ((NACK) == USARTNACK_DISABLED)) /** * @} */ /** @defgroup USART_Flags USART Flags * Elements values convention: 0xXXXX * - 0xXXXX : Flag mask in the SR register * @{ */ #define USART_FLAG_CTS ((uint32_t)USART_SR_CTS) #define USART_FLAG_LBD ((uint32_t)USART_SR_LBD) #define USART_FLAG_TXE ((uint32_t)USART_SR_TXE) #define USART_FLAG_TC ((uint32_t)USART_SR_TC) #define USART_FLAG_RXNE ((uint32_t)USART_SR_RXNE) #define USART_FLAG_IDLE ((uint32_t)USART_SR_IDLE) #define USART_FLAG_ORE ((uint32_t)USART_SR_ORE) #define USART_FLAG_NE ((uint32_t)USART_SR_NE) #define USART_FLAG_FE ((uint32_t)USART_SR_FE) #define USART_FLAG_PE ((uint32_t)USART_SR_PE) /** * @} */ /** @defgroup USART_Interrupt_definition USART Interrupts Definition * Elements values convention: 0xY000XXXX * - XXXX : Interrupt mask in the XX register * - Y : Interrupt source register (4bits) * - 01: CR1 register * - 10: CR2 register * - 11: CR3 register * * @{ */ #define USART_IT_PE ((uint32_t)0x10000100) #define USART_IT_TXE ((uint32_t)0x10000080) #define USART_IT_TC ((uint32_t)0x10000040) #define USART_IT_RXNE ((uint32_t)0x10000020) #define USART_IT_IDLE ((uint32_t)0x10000010) #define USART_IT_LBD ((uint32_t)0x20000040) #define USART_IT_CTS ((uint32_t)0x30000400) #define USART_IT_ERR ((uint32_t)0x30000001) /** * @} */ /** @defgroup USART_Interruption_Mask USART interruptions flag mask * @{ */ #define USART_IT_MASK ((uint32_t)0x0000FFFF) /** * @} */ /** * @} */ /* Exported macro ------------------------------------------------------------*/ /** @defgroup USART_Exported_Macros USART Exported Macros * @{ */ /** @brief Reset USART handle state * @param __HANDLE__: specifies the USART Handle. * This parameter can be USARTx where x: 1, 2 or 3 to select the USART peripheral. * @retval None */ #define __HAL_USART_RESET_HANDLE_STATE(__HANDLE__) ((__HANDLE__)->State = HAL_USART_STATE_RESET) /** @brief Checks whether the specified USART flag is set or not. * @param __HANDLE__: specifies the USART Handle. * This parameter can be USARTx where x: 1, 2 or 3 to select the USART peripheral. * @param __FLAG__: specifies the flag to check. * This parameter can be one of the following values: * @arg USART_FLAG_TXE: Transmit data register empty flag * @arg USART_FLAG_TC: Transmission Complete flag * @arg USART_FLAG_RXNE: Receive data register not empty flag * @arg USART_FLAG_IDLE: Idle Line detection flag * @arg USART_FLAG_ORE: OverRun Error flag * @arg USART_FLAG_NE: Noise Error flag * @arg USART_FLAG_FE: Framing Error flag * @arg USART_FLAG_PE: Parity Error flag * @retval The new state of __FLAG__ (TRUE or FALSE). */ #define __HAL_USART_GET_FLAG(__HANDLE__, __FLAG__) (((__HANDLE__)->Instance->SR & (__FLAG__)) == (__FLAG__)) /** @brief Clears the specified USART pending flags. * @param __HANDLE__: specifies the USART Handle. * This parameter can be USARTx where x: 1, 2 or 3 to select the USART peripheral. * @param __FLAG__: specifies the flag to check. * This parameter can be any combination of the following values: * @arg USART_FLAG_TC: Transmission Complete flag. * @arg USART_FLAG_RXNE: Receive data register not empty flag. * * @note PE (Parity error), FE (Framing error), NE (Noise error), ORE (OverRun * error) and IDLE (Idle line detected) flags are cleared by software * sequence: a read operation to USART_SR register followed by a read * operation to USART_DR register. * @note RXNE flag can be also cleared by a read to the USART_DR register. * @note TC flag can be also cleared by software sequence: a read operation to * USART_SR register followed by a write operation to USART_DR register. * @note TXE flag is cleared only by a write to the USART_DR register. * * @retval None */ #define __HAL_USART_CLEAR_FLAG(__HANDLE__, __FLAG__) ((__HANDLE__)->Instance->SR = ~(__FLAG__)) /** @brief Clear the USART PE pending flag. * @param __HANDLE__: specifies the USART Handle. * This parameter can be USARTx where x: 1, 2 or 3 to select the USART peripheral. * @retval None */ #define __HAL_USART_CLEAR_PEFLAG(__HANDLE__) do{(__HANDLE__)->Instance->SR;\ (__HANDLE__)->Instance->DR;}while(0) /** @brief Clear the USART FE pending flag. * @param __HANDLE__: specifies the USART Handle. * This parameter can be USARTx where x: 1, 2 or 3 to select the USART peripheral. * @retval None */ #define __HAL_USART_CLEAR_FEFLAG(__HANDLE__) __HAL_USART_CLEAR_PEFLAG(__HANDLE__) /** @brief Clear the USART NE pending flag. * @param __HANDLE__: specifies the USART Handle. * This parameter can be USARTx where x: 1, 2 or 3 to select the USART peripheral. * @retval None */ #define __HAL_USART_CLEAR_NEFLAG(__HANDLE__) __HAL_USART_CLEAR_PEFLAG(__HANDLE__) /** @brief Clear the USART ORE pending flag. * @param __HANDLE__: specifies the USART Handle. * This parameter can be USARTx where x: 1, 2 or 3 to select the USART peripheral. * @retval None */ #define __HAL_USART_CLEAR_OREFLAG(__HANDLE__) __HAL_USART_CLEAR_PEFLAG(__HANDLE__) /** @brief Clear the USART IDLE pending flag. * @param __HANDLE__: specifies the USART Handle. * This parameter can be USARTx where x: 1, 2 or 3 to select the USART peripheral. * @retval None */ #define __HAL_USART_CLEAR_IDLEFLAG(__HANDLE__) __HAL_USART_CLEAR_PEFLAG(__HANDLE__) /** @brief Enables or disables the specified Usart interrupts. * @param __HANDLE__: specifies the USART Handle. * This parameter can be USARTx where x: 1, 2 or 3 to select the USART peripheral. * @param __INTERRUPT__: specifies the USART interrupt source to check. * This parameter can be one of the following values: * @arg USART_IT_TXE: Transmit Data Register empty interrupt * @arg USART_IT_TC: Transmission complete interrupt * @arg USART_IT_RXNE: Receive Data register not empty interrupt * @arg USART_IT_IDLE: Idle line detection interrupt * @arg USART_IT_PE: Parity Error interrupt * @arg USART_IT_ERR: Error interrupt(Frame error, noise error, overrun error) * @retval None */ #define __HAL_USART_ENABLE_IT(__HANDLE__, __INTERRUPT__) ((((__INTERRUPT__) >> 28) == 1)? ((__HANDLE__)->Instance->CR1 |= ((__INTERRUPT__) & USART_IT_MASK)): \ (((__INTERRUPT__) >> 28) == 2)? ((__HANDLE__)->Instance->CR2 |= ((__INTERRUPT__) & USART_IT_MASK)): \ ((__HANDLE__)->Instance->CR3 |= ((__INTERRUPT__) & USART_IT_MASK))) #define __HAL_USART_DISABLE_IT(__HANDLE__, __INTERRUPT__) ((((__INTERRUPT__) >> 28) == 1)? ((__HANDLE__)->Instance->CR1 &= ~((__INTERRUPT__) & USART_IT_MASK)): \ (((__INTERRUPT__) >> 28) == 2)? ((__HANDLE__)->Instance->CR2 &= ~((__INTERRUPT__) & USART_IT_MASK)): \ ((__HANDLE__)->Instance->CR3 &= ~ ((__INTERRUPT__) & USART_IT_MASK))) /** @brief Checks whether the specified Usart interrupt has occurred or not. * @param __HANDLE__: specifies the USART Handle. * This parameter can be USARTx where x: 1, 2 or 3 to select the USART peripheral. * @param __IT__: specifies the USART interrupt source to check. * This parameter can be one of the following values: * @arg USART_IT_TXE: Transmit Data Register empty interrupt * @arg USART_IT_TC: Transmission complete interrupt * @arg USART_IT_RXNE: Receive Data register not empty interrupt * @arg USART_IT_IDLE: Idle line detection interrupt * @arg USART_IT_ERR: Error interrupt * @arg USART_IT_PE: Parity Error interrupt * @retval The new state of __IT__ (TRUE or FALSE). */ #define __HAL_USART_GET_IT_SOURCE(__HANDLE__, __IT__) (((((__IT__) >> 28) == 1)? (__HANDLE__)->Instance->CR1:(((((uint32_t)(__IT__)) >> 28) == 2)? \ (__HANDLE__)->Instance->CR2 : (__HANDLE__)->Instance->CR3)) & (((uint32_t)(__IT__)) & USART_IT_MASK)) /** @brief Enable USART * @param __HANDLE__: specifies the USART Handle. * The Handle Instance can be USARTx where x: 1, 2, 3 to select the USART peripheral * @retval None */ #define __HAL_USART_ENABLE(__HANDLE__) SET_BIT((__HANDLE__)->Instance->CR1,(USART_CR1_UE)) /** @brief Disable USART * @param __HANDLE__: specifies the USART Handle. * The Handle Instance can be USARTx where x: 1, 2, 3 to select the USART peripheral * @retval None */ #define __HAL_USART_DISABLE(__HANDLE__) CLEAR_BIT((__HANDLE__)->Instance->CR1,(USART_CR1_UE)) /** * @} */ /* Private macros --------------------------------------------------------*/ /** @defgroup USART_Private_Macros USART Private Macros * @{ */ #define USART_DIV(__PCLK__, __BAUD__) (((__PCLK__)*25)/(4*(__BAUD__))) #define USART_DIVMANT(__PCLK__, __BAUD__) (USART_DIV((__PCLK__), (__BAUD__))/100) #define USART_DIVFRAQ(__PCLK__, __BAUD__) (((USART_DIV((__PCLK__), (__BAUD__)) - (USART_DIVMANT((__PCLK__), (__BAUD__)) * 100)) * 16 + 50) / 100) #define USART_BRR(__PCLK__, __BAUD__) ((USART_DIVMANT((__PCLK__), (__BAUD__)) << 4)|(USART_DIVFRAQ((__PCLK__), (__BAUD__)) & 0x0F)) /** @brief Check USART Baud rate * @param __BAUDRATE__: Baudrate specified by the user * The maximum Baud Rate is derived from the maximum clock on APB (i.e. 32 MHz) * divided by the smallest oversampling used on the USART (i.e. 8) * @retval Test result (TRUE or FALSE) */ #define IS_USART_BAUDRATE(__BAUDRATE__) ((__BAUDRATE__) < 4000001) /** * @} */ /* Exported functions --------------------------------------------------------*/ /** @addtogroup USART_Exported_Functions USART Exported Functions * @{ */ /** @addtogroup USART_Exported_Functions_Group1 USART Initialization and de-initialization functions * @{ */ /* Initialization and de-initialization functions ******************************/ HAL_StatusTypeDef HAL_USART_Init(USART_HandleTypeDef *husart); HAL_StatusTypeDef HAL_USART_DeInit(USART_HandleTypeDef *husart); void HAL_USART_MspInit(USART_HandleTypeDef *husart); void HAL_USART_MspDeInit(USART_HandleTypeDef *husart); /** * @} */ /** @addtogroup USART_Exported_Functions_Group2 IO operation functions * @{ */ /* IO operation functions *******************************************************/ HAL_StatusTypeDef HAL_USART_Transmit(USART_HandleTypeDef *husart, uint8_t *pTxData, uint16_t Size, uint32_t Timeout); HAL_StatusTypeDef HAL_USART_Receive(USART_HandleTypeDef *husart, uint8_t *pRxData, uint16_t Size, uint32_t Timeout); HAL_StatusTypeDef HAL_USART_TransmitReceive(USART_HandleTypeDef *husart, uint8_t *pTxData, uint8_t *pRxData, uint16_t Size, uint32_t Timeout); HAL_StatusTypeDef HAL_USART_Transmit_IT(USART_HandleTypeDef *husart, uint8_t *pTxData, uint16_t Size); HAL_StatusTypeDef HAL_USART_Receive_IT(USART_HandleTypeDef *husart, uint8_t *pRxData, uint16_t Size); HAL_StatusTypeDef HAL_USART_TransmitReceive_IT(USART_HandleTypeDef *husart, uint8_t *pTxData, uint8_t *pRxData, uint16_t Size); HAL_StatusTypeDef HAL_USART_Transmit_DMA(USART_HandleTypeDef *husart, uint8_t *pTxData, uint16_t Size); HAL_StatusTypeDef HAL_USART_Receive_DMA(USART_HandleTypeDef *husart, uint8_t *pRxData, uint16_t Size); HAL_StatusTypeDef HAL_USART_TransmitReceive_DMA(USART_HandleTypeDef *husart, uint8_t *pTxData, uint8_t *pRxData, uint16_t Size); HAL_StatusTypeDef HAL_USART_DMAPause(USART_HandleTypeDef *husart); HAL_StatusTypeDef HAL_USART_DMAResume(USART_HandleTypeDef *husart); HAL_StatusTypeDef HAL_USART_DMAStop(USART_HandleTypeDef *husart); void HAL_USART_IRQHandler(USART_HandleTypeDef *husart); void HAL_USART_TxCpltCallback(USART_HandleTypeDef *husart); void HAL_USART_TxHalfCpltCallback(USART_HandleTypeDef *husart); void HAL_USART_RxCpltCallback(USART_HandleTypeDef *husart); void HAL_USART_RxHalfCpltCallback(USART_HandleTypeDef *husart); void HAL_USART_TxRxCpltCallback(USART_HandleTypeDef *husart); void HAL_USART_ErrorCallback(USART_HandleTypeDef *husart); /** * @} */ /* Peripheral Control functions ***********************************************/ /** @addtogroup USART_Exported_Functions_Group3 Peripheral State and Errors functions * @{ */ /* Peripheral State and Error functions ***************************************/ HAL_USART_StateTypeDef HAL_USART_GetState(USART_HandleTypeDef *husart); uint32_t HAL_USART_GetError(USART_HandleTypeDef *husart); /** * @} */ /** * @} */ /** * @} */ /** * @} */ #ifdef __cplusplus } #endif #endif /* __STM32L1xx_HAL_USART_H */ /************************ (C) COPYRIGHT STMicroelectronics *****END OF FILE****/ ================================================ FILE: Zelig/mbed/TARGET_NUCLEO_L152RE/stm32l1xx_hal_wwdg.h ================================================ /** ****************************************************************************** * @file stm32l1xx_hal_wwdg.h * @author MCD Application Team * @version V1.0.0 * @date 5-September-2014 * @brief Header file of WWDG HAL module. ****************************************************************************** * @attention * *

© COPYRIGHT(c) 2014 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. * ****************************************************************************** */ /* Define to prevent recursive inclusion -------------------------------------*/ #ifndef __STM32L1xx_HAL_WWDG_H #define __STM32L1xx_HAL_WWDG_H #ifdef __cplusplus extern "C" { #endif /* Includes ------------------------------------------------------------------*/ #include "stm32l1xx_hal_def.h" /** @addtogroup STM32L1xx_HAL_Driver * @{ */ /** @addtogroup WWDG * @{ */ /* Exported types ------------------------------------------------------------*/ /** @defgroup WWDG_Exported_Types WWDG Exported Types * @{ */ /** * @brief WWDG HAL State Structure definition */ typedef enum { HAL_WWDG_STATE_RESET = 0x00, /*!< WWDG not yet initialized or disabled */ HAL_WWDG_STATE_READY = 0x01, /*!< WWDG initialized and ready for use */ HAL_WWDG_STATE_BUSY = 0x02, /*!< WWDG internal process is ongoing */ HAL_WWDG_STATE_TIMEOUT = 0x03, /*!< WWDG timeout state */ HAL_WWDG_STATE_ERROR = 0x04 /*!< WWDG error state */ }HAL_WWDG_StateTypeDef; /** * @brief WWDG Init structure definition */ typedef struct { uint32_t Prescaler; /*!< Specifies the prescaler value of the WWDG. This parameter can be a value of @ref WWDG_Prescaler */ uint32_t Window; /*!< Specifies the WWDG window value to be compared to the downcounter. This parameter must be a number lower than Max_Data = 0x80 */ uint32_t Counter; /*!< Specifies the WWDG free-running downcounter value. This parameter must be a number between Min_Data = 0x40 and Max_Data = 0x7F */ }WWDG_InitTypeDef; /** * @brief WWDG handle Structure definition */ typedef struct { WWDG_TypeDef *Instance; /*!< Register base address */ WWDG_InitTypeDef Init; /*!< WWDG required parameters */ HAL_LockTypeDef Lock; /*!< WWDG locking object */ __IO HAL_WWDG_StateTypeDef State; /*!< WWDG communication state */ }WWDG_HandleTypeDef; /** * @} */ /* Exported constants --------------------------------------------------------*/ /** @defgroup WWDG_Exported_Constants WWDG Exported Constants * @{ */ /** @defgroup WWDG_BitAddress_AliasRegion WWDG BitAddress AliasRegion * @brief WWDG registers bit address in the alias region * @{ */ /* --- CFR Register ---*/ /* Alias word address of EWI bit */ #define CFR_BASE (uint32_t)(WWDG_BASE + 0x04) /** * @} */ /** @defgroup WWDG_Interrupt_definition WWDG Interrupt definition * @{ */ #define WWDG_IT_EWI ((uint32_t)WWDG_CFR_EWI) /** * @} */ /** @defgroup WWDG_Flag_definition WWDG Flag definition * @brief WWDG Flag definition * @{ */ #define WWDG_FLAG_EWIF ((uint32_t)WWDG_SR_EWIF) /*!< Early wakeup interrupt flag */ /** * @} */ /** @defgroup WWDG_Prescaler WWDG Prescaler * @{ */ #define WWDG_PRESCALER_1 ((uint32_t)0x00000000) /*!< WWDG counter clock = (PCLK1/4096)/1 */ #define WWDG_PRESCALER_2 ((uint32_t)WWDG_CFR_WDGTB0) /*!< WWDG counter clock = (PCLK1/4096)/2 */ #define WWDG_PRESCALER_4 ((uint32_t)WWDG_CFR_WDGTB1) /*!< WWDG counter clock = (PCLK1/4096)/4 */ #define WWDG_PRESCALER_8 ((uint32_t)WWDG_CFR_WDGTB) /*!< WWDG counter clock = (PCLK1/4096)/8 */ #define IS_WWDG_PRESCALER(__PRESCALER__) (((__PRESCALER__) == WWDG_PRESCALER_1) || \ ((__PRESCALER__) == WWDG_PRESCALER_2) || \ ((__PRESCALER__) == WWDG_PRESCALER_4) || \ ((__PRESCALER__) == WWDG_PRESCALER_8)) /** * @} */ /** @defgroup WWDG_Window WWDG Window * @{ */ #define IS_WWDG_WINDOW(__WINDOW__) ((__WINDOW__) <= 0x7F) /** * @} */ /** @defgroup WWDG_Counter WWDG Counter * @{ */ #define IS_WWDG_COUNTER(__COUNTER__) (((__COUNTER__) >= 0x40) && ((__COUNTER__) <= 0x7F)) /** * @} */ /** * @} */ /* Exported macro ------------------------------------------------------------*/ /** @defgroup WWDG_Exported_Macros WWDG Exported Macros * @{ */ /** @brief Reset WWDG handle state * @param __HANDLE__: WWDG handle * @retval None */ #define __HAL_WWDG_RESET_HANDLE_STATE(__HANDLE__) ((__HANDLE__)->State = HAL_WWDG_STATE_RESET) /** * @brief Enables the WWDG peripheral. * @param __HANDLE__: WWDG handle * @retval None */ #define __HAL_WWDG_ENABLE(__HANDLE__) SET_BIT((__HANDLE__)->Instance->CR, WWDG_CR_WDGA) /** * @brief Gets the selected WWDG's flag status. * @param __HANDLE__: WWDG handle * @param __FLAG__: specifies the flag to check. * This parameter can be one of the following values: * @arg WWDG_FLAG_EWIF: Early wakeup interrupt flag * @retval The new state of WWDG_FLAG (SET or RESET). */ #define __HAL_WWDG_GET_FLAG(__HANDLE__, __FLAG__) (((__HANDLE__)->Instance->SR & (__FLAG__)) == (__FLAG__)) /** * @brief Clears the WWDG's pending flags. * @param __HANDLE__: WWDG handle * @param __FLAG__: specifies the flag to clear. * This parameter can be one of the following values: * @arg WWDG_FLAG_EWIF: Early wakeup interrupt flag * @retval None */ #define __HAL_WWDG_CLEAR_FLAG(__HANDLE__, __FLAG__) (((__HANDLE__)->Instance->SR) = ~(__FLAG__)) /** * @brief Enables the WWDG early wakeup interrupt. * @param __INTERRUPT__: specifies the interrupt to enable. * This parameter can be one of the following values: * @arg WWDG_IT_EWI: Early wakeup interrupt * @note Once enabled this interrupt cannot be disabled except by a system reset. * @retval None */ #define __HAL_WWDG_ENABLE_IT(__INTERRUPT__) (*(__IO uint32_t *) CFR_BASE |= (__INTERRUPT__)) /** @brief Clear the WWDG's interrupt pending bits * bits to clear the selected interrupt pending bits. * @param __HANDLE__: WWDG handle * @param __INTERRUPT__: specifies the interrupt pending bit to clear. * This parameter can be one of the following values: * @arg WWDG_FLAG_EWIF: Early wakeup interrupt flag */ #define __HAL_WWDG_CLEAR_IT(__HANDLE__, __INTERRUPT__) __HAL_WWDG_CLEAR_FLAG((__HANDLE__), (__INTERRUPT__)) /** * @} */ /* Exported functions --------------------------------------------------------*/ /** @addtogroup WWDG_Exported_Functions * @{ */ /** @addtogroup WWDG_Exported_Functions_Group1 * @{ */ /* Initialization/de-initialization functions **********************************/ HAL_StatusTypeDef HAL_WWDG_Init(WWDG_HandleTypeDef *hwwdg); HAL_StatusTypeDef HAL_WWDG_DeInit(WWDG_HandleTypeDef *hwwdg); void HAL_WWDG_MspInit(WWDG_HandleTypeDef *hwwdg); void HAL_WWDG_MspDeInit(WWDG_HandleTypeDef *hwwdg); void HAL_WWDG_WakeupCallback(WWDG_HandleTypeDef* hwwdg); /** * @} */ /** @addtogroup WWDG_Exported_Functions_Group2 * @{ */ /* I/O operation functions ******************************************************/ HAL_StatusTypeDef HAL_WWDG_Start(WWDG_HandleTypeDef *hwwdg); HAL_StatusTypeDef HAL_WWDG_Start_IT(WWDG_HandleTypeDef *hwwdg); HAL_StatusTypeDef HAL_WWDG_Refresh(WWDG_HandleTypeDef *hwwdg, uint32_t Counter); void HAL_WWDG_IRQHandler(WWDG_HandleTypeDef *hwwdg); /** * @} */ /** @addtogroup WWDG_Exported_Functions_Group3 * @{ */ /* Peripheral State functions **************************************************/ HAL_WWDG_StateTypeDef HAL_WWDG_GetState(WWDG_HandleTypeDef *hwwdg); /** * @} */ /** * @} */ /** * @} */ /** * @} */ #ifdef __cplusplus } #endif #endif /* __STM32L1xx_HAL_WWDG_H */ /************************ (C) COPYRIGHT STMicroelectronics *****END OF FILE****/ ================================================ FILE: Zelig/mbed/TARGET_NUCLEO_L152RE/stm32l1xx_ll_fsmc.h ================================================ /** ****************************************************************************** * @file stm32l1xx_ll_fsmc.h * @author MCD Application Team * @version V1.0.0 * @date 5-September-2014 * @brief Header file of FSMC HAL module. ****************************************************************************** * @attention * *

© COPYRIGHT(c) 2014 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. * ****************************************************************************** */ /* Define to prevent recursive inclusion -------------------------------------*/ #ifndef __STM32L1xx_LL_FSMC_H #define __STM32L1xx_LL_FSMC_H #ifdef __cplusplus extern "C" { #endif #if defined (STM32L151xD) || defined (STM32L152xD) || defined (STM32L162xD) /* Includes ------------------------------------------------------------------*/ #include "stm32l1xx_hal_def.h" /** @addtogroup STM32L1xx_HAL_Driver * @{ */ /** @addtogroup FSMC_LL * @{ */ /* Exported typedef ----------------------------------------------------------*/ /** @defgroup FSMC_NORSRAM_Exported_typedef FSMC NOR/SRAM Exported typedef * @{ */ #define FSMC_NORSRAM_TYPEDEF FSMC_Bank1_TypeDef #define FSMC_NORSRAM_EXTENDED_TYPEDEF FSMC_Bank1E_TypeDef #define FSMC_NORSRAM_DEVICE FSMC_Bank1 #define FSMC_NORSRAM_EXTENDED_DEVICE FSMC_Bank1E /** * @brief FSMC_NORSRAM Configuration Structure definition */ typedef struct { uint32_t NSBank; /*!< Specifies the NORSRAM memory device that will be used. This parameter can be a value of @ref FSMC_NORSRAM_Bank */ uint32_t DataAddressMux; /*!< Specifies whether the address and data values are multiplexed on the data bus or not. This parameter can be a value of @ref FSMC_Data_Address_Bus_Multiplexing */ uint32_t MemoryType; /*!< Specifies the type of external memory attached to the corresponding memory device. This parameter can be a value of @ref FSMC_Memory_Type */ uint32_t MemoryDataWidth; /*!< Specifies the external memory device width. This parameter can be a value of @ref FSMC_NORSRAM_Data_Width */ uint32_t BurstAccessMode; /*!< Enables or disables the burst access mode for Flash memory, valid only with synchronous burst Flash memories. This parameter can be a value of @ref FSMC_Burst_Access_Mode */ uint32_t WaitSignalPolarity; /*!< Specifies the wait signal polarity, valid only when accessing the Flash memory in burst mode. This parameter can be a value of @ref FSMC_Wait_Signal_Polarity */ uint32_t WrapMode; /*!< Enables or disables the Wrapped burst access mode for Flash memory, valid only when accessing Flash memories in burst mode. This parameter can be a value of @ref FSMC_Wrap_Mode */ uint32_t WaitSignalActive; /*!< Specifies if the wait signal is asserted by the memory one clock cycle before the wait state or during the wait state, valid only when accessing memories in burst mode. This parameter can be a value of @ref FSMC_Wait_Timing */ uint32_t WriteOperation; /*!< Enables or disables the write operation in the selected device by the FSMC. This parameter can be a value of @ref FSMC_Write_Operation */ uint32_t WaitSignal; /*!< Enables or disables the wait state insertion via wait signal, valid for Flash memory access in burst mode. This parameter can be a value of @ref FSMC_Wait_Signal */ uint32_t ExtendedMode; /*!< Enables or disables the extended mode. This parameter can be a value of @ref FSMC_Extended_Mode */ uint32_t AsynchronousWait; /*!< Enables or disables wait signal during asynchronous transfers, valid only with asynchronous Flash memories. This parameter can be a value of @ref FSMC_AsynchronousWait */ uint32_t WriteBurst; /*!< Enables or disables the write burst operation. This parameter can be a value of @ref FSMC_Write_Burst */ }FSMC_NORSRAM_InitTypeDef; /** * @brief FSMC_NORSRAM Timing parameters structure definition */ typedef struct { uint32_t AddressSetupTime; /*!< Defines the number of HCLK cycles to configure the duration of the address setup time. This parameter can be a value between Min_Data = 0 and Max_Data = 15. @note This parameter is not used with synchronous NOR Flash memories. */ uint32_t AddressHoldTime; /*!< Defines the number of HCLK cycles to configure the duration of the address hold time. This parameter can be a value between Min_Data = 1 and Max_Data = 15. @note This parameter is not used with synchronous NOR Flash memories. */ uint32_t DataSetupTime; /*!< Defines the number of HCLK cycles to configure the duration of the data setup time. This parameter can be a value between Min_Data = 1 and Max_Data = 255. @note This parameter is used for SRAMs, ROMs and asynchronous multiplexed NOR Flash memories. */ uint32_t BusTurnAroundDuration; /*!< Defines the number of HCLK cycles to configure the duration of the bus turnaround. This parameter can be a value between Min_Data = 0 and Max_Data = 15. @note This parameter is only used for multiplexed NOR Flash memories. */ uint32_t CLKDivision; /*!< Defines the period of CLK clock output signal, expressed in number of HCLK cycles. This parameter can be a value between Min_Data = 2 and Max_Data = 16. @note This parameter is not used for asynchronous NOR Flash, SRAM or ROM accesses. */ uint32_t DataLatency; /*!< Defines the number of memory clock cycles to issue to the memory before getting the first data. The parameter value depends on the memory type as shown below: - It must be set to 0 in case of a CRAM - It is don't care in asynchronous NOR, SRAM or ROM accesses - It may assume a value between Min_Data = 2 and Max_Data = 17 in NOR Flash memories with synchronous burst mode enable */ uint32_t AccessMode; /*!< Specifies the asynchronous access mode. This parameter can be a value of @ref FSMC_Access_Mode */ }FSMC_NORSRAM_TimingTypeDef; /** * @} */ /* Exported constants --------------------------------------------------------*/ /** @defgroup FSMC_NORSRAM_Exported_constants FSMC NOR/SRAM Exported constants * @{ */ /** @defgroup FSMC_NORSRAM_Bank FSMC NOR/SRAM Bank * @{ */ #define FSMC_BANK1_NORSRAM1 ((uint32_t)0x00000000) #define FSMC_BANK1_NORSRAM2 ((uint32_t)0x00000002) #define FSMC_BANK1_NORSRAM3 ((uint32_t)0x00000004) #define FSMC_BANK1_NORSRAM4 ((uint32_t)0x00000006) /* To keep compatibility with previous families */ #define FSMC_NORSRAM_BANK1 FSMC_BANK1_NORSRAM1 #define FSMC_NORSRAM_BANK2 FSMC_BANK1_NORSRAM2 #define FSMC_NORSRAM_BANK3 FSMC_BANK1_NORSRAM3 #define FSMC_NORSRAM_BANK4 FSMC_BANK1_NORSRAM4 #define IS_FSMC_NORSRAM_BANK(__BANK__) (((__BANK__) == FSMC_BANK1_NORSRAM1) || \ ((__BANK__) == FSMC_BANK1_NORSRAM2) || \ ((__BANK__) == FSMC_BANK1_NORSRAM3) || \ ((__BANK__) == FSMC_BANK1_NORSRAM4)) /** * @} */ /** @defgroup FSMC_Data_Address_Bus_Multiplexing FSMC Data Address Bus Multiplexing * @{ */ #define FSMC_DATA_ADDRESS_MUX_DISABLE ((uint32_t)0x00000000) #define FSMC_DATA_ADDRESS_MUX_ENABLE ((uint32_t)FSMC_BCRx_MUXEN) #define IS_FSMC_MUX(__MUX__) (((__MUX__) == FSMC_DATA_ADDRESS_MUX_DISABLE) || \ ((__MUX__) == FSMC_DATA_ADDRESS_MUX_ENABLE)) /** * @} */ /** @defgroup FSMC_Memory_Type FSMC Memory Type * @{ */ #define FSMC_MEMORY_TYPE_SRAM ((uint32_t)0x00000000) #define FSMC_MEMORY_TYPE_PSRAM ((uint32_t)FSMC_BCRx_MTYP_0) #define FSMC_MEMORY_TYPE_NOR ((uint32_t)FSMC_BCRx_MTYP_1) #define IS_FSMC_MEMORY(__MEMORY__) (((__MEMORY__) == FSMC_MEMORY_TYPE_SRAM) || \ ((__MEMORY__) == FSMC_MEMORY_TYPE_PSRAM)|| \ ((__MEMORY__) == FSMC_MEMORY_TYPE_NOR)) /** * @} */ /** @defgroup FSMC_NORSRAM_Data_Width FSMC NOR/SRAM Data Width * @{ */ #define FSMC_NORSRAM_MEM_BUS_WIDTH_8 ((uint32_t)0x00000000) #define FSMC_NORSRAM_MEM_BUS_WIDTH_16 ((uint32_t)FSMC_BCRx_MWID_0) #define FSMC_NORSRAM_MEM_BUS_WIDTH_32 ((uint32_t)FSMC_BCRx_MWID_1) #define IS_FSMC_NORSRAM_MEMORY_WIDTH(__WIDTH__) (((__WIDTH__) == FSMC_NORSRAM_MEM_BUS_WIDTH_8) || \ ((__WIDTH__) == FSMC_NORSRAM_MEM_BUS_WIDTH_16) || \ ((__WIDTH__) == FSMC_NORSRAM_MEM_BUS_WIDTH_32)) /** * @} */ /** @defgroup FSMC_NORSRAM_Flash_Access FSMC NOR/SRAM Flash Access * @{ */ #define FSMC_NORSRAM_FLASH_ACCESS_ENABLE ((uint32_t)FSMC_BCRx_FACCEN) #define FSMC_NORSRAM_FLASH_ACCESS_DISABLE ((uint32_t)0x00000000) /** * @} */ /** @defgroup FSMC_Burst_Access_Mode FSMC Burst Access Mode * @{ */ #define FSMC_BURST_ACCESS_MODE_DISABLE ((uint32_t)0x00000000) #define FSMC_BURST_ACCESS_MODE_ENABLE ((uint32_t)FSMC_BCRx_BURSTEN) #define IS_FSMC_BURSTMODE(__STATE__) (((__STATE__) == FSMC_BURST_ACCESS_MODE_DISABLE) || \ ((__STATE__) == FSMC_BURST_ACCESS_MODE_ENABLE)) /** * @} */ /** @defgroup FSMC_Wait_Signal_Polarity FSMC Wait Signal Polarity * @{ */ #define FSMC_WAIT_SIGNAL_POLARITY_LOW ((uint32_t)0x00000000) #define FSMC_WAIT_SIGNAL_POLARITY_HIGH ((uint32_t)FSMC_BCRx_WAITPOL) #define IS_FSMC_WAIT_POLARITY(__POLARITY__) (((__POLARITY__) == FSMC_WAIT_SIGNAL_POLARITY_LOW) || \ ((__POLARITY__) == FSMC_WAIT_SIGNAL_POLARITY_HIGH)) /** * @} */ /** @defgroup FSMC_Wrap_Mode FSMC Wrap Mode * @{ */ #define FSMC_WRAP_MODE_DISABLE ((uint32_t)0x00000000) #define FSMC_WRAP_MODE_ENABLE ((uint32_t)FSMC_BCRx_WRAPMOD) #define IS_FSMC_WRAP_MODE(__MODE__) (((__MODE__) == FSMC_WRAP_MODE_DISABLE) || \ ((__MODE__) == FSMC_WRAP_MODE_ENABLE)) /** * @} */ /** @defgroup FSMC_Wait_Timing FSMC Wait Timing * @{ */ #define FSMC_WAIT_TIMING_BEFORE_WS ((uint32_t)0x00000000) #define FSMC_WAIT_TIMING_DURING_WS ((uint32_t)FSMC_BCRx_WAITCFG) #define IS_FSMC_WAIT_SIGNAL_ACTIVE(__ACTIVE__) (((__ACTIVE__) == FSMC_WAIT_TIMING_BEFORE_WS) || \ ((__ACTIVE__) == FSMC_WAIT_TIMING_DURING_WS)) /** * @} */ /** @defgroup FSMC_Write_Operation FSMC Write Operation * @{ */ #define FSMC_WRITE_OPERATION_DISABLE ((uint32_t)0x00000000) #define FSMC_WRITE_OPERATION_ENABLE ((uint32_t)FSMC_BCRx_WREN) #define IS_FSMC_WRITE_OPERATION(__OPERATION__) (((__OPERATION__) == FSMC_WRITE_OPERATION_DISABLE) || \ ((__OPERATION__) == FSMC_WRITE_OPERATION_ENABLE)) /** * @} */ /** @defgroup FSMC_Wait_Signal FSMC Wait Signal * @{ */ #define FSMC_WAIT_SIGNAL_DISABLE ((uint32_t)0x00000000) #define FSMC_WAIT_SIGNAL_ENABLE ((uint32_t)FSMC_BCRx_WAITEN) #define IS_FSMC_WAITE_SIGNAL(__SIGNAL__) (((__SIGNAL__) == FSMC_WAIT_SIGNAL_DISABLE) || \ ((__SIGNAL__) == FSMC_WAIT_SIGNAL_ENABLE)) /** * @} */ /** @defgroup FSMC_Extended_Mode FSMC Extended Mode * @{ */ #define FSMC_EXTENDED_MODE_DISABLE ((uint32_t)0x00000000) #define FSMC_EXTENDED_MODE_ENABLE ((uint32_t)FSMC_BCRx_EXTMOD) #define IS_FSMC_EXTENDED_MODE(__MODE__) (((__MODE__) == FSMC_EXTENDED_MODE_DISABLE) || \ ((__MODE__) == FSMC_EXTENDED_MODE_ENABLE)) /** * @} */ /** @defgroup FSMC_AsynchronousWait FSMC Asynchronous Wait * @{ */ #define FSMC_ASYNCHRONOUS_WAIT_DISABLE ((uint32_t)0x00000000) #define FSMC_ASYNCHRONOUS_WAIT_ENABLE ((uint32_t)FSMC_BCRx_ASYNCWAIT) #define IS_FSMC_ASYNWAIT(__STATE__) (((__STATE__) == FSMC_ASYNCHRONOUS_WAIT_DISABLE) || \ ((__STATE__) == FSMC_ASYNCHRONOUS_WAIT_ENABLE)) /** * @} */ /** @defgroup FSMC_Write_Burst FSMC Write Burst * @{ */ #define FSMC_WRITE_BURST_DISABLE ((uint32_t)0x00000000) #define FSMC_WRITE_BURST_ENABLE ((uint32_t)FSMC_BCRx_CBURSTRW) #define IS_FSMC_WRITE_BURST(__BURST__) (((__BURST__) == FSMC_WRITE_BURST_DISABLE) || \ ((__BURST__) == FSMC_WRITE_BURST_ENABLE)) /** * @} */ /** @defgroup FSMC_Address_Setup_Time FSMC Address Setup Time * @{ */ #define IS_FSMC_ADDRESS_SETUP_TIME(__TIME__) ((__TIME__) <= 15) /** * @} */ /** @defgroup FSMC_Address_Hold_Time FSMC Address Hold Time * @{ */ #define IS_FSMC_ADDRESS_HOLD_TIME(__TIME__) (((__TIME__) > 0) && ((__TIME__) <= 15)) /** * @} */ /** @defgroup FSMC_Data_Setup_Time FSMC Data Setup Time * @{ */ #define IS_FSMC_DATASETUP_TIME(__TIME__) (((__TIME__) > 0) && ((__TIME__) <= 255)) /** * @} */ /** @defgroup FSMC_Bus_Turn_around_Duration FSMC Bus Turn around Duration * @{ */ #define IS_FSMC_TURNAROUND_TIME(__TIME__) ((__TIME__) <= 15) /** * @} */ /** @defgroup FSMC_CLK_Division FSMC CLK Division * @{ */ #define FSMC_CLK_DIV2 ((uint32_t)0x00000002) #define FSMC_CLK_DIV3 ((uint32_t)0x00000003) #define FSMC_CLK_DIV4 ((uint32_t)0x00000004) #define FSMC_CLK_DIV5 ((uint32_t)0x00000005) #define FSMC_CLK_DIV6 ((uint32_t)0x00000006) #define FSMC_CLK_DIV7 ((uint32_t)0x00000007) #define FSMC_CLK_DIV8 ((uint32_t)0x00000008) #define FSMC_CLK_DIV9 ((uint32_t)0x00000009) #define FSMC_CLK_DIV10 ((uint32_t)0x0000000A) #define FSMC_CLK_DIV11 ((uint32_t)0x0000000B) #define FSMC_CLK_DIV12 ((uint32_t)0x0000000C) #define FSMC_CLK_DIV13 ((uint32_t)0x0000000D) #define FSMC_CLK_DIV14 ((uint32_t)0x0000000E) #define FSMC_CLK_DIV15 ((uint32_t)0x0000000F) #define FSMC_CLK_DIV16 ((uint32_t)0x00000010) #define IS_FSMC_CLK_DIV(__DIV__) (((__DIV__) > 1) && ((__DIV__) <= 16)) /** * @} */ /** @defgroup FSMC_Data_Latency FSMC Data Latency * @{ */ #define IS_FSMC_DATA_LATENCY(__LATENCY__) (((__LATENCY__) > 1) && ((__LATENCY__) <= 17)) /** * @} */ /** @defgroup FSMC_Access_Mode FSMC Access Mode * @{ */ #define FSMC_ACCESS_MODE_A ((uint32_t)0x00000000) #define FSMC_ACCESS_MODE_B ((uint32_t)FSMC_BTRx_ACCMOD_0) #define FSMC_ACCESS_MODE_C ((uint32_t)FSMC_BTRx_ACCMOD_1) #define FSMC_ACCESS_MODE_D ((uint32_t)(FSMC_BTRx_ACCMOD_0 | FSMC_BTRx_ACCMOD_1)) #define IS_FSMC_ACCESS_MODE(__MODE__) (((__MODE__) == FSMC_ACCESS_MODE_A) || \ ((__MODE__) == FSMC_ACCESS_MODE_B) || \ ((__MODE__) == FSMC_ACCESS_MODE_C) || \ ((__MODE__) == FSMC_ACCESS_MODE_D)) /** * @} */ /** @defgroup FSMC_NORSRAM_Device_Instance FSMC NOR/SRAM Device Instance * @{ */ #define IS_FSMC_NORSRAM_DEVICE(__INSTANCE__) ((__INSTANCE__) == FSMC_NORSRAM_DEVICE) /** * @} */ /** @defgroup FSMC_NORSRAM_EXTENDED_Device_Instance FSMC NOR/SRAM EXTENDED Device Instance * @{ */ #define IS_FSMC_NORSRAM_EXTENDED_DEVICE(__INSTANCE__) ((__INSTANCE__) == FSMC_NORSRAM_EXTENDED_DEVICE) /** * @} */ /** * @} */ /* Exported macro ------------------------------------------------------------*/ /** @defgroup FSMC_NOR_Macros FSMC NOR/SRAM Exported Macros * @brief macros to handle NOR device enable/disable and read/write operations * @{ */ /** * @brief Enable the NORSRAM device access. * @param __INSTANCE__: FSMC_NORSRAM Instance * @param __BANK__: FSMC_NORSRAM Bank * @retval none */ #define __FSMC_NORSRAM_ENABLE(__INSTANCE__, __BANK__) ((__INSTANCE__)->BTCR[(__BANK__)] |= FSMC_BCRx_MBKEN) /** * @brief Disable the NORSRAM device access. * @param __INSTANCE__: FSMC_NORSRAM Instance * @param __BANK__: FSMC_NORSRAM Bank * @retval none */ #define __FSMC_NORSRAM_DISABLE(__INSTANCE__, __BANK__) ((__INSTANCE__)->BTCR[(__BANK__)] &= ~FSMC_BCRx_MBKEN) /** * @} */ /* Exported functions --------------------------------------------------------*/ /** @addtogroup FSMC_Exported_Functions * @{ */ /** @addtogroup HAL_FSMC_NORSRAM_Group1 * @{ */ /* FSMC_NORSRAM Controller functions ******************************************/ /* Initialization/de-initialization functions */ HAL_StatusTypeDef FSMC_NORSRAM_Init(FSMC_NORSRAM_TYPEDEF *Device, FSMC_NORSRAM_InitTypeDef *Init); HAL_StatusTypeDef FSMC_NORSRAM_Timing_Init(FSMC_NORSRAM_TYPEDEF *Device, FSMC_NORSRAM_TimingTypeDef *Timing, uint32_t Bank); HAL_StatusTypeDef FSMC_NORSRAM_Extended_Timing_Init(FSMC_NORSRAM_EXTENDED_TYPEDEF *Device, FSMC_NORSRAM_TimingTypeDef *Timing, uint32_t Bank, uint32_t ExtendedMode); HAL_StatusTypeDef FSMC_NORSRAM_DeInit(FSMC_NORSRAM_TYPEDEF *Device, FSMC_NORSRAM_EXTENDED_TYPEDEF *ExDevice, uint32_t Bank); /** * @} */ /** @addtogroup HAL_FSMC_NORSRAM_Group2 * @{ */ /* FSMC_NORSRAM Control functions */ HAL_StatusTypeDef FSMC_NORSRAM_WriteOperation_Enable(FSMC_NORSRAM_TYPEDEF *Device, uint32_t Bank); HAL_StatusTypeDef FSMC_NORSRAM_WriteOperation_Disable(FSMC_NORSRAM_TYPEDEF *Device, uint32_t Bank); /** * @} */ #endif /* STM32L151xD || STM32L152xD || STM32L162xD */ /** * @} */ /** * @} */ /** * @} */ #ifdef __cplusplus } #endif #endif /* __STM32L1xx_LL_FSMC_H */ /************************ (C) COPYRIGHT STMicroelectronics *****END OF FILE****/ ================================================ FILE: Zelig/mbed/TARGET_NUCLEO_L152RE/stm32l1xx_ll_sdmmc.h ================================================ /** ****************************************************************************** * @file stm32l1xx_ll_sdmmc.h * @author MCD Application Team * @version V1.0.0 * @date 5-September-2014 * @brief Header file of low layer SDMMC HAL module. ****************************************************************************** * @attention * *

© COPYRIGHT(c) 2014 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. * ****************************************************************************** */ /* Define to prevent recursive inclusion -------------------------------------*/ #ifndef __STM32L1xx_LL_SD_H #define __STM32L1xx_LL_SD_H #if defined(STM32L151xD) || defined(STM32L152xD) || defined(STM32L162xD) #ifdef __cplusplus extern "C" { #endif /* Includes ------------------------------------------------------------------*/ #include "stm32l1xx_hal_def.h" /** @addtogroup STM32L1xx_HAL_Driver * @{ */ /** @addtogroup SDMMC_LL * @{ */ /* Exported types ------------------------------------------------------------*/ /** @defgroup SDMMC_LL_Exported_Types SDMMC_LL Exported Types * @{ */ /** * @brief SDMMC Configuration Structure definition */ typedef struct { uint32_t ClockEdge; /*!< Specifies the clock transition on which the bit capture is made. This parameter can be a value of @ref SDMMC_LL_Clock_Edge */ uint32_t ClockBypass; /*!< Specifies whether the SDIO Clock divider bypass is enabled or disabled. This parameter can be a value of @ref SDMMC_LL_Clock_Bypass */ uint32_t ClockPowerSave; /*!< Specifies whether SDIO Clock output is enabled or disabled when the bus is idle. This parameter can be a value of @ref SDMMC_LL_Clock_Power_Save */ uint32_t BusWide; /*!< Specifies the SDIO bus width. This parameter can be a value of @ref SDMMC_LL_Bus_Wide */ uint32_t HardwareFlowControl; /*!< Specifies whether the SDIO hardware flow control is enabled or disabled. This parameter can be a value of @ref SDMMC_LL_Hardware_Flow_Control */ uint32_t ClockDiv; /*!< Specifies the clock frequency of the SDIO controller. This parameter can be a value between Min_Data = 0 and Max_Data = 255 */ }SDIO_InitTypeDef; /** * @brief SDIO Command Control structure */ typedef struct { uint32_t Argument; /*!< Specifies the SDIO command argument which is sent to a card as part of a command message. If a command contains an argument, it must be loaded into this register before writing the command to the command register. */ uint32_t CmdIndex; /*!< Specifies the SDIO command index. It must be Min_Data = 0 and Max_Data = 64 */ uint32_t Response; /*!< Specifies the SDIO response type. This parameter can be a value of @ref SDMMC_LL_Response_Type */ uint32_t WaitForInterrupt; /*!< Specifies whether SDIO wait for interrupt request is enabled or disabled. This parameter can be a value of @ref SDMMC_LL_Wait_Interrupt_State */ uint32_t CPSM; /*!< Specifies whether SDIO Command path state machine (CPSM) is enabled or disabled. This parameter can be a value of @ref SDMMC_LL_CPSM_State */ }SDIO_CmdInitTypeDef; /** * @brief SDIO Data Control structure */ typedef struct { uint32_t DataTimeOut; /*!< Specifies the data timeout period in card bus clock periods. */ uint32_t DataLength; /*!< Specifies the number of data bytes to be transferred. */ uint32_t DataBlockSize; /*!< Specifies the data block size for block transfer. This parameter can be a value of @ref SDMMC_LL_Data_Block_Size */ uint32_t TransferDir; /*!< Specifies the data transfer direction, whether the transfer is a read or write. This parameter can be a value of @ref SDMMC_LL_Transfer_Direction */ uint32_t TransferMode; /*!< Specifies whether data transfer is in stream or block mode. This parameter can be a value of @ref SDMMC_LL_Transfer_Type */ uint32_t DPSM; /*!< Specifies whether SDIO Data path state machine (DPSM) is enabled or disabled. This parameter can be a value of @ref SDMMC_LL_DPSM_State */ }SDIO_DataInitTypeDef; /** * @} */ /* Exported constants --------------------------------------------------------*/ /** @defgroup SDMMC_LL_Exported_Constants SDMMC_LL Exported Constants * @{ */ /** @defgroup SDMMC_LL_Clock_Edge Clock Edge * @{ */ #define SDIO_CLOCK_EDGE_RISING ((uint32_t)0x00000000) #define SDIO_CLOCK_EDGE_FALLING SDIO_CLKCR_NEGEDGE #define IS_SDIO_CLOCK_EDGE(EDGE) (((EDGE) == SDIO_CLOCK_EDGE_RISING) || \ ((EDGE) == SDIO_CLOCK_EDGE_FALLING)) /** * @} */ /** @defgroup SDMMC_LL_Clock_Bypass Clock Bypass * @{ */ #define SDIO_CLOCK_BYPASS_DISABLE ((uint32_t)0x00000000) #define SDIO_CLOCK_BYPASS_ENABLE SDIO_CLKCR_BYPASS #define IS_SDIO_CLOCK_BYPASS(BYPASS) (((BYPASS) == SDIO_CLOCK_BYPASS_DISABLE) || \ ((BYPASS) == SDIO_CLOCK_BYPASS_ENABLE)) /** * @} */ /** @defgroup SDMMC_LL_Clock_Power_Save Clock Power Saving * @{ */ #define SDIO_CLOCK_POWER_SAVE_DISABLE ((uint32_t)0x00000000) #define SDIO_CLOCK_POWER_SAVE_ENABLE SDIO_CLKCR_PWRSAV #define IS_SDIO_CLOCK_POWER_SAVE(SAVE) (((SAVE) == SDIO_CLOCK_POWER_SAVE_DISABLE) || \ ((SAVE) == SDIO_CLOCK_POWER_SAVE_ENABLE)) /** * @} */ /** @defgroup SDMMC_LL_Bus_Wide Bus Width * @{ */ #define SDIO_BUS_WIDE_1B ((uint32_t)0x00000000) #define SDIO_BUS_WIDE_4B SDIO_CLKCR_WIDBUS_0 #define SDIO_BUS_WIDE_8B SDIO_CLKCR_WIDBUS_1 #define IS_SDIO_BUS_WIDE(WIDE) (((WIDE) == SDIO_BUS_WIDE_1B) || \ ((WIDE) == SDIO_BUS_WIDE_4B) || \ ((WIDE) == SDIO_BUS_WIDE_8B)) /** * @} */ /** @defgroup SDMMC_LL_Hardware_Flow_Control Hardware Flow Control * @{ */ #define SDIO_HARDWARE_FLOW_CONTROL_DISABLE ((uint32_t)0x00000000) #define SDIO_HARDWARE_FLOW_CONTROL_ENABLE SDIO_CLKCR_HWFC_EN #define IS_SDIO_HARDWARE_FLOW_CONTROL(CONTROL) (((CONTROL) == SDIO_HARDWARE_FLOW_CONTROL_DISABLE) || \ ((CONTROL) == SDIO_HARDWARE_FLOW_CONTROL_ENABLE)) /** * @} */ /** @defgroup SDMMC_LL_Clock_Division Clock Division * @{ */ #define IS_SDIO_CLKDIV(DIV) ((DIV) <= 0xFF) /** * @} */ /** @defgroup SDMMC_LL_Command_Index Command Index * @{ */ #define IS_SDIO_CMD_INDEX(INDEX) ((INDEX) < 0x40) /** * @} */ /** @defgroup SDMMC_LL_Response_Type Response Type * @{ */ #define SDIO_RESPONSE_NO ((uint32_t)0x00000000) #define SDIO_RESPONSE_SHORT SDIO_CMD_WAITRESP_0 #define SDIO_RESPONSE_LONG SDIO_CMD_WAITRESP #define IS_SDIO_RESPONSE(RESPONSE) (((RESPONSE) == SDIO_RESPONSE_NO) || \ ((RESPONSE) == SDIO_RESPONSE_SHORT) || \ ((RESPONSE) == SDIO_RESPONSE_LONG)) /** * @} */ /** @defgroup SDMMC_LL_Wait_Interrupt_State Wait Interrupt * @{ */ #define SDIO_WAIT_NO ((uint32_t)0x00000000) #define SDIO_WAIT_IT SDIO_CMD_WAITINT #define SDIO_WAIT_PEND SDIO_CMD_WAITPEND #define IS_SDIO_WAIT(WAIT) (((WAIT) == SDIO_WAIT_NO) || \ ((WAIT) == SDIO_WAIT_IT) || \ ((WAIT) == SDIO_WAIT_PEND)) /** * @} */ /** @defgroup SDMMC_LL_CPSM_State CPSM State * @{ */ #define SDIO_CPSM_DISABLE ((uint32_t)0x00000000) #define SDIO_CPSM_ENABLE SDIO_CMD_CPSMEN #define IS_SDIO_CPSM(CPSM) (((CPSM) == SDIO_CPSM_DISABLE) || \ ((CPSM) == SDIO_CPSM_ENABLE)) /** * @} */ /** @defgroup SDMMC_LL_Response_Registers Response Register * @{ */ #define SDIO_RESP1 ((uint32_t)0x00000000) #define SDIO_RESP2 ((uint32_t)0x00000004) #define SDIO_RESP3 ((uint32_t)0x00000008) #define SDIO_RESP4 ((uint32_t)0x0000000C) #define IS_SDIO_RESP(RESP) (((RESP) == SDIO_RESP1) || \ ((RESP) == SDIO_RESP2) || \ ((RESP) == SDIO_RESP3) || \ ((RESP) == SDIO_RESP4)) /** * @} */ /** @defgroup SDMMC_LL_Data_Length Data Lenght * @{ */ #define IS_SDIO_DATA_LENGTH(LENGTH) ((LENGTH) <= 0x01FFFFFF) /** * @} */ /** @defgroup SDMMC_LL_Data_Block_Size Data Block Size * @{ */ #define SDIO_DATABLOCK_SIZE_1B ((uint32_t)0x00000000) #define SDIO_DATABLOCK_SIZE_2B SDIO_DCTRL_DBLOCKSIZE_0 #define SDIO_DATABLOCK_SIZE_4B SDIO_DCTRL_DBLOCKSIZE_1 #define SDIO_DATABLOCK_SIZE_8B ((uint32_t)0x00000030) #define SDIO_DATABLOCK_SIZE_16B SDIO_DCTRL_DBLOCKSIZE_2 #define SDIO_DATABLOCK_SIZE_32B ((uint32_t)0x00000050) #define SDIO_DATABLOCK_SIZE_64B ((uint32_t)0x00000060) #define SDIO_DATABLOCK_SIZE_128B ((uint32_t)0x00000070) #define SDIO_DATABLOCK_SIZE_256B SDIO_DCTRL_DBLOCKSIZE_3 #define SDIO_DATABLOCK_SIZE_512B ((uint32_t)0x00000090) #define SDIO_DATABLOCK_SIZE_1024B ((uint32_t)0x000000A0) #define SDIO_DATABLOCK_SIZE_2048B ((uint32_t)0x000000B0) #define SDIO_DATABLOCK_SIZE_4096B ((uint32_t)0x000000C0) #define SDIO_DATABLOCK_SIZE_8192B ((uint32_t)0x000000D0) #define SDIO_DATABLOCK_SIZE_16384B ((uint32_t)0x000000E0) #define IS_SDIO_BLOCK_SIZE(SIZE) (((SIZE) == SDIO_DATABLOCK_SIZE_1B) || \ ((SIZE) == SDIO_DATABLOCK_SIZE_2B) || \ ((SIZE) == SDIO_DATABLOCK_SIZE_4B) || \ ((SIZE) == SDIO_DATABLOCK_SIZE_8B) || \ ((SIZE) == SDIO_DATABLOCK_SIZE_16B) || \ ((SIZE) == SDIO_DATABLOCK_SIZE_32B) || \ ((SIZE) == SDIO_DATABLOCK_SIZE_64B) || \ ((SIZE) == SDIO_DATABLOCK_SIZE_128B) || \ ((SIZE) == SDIO_DATABLOCK_SIZE_256B) || \ ((SIZE) == SDIO_DATABLOCK_SIZE_512B) || \ ((SIZE) == SDIO_DATABLOCK_SIZE_1024B) || \ ((SIZE) == SDIO_DATABLOCK_SIZE_2048B) || \ ((SIZE) == SDIO_DATABLOCK_SIZE_4096B) || \ ((SIZE) == SDIO_DATABLOCK_SIZE_8192B) || \ ((SIZE) == SDIO_DATABLOCK_SIZE_16384B)) /** * @} */ /** @defgroup SDMMC_LL_Transfer_Direction Transfer Direction * @{ */ #define SDIO_TRANSFER_DIR_TO_CARD ((uint32_t)0x00000000) #define SDIO_TRANSFER_DIR_TO_SDIO SDIO_DCTRL_DTDIR #define IS_SDIO_TRANSFER_DIR(DIR) (((DIR) == SDIO_TRANSFER_DIR_TO_CARD) || \ ((DIR) == SDIO_TRANSFER_DIR_TO_SDIO)) /** * @} */ /** @defgroup SDMMC_LL_Transfer_Type Transfer Type * @{ */ #define SDIO_TRANSFER_MODE_BLOCK ((uint32_t)0x00000000) #define SDIO_TRANSFER_MODE_STREAM SDIO_DCTRL_DTMODE #define IS_SDIO_TRANSFER_MODE(MODE) (((MODE) == SDIO_TRANSFER_MODE_BLOCK) || \ ((MODE) == SDIO_TRANSFER_MODE_STREAM)) /** * @} */ /** @defgroup SDMMC_LL_DPSM_State DPSM State * @{ */ #define SDIO_DPSM_DISABLE ((uint32_t)0x00000000) #define SDIO_DPSM_ENABLE SDIO_DCTRL_DTEN #define IS_SDIO_DPSM(DPSM) (((DPSM) == SDIO_DPSM_DISABLE) ||\ ((DPSM) == SDIO_DPSM_ENABLE)) /** * @} */ /** @defgroup SDMMC_LL_Read_Wait_Mode Read Wait Mode * @{ */ #define SDIO_READ_WAIT_MODE_CLK ((uint32_t)0x00000000) #define SDIO_READ_WAIT_MODE_DATA2 ((uint32_t)0x00000001) #define IS_SDIO_READWAIT_MODE(MODE) (((MODE) == SDIO_READ_WAIT_MODE_CLK) || \ ((MODE) == SDIO_READ_WAIT_MODE_DATA2)) /** * @} */ /** @defgroup SDMMC_LL_Interrupt_sources Interrupt Sources * @{ */ #define SDIO_IT_CCRCFAIL SDIO_STA_CCRCFAIL #define SDIO_IT_DCRCFAIL SDIO_STA_DCRCFAIL #define SDIO_IT_CTIMEOUT SDIO_STA_CTIMEOUT #define SDIO_IT_DTIMEOUT SDIO_STA_DTIMEOUT #define SDIO_IT_TXUNDERR SDIO_STA_TXUNDERR #define SDIO_IT_RXOVERR SDIO_STA_RXOVERR #define SDIO_IT_CMDREND SDIO_STA_CMDREND #define SDIO_IT_CMDSENT SDIO_STA_CMDSENT #define SDIO_IT_DATAEND SDIO_STA_DATAEND #define SDIO_IT_STBITERR SDIO_STA_STBITERR #define SDIO_IT_DBCKEND SDIO_STA_DBCKEND #define SDIO_IT_CMDACT SDIO_STA_CMDACT #define SDIO_IT_TXACT SDIO_STA_TXACT #define SDIO_IT_RXACT SDIO_STA_RXACT #define SDIO_IT_TXFIFOHE SDIO_STA_TXFIFOHE #define SDIO_IT_RXFIFOHF SDIO_STA_RXFIFOHF #define SDIO_IT_TXFIFOF SDIO_STA_TXFIFOF #define SDIO_IT_RXFIFOF SDIO_STA_RXFIFOF #define SDIO_IT_TXFIFOE SDIO_STA_TXFIFOE #define SDIO_IT_RXFIFOE SDIO_STA_RXFIFOE #define SDIO_IT_TXDAVL SDIO_STA_TXDAVL #define SDIO_IT_RXDAVL SDIO_STA_RXDAVL #define SDIO_IT_SDIOIT SDIO_STA_SDIOIT #define SDIO_IT_CEATAEND SDIO_STA_CEATAEND /** * @} */ /** @defgroup SDMMC_LL_Flags Flags * @{ */ #define SDIO_FLAG_CCRCFAIL SDIO_STA_CCRCFAIL #define SDIO_FLAG_DCRCFAIL SDIO_STA_DCRCFAIL #define SDIO_FLAG_CTIMEOUT SDIO_STA_CTIMEOUT #define SDIO_FLAG_DTIMEOUT SDIO_STA_DTIMEOUT #define SDIO_FLAG_TXUNDERR SDIO_STA_TXUNDERR #define SDIO_FLAG_RXOVERR SDIO_STA_RXOVERR #define SDIO_FLAG_CMDREND SDIO_STA_CMDREND #define SDIO_FLAG_CMDSENT SDIO_STA_CMDSENT #define SDIO_FLAG_DATAEND SDIO_STA_DATAEND #define SDIO_FLAG_STBITERR SDIO_STA_STBITERR #define SDIO_FLAG_DBCKEND SDIO_STA_DBCKEND #define SDIO_FLAG_CMDACT SDIO_STA_CMDACT #define SDIO_FLAG_TXACT SDIO_STA_TXACT #define SDIO_FLAG_RXACT SDIO_STA_RXACT #define SDIO_FLAG_TXFIFOHE SDIO_STA_TXFIFOHE #define SDIO_FLAG_RXFIFOHF SDIO_STA_RXFIFOHF #define SDIO_FLAG_TXFIFOF SDIO_STA_TXFIFOF #define SDIO_FLAG_RXFIFOF SDIO_STA_RXFIFOF #define SDIO_FLAG_TXFIFOE SDIO_STA_TXFIFOE #define SDIO_FLAG_RXFIFOE SDIO_STA_RXFIFOE #define SDIO_FLAG_TXDAVL SDIO_STA_TXDAVL #define SDIO_FLAG_RXDAVL SDIO_STA_RXDAVL #define SDIO_FLAG_SDIOIT SDIO_STA_SDIOIT #define SDIO_FLAG_CEATAEND SDIO_STA_CEATAEND /** * @} */ /** * @} */ /* Exported macro ------------------------------------------------------------*/ /** @defgroup SDMMC_LL_Exported_macros SDMMC_LL Exported Macros * @{ */ /** @defgroup SDMMC_LL_Register Bits And Addresses Definitions * @brief SDMMC_LL registers bit address in the alias region * @{ */ /* ------------ SDIO registers bit address in the alias region -------------- */ #define SDIO_OFFSET (SDIO_BASE - PERIPH_BASE) /* --- CLKCR Register ---*/ /* Alias word address of CLKEN bit */ #define CLKCR_OFFSET (SDIO_OFFSET + 0x04) #define CLKEN_BITNUMBER 0x08 #define CLKCR_CLKEN_BB (PERIPH_BB_BASE + (CLKCR_OFFSET * 32) + (CLKEN_BITNUMBER * 4)) /* --- CMD Register ---*/ /* Alias word address of SDIOSUSPEND bit */ #define CMD_OFFSET (SDIO_OFFSET + 0x0C) #define SDIOSUSPEND_BITNUMBER 0x0B #define CMD_SDIOSUSPEND_BB (PERIPH_BB_BASE + (CMD_OFFSET * 32) + (SDIOSUSPEND_BITNUMBER * 4)) /* Alias word address of ENCMDCOMPL bit */ #define ENCMDCOMPL_BITNUMBER 0x0C #define CMD_ENCMDCOMPL_BB (PERIPH_BB_BASE + (CMD_OFFSET * 32) + (ENCMDCOMPL_BITNUMBER * 4)) /* Alias word address of NIEN bit */ #define NIEN_BITNUMBER 0x0D #define CMD_NIEN_BB (PERIPH_BB_BASE + (CMD_OFFSET * 32) + (NIEN_BITNUMBER * 4)) /* Alias word address of ATACMD bit */ #define ATACMD_BITNUMBER 0x0E #define CMD_ATACMD_BB (PERIPH_BB_BASE + (CMD_OFFSET * 32) + (ATACMD_BITNUMBER * 4)) /* --- DCTRL Register ---*/ /* Alias word address of DMAEN bit */ #define DCTRL_OFFSET (SDIO_OFFSET + 0x2C) #define DMAEN_BITNUMBER 0x03 #define DCTRL_DMAEN_BB (PERIPH_BB_BASE + (DCTRL_OFFSET * 32) + (DMAEN_BITNUMBER * 4)) /* Alias word address of RWSTART bit */ #define RWSTART_BITNUMBER 0x08 #define DCTRL_RWSTART_BB (PERIPH_BB_BASE + (DCTRL_OFFSET * 32) + (RWSTART_BITNUMBER * 4)) /* Alias word address of RWSTOP bit */ #define RWSTOP_BITNUMBER 0x09 #define DCTRL_RWSTOP_BB (PERIPH_BB_BASE + (DCTRL_OFFSET * 32) + (RWSTOP_BITNUMBER * 4)) /* Alias word address of RWMOD bit */ #define RWMOD_BITNUMBER 0x0A #define DCTRL_RWMOD_BB (PERIPH_BB_BASE + (DCTRL_OFFSET * 32) + (RWMOD_BITNUMBER * 4)) /* Alias word address of SDIOEN bit */ #define SDIOEN_BITNUMBER 0x0B #define DCTRL_SDIOEN_BB (PERIPH_BB_BASE + (DCTRL_OFFSET * 32) + (SDIOEN_BITNUMBER * 4)) /* ---------------------- SDIO registers bit mask --------------------------- */ /* --- CLKCR Register ---*/ /* CLKCR register clear mask */ #define CLKCR_CLEAR_MASK ((uint32_t)(SDIO_CLKCR_CLKDIV | SDIO_CLKCR_PWRSAV |\ SDIO_CLKCR_BYPASS | SDIO_CLKCR_WIDBUS |\ SDIO_CLKCR_NEGEDGE | SDIO_CLKCR_HWFC_EN)) /* --- DCTRL Register ---*/ /* SDIO DCTRL Clear Mask */ #define DCTRL_CLEAR_MASK ((uint32_t)(SDIO_DCTRL_DTEN | SDIO_DCTRL_DTDIR |\ SDIO_DCTRL_DTMODE | SDIO_DCTRL_DBLOCKSIZE)) /* --- CMD Register ---*/ /* CMD Register clear mask */ #define CMD_CLEAR_MASK ((uint32_t)(SDIO_CMD_CMDINDEX | SDIO_CMD_WAITRESP |\ SDIO_CMD_WAITINT | SDIO_CMD_WAITPEND |\ SDIO_CMD_CPSMEN | SDIO_CMD_SDIOSUSPEND)) /* SDIO RESP Registers Address */ #define SDIO_RESP_ADDR ((uint32_t)(SDIO_BASE + 0x14)) /* SDIO Intialization Frequency (400KHz max) */ #define SDIO_INIT_CLK_DIV ((uint8_t)0x76) /* SDIO Data Transfer Frequency */ #define SDIO_TRANSFER_CLK_DIV ((uint8_t)0x4) /** * @} */ /** @defgroup SDMMC_LL_Interrupt_Clock Interrupt And Clock Configuration * @brief macros to handle interrupts and specific clock configurations * @{ */ /** * @brief Enable the SDIO device. * @retval None */ #define __SDIO_ENABLE() (*(__IO uint32_t *)CLKCR_CLKEN_BB = ENABLE) /** * @brief Disable the SDIO device. * @retval None */ #define __SDIO_DISABLE() (*(__IO uint32_t *)CLKCR_CLKEN_BB = DISABLE) /** * @brief Enable the SDIO DMA transfer. * @retval None */ #define __SDIO_DMA_ENABLE() (*(__IO uint32_t *)DCTRL_DMAEN_BB = ENABLE) /** * @brief Disable the SDIO DMA transfer. * @retval None */ #define __SDIO_DMA_DISABLE() (*(__IO uint32_t *)DCTRL_DMAEN_BB = DISABLE) /** * @brief Enable the SDIO device interrupt. * @param __INSTANCE__ : Pointer to SDIO register base * @param __INTERRUPT__ : specifies the SDIO interrupt sources to be enabled. * This parameter can be one or a combination of the following values: * @arg SDIO_IT_CCRCFAIL: Command response received (CRC check failed) interrupt * @arg SDIO_IT_DCRCFAIL: Data block sent/received (CRC check failed) interrupt * @arg SDIO_IT_CTIMEOUT: Command response timeout interrupt * @arg SDIO_IT_DTIMEOUT: Data timeout interrupt * @arg SDIO_IT_TXUNDERR: Transmit FIFO underrun error interrupt * @arg SDIO_IT_RXOVERR: Received FIFO overrun error interrupt * @arg SDIO_IT_CMDREND: Command response received (CRC check passed) interrupt * @arg SDIO_IT_CMDSENT: Command sent (no response required) interrupt * @arg SDIO_IT_DATAEND: Data end (data counter, SDIDCOUNT, is zero) interrupt * @arg SDIO_IT_STBITERR: Start bit not detected on all data signals in wide * bus mode interrupt * @arg SDIO_IT_DBCKEND: Data block sent/received (CRC check passed) interrupt * @arg SDIO_IT_CMDACT: Command transfer in progress interrupt * @arg SDIO_IT_TXACT: Data transmit in progress interrupt * @arg SDIO_IT_RXACT: Data receive in progress interrupt * @arg SDIO_IT_TXFIFOHE: Transmit FIFO Half Empty interrupt * @arg SDIO_IT_RXFIFOHF: Receive FIFO Half Full interrupt * @arg SDIO_IT_TXFIFOF: Transmit FIFO full interrupt * @arg SDIO_IT_RXFIFOF: Receive FIFO full interrupt * @arg SDIO_IT_TXFIFOE: Transmit FIFO empty interrupt * @arg SDIO_IT_RXFIFOE: Receive FIFO empty interrupt * @arg SDIO_IT_TXDAVL: Data available in transmit FIFO interrupt * @arg SDIO_IT_RXDAVL: Data available in receive FIFO interrupt * @arg SDIO_IT_SDIOIT: SD I/O interrupt received interrupt * @arg SDIO_IT_CEATAEND: CE-ATA command completion signal received for CMD61 interrupt * @retval None */ #define __SDIO_ENABLE_IT(__INSTANCE__, __INTERRUPT__) ((__INSTANCE__)->MASK |= (__INTERRUPT__)) /** * @brief Disable the SDIO device interrupt. * @param __INSTANCE__ : Pointer to SDIO register base * @param __INTERRUPT__ : specifies the SDIO interrupt sources to be disabled. * This parameter can be one or a combination of the following values: * @arg SDIO_IT_CCRCFAIL: Command response received (CRC check failed) interrupt * @arg SDIO_IT_DCRCFAIL: Data block sent/received (CRC check failed) interrupt * @arg SDIO_IT_CTIMEOUT: Command response timeout interrupt * @arg SDIO_IT_DTIMEOUT: Data timeout interrupt * @arg SDIO_IT_TXUNDERR: Transmit FIFO underrun error interrupt * @arg SDIO_IT_RXOVERR: Received FIFO overrun error interrupt * @arg SDIO_IT_CMDREND: Command response received (CRC check passed) interrupt * @arg SDIO_IT_CMDSENT: Command sent (no response required) interrupt * @arg SDIO_IT_DATAEND: Data end (data counter, SDIDCOUNT, is zero) interrupt * @arg SDIO_IT_STBITERR: Start bit not detected on all data signals in wide * bus mode interrupt * @arg SDIO_IT_DBCKEND: Data block sent/received (CRC check passed) interrupt * @arg SDIO_IT_CMDACT: Command transfer in progress interrupt * @arg SDIO_IT_TXACT: Data transmit in progress interrupt * @arg SDIO_IT_RXACT: Data receive in progress interrupt * @arg SDIO_IT_TXFIFOHE: Transmit FIFO Half Empty interrupt * @arg SDIO_IT_RXFIFOHF: Receive FIFO Half Full interrupt * @arg SDIO_IT_TXFIFOF: Transmit FIFO full interrupt * @arg SDIO_IT_RXFIFOF: Receive FIFO full interrupt * @arg SDIO_IT_TXFIFOE: Transmit FIFO empty interrupt * @arg SDIO_IT_RXFIFOE: Receive FIFO empty interrupt * @arg SDIO_IT_TXDAVL: Data available in transmit FIFO interrupt * @arg SDIO_IT_RXDAVL: Data available in receive FIFO interrupt * @arg SDIO_IT_SDIOIT: SD I/O interrupt received interrupt * @arg SDIO_IT_CEATAEND: CE-ATA command completion signal received for CMD61 interrupt * @retval None */ #define __SDIO_DISABLE_IT(__INSTANCE__, __INTERRUPT__) ((__INSTANCE__)->MASK &= ~(__INTERRUPT__)) /** * @brief Checks whether the specified SDIO flag is set or not. * @param __INSTANCE__ : Pointer to SDIO register base * @param __FLAG__: specifies the flag to check. * This parameter can be one of the following values: * @arg SDIO_FLAG_CCRCFAIL: Command response received (CRC check failed) * @arg SDIO_FLAG_DCRCFAIL: Data block sent/received (CRC check failed) * @arg SDIO_FLAG_CTIMEOUT: Command response timeout * @arg SDIO_FLAG_DTIMEOUT: Data timeout * @arg SDIO_FLAG_TXUNDERR: Transmit FIFO underrun error * @arg SDIO_FLAG_RXOVERR: Received FIFO overrun error * @arg SDIO_FLAG_CMDREND: Command response received (CRC check passed) * @arg SDIO_FLAG_CMDSENT: Command sent (no response required) * @arg SDIO_FLAG_DATAEND: Data end (data counter, SDIDCOUNT, is zero) * @arg SDIO_FLAG_STBITERR: Start bit not detected on all data signals in wide bus mode. * @arg SDIO_FLAG_DBCKEND: Data block sent/received (CRC check passed) * @arg SDIO_FLAG_CMDACT: Command transfer in progress * @arg SDIO_FLAG_TXACT: Data transmit in progress * @arg SDIO_FLAG_RXACT: Data receive in progress * @arg SDIO_FLAG_TXFIFOHE: Transmit FIFO Half Empty * @arg SDIO_FLAG_RXFIFOHF: Receive FIFO Half Full * @arg SDIO_FLAG_TXFIFOF: Transmit FIFO full * @arg SDIO_FLAG_RXFIFOF: Receive FIFO full * @arg SDIO_FLAG_TXFIFOE: Transmit FIFO empty * @arg SDIO_FLAG_RXFIFOE: Receive FIFO empty * @arg SDIO_FLAG_TXDAVL: Data available in transmit FIFO * @arg SDIO_FLAG_RXDAVL: Data available in receive FIFO * @arg SDIO_FLAG_SDIOIT: SD I/O interrupt received * @arg SDIO_FLAG_CEATAEND: CE-ATA command completion signal received for CMD61 * @retval The new state of SDIO_FLAG (SET or RESET). */ #define __SDIO_GET_FLAG(__INSTANCE__, __FLAG__) (((__INSTANCE__)->STA &(__FLAG__)) != RESET) /** * @brief Clears the SDIO pending flags. * @param __INSTANCE__ : Pointer to SDIO register base * @param __FLAG__: specifies the flag to clear. * This parameter can be one or a combination of the following values: * @arg SDIO_FLAG_CCRCFAIL: Command response received (CRC check failed) * @arg SDIO_FLAG_DCRCFAIL: Data block sent/received (CRC check failed) * @arg SDIO_FLAG_CTIMEOUT: Command response timeout * @arg SDIO_FLAG_DTIMEOUT: Data timeout * @arg SDIO_FLAG_TXUNDERR: Transmit FIFO underrun error * @arg SDIO_FLAG_RXOVERR: Received FIFO overrun error * @arg SDIO_FLAG_CMDREND: Command response received (CRC check passed) * @arg SDIO_FLAG_CMDSENT: Command sent (no response required) * @arg SDIO_FLAG_DATAEND: Data end (data counter, SDIDCOUNT, is zero) * @arg SDIO_FLAG_STBITERR: Start bit not detected on all data signals in wide bus mode * @arg SDIO_FLAG_DBCKEND: Data block sent/received (CRC check passed) * @arg SDIO_FLAG_SDIOIT: SD I/O interrupt received * @arg SDIO_FLAG_CEATAEND: CE-ATA command completion signal received for CMD61 * @retval None */ #define __SDIO_CLEAR_FLAG(__INSTANCE__, __FLAG__) ((__INSTANCE__)->ICR = (__FLAG__)) /** * @brief Checks whether the specified SDIO interrupt has occurred or not. * @param __INSTANCE__ : Pointer to SDIO register base * @param __INTERRUPT__: specifies the SDIO interrupt source to check. * This parameter can be one of the following values: * @arg SDIO_IT_CCRCFAIL: Command response received (CRC check failed) interrupt * @arg SDIO_IT_DCRCFAIL: Data block sent/received (CRC check failed) interrupt * @arg SDIO_IT_CTIMEOUT: Command response timeout interrupt * @arg SDIO_IT_DTIMEOUT: Data timeout interrupt * @arg SDIO_IT_TXUNDERR: Transmit FIFO underrun error interrupt * @arg SDIO_IT_RXOVERR: Received FIFO overrun error interrupt * @arg SDIO_IT_CMDREND: Command response received (CRC check passed) interrupt * @arg SDIO_IT_CMDSENT: Command sent (no response required) interrupt * @arg SDIO_IT_DATAEND: Data end (data counter, SDIDCOUNT, is zero) interrupt * @arg SDIO_IT_STBITERR: Start bit not detected on all data signals in wide * bus mode interrupt * @arg SDIO_IT_DBCKEND: Data block sent/received (CRC check passed) interrupt * @arg SDIO_IT_CMDACT: Command transfer in progress interrupt * @arg SDIO_IT_TXACT: Data transmit in progress interrupt * @arg SDIO_IT_RXACT: Data receive in progress interrupt * @arg SDIO_IT_TXFIFOHE: Transmit FIFO Half Empty interrupt * @arg SDIO_IT_RXFIFOHF: Receive FIFO Half Full interrupt * @arg SDIO_IT_TXFIFOF: Transmit FIFO full interrupt * @arg SDIO_IT_RXFIFOF: Receive FIFO full interrupt * @arg SDIO_IT_TXFIFOE: Transmit FIFO empty interrupt * @arg SDIO_IT_RXFIFOE: Receive FIFO empty interrupt * @arg SDIO_IT_TXDAVL: Data available in transmit FIFO interrupt * @arg SDIO_IT_RXDAVL: Data available in receive FIFO interrupt * @arg SDIO_IT_SDIOIT: SD I/O interrupt received interrupt * @arg SDIO_IT_CEATAEND: CE-ATA command completion signal received for CMD61 interrupt * @retval The new state of SDIO_IT (SET or RESET). */ #define __SDIO_GET_IT (__INSTANCE__, __INTERRUPT__) (((__INSTANCE__)->STA &(__INTERRUPT__)) == (__INTERRUPT__)) /** * @brief Clears the SDIO's interrupt pending bits. * @param __INSTANCE__ : Pointer to SDIO register base * @param __INTERRUPT__: specifies the interrupt pending bit to clear. * This parameter can be one or a combination of the following values: * @arg SDIO_IT_CCRCFAIL: Command response received (CRC check failed) interrupt * @arg SDIO_IT_DCRCFAIL: Data block sent/received (CRC check failed) interrupt * @arg SDIO_IT_CTIMEOUT: Command response timeout interrupt * @arg SDIO_IT_DTIMEOUT: Data timeout interrupt * @arg SDIO_IT_TXUNDERR: Transmit FIFO underrun error interrupt * @arg SDIO_IT_RXOVERR: Received FIFO overrun error interrupt * @arg SDIO_IT_CMDREND: Command response received (CRC check passed) interrupt * @arg SDIO_IT_CMDSENT: Command sent (no response required) interrupt * @arg SDIO_IT_DATAEND: Data end (data counter, SDIO_DCOUNT, is zero) interrupt * @arg SDIO_IT_STBITERR: Start bit not detected on all data signals in wide * bus mode interrupt * @arg SDIO_IT_SDIOIT: SD I/O interrupt received interrupt * @arg SDIO_IT_CEATAEND: CE-ATA command completion signal received for CMD61 * @retval None */ #define __SDIO_CLEAR_IT(__INSTANCE__, __INTERRUPT__) ((__INSTANCE__)->ICR = (__INTERRUPT__)) /** * @brief Enable Start the SD I/O Read Wait operation. * @retval None */ #define __SDIO_START_READWAIT_ENABLE() (*(__IO uint32_t *) DCTRL_RWSTART_BB = ENABLE) /** * @brief Disable Start the SD I/O Read Wait operations. * @retval None */ #define __SDIO_START_READWAIT_DISABLE() (*(__IO uint32_t *) DCTRL_RWSTART_BB = DISABLE) /** * @brief Enable Start the SD I/O Read Wait operation. * @retval None */ #define __SDIO_STOP_READWAIT_ENABLE() (*(__IO uint32_t *) DCTRL_RWSTOP_BB = ENABLE) /** * @brief Disable Stop the SD I/O Read Wait operations. * @retval None */ #define __SDIO_STOP_READWAIT_DISABLE() (*(__IO uint32_t *) DCTRL_RWSTOP_BB = DISABLE) /** * @brief Enable the SD I/O Mode Operation. * @retval None */ #define __SDIO_OPERATION_ENABLE() (*(__IO uint32_t *) DCTRL_SDIOEN_BB = ENABLE) /** * @brief Disable the SD I/O Mode Operation. * @retval None */ #define __SDIO_OPERATION_DISABLE() (*(__IO uint32_t *) DCTRL_SDIOEN_BB = DISABLE) /** * @brief Enable the SD I/O Suspend command sending. * @retval None */ #define __SDIO_SUSPEND_CMD_ENABLE() (*(__IO uint32_t *) CMD_SDIOSUSPEND_BB = ENABLE) /** * @brief Disable the SD I/O Suspend command sending. * @retval None */ #define __SDIO_SUSPEND_CMD_DISABLE() (*(__IO uint32_t *) CMD_SDIOSUSPEND_BB = DISABLE) /** * @brief Enable the command completion signal. * @retval None */ #define __SDIO_CEATA_CMD_COMPLETION_ENABLE() (*(__IO uint32_t *) CMD_ENCMDCOMPL_BB = ENABLE) /** * @brief Disable the command completion signal. * @retval None */ #define __SDIO_CEATA_CMD_COMPLETION_DISABLE() (*(__IO uint32_t *) CMD_ENCMDCOMPL_BB = DISABLE) /** * @brief Enable the CE-ATA interrupt. * @retval None */ #define __SDIO_CEATA_ENABLE_IT() (*(__IO uint32_t *) CMD_NIEN_BB = (uint32_t)0) /** * @brief Disable the CE-ATA interrupt. * @retval None */ #define __SDIO_CEATA_DISABLE_IT() (*(__IO uint32_t *) CMD_NIEN_BB = (uint32_t)1) /** * @brief Enable send CE-ATA command (CMD61). * @retval None */ #define __SDIO_CEATA_SENDCMD_ENABLE() (*(__IO uint32_t *) CMD_ATACMD_BB = ENABLE) /** * @brief Disable send CE-ATA command (CMD61). * @retval None */ #define __SDIO_CEATA_SENDCMD_DISABLE() (*(__IO uint32_t *) CMD_ATACMD_BB = DISABLE) /** * @} */ /** * @} */ /* Exported functions --------------------------------------------------------*/ /** @addtogroup SDMMC_LL_Exported_Functions * @{ */ /* Initialization/de-initialization functions **********************************/ /** @addtogroup HAL_SDMMC_LL_Group1 * @{ */ HAL_StatusTypeDef SDIO_Init(SDIO_TypeDef *SDIOx, SDIO_InitTypeDef Init); /** * @} */ /* I/O operation functions *****************************************************/ /** @addtogroup HAL_SDMMC_LL_Group2 * @{ */ /* Blocking mode: Polling */ uint32_t SDIO_ReadFIFO(SDIO_TypeDef *SDIOx); HAL_StatusTypeDef SDIO_WriteFIFO(SDIO_TypeDef *SDIOx, uint32_t *pWriteData); /** * @} */ /* Peripheral Control functions ************************************************/ /** @addtogroup HAL_SDMMC_LL_Group3 * @{ */ HAL_StatusTypeDef SDIO_PowerState_ON(SDIO_TypeDef *SDIOx); HAL_StatusTypeDef SDIO_PowerState_OFF(SDIO_TypeDef *SDIOx); uint32_t SDIO_GetPowerState(SDIO_TypeDef *SDIOx); /* Command path state machine (CPSM) management functions */ HAL_StatusTypeDef SDIO_SendCommand(SDIO_TypeDef *SDIOx, SDIO_CmdInitTypeDef *SDIO_CmdInitStruct); uint8_t SDIO_GetCommandResponse(SDIO_TypeDef *SDIOx); uint32_t SDIO_GetResponse(uint32_t SDIO_RESP); /* Data path state machine (DPSM) management functions */ HAL_StatusTypeDef SDIO_DataConfig(SDIO_TypeDef *SDIOx, SDIO_DataInitTypeDef* SDIO_DataInitStruct); uint32_t SDIO_GetDataCounter(SDIO_TypeDef *SDIOx); uint32_t SDIO_GetFIFOCount(SDIO_TypeDef *SDIOx); /* SDIO IO Cards mode management functions */ HAL_StatusTypeDef SDIO_SetSDIOReadWaitMode(uint32_t SDIO_ReadWaitMode); /** * @} */ /** * @} */ /** * @} */ /** * @} */ #ifdef __cplusplus } #endif #endif /* STM32L151xD || STM32L152xD || STM32L162xD */ #endif /* __STM32L1xx_LL_SD_H */ /************************ (C) COPYRIGHT STMicroelectronics *****END OF FILE****/ ================================================ FILE: Zelig/mbed/TARGET_NUCLEO_L152RE/system_stm32l1xx.h ================================================ /** ****************************************************************************** * @file system_stm32l1xx.h * @author MCD Application Team * @version V2.0.0 * @date 5-September-2014 * @brief CMSIS Cortex-M3 Device System Source File for STM32L1xx devices. ****************************************************************************** * @attention * *

© COPYRIGHT(c) 2014 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. * ****************************************************************************** */ /** @addtogroup CMSIS * @{ */ /** @addtogroup stm32l1xx_system * @{ */ /** * @brief Define to prevent recursive inclusion */ #ifndef __SYSTEM_STM32L1XX_H #define __SYSTEM_STM32L1XX_H #ifdef __cplusplus extern "C" { #endif /** @addtogroup STM32L1xx_System_Includes * @{ */ /** * @} */ /** @addtogroup STM32L1xx_System_Exported_types * @{ */ /* This variable is updated in three ways: 1) by calling CMSIS function SystemCoreClockUpdate() 2) by calling HAL API function HAL_RCC_GetSysClockFreq() 3) each time HAL_RCC_ClockConfig() is called to configure the system clock frequency Note: If you use this function to configure the system clock; then there is no need to call the 2 first functions listed above, since SystemCoreClock variable is updated automatically. */ extern uint32_t SystemCoreClock; /*!< System Clock Frequency (Core Clock) */ /** * @} */ /** @addtogroup STM32L1xx_System_Exported_Constants * @{ */ /** * @} */ /** @addtogroup STM32L1xx_System_Exported_Macros * @{ */ /** * @} */ /** @addtogroup STM32L1xx_System_Exported_Functions * @{ */ extern void SystemInit(void); extern void SystemCoreClockUpdate(void); extern void SetSysClock(void); /** * @} */ #ifdef __cplusplus } #endif #endif /*__SYSTEM_STM32L1XX_H */ /** * @} */ /** * @} */ /************************ (C) COPYRIGHT STMicroelectronics *****END OF FILE****/ ================================================ FILE: Zelig/mbed/Ticker.h ================================================ /* mbed Microcontroller Library * Copyright (c) 2006-2013 ARM Limited * * 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 MBED_TICKER_H #define MBED_TICKER_H #include "TimerEvent.h" #include "FunctionPointer.h" namespace mbed { /** A Ticker is used to call a function at a recurring interval * * You can use as many seperate Ticker objects as you require. * * Example: * @code * // Toggle the blinking led after 5 seconds * * #include "mbed.h" * * Ticker timer; * DigitalOut led1(LED1); * DigitalOut led2(LED2); * * int flip = 0; * * void attime() { * flip = !flip; * } * * int main() { * timer.attach(&attime, 5); * while(1) { * if(flip == 0) { * led1 = !led1; * } else { * led2 = !led2; * } * wait(0.2); * } * } * @endcode */ class Ticker : public TimerEvent { public: Ticker() : TimerEvent() { } Ticker(const ticker_data_t *data) : TimerEvent(data) { } /** Attach a function to be called by the Ticker, specifiying the interval in seconds * * @param fptr pointer to the function to be called * @param t the time between calls in seconds */ void attach(void (*fptr)(void), float t) { attach_us(fptr, t * 1000000.0f); } /** Attach a member function to be called by the Ticker, specifiying the interval in seconds * * @param tptr pointer to the object to call the member function on * @param mptr pointer to the member function to be called * @param t the time between calls in seconds */ template void attach(T* tptr, void (T::*mptr)(void), float t) { attach_us(tptr, mptr, t * 1000000.0f); } /** Attach a function to be called by the Ticker, specifiying the interval in micro-seconds * * @param fptr pointer to the function to be called * @param t the time between calls in micro-seconds */ void attach_us(void (*fptr)(void), timestamp_t t) { _function.attach(fptr); setup(t); } /** Attach a member function to be called by the Ticker, specifiying the interval in micro-seconds * * @param tptr pointer to the object to call the member function on * @param mptr pointer to the member function to be called * @param t the time between calls in micro-seconds */ template void attach_us(T* tptr, void (T::*mptr)(void), timestamp_t t) { _function.attach(tptr, mptr); setup(t); } virtual ~Ticker() { detach(); } /** Detach the function */ void detach(); protected: void setup(timestamp_t t); virtual void handler(); protected: timestamp_t _delay; /**< Time delay (in microseconds) for re-setting the multi-shot callback. */ FunctionPointer _function; /**< Callback. */ }; } // namespace mbed #endif ================================================ FILE: Zelig/mbed/Timeout.h ================================================ /* mbed Microcontroller Library * Copyright (c) 2006-2013 ARM Limited * * 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 MBED_TIMEOUT_H #define MBED_TIMEOUT_H #include "Ticker.h" namespace mbed { /** A Timeout is used to call a function at a point in the future * * You can use as many seperate Timeout objects as you require. * * Example: * @code * // Blink until timeout. * * #include "mbed.h" * * Timeout timeout; * DigitalOut led(LED1); * * int on = 1; * * void attimeout() { * on = 0; * } * * int main() { * timeout.attach(&attimeout, 5); * while(on) { * led = !led; * wait(0.2); * } * } * @endcode */ class Timeout : public Ticker { protected: virtual void handler(); }; } // namespace mbed #endif ================================================ FILE: Zelig/mbed/Timer.h ================================================ /* mbed Microcontroller Library * Copyright (c) 2006-2013 ARM Limited * * 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 MBED_TIMER_H #define MBED_TIMER_H #include "platform.h" #include "ticker_api.h" namespace mbed { /** A general purpose timer * * Example: * @code * // Count the time to toggle a LED * * #include "mbed.h" * * Timer timer; * DigitalOut led(LED1); * int begin, end; * * int main() { * timer.start(); * begin = timer.read_us(); * led = !led; * end = timer.read_us(); * printf("Toggle the led takes %d us", end - begin); * } * @endcode */ class Timer { public: Timer(); Timer(const ticker_data_t *data); /** Start the timer */ void start(); /** Stop the timer */ void stop(); /** Reset the timer to 0. * * If it was already counting, it will continue */ void reset(); /** Get the time passed in seconds */ float read(); /** Get the time passed in mili-seconds */ int read_ms(); /** Get the time passed in micro-seconds */ int read_us(); #ifdef MBED_OPERATORS operator float(); #endif protected: int slicetime(); int _running; // whether the timer is running unsigned int _start; // the start time of the latest slice int _time; // any accumulated time from previous slices const ticker_data_t *_ticker_data; }; } // namespace mbed #endif ================================================ FILE: Zelig/mbed/TimerEvent.h ================================================ /* mbed Microcontroller Library * Copyright (c) 2006-2013 ARM Limited * * 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 MBED_TIMEREVENT_H #define MBED_TIMEREVENT_H #include "ticker_api.h" #include "us_ticker_api.h" namespace mbed { /** Base abstraction for timer interrupts */ class TimerEvent { public: TimerEvent(); TimerEvent(const ticker_data_t *data); /** The handler registered with the underlying timer interrupt */ static void irq(uint32_t id); /** Destruction removes it... */ virtual ~TimerEvent(); protected: // The handler called to service the timer event of the derived class virtual void handler() = 0; // insert in to linked list void insert(timestamp_t timestamp); // remove from linked list, if in it void remove(); ticker_event_t event; const ticker_data_t *_ticker_data; }; } // namespace mbed #endif ================================================ FILE: Zelig/mbed/Transaction.h ================================================ /* mbed Microcontroller Library * Copyright (c) 2015 ARM Limited * * 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 MBED_TRANSACTION_H #define MBED_TRANSACTION_H #include "platform.h" #include "FunctionPointer.h" namespace mbed { /** Transaction structure */ typedef struct { void *tx_buffer; /**< Tx buffer */ size_t tx_length; /**< Length of Tx buffer*/ void *rx_buffer; /**< Rx buffer */ size_t rx_length; /**< Length of Rx buffer */ uint32_t event; /**< Event for a transaction */ event_callback_t callback; /**< User's callback */ uint8_t width; /**< Buffer's word width (8, 16, 32, 64) */ } transaction_t; /** Transaction class defines a transaction. */ template class Transaction { public: Transaction(Class *tpointer, const transaction_t& transaction) : _obj(tpointer), _data(transaction) { } Transaction() : _obj(), _data() { } ~Transaction() { } /** Get object's instance for the transaction * * @return The object which was stored */ Class* get_object() { return _obj; } /** Get the transaction * * @return The transaction which was stored */ transaction_t* get_transaction() { return &_data; } private: Class* _obj; transaction_t _data; }; } #endif ================================================ FILE: Zelig/mbed/analogin_api.h ================================================ /* mbed Microcontroller Library * Copyright (c) 2006-2013 ARM Limited * * 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 MBED_ANALOGIN_API_H #define MBED_ANALOGIN_API_H #include "device.h" #if DEVICE_ANALOGIN #ifdef __cplusplus extern "C" { #endif typedef struct analogin_s analogin_t; void analogin_init (analogin_t *obj, PinName pin); float analogin_read (analogin_t *obj); uint16_t analogin_read_u16(analogin_t *obj); #ifdef __cplusplus } #endif #endif #endif ================================================ FILE: Zelig/mbed/analogout_api.h ================================================ /* mbed Microcontroller Library * Copyright (c) 2006-2013 ARM Limited * * 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 MBED_ANALOGOUT_API_H #define MBED_ANALOGOUT_API_H #include "device.h" #if DEVICE_ANALOGOUT #ifdef __cplusplus extern "C" { #endif typedef struct dac_s dac_t; void analogout_init (dac_t *obj, PinName pin); void analogout_free (dac_t *obj); void analogout_write (dac_t *obj, float value); void analogout_write_u16(dac_t *obj, uint16_t value); float analogout_read (dac_t *obj); uint16_t analogout_read_u16 (dac_t *obj); #ifdef __cplusplus } #endif #endif #endif ================================================ FILE: Zelig/mbed/buffer.h ================================================ /* mbed Microcontroller Library * Copyright (c) 2014-2015 ARM Limited * * 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 MBED_BUFFER_H #define MBED_BUFFER_H #include /** Generic buffer structure */ typedef struct buffer_s { void *buffer; /**< the pointer to a buffer */ size_t length; /**< the buffer length */ size_t pos; /**< actual buffer position */ uint8_t width; /**< The buffer unit width (8, 16, 32, 64), used for proper *buffer casting */ } buffer_t; #endif ================================================ FILE: Zelig/mbed/can_api.h ================================================ /* mbed Microcontroller Library * Copyright (c) 2006-2013 ARM Limited * * 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 MBED_CAN_API_H #define MBED_CAN_API_H #include "device.h" #if DEVICE_CAN #include "PinNames.h" #include "PeripheralNames.h" #include "can_helper.h" #ifdef __cplusplus extern "C" { #endif typedef enum { IRQ_RX, IRQ_TX, IRQ_ERROR, IRQ_OVERRUN, IRQ_WAKEUP, IRQ_PASSIVE, IRQ_ARB, IRQ_BUS, IRQ_READY } CanIrqType; typedef enum { MODE_RESET, MODE_NORMAL, MODE_SILENT, MODE_TEST_LOCAL, MODE_TEST_GLOBAL, MODE_TEST_SILENT } CanMode; typedef void (*can_irq_handler)(uint32_t id, CanIrqType type); typedef struct can_s can_t; void can_init (can_t *obj, PinName rd, PinName td); void can_free (can_t *obj); int can_frequency(can_t *obj, int hz); void can_irq_init (can_t *obj, can_irq_handler handler, uint32_t id); void can_irq_free (can_t *obj); void can_irq_set (can_t *obj, CanIrqType irq, uint32_t enable); int can_write (can_t *obj, CAN_Message, int cc); int can_read (can_t *obj, CAN_Message *msg, int handle); int can_mode (can_t *obj, CanMode mode); int can_filter(can_t *obj, uint32_t id, uint32_t mask, CANFormat format, int32_t handle); void can_reset (can_t *obj); unsigned char can_rderror (can_t *obj); unsigned char can_tderror (can_t *obj); void can_monitor (can_t *obj, int silent); #ifdef __cplusplus }; #endif #endif // MBED_CAN_API_H #endif ================================================ FILE: Zelig/mbed/can_helper.h ================================================ /* mbed Microcontroller Library * Copyright (c) 2006-2013 ARM Limited * * 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 MBED_CAN_HELPER_H #define MBED_CAN_HELPER_H #if DEVICE_CAN #ifdef __cplusplus extern "C" { #endif enum CANFormat { CANStandard = 0, CANExtended = 1, CANAny = 2 }; typedef enum CANFormat CANFormat; enum CANType { CANData = 0, CANRemote = 1 }; typedef enum CANType CANType; struct CAN_Message { unsigned int id; // 29 bit identifier unsigned char data[8]; // Data field unsigned char len; // Length of data field in bytes CANFormat format; // 0 - STANDARD, 1- EXTENDED IDENTIFIER CANType type; // 0 - DATA FRAME, 1 - REMOTE FRAME }; typedef struct CAN_Message CAN_Message; #ifdef __cplusplus }; #endif #endif #endif // MBED_CAN_HELPER_H ================================================ FILE: Zelig/mbed/dma_api.h ================================================ /* mbed Microcontroller Library * Copyright (c) 2014-2015 ARM Limited * * 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 MBED_DMA_API_H #define MBED_DMA_API_H #include #define DMA_ERROR_OUT_OF_CHANNELS (-1) typedef enum { DMA_USAGE_NEVER, DMA_USAGE_OPPORTUNISTIC, DMA_USAGE_ALWAYS, DMA_USAGE_TEMPORARY_ALLOCATED, DMA_USAGE_ALLOCATED } DMAUsage; #ifdef __cplusplus extern "C" { #endif void dma_init(void); int dma_channel_allocate(uint32_t capabilities); int dma_channel_free(int channelid); #ifdef __cplusplus } #endif #endif ================================================ FILE: Zelig/mbed/ethernet_api.h ================================================ /* mbed Microcontroller Library * Copyright (c) 2006-2013 ARM Limited * * 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 MBED_ETHERNET_API_H #define MBED_ETHERNET_API_H #include "device.h" #if DEVICE_ETHERNET #ifdef __cplusplus extern "C" { #endif // Connection constants int ethernet_init(void); void ethernet_free(void); // write size bytes from data to ethernet buffer // return num bytes written // or -1 if size is too big int ethernet_write(const char *data, int size); // send ethernet write buffer, returning the packet size sent int ethernet_send(void); // recieve from ethernet buffer, returning packet size, or 0 if no packet int ethernet_receive(void); // read size bytes in to data, return actual num bytes read (0..size) // if data == NULL, throw the bytes away int ethernet_read(char *data, int size); // get the ethernet address void ethernet_address(char *mac); // see if the link is up int ethernet_link(void); // force link settings void ethernet_set_link(int speed, int duplex); #ifdef __cplusplus } #endif #endif #endif ================================================ FILE: Zelig/mbed/gpio_api.h ================================================ /* mbed Microcontroller Library * Copyright (c) 2006-2013 ARM Limited * * 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 MBED_GPIO_API_H #define MBED_GPIO_API_H #include "device.h" #ifdef __cplusplus extern "C" { #endif /* Set the given pin as GPIO * @param pin The pin to be set as GPIO * @return The GPIO port mask for this pin **/ uint32_t gpio_set(PinName pin); /* Checks if gpio object is connected (pin was not initialized with NC) * @param pin The pin to be set as GPIO * @return 0 if port is initialized with NC **/ int gpio_is_connected(const gpio_t *obj); /* GPIO object */ void gpio_init(gpio_t *obj, PinName pin); void gpio_mode (gpio_t *obj, PinMode mode); void gpio_dir (gpio_t *obj, PinDirection direction); void gpio_write(gpio_t *obj, int value); int gpio_read (gpio_t *obj); // the following set of functions are generic and are implemented in the common gpio.c file void gpio_init_in(gpio_t* gpio, PinName pin); void gpio_init_in_ex(gpio_t* gpio, PinName pin, PinMode mode); void gpio_init_out(gpio_t* gpio, PinName pin); void gpio_init_out_ex(gpio_t* gpio, PinName pin, int value); void gpio_init_inout(gpio_t* gpio, PinName pin, PinDirection direction, PinMode mode, int value); #ifdef __cplusplus } #endif #endif ================================================ FILE: Zelig/mbed/gpio_irq_api.h ================================================ /* mbed Microcontroller Library * Copyright (c) 2006-2013 ARM Limited * * 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 MBED_GPIO_IRQ_API_H #define MBED_GPIO_IRQ_API_H #include "device.h" #if DEVICE_INTERRUPTIN #ifdef __cplusplus extern "C" { #endif typedef enum { IRQ_NONE, IRQ_RISE, IRQ_FALL } gpio_irq_event; typedef struct gpio_irq_s gpio_irq_t; typedef void (*gpio_irq_handler)(uint32_t id, gpio_irq_event event); int gpio_irq_init(gpio_irq_t *obj, PinName pin, gpio_irq_handler handler, uint32_t id); void gpio_irq_free(gpio_irq_t *obj); void gpio_irq_set (gpio_irq_t *obj, gpio_irq_event event, uint32_t enable); void gpio_irq_enable(gpio_irq_t *obj); void gpio_irq_disable(gpio_irq_t *obj); #ifdef __cplusplus } #endif #endif #endif ================================================ FILE: Zelig/mbed/i2c_api.h ================================================ /* mbed Microcontroller Library * Copyright (c) 2006-2015 ARM Limited * * 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 MBED_I2C_API_H #define MBED_I2C_API_H #include "device.h" #include "buffer.h" #if DEVICE_I2C /** * @defgroup I2CEvents I2C Events Macros * * @{ */ #define I2C_EVENT_ERROR (1 << 1) #define I2C_EVENT_ERROR_NO_SLAVE (1 << 2) #define I2C_EVENT_TRANSFER_COMPLETE (1 << 3) #define I2C_EVENT_TRANSFER_EARLY_NACK (1 << 4) #define I2C_EVENT_ALL (I2C_EVENT_ERROR | I2C_EVENT_TRANSFER_COMPLETE | I2C_EVENT_ERROR_NO_SLAVE | I2C_EVENT_TRANSFER_EARLY_NACK) /**@}*/ #if DEVICE_I2C_ASYNCH /** Asynch i2c hal structure */ typedef struct { struct i2c_s i2c; /**< Target specific i2c structure */ struct buffer_s tx_buff; /**< Tx buffer */ struct buffer_s rx_buff; /**< Rx buffer */ } i2c_t; #else /** Non-asynch i2c hal structure */ typedef struct i2c_s i2c_t; #endif enum { I2C_ERROR_NO_SLAVE = -1, I2C_ERROR_BUS_BUSY = -2 }; #ifdef __cplusplus extern "C" { #endif /** * \defgroup GeneralI2C I2C Configuration Functions * @{ */ /** Initialize the I2C peripheral. It sets the default parameters for I2C * peripheral, and configure its specifieds pins. * @param obj The i2c object * @param sda The sda pin * @param scl The scl pin */ void i2c_init(i2c_t *obj, PinName sda, PinName scl); /** Configure the I2C frequency. * @param obj The i2c object * @param hz Frequency in Hz */ void i2c_frequency(i2c_t *obj, int hz); /** Send START command. * @param obj The i2c object */ int i2c_start(i2c_t *obj); /** Send STOP command. * @param obj The i2c object */ int i2c_stop(i2c_t *obj); /** Blocking reading data. * @param obj The i2c object * @param address 7-bit address (last bit is 1) * @param data The buffer for receiving * @param length Number of bytes to read * @param stop Stop to be generated after the transfer is done * @return Number of read bytes */ int i2c_read(i2c_t *obj, int address, char *data, int length, int stop); /** Blocking sending data. * @param obj The i2c object * @param address 7-bit address (last bit is 0) * @param data The buffer for sending * @param length Number of bytes to wrte * @param stop Stop to be generated after the transfer is done * @return Number of written bytes */ int i2c_write(i2c_t *obj, int address, const char *data, int length, int stop); /** Reset I2C peripheral. TODO: The action here. Most of the implementation sends stop(). * @param obj The i2c object */ void i2c_reset(i2c_t *obj); /** Read one byte. * @param obj The i2c object * @param last Acknoledge * @return The read byte */ int i2c_byte_read(i2c_t *obj, int last); /** Write one byte. * @param obj The i2c object * @param data Byte to be written * @return 1 if NAK was received, 0 if ACK was received, 2 for timeout. */ int i2c_byte_write(i2c_t *obj, int data); /**@}*/ #if DEVICE_I2CSLAVE /** * \defgroup SynchI2C Synchronous I2C Hardware Abstraction Layer for slave * @{ */ /** Configure I2C as slave or master. * @param obj The I2C object * @return non-zero if a value is available */ void i2c_slave_mode(i2c_t *obj, int enable_slave); /** Check to see if the I2C slave has been addressed. * @param obj The I2C object * @return The status - 1 - read addresses, 2 - write to all slaves, * 3 write addressed, 0 - the slave has not been addressed */ int i2c_slave_receive(i2c_t *obj); /** Configure I2C as slave or master. * @param obj The I2C object * @return non-zero if a value is available */ int i2c_slave_read(i2c_t *obj, char *data, int length); /** Configure I2C as slave or master. * @param obj The I2C object * @return non-zero if a value is available */ int i2c_slave_write(i2c_t *obj, const char *data, int length); /** Configure I2C address. * @param obj The I2C object * @param idx Currently not used * @param address The address to be set * @param mask Currently not used */ void i2c_slave_address(i2c_t *obj, int idx, uint32_t address, uint32_t mask); #endif /**@}*/ #if DEVICE_I2C_ASYNCH /** * \defgroup AsynchI2C Asynchronous I2C Hardware Abstraction Layer * @{ */ /** Start i2c asynchronous transfer. * @param obj The I2C object * @param tx The buffer to send * @param tx_length The number of words to transmit * @param rx The buffer to receive * @param rx_length The number of words to receive * @param address The address to be set - 7bit or 9 bit * @param stop If true, stop will be generated after the transfer is done * @param handler The I2C IRQ handler to be set * @param hint DMA hint usage */ void i2c_transfer_asynch(i2c_t *obj, const void *tx, size_t tx_length, void *rx, size_t rx_length, uint32_t address, uint32_t stop, uint32_t handler, uint32_t event, DMAUsage hint); /** The asynchronous IRQ handler * @param obj The I2C object which holds the transfer information * @return event flags if a transfer termination condition was met or 0 otherwise. */ uint32_t i2c_irq_handler_asynch(i2c_t *obj); /** Attempts to determine if I2C peripheral is already in use. * @param obj The I2C object * @return non-zero if the I2C module is active or zero if it is not */ uint8_t i2c_active(i2c_t *obj); /** Abort ongoing asynchronous transaction. * @param obj The I2C object */ void i2c_abort_asynch(i2c_t *obj); #endif /**@}*/ #ifdef __cplusplus } #endif #endif #endif ================================================ FILE: Zelig/mbed/lp_ticker_api.h ================================================ /* mbed Microcontroller Library * Copyright (c) 2015 ARM Limited * * 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 MBED_LPTICKER_API_H #define MBED_LPTICKER_API_H #include "device.h" #if DEVICE_LOWPOWERTIMER #include "ticker_api.h" #ifdef __cplusplus extern "C" { #endif /** * \defgroup LpTicker Low Power Ticker Functions * @{ */ /** Get low power ticker's data * * @return The low power ticker data */ const ticker_data_t* get_lp_ticker_data(void); /** The wrapper for ticker_irq_handler, to pass lp ticker's data * */ void lp_ticker_irq_handler(void); /* HAL lp ticker */ /** Initialize the low power ticker * */ void lp_ticker_init(void); /** Read the current counter * * @return The current timer's counter value in microseconds */ uint32_t lp_ticker_read(void); /** Set interrupt for specified timestamp * * @param timestamp The time in microseconds to be set */ void lp_ticker_set_interrupt(timestamp_t timestamp); /** Disable low power ticker interrupt * */ void lp_ticker_disable_interrupt(void); /** Clear the low power ticker interrupt * */ void lp_ticker_clear_interrupt(void); /**@}*/ #ifdef __cplusplus } #endif #endif #endif ================================================ FILE: Zelig/mbed/mbed.h ================================================ /* mbed Microcontroller Library * Copyright (c) 2006-2013 ARM Limited * * 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 MBED_H #define MBED_H #define MBED_LIBRARY_VERSION 104 #include "platform.h" // Useful C libraries #include #include // mbed Debug libraries #include "mbed_error.h" #include "mbed_interface.h" // mbed Peripheral components #include "DigitalIn.h" #include "DigitalOut.h" #include "DigitalInOut.h" #include "BusIn.h" #include "BusOut.h" #include "BusInOut.h" #include "PortIn.h" #include "PortInOut.h" #include "PortOut.h" #include "AnalogIn.h" #include "AnalogOut.h" #include "PwmOut.h" #include "Serial.h" #include "SPI.h" #include "SPISlave.h" #include "I2C.h" #include "I2CSlave.h" #include "Ethernet.h" #include "CAN.h" #include "RawSerial.h" // mbed Internal components #include "Timer.h" #include "Ticker.h" #include "Timeout.h" #include "LowPowerTimeout.h" #include "LowPowerTicker.h" #include "LowPowerTimer.h" #include "LocalFileSystem.h" #include "InterruptIn.h" #include "wait_api.h" #include "sleep_api.h" #include "rtc_time.h" using namespace mbed; using namespace std; #endif ================================================ FILE: Zelig/mbed/mbed_assert.h ================================================ /* mbed Microcontroller Library * Copyright (c) 2006-2013 ARM Limited * * 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 MBED_ASSERT_H #define MBED_ASSERT_H #ifdef __cplusplus extern "C" { #endif /** Internal mbed assert function which is invoked when MBED_ASSERT macro failes. * This function is active only if NDEBUG is not defined prior to including this * assert header file. * In case of MBED_ASSERT failing condition, the assertation message is printed * to stderr and mbed_die() is called. * @param expr Expresion to be checked. * @param file File where assertation failed. * @param line Failing assertation line number. */ void mbed_assert_internal(const char *expr, const char *file, int line); #ifdef __cplusplus } #endif #ifdef NDEBUG #define MBED_ASSERT(expr) ((void)0) #else #define MBED_ASSERT(expr) \ do { \ if (!(expr)) { \ mbed_assert_internal(#expr, __FILE__, __LINE__); \ } \ } while (0) #endif #endif ================================================ FILE: Zelig/mbed/mbed_debug.h ================================================ /* mbed Microcontroller Library * Copyright (c) 2006-2013 ARM Limited * * 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 MBED_DEBUG_H #define MBED_DEBUG_H #include "device.h" #ifdef __cplusplus extern "C" { #endif #if DEVICE_STDIO_MESSAGES #include #include /** Output a debug message * * @param format printf-style format string, followed by variables */ static inline void debug(const char *format, ...) { va_list args; va_start(args, format); vfprintf(stderr, format, args); va_end(args); } /** Conditionally output a debug message * * NOTE: If the condition is constant false (!= 1) and the compiler optimization * level is greater than 0, then the whole function will be compiled away. * * @param condition output only if condition is true (== 1) * @param format printf-style format string, followed by variables */ static inline void debug_if(int condition, const char *format, ...) { if (condition == 1) { va_list args; va_start(args, format); vfprintf(stderr, format, args); va_end(args); } } #else static inline void debug(const char *format, ...) {} static inline void debug_if(int condition, const char *format, ...) {} #endif #ifdef __cplusplus } #endif #endif ================================================ FILE: Zelig/mbed/mbed_error.h ================================================ /* mbed Microcontroller Library * Copyright (c) 2006-2013 ARM Limited * * 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 MBED_ERROR_H #define MBED_ERROR_H /** To generate a fatal compile-time error, you can use the pre-processor #error directive. * * @code * #error "That shouldn't have happened!" * @endcode * * If the compiler evaluates this line, it will report the error and stop the compile. * * For example, you could use this to check some user-defined compile-time variables: * * @code * #define NUM_PORTS 7 * #if (NUM_PORTS > 4) * #error "NUM_PORTS must be less than 4" * #endif * @endcode * * Reporting Run-Time Errors: * To generate a fatal run-time error, you can use the mbed error() function. * * @code * error("That shouldn't have happened!"); * @endcode * * If the mbed running the program executes this function, it will print the * message via the USB serial port, and then die with the blue lights of death! * * The message can use printf-style formatting, so you can report variables in the * message too. For example, you could use this to check a run-time condition: * * @code * if(x >= 5) { * error("expected x to be less than 5, but got %d", x); * } * #endcode */ #ifdef __cplusplus extern "C" { #endif void error(const char* format, ...); #ifdef __cplusplus } #endif #endif ================================================ FILE: Zelig/mbed/mbed_interface.h ================================================ /* mbed Microcontroller Library * Copyright (c) 2006-2013 ARM Limited * * 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 MBED_INTERFACE_H #define MBED_INTERFACE_H #include "device.h" /* Mbed interface mac address * if MBED_MAC_ADD_x are zero, interface uid sets mac address, * otherwise MAC_ADD_x are used. */ #define MBED_MAC_ADDR_INTERFACE 0x00 #define MBED_MAC_ADDR_0 MBED_MAC_ADDR_INTERFACE #define MBED_MAC_ADDR_1 MBED_MAC_ADDR_INTERFACE #define MBED_MAC_ADDR_2 MBED_MAC_ADDR_INTERFACE #define MBED_MAC_ADDR_3 MBED_MAC_ADDR_INTERFACE #define MBED_MAC_ADDR_4 MBED_MAC_ADDR_INTERFACE #define MBED_MAC_ADDR_5 MBED_MAC_ADDR_INTERFACE #define MBED_MAC_ADDRESS_SUM (MBED_MAC_ADDR_0 | MBED_MAC_ADDR_1 | MBED_MAC_ADDR_2 | MBED_MAC_ADDR_3 | MBED_MAC_ADDR_4 | MBED_MAC_ADDR_5) #ifdef __cplusplus extern "C" { #endif #if DEVICE_SEMIHOST /** Functions to control the mbed interface * * mbed Microcontrollers have a built-in interface to provide functionality such as * drag-n-drop download, reset, serial-over-usb, and access to the mbed local file * system. These functions provide means to control the interface suing semihost * calls it supports. */ /** Determine whether the mbed interface is connected, based on whether debug is enabled * * @returns * 1 if interface is connected, * 0 otherwise */ int mbed_interface_connected(void); /** Instruct the mbed interface to reset, as if the reset button had been pressed * * @returns * 1 if successful, * 0 otherwise (e.g. interface not present) */ int mbed_interface_reset(void); /** This will disconnect the debug aspect of the interface, so semihosting will be disabled. * The interface will still support the USB serial aspect * * @returns * 0 if successful, * -1 otherwise (e.g. interface not present) */ int mbed_interface_disconnect(void); /** This will disconnect the debug aspect of the interface, and if the USB cable is not * connected, also power down the interface. If the USB cable is connected, the interface * will remain powered up and visible to the host * * @returns * 0 if successful, * -1 otherwise (e.g. interface not present) */ int mbed_interface_powerdown(void); /** This returns a string containing the 32-character UID of the mbed interface * This is a weak function that can be overwritten if required * * @param uid A 33-byte array to write the null terminated 32-byte string * * @returns * 0 if successful, * -1 otherwise (e.g. interface not present) */ int mbed_interface_uid(char *uid); #endif /** This returns a unique 6-byte MAC address, based on the interface UID * If the interface is not present, it returns a default fixed MAC address (00:02:F7:F0:00:00) * * This is a weak function that can be overwritten if you want to provide your own mechanism to * provide a MAC address. * * @param mac A 6-byte array to write the MAC address */ void mbed_mac_address(char *mac); /** Cause the mbed to flash the BLOD (Blue LEDs Of Death) sequence */ void mbed_die(void); #ifdef __cplusplus } #endif #endif ================================================ FILE: Zelig/mbed/pinmap.h ================================================ /* mbed Microcontroller Library * Copyright (c) 2006-2013 ARM Limited * * 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 MBED_PINMAP_H #define MBED_PINMAP_H #include "PinNames.h" #ifdef __cplusplus extern "C" { #endif typedef struct { PinName pin; int peripheral; int function; } PinMap; void pin_function(PinName pin, int function); void pin_mode (PinName pin, PinMode mode); uint32_t pinmap_peripheral(PinName pin, const PinMap* map); uint32_t pinmap_function(PinName pin, const PinMap* map); uint32_t pinmap_merge (uint32_t a, uint32_t b); void pinmap_pinout (PinName pin, const PinMap *map); uint32_t pinmap_find_peripheral(PinName pin, const PinMap* map); uint32_t pinmap_find_function(PinName pin, const PinMap* map); #ifdef __cplusplus } #endif #endif ================================================ FILE: Zelig/mbed/platform.h ================================================ /* mbed Microcontroller Library * Copyright (c) 2006-2013 ARM Limited * * 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 MBED_PLATFORM_H #define MBED_PLATFORM_H #define MBED_OPERATORS 1 #include "device.h" #include "PinNames.h" #include "PeripheralNames.h" #include #include #include #include #endif ================================================ FILE: Zelig/mbed/port_api.h ================================================ /* mbed Microcontroller Library * Copyright (c) 2006-2013 ARM Limited * * 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 MBED_PORTMAP_H #define MBED_PORTMAP_H #include "device.h" #if DEVICE_PORTIN || DEVICE_PORTOUT #ifdef __cplusplus extern "C" { #endif typedef struct port_s port_t; PinName port_pin(PortName port, int pin_n); void port_init (port_t *obj, PortName port, int mask, PinDirection dir); void port_mode (port_t *obj, PinMode mode); void port_dir (port_t *obj, PinDirection dir); void port_write(port_t *obj, int value); int port_read (port_t *obj); #ifdef __cplusplus } #endif #endif #endif ================================================ FILE: Zelig/mbed/pwmout_api.h ================================================ /* mbed Microcontroller Library * Copyright (c) 2006-2013 ARM Limited * * 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 MBED_PWMOUT_API_H #define MBED_PWMOUT_API_H #include "device.h" #if DEVICE_PWMOUT #ifdef __cplusplus extern "C" { #endif typedef struct pwmout_s pwmout_t; void pwmout_init (pwmout_t* obj, PinName pin); void pwmout_free (pwmout_t* obj); void pwmout_write (pwmout_t* obj, float percent); float pwmout_read (pwmout_t* obj); void pwmout_period (pwmout_t* obj, float seconds); void pwmout_period_ms (pwmout_t* obj, int ms); void pwmout_period_us (pwmout_t* obj, int us); void pwmout_pulsewidth (pwmout_t* obj, float seconds); void pwmout_pulsewidth_ms(pwmout_t* obj, int ms); void pwmout_pulsewidth_us(pwmout_t* obj, int us); #ifdef __cplusplus } #endif #endif #endif ================================================ FILE: Zelig/mbed/rtc_api.h ================================================ /* mbed Microcontroller Library * Copyright (c) 2006-2013 ARM Limited * * 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 MBED_RTC_API_H #define MBED_RTC_API_H #include "device.h" #if DEVICE_RTC #include #ifdef __cplusplus extern "C" { #endif void rtc_init(void); void rtc_free(void); int rtc_isenabled(void); time_t rtc_read(void); void rtc_write(time_t t); #ifdef __cplusplus } #endif #endif #endif ================================================ FILE: Zelig/mbed/rtc_time.h ================================================ /* mbed Microcontroller Library * Copyright (c) 2006-2013 ARM Limited * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include #ifdef __cplusplus extern "C" { #endif /** Implementation of the C time.h functions * * Provides mechanisms to set and read the current time, based * on the microcontroller Real-Time Clock (RTC), plus some * standard C manipulation and formating functions. * * Example: * @code * #include "mbed.h" * * int main() { * set_time(1256729737); // Set RTC time to Wed, 28 Oct 2009 11:35:37 * * while(1) { * time_t seconds = time(NULL); * * printf("Time as seconds since January 1, 1970 = %d\n", seconds); * * printf("Time as a basic string = %s", ctime(&seconds)); * * char buffer[32]; * strftime(buffer, 32, "%I:%M %p\n", localtime(&seconds)); * printf("Time as a custom formatted string = %s", buffer); * * wait(1); * } * } * @endcode */ /** Set the current time * * Initialises and sets the time of the microcontroller Real-Time Clock (RTC) * to the time represented by the number of seconds since January 1, 1970 * (the UNIX timestamp). * * @param t Number of seconds since January 1, 1970 (the UNIX timestamp) * * Example: * @code * #include "mbed.h" * * int main() { * set_time(1256729737); // Set time to Wed, 28 Oct 2009 11:35:37 * } * @endcode */ void set_time(time_t t); /** Attach an external RTC to be used for the C time functions * * Do not call this function from an interrupt while an RTC read/write operation may be occurring * * @param read_rtc pointer to function which returns current UNIX timestamp * @param write_rtc pointer to function which sets current UNIX timestamp, can be NULL * @param init_rtc pointer to funtion which initializes RTC, can be NULL * @param isenabled_rtc pointer to function wich returns if the rtc is enabled, can be NULL */ void attach_rtc(time_t (*read_rtc)(void), void (*write_rtc)(time_t), void (*init_rtc)(void), int (*isenabled_rtc)(void)); #ifdef __cplusplus } #endif ================================================ FILE: Zelig/mbed/semihost_api.h ================================================ /* mbed Microcontroller Library * Copyright (c) 2006-2013 ARM Limited * * 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 MBED_SEMIHOST_H #define MBED_SEMIHOST_H #include "device.h" #include "toolchain.h" #ifdef __cplusplus extern "C" { #endif #if DEVICE_SEMIHOST #ifndef __CC_ARM #if defined(__ICCARM__) inline int __semihost(int reason, const void *arg) { return __semihosting(reason, (void*)arg); } #else #ifdef __thumb__ # define AngelSWI 0xAB # define AngelSWIInsn "bkpt" # define AngelSWIAsm bkpt #else # define AngelSWI 0x123456 # define AngelSWIInsn "swi" # define AngelSWIAsm swi #endif static inline int __semihost(int reason, const void *arg) { int value; asm volatile ( "mov r0, %1" "\n\t" "mov r1, %2" "\n\t" AngelSWIInsn " %a3" "\n\t" "mov %0, r0" : "=r" (value) /* output operands */ : "r" (reason), "r" (arg), "i" (AngelSWI) /* input operands */ : "r0", "r1", "r2", "r3", "ip", "lr", "memory", "cc" /* list of clobbered registers */ ); return value; } #endif #endif #if DEVICE_LOCALFILESYSTEM FILEHANDLE semihost_open(const char* name, int openmode); int semihost_close (FILEHANDLE fh); int semihost_read (FILEHANDLE fh, unsigned char* buffer, unsigned int length, int mode); int semihost_write (FILEHANDLE fh, const unsigned char* buffer, unsigned int length, int mode); int semihost_ensure(FILEHANDLE fh); long semihost_flen (FILEHANDLE fh); int semihost_seek (FILEHANDLE fh, long position); int semihost_istty (FILEHANDLE fh); int semihost_remove(const char *name); int semihost_rename(const char *old_name, const char *new_name); #endif int semihost_uid(char *uid); int semihost_reset(void); int semihost_vbus(void); int semihost_powerdown(void); int semihost_exit(void); int semihost_connected(void); int semihost_disabledebug(void); #endif #ifdef __cplusplus } #endif #endif ================================================ FILE: Zelig/mbed/serial_api.h ================================================ /* mbed Microcontroller Library * Copyright (c) 2006-2013 ARM Limited * * 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 MBED_SERIAL_API_H #define MBED_SERIAL_API_H #include "device.h" #include "buffer.h" #include "dma_api.h" #if DEVICE_SERIAL #define SERIAL_EVENT_TX_SHIFT (2) #define SERIAL_EVENT_RX_SHIFT (8) #define SERIAL_EVENT_TX_MASK (0x00FC) #define SERIAL_EVENT_RX_MASK (0x3F00) #define SERIAL_EVENT_ERROR (1 << 1) /** * @defgroup SerialTXEvents Serial TX Events Macros * * @{ */ #define SERIAL_EVENT_TX_COMPLETE (1 << (SERIAL_EVENT_TX_SHIFT + 0)) #define SERIAL_EVENT_TX_ALL (SERIAL_EVENT_TX_COMPLETE) /**@}*/ /** * @defgroup SerialRXEvents Serial RX Events Macros * * @{ */ #define SERIAL_EVENT_RX_COMPLETE (1 << (SERIAL_EVENT_RX_SHIFT + 0)) #define SERIAL_EVENT_RX_OVERRUN_ERROR (1 << (SERIAL_EVENT_RX_SHIFT + 1)) #define SERIAL_EVENT_RX_FRAMING_ERROR (1 << (SERIAL_EVENT_RX_SHIFT + 2)) #define SERIAL_EVENT_RX_PARITY_ERROR (1 << (SERIAL_EVENT_RX_SHIFT + 3)) #define SERIAL_EVENT_RX_OVERFLOW (1 << (SERIAL_EVENT_RX_SHIFT + 4)) #define SERIAL_EVENT_RX_CHARACTER_MATCH (1 << (SERIAL_EVENT_RX_SHIFT + 5)) #define SERIAL_EVENT_RX_ALL (SERIAL_EVENT_RX_OVERFLOW | SERIAL_EVENT_RX_PARITY_ERROR | \ SERIAL_EVENT_RX_FRAMING_ERROR | SERIAL_EVENT_RX_OVERRUN_ERROR | \ SERIAL_EVENT_RX_COMPLETE | SERIAL_EVENT_RX_CHARACTER_MATCH) /**@}*/ #define SERIAL_RESERVED_CHAR_MATCH (255) typedef enum { ParityNone = 0, ParityOdd = 1, ParityEven = 2, ParityForced1 = 3, ParityForced0 = 4 } SerialParity; typedef enum { RxIrq, TxIrq } SerialIrq; typedef enum { FlowControlNone, FlowControlRTS, FlowControlCTS, FlowControlRTSCTS } FlowControl; typedef void (*uart_irq_handler)(uint32_t id, SerialIrq event); #if DEVICE_SERIAL_ASYNCH /** Asynch serial hal structure */ typedef struct { struct serial_s serial; /**< Target specific serial structure */ struct buffer_s tx_buff; /**< Tx buffer */ struct buffer_s rx_buff; /**< Rx buffer */ uint8_t char_match; /**< Character to be matched */ uint8_t char_found; /**< State of the matched character */ } serial_t; #else /** Non-asynch serial hal structure */ typedef struct serial_s serial_t; #endif #ifdef __cplusplus extern "C" { #endif /** * \defgroup GeneralSerial Serial Configuration Functions * @{ */ /** Initialize the serial peripheral. It sets the default parameters for serial * peripheral, and configure its specifieds pins. * * @param obj The serial object * @param tx The TX pin * @param rx The RX pin */ void serial_init(serial_t *obj, PinName tx, PinName rx); /** Release the serial peripheral, not currently invoked. It requires further * resource management. * * @param obj The serial object */ void serial_free(serial_t *obj); /** Configure the baud rate * * @param obj The serial object * @param baudrate The baud rate to be configured */ void serial_baud(serial_t *obj, int baudrate); /** Configure the format. Set the number of bits, parity and the number of stop bits * * @param obj The serial object * @param data_bits The number of data bits * @param parity The parity * @param stop_bits The number of stop bits */ void serial_format(serial_t *obj, int data_bits, SerialParity parity, int stop_bits); /** The serial interrupt handler registration. * * @param obj The serial object * @param handler The interrupt handler which will be invoked when interrupt fires. * @param id The SerialBase object */ void serial_irq_handler(serial_t *obj, uart_irq_handler handler, uint32_t id); /** Configure serial interrupt. This function is used for word-approach * * @param obj The serial object * @param irq The serial IRQ type (RX or TX) * @param enable Set to non-zero to enable events, or zero to disable them */ void serial_irq_set(serial_t *obj, SerialIrq irq, uint32_t enable); /** Get character. This is a blocking call, waiting for a character * * @param obj The serial object */ int serial_getc(serial_t *obj); /** Put a character. This is a blocking call, waiting for a peripheral to be available * for writing * * @param obj The serial object * @param c The character to be sent */ void serial_putc(serial_t *obj, int c); /** Check if the serial peripheral is readable * * @param obj The serial object * @return Non-zero value if a character can be read, 0 if nothing to read. */ int serial_readable(serial_t *obj); /** Check if the serial peripheral is writable * * @param obj The serial object * @return Non-zero value if a character can be written, 0 otherwise. */ int serial_writable(serial_t *obj); /** Clear the serial peripheral * * @param obj The serial object */ void serial_clear(serial_t *obj); /** Set the break * * @param obj The serial object */ void serial_break_set(serial_t *obj); /** Clear the break * * @param obj The serial object */ void serial_break_clear(serial_t *obj); /** Configure the TX pin for UART function. * * @param tx The pin used for TX */ void serial_pinout_tx(PinName tx); /** Configure the serial for the flow control. It sets flow control in the hardware * if a serial peripheral supports it, otherwise software emulation is used. * * @param obj The serial object * @param type The type of the flow control. Look at the available FlowControl types. * @param rxflow The tx pin * @param txflow The rx pin */ void serial_set_flow_control(serial_t *obj, FlowControl type, PinName rxflow, PinName txflow); #if DEVICE_SERIAL_ASYNCH /**@}*/ /** * \defgroup AsynchSerial Asynchronous Serial Hardware Abstraction Layer * @{ */ /** Begin asynchronous TX transfer. The used buffer is specified in the serial object, * tx_buff * * @param obj The serial object * @param tx The buffer for sending * @param tx_length The number of words to transmit * @param tx_width The bit width of buffer word * @param handler The serial handler * @param event The logical OR of events to be registered * @param hint A suggestion for how to use DMA with this transfer * @return Returns number of data transfered, or 0 otherwise */ int serial_tx_asynch(serial_t *obj, const void *tx, size_t tx_length, uint8_t tx_width, uint32_t handler, uint32_t event, DMAUsage hint); /** Begin asynchronous RX transfer (enable interrupt for data collecting) * The used buffer is specified in the serial object - rx_buff * * @param obj The serial object * @param rx The buffer for sending * @param rx_length The number of words to transmit * @param rx_width The bit width of buffer word * @param handler The serial handler * @param event The logical OR of events to be registered * @param handler The serial handler * @param char_match A character in range 0-254 to be matched * @param hint A suggestion for how to use DMA with this transfer */ void serial_rx_asynch(serial_t *obj, void *rx, size_t rx_length, uint8_t rx_width, uint32_t handler, uint32_t event, uint8_t char_match, DMAUsage hint); /** Attempts to determine if the serial peripheral is already in use for TX * * @param obj The serial object * @return Non-zero if the RX transaction is ongoing, 0 otherwise */ uint8_t serial_tx_active(serial_t *obj); /** Attempts to determine if the serial peripheral is already in use for RX * * @param obj The serial object * @return Non-zero if the RX transaction is ongoing, 0 otherwise */ uint8_t serial_rx_active(serial_t *obj); /** The asynchronous TX and RX handler. * * @param obj The serial object * @return Returns event flags if a RX transfer termination condition was met or 0 otherwise */ int serial_irq_handler_asynch(serial_t *obj); /** Abort the ongoing TX transaction. It disables the enabled interupt for TX and * flush TX hardware buffer if TX FIFO is used * * @param obj The serial object */ void serial_tx_abort_asynch(serial_t *obj); /** Abort the ongoing RX transaction It disables the enabled interrupt for RX and * flush RX hardware buffer if RX FIFO is used * * @param obj The serial object */ void serial_rx_abort_asynch(serial_t *obj); /**@}*/ #endif #ifdef __cplusplus } #endif #endif #endif ================================================ FILE: Zelig/mbed/sleep_api.h ================================================ /* mbed Microcontroller Library * Copyright (c) 2006-2013 ARM Limited * * 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 MBED_SLEEP_API_H #define MBED_SLEEP_API_H #include "device.h" #if DEVICE_SLEEP #ifdef __cplusplus extern "C" { #endif /** Send the microcontroller to sleep * * The processor is setup ready for sleep, and sent to sleep using __WFI(). In this mode, the * system clock to the core is stopped until a reset or an interrupt occurs. This eliminates * dynamic power used by the processor, memory systems and buses. The processor, peripheral and * memory state are maintained, and the peripherals continue to work and can generate interrupts. * * The processor can be woken up by any internal peripheral interrupt or external pin interrupt. * * @note * The mbed interface semihosting is disconnected as part of going to sleep, and can not be restored. * Flash re-programming and the USB serial port will remain active, but the mbed program will no longer be * able to access the LocalFileSystem */ void sleep(void); /** Send the microcontroller to deep sleep * * This processor is setup ready for deep sleep, and sent to sleep using __WFI(). This mode * has the same sleep features as sleep plus it powers down peripherals and clocks. All state * is still maintained. * * The processor can only be woken up by an external interrupt on a pin or a watchdog timer. * * @note * The mbed interface semihosting is disconnected as part of going to sleep, and can not be restored. * Flash re-programming and the USB serial port will remain active, but the mbed program will no longer be * able to access the LocalFileSystem */ void deepsleep(void); #ifdef __cplusplus } #endif #endif #endif ================================================ FILE: Zelig/mbed/spi_api.h ================================================ /* mbed Microcontroller Library * Copyright (c) 2006-2013 ARM Limited * * 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 MBED_SPI_API_H #define MBED_SPI_API_H #include "device.h" #include "dma_api.h" #include "buffer.h" #if DEVICE_SPI #define SPI_EVENT_ERROR (1 << 1) #define SPI_EVENT_COMPLETE (1 << 2) #define SPI_EVENT_RX_OVERFLOW (1 << 3) #define SPI_EVENT_ALL (SPI_EVENT_ERROR | SPI_EVENT_COMPLETE | SPI_EVENT_RX_OVERFLOW) #define SPI_EVENT_INTERNAL_TRANSFER_COMPLETE (1 << 30) // internal flag to report an event occurred #define SPI_FILL_WORD (0xFFFF) #if DEVICE_SPI_ASYNCH /** Asynch spi hal structure */ typedef struct { struct spi_s spi; /**< Target specific spi structure */ struct buffer_s tx_buff; /**< Tx buffer */ struct buffer_s rx_buff; /**< Rx buffer */ } spi_t; #else /** Non-asynch spi hal structure */ typedef struct spi_s spi_t; #endif #ifdef __cplusplus extern "C" { #endif /** * \defgroup GeneralSPI SPI Configuration Functions * @{ */ /** Initialize the SPI peripheral * * Configures the pins used by SPI, sets a default format and frequency, and enables the peripheral * @param[out] obj The SPI object to initialize * @param[in] mosi The pin to use for MOSI * @param[in] miso The pin to use for MISO * @param[in] sclk The pin to use for SCLK * @param[in] ssel The pin to use for SSEL */ void spi_init(spi_t *obj, PinName mosi, PinName miso, PinName sclk, PinName ssel); /** Release a SPI object * * TODO: spi_free is currently unimplemented * This will require reference counting at the C++ level to be safe * * Return the pins owned by the SPI object to their reset state * Disable the SPI peripheral * Disable the SPI clock * @param[in] obj The SPI object to deinitialize */ void spi_free(spi_t *obj); /** Configure the SPI format * * Set the number of bits per frame, configure clock polarity and phase, shift order and master/slave mode * @param[in,out] obj The SPI object to configure * @param[in] bits The number of bits per frame * @param[in] mode The SPI mode (clock polarity, phase, and shift direction) * @param[in] slave Zero for master mode or non-zero for slave mode */ void spi_format(spi_t *obj, int bits, int mode, int slave); /** Set the SPI baud rate * * Actual frequency may differ from the desired frequency due to available dividers and bus clock * Configures the SPI peripheral's baud rate * @param[in,out] obj The SPI object to configure * @param[in] hz The baud rate in Hz */ void spi_frequency(spi_t *obj, int hz); /**@}*/ /** * \defgroup SynchSPI Synchronous SPI Hardware Abstraction Layer * @{ */ /** Write a byte out in master mode and receive a value * * @param[in] obj The SPI peripheral to use for sending * @param[in] value The value to send * @return Returns the value received during send */ int spi_master_write(spi_t *obj, int value); /** Check if a value is available to read * * @param[in] obj The SPI peripheral to check * @return non-zero if a value is available */ int spi_slave_receive(spi_t *obj); /** Get a received value out of the SPI receive buffer in slave mode * * Blocks until a value is available * @param[in] obj The SPI peripheral to read * @return The value received */ int spi_slave_read(spi_t *obj); /** Write a value to the SPI peripheral in slave mode * * Blocks until the SPI peripheral can be written to * @param[in] obj The SPI peripheral to write * @param[in] value The value to write */ void spi_slave_write(spi_t *obj, int value); /** Checks if the specified SPI peripheral is in use * * @param[in] obj The SPI peripheral to check * @return non-zero if the peripheral is currently transmitting */ int spi_busy(spi_t *obj); /** Get the module number * * @param[in] obj The SPI peripheral to check * @return The module number */ uint8_t spi_get_module(spi_t *obj); /**@}*/ #if DEVICE_SPI_ASYNCH /** * \defgroup AsynchSPI Asynchronous SPI Hardware Abstraction Layer * @{ */ /** Begin the SPI transfer. Buffer pointers and lengths are specified in tx_buff and rx_buff * * @param[in] obj The SPI object which holds the transfer information * @param[in] tx The buffer to send * @param[in] tx_length The number of words to transmit * @param[in] rx The buffer to receive * @param[in] rx_length The number of words to receive * @param[in] bit_width The bit width of buffer words * @param[in] event The logical OR of events to be registered * @param[in] handler SPI interrupt handler * @param[in] hint A suggestion for how to use DMA with this transfer */ void spi_master_transfer(spi_t *obj, const void *tx, size_t tx_length, void *rx, size_t rx_length, uint8_t bit_width, uint32_t handler, uint32_t event, DMAUsage hint); /** The asynchronous IRQ handler * * Reads the received values out of the RX FIFO, writes values into the TX FIFO and checks for transfer termination * conditions, such as buffer overflows or transfer complete. * @param[in] obj The SPI object which holds the transfer information * @return event flags if a transfer termination condition was met or 0 otherwise. */ uint32_t spi_irq_handler_asynch(spi_t *obj); /** Attempts to determine if the SPI peripheral is already in use. * * If a temporary DMA channel has been allocated, peripheral is in use. * If a permanent DMA channel has been allocated, check if the DMA channel is in use. If not, proceed as though no DMA * channel were allocated. * If no DMA channel is allocated, check whether tx and rx buffers have been assigned. For each assigned buffer, check * if the corresponding buffer position is less than the buffer length. If buffers do not indicate activity, check if * there are any bytes in the FIFOs. * @param[in] obj The SPI object to check for activity * @return non-zero if the SPI port is active or zero if it is not. */ uint8_t spi_active(spi_t *obj); /** Abort an SPI transfer * * @param obj The SPI peripheral to stop */ void spi_abort_asynch(spi_t *obj); #endif /**@}*/ #ifdef __cplusplus } #endif // __cplusplus #endif // SPI_DEVICE #endif // MBED_SPI_API_H ================================================ FILE: Zelig/mbed/ticker_api.h ================================================ /* mbed Microcontroller Library * Copyright (c) 2015 ARM Limited * * 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 MBED_TICKER_API_H #define MBED_TICKER_API_H #include "device.h" typedef uint32_t timestamp_t; /** Ticker's event structure */ typedef struct ticker_event_s { timestamp_t timestamp; /**< Event's timestamp */ uint32_t id; /**< TimerEvent object */ struct ticker_event_s *next; /**< Next event in the queue */ } ticker_event_t; typedef void (*ticker_event_handler)(uint32_t id); /** Ticker's interface structure - required API for a ticker */ typedef struct { void (*init)(void); /**< Init function */ uint32_t (*read)(void); /**< Read function */ void (*disable_interrupt)(void); /**< Disable interrupt function */ void (*clear_interrupt)(void); /**< Clear interrupt function */ void (*set_interrupt)(timestamp_t timestamp); /**< Set interrupt function */ } ticker_interface_t; /** Tickers events queue structure */ typedef struct { ticker_event_handler event_handler; /**< Event handler */ ticker_event_t *head; /**< A pointer to head */ } ticker_event_queue_t; /** Tickers data structure */ typedef struct { const ticker_interface_t *interface; /**< Ticker's interface */ ticker_event_queue_t *queue; /**< Ticker's events queue */ } ticker_data_t; #ifdef __cplusplus extern "C" { #endif /** Initialize a ticker and sets the event handler * * @param data The ticker's data * @param handler A handler to be set */ void ticker_set_handler(const ticker_data_t *const data, ticker_event_handler handler); /** Irq handler which goes through the events to trigger events in the past. * * @param data The ticker's data */ void ticker_irq_handler(const ticker_data_t *const data); /** Remove an event from the queue * * @param data The ticker's data * @param obj The event's queue to be removed */ void ticker_remove_event(const ticker_data_t *const data, ticker_event_t *obj); /** Insert an event from the queue * * @param data The ticker's data * @param obj The event's queue to be removed * @param timestamp The event's timestamp * @param id The event object */ void ticker_insert_event(const ticker_data_t *const data, ticker_event_t *obj, timestamp_t timestamp, uint32_t id); /** Read the current ticker's timestamp * * @param data The ticker's data * @return The current timestamp */ timestamp_t ticker_read(const ticker_data_t *const data); /** Read the next event's timestamp * * @param data The ticker's data * @return 1 if timestamp is pending event, 0 if there's no event pending */ int ticker_get_next_timestamp(const ticker_data_t *const data, timestamp_t *timestamp); #ifdef __cplusplus } #endif #endif ================================================ FILE: Zelig/mbed/toolchain.h ================================================ /* mbed Microcontroller Library * Copyright (c) 2006-2013 ARM Limited * * 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 MBED_TOOLCHAIN_H #define MBED_TOOLCHAIN_H #if defined(TOOLCHAIN_ARM) #include #endif #ifndef FILEHANDLE typedef int FILEHANDLE; #endif #if defined (__ICCARM__) # define WEAK __weak # define PACKED __packed #else # define WEAK __attribute__((weak)) # define PACKED __attribute__((packed)) #endif #endif ================================================ FILE: Zelig/mbed/us_ticker_api.h ================================================ /* mbed Microcontroller Library * Copyright (c) 2006-2015 ARM Limited * * 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 MBED_US_TICKER_API_H #define MBED_US_TICKER_API_H #include #include "ticker_api.h" #ifdef __cplusplus extern "C" { #endif /** * \defgroup UsTicker Microseconds Ticker Functions * @{ */ /** Get ticker's data * * @return The low power ticker data */ const ticker_data_t* get_us_ticker_data(void); /** The wrapper for ticker_irq_handler, to pass us ticker's data * */ void us_ticker_irq_handler(void); /* HAL us ticker */ /** Initialize the ticker * */ void us_ticker_init(void); /** Read the current counter * * @return The current timer's counter value in microseconds */ uint32_t us_ticker_read(void); /** Set interrupt for specified timestamp * * @param timestamp The time in microseconds to be set */ void us_ticker_set_interrupt(timestamp_t timestamp); /** Disable us ticker interrupt * */ void us_ticker_disable_interrupt(void); /** Clear us ticker interrupt * */ void us_ticker_clear_interrupt(void); /**@}*/ #ifdef __cplusplus } #endif #endif ================================================ FILE: Zelig/mbed/wait_api.h ================================================ /* mbed Microcontroller Library * Copyright (c) 2006-2013 ARM Limited * * 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 MBED_WAIT_API_H #define MBED_WAIT_API_H #ifdef __cplusplus extern "C" { #endif /** Generic wait functions. * * These provide simple NOP type wait capabilities. * * Example: * @code * #include "mbed.h" * * DigitalOut heartbeat(LED1); * * int main() { * while (1) { * heartbeat = 1; * wait(0.5); * heartbeat = 0; * wait(0.5); * } * } */ /** Waits for a number of seconds, with microsecond resolution (within * the accuracy of single precision floating point). * * @param s number of seconds to wait */ void wait(float s); /** Waits a number of milliseconds. * * @param ms the whole number of milliseconds to wait */ void wait_ms(int ms); /** Waits a number of microseconds. * * @param us the whole number of microseconds to wait */ void wait_us(int us); #ifdef __cplusplus } #endif #endif ================================================ FILE: Zelig/os_layer/ARMv7M/Vectors/startup_LPC17xx.S ================================================ /* File: startup_ARMCM3.s * Purpose: startup file for Cortex-M3/M4 devices. Should use with * GNU Tools for ARM Embedded Processors * Version: V1.1 * Date: 17 June 2011 * * Copyright (C) 2011 ARM Limited. All rights reserved. * ARM Limited (ARM) is supplying this software for use with Cortex-M3/M4 * processor based microcontrollers. This file can be freely distributed * within development tools that are supporting such ARM based processors. * * THIS SOFTWARE IS PROVIDED "AS IS". NO WARRANTIES, WHETHER EXPRESS, IMPLIED * OR STATUTORY, INCLUDING, BUT NOT LIMITED TO, IMPLIED WARRANTIES OF * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE APPLY TO THIS SOFTWARE. * ARM SHALL NOT, IN ANY CIRCUMSTANCES, BE LIABLE FOR SPECIAL, INCIDENTAL, OR * CONSEQUENTIAL DAMAGES, FOR ANY REASON WHATSOEVER. */ .syntax unified .arch armv7-m /* Memory Model The HEAP starts at the end of the DATA section and grows upward. The STACK starts at the end of the RAM and grows downward. The HEAP and stack STACK are only checked at compile time: (DATA_SIZE + HEAP_SIZE + STACK_SIZE) < RAM_SIZE This is just a check for the bare minimum for the Heap+Stack area before aborting compilation, it is not the run time limit: Heap_Size + Stack_Size = 0x800 + 0x800 = 0x1000 */ .section .stack .align 3 .ifdef __STACK_SIZE .equ Stack_Size, __STACK_SIZE .else .equ Stack_Size, 0x800 .endif .globl __StackTop .globl __StackLimit __StackLimit: .space Stack_Size .size __StackLimit, . - __StackLimit __StackTop: .size __StackTop, . - __StackTop .section .heap .align 3 .ifdef __HEAP_SIZE .equ Heap_Size, __HEAP_SIZE .else .equ Heap_Size, 0x800 .endif .globl __HeapBase .globl __HeapLimit __HeapBase: .space Heap_Size .size __HeapBase, . - __HeapBase __HeapLimit: .size __HeapLimit, . - __HeapLimit .section .isr_vector .align 2 .globl __isr_vector __isr_vector: .long __StackTop /* Top of Stack */ .long Reset_Handler /* Reset Handler */ .long NMI_Handler /* NMI Handler */ .long HardFault_Handler /* Hard Fault Handler */ .long MemManage_Handler /* MPU Fault Handler */ .long BusFault_Handler /* Bus Fault Handler */ .long UsageFault_Handler /* Usage Fault Handler */ .long 0 /* Reserved */ .long 0 /* Reserved */ .long 0 /* Reserved */ .long 0 /* Reserved */ .long SVC_Handler /* SVCall Handler */ .long DebugMon_Handler /* Debug Monitor Handler */ .long 0 /* Reserved */ .long PendSV_Handler /* PendSV Handler */ .long SysTick_Handler /* SysTick Handler */ /* External interrupts */ .long WDT_IRQHandler /* 16: Watchdog Timer */ .long TIMER0_IRQHandler /* 17: Timer0 */ .long TIMER1_IRQHandler /* 18: Timer1 */ .long TIMER2_IRQHandler /* 19: Timer2 */ .long TIMER3_IRQHandler /* 20: Timer3 */ .long UART0_IRQHandler /* 21: UART0 */ .long UART1_IRQHandler /* 22: UART1 */ .long UART2_IRQHandler /* 23: UART2 */ .long UART3_IRQHandler /* 24: UART3 */ .long PWM1_IRQHandler /* 25: PWM1 */ .long I2C0_IRQHandler /* 26: I2C0 */ .long I2C1_IRQHandler /* 27: I2C1 */ .long I2C2_IRQHandler /* 28: I2C2 */ .long SPI_IRQHandler /* 29: SPI */ .long SSP0_IRQHandler /* 30: SSP0 */ .long SSP1_IRQHandler /* 31: SSP1 */ .long PLL0_IRQHandler /* 32: PLL0 Lock (Main PLL) */ .long RTC_IRQHandler /* 33: Real Time Clock */ .long EINT0_IRQHandler /* 34: External Interrupt 0 */ .long EINT1_IRQHandler /* 35: External Interrupt 1 */ .long EINT2_IRQHandler /* 36: External Interrupt 2 */ .long EINT3_IRQHandler /* 37: External Interrupt 3 */ .long ADC_IRQHandler /* 38: A/D Converter */ .long BOD_IRQHandler /* 39: Brown-Out Detect */ .long USB_IRQHandler /* 40: USB */ .long CAN_IRQHandler /* 41: CAN */ .long DMA_IRQHandler /* 42: General Purpose DMA */ .long I2S_IRQHandler /* 43: I2S */ .long ENET_IRQHandler /* 44: Ethernet */ .long RIT_IRQHandler /* 45: Repetitive Interrupt Timer */ .long MCPWM_IRQHandler /* 46: Motor Control PWM */ .long QEI_IRQHandler /* 47: Quadrature Encoder Interface */ .long PLL1_IRQHandler /* 48: PLL1 Lock (USB PLL) */ .long USBActivity_IRQHandler /* 49: USB Activity */ .long CANActivity_IRQHandler /* 50: CAN Activity */ .size __isr_vector, . - __isr_vector .text .thumb .thumb_func .align 2 .globl Reset_Handler .type Reset_Handler, %function Reset_Handler: /* Loop to copy data from read only memory to RAM. The ranges * of copy from/to are specified by following symbols evaluated in * linker script. * _etext: End of code section, i.e., begin of data sections to copy from. * __data_start__/__data_end__: RAM address range that data should be * copied to. Both must be aligned to 4 bytes boundary. */ ldr r1, =__etext ldr r2, =__data_start__ ldr r3, =__data_end__ .Lflash_to_ram_loop: cmp r2, r3 ittt lt ldrlt r0, [r1], #4 strlt r0, [r2], #4 blt .Lflash_to_ram_loop ldr r0, =SystemInit blx r0 ldr r0, =_start bx r0 .pool .size Reset_Handler, . - Reset_Handler .text /* Macro to define default handlers. Default handler * will be weak symbol and just dead loops. They can be * overwritten by other handlers */ .macro def_default_handler handler_name .align 1 .thumb_func .weak \handler_name .type \handler_name, %function \handler_name : b . .size \handler_name, . - \handler_name .endm def_default_handler NMI_Handler def_default_handler HardFault_Handler def_default_handler MemManage_Handler def_default_handler BusFault_Handler def_default_handler UsageFault_Handler def_default_handler SVC_Handler def_default_handler DebugMon_Handler def_default_handler PendSV_Handler def_default_handler SysTick_Handler def_default_handler Default_Handler .macro def_irq_default_handler handler_name .weak \handler_name .set \handler_name, Default_Handler .endm def_irq_default_handler WDT_IRQHandler def_irq_default_handler TIMER0_IRQHandler def_irq_default_handler TIMER1_IRQHandler def_irq_default_handler TIMER2_IRQHandler def_irq_default_handler TIMER3_IRQHandler def_irq_default_handler UART0_IRQHandler def_irq_default_handler UART1_IRQHandler def_irq_default_handler UART2_IRQHandler def_irq_default_handler UART3_IRQHandler def_irq_default_handler PWM1_IRQHandler def_irq_default_handler I2C0_IRQHandler def_irq_default_handler I2C1_IRQHandler def_irq_default_handler I2C2_IRQHandler def_irq_default_handler SPI_IRQHandler def_irq_default_handler SSP0_IRQHandler def_irq_default_handler SSP1_IRQHandler def_irq_default_handler PLL0_IRQHandler def_irq_default_handler RTC_IRQHandler def_irq_default_handler EINT0_IRQHandler def_irq_default_handler EINT1_IRQHandler def_irq_default_handler EINT2_IRQHandler def_irq_default_handler EINT3_IRQHandler def_irq_default_handler ADC_IRQHandler def_irq_default_handler BOD_IRQHandler def_irq_default_handler USB_IRQHandler def_irq_default_handler CAN_IRQHandler def_irq_default_handler DMA_IRQHandler def_irq_default_handler I2S_IRQHandler def_irq_default_handler ENET_IRQHandler def_irq_default_handler RIT_IRQHandler def_irq_default_handler MCPWM_IRQHandler def_irq_default_handler QEI_IRQHandler def_irq_default_handler PLL1_IRQHandler def_irq_default_handler USBActivity_IRQHandler def_irq_default_handler CANActivity_IRQHandler def_irq_default_handler DEF_IRQHandler .end ================================================ FILE: Zelig/os_layer/ARMv7M/Vectors/startup_MK64F12.S ================================================ /* K64F startup ARM GCC * Purpose: startup file for Cortex-M4 devices. Should use with * GCC for ARM Embedded Processors * Version: V1.2 * Date: 15 Nov 2011 * * Copyright (c) 2011, ARM Limited * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * Neither the name of the ARM Limited 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 ARM LIMITED 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. */ .syntax unified .arch armv7-m /* Memory Model The HEAP starts at the end of the DATA section and grows upward. The STACK starts at the end of the RAM and grows downward. The HEAP and stack STACK are only checked at compile time: (DATA_SIZE + HEAP_SIZE + STACK_SIZE) < RAM_SIZE This is just a check for the bare minimum for the Heap+Stack area before aborting compilation, it is not the run time limit: Heap_Size + Stack_Size = 0x800 + 0x2000 = 0x2800 */ .section .stack .align 3 .ifdef __STACK_SIZE .equ Stack_Size, __STACK_SIZE .else .equ Stack_Size, 0x2000 .endif .globl __StackTop .globl __StackLimit __StackLimit: .space Stack_Size .size __StackLimit, . - __StackLimit __StackTop: .size __StackTop, . - __StackTop .section .heap .align 3 .ifdef __HEAP_SIZE .equ Heap_Size, __HEAP_SIZE .else .equ Heap_Size, 0x800 .endif .globl __HeapBase .globl __HeapLimit __HeapBase: .space Heap_Size .size __HeapBase, . - __HeapBase __HeapLimit: .size __HeapLimit, . - __HeapLimit .section .vector_table,"a",%progbits .align 2 .globl __isr_vector __isr_vector: .long __StackTop /* Top of Stack */ .long Reset_Handler /* Reset Handler */ .long NMI_Handler /* NMI Handler */ .long HardFault_Handler /* Hard Fault Handler */ .long MemManage_Handler /* MPU Fault Handler */ .long BusFault_Handler /* Bus Fault Handler */ .long UsageFault_Handler /* Usage Fault Handler */ .long 0 /* Reserved */ .long 0 /* Reserved */ .long 0 /* Reserved */ .long 0 /* Reserved */ .long SVC_Handler /* SVCall Handler */ .long DebugMon_Handler /* Debug Monitor Handler */ .long 0 /* Reserved */ .long PendSV_Handler /* PendSV Handler */ .long SysTick_Handler /* SysTick Handler */ /* External Interrupts */ .long DMA0_IRQHandler /* DMA Channel 0 Transfer Complete */ .long DMA1_IRQHandler /* DMA Channel 1 Transfer Complete */ .long DMA2_IRQHandler /* DMA Channel 2 Transfer Complete */ .long DMA3_IRQHandler /* DMA Channel 3 Transfer Complete */ .long DMA4_IRQHandler /* DMA Channel 4 Transfer Complete */ .long DMA5_IRQHandler /* DMA Channel 5 Transfer Complete */ .long DMA6_IRQHandler /* DMA Channel 6 Transfer Complete */ .long DMA7_IRQHandler /* DMA Channel 7 Transfer Complete */ .long DMA8_IRQHandler /* DMA Channel 8 Transfer Complete */ .long DMA9_IRQHandler /* DMA Channel 9 Transfer Complete */ .long DMA10_IRQHandler /* DMA Channel 10 Transfer Complete */ .long DMA11_IRQHandler /* DMA Channel 11 Transfer Complete */ .long DMA12_IRQHandler /* DMA Channel 12 Transfer Complete */ .long DMA13_IRQHandler /* DMA Channel 13 Transfer Complete */ .long DMA14_IRQHandler /* DMA Channel 14 Transfer Complete */ .long DMA15_IRQHandler /* DMA Channel 15 Transfer Complete */ .long DMA_Error_IRQHandler /* DMA Error Interrupt */ .long MCM_IRQHandler /* Normal Interrupt */ .long FTFE_IRQHandler /* FTFE Command complete interrupt */ .long Read_Collision_IRQHandler /* Read Collision Interrupt */ .long LVD_LVW_IRQHandler /* Low Voltage Detect, Low Voltage Warning */ .long LLW_IRQHandler /* Low Leakage Wakeup */ .long Watchdog_IRQHandler /* WDOG Interrupt */ .long RNG_IRQHandler /* RNG Interrupt */ .long I2C0_IRQHandler /* I2C0 interrupt */ .long I2C1_IRQHandler /* I2C1 interrupt */ .long SPI0_IRQHandler /* SPI0 Interrupt */ .long SPI1_IRQHandler /* SPI1 Interrupt */ .long I2S0_Tx_IRQHandler /* I2S0 transmit interrupt */ .long I2S0_Rx_IRQHandler /* I2S0 receive interrupt */ .long UART0_LON_IRQHandler /* UART0 LON interrupt */ .long UART0_RX_TX_IRQHandler /* UART0 Receive/Transmit interrupt */ .long UART0_ERR_IRQHandler /* UART0 Error interrupt */ .long UART1_RX_TX_IRQHandler /* UART1 Receive/Transmit interrupt */ .long UART1_ERR_IRQHandler /* UART1 Error interrupt */ .long UART2_RX_TX_IRQHandler /* UART2 Receive/Transmit interrupt */ .long UART2_ERR_IRQHandler /* UART2 Error interrupt */ .long UART3_RX_TX_IRQHandler /* UART3 Receive/Transmit interrupt */ .long UART3_ERR_IRQHandler /* UART3 Error interrupt */ .long ADC0_IRQHandler /* ADC0 interrupt */ .long CMP0_IRQHandler /* CMP0 interrupt */ .long CMP1_IRQHandler /* CMP1 interrupt */ .long FTM0_IRQHandler /* FTM0 fault, overflow and channels interrupt */ .long FTM1_IRQHandler /* FTM1 fault, overflow and channels interrupt */ .long FTM2_IRQHandler /* FTM2 fault, overflow and channels interrupt */ .long CMT_IRQHandler /* CMT interrupt */ .long RTC_IRQHandler /* RTC interrupt */ .long RTC_Seconds_IRQHandler /* RTC seconds interrupt */ .long PIT0_IRQHandler /* PIT timer channel 0 interrupt */ .long PIT1_IRQHandler /* PIT timer channel 1 interrupt */ .long PIT2_IRQHandler /* PIT timer channel 2 interrupt */ .long PIT3_IRQHandler /* PIT timer channel 3 interrupt */ .long PDB0_IRQHandler /* PDB0 Interrupt */ .long USB0_IRQHandler /* USB0 interrupt */ .long USBDCD_IRQHandler /* USBDCD Interrupt */ .long Reserved71_IRQHandler /* Reserved interrupt 71 */ .long DAC0_IRQHandler /* DAC0 interrupt */ .long MCG_IRQHandler /* MCG Interrupt */ .long LPTimer_IRQHandler /* LPTimer interrupt */ .long PORTA_IRQHandler /* Port A interrupt */ .long PORTB_IRQHandler /* Port B interrupt */ .long PORTC_IRQHandler /* Port C interrupt */ .long PORTD_IRQHandler /* Port D interrupt */ .long PORTE_IRQHandler /* Port E interrupt */ .long SWI_IRQHandler /* Software interrupt */ .long SPI2_IRQHandler /* SPI2 Interrupt */ .long UART4_RX_TX_IRQHandler /* UART4 Receive/Transmit interrupt */ .long UART4_ERR_IRQHandler /* UART4 Error interrupt */ .long UART5_RX_TX_IRQHandler /* UART5 Receive/Transmit interrupt */ .long UART5_ERR_IRQHandler /* UART5 Error interrupt */ .long CMP2_IRQHandler /* CMP2 interrupt */ .long FTM3_IRQHandler /* FTM3 fault, overflow and channels interrupt */ .long DAC1_IRQHandler /* DAC1 interrupt */ .long ADC1_IRQHandler /* ADC1 interrupt */ .long I2C2_IRQHandler /* I2C2 interrupt */ .long CAN0_ORed_Message_buffer_IRQHandler /* CAN0 OR'd message buffers interrupt */ .long CAN0_Bus_Off_IRQHandler /* CAN0 bus off interrupt */ .long CAN0_Error_IRQHandler /* CAN0 error interrupt */ .long CAN0_Tx_Warning_IRQHandler /* CAN0 Tx warning interrupt */ .long CAN0_Rx_Warning_IRQHandler /* CAN0 Rx warning interrupt */ .long CAN0_Wake_Up_IRQHandler /* CAN0 wake up interrupt */ .long SDHC_IRQHandler /* SDHC interrupt */ .long ENET_1588_Timer_IRQHandler /* Ethernet MAC IEEE 1588 Timer Interrupt */ .long ENET_Transmit_IRQHandler /* Ethernet MAC Transmit Interrupt */ .long ENET_Receive_IRQHandler /* Ethernet MAC Receive Interrupt */ .long ENET_Error_IRQHandler /* Ethernet MAC Error and miscelaneous Interrupt */ .size __isr_vector, . - __isr_vector .section .text.Reset_Handler .thumb .thumb_func .align 2 .globl Reset_Handler .type Reset_Handler, %function Reset_Handler: /* Loop to copy data from read only memory to RAM. The ranges * of copy from/to are specified by following symbols evaluated in * linker script. * __etext: End of code section, i.e., begin of data sections to copy from. * __data_start__/__data_end__: RAM address range that data should be * copied to. Both must be aligned to 4 bytes boundary. */ disable_watchdog: /* unlock */ ldr r1, =0x4005200e ldr r0, =0xc520 strh r0, [r1] ldr r0, =0xd928 strh r0, [r1] /* disable */ ldr r1, =0x40052000 ldr r0, =0x01d2 strh r0, [r1] ldr r1, =__etext ldr r2, =__data_start__ ldr r3, =__data_end__ subs r3, r2 ble .Lflash_to_ram_loop_end movs r4, 0 .Lflash_to_ram_loop: ldr r0, [r1,r4] str r0, [r2,r4] adds r4, 4 cmp r4, r3 blt .Lflash_to_ram_loop .Lflash_to_ram_loop_end: ldr r0, =SystemInit blx r0 ldr r0, =_start bx r0 .pool .size Reset_Handler, . - Reset_Handler .text /* Macro to define default handlers. Default handler * will be weak symbol and just dead loops. They can be * overwritten by other handlers */ .macro def_default_handler handler_name .align 1 .thumb_func .weak \handler_name .type \handler_name, %function \handler_name : b . .size \handler_name, . - \handler_name .endm /* Exception Handlers */ def_default_handler NMI_Handler def_default_handler HardFault_Handler def_default_handler MemManage_Handler def_default_handler BusFault_Handler def_default_handler UsageFault_Handler def_default_handler SVC_Handler def_default_handler DebugMon_Handler def_default_handler PendSV_Handler def_default_handler SysTick_Handler def_default_handler Default_Handler .macro def_irq_default_handler handler_name .weak \handler_name .set \handler_name, Default_Handler .endm /* IRQ Handlers */ def_irq_default_handler DMA0_IRQHandler def_irq_default_handler DMA1_IRQHandler def_irq_default_handler DMA2_IRQHandler def_irq_default_handler DMA3_IRQHandler def_irq_default_handler DMA4_IRQHandler def_irq_default_handler DMA5_IRQHandler def_irq_default_handler DMA6_IRQHandler def_irq_default_handler DMA7_IRQHandler def_irq_default_handler DMA8_IRQHandler def_irq_default_handler DMA9_IRQHandler def_irq_default_handler DMA10_IRQHandler def_irq_default_handler DMA11_IRQHandler def_irq_default_handler DMA12_IRQHandler def_irq_default_handler DMA13_IRQHandler def_irq_default_handler DMA14_IRQHandler def_irq_default_handler DMA15_IRQHandler def_irq_default_handler DMA_Error_IRQHandler def_irq_default_handler MCM_IRQHandler def_irq_default_handler FTFE_IRQHandler def_irq_default_handler Read_Collision_IRQHandler def_irq_default_handler LVD_LVW_IRQHandler def_irq_default_handler LLW_IRQHandler def_irq_default_handler Watchdog_IRQHandler def_irq_default_handler RNG_IRQHandler def_irq_default_handler I2C0_IRQHandler def_irq_default_handler I2C1_IRQHandler def_irq_default_handler SPI0_IRQHandler def_irq_default_handler SPI1_IRQHandler def_irq_default_handler I2S0_Tx_IRQHandler def_irq_default_handler I2S0_Rx_IRQHandler def_irq_default_handler UART0_LON_IRQHandler def_irq_default_handler UART0_RX_TX_IRQHandler def_irq_default_handler UART0_ERR_IRQHandler def_irq_default_handler UART1_RX_TX_IRQHandler def_irq_default_handler UART1_ERR_IRQHandler def_irq_default_handler UART2_RX_TX_IRQHandler def_irq_default_handler UART2_ERR_IRQHandler def_irq_default_handler UART3_RX_TX_IRQHandler def_irq_default_handler UART3_ERR_IRQHandler def_irq_default_handler ADC0_IRQHandler def_irq_default_handler CMP0_IRQHandler def_irq_default_handler CMP1_IRQHandler def_irq_default_handler FTM0_IRQHandler def_irq_default_handler FTM1_IRQHandler def_irq_default_handler FTM2_IRQHandler def_irq_default_handler CMT_IRQHandler def_irq_default_handler RTC_IRQHandler def_irq_default_handler RTC_Seconds_IRQHandler def_irq_default_handler PIT0_IRQHandler def_irq_default_handler PIT1_IRQHandler def_irq_default_handler PIT2_IRQHandler def_irq_default_handler PIT3_IRQHandler def_irq_default_handler PDB0_IRQHandler def_irq_default_handler USB0_IRQHandler def_irq_default_handler USBDCD_IRQHandler def_irq_default_handler Reserved71_IRQHandler def_irq_default_handler DAC0_IRQHandler def_irq_default_handler MCG_IRQHandler def_irq_default_handler LPTimer_IRQHandler def_irq_default_handler PORTA_IRQHandler def_irq_default_handler PORTB_IRQHandler def_irq_default_handler PORTC_IRQHandler def_irq_default_handler PORTD_IRQHandler def_irq_default_handler PORTE_IRQHandler def_irq_default_handler SWI_IRQHandler def_irq_default_handler SPI2_IRQHandler def_irq_default_handler UART4_RX_TX_IRQHandler def_irq_default_handler UART4_ERR_IRQHandler def_irq_default_handler UART5_RX_TX_IRQHandler def_irq_default_handler UART5_ERR_IRQHandler def_irq_default_handler CMP2_IRQHandler def_irq_default_handler FTM3_IRQHandler def_irq_default_handler DAC1_IRQHandler def_irq_default_handler ADC1_IRQHandler def_irq_default_handler I2C2_IRQHandler def_irq_default_handler CAN0_ORed_Message_buffer_IRQHandler def_irq_default_handler CAN0_Bus_Off_IRQHandler def_irq_default_handler CAN0_Error_IRQHandler def_irq_default_handler CAN0_Tx_Warning_IRQHandler def_irq_default_handler CAN0_Rx_Warning_IRQHandler def_irq_default_handler CAN0_Wake_Up_IRQHandler def_irq_default_handler SDHC_IRQHandler def_irq_default_handler ENET_1588_Timer_IRQHandler def_irq_default_handler ENET_Transmit_IRQHandler def_irq_default_handler ENET_Receive_IRQHandler def_irq_default_handler ENET_Error_IRQHandler def_irq_default_handler DefaultISR /* Flash protection region, placed at 0x400 */ .text .thumb .align 2 .section .kinetis_flash_config_field,"a",%progbits kinetis_flash_config: .long 0xffffffff .long 0xffffffff .long 0xffffffff .long 0xfffffdfe .end ================================================ FILE: Zelig/os_layer/ARMv7M/Vectors/startup_stm32f091xc.S ================================================ /** ****************************************************************************** * @file startup_stm32f091xc.s * @author MCD Application Team * @version V2.1.0 * @date 03-Oct-2014 * @brief STM32F091xC devices vector table for Atollic TrueSTUDIO toolchain. * This module performs: * - Set the initial SP * - Set the initial PC == Reset_Handler, * - Set the vector table entries with the exceptions ISR address * - Branches to main in the C library (which eventually * calls main()). * After Reset the Cortex-M0 processor is in Thread mode, * priority is Privileged, and the Stack is set to Main. ****************************************************************************** * * 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. * ****************************************************************************** */ .syntax unified .cpu cortex-m0 .fpu softvfp .thumb .global g_pfnVectors .global Default_Handler /* start address for the initialization values of the .data section. defined in linker script */ .word _sidata /* start address for the .data section. defined in linker script */ .word _sdata /* end address for the .data section. defined in linker script */ .word _edata /* start address for the .bss section. defined in linker script */ .word _sbss /* end address for the .bss section. defined in linker script */ .word _ebss /** * LLILUM: define stack and heap symbols to accomodate the MSP wrapping on exception thread */ .section .stack .align 3 .ifdef __STACK_SIZE .equ Stack_Size, __STACK_SIZE .else .equ Stack_Size, 0x800 .endif .globl __StackTop .globl __StackLimit __StackLimit: .space Stack_Size .size __StackLimit, . - __StackLimit __StackTop: .size __StackTop, . - __StackTop .section .heap .align 3 .ifdef __HEAP_SIZE .equ Heap_Size, __HEAP_SIZE .else .equ Heap_Size, 0x800 .endif .globl __HeapBase .globl __HeapLimit __HeapBase: .space Heap_Size .size __HeapBase, . - __HeapBase __HeapLimit: .size __HeapLimit, . - __HeapLimit .section .text.Reset_Handler .weak Reset_Handler .type Reset_Handler, %function Reset_Handler: ldr r0, =_estack mov sp, r0 /* set stack pointer */ /* Copy the data segment initializers from flash to SRAM */ movs r1, #0 b LoopCopyDataInit CopyDataInit: ldr r3, =_sidata ldr r3, [r3, r1] str r3, [r0, r1] adds r1, r1, #4 LoopCopyDataInit: ldr r0, =_sdata ldr r3, =_edata adds r2, r0, r1 cmp r2, r3 bcc CopyDataInit ldr r2, =_sbss b LoopFillZerobss /* Zero fill the bss segment. */ FillZerobss: movs r3, #0 str r3, [r2] adds r2, r2, #4 LoopFillZerobss: ldr r3, = _ebss cmp r2, r3 bcc FillZerobss /* Call the clock system intitialization function.*/ bl SystemInit /* Call static constructors */ //bl __libc_init_array /* Call the application's entry point.*/ //bl main /** * Calling the crt0 'cold-start' entry point. There __libc_init_array is called * and when existing hardware_init_hook() and software_init_hook() before * starting main(). software_init_hook() is available and has to be called due * to initializsation when using rtos. */ bl _start LoopForever: b LoopForever .size Reset_Handler, .-Reset_Handler /** * @brief This is the code that gets called when the processor receives an * unexpected interrupt. This simply enters an infinite loop, preserving * the system state for examination by a debugger. * * @param None * @retval : None */ .section .text.Default_Handler,"ax",%progbits Default_Handler: Infinite_Loop: b Infinite_Loop .size Default_Handler, .-Default_Handler /****************************************************************************** * * The minimal vector table for a Cortex M0. Note that the proper constructs * must be placed on this to ensure that it ends up at physical address * 0x0000.0000. * ******************************************************************************/ .section .isr_vector,"a",%progbits .type g_pfnVectors, %object .size g_pfnVectors, .-g_pfnVectors g_pfnVectors: .word _estack .word Reset_Handler .word NMI_Handler .word HardFault_Handler .word 0 .word 0 .word 0 .word 0 .word 0 .word 0 .word 0 .word SVC_Handler .word 0 .word 0 .word PendSV_Handler .word SysTick_Handler .word WWDG_IRQHandler /* Window WatchDog */ .word PVD_VDDIO2_IRQHandler /* PVD and VDDIO2 through EXTI Line detect */ .word RTC_IRQHandler /* RTC through the EXTI line */ .word FLASH_IRQHandler /* FLASH */ .word RCC_CRS_IRQHandler /* RCC and CRS */ .word EXTI0_1_IRQHandler /* EXTI Line 0 and 1 */ .word EXTI2_3_IRQHandler /* EXTI Line 2 and 3 */ .word EXTI4_15_IRQHandler /* EXTI Line 4 to 15 */ .word TSC_IRQHandler /* TSC */ .word DMA1_Ch1_IRQHandler /* DMA1 Channel 1 */ .word DMA1_Ch2_3_DMA2_Ch1_2_IRQHandler /* DMA1 Channel 2 and 3 & DMA2 Channel 1 and 2 */ .word DMA1_Ch4_7_DMA2_Ch3_5_IRQHandler /* DMA1 Channel 4 to 7 & DMA2 Channel 3 to 5 */ .word ADC1_COMP_IRQHandler /* ADC1, COMP1 and COMP2 */ .word TIM1_BRK_UP_TRG_COM_IRQHandler /* TIM1 Break, Update, Trigger and Commutation */ .word TIM1_CC_IRQHandler /* TIM1 Capture Compare */ .word TIM2_IRQHandler /* TIM2 */ .word TIM3_IRQHandler /* TIM3 */ .word TIM6_DAC_IRQHandler /* TIM6 and DAC */ .word TIM7_IRQHandler /* TIM7 */ .word TIM14_IRQHandler /* TIM14 */ .word TIM15_IRQHandler /* TIM15 */ .word TIM16_IRQHandler /* TIM16 */ .word TIM17_IRQHandler /* TIM17 */ .word I2C1_IRQHandler /* I2C1 */ .word I2C2_IRQHandler /* I2C2 */ .word SPI1_IRQHandler /* SPI1 */ .word SPI2_IRQHandler /* SPI2 */ .word USART1_IRQHandler /* USART1 */ .word USART2_IRQHandler /* USART2 */ .word USART3_8_IRQHandler /* USART3, USART4, USART5, USART6, USART7, USART8 */ .word CEC_CAN_IRQHandler /* CEC and CAN */ /******************************************************************************* * * Provide weak aliases for each Exception handler to the Default_Handler. * As they are weak aliases, any function with the same name will override * this definition. * *******************************************************************************/ .weak NMI_Handler .thumb_set NMI_Handler,Default_Handler .weak HardFault_Handler .thumb_set HardFault_Handler,Default_Handler .weak SVC_Handler .thumb_set SVC_Handler,Default_Handler .weak PendSV_Handler .thumb_set PendSV_Handler,Default_Handler .weak SysTick_Handler .thumb_set SysTick_Handler,Default_Handler .weak WWDG_IRQHandler .thumb_set WWDG_IRQHandler,Default_Handler .weak PVD_VDDIO2_IRQHandler .thumb_set PVD_VDDIO2_IRQHandler,Default_Handler .weak RTC_IRQHandler .thumb_set RTC_IRQHandler,Default_Handler .weak FLASH_IRQHandler .thumb_set FLASH_IRQHandler,Default_Handler .weak RCC_CRS_IRQHandler .thumb_set RCC_CRS_IRQHandler,Default_Handler .weak EXTI0_1_IRQHandler .thumb_set EXTI0_1_IRQHandler,Default_Handler .weak EXTI2_3_IRQHandler .thumb_set EXTI2_3_IRQHandler,Default_Handler .weak EXTI4_15_IRQHandler .thumb_set EXTI4_15_IRQHandler,Default_Handler .weak TSC_IRQHandler .thumb_set TSC_IRQHandler,Default_Handler .weak DMA1_Ch1_IRQHandler .thumb_set DMA1_Ch1_IRQHandler,Default_Handler .weak DMA1_Ch2_3_DMA2_Ch1_2_IRQHandler .thumb_set DMA1_Ch2_3_DMA2_Ch1_2_IRQHandler,Default_Handler .weak DMA1_Ch4_7_DMA2_Ch3_5_IRQHandler .thumb_set DMA1_Ch4_7_DMA2_Ch3_5_IRQHandler,Default_Handler .weak ADC1_COMP_IRQHandler .thumb_set ADC1_COMP_IRQHandler,Default_Handler .weak TIM1_BRK_UP_TRG_COM_IRQHandler .thumb_set TIM1_BRK_UP_TRG_COM_IRQHandler,Default_Handler .weak TIM1_CC_IRQHandler .thumb_set TIM1_CC_IRQHandler,Default_Handler .weak TIM2_IRQHandler .thumb_set TIM2_IRQHandler,Default_Handler .weak TIM3_IRQHandler .thumb_set TIM3_IRQHandler,Default_Handler .weak TIM6_DAC_IRQHandler .thumb_set TIM6_DAC_IRQHandler,Default_Handler .weak TIM7_IRQHandler .thumb_set TIM7_IRQHandler,Default_Handler .weak TIM14_IRQHandler .thumb_set TIM14_IRQHandler,Default_Handler .weak TIM15_IRQHandler .thumb_set TIM15_IRQHandler,Default_Handler .weak TIM16_IRQHandler .thumb_set TIM16_IRQHandler,Default_Handler .weak TIM17_IRQHandler .thumb_set TIM17_IRQHandler,Default_Handler .weak I2C1_IRQHandler .thumb_set I2C1_IRQHandler,Default_Handler .weak I2C2_IRQHandler .thumb_set I2C2_IRQHandler,Default_Handler .weak SPI1_IRQHandler .thumb_set SPI1_IRQHandler,Default_Handler .weak SPI2_IRQHandler .thumb_set SPI2_IRQHandler,Default_Handler .weak USART1_IRQHandler .thumb_set USART1_IRQHandler,Default_Handler .weak USART2_IRQHandler .thumb_set USART2_IRQHandler,Default_Handler .weak USART3_8_IRQHandler .thumb_set USART3_8_IRQHandler,Default_Handler .weak CEC_CAN_IRQHandler .thumb_set CEC_CAN_IRQHandler,Default_Handler /************************ (C) COPYRIGHT STMicroelectronics *****END OF FILE****/ ================================================ FILE: Zelig/os_layer/ARMv7M/Vectors/startup_stm32f401xe.S ================================================ /** ****************************************************************************** * @file startup_stm32f401xe.s * @author MCD Application Team * @version V2.3.0 * @date 02-March-2015 * @brief STM32F401xExx Devices vector table for Atollic TrueSTUDIO toolchain. * This module performs: * - Set the initial SP * - Set the initial PC == Reset_Handler, * - Set the vector table entries with the exceptions ISR address * - Branches to main in the C library (which eventually * calls main()). * After Reset the Cortex-M4 processor is in Thread mode, * priority is Privileged, and the Stack is set to Main. ****************************************************************************** * @attention * *

© COPYRIGHT 2015 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. * ****************************************************************************** */ .syntax unified .cpu cortex-m4 .fpu softvfp .thumb .global g_pfnVectors .global Default_Handler /* start address for the initialization values of the .data section. defined in linker script */ .word _sidata /* start address for the .data section. defined in linker script */ .word _sdata /* end address for the .data section. defined in linker script */ .word _edata /* start address for the .bss section. defined in linker script */ .word _sbss /* end address for the .bss section. defined in linker script */ .word _ebss /* stack used for SystemInit_ExtMemCtl; always internal RAM used */ /** * LLILUM: define stack and heap symbols to accomodate the MSP wrapping on exception thread */ .section .stack .align 3 .ifdef __STACK_SIZE .equ Stack_Size, __STACK_SIZE .else .equ Stack_Size, 0x800 .endif .globl __StackTop .globl __StackLimit __StackLimit: .space Stack_Size .size __StackLimit, . - __StackLimit __StackTop: .size __StackTop, . - __StackTop .section .heap .align 3 .ifdef __HEAP_SIZE .equ Heap_Size, __HEAP_SIZE .else .equ Heap_Size, 0x800 .endif .globl __HeapBase .globl __HeapLimit __HeapBase: .space Heap_Size .size __HeapBase, . - __HeapBase __HeapLimit: .size __HeapLimit, . - __HeapLimit /** * @brief This is the code that gets called when the processor first * starts execution following a reset event. Only the absolutely * necessary set is performed, after which the application * supplied main() routine is called. * @param None * @retval : None */ .section .text.Reset_Handler .weak Reset_Handler .type Reset_Handler, %function Reset_Handler: ldr sp, =_estack /* set stack pointer */ /* Copy the data segment initializers from flash to SRAM */ movs r1, #0 b LoopCopyDataInit CopyDataInit: ldr r3, =_sidata ldr r3, [r3, r1] str r3, [r0, r1] adds r1, r1, #4 LoopCopyDataInit: ldr r0, =_sdata ldr r3, =_edata adds r2, r0, r1 cmp r2, r3 bcc CopyDataInit ldr r2, =_sbss b LoopFillZerobss /* Zero fill the bss segment. */ FillZerobss: movs r3, #0 str r3, [r2], #4 LoopFillZerobss: ldr r3, = _ebss cmp r2, r3 bcc FillZerobss /* Call the clock system intitialization function.*/ bl SystemInit /* Call static constructors */ //bl __libc_init_array /* Call the application's entry point.*/ //bl main // Calling the crt0 'cold-start' entry point. There __libc_init_array is called // and when existing hardware_init_hook() and software_init_hook() before // starting main(). software_init_hook() is available and has to be called due // to initializsation when using rtos. bl _start bx lr .size Reset_Handler, .-Reset_Handler /** * @brief This is the code that gets called when the processor receives an * unexpected interrupt. This simply enters an infinite loop, preserving * the system state for examination by a debugger. * @param None * @retval None */ .section .text.Default_Handler,"ax",%progbits Default_Handler: Infinite_Loop: b Infinite_Loop .size Default_Handler, .-Default_Handler /****************************************************************************** * * The minimal vector table for a Cortex M3. Note that the proper constructs * must be placed on this to ensure that it ends up at physical address * 0x0000.0000. * *******************************************************************************/ .section .isr_vector,"a",%progbits .type g_pfnVectors, %object .size g_pfnVectors, .-g_pfnVectors g_pfnVectors: .word _estack .word Reset_Handler .word NMI_Handler .word HardFault_Handler .word MemManage_Handler .word BusFault_Handler .word UsageFault_Handler .word 0 .word 0 .word 0 .word 0 .word SVC_Handler .word DebugMon_Handler .word 0 .word PendSV_Handler .word SysTick_Handler /* External Interrupts */ .word WWDG_IRQHandler /* Window WatchDog */ .word PVD_IRQHandler /* PVD through EXTI Line detection */ .word TAMP_STAMP_IRQHandler /* Tamper and TimeStamps through the EXTI line */ .word RTC_WKUP_IRQHandler /* RTC Wakeup through the EXTI line */ .word FLASH_IRQHandler /* FLASH */ .word RCC_IRQHandler /* RCC */ .word EXTI0_IRQHandler /* EXTI Line0 */ .word EXTI1_IRQHandler /* EXTI Line1 */ .word EXTI2_IRQHandler /* EXTI Line2 */ .word EXTI3_IRQHandler /* EXTI Line3 */ .word EXTI4_IRQHandler /* EXTI Line4 */ .word DMA1_Stream0_IRQHandler /* DMA1 Stream 0 */ .word DMA1_Stream1_IRQHandler /* DMA1 Stream 1 */ .word DMA1_Stream2_IRQHandler /* DMA1 Stream 2 */ .word DMA1_Stream3_IRQHandler /* DMA1 Stream 3 */ .word DMA1_Stream4_IRQHandler /* DMA1 Stream 4 */ .word DMA1_Stream5_IRQHandler /* DMA1 Stream 5 */ .word DMA1_Stream6_IRQHandler /* DMA1 Stream 6 */ .word ADC_IRQHandler /* ADC1, ADC2 and ADC3s */ .word 0 /* Reserved */ .word 0 /* Reserved */ .word 0 /* Reserved */ .word 0 /* Reserved */ .word EXTI9_5_IRQHandler /* External Line[9:5]s */ .word TIM1_BRK_TIM9_IRQHandler /* TIM1 Break and TIM9 */ .word TIM1_UP_TIM10_IRQHandler /* TIM1 Update and TIM10 */ .word TIM1_TRG_COM_TIM11_IRQHandler /* TIM1 Trigger and Commutation and TIM11 */ .word TIM1_CC_IRQHandler /* TIM1 Capture Compare */ .word TIM2_IRQHandler /* TIM2 */ .word TIM3_IRQHandler /* TIM3 */ .word TIM4_IRQHandler /* TIM4 */ .word I2C1_EV_IRQHandler /* I2C1 Event */ .word I2C1_ER_IRQHandler /* I2C1 Error */ .word I2C2_EV_IRQHandler /* I2C2 Event */ .word I2C2_ER_IRQHandler /* I2C2 Error */ .word SPI1_IRQHandler /* SPI1 */ .word SPI2_IRQHandler /* SPI2 */ .word USART1_IRQHandler /* USART1 */ .word USART2_IRQHandler /* USART2 */ .word 0 /* Reserved */ .word EXTI15_10_IRQHandler /* External Line[15:10]s */ .word RTC_Alarm_IRQHandler /* RTC Alarm (A and B) through EXTI Line */ .word OTG_FS_WKUP_IRQHandler /* USB OTG FS Wakeup through EXTI line */ .word 0 /* Reserved */ .word 0 /* Reserved */ .word 0 /* Reserved */ .word 0 /* Reserved */ .word DMA1_Stream7_IRQHandler /* DMA1 Stream7 */ .word 0 /* Reserved */ .word SDIO_IRQHandler /* SDIO */ .word TIM5_IRQHandler /* TIM5 */ .word SPI3_IRQHandler /* SPI3 */ .word 0 /* Reserved */ .word 0 /* Reserved */ .word 0 /* Reserved */ .word 0 /* Reserved */ .word DMA2_Stream0_IRQHandler /* DMA2 Stream 0 */ .word DMA2_Stream1_IRQHandler /* DMA2 Stream 1 */ .word DMA2_Stream2_IRQHandler /* DMA2 Stream 2 */ .word DMA2_Stream3_IRQHandler /* DMA2 Stream 3 */ .word DMA2_Stream4_IRQHandler /* DMA2 Stream 4 */ .word 0 /* Reserved */ .word 0 /* Reserved */ .word 0 /* Reserved */ .word 0 /* Reserved */ .word 0 /* Reserved */ .word 0 /* Reserved */ .word OTG_FS_IRQHandler /* USB OTG FS */ .word DMA2_Stream5_IRQHandler /* DMA2 Stream 5 */ .word DMA2_Stream6_IRQHandler /* DMA2 Stream 6 */ .word DMA2_Stream7_IRQHandler /* DMA2 Stream 7 */ .word USART6_IRQHandler /* USART6 */ .word I2C3_EV_IRQHandler /* I2C3 event */ .word I2C3_ER_IRQHandler /* I2C3 error */ .word 0 /* Reserved */ .word 0 /* Reserved */ .word 0 /* Reserved */ .word 0 /* Reserved */ .word 0 /* Reserved */ .word 0 /* Reserved */ .word 0 /* Reserved */ .word FPU_IRQHandler /* FPU */ .word 0 /* Reserved */ .word 0 /* Reserved */ .word SPI4_IRQHandler /* SPI4 */ /******************************************************************************* * * Provide weak aliases for each Exception handler to the Default_Handler. * As they are weak aliases, any function with the same name will override * this definition. * *******************************************************************************/ .weak NMI_Handler .thumb_set NMI_Handler,Default_Handler .weak HardFault_Handler .thumb_set HardFault_Handler,Default_Handler .weak MemManage_Handler .thumb_set MemManage_Handler,Default_Handler .weak BusFault_Handler .thumb_set BusFault_Handler,Default_Handler .weak UsageFault_Handler .thumb_set UsageFault_Handler,Default_Handler .weak SVC_Handler .thumb_set SVC_Handler,Default_Handler .weak DebugMon_Handler .thumb_set DebugMon_Handler,Default_Handler .weak PendSV_Handler .thumb_set PendSV_Handler,Default_Handler .weak SysTick_Handler .thumb_set SysTick_Handler,Default_Handler .weak WWDG_IRQHandler .thumb_set WWDG_IRQHandler,Default_Handler .weak PVD_IRQHandler .thumb_set PVD_IRQHandler,Default_Handler .weak TAMP_STAMP_IRQHandler .thumb_set TAMP_STAMP_IRQHandler,Default_Handler .weak RTC_WKUP_IRQHandler .thumb_set RTC_WKUP_IRQHandler,Default_Handler .weak FLASH_IRQHandler .thumb_set FLASH_IRQHandler,Default_Handler .weak RCC_IRQHandler .thumb_set RCC_IRQHandler,Default_Handler .weak EXTI0_IRQHandler .thumb_set EXTI0_IRQHandler,Default_Handler .weak EXTI1_IRQHandler .thumb_set EXTI1_IRQHandler,Default_Handler .weak EXTI2_IRQHandler .thumb_set EXTI2_IRQHandler,Default_Handler .weak EXTI3_IRQHandler .thumb_set EXTI3_IRQHandler,Default_Handler .weak EXTI4_IRQHandler .thumb_set EXTI4_IRQHandler,Default_Handler .weak DMA1_Stream0_IRQHandler .thumb_set DMA1_Stream0_IRQHandler,Default_Handler .weak DMA1_Stream1_IRQHandler .thumb_set DMA1_Stream1_IRQHandler,Default_Handler .weak DMA1_Stream2_IRQHandler .thumb_set DMA1_Stream2_IRQHandler,Default_Handler .weak DMA1_Stream3_IRQHandler .thumb_set DMA1_Stream3_IRQHandler,Default_Handler .weak DMA1_Stream4_IRQHandler .thumb_set DMA1_Stream4_IRQHandler,Default_Handler .weak DMA1_Stream5_IRQHandler .thumb_set DMA1_Stream5_IRQHandler,Default_Handler .weak DMA1_Stream6_IRQHandler .thumb_set DMA1_Stream6_IRQHandler,Default_Handler .weak ADC_IRQHandler .thumb_set ADC_IRQHandler,Default_Handler .weak EXTI9_5_IRQHandler .thumb_set EXTI9_5_IRQHandler,Default_Handler .weak TIM1_BRK_TIM9_IRQHandler .thumb_set TIM1_BRK_TIM9_IRQHandler,Default_Handler .weak TIM1_UP_TIM10_IRQHandler .thumb_set TIM1_UP_TIM10_IRQHandler,Default_Handler .weak TIM1_TRG_COM_TIM11_IRQHandler .thumb_set TIM1_TRG_COM_TIM11_IRQHandler,Default_Handler .weak TIM1_CC_IRQHandler .thumb_set TIM1_CC_IRQHandler,Default_Handler .weak TIM2_IRQHandler .thumb_set TIM2_IRQHandler,Default_Handler .weak TIM3_IRQHandler .thumb_set TIM3_IRQHandler,Default_Handler .weak TIM4_IRQHandler .thumb_set TIM4_IRQHandler,Default_Handler .weak I2C1_EV_IRQHandler .thumb_set I2C1_EV_IRQHandler,Default_Handler .weak I2C1_ER_IRQHandler .thumb_set I2C1_ER_IRQHandler,Default_Handler .weak I2C2_EV_IRQHandler .thumb_set I2C2_EV_IRQHandler,Default_Handler .weak I2C2_ER_IRQHandler .thumb_set I2C2_ER_IRQHandler,Default_Handler .weak SPI1_IRQHandler .thumb_set SPI1_IRQHandler,Default_Handler .weak SPI2_IRQHandler .thumb_set SPI2_IRQHandler,Default_Handler .weak USART1_IRQHandler .thumb_set USART1_IRQHandler,Default_Handler .weak USART2_IRQHandler .thumb_set USART2_IRQHandler,Default_Handler .weak EXTI15_10_IRQHandler .thumb_set EXTI15_10_IRQHandler,Default_Handler .weak RTC_Alarm_IRQHandler .thumb_set RTC_Alarm_IRQHandler,Default_Handler .weak OTG_FS_WKUP_IRQHandler .thumb_set OTG_FS_WKUP_IRQHandler,Default_Handler .weak DMA1_Stream7_IRQHandler .thumb_set DMA1_Stream7_IRQHandler,Default_Handler .weak SDIO_IRQHandler .thumb_set SDIO_IRQHandler,Default_Handler .weak TIM5_IRQHandler .thumb_set TIM5_IRQHandler,Default_Handler .weak SPI3_IRQHandler .thumb_set SPI3_IRQHandler,Default_Handler .weak DMA2_Stream0_IRQHandler .thumb_set DMA2_Stream0_IRQHandler,Default_Handler .weak DMA2_Stream1_IRQHandler .thumb_set DMA2_Stream1_IRQHandler,Default_Handler .weak DMA2_Stream2_IRQHandler .thumb_set DMA2_Stream2_IRQHandler,Default_Handler .weak DMA2_Stream3_IRQHandler .thumb_set DMA2_Stream3_IRQHandler,Default_Handler .weak DMA2_Stream4_IRQHandler .thumb_set DMA2_Stream4_IRQHandler,Default_Handler .weak OTG_FS_IRQHandler .thumb_set OTG_FS_IRQHandler,Default_Handler .weak DMA2_Stream5_IRQHandler .thumb_set DMA2_Stream5_IRQHandler,Default_Handler .weak DMA2_Stream6_IRQHandler .thumb_set DMA2_Stream6_IRQHandler,Default_Handler .weak DMA2_Stream7_IRQHandler .thumb_set DMA2_Stream7_IRQHandler,Default_Handler .weak USART6_IRQHandler .thumb_set USART6_IRQHandler,Default_Handler .weak I2C3_EV_IRQHandler .thumb_set I2C3_EV_IRQHandler,Default_Handler .weak I2C3_ER_IRQHandler .thumb_set I2C3_ER_IRQHandler,Default_Handler .weak FPU_IRQHandler .thumb_set FPU_IRQHandler,Default_Handler .weak SPI4_IRQHandler .thumb_set SPI4_IRQHandler,Default_Handler /************************ (C) COPYRIGHT STMicroelectronics *****END OF FILE****/ ================================================ FILE: Zelig/os_layer/ARMv7M/Vectors/startup_stm32f411xe.S ================================================ /** ****************************************************************************** * @file startup_stm32f411xe.s * @author MCD Application Team * @version V2.3.0 * @date 02-March-2015 * @brief STM32F411xExx Devices vector table for Atollic TrueSTUDIO toolchain. * This module performs: * - Set the initial SP * - Set the initial PC == Reset_Handler, * - Set the vector table entries with the exceptions ISR address * - Branches to main in the C library (which eventually * calls main()). * After Reset the Cortex-M4 processor is in Thread mode, * priority is Privileged, and the Stack is set to Main. ****************************************************************************** * @attention * *

© COPYRIGHT 2015 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. * ****************************************************************************** */ .syntax unified .cpu cortex-m4 .fpu softvfp .thumb .global g_pfnVectors .global Default_Handler /* start address for the initialization values of the .data section. defined in linker script */ .word _sidata /* start address for the .data section. defined in linker script */ .word _sdata /* end address for the .data section. defined in linker script */ .word _edata /* start address for the .bss section. defined in linker script */ .word _sbss /* end address for the .bss section. defined in linker script */ .word _ebss /* stack used for SystemInit_ExtMemCtl; always internal RAM used */ /** * LLILUM: define stack and heap symbols to accomodate the MSP wrapping on exception thread */ .section .stack .align 3 .ifdef __STACK_SIZE .equ Stack_Size, __STACK_SIZE .else .equ Stack_Size, 0x800 .endif .globl __StackTop .globl __StackLimit __StackLimit: .space Stack_Size .size __StackLimit, . - __StackLimit __StackTop: .size __StackTop, . - __StackTop .section .heap .align 3 .ifdef __HEAP_SIZE .equ Heap_Size, __HEAP_SIZE .else .equ Heap_Size, 0x800 .endif .globl __HeapBase .globl __HeapLimit __HeapBase: .space Heap_Size .size __HeapBase, . - __HeapBase __HeapLimit: .size __HeapLimit, . - __HeapLimit /** * @brief This is the code that gets called when the processor first * starts execution following a reset event. Only the absolutely * necessary set is performed, after which the application * supplied main() routine is called. * @param None * @retval : None */ .section .text.Reset_Handler .weak Reset_Handler .type Reset_Handler, %function Reset_Handler: ldr sp, =_estack /* set stack pointer */ /* Copy the data segment initializers from flash to SRAM */ movs r1, #0 b LoopCopyDataInit CopyDataInit: ldr r3, =_sidata ldr r3, [r3, r1] str r3, [r0, r1] adds r1, r1, #4 LoopCopyDataInit: ldr r0, =_sdata ldr r3, =_edata adds r2, r0, r1 cmp r2, r3 bcc CopyDataInit ldr r2, =_sbss b LoopFillZerobss /* Zero fill the bss segment. */ FillZerobss: movs r3, #0 str r3, [r2], #4 LoopFillZerobss: ldr r3, = _ebss cmp r2, r3 bcc FillZerobss /* Call the clock system intitialization function.*/ bl SystemInit /* Call static constructors */ //bl __libc_init_array /* Call the application's entry point.*/ //bl main // Calling the crt0 'cold-start' entry point. There __libc_init_array is called // and when existing hardware_init_hook() and software_init_hook() before // starting main(). software_init_hook() is available and has to be called due // to initializsation when using rtos. bl _start bx lr .size Reset_Handler, .-Reset_Handler /** * @brief This is the code that gets called when the processor receives an * unexpected interrupt. This simply enters an infinite loop, preserving * the system state for examination by a debugger. * @param None * @retval None */ .section .text.Default_Handler,"ax",%progbits Default_Handler: Infinite_Loop: b Infinite_Loop .size Default_Handler, .-Default_Handler /****************************************************************************** * * The minimal vector table for a Cortex M3. Note that the proper constructs * must be placed on this to ensure that it ends up at physical address * 0x0000.0000. * *******************************************************************************/ .section .isr_vector,"a",%progbits .type g_pfnVectors, %object .size g_pfnVectors, .-g_pfnVectors g_pfnVectors: .word _estack .word Reset_Handler .word NMI_Handler .word HardFault_Handler .word MemManage_Handler .word BusFault_Handler .word UsageFault_Handler .word 0 .word 0 .word 0 .word 0 .word SVC_Handler .word DebugMon_Handler .word 0 .word PendSV_Handler .word SysTick_Handler /* External Interrupts */ .word WWDG_IRQHandler /* Window WatchDog */ .word PVD_IRQHandler /* PVD through EXTI Line detection */ .word TAMP_STAMP_IRQHandler /* Tamper and TimeStamps through the EXTI line */ .word RTC_WKUP_IRQHandler /* RTC Wakeup through the EXTI line */ .word FLASH_IRQHandler /* FLASH */ .word RCC_IRQHandler /* RCC */ .word EXTI0_IRQHandler /* EXTI Line0 */ .word EXTI1_IRQHandler /* EXTI Line1 */ .word EXTI2_IRQHandler /* EXTI Line2 */ .word EXTI3_IRQHandler /* EXTI Line3 */ .word EXTI4_IRQHandler /* EXTI Line4 */ .word DMA1_Stream0_IRQHandler /* DMA1 Stream 0 */ .word DMA1_Stream1_IRQHandler /* DMA1 Stream 1 */ .word DMA1_Stream2_IRQHandler /* DMA1 Stream 2 */ .word DMA1_Stream3_IRQHandler /* DMA1 Stream 3 */ .word DMA1_Stream4_IRQHandler /* DMA1 Stream 4 */ .word DMA1_Stream5_IRQHandler /* DMA1 Stream 5 */ .word DMA1_Stream6_IRQHandler /* DMA1 Stream 6 */ .word ADC_IRQHandler /* ADC1, ADC2 and ADC3s */ .word 0 /* Reserved */ .word 0 /* Reserved */ .word 0 /* Reserved */ .word 0 /* Reserved */ .word EXTI9_5_IRQHandler /* External Line[9:5]s */ .word TIM1_BRK_TIM9_IRQHandler /* TIM1 Break and TIM9 */ .word TIM1_UP_TIM10_IRQHandler /* TIM1 Update and TIM10 */ .word TIM1_TRG_COM_TIM11_IRQHandler /* TIM1 Trigger and Commutation and TIM11 */ .word TIM1_CC_IRQHandler /* TIM1 Capture Compare */ .word TIM2_IRQHandler /* TIM2 */ .word TIM3_IRQHandler /* TIM3 */ .word TIM4_IRQHandler /* TIM4 */ .word I2C1_EV_IRQHandler /* I2C1 Event */ .word I2C1_ER_IRQHandler /* I2C1 Error */ .word I2C2_EV_IRQHandler /* I2C2 Event */ .word I2C2_ER_IRQHandler /* I2C2 Error */ .word SPI1_IRQHandler /* SPI1 */ .word SPI2_IRQHandler /* SPI2 */ .word USART1_IRQHandler /* USART1 */ .word USART2_IRQHandler /* USART2 */ .word 0 /* Reserved */ .word EXTI15_10_IRQHandler /* External Line[15:10]s */ .word RTC_Alarm_IRQHandler /* RTC Alarm (A and B) through EXTI Line */ .word OTG_FS_WKUP_IRQHandler /* USB OTG FS Wakeup through EXTI line */ .word 0 /* Reserved */ .word 0 /* Reserved */ .word 0 /* Reserved */ .word 0 /* Reserved */ .word DMA1_Stream7_IRQHandler /* DMA1 Stream7 */ .word 0 /* Reserved */ .word SDIO_IRQHandler /* SDIO */ .word TIM5_IRQHandler /* TIM5 */ .word SPI3_IRQHandler /* SPI3 */ .word 0 /* Reserved */ .word 0 /* Reserved */ .word 0 /* Reserved */ .word 0 /* Reserved */ .word DMA2_Stream0_IRQHandler /* DMA2 Stream 0 */ .word DMA2_Stream1_IRQHandler /* DMA2 Stream 1 */ .word DMA2_Stream2_IRQHandler /* DMA2 Stream 2 */ .word DMA2_Stream3_IRQHandler /* DMA2 Stream 3 */ .word DMA2_Stream4_IRQHandler /* DMA2 Stream 4 */ .word 0 /* Reserved */ .word 0 /* Reserved */ .word 0 /* Reserved */ .word 0 /* Reserved */ .word 0 /* Reserved */ .word 0 /* Reserved */ .word OTG_FS_IRQHandler /* USB OTG FS */ .word DMA2_Stream5_IRQHandler /* DMA2 Stream 5 */ .word DMA2_Stream6_IRQHandler /* DMA2 Stream 6 */ .word DMA2_Stream7_IRQHandler /* DMA2 Stream 7 */ .word USART6_IRQHandler /* USART6 */ .word I2C3_EV_IRQHandler /* I2C3 event */ .word I2C3_ER_IRQHandler /* I2C3 error */ .word 0 /* Reserved */ .word 0 /* Reserved */ .word 0 /* Reserved */ .word 0 /* Reserved */ .word 0 /* Reserved */ .word 0 /* Reserved */ .word 0 /* Reserved */ .word FPU_IRQHandler /* FPU */ .word 0 /* Reserved */ .word 0 /* Reserved */ .word SPI4_IRQHandler /* SPI4 */ .word SPI5_IRQHandler /* SPI5 */ /******************************************************************************* * * Provide weak aliases for each Exception handler to the Default_Handler. * As they are weak aliases, any function with the same name will override * this definition. * *******************************************************************************/ .weak NMI_Handler .thumb_set NMI_Handler,Default_Handler .weak HardFault_Handler .thumb_set HardFault_Handler,Default_Handler .weak MemManage_Handler .thumb_set MemManage_Handler,Default_Handler .weak BusFault_Handler .thumb_set BusFault_Handler,Default_Handler .weak UsageFault_Handler .thumb_set UsageFault_Handler,Default_Handler .weak SVC_Handler .thumb_set SVC_Handler,Default_Handler .weak DebugMon_Handler .thumb_set DebugMon_Handler,Default_Handler .weak PendSV_Handler .thumb_set PendSV_Handler,Default_Handler .weak SysTick_Handler .thumb_set SysTick_Handler,Default_Handler .weak WWDG_IRQHandler .thumb_set WWDG_IRQHandler,Default_Handler .weak PVD_IRQHandler .thumb_set PVD_IRQHandler,Default_Handler .weak TAMP_STAMP_IRQHandler .thumb_set TAMP_STAMP_IRQHandler,Default_Handler .weak RTC_WKUP_IRQHandler .thumb_set RTC_WKUP_IRQHandler,Default_Handler .weak FLASH_IRQHandler .thumb_set FLASH_IRQHandler,Default_Handler .weak RCC_IRQHandler .thumb_set RCC_IRQHandler,Default_Handler .weak EXTI0_IRQHandler .thumb_set EXTI0_IRQHandler,Default_Handler .weak EXTI1_IRQHandler .thumb_set EXTI1_IRQHandler,Default_Handler .weak EXTI2_IRQHandler .thumb_set EXTI2_IRQHandler,Default_Handler .weak EXTI3_IRQHandler .thumb_set EXTI3_IRQHandler,Default_Handler .weak EXTI4_IRQHandler .thumb_set EXTI4_IRQHandler,Default_Handler .weak DMA1_Stream0_IRQHandler .thumb_set DMA1_Stream0_IRQHandler,Default_Handler .weak DMA1_Stream1_IRQHandler .thumb_set DMA1_Stream1_IRQHandler,Default_Handler .weak DMA1_Stream2_IRQHandler .thumb_set DMA1_Stream2_IRQHandler,Default_Handler .weak DMA1_Stream3_IRQHandler .thumb_set DMA1_Stream3_IRQHandler,Default_Handler .weak DMA1_Stream4_IRQHandler .thumb_set DMA1_Stream4_IRQHandler,Default_Handler .weak DMA1_Stream5_IRQHandler .thumb_set DMA1_Stream5_IRQHandler,Default_Handler .weak DMA1_Stream6_IRQHandler .thumb_set DMA1_Stream6_IRQHandler,Default_Handler .weak ADC_IRQHandler .thumb_set ADC_IRQHandler,Default_Handler .weak EXTI9_5_IRQHandler .thumb_set EXTI9_5_IRQHandler,Default_Handler .weak TIM1_BRK_TIM9_IRQHandler .thumb_set TIM1_BRK_TIM9_IRQHandler,Default_Handler .weak TIM1_UP_TIM10_IRQHandler .thumb_set TIM1_UP_TIM10_IRQHandler,Default_Handler .weak TIM1_TRG_COM_TIM11_IRQHandler .thumb_set TIM1_TRG_COM_TIM11_IRQHandler,Default_Handler .weak TIM1_CC_IRQHandler .thumb_set TIM1_CC_IRQHandler,Default_Handler .weak TIM2_IRQHandler .thumb_set TIM2_IRQHandler,Default_Handler .weak TIM3_IRQHandler .thumb_set TIM3_IRQHandler,Default_Handler .weak TIM4_IRQHandler .thumb_set TIM4_IRQHandler,Default_Handler .weak I2C1_EV_IRQHandler .thumb_set I2C1_EV_IRQHandler,Default_Handler .weak I2C1_ER_IRQHandler .thumb_set I2C1_ER_IRQHandler,Default_Handler .weak I2C2_EV_IRQHandler .thumb_set I2C2_EV_IRQHandler,Default_Handler .weak I2C2_ER_IRQHandler .thumb_set I2C2_ER_IRQHandler,Default_Handler .weak SPI1_IRQHandler .thumb_set SPI1_IRQHandler,Default_Handler .weak SPI2_IRQHandler .thumb_set SPI2_IRQHandler,Default_Handler .weak USART1_IRQHandler .thumb_set USART1_IRQHandler,Default_Handler .weak USART2_IRQHandler .thumb_set USART2_IRQHandler,Default_Handler .weak EXTI15_10_IRQHandler .thumb_set EXTI15_10_IRQHandler,Default_Handler .weak RTC_Alarm_IRQHandler .thumb_set RTC_Alarm_IRQHandler,Default_Handler .weak OTG_FS_WKUP_IRQHandler .thumb_set OTG_FS_WKUP_IRQHandler,Default_Handler .weak DMA1_Stream7_IRQHandler .thumb_set DMA1_Stream7_IRQHandler,Default_Handler .weak SDIO_IRQHandler .thumb_set SDIO_IRQHandler,Default_Handler .weak TIM5_IRQHandler .thumb_set TIM5_IRQHandler,Default_Handler .weak SPI3_IRQHandler .thumb_set SPI3_IRQHandler,Default_Handler .weak DMA2_Stream0_IRQHandler .thumb_set DMA2_Stream0_IRQHandler,Default_Handler .weak DMA2_Stream1_IRQHandler .thumb_set DMA2_Stream1_IRQHandler,Default_Handler .weak DMA2_Stream2_IRQHandler .thumb_set DMA2_Stream2_IRQHandler,Default_Handler .weak DMA2_Stream3_IRQHandler .thumb_set DMA2_Stream3_IRQHandler,Default_Handler .weak DMA2_Stream4_IRQHandler .thumb_set DMA2_Stream4_IRQHandler,Default_Handler .weak OTG_FS_IRQHandler .thumb_set OTG_FS_IRQHandler,Default_Handler .weak DMA2_Stream5_IRQHandler .thumb_set DMA2_Stream5_IRQHandler,Default_Handler .weak DMA2_Stream6_IRQHandler .thumb_set DMA2_Stream6_IRQHandler,Default_Handler .weak DMA2_Stream7_IRQHandler .thumb_set DMA2_Stream7_IRQHandler,Default_Handler .weak USART6_IRQHandler .thumb_set USART6_IRQHandler,Default_Handler .weak I2C3_EV_IRQHandler .thumb_set I2C3_EV_IRQHandler,Default_Handler .weak I2C3_ER_IRQHandler .thumb_set I2C3_ER_IRQHandler,Default_Handler .weak FPU_IRQHandler .thumb_set FPU_IRQHandler,Default_Handler .weak SPI4_IRQHandler .thumb_set SPI4_IRQHandler,Default_Handler .weak SPI5_IRQHandler .thumb_set SPI5_IRQHandler,Default_Handler /************************ (C) COPYRIGHT STMicroelectronics *****END OF FILE****/ ================================================ FILE: Zelig/os_layer/ARMv7M/Vectors/startup_stm32l152xe.S ================================================ /** ****************************************************************************** * @file startup_stm32l152xe.s * @author MCD Application Team * @version V2.0.0 * @date 5-September-2014 * @brief STM32L152XE Devices vector table for * Atollic toolchain. * This module performs: * - Set the initial SP * - Set the initial PC == Reset_Handler, * - Set the vector table entries with the exceptions ISR address * - Configure the clock system * - Branches to main in the C library (which eventually * calls main()). * After Reset the Cortex-M3 processor is in Thread mode, * priority is Privileged, and the Stack is set to Main. ****************************************************************************** * *

© COPYRIGHT(c) 2014 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. * ****************************************************************************** */ .syntax unified .cpu cortex-m3 .fpu softvfp .thumb .global g_pfnVectors .global Default_Handler /* start address for the initialization values of the .data section. defined in linker script */ .word _sidata /* start address for the .data section. defined in linker script */ .word _sdata /* end address for the .data section. defined in linker script */ .word _edata /* start address for the .bss section. defined in linker script */ .word _sbss /* end address for the .bss section. defined in linker script */ .word _ebss .equ BootRAM, 0xF108F85F /** * LLILUM: define stack and heap symbols to accomodate the MSP wrapping on exception thread */ .section .stack .align 3 .ifdef __STACK_SIZE .equ Stack_Size, __STACK_SIZE .else .equ Stack_Size, 0x800 .endif .globl __StackTop .globl __StackLimit __StackLimit: .space Stack_Size .size __StackLimit, . - __StackLimit __StackTop: .size __StackTop, . - __StackTop .section .heap .align 3 .ifdef __HEAP_SIZE .equ Heap_Size, __HEAP_SIZE .else .equ Heap_Size, 0x800 .endif .globl __HeapBase .globl __HeapLimit __HeapBase: .space Heap_Size .size __HeapBase, . - __HeapBase __HeapLimit: .size __HeapLimit, . - __HeapLimit /** * @brief This is the code that gets called when the processor first * starts execution following a reset event. Only the absolutely * necessary set is performed, after which the application * supplied main() routine is called. * @param None * @retval : None */ .section .text.Reset_Handler .weak Reset_Handler .type Reset_Handler, %function Reset_Handler: ldr r0, =_estack mov sp, r0 /* set stack pointer */ /* Copy the data segment initializers from flash to SRAM */ movs r1, #0 b LoopCopyDataInit CopyDataInit: ldr r3, =_sidata ldr r3, [r3, r1] str r3, [r0, r1] adds r1, r1, #4 LoopCopyDataInit: ldr r0, =_sdata ldr r3, =_edata adds r2, r0, r1 cmp r2, r3 bcc CopyDataInit ldr r2, =_sbss b LoopFillZerobss /* Zero fill the bss segment. */ FillZerobss: movs r3, #0 str r3, [r2], #4 LoopFillZerobss: ldr r3, = _ebss cmp r2, r3 bcc FillZerobss /* Call the clock system intitialization function.*/ bl SystemInit /* Call static constructors */ //bl __libc_init_array /* Call the application's entry point.*/ //bl main bl _start LoopForever: b LoopForever .size Reset_Handler, .-Reset_Handler /** * @brief This is the code that gets called when the processor receives an * unexpected interrupt. This simply enters an infinite loop, preserving * the system state for examination by a debugger. * * @param None * @retval : None */ .section .text.Default_Handler,"ax",%progbits Default_Handler: Infinite_Loop: b Infinite_Loop .size Default_Handler, .-Default_Handler /****************************************************************************** * * The minimal vector table for a Cortex M3. Note that the proper constructs * must be placed on this to ensure that it ends up at physical address * 0x0000.0000. * ******************************************************************************/ .section .isr_vector,"a",%progbits .type g_pfnVectors, %object .size g_pfnVectors, .-g_pfnVectors g_pfnVectors: .word _estack .word Reset_Handler .word NMI_Handler .word HardFault_Handler .word MemManage_Handler .word BusFault_Handler .word UsageFault_Handler .word 0 .word 0 .word 0 .word 0 .word SVC_Handler .word DebugMon_Handler .word 0 .word PendSV_Handler .word SysTick_Handler .word WWDG_IRQHandler .word PVD_IRQHandler .word TAMPER_STAMP_IRQHandler .word RTC_WKUP_IRQHandler .word FLASH_IRQHandler .word RCC_IRQHandler .word EXTI0_IRQHandler .word EXTI1_IRQHandler .word EXTI2_IRQHandler .word EXTI3_IRQHandler .word EXTI4_IRQHandler .word DMA1_Channel1_IRQHandler .word DMA1_Channel2_IRQHandler .word DMA1_Channel3_IRQHandler .word DMA1_Channel4_IRQHandler .word DMA1_Channel5_IRQHandler .word DMA1_Channel6_IRQHandler .word DMA1_Channel7_IRQHandler .word ADC1_IRQHandler .word USB_HP_IRQHandler .word USB_LP_IRQHandler .word DAC_IRQHandler .word COMP_IRQHandler .word EXTI9_5_IRQHandler .word LCD_IRQHandler .word TIM9_IRQHandler .word TIM10_IRQHandler .word TIM11_IRQHandler .word TIM2_IRQHandler .word TIM3_IRQHandler .word TIM4_IRQHandler .word I2C1_EV_IRQHandler .word I2C1_ER_IRQHandler .word I2C2_EV_IRQHandler .word I2C2_ER_IRQHandler .word SPI1_IRQHandler .word SPI2_IRQHandler .word USART1_IRQHandler .word USART2_IRQHandler .word USART3_IRQHandler .word EXTI15_10_IRQHandler .word RTC_Alarm_IRQHandler .word USB_FS_WKUP_IRQHandler .word TIM6_IRQHandler .word TIM7_IRQHandler .word 0 .word TIM5_IRQHandler .word SPI3_IRQHandler .word UART4_IRQHandler .word UART5_IRQHandler .word DMA2_Channel1_IRQHandler .word DMA2_Channel2_IRQHandler .word DMA2_Channel3_IRQHandler .word DMA2_Channel4_IRQHandler .word DMA2_Channel5_IRQHandler .word 0 .word COMP_ACQ_IRQHandler .word 0 .word 0 .word 0 .word 0 .word 0 .word BootRAM /* @0x108. This is for boot in RAM mode for STM32L152XE devices. */ /******************************************************************************* * * Provide weak aliases for each Exception handler to the Default_Handler. * As they are weak aliases, any function with the same name will override * this definition. * *******************************************************************************/ .weak NMI_Handler .thumb_set NMI_Handler,Default_Handler .weak HardFault_Handler .thumb_set HardFault_Handler,Default_Handler .weak MemManage_Handler .thumb_set MemManage_Handler,Default_Handler .weak BusFault_Handler .thumb_set BusFault_Handler,Default_Handler .weak UsageFault_Handler .thumb_set UsageFault_Handler,Default_Handler .weak SVC_Handler .thumb_set SVC_Handler,Default_Handler .weak DebugMon_Handler .thumb_set DebugMon_Handler,Default_Handler .weak PendSV_Handler .thumb_set PendSV_Handler,Default_Handler .weak SysTick_Handler .thumb_set SysTick_Handler,Default_Handler .weak WWDG_IRQHandler .thumb_set WWDG_IRQHandler,Default_Handler .weak PVD_IRQHandler .thumb_set PVD_IRQHandler,Default_Handler .weak TAMPER_STAMP_IRQHandler .thumb_set TAMPER_STAMP_IRQHandler,Default_Handler .weak RTC_WKUP_IRQHandler .thumb_set RTC_WKUP_IRQHandler,Default_Handler .weak FLASH_IRQHandler .thumb_set FLASH_IRQHandler,Default_Handler .weak RCC_IRQHandler .thumb_set RCC_IRQHandler,Default_Handler .weak EXTI0_IRQHandler .thumb_set EXTI0_IRQHandler,Default_Handler .weak EXTI1_IRQHandler .thumb_set EXTI1_IRQHandler,Default_Handler .weak EXTI2_IRQHandler .thumb_set EXTI2_IRQHandler,Default_Handler .weak EXTI3_IRQHandler .thumb_set EXTI3_IRQHandler,Default_Handler .weak EXTI4_IRQHandler .thumb_set EXTI4_IRQHandler,Default_Handler .weak DMA1_Channel1_IRQHandler .thumb_set DMA1_Channel1_IRQHandler,Default_Handler .weak DMA1_Channel2_IRQHandler .thumb_set DMA1_Channel2_IRQHandler,Default_Handler .weak DMA1_Channel3_IRQHandler .thumb_set DMA1_Channel3_IRQHandler,Default_Handler .weak DMA1_Channel4_IRQHandler .thumb_set DMA1_Channel4_IRQHandler,Default_Handler .weak DMA1_Channel5_IRQHandler .thumb_set DMA1_Channel5_IRQHandler,Default_Handler .weak DMA1_Channel6_IRQHandler .thumb_set DMA1_Channel6_IRQHandler,Default_Handler .weak DMA1_Channel7_IRQHandler .thumb_set DMA1_Channel7_IRQHandler,Default_Handler .weak ADC1_IRQHandler .thumb_set ADC1_IRQHandler,Default_Handler .weak USB_HP_IRQHandler .thumb_set USB_HP_IRQHandler,Default_Handler .weak USB_LP_IRQHandler .thumb_set USB_LP_IRQHandler,Default_Handler .weak DAC_IRQHandler .thumb_set DAC_IRQHandler,Default_Handler .weak COMP_IRQHandler .thumb_set COMP_IRQHandler,Default_Handler .weak EXTI9_5_IRQHandler .thumb_set EXTI9_5_IRQHandler,Default_Handler .weak LCD_IRQHandler .thumb_set LCD_IRQHandler,Default_Handler .weak TIM9_IRQHandler .thumb_set TIM9_IRQHandler,Default_Handler .weak TIM10_IRQHandler .thumb_set TIM10_IRQHandler,Default_Handler .weak TIM11_IRQHandler .thumb_set TIM11_IRQHandler,Default_Handler .weak TIM2_IRQHandler .thumb_set TIM2_IRQHandler,Default_Handler .weak TIM3_IRQHandler .thumb_set TIM3_IRQHandler,Default_Handler .weak TIM4_IRQHandler .thumb_set TIM4_IRQHandler,Default_Handler .weak I2C1_EV_IRQHandler .thumb_set I2C1_EV_IRQHandler,Default_Handler .weak I2C1_ER_IRQHandler .thumb_set I2C1_ER_IRQHandler,Default_Handler .weak I2C2_EV_IRQHandler .thumb_set I2C2_EV_IRQHandler,Default_Handler .weak I2C2_ER_IRQHandler .thumb_set I2C2_ER_IRQHandler,Default_Handler .weak SPI1_IRQHandler .thumb_set SPI1_IRQHandler,Default_Handler .weak SPI2_IRQHandler .thumb_set SPI2_IRQHandler,Default_Handler .weak USART1_IRQHandler .thumb_set USART1_IRQHandler,Default_Handler .weak USART2_IRQHandler .thumb_set USART2_IRQHandler,Default_Handler .weak USART3_IRQHandler .thumb_set USART3_IRQHandler,Default_Handler .weak EXTI15_10_IRQHandler .thumb_set EXTI15_10_IRQHandler,Default_Handler .weak RTC_Alarm_IRQHandler .thumb_set RTC_Alarm_IRQHandler,Default_Handler .weak USB_FS_WKUP_IRQHandler .thumb_set USB_FS_WKUP_IRQHandler,Default_Handler .weak TIM6_IRQHandler .thumb_set TIM6_IRQHandler,Default_Handler .weak TIM7_IRQHandler .thumb_set TIM7_IRQHandler,Default_Handler .weak TIM5_IRQHandler .thumb_set TIM5_IRQHandler,Default_Handler .weak SPI3_IRQHandler .thumb_set SPI3_IRQHandler,Default_Handler .weak UART4_IRQHandler .thumb_set UART4_IRQHandler,Default_Handler .weak UART5_IRQHandler .thumb_set UART5_IRQHandler,Default_Handler .weak DMA2_Channel1_IRQHandler .thumb_set DMA2_Channel1_IRQHandler,Default_Handler .weak DMA2_Channel2_IRQHandler .thumb_set DMA2_Channel2_IRQHandler,Default_Handler .weak DMA2_Channel3_IRQHandler .thumb_set DMA2_Channel3_IRQHandler,Default_Handler .weak DMA2_Channel4_IRQHandler .thumb_set DMA2_Channel4_IRQHandler,Default_Handler .weak DMA2_Channel5_IRQHandler .thumb_set DMA2_Channel5_IRQHandler,Default_Handler .weak COMP_ACQ_IRQHandler .thumb_set COMP_ACQ_IRQHandler,Default_Handler /************************ (C) COPYRIGHT STMicroelectronics *****END OF FILE****/ ================================================ FILE: Zelig/os_layer/inc/api/io/llos_analog.h ================================================ // // LLILUM OS Abstraction Layer - Analog // #ifndef __LLOS_ANALOG_H__ #define __LLOS_ANALOG_H__ #ifdef __cplusplus extern "C" { #endif #include "llos_types.h" // // Analog In/Out // typedef enum LLOS_ADC_Direction { LLOS_ADC_Input = 0, LLOS_ADC_Output, } LLOS_ADC_Direction; HRESULT LLOS_ADC_Initialize(uint32_t pinName, LLOS_ADC_Direction direction, LLOS_Context* channel); VOID LLOS_ADC_Uninitialize(LLOS_Context channel); HRESULT LLOS_ADC_ReadRaw(LLOS_Context channel, int32_t* value); HRESULT LLOS_ADC_WriteRaw(LLOS_Context channel, int32_t value); HRESULT LLOS_ADC_Read(LLOS_Context channel, float* value); HRESULT LLOS_ADC_Write(LLOS_Context channel, float value); HRESULT LLOS_ADC_GetPrecisionBits(LLOS_Context channel, uint32_t* precisionInBits); #ifdef __cplusplus } #endif #endif // __LLOS_ANALOG_H__ ================================================ FILE: Zelig/os_layer/inc/api/io/llos_gpio.h ================================================ // // LLILUM OS Abstraction Layer - GPIO // #ifndef __LLOS_GPIO_H__ #define __LLOS_GPIO_H__ #ifdef __cplusplus extern "C" { #endif #include "llos_types.h" // // GP I/O // typedef enum LLOS_GPIO_Resistor { LLOS_GPIO_ResistorDefault = 0, LLOS_GPIO_ResistorPullNone, LLOS_GPIO_ResistorPullup, LLOS_GPIO_ResistorPulldown, LLOS_GPIO_ResistorOpenDrain, LLOS_GPIO_ResistorRepeater, } LLOS_GPIO_Resistor; typedef enum LLOS_GPIO_Edge { LLOS_GPIO_EdgeNone = 0, LLOS_GPIO_EdgeRising, LLOS_GPIO_EdgeFalling, LLOS_GPIO_EdgeBoth, LLOS_GPIO_EdgeLevelLow, LLOS_GPIO_EdgeLevelHigh, } LLOS_GPIO_Edge; typedef enum LLOS_GPIO_Polarity { LLOS_GPIO_polarity_normal = 0, LLOS_GPIO_polarity_inverted, } LLOS_GPIO_Polarity; typedef enum LLOS_GPIO_Direction { LLOS_GPIO_Input = 0, LLOS_GPIO_Output } LLOS_GPIO_Direction; typedef VOID(*LLOS_GPIO_InterruptCallback)(LLOS_Context pin, LLOS_Context callbackCtx, LLOS_GPIO_Edge edge); HRESULT LLOS_GPIO_AllocatePin ( uint32_t pin_number, LLOS_Context* pin ); VOID LLOS_GPIO_FreePin ( LLOS_Context pin ); HRESULT LLOS_GPIO_EnablePin ( LLOS_Context pin, LLOS_GPIO_Edge edge, LLOS_GPIO_InterruptCallback callback, LLOS_Context callback_context ); HRESULT LLOS_GPIO_DisablePin ( LLOS_Context pin ); HRESULT LLOS_GPIO_SetPolarity ( LLOS_Context pin, LLOS_GPIO_Polarity polarity ); HRESULT LLOS_GPIO_SetMode ( LLOS_Context pin, LLOS_GPIO_Resistor resistor ); HRESULT LLOS_GPIO_SetDirection( LLOS_Context pin, LLOS_GPIO_Direction direction ); HRESULT LLOS_GPIO_SetDebounce ( LLOS_Context pin, LLOS_TimeSpan debounce_time ); // TOOD: Documentation: Make sure to note that the managed code layer does not restrict input pins from being written to. HRESULT LLOS_GPIO_Write ( LLOS_Context pin, int32_t value ); int32_t LLOS_GPIO_Read ( LLOS_Context pin ); #ifdef __cplusplus } #endif #endif // __LLOS_GPIO_H__ ================================================ FILE: Zelig/os_layer/inc/api/io/llos_i2c.h ================================================ // // LLILUM OS Abstraction Layer - I2C // #ifndef __LLOS_I2C_H__ #define __LLOS_I2C_H__ #ifdef __cplusplus extern "C" { #endif #include "llos_types.h" // // I2C // HRESULT LLOS_I2C_Initialize (int32_t sdaPin, int32_t sclPin, LLOS_Context* pChannel); VOID LLOS_I2C_Uninitialize(LLOS_Context channel); HRESULT LLOS_I2C_SetFrequency(LLOS_Context channel, uint32_t frequencyHz); HRESULT LLOS_I2C_Enable (LLOS_Context channel); HRESULT LLOS_I2C_Disable (LLOS_Context channel); HRESULT LLOS_I2C_Write (LLOS_Context channel, uint32_t address, uint8_t* pBuffer, int32_t offset, int32_t* pLength, BOOL stop); HRESULT LLOS_I2C_Read (LLOS_Context channel, uint32_t address, uint8_t* pBuffer, int32_t offset, int32_t* pLength, BOOL stop); HRESULT LLOS_I2C_Reset (LLOS_Context channel); #ifdef __cplusplus } #endif #endif // __LLOS_I2C_H__ ================================================ FILE: Zelig/os_layer/inc/api/io/llos_pwm.h ================================================ // // LLILUM OS Abstraction Layer - PWM // #ifndef __LLOS_PWM_H__ #define __LLOS_PWM_H__ #ifdef __cplusplus extern "C" { #endif #include "llos_types.h" typedef enum LLOS_PWM_Polarity { LLOS_PWM_PolarityNormal = 0, LLOS_PWM_PolarityInverted, } LLOS_PWM_Polarity; typedef enum LLOS_PWM_Prescaler { LLOS_PWM_PrescalerDiv1 = 0, LLOS_PWM_PrescalerDiv2, LLOS_PWM_PrescalerDiv4, LLOS_PWM_PrescalerDiv8, LLOS_PWM_PrescalerDiv16, LLOS_PWM_PrescalerDiv64, LLOS_PWM_PrescalerDiv256, LLOS_PWM_PrescalerDiv1024 } LLOS_PWM_Prescaler; // // PWM In/Out // HRESULT LLOS_PWM_Initialize (uint32_t pinName, LLOS_Context* channel); VOID LLOS_PWM_Uninitialize (LLOS_Context channel); HRESULT LLOS_PWM_SetDutyCycle (LLOS_Context channel, uint32_t dutyCycleNumerator, uint32_t dutyCycleDenominator); HRESULT LLOS_PWM_SetPeriod (LLOS_Context channel, uint32_t periodMicroSeconds); HRESULT LLOS_PWM_SetPulseWidth(LLOS_Context channel, uint32_t widthMicroSeconds); HRESULT LLOS_PWM_SetPolarity (LLOS_Context channel, LLOS_PWM_Polarity polarity); HRESULT LLOS_PWM_SetPrescaler (LLOS_Context channel, LLOS_PWM_Prescaler prescaler); HRESULT LLOS_PWM_Start (LLOS_Context channel); HRESULT LLOS_PWM_Stop (LLOS_Context channel); #ifdef __cplusplus } #endif #endif // __LLOS_PWM_H__ ================================================ FILE: Zelig/os_layer/inc/api/io/llos_serial.h ================================================ // // LLILUM OS Abstraction Layer - SERIAL // #ifndef __LLOS_SERIAL_H__ #define __LLOS_SERIAL_H__ #ifdef __cplusplus extern "C" { #endif #include "llos_types.h" // // Serial // typedef enum LLOS_SERIAL_Parity { LLOS_SERIAL_ParityNone = 0, LLOS_SERIAL_ParityOdd, LLOS_SERIAL_ParityEven, } LLOS_SERIAL_Parity; typedef enum LLOS_SERIAL_StopBits { LLOS_SERIAL_StopBitsNone = 0, LLOS_SERIAL_StopBitsOne, LLOS_SERIAL_StopBitsTwo, LLOS_SERIAL_StopBitsOnePointFive, } LLOS_SERIAL_StopBits; typedef struct LLOS_SERIAL_Config { uint32_t BaudRate; LLOS_SERIAL_Parity Parity; uint32_t DataBits; uint32_t StopBits; uint32_t SoftwareFlowControlValue; } LLOS_SERIAL_Config; typedef enum LLOS_SERIAL_Event { LLOS_SERIAL_EventRx = 0, LLOS_SERIAL_EventTx, } LLOS_SERIAL_Event; typedef enum LLOS_SERIAL_Irq { LLOS_SERIAL_IrqRx = 0, LLOS_SERIAL_IrqTx, LLOS_SERIAL_IrqBoth } LLOS_SERIAL_Irq; typedef VOID(*LLOS_SERIAL_InterruptCallback)(LLOS_Context port, LLOS_Context callbackCtx, LLOS_SERIAL_Event serialEvent); HRESULT LLOS_SERIAL_Open (int32_t rxPin, int32_t txPin, LLOS_SERIAL_Config **ppConfig, LLOS_Context* pChannel); VOID LLOS_SERIAL_Close (LLOS_Context channel); HRESULT LLOS_SERIAL_Enable (LLOS_Context channel, LLOS_SERIAL_Irq irq); HRESULT LLOS_SERIAL_Disable (LLOS_Context channel, LLOS_SERIAL_Irq irq); HRESULT LLOS_SERIAL_SetFlowControl(LLOS_Context channel, int32_t rtsPin, int32_t ctsPin); HRESULT LLOS_SERIAL_Configure (LLOS_Context channel, LLOS_SERIAL_Config* pConfig); HRESULT LLOS_SERIAL_Read (LLOS_Context channel, uint8_t* pBuffer, int32_t offset, int32_t* pLength); HRESULT LLOS_SERIAL_Write (LLOS_Context channel, uint8_t* pBuffer, int32_t offset, int32_t length); HRESULT LLOS_SERIAL_Flush (LLOS_Context channel); HRESULT LLOS_SERIAL_Clear (LLOS_Context channel); HRESULT LLOS_SERIAL_SetCallback (LLOS_Context channel, LLOS_SERIAL_InterruptCallback callback, LLOS_Context callbackContext); HRESULT LLOS_SERIAL_CanRead (LLOS_Context channel, BOOL *pCanRead); HRESULT LLOS_SERIAL_CanWrite (LLOS_Context channel, BOOL *pCanWrite); #ifdef __cplusplus } #endif #endif // __LLOS_SERIAL_H__ ================================================ FILE: Zelig/os_layer/inc/api/io/llos_spi.h ================================================ // // LLILUM OS Abstraction Layer - SPI // #ifndef __LLOS_SPI_H__ #define __LLOS_SPI_H__ #ifdef __cplusplus extern "C" { #endif #include "llos_types.h" // // SPI - master and slave mode // typedef struct LLOS_SPI_ControllerConfig { uint32_t ChipSelect; BOOL LoopbackMode; BOOL MSBTransferMode; BOOL ActiveLow; BOOL InversePolarity; BOOL ClockIdleLevel; BOOL ClockSamplingEdge; BOOL Master; uint32_t PhaseMode; uint32_t WordSize; uint32_t ClockRateHz; uint32_t ChipSelectSetupCycles; uint32_t ChipSelectHoldCycles; uint32_t BusyPin; } LLOS_SPI_ControllerConfig; typedef enum LLOS_SPI_Action { LLOS_SPI_ActionWrite = 0, LLOS_SPI_ActionRead, LLOS_SPI_ActionTransfer, LLOS_SPI_ActionError, } LLOS_SPI_Action; typedef VOID(*LLOS_SPI_Callback)(LLOS_Context channel, LLOS_Context callbackCtx, LLOS_SPI_Action edge); HRESULT LLOS_SPI_Initialize ( uint32_t mosi, uint32_t miso, uint32_t sclk, uint32_t chipSelect, LLOS_Context* ppChannel, LLOS_SPI_ControllerConfig** ppConfiguration ); VOID LLOS_SPI_Uninitialize( LLOS_Context channel ); HRESULT LLOS_SPI_Configure ( LLOS_Context channel, LLOS_SPI_ControllerConfig* pConfig ); HRESULT LLOS_SPI_SetCallback ( LLOS_Context channel, LLOS_SPI_Callback request, LLOS_Context context ); HRESULT LLOS_SPI_SetFrequency( LLOS_Context channel, uint32_t frequencyHz ); HRESULT LLOS_SPI_Transfer ( LLOS_Context channel, uint8_t* txBuffer, int32_t txOffset, int32_t txCount, uint8_t* rxBuffer, int32_t rxOffset, int32_t rxCount, int32_t rxStartOffset); HRESULT LLOS_SPI_Write ( LLOS_Context channel, uint8_t* txBuffer, int32_t txOffset, int32_t txCount ); HRESULT LLOS_SPI_Read ( LLOS_Context channel, uint8_t* rxBuffer, int32_t rxOffset, int32_t rxCount, int32_t rxStartOffset ); HRESULT LLOS_SPI_IsBusy ( LLOS_Context channel, BOOL* isBusy ); HRESULT LLOS_SPI_Suspend ( LLOS_Context channel ); HRESULT LLOS_SPI_Resume ( LLOS_Context channel ); #ifdef __cplusplus } #endif #endif // __LLOS_SPI_H__ ================================================ FILE: Zelig/os_layer/inc/api/llos_memory.h ================================================ // // LLILUM OS Abstraction Layer - Heap // #define LLOS_USE_MANAGED_HEAP 1 #ifndef __LLOS_MEMORY_H__ #define __LLOS_MEMORY_H__ #ifdef __cplusplus extern "C" { #endif #include "llos_types.h" // // General heap // #if LLOS_USE_MANAGED_HEAP extern LLOS_Opaque AllocateFromManagedHeap(uint32_t size); extern VOID FreeFromManagedHeap (LLOS_Opaque address); #else inline LLOS_Opaque AllocateFromManagedHeap(uint32_t size) { return LLOS_CALLOC(size, 1); } inline VOID FreeFromManagedHeap(LLOS_Opaque address) { LLOS_FREE(address); } #endif HRESULT LLOS_MEMORY_GetMaxHeapSize(uint32_t* pMaxHeapSize); HRESULT LLOS_MEMORY_Allocate (uint32_t size, uint8_t fill, LLOS_Opaque* pAllocation); HRESULT LLOS_MEMORY_Reallocate (LLOS_Opaque* allocation, uint32_t newSize); VOID LLOS_MEMORY_Free (LLOS_Opaque address); #ifdef __cplusplus } #endif #endif // __LLOS_MEMORY_H__ ================================================ FILE: Zelig/os_layer/inc/hal/llos_clock.h ================================================ // // LLILUM OS Abstraction Layer - Clock // #ifndef __LLOS_CLOCK_H__ #define __LLOS_CLOCK_H__ #ifdef __cplusplus extern "C" { #endif #include "llos_types.h" // // System clock controller // uint64_t LLOS_CLOCK_GetClockTicks(); uint64_t LLOS_CLOCK_GetClockFrequency(); uint64_t LLOS_CLOCK_GetPerformanceCounter(); uint64_t LLOS_CLOCK_GetPerformanceCounterFrequency(); uint32_t LLOS_CLOCK_DelayCycles(uint32_t cycles); uint32_t LLOS_CLOCK_Delay(uint32_t microSeconds); #ifdef __cplusplus } #endif #endif // __LLOS_CLOCK_H__ ================================================ FILE: Zelig/os_layer/inc/hal/llos_mutex.h ================================================ // // LLILUM OS Abstraction Layer - Mutex // #ifndef __LLOS_MUTEX_H__ #define __LLOS_MUTEX_H__ #ifdef __cplusplus extern "C" { #endif #include "llos_types.h" HRESULT LLOS_MUTEX_CreateGlobalLock(LLOS_Handle* mutexHandle); HRESULT LLOS_MUTEX_Create(LLOS_Context attributes, LLOS_Context name, LLOS_Handle* mutexHandle); HRESULT LLOS_MUTEX_Acquire(LLOS_Handle mutexHandle, int32_t timeout); HRESULT LLOS_MUTEX_Release(LLOS_Handle mutexHandle); BOOL LLOS_MUTEX_CurrentThreadHasLock(LLOS_Handle mutexHandle); HRESULT LLOS_MUTEX_Delete(LLOS_Handle mutexHandle); #ifdef __cplusplus } #endif #endif // __LLOS_MUTEX_H__ ================================================ FILE: Zelig/os_layer/inc/hal/llos_system_timer.h ================================================ // // LLILUM OS Abstraction Layer - Timer // #ifndef __LLOS_SYSTEM_TIMER_H__ #define __LLOS_SYSTEM_TIMER_H__ #ifdef __cplusplus extern "C" { #endif #include "llos_types.h" // // System timer controller // typedef VOID(*LLOS_SYSTEM_TIMER_Callback)(LLOS_Context callbackCtx, uint64_t ticks); HRESULT LLOS_SYSTEM_TIMER_AllocateTimer (LLOS_SYSTEM_TIMER_Callback callback, LLOS_Context callbackContext, uint64_t microsecondsFromNow, LLOS_Context *pTimer); VOID LLOS_SYSTEM_TIMER_FreeTimer (LLOS_Context pTimer ); HRESULT LLOS_SYSTEM_TIMER_ScheduleTimer (LLOS_Context pTimer, uint64_t microsecondsFromNow ); uint64_t LLOS_SYSTEM_TIMER_GetTimerFrequency(LLOS_Context pTimer ); uint64_t LLOS_SYSTEM_TIMER_GetTicks (LLOS_Context pTimer ); #ifdef __cplusplus } #endif #endif // __LLOS_SYSTEM_TIMER_H__ ================================================ FILE: Zelig/os_layer/inc/hal/llos_thread.h ================================================ // // LLILUM OS Abstraction Layer - Thread // #ifndef __LLOS_THREAD_H__ #define __LLOS_THREAD_H__ #ifdef __cplusplus extern "C" { #endif #include "llos_types.h" typedef enum LLOS_ThreadPriority { ThreadPriority_Lowest = 0, ThreadPriority_BelowNormal, ThreadPriority_Normal, ThreadPriority_AboveNormal, ThreadPriority_Highest, } LLOS_ThreadPriority; HRESULT LLOS_THREAD_CreateThread (LLOS_ThreadEntry threadEntry, LLOS_Context threadParameter, LLOS_Context managedThread, uint32_t stackSize, LLOS_Handle* threadHandle); HRESULT LLOS_THREAD_DeleteThread (LLOS_Handle threadHandle); HRESULT LLOS_THREAD_Start (LLOS_Handle threadHandle); HRESULT LLOS_THREAD_Yield (VOID); HRESULT LLOS_THREAD_Signal (LLOS_Handle threadHandle); HRESULT LLOS_THREAD_Wait (LLOS_Handle threadHandle, int32_t timeoutMs); VOID LLOS_THREAD_Sleep (int32_t timeoutMilliseconds); HRESULT LLOS_THREAD_GetCurrentThread (LLOS_Context* managedThread); HRESULT LLOS_THREAD_SetPriority (LLOS_Handle threadHandle, LLOS_ThreadPriority threadPriority); HRESULT LLOS_THREAD_GetPriority (LLOS_Handle threadHandle, LLOS_ThreadPriority* threadPriority); uint32_t LLOS_THREAD_GetMainStackAddress( ); uint32_t LLOS_THREAD_GetMainStackSize ( ); #ifdef __cplusplus } #endif #endif // __LLOS_THREAD_H__ ================================================ FILE: Zelig/os_layer/inc/llos_error.h ================================================ // // LLILUM OS Abstraction Layer - Errors // #ifndef __UW_ERROR_H_ #define __UW_ERROR_H_ // // Errors // #if defined(WIN32) #include #else // WIN32 typedef int HRESULT; // // Severity values // #define SEVERITY_SUCCESS 0 #define SEVERITY_ERROR 1 // // Generic test for success on any status value (non-negative numbers // indicate success). // #define SUCCEEDED(Status) ((HRESULT)(Status) >= 0) // // and the inverse // #define FAILED(Status) ((HRESULT)(Status)<0) // // Success codes // #define S_OK ((HRESULT)0x00000000L) #define S_FALSE ((HRESULT)0x00000001L) // // Return the code // #define HRESULT_CODE(hr) ((hr) & 0xFFFF) // // Return the facility // #define HRESULT_FACILITY(hr) (((hr) >> 16) & 0x1fff) // // Return the severity // #define HRESULT_SEVERITY(hr) (((hr) >> 31) & 0x1) // // Create an HRESULT value from component pieces // #define MAKE_HRESULT(sev,fac,code) ((HRESULT) (((unsigned long)(sev)<<31) | ((unsigned long)(fac)<<16) | ((unsigned long)(code))) ) //--// // // These are denormalized HRESULTs, only the 8 most significant bits are set, to allow use of MOV ,# by the compiler. // #define LLOS_E_UNKNOWN_INSTRUCTION MAKE_HRESULT( SEVERITY_ERROR , 0x0100, 0x0000 ) #define LLOS_E_UNSUPPORTED_INSTRUCTION MAKE_HRESULT( SEVERITY_ERROR , 0x0200, 0x0000 ) #define LLOS_E_STACK_OVERFLOW MAKE_HRESULT( SEVERITY_ERROR , 0x1100, 0x0000 ) #define LLOS_E_STACK_UNDERFLOW MAKE_HRESULT( SEVERITY_ERROR , 0x1200, 0x0000 ) #define LLOS_E_ENTRY_NOT_FOUND MAKE_HRESULT( SEVERITY_ERROR , 0x1500, 0x0000 ) #define LLOS_E_ASSM_WRONG_CHECKSUM MAKE_HRESULT( SEVERITY_ERROR , 0x1600, 0x0000 ) #define LLOS_E_ASSM_PATCHING_NOT_SUPPORTED MAKE_HRESULT( SEVERITY_ERROR , 0x1700, 0x0000 ) #define LLOS_E_SHUTTING_DOWN MAKE_HRESULT( SEVERITY_ERROR , 0x1800, 0x0000 ) #define LLOS_E_OBJECT_DISPOSED MAKE_HRESULT( SEVERITY_ERROR , 0x1900, 0x0000 ) #define LLOS_E_WATCHDOG_TIMEOUT MAKE_HRESULT( SEVERITY_ERROR , 0x1A00, 0x0000 ) #define LLOS_E_NULL_REFERENCE MAKE_HRESULT( SEVERITY_ERROR , 0x2100, 0x0000 ) #define LLOS_E_WRONG_TYPE MAKE_HRESULT( SEVERITY_ERROR , 0x2200, 0x0000 ) #define LLOS_E_TYPE_UNAVAILABLE MAKE_HRESULT( SEVERITY_ERROR , 0x2300, 0x0000 ) #define LLOS_E_INVALID_CAST MAKE_HRESULT( SEVERITY_ERROR , 0x2400, 0x0000 ) #define LLOS_E_OUT_OF_RANGE MAKE_HRESULT( SEVERITY_ERROR , 0x2500, 0x0000 ) #define LLOS_E_SERIALIZATION_VIOLATION MAKE_HRESULT( SEVERITY_ERROR , 0x2700, 0x0000 ) #define LLOS_E_SERIALIZATION_BADSTREAM MAKE_HRESULT( SEVERITY_ERROR , 0x2800, 0x0000 ) #define LLOS_E_INDEX_OUT_OF_RANGE MAKE_HRESULT( SEVERITY_ERROR , 0x2900, 0x0000 ) #define LLOS_E_DIVIDE_BY_ZERO MAKE_HRESULT( SEVERITY_ERROR , 0x3100, 0x0000 ) #define LLOS_E_BUSY MAKE_HRESULT( SEVERITY_ERROR , 0x3300, 0x0000 ) #define LLOS_E_PROCESS_EXCEPTION MAKE_HRESULT( SEVERITY_ERROR , 0x4100, 0x0000 ) #define LLOS_E_THREAD_WAITING MAKE_HRESULT( SEVERITY_ERROR , 0x4200, 0x0000 ) #define LLOS_E_LOCK_SYNCHRONIZATION_EXCEPTION MAKE_HRESULT( SEVERITY_ERROR , 0x4400, 0x0000 ) #define LLOS_E_APPDOMAIN_EXITED MAKE_HRESULT( SEVERITY_ERROR , 0x4800, 0x0000 ) #define LLOS_E_APPDOMAIN_MARSHAL_EXCEPTION MAKE_HRESULT( SEVERITY_ERROR , 0x4900, 0x0000 ) #define LLOS_E_NOTIMPL MAKE_HRESULT( SEVERITY_ERROR , 0x4a00, 0x0000 ) #define LLOS_E_UNKNOWN_TYPE MAKE_HRESULT( SEVERITY_ERROR , 0x4d00, 0x0000 ) #define LLOS_E_ARGUMENT_NULL MAKE_HRESULT( SEVERITY_ERROR , 0x4e00, 0x0000 ) #define LLOS_E_IO MAKE_HRESULT( SEVERITY_ERROR , 0x4f00, 0x0000 ) #define LLOS_E_ENTRYPOINT_NOT_FOUND MAKE_HRESULT( SEVERITY_ERROR , 0x5000, 0x0000 ) #define LLOS_E_DRIVER_NOT_REGISTERED MAKE_HRESULT( SEVERITY_ERROR , 0x5100, 0x0000 ) // // Gp IO error codes // #define LLOS_E_PIN_UNAVAILABLE MAKE_HRESULT( SEVERITY_ERROR , 0x5400, 0x0000 ) #define LLOS_E_PIN_DEAD MAKE_HRESULT( SEVERITY_ERROR , 0x5500, 0x0000 ) #define LLOS_E_INVALID_OPERATION MAKE_HRESULT( SEVERITY_ERROR , 0x5600, 0x0000 ) #define LLOS_E_WRONG_INTERRUPT_TYPE MAKE_HRESULT( SEVERITY_ERROR , 0x5700, 0x0000 ) #define LLOS_E_NO_INTERRUPT MAKE_HRESULT( SEVERITY_ERROR , 0x5800, 0x0000 ) #define LLOS_E_DISPATCHER_ACTIVE MAKE_HRESULT( SEVERITY_ERROR , 0x5900, 0x0000 ) // // IO error codes // (Keep in-sync with IOExceptionErrorCode enum in IOException.cs) // #define LLOS_E_FILE_IO MAKE_HRESULT( SEVERITY_ERROR , 0x6000, 0x0000 ) #define LLOS_E_INVALID_DRIVER MAKE_HRESULT( SEVERITY_ERROR , 0x6100, 0x0000 ) #define LLOS_E_FILE_NOT_FOUND MAKE_HRESULT( SEVERITY_ERROR , 0x6200, 0x0000 ) #define LLOS_E_DIRECTORY_NOT_FOUND MAKE_HRESULT( SEVERITY_ERROR , 0x6300, 0x0000 ) #define LLOS_E_VOLUME_NOT_FOUND MAKE_HRESULT( SEVERITY_ERROR , 0x6400, 0x0000 ) #define LLOS_E_PATH_TOO_LONG MAKE_HRESULT( SEVERITY_ERROR , 0x6500, 0x0000 ) #define LLOS_E_DIRECTORY_NOT_EMPTY MAKE_HRESULT( SEVERITY_ERROR , 0x6600, 0x0000 ) #define LLOS_E_UNAUTHORIZED_ACCESS MAKE_HRESULT( SEVERITY_ERROR , 0x6700, 0x0000 ) #define LLOS_E_PATH_ALREADY_EXISTS MAKE_HRESULT( SEVERITY_ERROR , 0x6800, 0x0000 ) #define LLOS_E_TOO_MANY_OPEN_HANDLES MAKE_HRESULT( SEVERITY_ERROR , 0x6900, 0x0000 ) // // General error codes // #define LLOS_E_NOT_FOUND MAKE_HRESULT( SEVERITY_ERROR , 0x7500, 0x0000 ) #define LLOS_E_BUFFER_TOO_SMALL MAKE_HRESULT( SEVERITY_ERROR , 0x7600, 0x0000 ) #define LLOS_E_NOT_SUPPORTED MAKE_HRESULT( SEVERITY_ERROR , 0x7700, 0x0000 ) #define LLOS_E_HMAC_NOT_SUPPORTED MAKE_HRESULT( SEVERITY_ERROR , 0x7701, 0x0000 ) #define LLOS_E_RESCHEDULE MAKE_HRESULT( SEVERITY_ERROR , 0x7800, 0x0000 ) #define LLOS_E_OUT_OF_MEMORY MAKE_HRESULT( SEVERITY_ERROR , 0x7A00, 0x0000 ) #define LLOS_E_RESTART_EXECUTION MAKE_HRESULT( SEVERITY_ERROR , 0x7B00, 0x0000 ) #define LLOS_E_INVALID_PARAMETER MAKE_HRESULT( SEVERITY_ERROR , 0x7D00, 0x0000 ) #define LLOS_E_TIMEOUT MAKE_HRESULT( SEVERITY_ERROR , 0x7E00, 0x0000 ) #define LLOS_E_FAIL MAKE_HRESULT( SEVERITY_ERROR , 0x7F00, 0x0000 ) //--// #define LLOS_S_THREAD_EXITED MAKE_HRESULT( SEVERITY_SUCCESS, 0x0100, 0x0000 ) #define LLOS_S_QUANTUM_EXPIRED MAKE_HRESULT( SEVERITY_SUCCESS, 0x0200, 0x0000 ) #define LLOS_S_NO_READY_THREADS MAKE_HRESULT( SEVERITY_SUCCESS, 0x0300, 0x0000 ) #define LLOS_S_NO_THREADS MAKE_HRESULT( SEVERITY_SUCCESS, 0x0400, 0x0000 ) #define LLOS_S_RESTART_EXECUTION MAKE_HRESULT( SEVERITY_SUCCESS, 0x0500, 0x0000 ) #endif //WIN32 || _WIN32 //--// #ifdef __cplusplus extern "C" { #endif void LLOS_Die(); #ifdef __cplusplus } #endif //--// #endif // __UW_ERROR_H_ ================================================ FILE: Zelig/os_layer/inc/llos_platform.h ================================================ // // LLILUM OS Abstraction Layer - Platform // #ifndef __LLOS_PLATFORM_H__ #define __LLOS_PLATFORM_H__ // // Platform dependent definitions // #ifndef LLOS_PLATFORM_AES_KEY_LENGTH_BYTES #define LLOS_PLATFORM_AES_KEY_LENGTH_BYTES 16 #endif // LLOS_PLATFORM_AES_KEY_LENGTH_BYTES #ifndef LLOS_PLATFORM_HASH_LENGTH_BYTES #define LLOS_PLATFORM_HASH_LENGTH_BYTES 32 #endif // LLOS_PLATFORM_HASH_LENGTH_BYTES #ifndef LLOS_MALLOC #define LLOS_MALLOC malloc #endif // LLOS_MALLOC #ifndef LLOS_REALLOC #define LLOS_REALLOC realloc #endif // LLOS_REALLOC #ifndef LLOS_CALLOC #define LLOS_CALLOC calloc #endif // LLOS_CALLOC #ifndef LLOS_FREE #define LLOS_FREE free #endif // LLOS_FREE #ifndef LLOS_MEMSET #ifndef _STRING_H_ #ifndef TARGET_STM32F411RE #ifndef WIN32 extern void memset(void* addr, uint8_t fill, size_t size); #endif #else extern void* memset(void* addr, int fill, size_t size); #endif #endif #define LLOS_MEMSET memset #endif // LLOS_MEMSET #endif // __LLOS_PLATFORM_H__ ================================================ FILE: Zelig/os_layer/inc/llos_types.h ================================================ // // LLILUM OS Abstraction Layer - Types // #ifndef __LLOS_TYPES_H__ #define __LLOS_TYPES_H__ #if defined(WIN32) || defined(_WIN32) #include #else #include #endif // WIN32 || _WIN32 #include #include #ifndef OS_TCB_H #ifndef WIN32 typedef uint32_t BOOL; #endif #endif #ifndef WIN32 typedef void VOID; #endif typedef uint32_t LLOS_Address; typedef void* LLOS_Opaque; typedef uint64_t LLOS_Ticks; typedef uint64_t LLOS_Time; typedef uint64_t LLOS_TimeSpan; typedef LLOS_Time LLOS_Timeout; typedef LLOS_Opaque LLOS_Context; typedef LLOS_Opaque LLOS_Handle; typedef int8_t LLOS_AesKey[ LLOS_PLATFORM_AES_KEY_LENGTH_BYTES ]; typedef int8_t LLOS_Hash [ LLOS_PLATFORM_HASH_LENGTH_BYTES ]; //--// #define LLOS_Infinite_Timeout ((LLOS_Timespan)(-1ll)) //--// typedef uint32_t LLOS_Com; // // Async types // typedef enum LLOS_AsyncStatus { LLOS_Created = 0, LLOS_Scheduled, LLOS_Running, LLOS_Cancelling, LLOS_Completed, LLOS_CompletedWithTimeout, LLOS_CompletedWithError, LLOS_CompletedWithCancellation, } LLOS_AsyncStatus; typedef VOID(*LLOS_Callback)(LLOS_Context); typedef VOID(*LLOS_ThreadEntry)(LLOS_Context); typedef struct LLOS_AddressRange { LLOS_Address Start; LLOS_Address End; } LLOS_AddressRange; typedef struct LLOS_BBuffer { uint32_t Length; uint8_t Data[1]; } LLOS_BBuffer; typedef struct LLOS_WBuffer { uint32_t Length; uint16_t Data[1]; } LLOS_WBuffer; #endif // __LLOS_TYPES_H__ ================================================ FILE: Zelig/os_layer/inc/llos_unwind.h ================================================ // // LLILUM OS Abstraction Layer - Unwind // #ifndef __LLOS_UNWIND_H__ #define __LLOS_UNWIND_H__ #include // NOTE: This is a very light abstraction over the Itanium ABI. Different platforms implement the // ABI in slighty different ways. This allows a specific platform to override the behavior where // they're not entirely compliant with the spec as described at the following URL: // http://mentorembedded.github.io/cxx-abi/abi-eh.html // Status flags describing the unwind phase and options. Should match _Unwind_Action in ABI. enum LLOS_Unwind_Actions { LLOS_UA_SEARCH_PHASE = 0x01, // Mutually exclusive with CLEANUP_PHASE LLOS_UA_CLEANUP_PHASE = 0x02, // Mutually exclusive with SEARCH_PHASE LLOS_UA_HANDLER_FRAME = 0x04, LLOS_UA_FORCE_UNWIND = 0x08, LLOS_UA_END_OF_STACK = 0x16, }; // Result of any given unwind operation; values should match _Unwind_Reason_Code. enum LLOS_Unwind_Reason_Code { LLOS_URC_NO_REASON = 0, // Success LLOS_URC_FOREIGN_EXCEPTION_CAUGHT = 1, LLOS_URC_PHASE2_ERROR = 2, LLOS_URC_PHASE1_ERROR = 3, LLOS_URC_NORMAL_STOP = 4, LLOS_URC_END_OF_STACK = 5, LLOS_URC_HANDLER_FOUND = 6, LLOS_URC_INSTALL_CONTEXT = 7, LLOS_URC_CONTINUE_UNWIND = 8, LLOS_URC_FAILURE = 9, }; extern "C" { LLOS_Unwind_Reason_Code LLOS_Unwind_Personality( LLOS_Unwind_Actions actions, uint64_t exceptionClass, uintptr_t exceptionObject, uintptr_t context); uintptr_t LLOS_AllocateException(LLOS_Opaque exception, uint64_t exceptionClass); LLOS_Opaque LLOS_GetExceptionObject(uintptr_t exception); uintptr_t LLOS_Unwind_GetIP(uintptr_t context); uintptr_t LLOS_Unwind_GetLanguageSpecificData(uintptr_t context); uintptr_t LLOS_Unwind_GetRegionStart(uintptr_t context); void LLOS_Unwind_RaiseException(uintptr_t exceptionObject); void LLOS_Unwind_SetRegisters( uintptr_t context, uintptr_t landingPad, uintptr_t exceptionObject, uintptr_t selector); void LLOS_Terminate(); } #endif // __LLOS_UNWIND_H__ ================================================ FILE: Zelig/os_layer/ports/mbed/MbedOSAbstraction.vcxproj ================================================  Debug ARM Release ARM {2832CE7B-8065-4473-A3C7-B8B069920A9C} Android MbedOSAbstraction 14.0 Llilum 1.0 MbedOSAbstraction $(LLILUM_GCC) $(LLILUM_ROOT)Zelig\ $(LLILUM_ROOT)VisualStudio\LlilumApplicationType\Llilum\1.0\ LPC1768 $(LlilumBuildRoot)\Host\bin\$(Configuration)\Microsoft.Llilum.BoardConfigurations.$(LlilumBoardName).dll MbedOSAbstraction_$(LlilumBoardName) $(OutDir)\$(LlilumOutputName).bin $(LlilumBuildRoot)\Host\bin\Debug\Microsoft.Zelig.Compiler.exe $(LlilumBuildRoot)\Host\bin\Debug\Microsoft.Zelig.Compiler.exe $(LlilumSourceRoot)\..\os_layer\inc\;$(LlilumSourceRoot)\..\os_layer\inc\api;$(LlilumSourceRoot)\..\os_layer\inc\api\io;$(LlilumSourceRoot)\..\os_layer\inc\hal $(LlilumClAdditionalOptionsLPC1768) $(LlilumClAdditionalIncludesLPC1768);$(ProjectDir);$(NativeIncludes) $(LlilumClPreprocessorDefsLPC1768) $(LlilumLinkAdditionalDepsLPC1768) $(LlilumLinkAdditionalLibDirsLPC1768) $(LlilumLinkAdditionalOptionsLPC1768) $(LlilumLinkLibDepsLPC1768) $(LlilumTargetBoardArchitectureLPC1768) $(LlilumAsmAdditionalOptionsLPC1768) $(LlilumStackSizeLPC1768) $(LlilumHeapSizeLPC1768) $(LlilumClAdditionalOptionsK64F) $(LlilumClAdditionalIncludesK64F);$(ProjectDir);$(NativeIncludes) $(LlilumClPreprocessorDefsK64F) $(LlilumLinkAdditionalDepsK64F) $(LlilumLinkAdditionalLibDirsK64F) $(LlilumLinkAdditionalOptionsK64F) $(LlilumLinkLibDepsK64F) $(LlilumTargetBoardArchitectureK64F) $(LlilumAsmAdditionalOptionsK64F) $(LlilumStackSizeK64F) $(LlilumHeapSizeK64F) $(LlilumClAdditionalOptionsSTM32L152) $(LlilumClAdditionalIncludesSTM32L152);$(ProjectDir);$(NativeIncludes) $(LlilumClPreprocessorDefsSTM32L152) $(LlilumLinkAdditionalDepsSTM32L152) $(LlilumLinkAdditionalLibDirsSTM32L152) $(LlilumLinkAdditionalOptionsSTM32L152) $(LlilumLinkLibDepsSTM32L152) $(LlilumTargetBoardArchitectureSTM32L152) $(LlilumAsmAdditionalOptionsSTM32L152) $(LlilumStackSizeSTM32L152) $(LlilumHeapSizeSTM32L152) StaticLibrary true $(LlilumTargetBoardArchitecture) DynamicLibrary false $(LlilumTargetBoardArchitecture) mbedOSAbstraction_$(LlilumBoardName) .a $(LlilumGccBin);$(ExecutablePath) $(LlilumBuildRoot)\Target\bin\$(ProjectName)\$(Configuration)\ *.bin;*.hex;*.elf;*.lst;*.d;*.tlog;$(ExtensionsToDeleteOnClean) $(LlilumBuildRoot)\Target\obj\$(ProjectName)\$(Configuration)\ SimpleTestProgram_$(LlilumBoardName) .elf $(LlilumGccBin);$(ExecutablePath) $(LlilumBuildRoot)\Target\bin\$(ProjectName)\$(Configuration)\ *.bin;*.hex;*.elf;*.lst;*.d;*.tlog;$(ExtensionsToDeleteOnClean) $(LlilumBuildRoot)\Target\obj\$(ProjectName)\$(Configuration)\ NotUsing pch.h $(LlilumClAdditionalOptions) %(AdditionalOptions) -mfloat-abi=softfp $(LlilumSourceRoot)\..\lwip\lwip;$(LlilumSourceRoot)\..\lwip\lwip\include;$(LlilumSourceRoot)\..\mbed-rtos\rtx\TARGET_CORTEX_M;$(LlilumSourceRoot)\..\mbed-rtos\rtos;$(LlilumSourceRoot)\..\lwip\lwip\include\netif;$(LlilumSourceRoot)\..\lwip\lwip\include\ipv4\lwip;$(LlilumSourceRoot)\..\lwip\lwip\include\lwip;$(LlilumSourceRoot)\..\lwip\lwip-eth\arch\TARGET_Freescale;$(LlilumSourceRoot)\..\lwip\lwip-eth\arch\TARGET_NXP;$(LlilumSourceRoot)\..\lwip\lwip-sys\arch;$(LlilumClAdditionalIncludes);$(AdditionalIncludeDirectories); $(LlilumClPreprocessorDefs);DEBUG;%(PreprocessorDefinitions);__DEFAULT_STACK_SIZE=$(LlilumStackSize);__HEAP_SIZE=$(LlilumHeapSize) $(LlilumAsmAdditionalOptions) %(LlilumClAdditionalOptions) -Wa,--defsym,__HEAP_SIZE=$(LlilumHeapSize) $(LlilumLinkAdditionalDeps) $(LlilumLinkAdditionalLibDirs) $(LlilumLinkAdditionalOptions) %(AdditionalOptions) $(LlilumLinkLibDeps) false Use pch.h $(LlilumClAdditionalOptions) %(AdditionalOptions) $(LlilumSourceRoot)\..\lwip\lwip;$(LlilumSourceRoot)\..\lwip\lwip\include;$(LlilumSourceRoot)\..\mbed-rtos\rtx\TARGET_CORTEX_M;$(LlilumSourceRoot)\..\mbed-rtos\rtos;$(LlilumSourceRoot)\..\lwip\lwip\include\netif;$(LlilumSourceRoot)\..\lwip\lwip\include\ipv4\lwip;$(LlilumSourceRoot)\..\lwip\lwip\include\lwip;$(LlilumSourceRoot)\..\lwip\lwip-eth\arch\TARGET_Freescale;$(LlilumSourceRoot)\..\lwip\lwip-eth\arch\TARGET_NXP;$(LlilumSourceRoot)\..\lwip\lwip-sys\arch;$(LlilumClAdditionalIncludes);$(AdditionalIncludeDirectories); $(LlilumClPreprocessorDefs);%(PreprocessorDefinitions);__DEFAULT_STACK_SIZE=$(LlilumStackSize);__HEAP_SIZE=$(LlilumHeapSize) $(LlilumAsmAdditionalOptions) %(LlilumClAdditionalOptions) -Wa,--defsym,__HEAP_SIZE=$(LlilumHeapSize) $(LlilumLinkAdditionalDeps) $(LlilumLinkAdditionalLibDirs) $(LlilumLinkAdditionalOptions) %(AdditionalOptions) $(LlilumLinkLibDeps) ================================================ FILE: Zelig/os_layer/ports/mbed/mbed_adc.cpp ================================================ #include "mbed_helpers.h" #include "llos_analog.h" #include "llos_memory.h" //--// extern "C" { #if DEVICE_ANALOGOUT typedef struct LLOS_MbedAdc { union { analogin_t InputChannel; dac_t OutputChannel; }; LLOS_ADC_Direction Direction; } LLOS_MbedAdc; HRESULT LLOS_ADC_Initialize(uint32_t pinName, LLOS_ADC_Direction direction, LLOS_Context* channel) { LLOS_MbedAdc *pCtx; if (channel == NULL) { return LLOS_E_INVALID_PARAMETER; } pCtx = (LLOS_MbedAdc*)AllocateFromManagedHeap(sizeof(LLOS_MbedAdc)); if (pCtx == NULL) { return LLOS_E_OUT_OF_MEMORY; } pCtx->Direction = direction; if (direction == LLOS_ADC_Input) { analogin_init(&pCtx->InputChannel, (PinName)pinName); } else { analogout_init(&pCtx->OutputChannel, (PinName)pinName); } *channel = pCtx; return S_OK; } VOID LLOS_ADC_Uninitialize(LLOS_Context channel) { FreeFromManagedHeap(channel); } HRESULT LLOS_ADC_ReadRaw(LLOS_Context channel, int32_t* value) { LLOS_MbedAdc *pCtx = (LLOS_MbedAdc*)channel; if (value == NULL || pCtx == NULL) { return LLOS_E_INVALID_PARAMETER; } if (pCtx->Direction == LLOS_ADC_Input) { *value = (uint32_t)analogin_read_u16(&pCtx->InputChannel); } else { *value = (uint32_t)analogout_read_u16(&pCtx->OutputChannel); } return S_OK; } HRESULT LLOS_ADC_WriteRaw(LLOS_Context channel, int32_t value) { LLOS_MbedAdc *pCtx = (LLOS_MbedAdc*)channel; if (pCtx == NULL || pCtx->Direction == LLOS_ADC_Input || value > 0xFFFF || value < 0) { return LLOS_E_INVALID_PARAMETER; } analogout_write_u16(&pCtx->OutputChannel, (uint16_t)value); return S_OK; } HRESULT LLOS_ADC_Read(LLOS_Context channel, float* value) { LLOS_MbedAdc *pCtx = (LLOS_MbedAdc*)channel; if (value == NULL || pCtx == NULL) { return LLOS_E_INVALID_PARAMETER; } if (pCtx->Direction == LLOS_ADC_Input) { *value = analogin_read(&pCtx->InputChannel); } else { *value = analogout_read(&pCtx->OutputChannel); } return S_OK; } HRESULT LLOS_ADC_Write(LLOS_Context channel, float value) { LLOS_MbedAdc *pCtx = (LLOS_MbedAdc*)channel; if (pCtx == NULL || pCtx->Direction == LLOS_ADC_Input) { return LLOS_E_INVALID_PARAMETER; } analogout_write(&pCtx->OutputChannel, value); return S_OK; } HRESULT LLOS_ADC_GetPrecisionBits(LLOS_Context channel, uint32_t* precisionInBits) { LLOS__UNREFERENCED_PARAMETER(channel); LLOS__UNREFERENCED_PARAMETER(precisionInBits); return LLOS_E_NOTIMPL; } #endif } ================================================ FILE: Zelig/os_layer/ports/mbed/mbed_asm.S ================================================ .text .thumb .thumb_func .align 2 .globl LLOS_CLOCK_DelayCycles .type LLOS_CLOCK_DelayCycles, %function LLOS_CLOCK_DelayCycles: MOV R2, #4 // Per loop cycles SUB R0, R0, #8 // Startup cycles (including inter-op instructions) START_LOOP: SUB R0, R0, R2 CMP R0, #0 BGT START_LOOP MOV R0, #0 BX LR .end ================================================ FILE: Zelig/os_layer/ports/mbed/mbed_clock.cpp ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // #include "mbed_helpers.h" #include "llos_clock.h" //--// extern "C" { uint64_t LLOS_CLOCK_GetClockTicks() { return us_ticker_read(); } uint64_t LLOS_CLOCK_GetClockFrequency() { return SystemCoreClock; } uint64_t LLOS_CLOCK_GetPerformanceCounter() { return us_ticker_read(); } uint64_t LLOS_CLOCK_GetPerformanceCounterFrequency() { return SystemCoreClock; } uint32_t LLOS_CLOCK_Delay(uint32_t microSeconds) { // LLOS_CLOCK_DelayCycles is defined in mbed_asm.S return LLOS_CLOCK_DelayCycles(SystemCoreClock / 1000000 * microSeconds); } } ================================================ FILE: Zelig/os_layer/ports/mbed/mbed_core.cpp ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // #include "mbed_helpers.h" //--// #define __ATTRIBUTE_ALIGNMENT_8__ __attribute__((aligned(8))) #define __DIRECTIVE_ALIGNMENT_8__ __ASM volatile (".align 8"); #define __ATTRIBUTE_ALIGNMENT_4__ __attribute__((aligned(4))) #define __DIRECTIVE_ALIGNMENT_4__ __ASM volatile (".align 4"); #define __ATTRIBUTE_ALIGNMENT__ __ATTRIBUTE_ALIGNMENT_8__ #define __DIRECTIVE_ALIGNMENT__ __DIRECTIVE_ALIGNMENT_8__ extern "C" { // // We want to run ISRs in privileged Handler mode using the Main Stack Pointer and all the other tasks // in privileged Thread mode using the Process Stack Pointer. // // We will assume that native context switching is possible when processor initialization is carried out in // Handler/Privileged mode. Of course that is not a complete guarantee. After carrying out the initialization of the // idle thread task, we will let the initialization thread return to thread mode upon first context switch as per classic // technique mentioned below, from ARM reference manual. As switching the mode is carried out naturally by // setting the appropriate flag, there is nothing else we need to do at initialization time. See context switch code // in thread manager as well. // // From ARMv-7M Architecture Reference Manual. // // // By default, Thread mode uses the MSP. To switch the stack pointer used in Thread mode to the // PSP, either: // - use the MSR instruction to set the Active stack pointer bit to 1 // - perform an exception return to Thread mode with the appropriate EXC_RETURN value // ////// ////// ////// ////// Table 2-17 Exception return behavior ////// ////// EXC_RETURN Description ////// ========================================================================= ////// 0xFFFFFF[F|E]1 Return to Handler mode. ////// Exception return gets state [and FP state] from the main ////// stack (MSP). ////// Execution uses MSP after return. ////// ////// 0xFFFFFF[F|E]9 Return to Thread mode. ////// Exception Return get state [and FP state] from the main ////// stack (MSP). ////// Execution uses MSP after return. ////// ////// 0xFFFFFF[F|E]D Return to Thread mode. ////// Exception return gets state [and FP state] from the process ////// stack (PSP). ////// Execution uses PSP after return. ////// ////// All other values Reserved. ////// // // System Control Block // /*__STATIC_INLINE*/ uint32_t CMSIS_STUB_SCB__get_CONTROL() { return __get_CONTROL(); } /*__STATIC_INLINE*/ void CMSIS_STUB_SCB__set_CONTROL(uint32_t control) { __set_CONTROL(control); __ISB(); // always emit a barrier } /*__STATIC_INLINE*/ uint32_t CMSIS_STUB_SCB__get_IPSR() { return __get_IPSR(); } /*__STATIC_INLINE*/ uint32_t CMSIS_STUB_SCB__get_APSR() { return __get_APSR(); } /*__STATIC_INLINE*/ uint32_t CMSIS_STUB_SCB__get_xPSR() { return __get_xPSR(); } /*__STATIC_INLINE*/ uint32_t CMSIS_STUB_SCB__get_PSP() { return __get_PSP(); } /*__STATIC_INLINE*/ void CMSIS_STUB_SCB__set_PSP(uint32_t topOfProcStack) { __set_PSP(topOfProcStack); __ISB(); // always emit a barrier } /*__STATIC_INLINE*/ uint32_t CMSIS_STUB_SCB__get_MSP() { return __get_MSP(); } /*__STATIC_INLINE*/ void* CMSIS_STUB_SCB__get_MSP_ResetValue() { // // Ignore first full frame // #if defined(TARGET_LPC1768) return (void*)0x10007FFC; #elif defined(TARGET_K64F) return (void*)0x2002FFFC; #elif defined(TARGET_STM32F411RE) return (void*)0x2001FFFC; #elif defined(TARGET_STM32F401RE) return (void*)0x20017FFC; #elif defined(TARGET_STM32L152RE) return (void*)0x20013FFC; #elif defined(TARGET_STM32F091RC) return (void*)0x20017FFC; #else !ERROR not supported platform #endif } /*__STATIC_INLINE*/ uint32_t CMSIS_STUB_SCB__get_MSP_StackSize() { return __StackTop - __StackLimit; } /*__STATIC_INLINE*/ void CMSIS_STUB_SCB__set_MSP(uint32_t topOfMainStack) { __set_MSP(topOfMainStack); __ISB(); // always emit a barrier } /*__STATIC_INLINE*/ uint32_t CMSIS_STUB_SCB__get_PRIMASK() { return __get_PRIMASK(); } /*__STATIC_INLINE*/ uint32_t CMSIS_STUB_SCB__set_PRIMASK(uint32_t priMask) { register uint32_t prev = __get_PRIMASK(); __set_PRIMASK(priMask); __ISB(); return prev; } /*__STATIC_INLINE*/ void CMSIS_STUB_SCB__Enable_Irq() { __enable_irq(); __ISB(); } /*__STATIC_INLINE*/ void CMSIS_STUB_SCB__Disable_Irq() { __disable_irq(); __ISB(); } // // vvvvv !!! Cortex M3 only !!! vvvvv // #if (__CORTEX_M >= 0x03) // //#define __enable_fault_irq __enable_fiq // //#define __disable_fault_irq __disable_fiq /*__STATIC_INLINE*/ void CMSIS_STUB_SCB__Enable_Fault_Irq() { __enable_fault_irq(); __ISB(); } /*__STATIC_INLINE*/ void CMSIS_STUB_SCB__Disable_Fault_Irq() { __disable_fault_irq(); __ISB(); } /*__STATIC_INLINE*/ uint32_t CMSIS_STUB_SCB__get_BASEPRI() { return __get_BASEPRI() >> (8 - __NVIC_PRIO_BITS); } /*__STATIC_INLINE*/ uint32_t CMSIS_STUB_SCB__set_BASEPRI(uint32_t basePri) { __set_PRIMASK(1); __ISB(); register uint32_t prev = __get_BASEPRI() >> (8 - __NVIC_PRIO_BITS); __set_BASEPRI(basePri << (8 - __NVIC_PRIO_BITS)); __set_PRIMASK(0); __ISB(); return prev; } /*__STATIC_INLINE*/ uint32_t CMSIS_STUB_SCB__get_FAULTMASK() { return __get_FAULTMASK(); } /*__STATIC_INLINE*/ void CMSIS_STUB_SCB__set_FAULTMASK(uint32_t faultMask) { __set_FAULTMASK(faultMask); } #endif /* (__CORTEX_M >= 0x03) */ // // vvvvv !!! Cortex M4 only !!! vvvvv // #if (__CORTEX_M >= 0x04) // // CCR // /*__STATIC_INLINE*/ uint32_t CUSTOM_STUB_SCB__get_FPCCR() { return __get_FPSCR(); } /*__STATIC_INLINE*/ void CUSTOM_STUB_SCB__set_FPCCR(uint32_t fpscr) { return __set_FPSCR(fpscr); } #else /* (__CORTEX_M != 0x04) */ // // CCR // // TODO: eliminate both functions below for M0 /*__STATIC_INLINE*/ uint32_t CUSTOM_STUB_SCB__get_FPCCR( ) { return *((uint32_t volatile *)0xE000EF34); } /*__STATIC_INLINE*/ void CUSTOM_STUB_SCB__set_FPCCR( uint32_t fpscr ) { *((uint32_t volatile *)0xE000EF34) = fpscr; } #endif /*__STATIC_INLINE*/ void CUSTOM_STUB_SCB_set_CCR(uint32_t value) { *((uint32_t volatile *)0xE000ED14) = value; } // // System Handlers // /*__STATIC_INLINE*/ void CUSTOM_STUB_SCB_SHCRS_EnableSystemHandler(uint32_t ex) { uint32_t SHCRS = *((uint32_t volatile *)0xE000ED24); SHCRS |= ex; *((uint32_t volatile *)0xE000ED24) = SHCRS; } /*__STATIC_INLINE*/ void CUSTOM_STUB_SCB_SHCRS_DisableSystemHandler(uint32_t ex) { uint32_t SHCRS = *((uint32_t volatile *)0xE000ED24); SHCRS &= ~ex; *((uint32_t volatile *)0xE000ED24) = SHCRS; } /*__STATIC_INLINE*/ void CUSTOM_STUB_SCB_ICSR_RaiseSystemException(uint32_t ex) { // // Set/Clears system handlers in ICSR register of SCB. // CMSIS does not allow using NVIC api to set/clear System Handlers. // uint32_t ICSR = *((uint32_t volatile *)0xE000ED04); ICSR |= ex; *((uint32_t volatile *)0xE000ED04) = ICSR; } /*__STATIC_INLINE*/ uint32_t CUSTOM_STUB_SCB_IPSR_GetCurrentISRNumber() { return __get_IPSR() & 0x000000FF; } /*__STATIC_INLINE*/ void CUSTOM_STUB_SCB_SCR_SetSystemControlRegister(uint32_t scr) { *((uint32_t volatile *)0xE000ED10) = scr; } /*__STATIC_INLINE*/ uint32_t CUSTOM_STUB_SCB_SCR_GetSystemControlRegister() { return *((uint32_t volatile *)0xE000ED10); } /*__STATIC_INLINE*/ void CMSIS_STUB_POWER_WaitForEvent() { __WFE(); } /*__STATIC_INLINE*/ void CMSIS_STUB_POWER_SendEvent() { __SEV(); } /*__STATIC_INLINE*/ void CMSIS_STUB_POWER_WaitForInterrupt() { __WFI(); } /*__STATIC_INLINE*/ __attribute__((naked)) __ATTRIBUTE_ALIGNMENT__ void CUSTOM_STUB_RaiseSupervisorCallForLongJump() { __ASM volatile ("svc #17"); } /*__STATIC_INLINE*/ __attribute__((naked)) __ATTRIBUTE_ALIGNMENT__ void CUSTOM_STUB_RaiseSupervisorCallForStartThreads() { __ASM volatile ("svc #18"); } /*__STATIC_INLINE*/ __attribute__((naked)) __ATTRIBUTE_ALIGNMENT__ void CUSTOM_STUB_RaiseSupervisorCallForRetireThread() { __ASM volatile ("svc #19"); } /*__STATIC_INLINE*/ /*__attribute__((naked))*/ __ATTRIBUTE_ALIGNMENT__ void CUSTOM_STUB_RaiseSupervisorCallForSnapshotProcessModeRegisters() { __ASM volatile ("svc #20"); } //--// // // The managed portion of the SVC_Handler // void SVC_Handler_Zelig_VFP_NoFPContext(); void SVC_Handler_Zelig(); void CUSTOM_STUB_NotifySoftwareFrameSnapshot(void* frame, int size); // // A convenience storage space to signal what mode to return too // Initialized to crash, as the Thread Manager needs to set it right // uint32_t svc_exc_return = 0xDEADBEEF; void CUSTOM_STUB_SetExcReturn(uint32_t ret) { svc_exc_return = ret; } //--// //--// //--// // !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! // !!! KEEP IN SYNC WITH ProcessorARMv7M.Context.SoftwareFrame & HardwareFrame !!! // !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! #define SW_FRAME_SIZE 10 #define HW_FRAME_SIZE 8 #define FRAME_SIZE SW_FRAME_SIZE + HW_FRAME_SIZE // // A convenience storage space to snapshot all registers for Mark & Sweep GC // uint32_t sw_hw__frame[FRAME_SIZE]; // // Pull // /*__STATIC_INLINE*/ __ATTRIBUTE_ALIGNMENT__ uint32_t* CUSTOM_STUB_FetchSoftwareFrameSnapshot() { // // Return the snapshot from the storage area at sw_hw__frame // return &sw_hw__frame[0]; } // // Push // extern void CUSTOM_STUB_NotifySoftwareFrameSnapshot(void* frame, int size); /*__STATIC_INLINE*/ __ATTRIBUTE_ALIGNMENT__ void NotifySoftwareFrameSnapshot() { // // Grab the snapshot from the storage area at sw_hw__frame // CUSTOM_STUB_NotifySoftwareFrameSnapshot(sw_hw__frame, FRAME_SIZE); } #if __CORTEX_M0 __attribute__((naked)) //__ATTRIBUTE_ALIGNMENT__ void SVC_Handler(void) { //__DIRECTIVE_ALIGNMENT__; __ASM volatile ("MOVS R0, #0x4"); // Test bit 3 to use decide which stack pointer we are coming from __ASM volatile ("MOV R1, LR"); __ASM volatile ("TST R0, R1"); __ASM volatile ("BEQ __FROM_MSP"); __ASM volatile ("__FROM_PSP:"); __ASM volatile ("MRS R0, psp"); __ASM volatile ("__FROM_MSP:"); __ASM volatile ("MRS R0, msp"); // // Test for SupervisorCall__SnapshotProcessModeRegisters (0x14) and snapshot // all remaining registers onto the stack first and into the convenience space // right after // { //__ASM volatile ("LDR R1, [R0 , #24]"); // load the SVC number //__ASM volatile ("LDRH R1, [R1, #-2]"); //__ASM volatile ("MOV R2, #0X00FF"); //__ASM volatile ("AND R1, R1, R2"); //__ASM volatile ("CMP R1, #20"); // check if we are serving a frame snapshot (SVC_Code.SupervisorCall__SnapshotProcessModeRegisters) ... //__ASM volatile ("BNE __SVCCALL"); // ... skip if not { // // Snapshot // __ASM volatile ("MOV R2 , LR"); // Save LR and CONTROL, to save the status and privilege/stack mode __ASM volatile ("MRS R3 , CONTROL"); __ASM volatile ("STMIA R0!, {R2-R3}"); // Stack the SW stack frame, a total of 10 registers, including R2/3 __ASM volatile ("STMIA R0!, {R4-R7}"); // Keep stacking... __ASM volatile ("MOV R4, R8"); // Keep stacking... __ASM volatile ("MOV R5, R9"); // Keep stacking... __ASM volatile ("MOV R6, R10"); // Keep stacking... __ASM volatile ("MOV R7, R11"); // Keep stacking... __ASM volatile ("STMIA R0!, {R4-R7}"); // Done! // // Now the stack has the full frame of 18 registers (RegistersOnStack) // We need to move the frame to the convenience space and then pop the // Software frame before return // __ASM volatile ("MOV R1 , %0" : /*output*/ : "r"(&sw_hw__frame[0])); __ASM volatile ("MOV R2 , R0"); // R0 contains the beginning of the frame __ASM volatile ("MOV R4, #18"); // // SAVE FRAME LOOP - start // __ASM volatile ("__COPY_TO_FRAME:"); __ASM volatile ("LDR R3, [R2]"); __ASM volatile ("STR R3, [R1]"); __ASM volatile ("ADD R2 , #4"); __ASM volatile ("ADD R1 , #4"); __ASM volatile ("SUB R4, #1"); __ASM volatile ("CMP R4, #0"); __ASM volatile ("BNE __COPY_TO_FRAME"); // // SAVE FRAME LOOP - end // __ASM volatile ("LDMIA R0!, {R4-R7}"); // Unstack the SW frame (10 registers) before proceeding as usual __ASM volatile ("MOV R8, R4"); // Keep unstacking... __ASM volatile ("MOV R9, R5"); // Keep unstacking... __ASM volatile ("MOV R10, R6"); // Keep unstacking... __ASM volatile ("MOV R11, R7"); // Keep unstacking... __ASM volatile ("SUB R0, #40"); // Set R0 to point to the top of the stack frame for the next registers __ASM volatile ("LDMIA R0!, {R2-R3}"); // Keep unstacking... __ASM volatile ("LDMIA R0!, {R4-R7}"); // Done! __ASM volatile ("MOV LR, R2"); // Restore LR and CONTROL, to restore the status and privilege/stack mode __ASM volatile ("MSR CONTROL, R3"); __ASM volatile ("ISB"); // architectural recommendation, always use ISB after updating control register } } // // End of snapshot // // // Normal service call // __ASM volatile ("__SVCCALL:"); __ASM volatile ("MOV R2, %0" : /*output*/ : "r"(&svc_exc_return) ); __ASM volatile ("MOV R1, LR"); __ASM volatile ("STR R1, [R2]"); //////__ASM volatile ("MOV R1, %0" : /*output*/ : "r"(&SVC_Handler_Zelig)); //////__ASM volatile ("BX R1"); SVC_Handler_Zelig(); // // Push - disabled in favor of polling from managed code to recover snapshot // //NotifySoftwareFrameSnapshot(); __ASM volatile ("MOV R1, %0" : /*output*/ : "r"(&svc_exc_return)); __ASM volatile ("LDR R1, [R2]"); __ASM volatile ("BX R1"); } /*__STATIC_INLINE*/ uint32_t CMSIS_STUB_SCB__get_BASEPRI() { return 0; } /*__STATIC_INLINE*/ uint32_t CMSIS_STUB_SCB__set_BASEPRI(uint32_t basePri) { LLOS__UNREFERENCED_PARAMETER(basePri); return 0; } /*__STATIC_INLINE*/ uint32_t CMSIS_STUB_SCB__get_FAULTMASK() { return 0; } #else __attribute__((naked)) //__ATTRIBUTE_ALIGNMENT__ void SVC_Handler(void) { //__DIRECTIVE_ALIGNMENT__; __ASM volatile ("TST LR, #0x4"); // Test bit 3 to use decide which stack pointer we are coming from __ASM volatile ("ITE EQ"); __ASM volatile ("MRSEQ R0, msp"); __ASM volatile ("MRSNE R0, psp"); // // Test for SupervisorCall__SnapshotProcessModeRegisters (0x14) and snapshot // all remaining registers onto the stack first and into the convenience space // right after // TODO: move to managed layer // { __ASM volatile ("LDR R12, [R0 , #24]"); // load the SVC number __ASM volatile ("LDRH R12, [R12, #-2]"); __ASM volatile ("BICS R12, R12, #0xFF00"); __ASM volatile ("CMP R12, #20"); // check if we are serving a frame snapshot (SVC_Code.SupervisorCall__SnapshotProcessModeRegisters) ... __ASM volatile ("BNE __SVCCALL"); // ... skip if not { // // Snapshot // __ASM volatile ("MOV R2 , LR"); // Save LR and CONTROL, to save the status and privilege/stack mode __ASM volatile ("MRS R3 , CONTROL"); __ASM volatile ("STMDB R0!, {R2-R11}"); // Push the SW stack frame, a total of 10 registers, including R2/3 // // Now the stack has the full frame of 18 registers (RegistersOnStack) // We need to move the frame to the convenience space and then pop the // Software frame before return // __ASM volatile ("MOV R1 , %0" : /*output*/ : "r"(&sw_hw__frame[0])); __ASM volatile ("MOV R2 , R0"); // R0 contains the beginning of the frame __ASM volatile ("MOV R12, #18"); // // SAVE FRAME LOOP - start // __ASM volatile ("__COPY_TO_FRAME:"); __ASM volatile ("LDR R3, [R2]"); __ASM volatile ("STR R3, [R1]"); __ASM volatile ("ADD R2 , #4"); __ASM volatile ("ADD R1 , #4"); __ASM volatile ("SUBS R12, #1"); __ASM volatile ("CMP R12, #0"); __ASM volatile ("BNE __COPY_TO_FRAME"); // // SAVE FRAME LOOP - end // __ASM volatile ("LDMIA R0!, {R2-R11}"); // Unstack the SW frame (10 registers) before proceeding as usual } } // // End of snapshot // // // Normal service call // __ASM volatile ("__SVCCALL:"); __ASM volatile ("MOV R1, %0" : /*output*/ : "r"(&svc_exc_return) ); __ASM volatile ("STR LR, [R1]"); #if __FPU_USED != 0 SVC_Handler_Zelig_VFP_NoFPContext(); #else SVC_Handler_Zelig(); #endif // // Push // //NotifySoftwareFrameSnapshot(); __ASM volatile ("MOV R1, %0" : /*output*/ : "r"(&svc_exc_return)); __ASM volatile ("LDR LR, [R1]"); __ASM volatile ("BX LR"); } #endif //--// //--// //--// // // The managed portion of the PendSV_Handler // extern void PendSV_Handler_Zelig_VFP(); extern void PendSV_Handler_Zelig(); // // A convenience storage space to signal when the floating // point context is active // #if __CORTEX_M0 __attribute__((naked)) //__ATTRIBUTE_ALIGNMENT__ void PendSV_Handler(void) { //__DIRECTIVE_ALIGNMENT__; // 8 bytes alignment __ASM volatile ("MRS R0, PSP"); // Save current process stack pointer value into R0 __ASM volatile ("SUB R0, #40"); // Allocate space for R4-R11, and LR/CONTROL as well (*) __ASM volatile ("MOV R2, LR"); // Save LR and CONTROL, to save the status and privilege/stack mode __ASM volatile ("MRS R3, CONTROL"); __ASM volatile ("STMIA R0!, {R2-R3}"); // Stack the SW stack frame, a total of 10 registers, including R2/3 __ASM volatile ("STMIA R0!, {R4-R7}"); // Keep stacking... __ASM volatile ("MOV R4, R8"); // Keep stacking... __ASM volatile ("MOV R5, R9"); // Keep stacking... __ASM volatile ("MOV R6, R10"); // Keep stacking... __ASM volatile ("MOV R7, R11"); // Keep stacking... __ASM volatile ("STMIA R0!, {R4-R7}"); // Done! __ASM volatile ("SUB R0, #40"); // Set R0 to be the top of the stack again PendSV_Handler_Zelig(); // Perform context switch, practically setting the stack pointer for the next task __ASM volatile ("ADD R0, #24"); // Set R0 to point to R8 in the stack frame (4th register to the last...) __ASM volatile ("LDMIA R0!, {R4-R7}"); // Unstack the next tasks state __ASM volatile ("MOV R8, R4"); // Keep unstacking... __ASM volatile ("MOV R9, R5"); // Keep unstacking... __ASM volatile ("MOV R10, R6"); // Keep unstacking... __ASM volatile ("MOV R11, R7"); // Keep unstacking... __ASM volatile ("SUB R0, #40"); // Set R0 to point to the top of the stack frame for the next registers __ASM volatile ("LDMIA R0!, {R2-R3}"); // Keep unstacking... __ASM volatile ("LDMIA R0!, {R4-R7}"); // Done! __ASM volatile ("MOV LR, R2"); // Restore LR and CONTROL, to restore the status and privilege/stack mode __ASM volatile ("MSR CONTROL, R3"); __ASM volatile ("ISB"); // architectural recommendation, always use ISB after updating control register __ASM volatile ("ADD R0, #16"); // (*) cleanup space for R4-R11, and LR/CONTROL as well, and have stack point to top of HW frame __ASM volatile ("MSR PSP, R0"); // update stack pointer to correct location after unstacking __ASM volatile ("BX LR"); } #else __attribute__((naked)) //__ATTRIBUTE_ALIGNMENT__ void PendSV_Handler(void) { //__DIRECTIVE_ALIGNMENT__; // 8 bytes alignment __ASM volatile ("MRS R0, PSP"); // Save current process stack pointer value into R0 #if __FPU_USED != 0 __ASM volatile ("ANDS R1, LR, #0x10"); // When bit 4 in LR is zero (0), we need to stack FP registers as well __ASM volatile ("CMP R1, #0"); // R1 is the second parameter of PendSV_Handler_Zelig_VFP_FullFPContext __ASM volatile ("IT EQ"); __ASM volatile ("VSTMDBEQ R0!, {S16-S31}"); #endif __ASM volatile ("MOV R2, LR"); // Save LR and CONTROL, to save the status and privilege/stack mode __ASM volatile ("MRS R3, CONTROL"); __ASM volatile ("STMDB R0!, {R2-R11}"); // Stack the SW stack frame, a total of 10 registers, including R2/3 #if __FPU_USED != 0 PendSV_Handler_Zelig_VFP(); #else PendSV_Handler_Zelig(); // Perform context switch, practically setting the stack pointer for the next task #endif __ASM volatile ("LDMIA R0!, {R2-R11}"); // Unstack the next tasks state __ASM volatile ("MOV LR, R2"); // Restore LR and CONTROL, to restore the status and privilege/stack mode __ASM volatile ("MSR CONTROL, R3"); __ASM volatile ("ISB"); // architectural recommendation, always use ISB after updating control register #if __FPU_USED != 0 __ASM volatile ("ANDS R1, LR, #0x10"); // When bit 4 in LR is zero (0), we need to stack FP registers as well __ASM volatile ("CMP R1, #0"); __ASM volatile ("IT EQ"); __ASM volatile ("VLDMIAEQ R0!, {S16-S31}"); #endif __ASM volatile ("MSR PSP, R0"); // update stack pointer to correct location after unstacking __ASM volatile ("BX LR"); } #endif //--// //--// //--// void CUSTOM_STUB_K64F_DisableMPU() { uint32_t CESR = *((uint32_t volatile *)0x4000D000); CESR &= ~(0x00000001); *((uint32_t volatile *)0x4000D000) = CESR; } // According to http://www.st.com/st-web-ui/static/active/en/resource/technical/document/programming_manual/DM00046982.pdf // pg. 186 the MPU is off by default // TODO: Someone should double-check I got the address right void CUSTOM_STUB_STM32F4xx_DisableMPU() { /*uint32_t CESR = *((uint32_t volatile *)0xE000ED94); CESR &= ~(0x00000001); *((uint32_t volatile *)0xE000ED94) = CESR;*/ } } ================================================ FILE: Zelig/os_layer/ports/mbed/mbed_debug.cpp ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // #include "mbed_helpers.h" #include //--// extern "C" { int GetANumber() { // // we will get max a 24 bit numer, never smaller than 42 // const int32_t max = (1 << 24) - 1; return (rand() % max) + 42; } void Nop() { asm("nop"); } void mbedPrint(const char *str) { printf("%s", str); } // // Debugging from BugCheck // #define MAXLOGSTRINGSIZE 256 void ConvertToCharString(char* output, const uint16_t* input, const uint32_t length) { for (unsigned i = 0; i < length; i++) { uint16_t ch = input[i]; output[i] = (ch > 0xFF) ? '?' : (char)ch; } } void DebugLogPrint(char* message) { LLOS__UNREFERENCED_PARAMETER(message); // To automatically dump out the debug log into gdb output, input the following commands // to set a breakpoint as such: /* br DebugLogPrint commands silent printf "DebugLog: %s\n", message cont end */ asm("nop"); } void DebugLog0(uint16_t* message, uint32_t length) { char buffer[MAXLOGSTRINGSIZE]; if (length < MAXLOGSTRINGSIZE) { ConvertToCharString(buffer, message, length); buffer[length] = '\0'; DebugLogPrint(buffer); } else { DebugLogPrint((char*)"ERROR: MAXLOGSTRINGSIZE exceeded"); } } void DebugLog1(uint16_t* message, uint32_t length, int32_t p1) { char buffer[MAXLOGSTRINGSIZE]; if (length < MAXLOGSTRINGSIZE) { ConvertToCharString(buffer, message, length); buffer[length] = '\0'; { char buffer2[MAXLOGSTRINGSIZE]; snprintf(buffer2, MAXLOGSTRINGSIZE, buffer, p1); DebugLogPrint(buffer2); } } else { DebugLogPrint((char*)"ERROR: MAXLOGSTRINGSIZE exceeded"); } } void DebugLog2(uint16_t* message, uint32_t length, int32_t p1, int32_t p2) { char buffer[MAXLOGSTRINGSIZE]; if (length < MAXLOGSTRINGSIZE) { ConvertToCharString(buffer, message, length); buffer[length] = '\0'; { char buffer2[MAXLOGSTRINGSIZE]; snprintf(buffer2, MAXLOGSTRINGSIZE, buffer, p1, p2); DebugLogPrint(buffer2); } } else { DebugLogPrint((char*)"ERROR: MAXLOGSTRINGSIZE exceeded"); } } void DebugLog3(uint16_t* message, uint32_t length, int32_t p1, int32_t p2, int32_t p3) { char buffer[MAXLOGSTRINGSIZE]; if (length < MAXLOGSTRINGSIZE) { ConvertToCharString(buffer, message, length); buffer[length] = '\0'; { char buffer2[MAXLOGSTRINGSIZE]; snprintf(buffer2, MAXLOGSTRINGSIZE, buffer, p1, p2, p3); DebugLogPrint(buffer2); } } else { DebugLogPrint((char*)"ERROR: MAXLOGSTRINGSIZE exceeded"); } } void DebugLog4(uint16_t* message, uint32_t length, int32_t p1, int32_t p2, int32_t p3, int32_t p4) { char buffer[MAXLOGSTRINGSIZE]; if (length < MAXLOGSTRINGSIZE) { ConvertToCharString(buffer, message, length); buffer[length] = '\0'; { char buffer2[MAXLOGSTRINGSIZE]; snprintf(buffer2, MAXLOGSTRINGSIZE, buffer, p1, p2, p3, p4); DebugLogPrint(buffer2); } } else { DebugLogPrint((char*)"ERROR: MAXLOGSTRINGSIZE exceeded"); } } void DebugLog5(uint16_t* message, uint32_t length, int32_t p1, int32_t p2, int32_t p3, int32_t p4, int32_t p5) { char buffer[MAXLOGSTRINGSIZE]; if (length < MAXLOGSTRINGSIZE) { ConvertToCharString(buffer, message, length); buffer[length] = '\0'; { char buffer2[MAXLOGSTRINGSIZE]; snprintf(buffer2, MAXLOGSTRINGSIZE, buffer, p1, p2, p3, p4, p5); DebugLogPrint(buffer2); } } else { DebugLogPrint((char*)"ERROR: MAXLOGSTRINGSIZE exceeded"); } } // // Faults and Diagnostic // uint32_t CUSTOM_STUB_DebuggerConnected() { #if __CORTEX_M0 return false; #else return (CoreDebug->DHCSR & 0x00000001); #endif } uint32_t CUSTOM_STUB_GetProgramCounter() { return 0; } uint32_t CUSTOM_STUB_SCB__get_CFSR() { return *((uint32_t volatile *)0xE000ED28); } uint32_t CUSTOM_STUB_SCB__get_HFSR() { return *((uint32_t volatile *)0xE000ED2C); } uint32_t CUSTOM_STUB_SCB__get_MMFAR() { return *((uint32_t volatile *)0xE000ED34); } uint32_t CUSTOM_STUB_SCB__get_BFAR() { return *((uint32_t volatile *)0xE000ED38); } void BreakWithTrap() { // this will likely generate a hard fault __builtin_trap(); } void Break() { if (CUSTOM_STUB_DebuggerConnected()) { asm("bkpt"); } else { while (1) { __WFE(); } } } // placing this outside the BreakPoint() function to avoid compiler unused var warning volatile uint32_t valueToWatch; void Breakpoint(unsigned n) { valueToWatch = n; Break(); } // // Stubs for Faults // extern void Zelig_Exception_MemManage_Handler (); extern void Zelig_Exception_BusFault_Handler (); extern void Zelig_Exception_UsageFault_Handler(); extern void Zelig_Exception_HardFault_Handler (); //--// #if __CORTEX_M0 #define DEFAULT_FAULT_HANDLER(handler) \ //////__ASM volatile ("MOVS R0, #0x4"); \ //////__ASM volatile ("MOV R1, LR"); \ //////__ASM volatile ("TST R0, R1"); \ //////__ASM volatile ("BEQ __FROM_MSP"); \ //////__ASM volatile ("__FROM_PSP:"); \ __ASM volatile ("MRS R0, psp"); \ //////__ASM volatile ("__FROM_MSP:"); \ //////__ASM volatile ("MRS R0, msp"); \ handler(); \ __ASM volatile ("BX LR"); \ #else #define DEFAULT_FAULT_HANDLER(handler) \ __ASM volatile ("TST LR, #0x4"); \ __ASM volatile ("ITE EQ"); \ __ASM volatile ("MRSEQ R0, msp"); \ __ASM volatile ("MRSNE R0, psp"); \ handler(); \ __ASM volatile ("BX LR"); \ #endif __attribute__((naked)) void HardFault_Handler(void) { DEFAULT_FAULT_HANDLER( Zelig_Exception_HardFault_Handler ); } __attribute__((naked)) void MemManage_Handler(void) { DEFAULT_FAULT_HANDLER( Zelig_Exception_MemManage_Handler ); } __attribute__((naked)) void BusFault_Handler(void) { DEFAULT_FAULT_HANDLER( Zelig_Exception_BusFault_Handler ); } __attribute__((naked)) void UsageFault_Handler(void) { DEFAULT_FAULT_HANDLER( Zelig_Exception_UsageFault_Handler ); } } ================================================ FILE: Zelig/os_layer/ports/mbed/mbed_ethernet.cpp ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // #include "mbed_helpers.h" #include "mbed.h" #include "EthernetInterface.h" #include "init.h" #include "tcpip.h" #include "dns.h" #include "netifapi.h" #include "Netdb.h" #include "tcp.h" #include "Sockets.h" #include "llos_error.h" int32_t WStringToCharBuffer(char* output, uint32_t outputBufferLength, const uint16_t* input, const uint32_t length) { if (length > outputBufferLength) { return -1; } uint32_t i; for (i = 0; i < length; i++) { uint16_t ch = input[i]; output[i] = (ch > 0xFF) ? '?' : (char)ch; } return i; } extern "C" { #define MAXADDRSTRINGSIZE 32 uint32_t LLOS_ethernet_address_from_string(uint16_t* address, uint32_t addrlen) { char ipBuffer[MAXADDRSTRINGSIZE]; char tempAddress[5]; uint32_t result = 0; if (WStringToCharBuffer(ipBuffer, MAXADDRSTRINGSIZE, address, addrlen) < 0) { return -1; } // Dot-decimal notation int scanResult = std::sscanf(ipBuffer, "%3u.%3u.%3u.%3u", (unsigned int*)&tempAddress[0], (unsigned int*)&tempAddress[1], (unsigned int*)&tempAddress[2], (unsigned int*)&tempAddress[3]); if (scanResult == 4) { result |= tempAddress[3] << 24; result |= tempAddress[2] << 16; result |= tempAddress[1] << 8; result |= tempAddress[0]; } return result; } HRESULT LLOS_ethernet_dhcp_init() { return EthernetInterface::init(); } HRESULT LLOS_ethernet_staticIP_init(const uint16_t* ip, const uint32_t ipLen, const uint16_t* mask, const uint32_t maskLen, const uint16_t* gateway, const uint32_t gatewayLen) { char ipBuffer[MAXADDRSTRINGSIZE]; char maskBuffer[MAXADDRSTRINGSIZE]; char gatewayBuffer[MAXADDRSTRINGSIZE]; if (ip == NULL || mask == NULL || gateway == NULL) { return LLOS_E_INVALID_PARAMETER; } if (ipLen < MAXADDRSTRINGSIZE && maskLen < MAXADDRSTRINGSIZE && gatewayLen < MAXADDRSTRINGSIZE) { WStringToCharBuffer(ipBuffer, MAXADDRSTRINGSIZE, ip, ipLen); WStringToCharBuffer(maskBuffer, MAXADDRSTRINGSIZE, mask, maskLen); WStringToCharBuffer(gatewayBuffer, MAXADDRSTRINGSIZE, gateway, gatewayLen); ipBuffer[ipLen] = '\0'; maskBuffer[maskLen] = '\0'; gatewayBuffer[gatewayLen] = '\0'; return EthernetInterface::init(ipBuffer, maskBuffer, gatewayBuffer); } return LLOS_E_INVALID_PARAMETER; } HRESULT LLOS_ethernet_connect(uint32_t timeout) { return EthernetInterface::connect(timeout); } HRESULT LLOS_ethernet_disconnect() { return EthernetInterface::disconnect(); } HRESULT LLOS_ethernet_get_macAddress(uint16_t* address, uint32_t bufferLen) { if (address == NULL) { return LLOS_E_INVALID_PARAMETER; } char* temp = EthernetInterface::getMACAddress(); while (*temp != '\0' && bufferLen > 0) { *address = *temp & 0x00FF; address++; temp++; bufferLen--; } return S_OK; } HRESULT LLOS_ethernet_get_IPv4Address(uint16_t* address, uint32_t bufferLen) { if (address == NULL) { return LLOS_E_INVALID_PARAMETER; } char* temp = EthernetInterface::getIPAddress(); while (*temp != '\0' && bufferLen > 0) { *address = *temp & 0x00FF; address++; temp++; bufferLen--; } return S_OK; } HRESULT LLOS_ethernet_get_gatewayIPv4Address(uint16_t* address, uint32_t bufferLen) { if (address == NULL) { return LLOS_E_INVALID_PARAMETER; } char* temp = EthernetInterface::getGateway(); while (*temp != '\0' && bufferLen > 0) { *address = *temp & 0x00FF; address++; temp++; bufferLen--; } return S_OK; } HRESULT LLOS_ethernet_get_networkIPv4Mask(uint16_t* mask, uint32_t bufferLen) { if (mask == NULL) { return LLOS_E_INVALID_PARAMETER; } char* temp = EthernetInterface::getNetworkMask(); while (*temp != '\0' && bufferLen > 0) { *mask = *temp & 0x00FF; mask++; temp++; bufferLen--; } return S_OK; } } ================================================ FILE: Zelig/os_layer/ports/mbed/mbed_gpio.cpp ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // #include "mbed_helpers.h" #include "llos_gpio.h" #include "llos_memory.h" //--// extern "C" { typedef struct LLOS_MbedGpio { gpio_t Pin; gpio_irq_t Irq; LLOS_GPIO_InterruptCallback Callback; LLOS_Context Context; } LLOS_MbedGpio; HRESULT LLOS_GPIO_AllocatePin(uint32_t pin_number, LLOS_Context* pPin) { LLOS_MbedGpio *pGpio; if (pPin == NULL) { return LLOS_E_INVALID_PARAMETER; } pGpio = (LLOS_MbedGpio*)AllocateFromManagedHeap(sizeof(LLOS_MbedGpio)); if (pGpio == NULL) { return LLOS_E_OUT_OF_MEMORY; } gpio_init( &pGpio->Pin, (PinName)pin_number); pGpio->Callback = NULL; pGpio->Context = NULL; *pPin = (LLOS_Context)pGpio; return S_OK; } void LLOS_GPIO_FreePin(LLOS_Context pin) { LLOS_MbedGpio *pGpio = (LLOS_MbedGpio*)pin; if (pGpio != NULL) { gpio_irq_disable(&pGpio->Irq); gpio_irq_free(&pGpio->Irq); FreeFromManagedHeap(pin); } } static void HandleGpioInterrupt(uint32_t id, gpio_irq_event evt) { LLOS_MbedGpio *pGpio = (LLOS_MbedGpio*)id; LLOS_GPIO_Edge edge = evt == IRQ_RISE ? LLOS_GPIO_EdgeRising : LLOS_GPIO_EdgeFalling; pGpio->Callback((LLOS_Context)&pGpio->Pin, pGpio->Context, edge); } HRESULT LLOS_GPIO_EnablePin(LLOS_Context pin, LLOS_GPIO_Edge edge, LLOS_GPIO_InterruptCallback callback, LLOS_Context callback_context) { LLOS_MbedGpio *pGpio = (LLOS_MbedGpio*)pin; int edgeRiseEnable = 0; int edgeFallEnable = 0; if (pGpio == NULL || callback == NULL || edge == LLOS_GPIO_EdgeNone) { return LLOS_E_INVALID_PARAMETER; } pGpio->Callback = callback; pGpio->Context = callback_context; if (0 != gpio_irq_init(&pGpio->Irq, pGpio->Pin.pin, (gpio_irq_handler)HandleGpioInterrupt, (uint32_t)pGpio)) { return LLOS_E_PIN_UNAVAILABLE; } switch (edge) { case LLOS_GPIO_EdgeBoth: edgeRiseEnable = 1; edgeFallEnable = 1; break; case LLOS_GPIO_EdgeFalling: edgeFallEnable = 1; break; case LLOS_GPIO_EdgeRising: edgeRiseEnable = 1; break; default: return LLOS_E_NOT_SUPPORTED; } gpio_irq_set(&pGpio->Irq, IRQ_RISE, edgeRiseEnable); gpio_irq_set(&pGpio->Irq, IRQ_FALL, edgeFallEnable); gpio_irq_enable(&pGpio->Irq); return S_OK; } HRESULT LLOS_GPIO_DisablePin(LLOS_Context pin) { LLOS_MbedGpio *pGpio = (LLOS_MbedGpio*)pin; if (pGpio != NULL) { gpio_irq_disable( &pGpio->Irq ); } return S_OK; } HRESULT LLOS_GPIO_SetPolarity(LLOS_Context pin, LLOS_GPIO_Polarity polarity) { LLOS__UNREFERENCED_PARAMETER(pin); LLOS__UNREFERENCED_PARAMETER(polarity); return LLOS_E_NOT_SUPPORTED; } HRESULT LLOS_GPIO_SetMode(LLOS_Context pin, LLOS_GPIO_Resistor resistor) { LLOS_MbedGpio *pGpio = (LLOS_MbedGpio*)pin; PinMode mode; switch (resistor) { case LLOS_GPIO_ResistorDefault: mode = PullDefault; break; case LLOS_GPIO_ResistorPullNone: mode = PullNone; break; case LLOS_GPIO_ResistorPullup: mode = PullUp; break; case LLOS_GPIO_ResistorPulldown: mode = PullDown; break; default: return LLOS_E_NOT_SUPPORTED; } gpio_mode(&pGpio->Pin, mode); return S_OK; } HRESULT LLOS_GPIO_SetDirection(LLOS_Context pin, LLOS_GPIO_Direction direction) { LLOS_MbedGpio *pGpio = (LLOS_MbedGpio*)pin; if (pGpio == NULL) { return LLOS_E_INVALID_PARAMETER; } if (direction == LLOS_GPIO_Output) { gpio_dir(&pGpio->Pin, PIN_OUTPUT); } else { gpio_dir(&pGpio->Pin, PIN_INPUT); } return S_OK; } HRESULT LLOS_GPIO_SetDebounce(LLOS_Context pin, LLOS_TimeSpan debounceTime) { LLOS__UNREFERENCED_PARAMETER(pin); LLOS__UNREFERENCED_PARAMETER(debounceTime); return LLOS_E_NOT_SUPPORTED; } HRESULT LLOS_GPIO_Write(LLOS_Context pin, int32_t value) { LLOS_MbedGpio *pGpio = (LLOS_MbedGpio*)pin; if (pGpio == NULL) { return LLOS_E_INVALID_PARAMETER; } gpio_write( &pGpio->Pin, value ); return S_OK; } int32_t LLOS_GPIO_Read(LLOS_Context pin) { LLOS_MbedGpio *pGpio = (LLOS_MbedGpio*)pin; if (pGpio == NULL) { return -1; } return gpio_read( &pGpio->Pin ); } HRESULT LLOS_GPIO_GetConfig(LLOS_Context pin, uint32_t* pin_number, LLOS_GPIO_Edge* edge, LLOS_GPIO_Resistor* resistor, LLOS_GPIO_Polarity* polarity) { LLOS__UNREFERENCED_PARAMETER(pin); LLOS__UNREFERENCED_PARAMETER(pin_number); LLOS__UNREFERENCED_PARAMETER(edge); LLOS__UNREFERENCED_PARAMETER(resistor); LLOS__UNREFERENCED_PARAMETER(polarity); return LLOS_E_NOT_SUPPORTED; } } ================================================ FILE: Zelig/os_layer/ports/mbed/mbed_helpers.h ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // // // Platform dependent configurations // #ifdef TARGET_LPC1768 #include "LPC17xx.h" #elif TARGET_K64F #include "MK64F12.h" #elif TARGET_STM32L152RE #include "stm32l1xx.h" #elif TARGET_STM32F411RE #include "stm32f4xx.h" #elif TARGET_STM32F401RE #include "stm32f4xx.h" #elif TARGET_STM32F091RC #include "stm32f0xx.h" #else #error Undefined plaform #endif #include "analogin_api.h" #include "analogout_api.h" #include "gpio_api.h" #include "gpio_irq_api.h" #include "spi_api.h" #include "i2c_api.h" #include "core_cmFunc.h" #include "us_ticker_api.h" #include "serial_api.h" #include "pwmout_api.h" #include #include //--// #ifndef LLOS__UNREFERENCED_PARAMETER #define LLOS__UNREFERENCED_PARAMETER(P) ((void)P) #endif //--// #define LLOS__PRESERVE_PRIMASK_STATE__SAVE() \ { uint32_t __primask = __get_PRIMASK(); { \ #define LLOS__PRESERVE_PRIMASK_STATE__RESTORE() \ } __set_PRIMASK(__primask); } \ //--// #if (__CORTEX_M >= 0x03) || (__CORTEX_SC >= 300) #define LLOS__PRESERVE_PRIMASK_STATE_M0_1__SAVE __NOP #else #define LLOS__PRESERVE_PRIMASK_STATE_M0_1__SAVE LLOS__PRESERVE_PRIMASK_STATE__SAVE #endif #if (__CORTEX_M >= 0x03) || (__CORTEX_SC >= 300) #define LLOS__PRESERVE_PRIMASK_STATE_M0_1__RESTORE __NOP #else #define LLOS__PRESERVE_PRIMASK_STATE_M0_1__RESTORE LLOS__PRESERVE_PRIMASK_STATE__RESTORE #endif //--// #define LLOS__PRESERVE_PRIMASK_STATE__FUNC(f) \ LLOS__PRESERVE_PRIMASK_STATE__SAVE(); \ f; \ LLOS__PRESERVE_PRIMASK_STATE__RESTORE(); \ //--// int32_t WStringToCharBuffer(char* output, uint32_t outputBufferLength, const uint16_t* input, const uint32_t length); //--// extern uint32_t* __StackTop; extern uint32_t* __StackLimit; ================================================ FILE: Zelig/os_layer/ports/mbed/mbed_i2c.cpp ================================================ #include "mbed_helpers.h" #include "llos_i2c.h" #include "llos_memory.h" //--// extern "C" { HRESULT LLOS_I2C_Initialize(int32_t sdaPin, int32_t sclPin, LLOS_Context* pChannel) { i2c_t *pI2C; if (pChannel == NULL) { return LLOS_E_INVALID_PARAMETER; } pI2C = (i2c_t*)AllocateFromManagedHeap(sizeof(i2c_t)); if (pI2C == NULL) { return LLOS_E_OUT_OF_MEMORY; } i2c_init(pI2C, (PinName)sdaPin, (PinName)sclPin); *pChannel = (LLOS_Context*)pI2C; return S_OK; } VOID LLOS_I2C_Uninitialize(LLOS_Context channel) { FreeFromManagedHeap(channel); } HRESULT LLOS_I2C_SetFrequency(LLOS_Context channel, uint32_t frequencyHz) { i2c_t *pI2C = (i2c_t*)channel; if (pI2C == NULL) { return LLOS_E_INVALID_PARAMETER; } i2c_frequency(pI2C, frequencyHz); return S_OK; } HRESULT LLOS_I2C_Enable(LLOS_Context channel) { LLOS__UNREFERENCED_PARAMETER(channel); return LLOS_E_NOT_SUPPORTED; } HRESULT LLOS_I2C_Disable(LLOS_Context channel) { LLOS__UNREFERENCED_PARAMETER(channel); return LLOS_E_NOT_SUPPORTED; } HRESULT LLOS_I2C_Write(LLOS_Context channel, uint32_t address, uint8_t* pBuffer, int32_t offset, int32_t *pLength, BOOL stop) { i2c_t *pI2C = (i2c_t*)channel; if (pI2C == NULL || pBuffer == NULL) { return LLOS_E_INVALID_PARAMETER; } *pLength = i2c_write(pI2C, address, (const char *)&pBuffer[offset], *pLength, stop); return S_OK; } HRESULT LLOS_I2C_Read(LLOS_Context channel, uint32_t address, uint8_t* pBuffer, int32_t offset, int32_t* pLength, BOOL stop) { i2c_t *pI2C = (i2c_t*)channel; if (pI2C == NULL || pBuffer == NULL) { return LLOS_E_INVALID_PARAMETER; } *pLength = i2c_read(pI2C, address, (char *)&pBuffer[offset], *pLength, stop); return S_OK; } HRESULT LLOS_I2C_Reset(LLOS_Context channel) { i2c_t *pI2C = (i2c_t*)channel; if (pI2C == NULL) { return LLOS_E_INVALID_PARAMETER; } i2c_reset(pI2C); return S_OK; } } ================================================ FILE: Zelig/os_layer/ports/mbed/mbed_mem.cpp ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // #include "mbed_helpers.h" // Enable this macro to shift object pointers from the beginning of the header to the beginning of the payload. #define CANONICAL_OBJECT_POINTERS struct Object; struct ObjectHeader { int32_t MultiUseWord; void* VTable; inline Object* get_Object() { #ifdef CANONICAL_OBJECT_POINTERS return reinterpret_cast(this + 1); #else // CANONICAL_OBJECT_POINTERS return reinterpret_cast(this); #endif // CANONICAL_OBJECT_POINTERS } }; struct Object { inline ObjectHeader* get_Header() { #ifdef CANONICAL_OBJECT_POINTERS return reinterpret_cast(this) - 1; #else // CANONICAL_OBJECT_POINTERS return reinterpret_cast(this); #endif // CANONICAL_OBJECT_POINTERS } }; extern "C" { // Must match consts defined in ObjectHeader.cs #define REFERENCE_COUNT_MASK 0xFF000000 #define REFERENCE_COUNT_SHIFT 24 // Helpers for starting / ending section of code that needs to be atomic __attribute__((always_inline)) __STATIC_INLINE void StartAtomicOperations(void) { __set_PRIMASK(1); } __attribute__((always_inline)) __STATIC_INLINE void EndAtomicOperations(void) { __set_PRIMASK(0); } __attribute__((always_inline)) __STATIC_INLINE void AddReferenceFast(Object* target) { if (target != NULL) { ObjectHeader* header = target->get_Header(); if (header->MultiUseWord & REFERENCE_COUNT_MASK) { header->MultiUseWord += (1 << REFERENCE_COUNT_SHIFT); } } } void AddReference(Object* target) { if (target != NULL) { ObjectHeader* header = target->get_Header(); StartAtomicOperations(); if (header->MultiUseWord & REFERENCE_COUNT_MASK) { header->MultiUseWord += (1 << REFERENCE_COUNT_SHIFT); } EndAtomicOperations(); } } // Return zero when target is dead after the call int ReleaseReferenceNative(Object* target) { int ret = 1; if (target != NULL) { ObjectHeader* header = target->get_Header(); StartAtomicOperations(); int32_t value = header->MultiUseWord; if (value & REFERENCE_COUNT_MASK) { value -= (1 << REFERENCE_COUNT_SHIFT); header->MultiUseWord = value; ret = value & REFERENCE_COUNT_MASK; } EndAtomicOperations(); } return ret; } Object* LoadAndAddReferenceNative(Object** target) { StartAtomicOperations(); Object* value = *target; AddReferenceFast(value); EndAtomicOperations(); return value; } Object* ReferenceCountingExchange(Object** target, Object* value) { StartAtomicOperations(); Object* oldValue = *target; *target = value; AddReferenceFast(value); EndAtomicOperations(); return oldValue; } Object* ReferenceCountingCompareExchange(Object** target, Object* value, Object* comparand) { StartAtomicOperations(); Object* oldValue = *target; Object* addRefTarget; if (oldValue == comparand) { *target = value; // Compare exchange succeeded, we need to add ref the new value // The old value's ref count will be passed back to the caller on return. addRefTarget = value; } else { // Target is not changed, we need to add ref the old value so it has // a ref count to pass back to caller on return addRefTarget = oldValue; } AddReferenceFast(addRefTarget); EndAtomicOperations(); return oldValue; } } ================================================ FILE: Zelig/os_layer/ports/mbed/mbed_memory.cpp ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // #include "mbed_helpers.h" #include "llos_memory.h" //--// extern "C" { HRESULT LLOS_MEMORY_GetMaxHeapSize(uint32_t* pMaxHeapSize) { if (pMaxHeapSize == NULL) { return LLOS_E_INVALID_PARAMETER; } *pMaxHeapSize = 0x4000; #if defined(__HEAP_SIZE) #if __HEAP_SIZE > 0 *pMaxHeapSize = __HEAP_SIZE; #endif #endif return S_OK; } uint32_t LLOS_MEMORY_GetDefaultManagedStackSize() { #if defined(__DEFAULT_STACK_SIZE) && __DEFAULT_STACK_SIZE > 0 return __DEFAULT_STACK_SIZE; #else // The following return value (0) will result in the default stack size defined in managed code being used return 0; #endif } HRESULT LLOS_MEMORY_Allocate(uint32_t size, uint8_t fill, LLOS_Opaque* pAllocation) { if (pAllocation == NULL) { return LLOS_E_INVALID_PARAMETER; } if (fill == 0) { *pAllocation = LLOS_CALLOC(size, 1); } else { *pAllocation = LLOS_MALLOC(size); if (*pAllocation != NULL) { LLOS_MEMSET(*pAllocation, fill, size); } } if (*pAllocation == NULL) { return LLOS_E_OUT_OF_MEMORY; } return S_OK; } HRESULT LLOS_MEMORY_Reallocate(LLOS_Opaque* pAllocation, uint32_t newSize) { LLOS_REALLOC(pAllocation, newSize); if (pAllocation == NULL && newSize > 0) { return LLOS_E_OUT_OF_MEMORY; } return S_OK; } VOID LLOS_MEMORY_Free(LLOS_Opaque address) { LLOS_FREE(address); } } ================================================ FILE: Zelig/os_layer/ports/mbed/mbed_nvic.cpp ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // #include "mbed_helpers.h" //--// extern "C" { // // NVIC // #if !__CORTEX_M0 /*__STATIC_INLINE*/ void CMSIS_STUB_NVIC_SetPriorityGrouping(uint32_t PriorityGroup) { NVIC_SetPriorityGrouping(PriorityGroup); __ISB(); // always emit a barrier } /*__STATIC_INLINE*/ uint32_t CMSIS_STUB_NVIC_GetPriorityGrouping(void) { return NVIC_GetPriorityGrouping(); } #endif /*__STATIC_INLINE*/ void CMSIS_STUB_NVIC_EnableIRQ(IRQn_Type IRQn) { NVIC_EnableIRQ(IRQn); } /*__STATIC_INLINE*/ void CMSIS_STUB_NVIC_DisableIRQ(IRQn_Type IRQn) { NVIC_DisableIRQ(IRQn); } /*__STATIC_INLINE*/ uint32_t CMSIS_STUB_NVIC_GetPendingIRQ(IRQn_Type IRQn) { return NVIC_GetPendingIRQ(IRQn); } /*__STATIC_INLINE*/ void CMSIS_STUB_NVIC_SetPendingIRQ(IRQn_Type IRQn) { NVIC_SetPendingIRQ(IRQn); } /*__STATIC_INLINE*/ void CMSIS_STUB_NVIC_ClearPendingIRQ(IRQn_Type IRQn) { NVIC_ClearPendingIRQ(IRQn); } #if !__CORTEX_M0 /*__STATIC_INLINE*/ uint32_t CMSIS_STUB_NVIC_GetActive(IRQn_Type IRQn) { return NVIC_GetActive(IRQn); } #endif /*__STATIC_INLINE*/ uint32_t CMSIS_STUB_NVIC_GetVector(IRQn_Type IRQn) { return NVIC_GetVector(IRQn); } /*__STATIC_INLINE*/ void CMSIS_STUB_NVIC_SetVector(IRQn_Type IRQn, uint32_t vector) { NVIC_SetVector(IRQn, vector); __ISB(); // always emit a barrier } /*__STATIC_INLINE*/ void CMSIS_STUB_NVIC_SetPriority(IRQn_Type IRQn, uint32_t priority) { NVIC_SetPriority(IRQn, priority); __ISB(); // always emit a barrier } /*__STATIC_INLINE*/ uint32_t CMSIS_STUB_NVIC_GetPriority(IRQn_Type IRQn) { return NVIC_GetPriority(IRQn); } #if !__CORTEX_M0 /*__STATIC_INLINE*/ uint32_t CMSIS_STUB_NVIC_EncodePriority(uint32_t PriorityGroup, uint32_t PreemptPriority, uint32_t SubPriority) { return NVIC_EncodePriority(PriorityGroup, PreemptPriority, SubPriority); } /*__STATIC_INLINE*/ void CMSIS_STUB_NVIC_DecodePriority(uint32_t Priority, uint32_t PriorityGroup, uint32_t* pPreemptPriority, uint32_t* pSubPriority) { NVIC_DecodePriority(Priority, PriorityGroup, pPreemptPriority, pSubPriority); } #endif /*__STATIC_INLINE*/ void CMSIS_STUB_NVIC_SystemReset(void) { NVIC_SystemReset(); } /*__STATIC_INLINE*/ void CUSTOM_STUB_NVIC_RaisePendSV() { *((uint32_t volatile *)0xE000ED04) = 0x10000000; // trigger PendSV } } ================================================ FILE: Zelig/os_layer/ports/mbed/mbed_overrides.cpp ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // #include "mbed_helpers.h" //--// extern "C" { // // NOTE: If you would like to configure your own MAC address, you can do so by // uncommenting the function below // //void mbed_mac_address(char *mac) //{ // mac[0] = (char)122; // mac[1] = (char)71; // mac[2] = (char)10; // mac[3] = (char)135; // mac[4] = (char)218; // mac[5] = (char)0; // // We want to force bits [1:0] of the most significant byte [0] // // to be "10" // // http://en.wikipedia.org/wiki/MAC_address // mac[0] |= 0x02; // force bit 1 to a "1" = "Locally Administered" // mac[0] &= 0xFE; // force bit 0 to a "0" = Unicast //} } ================================================ FILE: Zelig/os_layer/ports/mbed/mbed_pwm.cpp ================================================ #include "mbed_helpers.h" #include "llos_pwm.h" #include "llos_memory.h" extern "C" { typedef struct LLOS_MbedPwm { uint32_t PinName; uint32_t Period; uint32_t PulseWidth; float DutyCycle; pwmout_t Pwm; } LLOS_MbedPwm; HRESULT LLOS_PWM_Initialize(uint32_t pinName, LLOS_Context* pChannel) { LLOS_MbedPwm *pPwm; if (pChannel == NULL) { return LLOS_E_INVALID_PARAMETER; } pPwm = (LLOS_MbedPwm*)AllocateFromManagedHeap(sizeof(LLOS_MbedPwm)); if (pPwm == NULL) { return LLOS_E_OUT_OF_MEMORY; } pPwm->PinName = pinName; pPwm->Period = 20000; // 20ms pPwm->DutyCycle = 0.5; pPwm->PulseWidth = 0; pwmout_init(&pPwm->Pwm, (PinName)pinName); *pChannel = pPwm; return S_OK; } VOID LLOS_PWM_Uninitialize(LLOS_Context channel) { LLOS_MbedPwm *pPwm = (LLOS_MbedPwm*)channel; pwmout_free(&pPwm->Pwm); FreeFromManagedHeap(channel); } HRESULT LLOS_PWM_SetDutyCycle(LLOS_Context channel, uint32_t dutyCycleNumerator, uint32_t dutyCycleDenominator) { LLOS_MbedPwm *pPwm = (LLOS_MbedPwm*)channel; if (pPwm == NULL || dutyCycleDenominator == 0) { return LLOS_E_INVALID_PARAMETER; } pPwm->DutyCycle = (float)dutyCycleNumerator/(float)dutyCycleDenominator; pwmout_write(&pPwm->Pwm, pPwm->DutyCycle); return S_OK; } HRESULT LLOS_PWM_SetPeriod(LLOS_Context channel, uint32_t periodMicroSeconds) { LLOS_MbedPwm *pPwm = (LLOS_MbedPwm*)channel; if (pPwm == NULL) { return LLOS_E_INVALID_PARAMETER; } pPwm->Period = periodMicroSeconds; pwmout_period_us(&pPwm->Pwm, periodMicroSeconds); return S_OK; } HRESULT LLOS_PWM_SetPulseWidth(LLOS_Context channel, uint32_t widthMicroSeconds) { LLOS_MbedPwm *pPwm = (LLOS_MbedPwm*)channel; if (pPwm == NULL) { return LLOS_E_INVALID_PARAMETER; } pPwm->PulseWidth = widthMicroSeconds; pwmout_pulsewidth_us(&pPwm->Pwm, widthMicroSeconds); return S_OK; } HRESULT LLOS_PWM_SetPolarity(LLOS_Context channel, LLOS_PWM_Polarity polarity) { LLOS__UNREFERENCED_PARAMETER(channel); LLOS__UNREFERENCED_PARAMETER(polarity); return LLOS_E_NOT_SUPPORTED; } HRESULT LLOS_PWM_SetPrescaler(LLOS_Context channel, LLOS_PWM_Prescaler prescaler) { LLOS__UNREFERENCED_PARAMETER(channel); LLOS__UNREFERENCED_PARAMETER(prescaler); return LLOS_E_NOT_SUPPORTED; } HRESULT LLOS_PWM_Start(LLOS_Context channel) { LLOS_MbedPwm *pPwm = (LLOS_MbedPwm*)channel; if (pPwm == NULL) { return LLOS_E_INVALID_PARAMETER; } pwmout_write(&pPwm->Pwm, pPwm->DutyCycle); return S_OK; } HRESULT LLOS_PWM_Stop(LLOS_Context channel) { LLOS_MbedPwm *pPwm = (LLOS_MbedPwm*)channel; if (pPwm == NULL) { return LLOS_E_INVALID_PARAMETER; } pwmout_write(&pPwm->Pwm, 0.0); return S_OK; } } ================================================ FILE: Zelig/os_layer/ports/mbed/mbed_serial.cpp ================================================ #include "mbed_helpers.h" #include "llos_serial.h" #include "llos_memory.h" //--// extern "C" { typedef struct LLOS_MbedSerial { serial_t Port; LLOS_SERIAL_InterruptCallback Callback; LLOS_Context Context; LLOS_SERIAL_Config Config; } LLOS_MbedSerial; HRESULT LLOS_SERIAL_Open(int32_t rxPin, int32_t txPin, LLOS_SERIAL_Config** ppConfig, LLOS_Context* pChannel) { LLOS_MbedSerial *pSerial; if (pChannel == NULL) { return LLOS_E_INVALID_PARAMETER; } pSerial = (LLOS_MbedSerial*)AllocateFromManagedHeap(sizeof(LLOS_MbedSerial)); if (pSerial == NULL) { return LLOS_E_OUT_OF_MEMORY; } serial_init(&pSerial->Port, (PinName)txPin, (PinName)rxPin); *pChannel = (LLOS_Context)pSerial; *ppConfig = &pSerial->Config; return S_OK; } VOID LLOS_SERIAL_Close(LLOS_Context channel) { LLOS_MbedSerial *pSerial = (LLOS_MbedSerial*)channel; if (pSerial != NULL) { serial_free(&pSerial->Port); } FreeFromManagedHeap(pSerial); } HRESULT InternalSerialEnable(LLOS_Context channel, LLOS_SERIAL_Irq irq, BOOL fEnable) { LLOS_MbedSerial *pSerial = (LLOS_MbedSerial*)channel; if (pSerial == NULL) { return LLOS_E_INVALID_PARAMETER; } switch (irq) { case LLOS_SERIAL_IrqRx: serial_irq_set(&pSerial->Port, RxIrq, fEnable); break; case LLOS_SERIAL_IrqTx: serial_irq_set(&pSerial->Port, TxIrq, fEnable); break; case LLOS_SERIAL_IrqBoth: serial_irq_set(&pSerial->Port, TxIrq, fEnable); serial_irq_set(&pSerial->Port, RxIrq, fEnable); break; default: return LLOS_E_INVALID_PARAMETER; } return S_OK; } HRESULT LLOS_SERIAL_Enable(LLOS_Context channel, LLOS_SERIAL_Irq irq) { return InternalSerialEnable(channel, irq, 1); } HRESULT LLOS_SERIAL_Disable(LLOS_Context channel, LLOS_SERIAL_Irq irq) { return InternalSerialEnable(channel, irq, 0); } HRESULT LLOS_SERIAL_SetFlowControl(LLOS_Context channel, int32_t rtsPin, int32_t ctsPin) { #if DEVICE_SERIAL_FC LLOS_MbedSerial *pSerial = (LLOS_MbedSerial*)channel; FlowControl fc = FlowControlRTSCTS; if (pSerial == NULL) { return LLOS_E_INVALID_PARAMETER; } if (rtsPin == -1) { if (ctsPin == -1) { fc = FlowControlNone; } else { fc = FlowControlCTS; } } else if (ctsPin == -1) { fc = FlowControlRTS; } serial_set_flow_control(&pSerial->Port, fc, (PinName)rtsPin, (PinName)ctsPin); return S_OK; #else LLOS__UNREFERENCED_PARAMETER(channel); LLOS__UNREFERENCED_PARAMETER(rtsPin); LLOS__UNREFERENCED_PARAMETER(ctsPin); return LLOS_E_NOTIMPL; #endif } HRESULT LLOS_SERIAL_Configure(LLOS_Context channel, LLOS_SERIAL_Config* pConfig) { LLOS_MbedSerial *pSerial = (LLOS_MbedSerial*)channel; if (pSerial == NULL || pConfig == NULL) { return LLOS_E_INVALID_PARAMETER; } serial_format(&pSerial->Port, pConfig->DataBits, (SerialParity)pConfig->Parity, pConfig->StopBits); serial_baud(&pSerial->Port, pConfig->BaudRate); return S_OK; } HRESULT LLOS_SERIAL_Read(LLOS_Context channel, uint8_t* pBuffer, int32_t offset, int32_t* pLength) { LLOS_MbedSerial *pSerial = (LLOS_MbedSerial*)channel; int bytesRead = 0; char *pcNext = NULL; if (pSerial == NULL || pBuffer == NULL) { return LLOS_E_INVALID_PARAMETER; } pcNext = (char*)&pBuffer[offset]; while (serial_readable(&pSerial->Port) && bytesRead < *pLength) { *pcNext++ = serial_getc(&pSerial->Port); bytesRead++; } *pLength = bytesRead; return S_OK; } HRESULT LLOS_SERIAL_Write(LLOS_Context channel, uint8_t* pBuffer, int32_t offset, int32_t length) { LLOS_MbedSerial *pSerial = (LLOS_MbedSerial*)channel; char *pcNext = NULL; if (pSerial == NULL || pBuffer == NULL) { return LLOS_E_INVALID_PARAMETER; } pcNext = (char*)&pBuffer[offset]; while (length-- > 0) { serial_putc(&pSerial->Port, *pcNext++); } return S_OK; } HRESULT LLOS_SERIAL_Flush(LLOS_Context channel) { LLOS__UNREFERENCED_PARAMETER(channel); return S_OK; } HRESULT LLOS_SERIAL_Clear(LLOS_Context channel) { LLOS_MbedSerial *pSerial = (LLOS_MbedSerial*)channel; if (pSerial == NULL) { return LLOS_E_INVALID_PARAMETER; } serial_clear(&pSerial->Port); return S_OK; } static void HandleInternalSerialPortInterrupt(uint32_t id, SerialIrq data) { LLOS_MbedSerial *pSerial = (LLOS_MbedSerial*)id; if (pSerial != NULL && pSerial->Callback != NULL) { pSerial->Callback(pSerial, pSerial->Context, (LLOS_SERIAL_Event)data); } } HRESULT LLOS_SERIAL_SetCallback(LLOS_Context channel, LLOS_SERIAL_InterruptCallback callback, LLOS_Context callbackContext) { LLOS_MbedSerial *pSerial = (LLOS_MbedSerial*)channel; if (pSerial == NULL) { return LLOS_E_INVALID_PARAMETER; } pSerial->Callback = callback; pSerial->Context = callbackContext; serial_irq_handler(&pSerial->Port, (uart_irq_handler)HandleInternalSerialPortInterrupt, (uint32_t)channel); return S_OK; } HRESULT LLOS_SERIAL_CanRead(LLOS_Context channel, BOOL *pCanRead) { LLOS_MbedSerial *pSerial = (LLOS_MbedSerial*)channel; if (pSerial == NULL || pCanRead == NULL) { return LLOS_E_INVALID_PARAMETER; } *pCanRead = serial_readable(&pSerial->Port); return S_OK; } HRESULT LLOS_SERIAL_CanWrite(LLOS_Context channel, BOOL *pCanWrite) { LLOS_MbedSerial *pSerial = (LLOS_MbedSerial*)channel; if (pSerial == NULL || pCanWrite == NULL) { return LLOS_E_INVALID_PARAMETER; } *pCanWrite = serial_writable(&pSerial->Port); return S_OK; } } ================================================ FILE: Zelig/os_layer/ports/mbed/mbed_socket.cpp ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // #include "mbed_helpers.h" #include "mbed.h" #include "EthernetInterface.h" #include "init.h" #include "tcpip.h" #include "dns.h" #include "netifapi.h" #include "netdb.h" #include "tcp.h" #include "Sockets.h" extern "C" { int32_t LLOS_lwip_socket(int32_t family, int32_t type, int32_t protocol) { switch (protocol) { case 6://SOCK_IPPROTO_TCP: protocol = 6;// IPPROTO_TCP; break; case 17://SOCK_IPPROTO_UDP: protocol = 17;// IPPROTO_UDP; break; case 1://SOCK_IPPROTO_ICMP: protocol = 1;// IP_PROTO_ICMP; break; case 2://SOCK_IPPROTO_IGMP: protocol = 2;// IP_PROTO_IGMP; break; } return lwip_socket(family, type, protocol); } int32_t LLOS_lwip_bind(int32_t socket, void* address) { sockaddr_in _remoteHost; return lwip_bind(socket, (const struct sockaddr *) &_remoteHost, sizeof(_remoteHost)); } int32_t LLOS_lwip_connect(int32_t socket, void* address, bool fThrowOnWouldBlock) { sockaddr_in _remoteHost; uint8_t p1 = ((uint8_t*)address)[2]; uint8_t p2 = ((uint8_t*)address)[3]; uint16_t port = p1 << 8 | p2; std::memcpy((char*)&_remoteHost.sin_addr.s_addr, &((uint8_t*)address)[4], 4); // Address family _remoteHost.sin_family = AF_INET; // Set port _remoteHost.sin_port = htons(port); return lwip_connect(socket, (const struct sockaddr *) &_remoteHost, sizeof(_remoteHost)); } int32_t LLOS_lwip_send(int32_t socket, char* buf, int32_t count, int32_t flags, int32_t time_ms) { return lwip_send(socket, buf, count, flags); } int32_t LLOS_lwip_recv(int32_t socket, char* buf, int32_t count, int32_t flags, int32_t time_ms) { return lwip_recv(socket, buf, count, flags); } int32_t LLOS_lwip_close(int32_t socket) { return lwip_close(socket); } int32_t LLOS_lwip_listen(int32_t socket, int32_t backlog) { return lwip_listen(socket, backlog); } int32_t LLOS_lwip_accept(int32_t socket, void* address, uint32_t* addrlen) { return lwip_accept(socket, (sockaddr*)address, addrlen); } int32_t LLOS_lwip_getaddrinfo(uint16_t* name, uint32_t namelen, char* canonicalName, uint32_t canonicalNameBufferSize, char* addresses, uint32_t addressBufferSize) { char nameBuffer[256]; if (namelen >= 256) { return ERR_ARG; } WStringToCharBuffer(nameBuffer, 256, name, namelen); nameBuffer[namelen] = '\0'; addrinfo* addressInfo = NULL; int32_t res = lwip_getaddrinfo(nameBuffer, NULL, NULL, &addressInfo); char* canonName = addressInfo->ai_canonname; sockaddr* sockAddress = addressInfo->ai_addr; while (*canonName != '\0' && canonicalNameBufferSize > 0) { *canonicalName = *canonName; canonName++; canonicalName++; canonicalNameBufferSize--; } if (sockAddress->sa_len > addressBufferSize) { return ERR_VAL; } std::memcpy(addresses, sockAddress, sockAddress->sa_len); return res; } int32_t LLOS_lwip_shutdown(int32_t socket, int32_t how) { return lwip_shutdown(socket, how); } int32_t LLOS_lwip_sendto(int32_t socket, char* buf, int32_t count, int32_t flags, int32_t time_ms, void* address, uint32_t tolen) { return lwip_sendto(socket, buf, count, flags, (sockaddr*)address, tolen); } int32_t LLOS_lwip_recvfrom(int32_t socket, char* buf, int32_t count, int32_t flags, int32_t time_ms, void* address, uint32_t* fromlen) { return lwip_recvfrom(socket, buf, count, flags, (sockaddr*)address, fromlen); } int32_t LLOS_lwip_getpeername(int32_t socket, void* buf, uint32_t* namelen) { return lwip_getpeername(socket, (sockaddr*)buf, namelen); } int32_t LLOS_lwip_getsockname(int32_t socket, void* buf, uint32_t* namelen) { return lwip_getsockname(socket, (sockaddr*)buf, namelen); } int32_t LLOS_lwip_getsockopt(int32_t socket, int32_t level, int32_t optname, char* buf, uint32_t* optlen) { return lwip_getsockopt(socket, level, optname, buf, optlen); } int32_t LLOS_lwip_setsockopt(int32_t socket, int32_t level, int32_t optname, char* buf, uint32_t optlen) { return lwip_setsockopt(socket, level, optname, buf, optlen); } // TODO bool LLOS_lwip_poll(int32_t socket, int32_t mode, int32_t microSeconds) { return true; } int32_t LLOS_lwip_ioctl(int32_t socket, uint32_t cmd, uint32_t* arg) { return lwip_ioctl(socket, (long)cmd, arg); } } ================================================ FILE: Zelig/os_layer/ports/mbed/mbed_spi.cpp ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // #include "mbed_helpers.h" #include "llos_spi.h" #include "llos_memory.h" //--// extern "C" { typedef struct LLOS_MbedSpi { spi_t Spi; LLOS_SPI_Callback Callback; LLOS_Context Context; LLOS_SPI_ControllerConfig Config; } LLOS_MbedSpi; HRESULT LLOS_SPI_Initialize(uint32_t mosi, uint32_t miso, uint32_t sclk, uint32_t chipSelect, LLOS_Context* ppChannel, LLOS_SPI_ControllerConfig** ppConfiguration ) { LLOS_MbedSpi *pCtx; if (ppChannel == NULL || ppConfiguration == NULL) { return LLOS_E_INVALID_PARAMETER; } pCtx = (LLOS_MbedSpi*)AllocateFromManagedHeap(sizeof(LLOS_MbedSpi)); if (pCtx == NULL) { return LLOS_E_OUT_OF_MEMORY; } spi_init(&pCtx->Spi, (PinName)mosi, (PinName)miso, (PinName)sclk, (PinName)chipSelect); pCtx->Callback = NULL; pCtx->Context = NULL; *ppChannel = (LLOS_Context)pCtx; *ppConfiguration = &pCtx->Config; return S_OK; } VOID LLOS_SPI_Uninitialize(LLOS_Context channel) { FreeFromManagedHeap(channel); } HRESULT LLOS_SPI_Configure(LLOS_Context channel, LLOS_SPI_ControllerConfig* pConfig) { LLOS_MbedSpi *pCtx = (LLOS_MbedSpi*)channel; int32_t mode = 0; if (pCtx == NULL || pConfig == NULL) { return LLOS_E_INVALID_PARAMETER; } if (pConfig->WordSize != 8 && pConfig->WordSize != 16) { return LLOS_E_INVALID_OPERATION; } if (pConfig->PhaseMode == 1) { mode |= 1<<0; } if (pConfig->InversePolarity) { mode |= 1<<1; } pCtx->Config = *pConfig; spi_format(&pCtx->Spi, pConfig->WordSize, mode, pConfig->Master ? 0 : 1); if (pConfig->ClockRateHz != 0) { spi_frequency(&pCtx->Spi, pConfig->ClockRateHz); } return S_OK; } HRESULT LLOS_SPI_SetCallback(LLOS_Context channel, LLOS_SPI_Callback request, LLOS_Context context) { LLOS__UNREFERENCED_PARAMETER(channel); LLOS__UNREFERENCED_PARAMETER(request); LLOS__UNREFERENCED_PARAMETER(context); return LLOS_E_NOTIMPL; } HRESULT LLOS_SPI_SetFrequency(LLOS_Context channel, uint32_t frequencyHz) { LLOS_MbedSpi *pCtx = (LLOS_MbedSpi*)channel; if (pCtx == NULL) { return LLOS_E_INVALID_PARAMETER; } spi_frequency(&pCtx->Spi, frequencyHz); return S_OK; } HRESULT LLOS_SPI_Transfer(LLOS_Context channel, uint8_t* txBuffer, int32_t txOffset, int32_t txCount, uint8_t* rxBuffer, int32_t rxOffset, int32_t rxCount, int32_t rxStartOffset) { LLOS_MbedSpi *pCtx = (LLOS_MbedSpi*)channel; int32_t wordSizeBytes = (pCtx->Config.WordSize >> 3); int32_t ibNextWord = 0; int32_t ibRx = 0; if (pCtx == NULL || txBuffer == NULL || rxBuffer == NULL) { return LLOS_E_INVALID_PARAMETER; } if (!pCtx->Config.Master) { return LLOS_E_INVALID_OPERATION; } while (ibNextWord < txCount || ibRx < rxCount) { int32_t value = 0; int32_t response; if (ibNextWord < txCount) { value = (wordSizeBytes == 1) ? (int32_t)txBuffer[ibNextWord + txOffset] : (int32_t)*(uint16_t*)&txBuffer[ibNextWord + txOffset]; } response = spi_master_write(&pCtx->Spi, value); if (ibNextWord >= rxStartOffset && ibRx < rxCount) { if (wordSizeBytes == 8) { rxBuffer[ibRx + rxOffset] = (uint8_t)response; } else { *((uint16_t*)&rxBuffer[ibRx + rxOffset]) = (uint16_t)response; } ibRx += wordSizeBytes; } ibNextWord += wordSizeBytes; } return S_OK; } HRESULT LLOS_SPI_Write(LLOS_Context channel, uint8_t* txBuffer, int32_t txOffset, int32_t txCount) { LLOS_MbedSpi *pCtx = (LLOS_MbedSpi*)channel; int32_t wordSizeBytes = (pCtx->Config.WordSize >> 3); int32_t ibNextWord = 0; if (pCtx == NULL || txBuffer == NULL) { return LLOS_E_INVALID_PARAMETER; } while (ibNextWord < txCount) { int32_t value = (wordSizeBytes == 1) ? (int32_t)txBuffer[ibNextWord + txOffset] : (int32_t)*(uint16_t*)&txBuffer[ibNextWord + txOffset]; if (pCtx->Config.Master) { spi_master_write(&pCtx->Spi, value); } else { spi_slave_write(&pCtx->Spi, value); } ibNextWord += wordSizeBytes; } return S_OK; } HRESULT LLOS_SPI_Read(LLOS_Context channel, uint8_t* rxBuffer, int32_t rxOffset, int32_t rxCount, int32_t rxStartOffset) { LLOS_MbedSpi *pCtx = (LLOS_MbedSpi*)channel; int32_t wordSizeBytes = (pCtx->Config.WordSize >> 3); int32_t ibNextWord = 0; int32_t ibRx = 0; if (pCtx == NULL || rxBuffer == NULL || pCtx->Config.Master) { return LLOS_E_INVALID_PARAMETER; } while (ibRx < rxCount) { int32_t response = spi_slave_read(&pCtx->Spi); if (ibNextWord >= rxStartOffset) { if (wordSizeBytes == 1) { rxBuffer[ibRx + rxOffset] = (uint8_t)response; } else { *(uint16_t*)&rxBuffer[ibRx + rxOffset] = (uint16_t)response; } ibRx += wordSizeBytes; } ibNextWord += wordSizeBytes; } return S_OK; } HRESULT LLOS_SPI_IsBusy(LLOS_Context channel, BOOL* isBusy) { LLOS_MbedSpi *pCtx = (LLOS_MbedSpi*)channel; if (pCtx == NULL || isBusy == NULL) { return LLOS_E_INVALID_PARAMETER; } *isBusy = spi_busy( &pCtx->Spi ) != 0; return S_OK; } HRESULT LLOS_SPI_Suspend(LLOS_Context channel) { LLOS__UNREFERENCED_PARAMETER(channel); return LLOS_E_NOTIMPL; } HRESULT LLOS_SPI_Resume(LLOS_Context channel) { LLOS__UNREFERENCED_PARAMETER(channel); return LLOS_E_NOTIMPL; } } ================================================ FILE: Zelig/os_layer/ports/mbed/mbed_system_timer.cpp ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // #include "mbed_helpers.h" #include "llos_system_timer.h" #include "llos_memory.h" //--// extern "C" { typedef struct LLOS_MbedTimer { LLOS_Context Context; ticker_event_t TickerEvent; } LLOS_MbedTimer; static LLOS_SYSTEM_TIMER_Callback s_TimerCallback = NULL; static const ticker_data_t *s_pTickerData = get_us_ticker_data(); // This is used to call back into the Kernel using a WellKnownMethod static void MbedInterruptHandler(uint32_t id) { if (s_TimerCallback != NULL) { LLOS_MbedTimer *pCtx = (LLOS_MbedTimer*)id; if (pCtx != NULL) { uint64_t ticks = us_ticker_read(); s_TimerCallback(pCtx->Context, ticks); } } } HRESULT LLOS_SYSTEM_TIMER_SetTicks(uint64_t value) { LLOS__UNREFERENCED_PARAMETER(value); return LLOS_E_NOT_SUPPORTED; } uint64_t LLOS_SYSTEM_TIMER_GetTicks(LLOS_Context timerContext) { LLOS__UNREFERENCED_PARAMETER(timerContext); return us_ticker_read(); } uint64_t LLOS_SYSTEM_TIMER_GetTimerFrequency(LLOS_Context timerContext) { LLOS__UNREFERENCED_PARAMETER(timerContext); return 1000000; // 1us tick timer = 1MHz } HRESULT LLOS_SYSTEM_TIMER_AllocateTimer(LLOS_SYSTEM_TIMER_Callback callback, LLOS_Context callbackContext, uint64_t usFromNow, LLOS_Context *pTimer) { LLOS__UNREFERENCED_PARAMETER(usFromNow); LLOS_MbedTimer *pCtx; if (pTimer == NULL) { return LLOS_E_INVALID_PARAMETER; } pCtx = (LLOS_MbedTimer*)AllocateFromManagedHeap(sizeof(LLOS_MbedTimer)); if (pCtx == NULL) { return LLOS_E_OUT_OF_MEMORY; } s_TimerCallback = callback; us_ticker_init(); ticker_set_handler(s_pTickerData, MbedInterruptHandler); pCtx->Context = callbackContext; *pTimer = pCtx; return S_OK; } VOID LLOS_SYSTEM_TIMER_FreeTimer(LLOS_Context pTimer) { LLOS_MbedTimer *pCtx = (LLOS_MbedTimer*)pTimer; if (pCtx != NULL) { ticker_remove_event(s_pTickerData, &pCtx->TickerEvent); } } HRESULT LLOS_SYSTEM_TIMER_ScheduleTimer(LLOS_Context pTimer, uint64_t microsecondsFromNow) { LLOS_MbedTimer *pCtx = (LLOS_MbedTimer*)pTimer; if (pCtx == NULL || microsecondsFromNow > 0xFFFFFFFFuLL) { return LLOS_E_INVALID_PARAMETER; } if (microsecondsFromNow < 2) { microsecondsFromNow = 2; } LLOS__PRESERVE_PRIMASK_STATE_M0_1__SAVE(); ticker_remove_event(s_pTickerData, &pCtx->TickerEvent); ticker_insert_event(s_pTickerData, &pCtx->TickerEvent, us_ticker_read() + (uint32_t)microsecondsFromNow, (uint32_t)pTimer); LLOS__PRESERVE_PRIMASK_STATE_M0_1__RESTORE(); return S_OK; } } ================================================ FILE: Zelig/os_layer/ports/mbed/mbed_systick.cpp ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // #include "mbed_helpers.h" //--// extern "C" { // // SysTick // ////// ////// From core_cm3.h in mBed CMSIS support: ////// ////// /** \brief Structure type to access the System Timer (SysTick). ////// */ ////// typedef struct ////// { ////// __IO uint32_t CTRL; /*!< Offset: 0x000 (R/W) SysTick Control and Status Register */ ////// __IO uint32_t LOAD; /*!< Offset: 0x004 (R/W) SysTick Reload Value Register */ ////// __IO uint32_t VAL; /*!< Offset: 0x008 (R/W) SysTick Current Value Register */ ////// __I uint32_t CALIB; /*!< Offset: 0x00C (R/ ) SysTick Calibration Register */ ////// } SysTick_Type; ////// ////// ... ////// ... ////// ... ////// ////// #define SysTick ((SysTick_Type *) SysTick_BASE ) /*!< SysTick configuration struct */ ////// /*__STATIC_INLINE*/ uint32_t CMSIS_STUB_SysTick_GetCTRL() { return SysTick->CTRL; } /*__STATIC_INLINE*/ void CMSIS_STUB_SysTick_SetCTRL(uint32_t value) { SysTick->CTRL = value; } /*__STATIC_INLINE*/ uint32_t CMSIS_STUB_SysTick_GetLOAD() { return SysTick->LOAD & 0x00FFFFFF; } /*__STATIC_INLINE*/ void CMSIS_STUB_SysTick_SetLOAD(uint32_t value) { SysTick->LOAD |= value & 0x00FFFFFF; } /*__STATIC_INLINE*/ uint32_t CMSIS_STUB_SysTick_GetVAL() { return SysTick->VAL & 0x00FFFFFF; } /*__STATIC_INLINE*/ void CMSIS_STUB_SysTick_SetVAL(uint32_t value) { SysTick->VAL |= value & 0x00FFFFFF; } /*__STATIC_INLINE*/ uint32_t CMSIS_STUB_SysTick_GetCALIB() { return SysTick->CALIB; } // // // extern void SysTick_Handler_Zelig(); __attribute__((naked)) void SysTick_Handler(void) { #if __CORTEX_M0 __ASM volatile ("MOV R1, LR" ); __ASM volatile ("SUB SP, #4" ); __ASM volatile ("STR R1, [SP]"); #else __ASM volatile ("STR LR, [SP, #-4]!"); // Save LR to stack #endif SysTick_Handler_Zelig(); #if __CORTEX_M0 __ASM volatile ("LDR R1, [SP]"); __ASM volatile ("ADD SP, #4" ); __ASM volatile ("MOV LR, R1" ); __ASM volatile ("BX LR " ); #else __ASM volatile ("LDR LR, [SP], #4"); // Restore LR from stack __ASM volatile ("BX LR"); #endif } } ================================================ FILE: Zelig/os_layer/ports/mbed/mbed_threading.cpp ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // #include "mbed_helpers.h" //--// extern "C" { __attribute__((section(".managed_exception_thread"))) uint32_t stackAdjustForExceptionThread[4]; uint32_t LLOS_THREAD_GetMainStackAddress( ) { uint32_t addr = (uint32_t)&__StackLimit; return addr; } uint32_t LLOS_THREAD_GetMainStackSize( ) { uint32_t top = (uint32_t)&__StackTop; uint32_t limit = (uint32_t)&__StackLimit; return top - limit; } // // Threading // TODO TODO TODO: Eliminate this portion or convert the Win32 port over // void* CreateNativeContext(void* entryPoint, void* stack, int32_t stackSize) { LLOS__UNREFERENCED_PARAMETER(entryPoint); LLOS__UNREFERENCED_PARAMETER(stack); LLOS__UNREFERENCED_PARAMETER(stackSize); return NULL; } void Yield(void* nativeContext) { LLOS__UNREFERENCED_PARAMETER(nativeContext); } void Retire(void* nativeContext) { LLOS__UNREFERENCED_PARAMETER(nativeContext); } void SwitchToContext(void* nativeContext) { LLOS__UNREFERENCED_PARAMETER(nativeContext); } void* GetPriority(void* nativeContext) { LLOS__UNREFERENCED_PARAMETER(nativeContext); return 0; } void SetPriority(void* nativeContext, void* priority) { LLOS__UNREFERENCED_PARAMETER(nativeContext); LLOS__UNREFERENCED_PARAMETER(priority); } } ================================================ FILE: Zelig/os_layer/ports/mbed/mbed_unwind.cpp ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // #include "unwind.h" #include "mbed_helpers.h" #include "llos_unwind.h" struct ExceptionWrapper { // Header must be the last member of the struct as it may be extended with arbitrary data. LLOS_Opaque Exception; _Unwind_Exception Header; static void Free(_Unwind_Reason_Code reason, _Unwind_Exception* header) { LLOS__UNREFERENCED_PARAMETER(reason); LLOS_FREE(FromHeader(header)); } static ExceptionWrapper* FromHeader(_Unwind_Exception* header) { uint8_t* wrapper = reinterpret_cast(header) - offsetof(ExceptionWrapper, Header); return reinterpret_cast(wrapper); } }; // Note: These function parameters are inconsistent with the Itanium ABI detailed at // (http://mentorembedded.github.io/cxx-abi/abi-eh.html). The prototype defined here must match // the personality_routine type defined in unwind.h. extern "C" LLOS_Unwind_Reason_Code LLOS_Personality( _Unwind_State state, _Unwind_Exception* exceptionObject, _Unwind_Context* context) { uint32_t actions = state & (~_US_ACTION_MASK); switch (state & _US_ACTION_MASK) { case _US_VIRTUAL_UNWIND_FRAME: actions |= LLOS_UA_SEARCH_PHASE; break; case _US_UNWIND_FRAME_STARTING: actions |= LLOS_UA_CLEANUP_PHASE | LLOS_UA_HANDLER_FRAME; break; case _US_UNWIND_FRAME_RESUME: actions |= LLOS_UA_CLEANUP_PHASE; break; default: abort(); } // Many of the unwind context functions seem to expect the exception object to be set in the // first scratch register. This is a departure from the Itanium ABI. _Unwind_SetGR(context, 12, (uintptr_t)exceptionObject); LLOS_Unwind_Reason_Code result = LLOS_Unwind_Personality( static_cast(actions), *(uint64_t*)exceptionObject->exception_class, (uintptr_t)exceptionObject, (uintptr_t)context); // The GNU unwinder appears to assume the personality function will unwind the stack. If we're // to continue unwinding, reset the context to the next frame up the stack. if (result == LLOS_URC_CONTINUE_UNWIND) { __gnu_unwind_frame(exceptionObject, context); } return result; } uintptr_t LLOS_AllocateException(LLOS_Opaque exception, uint64_t exceptionClass) { ExceptionWrapper* wrapper = (ExceptionWrapper*)LLOS_CALLOC(1, sizeof(ExceptionWrapper)); *(uint64_t*)wrapper->Header.exception_class = exceptionClass; wrapper->Header.exception_cleanup = ExceptionWrapper::Free; wrapper->Exception = exception; return (uintptr_t)&wrapper->Header; } LLOS_Opaque LLOS_GetExceptionObject(uintptr_t exception) { return ExceptionWrapper::FromHeader((_Unwind_Control_Block*)exception)->Exception; } uintptr_t LLOS_Unwind_GetIP(uintptr_t context) { return _Unwind_GetIP((_Unwind_Context*)context); } uintptr_t LLOS_Unwind_GetLanguageSpecificData(uintptr_t context) { return (uintptr_t)_Unwind_GetLanguageSpecificData((_Unwind_Context*)context); } uintptr_t LLOS_Unwind_GetRegionStart(uintptr_t context) { return _Unwind_GetRegionStart((_Unwind_Context*)context); } void LLOS_Unwind_RaiseException(uintptr_t exceptionObject) { _Unwind_RaiseException((_Unwind_Exception*)exceptionObject); // There was an error while unwinding (usually end of stack). Terminate the app. abort(); } void LLOS_Unwind_SetRegisters( uintptr_t context, uintptr_t landingPad, uintptr_t exceptionObject, uintptr_t selector) { _Unwind_Context* contextPtr = (_Unwind_Context*)context; _Unwind_SetGR(contextPtr, __builtin_eh_return_data_regno(0), exceptionObject); _Unwind_SetGR(contextPtr, __builtin_eh_return_data_regno(1), selector); _Unwind_SetIP(contextPtr, landingPad); } void LLOS_Terminate() { abort(); } ================================================ FILE: Zelig/os_layer/ports/win32/Win32Abstraction/LlosClock.cpp ================================================ #include "LlosWin32.h" #include uint64_t LLOS_CLOCK_GetClockTicks() { uint64_t time = GetTickCount64(); return time; } uint64_t LLOS_CLOCK_GetPerformanceCounter() { return GetTickCount64(); } uint64_t LLOS_CLOCK_GetPerformanceCounterFrequency() { return 1000; } ================================================ FILE: Zelig/os_layer/ports/win32/Win32Abstraction/LlosDebug.cpp ================================================ #include "LlosWin32.h" #include VOID LLOS_DEBUG_Break(uint32_t code) { DebugBreak(); } VOID LLOS_DEBUG_LogText(wchar_t* text, int32_t textLength) { wprintf(text); wprintf(L"\r\n"); } ================================================ FILE: Zelig/os_layer/ports/win32/Win32Abstraction/LlosEntry.cpp ================================================ #include "LlosWin32.h" #include DWORD g_dwTlsIndex; int LlosWin32_Main() { g_dwTlsIndex = TlsAlloc(); // Thread local storage for refcount on global mutex LlosThread** ppvData = (LlosThread**)LocalAlloc(LPTR, sizeof(LlosThread) + sizeof(LlosThread*)); *ppvData = (LlosThread*)&ppvData[1]; TlsSetValue(g_dwTlsIndex, ppvData); LLILUM_main(); LocalFree(ppvData); TlsFree(g_dwTlsIndex); return 0; } ================================================ FILE: Zelig/os_layer/ports/win32/Win32Abstraction/LlosGarbageCollection.cpp ================================================ #include "LlosWin32.h" #include extern "C" { // Enable this macro to shift object pointers from the beginning of the header to the beginning of the payload. #define CANONICAL_OBJECT_POINTERS struct Object; struct ObjectHeader { int32_t MultiUseWord; void* VTable; inline Object* get_Object() { #ifdef CANONICAL_OBJECT_POINTERS return reinterpret_cast(this + 1); #else // CANONICAL_OBJECT_POINTERS return reinterpret_cast(this); #endif // CANONICAL_OBJECT_POINTERS } }; struct Object { inline ObjectHeader* get_Header() { #ifdef CANONICAL_OBJECT_POINTERS return reinterpret_cast(this) - 1; #else // CANONICAL_OBJECT_POINTERS return reinterpret_cast(this); #endif // CANONICAL_OBJECT_POINTERS } }; extern "C" { // Must match consts defined in ObjectHeader.cs #define REFERENCE_COUNT_MASK 0xFF000000 #define REFERENCE_COUNT_SHIFT 24 // Helpers for starting / ending section of code that needs to be atomic __inline void StartAtomicOperations(void) { LLOS_MUTEX_Acquire(g_globalMutex, -1); } __inline void EndAtomicOperations(void) { LLOS_MUTEX_Release(g_globalMutex); } __inline void AddReferenceFast(Object* target) { if (target != NULL) { ObjectHeader* header = target->get_Header(); if (header->MultiUseWord & REFERENCE_COUNT_MASK) { header->MultiUseWord += (1 << REFERENCE_COUNT_SHIFT); } } } void AddReference(Object* target) { if (target != NULL) { ObjectHeader* header = target->get_Header(); StartAtomicOperations(); if (header->MultiUseWord & REFERENCE_COUNT_MASK) { header->MultiUseWord += (1 << REFERENCE_COUNT_SHIFT); } EndAtomicOperations(); } } // Return zero when target is dead after the call int ReleaseReferenceNative(Object* target) { int ret = 1; if (target != NULL) { ObjectHeader* header = target->get_Header(); StartAtomicOperations(); int32_t value = header->MultiUseWord; if (value & REFERENCE_COUNT_MASK) { value -= (1 << REFERENCE_COUNT_SHIFT); header->MultiUseWord = value; ret = value & REFERENCE_COUNT_MASK; } EndAtomicOperations(); } return ret; } Object* LoadAndAddReferenceNative(Object** target) { StartAtomicOperations(); Object* value = *target; AddReferenceFast(value); EndAtomicOperations(); return value; } Object* ReferenceCountingExchange(Object** target, Object* value) { StartAtomicOperations(); Object* oldValue = *target; *target = value; AddReferenceFast(value); EndAtomicOperations(); return oldValue; } Object* ReferenceCountingCompareExchange(Object** target, Object* value, Object* comparand) { StartAtomicOperations(); Object* oldValue = *target; Object* addRefTarget; if (oldValue == comparand) { *target = value; // Compare exchange succeeded, we need to add ref the new value // The old value's ref count will be passed back to the caller on return. addRefTarget = value; } else { // Target is not changed, we need to add ref the old value so it has // a ref count to pass back to caller on return addRefTarget = oldValue; } AddReferenceFast(addRefTarget); EndAtomicOperations(); return oldValue; } } } ================================================ FILE: Zelig/os_layer/ports/win32/Win32Abstraction/LlosMemory.cpp ================================================ #include "LlosWin32.h" #include HRESULT LLOS_MEMORY_GetMaxHeapSize(uint32_t* pMaxHeapSize) { if (pMaxHeapSize == nullptr) { return E_INVALIDARG; } *pMaxHeapSize = 2 * 1024 * 1024; return S_OK; } HRESULT LLOS_MEMORY_Allocate(uint32_t size, uint8_t fill, LLOS_Opaque* pAllocation) { VOID *ptr = nullptr; if (pAllocation == nullptr) { return E_INVALIDARG; } *pAllocation = nullptr; ptr = malloc(size); if (ptr != nullptr) { memset(ptr, fill, size); *pAllocation = ptr; } return *pAllocation != NULL ? S_OK : E_FAIL; } HRESULT LLOS_MEMORY_Reallocate(LLOS_Opaque* allocation, uint32_t newSize) { return E_NOTIMPL; } VOID LLOS_MEMORY_Free(LLOS_Opaque address) { free(address); } ================================================ FILE: Zelig/os_layer/ports/win32/Win32Abstraction/LlosMutex.cpp ================================================ #include "LlosWin32.h" #include HANDLE g_globalMutex = INVALID_HANDLE_VALUE; HRESULT LLOS_MUTEX_CreateGlobalLock(LLOS_Handle* mutexHandle) { HRESULT hr = LLOS_MUTEX_Create(nullptr, nullptr, mutexHandle); // The first mutex created will be the global mutex for handling thread synchronization. // It is saved to g_globalMutex so that the native Win32 code can use the global lock. if (SUCCEEDED(hr) && *mutexHandle != INVALID_HANDLE_VALUE) { g_globalMutex = *mutexHandle; } return hr; } HRESULT LLOS_MUTEX_Create(LLOS_Context attributes, LLOS_Context name, LLOS_Handle* mutexHandle) { *mutexHandle = CreateMutexW((LPSECURITY_ATTRIBUTES)attributes, false, (LPCWSTR)name); return *mutexHandle != INVALID_HANDLE_VALUE ? S_OK : E_FAIL; } HRESULT LLOS_MUTEX_Acquire(LLOS_Handle mutexHandle, int32_t timeout) { if (mutexHandle != INVALID_HANDLE_VALUE && mutexHandle != 0) { if (WAIT_OBJECT_0 == WaitForSingleObject(mutexHandle, timeout)) { volatile LlosThread *tlsThread = GetThreadLocalStorage(); if (tlsThread != nullptr) { InterlockedIncrement(&tlsThread->globalLockRefCount); } } } return S_OK; } HRESULT LLOS_MUTEX_Release(LLOS_Handle mutexHandle) { if (mutexHandle != INVALID_HANDLE_VALUE && mutexHandle != 0) { if (ReleaseMutex(mutexHandle)) { volatile LlosThread *tlsThread = GetThreadLocalStorage(); if (tlsThread != nullptr) { InterlockedDecrement(&tlsThread->globalLockRefCount); } } } return S_OK; } BOOL LLOS_MUTEX_CurrentThreadHasLock(LLOS_Handle mutexHandle) { BOOL ownsMutex = FALSE; if (mutexHandle == INVALID_HANDLE_VALUE) { return ownsMutex; } switch(WaitForSingleObject(mutexHandle, 0)) { case WAIT_OBJECT_0: { volatile LlosThread *tlsThread = GetThreadLocalStorage(); ownsMutex = (tlsThread == nullptr) || (tlsThread->globalLockRefCount > 0); ReleaseMutex(mutexHandle); } break; case WAIT_TIMEOUT: case WAIT_ABANDONED: default: break; } return ownsMutex; } HRESULT LLOS_MUTEX_Delete(LLOS_Handle mutexHandle) { return CloseHandle(mutexHandle) ? S_OK : E_FAIL; } ================================================ FILE: Zelig/os_layer/ports/win32/Win32Abstraction/LlosStubs.cpp ================================================ #include "LlosWin32.h" extern "C" { uint32_t CMSIS_STUB_SCB__get_CONTROL() { return 0; } uint32_t CMSIS_STUB_SCB__get_BASEPRI() { return 0; } uint32_t CMSIS_STUB_SCB__set_BASEPRI(uint32_t basePri) { return 0; } void CUSTOM_STUB_SCB_SCR_SetSystemControlRegister(uint32_t scr) { } void CUSTOM_STUB_SCB_set_CCR(uint32_t value) { } void CUSTOM_STUB_SCB_SHCRS_EnableSystemHandler(uint32_t ex) { } void CUSTOM_STUB_RaiseSupervisorCallForLongJump() { } uint32_t CUSTOM_STUB_SCB__get_FPCCR() { return 0; } void CUSTOM_STUB_SCB__set_FPCCR(uint32_t fpscr) { } void Breakpoint() { } uint32_t CUSTOM_STUB_DebuggerConnected() { return 0; } uint32_t CUSTOM_STUB_SCB__get_CFSR() { return 0; } uint32_t CUSTOM_STUB_SCB__get_HFSR() { return 0; } uint32_t CUSTOM_STUB_SCB__get_MMFAR() { return 0; } uint32_t CUSTOM_STUB_SCB__get_BFAR() { return 0; } uint32_t* CUSTOM_STUB_FetchSoftwareFrameSnapshot() { return nullptr; } void CMSIS_STUB_SCB__set_PSP(uint32_t topOfProcStack) { } void CUSTOM_STUB_SetExcReturn(uint32_t ret) { } void CUSTOM_STUB_RaiseSupervisorCallForStartThreads() { } void CUSTOM_STUB_RaiseSupervisorCallForRetireThread() { } void CUSTOM_STUB_RaiseSupervisorCallForSnapshotProcessModeRegisters() { } uint32_t CMSIS_STUB_SCB__get_FAULTMASK() { return 0; } uint32_t CMSIS_STUB_SCB__get_PRIMASK() { return 0; } uint32_t CMSIS_STUB_SCB__set_PRIMASK(uint32_t priMask) { return 0; } uint32_t CUSTOM_STUB_SCB_IPSR_GetCurrentISRNumber() { return 0; } uint32_t us_ticker_read() { // This function will only be included and called if the test application was // compiledfor a board other than Win32. You should verify that program.cs in // the directory: zelig\zelig\test\mbed\simple\ defines WIN32 at the top of the // file. DebugBreak(); return 0; } } ================================================ FILE: Zelig/os_layer/ports/win32/Win32Abstraction/LlosThread.cpp ================================================ #include "LlosWin32.h" #include static DWORD WINAPI LlosThreadEntryWrapper(LPVOID lpThreadParameter) { LlosThread *pThread = (LlosThread*)lpThreadParameter; LlosThread** ppvData = nullptr; if (pThread == nullptr) { return 1; } try { ppvData = (LlosThread**)LocalAlloc(LPTR, sizeof(LlosThread*)); if (ppvData == nullptr) { return 1; } *ppvData = pThread; TlsSetValue(g_dwTlsIndex, ppvData); pThread->entry(pThread->param); } catch (...) { } if (ppvData != nullptr) { TlsSetValue(g_dwTlsIndex, nullptr); LocalFree(ppvData); } return 0; } LlosThread* GetThreadLocalStorage() { LlosThread** lpvData = (LlosThread**)TlsGetValue(g_dwTlsIndex); if (lpvData != nullptr) { return *lpvData; } return nullptr; } HRESULT LLOS_THREAD_GetCurrentThread(LLOS_Context* threadHandle) { LlosThread *pThread; if (threadHandle == nullptr) { return E_INVALIDARG; } pThread = GetThreadLocalStorage(); if (pThread != nullptr) { *threadHandle = pThread->managedThread; } else { *threadHandle = nullptr; } return *threadHandle != nullptr ? S_OK : E_FAIL; } HRESULT LLOS_THREAD_CreateThread(LLOS_ThreadEntry threadEntry, LLOS_Context threadParameter, LLOS_Context managedThread, uint32_t stackSize, LLOS_Handle* threadHandle) { LlosThread *pThread = (LlosThread*)calloc(1, sizeof(LlosThread)); if (threadHandle == nullptr) { return E_INVALIDARG; } if (pThread == nullptr) { return E_OUTOFMEMORY; } pThread->entry = threadEntry; pThread->param = threadParameter; pThread->managedThread = managedThread; pThread->globalLockRefCount = 0; pThread->hndThread = CreateThread(NULL, stackSize, LlosThreadEntryWrapper, pThread, CREATE_SUSPENDED, NULL); if (pThread->hndThread == INVALID_HANDLE_VALUE) { free(pThread); pThread = nullptr; } *threadHandle = pThread; return pThread != nullptr ? S_OK : E_FAIL; } HRESULT LLOS_THREAD_Start(LLOS_Handle threadHandle) { LlosThread *pThread = (LlosThread*)threadHandle; if (pThread == nullptr) { return E_INVALIDARG; } return ResumeThread(pThread->hndThread); } HRESULT LLOS_THREAD_Yield(VOID) { SwitchToThread(); return S_OK; } HRESULT LLOS_THREAD_Wait(LLOS_Handle threadHandle, int32_t timeoutMs) { HRESULT hr; LlosThread *pThread = (LlosThread*)threadHandle; if (pThread == nullptr) { return E_INVALIDARG; } hr = WaitOnAddress(&pThread->waitAddress, &pThread->compareAddress, sizeof(DWORD), timeoutMs) ? S_OK : E_ABORT; pThread->waitAddress = 0; return hr; } HRESULT LLOS_THREAD_Signal(LLOS_Handle threadHandle) { LlosThread *pThread = (LlosThread*)threadHandle; if (pThread == nullptr) { return E_INVALIDARG; } pThread->waitAddress = 1; WakeByAddressAll(&pThread->waitAddress); return S_OK; } HRESULT LLOS_THREAD_SetPriority(LLOS_Handle threadHandle, LLOS_ThreadPriority threadPriority) { int pri = THREAD_PRIORITY_NORMAL; LlosThread *pThread = (LlosThread*)threadHandle; if (pThread == nullptr) { return E_INVALIDARG; } switch (threadPriority) { case ThreadPriority_Lowest: pri = THREAD_PRIORITY_LOWEST; break; case ThreadPriority_BelowNormal: pri = THREAD_PRIORITY_BELOW_NORMAL; break; case ThreadPriority_Normal: pri = THREAD_PRIORITY_NORMAL; break; case ThreadPriority_AboveNormal: pri = THREAD_PRIORITY_ABOVE_NORMAL; break; case ThreadPriority_Highest: pri = THREAD_PRIORITY_HIGHEST; break; default: break; } return SetThreadPriority(pThread->hndThread, pri) ? S_OK : E_FAIL; } HRESULT LLOS_THREAD_GetPriority(LLOS_Handle threadHandle, LLOS_ThreadPriority* threadPriority) { LLOS_ThreadPriority llosPri = ThreadPriority_Normal; LlosThread *pThread = (LlosThread*)threadHandle; if (pThread == nullptr || threadPriority == nullptr) { return E_INVALIDARG; } int pri = GetThreadPriority(pThread->hndThread); switch (pri) { case THREAD_PRIORITY_LOWEST: llosPri = ThreadPriority_Lowest; break; case THREAD_PRIORITY_BELOW_NORMAL: llosPri = ThreadPriority_BelowNormal; break; case THREAD_PRIORITY_NORMAL: llosPri = ThreadPriority_Normal; break; case THREAD_PRIORITY_ABOVE_NORMAL: llosPri = ThreadPriority_AboveNormal; break; case THREAD_PRIORITY_HIGHEST: llosPri = ThreadPriority_Highest; break; default: break; } *threadPriority = llosPri; return S_OK; } HRESULT LLOS_THREAD_DeleteThread(LLOS_Handle threadHandle) { LlosThread *pThread = (LlosThread*)threadHandle; if (pThread != nullptr) { WaitForSingleObject(pThread->hndThread, -1); CloseHandle(pThread->hndThread); free(pThread); } return S_OK; } VOID LLOS_THREAD_Sleep(int32_t timeoutMilliseconds) { Sleep(timeoutMilliseconds); } uint32_t LLOS_THREAD_GetMainStackAddress() { return 0; } uint32_t LLOS_THREAD_GetMainStackSize() { return 0; } ================================================ FILE: Zelig/os_layer/ports/win32/Win32Abstraction/LlosTimer.cpp ================================================ #include "LlosWin32.h" #include #include typedef struct LlosTimerEntry { HANDLE hndThread; HANDLE hndEvent; BOOL fExit; LLOS_SYSTEM_TIMER_Callback callback; LLOS_Context callbackContext; uint64_t waitTime; CRITICAL_SECTION cs; } LlosTimerEntry; DWORD WINAPI LlosTimerThreadProc( LPVOID lpThreadParameter ) { LlosTimerEntry *pTimer = (LlosTimerEntry*)lpThreadParameter; uint32_t waitTimeout = 0; if (pTimer == nullptr) { return E_INVALIDARG; } LlosThread** ppvData = (LlosThread**)LocalAlloc(LPTR, sizeof(LlosThread) + sizeof(LlosThread*)); if (ppvData == nullptr) { return E_OUTOFMEMORY; } *ppvData = (LlosThread*)&ppvData[1]; TlsSetValue(g_dwTlsIndex, ppvData); while (!pTimer->fExit) { BOOL fTimerExpired = FALSE; EnterCriticalSection(&pTimer->cs); if (pTimer->waitTime >= INFINITE) { waitTimeout = 10000; } else { waitTimeout = (uint32_t)(pTimer->waitTime / 1000); } pTimer->waitTime = INFINITE; LeaveCriticalSection(&pTimer->cs); switch (WaitForSingleObject(pTimer->hndEvent, (uint32_t)waitTimeout)) { case WAIT_OBJECT_0: break; case WAIT_TIMEOUT: fTimerExpired = TRUE; break; default: DebugBreak(); break; } LLOS_MUTEX_Acquire((LLOS_Context)g_globalMutex, -1); pTimer->callback(pTimer->callbackContext, LLOS_SYSTEM_TIMER_GetTicks(pTimer)); LLOS_MUTEX_Release((LLOS_Context)g_globalMutex); } LocalFree(ppvData); return 0; } HRESULT LLOS_SYSTEM_TIMER_AllocateTimer(LLOS_SYSTEM_TIMER_Callback callback, LLOS_Context callbackContext, uint64_t microsecondsFromNow, LLOS_Context *pTimer) { LlosTimerEntry *pEntry = nullptr; if (pTimer == nullptr || callback == nullptr) { return E_INVALIDARG; } pEntry = (LlosTimerEntry*)calloc(1, sizeof(LlosTimerEntry)); if (pEntry != nullptr) { pEntry->callback = callback; pEntry->callbackContext = callbackContext; pEntry->fExit = FALSE; pEntry->waitTime = microsecondsFromNow; if (!InitializeCriticalSectionAndSpinCount(&pEntry->cs, 0x00000400)) { return E_FAIL; } pEntry->hndEvent = CreateEvent(nullptr, FALSE, FALSE, nullptr); pEntry->hndThread = CreateThread(nullptr, 1024 * 1024, LlosTimerThreadProc, pEntry, 0, nullptr); *pTimer = pEntry; } return pEntry != nullptr ? S_OK : E_FAIL; } VOID LLOS_SYSTEM_TIMER_FreeTimer(LLOS_Context pTimer) { if (pTimer != nullptr) { LlosTimerEntry *pEntry = (LlosTimerEntry*)pTimer; pEntry->fExit = TRUE; SetEvent(pEntry->hndEvent); WaitForSingleObject(pEntry->hndThread, INFINITE); CloseHandle(pEntry->hndThread); CloseHandle(pEntry->hndEvent); DeleteCriticalSection(&pEntry->cs); free(pTimer); } } HRESULT LLOS_SYSTEM_TIMER_ScheduleTimer(LLOS_Context pTimer, uint64_t microsecondsFromNow) { LlosTimerEntry *pEntry = (LlosTimerEntry*)pTimer; if (pTimer == nullptr) { return E_INVALIDARG; } EnterCriticalSection(&pEntry->cs); pEntry->waitTime = microsecondsFromNow; LeaveCriticalSection(&pEntry->cs); SetEvent(pEntry->hndEvent); SwitchToThread(); return S_OK; } uint64_t LLOS_SYSTEM_TIMER_GetTicks(LLOS_Context pTimer) { return GetTickCount64(); } uint64_t LLOS_SYSTEM_TIMER_GetTimerFrequency(LLOS_Context pTimer) { return 1000; } ================================================ FILE: Zelig/os_layer/ports/win32/Win32Abstraction/LlosUnwind.cpp ================================================ // // Copyright (c) Microsoft Corporation. All rights reserved. // #include "LlosWin32.h" #include "llos_unwind.h" extern "C" LLOS_Unwind_Reason_Code LLOS_Personality( int /*version*/, LLOS_Unwind_Actions actions, uint64_t exceptionClass, struct _Unwind_Exception* exceptionObject, struct _Unwind_Context* context) { return LLOS_Unwind_Personality(actions, exceptionClass, (uintptr_t)exceptionObject, (uintptr_t)context); } uintptr_t LLOS_AllocateException(LLOS_Opaque exception, uint64_t exceptionClass) { return 0; } LLOS_Opaque LLOS_GetExceptionObject(uintptr_t exception) { return NULL; } uintptr_t LLOS_Unwind_GetIP(uintptr_t context) { return 0; } uintptr_t LLOS_Unwind_GetLanguageSpecificData(uintptr_t context) { return 0; } uintptr_t LLOS_Unwind_GetRegionStart(uintptr_t context) { return 0; } void LLOS_Unwind_RaiseException(uintptr_t exceptionObject) { abort(); } void LLOS_Unwind_SetRegisters( uintptr_t context, uintptr_t landingPad, uintptr_t exceptionObject, uintptr_t selector) { } void LLOS_Terminate() { abort(); } ================================================ FILE: Zelig/os_layer/ports/win32/Win32Abstraction/LlosWin32.h ================================================ #include #include #include #include #pragma once typedef struct LlosThread { LLOS_ThreadEntry entry; LLOS_Context param; LLOS_Context managedThread; HANDLE hndThread; DWORD globalLockRefCount; DWORD waitAddress; DWORD compareAddress; } LlosThread; extern "C" void LLILUM_main(void); extern LlosThread* GetThreadLocalStorage(void); extern HANDLE g_globalMutex; extern DWORD g_dwTlsIndex; ================================================ FILE: Zelig/os_layer/ports/win32/Win32Abstraction/Win32Abstraction.vcxproj ================================================  Debug Win32 Release Win32 {E18A0A2A-60AF-4819-9F64-FD347E222144} Win32Abstraction 8.1 StaticLibrary true v140 MultiByte StaticLibrary false v140 true MultiByte $(LLILUM_ROOT)Zelig\Zelig\$(Configuration)\ $(LLILUM_ROOT)Zelig\Zelig\$(Configuration)\ Level3 Disabled true WIN32;_DEBUG;%(PreprocessorDefinitions) $(LLILUM_ROOT)\Zelig\os_layer\inc;$(LLILUM_ROOT)\Zelig\os_layer\inc\api;$(LLILUM_ROOT)\Zelig\os_layer\inc\api\io;$(LLILUM_ROOT)\Zelig\os_layer\inc\debug;$(LLILUM_ROOT)\Zelig\os_layer\inc\hal Level3 MaxSpeed true true true WIN32;NDEBUG;%(PreprocessorDefinitions) $(LLILUM_ROOT)\Zelig\os_layer\inc;$(LLILUM_ROOT)\Zelig\os_layer\inc\api;$(LLILUM_ROOT)\Zelig\os_layer\inc\api\io;$(LLILUM_ROOT)\Zelig\os_layer\inc\debug;$(LLILUM_ROOT)\Zelig\os_layer\inc\hal ================================================ FILE: Zelig/os_layer/ports/win32/Win32Abstraction/Win32Abstraction.vcxproj.filters ================================================  {4FC737F1-C7A5-4376-A066-2A32D752A2FF} cpp;c;cc;cxx;def;odl;idl;hpj;bat;asm;asmx {93995380-89BD-4b04-88EB-625FBE52EBFB} h;hh;hpp;hxx;hm;inl;inc;xsd {67DA6AB6-F800-4c08-8B7A-83BB121AAD01} rc;ico;cur;bmp;dlg;rc2;rct;bin;rgs;gif;jpg;jpeg;jpe;resx;tiff;tif;png;wav;mfcribbon-ms Source Files Source Files Source Files Source Files Source Files Source Files Source Files Source Files Source Files Header Files ================================================ FILE: Zelig/startVS.cmd ================================================ start /i "%VS140COMNTOOLS%..\IDE\devenv.exe" Zelig\Zelig.sln ================================================ FILE: Zelig/tools/readme.txt ================================================ Binaries for make: http://gnuwin32.sourceforge.net/packages/make.htm Binaries for pyOCD: https://launchpad.net/gcc-arm-embedded-misc/pyocd-binary/ ================================================ FILE: docs/CoAP/readme.txt ================================================ rfc7252 : The Constrained Application Protocol (CoAP) rfc6690 : Constrained RESTful Environments (CoRE) Link Format draft-ietf-core-block-19: Block-wise transfers in CoAP ================================================ FILE: llilum.vssettings ================================================ 4truetruetruetrue2truetruetruefalsefalsetruetruefalsetruetruetrue58falsefalse4truetruetruetrue101011110111011011100111100110011111112110110001111001111111011011100101 ================================================ FILE: setenv.cmd ================================================ @echo off set LLILUM_ROOT=%~dp0% prompt $_$+---$G $P$_$+ $G$_Cmd$G :: :: Set LLVM environment variables. :: set LLVM_BIN=%LLVM_SRCROOT_DIR%\build\x64\Release\bin\ set LLVM_INCLUDE=%LLVM_SRCROOT_DIR%\include\ set LLVM_LIBS=%LLVM_SRCROOT_DIR%\ :: :: Add pyOCD and and make to path. :: set PATH=%LLILUM_ROOT%Zelig\tools;%LLILUM_ROOT%Zelig\tools\openocd\bin-x64;%PATH% set LLILUM_OPENOCD_SCRIPTS=%LLILUM_ROOT%Zelig\tools\openocd\scripts\ cd Zelig echo Welcome to LLILUM! ================================================ FILE: setenv32.cmd ================================================ @echo off set LLILUM_ROOT=%~dp0% prompt $_$+---$G $P$_$+ $G$_Cmd$G :: :: Set LLVM environment variables. :: set LLVM_BIN=%LLVM_SRCROOT_DIR%\build\Win32\Release\bin\ set LLVM_INCLUDE=%LLVM_SRCROOT_DIR%\include\ set LLVM_LIBS=%LLVM_SRCROOT_DIR%\ :: :: Add pyOCD and and make to path. :: set PATH=%LLILUM_ROOT%Zelig\tools;%LLILUM_ROOT%Zelig\tools\openocd\bin-x64;%PATH% set LLILUM_OPENOCD_SCRIPTS=%LLILUM_ROOT%Zelig\tools\openocd\scripts\ cd Zelig echo Welcome to LLILUM!